{"text": "Inductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\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\n(* Compute (next_weekday friday). *)\n(* ==> monday : day *)\n(* Compute (next_weekday (next_weekday saturday)). *)\n(* ==> tuesday : day *)\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\n\nExample test_next_two_weekday: \n  (next_weekday (next_weekday monday)) =  wednesday .\nProof. simpl. reflexivity. Qed.\n\nFrom Coq Require Export String.\n\n\n(* Booleans *)\n\nInductive bool : Type := \n  | true\n  | false. \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\nExample test_orb1: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb2: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_orb4: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\n\n(* Infix syntax for boolean operators *)\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5:  false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n\n(* If then else syntax *)\nDefinition negb' (b:bool) : bool :=\n  if b then false\n  else true.\nDefinition andb' (b1:bool) (b2:bool) : bool :=\n  if b1 then b2\n  else false.\nDefinition orb' (b1:bool) (b2:bool) : bool :=\n  if b1 then true\n  else b2.\n\nExample test_andb1: (andb true true) = true. \nProof. simpl. reflexivity. Qed.  \nExample test_andb2: (andb true false) = false. \nProof. simpl. reflexivity. Qed.  \nExample test_andb3: (andb false true) = false. \nProof. simpl. reflexivity. Qed.  \nExample test_andb4: (andb false false) = false. \nProof. simpl. reflexivity. Qed.  \n\n\n(*  exercise 1 star *)\nDefinition nandb (b1 : bool) (b2 : bool) : bool := \n  (negb (andb b1 b2)). \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\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  (andb b1 (andb b2 b3)).\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\n\n(* \nAn Inductive definition does two things:\nIt defines a set of new constructors. E.g., red, primary, true, false, monday, etc. are constructors.\nIt groups them into a new named type, like bool, rgb, or color.\n \nConstructor expressions are formed by applying a constructor \nto zero or more other constructors or constructor expressions\nmatching the structure of the definition\n\n\nred, green, and blue belong to the set rgb;\nblack and white belong to the set color;\nif p is a constructor expression belonging to the set rgb, \nthen primary p (pronounced \"the constructor primary applied to the argument p\")\nis a constructor expression belonging to the set color; and\nconstructor expressions formed in these ways are the only ones belonging\nto the sets rgb and color.\n*)\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\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(* \nModules\n\nCoq provides a module system to aid in organizing large developments.\nWe won't need most of its features, but one is useful: \nIf we enclose a collection of declarations between Module X and End X markers, \nthen, in the remainder of the file after the End, these definitions are referred\nto by names like X.foo instead of just foo. \nWe will use this feature to limit the scope of definitions, \nso that we are free to reuse names.\n*)\n\nModule Playground.\nDefinition b : rgb := blue.\nEnd Playground.\n\n\n\nDefinition b : bool := true.\n\n\nModule TuplePlayground.\n\nInductive bit : Type :=\n  | B0\n  | B1.\nInductive nybble : Type :=\n  | bits (b0 b1 b2 b3 : bit).\n\n(*\nthe bits constructor is a wrapper for its contents\nunwrapping can be done by pattern-matching\nUse underscore ( _ ) as a wildcard  pattern to avoid inventing variable \nnames that aren't used. \n*)\nDefinition all_zero (nb : nybble) : bool :=\n  match nb with\n  | (bits B0 B0 B0 B0) => true\n  | (bits _ _ _ _) => false\n  end.\nExample all_zero_test1: (all_zero (bits B1 B0 B1 B0)) = false.\nProof. simpl. reflexivity. Qed.\nExample all_zero_test2: (all_zero (bits B0 B0 B0 B0)) = true.\nProof. simpl. reflexivity. Qed.\nEnd TuplePlayground.\n\n(* Use module so it doesn't conflict with later usages of Nats from stdlib *)\nModule NatPlayground.\n\n\n(* \nthere is a representation of numbers that is even simpler than binary, namely unary (base 1)\n *)\n\n Inductive nat : Type :=\n  | O            (* capital letter O stands for zero *)\n  | S (n : nat). (* S stands for successor *)\n\n\n(* This is just a representation of numbers: a way of writing them down\nThe names S and O are arbitrary, and at this point they have no special meaning\n-- they are just two different marks that we can use to write down numbers (together with a rule that says any nat will be written as some string of S marks followed by an O).\nIf we like, we can write essentially the same definition this way: *)\nInductive nat' : Type :=\n  | stop\n  | tick (foo : nat').\n\n(*\nThe interpretation of these marks comes from how we use them to compute.\n*)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\n\n(* Since natural numbers are such a pervasive form of data, \nCoq has built-in parser and printer for them, \nprinting numbers in decimal by default.  *)\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n  | O => O\n  | S O => O\n  | S (S n') => n'\n  end.\nExample minus_two_test: (minustwo (S (S (S (S O))))) = (S (S O)).\nProof. simpl. reflexivity. Qed.\n\n\n(* \nHowever, there is a fundamental difference between S and the other two: \nfunctions like pred and minustwo are defined by giving computation rules \n-- e.g., the definition of pred says that pred 2 can be simplified to 1 --\nwhile the definition of S has no such behavior attached. \nAlthough it is like a function in the sense that it can be applied to \nan argument, it does not do anything at all! It is just a way\nof writing down numbers. *)\n\n(* \nFor most interesting computations involving numbers, \nsimple pattern matching is not enough: we also need recursion.  \nSuch functions are introduced using the keyword Fixpoint instead of Definition. \n*)\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(* We can define odd in a similar way, but basing it off even is simpler *)\nDefinition odd (n:nat) : bool :=\n  negb (even n).\n\nExample test_odd1:    odd (S O) = true.\nProof. simpl. reflexivity. Qed.\nExample test_odd2:    odd (S (S (S (S O)))) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Multi-argument functions by recursion *)\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m) (* Predicate (S n' => n') *)\n  end.\n\nExample test_add1: (plus (S (S (S O))) (S (S O))) = (S (S (S (S (S O))))).\nProof. simpl. reflexivity. Qed.\n\n(* ===> 5 : nat *)\n(*      plus 3 2\n   i.e. plus (S (S (S O))) (S (S O))\n    ==> S (plus (S (S O)) (S (S O)))\n          by the second clause of the match\n    ==> S (S (plus (S O) (S (S O))))\n          by the second clause of the match\n    ==> S (S (S (plus O (S (S O)))))\n          by the second clause of the match\n    ==> S (S (S (S (S O))))\n          by the first clause of the match\n   i.e. 5  *)\n\n(* \nAs a notational convenience, if two or more arguments have the same type, \nthey can be written together. In the following definition, (n m : nat)\nmeans just the same as if we had written (n : nat) (m : nat).\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 (S (S O)) (S (S O))) = (S (S (S (S O)))).\nProof. simpl. reflexivity. Qed.\n\n(* Match two expressions at once with a comma between them *)\nFixpoint minus (n m : nat) : nat :=\n  match n, m with \n    | O, _ => O \n    | S _, O => O\n    | S n', S m' => minus n' m'\n  end.\n  \nExample test_minus1: (minus O O) = O.\nProof. simpl. reflexivity. Qed.\nExample test_minus2: (minus (S O) O) = O.\nProof. simpl. reflexivity. Qed.\nExample test_minus3: (minus (S O) (S O)) = O.\nProof. simpl. reflexivity. Qed.\n\nFixpoint exp (base power : nat) : nat :=\n  match base, power with \n    | _, O => S O \n    | O, _ => O \n    | base, S power' => mult base (exp base power') \n  end. \n\nExample test_exp0: exp O (S O) = O.\nProof. simpl. reflexivity. Qed.\nExample test_exp1: exp O O = S O.\nProof. simpl. reflexivity. Qed.\nExample test_exp2: exp (S O) O = S O.\nProof. simpl. reflexivity. Qed.\nExample test_exp3: exp (S (S O)) (S (S (S O))) = (S (S (S (S (S (S (S (S O)))))))).\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_factorial0: factorial O = S O. \nProof. simpl. reflexivity. Qed.\nExample test_factorial1: factorial( S O) = S O. \nProof. simpl. reflexivity. Qed.\nExample test_factorial2: factorial (S (S O)) = S (S O). \nProof. simpl. reflexivity. Qed.\nExample test_factorial3: factorial (S (S (S O))) = S (S (S (S (S (S O))))). \nProof. simpl. reflexivity. Qed.\n\n\nEnd NatPlayground.\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(* Note the use of nested matches (we could also have used a simultaneous match, as we did in minus.) *)\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\nend.\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\nend. \n\nExample test_leb1: leb 0 2 = true. \nProof. simpl. reflexivity. Qed.\nExample test_leb2: leb 2 2 = true. \nProof. simpl. reflexivity. Qed.\nExample test_leb3: leb 5 4 = false. \nProof. simpl. reflexivity. Qed.\n\nFixpoint geb (n m : nat) : bool := \n  match n with \n    | O => if (eqb m O) then true else false \n    | S n' => \n      match m with \n        | O => true \n        | S m' => geb n' m'\n      end\nend. \n\nExample test_geb1: geb 2 0 = true. Proof. simpl. reflexivity. Qed.\nExample test_geb2: geb 2 2 = true. Proof. simpl. reflexivity. Qed.\nExample test_geb3: geb 4 5 = false. Proof. simpl. reflexivity. Qed.\n  \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 >=? y\" := (geb x y) (at level 70) : nat_scope.\nExample test_leb3': (4 <=? 2) = false. Proof. simpl. reflexivity. Qed.\nExample test_geb3': (4 >=? 5) = false. Proof. simpl. reflexivity. Qed.\n\n\nDefinition ltb (n m : nat) : bool := \n  andb (leb n m) (negb (eqb n m)).\n\n\nExample test_ltb1: ltb 0 2 = true. \nProof. simpl. reflexivity. Qed.\nExample test_ltb2: ltb 2 2 = false. \nProof. simpl. reflexivity. Qed.\nExample test_ltb3: ltb 5 4 = false. \nProof. simpl. reflexivity. Qed.\n\n\n(* Proof by Simplification *)\n(* simpl is used when we want to understand the new goal it creates and not blindly expand definitions *)\n(*  Informally, to prove theorems of this form, we generally start by saying\n\"Suppose n is some number...\" Formally, this is achieved in the proof by intros n,\n which moves n from the quantifier in the goal to a context of current assumptions. *)\nTheorem plus_O_n' : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\n  (* The keywords intros, simpl, and reflexivity are examples of tactics. \n  A tactic is a command that is used between Proof and Qed to guide the process \n  of checking some claim we are making.  *)\n(* _l suffix is pronounced \"on the left\" *)\nTheorem plus_1_l : forall n:nat, 1 + n = S n.\nProof.\n  intros n. reflexivity. Qed.\nTheorem mult_0_l : forall n:nat, 0 * n = 0.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\nProof.\n  (* move both quantifiers into the context: *)\n  intros n m.\n  (* move the hypothesis into the context: *)\n  intros shamalamadingdong.\n  (* rewrite the goal using the hypothesis: *)\n\n  (* the arrow left to right and right to left has nothing to do with implication \n  it just tells coq which direction to apply the rewrite. defaulting to -> *)\n  (* rewrite -> shamalamadingdong. *)\n  rewrite <- shamalamadingdong.\n  reflexivity. Qed.\n\n\n(* \nAdmitted makes Coq skip trying to prove this theorem \nand just accept it as a given. \nUseful for developing longer proofs, \nsince we can state subsidiary lemmas that can be useful \nfor making some larger argument, \nuse Admitted to accept them on faith for the moment,\nand continue working on the main argument until we are sure it makes sense; \nthen we can go back and fill in the proofs we skipped.  *)\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 H. \n  intros H2.\n  rewrite H.\n  rewrite H2. \n  reflexivity. Qed. \n\n  (* Check is also used to examine statements of previously declared lemmas and theorems *)\n\n\n(* We can use the rewrite tactic with a previously proved theorem instead\n of a hypothesis from the context. If the statement of the previously proved theorem \n involves quantified variables, as in the example below, Coq tries to instantiate them \n by matching with the current goal. *)\n\nTheorem mult_n_0_m_0 : forall p q : nat,\n  (p * 0) + (q * 0) = 0.\nProof.\n  intros p q.\n  rewrite <- mult_n_O.\n  rewrite <- mult_n_O.\n  reflexivity. Qed.\n\nTheorem mult_n_1 : forall p : nat,\n  p * 1 = p.\nProof.\n  intros p. \n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_O. \n  rewrite -> plus_O_n'. \n  reflexivity. Qed.   \n\n\n(* Proof by Case Analysis *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E. \n  - reflexivity.\n  - reflexivity. Qed.\n(* \nThe destruct generates two subgoals, which we must then prove, \nseparately, in order to get Coq to accept the theorem.\n\nThe annotation \"as [| n']\" is called an intro pattern. \nIt tells Coq what variable names to introduce in each subgoal. \nIn general, what goes between the square brackets is a list \nof lists of names, separated by |.\neqn:E annotation tells destruct to give the name \nE to this equation. Leaving off the eqn:E annotation \ncauses Coq to elide these assumptions in the subgoals. \nThis slightly streamlines proofs where the assumptions are not \nexplicitly used, but it is better practice to keep them for\nthe sake of documentation, as they can help keep you oriented \nwhen working with the subgoals. \n- are bullets, marking the parts of the proof that correcspond to the generated subgoals\nthe part of the proof script that comes after a bullet is the entire proof for the \ncorresponding subgoal. bullets are optional, but use them for readability, and also\ndisambiguate which subgoal coq is trying to complete before trying to verify the next one\npreventing proofs for different subgoals from getting mixed up. \nthese issues are especially important when fragile proofs lead to long debugging. \n\n*)\n(* involutive - negation is its own inverse *)\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  - reflexivity.\n  - reflexivity. 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 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  andb b c = true -> c = true.\nProof.\n  intros b c. destruct b eqn:Eb. \n  - destruct c eqn:Ec. \n    + intros H.\n      reflexivity.\n    + intros H.\n      rewrite <- H.\n      reflexivity.  \n  - destruct c eqn:Ec. \n    + intros H.\n      reflexivity.\n    + intros H.\n      rewrite <- H.\n      reflexivity.\nQed.\n\n(* many proofs perform case analysis on a\n variable right after introducing it: \n [| n] is intro + destruct *)\nTheorem plus_1_neq_0' : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity. Qed.\n\n(* If there are no constructor arguments that need names,\n  we can just write [] to get the case analysis. *)\nTheorem andb_commutative'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof. \n  intros n. destruct n eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n\n(* Fixpoints and Structural Recursion *)\n(* Recursive calls only on strictly smaller values of n \nimplies tha all calls to plus' will eventually terminate.\nCoq demands that some argument of every Fixpoint defn is \"decreasing\"\nThis requirement guarantees every function defined in Coq\nwill terminate on all inputs. *)\nFixpoint plus' (n : nat) (m : nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (plus' n' m)\n  end.\n\n  (* To get a concrete sense of this, find a way to write a sensible Fixpoint definition (of a simple function on numbers, say) that does terminate on all inputs, but that Coq will reject because of this restriction. (If you choose to turn in this optional exercise as part of a homework assignment, make sure you comment out your solution so that it doesn't cause Coq to reject the whole file!) *)\n(* todo: *)\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 f.\n  intros x.  \n  intros b.\n  rewrite -> x.\n  rewrite -> x.\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 f.\n  intros x.  \n  intros b.\n  rewrite -> x. \n  rewrite -> x.\n  rewrite -> negb_involutive.\n  reflexivity.\nQed.\n\n\n\n\n(* 3 stars *)\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof. \nintros b c. \ndestruct b eqn:Eb. \n- destruct c eqn:Ec. \n  + reflexivity.\n  + simpl.\n  intros H. (* wtf *)\n  rewrite H. \n  reflexivity.\n- destruct c eqn: Ec. \n  + simpl. \n  intros H. \n  rewrite H. \n  reflexivity.\n  + simpl. \n  intros H.\n  reflexivity.\nQed.\n\n(* 3 stars *)\nInductive 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    | B1 m' => B0 (incr m')\n    | B0 m' => B1 m' \n  end. \n\n\n\nFixpoint bin_to_nat (m:bin) : nat := \n  match m with \n    | Z => 0\n    | B1 m' => 1 + (2 * bin_to_nat m') \n    | B0 m' => (2 * bin_to_nat m') \n  end. \n\n\nExample test_bin_incr1 : (incr (B1 Z)) = B0 (B1 Z).\nProof. reflexivity. Qed. \nExample test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\nProof. reflexivity. Qed. \nExample test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\nProof. reflexivity. Qed. \n\nExample test_bin_incr4 : bin_to_nat (B0 (B1 Z)) = 2.\nProof. reflexivity. Qed. \n\nExample test_bin_incr5 :\n        bin_to_nat (incr (B1 Z)) = 1 + bin_to_nat (B1 Z).\nProof. reflexivity. Qed. \n\nExample test_bin_incr6 :\n        bin_to_nat (incr (incr (B1 Z))) = 2 + bin_to_nat (B1 Z).\nProof. reflexivity. Qed. \n", "meta": {"author": "onlychans1", "repo": "dev-notes", "sha": "0bded3f6fd589630cc1826870383334eb2280266", "save_path": "github-repos/coq/onlychans1-dev-notes", "path": "github-repos/coq/onlychans1-dev-notes/dev-notes-0bded3f6fd589630cc1826870383334eb2280266/coq/LF/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7499254120090959}}
{"text": "From Coq Require Import Arith.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import Lia.\n\nOpen Scope nat_scope.\n\n\nFixpoint sum_n n :=\n  match n with\n  | 0 => 0\n  | S p => p + sum_n p\nend.\n\nLemma sum_n_p: forall n, \n  2 * sum_n n + n = n * n.\nProof.\n  intros. induction n.\n  - reflexivity.\n  - simpl. lia.\nQed.\n\nFixpoint sum_odd_n (n: nat): nat :=\n  match n with\n  | 0 => 0\n  | S p => 1 + 2 * p + sum_odd_n p\nend.\n\nLemma odd_sum: forall n: nat, \n  sum_odd_n n = n * n.\nProof.\n  intros. induction n.\n  - reflexivity.\n  - simpl. rewrite IHn. apply f_equal. rewrite Nat.add_0_r.\n    rewrite Nat.mul_succ_r. rewrite <- Nat.add_comm with (n) (n * n).\n    rewrite Nat.add_assoc. reflexivity.\nQed.\n\nFixpoint sum_n3 (n: nat): nat :=\n  match n with\n  | 0 => 0\n  | S p => p * p * p + sum_n3 p\nend.\n\nLemma sum_cube_p : forall n: nat, \n  sum_n3 n = (sum_n n) * (sum_n n).\nProof.\n  intros. induction n.\n  - reflexivity.\n  - simpl. rewrite IHn. Admitted.\n\nFixpoint fibonacci (n: nat): Z :=\n  match n with\n  | O => 1\n  | S O => 1\n  | S (S n as p) => fibonacci p + fibonacci n\nend.\n\nTheorem cassini_identity: forall (n: nat),\n  fibonacci (n + 1) * fibonacci (n - 1) - (fibonacci n) ^ 2 = Zpower_nat (-1) n.\nProof.\n  intros. induction n.\n  - simpl.", "meta": {"author": "d-krylov", "repo": "CSE191", "sha": "52efc44110268f0e7a91335773555705a4880709", "save_path": "github-repos/coq/d-krylov-CSE191", "path": "github-repos/coq/d-krylov-CSE191/CSE191-52efc44110268f0e7a91335773555705a4880709/Mathematical_Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7499130999497177}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Recdef.\nRequire Import List.\nRequire Import Program.Tactics.\nRequire Import Program.Equality.\nRequire Import Sorting.Permutation.\nRequire Import Sorting.Sorted.\nImport ListNotations.\n\nDefinition pairlen (x : list nat * list nat) : nat :=\n  length (fst x) + length (snd x).\n\nFunction merge (x : list nat * list nat) {measure pairlen x} : list nat :=\n  match x with\n  | ([], []) => []\n  | ([], (b :: t)) => b :: t\n  | ((a :: s), []) => a :: s\n  | ((a :: s), (b :: t)) => match (a ?= b) with\n                            | Lt => a :: (merge (s, (b :: t)))\n                            | Eq => a :: (merge (s, (b :: t)))\n                            | Gt => b :: (merge ((a :: s), t))\n                            end\n  end.\nProof.\n  all: intros; cbn; omega.\nDefined.\n\nFunction halve (l : list nat) : list nat * list nat :=\n  match l with\n  | [] => ([], [])\n  | a :: [] => ([a], [])\n  | a :: (b :: t) => let x := halve t in (a :: (fst x), b :: (snd x))\n  end.\n\nLemma halve_sum (l : list nat) :\n  length l = length (fst (halve l)) + length (snd (halve l)).\nProof.\n  functional induction (halve l); simpl; omega.\nQed.\n\nFunction mergesort (l : list nat) {measure length l} : list nat :=\n  match l with\n  | [] => []\n  | a :: [] => [a]\n  | a :: (b :: t) => let x := halve l in merge (mergesort (fst x), mergesort (snd x))\n  end.\nProof.\n  all: intros; cbn; rewrite (halve_sum t); omega.\nDefined.\n\nLemma halve_cons (a b : nat) (l : list nat) : \n  halve (a :: b :: l) = (a :: (fst (halve l)), b :: (snd (halve l))).\nProof.\n  unfold halve. cbn. auto.\nQed.\n\nLemma Permutation_merge (x : list nat * list nat) :\n  Permutation ((fst x) ++ (snd x)) (merge x).\nProof.\n  functional induction (merge x); cbn in *; auto.\n  - rewrite app_nil_end. auto.\n  - apply (perm_skip b) in IHl.\n    assert (Permutation ((a :: s) ++ (b :: t)) (b :: (a :: s) ++ t)).\n    + apply Permutation_sym. apply Permutation_middle.\n    + rewrite app_comm_cons in *. \n      apply Permutation_trans with (l':=(b :: (a :: s) ++ t)); auto.\nQed.\n\nLemma Permutation_halve (l : list nat) :\n  Permutation l (fst (halve l) ++ snd (halve l)).\nProof.\n  functional induction (halve l); simpl; auto.\n  apply perm_skip. apply perm_trans with (l' := (b :: snd (halve t) ++ fst (halve t))).\n  - apply perm_skip. apply perm_trans with (l' := (fst (halve t) ++ snd (halve t))); auto.\n    apply Permutation_app_comm.\n  - rewrite app_comm_cons. apply Permutation_app_comm.\nQed.\n\nLemma Permutation_mergesort (l : list nat) :\n  Permutation l (mergesort l).\nProof.\n  functional induction (mergesort l); auto.\n  remember (halve (a :: b :: t)) as x.\n  remember ((mergesort (fst x), mergesort (snd x))) as sortedx.\n  assert (Permutation (fst (sortedx) ++ snd (sortedx)) (merge sortedx)) by apply Permutation_merge.\n  apply perm_trans with (l' := (fst sortedx ++ snd sortedx)); auto.\n  rewrite Heqsortedx; simpl.\n  assert (Permutation (fst x ++ snd x) (mergesort (fst x) ++ mergesort (snd x))) by (apply Permutation_app; auto).\n  apply perm_trans with (l' := (fst x ++ snd x)); auto.\n  rewrite Heqx.\n  apply Permutation_halve.\nQed.\n\nLemma Sorted_merge (x : list nat * list nat) :\n  Sorted le (fst x) -> Sorted le (snd x) -> Sorted le (merge x).\nProof.\n  intros. functional induction merge x.\n  all: auto; cbn in *.\n  1-2: apply Sorted_inv in H. 3: apply Sorted_inv in H0.\n  all: destruct_conjs; apply Sorted_cons; auto.\n  all: specialize (IHl H H0).\n  1: apply nat_compare_lt in e0. 2: apply nat_compare_eq in e0. 3: apply nat_compare_gt in e0.\n  - rewrite merge_equation in IHl. destruct s.\n    + cbn. apply HdRel_cons; omega.\n    + rewrite merge_equation. remember (n ?= b) as cmp.\n      destruct cmp; symmetry in Heqcmp; apply HdRel_cons;\n      apply HdRel_inv in H1; omega.\n  - rewrite merge_equation in IHl. destruct s.\n    + cbn. apply HdRel_cons. omega.\n    + rewrite merge_equation. remember (n ?= b) as cmp.\n      destruct cmp; symmetry in Heqcmp; apply HdRel_cons;\n      apply HdRel_inv in H1; omega.\n  - rewrite merge_equation in IHl. destruct t.\n    + cbn. apply HdRel_cons. omega.\n    + rewrite merge_equation. remember (a ?= n) as cmp.\n      destruct cmp; apply HdRel_cons;\n      apply HdRel_inv in H1; omega.\nQed.\n\nLemma Sorted_mergesort (l : list nat) :\n  Sorted le (mergesort l).\nProof.\n  functional induction mergesort l; auto.\n  apply Sorted_merge; auto.\nQed.\n\nTheorem mergesort_correct (l : list nat) :\n  Permutation l (mergesort l) /\\ Sorted le (mergesort l).\nProof.\n  split.\n  - apply Permutation_mergesort.\n  - apply Sorted_mergesort.\nQed.", "meta": {"author": "gtanzer", "repo": "sort", "sha": "cb8801ca14ccceba27c2683f095bd5b3bb2a3be8", "save_path": "github-repos/coq/gtanzer-sort", "path": "github-repos/coq/gtanzer-sort/sort-cb8801ca14ccceba27c2683f095bd5b3bb2a3be8/sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7498999367333027}}
{"text": "Require Import XR_Rsqr.\nRequire Import XR_Rabs.\nRequire Import XR_Rsqr_le_abs_1.\nRequire Import XR_Rle_antisym.\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_eq_asb_1 : forall x y:R, Rabs x = Rabs y -> Rsqr x = Rsqr y.\nProof.\n  intros x y h.\n  apply Rle_antisym.\n  {\n    apply Rsqr_le_abs_1.\n    right.\n    exact h.\n  }\n  {\n    apply Rsqr_le_abs_1.\n    right.\n    symmetry.\n    exact h.\n  }\nQed.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rsqr_eq_abs_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7498999331297365}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export Tactics.\nRequire Export Induction.\nRequire Export List.\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 ([forall\n    x, P]).  In this chapter, we will see how Coq can be used to carry\n    out other familiar forms of logical reasoning.\n\n    Before diving into details, let's talk a bit about the status of\n    mathematical statements in Coq.  Recall that Coq is a _typed_\n    language, which means that every sensible expression in its world\n    has an associated type.  Logical claims are no exception: any\n    statement we might try to prove in Coq has a type, namely [Prop],\n    the type of _propositions_.  We can see this with the [Check]\n    command: *)\n\nCheck 3 = 3.\n(* ===> Prop *)\n\nCheck forall n m : nat, n + m = m + n.\n(* ===> Prop *)\n\n(** Note that all well-formed propositions have type [Prop] in Coq,\n    regardless of whether they are true or not. Simply _being_ a\n    proposition is one thing; being _provable_ is something else! *)\n\nCheck forall n : nat, n = 2.\n(* ===> Prop *)\n\nCheck 3 = 4.\n(* ===> Prop *)\n\n(** Indeed, propositions don't just have types: they are _first-class\n    objects_ that can be manipulated in the same ways as the other\n    entities in Coq's world.  So far, we've seen one primary place\n    that propositions can appear: in [Theorem] (and [Lemma] and\n    [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But propositions can be used in many other ways.  For example, we\n    can give a name to a proposition using a [Definition], just as we\n    have 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 can also write _parameterized_ propositions -- that is,\n    functions that take arguments of some type and return a\n    proposition. For instance, the following function takes a number\n    and returns a proposition asserting that this number is equal to\n    three: *)\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n(* ===> nat -> Prop *)\n\n(** In Coq, functions that return propositions are said to define\n    _properties_ of their arguments.  For instance, here's a\n    polymorphic property defining the familiar notion of an _injective\n    function_. *)\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\n\n(** The equality operator [=] that we have been using so far is also\n    just a function that returns a [Prop]. The expression [n = m] is\n    just syntactic sugar for [eq n m], defined using Coq's [Notation]\n    mechanism. Because [=] can be used with elements of any type, it\n    is also polymorphic: *)\n\nCheck @eq.\n(* ===> forall A : Type, A -> A -> Prop *)\n\n(** (Notice that we wrote [@eq] instead of [eq]: The type argument [A]\n    to [eq] is declared as implicit, so we need to turn off implicit\n    arguments to see the full type of [eq].) *)\n\n(* ################################################################# *)\n(** * Logical Connectives *)\n\n(* ================================================================= *)\n(** ** Conjunction *)\n\n(** The _conjunction_ or _logical and_ of propositions [A] and [B] is\n    written [A /\\ B], denoting the claim that both [A] and [B] are\n    true. *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\n\n(** To prove a conjunction, use the [split] tactic.  Its effect is to\n    generate two subgoals, one for each part of the statement: *)\n\nProof.\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** More generally, the following principle works for any two\n    propositions [A] and [B]: *)\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\n(** A logical statement with multiple arrows is just a theorem that\n    has several hypotheses.  Here, [and_intro] says that, for any\n    propositions [A] and [B], if we assume that [A] is true and we\n    assume that [B] is true, then [A /\\ B] is also true.\n\n    Since applying a theorem with hypotheses to some goal has the\n    effect of generating as many subgoals as there are hypotheses for\n    that theorem, we can, apply [and_intro] to achieve the same effect\n    as [split]. *)\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m HA. split.\n  - induction n as [| n']. reflexivity. inversion HA.\n  - induction m as [| m']. reflexivity. rewrite plus_comm in HA. inversion HA.\n    Qed.\n(** [] *)\n\n(** So much for proving conjunctive statements.  To go in the other\n    direction -- i.e., to _use_ a conjunctive hypothesis to prove\n    something else -- we employ the [destruct] tactic.\n\n    If the proof context contains a hypothesis [H] of the form [A /\\\n    B], writing [destruct H as [HA HB]] will remove [H] from the\n    context and add two new hypotheses: [HA], stating that [A] is\n    true, and [HB], stating that [B] is true.  For instance: *)\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** As usual, we can also destruct [H] when we introduce it instead of\n    introducing and then destructing it: *)\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** You may wonder why we bothered packing the two hypotheses [n = 0]\n    and [m = 0] into a single conjunction, since we could have also\n    stated the theorem with two separate premises: *)\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** In this case, there is not much difference between the two\n    theorems.  But it is often necessary to explicitly decompose\n    conjunctions that arise from intermediate steps in proofs,\n    especially in bigger developments.  Here's a simplified\n    example: *)\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n(** Another common situation with conjunctions is that we know [A /\\\n    B] but in some context we need just [A] (or just [B]).  The\n    following lemmas are useful in such cases: *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ]. apply HQ. Qed.\n(** [] *)\n\n(** Finally, we sometimes need to rearrange the order of conjunctions\n    and/or the grouping of conjuncts in multi-way conjunctions.  The\n    following commutativity and associativity theorems come in handy\n    in such cases. *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.  Qed.\n  \n(** **** Exercise: 2 stars (and_assoc)  *)\n(** (In the following proof of associativity, notice how the _nested_\n    intro pattern breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP : P], [HQ : Q], and [HR : R].  Finish the proof from\n    there.) *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]]. split.\n  - split. apply HP. apply HQ.\n  - apply HR. Qed.\n\n(** [] *)\n\n(** By the way, the infix notation [/\\] is actually just syntactic\n    sugar for [and A B].  That is, [and] is a Coq operator that takes\n    two propositions as arguments and yields a proposition. *)\n\nCheck and.\n(* ===> and : Prop -> Prop -> Prop *)\n\n(* ================================================================= *)\n(** ** Disjunction *)\n\n(** Another important connective is the _disjunction_, or _logical or_\n    of two propositions: [A \\/ B] is true when either [A] or [B]\n    is.  (Alternatively, we can write [or A B], where [or : Prop ->\n    Prop -> Prop].)\n\n    To use a disjunctive hypothesis in a proof, we proceed by case\n    analysis, which, as for [nat] or other data types, can be done\n    with [destruct] or [intros].  Here is an example: *)\n\nLemma or_example :\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(** We can see in this example that, when we perform case analysis on\n    a disjunction [A \\/ B], we must satisfy two proof obligations,\n    each showing that the conclusion holds under a different\n    assumption -- [A] in the first subgoal and [B] in the second.\n    Note that the case analysis pattern ([Hn | Hm]) allows us to name\n    the hypothesis that is generated in each subgoal.\n\n    Conversely, to show that a disjunction holds, we need to show that\n    one of its sides does. This is done via two tactics, [left] and\n    [right].  As their names imply, the first one requires proving the\n    left side of the disjunction, while the second requires proving\n    its right side.  Here is a trivial use... *)\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\n(** ... and a slightly more interesting example requiring the use of\n    both [left] and [right]: *)\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(** **** Exercise: 1 star (mult_eq_0)  *)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. induction n as [| n].\n  Case \"n = 0\". destruct m.\n    SCase \"m = 0\". left. reflexivity.\n    SCase \"m = S m\". left.  reflexivity.\n  Case \"n = S m\". destruct m.\n    SCase \"m = 0\". right. reflexivity.\n    SCase \"m = S m\". inversion H. Qed.\n  \n(** [] *)\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q [Hp | Hq]. right. apply Hp. left. apply Hq. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Falsehood and Negation *)\n\n(** So far, we have mostly been concerned with proving that certain\n    things are _true_ -- addition is commutative, appending lists is\n    associative, etc.  Of course, we may also be interested in\n    _negative_ results, showing that certain propositions are _not_\n    true. In Coq, such negative statements are expressed with the\n    negation operator [~].\n\n    To see how negation works, recall the discussion of the _principle\n    of explosion_ from the [Tactics] chapter; it asserts that, if we\n    assume a contradiction, then any other proposition can be derived.\n    Following this intuition, we could define [~ P] (\"not [P]\") as\n    [forall Q, P -> Q].  Coq actually makes a slightly different\n    choice, defining [~ P] as [P -> False], where [False] is a\n    _particular_ contradictory proposition defined in the standard\n    library. *)\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\nEnd MyNot.\n\n(** Since [False] is a contradictory proposition, the principle of\n    explosion also applies to it. If we get [False] into the proof\n    context, we can [destruct] it to complete any goal: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from falsehood\n    follows whatever you like\"; this is another common name for the\n    principle of explosion. *)\n\n(** **** Exercise: 2 stars, optional (not_implies_our_not)  *)\n(** Show that Coq's definition of negation implies the intuitive one\n    mentioned above: *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros P H1 p1 H2. destruct H1. apply H2. Qed.\n(** [] *)\n\n(** This is how we use [not] to state that [0] and [1] are different\n    elements of [nat]: *)\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra. inversion contra.\nQed.\n\n(** Such inequality statements are frequent enough to warrant a\n    special notation, [x <> y]: *)\n\nCheck (0 <> 1).\n(* ===> Prop *)\n\nTheorem zero_not_one' : 0 <> 1.\nProof.\n  intros H. inversion H.\nQed.\n\n(** It takes a little practice to get used to working with negation in\n    Coq.  Even though you can see perfectly well why a statement\n    involving negation is true, it can be a little tricky at first to\n    get things into the right configuration so that Coq can understand\n    it!  Here are proofs of a few familiar facts to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced, recommended (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* Skip *)\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive)  *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q Hp Hq. unfold not. intros eq. destruct Hq.  apply Hp.  apply eq.\n  Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P Hp. inversion Hp. destruct H0. apply H. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* Skip *)\n(** [] *)\n\n(** Similarly, since inequality involves a negation, it requires a\n    little practice to be able to work with it fluently.  Here is one\n    useful trick.  If you are trying to prove a goal that is\n    nonsensical (e.g., the goal state is [false = true]), apply\n    [ex_falso_quodlibet] to change the goal to [False].  This makes it\n    easier to use assumptions of the form [~P] that may be available\n    in the context -- in particular, assumptions of the form\n    [x<>y]. *)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\n(** Since reasoning with [ex_falso_quodlibet] is quite common, Coq\n    provides a built-in tactic, [exfalso], for applying it. *)\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = false *)\n    unfold not in H.\n    exfalso.                (* <=== *)\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\n\n(* ================================================================= *)\n(** ** Truth *)\n\n(** Besides [False], Coq's standard library also defines [True], a\n    proposition that is trivially true. To prove it, we use the\n    predefined constant [I : True]: *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n(** Unlike [False], which is used extensively, [True] is used quite\n    rarely, since it is trivial (and therefore uninteresting) to prove\n    as a goal, and it carries no useful information as a hypothesis.\n    But it can be quite useful when defining complex [Prop]s using\n    conditionals or as a parameter to higher-order [Prop]s.  We will\n    see some examples such uses of [True] later on. *)\n\n(* ================================================================= *)\n(** ** Logical Equivalence *)\n\n(** The handy \"if and only if\" connective, which asserts that two\n    propositions have the same truth value, is just the conjunction of\n    two implications. *)\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\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.  Qed.\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'. inversion H'.\nQed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros P.  split.\n  - (* -> *) intros Hp. apply Hp.\n  - (* <- *) intros Hp. apply Hp. Qed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R [Hp Hq Hr]. split.\n  - (* -> *) intros Hpp. apply Hr. apply Hp. apply Hpp.\n  - (* <- *) intros Hpp. apply Hq. apply Hr. apply Hpp. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. split.\n  - (* -> *) intros H. split. inversion H. left. apply H0.\n             inversion H0. right. apply H1. inversion H. left. apply H0.\n             inversion H0. right. apply H2.\n  - (* <- *) intros H. destruct H. destruct H. left. apply H. destruct H0.\n             left. apply H0. right. split. apply H. apply H0. Qed. \n\n              \n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, avoiding\n    the need for some low-level proof-state manipulation.  In\n    particular, [rewrite] and [reflexivity] can be used with [iff]\n    statements, not just equalities.  To enable this behavior, we need\n    to import a special Coq library that allows rewriting with other\n    formulas besides equality: *)\n\nRequire Import Coq.Setoids.Setoid.\n\n(** Here is a simple example demonstrating how these tactics work with\n    [iff].  First, let's prove a couple of basic iff equivalences: *)\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. 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\n(** We can now use these facts with [rewrite] and [reflexivity] to\n    give smooth proofs of statements involving equivalences.  Here is\n    a ternary version of the previous [mult_0] result: *)\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\n(** The [apply] tactic can also be used with [<->]. When given an\n    equivalence as its argument, [apply] tries to guess which side of\n    the equivalence to use. *)\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\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    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].  Here is an example: *)\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\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  intros n [m Hm].\n  exists (2 + m).\n  apply Hm.  Qed.\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  intros X P H. unfold not. intros eq. inversion eq. apply H0. apply H.\n  Qed.\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  intros X P Q. split.\n  - intros Hp. inversion Hp. inversion H. left. exists (x).\n  apply H0. right. exists (x). apply H0.\n  - intros Hp. inversion Hp. inversion H. exists (x). left. apply H0.\n    inversion H. exists (x). right. apply H0.\n    Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Programming with Propositions *)\n\n(** The logical connectives that we have seen provide a rich\n    vocabulary for defining complex propositions from simpler ones.\n    To illustrate, let's look at how to express the claim that an\n    element [x] occurs in a list [l].  Notice that this property has a\n    simple recursive structure:\n\n    - If [l] is the empty list, then [x] cannot occur on it, so the\n      property \"[x] appears in [l]\" is simply false.\n\n    - Otherwise, [l] has the form [x' :: l'].  In this case, [x]\n      occurs in [l] if either it is equal to [x'] or it occurs in\n      [l']. *)\n\n(** We can translate this directly into a straightforward Coq\n    function, [In].  (It can also be found in the Coq standard\n    library.) *)\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | nil => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\n\n(** When [In] is applied to a concrete list, it expands into a\n    concrete sequence of nested conjunctions. *)\n\nExample In_example_1 : In 4 [3; 4; 5].\nProof.\n  simpl. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\n(** (Notice the use of the empty pattern to discharge the last case\n    _en passant_.) *)\n\n(** We can also prove more generic, higher-level lemmas about [In].\n    Note, in the next, how [In] starts out applied to a variable and\n    only gets expanded when we do case analysis on this variable: *)\n\nLemma 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.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(** This way of defining propositions, though convenient in some\n    cases, also has some drawbacks.  In particular, it is subject to\n    Coq's usual restrictions regarding the definition of recursive\n    functions, e.g., the requirement that they be \"obviously\n    terminating.\"  In the next chapter, we will see how to define\n    propositions _inductively_, a different technique with its own set\n    of strengths and limitations. *)\n\n(** **** Exercise: 2 stars (In_map_iff)  *)\nLemma 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  induction l; firstorder (subst;auto). Qed.\n    \n(** [] *)\n\n(** **** Exercise: 2 stars (in_app_iff)  *)\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a. induction l as [| x].\n  Case \"l = []\". simpl. split. intros H. right. apply H.\n    intros [[] | H]. apply H.\n    Case \"l = cons\". simpl. split.\n    (* -> *) intros [[] | H]. left. left. reflexivity.\n    apply or_assoc. right. apply IHl. apply H.\n    (* <- *) intros [[] | H]. intros H1. left. apply H1. intros H. right.\n      apply IHl. left. apply H. right. apply IHl. right. apply H.\n      Qed.\n  \n(** [] *)\n\n(** **** Exercise: 3 stars (All)  *)\n(** Recall that functions returning propositions can be seen as\n    _properties_ of their arguments. For instance, if [P] has type\n    [nat -> Prop], then [P n] states that property [P] holds of [n].\n\n    Drawing inspiration from [In], write a recursive function [All]\n    stating that some property [P] holds of all elements of a list\n    [l]. To make sure your definition is correct, prove the [All_In]\n    lemma below.  (Of course, your definition should _not_ just\n    restate the left-hand side of [All_In].) *)\n\nFixpoint All {T} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n    | nil => True\n    | h :: t => P h /\\ All P t\n    end.\n      \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 T P l. induction l as [| l'].\n  Case \"l = []\". simpl. split.\n  (* -> *) intros H. reflexivity.\n  (* <- *) intros t T1 f.  destruct f.\n  Case \"l = cons\". simpl. split.\n  (* -> *) intros H. inversion IHl. split. apply H. left. reflexivity. apply H0.\n    intros x H2. apply H. right. apply H2.\n  (* <- *) intros H x H1. inversion H1. rewrite <- H0. inversion H. apply H2.\n    apply IHl. inversion H. apply H3. apply H0. Qed.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function below.\n    It takes as arguments two properties of numbers, [Podd] and\n    [Peven], and it should return a property [P] such that [P n] is\n    equivalent to [Podd n] when [n] is odd and equivalent to [Peven n]\n    otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun x => if (oddb x) then Podd x else Peven x.\n\n                             \n\n(** To test your definition, prove the following 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 Po Pe n Ho He. unfold combine_odd_even. induction n as [| n'].\n  Case \"n = 0\". simpl. apply He. reflexivity.\n  Case \"n = S n'\". destruct oddb.\n    SCase \"true\". apply Ho. reflexivity.\n    SCase \"false\". apply He. 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 Po Pe n H Ho. unfold combine_odd_even in H. rewrite Ho 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 Po Pe n H Ho. unfold combine_odd_even in H. rewrite Ho in H. apply H.\n  Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Applying Theorems to Arguments *)\n\n(** One feature of Coq that distinguishes it from many other proof\n    assistants is that it treats _proofs_ as first-class objects.\n\n    There is a great deal to be said about this, but it is not\n    necessary to understand it in detail in order to use Coq.  This\n    section gives just a taste, while a deeper exploration can be\n    found in the optional chapters [ProofObjects] and\n    [IndPrinciples]. *)\n\n(** We have seen that we can use the [Check] command to ask Coq to\n    print the type of an expression.  We can also use [Check] to ask\n    what theorem a particular identifier refers to. *)\n\nCheck plus_comm.\n(* ===> forall n m : nat, n + m = m + n *)\n\n(** Coq prints the _statement_ of the [plus_comm] theorem in the same\n    way that it prints the _type_ of any term that we ask it to\n    [Check].  Why?\n\n    The reason is that the identifier [plus_comm] actually refers to a\n    _proof object_ -- a data structure that represents a logical\n    derivation establishing of the truth of the statement [forall n m\n    : nat, n + m = m + n].  The type of this object _is_ the statement\n    of the theorem that it is a proof of.\n\n    Intuitively, this makes sense because the statement of a theorem\n    tells us what we can use that theorem for, just as the type of a\n    computational object tells us what we can do with that object --\n    e.g., if we have a term of type [nat -> nat -> nat], we can give\n    it two [nat]s as arguments and get a [nat] back.  Similarly, if we\n    have an object of type [n = m -> n + n = m + m] and we provide it\n    an \"argument\" of type [n = m], we can derive [n + n = m + m].\n\n    Operationally, this analogy goes even further: by applying a\n    theorem, as if it were a function, to hypotheses with matching\n    types, we can specialize its result without having to resort to\n    intermediate assertions.  For example, suppose we wanted to prove\n    the following result: *)\n\nLemma plus_comm3 :\n  forall n m p, n + (m + p) = (p + m) + n.\n\n(** It appears at first sight that we ought to be able to prove this\n    by rewriting with [plus_comm] twice to make the two sides match.\n    The problem, however, is that the second [rewrite] will undo the\n    effect of the first. *)\n\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* We are back where we started... *)\n\n(** One simple way of fixing this problem, using only tools that we\n    already know, is to use [assert] to derive a specialized version\n    of [plus_comm] that can be used to rewrite exactly where we\n    want. *)\n\n  rewrite plus_comm.\n  assert (H : m + p = p + m).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\n(** A more elegant alternative is to apply [plus_comm] directly to the\n    arguments we want to instantiate it with, in much the same way as\n    we apply a polymorphic function to a type argument. *)\n\nLemma plus_comm3_take2 :\n  forall n m p, n + (m + p) = (p + m) + n.\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite (plus_comm m).\n  reflexivity.\nQed.\n\n(** You can \"use theorems as functions\" in this way with almost all\n    tactics that take a theorem name as an argument.  Note also that\n    theorem application uses the same inference mechanisms as function\n    application; thus, it is possible, for example, to supply\n    wildcards as arguments to be inferred, or to declare some\n    hypotheses to a theorem as implicit by default.  These features\n    are illustrated in the proof below. *)\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(** We will see many more examples of the idioms from this section in\n    later chapters. *)\n\n(* ################################################################# *)\n(** * Coq vs. Set Theory *)\n\n(** Coq's logical core, the _Calculus of Inductive Constructions_,\n    differs in some important ways from other formal systems that are\n    used by mathematicians for writing down precise and rigorous\n    proofs.  For example, in the most popular foundation for\n    mainstream paper-and-pencil mathematics, Zermelo-Fraenkel Set\n    Theory (ZFC), a mathematical object can potentially be a member of\n    many different sets; a term in Coq's logic, on the other hand, is\n    a member of at most one type.  This difference often leads to\n    slightly different ways of capturing informal mathematical\n    concepts, though these are by and large quite natural and easy to\n    work with.  For example, instead of saying that a natural number\n    [n] belongs to the set of even numbers, we would say in Coq that\n    [ev n] holds, where [ev : nat -> Prop] is a property describing\n    even numbers.\n\n    However, there are some cases where translating standard\n    mathematical reasoning into Coq can be either cumbersome or\n    sometimes even impossible, unless we enrich the core logic with\n    additional axioms.  We conclude this chapter with a brief\n    discussion of some of the most significant differences between the\n    two worlds. *)\n\n(** ** Functional Extensionality\n\n    The equality assertions that we have seen so far mostly have\n    concerned elements of inductive types ([nat], [bool], etc.).  But\n    since Coq's equality operator is polymorphic, these are not the\n    only possibilities -- in particular, we can write propositions\n    claiming that two _functions_ are equal to each other: *)\n\nExample function_equality_ex : plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\n(** In common mathematical practice, two functions [f] and [g] are\n    considered equal if they produce the same outputs:\n\n    (forall x, f x = g x) -> f = g\n\n    This is known as the principle of _functional extensionality_.\n\n    Informally speaking, an \"extensional property\" is one that\n    pertains to an object's observable behavior.  Thus, functional\n    extensionality simply means that a function's identity is\n    completely determined by what we can observe from it -- i.e., in\n    Coq terms, the results we obtain after applying it.\n\n    Functional extensionality is not part of Coq's basic axioms: the\n    only way to show that two functions are equal is by\n    simplification (as we did in the proof of [function_equality_ex]).\n    But we can add it to Coq's core logic using the [Axiom]\n    command. *)\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\n(** Using [Axiom] has the same effect as stating a theorem and\n    skipping its proof using [Admitted], but it alerts the reader that\n    this isn't just something we're going to come back and fill in\n    later!\n\n    We can now invoke functional extensionality in proofs: *)\n\nLemma plus_comm_ext : plus = fun n m => m + n.\nProof.\n  apply functional_extensionality. intros n.\n  apply functional_extensionality. intros m.\n  apply plus_comm.\nQed.\n\n(** Naturally, we must be careful when adding new axioms into Coq's\n    logic, as they may render it inconsistent -- that is, it may\n    become possible to prove every proposition, including [False]!\n    Unfortunately, there is no simple way of telling whether an axiom\n    is safe: hard work is generally required to establish the\n    consistency of any particular combination of axioms.  Fortunately,\n    it is known that adding functional extensionality, in particular,\n    _is_ consistent.\n\n    Note that it is possible to check whether a particular proof\n    relies on any additional axioms, using the [Print Assumptions]\n    command. For instance, if we run it on [plus_comm_ext], we see\n    that it uses [functional_extensionality]: *)\n\nPrint Assumptions plus_comm_ext.\n(* ===>\n     Axioms:\n     functional_extensionality :\n         forall (X Y : Type) (f g : X -> Y),\n                (forall x : X, f x = g x) -> f = g *)\n\n(** **** Exercise: 5 stars (tr_rev)  *)\n(** One problem with the definition of the list-reversing function\n    [rev] that we have is that it performs a call to [app] on each\n    step; running [app] takes time asymptotically linear in the size\n    of the list, which means that [rev] has quadratic running time.\n    We can improve this with the following definition: *)\n\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\n(** This version is said to be _tail-recursive_, because the recursive\n    call to the function is the last operation that needs to be\n    performed (i.e., we don't have to execute [++] after the recursive\n    call); a decent compiler will generate very efficient code in this\n    case.  Prove that both definitions are indeed equivalent. *)\n\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n  intros X. apply functional_extensionality. intros x. unfold tr_rev.\n  induction x as [| l].\n  Case \"l = []\". simpl. reflexivity.\n  Case \"l = cons\". simpl. rewrite <- IHx. \n  (* skipping *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Propositions and Booleans *)\n\n(** We've seen that Coq has two different ways of encoding logical\n    facts: with _booleans_ (of type [bool]), and with\n    _propositions_ (of type [Prop]). For instance, to claim that a\n    number [n] is even, we can say either (1) that [evenb n] returns\n    [true] or (2) that there exists some [k] such that [n = double k].\n    Indeed, these two notions of evenness are equivalent, as can\n    easily be shown with a couple of auxiliary lemmas (one of which is\n    left as an exercise).\n\n    We often say that the boolean [evenb n] _reflects_ the proposition\n    [exists k, n = double k].  *)\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 (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  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\n  intros n. induction n as [| n']. simpl. exists 0. reflexivity.\n  inversion IHn' as [k H]. assert (2 * k = double k).\n  - simpl. rewrite -> double_plus. rewrite -> plus_0_r. reflexivity.\n  - destruct (evenb (S n')). exists k. Admitted.\n    \n(** Skipping after working on this for 3 days [] *)\n(** How does one show that there exists a k such that n = 2k or k = n / 2? **)\n(** How do I show a value that's < n using the exist tactic? **)\n(** How do I show that the inductive case S n' = 1? **)\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(** Similarly, to state that two numbers [n] and [m] are equal, we can\n    say either (1) that [beq_nat n m] returns [true] or (2) that [n =\n    m].  These two notions are equivalent. *)\n\nTheorem beq_nat_true_iff : forall n1 n2 : nat,\n  beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply beq_nat_true.\n  - intros H. rewrite H. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\n(** However, while the boolean and propositional formulations of a\n    claim are equivalent from a purely logical perspective, we have\n    also seen that they need not be equivalent _operationally_.\n    Equality provides an extreme example: knowing that [beq_nat n m =\n    true] is generally of little 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, when\n    proving the backwards direction of\n    [even_bool_prop] ([evenb_double], going from the propositional to\n    the boolean claim), we used a simple induction on [k]).  On the\n    other hand, the converse (the [evenb_double_conv] exercise)\n    required a clever generalization, since we can't directly prove\n    [(exists k, n = double k) -> evenb n = true].\n\n    For these examples, the propositional claims were 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 an\n    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, the next chapter\n    shows how to define the property that a regular expression matches\n    a given string using [Prop].  Doing the same with [bool] would\n    amount to writing a regular expression matcher, which would be\n    more complicated, harder to understand, and harder to reason\n    about.\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\n    reflection_. 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\n Proof. 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 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 this\n    case, larger proofs can often be made considerably simpler by the\n    use of reflection.  As an extreme example, the Coq proof of the\n    famous _4-color theorem_ uses reflection to reduce the analysis of\n    hundreds of different cases to a boolean computation.  We won't\n    cover reflection in great detail, but it serves as a good example\n    showing the complementary strengths of booleans and general\n    propositions. *)\n\n(** **** Exercise: 2 stars (logical_connectives)  *)\n(** The following lemmas relate the propositional connectives studied\n    in this chapter to the corresponding boolean operations. *)\n\n(** i replaced \"&&\" with andb, not the first typo i've come across **)\nLemma andb_true_iff : forall b1 b2:bool,\n  andb b1 b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2. split. intros H. split.\n  - apply andb_true_elim1 in H. apply H.\n  - apply andb_true_elim2 in H. apply H.\n  - intros H. inversion H. rewrite H0. rewrite H1. simpl. reflexivity. Qed.\n\nLemma orb_true_iff : forall b1 b2,\n  orb b1 b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2. split.\n  - intros H. inversion H. destruct b1. simpl. left. reflexivity.\n    right. destruct b2. simpl. reflexivity. simpl. reflexivity.\n  - intros H. inversion H. rewrite H0. simpl. reflexivity.\n    rewrite H0. destruct b1. simpl. reflexivity. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (beq_nat_false_iff)  *)\n(** The following theorem is an alternate \"negative\" formulation of\n    [beq_nat_true_iff] that is more convenient in certain\n    situations (we'll see examples in later chapters). *)\n\nLemma beq_nat_false : forall n m : nat,\n  beq_nat n m = false -> n <> m. \nProof.\n  intros n m H. unfold not. intro contra. rewrite contra in H.\n  rewrite <- beq_nat_refl in H.\n  inversion H. Qed.\n\nLemma beq_nat_false2 : forall n m : nat,\n  n <> m -> beq_nat n m = false.\nProof.\n  intros n. induction n.\n  Case \"n = 0\". intros m H. destruct m as [| m']. simpl. exfalso. apply H.\n    reflexivity.\n    SCase \"m = S m'\". simpl. reflexivity.\n  Case \"n = S n\". intros m H. destruct m as [| m']. simpl. reflexivity.\n    SCase \"m = S m'\". simpl. apply IHn. unfold not. intros H1. unfold not in H.\n    apply H. rewrite H1. reflexivity. Qed.\n\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  intros x y. split.\n  - (* -> *) intros H. unfold not. intros H1. rewrite H1 in H.\n             assert (beq_nat y y = true). apply beq_nat_true_iff. reflexivity.\n             rewrite H0 in H. inversion H.\n  - (* <- *) apply beq_nat_false2. Qed.\n(* that was pretty hard for a one star *)\n(** [] *)\n\n(** **** Exercise: 3 stars (beq_list)  *)\n(** Given a boolean operator [beq] for testing equality of elements of\n    some type [A], we can define a function [beq_list beq] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [beq_list] function below.  To make sure that your\n    definition is correct, prove the lemma [beq_list_true_iff]. *)\n\nFixpoint beq_list {A} (beq : A -> A -> bool)\n                  (l1 l2 : list A) : bool :=\n  match l1 with\n    | [] => match l2 with\n              | [] => true\n              | _ => false\n            end\n    | h1 :: t1 => match l2 with\n                    | [] => false\n                    | h2 :: t2 => match beq h1 h2 with\n                                    | false => false\n                                    | true => beq_list beq t1 t2\n                                  end\n                  end\nend.\n\nLemma beq_list_true_iff :\n  forall A (beq : A -> A -> bool),\n    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n  intros A beq H l1 l2. split. \n  - (* -> *) induction l1 as [| l1' l1]. intros eq.\n             Case \"l1 = []\". induction l2 as [| l2' l2].\n               SCase \"l2 = []\". reflexivity.\n               SCase \"l2 = cons\". unfold beq_list in eq. inversion eq.\n             Case \"l1 = cons\". induction l2 as [| l2' l2].\n               SCase \"l2 = []\". intros eq. unfold beq_list in eq. inversion eq.\n               SCase \"l2 = cons\". intros eq. Admitted.\n\n(* This section is a difficulty spike *)\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (All_forallb)  *)\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Tactics]: *)\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(** Prove the theorem below, which relates [forallb] to the [All]\n    property of the above exercise. *)\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 X test l. split. Admitted.\n  (* skipping hte rest of the Logic section. thinking of moving to previous\n  editions because this section was clearly made for a class to go through *)\n\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(* ================================================================= *)\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 that, to\n    prove a statement of the form [P \\/ Q], we use the [left] and\n    [right] tactics, which effectively require knowing which side of\n    the disjunction holds.  However, 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.  On the other hand, if we happen to know that [P] is\n    reflected in some boolean term [b], then knowing whether it holds\n    or not is trivial: we just have to check the value of [b].  This\n    leads to the following theorem: *)\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. inversion contra.\nQed.\n\n(** In particular, the excluded middle is valid for equations [n = m],\n    between natural numbers [n] and [m].\n\n    You may find it 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_.  Because of this, logics like Coq's,\n    which do not assume the excluded middle, are referred to as\n    _constructive logics_.  More conventional logical systems such as\n    ZFC, in which the excluded middle does hold for arbitrary\n    propositions, are referred 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\n    but we cannot determine what their actual values are (at least,\n    using 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\n    all!  Fortunately, like functional extensionality, the excluded\n    middle is known to be compatible with Coq's logic, allowing us to\n    add it safely as an axiom.  However, we will not need to do so in\n    this book: the results that we cover can be developed entirely\n    within constructive logic at negligible extra cost.\n\n    It takes some practice to understand which proof techniques must\n    be avoided in constructive reasoning, but arguments by\n    contradiction, in particular, are infamous for leading to\n    non-constructive proofs.  Here's a typical example: suppose that\n    we want to show that there exists [x] with some property [P],\n    i.e., such that [P x].  We start by assuming that our conclusion\n    is false; that is, [~ exists x, P x]. From this premise, it is not\n    hard to derive [forall x, ~ P x].  If we manage to show that this\n    intermediate fact results in a contradiction, we arrive at an\n    existence proof without ever exhibiting a value of [x] for which\n    [P x] holds!\n\n    The technical flaw here, from a constructive standpoint, is that\n    we claimed to prove [exists x, P x] using a proof of [~ ~ exists\n    x, P x]. However, allowing ourselves to remove double negations\n    from arbitrary statements is equivalent to assuming the excluded\n    middle, as shown in one of the exercises below.  Thus, this line\n    of reasoning cannot be encoded in Coq without assuming additional\n    axioms. *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** The consistency of Coq with the general excluded middle axiom\n    requires complicated reasoning that cannot be carried out within\n    Coq itself.  However, the following theorem implies that it is\n    always safe to assume a decidability axiom (i.e., an instance of\n    excluded middle) for any _particular_ Prop [P].  Why? Because we\n    cannot prove the negation of such an axiom; if we could, we would\n    have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist)  *)\n(** It is a theorem of classical logic that the following two\n    assertions are equivalent:\n\n    ~ (exists x, ~ P x)\n    forall x, P x\n\n    The [dist_not_exists] theorem above proves one side of this\n    equivalence. Interestingly, the other direction cannot be proved\n    in constructive logic. Your job is to show that it is implied by\n    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: 5 stars, advanced, optional (classical_axioms)  *)\n(** For those who like a challenge, here is an exercise taken from the\n    Coq'Art book by Bertot and Casteran (p. 123).  Each of the\n    following four statements, together with [excluded_middle], can be\n    considered as characterizing classical logic.  We can't prove any\n    of them in Coq, but we can consistently add any one of them as an\n    axiom if we wish to work in classical logic.\n\n    Prove that all five propositions (these four plus\n    [excluded_middle]) are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\n\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\n  \nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)\n", "meta": {"author": "doyougnu", "repo": "Software_Foundations_Solutions", "sha": "2012cf3816a4b3ebf502aa71d8dc9a30aa6d085e", "save_path": "github-repos/coq/doyougnu-Software_Foundations_Solutions", "path": "github-repos/coq/doyougnu-Software_Foundations_Solutions/Software_Foundations_Solutions-2012cf3816a4b3ebf502aa71d8dc9a30aa6d085e/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.7497555873771548}}
{"text": "Require Import Nat List.\nImport ListNotations.\n\n(*\n * This is an exercise on proof by reflection.\n * As always, it's about the journey, not the destination.\n * So there will be a discussion question at the bottom of the\n * file---you will be graded on answering that in the class\n * forum, and not your finished proofs. So don't worry\n * too much if you get stuck! But I'll be around to help.\n *\n * IMPORTANT NOTE: Throughout this exercise, you may find it\n * useful to look at the demo file from class on Tuesday:\n * https://dependenttyp.es/classes/fa2022/readings/reflectionnotes.v\n * It is totally fine to do this. The goal isn't to memorize\n * how to write these proofs, but rather to adapt this style\n * of automation to a different proof so you get a feel for\n * what it's like. Hope that helps!\n *)\n\n(* --- Part 1: naive tactic proofs --- *)\n\n(*\n * In this file, we're going to show that some very large\n * lists have the same length. It's a bit silly, but we'll\n * do so using this inductive relation, which is inhabited\n * whenever two lists are the same length:\n *)\nInductive Same_Length {T : Type} : list T -> list T -> Prop :=\n| length_nil : Same_Length [] []\n| length_cons :\n    forall (hd1 hd2 : T) (tl1 tl2 : list T),\n      Same_Length tl1 tl2 ->\n      Same_Length (hd1 :: tl1) (hd2 :: tl2).\n\n(*\n * Informally, note that for lists l1 and l2, we can construct a\n * term of type Same_Length l1 l2 if and only if l1 and l2 have\n * the same length: If l1 or l2 is nil, we construct this by the\n * length_nil constructor. If l1 and l2 are both not nil, and\n * the tails of l1 and l2 are the same length, then we can\n * construct this with the length_cons constructor. In all\n * other cases, we cannot construct an element of this type.\n *\n * The functions below let us construct very large lists easily.\n * The first gives us a list of length n that is all zeros:\n *)\nFixpoint nat_to_zero_list (n : nat) : list nat :=\n  match n with\n  | O => []\n  | S m => O :: nat_to_zero_list m\n  end.\n\n(*\n * The second gives us a list of length n that is all ones:\n *)\nFixpoint nat_to_one_list (n : nat) : list nat :=\n  match n with\n  | O => []\n  | S m => 1 :: nat_to_one_list m\n  end.\n\n(*\n * EXERCISE 1: I've written a proof below that shows that\n * two particular lists of length 50 are equal to each other.\n * Print the proof and look at it. Why is it so big?\n * Discuss with your group. \n *)\nLemma same_length_lists_50:\n  Same_Length (nat_to_zero_list 50) (nat_to_one_list 50).\nProof.\n  repeat constructor.\nQed.\n\nPrint same_length_lists_50.\n\n(*\n * EXERCISE 2: I've written another inefficient proof, this\n * time about lists of length 1000. The \"time\" tactical here\n * reports how long this proof takes. How long does it take?\n * Why do you think it takes so long? (I strongly recommend \n * against printing this proof. Doing so crashed CoqIDE for me.)\n *)\nLemma same_length_lists_1000:\n  Same_Length (nat_to_zero_list 1000) (nat_to_one_list 1000).\nProof.\n  time (repeat constructor).\nQed.\n\n(* --- Part 2: defining a decision procedure --- *)\n\n(*\n * Next, we will write the same proofs by reflection, using\n * a decision procedure that checks whether two lists are\n * the same length.\n *\n * EXERCISE 3: Fill in the decision procedure below.\n * If you are successful, the proofs of both\n * same_length_lists_50_reflective and \n * same_length_lists_1000_reflective below\n * should go through, and they should do so efficiently.\n *)\nFixpoint check_same_length {T : Type} (l1 l2 : list T) : option (Same_Length l1 l2) :=\n  match l1, l2 with\n  | [], [] => None (* replace with your code *)\n  | hd1 :: tl1, hd2 :: tl2 => None (* replace with your code *)\n  | _, _ => None\n  end.\n\n(*\n * I define these for you---note that, as in the demo we\n * saw on Tuesday, these let us apply our decision procedure\n * easily even though our decision procedure is partial\n * (it returns an optional proof that the lists are the same length,\n * and that proof is None when the lists are not the same length).\n *)\nDefinition optionOutType (P : Prop) (o : option P) :=\n  match o with\n  | Some _ => P\n  | _ => True\n  end.\n\nDefinition optionOut (P : Prop) (o : option P) : optionOutType P o :=\n  match o with\n  | Some pf => pf\n  | _ => I\n  end.\n\n(*\n * This proof should go through efficiently if your decision\n * procedure is correct:\n *)\nLemma same_length_lists_50_reflective:\n  Same_Length (nat_to_zero_list 50) (nat_to_one_list 50).\nProof.\n  exact (optionOut (Same_Length (nat_to_zero_list 50) (nat_to_one_list 50)) (check_same_length (nat_to_zero_list 50) (nat_to_one_list 50))).\nQed.\n\n(*\n * This should be small if your decision procedure is correct:\n *)\nPrint same_length_lists_50_reflective.\n\n(*\n * EXERCISE 4: How long does this proof by reflection take?\n * How much faster is it than the naive tactic proof of the\n * same theorem?\n *)\nLemma same_length_lists_1000_reflective:\n  Same_Length (nat_to_zero_list 1000) (nat_to_one_list 1000).\nProof.\n  time (exact (optionOut (Same_Length (nat_to_zero_list 1000) (nat_to_one_list 1000)) (check_same_length (nat_to_zero_list 1000) (nat_to_one_list 1000)))).\nQed.\n\n(*\n * Note how small this is!\n *)\nPrint same_length_lists_1000_reflective.\n\n(*\n * EXERCISE 5: What happens if you try to use the same tactic\n * to prove something unprovable? Why? What theorem could you \n * prove with this tactic instead?\n *)\nLemma same_length_bad : Same_Length (nat_to_zero_list 50) (nat_to_one_list 1000).\nProof.\n  (*exact (optionOut (Same_Length (nat_to_zero_list 50) (nat_to_one_list 1000)) (check_same_length (nat_to_zero_list 50) (nat_to_one_list 1000))).*)\nAbort.\n\n(* --- Part 3: reflective tactics --- *)\n\n(*\n * Now you can wrap all of this inside of a cute tactic, which\n * we'll call prove_same_length. You again may wish to refer to\n * the demo from Tuesday for this.\n *\n * EXERCISE 6: Implement the tactic prove_same_length, which\n * should prove the below proofs efficiently if the tactic\n * is correct.\n *)\nLtac prove_same_length := idtac. (* replace with your code *)\n\n(*\n * These should all go through efficiently now:\n *)\nLemma same_length_lists_50_ltac:\n  Same_Length (nat_to_zero_list 50) (nat_to_one_list 50).\nProof.\n  prove_same_length.\nQed.\n\nLemma same_length_lists_1000_ltac:\n  Same_Length (nat_to_zero_list 1000) (nat_to_one_list 1000).\nProof.\n  prove_same_length.\nQed.\n\nLemma same_length_lists_5000_ltac:\n  Same_Length (nat_to_zero_list 5000) (nat_to_one_list 5000).\nProof.\n  prove_same_length.\nQed.\n\n(* --- Part 4: proving your automation correct --- *)\n\n(*\n * EXERCISE 7: Prove check_same_length_OK below, which shows\n * that your check_same_length decision procedure returns\n * some proof that two lists are the same length if and only if\n * they're actually the same length.\n *\n * It will probably help a lot to look at the proof from the\n * demo in class. Tactics I found helpful (YMMV):\n *   `intros` (introduction)\n *   `split` (split P <-> Q into P -> Q and Q -> P)\n *   `induction` (note that you can induct not just over lists,\n *                but also over all proofs of Same_Length l1 l2\n *                for any two lists l1 and l2, and this may be\n *                easier for this proof)\n *   `econstructor` (apply some constructor, but choose it for me)\n *   `reflexivity`\n *   `eauto` (like auto, but also infer some arguments I don't\n *            feel like figuring out myself)\n *   `destruct` (like induction, but don't bother defining an\n *               inductive hypothesis)\n *   `unfold` (delta-reduce or unfold constants)\n *   `rewrite` (rewrite by equalities, like subst in Agda)\n *   `apply` (apply a hypothesis or lemma to some arguments)\n *\n * It's OK if this proof is hard. If it is, I recommend stepping\n * through the corresponding proof about isEven in the demo from\n * class on Tuesday (linked at the top of this file), and making\n * sure you understand each step.\n *)\n\nDefinition check_same_length_is_some {T : Type} (l1 l2 : list T) :=\n  exists (H : Same_Length l1 l2), check_same_length l1 l2 = Some H.\n\nTheorem check_same_length_OK:\n  forall {T : Type} (l1 l2 : list T),\n    Same_Length l1 l2 <-> check_same_length_is_some l1 l2.\nProof.\n  (* your proof here *)\nAbort. (* <- change to Qed when done *)\n\n(*\n * BONUS EXERCISE: If you have extra time, prove that this is\n * not only correct, but also respects the actual length function.\n * You may prove this however you like.\n *)\nTheorem check_same_length_OK_alt:\n  forall {T : Type} (l1 l2 : list T),\n    length l1 = length l2 <-> check_same_length_is_some l1 l2.\nProof.\n  (* your proof here *)\nAbort. (* <- change to Qed when done *)\n\n(* --- Discussion --- *)\n\n(*\n * Answer in the class forum, exactly one answer per group,\n * listing the names of everyone in your group as always:\n * Think back to the three different ways you've written\n * proofs so far in this class: by constructing proof terms\n * directly (Agda, Artifact 1), by using tactics (Coq, Artifact 2),\n * and by reflection (Coq, Artifact 3). When do you think you'd\n * use each one over the others, if ever? And why (even if never)?\n *)\n", "meta": {"author": "TheTripleV", "repo": "598tlr-artifact-3", "sha": "9d6172b087909e8dd2eaecc47d7a0d15e056a3d8", "save_path": "github-repos/coq/TheTripleV-598tlr-artifact-3", "path": "github-repos/coq/TheTripleV-598tlr-artifact-3/598tlr-artifact-3-9d6172b087909e8dd2eaecc47d7a0d15e056a3d8/reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.8740772318846387, "lm_q1q2_score": 0.7497555612743982}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (x : natural) : natural :=\n  plus y (mult x lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj144_coqofml_TBr5oy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7497224751237314}}
{"text": "Require Import Setoid Morphisms.\nRequire Export Coq.Classes.Equivalence.\nOpen Scope equiv_scope.\n\nGeneralizable All Variables.\n\n(** * Ordered Types\n\n   This file corresponds to OrderedType.v in the standard FSets/FMaps\n   library. It contains a formalization of types equipped with a total\n   and decidable order.\n   Notations on ordered types are defined in scope [compare_scope],\n   delimited by key [compare].\n   *)\nDelimit Scope compare_scope with compare.\n\n(** ** Strict orders : the [StrictOrder] class\n\n   A strict order [lt] with respect to an equivalence relation [eq]\n   on a type [A] is an antireflexive transitive relation, ie. it\n   is a transitive relation that does not contain two congruent terms.\n   We define the class [StrictOrder A lt eq] of such objects.\n   *)\nClass StrictOrder {A} lt eq {equiv : Equivalence eq} := {\n  StrictOrder_Transitive :> Transitive lt;\n  StrictOrder_Irreflexive : forall (x y : A), lt x y -> x =/= y\n}.\nDefinition lt_StrictOrder `{StrictOrder A lt_ eq_} := lt_.\n\n(** If [x] and [y] belong to a strict order, we define the\n   notations [x >>> y] and [y <<< x]. *)\nNotation \" x >>> y \" := (lt_StrictOrder y x)\n  (at level 70, no associativity, only parsing) : compare_scope.\nNotation \" x <<< y \" := (lt_StrictOrder x y)\n  (at level 70, no associativity) : compare_scope.\nOpen Scope compare_scope.\n\n(** A couple of useful basic properties about strict orders. *)\nSet Implicit Arguments. Unset Strict Implicit.\nSection StrictOrderProps.\n  Context `{StrictOrder A}.\n\n  Property lt_antirefl : forall x, ~x <<< x.\n  Proof using .\n    intros; intro Hlt; apply (StrictOrder_Irreflexive x x Hlt); reflexivity.\n  Qed.\n  Property lt_not_eq : forall x y, x <<< y -> x =/= y.\n  Proof using .\n    intros; apply StrictOrder_Irreflexive; auto.\n  Qed.\n  Property gt_not_eq : forall x y, x >>> y -> x =/= y.\n  Proof using .\n    intros; intro abs; symmetry in abs; revert abs; apply lt_not_eq; auto.\n  Qed.\n  Property eq_not_lt : forall x y, x === y -> ~ x <<< y.\n  Proof using .\n    intros; intro abs; apply (lt_not_eq abs); auto.\n  Qed.\n  Property eq_not_gt : forall x y, x === y -> ~ x >>> y.\n  Proof using .\n    intros; intro abs; apply (gt_not_eq abs); auto.\n  Qed.\n  Property lt_not_gt : forall x y, x <<< y -> ~(x >>> y).\n  Proof using .\n    intros; intro abs; refine (lt_not_eq _ _).\n    apply transitivity with y; eauto. reflexivity.\n  Qed.\nEnd StrictOrderProps.\nUnset Implicit Arguments.\n\n(** ** Ordered types : the [OrderedType] class\n\n   [OrderedType] is the class of types that enjoy decidable comparison for\n   a given setoid equality and strict order relation with respect to this\n   equality. An instance of [OrderedType] for a type [A] must bring :\n   - the equality relation [eq]\n   - a proof that [eq] is an equivalence relation\n   - the order relation [lt]\n   - an instance of [StrictOrder] for [lt] and [eq]\n   - a comparison function [cmp : A -> A -> comparison]\n   - a proof that [cmp] really implements [lt] and [eq]\n\n   With respect to the original formalization in the FSets/FMaps library,\n   the fundamental difference is that the comparison function is purely\n   computational, whereas the return type of the [compare] function in\n   [FSets.OrderedType] includes proofs. In that sense, this formalisation\n   is more similar to [FSets.OrderedTypeAlt]. To define the specification\n   that the function [cmp] must meet, unlike [OrderedTypeAlt], we use\n   the following inductive view [compare_spec] :\n   *)\nInductive compare_spec {A} eq lt (x y : A) : comparison -> Prop :=\n| compare_spec_lt : lt x y -> compare_spec eq lt x y Lt\n| compare_spec_eq : eq x y -> compare_spec eq lt x y Eq\n| compare_spec_gt : lt y x -> compare_spec eq lt x y Gt.\n\n(** [compare_spec] describes what is the correct result for a comparison\n   between two elements [x] and [y] ; in particular, a suitable comparison\n   function is a function that is included in this relation.\n\n   Given these definitions, we can now define the [OrderedType] class.\n   *)\nClass OrderedType (A : Type) := {\n  _eq : relation A;\n  _lt : relation A;\n  OT_Equivalence :> Equivalence _eq;\n  OT_StrictOrder :> StrictOrder _lt _eq;\n  _cmp : A -> A -> comparison;\n  _compare_spec : forall x y, compare_spec _eq _lt x y (_cmp x y)\n}.\n\n(** If [x] and [y] belong to an ordered type [A], we can write [compare x y]\n   to denote the comparison of [x] and [y], as well as the special handy\n   notation [x =?= y]. *)\nDefinition compare `{OrderedType A} := _cmp.\nNotation \" x =?= y \" :=\n  (compare (x :>) (y :>)) (no associativity, at level 70) : compare_scope.\n\n(** The following lemma is a convenient way to access the specification of\n   the [compare] function. Its typical use is the following : if a comparison\n   [x =?= y] appears in the Coq context, [destruct (compare_dec x y)] will\n   create 3 branches for each result of the comparison, and add the correct\n   hypothesis in each branch. It is almost as easy to work with as the\n   original dependently-typed [OrderedType.compare] function.\n   *)\nDefinition compare_dec `{H : OrderedType A} :\n  forall x y, compare_spec equiv lt_StrictOrder x y (compare x y) :=\n    @_compare_spec A H.\n\n(** [compare] is made globally opaque so that case analysis can be done\n   easily by destructing [compare_dec _ _]. *)\nGlobal Opaque compare.\n\n(** We define shortcut notations [x == y], [x << y] and [x >> y]\n   for purely computational equality and ordering tests, and\n   their specification as well. *)\nDefinition is_compare `{OrderedType A} (x y : A) c :=\n  match x =?= y, c with\n    | Eq, Eq | Lt, Lt | Gt, Gt => true\n    | _, _ => false\n  end.\nNotation \" x == y \" :=\n  (is_compare x y Eq) (no associativity, at level 70) : compare_scope.\nNotation \" x << y \" :=\n  (is_compare x y Lt) (no associativity, at level 70) : compare_scope.\nNotation \" x >> y \" :=\n  (is_compare x y Gt) (no associativity, at level 70) : compare_scope.\n\nProperty compare_1 `{OrderedType A} : forall x y, x =?= y = Lt -> x <<< y.\nProof using .\n  intros; destruct (compare_dec x y); auto; congruence.\nQed.\nProperty compare_2 `{OrderedType A} : forall x y, x =?= y = Eq -> x === y.\nProof using .\n  intros; destruct (compare_dec x y); auto; congruence.\nQed.\nProperty compare_3 `{OrderedType A} : forall x y, x =?= y = Gt -> x >>> y.\nProof using .\n  intros; destruct (compare_dec x y); auto; congruence.\nQed.\n\n(** Decidability lemmas for equality and orders, specified in a way\n   similar to [compare_spec]. *)\nInductive decides {A} (R : relation A) (x y : A) : bool -> Prop :=\n| decides_true : R x y -> decides R x y true\n| decides_false : ~(R x y) -> decides R x y false.\n\nProperty eq_dec `{OrderedType A} :\n  forall (x y : A), decides equiv x y (x==y).\nProof using .\n  intros; unfold is_compare. destruct (compare_dec x y); constructor.\n  apply lt_not_eq; auto.\n  assumption.\n  apply gt_not_eq; auto.\nQed.\nProperty lt_dec `{OrderedType A} :\n  forall x y, decides lt_StrictOrder x y (x<<y).\nProof using .\n  intros; unfold is_compare. destruct (compare_dec x y); constructor.\n  assumption.\n  intro abs; apply (lt_not_eq abs); auto.\n  apply lt_not_gt; auto.\nQed.\nProperty gt_dec `{OrderedType A} :\n  forall x y, decides lt_StrictOrder y x (x>>y).\nProof using .\n  intros; unfold is_compare. destruct (compare_dec x y); constructor.\n  apply lt_not_gt; auto.\n  intro abs; apply (gt_not_eq abs); auto.\n  assumption.\nQed.\n\n(** More lemmas about ordered types, in particular the fact that\n   the order relations are morphisms for equality. *)\nSet Implicit Arguments. Unset Strict Implicit.\nProperty eq_lt `{OrderedType A} :\n  forall (x x' y : A), x === x' -> x <<< y -> x' <<< y.\nProof using .\n  intros; destruct (compare_dec x' y); auto.\n  contradiction (lt_not_eq H1); transitivity x'; auto.\n  contradiction (lt_not_eq (x:=x) (y:=x')); auto; transitivity y; auto.\nQed.\nCorollary eq_lt2 `{OrderedType A} :\n  forall (x x' y : A), x === x' -> x' <<< y -> x <<< y.\nProof using .\n  intros; apply eq_lt with x'; auto; symmetry; auto.\nQed.\nProperty eq_gt `{OrderedType A} :\n  forall (x x' y : A), x === x' -> x >>> y -> x' >>> y.\nProof using .\n  intros; destruct (compare_dec x' y); auto.\n  contradiction (gt_not_eq (x:=x) (y:=x')); auto; transitivity y; auto.\n  contradiction (gt_not_eq H1); transitivity x'; auto.\nQed.\nInstance lt_m `{OrderedType A} : Proper (_eq ==> _eq ==> iff) _lt.\nProof using .\n  repeat intro; split; intro Hlt.\n  apply (eq_lt (x:=x)); auto. apply (eq_gt (x:=x0)); auto.\n  apply (eq_lt (x:=y)); try symmetry; auto.\n  apply (eq_gt (x:=y0)); try symmetry; auto.\nQed.\nInstance le_m `{OrderedType A} : Proper (_eq ==> _eq ==> iff) (complement _lt).\nProof using .\n  repeat intro; split; intro Hlt; unfold complement in  *.\n  rewrite H1 in Hlt; rewrite H0 in Hlt; assumption.\n  rewrite H0, H1; assumption.\nQed.\n\n(** Shortcut lemmas for the [order] tactic *)\nSection OrderLemmas.\n  Context `{OrderedType A}.\n  Variables x y z : A.\n\n  Corollary lt_eq : x <<< y -> y === z -> x <<< z.\n  Proof using .\n    intros; rewrite <- H1; assumption.\n  Qed.\n  Corollary le_eq : ~x <<< y -> y === z -> ~x <<< z.\n  Proof using .\n    intros; rewrite <- H1; assumption.\n  Qed.\n  Corollary eq_le : x === y -> ~y <<< z -> ~x <<< z.\n  Proof using .\n    intros; rewrite H0; assumption.\n  Qed.\n  Corollary neq_eq : x =/= y -> y === z -> x =/= z.\n  Proof using .\n    intros; rewrite <- H1; assumption.\n  Qed.\n  Corollary eq_neq : x === y -> y =/= z -> x =/= z.\n  Proof using .\n    intros; rewrite H0; assumption.\n  Qed.\n\n  Property le_lt_trans : ~ y <<< x -> y <<< z -> x <<< z.\n  Proof using .\n    intros; destruct (compare_dec x z); auto.\n    rewrite <- H2 in H1; contradiction.\n    contradiction H0; transitivity z; auto.\n  Qed.\n  Property lt_le_trans : x <<< y -> ~ z <<< y -> x <<< z.\n  Proof using .\n    intros; destruct (compare_dec x z); auto.\n    rewrite <- H2 in H1; contradiction.\n    contradiction H1; transitivity x; auto.\n  Qed.\n  Property le_neq : ~x <<< y -> x =/= y -> x >>> y.\n  Proof using .\n    intros; destruct (compare_dec x y); auto; contradiction.\n  Qed.\n\n  Lemma elim_compare_eq : x === y -> x =?= y = Eq.\n  Proof using .\n    intros; destruct (compare_dec x y); auto.\n    contradiction (lt_not_eq H1 H0).\n    contradiction (lt_not_eq H1 (symmetry H0)).\n  Qed.\n  Lemma elim_compare_lt : x <<< y -> x =?= y = Lt.\n  Proof using .\n    intros; destruct (compare_dec x y); auto.\n    contradiction (lt_not_eq H0 H1).\n    contradiction (lt_not_gt H1 H0).\n  Qed.\n  Lemma elim_compare_gt : x >>> y -> x =?= y = Gt.\n  Proof using .\n    intros; destruct (compare_dec x y); auto.\n    contradiction (lt_not_gt H1 H0).\n    contradiction (gt_not_eq H0 H1).\n  Qed.\nEnd OrderLemmas.\nUnset Implicit Arguments.\n\n(** The following is the adaptation of the original [order] tactic\n   developed by P. Letouzey in the original library. It should\n   prove exactly the same goals, with a slight decrease in performance\n   due to the extra implicit instance parameters.\n   *)\nLtac normalize_notations :=\n  match goal with\n | H : ?R ?x ?y |- _ =>\n   progress ((change (x === y) in H) || (change (x <<< y) in H) ||\n     (change (x >>> y) in H)); normalize_notations\n | H : ~(?R ?x ?y) |- _ =>\n   progress ((change (x =/= y) in H) || (change (~ x <<< y) in H) ||\n     (change (~ y <<< x) in H)); normalize_notations\n | |- ?R ?x ?y =>\n   progress (change (x === y) || change (x <<< y) || change (y <<< x))\n | |- ~?R ?x ?y =>\n   progress (change (x =/= y) || change (~x <<< y) || change (~y <<< x))\n | _ => idtac\n  end.\n\nLtac abstraction := match goal with\n | H : False |- _ => elim H\n | H : ?x <<< ?x |- _ => elim (lt_antirefl H)\n | H : ?x =/= ?x |- _ => elim (H (reflexivity x))\n | H : ?x === ?x |- _ => clear H; abstraction\n | H : ~?x <<< ?x |- _ => clear H; abstraction\n | |- ?x === ?x => reflexivity\n | |- ?x <<< ?x => elimtype False; abstraction\n | |- ~ _ => intro; abstraction\n | H1: ~?x <<< ?y, H2: ?x =/= ?y |- _ =>\n     generalize (le_neq H1 H2); clear H1 H2; intro; abstraction\n | H1: ~?x <<< ?y, H2: ?y =/= ?x |- _ =>\n     symmetry in H2; generalize (le_neq H1 H2);\n       clear H1 H2; intro; abstraction\n | H : ?x =/= ?y |- _ => revert H; abstraction\n | H : ~?x <<< ?y |- _ => revert H; abstraction\n | H : ?x <<< ?y |- _ => revert H; abstraction\n | H : ?x === ?y |- _ => revert H; abstraction\n | _ => idtac\nend.\n\nLtac do_eq a b EQ := match goal with\n | |- ?x <<< ?y -> _ => let H := fresh \"H\" in\n     (intro H;\n      (generalize (eq_lt EQ H); clear H; intro H) ||\n      (generalize (lt_eq H EQ); clear H; intro H) ||\n      idtac);\n      do_eq a b EQ\n | |- ~?x <<< ?y -> _ => let H := fresh \"H\" in\n     (intro H;\n      (generalize (eq_le (symmetry EQ) H); clear H; intro H) ||\n      (generalize (le_eq H EQ); clear H; intro H) ||\n      idtac);\n      do_eq a b EQ\n | |- ?x === ?y -> _ => let H := fresh \"H\" in\n     (intro H;\n      (generalize (transitivity (symmetry EQ) H); clear H; intro H) ||\n      (generalize (transitivity H EQ); clear H; intro H) ||\n      idtac);\n      do_eq a b EQ\n | |- ?x =/= ?y -> _ => let H := fresh \"H\" in\n     (intro H;\n      (generalize (eq_neq (symmetry EQ) H); clear H; intro H) ||\n      (generalize (neq_eq H EQ); clear H; intro H) ||\n      idtac);\n      do_eq a b EQ\n | |- a <<< ?y => apply eq_lt with b; [exact (symmetry EQ)|]\n | |- ?y <<< a => apply lt_eq with b; [|exact (symmetry EQ)]\n | |- a === ?y => transitivity b; [exact EQ|]\n | |- ?y === a => transitivity b; [|exact (symmetry EQ)]\n | _ => idtac\n end.\n\nLtac propagate_eq := abstraction; match goal with\n | |- ?a === ?b -> _ =>\n     let EQ := fresh \"EQ\" in (intro EQ; do_eq a b EQ; clear EQ);\n     propagate_eq\n | _ => idtac\nend.\n\n(* Example test `{OrderedType A} : *)\n(*   forall (x x' x'' x''' y a b c d e f g h : A), *)\n(*     x === x -> x === x' -> x' === x'' -> *)\n(*     x =/= y -> b =/= x -> *)\n(*     y >>> x -> c <<< x -> *)\n(*     x'' === x''' -> *)\n(*     ~a >>> x -> ~d <<< x -> *)\n(*     e === x -> x === e -> *)\n(*     f >>> x. *)\n(* Proof. *)\n(*   intros. *)\n(*   propagate_eq. *)\n\nLtac do_lt x y LT := match goal with\n | |- x <<< y -> _ => intros _; do_lt x y LT\n | |- y <<< ?z -> _ => let H := fresh \"H\" in\n     (intro H; generalize (transitivity LT H); intro); do_lt x y LT\n | |- ?z <<< x -> _ => let H := fresh \"H\" in\n     (intro H; generalize (transitivity H LT); intro); do_lt x y LT\n | |- _ <<< _ -> _ => intro; do_lt x y LT\n\n | |- ~y <<< x -> _ => intros _; do_lt x y LT\n | |- ~x <<< ?z -> _ => let H := fresh \"H\" in\n     (intro H; generalize (le_lt_trans H LT); intro); do_lt x y LT\n | |- ~?z <<< y -> _ => let H := fresh \"H\" in\n     (intro H; generalize (lt_le_trans LT H); intro); do_lt x y LT\n | |- ~_ <<< _ -> _ => intro; do_lt x y LT\n | _ => idtac\n end.\n\nDefinition hide_lt `{StrictOrder A lt_ eq_} := lt_StrictOrder.\n\nLtac propagate_lt := abstraction; match goal with\n | |- ?x <<< ?y -> _ =>\n     let LT := fresh \"LT\" in\n       (intro LT; do_lt x y LT; change (hide_lt x y) in LT);\n       propagate_lt\n | _ => unfold hide_lt in *\nend.\n\nLtac order :=\n intros;\n normalize_notations;\n abstraction;\n propagate_eq;\n propagate_lt;\n auto;\n propagate_lt;\n eauto.\n\nLtac false_order := elimtype False; order.\n\nHint Extern 0 (_eq _ _) => reflexivity.\nHint Extern 0 (_ === _) => reflexivity.\nHint Extern 2 (_eq _ _) => symmetry; assumption.\nHint Extern 2 (_ === _) => symmetry; assumption.\nHint Extern 1 (Equivalence _) => constructor; congruence.\nHint Extern 1 (Equivalence _) => apply OT_Equivalence.\nHint Extern 1 (StrictOrder _) => apply OT_StrictOrder.\nHint Extern 1 (RelationClasses.StrictOrder _) =>\n  constructor; repeat intro; order.\nHint Extern 1 (Proper _ _) => apply lt_m.\nHint Extern 1 (Proper _ _) => repeat intro; intuition order.\n\n(** ** Specific Ordered types : [OrderedType] with specific equality\n\n   Sometimes, one wants to consider ordered types where the equality\n   has to be Leibniz equality or any other specific equality. Because there\n   is no 'with' construct for  typeclasses, as there is for modules, we\n   define another class for these types and show that such types\n   also match [OrderedType]. An alternative would be to take the equality\n   relation ouf of the [OrderedType] instance and add it as a parameter.\n*)\nClass SpecificOrderedType\n  (A : Type) (eqA : relation A) := {\n  SOT_Equivalence :> Equivalence eqA ;\n  SOT_lt : relation A;\n  SOT_StrictOrder : StrictOrder SOT_lt eqA;\n  SOT_cmp : A -> A -> comparison;\n  SOT_compare_spec : forall x y, compare_spec eqA SOT_lt x y (SOT_cmp x y)\n}.\nInstance SOT_as_OT `{SpecificOrderedType A} : OrderedType A := {\n  _eq := eqA;\n  OT_StrictOrder := SOT_StrictOrder;\n  _compare_spec := SOT_compare_spec\n}.\nInstance SOT_SO_to_SO `{SpecificOrderedType A eqA} : StrictOrder SOT_lt eqA | 4.\nProof.\n  intros; apply SOT_StrictOrder.\nDefined.\n\n(** ** Usual Ordered types : [OrderedType] with Leibniz equality\n\n   A typical case is to require an instance of [OrderedType] where the equality\n   is the Leibniz equality. We define the notation [UsualOrderedType] for that\n   purpose.\n   *)\nNotation \"'UsualOrderedType' A\" :=\n  (SpecificOrderedType A (@eq A))(at level 30).\n\n(** * Facts about setoid list membership\n\n   The remainer of this file correspond to the final section\n   of the [OrderedTypeFacts] functor and the [KeyOrderedType] functor.\n   They are used especially in [SetList] and [MapList].\n   *)\nSet Implicit Arguments. Unset Strict Implicit.\nRequire Import SetoidList.\nSection ForNotations.\n  Notation In:=(InA _eq).\n  Notation Inf:=(lelistA _lt).\n  Notation Sort:=(sort _lt).\n  Notation NoDup:=(NoDupA _eq).\n\n  Context `{Helt : OrderedType elt}.\n  Implicit Types x y : elt.\n\n  Lemma In_eq : forall l x y, x === y -> In x l -> In y l.\n  Proof using . apply InA_eqA; eauto with typeclass_instances. Qed.\n\n  Lemma ListIn_In : forall l x, List.In x l -> In x l.\n  Proof using . apply In_InA; eauto with typeclass_instances. Qed.\n\n  Lemma Inf_lt : forall l x y, x <<< y -> Inf y l -> Inf x l.\n  Proof using .\n    apply InfA_ltA; constructor; repeat intro; order.\n  Qed.\n\n  Lemma Inf_eq : forall l x y, x === y -> Inf y l -> Inf x l.\n  Proof using .\n    apply InfA_eqA; eauto with typeclass_instances.\n  Qed.\n\n  Lemma Sort_Inf_In : forall l x a, Sort l -> Inf a l -> In x l -> a <<< x.\n  Proof using .\n    apply SortA_InfA_InA; eauto with typeclass_instances.\n  Qed.\n\n  Lemma ListIn_Inf : forall l x, (forall y, List.In y l -> x <<< y) -> Inf x l.\n  Proof using . exact (@In_InfA _ _lt). Qed.\n\n  Lemma In_Inf : forall l x, (forall y, In y l -> x <<< y) -> Inf x l.\n  Proof using .\n    apply InA_InfA; eauto with typeclass_instances.\n  Qed.\n\n  Lemma Inf_alt :\n    forall l x, Sort l -> (Inf x l <-> (forall y, In y l -> x <<< y)).\n  Proof using .\n    apply InfA_alt; eauto with typeclass_instances.\n  Qed.\n\n  Lemma Sort_NoDup : forall l, Sort l -> NoDup l.\n  Proof using .\n    apply SortA_NoDupA; eauto with typeclass_instances.\n  Qed.\nEnd ForNotations.\nUnset Implicit Arguments.\nHint Resolve @ListIn_In @Sort_NoDup @Inf_lt.\nHint Immediate @In_eq @Inf_lt.\n\nModule KeyOrderedType.\nSection KeyOrderedType.\n  Set Implicit Arguments.\n  Unset Strict Implicit.\n\n  Variable key : Type.\n  Hypothesis (key_OT : OrderedType key).\n  Variable elt : Type.\n\n  Definition eqk (p p':key*elt) := fst p === fst p'.\n  Definition eqke (p p':key*elt) :=\n    fst p === fst p' /\\ (snd p) = (snd p').\n  Definition ltk (p p':key*elt) := fst p <<< fst p'.\n\n  Local Instance eqk_Equiv : Equivalence eqk.\n  Proof using .\n    constructor; repeat intro; unfold eqk in *; eauto.\n    transitivity (fst y); auto.\n  Qed.\n  Local Instance eqke_Equiv : Equivalence eqke.\n  Proof using .\n    constructor; repeat intro; unfold eqke in *; intuition.\n    transitivity (fst y); auto.\n    congruence.\n  Qed.\n  Local Instance ltk_SO : RelationClasses.StrictOrder ltk.\n  Proof using .\n    constructor; repeat intro; unfold ltk in *; intuition order. \n  Qed.\n  Local Instance ltk_m : Proper (eqk ==> eqk ==> iff) ltk.\n  Proof using .\n    repeat intro; unfold ltk, eqk in *; intuition order.\n  Qed.\n  Ltac teauto := eauto with typeclass_instances.\n\n  Hint Unfold eqk eqke ltk.\n  Hint Extern 2 (eqke ?a ?b) => split.\n\n  (* eqke is stricter than eqk *)\n  Lemma eqke_eqk : forall x x', eqke x x' -> eqk x x'.\n  Proof using .\n    unfold eqk, eqke; intuition.\n  Qed.\n\n  (* ltk ignore the second components *)\n  Lemma ltk_right_r : forall x k e e', ltk x (k,e) -> ltk x (k,e').\n  Proof using . auto. Qed.\n\n  Lemma ltk_right_l : forall x k e e', ltk (k,e) x -> ltk (k,e') x.\n  Proof using . auto. Qed.\n  Hint Immediate ltk_right_r ltk_right_l.\n\n  (* eqk, eqke are equalities, ltk is a strict order *)\n  Lemma eqk_refl : forall e, eqk e e.\n  Proof using . auto. Qed.\n\n  Lemma eqke_refl : forall e, eqke e e.\n  Proof using . auto. Qed.\n\n  Lemma eqk_sym : forall e e', eqk e e' -> eqk e' e.\n  Proof using . auto. Qed.\n\n  Lemma eqke_sym : forall e e', eqke e e' -> eqke e' e.\n  Proof using . unfold eqke; intuition. Qed.\n\n  Lemma eqk_trans : forall e e' e'', eqk e e' -> eqk e' e'' -> eqk e e''.\n  Proof using .\n    intros; unfold eqk in *; auto; transitivity (fst e'); auto.\n  Qed.\n\n  Lemma eqke_trans : forall e e' e'', eqke e e' -> eqke e' e'' -> eqke e e''.\n  Proof using .\n    unfold eqke; intuition; [ eauto | congruence ].\n    transitivity (fst (a0, b0)); auto.\n  Qed.\n\n  Lemma ltk_trans : forall e e' e'', ltk e e' -> ltk e' e'' -> ltk e e''.\n  Proof using .\n    intros; unfold ltk in *; auto; transitivity (fst e'); auto.\n  Qed.\n\n  Lemma ltk_not_eqk : forall e e', ltk e e' -> ~ eqk e e'.\n  Proof using .\n    unfold eqk, ltk; auto; intros; apply lt_not_eq; auto.\n  Qed.\n\n  Lemma ltk_not_eqke : forall e e', ltk e e' -> ~eqke e e'.\n  Proof using .\n    unfold eqke, ltk; intuition; simpl in *; subst.\n    exact (lt_not_eq H H1).\n  Qed.\n\n  Hint Resolve eqk_trans eqke_trans eqk_refl eqke_refl.\n  Hint Resolve ltk_trans ltk_not_eqk ltk_not_eqke.\n  Hint Immediate eqk_sym eqke_sym.\n\n  (* Additionnal facts *)\n\n  Lemma eqk_not_ltk : forall x x', eqk x x' -> ~ltk x x'.\n  Proof using .\n    unfold eqk, ltk; simpl; auto.\n    intros; apply eq_not_lt; auto.\n  Qed.\n\n  Lemma ltk_eqk : forall e e' e'', ltk e e' -> eqk e' e'' -> ltk e e''.\n  Proof using .\n    intros; unfold ltk, eqk in *; auto; order.\n  Qed.\n\n  Lemma eqk_ltk : forall e e' e'', eqk e e' -> ltk e' e'' -> ltk e e''.\n  Proof using .\n      intros (k,e) (k',e') (k'',e'').\n      unfold ltk, eqk; simpl; eauto; order.\n  Qed.\n  Hint Resolve eqk_not_ltk.\n  Hint Immediate ltk_eqk eqk_ltk.\n\n  Lemma InA_eqke_eqk :\n     forall x m, InA eqke x m -> InA eqk x m.\n  Proof using .\n    unfold eqke; induction 1; intuition.\n  Qed.\n  Hint Resolve InA_eqke_eqk.\n\n  Definition MapsTo (k:key)(e:elt):= InA eqke (k,e).\n  Definition In k m := exists e:elt, MapsTo k e m.\n  Notation Sort := (sort ltk).\n  Notation Inf := (lelistA ltk).\n\n  Hint Unfold MapsTo In.\n\n  (* An alternative formulation for [In k l] is [exists e, InA eqk (k,e) l] *)\n  Lemma In_alt : forall k l, In k l <-> exists e, InA eqk (k,e) l.\n  Proof using .\n    firstorder.\n    exists x; auto.\n    induction H.\n    destruct y.\n    exists e; auto.\n    destruct IHInA as [e H0].\n    exists e; auto.\n  Qed.\n\n  Lemma MapsTo_eq : forall l x y e, x === y -> MapsTo x e l -> MapsTo y e l.\n  Proof using .\n    intros; unfold MapsTo in *; apply InA_eqA with (x,e); teauto.\n  Qed.\n\n  Lemma In_eq : forall l x y, x === y -> In x l -> In y l.\n  Proof using .\n    destruct 2 as (e,E); exists e; eapply MapsTo_eq; eauto.\n  Qed.\n\n  Lemma Inf_eq : forall l x x', eqk x x' -> Inf x' l -> Inf x l.\n  Proof using . apply InfA_eqA; teauto. Qed.\n\n  Lemma Inf_lt : forall l x x', ltk x x' -> Inf x' l -> Inf x l.\n  Proof using . apply InfA_ltA; teauto. Qed.\n\n  Hint Immediate Inf_eq.\n  Hint Resolve Inf_lt.\n\n  Lemma Sort_Inf_In :\n      forall l p q, Sort l -> Inf q l -> InA eqk p l -> ltk q p.\n  Proof using .\n    apply SortA_InfA_InA; teauto.\n  Qed.\n\n  Lemma Sort_Inf_NotIn :\n      forall l k e, Sort l -> Inf (k,e) l ->  ~In k l.\n  Proof using .\n    intros; red; intros.\n    destruct H1 as [e' H2].\n    elim (@ltk_not_eqk (k,e) (k,e')).\n    eapply Sort_Inf_In; eauto.\n    red; simpl; auto.\n  Qed.\n\n  Lemma Sort_NoDupA: forall l, Sort l -> NoDupA eqk l.\n  Proof using .\n    apply SortA_NoDupA; teauto.\n  Qed.\n\n  Lemma Sort_In_cons_1 : forall e l e', Sort (e::l) -> InA eqk e' l -> ltk e e'.\n  Proof using .\n   inversion 1; intros; eapply Sort_Inf_In; eauto.\n  Qed.\n\n  Lemma Sort_In_cons_2 : forall l e e', Sort (e::l) -> InA eqk e' (e::l) ->\n      ltk e e' \\/ eqk e e'.\n  Proof using .\n    inversion_clear 2; auto.\n    left; apply Sort_In_cons_1 with l; auto.\n  Qed.\n\n  Lemma Sort_In_cons_3 :\n    forall x l k e, Sort ((k,e)::l) -> In x l -> x =/= k.\n  Proof using .\n    inversion_clear 1; red; intros.\n    exact (Sort_Inf_NotIn H0 H1 (In_eq H2 H)).\n  Qed.\n\n  Lemma In_inv : forall k k' e l, In k ((k',e) :: l) -> k === k' \\/ In k l.\n  Proof using .\n    inversion 1.\n    inversion_clear H0; eauto.\n    destruct H1; simpl in *; intuition.\n  Qed.\n\n  Lemma In_inv_2 : forall k k' e e' l,\n      InA eqk (k, e) ((k', e') :: l) -> k =/= k' -> InA eqk (k, e) l.\n  Proof using .\n   inversion_clear 1; unfold eqk in H0; simpl in H0; order.\n  Qed.\n\n  Lemma In_inv_3 : forall x x' l,\n      InA eqke x (x' :: l) -> ~eqk x x' -> InA eqke x l.\n  Proof using .\n   inversion_clear 1; compute in H0; intuition.\n  Qed.\n\nEnd KeyOrderedType.\nHint Unfold eqk eqke ltk.\nHint Extern 2 (eqke ?a ?b) => split.\nHint Resolve eqk_trans eqke_trans eqk_refl eqke_refl.\nHint Resolve ltk_trans ltk_not_eqk ltk_not_eqke.\nHint Immediate eqk_sym eqke_sym.\nHint Resolve eqk_not_ltk.\nHint Immediate ltk_eqk eqk_ltk.\nHint Resolve InA_eqke_eqk.\nHint Unfold MapsTo In.\nHint Immediate Inf_eq.\nHint Resolve Inf_lt.\nHint Resolve Sort_Inf_NotIn.\nHint Resolve In_inv_2 In_inv_3.\n\nArguments eqk [key] [key_OT] [elt].\nArguments eqke [key] [key_OT] [elt].\nArguments ltk [key] [key_OT] [elt].\nArguments MapsTo [key] [key_OT] [elt].\nArguments In [key] [key_OT] [elt].\nEnd KeyOrderedType.\n", "meta": {"author": "MathisBD", "repo": "pactole_stage", "sha": "4b63da0898ae4f48956408dc31f7831d3ad8930f", "save_path": "github-repos/coq/MathisBD-pactole_stage", "path": "github-repos/coq/MathisBD-pactole_stage/pactole_stage-4b63da0898ae4f48956408dc31f7831d3ad8930f/Util/FSets/OrderedType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7497224741343939}}
{"text": "Set Implicit Arguments.\n\nInductive exp : Set :=\n| Nat : nat -> exp\n| Plus : exp -> exp -> exp\n| Bool : bool -> exp\n| And : exp -> exp -> exp.\n\nInductive type : Set := TNat | TBool.\n\nLocate \"+\".\n\nPrint sumbool.\n\n(*\nInductive sumbool (A B : Prop) : Set :=\n    left : A -> {A} + {B} | right : B -> {A} + {B}\n*)\n\nDefinition eq_type_dec: forall (t1 t2:type), {t1=t2}+{t1<>t2}.\ndecide equality.\nQed.\n\nPrint eq_type_dec.\n\n\nInductive hasType : exp -> type -> Prop :=\n| HtNat : forall n,\n  hasType (Nat n) TNat\n| HtPlus : forall e1 e2,\n  hasType e1 TNat\n  -> hasType e2 TNat\n  -> hasType (Plus e1 e2) TNat\n| HtBool : forall b,\n  hasType (Bool b) TBool\n| HtAnd : forall e1 e2,\n  hasType e1 TBool\n  -> hasType e2 TBool\n  -> hasType (And e1 e2) TBool.\n\n\nLemma hasType_det : forall e t1, hasType e t1 ->\n forall t2, hasType e t2 -> t1 = t2.\n  induction e.\n  inversion 1.\n  inversion 1;auto.\n  inversion 1.\n  inversion 1;auto.\n  inversion 1.\n  inversion 1;auto.\n  inversion 1.\n  inversion 1;auto.\nRestart.\n  induction 1.\n  inversion 1; auto. \n  inversion 1;auto. \n  inversion 1;auto. \n  inversion 1;auto.\nRestart.\n  induction 1;  inversion 1; auto.\nQed.\n\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/Slajdy19/PlikiCoqa/hastype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7497224684792905}}
{"text": "\n(** Church Number ~ nat *)\n\nRequire Import Arith.\nRequire Export FunctionalExtensionality.\nRequire Export ProofIrrelevance.\n\n\nNotation cnat_ctt := (forall (X : Type), (X -> X) -> X -> X).\n\n    Inductive valid_cnat : cnat_ctt -> Prop := \n    | Ocnat : valid_cnat (fun (X : Type) (f : X -> X) (x : X) => x)\n    | Scnat (c : cnat_ctt) (H : valid_cnat c) : valid_cnat (fun (X : Type) (f : X -> X) (x : X) => f (c X f x)).\n    \n    (** There is a practical example: Church numbers. *)\n    Record cnat := mk_cnat {\n        cn :> cnat_ctt;\n        cn_proof : valid_cnat cn;\n    }.\n    \n    Lemma cnat_eq : forall c1 c2 : cnat, c1 = c2 <-> (cn c1) = (cn c2).\n    Proof.\n        move => c1 c2. split. by move => ->.\n        destruct c1 as [c1 p1], c2 as [c2 p2] => //= H.\n        move : p1 p2. rewrite H => p1 p2. by rewrite (proof_irrelevance _ p1 p2).\n    Qed.\n    \n    Definition cnat2nat (c : cnat) : nat := c nat S O.\n    \n    Fixpoint nat2cnat_cn (n : nat) : forall X : Type, (X -> X) -> X -> X :=\n        fun (X : Type) (f : X -> X) (x : X) =>\n            match n with\n            | O => x\n            | S n' => f (nat2cnat_cn n' f x)\n            end.\n    \n    Definition nat2cnat (n : nat) : cnat.\n    Proof.\n        refine (@mk_cnat (nat2cnat_cn n) _).\n        elim: n. apply Ocnat.\n        move => n IHn. apply Scnat. apply IHn.\n    Defined.\n        \n    \n    \n    \n    \n    Lemma bijection_nat2cnat : bijective nat2cnat.\n    Proof. apply inv_is_bij. rewrite /invertible. exists cnat2nat. split.\n    \n        elim => //=. move => n. by rewrite /cnat2nat => ->.\n    \n        move => [y Hy]. apply cnat_eq => //=. \n        apply functional_extensionality_dep => X.\n        apply functional_extensionality => f. \n        apply functional_extensionality => x.\n        elim : Hy => //=.\n        move => c _ IHc.  by rewrite IHc.\n    Qed.\n    \n    Theorem cnat_nat_iso : isomorphic nat cnat.\n    Proof. exists nat2cnat. by apply bijection_nat2cnat. Qed.\n    \n    Theorem cnat_nat_eq : nat:Type = cnat.\n    Proof. apply isomorphic_extensionality. by apply cnat_nat_iso. Qed.\n    \n    \n    \n    Coercion cnat2nat : cnat >-> nat. \n    \n    Coercion nat2cnat : nat >-> cnat. \n    \n    \n    Compute (10 _ S 0).\n    Compute (10 _ (fun x => 2*x + 1) 0).\n\n    \nGoal inhabited cnat.\nProof. \n    Fail rewrite -cnat_nat_eq.\n    (** M@GIC *)\n    case cnat_nat_eq.\n    constructor. by exact 1.\nQed.\n\n\n(** This [theory_functor] can be considered as a `functor', meaning a `theory' about\n    T. *)\n    Definition theory_functor (T : Type) : Prop :=\n        exists add_op : T -> T -> T, (forall a b, add_op a b = add_op b a).\n    \n    Lemma theory_functor_nat : theory_functor nat.\n    Proof. exists Nat.add. apply Nat.add_comm. Qed.\n        \n    Lemma theory_functor_cnat : theory_functor cnat.\n    Proof. case cnat_nat_eq. apply theory_functor_nat. Qed.\n    \n    (** We have transported the theories from [nat] to [cnat]. *)\n    ", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/stories/church_num_isomorphic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7496759141789114}}
{"text": "(*\nAdresse email des TDmen : [Prenom].[Nom]@ens-lyon.fr\n\nPour avoir les raccourcis comme il faut :\n- Lancer \"coqide\" \n- Edit > Preferences > Shortcuts > Modifiers for Navigation Menu\n- Changer vers <alt> uniquement (en sélectionnant/désélectionnant les cases)\n- Cliquer sur OK\n- Quitter coqide\n- Relancer coqide\n*)\n\n\n\n(* Table des matières du TP:\n\t1. Découverte de coq\n\t2. Démonstrations élémentaires\n\t3. Inductions structurelles\n\t4. Calcul Propositionnel\n\t5. Arithmétique *)\n\n(** TP n°1 : Introduction à Coq **)\n\n(** Partie 1 : Découverte de coq **)\n\n(* Toutes les expressions bien formées de Coq ont un type que l'on\npeut demander à l'interpréteur grâce à la commande \"Check\" : *)\n\nCheck 3. (* \"nat\" : type des entiers naturels *)\nCheck 2 + 2. \nCheck (plus 2 2). (* + est une notation \"infixe\" de la fonction plus *)\nCheck plus.  (* fonction qui prend deux \"nat\"s et renvoie un \"nat\" *)\n\n\n(* Les types sont eux-mêmes des expressions bien formées de Coq, elles\nont donc également un type. *)\n\nCheck nat. (* \"Set\" est le type des types de données. *)\n\nCheck nat -> nat -> nat.\n\n\n(* On peut également demander à Coq de nous donner la définition d'une \nd'une expression déjà définie; on utilise pour ça la commande \"Print\". *) \n\nPrint nat.\nPrint plus.\n\n\n(* On peut bien sûr définir de nouvelles fonctions *) \n\nDefinition facteur_deux (n : nat) := 2 * n.\nCheck facteur_deux.\nPrint facteur_deux.\n\n\n(* Et on utilise la syntaxe suivante pour faire des définitions\nrécursives: *)\n\nFixpoint double (n : nat) :=\n  match n with \n    | 0 => 0\n    | S p => S (S (double p))\n  end.\n\nPrint double.\n\n\n(* Sur le même modèle implémentez la fonction [somme_jusqu_a : nat -> nat] qui\ncalcule la somme des premiers entiers *)\n\nFixpoint somme_jusqu_a (n : nat ) :=\n    match n with\n    |0 => 0\n    |S p => n + somme_jusqu_a p\n    end.\n(* ... Complétez ici ... *)\n\nEval compute in somme_jusqu_a 10.\n\n\n\n(** Partie 2 : Démonstrations élementaires **)\n\n\n(* En plus des types de données et des programmes, coq permet également \nde manipuler des formules. À commencer par les égalités : *)\n\nCheck 0 = 0. (* \"Prop\" : type des formules logiques. *)\nCheck 0 = 1. (* \"Prop\" : type des formules logiques, même si elles sont fausses! *)\n\n(* Enfin, Coq permet de prouver les formules à l'aide d'un système de \n   \"tactiques\" de preuves. \n   Voici la liste des tactiques que nous allons explorer: \n    reflexivity , intros , simpl , rewrite , induction\n    (l'utilisation de toute autre tactique, trouvée sur internet par exemple, est prohibée) *)\nLemma zero_egale_zero :\n  0 = 0.\nProof.\nreflexivity. (* Comme on le verra plus tard, c'est la tactique qui\n                  résout les égalités triviales. *)\nQed.\n\nLemma deux_plus_deux_egale_quatre : \n  2+2 = 4.\nProof.\nsimpl. (* Cette tactique nous sera très utile dans la suite, elle\n                  sert à effectuer les pas de calcul dans les buts. *)\nreflexivity.\nQed.\n\n(* On dispose également de quantificateurs pour fabriquer les formules :*)\nCheck (forall x y : nat, x+y = y + x). (* Une formule qui nous dit que + est commutatif. *)\n\n(* Il y a quelques tactiques qu'il faudra apprendre à utiliser.\n   Voici un exemple de preuve un peu moins triviales. Pouvez-vous \n   retranscrire cette preuve simple en \"mathématiques informelles\" ? *)\n\n(* On dispose également d'une égalité entre les termes de \n   coq qui vient avec trois tactiques pour les manipuler: \n      - [reflexivity] : permet de prouver les but de la forme t=t. \n      - [symmetry] : permet de transformer un but t₁ = t₂ en t₂ = t₁.\n      - [rewrite H] : si H est une hypothèse de la forme \"t₁ = t₂\"\n        cette tactique remplace dans le but courant les sous-termes\n        de la forme t₁ par t₂.\n      - [rewrite <-H] : si H est une hypothèse de la forme \"t₁ = t₂\"\n        cette tactique remplace dans le but courant les sous-termes\n        de la forme t₂ par t₁.  *)\n\nLemma double_egale_multiple_de_deux : \n  forall n, double n = n * 2.\nintros n. (*soit n entier*)\ninduction n. (*par récurrence sur n*)\n+ simpl. (*initialisation par calcul*)\n  reflexivity. (*par réflexivité*)\n+ simpl. (*heredite, calcul*)\n  rewrite IHn. (*par hypothese de recurrence*)\n  reflexivity. (*par reflexivite*)\nQed.\n\n\n(* \"+\", \"*\" ou \"-\" en début de ligne servent uniquement à mettre structurer et indenter la preuve;\n   mathématiquement, cela revient à ne rien faire *)\n\n\n(* Les deux tactiques centrales de COQ sont \n     - [intros H] : l'équivalent de \"soit H\" et de \"supposons que...\"\n                   dans les maths informelles, [intros H] introduit une\n                   hypothèse H dans le contexte.\n       (notez qu'il est également permis d'invoquer [intros H1 H2 H3]\n       à la place de [intros A. intros B. intros C.]  pour faire des \n       intros successifs)\n     - [apply H] : permet d'invoquer l'hypothèse nommée H. *)\n\n\n\n\nLemma egalite_transitive :\n  forall (x y z : nat), x = y -> y = z -> x = z.\nProof.\n    intros.\n    rewrite H.\n    rewrite H0.\n    reflexivity.\nQed.\n\n\n(** Partie 3: Définitions inductives, inductions structurelles *)\n\n\n(* Jusqu'ici, on a utilisés la commande induction \n   pour réaliser des récurrences sur les entiers; \n   cependant, les entiers sont des types inductifs! Regardez à nouveau: *)\n\nPrint nat.\nPrint plus.\n\n\n(* De facon informelle, quand on definit un type inductif on donne\ntoutes les manières de construire un élément de ce type.  Un entier\nnaturel est soit zéro (construit par le constructeur \"O\"), soit le\nsuccesseur d'un autre entier naturel (construit par le constructeur\n\"S\").\n  \n                      n : nat \n   ----------      --------------\n    0 : nat          S n : nat    \n  \nUn autre exemple : le type \"bool\" des booleens est également inductif:\n  \n    -----------          ------------\n    true : bool          false : bool      *)\n\nPrint bool.\n\n(* Un booléen est soit 0, soit 1; soit vrai, soit faux. *)\n\n(* En coq, on peut aussi définir de nouveaux types inductifs! Par exemple, les listes. La\ndéfinition ressemble à celle que l'on aurait fait en Caml: *)\n\nInductive liste_nat := \n | liste_vide : liste_nat\n | cons : nat -> liste_nat -> liste_nat.\n\n\n(* On définit le type \"liste_nat\" de liste des entiers naturels avec deux\nconstructeurs : \"liste_vide\" qui permet de construire la liste vide et\n\"cons_nat\" qui permet de construire une nouvele liste à partir d'un\nentier et une liste.\n                                      l : liste_nat                 n : nat\n   ------------------------         -----------------------------------------\n    liste_vide : liste_nat                  cons_nat n l : liste_nat\n*)\n\n\n\n(* Et on peut définir comment concaténer deux listes, comme on a fait plus tôt pour\ncalculer le double d'un entier: *)\n\nFixpoint concat (l l' : liste_nat) := match l with\n | liste_vide => l'\n | cons n l'' => cons n (concat l'' l')\nend.\n\n\n\n(* Complétez la définition de la mesure de la longueur d'une liste d'entiers: *)\n\nFixpoint longueur l := match l with\n | liste_vide => 0\n | cons n l' => 1 + longueur l'\nend.\n\n\n\n(* Chaque fois qu'on définit un type inductif, Coq génère un principe\nd'induction pour ce type. *)\n\nCheck liste_nat_ind.\nCheck nat_ind.\nCheck bool_ind.\n\n(* Ce principe va être automatiquement invoqué quand on utilise la\ntactique [induction]. Morale : on peut utiliser [induction] pour faire\nde preuves sur tous les types inductifs. *)\n\n\n(* On peut désormais prouver les lemmes suivants : *)\n\nLemma concat_vide : forall (l : liste_nat), concat liste_vide l = l.\nProof.\n    intros.\n    simpl.\n    reflexivity.\nQed.\n\n\nLemma vide_concat : forall (l : liste_nat), concat l liste_vide = l.\nProof.\n   intros.\n   induction l.\n   * simpl.\n   reflexivity.\n   *\n   simpl.\n   rewrite IHl.\n   reflexivity.\nQed.\n\n\nLemma longueur_concat : forall (l l' : liste_nat), longueur (concat l l') = longueur l + longueur l'.\nProof.\n    intros.\n    induction l.\n    *\n    simpl.\n    reflexivity.\n    *\n    simpl.\n    rewrite IHl.\n    reflexivity.\nQed.\n\n\n(** Partie 4 : Calcul propositionnel **)\n\n(* A vous de jouer maintenant! *)\n\nLemma trivial1 : forall P : Prop, P -> P.\nProof.\n    intros.\n    apply H.\nQed.\n\n\nLemma trivial2: forall P Q R:Prop, (P -> Q -> R) -> (P -> Q) -> P -> R.\nProof.\n    intros.\n    apply H.\n    *\n    apply H1.\n    *\n    apply H0.\n    apply H1.\nQed.\n\n\n(* Coq fournit les connecteurs logiques usuels :\n       connecteur ┃ destructeur ┃ constructeur\n      ━━━━━━━━━━━━╋━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━\n          P /\\ Q  ┃ [destruct]  ┆  [split]\n          P \\/ Q  ┃ [destruct]  ┆  [left] et [right]\n  exists x:nat, P ┃ [destruct]  ┆  [exists t]\n          False   ┃ [destruct]  ┆  aucun\n\n  Il est donc désormais autorisé d'utiliser, en plus des tactiques déjà explorées, les tactiques suivantes:\n   apply , destruct , split , left , right , exists\n\n  Mais, encore une fois, aucune autre tactique n'est autorisée!\n*)\n\nLemma conj1: forall P Q:Prop, P /\\ Q -> P.\nProof.\n    intros.\n    destruct H.\n    apply H.\nQed.\n\nLemma conj2: forall P Q:Prop, P /\\ Q -> Q.\nProof.\n    intros.\n    destruct H.\n    apply H0.\nQed.\n\nLemma conj3: forall P Q:Prop, P -> Q -> P /\\ Q.\nProof.\n    intros.\n    split.\n    apply H.\n    apply H0.\nQed.\n\nLemma or1 : forall P Q:Prop, P -> P \\/ Q.\nProof.\n    intros.\n    left.\n    apply H.\nQed.\n\nLemma or2 : forall P Q:Prop, Q -> P \\/ Q.\nProof.\n    intros.\n    right.\n    apply H.\nQed.\n\nLemma or3 : forall P Q R:Prop, P \\/ Q -> (P -> R) -> (Q -> R) -> R.\nProof.\n    intros.\n    destruct H.\n    * apply H0.\n    apply H.\n    *\n    apply H1.\n    apply H.\nQed.\n\n(* En COQ, la proposition fausse, ou \"l'absurde\", est appelée \"False\". *)\n\nLemma ex_falso: forall P:Prop, False -> P. (* si on suppose l'absurde, on peut tout démontrer *)\nProof.\n    intros.\n    destruct H.\nQed.\n\nNotation \"~ P\" := (P -> False). (* On définit la négation ainsi: la proposition \"Non P\", notée ~ P,\n                                   est vraie si supposer P permet de prouver l'absurde *)\n\n\nLemma not_not : forall P:Prop, P -> ~~P.\nProof.\n    intros P H H0.\n    apply H0.\n    apply H.\nQed.\n\nLemma morgan1 : forall P Q:Prop, \n  ~P \\/ ~Q -> ~(P /\\ Q).\nProof.\n    intros.\n    intros H0.\n    destruct H0.\n    destruct H.\n    *\n    apply H.\n    apply H0.\n    *\n    apply H.\n    apply H1.\nQed.\n\nLemma morgan2 : forall P Q:Prop, \n  ~P /\\ ~Q -> ~(P \\/ Q).\nProof.\n    intros.\n    intros H1.\n    destruct H.\n    destruct H1.\n    *\n    apply H.\n    apply H1.\n    *\n    apply H0.\n    apply H1.\nQed.\n\n\n(* En coq on peut également définition des propositions\n   qui dépendent de paramètre. Cela permet de représenter\n   d'autres relations que l'égalité *)\n\nDefinition leq (n m : nat) := exists k, n+k = m.\nCheck leq. (* Méditez le type de la relation. *)\n\n\nLemma leq_reflexive : \n  forall x, leq x x.\nProof.\n    intros.\n    exists 0.\n    induction x.\n    *\n    simpl.\n    apply zero_egale_zero.\n    *\n    simpl.\n    rewrite IHx.\n    reflexivity.\nQed.\n\nLemma plus_associative:\n  forall x y z, x+(y+z)=(x+y)+z.\nProof.\n  intros.\n  induction x.\n  *simpl.\n   reflexivity.\n  *simpl.\n   rewrite IHx.\n   reflexivity.\nQed.\n\nLemma leq_transitive : \n  forall x y z, leq x y -> leq y z -> leq x z.\nProof.\n  intros.\n  destruct H.\n  destruct H0.\n  exists (x0+x1).\n  rewrite<- H0.\n  rewrite<- H.\n  apply plus_associative.\nQed.\n(** Partie 5 : Arithmétique **)\n\n(* Rappel: on utilise la tactique simpl, pour simplifier les calculs. *)\nLemma zero_plus : forall x:nat, 0 + x = x.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma exists_factor : \n  exists n, exists m , n * (m+1) = 35.\nProof.\n  exists 5.\n  exists 6.\n  simpl.\n  reflexivity.\nQed.\n\n(* La tactique simpl ne marche par pour prouver la proposition\n   suivante. Pourquoi ? *)\n\nLemma plus_zero : forall x:nat, x + 0 = x.\nProof.\n\n(* Il va nous faloir démontrer le résultat par récurrence sur la\n   forme de x. \n   La tactique [induction x] invoque automatiquement le \n   principe d'induction pour prouver un but par induction sur \n   la variable x. *)\n\n  induction x.\n  *\n    reflexivity.\n  *\n    simpl.\n    rewrite IHx.\n    reflexivity.\n(* Il faut ensuite prouver le cas de base et l'hérédité...*) \n\nQed.\n\nLemma plus_assoc : forall a b c, (a + b) + c = a + (b + c).\nProof.\n  symmetry.\n  apply plus_associative.\nQed.\n\nLemma mult_zero : forall a, a*0 = 0.\nProof.\n  induction a.\n  *\n    simpl.\n    reflexivity.\n  *\n    simpl.\n    apply IHa.\nQed.\n\n\n\n\n\n(** Pour aller plus loin **)\n\n(* Pour finir, quelques exercices pour occuper les plus rapides d'entre vous :*)\n\n(* N'hésitez pas à faire des lemmes intermédiaires !*)\n\n\n(* Ce  n'est pas aussi trivial qu'il n'y paraît. *)\n\n\nLemma add1_trv : forall a, S a = 1+a.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma add1_comm : forall a, S a = a+1.\nProof.\n  intros.\n  induction a.\n  *\n    apply zero_plus.    \n  *\n    simpl.\n    rewrite IHa.\n    reflexivity.\nQed.\n    \nLemma plus_comm : forall a b, a + b = b + a.\nProof.\n  induction b.\n  *\n    simpl.\n    apply plus_zero.\n  *\n    rewrite add1_trv.\n    rewrite plus_associative.\n    rewrite<- add1_comm.\n    simpl.\n    rewrite IHb.\n    reflexivity.\nQed.\n\nLemma mult_distrib_gauche : forall a b c, a * (b + c) = a * b + a * c.\nProof.\n  induction a.\n  *\n  simpl.\n  reflexivity.\n  *\n    simpl.\n    intros.\n    rewrite IHa.\n    rewrite plus_assoc.\n    rewrite \nQed.\n\nLemma mult_distrib_droite : forall a b c, (b + c) * a = b * a + c * a.\nProof.\n...\nQed.\n\nLemma mult_comm : forall a b, a * b = b * a.\nProof.\n  induction a.\n  *\n    simpl.\n    symmetry.\n    apply mult_zero.\n  *\n    intros.\n    simpl.\n    Print Nat.mul.\n    rewrite. \nQed.\n\nLemma identite : \n  forall a b, (a + b)*(a+b) = a*a + 2*a*b + b*b.\nProof.\n...\nQed.\n\n(* Écrivez la fonction [power] qui calcule les puissances entières : *)\nFixpoint power a b := \n...\n\nInfix \"^\" := power.\n\nLemma power_exp: \n  forall a n m, a^(n + m) = a^n * a^m.\nProof.\n...\nQed.\n\nLemma closed:\n  forall n a b c, 3 <= n -> a^n + b^n = c^n -> a = c \\/ b = c.\nProof.\n...\nQed.\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/tp1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.8840392771633079, "lm_q1q2_score": 0.7496368007775838}}
{"text": "Require Import Nat_utils.\nRequire Import Validity.\nRequire Import ZArith. \nRequire Import Z_utils.\nRequire Import Coeff_utils.\nRequire Import Coeff.\nImport Z.\n\n(* Question 1.2.c *)\n\nFixpoint eval_base (p : poly) (f : nat -> Z) : Z := \nmatch p with\n| Cst z => z\n| Poly p1 i p2 => eval_base p1 f + (f i) * (eval_base p2 f)\nend.\n\nDefinition eval (p : valid_poly) (f : nat -> Z) : Z :=\n  eval_base (VP_value p) f.\n\n(* Question 1.2.d *)\n\nLemma invariance_i (p : poly) (i : nat) (f g : nat -> Z) :\n  valid_bool_i p i = true ->\n  (forall (j : nat), (i <=? j) = true -> f j = g j) ->\n  eval_base p f = eval_base p g.\nProof.\n  revert i.\n  induction p.\n  intros.\n  unfold eval_base.\n  reflexivity.\n  intros.\n  simpl eval_base.\n  apply Bool.andb_true_iff in H.\n  destruct H.\n  apply Bool.andb_true_iff in H1.\n  destruct H1.\n  apply Bool.andb_true_iff in H2.\n  destruct H2.\n  rewrite IHp1 with (i := i).\n  rewrite IHp2 with (i := i).\n  rewrite H0 with (j := n).\n  reflexivity.\n  assumption.\n  apply valid_leb with (p := p2) (m := i) (n := n).\n  assumption.\n  assumption.\n  assumption.\n  apply valid_leb with (p := p1) (m := i) (n := S n).\n  apply leb_trans with (n := n).\n  assumption.\n  apply leb_succ.\n  assumption.\n  assumption.\nQed.\n\nLemma non_constant_poly (p : poly) (i : nat) (z : Z) :\n  valid_bool_i p i = true ->\n  p <> Cst z ->\n  exists (f : nat -> Z) (n0 : Z),\n  forall (n : Z), (n0 <= n)%Z ->\n  eval_base p (fun (j : nat) => if j =? i then n else f j) <> z.\nProof.\n  revert i z.\n  induction p.\n  intros.\n  exists (fun _ => Z.zero).\n  exists Z.zero.\n  intros.\n  intro.\n  apply H0.\n  apply f_equal with (f := Cst).\n  assumption.\n\n  intros.\n  simpl valid_bool_i in H.\n  apply Bool.andb_true_iff in H.\n  destruct H.\n  apply Bool.andb_true_iff in H1.\n  destruct H1.\n  apply Bool.andb_true_iff in H2.\n  destruct H2.\n\n  destruct ltb_compare_dec with (m := n) (n := i).\n  exfalso.\n  revert H4.\n  apply Bool.not_true_iff_false.\n  apply ltb_leb.\n  assumption.\n  destruct H4.\n  destruct IHp2 with (i := n) (z := 0%Z).\n  assumption.\n  apply Bool.negb_true_iff in H1.\n  apply Bool.not_true_iff_false in H1.\n  intro.\n  apply H1.\n  apply is_null_iff.\n  assumption.\n  destruct H5.\n  exists (fun j => if j=? n then (max x0 (succ (abs (eval_base p1 x - z)))%Z) else x j).\n  exists 0%Z.\n  intros.\n  simpl eval_base.\n  rewrite <- invariance_i with (p := p1) (i := S n) (f := x) (g := fun  (j : nat) => if (j =? i)%nat then n0 else if (j =? n)%nat then max x0 (succ (abs (eval_base p1 x - z))) else x j).\n  rewrite ltb_is_neqb2 with (m := i) (n := n).\n  rewrite Nat.eqb_refl with (x := n).\n  rewrite <- invariance_i with (p := p2) (i := n) (f := fun (j : nat) => if (j =? n)%nat then max x0 (succ (abs (eval_base p1 x - z))) else x j) (g := fun (j : nat) => if (j =? i)%nat then n0 else if (j =? n)%nat then max x0 (succ (abs (eval_base p1 x - z))) else x j).\n  intro.\n  apply f_equal with (f := fun (x : Z) => Z.sub x z) in H7.\n  revert H7.\n  rewrite Z.sub_diag.\n  rewrite <- Z.add_opp_r.\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_comm with (m := (-z)%Z).\n  rewrite Z.add_assoc.\n  rewrite Z.add_opp_r.\n  apply z_abs_lt.\n  apply Z.lt_le_trans with (m := (succ (abs (eval_base p1 x - z)))%Z).\n  apply Z.lt_succ_diag_r.\n  apply Z.le_max_r.\n  apply H5 with (n := (max x0 (succ (abs (eval_base p1 x - z))))%Z).\n  apply Z.le_max_l.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  reflexivity.\n  apply leb_trans with (n := n).\n  assumption.\n  assumption.\n  assumption.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  rewrite ltb_is_neqb2 with (m := n) (n := j).\n  reflexivity.\n  assumption.\n  apply leb_trans with (n := n).\n  assumption.\n  apply leb_trans with (n := S n).\n  apply leb_succ.\n  assumption.\n\n  rewrite <- H4.\n  destruct IHp2 with (i := n) (z := 0%Z).\n  assumption.\n  apply Bool.negb_true_iff in H1.\n  apply Bool.not_true_iff_false in H1.\n  intro.\n  apply H1.\n  apply is_null_iff.\n  assumption.\n  destruct H5.\n  exists x.\n  exists (max x0 (succ (abs (eval_base p1 x - z)))%Z).\n  intros.\n  simpl eval_base.\n  rewrite Nat.eqb_refl with (x := n).\n  rewrite <- invariance_i with (p := p1) (i := S n) (f := x) (g := fun  (j : nat) => if (j =? n)%nat then n0 else x j).\n  intro.\n  apply f_equal with (f := fun (x : Z) => Z.sub x z) in H7.\n  revert H7.\n  rewrite Z.sub_diag.\n  rewrite <- Z.add_opp_r.\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_comm with (m := (-z)%Z).\n  rewrite Z.add_assoc.\n  rewrite Z.add_opp_r.\n  apply z_abs_lt.\n  apply Z.lt_le_trans with (m := (succ (abs (eval_base p1 x - z)))%Z).\n  apply Z.lt_succ_diag_r.\n  apply Z.le_trans with (m := (max x0 (succ (abs (eval_base p1 x - z))))%Z).\n  apply Z.le_max_r.\n  assumption.\n  apply H5 with (n := n0).\n  apply Z.le_trans with (m := (max x0 (succ (abs (eval_base p1 x - z))))%Z).\n  apply Z.le_max_l.\n  assumption.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := n) (n := j).\n  reflexivity.\n  assumption.\nQed.\n\nLemma diff_poly (p q : poly) (i : nat) :\n  valid_bool_i p i = true ->\n  valid_bool_i q i = true ->\n  p <> q ->\n  exists (f : nat -> Z) (n0 : Z), forall (n : Z), (n0 <= n)%Z ->\n  eval_base p (fun (j : nat) => if j =? i then n else f j) <> eval_base q (fun (j : nat) => if j =? i then n else f j).\nProof.\n  revert i q.\n  induction p.\n  induction q.\n  intros.\n  exists (fun _ => Z.zero).\n  exists 0%Z.\n  intros.\n  intro.\n  apply H1.\n  apply f_equal with (f := Cst).\n  assumption.\n\n  intros.\n  simpl eval_base.\n  destruct non_constant_poly with (p := Poly q1 n q2) (i := i) (z := z).\n  assumption.\n  intro.\n  apply H1.\n  symmetry.\n  assumption.\n  exists x.\n  destruct H2.\n  exists x0.\n  intros.\n  intro.\n  symmetry in H4.\n  revert H4.\n  apply H2 with (n := n0).\n  assumption.\n\n  induction q.\n  intros.\n  simpl eval_base.\n  apply non_constant_poly with (p := Poly p1 n p2) (i := i) (z := z).\n  assumption.\n  assumption.\n\n  intros.\n  destruct ltb_compare_dec with (m := n) (n := n0).\n  simpl valid_bool_i in H.\n  apply Bool.andb_true_iff in H.\n  destruct H.\n  apply Bool.andb_true_iff in H3.\n  destruct H3.\n  apply Bool.andb_true_iff in H4.\n  destruct H4.\n  destruct non_constant_poly with (p := p2) (i := n) (z := 0%Z).\n  assumption.\n  apply Bool.negb_true_iff in H3.\n  apply Bool.not_true_iff_false in H3.\n  intro.\n  apply H3.\n  apply is_null_iff.\n  assumption.\n  destruct H6.\n  exists (fun j => if j =? n then (max x0 (succ (abs (eval_base p1 x - eval_base (Poly q1 n0 q2) x))))%Z else x j).\n  exists (max x0 (succ (abs (eval_base p1 x - eval_base (Poly q1 n0 q2) x))))%Z.\n  intros.\n  rewrite <- invariance_i with (p := Poly q1 n0 q2) (i := n0) (f := x) (g := fun (j : nat) =>\n   if j =? i then n1 else if j =? n then (max x0 (succ (abs (eval_base p1 x - eval_base (Poly q1 n0 q2) x))))%Z else x j).\n  simpl eval_base.\n  rewrite <- invariance_i with (p := p1) (i := S n) (f := x) (g := fun (j : nat) =>\n   if j =? i then n1 else if j =? n then (max x0 (succ (abs (eval_base p1 x - (eval_base q1 x + x n0 * eval_base q2 x)))))%Z else x j).\n  intro.\n  apply f_equal with (f := fun y => (y - (eval_base q1 x + x n0 * eval_base q2 x))%Z) in H8.\n  revert H8.\n  rewrite Z.sub_diag.\n  rewrite <- Z.add_opp_r.\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_comm with (m := (-(eval_base q1 x + x n0 * eval_base q2 x))%Z).\n  rewrite Z.add_assoc.\n  rewrite Z.add_opp_r.\n  apply z_abs_lt.\n  apply Z.lt_le_trans with (m := (max x0 (succ (abs (eval_base p1 x - eval_base (Poly q1 n0 q2) x))))%Z).\n  apply Z.lt_le_trans with (m := (succ (abs (eval_base p1 x - eval_base (Poly q1 n0 q2) x)))%Z).\n  apply Z.lt_succ_diag_r.\n  apply Z.le_max_r.\n  elim (n =? i).\n  assumption.\n  rewrite Nat.eqb_refl with (x := n).\n  apply Z.le_refl.\n  destruct ltb_compare_dec with (m := n) (n := i).\n  exfalso.\n  revert H8.\n  apply Bool.not_true_iff_false.\n  apply ltb_leb.\n  assumption.\n  destruct H8.\n  rewrite <- invariance_i with (p := p2) (i := n) (f := fun (j : nat) => if j =? n then (max x0 (succ (abs (eval_base p1 x - (eval_base q1 x + x n0 * eval_base q2 x)))))%Z else x j).\n  apply H6 with (n := (max x0 (succ (abs (eval_base p1 x - (eval_base q1 x + x n0 * eval_base q2 x)))))%Z).\n  apply Z.le_max_l.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  reflexivity.\n  apply leb_trans with (n := n).\n  assumption.\n  assumption.\n  rewrite <- H8.\n  rewrite <- invariance_i with (p := p2) (i := n) (f := fun (j : nat) => if j =? n then n1 else x j).\n  apply H6 with (n := n1).\n  apply Z.le_trans with (m := (max x0 (succ (abs (eval_base p1 x - eval_base (Poly q1 n0 q2) x))))%Z).\n  apply Z.le_max_l.\n  assumption.\n  assumption.\n  intros.\n  elim (j =? n).\n  reflexivity.\n  reflexivity.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  rewrite ltb_is_neqb2 with (m := n) (n := j).\n  reflexivity.\n  assumption.\n  apply leb_trans with (n := S n).\n  assumption.\n  assumption.\n  simpl valid_bool_i in H0.\n  apply Bool.andb_true_iff in H0.\n  destruct H0.\n  simpl valid_bool_i.\n  apply Bool.andb_true_iff.\n  split.\n  apply Nat_utils.leb_refl.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  rewrite ltb_is_neqb2 with (m := n) (n := j).\n  reflexivity.\n  apply leb_trans with (n := n0).\n  assumption.\n  assumption.\n  apply leb_trans with (n := n0).\n  apply leb_trans with (n := S n).\n  assumption.\n  assumption.\n  assumption.\n\n  destruct H2.\n  simpl valid_bool_i in H0.\n  apply Bool.andb_true_iff in H0.\n  destruct H0.\n  apply Bool.andb_true_iff in H3.\n  destruct H3.\n  apply Bool.andb_true_iff in H4.\n  destruct H4.\n  destruct non_constant_poly with (p := q2) (i := n0) (z := 0%Z).\n  assumption.\n  apply Bool.negb_true_iff in H3.\n  apply Bool.not_true_iff_false in H3.\n  intro.\n  apply H3.\n  apply is_null_iff.\n  assumption.\n  destruct H6.\n  exists (fun j => if j =? n0 then (max x0 (succ (abs (eval_base q1 x - eval_base (Poly p1 n p2) x))))%Z else x j).\n  exists (max x0 (succ (abs (eval_base q1 x - eval_base (Poly p1 n p2) x))))%Z.\n  intros.\n  rewrite <- invariance_i with (p := Poly p1 n p2) (i := n) (f := x) (g := fun (j : nat) =>\n   if j =? i then n1 else if j =? n0 then (max x0 (succ (abs (eval_base q1 x - eval_base (Poly p1 n p2) x))))%Z else x j).\n  simpl eval_base.\n  rewrite <- invariance_i with (p := q1) (i := S n0) (f := x) (g := fun (j : nat) =>\n   if j =? i then n1 else if j =? n0 then (max x0 (succ (abs (eval_base q1 x - (eval_base p1 x + x n * eval_base p2 x)))))%Z else x j).\n  intro.\n  apply f_equal with (f := fun y => (y - (eval_base p1 x + x n * eval_base p2 x))%Z) in H8.\n  symmetry in H8.\n  revert H8.\n  rewrite Z.sub_diag.\n  rewrite <- Z.add_opp_r.\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_comm with (m := (-(eval_base p1 x + x n * eval_base p2 x))%Z).\n  rewrite Z.add_assoc.\n  rewrite Z.add_opp_r.\n  apply z_abs_lt.\n  apply Z.lt_le_trans with (m := (max x0 (succ (abs (eval_base q1 x - eval_base (Poly p1 n p2) x))))%Z).\n  apply Z.lt_le_trans with (m := (succ (abs (eval_base q1 x - eval_base (Poly p1 n p2) x)))%Z).\n  apply Z.lt_succ_diag_r.\n  apply Z.le_max_r.\n  elim (n0 =? i).\n  assumption.\n  rewrite Nat.eqb_refl with (x := n0).\n  apply Z.le_refl.\n  destruct ltb_compare_dec with (m := n0) (n := i).\n  exfalso.\n  revert H8.\n  apply Bool.not_true_iff_false.\n  apply ltb_leb.\n  assumption.\n  destruct H8.\n  rewrite <- invariance_i with (p := q2) (i := n0) (f := fun (j : nat) => if j =? n0 then (max x0 (succ (abs (eval_base q1 x - (eval_base p1 x + x n * eval_base p2 x)))))%Z else x j).\n  apply H6 with (n := (max x0 (succ (abs (eval_base q1 x - (eval_base p1 x + x n * eval_base p2 x)))))%Z).\n  apply Z.le_max_l.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  reflexivity.\n  apply leb_trans with (n := n0).\n  assumption.\n  assumption.\n  rewrite <- H8.\n  rewrite <- invariance_i with (p := q2) (i := n0) (f := fun (j : nat) => if j =? n0 then n1 else x j).\n  apply H6 with (n := n1).\n  apply Z.le_trans with (m := (max x0 (succ (abs (eval_base q1 x - eval_base (Poly p1 n p2) x))))%Z).\n  apply Z.le_max_l.\n  assumption.\n  assumption.\n  intros.\n  elim (j =? n0).\n  reflexivity.\n  reflexivity.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  rewrite ltb_is_neqb2 with (m := n0) (n := j).\n  reflexivity.\n  assumption.\n  apply leb_trans with (n := S n0).\n  assumption.\n  assumption.\n  simpl valid_bool_i in H.\n  apply Bool.andb_true_iff in H.\n  destruct H.\n  simpl valid_bool_i.\n  apply Bool.andb_true_iff.\n  split.\n  apply Nat_utils.leb_refl.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  rewrite ltb_is_neqb2 with (m := n0) (n := j).\n  reflexivity.\n  apply leb_trans with (n := n).\n  assumption.\n  assumption.\n  apply leb_trans with (n := n).\n  apply leb_trans with (n := S n0).\n  assumption.\n  assumption.\n  assumption.\n\n  simpl valid_bool_i in H.\n  apply Bool.andb_true_iff in H.\n  destruct H.\n  apply Bool.andb_true_iff in H3.\n  destruct H3.\n  apply Bool.andb_true_iff in H4.\n  destruct H4.\n  simpl valid_bool_i in H0.\n  apply Bool.andb_true_iff in H0.\n  destruct H0.\n  apply Bool.andb_true_iff in H6.\n  destruct H6.\n  apply Bool.andb_true_iff in H7.\n  destruct H7.\n  destruct excluded_middle_poly with (p := p2) (q := q2).\n  destruct excluded_middle_poly with (p := p1) (q := q1).\n  destruct H1.\n  apply f_equal3 with (f := Poly).\n  assumption.\n  assumption.\n  assumption.\n  destruct IHp1 with (i := i) (q := q1).\n  apply valid_leb with (n := S n).\n  apply leb_trans with (n := n).\n  assumption.\n  apply leb_succ.\n  assumption.\n  apply valid_leb with (n := S n0).\n  apply leb_trans with (n := n0).\n  assumption.\n  apply leb_succ.\n  assumption.\n  assumption.\n  destruct H11.\n  exists x.\n  exists x0.\n  intros.\n  rewrite <- H2.\n  rewrite <- H9.\n  simpl eval_base.\n  intro.\n  apply f_equal with (f := fun (y : Z) => (y - (if (n =? i)%nat then n1 else x n) * eval_base p2 (fun j : nat => if (j =? i)%nat then n1 else x j))%Z) in H13.\n  revert H13.\n  rewrite Z.add_simpl_r.\n  rewrite Z.add_simpl_r.\n  apply H11 with (n := n1).\n  assumption.\n  rewrite <- H2.\n  destruct IHp2 with (i := n) (q := q2).\n  assumption.\n  rewrite H2.\n  assumption.\n  assumption.\n  destruct H10.\n  exists (fun (j : nat) => if j =? n then (max x0 (succ (abs (eval_base p1 x - eval_base q1 x))))%Z else x j).\n  exists (max x0 (succ (abs (eval_base p1 x - eval_base q1 x))))%Z.\n  intros.\n  simpl eval_base.\n  rewrite <- invariance_i with (p := p1) (i := S n) (f := x) (g := fun (j : nat) =>\n   if j =? i then n1 else if j =? n then (max x0 (succ (abs (eval_base p1 x - eval_base q1 x))))%Z else x j).\n  rewrite <- invariance_i with (p := q1) (i := S n) (f := x) (g := fun (j : nat) =>\n   if j =? i then n1 else if j =? n then (max x0 (succ (abs (eval_base p1 x - eval_base q1 x))))%Z else x j).\n  rewrite Nat.eqb_refl with (x := n).\n  intro.\n  apply f_equal with (f := fun (y : Z) => (y-(eval_base q1 x +\n       (if (n =? i)%nat then n1 else max x0 (succ (abs (eval_base p1 x - eval_base q1 x)))) *\n       eval_base q2\n         (fun j : nat =>\n          if (j =? i)%nat\n          then n1\n          else if (j =? n)%nat then max x0 (succ (abs (eval_base p1 x - eval_base q1 x))) else x j)))%Z) in H12.\n  revert H12.\n  rewrite Z.sub_diag.\n  rewrite <- Z.add_opp_r.\n  rewrite Z.opp_add_distr.\n  rewrite Z.add_assoc.\n  rewrite <- Z.add_assoc with (p := (- eval_base q1 x)%Z).\n  rewrite Z.add_comm with (m := (- eval_base q1 x)%Z).\n  rewrite Z.add_assoc with (m := (- eval_base q1 x)%Z).\n  rewrite Z.add_opp_r with (n := eval_base p1 x).\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_opp_r.\n  rewrite <- Z.mul_sub_distr_l with (n := if (n =? i)%nat then n1 else max x0 (succ (abs (eval_base p1 x - eval_base q1 x)))).\n  apply z_abs_lt.\n  elim (n =? i).\n  apply Z.lt_le_trans with (m := (succ (abs (eval_base p1 x - eval_base q1 x)))%Z).\n  apply Z.lt_succ_diag_r.\n  apply Z.le_trans with (m := (max x0 (succ (abs (eval_base p1 x - eval_base q1 x))))%Z).\n  apply Z.le_max_r.\n  assumption.\n  apply Z.lt_le_trans with (m := (succ (abs (eval_base p1 x - eval_base q1 x)))%Z).\n  apply Z.lt_succ_diag_r.\n  apply Z.le_max_r.\n  destruct ltb_compare_dec with (m := n) (n := i).\n  exfalso.\n  revert H12.\n  apply Bool.not_true_iff_false.\n  apply ltb_leb.\n  assumption.\n  destruct H12.\n  rewrite <- invariance_i with (p := p2) (i := n) (f := fun (j : nat) => if (j =? n) then max x0 (succ (abs (eval_base p1 x - eval_base q1 x))) else x j).\n  rewrite <- invariance_i with (p := q2) (i := n) (f := fun (j : nat) => if (j =? n) then max x0 (succ (abs (eval_base p1 x - eval_base q1 x))) else x j).\n  intro.\n  apply f_equal with (f := fun (y : Z) => (y + eval_base q2\n         (fun j : nat => if (j =? n)%nat then max x0 (succ (abs (eval_base p1 x - eval_base q1 x))) else x j))%Z) in H13.\n  revert H13.\n  rewrite <- Z.add_opp_r.\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_opp_diag_l.\n  rewrite Z.add_0_r.\n  rewrite Z.add_0_l.\n  apply H10 with (n := (max x0 (succ (abs (eval_base p1 x - eval_base q1 x))))%Z).\n  apply Z.le_max_l.\n  rewrite H2.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  reflexivity.\n  apply leb_trans with (n := n).\n  assumption.\n  assumption.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  reflexivity.\n  apply leb_trans with (n := n).\n  assumption.\n  assumption.\n  rewrite <- H12.\n  rewrite <- invariance_i with (p := p2) (i := n) (f := fun (j : nat) => if j =? n then n1 else x j).\n  rewrite <- invariance_i with (p := q2) (i := n) (f := fun (j : nat) => if j =? n then n1 else x j).\n  intro.\n  apply f_equal with (f := fun (y : Z) => (y + eval_base q2\n         (fun j : nat => if (j =? n)%nat then n1 else x j))%Z) in H13.\n  revert H13.\n  rewrite <- Z.add_opp_r.\n  rewrite <- Z.add_assoc.\n  rewrite Z.add_opp_diag_l.\n  rewrite Z.add_0_r.\n  rewrite Z.add_0_l.\n  apply H10 with (n := n1).\n  apply Z.le_trans with (m := (max x0 (succ (abs (eval_base p1 x - eval_base q1 x))))%Z).\n  apply Z.le_max_l.\n  assumption. \n  rewrite H2.\n  assumption.\n  intros.\n  elim (j =? n).\n  reflexivity.\n  reflexivity.\n  assumption.\n  intros.\n  elim (j =? n).\n  reflexivity.\n  reflexivity.\n  rewrite H2.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  rewrite ltb_is_neqb2 with (m := n) (n := j).\n  reflexivity.\n  assumption.\n  apply leb_trans with (n := S n).\n  assumption.\n  assumption.\n  assumption.\n  intros.\n  rewrite ltb_is_neqb2 with (m := i) (n := j).\n  rewrite ltb_is_neqb2 with (m := n) (n := j).\n  reflexivity.\n  assumption.\n  apply leb_trans with (n := S n).\n  assumption.\n  assumption.\nQed.\n\nTheorem eval_eq (p q : valid_poly) :\n  (forall (f : nat -> Z), eval p f = eval q f) -> p = q.\nProof.\n  destruct p as [p p'].\n  destruct q as [q q'].\n  unfold eval.\n  simpl.\n  intro.\n  apply leibniz.\n  simpl.\n  destruct excluded_middle_poly with (p := p) (q := q).\n  assumption.\n  destruct diff_poly with (p := p) (q := q) (i := 0).\n  assumption.\n  assumption.\n  assumption.\n  destruct H1.\n  contradiction H1 with (n := x0).\n  apply Z.le_refl.\n  apply H with (f := fun (j : nat) => if j =? 0 then x0 else x j).\nQed.\n", "meta": {"author": "TabetSalwa", "repo": "2.7.2-polynomials", "sha": "78bcea3ccdf0b614223266cf867b6954dc704dbf", "save_path": "github-repos/coq/TabetSalwa-2.7.2-polynomials", "path": "github-repos/coq/TabetSalwa-2.7.2-polynomials/2.7.2-polynomials-78bcea3ccdf0b614223266cf867b6954dc704dbf/Values.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7496250956349011}}
{"text": "\nTheorem DeMorgan1 : forall A B, negb (andb A B) = orb (negb A) (negb B).\nProof.\n  intros. destruct A; destruct B; reflexivity. Qed.\n\nTheorem DeMorgan2 : forall A B, negb (orb A B) = andb (negb A) (negb B).\nProof.\n  intros. destruct A; destruct B; reflexivity. Qed.\n\nCheck andb.\nCheck orb.\nPrint DeMorgan1.\n(*DeMorgan1 = \nfun A B : bool =>\nif A as b return (negb (b && B) = (negb b || negb B)%bool)\nthen\n if B as b return (negb (true && b) = (negb true || negb b)%bool)\n then eq_refl\n else eq_refl\nelse\n if B as b return (negb (false && b) = (negb false || negb b)%bool)\n then eq_refl\n else eq_refl\n     : forall A B : bool, negb (A && B) = (negb A || negb B)%bool *)\n\n\n\n\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/class220.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7496250937487208}}
{"text": "\nInductive 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\nEval simpl in (next_weekday friday).\nEval simpl in (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity.  Qed.\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\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\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  negb (andb b1 b2).\n\nExample test_nandb1: (nandb true false) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_nandb2: (nandb false false) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_nandb3: (nandb false true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_nandb4: (nandb true true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  andb b1 (andb b2 b3).\n\nExample test_andb31: (andb3 true true true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_andb32: (andb3 false true true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_andb33: (andb3 true false true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_andb34: (andb3 true true false) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nCheck (negb true).\n\nCheck negb.\n\nModule Playground1.\n  Inductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n  \n  Definition 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.\n\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  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  Eval simpl in (plus (S (S (S O))) (S (S O))).\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  Eval simpl in (minus (S (S (S O))) (S (S O))).\n  Eval simpl in (minus (S (S O)) (S (S (S O)))).\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\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 3) = 6.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nNotation \"x + y\" := (plus  x y) (at level 50, left associativity) : nat_scope.\nNotation \"x - y\" := (minus x y) (at level 50, left associativity) : nat_scope.\nNotation \"x * y\" := (mult  x y) (at level 40, left associativity) : 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) (negb (beq_nat n m)).\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem plus_O_n: forall n:nat, 0 + n = n.\nProof. simpl. reflexivity. Qed.\n\nEval simpl in (forall n:nat, n + 0 = n).\n\nEval simpl in (forall n:nat, 0 + n = n).\n\nTheorem plus_O_n'' : 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\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 :\n  forall n m o:nat, n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o.\n  intros H1 H2.\n  rewrite -> H1.\n  rewrite <- H2.\n  reflexivity.\nQed.\n\nTheorem mult_0_l_plus:\n  forall n m:nat, (0+n)*m = n*m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.\nQed.\n\nTheorem mult_1_plus:\n  forall n m:nat, (1 + n) * m = m + (n * m).\n  intros n m.\n  rewrite -> plus_1_l.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_1_neq_0 :\n  forall n : nat, beq_nat (n + 1) 0 = false.\nProof.\n  intro n.\n  destruct n as [|n'].\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem negb_involutive : \n  forall b : bool, negb (negb b) = b.\nProof.\n  intros b.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1:\n  forall n : nat, beq_nat 0 (n+1) = false.\nProof.\n  intros n.\n  destruct n as [|n'].\n  reflexivity.\n  reflexivity.\nQed.\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\nTheorem andb_true_elim1:\n  forall b c : bool, andb b c = true -> b = true.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n  reflexivity.\n  Case \"b = false\".\n  rewrite <- H.\n  reflexivity.\nQed.\n\nTheorem andb_true_elim2:\n  forall b c : bool, andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct c.\n  Case \"c = true\".\n  reflexivity.\n  Case \"c = false\".\n  rewrite <- H.\n  destruct b.\n  SCase \"b = true\".\n  reflexivity.\n  SCase \"b = false\".\n  reflexivity.\nQed.\n\nTheorem plus_0_r :\n  forall n:nat, n + 0 = n.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem minus_diag :\n  forall n, minus n n = 0.\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 mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [|n'].\n  Case \"n = 0\".\n  reflexivity.\n  Case \"n = S 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. induction n as [|n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite -> IHn'.\n  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'].\n  Case \"n = 0\".\n  simpl.\n  rewrite -> plus_0_r.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite <- plus_n_Sm.\n  rewrite -> IHn'.\n  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 :\n  forall n, double n = n + n .\nProof.\n  intro n.\n  induction n as [|n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite -> IHn'.\n  rewrite -> plus_n_Sm.\n  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'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n  simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem beq_nat_refl :\n  forall n : nat, true = beq_nat n n.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite <- IHn'.\n  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).\n    Case \"Proof of assertion\". 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  Case \"Proof of assertion\".\n  rewrite -> plus_comm. reflexivity.\n  rewrite -> H. 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).\n  Case \"Proof of assertion H1\".\n  rewrite -> plus_assoc.\n  reflexivity.\n  assert (H2: m + (n + p) = (m + n) + p).\n  Case \"Proof of assertion H2\".\n  rewrite -> plus_assoc.\n  reflexivity.\n  assert (H3: n + m = m + n).\n  Case \"Proof of assertion H3\".\n  rewrite -> plus_comm.\n  reflexivity.\n  rewrite -> H1.\n  rewrite -> H2.\n  rewrite -> H3.\n  reflexivity.\nQed.\n\nTheorem mult_comm :\n  forall m n : nat, m * n = n * m.\nProof.\n  assert (mult_n_Sm: forall n m : nat, n + n * m = n * (S m)).\n  intros n m.\n  induction n as [|n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite <- IHn'.\n  rewrite <- plus_swap.\n  reflexivity.\n  intros n m.\n  induction n as [|n'].\n  Case \"n = 0\".\n  simpl.\n  rewrite -> mult_0_r.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite <- mult_n_Sm.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem ble_nat_refl : forall n:nat,\n  true = ble_nat n n.\nProof.\n  intros n.\n  induction n as [|n'].\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  intros b.\n  destruct b as [|b'].\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n  intros n m p H1.\n  induction p as [|p'].\n  simpl.\n  rewrite -> H1.\n  reflexivity.\n  simpl.\n  rewrite -> IHp'.\n  reflexivity.\nQed.\n\nTheorem S_nbeq_0 : forall n:nat,\n  beq_nat (S n) 0 = false.\nProof.\n  intros n.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  intros n.\n  simpl.\n  assert (plus_0_r: forall m : nat, m + 0 = m).\n  induction m as [|m'].\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHm'.\n  reflexivity.\n  rewrite -> plus_0_r.\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 b c.\n  destruct b as [|b'].\n  Case \"b = true\".\n  destruct c as [|c'].\n  SCase \"c = true\".\n  simpl.\n  reflexivity.\n  SCase \"c = false\".\n  simpl.\n  reflexivity.\n  Case \"b = false\".\n  destruct c as [|c'].\n  SCase \"c = true\".\n  simpl.\n  reflexivity.\n  SCase \"c = false\".\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 n as [|n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\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 m p.\n  induction n as [|n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite -> IHn'.\n  rewrite -> mult_plus_distr_r.\n  reflexivity.\nQed.\n\nTheorem plus_swap' :\n  forall n m p : nat, n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  rewrite -> plus_assoc.\n  rewrite -> plus_assoc.\n  replace (m + n) with (n + m).\n  reflexivity.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\n\n(** binary **)\n\nModule Binary.\n\n  Inductive bin : Type :=\n  | Zero  : bin\n  | Twice : bin -> bin\n  | TwicePlusOne : bin -> bin.\n\nFixpoint inc (b:bin) : bin :=\n  match b with\n      | Zero => TwicePlusOne Zero\n      | Twice b' => TwicePlusOne b'\n      | TwicePlusOne b' => Twice (inc b')\n  end.\n\nFixpoint bin_to_nat (b:bin) : nat :=\n  match b with\n      | Zero => O\n      | Twice b' => 2 * (bin_to_nat b')\n      | TwicePlusOne b' => 1 + 2 * (bin_to_nat b')\n  end.\n\nCheck inc. \nEval simpl in (inc Zero).\nEval simpl in (inc (inc Zero)).\nEval simpl in bin_to_nat (inc (inc (inc Zero))).\nEval simpl in (inc (inc (inc (inc Zero)))).\nEval simpl in bin_to_nat (inc (inc (inc (inc Zero)))).\n\nTheorem bin_nat_comm: \n  forall b:bin, bin_to_nat (inc b) = 1 + (bin_to_nat b).\nProof.\n  intros b.\n  induction b as [|b1|b2].\n  Case \"b = Zero\".\n  simpl.\n  reflexivity.\n  Case \"b = Twice b'\".\n  simpl.\n  reflexivity.\n  Case \"b = TwicePlusOne b'\".\n  simpl.\n  rewrite -> plus_0_r.\n  rewrite -> plus_0_r.\n  rewrite -> IHb2.\n  simpl.\n  rewrite <- plus_n_Sm.\n  reflexivity.\nQed.\n\nFixpoint nat_to_bin (n:nat) : bin:=\n  match n with\n    | O => Zero\n    | S n' => inc (nat_to_bin n')\n  end.\n\nEval simpl in (inc Zero).\nEval simpl in nat_to_bin 1.\nEval simpl in (inc (inc Zero)).\nEval simpl in nat_to_bin 2.\nEval simpl in (inc (inc (inc Zero))).\nEval simpl in bin_to_nat (nat_to_bin 3).\n\nTheorem nat_bin_comm:\n  forall n:nat, bin_to_nat (nat_to_bin n) = n.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite -> bin_nat_comm.\n  simpl.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nEnd Binary.", "meta": {"author": "seisyuu-hantatsushi", "repo": "coq-sf", "sha": "9f5088870d6734cebbbe9937f40b89b04ebd206b", "save_path": "github-repos/coq/seisyuu-hantatsushi-coq-sf", "path": "github-repos/coq/seisyuu-hantatsushi-coq-sf/coq-sf-9f5088870d6734cebbbe9937f40b89b04ebd206b/old/Basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.7495433021915594}}
{"text": "From Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nRequire Export Coq.Strings.String.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\n\nExample apply_ex1:forall P Q:Prop,\n(P->Q)->P->Q.\nProof.\n  intros P Q P_imply_Q P_holds.\n  (*apply P_imply_Q in P_holds.*) (* 正向推理 结果为将P_holds变为Q*)\n  apply P_imply_Q.\n  apply P_holds.\nQed.\n\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  apply eq2.  Qed.\n\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\nTheorem trans_eq_2 : forall (X:Type) (n m o p : X),\n  n = m -> m = p -> p = o -> n = o.\nProof.\nAdmitted.\n\nExample trans_eq_example'_2 : forall (a b c d e f h i: nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [e;f] = [h;i] ->\n     [a;b] = [h;i].\nProof.\n  intros a b c d e f h i eq1 eq2 eq3.\n  apply trans_eq_2 with (m:=[c;d]) (p:=[e;f]).\n  apply eq1. apply eq2. apply eq3.\nQed.\n\n(*通过在此处编写injection H\n我们命令Coq使用构造子的单射性来产生所有它能从H所推出的等式\n每一个产生的等式都作为一个前件附加在目标上\n在这个例子中 附加了前件n=m*)\nTheorem S_injective' : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n  injection H. intros Hnm. apply Hnm.\nQed.\n\n(*爆炸原理可能令你费解\n那么请记住上述证明并不肯定其后件\n而是说明:倘若荒谬的前件成立 则会得出荒谬的结论*)\nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. discriminate contra. Qed.\n\n", "meta": {"author": "10ca1h0st", "repo": "SomeThings", "sha": "7e8009783fc2596282dce5ede98e62dcb02fe329", "save_path": "github-repos/coq/10ca1h0st-SomeThings", "path": "github-repos/coq/10ca1h0st-SomeThings/SomeThings-7e8009783fc2596282dce5ede98e62dcb02fe329/apply_injection_discriminate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7495433001362222}}
{"text": "Inductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\nArguments nil {X}.\nArguments cons {X}.\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\nArguments pair {X} {Y}.\nNotation \"( x , y )\" := (pair x y).\nNotation \"X * Y\" := (prod X Y) : type_scope.\nFixpoint even (n:nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | S (S n') => even n'\n  end.\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.\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nFixpoint filter {X:Type} (test: X -> bool) (l:list X) : list X :=\n  match l with\n  | [] => []\n  | h :: t =>\n    if test h then h :: (filter test t)\n    else filter test t\n  end.\n  Fixpoint 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.\nDefinition negb (b : bool) : bool :=\n    match b with \n    | true => false\n    | false => true\n    end.\nDefinition odd (n:nat) : bool :=\n  negb (even n).\n\n(* Given a set X, a predicate of type X → bool and a list X, partition should return a pair of lists. The first member of the pair is the sublist of the original list containing the elements that satisfy the test, and the second is the sublist containing those that fail the test. The order of elements in the two sublists should be the same as their order in the original list. *)\nDefinition partition {X : Type} (test : X -> bool) (l : list X) : list X * list X :=\n    (filter test l, filter (fun n => negb (test n)) l).\n\nExample test_partition1: partition odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\n(* very easy 3 star imo *)", "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/poly/exercises/partition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.749543288146817}}
{"text": "Inductive ev: nat -> Prop :=\n| ev_0: ev 0\n| ev_SS: forall n: nat, ev n -> ev (S (S n)).\n\n(** **** Exercise: 1 star (eight_is_even)  *)\nTheorem ev_8: ev 8.\nProof.\n  apply ev_SS.\n  apply ev_SS.\n  apply ev_SS.\n  apply ev_SS.\n  apply ev_0.\nQed.\n\nPrint ev_8.\n\nDefinition ev_8' : ev 8 := ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0))).\n\n\n(** **** Exercise: 2 stars, optional (conj_fact)  *)\nTheorem test: forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R.\nProof.\n  intros P Q R H1 H2.\n  split.\n  - apply H1.\n  - apply H2.\nQed.\n\nPrint test.  \n\nDefinition conj_fact: forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R := \n  fun (P Q R: Prop)(H1: P /\\ Q)(H2: Q /\\ R) =>\n    conj \n      (let H := match H1 with\n                | conj x _ => x\n                end : P in H)\n      (let H := match H2 with\n                | conj _ x0 => x0\n                end : R in H).", "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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7494935216013376}}
{"text": "(* This file illustrates two approaches to C verification,\n  described in Section III of this paper:\n\n Modular Verification for Computer Security,\n by Andrew W. Appel, in IEEE Computer Security Foundations conference (CSF'16),\n June 2016.\n http://www.cs.princeton.edu/~appel/papers/modsec.pdf\n*)\n\nRequire Import floyd.proofauto.\nRequire Import progs.min.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nRequire Import ZArith.\nRequire Import List.\nImport ListNotations.\nOpen Scope Z.\n\n\nTheorem fold_min_general:\n  forall (al: list Z)(i: Z),\n  In i (al) ->\n  forall x, List.fold_right Z.min x al <= i.\nProof.\ninduction al; intros.\ninversion H.\ndestruct H.\nsubst a.\nsimpl.\napply Z.le_min_l.\nsimpl. rewrite Z.le_min_r.\napply IHal.\napply H.\nQed.\n\nTheorem fold_min:\n  forall (al: list Z)(i: Z),\n  In i (al) ->\n  List.fold_right Z.min (hd 0 al) al <= i.\nProof.\nintros.\napply fold_min_general.\napply H.\nQed.\n\nLemma Forall_fold_min:\n  forall (f: Z -> Prop) (x: Z) (al: list Z),\n    f x -> Forall f al -> f (fold_right Z.min x al).\nProof.\n intros.\n induction H0.\n simpl. auto.\n simpl.\n unfold Z.min at 1.\n destruct (Z.compare x0 (fold_right Z.min x l)) eqn:?; auto.\nQed.\n\nLemma fold_min_another:\n  forall x al y,\n    fold_right Z.min x (al ++ [y]) = Z.min (fold_right Z.min x al) y.\nProof.\n intros.\n revert x; induction al; simpl; intros.\n apply Z.min_comm.\n rewrite <- Z.min_assoc. f_equal.\n apply IHal.\nQed.\n\nLemma is_int_I32_Znth_map_Vint:\n forall i s al v,\n  0 <= i < Zlength al ->\n  is_int I32 s (Znth i (map Vint al) v).\nProof.\nintros. rewrite Znth_map with (d':= Int.zero); auto.\nQed.\nHint Extern 3 (is_int I32 _ (Znth _ (map Vint _) _)) =>\n  (apply  is_int_I32_Znth_map_Vint; rewrite ?Zlength_map; omega).\n\nDefinition minimum_spec :=\n DECLARE _minimum\n  WITH a: val, n: Z, al: list Z\n  PRE [ _a OF tptr tint , _n OF tint ]\n    PROP  (1 <= n <= Int.max_signed; Forall repable_signed al)\n    LOCAL (temp _a a; temp _n (Vint (Int.repr n)))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)\n  POST [ tint ]\n    PROP ()\n    LOCAL(temp ret_temp  (Vint (Int.repr (fold_right Z.min (hd 0 al) al))))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a).\n\nDefinition Gprog : funspecs :=\n      ltac:(with_library prog [minimum_spec]).\n\n(* First approach from \"Modular Verification for Computer Security\",\n  proved using forward_for_simple_bound *)\nLemma body_min: semax_body Vprog Gprog f_minimum minimum_spec.\nProof.\nstart_function.\nassert_PROP (Zlength al = n). {\n  entailer!. autorewrite with sublist; auto.\n}\nrevert POSTCONDITION;\n replace (hd 0 al) with (Znth 0 al 0) by (destruct al; reflexivity);\n intro POSTCONDITION.\nforward.  (* min = a[0]; *)\nautorewrite with sublist.\nforward_for_simple_bound n\n  (EX i:Z,\n    PROP()\n    LOCAL(temp _min (Vint (Int.repr (fold_right Z.min (Znth 0 al 0) (sublist 0 i al))));\n          temp _a a;\n          temp _n (Vint (Int.repr n)))\n    SEP(data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)).\n* (* Prove that the precondition implies the loop invariant *)\n entailer!.\n*\n forward. (* j = a[i]; *)\n assert (repable_signed (Znth i al 0))\n     by (apply Forall_Znth; auto; omega).\n assert (repable_signed (fold_right Z.min (Znth 0 al 0) (sublist 0 i al)))\n   by (apply Forall_fold_min;\n          [apply Forall_Znth; auto; omega\n          |apply Forall_sublist; auto]).\n autorewrite with sublist.\n subst POSTCONDITION; unfold abbreviate.\n rewrite (sublist_split 0 i (i+1)) by omega.\n rewrite (sublist_one i (i+1) al 0) by omega.\n rewrite fold_min_another.\n forward_if.\n +\n forward. (* min = j; *)\n entailer!. rewrite Z.min_r; auto; omega.\n +\n forward. (* skip; *)\n entailer!. rewrite Z.min_l; auto; omega.\n*\n forward. (* return *)\n entailer!.\n autorewrite with sublist. auto.\nQed.\n\n(* Demonstration of the same theorem, but using\n    forward_for  instead of forward_for_simple_bound *)\nLemma body_min': semax_body Vprog Gprog f_minimum minimum_spec.\nProof.\nstart_function.\nassert_PROP (Zlength al = n). {\n  entailer!. autorewrite with sublist; auto.\n}\nrevert POSTCONDITION;\n replace (hd 0 al) with (Znth 0 al 0) by (destruct al; reflexivity);\n intro POSTCONDITION.\nforward.  (* min = a[0]; *)\npose (Inv d (f: Z->Prop) (i: Z) :=\n    PROP(0 <= i <= n; f i)\n    LOCAL(temp _min (Vint (Int.repr (fold_right Z.min (Znth 0 al 0) (sublist 0 (i+d) al))));\n          temp _a a; temp _i (Vint (Int.repr i));\n          temp _n (Vint (Int.repr n)))\n    SEP(data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)).\nforward_for (Inv 0 (fun _ => True)) (Inv 1 (Z.gt n)).\n*\nforward.\nExists 0. unfold Inv; entailer!.\n*\nentailer!.\n*\nrename a0 into i.\n forward. (* j = a[i]; *)\n assert (repable_signed (Znth i al 0))\n     by (apply Forall_Znth; auto; omega).\n assert (repable_signed (fold_right Z.min (Znth 0 al 0) (sublist 0 i al)))\n   by (apply Forall_fold_min;\n          [apply Forall_Znth; auto; omega\n          |apply Forall_sublist; auto]).\n autorewrite with sublist.\n apply semax_post_flipped with  (normal_ret_assert (Inv 1 (Z.gt n) i)).\n unfold Inv.\n rewrite (sublist_split 0 i (i+1)) by omega.\n rewrite (sublist_one i (i+1) al 0) by omega.\n rewrite fold_min_another.\n forward_if.\n +\n forward. (* min = j; *)\n entailer!. rewrite Z.min_r; auto; omega.\n +\n forward. (* skip; *)\n entailer!. rewrite Z.min_l; auto; omega.\n +\n intros.\n subst POSTCONDITION; unfold abbreviate. (* TODO: some of these lines should all be done by forward_if *)\n unfold normal_ret_assert. normalize. autorewrite with ret_assert.\n (* TODO: entailer! fails here with a misleading error message *)\n Exists i. apply andp_left2. normalize.\n*\n rename a0 into i.\n forward.\n Exists (i+1).\n entailer!.\n*\n autorewrite with sublist.\n forward.\nQed.\n\nDefinition minimum_spec2 :=\n DECLARE _minimum\n  WITH a: val, n: Z, al: list Z\n  PRE [ _a OF tptr tint , _n OF tint ]\n    PROP  (1 <= n <= Int.max_signed; Forall repable_signed al)\n    LOCAL (temp _a a; temp _n (Vint (Int.repr n)))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)\n  POST [ tint ]\n   EX j: Z,\n    PROP (In j al; Forall (fun x => j<=x) al)\n    LOCAL(temp ret_temp  (Vint (Int.repr j)))\n    SEP   (data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a).\n\n\n(* Second approach from \"Modular Verification for Computer Security\",\n  proved using forward_for_simple_bound *)\nLemma body_min2: semax_body Vprog Gprog f_minimum minimum_spec2.\nProof.\nstart_function.\nassert_PROP (Zlength al = n). {\n  entailer!. autorewrite with sublist; auto.\n}\nforward.  (* min = a[0]; *)\nautorewrite with sublist.\nforward_for_simple_bound n\n  (EX i:Z, EX j:Z,\n    PROP(\n         In j (sublist 0 (Z.max 1 i) al);\n         Forall (Z.le j) (sublist 0 i al))\n    LOCAL(\n          temp _min (Vint (Int.repr j));\n          temp _a a;\n          temp _n (Vint (Int.repr n)))\n    SEP(data_at Ews (tarray tint n) (map Vint (map Int.repr al)) a)).\n* (* Show that the precondition entails the loop invariant *)\nExists (Znth 0 al 0).\nautorewrite with sublist.\nentailer!.\nrewrite sublist_one with (d:=0) by omega.\nconstructor; auto.\n* (* Show that the loop body preserves the loop invariant *)\nIntros.\nforward. (* j = a[i]; *)\nassert (repable_signed (Znth i al 0))\n   by (apply Forall_Znth; auto; omega).\nautorewrite with sublist in *.\nassert (repable_signed x)\n   by (eapply Forall_forall; [ | eassumption]; apply Forall_sublist; auto).\nforward_if.\n + (* Then clause *)\n forward. (* min = j; *)\n Exists (Znth i al 0).\n entailer!.\n rewrite Z.max_r by omega.\n rewrite (sublist_split 0 i (i+1)) by omega.\n rewrite (sublist_one i (i+1) al 0) by omega.\n split.\n apply in_app; right; constructor; auto.\n apply Forall_app; split.\n eapply Forall_impl; try apply H4.\n intros; omega.\n constructor; auto. omega.\n + (* Else clause *)\n forward. (* skip; *)\n Exists x.\n autorewrite with sublist.\n entailer!.\n split.\n destruct (zlt 1 i).\n rewrite Z.max_r in H3 by omega.\n rewrite (sublist_split 0 i (i+1)) by omega.\n apply in_app; left; auto.\n rewrite Z.max_l in H3 by omega.\n rewrite (sublist_split 0 1 (i+1)) by omega.\n apply in_app; left; auto.\n rewrite (sublist_split 0 i (i+1)) by omega.\n apply Forall_app. split; auto.\n rewrite (sublist_one _ _ _ 0) by omega.\n repeat constructor. omega.\n* (* After the loop *)\n Intros x.\n autorewrite with sublist in *.\n forward. (* return *)\n Exists x.\n entailer!.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/progs/verif_min.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7494935148838241}}
{"text": "Require Export ssreflect.\n\nAxiom ExcludedMiddle :\n  forall P, P \\/ ~ P.\n\nTheorem DoubleNegative (P : Prop) :\n  ~~ P <-> P.\nProof.\n  split.\n  + intro notP.\n    case (ExcludedMiddle P) as [p  | notp].\n  - apply p.\n  - case (notP notp).\n    + intros p notp.\n      apply (notp p).\nQed.\n\nTheorem DeMorgan_notand (A B : Prop) :\n  ~ (A /\\ B) <-> ~ A \\/ ~ B.\nProof.\n  split => [H | H].\n  + case (ExcludedMiddle A) as [a | nota].\n  - apply or_intror.\n    intro b.\n    apply (H (conj a b)).\n  - apply (or_introl nota).\n    + intro ab.\n      induction ab as [a b].\n      induction H as [nota | notb].\n  - apply (nota a).\n  - apply (notb b).\nQed.\n\nTheorem DeMorgan_notor (A B : Prop) :\n  ~ (A \\/ B) <-> ~ A /\\ ~ B.\nProof.\n  split => [H | H].\n  + split.\n  - intro a.\n    apply (H (or_introl a)).\n  - intro b.\n    apply (H (or_intror b)).\n    + induction H as [nota notb].\n      intro ab.\n      induction ab as [a | b].\n  - apply (nota a).\n  - apply (notb b).\nQed.\n\nTheorem contrapositive (A B : Prop) :\n  (A -> B) <-> (~ B -> ~ A).\nProof.\n  split => [H | H].\n  + intros notb a.\n    apply (notb (H a)).\n  + intro a.\n    apply DoubleNegative.\n    intro notb.\n    apply ((H notb) a).\nQed.\n\nTheorem notall_existsnot (X : Type) (P : X -> Prop) :\n  ~ (forall x, P x) <-> exists x, ~ P x.\nProof.\n  split.\n  + apply contrapositive.\n    intros H.\n    apply DoubleNegative.\n    intro x.\n    case (ExcludedMiddle (P x)) as [Px | notPx ].\n  - done.\n  - assert (Px : exists x, ~ P x).\n    * exists x.\n      apply notPx.\n    * case (H Px).\n    + intros H allPx.\n      induction H as [x notPx].\n      specialize (allPx x) as Px.\n      apply (notPx Px).\nQed.\n\n\nTheorem allnot_notexists (X : Type) (P : X  -> Prop) :\n  (forall x, ~ P x) <->  ~ exists x, P x.\nProof.\n  split.\n  + apply contrapositive.\n    intro H.\n    apply (DoubleNegative (exists x, P x)) in H.\n    apply (notall_existsnot X (fun x => ~ P x)).\n    induction H as [x Px].\n    exists x.\n      by apply DoubleNegative.\n  + intros H x Px.\n    apply H.\n    exists x.\n    apply Px.\nQed.\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "sets", "sha": "4db587e90349f1c8786dae9ffd14f56535512e07", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-sets", "path": "github-repos/coq/gaxiiiiiiiiiiii-sets/sets-4db587e90349f1c8786dae9ffd14f56535512e07/Logics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7494935145511856}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := mult (Succ y) (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj103_coqofml_EXO92A.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8128673155708976, "lm_q1q2_score": 0.7494001322961813}}
{"text": "Require Import ZArith.\nDefinition szam (k:Z):Z:=\n  k.\n\n\nPrint Z.\n\n\nEval compute in szam (Zneg 10).\n\nInductive Z_btree : Set :=\n  | leaf : Z -> Z_btree\n  | bnode : Z -> Z_btree-> Z_btree -> Z_btree.\n\nEval compute in szam 0.\n\n\n\nType (leaf 0).\n\nFixpoint vannulla(t:Z_btree):bool:=\n  match t with\n  | leaf 0=> true\n  | leaf _=> false\n  | bnode 0 t1 t2 => true\n  | bnode _ t3 t4 => orb(vannulla(t3))(vannulla(t4))\n  end.\n\nRequire Import BinPos BinInt Decidable Zcompare.\nRequire Import Arith_base.\nLocal Open Scope Z_scope.\nNotation dec_eq := Z.eq_decidable (only parsing).\nNotation dec_Zle := Z.le_decidable (only parsing).\nNotation dec_Zlt := Z.lt_decidable (only parsing).\n\nPrint Z.eqb.\n\nEval compute in Z.eqb (0)(0).\n\n\n\n\nEval compute in vannulla(bnode (-1) (leaf 10)(leaf (0))). \n\nFixpoint vanbennek(t:Z_btree)(k:Z):bool:=\n  match t with\n  | leaf m=> Z.eqb(k)(m)\n  | bnode u t1 t2 => match Z.eqb(k)(u) with\n                       | true => true\n                       | false => orb(vanbennek(t1)(k))(vanbennek(t2)(k))\n                        end\n  end.\n\n\nEval compute in vanbennek(bnode (-1) (leaf 10)(leaf (0)))(10). \n", "meta": {"author": "mozow01", "repo": "bizcoq2021", "sha": "f98f22ba3ce80899bc88605ce3193d8972102c92", "save_path": "github-repos/coq/mozow01-bizcoq2021", "path": "github-repos/coq/mozow01-bizcoq2021/bizcoq2021-f98f22ba3ce80899bc88605ce3193d8972102c92/hallgatoi/molnarbarna/ZH_8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7494001179999732}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool ssrnat eqtype seq choice fintype path bigop.\n\nRequire Import ord fset.\n\n(******************************************************************************)\n(*   This file defines a type {fmap T -> S} of partial functions with finite  *)\n(* domain from T to S, where T is assumed to have an ordType structure.       *)\n(* Throughtout this development, we refer to such functions as (finite) maps. *)\n(* The type {fmap T -> S} is defined as a list of pairs (k, v) : T * S that   *)\n(* is kept ordered by its keys.  This implies that the type supports          *)\n(* extensional equality, as shown by the lemma eq_fmap.                       *)\n(*                                                                            *)\n(*       getm m k == the value of the map f associated with the key k. getm   *)\n(*                   is declared as a coercion into Funclass, allowing us to  *)\n(*                   simply write m k instead.                                *)\n(*     setm m k v == set the value of k in m to v, replacing any previous     *)\n(*                   value.                                                   *)\n(*     updm m k v == a partial version of setm, that only replaces the value  *)\n(*                   of k if it is already present in m, and returns None     *)\n(*                   otherwise.                                               *)\n(*      mapim f m == apply the function f : T -> S -> S' to all bindings in   *)\n(*                   the map m : {fmap T -> S}.                               *)\n(*       mapm f m == specialized version of mapim that ignores the key value. *)\n(*   unionm m1 m2 == a map containing all the bindings of m1 and m2.  If a    *)\n(*                   key is present in both of them, the value of m1 is used. *)\n(*    filterm a m == given a predicate a : T -> S -> bool, remove from m all  *)\n(*                   bindings (k, v) such that a k v is false.                *)\n(*       remm m k == remove the value of k in m, if there is one.             *)\n(*         domm m == the domain of m: the set of keys associated with some    *)\n(*                   value in m.                                              *)\n(*       codomm m == the codomain of m: the set of values associated with     *)\n(*                   key in m.  This requires an ordType structure on the     *)\n(*                   type of values.                                          *)\n(*   injectivem m == the map m is injective on its domain (the type of        *)\n(*                   values must be an eqType).                               *)\n(*         invm m == the inverse of m.  If multiple keys of m are mapped to   *)\n(*                   the same value, only one of the bindings is used.        *)\n(*  fmap_of_seq s == convert s : seq T into a map {fmap nat -> T} that        *)\n(*                   indexes into s.                                          *)\n(*       currym m == convert from {fmap T * S -> R} to                        *)\n(*                   {fmap T -> {fmap S -> R}}.                               *)\n(*     uncurrym m == the left inverse of the previous function.               *)\n(* enum_fmap s s' == sequence of all maps whose domain and codomain are       *)\n(*                   contained in the sequences s and s'.                     *)\n(*                                                                            *)\n(*   The behavior of many of these functions is described by lemmas such as   *)\n(* setmE, unionmE, etc.  For example, setmE says that setm m k v k' is equal  *)\n(* to if k' == k then Some v else m k'.  Maps coerce to predicates:           *)\n(* (k, v) \\in m means that m k = Some v (cf. getmP).                          *)\n(*                                                                            *)\n(*   We provide the following map constructors:                               *)\n(*                                                                            *)\n(*         emptym == the empty map.                                           *)\n(*     mkfmap kvs == construct a map from kvs : seq (T * S).  If multiple     *)\n(*                   bindings are present in kvs for a given key k : T, the   *)\n(*                   first one is used.                                       *)\n(*   mkfmapf f ks == construct a map that associates to each element k of     *)\n(*                   the sequence ks the value f k, mapping all other keys to *)\n(*                   None.                                                    *)\n(*  mkfmapfp f ks == same as above but for a partial function                 *)\n(*                   f : T -> option S.                                       *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule FMap.\n\nSection Def.\n\nVariables (T : ordType) (S : Type).\n\nLocal Open Scope ord_scope.\n\nRecord fmap_type := FMap {\n  fmval : seq (T * S);\n  _ : sorted (@Ord.lt T) (unzip1 fmval)\n}.\n\nDefinition fmap_of & phant (T -> S) := fmap_type.\n\nEnd Def.\n\nModule Exports.\n\nIdentity Coercion fmap_of_fmap : fmap_of >-> fmap_type.\nNotation \"{ 'fmap' T }\" := (@fmap_of _ _ (Phant T))\n  (at level 0, format \"{ 'fmap'  T }\") : type_scope.\n\nSection WithOrdType.\n\nVariable T : ordType.\n\nCoercion fmval : fmap_type >-> seq.\nCanonical fmap_subType S := [subType for @fmval T S].\nDefinition fmap_eqMixin (S : eqType) :=\n  [eqMixin of fmap_type T S by <:].\nCanonical fmap_eqType (S : eqType) :=\n  Eval hnf in EqType (fmap_type T S) (fmap_eqMixin S).\nDefinition fmap_choiceMixin (S : choiceType) :=\n  [choiceMixin of fmap_type T S by <:].\nCanonical fmap_choiceType (S : choiceType) :=\n  Eval hnf in ChoiceType (fmap_type T S) (fmap_choiceMixin S).\nDefinition fmap_ordMixin (S : ordType) :=\n  [ordMixin of fmap_type T S by <:].\nCanonical fmap_ordType (S : ordType) :=\n  Eval hnf in OrdType (fmap_type T S) (fmap_ordMixin S).\n\nCanonical fmap_of_subType (S : Type) :=\n  Eval hnf in [subType of {fmap T -> S}].\nCanonical fmap_of_eqType (S : eqType) :=\n  Eval hnf in [eqType of {fmap T -> S}].\nCanonical fmap_of_choiceType (S : choiceType) :=\n  Eval hnf in [choiceType of {fmap T -> S}].\nCanonical fmap_of_ordType (S : ordType) :=\n  Eval hnf in [ordType of {fmap T -> S}].\n\n(*\n\nStill need to rethink the interface hierarchy to allow this...\n\nDefinition fmap_countMixin T (S : countType) :=\n  [countMixin of type T S by <:].\nCanonical fmap_countType T (S : countType) :=\n  Eval hnf in CountType (type T S) (fmap_countMixin T S).\nCanonical fmap_subCountType T (S : countType) :=\n  [subCountType of type T S].\n*)\n\nEnd WithOrdType.\n\nEnd Exports.\n\nEnd FMap.\n\nExport FMap.Exports.\n\n(* Redefine the fmap constructor with a different signature, in\norder to keep types consistent. *)\nDefinition fmap (T : ordType) S s Ps : {fmap T -> S} :=\n  @FMap.FMap T S s Ps.\n\nSection Operations.\n\nVariables (T : ordType) (S : Type).\n\nImplicit Type m : {fmap T -> S}.\nImplicit Type k : T.\n\nLocal Open Scope ord_scope.\n\nFixpoint getm_def s k : option S :=\n  if s is p :: s then\n    if k == p.1 then Some p.2\n    else getm_def s k\n  else None.\n\nDefinition getm (m : FMap.fmap_type T S) k := getm_def m k.\n\nFixpoint setm_def s k v : seq (T * S) :=\n  if s is p :: s' then\n    if k < p.1 then (k, v) :: s\n    else if k == p.1 then (k, v) :: s'\n    else p :: setm_def s' k v\n  else [:: (k, v)].\n\nLemma setm_subproof m k v : sorted (@Ord.lt T) (unzip1 (setm_def m k v)).\nProof.\nhave E: forall s, [seq p.1 | p <- setm_def s k v] =i k :: unzip1 s.\n  elim=> // p s /= IH k'; rewrite ![in X in X = _]fun_if /= !inE.\n  rewrite IH inE.\n  case: (Ord.ltgtP k p.1) => // H; try by bool_congr.\n  by rewrite H orbA orbb.\ncase: m; elim=> // p s /= IH Ps.\nmove: (order_path_min (@Ord.lt_trans T) Ps) => lb.\nrewrite ![in X in is_true X]fun_if /= path_min_sorted; last exact: lb.\nrewrite (path_sorted Ps); case: Ord.ltgtP=> [k_p//|k_p|-> //] /=.\nrewrite path_min_sorted ?(IH (path_sorted Ps)) //=.\nby rewrite !(eq_all_r (E s)) {E} /= lb andbT.\nQed.\n\nDefinition setm (m : {fmap T -> S}) k v :=\n  fmap (setm_subproof m k v).\n\nDefinition repm (m : {fmap T -> S}) k f : option {fmap T -> S} :=\n  omap (setm m k \\o f) (getm m k).\n\nDefinition updm (m : {fmap T -> S}) k v :=\n  if getm m k then Some (setm m k v) else None.\n\nDefinition unionm (m1 m2 : {fmap T -> S}) :=\n  foldr (fun p m => setm m p.1 p.2) m2 m1.\n\nLemma mapim_subproof S' (f : T -> S -> S') m :\n  sorted (@Ord.lt T) (unzip1 (map (fun p => (p.1, f p.1 p.2)) m)).\nProof. by rewrite /unzip1 -!map_comp; apply: (valP m). Qed.\n\nDefinition mapim S' (f : T -> S -> S') m := fmap (mapim_subproof f m).\n\nDefinition mapm S' (f : S -> S') := mapim (fun _ x => f x).\n\nLemma filterm_subproof (a : T -> S -> bool) m :\n  sorted (@Ord.lt T) (unzip1 [seq p | p <- m & a p.1 p.2]).\nProof.\nrewrite (subseq_sorted _ _ (valP m)) //; first exact: Ord.lt_trans.\nrewrite /=; elim: {m} (FMap.fmval m) => // p s IH.\nrewrite (lock subseq) /=; case: (a _); rewrite /= -lock.\n  by rewrite /= eqxx.\nby rewrite (subseq_trans IH) // subseq_cons.\nQed.\n\nDefinition filterm (a : T -> S -> bool) (m : {fmap T -> S}) :=\n  fmap (filterm_subproof a m).\n\nFixpoint remm_def (s : seq (T * S)) k :=\n  if s is p :: s then\n    if p.1 == k then s else p :: remm_def s k\n  else [::].\n\nLemma remm_subproof m k : sorted (@Ord.lt T) (unzip1 (remm_def m k)).\nProof.\napply/(subseq_sorted _ _ (valP m)); first exact: Ord.lt_trans.\nrewrite /=; elim: {m} (FMap.fmval m) => // p s IH.\nrewrite (lock subseq) /=; case: (_ == _); rewrite /= -lock.\n  by rewrite subseq_cons.\nby rewrite /= eqxx.\nQed.\n\nDefinition remm m k :=\n  fmap (remm_subproof m k).\n\nDefinition emptym : {fmap T -> S} :=\n  @fmap T S [::] erefl.\n\nDefinition mkfmap (kvs : seq (T * S)) : {fmap T -> S} :=\n  foldr (fun kv m => setm m kv.1 kv.2) emptym kvs.\n\nDefinition mkfmapf (f : T -> S) (ks : seq T) : {fmap T -> S} :=\n  mkfmap [seq (k, f k) | k <- ks].\n\nDefinition mkfmapfp (f : T -> option S) (ks : seq T) : {fmap T -> S} :=\n  mkfmap (pmap (fun k => omap (pair k) (f k)) ks).\n\nDefinition domm m := fset (unzip1 m).\n\nEnd Operations.\n\nCoercion getm : FMap.fmap_type >-> Funclass.\n\nArguments getm {_ _} _ _.\nArguments setm {_ _} _ _.\nArguments repm {_ _} _ _ _.\nArguments updm {_ _} _ _ _.\nArguments unionm {_ _} _ _.\nArguments mapim {_ _ _} _ _.\nArguments mapm {_ _ _} _ _.\nArguments filterm {_ _} _ _.\nArguments remm {_ _} _ _.\nArguments emptym {_ _}.\nArguments mkfmap {_ _} _.\nArguments mkfmapf {_ _} _ _.\nArguments mkfmapfp {_ _} _ _.\nArguments domm {_ _} _.\n\nNotation \"[ 'fmap' kv1 ; .. ; kvn ]\" :=\n  (mkfmap (cons kv1 .. (cons kvn nil) ..))\n  (at level 0, format \"[ 'fmap'  '[' kv1 ; '/' .. ; '/' kvn ']' ]\")\n  : form_scope.\n\nSection PredFmap.\n\nVariables (T : ordType) (S : eqType).\n\nDefinition mem_fmap (m : {fmap T -> S}) :=\n  [pred p : T * S | p \\in val m].\n\nCanonical mem_fmap_predType := PredType mem_fmap.\n\nEnd PredFmap.\n\nSection Properties.\n\nVariables (T : ordType) (S : Type).\nLocal Open Scope ord_scope.\nLocal Open Scope fset_scope.\n\nImplicit Type (m : {fmap T -> S}) (k : T) (v : S).\n\nLemma eq_fmap m1 m2 : m1 =1 m2 <-> m1 = m2.\nProof.\nsplit; last congruence.\nhave in_seq: forall s : seq (T * S), [pred k | getm_def s k] =i [seq p.1 | p <- s].\n  elim=> [|p s IH] k; rewrite /= !inE // -IH inE.\n  by case: (k == p.1).\ncase: m1 m2 => [s1 Ps1] [s2 Ps2]; rewrite /getm /= => s1_s2.\napply: val_inj=> /=.\nelim: s1 Ps1 s2 Ps2 s1_s2\n      => [_|[k1 v1] s1 IH /= Ps1] [_|[k2 v2] s2 /= Ps2] //\n      => [/(_ k2)|/(_ k1)| ]; try by rewrite eqxx.\nhave lb1 := order_path_min (@Ord.lt_trans _) Ps1.\nhave lb2 := order_path_min (@Ord.lt_trans _) Ps2.\nmove: {Ps1 Ps2} (path_sorted Ps2) (path_sorted Ps1) => Ps1 Ps2.\nmove: IH => /(_ Ps2 _ Ps1) {Ps1 Ps2} IH s1_s2.\nwlog: k1 k2 v1 v2 s1 s2 lb1 lb2 s1_s2 IH / k1 <= k2.\n  move=> H.\n  have [|k2_k1] := orP (Ord.leq_total k1 k2); first by eauto.\n  symmetry; apply: H; eauto.\n    by move=> k /=; rewrite s1_s2.\n  by move=> H'; rewrite IH //.\nrewrite Ord.leq_eqVlt=> /orP [/eqP k1_k2|k1_k2].\n  rewrite -{}k1_k2 {k2} in lb2 s1_s2 *.\n  move: (s1_s2 k1); rewrite eqxx=> - [->].\n  rewrite {}IH // => k; move: {s1_s2} (s1_s2 k).\n  have [-> {k} _|ne ?] // := altP (_ =P _).\n  move: (in_seq s1 k1) (in_seq s2 k1); rewrite !inE.\n  case: (getm_def s1 k1) (getm_def s2 k1) => [v1'|] [v2'|] //=.\n  - by move=> _ /esym/(allP lb2) /=; rewrite Ord.ltxx.\n  - by move=> /esym/(allP lb1) /=; rewrite Ord.ltxx.\n  by move=> _ /esym/(allP lb2) /=; rewrite Ord.ltxx.\nmove/(_ k1)/esym: s1_s2 k1_k2; rewrite eqxx.\nhave [->|_ s1_s2] := altP (_ =P _); first by rewrite Ord.ltxx.\nmove/(_ s2 k1): in_seq; rewrite inE {}s1_s2 /= => /esym/(allP lb2)/Ord.ltW /=.\nby rewrite Ord.ltNge => ->.\nQed.\n\nLemma mem_domm m k : k \\in domm m = m k.\nProof.\nrewrite inE /domm /= in_fset.\ncase: m => [s Ps] /=; rewrite /getm /=.\nby elim: s {Ps} => [|p s IH] //=; rewrite inE IH; case: (k == p.1).\nQed.\n\nLemma dommP m k : reflect (exists v, m k = Some v) (k \\in domm m).\nProof.\nby rewrite mem_domm; case: (m k) => /=; constructor; eauto; case.\nQed.\n\nLemma dommPn m k : reflect (m k = None) (k \\notin domm m).\nProof.\nby rewrite mem_domm; case: (m k)=> /=; constructor.\nQed.\n\nArguments dommP {_ _}.\nArguments dommPn {_ _}.\n\nLemma setmE m k v k' :\n  setm m k v k' =\n  if k' == k then Some v else getm m k'.\nProof.\ncase: m; rewrite /getm /setm /=; elim=> //= p s IH Ps.\nrewrite ![in LHS](fun_if, if_arg) /= {}IH; last exact: path_sorted Ps.\nhave [->{k'}|Hne] := altP (k' =P k); case: (Ord.ltgtP k) => //.\nby move=> <-; rewrite (negbTE Hne).\nQed.\n\nLemma setmC m k v k' v' : k != k' ->\n  setm (setm m k v) k' v' = setm (setm m k' v') k v.\nProof.\nmove=> ne; apply/eq_fmap=> k''; rewrite !setmE.\nhave [->{k''}|//] := altP (k'' =P k').\nby rewrite eq_sym (negbTE ne).\nQed.\n\nLemma setmxx m k v v' : setm (setm m k v) k v' = setm m k v'.\nProof. by apply/eq_fmap=> k'; rewrite !setmE; case: eqP. Qed.\n\nLemma repmE m m' k f :\n  repm m k f = Some m' ->\n  forall k', m' k' = if k' == k then omap f (m k) else getm m k'.\nProof.\nby rewrite /repm; case: (m k) => [v [<-]|] //= k'; rewrite setmE.\nQed.\n\nLemma updm_set m m' k v :\n  updm m k v = Some m' -> m' = setm m k v.\nProof. by rewrite /updm; case: (getm m _) => [m''|] //= [<-]. Qed.\n\nLemma unionmE m1 m2 k : unionm m1 m2 k = if m1 k then m1 k else m2 k.\nProof.\ncase: m1 => [m1 Pm1]; rewrite /unionm {2 3}/getm /= {Pm1}.\nelim: m1 => [|p m1 IH] //=.\nby rewrite setmE {}IH; case: (_ == _).\nQed.\n\nLemma domm_union m1 m2 : domm (unionm m1 m2) = domm m1 :|: domm m2.\nProof.\nby apply/eq_fset=> k; rewrite in_fsetU !mem_domm unionmE; case: (m1 k).\nQed.\n\nLemma domm_set m k v : domm (setm m k v) = k |: domm m.\nProof.\napply/eq_fset=> k'; apply/(sameP dommP)/(iffP idP);\nrewrite setmE in_fsetU1.\n  case/orP=> [->|]; first by eauto.\n  by move=> /dommP [v' ->]; case: eq_op; eauto.\nby have [-> //|] := altP eqP => _ /= [v']; rewrite mem_domm => ->.\nQed.\n\nLemma emptymE k : @emptym T S k = None.\nProof. by []. Qed.\n\nLemma domm0 : domm (@emptym T S) = fset0.\nProof.\nby apply/eq_fset=> k; rewrite mem_domm.\nQed.\n\nLemma emptymP m : reflect (m = emptym) (domm m == fset0).\nProof.\napply/(iffP eqP); last by move=> ->; rewrite domm0.\nby move=> e; apply/eq_fmap => x; apply/dommPn; rewrite e.\nQed.\n\nLemma mapimE S' (f : T -> S -> S') m k : mapim f m k = omap (f k) (m k).\nProof.\ncase: m=> [s Ps]; rewrite /mapim /getm /=.\nelim: s {Ps}=> [|[k' v] s IH] //=; rewrite {}IH ![in RHS]fun_if /=.\nby case: (k =P k') => [<-|].\nQed.\n\nLemma mapmE S' (f : S -> S') m k : mapm f m k = omap f (m k).\nProof. exact: mapimE. Qed.\n\nLemma filtermE a m k :\n  filterm a m k = obind (fun x => if a k x then Some x else None) (m k).\nProof.\ncase: m=> [s Ps]; rewrite /filterm /getm /=.\nelim: s Ps=> [|p s IH /= Ps] //=.\nrewrite ![in LHS](fun_if, if_arg) /= {}IH; last exact: path_sorted Ps.\nhave [-> {k}|k_p] //= := altP (_ =P _); case: (a _)=> //.\nelim: s {Ps} (order_path_min (@Ord.lt_trans _) Ps)\n      => [|p' s IH /andP /= [lb {}/IH IH]] //=.\nby move: lb; have [->|//] := altP (_ =P _); rewrite Ord.ltxx.\nQed.\n\nLemma filterm0 (a : T -> S -> bool) : filterm a emptym = emptym.\nProof. by apply/eq_fmap=> x; rewrite filtermE. Qed.\n\nLemma remmE m k k' :\n  remm m k k' =\n  if k' == k then None else getm m k'.\nProof.\ncase: m; rewrite /remm /getm /=; elim=> [|p s IH /= Ps] //=.\n  by case: (_ == _).\nrewrite ![in LHS](fun_if, if_arg) /= {}IH //; last exact: path_sorted Ps.\nmove: {Ps} (order_path_min (@Ord.lt_trans _) Ps).\nhave [-> lb|ne lb] := altP (_ =P _).\n  have [-> {k' p}|ne //] := altP (_ =P _).\n  elim: s lb=> [|p s IH /= /andP [lb /IH {IH} ->]] //=.\n  by move: lb; have [->|//] := altP (_ =P _); rewrite Ord.ltxx.\nhave [-> {k'}|ne'] // := altP (k' =P k).\nby rewrite eq_sym (negbTE ne).\nQed.\n\nLemma remmI m k : k \\notin domm m -> remm m k = m.\nProof.\nmove=> /dommPn m_k; apply/eq_fmap=> k'; rewrite remmE.\nby case: eqP=> // ->; rewrite m_k.\nQed.\n\nLemma setm_rem m k v : setm (remm m k) k v = setm m k v.\nProof.\napply/eq_fmap=> k'; rewrite !setmE !remmE; by case: eqP.\nQed.\n\nLemma filterm_set (a : T -> S -> bool) m x y :\n  filterm a (setm m x y) =\n  if a x y then setm (filterm a m) x y\n  else remm (filterm a m) x.\nProof.\napply/eq_fmap=> x'; have [yes|no] := boolP (a x y).\n  by rewrite !(setmE, filtermE); case: eqP=> //= ->; rewrite yes.\nby rewrite remmE !filtermE setmE; case: eqP no=> //= -> /negbTE ->.\nQed.\n\nLemma domm_rem m k : domm (remm m k) = domm m :\\ k.\nProof.\nby apply/eq_fset=> k'; rewrite in_fsetD1 !mem_domm remmE; case: eqP.\nQed.\n\nLemma domm_mkfmap (kvs : seq (T * S)) : domm (mkfmap kvs) =i unzip1 kvs.\nProof.\nmove=> k; rewrite mem_domm.\nelim: kvs => [|kv kvs IH] //=; rewrite !inE setmE -{}IH.\nby case: (_ == _).\nQed.\n\n(* TODO rename this *)\nLemma domm_mkfmap' (kvs : seq (T * S)) :\n  domm (mkfmap kvs) = fset (unzip1 kvs).\nProof. by apply/eq_fset=> x; rewrite domm_mkfmap in_fset. Qed.\n\nLemma mkfmapE (kvs : seq (T * S)) : mkfmap kvs =1 getm_def kvs.\nProof.\nby move=> k; elim: kvs=> [|p kvs IH] //=; rewrite setmE IH.\nQed.\n\nLemma mkfmapfE (f : T -> S) (ks : seq T) k :\n  mkfmapf f ks k = if k \\in ks then Some (f k) else None.\nProof.\nrewrite /mkfmapf; elim: ks => [|k' ks IH] //=.\nby rewrite setmE inE {}IH; have [<-|?] := altP (k =P k').\nQed.\n\nLemma mkfmapfpE (f : T -> option S) (ks : seq T) k :\n  mkfmapfp f ks k = if k \\in ks then f k else None.\nProof.\nrewrite /mkfmapfp; elim: ks => [|k' ks IH] //=.\ncase e: (f k') => [v|] //=.\n  by rewrite setmE inE {}IH; have [->|? //] := altP (k =P k'); rewrite e.\nrewrite inE {}IH; have [->|?] //= := altP (k =P k'); rewrite e.\nby case: ifP.\nQed.\n\nLemma domm_mkfmapf (f : T -> S) (ks : seq T) :\n  domm (mkfmapf f ks) = fset ks.\nProof.\napply/eq_fset=> k; rewrite mem_domm mkfmapfE in_fset.\nby case: (k \\in ks).\nQed.\n\nLemma domm_mkfmapfp (f : T -> option S) (ks : seq T) :\n  domm (mkfmapfp f ks) = fset [seq k <- ks | f k].\nProof.\napply/eq_fset=> k; rewrite mem_domm mkfmapfpE in_fset mem_filter andbC.\nby case: (k \\in ks).\nQed.\n\nLemma setm_union m1 m2 k v :\n  setm (unionm m1 m2) k v = unionm (setm m1 k v) m2.\nProof.\napply/eq_fmap=> k'; rewrite !(setmE, unionmE).\nby have [->{k'}|] := altP (k' =P k).\nQed.\n\nLemma filterm_union p m1 m2 :\n  fdisjoint (domm m1) (domm m2) ->\n  filterm p (unionm m1 m2) =\n  unionm (filterm p m1) (filterm p m2).\nProof.\nmove=> dis; apply/eq_fmap=> k; rewrite filtermE !unionmE !filtermE.\ncase get_k1: (m1 k)=> [v|] //=.\nhave: k \\in domm m1 by rewrite mem_domm get_k1.\nmove/fdisjointP: dis=> dis /dis; rewrite mem_domm.\nby case: (m2 k)=> //= _; case: ifP.\nQed.\n\nLemma eq_mkfmapf (f1 f2 : T -> S) :\n  f1 =1 f2 -> mkfmapf f1 =1 mkfmapf f2.\nProof.\nby move=> e ks; apply/eq_fmap=> k; rewrite !mkfmapfE e.\nQed.\n\nLemma eq_mkfmapfp (f1 f2 : T -> option S) :\n  f1 =1 f2 -> mkfmapfp f1 =1 mkfmapfp f2.\nProof.\nby move=> e ks; apply/eq_fmap=> k; rewrite !mkfmapfpE e.\nQed.\n\nLemma eq_filterm f1 f2 m :\n  (f1 =2 f2) ->\n  filterm f1 m = filterm f2 m.\nProof.\nmove=> e; apply/eq_fmap=> k; rewrite 2!filtermE.\ncase: (m k) => [v|] //=.\nby rewrite e.\nQed.\n\nLemma domm_filter p m : domm (filterm p m) :<=: domm m.\nProof.\napply/fsubsetP=> k; rewrite !mem_domm filtermE.\nby case: (m k).\nQed.\n\nLemma setmI m k v : m k = Some v -> setm m k v = m.\nProof.\nmove=> get_k; apply/eq_fmap=> k'; rewrite setmE.\nby have [->{k'}|//] := altP (_ =P _); rewrite get_k.\nQed.\n\nLemma union0m : left_id (@emptym T S) unionm.\nProof. by []. Qed.\n\nLemma unionm0 : right_id (@emptym T S) unionm.\nProof.\nmove=> m; apply/eq_fmap=> k; rewrite unionmE emptymE /=.\nby case: (m k).\nQed.\n\nLemma unionmA : associative (@unionm T S).\nProof.\nmove=> m1 m2 m3; apply/eq_fmap=> k; rewrite !unionmE.\nby case: (m1 k).\nQed.\n\nLemma unionmI : idempotent (@unionm T S).\nProof.\nmove=> m; apply/eq_fmap=> k; rewrite !unionmE.\nby case: (m k).\nQed.\n\nLemma unionmC m1 m2 :\n  fdisjoint (domm m1) (domm m2) ->\n  unionm m1 m2 = unionm m2 m1.\nProof.\nmove=> dis; apply/eq_fmap=> k; rewrite !unionmE.\nhave {dis}: ~~ (m1 k) || ~~ (m2 k).\n  by rewrite -!mem_domm -implybE; apply/implyP/fdisjointP.\nby case: (m1 k) (m2 k)=> [?|] [?|] //=.\nQed.\n\nLemma unionmK m1 m2 : filterm (fun k _ => m1 k) (unionm m1 m2) = m1.\nProof.\napply/eq_fmap=> k; rewrite filtermE unionmE.\nby case: (m1 k) (m2 k)=> //= - [].\nQed.\n\nLemma fmap_rect (P : {fmap T -> S} -> Type) :\n  P emptym ->\n  (forall m, P m -> forall x y, x \\notin domm m -> P (setm m x y)) ->\n  forall m, P m.\nProof.\nmove=> H0 H1 m; move e: (domm m)=> X.\nelim/fset_rect: X m e=> [|x X x_X IH] m e.\n  by move/eqP/emptymP: e=> ->.\nhave : x \\in domm m by rewrite e in_fsetU1 eqxx.\nrewrite mem_domm; case yP: (m x)=> [y|] // _.\nset m' := remm m x; have em : m = setm m' x y.\n  apply/eq_fmap=> x'; rewrite /m' setmE remmE.\n  by case: eqP => [->|].\nhave {}e : domm m' = X.\n  apply/eq_fset=> x'; rewrite /m' domm_rem e in_fsetD1 in_fsetU1.\n  by case: eqP=> // -> /=; rewrite (negbTE x_X).\nrewrite {}em; apply: H1; first by exact: IH.\nby rewrite e.\nQed.\n\nLemma fmap_ind (P : {fmap T -> S} -> Prop) :\n  P emptym ->\n  (forall m, P m -> forall x y, x \\notin domm m -> P (setm m x y)) ->\n  forall m, P m.\nProof. exact: fmap_rect. Qed.\n\nLemma val_domm m : domm m = unzip1 m :> seq _.\nProof.\napply: (sorted_eq (@Ord.lt_trans T)).\n- move=> x y /andP [/Ord.ltW xy /Ord.ltW yx].\n  by apply: Ord.anti_leq; rewrite xy.\n- exact: valP.\n- exact: (valP m).\nrewrite uniq_perm // ?uniq_fset //.\n  apply: sorted_uniq.\n  - exact: (@Ord.lt_trans T).\n  - exact: Ord.ltxx.\n  - exact: (valP m).\nby move=> x; rewrite in_fset.\nQed.\n\nLemma fmvalK : cancel val (@mkfmap T S).\nProof.\nby move=> /= m; apply/eq_fmap=> x; rewrite mkfmapE.\nQed.\n\nLemma mkfmapK (kvs : seq (T * S)) :\n  sorted Ord.lt (unzip1 kvs) ->\n  mkfmap kvs = kvs :> seq (T * S).\nProof.\nelim: kvs=> [|[k v] kvs IH]=> //= kvs_sorted.\nrewrite IH ?(path_sorted kvs_sorted) //.\ncase: kvs kvs_sorted {IH} => [|[k' v'] kvs] //=.\nby case/andP=> ->.\nQed.\n\nLemma getm_nth p (m : {fmap T -> S}) i :\n  (i < size m)%N ->\n  m (nth p.1 (domm m) i) = Some (nth p m i).2.\nProof.\nrewrite val_domm /getm; move: (valP m); rewrite /=.\nelim: (val m) i=> [//|[/= k v] kv IH] [|i] /= kv_sorted.\n  by rewrite eqxx.\nrewrite ltnS=> isize; rewrite (IH _ (path_sorted kv_sorted) isize).\ncase: eqP=> // kP; have kkv: k \\in unzip1 kv.\n  by rewrite -kP; apply/mem_nth; rewrite size_map.\nmove/(order_path_min (@Ord.lt_trans T))/allP/(_ _ kkv): kv_sorted.\nby rewrite Ord.ltxx.\nQed.\n\nEnd Properties.\n\nArguments dommP {_ _ _ _}.\nArguments dommPn {_ _ _ _}.\n\nLemma eq_setm (T : ordType) (S : eqType) m1 m2 (x : T) (y1 y2 : S) :\n  (setm m1 x y1 == setm m2 x y2) =\n  (y1 == y2) && (remm m1 x == remm m2 x).\nProof.\napply/(sameP eqP)/(iffP andP).\n  rewrite -[setm m1 x y1]setm_rem.\n  by case=> /eqP -> /eqP ->; rewrite setm_rem.\nmove=> /eq_fmap e.\nmove: (e x); rewrite !setmE eqxx; case=> ->; split=> //.\napply/eqP/eq_fmap=> x'; move: (e x'); rewrite !setmE !remmE.\nby case: eqP.\nQed.\n\nSection MapSplitting.\n\nLocal Open Scope fset_scope.\n\nVariables (T : ordType) (S : Type).\nImplicit Types m : {fmap T -> S}.\n\nDefinition splitm m :=\n  match val m with\n  | (x, y) :: ps => Some (x, y, mkfmap ps)\n  | [::] => None\n  end.\n\nLemma sizeES m :\n  size m = if splitm m is Some (_, _, m') then (size m').+1 else 0.\nProof.\nrewrite /splitm /=; move: (valP m)=> /=.\nby case: (val m)=> [|[x y] m'] //= /path_sorted /mkfmapK ->.\nQed.\n\nLemma dommES m :\n  domm m = if splitm m is Some (x, _, m) then x |: domm m\n           else fset0.\nProof.\nrewrite /domm /splitm /=.\ncase: m=> [[|[x y] m] mP] //=; first by rewrite fset0E.\nmove: mP=> /= /path_sorted/mkfmapK ->.\nby rewrite fset_cons.\nQed.\n\nEnd MapSplitting.\n\nSection FilterMap.\n\nVariables T : ordType.\nVariables S R : Type.\n\nImplicit Types (f : T -> S -> option R) (m : {fmap T -> S}).\n\nDefinition filter_map f m :=\n  mkfmapfp (fun x => obind (f x) (m x)) (domm m).\n\nLemma filter_mapE f m x : filter_map f m x = obind (f x) (m x).\nProof.\nby rewrite /filter_map mkfmapfpE mem_domm; case: (m x).\nQed.\n\nLemma domm_filter_map f m :\n  domm (filter_map f m) = fset_filter (fun x => obind (f x) (m x)) (domm m).\nProof.\napply/eq_fset=> x.\nby rewrite mem_domm filter_mapE in_fset_filter mem_domm andbC; case: (m x).\nQed.\n\nLemma mapimK (g : T -> R -> S) f :\n  (forall x y, f x (g x y) = Some y) ->\n  cancel (mapim g) (filter_map f).\nProof.\nmove=> gK m; apply/eq_fmap=> x.\nby rewrite filter_mapE mapimE; case: (m x)=> //= z.\nQed.\n\nEnd FilterMap.\n\nSection Map.\n\nVariables (T : ordType) (S S' : Type).\n\nImplicit Types (m : {fmap T -> S}) (k : T).\n\nLemma domm_mapi (f : T -> S -> S') m : domm (mapim f m) = domm m.\nProof.\nby apply/eq_fset=> k; rewrite !mem_domm mapimE; case: (m k).\nQed.\n\nLemma domm_map (f : S -> S') m : domm (mapm f m) = domm m.\nProof. exact: domm_mapi. Qed.\n\nLemma mapim_map (f : S -> S') m : mapim (fun=> f) m = mapm f m.\nProof. by []. Qed.\n\nLemma eq_mapm f g : f =1 g -> @mapm T S S' f =1 mapm g.\nProof.\nmove=> e m; apply/eq_fmap=> x; rewrite !mapmE.\nby case: (m x)=> [y|] //=; rewrite e.\nQed.\n\nLemma mapm_comp S'' (g : S' -> S'') (f : S -> S') m :\n  mapm (g \\o f) m = mapm g (mapm f m).\nProof.\nby apply/eq_fmap=> x; rewrite !mapmE; case: (m x).\nQed.\n\nLemma mapm_mkfmapf (f : S -> S') (g : T -> S) (X : {fset T}) :\n  mapm f (mkfmapf g X) = mkfmapf (f \\o g) X.\nProof.\nby apply/eq_fmap=> x; rewrite !mapmE !mkfmapfE /=; case: ifP.\nQed.\n\nEnd Map.\n\nSection Map2.\n\nImplicit Types (T : ordType) (S : Type).\n\nLocal Open Scope fset_scope.\n\nDefinition mapm2 T T' S S' f g (m : {fmap T -> S}) : {fmap T' -> S'} :=\n  mkfmap [seq (f p.1, g p.2) | p <- m].\n\nLemma mapm2E T T' S S' (f : T -> T') (g : S -> S') m x :\n  injective f ->\n  mapm2 f g m (f x) = omap g (m x).\nProof.\nrewrite /mapm2 => f_inj; rewrite mkfmapE /getm.\ncase: m=> [/= m _]; elim: m=> [|[x' y] m IH] //=.\nby rewrite (inj_eq f_inj) [in RHS]fun_if IH.\nQed.\n\nLemma domm_map2 T T' S S' (f : T -> T') (g : S -> S') m :\n  domm (mapm2 f g m) = f @: domm m.\nProof.\napply/eq_fset=> x; rewrite /mapm2 domm_mkfmap /unzip1 -map_comp /comp /=.\nby rewrite /domm imfset_fset in_fset -map_comp.\nQed.\n\nLemma mapm2_comp T T' T'' S S' S'' f f' g g' :\n  injective f  ->\n  injective f' ->\n  mapm2 (f' \\o f) (g' \\o g) =1\n  @mapm2 T' T'' S' T'' f' g' \\o @mapm2 T T' S S' f g.\nProof.\nmove=> f_inj f'_inj m; apply/eq_fmap=> x /=.\nhave [|xnin] := boolP (x \\in domm (mapm2 (f' \\o f) (g' \\o g) m)).\n- rewrite domm_map2; case/imfsetP=> {}x xin ->.\n  rewrite mapm2E /=; last exact: inj_comp.\n  by rewrite !mapm2E //; case: (m x).\n- move: (xnin); rewrite (dommPn xnin).\n  rewrite !domm_map2 // imfset_comp -(domm_map2 f g) -(domm_map2 f' g').\n  by move/dommPn=> ->.\nQed.\n\nEnd Map2.\n\nSection EqType.\n\nVariables (T : ordType) (S : eqType).\nImplicit Types (m : {fmap T -> S}) (k : T) (v : S).\n\nLemma getmP m k v : reflect (m k = Some v) ((k, v) \\in m).\nProof.\ncase: m => [s Ps] /=; apply/(iffP idP); rewrite /getm /= inE /=.\n  elim: s Ps => [|[k' v'] s IH] //= sorted_s.\n  move/(_ (path_sorted sorted_s)) in IH.\n  rewrite inE => /orP [/eqP [e_k e_v]|in_s].\n    by rewrite -{}e_k -{}e_v {k' v' sorted_s} eqxx.\n  have [e_k {IH} |n_k] := altP (k =P k'); last by auto.\n  rewrite -{}e_k {k'} in sorted_s.\n  suff : Ord.lt k k by rewrite Ord.ltxx.\n  move/allP: (order_path_min (@Ord.lt_trans T) sorted_s); apply.\n  by apply: map_f in_s.\nelim: s Ps=> [|[k' v'] s IH] //= sorted_s.\nmove/(_ (path_sorted sorted_s)) in IH.\nhave [e_k [e_v]|n_k get_k] := altP (k =P k').\n  by rewrite -{}e_k {}e_v {k' v'} inE eqxx in sorted_s *.\nby rewrite inE IH // orbT.\nQed.\n\nLemma mkfmap_Some (kvs : seq (T * S)) k v\n  : mkfmap kvs k = Some v -> (k, v) \\in kvs.\nProof.\nelim: kvs => [|[k' v'] kvs IH] //=; rewrite setmE.\nhave [-> [->]|_ H] := altP (_ =P _); first by rewrite inE eqxx.\nby rewrite inE IH // orbT.\nQed.\n\nDefinition injectivem m := uniq (unzip2 m).\n\nLemma injectivemP m : reflect {in domm m, injective m} (injectivem m).\nProof.\napply/(iffP idP).\n  move=> inj_m k1; rewrite mem_domm; case m_k1: (m k1) => [v|] // _.\n  move/getmP in m_k1; move=> k2 /esym/getmP.\n  move: inj_m m_k1; rewrite /injectivem.\n  have: uniq (unzip1 m).\n    apply (sorted_uniq (@Ord.lt_trans T) (@Ord.ltxx T)).\n    exact: (valP m).\n  rewrite !inE /=; elim: (val m) => [|[k' v'] s IH] //=.\n  move=>/andP [k'_nin_s {}/IH IH] /andP [v'_nin_s {}/IH IH].\n  rewrite !inE -pair_eqE /=.\n  have [k1k'|k1k'] /= := altP (k1 =P k').\n    subst k'; have /negbTE ->: (k1, v) \\notin s.\n      apply: contra k'_nin_s => k'_in_s.\n      by apply/mapP; exists (k1, v).\n    rewrite orbF=> /eqP ?; subst v'; rewrite eqxx andbT.\n    have /negbTE ->: (k2, v) \\notin s.\n      apply: contra v'_nin_s => v'_in_s.\n      by apply/mapP; exists (k2, v).\n    by rewrite orbF => /eqP ->.\n  move=> k1_in_s; move: (k1_in_s)=> {}/IH IH.\n  have [k2k'|k2k'] //= := altP (k2 =P k').\n  subst k'; case/orP=> [/eqP ?|//]; subst v'.\n  suff c : v \\in unzip2 s by rewrite c in v'_nin_s.\n  by apply/mapP; exists (k1, v).\nmove=> inj_m.\nrewrite /injectivem map_inj_in_uniq.\n  apply: (@map_uniq _ _ (@fst T S)).\n  apply: (sorted_uniq (@Ord.lt_trans T) (@Ord.ltxx T)).\n  exact: (valP m).\nmove=> [k1 v] [k2 v'] /= /getmP k1_in_m /getmP k2_in_m ?; subst v'.\nmove: (inj_m k1); rewrite mem_domm k1_in_m => /(_ erefl k2 (esym k2_in_m)).\ncongruence.\nQed.\n\nLemma eq_domm0 (S' : eqType) (m : {fmap T -> S'}) :\n  (domm m == fset0) = (m == emptym).\nProof.\napply/(sameP idP)/(iffP idP)=> [/eqP->|/eqP Pdom]; first by rewrite domm0.\napply/eqP/eq_fmap=> k; rewrite emptymE; apply/dommPn.\nby rewrite Pdom in_fset0.\nQed.\n\nEnd EqType.\n\nSection Inverse.\n\nSection Def.\n\nVariables (T S : ordType).\n\nImplicit Type (m : {fmap T -> S}).\n\nDefinition invm m := mkfmap [seq (p.2, p.1) | p <- m].\n\nDefinition codomm m := domm (invm m).\n\nEnd Def.\n\nSection Cancel.\n\nVariables (T S : ordType).\n\nImplicit Type (m : {fmap T -> S}).\n\nOpen Scope fset_scope.\n\nLemma getm_inv m k k' : invm m k = Some k' -> m k' = Some k.\nProof.\nrewrite /invm =>/mkfmap_Some/mapP [[h h'] /getmP get_k /= [??]].\nby subst h h'.\nQed.\n\nLemma codommP m k : reflect (exists k', m k' = Some k) (k \\in codomm m).\nProof.\nrewrite /codomm; apply/(iffP idP).\n  rewrite mem_domm; case im_k: (invm m k) => [k'|] //= _.\n  by rewrite -(getm_inv im_k); eauto.\nmove=> [k' /getmP m_k'].\nrewrite /invm domm_mkfmap; apply/mapP; exists (k, k') => //.\nby apply/mapP; exists (k', k).\nQed.\n\nLemma codommPn m k : reflect (forall k', m k' != Some k) (k \\notin codomm m).\nProof.\napply/(iffP idP).\n  by move=> h k'; apply: contra h=> /eqP h; apply/codommP; eauto.\nmove=> h; apply/negP=> /codommP [k' h'].\nby move: (h k'); rewrite h' eqxx.\nQed.\n\nArguments codommP {_ _}.\nArguments codommPn {_ _}.\n\nLemma codomm0 : codomm (@emptym T S) = fset0.\nProof. by rewrite /codomm /domm fset0E. Qed.\n\nLemma codomm_rem m k : codomm (remm m k) :<=: codomm m.\nProof.\napply/fsubsetP=> v /codommP [k']; rewrite remmE.\nby case: eqP=> // _ Pv; apply/codommP; eauto.\nQed.\n\nLemma invmE m k : obind m (invm m k) = if invm m k then Some k else None.\nProof.\ncase get_k: (invm m k) => [k'|] //=.\nrewrite /invm in get_k; move/mkfmap_Some/mapP in get_k.\nby case: get_k => [[h h'] /getmP get_k [??]]; subst k k'.\nQed.\n\nEnd Cancel.\n\nSection CancelRev.\n\nVariables (T S : ordType).\n\nImplicit Type (m : {fmap T -> S}).\n\nLemma invmEV m k :\n  {in domm m, injective m} ->\n  obind (invm m) (m k) = if m k then Some k else None.\nProof.\nmove=> inj_m; case m_k: (m k) => [k'|] //=.\nmove: (invmE m k').\ncase im_k': (invm m k') => [k''|] //=.\n  move=> m_k''; congr Some; apply: inj_m; last by congruence.\n  by rewrite mem_domm m_k''.\nhave /codommPn/(_ k) : k' \\notin domm (invm m) by rewrite mem_domm im_k'.\nby rewrite m_k eqxx.\nQed.\n\nEnd CancelRev.\n\nVariables (T S : ordType).\n\nImplicit Type (m : {fmap T -> S}).\n\nLemma invm_inj m : {in codomm m, injective (invm m)}.\nProof.\nmove=> k1 in_im k2 h; rewrite mem_domm in in_im.\nhave {h}: obind m (invm m k1) = obind m (invm m k2) by congruence.\nrewrite invmE {}in_im.\ncase im_k2: (invm m k2) => [k|] //=.\nby move/getm_inv in im_k2; congruence.\nQed.\n\nLemma invmK m : {in domm m, injective m} -> invm (invm m) = m.\nProof.\nmove=> inj_m; apply/eq_fmap=> k.\nmove: (invmEV k inj_m).\ncase m_k: (m k) => [k'|] //= im_k'.\n  by move: (invmEV k' (@invm_inj m)); rewrite im_k' /=.\nmove {im_k'}.\nsuff : k \\notin domm (invm (invm m)) by rewrite mem_domm; case: (invm (invm m) k).\napply/codommPn=> k'; apply/eqP=> im_k'.\nby move: (invmE m k'); rewrite im_k' /= m_k.\nQed.\n\nEnd Inverse.\n\nArguments codommP {_ _ _ _}.\nArguments codommPn {_ _ _ _}.\n\nSection OfSeq.\n\nVariable (T : Type).\n\nDefinition fmap_of_seq (xs : seq T) : {fmap nat -> T} :=\n  mkfmapfp (nth None [seq Some x | x <- xs]) (iota 0 (size xs)).\n\nLemma fmap_of_seqE xs n :\n  fmap_of_seq xs n = nth None [seq Some x | x <- xs] n.\nProof.\nrewrite /fmap_of_seq mkfmapfpE mem_iota leq0n /= add0n.\ncase: ltnP=> [l|g] //.\nby rewrite nth_default // size_map.\nQed.\n\nEnd OfSeq.\n\nSection Currying.\n\nVariables (T S : ordType) (R : Type).\nImplicit Type (m : {fmap T * S -> R}).\nImplicit Type (n : {fmap T -> {fmap S -> R}}).\n\nLocal Open Scope fset_scope.\n\nDefinition currym m :=\n  mkfmapf (fun x => mkfmapfp (fun y => m (x, y))\n                                   (@snd _ _ @: domm m))\n             (@fst _ _ @: domm m).\n\nDefinition uncurrym n : {fmap T * S -> R} :=\n  mkfmapfp (fun p : T * S => if n p.1 is Some n' then n' p.2\n                             else None)\n              (\\bigcup_(x <- domm n)\n                  if n x is Some n' then pair x @: domm n'\n                  else fset0).\n\nLemma currymP m x y v :\n  (exists2 n, currym m x = Some n & n y = Some v) <->\n  m (x, y) = Some v.\nProof.\nsplit.\n  move=> [n]; rewrite /currym mkfmapfE.\n  case: ifP=> [/imfsetP/= [[x' y'] /= E ?]|//]; subst x'.\n  move=> [<-] {n}; rewrite mkfmapfpE.\n  by case: ifP.\nmove=> get_xy.\nexists (mkfmapfp (fun y' => m (x, y')) (@snd _ _ @: domm m)).\n  rewrite /currym mkfmapfE -{1}[x]/(x, y).1 mem_imfset //.\n  by rewrite mem_domm get_xy.\nby rewrite mkfmapfpE -{1}[y]/(x, y).2 mem_imfset // mem_domm get_xy.\nQed.\n\nLemma currymE m x y :\n  m (x, y) = obind (fun n : {fmap S -> R} => n y) (currym m x).\nProof.\nrewrite /currym mkfmapfE.\ncase: imfsetP=> [[[x' y'] /=]|].\n  rewrite mem_domm => get_xy ?; subst x'.\n  rewrite mkfmapfpE.\n  case get_xy': (m (x, y))=> [v|] //=; last by case: ifP.\n  by rewrite -{1}[y]/(x, y).2 mem_imfset // mem_domm get_xy'.\ncase get_xy: (m (x, y))=> [v|] // h.\nsuff: False by [].\nby apply: h; exists (x, y)=> //; rewrite mem_domm get_xy.\nQed.\n\nLemma domm_curry m : domm (currym m) = @fst _ _ @: (domm m).\nProof.\nby apply/eq_fset=> x; rewrite /currym mem_domm mkfmapfE; case: ifP.\nQed.\n\nLemma uncurrymP n x y v :\n  (exists2 n', n x = Some n' & n' y = Some v) <->\n  uncurrym n (x, y) = Some v.\nProof.\npose f x' := if n x' is Some n'' then pair x' @: domm n'' else fset0.\nsplit.\n  move=> [n' get_x get_y].\n  rewrite /uncurrym mkfmapfpE /= get_x get_y.\n  have inDn' : (x, y) \\in f x.\n    by rewrite /f get_x mem_imfset // mem_domm get_y.\n  have inD : x \\in domm n by rewrite mem_domm get_x.\n  by move/fsubsetP/(_ _ inDn'): (bigcup_sup f inD erefl)=> ->.\nrewrite /uncurrym mkfmapfpE /=.\nby case: ifP=> [inU|] //=; case: (n x) => [n'|] //= get_y; eauto.\nQed.\n\nLemma uncurrymE n p :\n  uncurrym n p = obind (fun nn => getm nn p.2) (n p.1).\nProof.\ncase: p=> x y /=.\ncase e: (uncurrym n (x, y))=> [v|] /=.\n  by case/uncurrymP: e => nn -> /= ->.\ncase e': (n x) => [nn|] //=.\ncase e'': (nn y) => [v|] //=.\nhave/uncurrymP : exists2 n', n x = Some n' & n' y = Some v by eauto.\nby rewrite e.\nQed.\n\nLemma currymK : cancel currym uncurrym.\nProof.\nmove=> m; apply/eq_fmap=> - [x y].\ncase get_m: (m _)=> [v|]; first by move/currymP/uncurrymP: get_m.\ncase get_ucm : (uncurrym _ _)=> [v|] //.\nby move/uncurrymP/currymP: get_ucm get_m => ->.\nQed.\n\nEnd Currying.\n\nSection Enumeration.\n\nVariables (T S : ordType).\nImplicit Types (m : {fmap T -> S}) (xs : seq T) (ys : seq S).\n\nLocal Open Scope fset_scope.\n\nDefinition enum_fmap xs ys :=\n  foldr (fun x ms => ms ++ [seq setm m x y | m <- ms, y <- ys]) [:: emptym] xs.\n\nLemma enum_fmapP xs ys m :\n  reflect ({subset domm m <= xs} /\\ {subset codomm m <= ys})\n          (m \\in enum_fmap xs ys).\nProof.\nelim: xs m=> [|x xs IHx] //= m.\n  rewrite inE; apply/(iffP eqP)=> [->|[eq0 _]].\n    by rewrite domm0 codomm0; split=> ?; rewrite in_fset0.\n  apply/eqP; rewrite -eq_domm0 -fsubset0.\n  by apply/fsubsetP=> x /eq0.\nrewrite mem_cat.\napply/(iffP orP) => [[/IHx [subx suby] | /allpairsP h] | [subx suby]].\n- by split=> // x' x'_in; rewrite inE; apply/orP; right; apply: subx.\n- move: m h => m' [[m y] /= [/IHx [subx suby] h ->]] {m'}; split.\n    rewrite domm_set=> x' /fsetU1P [->|/subx]; rewrite inE ?eqxx //.\n    by move=> ->; rewrite orbT.\n  move=> y' /codommP [x']; rewrite setmE.\n  case: eqP=> [_ [<-] //| _ m_x']; apply: suby.\n  by apply/codommP; eauto.\nhave [/dommP [y h]|x_nin] := boolP (x \\in domm m).\n  right; apply/allpairsP; exists (remm m x, y)=> /=; split.\n  - apply/IHx; rewrite domm_rem; split.\n      by move=> x' /fsetDP [/subx]; rewrite inE => /orP [/eqP -> /fset1P|].\n    move=> y' /codommP [x' m_x']; apply: suby; apply/codommP.\n    by exists x'; move: m_x'; rewrite remmE; case: ifP.\n  - by apply: suby; apply/codommP; exists x.\n  by apply/eq_fmap=> x'; rewrite setmE remmE; case: eqP => [->|].\nleft; apply/IHx; split=> // x' x'_in; move/(_ _ x'_in): subx (x'_in) x_nin.\nby rewrite inE => /orP [/eqP -> ->|].\nQed.\n\nEnd Enumeration.\n", "meta": {"author": "arthuraa", "repo": "extructures", "sha": "7e613f67ef50c5e59788aa4cf591139fe4b4263b", "save_path": "github-repos/coq/arthuraa-extructures", "path": "github-repos/coq/arthuraa-extructures/extructures-7e613f67ef50c5e59788aa4cf591139fe4b4263b/theories/fmap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7493718753063937}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (x : natural) : natural :=\n  mult z (Succ (plus x y)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj232_coqofml_6eaIdL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7493718726421518}}
{"text": "Require Import Reals Coquelicot.Coquelicot.\nRequire Import Interval.Tactic.\n\nLemma constant :\n  3 <= RInt (fun x => 1) 0 3 <= 3.\nProof.\ninterval.\nQed.\n\nLemma exp_0_3 :\n  Rabs (RInt (fun x => exp x) 0 3 - (exp(1)*exp(1)*exp(1) - 1)) <= 1/(1000*1000).\nProof.\ninterval with (i_integral_depth 0, i_integral_deg 12).\nQed.\n\nLemma exp_0_3' :\n  Rabs (RInt (fun x => exp x) 0 3 - (exp(1)*exp(1)*exp(1) - 1)) <= 1/(1000*1000).\nProof.\ninterval with (i_integral_depth 1, i_integral_prec 20).\nQed.\n\nLemma x_ln1p_0_1 :\n  Rabs (RInt (fun x => x * ln(1 + x)) 0 1 - 1/4) <= 1/1000.\nProof.\ninterval with (i_integral_depth 0).\nQed.\n\nLemma circle :\n  Rabs (RInt (fun x => sqrt(1 - x * x)) 0 1 - PI / 4) <= 1/100.\nProof.\ninterval with (i_integral_depth 10, i_integral_deg 1).\nQed.\n\nLemma exp_cos_0_1 :\n  Rabs (RInt (fun x => sin(x) * exp(cos x)) 0 1 - (exp 1 - exp(cos 1))) <= 1/1000.\nProof.\ninterval with (i_integral_depth 0).\nQed.\n\nLemma arctan_0_1 :\n  Rabs (RInt (fun x => 1 / (1 + x*x)) 0 1 - PI / 4) <= 1/1000.\nProof.\ninterval with (i_integral_depth 0, i_integral_deg 13).\nQed.\n\nLemma arctan_0_1' :\n  Rabs (RInt (fun x => 1 / (1 + x*x)) 0 1 - PI / 4) <= 1/1000.\nProof.\ninterval with (i_integral_depth 1).\nQed.\n", "meta": {"author": "MSoegtropIMC", "repo": "interval", "sha": "2d7d7fe5d7e150372008924487186215774ba535", "save_path": "github-repos/coq/MSoegtropIMC-interval", "path": "github-repos/coq/MSoegtropIMC-interval/interval-2d7d7fe5d7e150372008924487186215774ba535/testsuite/example-20160218.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.749371869456887}}
{"text": "Require Import Omega.\nRequire Import List.\nImport ListNotations.\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.ListTactics.\nRequire Import StructTact.FilterMap.\nRequire Import StructTact.RemoveAll.\n\nSet Implicit Arguments.\n\nFixpoint subseq {A} (xs ys : list A) : Prop :=\n  match xs, ys with\n    | [], _ => True\n    | x :: xs', y :: ys' => (x = y /\\ subseq xs' ys') \\/ subseq xs ys'\n    | _, _ => False\n  end.\n\nSection subseq.\n  Variable A B : Type.\n  Hypothesis A_eq_dec : forall x y : A, {x = y} + {x <> y}.\n\n  Lemma subseq_refl : forall (l : list A), subseq l l.\n  Proof using.\n    induction l; simpl; tauto.\n  Qed.\n\n  Lemma subseq_trans :\n    forall (zs xs ys : list A),\n      subseq xs ys ->\n      subseq ys zs ->\n      subseq xs zs.\n  Proof using.\n    induction zs; intros; simpl in *;\n      repeat break_match; subst; simpl in *; intuition; subst; eauto;\n        right; (eapply IHzs; [|eauto]); simpl; eauto.\n  Qed.\n\n  Lemma subseq_In :\n    forall (ys xs : list A) x,\n      subseq xs ys ->\n      In x xs ->\n      In x ys.\n  Proof using.\n    induction ys; intros.\n    - destruct xs; simpl in *; intuition.\n    - simpl in *. break_match; simpl in *; intuition; subst; intuition eauto;\n                    right; (eapply IHys; [eauto| intuition]).\n  Qed.\n\n  Theorem subseq_NoDup :\n    forall (ys xs : list A),\n      subseq xs ys ->\n      NoDup ys ->\n      NoDup xs.\n  Proof using.\n    induction ys; intros.\n    - destruct xs; simpl in *; intuition.\n    - simpl in *. invc_NoDup.\n      break_match.\n      + constructor.\n      + intuition.\n        subst. constructor; eauto using subseq_In.\n  Qed.\n\n  Lemma subseq_remove :\n    forall (x : A) xs,\n      subseq (remove A_eq_dec x xs) xs.\n  Proof using.\n    induction xs; intros; simpl.\n    - auto.\n    - repeat break_match; auto.\n      + intuition congruence.\n      + find_inversion. auto.\n  Qed.\n\n  Lemma subseq_map :\n    forall (f : A -> B) ys xs,\n      subseq xs ys ->\n      subseq (map f xs) (map f ys).\n  Proof using.\n    induction ys; intros; simpl in *.\n    - repeat break_match; try discriminate; auto.\n    - repeat break_match; try discriminate; auto.\n      intuition.\n      + subst. simpl in *. find_inversion. auto.\n      + right. repeat find_reverse_rewrite. auto.\n  Qed.\n\n  Lemma subseq_cons_drop :\n    forall xs ys (a : A),\n      subseq (a :: xs) ys -> subseq xs ys.\n  Proof using.\n    induction ys; intros; simpl in *; intuition; break_match; eauto.\n  Qed.\n\n  Lemma subseq_length :\n    forall (ys xs : list A),\n      subseq xs ys ->\n      length xs <= length ys.\n  Proof using.\n    induction ys; intros; simpl in *; break_match; intuition.\n    subst. simpl in *. specialize (IHys l). concludes. auto with *.\n  Qed.\n\n  Lemma subseq_subseq_eq :\n    forall (xs ys : list A),\n      subseq xs ys ->\n      subseq ys xs ->\n      xs = ys.\n  Proof using.\n    induction xs; intros; destruct ys; simpl in *;\n      intuition eauto using f_equal2, subseq_cons_drop.\n    exfalso.\n    repeat find_apply_lem_hyp subseq_length.\n    simpl in *. omega.\n  Qed.\n\n  Lemma subseq_filter :\n    forall (f : A -> bool) xs,\n      subseq (filter f xs) xs.\n  Proof using.\n    induction xs; intros; simpl.\n    - auto.\n    - repeat break_match; intuition congruence.\n  Qed.\n\n  Lemma subseq_nil :\n    forall xs,\n      subseq (A:=A) [] xs.\n  Proof using.\n    destruct xs; simpl; auto.\n  Qed.\n\n  Lemma subseq_skip :\n    forall a xs ys,\n      subseq(A:=A) xs ys ->\n      subseq xs (a :: ys).\n  Proof using.\n    induction ys; intros; simpl in *; repeat break_match; intuition.\n  Qed.\n\n  Lemma subseq_filterMap :\n    forall (f : B -> option A) ys xs,\n      subseq xs ys ->\n      subseq (filterMap f xs) (filterMap f ys).\n  Proof using.\n    induction ys; intros; simpl in *; repeat break_match; auto; try discriminate; intuition; subst.\n    - simpl. find_rewrite. auto.\n    - auto using subseq_skip.\n    - auto using subseq_nil.\n    - simpl. find_rewrite. auto.\n  Qed.\n\n  Lemma subseq_app_r :\n    forall xs ys,\n      subseq (A:=A) ys (xs ++ ys).\n  Proof using.\n    induction xs; intros; simpl.\n    + auto using subseq_refl.\n    + break_match.\n      * auto.\n      * right. auto using subseq_nil.\n  Qed.\n\n  Lemma subseq_app_tail :\n    forall ys xs zs,\n      subseq (A:=A) xs ys ->\n      subseq (xs ++ zs) (ys ++ zs).\n  Proof using.\n    induction ys; intros; simpl in *.\n    - break_match; intuition auto using subseq_refl.\n    - repeat break_match.\n      + auto.\n      + discriminate.\n      + simpl in *. subst. right. auto using subseq_app_r.\n      + simpl in *. find_inversion. intuition.\n        rewrite app_comm_cons. auto.\n  Qed.\n\n  Lemma subseq_app_head :\n    forall xs ys zs,\n      subseq (A:=A) ys zs ->\n      subseq (A:=A) (xs ++ ys) (xs ++ zs).\n  Proof using.\n    induction xs; intros; simpl; intuition.\n  Qed.\n\n  Lemma subseq_2_3 :\n    forall xs ys zs x y,\n      subseq(A:=A) (xs ++ ys ++ zs) (xs ++ x :: ys ++ y :: zs).\n  Proof using.\n    auto using subseq_refl, subseq_skip, subseq_app_head.\n  Qed.\n\n  Lemma subseq_middle :\n    forall xs y zs,\n      subseq (A:=A) (xs ++ zs) (xs ++ y :: zs).\n  Proof using.\n    intros.\n    apply subseq_app_head.\n    apply subseq_skip.\n    apply subseq_refl.\n  Qed.\n\n  Lemma subseq_remove_all :\n    forall (ds l l' : list A),\n      subseq l l' ->\n      subseq (remove_all A_eq_dec ds l) l'.\n  Proof using.\n    induction ds; intros; simpl.\n    - auto.\n    - apply IHds.\n      eapply subseq_trans.\n      apply subseq_remove.\n      auto.\n  Qed.\nEnd subseq.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/StructTact/Subseq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7492599477619741}}
{"text": "(** * SearchTree: Binary Search Trees *)\n\n(** We have implemented maps twice so far: with lists in\n    [Lists], and with higher-order functions in [Maps].\n    Those are simple but inefficient implementations: looking up the\n    value bound to a given key takes time linear in the number of\n    bindings, both in the worst and expected case. *)\n\n(** If the type of keys can be totally ordered -- that is, it supports\n    a well-behaved [<=] comparison -- then maps can be implemented with\n    _binary search trees_ (BSTs).  Insert and lookup operations on\n    BSTs take time proportional to the height of the tree.  If the\n    tree is balanced, the operations therefore take logarithmic time. *)\n\n(** If you don't recall BSTs or haven't seen them in a while, see\n    Wikipedia or read any standard textbook; for example:\n\n    - Section 3.2 of _Algorithms, Fourth Edition_, by Sedgewick and\n      Wayne, Addison Wesley 2011; or\n\n    - Chapter 12 of _Introduction to Algorithms, 3rd Edition_, by\n      Cormen, Leiserson, and Rivest, MIT Press 2009. *)\n\nFrom Coq Require Import String.  (* for an example, and manual grading *)\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom VFA Require Import Perm.\nFrom VFA Require Import Maps.\nFrom VFA Require Import Sort.\n\n(* ################################################################# *)\n(** * BST Implementation *)\n\n(** We use [nat] as the key type in our implementation of BSTs,\n    since it has a convenient total order [<=?] with lots of theorems\n    and automation available. *)\n\nDefinition key := nat.\n\n(** [E] represents the empty map.  [T l k v r] represents the\n    map that binds [k] to [v], along with all the bindings in [l] and\n    [r].  No key may be bound more than once in the map. *)\n\nInductive tree (V : Type) : Type :=\n| E\n| T (l : tree V) (k : key) (v : V) (r : tree V).\n\nArguments E {V}.\nArguments T {V}.\n\n(** An example tree:\n\n      4 -> \"four\"\n      /        \\\n     /          \\\n  2 -> \"two\"   5 -> \"five\"\n*)\n\nDefinition ex_tree : tree string :=\n  (T (T E 2 \"two\" E) 4 \"four\" (T E 5 \"five\" E))%string.\n\n(** [empty_tree] contains no bindings. *)\n\nDefinition empty_tree {V : Type} : tree V :=\n  E.\n\n(** [bound k t] is whether [k] is bound in [t]. *)\n\nFixpoint bound {V : Type} (x : key) (t : tree V) :=\n  match t with\n  | E => false\n  | T l y v r => if x <? y then bound x l\n                else if x >? y then bound x r\n                     else true\n  end.\n\n(** [lookup d k t] is the value bound to [k] in [t], or is default\n    value [d] if [k] is not bound in [t]. *)\n\nFixpoint lookup {V : Type} (d : V) (x : key) (t : tree V) : V :=\n  match t with\n  | E => d\n  | T l y v r => if x <? y then lookup d x l\n                else if x >? y then lookup d x r\n                     else v\n  end.\n\n(** [insert k v t] is the map containing all the bindings of [t] along\n    with a binding of [k] to [v]. *)\n\nFixpoint insert {V : Type} (x : key) (v : V) (t : tree V) : tree V :=\n  match t with\n  | E => T E x v E\n  | T l y v' r => if x <? y then T (insert x v l) y v' r\n                 else if x >? y then T l y v' (insert x v r)\n                      else T l x v r\n  end.\n\n(** Note that [insert] is a _functional_ aka _persistent_\n    implementation: [t] is not changed. *)\n\nModule Tests.\n\n(** Here are some unit tests to check that BSTs behave the way we\n    expect. *)\n\n  Open Scope string_scope.\n\n  Example bst_ex1 :\n    insert 5 \"five\" (insert 2 \"two\" (insert 4 \"four\" empty_tree)) = ex_tree.\n  Proof. reflexivity. Qed.\n\n  Example bst_ex2 : lookup \"\" 5 ex_tree = \"five\".\n  Proof. reflexivity. Qed.\n\n  Example bst_ex3 : lookup \"\" 3 ex_tree = \"\".\n  Proof. reflexivity. Qed.\n\n  Example bst_ex4 : bound 3 ex_tree = false.\n  Proof. reflexivity. Qed.\n\nEnd Tests.\n\n(** Although we can spot-check the behavior of BST operations with\n    unit tests like these, we of course should prove general theorems\n    about their correctness.  We will do that later in the chapter. *)\n\n(* ################################################################# *)\n(** * BST Invariant *)\n\n(** The implementations of [lookup] and [insert] assume that\n    values of type [tree] obey the _BST invariant_: for any non-empty\n    node with key [k], all the values of the left subtree are less\n    than [k] and all the values of the right subtree are greater than\n    [k].  But that invariant is not part of the definition of\n    [tree]. For example, the following tree is not a BST: *)\n\nModule NotBst.\n  Open Scope string_scope.\n\n  Definition t : tree string :=\n    T (T E 5 \"five\" E) 4 \"four\" (T E 2 \"two\" E).\n\n  (** The [insert] function we wrote above would never produce\n      such a tree, but we can still construct it by manually applying\n      [T]. When we try to lookup [2] in that tree, we get the wrong\n      answer, because [lookup] assumes [2] is in the left subtree: *)\n\n  Example not_bst_lookup_wrong :\n    lookup \"\" 2 t <> \"two\".\n  Proof.\n    simpl. unfold not. intros contra. discriminate.\n  Qed.\nEnd NotBst.\n\n(** So, let's formalize the BST invariant. Here's one way to do\n    so.  First, we define a helper [ForallT] to express that idea that\n    a predicate holds at every node of a tree: *)\n\nFixpoint ForallT {V : Type} (P: key -> V -> Prop) (t: tree V) : Prop :=\n  match t with\n  | E => True\n  | T l k v r => P k v /\\ ForallT P l /\\ ForallT P r\n  end.\n\n(** Second, we define the BST invariant:\n\n    - An empty tree is a BST.\n\n    - A non-empty tree is a BST if all its left nodes have a lesser\n      key, its right nodes have a greater key, and the left and\n      right subtrees are themselves BSTs. *)\n\nInductive BST {V : Type} : tree V -> Prop :=\n| BST_E : BST E\n| BST_T : forall l x v r,\n    ForallT (fun y _ => y < x) l ->\n    ForallT (fun y _ => y > x) r ->\n    BST l ->\n    BST r ->\n    BST (T l x v r).\n\nHint Constructors BST.\n\n(** Let's check that [BST] correctly classifies a couple of example\n    trees: *)\n\nExample is_BST_ex :\n  BST ex_tree.\nProof.\n  unfold ex_tree.\n  repeat (constructor; try omega).\nQed.\n\nExample not_BST_ex :\n  ~ BST NotBst.t.\nProof.\n  unfold NotBst.t. intros contra.\n  inv contra. inv H3. omega.\nQed.\n\n(** **** Exercise: 1 star, standard (empty_tree_BST)  *)\n\n(** Prove that the empty tree is a BST. *)\n\nTheorem empty_tree_BST : forall (V : Type),\n    BST (@empty_tree V).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, standard (insert_BST)  *)\n\n(** Prove that [insert] produces a BST, assuming it is given one.\n\n    Start by proving this helper lemma, which says that [insert]\n    preserves any node predicate. Proceed by induction on [t]. *)\n\nLemma ForallT_insert : forall (V : Type) (P : key -> V -> Prop) (t : tree V),\n    ForallT P t -> forall (k : key) (v : V),\n      P k v -> ForallT P (insert k v t).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Now prove the main theorem. Proceed by induction on the evidence\n    that [t] is a BST. *)\n\nTheorem insert_BST : forall (V : Type) (k : key) (v : V) (t : tree V),\n    BST t -> BST (insert k v t).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** Since [empty_tree] and [insert] are the only operations that\n    create BSTs, we are guaranteed that any [tree] is a BST -- unless\n    it was constructed manually with [T].  It would therefore make\n    sense to limit the use of [T] to only within the tree operations,\n    rather than expose it.  Coq, like OCaml and other functional\n    languages, can do this with its module system.  See [ADT] for\n    details. *)\n\n(* ################################################################# *)\n(** * Correctness of BST Operations *)\n\n(** To prove the correctness of [lookup] and [bound], we need\n    specifications for them.  We'll study two different techniques for\n    that in this chapter. *)\n\n(** The first is called _algebraic specification_.  With it, we write\n    down equations relating the results of operations.  For example,\n    we could write down equations like the following to specify the\n    [+] and [*] operations:\n\n      (a + b) + c = a + (b + c)\n      a + b = b + a\n      a + 0 = a\n      (a * b) * c = a * (b * c)\n      a * b = b * a\n      a * 1 = a\n      a * 0 = 0\n      a * (b + c) = a * b + a * c\n\n    For BSTs, let's examine how [lookup] should interact with\n    when applied to other operations.  It is easy to see what needs to\n    be true for [empty_tree]: looking up any value at all in the empty\n    tree should fail and return the default value:\n\n      lookup d k empty_tree = d\n\n    What about non-empty trees?  The only way to build a non-empty\n    tree is by applying [insert k v t] to an existing tree [t]. So it\n    suffices to describe the behavior of [lookup] on the result of an\n    arbitrary [insert] operation. There are two cases.  If we look up\n    the same key that was just inserted, we should get the value that\n    was inserted with it:\n\n      lookup d k (insert k v t) = v\n\n    If we look up a different key than was just inserted, the insert\n    should not affect the answer -- which should be the same as if we\n    did the lookup in the original tree before the insert occured:\n\n      lookup d k' (insert k v t) = lookup d k' t      if k <> k'\n\n    These three basic equations specify the correct behavior of maps.\n    Let's prove that they hold. *)\n\nTheorem lookup_empty : forall (V : Type) (d : V) (k : key),\n    lookup d k empty_tree = d.\nProof.\n  auto.\nQed.\n\nTheorem lookup_insert_eq : forall (V : Type) (t : tree V) (d : V) (k : key) (v : V),\n    lookup d k (insert k v t)  = v.\nProof.\n  induction t; intros; simpl.\n  - bdestruct (k <? k); try omega; auto.\n  - bdestruct (k <? k0); bdestruct (k0 <? k); simpl; try omega; auto.\n    + bdestruct (k <? k0); bdestruct (k0 <? k); try omega; auto.\n    + bdestruct (k <? k0); bdestruct (k0 <? k); try omega; auto.\n    + bdestruct (k0 <? k0); try omega; auto.\nQed.\n\n(** The basic method of that proof is to repeatedly [bdestruct]\n    everything in sight, followed by generous use of [omega] and\n    [auto]. Let's automate that. *)\n\nLtac bdestruct_guard :=\n  match goal with\n  | |- context [ if ?X =? ?Y then _ else _ ] => bdestruct (X =? Y)\n  | |- context [ if ?X <=? ?Y then _ else _ ] => bdestruct (X <=? Y)\n  | |- context [ if ?X <? ?Y then _ else _ ] => bdestruct (X <? Y)\n  end.\n\nLtac bdall :=\n  repeat (simpl; bdestruct_guard; try omega; auto).\n\nTheorem lookup_insert_eq' :\n  forall (V : Type) (t : tree V) (d : V) (k : key) (v : V),\n    lookup d k (insert k v t) = v.\nProof.\n  induction t; intros; bdall.\nQed.\n\n(** The tactic immediately pays off in proving the third\n    equation. *)\n\nTheorem lookup_insert_neq :\n  forall (V : Type) (t : tree V) (d : V) (k k' : key) (v : V),\n   k <> k' -> lookup d k' (insert k v t) = lookup d k' t.\nProof.\n  induction t; intros; bdall.\nQed.\n\n(** Perhaps surprisingly, the proofs of these results do not\n    depend on whether [t] satisfies the BST invariant.  That's because\n    [lookup] and [insert] follow the same path through the tree, so\n    even if nodes are in the \"wrong\" place, they are consistently\n    \"wrong\". *)\n\n(** **** Exercise: 3 stars, standard, optional (bound_correct)  *)\n\n(** Specify and prove the correctness of [bound]. State and prove\n    three theorems, inspired by those we just proved for [lookup]. If\n    you have the right theorem statements, the proofs should all be\n    quite easy -- thanks to [bdall]. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_bound_correct : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bound_default)  *)\n\n(** Prove that if [bound] returns [false], then [lookup] returns\n    the default value. Proceed by induction on the tree. *)\n\nTheorem bound_default :\n  forall (V : Type) (k : key) (d : V) (t : tree V),\n    bound k t = false ->\n    lookup d k t = d.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * BSTs vs. Higher-order Functions (Optional) *)\n\n(** The three theorems we just proved for [lookup] should seem\n    familiar: we proved equivalent theorems in [Maps] for maps\n    defined as higher-order functions. *)\n\n(** - [lookup_empty] and [t_apply_empty] both state that the empty map\n      binds all keys to the default value. *)\n\nCheck lookup_empty : forall (V : Type) (d : V) (k : key),\n    lookup d k empty_tree = d.\n\nCheck t_apply_empty : forall (V : Type) (k : key) (d : V),\n    t_empty d k = d.\n\n(** - [lookup_insert_eq] and [t_update_eq] both state that updating a map\n      then looking for the updated key produces the updated value. *)\n\nCheck lookup_insert_eq : forall (V : Type) (t : tree V) (d : V) (k : key) (v : V),\n    lookup d k (insert k v t) = v.\n\nCheck t_update_eq : forall (V : Type) (m : total_map V) (k : key) (v : V),\n    (t_update m k v) k = v.\n\n(** - [lookup_insert_neq] and [t_update_neq] both state that updating\n      a map then looking for a different key produces the same value\n      as the original map. *)\n\nCheck lookup_insert_neq :\n  forall (V : Type) (t : tree V) (d : V) (k k' : key) (v : V),\n    k <> k' -> lookup d k' (insert k v t) = lookup d k' t.\n\nCheck t_update_neq : forall (V : Type) (v : V) (k k' : key) (m : total_map V),\n    k <> k' -> (t_update m k v) k' = m k'.\n\n(** In [Maps], we also proved three other theorems about the\n    behavior of functional maps on various combinations of updates and\n    lookups: *)\n\nCheck t_update_shadow : forall (V : Type) (m : total_map V) (v1 v2 : V) (k : key),\n    t_update (t_update m k v1) k v2 = t_update m k v2.\n\nCheck t_update_same : forall (V : Type) (k : key) (m : total_map V),\n    t_update m k (m k) = m.\n\nCheck t_update_permute :\n  forall (V : Type) (v1 v2 : V) (k1 k2 : key) (m : total_map V),\n    k2 <> k1 ->\n    t_update (t_update m k2 v2) k1 v1 = t_update (t_update m k1 v1) k2 v2.\n\n(** Let's prove analogues to these three theorems for search trees.\n\n    Hint: you do not need to unfold the definitions of [empty_tree],\n    [insert], or [lookup].  Instead, use [lookup_insert_eq] and\n    [lookup_insert_neq]. *)\n\n(** **** Exercise: 2 stars, standard, optional (lookup_insert_shadow)  *)\n\nLemma lookup_insert_shadow :\n  forall (V : Type) (t : tree V) (v v' d: V) (k k' : key),\n    lookup d k' (insert k v (insert k v' t)) = lookup d k' (insert k v t).\nProof.\n  intros. bdestruct (k =? k').\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (lookup_insert_same)  *)\n\nLemma lookup_insert_same :\n  forall (V : Type) (k k' : key) (d : V) (t : tree V),\n    lookup d k' (insert k (lookup d k t) t) = lookup d k' t.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (lookup_insert_permute)  *)\n\nLemma lookup_insert_permute :\n  forall (V : Type) (v1 v2 d : V) (k1 k2 k': key) (t : tree V),\n    k1 <> k2 ->\n    lookup d k' (insert k1 v1 (insert k2 v2 t))\n    = lookup d k' (insert k2 v2 (insert k1 v1 t)).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** Our ability to prove these lemmas without reference to the\n    underlying tree implementation demonstrates they hold for any map\n    implementation that satisfies the three basic equations. *)\n\n(** Each of these lemmas just proved was phrased as an equality\n    between the results of looking up an arbitrary key [k'] in two\n    maps.  But the lemmas for the function-based maps were phrased as\n    direct equalities between the maps themselves.\n\n    Could we state the tree lemmas with direct equalities?  For\n    [insert_shadow], the answer is yes: *)\n\nLemma insert_shadow_equality : forall (V : Type) (t : tree V) (k : key) (v v' : V),\n    insert k v (insert k v' t) = insert k v t.\nProof.\n  induction t; intros; bdall.\n  - rewrite IHt1; auto.\n  - rewrite IHt2; auto.\nQed.\n\n(** But the other two direct equalities on BSTs do not necessarily\n    hold. *)\n\n(** **** Exercise: 3 stars, standard, optional (direct_equalities_break)  *)\n\n(** Prove that the other equalities do not hold.  Hint: find a counterexample\n    first on paper, then use the [exists] tactic to instantiate the theorem\n    on your counterexample.  The simpler your counterexample, the simpler\n    the rest of the proof will be. *)\n\nLemma insert_same_equality_breaks :\n  exists (V : Type) (d : V) (t : tree V) (k : key),\n      insert k (lookup d k t) t <> t.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma insert_permute_equality_breaks :\n  exists (V : Type) (v1 v2 : V) (k1 k2 : key) (t : tree V),\n    k1 <> k2 /\\ insert k1 v1 (insert k2 v2 t) <> insert k2 v2 (insert k1 v1 t).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Converting a BST to a List *)\n\n(** Let's add a new operation to our BST: converting it to an\n    _association list_ that contains the key--value bindings from the\n    tree stored as pairs.  If that list is sorted by the keys, then\n    any two trees that represent the same map would be converted to\n    the same list. Here's a function that does so with an in-order\n    traversal of the tree: *)\n\nFixpoint elements {V : Type} (t : tree V) : list (key * V) :=\n  match t with\n  | E => []\n  | T l k v r => elements l ++ [(k, v)] ++ elements r\n  end.\n\nExample elements_ex :\n    elements ex_tree = [(2, \"two\"); (4, \"four\"); (5, \"five\")]%string.\nProof. reflexivity. Qed.\n\n(** Here are three desirable properties for [elements]:\n\n    1. The list has the same bindings as the tree.\n\n    2. The list is sorted by keys.\n\n    3. The list contains no duplicates.\n\n    Let's formally specify and verify them. *)\n\n(* ================================================================= *)\n(** ** Part 1: Same Bindings *)\n\n(** We want to show that a binding is in [elements t] iff it's in\n    [t]. We'll prove the two directions of that bi-implication\n    separately:\n\n    - [elements] is _complete_: if a binding is in [t] then it's in\n      [elements t].\n\n    - [elements] is _correct_: if a binding is in [elements t] then\n      it's in [t].  *)\n\n(** Getting the specification of completeness right is a little\n    tricky.  It's tempting to start off with something too simple like\n    this: *)\n\nDefinition elements_complete_broken_spec :=\n  forall (V : Type) (k : key) (v d : V) (t : tree V),\n    BST t ->\n    lookup d k t = v ->\n    In (k, v) (elements t).\n\n(** The problem with that specification is how it handles the default\n    element [d]: the specification would incorrectly require [elements\n    t] to contain a binding [(k, d)] for all keys [k] unbound in\n    [t]. That would force [elements t] to be infinitely long, since\n    it would have to contain a binding for every natural number. We can\n    observe this problem right away if we begin the proof: *)\n\nTheorem elements_complete_broken : elements_complete_broken_spec.\nProof.\n  unfold elements_complete_broken_spec. intros. induction t.\n  - (* t = E *) simpl.\n    (** We have nothing to work with, since [elements E] is [[]]. *)\nAbort.\n\n(** The solution is to check first to see whether [k] is bound in [t].\n    Only bound keys need be in the list of elements: *)\n\nDefinition elements_complete_spec :=\n  forall (V : Type) (k : key) (v d : V) (t : tree V),\n    BST t ->\n    bound k t = true ->\n    lookup d k t = v ->\n    In (k, v) (elements t).\n\n(** **** Exercise: 3 stars, standard (elements_complete)  *)\n\n(** Prove that [elements] is complete. Proceed by induction on [t]. *)\n\nTheorem elements_complete : elements_complete_spec.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** The specification for correctness likewise mentions that the\n    key must be bound: *)\n\nDefinition elements_correct_spec :=\n  forall (V : Type) (k : key) (v d : V) (t : tree V),\n    BST t ->\n    In (k, v) (elements t) ->\n    bound k t = true /\\ lookup d k t = v.\n\n(** Proving correctness requires more work than completeness.\n\n    [BST] uses [ForallT] to say that all nodes in the left/right\n    subtree have smaller/greater keys than the root.  We need to\n    relate [ForallT], which expresses that all nodes satisfy a\n    property, to [Forall], which expresses that all list elements\n    satisfy a property.\n\n    We begin with this lemma about [Forall], which is missing from the\n    standard library. *)\n\nLemma Forall_app : forall (A: Type) (P : A -> Prop) (l1 l2 : list A),\n    Forall P l1 -> Forall P l2 -> Forall P (l1 ++ l2).\nProof.\n  induction l1; intros; simpl; auto; inv H; constructor; auto.\nQed.\n\n(** **** Exercise: 2 stars, standard (elements_preserves_forall)  *)\n\n(** Prove that if a property [P] holds of every node in a tree [t],\n    then that property holds of every pair in [elements t]. Proceed\n    by induction on [t].\n\n    There is a little mismatch between the type of [P] in [ForallT]\n    and the type of the property accepted by [Forall], so we have to\n    _uncurry_ [P] when we pass it to [Forall]. (See [Poly] for\n    more about uncurrying.) The single quote used below is the Coq\n    syntax for doing a pattern match in the function arguments. *)\n\nDefinition uncurry {X Y Z : Type} (f : X -> Y -> Z) '(a, b) :=\n  f a b.\n\nHint Transparent uncurry.\n\nLemma elements_preserves_forall : forall (V : Type) (P : key -> V -> Prop) (t : tree V),\n    ForallT P t ->\n    Forall (uncurry P) (elements t).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (elements_preserves_relation)  *)\n\n(** Prove that if all the keys in [t] are in a relation [R] with a\n    distinguished key [k'], then any key [k] in [elements t] is also\n    related by [R] to [k']. For example, [R] could be [<], in which\n    case the lemma says that if all the keys in [t] are less than\n    [k'], then all the keys in [elements t] are also less than\n    [k'].\n\n    Hint: you don't need induction.  Immediately look for a way\n    to use [elements_preserves_forall] and library theorem\n    [Forall_forall]. *)\n\nLemma elements_preserves_relation :\n  forall (V : Type) (k k' : key) (v : V) (t : tree V) (R : key -> key -> Prop),\n    ForallT (fun y _ => R y k') t\n    -> In (k, v) (elements t)\n    -> R k k'.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, standard (elements_correct)  *)\n\n(** Prove that [elements] is correct. Proceed by induction on the\n    evidence that [t] is a BST. *)\n\nTheorem elements_correct : elements_correct_spec.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** The inverses of completeness and correctness also should hold:\n\n    - inverse completeness: if a binding is not in [t] then it's not\n      in [elements t].\n\n    - inverse correctness: if a binding is not in [elements t] then\n      it's not in [t].\n\n    Let's prove that they do. *)\n\n(** **** Exercise: 2 stars, advanced (elements_complete_inverse)  *)\n\n(** This inverse doesn't require induction.  Look for a way to use\n    [elements_correct] to quickly prove the result. *)\n\nTheorem elements_complete_inverse :\n  forall (V : Type) (k : key) (v : V) (t : tree V),\n    BST t ->\n    bound k t = false ->\n    ~ In (k, v) (elements t).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (elements_correct_inverse)  *)\n\n(** Prove the inverse.  First, prove this helper lemma by induction on\n    [t]. *)\n\nLemma bound_value : forall (V : Type) (k : key) (t : tree V),\n    bound k t = true -> exists v, forall d, lookup d k t = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Prove the main result.  You don't need induction. *)\n\nTheorem elements_correct_inverse :\n  forall (V : Type) (k : key) (t : tree V),\n    BST t ->\n    (forall v, ~ In (k, v) (elements t)) ->\n    bound k t = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Part 2: Sorted (Advanced) *)\n\n(** We want to show that [elements] is sorted by keys.  We follow a\n    proof technique contributed by Lydia Symmons et al.*)\n\n(** **** Exercise: 3 stars, advanced (sorted_app)  *)\n\n(** Prove that inserting an intermediate value between two lists\n    maintains sortedness. Proceed by induction on the evidence\n    that [l1] is sorted. *)\n\nLemma sorted_app: forall l1 l2 x,\n  Sort.sorted l1 -> Sort.sorted l2 ->\n  Forall (fun n => n < x) l1 -> Forall (fun n => n > x) l2 ->\n  Sort.sorted (l1 ++ x :: l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (sorted_elements)  *)\n\n(** The keys in an association list are the first elements of every\n    pair: *)\n\nDefinition list_keys {V : Type} (lst : list (key * V)) :=\n  map fst lst.\n\n(** Prove that [elements t] is sorted by keys. Proceed by induction\n    on the evidence that [t] is a BST. *)\n\nTheorem sorted_elements : forall (V : Type) (t : tree V),\n    BST t -> Sort.sorted (list_keys (elements t)).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Part 3: No Duplicates (Advanced and Optional) *)\n\n(** We want to show that [elements t] contains no duplicate\n    bindings. Tree [t] itself cannot contain any duplicates, so the\n    list that [elements] produces shouldn't either. The standard\n    library already contains a helpful inductive proposition,\n    [NoDup]. *)\n\nPrint NoDup.\n\n(** The library is missing a theorem, though, about [NoDup] and [++].\n    To state that theorem, we first need to formalize what it means\n    for two lists to be disjoint: *)\n\nDefinition disjoint {X:Type} (l1 l2: list X) := forall (x : X),\n    In x l1 -> ~ In x l2.\n\n(** **** Exercise: 3 stars, advanced, optional (NoDup_append)  *)\n\n(** Prove that if two lists are disjoint, appending them preserves\n    [NoDup].  Hint: You might already have proved this theorem in an\n    advanced exercise in [IndProp]. *)\n\nLemma NoDup_append : forall (X:Type) (l1 l2: list X),\n  NoDup l1 -> NoDup l2 -> disjoint l1 l2 ->\n  NoDup (l1 ++ l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (elements_nodup_keys)  *)\n\n(** Prove that there are no duplicate keys in the list returned\n    by [elements]. Proceed by induction on the evidence that [t] is a\n    BST. Make use of library theorems about [map] as needed. *)\n\nTheorem elements_nodup_keys : forall (V : Type) (t : tree V),\n    BST t ->\n    NoDup (list_keys (elements t)).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** That concludes the proof of correctness of [elements]. *)\n\n(* ################################################################# *)\n(** * A Faster [elements] Implementation *)\n\n(** The implemention of [elements] is inefficient because of how\n    it uses the [++] operator.  On a balanced tree its running time is\n    linearithmic, because it does a linear number of concatentations\n    at each level of the tree. On an unbalanced tree it's quadratic\n    time.  Here's a tail-recursive implementation than runs in linear\n    time, regardless of whether the tree is balanced: *)\n\nFixpoint fast_elements_tr {V : Type} (t : tree V)\n         (acc : list (key * V)) : list (key * V) :=\n  match t with\n  | E => acc\n  | T l k v r => fast_elements_tr l ((k, v) :: fast_elements_tr r acc)\n  end.\n\nDefinition fast_elements {V : Type} (t : tree V) : list (key * V) :=\n  fast_elements_tr t [].\n\n(** **** Exercise: 3 stars, standard (fast_elements_eq_elements)  *)\n\n(** Prove that [fast_elements] and [elements] compute the same\n    function. *)\n\nLemma fast_elements_tr_helper :\n  forall (V : Type) (t : tree V) (lst : list (key * V)),\n    fast_elements_tr t lst = elements t ++ lst.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma fast_elements_eq_elements : forall (V : Type) (t : tree V),\n    fast_elements t = elements t.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** Since the two implementations compute the same function, all\n    the results we proved about the correctness of [elements]\n    also hold for [fast_elements].  For example: *)\n\nCorollary fast_elements_correct :\n  forall (V : Type) (k : key) (v d : V) (t : tree V),\n    BST t ->\n    In (k, v) (fast_elements t) ->\n    bound k t = true /\\ lookup d k t = v.\nProof.\n  intros. rewrite fast_elements_eq_elements in *.\n  apply elements_correct; assumption.\nQed.\n\n(** This corollary illustrates a general technique:  prove the correctness\n    of a simple, slow implementation; then prove that the slow version\n    is functionally equivalent to a fast implementation.  The proof of\n    correctness for the fast implementation then comes \"for free\". *)\n\n(* ################################################################# *)\n(** * An Algebraic Specification of [elements] *)\n\n(** The verification of [elements] we did above did not adhere to the\n    algebraic specification approach, which would suggest that we look\n    for equations of the form\n\n      elements empty_tree = ...\n      elements (insert k v t) = ... (elements t) ...\n\n    The first of these is easy; we can trivially prove the following:\n    *)\n\nLemma elements_empty : forall (V : Type),\n    @elements V empty_tree = [].\nProof.\n  intros. simpl. reflexivity.\nQed.\n\n(** But for the second equation, we have to express the result of\n    inserting [(k, v)] into the elements list for [t], accounting for\n    ordering and the possibility that [t] may already contain a pair\n    [(k, v')] which must be replaced.  The following rather ugly\n    function will do the trick: *)\n\nFixpoint kvs_insert {V : Type} (k : key) (v : V) (kvs : list (key * V)) :=\n  match kvs with\n  | [] => [(k, v)]\n  | (k', v') :: kvs' =>\n    if k <? k' then (k, v) :: kvs\n    else if k >? k' then (k', v') :: kvs_insert k v kvs'\n         else (k, v) :: kvs'\n  end.\n\n(** That's not satisfactory, because the definition of\n    [kvs_insert] is so complex. Moreover, this equation doesn't tell\n    us anything directly about the overall properties of [elements t]\n    for a given tree [t].  Nonetheless, we can proceed with a rather\n    ugly verification. *)\n\n(** **** Exercise: 3 stars, standard, optional (kvs_insert_split)  *)\nLemma kvs_insert_split :\n  forall (V : Type) (v v0 : V) (e1 e2 : list (key * V)) (k k0 : key),\n    Forall (fun '(k',_) => k' < k0) e1 ->\n    Forall (fun '(k',_) => k' > k0) e2 ->\n    kvs_insert k v (e1 ++ (k0,v0):: e2) =\n    if k <? k0 then\n      (kvs_insert k v e1) ++ (k0,v0)::e2\n    else if k >? k0 then\n           e1 ++ (k0,v0)::(kvs_insert k v e2)\n         else\n           e1 ++ (k,v)::e2.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (kvs_insert_elements)  *)\nLemma kvs_insert_elements : forall (V : Type) (t : tree V),\n    BST t ->\n    forall (k : key) (v : V),\n      elements (insert k v t) = kvs_insert k v (elements t).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Model-based Specifications *)\n\n(** At the outset, we mentioned studying two techniques for\n    specifying the correctness of BST operations in this chapter.  The\n    first was algebraic specification.\n\n    Another approach to proving correctness of search trees is to\n    relate them to our existing implementation of functional partial\n    maps, as developed in [Maps]. To prove the correctness of a\n    search-tree algorithm, we can prove:\n\n    - Any search tree corresponds to some functional partial map,\n      using a function or relation that we write down.\n\n    - The [lookup] operation on trees gives the same result as the\n      [find] operation on the corresponding map.\n\n    - Given a tree and corresponding map, if we [insert] on the tree\n      and [update] the map with the same key and value, the resulting\n      tree and map are in correspondence.\n\n    This approach is sometimes called _model-based specification_: we\n    show that our implementation of a data type corresponds to a more\n    more abstract _model_ type that we already understand. To reason\n    about programs that use the implementation, it suffices to reason\n    about the behavior of the abstract type, which may be\n    significantly easier.  For example, we can take advantage of laws\n    that we proved for the abstract type, like [update_eq] for\n    functional maps, without having to prove them again for the\n    concrete tree type.\n\n    We also need to be careful here, because the type of functional\n    maps as defined in [Maps] do not actually behave quite like\n    our tree-based maps. For one thing, functional maps can be defined\n    on an infinite number of keys, and there is no mechanism for\n    enumerating over the key set. To maintain correspondence with our\n    finite trees, we need to make sure that we consider only\n    functional maps built by finitely many applications of constructor\n    functions ([empty] and [update]). Also, thanks to functional\n    extensionality, functional maps obey stronger equality laws than\n    our trees do (as we investigated in the [direct_equalities]\n    exercise above), so we should not be misled into thinking that\n    every fact we can prove about abstract maps necessarily holds for\n    concrete ones.\n\n    Compared to the algebraic-specification approach described earlier\n    in this chapter, the model-based approach can save some proof\n    effort, especially if we already have a well-developed theory for\n    the abstract model type.  On the other hand, we have to give an\n    explicit _abstraction_ relation between trees and maps, and show\n    that it is maintained by all operations. In the end, about the\n    same amount of work is needed to show correctness, though the work\n    shows up in different places depending on how the abstraction\n    relation is defined. *)\n\n(** We now give a model-based specification for trees in terms\n    of functional partial maps. It is based on a simple abstraction\n    relation that builds a functional map element by element. *)\n\nFixpoint map_of_list {V : Type} (el : list (key * V)) : partial_map V :=\n  match el with\n  | [] => empty\n  | (k, v) :: el' => update (map_of_list el') k v\n  end.\n\nDefinition Abs {V : Type} (t : tree V) : partial_map V :=\n  map_of_list (elements t).\n\n(** In general, model-based specifications may use an abstraction\n    relation, allowing each concrete value to be related to multiple\n    abstract values.  But in this case a simple abstraction _function_\n    will do, assigning a unique abstract value to each concrete\n    one. *)\n\n(** One small difference between trees and functional maps is that\n    applying the latter returns an [option V] which might be [None],\n    whereas [lookup] returns a default value if key is not bound\n    lookup fails.  We can easily provide a function on functional\n    partial maps having the latter behavior. *)\n\nDefinition find {V : Type} (d : V) (k : key) (m : partial_map V) : V :=\n  match m k with\n  | Some v => v\n  | None => d\n  end.\n\n(** We also need a [bound] operation on maps. *)\n\nDefinition map_bound {V : Type} (k : key) (m : partial_map V) : bool :=\n  match m k with\n  | Some _ => true\n  | None => false\n  end.\n\n(** We now proceed to prove that each operation preserves (or establishes)\n    the abstraction relationship in an appropriate way:\n\n    concrete        abstract\n    --------        --------\n    empty_tree      empty\n    bound           map_bound\n    lookup          find\n    insert          update\n*)\n\n(** The following lemmas will be useful, though you are not required\n    to prove them. They can all be proved by induction on the list. *)\n\n(** **** Exercise: 2 stars, standard, optional (in_fst)  *)\nLemma in_fst : forall (X Y : Type) (lst : list (X * Y)) (x : X) (y : Y),\n    In (x, y) lst -> In x (map fst lst).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (in_map_of_list)  *)\nLemma in_map_of_list : forall (V : Type) (el : list (key * V)) (k : key) (v : V),\n    NoDup (map fst el) ->\n    In (k,v) el -> (map_of_list el) k = Some v.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (not_in_map_of_list)  *)\nLemma not_in_map_of_list : forall (V : Type) (el : list (key * V)) (k : key),\n    ~ In k (map fst el) -> (map_of_list el) k = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nLemma empty_relate : forall (V : Type),\n    @Abs V empty_tree = empty.\nProof.\n  reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (bound_relate)  *)\n\nTheorem bound_relate : forall (V : Type) (t : tree V) (k : key),\n    BST t ->\n    map_bound k (Abs t) = bound k t.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (lookup_relate)  *)\n\nLemma lookup_relate : forall (V : Type) (t : tree V) (d : V) (k : key),\n    BST t -> find d k (Abs t) = lookup d k t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (insert_relate)  *)\nLemma insert_relate : forall (V : Type) (t : tree V) (k : key) (v : V),\n  BST t -> Abs (insert k v t) = update (Abs t) k v.\nProof.\n  (* TODO: find a direct proof that doesn't rely on [kvs_insert_elements] *)\n    unfold Abs.\n  intros.\n  rewrite kvs_insert_elements; auto.\n  remember (elements t) as l.\n  clear -l. (* clear everything not about [l] *)\n  (* Hint: proceed by induction on [l]. *)\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The previous three lemmas are in essence saying that the following\n    diagrams commute.\n\n             bound k\n      t -------------------+\n      |                    |\n  Abs |                    |\n      V                    V\n      m -----------------> b\n           map_bound k\n\n            lookup d k\n      t -----------------> v\n      |                    |\n  Abs |                    | Some\n      V                    V\n      m -----------------> Some v\n             find d k\n\n            insert k v\n      t -----------------> t'\n      |                    |\n  Abs |                    | Abs\n      V                    V\n      m -----------------> m'\n            update' k v\n\n    Where we define:\n\n      update' k v m = update m k v\n\n*)\n\n(** Functional partial maps lack a way to extract or iterate\n    over their elements, so we cannot give an analogous abstract\n    operation for [elements]. Instead, we can prove this trivial\n    little lemma. *)\n\nLemma elements_relate : forall (V : Type) (t : tree V),\n  BST t ->\n  map_of_list (elements t) = Abs t.\nProof.\n  unfold Abs. intros. reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * An Alternative Abstraction Relation (Optional, Advanced) *)\n\n(** There is often more than one way to specify a suitable abstraction\n    relation between given concrete and abstract datatypes. The\n    following exercises explore another way to relate search trees to\n    functional partial maps without using [elements] as an\n    intermediate step.\n\n    We extend our definition of functional partial maps by adding a\n    new primitive for combining two partial maps, which we call\n    [union].  Our intention is that it only be used to combine maps\n    with disjoint key sets; to keep the operation symmetric, we make\n    the result be undefined on any key they have in common.  *)\n\nDefinition union {X} (m1 m2: partial_map X) : partial_map X :=\n  fun k =>\n    match (m1 k, m2 k) with\n    | (None, None) => None\n    | (None, Some v) => Some v\n    | (Some v, None) => Some v\n    | (Some _, Some _) => None\n    end.\n\n(** We can prove some simple properties of lookup and update on unions,\n    which will prove useful later. *)\n\n(** **** Exercise: 2 stars, standard, optional (union_collapse)  *)\nLemma union_left : forall {X} (m1 m2: partial_map X) k,\n    m2 k = None -> union m1 m2 k = m1 k.\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma union_right : forall {X} (m1 m2: partial_map X) k,\n    m1 k = None ->\n    union m1 m2 k = m2 k.\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma union_both : forall {X} (m1 m2 : partial_map X) k v1 v2,\n    m1 k = Some v1 ->\n    m2 k = Some v2 ->\n    union m1 m2 k = None.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (union_update)  *)\nLemma union_update_right : forall {X} (m1 m2: partial_map X) k v,\n    m1 k = None ->\n    update (union m1 m2) k v = union m1 (update m2 k v).\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma union_update_left : forall {X} (m1 m2: partial_map X) k v,\n    m2 k = None ->\n    update (union m1 m2) k v = union (update m1 k v) m2.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We can now write a direct conversion function from trees to maps\n    based on the structure of the tree, and prove a basic property\n    preservation result. *)\n\nFixpoint map_of_tree {V : Type} (t: tree V) : partial_map V :=\n  match t with\n  | E => empty\n  | T l k v r => update (union (map_of_tree l) (map_of_tree r)) k v\n  end.\n\n(** **** Exercise: 3 stars, advanced, optional (map_of_tree_prop)  *)\nLemma map_of_tree_prop : forall (V : Type) (P : key -> V -> Prop) (t : tree V),\n    ForallT P t ->\n    forall k v, (map_of_tree t) k = Some v ->\n           P k v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Finally, we define our new abstraction function, and prove the\n    same lemmas as before. *)\n\nDefinition Abs' {V : Type} (t: tree V) : partial_map V :=\n  map_of_tree t.\n\nLemma empty_relate' : forall (V : Type),\n    @Abs' V empty_tree = empty.\nProof.\n  reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, advanced, optional (bound_relate')  *)\nTheorem bound_relate' : forall (V : Type) (t : tree V) (k : key),\n    BST t ->\n    map_bound k (Abs' t) = bound k t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (lookup_relate')  *)\nLemma lookup_relate' : forall (V : Type) (d : V) (t : tree V) (k : key),\n    BST t -> find d k (Abs' t) = lookup d k t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (insert_relate')  *)\nLemma insert_relate' : forall (V : Type) (k : key) (v : V) (t : tree V),\n   BST t -> Abs' (insert k v t) = update (Abs' t) k v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The [elements_relate] lemma, which was trivial for our previous [Abs]\n    function, is considerably harder this time.  We suggest starting with\n    an auxiliary lemma. *)\n\n(** **** Exercise: 3 stars, advanced, optional (map_of_list_app)  *)\nLemma map_of_list_app : forall (V : Type) (el1 el2: list (key * V)),\n   disjoint (map fst el1) (map fst el2) ->\n   map_of_list (el1 ++ el2) = union (map_of_list el1) (map_of_list el2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (elements_relate')  *)\nLemma elements_relate' : forall (V : Type) (t : tree V),\n  BST t ->\n  map_of_list (elements t) = Abs' t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Efficiency of Search Trees *)\n\n(** All the theory we've developed so far has been about correctness.\n    But the reason we use binary search trees is that they are\n    efficient.  That is, if there are [N] elements in a (reasonably\n    well balanced) BST, each insertion or lookup takes about [log N]\n    time.\n\n    What could go wrong?\n\n     1. The search tree might not be balanced.  In that case, each\n        insertion or lookup will take as much as linear time.\n\n        - SOLUTION: use an algorithm that ensures the trees stay\n          balanced.  We'll do that in [Redblack].\n\n     2. Our keys are natural numbers, and Coq's [nat] type takes linear\n        time per comparison.  That is, computing (j <? k) takes time\n        proportional to the value of [k-j].\n\n        - SOLUTION: represent keys by a data type that has a more\n          efficient comparison operator.  We used [nat] in this chapter\n          because it's something easy to work with.\n\n     3. There's no notion of running time in Coq.  That is, we can't\n        say what it means that a Coq function \"takes N steps to\n        evaluate.\"  Therefore, we can't prove that binary search trees\n        are efficient.\n\n        - SOLUTION 1: Don't prove (in Coq) that they're efficient;\n          just prove that they are correct.  Prove things about their\n          efficiency the old-fashioned way, on pencil and paper.\n\n        - SOLUTION 2: Prove in Coq some facts about the height of the\n          trees, which have direct bearing on their efficiency.  We'll\n          explore that in [Redblack].\n\n        - SOLUTION 3: Apply bleeding-edge frameworks for reasoning\n          about run-time of programs represented in Coq.\n\n      4. Our functions in Coq are models of implementations in \"real\"\n         programming languages.  What if the real implementations\n         differ from the Coq models?\n\n         - SOLUTION: Use Coq's [extraction] feature to derive the real\n\t   implementation (in Ocaml or Haskell) automatically from the\n\t   Coq function.  Or, use Coq's [Compute] or [Eval\n\t   native_compute] feature to compile and run the programs\n\t   efficiently inside Coq.  We'll explore [extraction] in a\n\t   [Extract]. *)\n\n(* 2020-08-07 17:08 *)\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/vfa/SearchTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8856314798554444, "lm_q1q2_score": 0.7491932595055629}}
{"text": "Require Import Arith.\nRequire Import List.\nExport ListNotations.\n\n(* LANGAGES FORMELS *)\n\n(* EXERCICE *)\n(* Écrire la fonction \"lgr\" qui calcule la longueur d'une liste de nat (et donc de type list nat) *)\nFixpoint lgr (l : list nat) := match l with [] => 0 | _::rl => 1 + (lgr rl) end.\n\nExample ex_lgr : (lgr (1::2::3::4::5::[])) = 5.\nProof. simpl. reflexivity. Qed.\n\n(* EXERCICE *)\n(* Écrire la fonction \"mir\" qui calcule le miroir d'une liste de nat *)\nFixpoint mir (l : list nat) := match l with [] => [] | e::rl => (mir rl) ++ e::[] end.\n\nExample ex_mir : (mir (1::2::3::4::5::[])) = 5::4::3::2::1::[].\nProof. simpl. reflexivity. Qed.\n\n\n(* EXERCICE *)\n(* Exprimer et prouver que le miroir d'une liste à laquelle on a ajouté un élément en tête\n   est le miroir de la liste concaténé à la liste constituée de juste cet élément *)\nGoal forall l : list nat, forall a : nat, rev (a :: l) = (rev l) ++ a::[].\nProof.\n  intro l0.\n  intro a0.\n  destruct l0. (* pas besoin d'hyp. d'induction *)\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(* EXERCICE SUJET A *)\nInductive btree : Type :=\n| F : nat -> btree\n| N : btree -> btree -> btree\n.\n\n(* Écrire la fonction \"bnbf\" qui calcule le nombre de feuilles d'un tel arbre *)\nFixpoint bnbf t :=\n  match t with\n  | F e => 1\n  | N t1 t2 => (bnbf t1) + (bnbf t2)\n  end.\n\n(* Écrire la fonction \"bnbn\" qui calcule le nombre de noeuds d'un tel arbre *)\nFixpoint bnbn t :=\n  match t with\n  | F e => 0\n  | N t1 t2 => 1 + (bnbn t1) + (bnbn t2)\n  end.\n\n(* Écrire la fonction \"bsumval\" qui calcule la somme des valeurs contenues dans l'arbre *)\nFixpoint bsumval t :=\n  match t with\n  | F e => e\n  | N t1 t2 => (bsumval t1) + (bsumval t2)\n  end.\n\n(* Écrire la fonction \"bajout\" qui ajoute un élément dans un arbre *)\nFixpoint bajout e t : btree :=\n  match t with\n  | F n => N t (F e)\n  | N t1 t2 => N (bajout e t1) t2\n  end.\n\n(* exemples *)\n(* Définir l'arbre \"ab1\" :  o\n                           / \\\n                          o   2\n                         / \\\n                        1   o\n                           / \\\n                          o   3\n                         / \\\n                        4   5\n*)\n\nDefinition ab1 := N (N (F 1) (N (N (F 4) (F 5)) (F 3))) (F 2).\n\nExample ex_bnbf_ab1 : (bnbf ab1) = 5.\nProof. cbv. reflexivity. Qed.\n\nExample ex_bnbn_ab1 : (bnbn ab1) = 4.\nProof. cbv. reflexivity. Qed.\n\nExample ex_bsumval_ab1 : (bsumval ab1) = 15.\nProof. cbv. reflexivity. Qed.\n\nExample ex_bajout_ab1 : bnbf (bajout 10 ab1) = 1 + bnbf ab1.\nProof. cbv. reflexivity. Qed.\n\n\n\n(* EXERCICE SUJET B *)\nInductive ctree : Type :=\n| V : nat -> ctree\n| R : ctree -> ctree -> ctree\n| T : ctree -> ctree -> ctree -> ctree\n.\n\n(* Ecrire la fonction \"cnbf\" qui calcule le nombre de feuilles d'un tel arbre *)\nFixpoint cnbf t :=\n  match t with\n  | V e => 1\n  | R t1 t2 => (cnbf t1) + (cnbf t2)\n  | T t1 t2 t3 => (cnbf t1) + (cnbf t2) + (cnbf t3)\n  end.\n\n(* Ecrire la fonction \"cnbn\" qui calcule le nombre de noeuds d'un tel arbre *)\nFixpoint cnbn t :=\n  match t with\n  | V e => 0\n  | R t1 t2 => 1 + (cnbn t1) + (cnbn t2)\n  | T t1 t2 t3 => 1 + (cnbn t1) + (cnbn t2) + (cnbn t3)\n  end.\n\n\n(* Ecrire la fonction \"csumval\" qui calcule la somme des valeurs contenues dans l'arbre *)\nFixpoint csumval t :=\n  match t with\n  | V e => e\n  | R t1 t2 => (csumval t1) + (csumval t2)\n  | T t1 t2 t3 => (csumval t1) + (csumval t2) + (csumval t3)\n  end.\n\n\n(* Ecrire la fonction \"bajout\" qui ajoute un élément dans un arbre *)\nFixpoint cajout e t : ctree :=\n  match t with\n  | V n => R t (V e)\n  | R t1 t2 => R (cajout e t1) t2\n  | T t1 t2 t3 => T (cajout e t1) t2 t3\n  end.\n\n(* exemples *)\n(* Définir l'arbre \"ac1\" : o\n                           / \\\n                          o   7\n                         /|\\\n                        1 2 o\n                           /|\\\n                          o 6 3\n                         / \\\n                        4   5\n*)\nDefinition ac1 := R (T (V 1) (V 2) (T (R (V 4) (V 5)) (V 6) (V 3))) (V 2).\n\nExample ex_cnbf_ab1 : (bnbf ab1) = 5.\nProof. cbv. reflexivity. Qed.\n\nExample ex_cnbn_ab1 : (bnbn ab1) = 4.\nProof. cbv. reflexivity. Qed.\n\nExample ex_csumval_ab1 : (bsumval ab1) = 15.\nProof. cbv. reflexivity. Qed.\n\nExample ex_cajout_ab1 : bnbf (bajout 10 ab1) = 1 + bnbf ab1.\nProof. cbv. reflexivity. Qed.\n\n\n\n(* LOGIQUE CLASSIQUE *)\n\nContext (A B C D : Prop).\n\n(* EXERCICE *)\n(* Prouver les lemmes suivants (permutation et renommage dans les deux sujets) *)\nLemma LC1 : ((A \\/ B) -> C) -> ((A -> C) /\\ (B -> C)).\nProof.\n  intro Himp.\n  split.\n  - intro Ha. apply Himp. left. assumption.\n  - intro Hb. apply Himp. right. assumption.\nQed.\n\n\nLemma LC2 : (A \\/ B) -> ((A -> B) -> B).\nProof.\n  intro Hou.\n  intro Hab.\n  destruct Hou. (* on l'a fait 10 fois... *)\n  - apply Hab. assumption.\n  - assumption.\nQed.\n\n\n(* EXERCICE *)\n(* Exprimer et montrer que la longueur de la concaténation de deux listes de nat est la somme des longueurs des concaténés*)\nLemma concat_compat : forall l1 l2 : list nat, lgr (l1 ++ l2) = (lgr l1) + (lgr l2).\nProof.\n  intro l1.\n  intro l2.\n  induction l1  as [| a l1' IHl1']. (* ou avec noms automatiques *)\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1'. reflexivity.\nQed.\n\n(* EXERCICE *)\n(* Montrer que la longueur d'une liste c'est la longueur de son miroir *)\n(* On pourra avoir besoin de la commutativité de l'addition, donnée par le lemme Nat.add_comm, et dulemme précédent *)\n\nCheck Nat.add_comm.\n\nLemma lgrmir_compat : forall l : list nat,  lgr l = lgr (mir l).\nProof.\n  induction l as [| a l' IHl']. (* ou avec noms automatiques  *)\n  - simpl. reflexivity.\n  - simpl.\n    rewrite IHl'.\n    rewrite (concat_compat (mir l') (a::[])). (* ou bien avec l'étape intermédiaire \"pose\" etc. *)\n    simpl.\n    rewrite (Nat.add_comm (lgr (mir l')) 1). (* oups ça n'est pas dans le bon sens *)\n    simpl.\n    reflexivity.\nQed.\n\n(* EXERCICE *)\n(* Exprimer et montrer que l'addition est associative, c'est-à-dire qu'on a (x + y) + z = x + (y + z) pour x, y et z de type nat. *)\n(* rappel : ce qui est noté x + y + z (sans parenthèses) est en fait (x + y) + z *)\nLemma p_assoc : forall x y z : nat, x + y + z = x + (y + z).\n  intro x0.\n  intro y0.\n  intro z0.\n  induction x0 as [| x0' IHx0']. (* ou avec noms automatiques *)\n  - simpl. reflexivity.\n  - simpl. rewrite IHx0'. reflexivity.\nQed.\n\n\n(* EXERCICE SUJET A *)\n(* Exprimer et montrer que la somme des valeurs d'un arbre t à laquelle on additionne un nat e est égale à la somme des valeurs de l'arbre t dans lequel on a ajouté un élément de valeur e. *)\n\n(* On pourra avoir besoin de la commutativité de l'addition, donnée par le lemme Nat.add_comm, et de l'associativité démontrée auparavant. *)\n\nCheck Nat.add_comm.\n\nLemma bsumaj_compat : forall t, forall e, bsumval t + e = bsumval (bajout e t).\n  intro t0.\n  intro e0. \n  induction t0 as [n | t1 IHt1 t2 IHt2] . (* ou avec noms automatiques *)\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHt1. (* on a à droite (a + b) + c et on veut (a + c) + b il faut donc 1) déplacer les parenthèses, permuter, replacer les parenthèses *)\n    rewrite (p_assoc (bsumval t1) e0 (bsumval t2)).\n    rewrite (Nat.add_comm e0 (bsumval t2)).\n    rewrite (p_assoc (bsumval t1) (bsumval t2) e0).\n    reflexivity.\nQed.\n\n(* EXERCICE SUJET B *)\n(* Exprimer et montrer que la somme des valeurs d'un arbre t à laquelle on additionne un nat e est égale à la somme des valeurs de l'arbre t dans lequel on a ajouté un élément de valeur e. *)\n\n(* On pourra avoir besoin de la commutativité de l'addition, donnée par le lemme Nat.add_comm, et de l'associativité démontrée auparavant. *)\n\nCheck Nat.add_comm.\n\n\n(* La même avec une étape en plus puisqu'on a 3 constructeurs pour les arbres *)\nLemma csumaj_compat : forall t, forall e, csumval t + e = csumval (cajout e t).\n  intro t0.\n  intro e0.\n  induction t0 as [n | t1 IHt1 t2 IHt2 | t1 IHt1 t2 IHt2 t3 IHt3]. (* ou avec noms automatiques *)\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHt1.\n    rewrite (p_assoc (csumval t1) e0 (csumval t2)).\n    rewrite (Nat.add_comm e0 (csumval t2)).\n    rewrite (p_assoc (csumval t1) (csumval t2) e0).\n    reflexivity.\n  - simpl. rewrite <- IHt1. (* on a ((a + b) + c) + d et on veut ((a + c )+ d) + b, on déplace les parenthèses et on commute en conséquence *)\n    rewrite (p_assoc (csumval t1 + e0) (csumval t2) (csumval t3)). (* (a + b) + (c + d) *)\n    rewrite (p_assoc (csumval t1) e0 (csumval t2 + csumval t3)).   (* a + (b + (c + d)) *)\n    rewrite (Nat.add_comm e0 (csumval t2 + csumval t3)).           (* on permute *)\n    rewrite (p_assoc (csumval t1) (csumval t2) (csumval t3)).      (* on remonte les parenthèses à gauche... *)\n    rewrite (p_assoc (csumval t1) (csumval t2 + csumval t3) e0).\n    reflexivity.\nQed.\n\n\n", "meta": {"author": "KevinFroissart", "repo": "coqTP", "sha": "f050bf832a49be9262aea70f4844a7394d112817", "save_path": "github-repos/coq/KevinFroissart-coqTP", "path": "github-repos/coq/KevinFroissart-coqTP/coqTP-f050bf832a49be9262aea70f4844a7394d112817/liflf/tpnote-correction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7491932551796471}}
{"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\nEval compute in (next_weekday friday).\n   (* ==> monday : day *)\nEval compute in (next_weekday (next_weekday saturday)).\n   (* ==> tuesday : day *)\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\nExample test_orb1: (orb true false) = true.\nProof. reflexivity. Qed.\nExample test_orb2: (orb false false) = false.\nProof. reflexivity. Qed.\nExample test_orb3: (orb false true) = true.\nProof. reflexivity. Qed.\nExample test_orb4: (orb true true) = true.\nProof. reflexivity. Qed.\\u00e5", "meta": {"author": "sguzman", "repo": "CoqRepo", "sha": "e802df1540b7cff7dad5731c6abfcbf8e669f44e", "save_path": "github-repos/coq/sguzman-CoqRepo", "path": "github-repos/coq/sguzman-CoqRepo/CoqRepo-e802df1540b7cff7dad5731c6abfcbf8e669f44e/days.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7491932321449188}}
{"text": "Require Import Nat Arith.\n\nInductive Lst : Type :=  nil : Lst | cons : nat -> Lst -> Lst.\n\nScheme Equality for Lst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : Lst) : nat\n           := match len_arg0 with\n              | nil => 0\n              | cons x y => plus 1 (len y)\n              end.\n\nFixpoint butlast (butlast_arg0 : Lst) : Lst\n           := match butlast_arg0 with\n              | nil => nil\n              | cons n x => if Lst_beq x nil then nil else cons n (butlast x)\n              end.\n\nTheorem theorem0 : forall (x : Lst) (n : nat), eq (Lst_beq (cons n x) nil) false.\nProof.\n  reflexivity.\nQed.\n\nTheorem theorem1 : forall (x : Lst) (n : nat), eq (plus 1 (len (butlast (cons n x)))) (len (cons n x)).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. destruct (Lst_beq x nil) eqn:?.\n    + destruct x.\n      * reflexivity.\n      * discriminate.\n    + simpl. simpl in IHx. rewrite Heqb in IHx. simpl in IHx. rewrite IHx. reflexivity.\nQed.\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/testing_results_initial/old_script_testing/NoLfindCall/lia/list_len_butlast.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118213, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7491620535238622}}
{"text": "Require Import rt.util.tactics.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\n(* Induction lemmas for natural numbers. *)\nSection NatInduction.\n  \n  Lemma strong_ind :\n    forall (P: nat -> Prop),\n      (forall n, (forall k, k < n -> P k) -> P n) ->\n      forall n, P n.\n  Proof.\n    intros P ALL n; apply ALL.\n    induction n; first by ins; apply ALL.\n    intros k LTkSn; apply ALL.\n    by intros k0 LTk0k; apply IHn, leq_trans with (n := k).\n  Qed.\n\n  Lemma leq_as_delta :\n    forall x1 (P: nat -> Prop),\n      (forall x2, x1 <= x2 -> P x2) <->\n      (forall delta, P (x1 + delta)).\n  Proof.\n    ins; split; last by intros ALL x2 LE; rewrite -(subnK LE) addnC; apply ALL.\n    {\n      intros ALL; induction delta.\n        by rewrite addn0; apply ALL, leqnn. \n        by apply ALL; rewrite -{1}[x1]addn0; apply leq_add; [by apply leqnn | by ins]. \n    }\n  Qed.\n  \nEnd NatInduction.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/util/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.74916204162354}}
{"text": "(* SumOfNatを解いてもらったもの *)\n\nRequire Import Arith.\n\n\nFixpoint sum (n: nat) {struct n}: nat :=\n  match n with\n  | O   => O\n  | S p => S p + sum p\n  end.\n\n\nLemma sum_Sn: forall n, sum (S n) = S n + sum n.\nProof.\n  simpl; reflexivity.\nQed.\n\nLemma succ_add: forall n, S n = n + 1.\nProof.\nAdmitted.\n\nLemma add_diag: forall n, n + n = 2 * n.\nProof.\nAdmitted.\n\nGoal forall n m: nat, m = 2 * sum n -> m = n * (n + 1).\nProof.\n  induction n.\n  - intros; apply H.\n  - rewrite sum_Sn.\n    intros.\n    (* ここまでは分かった *)\n    rewrite Nat.mul_add_distr_l.\n    rewrite Nat.mul_succ_l.\n    rewrite Nat.mul_1_r.\n    rewrite <- Nat.add_assoc.\n    rewrite add_diag.\n    rewrite Nat.add_comm.\n    rewrite Nat.mul_add_distr_l in H.\n    rewrite (IHn (2 * sum n)) in H.\n    rewrite <- succ_add in H.\n    apply H.\n    reflexivity.\nQed.", "meta": {"author": "ahuglajbclajep", "repo": "coq-sandbox", "sha": "ec4eda49412481ccaeab83581859f7b1965537c6", "save_path": "github-repos/coq/ahuglajbclajep-coq-sandbox", "path": "github-repos/coq/ahuglajbclajep-coq-sandbox/coq-sandbox-ec4eda49412481ccaeab83581859f7b1965537c6/hatena-hzkr/SumOfNat_ans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966096291997, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.7491577660874409}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Omega.\n\nTheorem l_le_max : ∀ n m, n ≤ max n m.\nProof.\n  induction n; cbn; intros; try omega.\n  destruct m; trivial.\n  cut (n ≤ max n m); trivial; omega.\nQed.\n\nTheorem r_le_max : ∀ n m, m ≤ max n m.\nProof.\n  induction n; cbn; intros; try omega.\n  destruct m;  try omega.\n  cut (m ≤ max n m); trivial; omega.\nQed.\n\nTheorem le_S_n_eq_or_le_n : ∀ n m, n ≤ S m → {n = S m} + {n ≤ m}.\nProof.\n  intros n m H.\n  destruct (eq_nat_dec n (S m)); [left; trivial|].\n  right.\n  omega.\nQed.", "meta": {"author": "amintimany", "repo": "CTDT", "sha": "91e390152e09c554126b13fd953c905d16bfed5f", "save_path": "github-repos/coq/amintimany-CTDT", "path": "github-repos/coq/amintimany-CTDT/CTDT-91e390152e09c554126b13fd953c905d16bfed5f/Essentials/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7491208696447605}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  plus (mult y x) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj234_coqofml_iZNPv0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7489974630233396}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus (mult y x) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj257_coqofml_rbh0dt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7489974549843479}}
{"text": "(** * Sorted types. *)\n(** Gianluca Amato,  Marco Maggesi, Cosimo Perini Brogi 2019-2021 *)\n(*\nThis file contains a formalization of _sorted types_, i.e. types indexed by elements of another\ntype, called _index type_. Notation and terminologies are inspired by Wolfgang Wechler,\n_Universal Algebra for Computer Scientist_, Springer.\n*)\n\nRequire Import UniMath.Foundations.All.\nRequire Export UniMath.Combinatorics.MoreLists.\n\nRequire Export UniMath.Algebra.Universal.HVectors.\n\nDeclare Scope sorted_scope.\n\nDelimit Scope sorted_scope with sorted.\n\nLocal Open Scope sorted_scope.\n\n(** An element of [sUU S] is an [S]-sorted type, i.e., an [S]-indexed family of types. *)\n\nDefinition sUU (S: UU): UU := S → UU.\n\n(** If [X] and [Y] are [S]-sorted types, then [sfun X Y] is an [S]-sorted mapping, i.e.,\na [S]-indexed family of functions [X s → Y s]. *)\n\nDefinition sfun {S: UU} (X Y: sUU S): UU := ∏ s: S, X s → Y s.\n\nNotation \"x s→ y\" := (sfun x y) (at level 99, y at level 200, right associativity): type_scope.\n\nBind Scope sorted_scope with sUU.\n\nBind Scope sorted_scope with sfun.\n\nDefinition idsfun {S: UU} (X: sUU S): X s→ X := λ s: S, idfun (X s).\n\nDefinition scomp {S: UU} {X Y Z: sUU S} (f: Y s→ Z) (g: X s→ Y): sfun X Z\n  := λ s: S, (f s) ∘ (g s).\n\nInfix \"s∘\" := scomp (at level 40, left associativity): sorted_scope.\n\nDefinition sunit (S: UU): sUU S := λ σ: S, unit.\n\nDefinition tosunit {S: UU} {X: sUU S}: X s→ sunit S := λ σ: S, tounit.\n\nLemma iscontr_sfuntosunit {S: UU} {X: sUU S}: iscontr (X s→ sunit S).\nProof.\n  apply impred_iscontr.\n  intros.\n  apply iscontrfuntounit.\nDefined.\n\n(** An element of [shSet S] is an [S]-sorted set, i.e., an [S]-indexed family of sets. It can be\nimmediately coerced to an [S]-sorted type. *)\n\nDefinition shSet (S: UU): UU := S → hSet.\n\nDefinition sunitset (S: UU): shSet S := λ _, unitset.\n\nLemma isaset_set_sfun_space {S: UU} {X: sUU S} {Y: shSet S}: isaset (X s→ Y).\nProof.\n  change (isaset (X s→ Y)).\n  apply impred_isaset.\n  intros.\n  apply isaset_forall_hSet.\nDefined.\n\n(** If [X: sUU S], then [star X] is the lifting of [X] to the index type [list S], given\nby [star X] [s1; s2; ...; sn] = [X s1 ; X s2 ; ... ; X sn]. *)\n\nDefinition star {S: UU} (X: sUU S): sUU (list S) := λ l: list S, hvec (vec_map X (pr2 l)).\n\nBind Scope hvec_scope with star.\n\nNotation \"A ⋆\" := (star A) (at level 3, format \"'[ ' A '⋆' ']'\"): sorted_scope.\n\n(** If [f] is an indexed mapping between [S]-indexed types [X] and [Y], then [starfun X] is the lifting of\n[f] to a [list S]-indexed mapping between [list S]-indexed sets [star X] and [star Y].\n*)\n\nDefinition starfun {S: UU} {X Y: sUU S} (f: sfun X Y) : sfun X⋆ Y⋆ := λ s: list S, h1map f.\n\nNotation \"f ⋆⋆\" := (starfun f) (at level 3, format \"'[ ' f '⋆⋆' ']'\"): sorted_scope.\n\n(** Here follows the proof that [starfun] is functorial. Compositionality w.r.t. [s∘] is presented as\n[(f s∘ g)⋆⋆ _ x = f⋆⋆ _ (g⋆⋆ _ x)] instead of [(f s∘ g)⋆⋆ = (f⋆⋆) s∘ (g⋆⋆ )] since the former\ndoes not require function extensionality. *)\n\nLemma staridfun {S: UU} {X: sUU S} (l: list S) (x: X⋆ l): (idsfun X)⋆⋆ _ x = idsfun X⋆ _ x.\nProof.\n  apply h1map_idfun.\nDefined.\n\nLemma starcomp {S: UU} {X Y Z: sUU S} (f: Y s→ Z) (g: X s→ Y) (l: list S) (x: X⋆ l)\n  : (f s∘ g)⋆⋆ _ x = f⋆⋆ _ (g⋆⋆ _ x).\nProof.\n  unfold starfun.\n  apply pathsinv0.\n  apply h1map_compose.\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Algebra/Universal/SortedTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7489924717529957}}
{"text": "Require Import Znumtheory.\nRequire Import QArith.\n\n(** Proof that Sqrt(2) cannot be rational *)\n\nLtac mysimpl := simplify_eq; repeat rewrite Pmult_xO_permute_r. \n\nTheorem main_thm : forall p q: positive, (p*p <> 2*(q*q))%positive.\nProof.\ninduction p; simpl; intro; mysimpl.\ndestruct q; mysimpl; firstorder.\nQed.\n\nCoercion inject_Z : Z >-> Q.\n\nTheorem sqrt2_not_rational : forall q:Q, ~ q^2 == 2.\nProof.\nintros (a,b).\nunfold Qeq, Qpower, Qmult; simpl.\nrepeat rewrite Zmult_1_r; rewrite Pmult_1_r.\ndestruct a as [|a|a]; simpl; simplify_eq; exact (main_thm a b).\nQed.\n\n\n\n(** Ok, I admit, the proof above is a hack, since we exploit the binary \n  nature of positive numbers in Coq. For comparison, let's do the same for \n  an arbitrary prime number. *)\n\nOpen Scope Z_scope.\n\nTheorem main_thm_gen : forall p:Z, prime p -> \n forall a b:Z, 0<a -> 0<b -> a*a <> p*b*b.\nProof.\nintros p Hp a b Ha.\ngeneralize Ha; revert b; pattern a.\napply Zlt_0_rec; auto with zarith.\nclear a Ha; intros a Hrec _ b Ha Hb Hneg.\nassert (Hdiv: (p|a)).\n destruct (prime_mult p Hp a a); auto.\n exists (b*b); rewrite Hneg; ring.\ndestruct Hdiv as (c,Hc).\nassert (Hneg': b*b = p*c*c).\n rewrite Hc in Hneg.\n replace (c*p*(c*p)) with (p*(p*c*c)) in Hneg by ring.\n symmetry.\n destruct Hp.\n apply Zmult_reg_l with p; auto with zarith.\n rewrite Hneg; ring.\nrevert Hneg'.\napply Hrec; auto.\n(* justification of the recursive call: *)\nsplit; auto with zarith.\ndestruct (Z_lt_ge_dec b a); auto.\ndestruct Hp as (Hp,_).\nassert (a*a < p*b*b); [|omega].\n apply Zle_lt_trans with (b*b). \n apply Zmult_le_compat; auto with zarith.\n replace (b*b) with (1*(b*b)) by (auto with zarith).\n rewrite <- Zmult_assoc.\n apply Zmult_lt_compat_r; auto with zarith.\n apply Zmult_lt_0_compat; auto with zarith.\ndestruct Hp as (Hp,_).\ndestruct p; destruct a; destruct c; auto; simpl in Hc; try discriminate.\nQed.\n\nTheorem sqrtprime_not_rational : forall p:Z, prime p -> \n forall q:Q, ~ q*q == p.\nProof.\nintros p Hp (a,b).\nunfold Qmult, Qeq; simpl.\nrewrite Zmult_1_r; rewrite Zpos_mult_morphism.\nrewrite Zmult_assoc.\ndestruct a as [|a|a].\ndestruct Hp; destruct p; simpl in *; try discriminate.\napply main_thm_gen; auto with zarith; compute; auto.\nsimpl; rewrite Zpos_mult_morphism.\napply main_thm_gen; auto with zarith; compute; auto.\nQed.\n\n", "meta": {"author": "coq-contribs", "repo": "qarith", "sha": "a30fd6b2fa71e35dbadf38e5c04df98b842ca479", "save_path": "github-repos/coq/coq-contribs-qarith", "path": "github-repos/coq/coq-contribs-qarith/qarith-a30fd6b2fa71e35dbadf38e5c04df98b842ca479/sqrt2_not_rational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7489924656220137}}
{"text": "From MyCoq.Lib Require Export Nat.\nFrom MyCoq.Lib Require Export Poly.\n\n\n(* apply *)\nTheorem silly2: forall (n m o p : nat),\n  n = m -> (n = m -> [n; o] = [m; p]) -> [n; o] = [m; p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2.\n  apply eq1.\nQed.\n\nTheorem silly2a: forall (n m : nat),\n  (n, n) = (m, m) -> (forall (q r : nat), (q, q) = (r, r) -> [q] = [r]) -> [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2.\n  apply eq1.\nQed.\n\nTheorem silly_ex: (forall n, evenb n = true -> oddb (S n) = true) -> evenb (N 4) = true -> oddb (N 3) = true.\nProof.\n  intros H.\n  apply H.\nQed.\n\nTheorem silly3_firsttry: forall (n : nat),\n  true = (n =? (N 5)) -> (S (S n)) =? (N 7) = true.\nProof.\n  intros n H.\n  symmetry.\n  apply H.\nQed.\n\nSearch rev.\nTheorem rev_exercise1: forall (l l' : list nat),\n  l = rev l' -> l' = rev l.\nProof.\n  intros l l'.\n  intros H.\n  rewrite H.\n  rewrite rev_involutive .\n  reflexivity.\nQed.\n\n\n(* apply with *)\nTheorem trans_eq: forall (X : Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2.\n  rewrite -> eq1.\n  rewrite -> eq2.\n  reflexivity.\nQed.\n\nExample trans_eq_example: forall (a b c d e f : nat),\n  [a; b] = [c; d] -> [c; d] = [e; f] -> [a; b] = [e; f].\nProof.\n  intros a b c d e f eq1 eq2.\n  (* 根据引理结论对证明目标进行匹配的过程中并没有为 m 确定实例 *)\n  apply trans_eq with (m := [c; d]).\n  - apply eq1.\n  - apply eq2.\nQed.\n\nExample trans_eq_exercise: forall (n m o p : nat),\n  m = (minustwo o) -> (n + p) = m -> (n + p) = (minustwo o).\nProof.\n  intros n m o p.\n  intros eq1 eq2.\n  apply trans_eq with (m := m).\n  - apply eq2.\n  - apply eq1.\nQed.\n\n\n(* The injection and discriminate Tactics *)\nTheorem S_injective: forall (n m : nat),\n  S n = S m -> n = m.\nProof.\n  intros n m H1.\n  assert (H2: n = pred (S n)).\n  { \n    reflexivity.\n  }\n  rewrite H2.\n  rewrite H1.\n  reflexivity.\nQed.\n\nTheorem S_injective': forall (n m : nat),\n  S n = S m -> n = m.\nProof.\n  intros n m H.\n  injection H as Hnm.\n  apply Hnm.\nQed.\n\nTheorem injection_ex1: forall (n m o : nat),\n  [n; m] = [o; o] -> [n] = [m].\nProof.\n  intros n m o H.\n  injection H as H1 H2.\n  rewrite H1.\n  rewrite H2.\n  reflexivity.\nQed.\n\nTheorem injection_ex2: forall (n m o : nat),\n  [n; m] = [o; o] -> [n] = [m].\nProof.\n  intros n m o H.\n  injection H.\n  intros H1 H2.\n  rewrite H1.\n  rewrite H2.\n  reflexivity.\nQed.\n\nExample injection_ex3: forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  j = z :: l ->\n  x = y.\nProof.\n  intros X x y z l j.\n  intros H1 H2.\n  injection H1 as H11 H12.\n  rewrite H2 in H12.\n  injection H12 as H3.\n  rewrite H11.\n  rewrite H3.\n  reflexivity.\nQed.\n\nTheorem eqb_0_l: forall n,\n   O =? n = true -> n = O.\nProof.\n  intros [| n'].\n  - reflexivity.\n  - intros H.\n    discriminate.\nQed.\n\nTheorem discriminate_ex1: forall (n : nat),\n  S n = O -> N 2 + N 2 = N 5.\nProof.\n  intros n.\n  intros contra.\n  discriminate contra.\nQed.\n\nExample discriminate_ex3: forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = [] -> x = z.\nProof.\n  intros x y z l j.\n  intros contra.\n  discriminate.\nQed.\n\nTheorem f_equal: forall (A B : Type) (f : A -> B) (x y : A),\n  x = y -> f x = f y.\nProof.\n  intros  A B f x y.\n  intros H.\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem eq_implies_succ_equal': forall (n m : nat),\n  n = m -> S n = S m.\nProof.\n  intros n m H.\n  apply f_equal.\n  apply H.\nQed.\n\n\n(* 对假设使用策略 *)\nTheorem S_inj: forall (n m : nat) (b : bool),\n  (S n) =? (S m) = b -> n =? m = b.\nProof.\n  intros n m b.\n  intros H.\n  simpl in H.\n  apply H.\nQed.\n\nTheorem silly3': forall (n : nat),\n  (n =? N 5 = true -> (S (S n)) =? N 7 = true) ->\n  true = (n =? N 5) ->\n  true = ((S (S n)) =? N 7).\nProof.\n  intros n eq H.\n  symmetry in H.\n  apply eq in H.\n  symmetry in H.\n  apply H.\nQed.\n\n\n(* 变换归纳假设 *)\nTheorem double_injective: forall (n m : nat),\n  double n = double m -> n = m.\nProof.\n  induction n as [| n' IHn'] .\n  - simpl.\n    intros [| m'] H.\n    + reflexivity.\n    + discriminate H.\n  - simpl.\n    intros [| m'] H.\n    + discriminate.\n    + apply f_equal.\n      apply IHn'.\n      injection H as goal.\n      apply goal.\nQed.\n\nTheorem eqb_true: forall n m,\n  n =? m = true -> n = m.\nProof.\n  induction n as [| n' IHn'].\n  - intros [| m'] H.\n    + reflexivity.\n    + discriminate.\n  - intros [| m'] H.\n    + discriminate.\n    + apply f_equal.\n      apply IHn'.\n      simpl in H.\n      apply H.\nQed.\n\nTheorem plus_n_n_injective: forall n m,\n  n + n = m + m -> n = m.\nProof.\n  induction n as [| n'].\n  - intros [| m'] H.\n    + reflexivity.\n    + discriminate.\n  - intros [| m'] H.\n    + discriminate.\n    + apply f_equal.\n      apply IHn'.\n      simpl in H.\n      rewrite plus_n_Sm in H.\n      rewrite plus_n_Sm in H.\n      injection H as H'.\n      apply H'.\nQed.\n\nTheorem double_injective_take2: forall (n m : nat),\n  double n = double m -> n = m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m as [| m' IHm'] .\n  - simpl.\n    intros [| n'] H.\n    + reflexivity.\n    + discriminate H.\n  - simpl.\n    intros [| n'] H.\n    + discriminate.\n    + apply f_equal.\n      apply IHm'.\n      injection H as goal.\n      apply goal.\nQed.\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n  length l = n ->\n  nth_error l n = None.\nProof.\n  intros n X.\n  induction n as [| n'].\n  - destruct l as [| n l']. \n    + reflexivity.\n    + intros H.\n      discriminate H.\n  - intros [| n l'] H.\n    + reflexivity.\n    + apply IHn'.\n      injection H as H'.\n      apply H'.\nQed.\n\n\n(* 展开定义 *)\nDefinition square n := n * n.\n\nLemma square_mult: forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  unfold square.\n  rewrite mult_assoc.\n  rewrite mult_assoc.\n  assert (H: n * m * n = n * n * m).\n  {\n    rewrite mult_comm.\n    rewrite mult_assoc.\n    reflexivity.\n  }\n  rewrite H.\n  reflexivity.\nQed.\n\nDefinition bar x :=\n  match x with\n  | O => N 5\n  | S _ => N 5\n  end.\n\nFact silly_fact: forall m, bar m + N 1 = bar (m + N 1) + N 1.\nProof.\n  intros m.\n  unfold bar.\n  destruct m as [| m'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n\n(* 对复合表达式使用 destruct *)\nDefinition sillyfun (n : nat) : bool :=\n  if n =? N 3 then false\n  else if n =? N 5 then false\n  else false.\n\nTheorem sillyfun_false: forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n.\n  unfold sillyfun.\n  destruct (n =? N 3) eqn : E1.\n  - reflexivity.\n  - destruct (n =? N 5) eqn : E2.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem combine_split: forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) -> combine l1 l2 = l.\nProof.\n  intros X Y.\n  intros l.\n  (* induction 后加 eqn : E 会产生矛盾的假设 *)\n  induction l as [| n l' IHl'].\n  - intros l1 l2 H.\n    injection H as H1 H2.\n    rewrite <- H1.\n    rewrite <- H2.\n    reflexivity.\n  - destruct n as [n1 n2].\n    simpl.\n    destruct (split l') as [l1' l2'].\n    intros l1 l2 H.\n    injection H as H1 H2.\n    rewrite <- H1.\n    rewrite <- H2.\n    simpl. \n    assert (Hc: combine l1' l2' = l').\n    { \n      apply IHl'.\n      - reflexivity.\n    }\n    rewrite Hc.\n    reflexivity.\nQed.\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? N 3 then true\n  else if n =? N 5 then true\n  else false.\n\nTheorem sillyfun1_odd_FAILED: forall (n : nat),\n  sillyfun1 n = true -> oddb n = true.\nProof.\n  intros n.\n  intros H.\n  unfold sillyfun1 in H.\n  destruct (n =? N 3) eqn : Heq3.\n  - apply eqb_true in Heq3.\n    rewrite Heq3.\n    reflexivity.\n  - destruct (n =? N 5) eqn : Heq5.\n    + apply eqb_true in Heq5.\n      rewrite Heq5.\n      reflexivity.\n    + discriminate.\nQed.\n\nTheorem bool_fn_applied_thrice: forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f.\n  intros b.\n  destruct b eqn : Eb.\n  - destruct (f true) eqn : Et.\n    + rewrite Et, Et.\n      reflexivity.\n    + destruct (f false) eqn : Ef.\n      * apply Et.\n      * apply Ef.\n  - destruct (f true) eqn : Et.\n    + destruct (f false) eqn : Ef.\n      * rewrite Et, Et.\n        reflexivity.\n      * rewrite Ef, Ef.\n        reflexivity.\n    + destruct (f false) eqn : Ef.\n      * rewrite Et, Ef.\n        reflexivity.\n      * rewrite Ef, Ef.\n        reflexivity.\nQed.\n\n\n(* exercises *)\nTheorem eqb_sym: forall (n m : nat),\n  (n =? m) = (m =? n).\nProof.\n  induction n as [| n'].\n  - intros [| m'].\n    + reflexivity.\n    + simpl.\n      reflexivity.\n  - intros [| m'].\n    + simpl.\n      reflexivity.\n    + simpl.\n      apply IHn'.\nQed.\n\nTheorem eqb_trans: forall n m p,\n  n =? m = true ->\n  m =? p = true ->\n  n =? p = true.\nProof.\n  intros n m p.\n  intros H1 H2.\n  apply eqb_true in H1.\n  apply eqb_true in H2.\n  rewrite -> H1.\n  rewrite <- H2.\n  apply self_eq.\nQed.\n\nDefinition split_combine_statement : Prop :=\n  forall (X Y : Type) (l1 : list X) (l2 : list Y) (l : list (X * Y)),\n  length l1 = length l2 -> combine l1 l2 = l -> split l = (l1, l2).\n\nTheorem split_combine: split_combine_statement.\nProof.\n  unfold split_combine_statement.\n  intros X Y.\n  induction l1 as [| n1 l1' IHl1'].\n  - intros l2 l.\n    intros H1 H2.\n    destruct l2 as [| n2 l2'].\n    + rewrite <- H2.\n      simpl.\n      reflexivity.\n    + discriminate H1.\n  - intros l2 l.\n    intros H1 H2.\n    destruct l2 as [| n2 l2'].\n    + discriminate H1.\n    + simpl in H2.\n      rewrite <- H2.\n      simpl.\n      assert (Hsc: split (combine l1' l2') = (l1', l2')).\n      {\n        apply IHl1'.\n        - simpl in H1.\n          injection H1 as H1'.\n          apply H1'.\n        - reflexivity.\n      }\n      rewrite Hsc.\n      reflexivity.\nQed.\n\nTheorem filter_exercise: forall (X : Type) (test : X -> bool) (x : X) (l lf : list X),\n  filter test l = x :: lf -> test x = true.\nProof.\n  intros X.\n  intros test.\n  intros x.\n  induction l as [| n l'].\n  - intros lf.\n    intros H.\n    simpl in H.\n    discriminate H.\n  - intros lf.\n    intros H.\n    simpl in H.\n    destruct (test n) eqn : E.\n    + injection H as H' H''.\n      rewrite <- H'.\n      apply E.\n    + apply IHl' with (lf := lf).\n      apply H.\nQed.\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | x :: y => (test x) && forallb test y\n  end.\n\nExample test_forallb1: forallb oddb [N 1; N 3; N 5; N 7; N 9] = true.\nProof. simpl. reflexivity. Qed.\nExample test_forallb2: forallb (eqb (N 5)) [] = true.\nProof. simpl. reflexivity. Qed.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => false\n  | x :: y => (test x) || existsb test y\n  end.\n\nExample test_existsb1: existsb (andb true) [true; true; false] = true.\nProof. simpl. reflexivity. Qed.\nExample test_existsb2: existsb (eqb (N 5)) [] = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=\n  negb (forallb (fun (x : X) => negb (test x)) l).\n\nExample test_existsb'1: existsb (andb true) [true; true; false] = true.\nProof. simpl. reflexivity. Qed.\nExample test_existsb'2: existsb (eqb (N 5)) [] = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem existsb_existsb': forall (X : Type) (test : X -> bool) (l : list X),\n  existsb test l = existsb' test l.\nProof.\n  intros X.\n  intros test.\n  unfold existsb'.\n  induction l as [| n l'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    destruct (test n) eqn : E.\n    + simpl.\n      reflexivity. \n    + simpl.\n      apply IHl'.\nQed.\n\n\nDefinition excluded_middle : Prop :=\n  forall (P : Prop), P \\/ ~ P.\n\nDefinition contrapositive : Prop :=\n  forall (P Q : Prop), (P -> Q) <-> (~ Q -> ~ P).\n\nDefinition double_negation : Prop :=\n  forall (P : Prop), ~ (~ P) <-> P.\n\nTheorem de_morgan: forall (P Q : Prop), ~ (P \\/ Q) <-> (~ P) /\\ (~ Q).\nProof.\n  intros P Q.\n  split.\n  - unfold not.\n    intro H1.\n    split.\n    + intro H2.\n      apply H1.\n      left.\n      apply H2.\n    + intro H2.\n      apply H1.\n      right.\n      apply H2.\n  - unfold not.\n    intros H1 H2.\n    destruct H1 as [H11 H12].\n    destruct H2 as [H21 | H22].\n    + apply H11.\n      apply H21.\n    + apply H12.\n      apply H22.\nQed.\n\nTheorem equivalent: excluded_middle <-> contrapositive.\nProof.\n  unfold excluded_middle.\n  unfold contrapositive.\n  split.\n  - intros H1 P Q.\n    split.\n    + intros H2 H3.\n      intro H4.\n      apply H3.\n      apply H2.\n      apply H4.\n    + intros H2 H3.\n      specialize (H1 Q) as H4.\n      destruct H4 as [H41 | H42].\n      * apply H41.\n      * apply H2 in H42.\n        apply H42 in H3.\n        destruct H3.\n  - intros H1 P.\n    assert double_negation as H2.\n    {\n      intro Q.\n      specialize (H1 True Q).\n      split.\n      - intro H3.\n        apply H1.\n        + intro H4.\n          apply H3 in H4.\n          destruct H4.\n        + reflexivity.\n      - intro H3.\n        unfold not.\n        intro H4.\n        apply H4.\n        apply H3.\n    }\n    apply H2.\n    intro H3.\n    apply de_morgan in H3.\n    destruct H3 as [H31 H32].\n    apply H32 in H31.\n    destruct H31.\nQed.\n\nTheorem not_equivalent_with_neg: forall (P : Prop), ~ (P <-> ~ P).\nProof.\n  intros P H1.\n  unfold not in H1.\n  destruct H1 as [H11 H12].\n  assert (H2: P -> False).\n  {\n    intro H3.\n    apply H11.\n    apply H3.\n    apply H3.\n  }\n  apply H11.\n  - apply H12.\n    apply H2.\n  - apply H12.\n    apply H2.\nQed.\n", "meta": {"author": "GanZiheng", "repo": "learn-coq", "sha": "6d915f299e0b483ba53a8184c9ec13ac275aeca6", "save_path": "github-repos/coq/GanZiheng-learn-coq", "path": "github-repos/coq/GanZiheng-learn-coq/learn-coq-6d915f299e0b483ba53a8184c9ec13ac275aeca6/Src/tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7489915540117591}}
{"text": "(*Robert Hughes\nComp 293 Hw 2\nThis is the document for the second homework for the software reliability class*)\n\nFrom LF Require Export Poly.\nFrom LF Require Export Lists.\nFrom LF Require Export Basics.\nFrom LF Require Export Induction.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\nfold (fun _ n => S n) l 0.\n\n\n\n\n(*Question #1*)\nTheorem question_1: forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - reflexivity.\n  - simpl.\n    rewrite <- IH.\n    unfold fold_length.\n    simpl. reflexivity.\nQed.\n\n\n(*Question #2*)\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=\nfold (fun x => fun xs => f x :: xs) l [].\n\nTheorem question_2: forall X Y (l : list X) (f: X -> Y),\n  fold_map f l = map f l.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - reflexivity.\n  - simpl.\n    rewrite <- IH.\n    unfold fold_map.\n    simpl. reflexivity.\nQed.\n\n(*Question 3a*)\n\nDefinition Nat := forall X : Type, (X -> X) -> X -> X.\n\n\n(*Question 3b*)\n\nDefinition zero : Nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\nDefinition one : Nat := \n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\nDefinition two : Nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\nDefinition three : Nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f( f (f x) ).\n\n(*Question 3c*)\n\nDefinition succ (a : Nat) : Nat :=\n  fun (X : Type) (f : X -> X) (x: X) => f (a X f x).\n\n\n(*Question 3d*)\n\nExample succ_1 : succ zero = one.\nProof.\nintros. simpl. reflexivity. Qed.\n\nExample succ_2 : succ one = two.\nProof.\nintros. reflexivity. Qed.\n\nExample succ_3 : succ two = three.\nProof.\nintros. reflexivity. Qed.\n\n(*Question 3e*)\nDefinition plus (a b : Nat) : Nat :=\n  fun (X : Type) (f : X -> X) (x: X) => b X f (a X f x).\n\n\n(*Question 3f*)\n\nExample plus_1 : plus zero one = one.\n  Proof. reflexivity. Qed.\n\nExample plus_2 : plus two three = plus three two.\n  Proof. reflexivity. Qed.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\n  Proof. reflexivity. Qed.\n\n(*Question 3g*)\n\nDefinition mult (a b : Nat) : Nat :=\n  fun (X : Type) (f : X -> X) => b X (a X f).\n\n(*Question 3h*)\n\nExample mult_1 : mult one one = one.\n  Proof. reflexivity. Qed.\n\nExample mult_2 : mult zero (plus three three) = zero.\n  Proof. reflexivity. Qed.\n\nExample mult_3 : mult two three = plus three three.\n  Proof. reflexivity. Qed.\n\n\n(*Question 3i*)\n\nDefinition exp (a b : Nat) : Nat := \nfun (X : Type) (f : X -> X) (x : X) =>  (b (X -> X) (a X) f) x.\n\n(*Question 3j*)\n\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\nExample exp_3 : exp three zero = one.\nProof. reflexivity. Qed.\n\n\n(*Question 3k*)\nTheorem question_3k: forall n : Nat,\nplus n one = succ n.\nProof.\n  intro n.  reflexivity. Qed.\n\n\n\n\n\n\n(*Question 3l*)\nTheorem question_3l: forall (n m: Nat),\nmult n (succ m) = plus (mult n m) n.\nProof.\n\n  intro n. reflexivity. Qed.\n\n\n(*Question 4*)\nDefinition func_comp {A B C : Type} (g : B -> C) (f : A -> B) :=\n  fun x => g (f x).\n\n(* \nTheorem question_4: forall(),\n*)\nTheorem composition_associative : forall A B C D (f : A -> B) (g : B -> C) (h : C -> D),\n  func_comp (func_comp h g) f = func_comp h (func_comp g f).\nProof.\n  intros. reflexivity. Qed.\n\n\n\n(*Question 5*)\n(*Question 5a*)\nInductive tree (X:Type) : Type :=\n  | empty : tree X\n  | branch : X -> list (tree X) -> tree X.\n\nArguments tree {X}.\nArguments empty {X}.\nArguments branch {X}.\n\n\n(*Question 5b*)\nDefinition mytree :=\n  branch 1 [ branch 5 [ branch 2 [empty] ] ;  branch 8 [empty] ;\n          branch 7 [ branch 3 [empty];branch 4 [empty] ] ].\n\n(*Question 5c*)\nDefinition isleaf {X: Type} (node: @tree X) : bool :=\n  match node with\n    | empty => true\n    | _ => false\n  end.\n\n(*Question 5d*)\nExample test_isleaf:\n  isleaf mytree = false.\nProof.\n  simpl. reflexivity.\nQed.\n\n(* Test tree for the height\nDefinition mytree_test :=\n  branch 1[ branch 3 [ branch 5 [ empty]; branch 2 [branch 2 [branch 2 [branch 2 [empty]]]] ]].\n\n*)\n\n(*Question 5e*)\n\nFixpoint height {X: Type} (tr: @tree X) : nat :=\n  let fix subtree_height (l: list tree) : nat := \n        match l with\n          |nil => 0\n          |h::t => max ( height h ) ( subtree_height t )\n        end\n  in\n  match tr with\n  | empty => 0\n  | branch _ l => S (subtree_height l)\n  end.\n\n\n(*Compute height mytree_test .*)\n\n\n(*Question 5f*)\n\nExample test_height:\n  height mytree = 3.\nProof.\n  simpl. reflexivity.\nQed.\n\n\n\n(*Question 5g*)\nFixpoint sum_nodes (tr: @tree nat) : nat :=\n  let fix subtree_node (l: list tree) : nat := \n        match l with\n          |nil => 0\n          |h::t =>  ( sum_nodes h ) + ( subtree_node t )\n        end\n  in\n  match tr with\n  | empty => 0\n  | branch r l => r + (subtree_node l)\n  end.\n\nCompute sum_nodes mytree.\n\n\n\n(*Question 5h*)\nExample test_sum_nodes:\n  sum_nodes mytree = 30.\nProof.\n  simpl. reflexivity.\nQed.\n\n\n\n(*Question 6*)\n(*Question 6a*)\n\nInductive b_tree (X: Type) : Type :=\n  | emp_tree : b_tree X\n  | node: X ->b_tree X -> b_tree X-> b_tree X.\n\nArguments b_tree {X}.\nArguments emp_tree {X}.\nArguments node {X}.\n\nDefinition mytree2 :=\nnode 1\n    (node 2\n        (node 4 emp_tree emp_tree)\n        (node 5 emp_tree emp_tree))\n    (node 3 emp_tree emp_tree).\n\n\n\n\n(*Question 6b*)\nFixpoint preorder {X: Type} (btr: b_tree) : list X:=\n  match btr with\n  | emp_tree => []\n  | node p q r =>   [p] ++ preorder q ++ preorder r \n  end.\n\n(*Question 6c*)\nCompute preorder mytree2.\n\n\n(*Question 6d*)\nFixpoint inorder {X: Type} (btr: b_tree) : list X:=\n  match btr with\n  | emp_tree => []\n  | node p q r => inorder q ++ [p] ++ inorder r\n  end.\n\n\n(*Question 6e*)\nCompute inorder mytree2.\n\n(*Question 6f*)\nFixpoint postorder {X: Type} (btr: b_tree) : list X:=\n  match btr with\n  | emp_tree => []\n  | node p q r =>  postorder q ++ postorder r ++  [p]\n  end.\n\n\n(*Question 6g*)\nCompute postorder mytree2.\n\n\n(*Question 6h*)\nTheorem question_6h : forall (X : Type) ( tree : @b_tree X ),\n\n  length (preorder tree) = length (postorder tree).\nProof.\n  intros X tree. induction tree.\n  - reflexivity.\n  - simpl. rewrite app_length. rewrite app_length. rewrite app_length. simpl. rewrite IHtree1.\n rewrite IHtree2.  rewrite <- plus_n_Sm. rewrite <- plus_n_O. rewrite plus_n_Sm. reflexivity.\nQed.\n\n\n\n(*Question 6i*)\nFixpoint count_nodes {X: Type} (btr : @b_tree X) : nat :=\n  match btr with \n  |emp_tree => 0\n  |node x y z => S( count_nodes y) + (count_nodes z)\nend.\n\n\nTheorem question_6i: forall (X:Type) (tr : @b_tree X),\ncount_nodes tr = length(preorder tr).\nProof.\n  intros. induction tr.\n  - reflexivity.\n  - simpl. rewrite app_length. rewrite IHtr2. rewrite IHtr1. reflexivity.\nQed.\n\n\n\n(*Question 6j*)\nFixpoint height_btr {X: Type} (btr : @b_tree X) : nat :=\n  match btr with\n  | emp_tree => 0\n  | node _ t1 t2 => 1 + max (height_btr t1) (height_btr t2)\n  end.\n\nLemma max_comm :\n  forall n m : nat, max n m = max m n.\nProof.\nintro n; induction n as [| n' IHn'];\n  intro m; destruct m as [| m'];\n    simpl; try (rewrite IHn'); trivial.\nQed.\n\nLemma plus_par : forall n m, n + m = (n + m).\nProof.\n  intros n m. reflexivity.\nQed.\n\nLemma leb_refl : forall n:nat,\n  leb n n = true.\nProof.\n  intros n. induction n as [|n'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nLemma leb_max : forall n m,\n  leb n (max n m) = true.\nProof.\n  intros.\n  generalize dependent m.\n  induction n.\n  -simpl. reflexivity.\n  - destruct m.\n    + simpl. apply leb_refl.\n    + simpl. destruct n.\n      * simpl. reflexivity.   \n      * rewrite IHn. reflexivity.\nQed.\n\nLemma leb_plus_max : forall n m,\n  leb (max n m) (n + m) = true.\nProof.\n  intros.\n  generalize dependent m.\n  intros. induction n. \n  - simpl. rewrite leb_refl. reflexivity.\nAdmitted.\n\n\nTheorem question_6j : forall {X: Type}(t : @b_tree X),\n      leb (height_btr t) (count_nodes t)=true. \nProof.\n  intros.\n  simpl.\n  - induction t.\n    apply leb_refl.\n  simpl. destruct t1. simpl.\n  + rewrite IHt2. reflexivity.\n  Admitted.\n\nTheorem question_6j_other: forall (X:Type) (tr : @b_tree X),\n  leb (height_btr tr) (count_nodes tr) = true.\nProof.\n  intros. induction tr.\n  - reflexivity.\n  - simpl. \nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Robert-M-Hughes", "repo": "software-foundations-work", "sha": "e000fe8cd3b2e36c79765c413c534d8d287755db", "save_path": "github-repos/coq/Robert-M-Hughes-software-foundations-work", "path": "github-repos/coq/Robert-M-Hughes-software-foundations-work/software-foundations-work-e000fe8cd3b2e36c79765c413c534d8d287755db/HW2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8791467611766711, "lm_q1q2_score": 0.7489915498304933}}
{"text": "(** A library of relation operators defining sequences of transitions\n  and useful properties about them. *)\n\nSet Implicit Arguments.\n\nSection SEQUENCES.\n\nVariable A: Type.                 (**r the type of states *)\nVariable R: A -> A -> Prop.       (**r the transition relation, from one state to the next *)\n\n(** ** Finite sequences of transitions *)\n\n(** Zero, one or several transitions: reflexive, transitive closure of [R]. *)\n\nInductive star: A -> A -> Prop :=\n  | star_refl: forall a,\n      star a a\n  | star_step: forall a b c,\n      R a b -> star b c -> star a c.\n\nLemma star_one:\n  forall (a b: A), R a b -> star a b.\nProof.\n  eauto using star.\nQed.\n\nLemma star_trans:\n  forall (a b: A), star a b -> forall c, star b c -> star a c.\nProof.\n  induction 1; eauto using star. \nQed.\n\n(** One or several transitions: transitive closure of [R]. *)\n\nInductive plus: A -> A -> Prop :=\n  | plus_left: forall a b c,\n      R a b -> star b c -> plus a c.\n\nLemma plus_one:\n  forall a b, R a b -> plus a b.\nProof.\n  eauto using star, plus. \nQed.\n\nLemma plus_star:\n  forall a b,\n  plus a b -> star a b.\nProof.\n  intros. inversion H. eauto using star.  \nQed.\n\nLemma plus_star_trans:\n  forall a b c, plus a b -> star b c -> plus a c.\nProof.\n  intros. inversion H. eauto using plus, star_trans.\nQed.\n\nLemma star_plus_trans:\n  forall a b c, star a b -> plus b c -> plus a c.\nProof.\n  intros. inversion H0. inversion H; eauto using plus, star, star_trans.\nQed.\n\nLemma plus_right:\n  forall a b c, star a b -> R b c -> plus a c.\nProof.\n  eauto using star_plus_trans, plus_one.\nQed.\n\n(** ** Infinite sequences of transitions *)\n\n(** It is easy to characterize the fact that all transition sequences starting\n  from a state [a] are infinite: it suffices to say that any finite sequence\n  starting from [a] can always be extended by one more transition. *)\n\nDefinition all_seq_inf (a: A) : Prop :=\n  forall b, star a b -> exists c, R b c.\n\n(** However, this is not the notion we are trying to characterize: that, starting\n  from [a], there exists one infinite sequence of transitions\n  [a --> a1 --> a2 --> ... -> aN -> ...].\n\n  Indeed, consider [A = nat] and [R] such that [R 0 0] and [R 0 1].  \n  [all_seq_inf 0] does not hold, because a sequence [0 -->* 1] cannot be extended.\n  Yet, [R] admits an infinite sequence, namely [0 --> 0 --> ...].  \n\n  Another attempt would be to represent the sequence of states \n  [a0 --> a1 --> a2 --> ... -> aN -> ...] explicitly, as a function \n  [f: nat -> A] such that [f i] is the [i]-th state [ai] of the sequence. *)\n\nDefinition infseq_with_function (a: A) : Prop :=\n  exists f: nat -> A, f 0 = a /\\ forall i, R (f i) (f (1 + i)).\n\n(** This is a correct characterization of the existence of an infinite sequence\n  of reductions.  However, it is very inconvenient to work with this definition\n  in Coq's constructive logic: in most use cases, the function [f] is not\n  computable and therefore cannot be defined in Coq.  *)\n\n(** To obtain a practical definition of infinite sequences, we use the following\n  coinductive definition of the predicate [infseq a]. *)\n\nCoInductive infseq: A -> Prop :=\n  | infseq_step: forall a b,\n      R a b -> infseq b -> infseq a.\n\n(** An inductive predicate such as [star a b] holds iff there exists a finite\n  derivation of the conclusion [star a b] that uses the constructors\n  [star_refl] and [star_step] a finite number of times.\n\n  A coinductive predicate is similar, but holds iff there exists a finite\n  OR INFINITE derivation of the conclusion that uses the constructors\n  of the predicate a finite OR INFINITE number of times.\n\n  In other words, an inductive predicate is a smallest fixpoint: the smallest predicate\n  that satisfies its constructors; a coinductive predicate is a greatest fixpoint:\n  the largest predicate that satisfies its constructors.\n\n  The [infseq] predicate above must be defined coinductively.  Indeed, if\n  we define it inductively, the predicate would be empty (always false),\n  since there are no base cases!  \n\n  Coq provides some primitive support for constructing infinite derivations\n  of facts such as [infseq a].  Such constructions are proofs by coinduction.\n  For example, we can prove the following: *)\n\nRemark cycle_infseq:\n  forall a, R a a -> infseq a.\nProof.\n  intros. cofix COINDHYP. apply infseq_step with a. auto. apply COINDHYP.\nQed.\n\n(** This style of proof by coinduction, using the [cofix] tactic, is effective\n  but can run into limitations of Coq's proof engine (the so-called \n  \"guard condition\").  However, we can derive more conventional\n  coinduction principles that are often easier to use. *)\n\n(** Consider a set [X] of states [A], that is, a predicate [X: A -> Prop].\n  Assume that for every [a] in [X], we can make one [R] transition to a [b]\n  that is still in [X].  Then, starting from [a] in [X], we can transition\n  to some [a1] in [X], then to some [a2] still in [X], then... It is clear\n  that we are just building an infinite sequence of transitions starting from\n  [a]. Therefore [infseq a] should hold.  Let's prove this! *)\n\nLemma infseq_coinduction_principle:\n  forall (X: A -> Prop),\n  (forall a, X a -> exists b, R a b /\\ X b) ->\n  forall a, X a -> infseq a.\nProof.\n  intros X P. cofix COINDHYP; intros.\n  destruct (P a H) as [b [U V]]. apply infseq_step with b; auto. \nQed.\n\n(** An even more useful variant of this coinduction principle considers a\n  set [X] where for every [a] in [X], we can make one *or several* transitions\n  to reach a [b] in [X].  *)\n\nLemma infseq_coinduction_principle_2:\n  forall (X: A -> Prop),\n  (forall a, X a -> exists b, plus a b /\\ X b) ->\n  forall a, X a -> infseq a.\nProof.\n  intros.\n  apply infseq_coinduction_principle with\n    (X := fun a => exists b, star a b /\\ X b).\n- intros. \n  destruct H1 as [b [STAR Xb]]. inversion STAR; subst.\n+ destruct (H b Xb) as [c [PLUS Xc]]. inversion PLUS; subst.\n  exists b0; split. auto. exists c; auto. \n+ exists b0; split. auto. exists b; auto.\n- exists a; split. apply star_refl. auto.\nQed.\n\n(** Here is an example of use of [infseq_coinduction_principle]:\n  if all finite transition sequences starting at [a] can be extended,\n  [infseq a] holds. *)\n\nLemma infseq_if_all_seq_inf:\n  forall a, all_seq_inf a -> infseq a.\nProof.\n  apply infseq_coinduction_principle.\n  intros. destruct (H a) as [b Rb]. constructor. \n  exists b; split; auto. \n  unfold all_seq_inf; intros. apply H. apply star_step with b; auto.\nQed.\n\n(** Likewise, the function-based characterization [infseq_with_function]\n  implies [infseq]. *)\n\nLemma infseq_from_function:\n  forall a, infseq_with_function a -> infseq a.\nProof.\n  apply infseq_coinduction_principle.\n  intros. destruct H as [f [P Q]].\n  exists (f 1); split.\n  subst a. apply Q. \n  exists (fun n => f (1 + n)); split. auto. intros. apply Q.\nQed.\n \n(** Consider the transition sequences starting at state [a].\n  They can be infinite, or they can be finite: after a number of transitions,\n  we reach a state from with no transition is possible.  It is intuitively\n  obvious that at least one of the two cases must hold. \n\n  It is however impossible to prove this fact in Coq's constructive logic.\n  Indeed, a constructive proof would be isomorphic (by the Curry-Howard isomorphism)\n  to a terminating function that solves Turing's halting problem!\n\n  To prove this fact, we must enrich Coq with axioms from classical logic,\n  namely the axiom of excluded middle: for all propositions [P],\n  either [P] or [~P] hold.  The Coq standard library provides such axioms\n  in the module named [Classical], which we now import. *)\n\nRequire Import Classical.\n\nDefinition irred (a: A) : Prop := forall b, ~(R a b).\n\nLemma infseq_or_finseq:\n  forall a, infseq a \\/ exists b, star a b /\\ irred b.\nProof.\n  intros.\n  destruct (classic (forall b, star a b -> exists c, R b c)).\n- left. apply infseq_if_all_seq_inf; auto.\n- right.\n  apply not_all_ex_not in H. destruct H as [b P].\n  apply imply_to_and in P. destruct P as [U V].\n  exists b; split. auto.\n  red; intros; red; intros. elim V. exists b0; auto.\nQed.\n\n(** ** Determinism properties for functional transition relations. *)\n\n(** A transition relation is functional if every state can transition to at most\n  one other state. *)\n\nHypothesis R_functional:\n  forall a b c, R a b -> R a c -> b = c.\n\n(** Uniqueness of finite transition sequences. *)\n\nLemma star_star_inv:\n  forall a b, star a b -> forall c, star a c -> star b c \\/ star c b.\nProof.\n  induction 1; intros.\n- auto.\n- inversion H1; subst.\n+ right. eauto using star. \n+ assert (b = b0) by (eapply R_functional; eauto). subst b0. \n  apply IHstar; auto.\nQed.\n\nLemma finseq_unique:\n  forall a b b',\n  star a b -> irred b ->\n  star a b' -> irred b' ->\n  b = b'.\nProof.\n  intros. destruct (star_star_inv H H1).\n- inversion H3; subst. auto. elim (H0 _ H4).\n- inversion H3; subst. auto. elim (H2 _ H4).\nQed.\n\n(** A state cannot both diverge and terminate on an irreducible state. *)\n\nLemma infseq_star_inv:\n  forall a b, star a b -> infseq a -> infseq b.\nProof.\n  induction 1; intros.\n- auto. \n- inversion H1; subst.\n  assert (b = b0) by (eapply R_functional; eauto). subst b0.\n  apply IHstar; auto.\nQed.\n\nLemma infseq_finseq_excl:\n  forall a b,\n  star a b -> irred b -> infseq a -> False.\nProof.\n  intros. \n  assert (infseq b) by (eapply infseq_star_inv; eauto). \n  inversion H2. elim (H0 b0); auto. \nQed.\n\n(** If there exists an infinite sequence of transitions from [a],\n  all sequences of transitions arising from [a] are infinite. *)\n\nLemma infseq_all_seq_inf:\n  forall a, infseq a -> all_seq_inf a.\nProof.\n  intros. unfold all_seq_inf. intros. \n  assert (infseq b) by (eapply infseq_star_inv; eauto). \n  inversion H1. subst. exists b0; auto.\nQed.\n\nEnd SEQUENCES.\n\n\n  \n\n\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/compiler/Sequences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7489878452834882}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrbool.\nRequire Import mathcomp.ssreflect.eqtype.\nRequire Import mathcomp.ssreflect.ssrnat.\n\nSection Smullyan_drinker.\n  Variables (D : Type)(P : D -> Prop).\n  Hypothesis (d : D) (EM : forall A, A \\/ ~A).\n\n  Lemma drinker : exists x, P x -> forall y, P y.\n  Proof.\n    (* case: (EM (exists y, ~P y)) is equivalent to move: (EM (exists y, ~P y)); case. *)\n    case: (EM (exists y, ~P y)) => [[y notPy]| nonotPy]; first by exists y.\n    (*\n      exists d => _ y.\n      case : (EM (P y)).\n        done.\n        move => notPy.\n    *)\n    exists d => _ y; case: (EM (P y)) => // notPy.\n    by case: nonotPy; exists y.\n  Qed.\nEnd Smullyan_drinker.", "meta": {"author": "ml4tp", "repo": "gamepad", "sha": "7092f50a96eae9a862e72ecb8a55a217fa97723c", "save_path": "github-repos/coq/ml4tp-gamepad", "path": "github-repos/coq/ml4tp-gamepad/gamepad-7092f50a96eae9a862e72ecb8a55a217fa97723c/examples/tutorial2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7489878429205812}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Sorting.Permutation.\nRequire Import TLC.LibTactics.\nRequire Import LibNatExtra.\nRequire Import LibRewrite.\nRequire Import ZArith.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Type classes for two central properties of a binary operation: associativity,\n   and the existence of a unit. *)\n\nClass Unit {A : Type} (op : A -> A -> A) := {\n  unit:\n    A;\n  left_unit:\n    forall a,\n    op unit a = a;\n  right_unit:\n    forall a,\n    op a unit = a\n}.\n\nClass Commutative {A : Type} (op : A -> A -> A) := {\n  commutativity:\n    forall a1 a2,\n    op a1 a2 = op a2 a1\n}.\n\nClass Associative {A : Type} (op : A -> A -> A) := {\n  associativity:\n    forall a1 a2 a3,\n    op (op a1 a2) a3 = op a1 (op a2 a3)\n}.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Instances for addition, multiplication, maximum. *)\n\nObligation Tactic := try solve [ intros; ring_simplify; omega ].\nProgram Instance unit_plus : Unit plus := { unit := 0 }.\nProgram Instance commutative_plus : Commutative plus.\nProgram Instance associative_plus : Associative plus.\nProgram Instance unit_mult : Unit mult := { unit := 1 }.\nProgram Instance commutative_mult : Commutative mult.\nProgram Instance associative_mult : Associative mult.\nProgram Instance unit_Zplus : Unit Z.add := { unit := 0%Z }.\nProgram Instance commutative_Zplus : Commutative Z.add.\nProgram Instance associative_Zplus : Associative Z.add.\nProgram Instance unit_Zmult : Unit Z.mul := { unit := 1%Z }.\nProgram Instance commutative_Zmult : Commutative Z.mul.\nProgram Instance associative_Zmult : Associative Z.mul.\nObligation Tactic := try solve [ intros; repeat max_case; omega ].\nProgram Instance unit_max  : Unit max  := { unit := 0 }.\nProgram Instance commutative_max  : Commutative max.\nProgram Instance associative_max  : Associative max.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* [big op xs] is the iterated application of [op] to the elements of\n   the list [xs]. *)\n\nDefinition big {A : Type} (op : A -> A -> A) `{Unit A op} xs :=\n  fold_right op unit xs.\n\n(* This notation is inspired by Bertot et al.'s paper. *)\n\nNotation \"\\big [ op ]_ ( r <- range ) f\" :=\n  (big op (map (fun r => f) range)) (at level 36).\n\n(* ---------------------------------------------------------------------------- *)\n\n(* [big] is covariant. *)\n\n(* TEMPORARY (unused)\n\nObligation Tactic := unfold Proper, respectful.\n\nProgram Instance proper_big A op `{Unit A op} (R : relation A) `{Reflexive A R} :\n  Proper (R ++> R ++> R) op -> Proper (Forall2 R ++> R) (big op).\nNext Obligation.\n  induction 3; simpl; eauto.\nQed.\n\n(* [map] is covariant. *)\n\nProgram Instance proper_map A B (R : relation A) (S : relation B) :\n  Proper ((R ++> S) ++> Forall2 R ++> Forall2 S) (@map A B).\nNext Obligation.\n  induction 2; simpl; eauto.\nQed.\n\n*)\n\nLemma big_covariant:\n  forall B op `{Unit B op} (R : relation B) `{Reflexive B R},\n  Proper (R ++> R ++> R) op ->\n  forall A (f g : A -> B) (xs : list A),\n  (forall x, In x xs -> R (f x) (g x)) ->\n  R (big op (map f xs)) (big op (map g xs)).\nProof using.\n  introv ? hop. induction xs; simpl; intros.\n  eauto.\n  eapply hop. eauto. eauto.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* [big op] plays well with lists. *)\n\nLemma big_nil:\n  forall A op `{Unit A op},\n  big op nil = unit.\nProof using.\n  reflexivity.\nQed.\n\nLemma big_app:\n  forall A op `{Unit A op} `{Associative A op} xs ys,\n  big op (xs ++ ys) = op (big op xs) (big op ys).\nProof using.\n  induction xs; simpl; intros.\n  rewrite left_unit. reflexivity.\n  rewrite IHxs. rewrite associativity. reflexivity.\nQed.\n\nLemma big_permutation:\n  forall A op `{Unit A op, Commutative A op, Associative A op} xs ys,\n  Permutation xs ys ->\n  big op xs = big op ys.\nProof using.\n  induction 3; simpl; try congruence.\n  rewrite <- associativity. rewrite (@commutativity _ _ _ y x). rewrite associativity. congruence.\nQed.\n\nObligation Tactic := try (repeat intro; eauto using big_permutation).\nProgram Instance big_permutation_ A op `{Unit A op, Commutative A op, Associative A op} :\n  Proper (@Permutation A ++> @eq A) (big op).\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Distributivity of a product onto a big sum. *)\n\nClass Distributive {A : Type} (mult plus : A -> A -> A) `{Unit A plus} := {\n  distributivity:\n    forall a b c,\n    mult c (plus a b) = plus (mult c a) (mult c b);\n  absorption:\n    (* The unit of addition must be absorbant for multiplication. *)\n    forall c, mult c unit = unit\n}.\n\nObligation Tactic := try (intros; simpl; ring_simplify; omega).\nProgram Instance distributive_mult_plus : Distributive mult plus.\n(* Program Instance distributive_plus_max  : Distributive plus max. (* fails, due to absorption *) *)\nProgram Instance distributive_Zmult_Zplus : Distributive Z.mul Z.add.\n\nLemma big_distributive:\n  forall A mult plus `{Unit A plus, Associative A plus, Distributive A mult plus},\n  forall c xs,\n  mult c (big plus xs) = big plus (map (mult c) xs).\nProof using.\n  induction xs; simpl; intros.\n  (* Nil. *)\n  rewrite absorption. reflexivity.\n  (* Cons. *)\n  rewrite distributivity. rewrite IHxs. reflexivity.\nQed.\n\nLemma big_map_distributive:\n  forall A mult plus `{Unit A plus, Associative A plus, Distributive A mult plus},\n  forall c B (f : B -> A) xs,\n  mult c (big plus (map f xs)) = big plus (map (fun x => mult c (f x)) xs).\nProof using.\n  intros. rewrite big_distributive by eauto with typeclass_instances.\n  rewrite map_map. reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Intervals. *)\n\n(* [interval_ i len] is the semi-open interval [i, i + len). *)\n\nFixpoint interval_ i len :=\n  match len with\n  | 0 =>\n      nil\n  | S len =>\n      i :: interval_ (i + 1) len\n  end.\n\n(* [interval i j] is the semi-open interval [i, j). *)\n\nDefinition interval i j :=\n  interval_ i (j - i).\n\n(* The length of [interval i j] is [j - i]. *)\n\nLemma length_interval_:\n  forall len i,\n  length (interval_ i len) = len.\nProof using.\n  induction len; simpl; congruence.\nQed.\n\nLemma length_interval:\n  forall i j,\n  length (interval i j) = j - i.\nProof using.\n  unfold interval. eauto using length_interval_.\nQed.\n\n(* Basic properties. *)\n\nLemma interval_is_empty:\n  forall i j,\n  j <= i ->\n  interval i j = nil.\nProof using.\n  unfold interval. intros.\n  replace (j - i) with 0 by omega.\n  reflexivity.\nQed.\n\nLemma interval_is_nonempty:\n  forall i j,\n  i < j ->\n  interval i j = i :: interval (i + 1) j.\nProof using.\n  unfold interval. intros.\n  replace (j - i) with (S (j - (i + 1))) by omega.\n  reflexivity.\nQed.\n\nLemma in_interval_lo:\n  forall x lo hi,\n  In x (interval lo hi) ->\n  lo <= x.\nProof using.\n  assert (forall x len lo, In x (interval_ lo len) -> lo <= x).\n    induction len; simpl; intros.\n    false.\n    match goal with h: _ \\/ _ |- _ => destruct h end.\n      omega.\n      forwards: IHlen. eauto. omega.\n  eauto.\nQed.\n\nLemma in_interval_hi:\n  forall x lo hi,\n  In x (interval lo hi) ->\n  x < hi.\nProof using.\n  assert (aux: forall x len lo, In x (interval_ lo len) -> x < lo + len /\\ len > 0).\n    induction len; simpl; intros.\n    false.\n    match goal with h: _ \\/ _ |- _ => destruct h end.\n      omega.\n      forwards: IHlen. eauto. omega.\n  intros. forwards: aux. eauto. omega.\nQed.\n\nLemma interval_app:\n  forall i j k,\n  i <= j ->\n  j <= k ->\n  interval i j ++ interval j k = interval i k.\nProof using.\n  assert (reformulation:\n    forall len1 i len2,\n    interval_ i len1 ++ interval_ (i + len1) len2 = interval_ i (len1 + len2)\n  ).\n  induction len1; simpl; intros.\n  (* Nil. *)\n  f_equal. omega.\n  (* Cons. *)\n  rewrite <- IHlen1. do 3 f_equal. omega.\n  (* Back to the original goal. *)\n  unfold interval. intros. replace (k - i) with ((j - i) + (k - j)) by omega.\n  rewrite <- reformulation. do 2 f_equal. omega.\nQed.\n\n(* Test. *)\n\nGoal \\big[plus]_(i <- interval 0 10) i = 45.\nProof using.\n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The Cartesian product of two lists. *)\n\nFixpoint cartesian {A B : Type} (xs : list A) (ys : list B) : list (A * B) :=\n  match xs with\n  | nil =>\n      nil\n  | x :: xs =>\n      map (fun y => (x, y)) ys ++ cartesian xs ys\n  end.\n\n(* Looking at [cartesian] from the other side. *)\n\nLemma cartesian_nil:\n  forall {A B : Type} (xs : list A),\n  cartesian xs (nil : list B) = nil.\nProof using.\n  induction xs; simpl; eauto.\nQed.\n\nLemma cartesian_cons:\n  forall {A B : Type} (xs : list A) y (ys : list B),\n  Permutation\n    (cartesian xs (y :: ys))\n    (map (fun x => (x, y)) xs ++ cartesian xs ys).\nProof using.\n  induction xs; simpl; intros.\n  (* Nil. *)\n  econstructor.\n  (* Cons. *)\n  econstructor.\n  rewrite IHxs.\n  do 2 rewrite app_assoc.\n  eauto using Permutation_app, Permutation_app_comm.\nQed.\n\n(* Up to a permutation of the list and up to swapping the pair components,\n   [cartesian] is commutative. *)\n\nLemma cartesian_commutative:\n  forall {A B C : Type} (f : A * B -> C) (g : B * A -> C),\n  (forall x y, f (x, y) = g (y, x)) ->\n  forall (xs : list A) (ys : list B),\n  Permutation\n    (map f (cartesian xs ys))\n    (map g (cartesian ys xs)).\nProof using.\n  introv h. induction xs as [| x xs ]; simpl; intros.\n  (* Nil. *)\n  rewrite cartesian_nil. econstructor.\n  (* Cons. *)\n  rewrite map_app.\n  rewrite IHxs.\n  rewrite map_map.\n  erewrite map_ext by eapply h.\n  rewrite <- map_map.\n  rewrite <- map_app.\n  rewrite <- cartesian_cons.\n  eapply Permutation_refl.\nQed.\n\n(* A sum of sums is equal to a single sum over the Cartesian product. *)\n\nLemma bigop_cartesian:\n  forall A B C : Type,\n  forall op `{Unit C op, Commutative C op, Associative C op},\n  forall f : A * B -> C,\n  forall xs ys,\n  big op (map f (cartesian xs ys)) =\n  big op (map (fun x => big op (map (fun y => f (x, y)) ys)) xs).\nProof using.\n  induction xs; simpl; intros.\n  (* Nil. *)\n  reflexivity.\n  (* Cons. *)\n  rewrite map_app.\n  rewrite map_map.\n  rewrite big_app by assumption.\n  rewrite IHxs.\n  reflexivity.\nQed.\n\nGoal\n  forall A B C : Type,\n  forall op `{Unit C op, Commutative C op, Associative C op},\n  forall f : A * B -> C,\n  forall xs ys,\n  \\big[op]_(xy <- cartesian xs ys) (f xy) =\n  \\big[op]_(x <- xs) \\big[op]_(y <- ys) (f (x, y)).\nProof using.\n  intros. eapply bigop_cartesian; eauto with typeclass_instances.\nQed.\n", "meta": {"author": "fakusb", "repo": "coq-bigO", "sha": "5607fd6cf3d9a30eac05c78f8efa500573b29630", "save_path": "github-repos/coq/fakusb-coq-bigO", "path": "github-repos/coq/fakusb-coq-bigO/coq-bigO-5607fd6cf3d9a30eac05c78f8efa500573b29630/src/Big.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7488840282256863}}
{"text": "Require Import ZArith.\nRequire Import Psatz.\nOpen Scope Z_scope.\n\nLemma two_x_eq_1 : forall x, 2 * x = 1 -> False.\nProof.\n  intros.\n  lia.\nQed.\n\nLemma two_x_y_eq_1 : forall x y, 2 * x + 2 * y = 1 -> False.\nProof.\n  intros.\n  lia.\nQed.\n\nLemma two_x_y_z_eq_1 : forall x y z, 2 * x + 2 * y + 2 * z= 1 -> False.\nProof.\n  intros.\n  lia.\nQed.\n\nLemma omega_nightmare : forall x y, 27 <= 11 * x + 13 * y <= 45 ->  -10 <= 7 * x - 9 * y <= 4 -> False.\nProof.\n  intros ; intuition auto.\n  lia.\nQed.\n\nLemma compact_proof : forall z,\n (z < 0) ->\n (z >= 0) ->\n  (0 >= z \\/ 0 < z) -> False.\nProof.\n intros.\n lia.\nQed.", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/micromega/zomicron.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7488322901707184}}
{"text": "\nLemma and_comm: forall P Q, P/\\Q -> Q /\\ P.\nProof.\nintros.\ndestruct H.\nsplit.\n * assumption.\n * assumption.\nQed.\n\nPrint and_comm.\n\n\n\nLemma or_comm: forall P Q, P \\/ Q -> Q \\/ P.\nProof.\nintros.\ndestruct H.\n * right. \n   assumption.\n * left;assumption.\nQed.\n\nPrint or_comm.\n\nPrint iff.\n\nLemma Iff_or_comm: forall P Q, P \\/ Q <-> Q \\/ P.\nProof.\nintros.\nsplit; apply or_comm.\nQed.\n\n\nPrint False.\n\nLemma FalseImpliesAny: False -> 2+2=5.\nProof.\nintro.\ndestruct H.\nQed.\n\n\nLemma negations: forall P Q :Prop, ~P -> ~ ~ P -> Q.\nProof.\nintros.\n(*contradiction.*)\ndestruct H0.\nassumption.\nQed.\n\n\nPrint ex.\n\n\n(*Lemma is: @ex nat (fun x:nat => x+1 = 2).*)\n\nLemma istnieje1: exists x, x+1=2.\nProof.\nexists 1.\nsimpl.\ntrivial.\nQed.\n\nLemma istnieje2: forall m n, (exists x, x+n = m) -> (n=m) \\/ (exists k, m = S k).\nProof.\nintros.\ndestruct H.\ndestruct x.\n(*destruct x eqn:?.*)\n* left.\n  simpl in H.\n  assumption.\n* right.\n  simpl in H.\n  exists (x+n).\n  symmetry.\n  assumption.\nQed.\n \n\nDefinition Double_neg : Prop := forall P:Prop, ~~P -> P.\n\nDefinition Exm : Prop := forall P : Prop, P \\/ ~P.\n\nDefinition Classical_impl : Prop := forall P Q:Prop, (P -> Q) -> ~P \\/ Q.\n\nDefinition Peirce : Prop := forall P Q : Prop, ((P -> Q) -> P) -> P.\n\nDefinition Not_forall_not_exists : Prop :=\n           forall (A:Type)(P:A->Prop), ~(forall x:A, ~P x) -> ex P.\n\n\nLemma  Exm_Double_neg : Exm -> Double_neg.\nProof.\n unfold Double_neg.\n intros H P.\n destruct (H P) as [p | p'].\n - intro;assumption.\n - (* generalize p'. *)\n apply negations.\n assumption. \n(* intro H1.\n apply (negations P); assumption.*)\nQed.\n\n\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/Slajdy19/PlikiCoqa/flogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7488032743052758}}
{"text": "Require Import Bool.\nRequire Import Arith.\n\nInductive lst : Type :=\n| Cons : nat -> lst -> lst\n| Nil : lst.\n\nInductive heap : Type :=\n| Hleaf : heap\n| Heap : nat -> nat -> heap -> heap -> heap.\n\nFixpoint right_height (h : heap) : nat :=\n  match h with\n  | Hleaf => 0\n  | Heap k v l r => right_height r + 1\n  end.\n\nDefinition rank (h : heap) : nat :=\n  match h with\n  | Hleaf => 0\n  | Heap k v l r => k\n  end.\n\nFixpoint has_leftist_property (h : heap) : bool :=\n  match h with\n  | Hleaf => true\n  | Heap k v l r =>\n    has_leftist_property l\n    && has_leftist_property r\n    && (right_height r <=? right_height l)\n    && (k =? right_height r + 1)\n  end.\n\nFixpoint hsize (h : heap) : nat :=\n  match h with\n  | Hleaf => 0\n  | Heap k v l r => hsize l + hsize r + 1\n  end.\n\nDefinition mergea (v : nat) (l r : heap) : heap :=\n  if rank r <=? rank l\n    then Heap (rank r + 1) v l r\n    else Heap (rank l + 1) v r l.\n\nFixpoint merge (h1 : heap) : heap -> heap :=\n  fix merge_aux (h2 : heap) : heap :=\n  match h1, h2 with\n  | h, Hleaf => h\n  | Hleaf, h => h\n  | Heap k1 v1 l1 r1, Heap k2 v2 l2 r2 =>\n    if v2 <? v1\n      then mergea v1 l1 (merge r1 (Heap k2 v2 l2 r2))\n      else mergea v2 l2 (merge_aux r2)\n  end.\n\nDefinition hinsert (h : heap) (n : nat) : heap :=\n  merge (Heap 1 n Hleaf Hleaf) h.\n\n(* Require Coq.extraction.Extraction.\n\nRecursive Extraction hinsert. *)\n\nLemma hsize_nonneg : forall h : heap, hsize h >= 0.\nProof.\n  (* This lemma is trivial since we use nat instead of Int. *)\n  intros.\n  induction (hsize h).\n  - auto.\n  - auto.\nQed.\n\nLemma rank_right_height : forall h : heap,\n  has_leftist_property h = true -> rank h = right_height h.\nProof.\n  intros.\n  induction h.\n  - auto.\n  - simpl. simpl in H. apply andb_true_iff in H. destruct H. apply Nat.eqb_eq in H0. assumption.\nQed.\n\nLemma leftist_mergea : forall (v : nat) (l r : heap),\n  has_leftist_property l && has_leftist_property r = true\n    -> has_leftist_property (mergea v l r) = true.\nProof.\n  intros.\n  unfold mergea.\n  apply andb_true_iff in H. destruct H.\n  destruct (Nat.leb_spec (rank r) (rank l)).\n  - rewrite (rank_right_height r H0) in H1.\n    rewrite (rank_right_height l H) in H1.\n    simpl. rewrite (rank_right_height r H0).\n    apply andb_true_iff. split.\n    + apply andb_true_iff. split.\n      * rewrite H. rewrite H0. reflexivity.\n      * apply Nat.leb_le. assumption.\n    + apply Nat.eqb_eq. reflexivity.\n  - rewrite (rank_right_height r H0) in H1.\n    rewrite (rank_right_height l H) in H1.\n    simpl. rewrite (rank_right_height l H).\n    apply le_Sn_le in H1.\n    apply andb_true_iff. split.\n    + apply andb_true_iff. split.\n      * rewrite H. rewrite H0. reflexivity.\n      * apply Nat.leb_le. assumption.\n    + apply Nat.eqb_eq. reflexivity.\nQed.\n\nLemma leftist_merge : forall h1 h2 : heap,\n  has_leftist_property h1 && has_leftist_property h2 = true\n    -> has_leftist_property (merge h1 h2) = true.\nProof.\n  intro h1.\n  induction h1.\n  - intros. destruct h2.\n    + reflexivity.\n    + simpl. simpl in H. assumption.\n  - intros. induction h2.\n    + simpl. apply andb_true_iff in H. destruct H. simpl in H. assumption.\n    + apply andb_true_iff in H. destruct H. simpl in H. apply andb_true_iff in H. destruct H. apply andb_true_iff in H. destruct H. apply andb_true_iff in H. destruct H. simpl. destruct (n2 <? n0).\n      * apply leftist_mergea. apply andb_true_iff. split.\n        -- assumption.\n        -- apply IHh1_2. rewrite H3. rewrite H0. reflexivity.\n      * simpl in H0. apply andb_true_iff in H0. destruct H0. apply andb_true_iff in H0. destruct H0. apply andb_true_iff in H0. destruct H0. simpl in IHh2_2. apply leftist_mergea. apply andb_true_iff. split.\n        -- assumption.\n        -- apply IHh2_2. rewrite H. rewrite H3. rewrite H2. rewrite H1. rewrite H6. reflexivity.\nQed.\n\nTheorem leftist_hinsert : forall (x : heap) (n : nat),\n  has_leftist_property x = true -> has_leftist_property (hinsert x n) = true.\nProof.\n  intros. unfold hinsert. apply leftist_merge. apply andb_true_iff. split.\n  - unfold has_leftist_property. reflexivity.\n  - assumption.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/heap_insert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7488032580984397}}
{"text": "\n(**Modal definitions based on Benzmuller and Paleo 2015**)\nParameter W: Type. (* Type for worlds *)\nParameter e: Type. (* Typefor individuals *)\nDefinition MProp := W  -> Prop. (* Type of modal propositions *)\nParameter R: W -> W -> Prop. (* Accessibility relation for worlds *)\n\n(**Defining the modal connectives**)\nDefinition mnot (p: MProp)(w: W) := ~ (p w).\nNotation \"m~ p\" := (mnot p) (at level 74, right associativity).\n\nDefinition mand (p q:MProp)(w: W) := (p w) /\\ (q w).\nNotation \"p m/\\ q\" := (mand p q) (at level 79, right associativity).\nDefinition mor (p q:MProp)(w: W) := (p w) \\/ (q w).\nNotation \"p m\\/ q\" := (mor p q) (at level 79, right associativity).\nDefinition mimplies (p q:MProp)(w:W) := (p w) -> (q w).\nNotation \"p m-> q\" := (mimplies p q) (at level 99, right associativity).\nDefinition mequiv (p q:MProp)(w:W) := (p w) <-> (q w).\nNotation \"p m<-> q\" := (mequiv p q) (at level 99, right associativity).\nDefinition mequal (x y: MProp)(w: W) := x = y.\nNotation \"x m= y\" := (mequal x y) (at level 99, right associativity).\n\nDefinition A {t: Type}(p: t -> MProp)(w: W) := forall x, p x w.\nNotation \"’mforall’ x , p\" := (A (fun x => p))\n(at level 200, x ident, right associativity) : type_scope.\n\nDefinition E {t: Type}(p: t -> MProp)(w: W) := exists x, p x w.\nNotation \"’mexists’ x , p\" := (E (fun x => p))(at level 200, x ident, right associativity) : type_scope.\n\nDefinition box (p: MProp) := fun w:W => forall w1, (R w w1) -> (p w1).\nDefinition dia (p: MProp) := fun w:W => exists w1, (R w w1) /\\ (p w1).\n\nDefinition V (p: MProp) := forall w, p w.\n\nNotation \"[ p ]\" := (V p).\n\n(** A bit of Montague**)\nParameter Man Human Walk : (e->MProp).\n\n\nDefinition man:=  fun x:e=> Man  x.\nDefinition human:= fun x:e=> Human  x.\nDefinition walk:= fun x:e=> Walk  x.\n\nParameter w_c:W.\nCheck E.\nDefinition a:= fun CN: (e->MProp)=>  fun VP:(e->MProp)=> fun w:W=> exists x,  \n                                                                           (VP x w).\nCheck a. \nCheck a.\nCheck (a man)  walk.\nCheck box.\nDefinition neccessarily:= fun P:MProp=>   box (P).\nDefinition possibly:= fun P:MProp=>  dia(P). \nTheorem NEC: neccessarily ((a man) walk) w_c-> exists w: W, R w_c w->  ((a man) walk w).\n  cbv. intros. exists w_c. intro. elim H with w_c. intros. exists x. apply H1. assumption. Qed.\n\nTheorem NEC2: neccessarily ((a man) walk) w_c-> forall w: W, R w_c w->  ((a man) walk w). cbv. intros.  apply H. assumption. Qed.\n\nSection POSS.\n  Variable refl: forall w: W,  R w w.\n  Variable trans: forall w w1 w2, R w w1 /\\ R w1 w2 -> R w w2.\n  Variable x:e.\n  (**Axiom M, needs refl**)\nTheorem NECW:  neccessarily ((a man) walk) w_c->   ((a man) walk) w_c. cbv. \n                                                                       firstorder.            Qed.\n(**Axiom D, needs refl**) \nTheorem NECPOSS:  neccessarily ((a man) walk) w_c->  possibly  ((a man) walk) w_c. cbv. firstorder. Qed.\n\n(**dia dia -> dia,  needs transitivity**)\nTheorem POSSPOSS:  possibly (possibly ((a man) walk)) w_c->  possibly  ((a man) walk) w_c. cbv. firstorder. Qed.\n\n(**Other theorems can be proven depending on the properties defined on the accessibility relation**)\nEnd POSS. \n", "meta": {"author": "StergiosCha", "repo": "CoqNL", "sha": "cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c", "save_path": "github-repos/coq/StergiosCha-CoqNL", "path": "github-repos/coq/StergiosCha-CoqNL/CoqNL-cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c/Code/Tutorial2_FS_in_Coq/modal_Montague.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8056321913146128, "lm_q1q2_score": 0.7487871107945492}}
{"text": "(*Require Import stdpp.base stdpp.numbers.\n*)\nRequire Import QArith.\nRecord V2 (a : Type) := {\n                         x2 : a;\n                         y2 : a\n                       }.\n\nArguments x2 {a}.\nArguments y2 {a}.\n\n\n\nRecord M2 := {\n              c1 : V2 Q;\n              c2 : V2 Q\n              }.\n\nOpen Scope Q_scope.\nDefinition vadd v w : V2 Q := {| x2 := v.(x2) + w.(x2) ; y2 := v.(y2) + w.(y2)  |}.\n\nDefinition smul s v : V2 Q := {| x2 := s * v.(x2) ; y2 := s * v.(y2)   |}.\n\nDefinition dot v w : Q := v.(x2) * w.(x2) + v.(y2) * w.(y2).\n\nDefinition mapply m v := vadd (smul v.(x2) m.(c1)) (smul v.(y2) m.(c2)).\n\n\n\nRequire Import Ring.\nRequire Import Psatz.\nRequire Import Lqa.\n\nGoal forall x y , x + y == x + y. intros. lra. Qed.\n\nDefinition VEq v w := v.(x2) == w.(x2)  /\\ v.(y2) == w.(y2).\nNotation \"x == y\" := (VEq x y).\nNotation \" x + y \" := (vadd x  y).\nNotation \" s * y \" := (smul s y).\n\n\n\nDefinition vzero := {| x2 := 0 ; y2 := 0 |}.\n\nDefinition xhat := {| x2 := 1 ; y2 := 0 |}.\n\nDefinition yhat := {| x2 := 0 ; y2 := 1 |}.\nCheck vzero.\nCheck vzero == vzero.\nTheorem vadd_comm : forall v w, v + w == w + v. Proof. intros. split; simpl; lra. Qed.\n\n(* This is a setoid equality. :/   Does lra not work on Qc? *)\n\nTheorem linop : forall v w m, mapply m (vadd v w) == (vadd (mapply m v)  (mapply m w)).\n  intros. unfold mapply. unfold vadd. simpl. split; simpl; lra. Qed.\n\nTheorem linop2 : forall s v m, mapply m (smul s v) == smul s (mapply m v).\n  intros. unfold mapply. unfold smul. simpl. split; simpl; lra. Qed.\n\nDefinition mcompose m n :=  {|\n                            c1 := mapply m n.(c1);\n                            c2 := mapply m n.(c2)\n\n                            |}.\n\nNotation \" m @@ n \" := (mcompose m n) (at level 50) .\nNotation \" m @ v \" := (mapply m v) (at level 50) .\n\n\n\nTheorem matrixgood : forall m n v, mapply m (mapply n v) == mapply ( mcompose m n ) v.\n   intros. unfold mapply. unfold mcompose. simpl. split; simpl; lra. Qed.\n\nDefinition madd m n := {|\n                        c1 := vadd m.(c1) n.(c1);\n                        c2 := vadd m.(c2) n.(c2)\n                      |}.\n\nNotation \"<< a b >>\" := {| x2 := a ; y2 := b |}.\nNotation \"<< a b , c d >>\" := {| c1 := {| x2 := a ; y2 := c|} ; c2 := {| x2 := b ; y2 := d |} |}.\n\nCheck << 1 0 >> .\n\n(*\n\nhttps://www.labri.fr/perso/casteran/CoqArt/TypeClassesTut/typeclassestut.pdf\nHe does a 2x2 matrix type\n*)\n\nRequire Import Extraction.\nRequire Import Coq.extraction.ExtrOcamlNatInt  Coq.extraction.ExtrOcamlZInt.\nRecursive Extraction vadd.\nRecursive Extraction smul.\n\nGoal dot vzero vzero <= 1. cbn. unfold dot. simpl. lra. Qed.\n\n\n\n\nTheorem vadd_comm : forall v w, vadd v w = vadd w v. Proof.\n                                                  intros v w. destruct v. destruct w. unfold vadd. cbn.  assert (x3 + x4 = x4 + x3). ring.  assert (y3 + y4 = y4 + y3). ring.  rewrite H. rewrite H0. auto. Qed.\n\nTheorem smul_assoc : forall a b v, smul a (smul b v)  = smul (a * b) v. Proof.\n     intros. destruct v.  unfold smul. cbn.  assert (a * (b * x3) = a * b * x3). ring.  assert (a * (b * y3) = a * b * y3). ring.  rewrite H. rewrite H0. auto. Qed.\n\n\n", "meta": {"author": "philzook58", "repo": "coq-vector", "sha": "18b71378556265e239126cf8497aeb1ee7182631", "save_path": "github-repos/coq/philzook58-coq-vector", "path": "github-repos/coq/philzook58-coq-vector/coq-vector-18b71378556265e239126cf8497aeb1ee7182631/matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7487756189527229}}
{"text": "Require Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.Combinatorics.FiniteSets.\nRequire Import UniMath.CategoryTheory.Core.Categories.\n\nRequire Import prelude.\nRequire Import syntax.containers.\nRequire Import syntax.hit_signature.\nRequire Import syntax.W_types.\nRequire Import algebra.set_algebra.\n\nLocal Open Scope container_scope.\n\n(**\nMonoids\n\nInductive monoid : Type :=\n| 1 : monoid\n| m : monoid -> monoid -> monoid\n| nl : ∏ (x : monoid), m(x, 1) = x\n| nr : ∏ (x : monoid), m(1, x) = x\n| assoc : ∏ (x y z : monoid), m(x, m(y, z)) = m(m(x, y), z)\n *)\nDefinition monoid_operations\n  : hSet\n  := setcoprod unitset unitset.\n\nDefinition monoid_unit\n  : monoid_operations\n  := inl tt.\n\nDefinition monoid_mult\n  : monoid_operations\n  := inr tt.\n\nDefinition monoid_arities\n  : monoid_operations → hSet.\nProof.\n  intro x.\n  induction x as [ | ].\n  - exact emptyset.\n  - exact boolset.\nDefined.\n\nDefinition monoid_sig_point_constr\n  : container.\nProof.\n  use make_container.\n  - exact monoid_operations.\n  - exact monoid_arities.\nDefined.\n\nDefinition monoid_eqs\n  : hSet\n  := setcoprod\n       unitset\n       (setcoprod\n          unitset\n          unitset).\n\nDefinition monoid_neutral_left\n  : monoid_eqs\n  := inl tt.\n\nDefinition monoid_neutral_right\n  : monoid_eqs\n  := inr (inl tt).\n\nDefinition monoid_assoc\n  : monoid_eqs\n  := inr (inr tt).\n\nDefinition monoid_eqs_args\n  : monoid_eqs → hSet.\nProof.\n  intros x.\n  induction x as [ | [ | ]].\n  - exact unitset.\n  - exact unitset.\n  - exact (setcoprod unitset (setcoprod unitset unitset)).\nDefined.\n\nDefinition monoid_sig_path_arg\n  : container.\nProof.\n  use make_container.\n  - exact monoid_eqs.\n  - exact monoid_eqs_args.\nDefined.\n\nDefinition W_unit\n           (A : hSet)\n  : W monoid_sig_point_constr A.\nProof.\n  use sup.\n  - exact monoid_unit.\n  - exact fromempty.\nDefined.\n\nDefinition W_mult\n           {A : hSet}\n           (x y : W monoid_sig_point_constr A)\n  : W monoid_sig_point_constr A.\nProof.\n  use sup.\n  - exact monoid_mult.\n  - intro b.\n    induction b.\n    + exact x.\n    + exact y.\nDefined.\n\nDefinition monoid_sig_lhs\n           (s : shapes monoid_sig_path_arg)\n  : W monoid_sig_point_constr (positions monoid_sig_path_arg s).\nProof.\n  induction s as [ | [ | ]].\n  - (* neutral left *)\n    use W_mult.\n    + refine (var _).\n      exact tt.\n    + apply W_unit.\n  - (* neutral right *)\n    use W_mult.\n    + apply W_unit.\n    + refine (var _).\n      exact tt.\n  - (* associativity *)\n    use W_mult.\n    + refine (var _).\n      exact (inl tt).\n    + use W_mult.\n      * refine (var _).\n        exact (inr (inl tt)).\n      * refine (var _).\n        exact (inr (inr tt)).\nDefined.\n\nDefinition monoid_sig_rhs\n           (s : shapes monoid_sig_path_arg)\n  : W monoid_sig_point_constr (positions monoid_sig_path_arg s).\nProof.\n  induction s as [ | [ | ]].\n  - (* neutral left *)\n    refine (var _).\n    exact tt.\n  - (* neutral right *)\n    refine (var _).\n    exact tt.\n  - (* associativity *)\n    use W_mult.\n    + use W_mult.\n      * refine (var _).\n        exact (inl tt).\n      * refine (var _).\n        exact (inr (inl tt)).\n    + refine (var _).\n      exact (inr (inr tt)).\nDefined.\n\nDefinition monoid_sig : hit_signature.\nProof.\n  use make_hit_signature.\n  - exact monoid_sig_point_constr.\n  - exact monoid_sig_path_arg.\n  - exact monoid_sig_lhs.\n  - exact monoid_sig_rhs.\nDefined.\n\nDefinition is_finitary_monoid_sig\n  : is_finitary_hit monoid_sig.\nProof.\n  split.\n  - intro x.\n    induction x as [ | ] ; cbn -[isfinite].\n    + apply isfiniteempty.\n    + apply isfinitebool.\n  - intro x.\n    induction x as [ | [ | ]] ; cbn -[isfinite].\n    + apply isfiniteunit.\n    + apply isfiniteunit.\n    + use isfinitecoprod.\n      * apply isfiniteunit.\n      * use isfinitecoprod.\n        ** apply isfiniteunit.\n        ** apply isfiniteunit.\nQed.\n\nSection MonoidAlgebra.\n  Variable (X : hit_algebra monoid_sig).\n\n  Definition monoid_carrier\n    : hSet\n    := pr11 X.\n\n  Definition monoid_alg_unit\n    : monoid_carrier\n    := pr21 X (monoid_unit ,, fromempty).\n\n  Definition monoid_alg_mult\n             (x y : monoid_carrier)\n    : monoid_carrier.\n  Proof.\n    refine (pr21 X (monoid_mult ,, _)).\n    intro b.\n    induction b.\n    - exact x.\n    - exact y.\n  Defined.\n\n  Local Notation e := monoid_alg_unit.\n  Local Notation \"x · y\" := (monoid_alg_mult x y).\n\n  Definition monoid_alg_neutral_left\n             (x : monoid_carrier)\n    : x · e = x.\n  Proof.\n    pose (p := pr2 X monoid_neutral_left (λ _, x)).\n    cbn in p.\n    refine (_ @ p) ; clear p.\n    unfold monoid_alg_mult ; cbn.\n    do 2 apply maponpaths.\n    use funextsec.\n    intro b.\n    induction b.\n    - apply idpath.\n    - unfold monoid_alg_unit ; cbn.\n      do 2 apply maponpaths.\n      use funextsec.\n      intro q ; induction q.\n  Qed.\n\n  Definition monoid_alg_neutral_right\n             (x : monoid_carrier)\n    : e · x = x.\n  Proof.\n    pose (p := pr2 X monoid_neutral_right (λ _, x)).\n    cbn in p.\n    refine (_ @ p) ; clear p.\n    unfold monoid_alg_mult ; cbn.\n    do 2 apply maponpaths.\n    use funextsec.\n    intro b.\n    induction b.\n    - unfold monoid_alg_unit ; cbn.\n      do 2 apply maponpaths.\n      use funextsec.\n      intro q ; induction q.\n    - apply idpath.\n  Qed.\n  \n  Definition monoid_alg_assoc_help\n             (x y z : monoid_carrier)\n    : path_arg monoid_sig monoid_assoc → alg_carrier (pr1 X).\n  Proof.\n    intro b.\n    induction b as [ | [ | ]].\n    - exact x.\n    - exact y.\n    - exact z.\n  Defined.\n  \n  Definition monoid_alg_assoc\n             (x y z : monoid_carrier)\n    : x · (y · z) = (x · y) · z.\n  Proof.\n    pose (p := pr2 X monoid_assoc (monoid_alg_assoc_help x y z)).\n    refine (_ @ p @ _) ; clear p.\n    - unfold monoid_alg_mult ; cbn.\n      do 2 apply maponpaths.\n      use funextsec.\n      intro b ; induction b ; cbn.\n      + apply idpath.\n      + do 2 apply maponpaths.\n        use funextsec.\n        intro b ; induction b ; cbn.\n        * apply idpath.\n        * apply idpath.\n    - unfold monoid_alg_mult ; cbn.\n      do 2 apply maponpaths.\n      use funextsec.\n      intro b ; induction b ; cbn.\n      + do 2 apply maponpaths.\n        use funextsec.\n        intro b ; induction b ; cbn.\n        * apply idpath.\n        * apply idpath.\n      + apply idpath.\n  Defined.\nEnd MonoidAlgebra.\n\nDefinition make_monoid_algebra\n           (G : hSet)\n           (e : G)\n           (i : G → G)\n           (m : G → G → G)\n           (nl : ∏ (g : G), m g e = g)\n           (nr : ∏ (g : G), m e g = g)\n           (a : ∏ (g₁ g₂ g₃ : G),\n                m g₁ (m g₂ g₃)\n                =\n                m (m g₁ g₂) g₃)\n  : hit_algebra monoid_sig.\nProof.\n  simple refine ((G ,, _) ,, _) ; cbn.\n  - intro x.\n    induction x as [s p].\n    induction s as [ | ] ; cbn in p.\n    + exact e.\n    + exact (m (p true) (p false)).\n  - intros j p.\n    induction j as [ | [ | ]] ; cbn in p ; cbn.\n    + apply nl.\n    + apply nr.\n    + apply a.\nDefined.\n", "meta": {"author": "nmvdw", "repo": "FinitaryFunctors", "sha": "7342b68819209fda64d2be8c8f0dbf5305e3608a", "save_path": "github-repos/coq/nmvdw-FinitaryFunctors", "path": "github-repos/coq/nmvdw-FinitaryFunctors/FinitaryFunctors-7342b68819209fda64d2be8c8f0dbf5305e3608a/new_code/examples/monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.74877493393823}}
{"text": "Require Import MathUtils.\n\nModule Export RSA.\n\nDefinition rsa_keygen_public (p q : nat) : nat * nat\n  := \n  let euler_totient := (p - 1) * (q - 1) in\n  let n := (p * q) in \n    ((coprime euler_totient) , n).\n\nDefinition rsa_keygen_private (p q : nat) : nat * nat\n  := \n  let e := (fst (rsa_keygen_public p q)) in\n  let n := p * q in\n  let euler_totient := (p - 1) * (q - 1) in\n    ((mod_inv e euler_totient) , (p * q)).\n\nDefinition rsa_encrypt' (plain_text : nat) (public_key : nat * nat) : nat\n  := match public_key with\n     | (e , n) => modl (exp plain_text e) n\n     end.\n\nDefinition rsa_encrypt'' (p q : nat) (plain_text : nat) : nat\n  :=\n  let public_key := (rsa_keygen_public p q) in\n    (rsa_encrypt' plain_text public_key).\n\nDefinition rsa_encrypt (p q : nat) (plain_text : list nat) : list nat\n  := loop (rsa_encrypt'' p q) plain_text.\n\nDefinition rsa_decrypt' (cipher_text : nat) (private_key : nat * nat) : nat\n  := match private_key with\n     | (d , n) => modl (exp cipher_text d) n\n     end.\n\nDefinition rsa_decrypt'' (p q : nat) (cipher_text : nat) : nat\n  :=\n  let private_key := (rsa_keygen_private p q) in\n    rsa_decrypt' cipher_text private_key.\n\nDefinition rsa_decrypt (p q : nat) (cipher_text : list nat) : list nat\n  := loop (rsa_decrypt'' p q) cipher_text.\n\nEnd RSA.", "meta": {"author": "pavenvivek", "repo": "Coq-Crypto", "sha": "7b20a3d8b7dc11148cc12f7435fb001cb0e20c3c", "save_path": "github-repos/coq/pavenvivek-Coq-Crypto", "path": "github-repos/coq/pavenvivek-Coq-Crypto/Coq-Crypto-7b20a3d8b7dc11148cc12f7435fb001cb0e20c3c/CryptDB/rsa_cryptosystem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305328688783, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7487189545089691}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nRequire Import Arith.\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint less (less_arg0 : natural) (less_arg1 : natural) : bool\n           := match less_arg0, less_arg1 with\n              | x, Zero => false\n              | Zero, Succ x => true\n              | Succ x, Succ y => less x y\n              end.\nFixpoint eqb (n m: natural) : bool :=\nmatch n, m with\n   | Zero, Zero => true\n   | Zero, Succ _ => false\n   | Succ _, Zero => false\n   | Succ n', Succ m' => eqb n' m'\nend.\nDefinition leq (x : natural) (y : natural) : bool :=\neqb x y || less x y.\n(* \nFixpoint leq (n m : natural) : bool :=\nmatch n, m with\n| Zero  , x   => true\n| x , Zero   => false\n| Succ x, Succ y => leq x y\nend. *)\n\nFixpoint insort (insort_arg0 : natural) (insort_arg1 : lst) : lst\n           := match insort_arg0, insort_arg1 with\n              | i, Nil => Cons i Nil\n              | i, Cons x y => if less i x then Cons i (Cons x y) else Cons x (insort i y)\n              end.\n\nFixpoint sorted (sorted_arg0 : lst) : bool\n:= match sorted_arg0 with\n   | Nil => true\n   | Cons x l => match l with\n      | Nil => true\n      | Cons z y => andb (sorted l) (leq x z)\n      end\n   end.\n\nFixpoint sort (sort_arg0 : lst) : lst\n           := match sort_arg0 with\n              | Nil => Nil\n              | Cons x y => insort x (sort y)\n              end.\nLemma not_less : forall (x y : natural), less x y = false -> leq y x = true.\nProof.\n   intros.\n   generalize dependent y.\n   induction x.\n   - intros. unfold leq. destruct y.\n   + simpl in H. apply IHx in H. unfold leq in H. simpl. assumption.\n   + reflexivity.\n   - intros. unfold leq. destruct y.\n   + discriminate.\n   + reflexivity.\nQed.\n              \nTheorem theorem0 : forall (x : lst) (y : natural), eq (sorted x) true -> eq (sorted (insort y x)) true.\nProof.\n   (* intros.\n  induction x.\n  - destruct x.\n    + simpl. destruct (less y n) eqn:?.\n      * simpl. unfold leq. rewrite Heqb. admit.\n      * simpl. lfind.  assumption. \nAdmitted.\n\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal62_theorem0_75_not_less/goal62.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7487076110176782}}
{"text": "Require Export induction.\nModule NatList.\n  \n  Inductive natprod : Type :=\n  | pair : nat -> nat -> natprod.\n\n  Definition fst (p :natprod) : nat :=\n    match p with\n    | pair x y => x\n    end.\n\n  Definition snd (p : natprod) : nat :=\n    match p with\n    | pair x y => y\n    end.\n\n  Notation \"( x , y )\" := (pair x y).\n\n  Definition fst' ( p :natprod) : nat :=\n    match p with\n    | (x,y) =>x\n    end.\n\n  Definition snd' (p : natprod) : nat :=\n    match p with\n    | (x,y) => y\n    end.\n\n  Definition swap_pair (p : natprod) : natprod :=\n    match p with\n    | (x,y)=>(y,x)\n    end.\n\n  Theorem surjective_pairing' : forall (n m : nat),\n      (n,m) = (fst (n,m), snd (n,m)).\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem snd_fst_is_swap : forall (p : natprod),\n      (snd p, fst p) = swap_pair p.\n  Proof.\n    intros [n m].\n    reflexivity.\n  Qed.\n\n  Theorem fst_swap_is_snd : forall (p: natprod),\n      fst (swap_pair p) = snd p.\n  Proof.\n    intros [n m].\n    reflexivity.\n  Qed.\n\n  Inductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n  Notation \"x :: l\" := (cons x l)\n                         (at level 60, right associativity).\n  Notation \"[ ]\" := nil.\n  Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) .. ).\n\n\n  Definition mylist3 := [1;2;3].\n  Definition mylist2 := 1 :: 2 :: 3 :: nil.\n  Definition mylist1 :=  1 :: (2 :: (3 :: nil)).\n\n  Fixpoint repeat (n count : nat) : natlist :=\n    match count with\n    | 0 => nil\n    | S count' =>  n :: (repeat n count')\n    end.\n\n  Fixpoint length (l:natlist) : nat :=\n    match l with\n    | nil => 0\n    |  h :: t => S (length t)\n    end.\n\n  Fixpoint app (l1 l2 : natlist) : natlist :=\n    match l1 with\n    | nil => l2\n    | h :: t => h :: (app t l2)\n    end.\n\n  Notation \"x ++ y\" := (app x y)\n                         (right associativity, at level 60).\n\n  Definition hd (default:nat) (l:natlist) :nat  :=\n    match l with\n    | nil => default\n    | h :: t => h\n    end.\n\n  Definition tl (l:natlist) : natlist :=\n    match l with\n    | nil => nil\n    | h :: t => t\n    end.\n\n  Fixpoint 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\n  Fixpoint 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\n  Fixpoint countoddmembers (l : natlist) : nat :=\n    match l with\n    | nil => 0\n    | h :: t =>\n      match (oddb h) with\n      | true => S (countoddmembers t)\n      | false => countoddmembers t\n      end\n    end.\n\n  Fixpoint alternate ( l1 l2 : natlist)  : natlist :=\n    match l1 with\n    | nil => l2\n    | h :: t =>\n      match l2 with\n      | nil => l1 \n      | h' :: t' => h :: h' :: ( alternate t t')\n      end\n    end.\n\n  Definition bag := natlist.\n    \n  Fixpoint count (v:nat) (s:bag) : nat :=\n    match s with\n    | nil => 0\n    | h :: t =>\n      match (beq_nat v h) with\n      | true => S (count v t)\n      | false => (count v t)\n      end\n    end.\n  \n  Definition sum : bag -> bag -> bag := alternate.\n  \n  Definition  add ( v:nat)(s:bag) : bag := v :: s .\n\n  Definition member (v:nat) (s:bag) : bool := negb ( beq_nat 0 (count v s)).\n\n  Fixpoint remove_one (v:nat) (s:bag) : bag :=\n    match s with\n    | nil => nil\n    | h :: t =>\n      match (beq_nat v h) with\n      | true => t\n      | false => remove_one v t\n      end\n    end.\n\n  Fixpoint 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\n  Theorem beqT : forall n : nat, beq_nat n n = true.\n  Proof.\n    intros n.\n    induction  n as  [| n' H'].\n    - reflexivity.\n    - simpl.\n      congruence.\n  Qed.\n  \n  Theorem bag_theorem : forall  n: natlist, forall m:nat,\n        S (count m n) =  (count m (add m n)).\n  Proof.\n    intros m n.\n    simpl.\n    rewrite  beqT.\n    reflexivity.\n  Qed.\n\n  Theorem app_assoc : forall l1 l2 l3 : natlist,\n      (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n  Proof.\n    intros l1 l2 l3.\n    induction l1 as [| n l1' IHl1'].\n    - reflexivity.\n    - simpl.\n      rewrite <- IHl1'.\n      reflexivity.\n  Qed.\n\n  Fixpoint rev (l:natlist) :natlist :=\n    match l with\n    | nil => []\n    | h :: t =>  rev t ++ [h]\n    end.\n\n  Theorem app_length : forall l1 l2 : natlist,\n      length (l1 ++ l2) = (length l1) + (length l2).\n  Proof.\n    intros l1 l2.\n    induction l1 as [| n l1' IHl1'].\n    - reflexivity.\n    - simpl.\n      rewrite IHl1'.\n      reflexivity.\n  Qed.\n  \n  Theorem rev_length: forall l : natlist,\n      length (rev l) = length l.\n  Proof.\n    intros l.\n    induction l as [| n l' IHn'].\n    - reflexivity.\n    - simpl.\n      rewrite -> app_length,plus_comm.\n      rewrite IHn'.\n      reflexivity.\n  Qed.\n\n  Theorem app_nil_r : forall l : natlist,\n      l ++ [] = l.\n  Proof.\n    intros l.\n    induction l as [| n l' IHl'].\n    - reflexivity.\n    - simpl.\n      rewrite IHl'.\n      reflexivity.\n  Qed.\n\n\n  Theorem rev_app_distr : forall l1 l2: natlist,\n      rev (l1 ++ l2) = rev l2 ++ rev l1.\n  Proof.\n    intros l1 l2.\n    induction l1 as [| n l' IHl'].\n    - simpl.\n      rewrite -> app_nil_r.\n      reflexivity.\n    - simpl.\n      rewrite IHl'.\n      rewrite -> app_assoc.\n      reflexivity.\n  Qed.\n  \n  Theorem rev_involutive : forall l : natlist,\n      rev (rev l) = l.\n  Proof.\n    intros l.\n    induction l as [| n l' IHl'].\n    - reflexivity.\n    - simpl.\n      rewrite rev_app_distr.\n      rewrite IHl'.\n      reflexivity.\n  Qed.\n\n  Theorem app_assoc4  : forall l1 l2 l3 l4 : natlist,\n      l1 ++ ( l2 ++ ( l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\n  Proof.\n    intros l1 l2 l3 l4.\n    rewrite <- app_assoc.\n    rewrite <- app_assoc.\n    reflexivity.\n  Qed.\n\n  Theorem nonzerosT: forall l1 : natlist,forall n : nat,\n        nonzeros(n :: l1) = (nonzeros [n]) ++ (nonzeros l1).\n  Proof.\n    intros l1 n.\n    destruct n as [ | n'].\n    - simpl.\n      reflexivity.\n    - simpl.\n      reflexivity.\n  Qed.\n  \n  Lemma nonzeros_app : forall l1 l2 :natlist,\n      nonzeros ( l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\n  Proof.\n    intros l1 l2.\n    induction l1 as [| n l IHl'].\n    - reflexivity.\n    - rewrite -> nonzerosT.\n      rewrite -> app_assoc.\n      rewrite <- IHl'.\n      rewrite <- nonzerosT.\n      reflexivity.\n  Qed.\n\n\n  Fixpoint beq_natlist (l1 l2 : natlist) : bool :=\n    match l1 with\n    | nil =>\n      match l2 with\n        | nil => true\n        | _ => false\n      end\n    | h :: t =>\n      match l2 with\n      | nil => false\n      | h2 :: t2 =>\n        match beq_nat h h2 with\n        | true => beq_natlist t t2\n        | false => false\n        end\n      end\n    end.\n  \n  Theorem beq_natlist_refl : forall l : natlist,\n      true = beq_natlist l l.\n  Proof.\n    intros l.\n    induction l as [| n l' IHl'].\n    - reflexivity.\n    - simpl.\n      assert (H: forall k: nat, beq_nat k k =true).\n      { intros k.\n        induction k as [| k'].\n        - reflexivity.\n        - simpl.\n          congruence.\n      }\n      rewrite -> H.\n      congruence.\n  Qed.\n\n  Theorem count_member_nonzero : forall ( s : bag),\n      leb 1 (count 1 (1 :: s)) =true.\n  Proof.\n    intros s.\n    induction s as [| n l' IHl'].\n    - reflexivity.\n    - reflexivity.\n  Qed.\n\n  Theorem ble_n_Sn : forall n,\n      leb n (S n) =true.\n  Proof.\n    intros n.\n    induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl.\n      rewrite IHn'.\n      reflexivity.\n  Qed.\n  \n  Theorem remove_decreases_count: forall (s : bag),\n      leb (count 0 (remove_one 0 s)) (count 0 s) = true.\n  Proof.\n    intros s.\n    induction s as [| n l' IH'].\n    - reflexivity.\n    - destruct n as [| n'].\n      + simpl.\n        rewrite ble_n_Sn.\n        reflexivity.\n      + simpl.\n        congruence.\n  Qed.\n\n  Theorem beq_nn: forall n,\n      beq_nat n n =true.\n  Proof.\n    intros n.\n    induction n as [| n'].\n    - reflexivity.\n    - simpl.\n      congruence.\n  Qed.\n\n  Theorem bag_count_sum: forall n: nat, forall l : natlist,\n        S(count n l) = count n (sum [n] l).\n  Proof.\n    intros n l.\n    induction l as [| n' l' IH'].\n    - simpl.\n      rewrite beq_nn.\n      reflexivity.\n    - simpl.\n      rewrite beq_nn.\n      reflexivity.\n  Qed.\n\n  Theorem rev_app : forall (l1 l2:natlist),\n      rev l1 = rev l2 -> rev (rev l1) = rev (rev l2).\n  Proof.\n    intros l1 l2 H.\n    rewrite H.\n    reflexivity.\n  Qed.\n\n  Theorem rev_injective:  forall ( l1 l2 :natlist),\n      rev l1 = rev l2 -> l1 = l2.\n  Proof.\n    intros l1 l2 H.\n    apply rev_app in H.\n    rewrite rev_involutive in H.\n    rewrite rev_involutive in H.\n    congruence.\n  Qed.\n  \n  Inductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n  Fixpoint nth_error (l:natlist) (n:nat) :natoption :=\n    match l with\n    | nil => None\n    | a:: l' => match beq_nat n 0 with\n                | true => Some a\n                | false => nth_error l' (pred n)\n                end\n    end.\n\n\n  Fixpoint nth_error' (l:natlist) (n:nat) : natoption :=\n    match l with\n    | nil => None\n    | a :: l' => if beq_nat n 0 then Some a\n                 else nth_error' l' (pred n)\n    end.\n\n  Definition option_elim ( d : nat) (o : natoption) : nat :=\n    match o with \n    | Some n' => n'\n    | None  => d\n    end.\n\n  Definition hd_error (l : natlist) : natoption :=\n    match l with\n    | nil => None\n    | h :: t => Some h\n    end.\n\n  Theorem option_elim_hd : forall (l:natlist) (default:nat) ,\n      hd default l = option_elim default (hd_error l).\n  Proof.\n    intros l default.\n    destruct l as [| h  t].\n    - reflexivity.\n    - reflexivity.\n  Qed.\n\n  End NatList.\n\n\n  Inductive id : Type :=\n  | Id : nat -> id.\n\n  Definition beq_id (x1 x2 : id) :=\n    match x1, x2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n    end.\n\n  Theorem beq_nn : forall n:nat, beq_nat n n=true.\n  Proof.\n    intros n.\n    induction n as [| n'].\n    - reflexivity.\n    - simpl.\n      congruence.\n  Qed.\n  \n  \n  Theorem beq_id_refl : forall x, true = beq_id x x.\n  Proof.\n    intros x.\n    destruct x as [n'].\n    simpl.\n    rewrite beq_nn.\n    reflexivity.\n  Qed.\n\n  Module PartialMap.\n    Export NatList.\n    Inductive partial_map : Type :=\n    | empty : partial_map\n    | record : id -> nat -> partial_map -> partial_map.\n\n    Definition update (d : partial_map) (x : id) (value : nat) : partial_map :=\n      record x value d.\n\n    Fixpoint 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    Theorem update_eq :\n      forall (d : partial_map) (x: id) (v: nat),\n        find x (update d x v) = Some v.\n    Proof.\n      intros d x v.\n      simpl.\n      rewrite <- beq_id_refl.\n      reflexivity.\n    Qed.\n\n    Theorem 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.\n    Proof.\n      intros d x y o H.\n      simpl.\n      rewrite H.\n      reflexivity.\n    Qed.\n", "meta": {"author": "Hatsunespica", "repo": "Coq", "sha": "969145e20cb6525d324bd6b5b03cfcb6f7fefa8d", "save_path": "github-repos/coq/Hatsunespica-Coq", "path": "github-repos/coq/Hatsunespica-Coq/Coq-969145e20cb6525d324bd6b5b03cfcb6f7fefa8d/SF/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.748707610051304}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2018 - Pset 2 *)\n\nRequire Import Frap Pset2Sig.\n\n(* If we [either] an [option] value with [None]\n * on the right, it leaves that value unchanged,\n * (just as if we put the [None] on the left).\n * This is analogous to how appending [nil]\n * on either side of a list leaves it unchanged.\n *)\nTheorem either_None_right : forall {A} (xo : option A),\n    either xo None = xo.\nProof.\nAdmitted.\n\n(* [either] is associative, just like [++].\n *)\nTheorem either_assoc : forall {A} (xo yo zo : option A),\n    either (either xo yo) zo = either xo (either yo zo).\nProof.\nAdmitted.\n\n(* [head] should compute the head of a list, that is,\n * it should return [Some] with the first element of\n * the list if the list is nonempty, and [None]\n * if the list is empty.\n *)\nFixpoint head {A} (xs : list A) : option A.\nAdmitted.\n\nExample head_example : head [1; 2; 3] = Some 1.\nProof.\nAdmitted.\n\n(* The following theorem makes a formal connection\n * between [either] and [++].\n *)\nTheorem either_app_head : forall {A} (xs ys : list A),\n    head (xs ++ ys) = either (head xs) (head ys).\nProof.\nAdmitted.\n\n(* [leftmost_Node] should compute the leftmost node of\n * a tree. \n *\n * Please implement [leftmost_Node] directly using\n * recursion (i.e., pattern matching) on the [tree] argument,\n * without using the [flatten] operation.\n *)\nFixpoint leftmost_Node {A} (t : tree A) : option A.\nAdmitted.\n\nExample leftmost_Node_example :\n    leftmost_Node (Node (Node Leaf 2 (Node Leaf 3 Leaf)) 1 Leaf)\n    = Some 2.\nProof.\nAdmitted.\n\n(* Prove that the leftmost node of the tree is the same\n * as the head of the list produced by flattening the tree\n * with an in-order traversal.\n *)\nTheorem leftmost_Node_head : forall {A} (t : tree A),\n      leftmost_Node t = head (flatten t).\nProof.\nAdmitted.\n\n(* Now let's work with the binary tries we defined earlier!\n *\n * Define [lookup] such that [lookup k t] looks up the\n * map entry corresponding to the key [k : list bool] in the\n * binary trie [t : binary_trie A], interpreting [t] such that\n * the value at the root of [t] corresponds to the \n * entry for the key [nil], the left subtree contains entries \n * for those keys that begin with [true], and the right subtree\n * contains entries for those keys that begin with [false].\n *)\nFixpoint lookup {A} (k : list bool) (t : binary_trie A) : option A.\nAdmitted.\n\nExample lookup_example1 : lookup [] (Node Leaf (None : option nat) Leaf) = None.\nProof.\nAdmitted.\n\nExample lookup_example2 : lookup [false; true]\n    (Node (Node Leaf (Some 2) Leaf) None (Node (Node Leaf (Some 1) Leaf) (Some 3) Leaf))\n                          = Some 1.\nProof.\nAdmitted.\n\n(* [Leaf] represents an empty binary trie, so a lookup for\n * any key should return [None].\n *)\nTheorem lookup_empty {A} (k : list bool)\n  : lookup k (Leaf : binary_trie A) = None.\nProof.\nAdmitted.\n\n(* Define an operation to \"insert\" a key and optional value\n * into a binary trie. The [insert] definition should satisfy two\n * properties: one is [lookup_insert] below, which says that if we\n * look up a key [k] in a trie where [(k, v)] has just been inserted,\n * the result should be [v]. The other is that lookups on keys different\n * from the one just inserted should be the same as on the original map.\n *\n * If an entry for that key already exists, [insert] should replace\n * that entry with the new one being inserted. Note that [insert] can\n * be used to remove an entry from the trie, too, by inserting [None] \n * as the value.\n *\n * Hint: it may be helpful to define an auxiliary function that inserts\n * a key and optional value into the empty trie.\n *)\nFixpoint insert {A} (k : list bool) (v : option A) (t : binary_trie A)\n  : binary_trie A.\nAdmitted.\n\nExample insert_example1 : lookup [] (insert [] None (Node Leaf (Some 0) Leaf)) = None.\nProof.\nAdmitted.\n\nExample insert_example2 : lookup [] (insert [true] (Some 2) (Node Leaf (Some 0) Leaf)) = Some 0.\nProof.\nAdmitted.\n\nTheorem lookup_insert {A} (k : list bool) (v : option A) (t : binary_trie A)\n  : lookup k (insert k v t) = v.\nProof.\nAdmitted.\n\n\n(* You've reached the end of the problem set. Congrats!\n *\n * If you're up for a completely optional additional challenge,\n * try defining a left-biased merge function below that merges two\n * binary tries, preferring map entries from the first binary trie\n * when an entry exists for both binary tries. Then prove\n * [lookup_left_biased_merge], which formally states that lookups\n * on the merged binary trie operate in exactly this manner.\n *\n * If you don't want to complete this additional challenge, you\n * can just leave everything below unmodified.\n *)\n\nFixpoint left_biased_merge {A} (t t' : binary_trie A) : binary_trie A.\nAdmitted.\n\nTheorem lookup_left_biased_merge {A} (k : list bool) (t t' : binary_trie A)\n  : lookup k (left_biased_merge t t') = either (lookup k t) (lookup k t').\nProof.\nAdmitted.\n", "meta": {"author": "mit-frap", "repo": "spring18", "sha": "f0f8b35613938e61e2c46f1c70f2fc6a9e04659f", "save_path": "github-repos/coq/mit-frap-spring18", "path": "github-repos/coq/mit-frap-spring18/spring18-f0f8b35613938e61e2c46f1c70f2fc6a9e04659f/pset2/Pset2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.748652122863549}}
{"text": "Require Export \"Prop\".\n\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\nTheorem proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HP. Qed.\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n  split.\n  split.\n  apply HP.\n  apply HQ.\n  apply HR.\nQed.\n\nTheorem even_ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  intros.\n  induction n.\n  Case \"n = 0\".\n  split.\n  SCase \"n = 0\".\n  intros.\n  apply ev_0.\n  SCase \"n = 1\".\n  intros.\n  inversion H.\n  Case \"n -> S n\".\n  inversion IHn.\n  split.\n  apply H0.\n  intros.\n  apply ev_SS.\n  inversion H1.\n  apply H.\n  apply H3.\nQed.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity) : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n  (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA]. apply HAB. Qed.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB. Qed.\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros.\n  split.\n  trivial.\n  trivial.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  split.\n  intros. apply H3. apply H1. apply H5.\n  intros. apply H2. apply H4. apply H5.\nQed.\n\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". right. apply HP.\n    Case \"right\". left. apply HQ. Qed.\n\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. inversion H as [HP | [HQ HR]].\n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR. Qed.\n\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros.\n  inversion H. inversion H0.\n  left.\n  apply H2.\n  inversion H1.\n  left.\n  apply H3.\n  right.\n  split.\n  apply H2.\n  apply H3.\nQed.\n\n\nTheorem andb_true__and : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H. Qed.\n\nTheorem and__andb_true : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  intros.\n  destruct b.\n  simpl in H.\n  right.\n  apply H.\n  left.\n  reflexivity.\nQed.\n\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros.\n  destruct b.\n  left.\n  reflexivity.\n  simpl in H.\n  right.\n  trivial.\nQed.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros.\n  destruct b.\n  inversion H.\n  split.\n  reflexivity.\n  simpl in H.\n  apply H.\nQed.\n\nInductive False : Prop := .\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra. Qed.\n\nInductive True : Prop :=\n  I : True.\n\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nTheorem not_true__false :\n  ~ True <-> False.\nProof.\n  split.\n  Case \" -> \".\n  intros.\n  apply H.\n  apply I.\n  Case \" <- \".\n  apply ex_falso_quodlibet.\nQed.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not.\n  intros H.\n  inversion H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HP HNA].\n  unfold not in HNA.\n  apply HNA in HP.\n  inversion HP.\nQed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H. Qed.\n\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros.\n  unfold not.\n  unfold not in H0.\n  intros.\n  apply H0.\n  apply H.\n  apply H1.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros.\n  unfold not.\n  apply contradiction_implies_anything.\nQed.\n\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof.\n  induction n.\n  destruct n'.\n  intros H.\n  unfold not in H.\n  apply ex_falso_quodlibet.\n  apply H.\n  reflexivity.\n\n  intros H.\n  simpl.\n  reflexivity.\n\n  destruct n'.\n  intros H.\n  simpl.\n  reflexivity.\n\n  intros H.\n  simpl.\n  apply IHn.\n  unfold not.\n  unfold not in H.\n  intros H2.\n  apply H.\n  rewrite H2.\n  reflexivity.\nQed.\n\n(** * Existential Quantification *)\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\nTheorem some_nat_is_even :\n  ex nat ev.\nProof.\n  apply ex_intro with 4.\n  apply ev_SS.\n  apply ev_SS.\n  apply ev_0.\nQed.\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\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  exists 2.\n  reflexivity.\nQed.\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros.\n  inversion H.\n  exists (2 + witness).\n  simpl.\n  apply H0.\nQed.\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros.\n  unfold not.\n  intros.\n  inversion H0. apply H1.\n  apply H.\nQed.\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  intros.\n  split.\n  (* -> *)\n  intros.\n  inversion H as [x0 Hx].\n  inversion Hx as [Hxl | Hxr].\n  left. exists x0. apply Hxl.\n  right. exists x0. apply Hxr.\n\n  (* <- *)\n  intros.\n  inversion H as [HL | HR].\n  inversion HL as [x0 Hx]. exists x0. left. apply Hx.\n  inversion HR as [x0 Hx]. exists x0. right. apply Hx.\nQed.\n\nModule MyEquality.\n\n  Inductive eq (X:Type) : X -> X -> Prop :=\n    refl_equal : forall x, eq X x x.\n\n  Notation \"x = y\" := (eq _ x y)\n                        (at level 70, no associativity) : type_scope.\n\n  Inductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\n  Notation \"x =' y\" := (eq' _ x y)\n                         (at level 70, no associativity) : type_scope.\n\n  Theorem two_defs_of_eq_coincide : forall (X:Type) (x y : X),\n                                      x = y <-> x =' y.\n  Proof.\n    intros.\n    split.\n    intros.\n    inversion H.\n    eapply refl_equal'.\n\n    intros.\n    inversion H.\n    eapply refl_equal.\n  Qed.\n\n  Check eq_ind.\n  Check eq'_ind.\n\nEnd MyEquality.\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (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\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\nInductive total_relation : nat -> nat -> Prop :=\n  | tl : forall (n:nat) (m:nat), total_relation n m.\n\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n  | all_empty : all X P []\n  | all_xs    : forall (x:X) (xs:list X), P x /\\ all X P xs -> all X P (x :: xs).\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\nRequire Export Bool.\n\nTheorem forallb_from_all :\n  forall {X : Type} (test : X -> bool) (l : list X),\n    all X (fun x0 => Is_true (test x0)) l -> Is_true (forallb test l).\nProof.\n  intros X test.\n  induction l.\n\n  (* [] *)\n  intros.\n  simpl.\n  trivial.\n\n  (* x :: xs *)\n  intros.\n  inversion H.\n  inversion H1.\n  unfold forallb.\n  apply andb_prop_intro.\n  split.\n  apply H3.\n  apply IHl.\n  apply H4.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  induction 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  apply le_n.\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  intros n m.  generalize dependent n.  induction m.\n  intros.\n  inversion H.\n  apply le_n.\n  inversion H1.\n  intros.\n  destruct n.\n  apply le_S.\n  apply O_le_n.\n  inversion H.\n  apply n_le_m__Sn_le_Sm.\n  apply le_n.\n  subst.\n  assert (S n <= m).\n  apply IHm.\n  apply H1.\n  apply le_S.\n  apply H0.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intro a.\n  induction a.\n  simpl.\n  apply O_le_n.\n  intros.\n  simpl.\n  apply n_le_m__Sn_le_Sm.\n  apply IHa.\nQed.\n\nTheorem le_trans : forall n m l,\n  n <= m -> m <= l -> n <= l.\nProof.\n  induction 2; auto.\n  apply le_S.\n  apply IHle.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n intros.\n inversion H.\n split.\n unfold lt.\n apply n_le_m__Sn_le_Sm. apply le_plus_l.\n apply n_le_m__Sn_le_Sm. rewrite plus_comm. apply le_plus_l.\n split.\n unfold lt.\n apply n_le_m__Sn_le_Sm.\n assert (n1 <= S (n1 + n2)).\n apply le_S. apply le_plus_l.\n apply le_trans with (n:=n1) (m:=(S (n1 + n2))) (l:=m0).\n apply H2.\n apply H0.\n unfold lt.\n apply n_le_m__Sn_le_Sm.\n assert (n2 <= S (n1 + n2)).\n apply le_S. rewrite plus_comm. apply le_plus_l.\n apply le_trans with (n:=n2) (m:=(S (n1 + n2))) (l:=m0).\n apply H2.\n apply H0.\nQed.\n\n Theorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  intros.\n  unfold lt.\n  unfold lt in H.\n  apply le_S in H.\n  apply H.\nQed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  induction n.\n  simpl.\n  intros.\n  apply O_le_n.\n  intros.\n  simpl in H.\n  destruct m.\n  inversion H.\n  apply n_le_m__Sn_le_Sm.\n  apply IHn.\n  apply H.\nQed.\n\nTheorem ble_nat_n_Sn_false : forall n m,\n  ble_nat n (S m) = false ->\n  ble_nat n m = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* Hint: Do the right induction! *)\n  (* FILL IN HERE *) Admitted.\n\nInductive top_not_x : nat -> list nat -> Prop :=\n  | tn_empty : forall n:nat, top_not_x n []\n  | tn_top   : forall (n:nat) (m:nat) (l:list nat), n <> m -> top_not_x n (m :: l)\n.\nInductive nostutter:  list nat -> Prop :=\n  | ns_empty : nostutter []\n  | ns_xs    : forall (n:nat) (l:list nat), top_not_x n l /\\ nostutter l -> nostutter (n::l)\n.\nExample test_nostutter_1:      nostutter [3,1,4,1,5,6].\nProof.\n  repeat (constructor || split || constructor);\n  unfold not;\n  intros;\n  inversion H.\nQed.\n\nExample test_nostutter_2:  nostutter [].\n  repeat (constructor || split || constructor);\n  unfold not;\n  intros;\n  inversion H.\nQed.\n\nExample test_nostutter_3:  nostutter [5].\n  repeat (constructor || split || constructor);\n  unfold not;\n  intros;\n  inversion H.\nQed.\n\nExample test_nostutter_4:      not (nostutter [3,1,1,4]).\nProof.\n  unfold not.\n  intros.\n  inversion H.\n  inversion H1.\n  inversion H4.\n  inversion H6.\n  inversion H8.\n  subst.\n  apply H12.\n  reflexivity.\nQed.\n", "meta": {"author": "egejjespersen", "repo": "software_foundation_exercise", "sha": "e2f788ff88b4b6a6cefc3f413e646c8a733232b2", "save_path": "github-repos/coq/egejjespersen-software_foundation_exercise", "path": "github-repos/coq/egejjespersen-software_foundation_exercise/software_foundation_exercise-e2f788ff88b4b6a6cefc3f413e646c8a733232b2/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7486521225654081}}
{"text": "Module NatList.\nFrom LF Require Import Tst.\nFrom LF Require Import Tst.\n\nInductive natprod : Type :=\n  | pair (n1 n2 : nat).\n\nCheck (pair 3 5) : natprod.\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.\nCompute (fst (pair 3 5)).\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3,5)).\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.\n\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. \n  destruct p as [n m]. \n  simpl. \n  reflexivity. \nQed.\n\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\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\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\n(*\nNotation \"x + y\" := (plus x y)\n                      (at level 50, left associativity).\n\n1 + 2 :: [3]\n    50 < 60\n(1 + 2) :: [3]\n*)\n\n\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\nPrint mylist2.\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 length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\n\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.\n\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n  | nil => default\n  | cons x _ => x\n  end.\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | cons _ 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\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with \n  | nil => nil\n  | cons O t => nonzeros t\n  | cons n t => n :: (nonzeros t)\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\nFixpoint even (n : nat) : bool :=\n  match n with\n  | O => true\n  | S (S n') => even n'\n  | S n' => false\n  end. \n\nDefinition odd (n : nat) : bool := negb (even n).\n\nFixpoint oddmembers (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | cons i t => if odd i then i :: (oddmembers t) 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 := length (oddmembers l).\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. unfold countoddmembers. simpl. reflexivity. Qed. \n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. unfold countoddmembers. simpl. reflexivity. Qed. \n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. unfold countoddmembers. simpl. reflexivity. Qed. \n\n\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | l1, nil => l1\n  | nil, l2 => l2\n  | cons a1 t1, cons a2 t2 => a1 :: a2 :: alternate t1 t2\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\n\n\n\nDefinition bag := natlist.\n\nPrint nat.\n\nFixpoint eqn (a : nat) (b : nat) : bool :=\n  match a, b with\n  | O, O => true\n  | O, _ => false\n  | _, O => false\n  | S a', S b' => eqn a' b'\n  end.\n\nFixpoint count (v : nat) (s : bag) : nat :=\n  match s with\n  | nil => O\n  | cons h t => if (eqn h v) then S (count v t) else count v t\n  end.\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\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 := cons 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\nFixpoint member (v : nat) (s : bag) : bool :=\n  match s with\n  | nil => false\n  | cons h t => if eqn v h then true else member v t\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\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with\n  | nil => nil\n  | cons h t => if eqn 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. 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  | cons h t => if eqn 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.\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\n\nFixpoint subset (s1 : bag) (s2 : bag) : bool :=\n  match s1 with\n  | nil => true\n  | cons h t => if member h s2 then subset t (remove_one h s2) 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\nTheorem bag_theorem : forall (b : bag) (n: nat), \n  length (add n b) = S (length b).\nProof.\n  intros b n.\n  simpl.\n  reflexivity.\nQed.\n\n\n\n\n\n\n\nTheorem nil_app : forall l : natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\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\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. \n  induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. \n    rewrite -> IHl1'. \n    reflexivity. \nQed.\n\n\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\n\n\n\n\n\n\n\n\n\n\n\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.\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\n\n\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. \n  induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. \n    rewrite -> IHl1'. \n    reflexivity. \nQed.\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  - reflexivity.\n  - simpl.\n    rewrite -> app_length.\n    simpl.\n    rewrite <- IHl'.\n    rewrite add_comm.\n    simpl.\n    reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l.\n  induction l as [| h t H ].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> app_length.\n    simpl.\n    rewrite -> add_comm.\n    simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nSearch rev.\nSearch (_ + _ = _ + _).\nSearch (?x + ?y = ?y + ?x).\n\n\nLemma cons_tst : forall (l m : natlist) (v : nat), \n  (v :: l) ++ m = v :: (l ++ m).\nProof.\n  intros l m v.\n  induction l as [| h t H ].\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l.\n  induction l as [| h t H ].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> H.\n    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 [| h t H ].\n  - simpl.\n    rewrite -> app_nil_r.\n    reflexivity.\n  - simpl.\n    rewrite -> H.\n    rewrite -> app_assoc.\n    reflexivity.\nQed.\n\n\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l.\n  induction l as [| h t H ].\n  - reflexivity.\n  - simpl.\n    rewrite -> rev_app_distr.\n    rewrite -> H.\n    simpl.\n    reflexivity.\nQed.\n\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil => true\n  | cons h1 t1, cons h2 t2 => if eqn h1 h2 then eqblist t1 t2 else false\n  | _, _ => false\n  end.\n\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\nLemma eqn_refl: forall n : nat, eqn 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 eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  intros l.\n  induction l as [| h t H ].\n  - reflexivity.\n  - simpl.\n    rewrite -> eqn_refl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\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.\n\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.\n\nFixpoint ltb (n m : nat) : bool :=\n  match n, m with\n  | O, S_ => true\n  | S i, S j => ltb i j\n  | _, _ => false\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 <? y\" := (ltb x y) (at level 70) : nat_scope.\n\n\n\nLemma tst : forall (n : nat) (s : bag),\n  count n (n :: s) = S (count n s).\nProof.\n  intros n s.\n  simpl.\n  rewrite -> eqn_refl.\n  reflexivity.\nQed.\n\nLemma leb_n_Sn : forall (n : nat), (n <=? S n) = true.\nProof.\n  intros n.\n  simpl.\n  induction n as [| n' H].\n  - reflexivity.\n  - simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nLemma leb_1_Sn : forall (n : nat), (1 <=? S n) = true.\nProof.\n  intros n.\n  simpl.\n  destruct n as [| n'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  intros s.\n  rewrite -> tst.\n  rewrite -> leb_1_Sn .\n  reflexivity.\nQed.\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.\n  induction s as [| h t H ].\n  - simpl.\n    reflexivity.\n  - destruct h as [| h'].\n    * simpl.\n      rewrite -> leb_n_Sn.\n      reflexivity.\n    * simpl.\n      rewrite -> H.\n      reflexivity.\nQed.\n\nTheorem count_sum_distr: forall (n : nat) (s1 s2: bag),\n  count n (sum s1 s2) = count n s1 + count n s2.\nProof.\n  intros n s1 s2.\n  induction s1 as [| h t H ].\n  - reflexivity.\n  - simpl.\n    destruct (eqn h n) as [|].\n    * simpl.\n      rewrite -> H.\n      reflexivity.\n    * simpl.\n      rewrite -> H.\n      reflexivity.\nQed.\n\nSearch (?l = ?m -> rev ?l = rev ?m).\n\nLemma rev_injective_reverse: forall (l m : natlist), l = m -> rev l = rev m.\nProof.\n  intros l m H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nSearch (rev [] = []).\nSearch (rev (rev ?l) = ?l).\n\nLemma rev_nil: forall (l : natlist), rev l = [] -> l = [].\nProof.\n  intros l H.\n  assert (G: rev (rev l) = rev []). {\n    rewrite -> (rev_injective_reverse (rev l) [] H).\n    reflexivity.\n  }\n  rewrite <- test_rev2.\n  rewrite <- G.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n\n\nTheorem rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H.\n  assert (G : rev (rev l1) = l1). {\n    rewrite -> rev_involutive.\n    reflexivity.\n  }\n  rewrite <- G.\n  rewrite -> H.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n\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  | 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\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | [] => None\n  | h :: _ => Some h\n  end.\n\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\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 as [| h t].\n  - reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\nEnd NatList.\n\n\n\nModule PartialMap.\nExport NatList.\n\nInductive id : Type :=\n  | Id (n : nat).\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\nTheorem eqb_id_refl : forall x, eqb_id x x = true.\nProof.\n  intros x.\n  destruct x as [n].\n  simpl.\n  induction n as [| n' H ].\n  - reflexivity.\n  - simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\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\nTheorem update_eq : 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.\n  reflexivity.\nQed.\n\nTheorem update_neq : 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 H.\n  simpl.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nEnd PartialMap.\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/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.8807970654616711, "lm_q1q2_score": 0.7486521038566826}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Logic.\nFrom Coq Require Export 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: _inductive definitions_.\n\n    _Note_: For the sake of simplicity, most of this chapter uses an\n    inductive definition of \"evenness\" as a running example.  You may\n    find this confusing, since we already have a perfectly good way of\n    defining evenness as a proposition ([n] is even if it is equal to\n    the result of doubling some number); if so, rest assured that we\n    will see many more compelling examples of inductively defined\n    propositions toward the end of this chapter and in future\n    chapters. *)\n\nPrint double.\nPrint evenb.\n\n(** In past chapters, we have seen two ways of stating that a number\n    [n] is even: We can say\n\n      (1) [evenb n = true], or\n\n      (2) [exists k, n = double k].\n\n    Yet another possibility is to say that [n] is even if we can\n    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\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(** (Why call this a \"tree\", rather than a \"stack\", for example?\n    Because, in general, inference rules can have multiple premises.\n    We will see examples of this shortly.) *)\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 (n : nat) (H : ev n) : ev (S (S n)).\n\nCheck (ev_SS 0 ev_0).\n\n(** This definition is interestingly different from previous uses of\n    [Inductive].  For one thing, we are defining not a [Type] (like\n    [nat]) or a function yielding a [Type] (like [list]), but rather a\n    function from [nat] to [Prop] -- that is, a property of numbers.\n    But what is really new is that, because the [nat] argument of\n    [ev] appears to the _right_ of the colon on the first line, it\n    is allowed to take different values in the types of different\n    constructors: [0] in the type of [ev_0] and [S (S n)] in the type\n    of [ev_SS].  Accordingly, the type of each constructor must be\n    specified explicitly (after a colon), and each constructor's type\n    must have the form [ev n] for some natural number [n].\n\n    In contrast, recall the definition of [list]:\n\n    Inductive list (X:Type) : Type :=\n      | nil\n      | cons (x : X) (l : list X).\n\n   This definition introduces the [X] parameter _globally_, to the\n   _left_ of the colon, forcing the result of [nil] and [cons] to be\n   the same (i.e., [list X]).  Had we tried to bring [nat] to the left\n   of the colon in defining [ev], we would have seen an error: *)\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS (H: wrong_ev n) : wrong_ev (S (S n)).\n(* ===> Error: Last occurrence of \"[wrong_ev]\" must have \"[n]\"\n        as 1st argument in \"[wrong_ev 0]\". *)\n\n(** In an [Inductive] definition, an argument to the type constructor\n    on the left of the colon is called a \"parameter\", whereas an\n    argument on the right is called an \"index\" or \"annotation.\"\n\n    For example, in [Inductive list (X : Type) := ...], the [X] is a\n    parameter; in [Inductive ev : nat -> Prop := ...], the unnamed\n    [nat] argument is an index. *)\n\n(** We can think of the definition of [ev] as defining a Coq\n    property [ev : nat -> Prop], together with \"evidence constructors\"\n    [ev_0 : ev 0] and [ev_SS : forall n, ev n -> ev (S (S n))]. *)\n\n(** Such \"evidence constructors\" have the same status as proven\n    theorems.  In particular, we can use Coq's [apply] tactic with the\n    rule names to prove [ev] for particular numbers... *)\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: *)\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\nTheorem ev_4_my : ev 4.\nProof.\n  Check (ev 2) : Prop.\n  assert (ev 2).\n  apply (ev_SS 0 ev_0).\n  apply (ev_SS 2 H).\nQed.\n\n(** We can also prove theorems that have hypotheses 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(** **** Exercise: 1 star, standard (ev_double)  *)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  intros n.\n  induction n as [| n' IHn].\n  - simpl. apply ev_0.\n  - simpl.\n    Print ev_SS.\n    apply ev_SS. apply IHn.\nQed.\n(** [] *)\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 that [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.\n    Check E. Check (ev (S (S n'))).\n    Check (ev_SS n' E'). Check (ev (S (S n'))).\n    exists n'. split. reflexivity. apply E'.\nQed.\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 *)\n    Print Nat.pred.\n    simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\n(** However, this variation cannot easily be handled with just\n    [destruct]. *)\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  destruct E as [| n' E'] eqn:EE.\n  - (* E = ev_0. *)\n    (* We must prove that [n] is even from no assumptions! *)\nAbort.\n\n(** What happened, exactly?  Calling [destruct] has the effect of\n    replacing all occurrences of the property argument by the values\n    that correspond to each constructor.  This is enough in the case\n    of [ev_minus2] because that argument [n] is mentioned directly\n    in the final goal. However, it doesn't help in the case of\n    [evSS_ev] since the term that gets replaced ([S (S n)]) is not\n    mentioned anywhere. *)\n\n(** If we [remember] that term [S (S n)], the proof goes\n    through.  (We'll discuss [remember] in more detail below.) *)\n\nTheorem evSS_ev_remember : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. remember (S (S n)) as k eqn:Hk. destruct E as [|n' E'] eqn:EE.\n  - (* E = ev_0 *)\n    (* Now we do have an assumption, in which [k = S (S n)] has been\n       rewritten as [0 = S (S n)] by [destruct]. That assumption\n       gives us a contradiction. *)\n    discriminate Hk.\n  - (* E = ev_S n' E' *)\n    (* This time [k = S (S n)] has been rewritten as [S (S n') = S (S n)]. *)\n    injection Hk as Heq. rewrite <- Heq. apply E'.\nQed.\n\n(** Alternatively, the proof is straightforward using our inversion\n    lemma. *)\n\nTheorem evSS_ev : forall n, ev (S (S n)) -> ev n.\nProof.\n intros n H. apply ev_inversion in H.\n destruct H as [H0|H1].\n - discriminate H0.\n - destruct H1 as [n' [Hnm Hev]]. injection Hnm as Heq.\n   rewrite Heq. apply Hev.\nQed.\n\n(** Note how both proofs produce two subgoals, which correspond\n    to the two ways of proving [ev].  The first subgoal is a\n    contradiction that is discharged with [discriminate].  The second\n    subgoal makes use of [injection] and [rewrite].  Coq provides a\n    handy tactic called [inversion] that factors out that common\n    pattern.\n\n    The [inversion] tactic can detect (1) that the first case ([n =\n    0]) does not apply and (2) that the [n'] that appears in the\n    [ev_SS] case must be the same as [n].  It has an \"[as]\" variant\n    similar to [destruct], allowing us to assign names rather than\n    have Coq choose them. *)\n\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.\n\n(** The [inversion] tactic can apply the principle of explosion to\n    \"obviously contradictory\" hypotheses involving inductively defined\n    properties, something that takes a bit more work using our\n    inversion lemma. For example: *)\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. apply ev_inversion in H.\n  destruct H as [ | [m [Hm _]]].\n  - discriminate H.\n  - discriminate Hm.\nQed.\n\nTheorem one_not_even' : ~ ev 1.\n  intros H. inversion H. Qed.\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 H.\n  inversion H.\n  inversion H1.\n  apply H3.\nQed.\n(** [] *)\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 H.\n  inversion H.\n  inversion H1.\n  inversion H3.\nQed.\n(** [] *)\n\n(** The [inversion] tactic does quite a bit of work. For\n    example, when applied to an equality assumption, it does the work\n    of both [discriminate] and [injection]. In addition, it carries\n    out the [intros] and [rewrite]s that are typically necessary in\n    the case of [injection]. It can also be applied, more generally,\n    to analyze evidence for inductively defined propositions.  As\n    examples, we'll use it to reprove some theorems from chapter\n    [Tactics].  (Here we are being a bit lazy by omitting the [as]\n    clause from [inversion], thereby asking Coq to choose names for\n    the variables and hypotheses that it introduces.) *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\n(** Here's how [inversion] works in general.  Suppose the name\n    [H] refers to an assumption [P] in the current context, where [P]\n    has been defined by an [Inductive] declaration.  Then, for each of\n    the constructors of [P], [inversion H] generates a subgoal in which\n    [H] has been replaced by the exact, specific conditions under\n    which this constructor could have been used to prove [P].  Some of\n    these subgoals will be self-contradictory; [inversion] throws\n    these away.  The ones that are left represent the cases that must\n    be proved to establish the original goal.  For those, [inversion]\n    adds all equations into the proof context that must hold of the\n    arguments given to [P] (e.g., [S (S n') = n] in the proof of\n    [evSS_ev]). *)\n\n(** The [ev_double] exercise above shows that our new notion of\n    evenness is implied by the two earlier ones (since, by\n    [even_bool_prop] in chapter [Logic], we already know that\n    those are equivalent to each other). To show that all three\n    coincide, we just need the following lemma. *)\n\nLemma ev_even_firsttry : forall n,\n  ev n -> even n.\nProof.\n  (* WORKED IN CLASS *)\n\n(** We could try to proceed by case analysis or induction on [n].  But\n    since [ev] is mentioned in a premise, this strategy would\n    probably lead to a dead end, because (as we've noted before) the\n    induction hypothesis will talk about n-1 (which is _not_ even!).\n    Thus, it seems better to first try [inversion] on the evidence for\n    [ev].  Indeed, the first case can be solved trivially. And we can\n    seemingly make progress on the second case with a helper lemma. *)\n\n  intros n E. inversion E as [EQ' | n' E' EQ'].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E' *) simpl.\n\n(** Unfortunately, the second case is harder.  We need to show [exists\n    k, S (S n') = double k], but the only available assumption is\n    [E'], which states that [ev n'] holds.  Since this isn't\n    directly useful, it seems that we are stuck and that performing\n    case analysis on [E] was a waste of time.\n\n    If we look more closely at our second goal, however, we can see\n    that something interesting happened: By performing case analysis\n    on [E], we were able to reduce the original result to a similar\n    one that involves a _different_ piece of evidence for [ev]:\n    namely [E'].  More formally, we can finish our proof by showing\n    that\n\n        exists k', n' = double k',\n\n    which is the same as the original statement, but with [n'] instead\n    of [n].  Indeed, it is not difficult to convince Coq that this\n    intermediate result suffices. *)\n\n    (** Unforunately, now we are stuck. To make that apparent, let's move\n        [E'] back into the goal from the hypotheses. *)\n\n    generalize dependent E'.\n\n    (** Now it is clear we are trying to prove another instance of the\n        same theorem we set out to prove.  This instance is with [n'],\n        instead of [n], where [n'] is a smaller natural number than [n]. *)\nAbort.\n\n(* ================================================================= *)\n(** ** Induction on Evidence *)\n\n(** If this looks familiar, it is no coincidence: We've encountered\n    similar problems in the [Induction] chapter, when trying to\n    use case analysis to prove results that required induction.  And\n    once again the solution is... induction! *)\n\n(** The behavior of [induction] on evidence is the same as its\n    behavior on data: It causes Coq to generate one subgoal for each\n    constructor that could have used to build that evidence, while\n    providing an induction hypothesis for each recursive occurrence of\n    the property in question.\n\n    To prove a property of [n] holds for all numbers for which [ev\n    n] holds, we can use induction on [ev n]. This requires us to\n    prove two things, corresponding to the two ways in which [ev n]\n    could have been constructed. If it was constructed by [ev_0], then\n    [n=0], and the property must hold of [0]. If it was constructed by\n    [ev_SS], then the evidence of [ev n] is of the form [ev_SS n'\n    E'], where [n = S (S n')] and [E'] is evidence for [ev n']. In\n    this case, the inductive hypothesis says that the property we are\n    trying to prove holds for [n']. *)\n\n(** Let's try our current lemma again: *)\n\nLemma ev_even : forall n,\n  ev n -> even n.\nProof.\n  intros n E.\n  induction E as [| n' E' IH].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       with IH : even E' *)\n    unfold even in IH.\n    destruct IH as [k Hk].\n    rewrite Hk. exists (S k). simpl. reflexivity.\nQed.\n\n(** Here, we can see that Coq produced an [IH] that corresponds\n    to [E'], the single recursive occurrence of [ev] in its own\n    definition.  Since [E'] mentions [n'], the induction hypothesis\n    talks about [n'], as opposed to [n] or some other number. *)\n\n(** The equivalence between the second and third definitions of\n    evenness now follows. *)\n\nTheorem ev_even_iff : forall n,\n  ev n <-> even n.\nProof.\n  intros n. split.\n  - (* -> *) apply ev_even.\n  - (* <- *) unfold even. intros [k Hk]. rewrite Hk.\n    Check ev_double.\n    apply ev_double.\nQed.\n\n(** As we will see in later chapters, induction on evidence is a\n    recurring technique across many areas, and in particular when\n    formalizing the semantics of programming languages, where many\n    properties of interest are defined inductively. *)\n\n(** The following exercises provide simple examples of this\n    technique, to help you familiarize yourself with it. *)\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.\n  intros He.\n  generalize dependent m.\n  induction He as [| n' He' IHe].\n  - intros. apply H.\n  - intros. simpl.\n    Search \"evSS\".\n    Search ( ev ?a -> ev (S (S ?a))).\n    apply ev_SS.\n    apply IHe.\n    apply H.\nQed.\n(** [] *)\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 ev'_ev_left : forall n, ev' n -> ev n.\nProof.\n  intros n H.\n  induction H.\n  - apply ev_0.\n  - Print ev.\n    apply (ev_SS 0 ev_0).\n  - apply (ev_sum n m IHev'1 IHev'2).\nQed.\n\nLemma ev'_ev_right : forall n, ev n -> ev' n.\nProof.\n  intros.\n  induction H.\n  - apply ev'_0.\n  - apply (ev'_sum 2 n ev'_2 IHev).\nQed.\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  split.\n  - apply ev'_ev_left.\n  - apply ev'_ev_right.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, especially useful (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 Hsum H.\n  generalize dependent m.\n  induction H.\n  - intros. simpl in Hsum. apply Hsum.\n  - intros. simpl in Hsum.\n    apply IHev.\n    Search ( ev (S(S ?a)) -> ev ?a).\n    apply evSS_ev.\n    apply Hsum.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (ev_plus_plus) \n\n    This exercise can be completed without induction or case analysis.\n    But, you will need a clever assertion and some tedious rewriting.\n    Hint:  is [(n+m) + (n+p)] even? *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  intros.\n  Search (ev ?a -> ev ?b -> ev _).\n  assert (ev (n+m+(n+p))).\n  { apply (ev_sum (n+m) (n+p)). apply H. apply H0. }\n  Check plus_comm.\n  rewrite (plus_comm n p) in H1.\n  rewrite plus_assoc in H1.\n  rewrite plus_comm in H1.\n  rewrite plus_assoc in H1.\n  rewrite plus_assoc in H1.\n  Check plus_assoc.\n  rewrite <- (plus_assoc (n+n) m p) in H1.\n  apply (ev_ev__ev (n+n) (m+p)).\n  - apply H1.\n  - Check double_plus.\n    rewrite <- double_plus.\n    apply ev_double.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Inductive Relations *)\n\n(** A proposition parameterized by a number (such as [ev])\n    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 Playground.\n\n(** Just like properties, relations can be defined inductively.  One\n    useful example is the \"less than or equal to\" relation on\n    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 (n : nat)                : le n n\n  | le_S (n m : nat) (H : le n m) : le n (S m).\n\nNotation \"n <= m\" := (le n m).\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] above. 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) ->\n    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\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\nEnd Playground.\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. *)\n\n(* FILL IN HERE\n\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\n(* FILL IN HERE\n\n    [] *)\n\n(** From the definition of [le], we can sketch the behaviors of\n    [destruct], [inversion], and [induction] on a hypothesis [H]\n    providing evidence of the form [le e1 e2].  Doing [destruct H]\n    will generate two cases. In the first case, [e1 = e2], and it\n    will replace instances of [e2] with [e1] in the goal and context.\n    In the second case, [e2 = S n'] for some [n'] for which [le e1 n']\n    holds, and it will replace instances of [e2] with [S n'].\n    Doing [inversion H] will remove impossible cases and add generated\n    equalities to the context for further use. Doing [induction H]\n    will, in the second case, add the induction hypothesis that the\n    goal holds when [e2] is replaced with [n']. *)\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 H1 H2.\n  induction H2.\n  - assumption.\n  - apply le_S. apply IHle.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros n.\n  induction n.\n  - reflexivity.\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 H1.\n  induction H1.\n  - reflexivity.\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 H1.\n  inversion H1.\n  - apply le_n.\n  - apply (le_trans n (S n) m).\n    + apply le_S. apply le_n.\n    + apply H0.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b.\n  induction b.\n  - Search (_ + 0 = _).\n    rewrite PeanoNat.Nat.add_0_r.\n    apply le_n.\n  - rewrite plus_comm.\n    simpl.\n    rewrite plus_comm.\n    apply (le_trans a (a+b) (S (a+b) )).\n    + apply IHb.\n    + apply le_S. apply (le_n (a+b)).\nQed.\n\nLemma plus_le_one : forall n1 n2 m,\n    n1 + n2 <= m -> n1 <= m.\nProof.\n  intros n1 n2 m H.\n  induction H.\n  - apply le_plus_l.\n  - apply (le_trans n1 m (S m)).\n    + apply IHle.\n    + Search (_ <= S _).\n      apply le_S. apply le_n.\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  - apply (plus_le_one n1 n2 m). apply H.\n  - rewrite plus_comm in H. apply (plus_le_one n2 n1 m). apply H.\nQed.\n(** Hint: the next one may be easiest to prove by induction on [n]. *)\n\nTheorem add_le_cases : forall n m p q,\n    n + m <= p + q -> n <= p \\/ m <= q.\nProof.\n  (* TODO *)\n  intros.\n  Search \"le_gt_cases\".\n  destruct (PeanoNat.Nat.le_gt_cases n p) as [H1 | H1]. now left.\n  destruct (PeanoNat.Nat.le_gt_cases m q) as [H2 | H2]. now right.\n  contradict H.\n  rewrite PeanoNat.Nat.nle_gt.\n  Search \"add_lt_mono\".\n  now apply (PeanoNat.Nat.add_lt_mono).\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt.\n  intros.\n  Search \"le_tran\".\n  apply (le_trans (S n) m (S m)).\n  - apply H.\n  - apply le_S. apply le_n.\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  - (* try forward reasoning *)\n    rewrite plus_comm in H.\n    Search (S (_ +_ )= _).\n    rewrite plus_n_Sm in H.\n    Search (_ + _ <= _).\n    rewrite plus_comm in H.\n    apply plus_le_one in H.\n    apply H.\n  - (* try backward reasoning *)\n    apply (plus_le_one (S n2) n1 ).\n    rewrite plus_comm.\n    rewrite <- plus_n_Sm.\n    apply H.\nQed.\n\nTheorem leb_complete : forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  intros.\n  generalize dependent m.\n  induction n.\n  - intros. apply O_le_n.\n  - destruct m.\n    + intros. simpl in H. discriminate H.\n    + intros. simpl in H. apply IHn in H.\n      now apply n_le_m__Sn_le_Sm.\nQed.\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.\n  generalize dependent m.\n  induction n.\n  - intros. simpl. reflexivity.\n  - destruct m.\n    + intros. inversion H.\n    + intros. simpl.\n      apply IHn.\n      now apply Sn_le_Sm__n_le_m.\nQed.\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_complete in H.\n  apply leb_complete in H0.\n  apply leb_correct.\n  apply (le_trans n m o H H0 ).\nQed.\n(** **** Exercise: 2 stars, standard, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  split.\n  (* use leb_complete and leb_correct *)\n  apply leb_complete.\n  apply leb_correct.\nQed.\n(** [] *)\n\nModule R.\n\n(** **** Exercise: 3 stars, standard, especially useful (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      (* Answer : [R 1 1 2] is provable. [R 2 2 6] isn't *)\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      (* Answer : not change. *)\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      (* Answer : not change *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_R_provability : option (nat*string) := None.\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  plus.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n  intros.\n  split.\n  - (* ---> *)\n    unfold fR.\n    intros H.\n    induction H.\n    + reflexivity.\n    + simpl. now rewrite IHR.\n    + rewrite <- plus_n_Sm. now rewrite IHR.\n    + simpl in IHR. rewrite <- plus_n_Sm in IHR. now injection IHR as H1.\n    + now rewrite plus_comm.\n  - (* <--- *)\n    unfold fR.\n    generalize dependent o.\n    induction m.\n    + induction n.\n      * intros. simpl in H. rewrite <- H. apply c1.\n      * simpl in IHn.\n        intros. rewrite <- H. simpl.\n        apply c3.\n        apply IHn.\n        reflexivity.\n    + intros.\n      rewrite <- H. simpl. apply c2.\n      apply IHm. reflexivity.\nQed.\n(** [] *)\n\nEnd R.\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(* FILL IN HERE *)\n.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\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(** * Case Study: Regular Expressions *)\n\n(** The [ev] property provides a simple example for\n    illustrating inductive definitions and the basic techniques for\n    reasoning about them, but it is not terribly exciting -- after\n    all, it is equivalent to the two non-inductive definitions of\n    evenness that we had already seen, and does not seem to offer any\n    concrete benefit over them.\n\n    To give a better sense of the power of inductive definitions, we\n    now show how to use them to model a classic concept in computer\n    science: _regular expressions_. *)\n\n(** Regular expressions are a simple language for describing sets of\n    strings.  Their syntax is defined as follows: *)\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\n(** Note that this definition is _polymorphic_: Regular\n    expressions in [reg_exp T] describe strings with characters drawn\n    from [T] -- that is, lists of elements of [T].\n\n    (We depart slightly from standard practice in that we do not\n    require the type [T] to be finite.  This results in a somewhat\n    different theory of regular expressions, but the difference is not\n    significant for our purposes.) *)\n\n(** We connect regular expressions and strings via the following\n    rules, which define when a regular expression _matches_ some\n    string:\n\n      - The expression [EmptySet] does not match any string.\n\n      - The expression [EmptyStr] matches the empty string [[]].\n\n      - The expression [Char x] matches the one-character string [[x]].\n\n      - If [re1] matches [s1], and [re2] matches [s2],\n        then [App re1 re2] matches [s1 ++ s2].\n\n      - If at least one of [re1] and [re2] matches [s],\n        then [Union re1 re2] matches [s].\n\n      - Finally, if we can write some string [s] as the concatenation\n        of a sequence of strings [s = s_1 ++ ... ++ s_k], and the\n        expression [re] matches each one of the strings [s_i],\n        then [Star re] matches [s].\n\n        In particular, the sequence of strings may be empty, so\n        [Star re] always matches the empty string [[]] no matter what\n        [re] is. *)\n\n(** We can easily translate this informal definition into an\n    [Inductive] one as follows.  We use the notation [s =~ re] in\n    place of [exp_match s re]; by \"reserving\" the notation before\n    defining the [Inductive], we can use it in the definition! *)\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\nLemma quiz : forall T (s:list T), ~(s =~ EmptySet).\nProof. intros T s Hc. inversion Hc. Qed.\n(** Again, for readability, we display this definition using\n    inference-rule notation. *)\n\n(**\n\n                          ----------------                    (MEmpty)\n                           [] =~ EmptyStr\n\n                          ---------------                      (MChar)\n                           [x] =~ Char x\n\n                       s1 =~ re1    s2 =~ re2\n                      -------------------------                 (MApp)\n                       s1 ++ s2 =~ App re1 re2\n\n                              s1 =~ re1\n                        ---------------------                (MUnionL)\n                         s1 =~ Union re1 re2\n\n                              s2 =~ re2\n                        ---------------------                (MUnionR)\n                         s2 =~ Union re1 re2\n\n                          ---------------                     (MStar0)\n                           [] =~ Star re\n\n                      s1 =~ re    s2 =~ Star re\n                     ---------------------------            (MStarApp)\n                        s1 ++ s2 =~ Star re\n*)\n\n(** Notice that these rules are not _quite_ the same as the\n    informal ones that we gave at the beginning of the section.\n    First, we don't need to include a rule explicitly stating that no\n    string matches [EmptySet]; we just don't happen to include any\n    rule that would have the effect of some string matching\n    [EmptySet].  (Indeed, the syntax of inductive definitions doesn't\n    even _allow_ us to give such a \"negative rule.\")\n\n    Second, the informal rules for [Union] and [Star] correspond\n    to two constructors each: [MUnionL] / [MUnionR], and [MStar0] /\n    [MStarApp].  The result is logically equivalent to the original\n    rules but more convenient to use in Coq, since the recursive\n    occurrences of [exp_match] are given as direct arguments to the\n    constructors, making it easier to perform induction on evidence.\n    (The [exp_match_ex1] and [exp_match_ex2] exercises below ask you\n    to prove that the constructors given in the inductive declaration\n    and the ones that would arise from a more literal transcription of\n    the informal rules are indeed equivalent.)\n\n    Let's illustrate these rules with a few examples. *)\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1]).\n  - apply MChar.\n  - apply MChar.\nQed.\n\n(** (Notice how the last example applies [MApp] to the string\n    [[1]] directly.  Since the goal mentions [[1; 2]] instead of \n    [[1] ++ [2]], Coq wouldn't be able to figure out how to split \n    the string on its own.)\n\n    Using [inversion], we can also show that certain strings do _not_\n    match a regular expression: *)\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. inversion H.\nQed.\n\n(** We can define helper functions for writing down regular\n    expressions. The [reg_exp_of_list] function constructs a regular\n    expression that matches exactly the list that it receives as an\n    argument: *)\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.\nQed.\n\n(** We can also prove general facts about [exp_match].  For instance,\n    the following lemma shows that every string [s] that matches [re]\n    also matches [Star re]. *)\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.\n  - apply H.\n  - apply MStar0.\nQed.\n\n(** (Note the use of [app_nil_r] to change the goal of the theorem to\n    exactly the same shape expected by [MStarApp].) *)\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\n(** [] *)\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: *)\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Since the definition of [exp_match] has a recursive\n    structure, we might expect that proofs involving regular\n    expressions will often require induction on evidence. *)\n\n(** For example, suppose that we wanted to prove the following\n    intuitive result: If a regular expression [re] matches some string\n    [s], then all elements of [s] must occur as character literals\n    somewhere in [re].\n\n    To state this theorem, we first define a function [re_chars] that\n    lists all characters that occur in a regular expression: *)\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\n(** We can then phrase our theorem as follows: *)\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  (* WORKED IN CLASS *)\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    simpl. 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(** **** 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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** The [remember] Tactic *)\n\n(** One potentially confusing feature of the [induction] tactic is\n    that it will let you try to perform an induction over a term that\n    isn't sufficiently general.  The effect of this is to lose\n    information (much as [destruct] without an [eqn:] clause can do),\n    and leave you unable to complete the proof.  Here's an example: *)\n\nLemma star_app: 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\n(** Just doing an [inversion] on [H1] won't get us very far in\n    the recursive cases. (Try it!). So we need induction (on\n    evidence!). Here is a naive first attempt: *)\n\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\n(** But now, although we get seven cases (as we would expect from the\n    definition of [exp_match]), we have lost a very important bit of\n    information from [H1]: the fact that [s1] matched something of the\n    form [Star re].  This means that we have to give proofs for _all_\n    seven constructors of this definition, even though all but two of\n    them ([MStar0] and [MStarApp]) are contradictory.  We can still\n    get the proof to go through for a few constructors, such as\n    [MEmpty]... *)\n\n  - (* MEmpty *)\n    simpl. intros s2 H. apply H.\n\n(** ... but most cases get stuck.  For [MChar], for instance, we\n    must show that\n\n    s2 =~ Char x' -> x' :: s2 =~ Char x',\n\n    which is clearly impossible. *)\n\n  - (* MChar. *) intros s2 H. simpl. (* Stuck... *)\nAbort.\n\n(** The problem is that [induction] over a Prop hypothesis only works\n    properly with hypotheses that are completely general, i.e., ones\n    in which all the arguments are variables, as opposed to more\n    complex expressions, such as [Star re].\n\n    (In this respect, [induction] on evidence behaves more like\n    [destruct]-without-[eqn:] than like [inversion].)\n\n    An awkward way to solve this problem is \"manually generalizing\"\n    over the problematic expressions by adding explicit equality\n    hypotheses to the lemma: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp T),\n  re' = Star re ->\n  s1 =~ re' ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\n\n(** We can now proceed by performing induction over evidence directly,\n    because the argument to the first hypothesis is sufficiently\n    general, which means that we can discharge most cases by inverting\n    the [re' = Star re] equality in the context.\n\n    This idiom is so common that Coq provides a tactic to\n    automatically generate such equations for us, avoiding thus the\n    need for changing the statements of our theorems. *)\n\nAbort.\n\n(** The tactic [remember e as x] causes Coq to (1) replace all\n    occurrences of the expression [e] by the variable [x], and (2) add\n    an equation [x = e] to the context.  Here's how we can use it to\n    show the above result: *)\n\nLemma star_app: 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\n(** We now have [Heqre' : re' = Star re]. *)\n\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\n(** The [Heqre'] is contradictory in most cases, allowing us to\n    conclude immediately. *)\n\n  - (* MEmpty *)  discriminate.\n  - (* MChar *)   discriminate.\n  - (* MApp *)    discriminate.\n  - (* MUnionL *) discriminate.\n  - (* MUnionR *) discriminate.\n\n(** The interesting cases are those that correspond to [Star].  Note\n    that the induction hypothesis [IH2] on the [MStarApp] case\n    mentions an additional premise [Star re'' = Star re], which\n    results from the equality generated by [remember]. *)\n\n  - (* MStar0 *)\n    injection Heqre' as Heqre''. intros s H. apply H.\n\n  - (* MStarApp *)\n    injection Heqre' as Heqre''.\n    intros s2 H1. rewrite <- app_assoc.\n    apply MStarApp.\n    + apply Hmatch1.\n    + apply IH2.\n      * rewrite Heqre''. reflexivity.\n      * apply H1.\nQed.\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  (* FILL IN HERE *) Admitted.\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    pumping_constant re >= 1.\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 : pumping_constant re >= 1).\n  { apply pumping_constant_ge_1. }\n  inversion Hp1 as [Hp1'| p Hp1' Hp1''].\n  - rewrite H in Hp1'. discriminate Hp1'.\n  - rewrite H in Hp1''. discriminate Hp1''.\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(** 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 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  (* FILL IN HERE *) Admitted.\n(** [] *)\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 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  - (* MEmpty *)\n    simpl. intros contra. inversion contra.\n  (* FILL IN HERE *) Admitted.\n\nEnd Pumping.\n(** [] *)\n\n(* ################################################################# *)\n(** * Case Study: Improving Reflection *)\n\n(** We've seen in the [Logic] chapter that we often need to\n    relate boolean computations to statements in [Prop].  But\n    performing this conversion as we did it there can result in\n    tedious proof scripts.  Consider the proof of the following\n    theorem: *)\n\nTheorem filter_not_empty_In : forall n l,\n  filter (fun x => n =? x) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (n =? m) eqn:H.\n    + (* n =? m = true *)\n      intros _. rewrite eqb_eq in H. rewrite H.\n      left. reflexivity.\n    + (* n =? m = false *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** In the first branch after [destruct], we explicitly apply\n    the [eqb_eq] lemma to the equation generated by\n    destructing [n =? m], to convert the assumption [n =? m\n    = true] into the assumption [n = m]; then we had to [rewrite]\n    using this assumption to complete the case. *)\n\n(** We can streamline this by defining an inductive proposition that\n    yields a better case-analysis principle for [n =? m].\n    Instead of generating an equation such as [(n =? m) = true],\n    which is generally not directly useful, this principle gives us\n    right away the assumption we really need: [n = m]. *)\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT (H :   P) : reflect P true\n| ReflectF (H : ~ P) : reflect P false.\n\n(** The [reflect] property takes two arguments: a proposition\n    [P] and a boolean [b].  Intuitively, it states that the property\n    [P] is _reflected_ in (i.e., equivalent to) the boolean [b]: that\n    is, [P] holds if and only if [b = true].  To see this, notice\n    that, by definition, the only way we can produce evidence for\n    [reflect P true] is by showing [P] and then using the [ReflectT]\n    constructor.  If we invert this statement, this means that it\n    should be possible to extract evidence for [P] from a proof of\n    [reflect P true].  Similarly, the only way to show [reflect P\n    false] is by combining evidence for [~ P] with the [ReflectF]\n    constructor.\n\n    It is easy to formalize this intuition and show that the\n    statements [P <-> b = true] and [reflect P b] are indeed\n    equivalent.  First, the left-to-right implication: *)\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  (* WORKED IN CLASS *)\n  intros P b H. destruct b.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. intros H'. discriminate.\nQed.\n\n(** Now you prove the right-to-left implication: *)\n\n(** **** Exercise: 2 stars, standard, especially useful (reflect_iff)  *)\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The advantage of [reflect] over the normal \"if and only if\"\n    connective is that, by destructing a hypothesis or lemma of the\n    form [reflect P b], we can perform case analysis on [b] while at\n    the same time generating appropriate hypothesis in the two\n    branches ([P] in the first subgoal and [~ P] in the second). *)\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(** A smoother proof of [filter_not_empty_In] now goes as follows.\n    Notice how the calls to [destruct] and [rewrite] are combined into a\n    single call to [destruct]. *)\n\n(** (To see this clearly, look at the two proofs of\n    [filter_not_empty_In] with Coq and observe the differences in\n    proof state at the beginning of the first case of the\n    [destruct].) *)\n\nTheorem filter_not_empty_In' : forall n l,\n  filter (fun x => n =? x) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (eqbP n m) as [H | H].\n    + (* n = m *)\n      intros _. rewrite H. left. reflexivity.\n    + (* n <> m *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** **** Exercise: 3 stars, standard, especially useful (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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** This small example shows how reflection gives us a small gain in\n    convenience; in larger developments, using [reflect] consistently\n    can often lead to noticeably shorter and clearer proof scripts.\n    We'll see many more examples in later chapters and in _Programming\n    Language Foundations_.\n\n    The use of the [reflect] property has been popularized by\n    _SSReflect_, a Coq library that has been used to formalize\n    important results in mathematics, including as the 4-color theorem\n    and the Feit-Thompson theorem.  The name SSReflect stands for\n    _small-scale reflection_, i.e., the pervasive use of reflection to\n    simplify small proof steps with boolean computations. *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars, standard, especially useful (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 (* FILL IN HERE *)\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(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply eqb_neq; auto.\n  Qed.\n*)\n\nExample test_nostutter_2:  nostutter (@nil nat).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply eqb_neq; auto.\n  Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; 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; auto. Qed.\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_nostutter : option (nat*string) := None.\n(** [] *)\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(* Do not modify the following line: *)\nDefinition manual_grade_for_filter_challenge : option (nat*string) := None.\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    [] *)\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(* Do not modify the following line: *)\nDefinition manual_grade_for_pal_pal_app_rev_pal_rev : option (nat*string) := None.\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(* Do not modify the following line: *)\nDefinition manual_grade_for_NoDup_disjoint_etc : option (nat*string) := None.\n(** [] *)\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *)\n.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_check_repeats : option (nat*string) := None.\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  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ================================================================= *)\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: *)\nRequire Import Coq.Strings.Ascii.\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(* 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/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7485914139905387}}
{"text": "(** * Projeto de LC1 - 2022-1 (30 pontos)  *)\n\n(**\n  Projeto De Lógica Computacional 1. 2022/1\n  Integrantes:\n  \n  1] Andrey Calaca Resende 180062433\n  2]Gustavo Lopes Dezan 202033463\n  3]Felipe Dantas Borges 202021749\n  4]Eduardo Ferreira Marques Cavalcante 202006368\n  \n  Descrição: Projeto que formaliza a equivalência entre as diferentes noções de permutação denominadas perm e equiv\n  utilizado o coq.\n*)\n\nRequire Import PeanoNat List.\nOpen Scope nat_scope.\nRequire Import List Arith.\nRequire Import Permutation.\nOpen Scope nat_scope.\n\n(** perm_hd = perm_skip acredito *)\n(** perm_eq = perm_eq *)\n\n(* Noção de permutação utilziado no trabalho, Permutation não tem perm_eq *)\nInductive perm : list nat -> list nat -> Prop :=\n| perm_eq: forall l1, perm l1 l1\n| perm_swap: forall x y l1, perm (x :: y :: l1) (y :: x :: l1)\n| perm_hd: forall x l1 l2, perm l1 l2 -> perm (x :: l1) (x :: l2)\n| perm_trans: forall l1 l2 l3, perm l1 l2 -> perm l2 l3 -> perm l1 l3.\n\n(** (2 pontos) *)\n(** Mostrar que o Permutation do coq library possui equivalência com perm deste trabalho *)\nLemma perm_equiv_Permutation: forall l1 l2, perm l1 l2 <-> Permutation l1 l2.\nProof.\nsplit.\n  - intro H. induction H.\n    -- apply Permutation_refl.\n    -- apply Permutation.perm_swap.\n    -- apply Permutation.perm_skip.\n      --- apply IHperm.\n    -- apply Permutation.perm_trans with (l2).\n      --- apply IHperm1.\n      --- apply IHperm2.\n   - intro H. induction H.\n     -- apply perm_eq.\n     -- apply perm_hd.\n       --- apply IHPermutation.\n     -- apply perm_swap.\n     -- apply perm_trans with (l').\n       --- apply IHPermutation1.\n       --- apply IHPermutation2.\n\nQed.\n\n(* Fixpoint para definir número de ocorrencias de algum elemento em uma lista *)\nFixpoint num_oc (x: nat) (l: list nat): nat :=\n  match l with\n  | nil => 0\n  | h::tl => if (x =? h) then S (num_oc x tl) else num_oc x tl\nend.\n\n(* Definição de equiv *)\nDefinition equiv l l' := forall n:nat, num_oc n l = num_oc n l'.\n\nLemma perm_app_cons: forall l1 l2 a, perm (a :: l1 ++ l2) (l1 ++ a :: l2).\nProof.\n  induction l1.\n  - intros l2 a.\n    simpl.\n    apply perm_eq.\n  - intros l2 a2. (* porque o coq usa o 'a' como o numero natural?*)\n    simpl.\n    apply perm_trans with (a :: a2 :: l1 ++ l2).\n    + apply perm_swap.\n    + apply perm_hd.\n      apply IHl1.\nQed.\n\nLemma num_oc_S: forall x l1 l2, num_oc x (l1 ++ x :: l2) = S (num_oc x (l1 ++ l2)).\nProof.\n  induction l1.\n  - intro l2.\n    simpl.\n    rewrite Nat.eqb_refl; reflexivity.\n  - intro l2.\n    simpl.\n    destruct (x =? a); rewrite IHl1; reflexivity.\nQed.\n\nLemma num_occ_cons: forall l x n, num_oc x l = S n -> exists l1 l2, l = l1 ++ x :: l2 /\\ num_oc x (l1 ++ l2) = n.\nProof.\n  induction l.\n  -intros.\n    simpl in H.\n    inversion H.\n  -intros.\n    simpl in H.\n    destruct (x =? a) eqn: H1.\n    +specialize (IHl x n).\n      apply Nat.eqb_eq in H1.\n      rewrite H1.\n      exists nil.\n      exists l.\n      simpl.\n      rewrite H1 in H.\n      apply eq_add_S in H.\n      split.\n      *reflexivity.\n      *assumption.\n    +apply IHl in H.\n      destruct H.\n      destruct H.\n      destruct H.\n      rewrite H.\n      exists (a :: x0).\n      exists x1.\n      split.\n      *reflexivity.\n      *simpl.\n        rewrite H1.\n        assumption.\n      Qed.\n\nLemma num_oc_neq: forall n a l1 l2, n =? a = false -> num_oc n (l1 ++ a :: l2) = num_oc n (l1 ++ l2).\nProof.\n  induction l1.\n  - intros l2 H.\n    simpl.\n    rewrite H.\n    reflexivity.\n  - intros l2 Hfalse.\n    simpl.\n    destruct (n =? a0) eqn:H.\n    + apply (IHl1 l2) in Hfalse.\n      rewrite Hfalse; reflexivity.\n    + apply (IHl1 l2) in Hfalse.\n      assumption.\nQed.\n\n\nLemma equiv_nil: forall l, equiv nil l -> l = nil.\nProof.\n  intro l.\n  case l.\n  - intro H.\n    reflexivity.\n  - intros n l' H. unfold equiv in H.\n    specialize (H n). simpl in H.\n    rewrite Nat.eqb_refl in H.\n    inversion H.\nQed.\n\n\nLemma equiv_to_perm: forall l l', equiv l l' -> perm l l'.\nProof.\n  induction l.\n  - intros.\n    apply equiv_nil in H.\n    rewrite H.\n    apply perm_eq.\n       \n  - intros.\n    assert (H' := H).\n    unfold equiv in H'.\n    specialize (H' a).\n    simpl in H'.\n    rewrite Nat.eqb_refl in H'.\n    symmetry in H'.\n    apply num_occ_cons in H'.\n    destruct H'. \n    destruct H0.\n    destruct H0.\n    assert(H2:=IHl).\n    specialize (IHl (x++x0)).\n    rewrite H0.\n    apply (perm_trans (a :: l) (a :: x ++ x0) (x ++ a :: x0) ).\n    -- apply perm_hd.\n       apply IHl.\n       rewrite H0 in H.\n       intro.\n       unfold equiv in H.\n       specialize (H n).\n       inversion H.\n       destruct (n =? a) eqn: eq.\n       --- apply Nat.eqb_eq in eq.\n           rewrite eq in H4.\n           rewrite (num_oc_S a x x0) in H4 .\n           inversion H4.\n           rewrite eq.\n           auto.\n       --- replace (num_oc n (x ++ a :: x0)) with (num_oc n (x ++ x0)) in H4.\n           ---- auto.\n           ---- symmetry.\n                apply (num_oc_neq n a x x0 ).\n                auto.\n    -- apply perm_app_cons.\n    \nQed.\n\n(** (18 pontos) *)\n(* Prova do equiv <-> perm *)\nTheorem perm_equiv: forall l l', equiv l l' <-> perm l l'.\nProof.\n  intros l l'.\n  split.\n  - apply equiv_to_perm. (* equiv -> perm dificil de se provar sem lemas separados *)\n  \n  - intro H. induction H.\n    -- unfold equiv. \n       intro x. \n       reflexivity.\n    -- unfold equiv in *. intro n. simpl. destruct (n =? x) eqn: H. \n       + destruct (n =? y) eqn: H'.\n       --- reflexivity.\n       --- reflexivity.\n       + destruct (n =? y) eqn: H'.\n       --- reflexivity.\n       --- reflexivity.\n    -- unfold equiv in *.\n       intro n.\n       destruct (n=?x) eqn:H'.\n       --- simpl. rewrite H'. rewrite IHperm. reflexivity.\n       --- simpl. rewrite H'. rewrite IHperm. reflexivity.\n    -- unfold equiv in *.\n       intro n.\n       specialize (IHperm1 n).\n       rewrite IHperm1.\n       apply IHperm2.\n\nQed.\n", "meta": {"author": "EduardoFMC", "repo": "LC1_PermEquiv", "sha": "d4c5212f73a82506597d8fc368d788b66d08e27c", "save_path": "github-repos/coq/EduardoFMC-LC1_PermEquiv", "path": "github-repos/coq/EduardoFMC-LC1_PermEquiv/LC1_PermEquiv-d4c5212f73a82506597d8fc368d788b66d08e27c/PermEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.8633916064587, "lm_q1q2_score": 0.7485914034455368}}
{"text": "(* We start by defining natural numbers *)\nInductive nat :=\n  | zero : nat\n  | succ : nat -> nat.\n\n(* We define addition as relation on three natural numbers *)\nInductive add_to : nat -> nat -> nat -> Prop :=\n  | add_zero : forall n : nat, add_to n zero n (* n + 0 = n *)\n  | add_succ :\n    forall (p q r : nat)\n    (_ : add_to p q r), (* p + q = r *)\n    add_to p (succ q) (succ r). (* p + (q + 1) = r + 1 *)\n\n(* We need to prove that add_to is at least a partial function *)\nLemma add_to_det :\n  forall {p q r1 r2 : nat}, add_to p q r1 -> add_to p q r2 -> r1 = r2.\nProof.\n  intros p q.\n  induction q.\n  intros.\n  inversion H.\n  inversion H0.\n  rewrite <- H3.\n  rewrite <- H5.\n  reflexivity.\n  intros.\n  inversion H.\n  inversion H0.\n  remember (IHq r r0 H3 H7).\n  f_equal.\n  exact e.\nQed.\n\n(* Subtraction works in a similar way *)\nInductive sub_to : nat -> nat -> nat -> Prop :=\n  | sub_zero : forall n : nat, sub_to n zero n (* n - 0 = n*)\n  | sub_succ :\n    forall (p q r : nat)\n    (_ : sub_to p q (succ r)), (* p - q = (r + 1) *)\n    sub_to p (succ q) r. (* p - (q + 1) = r *)\n\n(* Subtraction is a partial function *)\nLemma sub_to_det :\n  forall {p q r1 r2 : nat}, sub_to p q r1 -> sub_to p q r2 -> r1 = r2.\nProof.\n  intros p q.\n  induction q.\n  intros.\n  inversion H.\n  inversion H0.\n  rewrite <-H3.\n  rewrite <-H5.\n  reflexivity.\n  intros.\n  inversion H.\n  inversion H0.\n  remember (IHq (succ r1) (succ r2) H3 H7).\n  inversion e.\n  reflexivity.\nQed.\n\n(* WHILE language also has multiplication, so we need to define that as well *)\nInductive mul_to : nat -> nat -> nat -> Prop :=\n  | mul_zero : forall n : nat, mul_to n zero zero (* n * 0 = n *)\n  | mul_succ :\n    forall (p q r s : nat)\n    (_ : mul_to p q r) (* p * q = r *)\n    (_ : add_to r p s), (* r + p = s *)\n    mul_to p (succ q) s. (* p * (q + 1) = s *)\n\n(* Multiplication is at least a partial function *)\nLemma mul_to_det :\n  forall {p q r1 r2 : nat}, mul_to p q r1 -> mul_to p q r2 -> r1 = r2.\nProof.\n  intros p q.\n  induction q.\n  intros.\n  inversion H.\n  inversion H0.\n  reflexivity.\n  intros.\n  inversion H.\n  inversion H0.\n  remember (IHq r r0 H2 H7).\n  rewrite e in H4.\n  remember (add_to_det H4 H9).\n  exact e0.\nQed.\n\n(* We will represent variable names as natural numbers for the sake of simplicity *)\nDefinition atom := nat.\n\n(* Moving on. AST node types for integer expressions (expr),\n   boolean expressions (bool), and commands (com) follow *)\n\n(* Binary operation on expressions *)\nInductive eop :=\n  | eop_add  (* + *)\n  | eop_sub  (* - *)\n  | eop_mul. (* * *)\n\n(* Expressions *)\nInductive expr :=\n  (* n *)\n  | e_nat : nat -> expr\n  (* x *)\n  | e_atom : atom -> expr\n  (* e eop e *)\n  | e_eop : expr -> eop -> expr -> expr.\n\n(* Binary operations on booleans *)\nInductive bop :=\n  | bop_eq  (* = *)\n  | bop_lt. (* < *)\n\n(* Booleans *)\nInductive bool :=\n  (* true *)\n  | b_true : bool\n  (* false *)\n  | b_false : bool\n  (* b bop b *)\n  | b_bop : expr -> bop -> expr -> bool\n  (* b && b *)\n  | b_and : bool -> bool -> bool\n  (* !b *)\n  | b_not : bool -> bool.\n\nInductive com :=\n  (* x := n *)\n  | c_set : atom -> expr -> com\n  (* if b then c else c *)\n  | c_if : bool -> com -> com -> com\n  (* c; c *)\n  | c_seq : com -> com -> com\n  (* skip *)\n  | c_skip : com\n  (* while b do c *)\n  | c_while : bool -> com -> com.\n\n(* State is a partial function from var to nat. We define\n   it as an inductive type with two constructors *)\nInductive state :=\n  (* Empty state with no variables defined *)\n  | s_empty : state\n  (* Updated state with a new definition for var *)\n  | s_update : state -> atom -> nat -> state.\n\n(* We now need to define relation equivalent to s(u) = n\n   There are two cases *)\nInductive atom_lookup : state -> atom -> nat -> Prop :=\n  (* Irrelevance: if s2 = s1[x2 -> n2], x1 != x2 and\n    s1(x1) = n1, then s2(x1) = n1 *)\n  | atom_lookup_irrelevant :\n    forall (s1 : state) (x1 x2 : atom) (n1 n2 : nat)\n    (_ : atom_lookup s1 x1 n1) (* s1(x1) = n1 *)\n    (_ : x1 <> x2), (* x1 != x2 *)\n    atom_lookup (s_update s1 x2 n2) x1 n1\n  (* Most recent definition: if s2 = s1[x -> n] then\n     s2(x) = n *)\n  | atom_lookup_most_recent :\n    forall (s1 : state) (x : atom) (n : nat),\n    atom_lookup (s_update s1 x n) x n.\n\n(* To verify the definition of atom_lookup, we show that it\n   is determenistic *)\nLemma atom_lookup_det :\n  forall {s : state} {x : atom} {n1 n2 : nat}\n  (_ : atom_lookup s x n1)\n  (_ : atom_lookup s x n2),\n  n1 = n2.\nProof.\n  intros.\n  induction s.\n  inversion H.\n  inversion H.\n  inversion H0.\n  exact (IHs H6 H13).\n  rewrite H8 in H7.\n  remember (H7 (eq_refl x)).\n  contradiction.\n  inversion H0.\n  rewrite H1 in H12.\n  remember (H12 (eq_refl x)).\n  contradiction.\n  rewrite <- H5.\n  rewrite <- H10.\n  reflexivity.\nQed.\n\n(* We can now define small step semantics for expressions *)\n(* We work with configurations - pairs of state and expressions *)\nInductive e_small : state -> expr -> state -> expr -> Prop :=\n  (* W-EXP.VAR rule *)\n  | e_small_var :\n    forall (s : state) (x : atom) (n : nat)\n    (_ : atom_lookup s x n), (* s(x) = n *)\n    e_small s (e_atom x) s (e_nat n) (* (s, x) -> (s, n) *)\n  (* W-EXP.LEFT rule *)\n  | e_small_left :\n    forall (s s' : state) (e1 e1' e2 : expr) (op : eop)\n    (_ : e_small s e1 s' e1'), (* (s, e1) -> (s', e1') *)\n    (* (s, e1 @ e2) -> (s', e1' @ e2) *)\n    e_small s (e_eop e1 op e2) s' (e_eop e1' op e2)\n  (* W-EXP.RIGHT rule *)\n  | e_small_right :\n    forall (s s' : state) (e e' : expr) (op : eop) (n : nat)\n    (_ : e_small s e s' e'), (* (s, e) -> (s', e') *)\n    (* (s, n @ e) -> (s', n @ e') *)\n    e_small s (e_eop (e_nat n) op e) s' (e_eop (e_nat n) op e')\n  (* W-EXP.ADD rule *)\n  | e_small_add :\n    forall (s : state) (n1 n2 n3 : nat)\n    (_ : add_to n1 n2 n3), (* n1 + n2 = n3 *)\n    (* (s, n1 + n2) -> (s, n3) *)\n    e_small s (e_eop (e_nat n1) eop_add (e_nat n2)) s (e_nat n3)\n  (* W-EXP.SUB rule *)\n  | e_small_sub :\n    forall (s : state) (n1 n2 n3 : nat)\n    (_ : sub_to n1 n2 n3), (* n1 - n2 = n3 *)\n    (* (s, n1 - n2) -> (s, n3) *)\n    e_small s (e_eop (e_nat n1) eop_sub (e_nat n2)) s (e_nat n3)\n  (* W-EXP.MUL rule *)\n  | e_small_mul :\n    forall (s : state) (n1 n2 n3 : nat)\n    (_ : mul_to n1 n2 n3), (* n1 * n2 = n3 *)\n    (* (s, n1 * n2) -> (s, n3) *)\n    e_small s (e_eop (e_nat n1) eop_mul (e_nat n2)) s (e_nat n3).\n\n(* We now show that small step relation we defined earlier is determentistic *)\n(* We split the theorem into two lemmas: one about the rewritten expression\n   one about new state *)\n\n(* Expression produced by small step reduction of atom will always be the same *)\nLemma e_small_det_e_atom :\n  forall {e1 e2 : expr} {s s1 s2 : state} {x : atom}\n  (_: e_small s (e_atom x) s1 e1) (* (s, x) -> (s1, e1) *)\n  (_: e_small s (e_atom x) s2 e2), (* (s, x) -> (s2, e2) *)\n  e1 = e2.\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  rewrite <-H4 in H3.\n  rewrite <-H9 in H8.\n  f_equal.\n  exact (atom_lookup_det H3 H8).\nQed.\n\n(* Reduction of atom does not change state *)\nLemma e_small_pure_atom :\n  forall {s s' : state} {e' : expr} {x : atom}\n  (_ : e_small s (e_atom x) s' e'),\n  s = s'.\nProof.\n  intros.\n  inversion H.\n  reflexivity.\nQed.\n\n(* Small step relation is determenistic for atoms *)\nLemma e_small_det_atom :\n  forall {e1 e2 : expr} {s s1 s2 : state} {x : atom}\n  (_: e_small s (e_atom x) s1 e1) (* (s, x) -> (s1, e1) *)\n  (_: e_small s (e_atom x) s2 e2), (* (s, x) -> (s2, e2) *)\n  e1 = e2 /\\ s1 = s2.\nProof.\n  intros.\n  split.\n  exact (e_small_det_e_atom H H0).\n  remember (e_small_pure_atom H).\n  remember (e_small_pure_atom H0).\n  rewrite <-e.\n  rewrite <-e0.\n  reflexivity.\nQed.\n\n(* If operands are known, small step relation always reduces\n   binary operation to the same result *)\n(* TODO: avoid repetitions here *)\nLemma e_small_det_e_bin_nat :\n  forall {e1 e2 : expr} {s s1 s2 : state} {n1 n2 : nat} {op : eop}\n  (_: e_small s (e_eop (e_nat n1) op (e_nat n2)) s1 e1)\n  (_: e_small s (e_eop (e_nat n1) op (e_nat n2)) s2 e2),\n  e1 = e2.\nProof.\n  intros.\n  destruct op.\n  inversion H.\n  inversion H7.\n  inversion H7.\n  inversion H0.\n  inversion H13.\n  inversion H13.\n  f_equal.\n  exact (add_to_det H6 H12).\n  intros.\n  inversion H.\n  inversion H7.\n  inversion H7.\n  inversion H0.\n  inversion H13.\n  inversion H13.\n  f_equal.\n  exact (sub_to_det H6 H12).\n  intros.\n  inversion H.\n  inversion H7.\n  inversion H7.\n  inversion H0.\n  inversion H13.\n  inversion H13.\n  f_equal.\n  exact (mul_to_det H6 H12).\nQed.\n\n(* Binary operations on natural numbers do not modify state *)\nLemma e_small_pure_bin_nat :\n  forall {s s' : state} {e' : expr} {n1 n2 : nat} {op : eop}\n  (_ : e_small s (e_eop (e_nat n1) op (e_nat n2)) s' e'),\n  s = s'.\nProof.\n  intros.\n  inversion H.\n  inversion H6.\n  inversion H6.\n  reflexivity.\n  reflexivity.\n  reflexivity.\nQed.\n\n(* Small step relation is deterministic for binary operations on known\n   numbers *)\nLemma e_small_det_bin :\n  forall {e1 e2 : expr} {s s1 s2 : state} {n1 n2 : nat} {op : eop}\n  (_: e_small s (e_eop (e_nat n1) op (e_nat n2)) s1 e1)\n  (_: e_small s (e_eop (e_nat n1) op (e_nat n2)) s2 e2),\n  e1 = e2 /\\ s1 = s2.\nProof.\n  intros.\n  split.\n  exact (e_small_det_e_bin_nat H H0).\n  remember (e_small_pure_bin_nat H).\n  remember (e_small_pure_bin_nat H0).\n  rewrite <-e.\n  rewrite <-e0.\n  reflexivity.\nQed.\n\n(* We now prove similar properties for x @ e (binary operator\n   applied to a variable) *)\n\n(* x @ e always reduces to the same expression *)\nLemma e_small_det_e_bin_atom :\n  forall {e e1 e2 : expr} {s s1 s2 : state} {x : atom} {op : eop}\n  (_ : e_small s (e_eop (e_atom x) op e) s1 e1)\n  (_ : e_small s (e_eop (e_atom x) op e) s2 e2),\n  e1 = e2.\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  f_equal.\n  exact (e_small_det_e_atom H7 H14).\nQed.\n\n(* x @ e does not modify state *)\nLemma e_small_pure_bin_atom :\n  forall {e e' : expr} {s s' : state} {x : atom} {op : eop}\n  (_ : e_small s (e_eop (e_atom x) op e) s' e'),\n  s = s'.\nProof.\n  intros.\n  inversion H.\n  exact (e_small_pure_atom H6).\nQed.\n\n(* Small step relation is determenistic for x @ e *)\nLemma e_small_det_bin_atom :\n  forall {e e1 e2 : expr} {s s1 s2 : state} {x : atom} {op : eop}\n  (_ : e_small s (e_eop (e_atom x) op e) s1 e1)\n  (_ : e_small s (e_eop (e_atom x) op e) s2 e2),\n  e1 = e2 /\\ s1 = s2.\nProof.\n  intros.\n  split.\n  exact (e_small_det_e_bin_atom H H0).\n  remember (e_small_pure_bin_atom H).\n  remember (e_small_pure_bin_atom H0).\n  rewrite <-e0.\n  rewrite <-e3.\n  reflexivity.\nQed.\n\n(* Small step relation also produces the same expression *)\nLemma e_small_det_e :\n  forall {e e1 e2 : expr} {s s1 s2 : state}\n  (_ : e_small s e s1 e1)  (* (s, e) -> (s1, e1) *)\n  (_ : e_small s e s2 e2), (* (s, e) -> (s2, e2) *)\n  e1 = e2.\nProof.\n  intros.\n  generalize dependent s1.\n  generalize dependent s2.\n  generalize dependent e1.\n  generalize dependent e2.\n  induction e.\n  intros.\n  inversion H0.\n  intros.\n  exact (e_small_det_e_atom H H0).\n  intros.\n  destruct e1.\n  inversion H0.\n  inversion H7.\n  inversion H.\n  inversion H14.\n  f_equal.\n  exact (IHe2 _ _ _ H7 _ H14).\n  rewrite <-H12 in H7.\n  inversion H7.\n  rewrite <-H12 in H7.\n  inversion H7.\n  rewrite <-H12 in H7.\n  inversion H7.\n  rewrite <-H5 in H0.\n  rewrite <-H5 in H.\n  rewrite H6.\n  exact (e_small_det_e_bin_nat H H0).\n  rewrite <-H5 in H0.\n  rewrite <-H5 in H.\n  rewrite H6.\n  exact (e_small_det_e_bin_nat H H0).\n  rewrite <-H5 in H0.\n  rewrite <-H5 in H.\n  rewrite H6.\n  exact (e_small_det_e_bin_nat H H0).\n  exact (e_small_det_e_bin_atom H H0).\n  inversion H0.\n  inversion H.\n  f_equal.\n  exact (IHe1 _ _ _ H7 _ H14).\nQed.\n\n(* Small step relation does not modify expression state *)\nLemma e_small_pure :\n  forall {e e' : expr} {s s' : state}\n  (_ : e_small s e s' e'),\n  s = s'.\nProof.\n  intros.\n  generalize dependent s.\n  generalize dependent s'.\n  generalize dependent e'.\n  induction e.\n  intros.\n  inversion H.\n  intros.\n  exact (e_small_pure_atom H).\n  intros.\n  inversion H.\n  exact (IHe1 _ _ _ H6).\n  exact (IHe2 _ _ _ H6).\n  reflexivity.\n  reflexivity.\n  reflexivity.\nQed.\n\n(* We can now show that small step relation is determinstic *)\nTheorem e_small_det :\n  forall {e e1 e2 : expr} {s s1 s2 : state}\n  (_ : e_small s e s1 e1)  (* (s, e) -> (s1, e1) *)\n  (_ : e_small s e s2 e2), (* (s, e) -> (s2, e2) *)\n  e1 = e2 /\\ s1 = s2.\nProof.\n  split.\n  exact (e_small_det_e H H0).\n  remember (e_small_pure H).\n  remember (e_small_pure H0).\n  rewrite <-e0.\n  rewrite <-e3.\n  reflexivity.\nQed.\n", "meta": {"author": "RiscInside", "repo": "while", "sha": "e3525c266e11a41d84aa877e7021934044c97658", "save_path": "github-repos/coq/RiscInside-while", "path": "github-repos/coq/RiscInside-while/while-e3525c266e11a41d84aa877e7021934044c97658/While.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7485469903335166}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\nRequire Import BinInt BinNat Ring_theory.\n\nLocal Open Scope Z_scope.\n\n(** [Zpower_pos z n] is the n-th power of [z] when [n] is an binary\n      integer (type [positive]) and [z] a signed integer (type [Z]) *)\n\nDefinition Zpower_pos (z:Z) (n:positive) :=\n iter_pos n Z (fun x:Z => z * x) 1.\n\nDefinition Zpower (x y:Z) :=\n    match y with\n      | Zpos p => Zpower_pos x p\n      | Z0 => 1\n      | Zneg p => 0\n    end.\n\nInfix \"^\" := Zpower : Z_scope.\n\nLemma Zpower_0_r : forall n, n^0 = 1.\nProof. reflexivity. Qed.\n\nLemma Zpower_succ_r : forall a b, 0<=b -> a^(Zsucc b) = a * a^b.\nProof.\n intros a [|b|b] Hb; [ | |now elim Hb]; simpl.\n reflexivity.\n unfold Zpower_pos. now rewrite Pplus_comm, iter_pos_plus.\nQed.\n\nLemma Zpower_neg_r : forall a b, b<0 -> a^b = 0.\nProof.\n now destruct b.\nQed.\n\nLemma Zpower_theory : power_theory 1 Zmult (eq (A:=Z)) Z_of_N Zpower.\nProof.\n constructor. intros.\n destruct n;simpl;trivial.\n unfold Zpower_pos.\n rewrite <- (Zmult_1_r (pow_pos _ _ _)). generalize 1.\n induction p; simpl; intros; rewrite ?IHp, ?Zmult_assoc; trivial.\nQed.\n\nLemma Zpower_Ppow : forall p q, (Zpos p)^(Zpos q) = Zpos (p^q).\nProof.\n intros. unfold Ppow, Zpower, Zpower_pos.\n symmetry. now apply iter_pos_swap_gen.\nQed.\n\nLemma Zpower_Npow : forall n m,\n (Z_of_N n)^(Z_of_N m) = Z_of_N (n^m).\nProof.\n intros [|n] [|m]; simpl; trivial.\n unfold Zpower_pos. generalize 1. induction m; simpl; trivial.\n apply Zpower_Ppow.\nQed.\n\n(** An alternative Zpower *)\n\n(** This Zpower_alt is extensionnaly equal to Zpower in ZArith,\n    but not convertible with it. The number of\n    multiplications is logarithmic instead of linear, but\n    these multiplications are bigger. Experimentally, it seems\n    that Zpower_alt is slightly quicker than Zpower on average,\n    but can be quite slower on powers of 2.\n*)\n\nDefinition Zpower_alt n m :=\n  match m with\n    | Z0 => 1\n    | Zpos p => Piter_op Zmult p n\n    | Zneg p => 0\n  end.\n\nInfix \"^^\" := Zpower_alt (at level 30, right associativity) : Z_scope.\n\nLemma iter_pos_mult_acc : forall f,\n (forall x y:Z, (f x)*y = f (x*y)) ->\n forall p k, iter_pos p _ f k = (iter_pos p _ f 1)*k.\nProof.\n intros f Hf.\n induction p; simpl; intros.\n rewrite IHp. rewrite Hf. f_equal. rewrite (IHp (iter_pos _ _ _ _)).\n rewrite <- Zmult_assoc. f_equal. auto.\n rewrite IHp. rewrite (IHp (iter_pos _ _ _ _)).\n rewrite <- Zmult_assoc. f_equal. auto.\n rewrite Hf. f_equal. now rewrite Zmult_1_l.\nQed.\n\nLemma Piter_op_square : forall p a,\n Piter_op Zmult p (a*a) = (Piter_op Zmult p a)*(Piter_op Zmult p a).\nProof.\n induction p; simpl; intros; trivial.\n rewrite IHp. rewrite <- !Zmult_assoc. f_equal.\n rewrite Zmult_comm, <- Zmult_assoc.\n f_equal. apply Zmult_comm.\nQed.\n\nLemma Zpower_equiv : forall a b, a^^b = a^b.\nProof.\n intros a [|p|p]; trivial.\n unfold Zpower_alt, Zpower, Zpower_pos.\n revert a.\n induction p; simpl; intros.\n f_equal.\n rewrite iter_pos_mult_acc.\n now rewrite Piter_op_square, IHp.\n intros. symmetry; apply Zmult_assoc.\n rewrite iter_pos_mult_acc.\n now rewrite Piter_op_square, IHp.\n intros. symmetry; apply Zmult_assoc.\n now rewrite Zmult_1_r.\nQed.\n\nLemma Zpower_alt_0_r : forall n, n^^0 = 1.\nProof. reflexivity. Qed.\n\nLemma Zpower_alt_succ_r : forall a b, 0<=b -> a^^(Zsucc b) = a * a^^b.\nProof.\n intros a [|b|b] Hb; [ | |now elim Hb]; simpl.\n now rewrite Zmult_1_r.\n rewrite <- Pplus_one_succ_r. apply Piter_op_succ. apply Zmult_assoc.\nQed.\n\nLemma Zpower_alt_neg_r : forall a b, b<0 -> a^^b = 0.\nProof.\n now destruct b.\nQed.\n\nLemma Zpower_alt_Ppow : forall p q, (Zpos p)^^(Zpos q) = Zpos (p^q).\nProof.\n intros. now rewrite Zpower_equiv, Zpower_Ppow.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/ZArith/Zpow_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7485274697391631}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus Zero (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj264_coqofml_oMZhMm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7484798373475943}}
{"text": "(** A library of operators over relations,\n    to define transition sequences and their properties. *)\n\nSet Implicit Arguments.\n\nSection SEQUENCES.\n\nVariable A: Type.                 (**r the type of states *)\nVariable R: A -> A -> Prop.       (**r the transition relation between states *)\n\n(** ** Finite sequences of transitions *)\n\n(** Zero, one or several transitions: reflexive transitive closure of [R]. *)\n\nInductive star: A -> A -> Prop :=\n  | star_refl: forall a,\n      star a a\n  | star_step: forall a b c,\n      R a b -> star b c -> star a c.\n\nLemma star_one:\n  forall (a b: A), R a b -> star a b.\nProof.\n  eauto using star.\nQed.\n\nLemma star_trans:\n  forall (a b: A), star a b -> forall c, star b c -> star a c.\nProof.\n  induction 1; eauto using star. \nQed.\n\n(** One or several transitions: transitive closure of [R]. *)\n\nInductive plus: A -> A -> Prop :=\n  | plus_left: forall a b c,\n      R a b -> star b c -> plus a c.\n\nLemma plus_one:\n  forall a b, R a b -> plus a b.\nProof.\n  eauto using star, plus. \nQed.\n\nLemma plus_star:\n  forall a b,\n  plus a b -> star a b.\nProof.\n  intros. inversion H. eauto using star.  \nQed.\n\nLemma plus_star_trans:\n  forall a b c, plus a b -> star b c -> plus a c.\nProof.\n  intros. inversion H. eauto using plus, star_trans.\nQed.\n\nLemma star_plus_trans:\n  forall a b c, star a b -> plus b c -> plus a c.\nProof.\n  intros. inversion H0. inversion H; eauto using plus, star, star_trans.\nQed.\n\nLemma plus_right:\n  forall a b c, star a b -> R b c -> plus a c.\nProof.\n  eauto using star_plus_trans, plus_one.\nQed.\n\n(** Absence of transitions from a state. *)\n\nDefinition irred (a: A) : Prop := forall b, ~(R a b).\n\n(** ** Infinite transition sequences *)\n\n(** It is easy to characterize the fact that all transition sequences starting\n  from a state [a] are infinite: it suffices to say that any finite sequence\n  starting from [a] can always be extended by one more transition. *)\n\nDefinition all_seq_inf (a: A) : Prop :=\n  forall b, star a b -> exists c, R b c.\n\n(** However, this is not the notion we are trying to characterize: the case\n  where there exists an infinite sequence of transitions starting from [a],\n  [a --> a1 --> a2 --> ... -> aN -> ...]\n  leaving open the possibility that there exists finite sequences\n  starting from [a].\n\n  Example: consider [A = nat] and [R] such that [R 0 0] and [R 0 1].  \n  [all_seq_inf 0] does not hold, because a sequence [0 -->* 1] cannot\n  be extended.  Yet, [R] admits an infinite sequence, namely\n  [0 --> 0 --> ...].\n\n  Another attempt would be to represent the sequence of states \n  [a0 --> a1 --> a2 --> ... -> aN -> ...] explicitly, as a function \n  [f: nat -> A] such that [f i] is the [i]-th state [ai] of the sequence. *)\n\nDefinition infseq_with_function (a: A) : Prop :=\n  exists f: nat -> A, f 0 = a /\\ forall i, R (f i) (f (1 + i)).\n\n(** This is a correct characterization of the existence of an infinite\n  sequence of reductions.  However, it is inconvenient to work with\n  this definition in Coq's constructive logic: in most use cases, the\n  function [f] is not computable and therefore cannot be defined in Coq.\n\n  However, we do not really need the function [f]: its codomain [X] is\n  all we need!  What matters is the existence of a set [X] such as\n  [a] is in [X], and\n  every [b] in [X] can make a transition to an element of [X].\n  This suffices to prove the existence of an infinite sequence of transitions\n  starting from [a].\n*)\n\nDefinition infseq (a: A) : Prop :=\n  exists X: A -> Prop,\n  X a /\\ (forall a1, X a1 -> exists a2, R a1 a2 /\\ X a2).\n\n(** This definition is essentially a coinduction principle.\n  Let us show some expected properties.  For instance: if relation [R]\n  contains a cycle, an infinite sequence exists. *)\n\nRemark cycle_infseq:\n  forall a, R a a -> infseq a.\nProof.\n  intros. exists (fun b => b = a); split.\n  auto.\n  intros. subst a1. exists a; auto.\nQed.\n\n(** Mon generally: if all sequences from [a] are infinite, there exists one\n  infinite sequence starting in [a]. *)\n\nLemma infseq_if_all_seq_inf:\n  forall a, all_seq_inf a -> infseq a.\nProof.\n  intros a0 ALL0. \n  exists all_seq_inf; split; auto.\n  intros a1 ALL1. destruct (ALL1 a1) as [a2 R12]. constructor. \n  exists a2; split; auto.\n  intros a3 S23. destruct (ALL1 a3) as [a4 R23]. apply star_step with a2; auto.\n  exists a4; auto.\nQed.\n\n(** Likewise, the characterization [infseq_with_function] based on functions\n  implies [infseq]. *)\n\nLemma infseq_from_function:\n  forall a, infseq_with_function a -> infseq a.\nProof.\n  intros a0 (f & F0 & Fn). exists (fun a => exists i, f i = a); split.\n- exists 0; auto.\n- intros a1 (i1 & F1). subst a1. exists (f (1 + i1)); split; auto. exists (1 + i1); auto.\nQed.  \n\n(** An \"inversion lemma\" for [infseq]: if [infseq a], i.e. there exists\n  an infinite sequence starting in [a], then [a] can transition to a state [b]\n  that satisfies [infseq b]. *)\n\nLemma infseq_inv:\n  forall a, infseq a -> exists b, R a b /\\ infseq b.\nProof.\n  intros a (X & Xa & XP). destruct (XP a Xa) as (b & Rab & Xb). \n  exists b; split; auto. exists X; auto.\nQed.\n\n(** A very useful coinduction principle considers a set [X] where for\n  every [a] in [X], we can make one *or several* transitions to reach\n  a state [b] that belongs to [X].  *)\n\nLemma infseq_coinduction_principle:\n  forall (X: A -> Prop),\n  (forall a, X a -> exists b, plus a b /\\ X b) ->\n  forall a, X a -> infseq a.\nProof.\n  intros X H a0 Xa0. \n  exists (fun a => exists b, star a b /\\ X b); split.\n- exists a0; auto using star_refl.\n- intros a1 (a2 & S12 & X2). inversion S12; subst.\n  + destruct (H a2 X2) as (a3 & P23 & X3). inversion P23; subst.\n    exists b; split; auto. exists a3; auto.\n  + exists b; split; auto. exists a2; auto.\nQed.\n\n(** ** Determinism properties for functional transition relations. *)\n\n(** A transition relation is functional if every state can transition\n  to at most one other state. *)\n\nHypothesis R_functional:\n  forall a b c, R a b -> R a c -> b = c.\n\n(** Uniqueness of finite transition sequences. *)\n\nLemma star_star_inv:\n  forall a b, star a b -> forall c, star a c -> star b c \\/ star c b.\nProof.\n  induction 1; intros.\n- auto.\n- inversion H1; subst.\n+ right. eauto using star. \n+ assert (b = b0) by (eapply R_functional; eauto). subst b0. \n  apply IHstar; auto.\nQed.\n\nLemma finseq_unique:\n  forall a b b',\n  star a b -> irred b ->\n  star a b' -> irred b' ->\n  b = b'.\nProof.\n  intros. destruct (star_star_inv H H1).\n- inversion H3; subst. auto. elim (H0 _ H4).\n- inversion H3; subst. auto. elim (H2 _ H4).\nQed.\n\n(** A state cannot both diverge and terminate on an irreducible state. *)\n\nLemma infseq_inv':\n  forall a b, R a b -> infseq a -> infseq b.\nProof.\n  intros a b Rab Ia. \n  destruct (infseq_inv Ia) as (b' & Rab' & Xb').\n  assert (b' = b) by (eapply R_functional; eauto). \n  subst b'. auto.\nQed.\n\nLemma infseq_star_inv:\n  forall a b, star a b -> infseq a -> infseq b.\nProof.\n  induction 1; intros.\n- auto. \n- apply IHstar. apply infseq_inv' with a; auto.\nQed.\n\nLemma infseq_finseq_excl:\n  forall a b,\n  star a b -> irred b -> infseq a -> False.\nProof.\n  intros.\n  destruct (@infseq_inv b) as (c & Rbc & _). eapply infseq_star_inv; eauto. \n  apply (H0 c); auto.\nQed.\n\n(** If there exists an infinite sequence of transitions from [a],\n  all sequences of transitions arising from [a] are infinite. *)\n\nLemma infseq_all_seq_inf:\n  forall a, infseq a -> all_seq_inf a.\nProof.\n  intros. unfold all_seq_inf. intros.\n  destruct (@infseq_inv b) as (c & Rbc & _). eapply infseq_star_inv; eauto.\n  exists c; auto.\nQed.\n\nEnd SEQUENCES.\n\n\n\n", "meta": {"author": "xavierleroy", "repo": "cdf-mech-sem", "sha": "f8dc6f7e2cb42f0861406b2fa113e2a7e825c5f3", "save_path": "github-repos/coq/xavierleroy-cdf-mech-sem", "path": "github-repos/coq/xavierleroy-cdf-mech-sem/cdf-mech-sem-f8dc6f7e2cb42f0861406b2fa113e2a7e825c5f3/Sequences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7484798352604626}}
{"text": "Require Import Bool Arith List CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nInductive binop : Set := Plus | Times.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp.\n\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n  match b with\n  | Plus => plus\n  | Times => mult\n  end.\n\nFixpoint expDenote (e : exp) : nat :=\n  match e with\n  | Const n => n\n  | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n  end.\n\nEval simpl in expDenote (Const 42).\n\nEval simpl in expDenote (Binop Plus (Const 2) (Const 4)).\n\nEval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 4)) (Const 7)).\n\n\n(* Target Language *)\nInductive instr : Set :=\n| iConst : nat -> instr\n| iBinop : binop -> instr.\n\nDefinition prog := list instr.\nDefinition stack := list nat.\n\nDefinition instrDenote (i : instr) (s : stack) : option stack :=\n  match i with\n    | iConst n => Some (n :: s)\n    | iBinop b =>\n      match s with\n      | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')\n      | _ => None\n      end\n    end.\n\nFixpoint progDenote (p : prog) (s : stack) : option stack :=\n  match p with\n  | nil => Some s\n  | i :: p' =>\n    match (instrDenote i s) with\n    | None => None\n    | Some s' => progDenote p' s'\n    end\n  end.\n\nFixpoint compile (e : exp) : prog :=\n  match e with\n  | Const n => iConst n :: nil\n  | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil\n  end.\n\nEval simpl in compile (Const 42).\n\nEval simpl in compile (Binop Plus (Const 2) (Const 4)).\n\nEval simpl in compile (Binop Plus (Binop Times (Const 2) (Const 4)) (Const 7)).\n\nEval simpl in progDenote (compile (Const 42)).\n\nEval simpl in progDenote (compile (Binop Plus (Const 2) (Const 4))).\n\nEval simpl in progDenote (compile (Binop Times (Binop Plus (Const 2) (Const 4)) (Const 7))).\n\nTheorem compile_correct : forall e,\n  progDenote (compile e) nil = Some (expDenote e :: nil).\nProof.\n  induction e; intros; try reflexivity.\nAbort.\n\nLemma compile_correct' : forall e p s,\n  progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\nProof.\n  induction e.\n  - intros. unfold compile. unfold progDenote at 1. simpl. fold progDenote. reflexivity.\n  - intros. unfold compile. fold compile. unfold progDenote. fold progDenote.\n    Check app_assoc_reverse. SearchRewrite ((_ ++ _) ++ _). rewrite app_assoc_reverse.\n    rewrite IHe2. rewrite app_assoc_reverse. rewrite IHe1. unfold progDenote at 1. simpl. fold progDenote.\n    reflexivity.\nAbort.\n\nLemma compile_correct' : forall e s p,\n  progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\nProof.\n  induction e; crush.\nQed.\n\nTheorem compile_correct : forall e,\n  progDenote (compile e) nil = Some (expDenote e :: nil).\nProof.\n  intros.\n  Check app_nil_end.\n  rewrite (app_nil_end (compile e)).\n  rewrite compile_correct'.\n  reflexivity.\nQed.\n\n\n(* Typed Expressions *)\n\nInductive type : Set := Nat | Bool.\n\nInductive tbinop : type -> type -> type -> Set :=\n | TPlus : tbinop Nat Nat Nat\n | TTimes : tbinop Nat Nat Nat\n | TEq : forall t, tbinop t t Bool\n | TLt : tbinop Nat Nat Bool.\n\nInductive texp : type -> Set :=\n | TNConst : nat -> texp Nat\n | TBConst : bool -> texp Bool\n | TBinop : forall t t1 t2, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\nDefinition typeDenote (t : type) : Set :=\n  match t with\n  | Nat => nat\n  | Bool => bool\n  end.\n\nDefinition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b with\n  | TPlus => plus\n  | TTimes => mult\n  | TEq Nat => beq_nat\n  | TEq Bool => eqb\n  | TLt => leb\n  end.\n\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n  | TNConst n => n\n  | TBConst b => b\n  | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nEval simpl in texpDenote (TNConst 42).\n\nEval simpl in texpDenote (TBConst true).\n\nEval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 4)) (TNConst 7)).\n\nEval simpl in texpDenote (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 4)) (TNConst 7)).\n\nEval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\n\n(* Target Language *)\n\nDefinition tstack := list type.\n\nInductive tinstr : tstack -> tstack -> Set :=\n | TiNConst : forall s, nat -> tinstr s (Nat :: s)\n | TiBConst : forall s, bool -> tinstr s (Bool :: s)\n | TiBinop : forall arg1 arg2 res s, \n    tbinop arg1 arg2 res -> tinstr (arg1 :: arg2 :: s) (res :: s).\n\nInductive tprog : tstack -> tstack -> Set :=\n | TNil : forall s, tprog s s\n | TCons : forall s1 s2 s3,\n    tinstr s1 s2\n    -> tprog s2 s3\n    -> tprog s1 s3.\n\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n    | nil => unit\n    | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\n\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n    | TiNConst _ n => fun s => (n, s)\n    | TiBConst _ b => fun s => (b, s)\n    | TiBinop _ _ _ _ b => fun s =>\n      let '(arg1, (arg2, s')) := s in\n        ((tbinopDenote b) arg1 arg2, s')\n  end.\n\n\nFixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n    | TNil _ => fun s => s\n    | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\n\n(* Translation *)\n\nFixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n    | TNil _ => fun p' => p'\n    | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=\n  match e with\n    | TNConst n => TCons (TiNConst _ n) (TNil _)\n    | TBConst b => TCons (TiBConst _ b) (TNil _)\n    | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)\n      (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\nPrint tcompile.\n\nEval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.\n\nEval simpl in tprogDenote (tcompile (TBConst true) nil) tt.\n\nEval simpl in tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 4)) (TNConst 7)) nil) tt.\n\nEval simpl in tprogDenote (tcompile (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 4)) (TNConst 7)) nil) tt.\n\nEval simpl in tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 4)) (TNConst 7)) nil) tt.\n\n\n(* Translation Correctness *)\n\nTheorem tcompile_correct : forall t (e : texp t),\n  tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\n\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n  tprogDenote (tcompile e ts) s = (texpDenote e, s).\nProof.\n  induction e; crush.\nAbort.\n\nLemma tconcat_correct : forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'') (s : vstack ts),\n  tprogDenote (tconcat p p') s\n  = tprogDenote p' (tprogDenote p s).\nProof.\n  induction p; crush.\nQed.\n\nHint Rewrite tconcat_correct.\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n  tprogDenote (tcompile e ts) s = (texpDenote e, s).\nProof.\n  induction e; crush.\nQed.\n\nHint Rewrite tcompile_correct'.\n\nTheorem tcompile_correct : forall t (e : texp t),\n  tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\nProof.\n  induction e; crush.\nQed.\n\nRequire Coq.extraction.Extraction.\nExtraction Language OCaml.\n\nExtraction tcompile.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "prashantpawar", "repo": "cpdt", "sha": "c75e725042217fc440a8b9de3517c23e3340c390", "save_path": "github-repos/coq/prashantpawar-cpdt", "path": "github-repos/coq/prashantpawar-cpdt/cpdt-c75e725042217fc440a8b9de3517c23e3340c390/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7484798261057305}}
{"text": "(* ========================================================================== *]\n THINGS COQ CAN DO\n[* ========================================================================== *)\nRequire Import Nat List Lia.\n\nInductive tree {A} :=\n| Empty : tree\n| Node : tree -> A -> tree -> tree\n.\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\nFixpoint tree_map {A B} (f : A -> B) (t : @tree A) :=\n    match t with\n    | Empty => Empty\n    | Node l_t x r_t => Node (tree_map f l_t) (f x) (tree_map f r_t)\n    end.\n\n(* -------------------------------------------------------------------------- *]\n A very useful thing is defining relations between terms (as propositions).\n This is something that we usually do by defining functions that map\n to `bool`, but by defining the relation inductively, allows us to perform\n induction on the 'proof' that two terms are related.\n\n Consider the following relation, that links trees with the same shape.\n[* -------------------------------------------------------------------------- *)\n\nInductive same_shape {A B} : @tree A -> @tree B -> Prop :=\n| both_empty : ???\n| both_nodes lt_a lt_b a b rt_a rt_b : ???\n.\n\n\n(* -------------------------------------------------------------------------- *]\n Trees of the same shape have the same height, meaning that height is not\n impacted by the data of the tree (which is obvious to us, but sometimes\n obvious things turn out to be just our imagination...).\n[* -------------------------------------------------------------------------- *)\n\nLemma same_shape_same_height {A B} (ta : @tree A) (tb : @tree B) :\n    same_shape ta tb -> height ta = height tb.\nProof.\n    admit.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n We can check that functions such as `map` do not alter the shape of the tree,\n only its data.\n\n Here we need to construct the proof that the trees have the same shape, so\n we apply the constructors of `same_shape`.\n[* -------------------------------------------------------------------------- *)\n\nLemma map_preserves_shape {A B} (f : A -> B) (t : @tree A):\n    same_shape t (tree_map f t).\nProof.\n    admit.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n Coq also allows the use of 'values' in types. A standard example are vectors,\n which have their length specified as part of their type.\n[* -------------------------------------------------------------------------- *)\n\nInductive vector {A} : nat -> Type :=\n| Nil : vector 0\n| Cons {n} : A -> vector n -> vector (S n)\n.\n\nExample vector_3 : vector 3 := Cons true (Cons true (Cons true Nil)).\n\n\n(* -------------------------------------------------------------------------- *]\n Types now clearly state what happens to the vector length, which can help us\n avoid issues such as 'index out of range'.\n[* -------------------------------------------------------------------------- *)\n\nFixpoint concat ??? :=\n    match v1 with\n    | Nil => v2\n    | Cons x xs => Cons x (concat xs v2)\n    end.\n\nCompute (concat vector_3 vector_3).\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/things_coq_can_do.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7484690606982981}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Psatz.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\nRequire Import PL.CoqInductiveType.\nLocal Open Scope Z.\nLocal Open Scope string.\n\n\n(** **** Exercise **** *)\n(** 请证明下面引理_[size_nonneg]_。*)\n\nLemma size_nonneg: forall t,\n  0 <= tree_size t.\nProof.\n  intros.\n  induction t.\n  + simpl. reflexivity.\n  + simpl.\n    lia.\nQed.\n\n(** **** Exercise **** *)\n(** 下面定义的_[left_most]_与_[right_most]_函数分别计算了二叉树中最左边的节点编\n    号以及最右边的节点编号。如果树是空树，则返回_[default]_参数。请证明下面引理\n    _[left_most_reverse]_。*)\n\nFixpoint left_most (t: tree) (default: Z): Z :=\n  match t with\n  | Leaf => default\n  | Node l n r => left_most l n\n  end.\n\nFixpoint right_most (t: tree) (default: Z): Z :=\n  match t with\n  | Leaf => default\n  | Node l n r => right_most r n\n  end.\n\n(** 提示：如果你的前两步证明指令是_[intros]_以及_[induction t]_，那么你会发现，\n    归纳步骤的结论是无法证明的。你会发现你需要使用的_[default]_参数与归纳假设中\n    的不一致。你可以尝试用_[intros t]_以及_[induction t]_开始你的证明，看看有什\n    么不同。*)\n\nLemma left_most_reverse: forall t default,\n  left_most (tree_reverse t) default = right_most t default.\nProof.\n  intros t.\n  induction t.\n  + simpl. reflexivity.\n  + simpl.\n    rewrite IHt2.\n    reflexivity.\nQed.\n\n(** **** Exercise **** *)\n(** 下面定义的_[string_rev_append]_是一种用尾递归方法定义字符串左右翻转的方法。\n    请你证明它与我们先前定义的_[string_rev]_之间的关系。  *)\n\nFixpoint string_rev_append (s1 s2: string): string :=\n  match s1 with\n  | EmptyString => s2\n  | String c s1' => string_rev_append s1' (String c s2)\n  end.\n\nLemma string_rev_append_spec: forall s1 s2: string,\n  string_rev_append s1 s2 = string_app (string_rev s1) s2.\nProof.\n  intros s1.\n  induction s1.\n  + simpl. reflexivity.\n  + simpl.\n    intros s2.\n    rewrite <- string_app_assoc.\n    simpl.\n    rewrite IHs1.\n    reflexivity.\nQed.\n", "meta": {"author": "gzqaq", "repo": "CS2612-PLaC", "sha": "fb7be0651785905b60d3e705324175daaadcc96b", "save_path": "github-repos/coq/gzqaq-CS2612-PLaC", "path": "github-repos/coq/gzqaq-CS2612-PLaC/CS2612-PLaC-fb7be0651785905b60d3e705324175daaadcc96b/assigns/assign0916/Assignment0916.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7484209155860381}}
{"text": "Welcome to Coq 8.4pl6 (January 2017)\n\nCoq < Inductive natlist : Type := | nil : natlist | cons : nat -> natlist -> natlist.\nnatlist is defined\nnatlist_rect is defined\nnatlist_ind is defined\nnatlist_rec is defined\n\nCoq < Definition mylist := cons 1 (cons 2 (cons 3 nil)).\nmylist is defined\n\nCoq < Notation \"x :: l\" := (cons x l) (at level 60, right associativity).\n\nCoq < Notation \"[ ]\" := nil.\nSetting notation at level 0.\n\nCoq < Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\nSetting notation at level 0.\n\nCoq < Definition mylist1 := 1 :: (2 :: (3 :: nil)).\nmylist1 is defined\n\nCoq < Definition mylist2 := 1 :: 2 :: 3 :: nil.\nmylist2 is defined\n\nCoq < Definition mylist3 := [1;2;3].\nmylist3 is defined\n\nCoq < Notation \"x + y\" := (plus x y) (at level 50, left associativity).\n\nCoq < Fixpoint repeat (n count : nat) : natlist := match count with | O => nil | S count' => n :: (repeat n count') end.\nrepeat is recursively defined (decreasing on 2nd argument)\n\nCoq < Fixpoint length (l:natlist) : nat := match l with | nil => O | h :: t => S (length t) end.\nlength is recursively defined (decreasing on 1st argument)\n\nCoq < Fixpoint app (l1 l2 : natlist) : natlist := match l1 with | nil => l2 | h :: t => h :: (app t l2) end.\napp is recursively defined (decreasing on 1st argument)\n\nCoq < Notation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\nCoq < Example test_app1: [1;2;3] ++ [4;5] = [1;2;3;4;5].\n1 subgoal\n  \n  ============================\n   [1; 2; 3] ++ [4; 5] = [1; 2; 3; 4; 5]\n\ntest_app1 < Proof.\n1 subgoal\n  \n  ============================\n   [1; 2; 3] ++ [4; 5] = [1; 2; 3; 4; 5]\n\ntest_app1 < reflexivity.\nNo more subgoals.\n\ntest_app1 < Qed.\nreflexivity.\n\ntest_app1 is defined\n\nCoq < Example test_app2: nil ++ [4;5] = [4;5].\n1 subgoal\n  \n  ============================\n   [] ++ [4; 5] = [4; 5]\n\ntest_app2 < Proof.\n1 subgoal\n  \n  ============================\n   [] ++ [4; 5] = [4; 5]\n\ntest_app2 < reflexivity.\nNo more subgoals.\n\ntest_app2 < Qed.\nreflexivity.\n\ntest_app2 is defined\n\nCoq < Example test_app3: [1;2;3] ++ nil = [1;2;3].\n1 subgoal\n  \n  ============================\n   [1; 2; 3] ++ [] = [1; 2; 3]\n\ntest_app3 < Proof.\n1 subgoal\n  \n  ============================\n   [1; 2; 3] ++ [] = [1; 2; 3]\n\ntest_app3 < reflexivity.\nNo more subgoals.\n\ntest_app3 < Qed.\nreflexivity.\n\ntest_app3 is defined\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/foundations/lists/lists002.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7484209124558827}}
{"text": "(* week-04_live-coding-session.v *)\n(* FPP 2020 - YSC3236 2020-2021, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 05 Sep 2020, after a minimal cleanup *)\n\n(* ********** *)\n\n(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name :=\n  intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith Bool.\n\n(* ********** *)\n\nDefinition test_power (candidate : nat -> nat -> nat) : bool :=\n  (candidate 2 0 =? 1) &&\n  (candidate 10 2 =? 10 * 10) &&\n  (candidate 3 2 =? 3 * 3).\n\nDefinition specification_of_power (power : nat -> nat -> nat) :=\n  (forall x : nat,\n      power x 0 = 1)\n  /\\\n  (forall (x : nat)\n          (n' : nat),\n      power x (S n') = x * power x n').\n\nTheorem soundness_of_test_power :\n  forall power : nat -> nat -> nat,\n    specification_of_power power ->\n    test_power power = true.\nProof.\n  intro power.\n  unfold specification_of_power.\n  intros [S_power_O S_power_S].\n  unfold test_power.\n  Check (S_power_O 2).\n  rewrite -> (S_power_O 2).\n  Search (_ =? _).\n  Check (Nat.eqb_refl 1).\n  rewrite -> (Nat.eqb_refl 1).\n  Search (true && _ = _).\n  Check (true && (true && true), (true && true) && true).\n  Check (andb_true_l (power 10 2 =? 100)).\n  rewrite -> (andb_true_l (power 10 2 =? 10 * 10)).\n  assert (helpful :\n            forall x : nat,\n              power x 2 = x * x).\n  { intro x.\n    Check (S_power_S x 1).\n    rewrite -> (S_power_S x 1).\n    Check (S_power_S x 0).\n    rewrite -> (S_power_S x 0).\n    rewrite -> (S_power_O x).\n    rewrite -> (Nat.mul_1_r x).\n    reflexivity. }\n  rewrite -> (helpful 10).\n  rewrite -> (Nat.eqb_refl (10 * 10)).\n  rewrite -> (andb_true_l (power 3 2 =? 3 * 3)).\n  rewrite -> (helpful 3).\n  rewrite -> (Nat.eqb_refl (3 * 3)).\n  reflexivity.\nQed.\n\n(* ********** *)\n\nProposition identity :\n  forall A : Prop,\n    A -> A.\nProof.\n  intros A H_A.\n  apply H_A.\nQed.\n\n(* ***** *)\n\nProposition modus_ponens :\n  forall A B : Prop,\n    A -> (A -> B) -> B.\nProof.\n  intros A B H_A H_A_implies_B.\n  apply H_A_implies_B.\n  apply H_A.\n  Show Proof.\n(*(fun (A B : Prop) (H_A : A) (H_A_implies_B : A -> B) => H_A_implies_B H_A)*)\n\n  Restart.\n\n  intros A B H_A H_A_implies_B.\n  Check (H_A_implies_B H_A).\n  apply (H_A_implies_B H_A).\n  Show Proof.\n(*(fun (A B : Prop) (H_A : A) (H_A_implies_B : A -> B) => H_A_implies_B H_A)*)\n\n  Restart.\n\n  intros A B H_A H_A_implies_B.\n  assert (H_B := H_A_implies_B H_A).\n  apply H_B.\n  Show Proof.\n(*(fun (A B : Prop) (H_A : A) (H_A_implies_B : A -> B) => (fun H_B : B => H_B) (H_A_implies_B H_A)) *)\n\nQed.\n\n(* ***** *)\n\nProposition foo :\n  forall A B C1 C2 : Prop,\n    A -> (A -> B) -> (B -> C1) /\\ (B -> C2) -> C1 /\\ C2.\nProof.\n  intros A B C1 C2 H_A H_A_implies_B [H_B_implies_C1 H_B_implies_C2].\n  split.\n  - apply H_B_implies_C1.\n    apply H_A_implies_B.\n    apply H_A.\n  - apply H_B_implies_C2.\n    apply H_A_implies_B.\n    apply H_A.\n\n  Restart.\n\n  intros A B C1 C2 H_A H_A_implies_B [H_B_implies_C1 H_B_implies_C2].\n  - Check (H_A_implies_B H_A).\n    Check (H_B_implies_C1 (H_A_implies_B H_A)).\n    Check (H_B_implies_C2 (H_A_implies_B H_A)).\n    Check (conj (H_B_implies_C1 (H_A_implies_B H_A)) (H_B_implies_C2 (H_A_implies_B H_A))).\n    exact (conj (H_B_implies_C1 (H_A_implies_B H_A)) (H_B_implies_C2 (H_A_implies_B H_A))).\n\n  Restart.\n\n  intros A B C1 C2 H_A H_A_implies_B [H_B_implies_C1 H_B_implies_C2].\n  apply H_A_implies_B in H_A.\n  Check (H_B_implies_C1 H_A).\n  Check (H_B_implies_C2 H_A).\n  Check (conj (H_B_implies_C1 H_A) (H_B_implies_C2 H_A)).\n  exact (conj (H_B_implies_C1 H_A) (H_B_implies_C2 H_A)).\n\n  Restart.\n\n  intros A B C1 C2 H_A H_A_implies_B [H_B_implies_C1 H_B_implies_C2].\n  assert (H_B := H_A_implies_B H_A).\n  Check (H_B_implies_C1 H_B).\n  Check (conj (H_B_implies_C1 H_B) (H_B_implies_C2 H_B)).\n  exact (conj (H_B_implies_C1 H_B) (H_B_implies_C2 H_B)).\nQed.\n\n(* ********** *)\n\nFixpoint power_v0 (x n : nat) : nat :=\n  match n with\n  | O =>\n    1\n  | S n' =>\n    x * (power_v0 x n')\n  end.\n\nLemma fold_unfold_power_v0_O :\n  forall x : nat,\n    power_v0 x O =\n    1.\nProof.\n  fold_unfold_tactic power_v0.\nQed.\n\nLemma fold_unfold_power_v0_S :\n  forall x n' : nat,\n    power_v0 x (S n') =\n    x * (power_v0 x n').\nProof.\n  fold_unfold_tactic power_v0.\nQed.\n  \n(* ***** *)\n\nFixpoint power_v1_aux (x n a : nat) : nat :=\n  match n with\n  | O =>\n    a\n  | S n' =>\n    power_v1_aux x n' (x * a)\n  end.\n\nLemma fold_unfold_power_v1_aux_O :\n  forall x a : nat,\n    power_v1_aux x 0 a =\n    a.\nProof.\n  fold_unfold_tactic power_v1_aux.\nQed.\n\nLemma fold_unfold_power_v1_aux_S :\n  forall x n' a : nat,\n    power_v1_aux x (S n') a =\n    power_v1_aux x n' (x * a).\nProof.\n  fold_unfold_tactic power_v1_aux.\nQed.\n\nDefinition power_v1 (x n : nat) : nat :=\n  power_v1_aux x n 1.\n\n(* ***** *)\n\n(* Eureka lemma: *)\n\nLemma about_power_v0_and_power_v1_aux :\n  forall x n a : nat,\n    power_v0 x n * a = power_v1_aux x n a.\n(*\n    power_v0 x n is       x * x * ... * x n times\n\n    power_v1_aux x n a is x * x * ... * x * a\n *)\nProof.\n  intros x n.\n  induction n as [ | n' IHn'].\n  - intro a.\n    rewrite -> (fold_unfold_power_v0_O x).\n    rewrite -> (fold_unfold_power_v1_aux_O x a).\n    exact (Nat.mul_1_l a).\n  - intro a.\n    rewrite -> (fold_unfold_power_v0_S x n').\n    rewrite -> (fold_unfold_power_v1_aux_S x n' a).\n    Check (IHn' (x * a)).\n    rewrite <- (IHn' (x * a)).\n    rewrite -> (Nat.mul_comm x (power_v0 x n')).\n    Check (Nat.mul_assoc).\n    symmetry.\n    exact (Nat.mul_assoc (power_v0 x n') x a).\nQed.    \n\n(* Lemma that proved unnecessary: *)\n\nLemma power_v0_and_power_v1_are_equivalent_aux :\n  forall x n : nat,\n    power_v0 x n = power_v1_aux x n 1.\nProof.\n  intros x n.\n  induction n as [ | n' IHn'].\n  - rewrite -> (fold_unfold_power_v0_O x).\n    rewrite -> (fold_unfold_power_v1_aux_O x 1).\n    reflexivity.\n  - rewrite -> (fold_unfold_power_v0_S x n').\n    rewrite -> (fold_unfold_power_v1_aux_S x n' 1).\n    rewrite -> (Nat.mul_1_r x).\n    Check (about_power_v0_and_power_v1_aux x n' x).\n    rewrite <- (about_power_v0_and_power_v1_aux x n' x).\n    Check (Nat.mul_comm x (power_v0 x n')).\n    exact (Nat.mul_comm x (power_v0 x n')).\nQed.\n(*\n    case n' as [ | n''].\n    + rewrite -> (fold_unfold_power_v0_O x).\n      rewrite -> (fold_unfold_power_v1_aux_O x x).\n      exact (Nat.mul_1_r x).\n    + rewrite -> (fold_unfold_power_v0_S x n'').\n      rewrite -> (fold_unfold_power_v1_aux_S x n'' x).\n*)\n\nTheorem power_v0_and_power_v1_are_equivalent :\n  forall x n : nat,\n    power_v0 x n = power_v1 x n.\nProof.\n  intros x n.\n  unfold power_v1.\n  Check (about_power_v0_and_power_v1_aux x n 1).\n  rewrite <- (Nat.mul_1_r (power_v0 x n)).\n  exact (about_power_v0_and_power_v1_aux x n 1).\nQed.\n\n(* ********** *)\n\nFixpoint fib (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      fib n' + fib n''\n    end\n  end.\n\nLemma fold_unfold_lemma_fib_O :\n  fib 0 =\n  0.\nProof.\n  fold_unfold_tactic fib.\n Qed.\n\nLemma fold_unfold_lemma_fib_S :\n  forall n' : nat,\n    fib (S n') =\n    match n' with\n    | O =>\n      1\n    | S n'' =>\n      fib n' + fib n''\n    end.\nProof.\n  fold_unfold_tactic fib.\nQed.\n\nCorollary fold_unfold_lemma_fib_1 :\n  fib 1 =\n  1.\nProof.\n  Check (fold_unfold_lemma_fib_S 0).\n  exact (fold_unfold_lemma_fib_S 0).\nQed.\n\nCorollary fold_unfold_lemma_fib_SS :\n  forall n'' : nat,\n    fib (S (S n'')) =\n    fib (S n'') + fib n''.\nProof.\n  intro n''.\n  Check (fold_unfold_lemma_fib_S (S n'')).\n  exact (fold_unfold_lemma_fib_S (S n'')).\nQed.\n\n(* ********** *)\n\n(* end of week-04_live-coding-session.v *)\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w04/week-04_live-coding-session.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7482717541456984}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\n(**Set Warnings \"-notation-overridden,-parsing\".*)\nRequire Export IndProp.\n\n(** \"_Algorithms are the computational content of proofs_.\"  --Robert Harper *)\n\n(** We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types like [nat] or [list] and functions over\n    these types, and for _proving_ properties of these programs, using\n    inductive propositions (like [ev]), implication, universal\n    quantification, and the like.  So far, we have mostly treated\n    these mechanisms as if they were quite separate, and for many\n    purposes this is a good way to think.  But we have also seen hints\n    that Coq's programming and proving facilities are closely related.\n    For example, the keyword [Inductive] is used to declare both data\n    types and propositions, and [->] is used both to describe the type\n    of functions on data and logical implication.  This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are\n    almost the same thing.  In this chapter we will study how this\n    works.\n\n    We have already seen the fundamental idea: provability in Coq is\n    represented by concrete _evidence_.  When we construct the proof\n    of a basic proposition, we are actually building a tree of\n    evidence, which can be thought of as a data structure.\n\n    If the proposition is an implication like [A -> B], then its proof\n    will be an evidence _transformer_: a recipe for converting\n    evidence for A into evidence for B.  So at a fundamental level,\n    proofs are simply programs that manipulate evidence. *)\n\n(** Question: If evidence is data, what are propositions themselves?\n\n    Answer: They are types! *)\n\n(** Look again at the formal definition of the [ev] property.  *)\n\nPrint ev.\n(* ==>\n  Inductive ev : nat -> Prop :=\n    | ev_0 : ev 0\n    | ev_SS : forall n, ev n -> ev (S (S n)).\n*)\n\n(** Suppose we introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can say \"is a proof of.\"  For example,\n    the second line in the definition of [ev] declares that [ev_0 : ev\n    0].  Instead of \"[ev_0] has type [ev 0],\" we can say that \"[ev_0]\n    is a proof of [ev 0].\" *)\n\n(** This pun between types and propositions -- between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\" -- is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation:\n\n                 propositions  ~  types\n                 proofs        ~  data values\n\n    See [Wadler 2015] for a brief history and an up-to-date exposition. *)\n\n(** Many useful insights follow from this connection.  To begin with,\n    it gives us a natural interpretation of the type of the [ev_SS]\n    constructor: *)\n\nCheck ev_SS.\n(* ===> ev_SS : forall n,\n                  ev n ->\n                  ev (S (S n)) *)\n\n(** This can be read \"[ev_SS] is a constructor that takes two\n    arguments -- a number [n] and evidence for the proposition [ev\n    n] -- and yields evidence for the proposition [ev (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [ev]. *)\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** As with ordinary data values and functions, we can use the [Print]\n    command to see the _proof object_ that results from this proof\n    script. *)\n\nPrint ev_4.\n(* ===> ev_4 = ev_SS 2 (ev_SS 0 ev_0)\n     : ev 4  *)\n\n(** Indeed, we can also write down this proof object _directly_,\n    without the need for a separate proof script: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n(* ===> ev 4 *)\n\n(** The expression [ev_SS 2 (ev_SS 0 ev_0)] can be thought of as\n    instantiating the parameterized constructor [ev_SS] with the\n    specific arguments [2] and [0] plus the corresponding proof\n    objects for its premises [ev 2] and [ev 0].  Alternatively, we can\n    think of [ev_SS] as a primitive \"evidence constructor\" that, when\n    applied to a particular number, wants to be further applied to\n    evidence that that number is even; its type,\n\n      forall n, ev n -> ev (S (S n)),\n\n    expresses this functionality, in the same way that the polymorphic\n    type [forall X, list X] expresses the fact that the constructor\n    [nil] can be thought of as a function from types to empty lists\n    with elements of that type. *)\n\n(** We saw in the [Logic] chapter that we can use function\n    application syntax to instantiate universally quantified variables\n    in lemmas, as well as to supply evidence for assumptions that\n    these lemmas impose.  For instance: *)\n\nTheorem ev_4': ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(* ################################################################# *)\n(** * Proof Scripts *)\n\n(** The _proof objects_ we've been discussing lie at the core of how\n    Coq operates.  When Coq is following a proof script, what is\n    happening internally is that it is gradually constructing a proof\n    object -- a term whose type is the proposition being proved.  The\n    tactics between [Proof] and [Qed] tell it how to build up a term\n    of the required type.  To see this process in action, let's use\n    the [Show Proof] command to display the current state of the proof\n    tree at various points in the following tactic proof. *)\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with a\n    \"hole\" (indicated by [?Goal] here, and so on), and it knows what\n    type of evidence is needed to fill this hole.  \n\n    Each hole corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    evidence we've built stored in the global context under the name\n    given in the [Theorem] command. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand, as shown above. Then we can use [Definition]\n    (rather than [Theorem]) to give a global name directly to this\n    evidence. *)\n\nDefinition ev_4''' : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint ev_4.\n(* ===> ev_4    =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\n\n(** **** Exercise: 2 stars (eight_is_even)  *)\n(** Give a tactic proof and a proof object showing that [ev 8]. *)\n\nTheorem ev_8 : ev 8.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_SS. apply ev_SS. apply ev_0.\nQed.\n\nDefinition ev_8' : ev 8 :=\n  ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0))).\n(** [] *)\n\n(* ################################################################# *)\n(** * Quantifiers, Implications, Functions *)\n\n(** In Coq's computational universe (where data structures and\n    programs live), there are two sorts of values with arrows in their\n    types: _constructors_ introduced by [Inductive]ly defined data\n    types, and _functions_.\n\n    Similarly, in Coq's logical universe (where we carry out proofs),\n    there are two ways of giving evidence for an implication:\n    constructors introduced by [Inductive]ly defined propositions,\n    and... functions! *)\n\n(** For example, consider this statement: *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\n(** What is the proof object corresponding to [ev_plus4]?\n\n    We're looking for an expression whose _type_ is [forall n, ev n ->\n    ev (4 + n)] -- that is, a _function_ that takes two arguments (one\n    number and a piece of evidence) and returns a piece of evidence!\n\n    Here it is: *)\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah],\" and that Coq treats [4 + n] and [S (S (S (S n)))]\n    as synonyms. Another equivalent way to write this definition is: *)\n\nDefinition ev_plus4'' (n : nat) (H : ev n)\n                    : ev (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\n(* ===> \n     : forall n : nat, ev n -> ev (4 + n) *)\n\n(** When we view the proposition being proved by [ev_plus4] as a\n    function type, one interesting point becomes apparent: The second\n    argument's type, [ev n], mentions the _value_ of the first\n    argument, [n].\n\n    While such _dependent types_ are not found in conventional\n    programming languages, they can be useful in programming too, as\n    the recent flurry of activity in the functional programming\n    community demonstrates. *)\n\n(** Notice that both implication ([->]) and quantification ([forall])\n    correspond to functions on evidence.  In fact, they are really the\n    same thing: [->] is just a shorthand for a degenerate use of\n    [forall] where there is no dependency, i.e., no need to give a\n    name to the type on the left-hand side of the arrow:\n\n           forall (x:nat), nat  \n        =  forall (_:nat), nat  \n        =  nat -> nat\n*)\n\n\n(** For example, consider this proposition: *)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : ev n), ev (n + 2).\n\n(** A proof term inhabiting this proposition would be a function\n    with two arguments: a number [n] and some evidence [E] that [n] is\n    even.  But the name [E] for this evidence is not used in the rest\n    of the statement of [ev_plus2], so it's a bit silly to bother\n    making up a name for it.  We could write it like this instead,\n    using the dummy identifier [_] in place of a real name: *)\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : ev n), ev (n + 2).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, ev n -> ev (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\n(** If we can build proofs by giving explicit terms rather than\n    executing tactic scripts, you may be wondering whether we can\n    build _programs_ using _tactics_ rather than explicit terms.\n    Naturally, the answer is yes! *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n\nPrint add1.\n(* ==>\n    add1 = fun n : nat => S n\n         : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than\n    with [:=] followed by a term.  This tells Coq to enter _proof\n    scripting mode_ to build an object of type [nat -> nat].  Also, we\n    terminate the proof with [Defined] rather than [Qed]; this makes\n    the definition _transparent_ so that it can be used in computation\n    like a normally-defined function.  ([Qed]-defined objects are\n    opaque during computation.)\n\n    This feature is mainly useful for writing functions with dependent\n    types, which we won't explore much further in this book.  But it\n    does illustrate the uniformity and orthogonality of the basic\n    ideas in Coq. *)\n\n\n(* ################################################################# *)\n(** * Logical Connectives as Inductive Types *)\n\n(** Inductive definitions are powerful enough to express most of the\n    connectives and quantifiers we have seen so far.  Indeed, only\n    universal quantification (and thus implication) is built into Coq;\n    all the others are defined inductively.  We'll see these\n    definitions in this section. *)\n\nModule Props.\n\n(** ** Conjunction\n\n    To prove that [P /\\ Q] holds, we must present evidence for both\n    [P] and [Q].  Thus, it makes sense to define a proof object for [P\n    /\\ Q] as consisting of a pair of two proofs: one for [P] and\n    another one for [Q]. This leads to the following definition. *)\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\n\nEnd And.\n\n(** Notice the similarity with the definition of the [prod] type,\n    given in chapter [Poly]; the only difference is that [prod] takes\n    [Type] arguments, whereas [and] takes [Prop] arguments. *)\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\n\n(** This should clarify why [destruct] and [intros] patterns can be\n    used on a conjunctive hypothesis.  Case analysis allows us to\n    consider all possible ways in which [P /\\ Q] was proved -- here\n    just one (the [conj] constructor).  Similarly, the [split] tactic\n    actually works for any inductively defined proposition with only\n    one constructor.  In particular, it works for [and]: *)\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\nQed.\n\n(** This shows why the inductive definition of [and] can be\n    manipulated by tactics as we've been doing.  We can also use it to\n    build proofs directly, using pattern-matching.  For instance: *)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, optional (conj_fact)  *)\n(** Construct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun P Q R (PandQ: P/\\Q) (QandR: Q/\\R) =>\n    match PandQ with\n      | conj HP HQ => match QandR with\n                        | conj HQ HR => conj HP HR\n                      end\n    end.\n(** [] *)\n\n\n\n(** ** Disjunction\n\n    The inductive definition of disjunction uses two constructors, one\n    for each side of the disjunct: *)\n\nModule Or.\n\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\n\nEnd Or.\n\n(** This declaration explains the behavior of the [destruct] tactic on\n    a disjunctive hypothesis, since the generated subgoals match the\n    shape of the [or_introl] and [or_intror] constructors.\n\n    Once again, we can also directly write proof objects for theorems\n    involving [or], without resorting to tactics. *)\n\n(** **** Exercise: 2 stars, optional (or_commut'')  *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P. Admitted.\n(** [] *)\n\n(** ** Existential Quantification\n\n    To give evidence for an existential quantifier, we package a\n    witness [x] together with a proof that [x] satisfies the property\n    [P]: *)\n\nModule Ex.\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro : forall x : A, P x -> ex P.\n\nEnd Ex.\n\n(** This may benefit from a little unpacking.  The core definition is\n    for a type former [ex] that can be used to build propositions of\n    the form [ex P], where [P] itself is a _function_ from witness\n    values in the type [A] to propositions.  The [ex_intro]\n    constructor then offers a way of constructing evidence for [ex P],\n    given a witness [x] and a proof of [P x]. *)\n\n(** The more familiar form [exists x, P x] desugars to an expression\n    involving [ex]: *)\n\nCheck ex (fun n => ev n).\n(* ===> exists n : nat, ev n\n        : Prop *)\n\n(** Here's how to define an explicit proof object involving [ex]: *)\n\nDefinition some_nat_is_even : exists n, ev n :=\n  ex_intro ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** **** Exercise: 2 stars, optional (ex_ev_Sn)  *)\n(** Complete the definition of the following proof object: *)\n\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) :=\n  ex_intro (fun n => ev (S n)) 1 (ev_SS 0 ev_0).\n(** [] *)\n\n(* ================================================================= *)\n(** ** [True] and [False] *)\n\n(** The inductive definition of the [True] proposition is simple: *)\n\nInductive True : Prop :=\n  | I : True.\n\n(** It has one constructor (so every proof of [True] is the same, so\n    being given a proof of [True] is not informative.) *)\n\n(** [False] is equally simple -- indeed, so simple it may look\n    syntactically wrong at first glance! *)\n\nInductive False : Prop :=.\n\n(** That is, [False] is an inductive type with _no_ constructors --\n    i.e., no way to build evidence for it. *)\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has the\n    following inductive definition.  (Actually, the definition in the\n    standard library is a small variant of this, which gives an\n    induction principle that is slightly easier to use.) *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n| eq_refl : forall x, eq x x.\n\nNotation \"x = y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\n(** The way to think about this definition is that, given a set [X],\n    it defines a _family_ of propositions \"[x] is equal to [y],\"\n    indexed by pairs of values ([x] and [y]) from [X].  There is just\n    one way of constructing evidence for each member of this family:\n    applying the constructor [eq_refl] to a type [X] and a value [x :\n    X] yields evidence that [x] is equal to [x]. *)\n\n(** We can use [eq_refl] to construct evidence that, for example, [2 =\n    2].  Can we also use it to construct evidence that [1 + 1 = 2]?\n    Yes, we can.  Indeed, it is the very same piece of evidence!\n\n    The reason is that Coq treats as \"the same\" any two terms that are\n    _convertible_ according to a simple set of computation rules.\n\n    These rules, which are similar to those used by [Compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.  *)\n\nLemma four: 2 + 2 = 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove equalities up\n    to now is essentially just short-hand for [apply eq_refl].\n\n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).\n\n    But you can see them directly at work in the following explicit\n    proof objects: *)\n\nDefinition four' : 2 + 2 = 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), []++[x] = x::[]  :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\nEnd MyEquality.\n\n\n(** **** Exercise: 2 stars (equality__leibniz_equality)  *)\n(** The inductive definition of equality implies _Leibniz equality_:\n    what we mean when we say \"[x] and [y] are equal\" is that every\n    property on [P] that is true of [x] is also true of [y].  *)\n\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x = y -> forall P:X->Prop, P x -> P y.\nProof.\n  intros.\n  induction H.\n  apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (leibniz_equality__equality)  *)\n(** Show that, in fact, the inductive definition of equality is\n    _equivalent_ to Leibniz equality: *)\n\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P:X->Prop, P x -> P y) -> x = y.\nProof.\n  intros.\n  apply H.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves.\n\n    In general, the [inversion] tactic...\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n\n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are\n    two constructors, so two subgoals get generated.  The\n    conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [and], there is\n    only one constructor, so only one subgoal gets generated.  Again,\n    the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal.  The\n    constructor does have two arguments, though, and these can be seen\n    in the context in the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [eq], there is\n    again only one constructor, so only one subgoal gets generated.\n    Now, though, the form of the [refl_equal] constructor does give us\n    some extra information: it tells us that the two arguments to [eq]\n    must be the same!  The [inversion] tactic adds this fact to the\n    context. *)\n\n(** $Date: 2017-11-29 14:31:19 -0500 (Wed, 29 Nov 2017) $ *)\n\n", "meta": {"author": "gobaldia", "repo": "logical-foundations", "sha": "8dd76b5f50c2397fb6b49f2873699d2cec9ac5d1", "save_path": "github-repos/coq/gobaldia-logical-foundations", "path": "github-repos/coq/gobaldia-logical-foundations/logical-foundations-8dd76b5f50c2397fb6b49f2873699d2cec9ac5d1/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7482717476792311}}
{"text": "Module Playground1.\n\nInductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day\n  .\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\nEval simpl in (next_weekday friday).\nEval simpl in (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.\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\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise nandb *)\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | false => true\n  | true => match b2 with\n    | false => true\n    | true => false\n    end\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\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n  | false => false\n  | true => match b2 with\n    | false => false\n    | true => b3\n    end\n  end.\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nDefinition pred (n: nat) : nat :=\nmatch n with\n| O => O\n| S n' => n'\nend.\n\nEnd Playground1.\n\nModule Playground2.\n\nDefinition minustwo (n: nat) : nat :=\nmatch n with\n| O => O\n| S O => O\n| S (S n') => n'\nend.\n\nCheck S( S( S( S O ) ) ).\nEval simpl in (minustwo 11).\nCheck S.\nCheck pred.\nCheck minustwo.\n\nFixpoint evenb (n:nat) : bool :=\nmatch n with\n| O => true\n| S O => false\n| S (S n') => evenb n'\nend.\n\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nEval simpl in ( evenb 10 ). (* true *)\nEval simpl in ( evenb 9).   (* false *)\nEval simpl in ( oddb 10 ).  (* oddb 10 (!?) *)\nEval simpl in ( oddb 9).    (* oddb 9 (!?) *)\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\nFixpoint plus (n:nat) (m:nat) : nat :=\nmatch n with\n| O => m\n(*\n| S n' => plus n' (S m)\n*)\n| S n' => S( plus n' m )\nend.\n\nEval simpl in (plus (S (S (S O))) (S (S O)) ).\n\nFixpoint mult (n m : nat) : nat :=\nmatch n with\n| O => O\n| S n' => plus m (mult n' m)\nend.\n\nFixpoint minus (n m : nat) : nat :=\nmatch n, m with\n| O, _ => O\n| _, O => n\n| S n', S m' => minus n' m'\nend.\n\nFixpoint exp (base power : nat) : nat :=\nmatch power with\n| O => S O\n| S power' => mult base (exp base power')\nend.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity. Qed.\n\nFixpoint factorial (n:nat) : nat :=\nmatch n with\n| O => S O\n| S n' => mult n (factorial n')\nend.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y) (at level 50, left associativity) : nat_scope.\nNotation \"x - y\" := (minus x y) (at level 50, left associativity) : nat_scope.\nNotation \"x * y\" := (mult x y) (at level 40, left associativity) : nat_scope.\n\n(* nat_scope ってなんだろう？ *)\n\nCheck (0 + (1 + 1)).\nCheck (0 + 1) + 1.\n\nFixpoint beq_nat (n m : nat) : bool :=\nmatch n with\n| O => match m with\n  | O => true\n  | S _ => false\n  end\n| S n' => match m with\n  | O => false\n  | S m' => beq_nat n' m'\n  end\nend.\n\nFixpoint ble_nat (n m : nat) : bool :=\nmatch n with\n| O => true\n| S n' => match m with\n  | O => false\n  | S m' => ble_nat n' m'\n  end\nend.\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 := ble_nat (S n) m.\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\nTheorem plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  simpl. reflexivity. Qed.\n\n(*\nTheorem plus_n_0 : forall n:nat, n + 0 = n.\nProof.\n  simpl. reflexivity. Qed.\n  (* Error: Impossible to unify \"n\" with \"n + 0\". *)\n  (* see plus_0_r *)\n*)\n\nEval simpl in (forall n:nat, n + 0 = n).\n(*\nscripts\n     = forall n : nat, n + 0 = n\n     : Prop\n*)\nEval simpl in (forall n:nat, 0 + n = n).\n(*\nscripts\n     = forall n : nat, n = n\n     : Prop\n*)\n(* 違い：後者は、最初の引数が0なので、match clauseが選べる。再帰不要。 *)\n\nTheorem plus_id_example : forall n m : nat,\n  n = m ->\n  n + m = m + n.\n\nProof.\n  intros n m.\n  intros H.\n  rewrite -> H.\n  reflexivity.\n  Qed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\n\nProof.\n  intros n m o.\n  intros H.\n  intros I.\n  rewrite -> H.\n  rewrite -> I.\n  reflexivity.\n  Qed.\n\nTheorem mult_O_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\n  rewrite -> plus_O_n.\n  reflexivity.\n  Qed.\n\nTheorem mult_1_plus : forall n m : nat,\n  (1 + n) * m = m + (n * m).\nProof.\n  intros n m.\n  simpl.\n  reflexivity.\n  Qed.\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  simpl. reflexivity.\n  simpl. reflexivity.\n  Qed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b.\n  destruct b as [|].\n  simpl. reflexivity.\n  simpl. reflexivity.\n  Qed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  destruct n as [|n'].\n  simpl. reflexivity.\n  simpl. reflexivity.\n  Qed.\n\n\n(* tactic Case *)\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\n\nTheorem andb_true_elim1 : forall b c : bool,\n  andb b c = true -> b = true.\nProof.\n  intros b c.\n  intros H.\n  destruct b.\n  Case \"b = true\".\n    reflexivity.\n  Case \"b = false\".\n    rewrite <- H.\n    reflexivity.\n  Qed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct c.\n  Case \"c = true\".\n    reflexivity.\n  Case \"c = false\".\n    rewrite <- H.\n    destruct b.\n    SCase \"b = true\".\n      reflexivity.\n    SCase \"b = false\".\n      reflexivity.\n  Qed.\n\nTheorem plus_0_r : forall n : nat, 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.\n  Qed.\n\nTheorem minus_diag : forall n, minus n n = 0.\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.\n  Qed.\n\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\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.\n  Qed.\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'].\n  Case \"n = 0\".\n    simpl. reflexivity.\n  Case \"n = S(n')\".\n    simpl. rewrite -> IHn'. reflexivity.\n  Qed.\n\nTheorem plus_comm : forall n m : nat, n + m = m + n.\nProof.\n  intros n m.\n  induction m as [|m'].\n  Case \"m = 0\".\n    simpl. rewrite -> plus_0_r. reflexivity.\n  Case \"m = S(m')\".\n    simpl. rewrite <- IHm'. rewrite -> plus_n_Sm. reflexivity.\n  Qed.\n\nFixpoint double (n : nat) : 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.\n  intros n.\n  induction n.\n  Case \"n = 0\".\n    simpl. reflexivity.\n  Case \"n = S(n')\".\n    simpl. rewrite -> IHn. rewrite -> plus_n_Sm. reflexivity.\n  Qed.\n\n(* Exercise destruct_induction\n * induction は コンテキストに induction hypothesis が入る。natでなくても使える。\n *)\n(*\nInductive tree : Type :=\n| Leaf\n| Node : tree -> tree -> tree.\n\nFixpoint tree_size (t : tree) : nat :=\n  match t with\n  | Leaf => 1\n  | Node t' t'' => tree_size t' + tree_size t''\n  end.\n\nTheorem tree_size_plus : forall t u : tree, tree_size(Node t u) = tree_size t + tree_size u.\n  intros t u.\n  destruct t.\n  Case \"t = Leaf\". simpl. reflexivity.\n  Case \"t = Node(t1 t2)\". simpl. reflexivity.\n  Qed.\n\nTheorem tree_size_swap : forall t u : tree, tree_size(Node t u) = tree_size(Node u t).\n  intros t u.\n  induction u.\n  Case \"u = Leaf\". simpl.\n    induction t.\n      simpl. reflexivity.\n      simpl. rewrite <- tree_size_plus. rewrite <- plus_n_Sm. rewrite -> plus_0_r. reflexivity.\n  Case \"u = Node(t1 t2)\". simpl.\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'].\n  Case \"n = 0\". simpl. reflexivity.\n  Case \"n = S(n')\". simpl. rewrite -> IHn'. reflexivity.\n  Qed.\n\n(* Exercise plus_comm_informal\n\n 定理：加法は可換である。すなわち、任意の n, m について、以下が成り立つ。\n\n  n + m = m + n\n\n 証明： m についての帰納法を適用する。\n\n * まず m = 0 とおくと、証明するべき式は以下のようになる。\n   n + 0 = 0 + n\n   右辺を + の定義にしたがって簡約すると、 n となる。\n   ところで定理「任意のnについて n + 0 = n である」が成り立つので\n   左辺も n である。したがって n = n となり、この式は真である。\n * つぎに m = S m' と置き、帰納法の仮定を\n   n + m' = m' + n とすると、\n   S(n + m') = S(m' + n) も成立する。\n   定理「任意の n, m について、S(n + m) = n + S(m) である」で左辺を変形すると：\n   S(n + m') = n + S(m') = n + m\n   + の定義にしたがって右辺を変形すると：\n   S(m' + n) = S(m') + n = m + n\n   したがって n + m = m + n が成立する。これは、直後の値について帰納法の仮定が成り立つことを示している。\n (証明終わり)\n *)\n\nTheorem beq_nat_refl : forall n, true = beq_nat n n.\nProof. induction n. simpl. reflexivity.\n  simpl. rewrite <- IHn. reflexivity.\n  Qed.\n\n(* Exercise beq_nat_refl_informal\n 定理：任意の n について n ≧ n は常に真である\n 証明：n についての帰納法を適用する。\n * n = 0 のとき: 0 ≧ 0 は真である。これは「≧」の定義より直ちに導かれる。\n * n = S(n') のとき: 帰納法の仮定より n' ≧ n' は真である。\n   ここで「≧」の定義より S(n') ≧ S(n') も真である。\n   これは成立を示すべき式「n ≧ 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  assert (H: (m + n) + p = m + (n + p)).\n    Case \"Proof of assertion\".\n      rewrite <- plus_assoc. reflexivity.\n  rewrite <- H.\n  assert (H': m + n = n + m).\n    Case \"Proof of assertion\".\n      rewrite <- plus_comm. reflexivity.\n  rewrite -> H'.\n  rewrite <- plus_assoc.\n  reflexivity.\n  Qed.\n\nLemma mult_m_Sn: forall m n : nat,\n  m + m * n = m * S n.\nProof.\n  intros m n.\n  induction m as [|m'].\n    Case \"m=0\". reflexivity.\n    Case \"m=Sm'\".\n      simpl. rewrite <- IHm'.\n      rewrite <- plus_swap.\n      reflexivity.\n  Qed.\n\nTheorem mult_comm: forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n.\n  induction n as [| n'].\n  Case \"n=0\".\n    rewrite -> mult_0_r. reflexivity.\n  Case \"n=S(n')\".\n    simpl.\n    rewrite <- IHn'.\n    rewrite -> mult_m_Sn.\n    reflexivity.\n  Qed.\n\nTheorem ble_nat_refl : forall n:nat,\n  true = ble_nat n n.\nProof.\n  (* 予想: inductionが必要。そのままじゃ簡約できないし、destructしてもそこで詰む。 *)\n  intros n.\n  induction n as [|n'].\n    Case \"n=0\". simpl. reflexivity.\n    Case \"n=Sn'\". simpl. rewrite <- IHn'. reflexivity.\n  Qed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\n  (* 予想: 簡約だけで終わる。 *)\n  reflexivity. Qed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  (* 予想: 簡約のためにはbが邪魔。destructで十分。 *)\n  intros b. destruct b. reflexivity. reflexivity. Qed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n  (* 予想: pについてのinduction。 *)\n  intros n m p. intro H.\n  induction p as [|p'].\n    Case \"p=0\". simpl. rewrite -> H. reflexivity.\n    Case \"p=Sp'\". simpl. rewrite -> IHp'. reflexivity.\n  Qed.\n\nTheorem S_nbeq_0 : forall n:nat,\n  beq_nat (S n) 0 = false.\nProof. (* 予想: reflexivityで終了 *)\n  reflexivity. Qed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof. (* 予想: 簡約だけで終了。 *)\n  intros n.\n  simpl.\n  rewrite -> plus_0_r. (* 残念 rewriteが必要だった。 これは中でinductionしてる。 *)\n  reflexivity.\n  Qed.\n\nTheorem all3_spec : forall b c : bool,\n    orb\n      (andb b c)\n      (orb (negb b)\n           (negb c))\n  = true.\nProof. (* 予想: destructが必要。inductionいらない。 *)\n  intros b c.\n  destruct b.\n    Case \"b=true\". simpl.\n      destruct c. reflexivity. reflexivity.\n    Case \"b=false\". reflexivity.\n  Qed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof. (* 予想: pについてのinduction *)\n  intros n m.\n  intro p.\n  induction p as [|p'].\n    Case \"p=0\". rewrite -> mult_0_r.\n                rewrite -> mult_0_r.\n                rewrite -> mult_0_r. reflexivity.\n    Case \"p=Sp'\". rewrite <- mult_m_Sn.\n                  rewrite <- mult_m_Sn.\n                  rewrite <- mult_m_Sn.\n                  rewrite -> IHp'.\n                  rewrite <- plus_assoc.\n                  rewrite <- plus_assoc.\n                  assert (H: m + (n * p' + m * p') = n * p' + (m + m * p')).\n                         rewrite -> plus_swap. reflexivity.\n                  rewrite -> H.\n                  reflexivity.\n  Qed.\n\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof. (* 予想: nについてのinductionでできる。\n          が、destructと分配則と交換則でいけそうな気もするので試してみる *)\n  intros n m p.\n  induction n as [|n'].\n    Case \"n=0\". reflexivity.\n    Case \"n=Sn'\".\n      simpl. rewrite -> mult_plus_distr_r.\n      (* n' * (m * p) = n' * m * p がでてきてしまったのでやっぱりinduction必要だった *)\n      rewrite -> IHn'. reflexivity.\n  Qed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  replace (n + p) with (p + n).\n  replace (n + (m + p)) with ((m + p) + n).\n  rewrite -> plus_assoc. reflexivity.\n  Case \"proof of replace 1\".\n    rewrite -> plus_comm. reflexivity.\n  Case \"proof of replace 2\".\n    rewrite -> plus_comm. reflexivity.\n  Qed.\n\n\n(* (a) *)\nInductive bin : Type :=\n| B : bin\n| Ev : bin -> bin\n| Od : bin -> bin\n.\n\n(* (b) *)\nFixpoint bin_succ (x : bin) : bin :=\nmatch x with\n| B => Od B\n| Ev x' => Od x'\n| Od x' => Ev (bin_succ x')\nend.\n\nFixpoint nat_from_bin ( x : bin ) : nat :=\nmatch x with\n| B => 0\n| Ev x' => nat_from_bin x' + nat_from_bin x'\n| Od x' => S(nat_from_bin x' + nat_from_bin x')\nend.\n\n(* (c) *)\n\nTheorem binsucc_binnat_compatible: forall x : bin,\n  nat_from_bin(bin_succ(x)) = S(nat_from_bin(x)).\n\nProof.\n  intro x.\n  induction x as [|x'|x'].\n  Case \"x=B\".\n    reflexivity.\n  Case \"x=Ev x'\".\n    simpl. reflexivity.\n  Case \"x=Od x'\".\n    simpl.\n    rewrite -> IHx'. simpl. rewrite -> plus_comm. simpl.\n    reflexivity.\n    Qed.\n\n(* exercise binary_inverse *)\n(* (a) *)\n\nFixpoint bin_from_nat ( n : nat ) : bin :=\nmatch n with\n| O => B\n| S n' => bin_succ (bin_from_nat n')\nend.\n\nTheorem nat_from_bin_from_nat : forall n : nat,\n  nat_from_bin ( bin_from_nat n ) = n.\n\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n=0\". simpl. reflexivity.\n  Case \"n=S n'\".\n    simpl.\n    rewrite -> binsucc_binnat_compatible.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\n(* (b)\n  O に対応する二進表現が複数、というか無限にあるため。\n  B, Ev B, Ev( Ev B ), ...\n  これらはいわゆる leading zero に相当する。\n *)\n\n(* (c) *)\n\nFixpoint normalize ( x : bin ) : bin :=\n  bin_from_nat ( nat_from_bin x ).\n\nTheorem normalize_binsucc : forall x : bin,\n   normalize (bin_succ x) = bin_succ (normalize x).\nProof.\n  intros x.\n  destruct x as [|x'|x'].\n  Case \"x=B\". reflexivity.\n  Case \"x=Ev x'\".\n    simpl. reflexivity.\n  Case \"x=Od x'\".\n    simpl.\n    rewrite -> binsucc_binnat_compatible.\n    replace (S (nat_from_bin x') + S (nat_from_bin x')) with\n      (S(S(nat_from_bin x' + nat_from_bin x'))).\n    SCase \"original goal\".\n      simpl.\n      reflexivity.\n    SCase \"replaced goal\".\n      simpl. rewrite -> plus_n_Sm. reflexivity.\n  Qed.\n\nTheorem normalize_nat : forall n : nat,\n  nat_from_bin( normalize ( bin_from_nat n ) ) = n.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n=0\". reflexivity.\n  Case \"n=Sn'\".\n    simpl.\n    rewrite -> normalize_binsucc.\n    rewrite -> binsucc_binnat_compatible.\n    rewrite -> IHn'.\n    reflexivity.\n  Qed.\n\nFixpoint bin_plus (x y : bin) : bin :=\n  match x with\n  | B => y\n  | Ev x' => match y with\n    | B => x\n    | Ev y' => Ev (bin_plus x' y')\n    | Od y' => Od (bin_plus x' y')\n    end\n  | Od x' => match y with\n    | B => x\n    | Ev y' => Od (bin_plus x' y')\n    | Od y' => Ev (bin_succ (bin_plus x' y'))\n    end\n  end.\n\nLemma binsucc_left_dec : forall x y : bin,\n  bin_succ (bin_plus x y) = bin_plus (bin_succ x) y.\nProof.\n  intros x.\n  induction x as [|x'|x'].\n  Case \"B\". simpl.\n    destruct y as [|y'|y'].\n    reflexivity. reflexivity. reflexivity.\n  Case \"Ev\".\n    simpl.\n    destruct y as [|y'|y'].\n    SCase \"B\". reflexivity.\n    SCase \"Ev\". reflexivity.\n    SCase \"Od\". reflexivity.\n  Case \"Od\". simpl.\n    destruct y as [|y'|y'].\n    SCase \"B\". reflexivity.\n    SCase \"Ev\". simpl.\n      rewrite -> IHx'.\n      reflexivity.\n    SCase \"Od\". simpl.\n      rewrite -> IHx'.\n      reflexivity.\n  Qed.\n\nTheorem nat_from_bin_plus : forall n m : nat,\n  bin_from_nat( n + m ) = bin_plus (bin_from_nat n) (bin_from_nat m).\nProof.\n  intros n m.\n  induction n as [|n'].\n  Case \"0\". reflexivity.\n  Case \"n'\".\n    simpl.\n    rewrite -> IHn'.\n    rewrite -> binsucc_left_dec.\n    reflexivity.\n  Qed.\n\nTheorem plus_nnmm : forall n m : nat,\n  (n + n) + (m + m) = (n + m) + (n + m).\nProof.\n  intros n m.\n  rewrite -> plus_comm.\n  rewrite -> plus_assoc.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  replace (m + n) with (n + m).\n  assert (H: forall p : nat, n + (m + p) = (n + m) + p).\n    intro p. rewrite -> plus_assoc. reflexivity.\n  rewrite -> H. reflexivity.\n  rewrite -> plus_comm. reflexivity.\n  Qed.\n\nTheorem bin_from_nat_plus : forall x y : bin,\n  nat_from_bin (bin_plus x y) = (nat_from_bin x) + (nat_from_bin y).\nProof.\n  intro x.\n  induction x as [|x'|x'].\n  Case \"B\". reflexivity.\n  Case \"Ev\". simpl.\n    destruct y as [|y'|y'].\n    SCase \"B\". simpl. rewrite -> plus_0_r. reflexivity.\n    SCase \"Ev\". simpl. rewrite -> IHx'. rewrite -> plus_nnmm. reflexivity.\n    SCase \"Od\". simpl. rewrite -> IHx'.\n      rewrite <- plus_n_Sm. rewrite -> plus_nnmm. reflexivity.\n  Case \"Od\". simpl.\n    destruct y as [|y'|y'].\n    SCase \"B\". simpl. rewrite -> plus_0_r. reflexivity.\n    SCase \"Ev\". simpl. rewrite -> IHx'. rewrite -> plus_nnmm. reflexivity.\n    SCase \"Od\". simpl. rewrite -> binsucc_binnat_compatible. rewrite -> IHx'.\n      rewrite <- plus_n_Sm.\n      rewrite <- plus_n_Sm.\n      rewrite -> plus_nnmm. reflexivity.\n  Qed.\n\nTheorem bin_plus_right_B : forall x : bin,\n  bin_plus x B = x.\nProof.\n  destruct x as [|x'|x'].\n  Case \"B\". reflexivity.\n  Case \"Ev\". reflexivity.\n  Case \"Od\". reflexivity.\n  Qed.\n\nTheorem normalize_expand : forall x : bin,\n  normalize x = bin_from_nat (nat_from_bin x).\nProof.\n  intro x.\n  destruct x as [|x'|x'].\n  Case \"B\". reflexivity.\n  Case \"Ev\". reflexivity.\n  Case \"Od\". reflexivity.\n  Qed.\n\nTheorem binplus_comm : forall x y : bin,\n  bin_plus x y = bin_plus y x.\nProof.\n  intro x.\n  induction x as [|x'|x'].\n  Case \"B\". simpl.\n    destruct y. reflexivity. reflexivity. reflexivity.\n  Case \"Ev\". simpl.\n    destruct y.\n    SCase \"B\". reflexivity.\n    SCase \"Ev\". simpl. rewrite -> IHx'. reflexivity.\n    SCase \"Od\". simpl. rewrite -> IHx'. reflexivity.\n  Case \"Od\". simpl.\n    destruct y.\n    SCase \"B\". reflexivity.\n    SCase \"Od\". simpl. rewrite -> IHx'. reflexivity.\n    SCase \"Ev\". simpl. rewrite -> IHx'. reflexivity.\n  Qed.\n\nTheorem succ_natbin : forall n : nat,\n  bin_from_nat(S n) = bin_succ(bin_from_nat n).\nProof.\n  intro n.\n  destruct n as [|n'].\n  Case \"O\". reflexivity.\n  Case \"S\". reflexivity.\n  Qed.\n\nTheorem normalize_bin_plus : forall x y : bin,\n  bin_plus (normalize x) (normalize y) = normalize (bin_plus x y).\nProof.\n  intro x.\n  induction x as [|x'|x'].\n  Case \"B\". reflexivity.\n  Case \"Ev\". simpl.\n    destruct y as [|y'|y'].\n    SCase \"B\". simpl.\n      rewrite -> nat_from_bin_plus.\n      rewrite -> bin_plus_right_B.\n      reflexivity.\n    SCase \"Ev\". simpl.\n      rewrite <- nat_from_bin_plus.\n      rewrite -> bin_from_nat_plus.\n      rewrite -> plus_nnmm. reflexivity.\n    SCase \"Od\".\n      simpl.\n      rewrite -> binplus_comm.\n      rewrite <- binsucc_left_dec.\n      assert (H:\n        (bin_plus (bin_from_nat (nat_from_bin y' + nat_from_bin y'))\n                  (bin_from_nat (nat_from_bin x' + nat_from_bin x')))\n      = (bin_from_nat\n          (nat_from_bin (bin_plus x' y') + nat_from_bin (bin_plus x' y')))).\n      SSCase \"H\".\n        rewrite <- nat_from_bin_plus.\n        rewrite -> bin_from_nat_plus.\n        rewrite -> plus_comm.\n        rewrite -> plus_nnmm. reflexivity.\n      SSCase \"original\".\n        rewrite -> H. reflexivity.\n  Case \"Od\".\n    simpl.\n    destruct y as [|y'|y'].\n    SCase \"B\". simpl. rewrite <- binsucc_left_dec.\n      assert (H:\n        (bin_plus (bin_from_nat (nat_from_bin x' + nat_from_bin x')) B)\n      =           (bin_from_nat (nat_from_bin x' + nat_from_bin x'))\n      ).\n      SSCase \"H\".\n        rewrite -> binplus_comm. simpl. reflexivity.\n      SSCase \"original\". rewrite -> H. reflexivity.\n    SCase \"Ev\". simpl. rewrite <- binsucc_left_dec.\n      assert (H:\n        (bin_plus (bin_from_nat (nat_from_bin x' + nat_from_bin x'))\n                  (bin_from_nat (nat_from_bin y' + nat_from_bin y')))\n      =\n        (bin_from_nat\n          ( nat_from_bin (bin_plus x' y')\n          + nat_from_bin (bin_plus x' y')))\n      ).\n      SSCase \"H\".\n        rewrite <- nat_from_bin_plus.\n        rewrite -> bin_from_nat_plus.\n        rewrite -> plus_nnmm. reflexivity.\n      SSCase \"original\". rewrite -> H. reflexivity.\n    SCase \"Od\". simpl.\n      rewrite <- binsucc_left_dec.\n      rewrite -> binplus_comm.\n      rewrite <- binsucc_left_dec.\n      rewrite -> binplus_comm.\n      rewrite -> binsucc_binnat_compatible.\n      rewrite <- plus_n_Sm.\n      rewrite -> succ_natbin.\n      simpl.\n      rewrite <- nat_from_bin_plus.\n      rewrite -> bin_from_nat_plus.\n      rewrite -> plus_nnmm.\n      reflexivity.\n  Qed.\n\nTheorem normalize_fixpoint : forall x : bin,\n  normalize x = normalize(normalize x).\n\nProof.\n  intros x.\n  \n  induction x as [|x'|x'].\n  Case \"x=B\". reflexivity.\n  Case \"x=Ev x'\".\n    simpl.\n    rewrite -> nat_from_bin_plus.\n    replace ( bin_from_nat (nat_from_bin x')) with (normalize x').\n    SCase \"original goal\".\n      rewrite <- normalize_bin_plus.\n      rewrite <- IHx'. reflexivity.\n    SCase \"replaced goal\".\n      destruct x' as [|x''|x''].\n        SSCase \"B\". reflexivity.\n        SSCase \"Ev\".\n          simpl. reflexivity.\n        SSCase \"Od\".\n          simpl. reflexivity.\n  Case \"x=Od x'\".\n    simpl.\n    rewrite -> nat_from_bin_plus.\n    rewrite -> normalize_binsucc.\n    rewrite <- normalize_bin_plus.\n    replace ( bin_from_nat (nat_from_bin x')) with (normalize x').\n    SCase \"original goal\".\n      rewrite <- IHx'. reflexivity.\n    SCase \"replaced goal\".\n      destruct x' as [|x''|x''].\n        reflexivity. reflexivity. reflexivity.\n  Qed.\n\n(* Exercise 'decreasing' *)\n(*\nFixpoint swaprec (n m : nat) : nat :=\nmatch n with\n| 0 => 0\n| S n' => match m with\n  | 0 => 0\n  | S m' => swaprec m' n'\n  end\nend.\n\n  =>  Error: Cannot guess decreasing argument of fix.\n*)\n\nEnd Playground2.", "meta": {"author": "plaster", "repo": "sfja-note", "sha": "a15b6c6ee9a35f03fe53cc5fe1aa496c5254ac04", "save_path": "github-repos/coq/plaster-sfja-note", "path": "github-repos/coq/plaster-sfja-note/sfja-note-a15b6c6ee9a35f03fe53cc5fe1aa496c5254ac04/1/scratch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8824278788223264, "lm_q1q2_score": 0.7482703767736725}}
{"text": "Require Import bool.\nRequire Import nat.\nRequire Import Setoid.\n\nInductive list (a:Type) : Type :=\n    | nil  : list a\n    | cons : a -> list a -> list a\n    .\n\nArguments nil {a}.\nArguments cons {a} _ _.\n\nFixpoint repeat (a:Type) (x:a) (count:nat):list a :=\n    match count with\n    | 0     => nil\n    | S n   => cons x (repeat a x n)\n    end.\n\nArguments repeat {a} _ _.\n\n\nNotation \"x :: xs\" := (cons x xs) (at level 60, right associativity).\nNotation \"[]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..). (* syntax file has bug *)\n\n\nFixpoint app (a:Type) (k l: list a) : list a :=\n    match k with\n    | []        => l\n    | x::xs     => x :: (app a xs l)\n    end.  \n     \nArguments app {a} _ _. (* type argument declared as implicit *)\n\nNotation \"l ++ k\" := (app l k) (at level 60, right associativity). \n\n\nTheorem  app_nil_r : forall (a:Type) (l:list a), l ++ [] = l.\nProof.\n    induction l as [|x xs H].\n    - reflexivity.\n    - simpl. rewrite H. reflexivity.\nQed.\n\n(* not computationally efficient *)\nFixpoint rev (a:Type) (l:list a) : list a :=\n    match l with\n    |   []          => []\n    |   x :: xs     => (rev a xs) ++ [x]\n    end.\n\nArguments rev {a} _.\n\nFixpoint length (a:Type) (l:list a) : nat :=\n    match l with\n    | []        => 0\n    | (_::xs)   => S (length a xs)\n    end.\n        \nArguments length {a} _.\n\n\nTheorem app_assoc : forall (a:Type) (l m n: list a),\n    l ++ m ++ n = (l ++ m) ++ n.\nProof.\n    induction l as [|x xs H].\n    - reflexivity.\n    - simpl. intros m n. rewrite H. reflexivity.\nQed. \n\n\nTheorem app_length : forall (a:Type) (l k: list a),\n    length (l ++ k) = length l + length k.\nProof.\n    induction l as [| x xs H].\n    - reflexivity.\n    - intro k. simpl. rewrite H. reflexivity.\nQed.\n\n\nTheorem rev_app_distr : forall (a:Type) (l k: list a),\n    rev (l ++ k) = rev k ++ rev l.\nProof.\n    induction l as [| x xs H].\n    - intro k. simpl. rewrite app_nil_r. reflexivity.\n    - intro k. simpl. rewrite H. rewrite app_assoc. reflexivity.\nQed.\n\n\nTheorem rev_involutive : forall (a:Type) (l: list a),\n    rev (rev l) = l.\nProof.\n    induction l as [|x xs H].\n    - reflexivity.\n    - simpl. rewrite rev_app_distr. simpl. rewrite H. reflexivity.\nQed.\n\n\n(* we are not using app_length, exercise *)\nTheorem app_length_cons : forall (a:Type) (l k:list a) (x:a) (n:nat),\n    length (l ++ (x :: k)) = n -> S (length (l ++ k)) = n.\nProof.\n    intros a l. induction l as [|y ys H].\n    - intros k x n. simpl. intros H. exact H.\n    - intros k x n. simpl. destruct n.\n        + intros H'. inversion H'.\n        + intros H'. inversion H' as [H1]. clear H'.\n            rewrite H1. apply H in H1. rewrite H1. reflexivity.\nQed.\n\n\n(* we are not using app_length, exercise *)\nTheorem app_length_twice : forall (a:Type) (n:nat) (l:list a),\n    length l = n -> length (l ++ l) = n + n.\nProof.\n    intros a n l. generalize n. clear n. induction l as [|x xs H].\n    - destruct n.\n        + intros. reflexivity.\n        + intros H. inversion H.\n    - destruct n.\n        + intros H'. inversion H'.\n        + intros H'. inversion H' as [H1]. clear H'.\n            simpl. rewrite H1. rewrite (plus_comm n (S n)).\n            simpl. apply H in H1. \n            assert ( S (length (xs ++ xs)) = length (xs ++ x :: xs)) as H'.\n                { apply app_length_cons with (x:=x). reflexivity. }\n            rewrite <- H'. rewrite H1. reflexivity.\nQed.\n\n\nLemma app_cons : forall (a:Type) (l k:list a) (x:a),\n    (x :: l) ++ k = x :: (l ++ k).\nProof. reflexivity. Qed.\n\n\nFixpoint eqb_list (a:Type)(eqb: a -> a -> bool) (l k:list a) : bool :=\n    match l with \n    | []        =>\n        match k with\n        | []        => true\n        | _ :: _    => false\n        end\n    | x :: xs   =>\n        match k with\n        | []        => false\n        | y :: ys   => eqb x y && eqb_list a eqb xs ys\n        end \n    end.\n\nArguments eqb_list {a} _ _ _.\n\nLemma eqb_list_true_iff : forall (a:Type) (eqb: a -> a -> bool),\n    (forall x y, eqb x y = true <-> x = y) ->\n    (forall l k, eqb_list eqb l k = true <-> l = k).\nProof.\n    intros a eqb H. split.\n    - generalize k. clear k. induction l as [|x xs IH].\n        + intros [|y ys].\n            { intros. reflexivity. }\n            { intros H'. inversion H'. }\n        + intros [|y ys].\n            { intros H'. inversion H'. }\n            { intros H'. simpl in H'. rewrite andb_true_iff in H'. \n                destruct H' as [H1 H2]. destruct (H x y) as [H' H''].\n                apply H' in H1. rewrite H1. \n                assert (xs = ys) as E. { apply IH. exact H2. }\n                rewrite E. reflexivity. }\n    - generalize k. clear k. induction l as [|x xs IH].\n        + intros [|y ys].\n            { intros. reflexivity. }\n            { intros H'. inversion H'. }\n        + intros [|y ys].\n            { intros H'. inversion H'. }\n            { intros H'. inversion H'. simpl. apply andb_true_iff. split.\n                { apply H. reflexivity. }\n                { rewrite <- H2. apply IH. reflexivity. } } \nQed.\n\n\nLemma length_0_iff_nil : forall (a:Type) (l:list a),\n    length l = 0 <-> l = nil.\nProof.\n    intros a l. split.\n    - destruct l as [|x xs].\n        + intros. reflexivity.\n        + intros H. inversion H.\n    - intros H. rewrite H. reflexivity.\nQed.\n\nLemma l_not_cons_l : forall (a:Type) (l:list a) (x:a),\n    ~ (l = x :: l).\nProof.\n    intros a l. induction l as [|x xs IH].\n    - intros x H. inversion H.\n    - intros y H. inversion H. apply (IH y). exact H2.\nQed.\n\nLemma l_not_l_app : forall (a:Type) (l:list a) (x:a),\n    ~ (l = l ++ [x]).\nProof.\n    intros a l x H. remember (rev l) as l' eqn:H'.\n    assert (l' = x :: l') as H0.\n    { rewrite H'. rewrite H at 1. rewrite rev_app_distr. reflexivity. }\n    revert H0. apply l_not_cons_l.\nQed.\n\nLemma list_3_cases : forall (a:Type) (l:list a), \n    l = []                              \\/\n    (exists x, l = [x])                 \\/\n    (exists x y k, l = x :: k ++ [y])   .\nProof.\n    intros a l. induction l as [|x xs [IH|[[y IH]|[x' [y [k IH]]]]]].\n    - left. reflexivity.\n    - right. left. exists x. rewrite IH. reflexivity.\n    - right. right. exists x, y, []. rewrite IH. reflexivity.\n    - right. right. exists x, y, (x' :: k). rewrite IH. \n        rewrite app_cons. reflexivity.\nQed.\n\nLemma app_cons' : forall (a:Type) (l k:list a) (x:a),\n    l ++ x :: k = (l ++ [x]) ++ k.\nProof.\n    intros a l. induction l as [|x xs IH].\n    - intros k x. reflexivity.\n    - intros k y. rewrite app_cons, app_cons, app_cons.\n        rewrite <- (IH k y). reflexivity.\nQed.\n\nLemma app_injective_l : forall (a:Type) (l k m:list a),\n    k ++ l = m ++ l -> k = m.\nProof.\n    intros a l. induction l as [|x xs IH].\n    - intros k m H. rewrite app_nil_r in H. rewrite app_nil_r in H. exact H.\n    - intros k m H.\n      rewrite (app_cons' a k xs x) in H. \n      rewrite (app_cons' a m xs x) in H. \n      apply IH in H.\n      assert (rev (k ++ [x])  = rev (m ++ [x])) as H'.\n      { rewrite H. reflexivity. }\n      rewrite rev_app_distr in H'.\n      rewrite rev_app_distr in H'.\n      simpl in H'. inversion H' as [H0].\n      rewrite <- (rev_involutive a k).\n      rewrite <- (rev_involutive a m).\n      rewrite H0. reflexivity.\nQed.\n\nLemma app_injective_r : forall (a:Type) (l k m:list a),\n    l ++ k = l ++ m -> k = m.\nProof.\n    intros a l. induction l as [|x xs IH].\n    - intros k m H. exact H.\n    - intros k m H. rewrite app_cons in H. rewrite app_cons in H.\n        inversion H as [H']. apply IH. exact H'.\nQed.\n\n\nLemma rev_list_3_cases : forall (a:Type) (l:list a), l = rev l -> \n    l = []                                          \\/ \n    (exists x, l = [x])                             \\/\n    (exists x k, l = x :: k ++ [x] /\\ k = rev k)    .\nProof.\n    intros a l H. \n    assert (l = [] \\/ (exists x,l = [x]) \\/ \n        (exists x y k, l = x :: k ++ [y])) as [H'|[[x H']|[x [y [k H']]]]]. \n        { apply list_3_cases. }\n    - left. exact H'.\n    - right. left. exists x. exact H'.\n    - right. right. exists x, k.\n        rewrite H' in H at 2. simpl in H. rewrite rev_app_distr in H.\n        simpl in H. rewrite H' in H. inversion H as [H0]. split.\n        + rewrite H', H0. reflexivity.\n        + apply app_injective_l with (l:=[y]). exact H1. \nQed.\n        \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/sf/list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7482703738353119}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype.\nRequire Import BinNat.\nRequire BinPos Ndec.\nRequire Export Ring.\n\n(****************************************************************************)\n(* A version of arithmetic on nat (natural numbers) that is better suited   *)\n(* to small scale reflection than the Coq Arith library. It contains  an    *)\n(* extensive equational theory (including, e.g., the AGM inequality), as    *)\n(* well as support for the ring tactic, and congruence  tactics.            *)\n(*   The following operations and notations are provided:                   *)\n(*                                                                          *)\n(*   successor and predecessor                                              *)\n(*     n.+1, n.+2, n.+3, n.+4 and n.-1, n.-2                                *)\n(*     this frees the names \"S\" and \"pred\"                                  *)\n(*                                                                          *)\n(*   basic arithmetic                                                       *)\n(*     m + n, m - n, m * n                                                  *)\n(*   the definitions use the nosimpl tag to prevent undesirable computation *)\n(*   computation during simplification, but remain compatible with the ones *)\n(*   provided in the Coq.Init.Peano prelude.                                *)\n(*     For computation, a module NatTrec rebinds all arithmetic notations   *)\n(*   to less convenient but also less inefficient tail-recursive functions; *)\n(*   the auxiliary functions used by these versions are flagged with %Nrec. *)\n(*     Also, there is support for input and output of large nat values.     *)\n(*       Num 3 082 241 inputs the number 3082241                            *)\n(*         [Num of n]  outputs the value n                                  *)\n(*   There are coercions num >-> BinNat.N >-> nat; ssrnat rebinds the scope *)\n(*   delimter for BinNat.N to %num, as it uses the shorter %N for its own   *)\n(*   notations (Peano notations are flagged with %coq_nat).                 *)\n(*                                                                          *)\n(*   doubling, halving, and parity                                          *)\n(*      n.*2, n./2, odd n                                                   *)\n(*    bool coerces to nat so we can write, e.g., n = odd n + n./2.*2.       *)\n(*                                                                          *)\n(*   iteration                                                              *)\n(*             iter n f x0  == f ( .. (f x0))                               *)\n(*             iteri n g x0 == g n.-1 (g ... (g 0 x0))                      *)\n(*         iterop n op x x0 == op x (... op x x) (n x's) or x0 if n = 0     *)\n(*                                                                          *)\n(*   exponentiation, factorial                                              *)\n(*        m ^ n, n`!                                                        *)\n(*        m ^ 1 is convertible to m, and m ^ 2 to m * m                     *)\n(*                                                                          *)\n(*   comparison                                                             *)\n(*      m <= n, m < n, m >= n, m > n, m == n, m <= n <= p, etc.,            *)\n(*   comparisons are BOOLEAN operators, and m == n is the generic eqType    *)\n(*   operation.                                                             *)\n(*     Most compatibility lemmas are stated as boolean equalities; this     *)\n(*   keeps the size of the library down. All the inequalities refer to the  *)\n(*   same constant \"leq\"; in particular m < n is identical to m.+1 <= n.    *)\n(*                                                                          *)\n(*   conditionally strict inequality \"leqif\"                                *)\n(*      m <= n ?= iff condition   ==   (m <= n) and ((m == n) = condition)  *)\n(*   This is actually a pair of boolean equalities, so rewriting with an    *)\n(*   \"leqif\" lemma can affect several kinds of comparison. The transitivity *)\n(*   lemma for leqif aggregates the conditions, allowing for arguments of   *)\n(*   the form \"m <= n <= p <= m, so equality holds throughout\".             *)\n(*                                                                          *)\n(*   maximum and minimum                                                    *)\n(*     maxn m n, minn m n                                                   *)\n(*   Note that maxn m n = m + (m - n) (truncating subtraction).             *)\n(*                                                                          *)\n(*   countable choice                                                       *)\n(*     ex_minn : forall P : pred nat, (exists n, P n) -> nat                *)\n(*       This returns the smallest n such that P n holds.                   *)\n(*     ex_maxn : forall (P : pred nat) m,                                   *)\n(*        (exists n, P n) -> (forall n, P n -> n <= m) -> nat               *)\n(*       This returns the largest n such that P n holds (given an explicit  *)\n(*       upper bound).                                                      *)\n(*                                                                          *)\n(****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Declare legacy Arith operators in new scope. *)\n\nDelimit Scope coq_nat_scope with coq_nat.\n\nNotation \"m + n\" := (plus m n) : coq_nat_scope.\nNotation \"m - n\" := (minus m n) : coq_nat_scope.\nNotation \"m * n\" := (mult m n) : coq_nat_scope.\nNotation \"m <= n\" := (le m n) : coq_nat_scope.\nNotation \"m < n\" := (lt m n) : coq_nat_scope.\nNotation \"m >= n\" := (ge m n) : coq_nat_scope.\nNotation \"m > n\" := (gt m n) : coq_nat_scope.\n\n(* Rebind scope delimiters, reserving a scope for the \"recursive\",     *)\n(* i.e., unprotected version of operators.                             *)\n\nDelimit Scope N_scope with num.\nDelimit Scope nat_scope with N.\nDelimit Scope nat_rec_scope with Nrec.\n\n(* Postfix notation for the successor and predecessor functions.  *)\n(* SSreflect uses \"pred\" for the generic predicate type, and S as *)\n(* a local bound variable.                                        *)\n\nNotation succn := Datatypes.S (only parsing).\n\nNotation \"n .+1\" := (succn n) (at level 2, left associativity,\n  format \"n .+1\") : nat_scope.\nNotation \"n .+2\" := n.+1.+1 (at level 2, left associativity,\n  format \"n .+2\") : nat_scope.\nNotation \"n .+3\" := n.+2.+1 (at level 2, left associativity,\n  format \"n .+3\") : nat_scope.\nNotation \"n .+4\" := n.+2.+2 (at level 2, left associativity,\n  format \"n .+4\") : nat_scope.\n\n(* We provide a structurally decreasing predecessor function. *)\n\nDefinition predn n := if n is n'.+1 then n' else n.\n\nNotation \"n .-1\" := (predn n) (at level 2, left associativity,\n  format \"n .-1\") : nat_scope.\nNotation \"n .-2\" := n.-1.-1 (at level 2, left associativity,\n  format \"n .-2\") : nat_scope.\n\nLemma predE : Peano.pred =1 predn. Proof. by case. Qed.\nLemma succnK : cancel succn predn. Proof. by []. Qed.\nLemma succn_inj : injective succn. Proof. by move=> n m []. Qed.\n\n(* Predeclare postfix doubling/halving operators. *)\n\nReserved Notation \"n .*2\" (at level 2, format \"n .*2\").\nReserved Notation \"n ./2\" (at level 2, format \"n ./2\").\n\n(* Patch for ssreflect match pattern bug -- see ssrbool.v. *)\n\nDefinition ifn_expr T n x y : T := if n is n'.+1 then x n' else y.\n\nLemma ifnE : forall T x y n,\n  (if n is n'.+1 then x n' else y) = ifn_expr n x y :> T.\nProof. by []. Qed.\n\n\n(* Canonical comparison and eqType for nat.                                *)\n\nFixpoint eqn (m n : nat) {struct m} : bool :=\n  match m, n with\n  | 0, 0 => true\n  | m'.+1, n'.+1 => eqn m' n'\n  | _, _ => false\n  end.\n\nLemma eqnP : Equality.axiom eqn.\nProof.\nmove=> n m; apply: (iffP idP) => [|<-]; last by elim n.\nby elim: n m => [|n IHn] [|m] //=; move/IHn->.\nQed.\n\nCanonical Structure nat_eqMixin := EqMixin eqnP.\nCanonical Structure nat_eqType := Eval hnf in EqType nat nat_eqMixin.\n\nImplicit Arguments eqnP [x y].\nPrenex Implicits eqnP.\n\nLemma eqnE : eqn = eq_op. Proof. by []. Qed.\n\nLemma eqSS : forall m n, (m.+1 == n.+1) = (m == n). Proof. by []. Qed.\n\nLemma nat_irrelevance : forall (x y : nat) (E E' : x = y), E = E'.\nProof. exact: eq_irrelevance. Qed.\n\n(* Protected addition, with a more systematic set of lemmas.                *)\n\nDefinition addn_rec := plus.\nNotation \"m + n\" := (addn_rec m n) : nat_rec_scope.\n\nDefinition addn := nosimpl addn_rec.\nNotation \"m + n\" := (addn m n) : nat_scope.\n\nLemma addnE : addn = addn_rec. Proof. by []. Qed.\n\nLemma plusE : plus = addn. Proof. by []. Qed.\n\nLemma add0n : left_id 0 addn.                  Proof. by []. Qed.\nLemma addSn : forall m n, m.+1 + n = (m + n).+1. Proof. by []. Qed.\nLemma add1n : forall n, 1 + n = n.+1.            Proof. by []. Qed.\n\nLemma addn0 : right_id 0 addn. Proof. by move=> n; apply/eqP; elim: n. Qed.\n\nLemma addnS : forall m n, m + n.+1 = (m + n).+1.\nProof. by move=> m n; elim: m. Qed.\n\nLemma addSnnS : forall m n, m.+1 + n = m + n.+1.\nProof. by move=> *; rewrite addnS. Qed.\n\nLemma addnCA : left_commutative addn.\nProof. by move=> m n p; elim: m => //= m; rewrite addnS => <-. Qed.\n\nLemma addnC : commutative addn.\nProof. by move=> m n; rewrite -{1}[n]addn0 addnCA addn0. Qed.\n\nLemma addn1 : forall n, n + 1 = n.+1.\nProof. by move=> n; rewrite addnC. Qed.\n\nLemma addnA : associative addn.\nProof. by move=> m n *; rewrite (addnC n) addnCA addnC. Qed.\n\nLemma addnAC : right_commutative addn.\nProof. by move=> m n p; rewrite -!addnA (addnC n). Qed.\n\nLemma addn_eq0 : forall m n, (m + n == 0) = (m == 0) && (n == 0).\nProof. by do 2 case. Qed.\n\nLemma eqn_addl : forall p m n, (p + m == p + n) = (m == n).\nProof. by move=> p *; elim p. Qed.\n\nLemma eqn_addr : forall p m n, (m + p == n + p) = (m == n).\nProof. by move=> p *; rewrite -!(addnC p) eqn_addl. Qed.\n\nLemma addnI : right_injective addn.\nProof. by move=> p m n Heq; apply: eqP; rewrite -(eqn_addl p) Heq eqxx. Qed.\n\nLemma addIn : left_injective addn.\nProof. move=> p m n; rewrite -!(addnC p); apply addnI. Qed.\n\nLemma addn2 : forall m, m + 2 = m.+2. Proof. by move=> *; rewrite addnC. Qed.\nLemma add2n : forall m, 2 + m = m.+2. Proof. by []. Qed.\nLemma addn3 : forall m, m + 3 = m.+3. Proof. by move=> *; rewrite addnC. Qed.\nLemma add3n : forall m, 3 + m = m.+3. Proof. by []. Qed.\nLemma addn4 : forall m, m + 4 = m.+4. Proof. by move=> *; rewrite addnC. Qed.\nLemma add4n : forall m, 4 + m = m.+4. Proof. by []. Qed.\n\n(* Protected, structurally decreasing substraction, and basic lemmas. *)\n(* Further properties depend on ordering conditions.                  *)\n\nFixpoint subn_rec (m n : nat) {struct m} :=\n  match m, n with\n  | m'.+1, n'.+1 => (m' - n')%Nrec\n  | _, _ => m\n  end\nwhere \"m - n\" := (subn_rec m n) : nat_rec_scope.\n\nDefinition subn := nosimpl subn_rec.\nNotation \"m - n\" := (subn m n) : nat_scope.\n\nLemma subnE : subn = subn_rec. Proof. by []. Qed.\nLemma minusE : minus =2 subn.\nProof. elim=> [|m IHm] [|n] //=; exact: IHm. Qed.\n\nLemma sub0n : left_zero 0 subn.    Proof. by []. Qed.\nLemma subn0 : right_id 0 subn.   Proof. by case. Qed.\nLemma subnn : self_inverse 0 subn. Proof. by elim. Qed.\n\nLemma subSS : forall n m, m.+1 - n.+1 = m - n. Proof. by []. Qed.\nLemma subn1 : forall n, n - 1 = n.-1.          Proof. by do 2?case. Qed.\n\nLemma subn_add2l : forall p m n, (p + m) - (p + n) = m - n.\nProof. by move=> p *; elim p. Qed.\n\nLemma subn_add2r : forall p m n, (m + p) - (n + p) = m - n.\nProof. by move=> p *; rewrite -!(addnC p) subn_add2l. Qed.\n\nLemma addKn : forall n, cancel (addn n) (subn^~ n).\nProof. by move=> n m; rewrite -{2}[n]addn0 subn_add2l subn0. Qed.\n\nLemma addnK : forall n, cancel (addn^~ n) (subn^~ n).\nProof. by move=> n m; rewrite (addnC m) addKn. Qed.\n\nLemma subSnn : forall n, n.+1 - n = 1.\nProof. move=> n; exact (addnK n 1). Qed.\n\nLemma subn_sub : forall m n p, (n - m) - p = n - (m + p).\nProof. by move=> m n p; elim: m n => [|m IHm] [|n]; try exact (IHm n). Qed.\n\nLemma subnAC : right_commutative subn.\nProof. by move=> m n p; rewrite !subn_sub addnC. Qed.\n\nLemma predn_sub : forall m n, (m - n).-1 = m - n.+1.\nProof. by move=> m n; rewrite -subn1 subn_sub addn1. Qed.\n\nLemma predn_subS : forall m n, (m.+1 - n).-1 = m - n.\nProof. by move=> m n; rewrite predn_sub. Qed.\n\n(* Integer ordering, and its interaction with the other operations.       *)\n\nDefinition leq m n := m - n == 0.\n\nNotation \"m <= n\" := (leq m n) : nat_scope.\nNotation \"m < n\"  := (m.+1 <= n) : nat_scope.\nNotation \"m >= n\" := (n <= m) (only parsing) : nat_scope.\nNotation \"m > n\"  := (n < m) (only parsing)  : nat_scope.\n\n(* For sorting, etc. *)\nDefinition geq := [rel m n | m >= n].\nDefinition ltn := [rel m n | m < n].\nDefinition gtn := [rel m n | m > n].\n\nNotation \"m <= n <= p\" := ((m <= n) && (n <= p)) : nat_scope.\nNotation \"m < n <= p\" := ((m < n) && (n <= p)) : nat_scope.\nNotation \"m <= n < p\" := ((m <= n) && (n < p)) : nat_scope.\nNotation \"m < n < p\" := ((m < n) && (n < p)) : nat_scope.\n\nLemma ltnS : forall m n, (m < n.+1) = (m <= n).\nProof. by []. Qed.\n\nLemma leq0n : forall n, 0 <= n.\nProof. by []. Qed.\n\nLemma ltn0Sn : forall n, 0 < n.+1.\nProof. by []. Qed.\n\nLemma ltn0 : forall n, n < 0 = false.\nProof. by []. Qed.\n\nLemma leqnn : forall n, n <= n.\nProof. by elim. Qed.\nHint Resolve leqnn.\n\nLemma ltnSn : forall n, n < n.+1.\nProof. by []. Qed.\n\nLemma eq_leq : forall m n, m = n -> m <= n.\nProof. by move=> m n <-. Qed.\n\nLemma leqnSn : forall n, n <= n.+1.\nProof. by elim. Qed.\nHint Resolve leqnSn.\n\nLemma leq_pred : forall n, n.-1 <= n.\nProof. by case=> /=. Qed.\n\nLemma leqSpred : forall n, n <= n.-1.+1.\nProof. by case=> /=. Qed.\n\nLemma ltn_predK : forall m n, m < n -> n.-1.+1 = n.\nProof. by move=> ? []. Qed.\n\nLemma prednK : forall n, 0 < n -> n.-1.+1 = n.\nProof. by case. Qed.\n\nLemma leqNgt : forall m n, (m <= n) = ~~ (n < m).\nProof. by elim=> [|m IHm] [|n] //; rewrite ltnS IHm. Qed.\n\nLemma ltnNge : forall m n, (m < n) = ~~ (n <= m).\nProof. by move=> *; rewrite leqNgt. Qed.\n\nLemma ltnn : forall n, n < n = false.\nProof. by move=> *; rewrite ltnNge leqnn. Qed.\n\nLemma leqn0 : forall n, (n <= 0) = (n == 0).\nProof. by case. Qed.\n\nLemma lt0n : forall n, (0 < n) = (n != 0).\nProof. by case. Qed.\n\nLemma lt0n_neq0 : forall n, 0 < n -> n != 0.\nProof. by case. Qed.\n\nLemma eqn0Ngt : forall n, (n == 0) = ~~ (n > 0).\nProof. by case. Qed.\n\nLemma neq0_lt0n : forall n, (n == 0) = false -> 0 < n.\nProof. by case. Qed.\nHint Resolve lt0n_neq0 neq0_lt0n.\n\nLemma eqn_leq : forall m n, (m == n) = (m <= n <= m).\nProof. elim=> [|m IHm] [|n] //; exact: IHm n. Qed.\n\nLemma anti_leq : antisymmetric leq.\nProof. by move=> m n; rewrite -eqn_leq; move/eqP. Qed.\n\nLemma neq_ltn : forall m n, (m != n) = (m < n) || (n < m).\nProof. by move=> *; rewrite eqn_leq negb_and orbC -!ltnNge. Qed.\n\nLemma leq_eqVlt : forall m n, (m <= n) = (m == n) || (m < n).\nProof. elim=> [|m IHm] [|n] //; exact: IHm n. Qed.\n\nLemma ltn_neqAle : forall m n, (m < n) = (m != n) && (m <= n).\nProof. elim=> [|m IHm] [|n] //; exact: IHm n. Qed.\n\nLemma leq_trans : forall n m p, m <= n -> n <= p -> m <= p.\nProof. by elim=> [|i IHn] [|m] [|p] //; exact: IHn m p. Qed.\n\nLemma leq_ltn_trans : forall n m p, m <= n -> n < p -> m < p.\nProof. move=> n m p Hmn; exact: leq_trans. Qed.\n\nLemma ltnW : forall m n, m < n -> m <= n.\nProof. move=> m n; exact: leq_trans. Qed.\nHint Resolve ltnW.\n\nLemma leqW : forall m n, m <= n -> m <= n.+1.\nProof. move=> *; exact: ltnW. Qed.\n\nLemma ltn_trans : forall n m p, m < n -> n < p -> m < p.\nProof. move=> n m p Hmn; move/ltnW; exact: leq_trans. Qed.\n\nLemma leq_total : forall m n, (m <= n) || (m >= n).\nProof. by move=> m n; rewrite leq_eqVlt orbC orbCA ltnNge orbN orbT. Qed.\n\n(* Link to the legacy comparison predicates. *)\n\nLemma leP : forall m n, reflect (m <= n)%coq_nat (m <= n).\nProof.\nmove=> m n; apply: (iffP idP); last by elim: n / => // n _; move/leq_trans->.\nelim: n => [|n IHn]; first by case m.\nby rewrite leq_eqVlt ltnS; case/predU1P=> [<- //|]; move/IHn; right.\nQed.\n\nImplicit Arguments leP [m n].\nPrenex Implicits leP.\n\nLemma le_irrelevance : forall m n lemn1 lemn2,\n  lemn1 = lemn2 :> (m <= n)%coq_nat.\nProof.\nmove=> m n; elim: {n}n.+1 {-1}n (erefl n.+1) => // n IHn _ [<-] lemn1 lemn2.\npose def_n2 := erefl n; transitivity (eq_ind _ _ lemn2 _ def_n2) => //.\nmove def_n1: {1 4 5 7}n lemn1 lemn2 def_n2 => n1 lemn1.\ncase: n1 / lemn1 def_n1 => [|n1 lemn1] def_n1 [|n2 lemn2] def_n2.\n- by rewrite [def_n2]eq_axiomK.\n- by move/leP: (lemn2); rewrite -{1}def_n2 ltnn.\n- by move/leP: (lemn1); rewrite {1}def_n2 ltnn.\ncase: def_n2 (def_n2) lemn2 => ->{n2} def_n2 lemn2.\nrewrite [def_n2]eq_axiomK /=; congr le_S; exact: IHn.\nQed.\n\nLemma ltP : forall m n, reflect (m < n)%coq_nat (m < n).\nProof. move=> *; exact leP. Qed.\n\nImplicit Arguments ltP [m n].\nPrenex Implicits ltP.\n\nLemma lt_irrelevance : forall m n ltmn1 ltmn2,\n  ltmn1 = ltmn2 :> (m < n)%coq_nat.\nProof. move=> m; exact: le_irrelevance m.+1. Qed.\n\n(* Comparison predicates. *)\n\nCoInductive leq_xor_gtn (m n : nat) : bool -> bool -> Set :=\n  | LeqNotGtn of m <= n : leq_xor_gtn m n true false\n  | GtnNotLeq of n < m  : leq_xor_gtn m n false true.\n\nLemma leqP : forall m n, leq_xor_gtn m n (m <= n) (n < m).\nProof.\nmove=> m n; rewrite ltnNge; case Hmn: (m <= n); constructor; auto.\nby rewrite ltnNge Hmn.\nQed.\n\nCoInductive ltn_xor_geq (m n : nat) : bool -> bool -> Set :=\n  | LtnNotGeq of m < n  : ltn_xor_geq m n false true\n  | GeqNotLtn of n <= m : ltn_xor_geq m n true false.\n\nLemma ltnP : forall m n, ltn_xor_geq m n (n <= m) (m < n).\nProof. by move=> m n; rewrite -(ltnS n); case (leqP m.+1 n); constructor. Qed.\n\nCoInductive eqn0_xor_gt0 (n : nat) : bool -> bool -> Set :=\n  | Eq0NotPos of n = 0 : eqn0_xor_gt0 n true false\n  | PosNotEq0 of n > 0 : eqn0_xor_gt0 n false true.\n\nLemma posnP : forall n, eqn0_xor_gt0 n (n == 0) (0 < n).\nProof. by case; constructor. Qed.\n\nCoInductive compare_nat (m n : nat) : bool -> bool -> bool -> Set :=\n  | CompareNatLt of m < n : compare_nat m n true false false\n  | CompareNatGt of m > n : compare_nat m n false true false\n  | CompareNatEq of m = n : compare_nat m n false false true.\n\nLemma ltngtP : forall m n, compare_nat m n (m < n) (n < m) (m == n).\nProof.\nmove=> m n; rewrite ltn_neqAle eqn_leq; case: ltnP; first by constructor.\nby rewrite leq_eqVlt orbC; case: leqP => Hm; first move/eqnP; constructor.\nQed.\n\n(* Monotonicity lemmas *)\n\nDefinition monotone f := forall m n, (f m <= f n) = (m <= n).\n\nLemma leq_add2l : forall p m n, (p + m <= p + n) = (m <= n).\nProof. by move=> p *; elim p. Qed.\n\nLemma ltn_add2l : forall p m n, (p + m < p + n) = (m < n).\nProof. move=> *; rewrite -addnS; exact: leq_add2l. Qed.\n\nLemma leq_add2r : forall p m n, (m + p <= n + p) = (m <= n).\nProof. move=> p *; rewrite -!(addnC p); apply leq_add2l. Qed.\n\nLemma ltn_add2r : forall p m n, (m + p < n + p) = (m < n).\nProof. move=> *; exact: leq_add2r _.+1 _. Qed.\n\nLemma leq_add : forall m1 m2 n1 n2,\n  m1 <= n1 -> m2 <= n2 -> m1 + m2 <= n1 + n2.\nProof.\nmove=> m1 m2 n1 n2 Hm Hn.\nby apply (@leq_trans (m1 + n2)); rewrite ?leq_add2l ?leq_add2r.\nQed.\n\nLemma leq_addr : forall m n, n <= n + m.\nProof. by move=> m n; rewrite -{1}[n]addn0 leq_add2l. Qed.\n\nLemma leq_addl : forall m n, n <= m + n.\nProof. move=> *; rewrite addnC; apply leq_addr. Qed.\n\nLemma ltn_addr : forall m n p, m < n -> m < n + p.\nProof. move=> m n p; move/leq_trans=> -> //; exact: leq_addr. Qed.\n\nLemma ltn_addl : forall m n p, m < n -> m < p + n.\nProof. move=> m n p; move/leq_trans=> -> //; exact: leq_addl. Qed.\n\nLemma addn_gt0 : forall m n, (0 < m + n) = (0 < m) || (0 < n).\nProof. by move=> m n; rewrite !lt0n -negb_andb addn_eq0. Qed.\n\nLemma subn_gt0 : forall m n, (0 < n - m) = (m < n).\nProof. elim=> [|m IHm] [|n] //; exact: IHm n. Qed.\n\nLemma subn_eq0 : forall m n, (m - n == 0) = (m <= n).\nProof. by []. Qed.\n\nLemma leq_sub_add : forall m n p, (m - n <= p) = (m <= n + p).\nProof. by move=> *; rewrite /leq subn_sub. Qed.\n\nLemma leq_subr : forall m n, n - m <= n.\nProof. by move=> *; rewrite leq_sub_add leq_addl. Qed.\n\nLemma subnKC : forall m n, m <= n -> m + (n - m) = n.\nProof. by elim=> [|m IHm] [|n] // Hmn; congr _.+1; apply: IHm. Qed.\n\nLemma subnK : forall m n, m <= n -> (n - m) + m = n.\nProof. by move=> m n; rewrite addnC; exact: subnKC. Qed.\n\nLemma addn_subA : forall m n p, p <= n -> m + (n - p) = m + n - p.\nProof. by move=> m n p le_pn; rewrite -{2}(subnK le_pn) addnA addnK. Qed.\n\nLemma subn_subA : forall m n p, p <= n -> m - (n - p) = m + p - n.\nProof. by move=> m n p le_pn; rewrite -{2}(subnK le_pn) subn_add2r. Qed.\n\nLemma subKn : forall m n, m <= n -> n - (n - m) = m.\nProof. by move=> *; rewrite subn_subA // addKn. Qed.\n\nLemma leq_subS : forall m n, m <= n -> n.+1 - m = (n - m).+1.\nProof. by move => *; rewrite -add1n -addn_subA. Qed.\n\nLemma ltn_subS : forall m n, m < n -> n - m = (n - m.+1).+1.\nProof. move=> m; exact: leq_subS m.+1. Qed.\n\nLemma leq_sub2r : forall p m n, m <= n -> m - p <= n - p.\nProof.\nmove=> p m n Hmn; rewrite leq_sub_add; apply: (leq_trans Hmn).\nby rewrite -leq_sub_add leqnn.\nQed.\n\nLemma leq_sub2l : forall p m n, m <= n -> p - n <= p - m.\nProof.\nmove=> p m n; rewrite -(leq_add2r (p - m)) leq_sub_add.\nby apply: leq_trans; rewrite -leq_sub_add leqnn.\nQed.\n\nLemma leq_sub2 :  forall m1 m2 n1 n2,\n  m1 <= m2 -> n2 <= n1 -> m1 - n1 <= m2 - n2.\nProof.\nmove=> m1 m2 n1 n2 Hm Hn; exact: leq_trans (leq_sub2l _ Hn) (leq_sub2r _ Hm).\nQed.\n\nLemma ltn_sub2r : forall p m n, p < n -> m < n -> m - p < n - p.\nProof. move=> p m n; move/ltn_subS->; exact: (@leq_sub2r p.+1). Qed.\n\nLemma ltn_sub2l : forall p m n, m < p -> m < n -> p - n < p - m.\nProof. move=> p m n; move/ltn_subS->; exact: leq_sub2l. Qed.\n\nLemma ltn_add_sub : forall m n p, (m + n < p) = (n < p - m).\nProof. by move=> m n p; rewrite !ltnNge leq_sub_add. Qed.\n\n(* Eliminating the idiom for structurally decreasing compare and subtract. *)\nLemma subn_if_gt : forall T m n F (E : T),\n  (if m.+1 - n is m'.+1 then F m' else E) = (if n <= m then F (m - n) else E).\nProof.\nmove=> m n F E; case: leqP => [le_nm |]; last by move/eqnP->.\nby rewrite -{1}(subnK le_nm) -addSn addnK.\nQed.\n\n(* Max and min *)\n\nDefinition maxn m n := if m < n then n else m.\n\nDefinition minn m n := if m < n then m else n.\n\nLemma max0n : left_id 0 maxn.  Proof. by case. Qed.\nLemma maxn0 : right_id 0 maxn. Proof. by []. Qed.\n\nLemma maxnC : commutative maxn.\nProof. by move=> m n; rewrite /maxn; case ltngtP. Qed.\n\nLemma maxnl : forall m n, m >= n -> maxn m n = m.\nProof. by rewrite /maxn => m n; case leqP. Qed.\n\nLemma maxnr : forall m n, m <= n -> maxn m n = n.\nProof. by move=> m n le_mn; rewrite maxnC maxnl. Qed.\n\nLemma add_sub_maxn : forall m n, m + (n - m) = maxn m n.\nProof.\nmove=> m n; rewrite /maxn; case: leqP; last by move/ltnW; move/subnKC.\nby move/eqnP->; rewrite addn0.\nQed.\n\nLemma maxnAC : right_commutative maxn.\nProof.\nby move=> *; rewrite -!add_sub_maxn -!addnA -!subn_sub !add_sub_maxn maxnC.\nQed.\n\nLemma maxnA : associative maxn.\nProof. by move=> m n p; rewrite !(maxnC m) maxnAC. Qed.\n\nLemma maxnCA : left_commutative maxn.\nProof. by move=> m n p; rewrite !maxnA (maxnC m). Qed.\n\nLemma eqn_maxr : forall m n, (maxn m n == n) = (m <= n).\nProof. by move=> m n; rewrite maxnC -{2}[n]addn0 -add_sub_maxn eqn_addl. Qed.\n\nLemma eqn_maxl : forall m n, (maxn m n == m) = (m >= n).\nProof. by move=> m n; rewrite -{2}[m]addn0 -add_sub_maxn eqn_addl. Qed.\n\nLemma maxnn : idempotent maxn.\nProof. by move=> n; apply/eqP; rewrite eqn_maxl. Qed.\n\nLemma leq_maxr : forall m n1 n2, (m <= maxn n1 n2) = (m <= n1) || (m <= n2).\nProof.\nmove=> m n1 n2; wlog le_n21: n1 n2 / n2 <= n1.\n  by case/orP: (leq_total n2 n1) => ?; last rewrite maxnC orbC; auto.\nrewrite /maxn ltnNge le_n21 /=; case: leqP => // lt_m_n1.\nby rewrite leqNgt (leq_trans _ lt_m_n1).\nQed.\n\nLemma leq_maxl : forall m n1 n2, (maxn n1 n2 <= m) = (n1 <= m) && (n2 <= m).\nProof. by move=> m n1 n2; rewrite leqNgt leq_maxr negb_or -!leqNgt. Qed.\n\nLemma addn_maxl : left_distributive addn maxn.\nProof. by move=> m1 m2 n; rewrite -!add_sub_maxn subn_add2r addnAC. Qed.\n\nLemma addn_maxr : right_distributive addn maxn.\nProof. by move=> m n1 n2; rewrite !(addnC m) addn_maxl. Qed.\n\nLemma min0n : left_zero 0 minn. Proof. by case. Qed.\nLemma minn0 : right_zero 0 minn. Proof. by []. Qed.\n\nLemma minnC : commutative minn.\nProof. by move=> m n; rewrite /minn; case ltngtP. Qed.\n\nLemma minnr : forall m n, m >= n -> minn m n = n.\nProof. by rewrite /minn => m n; case leqP. Qed.\n\nLemma minnl : forall m n, m <= n -> minn m n = m.\nProof. by move=> m n le_mn; rewrite minnC minnr. Qed.\n\nLemma addn_min_max : forall m n, minn m n + maxn m n = m + n.\nProof.\nrewrite /minn /maxn => m n; case: ltngtP => // [_|->] //; exact: addnC.\nQed.\n\nRemark minn_to_maxn : forall m n, minn m n = m + n - maxn m n.\nProof. by move=> *; rewrite -addn_min_max addnK. Qed.\n\nLemma sub_sub_minn : forall m n, m - (m - n) = minn m n.\nProof.\nby move=> m n; rewrite minnC minn_to_maxn -add_sub_maxn subn_add2l.\nQed.\n\nLemma minnCA : left_commutative minn.\nProof.\nmove=> m1 m2 m3; rewrite !(minn_to_maxn _ (minn _ _)).\nrewrite -(subn_add2r (maxn m2 m3)) -(subn_add2r (maxn m1 m3) (m2 + _)) -!addnA.\nby rewrite !addn_maxl !addn_min_max !addn_maxr addnCA maxnAC (addnC m2 m1).\nQed.\n\nLemma minnA : associative minn.\nProof. by move=> m1 m2 m3; rewrite (minnC m2) minnCA minnC. Qed.\n\nLemma minnAC : right_commutative minn.\nProof. by move=> m1 m2 m3; rewrite minnC minnCA minnA. Qed.\n\nLemma eqn_minr : forall m n, (minn m n == n) = (n <= m).\nProof.\nmove=> m n; rewrite -(eqn_addr m) eq_sym addnC -addn_min_max eqn_addl.\nexact: eqn_maxl.\nQed.\n\nLemma eqn_minl : forall m n, (minn m n == m) = (m <= n).\nProof.\nby move=> m n; rewrite -(eqn_addr n) eq_sym -addn_min_max eqn_addl eqn_maxr.\nQed.\n\nLemma minnn : forall n, minn n n = n.\nProof. by move=> n; apply/eqP; rewrite eqn_minl. Qed.\n\nLemma leq_minr : forall m n1 n2, (m <= minn n1 n2) = (m <= n1) && (m <= n2).\nProof.\nmove=> m n1 n2; wlog le_n21: n1 n2 / n2 <= n1.\n  by case/orP: (leq_total n2 n1) => ?; last rewrite minnC andbC; auto.\nby rewrite /minn ltnNge le_n21 /= andbC; case: leqP => //; move/leq_trans->.\nQed.\n\nLemma leq_minl : forall m n1 n2, (minn n1 n2 <= m) = (n1 <= m) || (n2 <= m).\nProof. by move=> m n1 n2; rewrite leqNgt leq_minr negb_and -!leqNgt. Qed.\n\nLemma addn_minl : left_distributive addn minn.\nProof.\nmove=> m1 m2 n; rewrite !minn_to_maxn -addn_maxl addnA subn_add2r addnAC.\nby rewrite -!(addnC n) addn_subA // -addn_min_max leq_addl.\nQed.\n\nLemma addn_minr : right_distributive addn minn.\nProof. by move=> m n1 n2; rewrite !(addnC m) addn_minl. Qed.\n\n(* Quasi-cancellation (really, absorption) lemmas *)\nLemma maxnK : forall m n, minn (maxn m n) m = m.\nProof. by move=> m n; apply/eqP; rewrite eqn_minr leq_maxr leqnn. Qed.\n\nLemma maxKn : forall m n, minn n (maxn m n) = n.\nProof. by move=> m n; apply/eqP; rewrite eqn_minl leq_maxr leqnn orbT. Qed.\n\nLemma minnK : forall m n, maxn (minn m n) m = m.\nProof. by move=> m n; apply/eqP; rewrite eqn_maxr leq_minl leqnn. Qed.\n\nLemma minKn : forall m n, maxn n (minn m n) = n.\nProof. by move=> m n; apply/eqP; rewrite eqn_maxl leq_minl leqnn orbT. Qed.\n\n(* Distributivity. *)\n\nLemma maxn_minl : left_distributive maxn minn.\nProof.\nmove=> m1 m2 n; wlog le_m21: m1 m2 / m2 <= m1.\n  case/orP: (leq_total m2 m1) => ?; last rewrite minnC (minnC (maxn _ _));\n     by auto.\napply/eqP; rewrite /minn ltnNge le_m21 eq_sym eqn_minr leq_maxr !leq_maxl.\nrewrite le_m21 leqnn andbT; case: leqP => //; move/ltnW.\nby move/(leq_trans le_m21)->.\nQed.\n\nLemma maxn_minr : right_distributive maxn minn.\nProof. by move=> m n1 n2; rewrite !(maxnC m) maxn_minl. Qed.\n\nLemma minn_maxl : left_distributive minn maxn.\nProof.\nmove=> m1 m2 n; rewrite maxn_minr !maxn_minl -minnA maxnn; congr minn.\napply/eqP; rewrite maxnC minnA -maxn_minl eq_sym eqn_minr leq_maxr.\nby rewrite leqnn orbT.\nQed.\n\nLemma minn_maxr : right_distributive minn maxn.\nProof. by move=> m n1 n2; rewrite !(minnC m) minn_maxl. Qed.\n\n(* Getting a concrete value from an abstract existence proof. *)\n\nSection ExMinn.\n\nVariable P : pred nat.\nHypothesis exP : exists n, P n.\n\nInductive acc_nat i : Prop := AccNat0 of P i | AccNatS of acc_nat i.+1.\n\nLemma find_ex_minn : {m | P m & forall n, P n -> n >= m}.\nProof.\nhave: forall n, P n -> n >= 0 by [].\nhave: acc_nat 0.\n  case exP => n; rewrite -(addn0 n); elim: n 0 => [|n IHn] j; first by left.\n  rewrite addSnnS; right; exact: IHn.\nmove: 0; fix 2 => m IHm m_lb; case Pm: (P m); first by exists m.\napply: find_ex_minn m.+1 _ _ => [|n Pn]; first by case: IHm; rewrite ?Pm.\nby rewrite ltn_neqAle m_lb //; case: eqP Pm => // ->; case/idP.\nQed.\n\nDefinition ex_minn := s2val find_ex_minn.\n\nInductive ex_minn_spec : nat -> Type :=\n  ExMinnSpec m of P m & (forall n, P n -> n >= m) : ex_minn_spec m.\n\nLemma ex_minnP : ex_minn_spec ex_minn.\nProof. by rewrite /ex_minn; case: find_ex_minn. Qed.\n\nEnd ExMinn.\n\nSection ExMaxn.\n\nVariables (P : pred nat) (m : nat).\nHypotheses (exP : exists i, P i) (ubP : forall i, P i -> i <= m).\n\nLemma ex_maxn_subproof : exists i, P (m - i).\nProof. by case: exP => i Pi; exists (m - i); rewrite subKn ?ubP. Qed.\n\nDefinition ex_maxn := m - ex_minn ex_maxn_subproof.\n\nCoInductive ex_maxn_spec : nat -> Type :=\n  ExMaxnSpec i of P i & (forall j, P j -> j <= i) : ex_maxn_spec i.\n\nLemma ex_maxnP : ex_maxn_spec ex_maxn.\nProof.\nrewrite /ex_maxn; case: ex_minnP => i Pmi min_i; split=> // j Pj.\nhave le_i_mj: i <= m - j by rewrite min_i // subKn // ubP.\nrewrite -subn_eq0 subn_subA ?(leq_trans le_i_mj) ?leq_subr //.\nby rewrite addnC -subn_subA ?ubP.\nQed.\n\nEnd ExMaxn.\n\nLemma eq_ex_minn : forall P Q exP exQ,\n  P =1 Q -> @ex_minn P exP = @ex_minn Q exQ.\nProof.\nmove=> P Q exP exQ eqPQ.\ncase: ex_minnP => m1 Pm1 m1_lb; case: ex_minnP => m2 Pm2 m2_lb.\nby apply/eqP; rewrite eqn_leq m1_lb (m2_lb, eqPQ) // -eqPQ.\nQed.\n\nLemma eq_ex_maxn : forall (P Q : pred nat) m n exP ubP exQ ubQ,\n  P =1 Q -> @ex_maxn P m exP ubP = @ex_maxn Q n exQ ubQ.\nProof.\nmove=> P Q m n exP ubP exQ ubQ eqPQ.\ncase: ex_maxnP => i Pi max_i; case: ex_maxnP => j Pj max_j.\nby apply/eqP; rewrite eqn_leq max_i ?eqPQ // max_j -?eqPQ.\nQed.\n\nSection Iteration.\n\nVariable T : Type.\nImplicit Types m n : nat.\nImplicit Types x y : T.\n\nDefinition iter n f x :=\n  let fix loop m := if m is i.+1 then f (loop i) else x in loop n.\n\nDefinition iteri n f x :=\n  let fix loop m := if m is i.+1 then f i (loop i) else x in loop n.\n\nDefinition iterop n op x :=\n  let f i y := if i is 0 then x else op x y in iteri n f.\n\nLemma iterSr : forall n f x, iter n.+1 f x = iter n f (f x).\nProof. by move=> n f x; elim: n => //= n <-. Qed.\n\nLemma iterS : forall n f x, iter n.+1 f x = f (iter n f x). Proof. by []. Qed.\n\nLemma iter_add : forall n m f x, iter (n + m) f x = iter n f (iter m f x).\nProof. by move=> n m f x; elim: n => //= n ->. Qed.\n\nLemma iteriS : forall n f x, iteri n.+1 f x = f n (iteri n f x).\nProof. by []. Qed.\n\nLemma iteropS : forall idx n op x, iterop n.+1 op x idx = iter n (op x) x.\nProof. by move=> idx n op x; elim: n => //= n ->. Qed.\n\nLemma eq_iter : forall f f', f =1 f' -> forall n, iter n f =1 iter n f'.\nProof. by move=> f f' Ef n x; elim: n => //= n ->; rewrite Ef. Qed.\n\nLemma eq_iteri : forall f f', f =2 f' -> forall n, iteri n f =1 iteri n f'.\nProof. by move=> f f' Ef n x; elim: n => //= n ->; rewrite Ef. Qed.\n\nLemma eq_iterop : forall n op op', op =2 op' -> iterop n op =2 iterop n op'.\nProof. by move=> n op op' eqop x; apply: eq_iteri; case. Qed.\n\nEnd Iteration.\n\n(* Multiplication. *)\n\nDefinition muln_rec := mult.\nNotation \"m * n\" := (muln_rec m n) : nat_rec_scope.\n\nDefinition muln := nosimpl muln_rec.\nNotation \"m * n\" := (muln m n) : nat_scope.\n\nLemma multE : mult = muln.     Proof. by []. Qed.\nLemma mulnE : muln = muln_rec. Proof. by []. Qed.\n\nLemma mul0n : left_zero 0 muln. Proof. by []. Qed.\nLemma muln0 : right_zero 0 muln. Proof. by elim. Qed.\nLemma mul1n : left_id 1 muln. Proof. exact: addn0. Qed.\nLemma mulSn : forall m n, m.+1 * n = n + m * n. Proof. by []. Qed.\nLemma mulSnr : forall m n, m.+1 * n = m * n + n.\nProof. by move=> *; exact: addnC. Qed.\nLemma mulnS : forall m n, m * n.+1 = m + m * n.\nProof. by move=> m n; elim: m => // m; rewrite !mulSn !addSn addnCA => ->. Qed.\nLemma mulnSr : forall m n, m * n.+1 = m * n + m.\nProof. by move=> m n; rewrite addnC mulnS. Qed.\n\nLemma muln1 : right_id 1 muln.\nProof. by move=> n; rewrite mulnSr muln0. Qed.\n\nLemma mulnC : commutative muln.\nProof.\nby move=> m n; elim: m => [|m]; rewrite (muln0, mulnS) // mulSn => ->.\nQed.\n\nLemma muln_addl : left_distributive muln addn.\nProof. by move=> m1 m2 n; elim: m1 => //= m1 IHm; rewrite -addnA -IHm. Qed.\n\nLemma muln_addr : right_distributive muln addn.\nProof. by move=> m *; rewrite !(mulnC m) muln_addl. Qed.\n\nLemma muln_subl : left_distributive muln subn.\nProof.\nmove=> m n [|p]; first by rewrite !muln0.\nby elim: m n => // [m IHm] [|n] //; rewrite mulSn subn_add2l -IHm.\nQed.\n\nLemma muln_subr : right_distributive muln subn.\nProof. by move=> m n p; rewrite !(mulnC m) muln_subl. Qed.\n\nLemma mulnA : associative muln.\nProof. by move=> m n p; elim: m => //= m; rewrite mulSn muln_addl => ->. Qed.\n\nLemma mulnCA : left_commutative muln.\nProof. by move=> m *; rewrite !mulnA (mulnC m). Qed.\n\nLemma mulnAC : right_commutative muln.\nProof. by move=> m n p; rewrite -!mulnA (mulnC n). Qed.\n\nLemma muln_eq0 : forall m n, (m * n == 0) = (m == 0) || (n == 0).\nProof. by case=> // m [|n] //=; rewrite muln0. Qed.\n\nLemma eqn_mul1 : forall m n, (m * n == 1) = (m == 1) && (n == 1).\nProof. by case=> [|[|m]] [|[|n]] //; rewrite muln0. Qed.\n\nLemma muln_gt0 : forall m n, (0 < m * n) = (0 < m) && (0 < n).\nProof. by case=> // m [|n] //=; rewrite muln0. Qed.\n\nLemma leq_pmull : forall m n, n > 0 -> m <= n * m.\nProof. by move=> m [|n] // _; exact: leq_addr. Qed.\n\nLemma leq_pmulr : forall m n, n > 0 -> m <= m * n.\nProof. by move=> m n n_gt0; rewrite mulnC leq_pmull. Qed.\n\nLemma leq_mul2l : forall m n1 n2, (m * n1 <= m * n2) = (m == 0) || (n1 <= n2).\nProof. by move=> *; rewrite {1}/leq -muln_subr muln_eq0. Qed.\n\nLemma leq_mul2r : forall m n1 n2, (n1 * m <= n2 * m) = (m == 0) || (n1 <= n2).\nProof. by move=> m *; rewrite -!(mulnC m) leq_mul2l. Qed.\n\nLemma leq_mul : forall m1 m2 n1 n2, m1 <= n1 -> m2 <= n2 -> m1 * m2 <= n1 * n2.\nProof.\nmove=> m1 m2 n1 n2 le_mn1 le_mn2; apply (@leq_trans (m1 * n2)).\n  by rewrite leq_mul2l le_mn2 orbT.\nby rewrite leq_mul2r le_mn1 orbT.\nQed.\n\nLemma eqn_mul2l : forall m n1 n2, (m * n1 == m * n2) = (m == 0) || (n1 == n2).\nProof. by move=> *; rewrite eqn_leq !leq_mul2l -demorgan3 -eqn_leq. Qed.\n\nLemma eqn_mul2r : forall m n1 n2, (n1 * m == n2 * m) = (m == 0) || (n1 == n2).\nProof. by move=> *; rewrite eqn_leq !leq_mul2r -orb_andr -eqn_leq. Qed.\n\nLemma leq_pmul2l : forall m n1 n2, 0 < m -> (m * n1 <= m * n2) = (n1 <= n2).\nProof. by case=> // *; rewrite leq_mul2l. Qed.\nImplicit Arguments leq_pmul2l [m n1 n2].\n\nLemma leq_pmul2r : forall m n1 n2, 0 < m -> (n1 * m <= n2 * m) = (n1 <= n2).\nProof. by case=> // *; rewrite leq_mul2r. Qed.\nImplicit Arguments leq_pmul2r [m n1 n2].\n\nLemma eqn_pmul2l : forall m n1 n2, 0 < m -> (m * n1 == m * n2) = (n1 == n2).\nProof. by case=> // *; rewrite eqn_mul2l. Qed.\nImplicit Arguments eqn_pmul2l [m n1 n2].\n\nLemma eqn_pmul2r : forall m n1 n2, 0 < m -> (n1 * m == n2 * m) = (n1 == n2).\nProof. by case=> // *; rewrite eqn_mul2r. Qed.\nImplicit Arguments eqn_pmul2r [m n1 n2].\n\nLemma ltn_mul2l : forall m n1 n2, (m * n1 < m * n2) = (0 < m) && (n1 < n2).\nProof. by move=> *; rewrite lt0n !ltnNge leq_mul2l negb_orb. Qed.\n\nLemma ltn_mul2r : forall m n1 n2, (n1 * m < n2 * m) = (0 < m) && (n1 < n2).\nProof. by move=> *; rewrite lt0n !ltnNge leq_mul2r negb_orb. Qed.\n\nLemma ltn_pmul2l : forall m n1 n2, 0 < m -> (m * n1 < m * n2) = (n1 < n2).\nProof. by case=> // *; rewrite ltn_mul2l. Qed.\nImplicit Arguments ltn_pmul2l [m n1 n2].\n\nLemma ltn_pmul2r : forall m n1 n2, 0 < m -> (n1 * m < n2 * m) = (n1 < n2).\nProof. by case=> // *; rewrite ltn_mul2r. Qed.\nImplicit Arguments ltn_pmul2r [m n1 n2].\n\nLemma ltn_Pmull : forall m n, 1 < n -> 0 < m -> m < n * m.\nProof. by move=> m n lt1n m_gt0; rewrite -{1}[m]mul1n ltn_pmul2r. Qed.\n\nLemma ltn_Pmulr : forall m n, 1 < n -> 0 < m -> m < m * n.\nProof. by move=> m n lt1n m_gt0; rewrite mulnC ltn_Pmull. Qed.\n\nLemma ltn_mul : forall m1 m2 n1 n2, m1 < n1 -> m2 < n2 -> m1 * m2 < n1 * n2.\nProof.\nmove=> m1 m2 n1 n2 lt_mn1 lt_mn2; apply (@leq_ltn_trans (m1 * n2)).\n  by rewrite leq_mul2l orbC ltnW.\nby rewrite ltn_pmul2r // (leq_trans _ lt_mn2).\nQed.\n\nLemma maxn_mulr : right_distributive muln maxn.\nProof. by case=> // m n1 n2; rewrite /maxn (fun_if (muln _)) ltn_pmul2l. Qed.\n\nLemma maxn_mull : left_distributive muln maxn.\nProof. by move=> m1 m2 n; rewrite -!(mulnC n) maxn_mulr. Qed.\n\nLemma minn_mulr : right_distributive muln minn.\nProof. by case=> // m n1 n2; rewrite /minn (fun_if (muln _)) ltn_pmul2l. Qed.\n\nLemma minn_mull : left_distributive muln minn.\nProof. by move=> m1 m2 n; rewrite -!(mulnC n) minn_mulr. Qed.\n\n(* Exponentiation. *)\n\nDefinition expn_rec m n := iterop n muln m 1.\nNotation \"m ^ n\" := (expn_rec m n) : nat_rec_scope.\nDefinition expn := nosimpl expn_rec.\nNotation \"m ^ n\" := (expn m n) : nat_scope.\n\nLemma expnE : expn = expn_rec. Proof. by []. Qed.\n\nLemma expn0 : forall m, m ^ 0 = 1. Proof. by []. Qed.\nLemma expn1 : forall m, m ^ 1 = m. Proof. by []. Qed.\n\nLemma expnS : forall m n, m ^ n.+1 = m * m ^ n.\nProof. by move=> m [|n] //; rewrite muln1. Qed.\n\nLemma expnSr : forall m n, m ^ n.+1 = m ^ n * m.\nProof. by move=> m n; rewrite mulnC expnS. Qed.\n\nLemma exp0n : forall n, 0 < n -> 0 ^ n = 0. Proof. by do 2?case. Qed.\n\nLemma exp1n : forall n, 1 ^ n = 1.\nProof. by elim=> // n; rewrite expnS mul1n. Qed.\n\nLemma expn_add : forall m n1 n2, m ^ (n1 + n2) = m ^ n1 * m ^ n2.\nProof.\nby move=> m n1 n2; elim: n1 => [|n1 IHn]; rewrite !(mul1n, expnS) // IHn mulnA.\nQed.\n\nLemma expn_mull : forall m1 m2 n, (m1 * m2) ^ n = m1 ^ n * m2 ^ n.\nProof.\nby move=> m1 m2; elim=> // n IHn; rewrite !expnS IHn -!mulnA (mulnCA m2).\nQed.\n\nLemma expn_mulr : forall m n1 n2, m ^ (n1 * n2) = (m ^ n1) ^ n2.\nProof.\nmove=> m n1 n2; elim: n1 => [|n1 IHn]; first by rewrite exp1n.\nby rewrite expn_add expnS expn_mull IHn.\nQed.\n\nLemma expn_gt0 : forall m n, (0 < m ^ n) = (0 < m) || (n == 0).\nProof. by move=> [|m]; elim=> //= n IHn; rewrite expnS // addn_gt0 IHn. Qed.\n\nLemma expn_eq0 : forall m e, (m ^ e == 0) = (m == 0) && (e > 0).\nProof. by move=> *; rewrite !eqn0Ngt expn_gt0 negb_orb -lt0n. Qed.\n\nLemma ltn_expl : forall m n, 1 < m -> n < m ^ n.\nProof.\nmove=> m n Hm; elim: n => //= n; rewrite -(leq_pmul2l (ltnW Hm)) expnS.\napply: leq_trans; exact: ltn_Pmull.\nQed.\n\nLemma leq_exp2l : forall m n1 n2, 1 < m -> (m ^ n1 <= m ^ n2) = (n1 <= n2).\nProof.\nmove=> m n1 n2 Hm; elim: n1 n2 => [|n1 IHn] [|n2] //; last 1 first.\n- by rewrite !expnS leq_pmul2l ?IHn // ltnW.\n- by rewrite expn_gt0 ltnW.\nby rewrite leqNgt (leq_trans Hm) // expnS leq_pmulr // expn_gt0 ltnW.\nQed.\n\nLemma ltn_exp2l : forall m n1 n2, 1 < m -> (m ^ n1 < m ^ n2) = (n1 < n2).\nProof. by move=> *; rewrite !ltnNge leq_exp2l. Qed.\n\nLemma eqn_exp2l : forall m n1 n2, 1 < m -> (m ^ n1 == m ^ n2) = (n1 == n2).\nProof. by move=> *; rewrite !eqn_leq !leq_exp2l. Qed.\n\nLemma expnI : forall m, 1 < m -> injective (expn m).\nProof. by move=> * e1 e2; move/eqP; rewrite eqn_exp2l //; move/eqP. Qed.\n\nLemma leq_pexp2l : forall m n1 n2, 0 < m -> n1 <= n2 -> m ^ n1 <= m ^ n2.\nProof. by move=> [|[|m]] // *; [rewrite !exp1n | rewrite leq_exp2l]. Qed.\n\nLemma ltn_pexp2l : forall m n1 n2, 0 < m -> m ^ n1 < m ^ n2 -> n1 < n2.\nProof. by move=> [|[|m]] // n1 n2; [rewrite !exp1n | rewrite ltn_exp2l]. Qed.\n\nLemma ltn_exp2r : forall m n e, e > 0 -> (m ^ e < n ^ e) = (m < n).\nProof.\nmove=> m n e e_gt0; apply/idP/idP=> [|ltmn].\n  rewrite !ltnNge; apply: contra => lemn.\n  by elim: e {e_gt0} => // e IHe; rewrite !expnS leq_mul.\nelim: e e_gt0 => // [[|e] IHe] _; first by rewrite !expn1.\nby rewrite ltn_mul // IHe.\nQed.\n\nLemma leq_exp2r : forall m n e, e > 0 -> (m ^ e <= n ^ e) = (m <= n).\nProof. by move=> *; rewrite leqNgt ltn_exp2r // -leqNgt. Qed.\n\nLemma eqn_exp2r : forall m n e, e > 0 -> (m ^ e == n ^ e) = (m == n).\nProof. by move=> *; rewrite !eqn_leq !leq_exp2r. Qed.\n\nLemma expIn : forall e, e > 0 -> injective (expn^~ e).\nProof. by move=> * m n; move/eqP; rewrite eqn_exp2r //; move/eqP. Qed.\n\n(* Factorial. *)\n\nFixpoint fact_rec n := if n is n'.+1 then n * fact_rec n' else 1.\n\nDefinition factorial := nosimpl fact_rec.\n\nNotation \"n `!\" := (factorial n) (at level 2, format \"n `!\") : nat_scope.\n\nLemma factE : factorial = fact_rec. Proof. by []. Qed.\n\nLemma fact0 : 0`! = 1. Proof. by []. Qed.\n\nLemma factS : forall n, (n.+1)`!  = n.+1 * n`!. Proof. by []. Qed.\n\nLemma fact_gt0 : forall n, n`! > 0.\nProof. by elim=> //= n IHn; rewrite muln_gt0. Qed.\n\n(* Parity and bits. *)\n\nCoercion nat_of_bool (b : bool) := if b then 1 else 0.\n\nLemma leq_b1 : forall b : bool, b <= 1. Proof. by case. Qed.\n\nLemma addn_negb : forall b : bool, ~~ b + b = 1. Proof. by case. Qed.\n\nLemma sub1b : forall b : bool, 1 - b = ~~ b. Proof. by case. Qed.\n\nLemma mulnb : forall b1 b2 : bool, b1 * b2 = b1 && b2. Proof. by do 2!case. Qed.\n\nFixpoint odd n := if n is n'.+1 then ~~ odd n' else false.\n\nLemma oddb : forall b : bool, odd b = b. Proof. by case. Qed.\n\nLemma odd_add : forall m n, odd (m + n) = odd m (+) odd n.\nProof.\nby move=> m n; elim: m => [|m IHn] //=; rewrite -addTb IHn addbA addTb.\nQed.\n\nLemma odd_sub : forall m n, n <= m -> odd (m - n) = odd m (+) odd n.\nProof.\nby move=> m n le_nm; apply: (@canRL bool) (addbK _) _; rewrite -odd_add subnK.\nQed.\n\nLemma odd_opp : forall i m, odd m = false -> i < m -> odd (m - i) = odd i.\nProof. by move=> i m oddm lti; rewrite (odd_sub (ltnW lti)) oddm. Qed.\n\nLemma odd_mul : forall m n, odd (m * n) = odd m && odd n.\nProof. by elim=> //= m' IHm n; rewrite odd_add -addTb andb_addl -IHm. Qed.\n\nLemma odd_exp : forall m n, odd (m ^ n) = (n == 0) || odd m.\nProof.\nby move=> m; elim=> // n IHn; rewrite expnS odd_mul {}IHn orbC; case odd.\nQed.\n\n(* Doubling. *)\n\nFixpoint double_rec n := if n is n'.+1 then n'.*2%Nrec.+2 else 0\nwhere \"n .*2\" := (double_rec n) : nat_rec_scope.\n\nDefinition double := nosimpl double_rec.\nNotation \"n .*2\" := (double n) : nat_scope.\n\nLemma doubleE : double = double_rec. Proof. by []. Qed.\n\nLemma double0 : 0.*2 = 0. Proof. by []. Qed.\n\nLemma doubleS : forall n, n.+1.*2 = n.*2.+2. Proof. by []. Qed.\n\nLemma addnn : forall n, n + n = n.*2.\nProof. by move=> n; apply: eqP; elim: n => *; rewrite ?addnS. Qed.\n\nLemma mul2n : forall m, 2 * m = m.*2.\nProof. by move=> *; rewrite mulSn mul1n addnn. Qed.\n\nLemma muln2 : forall m, m * 2 = m.*2.\nProof. by move=> *; rewrite mulnC mul2n. Qed.\n\nLemma double_add : forall m n, (m + n).*2 = m.*2 + n.*2.\nProof. by move=> m n; rewrite -!addnn -!addnA (addnCA n). Qed.\n\nLemma double_sub : forall m n, (m - n).*2 = m.*2 - n.*2.\nProof. elim=> [|m IHm] [|n] //; exact: IHm n. Qed.\n\nLemma leq_double : forall m n, (m.*2 <= n.*2) = (m <= n).\nProof. by move=> m n; rewrite /leq -double_sub; case (m - n). Qed.\n\nLemma ltn_double : forall m n, (m.*2 < n.*2) = (m < n).\nProof. by move=> *; rewrite 2!ltnNge leq_double. Qed.\n\nLemma ltn_Sdouble : forall m n, (m.*2.+1 < n.*2) = (m < n).\nProof. by move=> *; rewrite -doubleS leq_double. Qed.\n\nLemma leq_Sdouble : forall m n, (m.*2 <= n.*2.+1) = (m <= n).\nProof. by move=> *; rewrite leqNgt ltn_Sdouble -leqNgt. Qed.\n\nLemma odd_double : forall n, odd n.*2 = false.\nProof. by move=> *; rewrite -addnn odd_add addbb. Qed.\n\nLemma double_gt0 : forall n, (0 < n.*2) = (0 < n).\nProof. by case. Qed.\n\nLemma double_eq0 : forall n, (n.*2 == 0) = (n == 0).\nProof. by case. Qed.\n\nLemma double_mull : forall m n, (m * n).*2 = m.*2 * n.\nProof. by move=> *; rewrite -!mul2n mulnA. Qed.\n\nLemma double_mulr : forall m n, (m * n).*2 = m * n.*2.\nProof. by move=> *; rewrite -!muln2 mulnA. Qed.\n\n(* Halving. *)\n\nFixpoint half (n : nat) : nat := if n is n'.+1 then uphalf n' else n\nwith   uphalf (n : nat) : nat := if n is n'.+1 then n'./2.+1 else n\nwhere \"n ./2\" := (half n) : nat_scope.\n\nLemma doubleK : cancel double half.\nProof. by elim=> //= n ->. Qed.\n\nDefinition half_double := doubleK.\nDefinition double_inj := can_inj doubleK.\n\nLemma uphalf_double : forall n, uphalf n.*2 = n.\nProof. by elim=> //= n ->. Qed.\n\nLemma uphalf_half : forall n, uphalf n = odd n + n./2.\nProof. by elim=> //= n ->; rewrite addnA addn_negb. Qed.\n\nLemma odd_double_half : forall n, odd n + n./2.*2 = n.\nProof.\nby elim=> [|n Hrec] //=; rewrite -{3}Hrec uphalf_half double_add; case (odd n).\nQed.\n\nLemma half_bit_double : forall n (b : bool), (b + n.*2)./2 = n.\nProof. by move=> n [|]; rewrite /= (half_double, uphalf_double). Qed.\n\nLemma half_add : forall m n, (m + n)./2 = (odd m && odd n) + (m./2 + n./2).\nProof.\nmove=> m n; rewrite -{1}[n]odd_double_half addnCA -{1}[m]odd_double_half.\nrewrite -addnA -double_add.\nby do 2!case: odd; rewrite /= ?add0n ?half_double ?uphalf_double.\nQed.\n\nLemma half_leq : forall m n, m <= n -> m./2 <= n./2.\nProof. by move=> m n; move/subnK <-; rewrite half_add addnA leq_addl. Qed.\n\nLemma half_gt0 : forall n, (0 < n./2) = (1 < n).\nProof. by do 2?case. Qed.\n\n(* Squares and square identities. *)\n\nLemma mulnn : forall m, m * m = m ^ 2.\nProof. by move=> *; rewrite !expnS muln1. Qed.\n\nLemma sqrn_add : forall m n, (m + n) ^ 2 = m ^ 2 + n ^ 2 + 2 * (m * n).\nProof.\nmove=> m n; rewrite -!mulnn mul2n muln_addr !muln_addl (mulnC n) -!addnA.\nby congr (_ + _); rewrite addnA addnn addnC.\nQed.\n\nLemma sqrn_sub : forall m n, n <= m ->\n  (m - n) ^ 2 = m ^ 2 + n ^ 2 - 2 * (m * n).\nProof.\nmove=> m n; move/subnK=> def_m; rewrite -{2}def_m sqrn_add -addnA addnAC.\nby rewrite -2!addnA addnn -mul2n -muln_addr -muln_addl def_m addnK.\nQed.\n\nLemma sqrn_add_sub : forall m n, n <= m ->\n  (m + n) ^ 2 - 4 * (m * n) = (m - n) ^ 2.\nProof.\nmove=> m n le_nm; rewrite -[4]/(2 * 2) -mulnA mul2n -addnn -subn_sub.\nby rewrite sqrn_add addnK sqrn_sub.\nQed.\n\nLemma subn_sqr : forall m n, m ^ 2 - n ^ 2 = (m - n) * (m + n).\nProof.\nby move=> m n; rewrite muln_subl !muln_addr addnC (mulnC m) subn_add2l !mulnn.\nQed.\n\nLemma ltn_sqr : forall m n, (m ^ 2 < n ^ 2) = (m < n).\nProof. by move=> m n; rewrite ltn_exp2r. Qed.\n\nLemma leq_sqr : forall m n, (m ^ 2 <= n ^ 2) = (m <= n).\nProof. by move=> m n; rewrite leq_exp2r. Qed.\n\nLemma sqrn_gt0 : forall n, (0 < n ^ 2) = (0 < n).\nProof. exact: (ltn_sqr 0). Qed.\n\nLemma eqn_sqr : forall m n, (m ^ 2 == n ^ 2) = (m == n).\nProof. by move=> *; rewrite eqn_exp2r. Qed.\n\nLemma sqrn_inj : injective (expn ^~ 2).\nProof. exact: expIn. Qed.\n\n(* Almost strict inequality: an inequality that is strict unless some    *)\n(* specific condition holds, such as the Cauchy-Schwartz or the AGM      *)\n(* inequality (we only prove the order-2 AGM here; the general one       *)\n(* requires sequences).                                                  *)\n(*   We formalize the concept as a rewrite multirule, that can be used   *)\n(* both to rewrite the non-strict inequality to true, and the equality   *)\n(* to the specific condition (for strict inequalities use the ltn_neqAle *)\n(* lemma); in addition, the conditional equality also coerces to a       *)\n(* non-strict one.                                                       *)\n\nDefinition leqif m n c := ((m <= n) * ((m == n) = c))%type.\n\nNotation \"m <= n ?= 'iff' c\" := (leqif m n c)\n    (at level 70, n at next level,\n  format \"m '[hv'  <=  n '/'  ?=  'iff'  c ']'\") : nat_scope.\n\nCoercion leq_of_leqif m n c (H : m <= n ?= iff c) := H.1 : m <= n.\n\nLemma leqifP : forall m n c,\n   reflect (m <= n ?= iff c) (if c then m == n else m < n).\nProof.\nmove=> m n c; rewrite ltn_neqAle.\napply: (iffP idP) => [|lte]; last by rewrite !lte; case c.\ncase c; [move/eqP-> | case/andP; move/negPf]; split=> //; exact: eqxx.\nQed.\n\nLemma leqif_refl : forall m c, reflect (m <= m ?= iff c) c.\nProof.\nmove=> m c; apply: (iffP idP) => [-> | <-]; last by rewrite eqxx.\nby split; rewrite (leqnn, eqxx).\nQed.\n\nLemma leqif_trans : forall m1 m2 m3 c1 c2,\n  m1 <= m2 ?= iff c1 -> m2 <= m3 ?= iff c2 -> m1 <= m3 ?= iff c1 && c2.\nProof.\nmove=> m1 m2 m3 c1 c2 ltm12 ltm23; apply/leqifP; rewrite -ltm12.\ncase eqm12: (m1 == m2).\n  by rewrite (eqP eqm12) ltn_neqAle !ltm23 andbT; case c2.\nby rewrite (@leq_trans m2) ?ltm23 // ltn_neqAle eqm12 ltm12.\nQed.\n\nLemma monotone_leqif : forall f, monotone f ->\n  forall m n c, (f m <= f n ?= iff c) <-> (m <= n ?= iff c).\nProof.\nmove=> f f_mono m n c.\nby split; move/leqifP=> hyp; apply/leqifP;\n   rewrite !eqn_leq !ltnNge !f_mono in hyp *.\nQed.\n\nLemma leqif_geq : forall m n, m <= n -> m <= n ?= iff (m >= n).\nProof. by move=> m n lemn; split=> //; rewrite eqn_leq lemn. Qed.\n\nLemma leqif_eq : forall m n, m <= n -> m <= n ?= iff (m == n).\nProof. by []. Qed.\n\nLemma geq_leqif : forall a b C, a <= b ?= iff C -> (b <= a) = C.\nProof. by move=> a b C [le_ab]; rewrite eqn_leq le_ab. Qed.\n\nLemma leqif_add : forall m1 n1 c1 m2 n2 c2,\n    m1 <= n1 ?= iff c1 -> m2 <= n2 ?= iff c2 ->\n  m1 + m2 <= n1 + n2 ?= iff c1 && c2.\nProof.\nmove=> m1 n1 c1 m2 n2 c2 le1; move/(monotone_leqif (leq_add2l n1)).\napply: leqif_trans; exact/(monotone_leqif (leq_add2r m2)).\nQed.\n\nLemma leqif_mul : forall m1 n1 c1 m2 n2 c2,\n    m1 <= n1 ?= iff c1 -> m2 <= n2 ?= iff c2 ->\n  m1 * m2 <= n1 * n2 ?= iff (n1 * n2 == 0) || (c1 && c2).\nProof.\nmove=> m1 n1 c1 m2 n2 c2 le1 le2; case: posnP => [n12_0 | ].\n  rewrite n12_0; move/eqP: n12_0 {le1 le2}le1.1 le2.1; rewrite muln_eq0.\n  case/orP; move/eqP->; case: m1 m2 => [|m1] [|m2] // _ _;\n   rewrite ?muln0; exact/leqif_refl.\nrewrite muln_gt0; move/andP=> [n1_gt0 n2_gt0].\ncase: (posnP m2) => [m2_0 | m2_gt0].\n  apply/leqifP; rewrite -le2 andbC eq_sym eqn_leq leqNgt m2_0 muln0.\n  by rewrite muln_gt0 n1_gt0 n2_gt0.\nmove/leq_pmul2l: n1_gt0; move/monotone_leqif=> Mn1; move/Mn1: le2 => {Mn1}.\nmove/leq_pmul2r: m2_gt0; move/monotone_leqif=> Mm2; move/Mm2: le1 => {Mm2}.\nexact: leqif_trans.\nQed.\n\nLemma nat_Cauchy : forall m n, 2 * (m * n) <= m ^ 2 + n ^ 2 ?= iff (m == n).\nProof.\nmove=> m n; wlog le_nm: m n / n <= m.\n  by case: (leqP m n); auto; rewrite eq_sym addnC (mulnC m); auto.\napply/leqifP; case: ifP => [|ne_mn].\n  by move/eqP->; rewrite mulnn addnn mul2n.\nby rewrite -subn_gt0 -sqrn_sub // sqrn_gt0 subn_gt0 ltn_neqAle eq_sym ne_mn.\nQed.\n\nLemma nat_AGM2 : forall m n, 4 * (m * n) <= (m + n) ^ 2 ?= iff (m == n).\nProof.\nmove=> m n; rewrite -[4]/(2 * 2) -mulnA mul2n -addnn sqrn_add.\napply/leqifP; rewrite ltn_add2r eqn_addr ltn_neqAle !nat_Cauchy.\nby case: ifP => ->.\nQed.\n\n(* Support for larger integers. The normal definitions of +, - and even  *)\n(* IO are unsuitable for Peano integers larger than 2000 or so because   *)\n(* they are not tail-recursive. We provide a workaround module, along    *)\n(* with a rewrite multirule to change the tailrec operators to the       *)\n(* normal ones. We handle IO via the NatBin module, but provide our      *)\n(* own (more efficient) conversion functions.                            *)\n\nModule NatTrec.\n\n(*   Usage:                                             *)\n(*     Import NatTrec.                                  *)\n(*        in section definining functions, rebinds all  *)\n(*        non-tail recursive operators.                 *)\n(*     rewrite !trecE.                                  *)\n(*        in the correctness proof, restores operators  *)\n\nFixpoint add (m n : nat) {struct m} :=\n  if m is m'.+1 then m' + n.+1 else n\nwhere \"n + m\" := (add n m) : nat_scope.\n\nFixpoint add_mul (m n s : nat) {struct m} :=\n  if m is m'.+1 then add_mul m' n (n + s) else s.\n\nDefinition mul m n := if m is m'.+1 then add_mul m' n n else 0.\n\nNotation \"n * m\" := (mul n m) : nat_scope.\n\nFixpoint mul_exp (m n p : nat) {struct n} :=\n  if n is n'.+1 then mul_exp m n' (m * p) else p.\n\nDefinition exp m n := if n is n'.+1 then mul_exp m n' m else 1.\n\nNotation \"n ^ m\" := (exp n m) : nat_scope.\n\nNotation Local oddn := odd.\nFixpoint odd (n : nat) := if n is n'.+2 then odd n' else eqn n 1.\n\nNotation Local doublen := double.\nDefinition double n := if n is n'.+1 then n' + n.+1 else 0.\nNotation \"n .*2\" := (double n) : nat_scope.\n\nLemma addE : add =2 addn.\nProof. by elim=> //= n IHn m; rewrite IHn addSnnS. Qed.\n\nLemma doubleE : double =1 doublen.\nProof. by case=> // n; rewrite -addnn -addE. Qed.\n\nLemma add_mulE : forall n m s, add_mul n m s = addn (muln n m) s.\nProof. by elim=> //= n IHn m s; rewrite IHn addE addnCA addnA. Qed.\n\nLemma mulE : mul =2 muln.\nProof. by case=> //= n m; rewrite add_mulE addnC. Qed.\n\nLemma mul_expE : forall m n p, mul_exp m n p = muln (expn m n) p.\nProof.\nby move=> m; elim=> [|n IHn] p; rewrite ?mul1n //= expnS IHn mulE mulnCA mulnA.\nQed.\n\nLemma expE : exp =2 expn.\nProof. by move=> m [|n] //=; rewrite mul_expE expnS mulnC. Qed.\n\nLemma oddE : odd =1 oddn.\nProof.\nmove=> n; rewrite -{1}[n]odd_double_half addnC.\nby elim: n./2 => //=; case (oddn n).\nQed.\n\nDefinition trecE :=\n  (addE, (doubleE, oddE), (mulE, add_mulE, (expE, mul_expE))).\n\nEnd NatTrec.\n\nNotation natTrecE := NatTrec.trecE.\n\nLemma eq_binP : Equality.axiom Ndec.Neqb.\nProof.\nmove=> p q; apply: (iffP idP) => [|[<-]]; last by case: p => //; elim.\nby case: q; case: p => //; elim=> [p IHp|p IHp|] [q|q|] //=; case/IHp=> ->.\nQed.\n\nCanonical Structure bin_nat_eqMixin := EqMixin eq_binP.\nCanonical Structure bin_nat_eqType := Eval hnf in EqType N bin_nat_eqMixin.\n\nSection NumberInterpretation.\n\nImport BinPos.\n\nSection Trec.\n\nImport NatTrec.\n\nFixpoint nat_of_pos p0 :=\n  match p0 with\n  | xO p => (nat_of_pos p).*2\n  | xI p => (nat_of_pos p).*2.+1\n  | xH   => 1\n  end.\n\nEnd Trec.\n\nCoercion Local nat_of_pos : positive >-> nat.\n\nCoercion nat_of_bin b := if b is Npos p then p : nat else 0.\n\nFixpoint pos_of_nat (n0 m0 : nat) {struct n0} :=\n  match n0, m0 with\n  | n.+1, m.+2 => pos_of_nat n m\n  | n.+1,    1 => xO (pos_of_nat n n)\n  | n.+1,    0 => xI (pos_of_nat n n)\n  |    0,    _ => xH\n  end.\n\nDefinition bin_of_nat n0 :=\n  if n0 is n.+1 then Npos (pos_of_nat n n) else 0%num.\n\nLemma bin_of_natK : cancel bin_of_nat nat_of_bin.\nProof.\nhave sub2nn: forall n, n.*2 - n = n by move=> n; rewrite -addnn addKn.\ncase=> //= n; rewrite -{3}[n]sub2nn.\nby elim: n {2 4}n => // m IHm [|[|n]] //=; rewrite IHm // natTrecE sub2nn.\nQed.\n\nLemma nat_of_binK : cancel nat_of_bin bin_of_nat.\nProof.\ncase=> //=; elim=> //= p; case: (nat_of_pos p) => //= n [<-].\n  by rewrite natTrecE !addnS {2}addnn; elim: {1 3}n.\nby rewrite natTrecE addnS /= addnS {2}addnn; elim: {1 3}n.\nQed.\n\nLemma nat_of_succ_gt0 : forall p, Psucc p = p.+1 :> nat.\nProof. by elim=> //= p ->; rewrite !natTrecE. Qed.\n\nLemma nat_of_addn_gt0 : forall p1 p2, (p1 + p2)%positive = p1 + p2 :> nat.\nProof.\nmove=> p q; apply: fst (Pplus_carry p q = (p + q).+1 :> nat) _.\nelim: p q => [p IHp|p IHp|] [q|q|] //=; rewrite !natTrecE //;\n  by rewrite ?IHp ?nat_of_succ_gt0 ?(doubleS, double_add, addn1, addnS).\nQed.\n\nLemma nat_of_add_bin : forall b1 b2, (b1 + b2)%num = b1 + b2 :> nat.\nProof. case=> [|p] [|q] //=; exact: nat_of_addn_gt0. Qed.\n\nLemma nat_of_mul_bin : forall b1 b2, (b1 * b2)%num = b1 * b2 :> nat.\nProof.\ncase=> [|p] [|q] //=; elim: p => [p IHp|p IHp|] /=;\n  by rewrite ?(mul1n, nat_of_addn_gt0, mulSn) //= !natTrecE IHp double_mull.\nQed.\n\nLemma nat_of_exp_bin : forall n (b : N), n ^ (b : nat) = pow_N 1 muln n b.\nProof.\nmove=> n [|p] /=; first exact: expn0.\nby elim: p => //= p <-; rewrite natTrecE mulnn -expn_mulr muln2 ?expnS.\nQed.\n\nEnd NumberInterpretation.\n\n(* Big(ger) nat IO; usage:                              *)\n(*     Num 1 072 399                                    *)\n(*        to create large numbers for test cases        *)\n(* Eval compute in [Num of some expression]             *)\n(*        to display the resut of an expression that    *)\n(*        returns a larger integer.                     *)\n\nRecord number : Type := Num {bin_of_number :> N}.\n\nDefinition extend_number (nn : number) m := Num (nn * 1000 + bin_of_nat m).\n\nCoercion extend_number : number >-> Funclass.\n\nCanonical Structure number_subType :=\n  [newType for bin_of_number by number_rect].\nDefinition number_eqMixin := Eval hnf in [eqMixin of number by <:].\nCanonical Structure number_eqType := Eval hnf in EqType number number_eqMixin.\n\nNotation \"[ 'Num' 'of' e ]\" := (Num (bin_of_nat e))\n  (at level 0, format \"[ 'Num'  'of'  e ]\") : nat_scope.\n\n(* Interface to ring/ring_simplify tactics *)\n\nLemma nat_semi_ring : semi_ring_theory 0 1 addn muln (@eq _).\nProof. exact: mk_srt add0n addnC addnA mul1n mul0n mulnC mulnA muln_addl. Qed.\n\nLemma nat_semi_morph :\n  semi_morph 0 1 addn muln (@eq _) 0%num 1%num Nplus Nmult pred1 nat_of_bin.\nProof.\nby move: nat_of_add_bin nat_of_mul_bin; split=> //= m n; move/eqP->.\nQed.\n\nLemma nat_power_theory : power_theory 1 muln (@eq _) nat_of_bin expn.\nProof. split; exact: nat_of_exp_bin. Qed.\n\n(* Interface to the ring tactic machinery. *)\n\nFixpoint pop_succn e := if e is e'.+1 then fun n => pop_succn e' n.+1 else id.\n\nLtac pop_succn e := eval lazy beta iota delta [pop_succn] in (pop_succn e 1).\n\nLtac nat_litteral e :=\n  match pop_succn e with\n  | ?n.+1 => constr: (bin_of_nat n)\n  |     _ => NotConstant\n  end.\n\nLtac succn_to_add :=\n  match goal with\n  | |- context G [?e.+1] =>\n    let x := fresh \"NatLit0\" in\n    match pop_succn e with\n    | ?n.+1 => pose x := n.+1; let G' := context G [x] in change G'\n    | _ ?e' ?n => pose x := n; let G' := context G [x + e'] in change G'\n    end; succn_to_add; rewrite {}/x\n  | _ => idtac\n  end.\n\nAdd Ring nat_ring_ssr : nat_semi_ring (morphism nat_semi_morph,\n   constants [nat_litteral], preprocess [succn_to_add],\n   power_tac nat_power_theory [nat_litteral]).\n\n(* A congruence tactic, similar to the boolean one, along with an .+1/+  *)\n(* normalization tactic.                                                 *)\n\n\nLtac nat_norm :=\n  succn_to_add; rewrite ?add0n ?addn0 -?addnA ?(addSn, addnS, add0n, addn0).\n\nLtac nat_congr := first\n [ apply: (congr1 succn _)\n | apply: (congr1 predn _)\n | apply: (congr1 (addn _) _)\n | apply: (congr1 (subn _) _)\n | apply: (congr1 (addn^~ _) _)\n | match goal with |- (?X1 + ?X2 = ?X3) =>\n     symmetry;\n     rewrite -1?(addnC X1) -?(addnCA X1);\n     apply: (congr1 (addn X1) _);\n     symmetry\n   end ].\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect12_trunk/theories/ssrnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7482537944282415}}
{"text": "\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Export Coq.Classes.SetoidClass.\nRequire Export Coq.Classes.Equivalence.\n\nOpen Scope equiv_scope.\n\nSection Composition.\n\n  Section Composition_def.\n    Context {A B C : Type}.\n\n    Definition f_comp (f : B -> C) (g : A -> B) : A -> C := fun a => f (g a).\n  \n    Global Instance f_comp_Proper : Proper ( equiv ==> equiv ==> equiv ) f_comp.\n    Proof.\n      intros f1 f2 eqf.\n      intros g1 g2 eqg.\n      intro a.\n      unfold f_comp.\n      rewrite (eqg _).\n      rewrite (eqf _).\n      reflexivity.\n    Qed.\n\n  End Composition_def.\n\n  Context {A B C D : Type}.\n  \n  Lemma f_comp_assoc : forall (f : C -> D) (g : B -> C) (h : A -> B), f_comp (f_comp f g) h === f_comp f (f_comp g h).\n  Proof.\n    unfold f_comp.\n    reflexivity.\n  Qed.\n  \n  Definition mono (f : A -> B) := forall (X : Type) (u1 u2 : X -> A), f_comp f u1 === f_comp f u2 -> u1 === u2.\n  Definition epi (f : A -> B) := forall (X : Type) (u1 u2 : B -> X), f_comp u1 f === f_comp u2 f -> u1 === u2.\n\n  Lemma mono_injection : forall f, mono f -> forall a1 a2, f a1 = f a2 -> a1 = a2.\n  Proof.\n    intros f monof a1 a2 eqfa.\n    cut ( (fun (i : True) => a1) === (fun (i : True) => a2)).\n    {\n      intro eH.\n      apply (eH I).\n    }\n    apply monof.\n    unfold f_comp.\n    intro i.\n    assumption.\n  Qed.\n\n  Lemma injection_mono : forall f, (forall a1 a2, f a1 = f a2 -> a1 = a2) -> mono f.\n  Proof.\n    intros f cond.\n    intros X u1 u2 eqf.\n    intro x.\n    apply cond.\n    apply eqf.\n  Qed.\n    \nEnd Composition.\n\nLemma f_comp_id_R : forall {A B : Type} (f : A -> B), f_comp f id === f.\nProof.\n  intros.\n  unfold id.  \n  unfold f_comp.\n  intro a.\n  reflexivity.\nQed.\n\nLemma f_comp_id_L : forall {A B : Type} (f : A -> B), f_comp id f === f.\nProof.\n  intros.\n  unfold id.  \n  unfold f_comp.\n  intro a.\n  reflexivity.\nQed.\n\nLemma f_equiv_eq : forall {A B} (f1 f2 : A -> B), f1 === f2 -> (forall a, f1 a = f2 a).\nProof.\n  auto.\nQed.\n\nLemma mono_id : forall {A : Type}, mono (@id A).\nProof.\n  intro A.\n  intros B u1 u2 eqH.\n  unfold f_comp in eqH.\n  unfold id in eqH.\n  intro a.\n  apply eqH.\nQed.\n\nLemma epi_id : forall {A : Type}, epi (@id A).\nProof.\n  intro A.\n  intros B u1 u2 eqH.\n  unfold f_comp in eqH.\n  unfold id in eqH.\n  intro a.\n  apply eqH.\nQed.\n\nDefinition isIsomorphism {A B : Type} (f1 : A -> B) (f2 : B -> A) :=\n  (f_comp f1 f2 === id) /\\ (f_comp f2 f1 === id).\n\nLemma de_morgan_nexists : forall {A} (P : A -> Prop), (~exists x, P x) -> forall x, ~P x.\nProof.\n  intros A P NP.\n  intros x Px.\n  apply NP.\n  exists x.\n  assumption.\nQed.\n\nLemma Neqtrue : forall b, ~b = true -> b = false.\nProof.\n  intros b neqbt.\n  destruct b.\n  elimtype False.\n  apply neqbt.\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma Neqtrue_inv : forall b, b = false -> ~b = true.\nProof.\n  intros b eqbf.\n  destruct b.\n  discriminate.\n  intro eqft.\n  discriminate.\nQed.\n", "meta": {"author": "k27c8ff627uxz", "repo": "quotient_in_coq", "sha": "b26d7f89d02a8f31092fb463b136f40012a34f71", "save_path": "github-repos/coq/k27c8ff627uxz-quotient_in_coq", "path": "github-repos/coq/k27c8ff627uxz-quotient_in_coq/quotient_in_coq-b26d7f89d02a8f31092fb463b136f40012a34f71/src/Construction/function_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7482537877548445}}
{"text": "Require Import Omega.\n\nOpen Scope Z_scope.\n\nLemma L1: forall (n m:Z), 1 + 2 * m <> 2 * n.\nProof.\n    intros n m. omega.\nQed.\n\n\nLemma L2: forall (z:Z), z > 0 -> 2 * z + 1 > z.\nProof. intros z. omega. Qed.\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/ref/omega.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813538993889, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7482107314293984}}
{"text": "Require Import Bool Arith Div2.\nRequire Import BellantoniCook.Lib BellantoniCook.Bitstring BellantoniCook.BC.\n\n(** * Zero\n\n  - with any arities (n, s)\n*)\n\nDefinition zero_e (n s:nat) : BC :=\n  comp n s zero nil nil.\n\nLemma zero_correct n s l1 l2: \n bs2nat (sem (zero_e n s) l1 l2) = 0.\nProof. intros; simpl; trivial. Qed.\n\n(** * One\n\n  - with any arities (n, s)\n*)\n\nDefinition one_e n s :=\n  comp n s (comp 0 0 (succ true) nil [zero]) nil nil.\n\n(** * Successor\n\n  - arities: (1, 0)\n*)\n\nDefinition succ_e : BC :=\n  rec (one_e 0 0)\n      (comp 1 1 (succ true) nil [proj 1 1 0])\n      (comp 1 1 (succ false) nil [proj 1 1 1]).\n\nLemma succ_correct :\n  forall n, bs2nat (sem succ_e [n] nil) = S (bs2nat n).\nProof.\n induction n; simpl in *; trivial.\n case a; simpl; [rewrite IHn | ]; ring.\nQed.\n\nGlobal Opaque succ_e.\n\n(** * Zero predicate\n\n  - arities: (1,0)\n*)\n\nDefinition is_zero_e : BC :=\n  rec (one_e 0 0) (proj 1 1 1) (zero_e 1 1).\n\nLemma is_zero_correct v :\n  bs2bool (sem is_zero_e [v] nil) = true <->\n  bs2nat v = 0.\nProof.\n intros; split; induction v; simpl; trivial.\n case a; intros; simpl in *.\n discriminate.\n rewrite IHv; trivial.\n case a; intros; simpl in *.\n contradict H; omega.\n apply IHv; omega.\nQed.\n\nLemma is_zero_correct_conv v :\n  bs2bool (sem is_zero_e [v] nil) = false <->\n  bs2nat v <> 0.\nProof.\n intros; split; intros. intro.\n apply is_zero_correct in H0.\n rewrite H in H0; discriminate.\n apply not_true_is_false.\n intro; apply is_zero_correct in H0.\n rewrite H0 in H; auto.\nQed.\n\nGlobal Opaque is_zero_e.\n\n(** * Predecessor\n\n  - arities: (1,0)\n*)\n\nDefinition pred_pos_e : BC :=\n  rec (zero_e 0 0)\n      (comp 1 1 (succ true) nil [proj 1 1 1])\n      (comp 1 1 (succ false) nil [proj 1 1 0]).\n\nLemma pred_pos_correct n :\n  bs2nat n <> 0 ->  \n  bs2nat (sem pred_pos_e [n] nil) = Peano.pred (bs2nat n).\nProof.\n intros; induction n; simpl in *; trivial.\n destruct a; simpl.\n trivial.\n rewrite IHn.\n destruct (bs2nat n).\n elim H; trivial.\n simpl.\n ring.\n omega.\nQed.\n\nGlobal Opaque pred_pos_e.\n\nDefinition pred_e : BC :=\n  comp 1 0 cond \n       nil [is_zero_e; pred_pos_e; zero_e 1 0; pred_pos_e].\n\nLemma pred_correct n :\n  bs2nat (sem pred_e [n] nil) = Peano.pred (bs2nat n).\nProof.\n simpl; intros.\n case_eq (sem is_zero_e [n] nil); intros.\n assert (bs2bool (sem is_zero_e [n] nil) = false).\n rewrite H; simpl; trivial.\n apply is_zero_correct_conv  in H0.\n apply pred_pos_correct; trivial.\n destruct b.\n assert (bs2bool (sem is_zero_e [n] nil) = true).\n rewrite H; simpl; trivial.\n apply is_zero_correct  in H0.\n rewrite H0; simpl; trivial.\n assert (bs2bool (sem is_zero_e [n] nil) = false).\n rewrite H; simpl; trivial.\n apply is_zero_correct_conv  in H0.\n apply pred_pos_correct; trivial.\nQed.\n\nGlobal Opaque pred_e.\n\n(** * Division by 2\n\n  - arities: (1,0)\n*)\n\nNotation div2_e := pred.\n\nLemma div2_correct : forall v,\n  bs2nat (sem pred nil [v]) = div2 (bs2nat v).\nProof.\n intros v; case v; simpl; trivial; intros.\n case b.\n replace (bs2nat l + (bs2nat l + 0)) with (2 * (bs2nat l)).\n rewrite div2_double_plus_one; trivial.\n ring.\n replace (bs2nat l + (bs2nat l + 0)) with (2 * (bs2nat l)).\n rewrite div2_double; trivial.\n omega.\nQed.\n", "meta": {"author": "davidnowak", "repo": "bellantonicook", "sha": "1f03b9296104646ddc2b2b4b12e35a6619c17a99", "save_path": "github-repos/coq/davidnowak-bellantonicook", "path": "github-repos/coq/davidnowak-bellantonicook/bellantonicook-1f03b9296104646ddc2b2b4b12e35a6619c17a99/src/BellantoniCook/BCBinary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8418256393148981, "lm_q1q2_score": 0.7481799444893266}}
{"text": "Section Ejercicio3.\n\nVariable U   : Set.\nVariable A B : U -> Prop.\nVariable P Q : Prop.\nVariable R S : U -> U -> Prop.\n\nHypothesis H1: forall x:U, (R x x).\nHypothesis H2: forall x y z:U, (R x y) /\\ (R x z) -> (R y z).\n\nTheorem reflexiva: (forall x:U, (R x x)).\nProof.\n  intros.\n  apply (H1 x).\nQed.\n\nTheorem simetrica: (forall x y:U, (R x y) -> (R y x)).\nProof.\n  intros.\n  apply (H2 x y x).\n  split.\n  assumption.\n  apply (H1 x).\nQed.\n\nTheorem transitiva: (forall x y z:U, (R x y) /\\ (R y z) -> (R x z)).\n\nProof.\n  \n  intros.\n  apply (H2 y x z).\n  split.\n  apply (simetrica x y).\n  elim H.\n  intros.\n  assumption.\n  elim H.\n  intros.\n  assumption.\nQed.\nEnd Ejercicio3.\n\n\nSection Ejercicio5.\n\nVariable nat      : Set.\nVariable S        : nat -> nat.\nVariable a b c    : nat.\nVariable odd even : nat -> Prop.\nVariable P Q      : nat -> Prop.\nVariable f        : nat -> nat.\n\nTheorem e51: forall x:nat, exists y:nat, (P(x)->P(y)).\nProof.\n  intros.\n  exists x.\n  intro;assumption.\nQed.\n\nTheorem e52: exists x:nat, (P x)\n                            -> (forall y:nat, (P y)->(Q y))\n                               -> (exists z:nat, (Q z)).\nProof.\n  exists a;intros.\n  exists a.\n  apply (H0 a).\n  assumption.\nQed.\n\n\nTheorem e53: even(a) -> (forall x:nat, (even(x)->odd (S(x)))) -> exists y: nat, odd(y).\nProof.\n  intros.\n  exists (S a).\n  apply (H0 a).\n  assumption.\nQed.\n\n\nTheorem e54: (forall x:nat, P(x) /\\ odd(x) ->even(f(x)))\n                            -> (forall x:nat, even(x)->odd(S(x)))\n                            -> even(a)\n                            -> P(S(a))\n                            -> exists z:nat, even(f(z)).\nProof.\n  intros.\n  exists (S a).\n  apply (H (S a)).\n  split.\n  assumption.\n  apply (H0 a).\n  assumption.  \nQed.\n\nEnd Ejercicio5.\n\n\nSection Ejercicio7.\n\nVariable U   : Set.\nVariable A B : U -> Prop.\n\nTheorem e71: (forall x:U, ((A x) /\\ (B x)))\n                       -> (forall x:U, (A x)) /\\ (forall x:U, (B x)).\nProof.\n  intro; split; intros; apply (H x).  \nQed.\n\nTheorem e72: (exists x:U, (A x \\/ B x))->(exists x:U, A x )\\/(exists x:U, B x).\nProof.\n  intro; elim H; intros; elim H0; intros; [left|right]; exists x; assumption.  \nQed.\n\nEnd Ejercicio7.\n\n\nSection Ejercicio8.\nVariable U   : Set.\nVariable T V : U -> Prop.\nVariable R   : U -> U -> Prop.\n\nTheorem e81: (exists y:U, forall x:U, R x y) \n                      -> (forall x:U, exists y:U, R x y).\nProof.\n  intros.\n  elim H.\n  intros.\n  exists x0.\n  apply (H0 x).\nQed.\n\n\nTheorem T282: (exists y:U, True) /\\ (forall x:U, (T x) \\/ (V x)) \n                          -> (exists z:U, (T z)) \\/ (exists w:U, (V w)).\nProof.\n  intro.\n  elim H.\n  intros.\n  elim H0.\n  intros.\n  assert (T x \\/ V x).\n  apply (H1 x).\n  elim H3; intro; [left | right]; exists x; assumption. \nQed.\n\n(* La condición (exists y:U, True) es necesaria para la prueba del teorema\n   anterior, ya que necesito que exista al menos un elemento x de tipo U.\n   Para probar el consecuente:  (exists z:U, (T z)) \\/ (exists w:U, (V w))\n   es necesario encontrar un testigo para al menos uno de los 2 lados de \n   la disjunción. De no tener la condición mencionada anteriormente, no \n   podré encontrar dicho testigo, y por ende no seguirá siendo cierto para\n   cualquier tipo U (si no hay elementos de tipo U la proposición será falsa).\n*)\n\nEnd Ejercicio8.\n\n\nSection Ejercicio9.\nRequire Import Classical.\nVariables U : Set.\nVariables A : U -> Prop.\n\nLemma not_ex_not_forall: (~exists x :U, ~A x) -> (forall x:U, A x).\nProof.\n  intros.\n  elim(classic(A x));intro.\n  assumption.\n  unfold not in H.\n  elim H.\n  exists x.\n  intro.\n  absurd (A x);assumption.\nQed.\n\nTheorem contrarreciproco: forall x y: Prop, (~y -> ~x) -> (x -> y).\nProof.\n  intros.\n  elim(classic y); intro.\n  assumption.\n  absurd x; [apply H|];assumption.\nQed.\n\nTheorem doble_negacion: forall x : Prop, x -> ~~x.\nProof.\n  unfold not.\n  intros.\n  exact (H0 H).\nQed.\n\nLemma not_forall_ex_not: (~forall x :U, A x) -> (exists x:U,  ~A x).\nProof.\n  apply (contrarreciproco (~forall x :U, A x) (exists x:U,  ~A x)).\n  intro.\n  apply (doble_negacion (forall x:U, A x)).\n  apply not_ex_not_forall.\n  assumption.  \nQed.\n\nEnd Ejercicio9.\n\n\nSection Ejercicio10y11.\n\nVariable nat : Set.\nVariable  O  : nat.\nVariable  S  : nat -> nat.\n\nAxiom disc   : forall n:nat, ~O=(S n).\nAxiom inj    : forall n m:nat, (S n)=(S m) -> n=m.\n\nVariable sum prod : nat->nat->nat.\nAxiom sum0   : forall n :nat, (sum n O)=n.\nAxiom sumS   : forall n m :nat, (sum n (S m))=(S (sum n m)).\nAxiom prod0  : forall n :nat, (prod n O)=O.\nAxiom prodS  : forall n m :nat, (prod n (S m))=(sum n (prod n m)).\n\n(* Ej. 10 *)\n\nLemma L10_1: (sum (S O) (S O)) = (S (S O)).\nProof.\n  rewrite -> (sumS (S O) O).\n  rewrite -> (sum0 (S O)).\n  reflexivity.\nQed.\n\nLemma L10_2: forall n :nat, ~(O=n /\\ (exists m :nat, n = (S m))).\nProof.\n  unfold not.\n  intros.\n  elim H; intros.\n  elim H1; intros.  \n  apply (disc x).\n  rewrite -> H0.\n  assumption.\nQed.\n\nLemma prod_neutro: forall n :nat, (prod n (S O)) = n.\nProof.\n  intro.\n  rewrite -> (prodS n O).\n  rewrite -> (prod0 n).\n  rewrite -> (sum0 n).\n  reflexivity.\nQed.\n\nLemma diff: forall n:nat, ~(S (S n))=(S O).\nProof.\n  intro.\n  unfold not.\n  intro.\n  elim (disc n). \n  symmetry.\n  apply (inj).\n  assumption.\nQed.\n\n(* Principio de inducción *)\nAxiom induction: forall n:nat, forall P : nat -> Prop,\n                              (P O) /\\ (forall k: nat, P k -> P (S k)) -> P n.\n\n(* Ej. 11 *)\n\nVariable le : nat->nat->Prop.\nAxiom leinv: forall n m:nat, (le n m) -> n=O \\/\n      (exists p:nat, (exists q:nat, n=(S p)/\\ m=(S q) /\\ (le p q))).\n\nLemma notle_s_o: forall n:nat, ~(le (S n) O).\nProof.\n  unfold not.  \n  intros.\n  elim (leinv (S n) O); intros.\n  apply (disc n).\n  symmetry.\n  assumption.\n  elim H0.\n  intros.\n  elim H1.\n  intros.\n  apply (disc x0).\n  apply H2.\n  assumption.  \nQed.\n\nEnd Ejercicio10y11.\n", "meta": {"author": "adrielulanovsky", "repo": "Coq", "sha": "f75a35e28d171239ec6c8af3f24b64dc04628202", "save_path": "github-repos/coq/adrielulanovsky-Coq", "path": "github-repos/coq/adrielulanovsky-Coq/Coq-f75a35e28d171239ec6c8af3f24b64dc04628202/TP2/AdrielUlanovsky.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7481799391411078}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\n\nOpen Scope Z_scope.\n\nGoal forall base a b c d: Z,\n  0 <= a < base ->\n  0 <= b < base ->\n  0 <= c < base ->\n  0 <= d < base ->\n  base * a + b = base * c + d ->\n  b = d.\nProof.\n  intros.\n  pose proof Z.mod_unique as P.\n  specialize P with (b := base) (q := c) (r := d).\n  specialize P with (2 := H3).\n  rewrite P by lia.\n  rewrite <- Z.add_mod_idemp_l by lia.\n  rewrite Z.mul_comm.\n  rewrite Z.mod_mul by lia.\n  rewrite Z.add_0_l.\n  rewrite Z.mod_small by lia.\n  reflexivity.\nQed.\n\n(* If we turn this goal into smtlib language using the tactics and notations in smt_demo.v,\n   we get the following:\n\n  (declare-const a Int)\n  (declare-const a0 Int)\n  (declare-const a1 Int)\n  (declare-const a2 Int)\n  (declare-const a3 Int)\n  (assert (not (implies (and (<= 0 a0) (< a0 a))\n                (implies (and (<= 0 a1) (< a1 a))\n                 (implies (and (<= 0 a2) (< a2 a))\n                  (implies (and (<= 0 a3) (< a3 a))\n                   (implies (= (+ ( * a a0) a1) (+ ( * a a2) a3)) (= a1 a3))))))))\n  (check-sat)\n\nbut Z3 returns \"unknown\"\n*)\n", "meta": {"author": "samuelgruetter", "repo": "coq-smt-notations", "sha": "3c96c462e1e0b95b6d305e472b34e7c5095d10cb", "save_path": "github-repos/coq/samuelgruetter-coq-smt-notations", "path": "github-repos/coq/samuelgruetter-coq-smt-notations/coq-smt-notations-3c96c462e1e0b95b6d305e472b34e7c5095d10cb/unknown.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629194, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7481745782695444}}
{"text": "Require Import Psatz Reals.\nRequire Import Interval.Tactic.\nLocal Open Scope R_scope.\n\nLemma exp_lt_pow4 :\n  forall n : nat, exp (INR n) <= 2^(n * 2).\nProof.\n  induction n. simpl. interval.\n  replace (INR (S n)) with (1 + INR n) by (destruct n; simpl; lra).\n  rewrite exp_plus.\n  replace ((S n) * 2)%nat with (2 + n * 2)%nat by lia.\n  rewrite pow_add. replace (2^2) with 4 by (simpl; lra).\n  assert (exp 1 <= 4) by (specialize exp_le_3 as G; lra).\n  assert (0 < exp 1) by apply exp_pos.\n  assert (0 < exp (INR n)) by apply exp_pos.\n  nra.\nQed.\n\nLemma log_bound :\n  forall n, (0 < n)%nat -> INR (Nat.log2 n) <= 2 * ln (INR n).\nProof.\n  intros. rewrite <- ln_exp with (x := INR (Nat.log2 n)).\n  specialize exp_lt_pow4 with (n := Nat.log2 n) as G.\n  rewrite pow_mult in G.\n  assert (2 ^ Nat.log2 n <= INR n).\n  { replace 2 with (INR 2) by easy.\n    rewrite <- pow_INR. apply le_INR.\n    specialize (Nat.log2_spec n H) as T.\n    easy.\n  }\n  assert (0 < 2 ^ Nat.log2 n).\n  { replace 2 with (INR 2) by easy.\n    rewrite <- pow_INR. apply lt_0_INR.\n    assert (2 <> 0)%nat by easy.\n    specialize (Nat.pow_nonzero _ (Nat.log2 n) H1) as T.\n    lia.\n  }\n  replace 2 with (INR 2) by easy.\n  rewrite <- Rcomplements.ln_pow by (apply lt_0_INR; easy).\n  apply Rcomplements.ln_le. apply exp_pos.\n  replace (INR n ^ 2) with (INR n * INR n) by (simpl; lra).\n  replace ((2 ^ Nat.log2 n) ^ 2) with ((2 ^ Nat.log2 n) * (2 ^ Nat.log2 n)) in G by (simpl; lra).\n  assert (2 ^ Nat.log2 n * 2 ^ Nat.log2 n <= INR n * INR n) by nra.\n  lra.\nQed.\n", "meta": {"author": "taorunz", "repo": "euler", "sha": "5fcf1db4d5a68f0d55118fb2733cede2cc515a23", "save_path": "github-repos/coq/taorunz-euler", "path": "github-repos/coq/taorunz-euler/euler-5fcf1db4d5a68f0d55118fb2733cede2cc515a23/Log.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7481156562027584}}
{"text": "From Coq.Logic Require Import\n  Classical_Prop Classical_Pred_Type.\n\nFrom stdpp Require Import base.\n\nModule classical.\n\n  Lemma not_forall {A: Type} (P: A → Prop) :\n    ¬ (∀ x, P x) ↔ (∃ x, ¬ P x).\n  Proof.\n    split.\n    - apply not_all_ex_not.\n    - intros [x HP] H.\n      eauto.\n  Qed.\n\n  Lemma not_exists {A: Type} (P: A → Prop) :\n    ¬ (∃ x, P x) ↔ (∀ x, ¬ P x).\n  Proof.\n    split.\n    - apply not_ex_all_not.\n    - intros HnotP [x HP].\n      eapply HnotP; eauto.\n  Qed.\n\n  Lemma double_negation (P: Prop) : (~~P) ↔ P.\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma not_or (P Q: Prop) : ~(P ∨ Q) ↔ (~P) ∧ (~Q).\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma not_and (P Q: Prop) : ~(P ∧ Q) ↔ (~P) ∨ (~Q).\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma excluded_middle (P: Prop) : P ∨ ~P.\n    tauto.\n  Qed.\n\nEnd classical.\n", "meta": {"author": "tchajed", "repo": "coq-tla", "sha": "b2973089a67646614720c27031f9dde8ff2f82f6", "save_path": "github-repos/coq/tchajed-coq-tla", "path": "github-repos/coq/tchajed-coq-tla/coq-tla-b2973089a67646614720c27031f9dde8ff2f82f6/src/classical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7481037898593215}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf3 : natural) : natural :=\n  plus lf1 (plus Zero lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj111_coqofml_Vlxzgi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7481003314370789}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint even (even_arg0 : natural) : bool\n           := match even_arg0 with\n              | Zero => true\n              | Succ n => negb (even n)\n              end.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\nLemma lem: forall l1 l2 n, negb (even (len (append l1 l2))) = even (len (append l1 (Cons n l2))).\nProof.\ninduction l1.\n  - intros. simpl. rewrite (IHl1 l2 n0). reflexivity.\n  - intros. simpl. reflexivity.\nQed.\n\nLemma lem3: forall l, append l Nil = l.\nProof.\ninduction l.\n  - simpl. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (even (len (append x y))) (even (len (append y x))).\nProof.\ninduction x.\n  - intros. simpl. rewrite <- lem. f_equal. rewrite IHx. reflexivity.\n  - intros. simpl. rewrite lem3. reflexivity.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal22.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7480715742863874}}
{"text": "Require Import Frap.\n\n\n(* We begin with a return to our arithmetic language from the last chapter,\n * adding subtraction*, which will come in handy later.\n * *: good pun, right? *)\nInductive arith : Set :=\n| Const (n : nat)\n| Var (x : var)\n| Plus (e1 e2 : arith)\n| Minus (e1 e2 : arith)\n| Times (e1 e2 : arith).\n\nExample ex1 := Const 42.\nExample ex2 := Plus (Var \"y\") (Times (Var \"x\") (Const 3)).\n\nDefinition valuation := fmap var nat.\n(* A valuation is a finite map from [var] to [nat]. *)\n\n(* The interpreter is a fairly innocuous-looking recursive function. *)\nFixpoint interp (e : arith) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x =>\n    (* Note use of infix operator to look up a key in a finite map. *)\n    match v $? x with\n    | None => 0 (* goofy default value! *)\n    | Some n => n\n    end\n  | Plus e1 e2 => interp e1 v + interp e2 v\n  | Minus e1 e2 => interp e1 v - interp e2 v\n                   (* For anyone who's wondering: this [-] sticks at 0,\n                    * if we would otherwise underflow. *)\n  | Times e1 e2 => interp e1 v * interp e2 v\n  end.\n\n(* Here's an example valuation, using an infix operator for map extension. *)\nDefinition valuation0 : valuation :=\n  $0 $+ (\"x\", 17) $+ (\"y\", 3).\n\nTheorem interp_ex1 : interp ex1 valuation0 = 42.\nProof.\n  simplify.\n  equality.\nQed.\n\nTheorem interp_ex2 : interp ex2 valuation0 = 54.\nProof.\n  unfold valuation0.\n  simplify.\n  equality.\nQed.\n\n(* Here's the silly transformation we defined last time. *)\nFixpoint commuter (e : arith) : arith :=\n  match e with\n  | Const _ => e\n  | Var _ => e\n  | Plus e1 e2 => Plus (commuter e2) (commuter e1)\n  | Minus e1 e2 => Minus (commuter e1) (commuter e2)\n                   (* ^-- NB: didn't change the operand order here! *)\n  | Times e1 e2 => Times (commuter e2) (commuter e1)\n  end.\n\n(* Instead of proving various odds-and-ends properties about it,\n * let's show what we *really* care about: it preserves the\n * *meanings* of expressions! *)\nTheorem commuter_ok : forall v e, interp (commuter e) v = interp e v.\nProof.\nAdmitted.\n\n(* Let's also revisit substitution. *)\nFixpoint substitute (inThis : arith) (replaceThis : var) (withThis : arith) : arith :=\n  match inThis with\n  | Const _ => inThis\n  | Var x => if x ==v replaceThis then withThis else inThis\n  | Plus e1 e2 => Plus (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n  | Minus e1 e2 => Minus (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n  | Times e1 e2 => Times (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n  end.\n\n(* How should we state a correctness property for [substitute]?\nTheorem substitute_ok : forall v replaceThis withThis inThis,\n  ...\nProof.\n\nQed.*)\n\n(* Let's also defined a pared-down version of the expression-simplificaton\n * functions from last chapter. *)\nFixpoint doSomeArithmetic (e : arith) : arith :=\n  match e with\n  | Const _ => e\n  | Var _ => e\n  | Plus (Const n1) (Const n2) => Const (n1 + n2)\n  | Plus e1 e2 => Plus (doSomeArithmetic e1) (doSomeArithmetic e2)\n  | Minus e1 e2 => Minus (doSomeArithmetic e1) (doSomeArithmetic e2)\n  | Times (Const n1) (Const n2) => Const (n1 * n2)\n  | Times e1 e2 => Times (doSomeArithmetic e1) (doSomeArithmetic e2)\n  end.\n\nTheorem doSomeArithmetic_ok : forall e v, interp (doSomeArithmetic e) v = interp e v.\nProof.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(* Of course, we're going to get bored if we confine ourselves to arithmetic\n * expressions for the rest of our journey.  Let's get a bit fancier and define\n * a *stack machine*, related to postfix calculators that some of you may have\n * experienced. *)\nInductive instruction :=\n| PushConst (n : nat)\n| PushVar (x : var)\n| Add\n| Subtract\n| Multiply.\n\n(* What does it all mean?  An interpreter tells us unambiguously! *)\nDefinition run1 (i : instruction) (v : valuation) (stack : list nat) : list nat :=\n  match i with\n  | PushConst n => n :: stack\n  | PushVar x => (match v $? x with\n                  | None => 0\n                  | Some n => n\n                  end) :: stack\n  | Add =>\n    match stack with\n    | arg2 :: arg1 :: stack' => arg1 + arg2 :: stack'\n    | _ => stack (* arbitrary behavior in erroneous case (stack underflow) *)\n    end\n  | Subtract =>\n    match stack with\n    | arg2 :: arg1 :: stack' => arg1 - arg2 :: stack'\n    | _ => stack (* arbitrary behavior in erroneous case *)\n    end\n  | Multiply =>\n    match stack with\n    | arg2 :: arg1 :: stack' => arg1 * arg2 :: stack'\n    | _ => stack (* arbitrary behavior in erroneous case *)\n    end\n  end.\n\n(* That function explained how to run one instruction.\n * Here's how to run several of them. *)\nFixpoint run (is : list instruction) (v : valuation) (stack : list nat) : list nat :=\n  match is with\n  | nil => stack\n  | i :: is' => run is' v (run1 i v stack)\n  end.\n\n(* Instead of writing fiddly stack programs ourselves, let's *compile*\n * arithmetic expressions into equivalent stack programs. *)\nFixpoint compile (e : arith) : list instruction :=\n  match e with\n  | Const n => PushConst n :: nil\n  | Var x => PushVar x :: nil\n  | Plus e1 e2 => compile e1 ++ compile e2 ++ Add :: nil\n  | Minus e1 e2 => compile e1 ++ compile e2 ++ Subtract :: nil\n  | Times e1 e2 => compile e1 ++ compile e2 ++ Multiply :: nil\n  end.\n\nTheorem compile_ok : forall e v, run (compile e) v nil = interp e v :: nil.\nProof.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(* Let's get a bit fancier, moving toward the level of general-purpose\n * imperative languages.  Here's a language of commands, building on the\n * language of expressions we have defined. *)\nInductive cmd :=\n| Skip\n| Assign (x : var) (e : arith)\n| Sequence (c1 c2 : cmd)\n| Repeat (e : arith) (body : cmd).\n\nFixpoint selfCompose {A} (f : A -> A) (n : nat) : A -> A :=\n  match n with\n  | O => fun x => x\n  | S n' => fun x => selfCompose f n' (f x)\n  end.\n\nFixpoint exec (c : cmd) (v : valuation) : valuation :=\n  match c with\n  | Skip => v\n  | Assign x e => v $+ (x, interp e v)\n  | Sequence c1 c2 => exec c2 (exec c1 v)\n  | Repeat e body => selfCompose (exec body) (interp e v) v\n  end.\n\n(* Let's define some programs and prove that they operate in certain ways. *)\n\nExample factorial_ugly :=\n  Sequence\n    (Assign \"output\" (Const 1))\n    (Repeat (Var \"input\")\n            (Sequence\n               (Assign \"output\" (Times (Var \"output\") (Var \"input\")))\n               (Assign \"input\" (Minus (Var \"input\") (Const 1))))).\n\n(* Ouch; that code is hard to read.  Let's introduce some notations to make the\n * concrete syntax more palatable.  We won't explain the general mechanisms on\n * display here, but see the Coq manual for details, or try to reverse-engineer\n * them from our examples. *)\nCoercion Const : nat >-> arith.\nCoercion Var : var >-> arith.\n(*Declare Scope arith_scope.*)\nInfix \"+\" := Plus : arith_scope.\nInfix \"-\" := Minus : arith_scope.\nInfix \"*\" := Times : arith_scope.\nDelimit Scope arith_scope with arith.\nNotation \"x <- e\" := (Assign x e%arith) (at level 75).\nInfix \";\" := Sequence (at level 76).\nNotation \"'repeat' e 'doing' body 'done'\" := (Repeat e%arith body) (at level 75).\n\n(* OK, let's try that program again. *)\nExample factorial :=\n  \"output\" <- 1;\n  repeat \"input\" doing\n    \"output\" <- \"output\" * \"input\";\n    \"input\" <- \"input\" - 1\n  done.\n\n(* Now we prove that it really computes factorial.\n * First, a reference implementation as a functional program. *)\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => n * fact n'\n  end.\n\nTheorem factorial_ok : forall v input,\n  v $? \"input\" = Some input\n  -> exec factorial v $? \"output\" = Some (fact input).\nProof.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(* One last example: let's try to do loop unrolling, for constant iteration\n * counts.  That is, we can duplicate the loop body instead of using an explicit\n * loop. *)\n\n(* This obvious-sounding fact will come in handy: self-composition gives the\n * same result, when passed two functions that map equal inputs to equal\n * outputs. *)\nLemma selfCompose_extensional : forall {A} (f g : A -> A) n x,\n  (forall y, f y = g y)\n  -> selfCompose f n x = selfCompose g n x.\nProof.\n  induct n; simplify; try equality.\n\n  rewrite H.\n  apply IHn.\n  trivial.\nQed.\n\n(*Theorem unroll_ok : forall c v, exec (unroll c) v = exec c v.\nProof.\n\nQed.*)\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/Interpreters_template.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7480715678668167}}
{"text": "Require Import List Logic Nat Omega FunctionalExtensionality ExtensionalityFacts ChoiceFacts Wellfounded Classical.\nRequire Import Compare_dec EqNat Decidable ListDec FinFun.\nRequire Fin. \nImport ListNotations.\nFrom Block  \nRequire Import finite lib definitions ramsey. \n\n(* ********************* *)\n(* **** Finite-hood **** *)\n(* ********************* *)\n\n(* Words up to length n are finite *)  \nLemma wordlength_finite : forall (n : nat),\n    is_finite (fun (w : word) => length w <= n).\nProof.\n  unfold is_finite. \n  induction n as [|n IHn].  \n  + (* When length is zero, finite because no words exist *)\n    exists [[]; []]. intro w; split.\n    (* Left direction *) \n    ++ intro H_absurd; inversion H_absurd.\n       rewrite <- H; reflexivity.\n       inversion H. \n       rewrite <- H0; reflexivity. inversion H0. \n    (* Right direction *) \n    ++ intro H_length; inversion H_length.\n       rewrite length_zero_iff_nil in H0.\n       rewrite H0. constructor. reflexivity. \n  + (* When the length is n, finite because adding an extra symbol\n       onto all words in a finite list of words keeps the list finite *)  \n    destruct IHn as [L IHn].\n    exists (map (fun w => aa :: w) L ++ \n           map (fun w => bb :: w) L ++ \n           map (fun w => cc :: w) L ++ L).\n    intro w; split; intros H.\n    (* Left direction *) \n    ++ repeat rewrite in_app_iff in H; \n         repeat rewrite in_map_iff in H.  \n       destruct H as [[h [H_h H_mem]] |\n                      [[h [H_h H_mem]] |\n                       [[h [H_h H_mem]] | ?]]]. \n       (* When the word is in appended original list *) \n       +++ spec IHn h. \n           rewrite <- H_h.\n           apply IHn in H_mem.\n           rewrite unfold_length_S.\n           apply (le_n_S (length h) n); exact H_mem.\n       +++ spec IHn h. \n           rewrite <- H_h.\n           apply IHn in H_mem.\n           rewrite unfold_length_S.\n           apply (le_n_S (length h) n); exact H_mem.\n       +++ spec IHn h. \n           rewrite <- H_h.\n           apply IHn in H_mem.\n           rewrite unfold_length_S.\n           apply (le_n_S (length h) n); exact H_mem.\n       (* When the word is in the original list *) \n       +++ constructor.\n           spec IHn w.\n           apply IHn in H.\n           exact H.\n    (* Right direction *) \n    ++ repeat rewrite in_app_iff; repeat rewrite in_map_iff.\n       apply le_lt_or_eq in H.\n       destruct H as [H_lt | H_eq].\n       +++ spec IHn w.\n           apply lt_n_Sm_le in H_lt.\n           apply IHn in H_lt.\n           right; right; right; exact H_lt. \n       +++ destruct w. \n           inversion H_eq.\n           spec IHn w.\n           rewrite unfold_length_S in H_eq.\n           apply Nat.succ_inj in H_eq.\n           rewrite H_eq in IHn.\n           assert (n <= n) by omega.\n           apply IHn in H.\n           destruct t.\n           left; exists w.\n           split; try reflexivity; assumption.\n           right; left; exists w; split; try reflexivity; assumption.\n           right; right; left; exists w; split; try reflexivity; assumption.\nQed.\n\nDefinition grow_lang (L : language) (new : word) : language :=\n  fun w => L w \\/ w = new.\n\n(* Languages containing words in some finite set of words are finite *) \nLemma shortlang_finite : forall (LW : list word),\n    is_finite (fun L : word -> Prop => forall w : word, L w -> In w LW).\nProof.\n  intros LW.  \n  induction LW as [|hd tl IHl].\n  (* When the list of words is empty, the language is empty *) \n  + exists ((fun w : word => False) :: nil).\n    intro L; split.\n    ++ intros H w H_mem.\n       inversion H.\n       rewrite <- H0 in H_mem.\n       contradiction.\n       inversion H0. \n    ++ intro H.\n       unfold In.\n       left. apply functional_extensionality.\n       intro abword.\n       apply prop_ext. split.\n       intro false; inversion false.\n       intro Habsurd; spec H abword; apply H in Habsurd.\n       inversion Habsurd.\n  (* When the list of words is non-empty, *) \n  + destruct IHl as [LS IHl].  \n    (* LS is a list of languages containing only words in tl *)\n    (* Now I need to construct a list of languages containing words in hd :: tl *)\n    unfold is_finite.\n    exists (LS ++ (map (fun L => grow_lang L hd) LS)).\n    \n    intros lang; split; intros.\n    simpl. \n    apply in_app_or in H.\n    destruct H. \n    right.\n    (* *)\n    spec IHl lang. destruct IHl. spec H1 H. apply H1. exact H0.\n    case_eq (word_eq hd w); intro.\n    left. rewrite word_eq_refl in H1. assumption. right.\n    rewrite in_map_iff in H.\n    destruct H as [lang' [? ?]].\n    spec IHl lang'.  \n    rewrite IHl in H2. apply H2. unfold grow_lang in H.\n    subst lang. destruct H0. assumption.\n    rewrite word_eq_refl' in H1. symmetry in H; contradiction.\n    apply in_or_app.    \n    destruct (classic (lang hd)).    \n    right.\n    rewrite in_map_iff. \n    set (lang' := fun w => lang w /\\ w <> hd).\n    exists lang'.\n    split.\n    unfold grow_lang, lang'.\n    apply functional_extensionality. intro w. apply prop_ext; split; intro.\n    destruct H1. tauto. rewrite H1. apply H0.\n    case_eq (word_eq w hd); intro.\n    right. rewrite word_eq_refl in H2. assumption.\n    rewrite word_eq_refl' in H2. tauto. \n    rewrite IHl.\n    intros.\n    spec H w.\n    unfold lang' in H1. destruct H1.\n    spec H H1. destruct H; auto.\n    symmetry in H. contradiction.\n    left. \n    apply IHl.\n    intros.\n    spec H w H1. destruct H. 2 : auto. subst hd. contradiction.\nQed.\n\n\n(* ******************* *)\n(* **** Factories **** *)\n(* ******************* *)\n\n(* A function which takes a language and returns a language\n   which only accepts the short strings from that language *)\n(* Wrong version had an extra universal quantifier *) \nDefinition filter_shortlang (n : nat) : language -> language :=\n  fun L : language => (fun w : word => L w /\\ length w <= n).\n\n(* Sanity check for filter_shortlang *)\nLemma filter_shortlang_sane :\n  forall n1 n2,\n    n1 < n2 ->\n    forall (L : language) (w : word), \n      filter_shortlang n1 L w -> filter_shortlang n2 L w.\nProof.\n  intros n1 n2 H_lt L w H_in_longer. \n  unfold filter_shortlang in *. \n  destruct H_in_longer; split; try assumption.\n  omega.\nQed. \n\n\n(* ************************* *)\n(* **** Proving two-ish **** *)\n(* ************************* *)\n\nDefinition is_cancellable (L : language) (w : word) :=\n  fun i j => L (firstn i w ++ skipn j w). \n\nLemma twoish_two : forall k : block_pumping_constant, \n    exists rk : block_pumping_constant,\n      forall L1 L2 : language, \n        block_cancellable_matching_with k L1 ->\n        block_cancellable_matching_with k L2 ->\n        (forall w, length w <= rk ->\n              L1 w <-> L2 w) ->\n        forall w, L1 w <-> L2 w.\nProof.\n  intros k. \n  assert (H_ramsey := Theorem_of_Ramsey_duo_prop k). \n  destruct H_ramsey as [rk [H_lt H_ramsey]]. \n  exists rk. \n  intros L1 L2 H_L H_L' H_length w. \n  (** Setting the strong induction on word length **)\n  remember (length w) as n.  \n  assert (H_move := Nat.eq_refl (length w)).\n  rewrite <- Heqn in H_move at 2. clear Heqn. \n  generalize dependent w. \n  induction n as [|n IHn] using strong_induction; intros w H_w_length.\n  - (* In the trivial base case *)\n    spec H_length w.\n    assert (0 <= rk) by omega.\n    rewrite H_w_length in H_length; spec H_length H; assumption.\n  - (* In the inductive case, with all shorter words satisfying P *)\n    assert (n < rk \\/ n >= rk) by omega.\n    destruct H as [H_short | H_long].\n    + (* In the case that the words are shorter than rk, trivial *)\n      assert (length w <= rk) by omega.\n      spec H_length w H; assumption. \n    + (* In the case that the words are longer than rk, but all shorter words satisfy *)\n      (** Constructing a (breakpoint_set rk w d) which enumerates all the slots *)\n      remember (iota 1 rk) as bp_list.\n      assert (bp_list_pred : breakpoint_set_predicate bp_list w rk).\n      rewrite Heqbp_list.\n      { unfold breakpoint_set_predicate; split.\n        rewrite length_iota; reflexivity.\n        split.\n        apply (iota_increasing 1 rk definitions.d).\n        assert (H_useful := last_indep (iota 1 rk)).\n        destruct H_useful as [H_absurd | H_useful]. \n        destruct H_absurd as [H_absurd _].\n        subst bp_list.\n        assert (rk >= 1).\n        { destruct k as [k about_k]; unfold p_predicate in about_k.\n          simpl in H_lt; omega. }\n        assert (length (iota 1 rk) = rk) by apply length_iota.\n        rewrite H_absurd in H0.\n        unfold length in H0; omega.\n        destruct H_useful as [H_non_nil H_useful].\n        spec H_useful definitions.d 0.\n        rewrite H_useful.\n        rewrite iota_last. omega. } \n      (* Explicitly tell Coq the sigma-type here - must remember! *)\n      spec H_ramsey w (exist _ bp_list bp_list_pred : breakpoint_set rk w). \n      (** Trying Ramsey's Theorem with two colors **)\n      spec H_ramsey (is_cancellable L1 w). \n      (* Setting up the context variables for the case analysis *)\n      destruct H_ramsey as [bps' H_ramsey].\n      simpl in * (* Bookkeeping to refold the sigma-types *).\n      assert (IHn' := IHn).\n      spec H_L w bps'; spec H_L' w bps';\n      destruct H_L as [bp1 [bp2 [H_bp_lt H_L]]];\n      assert (H_bc1 : length (firstn bp1 w ++ skipn bp2 w) < length w).\n      apply about_pump_length; assumption.\n      spec IHn (length (firstn bp1 w ++ skipn bp2 w));\n      rewrite <- H_w_length in IHn; spec IHn H_bc1;\n      spec IHn (firstn bp1 w ++ skipn bp2 w)\n           (eq_refl (length (firstn bp1 w ++ skipn bp2 w))).\n      destruct H_L' as [bp1' [bp2' [H_bp'_lt H_L']]];\n      assert (H_bc2 : length (firstn bp1' w ++ skipn bp2' w) < length w).\n      apply about_pump_length; assumption.\n      spec IHn' (length (firstn bp1' w ++ skipn bp2' w));\n      rewrite <- H_w_length in IHn'; spec IHn' H_bc2;\n      spec IHn' (firstn bp1' w ++ skipn bp2' w)\n           (eq_refl (length (firstn bp1' w ++ skipn bp2' w))).\n      clear -H_ramsey H_bp_lt H_bp'_lt H_L H_L' IHn IHn' H_bp_lt. \n      (* Case analysis on additional information about breakpoints *) \n      destruct H_ramsey as [H_sublist [case1 | case0]].  \n      ++ (* Ramsey cancels word into L1 *)\n        (* L2's breakpoints also work for L1 *)\n        split; intro H.\n        spec case1 bp1' bp2' H_bp'_lt;\n          unfold is_cancellable in case1; tauto.\n        spec case1 bp1 bp2 H_bp_lt;\n          unfold is_cancellable in case1; tauto. \n      ++ (* Ramsey cancels word into L2 *)\n        (* L1's breakpoints work for itself *)\n        split; intro H.\n         spec case0 bp1 bp2 H_bp_lt;\n          unfold is_cancellable in case0; tauto.\n        spec case0 bp1' bp2' H_bp'_lt;\n          unfold is_cancellable in case0; tauto.\nQed.\n\n(* ***************** *)\n(* **** Lemma 2 **** *)\n(* ***************** *)\n\n(* inj_finite\n     : forall (P : X -> Prop) (Q : Y -> Prop)\n         (f : {x : X | P x} -> {y : Y | Q y}),\n       inhabited {x : X | P x} ->\n       injective P Q f ->\n       is_finite_dep Q -> \n       is_finite_dep P *)\n\n(* We require the following building blocks for our grand finale: \n   X : {l | BC(k,l)} \n   Y : {l | short_lang l} \n   P : BC(k)\n   Q : short \n   f : dependent length shearing function \n   injective f \n   is_finite Q\n   inhabited X \n *)\n\n(*****)\n(* P *)\n(*****)\n\n(* This line causes Coq universe inconsistency! \nCoercion bc_language_proj1 : bc_language >-> language. *) \n\n(***************)\n(* inhabited X *)\n(***************)\nLemma inhabited_bc : forall k : block_pumping_constant, inhabited (bc_language k).\nProof.\n  intros k.\n  (* Constructing an absurd language that can still have breakpoints *) \n  remember ((fun w => False) : language) as absurd. \n  assert (bc_sigma k absurd).\n  { unfold bc_sigma. intros w bps.\n    exists (get_bp1_from_bps bps).\n    exists (get_bp2_from_bps bps).\n    split.\n    unfold get_bp1_from_bps, get_bp2_from_bps.\n    simpl.\n    destruct bps as [x about_bps]. \n    (* Destruction/inversion until I reveal two elements *)\n    destruct x as [_ | x].\n    { unfold breakpoint_set_predicate in about_bps.\n      destruct k as [k about_k]; unfold p_predicate in about_k.\n      destruct about_bps as [H_length H_incr H_last].\n      simpl in H_length. omega. }\n    destruct x0 as [_ | x0].\n    { unfold breakpoint_set_predicate in about_bps.\n      destruct k as [k about_k]; unfold p_predicate in about_k.\n      destruct about_bps as [H_length H_incr H_last].\n      simpl in H_length. omega. }\n    simpl.\n    unfold breakpoint_set_predicate in about_bps.\n    destruct about_bps as [H_length [H_incr H_last]].\n    unfold increasing in H_incr.\n    spec H_incr 0 1.\n    assert (0 < 1 < length (x::x0::x1)). simpl; omega.\n    spec H_incr H.\n    unfold nth in H_incr. assumption.\n    split; intro H_absurd_mem;\n      subst absurd; contradiction. } \n  (* Finally we have our witness *)\n  constructor. exists absurd. assumption.\nQed.\n\n(*****) (*****)\n(* Y *) (* Q *)\n(*****) (*****)\nDefinition is_short_lang (n : nat) (L: language) : Prop :=\n  forall w : word, L w -> length w <= n.\n\nDefinition short_lang (n : nat) : Type :=\n  { l | is_short_lang n l}. \n\nDefinition short_lang_proj1 {n : nat} (sl : short_lang n) :=\n  match sl with\n  | exist _ b _ => b\n  end.\n\n(*****)\n(* f *)\n(*****)\nProgram Definition filter_shortbclang (k : block_pumping_constant) (rk : block_pumping_constant) :=\n  fun bcl : {l | bc_sigma k l} => exist (is_short_lang rk)\n                                     (filter_shortlang rk (bc_language_proj1 bcl))\n                                     _.\nNext Obligation.  \n  unfold is_short_lang, filter_shortlang;\n    intros; unfold bc_language_proj1;\n      destruct H0; assumption. \nDefined.\n(* filter_shortbclang\n     : forall k rk : nat,\n       {l : language | bc_sigma k l} -> {x : language | short_lang rk x} *)\n\n(***************)\n(* injective f *)\n(***************)\n(** This is the real statement of injectivity we want! **)\n(** Significantly, the precise way rk is dependent is super important **)\nLemma twoish_sigma : forall k : block_pumping_constant, \n    exists rk : block_pumping_constant,\n      forall BCL1 BCL2 : bc_language k, \n        block_cancellable_matching_with k (proj1_sig BCL1) ->\n        block_cancellable_matching_with k (proj1_sig BCL2) ->\n        (forall w, length w <= rk ->\n              (proj1_sig BCL1 w <-> proj1_sig BCL2 w)) ->\n        forall w, proj1_sig BCL1 w <-> proj1_sig BCL2 w.\nProof.\n  intro k.\n  assert (H_useful := twoish_two k).\n  destruct H_useful as [rk H_useful].\n  exists rk.\n  intros BCL1 BCL2.\n  destruct BCL1 as [L1 about_L1];\n    destruct BCL2 as [L2 about_L2].\n  spec H_useful L1 L2.\n  spec H_useful about_L1 about_L2.\n  simpl in *.\n  intros _ _ H w. \n  spec H_useful H.\n  exact (H_useful w). \nQed.\n\nTheorem real_injectivity :\n  forall (k : block_pumping_constant),\n  exists rk : block_pumping_constant,\n    injective (block_cancellable_matching_with k)\n              (is_short_lang rk)\n              (filter_shortbclang k rk). \nProof.\n  intros k. \n  assert (H_twoish := twoish_sigma k).\n  (* Using the sigma version doesn't prevent us from being destructive *) \n  destruct H_twoish as [rk H_twoish].\n  exists rk.\n  unfold injective, Injective. \n  intros bcx bcy H_length.\n  spec H_twoish bcx bcy.  \n  (* However, in order to use our equality lemma we must destruct *)\n  destruct bcx as [l1 about_l1];\n    destruct bcy as [l2 about_l2].\n  spec H_twoish about_l1 about_l2. \n  (* Two dependent languages are equal iff the languages are equal *) \n  apply language_equality_sigma. \n  simpl in *.\n  (* Two languages are equal iff forall words, they agree *) \n  apply language_equality.\n  (* Now we have the exact conclusion of H_twoish *) \n  assert (H_next : forall w : word, length w <= rk -> l1 w <-> l2 w).\n  { (* This needs to be proven using H_length *)\n    (* What does it mean for languages to be equal? *)\n    intros w w_length.\n    apply language_equality_sigma in H_length.\n    unfold bc_language_proj1 in H_length.\n    rewrite (language_equality (filter_shortlang rk l1)\n                               (filter_shortlang rk l2)) in H_length.\n    unfold filter_shortlang in H_length.\n    spec H_length w.\n    destruct H_length.\n    split; intros.\n    assert (H_away : l1 w /\\ length w <= rk). split; assumption. \n    spec H H_away; destruct H; assumption.\n    assert (H_away : l2 w /\\ length w <= rk). split; assumption.\n    spec H0 H_away; destruct H0; assumption. }\n  apply (H_twoish H_next).\nQed.\n\n(************)\n(* finite Q *)\n(************)\nLemma is_finite_sheared : forall n : nat,\n    is_finite (is_short_lang n). \nProof.\n  intro n.\n  destruct (wordlength_finite n) as [ws about_ws].\n  destruct (shortlang_finite ws) as [ls about_ls].\n  exists ls.\n  intro l; split.\n  intros H_l_mem w H_mem.\n  apply (about_ws w).\n  spec about_ls l.\n  destruct about_ls.\n  apply (H H_l_mem w); assumption.\n  intro H.\n  spec about_ls l. destruct about_ls.\n  apply H1. intros w H_l_mem.\n  spec H w. spec H H_l_mem.\n  spec about_ws w. destruct about_ws.\n  apply H3; assumption.  \nQed.\n\n(* Enter magical finite library! *)\nLemma is_finite_sheared_dep : forall n : nat,\n    is_finite_dep (is_short_lang n).  \nProof.\n  intro n.\n  assert (H_useful := is_finite_sheared n).\n  apply list_to_dep_list in H_useful. \n  assumption. \nQed.\n\n(*****************)\n(* Grand finale! *)\n(*****************)\nTheorem bc_k_is_finite_dep :\n  forall k : block_pumping_constant, is_finite_dep (bc_sigma k).\nProof.\n  intro k.\n  assert (H_real := real_injectivity k).\n  destruct H_real as [rk H_real].\n  generalize (is_finite_sheared_dep rk).\n  eapply (inj_finite \n            (bc_sigma k) (is_short_lang rk) (filter_shortbclang k rk)).\n  apply inhabited_bc.\n  exact H_real. \nQed.\n\nTheorem bc_k_is_finite :\n  forall k : block_pumping_constant, is_finite (bc_sigma k).\nProof. \n  intro k.\n  apply (is_finite_equiv (bc_sigma k)).\n  exact (bc_k_is_finite_dep k). \nQed.\n\nPrint Assumptions bc_k_is_finite. \n  ", "meta": {"author": "atufchoice", "repo": "blockpump", "sha": "678917d1177dd7cac9fc715d89ef28102a076654", "save_path": "github-repos/coq/atufchoice-blockpump", "path": "github-repos/coq/atufchoice-blockpump/blockpump-678917d1177dd7cac9fc715d89ef28102a076654/lemma2choice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7480715631386678}}
{"text": "Require Import Bool.\nRequire Import EqNat.\nRequire Import Setoid.\nRequire Import Le Lt Plus Minus Compare_dec.\n\n\n(*****************************************************************)\n(*Compare nat returning boolean*)\n(*****************************************************************)\n\n(*****************************************************************)\n(*beq_nat*)\nLemma beq_nat_sym : forall m n, beq_nat m n = beq_nat n m.\nintros m n.\ncase_eq (beq_nat m n); intros.\n rewrite beq_nat_true_iff in H; subst m;\n   rewrite (beq_nat_refl n); trivial.\n\n rewrite beq_nat_false_iff in H.\n case_eq (beq_nat n m); intros; trivial.\n  rewrite beq_nat_true_iff in H0.\n  elim H; subst n; trivial.\nQed.\n\n(****************************************************************)\n(*ltb*)\nDefinition ltb n m := leb (S n) m.\n\nLemma ltb_iff : forall m n,\n  ltb m n = true <-> m < n.\nunfold ltb; intros; rewrite leb_iff; split; trivial.\nQed.\n\nLemma ltb_eq_nat_dec : forall m n,\n  {ltb m n = true} + {beq_nat m n = true} + {ltb n m = true}.\nintros m n.\ngeneralize (lt_eq_lt_dec m n); intros H.\ndestruct H as [[H|H]|H]; [left; left; rewrite ltb_iff|\n  left; right; rewrite beq_nat_true_iff|\n    right; rewrite ltb_iff]; trivial.\nQed.\n\nLemma ltb_leb_iff : forall m n b,\n  ltb m n = b <-> leb n m = negb b.\nintros m n b.\ndestruct b; simpl; [|unfold ltb]; rewrite leb_iff_conv;\n  [rewrite ltb_iff; reflexivity|rewrite leb_iff].\n split; intros; [apply lt_n_Sm_le|\n   apply le_lt_n_Sm]; trivial.\nQed.\n\nLemma ltb_antirefl : forall m, ltb m m = false.\nunfold ltb; intro m.\nrewrite leb_iff_conv.\napply lt_n_Sn.\nQed.\n\nLemma leb_ltb_beq_conv : forall m n, \n  leb m n = ltb m n || beq_nat m n.\nintros m n.\ncase_eq (leb m n); intro H.\n rewrite leb_iff in H.\n rewrite le_lt_or_eq_iff in H.\n destruct H as [H|H].\n  rewrite <- ltb_iff in H; rewrite H; simpl; trivial.\n\n  subst m; rewrite <- beq_nat_refl.\n  rewrite orb_true_r; trivial.\n\n rewrite leb_iff_conv in H.\n case_eq (ltb m n); intros H'; [|clear H']; simpl.\n  rewrite ltb_iff in H'; apply lt_asym in H; contradiction.\n  \n  case_eq (beq_nat m n); intros H'; trivial.\n   rewrite beq_nat_true_iff in H'.\n   subst m; apply lt_irrefl in H; contradiction.\nQed.\n  \n\n(*****************************************************************)\n(*Cantor Normal Form Ordinals*)\n(*****************************************************************)\nInductive Ord : Set :=\n| fin : nat -> Ord \n| inf : nat -> Ord -> Ord -> Ord.\n\nFixpoint degree (o : Ord) : Ord :=\n  match o with\n    | fin _ => fin 0\n    | inf n p Q => p\n  end.\n\nFixpoint scan (o : Ord) : bool :=\n  match o with\n    | fin 0 => false\n    | fin (S _) => true\n    | inf _ _ o' => scan o'\n  end.\n\nDefinition ZeroO (o : Ord) : bool :=\n  match o with\n    | fin 0 => true\n    | _ => false\n  end.\n\nLemma ZeroO_fin0 : forall o, ZeroO o = true -> o = fin 0.\ndestruct o as [n|n p q]; simpl; intros; [\n  destruct n; [trivial|discriminate]|discriminate].\nQed.\n\nDefinition SuccOFin (o : Ord) : bool :=\n  match o with\n    | fin (S _) => true\n    | _ => false\n  end.\n\nDefinition SuccOInf (o : Ord) := \n  match o with\n    | inf _ _ _  => scan o\n    | _ => false\n  end.\n\nDefinition InfO (o : Ord) :=\n  match o with\n    | inf _ _ _ => negb (scan o)\n    | _ => false\n  end.\n\nDefinition SuccO (o : Ord) := SuccOInf o || SuccOFin o.\n\nLemma ord_classification : forall (o : Ord),\n  {ZeroO o = true} + {SuccO o = true} + {InfO o = true}.\ninduction o as [n|n p _ q Hq]; simpl.\n destruct n; left; [left|right]; trivial.\n \n destruct Hq as [[HO|HS]|HI].\n  apply ZeroO_fin0 in HO; subst q; right; simpl; trivial.\n\n  left; right; unfold SuccO in HS |- *; simpl.\n  destruct q; simpl in *; trivial.\n   rewrite orb_false_r; trivial.\n\n  destruct q as [m|m u v]. \n   destruct m; simpl in HI; discriminate.\n   \n   simpl in *; right; trivial.\nQed.\n\n\n(*Equality of ordinals*)\nFixpoint beq_ord (o o' : Ord) : bool :=\n  match o, o' with\n    | fin m, fin n => beq_nat m n\n    | inf n p Q, inf n' p' Q' =>\n      (beq_nat n n') && (beq_ord p p') && (beq_ord Q Q')\n    | _, _ => false\n  end.\n\nLemma beq_ord_refl : forall o, beq_ord o o = true.\ninduction o; simpl; [|repeat rewrite andb_true_iff; \n  split; [split|]]; trivial; rewrite beq_nat_true_iff; trivial.\nQed.\n\nLemma beq_ord_eq : forall o o',\n  beq_ord o o' = true <-> o = o'.\nsplit; [revert o'|].\n induction o as [|n p Hp Q HQ]; destruct o' as [|n' p' Q']; \n   simpl; intros; [apply beq_nat_true in H; subst n; trivial|\n     discriminate|discriminate|].\n  repeat rewrite andb_true_iff in H.\n  destruct H as ((Hnn', Hpp'), Hqq').\n  apply Hp in Hpp'.\n  apply HQ in Hqq'.\n  apply beq_nat_true in Hnn'.\n  subst n p Q; trivial.\n\n intros; subst o'.\n induction o; simpl; [rewrite beq_nat_true_iff; trivial|].\n  repeat rewrite andb_true_iff.\n  split; [split|]; trivial; rewrite beq_nat_true_iff; trivial.\nQed.\n\n\n(*Order between ordinals*)\nFixpoint btb_ord (o o' : Ord) : bool :=\n  match o, o' with\n    | fin m, fin n => (ltb n m)\n    | fin _, inf _ _ _  => false\n    | inf _ _ _, fin _ => true\n    | inf n p Q, inf n' p' Q' =>\n      (btb_ord p p') || (beq_ord p p') && (ltb n' n) || \n        (beq_ord p p') && (beq_nat n n') && (btb_ord Q Q')\n  end.\n\n\nDefinition beb_ord (o o' : Ord) := btb_ord o o' || beq_ord o o'.\n \nLemma btb_0 : forall o o',\n  btb_ord o o' = true -> btb_ord o (fin 0) = true.\ninduction o as [|n p Hp Q HQ]; destruct o' as [|n' p' Q']; \n  simpl; intros; [|discriminate| |]; trivial.\n rewrite ltb_iff in *.\n apply le_lt_trans with (1:=(le_0_n n0)) (2:=(H)).\nQed.\n\nLemma not_0_bt_0 : forall (o : Ord),\n  ZeroO o = false ->\n  btb_ord o (fin 0) = true.\ndestruct o as [n|n p q]; simpl; trivial.\n destruct n; [discriminate|intros _].\n  rewrite ltb_iff.\n  apply lt_0_Sn.\nQed.\n\nLemma btb_antirefl : forall o, btb_ord o o = false.\ninduction o; simpl.\n apply ltb_antirefl.\n \n rewrite IHo1; rewrite IHo2.\n rewrite ltb_antirefl.\n repeat rewrite andb_false_r; simpl; trivial.\nQed.\n\nLemma btb_ord_trans : forall o1 o2 o3,\n  btb_ord o1 o2 = true ->\n  btb_ord o2 o3 = true ->\n  btb_ord o1 o3 = true.\ninduction o1 as [n1|n1 p1 Hp1 q1 Hq1]; \n  destruct o2 as [n2|n2 p2 q2]; destruct o3 as [n3|n3 p3 q3]; \n    simpl; intros H12 H23; try discriminate; trivial.\n rewrite ltb_iff in H12, H23 |- *.\n apply lt_trans with (1:=H23) (2:=H12).\n\n repeat rewrite orb_true_iff in H12, H23 |- *.\n destruct H12 as [[H12|H12]|H12].\n  left; left; destruct H23 as [[H23|H23]|H23].\n   apply Hp1 with (1:=H12) (2:=H23).\n\n   rewrite andb_true_iff in H23; destruct H23 as (H23, _).\n   rewrite beq_ord_eq in H23; subst p3; trivial.\n\n   repeat rewrite andb_true_iff in H23.\n   destruct H23 as ((H23, _), _).\n   rewrite beq_ord_eq in H23; subst p3; trivial.\n\n  rewrite andb_true_iff in H12; destruct H12 as (H12, H12').\n  rewrite beq_ord_eq in H12; subst p2.\n  destruct H23 as [[H23|H23]|H23]; \n    [left;left|left;right|left;right]; trivial; \n      rewrite andb_true_iff in H23 |- *;\n        [|rewrite andb_true_iff in H23; destruct H23 as (H23, _)];\n        destruct H23 as (H23, H23');\n          rewrite beq_ord_eq in H23; subst p3;\n            rewrite beq_ord_eq; rewrite ltb_iff in H12' |- *.\n   rewrite ltb_iff in H23'.\n   split; [|apply lt_trans with (m:=n2)]; trivial.\n\n   rewrite beq_nat_true_iff in H23'; subst n3.\n   split; trivial.\n\n  repeat rewrite andb_true_iff in H12.\n  destruct H12 as ((H12_, H12'), H12).\n  rewrite beq_ord_eq in H12_; subst p2.\n  rewrite beq_nat_true_iff in H12'; subst n2.\n  destruct H23 as [[H23|H23]|H23]; \n    [left;left|left;right|right]; trivial.\n   repeat rewrite andb_true_iff in H23 |- *.\n   destruct H23 as ((H23', H23_), H23).\n   split; [split|apply Hq1 with (1:=H12)]; trivial.\nQed. \n\nLemma beb_btb_trans : forall o1 o2 o3,\n  beb_ord o1 o2 = true ->\n  btb_ord o2 o3 = true ->\n  btb_ord o1 o3 = true.\nintros o1 o2 o3 Ho12 Ho23.\nunfold beb_ord in Ho12.\nrewrite orb_true_iff in Ho12.\ndestruct Ho12 as [Hlt|Heq];\n  [apply btb_ord_trans with (1:=Hlt) (2:=Ho23) |\n  rewrite beq_ord_eq in Heq; subst o2; trivial].\nQed. \n\nLemma btb_beb_trans : forall o1 o2 o3,\n  btb_ord o1 o2 = true ->\n  beb_ord o2 o3 = true ->\n  btb_ord o1 o3 = true.\nintros o1 o2 o3 Ho12 Ho23.\nunfold beb_ord in Ho23.\nrewrite orb_true_iff in Ho23.\ndestruct Ho23 as [Hlt|Heq];\n  [apply btb_ord_trans with (2:=Hlt) (1:=Ho12) |\n  rewrite beq_ord_eq in Heq; subst o2; trivial].\nQed. \n\nLemma beb_trans : forall o1 o2 o3,\n  beb_ord o1 o2 = true ->\n  beb_ord o2 o3 = true ->\n  beb_ord o1 o3 = true.\nintros o1 o2 o3 Ho12 Ho23.\nunfold beb_ord in Ho12.\nrewrite orb_true_iff in Ho12.\ndestruct Ho12 as [Hlt1|Heq1]; [unfold beb_ord;\n  apply btb_beb_trans with (1:=Hlt1) in Ho23; rewrite Ho23 |\n    rewrite beq_ord_eq in Heq1; subst o2]; trivial.\nQed.\n\nLemma btb_eq_dec : forall o o',\n  {btb_ord o o'=true} + {beq_ord o o'=true} + {btb_ord o' o=true}.\ninduction o as [n|n p Hp q Hq]; destruct o' as [n'|n' p' q']; \n  simpl; [|right|left; left|]; trivial.\n generalize (lt_eq_lt_dec n n'); intro H.\n destruct H as [[H|H]|H]; [right; rewrite ltb_iff |\n   left; right; rewrite beq_nat_true_iff |\n     left; left; rewrite ltb_iff]; trivial.\n\n specialize Hp with (o':=p').\n specialize Hq with (o':=q').\n destruct Hp as [[Hp|Hp]|Hp]; [\n   left; left; repeat rewrite orb_true_iff; left; left| |\n     right; repeat rewrite orb_true_iff; left; left]; trivial.\n  rewrite beq_ord_eq in Hp; subst p'.\n  generalize (lt_eq_lt_dec n n'); intro H.\n  destruct H as [[H|H]|H].\n   right; repeat rewrite orb_true_iff; left; right.\n   rewrite andb_true_iff; rewrite ltb_iff; \n     split; [apply beq_ord_refl|]; trivial.\n\n   subst n'; destruct Hq as [[Hq|Hq]|Hq].\n    left; left; repeat rewrite orb_true_iff; right.\n    repeat rewrite andb_true_iff; split; [split; \n      [apply beq_ord_refl|rewrite beq_nat_true_iff]|]; trivial.\n\n    rewrite beq_ord_eq in Hq; subst q'.\n    left; right; repeat rewrite andb_true_iff; \n      split; [split; [rewrite beq_nat_true_iff|apply beq_ord_refl]|\n        apply beq_ord_refl]; trivial.\n\n    right; repeat rewrite orb_true_iff; right.\n    repeat rewrite andb_true_iff; split; [split; \n      [apply beq_ord_refl|rewrite beq_nat_true_iff]|]; trivial.\n\n   left; left; repeat rewrite orb_true_iff.\n   left; right; rewrite andb_true_iff.\n   split; [apply beq_ord_refl|rewrite ltb_iff]; trivial.\nQed.\n\nLemma btb_beb_iff : forall o o' b,\n  btb_ord o o' = b <-> beb_ord o' o = negb b.\nunfold beb_ord.\ninduction o as [n|n p Hp q Hq];\n  destruct o' as [n'|n' p' q']; simpl in *; intro b.\n rewrite ltb_leb_iff.\n rewrite leb_ltb_beq_conv.\n rewrite beq_nat_sym; reflexivity.\n\n destruct b; simpl; split; [discriminate|discriminate|trivial|trivial].\n\n destruct b; simpl; split; [trivial|trivial|discriminate|discriminate].\n\n case_eq (btb_ord p p'); intro Hbt; simpl.\n  rewrite Hp in Hbt; simpl in Hbt.\n  rewrite orb_false_iff in Hbt.\n  destruct Hbt as (Hbt1, Hbt2).\n  rewrite Hbt1, Hbt2; simpl.\n  rewrite andb_false_r; simpl.\n  split; intro H; [subst b|]; simpl; trivial.\n   destruct b; simpl in H |- *; [trivial|discriminate].\n\n  rewrite Hp in Hbt; simpl in Hbt; simpl.\n  rewrite orb_true_iff in Hbt.\n  destruct Hbt as [Hbt|Hbt]; repeat rewrite Hbt; simpl.\n   case_eq (beq_ord p p'); intro H; [rewrite beq_ord_eq in H; \n     subst p'; rewrite btb_antirefl in Hbt; discriminate|clear H; simpl].\n    split; intro H; [subst b|]; simpl; trivial.\n     destruct b; simpl in H |- *; [discriminate|trivial].\n\n   rewrite beq_ord_eq in Hbt; subst p'.\n   rewrite beq_ord_refl; rewrite btb_antirefl; simpl.\n   rewrite andb_true_r.\n   case_eq (ltb n' n); intro Hltn; simpl.\n    rewrite ltb_leb_iff in Hltn.\n    rewrite leb_ltb_beq_conv in Hltn; simpl in Hltn.\n    rewrite orb_false_iff in Hltn.\n    destruct Hltn as (Hltn, Heqn).\n    rewrite beq_nat_sym in Heqn.\n    rewrite Hltn; repeat rewrite Heqn; simpl.\n    split; intro H; [subst b|]; simpl; trivial.\n     destruct b; simpl in H |- *; [trivial|discriminate].\n\n    rewrite ltb_leb_iff in Hltn.\n    rewrite leb_ltb_beq_conv in Hltn; simpl in Hltn.\n    rewrite orb_true_iff in Hltn.\n    destruct Hltn as [Hltn|Heqn].\n     rewrite Hltn; apply ltb_leb_iff in Hltn.\n     rewrite leb_ltb_beq_conv in Hltn; simpl in Hltn.\n     rewrite orb_false_iff in Hltn.\n     destruct Hltn as (Hltn, Heqn).\n     repeat rewrite Heqn; simpl.\n     rewrite beq_nat_sym in Heqn; rewrite Heqn; simpl.\n     split; intro H; [subst b|]; simpl; trivial.\n      destruct b; simpl in H |- *; [discriminate|trivial].\n\n     rewrite beq_nat_true_iff in Heqn; subst n'.\n     rewrite <- (beq_nat_refl n).\n     rewrite ltb_antirefl; simpl; apply Hq.\nQed.\n    \n(*****************************************************************)\n(*Max of two ordinals*)\nDefinition max_ord o o' := if (btb_ord o o') then o else o'.\n\nLemma btb_max_ord : forall p q r, \n  btb_ord r p = true ->\n  btb_ord r q = true ->\n  btb_ord r (max_ord p q) = true.\nintros p q r; unfold max_ord; case (btb_ord p q); trivial.\nQed.\n\n(*****************************************************************)\n(*Cantor Normal Form (CNF) and some properties.*)\nFixpoint CNF (o : Ord) : bool :=\n  match o with\n    | fin _ => true\n    | inf n p Q => ((ltb 0 n)) && (CNF p) && \n      (CNF Q) && (btb_ord p (degree Q))\n  end.\n\nLemma btb_ord_subterm : forall n p q,\n  CNF (inf n p q) = true ->\n  btb_ord (inf n p q) q = true.\ndestruct q; intros; simpl in *; trivial.\n repeat rewrite orb_true_iff; left; left.\n rewrite andb_true_iff in H; destruct H as (_, H); trivial.\nQed.\n\n(*Plus and minus operations act as expected only when the *)\n(*operands are in CNF*)\n\nFixpoint ord_plus (o o' : Ord) :=\n  match o with\n    | fin m  =>\n      match o' with\n        | fin n => fin (m+n)\n        | inf _ _ _ => o'\n      end\n    | inf n p Q => \n      match o' with\n        | fin _ => inf n p (ord_plus Q o')\n        | inf n' p' Q' =>\n          if (btb_ord p p') then (inf n p (ord_plus Q o')) else \n            if (beq_ord p p') then (inf (n+n') p' Q') else o'\n      end\n  end.\n\nLemma degree_plus : forall o o',\n  degree (ord_plus o o') = max_ord (degree o) (degree o').\nunfold max_ord; destruct o as [|n p Q]; \n  destruct o' as [|n' p' Q']; [simpl|destruct p'; simpl| \n    simpl ord_plus; simpl degree; destruct p as [n'|n' p' Q'];\n      [destruct n'|]; simpl|simpl ord_plus]; trivial.\n case_eq (btb_ord p p'); intros Hbt; simpl;\n   rewrite Hbt; trivial.\n  case_eq (beq_ord p p'); intro Heq; simpl; trivial.\nQed.\n\nLemma beb_degree_cases : forall (o : Ord),\n  match o with\n    | fin 0 => beq_ord o (degree o) = true\n    | _  => btb_ord o (degree o) = true\n  end.\ninduction o as [n|n p Hp q _].\n destruct n as [|n]; simpl; trivial.\n\n destruct p as [pn|pn pp pq]; [simpl|]; trivial.\n  simpl in Hp |- *; repeat rewrite orb_true_iff; \n    left; left; trivial.\nQed.\n \nLemma beb_degree : forall (o : Ord), \n  beb_ord o (degree o) = true.\nintro o; unfold beb_ord; rewrite orb_true_iff.\ngeneralize (beb_degree_cases o); intro H.\ndestruct o; [destruct n|]; [right|left|left]; trivial.\nQed.\n\nLemma CNF_ord_plus : forall o o',\n  CNF o = true ->\n  CNF o' = true ->\n  CNF (ord_plus o o') = true.\ninduction o as [n|n p _ q Hq]; destruct o' as [n'|n' p' q'];\n  intros Ho Ho'; simpl in *; trivial;\n    repeat rewrite andb_true_iff in Ho;\n      destruct Ho as (((Hlt, HCp), HCq), Hdg).\n rewrite degree_plus.\n rewrite Hlt, HCp; simpl.\n rewrite andb_true_iff; split; [apply Hq|]; trivial.\n  apply btb_max_ord; simpl; [|apply btb_0 in Hdg]; trivial.\n\n case_eq (btb_ord p p'); intro Hbtp; simpl.\n  rewrite Hlt, HCp; simpl.\n  rewrite andb_true_iff; split; [apply Hq; simpl|]; trivial.\n   rewrite degree_plus; rewrite btb_max_ord; simpl; trivial.\n\n  case_eq (beq_ord p p'); intro Heqp; simpl; trivial.\n   repeat rewrite andb_true_iff in Ho'.\n   destruct Ho' as (((Hlt', HCp'), HCq'), Hdg').\n   rewrite HCq', HCp', Hdg'; repeat rewrite andb_true_r.\n   rewrite ltb_iff in Hlt' |- *.\n   apply lt_le_trans with (1:=Hlt') (2:=le_plus_r n n').\nQed.\n\n\nLemma ord_plus_0_l : forall (o o' : Ord),\n  ZeroO o = true ->\n  ord_plus o o' = o'.\ndestruct o as [n|n p q]; simpl; intros; [|discriminate].\n destruct n as [|n]; intros; [simpl|discriminate].\n  destruct o'; trivial.\nQed.\n\nLemma ord_plus_0_r : forall (o o' : Ord),\n  ZeroO o = true ->\n  ord_plus o' o = o'.\nintro o; destruct o as [n|n p q]; simpl; intros o' H; [|discriminate].\n destruct n; [clear H|discriminate].\n  induction o' as [n|n p _ q Hq]; simpl; [\n    rewrite plus_0_r |  rewrite Hq]; trivial.\nQed.\n\n\nLemma plus_m_r : forall o o' oo, \n  CNF oo = true ->\n  btb_ord o o' = true ->\n  btb_ord (ord_plus o oo) o' = true.\ninduction o as [n|n p _ q Hq]; destruct o' as [n'|n' p' q'];\n  destruct oo as [nn|nn pp qq]; simpl; intros HCNF H;\n    try discriminate; trivial.\n rewrite ltb_iff in H |- *.\n apply lt_plus_trans; trivial.\n \n case (beq_ord p pp); case (btb_ord p pp); simpl; trivial.\n\n repeat rewrite orb_true_iff in H |- *.\n destruct H as [[H|H]|H]; [left;left|left;right|right]; trivial.\n  repeat rewrite andb_true_iff in H |- *.\n  destruct H as ((Heqp, Heqn), Hbtq).\n  split; [split|apply Hq]; trivial.\n\n case_eq (btb_ord p pp); intros Hbtppp; simpl.\n  repeat rewrite orb_true_iff in H |- *.\n  destruct H as [[H|H]|H]; [left;left|left;right|right];trivial.\n   repeat rewrite andb_true_iff in H |- *.\n   destruct H as ((Heqp, Heqn), Hbtq).\n   split; [split|apply Hq]; trivial.\n\n  rewrite btb_beb_iff in Hbtppp; simpl.\n  unfold beb_ord in Hbtppp; rewrite orb_true_iff in Hbtppp;\n    destruct Hbtppp as [Hbtp|Heqp].\n   case_eq (beq_ord p pp); intro Heqp; [rewrite beq_ord_eq in Heqp; \n     subst pp; rewrite btb_antirefl in Hbtp; discriminate|clear Heqp].\n    simpl; repeat rewrite orb_true_iff in H |- *; left; left.\n    destruct H as [[H|H]|H].\n     apply btb_ord_trans with (1:=Hbtp) (2:=H).\n\n     rewrite andb_true_iff in H; destruct H as (H, _).\n     rewrite beq_ord_eq in H; subst p'; trivial.\n\n     repeat rewrite andb_true_iff in H; destruct H as ((H, _), _).\n     rewrite beq_ord_eq in H; subst p'; trivial.\n\n   rewrite beq_ord_eq in Heqp; subst pp.\n   rewrite beq_ord_refl; simpl.\n   repeat rewrite andb_true_iff in HCNF;\n     destruct HCNF as (((H0n, _), _), _).\n   case_eq (btb_ord p p'); intros Hbtp;\n    rewrite Hbtp in H; simpl in H |- *; trivial.\n    case_eq (beq_ord p p'); intro Heqp;\n      rewrite Heqp in H; simpl in H |- *; [|discriminate].\n     rewrite orb_true_iff in H |- *.\n     destruct H as [H|H]; left; rewrite ltb_iff in H0n |- *.\n      rewrite ltb_iff in H; apply lt_plus_trans; trivial.\n\n      rewrite andb_true_iff in H; destruct H as (H, _);\n        rewrite beq_nat_true_iff in H; subst n'.\n      apply plus_lt_compat_l with (p:=n) in H0n;\n        rewrite plus_0_r in H0n; trivial.\nQed.\n\n\n\n\n\n(*******************************************************************)\n(*Pred and Minus*)\nFixpoint ord_pred (o : Ord) : Ord :=\n  match o with\n    | fin 0 => o\n    | fin (S n) => fin n\n    | inf n p o' => inf n p (ord_pred o')\n  end.\n\nLemma degree_pred : forall o, degree o = degree (ord_pred o).\ndestruct o as [n|n p q]; [destruct n|]; simpl; trivial.\nQed.\n\nLemma CNF_ord_pred : forall o,\n  CNF o = true ->\n  CNF (ord_pred o) = true.\ninduction o as [n|n p _ q Hq]; intros Ho; simpl in *; trivial.\n destruct n; simpl; trivial.\n\n rewrite <- degree_pred.\n repeat rewrite andb_true_iff in Ho.\n destruct Ho as (((Hlt, HCp), HCq), Hdg).\n rewrite Hlt, HCp, Hdg; simpl.\n rewrite andb_true_r.\n apply Hq; trivial.\nQed.\n\nLemma btb_pred_S : forall o, \n  SuccO o = true ->\n  btb_ord o (ord_pred o) = true.\nunfold SuccO.\ninduction o as [n|n p _ q Hq]; intros; simpl in *.\n destruct n; simpl in *; [discriminate|\n   rewrite ltb_iff; apply lt_n_Sn].\n\n rewrite orb_false_r in H.\n rewrite orb_true_iff; right.\n repeat rewrite andb_true_iff.\n split; [split; [rewrite beq_ord_eq|rewrite beq_nat_true_iff]|\n   apply Hq; clear n p Hq]; trivial.\n  rewrite orb_true_iff.\n  destruct q; simpl in *; [right|left]; trivial.\nQed.\n\nLemma eq_pred_notS : forall o,\n  SuccO o = false -> ord_pred o = o.\nintro o; unfold SuccO; rewrite orb_false_iff.\ninduction o as [n|n p _ q Hq]; intro HNS; \n  destruct HNS as (HNS1, HNS2).\n destruct n; simpl in *; [trivial|discriminate].\n\n simpl in *; rewrite Hq; trivial.\n destruct q as [n'|n' p' q']; [destruct n'|]; \n   simpl in *; [split; trivial|discriminate|split; trivial].\nQed.\n \n\nFixpoint ord_minus (o o' : Ord) :=\n  match o, o' with\n    | fin n, fin m => fin (n - m)\n    | fin n, inf _ _ _ => o\n    | inf n p q, fin _ => inf n p (ord_minus q o')\n    | inf n p q, inf n' p' q' =>\n      if (btb_ord p p') then inf n p (ord_minus q o') else\n        if (beq_ord p p') then \n          (if (ltb n' n) then inf (n-n') p (ord_minus q q') else\n            ord_minus q q') \n          else o \n  end.\n\nLemma ord_minus_degree : forall o o',\n  CNF o = true ->\n  beb_ord (degree o) (degree (ord_minus o o')) = true.\ninduction o as [n|n p _ q Hq]; destruct o' as [n'|n' p' q'];\n  intro Ho; simpl; trivial.\n unfold beb_ord; rewrite beq_ord_refl;\n   rewrite orb_true_r; trivial.\n\n case_eq (btb_ord p p'); intro Hbtp; simpl;\n   [unfold beb_ord; rewrite beq_ord_refl;\n     rewrite orb_true_r; trivial|].\n  case_eq (beq_ord p p'); intro Heqp; simpl;\n    [|unfold beb_ord; rewrite beq_ord_refl;\n      rewrite orb_true_r; trivial].\n   case_eq (ltb n' n); intro Hltn; simpl;\n     [unfold beb_ord; rewrite beq_ord_refl;\n       rewrite orb_true_r; trivial|].\n    simpl in Ho; repeat rewrite andb_true_iff in Ho;\n      destruct Ho as (((_, _), HCq), Hdg).\n    specialize Hq with (o':=q') (1:=HCq).\n    apply beb_trans with (2:=Hq).\n    unfold beb_ord; rewrite Hdg; simpl; trivial.\nQed.\n\n\nLemma CNF_ord_minus : forall o o',\n  CNF o = true ->\n  CNF o' = true ->\n  CNF (ord_minus o o') = true.\ninduction o as [n|n p _ q Hq]; destruct o' as [n'|n' p' q'];\n  intros Ho Ho'; simpl in *; trivial;\n    repeat rewrite andb_true_iff in Ho;\n      destruct Ho as (((Hlt, HCp), HCq), Hdg).\n rewrite Hlt, HCp; simpl.\n rewrite andb_true_iff; split; [apply Hq|]; trivial.\n  apply btb_beb_trans with (1:=Hdg).\n  apply ord_minus_degree; trivial.\n\n case_eq (btb_ord p p'); intro Hbtp; simpl.\n  rewrite Hlt, HCp; simpl.\n  rewrite andb_true_iff; split; [apply Hq; simpl|]; trivial.\n   apply btb_beb_trans with (1:=Hdg).\n   apply ord_minus_degree; trivial.\n\n  case_eq (beq_ord p p'); intro Heqp; simpl;\n    [|repeat rewrite andb_true_iff; repeat split; trivial].\n   repeat rewrite andb_true_iff in Ho'.\n   destruct Ho' as (((Hlt', HCp'), HCq'), Hdg').\n   case_eq (ltb n' n); intro Hltn; simpl; [|apply Hq; trivial].\n    rewrite HCp; rewrite andb_true_r.\n    repeat rewrite andb_true_iff; \n      repeat split; [|apply Hq; trivial|].\n     rewrite ltb_iff in Hltn |- *.\n     unfold lt in Hltn |- *.\n     apply minus_le_compat_r with (p:=n') in Hltn.\n     rewrite <- minus_Sn_m in Hltn; trivial.\n     rewrite minus_diag in Hltn; trivial.\n\n     apply btb_beb_trans with (1:=Hdg).\n     apply ord_minus_degree; trivial.\nQed.\n\n\nLemma btb_minus : forall o' o oo,\n  CNF o' = true ->\n  CNF o  = true ->\n  CNF oo = true ->\n  btb_ord o o' = true -> \n  btb_ord o (ord_minus o' oo) = true.\ninduction o' as [n'|n' p' _ q' Hq'].\n destruct o as [n|n p q]; [|destruct oo; simpl; trivial].\n  destruct oo as [nn|nn pp qq]; simpl; trivial.\n   do 2 rewrite ltb_iff; intros _ _ _ H.\n   apply le_lt_trans with (1:=le_minus n' nn) (2:=H).\n\n destruct o as [n|n p q]; [simpl; discriminate|intros oo Ho' Ho Hoo H].\n  destruct oo as [nn|nn pp qq]; [\n    simpl; repeat rewrite orb_true_iff|simpl ord_minus].\n   simpl in H; repeat rewrite orb_true_iff in H.\n   destruct H as [[H|H]|H]; [left;left|left;right|right]; trivial.\n    repeat rewrite andb_true_iff in H |- *.\n    destruct H as ((Hpp, Hnn), Hqq).\n    simpl in Ho, Ho'; repeat rewrite andb_true_iff in Ho, Ho'.\n    destruct Ho as (((_, _), Ho), _).\n    destruct Ho' as (((_, _), Ho'), _).\n    split; [split|apply Hq'; simpl]; trivial.     \n\n   case_eq (btb_ord p' pp); intros _ ; [simpl|].\n    repeat rewrite orb_true_iff.\n    simpl in H; repeat rewrite orb_true_iff in H.\n    destruct H as [[H|H]|H]; [left;left|left;right|right]; trivial.\n     repeat rewrite andb_true_iff in H |- *.\n     destruct H as ((Hpp, Hnn), Hqq).\n      simpl in Ho, Ho'; repeat rewrite andb_true_iff in Ho, Ho'.\n      destruct Ho as (((_, _), Ho), _).\n      destruct Ho' as (((_, _), Ho'), _).\n      split; [split|apply Hq'; simpl]; trivial.\n       \n    case_eq (beq_ord p' pp); intro Hppp; [\n      rewrite beq_ord_eq in Hppp; subst pp|trivial].\n     case_eq (ltb nn n'); intros Hnn ; [simpl|].\n      repeat rewrite orb_true_iff.\n      simpl in Hoo; repeat rewrite andb_true_iff in Hoo; \n        destruct Hoo as (((Hoo, _), _), _).\n      simpl in H; repeat rewrite orb_true_iff in H.\n      destruct H as [[H|H]|H]; [left;left| |]; trivial; left; right; \n        repeat rewrite andb_true_iff in H |- *. \n       destruct H as (Heqp, Hn).\n       split; [trivial|].\n        rewrite ltb_iff in Hn, Hnn, Hoo |- *.\n        apply lt_trans with (2:=Hn).\n        apply lt_minus; [apply lt_le_weak|]; trivial.\n        \n       rewrite andb_true_iff in H. \n       destruct H as ((Heqp, Hn), _).\n       split; [trivial|].\n        rewrite beq_nat_true_iff in Hn; subst n'.\n        rewrite ltb_iff in Hnn, Hoo |- *.\n        apply lt_minus; [apply lt_le_weak|]; trivial.\n      \n      apply btb_ord_trans with (o2:=(inf n' p' q')); trivial.\n       generalize Ho'; intro H'.\n       simpl in Ho, Ho', Hoo.\n       repeat rewrite andb_true_iff in Ho, Ho', Hoo.\n       destruct Ho as (((_, _), Ho), _).\n       destruct Ho' as (((_, _), Ho'), _).\n       destruct Hoo as (((_, _), Hoo), _).\n        apply Hq'; [| | |apply btb_ord_subterm]; trivial.\nQed.\n\n\nLemma plus_bt_minus : forall o o' oo, \n  CNF o  = true ->\n  CNF o' = true ->\n  CNF oo = true ->\n  btb_ord o oo = false ->\n  btb_ord (ord_plus o o') oo = true -> \n  btb_ord o' (ord_minus oo o) = true.\ninduction o as [n|n p _ q Hq]; destruct oo as [nn|nn pp qq]; \n  destruct o' as [n'|n' p' q']; intros Ho Ho' Hoo H H';\n    try discriminate; trivial.\n simpl in H, H' |- *.\n rewrite ltb_leb_iff in H; simpl in H; rewrite leb_iff in H.\n rewrite ltb_iff in H' |- *; unfold lt in H' |- *.\n apply minus_le_compat_r with (p:=n) in H'.\n rewrite minus_plus in H'.\n rewrite <- minus_Sn_m in H'; trivial.\n \n simpl ord_plus in H'.\n apply btb_minus; trivial.\n\n simpl in Ho, Hoo.\n repeat rewrite andb_true_iff in Ho, Hoo.\n destruct Ho as (((_, _), Ho), _).\n destruct Hoo as (((_, _), Hoo), _).\n simpl in H', H; simpl ord_minus.\n repeat rewrite orb_false_iff in H.\n destruct H as ((Hbt1, Hbt2), Hbt3).\n rewrite Hbt1, Hbt2 in H'; simpl in H'.\n rewrite btb_beb_iff in Hbt1; \n   unfold beb_ord in Hbt1; simpl in Hbt1.\n rewrite orb_true_iff in Hbt1; destruct Hbt1 as [Hbt|Heq].\n  rewrite Hbt; rewrite btb_beb_iff in Hbt; simpl in Hbt.\n  unfold beb_ord in Hbt; rewrite orb_false_iff in Hbt.\n  destruct Hbt as (Hbt, Heq).\n  rewrite Heq in H'; simpl in H'; discriminate.\n  \n  rewrite beq_ord_eq in Heq; subst pp; rewrite btb_antirefl.\n  rewrite beq_ord_refl in Hbt2, Hbt3, H' |- *; \n    simpl in Hbt2, Hbt3, H'.\n  rewrite ltb_leb_iff in Hbt2.\n  rewrite leb_ltb_beq_conv in Hbt2; simpl in Hbt2.\n  rewrite orb_true_iff in Hbt2; destruct Hbt2 as [Hlt|Heq].\n   rewrite Hlt; rewrite ltb_leb_iff in Hlt.\n   rewrite leb_ltb_beq_conv in Hlt; simpl in Hlt.\n   rewrite orb_false_iff in Hlt; destruct Hlt as (_, Heq).\n   rewrite beq_nat_sym in Heq; rewrite Heq in H'; \n     simpl in H'; discriminate.\n\n   rewrite Heq in Hbt3, H'; simpl in Hbt3, H'.\n   rewrite beq_nat_true_iff in Heq; subst nn.\n   rewrite ltb_antirefl; apply Hq; trivial.\n   \n simpl ord_plus in H'.\n case_eq (btb_ord p p'); intros Hbtp; rewrite Hbtp in H'.\n  simpl in H, H'; simpl ord_minus.\n  case_eq (btb_ord p pp); intros Hbtppp; \n    rewrite Hbtppp in H; simpl in H; [discriminate|].\n   rewrite btb_beb_iff in Hbtppp; simpl in Hbtppp.\n   unfold beb_ord in Hbtppp; rewrite orb_true_iff in Hbtppp.\n   destruct Hbtppp as [Hppp|Hppp].\n    rewrite btb_beb_iff in Hppp; simpl in Hppp.\n    unfold beb_ord in Hppp; rewrite orb_false_iff in Hppp.\n    destruct Hppp as (Hbtpp, Heqp); rewrite Hbtpp, Heqp in H'; \n      simpl in H'; discriminate.\n\n    rewrite beq_ord_eq in Hppp; subst pp.\n    rewrite btb_antirefl in H' |- *.\n    repeat rewrite beq_ord_refl in H, H'; simpl in H, H'.\n    case_eq (ltb nn n); intro Hnnn; \n      rewrite Hnnn in H, H'; simpl in H, H'; [discriminate|].\n     rewrite ltb_leb_iff in Hnnn; simpl in Hnnn.\n     rewrite leb_ltb_beq_conv in Hnnn; \n       rewrite orb_true_iff in Hnnn; destruct Hnnn as [Hnnn|Hnnn].\n      rewrite ltb_leb_iff in Hnnn; simpl in Hnnn.\n      rewrite leb_ltb_beq_conv in Hnnn; rewrite orb_false_iff in Hnnn;\n        destruct Hnnn as (_, Hnnn); rewrite beq_nat_sym in Hnnn;\n          rewrite Hnnn in H'; simpl in H'; discriminate.\n\n      rewrite Hnnn in H, H'; simpl in H, H'.\n      rewrite beq_nat_true_iff in Hnnn; subst nn.\n      rewrite ltb_antirefl, beq_ord_refl.\n      simpl in Ho, Hoo.\n      repeat rewrite andb_true_iff in Ho, Hoo.\n      destruct Ho as (((_, _), Ho), _).\n      destruct Hoo as (((_, _), Hoo), _).\n      apply Hq; trivial.\n\n  rewrite btb_beb_iff in Hbtp; simpl in Hbtp.\n  unfold beb_ord in Hbtp; rewrite orb_true_iff in Hbtp.\n  destruct Hbtp as [Hpp'|Hpp'].\n   rewrite btb_beb_iff in Hpp'; simpl in Hpp';\n     unfold beb_ord in Hpp'; rewrite orb_false_iff in Hpp'.\n   destruct Hpp' as (_, Hpp'); rewrite Hpp' in H'.\n   apply btb_minus; trivial.\n\n  rewrite beq_ord_eq in Hpp'; subst p'.\n  rewrite beq_ord_refl in H'.\n  case_eq (btb_ord p pp); intros Hbt; [\n    simpl in H; rewrite Hbt in H; simpl in H; discriminate|].\n   rewrite btb_beb_iff in Hbt; simpl in Hbt.\n   unfold beb_ord in Hbt; rewrite orb_true_iff in Hbt.\n   destruct Hbt as [Hbt|Heq]; [\n     simpl in H'; rewrite btb_beb_iff in Hbt; simpl in Hbt;\n       unfold beb_ord in Hbt; rewrite orb_false_iff in Hbt;\n         destruct Hbt as (Hbt, Heq); rewrite Hbt, Heq in H';\n           simpl in H'; discriminate|].\n    rewrite beq_ord_eq in Heq; subst pp.\n    case_eq (ltb nn n); intros Heqn; simpl in H.\n     rewrite btb_antirefl in H; repeat rewrite beq_ord_refl in H;\n       rewrite Heqn in H; simpl in H; discriminate.\n     \n     simpl in H'; simpl ord_minus.\n     simpl in Ho, Hoo.\n     repeat rewrite andb_true_iff in Ho, Hoo.\n     destruct Ho as (((_, _), Ho), _).\n     destruct Hoo as (((_, _), Hoo), Hdegree).\n     rewrite btb_antirefl in H, H' |- *; simpl in H, H'.\n     repeat rewrite beq_ord_refl in H, H'; simpl in H, H'.\n     rewrite beq_ord_refl.\n     rewrite Heqn in H; simpl in H, H'.\n     rewrite ltb_leb_iff in Heqn; simpl in Heqn.\n     rewrite leb_ltb_beq_conv in Heqn; rewrite orb_true_iff in Heqn.\n     destruct Heqn as [Hlt|Heq].\n      rewrite Hlt; simpl; rewrite btb_antirefl; \n        repeat rewrite beq_ord_refl; simpl; rewrite orb_true_iff.\n      case_eq (ltb nn (n+n')); intros Heqn; \n        rewrite Heqn in H'; simpl in H' |- *; [left|right].\n       rewrite ltb_iff in Hlt, Heqn |- *.\n       apply lt_le_weak in Hlt; unfold lt in Heqn |- *.\n       apply minus_le_compat_r with (p:=n) in Heqn.\n       rewrite minus_plus in Heqn.\n       rewrite <- minus_Sn_m in Heqn; trivial.\n\n       rewrite ltb_leb_iff in Heqn; unfold beb_ord in Heqn;\n         simpl in Heqn; rewrite leb_ltb_beq_conv in Heqn;\n           rewrite orb_true_iff in Heqn; destruct Heqn as [Hltn|Heqn].\n        rewrite ltb_leb_iff in Hltn; unfold beb_ord in Hltn;\n          simpl in Hltn; rewrite leb_ltb_beq_conv in Hltn;\n            rewrite orb_false_iff in Hltn; destruct Hltn as (Hltn,Heqn).\n        rewrite beq_nat_sym in Heqn; rewrite Heqn in H'; \n          simpl in H'; discriminate.\n\n        rewrite Heqn in H'; simpl in H'.\n        rewrite beq_nat_true_iff in Heqn; subst nn.\n        rewrite minus_plus; rewrite <- (beq_nat_refl n'); simpl.\n        simpl in Ho'; repeat rewrite andb_true_iff in Ho'.\n        destruct Ho' as (((_, _), Ho'), _).\n        apply btb_minus; trivial.\n        \n      rewrite beq_nat_true_iff in Heq; subst nn.\n      rewrite ltb_antirefl.\n      rewrite <- (beq_nat_refl n) in H; simpl in H.\n      apply btb_minus; trivial.\n       destruct qq; simpl; \n         [|simpl in Hdegree; rewrite Hdegree; simpl]; trivial.\nQed.\n  \n\n(******************************************************************)\n(*Cantor Normal Form Ordinals*)\n(******************************************************************)\nDefinition CNFO := {o : Ord | CNF o = true}.\n\nDefinition CNFO_plus (o : CNFO) (o' : CNFO) : CNFO.\ndestruct o as (o, CNFo); destruct o' as (o', CNFo').\nexists (ord_plus o o').\napply CNF_ord_plus; trivial.\nDefined.\n\nDefinition CNFO_pred (o : CNFO) : CNFO.\ndestruct o as (o, CNFO).\nexists (ord_pred o).\napply CNF_ord_pred; trivial.\nDefined.\n\nDefinition CNFO_minus (o : CNFO) (o' : CNFO) : CNFO.\ndestruct o as (o, CNFo); destruct o' as (o', CNFo').\nexists (ord_minus o o').\napply CNF_ord_minus; trivial.\nDefined.\n\nDefinition CNFO_nat (n : nat) : CNFO.\nexists (fin n); simpl; trivial.\nDefined.\n\nDefinition CNFO_btb (o o' : CNFO) := \n  btb_ord (proj1_sig o) (proj1_sig o').\n\nDefinition CNFO_beq (o o' : CNFO) := \n  beq_ord (proj1_sig o) (proj1_sig o').\n\n\n(******************************************************************)\n(*A path with an ordinal length*)\n(******************************************************************)\n\nSection Path.\n \n Variable A : Type.\n Variable eq_A : A -> A -> bool.\n\n Definition domain (o : CNFO) := {i: CNFO|CNFO_btb o i = true}.\n\n Definition path (o : CNFO) := (domain o) -> A.\n\n Definition join (o o' : CNFO) (p : path o) (p' : path o') : \n   option (path (CNFO_plus (CNFO_pred o) o')).\n case_eq (ZeroO (proj1_sig o')); intros HO; [exact None|].\n  (*The second path is not length 0*)\n  case_eq (SuccO (proj1_sig o)); intro HS.\n   (*The first path is of length (w^pi*ci + S n) *)\n   assert (domain o) as po. (*The last index of fst path*)\n    exists (CNFO_pred o).\n    destruct o, o'; simpl in HS |- *.\n    unfold CNFO_btb; apply btb_pred_S in HS; trivial.\n   assert (domain o') as po'. (*The first index of snd path*)\n    exists (CNFO_nat 0).\n    destruct o'; unfold CNFO_btb; simpl.\n    apply not_0_bt_0; trivial.\n   case_eq (eq_A (p po) (p' po')); intro Heq; [|exact None].\n    (*The last el of fst path is equal to the fst el of snd path*)\n    assert (f : path (CNFO_plus (CNFO_pred o) o')).\n     intros oo; destruct oo as (oo, Hoo).\n     case_eq (btb_ord (ord_pred (proj1_sig o)) (proj1_sig oo)); \n     intros Hpart.\n      (*The index oo < o - 1*)\n      assert (domain o) as poo.\n       exists oo.\n       apply btb_ord_trans with (2:=Hpart).\n       apply btb_pred_S; trivial.\n      exact (p poo).\n      (*The index oo >= o - 1*)\n      assert (domain o') as poo.\n       exists (CNFO_minus oo (CNFO_pred o)).\n       unfold CNFO_btb in Hoo |- *.\n       destruct o as (o, cnfo); destruct o' as (o', cnfo');\n         destruct oo as (oo, cnfoo); simpl in Hoo, Hpart |- *.\n       apply plus_bt_minus; trivial.\n        apply CNF_ord_pred; trivial.\n      exact (p' poo).\n    exact (Some f).\n    \n   (*The length of fst path is not succ case*)\n   assert (f : path (CNFO_plus (CNFO_pred o) o')).\n    intros oo; destruct oo as (oo, Hoo).\n    case_eq (CNFO_btb o oo); intros Hpart.\n      (*The index oo < o*)\n      assert (domain o) as poo.\n       exists oo; trivial.\n      exact (p poo).\n      (*The index oo >= o*)\n      assert (domain o') as poo.\n       exists (CNFO_minus oo o).\n       unfold CNFO_btb in Hoo, Hpart |- *.\n       destruct o as (o, cnfo); destruct o' as (o', cnfo');\n         destruct oo as (oo, cnfoo); simpl in Hoo, Hpart, HS |- *.\n        rewrite eq_pred_notS in Hoo; trivial.\n        apply plus_bt_minus; trivial.\n      exact (p' poo).\n    exact (Some f).\n Defined.\n\nEnd Path.\n\n\n\n(******************************************************************)\n(*Set of paths*)\n(******************************************************************)\n\nSet Implicit Arguments.\n\nSection SetOfPaths.\n\n Parameter A : Type.\n Parameter eq_A : A -> A -> bool.\n \n Definition PathSet (o : CNFO) := path A o -> Prop.\n\n Definition pathin o (s : PathSet o) (p : path A o) := s p.\n\n Inductive setjoin o o' (s : PathSet o) (s' : PathSet o') : \n   PathSet (CNFO_plus (CNFO_pred o) o') :=\n   jointwo : forall p p' p'', \n     pathin s p ->\n     pathin s' p' ->\n     join A eq_A o o' p p' = Some p'' ->\n     pathin (setjoin s s') p''.\n\n Definition set_include o o' (s : PathSet o) (s' : PathSet o') :=\n   CNFO_beq o o' /\\ \n \n  \n \n\n Lemma setjoin_comm : forall or os oq \n   (r : PathSet or) (s : PathSet os) (q : PathSet oq),\n   setjoin (setjoin r s) q \n\n\n\n\n\n\n\n (*Don't requrie elements are different, infinitely many elements*)\n(* Record PathSet := mkset {\n   elelen : CNFO -> CNFO;\n   elemen : forall (o : CNFO), path A (elelen o)\n }.\n\n Definition constone : CNFO.\n exists (fin 1); trivial.\n Defined.\n\n Definition one : PathSet.\n exists (fun _ => constone).\n intro index.\n unfold path.\n *)\n\n \n  \n\n\n\n", "meta": {"author": "superwalter", "repo": "Sequences", "sha": "5802f92efbd1b193ac82924a7c4016b5dab33d77", "save_path": "github-repos/coq/superwalter-Sequences", "path": "github-repos/coq/superwalter-Sequences/Sequences-5802f92efbd1b193ac82924a7c4016b5dab33d77/recursorOrd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7480715550276748}}
{"text": "Load \"./syntax\".\nImport Nat.\n\nFixpoint match_natlist {A: Type} (l: list (nat * A)) n def :=\n  match l with\n  | [] => def\n  | (n1, h) :: t => if eqb n1 n then h else match_natlist t n def\n  end.\n\nFixpoint subst_type l t :=\n  match t with\n  | TyVar n => match_natlist l n t\n  | Bool => Bool\n  | Arrow t1 t2 =>\n    subst_type l t1 |--> subst_type l t2 \n  end.\n\nFixpoint subst_type_term l t :=\n  match t with\n  | Var n => Var n\n  | Abs x typ e1 =>\n    Abs x (subst_type l typ) (subst_type_term l e1)\n  | Tru => Tru\n  | Fls => Fls\n  | App e1 e2 => App (subst_type_term l e1) (subst_type_term l e2)\n  | If e1 e2 e3 => If (subst_type_term l e1) (subst_type_term l e2) (subst_type_term l e3)\n  end.\n\nDefinition subst_type_list subl (ctx: context) := map (subst_type subl) ctx.\n\nTheorem T22_1_2 : forall Γ σ t T,\n    Γ |- t \\in T -> subst_type_list σ Γ |- subst_type_term σ t \\in subst_type σ T.\nProof.\n  intros. generalize dependent σ. induction H; simpl; intros; try solve [econstructor; eauto].\n  -\n    constructor; eauto. generalize dependent n1.\n    induction ctx; simpl; intros; simpl in H; auto.\n    destruct n1; simpl in H; try discriminate.\n    destruct n1. simpl. simpl in H. inversion H; subst. reflexivity.\n    simpl. simpl in H. apply IHctx in H. apply H.\nQed.\n\nFixpoint tyn_in_type n ty :=\n  match ty with\n  | TyVar n1 => eqb n n1\n  | t1 |--> t2 => (tyn_in_type n t1) || (tyn_in_type n t2)\n  | _ => false\n  end.\n\nFixpoint tyn_in_term n t :=\n  match t with\n  | App e1 e2 => (tyn_in_term n e1) || (tyn_in_term n e2)\n  | Abs x typ e1 => if tyn_in_type n typ then true else (tyn_in_term n e1)\n  | If e1 e2 e3 => (tyn_in_term n e1) || (tyn_in_term n e2) || (tyn_in_term n e3)\n  | _ => false\n  end.\n\nFixpoint tyn_in_list n l :=\n  match l with\n  | [] => false\n  | ty :: t => (tyn_in_type n ty) || (tyn_in_list n t)\n  end.\n\nFixpoint max_tyvar_type n ty :=\n  match ty with\n  | TyVar m => if ltb n m then m else n\n  | ty1 |--> ty2 =>\n    let n1 := max_tyvar_type n ty1 in\n    let n2 := max_tyvar_type n ty2 in\n    if ltb n1 n2 then n2 else n1\n  | _ => n\n  end.\n\nFixpoint max_tyvar_term n t :=\n  match t with\n  | Abs _ ty e1 =>\n    let n1 := max_tyvar_type n ty in\n    let n2 := max_tyvar_term n e1 in\n    if ltb n1 n2 then n2 else n1\n  | App e1 e2 =>\n    let n1 := max_tyvar_term n e1 in\n    let n2 := max_tyvar_term n e2 in\n    if ltb n1 n2 then n2 else n1\n  | If e1 e2 e3 =>\n    let n1 := max_tyvar_term n e1 in\n    let n2 := max_tyvar_term n e2 in\n    let n3 := max_tyvar_term n e3 in\n    let r := if ltb n1 n2 then n2 else n1 in\n    if ltb r n3 then n3 else r\n  | _ => n\n  end.\n\nFixpoint max_tyvar_list n l :=\n  match l with\n  | [] => n\n  | h :: t =>\n    let m := max_tyvar_type n h in\n    let r := if ltb n m then m else n in\n    max_tyvar_list r t\n  end.\n\nLemma Smax_tyvar_type_is_not_in : forall typ n n1,\n    max_tyvar_type n typ < n1 ->\n    tyn_in_type n1 typ = false.\nProof.\n  induction typ; simpl; intros; auto.\n  -\n    destruct ltb eqn:IH1.\n    apply Nat.ltb_lt in IH1. apply Nat.lt_trans with (p:= n1) in IH1; auto.\n    apply IHtyp1 in IH1. apply IHtyp2 in H. rewrite IH1, H. reflexivity.\n    apply Nat.ltb_ge in IH1. apply Nat.le_lt_trans with (p:= n1) in IH1; auto.\n    apply IHtyp1 in H. apply IHtyp2 in IH1. rewrite IH1, H; reflexivity.\n  -\n    destruct ltb eqn:IH.\n    +\n      apply Nat.lt_neq in H. apply Nat.eqb_neq in H. rewrite Nat.eqb_sym in H. rewrite H. reflexivity.\n    +\n      apply Nat.ltb_ge in IH. apply Nat.le_lt_trans with (p:= n1) in IH; auto.\n      rewrite Nat.eqb_sym. apply Nat.lt_neq in IH. apply Nat.eqb_neq in IH. rewrite IH. reflexivity.\nQed.\n\nLemma Smax_tyvar_term_is_not_in : forall e n m,\n    max_tyvar_term n e < m ->\n    tyn_in_term m e = false.\nProof.\n  induction e; simpl; intros; auto.\n  -\n    destruct ltb eqn:IH.\n    assert (tyn_in_type m typ = false).\n    +\n      apply Smax_tyvar_type_is_not_in with n. apply Nat.ltb_lt in IH.\n      apply Nat.lt_trans with (max_tyvar_term n e); auto.\n    +\n      rewrite H0. apply IHe in H. apply H.\n    +\n      apply Nat.ltb_ge in IH. apply Nat.le_lt_trans with (p:= m) in IH; auto. apply IHe in IH.\n      apply Smax_tyvar_type_is_not_in in H. rewrite IH, H. reflexivity.\n  -\n    destruct ltb eqn:IH.\n    +\n      apply Nat.ltb_lt in IH. apply Nat.lt_trans with (p:= m) in IH; auto.\n      apply IHe1 in IH. apply IHe2 in H. rewrite IH, H; reflexivity.\n    +\n      apply Nat.ltb_ge in IH. eapply Nat.le_lt_trans in IH; eauto.\n      apply IHe1 in H. apply IHe2 in IH. rewrite IH, H; reflexivity.\n  -\n    destruct (max_tyvar_term n e1 <? max_tyvar_term n e2) eqn:IH1.\n    +\n      destruct (max_tyvar_term n e2 <? max_tyvar_term n e3) eqn:IH2.\n      ++\n        apply Nat.ltb_lt in IH2. apply Nat.ltb_lt in IH1.\n        apply Nat.lt_trans with (p:= m) in IH2; auto.\n        apply Nat.lt_trans with (p:= m) in IH1; auto.\n        apply IHe1 in IH1. apply IHe2 in IH2. apply IHe3 in H.\n        rewrite IH1, IH2, H; reflexivity.\n      ++\n        apply Nat.ltb_lt in IH1. apply Nat.ltb_ge in IH2.\n        apply Nat.lt_trans with (p:= m) in IH1; auto.\n        apply Nat.le_lt_trans with (p:= m) in IH2; auto.\n        apply IHe1 in IH1. apply IHe2 in H. apply IHe3 in IH2.\n        rewrite IH1, IH2, H; reflexivity.\n    +\n      apply Nat.ltb_ge in IH1.\n      destruct (max_tyvar_term n e1 <? max_tyvar_term n e3) eqn:IH2.\n      ++\n        apply Nat.ltb_lt in IH2. apply Nat.lt_trans with (p:= m) in IH2; auto.\n        apply Nat.le_lt_trans with (p:= m) in IH1; auto.\n        apply IHe1 in IH2. apply IHe2 in IH1. apply IHe3 in H.\n        rewrite IH1, IH2, H; reflexivity.\n      ++\n        apply Nat.ltb_ge in IH2.\n        apply Nat.le_lt_trans with (p:= m) in IH1; auto.\n        apply Nat.le_lt_trans with (p:= m) in IH2; auto.\n        apply IHe1 in H. apply IHe2 in IH1. apply IHe3 in IH2.\n        rewrite H, IH1, IH2; reflexivity.\nQed.\n\nLemma max_tyvar_list_n_lt_m : forall l n m,\n    max_tyvar_list n l < m ->\n    n < m.\nProof.\n  induction l; simpl; intros; eauto.\n  destruct ltb eqn:IH; eauto.\n  apply Nat.ltb_lt in IH. apply Nat.lt_trans with (p:= m) in IH; auto.\nQed.\n\nLemma Smax_tyvar_list_is_not_in : forall l n m,\n    max_tyvar_list n l < m ->\n    tyn_in_list m l = false.\nProof.\n  induction l; simpl; intros; auto.\n  destruct ltb eqn:IH.\n  -\n    erewrite IHl; eauto.\n    apply max_tyvar_list_n_lt_m in H. apply Smax_tyvar_type_is_not_in in H.\n    rewrite H. reflexivity.\n  -\n    apply Nat.ltb_ge in IH.\n    apply Nat.le_lt_trans with (p:= m) in IH.\n    apply Smax_tyvar_type_is_not_in in IH.\n    erewrite IHl; eauto.\n    rewrite IH. reflexivity.\n    apply max_tyvar_list_n_lt_m in H; apply H.\nQed.\n\nDefinition max_tyvar_list_term n l e :=\n  let n1 := max_tyvar_list n l in\n  let m := max_tyvar_term n e in\n  if ltb n1 m then m else n1.\n\nLemma max_tyvar_list_term_is_not_in : forall n l e m,\n    max_tyvar_list_term n l e < m ->\n    tyn_in_list m l = false /\\ tyn_in_term m e = false.\nProof.\n  intros. unfold max_tyvar_list_term in H.\n  destruct ltb eqn:IH.\n  -\n    apply Nat.ltb_lt in IH.\n    apply Nat.lt_trans with (p:= m) in IH; auto.\n    apply Smax_tyvar_list_is_not_in in IH. rewrite IH.\n    apply Smax_tyvar_term_is_not_in in H. rewrite H. split; reflexivity.\n  -\n    apply Nat.ltb_ge in IH.\n    apply Nat.le_lt_trans with (p:= m) in IH; auto.\n    apply Smax_tyvar_term_is_not_in in IH.\n    apply Smax_tyvar_list_is_not_in in H.\n    auto.\nQed.\n\nReserved Notation \"Γ |-- n ` t \\in T | m ` C \"(at level 50).\nInductive Constrait_Type : context -> nat -> term -> ty -> nat -> list (ty * ty) -> Prop :=\n| CT_Var : forall x T Γ F,\n    getbinding x Γ = Some T ->\n    Γ |-- F ` Var x \\in T | F ` []\n| CT_Abs : forall Γ x T1 t2 T2 C F' F,\n    (T1:: Γ) |-- F ` t2 \\in T2 | F' ` C ->\n    Γ |-- F ` (Abs x T1 t2) \\in T1 |--> T2 | F' ` C\n| CT_App : forall Γ t1 ty1 C1 t2 ty2 C2 F' F'' F,\n    Γ |-- F ` t1 \\in ty1 | F' ` C1 -> Γ |-- F' ` t2 \\in ty2 | F'' ` C2 ->\n    Γ |-- F ` App t1 t2 \\in (TyVar (F'')) | (S F'') ` ((ty1, ty2 |--> TyVar (F'') ) :: C1 ++ C2)\n| CT_Tru : forall Γ F,\n    Γ |-- F ` Tru \\in Bool | F ` []\n| CT_Fls : forall Γ F,\n    Γ |-- F ` Fls \\in Bool | F ` []\n| CT_If : forall e1 e2 e3 ty1 ty2 ty3 F1 F2 F3 C1 C2 C3 Γ F,\n    Γ |-- F ` e1 \\in ty1 | F1 ` C1 -> Γ |-- F1 ` e2 \\in ty2 | F2 ` C2 ->\n    Γ |-- F2 ` e3 \\in ty3 | F3 ` C3 -> \n    Γ |-- F ` If e1 e2 e3 \\in ty3 | F3 ` ( (ty1, Bool):: (ty2, ty3) :: C1 ++ C2 ++ C3 )\nwhere \"Γ |-- n ` t \\in T | m ` C\" := (Constrait_Type Γ n t T m C).\n\nFixpoint Constrait_Type_fix Γ n e :=\n  match e with\n  | Var x => match getbinding x Γ with\n             | Some ty => Some (ty, n, nil)\n             | None => None\n             end\n  | Abs _ ty1 e1 =>\n    match Constrait_Type_fix (ty1 :: Γ) n e1 with\n    | Some (ty, n1, l) => Some (ty1 |--> ty, n1, l)\n    | None => None\n    end\n  | App e1 e2 =>\n    match Constrait_Type_fix Γ n e1 with\n    | Some (ty1, n1, C1) =>\n      match Constrait_Type_fix Γ n1 e2 with\n      | Some (ty2, n2, C2) =>\n        Some (TyVar (n2), S n2, (ty1, ty2 |--> (TyVar (n2)) ):: C1 ++ C2)\n      | None => None\n      end\n    | None => None\n    end\n  | Tru => Some (Bool, n, nil)\n  | Fls => Some (Bool, n, nil)\n  | If e1 e2 e3 =>\n    match Constrait_Type_fix Γ n e1 with\n    | Some (ty1, n1, C1) =>\n      match Constrait_Type_fix Γ n1 e2 with\n      | Some (ty2, n2, C2) =>\n        match Constrait_Type_fix Γ n2 e3 with\n        | Some (ty3, n3, C3) => Some (ty3, n3, (ty1, Bool):: (ty2, ty3) :: C1 ++ C2 ++ C3)\n        | Noen => None\n        end\n      | None => None\n      end\n    | None => None\n    end\n  end.\n\nLemma Constrait_Type_fix_Correct1 : forall Γ n e typ m C,\n    Γ |-- n ` e \\in typ | m ` C -> Constrait_Type_fix Γ n e = Some (typ, m, C).\nProof.\n  intros.\n  induction H; simpl; auto.\n  +\n    rewrite H. reflexivity.\n  +\n    rewrite IHConstrait_Type. reflexivity.\n  +\n    rewrite IHConstrait_Type1, IHConstrait_Type2. reflexivity.\n  +\n    rewrite IHConstrait_Type1, IHConstrait_Type2, IHConstrait_Type3; reflexivity.\nQed.\n\nLemma Constrait_Type_fix_Correct2 : forall e Γ n typ m C,\n    Constrait_Type_fix Γ n e = Some(typ, m, C) -> Γ |-- n ` e \\in typ | m ` C.\nProof.\n  induction e; simpl; intros; auto.\n  -\n    destruct getbinding eqn:IH; try discriminate.\n    inversion H; subst. constructor. rewrite IH. reflexivity.\n  -\n    destruct Constrait_Type_fix eqn:IH; try discriminate.\n    destruct p. destruct p. apply IHe in IH. inversion H; subst.\n    econstructor; eauto.\n  -\n    destruct Constrait_Type_fix eqn:IH1; try discriminate.\n    destruct p. destruct p. apply IHe1 in IH1.\n    destruct Constrait_Type_fix eqn:IH2; try discriminate.\n    destruct p. destruct p. apply IHe2 in IH2.\n    inversion H; subst.\n    econstructor; eauto.\n  -\n    inversion H; subst; constructor.\n  -\n    inversion H; subst; constructor.\n  -\n    destruct Constrait_Type_fix eqn:IH1; try discriminate.\n    destruct p. destruct p. apply IHe1 in IH1.\n    destruct Constrait_Type_fix eqn:IH2; try discriminate.\n    destruct p. destruct p. apply IHe2 in IH2.\n    destruct Constrait_Type_fix eqn:IH3; try discriminate.\n    destruct p. destruct p. apply IHe3 in IH3.\n    inversion H; subst.\n    econstructor; eauto.\nQed.\n\nDefinition CT_fix Γ e := Constrait_Type_fix Γ (S(max_tyvar_list_term 0 Γ e)) e.\n\nCompute (CT_fix []  (Abs \"x\" (TyVar 0) (Abs \"y\" (TyVar 1) (Abs \"z\" (TyVar 2)\n           (App (App (Var 2) (Var 0) ) (App (Var 1) (Var 0)) )) ))).\n\nFixpoint Constrais_sol_bool σ C :=\n  match C with\n  | nil => true\n  | (ty1, ty2) :: t =>\n    if eqb_ty (subst_type σ ty1) (subst_type σ ty2) then\n      (Constrais_sol_bool σ t)\n    else false\n  end.\n\nLemma Constrais_sol_bool_app : forall σ C1 C2,\n    Constrais_sol_bool σ (C1 ++ C2) = true ->\n    Constrais_sol_bool σ C1 = true /\\ Constrais_sol_bool σ C2 = true.\nProof.\n  induction C1; simpl; intros; auto.\n  destruct a.\n  destruct eqb_ty; try discriminate.\n  apply IHC1 in H. apply H.\nQed.\n\nTheorem T22_3_5 : forall e Γ S C σ T n m,\n    Γ |-- n ` e \\in S | m ` C ->\n    subst_type σ S = T -> Constrais_sol_bool σ C = true ->\n    subst_type_list σ Γ |- subst_type_term σ e \\in T.\nProof.\n  induction e; simpl; intros; auto.\n  -\n    rewrite <- H0.\n    inversion H; subst.\n    assert (Var n = subst_type_term σ (Var n)). reflexivity.\n    rewrite H0.\n    apply T22_1_2. constructor; auto.\n  -\n    inversion H; subst.\n    eapply IHe in H10; eauto.\n    constructor. apply H10.\n  -\n    inversion H; subst.\n    simpl in H1.\n    destruct eqb_ty eqn:IH1; try discriminate.\n    apply eqb_ty_eq in IH1; subst.\n    apply Constrais_sol_bool_app in H1. destruct H1.\n    econstructor; eauto.\n  -\n    inversion H; subst. simpl. constructor.\n  -\n    inversion H; subst. simpl. constructor.\n  -\n    inversion H; subst. simpl in H1.\n    destruct eqb_ty eqn:IH1; try discriminate.\n    apply eqb_ty_eq in IH1; subst.\n    destruct eqb_ty eqn:IH2; try discriminate.\n    apply eqb_ty_eq in IH2; subst.\n    apply Constrais_sol_bool_app in H1. destruct H1.\n    apply Constrais_sol_bool_app in H1; destruct H1.\n    constructor; eauto.\nQed.\n\nLemma app_Constrais_sol_bool : forall σ C1 C2,\n    Constrais_sol_bool σ C1 = true -> Constrais_sol_bool σ C2 = true ->\n    Constrais_sol_bool σ (C1 ++ C2) = true.\nProof.\n  induction C1; simpl; intros; auto.\n  destruct a. destruct eqb_ty; try discriminate.\n  apply IHC1; auto.\nQed.    \n\nLemma getbind_sub : forall σ Γ n T S,\n  getbinding n (subst_type_list σ Γ) = Some T ->\n  getbinding n Γ = Some S ->\n  subst_type σ S = T.\nProof.\n  induction Γ; simpl; intros.\n  -\n    destruct n; discriminate.\n  -\n    destruct n; simpl in H, H0.\n    inversion H0; subst. inversion H; subst. reflexivity.\n    eapply IHΓ; eauto.\n Qed.   \n\nFixpoint max_sigma n (σ: list (nat * ty) ) :=\n  match σ with\n  | nil => n\n  | (m, _):: rest =>\n    let x := if ltb n m then m else n in\n    max_sigma x rest\n  end.\n\nLemma CT_n_lt : forall e Γ n typ m C,\n    Γ |-- n ` e \\in typ | m ` C -> n <= m.\nProof.\n  intros. induction H; auto.\n  -\n    eapply le_trans with (p:= F'') in IHConstrait_Type1; eauto. \n  -\n    eapply le_trans with (p:= F2) in IHConstrait_Type1; eauto. \n    eapply le_trans with (p:= F3) in IHConstrait_Type1; eauto. \nQed.\n\nFixpoint dom_sigma_in n (σ :list (nat * ty)) :=\n  match σ with\n  | nil => false\n  | (m, _) :: rest => if eqb n m then true else dom_sigma_in n rest\n  end.\n\nFixpoint dom_sigma_in_range n m σ :=\n  match m with\n  | 0 => false\n  | S m' => dom_sigma_in (S n) σ || dom_sigma_in_range (S n) m' σ\n  end.\n\nLemma dom_sigma_range_correct : forall m n σ,\n    dom_sigma_in_range n m σ = false ->\n    (forall x, n <= S x -> x <= (n + m) -> dom_sigma_in x σ = false).\nProof.\nAbort.\n\nFixpoint subst_type_opt l t n m :=\n  match t with\n  | Bool => Some Bool\n  | TyVar x =>\n    if ltb n x && leb x m then None\n    else Some (match_natlist l x t)\n  | t1 |--> t2 =>\n    match subst_type_opt l t1 n m , subst_type_opt l t2 n m with\n    | Some ty1, Some ty2 => Some (ty1 |--> ty2)\n    | _, _ => None\n    end\n  end.\n\nFixpoint opt_subst_type_list σ Γ n m :=\n  match Γ with\n  | nil => Some nil\n  | h :: t =>\n    match subst_type_opt σ h n m with\n    | Some h' =>\n      match opt_subst_type_list σ t n m with\n      | Some t' => Some (h' :: t')\n      | None => None\n      end\n    | None => None\n    end\n  end.\n\nFixpoint opt_subst_type_term σ e n m :=\n  match e with\n  | Abs x typ e1 =>\n    match subst_type_opt σ typ n m, opt_subst_type_term σ e1 n m with\n    | Some ty', Some e' => Some (Abs x ty' e')\n    | _, _ => None\n    end\n  | App e1 e2 =>\n    match opt_subst_type_term σ e1 n m, opt_subst_type_term σ e2 n m with\n    | Some e1', Some e2' => Some (App e1' e2')\n    | _, _ => None\n    end\n  | If e1 e2 e3 =>\n    match opt_subst_type_term σ e1 n m, opt_subst_type_term σ e2 n m, opt_subst_type_term σ e3 n m with\n    | Some e1', Some e2', Some e3' => Some (If e1' e2' e3')\n    | _, _, _ => None\n    end\n  | _ => Some e\n  end.\n\nLemma subst_type_opt_refl : forall σ typ n,\n    subst_type_opt σ typ n n = Some (subst_type σ typ).\nProof.\n  induction typ; simpl; intros; auto.\n  -\n    rewrite IHtyp1, IHtyp2. reflexivity.\n  -\n    destruct ltb eqn:IH1; simpl; auto.\n    apply ltb_lt in IH1. apply leb_gt in IH1. rewrite IH1. reflexivity.\nQed.    \n\nLemma opt_subst_type_term_refl : forall σ e n,\n    opt_subst_type_term σ e n n = Some (subst_type_term σ e).\nProof.\n  induction e; simpl; intros; eauto.\n  -\n    rewrite IHe. rewrite subst_type_opt_refl. reflexivity.\n  -\n    rewrite IHe1, IHe2. reflexivity.\n  -\n    rewrite IHe1, IHe2, IHe3. reflexivity.\nQed.    \n\nLemma opt_subst_type_list_refl : forall σ Γ n,\n    opt_subst_type_list σ Γ n n = Some (subst_type_list σ Γ).\nProof.\n  induction Γ; simpl; intros; auto.\n  rewrite IHΓ. rewrite subst_type_opt_refl. reflexivity.\nQed.\n\nLemma opt_to_subst_type : forall typ σ n m t',\n    subst_type_opt σ typ n m = Some t' ->\n    subst_type σ typ = t'.\nProof.\n  induction typ; simpl; intros; auto.\n  -\n    inversion H; subst; auto.\n  -\n    destruct subst_type_opt eqn:IH1; try discriminate.\n    apply IHtyp1 in IH1. \n    destruct subst_type_opt eqn:IH2; try discriminate.\n    apply IHtyp2 in IH2.\n    inversion H; subst.\n    reflexivity.\n  -\n    destruct ltb; simpl in H.\n    destruct leb; try discriminate.\n    inversion H; subst. reflexivity.\n    inversion H; subst. reflexivity.\nQed.\n\nLemma opt_to_subst_list : forall l σ n m l',\n    opt_subst_type_list σ l n m = Some l' ->\n    subst_type_list σ l = l'.\nProof.\n  induction l; simpl; intros; auto.\n  -\n    inversion H; subst. reflexivity.\n  -\n    destruct subst_type_opt eqn:IH1; try discriminate.\n    destruct opt_subst_type_list eqn:IH2; try discriminate.\n    apply opt_to_subst_type in IH1.\n    inversion H; subst.\n    apply IHl in IH2. rewrite IH2.\n    reflexivity.\nQed.    \n\nLemma opt_to_subst_term : forall e σ n m e',\n    opt_subst_type_term σ e n m = Some e' ->\n    subst_type_term σ e = e'.\nProof.\n  induction e; simpl; intros; try solve [inversion H; subst; reflexivity].\n  -\n    destruct subst_type_opt eqn:IH1; try discriminate.\n    apply opt_to_subst_type in IH1.\n    destruct opt_subst_type_term eqn:IH2; try discriminate.\n    apply IHe in IH2. inversion H; subst.\n    reflexivity.\n  -\n    destruct opt_subst_type_term eqn:IH1; try discriminate.\n    apply IHe1 in IH1.\n    destruct opt_subst_type_term eqn:IH2; try discriminate.\n    apply IHe2 in IH2.\n    inversion H; subst. reflexivity.\n  -\n    destruct opt_subst_type_term eqn:IH1; try discriminate.\n    apply IHe1 in IH1.\n    destruct opt_subst_type_term eqn:IH2; try discriminate.\n    apply IHe2 in IH2.\n    destruct opt_subst_type_term eqn:IH3; try discriminate.\n    apply IHe3 in IH3.\n    inversion H; subst; reflexivity.\nQed.    \n\nLemma dom_notin_app : forall σ1 σ2 n,\n    dom_sigma_in n σ1 = false ->\n    dom_sigma_in n σ2 = false ->\n    dom_sigma_in n (σ1 ++ σ2) = false.\nProof.\n  induction σ1; simpl; intros; auto.\n  destruct a. destruct eqb; try discriminate.\n  apply IHσ1; auto.\nQed.\n\nLemma dom_notin_app_eq : forall ad n σ,\n    dom_sigma_in n ad = false ->\n    match_natlist σ n (TyVar n) = match_natlist (ad ++ σ) n (TyVar n).\nProof.\n  induction ad; simpl; intros.\n  -\n    reflexivity.\n  -\n    destruct a. destruct eqb eqn:IH; try discriminate.\n    apply IHad with (σ := σ) in H; eauto.\n    rewrite eqb_sym. rewrite IH. rewrite H. reflexivity.\nQed.\n\nLemma subst_type_opt_m : forall ty1 n m x σ ty2,\n    x <= m ->\n    subst_type_opt σ ty1 n m = Some ty2 ->\n    subst_type_opt σ ty1 n x = Some ty2.\nProof.\n  induction ty1; simpl; intros; auto.\n  -\n    destruct subst_type_opt eqn:IH1; try discriminate.\n    eapply IHty1_1 in IH1; eauto.\n    destruct subst_type_opt eqn:IH2; try discriminate.\n    eapply IHty1_2 in IH2; eauto.\n    inversion H0; inversion IH1; inversion IH2; subst.\n    rewrite IH1, IH2. reflexivity.\n  -\n    destruct ltb eqn:IH1; destruct leb eqn:IH2; try discriminate;\n      simpl in H0; inversion H0; subst; try rewrite andb_false_l; auto.\n    apply ltb_lt in IH1. apply leb_gt in IH2.\n    apply le_lt_trans with (p:= n) in H; auto.\n    apply leb_gt in H. rewrite H. simpl. reflexivity.\nQed.\n\nLemma opt_subst_type_list_m : forall l n m x σ l',\n    x <= m ->\n    opt_subst_type_list σ l n m = Some l' ->\n    opt_subst_type_list σ l n x = Some l'.\nProof.\n  induction l; simpl; auto; intros.\n  destruct subst_type_opt eqn:IH1; try discriminate.\n  eapply subst_type_opt_m in IH1; eauto. rewrite IH1.\n  destruct opt_subst_type_list eqn:IH2; try discriminate.\n  eapply IHl in IH2; eauto. rewrite IH2.\n  apply H0.\nQed.\n\nLemma opt_subst_type_term_m : forall e n m x σ e',\n    x <= m ->\n    opt_subst_type_term σ e n m = Some e' ->\n    opt_subst_type_term σ e n x = Some e'.\nProof.\n  induction e; simpl; intros; auto.\n  -\n    destruct subst_type_opt eqn:IH1; try discriminate.\n    erewrite subst_type_opt_m; eauto.\n    destruct opt_subst_type_term eqn:IH2; try discriminate.\n    erewrite IHe; eauto.\n  -\n    destruct opt_subst_type_term eqn:IH1; try discriminate.\n    erewrite IHe1; eauto; clear IH1.\n    destruct opt_subst_type_term eqn:IH; try discriminate.\n    erewrite IHe2; eauto.\n  -\n    destruct opt_subst_type_term eqn:IH1; try discriminate.\n    erewrite IHe1; eauto; clear IH1.\n    destruct opt_subst_type_term eqn:IH; try discriminate.\n    erewrite IHe2; eauto; clear IH.\n    destruct opt_subst_type_term eqn:IH; try discriminate.\n    erewrite IHe3; eauto; clear IH.\nQed.\n\nLemma subst_type_opt_n : forall ty1 n m x σ ty2,\n    n <= x <= m ->\n    subst_type_opt σ ty1 n m = Some ty2 ->\n    subst_type_opt σ ty1 x m = Some ty2.\nProof.\n  induction ty1; simpl; intros; auto.\n  -\n    destruct subst_type_opt eqn:IH1; try discriminate.\n    eapply IHty1_1 in IH1; eauto.\n    destruct subst_type_opt eqn:IH2; try discriminate.\n    eapply IHty1_2 in IH2; eauto.\n    inversion H0; inversion IH1; inversion IH2; subst.\n    rewrite IH1, IH2. reflexivity.\n  -\n    destruct ltb eqn:IH1.\n    +\n      destruct leb eqn:IH2; try discriminate.\n      simpl in H0. inversion H0; subst.\n      apply ltb_lt in IH1. apply leb_gt in IH2.\n      destruct H.\n      apply le_lt_trans with (p:= n) in H1; auto. apply ltb_lt in H1.\n      rewrite H1. simpl. reflexivity.\n    +\n      rewrite andb_false_l in H0. inversion H0; subst.\n      destruct H. apply ltb_ge in IH1.\n      apply le_trans with (p:= x) in IH1; auto.\n      apply ltb_ge in IH1. rewrite IH1.\n      rewrite andb_false_l. reflexivity.\nQed.\n\nLemma subst_list_opt_n : forall l n m x σ l0,\n    n <= x <= m ->\n    opt_subst_type_list σ l n m = Some l0 ->\n    opt_subst_type_list σ l x m = Some l0.\nProof.\n  induction l; simpl; intros; auto.\n  destruct subst_type_opt eqn:IH1; try discriminate.\n  destruct opt_subst_type_list eqn:IH2; try discriminate.\n  eapply subst_type_opt_n in IH1; eauto. rewrite IH1.\n  eapply IHl in IH2; eauto. rewrite IH2.\n  inversion H; subst; auto.\nQed.    \n\nLemma subst_term_opt_n : forall e n m x σ e0,\n    n <= x <= m ->\n    opt_subst_type_term σ e n m = Some e0 ->\n    opt_subst_type_term σ e x m = Some e0.\nProof.\n  induction e; simpl; intros; auto.\n  -\n    destruct subst_type_opt eqn:IH1; try discriminate.\n    erewrite subst_type_opt_n; eauto.\n    destruct opt_subst_type_term eqn:IH2; try discriminate.\n    erewrite IHe; eauto.\n  -\n    destruct opt_subst_type_term eqn:IH; try discriminate.\n    erewrite IHe1; eauto; clear IH.\n    destruct opt_subst_type_term eqn:IH; try discriminate.\n    erewrite IHe2; eauto; clear IH.\n  -\n    destruct opt_subst_type_term eqn:IH; try discriminate.\n    erewrite IHe1; eauto; clear IH.\n    destruct opt_subst_type_term eqn:IH; try discriminate.\n    erewrite IHe2; eauto; clear IH.\n    destruct opt_subst_type_term eqn:IH; try discriminate.\n    erewrite IHe3; eauto; clear IH.\nQed.\n\nLemma dom_in_app : forall σ1 σ2 n typ,\n    dom_sigma_in n σ1 = true ->\n    match_natlist (σ1 ++ σ2) n typ = match_natlist σ1 n typ.\nProof.\n  induction σ1; simpl; intros; auto.\n  -\n    inversion H; subst.\n  -\n    destruct a. rewrite eqb_sym. destruct eqb; auto.\nQed.\n\nLemma subst_type_eq_add : forall t1 σ1 σ2 ad,\n    subst_type σ1 t1 = subst_type σ2 t1 ->\n    subst_type (ad ++ σ1) t1 = subst_type (ad ++ σ2) t1.\nProof.\n  induction t1; simpl; intros; auto.\n  -\n    inversion H; subst.\n    erewrite IHt1_1, IHt1_2; eauto.\n  -\n    induction ad; simpl; auto.\n    destruct a.\n    rewrite IHad. reflexivity.\nQed.    \n\nLemma max_tyvar_app : forall e1 e2 m n,\n    max_tyvar_term n (App e1 e2) < m ->\n    max_tyvar_term n e1 < m /\\ max_tyvar_term n e2 < m.\nProof.\n  simpl; intros.\n  destruct ltb eqn:IH.\n  apply ltb_lt in IH. split; auto. eapply lt_trans; eauto.\n  apply ltb_ge in IH. apply le_lt_trans with (p:= m) in IH; auto.\nQed.\n\nLemma max_tyvar_abs : forall e1 t1 m n x,\n    max_tyvar_term n ( Abs x t1 e1 ) < m ->\n    max_tyvar_term n e1 < m /\\ max_tyvar_type n t1 < m.\nProof.\n  simpl; intros.\n  destruct ltb eqn:IH.\n  apply ltb_lt in IH. split; auto. eapply lt_trans; eauto.\n  apply ltb_ge in IH. split; auto. eapply le_lt_trans; eauto.\nQed.\n\nLemma max_tyvar_if : forall e1 e2 e3 m n ,\n    max_tyvar_term n ( If e1 e2 e3 ) < m ->\n    max_tyvar_term n e1 < m /\\ max_tyvar_term n e2 < m /\\ max_tyvar_term n e3 < m.\nProof.\n  simpl; intros.\n  destruct (ltb (max_tyvar_term n e1) (max_tyvar_term n e2) ) eqn:IH1.\n  -\n    apply ltb_lt in IH1. destruct ltb eqn:IH2.\n    ++\n      apply ltb_lt in IH2.\n      repeat split; auto. eapply lt_trans in IH2; eauto.\n      eapply lt_trans; eauto.\n      eapply lt_trans; eauto.\n    ++\n      apply ltb_ge in IH2.\n      repeat split; auto.\n      eapply lt_trans; eauto.\n      eapply le_lt_trans in H; eauto.\n  -\n    apply ltb_ge in IH1. destruct ltb eqn:IH2.\n    +\n      apply ltb_lt in IH2.\n      repeat split; auto.\n      eapply lt_trans; eauto.\n      apply le_lt_trans with (p:= max_tyvar_term n e3) in IH1; auto.\n      apply lt_le_trans with (p:=m) in IH1; auto.\n      apply lt_le_incl; auto.\n    +\n      apply ltb_ge in IH2.\n      repeat split; auto.\n      eapply le_lt_trans; eauto.\n      eapply le_lt_trans; eauto.\nQed.\n\nLemma max_tyvar_list_lt : forall Γ n m,\n    max_tyvar_list n Γ < m ->\n    n < m.\nProof.\n  induction Γ; intros; auto.\n  simpl in H.\n  destruct ltb eqn:IH; eauto.\n  apply ltb_lt in IH.\n  eapply IHΓ in H. eapply lt_trans; eauto.\nQed.\n\nLemma max_list_getbind : forall Γ m typ n x,\n    max_tyvar_list x Γ < m ->\n    getbinding n Γ = Some typ ->\n    tyn_in_type m typ = false.\nProof.\n  induction Γ; intros; auto.\n  -\n    destruct n; simpl in H0; try discriminate.\n  -\n    destruct n; simpl in H0.\n    inversion H0; subst; clear H0.\n    simpl in H.\n    destruct ltb eqn:IH1.\n    apply max_tyvar_list_lt in H.\n    apply Smax_tyvar_type_is_not_in with x; auto.\n    apply ltb_ge in IH1.\n    apply max_tyvar_list_lt in H.\n    apply Smax_tyvar_type_is_not_in with x; auto.\n    apply le_lt_trans with x; auto.\n    eapply IHΓ in H0; eauto.\nQed.\n\nLemma max_type_ch : forall t1 n m x,\n    n < m < x ->\n    max_tyvar_type n t1 < x ->\n    max_tyvar_type m t1 < x.\nProof.\n  induction t1; simpl; intros; auto.\n  -\n    destruct H; auto.\n  -\n    destruct (ltb (max_tyvar_type n t1_1) (max_tyvar_type n t1_2) ) eqn:IH1.\n    apply ltb_lt in IH1. \n    destruct ltb eqn:IH2; auto.\n    eapply IHt1_2 in H0; eauto.\n    apply ltb_ge in IH2.\n    apply IHt1_1 with n; auto.\n    eapply lt_trans; eauto.\n\n    apply ltb_ge in IH1.\n    destruct ltb eqn:IH2; eauto.\n    apply ltb_lt in IH2.\n    apply IHt1_2 with n; auto.\n    eapply le_lt_trans; eauto.\n  -\n    destruct H.\n    destruct (n0 <? n) eqn:IH1.\n    apply ltb_lt in IH1.\n    destruct ltb; auto.\n    apply ltb_ge in IH1.\n    apply le_lt_trans with (p:= x) in IH1; auto.\n    destruct ltb; auto.\nQed.\n\nLemma max_list_ch : forall Γ n m x,\n    n < m < x ->\n    max_tyvar_list n Γ < x ->\n    max_tyvar_list m Γ < x.\nProof.\n  induction Γ; simpl; intros; destruct H; auto.\n  destruct ltb eqn:IH1.\n  -\n    apply ltb_lt in IH1.\n    destruct ltb eqn:IH2.\n    +\n      apply ltb_lt in IH2.\n      generalize H0; intros.\n      apply max_tyvar_list_n_lt_m in H0.\n      generalize max_type_ch; intros.\n      eapply IHΓ; eauto.\n      destruct (ltb (max_tyvar_type n a) m) eqn:IH.\n      apply ltb_lt in IH.\n      eapply IHΓ with (max_tyvar_type n a); auto.\n      apply ltb_ge in IH.\nAdmitted.\n\nLemma max_list_app : forall Γ m G x,\n    max_tyvar_list x Γ < m ->\n    max_tyvar_list x G < m ->\n    max_tyvar_list x (Γ ++ G) < m.\nProof.\n  induction Γ; intros; auto.\n  simpl. simpl in H. \n  destruct ltb eqn:IH.\n  apply ltb_lt in IH.\n  generalize H; intros.\n  apply IHΓ; auto.\n  apply max_list_ch with x; auto.\n  split; auto. apply max_tyvar_list_n_lt_m in H.\n  apply H.\n  apply IHΓ; eauto.\nQed.\n\nLemma CT_nont : forall e Γ n m T C,\n    Γ |-- n ` e \\in T | m ` C ->\n    max_tyvar_list 0 Γ < n ->\n    max_tyvar_term 0 e < n ->\n    forall x, m <= x -> tyn_in_type x T = false. \nProof.\n  intros. generalize dependent x. induction H; simpl; intros; auto.\n  -\n    eapply max_list_getbind; eauto.\n    apply lt_le_trans with F; eauto.\n  -\n    apply CT_n_lt in H.\n    apply orb_false_iff. apply max_tyvar_abs in H1. destruct H1.\n    split; auto.\n    eapply Smax_tyvar_type_is_not_in.\n    apply lt_le_trans with F'; eauto.\n    apply lt_le_trans with F; eauto.\n    apply IHConstrait_Type; auto.\n    assert (T1 :: Γ = [T1] ++ Γ); auto.\n    rewrite H4.\n    apply max_list_app; auto.\n    simpl. destruct ltb; auto.\n    apply max_tyvar_list_n_lt_m in H0. apply H0.\n  -\n    apply eqb_neq. intro.\n    subst. apply nle_succ_diag_l in H3. apply H3.\n  -\n    apply CT_n_lt in H, H2, H3.\n    apply max_tyvar_if in H1.\n    destruct H1. destruct H5.\n    apply IHConstrait_Type3; auto.\n    apply lt_le_trans with F; auto.\n    apply le_trans with F1; auto.\n    apply lt_le_trans with F; auto.\n    apply le_trans with F1; auto.\nQed.\n\nFixpoint ext_sigma (σ: list (nat * ty)) n m :=\n  match σ with\n  | nil => nil\n  | (x, t1) :: rest =>\n    if (n <? x) && (x <=? m) then (x, t1) :: (ext_sigma rest n m)\n    else ext_sigma rest n m\n  end.\n\nTheorem T22_3_7 : forall e Γ S1 C σ T n m,\n    max_tyvar_list 0 Γ < n ->\n    max_tyvar_term 0 e < n ->\n    subst_type_list σ Γ |- subst_type_term σ e \\in T ->\n    Γ |-- n ` e \\in S1 | m ` C ->\n    (forall x, n < x <= m -> dom_sigma_in x σ = false) ->\n    exists σ', (forall typ, subst_type_opt σ' typ n m = Some (subst_type σ typ)) /\\\n    subst_type σ' S1 = T /\\ Constrais_sol_bool σ' C = true.\nProof.\n  intros. generalize dependent σ. generalize dependent T.\n  induction H2; simpl; intros; auto.\n  -\n    inversion H2; subst. exists σ. repeat split;  intros; auto.\n    apply subst_type_opt_refl.\n    eapply getbind_sub; eauto.\n  -\n    inversion H1; subst.\n    apply max_tyvar_abs in H0. destruct H0.\n    eapply IHConstrait_Type in H9; eauto; clear IHConstrait_Type.\n    destruct H9. destruct H5. destruct H6.\n    exists x0. repeat split; intros; auto. rewrite H6.\n    admit.\n    simpl.\n    destruct ltb eqn:IH; auto.\n    admit.\n  -\n    inversion H1; subst.\n    eapply IHConstrait_Type1 in H6; eauto; clear IHConstrait_Type1.\n    eapply IHConstrait_Type2 in H8; eauto; clear IHConstrait_Type2.\n    destruct H6. destruct H2. destruct H4.\n    destruct H8. destruct H6; destruct H7.\n    admit. admit. admit. admit. admit. admit.\n  -\n    exists σ. inversion H1; subst; repeat split; intros; auto.\n    apply subst_type_opt_refl.\n  -\n    exists σ. inversion H1; subst; repeat split; intros; auto.\n    apply subst_type_opt_refl.\n  -\n    inversion H1; subst.\n    apply CT_n_lt in H2_, H2_0, H2_1.\n    eapply IHConstrait_Type1 in H7; eauto; clear IHConstrait_Type1.\n    eapply IHConstrait_Type2 in H9; eauto; clear IHConstrait_Type2.\n    eapply IHConstrait_Type3 in H10; eauto; clear IHConstrait_Type3.\n    destruct H7. destruct H2. destruct H4.\n    destruct H9. destruct H6. destruct H7.\n    destruct H10. destruct H9. destruct H10.\nAbort.\n", "meta": {"author": "NeM-T", "repo": "Formalizing-TaPL", "sha": "2a4dba29d0850a7494c7fd52c0daf4bbb3879691", "save_path": "github-repos/coq/NeM-T-Formalizing-TaPL", "path": "github-repos/coq/NeM-T-Formalizing-TaPL/Formalizing-TaPL-2a4dba29d0850a7494c7fd52c0daf4bbb3879691/recon/chap22.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7480443678222894}}
{"text": "Require Import Problem PeanoNat Nat.\n\nLemma plus_decomp (m n : nat) (f : nat -> nat) (x : nat)\n  : iter (m + n) f x = iter m f (iter n f x).\nProof.\n  induction m; simpl; auto.\nQed.\n\nLemma mult_decomp (m n : nat) (f : nat -> nat) (x : nat)\n  : iter (m * n) f x = iter m (iter n f) x.\nProof.\n  induction m; simpl; [auto|].\n  rewrite plus_decomp; auto.\nQed.\n\nLemma beta (n y : nat) (f g : nat -> nat)\n  : (forall x, f x = g x) -> iter n f y = iter n g y.\nProof.\n  intros.\n  induction n; [auto|].\n  simpl; rewrite IHn; auto.\nQed.\n\nTheorem solution: task.\nProof.\n  unfold task.\n  induction n; [auto|].\n  intros; simpl.\n  rewrite mult_decomp.\n  apply beta.\n  auto.\nQed.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/028/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7479996670141233}}
{"text": "Require Import PeanoNat.\n\nRequire Import RaftState.\nRequire Import Raft.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Export CommonDefinitions.\n\nSection CommonTheorems.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Lemma uniqueIndices_elim_eq :\n    forall xs x y,\n      uniqueIndices xs ->\n      In x xs ->\n      In y xs ->\n      eIndex x = eIndex y ->\n      x = y.\n  Proof using. \n    unfold uniqueIndices.\n    eauto using NoDup_map_elim.\n  Qed.\n\n  Lemma sorted_cons :\n    forall xs a,\n      sorted xs ->\n      (forall a', In a' xs -> eIndex a > eIndex a' /\\ eTerm a >= eTerm a') ->\n      sorted (a :: xs).\n  Proof using. \n    intros.\n    simpl in *. intuition;\n      find_apply_hyp_hyp; intuition.\n  Qed.\n\n  Lemma sorted_subseq :\n    forall ys xs,\n      subseq xs ys ->\n      sorted ys ->\n      sorted xs.\n  Proof using. \n    induction ys; intros; simpl in *.\n    - break_match; intuition.\n    - break_match; intuition.\n      subst. apply sorted_cons; eauto.\n      intros. eauto using subseq_In.\n  Qed.\n\n  Theorem maxTerm_is_max :\n    forall l e,\n      sorted l ->\n      In e l ->\n      maxTerm l >= eTerm e.\n  Proof using. \n    induction l; intros.\n    - simpl in *. intuition.\n    - simpl in *. intuition.\n      + subst. auto with *.\n      + find_apply_hyp_hyp. omega.\n  Qed.\n\n  Theorem maxIndex_is_max :\n    forall l e,\n      sorted l ->\n      In e l ->\n      maxIndex l >= eIndex e.\n  Proof using. \n    induction l; intros.\n    - simpl in *. intuition.\n    - simpl in *. intuition.\n      + subst. auto with *.\n      + find_apply_hyp_hyp. omega.\n  Qed.\n\n  Theorem S_maxIndex_not_in :\n    forall l e,\n      sorted l ->\n      eIndex e = S (maxIndex l) ->\n      ~ In e l.\n  Proof using. \n    intros. intro.\n    find_apply_lem_hyp maxIndex_is_max; auto.\n    subst. omega.\n  Qed.\n\n  Lemma maxIndex_non_empty :\n    forall l,\n      l <> nil ->\n      exists e,\n        In e l /\\ maxIndex l = eIndex e /\\ maxTerm l = eTerm e.\n  Proof using. \n    destruct l; intros; simpl in *; eauto; congruence.\n  Qed.\n\n  Lemma removeAfterIndex_subseq :\n    forall l i,\n      subseq (removeAfterIndex l i) l.\n  Proof using. \n    induction l; intros; simpl; auto.\n    repeat break_match; intuition.\n    - find_inversion. eauto using subseq_refl.\n    - right. find_reverse_rewrite. auto.\n  Qed.\n\n  Lemma removeAfterIndex_sorted :\n    forall l i,\n      sorted l ->\n      sorted (removeAfterIndex l i).\n  Proof using. \n    intros. eauto using removeAfterIndex_subseq, sorted_subseq.\n  Qed.\n\n  Lemma removeAfterIndex_in :\n    forall l i a,\n      In a (removeAfterIndex l i) ->\n      In a l.\n  Proof using. \n    eauto using removeAfterIndex_subseq, subseq_In.\n  Qed.\n\n\n  Lemma findAtIndex_not_in :\n    forall l e,\n      sorted l ->\n      findAtIndex l (eIndex e) = None ->\n      ~ In e l.\n  Proof using. \n    induction l; intros; intro.\n    - intuition.\n    - simpl in *. break_match; try discriminate. intuition.\n      + subst. rewrite <- beq_nat_refl in *. discriminate.\n      + find_copy_apply_hyp_hyp. intuition. break_if; do_bool; eauto. omega.\n  Qed.\n\n  Lemma findAtIndex_in :\n    forall l i e',\n      findAtIndex l i = Some e' ->\n      In e' l.\n  Proof using. \n    induction l; intros.\n    - discriminate.\n    - simpl in *. break_match.\n      + find_inversion. auto.\n      + break_if; eauto; discriminate.\n  Qed.\n\n  Lemma findAtIndex_index :\n    forall l i e',\n      findAtIndex l i = Some e' ->\n      i = eIndex e'.\n  Proof using. \n    induction l; intros.\n    - discriminate.\n    - simpl in *. break_match.\n      + find_inversion. apply beq_nat_true in Heqb. auto.\n      + break_if; eauto; discriminate.\n  Qed.\n\n  Lemma NoDup_removeAfterIndex :\n    forall l i,\n      NoDup l ->\n      NoDup (removeAfterIndex l i).\n  Proof using. \n    eauto using subseq_NoDup, removeAfterIndex_subseq.\n  Qed.\n\n  Notation disjoint xs ys := (forall x, In x xs -> In x ys -> False).\n\n  Lemma removeAfterIndex_le_In :\n    forall xs i x,\n      eIndex x <= i ->\n      In x xs ->\n      In x (removeAfterIndex xs i).\n  Proof using. \n    induction xs; intros.\n    - intuition.\n    - simpl in *. break_if; simpl in *; intuition.\n      subst. do_bool. omega.\n  Qed.\n\n  Lemma removeAfterIndex_In_le :\n    forall xs i x,\n      sorted xs ->\n      In x (removeAfterIndex xs i) ->\n      eIndex x <= i.\n  Proof using. \n    induction xs; intros.\n    - simpl in *. intuition.\n    - simpl in *.\n      break_if; simpl in *; do_bool; intuition; subst; auto.\n      find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma removeAfterIndex_covariant :\n    forall xs ys i x,\n      sorted xs ->\n      sorted ys ->\n      In x (removeAfterIndex xs i) ->\n      (forall x, In x xs -> In x ys) ->\n      In x (removeAfterIndex ys i).\n  Proof using. \n    induction xs; intros.\n    - simpl in *. intuition.\n    - simpl in *.\n      break_match; simpl in *; intuition;\n      subst; do_bool;\n      match goal with\n        | e : entry, H : forall _, _ = _ \\/ _ -> _ |- _ =>\n          specialize (H e)\n      end;\n      intuition.\n      + eauto using removeAfterIndex_le_In.\n      + find_apply_hyp_hyp. intuition.\n        match goal with\n          | _ : eIndex ?e <= ?li, _ : eIndex ?e > eIndex ?e' |- _ =>\n            assert (eIndex e' <= li) by omega\n        end.\n        eauto using removeAfterIndex_le_In.\n  Qed.\n\n  Lemma removeAfterIndex_le :\n    forall xs i j,\n      i <= j ->\n      removeAfterIndex xs i = removeAfterIndex (removeAfterIndex xs j) i.\n  Proof using. \n    induction xs; intros.\n    - reflexivity.\n    - simpl.\n      find_copy_apply_hyp_hyp.\n      repeat (break_if; simpl in *; intuition); try discriminate.\n      do_bool. omega.\n  Qed.\n\n  Lemma removeAfterIndex_2_subseq :\n    forall xs i j,\n      subseq (removeAfterIndex (removeAfterIndex xs i) j) (removeAfterIndex (removeAfterIndex xs j) i).\n  Proof using. \n    induction xs; intros; simpl.\n    - auto.\n    - repeat (break_match; simpl); intuition; try discriminate.\n      + eauto using subseq_refl.\n      + do_bool. assert (j < i) by omega.\n        rewrite removeAfterIndex_le with (j := i) (i := j) at 1; auto; omega.\n      + do_bool. assert (i < j) by omega.\n        rewrite removeAfterIndex_le with (i := i) (j := j) at 2; auto; omega.\n  Qed.\n\n  Lemma removeAfterIndex_comm :\n    forall xs i j,\n      removeAfterIndex (removeAfterIndex xs i) j =\n      removeAfterIndex (removeAfterIndex xs j) i.\n  Proof using. \n    auto using subseq_subseq_eq, removeAfterIndex_2_subseq.\n  Qed.\n\n  Lemma removeAfterIndex_2_eq_min :\n    forall xs i j,\n      removeAfterIndex (removeAfterIndex xs i) j =\n      removeAfterIndex xs (min i j).\n  Proof using. \n    intros.\n    pose proof Min.min_spec i j. intuition.\n    - find_rewrite. rewrite removeAfterIndex_le with (i := i) (j := j) at 2;\n        eauto using removeAfterIndex_comm; omega.\n    - find_rewrite.\n      rewrite <- removeAfterIndex_le with (i := j) (j := i);\n        auto; omega.\n  Qed.\n\n  Lemma findAtIndex_None :\n    forall xs i x,\n      sorted xs ->\n      findAtIndex xs i = None ->\n      In x xs ->\n      eIndex x <> i.\n  Proof using. \n    induction xs; intros; simpl in *; intuition; break_match; try discriminate.\n    - subst. do_bool. congruence.\n    - do_bool. break_if; eauto.\n      do_bool. find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma findAtIndex_removeAfterIndex_agree :\n    forall xs i j e e',\n      NoDup (map eIndex xs) ->\n      findAtIndex xs i = Some e ->\n      findAtIndex (removeAfterIndex xs j) i = Some e' ->\n      e = e'.\n  Proof using. \n    intros.\n    eapply NoDup_map_elim with (f := eIndex); eauto using findAtIndex_in, removeAfterIndex_in.\n    apply findAtIndex_index in H0.\n    apply findAtIndex_index in H1.\n    congruence.\n  Qed.\n\n  Lemma subseq_uniqueIndices :\n    forall ys xs,\n      subseq xs ys ->\n      uniqueIndices ys ->\n      uniqueIndices xs.\n  Proof using. \n    unfold uniqueIndices.\n    induction ys; intros.\n    - simpl in *. break_match; intuition.\n    - simpl in *. break_match; intuition.\n      + simpl. constructor.\n      + subst. simpl in *. invc H0. constructor; auto.\n        intro. apply H3.\n        eapply subseq_In; eauto.\n        apply subseq_map. auto.\n      + subst. invc H0. eauto.\n  Qed.\n\n  Lemma subseq_findGtIndex :\n    forall xs i,\n      subseq (findGtIndex xs i) xs.\n  Proof using. \n    induction xs; intros.\n    - simpl. auto.\n    - simpl. repeat break_match; auto.\n      + find_inversion. eauto.\n      + congruence.\n  Qed.\n\n  Lemma findGtIndex_in :\n    forall xs i x,\n      In x (findGtIndex xs i) ->\n      In x xs.\n  Proof using. \n    eauto using subseq_In, subseq_findGtIndex.\n  Qed.\n\n  Lemma findGtIndex_sufficient :\n    forall e entries x,\n      sorted entries ->\n      In e entries ->\n      eIndex e > x ->\n      In e (findGtIndex entries x).\n  Proof using. \n    induction entries; intros.\n    - simpl in *. intuition.\n    - simpl in *. break_if; intuition.\n      + subst. in_crush.\n      + subst. do_bool. omega.\n      + do_bool. find_apply_hyp_hyp. omega.\n  Qed.\n\n  Definition contiguous_range_exact_lo xs lo :=\n    (forall i,\n       lo < i <= maxIndex xs ->\n       exists e,\n         eIndex e = i /\\\n         In e xs) /\\\n    (forall e,\n       In e xs ->\n       lo < eIndex e).\n\n  Lemma removeAfterIndex_uniqueIndices :\n    forall l i,\n      uniqueIndices l ->\n      uniqueIndices (removeAfterIndex l i).\n  Proof with eauto using subseq_uniqueIndices, removeAfterIndex_subseq.\n    intros...\n  Qed.\n\n  Lemma maxIndex_subset :\n    forall xs ys,\n      sorted xs -> sorted ys ->\n      (forall x, In x xs -> In x ys) ->\n      maxIndex xs <= maxIndex (orig_base_params:=orig_base_params) ys.\n  Proof using. \n    destruct xs; intros.\n    - simpl. omega.\n    - destruct ys; simpl in *.\n      + match goal with\n          | [ H : forall _, _ = _ \\/ _ -> _, a : entry |- _ ] =>\n            solve [ specialize (H a); intuition ]\n        end.\n    + match goal with\n        | [ H : forall _, _ = _ \\/ _ -> _ |- eIndex ?a <= _ ] =>\n          specialize (H a); intuition\n      end; subst; auto.\n      find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma maxIndex_exists_in :\n    forall xs,\n      maxIndex xs >= 1 ->\n      exists x,\n        eIndex x = maxIndex xs /\\\n        In x xs.\n  Proof using. \n    destruct xs; intros.\n    - simpl in *. omega.\n    - simpl in *. eauto.\n  Qed.\n\n  Lemma maxIndex_app :\n    forall l l',\n      maxIndex (l ++ l') = maxIndex l \\/\n      maxIndex (l ++ l') = maxIndex l' /\\ l = [].\n  Proof using. \n    induction l; intuition.\n  Qed.\n\n  Lemma maxIndex_removeAfterIndex_le :\n    forall l i,\n      sorted l ->\n      maxIndex (removeAfterIndex l i) <= maxIndex l.\n  Proof using. \n    intros.\n    apply maxIndex_subset; eauto using removeAfterIndex_sorted.\n    intros. eauto using removeAfterIndex_in.\n  Qed.\n\n  Lemma maxIndex_removeAfterIndex :\n    forall l i e,\n      sorted l ->\n      In e l ->\n      eIndex e = i ->\n      maxIndex (removeAfterIndex l i) = i.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    - subst. break_if; do_bool; try omega.\n      reflexivity.\n    - break_if; simpl in *.\n      + do_bool.\n        match goal with\n          | H : forall _, In _ _ -> _ |- _ =>\n            specialize (H2 e)\n        end. intuition. omega.\n      + eauto.\n  Qed.\n\n  Lemma maxIndex_gt_0_nonempty :\n    forall es,\n      0 < maxIndex es ->\n      es <> nil.\n  Proof using. \n    intros.\n    destruct es; simpl in *.\n    - omega.\n    - congruence.\n  Qed.\n\n  Lemma removeIncorrect_new_contiguous :\n    forall new current prev e,\n      sorted current ->\n      uniqueIndices current ->\n      (forall e e',\n         eIndex e = eIndex e' ->\n         eTerm e = eTerm e' ->\n         In e new ->\n         In e' current ->\n         e = e') ->\n      contiguous_range_exact_lo current 0 ->\n      contiguous_range_exact_lo new prev ->\n      In e current ->\n      eIndex e = prev ->\n      contiguous_range_exact_lo (new ++ removeAfterIndex current prev)\n                                0.\n  Proof using one_node_params. \n    intros new current prev e Hsorted Huniq Hinv. intros. red. intros.\n    intuition.\n    - destruct (le_lt_dec i prev).\n      + unfold contiguous_range_exact_lo in *. intuition.\n        match goal with\n          | H: forall _, _ < _ <= _ current -> _, H' : In _ current |- _ =>\n            specialize (H i); apply maxIndex_is_max in H'; auto; forward H; intuition\n        end.\n        break_exists. exists x. intuition.\n        apply in_or_app. right. subst.\n        eapply removeAfterIndex_le_In; eauto.\n      + pose proof maxIndex_app new (removeAfterIndex current prev). intuition.\n        * find_rewrite.\n          unfold contiguous_range_exact_lo in *. intuition.\n          match goal with\n            | H: forall _, _ < _ <= _ new -> _ |- _ =>\n              specialize (H i); auto; forward H; intuition\n          end. break_exists. exists x. intuition.\n        * subst. simpl in *. clean.\n          exfalso.\n          pose proof maxIndex_removeAfterIndex current (eIndex e) e.\n          intuition.\n    - unfold contiguous_range_exact_lo in *.\n      do_in_app. intuition.\n      + firstorder.\n      + firstorder using removeAfterIndex_in.\n  Qed.\n\n  Lemma incoming_entries_in_log :\n    forall es log x i,\n      In x es ->\n      uniqueIndices log ->\n      exists y,\n        eIndex x = eIndex y /\\\n        eTerm x = eTerm y /\\\n        In y (es ++ (removeAfterIndex log i)).\n  Proof using. \n    intros.\n    exists x. intuition.\n  Qed.\n\n  Lemma findGtIndex_necessary :\n    forall entries e x,\n      In e (findGtIndex entries x) ->\n      In e entries /\\\n      eIndex e > x.\n  Proof using. \n    induction entries; intros; simpl in *; intuition.\n    - break_if; simpl in *; intuition; right; eapply IHentries; eauto.\n    - break_if;\n      simpl in *; intuition.\n      + do_bool. subst. omega.\n      + simpl in *; intuition; eapply IHentries; eauto.\n  Qed.\n\n  Lemma findGtIndex_contiguous :\n    forall entries x,\n      sorted entries ->\n      (forall i, 0 < i <= maxIndex entries -> (exists e, In e entries /\\ eIndex e = i)) ->\n      forall i, x < i <= maxIndex entries ->\n           exists e, In e (findGtIndex entries x) /\\ eIndex e = i.\n  Proof using. \n    intros entries x Hsorted; intros. specialize (H i).\n    conclude H ltac:(omega).\n    break_exists. exists x0. intuition.\n    apply findGtIndex_sufficient; auto; omega.\n  Qed.\n\n  Lemma findGtIndex_max :\n    forall entries x,\n      maxIndex (findGtIndex entries x) <= maxIndex entries.\n  Proof using. \n    intros. destruct entries; simpl; auto.\n    break_if; simpl; intuition.\n  Qed.\n\n  Lemma findAtIndex_uniq_equal :\n    forall e e' es,\n      findAtIndex es (eIndex e) = Some e' ->\n      In e es ->\n      uniqueIndices es ->\n      e = e'.\n  Proof using. \n    intros.\n    pose proof findAtIndex_in _ _ _ H.\n    pose proof findAtIndex_index _ _ _ H.\n    eapply uniqueIndices_elim_eq; eauto.\n  Qed.\n\n  Definition entries_match' entries entries' :=\n    forall e e' e'',\n      eIndex e = eIndex e' ->\n      eTerm e = eTerm e' ->\n      In e entries ->\n      In e' entries' ->\n      eIndex e'' <= eIndex e ->\n      (In e'' entries -> In e'' entries').\n\n  Lemma entries_match_entries_match' :\n    forall xs ys,\n      entries_match xs ys ->\n      entries_match' xs ys /\\\n      entries_match' ys xs.\n  Proof using. \n    unfold entries_match, entries_match'.\n    intros. intuition.\n    - eapply H; eauto.\n    - eapply (H e' e); eauto with *.\n  Qed.\n\n  Definition contiguous\n             (prevLogIndex : logIndex)\n             (prevLogTerm : term)\n             (leaderLog entries : list entry) : Prop :=\n    (prevLogIndex = 0 \\/\n     exists e, findAtIndex leaderLog prevLogIndex = Some e /\\\n          eTerm e = prevLogTerm) /\\\n    (forall e,\n       In e leaderLog ->\n       eIndex e > prevLogIndex ->\n       eIndex e <= maxIndex entries ->\n       In e entries) /\\\n    forall e e',\n      eIndex e = eIndex e' ->\n      eTerm e = eTerm e' ->\n      In e entries ->\n      In e' leaderLog ->\n      e = e'.\n\n  Lemma entries_match_refl :\n    forall l,\n      entries_match l l.\n  Proof using. \n    unfold entries_match. intuition.\n  Qed.\n\n  Lemma entries_match_sym :\n    forall xs ys,\n      entries_match xs ys ->\n      entries_match ys xs.\n  Proof using. \n    intros.\n    unfold entries_match in *.\n    intros. intuition.\n    - apply H with (e:=e')(e':=e); auto.\n      repeat find_rewrite. auto.\n    - apply H with (e:=e')(e':=e); auto.\n      repeat find_rewrite. auto.\n  Qed.\n\n  Lemma advanceCurrentTerm_same_log :\n    forall st t,\n      log (advanceCurrentTerm st t) = log st.\n  Proof using. \n    unfold advanceCurrentTerm. intros.\n    break_if; auto.\n  Qed.\n\n  Lemma tryToBecomeLeader_same_log :\n    forall n st out st' ms,\n      tryToBecomeLeader n st = (out, st', ms) ->\n      log st' = log st.\n  Proof using. \n    unfold tryToBecomeLeader.\n    intros. find_inversion. auto.\n  Qed.\n\n  Lemma handleRequestVote_same_log :\n    forall n st t c li lt st' ms,\n      handleRequestVote n st t c li lt = (st', ms) ->\n      log st' = log st.\n  Proof using. \n    unfold handleRequestVote.\n    intros.\n    repeat (break_match; try discriminate; repeat (find_inversion; simpl in *));\n      auto using advanceCurrentTerm_same_log.\n  Qed.\n\n  Lemma handleRequestVoteReply_same_log :\n    forall n st src t v,\n      log (handleRequestVoteReply n st src t v) = log st.\n  Proof using. \n    unfold handleRequestVoteReply.\n    intros. repeat break_match; simpl; auto using advanceCurrentTerm_same_log.\n  Qed.\n\n\n  Lemma advanceCurrentTerm_same_lastApplied :\n    forall st t,\n      lastApplied (advanceCurrentTerm st t) = lastApplied st.\n  Proof using. \n    unfold advanceCurrentTerm. intros.\n    break_if; auto.\n  Qed.\n\n  Theorem handleTimeout_lastApplied :\n    forall h st out st' ps,\n      handleTimeout h st = (out, st', ps) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    intros. unfold handleTimeout, tryToBecomeLeader in *.\n    break_match; find_inversion; subst; auto.\n  Qed.\n\n  Theorem handleClientRequest_lastApplied:\n  forall h st client id c out st' ps,\n    handleClientRequest h st client id c = (out, st', ps) ->\n    lastApplied st' = lastApplied st.\n  Proof using. \n    intros. unfold handleClientRequest in *.\n    break_match; find_inversion; subst; auto.\n  Qed.\n\n  Lemma tryToBecomeLeader_same_lastApplied :\n    forall n st out st' ms,\n      tryToBecomeLeader n st = (out, st', ms) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    unfold tryToBecomeLeader.\n    intros. find_inversion. auto.\n  Qed.\n\n  Lemma handleRequestVote_same_lastApplied :\n    forall n st t c li lt st' ms,\n      handleRequestVote n st t c li lt = (st', ms) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    unfold handleRequestVote.\n    intros.\n    repeat (break_match; try discriminate; repeat (find_inversion; simpl in *));\n      auto using advanceCurrentTerm_same_lastApplied.\n  Qed.\n\n  Lemma handleRequestVoteReply_same_lastApplied :\n    forall n st src t v,\n      lastApplied (handleRequestVoteReply n st src t v) = lastApplied st.\n  Proof using. \n    unfold handleRequestVoteReply.\n    intros. repeat break_match; simpl; auto using advanceCurrentTerm_same_lastApplied.\n  Qed.\n\n  Lemma findAtIndex_elim :\n    forall l i e,\n      findAtIndex l i = Some e ->\n      i = eIndex e /\\ In e l.\n  Proof using. \n    eauto using findAtIndex_in, findAtIndex_index.\n  Qed.\n\n  Lemma index_in_bounds :\n    forall e es i,\n      sorted es ->\n      In e es ->\n      i <> 0 ->\n      i <= eIndex e ->\n      1 <= i <= maxIndex es.\n  Proof using. \n    intros. split.\n    - omega.\n    - etransitivity; eauto. apply maxIndex_is_max; auto.\n  Qed.\n\n  Lemma rachet :\n    forall x x' xs ys,\n      eIndex x = eIndex x' ->\n      In x xs ->\n      In x' ys ->\n      In x' xs ->\n      uniqueIndices xs ->\n      In x ys.\n  Proof using. \n    intros.\n    assert (x = x').\n    - eapply uniqueIndices_elim_eq; eauto.\n    - subst. auto.\n  Qed.\n\n  Lemma findAtIndex_intro :\n    forall l i e,\n      sorted l ->\n      In e l ->\n      eIndex e = i ->\n      uniqueIndices l ->\n      findAtIndex l i = Some e.\n  Proof using. \n    induction l; intros.\n    - simpl in *. intuition.\n    - simpl in *. intuition; break_if; subst; do_bool.\n      + auto.\n      + congruence.\n      + f_equal. eauto using uniqueIndices_elim_eq with *.\n      + break_if; eauto.\n        * do_bool. find_apply_hyp_hyp. omega.\n        * eapply IHl; auto. unfold uniqueIndices in *.\n          simpl in *. solve_by_inversion.\n  Qed.\n\n  Theorem sorted_uniqueIndices :\n    forall l,\n      sorted l -> uniqueIndices l.\n  Proof using. \n    intros; induction l; simpl; auto.\n    - unfold uniqueIndices. simpl. constructor.\n    - unfold uniqueIndices in *. simpl in *. intuition. constructor; eauto.\n      intuition. do_in_map. find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma findAtIndex_intro' :\n    forall l i e,\n      sorted l ->\n      In e l ->\n      eIndex e = i ->\n      findAtIndex l i = Some e.\n  Proof using. \n    intros.\n    apply findAtIndex_intro; auto using sorted_uniqueIndices.\n  Qed.\n\n  Lemma doLeader_same_log :\n    forall st n os st' ms,\n      doLeader st n = (os, st', ms) ->\n      log st' = log st.\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma handleAppendEntriesReply_same_log :\n    forall n st src t es b st' l,\n      handleAppendEntriesReply n st src t es b = (st', l) ->\n      log st' = log st.\n  Proof using. \n    intros.\n    unfold handleAppendEntriesReply in *.\n    repeat (break_match; repeat (find_inversion; simpl in *)); auto using advanceCurrentTerm_same_log.\n  Qed.\n\n  Lemma handleAppendEntriesReply_same_lastApplied :\n    forall n st src t es b st' l,\n      handleAppendEntriesReply n st src t es b = (st', l) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    intros.\n    unfold handleAppendEntriesReply in *.\n    repeat (break_match; repeat (find_inversion; simpl in *)); auto using advanceCurrentTerm_same_lastApplied.\n  Qed.\n\n  Lemma handleAppendEntries_same_lastApplied :\n    forall h st t n pli plt es ci st' ps,\n      handleAppendEntries h st t n pli plt es ci = (st', ps) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    intros.\n    unfold handleAppendEntries in *.\n    repeat (break_match; repeat (find_inversion; simpl in *)); auto using advanceCurrentTerm_same_lastApplied.\n  Qed.\n\n  Definition term_of msg :=\n    match msg with\n      | RequestVote t _ _ _ => Some t\n      | RequestVoteReply t _ => Some t\n      | AppendEntries t _ _ _ _ _ => Some t\n      | AppendEntriesReply t _ _ => Some t\n    end.\n\n  Lemma wonElection_length :\n    forall l1 l2,\n      wonElection l1 = true ->\n      length l1 <= length l2 ->\n      wonElection l2 = true.\n  Proof using. \n    intros.\n    unfold wonElection in *. do_bool.\n    omega.\n  Qed.\n\n  Lemma wonElection_no_dup_in :\n    forall l1 l2,\n      wonElection l1 = true ->\n      NoDup l1 ->\n      (forall x, In x l1 -> In x l2) ->\n      wonElection l2 = true.\n  Proof using. \n    intros.\n    find_eapply_lem_hyp subset_length;\n      eauto using name_eq_dec, wonElection_length.\n  Qed.\n\n  Lemma wonElection_exists_voter :\n    forall l,\n      wonElection l = true ->\n      exists x,\n        In x l.\n  Proof using. \n    unfold wonElection.\n    intros.\n    destruct l; try discriminate.\n    simpl. eauto.\n  Qed.\n\n\n  Lemma argmax_fun_ext :\n    forall A (f : A -> nat) g l,\n      (forall a, f a = g a) ->\n      argmax f l = argmax g l.\n  Proof using. \n    intros. induction l; simpl in *; intuition.\n    find_rewrite. break_match; intuition.\n    repeat find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma argmax_None :\n    forall A (f : A -> nat) l,\n      argmax f l = None ->\n      l = [].\n  Proof using. \n    intros. destruct l; simpl in *; intuition.\n    repeat break_match; congruence.\n  Qed.\n\n  Lemma argmax_elim :\n    forall A (f : A -> nat) l a,\n      argmax f l = Some a ->\n      (In a l /\\\n       forall x, In x l -> f a >= f x).\n  Proof using. \n    induction l; intros; simpl in *; [congruence|].\n    repeat break_match; find_inversion.\n    - do_bool.\n      match goal with\n        | H : forall _, Some ?a = Some _ -> _ |- _ =>\n          specialize (H a)\n      end. intuition; subst; auto.\n      find_apply_hyp_hyp. omega.\n    - do_bool.\n      match goal with\n        | H : forall _, Some ?a = Some _ -> _ |- _ =>\n          specialize (H a)\n      end. intuition; subst; auto.\n      find_apply_hyp_hyp. omega.\n    - intuition; subst; auto.\n      find_apply_lem_hyp argmax_None.\n      subst. solve_by_inversion.\n  Qed.\n\n  Lemma argmax_in :\n    forall A (f : A -> nat) l a,\n      argmax f l = Some a ->\n      In a l.\n  Proof using. \n    intros. find_apply_lem_hyp argmax_elim. intuition.\n  Qed.\n\n  Lemma argmax_one_different :\n    forall A (A_eq_dec : forall x y : A, {x = y} + {x <> y}) f g (l : list A) a,\n      (forall x, In x l -> a <> x -> f x = g x) ->\n      (forall x, In x l -> f x <= g x) ->\n      (argmax g l = argmax f l \\/\n       argmax g l = Some a).\n  Proof using. \n    intros. induction l; simpl in *; intuition.\n    conclude IHl intuition.\n    conclude IHl intuition. intuition.\n    - find_rewrite. break_match; intuition.\n      repeat break_if; intuition.\n      + do_bool. right.\n        find_apply_lem_hyp argmax_in; intuition.\n        destruct (A_eq_dec a a1); destruct (A_eq_dec a a0); repeat subst; intuition;\n        specialize (H0 a1); specialize (H a0); intuition; repeat find_rewrite; omega.\n      + do_bool. right.\n        find_apply_lem_hyp argmax_in; intuition.\n        destruct (A_eq_dec a a1); destruct (A_eq_dec a a0); repeat subst; intuition.\n        * specialize (H a1); specialize (H0 a0); intuition. repeat find_rewrite. omega.\n        * specialize (H a1); specialize (H0 a0); intuition. repeat find_rewrite. omega.\n    - find_rewrite. repeat break_match; subst; intuition.\n      do_bool.\n      repeat find_apply_lem_hyp argmax_elim; intuition.\n      destruct (A_eq_dec a a1); destruct (A_eq_dec a a0); repeat subst; intuition.\n      + specialize (H a0); specialize (H0 a1); intuition. repeat find_rewrite. omega.\n      + pose proof H a0; pose proof H a1; intuition. repeat find_rewrite.\n        specialize (H3 a1). intuition. omega.\n  Qed.\n\n  Lemma argmin_fun_ext :\n    forall A (f : A -> nat) g l,\n      (forall a, f a = g a) ->\n      argmin f l = argmin g l.\n  Proof using. \n    intros. induction l; simpl in *; intuition.\n    find_rewrite. break_match; intuition.\n    repeat find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma argmin_None :\n    forall A (f : A -> nat) l,\n      argmin f l = None ->\n      l = [].\n  Proof using. \n    intros. destruct l; simpl in *; intuition.\n    repeat break_match; congruence.\n  Qed.\n\n  Lemma argmin_elim :\n    forall A (f : A -> nat) l a,\n      argmin f l = Some a ->\n      (In a l /\\\n       forall x, In x l -> f a <= f x).\n  Proof using. \n    induction l; intros; simpl in *; [congruence|].\n    repeat break_match; find_inversion.\n    - do_bool.\n      match goal with\n        | H : forall _, Some ?a = Some _ -> _ |- _ =>\n          specialize (H a)\n      end. intuition; subst; auto.\n      find_apply_hyp_hyp. omega.\n    - do_bool.\n      match goal with\n        | H : forall _, Some ?a = Some _ -> _ |- _ =>\n          specialize (H a)\n      end. intuition; subst; auto.\n      find_apply_hyp_hyp. omega.\n    - intuition; subst; auto.\n      find_apply_lem_hyp argmin_None.\n      subst. solve_by_inversion.\n  Qed.\n\n  Lemma argmin_in :\n    forall A (f : A -> nat) l a,\n      argmin f l = Some a ->\n      In a l.\n  Proof using. \n    intros. find_apply_lem_hyp argmin_elim. intuition.\n  Qed.\n\n  Lemma argmin_one_different :\n    forall A (A_eq_dec : forall x y : A, {x = y} + {x <> y}) f g (l : list A) a,\n      (forall x, In x l -> a <> x -> f x = g x) ->\n      (forall x, In x l -> g x <= f x) ->\n      (argmin g l = argmin f l \\/\n       argmin g l = Some a).\n  Proof using. \n    intros. induction l; simpl in *; intuition.\n    conclude IHl intuition.\n    conclude IHl intuition. intuition.\n    - find_rewrite. break_match; intuition.\n      repeat break_if; intuition.\n      + do_bool. right.\n        find_apply_lem_hyp argmin_in; intuition.\n        destruct (A_eq_dec a a1); destruct (A_eq_dec a a0); repeat subst; intuition;\n        specialize (H0 a1); specialize (H a0); intuition; repeat find_rewrite; omega.\n      + do_bool. right.\n        find_apply_lem_hyp argmin_in; intuition.\n        destruct (A_eq_dec a a1); destruct (A_eq_dec a a0); repeat subst; intuition.\n        * specialize (H a1); specialize (H0 a0); intuition. repeat find_rewrite. omega.\n        * specialize (H a1); specialize (H0 a0); intuition. repeat find_rewrite. omega.\n    - find_rewrite. repeat break_match; subst; intuition.\n      do_bool.\n      repeat find_apply_lem_hyp argmin_elim; intuition.\n      destruct (A_eq_dec a a1); destruct (A_eq_dec a a0); repeat subst; intuition.\n      + specialize (H a0); specialize (H0 a1); intuition. repeat find_rewrite. omega.\n      + pose proof H a0; pose proof H a1; intuition. repeat find_rewrite.\n        specialize (H3 a1). intuition. omega.\n  Qed.\n\n  Ltac update_destruct :=\n    match goal with\n    | [ |- context [ update _ ?y _ ?x ] ] => destruct (name_eq_dec y x)\n    end.\n\n  Ltac update_destruct_hyp :=\n    match goal with\n    | [ _ : context [ update _ ?y _ ?x ] |- _ ] => destruct (name_eq_dec y x)\n    end.\n\n\n  Lemma applied_entries_update :\n    forall sigma h st,\n      lastApplied st >= lastApplied (sigma h) ->\n      (applied_entries (update sigma h st) = applied_entries sigma /\\\n       (exists h',\n          argmax (fun h => lastApplied (sigma h)) (all_fin N) = Some h' /\\\n          lastApplied (sigma h') >= lastApplied st))\n      \\/\n      (argmax (fun h' => lastApplied (update sigma h st h')) (all_fin N) = Some h /\\\n       applied_entries (update sigma h st) = (rev (removeAfterIndex (log st) (lastApplied st)))).\n  Proof using. \n    intros.\n    unfold applied_entries in *.\n    repeat break_match; intuition;\n    try solve [find_apply_lem_hyp argmax_None;\n                exfalso;\n                pose proof (all_fin_all _ h); find_rewrite; intuition].\n    match goal with\n      | _ : argmax ?f ?l = _, _ : argmax ?g ?l = _ |- _ =>\n        pose proof argmax_one_different name name_eq_dec g f l h as Hproof\n    end.\n    forward Hproof; [intros; rewrite_update; intuition|]; concludes.\n    forward Hproof; [intros; update_destruct; subst; rewrite_update; intuition|]; concludes.\n    intuition.\n    - repeat find_rewrite. find_inversion.\n      update_destruct; subst; rewrite_update; intuition. left.\n      intuition. eexists; intuition eauto. repeat find_apply_lem_hyp argmax_elim; intuition eauto.\n      match goal with\n          H : _ |- _ =>\n          solve [specialize (H h); rewrite_update; eauto using all_fin_all]\n      end.\n    - repeat find_rewrite. find_inversion. rewrite_update. intuition.\n  Qed.\n\n  Lemma applied_entries_safe_update :\n    forall sigma h st,\n      lastApplied st = lastApplied (sigma h) ->\n      removeAfterIndex (log st) (lastApplied (sigma h))\n      = removeAfterIndex (log (sigma h)) (lastApplied (sigma h)) ->\n      applied_entries (update sigma h st) = applied_entries sigma.\n  Proof using. \n    intros. unfold applied_entries in *.\n    repeat break_match; repeat find_rewrite; intuition;\n    match goal with\n      | _ : argmax ?f ?l = _, _ : argmax ?g ?l = _ |- _ =>\n        assert (argmax f l = argmax g l) by\n            (apply argmax_fun_ext; intros; update_destruct; subst; rewrite_update; auto)\n    end; repeat find_rewrite; try congruence.\n    match goal with | H : Some _ = Some _ |- _ => inversion H end.\n    subst. clean.\n    f_equal. update_destruct; subst; rewrite_update; repeat find_rewrite; auto.\n  Qed.\n\n\n  Lemma applied_entries_log_lastApplied_same :\n    forall sigma sigma',\n      (forall h, log (sigma' h) = log (sigma h)) ->\n      (forall h, lastApplied (sigma' h) = lastApplied (sigma h)) ->\n      applied_entries sigma' = applied_entries sigma.\n  Proof using. \n    intros.\n    unfold applied_entries in *.\n    rewrite argmax_fun_ext with (g := fun h : name => lastApplied (sigma h)); intuition.\n    break_match; auto.\n    repeat find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma applied_entries_log_lastApplied_update_same :\n    forall sigma h st,\n      log st = log (sigma h) ->\n      lastApplied st = lastApplied (sigma h) ->\n      applied_entries (update sigma h st) = applied_entries sigma.\n  Proof using. \n    intros.\n    apply applied_entries_log_lastApplied_same;\n      intros; update_destruct; subst; rewrite_update; auto.\n  Qed.\n\n  Lemma applied_entries_cases :\n    forall sigma,\n      applied_entries sigma = [] \\/\n      exists h,\n        applied_entries sigma = rev (removeAfterIndex (log (sigma h)) (lastApplied (sigma h))).\n  Proof using. \n    intros.\n    unfold applied_entries in *.\n    break_match; simpl in *; intuition eauto.\n  Qed.\n\n  Lemma removeAfterIndex_partition :\n    forall l x,\n      exists l',\n        l = l' ++ removeAfterIndex l x.\n  Proof using. \n    intros; induction l; simpl in *; intuition eauto using app_nil_r.\n    break_exists. break_if; [exists nil; eauto|].\n    do_bool.\n    match goal with\n      | l : list entry, e : entry |- _ =>\n        solve [exists (e :: l); simpl in *; f_equal; auto]\n    end.\n  Qed.\n\n  Lemma entries_match_scratch :\n    forall es ys plt,\n      sorted es ->\n      uniqueIndices ys ->\n      (forall e1 e2,\n         eIndex e1 = eIndex e2 ->\n         eTerm e1 = eTerm e2 ->\n         In e1 es ->\n         In e2 ys ->\n         (forall e3,\n            eIndex e3 <= eIndex e1 ->\n            In e3 es ->\n            In e3 ys) /\\\n         (0 <> 0 ->\n          exists e4,\n            eIndex e4 = 0 /\\\n            eTerm e4 = plt /\\\n            In e4 ys)) ->\n      (forall i, 0 < i <= maxIndex es -> exists e, eIndex e = i /\\ In e es) ->\n      (forall e,\n         In e es ->\n         0 < eIndex e) ->\n      (forall y, In y ys -> 0 < eIndex y) ->\n      entries_match es ys.\n  Proof using. \n    intros.\n    unfold entries_match. intuition.\n    - match goal with\n        | [ H : _ |- _ ] => solve [eapply H; eauto]\n      end.\n    - match goal with\n        | [ H : forall _ _, _, H' : eIndex ?e1 = eIndex ?e2 |- _ ] =>\n          specialize (H e1 e2); do 4 concludes\n      end. intuition.\n        match goal with\n          | [ H : forall _, _ < _ <= _ -> _,\n              _ : eIndex ?e3 <= eIndex _\n                |- _ ] =>\n            specialize (H (eIndex e3));\n              conclude H\n                       ltac:(split; [eauto|\n                                     eapply le_trans; eauto; apply maxIndex_is_max; eauto])\n\n        end.\n        break_exists. intuition.\n        match goal with\n          | [ _ : In ?x _,\n              _ : eIndex ?x = eIndex ?e3,\n              _ : eIndex ?e3 <= eIndex _ |- _ ] =>\n            eapply rachet with (x' := x); eauto using sorted_uniqueIndices\n        end.\n        match goal with\n          | [ H : _ |- _ ] => solve [ eapply H; eauto; congruence ]\n        end.\n  Qed.\n\n  Ltac use_entries_match :=\n    match goal with\n      | [ _ : eIndex ?e1 = eIndex ?e2,\n              H : context [entries_match]\n                              |- _ ] =>\n        first [ solve [eapply H with (e:=e2)(e':=e1); eauto; congruence] |\n                solve [eapply H with (e:=e1)(e':=e2); eauto; congruence]]\n    end.\n\n  Lemma entries_match_append :\n    forall xs ys es ple pli plt,\n      sorted xs ->\n      sorted ys ->\n      sorted es ->\n      entries_match xs ys ->\n      (forall e1 e2,\n         eIndex e1 = eIndex e2 ->\n         eTerm e1 = eTerm e2 ->\n         In e1 es ->\n         In e2 ys ->\n         (forall e3,\n            eIndex e3 <= eIndex e1 ->\n            In e3 es ->\n            In e3 ys) /\\\n         (pli <> 0 ->\n          exists e4,\n            eIndex e4 = pli /\\\n            eTerm e4 = plt /\\\n            In e4 ys)) ->\n      (forall i, pli < i <= maxIndex es -> exists e, eIndex e = i /\\ In e es) ->\n      (forall e,\n         In e es ->\n         pli < eIndex e) ->\n      findAtIndex xs pli = Some ple ->\n      eTerm ple = plt ->\n      pli <> 0 ->\n      entries_match (es ++ removeAfterIndex xs pli) ys.\n  Proof using. \n    intros.\n    unfold entries_match. intros. split; intros.\n    - in_crush_start.\n      + match goal with\n          | [ H : _ |- _ ] => solve [eapply H; eauto]\n        end.\n      + exfalso.\n        find_apply_lem_hyp removeAfterIndex_In_le; intuition.\n        find_apply_hyp_hyp. omega.\n      + find_apply_lem_hyp findAtIndex_elim.\n        intuition subst.\n        match goal with\n          | [ H : forall _ _, _, H' : eIndex ?e1 = eIndex ?e2 |- _ ] =>\n            specialize (H e1 e2); do 4 concludes\n        end.\n        intuition. break_exists.\n        intuition.\n        find_copy_apply_lem_hyp removeAfterIndex_In_le; intuition.\n        find_apply_lem_hyp removeAfterIndex_in.\n        use_entries_match.\n      + repeat find_apply_lem_hyp removeAfterIndex_in. use_entries_match.\n    - in_crush_start.\n      + match goal with\n          | [ H : forall _ _, _, H' : eIndex ?e1 = eIndex ?e2 |- _ ] =>\n            specialize (H e1 e2); do 4 concludes\n        end.\n        intuition. break_exists. intuition.\n        destruct (le_lt_dec (eIndex e'') pli).\n        * apply in_or_app. right.\n          apply removeAfterIndex_le_In; auto.\n          find_apply_lem_hyp findAtIndex_elim. intuition.\n          subst. use_entries_match.\n        * apply in_or_app. left.\n          match goal with\n            | H : forall _, _ < _ <= _ -> _ |- In ?e _ =>\n              specialize (H (eIndex e))\n          end.\n          intuition.\n          conclude_using ltac:(eapply le_trans; eauto; apply maxIndex_is_max; eauto).\n          break_exists. intuition.\n          match goal with\n            | _: eIndex ?e1 = eIndex ?e2 |- context [ ?e2 ] =>\n              eapply rachet with (x' := e1); eauto using sorted_uniqueIndices with *\n          end.\n      + apply in_or_app. right.\n        find_copy_apply_lem_hyp removeAfterIndex_In_le; eauto.\n        apply removeAfterIndex_le_In; [omega|].\n        find_apply_lem_hyp removeAfterIndex_in.\n        use_entries_match.\n  Qed.\n\n  Lemma doLeader_appliedEntries :\n  forall sigma h os st' ms,\n    doLeader (sigma h) h = (os, st', ms) ->\n    applied_entries (update sigma h st') = applied_entries sigma.\n  Proof using. \n    intros.\n    apply applied_entries_log_lastApplied_same.\n    - intros. update_destruct; subst; rewrite_update; auto.\n      eapply doLeader_same_log; eauto.\n    - intros. update_destruct; subst; rewrite_update; auto.\n      unfold doLeader in *. repeat break_match; find_inversion; auto.\n  Qed.\n\n  Lemma applyEntries_spec :\n    forall es h st os st',\n      applyEntries h st es = (os, st') ->\n      exists d cc,\n        st' = {[ {[ st with stateMachine := d ]} with clientCache := cc ]}.\n  Proof using. \n    induction es; intros; simpl in *; intuition.\n    - find_inversion. destruct st'; repeat eexists; eauto.\n    - unfold cacheApplyEntry, applyEntry in *.\n      repeat break_match; repeat find_inversion;\n      find_apply_hyp_hyp; break_exists; repeat eexists; eauto.\n  Qed.\n\n  Lemma applyEntries_spec_ind :\n    forall {es h st os st'},\n      applyEntries h st es = (os, st') ->\n      forall P : raft_data -> Prop,\n        (forall d cc,\n           P {[ {[ st with stateMachine := d ]} with clientCache := cc ]}) ->\n        P st'.\n  Proof using. \n    intros.\n    find_apply_lem_hyp applyEntries_spec.\n    break_exists. subst. eauto.\n  Qed.\n\n  Lemma handleClientRequest_commitIndex :\n    forall h st client id c out st' l,\n      handleClientRequest h st client id c = (out, st', l) ->\n      commitIndex st' = commitIndex st.\n  Proof using. \n    unfold handleClientRequest.\n    intros.\n    repeat break_match; find_inversion; auto.\n  Qed.\n\n  Lemma handleTimeout_commitIndex :\n    forall h st out st' l,\n      handleTimeout h st = (out, st', l) ->\n      commitIndex st' = commitIndex st.\n  Proof using. \n    unfold handleTimeout, tryToBecomeLeader; intros; repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma handleAppendEntriesReply_same_commitIndex :\n    forall n st src t es b st' l,\n      handleAppendEntriesReply n st src t es b = (st', l) ->\n      commitIndex st' = commitIndex st.\n  Proof using. \n    unfold handleAppendEntriesReply, advanceCurrentTerm.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma handleRequestVote_same_commitIndex :\n    forall n st t c li lt st' ms,\n      handleRequestVote n st t c li lt = (st', ms) ->\n      commitIndex st' = commitIndex st.\n  Proof using. \n    unfold handleRequestVote, advanceCurrentTerm.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma handleRequestVoteReply_same_commitIndex :\n    forall n st src t v,\n      commitIndex (handleRequestVoteReply n st src t v) = commitIndex st.\n  Proof using. \n    unfold handleRequestVoteReply, advanceCurrentTerm.\n    intros. repeat break_match; simpl; auto.\n  Qed.\n\n  Lemma doGenericServer_commitIndex :\n    forall h st out st' ms,\n      doGenericServer h st = (out, st', ms) ->\n      commitIndex st' = commitIndex st.\n  Proof using. \n    unfold doGenericServer.\n    intros.\n    repeat break_match; repeat find_inversion; simpl;\n    eapply applyEntries_spec_ind; eauto.\n  Qed.\n\n  Functional Scheme div2_ind := Induction for div2 Sort Prop.\n\n  Theorem div2_correct' :\n    forall n,\n      n <= div2 n + S (div2 n).\n  Proof using. \n    intro n. functional induction (div2 n); omega.\n  Qed.\n\n  Theorem div2_correct :\n    forall c a b,\n      a > div2 c ->\n      b > div2 c ->\n      a + b > c.\n  Proof using. \n    intros n. functional induction (div2 n); intros; try omega.\n    specialize (IHn0 (pred a) (pred b)). omega.\n  Qed.\n\n  Lemma wonElection_one_in_common :\n    forall l l',\n      wonElection (dedup name_eq_dec l) = true ->\n      wonElection (dedup name_eq_dec l') = true ->\n      exists h, In h l /\\ In h l'.\n  Proof using. \n    intros. unfold wonElection in *. do_bool.\n    cut (exists h, In h (dedup name_eq_dec l) /\\ In h (dedup name_eq_dec l'));\n      [intros; break_exists; exists x; intuition eauto using in_dedup_was_in|].\n    eapply pigeon with (l := nodes); eauto using all_fin_all, all_fin_NoDup, NoDup_dedup, name_eq_dec, div2_correct.\n  Qed.\n\n  Lemma execute_log'_app :\n    forall xs ys st tr,\n      execute_log' (xs ++ ys) st tr =\n      let (tr', st') := execute_log' xs st tr in\n      execute_log' ys st' tr'.\n  Proof using. \n    induction xs; intros.\n    - auto.\n    - simpl in *. repeat break_let.\n      rewrite IHxs. break_let. find_inversion. auto.\n  Qed.\n\n  Lemma fst_execute_log' :\n    forall log st tr,\n      fst (execute_log' log st tr) = tr ++ fst (execute_log' log st []).\n  Proof using. \n    induction log; intros.\n    - simpl. rewrite app_nil_r. auto.\n    - simpl. break_let. rewrite IHlog. rewrite app_ass. simpl.\n      rewrite IHlog with (tr := [(eInput a, o)]).\n      auto.\n  Qed.\n\n  Lemma snd_execute_log' :\n    forall log st tr,\n      snd (execute_log' log st tr) = snd (execute_log' log st []).\n  Proof using. \n    induction log; intros.\n    - auto.\n    - simpl. break_let. rewrite IHlog.\n      rewrite IHlog with (tr := [(eInput a, o)]).\n      auto.\n  Qed.\n\n  Lemma execute_log_correct' :\n    forall log st,\n      step_1_star st (snd (execute_log' log st []))\n                  (fst (execute_log' log st [])).\n  Proof using. \n    induction log; intros.\n    - simpl. constructor.\n    - simpl. break_let.\n      rewrite fst_execute_log'.\n      rewrite snd_execute_log'.\n      unfold step_1_star in *.\n      econstructor.\n      + constructor. eauto.\n      + auto.\n  Qed.\n\n  Lemma execute_log_correct :\n    forall log,\n      step_1_star init (snd (execute_log log))\n                  (fst (execute_log log)).\n  Proof using. \n    intros. apply execute_log_correct'.\n  Qed.\n\n  Lemma contiguous_nil :\n    forall i,\n      contiguous_range_exact_lo [] i.\n  Proof using. \n    unfold contiguous_range_exact_lo. intuition.\n    - simpl in *. omega.\n    - contradiction.\n  Qed.\n\n  Lemma contiguous_index_singleton :\n    forall i a,\n      contiguous_range_exact_lo [a] i ->\n      eIndex a = S i.\n  Proof using. \n    intros. unfold contiguous_range_exact_lo in *. intuition.\n    find_insterU. concludes. find_insterU. concludes. break_exists.\n    simpl in *. intuition. subst. auto.\n  Qed.\n\n  Lemma contiguous_index_adjacent :\n    forall l i a b,\n      sorted (a :: b :: l) ->\n      contiguous_range_exact_lo (a :: b :: l) i ->\n      eIndex a = S (eIndex b) /\\ eIndex a > i.\n  Proof using. \n    intros. unfold contiguous_range_exact_lo in *. intuition.\n    assert (i < S (eIndex b) <= eIndex a).\n      simpl in *. intuition. specialize (H0 b). concludes. intuition.\n    specialize (H1 (S (eIndex b))). concludes.\n    break_exists. simpl In in *. intuition; subst.\n    - auto.\n    - omega.\n    - simpl in *. intuition. specialize (H x). concludes. omega.\n  Qed.\n\n  Lemma cons_contiguous_sorted :\n    forall l i a,\n      sorted (a :: l) ->\n      contiguous_range_exact_lo (a :: l) i ->\n      contiguous_range_exact_lo l i.\n  Proof using. \n    induction l; intros.\n    - apply contiguous_nil.\n    - eapply contiguous_index_adjacent in H; eauto.\n      unfold contiguous_range_exact_lo in *. break_and.\n      intuition. simpl maxIndex in *. specialize (H0 i0).\n      assert (i < i0 <= eIndex a0) by omega.\n      concludes. break_exists. intuition. simpl in *. intuition; subst.\n      + omega.\n      + exists x. intuition.\n      + exists x. intuition.\n  Qed.\n\n  Lemma contiguous_app :\n    forall l1 l2 i,\n      sorted (l1 ++ l2) ->\n      contiguous_range_exact_lo (l1 ++ l2) i ->\n      contiguous_range_exact_lo l2 i.\n  Proof using. \n    induction l1; intros.\n    - auto.\n    - simpl ((a :: l1) ++ l2) in *.\n      find_apply_lem_hyp cons_contiguous_sorted; auto.\n      simpl in *. intuition.\n  Qed.\n\n  Lemma prefix_sorted :\n    forall l l',\n      sorted l ->\n      Prefix l' l ->\n      sorted l'.\n  Proof using. \n    induction l; intros.\n    - find_apply_lem_hyp Prefix_nil. subst. auto.\n    - destruct l'.\n      + auto.\n      + simpl. split.\n        * intros. simpl in *. break_and. find_eapply_lem_hyp Prefix_in; eauto.\n          find_insterU. econcludes. subst. intuition.\n        * apply IHl; simpl in *; intuition.\n  Qed.\n\n  Lemma prefix_contiguous :\n    forall l l' e i,\n      l' <> [] ->\n      Prefix l' l ->\n      sorted l ->\n      In e l ->\n      eIndex e > i ->\n      contiguous_range_exact_lo l' i ->\n      In e l'.\n  Proof using. \n    induction l; intros.\n    - contradiction.\n    - destruct l'; try congruence.\n      find_copy_apply_lem_hyp prefix_sorted; auto. simpl in *. intuition.\n      + left. subst. reflexivity.\n      + right. subst. destruct l'.\n        * find_apply_lem_hyp contiguous_index_singleton.\n          specialize (H0 e). concludes. omega.\n        * eapply IHl; try discriminate; eauto. eapply cons_contiguous_sorted; eauto.\n          simpl in *. intuition.\n  Qed.\n  \n  Lemma removeAfterIndex_contiguous :\n    forall l i i',\n      sorted l ->\n      contiguous_range_exact_lo l i ->\n      contiguous_range_exact_lo (removeAfterIndex l i') i.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    break_if; auto.\n    do_bool.\n    eapply IHl; eauto.\n    eapply cons_contiguous_sorted; eauto.\n    simpl; intuition.\n  Qed.\n\n\n\n  Lemma sorted_NoDup :\n    forall l,\n      sorted l -> NoDup l.\n  Proof using. \n    induction l; intros; simpl in *; auto.\n    - constructor.\n    - constructor; intuition.\n      match goal with\n        | H : forall _, _ |- _ => specialize (H a)\n      end. intuition.\n  Qed.\n\n  Lemma sorted_Permutation_eq :\n    forall l l',\n      sorted l ->\n      sorted l' ->\n      Permutation l l' ->\n      l = l'.\n  Proof using. \n    induction l; intros.\n    - symmetry. apply Permutation_nil. assumption.\n    - destruct l'.\n      + apply Permutation_nil. apply Permutation_sym. assumption.\n      + simpl in *. intuition.\n        find_copy_eapply_lem_hyp Permutation_in; intuition.\n        find_copy_apply_lem_hyp Permutation_sym.\n        find_copy_eapply_lem_hyp Permutation_in; intuition.\n        simpl in *. intuition;\n          try (subst a; f_equal; eauto using Permutation_cons_inv).\n        repeat find_apply_hyp_hyp. intuition.\n        omega.\n  Qed.\n\n  Lemma removeAfterIndex_same_sufficient :\n    forall x l l',\n      sorted l ->\n      sorted l' ->\n      (forall e, eIndex e <= x ->\n            In e l ->\n            In e l') ->\n      (forall e, eIndex e <= x ->\n            In e l' ->\n            In e l) ->\n      removeAfterIndex l' x = removeAfterIndex l x.\n  Proof using. \n    intros. apply sorted_Permutation_eq;\n      try (apply removeAfterIndex_sorted; assumption).\n    apply NoDup_Permutation;\n      try (apply NoDup_removeAfterIndex; apply sorted_NoDup; assumption).\n    split; intros; apply removeAfterIndex_le_In;\n        eauto using removeAfterIndex_In_le, removeAfterIndex_in.\n  Qed.\n\n  Lemma removeAfterIndex_same_sufficient' :\n    forall x l l',\n      sorted l ->\n      sorted l' ->\n      contiguous_range_exact_lo l 0 ->\n      (forall e, In e l' -> 0 < eIndex e) ->\n      x <= maxIndex l ->\n      (forall e, eIndex e <= x ->\n            In e l ->\n            In e l') ->\n      removeAfterIndex l' x = removeAfterIndex l x.\n  Proof using. \n    intros.\n    eapply removeAfterIndex_same_sufficient; eauto.\n    intros.\n    unfold contiguous_range_exact_lo in *. intuition.\n    specialize (H7 (eIndex e)).\n    intuition. find_copy_apply_hyp_hyp.\n    repeat conclude_using omega.\n    break_exists. intuition.\n    symmetry in H9. copy_apply H4 H10; try omega.\n    eapply rachet with (xs := l'); eauto using sorted_uniqueIndices.\n  Qed.\n\n  Lemma thing2 :\n    forall l l' i,\n      l <> [] ->\n      Prefix l l' ->\n      sorted l' ->\n      contiguous_range_exact_lo l i ->\n      contiguous_range_exact_lo l' 0 ->\n      l ++ (removeAfterIndex l' i) = l'.\n  Proof using one_node_params. \n    induction l; try congruence; intros.\n    destruct l'; simpl.\n    - contradiction.\n    - simpl Prefix in *. intuition. subst a. f_equal. break_if.\n      + do_bool. unfold contiguous_range_exact_lo in *.\n        intuition. find_insterU. simpl in *. conclude_using eauto.\n        omega.\n      + destruct l.\n        { do_bool. simpl in *. find_apply_lem_hyp contiguous_index_singleton. destruct l'.\n          - reflexivity.\n          - simpl. intuition. find_insterU. concludes. intuition. find_rewrite. break_if.\n            + reflexivity.\n            + do_bool. omega. }\n        { apply IHl; try discriminate; auto.\n          - find_apply_lem_hyp cons_contiguous_sorted.\n            + firstorder.\n            + eauto using Prefix_cons, prefix_sorted.\n          - find_apply_lem_hyp cons_contiguous_sorted.\n            + firstorder.\n            + eauto using Prefix_cons, prefix_sorted.\n          - apply cons_contiguous_sorted in H3; auto. }\n  Qed.\n\n  Lemma thing :\n    forall es l l' e e',\n      sorted l ->\n      sorted l' ->\n      contiguous_range_exact_lo l' 0 ->\n      entries_match l l' ->\n      es <> [] ->\n      Prefix es l' ->\n      contiguous_range_exact_lo es (eIndex e) ->\n      In e l ->\n      In e' l' ->\n      eIndex e = eIndex e' ->\n      eTerm e = eTerm e' ->\n      es ++ (removeAfterIndex l (eIndex e)) = l'.\n  Proof using one_node_params. \n    intros.\n    rewrite removeAfterIndex_same_sufficient with (l := l'); auto.\n    - apply thing2; auto.\n    - unfold entries_match in *. intros. eapply H2; eauto.\n    - unfold entries_match in *. intros. eapply H2; eauto.\n  Qed.\n\n  Lemma sorted_findGtIndex_0 :\n    forall l,\n      (forall e, In e l -> eIndex e > 0) ->\n      sorted l ->\n      findGtIndex l 0 = l.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    break_if; intuition.\n    - f_equal. auto.\n    - do_bool. specialize (H a); intuition; omega.\n  Qed.\n  \n  Lemma Prefix_refl :\n    forall A (l : list A),\n      Prefix l l.\n  Proof using. \n    intros. induction l; simpl in *; auto.\n  Qed.\n\n  \n  Lemma findGtIndex_app_in_1 :\n    forall l1 l2 e,\n      sorted (l1 ++ l2) ->\n      In e l1 ->\n      exists l',\n        findGtIndex (l1 ++ l2) (eIndex e) = l' /\\\n        forall x,\n          In x l' -> In x l1.\n  Proof using. \n    induction l1; intros; simpl in *; intuition.\n    - subst. break_if; do_bool; try omega.\n      eexists; repeat (simpl in *; intuition).\n    - specialize (H1 e); intuition. conclude H1 ltac:(apply in_app_iff; intuition).\n      break_if; do_bool; try omega. eexists; intuition; eauto.\n      simpl in *. intuition.\n      eapply_prop_hyp sorted sorted; eauto. break_exists; intuition.\n      find_rewrite. eauto.\n  Qed.\n  \n  Lemma sorted_app_in_1 :\n    forall l1 l2 e,\n      sorted (l1 ++ l2) ->\n      eIndex e > 0 ->\n      In e l1 ->\n      eIndex e > maxIndex l2.\n  Proof using. \n    induction l1; intros; simpl in *; intuition.\n    subst. destruct l2; simpl in *; auto.\n    specialize (H2 e0); concludes; intuition.\n  Qed.\n\n  Lemma findGtIndex_Prefix :\n    forall l i,\n      Prefix (findGtIndex l i) l.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    break_if; simpl in *; intuition.\n  Qed.\n  \n  Lemma findGtIndex_app_in_2 :\n    forall l1 l2 e,\n      sorted (l1 ++ l2) ->\n      In e l2 ->\n      exists l',\n        findGtIndex (l1 ++ l2) (eIndex e) = l1 ++ l' /\\\n        Prefix l' l2.\n  Proof using. \n    induction l1; intros; simpl in *; intuition.\n    - eexists; intuition eauto using findGtIndex_Prefix.\n    - break_if; simpl in *; intuition.\n      + eapply_prop_hyp sorted sorted; eauto.\n        break_exists; intuition; find_rewrite; eauto.\n      + do_bool. specialize (H1 e); conclude H1 ltac:(apply in_app_iff; intuition).\n        omega.\n  Qed.\n\n  Lemma findGtIndex_nil :\n    forall l i,\n      (forall e', In e' l -> eIndex e' <= i) ->\n      findGtIndex l i = [].\n  Proof using. \n    intros; induction l; simpl in *; intuition.\n    break_if; do_bool; intuition.\n    specialize (H a); intuition. omega.\n  Qed.\n\n  Lemma findGtIndex_removeAfterIndex_commute :\n    forall l i i',\n      sorted l ->\n      removeAfterIndex (findGtIndex l i) i' =\n      findGtIndex (removeAfterIndex l i') i.\n  Proof using. \n    intros. induction l; simpl in *; auto.\n    repeat (break_if; simpl; intuition); do_bool;\n    try congruence.\n    symmetry. apply findGtIndex_nil.\n    intros. find_apply_lem_hyp removeAfterIndex_in.\n    find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma findGtIndex_app_1 :\n    forall l l' i,\n      maxIndex l' <= i ->\n      findGtIndex (l ++ l') i = findGtIndex l i.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    - destruct l'; simpl in *; intuition.\n      break_if; do_bool; auto; omega.\n    - break_if; do_bool; auto.\n      f_equal. eauto.\n  Qed.\n\n  Lemma findGtIndex_app_2 :\n    forall l l' i,\n      sorted (l ++ l') ->\n      i < maxIndex l' ->\n      findGtIndex (l ++ l') i = l ++ findGtIndex l' i.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    break_if; do_bool; auto.\n    - f_equal. eauto.\n    - exfalso.\n      destruct l'; simpl in *; intuition.\n      specialize (H1 e); conclude_using intuition; intuition.\n  Qed.\n\n  Lemma thing3 :\n    forall l l' e,\n      sorted (l ++ l') ->\n      (forall e', In e' (l ++ l') -> eIndex e' > 0) ->\n      In e (l ++ l') ->\n      eIndex e <= maxIndex l' ->\n      In e l'.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    subst. destruct l'; simpl in *; intuition.\n    - exfalso. specialize (H0 e). intuition.\n    - exfalso. specialize (H3 e0). conclude_using intuition.\n      intuition.\n  Qed.\n  \n  Lemma findGtIndex_non_empty :\n    forall l i,\n      i < maxIndex l ->\n      findGtIndex l i <> [].\n  Proof using. \n    intros. induction l; simpl in *; intuition.\n    break_if; do_bool; simpl in *; intuition.\n    congruence.\n  Qed.\n  \n  Lemma sorted_Prefix_in_eq :\n    forall l' l,\n      sorted l ->\n      Prefix l' l ->\n      (forall e, In e l -> In e l') ->\n      l' = l.\n  Proof using. \n    induction l'; intros; simpl in *; intuition.\n    - destruct l; simpl in *; auto.\n      specialize (H1 e); intuition.\n    - break_match; intuition. subst.\n      simpl in *. intuition. f_equal.\n      eapply IHl'; eauto.\n      intros.\n      specialize (H1 e0); intuition.\n      subst. specialize (H0 e0); intuition. omega.\n  Qed.\n\n  Lemma removeAfterIndex_eq :\n    forall l i,\n      (forall e, In e l -> eIndex e <= i) ->\n      removeAfterIndex l i = l.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    break_if; intuition.\n    do_bool. specialize (H a). intuition. omega.\n  Qed.\n\n  Lemma removeAfterIndex_in_app :\n    forall l l' e,\n      In e l ->\n      removeAfterIndex (l ++ l') (eIndex e) =\n      (removeAfterIndex l (eIndex e)) ++ l'.\n  Proof using. \n    induction l; intros; simpl in *; intuition;\n    subst; break_if; do_bool; eauto using app_ass.\n    omega.\n  Qed.\n\n  Lemma removeAfterIndex_in_app_l' :\n    forall l l' e,\n      (forall e', In e' l -> eIndex e' > eIndex e) ->\n      In e l' ->\n      removeAfterIndex (l ++ l') (eIndex e) =\n      removeAfterIndex l' (eIndex e).\n  Proof using. \n    induction l; intros; simpl in *; intuition;\n    subst; break_if; do_bool; eauto using app_ass.\n    specialize (H a). intuition. omega.\n  Qed.\n\n  Lemma removeAfterIndex_maxIndex_sorted :\n    forall l,\n      sorted l ->\n      l = removeAfterIndex l (maxIndex l).\n  Proof using. \n    intros; induction l; simpl in *; intuition.\n    break_if; auto. do_bool. omega.\n  Qed.\n\n  Lemma contiguous_singleton_sufficient :\n    forall x n,\n      S n = eIndex x ->\n      contiguous_range_exact_lo [x] n.\n  Proof using. \n    red. intuition.\n    - exists x. intuition. simpl in *. inv H2; [reflexivity | omega].\n    - simpl in *. intuition. subst. omega.\n  Qed.\n\n  Lemma contiguous_adjacent_sufficient :\n    forall x y l i,\n      eIndex x = S (eIndex y) ->\n      contiguous_range_exact_lo (y :: l) i ->\n      contiguous_range_exact_lo (x :: y :: l) i.\n  Proof using. \n    intros. unfold contiguous_range_exact_lo in *. intuition.\n    - invc H4.\n      + eexists; intuition.\n      + find_rewrite. find_apply_lem_hyp Nat.succ_inj. subst.\n        assert (i < i0 <= maxIndex (y :: l)). simpl. omega.\n        find_apply_hyp_hyp. break_exists. simpl in *.\n        intuition; subst; eexists; intuition.\n    - simpl in *. intuition; subst; auto. specialize (H2 y). concludes. omega.\n  Qed.\n\n  Lemma contiguous_partition :\n    forall l1 x l2 i,\n      sorted (l1 ++ x :: l2) ->\n      contiguous_range_exact_lo (l1 ++ x :: l2) i ->\n      contiguous_range_exact_lo l1 (eIndex x).\n  Proof using. \n    Opaque sorted.\n    induction l1; intros.\n    - apply contiguous_nil.\n    - destruct l1; simpl in *; find_copy_apply_lem_hyp contiguous_index_adjacent; auto.\n      + apply contiguous_singleton_sufficient. intuition.\n      + intuition. eapply contiguous_adjacent_sufficient; auto.\n        eauto using contiguous_singleton_sufficient. eapply IHl1.\n        * eauto using sorted_subseq, subseq_skip, subseq_refl.\n        * eauto using cons_contiguous_sorted.\n    Transparent sorted.\n  Qed.\n\n\n  Lemma rev_exists :\n    forall A (l : list A) l',\n    (exists l'',\n       l = l'' ++ l') ->\n    exists l'',\n      rev l = rev l' ++ l''.\n  Proof using. \n    intros.\n    break_exists.\n    exists (rev x). subst. eauto using rev_app_distr.\n  Qed.\n\n  Lemma app_in_2 :\n    forall A l l1 l2 (x : A),\n      l = l1 ++ l2 ->\n      In x l2 ->\n      In x l.\n  Proof using. \n    intros. subst. intuition.\n  Qed.\n\n  Lemma app_contiguous_maxIndex_le_eq :\n    forall l l1 l2 l2' i,\n      l = l1 ++ l2 ->\n      Prefix l2 l2' ->\n      contiguous_range_exact_lo l i ->\n      maxIndex l2' <= i ->\n      l = l1.\n  Proof using. \n    intros. subst.\n    destruct l2; eauto using app_nil_r.\n    simpl in *.\n    break_match; intuition. subst. simpl in *.\n    unfold contiguous_range_exact_lo in *.\n    intuition. specialize (H0 e0). conclude_using intuition.\n    omega.\n  Qed.\n\n  Lemma Prefix_nil :\n    forall A l,\n      Prefix (A := A) l [] ->\n      l = [].\n  Proof using. \n    intros. destruct l; simpl in *; intuition.\n  Qed.\n\n  Lemma sorted_app_1 :\n    forall l1 l2,\n      sorted (l1 ++ l2) ->\n      sorted l1.\n  Proof using. \n    intros. induction l1; simpl in *; intuition;\n    eapply H0; intuition.\n  Qed.\n\n  Lemma Prefix_maxIndex :\n    forall l l' e,\n      sorted l' ->\n      Prefix l l' ->\n      In e l ->\n      eIndex e <= maxIndex l'.\n  Proof using. \n    induction l; intros; simpl in *; intuition;\n    break_match; intuition; repeat subst; simpl in *; auto.\n    intuition.\n    eapply_prop_hyp sorted sorted; eauto.\n    match goal with\n      | _ : eIndex _ <= maxIndex ?l |- _ =>\n        destruct l\n    end.\n    - simpl in *.\n      find_apply_lem_hyp Prefix_nil. subst. simpl in *. intuition.\n    - simpl in *.\n      match goal with\n        | [ H : forall _, _ = _ \\/ In _ _ -> _, _ : eIndex _ <= eIndex ?e |- _ ] =>\n          specialize (H e)\n      end; intuition.\n  Qed.\n\n  Lemma app_maxIndex_In_l :\n    forall l l' e,\n      sorted (l ++ l') ->\n      In e (l ++ l') ->\n      maxIndex l' < eIndex e ->\n      In e l.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    - destruct l'; simpl in *; intuition; subst; intuition.\n      find_apply_hyp_hyp. intuition.\n    - do_in_app. intuition. right. eapply IHl; eauto.\n      intuition.\n  Qed.\n\n  Lemma contiguous_app_prefix_contiguous :\n    forall l1 l2 l2' i,\n      Prefix l2 l2' ->\n      sorted (l1 ++ l2) ->\n      contiguous_range_exact_lo (l1 ++ l2) i ->\n      (l2 <> [] \\/ i = maxIndex l2') ->\n      contiguous_range_exact_lo l1 (maxIndex l2').\n  Proof using. \n    intros.\n    destruct l2.\n    - intuition. subst. rewrite app_nil_r in *. auto.\n    - match goal with H : _ \\/ _ |- _ => clear H end.\n      simpl in *. break_match; intuition. subst. simpl.\n      eauto using contiguous_partition.\n  Qed.\n\n  Lemma Prefix_In :\n    forall A (l : list A) l' x,\n      Prefix l l' ->\n      In x l ->\n      In x l'.\n  Proof using. \n    induction l; intros; simpl in *; intuition;\n    subst; break_match; intuition; subst; intuition.\n  Qed.\n\n  Lemma sorted_term_index_lt :\n    forall l e e',\n      sorted l ->\n      In e l ->\n      In e' l ->\n      eIndex e < eIndex e' ->\n      eTerm e <= eTerm e'.\n  Proof using. \n    intros.\n    induction l; simpl in *; intuition; repeat subst; auto;\n    find_apply_hyp_hyp; intuition.\n  Qed.\n\n  Lemma contiguous_app_prefix_2 :\n    forall l l' l'' i,\n      sorted (l ++ l') ->\n      contiguous_range_exact_lo (l ++ l') 0 ->\n      Prefix l' l'' ->\n      maxIndex l'' < i <= maxIndex l ->\n      exists e, eIndex e = i /\\ In e l.\n  Proof using. \n    destruct l'.\n    - intros. simpl in *. rewrite app_nil_r in *.\n      eapply_prop (contiguous_range_exact_lo l). omega.\n    - intros. find_eapply_lem_hyp contiguous_app_prefix_contiguous; eauto.\n      left. intuition. congruence.\n  Qed.\n\n  Lemma contiguous_0_app :\n    forall l1 l2 e,\n      sorted (l1 ++ l2) ->\n      contiguous_range_exact_lo (l1 ++ l2) 0 ->\n      In e l1 ->\n      eIndex e > maxIndex l2.\n  Proof using. \n    induction l1; intros.\n    - simpl in *. intuition.\n    - rewrite <- app_comm_cons in *.\n      match goal with\n        | H : In _ _ |- _ => simpl in H\n      end. intuition.\n      + subst. simpl in *. intuition.\n        destruct l2; simpl in *.\n        * unfold contiguous_range_exact_lo in *. intuition.\n        * match goal with\n            | H : _ |- eIndex _ > eIndex ?e =>\n              specialize (H e)\n          end. conclude_using intuition. intuition.\n      + find_apply_lem_hyp cons_contiguous_sorted; eauto.\n        simpl in *. intuition.\n  Qed.\n\n  Lemma deduplicate_log'_In_if :\n    forall e l ks,\n      In e (deduplicate_log' l ks) ->\n      In e l.\n  Proof using. \n    induction l; intros; simpl in *; intuition.\n    repeat break_match; simpl in *; intuition; find_apply_hyp_hyp; auto.\n  Qed.\n\n\n  Lemma findGtIndex_removeAfterIndex_i_lt_i' :\n    forall l i i',\n      sorted l ->\n      i < i' ->\n      (filter\n         (fun x : entry =>\n            (i <? eIndex x) && (eIndex x <=? i'))\n         (findGtIndex l i))\n        ++ removeAfterIndex l i =\n      removeAfterIndex l i'.\n  Proof using. \n    induction l; intros; intuition.\n    simpl in *.\n    repeat break_if; simpl in *; repeat break_if;\n    repeat (do_bool; intuition); try omega.\n    simpl. f_equal.\n    rewrite IHl; eauto.\n    apply removeAfterIndex_eq.\n    intros.\n    find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma findGtIndex_removeAfterIndex_i'_le_i :\n    forall l i i',\n      sorted l ->\n      i' <= i ->\n      (filter\n         (fun x : entry =>\n            (i <? eIndex x) && (eIndex x <=? i'))\n         (findGtIndex l i))\n        ++ removeAfterIndex l i =\n      removeAfterIndex l i.\n  Proof using. \n    induction l; intros; intuition.\n    simpl in *.\n    repeat break_if; simpl in *; repeat break_if;\n    repeat (do_bool; intuition); omega.\n  Qed.\n\n\n  Lemma sorted_cons_elim :\n    forall e l,\n      sorted (e :: l) ->\n      sorted l.\n  Proof using. \n    eauto using sorted_subseq, subseq_skip, subseq_refl.\n  Qed.\n\n  Lemma contiguous_sorted_last :\n    forall l x i,\n      sorted (l ++ [x]) ->\n      contiguous_range_exact_lo (l ++ [x]) i ->\n      eIndex x = S i /\\ contiguous_range_exact_lo l (S i).\n  Proof using. \n    Opaque sorted.\n    induction l; intros.\n    - split.\n      + simpl in *. find_apply_lem_hyp contiguous_index_singleton. assumption.\n      + apply contiguous_nil.\n    - destruct l.\n      + simpl in *. find_copy_apply_lem_hyp contiguous_index_adjacent; auto.\n        find_apply_lem_hyp cons_contiguous_sorted; auto.\n        find_copy_apply_lem_hyp contiguous_index_singleton.\n        intuition. eapply contiguous_singleton_sufficient. omega.\n      + simpl in *. find_copy_apply_lem_hyp contiguous_index_adjacent; auto.\n        find_apply_lem_hyp cons_contiguous_sorted; auto.\n        find_apply_lem_hyp sorted_cons_elim. split.\n        * eapply IHl; eauto.\n        * eapply contiguous_adjacent_sufficient; intuition.\n          eapply IHl; eauto.\n    Transparent sorted.\n  Qed.\n\n  Lemma sorted_app_gt :\n    forall l1 l2 e1 e2,\n      sorted (l1 ++ l2) ->\n      In e1 l1 ->\n      In e2 l2 ->\n      eIndex e1 > eIndex e2.\n  Proof using. \n    induction l1; intros.\n    - contradiction.\n    - simpl in *. intuition.\n      + subst. assert (In e2 (l1 ++ l2)). apply in_or_app. intuition.\n        find_apply_hyp_hyp. intuition.\n      + eauto.\n  Qed.\n\n  Lemma sorted_app_In_reduce:\n    forall l1 l2 e1 e2,\n      sorted (l1 ++ [e1]) ->\n      sorted (l2 ++ [e2]) ->\n      eIndex e1 = eIndex e2 ->\n      (forall e, In e (l1 ++ [e1]) -> In e (l2 ++ [e2])) ->\n      (forall e, In e l1 -> In e l2).\n  Proof using. \n    intros.\n    find_copy_eapply_lem_hyp (sorted_app_gt l1 [e1]); simpl; eauto.\n    assert (In e (l1 ++ [e1])). apply in_or_app. intuition.\n    find_apply_hyp_hyp. find_apply_lem_hyp in_app_or. intuition.\n    simpl in *. intuition. subst. omega.\n  Qed.\n\n  Lemma contiguous_sorted_subset_prefix :\n    forall l1 l2 i,\n      contiguous_range_exact_lo l1 i ->\n      contiguous_range_exact_lo l2 i ->\n      sorted l1 ->\n      sorted l2 ->\n      (forall e, In e l1 -> In e l2) ->\n      Prefix (rev l1) (rev l2).\n  Proof using. \n    intros l1.\n    induction l1 using rev_ind; intuition.\n    induction l2 using rev_ind.\n    - find_insterU. concludes. contradiction.\n    - repeat rewrite rev_unit.\n      find_apply_lem_hyp contiguous_sorted_last; auto.\n      find_apply_lem_hyp contiguous_sorted_last; auto.\n      intuition. repeat find_reverse_rewrite. simpl. intuition.\n      + eapply uniqueIndices_elim_eq; eauto using sorted_uniqueIndices.\n      + eapply IHl1; eauto using sorted_app_1, sorted_app_In_reduce.\n  Qed.\n\n  Lemma Prefix_exists_rest :\n    forall A l1 l2,\n      Prefix (A := A) l1 l2 ->\n      exists rest,\n        l2 = l1 ++ rest.\n  Proof using. \n    induction l1; intros; simpl in *; eauto.\n    break_match; intuition. subst.\n    find_apply_hyp_hyp.\n    break_exists_exists. subst. auto.\n  Qed.\n\n  Lemma not_empty_false :\n    forall A (l : list A),\n      not_empty l = false ->\n      l  = [].\n  Proof using. \n    destruct l; [auto|discriminate].\n  Qed.\n\n  Lemma moreUpToDate_refl :\n    forall x y,\n      moreUpToDate x y x y = true.\n  Proof using. \n    intros.\n    unfold moreUpToDate in *.\n    apply Bool.orb_true_intro.\n    right. do_bool.\n    intuition; do_bool; intuition.\n  Qed.\n\n  Lemma wonElection_dedup_spec :\n    forall l,\n      wonElection (dedup name_eq_dec l) = true ->\n      exists quorum,\n        NoDup quorum /\\\n        length quorum > div2 (length nodes) /\\\n        (forall h, In h quorum -> In h l).\n  Proof using. \n    intros.\n    exists (dedup name_eq_dec l). intuition; eauto using NoDup_dedup, in_dedup_was_in.\n    unfold wonElection in *.\n    do_bool. omega.\n  Qed.\n\n\n  Lemma contiguous_findAtIndex :\n    forall l s i,\n      sorted l ->\n      contiguous_range_exact_lo l s ->\n      s < i <= maxIndex l ->\n      exists e, findAtIndex l i = Some e.\n  Proof using. \n    unfold contiguous_range_exact_lo.\n    intros.\n    intuition.\n    match goal with\n    | [ H : forall _, _ |- _ ] => specialize (H i)\n    end.\n    intuition.\n    break_exists_exists.\n    intuition.\n    eapply findAtIndex_intro; auto using sorted_uniqueIndices.\n  Qed.\nEnd CommonTheorems.\n\nNotation is_append_entries m :=\n  (exists t n prevT prevI entries c,\n     m = AppendEntries t n prevT prevI entries c).\n\nNotation is_request_vote_reply m :=\n  (exists t r,\n     m = RequestVoteReply t r).\n\nLtac use_applyEntries_spec :=\n  match goal with\n    | H : context [applyEntries] |- _ => eapply applyEntries_spec in H; eauto; break_exists\n  end.\n\nLtac unfold_invariant hyp :=\n  (red in hyp;  (* try unfolding the invariant and look for conjunction *)\n    match type of hyp with\n      | _ /\\ _ => break_and\n      | _ => fail 1  (* better to not unfold *)\n    end) ||\n  break_and.\n\n(* introduces an invariant then tries to break apart any nested\n   conjunctions to return the usable invariants as hypotheses *)\nLtac intro_invariant lem :=\n  match goal with\n  | [ h: raft_intermediate_reachable _ |- _ ] =>\n      let x := fresh in\n      pose proof h as x;\n        apply lem in x;\n        unfold_invariant x\n  end.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft/CommonTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7479996592896804}}
{"text": "Require Import SQIR.UnitaryOps.\nRequire Import QuantumLib.Matrix.\nRequire Import QuantumLib.Measurement.\n\nOpen Scope ucom.\nLocal Open Scope C_scope.\nLocal Open Scope R_scope.\n\nLocal Coercion Nat.b2n : bool >-> nat.\n\n(* Utility function *)\nLemma times_n_C : forall (c : Complex.C) n, times_n c n = (INR n * c)%C.\nProof.\n  intros c n. \n  induction n; simpl. \n  lca. \n  rewrite IHn.\n  destruct n; lca.\nQed.\n\n(* Bernstein Vazirani circuit *)\nDefinition bernstein_vazirani {n} (U : base_ucom n) : base_ucom n :=\n    npar n U_H; U; npar n U_H.\n\n(* Definition of the function the oracle will implement *)\n(* This is f(s, x) = s . x mod 2 *)\nDefinition bitwise_product n x y :=\n  Nat.b2n (product (nat_to_funbool n x) (nat_to_funbool n y) n).\n\n(* Definition of phase oracle U : ∣ x ⟩ ↦ (-1) ^ (f(s, x)) ∣ x ⟩ *)\nDefinition phase_oracle {n} (U : base_ucom n) f :=\n    forall (x : nat), (x < 2 ^ n)%nat ->\n    @Mmult _ _ 1 (uc_eval U) (basis_vector (2 ^ n) x) = \n            (-1) ^ (f x) .* basis_vector (2 ^ n) x. \n\n(* Probability of measuring ∣ s ⟩ is 1 *)\nLemma bernstein_vazirani_is_correct :\n    forall {n : nat} (U : base_ucom n) (s : nat),\n    (n > 0)%nat -> (s < 2 ^ n)%nat -> phase_oracle U (bitwise_product n s) ->\n    probability_of_outcome (basis_vector (2 ^ n) s) (uc_eval (bernstein_vazirani U) × (n ⨂ ∣0⟩)) = 1.\nProof.\n    intros.\n    unfold bernstein_vazirani.\n    simpl uc_eval.\n    rewrite npar_H by lia.\n    repeat (rewrite Mmult_assoc; restore_dims).\n    rewrite H0_kron_n_spec_alt by auto.\n    restore_dims; distribute_scale.\n    repeat rewrite Mmult_Msum_distr_l. \n    erewrite big_sum_eq_bounded.\n    2: { intros.\n        unfold phase_oracle in H1.\n        rewrite (H1 x) by assumption.\n        distribute_scale.\n        reflexivity. }\n    unfold probability_of_outcome, inner_product.\n    distribute_scale.\n    rewrite Mmult_Msum_distr_l.\n    erewrite big_sum_eq_bounded.   \n    2: { intros.\n        replace (basis_vector (2 ^ n) x) with (f_to_vec n (nat_to_funbool n x)).\n        - rewrite H_kron_n_spec by assumption.\n          distribute_scale.\n          rewrite Cmult_comm.\n          rewrite Mmult_Msum_distr_l.\n          erewrite big_sum_unique.\n          2: { exists s. \n              split; [lia | split].\n              distribute_scale. \n              rewrite basis_vector_product_eq by lia.\n              reflexivity.\n              intros j ? ?.\n              distribute_scale. \n              rewrite basis_vector_product_neq by lia.\n              lma. }\n          distribute_scale.\n          unfold bitwise_product.\n          reflexivity. \n        - rewrite basis_f_to_vec_alt by assumption; reflexivity. }\n    rewrite Mscale_Msum_distr_l.\n    rewrite Mscale_assoc.\n    erewrite big_sum_eq_bounded.\n    2: { intros.\n        rewrite product_comm.\n        assert (forall a, (/ √ (2 ^ n) * (-1) ^ a * (-1) ^ a)%C = (/ √ (2 ^ n))%C).\n        intros.\n        induction a.\n        simpl; repeat rewrite Cmult_1_r; reflexivity.\n        simpl.\n        replace (/ √ (2 ^ n) * (-1 * (-1) ^ a) * (-1 * (-1) ^ a))%C with (/ √ (2 ^ n) * (-1) ^ a * (-1) ^ a)%C by lca.\n        rewrite IHa; reflexivity.\n        rewrite (H3 (product (nat_to_funbool n x) (nat_to_funbool n s) n)).\n        reflexivity. }\n    unfold I, scale.\n    simpl.\n    rewrite Cmult_1_r, Rmult_1_r.\n    rewrite big_sum_constant.\n    rewrite times_n_C.\n    rewrite <- Cmod_mult.\n    autorewrite with RtoC_db.\n    replace (INR (2 ^ n)) with (2 ^ n)%R.\n    2: { rewrite pow_INR; reflexivity. }\n    assert (/ √ (2 ^ n) * / √ (2 ^ n) = / (2 ^ n)).\n    rewrite <- sqrt_inv; try nonzero. (* for compatibility with RealAux and Coq <8.16 *)\n    rewrite sqrt_sqrt.\n    reflexivity.\n    constructor; apply Rinv_0_lt_compat; nonzero.\n    repeat rewrite <- Rmult_assoc.\n    rewrite Rmult_comm.\n    repeat rewrite <- Rmult_assoc.\n    rewrite H2.\n    do 3 ( rewrite Rmult_comm;\n           repeat rewrite <- Rmult_assoc).\n    rewrite H2.\n    field_simplify (/ 2 ^ n * 2 ^ n * / 2 ^ n * 2 ^ n)%R.\n    rewrite Cmod_1; reflexivity.\n    nonzero.\nQed.\n    ", "meta": {"author": "inQWIRE", "repo": "SQIR", "sha": "7d2938bf63080e37d47059befa27a57f12cc099c", "save_path": "github-repos/coq/inQWIRE-SQIR", "path": "github-repos/coq/inQWIRE-SQIR/SQIR-7d2938bf63080e37d47059befa27a57f12cc099c/examples/examples/BernsteinVazirani.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787997, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7479560293094926}}
{"text": "\n\nRequire Import ZArith.\nOpen Scope Z_scope.\nRequire Import ssreflect.\n\n\nInductive Value : Set :=\n    | VInt : Z -> Value\n    | VBool : bool -> Value.\n\nInductive Exp : Set :=\n    | EValue : Value -> Exp\n    | EIf    : Exp -> Exp -> Exp -> Exp \n    | EPlus  : Exp -> Exp -> Exp \n    | EMinus : Exp -> Exp -> Exp \n    | ETimes : Exp -> Exp -> Exp \n    | ELt    : Exp -> Exp -> Exp.\n\n\nInductive Plus : Z -> Z -> Z -> Prop :=\n    | B_Plus : forall x y z, z = x + y -> Plus x y z.\n\nInductive Minus : Z -> Z -> Z -> Prop :=\n    | B_Minus : forall x y z, z = x - y -> Minus x y z.\n\nInductive Times : Z -> Z -> Z -> Prop :=\n    | B_Times : forall x y z, z = x * y -> Times x y z.\n    \nInductive Lt : Z -> Z -> bool -> Prop :=\n    | B_Lt : forall x y b, b = (x <? y) -> Lt x y b.\n    \nTheorem Plus_uniq :\n    forall x y z1 z2, Plus x y z1 -> Plus x y z2 -> z1 = z2.\nProof.\n    move => x y z1 z2 H1 H2.\n    inversion H1; inversion H2; subst => //.\nQed. \n\nTheorem Minus_uniq :\n    forall x y z1 z2, Minus x y z1 -> Minus x y z2 -> z1 = z2.\nProof.\n    move => x y z1 z2 H1 H2.\n    inversion H1; inversion H2; subst => //.\nQed. \n\nTheorem Times_uniq :\n    forall x y z1 z2, Times x y z1 -> Times x y z2 -> z1 = z2.\nProof.\n    move => x y z1 z2 H1 H2.\n    inversion H1; inversion H2; subst => //.\nQed.   \n\nTheorem Lt_uniq :\n    forall x y b1 b2, Lt x y b1 -> Lt x y b2 -> b1 = b2.\nProof.\n    move => x y b1 b2 H1 H2.\n    inversion H1; inversion H2; subst => //.\nQed.\n\nInductive EvalTo : Exp -> Value -> Prop :=\n    | E_Int   : forall i, EvalTo (EValue (VInt i)) (VInt i)\n    | E_Bool  : forall b, EvalTo (EValue (VBool b)) (VBool b)\n    | E_IfT   : forall B T F v, EvalTo B (VBool true)  -> EvalTo T v -> EvalTo (EIf B T F) v\n    | E_IfF   : forall B T F v, EvalTo B (VBool false) -> EvalTo F v -> EvalTo (EIf B T F) v\n    | E_Plus  : forall X Y x y z,\n                EvalTo X (VInt x) -> EvalTo Y (VInt y) -> Plus x y z ->\n                EvalTo (EPlus X Y) (VInt z)\n    | E_Minus : forall X Y x y z,\n                EvalTo X (VInt x) -> EvalTo Y (VInt y) -> Minus x y z ->\n                EvalTo (EMinus X Y) (VInt z)\n    | E_Times : forall X Y x y z,\n                EvalTo X (VInt x) -> EvalTo Y (VInt y) -> Times x y z ->\n                EvalTo (ETimes X Y) (VInt z)\n    | E_Lt    : forall X Y x y b,\n                EvalTo X (VInt x) -> EvalTo Y (VInt y) -> Lt x y b ->\n                EvalTo (ELt X Y) (VBool b).\n\nLemma EvalTo_Bool : \n    forall E b, EvalTo E (VBool b) -> \n    (E = EValue (VBool b)) \\/ \n    (exists B T F, E = EIf B T F )  \\/\n    (exists X Y, E = ELt X Y).\nProof.\n    move => E b H.\n    inversion H.\n    +   left => //.\n    +   right; left.\n        exists B, T, F => //.\n    +   right; left.\n        exists B, T, F => //.\n    +   right; right.\n        exists X, Y => //.\nQed.\n\nLemma EvalTo_Int :\n        forall E i, EvalTo E (VInt i) ->\n        (E = EValue (VInt i)) \\/ \n        (exists B T F, E = EIf B T F) \\/ \n        (exists X Y, E = EPlus X Y) \\/ \n        (exists X Y, E = EMinus X Y) \\/ \n        (exists X Y, E = ETimes X Y).\nProof.\n    move => E i H.\n    inversion H.\n    +   left => //.\n    +   right; left.\n        exists B, T, F => //.\n    +   right; left.\n        exists B, T, F => //.\n    +   right; right; left.\n        exists X, Y => //. \n    +   right; right; right; left.\n        exists X, Y => //.\n    +   right; right; right; right.\n        exists X, Y => //.\nQed.          \n\nTheorem EvalTo_uniq :\n    forall E v1 v2, EvalTo E v1 -> EvalTo E v2 -> v1 = v2.\nProof.  \n    elim.\n    +   move => v v1 v2 H1 H2.\n        inversion H1; inversion H2; subst => //.\n    +   move => B HB T HT F HF v1 v2 H1 H2.\n        inversion H1; inversion H2; subst.\n        -   apply HT => //.\n        -   move : (HB (VBool true) (VBool false) H5 H11) => f.\n            inversion f.\n        -   move : (HB (VBool true) (VBool false) H11 H5) => f.\n            inversion f.\n        -   apply HF => //.\n    +   move => X HX Y HY v1 v2 H1 H2.\n        inversion H1; inversion H2; subst.\n        move : (HX (VInt x) (VInt x0) H3 H9) => Hx; inversion Hx.\n        move : (HY (VInt y) (VInt y0) H4 H10) => Hy; inversion Hy.\n        subst x0 y0.\n        move : (Plus_uniq x y z z0 H6 H12) -> => //.\n    +   move => X HX Y HY v1 v2 H1 H2.\n        inversion H1; inversion H2; subst.\n        move : (HX (VInt x) (VInt x0) H3 H9) => Hx; inversion Hx.\n        move : (HY (VInt y) (VInt y0) H4 H10) => Hy; inversion Hy.\n        subst x0 y0.\n        move : (Minus_uniq x y z z0 H6 H12) -> => //.\n    +   move => X HX Y HY v1 v2 H1 H2.\n        inversion H1; inversion H2; subst.\n        move : (HX (VInt x) (VInt x0) H3 H9) => Hx; inversion Hx.\n        move : (HY (VInt y) (VInt y0) H4 H10) => Hy; inversion Hy.\n        subst x0 y0.\n        move : (Times_uniq x y z z0 H6 H12) -> => //.\n    +   move => X HX Y HY v1 v2 H1 H2.\n        inversion H1; inversion H2; subst.\n        move : (HX (VInt x) (VInt x0) H3 H9) => Hx; inversion Hx.\n        move : (HY (VInt y) (VInt y0) H4 H10) => Hy; inversion Hy.\n        subst x0 y0.\n        move : (Lt_uniq x y b b0 H6 H12) -> => //.\nQed.     \n\n\nInductive Error : Exp -> Prop :=\n    | E_IfInt       : forall B T F i, EvalTo B (VInt i)  -> Error (EIf B T F)\n    | E_PlusBoolL   : forall X Y b,   EvalTo X (VBool b) -> Error (EPlus X Y)\n    | E_PlusBoolR   : forall X Y b,   EvalTo Y (VBool b) -> Error (EPlus X Y)\n    | E_MinusBoolL  : forall X Y b,   EvalTo X (VBool b) -> Error (EMinus X Y)\n    | E_MinusBoolR  : forall X Y b,   EvalTo Y (VBool b) -> Error (EMinus X Y)\n    | E_TimesBoolL  : forall X Y b,   EvalTo X (VBool b) -> Error (ETimes X Y)\n    | E_TimesBoolR  : forall X Y b,   EvalTo Y (VBool b) -> Error (ETimes X Y)\n    | E_LtBoolL     : forall X Y b,   EvalTo X (VBool b) -> Error (ELt X Y)\n    | E_LtBoolR     : forall X Y b,   EvalTo Y (VBool b) -> Error (ELt X Y)\n    | E_IfTError    : forall B T F,   EvalTo B (VBool true)  -> Error T -> Error (EIf B T F)\n    | E_IfFError    : forall B T F,   EvalTo B (VBool false) -> Error F -> Error (EIf B T F)\n    | E_IfError     : forall B T F,   Error B -> Error (EIf B T F)\n    | E_PlusErrorL  : forall X Y  ,   Error X -> Error (EPlus X Y)\n    | E_PlusErrorR  : forall X Y  ,   Error Y -> Error (EPlus X Y)\n    | E_MinusErrorL : forall X Y  ,   Error X -> Error (EMinus X Y)\n    | E_MinusErrorR : forall X Y  ,   Error Y -> Error (EMinus X Y)\n    | E_TimesErrorL : forall X Y  ,   Error X -> Error (ETimes X Y)\n    | E_TimesErrorR : forall X Y  ,   Error Y -> Error (ETimes X Y)\n    | E_LtErrorL    : forall X Y  ,   Error X -> Error (ELt X Y)\n    | E_LtErrorR    : forall X Y  ,   Error Y -> Error (ELt X Y).\n\nTheorem EvalTo_Error_total :\n    forall e, (exists v, EvalTo e v) \\/ Error e.\nProof.\n    elim.\n    +   move => v.\n        left; exists v.\n        induction v; [apply E_Int | apply E_Bool ].\n    +   move => B HB T HT F HF.\n        case HB as [[b Hb] | Eb]; last first.\n        right; apply E_IfError => //.\n        induction b as [i|b].\n        right; apply E_IfInt with (i := i) => //.\n        induction b.\n        -   case HT as [[t Ht] | Et].\n            *   left; exists t; apply E_IfT => //.\n            *   right; apply E_IfTError => //.\n        -   case HF as [[f Hf] | Ef].\n            *   left; exists f; apply E_IfF => //.\n            *   right; apply E_IfFError => //.\n    +   move => X HX Y HY.\n        case HX => [[x Hx]| Ex]; last first.\n        right; apply E_PlusErrorL => //.\n        induction x as [i|b]; last first.\n        right; apply E_PlusBoolL with (b := b) => //.\n        case HY => [[y Hy]| Ey]; last first.\n        right; apply E_PlusErrorR => //.\n        induction y as [j|b]; last first.\n        right; apply E_PlusBoolR with (b := b) => //.\n        left; exists (VInt (i + j)); apply (E_Plus _ _ i j) => //.\n    +   move => X HX Y HY.\n        case HX => [[x Hx]| Ex]; last first.\n        right; apply E_MinusErrorL => //.\n        induction x as [i|b]; last first.\n        right; apply E_MinusBoolL with (b := b) => //.\n        case HY => [[y Hy]| Ey]; last first.\n        right; apply E_MinusErrorR => //.\n        induction y as [j|b]; last first.\n        right; apply E_MinusBoolR with (b := b) => //.\n        left; exists (VInt (i - j)); apply (E_Minus _ _ i j) => //.\n    +   move => X HX Y HY.\n        case HX => [[x Hx]| Ex]; last first.\n        right; apply E_TimesErrorL => //.\n        induction x as [i|b]; last first.\n        right; apply E_TimesBoolL with (b := b) => //.\n        case HY => [[y Hy]| Ey]; last first.\n        right; apply E_TimesErrorR => //.\n        induction y as [j|b]; last first.\n        right; apply E_TimesBoolR with (b := b) => //.\n        left; exists (VInt (i * j)); apply (E_Times _ _ i j) => //.\n    +   move => X HX Y HY.\n        case HX => [[x Hx]| Ex]; last first.\n        right; apply E_LtErrorL => //.\n        induction x as [i|b]; last first.\n        right; apply E_LtBoolL with (b := b) => //.\n        case HY => [[y Hy]| Ey]; last first.\n        right; apply E_LtErrorR => //.\n        induction y as [j|b]; last first.\n        right; apply E_LtBoolR with (b := b) => //.\n        left; exists (VBool (i <? j)); apply (E_Lt _ _ i j) => //.\nQed.        \n\n\n\n\n\n\n\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "CoPL", "sha": "fdf26a94dc8dae7b53c6a12679e3ebb417113f31", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-CoPL", "path": "github-repos/coq/gaxiiiiiiiiiiii-CoPL/CoPL-fdf26a94dc8dae7b53c6a12679e3ebb417113f31/IntegerAndBooleans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7479560233810467}}
{"text": "Require Import ZArith.\nSection section_for_chapter_4.\n\n(* 4.1 p70 *)\n\n(* 4.2 p82 *)\n\n(* 4.3 p85 *)\n\nSection A_declared.\nVariable (A:Set) (P Q:A->Prop) (R:A->A->Prop).\n\nTheorem all_perm : (forall a b : A, R a b)->forall a b : A, R b a.\nProof.\nintros. apply H.\nQed.\n\nTheorem all_imp_dist: (forall a:A, P a -> Q a)->(forall a:A, P a)->forall a:A, Q a.\nProof.\nintros. apply H. apply H0.\nQed.\n\nTheorem all_delta : (forall a b:A, R a b)->forall a:A, R a a.\nProof.\nintros. apply H.\nQed.\n\nEnd A_declared.\n\n(* 4.4 p88 *)\n\nDefinition id' : forall A:Set, A->A.\nintros.\nassumption.\nQed.\n\nPrint id'.\n\nDefinition diag : forall A B:Set, (A->A->B)->A->B := fun A B f a => f a a.\n\nDefinition permute: forall A B C:Set, (A->B->C)->B->A->C := fun A B C f b a => f a b.\n\nDefinition f_nat_Z: forall A:Set, (nat->A)->Z->A := fun A f z => f (Z.to_nat  z).\n\n(* 4.5 p89 *)\nTheorem all_perm' : forall (A : Type) (P : A -> A -> Prop),\n  (forall (x y : A), P x y) -> forall (x y : A), P y x.\nProof.\nintros.\napply H.\nQed.\n\nTheorem resolution : forall (A : Type) (P Q R S : A->Prop),\n  (forall (a : A), Q a -> R a -> S a) ->\n  (forall (b : A), P b -> Q b) ->\n  (forall (c : A), P c -> R c -> S c).\nProof.\nintros.\napply H;[apply H0; assumption | assumption].\nQed.\n\nEnd section_for_chapter_4.", "meta": {"author": "FiveEyes", "repo": "Notes", "sha": "5b5dfdddd4cb6eb05179ae3c58e2f33b7c88e2f9", "save_path": "github-repos/coq/FiveEyes-Notes", "path": "github-repos/coq/FiveEyes-Notes/Notes-5b5dfdddd4cb6eb05179ae3c58e2f33b7c88e2f9/PL/Coq/coq_art_exercise_chapter4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7479560207598754}}
{"text": "Require Import ZArith.\nRequire Import Eqdep_dec.\nLocal Open Scope Z_scope.\n\nDefinition t := { n: Z | n > 1 }.\n\nProgram Definition two : t := 2.\nNext Obligation. omega. Qed.\n\nProgram Definition t_eq (x y: t) : {x=y} + {x<>y} :=\n  if Z.eq_dec (proj1_sig x) (proj1_sig y) then left _ else right _.\nNext Obligation.\n  destruct x as [x Px], y as [y Py]. simpl in H; subst y.\n  f_equal. apply UIP_dec. decide equality.\nQed.\nNext Obligation.\n  congruence.\nQed.\n\nDefinition t_list_eq: forall (x y: list t), {x=y} + {x<>y}.\nProof. decide equality. apply t_eq. Defined.\n\nGoal match t_list_eq (two::nil) (two::nil) with left _ => True | right _ => False end.\nProof. exact I. Qed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/4280.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7479560147158086}}
{"text": "Require Import Relations.\nSection Sequences.\n Variable A : Type.\n\n Variable R : A -> A -> Prop. \n\n Lemma not_acc : forall a b:A, R a b -> ~ Acc R a -> ~ Acc R b.\n Proof.\n  intros a b H H0 H1;  absurd (Acc R a); auto.\n  generalize a H; now induction H1.\n Qed.\n\n Lemma acc_imp : forall a b:A, R a b -> Acc R b -> Acc R a.\n Proof.\n  intros a b H H0;  generalize a H; now induction H0.\n Qed.\n\n Hypothesis W : well_founded R.\n Hint Resolve W.\n\t\n Section seq_intro.\n  Variable seq : nat -> A. \n\n  Let is_in_seq (x:A) :=  exists i : nat, x = seq i.\n\n  Lemma not_decreasing_aux : ~ (forall n:nat, R (seq (S n)) (seq n)). \n  Proof.\n   unfold not in |- *; intro Hseq.\n  assert  (H : forall a:A, is_in_seq a -> ~ Acc R a).\n  -   intro a; pattern a in |- *; apply well_founded_ind with A R; auto.\n      intros x Hx [i Hi]; generalize (Hseq i); intro H0; rewrite Hi.\n      apply not_acc with (seq (S i)); auto.\n      apply Hx.\n      +  rewrite Hi; auto.\n      +  exists (S i); auto.\n  - apply (H (seq 0)). \n    +  exists 0; trivial. \n    + apply W.\n Qed.\n\n\n End seq_intro.\n\n Theorem not_decreasing :\n  ~ (exists seq : nat -> A, (forall i:nat, R (seq (S i)) (seq i))).\n Proof.\n   intros [s Hs];  now apply (not_decreasing_aux s).\n Qed.\n\nEnd Sequences.\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/ch15_general_recursion/SRC/not_decreasing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.747956010953672}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat ssrfun eqtype.\nRequire Import monoid_record.\n\nRequire Import ZArith.\n\nLemma mul1z : forall x : Z, (1 * x)%Z = x.\nProof. by auto with zarith. Qed.\n\nLemma mulz1 : forall x : Z, (x * 1)%Z = x.\nProof. by auto with zarith. Qed.\n\nDefinition Z_mul_monoidMixin := MonoidMixin Z.mul_assoc mul1z mulz1.\nCanonical Z_mul_monoid := Eval hnf in MonoidType Z Z_mul_monoidMixin.\n\nDefinition Z_mul_commMonoidMixin := CommMonoidMixin Z.mul_comm.\nCanonical Z_mul_commMonoid := Eval hnf in CommMonoidType Z_mul_monoid Z_mul_commMonoidMixin.\n", "meta": {"author": "palmskog", "repo": "monoid-ssreflect", "sha": "17829b473afb0fa9a85c319a5f8a259e14d91b33", "save_path": "github-repos/coq/palmskog-monoid-ssreflect", "path": "github-repos/coq/palmskog-monoid-ssreflect/monoid-ssreflect-17829b473afb0fa9a85c319a5f8a259e14d91b33/monoid_Z_mul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7478496606367092}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSection ListUtils.\n\nVariable T : Type.\nImplicit Type s : seq T.\n\nLemma drop_drop s a b : drop a (drop b s) = drop (a + b) s.\nProof.\nelim: s a b => // ? ? H ? [|?]; by [rewrite drop0 addn0 | rewrite H addnS].\nQed.\n\nLemma take_take s b a : a <= b -> take a (take b s) = take a s.\nProof.\nelim: s a b => // h t H [ [] | a] // [ | b] //=.\nrewrite ltnS => ?; by rewrite H.\nQed.\n\nLemma take_minn m n s : take (minn m n) s = take m (take n s).\nProof.\n  case: (ltnP n m).\n    move=> H.\n    rewrite minnC /minn H.\n    rewrite [take m _]take_oversize.\n      by [].\n    rewrite size_take.\n    case: ltnP.\n      move=> _.\n      by apply ltnW.\n    move=> Hs.\n    apply (leq_trans Hs).\n    by apply ltnW.\n  move=> H.\n  rewrite minnC /minn.\n  rewrite ltnNge H /=.\n  symmetry.\n  by apply take_take.\nQed.\n\nLemma catr_take n (s1 s2 : seq T) : s1 ++ take n s2 = take (size s1 + n) (s1 ++ s2).\nProof. by rewrite take_cat -ltn_subRL subnn ltn0 addnC addnK. Qed.\n\nLemma drop_take_inv m n s : drop m (take (m + n) s) = take n (drop m s).\nProof.\n  elim: s m n => [|a l IH m n]; first by [].\n  by case: m => [|m /=]; [rewrite 2!drop0 add0n|rewrite -IH].\nQed.\n\nEnd ListUtils.\n\n\nFixpoint map_prefix {T1 T2 : Type} (f : T1 -> option T2) (s : seq T1) : seq T2 :=\n  match s with\n  | nil => nil\n  | e :: s' =>\n      if f e is Some v then\n        v :: map_prefix f s'\n      else\n        nil\n  end.\n\nLemma map_prefix_cat {T1 T2 : Type} (f : T1 -> option T2) e s1 s2 :\n  f e = None -> map_prefix f (s1 ++ e :: s2) = map_prefix f s1.\nProof.\n  move=> H.\n  elim: s1.\n    simpl.\n    by rewrite H.\n  move=> a s IH /=.\n  by rewrite IH.\nQed.\n\nLemma size_map_prefix_full {T1 T2 : Type} (f : T1 -> option T2) s :\n  (size (map_prefix f s) == size s) = (all (isSome \\o f) s).\nProof.\n  elim: s.\n    by [].\n  move=> e s IH /=.\n  case: (f e) => [_ /=|]; last by [].\n  by rewrite eqSS.\nQed.\n\n", "meta": {"author": "akr", "repo": "coq-html-escape", "sha": "37a070f4bc18694f6f2b0aea4a2c64636dbb556f", "save_path": "github-repos/coq/akr-coq-html-escape", "path": "github-repos/coq/akr-coq-html-escape/coq-html-escape-37a070f4bc18694f6f2b0aea4a2c64636dbb556f/coq/theories/listutils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7478463464121035}}
{"text": "(** * Logic: Logic in Coq *)\n\n(* $Date: 2011-06-22 10:06:32 -0400 (Wed, 22 Jun 2011) $ *)\n\nRequire Export \"Prop\". \nRequire Import LibTactics.\n(** Coq's built-in logic is extremely small: [Inductive] definitions,\n    universal quantification ([forall]), and implication ([->]) are\n    primitive, but all the other familiar logical connectives --\n    conjunction, disjunction, negation, existential quantification,\n    even equality -- can be defined using just these. *)\n\n(* ########################################################### *)\n(** * Quantification and Implication *)\n\n(** In fact, [->] and [forall] are the _same_ primitive!  Coq's [->]\n    notation is actually just a shorthand for [forall].  The [forall]\n    notation is more general, because it allows us to _name_ the\n    hypothesis. *)\n\n(** For example, consider this proposition: *)\n\nDefinition funny_prop1 := forall n, forall (E : ev n), ev (n+4).\n\n(** If we had a proof term inhabiting this proposition, it would be a\n    function with two arguments: a number [n] and some evidence that\n    [n] is even.  But the name [E] for this evidence is not used in\n    the rest of the statement of [funny_prop1], so it's a bit silly to\n    bother making up a name.  We could write it like this instead: *)\n\nDefinition funny_prop1' := forall n, forall (_ : ev n), ev (n+4).\n\n(** Or we can write it in more familiar notation: *)\n\nDefinition funny_prop1'' := forall n, ev n -> ev (n+4).\n\n(** This illustrates that \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ########################################################### *)\n(** * Conjunction *)\n\n(** The logical conjunction of propositions [P] and [Q] is\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q). \n\n(** Note that, like the definition of [ev] in the previous\n    chapter, this definition is parameterized; however, in this case,\n    the parameters are themselves propositions, rather than numbers. *)\n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q]. \n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example : \n  (ev 0) /\\ (ev 4).\nProof.\n  apply conj.\n  (* Case \"left\". *) apply ev_0.\n  (* Case \"right\". *) apply ev_SS. apply ev_SS. apply ev_0.  Qed.\n\n(** Let's take a look at the proof object for the above theorem. *)\n\nPrint and_example. \n(* ===>  conj (ev 0) (ev 4) ev_0 (ev_SS 2 (ev_SS 0 ev_0))\n            : ev 0 /\\ ev 4 *)\n\n(** Note that the proof is of the form\n[[\n    conj (ev 0) (ev 4) (...pf of ev 0...) (...pf of ev 4...)\n]]\n    which is what you'd expect, given the type of [conj]. *)\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n    Case \"left\". apply ev_0.\n    Case \"right\". apply ev_SS. apply ev_SS. apply ev_0.  Qed.\n\n(** Conversely, the [inversion] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and put this evidence into the\n    proof context. *)\n\nTheorem proj1 : forall P Q : Prop, \n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ]. \n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2) *)\nTheorem proj2 : forall P Q : Prop, \n  P /\\ Q -> Q.\nProof.\n  introv H.\n  inversion H as [HP HQ].\n  apply HQ. Qed.\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop, \n  P /\\ Q -> Q /\\ P.\nProof.\n  introv H. inversion H as [HP HQ]. split; assumption.\nQed.\n(*\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HP HQ]. \n  split.  \n    (* Case \"left\". *) apply HQ. \n    (* Case \"right\".*) apply HP.  Qed. *)\n  \n(** Once again, we have commented out the [Case] tactics to make the\n    proof object for this theorem easy to understand.  Examining it\n    shows that all that is really happening is taking apart a record\n    containing evidence for [P] and [Q] and rebuilding it in the\n    opposite order: *)\n\nPrint and_commut.\n(* ===>\n   and_commut = \n     fun (P Q : Prop) (H : P /\\ Q) =>\n     let H0 := match H with\n               | conj HP HQ => conj Q P HQ HP\n               end in H0\n     : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\n\n(** **** Exercise: 2 stars (and_assoc) *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [inversion] breaks [H : P /\\ (Q /\\ R)] down into [HP: P], [HQ :\n    Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop, \n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n  split; [split | ]; assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (even_ev) *)\n(** Now we can prove the other direction of the equivalence of [even]\n   and [ev], which we left hanging in the last chapter.  Notice that\n   the left-hand conjunct here is the statement we are actually\n   interested in; the right-hand conjunct is needed in order to make\n   the induction hypothesis strong enough that we can carry out the\n   reasoning in the inductive step.  (To see why this is needed, try\n   proving the left conjunct by itself and observe where things get\n   stuck.) *)\n\nTheorem even_ev_fails : forall n : nat,\n  even n -> ev n.\nProof.\n  induction n.\n  intros. apply ev_0.\nAdmitted.\nTheorem even_ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  (* Hint: Use induction on [n]. *)\n  induction n as [|n']; [| inversion IHn' as [H0 H1]]; split; intros.\n    apply ev_0.\n    inversion H.\n    apply H1. assumption.\n    apply ev_SS. apply H0. unfold even. unfold even in H. simpl in H. assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars *)\n(** Construct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun _ _ _ pq qr =>\n    match pq with\n      | conj p q =>\n        match qr with\n          | conj q2 r => conj _ _ p r\n        end\n    end.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The familiar logical \"if and only if\" is just the\n    conjunction of two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) \n                      (at level 95, no associativity) : type_scope.\n\nTheorem iff_implies : forall P Q : Prop, \n  (P <-> Q) -> P -> Q.\nProof.  \n  intros P Q H. \n  inversion H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop, \n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. \n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star (iff_properties) *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop, \n  P <-> P.\nProof. \n  intros. split; intros; assumption.\nQed.\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  introv pqEq qrEq. inversion pqEq as [pq qp]. inversion qrEq as [qr rq].\n  dup.\n    split; intros; tauto.\n\n    split.\n    Case \"P -> R\". introv p. apply qr. apply pq. apply p.\n    Case \"R -> P\". introv r. apply qp. apply rq. apply r.\n    Qed.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n(** **** Exercise: 2 stars (MyProp_iff_ev) *)\n(** We have seen that the families of propositions [MyProp] and [ev]\n    actually characterize the same set of numbers (the even ones).\n    Prove that [MyProp n <-> ev n] for all [n].  Just for fun, write\n    your proof as an explicit proof object, rather than using\n    tactics. (_Hint_: if you make use of previously defined thoerems,\n    you should only need a single line!) *)\nDefinition MyProp_iff_ev : forall n, MyProp n <-> ev n :=\n  fun n => conj _ _ (ev_MyProp _) (MyProp_ev _).\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q. \n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P],[Q] and\n    evidence of [P], and returns as output, the evidence of [P /\\ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for! -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** Since [P \\/ Q] has two constructors, doing [inversion] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"right\". apply or_intror. apply HP.\n    Case \"left\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"right\". right. apply HP.\n    Case \"left\". left. apply HQ.  Qed.\n\n(** **** Exercise: 2 stars, optional (or_commut'') *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\nCheck or_commut'.\nDefinition or_commut'' P Q (pq: P \\/ Q): Q \\/ P :=\n  match pq with\n    | or_introl p => or_intror _ _ p\n    | or_intror q => or_introl _ _ q\n  end.\n(** [] *)\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof. \n  intros P Q R. intros H. inversion H as [HP | [HQ HR]]. \n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars, recommended (or_distributes_over_and_2) *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  introv H. inversion H as [[HP | HQ] [HP' | HR]].\n  Case \"PP\".\n  left. apply HP.\n  Case \"PR\".\n  left. apply HP.\n  Case \"QP\".\n  left. apply HP'.\n  Case \"QR\".\n  right. split; assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (or_distributes_over_and) *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  split; [apply or_distributes_over_and_1 | apply or_distributes_over_and_2].\nQed.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are obviously analogs, in some sense, of the logical connectives\n    [/\\] and [\\/].  This analogy can be made more precise by the\n    following theorems, which show how to translate knowledge about\n    [andb] and [orb]'s behaviors on certain inputs into propositional\n    facts about those inputs. *)\n\nTheorem andb_true__and : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  introv H. unfold andb in H. split.\n  Case \"b = true\".\n    destruct b; [reflexivity | inversion H].\n  Case \"c = true\".\n    destruct c; [reflexivity | destruct b; inversion H].\nQed.\n(*\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n*)\n\nTheorem and__andb_true : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  introv H.\n  inversion H. subst. reflexivity.\nQed.\n(*\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.*)\n\n(** **** Exercise: 1 star (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  introv H.\n  destruct b; destruct c; inversion H.\n  Case \"c = false\". right. reflexivity.\n  Case \"b = false\". left. reflexivity.\n  Case \"b = c = false\". left. reflexivity.\nQed.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  introv H.\n  destruct b; destruct c; inversion H.\n  Case \"c = false\". right. reflexivity.\n  Case \"b = false\". left. reflexivity.\n  Case \"b = c = false\". right. reflexivity.\nQed.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  introv H. destruct b; destruct c; inversion H; split; reflexivity.\nQed.\n(** [] *)\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := . \n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n(** **** Exercise: 1 star (False_ind_principle) *)\n(** Can you predict the induction principle for falsehood? *)\n\nCheck False_ind.\n(* False_ind *)\n(*      : forall P : Prop, False -> P *)\n\n(** [] *)\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof. \n  intros contra.\n  inversion contra.  Qed. \n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, we might wonder whether it\n    is possible to define truth in the same way.  Naturally, the\n    answer is yes. *)\n\n(** **** Exercise: 2 stars (True_induction) *)\n(** Define [True] as another inductively defined proposition.  What\n    induction principle will Coq generate for your definition?  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.  Alternatively, you may find it easiest\n    to start with the induction principle and work backwards to the\n    inductive definition.) *)\n\nInductive True :=\n| tt : True.\nCheck True_ind.\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    just a theoretical curiosity: it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False : \n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof. \n  introv contra. inversion contra as [HP HNP]. apply HNP in HP. inversion HP.\n\n  Restart.\n  (* WORKED IN CLASS *)\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA. \n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  introv HP. unfold not. introv HNP. apply HNP. apply HP.\n  Restart.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, recommended (double_neg_inf) *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_: Suppose that [P] is true. We need then to prove that\n   [~~P], that is that [(P -> False) -> False]. Let us introduce (HNP:\n   P -> False) in the context; we need now to prove False. Since we\n   know that P is true and that HNP is true, by modus ponens we can\n   conclude that P's conclusion, False, is true.\n [] *)\n\n(** **** Exercise: 2 stars, recommended (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  unfold not.\n  introv HPQ HNQ HP. apply HNQ in HPQ. assumption. assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof. \n  unfold not. introv HPNP. inversion HPNP as [HP HNP]. apply (HNP HP).\nQed.\n(** [] *)\n\nTheorem five_not_even :  \n  ~ ev 5.\nProof. \n  unfold not. introv H. inverts H as H. inverts H as H. inverts H as H.\n\n  Restart.\n\n  (* WORKED IN CLASS *)\n  unfold not. intros Hev5. inversion Hev5 as [|n Hev3 Heqn]. \n  inversion Hev3 as [|n' Hev1 Heqn']. inversion Hev1.  Qed.\n\n(** **** Exercise: 1 star ev_not_ev_S *)\n(** Theorem [five_not_even] confirms the unsurprising fact that five\n    is not an even number.  Prove this more interesting fact: *)\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof. \n  unfold not. intros n H. induction H. (* not n! *)\n    Case \"n = 0\". introv H. inversion H.\n    Case \"n = S n'\". introv H1. inverts H1 as. apply IHev.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (informal_not_PNP) *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** Note that some theorems that are true in classical logic\n    are _not_ provable in Coq's \"built in\" constructive logic... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H. \n  (* But now what? There is no way to \"invent\" evidence for [P]. *) \n  Admitted.\n\n(** **** Exercise: 5 stars, optional (classical_axioms) *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop, \n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop, \n  ~~P -> P.\nDefinition excluded_middle := 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\n(* FILL IN HERE *)\nTheorem excluded_middle_to_peirce : excluded_middle -> peirce.\nProof.\n  unfold peirce. unfold excluded_middle. unfold not.\n  introv no_middle. introv H.\n  assert (PorNP := no_middle P).\n  inversion PorNP as [| HNP].\n  Case \"P\". assumption.\n  Case \"NP\". apply H. intro HP. apply ex_falso_quodlibet. apply HNP. apply HP.\nQed.\n\n(*\nTheorem classic_to_peirce : classic -> peirce.\nProof.\n  unfold peirce. unfold classic. unfold not.\n  introv classic.\n  apply classic.\n  introv H. apply H.\n  introv Hpeirce. apply Hpeirce.\n*)\n\nTheorem excluded_middle_to_classic : excluded_middle -> classic.\nProof.\n  unfold classic. unfold excluded_middle. unfold not.\n  introv H HNNP.\n  assert (PorNP := H P).\n  inversion PorNP as [HP | HNP].\n  Case \"P\". apply HP.\n  Case \"~P\". apply HNNP in HNP. inversion HNP.\nQed.\n\n(*\nTheorem classic_to_excluded_middle : classic -> excluded_middle.\nProof.\n  unfold classic. unfold excluded_middle. unfold not.\n  introv classic. introv.\n  assert (classicP := classic P).\n  (* cases ((P -> False) -> False). *)\nAdmitted.\nTheorem classic_to_de_morgan_not_and_not : classic -> de_morgan_not_and_not.\nProof.\n  unfold classic. unfold de_morgan_not_and_not. unfold not.\n  intros.\n  assert (H2 := H P).\n*)\n\nTheorem excluded_middle_to_de_morgan_not_and_not :\n  excluded_middle -> de_morgan_not_and_not.\nProof.\n  unfold excluded_middle. unfold de_morgan_not_and_not.\n  introv no_middle. introv no_conj.\n  assert (PorNP := no_middle P).\n  assert (QorNQ := no_middle Q).\n  inversion PorNP as [| NP].\n    Case \"P\". left. assumption.\n    Case \"NQ\". \n      inversion QorNQ as [| NQ].\n      SCase \"Q\". right. assumption.\n      SCase \"NQ\".\n        unfold not in no_conj, NP, NQ.\n        apply ex_falso_quodlibet.\n        apply (no_conj (conj _ _ NP NQ)).\nQed.\n\nTheorem excluded_middle_to_implies_to_or : excluded_middle -> implies_to_or.\nProof.\n  unfold excluded_middle. unfold implies_to_or.\n  introv no_middle. introv PtoQ.\n  assert (PorNP := no_middle P).\n  inversion PorNP.\n  Case \"P\". right. apply PtoQ. assumption.\n  Case \"NP\". left. assumption.\nQed.\n\n(*\nTheorem implies_to_or_to_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or. unfold excluded_middle. unfold not.\n  introv impl_to_or. introv\n  assert (H := impl_to_or P (~P)).\n\nTheorem implies_to_or_to_classic : implies_to_or -> classic.\nProof.\n  unfold implies_to_or. unfold classic.\n  introv impl_to_or. introv NNP.\n  unfold not in NNP.  \n  (* assert (H1 := impl_to_or P (~P)).\n  assert (H2 := impl_to_or (not P) False).\n  assert (H3 := impl_to_or P False). *)\n  unfold not in *.\n  apply H2 in NNP.\n*)\n(** [] *)\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.  \n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\nSearchAbout beq_nat.\nCheck beq_nat_eq.\n(* beq_nat_eq *)\n(*      : forall n m : nat, true = beq_nat n m -> n = m *)\n\n(** **** Exercise: 2 stars, recommended (not_eq_beq_false) *)\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof.\n  unfold not.\n  introv neq.\n  cases (beq_nat n n'); [| reflexivity].\n  apply ex_falso_quodlibet.\n  apply neq.\n  apply beq_nat_eq. symmetry. assumption.\nQed.\n  (* unfold not.\n  introv neq.\n  induction n as [|n0].\n  Case \"n = 0\".\n    induction n'.\n    apply ex_falso_quodlibet. apply neq. reflexivity.\n    reflexivity.\n  Case \"n = S n0\".\n    induction n'.\n    reflexivity.\n\n    simpl.\n    destruct (beq_nat n0 n'). apply ex_falso_quodlibet.\n  Restart.\n  \n  unfold not.\n  introv neq.\n  cases (beq_nat n n'); [| reflexivity].\n  apply ex_falso_quodlibet.\n  apply neq.\n  destruct n; destruct n'; try reflexivity; inverts H. *)\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_false_not_eq) *)\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  unfold not.\n  introv beq_False nEqm. subst.\n  Check beq_nat_refl.\n(* beq_nat_refl *)\n(*      : forall n : nat, true = beq_nat n n *)\n  rewrite <- beq_nat_refl in beq_False.\n  inversion beq_False.\nQed.\n(** [] *)\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can capture what this means with the\n    following 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    For example, consider this existentially quantified proposition: *)\n\nDefinition some_nat_is_even : Prop := \n  ex nat ev.\n\n(** To prove this proposition, we need to choose a particular number\n    as witness -- say, 4 -- and give some evidence that that number is\n    even. *)\n\nDefinition snie : some_nat_is_even := \n  ex_intro _ ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** Coq's notation definition facility can be used to introduce\n    more 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(** We can use the same set of tactics as always for\n    manipulating existentials.  For example, if to prove an\n    existential, we [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, again, that we have to explicitly give the witness. *)\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 * n) = 6.\nProof.\n  exists 2. \n  reflexivity.  Qed.\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(** **** Exercise: 1 star (english_exists) *)\n(** In English, what does the proposition \n[[\n      ex nat (fun n => ev (S n))\n]] \n    mean? *)\n\n(* FILL IN HERE *)\n\n(** Complete the definition of the following proof object: *)\nCheck ex_intro.\n(* ex_intro *)\n(*      : forall (X : Type) (P : X -> Prop) (witness : X), *)\n(*        P witness -> exists x, P x *)\n\nDefinition p : ex nat (fun n => ev (S n)) := ex_intro _ (fun n => ev (S n)) 1 (ev_SS _ ev_0).\nCheck p.\n(* p *)\n(*      : exists n : nat, ev (S n) *)\n\n(** [] *)\n\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" and \"there is no [x] for\n    which [P] does not hold\" are equivalent assertions. *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof. \n  unfold not. introv forAll nExists.\n  inversion nExists as [x px].\n  apply px. apply forAll.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** The other direction requires the classical \"law of the excluded\n    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  unfold excluded_middle. unfold not.\n  introv no_middle nnExists. introv.\n  assert (H := no_middle (P x)).\n  inversion H.\n  Case \"P x\". assumption.\n  Case \"~ (P x)\".\n    apply ex_falso_quodlibet.\n    apply nnExists.\n    exists x. assumption.\nQed.\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  split.\n  Case \"->\".\n    introv exOr.\n    inversion exOr as [x [Px | Qx]]; [left | right]; exists x; assumption.\n  Case \"<-\".\n    introv orEx.\n    inversion orEx as [[x Px] | [x Qx]]; exists x; [left | right]; assumption.\nQed.\n(** [] *)\n\nPrint dist_exists_or.\n\n\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has the\n    following inductive definition.  (We enclose the definition in a\n    module to avoid confusion with the standard library equality,\n    which we have used extensively already.) *)\n\nModule MyEquality.\n\nInductive eq (X:Type) : X -> X -> Prop :=\n  refl_equal : forall x, eq X x x.\nCheck eq_ind.\n(* eq_ind *)\n(*      : forall (X : Type) (P : X -> X -> Prop), *)\n(*        (forall x : X, P x x) -> forall y y0 : X, eq X y y0 -> P y y0 *)\n\n(** Standard infix notation (using Coq's type argument synthesis): *)\n\nNotation \"x = y\" := (eq _ x y) \n                    (at level 70, no associativity) : type_scope.\n\n(** This is a bit subtle.  The way to think about it is that, given a\n    set [X], it defines a _family_ of propositions \"[x] is equal to\n    [y],\" indexed by pairs of values ([x] and [y]) from [X].  There is\n    just one way of constructing evidence for members of this family:\n    applying the constructor [refl_equal] to a type [X] and a value [x\n    : X] yields evidence that [x] is equal to [x]. *)\n\n(** Here is a slightly different definition -- the one that actually\n    appears in the Coq standard library. *)\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\nCheck eq'_ind.\n(* eq'_ind *)\n(*      : forall (X : Type) (x : X) (P : X -> Prop), *)\n(*        P x -> forall y : X, eq' X x y -> P y *)\nNotation \"x =' y\" := (eq' _ x y) \n                     (at level 70, no associativity) : type_scope.\n\n(** **** Exercise: 3 stars, optional (two_defs_of_eq_coincide) *)\n(** Verify that the two definitions of equality are equivalent. *)\n\nTheorem two_defs_of_eq_coincide : forall (X:Type) (x y : X),\n  x = y <-> x =' y.\nProof.\n  split; introv eq; inverts eq; [apply refl_equal' | apply refl_equal].\nQed.\n(** [] *)\n\n(** The advantage of the second definition is that the induction\n    principle that Coq derives for it is precisely the familiar\n    principle of _Leibniz equality_: what we mean when we say \"[x] and\n    [y] are equal\" is that every property on [P] that is true of [x]\n    is also true of [y]. *)\n\nCheck eq'_ind.\n(* ===>  forall (X : Type) (x : X) (P : X -> Prop),\n             P x -> forall y : X, x =' y -> P y *)\n\n(** One important consideration remains.  Clearly, we can use\n    [refl_equal] to construct evidence that, for example, [2 = 2].\n    Can we also use it to construct evidence that [1 + 1 = 2]?  Yes.\n    Indeed, it is the very same piece of evidence!  The reason is that\n    Coq treats as \"the same\" any two terms that are _convertible_\n    according to a simple set of computation rules.  These rules,\n    which are similar to those used by [Eval simpl], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.\n    \n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).  But you can see them\n    directly at work in the following explicit proof objects: *)\n\nDefinition four : 2 + 2 = 1 + 3 :=  \n  refl_equal nat 4. \nDefinition singleton : forall (X:Set) (x:X), []++[x] = x::[]  :=\n  fun (X:Set) (x:X) => refl_equal (list X) [x]. \n\nEnd MyEquality.\n\n(* ####################################################### *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves...\n\n    In general, the [inversion] tactic\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n        \n      - adds these equalities to the context of the subgoal, and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal.\n\n   _Example_: If we invert a hypothesis built with [or], there are two\n   constructors, so two subgoals get generated.  The\n   conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.\n\n   _Example_: If we invert a hypothesis built with [and], there is\n   only one constructor, so only one subgoal gets generated.  Again,\n   the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.  The\n   constructor does have two arguments, though, and these can be seen\n   in the context in the subgoal.\n\n   _Example_: If we invert a hypothesis built with [eq], there is\n   again only one constructor, so only one subgoal gets generated.\n   Now, though, the form of the [refl_equal] constructor does give us\n   some extra information: it tells us that the two arguments to [eq]\n   must be the same!  The [inversion] tactic adds this fact to the\n   context.  *)\n\n(* ####################################################### *)\n(** * Relations as Propositions *)\n\n(** A proposition parameterized numbers (such as [ev]) can be\n    thought of as a _property_ -- i.e., it defines a subset of [nat],\n    namely those numbers for which the proposition is provable.  In\n    the same way, a two-argument proposition can be thought of as a\n    _relation_ -- i.e., it defines a set of pairs for which the\n    proposition is provable. *)\n\nModule LeFirstTry.  \n\n(** We've already seen an inductive definition of one\n    fundamental relation: equality.  Another useful one is the \"less\n    than or equal to\" relation on numbers: *)\n\n(** This definition should be fairly intuitive.  It says that\n    there are two ways to give evidence that one number is less than\n    or equal to another: either observe that they are the same number,\n    or give evidence that the first is less than or equal to the\n    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)).\nCheck le_ind.\n(* le_ind *)\n(*      : forall P : nat -> nat -> Prop, *)\n(*        (forall n : nat, P n n) -> *)\n(*        (forall n m : nat, le n m -> P n m -> P n (S m)) -> *)\n(*        forall n n0 : nat, le n n0 -> P n n0 *)\n\nEnd LeFirstTry.\n\n(** This is a reasonable definition of the [<=] relation, but we\n    can streamline it a little by observing that the left-hand\n    argument [n] is the same everywhere in the definition, so we can\n    actually make it a \"general parameter\" to the whole definition,\n    rather than an argument to each constructor.  This is similar to\n    what we did in our second definition of the [eq] relation,\n    above. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. \n    (The same was true of our second version of [eq].) *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(** By contrast, the induction principle that Coq calculates for the\n    first definition has a lot of extra quantifiers, which makes it\n    messier to work with when proving things by induction.  Here is\n    the induction principle for the first [le]: *)\n\n(* le_ind : \n     forall P : nat -> nat -> Prop,\n     (forall n : nat, P n n) ->\n     (forall n m : nat, le n m -> P n m -> P n (S m)) ->\n     forall n n0 : nat, le n n0 -> P n n0 *)\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 the previous chapter.  We can [apply] the constructors to\n    prove [<=] goals (e.g., to show that [3<=3] or [3<=6]), and we can\n    use tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [~(2 <= 1)].) *)\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).\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H1.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\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, recommended (total_relation) *)\n(** Define an inductive relation [total_relation] that holds\n    between every pair of natural numbers. *)\n\nInductive total_relation : nat -> nat -> Prop :=\n  r' : forall n m : nat, total_relation n m.\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive relation [empty_relation] (on numbers)\n    that never holds. *)\nInductive empty_relation : nat -> nat -> Prop := .\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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- Yes; No.\n- No; c5 only guarantees commutativity in the first two components, but the other constructors are already symmetric or dualizable.\n- No.\n*)\nDefinition R1 : R 1 1 2 := c3 _ _ _ (c2 _ _ _ c1).\nDefinition R1' : R 1 1 2 := c2 _ _ _ (c3 _ _ _ c1).\nPrint R1.\nPrint R1'.\n(*\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** State and prove an equivalent characterization of the relation\n    [R].  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_fact : forall m n o, R m n o <-> m + n = o.\nProof.\n  split; introv H.\n  Case \"->\".\n    induction H.\n    SCase \"c1\". reflexivity.\n    SCase \"c2\". simpl. congruence.\n    SCase \"c3\". rewrite <- plus_n_Sm; congruence.\n    SCase \"c4\".\n      inverts IHR as IHR. rewrite <- plus_n_Sm in IHR. inverts IHR. reflexivity.\n    SCase \"c5\".\n      subst. apply plus_comm.\n  Case \"<-\".\n    subst.\n    induction m as [|m']; simpl.\n    SCase \"m = 0\".\n      induction n as [|n'].\n      SSCase \"n = 0\". apply c1.\n      SSCase \"n = S n'\". apply c3. assumption.\n    SCase \"m = S m'\". apply c2. assumption.\nQed.\n(** [] *)\n\nEnd R.\n\n(** **** Exercise: 3 stars, recommended (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 X P []\n  | all_cons : forall x l, P x -> all X P l -> all X P (x :: l).\n\n(** Recall the function [forallb], from the exercise\n[forall_exists_challenge] in [Poly.v]: *)\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(* Complete specification of forallb. *)\nLemma forallb_all :\n  forall X test l, all X (fun x => test x = true) l <-> forallb test l = true.\nProof.\n  split; introv H.\n  Case \"->\".\n    induction H.\n    SCase \"H = all_nil\". reflexivity.\n    SCase \"H = all_cons\".\n      simpl. rewrite H. rewrite IHall. reflexivity.\n  Case \"<-\".\n    induction l as [| x l']. \n    SCase \"l = []\". apply all_nil.\n    SCase \"l = x :: l'\".\n      simpl in H.\n      assert (H2 : forallb test l' = true).\n\n      SSCase \"proof of assertion\".\n        apply andb_true_elim2 in H. apply H.\n      apply IHl' in H2.\n      assert (H3 : test x = true).\n      SSCase \"proof of assertion\".\n        apply andb_true_elim1 in H. apply H.\n      apply all_cons; assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (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[[\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    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\nInductive merge_of {X} : list X -> list X -> list X -> Prop :=\n  | merge_of_nil : merge_of [] [] []\n  | merge_of_l : forall {x l1 l2 l3},\n                   merge_of l1 l2 l3 ->\n                   merge_of (x :: l1) l2 (x :: l3)\n  | merge_of_r : forall {x l1 l2 l3},\n                   merge_of l1 l2 l3 ->\n                   merge_of l1 (x :: l2) (x :: l3).\n\nExample merge_of_1 : merge_of [1,6,2] [4,3] [1,4,6,2,3].\nProof.\n  apply merge_of_l.\n  apply merge_of_r.\n  repeat (apply merge_of_l).\n  apply merge_of_r.\n  apply merge_of_nil.\nQed.\nExample merge_of_1' : merge_of [1,6,2] [4,3] [1,4,6,2,3] :=\n  merge_of_l (merge_of_r (merge_of_l (merge_of_l (merge_of_r merge_of_nil)))).\nPrint merge_of_1'.\nCheck filter.\n\nLemma merge_of_nil_any : forall X (l1 l2 : list X), merge_of [] l1 l2 -> l1 = l2.\nProof.\n  induction l1 as [|x1 l1']; introv H.\n  Case \"l1 = []\". inverts H. reflexivity.\n  Case \"l1 = x1 :: l1'\".\n    destruct l2 as [|x2 l2'].\n    SCase \"l2 = []\". inverts H.\n    SCase \"l2 = x2 :: l2'\".\n      inverts H as H.\n      apply IHl1' in H.\n      congruence.\nQed.\n\nTheorem filter_spec_challenge :\n  forall X (l1 l2 l : list X) test,\n    all _ (fun x => test x = true) l1 ->\n    all _ (fun x => test x = false) l2 ->\n    merge_of l1 l2 l ->\n    filter test l = l1.\nProof.\n  introv all_l1_t all_l2_f.\n  induction all_l1_t; introv merge.\n\n  Case \"all_nil\".\n    inverts merge.\n    SCase \"merge_of_nil\". reflexivity.\n    SCase \"merge_of_l\".\n      apply merge_of_nil_any in H. subst.\n      induction (x :: l4) as [|x' l'].\n      SSCase \"x :: l4 = []\". reflexivity.\n      SSCase \"x :: l4 = x' :: l'\".\n        simpl.\n        inverts all_l2_f.\n        replace (test x') with false by assumption.\n        apply IHl', H2.\n      (*\n      inverts H.\n      SSCase \"H = merge_of_nil\".\n        inverts all_l2_f. simpl.\n        replace (test x) with false by assumption. reflexivity.\n      SSCase \"H = ?\".\n        (* inverts H0.\n        SCase \"merge_of_r\". *)\n        apply merge_of_nil_any in H0. subst. simpl.\n        inversion all_l2_f.\n        inversion H2. subst.\n        replace (test x) with false by assumption.\n        replace (test x0) with false by assumption.\n*)\n  Case \"all_cons\".\n\n  Restart.\n\n  introv all_l1_t all_l2_f.\n  induction l as [|x l']; introv merge.\n  Case \"l = []\". inversion merge. reflexivity.\n  Case \"l = cons\".\n\n  Restart.\n  introv all_l1_t all_l2_f.\n  induction all_l2_f; introv merge.\n  Restart.\n  introv.\n  generalize dependent l2.\n  generalize dependent l1.\n  induction l as [|x l']; introv all_l1_t all_l2_f merge.\n  Case \"l = []\". inversion merge. reflexivity.\n  Case \"l = x :: l'\".\n    inverts merge.\n    SCase \"merge_of_l\".\n      inverts all_l1_t.\n      simpl. replace (test x) with true by assumption.\n      replace l0 with (filter test l'). reflexivity.\n      apply IHl' with (l2 := l2); assumption.\n    SCase \"merge_of_r\".\n      inverts all_l2_f.\n      simpl.\n      replace (test x) with false by assumption.\n      apply IHl' with (l2 := l3); assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, 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, optional (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  (*\n  introv H.\n  inversion H.\n  Case \"ai_here\".\n    destruct xs as [|x' xs'].\n    SCase \"xs = []\".\n      simpl in H1. subst. right. constructor.\n    SCase \"xs = x' :: xs'\".\n      inverts H1. simpl in H. left. constructor.\n  Case \"ai_later\".\n    destruct xs as [|x' xs'].\n    SCase \"xs = []\".\n      simpl in H. subst. right. assumption.\n    SCase \"xs = x' :: xs'\".\n    simpl in H0. inverts H0.\n      inverts H1. simpl in H. left. constructor.\n   *)\n  introv. generalize dependent ys.\n  induction xs as [|x' xs']; simpl; introv H.\n  Case \"xs = []\".\n    right. assumption.\n  Case \"xs = x' :: xs'\".\n    inverts H.\n    SCase \"left\". left. constructor.\n    SCase \"right\".\n      apply IHxs' in H1.\n      destruct H1.\n      SSCase \"left\".\n        left. constructor. assumption.\n      SSCase \"right\".\n        right. assumption.\nQed.\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  introv H. destruct H.\n  Case \"appears_in x xs\".\n    induction xs as [|x' xs']; simpl.\n    SCase \"xs = []\". inversion H.\n    SCase \"xs = x' :: xs'\".\n      inverts H; constructor.\n      SSCase \"x <> x'\".\n        apply IHxs', H1.\n  Case \"appears_in x ys\".\n    induction xs; simpl; [| constructor]; assumption.\nQed.\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. *)\nCheck all.\nDefinition disjoint {X} (l1 l2 : list X) := all _ (fun x => ~(appears_in x l2)) l1.\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\nInductive no_repeats {X} : list X -> Prop :=\n  | nr_nil : no_repeats []\n  | nr_cons : forall x l, ~(appears_in x l) -> no_repeats l -> no_repeats (x :: l).\n\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [no_repeats] and [++] (list append).  *)\n\nLemma disjoint_distr :\n  forall X x (l1 l2 : list X),\n    disjoint (x :: l1) l2 -> disjoint l1 l2.\nProof.\n  unfold disjoint. introv H. inverts H. assumption.\nQed.\n\nLemma foo : forall X x (l1 l2 : list X), appears_in x (l1 ++ l2) -> no_repeats (x :: l1) -> appears_in x l2.\nProof.\n  introv Happ Hnr.\n  induction l1; simpl in Happ.\n  assumption.\n  apply IHl1; clear IHl1.\n  Case \"1\".\n    inverts Happ.\n    SCase \"1\".\n      inverts Hnr. apply ex_falso_quodlibet, H1. constructor.\n    SCase \"2\".\n      assumption.\n  Case \"2\".\n    inverts Hnr. constructor.\n    SCase \"1\".\n      unfold not in *. intro H. apply H1. constructor. assumption.\n    SCase \"2\". inverts H2. assumption.\nQed.\n  (*\n  inverts Happ as Happ.\n  Case \"1\".\n    destruct l1 as [|x' l1'].\n    SCase \"l1 = []\".\n      simpl in Happ. subst. constructor.\n    SCase \"l1 = x' :: l1'\".\n      simpl in Happ. inverts Happ. inverts Hnr.\n      apply ex_falso_quodlibet.\n      apply H1. constructor.\n  Case \"2\".\n    destruct l1 as [|x' l1'].\n    SCase \"l1 = []\".\n      simpl in H0. subst. constructor. assumption.\n    SCase \"l1 = x' :: l1'\".\n      simpl in H0. inverts H0.*)\n\nTheorem no_r_distr :\n  forall X (l1 l2 : list X), disjoint l1 l2 -> no_repeats l1 -> no_repeats l2 ->\n                             no_repeats (l1 ++ l2).\nProof.\n  introv disj nr_l1 nr_l2.\n  induction l1; simpl. assumption.\n  constructor.\n  Case \"1st hp\".\n    inverts disj.\n    intro H. apply foo in H. 2: apply nr_l1. apply H1 in H. assumption.\n    (* inversion H.\n    unfold not in H1. *)\n  Case \"2nd hp\".\n    apply IHl1.\n    apply disjoint_distr in disj. apply disj.\n    inverts nr_l1. assumption.\nQed.\n\n(** [] *)\n\n(* ######################################################### *)\n(** ** Digression: More Facts about [<=] and [<] *)\n\n(** Let's pause briefly to record several facts about the [<=]\n    and [<] relations that we are going to need later in the\n    course.  The proofs make good practice exercises. *)\n\nPrint le.\n(* Inductive le (n : nat) : nat -> Prop := *)\n(*     le_n : n <= n | le_S : forall m : nat, n <= m -> n <= S m *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros.\n  induction n; constructor. assumption.\nQed.\n\nCheck le_ind.\n(* le_ind *)\n(*      : forall (n : nat) (P : nat -> Prop), *)\n(*        P n -> *)\n(*        (forall m : nat, n <= m -> P m -> P (S m)) -> *)\n(*        forall n0 : nat, n <= n0 -> P n0 *)\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  introv H. induction H as [|m' H].\n  constructor.\n  constructor. assumption.\nRestart.\n  intro n. apply le_ind.\n  constructor.\n  intros. constructor. assumption.\n  (*\n  generalize dependent n.\n  induction m as [|m']. intros. inversion H. constructor.\n  intros.\n   *)\n  (*\n  generalize dependent m.\n  induction n as [|n'].\n\n  induction m. constructor. constructor. apply IHm. apply O_le_n.\n\n  induction m as [|m']; introv H. inversion H.\n  constructor.\n  apply IHm'. \n   *)\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  intros n m.  generalize dependent n.  induction m. \n    introv H. inversion H.\n      constructor.\n\n      inversion H1.\n\n    introv H. inverts H.\n      constructor.\n\n      inverts H1.\n        repeat constructor.\n\n        constructor. apply IHm. constructor. assumption.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  induction a as [|a'].\n  apply O_le_n.\n  simpl.\n  introv.\n\nRestart.\n  induction b as [|b'].\n  rewrite plus_0_r. constructor.\n\n  rewrite <- plus_n_Sm. constructor.\n  assumption.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof. \n  split.\n\n  Case \"n1 < m\".\n    unfold lt in *.\n    induction m as [|m'].\n    SCase \"m = 0\". inversion H.\n\n    SCase \"m = S m'\".\n      inverts H.\n      SSCase \"1\".\n        clear IHm'.\n        induction n2 as [|n2'].\n        SSSCase \"n2 = 0\".\n          rewrite plus_0_r. constructor.\n        SSSCase \"n2 = S n2'\".\n          rewrite <- plus_n_Sm. constructor. apply IHn2'.\n      SSCase \"2\".\n        constructor. apply IHm', H1.\n  Case \"n2 < m\".\n    unfold lt in *.\n    induction m as [|m'].\n    SCase \"m = 0\". inversion H.\n    SCase \"m = S m'\".\n      inverts H.\n      SSCase \"1\".\n        clear IHm'.\n        induction n1 as [|n1']; simpl; constructor; assumption.\n      SSCase \"2\".\n        constructor. apply IHm'. assumption. Qed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  unfold lt. constructor. assumption. Qed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  induction n.\n    intros. apply O_le_n.\n\n    intros. destruct m.\n      inversion H.\n\n      simpl in H.\n      apply n_le_m__Sn_le_Sm. apply IHn. assumption. Qed.\n\nTheorem ble_nat_n_Sn_false : forall n m,\n  ble_nat n (S m) = false ->\n  ble_nat n m = false.\nProof.\n  induction n as [|n']; introv H.\n  Case \"n = 0\".\n    inversion H.\n  Case \"n = S n'\".\n    inverts H. rewrite H1.\n    destruct m; simpl. reflexivity.\n    apply IHn'. assumption.\nQed.\n\nSearchAbout ble_nat.\n(* test_ble_nat1: ble_nat 2 2 = true *)\n(* test_ble_nat2: ble_nat 2 4 = true *)\n(* test_ble_nat3: ble_nat 4 2 = false *)\n(* ble_nat_refl: forall n : nat, true = ble_nat n n *)\n(* plus_ble_compat_l: *)\n(*   forall n m p : nat, ble_nat n m = true -> ble_nat (p + n) (p + m) = true *)\n(* NatList.count_member_nonzero: *)\n(*   forall s : NatList.bag, *)\n(*   ble_nat 1 (NatList.count 1 (NatList.cons 1 s)) = true *)\n(* NatList.ble_n_Sn: forall n : nat, ble_nat n (S n) = true *)\n(* NatList.remove_decreases_count: *)\n(*   forall s : NatList.bag, *)\n(*   ble_nat (NatList.count 0 (NatList.remove_one 0 s)) (NatList.count 0 s) = *)\n(*   true *)\n(* ble_nat_n_Sn_false: *)\n(*   forall n m : nat, ble_nat n (S m) = false -> ble_nat n m = false *)\n(* ble_nat_true: forall n m : nat, ble_nat n m = true -> n <= m *)\n\nSearchAbout le.\n(* ble_nat_true: forall n m : nat, ble_nat n m = true -> n <= m *)\n(* le_plus_l: forall a b : nat, a <= a + b *)\n(* Sn_le_Sm__n_le_m: forall n m : nat, S n <= S m -> n <= m *)\n(* n_le_m__Sn_le_Sm: forall n m : nat, n <= m -> S n <= S m *)\n(* O_le_n: forall n : nat, 0 <= n *)\n(* test_le3: ~ 2 <= 1 *)\n(* test_le2: 3 <= 6 *)\n(* test_le1: 3 <= 3 *)\n(* le_ind: *)\n(*   forall (n : nat) (P : nat -> Prop), *)\n(*   P n -> *)\n(*   (forall m : nat, n <= m -> P m -> P (S m)) -> *)\n(*   forall n0 : nat, n <= n0 -> P n0 *)\n(* le_n: forall n : nat, n <= n *)\n(* le_S: forall n m : nat, n <= m -> n <= S m *)\n\nLemma le_Sn_m_remove_S : forall n m, S n <= m -> n <= m.\nProof.\n  introv H.\n  induction H. repeat constructor.\n  constructor; assumption.\nQed.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* Hint: Do the right induction! *)\n  unfold not.\n  introv H nm.\n  induction m as [|m'].\n  Case \"m = 0\".\n    inverts nm. inverts H.\n  Case \"m = S m'\".\n    destruct n as [|n']; inverts H.\n    SCase \"n = S n'\".\n      inverts nm.\n        rewrite <- ble_nat_refl in H1. inverts H1.\n\n        apply IHm', H0.\nRestart.\n  unfold not.\n  introv H nm.\n  generalize dependent m.\n  induction n as [|n'].\n  Case \"m = 0\". intros. inverts H.\n  Case \"m = S m'\".\n    intros.\n    destruct m.\n      inverts nm.\n\n      inverts nm.\n        rewrite <- ble_nat_refl in H. inverts H.\n\n        inverts H as H.\n\n        (* inverts H1. apply ble_nat_n_Sn_false in H.\n        rewrite <- ble_nat_refl in H. inverts H. *)\n        apply IHn' with (m := m). assumption.\n        SearchAbout le.\n        clear H IHn'.\n\n        simpl.\n        apply le_Sn_m_remove_S, H1.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (nostutter) *)\n(** Formulating inductive definitions of predicates is an important skill\n    you'll need in this course.\n\n    Try to solve this exercise without any help at all.   If you do receive \n    assistance from anyone, please say so specifically in a comment.\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*)\n\nInductive nostutter:  list nat -> Prop :=\n  | ns_nil : nostutter nil\n  | ns_single : forall x, nostutter [x]\n  | ns_cons : forall x1 x2 l, x1 <> x2 -> nostutter (x2 :: l) -> nostutter (x1 :: x2 :: l).\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].\nProof. repeat constructor; apply beq_false_not_eq; reflexivity. Qed.\n(* \n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_2:  nostutter [].\nProof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n(* \n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\nProof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n(* \n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n*)\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 H1; reflexivity. Qed.\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, optional (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 this 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  induction l1; simpl; try reflexivity.\n  intros.\n  rewrite IHl1. reflexivity.\nQed.\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  intros.\n  induction l; inverts H.\n  exists (@nil X). exists l. reflexivity.\n  apply IHl in H1. clear IHl.\n  destruct H1 as [l1' [l2' H2]].\n  subst.\n  exists (x0 :: l1'). exists l2'.\n  reflexivity.\nQed.\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  | rp_base : forall x l, appears_in x l -> repeats (x :: l)\n  | rp_cons : forall x l, repeats l -> repeats (x :: l).\n\n\nLemma pigeonhole_principle_hard: 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 -> ~ repeats l1 ->\n  (forall x, appears_in x l2 -> appears_in x l1).\nProof.\n  intros X l1 l2 excl.\n  intros.\n  gen l1 l2.\n  induction l1.\n  Case \"l1 = []\".\n  intros.\n  simpl in H0.\n  destruct l2; try assumption.\n  inverts H0.\n  Case \"l1 = x0 :: l1\".\n  intros.\n  assert (Hexcl := excl (x = x0)).\n  destruct Hexcl.\n  SCase \"x = x0\".\n  subst. constructor.\n  SCase \"x <> x0\".\n  constructor.\nAdmitted.\n(** Now here's a way to formalize the pigeonhole principle. List [l2]\n   represents a list of pigeonhole labels, and list [l1] represents an\n   assignment of items to labels: if there are more items than labels,\n   at least two items must have the same label.  You will almost\n   certainly need to use 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(*\n  intros X l1 l2.\n  gen l1.\n  induction l2.\n  Case \"l2 = []\".\n  intros.\n  destruct l1.\n  inverts H1.\n  assert (Habs := H0 x).\n  apply ex_falso_quodlibet.\n  assert (Happ : appears_in x (x :: l1)). constructor.\n  apply Habs in Happ.\n  inverts Happ.\n  Case \"l2 = x :: l2\".\n  intro l1.\n  intro Hexcl.\n  intro Hcontained.\n  intro Hlen.\n  apply \n  apply IHl2 in Hexcl.\n*)\n  intros X l1. induction l1; simpl.\n  Case \"l1 = []\".\n\n  introv H0 H1 H2. inversion H2.\n  Case \"l1 = x :: l1\".\n  introv excl H1 H2.\n  inverts H2.\n  SCase \"length l2 = length l1\".\n  assert (Hcases := excl (repeats l1)).\n  inverts Hcases.\n  SSCase \"repeats l1\".\n  apply rp_cons. assumption.\n  SSCase \"~ (repeats l1)\".\n  apply rp_base.\n  assert (appears_in x l2). apply H1. constructor.\n  SSCase \"~ (repeats l1)\".\n  apply (pigeonhole_principle_hard l1 l2); try assumption.\n  intros.\n  apply H1.\n  constructor. assumption.\n  SCase \"length l2 < length l1\".\n  apply rp_cons.\n  apply IHl1 with (l2 := l2).\n  assumption.\n  intros x0 app.\n  apply H1.\n  constructor.\n  assumption.\n  assumption.\n(*\n  Check (IHl1 _ excl _ H0).\n  Check H1 x.\n  assert (Hcases := excl (repeats (x :: l1))).\n  inverts Hcases; try assumption.\n    \n    (* unfold not in *.\n    apply ex_falso_quodlibet. *)\n    assert (Happ : appears_in x (x :: l1)). constructor.\n    apply (H1 x) in Happ.\n    assert (Hlemma: (forall x : X, appears_in x l1 -> appears_in x l2)).\n    introv Happears.\n    apply H1.\n    constructor. assumption.\n    assert (Hcases := excl (x = x0)).\n    inverts Hcases.\n      assumption.\n\n      Print appears_in.\n(* Inductive appears_in (X : Type) (a : X) : list X -> Prop := *)\n(*     ai_here : forall l : list X, appears_in a (a :: l) *)\n(*   | ai_later : forall (b : X) (l : list X), *)\n(*                appears_in a l -> appears_in a (b :: l) *)\n\n(* For appears_in: Argument X is implicit and maximally inserted *)\n(* For ai_here: Argument X is implicit and maximally inserted *)\n(* For ai_later: Argument X is implicit and maximally inserted *)\n(* For appears_in: Argument scopes are [type_scope _ _] *)\n(* For ai_here: Argument scopes are [type_scope _ _] *)\n(* For ai_later: Argument scopes are [type_scope _ _ _ _] *)\n      apply (ai_later x0 x l1) in Happears. apply H1, Happears.\n\n      induction l2.\n      inversion Happ. simpl in *. inversion H2.\n\n        apply Sn_le_Sm__n_le_m in H2.\n        apply IHl2. \n        (* introv x1inl1.\n        inverts x1inl1.\n          admit. \n        apply Hlemma. *)\n          admit.\n          rewrite <- H3.\n          constructor. constructor.\n          admit.\n\n          assert (Hcases2 := excl (x = x0)).\n          inverts Hcases2.\n          introv xInL1.\n      (* inverts H2.\n        SSCase \"length l2 = length l1\".\n        assert (Hlemma2: appears_in x l1).\nLemma Hlemma2: forall {X} (x : X) l1 l2, length l1 = length l2 -> \n    (forall x : X, appears_in x l1 -> appears_in x l2) -> appears_in x l2 ->\n    appears_in x l1. Admitted.\n\n\n        admit.\n        constructor. apply Hlemma2.\n        SSCase \"length l2 < length l1\".\n        apply rp_cons. apply IHl1 with (l2 := l2); assumption. *)\n*)\nQed.\n(** [] *)\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(* ################################################### *)\n(** ** Induction Principles for [/\\] and [\\/] *)\n\n(** The induction principles for conjunction and disjunction are a\n    good illustration of Coq's way of generating simplified induction\n    principles for [Inductive]ly defined propositions, which we\n    discussed in the last chapter.  You try first: *)\n\n(** **** Exercise: 1 star (and_ind_principle) *)\n(** See if you can predict the induction principle for conjunction. *)\n\n(* Check and_ind. *)\n(** [] *)\n\n(** **** Exercise: 1 star (or_ind_principle) *)\n(** See if you can predict the induction principle for disjunction. *)\n\n(* Check or_ind. *)\n(** [] *)\n\nCheck and_ind.\n\n(** From the inductive definition of the proposition [and P Q]\n[[\n     Inductive and (P Q : Prop) : Prop :=\n       conj : P -> Q -> (and P Q).\n]]\n    we might expect Coq to generate this induction principle\n[[\n     and_ind_max :\n       forall (P Q : Prop) (P0 : P /\\ Q -> Prop),\n            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->\n            forall a : P /\\ Q, P0 a\n]]\n    but actually it generates this simpler and more useful one:\n[[\n     and_ind :\n       forall P Q P0 : Prop,\n            (P -> Q -> P0) ->\n            P /\\ Q -> P0\n]]\n    In the same way, when given the inductive definition of [or P Q]\n[[\n     Inductive or (P Q : Prop) : Prop :=\n       | or_introl : P -> or P Q\n       | or_intror : Q -> or P Q.\n]]\n    instead of the \"maximal induction principle\"\n[[\n     or_ind_max :\n       forall (P Q : Prop) (P0 : P \\/ Q -> Prop),\n            (forall a : P, P0 (or_introl P Q a)) ->\n            (forall b : Q, P0 (or_intror P Q b)) ->\n            forall o : P \\/ Q, P0 o\n]]\n    what Coq actually generates is this:\n[[\n     or_ind :\n       forall P Q P0 : Prop,\n            (P -> P0) ->\n            (Q -> P0) ->\n            P \\/ Q -> P0\n]] \n*)\n\n(* ######################################################### *)\n(** ** Explicit Proof Objects for Induction *)\n\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n    \n(** Recall the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\n(* Check nat_ind. *)\n(* ===> \n   nat_ind : forall P : nat -> Prop,\n      P 0%nat -> \n      (forall n : nat, P n -> P (S n)) -> \n      forall n : nat, P n  *)\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n \nPrint nat_ind.  Print nat_rect.\n(* ===> (after some manual inlining)\n   nat_ind =\n    fun (P : nat -> Type) \n        (f : P 0%nat) \n        (f0 : forall n : nat, P n -> P (S n)) =>\n          fix F (n : nat) : P n :=\n             match n as n0 return (P n0) with\n            | 0%nat => f\n            | S n0 => f0 n0 (F n0)\n            end.\n*)\n\n(** We can read this as follows: \n     Suppose we have evidence [f] that [P] holds on 0,  and \n     evidence [f0] that [forall n:nat, P n -> P (S n)].  \n     Then we can prove that [P] holds of an arbitrary nat [n] via \n     a recursive function [F] (here defined using the expression \n     form [Fix] rather than by a top-level [Fixpoint] \n     declaration).  [F] pattern matches on [n]: \n      - If it finds 0, [F] uses [f] to show that [P n] holds.\n      - If it finds [S n0], [F] applies itself recursively on [n0] \n         to obtain evidence that [P n0] holds; then it applies [f0] \n         on that evidence to show that [P (S n)] holds. \n    [F] is just an ordinary recursive function that happens to \n    operate on evidence in [Prop] rather than on terms in [Set].\n \n    Aside to those interested in functional programming: You may\n    notice that the [match] in [F] requires an annotation [as n0\n    return (P n0)] to help Coq's typechecker realize that the two arms\n    of the [match] actually return the same type (namely [P n]).  This\n    is essentially like matching over a GADT (generalized algebraic\n    datatype) in Haskell.  In fact, [F] has a _dependent_ type: its\n    result type depends on its argument; GADT's can be used to\n    describe simple dependent types like this.\n \n    We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  Recall our desire to\n    prove that\n\n    [forall n : nat, even n -> ev n].\n \n    Attempts to do this by standard induction on [n] fail, because the\n    induction principle only lets us proceed when we can prove that\n    [even n -> even (S n)] -- which is of course never provable.  What\n    we did earlier in this chapter was a bit of a hack:\n \n    [Theorem even_ev : forall n : nat,\n     (even n -> ev n) /\\ (even (S n) -> ev (S n))].\n \n    We can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n \n *)\n \n Definition nat_ind2 : \n    forall (P : nat -> Prop), \n    P 0 -> \n    P 1 -> \n    (forall n : nat, P n -> P (S(S n))) -> \n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS => \n          fix f (n:nat) := match n return P n with \n                             0 => P0 \n                           | 1 => P1 \n                           | S (S n') => PSS n' (f n') \n                          end.\n \n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive (try\n     it!).\n\n     The [induction ... using] tactic gives a convenient way to\n     specify a non-standard induction principle like this. *)\n \nLemma even_ev' : forall n, even n -> ev n.\nProof. \n intros.  \n induction n as [ | |n'] using nat_ind2. \n  Case \"even 0\". \n    apply ev_0.  \n  Case \"even 1\". \n    inversion H.\n  Case \"even (S(S n'))\". \n    apply ev_SS. \n    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H. \nQed. \n\n(* ######################################################### *)\n(** ** The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is \"why\n    trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard Correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on.\n\n    There are a few additional wrinkles:\n\n    - Since Coq types can themselves be expressions, the checker must\n      normalize these (by using the conversion rules) before\n      comparing them.\n\n    - The checker must make sure that [match] expressions are\n      _exhaustive_.  That is, there must be an arm for every possible\n      constructor.  To see why, consider the following alleged proof\n      object:\n[[\n      Definition or_bogus : forall P Q, P \\/ Q -> P :=\n        fun (P Q : Prop) (A : P \\/ Q) =>\n           match A with\n           | or_introl H => H\n           end. \n]]\n      All the types here match correctly, but the [match] only\n      considers one of the possible constructors for [or].  Coq's\n      exhaustiveness check will reject this definition.\n\n    - The checker must make sure that each [fix] expression\n      terminates.  It does this using a syntactic check to make sure\n      that each recursive call is on a subexpression of the original\n      argument.  To see why this is essential, consider this alleged\n      proof:\n[[\n          Definition nat_false : forall (n:nat), False :=\n             fix f (n:nat) : False := f n. \n]]\n      Again, this is perfectly well-typed, but (fortunately) Coq will\n      reject it. *)\n\n(** Note that the soundness of Coq depends only on the correctness of\n    this typechecking engine, not on the tactic machinery.  If there\n    is a bug in a tactic implementation (and this certainly does\n    happen!), that tactic might construct an invalid proof term.  But\n    when you type [Qed], Coq checks the term for validity from\n    scratch.  Only lemmas whose proofs pass the type-checker can be\n    used in further proof developments.  *)\n\n\n", "meta": {"author": "Blaisorblade", "repo": "Software-Foundations", "sha": "aeb1b49fd922a346b774b330694fe6c16caf9626", "save_path": "github-repos/coq/Blaisorblade-Software-Foundations", "path": "github-repos/coq/Blaisorblade-Software-Foundations/Software-Foundations-aeb1b49fd922a346b774b330694fe6c16caf9626/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7478463438276223}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n(*                      Evgeny Makarov, INRIA, 2007                     *)\n(************************************************************************)\n\nRequire Import\n Bool Peano Peano_dec Compare_dec Plus Mult Minus Le Lt EqNat Div2 Wf_nat\n NAxioms NProperties.\n\n(** Functions not already defined *)\n\nFixpoint pow n m :=\n  match m with\n    | O => 1\n    | S m => n * (pow n m)\n  end.\n\nInfix \"^\" := pow : nat_scope.\n\nLemma pow_0_r : forall a, a^0 = 1.\nProof. reflexivity. Qed.\n\nLemma pow_succ_r : forall a b, 0<=b -> a^(S b) = a * a^b.\nProof. reflexivity. Qed.\n\nDefinition Even n := exists m, n = 2*m.\nDefinition Odd n := exists m, n = 2*m+1.\n\nFixpoint even n :=\n  match n with\n    | O => true\n    | 1 => false\n    | S (S n') => even n'\n  end.\n\nDefinition odd n := negb (even n).\n\nLemma even_spec : forall n, even n = true <-> Even n.\nProof.\n fix 1.\n  destruct n as [|[|n]]; simpl; try rewrite even_spec; split.\n  now exists 0.\n  trivial.\n  discriminate.\n  intros (m,H). destruct m. discriminate.\n   simpl in H. rewrite <- plus_n_Sm in H. discriminate.\n  intros (m,H). exists (S m). rewrite H. simpl. now rewrite plus_n_Sm.\n  intros (m,H). destruct m. discriminate. exists m.\n   simpl in H. rewrite <- plus_n_Sm in H. inversion H. reflexivity.\nQed.\n\nLemma odd_spec : forall n, odd n = true <-> Odd n.\nProof.\n unfold odd.\n fix 1.\n  destruct n as [|[|n]]; simpl; try rewrite odd_spec; split.\n  discriminate.\n  intros (m,H). rewrite <- plus_n_Sm in H; discriminate.\n  now exists 0.\n  trivial.\n  intros (m,H). exists (S m). rewrite H. simpl. now rewrite <- (plus_n_Sm m).\n  intros (m,H). destruct m. discriminate. exists m.\n   simpl in H. rewrite <- plus_n_Sm in H. inversion H. simpl.\n   now rewrite <- !plus_n_Sm, <- !plus_n_O.\nQed.\n\nLemma Even_equiv : forall n, Even n <-> Even.even n.\nProof.\n split. intros (p,->). apply Even.even_mult_l. do 3 constructor.\n intros H. destruct (even_2n n H) as (p,->).\n exists p. unfold double. simpl. now rewrite <- plus_n_O.\nQed.\n\nLemma Odd_equiv : forall n, Odd n <-> Even.odd n.\nProof.\n split. intros (p,->). rewrite <- plus_n_Sm, <- plus_n_O.\n apply Even.odd_S. apply Even.even_mult_l. do 3 constructor.\n intros H. destruct (odd_S2n n H) as (p,->).\n exists p. unfold double. simpl. now rewrite <- plus_n_Sm, <- !plus_n_O.\nQed.\n\n(* A linear, tail-recursive, division for nat.\n\n   In [divmod], [y] is the predecessor of the actual divisor,\n   and [u] is [y] minus the real remainder\n*)\n\nFixpoint divmod x y q u :=\n  match x with\n    | 0 => (q,u)\n    | S x' => match u with\n                | 0 => divmod x' y (S q) y\n                | S u' => divmod x' y q u'\n              end\n  end.\n\nDefinition div x y :=\n  match y with\n    | 0 => y\n    | S y' => fst (divmod x y' 0 y')\n  end.\n\nDefinition modulo x y :=\n  match y with\n    | 0 => y\n    | S y' => y' - snd (divmod x y' 0 y')\n  end.\n\nInfix \"/\" := div : nat_scope.\nInfix \"mod\" := modulo (at level 40, no associativity) : nat_scope.\n\nLemma divmod_spec : forall x y q u, u <= y ->\n let (q',u') := divmod x y q u in\n x + (S y)*q + (y-u) = (S y)*q' + (y-u') /\\ u' <= y.\nProof.\n induction x. simpl. intuition.\n intros y q u H. destruct u; simpl divmod.\n generalize (IHx y (S q) y (le_n y)). destruct divmod as (q',u').\n intros (EQ,LE); split; trivial.\n rewrite <- EQ, <- minus_n_O, minus_diag, <- plus_n_O.\n now rewrite !plus_Sn_m, plus_n_Sm, <- plus_assoc, mult_n_Sm.\n generalize (IHx y q u (le_Sn_le _ _ H)). destruct divmod as (q',u').\n intros (EQ,LE); split; trivial.\n rewrite <- EQ.\n rewrite !plus_Sn_m, plus_n_Sm. f_equal. now apply minus_Sn_m.\nQed.\n\nLemma div_mod : forall x y, y<>0 -> x = y*(x/y) + x mod y.\nProof.\n intros x y Hy.\n destruct y; [ now elim Hy | clear Hy ].\n unfold div, modulo.\n generalize (divmod_spec x y 0 y (le_n y)).\n destruct divmod as (q,u).\n intros (U,V).\n simpl in *.\n now rewrite <- mult_n_O, minus_diag, <- !plus_n_O in U.\nQed.\n\nLemma mod_bound_pos : forall x y, 0<=x -> 0<y -> 0 <= x mod y < y.\nProof.\n intros x y Hx Hy. split. auto with arith.\n destruct y; [ now elim Hy | clear Hy ].\n unfold modulo.\n apply le_n_S, le_minus.\nQed.\n\n(** Square root *)\n\n(** The following square root function is linear (and tail-recursive).\n  With Peano representation, we can't do better. For faster algorithm,\n  see Psqrt/Zsqrt/Nsqrt...\n\n  We search the square root of n = k + p^2 + (q - r)\n  with q = 2p and 0<=r<=q. We start with p=q=r=0, hence\n  looking for the square root of n = k. Then we progressively\n  decrease k and r. When k = S k' and r=0, it means we can use (S p)\n  as new sqrt candidate, since (S k')+p^2+2p = k'+(S p)^2.\n  When k reaches 0, we have found the biggest p^2 square contained\n  in n, hence the square root of n is p.\n*)\n\nFixpoint sqrt_iter k p q r :=\n  match k with\n    | O => p\n    | S k' => match r with\n                | O => sqrt_iter k' (S p) (S (S q)) (S (S q))\n                | S r' => sqrt_iter k' p q r'\n              end\n  end.\n\nDefinition sqrt n := sqrt_iter n 0 0 0.\n\nLemma sqrt_iter_spec : forall k p q r,\n q = p+p -> r<=q ->\n let s := sqrt_iter k p q r in\n s*s <= k + p*p + (q - r) < (S s)*(S s).\nProof.\n induction k.\n (* k = 0 *)\n simpl; intros p q r Hq Hr.\n split.\n apply le_plus_l.\n apply le_lt_n_Sm.\n rewrite <- mult_n_Sm.\n rewrite plus_assoc, (plus_comm p), <- plus_assoc.\n apply plus_le_compat; trivial.\n rewrite <- Hq. apply le_minus.\n (* k = S k' *)\n destruct r.\n (* r = 0 *)\n intros Hq _.\n replace (S k + p*p + (q-0)) with (k + (S p)*(S p) + (S (S q) - S (S q))).\n apply IHk.\n simpl. rewrite <- plus_n_Sm. congruence.\n auto with arith.\n rewrite minus_diag, <- minus_n_O, <- plus_n_O. simpl.\n rewrite <- plus_n_Sm; f_equal. rewrite <- plus_assoc; f_equal.\n rewrite <- mult_n_Sm, (plus_comm p), <- plus_assoc. congruence.\n (* r = S r' *)\n intros Hq Hr.\n replace (S k + p*p + (q-S r)) with (k + p*p + (q - r)).\n apply IHk; auto with arith.\n simpl. rewrite plus_n_Sm. f_equal. rewrite minus_Sn_m; auto.\nQed.\n\nLemma sqrt_spec : forall n,\n (sqrt n)*(sqrt n) <= n < S (sqrt n) * S (sqrt n).\nProof.\n intros.\n set (s:=sqrt n).\n replace n with (n + 0*0 + (0-0)).\n apply sqrt_iter_spec; auto.\n simpl. now rewrite <- 2 plus_n_O.\nQed.\n\n(** A linear tail-recursive base-2 logarithm\n\n  In [log2_iter], we maintain the logarithm [p] of the counter [q],\n  while [r] is the distance between [q] and the next power of 2,\n  more precisely [q + S r = 2^(S p)] and [r<2^p]. At each\n  recursive call, [q] goes up while [r] goes down. When [r]\n  is 0, we know that [q] has almost reached a power of 2,\n  and we increase [p] at the next call, while resetting [r]\n  to [q].\n\n  Graphically (numbers are [q], stars are [r]) :\n\n<<\n                    10\n                  9\n                8\n              7   *\n            6       *\n          5           ...\n        4\n      3   *\n    2       *\n  1   *       *\n0   *   *       *\n>>\n\n  We stop when [k], the global downward counter reaches 0.\n  At that moment, [q] is the number we're considering (since\n  [k+q] is invariant), and [p] its logarithm.\n*)\n\nFixpoint log2_iter k p q r :=\n  match k with\n    | O => p\n    | S k' => match r with\n                | O => log2_iter k' (S p) (S q) q\n                | S r' => log2_iter k' p (S q) r'\n              end\n  end.\n\nDefinition log2 n := log2_iter (pred n) 0 1 0.\n\nLemma log2_iter_spec : forall k p q r,\n 2^(S p) = q + S r -> r < 2^p ->\n let s := log2_iter k p q r in\n 2^s <= k + q < 2^(S s).\nProof.\n induction k.\n (* k = 0 *)\n intros p q r EQ LT. simpl log2_iter. cbv zeta.\n split.\n rewrite plus_O_n.\n apply plus_le_reg_l with (2^p).\n simpl pow in EQ. rewrite <- plus_n_O in EQ. rewrite EQ.\n rewrite plus_comm. apply plus_le_compat_r. now apply lt_le_S.\n rewrite EQ, plus_comm. apply plus_lt_compat_l. apply lt_0_Sn.\n (* k = S k' *)\n intros p q r EQ LT. destruct r.\n (* r = 0 *)\n rewrite <- plus_n_Sm, <- plus_n_O in EQ.\n rewrite plus_Sn_m, plus_n_Sm. apply IHk.\n rewrite <- EQ. remember (S p) as p'; simpl. now rewrite <- plus_n_O.\n unfold lt. now rewrite EQ.\n (* r = S r' *)\n rewrite plus_Sn_m, plus_n_Sm. apply IHk.\n now rewrite plus_Sn_m, plus_n_Sm.\n unfold lt.\n now apply lt_le_weak.\nQed.\n\nLemma log2_spec : forall n, 0<n ->\n 2^(log2 n) <= n < 2^(S (log2 n)).\nProof.\n intros.\n set (s:=log2 n).\n replace n with (pred n + 1).\n apply log2_iter_spec; auto.\n rewrite <- plus_n_Sm, <- plus_n_O.\n symmetry. now apply S_pred with 0.\nQed.\n\nLemma log2_nonpos : forall n, n<=0 -> log2 n = 0.\nProof.\n inversion 1; now subst.\nQed.\n\n(** * Gcd *)\n\n(** We use Euclid algorithm, which is normally not structural,\n    but Coq is now clever enough to accept this (behind modulo\n    there is a subtraction, which now preserves being a subterm)\n*)\n\nFixpoint gcd a b :=\n  match a with\n   | O => b\n   | S a' => gcd (b mod (S a')) (S a')\n  end.\n\nDefinition divide x y := exists z, x*z=y.\nNotation \"( x | y )\" := (divide x y) (at level 0) : nat_scope.\n\nLemma gcd_divide : forall a b, (gcd a b | a) /\\ (gcd a b | b).\nProof.\n fix 1.\n intros [|a] b; simpl.\n split.\n  exists 0; now rewrite <- mult_n_O.\n  exists 1; now rewrite <- mult_n_Sm, <- mult_n_O.\n fold (b mod (S a)).\n destruct (gcd_divide (b mod (S a)) (S a)) as (H,H').\n set (a':=S a) in *.\n split; auto.\n rewrite (div_mod b a') at 2 by discriminate.\n destruct H as (u,Hu), H' as (v,Hv).\n exists ((b/a')*v + u).\n rewrite mult_plus_distr_l.\n now rewrite (mult_comm _ v), mult_assoc, Hv, Hu.\nQed.\n\nLemma gcd_divide_l : forall a b, (gcd a b | a).\nProof.\n intros. apply gcd_divide.\nQed.\n\nLemma gcd_divide_r : forall a b, (gcd a b | b).\nProof.\n intros. apply gcd_divide.\nQed.\n\nLemma gcd_greatest : forall a b c, (c|a) -> (c|b) -> (c|gcd a b).\nProof.\n fix 1.\n intros [|a] b; simpl; auto.\n fold (b mod (S a)).\n intros c H H'. apply gcd_greatest; auto.\n set (a':=S a) in *.\n rewrite (div_mod b a') in H' by discriminate.\n destruct H as (u,Hu), H' as (v,Hv).\n exists (v - u * (b/a')).\n now rewrite mult_minus_distr_l, mult_assoc, Hu, Hv, minus_plus.\nQed.\n\n(** * Bitwise operations *)\n\n(** We provide here some bitwise operations for unary numbers.\n  Some might be really naive, they are just there for fullfiling\n  the same interface as other for natural representations. As\n  soon as binary representations such as NArith are available,\n  it is clearly better to convert to/from them and use their ops.\n*)\n\nFixpoint testbit a n :=\n match n with\n   | O => odd a\n   | S n => testbit (div2 a) n\n end.\n\nDefinition shiftl a n := iter_nat n _ double a.\nDefinition shiftr a n := iter_nat n _ div2 a.\n\nFixpoint bitwise (op:bool->bool->bool) n a b :=\n match n with\n  | O => O\n  | S n' =>\n    (if op (odd a) (odd b) then 1 else 0) +\n    2*(bitwise op n' (div2 a) (div2 b))\n end.\n\nDefinition land a b := bitwise andb a a b.\nDefinition lor a b := bitwise orb (max a b) a b.\nDefinition ldiff a b := bitwise (fun b b' => b && negb b') a a b.\nDefinition lxor a b := bitwise xorb (max a b) a b.\n\nLemma double_twice : forall n, double n = 2*n.\nProof.\n simpl; intros. now rewrite <- plus_n_O.\nQed.\n\nLemma testbit_0_l : forall n, testbit 0 n = false.\nProof.\n now induction n.\nQed.\n\nLemma testbit_odd_0 a : testbit (2*a+1) 0 = true.\nProof.\n unfold testbit. rewrite odd_spec. now exists a.\nQed.\n\nLemma testbit_even_0 a : testbit (2*a) 0 = false.\nProof.\n unfold testbit, odd. rewrite (proj2 (even_spec _)); trivial.\n now exists a.\nQed.\n\nLemma testbit_odd_succ a n : testbit (2*a+1) (S n) = testbit a n.\nProof.\n unfold testbit; fold testbit.\n rewrite <- plus_n_Sm, <- plus_n_O. f_equal.\n apply div2_double_plus_one.\nQed.\n\nLemma testbit_even_succ a n : testbit (2*a) (S n) = testbit a n.\nProof.\n unfold testbit; fold testbit. f_equal. apply div2_double.\nQed.\n\nLemma shiftr_spec : forall a n m,\n testbit (shiftr a n) m = testbit a (m+n).\nProof.\n induction n; intros m. trivial.\n now rewrite <- plus_n_O.\n now rewrite <- plus_n_Sm, <- plus_Sn_m, <- IHn.\nQed.\n\nLemma shiftl_spec_high : forall a n m, n<=m ->\n testbit (shiftl a n) m = testbit a (m-n).\nProof.\n induction n; intros m H. trivial.\n now rewrite <- minus_n_O.\n destruct m. inversion H.\n simpl. apply le_S_n in H.\n change (shiftl a (S n)) with (double (shiftl a n)).\n rewrite double_twice, div2_double. now apply IHn.\nQed.\n\nLemma shiftl_spec_low : forall a n m, m<n ->\n testbit (shiftl a n) m = false.\nProof.\n induction n; intros m H. inversion H.\n change (shiftl a (S n)) with (double (shiftl a n)).\n destruct m; simpl.\n unfold odd. apply negb_false_iff.\n apply even_spec. exists (shiftl a n). apply double_twice.\n rewrite double_twice, div2_double. apply IHn.\n now apply lt_S_n.\nQed.\n\nLemma div2_bitwise : forall op n a b,\n div2 (bitwise op (S n) a b) = bitwise op n (div2 a) (div2 b).\nProof.\n intros. unfold bitwise; fold bitwise.\n destruct (op (odd a) (odd b)).\n now rewrite div2_double_plus_one.\n now rewrite plus_O_n, div2_double.\nQed.\n\nLemma odd_bitwise : forall op n a b,\n odd (bitwise op (S n) a b) = op (odd a) (odd b).\nProof.\n intros. unfold bitwise; fold bitwise.\n destruct (op (odd a) (odd b)).\n apply odd_spec. rewrite plus_comm. eexists; eauto.\n unfold odd. apply negb_false_iff. apply even_spec.\n rewrite plus_O_n; eexists; eauto.\nQed.\n\nLemma div2_decr : forall a n, a <= S n -> div2 a <= n.\nProof.\n destruct a; intros. apply le_0_n.\n apply le_trans with a.\n apply lt_n_Sm_le, lt_div2, lt_0_Sn. now apply le_S_n.\nQed.\n\nLemma testbit_bitwise_1 : forall op, (forall b, op false b = false) ->\n forall n m a b, a<=n ->\n testbit (bitwise op n a b) m = op (testbit a m) (testbit b m).\nProof.\n intros op Hop.\n induction n; intros m a b Ha.\n simpl. inversion Ha; subst. now rewrite testbit_0_l.\n destruct m.\n apply odd_bitwise.\n unfold testbit; fold testbit. rewrite div2_bitwise.\n apply IHn; now apply div2_decr.\nQed.\n\nLemma testbit_bitwise_2 : forall op, op false false = false ->\n forall n m a b, a<=n -> b<=n ->\n testbit (bitwise op n a b) m = op (testbit a m) (testbit b m).\nProof.\n intros op Hop.\n induction n; intros m a b Ha Hb.\n simpl. inversion Ha; inversion Hb; subst. now rewrite testbit_0_l.\n destruct m.\n apply odd_bitwise.\n unfold testbit; fold testbit. rewrite div2_bitwise.\n apply IHn; now apply div2_decr.\nQed.\n\nLemma land_spec : forall a b n,\n testbit (land a b) n = testbit a n && testbit b n.\nProof.\n intros. unfold land. apply testbit_bitwise_1; trivial.\nQed.\n\nLemma ldiff_spec : forall a b n,\n testbit (ldiff a b) n = testbit a n && negb (testbit b n).\nProof.\n intros. unfold ldiff. apply testbit_bitwise_1; trivial.\nQed.\n\nLemma lor_spec : forall a b n,\n testbit (lor a b) n = testbit a n || testbit b n.\nProof.\n intros. unfold lor. apply testbit_bitwise_2. trivial.\n destruct (le_ge_dec a b). now rewrite max_r. now rewrite max_l.\n destruct (le_ge_dec a b). now rewrite max_r. now rewrite max_l.\nQed.\n\nLemma lxor_spec : forall a b n,\n testbit (lxor a b) n = xorb (testbit a n) (testbit b n).\nProof.\n intros. unfold lxor. apply testbit_bitwise_2. trivial.\n destruct (le_ge_dec a b). now rewrite max_r. now rewrite max_l.\n destruct (le_ge_dec a b). now rewrite max_r. now rewrite max_l.\nQed.\n\n(** * Implementation of [NAxiomsSig] by [nat] *)\n\nModule Nat\n <: NAxiomsSig <: UsualDecidableTypeFull <: OrderedTypeFull <: TotalOrder.\n\n(** Bi-directional induction. *)\n\nTheorem bi_induction :\n  forall A : nat -> Prop, Proper (eq==>iff) A ->\n    A 0 -> (forall n : nat, A n <-> A (S n)) -> forall n : nat, A n.\nProof.\nintros A A_wd A0 AS. apply nat_ind. assumption. intros; now apply -> AS.\nQed.\n\n(** Basic operations. *)\n\nDefinition eq_equiv : Equivalence (@eq nat) := eq_equivalence.\nLocal Obligation Tactic := simpl_relation.\nProgram Instance succ_wd : Proper (eq==>eq) S.\nProgram Instance pred_wd : Proper (eq==>eq) pred.\nProgram Instance add_wd : Proper (eq==>eq==>eq) plus.\nProgram Instance sub_wd : Proper (eq==>eq==>eq) minus.\nProgram Instance mul_wd : Proper (eq==>eq==>eq) mult.\n\nTheorem pred_succ : forall n : nat, pred (S n) = n.\nProof.\nreflexivity.\nQed.\n\nTheorem one_succ : 1 = S 0.\nProof.\nreflexivity.\nQed.\n\nTheorem two_succ : 2 = S 1.\nProof.\nreflexivity.\nQed.\n\nTheorem add_0_l : forall n : nat, 0 + n = n.\nProof.\nreflexivity.\nQed.\n\nTheorem add_succ_l : forall n m : nat, (S n) + m = S (n + m).\nProof.\nreflexivity.\nQed.\n\nTheorem sub_0_r : forall n : nat, n - 0 = n.\nProof.\nintro n; now destruct n.\nQed.\n\nTheorem sub_succ_r : forall n m : nat, n - (S m) = pred (n - m).\nProof.\ninduction n; destruct m; simpl; auto. apply sub_0_r.\nQed.\n\nTheorem mul_0_l : forall n : nat, 0 * n = 0.\nProof.\nreflexivity.\nQed.\n\nTheorem mul_succ_l : forall n m : nat, S n * m = n * m + m.\nProof.\nassert (add_S_r : forall n m, n+S m = S(n+m)) by (induction n; auto).\nassert (add_comm : forall n m, n+m = m+n).\n induction n; simpl; auto. intros; rewrite add_S_r; auto.\nintros n m; now rewrite add_comm.\nQed.\n\n(** Order on natural numbers *)\n\nProgram Instance lt_wd : Proper (eq==>eq==>iff) lt.\n\nTheorem lt_succ_r : forall n m : nat, n < S m <-> n <= m.\nProof.\nunfold lt; split. apply le_S_n. induction 1; auto.\nQed.\n\n\nTheorem lt_eq_cases : forall n m : nat, n <= m <-> n < m \\/ n = m.\nProof.\nsplit.\ninversion 1; auto. rewrite lt_succ_r; auto.\ndestruct 1; [|subst; auto]. rewrite <- lt_succ_r; auto.\nQed.\n\nTheorem lt_irrefl : forall n : nat, ~ (n < n).\nProof.\ninduction n. intro H; inversion H. rewrite lt_succ_r; auto.\nQed.\n\n(** Facts specific to natural numbers, not integers. *)\n\nTheorem pred_0 : pred 0 = 0.\nProof.\nreflexivity.\nQed.\n\n(** Recursion fonction *)\n\nDefinition recursion {A} : A -> (nat -> A -> A) -> nat -> A :=\n  nat_rect (fun _ => A).\n\nInstance recursion_wd {A} (Aeq : relation A) :\n Proper (Aeq ==> (eq==>Aeq==>Aeq) ==> eq ==> Aeq) recursion.\nProof.\nintros a a' Ha f f' Hf n n' Hn. subst n'.\ninduction n; simpl; auto. apply Hf; auto.\nQed.\n\nTheorem recursion_0 :\n  forall {A} (a : A) (f : nat -> A -> A), recursion a f 0 = a.\nProof.\nreflexivity.\nQed.\n\nTheorem recursion_succ :\n  forall {A} (Aeq : relation A) (a : A) (f : nat -> A -> A),\n    Aeq a a -> Proper (eq==>Aeq==>Aeq) f ->\n      forall n : nat, Aeq (recursion a f (S n)) (f n (recursion a f n)).\nProof.\nunfold Proper, respectful in *; induction n; simpl; auto.\nQed.\n\n(** The instantiation of operations.\n    Placing them at the very end avoids having indirections in above lemmas. *)\n\nDefinition t := nat.\nDefinition eq := @eq nat.\nDefinition eqb := beq_nat.\nDefinition compare := nat_compare.\nDefinition zero := 0.\nDefinition one := 1.\nDefinition two := 2.\nDefinition succ := S.\nDefinition pred := pred.\nDefinition add := plus.\nDefinition sub := minus.\nDefinition mul := mult.\nDefinition lt := lt.\nDefinition le := le.\n\nDefinition min := min.\nDefinition max := max.\nDefinition max_l := max_l.\nDefinition max_r := max_r.\nDefinition min_l := min_l.\nDefinition min_r := min_r.\n\nDefinition eqb_eq := beq_nat_true_iff.\nDefinition compare_spec := nat_compare_spec.\nDefinition eq_dec := eq_nat_dec.\n\nDefinition Even := Even.\nDefinition Odd := Odd.\nDefinition even := even.\nDefinition odd := odd.\nDefinition even_spec := even_spec.\nDefinition odd_spec := odd_spec.\n\nProgram Instance pow_wd : Proper (eq==>eq==>eq) pow.\nDefinition pow_0_r := pow_0_r.\nDefinition pow_succ_r := pow_succ_r.\nLemma pow_neg_r : forall a b, b<0 -> a^b = 0. inversion 1. Qed.\nDefinition pow := pow.\n\nDefinition log2_spec := log2_spec.\nDefinition log2_nonpos := log2_nonpos.\nDefinition log2 := log2.\n\nDefinition sqrt_spec a (Ha:0<=a) := sqrt_spec a.\nLemma sqrt_neg : forall a, a<0 -> sqrt a = 0. inversion 1. Qed.\nDefinition sqrt := sqrt.\n\nDefinition div := div.\nDefinition modulo := modulo.\nProgram Instance div_wd : Proper (eq==>eq==>eq) div.\nProgram Instance mod_wd : Proper (eq==>eq==>eq) modulo.\nDefinition div_mod := div_mod.\nDefinition mod_bound_pos := mod_bound_pos.\n\nDefinition divide := divide.\nDefinition gcd := gcd.\nDefinition gcd_divide_l := gcd_divide_l.\nDefinition gcd_divide_r := gcd_divide_r.\nDefinition gcd_greatest := gcd_greatest.\nLemma gcd_nonneg : forall a b, 0<=gcd a b.\nProof. intros. apply le_O_n. Qed.\n\nDefinition testbit := testbit.\nDefinition shiftl := shiftl.\nDefinition shiftr := shiftr.\nDefinition lxor := lxor.\nDefinition land := land.\nDefinition lor := lor.\nDefinition ldiff := ldiff.\nDefinition div2 := div2.\n\nProgram Instance testbit_wd : Proper (eq==>eq==>Logic.eq) testbit.\nDefinition testbit_odd_0 := testbit_odd_0.\nDefinition testbit_even_0 := testbit_even_0.\nDefinition testbit_odd_succ a n (_:0<=n) := testbit_odd_succ a n.\nDefinition testbit_even_succ a n (_:0<=n) := testbit_even_succ a n.\nLemma testbit_neg_r a n (H:n<0) : testbit a n = false.\nProof. inversion H. Qed.\nDefinition shiftl_spec_low := shiftl_spec_low.\nDefinition shiftl_spec_high a n m (_:0<=m) := shiftl_spec_high a n m.\nDefinition shiftr_spec a n m (_:0<=m) := shiftr_spec a n m.\nDefinition lxor_spec := lxor_spec.\nDefinition land_spec := land_spec.\nDefinition lor_spec := lor_spec.\nDefinition ldiff_spec := ldiff_spec.\nDefinition div2_spec a : div2 a = shiftr a 1 := eq_refl _.\n\n(** Generic Properties *)\n\nInclude NProp\n <+ UsualMinMaxLogicalProperties <+ UsualMinMaxDecProperties.\n\nEnd Nat.\n\n(** [Nat] contains an [order] tactic for natural numbers *)\n\n(** Note that [Nat.order] is domain-agnostic: it will not prove\n    [1<=2] or [x<=x+x], but rather things like [x<=y -> y<=x -> x=y]. *)\n\nSection TestOrder.\n Let test : forall x y, x<=y -> y<=x -> x=y.\n Proof.\n Nat.order.\n Qed.\nEnd TestOrder.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/Natural/Peano/NPeano.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.747845690483035}}
{"text": "Add LoadPath \"$COQ_PROOFS\" as Path.\nLoad unit_3_001_structured_data.\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  rewrite eq2.\n  reflexivity.\nQed.\n\nTheorem silly1' : forall (n m o p : nat),\n     n = m ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  apply eq2.\nQed.\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2. \n  apply eq2. apply eq1. Qed.\n\nDefinition oddb (X: nat) := negb (evenb X).\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. apply H0.\nQed.\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5 ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl.\n  apply H.\nQed.\n\n(*Theorem 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 X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl. simpl. reflexivity.\nQed.\n*)\n\n(*\nTo sum up, one can say apply H when H is a \nhypothesis in the context or a previously \nproven lemma of the form \n∀x1 ..., H1 → H2 → ... → Hn and the current \ngoal is shape Hn (for some instantatiation of \neach of the xi). After running apply H in such\n a state, you will have a subgoal for each of \nH1 through Hn-1. In the special case where H \nisn't an implication, your proof will be \ncompleted.\n*)\n\nTheorem rev_exercise1 : forall (l l' : natlist),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros.\n  symmetry.\n  apply rev_injective.\n  rewrite rev_involutive.\n  apply H.\nQed.\n\nTheorem rev_exercise1' : forall (l l' : natlist),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  assert (forall l: natlist, rev (rev l) = l).\n  {\n    intros.\n    induction l.\n    - reflexivity.\n    - simpl. rewrite <- rev_involutive. simpl. reflexivity.\n  }\n  intros.\n  induction l'.\n  - rewrite H0. simpl. reflexivity.\n  - rewrite H0. rewrite H. reflexivity.\nQed.\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity. Qed.\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. \n  rewrite -> eq1.\n  rewrite -> eq2.\n  reflexivity. Qed.\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.\nQed.\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\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros.\n  apply trans_eq with (m:=(minustwo o)).\n  rewrite H0. apply H.\n  reflexivity.\nQed.\n\n(* Inductive definitions have two major properties:\n  - The constructor S is injective. That is, if S n = S m, it must be the case that n = m.\n  - The constructors O and S are disjoint. That is, O is not equal to S n for any n.\n*)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity.\nQed.\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. inversion H as [Hnm]. reflexivity. Qed.\n\nExample inversion_ex3 : forall (x y z : nat) (l j : natlist),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  inversion H2.\n  reflexivity.\nQed.\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros.\n  destruct n.\n  - reflexivity.\n  - inversion H.\n  Qed.\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nExample inversion_ex6 : forall\n                          (x y z : nat) (l j : natlist),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  intros.\n  inversion H.\nQed.\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq. reflexivity. Qed.\n\nTheorem f_equal2 : forall (A1 A2 B:Type) (f:A1 -> A2 -> B)\n                          (x1 y1:A1) (x2 y2:A2),\n    x1 = y1 -> x2 = y2 -> f x1 x2 = f y1 y2.\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  reflexivity.\nQed.\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b ->\n     beq_nat n m = b.\nProof.\n  intros n m b H. simpl in H. apply H. Qed.\n\n(*\nIn other words, apply L in H gives us a form of \"forward reasoning\": from L1 → L2 and a hypothesis matching L1, it produces a hypothesis matching L2. By contrast, apply L is \"backward reasoning\": it says that if we know L1→L2 and we are trying to prove L2, it suffices to prove L1.\n*)\n\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  symmetry in H. apply eq in H. symmetry in H.\n  apply H. Qed.\n\nTheorem plus_equal' : forall \n                          (n m: nat) (n m: nat),\n    n = m -> m + m = n + n.\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  reflexivity.\nQed.\n\nTheorem plus_equal'' : forall \n                          (n m: nat),\n    S n = m -> m + m = S n + S n.\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  reflexivity.\nQed.\n\nModule test.\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.\nEnd test.\n\n\n(*\nNOTE: Binding variables too soon can get you stuck!\n\nTheorem plus_n_n_injective_stuck : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros.\n  induction n as [| n' IHn'].\n  - inversion H. destruct m. reflexivity. inversion H1.\n  - destruct m.\n    + intros. inversion H.\n    + intros. \n      simpl in H. \n      rewrite <- plus_n_Sm in H.\n      rewrite <- plus_n_Sm in H.\n      inversion H.\n      apply IHn' in H1.\nQed.\n*)\n\n\n(* Big thanks to http://www.edwardzcn98yx.com/post/ec8fb64d.html) *)\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  (* Hint: use [plus_n_Sm] *)\n  intros n.\n  induction n as [| n' IHn'].\n  - intros. destruct m as [| m'].\n    + reflexivity.\n    + simpl in H. inversion H.\n  - induction  m as [| m'].\n    + intros. inversion H.\n    + intros. simpl in H.\n      Check plus_n_Sm.\n      Search (S ( _ + _ ) ).\n      rewrite <- plus_n_Sm in H.\n      rewrite <- plus_n_Sm in H.\n      (* Use injection property *)\n      injection H as IHinj.\n      (* Now we can apply IHn' in IHinj with specific m ( that is m') *)\n      apply IHn' in IHinj.\n      Search ( ?a = ?b -> S ?a = S ?b).\n      (* As a backward reasoning, we could rewrite the goal with IHinj and  *)\n      rewrite IHinj.\n      reflexivity.\n      (* As a forward reasoning, I search the existing therom and make S n' = S m' *)\n      (* apply eq_S in IHinj. *)\n      (* apply IHinj. *)\nQed.\n\nSearch (_ + _ = _ + _).\n\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n.\n  induction n.\n  - intros. destruct m. reflexivity. inversion H.\n  - intros. destruct m. inversion H. apply IHn in H. rewrite H. reflexivity.\nQed.\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_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n.\n  induction n.\n  - intros. induction m. \n    + reflexivity.\n    + inversion H.\n  - intros. induction m.\n    + inversion H.\n    + Search (f_equal). (* n = S n' *) apply f_equal.\n      apply IHn. inversion H. reflexivity. Qed.\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* n and m are both in the context *)\n  generalize dependent n.\n  (* Now n is back in the goal and we can do induction on\n     m and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    \n    + Search (f_equal). (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. \nQed.\n\nTheorem nth_error_after_last: forall (n : nat) (l : natlist),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros n.\n  induction n.\n  - destruct l. \n    + simpl. reflexivity.\n    + intros. inversion H.\n  - destruct l.\n    + simpl. reflexivity.\n    + intros. inversion H. simpl. rewrite H1. rewrite IHn. reflexivity. apply H1.\nQed.\n\nDefinition square n := n * n.\n\n(* \nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  unfold square.\n  Search (_ * _).\n*)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity. Qed.\n\n(* Fixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x, y) :: t =>\n      match split t with\n      | (lx, ly) => (x :: lx, y :: ly)\n      end\n  end. *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        eqn: again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq. Qed.\n\nTheorem bool_fn_applied_thrice' :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros.\n  destruct (f true) eqn:FT.\n  - destruct (f false) eqn:FF.\n    + destruct b.\n      * rewrite FT. rewrite FT. rewrite FT. reflexivity.\n      * rewrite FF. rewrite FT. rewrite FT. reflexivity.\n    + destruct b.\n      * rewrite FT. rewrite FT. rewrite FT. reflexivity.\n      * rewrite FF. rewrite FF. rewrite FF. reflexivity.\n  - destruct (f false) eqn:FF.\n    + destruct b.\n      * rewrite FT. rewrite FF. rewrite FT. reflexivity.\n      * rewrite FF. rewrite FT. rewrite FF. reflexivity.\n    + destruct b.\n      * rewrite FT. rewrite FF. rewrite FF. reflexivity.\n      * rewrite FF. rewrite FF. rewrite FF. reflexivity.\nQed.\n\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros.\n  destruct (f true) eqn: fb.\n  * destruct (f false) eqn: fb'.\n    - destruct b.\n      + rewrite fb. rewrite fb. rewrite fb. reflexivity.\n      + rewrite fb'. rewrite fb. rewrite fb. reflexivity.\n    - destruct b.\n      + rewrite fb. rewrite fb. rewrite fb. reflexivity.\n      + rewrite fb'. rewrite fb'. rewrite fb'. reflexivity.\n  * destruct (f false) eqn: fb'.  \n    - destruct b.\n      + rewrite fb. rewrite fb'. rewrite fb. reflexivity.\n      + rewrite fb'. rewrite fb. rewrite fb'. reflexivity.\n    - destruct b.\n      + rewrite fb. rewrite fb'. rewrite fb'. reflexivity.\n      + rewrite fb'. rewrite fb'. rewrite fb'. reflexivity. \nQed.\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_5_tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8757869981319862, "lm_q1q2_score": 0.7478456865741935}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nInductive binop : Set := Plus | Times.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp.\n\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n  match b with\n    | Plus => plus\n    | Times => mult\n  end.\n\nFixpoint expDenote (e : exp) : nat :=\n  match e with\n    | Const n => n\n    | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n  end.\n\nEval simpl in expDenote (Const 42).\n\nEval simpl in expDenote (Binop Plus (Const 2) (Const 3)).\n\nEval simpl in expDenote (Binop Times (Binop Times (Const 10) (Const 20)) (Const 30)).\n", "meta": {"author": "guojing0", "repo": "cert-prog-with-dep-types", "sha": "5e709830951e313890aa2638d7d1d7229685f264", "save_path": "github-repos/coq/guojing0-cert-prog-with-dep-types", "path": "github-repos/coq/guojing0-cert-prog-with-dep-types/cert-prog-with-dep-types-5e709830951e313890aa2638d7d1d7229685f264/stack-machine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7478149283884777}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2018   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire real.Real.\n\nRequire Import Rbasic_fun.\n\n(* Why3 comment *)\n(* min is replaced with (Reals.Rbasic_fun.Rmin x x1) by the coq driver *)\n\n(* Why3 goal *)\nLemma min_def :\nforall (x:R) (y:R),\n ((x <= y)%R -> ((Reals.Rbasic_fun.Rmin x y) = x))\n /\\ ((~ (x <= y)%R) -> ((Reals.Rbasic_fun.Rmin x y) = y)).\nProof.\nintros x y.\nsplit ; intros H.\nnow apply Rmin_left.\napply Rmin_right.\nnow apply Rlt_le, Rnot_le_lt.\nQed.\n\n(* Why3 comment *)\n(* max is replaced with (Reals.Rbasic_fun.Rmax x x1) by the coq driver *)\n\n(* Why3 goal *)\nLemma max_def :\nforall (x:R) (y:R),\n ((x <= y)%R -> ((Reals.Rbasic_fun.Rmax x y) = y))\n /\\ ((~ (x <= y)%R) -> ((Reals.Rbasic_fun.Rmax x y) = x)).\nProof.\nintros x y.\nsplit ; intros H.\nnow apply Rmax_right.\napply Rmax_left.\nnow apply Rlt_le, Rnot_le_lt.\nQed.\n\n(* Why3 goal *)\nLemma Min_r :\nforall (x:R) (y:R), (y <= x)%R -> ((Reals.Rbasic_fun.Rmin x y) = y).\nexact Rmin_right.\nQed.\n\n(* Why3 goal *)\nLemma Max_l :\nforall (x:R) (y:R), (y <= x)%R -> ((Reals.Rbasic_fun.Rmax x y) = x).\nexact Rmax_left.\nQed.\n\n(* Why3 goal *)\nLemma Min_comm :\nforall (x:R) (y:R),\n ((Reals.Rbasic_fun.Rmin x y) = (Reals.Rbasic_fun.Rmin y x)).\nexact Rmin_comm.\nQed.\n\n(* Why3 goal *)\nLemma Max_comm :\nforall (x:R) (y:R),\n ((Reals.Rbasic_fun.Rmax x y) = (Reals.Rbasic_fun.Rmax y x)).\nexact Rmax_comm.\nQed.\n\n(* Why3 goal *)\nLemma Min_assoc :\nforall (x:R) (y:R) (z:R),\n ((Reals.Rbasic_fun.Rmin (Reals.Rbasic_fun.Rmin x y) z) = (Reals.Rbasic_fun.Rmin x (Reals.Rbasic_fun.Rmin y z))).\nProof.\nintros x y z.\ndestruct (Rle_or_lt x y) as [Hxy|Hxy].\nrewrite Rmin_left with (1 := Hxy).\ndestruct (Rle_or_lt x z) as [Hxz|Hxz].\nrewrite Rmin_left with (1 := Hxz).\napply eq_sym, Rmin_left.\nnow apply Rmin_case.\nrewrite (Rmin_right y z).\nreflexivity.\napply Rlt_le.\nnow apply Rlt_le_trans with x.\nrewrite (Rmin_right x y) by now apply Rlt_le.\napply eq_sym, Rmin_right.\napply Rlt_le.\napply Rle_lt_trans with (2 := Hxy).\napply Rmin_l.\nQed.\n\n(* Why3 goal *)\nLemma Max_assoc :\nforall (x:R) (y:R) (z:R),\n ((Reals.Rbasic_fun.Rmax (Reals.Rbasic_fun.Rmax x y) z) = (Reals.Rbasic_fun.Rmax x (Reals.Rbasic_fun.Rmax y z))).\nProof.\nintros x y z.\ndestruct (Rle_or_lt x y) as [Hxy|Hxy].\nrewrite Rmax_right with (1 := Hxy).\napply eq_sym, Rmax_right.\napply Rle_trans with (1 := Hxy).\napply Rmax_l.\nrewrite (Rmax_left x y) by now apply Rlt_le.\ndestruct (Rle_or_lt x z) as [Hxz|Hxz].\nrewrite Rmax_right with (1 := Hxz).\nrewrite Rmax_right.\napply eq_sym, Rmax_right.\napply Rlt_le.\nnow apply Rlt_le_trans with x.\napply Rle_trans with (1 := Hxz).\napply Rmax_r.\nrewrite Rmax_left.\napply eq_sym, Rmax_left.\napply Rmax_case ; now apply Rlt_le.\nnow apply Rlt_le.\nQed.\n\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/real/MinMax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7478149226434672}}
{"text": "Theorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P.\n  unfold not.\n  intros H1.\n  destruct H1 as [H_left H_right].\n  apply H_right in H_left.\n  apply H_left.\nQed.", "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/Chapter6/not_both_true_and_false.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7476526200631008}}
{"text": "Require Import FormalMath.Algebra.Group.\nRequire Import Coq.Lists.SetoidList.\nRequire Import Coq.Lists.SetoidPermutation.\n\nSection FINITE_GROUP.\n\n  Context `{G: Group A}.\n\n  Lemma finite_group_left_perm: forall l,\n      (forall a: A, InA Ae a l) -> NoDupA Ae l ->\n      forall x, PermutationA Ae l (map (x &) l).\n  Proof.\n    intros. pose proof gr_as_setoid. apply NoDupA_equivlistA_PermutationA; auto.\n    - clear H. induction H0; simpl. 1: easy. constructor; auto.\n      intro. rewrite InA_alt in H2. destruct H2 as [y [? ?]]. rewrite in_map_iff in H3.\n      destruct H3 as [x1 [? ?]]. rewrite <- H3 in H2.\n      assert (x & x0 = x & x1) by easy. rewrite <- eq_left in H5.\n      rewrite H5 in H. apply H. apply In_InA; auto.\n    - intro y. split; intro. 2: apply H. specialize (H (neg x & y)).\n      rewrite InA_alt in H |- *. destruct H as [z [? ?]]. exists (x & z). split.\n      * rewrite <- H. rewrite <- op_assoc.\n        autorewrite with group; [easy | apply G..].\n      * now apply in_map.\n  Qed.\n\nEnd FINITE_GROUP.\n", "meta": {"author": "txyyss", "repo": "FormalMath", "sha": "35d2593efbc346433fe586b8f8dbaede046df6dc", "save_path": "github-repos/coq/txyyss-FormalMath", "path": "github-repos/coq/txyyss-FormalMath/FormalMath-35d2593efbc346433fe586b8f8dbaede046df6dc/Algebra/FiniteGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7476479935720367}}
{"text": "Require Import List.\nRequire Import EquivDec.\nModule Type Remove_Correctness.\n\n   Parameter remove : forall (X : Type) {eq : EqDec X eq} , list X -> X -> list X.\n\n   Arguments remove [X] _ _ _ .\n\n   Axiom remove_exclusion : forall (X : Type) {eq : EqDec X eq} (x : X) (l : list X), ~ In x (remove eq l x).\n\n   Axiom remove_subset : forall (X : Type) {eq : EqDec X eq} (x : X) (y : X) (l : list X), x =/= y -> In x l <-> In x (remove eq l y).\nEnd Remove_Correctness.\n\nModule Type Remove_Spec.\n\n  Parameter remove : forall (X : Type) {eq : EqDec X eq}, list X -> X -> list X.\n\n  Arguments remove [X] _ _ _.\n\n  Axiom remove_nil : forall (X : Type) {eq : EqDec X eq} (x : X), remove eq nil x = nil.\n\n  Axiom remove_exclude : forall (X : Type) {eq : EqDec X eq} (x : X) (xs : list X), remove eq (x :: xs) x = remove eq xs x.\n\n  Axiom remove_keep : forall (X : Type) {eq : EqDec X eq} (x y : X) (xs : list X), x =/= y -> remove eq (x :: xs) y = x :: (remove eq xs y).\n\nEnd Remove_Spec.\n\nModule Remove_Correct (P : Remove_Spec) : Remove_Correctness.\n\n  Theorem remove_exclusion : forall (X : Type) {eq : EqDec X eq} (x : X) (l : list X), ~ In x (P.remove eq l x).\n    intros.\n    unfold not. (* ~ aka not defined as P -> False *)\n    intros.\n    (* Proof goal is to show that x being in the result of remove leads to contradiction *)\n    induction l as [| y ys].\n    (* Base Case *)\n    rewrite P.remove_nil in H.\n    simpl in H.\n    assumption.\n    (* Inductive Case *)\n    destruct (eq x y) eqn:H1.\n    (* x == y *)\n    rewrite <- e in H.\n    rewrite P.remove_exclude in H.\n    apply IHys in H.\n    assumption.\n    (* x =/= y *)\n    apply IHys.\n    assert (P.remove eq (y :: ys) x = y :: (P.remove eq ys x)) as H2.\n    apply P.remove_keep.\n    assert (y =/= x) as H3.\n    symmetry.\n    assumption.\n    assumption.\n    rewrite H2 in H.\n    simpl in H.\n    destruct H.\n    (* Case y = x *)\n    assert (x === y) as H4.\n    rewrite H.\n    reflexivity.\n    contradiction.\n    (* Case In x (P.remove eq ys x) *)\n    assumption.\n  Qed.\n    \n   Theorem remove_subset : forall (X : Type) {eq : EqDec X eq} (x : X) (y : X) (l : list X), x =/= y -> In x l <-> In x (P.remove eq l y).\n     intros.\n     split.\n     (* -> *)\n     intros.\n     induction l as [| z zs].\n     (* Base Case *)\n     rewrite P.remove_nil.\n     assumption.\n     (* Inductive Case *)\n     destruct (eq y z) eqn:H1.\n     (* y == z *)\n     assert (P.remove eq (z :: zs) y = P.remove eq zs y) as H2.\n     rewrite e.\n     apply P.remove_exclude.\n     rewrite H2.\n     apply IHzs.\n     destruct H0.\n     (* z = x *)\n     assert (x === y) as H3.\n     assert (z === y) as H4.\n     symmetry.\n     assumption.\n     rewrite -> H0 in H4. \n     assumption.\n     contradiction.\n     (* In x zs *)\n     assumption.\n     (* y =/= z *)\n     assert (P.remove eq (z :: zs) y = z :: (P.remove eq zs y)) as H2.\n     apply P.remove_keep.\n     symmetry.\n     assumption.\n     rewrite H2.\n     simpl.\n     simpl in H0.\n     destruct H0.\n     left.\n     assumption.\n     right.\n     apply IHzs.\n     assumption.\n     (* <- *)\n     intros.     \n     induction l as [| z zs].\n     rewrite P.remove_nil in H0.\n     assumption.\n     simpl.\n     destruct (eq y z) eqn:H1.\n     right.\n     apply IHzs.\n     assert (P.remove eq (z :: zs) y = P.remove eq zs y) as H2.\n     rewrite e.\n     apply P.remove_exclude.\n     rewrite H2 in H0.\n     assumption.\n     assert (P.remove eq (z :: zs) y = z :: (P.remove eq zs y)) as H2.\n     apply P.remove_keep.\n     symmetry.\n     assumption.\n     rewrite H2 in H0.\n     simpl in H0.\n     destruct H0.\n     left.\n     assumption.\n     right.\n     apply IHzs.\n     assumption.\n   Qed.\n\n   Definition remove := P.remove.\n\nEnd Remove_Correct.\n\n \nModule Remove_IMPL : Remove_Spec.\n\n  Fixpoint remove {X : Type } {eq : EqDec X eq} (l : list X) (x : X) : list X :=\n    match l with\n      | nil => nil\n      | y :: ys => if eq x y then remove ys x else y :: (remove ys x)\n    end.\n\n  Theorem remove_nil : forall (X : Type) {eq : EqDec X eq} (x : X), remove nil x = nil.\n  Proof.\n    intros.\n    reflexivity.\n  Qed.\n\n  Theorem remove_exclude : forall (X : Type) {eq : EqDec X eq} (x : X) (xs : list X), remove (x :: xs) x = remove xs x.\n  Proof.\n    intros.\n    simpl.\n    destruct (eq x x) eqn:H1.\n    reflexivity.\n    assert (x === x) as H2.\n    reflexivity.\n    contradiction.\n   Qed.\n\n  Theorem remove_keep : forall (X : Type) {eq : EqDec X eq} (x y : X) (xs : list X), x =/= y -> remove (x :: xs) y = x :: (remove xs y).\n  Proof.\n    intros.\n    simpl.\n    destruct (eq y x) eqn:H1.\n    symmetry in H.\n    contradiction.\n    reflexivity.\n  Qed.\nEnd Remove_IMPL.\n   \n\n\n\n   ", "meta": {"author": "Admasnd", "repo": "formalverif", "sha": "87d154c0e9ac024ba75f798eb3643132a8aad91d", "save_path": "github-repos/coq/Admasnd-formalverif", "path": "github-repos/coq/Admasnd-formalverif/formalverif-87d154c0e9ac024ba75f798eb3643132a8aad91d/remove.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7476370521493718}}
{"text": "(* We copied and modified this file from https://github.com/roglo/coq_euler_prod_form/blob/master/Totient.v *)\n\nRequire Import Utf8 Arith.\nRequire Import Sorting.Permutation.\nImport List List.ListNotations.\n\nRequire Import Misc.\n\n(* gcd_and_bezout a b returns (g, (u, v)) with the property\n        a * u = b * v + g\n        g = gcd a b;\n   requires a ≠ 0 *)\n\nFixpoint gcd_bezout_loop n (a b : nat) : (nat * (nat * nat)) :=\n  match n with\n  | 0 => (0, (0, 0)) (* should not happen *)\n  | S n' =>\n      match b with\n      | 0 => (a, (1, 0))\n      | S _ =>\n          let '(g, (u, v)) := gcd_bezout_loop n' b (a mod b) in\n          let w := (u * b + v * (a - a mod b)) / b in\n          let k := max (v / b) (w / a) + 1 in\n          (g, (k * b - v, k * a - w))\n      end\n  end.\n\nDefinition gcd_and_bezout a b := gcd_bezout_loop (a + b + 1) a b.\n\nLemma gcd_bezout_loop_enough_iter_lt : ∀ m n a b,\n  a + b ≤ m\n  → a + b ≤ n\n  → b < a\n  → gcd_bezout_loop m a b = gcd_bezout_loop n a b.\nProof.\nintros * Habm Habn Hba.\nrevert n a b Habm Habn Hba.\ninduction m; intros; [ flia Habm Hba | ].\ndestruct n; [ flia Habn Hba | cbn ].\ndestruct (Nat.eq_dec b 0) as [Hbz| Hbz]; [ now subst b | ].\nreplace b with (S (b - 1)) at 1 2 by flia Hbz.\nremember (gcd_bezout_loop m b (a mod b)) as gbm eqn:Hgbm; symmetry in Hgbm.\nremember (gcd_bezout_loop n b (a mod b)) as gbn eqn:Hgbn; symmetry in Hgbn.\nspecialize (IHm n b (a mod b)) as H1.\nassert (H : ∀ p, a + b ≤ S p → b + a mod b ≤ p). {\n  intros * Habp.\n  transitivity (b + (a - 1)). {\n    apply Nat.add_le_mono_l.\n    specialize (Nat.div_mod a b Hbz) as H2.\n    apply (Nat.add_le_mono_l _ _ (b * (a / b))).\n    rewrite <- H2, Nat.add_comm.\n    remember (a / b) as q eqn:Hq; symmetry in Hq.\n    destruct q. {\n      apply Nat.div_small_iff in Hq; [ flia Hba Hq | easy ].\n    }\n    destruct b; [ easy | ].\n    cbn; remember (b * S q); flia.\n  }\n  flia Habp Hba.\n}\nspecialize (H1 (H m Habm) (H n Habn)); clear H.\nassert (H : a mod b < b) by now apply Nat.mod_upper_bound.\nspecialize (H1 H); clear H.\nnow rewrite <- Hgbm, H1, Hgbn.\nQed.\n\nLemma gcd_bezout_loop_enough_iter_ge : ∀ m n a b,\n  a + b + 1 ≤ m\n  → a + b + 1 ≤ n\n  → a ≤ b\n  → gcd_bezout_loop m a b = gcd_bezout_loop n a b.\nProof.\nintros * Habm Habn Hab.\ndestruct (Nat.eq_dec m 0) as [Hmz| Hmz]; [ flia Hmz Habm | ].\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]; [ flia Hnz Habn | ].\nreplace m with (S (m - 1)) by flia Hmz.\nreplace n with (S (n - 1)) by flia Hnz.\ncbn.\ndestruct (Nat.eq_dec b 0) as [Hbz| Hbz]; [ now subst b | ].\nreplace b with (S (b - 1)) at 1 2 by flia Hbz.\nrewrite (gcd_bezout_loop_enough_iter_lt _ (n - 1)); [ easy | | | ]. {\n  destruct (Nat.eq_dec a b) as [Habe| Habe]. {\n    subst a.\n    rewrite Nat.mod_same; [ | easy ].\n    flia Habm.\n  }\n  rewrite Nat.mod_small; [ | flia Hab Habe ].\n  flia Habm.\n} {\n  destruct (Nat.eq_dec a b) as [Habe| Habe]. {\n    subst a.\n    rewrite Nat.mod_same; [ | easy ].\n    flia Habn.\n  }\n  rewrite Nat.mod_small; [ | flia Hab Habe ].\n  flia Habn.\n} {\n  now apply Nat.mod_upper_bound.\n}\nQed.\n\nLemma fst_gcd_bezout_loop_is_gcd_lt : ∀ n a b,\n  a ≠ 0\n  → a + b + 1 ≤ n\n  → b < a\n  → fst (gcd_bezout_loop n a b) = Nat.gcd a b.\nProof.\nintros * Haz Hn Hba.\nrevert a b Haz Hn Hba.\ninduction n; intros; [ flia Hn | cbn ].\ndestruct (Nat.eq_dec b 0) as [Hbz| Hbz]. {\n  subst b.\n  now rewrite Nat.gcd_0_r.\n}\nreplace b with (S (b - 1)) at 1 by flia Hbz.\nremember (gcd_bezout_loop n b (a mod b)) as gb eqn:Hgb; symmetry in Hgb.\ndestruct gb as (g, (u, v)).\nrewrite Nat.gcd_comm, <- Nat.gcd_mod; [ | easy ].\nrewrite Nat.gcd_comm.\ncbn.\nreplace g with (fst (gcd_bezout_loop n b (a mod b))) by now rewrite Hgb.\napply IHn; [ easy | | ]. {\n  transitivity (a + b); [ | flia Hn ].\n  rewrite <- Nat.add_assoc, Nat.add_comm.\n  apply Nat.add_le_mono_r.\n  apply (Nat.add_le_mono_l _ _ (b * (a / b))).\n  rewrite Nat.add_assoc.\n  rewrite <- Nat.div_mod; [ | easy ].\n  rewrite Nat.add_comm.\n  apply Nat.add_le_mono_r.\n  remember (a / b) as q eqn:Hq; symmetry in Hq.\n  destruct q. {\n    apply Nat.div_small_iff in Hq; [ flia Hba Hq | easy ].\n  }\n  destruct b; [ easy | ].\n  cbn; remember (b * S q); flia.\n} {\n  now apply Nat.mod_upper_bound.\n}\nQed.\n\nLemma fst_gcd_bezout_loop_is_gcd_ge : ∀ n a b,\n  a ≠ 0\n  → a + b + 1 ≤ n\n  → a ≤ b\n  → fst (gcd_bezout_loop n a b) = Nat.gcd a b.\nProof.\nintros * Haz Hn Hba.\nrewrite (gcd_bezout_loop_enough_iter_ge _ (S n)); [ | easy | flia Hn | easy ].\ndestruct (Nat.eq_dec b 0) as [Hbz| Hbz]; [ subst b; flia Haz Hba | ].\ncbn.\nreplace b with (S (b - 1)) at 1 by flia Hbz.\nremember (gcd_bezout_loop n b (a mod b)) as gb eqn:Hgb; symmetry in Hgb.\ndestruct gb as (g, (u, v)); cbn.\nreplace g with (fst (gcd_bezout_loop n b (a mod b))) by now rewrite Hgb.\nrewrite Nat.gcd_comm.\nrewrite <- Nat.gcd_mod; [ | easy ].\nrewrite Nat.gcd_comm.\napply fst_gcd_bezout_loop_is_gcd_lt; [ easy | | ]. {\n  destruct (Nat.eq_dec a b) as [Habe| Habe]. {\n    subst a.\n    rewrite Nat.mod_same; [ | easy ].\n    flia Hn.\n  }\n  rewrite Nat.mod_small; [ | flia Hba Habe ].\n  flia Hn.\n} {\n  now apply Nat.mod_upper_bound.\n}\nQed.\n\nLemma fst_gcd_bezout_loop_is_gcd : ∀ n a b,\n  a ≠ 0\n  → a + b + 1 ≤ n\n  → fst (gcd_bezout_loop n a b) = Nat.gcd a b.\nProof.\nintros * Haz Hn.\ndestruct (le_dec a b) as [Hab| Hab]. {\n  now apply fst_gcd_bezout_loop_is_gcd_ge.\n} {\n  apply Nat.nle_gt in Hab.\n  now apply fst_gcd_bezout_loop_is_gcd_lt.\n}\nQed.\n\nTheorem fst_gcd_and_bezout_is_gcd : ∀ a b,\n  a ≠ 0\n  → fst (gcd_and_bezout a b) = Nat.gcd a b.\nProof.\nintros * Haz.\nnow apply fst_gcd_bezout_loop_is_gcd.\nQed.\n\nTheorem gcd_bezout_loop_enough_iter : ∀ m n a b,\n  a + b + 1 ≤ m\n  → a + b + 1 ≤ n\n  → gcd_bezout_loop m a b = gcd_bezout_loop n a b.\nProof.\nintros * Habm Habn.\ndestruct (le_dec a b) as [Hab| Hab]. {\n  now apply gcd_bezout_loop_enough_iter_ge.\n} {\n  apply Nat.nle_gt in Hab.\n  apply gcd_bezout_loop_enough_iter_lt; [ flia Habm | flia Habn | easy ].\n}\nQed.\n\nTheorem gcd_bezout_loop_fst_0_gcd_0 : ∀ n a b g v,\n  a ≠ 0\n  → a + b + 1 ≤ n\n  → b < a\n  → gcd_bezout_loop n a b = (g, (0, v))\n  → g = 0.\nProof.\nintros * Haz Hn Hba Hnab.\nassert (Hg : Nat.gcd a b = g). {\n  replace g with (fst (gcd_bezout_loop n a b)) by now rewrite Hnab.\n  now rewrite fst_gcd_bezout_loop_is_gcd.\n}\nrevert a b g v Haz Hn Hba Hnab Hg.\ninduction n; intros; [ flia Hn | ].\ndestruct (Nat.eq_dec b 0) as [Hbz| Hbz]; [ now subst b | ].\ncbn in Hnab.\nreplace b with (S (b - 1)) in Hnab at 1 by flia Hbz.\nremember (gcd_bezout_loop n b (a mod b)) as gb eqn:Hgb; symmetry in Hgb.\ndestruct gb as (g', (u, v')).\ninjection Hnab; clear Hnab; intros H1 Hv H2; subst g' v.\nrename v' into v.\napply Nat.sub_0_le in Hv.\nrewrite Nat.mul_add_distr_r, Nat.mul_1_l in Hv.\nrewrite <- Nat.mul_max_distr_r in Hv.\nrewrite <- Nat.add_max_distr_r in Hv.\napply Nat.max_lub_iff in Hv.\ndestruct Hv as (Hvb, Huv).\nrewrite Nat.div_div in Huv; [ | easy | easy ].\napply Nat.nlt_ge in Hvb.\nexfalso; apply Hvb; clear Hvb.\nrewrite Nat.mul_comm.\nspecialize (Nat.div_mod v b Hbz) as H1.\nrewrite Nat.add_comm.\napply (Nat.add_lt_mono_r _ _ (v mod b)).\nrewrite <- Nat.add_assoc, <- H1.\nrewrite Nat.add_comm.\napply Nat.add_lt_mono_r.\nnow apply Nat.mod_upper_bound.\nQed.\n\nTheorem gcd_bezout_loop_prop_lt : ∀ n a b g u v,\n  a ≠ 0\n  → a + b + 1 ≤ n\n  → b < a\n  → gcd_bezout_loop n a b = (g, (u, v))\n  → a * u = b * v + g.\nProof.\nintros * Haz Hn Hba Hnab.\nassert (Hgcd : g = Nat.gcd a b). {\n  apply fst_gcd_bezout_loop_is_gcd in Hn; [ | easy ].\n  now rewrite Hnab in Hn; cbn in Hn.\n}\nrewrite (gcd_bezout_loop_enough_iter _ (S n)) in Hnab; [ | easy | flia Hn ].\nrevert a b g u v Haz Hn Hba Hnab Hgcd.\ninduction n; intros; [ flia Hn | ].\nremember (S n) as sn; cbn in Hnab; subst sn.\ndestruct (Nat.eq_dec b 0) as [Hbz| Hbz]. {\n  subst b.\n  rewrite Nat.mul_0_l.\n  injection Hnab; clear Hnab; intros; subst g u v.\n  now rewrite Nat.mul_1_r.\n}\nreplace b with (S (b - 1)) in Hnab at 1 by flia Hbz.\nremember (gcd_bezout_loop (S n) b (a mod b)) as gb eqn:Hgb; symmetry in Hgb.\ndestruct gb as (g', (u', v')).\ninjection Hnab; clear Hnab; intros; move Hgcd at bottom; subst g u v.\nrename g' into g; rename u' into u; rename v' into v.\nremember ((u * b + v * (a - a mod b)) / b) as w eqn:Hw; symmetry in Hw.\nremember (max (v / b) (w / a) + 1) as k eqn:Hk.\ndo 2 rewrite Nat.mul_sub_distr_l.\nreplace (a * (k * b)) with (k * a * b) by flia.\nreplace (b * (k * a)) with (k * a * b) by flia.\nrewrite <- Nat_sub_sub_distr. 2: {\n  split. 2: {\n    rewrite Nat.mul_comm.\n    apply Nat.mul_le_mono_r.\n    apply Nat_div_lt_le_mul; [ flia Hk | ].\n    destruct (Nat.lt_trichotomy (v / b) (w / a)) as [H| H]. {\n      rewrite max_r in Hk; [ | now apply Nat.lt_le_incl ].\n      rewrite Hk.\n      apply Nat.div_lt_upper_bound; [ now rewrite Nat.add_comm | ].\n      rewrite Nat.mul_add_distr_r, Nat.mul_1_l, Nat.mul_comm.\n      specialize (Nat.div_mod w a Haz) as H1.\n      apply (Nat.add_lt_mono_r _ _ (w mod a)).\n      rewrite Nat.add_shuffle0.\n      rewrite <- H1.\n      apply Nat.add_lt_mono_l.\n      now apply Nat.mod_upper_bound.\n    } {\n      assert (Huv : w / a ≤ v / b) by flia H; clear H.\n      rewrite max_l in Hk; [ | easy ].\n      rewrite Hk.\n      apply (le_lt_trans _ (w / (w / a + 1))). {\n        apply Nat.div_le_compat_l.\n        split; [ flia | ].\n        now apply Nat.add_le_mono_r.\n      }\n      apply Nat.div_lt_upper_bound; [ now rewrite Nat.add_comm | ].\n      rewrite Nat.mul_add_distr_r, Nat.mul_1_l, Nat.mul_comm.\n      specialize (Nat.div_mod w a Haz) as H1.\n      rewrite H1 at 1.\n      apply Nat.add_lt_mono_l.\n      now apply Nat.mod_upper_bound.\n    }\n  } {\n    clear k Hk.\n    rewrite Nat.add_comm, Nat.div_add in Hw; [ | easy ].\n    rewrite Nat.add_comm in Hw.\n    destruct u. {\n      apply gcd_bezout_loop_fst_0_gcd_0 in Hgb; [ | easy | | ]; cycle 1. {\n        destruct (lt_dec a b) as [Hab| Hab]. {\n          rewrite Nat.mod_small in Hgb; [ | easy ].\n          rewrite Nat.mod_small; [ | easy ].\n          now rewrite (Nat.add_comm b).\n        } {\n          apply Nat.nlt_ge in Hab.\n          transitivity (a + b + 1); [ | easy ].\n          rewrite (Nat.add_comm b).\n          do 2 apply Nat.add_le_mono_r.\n          now apply Nat.mod_le.\n        }\n      } {\n        now apply Nat.mod_upper_bound.\n      }\n      subst g; apply Nat.le_0_l.\n    }\n    rewrite <- Hw.\n    rewrite Nat.mul_comm; cbn.\n    transitivity b; [ | remember (_ * b); flia ].\n    rewrite Hgcd.\n    now apply Nat_gcd_le_r.\n  }\n}\nf_equal.\napply IHn in Hgb; [ | easy | | | ]; cycle 1. {\n  transitivity (a + b); [ | flia Hn ].\n  rewrite <- Nat.add_assoc, Nat.add_comm.\n  apply Nat.add_le_mono_r.\n  apply (Nat.add_le_mono_l _ _ (b * (a / b))).\n  rewrite Nat.add_assoc.\n  rewrite <- Nat.div_mod; [ | easy ].\n  rewrite Nat.add_comm.\n  apply Nat.add_le_mono_r.\n  remember (a / b) as q eqn:Hq; symmetry in Hq.\n  destruct q. {\n    apply Nat.div_small_iff in Hq; [ flia Hba Hq | easy ].\n  }\n  destruct b; [ easy | ].\n  cbn; remember (b * S q); flia.\n} {\n  now apply Nat.mod_upper_bound.\n} {\n  rewrite Nat.gcd_comm, Nat.gcd_mod; [ | easy ].\n  now rewrite Nat.gcd_comm.\n}\nrewrite <- Hw.\nrewrite <- Nat.divide_div_mul_exact; [ | easy | ]. 2: {\n  exists (u + v * (a - a mod b) / b).\n  rewrite Nat.mul_add_distr_r; f_equal.\n  rewrite Nat.divide_div_mul_exact; [ | easy | ]. 2: {\n    exists (a / b).\n    rewrite (Nat.div_mod a b Hbz) at 1.\n    now rewrite Nat.add_sub, Nat.mul_comm.\n  }\n  rewrite <- Nat.mul_assoc; f_equal.\n  rewrite Nat.mul_comm.\n  rewrite <- Nat.divide_div_mul_exact; [ | easy | ]. 2: {\n    exists (a / b).\n    rewrite (Nat.div_mod a b Hbz) at 1.\n    now rewrite Nat.add_sub, Nat.mul_comm.\n  }\n  rewrite Nat.mul_comm.\n  now rewrite Nat.div_mul.\n}\nrewrite (Nat.mul_comm b).\nrewrite Nat.div_mul; [ | easy ].\nrewrite Nat.mul_sub_distr_l, (Nat.mul_comm v).\nrewrite Nat.add_sub_assoc. 2: {\n  rewrite Nat.mul_comm.\n  apply Nat.mul_le_mono_r.\n  now apply Nat.mod_le.\n}\nsymmetry; apply Nat.add_sub_eq_l.\nsymmetry; apply Nat.add_sub_eq_l.\nrewrite Nat.add_assoc; f_equal.\nnow rewrite (Nat.mul_comm u), (Nat.mul_comm v).\nQed.\n\nTheorem gcd_bezout_loop_prop_ge : ∀ n a b g u v,\n  a ≠ 0\n  → a + b + 1 ≤ n\n  → a ≤ b\n  → gcd_bezout_loop n a b = (g, (u, v))\n  → a * u = b * v + g.\nProof.\nintros * Haz Hn Hba Hbez.\nassert (Hgcd : g = Nat.gcd a b). {\n  specialize (fst_gcd_bezout_loop_is_gcd n a b Haz Hn) as H1.\n  now rewrite Hbez in H1.\n}\ndestruct (Nat.eq_dec b 0) as [Hbz| Hbz]; [ subst b; flia Haz Hba | ].\nrewrite (gcd_bezout_loop_enough_iter _ (S n)) in Hbez; try flia Hn.\ncbn - [ \"/\" \"mod\" ] in Hbez.\nreplace b with (S (b - 1)) in Hbez at 1 by flia Haz Hba.\nremember (gcd_bezout_loop n b (a mod b)) as gb eqn:Hgb.\nsymmetry in Hgb.\ndestruct gb as (g', (u', v')).\napply gcd_bezout_loop_prop_lt in Hgb; [ | easy | | ]; cycle 1. {\n  destruct (Nat.eq_dec a b) as [Hab| Hab]. {\n    subst b.\n    rewrite Nat.mod_same; [ flia Hn | easy ].\n  }\n  rewrite (Nat.add_comm b).\n  rewrite Nat.mod_small; [ easy | flia Hba Hab ].\n} {\n  now apply Nat.mod_upper_bound.\n}\ninjection Hbez; clear Hbez; intros; move Hgcd at bottom; subst g u v.\nrename g' into g; rename u' into u; rename v' into v.\nremember ((u * b + v * (a - a mod b)) / b) as w eqn:Hw; symmetry in Hw.\nremember (max (v / b) (w / a) + 1) as k eqn:Hk.\ndo 2 rewrite Nat.mul_sub_distr_l.\nreplace (a * (k * b)) with (k * a * b) by flia.\nreplace (b * (k * a)) with (k * a * b) by flia.\nrewrite <- Nat_sub_sub_distr. 2: {\n  split. 2: {\n    rewrite Nat.mul_comm.\n    apply Nat.mul_le_mono_r.\n    apply Nat_div_lt_le_mul; [ flia Hk | ].\n    destruct (Nat.lt_trichotomy (v / b) (w / a)) as [H| H]. {\n      rewrite max_r in Hk; [ | now apply Nat.lt_le_incl ].\n      rewrite Hk.\n      apply Nat.div_lt_upper_bound; [ now rewrite Nat.add_comm | ].\n      rewrite Nat.mul_add_distr_r, Nat.mul_1_l, Nat.mul_comm.\n      specialize (Nat.div_mod w a Haz) as H1.\n      apply (Nat.add_lt_mono_r _ _ (w mod a)).\n      rewrite Nat.add_shuffle0.\n      rewrite <- H1.\n      apply Nat.add_lt_mono_l.\n      now apply Nat.mod_upper_bound.\n    } {\n      assert (Huv : w / a ≤ v / b) by flia H; clear H.\n      rewrite max_l in Hk; [ | easy ].\n      rewrite Hk.\n      apply (le_lt_trans _ (w / (w / a + 1))). {\n        apply Nat.div_le_compat_l.\n        split; [ flia | ].\n        now apply Nat.add_le_mono_r.\n      }\n      apply Nat.div_lt_upper_bound; [ now rewrite Nat.add_comm | ].\n      rewrite Nat.mul_add_distr_r, Nat.mul_1_l, Nat.mul_comm.\n      specialize (Nat.div_mod w a Haz) as H1.\n      rewrite H1 at 1.\n      apply Nat.add_lt_mono_l.\n      now apply Nat.mod_upper_bound.\n    }\n  } {\n    clear k Hk.\n    rewrite Nat.add_comm, Nat.div_add in Hw; [ | easy ].\n    rewrite Nat.add_comm in Hw.\n    destruct u. {\n      rewrite Nat.mul_0_r in Hgb.\n      symmetry in Hgb.\n      apply Nat.eq_add_0 in Hgb.\n      rewrite (proj2 Hgb).\n      apply Nat.le_0_l.\n    }\n    rewrite <- Hw.\n    rewrite Nat.mul_comm; cbn.\n    transitivity b; [ | remember (_ * b); flia ].\n    rewrite Hgcd.\n    now apply Nat_gcd_le_r.\n  }\n}\nf_equal.\nrewrite <- Hw.\nrewrite <- Nat.divide_div_mul_exact; [ | easy | ]. 2: {\n  exists (u + v * ((a - a mod b) / b)).\n  rewrite Nat.mul_add_distr_r; f_equal.\n  rewrite <- Nat.mul_assoc; f_equal.\n  rewrite Nat.mul_comm.\n    rewrite <- Nat.divide_div_mul_exact; [ | easy | ]. 2: {\n      exists (a / b).\n      rewrite (Nat.div_mod a b) at 1; [ | easy ].\n      now rewrite Nat.add_sub, Nat.mul_comm.\n    }\n    now rewrite Nat.mul_comm, Nat.div_mul.\n  }\n  rewrite (Nat.mul_comm b), Nat.div_mul; [ | easy ].\n  rewrite (Nat.mul_comm u), Hgb.\n  rewrite Nat.mul_sub_distr_l.\n  rewrite Nat.add_shuffle0, Nat.add_sub.\n  rewrite Nat.add_sub_assoc. 2: {\n    apply Nat.mul_le_mono_l.\n    destruct (Nat.eq_dec a b) as [Hab| Hab]. {\n      subst a.\n      rewrite Nat.mod_same; [ apply Nat.le_0_l | easy ].\n    }\n    now apply Nat.mod_le.\n  }\n  rewrite Nat.add_comm, (Nat.mul_comm (a mod b)).\n  now rewrite Nat.add_sub, Nat.mul_comm.\nQed.\n\nTheorem gcd_and_bezout_prop : ∀ a b g u v,\n  a ≠ 0\n  → gcd_and_bezout a b = (g, (u, v))\n  → a * u = b * v + g ∧ g = Nat.gcd a b.\nProof.\nintros * Haz Hbez.\nassert (Hgcd : g = Nat.gcd a b). {\n  specialize (fst_gcd_and_bezout_is_gcd a b Haz) as H1.\n  now rewrite Hbez in H1.\n}\nsplit; [ | easy ].\ndestruct (lt_dec b a) as [Hba| Hba]. {\n  now apply (gcd_bezout_loop_prop_lt (a + b + 1)).\n} {\n  apply Nat.nlt_ge in Hba.\n  now apply (gcd_bezout_loop_prop_ge (a + b + 1)).\n}\nQed.\n\n(* Nat.gcd_bezout_pos could be implemented like this *)\nTheorem Nat_gcd_bezout_pos n m : 0 < n → Nat.Bezout n m (Nat.gcd n m).\nProof.\nintros * Hn.\napply Nat.neq_0_lt_0 in Hn.\nremember (gcd_and_bezout n m) as gb eqn:Hgb; symmetry in Hgb.\ndestruct gb as (g, (u, v)).\napply gcd_and_bezout_prop in Hgb; [ | easy ].\ndestruct Hgb as (Hnm, Hg); rewrite <- Hg.\nexists u, v.\nrewrite Nat.mul_comm, Nat.add_comm.\nnow rewrite (Nat.mul_comm v).\nQed.\n\n(* Euler's totient function *)\n\nDefinition coprimes' n := filter (λ d, Nat.gcd n d =? 1) (seq 1 (n - 1)).\nDefinition φ' n := length (coprimes' n).\n\n(* Totient function is multiplicative *)\n\nTheorem bijection_same_length {A B} : ∀ f g (l : list A) (l' : list B),\n  NoDup l\n  → NoDup l'\n  → (∀ a, a ∈ l → f a ∈ l')\n  → (∀ b, b ∈ l' → g b ∈ l)\n  → (∀ a, a ∈ l → g (f a) = a)\n  → (∀ b, b ∈ l' → f (g b) = b)\n  → length l = length l'.\nProof.\nintros * Hnl Hnl' Hf Hg Hgf Hfg.\nrevert l' Hf Hg Hfg Hnl'.\ninduction l as [| x l]; intros. {\n  destruct l' as [| y l']; [ easy | exfalso ].\n  now specialize (Hg y (or_introl eq_refl)).\n}\ndestruct l' as [| y l']. {\n  exfalso.\n  now specialize (Hf x (or_introl eq_refl)).\n}\nspecialize (in_split (f x) (y :: l') (Hf x (or_introl eq_refl))) as H.\ndestruct H as (l1 & l2 & Hll).\nrewrite Hll.\ntransitivity (length (f x :: l1 ++ l2)). 2: {\n  cbn; do 2 rewrite app_length; cbn; flia.\n}\ncbn; f_equal.\napply IHl. {\n    now apply NoDup_cons_iff in Hnl.\n} {\n  intros a Ha.\n  now apply Hgf; right.\n} {\n  intros a Ha.\n  specialize (Hf a (or_intror Ha)) as H1.\n  rewrite Hll in H1.\n  apply in_app_or in H1.\n  apply in_or_app.\n  destruct H1 as [H1| H1]; [ now left | ].\n  destruct H1 as [H1| H1]; [ | now right ].\n  apply (f_equal g) in H1.\n  rewrite Hgf in H1; [ | now left ].\n  rewrite Hgf in H1; [ | now right ].\n  subst a.\n  now apply NoDup_cons_iff in Hnl.\n} {\n  intros b Hb.\n  rewrite Hll in Hg.\n  specialize (Hg b) as H1.\n  assert (H : b ∈ l1 ++ f x :: l2). {\n    apply in_app_or in Hb.\n    apply in_or_app.\n    destruct Hb as [Hb| Hb]; [ now left | ].\n    now right; right.\n  }\n  specialize (H1 H); clear H.\n  destruct H1 as [H1| H1]; [ | easy ].\n  subst x.\n  rewrite Hfg in Hll. 2: {\n    rewrite Hll.\n    apply in_app_or in Hb.\n    apply in_or_app.\n    destruct Hb as [Hb| Hb]; [ now left | ].\n    now right; right.\n  }\n  rewrite Hll in Hnl'.\n  now apply NoDup_remove_2 in Hnl'.\n} {\n  intros b Hb.\n  apply Hfg.\n  rewrite Hll.\n  apply in_app_or in Hb.\n  apply in_or_app.\n  destruct Hb as [Hb| Hb]; [ now left | ].\n  now right; right.\n} {\n  rewrite Hll in Hnl'.\n  now apply NoDup_remove_1 in Hnl'.\n}\nQed.\n\nDefinition prod_copr_of_copr_mul m n a := (a mod m, a mod n).\n\nDefinition copr_mul_of_prod_copr (m n : nat) '((x, y) : nat * nat) :=\n  let '(u, v) := snd (gcd_and_bezout m n) in\n  m * n - (n * x * v + m * (n - 1) * y * u) mod (m * n).\n\nTheorem in_coprimes'_iff : ∀ n a,\n  a ∈ seq 1 (n - 1) ∧ Nat.gcd n a = 1 ↔ a ∈ coprimes' n.\nProof.\nintros.\nsplit; intros Ha. {\n  apply filter_In.\n  split; [ easy | ].\n  now apply Nat.eqb_eq.\n} {\n  apply filter_In in Ha.\n  split; [ easy | ].\n  now apply Nat.eqb_eq.\n}\nQed.\n\nTheorem prod_copr_of_copr_mul_in_prod : ∀ m n a,\n  2 ≤ m\n  → 2 ≤ n\n  → a ∈ coprimes' (m * n)\n  → prod_copr_of_copr_mul m n a ∈\n       list_prod (coprimes' m) (coprimes' n).\nProof.\nintros * H2m H2n Ha.\ndestruct (Nat.eq_dec m 0) as [Hmz| Hmz]; [ now subst m | ].\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  now subst n; rewrite Nat.mul_0_r in Ha.\n}\napply in_coprimes'_iff in Ha.\ndestruct Ha as (Ha, Hga).\napply in_seq in Ha.\nrewrite Nat.add_comm, Nat.sub_add in Ha by flia Ha.\nunfold prod_copr_of_copr_mul.\napply in_prod. {\n  apply in_coprimes'_iff.\n  split. {\n    apply in_seq.\n    split. {\n      remember (a mod m) as r eqn:Hr; symmetry in Hr.\n      destruct r; [ | flia ].\n      apply Nat.mod_divides in Hr; [ | easy ].\n      destruct Hr as (k, Hk).\n      rewrite Hk in Hga.\n      rewrite Nat.gcd_mul_mono_l in Hga.\n      apply Nat.eq_mul_1 in Hga.\n      flia Hga H2m.\n    } {\n      rewrite Nat.add_comm, Nat.sub_add; [ | flia Hmz ].\n      now apply Nat.mod_upper_bound.\n    }\n  } {\n    rewrite Nat.gcd_comm, Nat.gcd_mod; [ | easy ].\n    remember (Nat.gcd m a) as g eqn:Hg; symmetry in Hg.\n    destruct g; [ now apply Nat.gcd_eq_0_l in Hg | ].\n    destruct g; [ easy | exfalso ].\n    replace (S (S g)) with (g + 2) in Hg by flia.\n    specialize (Nat.gcd_divide_l m a) as H1.\n    specialize (Nat.gcd_divide_r m a) as H2.\n    rewrite Hg in H1, H2.\n    destruct H1 as (k1, Hk1).\n    destruct H2 as (k2, Hk2).\n    rewrite Hk1, Hk2 in Hga.\n    rewrite Nat.mul_shuffle0 in Hga.\n    rewrite Nat.gcd_mul_mono_r in Hga.\n    apply Nat.eq_mul_1 in Hga.\n    flia Hga.\n  }\n} {\n  apply in_coprimes'_iff.\n  rewrite Nat.mul_comm in Hga.\n  split. {\n    apply in_seq.\n    split. {\n      remember (a mod n) as r eqn:Hr; symmetry in Hr.\n      destruct r; [ | flia ].\n      apply Nat.mod_divides in Hr; [ | easy ].\n      destruct Hr as (k, Hk).\n      rewrite Hk in Hga.\n      rewrite Nat.gcd_mul_mono_l in Hga.\n      apply Nat.eq_mul_1 in Hga.\n      flia Hga H2n.\n    } {\n      rewrite Nat.add_comm, Nat.sub_add; [ | flia Hnz ].\n      now apply Nat.mod_upper_bound.\n    }\n  } {\n    rewrite Nat.gcd_comm, Nat.gcd_mod; [ | easy ].\n    remember (Nat.gcd n a) as g eqn:Hg; symmetry in Hg.\n    destruct g; [ now apply Nat.gcd_eq_0_l in Hg | ].\n    destruct g; [ easy | exfalso ].\n    replace (S (S g)) with (g + 2) in Hg by flia.\n    specialize (Nat.gcd_divide_l n a) as H1.\n    specialize (Nat.gcd_divide_r n a) as H2.\n    rewrite Hg in H1, H2.\n    destruct H1 as (k1, Hk1).\n    destruct H2 as (k2, Hk2).\n    rewrite Hk1, Hk2 in Hga.\n    rewrite Nat.mul_shuffle0 in Hga.\n    rewrite Nat.gcd_mul_mono_r in Hga.\n    apply Nat.eq_mul_1 in Hga.\n    flia Hga.\n  }\n}\nQed.\n\nTheorem copr_mul_of_prod_copr_in_coprimes' : ∀ m n,\n  2 ≤ m\n  → Nat.gcd m n = 1\n  → ∀ a, a ∈ list_prod (coprimes' m) (coprimes' n)\n  → copr_mul_of_prod_copr m n a ∈ coprimes' (m * n).\nProof.\nintros m n H2m Hmn (a, b) Hab.\ndestruct (Nat.eq_dec m 0) as [Hmz| Hmz]; [ now subst m | ].\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  subst n; cbn in Hab.\n  now rewrite List_list_prod_nil_r in Hab.\n}\napply in_prod_iff in Hab.\ndestruct Hab as (Ha, Hb).\napply in_coprimes'_iff in Ha.\napply in_coprimes'_iff in Hb.\ndestruct Ha as (Ha, Hma).\ndestruct Hb as (Hb, Hnb).\nmove Hb before Ha.\napply in_seq in Ha.\napply in_seq in Hb.\nreplace (1 + (m - 1)) with m in Ha by flia Hmz.\nreplace (1 + (n - 1)) with n in Hb by flia Hnz.\nunfold copr_mul_of_prod_copr.\nremember (gcd_and_bezout m n) as gb eqn:Hgb.\nsymmetry in Hgb.\ndestruct gb as (g & u & v); cbn.\nspecialize (gcd_and_bezout_prop m n g u v Hmz Hgb) as (Hmng & Hg).\nrewrite Hmn in Hg; subst g.\napply in_coprimes'_iff.\nassert (Hnmz : (n * a * v + m * (n - 1) * b * u) mod (m * n) ≠ 0). {\n  rewrite Nat.mod_mul_r; [ | easy | easy ].\n  do 2 rewrite <- (Nat.mul_assoc m).\n  rewrite Nat_mod_add_r_mul_l; [ | easy ].\n  remember ((n * a * v) mod m) as p eqn:Hp; symmetry in Hp.\n  destruct p. {\n    apply Nat.mod_divides in Hp; [ | easy ].\n    destruct Hp as (k, Hk).\n    rewrite Nat.mul_shuffle0 in Hk.\n    replace (n * v) with (m * u - 1) in Hk by flia Hmng.\n    rewrite Nat.mul_sub_distr_r, Nat.mul_1_l in Hk.\n    apply Nat.add_sub_eq_nz in Hk. 2: {\n      apply Nat.neq_mul_0.\n      split; [ easy | ].\n      intros H; subst k; rewrite Nat.mul_0_r in Hk.\n      apply Nat.sub_0_le in Hk.\n      apply Nat.nlt_ge in Hk; apply Hk; clear Hk.\n      replace a with (1 * a) at 1 by flia.\n      apply Nat.mul_lt_mono_pos_r; [ easy | ].\n      destruct u. {\n        rewrite Nat.mul_0_r in Hmng; flia Hmng.\n      }\n      rewrite Nat.mul_succ_r.\n      destruct m; [ easy | ].\n      destruct m; [ flia H2m | ].\n      remember (S (S m) * u); flia.\n    }\n    rewrite Hmng in Hk.\n    rewrite Nat.mul_add_distr_r, Nat.mul_1_l in Hk.\n    rewrite Nat.add_comm in Hk.\n    apply Nat.add_cancel_r in Hk.\n    rewrite Nat.mul_shuffle0 in Hk; rewrite <- Hk.\n    rewrite Nat.mul_shuffle0 in Hk.\n    replace (n * v) with (m * u - 1) in Hk by flia Hmng.\n    rewrite Nat.mul_sub_distr_r, Nat.mul_1_l in Hk.\n    symmetry in Hk.\n    destruct (le_dec k (u * a)) as [Hku| Hku]. {\n      assert (H : a = m * u * a - m * k). {\n        rewrite <- Hk.\n        rewrite Nat_sub_sub_distr. 2: {\n          split; [ | easy ].\n          destruct m; [ easy | ].\n          destruct u; [ rewrite Nat.mul_0_r in Hmng; flia Hmng | cbn ].\n          remember ((u + m * S u) * a); flia.\n        }\n        now rewrite Nat.sub_diag.\n      }\n      rewrite <- Nat.mul_assoc in H.\n      rewrite <- Nat.mul_sub_distr_l in H.\n      destruct Ha as (Ha1, Ha).\n      rewrite H in Ha.\n      apply Nat.nle_gt in Ha; exfalso; apply Ha.\n      destruct (Nat.eq_dec (u * a) k) as [Huk| Huk]. {\n        subst k.\n        rewrite Nat.sub_diag, Nat.mul_0_r in H; flia H Ha1.\n      }\n      remember (u * a - k) as p eqn:Hp.\n      destruct p. {\n        rewrite Nat.mul_0_r in H; flia H Ha1.\n      }\n      rewrite Nat.mul_succ_r; flia.\n    }\n    apply Nat.nle_gt in Hku.\n    apply (Nat.mul_lt_mono_pos_r m) in Hku; [ | flia Hmz ].\n    rewrite (Nat.mul_comm k) in Hku.\n    rewrite <- Hk in Hku.\n    rewrite Nat.mul_comm, Nat.mul_assoc in Hku.\n    remember (m * u * a).\n    flia Hku.\n  }\n  flia.\n}\nsplit. {\n  apply in_seq.\n  split. 2: {\n    rewrite (Nat.add_comm _ (m * n - 1)).\n    rewrite Nat.sub_add. 2: {\n      destruct m; [ flia Hmz | ].\n      destruct n; [ flia Hnz | ].\n      cbn; remember (m * S n); flia.\n    }\n    apply Nat.sub_lt; [ | now apply Nat.neq_0_lt_0 ].\n    apply Nat.lt_le_incl.\n    apply Nat.mod_upper_bound.\n    now apply Nat.neq_mul_0.\n  }\n  apply Nat.le_add_le_sub_r.\n  apply Nat.mod_upper_bound.\n  now apply Nat.neq_mul_0.\n}\nremember (n * a * v + m * (n - 1) * b * u) as p eqn:Hp.\nrewrite Nat_gcd_sub_diag_l. 2: {\n  apply Nat.lt_le_incl.\n  apply Nat.mod_upper_bound.\n  now apply Nat.neq_mul_0.\n}\nrewrite Nat.gcd_comm.\nrewrite Nat.gcd_mod; [ | now apply Nat.neq_mul_0 ].\nrewrite Nat.gcd_comm.\napply Nat_gcd_1_mul_r. {\n  rewrite Hp.\n  rewrite Nat.gcd_comm.\n  do 2 rewrite <- (Nat.mul_assoc m).\n  rewrite (Nat.mul_comm m).\n  rewrite Nat.gcd_add_mult_diag_r.\n  rewrite <- Nat.mul_assoc.\n  apply Nat_gcd_1_mul_r; [ easy | ].\n  apply Nat_gcd_1_mul_r; [ easy | ].\n  apply Nat.bezout_1_gcd.\n  exists u, n.\n  flia Hmng.\n} {\n  rewrite Hp.\n  rewrite <- (Nat.mul_assoc n).\n  rewrite (Nat.mul_comm n).\n  rewrite Nat.add_comm, Nat.gcd_comm.\n  rewrite Nat.gcd_add_mult_diag_r.\n  do 2 rewrite <- Nat.mul_assoc.\n  rewrite Nat.mul_comm.\n  apply Nat_gcd_1_mul_r; [ | now rewrite Nat.gcd_comm ].\n  rewrite Nat.mul_assoc.\n  apply Nat_gcd_1_mul_r. 2: {\n    apply Nat.bezout_1_gcd.\n    apply Nat_bezout_comm; [ easy | ].\n    exists m, v.\n    flia Hmng.\n  }\n  apply Nat_gcd_1_mul_r; [ | easy ].\n  rewrite Nat_gcd_sub_diag_l; [ | flia Hnz ].\n  apply Nat.gcd_1_r.\n}\nQed.\n\nTheorem Nat_mul_pred_r_mod : ∀ a b,\n  a ≠ 0\n  → 1 ≤ b < a\n  → (b * (a - 1)) mod a = a - b.\nProof.\nintros n a Hmn Ha.\nremember (n - a) as b.\nreplace a with (n - b) in * by flia Heqb Ha.\nclear a Heqb; rename b into a.\nassert (H : 1 ≤ a < n) by flia Ha.\nclear Ha; rename H into Ha.\n(* or lemma here, perhaps? *)\nrewrite Nat.mul_sub_distr_r.\ndo 2 rewrite Nat.mul_sub_distr_l, Nat.mul_1_r.\nrewrite Nat_sub_sub_assoc. 2: {\n  split. {\n    destruct n; [ easy | ].\n    rewrite Nat.mul_succ_r; flia.\n  } {\n    replace n with (1 * n) at 4 by flia.\n    rewrite <- Nat.mul_sub_distr_r.\n    transitivity ((n - 1) * n); [ | flia ].\n    apply Nat.mul_le_mono_r; flia Ha.\n  }\n}\nrewrite <- (Nat.mod_add _ a); [ | easy ].\nrewrite Nat.sub_add. 2: {\n  replace n with (1 * n) at 4 by flia.\n  rewrite <- Nat.mul_sub_distr_r.\n  transitivity ((n - 1) * n); [ | flia ].\n  apply Nat.mul_le_mono_r; flia Ha.\n}\nrewrite <- Nat.add_sub_swap. 2: {\n  replace n with (1 * n) at 1 by flia.\n  apply Nat.mul_le_mono_r; flia Hmn.\n}\nrewrite <- (Nat.mod_add _ 1); [ | easy ].\nrewrite Nat.mul_1_l.\nrewrite Nat.sub_add. 2: {\n  transitivity (n * n); [ | flia ].\n  replace n with (1 * n) at 1 by flia.\n  apply Nat.mul_le_mono_r; flia Hmn.\n}\nrewrite Nat.add_comm, Nat.mod_add; [ | easy ].\nnow rewrite Nat.mod_small.\nQed.\n\nTheorem coprimes'_mul_prod_coprimes' : ∀ m n,\n  m ≠ 0\n  → n ≠ 0\n  → Nat.gcd m n = 1\n  → ∀ a, a ∈ seq 1 (m * n - 1)\n  → copr_mul_of_prod_copr m n (prod_copr_of_copr_mul m n a) = a.\nProof.\nintros * Hmz Hnz Hgmn * Ha.\nunfold copr_mul_of_prod_copr.\nunfold prod_copr_of_copr_mul.\nremember (gcd_and_bezout m n) as gb eqn:Hgb.\nsymmetry in Hgb.\ndestruct gb as (g & u & v); cbn.\nspecialize (gcd_and_bezout_prop m n g u v Hmz Hgb) as (Hmng & Hg).\nrewrite Hgmn in Hg; subst g.\nspecialize (Nat.div_mod a m Hmz) as Ham.\nspecialize (Nat.div_mod a n Hnz) as Han.\nremember (a / m) as qm eqn:Hqm.\nremember (a / n) as qn eqn:Hqn.\nreplace (a mod m) with (a - m * qm) by flia Ham.\nreplace (a mod n) with (a - n * qn) by flia Han.\nrewrite Nat.mul_sub_distr_l, Nat.mul_assoc.\nrewrite (Nat.mul_shuffle0 m).\nrewrite (Nat.mul_sub_distr_l _ _ m), Nat.mul_assoc.\ndo 3 rewrite Nat.mul_sub_distr_r.\nrewrite Nat.add_sub_assoc. 2: {\n  do 2 apply Nat.mul_le_mono_r.\n  rewrite <- Nat.mul_assoc.\n  apply Nat.mul_le_mono_l.\n  subst qn.\n  now apply Nat.mul_div_le.\n}\nassert (Hmn : m * n ≠ 0) by now apply Nat.neq_mul_0.\nrewrite <- (Nat.mod_add _ (qn * (n - 1) * u)); [ | easy ].\nreplace (qn * (n - 1) * u * (m * n)) with (m * n * qn * (n - 1) * u) by flia.\nrewrite Nat.sub_add. 2: {\n  ring_simplify.\n  transitivity (m * (n - 1) * u * a); [ | flia ].\n  rewrite Nat.mul_shuffle0.\n  rewrite (Nat.mul_shuffle0 m (n - 1)).\n  rewrite (Nat.mul_shuffle0 (m * u)).\n  apply Nat.mul_le_mono_r.\n  rewrite (Nat.mul_shuffle0 _ u).\n  apply Nat.mul_le_mono_r.\n  rewrite <- Nat.mul_assoc.\n  apply Nat.mul_le_mono_l.\n  subst qn.\n  now apply Nat.mul_div_le.\n}\nrewrite <- Nat.add_sub_swap. 2: {\n  apply Nat.mul_le_mono_r.\n  rewrite <- Nat.mul_assoc.\n  apply Nat.mul_le_mono_l.\n  subst qm.\n  now apply Nat.mul_div_le.\n}\nrewrite <- (Nat.mod_add _ (qm * v)); [ | easy ].\nreplace (qm * v * (m * n)) with (n * m * qm * v) by flia.\nrewrite Nat.sub_add. 2: {\n  transitivity (n * a * v). 2: {\n    remember (m * a * (n - 1) * u); flia.\n  }\n  apply Nat.mul_le_mono_r.\n  rewrite <- Nat.mul_assoc.\n  apply Nat.mul_le_mono_l.\n  subst qm.\n  now apply Nat.mul_div_le.\n}\nrewrite Nat.mul_sub_distr_l, Nat.mul_1_r.\nrewrite Nat.mul_sub_distr_r.\nrewrite Nat.add_sub_assoc. 2: {\n  apply Nat.mul_le_mono_r.\n  rewrite <- Nat.mul_assoc.\n  apply Nat.mul_le_mono_l.\n  destruct n; [ easy | ].\n  rewrite Nat.mul_succ_r; flia.\n}\nrewrite (Nat.mul_shuffle0 m a u).\nrewrite Hmng.\nrewrite Nat.mul_add_distr_r, Nat.mul_1_l.\nrewrite Nat.add_comm.\nrewrite Nat.sub_add_distr.\nrewrite (Nat.mul_shuffle0 n a v).\nrewrite Nat.add_sub.\nrewrite <- (Nat.mod_add _ a); [ | easy ].\nrewrite <- Nat.add_sub_swap. 2: {\n  destruct m; [ easy | ].\n  destruct n; [ easy | ].\n  destruct u; [ rewrite Nat.mul_comm in Hmng; cbn in Hmng; flia Hmng | ].\n  rewrite (Nat.mul_shuffle0 (S m)).\n  rewrite Nat.mul_shuffle0.\n  cbn.\n  remember ((u + (n + m * S n) * S u) * a).\n  flia.\n}\nrewrite <- Nat.add_sub_assoc. 2: {\n  destruct m; [ easy | ].\n  destruct n; [ easy | ].\n  rewrite Nat.mul_comm; cbn.\n  remember (n + m * S n); flia.\n}\nreplace a with (a * 1) at 3 by flia.\nrewrite <- Nat.mul_sub_distr_l.\nrewrite Nat.add_comm.\nreplace (m * a * n * u) with (a * u * (m * n)) by flia.\nrewrite Nat.mod_add; [ | easy ].\napply in_seq in Ha.\nreplace (1 + (m * n - 1)) with (m * n) in Ha by flia Hmn.\nrewrite Nat_mul_pred_r_mod; [ | easy | easy ].\nrewrite Nat_sub_sub_distr. 2: {\n  split; [ | easy ].\n  now apply Nat.lt_le_incl.\n}\nnow rewrite Nat.sub_diag.\nQed.\n\nTheorem prod_coprimes'_coprimes'_mul_prod : ∀ m n,\n  n ≠ 0\n  → Nat.gcd m n = 1\n  → ∀ x y, x < m → y < n\n  → prod_copr_of_copr_mul m n\n       (copr_mul_of_prod_copr m n (x, y)) = (x, y).\nProof.\nintros * Hnz Hgmn * Hxm Hyn.\nassert (Hmz : m ≠ 0) by flia Hxm.\nmove Hmz before n.\nunfold copr_mul_of_prod_copr.\nunfold prod_copr_of_copr_mul.\nremember (gcd_and_bezout m n) as gb eqn:Hgb.\nsymmetry in Hgb.\ndestruct gb as (g & u & v); cbn.\nspecialize (gcd_and_bezout_prop m n g u v Hmz Hgb) as (Hmng & Hg).\nrewrite Hgmn in Hg; subst g.\nremember (n * x * v + m * (n - 1) * y * u) as p eqn:Hp.\nf_equal. {\n  rewrite Nat.mod_mul_r; [ | easy | easy ].\n  rewrite Nat.sub_add_distr.\n  rewrite <- (Nat.mod_add _ ((p / m) mod n)); [ | easy ].\n  rewrite (Nat.mul_comm _ m).\n  rewrite Nat.sub_add. 2: {\n    apply Nat.le_add_le_sub_r.\n    replace (m * n) with (m * (n - 1) + m). 2: {\n      rewrite Nat.mul_sub_distr_l, Nat.mul_1_r.\n      apply Nat.sub_add.\n      destruct n; [ easy | ].\n      rewrite Nat.mul_succ_r; flia.\n    }\n    apply Nat.add_le_mono. {\n      apply Nat.mul_le_mono_l.\n      rewrite Nat.sub_1_r.\n      apply Nat.lt_le_pred.\n      now apply Nat.mod_upper_bound.\n    } {\n      now apply Nat.lt_le_incl, Nat.mod_upper_bound.\n    }\n  }\n  rewrite Hp.\n  do 2 rewrite <- (Nat.mul_assoc m).\n  rewrite Nat_mod_add_r_mul_l; [ | easy ].\n  rewrite Nat.mul_shuffle0.\n  replace (n * v) with (m * u - 1) by flia Hmng.\n  rewrite Nat.mul_sub_distr_r, Nat.mul_1_l.\n  rewrite <- (Nat.mod_add (m * u * x - x) x); [ | easy ].\n  rewrite <- Nat.add_sub_swap. 2: {\n    destruct m; [ easy | ].\n    destruct u; [ now rewrite Nat.mul_0_r, Nat.add_1_r in Hmng | ].\n    cbn.\n    apply Nat.le_sub_le_add_l.\n    rewrite Nat.sub_diag.\n    apply Nat.le_0_l.\n  }\n  rewrite <- Nat.add_sub_assoc. 2: {\n    destruct m; [ easy | ].\n    rewrite Nat.mul_succ_r; flia.\n  }\n  replace x with (x * 1) at 3 by flia.\n  rewrite <- Nat.mul_sub_distr_l.\n  rewrite Nat.add_comm, <- Nat.mul_assoc.\n  rewrite Nat_mod_add_r_mul_l; [ | easy ].\n  rewrite <- (Nat.mod_add _ ((x * (m - 1)) mod m)); [ | easy ].\n  rewrite <- Nat.add_sub_swap. 2: {\n    transitivity (pred m). 2: {\n      destruct n; [ easy | ].\n      rewrite Nat.mul_succ_r; flia.\n    }\n    apply Nat.lt_le_pred.\n    now apply Nat.mod_upper_bound.\n  }\n  remember ((x * (m - 1)) mod m) as a.\n  rewrite <- Nat.add_sub_assoc. 2: {\n    destruct m; [ easy | ].\n    rewrite Nat.mul_succ_r; flia.\n  }\n  replace a with (a * 1) at 2 by flia.\n  rewrite <- Nat.mul_sub_distr_l.\n  rewrite Nat.add_comm.\n  rewrite Nat_mod_add_r_mul_l; [ | easy ].\n  subst a.\n  rewrite Nat.mul_mod_idemp_l; [ | easy ].\n  rewrite <- Nat.mul_assoc.\n  rewrite <- Nat.pow_2_r.\n  rewrite Nat_sqr_sub; [ | flia Hmz ].\n  rewrite Nat.pow_1_l, Nat.mul_1_r, Nat.pow_2_r.\n  rewrite <- Nat.mul_mod_idemp_r; [ | easy ].\n  rewrite <- (Nat.mod_add (m * m + 1 - 2 * m) 2); [ | easy ].\n  rewrite Nat.sub_add. 2: {\n    destruct m; [ easy | ].\n    destruct m; [ easy | ].\n    cbn; remember (m * (S (S m))); flia.\n  }\n  rewrite Nat.add_comm, Nat.mod_add; [ | easy ].\n  rewrite Nat.mul_mod_idemp_r; [ | easy ].\n  rewrite Nat.mul_1_r.\n  now apply Nat.mod_small.\n} {\n  rewrite Nat.mul_comm at 2.\n  rewrite Nat.mod_mul_r; [ | easy | easy ].\n  rewrite Nat.sub_add_distr.\n  rewrite <- (Nat.mod_add _ ((p / n) mod m)); [ | easy ].\n  rewrite (Nat.mul_comm n).\n  rewrite Nat.sub_add. 2: {\n    apply Nat.le_add_le_sub_r.\n    replace (m * n) with (n * (m - 1) + n). 2: {\n      rewrite Nat.mul_sub_distr_l, Nat.mul_1_r.\n      rewrite Nat.mul_comm.\n      apply Nat.sub_add.\n      destruct m; [ easy | ].\n      rewrite Nat.mul_succ_l; flia.\n    }\n    apply Nat.add_le_mono. {\n      rewrite Nat.mul_comm.\n      apply Nat.mul_le_mono_l.\n      rewrite Nat.sub_1_r.\n      apply Nat.lt_le_pred.\n      now apply Nat.mod_upper_bound.\n    } {\n      now apply Nat.lt_le_incl, Nat.mod_upper_bound.\n    }\n  }\n  rewrite Hp.\n  rewrite Nat.add_comm.\n  rewrite <- (Nat.mul_assoc n).\n  rewrite Nat_mod_add_r_mul_l; [ | easy ].\n  rewrite Nat.mul_shuffle0.\n  rewrite (Nat.mul_shuffle0 m).\n  rewrite Hmng.\n  rewrite Nat.mul_add_distr_r, Nat.mul_1_l.\n  rewrite Nat.mul_add_distr_r.\n  do 2 rewrite <- Nat.mul_assoc.\n  rewrite Nat.add_comm.\n  rewrite Nat_mod_add_r_mul_l; [ | easy ].\n  rewrite Nat.mul_sub_distr_r, Nat.mul_1_l.\n  rewrite <- (Nat.mod_add (n * y - y) y); [ | easy ].\n  rewrite <- Nat.add_sub_swap. 2: {\n    destruct n; [ easy | cbn; flia ].\n  }\n  rewrite <- Nat.add_sub_assoc. 2: {\n    rewrite Nat.mul_comm.\n    destruct n; [ easy | cbn; flia ].\n  }\n  rewrite Nat.add_comm.\n  rewrite Nat_mod_add_r_mul_l; [ | easy ].\n  replace y with (y * 1) at 2 by flia.\n  rewrite <- Nat.mul_sub_distr_l.\n  rewrite <- (Nat.mod_add _ ((y * (n - 1)) mod n)); [ | easy ].\n  rewrite <- Nat.add_sub_swap. 2: {\n    transitivity (pred n). 2: {\n      destruct m; [ easy | ].\n      rewrite Nat.mul_succ_l; flia.\n    }\n    apply Nat.lt_le_pred.\n    now apply Nat.mod_upper_bound.\n  }\n  remember ((y * (n - 1)) mod n) as a.\n  rewrite <- Nat.add_sub_assoc. 2: {\n    destruct n; [ easy | ].\n    rewrite Nat.mul_succ_r; flia.\n  }\n  replace a with (a * 1) at 2 by flia.\n  rewrite <- Nat.mul_sub_distr_l.\n  rewrite Nat.add_comm.\n  rewrite Nat.mod_add; [ | easy ].\n  subst a.\n  rewrite Nat.mul_mod_idemp_l; [ | easy ].\n  rewrite <- Nat.mul_assoc.\n  rewrite <- Nat.pow_2_r.\n  rewrite Nat_sqr_sub; [ | flia Hnz ].\n  rewrite Nat.pow_1_l, Nat.mul_1_r, Nat.pow_2_r.\n  rewrite <- Nat.mul_mod_idemp_r; [ | easy ].\n  rewrite <- (Nat.mod_add (n * n + 1 - 2 * n) 2); [ | easy ].\n  rewrite Nat.sub_add. 2: {\n    destruct n; [ easy | ].\n    destruct n; [ easy | ].\n    cbn; remember (n * (S (S n))); flia.\n  }\n  rewrite Nat.add_comm, Nat.mod_add; [ | easy ].\n  rewrite Nat.mul_mod_idemp_r; [ | easy ].\n  rewrite Nat.mul_1_r.\n  now apply Nat.mod_small.\n}\nQed.\n\nTheorem φ'_multiplicative : ∀ m n,\n  2 ≤ m\n  → 2 ≤ n\n  → Nat.gcd m n = 1\n  → φ' (m * n) = φ' m * φ' n.\nProof.\nintros * H2m H2n Hg.\nunfold φ'.\nrewrite <- prod_length.\napply\n  (bijection_same_length (prod_copr_of_copr_mul m n)\n     (copr_mul_of_prod_copr m n)). {\n  unfold coprimes'.\n  apply NoDup_filter, seq_NoDup.\n} {\n  apply NoDup_prod; apply NoDup_filter, seq_NoDup.\n} {\n  intros a Ha.\n  now apply prod_copr_of_copr_mul_in_prod.\n} {\n  intros b Hb.\n  now apply copr_mul_of_prod_copr_in_coprimes'.\n} {\n  intros a Ha.\n  apply coprimes'_mul_prod_coprimes'; [ flia H2m | flia H2n | easy | ].\n  now apply filter_In in Ha.\n} {\n  intros (x, y) Hxy.\n  apply in_prod_iff in Hxy.\n  destruct Hxy as (Hx, Hy).\n  apply prod_coprimes'_coprimes'_mul_prod; [ flia H2n | easy | | ]. {\n    apply filter_In in Hx.\n    destruct Hx as (Hx, _).\n    apply in_seq in Hx.\n    flia Hx.\n  } {\n    apply filter_In in Hy.\n    destruct Hy as (Hy, _).\n    apply in_seq in Hy.\n    flia Hy.\n  }\n}\nQed.\n\n(* Euler's theorem *)\n\nRequire Import Primes.\n\nTheorem different_coprimes'_all_different_multiples : ∀ n a,\n  a ∈ coprimes' n\n  → ∀ i j,\n  i ∈ coprimes' n\n  → j ∈ coprimes' n\n  → i ≠ j\n  → (i * a) mod n ≠ (j * a) mod n.\nProof.\n(* like smaller_than_prime_all_different_multiples but more general *)\nintros * Ha * Hi Hj Hij.\nintros Haa; symmetry in Haa.\napply in_coprimes'_iff in Ha.\napply in_coprimes'_iff in Hi.\napply in_coprimes'_iff in Hj.\ndestruct Ha as (Ha, Hna).\ndestruct Hi as (Hi, Hni).\ndestruct Hj as (Hj, Hnj).\nassert\n  (H : ∀ i j, i ∈ seq 1 (n - 1) → j ∈ seq 1 (n - 1) → i < j →\n   (j * a) mod n ≠ (i * a) mod n). {\n  clear i j Hi Hj Hni Hnj Hij Haa.\n  intros * Hi Hj Hilj Haa.\n  apply in_seq in Hi.\n  apply in_seq in Hj.\n  apply Nat_mul_mod_cancel_r in Haa; [ | now rewrite Nat.gcd_comm ].\n  rewrite Nat.mod_small in Haa; [ | flia Hj ].\n  rewrite Nat.mod_small in Haa; [ | flia Hi ].\n  flia Hilj Haa.\n}\ndestruct (lt_dec i j) as [Hilj| Hjli]. {\n  now revert Haa; apply H.\n} {\n  symmetry in Haa.\n  assert (Hilj : j < i) by flia Hij Hjli.\n  now revert Haa; apply H.\n}\nQed.\n\nTheorem coprimes'_mul_in_coprimes' : ∀ n i j,\n  i ∈ coprimes' n → j ∈ coprimes' n → (i * j) mod n ∈ coprimes' n.\nProof.\nintros * Hi Hj.\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]; [ now subst n | ].\napply in_coprimes'_iff in Hi.\napply in_coprimes'_iff in Hj.\ndestruct Hi as (Hi, Hgi).\ndestruct Hj as (Hj, Hgj).\napply in_seq in Hi.\napply in_seq in Hj.\napply in_coprimes'_iff.\nsplit. {\n  apply in_seq.\n  split. {\n    remember ((i * j) mod n) as a eqn:Ha; symmetry in Ha.\n    destruct a; [ | flia ].\n    apply Nat.mod_divide in Ha; [ | easy ].\n    apply Nat.gauss in Ha; [ | easy ].\n    destruct Ha as (k, Hk).\n    replace n with (1 * n) in Hgj by flia.\n    subst j.\n    rewrite Nat.gcd_mul_mono_r in Hgj.\n    apply Nat.eq_mul_1 in Hgj.\n    destruct Hgj as (H1k, Hn); subst n.\n    flia Hi.\n  } {\n    rewrite Nat.add_comm, Nat.sub_add; [ | flia Hnz ].\n    now apply Nat.mod_upper_bound.\n  }\n} {\n  rewrite Nat.gcd_comm, Nat.gcd_mod; [ | easy ].\n  now apply Nat_gcd_1_mul_r.\n}\nQed.\n\nTheorem NoDup_coprimes' : ∀ n, NoDup (coprimes' n).\nProof.\nintros.\nunfold coprimes'.\napply NoDup_filter, seq_NoDup.\nQed.\n\nTheorem gcd_prod_coprimes' : ∀ n,\n  Nat.gcd n (fold_left Nat.mul (coprimes' n) 1) = 1.\nProof.\nintros.\nassert (H : ∀ a, a ∈ coprimes' n → Nat.gcd n a = 1). {\n  intros * H.\n  now apply in_coprimes'_iff in H.\n}\nremember (coprimes' n) as l eqn:Hl; symmetry in Hl; clear Hl.\ninduction l as [| a l]; intros; [ apply Nat.gcd_1_r | ].\ncbn; rewrite Nat.add_0_r.\nrewrite fold_left_mul_from_1.\napply Nat_gcd_1_mul_r; [ now apply H; left | ].\napply IHl.\nintros b Hb.\nnow apply H; right.\nQed.\n\nTheorem euler_fermat_little : ∀ n a,\n  n ≠ 0 → a ≠ 0 → Nat.gcd a n = 1 → a ^ φ' n ≡ 1 mod n.\nProof.\nintros * Hnz Haz Hg.\n(* https://wstein.org/edu/2007/spring/ent/ent-html/node19.html#sec:flittle *)\ndestruct (Nat.eq_dec n 1) as [Hn1| Hn1]; [ now subst n | ].\nassert (Ha : a mod n ∈ coprimes' n). {\n  apply in_coprimes'_iff.\n  rewrite Nat.gcd_comm, Nat.gcd_mod; [ | easy ].\n  rewrite Nat.gcd_comm.\n  split; [ | easy ].\n  apply in_seq.\n  rewrite Nat.add_comm, Nat.sub_add; [ | flia Hnz ].\n  split. {\n    remember (a mod n) as b eqn:Hb; symmetry in Hb.\n    destruct b; [ | flia ].\n    apply Nat.mod_divides in Hb; [ | easy ].\n    replace n with (n * 1) in Hg by flia.\n    destruct Hb as (k, Hk); subst a.\n    rewrite Nat.gcd_mul_mono_l in Hg.\n    now apply Nat.eq_mul_1 in Hg.\n  } {\n    now apply Nat.mod_upper_bound.\n  }\n}\nrewrite <- Nat_mod_pow_mod.\nassert\n  (H1 : ∀ i j, i ∈ coprimes' n → j ∈ coprimes' n\n   → i ≠ j → (i * a) mod n ≠ (j * a) mod n). {\n  intros * Hi Hj Hij.\n  rewrite <- (Nat.mul_mod_idemp_r i); [ | easy ].\n  rewrite <- (Nat.mul_mod_idemp_r j); [ | easy ].\n  now apply different_coprimes'_all_different_multiples.\n}\nassert (Hcc : ∀ i, i ∈ coprimes' n → (i * a) mod n ∈ coprimes' n). {\n  intros i Hi.\n  rewrite <- Nat.mul_mod_idemp_r; [ | easy ].\n  now apply coprimes'_mul_in_coprimes'.\n}\nassert\n  (Hperm :\n     Permutation (map (λ i, (i * a) mod n) (coprimes' n)) (coprimes' n)). {\n  apply NoDup_Permutation_bis; try apply NoDup_coprimes'; cycle 1. {\n    now rewrite map_length.\n  } {\n    intros i Hi.\n    apply in_map_iff in Hi.\n    destruct Hi as (j & Hji & Hj).\n    rewrite <- Hji.\n    rewrite <- Nat.mul_mod_idemp_r; [ | easy ].\n    now apply coprimes'_mul_in_coprimes'.\n  } {\n    apply NoDup_map_iff with (d := 0).\n    intros * Hi Hj Hnth.\n    destruct (Nat.eq_dec i j) as [Heij| Heij]; [ easy | exfalso ].\n    revert Hnth.\n    apply H1; [ now apply nth_In | now apply nth_In | ].\n    specialize (NoDup_coprimes' n) as H2.\n    remember (coprimes' n) as l.\n    clear - Hi Hj Heij H2.\n    revert i j Hi Hj Heij.\n    induction l as [| a l]; intros; [ easy | ].\n    apply NoDup_cons_iff in H2.\n    destruct H2 as (Ha, Hnd).\n    intros H; cbn in H.\n    destruct i. {\n      destruct j; [ easy | ].\n      subst a; apply Ha.\n      cbn in Hj.\n      apply Nat.succ_lt_mono in Hj.\n      now apply nth_In.\n    }\n    destruct j. {\n      subst a; apply Ha.\n      cbn in Hi.\n      apply Nat.succ_lt_mono in Hi.\n      now apply nth_In.\n    }\n    cbn in Hi, Hj.\n    apply Nat.succ_lt_mono in Hi.\n    apply Nat.succ_lt_mono in Hj.\n    apply -> Nat.succ_inj_wd_neg in Heij.\n    revert H.\n    now apply IHl.\n  }\n}\nremember (λ i : nat, (i * a) mod n) as f eqn:Hf.\nremember (fold_left Nat.mul (map f (coprimes' n)) 1) as x eqn:Hx.\nremember (fold_left Nat.mul (coprimes' n) 1) as y eqn:Hy.\nassert (Hx1 : x mod n = y mod n). {\n  subst x y.\n  erewrite Permutation_fold_mul; [ easy | apply Hperm ].\n}\nassert (Hx2 : x mod n = (y * a ^ φ' n) mod n). {\n  subst x y; rewrite Hf.\n  rewrite <- (map_map (λ i, i * a) (λ j, j mod n)).\n  rewrite fold_left_mul_map_mod.\n  now rewrite fold_left_mul_map_mul.\n}\nrewrite Hx2 in Hx1.\nreplace y with (y * 1) in Hx1 at 2 by flia.\napply Nat_mul_mod_cancel_l in Hx1. 2: {\n  rewrite Hy, Nat.gcd_comm.\n  apply gcd_prod_coprimes'.\n}\nnow rewrite Nat_mod_pow_mod.\nQed.\n\nTheorem prime_φ' : ∀ p, prime p → φ' p = p - 1.\nProof.\nintros * Hp.\nunfold φ'.\nunfold coprimes'.\nrewrite (filter_ext_in _ (λ d, true)). 2: {\n  intros a Ha.\n  apply Nat.eqb_eq.\n  apply in_seq in Ha.\n  rewrite Nat.add_comm, Nat.sub_add in Ha. 2: {\n    destruct p; [ easy | flia ].\n  }\n  now apply eq_gcd_prime_small_1.\n}\nclear Hp.\ndestruct p; [ easy | ].\nrewrite Nat.sub_succ, Nat.sub_0_r.\ninduction p; [ easy | ].\nrewrite <- (Nat.add_1_r p).\nrewrite seq_app.\nrewrite filter_app.\nnow rewrite app_length, IHp.\nQed.\n\nCorollary fermat_little_again : ∀ p,\n  prime p → ∀ a, 1 ≤ a < p → a ^ (p - 1) mod p = 1.\nProof.\nintros * Hp * Hap.\nrewrite <- prime_φ'; [ | easy ].\nreplace 1 with (1 mod p). 2: {\n  apply Nat.mod_1_l.\n  now apply prime_ge_2.\n}\napply euler_fermat_little; [ now intros H; subst p | flia Hap | ].\nrewrite Nat.gcd_comm.\nnow apply eq_gcd_prime_small_1.\nQed.\n\n(* proof of corollary above simpler than fermat_little, isn't it? *)\n", "meta": {"author": "taorunz", "repo": "euler", "sha": "5fcf1db4d5a68f0d55118fb2733cede2cc515a23", "save_path": "github-repos/coq/taorunz-euler", "path": "github-repos/coq/taorunz-euler/euler-5fcf1db4d5a68f0d55118fb2733cede2cc515a23/PTotient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7476102950966186}}
{"text": "Require Import GeoCoq.Tarski_dev.Definitions.\n\nSection Continuity_Defs.\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\n(** In this file, we introduce elementary continuity properties.\n    These properties are different variant to assert that the intersection\n    of line, segment and circles exists under some assumptions.\n    Adding one of these properties as axiom to the Tarski_2D type class gives us\n    a definition of ruler and compass geometry.\n    The links between these properties are in file elementary_continuity_props.v .\n\n    We also introduce other continuity properties.\n*)\n\n\n(** If there is a point P inside a circle, and Q outside then there is\n    a point Z of the segment PQ which is on the circle. *)\n\nDefinition segment_circle := forall A B P Q,\n  InCircle P A B ->\n  OutCircle Q A B ->\n  exists Z, Bet P Z Q /\\ OnCircle Z A B.\n\n(** Given a line UV which contains a point inside the circle, there is\n   a point of line UV which is on the circle. *)\n\nDefinition one_point_line_circle := forall A B U V P,\n  Col U V P -> U <> V -> Bet A P B ->\n  exists Z, Col U V Z /\\ OnCircle Z A B.\n\n(** Given a line UV which contains a point P inside the circle, there are\n  two points on line UV which belong to the circle and they are distinct if\n if P is strictly inside the circle. *)\n\nDefinition two_points_line_circle := forall A B U V P,\n  Col U V P -> U <> V -> Bet A P B ->\n  exists Z1 Z2, Col U V Z1 /\\ OnCircle Z1 A B /\\\n                Col U V Z2 /\\ OnCircle Z2 A B /\\\n                Bet Z1 P Z2 /\\ (P <> B -> Z1 <> Z2).\n\n(** Given two circles (A,B) and (C,D), if there are two points of (C,D)\n one inside and one outside (A,B) then there is a point of intersection\n of the two circles. *)\n\nDefinition circle_circle := forall A B C D P Q,\n  OnCircle P C D ->\n  OnCircle Q C D ->\n  InCircle P A B ->\n  OutCircle Q A B ->\n  exists Z, OnCircle Z A B /\\ OnCircle Z C D.\n\n(** Given two circles (A,B) and (C,D),\n   if there is a point of (A,B) which is inside (C,D)\n  and vice-versa, then there is a point of intersection of the two circles. *)\n\nDefinition circle_circle_bis := forall A B C D P Q,\n  OnCircle P C D ->\n  InCircle P A B ->\n  OnCircle Q A B ->\n  InCircle Q C D ->\n  exists Z, OnCircle Z A B /\\ OnCircle Z C D.\n\n(** A simplification of the previous statement we use in our axiom system. *)\n\nDefinition circle_circle_axiom := forall A B C D B' D',\n  Cong A B' A B -> Cong C D' C D ->\n  Bet A D' B -> Bet C B' D ->\n  exists Z, Cong A Z A B /\\ Cong C Z C D.\n\n(** Given two circles (A,B) and (C,D), if there are two points of (C,D)\n one inside and one outside (A,B) then there are two points of intersection\n of the two circles.\n They are distinct if the inside and outside properties are strict. *)\n\nDefinition circle_circle_two := forall A B C D P Q,\n  OnCircle P C D ->\n  OnCircle Q C D ->\n  InCircle P A B ->\n  OutCircle Q A B ->\n  exists Z1 Z2,\n    OnCircle Z1 A B /\\ OnCircle Z1 C D /\\\n    OnCircle Z2 A B /\\ OnCircle Z2 C D /\\\n    (InCircleS P A B -> OutCircleS Q A B -> Z1<>Z2).\n\n(** Proposition 22 from Euclid's Elements, Book I:\n \"Out of three straight lines, which are equal to three given straight lines, to construct a triangle:\n thus it is necessary that two of the straight lines taken together in any manner\n should be greater than the remaining one.\"\n*)\n\nDefinition euclid_s_prop_1_22 := forall A B C D E F A' B' C' D' E' F',\n  SumS A B C D E' F' -> SumS A B E F C' D' -> SumS C D E F A' B' ->\n  Le E F E' F' -> Le C D C' D' -> Le A B A' B' ->\n  exists P Q R, Cong P Q A B /\\ Cong P R C D /\\ Cong Q R E F.\n\n(*\nDefinition weak_cantor_s_axiom := forall (A B:nat -> Tpoint),\n  (forall n, Bet (A n) (A (S n)) (B (S n)) /\\ Bet (A (S n)) (B (S n)) (B n) /\\ A (S n) <> B (S n)) ->\n  exists X, forall n, Bet (A n) X (B n).\n*)\n\n(** Nested A B describes the fact that the sequences A and B form the end points\n of nested non-degenerate segments *)\n\nDefinition Nested (A B:nat -> Tpoint -> Prop) :=\n  (forall n, exists An Bn, A n An /\\ B n Bn) /\\\n  forall n An Am Bm Bn,\n    A n An -> A (S n) Am -> B (S n) Bm -> B n Bn -> Bet An Am Bm /\\ Bet Am Bm Bn /\\ Am <> Bm.\n\nDefinition cantor_s_axiom := forall A B, Nested A B ->\n  exists X, forall n An Bn, A n An -> B n Bn -> Bet An X Bn.\n\nDefinition dedekind_s_axiom := forall (Alpha Beta : Tpoint -> Prop),\n  (exists A, forall X Y, Alpha X -> Beta Y -> Bet A X Y) ->\n  (exists B, forall X Y, Alpha X -> Beta Y -> Bet X B Y).\n\nDefinition dedekind_variant := forall (Alpha Beta : Tpoint -> Prop) A C,\n  Alpha A -> Beta C -> (forall P, Out A P C -> Alpha P \\/ Beta P) ->\n  (forall X Y, Alpha X -> Beta Y -> Bet A X Y /\\ X <> Y) ->\n  (exists B, forall X Y, Alpha X -> Beta Y -> Bet X B Y).\n\n(** First-order formula *)\n\nInductive FOF : Prop -> Prop :=\n| eq_fof : forall A B:Tpoint, FOF (A = B)\n| bet_fof : forall A B C, FOF (Bet A B C)\n| cong_fof : forall A B C D, FOF (Cong A B C D)\n| not_fof : forall P, FOF P -> FOF (~ P)\n| and_fof : forall P Q, FOF P -> FOF Q -> FOF (P /\\ Q)\n| or_fof : forall P Q, FOF P -> FOF Q -> FOF (P \\/ Q)\n| implies_fof : forall P Q, FOF P -> FOF Q -> FOF (P -> Q)\n| forall_fof : forall P, (forall (A:Tpoint), FOF (P A)) -> FOF (forall A, P A)\n| exists_fof : forall P, (forall (A:Tpoint), FOF (P A)) -> FOF (exists A, P A).\n\nDefinition first_order_dedekind := forall Alpha Beta,\n  (forall X, FOF (Alpha X)) -> (forall Y, FOF (Beta Y)) ->\n  (exists A, forall X Y, Alpha X -> Beta Y -> Bet A X Y) ->\n  (exists B, forall X Y, Alpha X -> Beta Y -> Bet X B Y).\n\nDefinition archimedes_axiom := forall A B C D, A <> B -> Reach A B C D.\n\nDefinition aristotle_s_axiom := forall P Q A B C,\n  ~ Col A B C -> Acute A B C ->\n  exists X Y, Out B A X /\\ Out B C Y /\\ Per B X Y /\\ Lt P Q X Y.\n\nDefinition greenberg_s_axiom := forall P Q R A B C,\n  ~ Col A B C ->\n  Acute A B C -> Q <> R -> Per P Q R ->\n  exists S, LtA P S Q A B C /\\ Out Q S R.\n\nEnd Continuity_Defs.\n\nSection Completeness.\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\n(** These are formalizations of Hilbert's axiom of completeness:\n    \"To a system of points, straight lines, and planes,\n    it is impossible to add other elements in such a manner that the system thus generalized \n    shall form a new geometry obeying all of the five groups of axioms.\n    In other words, the elements of geometry form a system which is not susceptible of extension,\n    if we regard the five groups of axioms as valid.\"\n    Our formalizations only work respectively for 2 and 3-dimensional spaces:\n    it assumes the extension to be respectively 2 and 3-dimensional\n    because we have not defined the fact for two spaces to have the same dimension.\n*)\n\nDefinition inj {T1 T2:Type} (f:T1->T2) := forall A B, f A = f B -> A = B.\n\nDefinition pres_bet {Tm: Tarski_neutral_dimensionless}\n  (f : @Tpoint Tn -> @Tpoint Tm) := forall A B C, Bet A B C -> Bet (f A) (f B) (f C).\n\nDefinition pres_cong {Tm: Tarski_neutral_dimensionless}\n  (f : @Tpoint Tn -> @Tpoint Tm) := forall A B C D, Cong A B C D -> Cong (f A) (f B) (f C) (f D).\n\nDefinition extension {Tm: Tarski_neutral_dimensionless} f := inj f /\\ pres_bet f /\\ pres_cong f.\n\n\nDefinition completeness_for_planes := forall (Tm: Tarski_neutral_dimensionless)\n  (Tm2 : Tarski_neutral_dimensionless_with_decidable_point_equality Tm)\n  (M : Tarski_2D Tm2)\n  (f : @Tpoint Tn -> @Tpoint Tm),\n  @archimedes_axiom Tm ->\n  extension f ->\n  forall A, exists B, f B = A.\n\nDefinition completeness_for_3d_spaces := forall (Tm: Tarski_neutral_dimensionless)\n  (Tm2 : Tarski_neutral_dimensionless_with_decidable_point_equality Tm)\n  (M : Tarski_3D Tm2)\n  (f : @Tpoint Tn -> @Tpoint Tm),\n  @archimedes_axiom Tm ->\n  extension f ->\n  forall A, exists B, f B = A.\n\n(** This is a formalization of Hilbert's axiom of line completeness:\n    \"An extension of a set of points on a line with its order and congruence relations\n    that would preserve the relations existing among the original elements\n    as well as the fundamental properties of line order and congruence [of Archimedean neutral geometry]\n    is impossible.\"\n*)\n\nDefinition inj_line {T:Type} (f:Tpoint->T) P Q := forall A B, Col P Q A -> Col P Q B ->\n  f A = f B -> A = B.\n\nDefinition pres_bet_line {Tm: Tarski_neutral_dimensionless}\n  (f : @Tpoint Tn -> @Tpoint Tm) P Q := forall A B C, Col P Q A -> Col P Q B -> Col P Q C ->\n  Bet A B C -> Bet (f A) (f B) (f C).\n\nDefinition pres_cong_line {Tm: Tarski_neutral_dimensionless}\n  (f : @Tpoint Tn -> @Tpoint Tm) P Q := forall A B C D,\n  Col P Q A -> Col P Q B -> Col P Q C -> Col P Q D ->\n  Cong A B C D -> Cong (f A) (f B) (f C) (f D).\n\nDefinition line_extension {Tm: Tarski_neutral_dimensionless} f P Q :=\n  P <> Q /\\ inj_line f P Q /\\ pres_bet_line f P Q /\\ pres_cong_line f P Q.\n\n\nDefinition line_completeness := forall (Tm: Tarski_neutral_dimensionless)\n  (Tm2 : Tarski_neutral_dimensionless_with_decidable_point_equality Tm)\n  P Q\n  (f : @Tpoint Tn -> @Tpoint Tm),\n  @archimedes_axiom Tm ->\n  line_extension f P Q ->\n  forall A, Col (f P) (f Q) A -> exists B, Col P Q B /\\ f B = A.\n\nEnd Completeness.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Axioms/continuity_axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7475818694235646}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Import ZAxioms ZMulOrder ZSgnAbs NZDiv.\n\n(** * Euclidean Division for integers, Euclid convention\n\n    We use here the \"usual\" formulation of the Euclid Theorem\n    [forall a b, b<>0 -> exists b q, a = b*q+r /\\ 0 < r < |b| ]\n\n    The outcome of the modulo function is hence always positive.\n    This corresponds to convention \"E\" in the following paper:\n\n    R. Boute, \"The Euclidean definition of the functions div and mod\",\n    ACM Transactions on Programming Languages and Systems,\n    Vol. 14, No.2, pp. 127-144, April 1992.\n\n    See files [ZDivTrunc] and [ZDivFloor] for others conventions.\n\n    We simply extend NZDiv with a bound for modulo that holds\n    regardless of the sign of a and b. This new specification\n    subsume mod_bound_pos, which nonetheless stays there for\n    subtyping. Note also that ZAxiomSig now already contain\n    a div and a modulo (that follow the Floor convention).\n    We just ignore them here.\n*)\n\nModule Type EuclidSpec (Import A : ZAxiomsSig')(Import B : DivMod A).\n Axiom mod_always_pos : forall a b, b ~= 0 -> 0 <= B.modulo a b < abs b.\nEnd EuclidSpec.\n\nModule Type ZEuclid (Z:ZAxiomsSig) := NZDiv.NZDiv Z <+ EuclidSpec Z.\n\nModule ZEuclidProp\n (Import A : ZAxiomsSig')\n (Import B : ZMulOrderProp A)\n (Import C : ZSgnAbsProp A B)\n (Import D : ZEuclid A).\n\n (** We put notations in a scope, to avoid warnings about\n     redefinitions of notations *)\n Infix \"/\" := D.div : euclid.\n Infix \"mod\" := D.modulo : euclid.\n Local Open Scope euclid.\n\n Module Import Private_NZDiv := Nop <+ NZDivProp A D B.\n\n(** Another formulation of the main equation *)\n\nLemma mod_eq :\n forall a b, b~=0 -> a mod b == a - b*(a/b).\nProof.\nintros.\nrewrite <- add_move_l.\nsymmetry. now apply div_mod.\nQed.\n\nLtac pos_or_neg a :=\n let LT := fresh \"LT\" in\n let LE := fresh \"LE\" in\n destruct (le_gt_cases 0 a) as [LE|LT]; [|rewrite <- opp_pos_neg in LT].\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique : forall b q1 q2 r1 r2 : t,\n  0<=r1<abs b -> 0<=r2<abs b ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof.\nintros b q1 q2 r1 r2 Hr1 Hr2 EQ.\npos_or_neg b.\nrewrite abs_eq in * by trivial.\napply div_mod_unique with b; trivial.\nrewrite abs_neq' in * by auto using lt_le_incl.\nrewrite eq_sym_iff. apply div_mod_unique with (-b); trivial.\nrewrite 2 mul_opp_l.\nrewrite add_move_l, sub_opp_r.\nrewrite <-add_assoc.\nsymmetry. rewrite add_move_l, sub_opp_r.\nnow rewrite (add_comm r2), (add_comm r1).\nQed.\n\nTheorem div_unique:\n forall a b q r, 0<=r<abs b -> a == b*q + r -> q == a/b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0).\n pos_or_neg b.\n rewrite abs_eq in Hr; intuition; order.\n rewrite <- opp_0, eq_opp_r. rewrite abs_neq' in Hr; intuition; order.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\nnow apply mod_always_pos.\nnow rewrite <- div_mod.\nQed.\n\nTheorem mod_unique:\n forall a b q r, 0<=r<abs b -> a == b*q + r -> r == a mod b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0).\n pos_or_neg b.\n rewrite abs_eq in Hr; intuition; order.\n rewrite <- opp_0, eq_opp_r. rewrite abs_neq' in Hr; intuition; order.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\nnow apply mod_always_pos.\nnow rewrite <- div_mod.\nQed.\n\n(** Sign rules *)\n\nLemma div_opp_r : forall a b, b~=0 -> a/(-b) == -(a/b).\nProof.\nintros. symmetry.\napply div_unique with (a mod b).\nrewrite abs_opp; now apply mod_always_pos.\nrewrite mul_opp_opp; now apply div_mod.\nQed.\n\nLemma mod_opp_r : forall a b, b~=0 -> a mod (-b) == a mod b.\nProof.\nintros. symmetry.\napply mod_unique with (-(a/b)).\nrewrite abs_opp; now apply mod_always_pos.\nrewrite mul_opp_opp; now apply div_mod.\nQed.\n\nLemma div_opp_l_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a)/b == -(a/b).\nProof.\nintros a b Hb Hab. symmetry.\napply div_unique with (-(a mod b)).\nrewrite Hab, opp_0. split; [order|].\npos_or_neg b; [rewrite abs_eq | rewrite abs_neq']; order.\nnow rewrite mul_opp_r, <-opp_add_distr, <-div_mod.\nQed.\n\nLemma div_opp_l_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a)/b == -(a/b)-sgn b.\nProof.\nintros a b Hb Hab. symmetry.\napply div_unique with (abs b -(a mod b)).\nrewrite lt_sub_lt_add_l.\nrewrite <- le_add_le_sub_l. nzsimpl.\nrewrite <- (add_0_l (abs b)) at 2.\nrewrite <- add_lt_mono_r.\ndestruct (mod_always_pos a b); intuition order.\nrewrite <- 2 add_opp_r, mul_add_distr_l, 2 mul_opp_r.\nrewrite sgn_abs.\nrewrite add_shuffle2, add_opp_diag_l; nzsimpl.\nrewrite <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma mod_opp_l_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a) mod b == 0.\nProof.\nintros a b Hb Hab. symmetry.\napply mod_unique with (-(a/b)).\nsplit; [order|now rewrite abs_pos].\nnow rewrite <-opp_0, <-Hab, mul_opp_r, <-opp_add_distr, <-div_mod.\nQed.\n\nLemma mod_opp_l_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a) mod b == abs b - (a mod b).\nProof.\nintros a b Hb Hab. symmetry.\napply mod_unique with (-(a/b)-sgn b).\nrewrite lt_sub_lt_add_l.\nrewrite <- le_add_le_sub_l. nzsimpl.\nrewrite <- (add_0_l (abs b)) at 2.\nrewrite <- add_lt_mono_r.\ndestruct (mod_always_pos a b); intuition order.\nrewrite <- 2 add_opp_r, mul_add_distr_l, 2 mul_opp_r.\nrewrite sgn_abs.\nrewrite add_shuffle2, add_opp_diag_l; nzsimpl.\nrewrite <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma div_opp_opp_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a)/(-b) == a/b.\nProof.\nintros. now rewrite div_opp_r, div_opp_l_z, opp_involutive.\nQed.\n\nLemma div_opp_opp_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a)/(-b) == a/b + sgn(b).\nProof.\nintros. rewrite div_opp_r, div_opp_l_nz by trivial.\nnow rewrite opp_sub_distr, opp_involutive.\nQed.\n\nLemma mod_opp_opp_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a) mod (-b) == 0.\nProof.\nintros. now rewrite mod_opp_r, mod_opp_l_z.\nQed.\n\nLemma mod_opp_opp_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a) mod (-b) == abs b - a mod b.\nProof.\nintros. now rewrite mod_opp_r, mod_opp_l_nz.\nQed.\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, a~=0 -> a/a == 1.\nProof.\nintros. symmetry. apply div_unique with 0.\nsplit; [order|now rewrite abs_pos].\nnow nzsimpl.\nQed.\n\nLemma mod_same : forall a, a~=0 -> a mod a == 0.\nProof.\nintros.\nrewrite mod_eq, div_same by trivial. nzsimpl. apply sub_diag.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, 0<=a<b -> a/b == 0.\nProof. exact div_small. Qed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, 0<=a<b -> a mod b == a.\nProof. exact mod_small. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, a~=0 -> 0/a == 0.\nProof.\nintros. pos_or_neg a. apply div_0_l; order.\napply opp_inj. rewrite <- div_opp_r, opp_0 by trivial. now apply div_0_l.\nQed.\n\nLemma mod_0_l: forall a, a~=0 -> 0 mod a == 0.\nProof.\nintros; rewrite mod_eq, div_0_l; now nzsimpl.\nQed.\n\nLemma div_1_r: forall a, a/1 == a.\nProof.\nintros. symmetry. apply div_unique with 0.\nassert (H:=lt_0_1); rewrite abs_pos; intuition; order.\nnow nzsimpl.\nQed.\n\nLemma mod_1_r: forall a, a mod 1 == 0.\nProof.\nintros. rewrite mod_eq, div_1_r; nzsimpl; auto using sub_diag.\napply neq_sym, lt_neq; apply lt_0_1.\nQed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof. exact div_1_l. Qed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof. exact mod_1_l. Qed.\n\nLemma div_mul : forall a b, b~=0 -> (a*b)/b == a.\nProof.\nintros. symmetry. apply div_unique with 0.\nsplit; [order|now rewrite abs_pos].\nnzsimpl; apply mul_comm.\nQed.\n\nLemma mod_mul : forall a b, b~=0 -> (a*b) mod b == 0.\nProof.\nintros. rewrite mod_eq, div_mul by trivial. rewrite mul_comm; apply sub_diag.\nQed.\n\nTheorem div_unique_exact a b q: b~=0 -> a == b*q -> q == a/b.\nProof.\n intros Hb H. rewrite H, mul_comm. symmetry. now apply div_mul.\nQed.\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, 0<=a -> b~=0 -> a mod b <= a.\nProof.\nintros. pos_or_neg b. apply mod_le; order.\nrewrite <- mod_opp_r by trivial. apply mod_le; order.\nQed.\n\nTheorem div_pos : forall a b, 0<=a -> 0<b -> 0<= a/b.\nProof. exact div_pos. Qed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof. exact div_str_pos. Qed.\n\nLemma div_small_iff : forall a b, b~=0 -> (a/b==0 <-> 0<=a<abs b).\nProof.\nintros a b Hb.\nsplit.\nintros EQ.\nrewrite (div_mod a b Hb), EQ; nzsimpl.\nnow apply mod_always_pos.\nintros. pos_or_neg b.\napply div_small.\nnow rewrite <- (abs_eq b).\napply opp_inj; rewrite opp_0, <- div_opp_r by trivial.\napply div_small.\nrewrite <- (abs_neq' b) by order. trivial.\nQed.\n\nLemma mod_small_iff : forall a b, b~=0 -> (a mod b == a <-> 0<=a<abs b).\nProof.\nintros.\nrewrite <- div_small_iff, mod_eq by trivial.\nrewrite sub_move_r, <- (add_0_r a) at 1. rewrite add_cancel_l.\nrewrite eq_sym_iff, eq_mul_0. tauto.\nQed.\n\n(** As soon as the divisor is strictly greater than 1,\n    the division is strictly decreasing. *)\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof. exact div_lt. Qed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, 0<c -> a<=b -> a/c <= b/c.\nProof.\nintros a b c Hc Hab.\nrewrite lt_eq_cases in Hab. destruct Hab as [LT|EQ];\n [|rewrite EQ; order].\nrewrite <- lt_succ_r.\nrewrite (mul_lt_mono_pos_l c) by order.\nnzsimpl.\nrewrite (add_lt_mono_r _ _ (a mod c)).\nrewrite <- div_mod by order.\napply lt_le_trans with b; trivial.\nrewrite (div_mod b c) at 1 by order.\nrewrite <- add_assoc, <- add_le_mono_l.\napply le_trans with (c+0).\nnzsimpl; destruct (mod_always_pos b c); try order.\nrewrite abs_eq in *; order.\nrewrite <- add_le_mono_l. destruct (mod_always_pos a c); order.\nQed.\n\n(** In this convention, [div] performs Rounding-Toward-Bottom\n    when divisor is positive, and Rounding-Toward-Top otherwise.\n\n    Since we cannot speak of rational values here, we express this\n    fact by multiplying back by [b], and this leads to a nice\n    unique statement.\n*)\n\nLemma mul_div_le : forall a b, b~=0 -> b*(a/b) <= a.\nProof.\nintros.\nrewrite (div_mod a b) at 2; trivial.\nrewrite <- (add_0_r (b*(a/b))) at 1.\nrewrite <- add_le_mono_l.\nnow destruct (mod_always_pos a b).\nQed.\n\n(** Giving a reversed bound is slightly more complex *)\n\nLemma mul_succ_div_gt: forall a b, 0<b -> a < b*(S (a/b)).\nProof.\nintros.\nnzsimpl.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_always_pos a b). order.\nrewrite abs_eq in *; order.\nQed.\n\nLemma mul_pred_div_gt: forall a b, b<0 -> a < b*(P (a/b)).\nProof.\nintros a b Hb.\nrewrite mul_pred_r, <- add_opp_r.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_always_pos a b). order.\nrewrite <- opp_pos_neg in Hb. rewrite abs_neq' in *; order.\nQed.\n\n(** NB: The three previous properties could be used as\n    specifications for [div]. *)\n\n(** Inequality [mul_div_le] is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, b~=0 -> (a == b*(a/b) <-> a mod b == 0).\nProof.\nintros.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- (add_0_r (b*(a/b))) at 2.\napply add_cancel_l.\nQed.\n\n(** Some additional inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, 0<b -> a < b*q -> a/b < q.\nProof.\nintros.\nrewrite (mul_lt_mono_pos_l b) by trivial.\napply le_lt_trans with a; trivial.\napply mul_div_le; order.\nQed.\n\nTheorem div_le_upper_bound:\n  forall a b q, 0<b -> a <= b*q -> a/b <= q.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\nTheorem div_le_lower_bound:\n  forall a b q, 0<b -> b*q <= a -> q <= a/b.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<=p -> 0<q<=r -> p/r <= p/q.\nProof. exact div_le_compat_l. Qed.\n\n(** * Relations between usual operations and mod and div *)\n\nLemma mod_add : forall a b c, c~=0 ->\n (a + b * c) mod c == a mod c.\nProof.\nintros.\nsymmetry.\napply mod_unique with (a/c+b); trivial.\nnow apply mod_always_pos.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add : forall a b c, c~=0 ->\n (a + b * c) / c == a / c + b.\nProof.\nintros.\napply (mul_cancel_l _ _ c); try order.\napply (add_cancel_r _ _ ((a+b*c) mod c)).\nrewrite <- div_mod, mod_add by order.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add_l: forall a b c, b~=0 ->\n (a * b + c) / b == a + c / b.\nProof.\n intros a b c. rewrite (add_comm _ c), (add_comm a).\n now apply div_add.\nQed.\n\n(** Cancellations. *)\n\n(** With the current convention, the following isn't always true\n    when [c<0]: [-3*-1 / -2*-1 = 3/2 = 1] while [-3/-2 = 2] *)\n\nLemma div_mul_cancel_r : forall a b c, b~=0 -> 0<c ->\n (a*c)/(b*c) == a/b.\nProof.\nintros.\nsymmetry.\napply div_unique with ((a mod b)*c).\n(* ineqs *)\nrewrite abs_mul, (abs_eq c) by order.\nrewrite <-(mul_0_l c), <-mul_lt_mono_pos_r, <-mul_le_mono_pos_r by trivial.\nnow apply mod_always_pos.\n(* equation *)\nrewrite (div_mod a b) at 1 by order.\nrewrite mul_add_distr_r.\nrewrite add_cancel_r.\nrewrite <- 2 mul_assoc. now rewrite (mul_comm c).\nQed.\n\nLemma div_mul_cancel_l : forall a b c, b~=0 -> 0<c ->\n (c*a)/(c*b) == a/b.\nProof.\nintros. rewrite !(mul_comm c); now apply div_mul_cancel_r.\nQed.\n\nLemma mul_mod_distr_l: forall a b c, b~=0 -> 0<c ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof.\nintros.\nrewrite <- (add_cancel_l _ _ ((c*b)* ((c*a)/(c*b)))).\nrewrite <- div_mod.\nrewrite div_mul_cancel_l by trivial.\nrewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\napply div_mod; order.\nrewrite <- neq_mul_0; intuition; order.\nQed.\n\nLemma mul_mod_distr_r: forall a b c, b~=0 -> 0<c ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof.\n intros. rewrite !(mul_comm _ c); now rewrite mul_mod_distr_l.\nQed.\n\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, n~=0 ->\n (a mod n) mod n == a mod n.\nProof.\nintros. rewrite mod_small_iff by trivial.\nnow apply mod_always_pos.\nQed.\n\nLemma mul_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite add_comm, (mul_comm n), (mul_comm _ b).\n rewrite mul_add_distr_l, mul_assoc.\n rewrite mod_add by trivial.\n now rewrite mul_comm.\nQed.\n\nLemma mul_mod_idemp_r : forall a b n, n~=0 ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof.\n intros. rewrite !(mul_comm a). now apply mul_mod_idemp_l.\nQed.\n\nTheorem mul_mod: forall a b n, n~=0 ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof.\n intros. now rewrite mul_mod_idemp_l, mul_mod_idemp_r.\nQed.\n\nLemma add_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite <- add_assoc, add_comm, mul_comm.\n now rewrite mod_add.\nQed.\n\nLemma add_mod_idemp_r : forall a b n, n~=0 ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof.\n intros. rewrite !(add_comm a). now apply add_mod_idemp_l.\nQed.\n\nTheorem add_mod: forall a b n, n~=0 ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof.\n intros. now rewrite add_mod_idemp_l, add_mod_idemp_r.\nQed.\n\n(** With the current convention, the following result isn't always\n    true with a negative intermediate divisor. For instance\n    [ 3/(-2)/(-2) = 1 <> 0 = 3 / (-2*-2) ] and\n    [ 3/(-2)/2 = -1 <> 0 = 3 / (-2*2) ]. *)\n\nLemma div_div : forall a b c, 0<b -> c~=0 ->\n (a/b)/c == a/(b*c).\nProof.\n intros a b c Hb Hc.\n apply div_unique with (b*((a/b) mod c) + a mod b).\n (* begin 0<= ... <abs(b*c) *)\n rewrite abs_mul.\n destruct (mod_always_pos (a/b) c), (mod_always_pos a b); try order.\n split.\n apply add_nonneg_nonneg; trivial.\n apply mul_nonneg_nonneg; order.\n apply lt_le_trans with (b*((a/b) mod c) + abs b).\n now rewrite <- add_lt_mono_l.\n rewrite (abs_eq b) by order.\n now rewrite <- mul_succ_r, <- mul_le_mono_pos_l, le_succ_l.\n (* end 0<= ... < abs(b*c) *)\n rewrite (div_mod a b) at 1 by order.\n rewrite add_assoc, add_cancel_r.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\nQed.\n\n(** Similarly, the following result doesn't always hold when [b<0].\n    For instance [3 mod (-2*-2)) = 3] while\n    [3 mod (-2) + (-2)*((3/-2) mod -2) = -1]. *)\n\nLemma mod_mul_r : forall a b c, 0<b -> c~=0 ->\n a mod (b*c) == a mod b + b*((a/b) mod c).\nProof.\n intros a b c Hb Hc.\n apply add_cancel_l with (b*c*(a/(b*c))).\n rewrite <- div_mod by (apply neq_mul_0; split; order).\n rewrite <- div_div by trivial.\n rewrite add_assoc, add_shuffle0, <- mul_assoc, <- mul_add_distr_l.\n rewrite <- div_mod by order.\n apply div_mod; order.\nQed.\n\nLemma mod_div: forall a b, b~=0 ->\n a mod b / b == 0.\nProof.\n intros a b Hb.\n rewrite div_small_iff by assumption.\n auto using mod_always_pos.\nQed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a/b) <= (c*a)/b.\nProof. exact div_mul_le. Qed.\n\n(** mod is related to divisibility *)\n\nLemma mod_divides : forall a b, b~=0 ->\n (a mod b == 0 <-> (b|a)).\nProof.\nintros a b Hb. split.\nintros Hab. exists (a/b). rewrite mul_comm.\n rewrite (div_mod a b Hb) at 1. rewrite Hab; now nzsimpl.\nintros (c,Hc). rewrite Hc. now apply mod_mul.\nQed.\n\nEnd ZEuclidProp.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Numbers/Integer/Abstract/ZDivEucl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.7475818513952741}}
{"text": "Require Export Coq.Arith.PeanoNat.\nInclude Coq.Init.Nat.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nDefinition nat_lt_dec : forall n m : nat, {n < m} + {~ (n < m)}.\n  intros n m.\n  destruct (n <? m) eqn:e.\n  left; apply Nat.ltb_lt; auto.\n  right; intro H. assert (true = false) by (transitivity (n <? m); [symmetry; apply Nat.ltb_lt; auto | auto]); discriminate H0.\nDefined.\n\nFixpoint list_max (default : nat) (l : list nat) {struct l}: nat :=\n  match l with\n  | [] => default\n  | x :: xs => max x (list_max default xs)\n  end.\n\nLemma list_max_larger : forall (x default : nat) (l : list nat),\n    x = default \\/ In x l -> x <= list_max default l.\nProof.\n  intros x default l H.\n  induction l.\n  destruct H; [simpl; rewrite H; reflexivity | inversion H].\n  destruct H; [|simpl in H; destruct H].\n  - simpl; transitivity (list_max default l);\n      [apply IHl; auto| apply Nat.le_max_r].\n  - simpl; rewrite H; apply Nat.le_max_l.\n  - simpl. transitivity (list_max default l); [apply IHl; auto | apply Nat.le_max_r].\nQed.\n\nFixpoint RemoveZeros (ns : list nat) : list nat :=\n  match ns with\n  | [] => []\n  | n :: ns' => if n =? 0\n               then RemoveZeros ns'\n               else n :: RemoveZeros ns'\n  end.\n\nLemma InRemoveZeros : forall (ns : list nat) (n : nat), In n (RemoveZeros ns) -> n <> 0 /\\ In n ns.\nProof.\n  intros ns n H.\n  induction ns; simpl in H; [inversion H | destruct (a =? 0) eqn:e].\n  specialize (IHns H); destruct IHns; split; [|right]; auto.\n  destruct H. pose proof (Nat.eqb_spec a 0); destruct H0; inversion e.\n  rewrite <- H; split; [| left]; auto.\n  specialize (IHns H); destruct IHns; split; [|right]; auto.\nQed.\n\nLemma InRemoveZeros' : forall (ns : list nat) (n : nat), n <> 0 -> In n ns -> In n (RemoveZeros ns).\nProof.\n  intros ns. induction ns; simpl; intros n ne nInNs.\n  inversion nInNs.\n  destruct nInNs.\n  destruct (a =? 0) eqn:e;\n    [exfalso; apply ne; rewrite Nat.eqb_eq in e; rewrite H in e; auto | left; auto].\n  destruct (a =? 0); [apply IHns | right; apply IHns]; auto.\nQed.\n\nLemma RemoveZerosWithoutZerosInv : forall (ns : list nat), ~ In 0 ns -> RemoveZeros ns = ns.\nProof.\n  intros ns H. induction ns.\n  simpl. auto.\n  simpl. destruct (a =? 0) eqn:e.\n  rewrite Nat.eqb_eq in e; exfalso; apply H; left; auto.\n  apply f_equal. apply IHns. intro Hcontra; apply H; right; auto.\nQed.\n\nLemma ZeroNotInRemoveZeros : forall (ns : list nat), ~In 0 (RemoveZeros ns).\nProof.\n  intros ns; induction ns; simpl; auto.\n  destruct (a =? 0) eqn:e ; auto.\n  intro Hcontra. apply IHns. destruct Hcontra; auto.\n  rewrite Nat.eqb_neq in e. exfalso; apply e; auto.\nQed.\n\nLemma minus_one_plus_one : forall m n : nat, m <> 0 -> m - 1 = n  -> m = n + 1.\nProof.\n  intros m n H H0;\n  induction m; [exfalso; apply H; auto|];\n  simpl in H0; rewrite Nat.sub_0_r in H0; rewrite H0; rewrite Nat.add_comm; simpl; reflexivity.\nQed.  \n\nTheorem OneLE : forall x, x = 0 \\/ 1 <= x.\nProof.\n  intros x.\n  destruct x. left; auto. right. apply le_n_S.  apply Nat.le_0_l.\nQed.\n\nTheorem OneLES : forall x, 1 <= S x.\nProof.\n  intros x. destruct (OneLE (S x)); auto. inversion H.\nQed.\n\n\nTheorem le_minus_plus : forall n m o, m <= n -> n - m = o -> n = o + m.\nProof.\n  induction n; intros m o H H0.\n  inversion H. simpl in H0. rewrite Nat.add_0_r. auto.\n  destruct m. rewrite Nat.sub_0_r in H0. rewrite Nat.add_0_r. auto.\n  simpl in H0. pose proof (le_S_n _ _ H). specialize (IHn m o H1 H0).\n  rewrite Nat.add_comm. simpl. apply f_equal. rewrite Nat.add_comm. apply IHn.\nQed.\n\nTheorem ZeroUniqueIdent : forall {a b}, a = a + b -> b = 0.\nProof.\n  intros a; induction a; intros b H; simpl.\n  simpl in H; symmetry; exact H.\n  simpl in H. inversion H. apply IHa; exact H1.\nQed.\n\nLemma OneUniqueS  :forall {a b}, S a = a + b -> b = 1.\nProof.\n  intros a; induction a; intros b H; simpl.\n  simpl in H; symmetry; exact H.\n  inversion H. apply IHa; exact H1.\nQed.\n", "meta": {"author": "akhirsch", "repo": "CoqBase", "sha": "651160f9de97481ff86347d2dc2f3cee5a0649d1", "save_path": "github-repos/coq/akhirsch-CoqBase", "path": "github-repos/coq/akhirsch-CoqBase/CoqBase-651160f9de97481ff86347d2dc2f3cee5a0649d1/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7475688143540777}}
{"text": "(* Exercise 45 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_045 : ((exists x, P x) -> (forall x, Q x)) -> (forall x, P x -> Q x).\nProof.\nimp_i a1.\nall_i a.\nimp_i a2.\nall_e (forall x:D, Q x) a.\nimp_e (exists x:D, P x).\nhyp a1.\nexi_i a.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred045.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7475076970421939}}
{"text": "Require Import BinNat.\nRequire Import BinPos.\nInclude BinNat.N.\n\nFrom Proyecto Require Export Defs_Bin.\n\n\n(* Todo número binario es igual a sí mismo. *)\nLemma bin_eq: forall (b: N), N.eqb b b = true.\nProof.\nintro.\napply eqb_eq.\ntrivial.\nQed.\n\n(* Equivalencia entre mi podd y el odd de Coq. *)\nTheorem podd_correct: forall (p: positive), N.odd (Npos p) = podd p.\nProof.\nunfold N.odd.\ninduction p; reflexivity.\nQed.\n\n(* Nuestra división entre 2 es equivalente a la de coq *)\nTheorem pdiv2_correct: forall (p: positive), p <> xH -> \nNpos (pdiv2 p) = N.div2 (Npos p).\nProof.\ninduction p.\n+ reflexivity.\n+ reflexivity.\n+ intro.\n  contradiction.\nQed.\n\n(* El XOR de un positivo con si mismo es 0. *)\nTheorem pos_xor_zero: forall p, Pos.lxor p p = N0.\nProof.\ninduction p.\n- simpl.\n  rewrite IHp.\n  reflexivity.\n- simpl.\n  rewrite IHp.\n  reflexivity.\n- reflexivity.\nQed.\n\n(* XOR de un número con si mismo siempre es 0. *)\nTheorem xor_zero: forall k, N.lxor k k = N0.\nProof.\ndestruct k.\n+ reflexivity.\n+ simpl.\n  apply pos_xor_zero.\nQed.\n\n(* Xor de dos positivos distintos no es 0. *)\nTheorem xor_not_zero_pos: forall k1 k2, k1 <> k2 -> Pos.lxor k1 k2 <> N0.\nProof.\ninduction k1.\n+ intros.\n  simpl.\n  destruct k2.\n  - unfold Pos.Ndouble.\n    assert (Pos.lxor k1 k2 <> 0%N).\n    * apply IHk1.\n      intro contra.\n      rewrite contra in H.\n      contradiction H.\n      trivial.\n    * destruct (Pos.lxor k1 k2) eqn:lxor.\n      ++ assumption.\n      ++ discriminate.\n  - unfold Pos.Nsucc_double.\n    destruct (Pos.lxor k1 k2).\n    * discriminate.\n    * discriminate.\n  - discriminate. \n+ intros.\n  destruct k2.\n  - simpl.\n    unfold Pos.Nsucc_double.\n    destruct (Pos.lxor k1 k2); discriminate.\n  - simpl.\n    unfold Pos.Ndouble.\n    destruct (Pos.lxor k1 k2) eqn:xor.\n    * apply IHk1 in xor.\n      ++ exfalso.\n         assumption.\n      ++ intro.\n         rewrite H0 in H.\n         contradiction H.\n         trivial.\n    * discriminate.\n  - destruct k1.\n    * simpl.\n      discriminate.\n    * simpl.\n      discriminate.\n    * simpl.\n      discriminate.\n+ intros.\n  destruct k2; simpl.\n  - discriminate.\n  - discriminate.\n  - contradiction H.\n    reflexivity.\nQed.\n\n(* Xor de dos números distintos no es 0. *)\nTheorem xor_not_zero: forall k1 k2, k1 <> k2 -> N.lxor k1 k2 <> N0.\nProof.\ninduction k1.\n+ simpl.\n  intros.\n  intuition.\n+ intros.\n  simpl.\n  destruct k2.\n  - assumption.\n  - apply xor_not_zero_pos.\n    intro.\n    rewrite H0 in H.\n    contradiction H.\n    reflexivity.\nQed.\n\nLemma obvious_matchP: forall k x, matchPrefix k (mask k x) x = true.\nProof.\nintros.\nunfold matchPrefix.\nrewrite bin_eq.\ntrivial.\nQed.\n\n(* 0 es neutro en xor. *)\nTheorem xor_neutral: forall x, N.lxor x N0 = x.\nProof.\ndestruct x.\n+ reflexivity.\n+ destruct p; reflexivity.\nQed.\n\n(* Xor conmuta para positivos. *)\nTheorem xor_comm_pos: forall p1 p2, Pos.lxor p1 p2 = Pos.lxor p2 p1.\ninduction p1.\n+ intro.\n  simpl.\n  destruct p2 eqn:P2.\n  - rewrite IHp1.\n    reflexivity.\n  - rewrite IHp1.\n    reflexivity.\n  - reflexivity.\n+ intro.\n  simpl.\n  destruct p2 eqn:P2.\n  - rewrite IHp1; reflexivity.\n  - rewrite IHp1; reflexivity.\n  - reflexivity.\n+ intro.\n  destruct p2 eqn:P2; reflexivity.\nQed.\n\n(* lxor es conmutativo *)\nTheorem xor_comm: forall n1 n2, N.lxor n1 n2 = N.lxor n2 n1.\nProof.\ndestruct n1, n2.\n+ reflexivity.\n+ reflexivity.\n+ reflexivity.\n+ simpl; rewrite xor_comm_pos; trivial.\nQed.\n\n(* branchingBit es conmutativo. *)\nLemma branchingBit_comm: forall x k, branchingBit x k = branchingBit k x.\nProof.\nintros.\nunfold branchingBit.\nrewrite xor_comm.\ntrivial.\nQed.\n\n(* Predecesor de 1 es 0 *)\nLemma pred_1: forall x, Pos.pred_N x = N0 -> x = xH.\nProof.\ndestruct x; simpl.\n+ intro.\n  inversion H.\n+ intro.\n  inversion H.\n+ intro.\n  trivial.\nQed. \n\n(* El predecesor del doble del bit más bajo de un número es es el predecesor del\n   número con un 1 pegado.*)\nLemma pred_double_pred: forall (x w:positive), Pos.pred_N (lowestBitP x) = pos w -> Pos.pred_double (lowestBitP x) = (xI w).\nProof.\ninduction x.\n+ intros.\n  simpl in H.\n  inversion H.\n+ intros.\n  simpl in H.\n  simpl.\n  inversion H.\n  trivial.\n+ intros.\n  simpl in H.\n  inversion H.\nQed.\n\nLemma lowestBit_mask: forall x, mask x (lowestBit x) = N0.\nProof.\ninduction x.\n+ reflexivity.\n+ induction p.\n  - reflexivity.\n  - simpl.\n    simpl in IHp.\n    destruct (Pos.pred_N (lowestBitP p)) eqn:Predecessor.\n    * unfold Pos.pred_N in Predecessor.\n      ++ assert (lowestBitP p = 1%positive).\n         -- destruct (lowestBitP p) eqn:Low.\n            ** inversion Predecessor.\n            ** inversion Predecessor.\n            ** trivial.\n         -- rewrite H.\n            reflexivity. \n    * apply pred_double_pred in Predecessor.\n      rewrite Predecessor.\n      rewrite IHp.\n      reflexivity.\n  - reflexivity.\nQed.\n\n(* Multiplicar por dos es pegar un 0 *)\nTheorem Ndouble_0: forall p, Pos.Ndouble (pos p) = pos (p~0).\nProof.\ndestruct p; reflexivity.\nQed.\n\n(* Lemma auxiliar sobre branchingBit. *)\nLemma branchingBit_end1: forall p1 p2 x, branchingBit (pos p1) (pos p2) = pos x -> \n                                         branchingBit (pos p1~1) (pos p2~1) = pos x~0.\nProof.\ninduction p1.\n+ intros.\n  unfold branchingBit.\n  simpl.\n  unfold branchingBit in H; simpl in H. \n  destruct p2 eqn:P2.\n  - simpl.\n    destruct (Pos.Ndouble (Pos.lxor p1 p)) eqn:Double.\n    * simpl in H.\n      inversion H.\n    * rewrite Ndouble_0.\n      simpl in H.\n      simpl.\n      inversion H.\n      trivial.\n  - unfold lowestBit in H.\n    unfold Pos.Nsucc_double in H.\n    destruct (Pos.lxor p1 p) eqn:Xor.\n    * simpl in H.\n      simpl.\n      inversion H.\n      trivial.\n    * simpl in H.\n      inversion H.\n      reflexivity.\n  - unfold lowestBit in H.\n    simpl in H.\n    unfold lowestBit.\n    simpl.\n    inversion H.\n    trivial.\n+ intros.\n  unfold branchingBit in H.\n  simpl in H.\n  destruct p2 eqn:P2.\n  - unfold lowestBit in H.\n    destruct (Pos.lxor p1 p) eqn:Xor.\n    * simpl in H.\n      inversion H.\n      unfold branchingBit.\n      simpl.\n      rewrite Xor.\n      reflexivity.\n    * unfold branchingBit.\n      simpl.\n      rewrite Xor.\n      simpl.\n      inversion H.\n      trivial.\n  - destruct (Pos.lxor p1 p) eqn:Xor.\n    * inversion H.\n    * inversion H.\n      unfold branchingBit.\n      simpl.\n      rewrite Xor.\n      reflexivity.\n  - inversion H.\n    unfold branchingBit.\n    reflexivity.\n+ intros.\n  unfold branchingBit in H.\n  inversion H.\n  destruct p2 eqn:P2.\n  - unfold branchingBit.\n    simpl.\n    inversion H1.\n    trivial.\n  - inversion H1.\n    unfold branchingBit; reflexivity.\n  - inversion H1.\nQed.\n    \n(* Auxiliar, predecesor del doble es predecesor del número con un 0 pegado *)\nLemma pred_double_pred_0: forall x, pos (Pos.pred_double x) = N.pred (pos (x~0)).\nProof.\ndestruct x; reflexivity.\nQed.\n\n(* Auxiliar *)\nLemma first_branchingBit: forall p1 p2, branchingBit (pos p1~0) (pos p2~1) = (pos xH).\nProof.\nunfold branchingBit.\nunfold lowestBit.\nintros.\ndestruct (N.lxor (pos p1~0) (pos p2~1)) eqn:Xor.\n+ simpl in Xor.\n  unfold Pos.Nsucc_double in Xor.\n  - destruct (Pos.lxor p1 p2) eqn:Xor2.\n    * inversion Xor.\n    * inversion Xor.\n+ destruct p eqn:P.\n  - reflexivity.\n  - simpl in Xor.\n    unfold Pos.Nsucc_double in Xor.\n    destruct (Pos.lxor p1 p2) eqn:Xor2.\n    * inversion Xor.\n    * inversion Xor.\n  - reflexivity.\nQed. \n\n(* Lema auxiliar para positivos *)\nLemma obvious_matchP_pos: forall p x, matchPrefix (pos p) (mask x (branchingBit x (pos p)))\n  (branchingBit x (pos p)) = true.\nProof.\ninduction p.\n+ intro.\n  unfold matchPrefix.\n  simpl.\n  destruct x eqn:X.\n  - reflexivity.\n  - simpl.\n    destruct p0 eqn:P0.\n    * simpl.\n      destruct (branchingBit (pos p1) (pos p)) eqn:Branch.\n      ++ unfold branchingBit in Branch.\n         simpl in Branch.\n         destruct (Pos.lxor p1 p) eqn:Xor.\n         -- unfold branchingBit.\n            simpl.\n            rewrite Xor.\n            reflexivity.\n         -- destruct p2 eqn:P2.\n            ** simpl in Branch.\n               inversion Branch.\n            ** inversion Branch.\n            ** inversion Branch.\n      ++ rewrite (branchingBit_end1 p1 p p2).\n         -- simpl.\n            destruct p2 eqn:P2.\n            ** unfold branchingBit in Branch.\n               simpl in Branch.\n               destruct (Pos.lxor p1 p) eqn:Xor.\n               +++ inversion Branch.\n               +++ destruct p4 eqn:P4; inversion Branch.\n            ** simpl.\n               unfold matchPrefix in IHp.\n               unfold branchingBit in IHp.\n               unfold branchingBit in Branch.\n               unfold lowestBit in Branch.\n               destruct (N.lxor (pos p1) (pos p)) eqn:Xor.\n               +++ inversion Branch.\n               +++ simpl in IHp.\n                   assert (Hip:= (IHp (pos p1))).\n                   rewrite Xor in Hip.\n                   destruct (lowestBit (pos p4)) eqn:Low.\n                   --- unfold lowestBit in Low.\n                       inversion Low.\n                   --- destruct p5 eqn:P5.\n                       *** simpl in Hip.\n                           simpl in Low.\n                           inversion Low.\n                           inversion Branch.\n                           rewrite H0 in H1.\n                           inversion H1.\n                       *** simpl in Hip.\n                           inversion Low; inversion Branch.\n                           rewrite H0 in H1.\n                           inversion H1.\n                           rewrite <- H2.\n                           apply eqb_eq in Hip.\n                           rewrite Hip.\n                           apply eqb_eq.\n                           trivial.\n                       *** simpl in Low; inversion Branch; inversion Low.\n                           rewrite H0 in H1; inversion H1.\n            ** reflexivity.\n         -- trivial.\n    * simpl.\n      rewrite first_branchingBit.\n      reflexivity.\n    * simpl.\nAdmitted.\n      \nLemma obvious_matchP2: forall k x, matchPrefix k (mask x (branchingBit x k))\n             (branchingBit x k) = true.\nProof.\ninduction k.\n+ unfold matchPrefix.\n  intro.\n  simpl.\n  rewrite branchingBit_comm.\n  unfold branchingBit.\n  simpl.\n  rewrite lowestBit_mask.\n  trivial.\n+ intro.\n  unfold matchPrefix.\n  simpl.\n  destruct (N.pred (branchingBit x (pos p))) eqn:Pred.\n  - simpl.\nAdmitted. \n\n(* Un número siempre tiene branchingBit 0 con si mismo *)\nLemma zeroBit_self: forall k, zeroBit k (branchingBit k k) = true.\nProof.\nintro.\nunfold branchingBit.\nunfold lowestBit.\nunfold zeroBit.\ndestruct k.\n+ reflexivity.\n+ rewrite xor_zero.\n  simpl.\n  trivial.\nQed.\n\n(* Lema auxiliar *)\nLemma branchingBit_zero_r: forall x, branchingBit x N0 = lowestBit x.\nProof.\nintro.\nunfold branchingBit.\ndestruct x eqn:X.\n+ reflexivity.\n+ reflexivity.\nQed.\n\n(* El bit más pequeño prendido de un número que termina en 0 no es el último. *)\nLemma lowestBit_not_last: forall p, lowestBitP (xO p) = xO (lowestBitP p).\nProof.\ndestruct p; reflexivity.\nQed.\n\n(* Si el doble de un número es 0, el número es 0. *)\nLemma double_zero: forall p, Pos.Ndouble p = N0 -> p = N0.\ninduction p.\n+ reflexivity.\n+ intros.\n  simpl in H.\n  inversion H.\nQed.\n\n(* La máscara conserva bit 0. *)\nLemma mask_cons_0: forall p q, mask (pos (xO p)) (pos (xO q)) = N0 -> mask (pos p) (pos q) = N0.\nProof.\ninduction p.\n+ intros.\n  destruct q eqn:Q.\n  - simpl.\n    simpl in H.\n    apply double_zero in H.\n    trivial.\n  - simpl in H.\n    simpl.\n    apply double_zero in H; trivial.\n  - reflexivity.\n+ intros.\n  simpl.\n  destruct (Pos.pred_N q) eqn:Predq.\n  - trivial.\n  - destruct p0 eqn:P0.\n    * simpl in IHp.\nAdmitted.\n\n(* La máscara de un número con su bit prendido más pequeño es 0. *)\nLemma mask_lowestBit: forall p, mask (pos p) (lowestBit (pos p)) = N0.\nProof.\ndestruct p.\n+ reflexivity.\n+ induction p.\n  - reflexivity.\n  - unfold lowestBit.\n    rewrite lowestBit_not_last.\nAdmitted.\n\n(* Lema auxiliar *)\nLemma compl_matchP: forall a x, matchPrefix a (mask x (branchingBit x a)) (branchingBit x a) = true.\nProof.\ninduction a.\n+ simpl.\n  intro.\n  destruct x eqn:X.\n  * reflexivity.\n  * rewrite branchingBit_zero_r.\n    simpl.\n    destruct (Pos.pred_N (lowestBitP p)) eqn:Pos.\n    - reflexivity.\n    - unfold matchPrefix.\n      unfold mask.\n      simpl.\nAdmitted.\n\n(* matchPrefix k x y = false /\\ matchPrefix k x z = true -> z < y *)\nLemma matchP_lt: forall k x y z, matchPrefix k x y = false /\\ matchPrefix k x z = true -> (N.lt z y).\nProof.\ninduction k.\n+ intros.\n  destruct H.\n  unfold matchPrefix in H0.\n  unfold mask in H0.\n  simpl in H0.\n  destruct x eqn:X.\n  - unfold matchPrefix in H.\n    unfold mask in H.\n    simpl in H.\n    inversion H.\n  - inversion H0.\n+ intros.\n  unfold matchPrefix in H.\n  unfold mask in H.\n  destruct H.\n  simpl in H.\n  simpl in H0.\n  destruct y eqn:Y.\n  - simpl in H.\n    destruct x eqn:X.\n    * inversion H.\n    * destruct z eqn:Z.\n      ++ simpl in H0.\n         inversion H0.\n      ++ destruct p1 eqn:P1.\n         -- simpl in H0.\nAdmitted.\n  \n(* Lema auxiliar matchPrefix k n n0 = true -> n0 < branchingBit en este caso*)\nLemma very_specific: forall k x n n0, matchPrefix k (mask x (branchingBit x n)) (branchingBit x n) = false \n                     /\\ matchPrefix k n n0 = true -> matchPrefix x n n0 = true.\nProof.\ndestruct k.\n+ intros.\n  destruct H.\n  unfold matchPrefix in H0.\n  simpl in H0.\n  destruct n eqn:N.\n  - unfold matchPrefix in H.\n    simpl in H.\n    unfold branchingBit in H.\n    rewrite xor_neutral in H.\n    rewrite lowestBit_mask in H.\n    inversion H.\n  - inversion H0.\n+ intros.\n  induction p.\n  - apply IHp.\n    unfold matchPrefix in H; unfold branchingBit in H; destruct H.\n    simpl in H.\n    unfold matchPrefix; unfold branchingBit.\n    simpl.\n    destruct (lowestBit (N.lxor x n)) eqn:Low.\n    * simpl.\n      simpl in H.\n      split.\n      trivial.\n      simpl in H0.\n      destruct (N.pred n0) eqn:Pred.\n      ++ trivial.\n      ++ destruct p0 eqn:P0.\n         -- simpl in H0.\nAdmitted.", "meta": {"author": "victorz3", "repo": "CoqPatriciaTrees", "sha": "8ffecd6276845d20b954283f08936367e87eed1d", "save_path": "github-repos/coq/victorz3-CoqPatriciaTrees", "path": "github-repos/coq/victorz3-CoqPatriciaTrees/CoqPatriciaTrees-8ffecd6276845d20b954283f08936367e87eed1d/Props_Bin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7473800659707359}}
{"text": "(* Section の練習 *)\n\nSection Poslist.\n  (* このセクションの中では、Aが共通の変数として使える。 *)\n  Variable A : Type.\n  (* 非空なリスト *)\n  Inductive poslist : Type := one: A -> poslist\n    | cons: A -> poslist -> poslist.\n\n  Section Fold.\n    (* 二項演算 *)\n    Variable g : A -> A -> A.\n\n   (* gによって畳み込む。\n    * 次のどちらかを定義すること。どちらでもよい。\n    * 左畳み込み : リスト [a; b; c] に対して (a * b) * c を計算する。\n    * 右畳み込み : リスト [a; b; c] に対して a * (b * c) を計算する。\n    *)\n    Fixpoint fold (l : poslist): A := \n      match l with\n        | one x => x\n        | cons x y => g x (fold y)\n      end.\n    (* DefinitionをFixpointなどに置き換えてもよい。 *)\n  End Fold.\n  Check fold.\nEnd Poslist.\nCheck fold.\n(* Poslistから抜けたことにより、poslistは変数Aについて量化された形になる。 *)\n\n(* このリストに関するmap関数 *)\nSection PoslistMap.\n  Variable A B : Type.\n  Variable f : A -> B.\n\n  Fixpoint map (ls: poslist A): poslist B :=\n    match ls with\n    | one _ x => one _ (f x)\n    | cons _ x y => cons _ (f x) (map y)\n    end.\nEnd PoslistMap.\n\n(* 今回は証明すべきことはないので、定義を正確に *)", "meta": {"author": "koba-e964", "repo": "coqworks", "sha": "d6d154e0fda8adc3d65a4ea78cdbc64993f7c59c", "save_path": "github-repos/coq/koba-e964-coqworks", "path": "github-repos/coq/koba-e964-coqworks/coqworks-d6d154e0fda8adc3d65a4ea78cdbc64993f7c59c/coqex7/PosList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623015, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7473800592581398}}
{"text": "Require Import List Orders.\nRequire Import Coq.Structures.OrdersFacts.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Sorting.Sorted.\nRequire Import Sorticoq.SortedList.\nImport ListNotations.\n\nModule InsertionSort (Import O: UsualOrderedTypeFull').\n\nInclude (OrderedTypeFacts O).\n\nDefinition A := O.t.\n\nFixpoint Insert (l: list A) x : list A :=\n  match l with\n  | [] => [x]\n  | h::t => match (O.compare x h) with\n    | Lt => x::l\n    | _ => h::(Insert t x)\n    end\n  end.\n\nDefinition InsertionSort (l: list A) :=\n  @fold_right (list A) A (fun x y => Insert y x) [] l.\n\nHint Resolve perm_skip perm_swap.\nHint Constructors LocallySorted.\nHint Extern 1 (?x <= ?y) => apply le_lteq; OrderTac.order.\n\nLtac convert_compare :=\n  repeat match goal with\n  | H: compare ?x ?y = Lt |- _ => apply compare_lt_iff in H\n  | H: compare ?x ?y = Gt |- _ => apply compare_gt_iff in H\n  | H: compare ?x ?y = Eq |- _ => apply compare_eq in H\n  end.\n\nLemma Permute: forall l x,\n  Permutation (x::l) (Insert l x).\nProof.\n  induction l; simpl; auto.\n  intros. destruct (compare _ _);\n  specialize IHl with x; transitivity (a::x::l); auto.\nQed.\n\nLemma InsertionSort_Permutation: forall l,\n  Permutation l (InsertionSort l).\nProof.\n  induction l; simpl; auto.\n  transitivity (a::(InsertionSort l)); auto.\n  apply Permute.\nQed.\n\nLemma Insert_LocallySorted: forall l a,\n  LocallySorted le l -> LocallySorted le (Insert l a).\nProof.\n  induction 1; [simpl | simpl | ]; auto.\n  - destruct (compare a a0) eqn:E; convert_compare; subst; auto.\n  - simpl in *. destruct (compare _ _) eqn:R1;\n    destruct (compare a a0) eqn:R2; convert_compare; subst; auto.\nQed.\n\nLemma InsertionSort_LocallySorted: forall l,\n  LocallySorted le (InsertionSort l).\nProof.\n  induction l; simpl; auto.\n  apply Insert_LocallySorted; auto.\nQed.\n\nCorollary InsertionSort_Sorted: forall l,\n  Sorted le (InsertionSort l).\nProof.\n  intros; apply Sorted_LocallySorted_iff.\n  apply InsertionSort_LocallySorted.\nQed.\n\nTheorem InsertionSort_is_sorting_algo:\n  is_sorting_algo le InsertionSort.\nProof.\n  unfold is_sorting_algo; intros; split.\n  - apply InsertionSort_Permutation.\n  - apply InsertionSort_Sorted.\nQed.\n\nEnd InsertionSort.\n\n(**\n   An example\n*)\n\nRequire Import ZArith.\n\nModule Import ZSort := InsertionSort Z.\n\nExample SortingExample: [2%Z; 4%Z; 4%Z; 6%Z; 8%Z] =\n  (InsertionSort [4%Z; 2%Z; 8%Z; 4%Z; 6%Z]).\nProof.\n  compute. reflexivity.\nQed.\n", "meta": {"author": "holmuk", "repo": "Sorticoq", "sha": "ac115f2a80deb5c2db2a56ba6b7adfad043e84b5", "save_path": "github-repos/coq/holmuk-Sorticoq", "path": "github-repos/coq/holmuk-Sorticoq/Sorticoq-ac115f2a80deb5c2db2a56ba6b7adfad043e84b5/src/InsertionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7473800583285183}}
{"text": "Require Export Induction.\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\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\nNotation \"( x , y )\" := (pair x y).\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) :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  simpl. reflexivity.\nQed.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\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\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\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 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\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\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 length (l:natlist) : nat :=\n  match l with\n  | nil => 0\n  | h :: t => 1 + (length t)\n  end.\n\nFixpoint app (l_1 l_2 : natlist) : natlist :=\n  match l_1 with\n  | nil => l_2\n  | h :: t => h :: (app t l_2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_appl: [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\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_hd_1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd_2: hd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_t1: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => match beq_nat h 0 with\n              | true => nonzeros t\n              | false => h :: (nonzeros t)\n              end\nend.\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  | nil => nil\n  | h :: t => match evenb h with\n              | true => oddmembers t\n              | false => h :: (oddmembers t)\n              end\nend.\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_countoddnumbers2:\n  countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddnumbers3:\n  countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\nFixpoint alternate (l_1 l_2 : natlist) : natlist :=\n  match l_1 with\n  | nil => l_2\n  | h :: t => match l_2 with\n              | nil => l_1\n              | h' :: t' => h :: h' :: (alternate t t')\n              end\nend.\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\nDefinition bag := natlist.\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\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\nDefinition sum : bag -> bag -> bag :=\n  app.\n\nExample test_sum_1: 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.\n\nExample test_add2: count 5 (add 1 [1;4;1]) = 0.\nProof. reflexivity. Qed.\n\nDefinition member (v:nat) (s:bag) : bool :=\n  match count v s with\n  | 0 => 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\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\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  | 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.\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 (s_1:bag) (s_2:bag) : bool :=\n  match s_1 with\n  | nil => true\n  | h :: t => match member h s_2 with\n              | true => subset t (remove_one h s_2)\n              | false => 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\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\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  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem app_assoc : forall l_1 l_2 l_3 : natlist,\n  (l_1 ++ l_2) ++ l_3 = l_1 ++ (l_2 ++ l_3).\nProof.\n  intros l_1 l_2 l_3.\n  induction l_1 as [| n l_1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity. Qed.\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.\n\nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\n\nTheorem app_length : forall l_1 l_2 : natlist,\n  length (l_1 ++ l_2) = (length l_1) + (length l_2).\nProof.\n  intros l_1 l_2. induction l_1 as [| n l_1' IHl1'].\n  - reflexivity.\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' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> app_length, plus_comm.\n    rewrite -> IHl1'. simpl. reflexivity. Qed.\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHl'.\n    reflexivity.\n  Qed.\n\nTheorem rev_app_distr : forall l_1 l_2 : natlist,\n  rev (l_1 ++ l_2) = rev l_2 ++ rev l_1.\nProof.\n  intros l_1 l_2.\n  induction l_1 as [| n l_1' IHl1'].\n  - simpl.\n    rewrite -> app_nil_r.\n    reflexivity.\n  - simpl.\n    rewrite -> IHl1'.\n    rewrite -> app_assoc.\n    reflexivity.\n  Qed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. \n    rewrite -> rev_app_distr.\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\n  Qed.\n\nTheorem app_assoc4 : forall l_1 l_2 l_3 l_4 : natlist,\n  l_1 ++ (l_2 ++ (l_3 ++ l_4)) = ((l_1 ++ l_2) ++ l_3) ++ l_4.\nProof.\n  intros l_1 l_2 l_3 l_4.\n  rewrite -> app_assoc, app_assoc.\n  reflexivity.\nQed.\n\nLemma nonzeros_app : forall l_1 l_2 : natlist,\n  nonzeros (l_1 ++ l_2) = (nonzeros l_1) ++ (nonzeros l_2).\nProof.\n  intros l_1 l_2.\n  induction l_1 as [|n l_1' IHl1'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHl1'.\n    destruct beq_nat.\n    + reflexivity.\n    + reflexivity.\n  Qed.\n\nFixpoint beq_natlist (l_1 l_2 : natlist) : bool :=\n   match l_1 with\n    | nil => match l_2 with\n             | nil => true\n             | _ => false\n             end\n    | h1 :: t1 => match l_2 with\n                  | nil => false\n                  | h2 :: t2 => beq_nat h1 h2 && beq_natlist t1 t2\n                  end\n    end.\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_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  intros n. induction n as [|n' IHn'].\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 l.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHl'.\n    rewrite <- beq_nat_refl.\n    reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall s:bag,\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s.\n  reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\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 l.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - destruct n as [| n'].\n    + simpl.\n      rewrite -> ble_n_Sn.\n      reflexivity.\n    + simpl.\n      rewrite -> IHl'.\n      reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "binaks", "repo": "softfound", "sha": "a3c23c8785c34ba6e2fe77f1ba5a8eab08685a31", "save_path": "github-repos/coq/binaks-softfound", "path": "github-repos/coq/binaks-softfound/softfound-a3c23c8785c34ba6e2fe77f1ba5a8eab08685a31/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.8856314798554444, "lm_q1q2_score": 0.7473800546100304}}
{"text": "Require Export Arith.\nRequire Export XR_S_INR.\nRequire Export XR_Rplus_0_r.\nRequire Export XR_Rplus_assoc.\n\nLocal Open Scope R_scope.\n\nLemma plus_INR : forall n m:nat,\n  INR (n + m) = INR n + INR m.\nProof.\n  intros n m.\n  induction m as [ | m im ].\n  {\n    simpl.\n    rewrite Rplus_0_r.\n    rewrite <- plus_n_O.\n    reflexivity.\n  }\n  {\n    rewrite Nat.add_comm.\n    simpl.\n    rewrite S_INR.\n    rewrite Nat.add_comm.\n    rewrite im.\n    rewrite S_INR.\n    repeat rewrite <- Rplus_assoc.\n    reflexivity.\n  }\nQed.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_plus_INR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7473303132030182}}
{"text": "(* 変数名 x, y, z *)\nDefinition var := nat.\nDefinition eqb := Nat.eqb.\n\n(* 型名 S, T *)\nInductive type :=\n  | tyBool\n  | tyFun : type -> type -> type.\n\n(* 文脈 C *)\nDefinition context := var -> type -> Prop.\n(* C, x1 : T1 *)\nDefinition append (C:context) x1 T1 x2 T2 := x1 = x2 /\\ T1 = T2 \\/ C x2 T2.\n(* 空の文脈 *)\nDefinition empty_context:context := fun x T => False.\n\n(* 値 u, v，項 s, t *)\nInductive term :=\n  | tmVal : value -> term\n  | tmIf : term -> term -> term -> term (* if t then t else t *)\n  | tmVar : var -> term\n  | tmApp : term -> term -> term (* t t *)\nwith value :=\n  | vTrue | vFalse\n  | vAbs : nat -> type -> term -> value  (* λx:T.t *).\n\nDefinition tmTrue := tmVal vTrue.\nDefinition tmFalse := tmVal vFalse.\nDefinition tmAbs x T t := tmVal (vAbs x T t).\n\n(* C ⊢ t : T *)\nFixpoint is_type_candidate C t T {struct t} :=\n  match t, T with\n  | tmVal vTrue, tyBool => True\n  | tmVal vFalse, tyBool => True\n  | tmVal (vAbs x T1 t1), tyFun T2 T3 => T1 = T2 /\\ is_type_candidate (append C x T1) t1 T3\n  | tmIf t1 t2 t3, T1 => is_type_candidate C t1 tyBool /\\ is_type_candidate C t2 T1 /\\ is_type_candidate C t3 T1\n  | tmVar x, T1 => C x T1\n  | tmApp t1 t2, T1 => exists T2, is_type_candidate C t1 (tyFun T2 T1) /\\ is_type_candidate C t2 T2\n  | _, _ => False\n  end.\n\nDefinition is_typed t T :=\n  is_type_candidate empty_context t T\n  /\\ forall S, is_type_candidate empty_context t S -> S = T.\n\nExample type_of_true : is_typed tmTrue tyBool.\nProof.\n  split.\n  - simpl.\n    trivial.\n  - destruct S.\n    reflexivity.\n    contradiction.\nQed.\nExample type_of_false : is_typed tmFalse tyBool.\nProof.\n  split.\n  - simpl.\n    trivial.\n  - destruct S.\n    reflexivity.\n    contradiction.\nQed.\n\nGoal\n  let t := (tmAbs 0 tyBool (tmAbs 0 (tyFun tyBool tyBool) (tmApp (tmVar 0) (tmVar 0)))) in\n  let T := (tyFun tyBool (tyFun (tyFun tyBool tyBool) tyBool)) in\n  is_typed t T.\nProof.\n  intros t T.\n  assert (is_type_candidate empty_context t T). {\n    split. reflexivity. split. reflexivity.\n    exists tyBool. split.\n    - left. split. reflexivity. reflexivity.\n    - right. left. split. reflexivity. reflexivity.\n  }\n  split. exact H. destruct S.\n  - contradiction.\n  - destruct S2 as [| S21 S22].\n    + intros [_ H0]. contradiction.\n    + destruct S22.\n      * intros [HS1 [HS21 _]].\n        rewrite <-HS1, <-HS21.\n        reflexivity.\n      * intros [_[_[S22[[[_ HS221]|[[_ HS222]|HS223]] _]]]].\n        discriminate. discriminate. contradiction.\nQed.", "meta": {"author": "fiveseven-lambda", "repo": "coq-sandbox", "sha": "daf30865b1304f7aa79c9094b9cef453f75ea4a7", "save_path": "github-repos/coq/fiveseven-lambda-coq-sandbox", "path": "github-repos/coq/fiveseven-lambda-coq-sandbox/coq-sandbox-daf30865b1304f7aa79c9094b9cef453f75ea4a7/overload.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7472984751586349}}
{"text": "(* dokumentacja\nhttps://coq.inria.fr/distrib/current/refman/index.html \n*)\n\nCheck Set.\nCheck Prop.\nCheck Type.\n\n\nSection Logic.\n\nVariables A B C : Prop.\n\nCheck True.\nCheck False.\nCheck and.\nCheck or.\nCheck not.\n\nCheck (A \\/ B).\nCheck (A /\\ B).\nCheck (A -> B).\n\nSearch \"/\\\".\n\nLemma id_auto:\nA -> A.\nProof.\nauto.\nQed.\n\nLemma id_2:\nA -> A.\nProof.\nintro.\nassumption.\nQed.\n\nPrint id_2.\n\nLemma contraction:\nA /\\ A -> A.\nProof.\nintro.\ndestruct H.\nassumption.\nQed.\n\nLemma apply:\n(A -> B) -> A -> B.\nProof.\nintros H1 H2.\napply H1.\nassumption.\nQed.\n\nPrint apply.\n\n\nVariable T : Type.\nVariable P Q : T -> Prop.\n\nLemma first_order:\n(forall x, P x) \\/ (forall x, Q x) -> forall x, P x \\/ Q x.\nProof.\nintros.\ndestruct H.\nleft.\napply H.\nright.\napply H.\nQed.\n\nEnd Logic.\n\nSection Nats.\n\nCheck nat.\nCheck 0.\nCheck (fun x => x).\nCheck (fun x => x + 0).\n\nDefinition double := fun x => x * 2.\nCheck double.\n\nEval compute in (double 4).\n\n(* Popraw definicje compose *)\n\n(* Definition compose := fun f => fun g => fun x => f (g x).*)\n\nEnd Nats.\n\nSection Lambda.\n\nVariable L : Type.\nVariable red_trans_refl : L -> L -> Prop. (* ->*_beta *)\n\n(* Uzupelnij definicje *)\n\n(* t jest w postaci normalnej *)\nDefinition normal t : Prop := \n.\n\n(* red_trans_refl jest konfluentna *)\nDefinition confluent : Prop := \n.\n\n(* t ma postac normalna *)\nDefinition has_normal  t : Prop := \n.\n\n(* Zapisz lemat: istnieje term, ktory nie ma postaci normalnej *)\n\nEnd Lambda.\n\n\n\n\n\n\n", "meta": {"author": "Kamirus", "repo": "coq-course", "sha": "18d35bbcd8a1cb5f1dabd8ecb497a1a8ea059d6f", "save_path": "github-repos/coq/Kamirus-coq-course", "path": "github-repos/coq/Kamirus-coq-course/coq-course-18d35bbcd8a1cb5f1dabd8ecb497a1a8ea059d6f/w/p1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7472494156389101}}
{"text": "Require Export InsertionSortAlgorithm.\n\n(** Sorting stuff **)\n\n(** Preliminary lemmas:\n    Here we prove some general facts that will be useful\n    later on. *)\n\n\n(** Count distributes over append as addition *)\nTheorem append_add_counts : forall (x y : natlist) (v : nat),\n  count v (x ++ y) = count v x + count v y.\nProof.\n  intros x y v. induction x as [ | h t].\n  Case \"x = []\". simpl. reflexivity.\n  Case \"x = h :: t\". destruct (beq_nat v h) eqn:Casev.\n    SCase \"v = h\". simpl. rewrite Casev. rewrite IHt. simpl. reflexivity.\n    SCase \"v != h\". simpl. rewrite Casev. rewrite IHt. reflexivity. Qed.\n\n(** Helper for later: If v is not present in a list l, it is not\n    present in the tail of l *)\nLemma count_helper : forall (v h : nat) (l : natlist),\n  count v (h :: l) = 0 -> count v l = 0.\nProof.\n  intros v h l. intros H. simpl in H.\n  destruct (beq_nat v h) eqn:Casevh.\n  Case \"v <= h\". inversion H.\n  Case \"v > h\". apply H. Qed.\n\n(** Disjunction of opposites is always true *)\nLemma orb_x_negx_true : forall (b : bool),\n  orb b (negb b) = true.\nProof.\n  intros b. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\". reflexivity. Qed.\n\n(** Equality is transitive *)\nTheorem trans_eq : forall (n m o : nat),\n  n = m -> m = o -> n = o.\nProof.\n  intros n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Helpful properties of ble_nat:\n    Here we assume some basic properties of the less than \n    or equal relation.*)\n\n\n\nLemma ble_nat_helper : forall (u v : nat),\n  ble_nat (S u) v = true -> ble_nat u v = true.\nProof.\n  intros u v.\n  intros H.\n  induction v as [ | v'].\n  simpl in H.\n  inversion H.\n  simpl in H.\n  Admitted.\n\nTheorem ble_nat_transitive : forall (u v w : nat),\n  ble_nat u v = true -> ble_nat v w = true -> ble_nat u w = true.\nProof.\n  intros u v w.\n  intros H.\n  intros H'.\n  induction v as [ | v'].\n  destruct u as [ | u'].\n  reflexivity.\n  simpl in H.\n  inversion H.\n  Admitted.\n\n\nLemma ble_nat_anticomm : forall (u v : nat),\n  (ble_nat u v) = false -> (ble_nat v u) = true.\nProof.\n  intros u v.\n  intros H.\n  induction u as [ | u'].\n  Case \"u = 0\".\n  simpl. simpl in H.\n  destruct (ble_nat v 0).\n  reflexivity.\n  rewrite H. reflexivity. \n  induction v as [ | v'].\n  simpl. reflexivity.\n  simpl. simpl in IHu'.\n  Admitted.\n\nLemma ble_nat_helper1 : forall (u v w: nat),\n  ble_nat u v = false -> ble_nat u w = true -> beq_nat v w = false.\nProof.\n  intros u v w. intros H. intros H'.\n  Admitted.\n\n\n(** Sorting basics: \n    Here we introduce predicates that test whether a list\n    is sorted, and whether one list is a permutation of another.\n    We use these two properties to define what it means for a \n    sorting algorithm to be correct: it has to produce a sorted\n    list which is a permutation of the original list *)\n\n(** Sortedness predicate: compare first two elements, and recurse *)\nFixpoint is_sorted (l : natlist) : bool :=\n  match l with\n  | [] => true\n  | h :: t => match t with \n              | [] => true\n              | h1 :: t1 => andb (ble_nat h h1) (is_sorted t)\n  end\n  end.\n\n(** Permutation predicate: every natural number appears the\n    same number of times in the two lists *)\nDefinition is_permutation (l l' : natlist) : Prop :=\n  forall (v : nat), (count v l) = (count v l').\n\n(** Helpful properties of is_sorted *)\n\n(** Appending an element smaller than the head to a sorted list\n    preserves sortedness *)\nLemma sorted_from_tail : forall (l : natlist) (v h : nat),\n  andb (ble_nat v h) (is_sorted (h :: l)) = true -> is_sorted (v :: h :: l) = true.\nProof.\n  intros l v h. intros H. simpl in H. simpl. apply H. Qed.\n\n(** For a sorted list, the tail is sorted *)      \nLemma sorted_implies_subsorted : forall (l : natlist) (v : nat),\n  is_sorted (v :: l) = true -> is_sorted l = true.\nProof.\n  intros l v. intros H. simpl.\n  destruct l as [ | h t].\n  Case \"l = []\". simpl. reflexivity.\n  Case \"l = h t\".\n    simpl in H.  apply andb_true_elim2 in H.\n    destruct t as [ | h' t'].\n    SCase \"t = []\". simpl. reflexivity.\n    SCase \"t = h' t'\". apply sorted_from_tail. apply H. Qed.  \n\n(** Predicate that tests whether an element is less than or equal to\n    all elements in a given list. This will be useful later on\n    when we prove correctness of insertion sort, so we'll prove\n    some properties of that predicate now. *)\nFixpoint leq_than_all (v : nat) (l : natlist) : bool :=\n  match l with\n  | [] => true\n  | h :: t => andb (ble_nat v h) (leq_than_all v t)\n  end.\n\n(** For a sorted list, the head is <= all elements of the tail *)\nLemma sorted_implies_head_leq_than_all : forall (v : nat) (l : natlist),\n  is_sorted (v :: l) = true -> leq_than_all v l = true.\nProof.\n  intros v l. intros H. induction l as [ | h t].\n  (* we induct on the list l: the rest is piecing \n     the inequalities in the right way and doing casework\n     unfolding is_sorted and leq_than_all. The key point is that\n     the two functions are defined in terms of the same recursion. *)\n  Case \"l = []\". simpl. reflexivity.\n  Case \"l = h :: t\". simpl.\n    assert (Lemma1 : is_sorted (v :: h :: t) = true).\n      SCase \"Proof of Lemma 1\". apply H.\n    assert (Lemma2 : ble_nat v h = true).\n      SCase \"Proof of Lemma 2\". simpl in Lemma1. apply andb_true_elim1 in Lemma1.\n        apply Lemma1.\n  rewrite Lemma2.\n  assert (Lemma3 : is_sorted t = true).\n    SCase \"Proof of Lemma 3\". apply sorted_implies_subsorted in H.\n      apply sorted_implies_subsorted in H. apply H.\n  destruct t as [ | h' t'].\n  SCase \"t = []\". simpl. reflexivity.\n  SCase \"t = h' :: t'\". \n    apply sorted_implies_subsorted in H. simpl in H. apply andb_true_elim1 in H.\n  assert (Lemma4 : ble_nat v h' = true).\n    SSCase \"Proof of Lemma 4\".\n      apply ble_nat_transitive with (v := h). apply Lemma2. apply H.\n  assert (Lemma5 : is_sorted (v :: h' :: t') = true).\n    SSCase \"Proof of Lemma 5\".\n      apply sorted_from_tail. rewrite Lemma4. rewrite Lemma3. simpl. reflexivity.\n  assert (Lemma6 : leq_than_all v (h' :: t') = true).\n    SSCase \"Proof of Lemma 6\".\n      apply IHt. apply Lemma5.\n  rewrite Lemma6. simpl. reflexivity. Qed.\n \n\n(** Helpful properties of is_permutation: among other things, here we show\n    that the permutation relation we've defined is an equivalence\n    relation: that is, it is reflexive, symmetric and transitive. *)\n\nTheorem is_permutation_reflexive : forall (l : natlist),\n  is_permutation l l.\nProof.\n  intros l. unfold is_permutation. reflexivity. Qed.\n\nTheorem is_permutation_symmetric : forall (l l' : natlist),\n  is_permutation l l' -> is_permutation l' l.\nProof.\n  intros l l'. intros H. unfold is_permutation in H. symmetry in H.\n  unfold is_permutation. apply H. Qed.\n\nTheorem is_permutation_transitive : forall (l l' l'' : natlist),\n  is_permutation l l' -> is_permutation l' l'' -> is_permutation l l''.\nProof.\n  intros l l' l''. intros H1. intros H2. unfold is_permutation in H1, H2.\n  unfold is_permutation. intros v.\n  (* the rest of the proof is just an application of transitivity of\n     equality. *)\n  assert (Lemma1 : count v l = count v l').\n    Case \"Proof of Lemma 1\". apply H1.\n  assert (Lemma2 : count v l' = count v l'').\n    Case \"Proof of Lemma 2\". apply H2.\n  apply trans_eq with (m := count v l').\n  rewrite Lemma1. reflexivity. rewrite Lemma2. reflexivity. Qed.\n\n(** If two lists can be broken into parts that are permutations of one \n    another, the lists are permutations of one another *)\nTheorem is_permutation_append : forall (x x' y y' : natlist),\n  is_permutation x y -> is_permutation x' y' -> is_permutation (x ++ x') (y ++ y').\nProof.\n  intros x x' y y'. intros H. intros H'. \n  unfold is_permutation. \n  intros v. \n  (* at this point, the theorem is a simple consequence of \n     the fact that count distributes over append as addition *)\n  rewrite append_add_counts. rewrite append_add_counts. \n  unfold is_permutation in H, H'. rewrite H. rewrite H'. reflexivity. Qed.\n\n(** For a list of length 2, transpositing the elements is a \n    permutation. *)\nTheorem is_permutation_transposition : forall (v h : nat),\n  is_permutation (v :: [h]) (h :: [v]).\nProof.\n  intros v h. unfold is_permutation. intros v0.\n  (* this is just a lot of casework *)\n  destruct (beq_nat v0 v) eqn:Casev.\n  destruct (beq_nat v0 h) eqn:Caseh.\n  Case \"v0 = v, v0 = h\". simpl. rewrite Casev. rewrite Caseh. reflexivity.\n  Case \"v0 = v, v0 != h\". simpl. rewrite Casev. rewrite Caseh. reflexivity.\n  destruct (beq_nat v0 h) eqn:Caseh.\n  Case \"v0 != v, v0 = h\". simpl. rewrite Casev. rewrite Caseh. reflexivity.\n  Case \"v0 != v, v0 != h\". simpl. rewrite Casev. rewrite Caseh. reflexivity. Qed.\n  \n(** Swapping the first two elements in a list is a permutation *)\n Theorem is_permutation_swap_first : forall (l : natlist) (v h : nat),\n  is_permutation (v :: h :: l) (h :: v :: l).\nProof.\n  intros l v h.\n  (* the goal follows readily by combining is_permutation_transposition\n     with is_permutation_append *)\n  assert (Lemma1 : is_permutation (v :: [h]) (h :: [v])).\n    Case \"Proof of Lemma 1\". apply is_permutation_transposition.\n  apply is_permutation_append with (x := (v :: [h]))\n                                   (x' := l) (y := (h :: [v])) (y' := l).\n  apply is_permutation_transposition. apply is_permutation_reflexive. Qed.\n    \n(** Prepending the same element to two lists that are permutations\n    of each other preserves the permutation relation. *)\nTheorem is_permutation_same_head : forall (v : nat) (l l' : natlist),\n  is_permutation l l' -> is_permutation (v :: l) (v :: l').\nProof.\n  intros v l l'. intros H.\n  (* this easily follows by is_permutation_append *)\n  apply is_permutation_append with (x := [v]) (x' := l) (y := [v]) (y' := l').\n  apply is_permutation_reflexive. apply H. Qed. \n\n\n\n(** Insertion sort : correctness.\n    Here we show insertion sort is correct, that is, for every list \n    l, (insertion_sort l) is a sorted list and a permutation of l. *)\n\n(** Permutation correctness: here we show that for every list l,\n    (insertion_sort l) is a permutation of l. *)\n\n(* First, we show that the insert subroutine gives a permutation\n   of what we would get if we just inserted in the first position. *)\nTheorem insert_is_permutation : forall (v : nat) (l : natlist),\n  is_permutation (v :: l) (insert v l).\nProof.\n  intros v l. induction l as [ | h t].\n  Case \"l = []\". simpl. apply is_permutation_reflexive.\n  Case \"l = h :: t\".\n  destruct (ble_nat v h) eqn:Case1.\n    SCase \"v <= h\".\n      simpl. rewrite Case1. apply is_permutation_reflexive.\n    SCase \"v > h\".\n      simpl. rewrite -> Case1.\n      assert (Lemma1 : is_permutation (v :: h :: t) (h :: v :: t)).\n        SSCase \"Proof of Lemma 1\". apply is_permutation_swap_first.\n      apply is_permutation_transitive with (l' := (h :: v :: t)).\n        apply Lemma1. \n        apply is_permutation_same_head with (v := h) (l := (v :: t)) \n                                                     (l' := (insert v t)).\n        apply IHt. Qed.\n\n(* Now it's easy to show the main lemma *)\nTheorem insertion_sort_is_permutation : forall (l : natlist),\n  is_permutation l (insertion_sort l).\nProof.\n  intros l. induction l as [ | h t].\n  Case \"l = []\".\n  simpl. apply is_permutation_reflexive.\n  Case \"l = h :: t\".\n  simpl.\n  assert (Lemma1 : is_permutation (insert h (insertion_sort t)) (h :: (insertion_sort t))).\n  SCase \"Proof of Lemma 1\". apply is_permutation_symmetric. apply insert_is_permutation.\n  assert (Lemma2 : is_permutation (h :: t) (h :: (insertion_sort t))).\n  SCase \"Proof of Lemma 2\". apply is_permutation_same_head. apply IHt.\n  apply is_permutation_symmetric in Lemma1.\n  apply is_permutation_transitive with (l' := (h :: insertion_sort t)).\n  apply Lemma2.\n  apply Lemma1. Qed.\n  \n\n(* Sortedness correctness *)\n\nTheorem leq_than_all_alternative_def : forall (v : nat) (l : natlist),\n  (leq_than_all v l) = true -> (forall (n : nat), (ble_nat v n) = false -> count n l = 0).\nProof.\n  intros v l. intros H. intros n. intros H'. induction l as [ | h t].\n  Case \"l = []\". simpl. reflexivity.\n  Case \"l = h :: t\". simpl.\n    assert (Helper1 : leq_than_all v (h :: t) = true).\n      SCase \"Proof of Helper 1\". rewrite H. reflexivity.\n    assert (Helper2 : leq_than_all v (h :: t) = true).\n      SCase \"Proof of Helper 1\". rewrite H. reflexivity.\n    assert (Lemma1: leq_than_all v t = true).\n      SCase \"Proof of Lemma 1\". simpl in Helper1. apply andb_true_elim2 in Helper1.\n        apply Helper1.\n    rewrite Lemma1 in IHt. rewrite IHt.\n    assert (Lemma2: ble_nat v h = true).\n      SCase \"Proof of Lemma 2\". simpl in Helper2. apply andb_true_elim1 in Helper2.\n        apply Helper2.\n    assert (Lemma3: beq_nat n h = false).\n      SCase \"Proof of Lemma 3\". apply ble_nat_helper1 with (u := v).\n        apply H'. apply Lemma2.\n  rewrite Lemma3. reflexivity. reflexivity. Qed.    \n  \nTheorem leq_than_all_alternative_def1 : forall (v : nat) (l : natlist),\n  (forall (n : nat), (ble_nat v n) = false -> count n l = 0) -> (leq_than_all v l) = true.\nProof. \n  intros v l. intros H. induction l as [ | h t].\n  Case \"l = []\". simpl. reflexivity.\n  Case \"l = h :: t\". simpl.\n  assert (Lemma1 : forall (n : nat), count n (h :: t) = 0 -> count n t = 0).\n    SCase \"Proof of Lemma 1\". intros n. apply count_helper.\n  assert (Lemma2 : forall n : nat, ble_nat v n = false -> count n t = 0).\n    SCase \"Proof of Lemma 2\". intros n H'. apply Lemma1. apply H. apply H'.\n  assert (Lemma3 : leq_than_all v t = true).\n    SCase \"Proof of Lemma 3\". apply IHt. apply Lemma2.\n  rewrite Lemma3. destruct (ble_nat v h) eqn:Casevh.\n  SCase \"v <= h\". simpl. reflexivity.\n  SCase \"v > h\".\n  assert (Lemma4 : count h (h :: t) = 0).\n    SSCase \"Proof of Lemma 4\". apply H. apply Casevh.\n  simpl in Lemma4. rewrite <- beq_nat_refl in Lemma4. inversion Lemma4. Qed.\n\nTheorem leq_than_all_invariant_permutation : forall (v : nat) (l l' : natlist),\n  is_permutation l l' -> (leq_than_all v l) = true -> (leq_than_all v l') = true.\nProof. \n  intros v l l'. intros H. intros H'. unfold is_permutation in H.\n  assert (Lemma1 : forall (n : nat), (ble_nat v n) = false -> count n l = 0). \n    Case \"Proof of Lemma 1\". apply leq_than_all_alternative_def. apply H'.\n  assert (Lemma2 : forall (n : nat), (ble_nat v n) = false -> count n l' = 0).\n    Case \"Proof of Lemma 2\". intros n.\n      assert (Lemma21 : count n l = count n l'). apply H.\n      rewrite <- Lemma21. apply Lemma1.\n  apply leq_than_all_alternative_def1. apply Lemma2. Qed.\n  \nTheorem insertion_helper : forall (l : natlist) (v h: nat),\n  leq_than_all v l = true -> ble_nat v h = true -> leq_than_all v (insert h l) = true.\nProof.\n  intros l v h. intros H. intros H'.\n  assert (Lemma1 : leq_than_all v (h :: l) = true).\n    Case \"Proof of Lemma 1\". simpl. rewrite H. rewrite H'. simpl. reflexivity.\n  assert (Lemma2 : is_permutation (h :: l) (insert h l)).\n    Case \"Proof of Lemma 2\". apply insert_is_permutation.\n  apply leq_than_all_invariant_permutation with (l := (h :: l)).\n  apply Lemma2. apply Lemma1. Qed.\n\n     \nTheorem insert_preserves_sortedness : forall (v : nat) (l : natlist),\n  is_sorted l = true -> is_sorted (insert v l) = true.\nProof.\n  intros v l. intros H. induction l as [ | h t].\n  Case \"l = []\". simpl. reflexivity.\n  Case \"l = h :: t\". simpl.\n    assert (Lemma1: andb (ble_nat v h) (is_sorted (h :: t)) = true  \n                    -> is_sorted (v :: h :: t) = true).\n      SCase \"Proof of Lemma 1\". apply sorted_from_tail.\n    assert (Lemma2 : is_sorted (h :: t) = true).\n      SCase \"Proof of Lemma 2\". rewrite H. reflexivity.\n    assert (Lemma3: is_sorted t = true).\n      SCase \"Proof of Lemma 3\".\n        apply sorted_implies_subsorted in Lemma2. rewrite -> Lemma2. reflexivity.\n    assert (Lemma4: is_sorted (insert v t) = true).\n      SCase \"Proof of Lemma 4\". rewrite Lemma3 in IHt. apply IHt. reflexivity.\n  destruct (insert v t) as [ | h' t'] eqn:Caseinsert.\n    SCase \"insert v t = []\". destruct (ble_nat v h) eqn:Casevh. \n      rewrite H in Lemma1. apply Lemma1. simpl. reflexivity. simpl. reflexivity.\n    SCase \"insert v t = h' :: t'\". destruct (ble_nat v h) eqn:Casevh.\n      SSCase \"v <= h\". rewrite H in Lemma1. apply Lemma1. simpl. reflexivity.\n      SSCase \"v > h\".\n        assert (Lemma5 : ble_nat h v = true).\n          SSSCase \"Proof of Lemma 5\". apply ble_nat_anticomm. apply Casevh.\n        assert (Lemma6 : leq_than_all h t = true).\n          SSSCase \"Proof of Lemma 6\".\n            apply sorted_implies_head_leq_than_all. apply H.\n        assert (Lemma7 : leq_than_all h (insert v t) = true).\n          SSSCase \"Proof of Lemma 7\". \n            apply insertion_helper. apply Lemma6. apply Lemma5.\n        assert (Lemma8 : ble_nat h h' = true).\n          SSSCase \"Proof of Lemma 8\".\n            rewrite Caseinsert in Lemma7. simpl in Lemma7. \n            apply andb_true_elim1 in Lemma7. apply Lemma7.\n      apply sorted_from_tail. rewrite Lemma8. rewrite Lemma4. simpl. reflexivity. Qed.\n      \n\nTheorem insertion_sort_correct : forall (l : natlist),\n  is_sorted (insertion_sort l) = true.\nProof.\n  intros l. induction l as [ | h t].\n  Case \"l = []\". simpl. reflexivity.\n  Case \"l = h :: t\". simpl.\n    apply insert_preserves_sortedness with (v:=h) in IHt.\n    rewrite IHt. reflexivity. Qed.\n  ", "meta": {"author": "mfount", "repo": "chicken", "sha": "83bb022522499272b4c246432188cfd5cce89c64", "save_path": "github-repos/coq/mfount-chicken", "path": "github-repos/coq/mfount-chicken/chicken-83bb022522499272b4c246432188cfd5cce89c64/final-submission/submission/code/InsertionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002789, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7471982085516263}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (x : natural) : natural :=\n  plus (mult lf1 x) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj156_coqofml_LRrj5j.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.74719819526652}}
{"text": "Load Preamble.\n\n(*  Here is the most common formulation of Lawvere's Fixpoint theorem:\n    If there is a surjection X -> X -> Y, then every function Y -> Y \n    has a fixpoint. \n *)\nSection Lawvere.\n  Variables X Y : Type.\n  Implicit Type g : Y -> Y.\n  Implicit Type f : X -> X -> Y.\n\n  Fact Lawvere_surj f :\n    surj f -> forall g, exists y, g y = y.\n  Proof.\n    intros Surj g.\n    destruct (Surj (fun x => g (f x x))) as [a Ha].\n    exists (f a a). pattern (f a) at 2.\n    now rewrite Ha.\n  Qed.\nEnd Lawvere.\n\n\n(*  Remark (2.2) on nLab: Lawvere remarks that surjectivity up to\n    functional extensionality (he calls it weak surj.) is enough \n    to show the fixpoint theorem.\n\n    We additionally want to note that we can generalize from the \n    function type Y -> Y to relations Y -> Y -> Prop. This turns \n    the fixpoint-theorem into a theorem showing the existence of \n    a reflexive element.\n *)\nSection repr.\n  Variables I X Y : Type.\n  Implicit Type R : X -> Y -> Prop.\n\n  Definition repr R f :=\n    forall x : X, R x (f x).\n\n  Definition ext_repr R f :=\n    exists i : I, repr R (f i).\n\n  Definition ext_surj f :=\n    forall R, ext_repr R f.\nEnd repr.\nArguments repr {_ _}.\nArguments ext_repr {_ _ _}.\nArguments ext_surj {_ _ _}.\n\n\nSection Lawvere.\n\nVariables X Y : Type.\nImplicit Type R : Y -> Y -> Prop.\nImplicit Type f : X -> X -> Y.\n\nDefinition diag R f := fun x => R (f x x).\n\n(*  If we are interested in a reflexive point for one particular \n    relation R, we only need a representation (up to extensionality) \n    of R (f x x) \n *)\nFact diag_refl R f :\n  forall a, repr (diag R f) (f a) -> R (f a a) (f a a).\nProof.\n  refine (fun a H => H a).\nQed.\n\nFact Lawvere_diag R f :\n  ext_repr (diag R f) f -> exists y, R y y.\nProof.\n  intros [a ?%diag_refl]. now exists (f a a).\nQed.\n\nFact Lawvere f :\n  ext_surj f -> forall R, exists y, R y y.\nProof.\n  intros Hf R. apply (Lawvere_diag R f), Hf.\nQed.\n\nFact CP_Lawvere :\n  (exists R, forall y, ~ R y y) -> forall f, ~ ext_surj f.\nProof.\n  intros [g Hg] f Hf.\n  destruct (Lawvere f Hf g) as [y ].\n  now apply (Hg y).\nQed.\n\nEnd Lawvere.\n\n\n\n\nDefinition Pow X := X -> bool.\nExample Cantor X :\n  forall f : X -> Pow X, ~ ext_surj f.\nProof.\n  intros f.\n  eapply CP_Lawvere.\n  exists (fun x y => y = negb x).\n  now intros [].\nQed.\n\nDefinition Preds X := X -> Prop.\nExample Cantor2 X :\n  forall f : X -> Preds X, ~ ext_surj f.\nProof.\n  intros f.\n  eapply CP_Lawvere.\n  exists (fun x y => (x <-> ~ y)).\n  tauto.\nQed.\n\nExample Negation X :\n  ~ exists f : X -> (X -> False), surj f.\nProof.\n  intros [f Hf].\n  now destruct (Lawvere_surj _ _ _ Hf (fun F => F)) as [[] ].\nQed.", "meta": {"author": "HermesMarc", "repo": "Coq_files", "sha": "1eea4f8c843f6ed43fca1c793c78b52ab9a45986", "save_path": "github-repos/coq/HermesMarc-Coq_files", "path": "github-repos/coq/HermesMarc-Coq_files/Coq_files-1eea4f8c843f6ed43fca1c793c78b52ab9a45986/Lawvere.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.8056321913146128, "lm_q1q2_score": 0.7471137207819871}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) : natural :=\n  plus Zero (mult y lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj84_coqofml_YEdP1f.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.747070178045825}}
{"text": "Require Export P02.\n\n\n\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H HQnot.\n  unfold not. unfold not in HQnot. intros P'. apply HQnot. apply H. apply P'.\nQed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/05/P03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7470557707527891}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_inequalitysymmetric.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral}.\n\nLemma lemma_NCdistinct :\n\tforall A B C,\n\tnCol A B C ->\n\tneq A B /\\ neq B C /\\ neq A C /\\ neq B A /\\ neq C B /\\ neq C A.\nProof.\n\tintros A B C.\n\tintros nCol_A_B_C.\n\tdestruct nCol_A_B_C as (neq_A_B & neq_A_C & neq_B_C & _).\n\tapply lemma_inequalitysymmetric in neq_A_B as neq_B_A.\n\tapply lemma_inequalitysymmetric in neq_B_C as neq_C_B.\n\tapply lemma_inequalitysymmetric in neq_A_C as neq_C_A.\n\n\trepeat split.\n\texact neq_A_B.\n\texact neq_B_C.\n\texact neq_A_C.\n\texact neq_B_A.\n\texact neq_C_B.\n\texact neq_C_A.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_NCdistinct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7470557666837276}}
{"text": "(** Homework Assignment 0#<br>#\n#<a href=\"http://www.cs.berkeley.edu/~adamc/itp/\">#Interactive Computer Theorem\nProving#</a><br>#\nCS294-9, Fall 2006#<br>#\nUC Berkeley *)\n\n(** * Installing Coq *)\n\n(** This section deals with getting Coq, the main tool we'll use in this class,\n  up and running.\n  - #<a href=\"http://coq.inria.fr/distrib-eng.html\">#Download Coq version\n    8.0#</a># from #<a href=\"http://coq.inria.fr/\">#the Coq web site#</a>#.\n    -- Version 8.1 might work for what we'll do in this class, but I haven't\n       tried it yet.\n    -- For any #<a href=\"http://www.debian.org/\">#Debian Linux#</a># fans out\n       there, there are\n       #<a href=\"http://packages.debian.org/stable/math/coq\">#Coq Debian\n       packages#</a># that aren't mentioned on the Coq download page.\n  - Following the installation instructions, you should end up with a\n    #<tt>#coqtop#</tt># program that you can invoke from a command-line.  This\n    is the simplest, text-based interface to Coq.  Try running\n    #<tt>#coqtop#</tt># and stepping through the following interactive session,\n    where the text on lines after #&lt;# prompts is for you to enter, and the\n    rest should be produced by #<tt>#coqtop#</tt>#.\n<<\nWelcome to Coq 8.0pl3 (Jan 2006)\n\nCoq < Check (1 + 1 = 2).\n1 + 1 = 2\n     : Prop\n\nCoq < Goal (1 + 1 = 2).\n1 subgoal\n  \n  ============================\n   1 + 1 = 2\n\nUnnamed_thm < trivial.\nProof completed.\n\nUnnamed_thm < Qed.\ntrivial.\nUnnamed_thm is defined\n\nCoq < ^D\n>>\n  *)\n\n(** * The Proof General Emacs mode *)\n\n(**\n  - I'm going to run briefly through how to use a particular \"IDE\" of sorts for\n    Coq.  I use\n    #<a href=\"http://proofgeneral.inf.ed.ac.uk/download\">#Proof General#</a>#\n    (#<a href=\"http://packages.debian.org/stable/editors/proofgeneral-coq\">#Debian\n    package#</a>#),\n    an Emacs mode that supports a number of proof assistants.  There's also\n    CoqIDE, the \"official\" IDE that is distributed with Coq.  I started using\n    Proof General before CoqIDE was available and never switched, so I can't\n    offer much advice on it.  You might want to try both, but, in any case,\n    having something beyond #<tt>#coqtop#</tt>#'s console interface is seriously\n    beneficial.  Without one, using Coq will feel like programming with\n    #<tt>#ed#</tt>#.\n  - Let's walk through an example with Proof\n    General.  The HTML file you're reading was actually generated from a Coq\n    source file. #<a href=\"HW0.v\">#Download it#</a># to some convenient\n    location.  Assuming you've installed Proof General for your preferred Emacs,\n    you should be able to open the HW0.v file and see a fancy Proof General\n    splash screen, followed by a syntax-highlighted display of that source file.\n  - Press C-c . to turn on \"electric period\" mode, where every press of the\n    period key is used to signal that you've finished entering a command.\n  - Move to the end of the following definition of a list datatype and press the\n    period key.  The definition should be accepted, as indicated by a message in\n    a new buffer that is opened.  A general note about this section is that I'm\n    not expecting you to understand what this code means, but rather just to get\n    a feel for the Proof General interaction process.\n  *)\n\nInductive list : Set :=\n  | nil : list\n  | cons : nat -> list -> list.\n\n(** Do the same for this recursive definition of a list append function. *)\n\nFixpoint append (ls1 ls2 : list) {struct ls1} : list :=\n  match ls1 with\n    | nil => ls2\n    | cons x ls1' => cons x (append ls1' ls2)\n  end.\n\n(** Now let's prove that [append] is associative.  Move the cursor after the\n  period in the following [Theorem] command and press the period key.\n  *)\n\nTheorem append_associative : forall ls1 ls2 ls3,\n  append (append ls1 ls2) ls3 = append ls1 (append ls2 ls3).\n\n(** In the other buffer, you should see a representation of the initial proof\n  state.  The formula we want to prove is displayed below a double-dashed line.\n  We need to specify #<i>#tactics#</i># to direct Coq in performing the proof.\n  Hit the period key at the end of the next line to send the first batch of\n  instructions, which say that we want to proceed by induction on the first\n  quantified argument [ls1].\n  *)\n\n  induction ls1; simpl; intros.\n\n(** You should now see two subgoals displayed in the other buffer; one for the\n  base ([nil]) case of the proof and one for the inductive ([cons]) case.  Now\n  we have some named variables appearing above the double-dashed line.  Their\n  presence tells us that we need to prove the formula for #<i>#any#</i># values\n  of those variables.  You can probably see that the formula in this case is\n  obviously true, so advance the proof by hitting period at the end of the next\n  line.\n  *)\n\n  trivial.\n\n(** In a less trivial case, we might have made a mistake and wish to back up.\n  Position the cursor at the #<i>#start#</i># of the previous proof line and\n  press C-c C-RET to undo the proof interaction back to that point.  After\n  undoing, you can advance forward again by hitting the period key at the end of\n  the line you want to return to, or by using C-c C-RET again with the cursor\n  positioned anywhere on the line to fast-forward to.\n\n  Now we're ready to finish the proof.  If you haven't already, fast-forward the\n  proof state back to directly after the lone [trivial] tactic.  This leaves us\n  with the task of giving the inductive step of the proof.\n\n  We have our most complicated proof state yet.  Not only are there variables of\n  types [nat] and [list] above the double line, but we also have a logical\n  assumption [IHls1] that expresses the induction hypothesis.  We can finish the\n  proof by rewriting the goal using the IH's quantified equality:\n  *)\n\n  rewrite IHls1; trivial.\n\n(** Finally, we add this named theorem to the environment: *)\nQed.\n\nPrint append_associative.\n\n(** And that's that.  There's no need to \"turn in\" this assignment, but\n  definitely #<a href=\"mailto:adamc@cs.berkeley.edu\">#let me know#</a># if you\n  run into any problems getting this basic interaction to work.\n  *)\n", "meta": {"author": "jpt4", "repo": "noq", "sha": "c8f34737be5953b3fc5fe2c04f69388d7ce85414", "save_path": "github-repos/coq/jpt4-noq", "path": "github-repos/coq/jpt4-noq/noq-c8f34737be5953b3fc5fe2c04f69388d7ce85414/HW0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.8652240912652671, "lm_q1q2_score": 0.74702723331095}}
{"text": "(** * Rel: Properties of Relations *)\n\n(* $Date: 2011-03-21 10:44:46 -0400 (Mon, 21 Mar 2011) $ *)\n\n\n(** This short chapter develops some basic definitions that will be\n    needed when we come to working with small-step operational\n    semantics in [Smallstep.v].  It can be postponed until just before\n    [Smallstep.v], but it is also a good source of good exercises for\n    developing facility with Coq's basic reasoning facilities, so it\n    may be useful to look at it just after [Logic.v]. *)\n\n(* Require Export Logic. *)\nRequire Import SfLib.\n\n(** A _relation_ is just a parameterized proposition.  As you know\n    from your undergraduate discrete math course, there are a lot of\n    ways of discussing and describing relations _in general_ -- ways\n    of classifying relations (are they reflexive, transitive, etc.),\n    theorems that can be proved generically about classes of\n    relations, constructions that build one relation from another,\n    etc.  Let us pause here to review a few that will be useful in\n    what follows. *)\n\n(** A relation _on_ a set [X] is a proposition parameterized by two\n    [X]s -- i.e., it is a logical assertion involving two values from\n    the set [X].  *)\n\nDefinition relation (X: Type) := X->X->Prop.\n\n(** Somewhat confusingly, the Coq standard library hijacks the generic\n    term \"relation\" for this specific instance. To maintain\n    consistency with the library, we will do the same.  So, henceforth\n    the Coq identifier [relation] will always refer to a binary\n    relation between some set and itself, while the English word\n    \"relation\" can refer either to the specific Coq concept or the\n    more general concept of a relation between any number of possibly\n    different sets.  The context of the discussion should always make\n    clear which is meant. *)\n\n(* ######################################################### *)\n(** * Basic Properties of Relations *)\n\n(** A relation [R] on a set [X] is a _partial function_ if, for every\n    [x], there is at most one [y] such that [R x y] -- i.e., if [R x\n    y1] and [R x y2] together imply [y1 = y2]. *)\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2. \n\n(** For example, the [next_nat] relation defined in Logic.v is a\n    partial function. *)\n\n(* Copied from Logic.v *)\nInductive next_nat (n:nat) : nat -> Prop :=\n  | nn : next_nat n (S n).\n\nTheorem next_nat_partial_function : \n   partial_function next_nat.\nProof. \n  unfold partial_function.\n  intros x y1 y2 P Q. \n  inversion P. inversion Q.\n  reflexivity.  Qed.\n\n(** However, the [<=] relation on numbers is not a partial function.\n\n    This can be shown by contradiction.  In short: Assume, for a\n    contradiction, that [<=] is a partial function.  But then, since\n    [0 <= 0] and [0 <= 1], it follows that [0 = 1].  This is nonsense,\n    so our assumption was contradictory. *)\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold not. unfold partial_function. intros H.\n  assert (0 = 1) as Nonsense.\n   Case \"Proof of assertion\".\n   apply H with 0. \n     apply le_n. \n     apply le_S. apply le_n. \n  inversion Nonsense.   Qed.\n\n(** **** Exercise: 2 stars, optional *)\n(** Show that the [total_relation] defined in Logic.v is not a partial\n    function. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\n(** Show that the [empty_relation] defined in Logic.v is a partial\n    function. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** A _reflexive_ relation on a set [X] is one that holds for every\n    element of [X]. *)\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive :\n  reflexive le.\nProof. \n  unfold reflexive. intros n. apply le_n.  Qed.\n\n(** A relation [R] is _transitive_ if [R a c] holds whenever [R a b]\n    and [R b c] do. *)\n\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  Case \"le_n\". apply Hnm.\n  Case \"le_S\". apply le_S. apply IHHmo.  Qed.\n\nTheorem lt_trans:\n  transitive lt.\nProof. \n  unfold lt. unfold transitive. \n  intros n m o Hnm Hmo.\n  apply le_S in Hnm. \n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. Qed.\n\n(** **** Exercise: 2 stars, optional *)\n(** We can also prove [lt_trans] more laboriously by induction,\n    without using le_trans.  Do this.*)\n\nTheorem lt_trans' :\n  transitive lt.\nProof.\n  (* Prove this by induction on evidence that [m] is less than [o]. *)\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [| m' Hm'o].\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\n(** Prove the same thing again by induction on [o]. *)\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The transitivity of [le], in turn, can be used to prove some facts\n    that will be useful later (e.g., for the proof of antisymmetry\n    below)... *)\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof. \n  intros n m H. apply le_trans with (S n).\n    apply le_S. apply le_n.\n    apply H.  Qed.\n\n(** **** Exercise: 1 star, optional *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_Sn_n_inf) *)\n(** Provide an informal proof of the following theorem:\n \n    Theorem: For every [n], [~(S n <= n)]\n \n    A formal proof of this is an optional exercise below, but try\n    the informal proof without doing the formal proof first.\n \n    Proof:\n    (* FILL IN HERE *)\n    []\n *)\n\n(** **** Exercise: 1 star, optional *)\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Reflexivity and transitivity are the main concepts we'll need for\n    later chapters, but, for a bit of additional practice working with\n    relations in Coq, here are a few more common ones.\n\n   A relation [R] is _symmetric_ if [R a b] implies [R b a]. *)\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** A relation [R] is _antisymmetric_ if [R a b] and [R b a] together\n    imply [a = b] -- that is, if the only \"cycles\" in [R] are trivial\n    ones. *)\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_step : forall n m p,\n  n < m ->\n  m <= S p ->\n  n <= p.\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** A relation is an _equivalence_ if it's reflexive, symmetric, and\n    transitive.  *)\n\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(** A relation is a _partial order_ when it's reflexive,\n    _anti_-symmetric, and transitive.  In the Coq standard library\n    it's called just \"order\" for short. *)\n\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\n(** A preorder is almost like a partial order, but doesn't have to be\n    antisymmetric. *)\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split. \n    Case \"refl\". apply le_reflexive.\n    split. \n      Case \"antisym\". apply le_antisymmetric. \n      Case \"transitive.\". apply le_trans.  Qed.\n\n(* ########################################################### *)\n(** * Reflexive, Transitive Closure *)\n\n(** The _reflexive, transitive closure_ of a relation [R] is the\n    smallest relation that contains [R] and that is both reflexive and\n    transitive.  Formally, it is defined like this in the Relations\n    module of the Coq standard library: *)\n\nInductive clos_refl_trans {A: Type} (R: relation A) : relation A :=\n    | rt_step : forall x y, R x y -> clos_refl_trans R x y\n    | rt_refl : forall x, clos_refl_trans R x x\n    | rt_trans : forall x y z,\n          clos_refl_trans R x y -> clos_refl_trans R y z -> clos_refl_trans R x z.\n\n(** For example, the reflexive and transitive closure of the\n    [next_nat] relation coincides with the [le] relation. *)\n\nTheorem next_nat_closure_is_le : forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m. split.\n    Case \"->\".\n      intro H. induction H. \n         apply rt_refl.\n         apply rt_trans with m. apply IHle. apply rt_step. apply nn.\n    Case \"<-\".\n      intro H. induction H.\n        SCase \"rt_step\".  inversion H. apply le_S.  apply le_n. \n        SCase \"rt_refl\". apply le_n. \n        SCase \"rt_trans\". \n           apply le_trans with y.  \n           apply IHclos_refl_trans1. \n           apply IHclos_refl_trans2.  Qed.\n\n(** The above definition of reflexive, transitive closure is\n    natural -- it says, explicitly, that the reflexive and transitive\n    closure of [R] is the least relation that includes [R] and that is\n    closed under rules of reflexivity and transitivity.  But it turns\n    out that this definition is not very convenient for doing\n    proofs -- the \"nondeterminism\" of the rt_trans rule can sometimes\n    lead to tricky inductions.\n \n    Here is a more useful definition... *)\n\nInductive refl_step_closure {X:Type} (R: relation X) \n                            : X -> X -> Prop :=\n  | rsc_refl  : forall (x : X),\n                 refl_step_closure R x x\n  | rsc_step : forall (x y z : X),\n                    R x y ->\n                    refl_step_closure R y z ->\n                    refl_step_closure R x z.\n\n(** (The following [Tactic Notation] definitions are explained in\n    Imp.v.  You can ignore them if you haven't read that chapter\n    yet.) *)\n\nTactic Notation \"rt_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"rt_step\" | Case_aux c \"rt_refl\" \n  | Case_aux c \"rt_trans\" ].\n\nTactic Notation \"rsc_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"rsc_refl\" | Case_aux c \"rsc_step\" ].\n\n(** Our new definition of reflexive, transitive closure \"bundles\"\n    the [rtc_R] and [rtc_trans] rules into the single rule step.\n    The left-hand premise of this step is a single use of [R],\n    leading to a much simpler induction principle.\n \n    Before we go on, we should check that the two definitions do\n    indeed define the same relation...\n    \n    First, we prove two lemmas showing that [rsc] mimics the behavior\n    of the two \"missing\" [rtc] constructors.  *)\n\nTheorem rsc_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> refl_step_closure R x y.\nProof.\n  intros X R x y r.\n  apply rsc_step with y. apply r. apply rsc_refl.   Qed.\n\n(** **** Exercise: 2 stars, optional (rsc_trans) *)\nTheorem rsc_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      refl_step_closure R x y  ->\n      refl_step_closure R y z ->\n      refl_step_closure R x z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Then we use these facts to prove that the two definitions of\n    reflexive, transitive closure do indeed define the same\n    relation. *)\n\n(** **** Exercise: 3 stars, optional (rtc_rsc_coincide) *)\nTheorem rtc_rsc_coincide : \n         forall (X:Type) (R: relation X) (x y : X),\n  clos_refl_trans R x y <-> refl_step_closure R x y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n", "meta": {"author": "melloc", "repo": "atomicity", "sha": "357d34f50dde3bad7bd3566d252655fb6ec4ca03", "save_path": "github-repos/coq/melloc-atomicity", "path": "github-repos/coq/melloc-atomicity/atomicity-357d34f50dde3bad7bd3566d252655fb6ec4ca03/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7470272226866849}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export tactics.\n\n(*命題に名前付けられるよ。嬉しいね。*)\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity. Qed.\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. injection H as H1. apply H1.\nQed.\n\n(*論理積の書き方*)\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\n(*and_introでsplitと同じことができる*)\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros [] []. split.\n  reflexivity. reflexivity. discriminate. discriminate. discriminate.\nQed.\n\n\n(*仮説の論理積の分解方法\n   destruct H as [Hn Hm] | \n   intros [Hn Hm]*)\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(*論理積をHn -> Hmで表記できるけど論理積の扱いは理解しよう*)\n\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP. Qed.\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof. intros P Q [HP HQ].\n       apply HQ. Qed.\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n    - apply HQ.\n    - apply HP. Qed.\n\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\nCheck and. (*Prop -> Prop -> Prop*)\n\n\n(*------------論理和----------------*)\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m [Hn | Hm].\n  -\n    rewrite Hn. reflexivity.\n  -\n    rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\n(*論理和なんだから証明は片方でいいじゃん！！*)\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros [] [] H. - left. reflexivity. - left. reflexivity.\n  - right. reflexivity. - discriminate.\nQed.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof. intros P Q [HP | HQ]. right. apply HP. left. apply HQ.\nQed.  \n\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nEnd MyNot.\n\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  destruct contra. Qed.\n\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros P notP Q HP. destruct notP. apply HP.\nQed.  \n\nNotation \"x <> y\" := (~(x = y)).\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not. discriminate.\nQed.\n\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP. Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  intros P H. unfold not. intros G. apply G. apply H. Qed.\n\nTheorem  double_neg' : forall P : Prop,\n  P -> ~~P.\nProof.\n  unfold not. intros. apply H0. apply H.\nQed.\n\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  unfold not. intros. apply H in H1. apply H0 in H1. apply H1.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof. \n  unfold not. intros P H. destruct H. apply H0 in H. apply H.\nQed.\n\n\n(*true = false などの矛盾したゴールのときは\n　apply ex_falso_quodlibet.\n　でFalseをゴールに設定できる*)\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  -\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  -\n    reflexivity.\nQed.\n\n(*exfalso.はapply ex_falso_quodlibet.の代わりに使える*)\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  -\n    unfold not in H.\n    exfalso.     apply H. reflexivity.\n  - reflexivity.\nQed.\n\n(*定数Iは予めTrueに設定されている*)\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n\n\n(*---------------------------------------*)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [HAB HBA].\n  split.\n  - apply HBA.\n  - apply HAB. Qed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  intros b. split.\n  - apply not_true_is_false.\n  -\n    intros H. rewrite H. intros H'. discriminate H'.\nQed.\n\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  split. \n  - intros. apply H.\n  - intros. apply H.\nQed.\n\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  split. intros.\n  - apply H0. apply H. apply H1.\n  - intros. apply H. apply H0. apply H1.\nQed.\n\n\nTheorem or_distributes_over_and1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  split.\n  - inversion H as [HP | [HQ HR]].\n     + left. apply HP. \n     + right.  apply HQ.\n  - inversion H as [HP | [HQ HR]].\n     + left.  apply HP. \n     + right. apply HR.\nQed.\n\nFrom Coq Require Import Setoids.Setoid.\n\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split. \n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. 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\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\n\n\n(*exists == ∃*)\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2. reflexivity.\nQed.\n\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].   exists (2 + m).\n  apply Hm. Qed.\n\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros. unfold not. intros H1. destruct H1. apply H0. apply H.\nQed.\n\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  intros. split.\n  - intros. destruct H as [m Hm]. inversion Hm as [HP | HQ].\n     + apply or_introl. exists m. apply HP.\n     + apply or_intror. exists m. apply HQ.\n  - intros. inversion H as [HH | H0]. inversion HH as [m  H2].\n     + exists m. apply or_introl. apply H2.\n     + inversion H0. exists x. apply or_intror. apply H1.\nQed.\n\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\nLemma 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.\n  induction l as [|x' l' IHl'].\n  -\n    simpl. intros [].\n  -\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\nLemma 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. split.\n  induction l as [|h t].\n  - simpl. intros [].\n  - simpl. intros [].\n    + exists h. split. apply H. left. reflexivity.\n    + apply IHt in H. destruct H as [w [F I]].\n      exists w. split. apply F. right. apply I.\n  - intros [w [F I]].\n    rewrite <- F. apply In_map. apply I.\nQed.\n\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\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n =>\n    match oddb n with\n      | true => Podd n\n      | false => Peven n\n    end.\n\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). \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    oddb n = true ->\n    Podd n.\nProof.\n  intros A B n. unfold combine_odd_even. destruct (oddb n).\n  + intros. apply H.\n  + intros. discriminate H0.\nQed. \n\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 A B n.  unfold combine_odd_even. destruct (oddb n).\n  + intros. discriminate. \n  + intros. apply H.\nQed.\n\nCheck plus_comm. (*forall n m : nat, n + m = m + n*)\n\nLemma plus_comm3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm. (*y + z + x = z + y + x*)\n  rewrite plus_comm. (*x + (y + z) = z + y + x*)\nAbort.\n\n\nLemma plus_comm3_take2 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  assert (H : y + z = z + y).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma plus_comm3_take3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite (plus_comm y z).\n  reflexivity.\nQed.\n\nLemma in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H. unfold not. intro Hl. destruct l.\n  - simpl in H. destruct H.\n  - discriminate Hl.\nQed.\n\n\nLemma in_not_nil_42 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  Fail apply in_not_nil.\nAbort.\n\nLemma in_not_nil_42_take2 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil with (x := 42).\n  apply H.\nQed.\n\nLemma in_not_nil_42_take3 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil in H.\n  apply H.\nQed.\n\nLemma in_not_nil_42_take4 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil nat 42).\n  apply H.\nQed.\n\nLemma in_not_nil_42_take5 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil _ _ _ H).\nQed.\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n\n\n\n(*------------Coq VS Set Theory-------*)\n\n(*関数の等価性*)\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. reflexivity. Qed.\n\n(*(forall x, f x = g x) -> f = g\n　　が組み込み論理ではない*)\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\nAbort.\n\n(*AxiomはAdmittedと同じ役割をするが、あとで証明するわけではないことを明示する*)\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply plus_comm.\nQed.\n\n\n(*Print Assumptions ：自分で追加した公理に依存しているか確認*)\nPrint Assumptions function_equality_ex2.\n\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\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros. apply functional_extensionality.\n  intros l. unfold tr_rev. induction l.\n  - unfold tr_rev. simpl. reflexivity.\n  - simpl. rewrite <- IHl.\n    assert ( H: forall T l1 l2, @rev_append T l1 l2 = @rev_append T l1 [] ++ l2).\n    { intros T. induction l1 as [|h' t'].\n      - reflexivity.\n      - simpl. rewrite IHt'. intros. \n        rewrite (IHt' (h'::l2)).\n        rewrite <- app_assoc. reflexivity. }\n    apply H.\nQed.\n\n(*偶数の確認方法*)\nExample even_42_bool : evenb 42 = true.\nProof. reflexivity. Qed.\nExample even_42_prop : exists k, 42 = double k.\nProof. exists 21. reflexivity. Qed.\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\nTheorem evenb_double_conv : forall n,\n  exists k, n = if evenb n then double k\n                else S (double k).\nProof.\n  intros. induction n.\n  - simpl. exists 0. reflexivity.\n  - rewrite evenb_S. destruct IHn as [w H].\n    destruct (evenb n).\n    + simpl. exists w. rewrite H. reflexivity.\n    + simpl. exists (S w). rewrite H. reflexivity.\nQed.\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\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\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n\n(*bool値はreflexivityでできる*)\nExample even_1000 : exists k, 1000 = double k.\nProof. exists 500. reflexivity. Qed.\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\nExample even_1000'' : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\n\nLemma plus_eqb_example : forall n m p : nat,\n    n == m = true -> n + p == m + p = true.\nProof.\n  intros n m p H.\n    apply eqb_eq in H.\n  rewrite H.\n  apply eqb_eq.\n  reflexivity.\nQed.\n\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros [] []. split.\n  - intros. split. reflexivity. reflexivity. \n  - intros. reflexivity.\n  - simpl. split. discriminate. intros. apply proj2 in H. apply H. \n  - split. intros. discriminate. intros. simpl. apply proj1 in H. apply H.\n  - simpl. split. discriminate. intros. apply proj1 in H. apply H.\nQed.\n\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros [] [].  split.\n  - intros. left. reflexivity.\n  - intros. simpl. reflexivity.\n  - simpl. split. intros. left. reflexivity. intros. reflexivity.\n  - simpl. split. intros. right. reflexivity. intros. reflexivity.\n  - simpl. split. intros. discriminate. intros. Search or. induction H. apply H. apply H.\nQed.\n\nTheorem eqb_neq : forall x y : nat,\n  x == y = false <-> ~(x = y).\nProof.\n  intros x y. unfold not.\n  destruct (x == y) eqn:IH. split.\n  -  discriminate.\n  -  intros. rewrite <- IH. apply eqb_true in IH. destruct H. apply IH.\n  - split. intros. destruct H0. rewrite eqb_nn in IH. discriminate.\n      + intros. reflexivity.\nQed.\n\n\nFixpoint eqb_list {A : Type} (eqb : A -> A -> bool)\n                  (l1 l2 : list A) : 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 => if (eqb h1 h2) then eqb_list eqb t1 t2\n                                             else false\n                end\nend.\n\nLemma 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.\n  induction l1 as [| a t IH].\n  - destruct l2.\n    + split.\n      intros _. reflexivity.\n      intros _. reflexivity.\n    + split.\n      * intros H'. discriminate.\n      * intros H'. discriminate.\n  - destruct l2.\n    + split.\n      * intros H'. discriminate.\n      * intros H'. discriminate.\n    + simpl. split.\n      * intros H'. apply andb_true_iff in H'.\n        destruct H' as [H1 H2].\n        apply H in H1.\n        apply IH in H2.\n        rewrite H1, H2.\n        reflexivity.\n      * intros H'.\n        injection H' as H1 H2.\n        apply H in H1.\n        apply IH in H2.\n        rewrite H1, H2.\n        reflexivity.\nQed.\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\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  - induction l. simpl. + intro. reflexivity.\n      + simpl. intros. apply andb_true_iff in H. left. apply proj1 in H. apply H.\n  - induction l. simpl. intro. reflexivity. \n      + simpl. intros H. apply andb_true_iff. induction (forallb test l).\nAdmitted.\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. apply H. reflexivity.\n  - right. unfold not. intros. apply H in H0. discriminate.\nQed.\n\nTheorem prop_no : forall (P : Prop),\n  P -> ~~P.\nProof.\n  intros. unfold not. intros. apply H0. apply H.\nQed.\n\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  unfold not. intros. apply H. right.\n  intros. apply H. left. apply H0.\nQed.\n\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  unfold excluded_middle. intros H X P H0 a. \n   assert ( P a \\/ ~ P a).  apply H.\n   inversion H1. apply H2. apply ex_falso_quodlibet.\n   unfold not in H0. apply H0. unfold not in H2. exists a.\n   apply H2.\nQed.\n  \n\n\n(*以下の４つとexcluded_middle は等価である証明\n  できたらやる。*)\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\n\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\n\nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\n\nLemma In_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros. split. induction l.\n  - simpl. intros. right. apply H.\n  - simpl. induction l'.\n      + simpl. rewrite app_nil_r. rewrite app_nil_r in IHl. simpl in IHl. intros. left. apply H.\n      + simpl. simpl in IHl. intros.\nAdmitted.\n\n(*\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n intros P Q R H. inversion H. inversion H0.\n - left. apply H2.\n - apply  or_commut in H0. Search and. apply proj1 in H0. inversion H1.\n    + left. apply H3.\n    + apply (and_commut R Q). Search and. rewrite proj2. generalize dependent H2. apply (or_intror R Q ). apply or_commut in H1. apply  Search or. split. \n    + right.  Search and. apply (proj2 Q R).  apply H.\n\n\n\n\n\nLemma 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 [|h t].\n    + reflexivity.\n    + intros. simpl.\n      left. apply H. simpl. left. reflexivity.\n  - induction l as [|h t].\n    + intros. inversion H0.\n    + intros. simpl in H0. simpl in H.  \n      apply IHt. generalize dependent H. Search or. apply or_comm.\n apply proj2 with (P h ). Search and. in H.  apply H. inversion H.\n      inversion H0. apply or_intro in H. inversion H. rewrite H1 in H2.\n      apply H2. \n      destruct H as [PH | APT].*)\n\n", "meta": {"author": "NeM-T", "repo": "sfc", "sha": "e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e", "save_path": "github-repos/coq/NeM-T-sfc", "path": "github-repos/coq/NeM-T-sfc/sfc-e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e/practice/Coq/SF/1st/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.7470272105621514}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export ZArithRing.\n\n(* Exercise 5.1, too simple *)\n\n(* Exercise 5.2 *)\nTheorem all_perm : forall (A: Type) (P: A -> A -> Prop), (forall x y: A, P x y) -> forall x y: A, P y x.\nProof.\n  intros A P Hp x y; apply (Hp y x).\nQed.\n\nPrint all_perm.\n\nTheorem resolution :\n  forall (A:Type) (P Q R S: A -> Prop), (forall a:A, Q a -> R a -> S a) -> (forall b:A, P b -> Q b) -> (forall c:A, P c -> R c -> S c).\nProof.\n  intros A P Q R S Hqrs Hpq c Hp Hr.\n  apply Hqrs; [apply Hpq | idtac]; assumption.\nQed.\n\n(* Exercise 5.3 *)\n\nTheorem modus_ponens : forall P Q:Prop, P -> (P -> Q) -> Q.\nProof.\n  intros P Q p Hp; apply Hp; assumption.\nQed.\n\nLemma ex_5_3_1 : ~False.\nProof.\n  intros Hf. elim Hf.\nQed.\n\n(* double negation elimination *)\nLemma ex_5_3_2 : forall P: Prop, ~~~P -> ~P.\nProof.\n  intros P Hp Cp. unfold not in Hp.\n  apply Hp. intros Hp0. apply Hp0.\n  assumption.\nQed.\n\n(* did not use elim *)\nLemma ex_5_3_3 : forall P Q: Prop, (P -> Q) -> ~Q -> ~P.\nProof.\n  intros P Q Hpq Cp Hq.\n  apply Cp; apply Hpq; assumption.\nQed.\n\n(* for some reason i cannot use the absurd thm *)\nLemma ex_5_3_4 : forall P Q R: Prop, (P -> Q) -> (P -> ~Q) -> P -> R.\nProof.\n  unfold not; intros P Q R Hpq Hpnq Hp.\n  elim Hpnq; [assumption | apply Hpq; assumption].\nQed.\n\n(* Exercise 5.4 *)\n\n(* Definition dyslexic_contrap : forall P Q: Prop, (P -> Q) -> (~P -> ~Q). *)\n\nTheorem dys_imp_f :\n  (forall P Q: Prop, (P -> Q) -> (Q -> P)) -> False.\nProof.\n  intros Hd; apply (Hd False True);\n    [intros C; elim C | apply I].\nQed.\n\nTheorem dys_contrap_f :\n  (forall P Q: Prop, (P -> Q) -> (~P -> ~Q)) -> False.\nProof.\n  intros Hc; apply (Hc False True);\n    try (intros C; elim C); apply I.\nQed.\n\n(* Exercise 5.5 *)\n\nTheorem ex_5_5 : forall (A: Set) (a b c d: A), a=c \\/ b=c \\/ c=c \\/ d=c.\nProof.\n  intros A a b c d;\n    right; right; left; reflexivity.\nQed.\n\n(* Exercise 5.6 *)\n\nLemma ex_5_6_1 :\n  forall A B C: Prop, A /\\ (B /\\ C) -> (A /\\ B) /\\ C.\nProof.\n  intros A B C H.\n  destruct H as [Ha [Hb Hc]];\n  repeat split; assumption.\nQed.\n\nLemma ex_5_6_2 :\n  forall A B C D: Prop, (A -> B) /\\ (C -> D) /\\ A /\\ C -> B /\\ D.\nProof.\n  intros A B C D [Hab [Hcd [Ha Hc]]]; split;\n    [apply Hab | apply Hcd]; assumption.\nQed.\n\nLemma ex_5_6_3 :\n  forall A: Prop, ~(A /\\ ~A).\nProof.\n  intros A [C1 C2]; apply C2; assumption.\nQed.\n\nLemma ex_5_6_4 :\n  forall A B C: Prop, A \\/ (B \\/ C) -> (A \\/ B) \\/ C.\nProof.\n  intros A B C [Ha | [Hb | Hc]];\n    [ left; left | left; right | right ];\n    assumption.\nQed.\n\nLemma ex_5_6_5 :\n  forall A: Prop, ~~(A \\/ ~A).\nProof.\n  unfold not;\n    intros A C; apply C; right; intros Ha;\n      apply C; left; assumption.\nQed.\n\nLemma ex_5_6_6 :\n  forall A B: Prop, (A \\/ B) /\\ ~A -> B.\nProof.\n  intros A B [[Ha | Hb] Ca];\n    [elim Ca | idtac ]; assumption.\nQed.\n\n(* Exercise 5.7 *)\n\nDefinition peirce := forall P Q: Prop, ((P -> Q) -> P) -> P.\nDefinition classic := forall P: Prop, ~~P -> P.\nDefinition excluded_middle := forall P: Prop, P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q: Prop, ~(~P /\\ ~Q) -> P \\/ Q.\nDefinition implies_to_or := forall P Q: Prop, (P -> Q) -> (~P \\/ Q).\n\nLemma ex_5_7_1:\n  peirce -> classic.\nProof.\n  unfold peirce, classic, not; intros H P Hp.\n  apply (H P False). intros H0; elim Hp; assumption.\nQed.\n\nLemma ex_5_7_2:\n  classic -> excluded_middle.\nProof.\n  unfold classic, excluded_middle; intros H P;\n    apply H; intros H0.\n  absurd P.\n  - intros Hp; apply H0; now left.\n  - apply H; intros Cp; apply H0; now right.\nQed.\n\nLemma ex_5_7_3:\n  excluded_middle -> de_morgan_not_and_not.\nProof.\n  unfold excluded_middle, de_morgan_not_and_not.\n  intros H P Q Hpq.\n  destruct (H P) as [Hp | Cp];\n    destruct (H Q) as [Hq | Cq];\n    [ left | left | right | elim Hpq; split ];\n    assumption.\nQed.\n\nLemma pp: forall P: Prop, P -> P.\nProof.\n  (intros P Hp; assumption). Qed.\n\nLemma ex_5_7_4':\n  de_morgan_not_and_not -> classic.\nProof.\n  unfold de_morgan_not_and_not, classic.\n  intros H P Cp.\n  apply or_ind with (A:=P) (B:=P);\n    [apply pp | apply pp | idtac].\n  apply H; intros [Hc _].\n  apply Cp; assumption.\nQed.\n\nLemma ex_5_7_4:\n  de_morgan_not_and_not -> implies_to_or.\nProof.\n  unfold de_morgan_not_and_not, implies_to_or;\n    intros Hm P Q Hpq.\n  apply Hm; intros [Cp Cq].\n  apply Cq. apply Hpq.\n  apply ex_5_7_4';\n    [intros | idtac]; assumption.\nQed.\n\nLemma ex_5_7_5:\n  implies_to_or -> peirce.\nProof.\n  unfold implies_to_or, peirce;\n    intros Hpq P Q H.\n  assert (Hc: ~P \\/ P) by (apply Hpq; now intros Hp).\n  destruct Hc.\n  - apply H; intros Hp; elim (H0 Hp).\n  - assumption.\nQed.\n\n(* Exercise 5.9 *)\n\nSection Ex_5_9.\n  Variable A:Set.\n  Variables P Q: A -> Prop.\n\n  Theorem ex_5_9_1:\n    (exists x: A, P x \\/ Q x) -> (ex P) \\/ (ex Q).\n  Proof.\n    intros H; elim H; clear H; intros x [H | H];\n      [left | right]; now exists x.\n  Qed.\n\n  Theorem ex_5_9_2:\n    (ex P) \\/ (ex Q) -> exists x: A, P x \\/ Q x.\n  Proof.\n    intros [H | H];\n      elim H; clear H; intros x H;\n    exists x; [left | right]; assumption.\n  Qed.\n\n  Theorem ex_5_9_3:\n    (exists x: A, (forall R: A -> Prop, R x)) -> 2 = 3.\n  Proof.\n    intros H; elim H; clear H; intros a Hr.\n    elim (Hr (fun _ => False)).\n  Qed.\n\n  Theorem ex_5_9_4:\n    (forall x:A, P x) -> ~(exists y: A, ~ P y).\n  Proof.\n    intros H Hy; elim Hy; clear Hy; intros y Hy.\n    elim (Hy (H y)).\n  Qed.\n\nEnd Ex_5_9.\n\n(* Exercise 5.10 *)\n\nTheorem plus_permute2:\n  forall n m p: nat, n + m + p = n + p + m.\nProof.\n  intros n m p.\n  rewrite <- plus_assoc.\n  pattern (m + p).\n  rewrite plus_comm.\n  rewrite plus_assoc.\n  reflexivity.\nQed.\n\n(* Exercise 5.11 *)\n\nTheorem eq_trans:\n  forall (A: Type) (x y z: A), x = y -> y = z -> x = z.\nProof.\n  intros A x y z Hxy Hyz.\n  apply eq_ind with (x:=y);\n    assumption.\n  Restart.\n  intros A x y z Hxy Hyz.\n  rewrite Hxy, Hyz.\n  reflexivity.\nQed.\n\nModule Impredicative.\n  Definition mTrue : Prop := forall P: Prop, P -> P.\n  Definition mFalse : Prop := forall P: Prop, P.\n\n  Theorem mFalse_ind : forall P: Prop, mFalse -> P.\n  Proof. intros P Hf; apply Hf. Qed.\n\n  (* Exercise 5.12 *)\n\n  Theorem myI : mTrue.\n  Proof (fun P p => p). \n\n  Theorem mFalse_ind' : forall P: Prop, mFalse -> P.\n  Proof (fun P Hf => Hf P).\n\n  (* Exercise 5.13 *)\n  Definition mNot (P: Prop): Prop := P -> mFalse.\n\n  Lemma ex_5_3_1 : mNot mFalse.\n  Proof.\n    unfold mNot, mFalse.\n    intros Hf P. apply Hf.\n  Qed.\n\nEnd Impredicative.\nExport Impredicative.\n\nSection leibniz.\n  Set Implicit Arguments.\n  Unset Strict Implicit.\n  Variable A: Set.\n\n  Definition leibniz (a b: A): Prop := forall P: A -> Prop, P a -> P b.\n\n  Require Import Relations.\n  \n\n  Theorem leibniz_sym : symmetric A leibniz.\n  Proof.\n    unfold symmetric.\n    intros x y H.\n    now apply H.\n  Qed.\n\n  (* Exercise 5.14 *)\n  Theorem leibniz_refl: reflexive A leibniz.\n  Proof. easy. Qed.\n\n  Theorem leibniz_trans: transitive A leibniz.\n  Proof.\n    unfold transitive; intros x y z Hxy Hyz;\n      apply Hyz; apply Hxy.\n  Qed.\n\n  Theorem leibniz_quiv: equiv A leibniz.\n  Proof.\n    unfold equiv; split;\n      [apply leibniz_refl | split;\n                            [apply leibniz_trans | apply leibniz_sym]].\n  Qed.\n\n  Theorem leibniz_least_reflexive:\n    forall R: relation A, reflexive A R -> inclusion A leibniz R.\n  Proof.\n    intros R Hrefl x y Hl;\n      apply Hl; apply Hrefl.\n  Qed.\n\n  Theorem leibniz_eq: forall a b: A, leibniz a b -> a = b.\n  Proof.\n    intros a b Hl;\n      apply Hl; reflexivity.\n  Qed.\n\n  Theorem eq_leibniz: forall a b: A, a = b -> leibniz a b.\n  Proof.\n    intros a b He;\n      rewrite He; apply leibniz_refl.\n  Qed.\n\n  Theorem leibniz_ind:\n    forall (x: A) (P: A -> Prop), P x -> forall y: A, leibniz x y -> P y.\n  Proof.\n    intros x P Hp y Hl;\n      now apply Hl.\n  Qed.    \n\n  Definition mAnd (P Q: Prop) := forall R: Prop, (P -> Q -> R) -> R.\n  Definition mOr  (P Q: Prop) := forall R: Prop, (P -> R) -> (Q -> R) -> R.\n  Definition mEx  (A: Set) (P: A -> Prop) := forall R: Prop, (forall x: A, P x -> R) -> R.\n\n  (* Exercise 5.15 *)\n  Section ex_5_15.\n    Variables P Q R: Prop.\n    Variable  PA : A -> Prop.\n\n    Theorem ex_5_15_1: mAnd P Q -> P.\n    Proof.\n      intros H; apply H; now intros P' Q'.\n    Qed.\n\n    Theorem ex_5_15_2: mAnd P Q -> Q.\n    Proof.\n      intros H; apply H; now intros P' Q'.\n    Qed.\n\n    Theorem ex_5_15_3: (P -> Q -> R) -> mAnd P Q -> R.\n    Proof.\n      intros Hpqr H;\n        apply H; apply Hpqr.\n    Qed.\n\n    Theorem ex_5_15_4: P -> mOr P Q.\n    Proof.\n      intros P' p Hp Hq;\n        now apply Hp.\n    Qed.      \n\n    Theorem ex_5_15_5: Q -> mOr P Q.\n    Proof.\n      intros Q' p Hp Hq;\n        now apply Hq.\n    Qed.\n\n    Theorem ex_5_15_6: (P -> R) -> (Q -> R) -> mOr P Q -> R.\n    Proof.\n      intros Hpr Hqr Hpq;\n        apply Hpq; [apply Hpr | apply Hqr].\n    Qed.\n\n    Theorem ex_5_15_7: mOr P mFalse -> P.\n    Proof.\n      intros Hor; apply Hor;\n        [trivial | apply mFalse_ind].\n    Qed.\n\n    Theorem ex_5_15_8: mOr P Q -> mOr Q P.\n    Proof.\n      intros Hor P' Hqr Hpr.\n      apply Hor; assumption.\n    Qed.\n\n    Theorem ex_5_15_9: forall a: A, PA a -> mEx PA.\n    Proof.\n      intros a H R0 He.\n      now apply (He a). \n    Qed.\n\n    Theorem ex_5_15_10:\n      mNot (mEx PA) -> forall a: A, mNot (PA a).\n    Proof.\n      intros H a Hpa;\n        unfold mNot, mEx in *.\n      apply H; clear H; intros R0 Hr.\n      now apply (Hr a).\n    Qed.\n  End ex_5_15.\n\n  Definition mLe (n p: nat) :=\n    forall P: nat -> Prop, P n -> (forall q: nat, P q -> P (S q)) -> P p.\n\n  (* Exercise 5.16 *)\n\n  Lemma my_le_n: forall n: nat, mLe n n.\n  Proof.\n    now intros n P Hn Hq.\n  Qed.\n\n  Lemma my_le_S:\n    forall n p: nat, mLe n p -> mLe n (S p).\n  Proof.\n    intros n p Hnp P Hrefl Hind.\n    apply Hnp.\n    - apply Hind; assumption.\n    - intros q; apply (Hind (S q)).\n  Qed.\n\n  Lemma my_le_le: forall n p: nat, mLe n p -> n <= p.\n  Proof.\n    unfold mLe; intros n p Hle.\n    apply Hle;\n      [apply le_refl | apply le_S].\n  Qed.\n\nUnset Implicit Arguments.\nEnd leibniz.", "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/ch5_everydays_logic/hw5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7470272074800217}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia Permutation.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import list_focus utils_tac.\n\nSet Implicit Arguments.\n\nCreate HintDb length_db.\n\nTactic Notation \"rew\" \"length\" := autorewrite with length_db.\nTactic Notation \"rew\" \"length\" \"in\" hyp(H) := autorewrite with length_db in H.\n\nInfix \"~p\" := (@Permutation _) (at level 70).\n\nSection In_t.\n\n  Variable (X : Type).\n\n  Fixpoint In_t (x : X) l : Type :=\n    match l with\n      | nil  => False\n      | y::l => ((y = x) + In_t x l)%type\n    end.\n\n  Fact In_t_In x l : In_t x l -> In x l.\n  Proof. induction l; simpl; tauto. Qed.\n\n  Fact In_In_t x l (P : Prop) : (In_t x l -> P) -> In x l -> P.\n  Proof.\n    induction l as [ | y l IHl ].\n    + intros _ [].\n    + intros H1 [ -> | H2 ]. \n      * apply H1; simpl; auto.\n      * apply IHl; auto.\n        intros; apply H1; simpl; auto.\n  Qed.\n\nEnd In_t.\n\nSection length.\n   \n  Variable X : Type.\n\n  Implicit Type l : list X.\n\n  Fact length_nil : length (@nil X) = 0.\n  Proof. auto. Qed.\n\n  Fact length_cons x l : length (x::l) = S (length l).\n  Proof. auto. Qed.\n\nEnd length.\n\nGlobal Hint Rewrite length_nil length_cons app_length map_length rev_length : length_db.\n\nSection list_an.\n\n  Fixpoint list_an a n :=\n    match n with \n      | 0   => nil\n      | S n => a::list_an (S a) n\n    end.\n\n  Fact list_an_S a n : list_an a (S n) = a::list_an (S a) n.\n  Proof. auto. Qed. \n\n  Fact list_an_plus a n m : list_an a (n+m) = list_an a n ++ list_an (n+a) m.\n  Proof.\n    revert a; induction n; intros a; simpl; auto.\n    rewrite IHn; do 3 f_equal; lia.\n  Qed.\n\n  Fact list_an_length a n : length (list_an a n) = n.\n  Proof.\n    revert a; induction n; intro; simpl; f_equal; auto.\n  Qed.\n  \n  Fact list_an_spec a n m : In m (list_an a n) <-> a <= m < a+n.\n  Proof.\n    revert a; induction n as [ | n IHn ]; simpl; intros a; [ | rewrite IHn ]; lia. \n  Qed.\n\n  Fact map_S_list_an a n : map S (list_an a n) = list_an (S a) n.\n  Proof. revert a; induction n; simpl; intro; f_equal; auto. Qed.\n\n  Fact list_an_app_inv a n l r : list_an a n = l++r -> l = list_an a (length l) /\\ r = list_an (a+length l) (length r).\n  Proof.\n    revert a l r; induction n as [ | n IHn ]; intros a l r; simpl.\n    + destruct l; destruct r; intros; auto; discriminate.\n    + destruct l as [ | x l ]; simpl; intros H1.\n      * split; auto.\n        rewrite <- H1; simpl; rewrite Nat.add_0_r, list_an_length; auto.\n      * injection H1; clear H1; intros H1 H0.\n        apply IHn in H1; destruct H1; split; f_equal; auto.\n        rewrite H1 at 1; f_equal; lia.\n  Qed.\n\n  Fact list_an_duplicate_inv a n l x m y r : \n        list_an a n = l++x::m++y::r -> a <= x /\\ x < y < a+n.\n  Proof.\n    intros H.\n    generalize H; intros H1.\n    apply f_equal with (f := @length _) in H1.\n    rewrite list_an_length in H1.\n    apply list_an_app_inv in H; simpl in H.\n    destruct H as (E1 & H); injection H; clear H; intros H E2.\n    symmetry in H; apply list_an_app_inv in H; simpl in H.\n    destruct H as (E3 & H); injection H; clear H; intros E4 E5.\n    do 2 (rewrite app_length in H1; simpl in H1).\n    lia.\n  Qed.\n\nEnd list_an.\n\nGlobal Hint Rewrite list_an_length : length_db.\n\nDefinition list_fun_inv X (l : list X) (x : X) : { f : nat -> X | l = map f (list_an 0 (length l)) }.\nProof.\n  induction l as [ | y l IHl ].\n  + exists (fun _ => x); auto.\n  + destruct IHl as (f & Hf).\n    exists (fun i => match i with 0 => y | S i => f i end); simpl.\n    f_equal.\n    rewrite Hf, <- map_S_list_an, map_length, list_an_length, map_map; auto.\nQed.\n\nFact list_upper_bound (l : list nat) : { m | forall x, In x l -> x < m }.\nProof.\n  induction l as [ | x l (m & Hm) ].\n  + exists 0; simpl; tauto.\n  + exists (1+x+m); intros y [ [] | H ]; simpl; try lia.\n    generalize (Hm _ H); intros; lia.\nQed.\n\nSection list_injective.\n\n  Variable X : Type.\n   \n  Definition list_injective (ll : list X) :=  forall l a m b r, ll = l ++ a :: m ++ b :: r -> a <> b.\n  \n  Fact in_list_injective_0 : list_injective nil.\n  Proof. intros [] ? ? ? ? ?; discriminate. Qed.\n  \n  Fact in_list_injective_1 x ll : ~ In x ll -> list_injective ll -> list_injective (x::ll).\n  Proof.\n    intros H1 H2 l a m b r H3.\n    destruct l as [ | u l ].\n    inversion H3; subst.\n    destruct m as [ | v m ].\n    contradict H1; subst; simpl; auto.\n    contradict H1; subst; simpl; right; apply in_or_app; right; left; auto.\n    inversion H3; subst.\n    apply (H2 l _ m _ r); auto.\n  Qed.\n  \n  Fact list_injective_inv x ll : list_injective (x::ll) -> ~ In x ll /\\ list_injective ll.\n  Proof.\n    split.\n    intros H1; apply in_split in H1; destruct H1 as (l & r & ?); subst.\n    apply (H nil x l x r); auto.\n    intros l a m b r ?; apply (H (x::l) a m b r); subst; solve list eq.\n  Qed.\n  \n  Variable P : list X -> Type.\n  \n  Hypothesis (HP0 : P nil).\n  Hypothesis (HP1 : forall x l, ~ In x l -> P l -> P (x::l)).\n  \n  Theorem list_injective_rect l : list_injective l -> P l.\n  Proof using HP0 HP1.\n    induction l as [ [ | x l ] IHl ] using (measure_rect (@length _)).\n    intro; apply HP0.\n    intros; apply HP1.\n    apply list_injective_inv, H.\n    apply IHl; simpl; auto.\n    apply list_injective_inv with (1 := H).\n  Qed.\n\nEnd list_injective.\n\nFact list_injective_map X Y (f : X -> Y) ll :\n       (forall x y, f x = f y -> x = y) -> list_injective ll -> list_injective (map f ll).\nProof.\n  intros Hf.\n  induction 1 as [ | x l Hl IHl ] using list_injective_rect.\n  apply in_list_injective_0.\n  simpl; apply in_list_injective_1; auto.\n  contradict Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (y & Hl & ?).\n  apply Hf in Hl; subst; auto.\nQed.\n\nFact list_app_head_not_nil X (u v : list X) : u <> nil -> v <> u++v.\nProof.\n  intros H; contradict H.\n  destruct u as [ | a u ]; auto; exfalso.\n  apply f_equal with (f := @length _) in H.\n  revert H; simpl; rewrite app_length; intros; lia.\nQed.\n\nSection iter.\n  \n  Variable (X : Type) (f : X -> X).\n\n  Fixpoint iter x n :=\n    match n with\n      | 0   => x\n      | S n => iter (f x) n\n    end.\n\n  Fact iter_plus x a b : iter x (a+b) = iter (iter x a) b.\n  Proof. revert x; induction a; intros x; simpl; auto. Qed.\n\n  Fact iter_swap x n : iter (f x) n = f (iter x n).\n  Proof. \n    change (iter (f x) n) with (iter x (1+n)).\n    rewrite Nat.add_comm, iter_plus; auto.\n  Qed.\n\n  Fact iter_S x n : iter x (S n) = f (iter x n).\n  Proof. apply iter_swap. Qed.\n\nEnd iter.\n\nFixpoint list_repeat X (x : X) n :=\n  match n with\n    | 0   => nil\n    | S n => x::list_repeat x n\n  end.\n  \nFact list_repeat_plus X x a b : @list_repeat X x (a+b) = list_repeat x a ++ list_repeat x b.\nProof. induction a; simpl; f_equal; auto. Qed.\n  \nFact list_repeat_length X x n : length (@list_repeat X x n) = n.\nProof. induction n; simpl; f_equal; auto. Qed.\n\nFact In_list_repeat X (x y : X) n : In y (list_repeat x n) -> x = y /\\ 0 < n.\nProof.\n  induction n; simpl; intros [].\n  split; auto; lia.\n  split; try lia; apply IHn; auto.\nQed.\n\nFact map_list_repeat X Y f x n : @map X Y f (list_repeat x n) = list_repeat (f x) n.\nProof. induction n; simpl; f_equal; auto. Qed.\n\nFact map_cst_repeat X Y (y : Y) ll : map (fun _ : X => y) ll = list_repeat y (length ll).\nProof. induction ll; simpl; f_equal; auto. Qed.\n  \nFact map_cst_snoc X Y (y : Y) ll mm : y :: map (fun _ : X => y) ll++mm = map (fun _ => y) ll ++ y::mm.\nProof. induction ll; simpl; f_equal; auto. Qed.\n\nFact map_cst_rev  X Y (y : Y) ll : map (fun _ : X => y) (rev ll) = map (fun _ => y) ll.\nProof. do 2 rewrite map_cst_repeat; rewrite rev_length; auto. Qed.\n\nFact In_perm X (x : X) l : In x l -> exists m, x::m ~p l.\nProof.\n  intros H; apply in_split in H.\n  destruct H as (m & k & ?); subst.\n  exists (m++k).\n  apply Permutation_cons_app; auto.\nQed.\n\nFact list_app_eq_inv X (l1 l2 r1 r2 : list X) :\n       l1++r1 = l2++r2 -> { m | l1++m = l2 /\\ r1 = m++r2 } \n                        + { m | l2++m = l1 /\\ r2 = m++r1 }.\nProof.\n  revert l2 r1 r2; induction l1 as [ | x l1 IH ].\n  intros; left; exists l2; auto.\n  intros [ | y l2 ] r1 r2; simpl; intros H.\n  right; exists (x::l1); auto.\n  inversion H.\n  destruct (IH l2 r1 r2) as [ (m & Hm) | (m & Hm) ]; auto; \n    [ left | right ]; exists m; split; f_equal; tauto.\nQed.\n\nFact list_app_cons_eq_inv X (l1 l2 r1 r2 : list X) x :\n       l1++r1 = l2++x::r2 -> { m | l1++m = l2 /\\ r1 = m++x::r2 } \n                           + { m | l2++x::m = l1 /\\ r2 = m++r1 }.\nProof.\n  intros H.\n  apply list_app_eq_inv in H.\n  destruct H as [ H | (m & H1 & H2) ]; auto.\n  destruct m as [ | y m ].\n  left; exists nil; simpl in *; split; auto.\n  revert H1; do 2 rewrite <- app_nil_end; auto.\n  inversion H2; subst.\n  right; exists m; auto.\nQed.\n\nFact list_cons_app_cons_eq_inv X (l2 r1 r2 : list X) x y :\n       x::r1 = l2++y::r2 -> (l2 = nil /\\ x = y /\\ r1 = r2) \n                          + { m | l2 = x::m /\\ r1 = m++y::r2 }.\nProof.\n  intros H.\n  destruct l2 as [ | z m ]; simpl in H.\n  + left; inversion H; auto.\n  + right; exists m; inversion H; auto.\nQed.\n \nFact list_app_inj X (l1 l2 r1 r2 : list X) : length l1 = length l2 -> l1++r1 = l2++r2 -> l1 = l2 /\\ r1 = r2.\nProof.\n  revert l2; induction l1 as [ | x l1 IH ]; intros [ | y l2 ]; try discriminate.\n  simpl; auto.\n  intros H1 H2; inversion H1; inversion H2.\n  apply IH in H4; auto.\n  split; f_equal; tauto.\nQed.\n\nFact list_split_length X (ll : list X) k : k <= length ll -> { l : _ & { r | ll = l++r /\\ length l = k } }.\nProof.\n  revert k; induction ll as [ | x ll IHll ]; intros k.\n  exists nil, nil; split; simpl in * |- *; auto; lia.\n  destruct k as [ | k ]; intros Hk.\n  exists nil, (x::ll); simpl; split; auto.\n  destruct (IHll k) as (l & r & H1 & H2).\n  simpl in Hk; lia.\n  exists (x::l), r; split; simpl; auto; f_equal; auto.\nQed.\n\nFact list_pick X (ll : list X) k : k < length ll -> { x : _ & { l : _ & { r | ll = l++x::r /\\ length l = k } } }.\nProof.\n  revert k; induction ll as [ | x ll IHll ]; intros k.\n  simpl; lia.\n  destruct k as [ | k ]; intros H.\n  exists x, nil, ll; simpl; auto.\n  simpl in H.\n  destruct IHll with (k := k) as (y & l & r & ? & ?); try lia.\n  exists y, (x::l), r; subst; simpl; split; auto.\nQed.\n\nFact list_split_middle X l1 (x1 : X) r1 l2 x2 r2 : \n       ~ In x1 l2 -> ~ In x2 l1 -> l1++x1::r1 = l2++x2::r2 -> l1 = l2 /\\ x1 = x2 /\\ r1 = r2.\nProof.\n  intros H1 H2 H.\n  apply list_app_eq_inv in H.\n  destruct H as [ (m & H3 & H4) | (m & H3 & H4) ]; destruct m.\n  inversion H4; subst; rewrite <- app_nil_end; auto.\n  inversion H4; subst; destruct H1; apply in_or_app; right; left; auto.\n  inversion H4; subst; rewrite <- app_nil_end; auto.\n  inversion H4; subst; destruct H2; apply in_or_app; right; left; auto.\nQed.\n\nSection flat_map.\n\n  Variable (X Y : Type) (f : X -> list Y).\n\n  Fact flat_map_app l1 l2 : flat_map f (l1++l2) = flat_map f l1 ++ flat_map f l2.\n  Proof.\n    induction l1; simpl; auto; solve list eq; f_equal; auto.\n  Qed.\n\n  Fact flat_map_app_inv l r1 y r2 : flat_map f l = r1++y::r2 -> exists l1 m1 x m2 l2, l = l1++x::l2 /\\ f x = m1++y::m2 \n                                                                  /\\ r1 = flat_map f l1++m1 /\\ r2 = m2++flat_map f l2. \n  Proof.\n    revert r1 y r2.\n    induction l as [ | x l IHl ]; intros r1 y r2 H.\n    + destruct r1; discriminate.\n    + simpl in H.\n      apply list_app_cons_eq_inv in H.\n      destruct H as [ (m & Hm1 & Hm2) | (m & Hm1 & Hm2) ].\n      - apply IHl in Hm2.\n        destruct Hm2 as (l1 & m1 & x' & m2 & l2 & G1 & G2 & G3 & G4); subst.\n        exists (x::l1), m1, x', m2, l2; simpl; repeat (split; auto).\n        rewrite app_ass; auto.\n      - exists nil, r1, x, m, l; auto.\n  Qed.\n\nEnd flat_map.\n\nFact in_concat_iff X (ll : list (list X)) x : In x (concat ll) <-> exists l, In x l /\\ In l ll.\nProof.\n  rewrite <- (map_id ll) at 1.\n  rewrite <- flat_map_concat_map, in_flat_map.\n  firstorder.\nQed.\n\nFact flat_map_flat_map X Y Z (f : X -> list Y) (g : Y -> list Z) l : \n       flat_map g (flat_map f l) = flat_map (fun x => flat_map g (f x)) l.\nProof.\n  induction l; simpl; auto.\n  rewrite flat_map_app; f_equal; auto.\nQed.\n\nFact flat_map_single X Y (f : X -> Y) l : flat_map (fun x => f x::nil) l = map f l.\nProof. induction l; simpl; f_equal; auto. Qed.\n\nSection list_in_map.\n\n  Variable (X Y : Type).\n\n  Fixpoint list_in_map l : (forall x, @In X x l -> Y) -> list Y.\n  Proof.\n    refine (match l with\n      | nil  => fun _ => nil\n      | x::l => fun f => f x _ :: @list_in_map l _\n    end).\n    + left; auto.\n    + intros y Hy; apply (f y); right; auto.\n  Defined.\n\n  Theorem In_list_in_map l f x (Hx : In x l) : In (f x Hx) (list_in_map l f).\n  Proof.\n    revert f x Hx.\n    induction l as [ | x l IHl ]; intros f y Hy.\n    + destruct Hy.\n    + destruct Hy as [ -> | Hy ].\n      * left; auto.\n      * right.\n        apply (IHl (fun z Hz => f z (or_intror Hz))).\n  Qed.\n\n  Theorem In_list_in_map_inv l f y : In y (list_in_map l f) -> exists x Hx, y = f x Hx.\n  Proof.\n    revert f y; induction l as [ | x l IHl ]; intros f y; simpl; try tauto.\n    intros [ H | H ].\n    + now exists x, (or_introl eq_refl).\n    + destruct IHl with (1 := H) as (z & Hz & E).\n      now exists z, (or_intror Hz).\n  Qed.\n\nEnd list_in_map.\n\nDefinition prefix X (l ll : list X) := exists r, ll = l++r.\n  \nInfix \"<p\" := (@prefix _) (at level 70, no associativity).\n  \nSection prefix. (* as an inductive predicate *)\n   \n  Variable X : Type.\n  \n  Implicit Types (l ll : list X).\n  \n  Fact in_prefix_0 ll : nil <p ll.\n  Proof.\n    exists ll; auto.\n  Qed.\n  \n  Fact in_prefix_1 x l ll : l <p ll -> x::l <p x::ll.\n  Proof.\n    intros (r & ?); subst; exists r; auto.\n  Qed.\n\n  Fact prefix_length l m : l <p m -> length l <= length m.\n  Proof. intros (? & ?); subst; rew length; lia. Qed.\n  \n  Fact prefix_app_lft l r1 r2 : r1 <p r2 -> l++r1 <p l++r2.\n  Proof.\n    intros (a & ?); subst.\n    exists a; rewrite app_ass; auto.\n  Qed.\n  \n  Fact prefix_inv x y l ll : x::l <p y::ll -> x = y /\\ l <p ll.\n  Proof.\n    intros (r & Hr).\n    inversion Hr; split; auto.\n    exists r; auto.\n  Qed.\n  \n  Fact prefix_list_inv l r rr : l++r <p l++rr -> r <p rr.\n  Proof.\n    induction l as [ | x l IHl ]; simpl; auto.\n    intros H; apply prefix_inv, proj2, IHl in H; auto.\n  Qed.\n\n  Fact prefix_refl l : l <p l.\n  Proof. exists nil; rewrite <- app_nil_end; auto. Qed.\n\n  Fact prefix_trans l1 l2 l3 : l1 <p l2 -> l2 <p l3 -> l1 <p l3.\n  Proof. intros (m1 & H1) (m2 & H2); subst; exists (m1++m2); solve list eq. Qed.\n\n  Section prefix_rect.\n\n    Variables (P : list X -> list X -> Type)\n              (HP0 : forall ll, P nil ll)\n              (HP1 : forall x l ll, l <p ll -> P l ll -> P (x::l) (x::ll)).\n              \n    Definition prefix_rect l ll : prefix l ll -> P l ll.\n    Proof using HP0 HP1.\n      revert l; induction ll as [ | x ll IHll ]; intros l H.\n      \n      replace l with (nil : list X).\n      apply HP0.\n      destruct H as (r & Hr).\n      destruct l; auto; discriminate.\n      \n      destruct l as [ | y l ].\n      apply HP0.\n      apply prefix_inv in H.\n      destruct H as (? & E); subst y.\n      apply HP1; [ | apply IHll ]; trivial.\n    Qed.\n   \n  End prefix_rect.\n\n  Fact prefix_app_inv l1 l2 r1 r2 : l1++l2 <p r1++r2 -> { l1 <p r1 } + { r1 <p l1 }.\n  Proof.\n    revert l2 r1 r2; induction l1 as [ | x l1 IH ].\n    left; apply in_prefix_0.\n    intros l2 [ | y r1 ] r2.\n    right; apply in_prefix_0.\n    simpl; intros H; apply prefix_inv in H.\n    destruct H as (E & H); subst y.\n    destruct IH with (1 := H); [ left | right ];\n      apply in_prefix_1; auto.\n  Qed. \n  \nEnd prefix.\n\nDefinition prefix_spec X (l ll : list X) : l <p ll -> { r | ll = l ++ r }.\nProof.\n  induction 1 as [ ll | x l ll _ (r & Hr) ] using prefix_rect.\n  exists ll; trivial.\n  exists r; simpl; f_equal; auto.\nQed.\n\nFact prefix_app_lft_inv X (l1 l2 m : list X) : l1++l2 <p m -> { m2 | m = l1++m2 /\\ l2 <p m2 }.\nProof.\n  intros H.\n  apply prefix_spec in H. \n  destruct H as (r & H).\n  exists (l2++r); simpl.\n  solve list eq in H; split; auto.\n  exists r; auto.\nQed.\n\nSection list_assoc.\n\n  Variables (X Y : Type) (eq_X_dec : eqdec X).\n\n  Fixpoint list_assoc x l : option Y :=\n    match l with \n      | nil  => None\n      | (y,a)::l => if eq_X_dec x y then Some a else list_assoc x l\n    end.\n\n  Fact list_assoc_eq x y l x' : x = x' -> list_assoc x' ((x,y)::l) = Some y.\n  Proof.    \n    intros []; simpl.\n    destruct (eq_X_dec x x) as [ | [] ]; auto.\n  Qed.\n\n  Fact list_assoc_neq x y l x' : x <> x' -> list_assoc x' ((x,y)::l) = list_assoc x' l.\n  Proof.    \n    intros H; simpl.\n    destruct (eq_X_dec x' x) as [ | ]; auto.\n    destruct H; auto.\n  Qed.\n\n  Fact list_assoc_In x l : \n    match list_assoc x l with \n      | None   => ~ In x (map fst l)\n      | Some y => In (x,y) l\n    end.\n  Proof.\n    induction l as  [ | (x',y) l IHl ]; simpl; auto.\n    destruct (eq_X_dec x x'); subst; auto.\n    destruct (list_assoc x l); auto.\n    intros [ ? | ]; subst; tauto.\n  Qed.\n\n  Fact In_list_assoc x l : In x (map fst l) -> { y | list_assoc x l = Some y /\\ In (x,y) l }.\n  Proof.\n    intros H.\n    generalize (list_assoc_In x l).\n    destruct (list_assoc x l) as [ y | ].\n    exists y; auto.\n    tauto.\n  Qed.\n  \n  Fact not_In_list_assoc x l : ~ In x (map fst l) -> list_assoc x l = None.\n  Proof.\n    intros H.\n    generalize (list_assoc_In x l).\n    destruct (list_assoc x l) as [ y | ]; auto.\n    intros H1; contradict H.\n    apply in_map_iff.\n    exists (x,y); simpl; auto.\n  Qed.\n\n  Fact list_assoc_app x ll mm : list_assoc x (ll++mm) \n                              = match list_assoc x ll with\n                                  | None   => list_assoc x mm\n                                  | Some y => Some y\n                                end.\n  Proof.\n    induction ll as [ | (x',?) ]; simpl; auto.\n    destruct (eq_X_dec x x'); auto.\n  Qed.\n\nEnd list_assoc.\n\nSection list_first_dec.\n\n  Variable (X : Type) (P : X -> Prop) (Pdec : forall x, { P x } + { ~ P x }).\n  \n  Theorem list_choose_dec ll : { l : _ & { x : _ & { r | ll = l++x::r /\\ P x /\\ forall y, In y l -> ~ P y } } }\n                             + { forall x, In x ll -> ~ P x }.\n  Proof using Pdec.\n    induction ll as [ | a ll IH ];\n      [ | destruct (Pdec a) as [ Ha | Ha ]; [ | destruct IH as [ (l & x & r & H1 & H2 & H3) | H ]] ].\n    * right; intros _ [].\n    * left; exists nil, a, ll; repeat split; auto.\n    * left; exists (a::l), x, r; repeat split; subst; auto. \n      intros ? [ | ]; subst; auto.\n    * right; intros ? [ | ]; subst; auto.\n  Qed.\n  \n  Theorem list_first_dec a ll : P a -> In a ll -> { l : _ & { x : _ & { r | ll = l++x::r /\\ P x /\\ forall y, In y l -> ~ P y } } }.\n  Proof using Pdec.\n    intros H1 H2.\n    destruct (list_choose_dec ll) as [ H | H ]; trivial.\n    destruct (H _ H2 H1).\n  Qed.\n  \nEnd list_first_dec.\n\nSection list_dec.\n\n  Variable (X : Type) (P Q : X -> Prop) (H : forall x, { P x } + { Q x }).\n  \n  Theorem list_dec l : { x | In x l /\\ P x } + { forall x, In x l -> Q x }.\n  Proof using H.\n    induction l as [ | x l IHl ].\n    + right; intros _ [].\n    + destruct (H x) as [ Hx | Hx ].\n      1: { left; exists x; simpl; auto. }\n      destruct IHl as [ (y & H1 & H2) | H1 ].\n      * left; exists y; split; auto; right; auto.\n      * right; intros ? [ -> | ? ]; auto.\n  Qed.\n\nEnd list_dec.\n\nSection map.\n\n  Variable (X Y : Type) (f : X -> Y).\n  \n  Fact map_cons_inv ll y m : map f ll = y::m -> { x : _ & { l | ll = x::l /\\ f x = y /\\ map f l = m } }.\n  Proof.\n    destruct ll as [ | x l ]; try discriminate; simpl.\n    intros H; inversion H; subst; exists x, l; auto.\n  Qed.\n\n  Fact map_app_inv ll m n : map f ll = m++n -> { l : _  & { r | ll = l++r /\\ m = map f l /\\ n = map f r } }.\n  Proof.\n    revert m n; induction ll as [ | x ll IH ]; intros m n H.\n    * destruct m; destruct n; try discriminate; exists nil, nil; auto.\n    * destruct m as [ | y m ]; simpl in H.\n      + exists nil, (x::ll); auto.\n      + inversion H; subst y.\n        destruct IH with (1 := H2) as (l & r & H3 & H4 & H5); subst.\n        exists (x::l), r; auto.\n  Qed.\n  \n  Fact map_middle_inv ll m y n : map f ll = m++y::n -> { l : _ & { x : _ & { r | ll = l++x::r /\\ map f l = m /\\ f x = y /\\ map f r = n } } }.\n  Proof.\n    intros H.\n    destruct map_app_inv with (1 := H) as (l & r & H1 & H2 & H3).\n    symmetry in H3.\n    destruct map_cons_inv with (1 := H3) as (x & r' & H4 & H5 & H6); subst.\n    exists l, x, r'; auto.\n  Qed.\n\n  Fact map_duplicate_inv ll l' y1 m' y2 r' :\n            map f ll = l'++y1::m'++y2::r'\n       -> { l : _ & \n          { x1 : _ &\n          { m : _ &\n          { x2 : _ &\n          { r | l' = map f l /\\ y1 = f x1 \n             /\\ m' = map f m /\\ y2 = f x2\n             /\\ r' = map f r /\\ ll = l++x1::m++x2::r } } } } }.\n  Proof.\n    intros H1.\n    apply map_middle_inv in H1.\n    destruct H1 as (l & x1 & k & H1 & H3 & H4 & H5).\n    apply map_middle_inv in H5.\n    destruct H5 as (m & x2 & r & -> & H6 & H7 & H8).\n    now exists l, x1, m, x2, r.\n  Qed.\n  \nEnd map.\n\nFact Forall2_mono X Y (R S : X -> Y -> Prop) :\n         (forall x y, R x y -> S x y) -> forall l m, Forall2 R l m -> Forall2 S l m.\nProof.\n  induction 2; constructor; auto.\nQed. \n\nFact Forall2_nil_inv_l X Y R m : @Forall2 X Y R nil m -> m = nil.\nProof.\n  inversion_clear 1; reflexivity.\nQed.\n\nFact Forall2_nil_inv_r X Y R m : @Forall2 X Y R m nil -> m = nil.\nProof.\n  inversion_clear 1; reflexivity.\nQed.\n\nFact Forall2_cons_inv X Y R x l y m : @Forall2 X Y R (x::l) (y::m) <-> R x y /\\ Forall2 R l m.\nProof.\n  split.\n  inversion_clear 1; auto.\n  intros []; constructor; auto.\nQed.\n\nFact Forall2_app_inv_l X Y R l1 l2 m : \n    @Forall2 X Y R (l1++l2) m -> { m1 : _ & { m2 | Forall2 R l1 m1 /\\ Forall2 R l2 m2 /\\ m = m1++m2 } }.\nProof.\n  revert l2 m;\n  induction l1 as [ | x l1 IH ]; simpl; intros l2 m H.\n  exists nil, m; repeat split; auto.\n  destruct m as [ | y m ].\n  apply Forall2_nil_inv_r in H; discriminate H.\n  apply Forall2_cons_inv in H; destruct H as [ H1 H2 ].\n  apply IH in H2.\n  destruct H2 as (m1 & m2 & H2 & H3 & H4); subst m.\n  exists (y::m1), m2; repeat split; auto.\nQed.\n\nFact Forall2_app_inv_r X Y R l m1 m2 : \n    @Forall2 X Y R l (m1++m2) -> { l1 : _ & { l2 | Forall2 R l1 m1 /\\ Forall2 R l2 m2 /\\ l = l1++l2 } }.\nProof.\n  revert m2 l;\n  induction m1 as [ | y m1 IH ]; simpl; intros m2 l H.\n  exists nil, l; repeat split; auto.\n  destruct l as [ | x l ].\n  apply Forall2_nil_inv_l in H; discriminate H.\n  apply Forall2_cons_inv in H; destruct H as [ H1 H2 ].\n  apply IH in H2.\n  destruct H2 as (l1 & l2 & H2 & H3 & H4); subst l.\n  exists (x::l1), l2; repeat split; auto.\nQed.\n\nFact Forall2_cons_inv_l X Y R a ll mm : \n      @Forall2 X Y R (a::ll) mm \n   -> { b : _ & { mm' | R a b /\\ mm = b::mm' /\\ Forall2 R ll mm' } }.\nProof.\n  intros H.\n  apply Forall2_app_inv_l with (l1 := a::nil) (l2 := ll) in H.\n  destruct H as (l & mm' & H1 & H2 & H3).\n  destruct l as [ | y l ].\n  exfalso; inversion H1.\n  apply Forall2_cons_inv in H1.\n  destruct H1 as [ H1 H4 ].\n  apply Forall2_nil_inv_l in H4; subst l.\n  exists y, mm'; auto.\nQed.\n\nFact Forall2_cons_inv_r X Y R b ll mm : \n      @Forall2 X Y R ll (b::mm) \n   -> { a : _ & { ll' | R a b /\\ ll = a::ll' /\\ Forall2 R ll' mm } }.\nProof.\n  intros H.\n  apply Forall2_app_inv_r with (m1 := b::nil) (m2 := mm) in H.\n  destruct H as (l & ll' & H1 & H2 & H3).\n  destruct l as [ | x l  ].\n  exfalso; inversion H1.\n  apply Forall2_cons_inv in H1.\n  destruct H1 as [ H1 H4 ].\n  apply Forall2_nil_inv_r in H4; subst l.\n  exists x, ll'; auto.\nQed.\n\nFact Forall2_map_left X Y Z (R : Y -> X -> Prop) (f : Z -> Y) ll mm : Forall2 R (map f ll) mm <-> Forall2 (fun x y => R (f x) y) ll mm.\nProof.\n  split.\n  revert mm.\n  induction ll; intros [ | y mm ] H; simpl in H; auto; try (inversion H; fail).\n  apply Forall2_cons_inv in H; constructor. \n  tauto.\n  apply IHll; tauto.\n  induction 1; constructor; auto.\nQed.\n\nFact Forall2_map_right X Y Z (R : Y -> X -> Prop) (f : Z -> X) mm ll : Forall2 R mm (map f ll) <-> Forall2 (fun y x => R y (f x)) mm ll.\nProof.\n  split.\n  revert mm.\n  induction ll; intros [ | y mm ] H; simpl in H; auto; try (inversion H; fail).\n  apply Forall2_cons_inv in H; constructor. \n  tauto.\n  apply IHll; tauto.\n  induction 1; constructor; auto.\nQed.\n\nFact Forall2_map_both X Y X' Y' (R : X -> Y -> Prop) (f : X' -> X) (g : Y' -> Y) ll mm : Forall2 R (map f ll) (map g mm) <-> Forall2 (fun x y => R (f x) (g y)) ll mm.\nProof.\n  rewrite Forall2_map_left, Forall2_map_right; split; auto.\nQed.\n\nFact Forall2_Forall X (R : X -> X -> Prop) ll : Forall2 R ll ll <-> Forall (fun x => R x x) ll.\nProof.\n  split.\n  induction ll as [ | x ll ]; inversion_clear 1; auto.\n  induction 1; auto.\nQed.\n\nFact Forall_app X (P : X -> Prop) ll mm : Forall P (ll++mm) <-> Forall P ll /\\ Forall P mm.\nProof.\n  repeat rewrite Forall_forall.\n  split.\n  firstorder.  \n  1,2: eapply H, in_app_iff; eauto.\n  intros (H1 & H2) x Hx.\n  apply in_app_or in Hx; firstorder.\nQed.\n\nFact Forall_cons_inv X (P : X -> Prop) x ll : Forall P (x::ll) <-> P x /\\ Forall P ll.\nProof.\n  split.\n  + inversion 1; auto.\n  + constructor; tauto.\nQed.\n\nFact Forall_rev X (P : X -> Prop) ll : Forall P ll -> Forall P (rev ll).\nProof.\n  induction 1 as [ | x ll Hll IH ].\n  constructor.\n  simpl.\n  apply Forall_app; split; auto.\nQed.\n\nFact Forall_map X Y (f : X -> Y) (P : Y -> Prop) ll : Forall P (map f ll) <-> Forall (fun x => P (f x)) ll.\nProof.\n  split.\n  + induction ll; simpl; try rewrite Forall_cons_inv; constructor; tauto.\n  + induction 1; simpl; constructor; auto.\nQed.\n\nFact Forall_forall_map X (f : nat -> X) n l (P : X -> Prop) :\n           l = map f (list_an 0 n) -> (forall i, i < n -> P (f i)) <-> Forall P l.\nProof.\n  intros Hl; rewrite Forall_forall.\n  split.\n  + intros H x; rewrite Hl, in_map_iff.\n    intros (y & ? & H1).\n    apply list_an_spec in H1; subst; apply H; lia.\n  + intros H x Hx; apply H; rewrite Hl, in_map_iff.\n    exists x; split; auto; apply list_an_spec; lia.\nQed.\n\nFact Forall_impl X (P Q : X -> Prop) ll : (forall x, In x ll -> P x -> Q x) -> Forall P ll -> Forall Q ll.\nProof.\n  intros H; induction 1 as [ | x ll Hx Hll IH ]; constructor.\n  + apply H; simpl; auto.\n  + apply IH; intros ? ?; apply H; simpl; auto.\nQed.\n\nFact Forall_filter X (P : X -> Prop) (f : X -> bool) ll : Forall P ll -> Forall P (filter f ll).\nProof. induction 1; simpl; auto; destruct (f x); auto. Qed.\n\nSection list_discrim.\n\n  Variable (X : Type) (P Q : X -> Prop) (PQdec : forall x, { P x } + { Q x}).\n\n  Definition list_discrim l : { lP : _ & { lQ | l ~p lP++lQ /\\ Forall P lP /\\ Forall Q lQ } }.\n  Proof using PQdec.\n    induction l as [ | x l (lP & lQ & H1 & H2 & H3) ].\n    + exists nil, nil; simpl; auto.\n    + destruct (PQdec x) as [ H | H ].\n      * exists (x::lP), lQ; repeat split; auto; constructor; auto.\n      * exists lP, (x::lQ); repeat split; auto.\n        apply Permutation_cons_app; auto.\n  Qed.\n\nEnd list_discrim.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/Shared/Libs/DLW/Utils/utils_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7469987375884756}}
{"text": "(* For the first part of this assignment, I'd like you to construct\n   proof terms manually, as we did at the beginning of class, instead\n   of using tactics.  \n\n   For each Definition provided, please replace the \".\" with\n   \":= <exp>.\" for some expression of the appropriate type.\n*)\n\nModule PSET1_EX1.\n\n  Definition X1 {A B C D:Prop} : \n    (B /\\ (B -> C /\\ D)) -> D :=\n      fun H1 => match H1 with\n        | conj H2 H3 => match (H3 H2) with\n          | conj H4 H5 => H5\n        end\n      end.\n\n  Definition X2 {A B C:Prop} : \n   ~(A \\/ B) -> B -> C :=\n    fun H1 H2 => match (H1 (or_intror H2)) with\n    end.\n\n  Definition X3 {A B C:Prop} : \n    A /\\ (B \\/ C) -> (A /\\ B) \\/ (A /\\ C) :=\n      fun H1 =>\n        match H1 with\n          | conj H2 H3 => match H3 with\n            | or_intror H4 => or_intror (conj H2 H4)\n            | or_introl H4 => or_introl (conj H2 H4)\n          end\n        end.\n\n  Locate \"_ <-> _\".\n\n  (* To solve the following, you'll need to figure out what\n     the definition of \"<->\" is and how to work with it... *)\n  Definition X4 {A:Prop} : \n    A <-> A :=\n      (conj (fun H1 => H1) (fun H1 => H1)).\n\n  Definition swap {A B:Prop} (H1: A <-> B) : (B <-> A) :=\n    match H1 with\n      | conj H2 H3 => conj H3 H2\n    end.\n\n  Definition X5 {A B:Prop} : \n    (A <-> B) <-> (B <-> A) :=\n      (conj swap swap).\n\n  Definition compose {A B C} (g : B -> C) (f : A -> B) :=\n  fun x : A => g (f x).\n\n  Definition X6 {A B C:Prop} : \n    (A <-> B) -> (B <-> C) -> (A <-> C) :=\n      fun (H1: A <-> B) (H2: B <-> C) =>\n        match H1, H2 with\n          | conj H3 H4, conj H5 H6 => (conj (compose H5 H3) (compose H4 H6))\n        end.\n\n\n\n  (* Thought exercise:  *)\n\n  (* This is not provable in Coq without adding an axiom, even\n     though in classical logic, we take this for granted:\n\n     P \\/ ~P\n\n     Try to prove it and see what goes wrong...  Interestingly,\n     this will almost never bite us.  \n  *)\nEnd PSET1_EX1.\n\n(* Now re-do these using only the following tactics:\n\n   intros, apply, destruct, unfold, split, contradiction, left, right\n\n   Hopefully I haven't left off any that you may need.  In general,\n   I don't want you using something such as firstorder or tauto\n   that trivially solves the goal.  I want you to perform the basic\n   steps.  \n*)\nModule PSET1_EX2.\n\n  Lemma X1 {A B C D:Prop} : \n    (B /\\ (B -> C /\\ D)) -> D.\n  Proof.\n    intros.\n    destruct H.\n    apply H0.\n    apply H.\n  Qed.\n\n  Lemma X2 {A B C:Prop} : \n    ~(A \\/ B) -> B -> C.\n  Proof.\n    intros.\n    destruct H.\n    right.\n    apply H0.\n  Qed.\n\n  Lemma X3 {A B C:Prop} : \n    A /\\ (B \\/ C) -> (A /\\ B) \\/ (A /\\ C).\n  Proof.\n    intros.\n    destruct H.\n    destruct H0.\n    left.\n    split.\n    apply H.\n    apply H0.\n    right.\n    split.\n    apply H.\n    apply H0.\n  Qed.\n\n  Lemma X4 {A:Prop} : \n    A <-> A. \n  Proof.\n    split.\n    intros.\n    apply H.\n    intros.\n    apply H.\n  Qed.\n\n  Lemma X5 {A B:Prop} : \n    (A <-> B) <-> (B <-> A).\n  Proof.\n    split.\n    intros.\n    split.\n    intros.\n    apply H.\n    apply H0.\n    apply H.\n    intros.\n    split.\n    apply H.\n    apply H.\n  Qed.\n\n  Lemma X6 {A B C:Prop} : \n    (A <-> B) -> (B <-> C) -> (A <-> C).\n  Proof.\n    intros.\n    split.\n    intros.\n    apply H0.\n    apply H.\n    apply H1.\n    intros.\n    apply H.\n    apply H0.\n    apply H1.\n  Qed.\n\nEnd PSET1_EX2.\n\n(* Here, we're going to exercise the [simpl], [induction] and [rewrite] tactics.\n   Replace the [Admitted.]'s with an appropriate proof.\n   Don't forget to write \"Qed.\" to terminate your proofs.  It goes\n   without saying that you shouldn't just prove these by using a\n   library lemma :-)  However, if you get stuck proving one of these, then\n   it is sometimes useful to look for one that does solve this, using\n   the top-level [SearchAbout] command, and then [Print] the corresponding\n   proof.\n*)\nModule PSET1_EX3.\n  Require Import List.\n  Require Import Arith.\n\n  Lemma zero_plus_x : forall n, 0 + n = n.\n  Proof.\n    simpl.\n    intros.\n    apply eq_refl.\n  Qed.\n\n  Lemma x_plus_zero : forall n, n + 0 = n.\n  Proof.\n    intros.\n    auto.\n  Qed.\n\n  Lemma map_map : forall {A B C:Type} (f:A->B) (g:B -> C) (xs:list A), \n    map g (map f xs) = map (fun x => g (f x)) xs.\n  Proof.\n    intros.\n    induction xs.\n    reflexivity.\n    simpl.\n    rewrite -> IHxs.\n    reflexivity.\n  Qed.\n\n  Lemma app_assoc : forall {A:Type} (xs ys zs:list A), \n    xs ++ (ys ++ zs) = (xs ++ ys) ++ zs.\n  Proof.\n    intros.\n    induction xs.\n    simpl.\n    reflexivity.\n    simpl.\n    rewrite <- IHxs.\n    reflexivity.\n  Qed.\n\n  Lemma map_is_fold : forall {A B} (f:A->B) (xs:list A),\n    map f xs = fold_right (fun x y => (f x)::y) nil xs.\n  Proof.\n    intros.\n    induction xs.\n    simpl.\n    reflexivity.\n    simpl.\n    rewrite <- IHxs.\n    reflexivity.\n  Qed.\n\n  Definition list_sum (xs:list nat) : nat := fold_right plus 0 xs.\n\n  Print plus.\n\n  Lemma my_plus_assoc : forall (a b c: nat), a + (b + c) = (a + b) + c.\n  Proof.\n    intros.\n    unfold plus.\n    induction a.\n    simpl.\n    reflexivity.\n    rewrite IHa.\n    reflexivity.\n  Qed.\n\n\n  Lemma list_sum_app : forall (t1 t2: list nat), \n     list_sum (t1 ++ t2) = list_sum t1 + list_sum t2.\n  Proof.\n    intros.\n    induction t1.\n    simpl.\n    reflexivity.\n    simpl.\n    rewrite IHt1.\n    rewrite my_plus_assoc.\n    reflexivity.\n  Qed.\n\n  Inductive tree(A:Type) : Type := \n    | Leaf : tree A\n    | Node : tree A -> A -> tree A -> tree A.\n  Implicit Arguments Leaf [A].\n  Implicit Arguments Node [A].\n\n  Fixpoint mirror{A:Type} (t:tree A) : tree A := \n    match t with\n      | Leaf => Leaf\n      | Node lft v rgt => Node (mirror rgt) v (mirror lft)\n    end.\n\n  Lemma mirror_mirror : forall A (t:tree A), mirror (mirror t) = t.\n  Proof.\n    intros.\n    induction t.\n    simpl.\n    reflexivity. \n    simpl.\n    rewrite -> IHt1.\n    rewrite -> IHt2.\n    reflexivity. \n  Qed.\n\n  Fixpoint flatten {A:Type} (t:tree A) : list A := \n    match t with \n      | Leaf => nil\n      | Node lft v rgt => (flatten lft) ++ v::(flatten rgt)\n    end.\n\n  Fixpoint tree_sum (t:tree nat) : nat := \n    match t with \n      | Leaf => 0\n      | Node lft v rgt => (tree_sum lft) + v + (tree_sum rgt)\n    end.\n\n  Lemma tree_flatten_sum : forall t, tree_sum t = list_sum (flatten t).\n  Proof.\n    intros.\n    induction t.\n    simpl.\n    reflexivity. \n    simpl.\n    rewrite list_sum_app.\n    rewrite <- IHt1.\n    simpl.\n    rewrite <- IHt2.\n    rewrite my_plus_assoc.\n    reflexivity.\n  Qed.\n\nEnd PSET1_EX3.\n", "meta": {"author": "Keno", "repo": "CS250", "sha": "5865c43b99d3acee956d610475445894851397f6", "save_path": "github-repos/coq/Keno-CS250", "path": "github-repos/coq/Keno-CS250/CS250-5865c43b99d3acee956d610475445894851397f6/pset1/pset1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.891811044719067, "lm_q1q2_score": 0.7469987309628545}}
{"text": "Set Implicit Arguments.\n\nFrom TLC Require Import LibLN.\n\nRequire Import DeclDef.\n\n\n(** Computing free term variables in a term *)\n\nFixpoint dfv_ee (e : dtrm) {struct e} : vars :=\n  match e with\n  | dtrm_bvar i       => \\{}\n  | dtrm_fvar x       => \\{x}\n  | dtrm_nat i        => \\{}\n  | dtrm_absann V e1  => (dfv_ee e1)\n  | dtrm_abs e1       => (dfv_ee e1)\n  | dtrm_app e1 e2    => (dfv_ee e1) \\u (dfv_ee e2)\n  | dtrm_let e1 e2    => (dfv_ee e1) \\u (dfv_ee e2)\n  end.\n\n(** Substitution for free term variables in terms. *)\n\nFixpoint dsubst_ee (z : var) (u : dtrm) (e : dtrm) {struct e} : dtrm :=\n  match e with\n  | dtrm_bvar i       => dtrm_bvar i\n  | dtrm_fvar x       => If x = z then u else (dtrm_fvar x)\n  | dtrm_nat i        => dtrm_nat i\n  | dtrm_absann V e1  => dtrm_absann V (dsubst_ee z u e1)\n  | dtrm_abs e1       => dtrm_abs (dsubst_ee z u e1)\n  | dtrm_app e1 e2    => dtrm_app (dsubst_ee z u e1) (dsubst_ee z u e2)\n  | dtrm_let e1 e2    => dtrm_let (dsubst_ee z u e1) (dsubst_ee z u e2)\n  end.\n\n(** Computing free type variables in a type *)\n\nFixpoint dfv_tt (T : dtyp) {struct T} : vars :=\n  match T with\n  | dtyp_nat         => \\{}\n  | dtyp_unknown     => \\{}\n  | dtyp_bvar J      => \\{}\n  | dtyp_fvar X      => \\{X}\n  | dtyp_arrow T1 T2 => (dfv_tt T1) \\u (dfv_tt T2)\n  | dtyp_all T1      => (dfv_tt T1)\n  end.\n\n(** Substitution for free type variables in types. *)\n\nFixpoint dsubst_tt (Z : var) (U : dtyp) (T : dtyp) {struct T} : dtyp :=\n  match T with\n  | dtyp_nat         => dtyp_nat\n  | dtyp_unknown     => dtyp_unknown\n  | dtyp_bvar J      => dtyp_bvar J\n  | dtyp_fvar X      => If X = Z then U else (dtyp_fvar X)\n  | dtyp_arrow T1 T2 => dtyp_arrow (dsubst_tt Z U T1) (dsubst_tt Z U T2)\n  | dtyp_all T1      => dtyp_all (dsubst_tt Z U T1)\n  end.\n\n(** Substitution for free type variables in environment. *)\n\nDefinition dsubst_tb (Z : var) (P : dtyp) (b : dbind) : dbind :=\n  match b with\n  | dbind_tvar => dbind_tvar\n  | dbind_typ T => dbind_typ (dsubst_tt Z P T)\n  end.\n\n(** Computing free type variables in a env *)\n\nFixpoint dfv_tt_env (E : denv) {struct E} : vars :=\n  match E with\n  | nil                      => \\{}\n  | cons (x, dbind_typ t) E' => dfv_tt t \\u dfv_tt_env E'\n  | cons (x, dbind_tvar) E'  => dfv_tt_env E'\n  end.\n\n(** * Tactics *)\n\n(** Constructors as hints. *)\n\nHint Constructors dtype dterm dokt dokt dtyp_mono.\n\nLtac gather_vars :=\n  let A := gather_vars_with (fun x : vars => x) in\n  let B := gather_vars_with (fun x : var => \\{x}) in\n  let C := gather_vars_with (fun x : dtrm => dfv_ee x) in\n  let D := gather_vars_with (fun x : dtyp => dfv_tt x) in\n  let E := gather_vars_with (fun x : denv => dom x) in\n  let F := gather_vars_with (fun x : denv => dfv_tt_env x) in\n  constr:(A \\u B \\u C \\u D \\u E \\u F).\n\n(** \"pick_fresh x\" tactic create a fresh variable with name x *)\n\nLtac pick_fresh X :=\n  let L := gather_vars in (pick_fresh_gen L X).\n\n(** \"apply_fresh T as x\" is used to apply inductive rule which\n   use an universal quantification over a cofinite set *)\n\nTactic Notation \"apply_fresh\" constr(T) \"as\" ident(x) :=\n  apply_fresh_base T gather_vars x.\n\nTactic Notation \"apply_fresh\" \"*\" constr(T) \"as\" ident(x) :=\n  apply_fresh T as x; autos*.\n\n(* ********************************************************************** *)\n(** ** Properties of type substitution in type *)\n\n(** Substitution on indices is identity on well-formed terms. *)\n\nLemma dopen_tt_rec_type_core : forall T j V U i, i <> j ->\n  (dopen_tt_rec j V T) = dopen_tt_rec i U (dopen_tt_rec j V T) ->\n  T = dopen_tt_rec i U T.\nProof.\n  induction T; introv Neq H; simpl in *; inversion H; f_equal*.\n  case_nat*. case_nat*.\nQed.\n\nLemma dopen_tt_rec_type : forall T U,\n  dtype T -> forall k, T = dopen_tt_rec k U T.\nProof.\n  induction 1; intros; simpl; f_equal*.\n  pick_fresh X. apply* (@dopen_tt_rec_type_core T2 0 (dtyp_fvar X)).\nQed.\n\n(** Substitution for a fresh name is identity. *)\n\nLemma dsubst_tt_fresh : forall Z U T,\n  Z \\notin dfv_tt T -> dsubst_tt Z U T = T.\nProof.\n  induction T; simpl; intros; f_equal*.\n  case_var*.\nQed.\n\n(** Substitution distributes on the open operation. *)\n\nLemma dsubst_tt_open_tt_rec : forall T1 T2 X P n, dtype P ->\n  dsubst_tt X P (dopen_tt_rec n T2 T1) =\n  dopen_tt_rec n (dsubst_tt X P T2) (dsubst_tt X P T1).\nProof.\n  introv WP. generalize n.\n  induction T1; intros k; simpls; f_equal*.\n  case_nat*.\n  case_var*. rewrite* <- dopen_tt_rec_type.\nQed.\n\nLemma dsubst_tt_open_tt : forall T1 T2 X P, dtype P ->\n  dsubst_tt X P (dopen_tt T1 T2) =\n  dopen_tt (dsubst_tt X P T1) (dsubst_tt X P T2).\nProof.\n  unfold dopen_tt. autos* dsubst_tt_open_tt_rec.\nQed.\n\n(** Substitution and open_var for distinct names commute. *)\n\nLemma dsubst_tt_open_tt_var : forall X Y U T, Y <> X -> dtype U ->\n  (dsubst_tt X U T) dopen_tt_var Y = dsubst_tt X U (T dopen_tt_var Y).\nProof.\n  introv Neq Wu. rewrite* dsubst_tt_open_tt.\n  simpl. case_var*.\nQed.\n\n(** Opening up a body t with a type u is the same as opening\n  up the abstraction with a fresh name x and then substituting u for x. *)\n\nLemma dsubst_tt_intro : forall X T2 U,\n  X \\notin dfv_tt T2 -> dtype U ->\n  dopen_tt T2 U = dsubst_tt X U (T2 dopen_tt_var X).\nProof.\n  introv Fr Wu. rewrite* dsubst_tt_open_tt.\n  rewrite* dsubst_tt_fresh. simpl. case_var*.\nQed.\n\nLemma dsubst_tt_rec_intro : forall X T2 U k,\n  X \\notin dfv_tt T2 -> dtype U ->\n  dopen_tt_rec k U T2 = dsubst_tt X U (dopen_tt_rec k (dtyp_fvar X) T2).\nProof.\n  introv Fr Wu. rewrite* dsubst_tt_open_tt_rec.\n  simpls. case_var~.\n  rewrite* dsubst_tt_fresh.\nQed.\n\nLemma dopen_tt_rec_type_commu : forall e j v u i, i <> j ->\n  dtype v -> dtype u ->\n  dopen_tt_rec j v (dopen_tt_rec i u e) = dopen_tt_rec i u (dopen_tt_rec j v e).\nProof.\n  induction e; introv Neq tv tu; simpl in *; auto.\n  f_equal*.\n  case_nat*. case_nat*. simpls. case_nat*.\n  symmetry. apply~ dopen_tt_rec_type.\n  case_nat*.\n  simpls. case_nat*.\n  apply~ dopen_tt_rec_type.\n  simpls. case_nat*. case_nat*.\n  f_equal*.\nQed.\n\n(** substitute a mono type with a mono type gives back mono type **)\n\nLemma dsubst_mono: forall U u z,\n    dtyp_mono U ->\n    dtyp_mono u ->\n    dtyp_mono (dsubst_tt z u U).\nProof.\n  introv mu me. inductions mu; simpls; auto.\n  case_var*.\nQed.\n\nLemma dtyp_mono_dtype: forall A,\n    dtyp_mono A ->\n    dtype A.\nProof.\n  introv mn. inductions mn; auto.\nQed.\n\n\n(** Substitutions preserve local closure. *)\n\nLemma dsubst_tt_type : forall T Z P,\n  dtype T -> dtype P -> dtype (dsubst_tt Z P T).\nProof.\n  induction 1; intros; simpl; auto.\n  case_var*.\n  apply_fresh* dtype_all as X. rewrite* dsubst_tt_open_tt_var.\nQed.\n\n(* ********************************************************************** *)\n(** ** Properties of term substitution in terms *)\n\nLemma dopen_ee_rec_term_core : forall e j v u i, i <> j ->\n  dopen_ee_rec j v e = dopen_ee_rec i u (dopen_ee_rec j v e) ->\n  e = dopen_ee_rec i u e.\nProof.\n  induction e; introv Neq H; simpl in *; inversion H; f_equal*.\n  case_nat*. case_nat*.\nQed.\n\nLemma dopen_ee_rec_term : forall u e,\n  dterm e -> forall k, e = dopen_ee_rec k u e.\nProof.\n  induction 1; intros; simpl; f_equal*.\n  unfolds dopen_ee. pick_fresh x.\n   apply* (@dopen_ee_rec_term_core e1 0 (dtrm_fvar x)).\n  unfolds dopen_ee. pick_fresh x.\n   apply* (@dopen_ee_rec_term_core e1 0 (dtrm_fvar x)).\n  unfolds dopen_ee. pick_fresh x.\n   apply* (@dopen_ee_rec_term_core e2 0 (dtrm_fvar x)).\nQed.\n\n(** Substitution for a fresh name is identity. *)\n\nLemma dsubst_ee_fresh : forall x u e,\n  x \\notin dfv_ee e -> dsubst_ee x u e = e.\nProof.\n  induction e; simpl; intros; f_equal*.\n  case_var*.\nQed.\n\n(** Substitution distributes on the open operation. *)\n\nLemma dsubst_ee_open_ee : forall t1 t2 u x, dterm u ->\n  dsubst_ee x u (dopen_ee t1 t2) =\n  dopen_ee (dsubst_ee x u t1) (dsubst_ee x u t2).\nProof.\n  intros. unfold dopen_ee. generalize 0.\n  induction t1; intros; simpls; f_equal*.\n  case_nat*.\n  case_var*. rewrite* <- dopen_ee_rec_term.\nQed.\n\n(** Substitution and open_var for distinct names commute. *)\n\nLemma dsubst_ee_open_ee_var : forall x y u e, y <> x -> dterm u ->\n  (dsubst_ee x u e) dopen_ee_var y = dsubst_ee x u (e dopen_ee_var y).\nProof.\n  introv Neq Wu. rewrite* dsubst_ee_open_ee.\n  simpl. case_var*.\nQed.\n\n(** Opening up a body t with a type u is the same as opening\n  up the abstraction with a fresh name x and then substituting u for x. *)\n\nLemma dsubst_ee_intro : forall x u e,\n  x \\notin dfv_ee e -> dterm u ->\n  dopen_ee e u = dsubst_ee x u (e dopen_ee_var x).\nProof.\n  introv Fr Wu. rewrite* dsubst_ee_open_ee.\n  rewrite* dsubst_ee_fresh. simpl. case_var*.\nQed.\n\n(** Substitutions preserve local closure. *)\n\nLemma dsubst_ee_term : forall e1 Z e2,\n  dterm e1 -> dterm e2 -> dterm (dsubst_ee Z e2 e1).\nProof.\n  induction 1; intros; simpl; auto.\n  case_var*.\n  apply_fresh* dterm_absann as y. rewrite* dsubst_ee_open_ee_var.\n  apply_fresh* dterm_abs as y. rewrite* dsubst_ee_open_ee_var.\n  apply_fresh* dterm_let as y. rewrite* dsubst_ee_open_ee_var.\nQed.\n\nLemma dterm_subst : forall t z u,\n    dterm t ->\n    dterm (dsubst_ee z (dtrm_fvar u) t)\n.\nProof.\n  introv typt.\n  apply* dsubst_ee_term.\nQed.\n\nLemma dterm_rename : forall x y S,\n  dterm (S dopen_ee_var x) ->\n  x \\notin dfv_ee S ->\n  y \\notin dfv_ee S ->\n  dterm (S dopen_ee_var y).\nProof.\n  introv Typx Frx Fry.\n  tests: (x = y). subst*.\n  rewrite~ (@dsubst_ee_intro x).\n  apply~ dterm_subst.\nQed.\n\nHint Resolve dsubst_tt_type dsubst_ee_term.\n\n(** Open_var with fresh names is an injective operation *)\n\nLemma dopen_ee_rec_inj : forall x t1 t2 k,\n  x \\notin (dfv_ee t1) -> x \\notin (dfv_ee t2) ->\n  (dopen_ee_rec k (dtrm_fvar x) t1 = dopen_ee_rec k (dtrm_fvar x) t2) -> (t1 = t2).\nProof.\n  intros x t1.\n  induction t1; intros t2 k; destruct t2; simpl; intros; inversion H1;\n  try solve [ f_equal*\n  | do 2 try case_nat; inversions* H1; try notin_false ].\nQed.\n\nLemma dopen_tt_rec_inj : forall x t1 t2 k,\n  x \\notin (dfv_tt t1) -> x \\notin (dfv_tt t2) ->\n  (dopen_tt_rec k (dtyp_fvar x) t1 = dopen_tt_rec k (dtyp_fvar x) t2) -> (t1 = t2).\nProof.\n  intros x t1.\n  induction t1; intros t2 k; destruct t2; simpl; intros; inversion H1;\n  try solve [ f_equal*\n  | do 2 try case_nat; inversions* H1; try notin_false ].\nQed.\n\nHint Resolve dopen_ee_rec_inj dopen_tt_rec_inj.\n\n(** More properties about free variables *)\n\nLemma notin_subst: forall x A B,\n    x \\notin dfv_tt A ->\n    x \\notin dfv_tt (dsubst_tt x A B).\nProof.\n  introv neq. inductions B; simpls~.\n  case_var~.\n  simpls~.\nQed.\n\nLemma dnotin_fv_tt_subst_inv: forall V z x U,\n    z \\notin dfv_tt U ->\n    z \\notin dfv_tt V ->\n    z <> x ->\n    z \\notin dfv_tt (dsubst_tt x U V).\nProof.\n  induction V; introv notinu notinv neq; simpls~.\n  case_var~.\nQed.\n\nHint Resolve dnotin_fv_tt_subst_inv.\n\n(* ********************************************************************** *)\n(** ** Free Variables *)\n\nLemma din_open_tt_rec: forall x T k U,\n    x \\in dfv_tt T ->\n    x \\in dfv_tt (dopen_tt_rec k U T).\nProof.\n  intros. gen x k U. induction T; simpls~; intros.\n  rewrite in_union in *.\n  destruct H.\n  left. apply* IHT1.\n  right. apply* IHT2.\n  case_nat~.\n  rewrite in_empty in H. false~.\nQed.\n\nLemma din_open_tt_var: forall x T y,\n    x \\in dfv_tt T ->\n    x \\in dfv_tt (T dopen_tt_var y).\nProof.\n  intros. unfolds dopen_tt. apply* din_open_tt_rec.\nQed.\n\nLemma dnotin_fv_tt_open : forall Y X T,\n  X \\notin dfv_tt (T dopen_tt_var Y) ->\n  X \\notin dfv_tt T.\nProof.\n introv. unfold dopen_tt. generalize 0.\n induction T; simpl; intros k Fr; auto.\n specializes IHT1 k. specializes IHT2 k. auto.\n specializes IHT (S k). auto.\nQed.\n\nLemma dnotin_fv_tt_dopen : forall Y X T,\n  X \\notin dfv_tt (dopen_tt T Y) ->\n  X \\notin dfv_tt T.\nProof.\n introv. unfold dopen_tt. generalize 0.\n induction T; simpl; intros k Fr; auto.\n specializes IHT1 k. specializes IHT2 k. auto.\n specializes IHT (S k). auto.\nQed.\n\nLemma dnotin_fv_tt_open_inv : forall X T U k,\n  X \\notin dfv_tt T ->\n  X \\notin dfv_tt U ->\n  X \\notin dfv_tt (dopen_tt_rec k U T).\nProof.\n  introv notint notinu. gen k.\n  inductions T; introv; simpls~.\n  case_nat*.\nQed.\n\nLemma  dfv_tt_env_push_typ_inv: forall G x v,\n  dfv_tt_env (G & x ~: v) = dfv_tt v \\u dfv_tt_env G.\nProof.\n  introv.\n  rewrite <- cons_to_push.\n  simpls~.\nQed.\n\nLemma  dfv_tt_env_push_tvar_inv: forall G x,\n  dfv_tt_env (G & x ~tvar) = dfv_tt_env G.\nProof.\n  introv.\n  rewrite <- cons_to_push.\n  simpls~.\nQed.\n\nLemma dnotin_fv_tt_env_bind_inv: forall E x T y,\n    binds y (dbind_typ T) E ->\n    x \\notin dfv_tt_env E ->\n    x \\notin dfv_tt T.\nProof.\n  induction E using env_ind; introv bd hy.\n  false* binds_empty_inv.\n  apply binds_push_inv in bd.\n  destruct bd as [[v1 v2]| [v3 v4]].\n  subst. rewrite dfv_tt_env_push_typ_inv in hy. autos*.\n  apply* IHE.\n  destruct v.\n  rewrite dfv_tt_env_push_tvar_inv in hy; auto.\n  rewrite dfv_tt_env_push_typ_inv in hy; auto.\nQed.\n\n\n(* ********************************************************************** *)\n(** * Relations between well-formed environment and types well-formed\n  in environments *)\n\nLemma dtype_open : forall U T2,\n  dtype (dtyp_all T2) ->\n  dtype U ->\n  dtype (dopen_tt T2 U).\nProof.\n  introv WA WU. inversions WA. pick_fresh X.\n  rewrite* (@dsubst_tt_intro X).\nQed.\n\n(** If an environment is well-formed, then it does not contain duplicated keys. *)\n\nLemma dok_from_okt : forall E,\n  dokt E -> ok E.\nProof.\n  induction 1; auto.\nQed.\n\nHint Extern 1 (ok _) => apply dok_from_okt.\n\nLemma dokt_push_inv : forall E x T,\n  dokt (E & x ~ T) -> dokt E /\\  x # E.\nProof.\n  introv O. inverts O.\n    false* empty_push_inv.\n    lets (?&M&?): (eq_push_inv H). subst. auto.\n    lets (?&M&?): (eq_push_inv H). subst. auto.\nQed.\n\nLemma dokt_push_typ_inv : forall E x T,\n  dokt (E & x ~ dbind_typ T) -> dwft E T.\nProof.\n  introv O. inverts O.\n    false* empty_push_inv.\n    lets (?&M&?): (eq_push_inv H). subst. false H.\n    lets (?&M&?): (eq_push_inv H). subst. inversions~ M.\nQed.\n\nLemma dwft_ok: forall E t,\n    dwft E t ->\n    ok E.\nProof.\n  introv wf. inductions wf; simpls~.\n  pick_fresh y.\n  forwards ~ : H0 y.\nQed.\n\nLemma dwft_dtype: forall E t,\n    dwft E t ->\n    dtype t.\nProof.\n  introv wf. inductions wf; simpls~.\n  apply_fresh dtype_all as x.\n  apply* H0.\nQed.\n\nHint Resolve dwft_ok dwft_dtype.\n\nHint Extern 1 (ok ?E) =>\n  match goal with\n  | H: dwft _ _ |- _ => apply (dwft_ok H)\n  end.\n\nHint Extern 1 (dtype ?E) =>\n  match goal with\n  | H: dwft _ _ |- _ => apply (dwft_dtype H)\n  end.\n\nHint Constructors dwft.\nLemma dwft_weakening : forall F x U E v,\n    dwft (E & F) U ->\n    ok (E & x ~ v & F) ->\n    dwft (E & x ~ v & F) U.\nProof.\n  introv wf okt. gen v.\n  inductions wf; introv okt; auto.\n  apply~ dwft_var.\n  apply~ binds_weaken.\n\n  apply_fresh dwft_all as x.\n  rewrite <- concat_assoc.\n  apply~ H0.\n  rewrite~ concat_assoc.\n  rewrite~ concat_assoc.\nQed.\n\nLemma dwft_push : forall x U E v,\n    dwft E U ->\n    ok (E & x ~ v) ->\n    dwft (E & x ~ v) U.\nProof.\n  intros.\n  apply_empty~ dwft_weakening.\nQed.\n\nLemma dwft_strengthen : forall F E x A v,\n    dwft (E & x ~ v & F) A ->\n    x \\notin dfv_tt A ->\n    dwft (E & F) A.\nProof.\n  introv wf1 notin.\n  inductions wf1; try(constructor~); simpls~.\n\n  apply binds_remove in H0; auto.\n  apply~ IHwf1_1.\n  apply~ IHwf1_2.\n\n  apply_fresh dwft_all as x.\n  rewrite <- concat_assoc.\n  apply~ H0.\n  rewrite~ concat_assoc.\n  apply~ dnotin_fv_tt_open_inv.\n  simpls~.\nQed.\n\nLemma dwft_weaken : forall G T E F,\n  dwft (E & G) T ->\n  ok (E & F & G) ->\n  dwft (E & F & G) T.\nProof.\n  intros. gen_eq K: (E & G). gen E F G.\n  induction H; intros; subst; eauto.\n  (* case: var *)\n  apply* dwft_var. apply* binds_weaken.\n  (* case: all *)\n  apply_fresh* dwft_all as Y. apply_ih_bind* H0.\nQed.\n\n\nLemma dwft_strengthen_push : forall E x A v,\n    dwft (E & x ~ v) A ->\n    x \\notin dfv_tt A ->\n    dwft (E) A.\nProof.\n  intros.\n  apply_empty* dwft_strengthen.\nQed.\n\nLemma dwft_strengthen_typ : forall F E x A v,\n    dwft (E & x ~: v & F) A ->\n    dwft (E & F) A.\nProof.\n  introv wf1.\n  inductions wf1; try(constructor~); simpls~.\n\n  tests : (x = x0).\n  apply binds_middle_eq_inv in H0; auto.\n  inversions H0.\n  apply binds_remove in H0; auto.\n  apply~ IHwf1_1.\n  apply~ IHwf1_2.\n\n  apply_fresh dwft_all as x.\n  rewrite <- concat_assoc.\n  apply~ H0.\n  rewrite~ concat_assoc.\nQed.\n\n\nLemma dwft_subst_tb : forall F E T P x,\n  dwft (E & x ~tvar & F) T ->\n  dwft E P ->\n  ok (E & map (dsubst_tb x P) F) ->\n  dwft (E & map (dsubst_tb x P) F) (dsubst_tt x P T).\nProof.\n  introv WT WP. gen_eq G: (E & x ~tvar & F). gen F.\n  induction WT; intros F EQ Ok; subst; simpl dsubst_tt; auto.\n  case_var*.\n    apply_empty* dwft_weaken.\n    destruct (binds_concat_inv H0) as [?|[? ?]].\n      apply* dwft_var.\n       apply~ binds_concat_right.\n       assert (dbind_tvar = dsubst_tb x P dbind_tvar).\n       reflexivity. rewrite H2.\n       apply~ binds_map.\n      destruct (binds_push_inv H2) as [[? ?]|[? ?]].\n        subst. false~.\n        apply* dwft_var.\n  apply_fresh* dwft_all as Y.\n   rewrite* dsubst_tt_open_tt_var.\n   assert (dbind_tvar = dsubst_tb x P dbind_tvar). reflexivity.\n   rewrite H1.\n   apply_ih_map_bind* H0.\nQed.\n\n\nLemma dokt_strengthen_typ : forall F E x v,\n    dokt (E & x ~: v & F) ->\n    dokt (E & F).\nProof.\n  induction F using env_ind; rew_env_concat; introv Ok.\n  rewrite concat_empty_r in *.\n  apply dokt_push_inv in Ok; destructs~ Ok.\n  rewrite concat_assoc in *.\n  destruct v.\n  constructor~.\n  forwards ~ [? ?] : dokt_push_inv Ok.\n  apply* IHF.\n  apply dok_from_okt in Ok.\n  forwards~ [? ?] : ok_push_inv Ok.\n  forwards ~ : dokt_push_typ_inv Ok.\n  forwards ~ [? ?] : dokt_push_inv Ok.\n  constructor~.\n  apply* IHF.\n  apply* dwft_strengthen_typ.\nQed.\n\nLemma dwft_rename : forall E F z u A,\n    dwft (E & z ~tvar & F) A ->\n    dokt (E & u ~tvar & F) ->\n    dwft (E & u ~tvar & F) (dsubst_tt z (dtyp_fvar u) A).\nProof.\n  introv wf okt.\n  inductions wf; simpls; auto.\n  case_var~.\n  apply~ dwft_var.\n  apply~ binds_middle_eq.\n  lets: dok_from_okt okt.\n  lets ~ : ok_middle_inv_r H1.\n\n  apply* dwft_var.\n  forwards ~ : binds_remove H0.\n  apply~ binds_weaken.\n\n  apply_fresh dwft_all as x.\n  forwards ~ : H0 x E (F & x ~tvar) z.\n  rewrite~ concat_assoc.\n  rewrite~ concat_assoc.\n  rewrite concat_assoc in H1; auto.\n  rewrite <- dsubst_tt_open_tt_var in H1; auto.\nQed.\n\n(** Extraction from a typing assumption in a well-formed environments *)\n\nLemma dwft_from_env_has_typ : forall x U E,\n  dokt E -> binds x (dbind_typ U) E -> dwft E U.\nProof.\n  induction E using env_ind; intros Ok B.\n  false* binds_empty_inv.\n  inversions Ok.\n    false (empty_push_inv H0).\n    destruct (eq_push_inv H) as [? [? ?]]. subst. clear H.\n    apply~ dwft_push.\n    apply* IHE.\n    destruct (binds_push_inv B) as [[? ?]|[? ?]]. false H2. auto.\n\n    destruct (eq_push_inv H) as [? [? ?]]. subst. clear H.\n     destruct (binds_push_inv B) as [[? ?]|[? ?]]. inversions H3.\n    apply~ dwft_push.\n    apply~ dwft_push.\nQed.\n\n(** Extraction from a well-formed environment *)\n\nLemma dwft_from_okt_typ : forall x T E,\n  dokt (E & x ~ dbind_typ T) -> dwft E T.\nProof.\n  intros. inversions* H.\n  false (empty_push_inv H1).\n  destruct (eq_push_inv H0) as [? [? ?]]. false~ H3.\n  destruct (eq_push_inv H0) as [? [? ?]].\n  inversion~ H4. subst~.\nQed.\n\n\nLemma dokt_subst_tb : forall F E x T,\n  dokt (E & x ~tvar & F) ->\n  dwft E T ->\n  dokt (E & map (dsubst_tb x T) F).\nProof.\n introv O W. induction F using env_ind.\n  rewrite map_empty. rewrite concat_empty_r in *.\n  lets*: (dokt_push_inv O).\n  rewrite map_push. rewrite concat_assoc in *.\n  lets (?&?): (dokt_push_inv O).\n  destruct v.\n  simpls*.\n  applys~ dokt_typ. applys* dwft_subst_tb.\n  apply* dwft_from_okt_typ.\nQed.\n\n\nLemma dwft_open_inv: forall E k T U P,\n    dwft E U ->\n    dwft E P ->\n    dwft E (dopen_tt_rec k U T) ->\n    dwft E (dopen_tt_rec k P T).\nProof.\n  introv wf1 wf2 wfh.\n  inductions wfh.\n\n  destruct T;  simpls~; try(solve[inversion x]).\n  case_nat* .\n\n  destruct T;  simpls~; try(solve[inversion x]).\n  case_nat* .\n\n  destruct T;  simpls~; try(solve[inversion x]).\n  case_nat* .\n  inversions x.\n  apply~ dwft_var.\n\n  destruct T;  simpls~; try(solve[inversion x]).\n  inversions x.\n  apply~ dwft_arrow. apply IHwfh1 with U; auto.\n  apply IHwfh2 with U; auto.\n  case_nat*.\n\n  destruct T;  simpls~; try(solve[inversion x]).\n  case_nat* .\n  inversions x.\n  apply_fresh dwft_all as x.\n  unfold dopen_tt.\n  rewrite~ dopen_tt_rec_type_commu.\n  apply H0 with U; auto.\n  apply~ dwft_push.\n  apply~ dwft_push.\n  unfold dopen_tt.\n  rewrite~ dopen_tt_rec_type_commu.\nQed.\n\nLemma dwft_open_inv_all: forall E T U,\n    dwft E U ->\n    dwft E (dopen_tt T U) ->\n    dwft E (dtyp_all T).\nProof.\n  introv wf1 wf2. unfolds dopen_tt.\n  apply_fresh dwft_all as x.\n  apply dwft_open_inv with U; auto.\n  apply~ dwft_push.\n  apply~ dwft_push.\nQed.\n\nLemma dwft_open: forall E T U,\n    dwft E U ->\n    dwft E (dtyp_all T) ->\n    dwft E (dopen_tt T U).\nProof.\n  introv wf1 wf2.\n  inversions wf2.\n  pick_fresh x.\n  forwards ~ : H1 x.\n  apply dwft_strengthen_push with x dbind_tvar; auto.\n  unfolds dopen_tt.\n  apply dwft_open_inv with (dtyp_fvar x); auto.\n  apply~ dwft_push.\n  apply~ dnotin_fv_tt_open_inv.\nQed.\n\nLemma dwft_notin_env: forall E A y,\n    dwft E A ->\n    y \\notin dom E ->\n    y \\notin dfv_tt A.\nProof.\n  introv wf notin. inductions wf; simpls~.\n  apply~ notin_singleton. introv veq. subst~.\n  false binds_fresh_inv H0 notin0.\n  pick_fresh x.\n  forwards~ : H0 x.\n  apply* dnotin_fv_tt_dopen.\nQed.\n\n(** Automation *)\n\nHint Resolve dwft_from_okt_typ.\nHint Immediate dwft_from_env_has_typ.\nHint Resolve dokt_subst_tb dwft_weaken.\nHint Immediate dokt_strengthen_typ.\nHint Resolve dwft_subst_tb.\n\n\n(** If an environment is well-formed, then its left part is also well-formed. *)\n\nLemma dokt_concat_left_inv: forall E F,\n    dokt (E & F) -> dokt E.\nProof.\n  induction F using env_ind; introv okt; auto.\n  clean_empty okt; auto.\n  rewrite concat_assoc in okt.\n  lets [? ?]: dokt_push_inv okt. apply* IHF.\nQed.\n\n(* ********************************************************************** *)\n(** * Properties of Closeness *)\n\n(** Abstracting a term name out of a term *)\n\nFixpoint dclose_ee_rec (k : nat) (z : var) (t : dtrm) {struct t} : dtrm :=\n  match t with\n  | dtrm_bvar i        => dtrm_bvar i\n  | dtrm_fvar x        => If x = z then (dtrm_bvar k) else (dtrm_fvar x)\n  | dtrm_nat  i        => dtrm_nat i\n  | dtrm_absann t1 t2  => dtrm_absann t1 (dclose_ee_rec (S k) z t2)\n  | dtrm_abs t         => dtrm_abs (dclose_ee_rec (S k) z t)\n  | dtrm_app t1 t2     => dtrm_app (dclose_ee_rec k z t1) (dclose_ee_rec k z t2)\n  | dtrm_let t1 t2     => dtrm_let (dclose_ee_rec k z t1) (dclose_ee_rec (S k) z t2)\n  end.\n\nDefinition dclose_ee z t := dclose_ee_rec 0 z t.\n\n(** Close var commutes with open with some freshness conditions,\n  this is used in the proofs of [close_ee_open] *)\n\nLemma dclose_ee_rec_open : forall x y z t1 i j,\n  i <> j -> y <> x -> y \\notin (dfv_ee t1) ->\n    (dopen_ee_rec i (dtrm_fvar y) (dopen_ee_rec j (dtrm_fvar z) (dclose_ee_rec j x t1)))\n  = (dopen_ee_rec j (dtrm_fvar z) (dclose_ee_rec j x (dopen_ee_rec i  (dtrm_fvar y) t1) )).\nProof.\n  induction t1; simpl; intros; try solve [ f_equal* ].\n  do 2 (case_nat; simpl); try solve [ case_var* | case_nat* ].\n  case_var*. simpl. case_nat*.\nQed.\n\n(** Close var removes fresh var *)\n\nLemma dclose_ee_fresh : forall x t,\n  x \\notin dfv_ee (dclose_ee x t).\nProof.\n  introv. unfold dclose_ee. generalize 0.\n  induction t; intros k; simpls; notin_simpl; auto.\n  case_var; simple*.\nQed.\n\n(** Close var is the right inverse of open_var *)\n\nLemma dclose_ee_open : forall x t,\n  dterm t -> t = (dclose_ee x t) dopen_ee_var x.\nProof.\n  introv W. unfold dclose_ee, dopen_ee. generalize 0.\n  induction W; intros k; simpls; f_equal*.\n  case_var*. simpl. case_nat*.\n  let L := gather_vars in match goal with |- _ = ?t =>\n    destruct (var_fresh (L \\u dfv_ee t)) as [y Fr] end.\n  apply* (@dopen_ee_rec_inj y).\n  unfolds dopen_ee. rewrite* dclose_ee_rec_open.\n  let L := gather_vars in match goal with |- _ = ?t =>\n    destruct (var_fresh (L \\u dfv_ee t)) as [y Fr] end.\n  apply* (@dopen_ee_rec_inj y).\n  unfolds dopen_ee. rewrite* dclose_ee_rec_open.\n  let L := gather_vars in match goal with |- _ = ?t =>\n    destruct (var_fresh (L \\u dfv_ee t)) as [y Fr] end.\n  apply* (@dopen_ee_rec_inj y).\n  unfolds dopen_ee. rewrite* dclose_ee_rec_open.\nQed.\n\n(** Abstracting a type name out of a type *)\n\nFixpoint dclose_tt_rec (k : nat) (z : var) (t : dtyp) {struct t} : dtyp :=\n  match t with\n  | dtyp_bvar i        => dtyp_bvar i\n  | dtyp_unknown       => dtyp_unknown\n  | dtyp_fvar x        => If x = z then (dtyp_bvar k) else (dtyp_fvar x)\n  | dtyp_nat           => dtyp_nat\n  | dtyp_arrow t1 t2   => dtyp_arrow (dclose_tt_rec k z t1) (dclose_tt_rec k z t2)\n  | dtyp_all t1        => dtyp_all (dclose_tt_rec (S k) z t1)\n  end.\n\nDefinition dclose_tt z t := dclose_tt_rec 0 z t.\n\n(** Close var commutes with open with some freshness conditions *)\n\nLemma dclose_tt_rec_open : forall x y z t1 i j,\n  i <> j -> y <> x -> y \\notin (dfv_tt t1) ->\n    (dopen_tt_rec i (dtyp_fvar y) (dopen_tt_rec j (dtyp_fvar z) (dclose_tt_rec j x t1)))\n  = (dopen_tt_rec j (dtyp_fvar z) (dclose_tt_rec j x (dopen_tt_rec i  (dtyp_fvar y) t1) )).\nProof.\n  induction t1; simpl; intros; try solve [ f_equal* ].\n  do 2 (case_nat; simpl); try solve [ case_var* | case_nat* ].\n  case_var*. simpl. case_nat*.\nQed.\n\n(** Close var removes fresh var *)\n\nLemma dclose_tt_fresh_rec : forall x t k,\n  x \\notin dfv_tt (dclose_tt_rec k x t).\nProof.\n  introv. unfold dclose_tt. gen k.\n  induction t; intros k; simpls; notin_simpl; auto.\n  case_var; simple*.\nQed.\n\nLemma dclose_tt_fresh : forall x t,\n  x \\notin dfv_tt (dclose_tt x t).\nProof.\n  unfold dclose_tt.  introv.\n  apply dclose_tt_fresh_rec.\nQed.\n\nHint Resolve dclose_tt_fresh_rec dclose_tt_fresh.\n\n(** Close var is the right inverse of open_var *)\n\nLemma dclose_tt_open : forall x t k,\n  dtype t -> t = dopen_tt_rec k (dtyp_fvar x) (dclose_tt_rec k x t).\nProof.\n  introv W. unfold dclose_tt, dopen_tt. gen k.\n  induction W; intros k; simpls; f_equal*.\n  case_var*. simpl. case_nat*.\n  let L := gather_vars in match goal with |- _ = ?t =>\n    destruct (var_fresh (L \\u dfv_tt t)) as [y Fr] end.\n  apply* (@dopen_tt_rec_inj y).\n  unfolds dopen_tt. rewrite* dclose_tt_rec_open.\nQed.\n\nLemma dclose_tt_open_var : forall x t,\n  dtype t -> t = dopen_tt (dclose_tt x t) (dtyp_fvar x).\nProof.\n  intros. unfolds dopen_tt.\n  apply* dclose_tt_open.\nQed.\n\nLemma dopen_tt_close_fresh : forall y A,\n    y \\notin dfv_tt A ->\n    dclose_tt y (A dopen_tt_var y) = A.\nProof.\n  unfolds dopen_tt. unfolds dclose_tt.\n  generalize 0. introv. gen n.\n  inductions A; introv neq; simpls~;f_equal~.\n  case_nat~. simpls~. case_var~.\n  case_var~.\nQed.\n\nHint Resolve dclose_tt_rec_open.\nHint Resolve dclose_tt_open.\n\n(* close does not introduce new free vairables *)\n\nLemma dnotin_fv_tt_close_inv: forall S x y k,\n    x \\notin dfv_tt S ->\n    x \\notin dfv_tt (dclose_tt_rec k y S).\nProof.\n  induction S; introv notin; simpls~.\n  case_var~. simpls~.\nQed.\n\nLemma dclose_tt_in_inv : forall x t k y,\n        x <> y ->\n        x \\in dfv_tt (dclose_tt_rec k y t) ->\n        x \\in dfv_tt t.\nProof.\n  introv. unfold dclose_tt. gen k.\n  induction t; intros; simpls; notin_simpl; auto.\n  rewrite in_union in *. destruct H0. left. apply* IHt1. right. apply* IHt2.\n  case_var; simple*.\n  simpls. rewrite in_empty in H0. false~.\n  apply* IHt.\nQed.\n\nHint Resolve dnotin_fv_tt_close_inv\n.\n\n(** open a closed one is substitution *)\n\nLemma dclose_tt_open_subst: forall S k x y,\n    dtype S ->\n    dopen_tt_rec k (dtyp_fvar y) (dclose_tt_rec k x S) = dsubst_tt x (dtyp_fvar y) S.\nProof.\n  introv ty. gen k. induction ty; introv; simpls; auto.\n  case_var~. simpls. case_nat~.\n  rewrite* IHty1. rewrite* IHty2.\n\n  pick_fresh z.\n  specializes H0 z (S k).\n\n  rewrite dsubst_tt_open_tt in H0; auto.\n  simpls. case_var.\n\n  unfolds dopen_tt.\n  unfolds dopen_tt.\n  rewrite <- dclose_tt_rec_open in H0; auto.\n  apply dopen_tt_rec_inj in H0; auto.\n  rewrite~ H0.\n  apply dnotin_fv_tt_open_inv; simpls~.\n  apply dnotin_fv_tt_subst_inv; simpls~.\nQed.\n\nHint Resolve dclose_tt_open_subst.\n\n(* ********************************************************************** *)\n(** ** Number of All *)\n\nFixpoint num_of_all (t: dtyp) : nat :=\n  match t with\n      | dtyp_nat => 0\n      | dtyp_unknown => 0\n      | dtyp_fvar x => 0\n      | dtyp_bvar x => 0\n      | dtyp_arrow n1 n2 => (num_of_all n1) + (num_of_all n2)\n      | dtyp_all n => 1 + (num_of_all n)\n  end.\n\nLemma num_of_all_mono: forall U,\n    dtyp_mono U ->\n    num_of_all U = 0.\nProof.\n  induction U; introv mn; simpls~.\n  inversion~ mn; subst~. rewrite~ IHU1.\n  inversion mn.\nQed.\n\nLemma num_of_all_open_rec_mono: forall S U k,\n    dtyp_mono U ->\n    num_of_all (dopen_tt_rec k U S) = num_of_all S.\nProof.\n  induction S; introv mn; simpls~.\n  case_nat~. apply~ num_of_all_mono.\nQed.\n\nLemma num_of_all_open_mono: forall S U,\n    dtyp_mono U ->\n    num_of_all (dopen_tt S U) = num_of_all S.\nProof.\n  intros. apply* num_of_all_open_rec_mono.\nQed.\n\nLemma num_of_all_open_rec_unknown: forall S k,\n    num_of_all (dopen_tt_rec k dtyp_unknown S) = num_of_all S.\nProof.\n  induction S; introv; simpls~.\n  case_nat~.\nQed.\n\nLemma num_of_all_open_unknown: forall S,\n    num_of_all (dopen_tt S dtyp_unknown) = num_of_all S.\nProof.\n  intros. apply* num_of_all_open_rec_unknown.\nQed.\n\n(* ********************************************************************** *)\n(** ** Dtyp Len *)\n\nFixpoint dtyp_len (t: dtyp) : nat :=\n  match t with\n  | dtyp_nat => 1\n  | dtyp_unknown => 1\n  | dtyp_fvar _ => 1\n  | dtyp_bvar _ => 1\n  | dtyp_arrow t1 t2 =>\n      1 + dtyp_len t1 + dtyp_len t2\n  | dtyp_all t1 =>\n    1 + dtyp_len t1\n  end.\n\nLemma dtyp_len_open_tt_fvar: forall S U k,\n    dtyp_len (dopen_tt_rec k (dtyp_fvar U) S) = dtyp_len S.\nProof.\n  induction S; introv; simpls~.\n  case_nat~.\nQed.\n\nLemma dtyp_len_open_tt_unknown: forall S k,\n    dtyp_len (dopen_tt_rec k dtyp_unknown S) = dtyp_len S.\nProof.\n  induction S; introv; simpls~.\n  case_nat~.\nQed.\n\n(* ********************************************************************** *)\n(** ** Regularity of relations *)\n\nLemma dsub_regular : forall E A B,\n  dsub E A B -> dokt E /\\ dwft E A /\\ dwft E B.\nProof.\n  introv sub.\n  inductions sub; try(solve[splits~]).\n  destructs~ IHsub1.\n  destructs~ IHsub2.\n\n  destructs~ IHsub.\n  splits~.\n  apply dwft_open_inv_all with tau; auto.\n\n  splits~.\n  pick_fresh y. forwards ~ : H0 y.\n  destructs H1.\n  apply* dokt_concat_left_inv.\n  pick_fresh y. forwards ~ : H0 y.\n  destructs H1.\n  apply* dwft_strengthen_push.\n\n  apply_fresh dwft_all as x.\n  forwards ~ : H0 x.\n  destructs~ H1.\nQed.\n\nLemma dconsub_regular : forall E A B,\n  dconsub E A B -> dokt E /\\ dwft E A /\\ dwft E B.\nProof.\n  introv sub. inductions sub; auto.\n  destructs IHsub1. destructs IHsub2.\n  splits~.\n\n  destructs IHsub.\n  splits~.\n  apply dwft_open_inv_all with tau; auto.\n\n  splits~.\n  pick_fresh y. forwards ~ [? [? ?]]: H0 y.\n    apply* dokt_concat_left_inv.\n  pick_fresh y. forwards ~ [? [? ?]]: H0 y.\n    apply* dwft_strengthen_push.\n  apply_fresh dwft_all as x.\n    forwards ~ [? [? ?]] : H0 x.\nQed.\n\nLemma dmatch_regular : forall A A1 A2 E,\n    dwft E A ->\n    dmatch E A A1 A2 ->\n    dwft E A1 /\\ dwft E A2.\nProof.\n  introv wf mat. inductions mat.\n  apply~ IHmat.\n  inversions wf.\n  pick_fresh y.\n  apply dwft_strengthen_push with y (dbind_tvar); auto.\n  apply dwft_open_inv with (dtyp_fvar y); auto.\n  apply~ dwft_push.\n  apply~ H3.\n  apply~ dnotin_fv_tt_open_inv.\n\n  inversions wf. splits~.\n  splits~.\nQed.\n\nLemma dmatch_regular_inv : forall A A1 A2 E,\n    dmatch E A A1 A2 ->\n    dwft E A1 -> dwft E A2 ->\n    dwft E A.\nProof.\n  introv mat wfa1 wfa2. inductions mat; auto.\n  apply_fresh dwft_all as x.\n  apply dwft_open_inv with tau; auto.\n  apply~ dwft_push.\n  apply~ dwft_push.\nQed.\n\nLemma dmatch_regular_dtype : forall A A1 A2 E,\n    dmatch E A A1 A2 ->\n    dtype A ->\n    dtype A1 /\\ dtype A2.\nProof.\n  introv mat wf. inductions mat.\n  apply~ IHmat.\n  apply* dtype_open.\n  inversions~ wf.\n  splits~.\nQed.\n\nLemma dtyping_regular : forall E e T,\n  dtyping E e T -> dokt E /\\ dterm e /\\ dwft E T.\nProof.\n  induction 1; try(solve[auto;splits~]).\n  splits~. apply* dwft_from_env_has_typ.\n  splits~.\n    pick_fresh y. specializes H1 y. destructs~ H1.\n      forwards*: dokt_push_inv.\n    apply_fresh dterm_absann as y.\n      pick_fresh y. specializes H1 y. destructs~ H1.\n        specializes H1 y. destructs~ H1.\n    apply~ dwft_arrow.\n      pick_fresh y. specializes H1 y. destructs~ H1.\n      apply* dokt_push_typ_inv.\n      pick_fresh y. specializes H1 y. destructs~ H1.\n      apply* dwft_strengthen_push.\n\n  destructs IHdtyping1.\n  destructs IHdtyping2.\n  forwards ~ [? ?] : dmatch_regular H0.\n\n  splits~.\n    pick_fresh y. specializes H1 y. destructs~ H1.\n      forwards*: dokt_push_inv.\n    apply_fresh dterm_abs as y.\n      specializes H1 y. destructs~ H1.\n    apply~ dwft_arrow.\n      pick_fresh y. specializes H1 y. destructs~ H1.\n      apply* dokt_push_typ_inv.\n      pick_fresh y. specializes H1 y. destructs~ H1.\n      apply* dwft_strengthen_push.\n\n  splits~.\n    pick_fresh y. specializes H0 y. destructs~ H0.\n      forwards*: dokt_push_inv.\n    pick_fresh y. specializes H0 y. destructs~ H0.\n    apply_fresh dwft_all as y.\n      specializes H0 y. destructs~ H0.\n\n  destructs IHdtyping.\n  splits~.\n    apply_fresh dterm_let as y.\n    pick_fresh y. specializes H1 y. destructs~ H1.\n    specializes H1 y. destructs~ H1.\n    pick_fresh y. specializes H1 y. destructs~ H1.\n      apply* dwft_strengthen_push.\nQed.\n\n(** Automation *)\n\nHint Extern 1 (dokt ?E) =>\n  match goal with\n  | H: dsub _ _ _ |- _ => apply (proj31 (dsub_regular H))\n  | H: dconsub _ _ _ |- _ => apply (proj31 (dconsub_regular H))\n  | H: dtyping _ _ _ |- _ => apply (proj31 (dtyping_regular H))\n  end.\n\nHint Extern 1 (dterm ?E) =>\n  match goal with\n  | H: dtyping _ _ _ |- _ => apply (proj32 (dtyping_regular H))\n  end.\n\nHint Extern 1 (dwft ?E ?t) =>\n  match goal with\n  | H: dsub _ _ _ |- _ => apply (proj32 (dsub_regular H))\n  | H: dsub _ _ _ |- _ => apply (proj33 (dsub_regular H))\n  | H: dconsub _ _ _ |- _ => apply (proj32 (dconsub_regular H))\n  | H: dconsub _ _ _ |- _ => apply (proj33 (dconsub_regular H))\n  | H: dmatch _ _ _ _ |- _ => apply (proj21 (dmatch_regular H))\n  | H: dmatch _ _ _ _ |- _ => apply (proj22 (dmatch_regular H))\n  | H: dtyping _ _ _ |- _ => apply (proj33 (dtyping_regular H))\n  end.\n", "meta": {"author": "xnning", "repo": "Consistent-Subtyping-for-All", "sha": "1bf23ed3906f2e244d081c75be90f3a54899e375", "save_path": "github-repos/coq/xnning-Consistent-Subtyping-for-All", "path": "github-repos/coq/xnning-Consistent-Subtyping-for-All/Consistent-Subtyping-for-All-1bf23ed3906f2e244d081c75be90f3a54899e375/coq/decl-higher-rank/DeclInfra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.746998724339384}}
{"text": "Require Import Braun.common.util Braun.common.le_util Braun.common.same_structure.\nRequire Import Braun.common.log Braun.common.big_oh Braun.common.pow.\nRequire Import Braun.monad.monad Braun.arith.plus.\nRequire Import Program Div2 Omega Even.\n\nInductive Fib : nat -> nat -> Prop :=\n| F_0 :\n  Fib 0 0\n| F_1 :\n  Fib 1 1\n| F_n :\n  forall n a b,\n    Fib n a ->\n    Fib (S n) b  ->\n    Fib (S (S n)) (a + b).\nHint Constructors Fib.\n\nFixpoint fib n :=\n  match n with \n    | 0 => 0\n    | S n' => \n      match n' with\n        | 0 => 1\n        | S n'' => fib n''  + fib n'\n      end\n  end.\n\nLemma Fib_fib:\n  forall n, Fib n (fib n).\nProof.\n  apply (well_founded_induction lt_wf).\n  intros n IH.\n  destruct n as [|n].\n  eauto.\n  destruct n as [|n].\n  eauto.\n  replace (fib (S (S n))) with (fib n + fib (S n));auto.\nDefined.\n\nLemma fib_SS : forall n, fib (S (S n)) = fib (S n) + fib n.\nProof.\n  intros; unfold fib; rewrite plus_comm; auto.\nQed.\n\nLemma fib_monotone : forall (n : nat) (m : nat), m <= n -> fib m <= fib n.\nProof.\n  intros n m LE.\n  destruct LE.\n  auto.\n  remember (S m0) as n.\n  assert (m < n) as LT; [omega|].\n  clear LE Heqn.\n  apply (well_founded_induction lt_wf\n                                (fun (n : nat) =>\n                                   forall (m : nat), m < n -> fib m <= fib n)); auto.\n  clear m m0 n LT.\n  intros x0 H m H0.\n  destruct x0 as [|n'].\n  inversion H0.\n  destruct n' as [|n''].\n  inversion H0; [compute; omega|inversion H2].\n  rewrite fib_SS.\n  destruct m as [|m'].\n  replace (fib 0) with 0; [|compute;auto].\n  apply le_0_n.\n  destruct m' as [|m''].\n  apply le_plus_trans.\n  destruct n'' as [|n''']; [|apply H]; try omega.\n  destruct n'' as [|n''']; [intuition|]. \n  apply le_plus_trans.\n  inversion H0; auto.\nQed.\n\nLemma fib_nonneg : forall n, 0 < fib (S n).\nProof.\n  induction n;[simpl|rewrite fib_SS]; omega.\nQed.  \n\nLemma fib_lower_bound : \n  forall n,\n    pow 2 (div2 (S n)) <= 2 * fib (S n).\nProof.\n  apply (well_founded_ind\n           lt_wf\n           (fun n => pow 2 (div2 (S n)) <= 2 * fib (S n))).\n  intros n IND.\n  destruct n;[simpl;auto|].\n  destruct n;[simpl;auto|].\n  replace (div2 (S (S (S n)))) with (S (div2 (S n)));[|unfold div2;auto].\n  unfold pow; fold pow.\n  apply (le_trans (2 * pow 2 (div2 (S n)))\n                  (2 * (2 * fib (S n)))).\n  apply mult_le_compat; auto.\n\n  clear IND.\n  apply mult_le_compat; auto.\n  replace (fib (S (S (S n)))) with (fib (S (S n)) + fib (S n));[|simpl fib;omega].\n  unfold mult.\n  rewrite plus_0_r.\n  apply plus_le_compat;auto.\n  apply fib_monotone; auto.\nQed.\n\nLemma fib_lower_bound2 :\n  forall n, 6 <= n ->\n            pow 2 (div2 n) <= fib n.\nProof.\n  apply (well_founded_ind\n           lt_wf\n           (fun n => 6 <= n -> pow 2 (div2 n) <= fib n)).\n  intros.\n  destruct x; inversion H0;[compute;auto|].\n  clear H0 H1 m.\n  destruct x; inversion H2;[compute;omega|].\n  clear m H2 H0.\n  replace (div2 (S (S x))) with (S (div2 x));[|unfold div2; auto].\n  unfold pow; fold pow.\n  apply (le_trans (2 * pow 2 (div2 x))\n                  (2 * fib x)).\n  apply mult_le_compat; auto.\n  replace (fib (S (S x))) with (fib (S x) + fib x);[|simpl fib; omega].\n  unfold mult.\n  rewrite plus_0_r.\n  apply plus_le_compat; auto.\n  apply fib_monotone; auto.\nQed.\n\nLemma fib_log_lower_bound :\n  forall n,\n    (div2 n) <= cl_log (fib ((S (S n)))).\nProof.\n  intros.\n  destruct n.\n  simpl;omega.\n  rewrite fib_SS.\n  apply (le_trans ((div2 (S n)))\n                  (cl_log (fib (S n) + fib (S n)))).\n  replace (fib (S n) + fib (S n)) with (2*fib (S n));[|omega].\n  apply (le_trans  ((div2 (S n)))\n                   (cl_log ( pow 2 (div2 (S n))))).\n  rewrite pow2_log.\n  auto.\n  apply cl_log_monotone.\n  apply fib_lower_bound.\n  apply cl_log_monotone.\n  apply plus_le_compat; auto.\n  apply fib_monotone.\n  auto.\nQed.\n  \n  \nTheorem fib_big_omega_2_to_the_div2_n : \n  big_omega fib (fun n => pow 2 (div2 n)).\nProof.\n  apply big_oh_rev.\n  exists 1, 2.\n  intros n LT.\n  destruct n. intuition.\n  apply fib_lower_bound.\nQed.\n\nLemma fib_upper_bound : \n  forall n,\n    fib n <= pow 2 n.\nProof.\n  apply (well_founded_ind\n           lt_wf \n           (fun n => fib n <= pow 2 n)).\n  intros n IND.\n  destruct n. simpl. auto.\n  destruct n. simpl. auto.\n  replace (fib (S (S n))) with (fib (S n) + fib n);[|unfold fib; omega].\n  replace (pow 2 (S (S n))) with (2 * pow 2 (S n));[|unfold pow; omega].\n  unfold mult; rewrite plus_0_r.\n  apply (le_trans (fib (S n) + fib n)\n                  (pow 2 (S n) + pow 2 n)).\n  apply plus_le_compat; apply IND; auto.\n  apply plus_le_compat; auto.\n  apply pow2_monotone; auto.\nQed.\n\nLemma fib_log_upper_bound :\n  forall n,\n    cl_log (fib n) <= n+1.\nProof.\n  intros.\n  apply (le_trans (cl_log (fib n))\n                  (cl_log (pow 2 n))).\n  apply cl_log_monotone.\n  apply fib_upper_bound.\n  rewrite pow2_log.\n  omega.\nQed.  \n\nTheorem fib_big_oh_2_to_the_n : \n  big_oh fib (fun n => pow 2 n).\nProof.\n  exists 0, 1.\n  intros n _.\n  rewrite mult_1_l.\n  apply fib_upper_bound.\nQed.\n\nLemma mle_2_and_3 : forall a b, 3 * a < 2 * b -> 3 * (b + a) < 2 * (b + a + b).\nProof.\n  intros.\n  simpl. intuition.\nQed.\n\nLemma fib_S : forall (n : nat), n > 3 -> 3 * fib n < 2 * (fib (S n)).\nProof.\n  apply (well_founded_induction lt_wf\n                                (fun (n : nat) =>\n                                   n > 3 -> 3 * fib n < 2 * (fib (S n)))).\n  intros n IH g2.\n  destruct n as [|n]; [compute; auto|].\n  destruct n as [|n]; [inversion g2 as [|q G qq]; inversion G|].\n  rewrite fib_SS.\n  destruct n as [|n]; [compute; auto|].\n  destruct n as [|n]; [inversion g2 as [|q1 G q2]; inversion G; omega|].\n  destruct n as [|n]; [compute; auto|].\n  destruct n as [|n]; [compute; auto|].\n  replace (fib (S (S (S (S (S (S (S n))))))))\n  with (fib (S (S (S (S (S n))))) + fib (S (S (S (S n)))) + fib (S (S (S (S (S n)))))).\n  apply mle_2_and_3.\n  apply IH; auto.\n  omega.\n  remember (fib (S (S (S (S (S n)))))) as a.\n  remember (fib (S (S (S (S n))))) as b.\n  rewrite fib_SS.\n  rewrite <- Heqa.\n  rewrite fib_SS.\n  auto.\nQed.\nHint Resolve fib_S.\n\nLemma fib_log_div2 : forall (n : nat), \n                       n > 16 -> 3 * fib (cl_log (div2 n)) < 2 * fib (cl_log n).\nProof.\n  intros n g16.\n  unfold_sub cl_log (cl_log n).\n  do 16 (destruct n as [|n]; [inversion g16; try omega|]).\n  fold_sub cl_log.\n  unfold div2. fold div2.\n  apply fib_S.\n  unfold gt.\n  apply lt_le_trans with (m := cl_log 8); [compute; auto|]. \n  apply cl_log_monotone. \n  intuition.\nAdmitted.\n\nHint Resolve fib_log_div2.\n\nLemma fib_sum_less_than_fib_product:\n  forall n, \n    n >= 4 ->\n    fib n + fib n <= fib n * fib n.\nProof.\n  intros n LE.\n  destruct n;[intuition|].\n  destruct n;[intuition|].\n  destruct n;[intuition|].\n  destruct n;[intuition|].\n  clear LE.\n  apply (well_founded_ind\n           lt_wf\n           (fun n => fib (S (S (S (S n)))) + fib (S (S (S (S n)))) <=\n                     fib (S (S (S (S n)))) * fib (S (S (S (S n)))))).\n  clear n; intros n IND.\n  destruct n.\n  compute; omega.\n  destruct n.\n  compute; omega.\n  \n  replace (fib (S (S (S (S (S (S n))))))) \n  with (fib (S (S (S (S (S n))))) + (fib (S (S (S (S n))))));[|unfold fib;omega].\n  replace ((fib (S (S (S (S (S n))))) + fib (S (S (S (S n))))) +\n           (fib (S (S (S (S (S n))))) + fib (S (S (S (S n))))))\n  with ((fib (S (S (S (S n)))) + fib (S (S (S (S n))))) +\n        (fib (S (S (S (S (S n))))) + fib (S (S (S (S (S n)))))));[|omega].\n  apply (le_trans ((fib (S (S (S (S n)))) + fib (S (S (S (S n))))) +\n                   (fib (S (S (S (S (S n))))) + fib (S (S (S (S (S n)))))))\n                  ((fib (S (S (S (S n)))) * fib (S (S (S (S n))))) +\n                   (fib (S (S (S (S (S n))))) * fib (S (S (S (S (S n)))))))).\n  apply plus_le_compat; apply IND; auto.\n  rewrite mult_plus_distr_r.\n  repeat (rewrite mult_plus_distr_l).\n  remember (fib (S (S (S (S n)))) * fib (S (S (S (S n))))) as i.\n  remember (fib (S (S (S (S (S n))))) * fib (S (S (S (S (S n)))))) as j.\n  replace (j + fib (S (S (S (S (S n))))) * fib (S (S (S (S n)))) +\n           (fib (S (S (S (S n)))) * fib (S (S (S (S (S n))))) + i)) \n  with (i + j + \n        (fib (S (S (S (S (S n))))) * fib (S (S (S (S n)))) +\n         fib (S (S (S (S n)))) * fib (S (S (S (S (S n)))))));[|omega].\n  apply le_plus_trans.\n  omega.\nQed.\n\nLemma cl_log_big_oh_double : \n  big_oh (fun n => cl_log (2 * fib n)) (fun n => cl_log (fib n)).\nProof.\n  apply (big_oh_trans (fun n => cl_log (2 * fib n))\n                      (fun n => (cl_log (fib n * fib n)))).\n  exists 4, 1.\n  intros n LE.\n  rewrite mult_1_l.\n  apply cl_log_monotone.\n  replace (2 * fib n) with (fib n + fib n);[|simpl mult;omega].\n  apply fib_sum_less_than_fib_product.\n  omega.\n\n  exists 0, 4.\n  intros n _.\n  apply cl_log_square_four.\nQed.\n\n", "meta": {"author": "rfindler", "repo": "395-2013", "sha": "afaeb6f4076a1330bbdeb4537417906bbfab5119", "save_path": "github-repos/coq/rfindler-395-2013", "path": "github-repos/coq/rfindler-395-2013/395-2013-afaeb6f4076a1330bbdeb4537417906bbfab5119/fib/fib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.746998724339384}}
{"text": "(* http://study-func-prog.blogspot.jp/2012/04/coq-group-on-setoid.html *)\nRequire Import Relation_Definitions Setoid Morphisms.\nRequire Import Arith Omega.\n\nInductive Z' : Set :=\n| mkZ' : nat -> nat -> Z'.\n\nDefinition eq'(z1 z2:Z') : Prop :=\n  match z1, z2 with\n  | (mkZ' p1 n1), (mkZ' p2 n2) => (p1 + n2 = p2 + n1)\n                                    end.\n\nDefinition minus'(z:Z') :=\n  match z with\n  | mkZ' a b => mkZ' b a\n                     end.\nDefinition plus'(z1 z2:Z') :=\n  match z1, z2 with\n  | (mkZ' a1 b1), (mkZ' a2 b2) => (mkZ' (a1+a2) (b1+b2))\n                                    end.\n\nLemma refl_eq' : reflexive _ eq'.\nProof.\n  unfold reflexive.\n  intro.\n  destruct x as [a b].\n  unfold eq'.\n  omega.\nQed.\n\nLemma sym_eq' : symmetric _ eq'.\nProof.\n  unfold symmetric.\n  intros.\n  destruct x.\n  destruct y.\n  unfold eq'.\n  unfold eq' in H.\n  omega.\nQed.\n\nLemma trans_eq' : transitive _ eq'.\nProof.\n  unfold transitive.\n  intros.\n  destruct x.\n  destruct y.\n  destruct z.\n  unfold eq' in *.\n  omega.\nQed.\n\nAdd Parametric Relation : Z' eq'\n    reflexivity proved by refl_eq'\n    symmetry proved by sym_eq'\n                         transitivity proved by trans_eq' as Z'_setoid.\n\nAdd Parametric Morphism :\n  minus' with signature (eq' ==> eq') as minus'_mor.\nProof.\n  intros.\n  destruct x.\n  destruct y.\n  unfold minus'.\n  unfold eq' in *.\n  omega.\nQed.\n\nAdd Parametric Morphism :\n  plus' with signature (eq' ==> eq' ==> eq') as plus'_mor.\nProof.\n  intros.\n  destruct x.\n  destruct y.\n  destruct x0.\n  destruct y0.\n  unfold plus'.\n  unfold eq' in *.\n  omega.\nQed.\n\nClass Group {S:Set}(eq:S->S->Prop)\n      (e:S)(inv:S->S)(op:S->S->S) := {\n                                      equiv : Equivalence eq;\n                                      equiv_dec : forall x y:S, {eq x y} + {~(eq x y)};\n                                      inv_mor : forall x y:S, eq x y -> eq (inv x) (inv y);\n                                      op_mor : forall x1 y1 x2 y2:S, eq x1 y1 -> eq x2 y2 ->\n                                                                     eq (op x1 x2) (op y1 y2);\n                                      op_assoc : forall x y z:S, eq (op (op x y) z) (op x (op y z));\n                                      left_unit : forall x:S, eq (op e x) x;\n                                      right_unit : forall x:S, eq (op x e) x;\n                                      left_inv : forall x:S, eq (op (inv x) x) e;\n                                      right_inv : forall x:S, eq (op x (inv x)) e}.\n\nInstance Z'_group : Group eq' (mkZ' O O) minus' plus'.\nProof.\n  apply Build_Group.\n  apply Z'_setoid.\n  intros.\n  destruct x.\n  destruct y.\n  unfold eq'.\n  eapply eq_nat_dec.\n  intros.\n  destruct x.\n  destruct y.\n  unfold minus'.\n  unfold eq' in *.\n  omega.\n  intros.\n  destruct x1.\n  destruct x2.\n  destruct y1.\n  destruct y2.\n  unfold plus'.\n  unfold eq' in *.\n  omega.\n  intros.\n  destruct x.\n  destruct y.\n  destruct z.\n  unfold plus'.\n  unfold eq'.\n  omega.\n  intros.\n  destruct x.\n  unfold plus'.\n  unfold eq'.\n  omega.\n  intros.\n  destruct x.\n  unfold plus'.\n  unfold eq'.\n  omega.\n  intros.\n  destruct x.\n  unfold minus'.\n  unfold plus'.\n  unfold eq'.\n  omega.\n  intros.\n  destruct x.\n  unfold minus'.\n  unfold plus'.\n  unfold eq'.\n  omega.\nDefined.  ", "meta": {"author": "unaoya", "repo": "coq_intro", "sha": "c417320df036d96f22744c7bb90695160c012e91", "save_path": "github-repos/coq/unaoya-coq_intro", "path": "github-repos/coq/unaoya-coq_intro/coq_intro-c417320df036d96f22744c7bb90695160c012e91/setoid_group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7469986110233786}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint even (even_arg0 : natural) : bool\n           := match even_arg0 with\n              | Zero => true\n              | Succ n => negb (even n)\n              end.\n\n\nLemma lem: forall m n, even (plus m n) = negb (even (plus m (Succ n))).\nProof.\ninduction m.\n  - intros. simpl. rewrite <- IHm. reflexivity.\n  - intros. simpl. unfold negb. destruct (even n). reflexivity. reflexivity.\nQed.\n\nLemma lem2: forall n, plus n Zero = n.\nProof.\ninduction n.\n  - simpl. rewrite IHn. reflexivity.\n  - reflexivity.\nQed.\n\n\n(* An alternaturale proof strategy is to prove that plus is commutative as a helper lemma,\nand then this theorem can be proven without induction. *)\n\nTheorem theorem0 : forall (x : natural) (y : natural), eq (even (plus x y)) (even (plus y x)).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. rewrite lem. unfold negb.\n  destruct (even (plus y (Succ x))). reflexivity. reflexivity.\n- intros.  simpl. lfind.  reflexivity. \nAdmitted.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal24_theorem0_47_lem2/goal24.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126078, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7469986032274974}}
{"text": "Section Metatheorems.\nRequire Import NaturalNumbers.\n\n(* Theorem 2.1 (1) *)\nTheorem Plus_unit_l :\n    forall n : peano, Plus Z n n.\nProof.\n    apply P_Zero.\nQed.\n\n(* Theorem 2.1 (2) *)\nTheorem Plus_unit_r :\n    forall n : peano, Plus n Z n.\nProof.\n    induction n as [| n' H_n'].\n    \n        (* Case : n = Z *)\n        apply P_Zero.\n    \n        (* Case : n = S n' *)\n        apply (P_Succ _ _ _ H_n').\nQed.\n\n(* Theorem 2.2 *)\nTheorem Plus_uniq :\n    forall n1 n2 n3 n4 : peano, Plus n1 n2 n3 -> Plus n1 n2 n4 -> n3 = n4.\nProof.\n    intros n1 n2.\n    induction n1 as [| n1' H'].\n    \n        (* Case : n1 = Z *)\n        intros n3 n4 H3 H4.\n        inversion H3; subst.\n        inversion H4; subst.\n        reflexivity.\n    \n        (* Case : n1 = S n1' *)\n        intros n3 n4 H3 H4.\n        inversion H3 as [| t1 t2 n3' H3']; subst.\n        inversion H4 as [| t1 t2 n4' H4']; subst.\n        assert (n3' = n4') by apply (H' _ _ H3' H4').\n        subst.\n        reflexivity.\nQed.\n\n(* Theorem 2.3 *)\nTheorem Plus_close :\n    forall n1 n2 : peano, exists n3 : peano, Plus n1 n2 n3.\nProof.\n    intros n1 n2.\n    induction n1 as [| n1' H1].\n    \n        (* Case : n1 = Z *)\n        exists n2.\n        apply P_Zero.\n    \n        (* Case : n1 = S n1' *)\n        destruct H1 as [n3 H3].\n        exists (S n3).\n        apply (P_Succ _ _ _ H3).\nQed.\n\n(* Exercise 2.2 *)\nLemma P_Succ_r :\n    forall n1 n2 n3 : peano, Plus n1 n2 n3 -> Plus n1 (S n2) (S n3).\nProof.\n    induction n1 as [| n1' H1].\n    \n        (* Case : n1 = Z *)\n        intros n2 n3 H.\n        inversion H; subst.\n        apply P_Zero.\n    \n        (* Case : n1 = S n' *)\n        intros n2 n3 H.\n        inversion H; subst.\n        apply P_Succ.\n        apply (H1 _ _ H2).\nQed.\n\n(* Theorem 2.4 *)\nTheorem Plus_comm :\n    forall n1 n2 n3 : peano, Plus n1 n2 n3 -> Plus n2 n1 n3.\nProof.\n    induction n1 as [| n1' H1].\n    \n        (* Case : n1 = Z *)\n        intros n2 n3 H.\n        inversion H; subst.\n        apply Plus_unit_r.\n    \n        (* Case : n1 = S n1' *)\n        intros n2 n3 H.\n        inversion H; subst.\n        apply P_Succ_r.\n        apply (H1 _ _ H2).\nQed.\n\n(* Theorem 2.5 *)\nTheorem Plus_assoc :\n    forall n1 n2 n3 n4 n5 : peano,\n    Plus n1 n2 n4 -> Plus n4 n3 n5 ->\n    exists n6 : peano, Plus n2 n3 n6 /\\ Plus n1 n6 n5.\nProof.\n    induction n1 as [| n1' H1].\n    \n        (* Case : n1 = Z *)\n        intros n2 n3 n4 n5 H4 H5.\n        assert (exists n6, Plus n2 n3 n6) as H6 by apply Plus_close.\n        destruct H6 as [n6 H6].\n        exists n6.\n        split.\n        \n            (* Plus n2 n3 n6 *)\n            apply H6.\n        \n            (* Plus Z n6 n5 *)\n            inversion H4; subst.\n            assert (n5 = n6) as H56 by apply (Plus_uniq _ _ _ _ H5 H6).\n            subst.\n            apply P_Zero.\n    \n        (* Case : n1 = S n1' *)\n        intros n2 n3 n4 n5 H4 H5.\n        assert (exists n6, Plus n2 n3 n6) as H6 by apply Plus_close.\n        destruct H6 as [n6 H6].\n        exists n6.\n        split.\n        \n            (* Plus n2 n3 n6 *)\n            apply H6.\n        \n            (* Plus (S n1') n6 n5 *)\n            inversion H4 as [| A B n4' H4' E F G]; subst.\n            inversion H5 as [| A B n5' H5' E F G]; subst.\n            apply P_Succ.\n            specialize (H1 n2 n3 n4' n5' H4' H5').\n            destruct H1 as [n7 [H7 H1]].\n            assert (n6 = n7) by apply (Plus_uniq _ _ _ _ H6 H7).\n            subst.\n            apply H1.\nQed.\n\n(* Theorem 2.6 *)\nTheorem Times_uniq :\n    forall n1 n2 n3 n4 : peano, Times n1 n2 n3 -> Times n1 n2 n4 -> n3 = n4.\nProof.\n    intros n1 n2.\n    induction n1 as [| n1' H1].\n    \n        (* Case : n1 = Z *)\n        intros n3 n4 H3 H4.\n        inversion H3; subst.\n        inversion H4; subst.\n        reflexivity.\n    \n        (* Case : n1 = S n1' *)\n        intros n3 n4 H3 H4.\n        inversion H3 as [| t1 t2 x t3 Hxt Hxp]; subst.\n        inversion H4 as [| t1 t2 y t3 Hyt Hyp]; subst.\n        assert (x = y) by apply (H1 _ _ Hxt Hyt); subst.\n        apply (Plus_uniq _ _ _ _ Hxp Hyp).\nQed.\n\n(* Theorem 2.7 *)\nTheorem Times_close :\n    forall n1 n2 : peano, exists n3 : peano, Times n1 n2 n3.\nProof.\n    intros n1 n2.\n    induction n1 as [| n1' H1].\n    \n        (* Case : n1 = Z *)\n        exists Z.\n        apply T_Zero.\n    \n        (* Case : n1 = S n1' *)\n        destruct H1 as [n3 H3].\n        assert (exists n4, Plus n2 n3 n4) by apply Plus_close.\n        destruct H as [n4 H4].\n        exists n4.\n        apply (T_Succ _ _ n3 _ H3 H4).\nQed.\n\n(* Theorem 2.8 (1) *)\nTheorem Times_zero_l :\n    forall n : peano, Times Z n Z.\nProof.\n    apply T_Zero.\nQed.\n\n(* Theorem 2.8 (2) *)\nTheorem Times_zero_r :\n    forall n : peano, Times n Z Z.\nProof.\n    induction n as [| n' H].\n    \n        (* Case : n = Z *)\n        apply T_Zero.\n    \n        (* Case : n = S n' *)\n        apply (T_Succ _ _ Z _ H).\n        apply P_Zero.\nQed.\n\nLemma T_Zero_r :\n    forall n : peano, Times n Z Z.\nProof.\n    induction n as [| n' H].\n    \n        (* Case : n = Z *)\n        apply T_Zero.\n    \n        (* Case : n = S n' *)\n        apply (T_Succ _ _ Z _ H).\n        apply P_Zero.\nQed.\n\nLemma T_Succ_r :\n    forall n1 n2 n3 n4 : peano,\n    Times n1 n2 n3 -> Plus n1 n3 n4 -> Times n1 (S n2) n4.\nProof.\nAdmitted.\n\n(* Theorem 2.9 *)\nTheorem Times_comm :\n    forall n1 n2 n3 : peano, Times n1 n2 n3 -> Times n2 n1 n3.\nProof.\n    induction n1 as [| n1' H1].\n    \n        (* Case : n1 = Z *)\n        intros n2 n3 H.\n        inversion H; subst.\n        apply T_Zero_r.\n    \n        (* Case : n1 = S n' *)\n        intros n2 n3 H.\n        inversion H as [| t1 t2 x t3 Hxt Hxp]; subst.\n        assert (Times n2 n1' x) as Hxt' by apply (H1 _ _ Hxt).\n        apply (T_Succ_r _ _ x _ Hxt' Hxp).\nQed.\n\n(* Theorem 2.10 *)\nTheorem Times_assoc :\n    forall n1 n2 n3 n4 n5 : peano,\n    Times n1 n2 n4 -> Times n4 n3 n5 ->\n    exists n6 : peano, Times n2 n3 n6 /\\ Times n1 n6 n5.\nProof.\nAdmitted.\n\n(* Theorem 2.11 (CompareNat1) *)\nTheorem LessThan1_Z_Sn :\n    forall n : peano, LessThan1 Z (S n).\nProof.\n    induction n as [| n' H'].\n    \n        (* Case : n = Z *)\n        apply L1_Succ.\n    \n        (* Case : n = S n' *)\n        apply (L1_Trans _ (S n') _ H').\n        apply L1_Succ.\nQed.\n\n(* Theorem 2.11 (CompareNat2) *)\nTheorem LessThan2_Z_Sn :\n    forall n : peano, LessThan2 Z (S n).\nProof.\n    apply L2_Zero.\nQed.\n\n(* Theorem 2.11 (CompareNat3) *)\nTheorem LessThan3_Z_Sn :\n    forall n : peano, LessThan3 Z (S n).\nProof.\n    induction n as [| n' H].\n    \n        (* Case : n = Z *)\n        apply L3_Succ.\n    \n        (* Case : n = S n' *)\n        apply (L3_SuccR _ _ H).\nQed.\n\n(* Theorem 2.12 (CompareNat1) *)\nTheorem LessThan1_prev :\n    forall n1 n2 : peano, LessThan1 (S n1) (S n2) -> LessThan1 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.12 (CompareNat2) *)\nTheorem LessThan2_prev :\n    forall n1 n2 : peano, LessThan2 (S n1) (S n2) -> LessThan2 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.12 (CompareNat3) *)\nTheorem LessThan3_prev :\n    forall n1 n2 : peano, LessThan3 (S n1) (S n2) -> LessThan3 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.13 (CompareNat1) *)\nTheorem LessThan1_trans :\n    forall n1 n2 n3 : peano,\n    LessThan1 n1 n2 -> LessThan1 n2 n3 -> LessThan1 n1 n3.\nProof.\n    apply L1_Trans.\nQed.\n\n(* Theorem 2.13 (CompareNat2) *)\nTheorem LessThan2_trans :\n    forall n1 n2 n3 : peano,\n    LessThan2 n1 n2 -> LessThan2 n2 n3 -> LessThan2 n1 n3.\nProof.\nAdmitted.\n\n(* Theorem 2.13 (CompareNat3) *)\nTheorem LessThan3_trans :\n    forall n1 n2 n3 : peano,\n    LessThan3 n1 n2 -> LessThan3 n2 n3 -> LessThan3 n1 n3.\nProof.\nAdmitted.\n\n(* Theorem 2.14 (1) (2) *)\nTheorem LessThan_equiv_1_2 :\n    forall n1 n2 : peano, LessThan1 n1 n2 <-> LessThan2 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.14 (2) (3) *)\nTheorem LessThan_equiv_2_3 :\n    forall n1 n2 : peano, LessThan2 n1 n2 <-> LessThan3 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.14 (1) (3) *)\nTheorem LessThan_equiv_1_3 :\n    forall n1 n2 : peano, LessThan1 n1 n2 <-> LessThan3 n1 n2.\nProof.\nAdmitted.\n\n(* Theorem 2.15 *)\nTheorem EvalTo_total :\n    forall e : Exp, exists n : peano, EvalTo e n.\nProof.\n    induction e as [ n1 | e1 [n1 H1] e2 [n2 H2] | e1 [n1 H1] e2 [n2 H2]].\n    \n        (* Case : e = ENum n1 *)\n        exists n1.\n        apply E_Const.\n    \n        (* Case : e = EPlus e1 e2 *)\n        assert (exists n, Plus n1 n2 n) by apply Plus_close.\n        destruct H as [n H].\n        exists n.\n        apply (E_Plus _ _ n1 n2 _ H1 H2 H).\n    \n        (* Case : e = ETimes e1 e2 *)\n        assert (exists n, Times n1 n2 n) by apply Times_close.\n        destruct H as [n H].\n        exists n.\n        apply (E_Times _ _ n1 n2 _ H1 H2 H).\nQed.\n\n(* Theorem 2.16 *)\nTheorem EvalTo_uniq :\n    forall (e : Exp) (n1 n2 : peano), EvalTo e n1 -> EvalTo e n2 -> n1 = n2.\nProof.\n    induction e as [n | e1 He1 e2 He2 | e1 He1 e2 He2].\n    \n        (* Case : e = ENum n *)\n        intros n1 n2 H1 H2.\n        inversion H1; subst.\n        inversion H2; subst.\n        reflexivity.\n    \n        (* Case : e = EPlus e1 e2 *)\n        intros n1 n2 H1 H2.\n        inversion H1 as [| t1 t2 n11' n12' H H11' H12' H1' |]; subst.\n        inversion H2 as [| t1 t2 n21' n22' H H21' H22' H2' |]; subst.\n        assert (n11' = n21') by apply  (He1 _ _ H11' H21'); subst.\n        assert (n12' = n22') by apply  (He2 _ _ H12' H22'); subst.\n        apply (Plus_uniq _ _ _ _ H1' H2').\n    \n        (* Case : e = ETimes e1 e2 *)\n        intros n1 n2 H1 H2.\n        inversion H1 as [| | t1 t2 n11' n12' H H11' H12' H1']; subst.\n        inversion H2 as [| | t1 t2 n21' n22' H H21' H22' H2']; subst.\n        assert (n11' = n21') by apply  (He1 _ _ H11' H21'); subst.\n        assert (n12' = n22') by apply  (He2 _ _ H12' H22'); subst.\n        apply (Times_uniq _ _ _ _ H1' H2').\nQed.\n\n(* Theorem 2.17 *)\nTheorem EPlus_comm :\n    forall (e1 e2 : Exp) (n : peano),\n    EvalTo (EPlus e1 e2) n -> EvalTo (EPlus e2 e1) n.\nProof.\n    intros e1 e2 n H.\n    inversion H as [| t1 t2 n1 n2 t3 H1 H2 Hp t4 |]; subst.\n    assert (Plus n2 n1 n) as Hp' by apply (Plus_comm _ _ _  Hp).\n    apply (E_Plus _ _ _ _ _ H2 H1 Hp').\nQed.\n\n(* Theorem 2.18 *)\nTheorem EPlus_assoc :\n    forall (e1 e2 e3 : Exp) (n : peano),\n    EvalTo (EPlus (EPlus e1 e2) e3) n -> EvalTo (EPlus e1 (EPlus e2 e3)) n.\nProof.\nAdmitted.\n\n(* Theorem 2.19 *)\nTheorem ETimes_comm :\n    forall (e1 e2 : Exp) (n : peano),\n    EvalTo (ETimes e1 e2) n -> EvalTo (ETimes e2 e1) n.\nProof.\n    intros e1 e2 n H.\n    inversion H as [| | t1 t2 n1 n2 t3 H1 H2 Ht t4]; subst.\n    assert (Times n2 n1 n) as Ht' by apply (Times_comm _ _ _ Ht).\n    apply (E_Times _ _ _ _ _ H2 H1 Ht').\nQed.\n\n(* Theorem 2.20 *)\nTheorem ETimes_assoc :\n    forall (e1 e2 e3 : Exp) (n : peano),\n    EvalTo (ETimes (ETimes e1 e2) e3) n -> EvalTo (ETimes e1 (ETimes e2 e3)) n.\nProof.\nAdmitted.\n\n(* Theorem 2.21 *)\nTheorem ReduceTo_progress :\n    forall e : Exp,\n    (exists n : peano, e = ENum n) \\/ (exists e' : Exp, ReduceTo e e').\nProof.\n    induction e as [p | e1 H1 e2 H2 | e1 H1 e2 H2].\n    \n        (* Case : e = ENum p *)\n        left.\n        exists p.\n        reflexivity.\n    \n        (* Case : e = EPlus e1 e2 *)\n        right.\n        destruct H1 as [[n1 H1] | [e1' H1]].\n        \n            (* Case : e1 = Enum n1 *)\n            destruct H2 as [[n2 H2] | [e2' H2]]; subst.\n            \n                (* Case : e2 = ENum n2 *)\n                assert (exists n, Plus n1 n2 n) as H by apply Plus_close.\n                destruct H as [n H].\n                exists (ENum n).\n                apply (R_Plus _ _ _ H).\n            \n                (* Case : ReduceTo e2 e2' *)\n                exists (EPlus (ENum n1) e2').\n                apply (R_PlusR _ _ _ H2).\n        \n            (* Case : ReduceTo e1 e1' *)\n            exists (EPlus e1' e2).\n            apply (R_PlusL _ _ _ H1).\n    \n        (* Case : e = ETimes e1 e2 *)\n        right.\n        destruct H1 as [[n1 H1] | [e1' H1]].\n        \n            (* Case : e1 = Enum n1 *)\n            destruct H2 as [[n2 H2] | [e2' H2]]; subst.\n            \n                (* Case : e2 = ENum n2 *)\n                assert (exists n, Times n1 n2 n) as H by apply Times_close.\n                destruct H as [n H].\n                exists (ENum n).\n                apply (R_Times _ _ _ H).\n            \n                (* Case : ReduceTo e2 e2' *)\n                exists (ETimes (ENum n1) e2').\n                apply (R_TimesR _ _ _ H2).\n        \n            (* Case : ReduceTo e1 e1' *)\n            exists (ETimes e1' e2).\n            apply (R_TimesL _ _ _ H1).\nQed.\n\n(* Theorem 2.22 (incorrect?) *)\nTheorem ReduceTo_confl :\n    forall e1 e2 e3 : Exp,\n    ReduceTo e1 e2 -> ReduceTo e1 e3 ->\n    exists e4 : Exp, ReduceTo e2 e4 /\\ ReduceTo e3 e4.\nProof.\nAdmitted.\n\n(* Theorem 2.23 *)\nTheorem DetReduceTo_uniq :\n    forall e e' e'' : Exp, DetReduceTo e e' -> DetReduceTo e e'' -> e' = e''.\nProof.\nAdmitted.\n\n(* Theorem 2.24 *)\nTheorem DetReduceTo_ReduceTo :\n    forall e e' : Exp, DetReduceTo e e' -> ReduceTo e e'.\nProof.\n    intros e e' H.\n    induction H as [n1 n2 n3 H | n1 n2 n3 H |\n                    e1 e1' e2 _ H' | e1 e2 e2' _ H' |\n                    e1 e1' e2 _ H' | e1 e2 e2' _ H'].\n    \n        (* Case : e = EPlus (ENum n1) (ENum n2) *)\n        apply (R_Plus _ _ _ H).\n    \n        (* Case : e = ETimes (ENum n1) (ENum n2) *)\n        apply (R_Times _ _ _ H).\n    \n        (* Case : DetReduceTo e1 e1', e = EPlus e1 e2 *)\n        apply (R_PlusL _ _ _ H').\n    \n        (* Case : DetReduceTo e2 e2', e = EPlus e1 e2 *)\n        apply (R_PlusR _ _ _ H').\n    \n        (* Case : DetReduceTo e1 e1', e = ETimes e1 e2 *)\n        apply (R_TimesL _ _ _ H').\n    \n        (* Case : DetReduceTo e2 e2', e = ETimes e1 e2 *)\n        apply (R_TimesR _ _ _ H').\nQed.\n\n(* Theorem 2.25 *)\nTheorem ReduceTo_weak_normal :\n    forall e : Exp, exists n : peano, MultiReduceTo e (ENum n).\nProof.\nAdmitted.\n\n(* FIXME: Theorem 2.26 *)\n\n(* Theorem 2.27 *)\nTheorem EvalTo_MultiReduceTo :\n    forall (e : Exp) (n : peano), EvalTo e n -> MultiReduceTo e (ENum n).\nProof.\nAdmitted.\n\n(* Theorem 2.28 *)\nTheorem MultiReduceTo_EvalTo :\n    forall (e : Exp) (n : peano), MultiReduceTo e (ENum n) -> EvalTo e n.\nProof.\nAdmitted.\n\nEnd Metatheorems.\n\n", "meta": {"author": "y-taka-23", "repo": "concepts-of-proglangs", "sha": "980a9a47dccb768b6401bf68db24d93680bb50ce", "save_path": "github-repos/coq/y-taka-23-concepts-of-proglangs", "path": "github-repos/coq/y-taka-23-concepts-of-proglangs/concepts-of-proglangs-980a9a47dccb768b6401bf68db24d93680bb50ce/Metatheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7469844373090772}}
{"text": "(* ConvexHull.v *)\n\nRequire Import Utf8 QArith List.\nImport ListNotations.\n\nRequire Import Slope_base.\n\nRecord newton_segment := mkns\n  { ini_pt : (Q * Q);\n    fin_pt : (Q * Q);\n    oth_pts : list (Q * Q) }.\n\nDefinition slope ms := slope_expr (ini_pt ms) (fin_pt ms).\n\nFixpoint minimise_slope pt₁ pt₂ pts₂ :=\n  match pts₂ with\n  | [] =>\n      {| ini_pt := pt₁; fin_pt := pt₂; oth_pts := [] |}\n  | pt₃ :: pts₃ =>\n      let ms := minimise_slope pt₁ pt₃ pts₃ in\n      match Qcompare (slope_expr pt₁ pt₂) (slope ms) with\n      | Eq =>\n          {| ini_pt := pt₁; fin_pt := fin_pt ms; oth_pts := pt₂ :: oth_pts ms |}\n      | Lt =>\n          {| ini_pt := pt₁; fin_pt := pt₂; oth_pts := [] |}\n      | Gt =>\n          ms\n      end\n  end.\n\nDefinition lower_convex_hull_points pts :=\n  match pts with\n  | [] => None\n  | [pt₁] => None\n  | pt₁ :: pt₂ :: pts₂ =>\n      let ms := minimise_slope pt₁ pt₂ pts₂ in\n      Some {| ini_pt := ini_pt ms; fin_pt := fin_pt ms; oth_pts := oth_pts ms |}\n  end.\n\nTheorem minimised_slope_beg_pt : ∀ pt₁ pt₂ pts,\n  ini_pt (minimise_slope pt₁ pt₂ pts) = pt₁.\nProof.\nintros pt₁ pt₂ pts.\nrevert pt₁ pt₂.\ninduction pts as [| pt]; intros; [ reflexivity | simpl ].\nremember (minimise_slope pt₁ pt pts) as ms.\nremember (slope_expr pt₁ pt₂ ?= slope ms) as c.\nsymmetry in Heqc.\ndestruct c; simpl; [ reflexivity | reflexivity | idtac ].\nsubst ms; apply IHpts.\nQed.\n\nTheorem slope_slope_expr : ∀ ms pt₁ pt₂ pts,\n  minimise_slope pt₁ pt₂ pts = ms\n  → slope ms == slope_expr pt₁ (fin_pt ms).\nProof.\nintros ms pt₁ pt₂ pts Hms.\nunfold slope.\nrewrite <- Hms at 1.\nrewrite minimised_slope_beg_pt.\nreflexivity.\nQed.\n", "meta": {"author": "roglo", "repo": "puiseuxth", "sha": "5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5", "save_path": "github-repos/coq/roglo-puiseuxth", "path": "github-repos/coq/roglo-puiseuxth/puiseuxth-5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5/coq/ConvexHull.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7469541085443029}}
{"text": "Require Import Arith.\n\n(* some useful bindings *)\nDefinition peirce                 := forall P Q:Prop, ((P->Q)->P)->P.\nDefinition classic                := forall P:Prop, ~~P -> P.\nDefinition lem                    := forall P:Prop, P \\/ ~P.\nDefinition and_to_or              := forall P Q:Prop, ~(~P /\\ ~Q) -> P \\/ Q.\nDefinition imp_to_or              := forall P Q:Prop, (P -> Q) -> (~P \\/ Q).\nDefinition ex_to_all              := forall (A:Type) (P: A -> Prop), \n    ~(exists x:A, ~P x) -> (forall x:A, P x).\n\nInductive isZero : nat -> Prop :=\n| IsZero : isZero 0\n.\n\nInductive Even : nat -> Prop :=\n| EvenO  : Even 0\n| EvenSS : forall (n:nat), Even n -> Even (S (S n))\n.\n\n(* discriminate tactic*)\nLemma true_neq_false1 : true <> false.\nProof. intros H. discriminate. Qed.\n\nDefinition toProp (b:bool) : Prop := if b then True else False.\n\n(* change tactic *)\nLemma true_neq_false2 : true <> false.\nProof. intros H. change (toProp  false). rewrite <- H. simpl. exact I. Qed.\n\n(* congruence tactic *)\nLemma true_neq_false3 : true <> false.\nProof. congruence. Qed.\n\n(* injection tactic *)\nLemma S_inj1 : forall (n m:nat), S n = S m -> n = m.\nProof. intros n m H. injection H. intros. assumption. Qed.\n\n(* change tactic *)\nLemma S_inj2 : forall (n m:nat), S n = S m -> n = m.\nProof. \n    intros n m H. change (pred (S n) = pred (S m)). \n    rewrite H. reflexivity. \nQed.\n\n(* apply tactic *)\nLemma obvious1 : True.\nProof. apply I. Qed.\n\n(* constructor tactic *)\nLemma obvious2 : True.\nProof. constructor. Qed.\n\n(* destruct tactic *)\nLemma False_imp1: False -> 2 + 2 = 5.\nProof. intros H. destruct H. Qed.\n\n(* exfalso tactic *)\nLemma False_imp2: False -> 2 + 2 = 5.\nProof. intros H. exfalso. assumption. Qed.\n\n(* discriminate tactic *)\nLemma not1 : ~(2 + 2 = 5).\nProof. intros H. discriminate H. Qed.\n\nFixpoint even (n:nat) : bool :=\n    match n with\n    | 0     => true\n    | S p   => negb (even p)\n    end.\n\n(* change tactic *)\nLemma not2 : ~(2 + 2 = 5).\nProof. intros H. change (toProp (even 5)). rewrite <- H. simpl. apply I. Qed.\n\n(* split tactic *)\nLemma and_comm1 : forall (A B:Prop), A /\\ B -> B /\\ A.\nProof. intros A B [H1 H2]. split; assumption. Qed.\n\n(* left and right tactics *)\nLemma or_comm1 : forall (A B:Prop), A \\/ B -> B \\/ A.\nProof. \n    intros A B [H1|H2].\n    - right. assumption.\n    - left . assumption.\nQed. \n\n(* tauto tactic *)\nLemma and_comm2 : forall (A B:Prop), A /\\ B -> B /\\ A.\nProof. tauto. Qed. \n\n\n(* tauto tactic *)\nLemma or_comm2 : forall (A B:Prop), A \\/ B -> B \\/ A.\nProof. tauto. Qed. \n\n(* exists tactic *)\nLemma exist1 : exists (n:nat), n + 3 = 5.\nProof. exists 2. reflexivity. Qed.\n\n(* firstorder tactic *)\nLemma firstorder1 : forall (A:Type) (P: A->Prop),\n  (forall x:A, P x) -> ~(exists x:A, ~P x).\nProof.  firstorder. Qed.\n\n(* intuition tactic *)\nLemma intuition1 : peirce -> classic.\nProof.\n  unfold peirce. unfold classic. intuition.\n  apply H with False. intros H1. exfalso. apply H0. assumption.\nQed.\n\n(* firstorder tactic *)\nLemma firstorder2 : peirce -> classic.\nProof.\n  unfold peirce. unfold classic. firstorder.\n  apply H with False. intros H1. exfalso. apply H0. assumption.\nQed.\n\n(* cut tactic *)\nLemma cut1: 1 + 1 = 2.\nProof. \n    cut (2 + 2 = 4).\n    - intros E. reflexivity.\n    - reflexivity. \nQed.\n\n(* assert tactic *)\nLemma assert1: 1 + 1 = 2.\nProof.\n    assert (2 + 2 = 4) as E.\n    - reflexivity.\n    - reflexivity.\nQed.\n\n(* remember tactic *)\nLemma remember1 : 1 + 1 = 2.\n    remember 1 as x eqn:E.\n    rewrite E. reflexivity.\nQed.\n\n(* inversion tactic *)\nLemma not_isZero_1 : ~ isZero 1.\nProof. intros H. inversion H. Qed.\n\n\n(* tactic auto *)\nHint Constructors Even.\n\nLemma Even_4 : Even 4.\nProof. auto. Qed.\n\n(* tactic ring*)\nLemma fact_basic: forall (n:nat), (S n) * fact n = fact (S n).\nProof.\n    induction n as [|n IH].\n    - reflexivity.\n    - simpl. ring.\nQed.\n\n\n(* refine tactic *)\nDefinition refine_test : forall (n m:nat), {n = m} + {n <> m}.\n    refine (fix f (n m:nat) : {n = m} + {n <> m} :=\n        match n,m with\n        | 0,0       => left _                             (* leaving a hole *)\n        | S n, S m  => if f n m then left _ else right _  (* two more holes *)\n        | _, _      => right _                            (* one last hole  *) \n        end).\n    (* getting 5 goals though, not four, probably a good reason to this *)\n    (* could factorize with a single 'congruence'                       *)\n    - reflexivity.\n    - congruence.\n    - congruence.\n    - congruence.\n    - congruence.\nDefined.  (* rather than 'Qed' so proof term is not opaque  *)\n\n(* decide tactic *)\nDefinition decide_test : forall (n m:nat), {n = m} + {n <> m}.\n    decide equality.\nDefined.\n\n(*\nPrint decide_test.\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/cpdt/tactic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7468989002153803}}
{"text": "Require Export Lib.\nRequire Export Coq.Classes.RelationClasses.\nRequire Export Coq.Setoids.Setoid.\n\nParameter set : Type.\n\nParameter In : set → set → Prop.\n\nNotation \"x ∈ X\" := (In x X) (at level 69).\nNotation \"x ∉ X\" := (not (In x X)) (at level 69).\n\nDefinition Subq (X Y : set) : Prop := ∀ x : set, x ∈ X → x ∈ Y.\n\nNotation \"X ⊆ Y\" := (Subq X Y) (at level 69).\n\nLemma Subq_refl : ∀ (A : set), A ⊆ A.\nProof. compute. auto. Qed.\nHint Resolve Subq_refl.\n\nInstance Subq_Refl : Reflexive Subq.\nProof. exact Subq_refl. Qed.\n\nLemma Subq_trans : ∀ (A B C : set), A ⊆ B → B ⊆ C → A ⊆ C.\nProof. compute. auto. Qed.\nHint Resolve Subq_trans.\n\nInstance Subq_Trans : Transitive Subq.\nProof. exact Subq_trans. Qed.\n\nDefinition set_equiv (A B : set) := A ⊆ B /\\ B ⊆ A.\n\nInstance set_Equiv : Equivalence set_equiv.\nProof.\n  constructor.\n  - intro x.\n    split; intros; auto.\n  - intros x y.\n    destruct 1.\n    split; intros; auto.\n  - intros x y z.\n    destruct 1, 1.\n    split; intros;\n    [ apply (Subq_trans x y z)\n    | apply (Subq_trans z y x) ]; auto.\nQed.\n\nAdd Parametric Relation : set set_equiv\n  reflexivity proved by (@Equivalence_Reflexive _ _ set_Equiv)\n  symmetry proved by (@Equivalence_Symmetric _ _ set_Equiv)\n  transitivity proved by (@Equivalence_Transitive _ _ set_Equiv)\n  as set_equiv_rel.\n\n(* Axiom 1 (Extensionality). Two sets X and Y are equal if they contain the\n   same elements. *)\n\nAxiom extensionality : ∀ X Y : set, X ⊆ Y → Y ⊆ X → X = Y.\nHint Resolve extensionality.\n\nLemma extensionality_E : ∀ X Y : set, X = Y -> X ⊆ Y ∧ Y ⊆ X.\nProof.\n  intros. split; compute; intros.\n    rewrite <- H. assumption.\n    rewrite H. assumption.\nQed.\n\nHint Resolve extensionality_E.\n\nLtac extension := apply extensionality; unfold Subq; intros.\n\n(* Axiom 2 (∈-induction). The membership relation on sets satisfies the\n   induction principle. *)\n\nAxiom In_ind : ∀ P : set → Prop,\n  (∀ X : set, (∀ x, x ∈ X → P x) → P X) →\n  (∀ X : set, P X).\n\n(* Axiom 3 (The empty set). There ∃ a set which does not contain any\n   elements.  We call this set the empty set and denote it by ∅. *)\n\nParameter Empty : set.\n\nNotation \"∅\" := (Empty).\n\nAxiom Empty_E : ∀ x : set, x ∉ ∅.\n\nHint Resolve Empty_E.\n\nDefinition inh_set (S : set) := ∃ w, w ∈ S.\n\n(* Axiom 4 (Pairing). For all sets y and z there ∃ a set containing\n   exactly y and z as elements. We call this set the unordered pair of y and z\n   and denote it by {y,z}. *)\n\nParameter UPair : set → set → set.\n\nAxiom UPair_I1 : ∀ y z : set, y ∈ (UPair y z).\nAxiom UPair_I2 : ∀ y z : set, z ∈ (UPair y z).\nAxiom UPair_E : ∀ x y z : set, x ∈ (UPair y z) → x = y ∨ x = z.\n\nHint Resolve UPair_I1.\nHint Resolve UPair_I2.\nHint Resolve UPair_E.\n\nNotation \"{ a , b }\" := (UPair a b) (at level 69).\n\n(* The axiomatic pairing of sets a and b is agnostic with respect to their\n   ordering. *)\n\nTheorem pair_agnostic : ∀ a b, {a, b} = {b, a}.\nProof.\n  intros.\n  apply (extensionality (UPair a b) (UPair b a));\n  intros x H; apply UPair_E in H; inversion H; rewrite H0; auto.\nQed.\n\nHint Resolve pair_agnostic.\n\nLtac pair_e H := apply UPair_E in H; try (inv H); try auto.\nLtac pair_1 := apply UPair_I1; try auto.\nLtac pair_2 := apply UPair_I2; try auto.\n\n(* Axiom 5 (Union). Given a collection of sets X, there ∃ a set whose\n   elements are exactly those which are a member of at least one of the sets\n   in the collection X.  We call this set the union over X and denote it by\n   ∪. *)\n\nParameter Union : set → set.\n\nAxiom Union_I : ∀ X x Y : set, x ∈ Y → Y ∈ X → x ∈ (Union X).\nAxiom Union_E : ∀ X x : set, x ∈ (Union X) → ∃ Y : set, x ∈ Y ∧ Y ∈ X.\n\nHint Resolve Union_I.\nHint Resolve Union_E.\n\nDefinition BinUnion (A B : set) : set := Union (UPair A B).\n\nLtac obvious_PU :=\n  intros; repeat (match goal with\n  | [ |- ?X = ?Y ] => extension\n\n  | [ |- ?A ∈ ({?A, ?B}) ] => pair_1\n  | [ |- ?B ∈ ({?A, ?B}) ] => pair_2\n  | [ H : ?X ∈ ({?A, ?B}) |- _ ] => pair_e H\n\n  | [ H : ?X ∈ Union ?M |- _ ] =>\n    apply Union_E in H; destruct H; inv H\n\n  | [ H : ?X ∈ ?A |- ?X ∈ Union({?A, ?B}) ] =>\n    apply Union_I with (Y := A)\n  | [ H : ?X ∈ ?B |- ?X ∈ Union({?A, ?B}) ] =>\n    apply Union_I with (Y := B)\n\n  end; auto).\n\nLemma BinUnion_I1 : ∀ A B a: set, a ∈ A → a ∈ BinUnion A B.\nProof. compute. obvious_PU. Qed.\n\nHint Resolve BinUnion_I1.\n\nLemma BinUnion_I2 : ∀ A B b: set, b ∈ B → b ∈ BinUnion A B.\nProof. compute. obvious_PU. Qed.\n\nHint Resolve BinUnion_I2.\n\nLemma BinUnion_E : ∀ A B x, x ∈ BinUnion A B → x ∈ A ∨ x ∈ B.\nProof. compute. obvious_PU. Qed.\n\nHint Resolve BinUnion_E.\n\nNotation \"X ∪ Y\" := (BinUnion X Y) (at level 69).\n\nLtac union_e H := apply BinUnion_E in H; destruct H; try (inv H); try auto.\nLtac union_1 := apply BinUnion_I1; try auto.\nLtac union_2 := apply BinUnion_I2; try auto.\n\n(* Axiom 6 (Powerset). Given a set X, there ∃ a set which contains as its\n   elements exactly those sets which are the subsets of X. We call this set the\n   powerset of X and denote it by 𝒫(X). *)\n\nParameter Power : set → set.\n\nAxiom Power_I : ∀ X Y : set, Y ⊆ X → Y ∈ (Power X).\nAxiom Power_E : ∀ X Y : set, Y ∈ (Power X) → Y ⊆ X.\n\nHint Resolve Power_I.\nHint Resolve Power_E.\n\n(* Axiom 7 (Replacement). Given a unary set former F and a set X, there ∃\n   a set which contains exactly those elements obtained by applying F to each\n   element in X. We denote this construction with {F x | x ∈ X}. *)\n\nParameter Repl : (set → set) → set → set.\n\nAxiom Repl_I : ∀ (X : set) (F : set → set) (x : set),\n  x ∈ X → (F x) ∈ (Repl F X).\nAxiom Repl_E : ∀ (X : set) (F : set → set) (y : set),\n  y ∈ (Repl F X) → ∃ x : set, x ∈ X ∧ y = F x.\n\nHint Resolve Repl_I.\nHint Resolve Repl_E.\n\nLtac obvious_BUR :=\n  repeat (try obvious_PU; match goal with\n  | [ H : ?X ∈ (?A ∪ ?B) |- _ ] => union_e H\n  | [ |- ?A ∈ (?A ∪ ?B) ] => union_1\n  | [ |- ?B ∈ (?A ∪ ?B) ] => union_2\n  end; auto).\n", "meta": {"author": "jwiegley", "repo": "set-theory", "sha": "ae9714a5b7355fb23b7383a0bc4c90dc00c50264", "save_path": "github-repos/coq/jwiegley-set-theory", "path": "github-repos/coq/jwiegley-set-theory/set-theory-ae9714a5b7355fb23b7383a0bc4c90dc00c50264/Axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7468988870761589}}
{"text": "(* ================================================================== *)\nSection EX.\n\nVariables (A:Set) (P : A->Prop).\nVariable Q:Prop.\n\n\n(* Check the type of an expression. *)\nCheck P.\nCheck Set.\nCheck A -> Prop.\n\nVariable a:A.\n\nCheck P a.\n\n\nLemma trivial : forall x:A, P x -> P x.\nProof.\n  intros.\n  assumption.\nQed.\n\n\n(* Prints the definition of an identifier. *)\nPrint trivial.\n\n\nLemma example : forall x:A, (Q -> Q -> P x) -> Q -> P x.\nProof.\n  intros x H H0.\n  apply H.\n  assumption.\n  assumption.\nQed.\n\nPrint example.\n\n\nProposition nova : Q -> ~ ~ Q.\nProof.\n  intros.\n  unfold not.\n  intros.\n  apply H0.\n  assumption.\nQed.           (* when we close the proof the definition of the identifier \n                  \"nova\" goes to the global environment *)\n\nTheorem demo : forall y,  Q -> (~ ~ Q -> P y) -> P y.\nProof.\n  intros.\n  apply H0.\n  apply nova.   (* we can use a definition in the global environment *)\n  assumption.\nQed.\n\n  \nEnd EX.\n\nPrint trivial.\nPrint example.\n(* ================================================================== *)\n\n\n\n\n(* ================================================================== *)\n(* ====================== Propositional Logic ======================= *)\n(* ================================================================== *)\n\nSection ExamplesPL.\n\nVariables Q P :Prop.\n\nLemma ex1 : (P -> Q) -> ~Q -> ~P.\nProof.\n  tauto.\nQed.\n\nPrint ex1.\n\nLemma ex1' : (P -> Q) -> ~Q -> ~P.\nProof.\n  intros.\n  intro.\n  apply H0.\n  apply H.\n  assumption.\nQed.\n\nPrint ex1'.\n\n\nLemma ex2 : P /\\ Q -> Q /\\ P.\nProof.\n  intro H.\n  split.\n  destruct H as [H1 H2].\n  exact H2.\n  destruct H; assumption.\nQed.\n\n(* We can itemize the subgoals using - for each of them. Note that whem entering in this mode the other subgoals are not displayed. For nested item use the symbols -, +, *, --, ++, **, ... *)\nLemma ex2' : P /\\ Q -> Q /\\ P.\nProof.\n  intro H.  split.\n  - destruct H as [H1 H2]. exact H2.\n  - destruct H; assumption.\nQed.\n\n\nLemma ex3 : P \\/ Q -> Q \\/ P.\nProof.\n  intros.\n  destruct H as [h1 | h2].\n  - right. assumption.\n  - left; assumption.\nQed.\n\n\n\nTheorem ex4 : forall A:Prop, A -> ~~A.\nProof.\n  intros.\n  intro.\n  apply H0. \n  exact H.\nQed.\n\nLemma ex4' : forall A:Prop, A -> ~~A.\nProof.\n  intros.\n  red.     (* does only the unfolding of the head of the goal *)\n  intro.\n  unfold not in H0.   (* unfold – applies the delta rule for a transparent constant. *)\n  apply H0; assumption.   (* exact (H0 H) *)\nQed.\n\n\n\n\nAxiom double_neg_law : forall A:Prop, ~~A -> A.  (* classical *)\n\n(* CAUTION: Axiom is a global declaration. \n   Even after the section is closed double_neg_law is assume in the enviroment, and can be used. \n   If we want to avoid this we should decalre double_neg_law using the command Hypothesis. \n*)  \n\n\nLemma ex5 : (~Q -> ~P) -> P -> Q.   (* this result is only valid classically *)\nProof.\n  intros.\n  apply double_neg_law.\n  intro.\n  (* apply H; assumption. *)\n  apply H.\n  - assumption.\n  - assumption.\nQed.\n\n\nLemma ex6 : (P\\/Q)/\\~P -> Q.\nProof.\n  intros.\n  elim H. intros .\n  destruct H0.\n  - contradiction.\n  - assumption.\nQed.\n\n\nLemma ex7 : ~(P \\/ Q) <-> ~P /\\ ~Q.\nProof.\n  red.\n  split.\n  - intros.\n    split.\n    + unfold not in H.\n      intro H1.\n      apply H.\n      left; assumption.\n    + intro H1; apply H; right; assumption.\n  - intros H H1.\n    destruct H.\n    destruct H1.  \n    + contradiction.\n    + contradiction.\nQed.\n\n\nLemma ex7' : ~(P \\/ Q) <-> ~P /\\ ~Q.\nProof.\n  tauto.\nQed.\n\n\n\nVariable B :Prop.\nVariable C :Prop.\n\n\n(* exercise *)\nLemma ex8 : (P->Q) /\\ (B->C) /\\ P /\\ B -> Q/\\C. \nAdmitted.\n \n(* exercise *)\nLemma ex9 : ~ (P /\\ ~P).   \nAdmitted.\n\n\nEnd ExamplesPL.\n\n(* ================================================================== *)\n(* =======================  First-Order Logic ======================= *)\n(* ================================================================== *)\n\nSection ExamplesFOL.\n\nVariable X :Set.\nVariable t :X. \nVariables R W : X -> Prop.\n\nLemma ex10 : R(t) -> (forall x, R(x)->~W(x)) -> ~W(t).\nProof.\n  intros.\n  apply H0.\n  exact H.\nQed.\n\n\nLemma ex11 : forall x, R x -> exists x, R x.\nProof.\n  intros.\n  exists x.\n  assumption.\nQed.\n\n\nLemma ex11' : forall x, R x -> exists x, R x.\nProof.\n  firstorder.\nQed.\n\n\n\nLemma ex12 : (exists x, ~(R x)) -> ~ (forall x, R x).\nProof.\n  intros H H1.\n  destruct H as [x0 H0].\n  apply H0.\n  apply H1.\nQed.\n\n\n(* Exercise *)\nLemma ex13 : (forall x, R x) \\/ (forall x, W x) -> forall x, (R x) \\/ (W x).\nAdmitted.\n\nVariable G : X->X->Prop.\n\n(* Exercise *)\nLemma ex14 : (exists x, exists y, (G x y)) -> exists y, exists x, (G x y).\nAdmitted.\n\n\n(* Exercise *)\nProposition ex15: (forall x, W x)/\\(forall x, R x) -> (forall x, W x /\\ R x).\nAdmitted.\n\n\n(* ------- Note that we can have nested sections ----------- *)\nSection Relations.\n\nVariable D : Set.\nVariable Rel : D->D->Prop.\n\nHypothesis R_symmetric : forall x y:D, Rel x y -> Rel y x.\nHypothesis R_transitive : forall x y z:D, Rel x y -> Rel y z -> Rel x z.\n\n\nLemma refl_if : forall x:D, (exists y, Rel x y) -> Rel x x.\nProof.\n  intros.\n  destruct H.\n  (* try \"apply R_transitive\" to see de error message *)\n  apply R_transitive with x0. \n  - assumption.\n  - apply R_symmetric.\n    assumption.\nQed.\n\nCheck refl_if.\n\nEnd Relations.\n\nCheck refl_if. (* Note the difference after the end of the section Relations. *)\n\n\n\n(* ====== OTHER USES OF AXIOMS ====== *)\n\n(* --- A stack abstract data type --- *)\nSection Stack.\n\nVariable U:Type.\n\nParameter stack : Type -> Type.\nParameter emptyS : stack U. \nParameter push : U -> stack U -> stack U.\nParameter pop : stack U -> stack U.\nParameter top : stack U -> U.\nParameter isEmpty : stack U -> Prop.\n\nAxiom emptyS_isEmpty : isEmpty emptyS.\nAxiom push_notEmpty : forall x s, ~isEmpty (push x s).\nAxiom pop_push : forall x s, pop (push x s) = s.\nAxiom top_push : forall x s, top (push x s) = x.\n\nEnd Stack.\n\nCheck pop_push.\n\n(* Now we can make use of stacks in our formalisation!!! *)\n\n(* A NOTE OF CAUTION!!! *)\n(* The capability to extend the underlying theory with arbitary axiom \n   is a powerful but dangerous mechanism. We must avoid inconsistency. \n*)\nSection Caution.\n\nCheck False_ind.\n\nHypothesis ABSURD : False.\n\nTheorem oops : forall (P:Prop), P /\\ ~P.\nelim ABSURD.\nQed.\n\nEnd Caution. (* We have declared ABSURD as an hypothesis to avoid its use outside this section. *)\n\n\n\n", "meta": {"author": "sir-onze", "repo": "Formal-Verification", "sha": "d55362a3c0f3e760d68b7e95b99d0a8b84d688da", "save_path": "github-repos/coq/sir-onze-Formal-Verification", "path": "github-repos/coq/sir-onze-Formal-Verification/Formal-Verification-d55362a3c0f3e760d68b7e95b99d0a8b84d688da/lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7468875264519798}}
{"text": "Fixpoint max (n m : nat) {struct n} : nat :=\n  match n, m with\n  | 0 , _ => m\n  | S n' , 0 => n\n  | S n' , S m' => S (max n' m')\n  end.\n\nExample max_test1 : max 100 200 = 200. simpl. reflexivity. Qed.\nExample max_test2 : max 3 3 = 3. simpl. reflexivity. Qed.\nExample max_test3 : max 4 3 = 4. simpl. reflexivity. Qed.\n\nInductive Tree : Type :=\n  | Leaf : Tree\n  | Node2 : Tree -> Tree -> Tree\n  | Node3 : Tree -> Tree -> Tree -> Tree.\n\nDefinition exTree1 : Tree := Node2 (Node3 Leaf Leaf Leaf) Leaf.\n\nDefinition exTree2 : Tree := Node2 (Node2 Leaf (Node2 (Node2 Leaf Leaf) Leaf)) (Node2 Leaf Leaf).\n\nFixpoint height (t : Tree) {struct t} : nat :=\n  match t with\n  | Leaf => 0\n  | Node2 lhs rhs => S (max (height lhs) (height rhs))\n  | Node3 lhs mid rhs => S (max (max (height lhs) (height mid)) (height rhs))\n  end.\n\n\n(* BEGIN FIX *)\nExample height_test_1 : height exTree1 = 2.\nProof.\n  trivial.\nQed.\n(* END FIX *)\n\n(* BEGIN FIX *)\nExample height_test_2 : height exTree2 = 4.\nProof.\n  trivial.\nQed.\n(* END FIX *)\n\n(* BEGIN FIX *)\nLemma max_0 (m : nat) : max m 0 = m.\nProof.\n  induction m.\n    trivial.\n    simpl. trivial.\nQed.\n(* END FIX *)\n\n(* BEGIN FIX *)\nLemma height_Leaf (t : Tree) : height (Node2 t Leaf) = height (Node2 Leaf t).\nProof.\n  simpl. rewrite max_0. trivial.\nQed.\n(* END FIX *)\n\n(* BEGIN FIX *)\nLemma max_comm : forall (m n : nat),  max m n = max n m.\nProof.\n  intro m.\n  induction m.\n    simpl. intro n. rewrite max_0. trivial.\n    (* why do I get a more general IH? *)\n    destruct n.\n      trivial.\n      simpl. rewrite IHm. trivial.\nQed.\n(* END FIX *)", "meta": {"author": "Anabra", "repo": "Formal-Semantics", "sha": "e72f9999aae6ee5cb7eeffc0d8619db7cebecbc1", "save_path": "github-repos/coq/Anabra-Formal-Semantics", "path": "github-repos/coq/Anabra-Formal-Semantics/Formal-Semantics-e72f9999aae6ee5cb7eeffc0d8619db7cebecbc1/homework/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7468875201840137}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, fold_length *)\n\nNotation \"[]\" := nil.\nNotation \"x :: y\" := (cons x y)(at level 60, right associativity).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint fold{X Y: Type}(f: X -> Y -> Y)(l: list X)(v: Y): Y :=\n    match l with \n    |[]   => v\n    |h::t => f h (fold f t v)\n    end.\n\nDefinition fold_length{X: Type}(l: list X): nat :=\n      fold (fun _ n => S n) l O.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\nTheorem fold_length_correct: forall X (l: list X),\n      fold_length l = length l.\nProof.\n    intros. unfold fold_length.\n    induction l as [|h t].\n    simpl. reflexivity.\n    simpl. rewrite IHt. reflexivity.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter6_Library_Poly/fold_length.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.7468875103971382}}
{"text": "(**\nThe Little Prover の memb?/remb をCoqで解いてみる（サブリスト改訂版）\n *)\n\nRequire Import Bool.\nRequire Import List.\nRequire Import Program.\nSet Implicit Arguments.\n\n(** * はじめに *)\n\n(**\nThe Little Prover (TLP) の第6章では、memb?/remb という定理が扱われています。\nこれは、リニアなリストの要素から、文字 '?' を削除する関数 remb と、\nこれは、リニアなリストの要素に、文字 '?' が含まれるかを判定する関数 memb? が\n定義されているとき、\n任意のリスト xs に対して、(memb? (remb xs)) が必ず False になるというものです。\n\nオリジナルはLisp系の言語なので、リストの要素は任意のデータでよいのですが、\nCoqの場合は、自然数のリストとし、もじ '?' の代わりに 0 とします。\n  *)\n\n(**\nソースコードは、\n#<a href=\"https://github.com/suharahiromichi/coq/blob/master/prog/coq_membp_remb_3.v\">\nここ\n</a>\nにあります。\n *)\n\n(**\nまず、membp (memb? に対応する) の自然数のリストに 0 が含まれていることを判定する関数を定義ましす。\nリストの先頭から見ていき 0 が含まれていたらそこで True を返します。\n*)\n\nFixpoint membp (xs : list nat) : Prop :=\n  match xs with\n  | nil => False\n  | 0 :: xs' => True\n  | _ :: xs' => membp xs'\n  end.\n\nCompute membp (1 :: 0 :: 2 :: nil).         (** ==> [True] *)\n\nCompute membp (1 :: 2 :: 3 :: nil).         (** ==> [False] *)\n\nCompute membp nil.                          (** ==> [False] *)\n\n(**\nついで、remb のリストから 0 を削除する関数を定義します。\nリストの先頭から見ていき 0 なら、それを含まない結果を返し\nfalse なら、それを含む結果を返します。\n*)\n\nFixpoint remb (xs : list nat) : list nat :=\n  match xs with\n  | nil => nil\n  | 0 :: xs' => remb xs'\n  | x :: xs' => x :: remb xs'\n  end.\n\nCompute remb (0 :: 1 :: 0 :: nil).         (** ==> [[1]] *)\n\n(** * memb?/remb の証明 *)\n\n(**\nmemb?/remb に対応する membp_remb は、文字通りの定義です。\n結果は偽であるため、「~」がついています。\n *)\n\nDefinition membp_remb (xs : list nat) := ~ membp (remb xs).\n\n(** 以下に、membp_remb を証明します。線形リスト xs に対する帰納法と、\n要素 x に対する場合分けだけで証明されています。\nなお、帰納法の仮定IHxsは、ふたつめとみっつめのnowでトリビアルに使われます。\n *)\n  \nLemma le_membp_remb : forall (xs : list nat), membp_remb xs.\nProof.\n  unfold membp_remb.\n  induction xs as [|x xs IHxs].\n  - now simpl.\n  (** x が 0 か 0 でないかで場合分けする。 *)\n  - case x as [| x']; simpl.\n    (** ここで帰納法の仮定を使う。 *)\n    + now trivial.\n    + now trivial.\n\n  Restart.\n  unfold membp_remb.\n  intros xs.\n  induction xs as [|x xs IHxs]; try auto.\n  now case x.\nQed.\n\n(**\nmemb?/remb は定理としては自明ですが、 0 が含まれないことをチェックする関数membpによって、\n 0 を削除する関数rembが正しく動作していることを証明する、と考えることができます。\n\nこれは、関数の定義とその証明を同時におこなう証明駆動開発の一例となります。\nCoqにはそれをサポートする「Program」コマンドがあります。\nこれを使って remb を再定義してみましょう。\n\nremb' の値は、単なる list nat ではなく、\n[{ys : list nat | ~ membp ys}]\nすなわち、\n[~ membp ys] を満たす [ys] の集合の要素、\nとなります。\n\nこれだと、最初に想定した型と違うので困ると思うかもしれませんが、\n「Program」コマンドの中では、そのサブタイプ・コアーションの機能によって、\nlist boot 型と同一視されます。\n\nremb' の結果が普通にconsされていることに気づいてください。\n\n「Program」コマンドの中では、そのサブタイプ・コアーションは、\n再帰呼び出しのみならず、他の（定義済みの）任意な関数に適用されます。\n *)\n\nProgram Fixpoint remb' (xs : list nat) : {ys : list nat | ~ membp ys} :=\n  match xs with\n  | nil => nil\n  | 0 :: xs' => remb' xs'\n  | x :: xs' => x :: remb' xs'\n  end.\nObligation 2.\nProof.\n  case x as [| x']; simpl.\n  - generalize (H xs'); intro H'.\n    exfalso.\n    now apply H'.\n  - now trivial.\nDefined.\n\nCompute ` (remb' (0 :: 1 :: 0 :: nil)).     (** ==> [[1]] *)\n\nExtraction remb'.\n(**\n生成されたコードには、rembp は含まれていない。\n\n[[\nval remb' : nat list -> nat list,\n\nlet rec remb' = function\n| Nil -> Nil\n| Cons (x, xs') ->\n  (match x with\n   | O -> remb' xs'\n   | S n -> let x0 = S n in Cons (x0, (remb' xs')))\n]]\n*)\n\n(** * 証明駆動開発 *)\n\n(** ** remb 条件を Inductive に定義する *)\n\n(** remb を Inductive に定義した、Listwo0 (List without 0 のつもり) を定義します。 *)\n\nInductive Listwo0 : list nat -> Prop :=\n| Wo0_nil      : Listwo0 nil\n| Wo0_skip   l : Listwo0 l -> Listwo0 (0 :: l)\n| Wo0_cons x l : x <> 0 -> Listwo0 l -> Listwo0 (x :: l).\n\nHint Constructors Listwo0.\n\nProgram Fixpoint remb'' (xs : list nat) : {ys : list nat | Listwo0 ys} :=\n  match xs with\n  | nil => nil\n  | 0 :: xs' => remb'' xs'\n  | x :: xs' => x :: remb'' xs'\n  end.\nObligation 2.\nProof.\n  apply Wo0_cons.\n  - case x as [| x']; simpl.\n    + generalize (H xs'); intro H'.\n      exfalso.\n      now apply H'.\n    + now trivial.\n  - now trivial.\nDefined.\n\nCompute ` (remb'' (0 :: 1 :: 0 :: nil)).    (** ==> [[1]] *)\n\n(**\nremb' の定義を「リストから 0 を除去する関数」の証明付き定義と考えると問題があります。\n *)\n\n(** 0を抜いたサブリストの関係を定義します。  *)\n\nInductive Sublist0 : list nat -> list nat -> Prop :=\n| SL0_nil         : Sublist0 nil nil\n| SL0_skip   l' l : Sublist0 l' l -> Sublist0 l' (0 :: l)\n| SL0_cons x l' l : x <> 0 -> Sublist0 l' l -> Sublist0 (x :: l') (x :: l).\n\nHint Constructors Sublist0.\n\nProgram Fixpoint remb''' (xs : list nat) :\n  {ys : list nat | Sublist0 ys xs} :=\n  match xs with\n  | nil => nil\n  | 0 :: xs' => remb''' xs'\n  | x :: xs' => x :: remb''' xs'\n  end.\nObligation 3.\nProof.\n  apply SL0_cons.\n  - case x as [| x']; simpl.\n    + generalize (H xs'); intro H'.\n      exfalso.\n      now apply H'.\n    + now trivial.\n  - now trivial.\nDefined.\n\nCompute ` (remb''' (0 :: 1 :: 0 :: nil)).    (** ==> [[1]] *)\n\nExtraction remb'''.\n\n(**\n生成されたコードには、Sublist0 は含まれていません。\n\n[[\nval remb'' : nat list -> nat list\n\nlet rec remb'' = function\n| Nil -> Nil\n| Cons (b, xs') ->\n  (match b with\n   |  0  -> remb'' xs'\n   | False -> Cons (False, (remb'' xs')))\n]]\n *)\n\n(** * 帰納法の公理 *)\n\n(**\nTLPにもどって、帰納法による証明について考えてみましょう。\nTLPでは、（例によって、天から降ってきた）「inductive claim」を証明しています。\nこれの導きかたは第6章の最後に記載されていますが、Coqの場合は、\nリストの型定義にもとづく「公理」を使います。\n *)\n\nCheck list_ind : forall (A : Type) (P : list A -> Prop),\n    P [] ->\n    (forall (a : A) (l : list A), P l -> P (a :: l)) ->\n    forall l : list A, P l.\n\n(**\nこれを membp_remb に適用すると次を得ます。\n繰り返しますが、これは証明するべきものではなく、「公理」です。\n *)\n\nCheck list_ind membp_remb :\n  membp_remb [] ->\n  (forall (a : nat) (l : list nat), membp_remb l -> membp_remb (a :: l)) ->\n  forall l : list nat, membp_remb l.\n\n(**\nこの公理を使うなら、\n\n[forall l : list nat, membp_remb l]\n\nを証明するには、\n\n[membp_remb []]\n\nと\n\n[forall (a : nat) (l : list nat), membp_remb l -> membp_remb (a :: l)]\n\nとを証明すればよいことになります。後者は、TLPでは、l は nil でないことを条件に、\n[(cdr l)] をとっていて、つまり、\n\n[forall (l : list nat  ), membp_remb (tl l) -> membp_remb l]\n\nとなっています。おなじですね。\n *)\n\n(**\n実際の証明は、以下の通りです。\n *)\n\nGoal forall xs, membp_remb xs.\nProof.\n  intros xs.\n  apply (list_ind membp_remb).\n  - now simpl.\n  - intros x' xs' IHxs.\n    case x'; simpl.\n    + now trivial.\n    + now trivial.\nQed.\n\n(**\n最初の証明では、\n\n[induction xs] というタクティクを使いましたが、\n\nこの公理を\n\n[apply (list_ind membp_remb)]\n\nとして、適用することと同じです。\n *)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/prog/coq_membp_remb_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7468715858812606}}
{"text": "Require Import Coq.Logic.Classical.\nRequire Import Coq.Sets.Ensembles.\n\nLemma union_empty_r : forall U A,\n  Union U A (Empty_set U) = A.\nProof.\n  intros. apply Extensionality_Ensembles.\n  split; intros x x_in_one.\n  inversion x_in_one as [ _x in_A x_eq | _x false x_eq ].\n  auto. inversion false.\n  left. auto.\nQed.\n\nLemma union_empty_l : forall U A, Union U (Empty_set U) A = A. \nProof.\n  intros. apply Extensionality_Ensembles. split; intros x x'. \n  inversion x'. inversion H. auto. apply Union_intror. auto. \nQed. \n\nLemma union_swap : forall U A B,\n  Union U A B = Union U B A.\n\nintros. \napply Extensionality_Ensembles. \nsplit; intros x x_in_one;\ndestruct x_in_one as [ x x_in_left | x x_in_right ];\nauto using Union_introl, Union_intror.\n\nQed.\n\nLemma disjoint_setminus :\n  forall U A B,\n    Disjoint U A (Setminus U B A).\n\n  intros.\n  apply Disjoint_intro. unfold not.\n  intros x in_int.\n  destruct in_int as [ x x_in_A x_in_setminus ].\n  destruct x_in_setminus.\n  tauto.\n\nQed.\n\nLemma add_add_to_union_couple :\n  forall U A x y,\n    (Add U (Add U A x) y) = (Union U A (Couple U y x)).\n\nintros.\napply Extensionality_Ensembles. split; intros z z_in_one.\ndestruct z_in_one as [ z' [ z z_in_A | z z_is_x ] | z z_is_y ].\nleft. auto. \nright. inversion z_is_x. subst z. right.\nright. inversion z_is_y. subst z. left.\ndestruct z_in_one as [ z z_in_A | z [ | ] ].\nleft. left. auto.\nright. apply In_singleton. \nleft. right. apply In_singleton.\n\nQed.\n\nLemma couple_swap :\n  forall U A B,\n    Couple U A B = Couple U B A.\n\nintros.\napply Extensionality_Ensembles. split; intros x x_in_one.\ndestruct x_in_one. right. left.\ndestruct x_in_one. right. left.\n\nQed.\n\nLemma add_subtract :\n  forall U A x,\n    In U A x ->\n    A = Add U (Subtract U A x) x.\n\nintros.\napply Extensionality_Ensembles. split; intros y y_in_one.\nassert (x = y \\/ x <> y) as [ is_x | not_x ]. apply classic.\nright. subst y. apply In_singleton.\nleft. split. auto. intros false.\ninversion false. tauto.\ndestruct y_in_one as [ y y_in_subtract | y y_is_x ].\ndestruct y_in_subtract. auto. inversion y_is_x. subst y. auto.\n\nQed.\n\n\nTheorem eqImpliesSameSet : forall (T:Type) T1 T2, T1 = T2 -> Same_set T T1 T2. \nProof.\n  intros. unfold Same_set. unfold Included. split; intros. \n  {subst. assumption. }\n  {subst. assumption. }\nQed. \n\nHint Unfold In. \nHint Constructors Singleton Couple. \n\nTheorem SingleEqCouple : forall (T:Type) s1 s2 s3,\n                           Singleton T s1 = Couple T s2 s3 -> s1 = s2 /\\ s1 = s3.\nProof.\n  intros. apply eqImpliesSameSet in H. unfold Same_set in H.\n  unfold Included in H. inversion H. split.\n  {assert(In T (Couple T s2 s3) s2). auto. apply H1 in H2.\n   inversion H2. reflexivity. }\n  {assert(In T (Couple T s2 s3) s3). auto. apply H1 in H2.\n   inversion H2. reflexivity. }\nQed.\n\nTheorem SingletonEq : forall (T:Type) (e1 e2 : T), Singleton T e1 = Singleton T e2 -> e1 = e2. \nProof.\n  intros. apply eqImpliesSameSet in H. unfold Same_set in H. unfold Included in *. \n  inversion H. assert(Ensembles.In T (Singleton T e1) e1). auto. apply H0 in H2. \n  inversion H2. reflexivity. Qed. \n \nTheorem UnionEqSingleton : forall (T:Type) S e1 e2, \n                             Union T S (Singleton T e1) = Singleton T e2 ->\n                             e1 = e2. \nProof.\n  intros. apply eqImpliesSameSet in H. unfold Same_set in H. unfold Included in *. \n  inversion H. assert(In T (Union T S(Singleton T e1)) e1). \n  apply Union_intror. constructor. apply H0 in H2. inversion H2. \n  reflexivity. Qed. \n\nTheorem InL : forall X T1 T2 t, In X T2 t -> In X (Union X T1 T2) t. \nProof.\n  intros. apply Union_intror. auto. \nQed. \n\nHint Resolve InL. \n \nLtac solveSet := try(solve[eauto with sets]); try solve[eapply InL; eauto with sets]. \n\nLtac eqSets := apply Extensionality_Ensembles; unfold Same_set; unfold Included; split; intros. \n\n\nTheorem disjointUnionEqSingleton : forall (T:Type) S e1 e2, \n                                     Disjoint T S (Singleton T e1) ->\n                                     Union T S (Singleton T e1) = Singleton T e2 ->\n                                     e1 = e2 /\\ S = Empty_set T. \nProof.\n  intros. apply eqImpliesSameSet in H0. unfold Same_set in *. unfold Included in *. \n  inversion H0. inversion H. split.\n  {assert(In T (Union T S (Singleton T e1)) e1). apply Union_intror. \n   constructor. apply H1 in H4. inversion H4. reflexivity. }\n  {assert(In T (Singleton T e2) e2). constructor. apply H2 in H4. inversion H4. \n   {assert(In T (Union T S (Singleton T e1)) e1). solveSet. apply H1 in H7. \n    inversion H7. subst. inversion H. \n    assert(In T (Intersection T S (Singleton T e1)) e1). solveSet. \n    apply H6 in H8. contradiction. }\n   {subst. apply Extensionality_Ensembles. unfold Same_set. unfold Included. \n    split; intros. \n    {assert(In T (Union T S (Singleton T e1)) x). solveSet. \n     apply H1 in H7. inversion H7. subst. inversion H5. subst. \n     assert(In T (Intersection T S(Singleton T x)) x). solveSet. \n     apply H3 in H8. contradiction. }\n    {inversion H6. }\n   }\n  }\nQed. \n\nTheorem AddEqCouple : forall T S e e1 e2, Add T S e = Couple T e1 e2 ->\n                                          e = e1 \\/ e = e2. \nProof.\n  intros. unfold Add in H. apply eqImpliesSameSet in H. unfold Same_set in *. \n  unfold Included in *. inversion H. \n  assert(Ensembles.In T (Union T S (Singleton T e)) e). solveSet. \n  apply H0 in H2. inversion H2; auto. \nQed. \n\nTheorem AddEqSingleton : forall T S e e', Add T S e = Singleton T e' -> e = e'. \nProof.\n  intros. unfold Add in H. apply UnionEqSingleton in H. assumption. Qed. \n\nTheorem pullOut : forall X T t, Ensembles.In X T t -> T = Union X (Subtract X T t) (Singleton X t). \nProof.\n  intros. apply Extensionality_Ensembles. unfold Same_set. unfold Included. split; intros. \n  {unfold Subtract. assert(x=t \\/ x<>t). apply classic. inversion H1; subst. \n   {apply Union_intror. constructor. }\n   {apply Union_introl. constructor. assumption. intros c. inversion c. symmetry in H3. \n    contradiction. }\n  }\n  {inversion H0; subst.\n   {inversion H1; subst. assumption. }\n   {inversion H1; subst. assumption. }\n  }\nQed. \n\nTheorem SingletonNeqEmpty : forall X t, Singleton X t = Empty_set X -> False.\nProof.\n  intros. apply eqImpliesSameSet in H. unfold Same_set in H. unfold Included in H. inversion H. \n  assert(Ensembles.In X (Singleton X t) t). constructor. subst. apply H0 in H2. inversion H2. Qed. \n\nTheorem AddNeqEmpty : forall X T t, Add X T t = Empty_set X -> False. \nProof.\n  intros. apply eqImpliesSameSet in H. unfold Same_set in H. unfold Included in H. inversion H. \n  assert(Ensembles.In X (Add X T t) t). apply Union_intror. constructor. apply H0 in H2. inversion H2. \nQed. \n\nTheorem CoupleNeqEmpty : forall X t1 t2, Couple X t1 t2 = Empty_set X -> False.\nProof.\n  intros. apply eqImpliesSameSet in H. unfold Same_set in H. unfold Included in H. inversion H. \n  assert(Ensembles.In X (Couple X t1 t2) t1). constructor. apply H0 in H2. inversion H2. Qed. \n\n\nHint Constructors Union Couple. \n\nTheorem coupleUnion : forall X t1 t2, Couple X t1 t2 = Union X (Singleton X t1) (Singleton X t2). \nProof.\n  intros. apply Extensionality_Ensembles. unfold Same_set. unfold Included. split; intros. \n  {inversion H; subst; auto. }\n  {inversion H; subst. inversion H0; subst; auto. inversion H0; subst; auto. }\nQed. \n\nTheorem UnionSwap : forall X T1 T2 T3,\n                      Union X (Union X T1 T2) T3 = Union X (Union X T1 T3) T2. \nProof.\n  intros. apply Extensionality_Ensembles. unfold Same_set. unfold Included. split; intros. \n  {inversion  H; subst. inversion H0; subst. constructor. constructor. auto. apply Union_intror. \n  auto. constructor. apply Union_intror. auto. }\n  {inversion H; subst. inversion H0; subst. constructor. constructor. auto. \n   apply Union_intror. auto. constructor. apply Union_intror. auto. }\nQed. \n\n\nTheorem UnionSwapR : forall X T t1 t2 t3,\n                       Union X (Union X T (Singleton X t1)) (Couple X t2 t3) = \n                       Union X (Union X T (Singleton X t3)) (Couple X t2 t1). \nProof.\n  intros. eqSets. \n  {inversion H; inversion H0; subst; solveSet. inversion H2; subst; solveSet. }\n  {inversion H; inversion H0; solveSet. inversion H2; subst. solveSet. }\nQed. \n\nTheorem UnionSwapL : forall X T t1 t2 t3,\n                       Union X (Union X T (Singleton X t1)) (Couple X t2 t3) = \n                       Union X (Union X T (Singleton X t2)) (Couple X t1 t3). \nProof.\n  intros. eqSets. \n  {inversion H; inversion H0; solveSet. inversion H2; solveSet. }\n  {inversion H; inversion H0; solveSet. inversion H2; solveSet. }\nQed.\n\nTheorem pullOutR : forall X T t1 t2, \n                     Union X T (Couple X t1 t2) = \n                     Union X (Union X T (Singleton X t1)) (Singleton X t2). \nProof.\n  intros. eqSets. \n  {inversion H; solveSet. inversion H0; solveSet. }\n  {inversion H; solveSet; inversion H0; solveSet. inversion H2; solveSet. }\nQed. \n\n\nTheorem pullOutL : forall X T t1 t2, \n                     Union X T (Couple X t1 t2) = \n                     Union X (Union X T (Singleton X t2)) (Singleton X t1). \nProof.\n  intros. eqSets. \n  {inversion H; solveSet. inversion H0; solveSet. }\n  {inversion H; solveSet; inversion H0; solveSet. inversion H2; solveSet. }\nQed. \n\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/newest/sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7468715806001732}}
{"text": "(*** Montgomery Multiplication *)\n(** This file implements the proofs for Montgomery Form, Montgomery\n    Reduction, and Montgomery Multiplication on [Z].  We follow\n    Wikipedia. *)\nRequire Import Coq.ZArith.ZArith Coq.micromega.Lia Coq.Structures.Equalities.\nRequire Import Crypto.Arithmetic.MontgomeryReduction.Definition.\nRequire Import Crypto.Util.ZUtil.EquivModulo.\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SimplifyRepeatedIfs.\nRequire Import Crypto.Util.Notations.\n\nDeclare Module Nop : Nop.\nModule Import ImportEquivModuloInstances := Z.EquivModuloInstances Nop.\n\nLocal Existing Instance eq_Reflexive. (* speed up setoid_rewrite as per https://coq.inria.fr/bugs/show_bug.cgi?id=4978 *)\n\nLocal Open Scope Z_scope.\n\nSection montgomery.\n  Context (N : Z)\n          (N_reasonable : N <> 0)\n          (R : Z)\n          (R_good : Z.gcd N R = 1).\n  Local Notation \"x ≡ y\" := (Z.equiv_modulo N x y) : type_scope.\n  Local Notation \"x ≡ᵣ y\" := (Z.equiv_modulo R x y) : type_scope.\n  Context (R' : Z)\n          (R'_good : R * R' ≡ 1).\n\n  Lemma R'_good' : R' * R ≡ 1.\n  Proof using R'_good. rewrite <- R'_good; apply f_equal2; lia. Qed.\n\n  Local Notation to_montgomery_naive := (to_montgomery_naive R) (only parsing).\n  Local Notation from_montgomery_naive := (from_montgomery_naive R') (only parsing).\n\n  Lemma to_from_montgomery_naive x : to_montgomery_naive (from_montgomery_naive x) ≡ x.\n  Proof using R'_good.\n    unfold to_montgomery_naive, from_montgomery_naive.\n    rewrite <- Z.mul_assoc, R'_good'.\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n  Lemma from_to_montgomery_naive x : from_montgomery_naive (to_montgomery_naive x) ≡ x.\n  Proof using R'_good.\n    unfold to_montgomery_naive, from_montgomery_naive.\n    rewrite <- Z.mul_assoc, R'_good.\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n\n  (** * Modular arithmetic and Montgomery form *)\n  Section general.\n    Local Infix \"+\" := add : montgomery_scope.\n    Local Infix \"-\" := sub : montgomery_scope.\n    Local Infix \"*\" := (mul_naive R') : montgomery_scope.\n\n    Lemma add_correct_naive x y : from_montgomery_naive (x + y) = from_montgomery_naive x + from_montgomery_naive y.\n    Proof using Type. unfold from_montgomery_naive, add; lia. Qed.\n    Lemma add_correct_naive_to x y : to_montgomery_naive (x + y) = (to_montgomery_naive x + to_montgomery_naive y)%montgomery.\n    Proof using Type. unfold to_montgomery_naive, add; autorewrite with push_Zmul; reflexivity. Qed.\n    Lemma sub_correct_naive x y : from_montgomery_naive (x - y) = from_montgomery_naive x - from_montgomery_naive y.\n    Proof using Type. unfold from_montgomery_naive, sub; lia. Qed.\n    Lemma sub_correct_naive_to x y : to_montgomery_naive (x - y) = (to_montgomery_naive x - to_montgomery_naive y)%montgomery.\n    Proof using Type. unfold to_montgomery_naive, sub; autorewrite with push_Zmul; reflexivity. Qed.\n\n    Theorem mul_correct_naive x y : from_montgomery_naive (x * y) = from_montgomery_naive x * from_montgomery_naive y.\n    Proof using Type. unfold from_montgomery_naive, mul_naive; lia. Qed.\n    Theorem mul_correct_naive_to x y : to_montgomery_naive (x * y) ≡ (to_montgomery_naive x * to_montgomery_naive y)%montgomery.\n    Proof using R'_good.\n      unfold to_montgomery_naive, mul_naive.\n      rewrite <- !Z.mul_assoc, R'_good.\n      autorewrite with zsimplify; apply (f_equal2 Z.modulo); lia.\n    Qed.\n  End general.\n\n  (** * The REDC algorithm *)\n  Section redc.\n    Context (N' : Z)\n            (N'_in_range : 0 <= N' < R)\n            (N'_good : N * N' ≡ᵣ -1).\n\n    Lemma N'_good' : N' * N ≡ᵣ -1.\n    Proof using N'_good. rewrite <- N'_good; apply f_equal2; lia. Qed.\n\n    Lemma N'_good'_alt x : (((x mod R) * (N' mod R)) mod R) * (N mod R) ≡ᵣ x * -1.\n    Proof using N'_good.\n      rewrite <- N'_good', Z.mul_assoc.\n      unfold Z.equiv_modulo; push_Zmod.\n      reflexivity.\n    Qed.\n\n    Section redc.\n      Context (T : Z).\n\n      Local Notation m := (((T mod R) * N') mod R).\n      Local Notation prereduce := (prereduce N R N').\n\n      Local Ltac t_fin_correct :=\n        unfold Z.equiv_modulo; push_Zmod; autorewrite with zsimplify; reflexivity.\n\n      Lemma prereduce_correct : prereduce T ≡ T * R'.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        transitivity ((T + m * N) * R').\n        { unfold prereduce.\n          autorewrite with zstrip_div; push_Zmod.\n          rewrite N'_good'_alt.\n          autorewrite with zsimplify pull_Zmod.\n          reflexivity. }\n        t_fin_correct.\n      Qed.\n\n      Lemma reduce_correct : reduce N R N' T ≡ T * R'.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold reduce.\n        break_match; rewrite prereduce_correct; t_fin_correct.\n      Qed.\n\n      Lemma partial_reduce_correct : partial_reduce N R N' T ≡ T * R'.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold partial_reduce.\n        break_match; rewrite prereduce_correct; t_fin_correct.\n      Qed.\n\n      Lemma reduce_via_partial_correct : reduce_via_partial N R N' T ≡ T * R'.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold reduce_via_partial.\n        break_match; rewrite partial_reduce_correct; t_fin_correct.\n      Qed.\n\n      Let m_small : 0 <= m < R. Proof. auto with zarith. Qed.\n\n      Section generic.\n        Lemma prereduce_in_range_gen B\n        : 0 <= N\n          -> 0 <= T <= R * B\n          -> 0 <= prereduce T < B + N.\n        Proof using N_reasonable m_small. unfold prereduce; auto with zarith nia. Qed.\n      End generic.\n\n      Section N_very_small.\n        Context (N_very_small : 0 <= 4 * N < R).\n\n        Lemma prereduce_in_range_very_small\n          : 0 <= T <= (2 * N - 1) * (2 * N - 1)\n            -> 0 <= prereduce T < 2 * N.\n        Proof using N_reasonable N_very_small m_small. pose proof (prereduce_in_range_gen N); nia. Qed.\n      End N_very_small.\n\n      Section N_small.\n        Context (N_small : 0 <= 2 * N < R).\n\n        Lemma prereduce_in_range_small\n          : 0 <= T <= (2 * N - 1) * (N - 1)\n            -> 0 <= prereduce T < 2 * N.\n        Proof using N_reasonable N_small m_small. pose proof (prereduce_in_range_gen N); nia. Qed.\n\n        Lemma prereduce_in_range_small_fully_reduced\n          : 0 <= T <= 2 * N\n            -> 0 <= prereduce T <= N.\n        Proof using N_reasonable N_small m_small. pose proof (prereduce_in_range_gen 1); nia. Qed.\n      End N_small.\n\n      Section N_small_enough.\n        Context (N_small_enough : 0 <= N < R).\n\n        Lemma prereduce_in_range_small_enough\n          : 0 <= T <= R * R\n            -> 0 <= prereduce T < R + N.\n        Proof using N_reasonable N_small_enough m_small. pose proof (prereduce_in_range_gen R); nia. Qed.\n\n        Lemma reduce_in_range_R\n          : 0 <= T <= R * R\n            -> 0 <= reduce N R N' T < R.\n        Proof using N_reasonable N_small_enough m_small.\n          intro H; pose proof (prereduce_in_range_small_enough H).\n          unfold reduce, prereduce in *; break_match; Z.ltb_to_lt; nia.\n        Qed.\n\n        Lemma partial_reduce_in_range_R\n          : 0 <= T <= R * R\n            -> 0 <= partial_reduce N R N' T < R.\n        Proof using N_reasonable N_small_enough m_small.\n          intro H; pose proof (prereduce_in_range_small_enough H).\n          unfold partial_reduce, prereduce in *; break_match; Z.ltb_to_lt; nia.\n        Qed.\n\n        Lemma reduce_via_partial_in_range_R\n          : 0 <= T <= R * R\n            -> 0 <= reduce_via_partial N R N' T < R.\n        Proof using N_reasonable N_small_enough m_small.\n          intro H; pose proof (prereduce_in_range_small_enough H).\n          unfold reduce_via_partial, partial_reduce, prereduce in *; break_match; Z.ltb_to_lt; nia.\n        Qed.\n      End N_small_enough.\n\n      Section unconstrained.\n        Lemma prereduce_in_range\n          : 0 <= T <= R * N\n            -> 0 <= prereduce T < 2 * N.\n        Proof using N_reasonable m_small. pose proof (prereduce_in_range_gen N); nia. Qed.\n\n        Lemma reduce_in_range\n        : 0 <= T <= R * N\n          -> 0 <= reduce N R N' T < N.\n        Proof using N_reasonable m_small.\n          intro H; pose proof (prereduce_in_range H).\n          unfold reduce, prereduce in *; break_match; Z.ltb_to_lt; nia.\n        Qed.\n\n        Lemma partial_reduce_in_range\n        : 0 <= T <= R * N\n          -> Z.min 0 (R - N) <= partial_reduce N R N' T < 2 * N.\n        Proof using N_reasonable m_small.\n          intro H; pose proof (prereduce_in_range H).\n          unfold partial_reduce, prereduce in *; break_match; Z.ltb_to_lt;\n            apply Z.min_case_strong; nia.\n        Qed.\n\n        Lemma reduce_via_partial_in_range\n        : 0 <= T <= R * N\n          -> Z.min 0 (R - N) <= reduce_via_partial N R N' T < N.\n        Proof using N_reasonable m_small.\n          intro H; pose proof (partial_reduce_in_range H).\n          unfold reduce_via_partial in *; break_match; Z.ltb_to_lt; lia.\n        Qed.\n      End unconstrained.\n\n      Section alt.\n        Context (N_in_range : 0 <= N < R)\n                (T_representable : 0 <= T < R * R).\n        Lemma partial_reduce_alt_eq : partial_reduce_alt N R N' T = partial_reduce N R N' T.\n        Proof using N_in_range N_reasonable T_representable m_small.\n          assert (0 <= T + m * N < 2 * (R * R)) by nia.\n          assert (0 <= T + m * N < R * (R + N)) by nia.\n          assert (0 <= (T + m * N) / R < R + N) by auto with zarith.\n          assert ((T + m * N) / R - N < R) by lia.\n          assert (R * R <= T + m * N -> R <= (T + m * N) / R) by auto with zarith.\n          assert (T + m * N < R * R -> (T + m * N) / R < R) by auto with zarith.\n          assert (H' : (T + m * N) mod (R * R) = if R * R <=? T + m * N then T + m * N - R * R else T + m * N)\n            by (break_match; Z.ltb_to_lt; autorewrite with zsimplify; lia).\n          unfold partial_reduce, partial_reduce_alt, prereduce.\n          rewrite H'; clear H'.\n          simplify_repeated_ifs.\n          set (m' := m) in *.\n          autorewrite with zsimplify; push_Zmod; autorewrite with zsimplify; pull_Zmod.\n          break_match; Z.ltb_to_lt; autorewrite with zsimplify; try reflexivity; lia.\n        Qed.\n\n        Lemma reduce_via_partial_alt_eq : reduce_via_partial_alt N R N' T = reduce_via_partial N R N' T.\n        Proof.\n            cbv [reduce_via_partial_alt reduce_via_partial].\n            rewrite partial_reduce_alt_eq by lia. reflexivity.\n        Qed.\n      End alt.\n    End redc.\n\n    (** * Arithmetic in Montgomery form *)\n    Section arithmetic.\n      Local Infix \"*\" := (mul N R N') : montgomery_scope.\n\n      Local Notation to_montgomery := (to_montgomery N R N').\n      Local Notation from_montgomery := (from_montgomery N R N').\n      Lemma to_from_montgomery a : to_montgomery (from_montgomery a) ≡ a.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold to_montgomery, from_montgomery.\n        transitivity ((a * 1) * 1); [ | apply f_equal2; lia ].\n        rewrite <- !R'_good, !reduce_correct.\n        unfold Z.equiv_modulo; push_Zmod; pull_Zmod.\n        apply f_equal2; lia.\n      Qed.\n      Lemma from_to_montgomery a : from_montgomery (to_montgomery a) ≡ a.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold to_montgomery, from_montgomery.\n        rewrite !reduce_correct.\n        transitivity (a * ((R * (R * R' mod N) * R') mod N)).\n        { unfold Z.equiv_modulo; push_Zmod; pull_Zmod.\n          apply f_equal2; lia. }\n        { repeat first [ rewrite R'_good\n                       | reflexivity\n                       | push_Zmod; pull_Zmod; progress autorewrite with zsimplify\n                       | progress unfold Z.equiv_modulo ]. }\n      Qed.\n\n      Theorem mul_correct x y : from_montgomery (x * y) ≡ from_montgomery x * from_montgomery y.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold from_montgomery, mul.\n        rewrite !reduce_correct; apply f_equal2; lia.\n      Qed.\n      Theorem mul_correct_to x y : to_montgomery (x * y) ≡ (to_montgomery x * to_montgomery y)%montgomery.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold to_montgomery, mul.\n        rewrite !reduce_correct.\n        transitivity (x * y * R * 1 * 1 * 1);\n          [ rewrite <- R'_good at 1\n          | rewrite <- R'_good at 1 2 3 ];\n          autorewrite with zsimplify;\n          unfold Z.equiv_modulo; push_Zmod; pull_Zmod.\n        { apply f_equal2; lia. }\n        { apply f_equal2; lia. }\n      Qed.\n    End arithmetic.\n  End redc.\nEnd montgomery.\n\nModule Import LocalizeEquivModuloInstances := Z.RemoveEquivModuloInstances Nop.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Arithmetic/MontgomeryReduction/Proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7468683271621166}}
{"text": "Require Import Bool.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Lib.EqDec.\n\nDefinition FunExt := forall (A B: Type) (f g: A -> B), (forall x: A, f x = g x) -> f = g.\n\nDefinition set (A: Type) : Type := A -> bool.\n\n\nDefinition set_filter {A: Type} (p: A-> bool) (s: set A) : set A :=\n  fun x: A => if p x then s x else false.\n\nDefinition set_union {A: Type} (s s': set A) : set A :=\n  fun x: A => (s x) || (s' x).\n\nDefinition set_intersection {A: Type} (s s': set A) : set A :=\n  fun x: A => (s x) && (s' x).\n\nDefinition set_complement {A: Type} (s: set A) : set A :=\n  fun x: A => negb (s x).\n\nDefinition set_add {A: Type} `{EqDec A} (a: A) (s: set A)  : set A :=\n  fun x: A => if eqf x a then true else s x.\n\nFixpoint list_to_set {A: Type} `{EqDec A} (l: list A) : set A :=\nmatch l with\n| []        => fun _ => false\n| (h :: l') => set_add h (list_to_set l')\nend.\n\nTheorem double_set_complement {A: Type} `{FunExt} `{EqDec A} (s: set A) :\n  s = set_complement (set_complement s).\nProof.\n  unfold set_complement. apply H. intros x. destruct (s x); auto.\nQed.\n\nTheorem list_to_set_correct {A: Type} `{EqDec A} (l: list A) :\n  forall x: A, reflect (In x l) (list_to_set l x).\nProof.\n  intros x. destruct (list_to_set l x) eqn:e; constructor.\n  - induction l; cbn in *; [inversion e|].\n    unfold set_add in *. rewrite eqf_sym in e. destruct (eqf a x) eqn:e'.\n    + left. apply eqf_iff. auto.\n    + right. auto.\n  - intros I. induction l; cbn in *; [inversion I|].\n    unfold set_add in *. destruct I.\n    + subst. rewrite eqf_refl in e. inversion e.\n    + apply IHl; [|auto]. destruct (eqf x a); [inversion e | auto].\nQed.\n\n\n\nDefinition mset (A: Type) : Type := A -> nat.\n\n\nDefinition mset_filter {A: Type} (p: A-> bool) (s: mset A) : mset A :=\n  fun x: A => if p x then s x else 0.\n\nDefinition mset_union {A: Type} (s s': mset A) : mset A :=\n  fun x: A => (s x) + (s' x).\n\nDefinition mset_intersection {A: Type} (s s': mset A) : mset A :=\n  fun x: A => min (s x) (s' x). \n\nDefinition mset_add {A: Type} `{EqDec A} (a: A) (s: mset A)  : mset A :=\n  fun x: A => if eqf x a then S (s x) else s x.\n\nFixpoint list_to_mset {A: Type} `{EqDec A} (l: list A) : mset A :=\nmatch l with\n| []        => fun _ => O\n| (h :: l') => mset_add h (list_to_mset l')\nend.", "meta": {"author": "speederking07", "repo": "magisterka", "sha": "602d1e328ac4a396c282e241744d129573a65381", "save_path": "github-repos/coq/speederking07-magisterka", "path": "github-repos/coq/speederking07-magisterka/magisterka-602d1e328ac4a396c282e241744d129573a65381/Master/FunctionalQuotient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7468683229978724}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) : natural :=\n  plus (mult x lf1) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj241_coqofml_GOBDWc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7468423249182896}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint less (less_arg0 : natural) (less_arg1 : natural) : bool\n           := match less_arg0, less_arg1 with\n              | x, Zero => false\n              | Zero, Succ x => true\n              | Succ x, Succ y => less x y\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\nFixpoint insort (insort_arg0 : natural) (insort_arg1 : lst) : lst\n           := match insort_arg0, insort_arg1 with\n              | i, Nil => Cons i Nil\n              | i, Cons x y => if less i x then Cons i (Cons x y) else Cons x (insort i y)\n              end.\n\nFixpoint sort (sort_arg0 : lst) : lst\n           := match sort_arg0 with\n              | Nil => Nil\n              | Cons x y => insort x (sort y)\n              end.\n(* Requires No helper lemma *)\nTheorem theorem0 : forall (x : natural) (y : lst), eq (len (insort x y)) (Succ (len y)).\nProof.\n   intros.\n  induction y.\n  - simpl. destruct (less x n) eqn:?.\n    + reflexivity.\n    + simpl. rewrite IHy. reflexivity.\n    - reflexivity.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal68.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7468423129589103}}
{"text": "\n    (*nandb*)\n    Definition neg (b:bool):bool := \n        match b with\n        | true => false\n        | false => true\n        end.\n    Notation \"~ x\" := (neg x).\n\n    Definition orb (b1:bool) (b2:bool) : bool :=\n        match b1 with\n        | true => true\n        | false => b2\n    end.\n    \n    Definition andb (b1:bool) (b2:bool):bool := \n        match b1 with\n        | true => b2\n        | false => false\n        end.\n    \n    Definition nandb (b1:bool) (b2:bool) :bool := \n        match b1 with\n        | false => true\n        | true => ~ b2\n        end.\n\n    Example testnandb1: (nandb true false)=true.\n    Proof. simpl. reflexivity. Qed.\n    Example testnandb2: (nandb false false)=true.\n    Proof. simpl. reflexivity. Qed.\n    Example testnandb3: (nandb false true)=true.\n    Proof. simpl. reflexivity. Qed.\n    Example testnandb4: (nandb true true)=false.\n    Proof. simpl. reflexivity. Qed.\n\n    (*andb3*)\n    Definition and (b1:bool) (b2:bool):bool :=\n        match b1 with \n        |false => false\n        |true => b2\n        end.\n    Notation \"a && b\" := (and a b).\n\n    Definition andb3 (b1:bool) (b2:bool) (b3:bool):bool := \n        match b1 with\n        |false => false\n        |true => b2 && b3\n        end.\n    Example test_andb31: (andb3 true true true) = true.\n    Proof. simpl. reflexivity. Qed.\n    Example test_andb32: (andb3 false true true) = false.\n    Proof. simpl. reflexivity. Qed.\n    Example test_andb33: (andb3 true false true) = false.\n    Proof. simpl. reflexivity. Qed.\n    Example test_andb34: (andb3 true true false) = false.\n    Proof. simpl. reflexivity. Qed.\n\n    (*factorial*)\n    Fixpoint 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    Fixpoint add (n m:nat): nat :=\n        match n with \n        |0=>m\n        |S n=> S (add n m)\n        end.\n    Example testadd: add 2 3 = 5.\n    Proof. simpl. reflexivity. Qed.\n    \n    Fixpoint mult (n m:nat) :nat :=\n        match n with \n        |0 =>0\n        |S n=>add m (mult n m)\n        end.\n    Example testmult: mult 2 3 = 6.\n    Proof. simpl. reflexivity. Qed.\n\n    Fixpoint minus (n m :nat):nat:=\n        match n,m with \n        |0 ,_ =>0\n        |_ ,0 =>n\n        |S n ,S m =>minus n m\n        end.\n    Example testminus : minus 2 3 =0. \n    Proof. simpl. reflexivity. Qed.\n    \n    Fixpoint factorial (n:nat):nat :=\n        match n with \n        |0 =>1\n        |S n' => (S n')*(factorial n')\n        end.\n    Example test_factorial1: (factorial 3) = 6.\n    Proof. simpl. reflexivity. Qed.\n    Example test_factorial2: (factorial 5) = (mult 10 12).\n    Proof. simpl. reflexivity. Qed.\n\n    Notation \"x + y\" := (add 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    (*ltb*)\n    Fixpoint eqb (n m : nat) : bool :=\n        match n with\n        | 0=> match m with\n            | 0 => true\n            | S m' => false\n            end\n        | S n' => match m with\n            | 0 => false\n            | S m' => eqb n' m'\n            end\n    end.\n    Fixpoint leb (n m : nat) : bool :=\n        match n with\n        | 0 =>true\n        | S n' =>\n            match m with\n            | 0 => false\n            | S m' => leb n' m'\n            end\n        end.\n    Example test_leb1: leb 2 2 = true.\n    Proof. simpl. reflexivity. Qed.\n    Example test_leb2: leb 2 4 = true.\n    Proof. simpl. reflexivity. Qed.\n    Example test_leb3: leb 4 2 = false.\n    Proof. simpl. reflexivity. Qed.\n    Notation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\n    Notation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n    Example test_leb3': (4 <=? 2) = false.\n    Proof. simpl. reflexivity. Qed.\n\n    Definition ltb (n m:nat):bool := \n        match m with \n        |0=>false\n        |S m' => (n<=?m')\n        end.    \n    Notation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n    Example test_ltb1: (ltb 2 2) = false.\n    Proof. simpl. reflexivity. Qed.\n    Example test_ltb2: (ltb 2 4) = true.\n    Proof. simpl. reflexivity. Qed.\n    Example test_ltb3: (ltb 4 2) = false.\n    Proof. simpl. reflexivity. Qed.\n    \n    Theorem add_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.\n    Qed.\n\n    Theorem add_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        intros J.\n        rewrite->H.\n        rewrite<-J.\n        reflexivity.\n    Qed.\n    \n    Theorem mult_n_1: forall p:nat,\n    p * 1 = p .\n    Proof.\n        intros p.\n        rewrite<-mult_n_Sm.\n        rewrite<-mult_n_O.\n        reflexivity.\n    Qed.\n    \n    Theorem plus_1_neq_0 : forall n : nat,\n    (n + 1) =? 0 = false.\n    Proof.\n        intros n. destruct n as [| n'] eqn:E.\n        - reflexivity.\n        - reflexivity. \n    Qed.\n\n    Theorem andb3_exchange :\n        forall b c d, andb (andb b c) d = andb (andb b d) c.\n    Proof.\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. }\n    Qed.\n\n    Theorem andb_true_elim2:forall b c:bool,\n    andb b c = true -> c = true .\n    Proof.\n        intros b c H.\n        destruct c eqn:EC.\n        - reflexivity.\n        - rewrite<-H. destruct b eqn:EB.\n            -- reflexivity.\n            -- reflexivity.        \n    Qed.\n    \n    Theorem zero_nbeq_plus_1: forall n:nat,\n    0 =? (n+1) = false.\n    Proof.\n        intros n. destruct n.\n        - reflexivity.\n        - reflexivity.\n    Qed.\n    \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 H J.\n        destruct b eqn:EB. \n        - rewrite->J.  rewrite->J. reflexivity.\n        - rewrite->J.  rewrite->J. reflexivity.\n    Qed.\n    \n    Theorem negb_involutive:forall b:bool,\n    negb (negb b) = b .\n    Proof.\n        intros b. destruct b eqn:E.\n        - reflexivity.\n        -reflexivity.\n    Qed.\n    \n\n    Theorem negation_fn_applied_twice: \n    forall (f:bool->bool),\n    (forall (x:bool),f x = neg x)->\n    forall (b:bool), f (f b) = b.\n    Proof.\n        intros H J.\n        destruct b eqn:EB.\n        - rewrite->J.  rewrite->J. reflexivity.\n        - rewrite->J.  rewrite->J. reflexivity.\n    Qed.\n\n    Theorem andb_eq_orb :\n    forall (b c : bool),\n    (andb b c = orb b c) -> b = c.\n    Proof.\n        intros b c. destruct b eqn:EB.\n        - simpl. intros H. rewrite<-H. reflexivity. \n        - simpl. intros H. rewrite->H. reflexivity.\n    Qed.\n\n    Inductive bin: Type:=\n    | Z\n    | B0 (n:bin)\n    | B1 (n:bin).\n\n    Fixpoint 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\n    Fixpoint bin_to_nat (m :bin) :nat :=\n        match m with \n        | Z=>O\n        | B0 n => (bin_to_nat n) + (bin_to_nat n)\n        | B1 n => S ((bin_to_nat n) + (bin_to_nat n))\n    end.\n    \n    Example test_bin_incr1 : (incr (B1 Z)) = B0 (B1 Z).\n    Proof. simpl. reflexivity. Qed.\n    Example test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\n    Proof. simpl. reflexivity. Qed.\n    Example test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\n    Proof. simpl. reflexivity. Qed.\n    Example test_bin_incr4 : bin_to_nat (B0 (B1 Z)) = 2.\n    Proof. simpl. reflexivity. Qed.\n    Example test_bin_incr5 :\n            bin_to_nat (incr (B1 Z)) = 1 + bin_to_nat (B1 Z).\n    Proof. simpl. reflexivity. Qed.\n    Example test_bin_incr6 :\n            bin_to_nat (incr (incr (B1 Z))) = 2 + bin_to_nat (B1 Z).\n    Proof. simpl. reflexivity. Qed.\n\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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7467687075335875}}
{"text": "Require Import Arith Omega Reals.\n\n(* The standard recursive definition of the Fibonacci numbers *)\n\nOpen Scope nat_scope.\n\nFixpoint fib n := \n  match n with\n    0 => 0\n  | (S n) => (* this nested match trick helps coq prove n and m are decreasing [1] *)\n      match n with\n        0 => 1\n      | (S m) => fib n + fib m\n      end\n  end.\n\n(* F_{n+2} = F_{n+1} + F_n *)\nLemma fib_rec : forall n, fib (S (S n)) = fib n + fib (S n).\ninduction n.\ntrivial.\nsimpl.\nomega.\nQed.\n\nClose Scope nat_scope.\n\n(* Closed-form definition of the Fibonacci numbers using the golden ratio (phi) [2] *)\n\nOpen Scope R_scope.\n\nDefinition phi  := (1 + sqrt 5)/2.\nDefinition phi' := (1 - sqrt 5)/2.\n\nDefinition F n := (phi ^ n - phi' ^ n)/(sqrt 5).\n\n(* Next we prove some handy results about phi and phi' *)\n\n(* This is only used to prove sqrt 5 <> 0 but it's handy to have around i suppose [2] *)\nLemma sqrt_pos_neq_0 : forall n, 0 < n -> sqrt n <> 0.\nintros n Hgt.\ngeneralize (Rlt_le 0 n Hgt).\nintro Hge.\nred.\nintro Hs_eq_z.\ngeneralize sqrt_eq_0 n Hge Hs_eq_z.\nintro H.\nabsurd (n = 0).\nauto with *.\napply H; assumption.\nQed.\n\nLemma sqrt5_neq_0 : sqrt 5 <> 0.\napply sqrt_pos_neq_0.\nprove_sup0. (* proves 0 < 5 *)\nQed.\n\n(* Split this out to shorten later proofs [3] *)\nLemma pow2_sqrt : forall n, 0 <= n -> sqrt n ^ 2 = n.\nintros n Hle.\nsimpl.\nreplace (sqrt n * (sqrt n * 1)) with (sqrt n * sqrt n) by field. (* 'by field' means 'do basic algebra please' *)\nrewrite sqrt_def by (exact Hle). (* sqrt n * sqrt n -> n *)\nreflexivity.\nQed.\n\n\n(* Now: proofs that phi and phi' are the roots of x^2 = x + 1 (CLRS 3.2-6) *)\n\nLemma phi_root : phi ^ 2 = phi + 1.\nunfold phi.\nreplace (((1 + sqrt 5) / 2) ^ 2) with ((1 + 2 * sqrt 5 + sqrt 5 ^ 2) / 4) by field.\nrewrite pow2_sqrt by (unfold Rle; left; prove_sup0). (* sqrt 5 ^ 2 -> 5; 'by ...' proves 0 <= 5 *)\nfield.\nQed.\n\nLemma phi'_root : phi' ^ 2 = phi' + 1.\nunfold phi'.\nreplace (((1 - sqrt 5) / 2) ^ 2) with ((1 - 2 * sqrt 5 + sqrt 5 ^ 2) / 4) by field.\nrewrite pow2_sqrt by (unfold Rle; left; prove_sup0).\nfield.\nQed.\n\n(* Slightly generalize the above results for higher powers *)\nLemma phi_root_n : forall n, (phi ^ S (S n)) = (phi ^ n + phi ^ (S n)).\nintro.\nreplace  (phi ^ S (S n)) with ((phi ^ 2) * (phi ^ n)) by (simpl; field). (* field can't do powers, so simplify those to multiplication first *)\nrewrite phi_root.\nsimpl.\nfield.\nQed.\n\nLemma phi'_root_n : forall n, (phi' ^ S (S n)) = (phi' ^ n + phi' ^ (S n)).\nintro.\nreplace  (phi' ^ S (S n)) with ((phi' ^ 2) * (phi' ^ n)) by (simpl; field).\nrewrite phi'_root.\nsimpl.\nfield.\nQed.\n\n(* The main result! (CLRS 3.2-7) *)\n\n(* If we attempt to prove F n = fib n by induction on n, we run into trouble because the inductive step\n   needs access to the /two/ 'rungs' before it. You can't generally do that -- i think it could allow\n   you to make use of an unbounded number of previous 'rungs', which could lead to unsoundness. All you\n   get is the 'rung' before. That is, to prove F (n + 1) = fib (n + 1), we need to know F n = fib n AND\n   F (n - 1) = fib (n - 1), but we only get F n = fib n. :(\n\n   So, instead, here's an odd proof technique that gives us access to more than one 'rung' at a time:\n   Prove something stronger: /two steps/ at once, giving us access to the previous two 'rungs' simultaneously!\n   It's just like the usual 'climbing a ladder' analogy, but you have three legs instead of two.\n\n   Technically this is stronger, but practically it is not any more difficult to do.\n   The inductive step now gives us two hypotheses:\n     IHn : F n = fib n\n     IHSn : F (n + 1) = fib (n + 1)\n   and two goals:\n     1: F (n + 1) = fib (n + 1)\n     2: F (n + 2) = fib (n + 2)\n   The 'extra' goal (goal 1) that this technique adds is exactly one of the induction hypotheses!\n   Finally, goal 2 is where the \"actual\" proof happens: algebra it into F (n + 1) + F n = fib (n + 1) + fib n,\n   then use the inductive hypotheses to prove the equality.\n*)\n(* Note: INR ('inject nat to real') converts natural numbers (the realm of fib) to reals (the realm of F) [4] *)\nLemma F_eq_fib' : forall n, F n = INR (fib n) /\\ F (S n) = INR (fib (S n)).\ninduction n.\n+ (* base case: split it up and do the arithmetic *)\n  unfold F; unfold phi; unfold phi'.\n  split; simpl; field; apply sqrt5_neq_0.\n+ (* inductive case *)\n  destruct IHn as [IHn IHSn]. (* make that inductive hypothesis more presentable *)\n  split. (* split the goal into two, just like solomon would have wanted *)\n  exact IHSn. (* goal 1: easy peasy; already done it! *)\n  unfold F in *. (* goal 2: actually requires some thinking *)\n  rewrite phi_root_n. (* Use phi^2 = phi + 1 to make enough phi terms for F n and F (n + 1) *)\n  rewrite phi'_root_n.\n  replace ((phi ^ n + phi ^ S n - (phi' ^ n + phi' ^ S n)) / sqrt 5)\n    with (((phi ^ n - phi' ^ n) / sqrt 5) + ((phi ^ S n - phi' ^ S n) / sqrt 5))\n    by (simpl; field; apply sqrt5_neq_0).\n    (* algebra ain't hard when you got a, uh, piece of scratch paper and a computer to check it! *)\n  rewrite IHn. (* ahh, the refreshing taste of induction *)\n  rewrite IHSn.\n  rewrite <- plus_INR. (* INR (fib n) + INR (fib (n + 1)) -> INR (fib n + fib (n + 1)) *)\n  rewrite fib_rec. (* fib (n + 2) -> fib n + fib (n + 1) *)\n  trivial.\nQed.\n\n(* The actual result we were after follows directly from the more complex result. *)\nLemma F_eq_fib : forall n, F n = INR (fib n).\napply F_eq_fib'.\nQed.\n\n(* and that's all, folks! *)\n\n(* Foontotes:\n [1]: I learned this trick from https://www.irif.fr/~letouzey/hofstadter_g/doc/Fib.html\n [2]: This proof generalized from the proof of sqrt2_neq_0 from the Rtrigo_calc library; see\n      https://www.cs.princeton.edu/courses/archive/fall07/cos595/stdlib/html/Coq.Reals.Rtrigo_calc.html#sqrt2_neq_0\n [3]: They give us sqrt_pow2: forall x : R, 0 <= x -> sqrt (x ^ 2) = x but not the other way around!\n [4]: Defined in Raxioms: https://coq.inria.fr/distrib/8.4pl6/stdlib/Coq.Reals.Raxioms.html#INR\n      but see Rineq (???) for handy theorems: https://coq.inria.fr/library/Coq.Reals.RIneq.html#lab145\n*)\n\n", "meta": {"author": "LinuxMercedes", "repo": "miscellany", "sha": "08826b26a1d6f7fb5c06e6c2cf98844b96dd6e30", "save_path": "github-repos/coq/LinuxMercedes-miscellany", "path": "github-repos/coq/LinuxMercedes-miscellany/miscellany-08826b26a1d6f7fb5c06e6c2cf98844b96dd6e30/theorems/fibonacci-and-golden-ratio.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7467639862154041}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqExt. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Extension for permutation, especially for computable permutation.\n  author    : ZhengPu Shi\n  date      : 2022.06\n  \n  remark    :\n  1. compute permutation of a list, such as \n     perm [a;b;c] => [[a;b;c]; [a;c;b]; [b;a;c]; [b;c;a]; [c;a;b]; [c;b;a]]\n     perm [1;2;3] => [[1;2;3]; [1;3;2]; [2;1;3]; [2;3;1]; [3;1;2]; [3;2;1]]\n *)\n\nRequire Import SetoidListExt.\nRequire Import SafeNatFun.Vector.\n\n\n(* ######################################################################### *)\n(** * reverse-order-number of a list *)\nSection ronum.\n\n  Context {A : Type}.\n  Context {Altb : A -> A -> bool}.\n  Infix \"<?\" := Altb.\n  (* Context {Alt : A -> A -> Prop}. *)\n  (* Context {Alt_dec : Decidable Alt}. *)\n\n  Definition ronum1 (a : A) (l : list A) : nat :=\n    fold_left (fun (n : nat) (b : A) => n + (if b <? a then 1 else 0)) l 0.\n  \n  Fixpoint ronum (l : list A) : nat :=\n    match l with\n    | [] => 0\n    | x :: l' => ronum1 x l' + ronum l'\n    end.\n\n  (** ** parity of a list *)\n  Section parity.\n\n    (** Give speciall name for parity *)\n    Definition Parity := bool.\n    Definition POdd := true.\n    Definition PEven := false.\n\n    (** Calulate parity of a list *)\n    Definition perm_parity (l : list A) : Parity := odd (ronum l).\n    \n    (** Is two list have different parity? *)\n    Definition perm_parity_diff (l1 l2 : list A) : Prop :=\n      let p1 := perm_parity l1 in\n      let p2 := perm_parity l2 in\n      p1 = (negb p2).\n    \n  End parity.\n\nEnd ronum.\n\n(* Compute ronum (Altb:=Nat.ltb) [2;4;3;1]. *)\n(* Compute ronum (Altb:=Nat.ltb) [2;1;3;4]. *)\n\n\n(* ######################################################################### *)\n(** * Permutation of a list *)\nModule Perm_with_list.\n\n  (** ** Permutation of a list of n elements *)\n  Section perm.\n    Context {A : Type} {A0 : A}.\n\n    (** Get k-th element and remaining elements from a list *)\n    Fixpoint pick (l : list A) (k : nat) : A * list A :=\n      match k with\n      | 0 => (hd A0 l, tl l)\n      | S k' =>\n          match l with\n          | [] => (A0, [])\n          | x :: l' =>\n              let (a,l0) := pick l' k' in\n              (a, [x] ++ l0)\n          end\n      end.\n\n    Section test.\n      Variable a b c : A.\n      Let l := [a;b;c].\n      (* Compute pick l 0.     (* = (a, [b; c]) *) *)\n      (* Compute pick l 1.     (* = (b, [a; c]) *) *)\n      (* Compute pick l 2.     (* = (c, [a; b]) *) *)\n      (* Compute pick l 3.     (* = (A0, [a; b; c]) *) *)\n    End test.\n\n    (** Get permutation of a list with a special level number *)\n    Fixpoint perm_aux (n : nat) (l : list A) : list (list A) :=\n      match n with\n      | 0 => [[]]\n      | S n' =>\n          let d1 := map (fun i => pick l i) (seq 0 n) in\n          let d2 :=\n            map (fun k : A * list A =>\n                   let (x, lx) := k in\n                   let d3 := perm_aux n' lx in\n                   map (fun l1 => [x] ++ l1) d3) d1 in\n          concat d2\n      end.\n\n    Section test.\n      Variable a b c : A.\n      Let l := [a;b;c].\n      (* Compute perm_aux 0 l.     (* = [[]] *) *)\n      (* Compute perm_aux 1 l.     (* = [[a]] *) *)\n      (* Compute perm_aux 2 l.     (* = [[a; b]; [b; a]] *) *)\n    (* Compute perm_aux 3 l.     (* = [[a; b; c]; [a; c; b]; [b; a; c]; [b; c; a];  *)\n     (*                              [c; a; b]; [c; b; a]] *) *)\n    End test.\n\n    (** Get permutation of a list *)\n    Definition perm (l : list A) : list (list A) := perm_aux (length l) l.\n\n    Section test.\n      Variable a b c : A.\n      (* Compute perm [a;b;c]. *)\n      (* = [[a; b; c]; [a; c; b]; [b; a; c]; [b; c; a]; [c; a; b]; [c; b; a]] *)\n    End test.\n\n    (** Length of permutation *)\n    Definition Pn (l : list A) := length (perm l).\n\n    (** Pn of cons. \n      Example: Pn [a;b;c;d] = 4 * Pn [a;b;c] *)\n    Lemma Pn_cons : forall (a : A) (l : list A), Pn (a :: l) = (length (a :: l)) * (Pn l).\n    Proof.\n      intros. simpl. unfold Pn.\n      unfold perm. simpl. rewrite app_length. rewrite map_length. f_equal.\n      rewrite List.map_map.\n      rewrite concat_length.\n      rewrite List.map_map.\n    Admitted.\n\n    (** Length of permutation equal to the factorial of the length *)\n    Lemma Pn_eq : forall l, Pn l = fact (length l).\n    Proof.\n      induction l; simpl; auto.\n      rewrite Pn_cons. rewrite IHl. simpl. auto.\n    Qed.\n\n    (** The inverse number of a permutation *)\n    (* Definition inv_no             (*  *) *)\n\n  End perm.\n\n  (* Compute perm [1;2]. *)\n  (* Compute perm [1;2;3]. *)\n  (* Compute perm [1;2;3;4]. *)\nEnd Perm_with_list.\n\n\n(* ######################################################################### *)\n(** * Permutation of a vector *)\nModule Perm_with_vector.\n\n  Context {A : Type} {A0 : A}.\n  Context {Altb : A -> A -> bool}.\n  Infix \"!\" := (vnth (A0:=A0)) : vec_scope.\n  \n  (** ** Permutation of a list of n elements *)\n  Section perm.\n    \n    (** Get k-th element and remaining elements from a vector *)\n    Definition pick {n : nat} (v : @vec A (S n)) (k : nat) : A * (vec n) :=\n      (v ! k, vremove (A0:=A0) v k).\n\n    Section test.\n      Variable a0 a b c : A.\n      Let l := l2v a0 3 [a;b;c].\n      (* Compute pick l 0.     (* = (a, [b; c]) *) *)\n      (* Compute pick l 1.     (* = (b, [a; c]) *) *)\n      (* Compute pick l 2.     (* = (c, [a; b]) *) *)\n      (* Compute pick l 3.     (* = (A0, [a; b; c]) *) *)\n      (* Compute v2l (vremove l 4). *)\n    End test.\n\n    (** Get permutation of a vector *)\n    Fixpoint perm {n : nat} : @vec A n -> list (@vec A n) :=\n      match n with\n      | 0 => fun _ => [vec0 (A0:=A0)]\n      | S n' => fun (v : vec (S n')) =>\n          let d1 := map (fun i => pick v i) (seq 0 n) in\n          let d2 :=\n            map (fun k : A * @vec A n' =>\n                   let (x, v') := k in\n                   let d3 := perm v' in\n                   map (fun v0 => vcons (A0:=A0) x v') d3) d1 in\n          concat d2\n      end.\n\n    Section test.\n      Variable a0 a b c : A.\n      (* Compute vl2dl (perm (l2v a0 0 [])). *)\n      (* Compute vl2dl (perm (l2v a0 1 [a])). *)\n      (* Compute vl2dl (perm (l2v a0 2 [a;b])). *)\n      (* Compute vl2dl (perm (l2v a0 3 [a;b;c])). *)\n      (* = [[a; b; c]; [a; b; c]; [b; a; c]; [b; a; c]; [c; a; b]; [c; a; b]] *)\n    End test.\n\n    (** Length of permutation *)\n    Definition Pn {n} (v : @vec A n) := length (perm v).\n\n    (** Pn of cons. \n      Example: Pn [a;b;c;d] = 4 * Pn [a;b;c] *)\n    (* Lemma Pn_cons : forall {n} (a : A) (v : @vec A n), Pn (a :: v) = (length (a :: l)) * (Pn l). *)\n    (* Proof. *)\n    (*   intros. simpl. unfold Pn. *)\n    (*   unfold perm. simpl. rewrite app_length. rewrite map_length. f_equal. *)\n    (*   rewrite List.map_map. *)\n    (*   rewrite concat_length. *)\n    (*   rewrite List.map_map. *)\n    (* Admitted. *)\n\n    (** Length of permutation equal to the factorial of the length *)\n    Lemma Pn_eq : forall n (v : @vec A n), Pn v = fact n.\n    Proof.\n    (*   induction l; simpl; auto. *)\n    (*   rewrite Pn_cons. rewrite IHl. simpl. auto. *)\n      (* Qed. *)\n      Abort.\n\n    (** The inverse number of a permutation *)\n    (* Definition inv_no             (*  *) *)\n\n  End perm.\n\n  (* Compute vl2dl (perm (l2v 0 2 [1;2])). *)\n  (* Compute vl2dl (perm (l2v 0 3 [1;2;3])). *)\n  (* Compute vl2dl (perm (l2v 0 4 [1;2;3;4])). *)\n\n  (** ** parity of a vector *)\n  Definition perm_parity {n} (v : @vec A n) : Parity :=\n    perm_parity (Altb:=Altb) (v2l v).\n  Definition perm_parity_diff {n} (v1 v2 : @vec A n) : Prop :=\n    perm_parity_diff (Altb:=Altb) (v2l v1) (v2l v2).\n  \n  (** ** transposition, exchange, swap 对换 *)\n  Section exchange.\n    \n    Definition vexchg {n} (v : @vec A n) (i0 i1 : nat) : @vec A n :=\n      mk_vec (A0:=A0) (fun i =>\n                if i =? i0\n                then v!i1\n                else (if i =? i1 then v!i0 else v!i)).\n\n    (** 对换相邻位置改变排列的奇偶性 *)\n    Theorem vexchg_swap2close_parity : forall {n} (v : @vec A n) i0 i1,\n        i0 < n -> i1 < n -> (i0 = S i1 \\/ i1 = S i0) ->\n        perm_parity_diff v (vexchg v i0 i1).\n    Proof.\n      (* 教科书上的证明很巧妙，难以形式化的描述出来 *)\n      intros. unfold vexchg, perm_parity_diff.\n      unfold PermutationExt.perm_parity_diff, PermutationExt.perm_parity.\n      unfold vnth,mnth. solve_mnth; try lia.\n      clear l0 l l1.\n      unfold vec in *. mat_to_fun. simpl. unfold v2l. simpl.\n      (* key part *)\n      destruct H1; subst.\n      - rename i1 into j.\n        revert v j H H0. induction n; try easy.\n        intros. simpl.\n        rewrite <- ?seq_shift. rewrite ?map_map.\n        destruct j.\n        + simpl.\n          rewrite Nat.odd_add.\n    Abort.\n    \n    (** 对换改变排列的奇偶性 *)\n    Theorem vexchg_swap2_parity : forall {n} (v : @vec A n),\n        (forall i0 i1, i0 < n -> i1 < n -> i0 <> i1 -> perm_parity_diff v (vexchg v i0 i1)).\n    Proof.\n      (* 教科书上的证明很巧妙，难以形式化的描述出来 *)\n      Admitted.\n      \n  End exchange.\n\n  (* Let v := l2v 0 3 [1;2;3]. *)\n  (* Compute v2l (vexchg v 0 1). *)\n  (* Compute v2l (vexchg v 0 2). *)\n\n  (** ** odd/even permutation *)\n  Section odd_even.\n    Context {A : Type}.\n    Context {Altb : A -> A -> bool}.\n\n    Definition odd_perm (l : list A) : bool := odd (ronum (Altb:=Altb) l).\n    Definition even_perm (l : list A) : bool := even (ronum (Altb:=Altb) l).\n  End odd_even.\n\n  (** ** transposition, exchange, swap *)\n  Section exchange.\n    \n\n  End exchange.\nEnd Perm_with_vector.\n\n\n(* ######################################################################### *)\n(** * Determinant *)\n\n", "meta": {"author": "zhengpushi", "repo": "CoqMatrix", "sha": "28fa5f96e38a07659cfd373e09b0e75c24c22bfd", "save_path": "github-repos/coq/zhengpushi-CoqMatrix", "path": "github-repos/coq/zhengpushi-CoqMatrix/CoqMatrix-28fa5f96e38a07659cfd373e09b0e75c24c22bfd/CoqMatrix/LinearAlgebra/PermutationExt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7467639847349653}}
{"text": "Require Import List.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nSection tree.\n  (* The tree is parametrized on the type of data stored at the leaves. *)\n  Variable A : Type.\n\n  (* Each node of the tree contains a list of subtrees.\n     Coq does not generate a useful induction scheme for such types,\n     so we just tell it not to generate anything, and we'll write our own. *)\n  Local Unset Elimination Schemes.\n\n  Inductive tree : Type :=\n  | atom : A -> tree\n  | node : list tree -> tree\n  .\n\n  (* Here is an actually useful recursion principle for tree,\n     which requires an additional motive P_list. *)\n  Section tree_rect.\n    Variable P : tree -> Type.\n    Variable P_list : list tree -> Type.\n    Hypothesis P_nil : P_list [].\n    Hypothesis P_cons : forall t l, P t -> P_list l -> P_list (t :: l).\n    Hypothesis P_atom : forall a, P (atom a).\n    Hypothesis P_node : forall l, P_list l -> P (node l).\n\n    Fixpoint tree_rect (t : tree) : P t :=\n      let fix go_list (l : list tree) : P_list l :=\n          match l with\n          | [] => P_nil\n          | t :: l => P_cons (tree_rect t) (go_list l)\n          end\n      in\n      match t with\n      | atom a => P_atom a\n      | node l => P_node (go_list l)\n      end.\n  End tree_rect.\n\n  (* Setting P_list := List.Forall P is a reasonable default. *)\n  Section tree_ind.\n    Variable P : tree -> Prop.\n\n    Hypothesis P_atom : forall a, P (atom a).\n    Hypothesis P_node : forall l, List.Forall P l -> P (node l).\n\n    Definition tree_ind (t : tree) : P t :=\n      tree_rect P (List.Forall P)\n                (List.Forall_nil _)\n                (fun t l Pt Pl => List.Forall_cons _ Pt Pl) P_atom P_node t.\n  End tree_ind.\n\n  Variable A_eq_dec : forall a1 a2 : A, {a1 = a2} + {a1 <> a2}.\n\n  Fixpoint tree_eq_dec (t1 t2 : tree) : {t1 = t2} + {t1 <> t2}.\n    unshelve refine (\n    let fix go_list (l1 l2 : list tree) : {l1 = l2} + {l1 <> l2}  :=\n        match l1 with\n        | [] =>\n          match l2 with\n          | [] => left eq_refl\n          | _ => right _\n          end\n        | t1 :: l1 =>\n          match l2 with\n          | [] => right _\n          | t2 :: l2 =>\n            match tree_eq_dec t1 t2 with\n            | left _ =>\n              match go_list l1 l2 with\n              | left _ => left _\n              | right _ => right _\n              end\n            | right _ => right _\n            end\n          end\n        end\n    in\n    match t1 with\n    | atom a1 =>\n      match t2 with\n      | atom a2 =>\n        match A_eq_dec a1 a2 with\n        | left _ => left _\n        | right _ => right _\n        end\n      | _ => right _\n      end\n    | node l1 =>\n      match t2 with\n      | atom a2 => right _\n      | node l2 =>\n        match go_list l1 l2 with\n        | left _ => left _\n        | right _ => right _\n        end\n      end\n    end); congruence.\n  Defined.\n\n  Definition get_atom (t : tree) : option A :=\n    match t with\n    | atom a => Some a\n    | _ => None\n    end.\nEnd tree.\n\nSection Forall.\n  Variable A : Type.\n  Variable P : A -> Prop.\n\n  Inductive Forall : tree A -> Prop :=\n  | Forall_atom : forall a, P a -> Forall (atom a)\n  | Forall_node : forall l, List.Forall Forall l -> Forall (node l)\n  .\nEnd Forall.\nHint Resolve Forall_atom Forall_node.", "meta": {"author": "wilcoxjay", "repo": "PrettyParsing", "sha": "189a262538d6c47358940b0dd43f60463e1abc3c", "save_path": "github-repos/coq/wilcoxjay-PrettyParsing", "path": "github-repos/coq/wilcoxjay-PrettyParsing/PrettyParsing-189a262538d6c47358940b0dd43f60463e1abc3c/Tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7467639845110394}}
{"text": "Require Export state. \nImport StateNotations.\nRequire Export aexp.\n\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Arith.EqNat. Import Nat.\n\nInductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2 : aexp)\n  | BLe (a1 a2 : aexp)\n  | BNot (b : bexp)\n  | BAnd (b1 b2 : bexp).\n\nFixpoint beval (st : state) (b : bexp) {struct b} : bool :=\nmatch b with\n| BTrue => true\n| BFalse => false\n| BEq a1 a2 => (aeval st a1) =? (aeval st a2)\n| BLe a1 a2 => (aeval st a1) <=? (aeval st a2)\n| BNot b1 => negb (beval st b1)\n| BAnd b1 b2 => andb (beval st b1) (beval st b2)\nend.\n  \nExample bexp1 :\n    beval (\"x\" !-> 5) (BAnd BTrue (BNot (BLe (AId \"x\") (ANum 4)))) = true.\nProof. \n  reflexivity.\nQed.\n\nInductive bevalR : state -> bexp -> bool -> Prop :=\n  | E_BTrue (st: state) :\n      bevalR st BTrue true\n  | E_BFalse (st: state) :\n      bevalR st BFalse false\n  | E_BEq (st: state) (e1 e2: aexp) (n1 n2 : nat) \n      (H1: aevalR st e1 n1)\n      (H2: aevalR st e2 n2) :\n      bevalR st (BEq e1 e2) (n1 =? n2)\n  | E_BLe (st: state) (e1 e2: aexp) (n1 n2 : nat) \n    (H1: aevalR st e1 n1)\n    (H2: aevalR st e2 n2) :\n    bevalR st (BLe e1 e2) (n1 <=? n2)\n  | E_BNot (st: state) (e: bexp) (b: bool)\n    (H1: bevalR st e b) :\n    bevalR st (BNot e) (negb b)\n  | E_BAnd (st: state) (e1 e2: bexp) (b1 b2 : bool) \n    (H1: bevalR st e1 b1)\n    (H2: bevalR st e2 b2) :\n    bevalR st (BAnd e1 e2) (andb b1 b2).\n\nTheorem beval_iff_bevalR : forall e b st,\n  bevalR st e b <-> beval st e = b.\nProof.\n  intros; split.\n\n  - intros; induction H.\n    1, 2: reflexivity.\n    3, 4: subst; reflexivity.\n    all: unfold beval.\n    all: \n      apply (aeval_iff_aevalR e1 n1) in H1;\n      apply (aeval_iff_aevalR e2 n2) in H2.\n    all: induction H1; induction H2; reflexivity.\n  \n  - generalize dependent b.\n    induction e; simpl; intros; subst. \n    1, 2: constructor.\n    1, 2: constructor; apply aeval_iff_aevalR; reflexivity.\n    1: constructor. apply IHe. reflexivity. \n    1: constructor.\n    apply IHe1. reflexivity.\n    apply IHe2. reflexivity.\nQed.\n\nTheorem bev_not_true_iff_false: forall b st,\n  beval st b = false <-> beval st (BNot b) = true.\nProof.\n  intros. split; intros.\n  - unfold beval.\n    apply negb_true_iff.\n    exact H.\n  - unfold beval.\n    apply negb_true_iff.\n    exact H.\nQed.\n    \nLemma bev_negb_involutive : forall b st,\n  beval st (BNot (BNot b)) = beval st b.\nProof.\n  intros.\n  unfold beval.\n  apply negb_involutive.\nQed.\n\nDefinition bequiv (b1 b2 : bexp) : Prop :=\n  forall (st : state),\n    beval st b1 = beval st b2.", "meta": {"author": "remind-me-later", "repo": "Semantics", "sha": "cc760c43ccb98b92704dc06a189cbf544374d1d6", "save_path": "github-repos/coq/remind-me-later-Semantics", "path": "github-repos/coq/remind-me-later-Semantics/Semantics-cc760c43ccb98b92704dc06a189cbf544374d1d6/bexp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7467639748695866}}
{"text": "Set Implicit Arguments. (* Allows us to use inference for dependent arguments *)\n\nRequire Import Reals.   (* Imports real arithmetic. *)\nNotation Real := R.        (* Notice: due to the absence of overloading, all       *)\nDelimit Scope R_scope   (* numerical constants and operators are nat-typed,     *)\n  with Real.               (* unless stated otherwise via the scope delimiter '%'. *)\n\nCheck 3 + 4.            (* : ℕ  (nat)  *)\nCheck (3 + 4) % Real.      (* : ℝ  (Real) *)\n\n\nInductive Vec : nat -> Set :=\n  VNil : Vec 0\n| VCons : forall n, Real -> Vec n -> Vec (S n).\n\n(* Some syntactic sugar *)\nNotation \"<< x , .. , y >>\" := (VCons x .. (VCons y VNil) .. ).\n\nCheck << 5, 9, 6 >> .\n\n\n\n\n\n\n(* For Q3 + Q4 *)\n\nFixpoint Vec' n : Set :=\n  match n with\n    0 => unit\n  | S k => Real * Vec' k\n  end.\n", "meta": {"author": "corwin-of-amber", "repo": "various-proofs", "sha": "e7c19549f1d573487f9fb3ebd5d6b80b2c52184b", "save_path": "github-repos/coq/corwin-of-amber-various-proofs", "path": "github-repos/coq/corwin-of-amber-various-proofs/various-proofs-e7c19549f1d573487f9fb3ebd5d6b80b2c52184b/ssar-class/vecn_ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7467639718216665}}
{"text": "(****************************************************************)\n(****************************************************************)\n(****                                                        ****)\n(****   The data needed for the Kleene fixed-point theorem   ****)\n(****                                                        ****)\n(****************************************************************)\n(****************************************************************)\n\nModule Type KleeneData.\n  (*\n    Assumption: Let (`T`, `leq`) be a partially ordered set, or poset. A poset\n    is a set with a binary relation that is reflexive, transitive, and\n    antisymmetric.\n  *)\n\n  Parameter T : Type.\n  Parameter leq : T -> T -> Prop.\n\n  Axiom reflexivity : forall x, leq x x.\n  Axiom transitivity : forall x y z, leq x y -> leq y z -> leq x z.\n  Axiom antisymmetry : forall x y, leq x y -> leq y x -> x = y.\n\n  #[export] Hint Resolve reflexivity : main.\n  #[export] Hint Resolve transitivity : main.\n  #[export] Hint Resolve antisymmetry: main.\n  #[export] Hint Rewrite antisymmetry: main.\n\n  (*\n    A supremum of a subset of `T` is a least element of `T` which is greater\n    than or equal to every element in the subset. This is also called a join or\n    least upper bound.\n  *)\n\n  Definition supremum P x1 :=\n    (forall x2, P x2 -> leq x2 x1) /\\\n    forall x3, (forall x2, P x2 -> leq x2 x3) -> leq x1 x3.\n\n  #[export] Hint Unfold supremum : main.\n\n  (*\n    A directed subset of `T` is a non-empty subset of `T` such that any two\n    elements in the subset have an upper bound in the subset.\n  *)\n\n  Definition directed P :=\n    (exists x1, P x1) /\\\n    forall x1 x2, P x1 -> P x2 -> exists x3, leq x1 x3 /\\ leq x2 x3 /\\ P x3.\n\n  #[export] Hint Unfold directed : main.\n\n  (*\n    Assumption: Let the partial order be directed-complete. That means every\n    directed subset has a supremum.\n  *)\n\n  Axiom directedComplete :\n    forall P,\n    directed P ->\n    exists x, supremum P x.\n\n  #[export] Hint Resolve directedComplete : main.\n\n  (*\n    Assumption: Let `T` have a least element called bottom. This makes our\n    partial order a pointed directed-complete partial order.\n  *)\n\n  Parameter bottom : T.\n\n  Axiom bottomLeast : forall x, leq bottom x.\n\n  #[export] Hint Resolve bottomLeast : main.\nEnd KleeneData.\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/Kleene/KleeneData.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942093072239, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.746763968636863}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (z : natural) (x : natural) : natural :=\n  plus lf2 (mult z x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj192_coqofml_hfdlGu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7466025862167815}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq fintype.\n\nSection SeqSet.\n\n  (* Let T be any type with decidable equality. *)\n  Context {T: eqType}.\n\n  (* We define a set as a sequence that has no duplicates. *)\n  Record set :=\n  {\n    _set_seq :> seq T ;\n    _ : uniq _set_seq (* no duplicates *)\n  }.\n\n  (* Now we add the ssreflect boilerplate code. *)\n  Canonical Structure setSubType := [subType for _set_seq].\n  Definition set_eqMixin := [eqMixin of set by <:].\n  Canonical Structure set_eqType := EqType set set_eqMixin.\n  Canonical Structure mem_set_predType := mkPredType (fun (l : set) => mem_seq (_set_seq l)).\n  Definition set_of of phant T := set.\n\nEnd SeqSet.\n\nNotation \" {set R } \" := (set_of (Phant R)).\n\nSection Lemmas.\n\n  Context {T: eqType}.\n  Variable s: {set T}.\n\n  Lemma set_uniq : uniq s.\n  Proof.\n    by destruct s.\n  Qed.\n\n  Lemma set_mem : forall x, (x \\in s) = (x \\in _set_seq s).\n  Proof.\n    by intros x; destruct s.\n  Qed.\n  \nEnd Lemmas.\n\nSection LemmasFinType.\n  \n  Context {T: finType}.\n  Variable s: {set T}.\n\n  Lemma set_card : #|s| = size s.\n  Proof.\n    have UNIQ: uniq s by destruct s.\n    by move: UNIQ => /card_uniqP ->.\n  Qed.\n  \nEnd LemmasFinType.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/util/seqset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.746602583866842}}
{"text": "Require Export Basics.\n\nTheorem plus_n_0_firsttry : forall n:nat,\n  n = n + 0.\n\nProof.\n  intros n.\n  simpl.\nAbort.\n\nTheorem plus_n_0_secondtry : forall n:nat,\n  n = n + 0.\nProof.\n  intros n. destruct n as [| n'].\n  reflexivity.\n  simpl.\nAbort.\n\nTheorem plus_n_0 : forall n:nat, n = n+0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem minus_diag : forall n, minus n n = 0.\nProof.\n  intros n. induction n as [| n' IHn' ].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. 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. induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn'. reflexivity.\nQed.\n\n\nTheorem plus_comm : forall n m : nat, n + m = m + n.\nProof.\n  intros n m. induction n as [| n' IHn'].\n  - simpl. rewrite <- plus_n_0. reflexivity.\n  - simpl. rewrite <- plus_n_Sm. rewrite <- IHn'. 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  | 0 => 0\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. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat, evenb (S n) = negb (evenb n).\nProof.\n  intros n. induction n as [| n' IHn' ].\n  - simpl. reflexivity.\n  - rewrite -> IHn'. simpl. rewrite -> negb_involute. 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_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.\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.\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 as [| n' IHn' ].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity.\nQed.\n", "meta": {"author": "jonludlam", "repo": "softwarefoundations", "sha": "26b49791958ffec7cdf47541c7ebaa5667d6da0a", "save_path": "github-repos/coq/jonludlam-softwarefoundations", "path": "github-repos/coq/jonludlam-softwarefoundations/softwarefoundations-26b49791958ffec7cdf47541c7ebaa5667d6da0a/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7466025670060663}}
{"text": "Require Export TopologicalSpaces.\nRequire Export OpenBases.\nFrom ZornsLemma Require Export FiniteTypes.\nFrom ZornsLemma Require Export EnsemblesSpec.\n\nSection Subbasis.\n\nVariable X:TopologicalSpace.\nVariable SB:Family (point_set X).\n\nRecord subbasis : Prop := {\n  subbasis_elements: forall U:Ensemble (point_set X),\n    In SB U -> open U;\n  subbasis_cover: forall (U:Ensemble (point_set X)) (x:point_set X),\n    In U x -> open U ->\n    exists A:Type, FiniteT A /\\\n    exists V:A->Ensemble (point_set X),\n      (forall a:A, In SB (V a)) /\\\n      In (IndexedIntersection V) x /\\\n      Included (IndexedIntersection V) U\n}.\n\nLemma open_basis_is_subbasis: open_basis SB -> subbasis.\nProof.\nintros.\ndestruct H.\nconstructor.\nexact open_basis_elements.\nintros.\ndestruct (open_basis_cover x U); trivial.\ndestruct H1 as [? [? ?]].\nexists True.\nsplit.\napply True_finite.\nexists (True_rect x0).\nrepeat split; intros.\ndestruct a.\nsimpl.\nassumption.\ndestruct a.\nsimpl.\nassumption.\nred; intros.\ndestruct H4.\napply H2.\nexact (H4 I).\nQed.\n\nLemma finite_intersections_of_subbasis_form_open_basis:\n  subbasis ->\n  open_basis [ U:Ensemble (point_set X) |\n              exists A:Type, FiniteT A /\\\n              exists V:A->Ensemble (point_set X),\n              (forall a:A, In SB (V a)) /\\\n              U = IndexedIntersection V ].\nProof.\nconstructor.\nintros.\ndestruct H0.\ndestruct H0 as [A [? [V' [? ?]]]].\nrewrite H2.\napply open_finite_indexed_intersection; trivial.\nintros.\napply H; trivial.\n\nintros.\npose proof (subbasis_cover H U x).\ndestruct H2 as [A [? [V [? [? ?]]]]]; trivial.\nexists (IndexedIntersection V).\nrepeat split; trivial.\nexists A; split; trivial.\nexists V; trivial.\nsplit; trivial.\ndestruct H4.\nexact H4.\nQed.\n\nEnd Subbasis.\n\nArguments subbasis {X}.\n\nSection build_from_subbasis.\n\nVariable X:Type.\nVariable S:Family X.\n\nFrom ZornsLemma Require Import FiniteIntersections.\n\nDefinition Build_TopologicalSpace_from_subbasis : TopologicalSpace.\nrefine (Build_TopologicalSpace_from_open_basis\n  (finite_intersections S) _ _).\nred; intros.\nexists (Intersection U V); repeat split; trivial.\napply intro_intersection; trivial.\ndestruct H1; assumption.\ndestruct H1; assumption.\ndestruct H2; assumption.\ndestruct H2; assumption.\n\nred; intro.\nexists Full_set.\nsplit; constructor.\nDefined.\n\nLemma Build_TopologicalSpace_from_subbasis_subbasis:\n  @subbasis Build_TopologicalSpace_from_subbasis S.\nProof.\nassert (@open_basis Build_TopologicalSpace_from_subbasis\n  (finite_intersections S)).\napply Build_TopologicalSpace_from_open_basis_basis.\nconstructor.\nintros.\nsimpl in U.\napply open_basis_elements with (finite_intersections S); trivial.\nconstructor; trivial.\n\nintros.\ndestruct (@open_basis_cover _ _ H x U) as [V]; trivial.\ndestruct H2 as [? [? ?]].\nsimpl.\n\npose proof (finite_intersection_is_finite_indexed_intersection\n  _ _ H2).\ndestruct H5 as [A [? [W [? ?]]]].\nexists A; split; trivial.\nexists W; repeat split; trivial.\n\nrewrite H7 in H4; destruct H4; apply H4.\nrewrite H7 in H3; assumption.\nQed.\n\nEnd build_from_subbasis.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/topology/Subbases.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7466025623061875}}
{"text": "Theorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - simpl. reflexivity.\n  - simpl. rewrite IH. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - simpl. reflexivity.\n  - simpl. rewrite IH. reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  induction l1 as [| h t IH].\n  - simpl. reflexivity.\n  - simpl. rewrite IH. 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/Chapter4/poly_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7465994922842096}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Yannick Forster            [+]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [+] Affiliation Saarland Univ. *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\n(* ** Two infinite sequences of primes *)\n\nRequire Import List Arith Lia Bool Permutation.\n\nFrom Undecidability.Shared.Libs.DLW \n  Require Import utils utils_tac utils_list utils_nat gcd rel_iter prime pos vec.\n\nSet Implicit Arguments.\n\nLocal Notation \"e #> x\" := (vec_pos e x).\nLocal Notation \"e [ v / x ]\" := (vec_change e x v).\n\nSet Implicit Arguments.\n\n(* Unique decomposition with a prime *)\n\nLemma prime_neq_0 p : prime p -> p <> 0.\nProof.\n  intros ? % prime_ge_2; lia.\nQed.\n\n#[export] Hint Resolve prime_neq_0 : core.\n\nLemma power_factor_lt_neq p i j x y : \n         p <> 0 \n      -> i < j \n      -> ~ divides p x \n      -> p^i * x <> p^j * y.\nProof.\n  intros H1 H2 H3 H5.\n  replace j with (i+S (j-i-1)) in H5 by lia.\n  rewrite Nat.pow_add_r, <- mult_assoc in H5.\n  rewrite Nat.mul_cancel_l in H5.\n  2: apply Nat.pow_nonzero; auto.\n  apply H3; subst x; simpl. \n  do 2 apply divides_mult_r; apply divides_refl.\nQed.\n\nLemma power_factor_uniq p i j x y : \n         p <> 0  \n      -> ~ divides p x\n      -> ~ divides p y \n      -> p^i * x = p^j * y\n      -> i = j /\\ x = y.\nProof.\n  intros H1 H2 H3 H4.\n  destruct (lt_eq_lt_dec i j) as [ [ H | H ] | H ].\n  + exfalso; revert H4; apply power_factor_lt_neq; auto.\n  + split; auto; subst j.\n    rewrite Nat.mul_cancel_l in H4; auto.\n    apply Nat.pow_nonzero; auto.\n  + exfalso; symmetry in H4; revert H4; apply power_factor_lt_neq; auto.\nQed.\n\n(* The unboundedness of primes *)\n\nLemma prime_above m : { p | m < p /\\ prime p }.\nProof.\n  destruct (prime_factor (n := fact m + 1)) as (p & ? & ?).\n  - pose proof (lt_O_fact m); lia.\n  - exists p; eauto. destruct (Nat.lt_ge_cases m p); eauto.\n    eapply divides_plus_inv in H0.\n    + eapply divides_1_inv in H0; subst. destruct H; lia.\n    + eapply divides_fact. eapply prime_ge_2 in H; eauto.\nQed.\n\nLemma prime_dec p : { prime p } + { ~ prime p }.\nProof.\n  destruct (le_lt_dec 2 p) as [ H | H ].\n  + destruct (prime_or_div H) as [ (q & H1 & H2) | ? ]; auto.\n    right; intros C; apply C in H2; lia.\n  + right; intros (H1 & H2).\n    destruct (H2 2); try lia.\n    exists 0; simpl; lia.\nQed.\n\nLemma first_prime_above m : { p | m < p /\\ prime p /\\ forall q, m < q -> prime q -> p <= q }.\nProof.\n  destruct min_dec with (P := fun p => m < p /\\ prime p)\n    as (p & H1 & H2).\n  + intros n.\n    destruct (lt_dec m n); destruct (prime_dec n); tauto.\n  + destruct (prime_above m) as (p & ?); exists p; auto.\n  + exists p; firstorder.\nQed.\n\nLemma prime_divides p q :\n  prime p -> prime q -> divides p q -> p = q.\nProof.\n  now intros Hp Hq [ [] % Hp | ] % Hq.\nQed.\n\nDefinition nxtprime n := proj1_sig (first_prime_above n).\n\nFact nxtprime_spec1 n : n < nxtprime n.\nProof. apply (proj2_sig (first_prime_above n)). Qed.\n\nFact nxtprime_spec2 n : prime (nxtprime n).\nProof. apply (proj2_sig (first_prime_above n)). Qed.\n\n#[export] Hint Resolve nxtprime_spec1 nxtprime_spec2 prime_2 : core.\n\nFixpoint notprime_bool_rec n k :=\n  match k with\n    | 0   => true\n    | S k' => negb (prime_bool n) && notprime_bool_rec (S n) k'\n  end.\n\nTheorem prime_bool_spec' p : prime_bool p = false <-> ~ prime p.\nProof.\n  rewrite <- not_true_iff_false, prime_bool_spec; tauto.\nQed.\n\nFact notprime_bool_rec_spec n k : notprime_bool_rec n k = true <-> forall i, n <= i < k+n -> ~ prime i.\nProof.\n  revert n; induction k as [ | k IHk ]; intros n; simpl.\n  + split; auto; intros; lia.\n  + rewrite andb_true_iff, negb_true_iff, \n            <- not_true_iff_false, prime_bool_spec, IHk.\n    split.\n    * intros (H1 & H2) i Hi.\n      destruct (eq_nat_dec n i); subst; auto.\n      apply H2; lia.\n    * intros H; split; intros; apply H; lia.\nQed.\n\nDefinition nxtprime_bool n p := Nat.leb (S n) p && notprime_bool_rec (S n) (p - S n) && prime_bool p.\n\nFact nxtprime_bool_spec n p : nxtprime_bool n p = true <-> nxtprime n = p.\nProof.\n  unfold nxtprime_bool.\n  rewrite !andb_true_iff, Nat.leb_le, notprime_bool_rec_spec, prime_bool_spec.\n  unfold nxtprime.\n  destruct (first_prime_above n) as (q & G1 & G2 & G3); simpl.\n  split.\n  + intros ((H1 & H2) & H3).\n    apply le_antisym.\n    * apply G3; auto.\n    * apply Nat.nlt_ge. \n      intro; apply (H2 q); auto; lia.\n  + intros ->; lsplit 2; auto.\n    intros q Hq C; apply G3 in C; lia.\nQed.\n\nDefinition nthprime (n : nat) := iter nxtprime 2 n.\n\nLemma nthprime_prime n : prime (nthprime n).\nProof. unfold nthprime; destruct n; simpl; auto; rewrite iter_swap; auto. Qed. \n\n#[export] Hint Resolve nthprime_prime : core.\n\nLemma nthprime_ge n m : n < m -> nthprime n < nthprime m.\nProof.\n  unfold nthprime.\n  induction 1; simpl iter; rewrite iter_swap; auto.\n  apply lt_trans with (2 := nxtprime_spec1 _); auto.  \nQed.\n\nLemma nthprime_inj n m : nthprime n = nthprime m -> n = m.\nProof.\n  destruct (lt_eq_lt_dec n m) as [ [ H | ] | H ]; auto; \n    intros; eapply nthprime_ge in H; lia.\nQed.\n\nFact nthprime_nxt i p q : nthprime i = p -> nxtprime p = q -> nthprime (S i) = q.\nProof.\n  replace (S i) with (i+1) by lia.\n  unfold nthprime at 2.\n  rewrite iter_plus; fold (nthprime i).\n  intros -> ?; simpl; auto.\nQed.\n\n(* Certified Erastosthene sieve would be helpfull here *)\n\nFact nthprime_0 : nthprime 0 = 2.\nProof. auto. Qed.\n\nLocal Ltac nth_prime_tac H := \n  apply nthprime_nxt with (1 := H);\n  apply nxtprime_bool_spec; auto.\n\nFact nthprime_1 : nthprime 1 = 3.    Proof. nth_prime_tac nthprime_0. Qed.\nFact nthprime_2 : nthprime 2 = 5.    Proof. nth_prime_tac nthprime_1. Qed.\nFact nthprime_3 : nthprime 3 = 7.    Proof. nth_prime_tac nthprime_2. Qed.\nFact nthprime_4 : nthprime 4 = 11.   Proof. nth_prime_tac nthprime_3. Qed.\nFact nthprime_5 : nthprime 5 = 13.   Proof. nth_prime_tac nthprime_4. Qed.\nFact nthprime_6 : nthprime 6 = 17.   Proof. nth_prime_tac nthprime_5. Qed.\n\nRecord primestream :=\n  {\n    str :> nat -> nat;\n    str_inj : forall n m, str n = str m -> n = m;\n    str_prime : forall n, prime (str n);\n  }.\n\n#[export] Hint Immediate str_prime : core.\n#[export] Hint Resolve str_inj : core.\n\nLemma primestream_divides (ps : primestream) n m :  divides (ps n) (ps m) -> n = m.\nProof.\n  destruct ps as [ str H1 H2 ]; simpl.\n  intros ? % prime_divides; eauto.\nQed.\n\nDefinition ps : primestream.\nProof.\n  exists (fun n => nthprime (2 * n)); auto.\n  intros; apply nthprime_inj in H; lia.\nDefined.\n\nFact ps_1 : ps 1 = 5.\nProof. simpl; apply nthprime_2. Qed.\n\nDefinition qs : primestream.\nProof.\n  exists (fun n => nthprime (1 + 2 * n)); auto.\n  intros; apply nthprime_inj in H; lia.\nDefined.\n\nFact qs_1 : qs 1 = 7.\nProof. simpl; apply nthprime_3. Qed.\n\nLemma ps_qs : forall n m, ps n = qs m -> False.\nProof. intros ? ? ? % nthprime_inj; lia. Qed. \n\n#[export] Hint Resolve ps_qs : core.\n\nLemma ps_qs_div n m : ~ divides (ps n) (qs m).\nProof. intros ? % prime_divides; eauto. Qed.\n\nLemma qs_ps_div n m : ~ divides (qs n) (ps m).\nProof. intros ? % prime_divides; eauto. Qed.\n\nFixpoint exp {n} (i : nat) (v : vec nat n) : nat :=\n  match v with\n    | vec_nil => 1\n    | x##v    => qs i ^ x * exp (S i) v\n  end.\n\nFact exp_nil i : exp i vec_nil = 1.\nProof. auto. Qed.\n\nFact exp_cons n i x v : @exp (S n) i (x##v) = qs i^x*exp (S i) v.\nProof. auto. Qed.\n\nFact exp_zero n i : @exp n i vec_zero = 1.\nProof.\n  revert i; induction n as [ | n IHn ]; intros i; simpl; auto.\n  rewrite IHn; ring.\nQed.\n\nFact exp_app n m i v w : @exp (n+m) i (vec_app v w) = exp i v * exp (n+i) w.\nProof.\n  revert i; induction v as [ | x n v IHv ]; intros i.\n  + rewrite vec_app_nil, exp_zero; simpl; ring.\n  + rewrite vec_app_cons, exp_cons.\n    simpl plus; rewrite exp_cons, IHv.\n    replace (n+S i) with (S (n+i)) by lia; ring.\nQed.\n\nLocal Notation divides_mult_inv := prime_div_mult.\n\nLemma not_prime_1 : ~ prime 1.\nProof. intros [ [] ]; auto. Qed.\n\nLemma not_ps_1 n : ~ ps n = 1.\nProof.\n  intros H; generalize (str_prime ps n).\n  rewrite H; apply not_prime_1.\nQed. \n\nLemma not_qs_1 n : ~ qs n = 1.\nProof.\n  intros H; generalize (str_prime qs n).\n  rewrite H; apply not_prime_1.\nQed. \n\n#[export] Hint Resolve not_prime_1 not_qs_1 : core.\n\nLemma divides_pow p n k : prime p -> divides p (n ^ k) -> divides p n.\nProof.\n  induction k.\n  - cbn; intros H H0 % divides_1_inv; subst; exfalso; revert H; apply not_prime_1.\n  - cbn; intros ? [ | ] % divides_mult_inv; eauto.\nQed.  \n\nOpaque ps qs.\n\nLemma ps_exp n m (v : vec nat m) i : ~ divides (ps n) (exp i v).\nProof.\n  revert i; induction v as [ | m x v IHv ]; intros i; simpl.\n  - intros H % divides_1_inv; revert H; apply not_ps_1.\n  - intros [H % divides_pow | ] % divides_mult_inv; eauto.\n    + now eapply ps_qs_div in H.\n    + eapply IHv; eauto.\nQed.\n\nCoercion tonat {n} := @pos2nat n.\n\nLemma vec_prod_div m (v : vec nat m) (u0 : nat) (p : pos m) i :\n    vec_pos v p = S u0 -> qs (p + i) * exp i (vec_change v p u0) = exp i v.\nProof.\n  revert p i; induction v; intros p i; analyse pos p; simpl; intros H.\n  - rewrite pos2nat_fst; subst; simpl; ring.\n  - rewrite pos2nat_nxt; simpl.\n    rewrite <- IHv with (1 := H).\n    unfold tonat.\n    replace (S (pos2nat p + i)) with (pos2nat p+S i); ring.\nQed.         \n\nLemma qs_exp_div i j n v : i < j -> ~ divides (qs i) (@exp n j v).\nProof with eauto.\n  revert i j; induction v; intros i j Hi.\n  + cbn; intros ? % divides_1_inv % not_qs_1; auto.\n  + cbn; intros [ H % divides_pow | H  ] % divides_mult_inv; eauto.\n    * eapply primestream_divides in H; lia.\n    * eapply IHv in H; eauto.\nQed.\n\nLemma qs_shift n m j k (v : vec nat k) :\n  divides (qs n) (exp j v) <-> divides (qs (m + n)) (exp (m + j) v).\nProof.\n  revert m n j; induction v as [ | x k v IHv ]; intros m n j.\n  - cbn; split; intros ? % divides_1_inv % not_qs_1; tauto.\n  - cbn. split.\n    + intros [ | ] % divides_mult_inv; auto.\n      * destruct x.\n        -- cbn in H; revert H.\n           intros ? % divides_1_inv % not_qs_1; tauto.\n        -- eapply divides_pow in H; auto. \n           eapply primestream_divides in H as ->.\n           cbn; do 2 apply divides_mult_r; apply divides_refl.\n      * eapply divides_mult. \n        rewrite IHv with (m := m) in H.\n        rewrite <- plus_n_Sm in H; auto.\n    + intros [ | ] % divides_mult_inv; auto.\n      * destruct x.\n        -- cbn in H; revert H.\n           intros ? % divides_1_inv % not_qs_1; tauto.\n        -- eapply divides_pow in H; auto. \n           eapply primestream_divides in H.\n           assert (n = j) by lia. subst.\n           cbn; do 2 apply divides_mult_r; apply divides_refl.\n      * eapply divides_mult. replace (S (m + j)) with (m + S j) in H by lia.\n        rewrite <- IHv in H. eauto.\nQed.\n\nLemma vec_prod_mult m v (u : pos m) i : @exp m i (vec_change v u (1 + vec_pos v u)) = qs (u + i) * exp i v.\nProof.\n  revert i; induction v; analyse pos u; intros.\n  + rewrite pos2nat_fst; simpl; ring.\n  + rewrite pos2nat_nxt; simpl; rewrite IHv.\n    unfold tonat.\n    replace (pos2nat u+S i) with (S (pos2nat u+i)) by lia; ring.\nQed.\n\nLemma inv_exp q p1 p2 x y : \n         q <> 0 \n      -> ~ divides q p1 \n      -> ~ divides q p2 \n      -> q ^ x * p1 = q ^ y * p2 \n      -> x = y.\nProof.\n  intros H1 H2 H3 H4.\n  apply power_factor_uniq in H4; tauto.\nQed.\n\nLemma exp_inj n i v1 v2 :\n  @exp n i v1 = exp i v2 -> v1 = v2.\nProof.\n  revert i v2; induction v1 as [ | x n v1 IH ]; intros i v2.\n  + vec nil v2; auto.\n  + vec split v2 with y.\n    simpl; intros H.\n    assert (forall v, ~ divides (qs i) (@exp n (S i) v)) as G.\n    { intros v; apply qs_exp_div; auto. }\n    apply power_factor_uniq in H; auto.\n    destruct H; f_equal; subst; eauto.\nQed.\n\nLemma exp_inv_inc n u v1 :\n  @exp n 0 (vec_change v1 u (S (vec_pos v1 u))) = qs u * exp 0 v1.\nProof.\n  enough (forall i, exp i (vec_change v1 u (S (vec_pos v1 u))) = qs (i + u) * exp i v1). eapply H.\n  induction v1 as [ | n x v1 IHv1 ]; analyse pos u; intros.\n  + rewrite pos2nat_fst, Nat.add_0_r; cbn; ring.\n  + intros; rewrite pos2nat_nxt; simpl; rewrite IHv1; unfold tonat.\n    replace (S i+pos2nat u) with (i+S (pos2nat u)) by lia; ring.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/FRACTRAN/Utils/prime_seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7465021735280903}}
{"text": "Require Import nat.\nRequire Import syntax.\n\nInductive aevalR:aexp -> nat -> Prop :=\n| E_ANum : forall (n:nat), aevalR (ANum n) n\n| E_APlus: forall (n1 n2:nat) (a1 a2:aexp), \n    aevalR a1 n1 -> aevalR a2 n2 -> aevalR (APlus a1 a2) (n1 + n2)\n| E_AMinus: forall (n1 n2:nat) (a1 a2:aexp), \n    aevalR a1 n1 -> aevalR a2 n2 -> aevalR (AMinus a1 a2) (n1 - n2)\n| E_AMult: forall (n1 n2:nat) (a1 a2:aexp), \n    aevalR a1 n1 -> aevalR a2 n2 -> aevalR (AMult a1 a2) (n1 * n2)\n.\n\nNotation \"e \\\\ n\" := (aevalR e n) (at level 50, no associativity) : type_scope.\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/sf/try_evalR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361162033533, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7464885979262302}}
{"text": "Require Import Basic.\nRequire Import Full.\nRequire Import ZArith.\nRequire Import EqDec.\n\nExport ZArith.\n\nOpen Scope Z.\n\nClass Integer `{Basic} := { \n  Int : Type;\n  denotationInt :> Denotation Int Z;\n  fullInt :> Full Int;\n\n  fromZ : Z -> Int;\n  plus : Int -> Int -> Int;\n  minus : Int -> Int -> Int;\n  equal : Int -> Int -> bool;\n  le : Int -> Int -> bool;\n\n  denoteFromZOk z : ⟦fromZ z⟧ = z;\n  denotePlusOk n m : ⟦plus n m⟧ = ⟦n⟧ + ⟦m⟧;\n  denoteMinusOk n m : ⟦minus n m⟧ = ⟦n⟧ - ⟦m⟧;\n  denoteEqualOk n m : equal n m = (⟦ n ⟧ =? ⟦ m ⟧);\n  denoteLeOk n m : le n m = (⟦ n ⟧ <=? ⟦ m ⟧);\n  denoteInjective n m : ⟦n⟧ = ⟦m⟧ -> n = m\n}.\n\nSection Integer.\n  Context `{Integer}.\n\n  Definition mone : Int := fromZ (-1).\n  Definition zero := fromZ 0.\n  Definition one  := fromZ 1.\n\n  Lemma denoteMoneOk : ⟦mone⟧ = -1.\n    apply denoteFromZOk.\n  Qed.\n\n  Lemma denoteZeroOk : ⟦zero⟧ = 0.\n    apply denoteFromZOk.\n  Qed.\n\n  Lemma denoteOneOk : ⟦one⟧ = 1.\n    apply denoteFromZOk.\n  Qed.\nEnd Integer.\n\nSection Definitions.\n  Context `{Basic}.\n  Context `{Integer}.\n  \n  Global Instance eqDecInteger : eqDec Int := {|\n    eqDecide := _\n  |}.\n    intros n m.\n    destruct (equal n m) eqn:eq.\n    - left.\n      rewrite denoteEqualOk in eq.\n      rewrite Z.eqb_eq in eq. \n      apply denoteInjective.\n      assumption.\n    - right.\n      rewrite denoteEqualOk in eq.\n      rewrite Z.eqb_neq in eq.\n      congruence.\n  Defined.\n  \n  Fixpoint natToInt (n:nat) : Int :=\n    match n with\n    | O => zero\n    | S n => plus one (natToInt n)\n    end.\n  \n  Definition lt (n m:Int) : bool := \n    andb (le n m) (negb (equal n m)).\n\n  Lemma denoteLtOk n m : lt n m = (⟦ n ⟧ <? ⟦ m ⟧).\n  Proof.\n    unfold lt.\n    rewrite denoteLeOk.\n    apply Bool.eq_true_iff_eq.\n    rewrite Bool.andb_true_iff, Bool.negb_true_iff.\n    rewrite denoteEqualOk.\n    rewrite Z.leb_le, Z.eqb_neq, Z.ltb_lt.\n    omega.\n  Qed.\n\n  Lemma fromZInv : forall (i : Int), fromZ ⟦ i ⟧ = i.\n    intros.\n    apply denoteInjective.\n    now rewrite denoteFromZOk.\n  Qed.\n\n  (* { v | n <= v < m } *)\n  Definition range (n m:Int) : Space Int.\n    refine (bind full (fun v : Int => _)).\n    refine (if (andb (le n v) (lt v m))\n            then single v else empty).\n  Defined.\nEnd Definitions.\n\n", "meta": {"author": "konne88", "repo": "SpaceSearch", "sha": "524040a1f60a629c4f71c233341ad39a43d44eff", "save_path": "github-repos/coq/konne88-SpaceSearch", "path": "github-repos/coq/konne88-SpaceSearch/SpaceSearch-524040a1f60a629c4f71c233341ad39a43d44eff/src/coq/Space/Integer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7464831913716304}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat div.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*  This is the proof script associated with the tutorial                    *)\n(*                                                                           *)\n(*      An Ssreflect Tutorial                                                *)\n(*      Georges Gonthier Stéphane Le Roux                                    *)\n(*                                                                           *)\n(*      https://hal.inria.fr/inria-00407778                                  *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\n(*****************************************************************************)\n(*                                                                           *)\n(*      Hilbert's axiom S                                                    *)\n(*                                                                           *)\n(*****************************************************************************)\n\nSection HilbertSaxiom.\n\nVariables A B C : Prop.\n\nLemma HilbertS : (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\nmove=> hAiBiC hAiB hA.\nmove: hAiBiC.\napply.\n  by [].\nby apply: hAiB.\nQed.\n\nHypotheses (hAiBiC : A -> B -> C) (hAiB : A -> B) (hA : A).\n\nLemma HilbertS2 : C.\nProof.\napply: hAiBiC; first by apply: hA.\nexact: hAiB.\nQed.\n\nLemma HilbertS3 : C.\nProof. by apply: hAiBiC; last exact: hAiB. Qed.\n\nCheck (hAiB hA).\n\nLemma HilbertS4 : C.\nProof. exact:  (hAiBiC _ (hAiB _)). Qed.\n\nLemma HilbertS5 : C.\nProof. exact: hAiBiC (hAiB _). Qed.\n\nLemma HilbertS6 : C.\nProof. exact: HilbertS5. Qed.\n\nPrint HilbertS5.\n\nPrint HilbertS2.\n\nPrint HilbertS.\n\nCheck HilbertS.\n\nEnd HilbertSaxiom.\n\nPrint HilbertS5.\n\n\n(*****************************************************************************)\n(*                                                                           *)\n(*      Logical connectives                                                  *)\n(*                                                                           *)\n(*****************************************************************************)\n\nPrint bool.\n\nSection Symmetric_Conjunction_Disjunction.\n\nLemma andb_sym : forall A B : bool, A && B -> B && A.\nProof.\ncase.\n  by case.\nby [].\nQed.\n\nLemma andb_sym2 : forall A B : bool, A && B -> B && A.\nProof. by case; case. Qed.\n\nLemma andb_sym3 : forall A B : bool, A && B -> B && A.\nProof. by do 2! case. Qed.\n\nVariables (C D : Prop) (hC : C) (hD : D).\n\nCheck (and C D).\n\nPrint and.\n\nCheck conj.\n\nCheck (conj hC hD).\n\nLemma and_sym : forall A B : Prop, A /\\ B -> B /\\ A.\nProof. by move=> A1 B []. Qed.\n\nCheck or.\n\nCheck or_introl.\n\nLemma or_sym : forall A B : Prop, A \\/ B -> B \\/ A.\nProof. by move=> A B [hA | hB]; [apply: or_intror | apply: or_introl]. Qed.\n\nLemma or_sym2 : forall A B : bool, A \\/ B -> B \\/ A.\nProof. by move=> [] [] AorB; apply/orP; move/orP : AorB. Qed.\n\nEnd Symmetric_Conjunction_Disjunction.\n\nSection R_sym_trans.\n\nVariables (D : Type) (R : D -> D -> Prop).\n\nHypothesis R_sym : forall x y, R x y -> R y x.\n\nHypothesis R_trans : forall x y z, R x y -> R y z -> R x z.\n\nLemma refl_if : forall x : D, (exists y, R x y) -> R x x.\nProof.\nmove=> x [y Rxy].\nby apply: R_trans _ (R_sym _ y _).\nQed.\n\nEnd R_sym_trans.\n\nSection Smullyan_drinker.\n\nVariables (D : Type)(P : D -> Prop).\n\nHypothesis (d : D) (EM : forall A, A \\/ ~A).\n\nLemma drinker : exists x, P x -> forall y, P y.\nProof.\ncase: (EM (exists y, ~P y)) => [[y notPy]| nonotPy]; first by exists y.\nexists d => _ y; case: (EM (P y)) => // notPy.\nby case: nonotPy; exists y.\nQed.\n\nEnd Smullyan_drinker.\n\nSection Equality.\n\nVariable f : nat -> nat.\nHypothesis f00 : f 0 = 0.\n\nLemma fkk : forall k, k = 0 -> f k = k.\nProof.\nmove=> k k0.\nby rewrite k0.\nQed.\n\nLemma fkk2 : forall k, k = 0 -> f k = k.\nProof. by move=> k ->. Qed.\n\nVariable f10 : f 1 = f 0.\n\nLemma ff10 : f (f 1) = 0.\nProof. by rewrite f10 f00. Qed.\n\nVariables (D : eqType) (x y : D).\n\nLemma eq_prop_bool : x = y -> x == y.\nProof. by move/eqP. Qed.\n\nLemma eq_bool_prop : x == y -> x = y.\nProof. by move/eqP. Qed.\n\nEnd Equality.\n\nSection Using_Definition.\n\nVariable U : Type.\n\nDefinition set := U -> Prop.\n\nDefinition subset (A B : set) := forall x, A x -> B x.\n\nDefinition transitive (T : Type) (R : T -> T -> Prop) :=\n forall x y z, R x y -> R y z -> R x z.\n\nLemma subset_trans : transitive set subset.\nProof.\nrewrite /transitive /subset => x y z subxy subyz t xt.\nby apply: subyz; apply: subxy.\nQed.\n\nLemma subset_trans2 : transitive set subset.\nProof.\nmove=> x y z subxy subyz t.\nby move/subxy; move/subyz.\nQed.\n\nEnd Using_Definition.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*     Arithmetic for Euclidean division                                     *)\n(*                                                                           *)\n(*****************************************************************************)\n\nSection Arithmetic.\n\nCheck nat.\n\nPrint nat.\n\nLemma three : S (S (S O)) = 3 /\\ 2 = 0.+1.+1.\nProof. by []. Qed.\n\nPrint plus.\n\nLemma concrete_plus : plus 16 64 = 80.\nProof. (* simpl. *) by []. Qed.\n\nLemma concrete_plus_bis : 16 + 64 = 80.\nProof. (* simpl. *)  by []. Qed.\n\nPrint mult.\n\nPrint le.\n\nLemma concrete_le : le 1 3.\nProof.\nby apply: (PeanoNat.Nat.le_trans _ 2); apply: PeanoNat.Nat.le_succ_diag_r.\nQed.\n\nLemma concrete_big_le : le 16 64.\nProof. by auto 50. Qed.\n\nPrint leq.\n\nPrint subn.\n\nPrint subn_rec.\n\nLemma concrete_big_leq : 0 <= 51.\nProof. by []. Qed.\n\nLemma semi_concrete_leq : forall n m, n <= m -> 51 + n <= 51 + m.\nProof. by []. Qed.\n\nLemma concrete_arith : (50 < 100) && (3 + 4 < 3 * 4 <= 17 - 2).\nProof. by []. Qed.\n\nPrint nat_ind.\n\nLemma plus_commute : forall n1 m1, n1 + m1 = m1 + n1.\nProof.\nelim=> [m1 | n1 IHn1 m1].\n  by elim: m1 => // m1 IHm1; rewrite -[0 + m1.+1]/(0 + m1).+1 IHm1.\nrewrite -[n1.+1 + m1]/(n1 + m1).+1 IHn1.\nby elim: m1 => // m1 IHm1; rewrite -[m1.+1 + n1]/(m1 + n1).+1 IHm1.\nQed.\n\nCheck edivn_rec.\n\nPrint edivn_rec.\n\nPrint edivn.\n\nPrint edivn_spec.\n\nLemma edivnP : forall m d, edivn_spec m d (edivn m d).\nProof.\nrewrite /edivn => m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\nrewrite subn_if_gt; case: ltnP => [// | le_dm].\nrewrite -{1}(subnK le_dm) [_ + d]addnC -addSn addnA -mulSnr; apply: IHn.\napply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nCheck nat_ind.\n\nCheck ltnP.\n\nPrint ltn_xor_geq.\n\nLemma edivn_eq : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> d q r lt_rd; have d_pos: 0 < d by exact: leq_trans lt_rd.\ncase: edivnP lt_rd => q' r'; rewrite d_pos /=.\nwlog: q q' r r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\nrewrite -(leq_pmul2r d_pos); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\nby rewrite addnS ltnNge mulSn -addnA Eqr addnCA addnA leq_addr.\nQed.\n\n(*****************************************************************************)\n(*                                                                           *)\n(*      Parametric type families and alternative specifications              *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\nCheck edivn_spec.\n\nPrint edivn_spec.\n\nCoInductive edivn_spec_right : nat -> nat -> nat * nat -> Type :=\n  EdivnSpec_right m d q r of m = q * d + r & (d > 0) ==> (r < d) :\n  edivn_spec_right m d (q, r).\n\nCoInductive edivn_spec_left (m d : nat)(qr : nat * nat) : Type :=\nEdivnSpec_left of m = (fst qr) * d + (snd qr) & (d > 0) ==> (snd qr < d) :\n   edivn_spec_left m d qr.\n\n\nLemma edivnP_right : forall m d, edivn_spec_right m d (edivn m d).\nAdmitted.\n\nLemma edivnP_left : forall m d, edivn_spec_left m d (edivn m d).\nAdmitted.\n\n\nLemma edivn_eq_right : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> d q r lt_rd; have d_pos: 0 < d by exact: leq_trans lt_rd.\nset m := q * d + r; have: m = q * d + r by [].\nset d' := d; have: d' = d by [].\ncase: (edivnP_right m d') => {d'}m d' q' r' -> lt_r'd' d'd q'd'r'.\nmove: q'd'r' lt_r'd' lt_rd; rewrite d'd d_pos {d'd m} /=.\nwlog: q q' r r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\nrewrite -(leq_pmul2r d_pos); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\nby rewrite addnS ltnNge mulSn -addnA -Eqr addnCA addnA leq_addr.\nQed.\n\nLemma edivn_eq_left : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> d q r lt_rd; have d_pos: 0 < d by exact: leq_trans lt_rd.\ncase: (edivnP_left (q * d + r) d) lt_rd; rewrite d_pos /=.\nset q':= (edivn (q * d + r) d).1; set r':= (edivn (q * d + r) d).2.\nrewrite (surjective_pairing (edivn (q * d + r) d)) -/q' -/r'.\nwlog: q r q' r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\nrewrite -(leq_pmul2r d_pos); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\nby rewrite addnS ltnNge mulSn -addnA Eqr addnCA addnA leq_addr.\nQed.\n\nEnd Arithmetic.\n", "meta": {"author": "math-comp", "repo": "tutorial_material", "sha": "3e5fcef3a25d2a43115fb645645b437640624ad3", "save_path": "github-repos/coq/math-comp-tutorial_material", "path": "github-repos/coq/math-comp-tutorial_material/tutorial_material-3e5fcef3a25d2a43115fb645645b437640624ad3/AnSsreflectTutorial/tutorial_Gonthier_LeRoux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7464831826228076}}
{"text": "Goal forall x : nat, 1 * x = x.\nintros.\nsimpl.\nelim x.\nreflexivity.\nintros.\nsimpl.\nrewrite H.\nreflexivity.\n\n\nFixpoint f (n : nat) {struct n} : nat :=\nmatch n with\n0 => 1\n| S(n) =>2 * f(n)\nend.\n\nLemma fdix :\n(f 10)=1024.\nsimpl.\nreflexivity.\n\nPrint list.\nOpen Scope list.\nCheck (0 :: 1 :: nil).\n\nRequire Export List.\n\nLemma rev_proof:\nforall E : Type, forall l : (list E), forall a : E, rev (l ++ a::nil)=a ::rev l.\nintros.\nelim l.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nrewrite H.\nsimpl.\nreflexivity.\nQed.\n\n\n(*Lemma list_identity :\nGoal forall (E : Type) (l : list E), l ++ nil = l.\nintros.\nelim l.\nreflexivity.\nintros.\nsimpl.\nrewrite H.\nreflexivity.\nQed.\n*)\n\nLemma rev_consistence :\nforall E : Type, forall l : (list E), rev(rev l) = l.\nintros.\nelim l.\nreflexivity.\nintros.\nsimpl.\nrewrite rev_proof.\nrewrite H.\nreflexivity.\n\nLemma my_eq_nat_dec :\nforall n m : nat, {n = m} + {n <> m}.\ndecide equality.\n(*No idea how to do that*)\n\n\nInductive binary_tree ( A : Type ) : Type\n\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/tp2.type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7464831730622951}}
{"text": "Variable a:Set.\nVariable Q:Prop -> Prop.\n\nLemma L1 : (forall (x:a) (p:Prop), Q p) <-> forall (p:a -> Prop) (x:a), Q (p x).\nProof.\n    split.\n    - intros H p x. apply H. assumption.\n    - intros H x p.  apply (H (fun x => p)). assumption.\nQed.\n\nLemma L2 : (forall (x y:a) (p:Prop), Q p) <-> forall (p:a -> a -> Prop) (x y:a), Q (p x y).\nProof.\n    split. \n    - intros H p x y. apply H; assumption.\n    - intros H x y p. apply (H (fun x y => p)); assumption.\nQed.\n\nLemma L3 : (forall (x:a), False) -> False.\nProof.\n    intros H. \n    \nAbort. (* Cannot be proven *) \n\n(* However *)\nLemma L4 : forall (y:a), (forall (x:a), False) -> False.\nProof.\n    intros y H. apply H. assumption.\nQed.\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/specialize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7464259753683777}}
{"text": "Require Export D.\n\n(** 2 stars (gorgeous_sum)  *)\n\nLemma plus_assoc: forall a b c, \n  (a + b) + c = a + (b + c).\nProof. intros. induction a.\n  Case \"a = 0\". reflexivity.\n  Case \"a = S a\". simpl. rewrite -> IHa. reflexivity. Qed.\n\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros n m Hn Hm. induction Hn.\n  Case \"n = 0\". simpl. apply Hm.\n  Case \"n = 3 + n0\". rewrite -> plus_assoc. apply g_plus3. apply IHHn.\n  Case \"n = 5 + n0\". rewrite -> plus_assoc. apply g_plus5. apply IHHn.  \n  Qed.\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/P05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865197, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7464259644205935}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice.\nFrom mathcomp Require Import fintype bigop div ssralg countalg binomial tuple.\n\n(******************************************************************************)\n(* This file provides a library for univariate polynomials over ring          *)\n(* structures; it also provides an extended theory for polynomials whose      *)\n(* coefficients range over commutative rings and integral domains.            *)\n(*                                                                            *)\n(*           {poly R} == the type of polynomials with coefficients of type R, *)\n(*                       represented as lists with a non zero last element    *)\n(*                       (big endian representation); the coeficient type R   *)\n(*                       must have a canonical ringType structure cR. In fact *)\n(*                       {poly R} denotes the concrete type polynomial cR; R  *)\n(*                       is just a phantom argument that lets type inference  *)\n(*                       reconstruct the (hidden) ringType structure cR.      *)\n(*          p : seq R == the big-endian sequence of coefficients of p, via    *)\n(*                       the coercion polyseq : polynomial >-> seq.           *)\n(*             Poly s == the polynomial with coefficient sequence s (ignoring *)\n(*                       trailing zeroes).                                    *)\n(* \\poly_(i < n) E(i) == the polynomial of degree at most n - 1 whose         *)\n(*                       coefficients are given by the general term E(i)      *)\n(*  0, 1, - p, p + q, == the usual ring operations: {poly R} has a canonical  *)\n(* p * q, p ^+ n, ...    ringType structure, which is commutative / integral  *)\n(*                       when R is commutative / integral, respectively.      *)\n(*      polyC c, c%:P == the constant polynomial c                            *)\n(*                 'X == the (unique) variable                                *)\n(*               'X^n == a power of 'X; 'X^0 is 1, 'X^1 is convertible to 'X  *)\n(*               p`_i == the coefficient of 'X^i in p; this is in fact just   *)\n(*                       the ring_scope notation generic seq-indexing using   *)\n(*                       nth 0%R, combined with the polyseq coercion.         *)\n(*            coefp i == the linear function p |-> p`_i (self-exapanding).    *)\n(*             size p == 1 + the degree of p, or 0 if p = 0 (this is the      *)\n(*                       generic seq function combined with polyseq).         *)\n(*        lead_coef p == the coefficient of the highest monomial in p, or 0   *)\n(*                       if p = 0 (hence lead_coef p = 0 iff p = 0)           *)\n(*        p \\is monic <=> lead_coef p == 1 (0 is not monic).                  *)\n(* p \\is a polyOver S <=> the coefficients of p satisfy S; S should have a    *)\n(*                        key that should be (at least) an addrPred.          *)\n(*             p.[x]  == the evaluation of a polynomial p at a point x using  *)\n(*                       the Horner scheme                                    *)\n(*                   *** The multi-rule hornerE (resp., hornerE_comm) unwinds *)\n(*                       horner evaluation of a polynomial expression (resp., *)\n(*                       in a non commutative ring, with side conditions).    *)\n(*             p^`()  == formal derivative of p                               *)\n(*             p^`(n) == formal n-derivative of p                             *)\n(*            p^`N(n) == formal n-derivative of p divided by n!               *)\n(*            p \\Po q == polynomial composition; because this is naturally a  *)\n(*                       a linear morphism in the first argument, this        *)\n(*                       notation is transposed (q comes before p for redex   *)\n(*                       selection, etc).                                     *)\n(*                      := \\sum(i < size p) p`_i *: q ^+ i                    *)\n(*      comm_poly p x == x and p.[x] commute; this is a sufficient condition  *)\n(*                       for evaluating (q * p).[x] as q.[x] * p.[x] when R   *)\n(*                       is not commutative.                                  *)\n(*      comm_coef p x == x commutes with all the coefficients of p (clearly,  *)\n(*                       this implies comm_poly p x).                         *)\n(*           root p x == x is a root of p, i.e., p.[x] = 0                    *)\n(*    n.-unity_root x == x is an nth root of unity, i.e., a root of 'X^n - 1  *)\n(* n.-primitive_root x == x is a primitive nth root of unity, i.e., n is the  *)\n(*                       least positive integer m > 0 such that x ^+ m = 1.   *)\n(*                   *** The submodule poly.UnityRootTheory can be used to    *)\n(*                       import selectively the part of the theory of roots   *)\n(*                       of unity that doesn't mention polynomials explicitly *)\n(*       map_poly f p == the image of the polynomial by the function f (which *)\n(*     (locally, p^f)    is usually a ring morphism).                         *)\n(*               p^:P == p lifted to {poly {poly R}} (:= map_poly polyC p).   *)\n(*   commr_rmorph f u == u commutes with the image of f (i.e., with all f x). *)\n(*   horner_morph cfu == given cfu : commr_rmorph f u, the function mapping p *)\n(*                       to the value of map_poly f p at u; this is a ring    *)\n(*                       morphism from {poly R} to the codomain of f when f   *)\n(*                       is a ring morphism.                                  *)\n(*      horner_eval u == the function mapping p to p.[u]; this function can   *)\n(*                       only be used for u in a commutative ring, so it is   *)\n(*                       always a linear ring morphism from {poly R} to R.    *)\n(*       horner_alg a == given a in some R-algebra A, the function evaluating *)\n(*                       a polynomial p at a; it is always a linear ring      *)\n(*                       morphism from {poly R} to A.                         *)\n(*     diff_roots x y == x and y are distinct roots; if R is a field, this    *)\n(*                       just means x != y, but this concept is generalized   *)\n(*                       to the case where R is only a ring with units (i.e., *)\n(*                       a unitRingType); in which case it means that x and y *)\n(*                       commute, and that the difference x - y is a unit     *)\n(*                       (i.e., has a multiplicative inverse) in R.           *)\n(*                       to just x != y).                                     *)\n(*       uniq_roots s == s is a sequence or pairwise distinct roots, in the   *)\n(*                       sense of diff_roots p above.                         *)\n(*   *** We only show that these operations and properties are transferred by *)\n(*       morphisms whose domain is a field (thus ensuring injectivity).       *)\n(* We prove the factor_theorem, and the max_poly_roots inequality relating    *)\n(* the number of distinct roots of a polynomial and its size.                 *)\n(*   The some polynomial lemmas use following suffix interpretation :         *)\n(*   C - constant polynomial (as in polyseqC : a%:P = nseq (a != 0) a).       *)\n(*   X - the polynomial variable 'X (as in coefX : 'X`_i = (i == 1%N)).       *)\n(*   Xn - power of 'X (as in monicXn : monic 'X^n).                           *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nReserved Notation \"{ 'poly' T }\" (at level 0, format \"{ 'poly'  T }\").\nReserved Notation \"c %:P\" (at level 2, format \"c %:P\").\nReserved Notation \"p ^:P\" (at level 2, format \"p ^:P\").\nReserved Notation \"'X\" (at level 0).\nReserved Notation \"''X^' n\" (at level 3, n at level 2, format \"''X^' n\").\nReserved Notation \"\\poly_ ( i < n ) E\"\n  (at level 36, E at level 36, i, n at level 50,\n   format \"\\poly_ ( i  <  n )  E\").\nReserved Notation \"p \\Po q\" (at level 50).\nReserved Notation \"p ^`N ( n )\" (at level 8, format \"p ^`N ( n )\").\nReserved Notation \"n .-unity_root\" (at level 2, format \"n .-unity_root\").\nReserved Notation \"n .-primitive_root\"\n  (at level 2, format \"n .-primitive_root\").\n\nLocal Notation simp := Monoid.simpm.\n\nSection Polynomial.\n\nVariable R : ringType.\n\n(* Defines a polynomial as a sequence with <> 0 last element *)\nRecord polynomial := Polynomial {polyseq :> seq R; _ : last 1 polyseq != 0}.\n\nCanonical polynomial_subType := Eval hnf in [subType for polyseq].\nDefinition polynomial_eqMixin := Eval hnf in [eqMixin of polynomial by <:].\nCanonical polynomial_eqType := Eval hnf in EqType polynomial polynomial_eqMixin.\nDefinition polynomial_choiceMixin := [choiceMixin of polynomial by <:].\nCanonical polynomial_choiceType :=\n  Eval hnf in ChoiceType polynomial polynomial_choiceMixin.\n\nLemma poly_inj : injective polyseq. Proof. exact: val_inj. Qed.\n\nDefinition poly_of of phant R := polynomial.\nIdentity Coercion type_poly_of : poly_of >-> polynomial.\n\nDefinition coefp_head h i (p : poly_of (Phant R)) := let: tt := h in p`_i.\n\nEnd Polynomial.\n\n(* We need to break off the section here to let the Bind Scope directives     *)\n(* take effect.                                                               *)\nBind Scope ring_scope with poly_of.\nBind Scope ring_scope with polynomial.\nArguments polyseq {R} p%R.\nArguments poly_inj {R} [p1%R p2%R] : rename.\nArguments coefp_head {R} h i%N p%R.\nNotation \"{ 'poly' T }\" := (poly_of (Phant T)).\nNotation coefp i := (coefp_head tt i).\n\nDefinition poly_countMixin (R : countRingType) :=\n  [countMixin of polynomial R by <:].\nCanonical polynomial_countType R := CountType _ (poly_countMixin R).\nCanonical poly_countType (R : countRingType) := [countType of {poly R}].\n\nSection PolynomialTheory.\n\nVariable R : ringType.\nImplicit Types (a b c x y z : R) (p q r d : {poly R}).\n\nCanonical poly_subType := Eval hnf in [subType of {poly R}].\nCanonical poly_eqType := Eval hnf in [eqType of {poly R}].\nCanonical poly_choiceType := Eval hnf in [choiceType of {poly R}].\n\nDefinition lead_coef p := p`_(size p).-1.\nLemma lead_coefE p : lead_coef p = p`_(size p).-1. Proof. by []. Qed.\n\nDefinition poly_nil := @Polynomial R [::] (oner_neq0 R).\nDefinition polyC c : {poly R} := insubd poly_nil [:: c].\n\nLocal Notation \"c %:P\" := (polyC c).\n\n(* Remember the boolean (c != 0) is coerced to 1 if true and 0 if false *)\nLemma polyseqC c : c%:P = nseq (c != 0) c :> seq R.\nProof. by rewrite val_insubd /=; case: (c == 0). Qed.\n\nLemma size_polyC c : size c%:P = (c != 0).\nProof. by rewrite polyseqC size_nseq. Qed.\n\nLemma coefC c i : c%:P`_i = if i == 0%N then c else 0.\nProof. by rewrite polyseqC; case: i => [|[]]; case: eqP. Qed.\n\nLemma polyCK : cancel polyC (coefp 0).\nProof. by move=> c; rewrite [coefp 0 _]coefC. Qed.\n\nLemma polyC_inj : injective polyC.\nProof. by move=> c1 c2 eqc12; have:= coefC c2 0; rewrite -eqc12 coefC. Qed.\n\nLemma lead_coefC c : lead_coef c%:P = c.\nProof. by rewrite /lead_coef polyseqC; case: eqP. Qed.\n\n(* Extensional interpretation (poly <=> nat -> R) *)\nLemma polyP p q : nth 0 p =1 nth 0 q <-> p = q.\nProof.\nsplit=> [eq_pq | -> //]; apply: poly_inj.\nwithout loss lt_pq: p q eq_pq / size p < size q.\n  move=> IH; case: (ltngtP (size p) (size q)); try by move/IH->.\n  by move/(@eq_from_nth _ 0); apply.\ncase: q => q nz_q /= in lt_pq eq_pq *; case/eqP: nz_q.\nby rewrite (last_nth 0) -(subnKC lt_pq) /= -eq_pq nth_default ?leq_addr.\nQed.\n\nLemma size1_polyC p : size p <= 1 -> p = (p`_0)%:P.\nProof.\nmove=> le_p_1; apply/polyP=> i; rewrite coefC.\nby case: i => // i; rewrite nth_default // (leq_trans le_p_1).\nQed.\n\n(* Builds a polynomial by extension. *)\nDefinition cons_poly c p : {poly R} :=\n  if p is Polynomial ((_ :: _) as s) ns then\n    @Polynomial R (c :: s) ns\n  else c%:P.\n\nLemma polyseq_cons c p :\n  cons_poly c p = (if ~~ nilp p then c :: p else c%:P) :> seq R.\nProof. by case: p => [[]]. Qed.\n\nLemma size_cons_poly c p :\n  size (cons_poly c p) = (if nilp p && (c == 0) then 0%N else (size p).+1).\nProof. by case: p => [[|c' s] _] //=; rewrite size_polyC; case: eqP. Qed.\n\nLemma coef_cons c p i : (cons_poly c p)`_i = if i == 0%N then c else p`_i.-1.\nProof.\nby case: p i => [[|c' s] _] [] //=; rewrite polyseqC; case: eqP => //= _ [].\nQed.\n\n(* Build a polynomial directly from a list of coefficients. *)\nDefinition Poly := foldr cons_poly 0%:P.\n\nLemma PolyK c s : last c s != 0 -> Poly s = s :> seq R.\nProof.\ncase: s => {c}/= [_ |c s]; first by rewrite polyseqC eqxx.\nelim: s c => /= [|a s IHs] c nz_c; rewrite polyseq_cons ?{}IHs //.\nby rewrite !polyseqC !eqxx nz_c.\nQed.\n\nLemma polyseqK p : Poly p = p.\nProof. by apply: poly_inj; apply: PolyK (valP p). Qed.\n\nLemma size_Poly s : size (Poly s) <= size s.\nProof.\nelim: s => [|c s IHs] /=; first by rewrite polyseqC eqxx.\nby rewrite polyseq_cons; case: ifP => // _; rewrite size_polyC; case: (~~ _).\nQed.\n\nLemma coef_Poly s i : (Poly s)`_i = s`_i.\nProof.\nby elim: s i => [|c s IHs] /= [|i]; rewrite !(coefC, eqxx, coef_cons) /=.\nQed.\n\n(* Build a polynomial from an infinite sequence of coefficients and a bound. *)\nDefinition poly_expanded_def n E := Poly (mkseq E n).\nFact poly_key : unit. Proof. by []. Qed.\nDefinition poly := locked_with poly_key poly_expanded_def.\nCanonical poly_unlockable := [unlockable fun poly].\nLocal Notation \"\\poly_ ( i < n ) E\" := (poly n (fun i : nat => E)).\n\nLemma polyseq_poly n E :\n  E n.-1 != 0 -> \\poly_(i < n) E i = mkseq [eta E] n :> seq R.\nProof.\nrewrite unlock; case: n => [|n] nzEn; first by rewrite polyseqC eqxx.\nby rewrite (@PolyK 0) // -nth_last nth_mkseq size_mkseq.\nQed.\n\nLemma size_poly n E : size (\\poly_(i < n) E i) <= n.\nProof. by rewrite unlock (leq_trans (size_Poly _)) ?size_mkseq. Qed.\n\nLemma size_poly_eq n E : E n.-1 != 0 -> size (\\poly_(i < n) E i) = n.\nProof. by move/polyseq_poly->; apply: size_mkseq. Qed.\n\nLemma coef_poly n E k : (\\poly_(i < n) E i)`_k = (if k < n then E k else 0).\nProof.\nrewrite unlock coef_Poly.\nhave [lt_kn | le_nk] := ltnP k n; first by rewrite nth_mkseq.\nby rewrite nth_default // size_mkseq.\nQed.\n\nLemma lead_coef_poly n E :\n  n > 0 -> E n.-1 != 0 -> lead_coef (\\poly_(i < n) E i) = E n.-1.\nProof.\nby case: n => // n _ nzE; rewrite /lead_coef size_poly_eq // coef_poly leqnn.\nQed.\n\nLemma coefK p : \\poly_(i < size p) p`_i = p.\nProof.\nby apply/polyP=> i; rewrite coef_poly; case: ltnP => // /(nth_default 0)->.\nQed.\n\n(* Zmodule structure for polynomial *)\nDefinition add_poly_def p q := \\poly_(i < maxn (size p) (size q)) (p`_i + q`_i).\nFact add_poly_key : unit. Proof. by []. Qed.\nDefinition add_poly := locked_with add_poly_key add_poly_def.\nCanonical add_poly_unlockable := [unlockable fun add_poly].\n\nDefinition opp_poly_def p := \\poly_(i < size p) - p`_i.\nFact opp_poly_key : unit. Proof. by []. Qed.\nDefinition opp_poly := locked_with opp_poly_key opp_poly_def.\nCanonical opp_poly_unlockable := [unlockable fun opp_poly].\n\nFact coef_add_poly p q i : (add_poly p q)`_i = p`_i + q`_i.\nProof.\nrewrite unlock coef_poly; case: leqP => //.\nby rewrite geq_max => /andP[le_p_i le_q_i]; rewrite !nth_default ?add0r.\nQed.\n\nFact coef_opp_poly p i : (opp_poly p)`_i = - p`_i.\nProof.\nrewrite unlock coef_poly /=.\nby case: leqP => // le_p_i; rewrite nth_default ?oppr0.\nQed.\n\nFact add_polyA : associative add_poly.\nProof. by move=> p q r; apply/polyP=> i; rewrite !coef_add_poly addrA. Qed.\n\nFact add_polyC : commutative add_poly.\nProof. by move=> p q; apply/polyP=> i; rewrite !coef_add_poly addrC. Qed.\n\nFact add_poly0 : left_id 0%:P add_poly.\nProof.\nby move=> p; apply/polyP=> i; rewrite coef_add_poly coefC if_same add0r.\nQed.\n\nFact add_polyN : left_inverse 0%:P opp_poly add_poly.\nProof.\nmove=> p; apply/polyP=> i.\nby rewrite coef_add_poly coef_opp_poly coefC if_same addNr.\nQed.\n\nDefinition poly_zmodMixin :=\n  ZmodMixin add_polyA add_polyC add_poly0 add_polyN.\n\nCanonical poly_zmodType := Eval hnf in ZmodType {poly R} poly_zmodMixin.\nCanonical polynomial_zmodType :=\n  Eval hnf in ZmodType (polynomial R) poly_zmodMixin.\n\n(* Properties of the zero polynomial *)\nLemma polyC0 : 0%:P = 0 :> {poly R}. Proof. by []. Qed.\n\nLemma polyseq0 : (0 : {poly R}) = [::] :> seq R.\nProof. by rewrite polyseqC eqxx. Qed.\n\nLemma size_poly0 : size (0 : {poly R}) = 0%N.\nProof. by rewrite polyseq0. Qed.\n\nLemma coef0 i : (0 : {poly R})`_i = 0.\nProof. by rewrite coefC if_same. Qed.\n\nLemma lead_coef0 : lead_coef 0 = 0 :> R. Proof. exact: lead_coefC. Qed.\n\nLemma size_poly_eq0 p : (size p == 0%N) = (p == 0).\nProof. by rewrite size_eq0 -polyseq0. Qed.\n\nLemma size_poly_leq0 p : (size p <= 0) = (p == 0).\nProof. by rewrite leqn0 size_poly_eq0. Qed.\n\nLemma size_poly_leq0P p : reflect (p = 0) (size p <= 0%N).\nProof. by apply: (iffP idP); rewrite size_poly_leq0; move/eqP. Qed.\n\nLemma size_poly_gt0 p : (0 < size p) = (p != 0).\nProof. by rewrite lt0n size_poly_eq0. Qed.\n\nLemma gt_size_poly_neq0 p n : (size p > n)%N -> p != 0.\nProof. by move=> /(leq_ltn_trans _) h; rewrite -size_poly_eq0 lt0n_neq0 ?h. Qed.\n\nLemma nil_poly p : nilp p = (p == 0).\nProof. exact: size_poly_eq0. Qed.\n\nLemma poly0Vpos p : {p = 0} + {size p > 0}.\nProof. by rewrite lt0n size_poly_eq0; case: eqVneq; [left | right]. Qed.\n\nLemma polySpred p : p != 0 -> size p = (size p).-1.+1.\nProof. by rewrite -size_poly_eq0 -lt0n => /prednK. Qed.\n\nLemma lead_coef_eq0 p : (lead_coef p == 0) = (p == 0).\nProof.\nrewrite -nil_poly /lead_coef nth_last.\nby case: p => [[|x s] /= /negbTE // _]; rewrite eqxx.\nQed.\n\nLemma polyC_eq0 (c : R) : (c%:P == 0) = (c == 0).\nProof. by rewrite -nil_poly polyseqC; case: (c == 0). Qed.\n\nLemma size_poly1P p : reflect (exists2 c, c != 0 & p = c%:P) (size p == 1%N).\nProof.\napply: (iffP eqP) => [pC | [c nz_c ->]]; last by rewrite size_polyC nz_c.\nhave def_p: p = (p`_0)%:P by rewrite -size1_polyC ?pC.\nby exists p`_0; rewrite // -polyC_eq0 -def_p -size_poly_eq0 pC.\nQed.\n\nLemma size_polyC_leq1 (c : R) : (size c%:P <= 1)%N.\nProof. by rewrite size_polyC; case: (c == 0). Qed.\n\nLemma leq_sizeP p i : reflect (forall j, i <= j -> p`_j = 0) (size p <= i).\nProof.\napply: (iffP idP) => [hp j hij| hp].\n  by apply: nth_default; apply: leq_trans hij.\ncase p0: (p == 0); first by rewrite (eqP p0) size_poly0.\nmove: (lead_coef_eq0 p); rewrite p0 leqNgt; move/negbT; apply: contra => hs.\nby apply/eqP; apply: hp; rewrite -ltnS (ltn_predK hs).\nQed.\n\n(* Size, leading coef, morphism properties of coef *)\n\nLemma coefD p q i : (p + q)`_i = p`_i + q`_i.\nProof. exact: coef_add_poly. Qed.\n\nLemma coefN p i : (- p)`_i = - p`_i.\nProof. exact: coef_opp_poly. Qed.\n\nLemma coefB p q i : (p - q)`_i = p`_i - q`_i.\nProof. by rewrite coefD coefN. Qed.\n\nCanonical coefp_additive i :=\n  Additive ((fun p => (coefB p)^~ i) : additive (coefp i)).\n\nLemma coefMn p n i : (p *+ n)`_i = p`_i *+ n.\nProof. exact: (raddfMn (coefp_additive i)). Qed.\n\nLemma coefMNn p n i : (p *- n)`_i = p`_i *- n.\nProof. by rewrite coefN coefMn. Qed.\n\nLemma coef_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) k :\n  (\\sum_(i <- r | P i) F i)`_k = \\sum_(i <- r | P i) (F i)`_k.\nProof. exact: (raddf_sum (coefp_additive k)). Qed.\n\nLemma polyC_add : {morph polyC : a b / a + b}.\nProof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefD !coefC ?addr0. Qed.\n\nLemma polyC_opp : {morph polyC : c / - c}.\nProof. by move=> c; apply/polyP=> [[|i]]; rewrite coefN !coefC ?oppr0. Qed.\n\nLemma polyC_sub : {morph polyC : a b / a - b}.\nProof. by move=> a b; rewrite polyC_add polyC_opp. Qed.\n\nCanonical polyC_additive := Additive polyC_sub.\n\nLemma polyC_muln n : {morph polyC : c / c *+ n}.\nProof. exact: raddfMn. Qed.\n\nLemma size_opp p : size (- p) = size p.\nProof.\nby apply/eqP; rewrite eqn_leq -{3}(opprK p) -[-%R]/opp_poly unlock !size_poly.\nQed.\n\nLemma lead_coef_opp p : lead_coef (- p) = - lead_coef p.\nProof. by rewrite /lead_coef size_opp coefN. Qed.\n\nLemma size_add p q : size (p + q) <= maxn (size p) (size q).\nProof. by rewrite -[+%R]/add_poly unlock; apply: size_poly. Qed.\n\nLemma size_addl p q : size p > size q -> size (p + q) = size p.\nProof.\nmove=> ltqp; rewrite -[+%R]/add_poly unlock size_poly_eq (maxn_idPl (ltnW _))//.\nby rewrite addrC nth_default ?simp ?nth_last //; case: p ltqp => [[]].\nQed.\n\nLemma size_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) :\n  size (\\sum_(i <- r | P i) F i) <= \\max_(i <- r | P i) size (F i).\nProof.\nelim/big_rec2: _ => [|i p q _ IHp]; first by rewrite size_poly0.\nby rewrite -(maxn_idPr IHp) maxnA leq_max size_add.\nQed.\n\nLemma lead_coefDl p q : size p > size q -> lead_coef (p + q) = lead_coef p.\nProof.\nmove=> ltqp; rewrite /lead_coef coefD size_addl //.\nby rewrite addrC nth_default ?simp // -ltnS (ltn_predK ltqp).\nQed.\n\nLemma lead_coefDr p q : size q > size p -> lead_coef (p + q) = lead_coef q.\nProof. by move/lead_coefDl<-; rewrite addrC. Qed.\n\n(* Polynomial ring structure. *)\n\nDefinition mul_poly_def p q :=\n  \\poly_(i < (size p + size q).-1) (\\sum_(j < i.+1) p`_j * q`_(i - j)).\nFact mul_poly_key : unit. Proof. by []. Qed.\nDefinition mul_poly := locked_with mul_poly_key mul_poly_def.\nCanonical mul_poly_unlockable := [unlockable fun mul_poly].\n\nFact coef_mul_poly p q i :\n  (mul_poly p q)`_i = \\sum_(j < i.+1) p`_j * q`_(i - j)%N.\nProof.\nrewrite unlock coef_poly -subn1 ltn_subRL add1n; case: leqP => // le_pq_i1.\nrewrite big1 // => j _; have [lq_q_ij | gt_q_ij] := leqP (size q) (i - j).\n  by rewrite [q`__]nth_default ?mulr0.\nrewrite nth_default ?mul0r // -(leq_add2r (size q)) (leq_trans le_pq_i1) //.\nby rewrite -leq_subLR -subnSK.\nQed.\n\nFact coef_mul_poly_rev p q i :\n  (mul_poly p q)`_i = \\sum_(j < i.+1) p`_(i - j)%N * q`_j.\nProof.\nrewrite coef_mul_poly (reindex_inj rev_ord_inj) /=.\nby apply: eq_bigr => j _; rewrite (sub_ordK j).\nQed.\n\nFact mul_polyA : associative mul_poly.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coef_mul_poly coef_mul_poly_rev.\npose coef3 j k := p`_j * (q`_(i - j - k)%N * r`_k).\ntransitivity (\\sum_(j < i.+1) \\sum_(k < i.+1 | k <= i - j) coef3 j k).\n  apply: eq_bigr => /= j _; rewrite coef_mul_poly_rev big_distrr /=.\n  by rewrite (big_ord_narrow_leq (leq_subr _ _)).\nrewrite (exchange_big_dep predT) //=; apply: eq_bigr => k _.\ntransitivity (\\sum_(j < i.+1 | j <= i - k) coef3 j k).\n  apply: eq_bigl => j; rewrite -ltnS -(ltnS j) -!subSn ?leq_ord //.\n  by rewrite -subn_gt0 -(subn_gt0 j) -!subnDA addnC.\nrewrite (big_ord_narrow_leq (leq_subr _ _)) coef_mul_poly big_distrl /=.\nby apply: eq_bigr => j _; rewrite /coef3 -!subnDA addnC mulrA.\nQed.\n\nFact mul_1poly : left_id 1%:P mul_poly.\nProof.\nmove=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nFact mul_poly1 : right_id 1%:P mul_poly.\nProof.\nmove=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nFact mul_polyDl : left_distributive mul_poly +%R.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split.\nby apply: eq_bigr => j _; rewrite coefD mulrDl.\nQed.\n\nFact mul_polyDr : right_distributive mul_poly +%R.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split.\nby apply: eq_bigr => j _; rewrite coefD mulrDr.\nQed.\n\nFact poly1_neq0 : 1%:P != 0 :> {poly R}.\nProof. by rewrite polyC_eq0 oner_neq0. Qed.\n\nDefinition poly_ringMixin :=\n  RingMixin mul_polyA mul_1poly mul_poly1 mul_polyDl mul_polyDr poly1_neq0.\n\nCanonical poly_ringType := Eval hnf in RingType {poly R} poly_ringMixin.\nCanonical polynomial_ringType :=\n  Eval hnf in RingType (polynomial R) poly_ringMixin.\n\nLemma polyC1 : 1%:P = 1 :> {poly R}. Proof. by []. Qed.\n\nLemma polyseq1 : (1 : {poly R}) = [:: 1] :> seq R.\nProof. by rewrite polyseqC oner_neq0. Qed.\n\nLemma size_poly1 : size (1 : {poly R}) = 1%N.\nProof. by rewrite polyseq1. Qed.\n\nLemma coef1 i : (1 : {poly R})`_i = (i == 0%N)%:R.\nProof. by case: i => [|i]; rewrite polyseq1 /= ?nth_nil. Qed.\n\nLemma lead_coef1 : lead_coef 1 = 1 :> R. Proof. exact: lead_coefC. Qed.\n\nLemma coefM p q i : (p * q)`_i = \\sum_(j < i.+1) p`_j * q`_(i - j)%N.\nProof. exact: coef_mul_poly. Qed.\n\nLemma coefMr p q i : (p * q)`_i = \\sum_(j < i.+1) p`_(i - j)%N * q`_j.\nProof. exact: coef_mul_poly_rev. Qed.\n\nLemma size_mul_leq p q : size (p * q) <= (size p + size q).-1.\nProof. by rewrite -[*%R]/mul_poly unlock size_poly. Qed.\n\nLemma mul_lead_coef p q :\n  lead_coef p * lead_coef q = (p * q)`_(size p + size q).-2.\nProof.\npose dp := (size p).-1; pose dq := (size q).-1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 !mul0r coef0.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite lead_coef0 !mulr0 coef0.\nhave ->: (size p + size q).-2 = (dp + dq)%N.\n  by do 2!rewrite polySpred // addSn addnC.\nhave lt_p_pq: dp < (dp + dq).+1 by rewrite ltnS leq_addr.\nrewrite coefM (bigD1 (Ordinal lt_p_pq)) ?big1 ?simp ?addKn //= => i.\nrewrite -val_eqE neq_ltn /= => /orP[lt_i_p | gt_i_p]; last first.\n  by rewrite nth_default ?mul0r //; rewrite -polySpred in gt_i_p.\nrewrite [q`__]nth_default ?mulr0 //= -subSS -{1}addnS -polySpred //.\nby rewrite addnC -addnBA ?leq_addr.\nQed.\n\nLemma size_proper_mul p q :\n  lead_coef p * lead_coef q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\napply: contraNeq; rewrite mul_lead_coef eqn_leq size_mul_leq -ltnNge => lt_pq.\nby rewrite nth_default // -subn1 -(leq_add2l 1) -leq_subLR leq_sub2r.\nQed.\n\nLemma lead_coef_proper_mul p q :\n  let c := lead_coef p * lead_coef q in c != 0 -> lead_coef (p * q) = c.\nProof. by move=> /= nz_c; rewrite mul_lead_coef -size_proper_mul. Qed.\n\nLemma size_prod_leq (I : finType) (P : pred I) (F : I -> {poly R}) :\n  size (\\prod_(i | P i) F i) <= (\\sum_(i | P i) size (F i)).+1 - #|P|.\nProof.\nrewrite -sum1_card.\nelim/big_rec3: _ => [|i n m p _ IHp]; first by rewrite size_poly1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0.\nrewrite (leq_trans (size_mul_leq _ _)) // subnS -!subn1 leq_sub2r //.\nrewrite -addnS -addnBA ?leq_add2l // ltnW // -subn_gt0 (leq_trans _ IHp) //.\nby rewrite polySpred.\nQed.\n\nLemma coefCM c p i : (c%:P * p)`_i = c * p`_i.\nProof.\nrewrite coefM big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nLemma coefMC c p i : (p * c%:P)`_i = p`_i * c.\nProof.\nrewrite coefMr big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nLemma polyC_mul : {morph polyC : a b / a * b}.\nProof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefCM !coefC ?simp. Qed.\n\nFact polyC_multiplicative : multiplicative polyC.\nProof. by split; first apply: polyC_mul. Qed.\nCanonical polyC_rmorphism := AddRMorphism polyC_multiplicative.\n\nLemma polyC_exp n : {morph polyC : c / c ^+ n}.\nProof. exact: rmorphX. Qed.\n\nLemma size_exp_leq p n : size (p ^+ n) <= ((size p).-1 * n).+1.\nProof.\nelim: n => [|n IHn]; first by rewrite size_poly1.\nhave [-> | nzp] := poly0Vpos p; first by rewrite exprS mul0r size_poly0.\nrewrite exprS (leq_trans (size_mul_leq _ _)) //.\nby rewrite -{1}(prednK nzp) mulnS -addnS leq_add2l.\nQed.\n\nLemma size_Msign p n : size ((-1) ^+ n * p) = size p.\nProof.\nby rewrite -signr_odd; case: (odd n); rewrite ?mul1r // mulN1r size_opp.\nQed.\n\nFact coefp0_multiplicative : multiplicative (coefp 0 : {poly R} -> R).\nProof.\nsplit=> [p q|]; last by rewrite polyCK.\nby rewrite [coefp 0 _]coefM big_ord_recl big_ord0 addr0.\nQed.\n\nCanonical coefp0_rmorphism := AddRMorphism coefp0_multiplicative.\n\n(* Algebra structure of polynomials. *)\nDefinition scale_poly_def a (p : {poly R}) := \\poly_(i < size p) (a * p`_i).\nFact scale_poly_key : unit. Proof. by []. Qed.\nDefinition scale_poly := locked_with scale_poly_key scale_poly_def.\nCanonical scale_poly_unlockable := [unlockable fun scale_poly].\n\nFact scale_polyE a p : scale_poly a p = a%:P * p.\nProof.\napply/polyP=> n; rewrite unlock coef_poly coefCM.\nby case: leqP => // le_p_n; rewrite nth_default ?mulr0.\nQed.\n\nFact scale_polyA a b p : scale_poly a (scale_poly b p) = scale_poly (a * b) p.\nProof. by rewrite !scale_polyE mulrA polyC_mul. Qed.\n\nFact scale_1poly : left_id 1 scale_poly.\nProof. by move=> p; rewrite scale_polyE mul1r. Qed.\n\nFact scale_polyDr a : {morph scale_poly a : p q / p + q}.\nProof. by move=> p q; rewrite !scale_polyE mulrDr. Qed.\n\nFact scale_polyDl p : {morph scale_poly^~ p : a b / a + b}.\nProof. by move=> a b /=; rewrite !scale_polyE raddfD mulrDl. Qed.\n\nFact scale_polyAl a p q : scale_poly a (p * q) = scale_poly a p * q.\nProof. by rewrite !scale_polyE mulrA. Qed.\n\nDefinition poly_lmodMixin :=\n  LmodMixin scale_polyA scale_1poly scale_polyDr scale_polyDl.\n\nCanonical poly_lmodType :=\n  Eval hnf in LmodType R {poly R} poly_lmodMixin.\nCanonical polynomial_lmodType :=\n  Eval hnf in LmodType R (polynomial R) poly_lmodMixin.\nCanonical poly_lalgType :=\n  Eval hnf in LalgType R {poly R} scale_polyAl.\nCanonical polynomial_lalgType :=\n  Eval hnf in LalgType R (polynomial R) scale_polyAl.\n\nLemma mul_polyC a p : a%:P * p = a *: p.\nProof. by rewrite -scale_polyE. Qed.\n\nLemma alg_polyC a : a%:A = a%:P :> {poly R}.\nProof. by rewrite -mul_polyC mulr1. Qed.\n\nLemma coefZ a p i : (a *: p)`_i = a * p`_i.\nProof.\nrewrite -[*:%R]/scale_poly unlock coef_poly.\nby case: leqP => // le_p_n; rewrite nth_default ?mulr0.\nQed.\n\nLemma size_scale_leq a p : size (a *: p) <= size p.\nProof. by rewrite -[*:%R]/scale_poly unlock size_poly. Qed.\n\nCanonical coefp_linear i : {scalar {poly R}} :=\n  AddLinear ((fun a => (coefZ a) ^~ i) : scalable_for *%R (coefp i)).\nCanonical coefp0_lrmorphism := [lrmorphism of coefp 0].\n\n(* The indeterminate, at last! *)\nDefinition polyX_def := Poly [:: 0; 1].\nFact polyX_key : unit. Proof. by []. Qed.\nDefinition polyX : {poly R} := locked_with polyX_key polyX_def.\nCanonical polyX_unlockable := [unlockable of polyX].\nLocal Notation \"'X\" := polyX.\n\nLemma polyseqX : 'X = [:: 0; 1] :> seq R.\nProof. by rewrite unlock !polyseq_cons nil_poly eqxx /= polyseq1. Qed.\n\nLemma size_polyX : size 'X = 2. Proof. by rewrite polyseqX. Qed.\n\nLemma polyX_eq0 : ('X == 0) = false.\nProof. by rewrite -size_poly_eq0 size_polyX. Qed.\n\nLemma coefX i : 'X`_i = (i == 1%N)%:R.\nProof. by case: i => [|[|i]]; rewrite polyseqX //= nth_nil. Qed.\n\nLemma lead_coefX : lead_coef 'X = 1.\nProof. by rewrite /lead_coef polyseqX. Qed.\n\nLemma commr_polyX p : GRing.comm p 'X.\nProof.\napply/polyP=> i; rewrite coefMr coefM.\nby apply: eq_bigr => j _; rewrite coefX commr_nat.\nQed.\n\nLemma coefMX p i : (p * 'X)`_i = (if (i == 0)%N then 0 else p`_i.-1).\nProof.\nrewrite coefMr big_ord_recl coefX ?simp.\ncase: i => [|i]; rewrite ?big_ord0 //= big_ord_recl polyseqX subn1 /=.\nby rewrite big1 ?simp // => j _; rewrite nth_nil !simp.\nQed.\n\nLemma coefXM p i : ('X * p)`_i = (if (i == 0)%N then 0 else p`_i.-1).\nProof. by rewrite -commr_polyX coefMX. Qed.\n\nLemma cons_poly_def p a : cons_poly a p = p * 'X + a%:P.\nProof.\napply/polyP=> i; rewrite coef_cons coefD coefMX coefC.\nby case: ifP; rewrite !simp.\nQed.\n\nLemma poly_ind (K : {poly R} -> Type) :\n  K 0 -> (forall p c, K p -> K (p * 'X + c%:P)) -> (forall p, K p).\nProof.\nmove=> K0 Kcons p; rewrite -[p]polyseqK.\nby elim: {p}(p : seq R) => //= p c IHp; rewrite cons_poly_def; apply: Kcons.\nQed.\n\nLemma polyseqXsubC a : 'X - a%:P = [:: - a; 1] :> seq R.\nProof.\nby rewrite -['X]mul1r -polyC_opp -cons_poly_def polyseq_cons polyseq1.\nQed.\n\nLemma size_XsubC a : size ('X - a%:P) = 2%N.\nProof. by rewrite polyseqXsubC. Qed.\n\nLemma size_XaddC b : size ('X + b%:P) = 2.\nProof. by rewrite -[b]opprK rmorphN size_XsubC. Qed.\n\nLemma lead_coefXsubC a : lead_coef ('X - a%:P) = 1.\nProof. by rewrite lead_coefE polyseqXsubC. Qed.\n\nLemma polyXsubC_eq0 a : ('X - a%:P == 0) = false.\nProof. by rewrite -nil_poly polyseqXsubC. Qed.\n\nLemma size_MXaddC p c :\n  size (p * 'X + c%:P) = (if (p == 0) && (c == 0) then 0%N else (size p).+1).\nProof. by rewrite -cons_poly_def size_cons_poly nil_poly. Qed.\n\nLemma polyseqMX p : p != 0 -> p * 'X = 0 :: p :> seq R.\nProof.\nby move=> nz_p; rewrite -[p * _]addr0 -cons_poly_def polyseq_cons nil_poly nz_p.\nQed.\n\nLemma size_mulX p : p != 0 -> size (p * 'X) = (size p).+1.\nProof. by move/polyseqMX->. Qed.\n\nLemma lead_coefMX p : lead_coef (p * 'X) = lead_coef p.\nProof.\nhave [-> | nzp] := eqVneq p 0; first by rewrite mul0r.\nby rewrite /lead_coef !nth_last polyseqMX.\nQed.\n\nLemma size_XmulC a : a != 0 -> size ('X * a%:P) = 2.\nProof.\nby move=> nz_a; rewrite -commr_polyX size_mulX ?polyC_eq0 ?size_polyC nz_a.\nQed.\n\nLocal Notation \"''X^' n\" := ('X ^+ n).\n\nLemma coefXn n i : 'X^n`_i = (i == n)%:R.\nProof.\nby elim: n i => [|n IHn] [|i]; rewrite ?coef1 // exprS coefXM ?IHn.\nQed.\n\nLemma polyseqXn n : 'X^n = rcons (nseq n 0) 1 :> seq R.\nProof.\nelim: n => [|n IHn]; rewrite ?polyseq1 // exprSr.\nby rewrite polyseqMX -?size_poly_eq0 IHn ?size_rcons.\nQed.\n\nLemma size_polyXn n : size 'X^n = n.+1.\nProof. by rewrite polyseqXn size_rcons size_nseq. Qed.\n\nLemma commr_polyXn p n : GRing.comm p 'X^n.\nProof. by apply: commrX; apply: commr_polyX. Qed.\n\nLemma lead_coefXn n : lead_coef 'X^n = 1.\nProof. by rewrite /lead_coef nth_last polyseqXn last_rcons. Qed.\n\nLemma polyseqMXn n p : p != 0 -> p * 'X^n = ncons n 0 p :> seq R.\nProof.\ncase: n => [|n] nz_p; first by rewrite mulr1.\nelim: n => [|n IHn]; first exact: polyseqMX.\nby rewrite exprSr mulrA polyseqMX -?nil_poly IHn.\nQed.\n\nLemma coefMXn n p i : (p * 'X^n)`_i = if i < n then 0 else p`_(i - n).\nProof.\nhave [-> | /polyseqMXn->] := eqVneq p 0; last exact: nth_ncons.\nby rewrite mul0r !coef0 if_same.\nQed.\n\nLemma coefXnM n p i : ('X^n * p)`_i = if i < n then 0 else p`_(i - n).\nProof. by rewrite -commr_polyXn coefMXn. Qed.\n\n(* Expansion of a polynomial as an indexed sum *)\nLemma poly_def n E : \\poly_(i < n) E i = \\sum_(i < n) E i *: 'X^i.\nProof.\nrewrite unlock; elim: n => [|n IHn] in E *; first by rewrite big_ord0.\nrewrite big_ord_recl /= cons_poly_def addrC expr0 alg_polyC.\ncongr (_ + _); rewrite (iota_addl 1 0) -map_comp IHn big_distrl /=.\nby apply: eq_bigr => i _; rewrite -scalerAl exprSr.\nQed.\n\n(* Monic predicate *)\nDefinition monic := [qualify p | lead_coef p == 1].\nFact monic_key : pred_key monic. Proof. by []. Qed.\nCanonical monic_keyed := KeyedQualifier monic_key.\n\nLemma monicE p : (p \\is monic) = (lead_coef p == 1). Proof. by []. Qed.\nLemma monicP p : reflect (lead_coef p = 1) (p \\is monic).\nProof. exact: eqP. Qed.\n\nLemma monic1 : 1 \\is monic. Proof. exact/eqP/lead_coef1. Qed.\nLemma monicX : 'X \\is monic. Proof. exact/eqP/lead_coefX. Qed.\nLemma monicXn n : 'X^n \\is monic. Proof. exact/eqP/lead_coefXn. Qed.\n\nLemma monic_neq0 p : p \\is monic -> p != 0.\nProof. by rewrite -lead_coef_eq0 => /eqP->; apply: oner_neq0. Qed.\n\nLemma lead_coef_monicM p q : p \\is monic -> lead_coef (p * q) = lead_coef q.\nProof.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite mulr0.\nby move/monicP=> mon_p; rewrite lead_coef_proper_mul mon_p mul1r ?lead_coef_eq0.\nQed.\n\nLemma lead_coef_Mmonic p q : q \\is monic -> lead_coef (p * q) = lead_coef p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mul0r.\nby move/monicP=> mon_q; rewrite lead_coef_proper_mul mon_q mulr1 ?lead_coef_eq0.\nQed.\n\nLemma size_monicM p q :\n  p \\is monic -> q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nmove/monicP=> mon_p nz_q.\nby rewrite size_proper_mul // mon_p mul1r lead_coef_eq0.\nQed.\n\nLemma size_Mmonic p q :\n  p != 0 -> q \\is monic -> size (p * q) = (size p + size q).-1.\nProof.\nmove=> nz_p /monicP mon_q.\nby rewrite size_proper_mul // mon_q mulr1 lead_coef_eq0.\nQed.\n\nLemma monicMl p q : p \\is monic -> (p * q \\is monic) = (q \\is monic).\nProof. by move=> mon_p; rewrite !monicE lead_coef_monicM. Qed.\n\nLemma monicMr p q : q \\is monic -> (p * q \\is monic) = (p \\is monic).\nProof. by move=> mon_q; rewrite !monicE lead_coef_Mmonic. Qed.\n\nFact monic_mulr_closed : mulr_closed monic.\nProof. by split=> [|p q mon_p]; rewrite (monic1, monicMl). Qed.\nCanonical monic_mulrPred := MulrPred monic_mulr_closed.\n\nLemma monic_exp p n : p \\is monic -> p ^+ n \\is monic.\nProof. exact: rpredX. Qed.\n\nLemma monic_prod I rI (P : pred I) (F : I -> {poly R}):\n  (forall i, P i -> F i \\is monic) -> \\prod_(i <- rI | P i) F i \\is monic.\nProof. exact: rpred_prod. Qed.\n\nLemma monicXsubC c : 'X - c%:P \\is monic.\nProof. exact/eqP/lead_coefXsubC. Qed.\n\nLemma monic_prod_XsubC I rI (P : pred I) (F : I -> R) :\n  \\prod_(i <- rI | P i) ('X - (F i)%:P) \\is monic.\nProof. by apply: monic_prod => i _; apply: monicXsubC. Qed.\n\nLemma size_prod_XsubC I rI (F : I -> R) :\n  size (\\prod_(i <- rI) ('X - (F i)%:P)) = (size rI).+1.\nProof.\nelim: rI => [|i r /= <-]; rewrite ?big_nil ?size_poly1 // big_cons.\nrewrite size_monicM ?monicXsubC ?monic_neq0 ?monic_prod_XsubC //.\nby rewrite size_XsubC.\nQed.\n\nLemma size_exp_XsubC n a : size (('X - a%:P) ^+ n) = n.+1.\nProof.\nrewrite -[n]card_ord -prodr_const -big_filter size_prod_XsubC.\nby have [e _ _ [_ ->]] := big_enumP.\nQed.\n\n(* Some facts about regular elements. *)\n\nLemma lreg_lead p : GRing.lreg (lead_coef p) -> GRing.lreg p.\nProof.\nmove/mulrI_eq0=> reg_p; apply: mulrI0_lreg => q /eqP; apply: contraTeq => nz_q.\nby rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0.\nQed.\n\nLemma rreg_lead p : GRing.rreg (lead_coef p) -> GRing.rreg p.\nProof.\nmove/mulIr_eq0=> reg_p; apply: mulIr0_rreg => q /eqP; apply: contraTeq => nz_q.\nby rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0.\nQed.\n\nLemma lreg_lead0 p : GRing.lreg (lead_coef p) -> p != 0.\nProof. by move/lreg_neq0; rewrite lead_coef_eq0. Qed.\n\nLemma rreg_lead0 p : GRing.rreg (lead_coef p) -> p != 0.\nProof. by move/rreg_neq0; rewrite lead_coef_eq0. Qed.\n\nLemma lreg_size c p : GRing.lreg c -> size (c *: p) = size p.\nProof.\nmove=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite scaler0.\nrewrite -mul_polyC size_proper_mul; first by rewrite size_polyC lreg_neq0.\nby rewrite lead_coefC mulrI_eq0 ?lead_coef_eq0.\nQed.\n\nLemma lreg_polyZ_eq0 c p : GRing.lreg c -> (c *: p == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /lreg_size->. Qed.\n\nLemma lead_coef_lreg c p :\n  GRing.lreg c -> lead_coef (c *: p) = c * lead_coef p.\nProof. by move=> reg_c; rewrite !lead_coefE coefZ lreg_size. Qed.\n\nLemma rreg_size c p : GRing.rreg c -> size (p * c%:P) =  size p.\nProof.\nmove=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r.\nrewrite size_proper_mul; first by rewrite size_polyC rreg_neq0 ?addn1.\nby rewrite lead_coefC mulIr_eq0 ?lead_coef_eq0.\nQed.\n\nLemma rreg_polyMC_eq0 c p : GRing.rreg c -> (p * c%:P == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /rreg_size->. Qed.\n\nLemma rreg_div0 q r d :\n    GRing.rreg (lead_coef d) -> size r < size d ->\n  (q * d + r == 0) = (q == 0) && (r == 0).\nProof.\nmove=> reg_d lt_r_d; rewrite addrC addr_eq0.\nhave [-> | nz_q] := altP (q =P 0); first by rewrite mul0r oppr0.\napply: contraTF lt_r_d => /eqP->; rewrite -leqNgt size_opp.\nrewrite size_proper_mul ?mulIr_eq0 ?lead_coef_eq0 //.\nby rewrite (polySpred nz_q) leq_addl.\nQed.\n\nLemma monic_comreg p :\n  p \\is monic -> GRing.comm p (lead_coef p)%:P /\\ GRing.rreg (lead_coef p).\nProof. by move/monicP->; split; [apply: commr1 | apply: rreg1]. Qed.\n\n(* Horner evaluation of polynomials *)\nImplicit Types s rs : seq R.\nFixpoint horner_rec s x := if s is a :: s' then horner_rec s' x * x + a else 0.\nDefinition horner p := horner_rec p.\n\nLocal Notation \"p .[ x ]\" := (horner p x) : ring_scope.\n\nLemma horner0 x : (0 : {poly R}).[x] = 0.\nProof. by rewrite /horner polyseq0. Qed.\n\nLemma hornerC c x : (c%:P).[x] = c.\nProof. by rewrite /horner polyseqC; case: eqP; rewrite /= ?simp. Qed.\n\nLemma hornerX x : 'X.[x] = x.\nProof. by rewrite /horner polyseqX /= !simp. Qed.\n\nLemma horner_cons p c x : (cons_poly c p).[x] = p.[x] * x + c.\nProof.\nrewrite /horner polyseq_cons; case: nilP => //= ->.\nby rewrite !simp -/(_.[x]) hornerC.\nQed.\n\nLemma horner_coef0 p : p.[0] = p`_0.\nProof. by rewrite /horner; case: (p : seq R) => //= c p'; rewrite !simp. Qed.\n\nLemma hornerMXaddC p c x : (p * 'X + c%:P).[x] = p.[x] * x + c.\nProof. by rewrite -cons_poly_def horner_cons. Qed.\n\nLemma hornerMX p x : (p * 'X).[x] = p.[x] * x.\nProof. by rewrite -[p * 'X]addr0 hornerMXaddC addr0. Qed.\n\nLemma horner_Poly s x : (Poly s).[x] = horner_rec s x.\nProof. by elim: s => [|a s /= <-]; rewrite (horner0, horner_cons). Qed.\n\nLemma horner_coef p x : p.[x] = \\sum_(i < size p) p`_i * x ^+ i.\nProof.\nrewrite /horner.\nelim: {p}(p : seq R) => /= [|a s ->]; first by rewrite big_ord0.\nrewrite big_ord_recl simp addrC big_distrl /=.\nby congr (_ + _); apply: eq_bigr => i _; rewrite -mulrA exprSr.\nQed.\n\nLemma horner_coef_wide n p x :\n  size p <= n -> p.[x] = \\sum_(i < n) p`_i * x ^+ i.\nProof.\nmove=> le_p_n.\nrewrite horner_coef (big_ord_widen n (fun i => p`_i * x ^+ i)) // big_mkcond.\nby apply: eq_bigr => i _; case: ltnP => // le_p_i; rewrite nth_default ?simp.\nQed.\n\nLemma horner_poly n E x : (\\poly_(i < n) E i).[x] = \\sum_(i < n) E i * x ^+ i.\nProof.\nrewrite (@horner_coef_wide n) ?size_poly //.\nby apply: eq_bigr => i _; rewrite coef_poly ltn_ord.\nQed.\n\nLemma hornerN p x : (- p).[x] = - p.[x].\nProof.\nrewrite -[-%R]/opp_poly unlock horner_poly horner_coef -sumrN /=.\nby apply: eq_bigr => i _; rewrite mulNr.\nQed.\n\nLemma hornerD p q x : (p + q).[x] = p.[x] + q.[x].\nProof.\nrewrite -[+%R]/add_poly unlock horner_poly; set m := maxn _ _.\nrewrite !(@horner_coef_wide m) ?leq_max ?leqnn ?orbT // -big_split /=.\nby apply: eq_bigr => i _; rewrite -mulrDl.\nQed.\n\nLemma hornerXsubC a x : ('X - a%:P).[x] = x - a.\nProof. by rewrite hornerD hornerN hornerC hornerX. Qed.\n\nLemma horner_sum I (r : seq I) (P : pred I) F x :\n  (\\sum_(i <- r | P i) F i).[x] = \\sum_(i <- r | P i) (F i).[x].\nProof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (horner0, hornerD). Qed.\n\nLemma hornerCM a p x : (a%:P * p).[x] = a * p.[x].\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(mulr0, horner0).\nby rewrite mulrDr mulrA -polyC_mul !hornerMXaddC IHp mulrDr mulrA.\nQed.\n\nLemma hornerZ c p x : (c *: p).[x] = c * p.[x].\nProof. by rewrite -mul_polyC hornerCM. Qed.\n\nLemma hornerMn n p x : (p *+ n).[x] = p.[x] *+ n.\nProof. by elim: n => [| n IHn]; rewrite ?horner0 // !mulrS hornerD IHn. Qed.\n\nDefinition comm_coef p x := forall i, p`_i * x = x * p`_i.\n\nDefinition comm_poly p x := x * p.[x] = p.[x] * x.\n\nLemma comm_coef_poly p x : comm_coef p x -> comm_poly p x.\nProof.\nmove=> cpx; rewrite /comm_poly !horner_coef big_distrl big_distrr /=.\nby apply: eq_bigr => i _; rewrite /= mulrA -cpx -!mulrA commrX.\nQed.\n\nLemma comm_poly0 x : comm_poly 0 x.\nProof. by rewrite /comm_poly !horner0 !simp. Qed.\n\nLemma comm_poly1 x : comm_poly 1 x.\nProof. by rewrite /comm_poly !hornerC !simp. Qed.\n\nLemma comm_polyX x : comm_poly 'X x.\nProof. by rewrite /comm_poly !hornerX. Qed.\n\nLemma hornerM_comm p q x : comm_poly q x -> (p * q).[x] = p.[x] * q.[x].\nProof.\nmove=> comm_qx.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(simp, horner0).\nrewrite mulrDl hornerD hornerCM -mulrA -commr_polyX mulrA hornerMX.\nby rewrite {}IHp -mulrA -comm_qx mulrA -mulrDl hornerMXaddC.\nQed.\n\nLemma horner_exp_comm p x n : comm_poly p x -> (p ^+ n).[x] = p.[x] ^+ n.\nProof.\nmove=> comm_px; elim: n => [|n IHn]; first by rewrite hornerC.\nby rewrite !exprSr -IHn hornerM_comm.\nQed.\n\nLemma hornerXn x n : ('X^n).[x] = x ^+ n.\nProof. by rewrite horner_exp_comm /comm_poly hornerX. Qed.\n\nDefinition hornerE_comm :=\n  (hornerD, hornerN, hornerX, hornerC, horner_cons,\n   simp, hornerCM, hornerZ,\n   (fun p x => hornerM_comm p (comm_polyX x))).\n\nDefinition root p : pred R := fun x => p.[x] == 0.\n\nLemma mem_root p x : x \\in root p = (p.[x] == 0).\nProof. by []. Qed.\n\nLemma rootE p x : (root p x = (p.[x] == 0)) * ((x \\in root p) = (p.[x] == 0)).\nProof. by []. Qed.\n\nLemma rootP p x : reflect (p.[x] = 0) (root p x).\nProof. exact: eqP. Qed.\n\nLemma rootPt p x : reflect (p.[x] == 0) (root p x).\nProof. exact: idP. Qed.\n\nLemma rootPf p x : reflect ((p.[x] == 0) = false) (~~ root p x).\nProof. exact: negPf. Qed.\n\nLemma rootC a x : root a%:P x = (a == 0).\nProof. by rewrite rootE hornerC. Qed.\n\nLemma root0 x : root 0 x.\nProof. by rewrite rootC. Qed.\n\nLemma root1 x : ~~ root 1 x.\nProof. by rewrite rootC oner_eq0. Qed.\n\nLemma rootX x : root 'X x = (x == 0).\nProof. by rewrite rootE hornerX. Qed.\n\nLemma rootN p x : root (- p) x = root p x.\nProof. by rewrite rootE hornerN oppr_eq0. Qed.\n\nLemma root_size_gt1 a p : p != 0 -> root p a -> 1 < size p.\nProof.\nrewrite ltnNge => nz_p; apply: contraL => /size1_polyC Dp.\nby rewrite Dp rootC -polyC_eq0 -Dp.\nQed.\n\nLemma root_XsubC a x : root ('X - a%:P) x = (x == a).\nProof. by rewrite rootE hornerXsubC subr_eq0. Qed.\n\nLemma root_XaddC a x : root ('X + a%:P) x = (x == - a).\nProof. by rewrite -root_XsubC rmorphN opprK. Qed.\n\nTheorem factor_theorem p a : reflect (exists q, p = q * ('X - a%:P)) (root p a).\nProof.\napply: (iffP eqP) => [pa0 | [q ->]]; last first.\n  by rewrite hornerM_comm /comm_poly hornerXsubC subrr ?simp.\nexists (\\poly_(i < size p) horner_rec (drop i.+1 p) a).\napply/polyP=> i; rewrite mulrBr coefB coefMX coefMC !coef_poly.\napply: canRL (addrK _) _; rewrite addrC; have [le_p_i | lt_i_p] := leqP.\n  rewrite nth_default // !simp drop_oversize ?if_same //.\n  exact: leq_trans (leqSpred _).\ncase: i => [|i] in lt_i_p *; last by rewrite ltnW // (drop_nth 0 lt_i_p).\nby rewrite drop1 /= -{}pa0 /horner; case: (p : seq R) lt_i_p.\nQed.\n\nLemma multiplicity_XsubC p a :\n  {m | exists2 q, (p != 0) ==> ~~ root q a & p = q * ('X - a%:P) ^+ m}.\nProof.\nhave [n le_p_n] := ubnP (size p); elim: n => // n IHn in p le_p_n *.\nhave [-> | nz_p /=] := eqVneq p 0; first by exists 0%N, 0; rewrite ?mul0r.\nhave [/sig_eqW[p1 Dp] | nz_pa] := altP (factor_theorem p a); last first.\n  by exists 0%N, p; rewrite ?mulr1.\nhave nz_p1: p1 != 0 by apply: contraNneq nz_p => p1_0; rewrite Dp p1_0 mul0r.\nhave /IHn[m /sig2_eqW[q nz_qa Dp1]]: size p1 < n.\n  by rewrite Dp size_Mmonic ?monicXsubC // size_XsubC addn2 in le_p_n. \nby exists m.+1, q; [rewrite nz_p1 in nz_qa | rewrite exprSr mulrA -Dp1].\nQed.\n\n(* Roots of unity. *)\n\nLemma size_Xn_sub_1 n : n > 0 -> size ('X^n - 1 : {poly R}) = n.+1.\nProof.\nby move=> n_gt0; rewrite size_addl size_polyXn // size_opp size_poly1.\nQed.\n\nLemma monic_Xn_sub_1 n : n > 0 -> 'X^n - 1 \\is monic.\nProof.\nmove=> n_gt0; rewrite monicE lead_coefE size_Xn_sub_1 // coefB.\nby rewrite coefXn coef1 eqxx eqn0Ngt n_gt0 subr0.\nQed.\n\nDefinition root_of_unity n : pred R := root ('X^n - 1).\nLocal Notation \"n .-unity_root\" := (root_of_unity n) : ring_scope.\n\nLemma unity_rootE n z : n.-unity_root z = (z ^+ n == 1).\nProof.\nby rewrite /root_of_unity rootE hornerD hornerN hornerXn hornerC subr_eq0.\nQed.\n\nLemma unity_rootP n z : reflect (z ^+ n = 1) (n.-unity_root z).\nProof. by rewrite unity_rootE; apply: eqP. Qed.\n\nDefinition primitive_root_of_unity n z :=\n  (n > 0) && [forall i : 'I_n, i.+1.-unity_root z == (i.+1 == n)].\nLocal Notation \"n .-primitive_root\" := (primitive_root_of_unity n) : ring_scope.\n\nLemma prim_order_exists n z :\n  n > 0 -> z ^+ n = 1 -> {m | m.-primitive_root z & (m %| n)}.\nProof.\nmove=> n_gt0 zn1.\nhave: exists m, (m > 0) && (z ^+ m == 1) by exists n; rewrite n_gt0 /= zn1.\ncase/ex_minnP=> m /andP[m_gt0 /eqP zm1] m_min.\nexists m.\n  apply/andP; split=> //; apply/eqfunP=> [[i]] /=.\n  rewrite leq_eqVlt unity_rootE.\n  case: eqP => [-> _ | _]; first by rewrite zm1 eqxx.\n  by apply: contraTF => zi1; rewrite -leqNgt m_min.\nhave: n %% m < m by rewrite ltn_mod.\napply: contraLR; rewrite -lt0n -leqNgt => nm_gt0; apply: m_min.\nby rewrite nm_gt0 /= expr_mod ?zn1.\nQed.\n\nSection OnePrimitive.\n\nVariables (n : nat) (z : R).\nHypothesis prim_z : n.-primitive_root z.\n\nLemma prim_order_gt0 : n > 0. Proof. by case/andP: prim_z. Qed.\nLet n_gt0 := prim_order_gt0.\n\nLemma prim_expr_order : z ^+ n = 1.\nProof.\ncase/andP: prim_z => _; rewrite -(prednK n_gt0) => /forallP/(_ ord_max).\nby rewrite unity_rootE eqxx eqb_id => /eqP.\nQed.\n\nLemma prim_expr_mod i : z ^+ (i %% n) = z ^+ i.\nProof. exact: expr_mod prim_expr_order. Qed.\n\nLemma prim_order_dvd i : (n %| i) = (z ^+ i == 1).\nProof.\nmove: n_gt0; rewrite -prim_expr_mod /dvdn -(ltn_mod i).\ncase: {i}(i %% n)%N => [|i] lt_i; first by rewrite !eqxx.\ncase/andP: prim_z => _ /forallP/(_ (Ordinal (ltnW lt_i))).\nby move/eqP; rewrite unity_rootE eqn_leq andbC leqNgt lt_i.\nQed.\n\nLemma eq_prim_root_expr i j : (z ^+ i == z ^+ j) = (i == j %[mod n]).\nProof.\nwlog le_ji: i j / j <= i.\n  move=> IH; case: (leqP j i); last move/ltnW; move/IH=> //.\n  by rewrite eq_sym (eq_sym (j %% n)%N).\nrewrite -{1}(subnKC le_ji) exprD -prim_expr_mod eqn_mod_dvd //.\nrewrite prim_order_dvd; apply/eqP/eqP=> [|->]; last by rewrite mulr1.\nmove/(congr1 ( *%R (z ^+ (n - j %% n)))); rewrite mulrA -exprD.\nby rewrite subnK ?prim_expr_order ?mul1r // ltnW ?ltn_mod.\nQed.\n\nLemma exp_prim_root k : (n %/ gcdn k n).-primitive_root (z ^+ k).\nProof.\nset d := gcdn k n; have d_gt0: (0 < d)%N by rewrite gcdn_gt0 orbC n_gt0.\nhave [d_dv_k d_dv_n]: (d %| k /\\ d %| n)%N by rewrite dvdn_gcdl dvdn_gcdr.\nset q := (n %/ d)%N; rewrite /q.-primitive_root ltn_divRL // n_gt0.\napply/forallP=> i; rewrite unity_rootE -exprM -prim_order_dvd.\nrewrite -(divnK d_dv_n) -/q -(divnK d_dv_k) mulnAC dvdn_pmul2r //.\napply/eqP; apply/idP/idP=> [|/eqP->]; last by rewrite dvdn_mull.\nrewrite Gauss_dvdr; first by rewrite eqn_leq ltn_ord; apply: dvdn_leq.\nby rewrite /coprime gcdnC -(eqn_pmul2r d_gt0) mul1n muln_gcdl !divnK.\nQed.\n\nLemma dvdn_prim_root m : (m %| n)%N -> m.-primitive_root (z ^+ (n %/ m)).\nProof.\nset k := (n %/ m)%N => m_dv_n; rewrite -{1}(mulKn m n_gt0) -divnA // -/k.\nby rewrite -{1}(@gcdn_idPl k n _) ?exp_prim_root // -(divnK m_dv_n) dvdn_mulr.\nQed.\n\nEnd OnePrimitive.\n\nLemma prim_root_exp_coprime n z k :\n  n.-primitive_root z -> n.-primitive_root (z ^+ k) = coprime k n.\nProof.\nmove=> prim_z; have n_gt0 := prim_order_gt0 prim_z.\napply/idP/idP=> [prim_zk | co_k_n].\n  set d := gcdn k n; have dv_d_n: (d %| n)%N := dvdn_gcdr _ _.\n  rewrite /coprime -/d -(eqn_pmul2r n_gt0) mul1n -{2}(gcdnMl n d).\n  rewrite -{2}(divnK dv_d_n) (mulnC _ d) -muln_gcdr (gcdn_idPr _) //.\n  rewrite (prim_order_dvd prim_zk) -exprM -(prim_order_dvd prim_z).\n  by rewrite muln_divCA_gcd dvdn_mulr.\nhave zkn_1: z ^+ k ^+ n = 1 by rewrite exprAC (prim_expr_order prim_z) expr1n.\nhave{zkn_1} [m prim_zk dv_m_n]:= prim_order_exists n_gt0 zkn_1.\nsuffices /eqP <-: m == n by [].\nrewrite eqn_dvd dv_m_n -(@Gauss_dvdr n k m) 1?coprime_sym //=.\nby rewrite (prim_order_dvd prim_z) exprM (prim_expr_order prim_zk).\nQed.\n\n(* Lifting a ring predicate to polynomials. *)\n\nImplicit Type S : {pred R}.\n\nDefinition polyOver S := [qualify a p : {poly R} | all (mem S) p].\n\nFact polyOver_key S : pred_key (polyOver S). Proof. by []. Qed.\nCanonical polyOver_keyed S := KeyedQualifier (polyOver_key S).\n\nLemma polyOverS (S1 S2 : {pred R}) :\n  {subset S1 <= S2} -> {subset polyOver S1 <= polyOver S2}.\nProof.\nby move=> sS12 p /(all_nthP 0)S1p; apply/(all_nthP 0)=> i /S1p; apply: sS12.\nQed.\n\nLemma polyOver0 S : 0 \\is a polyOver S.\nProof. by rewrite qualifE polyseq0. Qed.\n\nLemma polyOver_poly S n E :\n  (forall i, i < n -> E i \\in S) -> \\poly_(i < n) E i \\is a polyOver S.\nProof.\nmove=> S_E; apply/(all_nthP 0)=> i lt_i_p /=; rewrite coef_poly.\nby case: ifP => [/S_E// | /idP[]]; apply: leq_trans lt_i_p (size_poly n E).\nQed.\n\nSection PolyOverAdd.\n\nVariables (S : {pred R}) (addS : addrPred S) (kS : keyed_pred addS).\n\nLemma polyOverP {p} : reflect (forall i, p`_i \\in kS) (p \\in polyOver kS).\nProof.\napply: (iffP (all_nthP 0)) => [Sp i | Sp i _]; last exact: Sp.\nby have [/Sp // | /(nth_default 0)->] := ltnP i (size p); apply: rpred0.\nQed.\n\nLemma polyOverC c : (c%:P \\in polyOver kS) = (c \\in kS).\nProof.\nby rewrite qualifE polyseqC; case: eqP => [->|] /=; rewrite ?andbT ?rpred0.\nQed.\n\nFact polyOver_addr_closed : addr_closed (polyOver kS).\nProof.\nsplit=> [|p q Sp Sq]; first exact: polyOver0.\nby apply/polyOverP=> i; rewrite coefD rpredD ?(polyOverP _).\nQed.\nCanonical polyOver_addrPred := AddrPred polyOver_addr_closed.\n\nEnd PolyOverAdd.\n\nFact polyOverNr S (addS : zmodPred S) (kS : keyed_pred addS) :\n  oppr_closed (polyOver kS).\nProof.\nby move=> p /polyOverP Sp; apply/polyOverP=> i; rewrite coefN rpredN.\nQed.\nCanonical polyOver_opprPred S addS kS := OpprPred (@polyOverNr S addS kS).\nCanonical polyOver_zmodPred S addS kS := ZmodPred (@polyOverNr S addS kS).\n\nSection PolyOverSemiring.\n\nVariables (S : {pred R}) (ringS : semiringPred S) (kS : keyed_pred ringS).\n\nFact polyOver_mulr_closed : mulr_closed (polyOver kS).\nProof.\nsplit=> [|p q /polyOverP Sp /polyOverP Sq]; first by rewrite polyOverC rpred1.\nby apply/polyOverP=> i; rewrite coefM rpred_sum // => j _; apply: rpredM.\nQed.\nCanonical polyOver_mulrPred := MulrPred polyOver_mulr_closed.\nCanonical polyOver_semiringPred := SemiringPred polyOver_mulr_closed.\n\nLemma polyOverZ : {in kS & polyOver kS, forall c p, c *: p \\is a polyOver kS}.\nProof.\nby move=> c p Sc /polyOverP Sp; apply/polyOverP=> i; rewrite coefZ rpredM ?Sp.\nQed.\n\nLemma polyOverX : 'X \\in polyOver kS.\nProof. by rewrite qualifE polyseqX /= rpred0 rpred1. Qed.\n\nLemma rpred_horner : {in polyOver kS & kS, forall p x, p.[x] \\in kS}.\nProof.\nmove=> p x /polyOverP Sp Sx; rewrite horner_coef rpred_sum // => i _.\nby rewrite rpredM ?rpredX.\nQed.\n\nEnd PolyOverSemiring.\n\nSection PolyOverRing.\n\nVariables (S : {pred R}) (ringS : subringPred S) (kS : keyed_pred ringS).\nCanonical polyOver_smulrPred := SmulrPred (polyOver_mulr_closed kS).\nCanonical polyOver_subringPred := SubringPred (polyOver_mulr_closed kS).\n\nLemma polyOverXsubC c : ('X - c%:P \\in polyOver kS) = (c \\in kS).\nProof. by rewrite rpredBl ?polyOverX ?polyOverC. Qed.\n\nEnd PolyOverRing.\n\n(* Single derivative. *)\n\nDefinition deriv p := \\poly_(i < (size p).-1) (p`_i.+1 *+ i.+1).\n\nLocal Notation \"a ^` ()\" := (deriv a).\n\nLemma coef_deriv p i : p^`()`_i = p`_i.+1 *+ i.+1.\nProof.\nrewrite coef_poly -subn1 ltn_subRL.\nby case: leqP => // /(nth_default 0) ->; rewrite mul0rn.\nQed.\n\nLemma polyOver_deriv S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p, p^`() \\is a polyOver kS}.\nProof.\nby move=> p /polyOverP Kp; apply/polyOverP=> i; rewrite coef_deriv rpredMn ?Kp.\nQed.\n\nLemma derivC c : c%:P^`() = 0.\nProof. by apply/polyP=> i; rewrite coef_deriv coef0 coefC mul0rn. Qed.\n\nLemma derivX : ('X)^`() = 1.\nProof. by apply/polyP=> [[|i]]; rewrite coef_deriv coef1 coefX ?mul0rn. Qed.\n\nLemma derivXn n : 'X^n^`() = 'X^n.-1 *+ n.\nProof.\ncase: n => [|n]; first exact: derivC.\napply/polyP=> i; rewrite coef_deriv coefMn !coefXn eqSS.\nby case: eqP => [-> // | _]; rewrite !mul0rn.\nQed.\n\nFact deriv_is_linear : linear deriv.\nProof.\nmove=> k p q; apply/polyP=> i.\nby rewrite !(coef_deriv, coefD, coefZ) mulrnDl mulrnAr.\nQed.\nCanonical deriv_additive := Additive deriv_is_linear.\nCanonical deriv_linear := Linear deriv_is_linear.\n\nLemma deriv0 : 0^`() = 0.\nProof. exact: linear0. Qed.\n\nLemma derivD : {morph deriv : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma derivN : {morph deriv : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma derivB : {morph deriv : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma derivXsubC (a : R) : ('X - a%:P)^`() = 1.\nProof. by rewrite derivB derivX derivC subr0. Qed.\n\nLemma derivMn n p : (p *+ n)^`() = p^`() *+ n.\nProof. exact: linearMn. Qed.\n\nLemma derivMNn n p : (p *- n)^`() = p^`() *- n.\nProof. exact: linearMNn. Qed.\n\nLemma derivZ c p : (c *: p)^`() = c *: p^`().\nProof. by rewrite linearZ. Qed.\n\nLemma deriv_mulC c p : (c%:P * p)^`() = c%:P * p^`().\nProof. by rewrite !mul_polyC derivZ. Qed.\n\nLemma derivMXaddC p c : (p * 'X + c%:P)^`() = p + p^`() * 'X.\nProof.\napply/polyP=> i; rewrite raddfD /= derivC addr0 coefD !(coefMX, coef_deriv).\nby case: i; rewrite ?addr0.\nQed.\n\nLemma derivM p q : (p * q)^`() = p^`() * q + p * q^`().\nProof.\nelim/poly_ind: p => [|p b IHp]; first by rewrite !(mul0r, add0r, derivC).\nrewrite mulrDl -mulrA -commr_polyX mulrA -[_ * 'X]addr0 raddfD /= !derivMXaddC.\nby rewrite deriv_mulC IHp !mulrDl -!mulrA !commr_polyX !addrA.\nQed.\n\nDefinition derivE := Eval lazy beta delta [morphism_2 morphism_1] in\n  (derivZ, deriv_mulC, derivC, derivX, derivMXaddC, derivXsubC, derivM, derivB,\n   derivD, derivN, derivXn, derivM, derivMn).\n\n(* Iterated derivative. *)\nDefinition derivn n p := iter n deriv p.\n\nLocal Notation \"a ^` ( n )\" := (derivn n a) : ring_scope.\n\nLemma derivn0 p : p^`(0) = p.\nProof. by []. Qed.\n\nLemma derivn1 p : p^`(1) = p^`().\nProof. by []. Qed.\n\nLemma derivnS p n : p^`(n.+1) = p^`(n)^`().\nProof. by []. Qed.\n\nLemma derivSn p n : p^`(n.+1) = p^`()^`(n).\nProof. exact: iterSr. Qed.\n\nLemma coef_derivn n p i : p^`(n)`_i = p`_(n + i) *+ (n + i) ^_ n.\nProof.\nelim: n i => [|n IHn] i; first by rewrite ffactn0 mulr1n.\nby rewrite derivnS coef_deriv IHn -mulrnA ffactnSr addSnnS addKn.\nQed.\n\nLemma polyOver_derivn S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p n, p^`(n) \\is a polyOver kS}.\nProof.\nmove=> p /polyOverP Kp /= n; apply/polyOverP=> i.\nby rewrite coef_derivn rpredMn.\nQed.\n\nFact derivn_is_linear n : linear (derivn n).\nProof. by elim: n => // n IHn a p q; rewrite derivnS IHn linearP. Qed.\nCanonical derivn_additive n :=  Additive (derivn_is_linear n).\nCanonical derivn_linear n :=  Linear (derivn_is_linear n).\n\nLemma derivnC c n : c%:P^`(n) = if n == 0%N then c%:P else 0.\nProof. by case: n => // n; rewrite derivSn derivC linear0. Qed.\n\nLemma derivnD n : {morph derivn n : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma derivn_sub n : {morph derivn n : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma derivnMn n m p : (p *+ m)^`(n) = p^`(n) *+ m.\nProof. exact: linearMn. Qed.\n\nLemma derivnMNn n m p : (p *- m)^`(n) = p^`(n) *- m.\nProof. exact: linearMNn. Qed.\n\nLemma derivnN n : {morph derivn n : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma derivnZ n : scalable (derivn n).\nProof. exact: linearZZ. Qed.\n\nLemma derivnXn m n : 'X^m^`(n) = 'X^(m - n) *+ m ^_ n.\nProof.\napply/polyP=>i; rewrite coef_derivn coefMn !coefXn.\ncase: (ltnP m n) => [lt_m_n | le_m_n].\n  by rewrite eqn_leq leqNgt ltn_addr // mul0rn ffact_small.\nby rewrite -{1 3}(subnKC le_m_n) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn.\nQed.\n\nLemma derivnMXaddC n p c :\n  (p * 'X + c%:P)^`(n.+1) = p^`(n) *+ n.+1  + p^`(n.+1) * 'X.\nProof.\nelim: n => [|n IHn]; first by rewrite derivn1 derivMXaddC.\nrewrite derivnS IHn derivD derivM derivX mulr1 derivMn -!derivnS.\nby rewrite addrA addrAC -mulrSr.\nQed.\n\nLemma derivn_poly0 p n : size p <= n -> p^`(n) = 0.\nProof.\nmove=> le_p_n; apply/polyP=> i; rewrite coef_derivn.\nrewrite nth_default; first by rewrite mul0rn coef0.\nby apply: leq_trans le_p_n _; apply leq_addr.\nQed.\n\nLemma lt_size_deriv (p : {poly R}) : p != 0 -> size p^`() < size p.\nProof. by move=> /polySpred->; apply: size_poly. Qed.\n\n(* A normalising version of derivation to get the division by n! in Taylor *)\n\nDefinition nderivn n p := \\poly_(i < size p - n) (p`_(n + i) *+  'C(n + i, n)).\n\nLocal Notation \"a ^`N ( n )\" := (nderivn n a) : ring_scope.\n\nLemma coef_nderivn n p i : p^`N(n)`_i = p`_(n + i) *+  'C(n + i, n).\nProof.\nrewrite coef_poly ltn_subRL; case: leqP => // le_p_ni.\nby rewrite nth_default ?mul0rn.\nQed.\n\n(* Here is the division by n! *)\nLemma nderivn_def n p : p^`(n) = p^`N(n) *+ n`!.\nProof.\nby apply/polyP=> i; rewrite coefMn coef_nderivn coef_derivn -mulrnA bin_ffact.\nQed.\n\nLemma polyOver_nderivn S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p n, p^`N(n) \\in polyOver kS}.\nProof.\nmove=> p /polyOverP Sp /= n; apply/polyOverP=> i.\nby rewrite coef_nderivn rpredMn.\nQed.\n\nLemma nderivn0 p : p^`N(0) = p.\nProof. by rewrite -[p^`N(0)](nderivn_def 0). Qed.\n\nLemma nderivn1 p : p^`N(1) = p^`().\nProof. by rewrite -[p^`N(1)](nderivn_def 1). Qed.\n\nLemma nderivnC c n : (c%:P)^`N(n) = if n == 0%N then c%:P else 0.\nProof.\napply/polyP=> i; rewrite coef_nderivn.\nby case: n => [|n]; rewrite ?bin0 // coef0 coefC mul0rn.\nQed.\n\nLemma nderivnXn m n : 'X^m^`N(n) = 'X^(m - n) *+ 'C(m, n).\nProof.\napply/polyP=> i; rewrite coef_nderivn coefMn !coefXn.\nhave [lt_m_n | le_n_m] := ltnP m n.\n  by rewrite eqn_leq leqNgt ltn_addr // mul0rn bin_small.\nby rewrite -{1 3}(subnKC le_n_m) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn.\nQed.\n\nFact nderivn_is_linear n : linear (nderivn n).\nProof.\nmove=> k p q; apply/polyP=> i.\nby rewrite !(coef_nderivn, coefD, coefZ) mulrnDl mulrnAr.\nQed.\nCanonical nderivn_additive n := Additive(nderivn_is_linear n).\nCanonical nderivn_linear n := Linear (nderivn_is_linear n).\n\nLemma nderivnD n : {morph nderivn n : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma nderivnB n : {morph nderivn n : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma nderivnMn n m p : (p *+ m)^`N(n) = p^`N(n) *+ m.\nProof. exact: linearMn. Qed.\n\nLemma nderivnMNn n m p : (p *- m)^`N(n) = p^`N(n) *- m.\nProof. exact: linearMNn. Qed.\n\nLemma nderivnN n : {morph nderivn n : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma nderivnZ n : scalable (nderivn n).\nProof. exact: linearZZ. Qed.\n\nLemma nderivnMXaddC n p c :\n  (p * 'X + c%:P)^`N(n.+1) = p^`N(n) + p^`N(n.+1) * 'X.\nProof.\napply/polyP=> i; rewrite coef_nderivn !coefD !coefMX coefC.\nrewrite !addSn /= !coef_nderivn addr0 binS mulrnDr addrC; congr (_ + _).\nby rewrite addSnnS; case: i; rewrite // addn0 bin_small.\nQed.\n\nLemma nderivn_poly0 p n : size p <= n -> p^`N(n) = 0.\nProof.\nmove=> le_p_n; apply/polyP=> i; rewrite coef_nderivn.\nrewrite nth_default; first by rewrite mul0rn coef0.\nby apply: leq_trans le_p_n _; apply leq_addr.\nQed.\n\nLemma nderiv_taylor p x h :\n  GRing.comm x h -> p.[x + h] = \\sum_(i < size p) p^`N(i).[x] * h ^+ i.\nProof.\nmove/commrX=> cxh; elim/poly_ind: p => [|p c IHp].\n  by rewrite size_poly0 big_ord0 horner0.\nrewrite hornerMXaddC size_MXaddC.\nhave [-> | nz_p] := altP (p =P 0).\n  rewrite horner0 !simp; have [-> | _] := c =P 0; first by rewrite big_ord0.\n  by rewrite size_poly0 big_ord_recl big_ord0 nderivn0 hornerC !simp.\nrewrite big_ord_recl nderivn0 !simp hornerMXaddC addrAC; congr (_ + _).\nrewrite mulrDr {}IHp !big_distrl polySpred //= big_ord_recl /= mulr1 -addrA.\nrewrite nderivn0 /bump /(addn 1) /=; congr (_ + _).\nrewrite !big_ord_recr /= nderivnMXaddC -mulrA -exprSr -polySpred // !addrA.\ncongr (_ + _); last by rewrite (nderivn_poly0 (leqnn _)) !simp.\nrewrite addrC -big_split /=; apply: eq_bigr => i _.\nby rewrite nderivnMXaddC !hornerE_comm /= mulrDl -!mulrA -exprSr cxh.\nQed.\n\nLemma nderiv_taylor_wide n p x h :\n    GRing.comm x h -> size p <= n ->\n  p.[x + h] = \\sum_(i < n) p^`N(i).[x] * h ^+ i.\nProof.\nmove/nderiv_taylor=> -> le_p_n.\nrewrite (big_ord_widen n (fun i => p^`N(i).[x] * h ^+ i)) // big_mkcond.\napply: eq_bigr => i _; case: leqP => // /nderivn_poly0->.\nby rewrite horner0 simp.\nQed.\n\nLemma eq_poly n E1 E2 : E1 =1 E2 -> poly n E1 = poly n E2.\nProof. by move=> E; rewrite !poly_def; apply: eq_bigr => i _; rewrite E. Qed.\n\nEnd PolynomialTheory.\n\nPrenex Implicits polyC polyCK Poly polyseqK lead_coef root horner polyOver.\nArguments monic {R}.\nNotation \"\\poly_ ( i < n ) E\" := (poly n (fun i => E)) : ring_scope.\nNotation \"c %:P\" := (polyC c) : ring_scope.\nNotation \"'X\" := (polyX _) : ring_scope.\nNotation \"''X^' n\" := ('X ^+ n) : ring_scope.\nNotation \"p .[ x ]\" := (horner p x) : ring_scope.\nNotation \"n .-unity_root\" := (root_of_unity n) : ring_scope.\nNotation \"n .-primitive_root\" := (primitive_root_of_unity n) : ring_scope.\nNotation \"a ^` ()\" := (deriv a) : ring_scope.\nNotation \"a ^` ( n )\" := (derivn n a) : ring_scope.\nNotation \"a ^`N ( n )\" := (nderivn n a) : ring_scope.\n\nArguments monicP {R p}.\nArguments rootP {R p x}.\nArguments rootPf {R p x}.\nArguments rootPt {R p x}.\nArguments unity_rootP {R n z}.\nArguments polyOverP {R S0 addS kS p}.\nArguments polyC_inj {R} [x1 x2] eq_x12P.\nArguments eq_poly {R n} [E1] E2 eq_E12.\n\nCanonical polynomial_countZmodType (R : countRingType) :=\n  [countZmodType of polynomial R].\nCanonical poly_countZmodType (R : countRingType) := [countZmodType of {poly R}].\nCanonical polynomial_countRingType (R : countRingType) :=\n  [countRingType of polynomial R].\nCanonical poly_countRingType (R : countRingType) := [countRingType of {poly R}].\n\n(* Container morphism. *)\nSection MapPoly.\n\nSection Definitions.\n\nVariables (aR rR : ringType) (f : aR -> rR).\n\nDefinition map_poly (p : {poly aR}) := \\poly_(i < size p) f p`_i.\n\n(* Alternative definition; the one above is more convenient because it lets *)\n(* us use the lemmas on \\poly, e.g., size (map_poly p) <= size p is an      *)\n(* instance of size_poly.                                                   *)\nLemma map_polyE p : map_poly p = Poly (map f p).\nProof.\nrewrite /map_poly unlock; congr Poly.\napply: (@eq_from_nth _ 0); rewrite size_mkseq ?size_map // => i lt_i_p.\nby rewrite (nth_map 0) ?nth_mkseq.\nQed.\n\nDefinition commr_rmorph u := forall x, GRing.comm u (f x).\n\nDefinition horner_morph u of commr_rmorph u := fun p => (map_poly p).[u].\n\nEnd Definitions.\n\nVariables aR rR : ringType.\n\nSection Combinatorial.\n\nVariables (iR : ringType) (f : aR -> rR).\nLocal Notation \"p ^f\" := (map_poly f p) : ring_scope.\n\nLemma map_poly0 : 0^f = 0.\nProof. by rewrite map_polyE polyseq0. Qed.\n\nLemma eq_map_poly (g : aR -> rR) : f =1 g -> map_poly f =1 map_poly g.\nProof. by move=> eq_fg p; rewrite !map_polyE (eq_map eq_fg). Qed.\n\nLemma map_poly_id g (p : {poly iR}) :\n  {in (p : seq iR), g =1 id} -> map_poly g p = p.\nProof. by move=> g_id; rewrite map_polyE map_id_in ?polyseqK. Qed.\n\nLemma coef_map_id0 p i : f 0 = 0 -> (p^f)`_i = f p`_i.\nProof.\nby move=> f0; rewrite coef_poly; case: ltnP => // le_p_i; rewrite nth_default.\nQed.\n\nLemma map_Poly_id0 s : f 0 = 0 -> (Poly s)^f = Poly (map f s).\nProof.\nmove=> f0; apply/polyP=> j; rewrite coef_map_id0 ?coef_Poly //.\nhave [/(nth_map 0 0)->// | le_s_j] := ltnP j (size s).\nby rewrite !nth_default ?size_map.\nQed.\n\nLemma map_poly_comp_id0 (g : iR -> aR) p :\n  f 0 = 0 -> map_poly (f \\o g) p = (map_poly g p)^f.\nProof. by move=> f0; rewrite map_polyE map_comp -map_Poly_id0 -?map_polyE. Qed.\n\nLemma size_map_poly_id0 p : f (lead_coef p) != 0 -> size p^f = size p.\nProof. by move=> nz_fp; apply: size_poly_eq. Qed.\n\nLemma map_poly_eq0_id0 p : f (lead_coef p) != 0 -> (p^f == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /size_map_poly_id0->. Qed.\n\nLemma lead_coef_map_id0 p :\n  f 0 = 0 -> f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p).\nProof.\nby move=> f0 nz_fp; rewrite lead_coefE coef_map_id0 ?size_map_poly_id0.\nQed.\n\nHypotheses (inj_f : injective f) (f_0 : f 0 = 0).\n\nLemma size_map_inj_poly p : size p^f = size p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite map_poly0 !size_poly0.\nby rewrite size_map_poly_id0 // -f_0 (inj_eq inj_f) lead_coef_eq0.\nQed.\n\nLemma map_inj_poly : injective (map_poly f).\nProof.\nmove=> p q /polyP eq_pq; apply/polyP=> i; apply: inj_f.\nby rewrite -!coef_map_id0 ?eq_pq.\nQed.\n\nLemma lead_coef_map_inj p : lead_coef p^f = f (lead_coef p).\nProof. by rewrite !lead_coefE size_map_inj_poly coef_map_id0. Qed.\n\nEnd Combinatorial.\n\nLemma map_polyK (f : aR -> rR) g :\n  cancel g f -> f 0 = 0 -> cancel (map_poly g) (map_poly f).\nProof.\nby move=> gK f_0 p; rewrite /= -map_poly_comp_id0 ?map_poly_id // => x _ //=.\nQed.\n\nSection Additive.\n\nVariables (iR : ringType) (f : {additive aR -> rR}).\n\nLocal Notation \"p ^f\" := (map_poly (GRing.Additive.apply f) p) : ring_scope.\n\nLemma coef_map p i : p^f`_i = f p`_i.\nProof. exact: coef_map_id0 (raddf0 f). Qed.\n\nLemma map_Poly s : (Poly s)^f = Poly (map f s).\nProof. exact: map_Poly_id0 (raddf0 f). Qed.\n\nLemma map_poly_comp (g : iR -> aR) p :\n  map_poly (f \\o g) p = map_poly f (map_poly g p).\nProof. exact: map_poly_comp_id0 (raddf0 f). Qed.\n\nFact map_poly_is_additive : additive (map_poly f).\nProof. by move=> p q; apply/polyP=> i; rewrite !(coef_map, coefB) raddfB. Qed.\nCanonical map_poly_additive := Additive map_poly_is_additive.\n\nLemma map_polyC a : (a%:P)^f = (f a)%:P.\nProof. by apply/polyP=> i; rewrite !(coef_map, coefC) -!mulrb raddfMn. Qed.\n\nLemma lead_coef_map_eq p :\n  f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p).\nProof. exact: lead_coef_map_id0 (raddf0 f). Qed.\n\nEnd Additive.\n\nVariable f : {rmorphism aR -> rR}.\nImplicit Types p : {poly aR}.\n\nLocal Notation \"p ^f\" := (map_poly (GRing.RMorphism.apply f) p) : ring_scope.\n\nFact map_poly_is_rmorphism : rmorphism (map_poly f).\nProof.\nsplit; first exact: map_poly_is_additive.\nsplit=> [p q|]; apply/polyP=> i; last first.\n  by rewrite !(coef_map, coef1) /= rmorph_nat.\nrewrite coef_map /= !coefM /= !rmorph_sum; apply: eq_bigr => j _.\nby rewrite !coef_map rmorphM.\nQed.\nCanonical map_poly_rmorphism := RMorphism map_poly_is_rmorphism.\n\nLemma map_polyZ c p : (c *: p)^f = f c *: p^f.\nProof. by apply/polyP=> i; rewrite !(coef_map, coefZ) /= rmorphM. Qed.\nCanonical map_poly_linear :=\n  AddLinear (map_polyZ : scalable_for (f \\; *:%R) (map_poly f)).\nCanonical map_poly_lrmorphism := [lrmorphism of map_poly f].\n\nLemma map_polyX : ('X)^f = 'X.\nProof. by apply/polyP=> i; rewrite coef_map !coefX /= rmorph_nat. Qed.\n\nLemma map_polyXn n : ('X^n)^f = 'X^n.\nProof. by rewrite rmorphX /= map_polyX. Qed.\n\nLemma monic_map p : p \\is monic -> p^f \\is monic.\nProof.\nmove/monicP=> mon_p; rewrite monicE.\nby rewrite lead_coef_map_eq mon_p /= rmorph1 ?oner_neq0.\nQed.\n\nLemma horner_map p x : p^f.[f x] = f p.[x].\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(rmorph0, horner0).\nrewrite hornerMXaddC !rmorphD !rmorphM /=.\nby rewrite map_polyX map_polyC hornerMXaddC IHp.\nQed.\n\nLemma map_comm_poly p x : comm_poly p x -> comm_poly p^f (f x).\nProof. by rewrite /comm_poly horner_map -!rmorphM // => ->. Qed.\n\nLemma map_comm_coef p x : comm_coef p x -> comm_coef p^f (f x).\nProof. by move=> cpx i; rewrite coef_map -!rmorphM ?cpx. Qed.\n\nLemma rmorph_root p x : root p x -> root p^f (f x).\nProof. by move/eqP=> px0; rewrite rootE horner_map px0 rmorph0. Qed.\n\nLemma rmorph_unity_root n z : n.-unity_root z -> n.-unity_root (f z).\nProof.\nmove/rmorph_root; rewrite rootE rmorphB hornerD hornerN.\nby rewrite /= map_polyXn rmorph1 hornerC hornerXn subr_eq0 unity_rootE.\nQed.\n\nSection HornerMorph.\n\nVariable u : rR.\nHypothesis cfu : commr_rmorph f u.\n\nLemma horner_morphC a : horner_morph cfu a%:P = f a.\nProof. by rewrite /horner_morph map_polyC hornerC. Qed.\n\nLemma horner_morphX : horner_morph cfu 'X = u.\nProof. by rewrite /horner_morph map_polyX hornerX. Qed.\n\nFact horner_is_lrmorphism : lrmorphism_for (f \\; *%R) (horner_morph cfu).\nProof.\nrewrite /horner_morph; split=> [|c p]; last by rewrite linearZ hornerZ.\nsplit=> [p q|]; first by rewrite /horner_morph rmorphB hornerD hornerN.\nsplit=> [p q|]; last by rewrite /horner_morph rmorph1 hornerC.\nrewrite /horner_morph rmorphM /= hornerM_comm //.\nby apply: comm_coef_poly => i; rewrite coef_map cfu.\nQed.\nCanonical horner_additive := Additive horner_is_lrmorphism.\nCanonical horner_rmorphism := RMorphism horner_is_lrmorphism.\nCanonical horner_linear := AddLinear horner_is_lrmorphism.\nCanonical horner_lrmorphism := [lrmorphism of horner_morph cfu].\n\nEnd HornerMorph.\n\nLemma deriv_map p : p^f^`() = (p^`())^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_deriv) //= rmorphMn. Qed.\n\nLemma derivn_map p n : p^f^`(n) = (p^`(n))^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_derivn) //= rmorphMn. Qed.\n\nLemma nderivn_map p n : p^f^`N(n) = (p^`N(n))^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_nderivn) //= rmorphMn. Qed.\n\nEnd MapPoly.\n\n(* Morphisms from the polynomial ring, and the initiality of polynomials  *)\n(* with respect to these.                                                 *)\nSection MorphPoly.\n\nVariable (aR rR : ringType) (pf : {rmorphism {poly aR} -> rR}).\n\nLemma poly_morphX_comm : commr_rmorph (pf \\o polyC) (pf 'X).\nProof. by move=> a; rewrite /GRing.comm /= -!rmorphM // commr_polyX. Qed.\n\nLemma poly_initial : pf =1 horner_morph poly_morphX_comm.\nProof.\napply: poly_ind => [|p a IHp]; first by rewrite !rmorph0.\nby rewrite !rmorphD !rmorphM /= -{}IHp horner_morphC ?horner_morphX.\nQed.\n\nEnd MorphPoly.\n\nNotation \"p ^:P\" := (map_poly polyC p) : ring_scope.\n\nSection PolyCompose.\n\nVariable R : ringType.\nImplicit Types p q : {poly R}.\n\nDefinition comp_poly q p := p^:P.[q].\n\nLocal Notation \"p \\Po q\" := (comp_poly q p) : ring_scope.\n\nLemma size_map_polyC p : size p^:P = size p.\nProof. exact/(size_map_inj_poly polyC_inj). Qed.\n\nLemma map_polyC_eq0 p : (p^:P == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 size_map_polyC. Qed.\n\nLemma root_polyC p x : root p^:P x%:P = root p x.\nProof. by rewrite rootE horner_map polyC_eq0. Qed.\n\nLemma comp_polyE p q : p \\Po q = \\sum_(i < size p) p`_i *: q^+i.\nProof.\nby rewrite [p \\Po q]horner_poly; apply: eq_bigr => i _; rewrite mul_polyC.\nQed.\n\nLemma coef_comp_poly p q n :\n  (p \\Po q)`_n = \\sum_(i < size p) p`_i * (q ^+ i)`_n.\nProof. by rewrite comp_polyE coef_sum; apply: eq_bigr => i; rewrite coefZ. Qed.\n\nLemma polyOver_comp S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS &, forall p q, p \\Po q \\in polyOver kS}.\nProof.\nmove=> p q /polyOverP Sp Sq; rewrite comp_polyE rpred_sum // => i _.\nby rewrite polyOverZ ?rpredX.\nQed.\n\nLemma comp_polyCr p c : p \\Po c%:P = p.[c]%:P.\nProof. exact: horner_map. Qed.\n\nLemma comp_poly0r p : p \\Po 0 = (p`_0)%:P.\nProof. by rewrite comp_polyCr horner_coef0. Qed.\n\nLemma comp_polyC c p : c%:P \\Po p = c%:P.\nProof. by rewrite /(_ \\Po p) map_polyC hornerC. Qed.\n\nFact comp_poly_is_linear p : linear (comp_poly p).\nProof.\nmove=> a q r.\nby rewrite /comp_poly rmorphD /= map_polyZ !hornerE_comm mul_polyC.\nQed.\nCanonical comp_poly_additive p := Additive (comp_poly_is_linear p).\nCanonical comp_poly_linear p := Linear (comp_poly_is_linear p).\n\nLemma comp_poly0 p : 0 \\Po p = 0.\nProof. exact: raddf0. Qed.\n\nLemma comp_polyD p q r : (p + q) \\Po r = (p \\Po r) + (q \\Po r).\nProof. exact: raddfD. Qed.\n\nLemma comp_polyB p q r : (p - q) \\Po r = (p \\Po r) - (q \\Po r).\nProof. exact: raddfB. Qed.\n\nLemma comp_polyZ c p q : (c *: p) \\Po q = c *: (p \\Po q).\nProof. exact: linearZZ. Qed.\n\nLemma comp_polyXr p : p \\Po 'X = p.\nProof. by rewrite -{2}/(idfun p) poly_initial. Qed.\n\nLemma comp_polyX p : 'X \\Po p = p.\nProof. by rewrite /(_ \\Po p) map_polyX hornerX. Qed.\n\nLemma comp_poly_MXaddC c p q : (p * 'X + c%:P) \\Po q = (p \\Po q) * q + c%:P.\nProof.\nby rewrite /(_ \\Po q) rmorphD rmorphM /= map_polyX map_polyC hornerMXaddC.\nQed.\n\nLemma comp_polyXaddC_K p z : (p \\Po ('X + z%:P)) \\Po ('X - z%:P) = p.\nProof.\nhave addzK: ('X + z%:P) \\Po ('X - z%:P) = 'X.\n  by rewrite raddfD /= comp_polyC comp_polyX subrK.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !comp_poly0.\nrewrite comp_poly_MXaddC linearD /= comp_polyC {1}/comp_poly rmorphM /=.\nby rewrite hornerM_comm /comm_poly -!/(_ \\Po _) ?IHp ?addzK ?commr_polyX.\nQed.\n\nLemma size_comp_poly_leq p q :\n  size (p \\Po q) <= ((size p).-1 * (size q).-1).+1.\nProof.\nrewrite comp_polyE (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _.\nrewrite (leq_trans (size_scale_leq _ _)) // (leq_trans (size_exp_leq _ _)) //.\nby rewrite ltnS mulnC leq_mul // -{2}(subnKC (valP i)) leq_addr.\nQed.\n\nEnd PolyCompose.\n\nNotation \"p \\Po q\" := (comp_poly q p) : ring_scope.\n\nLemma map_comp_poly (aR rR : ringType) (f : {rmorphism aR -> rR}) p q :\n  map_poly f (p \\Po q) = map_poly f p \\Po map_poly f q.\nProof.\nelim/poly_ind: p => [|p a IHp]; first by rewrite !raddf0.\nrewrite comp_poly_MXaddC !rmorphD !rmorphM /= !map_polyC map_polyX.\nby rewrite comp_poly_MXaddC -IHp.\nQed.\n\nSection PolynomialComRing.\n\nVariable R : comRingType.\nImplicit Types p q : {poly R}.\n\nFact poly_mul_comm p q : p * q = q * p.\nProof.\napply/polyP=> i; rewrite coefM coefMr.\nby apply: eq_bigr => j _; rewrite mulrC.\nQed.\n\nCanonical poly_comRingType := Eval hnf in ComRingType {poly R} poly_mul_comm.\nCanonical polynomial_comRingType :=\n  Eval hnf in ComRingType (polynomial R) poly_mul_comm.\nCanonical poly_algType := Eval hnf in CommAlgType R {poly R}.\nCanonical polynomial_algType :=\n  Eval hnf in [algType R of polynomial R for poly_algType].\nCanonical poly_comAlgType := Eval hnf in [comAlgType R of {poly R}].\n\nLemma hornerM p q x : (p * q).[x] = p.[x] * q.[x].\nProof. by rewrite hornerM_comm //; apply: mulrC. Qed.\n\nLemma horner_exp p x n : (p ^+ n).[x] = p.[x] ^+ n.\nProof. by rewrite horner_exp_comm //; apply: mulrC. Qed.\n\nLemma horner_prod I r (P : pred I) (F : I -> {poly R}) x :\n  (\\prod_(i <- r | P i) F i).[x] = \\prod_(i <- r | P i) (F i).[x].\nProof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (hornerM, hornerC). Qed.\n\nDefinition hornerE :=\n  (hornerD, hornerN, hornerX, hornerC, horner_cons,\n   simp, hornerCM, hornerZ, hornerM).\n\nDefinition horner_eval (x : R) := horner^~ x.\nLemma horner_evalE x p : horner_eval x p = p.[x]. Proof. by []. Qed.\n\nFact horner_eval_is_lrmorphism x : lrmorphism_for *%R (horner_eval x).\nProof.\nhave cxid: commr_rmorph idfun x by apply: mulrC.\nhave evalE : horner_eval x =1 horner_morph cxid.\n  by move=> p; congr _.[x]; rewrite map_poly_id.\nsplit=> [|c p]; last by rewrite !evalE /= -linearZ.\nby do 2?split=> [p q|]; rewrite !evalE (rmorphB, rmorphM, rmorph1).\nQed.\nCanonical horner_eval_additive x := Additive (horner_eval_is_lrmorphism x).\nCanonical horner_eval_rmorphism x := RMorphism (horner_eval_is_lrmorphism x).\nCanonical horner_eval_linear x := AddLinear (horner_eval_is_lrmorphism x).\nCanonical horner_eval_lrmorphism x := [lrmorphism of horner_eval x].\n\nSection HornerAlg.\n\nVariable A : algType R. (* For univariate polys, commutativity is not needed *)\n\nSection Defs.\n\nVariable a : A.\n\nLemma in_alg_comm : commr_rmorph (in_alg A) a.\nProof. move=> r /=; by rewrite /GRing.comm comm_alg. Qed.\n\nDefinition horner_alg := horner_morph in_alg_comm.\n\nLemma horner_algC c : horner_alg c%:P = c%:A.\nProof. exact: horner_morphC. Qed.\n\nLemma horner_algX : horner_alg 'X = a.\nProof. exact:  horner_morphX. Qed.\n\nFact horner_alg_is_lrmorphism : lrmorphism horner_alg.\nProof.\nrewrite /horner_alg; split=> [|c p]; last by rewrite linearZ /= mulr_algl.\nsplit=> [p q|]; first by rewrite rmorphB.\nsplit=> [p q|]; last by rewrite rmorph1.\nby rewrite rmorphM.\nQed.\nCanonical horner_alg_additive := Additive horner_alg_is_lrmorphism.\nCanonical horner_alg_rmorphism := RMorphism horner_alg_is_lrmorphism.\nCanonical horner_alg_linear := AddLinear horner_alg_is_lrmorphism.\nCanonical horner_alg_lrmorphism := [lrmorphism of horner_alg].\n\nEnd Defs.\n\nVariable (pf : {lrmorphism {poly R} -> A}).\n\nLemma poly_alg_initial : pf =1 horner_alg (pf 'X).\nProof.\napply: poly_ind => [|p a IHp]; first by rewrite !rmorph0.\nrewrite !rmorphD !rmorphM /= -{}IHp horner_algC ?horner_algX.\nby rewrite -alg_polyC rmorph_alg.\nQed.\n\nEnd HornerAlg.\n\nFact comp_poly_multiplicative q : multiplicative (comp_poly q).\nProof.\nsplit=> [p1 p2|]; last by rewrite comp_polyC.\nby rewrite /comp_poly rmorphM hornerM_comm //; apply: mulrC.\nQed.\nCanonical comp_poly_rmorphism q := AddRMorphism (comp_poly_multiplicative q).\nCanonical comp_poly_lrmorphism q := [lrmorphism of comp_poly q].\n\nLemma comp_polyM p q r : (p * q) \\Po r = (p \\Po r) * (q \\Po r).\nProof. exact: rmorphM. Qed.\n\nLemma comp_polyA p q r : p \\Po (q \\Po r) = (p \\Po q) \\Po r.\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !comp_polyC.\nby rewrite !comp_polyD !comp_polyM !comp_polyX IHp !comp_polyC.\nQed.\n\nLemma horner_comp p q x : (p \\Po q).[x] = p.[q.[x]].\nProof. by apply: polyC_inj; rewrite -!comp_polyCr comp_polyA. Qed.\n\nLemma root_comp p q x : root (p \\Po q) x = root p (q.[x]).\nProof. by rewrite !rootE horner_comp. Qed.\n\nLemma deriv_comp p q : (p \\Po q) ^`() = (p ^`() \\Po q) * q^`().\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(deriv0, comp_poly0) mul0r.\nrewrite comp_poly_MXaddC derivD derivC derivM IHp derivMXaddC comp_polyD.\nby rewrite comp_polyM comp_polyX addr0 addrC mulrAC -mulrDl.\nQed.\n\nLemma deriv_exp p n : (p ^+ n)^`() = p^`() * p ^+ n.-1 *+ n.\nProof.\nelim: n => [|n IHn]; first by rewrite expr0 mulr0n derivC.\nby rewrite exprS derivM {}IHn (mulrC p) mulrnAl -mulrA -exprSr mulrS; case n.\nQed.\n\nDefinition derivCE := (derivE, deriv_exp).\n\nEnd PolynomialComRing.\n\nCanonical polynomial_countComRingType (R : countComRingType) :=\n  [countComRingType of polynomial R].\nCanonical poly_countComRingType (R : countComRingType) :=\n  [countComRingType of {poly R}].\n\nSection PolynomialIdomain.\n\n(* Integral domain structure on poly *)\nVariable R : idomainType.\n\nImplicit Types (a b x y : R) (p q r m : {poly R}).\n\nLemma size_mul p q : p != 0 -> q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nby move=> nz_p nz_q; rewrite -size_proper_mul ?mulf_neq0 ?lead_coef_eq0.\nQed.\n\nFact poly_idomainAxiom p q : p * q = 0 -> (p == 0) || (q == 0).\nProof.\nmove=> pq0; apply/norP=> [[p_nz q_nz]]; move/eqP: (size_mul p_nz q_nz).\nby rewrite eq_sym pq0 size_poly0 (polySpred p_nz) (polySpred q_nz) addnS.\nQed.\n\nDefinition poly_unit : pred {poly R} :=\n  fun p => (size p == 1%N) && (p`_0 \\in GRing.unit).\n\nDefinition poly_inv p := if p \\in poly_unit then (p`_0)^-1%:P else p.\n\nFact poly_mulVp : {in poly_unit, left_inverse 1 poly_inv *%R}.\nProof.\nmove=> p Up; rewrite /poly_inv Up.\nby case/andP: Up => /size_poly1P[c _ ->]; rewrite coefC -polyC_mul => /mulVr->.\nQed.\n\nFact poly_intro_unit p q : q * p = 1 -> p \\in poly_unit.\nProof.\nmove=> pq1; apply/andP; split; last first.\n  apply/unitrP; exists q`_0.\n  by rewrite 2!mulrC -!/(coefp 0 _) -rmorphM pq1 rmorph1.\nhave: size (q * p) == 1%N by rewrite pq1 size_poly1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite mul0r size_poly0.\nrewrite size_mul // (polySpred nz_p) (polySpred nz_q) addnS addSn !eqSS.\nby rewrite addn_eq0 => /andP[].\nQed.\n\nFact poly_inv_out : {in [predC poly_unit], poly_inv =1 id}.\nProof. by rewrite /poly_inv => p /negbTE/= ->. Qed.\n\nDefinition poly_comUnitMixin :=\n  ComUnitRingMixin poly_mulVp poly_intro_unit poly_inv_out.\n\nCanonical poly_unitRingType :=\n  Eval hnf in UnitRingType {poly R} poly_comUnitMixin.\nCanonical polynomial_unitRingType :=\n  Eval hnf in [unitRingType of polynomial R for poly_unitRingType].\n\nCanonical poly_unitAlgType := Eval hnf in [unitAlgType R of {poly R}].\nCanonical polynomial_unitAlgType := Eval hnf in [unitAlgType R of polynomial R].\n\nCanonical poly_comUnitRingType := Eval hnf in [comUnitRingType of {poly R}].\nCanonical polynomial_comUnitRingType :=\n  Eval hnf in [comUnitRingType of polynomial R].\n\nCanonical poly_idomainType :=\n  Eval hnf in IdomainType {poly R} poly_idomainAxiom.\nCanonical polynomial_idomainType :=\n  Eval hnf in [idomainType of polynomial R for poly_idomainType].\n\nLemma poly_unitE p :\n  (p \\in GRing.unit) = (size p == 1%N) && (p`_0 \\in GRing.unit).\nProof. by []. Qed.\n\nLemma poly_invE p : p ^-1 = if p \\in GRing.unit then (p`_0)^-1%:P else p.\nProof. by []. Qed.\n\nLemma polyC_inv c : c%:P^-1 = (c^-1)%:P.\nProof.\nhave [/rmorphV-> // | nUc] := boolP (c \\in GRing.unit).\nby rewrite !invr_out // poly_unitE coefC (negbTE nUc) andbF.\nQed.\n\nLemma rootM p q x : root (p * q) x = root p x || root q x.\nProof. by rewrite !rootE hornerM mulf_eq0. Qed.\n\nLemma rootZ x a p : a != 0 -> root (a *: p) x = root p x.\nProof. by move=> nz_a; rewrite -mul_polyC rootM rootC (negPf nz_a). Qed.\n\nLemma size_scale a p : a != 0 -> size (a *: p) = size p.\nProof. by move/lregP/lreg_size->. Qed.\n\nLemma size_Cmul a p : a != 0 -> size (a%:P * p) = size p.\nProof. by rewrite mul_polyC => /size_scale->. Qed.\n\nLemma lead_coefM p q : lead_coef (p * q) = lead_coef p * lead_coef q.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, lead_coef0).\nhave [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, lead_coef0).\nby rewrite lead_coef_proper_mul // mulf_neq0 ?lead_coef_eq0.\nQed.\n\nLemma lead_coefZ a p : lead_coef (a *: p) = a * lead_coef p.\nProof. by rewrite -mul_polyC lead_coefM lead_coefC. Qed.\n\nLemma scale_poly_eq0 a p : (a *: p == 0) = (a == 0) || (p == 0).\nProof. by rewrite -mul_polyC mulf_eq0 polyC_eq0. Qed.\n\nLemma size_prod (I : finType) (P : pred I) (F : I -> {poly R}) :\n    (forall i, P i -> F i != 0) ->\n  size (\\prod_(i | P i) F i) = ((\\sum_(i | P i) size (F i)).+1 - #|P|)%N.\nProof.\nmove=> nzF; transitivity (\\sum_(i | P i) (size (F i)).-1).+1; last first.\n  apply: canRL (addKn _) _; rewrite addnS -sum1_card -big_split /=.\n  by congr _.+1; apply: eq_bigr => i /nzF/polySpred.\nelim/big_rec2: _ => [|i d p /nzF nzFi IHp]; first by rewrite size_poly1.\nby rewrite size_mul // -?size_poly_eq0 IHp // addnS polySpred.\nQed.\n\nLemma size_prod_seq (I : eqType)  (s : seq I) (F : I -> {poly R}) :\n    (forall i, i \\in s -> F i != 0) ->\n  size (\\prod_(i <- s) F i) = ((\\sum_(i <- s) size (F i)).+1 - size s)%N.\nProof.\nmove=> nzF; rewrite big_tnth size_prod; last by move=> i; rewrite nzF ?mem_tnth.\nby rewrite cardT /= size_enum_ord [in RHS]big_tnth.\nQed.\n\nLemma size_mul_eq1 p q :\n  (size (p * q) == 1%N) = ((size p == 1%N) && (size q == 1%N)).\nProof.\nhave [->|pNZ] := eqVneq p 0; first by rewrite mul0r size_poly0.\nhave [->|qNZ] := eqVneq q 0; first by rewrite mulr0 size_poly0 andbF.\nrewrite size_mul //.\nby move: pNZ qNZ; rewrite -!size_poly_gt0; (do 2 case: size) => //= n [|[|]].\nQed.\n\nLemma size_prod_seq_eq1 (I : eqType) (s : seq I) (P : pred I) (F : I -> {poly R}) :\n  reflect (forall i, P i && (i \\in s) -> size (F i) = 1%N)\n          (size (\\prod_(i <- s | P i) F i) == 1%N).\nProof.\nhave -> : (size (\\prod_(i <- s | P i) F i) == 1%N) =\n  (all [pred i | P i ==> (size (F i) == 1%N)] s).\n  elim: s => [|a s IHs /=]; first by rewrite big_nil size_poly1.\n  by rewrite big_cons; case: (P a) => //=; rewrite size_mul_eq1 IHs.\napply: (iffP allP) => /= [/(_ _ _)/implyP /(_ _)/eqP|] sF_eq1 i.\n  by move=> /andP[Pi si]; rewrite sF_eq1.\nby move=> si; apply/implyP => Pi; rewrite sF_eq1 ?Pi.\nQed.\n\nLemma size_prod_eq1 (I : finType) (P : pred I) (F : I -> {poly R}) :\n  reflect (forall i, P i -> size (F i) = 1%N)\n          (size (\\prod_(i | P i) F i) == 1%N).\nProof.\napply: (iffP (size_prod_seq_eq1 _ _ _)) => Hi i.\n  by move=> Pi; apply: Hi; rewrite Pi /= mem_index_enum.\nby rewrite mem_index_enum andbT; apply: Hi.\nQed.\n\nLemma size_exp p n : (size (p ^+ n)).-1 = ((size p).-1 * n)%N.\nProof.\nelim: n => [|n IHn]; first by rewrite size_poly1 muln0.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite exprS mul0r size_poly0.\nrewrite exprS size_mul ?expf_neq0 // mulnS -{}IHn.\nby rewrite polySpred // [size (p ^+ n)]polySpred ?expf_neq0 ?addnS.\nQed.\n\nLemma lead_coef_exp p n : lead_coef (p ^+ n) = lead_coef p ^+ n.\nProof.\nelim: n => [|n IHn]; first by rewrite !expr0 lead_coef1.\nby rewrite !exprS lead_coefM IHn.\nQed.\n\nLemma root_prod_XsubC rs x :\n  root (\\prod_(a <- rs) ('X - a%:P)) x = (x \\in rs).\nProof.\nelim: rs => [|a rs IHrs]; first by rewrite rootE big_nil hornerC oner_eq0.\nby rewrite big_cons rootM IHrs root_XsubC.\nQed.\n\nLemma root_exp_XsubC n a x : root (('X - a%:P) ^+ n.+1) x = (x == a).\nProof. by rewrite rootE horner_exp expf_eq0 [_ == 0]root_XsubC. Qed.\n\nLemma size_comp_poly p q :\n  (size (p \\Po q)).-1 = ((size p).-1 * (size q).-1)%N.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite comp_poly0 size_poly0.\nhave [/size1_polyC-> | nc_q] := leqP (size q) 1.\n  by rewrite comp_polyCr !size_polyC -!sub1b -!subnS muln0.\nhave nz_q: q != 0 by rewrite -size_poly_eq0 -(subnKC nc_q).\nrewrite mulnC comp_polyE (polySpred nz_p) /= big_ord_recr /= addrC.\nrewrite size_addl size_scale ?lead_coef_eq0 ?size_exp //=.\nrewrite [X in _ < X]polySpred ?expf_neq0 // ltnS size_exp.\nrewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _.\nrewrite (leq_trans (size_scale_leq _ _)) // polySpred ?expf_neq0 //.\nby rewrite size_exp -(subnKC nc_q) ltn_pmul2l.\nQed.\n\nLemma lead_coef_comp p q : size q > 1 ->\n  lead_coef (p \\Po q) = (lead_coef p) * lead_coef q ^+ (size p).-1.\nProof.\nmove=> q_gt1; rewrite !lead_coefE coef_comp_poly size_comp_poly.\nhave [->|nz_p] := eqVneq p 0; first by rewrite size_poly0 big_ord0 coef0 mul0r.\nrewrite polySpred //= big_ord_recr /= big1 ?add0r => [|i _].\n  by rewrite -!lead_coefE -lead_coef_exp !lead_coefE size_exp mulnC.\nrewrite [X in _ * X]nth_default ?mulr0 ?(leq_trans (size_exp_leq _ _)) //.\nby rewrite mulnC ltn_mul2r -subn1 subn_gt0 q_gt1 /=.\nQed.\n\nLemma comp_poly_eq0 p q : size q > 1 -> (p \\Po q == 0) = (p == 0).\nProof.\nmove=> sq_gt1; rewrite -!lead_coef_eq0 lead_coef_comp //.\nrewrite mulf_eq0 expf_eq0 !lead_coef_eq0 -[q == 0]size_poly_leq0.\nby rewrite [_ <= 0]leqNgt (leq_ltn_trans _ sq_gt1) ?andbF ?orbF.\nQed.\n\nLemma size_comp_poly2 p q : size q = 2 -> size (p \\Po q) = size p.\nProof.\nmove=> sq2; have [->|pN0] := eqVneq p 0; first by rewrite comp_polyC.\nby rewrite polySpred ?size_comp_poly ?comp_poly_eq0 ?sq2 // muln1 polySpred.\nQed.\n\nLemma comp_poly2_eq0 p q : size q = 2 -> (p \\Po q == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /size_comp_poly2->. Qed.\n\nTheorem max_poly_roots p rs :\n  p != 0 -> all (root p) rs -> uniq rs -> size rs < size p.\nProof.\nelim: rs p => [p pn0 _ _ | r rs ihrs p pn0] /=; first by rewrite size_poly_gt0.\ncase/andP => rpr arrs /andP [rnrs urs]; case/factor_theorem: rpr => q epq.\ncase: (altP (q =P 0)) => [q0 | ?]; first by move: pn0; rewrite epq q0 mul0r eqxx.\nhave -> : size p = (size q).+1.\n   by rewrite epq size_Mmonic ?monicXsubC // size_XsubC addnC.\nsuff /eq_in_all h : {in rs, root q =1 root p} by apply: ihrs => //; rewrite h.\nmove=> x xrs; rewrite epq rootM root_XsubC orbC; case: (altP (x =P r)) => // exr.\nby move: rnrs; rewrite -exr xrs.\nQed.\n\nLemma roots_geq_poly_eq0 p (rs : seq R) : all (root p) rs -> uniq rs ->\n  (size rs >= size p)%N -> p = 0.\nProof. by move=> ??; apply: contraTeq => ?; rewrite leqNgt max_poly_roots. Qed.\n\nEnd PolynomialIdomain.\n\nCanonical polynomial_countUnitRingType (R : countIdomainType) :=\n  [countUnitRingType of polynomial R].\nCanonical poly_countUnitRingType (R : countIdomainType) :=\n  [countUnitRingType of {poly R}].\nCanonical polynomial_countComUnitRingType (R : countIdomainType) :=\n  [countComUnitRingType of polynomial R].\nCanonical poly_countComUnitRingType (R : countIdomainType) :=\n  [countComUnitRingType of {poly R}].\nCanonical polynomial_countIdomainType (R : countIdomainType) :=\n  [countIdomainType of polynomial R].\nCanonical poly_countIdomainType (R : countIdomainType) :=\n  [countIdomainType of {poly R}].\n\nSection MapFieldPoly.\n\nVariables (F : fieldType) (R : ringType) (f : {rmorphism F -> R}).\n\nLocal Notation \"p ^f\" := (map_poly f p) : ring_scope.\n\nLemma size_map_poly p : size p^f = size p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite rmorph0 !size_poly0.\nby rewrite size_poly_eq // fmorph_eq0 // lead_coef_eq0.\nQed.\n\nLemma lead_coef_map p : lead_coef p^f = f (lead_coef p).\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !(rmorph0, lead_coef0).\nby rewrite lead_coef_map_eq // fmorph_eq0 // lead_coef_eq0.\nQed.\n\nLemma map_poly_eq0 p : (p^f == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 size_map_poly. Qed.\n\nLemma map_poly_inj : injective (map_poly f).\nProof.\nmove=> p q eqfpq; apply/eqP; rewrite -subr_eq0 -map_poly_eq0.\nby rewrite rmorphB /= eqfpq subrr.\nQed.\n\nLemma map_monic p : (p^f \\is monic) = (p \\is monic).\nProof. by rewrite monicE lead_coef_map fmorph_eq1. Qed.\n\nLemma map_poly_com p x : comm_poly p^f (f x).\nProof. exact: map_comm_poly (mulrC x _). Qed.\n\nLemma fmorph_root p x : root p^f (f x) = root p x.\nProof. by rewrite rootE horner_map // fmorph_eq0. Qed.\n\nLemma fmorph_unity_root n z : n.-unity_root (f z) = n.-unity_root z.\nProof. by rewrite !unity_rootE -(inj_eq (fmorph_inj f)) rmorphX ?rmorph1. Qed.\n\nLemma fmorph_primitive_root n z :\n  n.-primitive_root (f z) = n.-primitive_root z.\nProof.\nby congr (_ && _); apply: eq_forallb => i; rewrite fmorph_unity_root.\nQed.\n\nEnd MapFieldPoly.\n\nArguments map_poly_inj {F R} f [p1 p2] : rename.\n\nSection MaxRoots.\n\nVariable R : unitRingType.\nImplicit Types (x y : R) (rs : seq R) (p : {poly R}).\n\nDefinition diff_roots (x y : R) := (x * y == y * x) && (y - x \\in GRing.unit).\n\nFixpoint uniq_roots rs :=\n  if rs is x :: rs' then all (diff_roots x) rs' && uniq_roots rs' else true.\n\nLemma uniq_roots_prod_XsubC p rs :\n    all (root p) rs -> uniq_roots rs ->\n  exists q, p = q * \\prod_(z <- rs) ('X - z%:P).\nProof.\nelim: rs => [|z rs IHrs] /=; first by rewrite big_nil; exists p; rewrite mulr1.\ncase/andP=> rpz rprs /andP[drs urs]; case: IHrs => {urs rprs}// q def_p.\nhave [|q' def_q] := factor_theorem q z _; last first.\n  by exists q'; rewrite big_cons mulrA -def_q.\nrewrite {p}def_p in rpz.\nelim/last_ind: rs drs rpz => [|rs t IHrs] /=; first by rewrite big_nil mulr1.\nrewrite all_rcons => /andP[/andP[/eqP czt Uzt] /IHrs {IHrs}IHrs].\nrewrite -cats1 big_cat big_seq1 /= mulrA rootE hornerM_comm; last first.\n  by rewrite /comm_poly hornerXsubC mulrBl mulrBr czt.\nrewrite hornerXsubC -opprB mulrN oppr_eq0 -(mul0r (t - z)).\nby rewrite (inj_eq (mulIr Uzt)) => /IHrs.\nQed.\n\nTheorem max_ring_poly_roots p rs :\n  p != 0 -> all (root p) rs -> uniq_roots rs -> size rs < size p.\nProof.\nmove=> nz_p _ /(@uniq_roots_prod_XsubC p)[// | q def_p]; rewrite def_p in nz_p *.\nhave nz_q: q != 0 by apply: contraNneq nz_p => ->; rewrite mul0r.\nrewrite size_Mmonic ?monic_prod_XsubC // (polySpred nz_q) addSn /=.\nby rewrite size_prod_XsubC leq_addl.\nQed.\n\nLemma all_roots_prod_XsubC p rs :\n    size p = (size rs).+1 -> all (root p) rs -> uniq_roots rs ->\n  p = lead_coef p *: \\prod_(z <- rs) ('X - z%:P).\nProof.\nmove=> size_p /uniq_roots_prod_XsubC def_p Urs.\ncase/def_p: Urs => q -> {p def_p} in size_p *.\nhave [q0 | nz_q] := eqVneq q 0; first by rewrite q0 mul0r size_poly0 in size_p.\nhave{q nz_q size_p} /size_poly1P[c _ ->]: size q == 1%N.\n  rewrite -(eqn_add2r (size rs)) add1n -size_p.\n  by rewrite size_Mmonic ?monic_prod_XsubC // size_prod_XsubC addnS.\nby rewrite lead_coef_Mmonic ?monic_prod_XsubC // lead_coefC mul_polyC.\nQed.\n\nEnd MaxRoots.\n\nSection FieldRoots.\n\nVariable F : fieldType.\nImplicit Types (p : {poly F}) (rs : seq F).\n\nLemma poly2_root p : size p = 2 -> {r | root p r}.\nProof.\ncase: p => [[|p0 [|p1 []]] //= nz_p1]; exists (- p0 / p1).\nby rewrite /root addr_eq0 /= mul0r add0r mulrC divfK ?opprK.\nQed.\n\nLemma uniq_rootsE rs : uniq_roots rs = uniq rs.\nProof.\nelim: rs => //= r rs ->; congr (_ && _); rewrite -has_pred1 -all_predC.\nby apply: eq_all => t; rewrite /diff_roots mulrC eqxx unitfE subr_eq0.\nQed.\n\nSection UnityRoots.\n\nVariable n : nat.\n\nLemma max_unity_roots rs :\n  n > 0 -> all n.-unity_root rs -> uniq rs -> size rs <= n.\nProof.\nmove=> n_gt0 rs_n_1 Urs; have szPn := size_Xn_sub_1 F n_gt0.\nby rewrite -ltnS -szPn max_poly_roots -?size_poly_eq0 ?szPn.\nQed.\n\nLemma mem_unity_roots rs :\n    n > 0 -> all n.-unity_root rs -> uniq rs -> size rs = n ->\n  n.-unity_root =i rs.\nProof.\nmove=> n_gt0 rs_n_1 Urs sz_rs_n x; rewrite -topredE /=.\napply/idP/idP=> xn1; last exact: (allP rs_n_1).\napply: contraFT (ltnn n) => not_rs_x.\nby rewrite -{1}sz_rs_n (@max_unity_roots (x :: rs)) //= ?xn1 ?not_rs_x.\nQed.\n\n(* Showing the existence of a primitive root requires the theory in cyclic. *)\n\nVariable z : F.\nHypothesis prim_z : n.-primitive_root z.\n\nLet zn := [seq z ^+ i | i <- index_iota 0 n].\n\nLemma factor_Xn_sub_1 : \\prod_(0 <= i < n) ('X - (z ^+ i)%:P) = 'X^n - 1.\nProof.\ntransitivity (\\prod_(w <- zn) ('X - w%:P)); first by rewrite big_map.\nhave n_gt0: n > 0 := prim_order_gt0 prim_z.\nrewrite (@all_roots_prod_XsubC _ ('X^n - 1) zn); first 1 last.\n- by rewrite size_Xn_sub_1 // size_map size_iota subn0.\n- apply/allP=> _ /mapP[i _ ->] /=; rewrite rootE !hornerE hornerXn.\n  by rewrite exprAC (prim_expr_order prim_z) expr1n subrr.\n- rewrite uniq_rootsE map_inj_in_uniq ?iota_uniq // => i j.\n  rewrite !mem_index_iota => ltin ltjn /eqP.\n  by rewrite (eq_prim_root_expr prim_z) !modn_small // => /eqP.\nby rewrite (monicP (monic_Xn_sub_1 F n_gt0)) scale1r.\nQed.\n\nLemma prim_rootP x : x ^+ n = 1 -> {i : 'I_n | x = z ^+ i}.\nProof.\nmove=> xn1; pose logx := [pred i : 'I_n | x == z ^+ i].\ncase: (pickP logx) => [i /eqP-> | no_i]; first by exists i.\ncase: notF; suffices{no_i}: x \\in zn.\n  case/mapP=> i; rewrite mem_index_iota => lt_i_n def_x.\n  by rewrite -(no_i (Ordinal lt_i_n)) /= -def_x.\nrewrite -root_prod_XsubC big_map factor_Xn_sub_1.\nby rewrite [root _ x]unity_rootE xn1.\nQed.\n\nEnd UnityRoots.\n\nEnd FieldRoots.\n\nSection MapPolyRoots.\n\nVariables (F : fieldType) (R : unitRingType) (f : {rmorphism F -> R}).\n\nLemma map_diff_roots x y : diff_roots (f x) (f y) = (x != y).\nProof.\nrewrite /diff_roots -rmorphB // fmorph_unit // subr_eq0 //.\nby rewrite rmorph_comm // eqxx eq_sym.\nQed.\n\nLemma map_uniq_roots s : uniq_roots (map f s) = uniq s.\nProof.\nelim: s => //= x s ->; congr (_ && _); elim: s => //= y s ->.\nby rewrite map_diff_roots -negb_or.\nQed.\n\nEnd MapPolyRoots.\n\nSection AutPolyRoot.\n(* The action of automorphisms on roots of unity. *)\n\nVariable F : fieldType.\nImplicit Types u v : {rmorphism F -> F}.\n\nLemma aut_prim_rootP u z n :\n  n.-primitive_root z -> {k | coprime k n & u z = z ^+ k}.\nProof.\nmove=> prim_z; have:= prim_z; rewrite -(fmorph_primitive_root u) => prim_uz.\nhave [[k _] /= def_uz] := prim_rootP prim_z (prim_expr_order prim_uz).\nby exists k; rewrite // -(prim_root_exp_coprime _ prim_z) -def_uz.\nQed.\n\nLemma aut_unity_rootP u z n : n > 0 -> z ^+ n = 1 -> {k | u z = z ^+ k}.\nProof.\nby move=> _ /prim_order_exists[// | m /(aut_prim_rootP u)[k]]; exists k.\nQed.\n\nLemma aut_unity_rootC u v z n : n > 0 -> z ^+ n = 1 -> u (v z) = v (u z).\nProof.\nmove=> n_gt0 /(aut_unity_rootP _ n_gt0) def_z.\nhave [[i def_uz] [j def_vz]] := (def_z u, def_z v).\nby rewrite !(def_uz, def_vz, rmorphX) exprAC.\nQed.\n\nEnd AutPolyRoot.\n\nModule UnityRootTheory.\n\nNotation \"n .-unity_root\" := (root_of_unity n) : unity_root_scope.\nNotation \"n .-primitive_root\" := (primitive_root_of_unity n) : unity_root_scope.\nOpen Scope unity_root_scope.\n\nDefinition unity_rootE := unity_rootE.\nDefinition unity_rootP := @unity_rootP.\nArguments unity_rootP {R n z}.\n\nDefinition prim_order_exists := prim_order_exists.\nNotation prim_order_gt0 :=  prim_order_gt0.\nNotation prim_expr_order := prim_expr_order.\nDefinition prim_expr_mod := prim_expr_mod.\nDefinition prim_order_dvd := prim_order_dvd.\nDefinition eq_prim_root_expr := eq_prim_root_expr.\n\nDefinition rmorph_unity_root := rmorph_unity_root.\nDefinition fmorph_unity_root := fmorph_unity_root.\nDefinition fmorph_primitive_root := fmorph_primitive_root.\nDefinition max_unity_roots := max_unity_roots.\nDefinition mem_unity_roots := mem_unity_roots.\nDefinition prim_rootP := prim_rootP.\n\nEnd UnityRootTheory.\n\nSection DecField.\n\nVariable F : decFieldType.\n\nLemma dec_factor_theorem (p : {poly F}) :\n  {s : seq F & {q : {poly F} | p = q * \\prod_(x <- s) ('X - x%:P)\n                             /\\ (q != 0 -> forall x, ~~ root q x)}}.\nProof.\npose polyT (p : seq F) := (foldr (fun c f => f * 'X_0 + c%:T) (0%R)%:T p)%T.\nhave eval_polyT (q : {poly F}) x : GRing.eval [:: x] (polyT q) = q.[x].\n  by rewrite /horner; elim: (val q) => //= ? ? ->.\nhave [n] := ubnP (size p); elim: n => // n IHn in p *.\nhave /decPcases /= := @satP F [::] ('exists 'X_0, polyT p == 0%T).\ncase: ifP => [_ /sig_eqW[x]|_ noroot]; last first.\n  exists [::], p; rewrite big_nil mulr1; split => // p_neq0 x.\n  by apply/negP=> /rootP rpx; apply noroot; exists x; rewrite eval_polyT.\nrewrite eval_polyT => /rootP/factor_theorem/sig_eqW[p1 ->].\nhave [->|nz_p1] := eqVneq p1 0; first by exists [::], 0; rewrite !mul0r eqxx.\nrewrite size_Mmonic ?monicXsubC // size_XsubC addn2 => /IHn[s [q [-> irr_q]]].\nby exists (rcons s x), q; rewrite -cats1 big_cat big_seq1 mulrA.\nQed.\n\nEnd DecField.\n\nModule PreClosedField.\nSection UseAxiom.\n\nVariable F : fieldType.\nHypothesis closedF : GRing.ClosedField.axiom F.\nImplicit Type p : {poly F}.\n\nLemma closed_rootP p : reflect (exists x, root p x) (size p != 1%N).\nProof.\nhave [-> | nz_p] := eqVneq p 0.\n  by rewrite size_poly0; left; exists 0; rewrite root0.\nrewrite neq_ltn [in _ < 1]polySpred //=.\napply: (iffP idP) => [p_gt1 | [a]]; last exact: root_size_gt1.\npose n := (size p).-1; have n_gt0: n > 0 by rewrite -ltnS -polySpred.\nhave [a Dan] := closedF (fun i => - p`_i / lead_coef p) n_gt0.\nexists a; apply/rootP; rewrite horner_coef polySpred // big_ord_recr /= -/n.\nrewrite {}Dan mulr_sumr -big_split big1 //= => i _.\nby rewrite -!mulrA mulrCA mulNr mulVKf ?subrr ?lead_coef_eq0.\nQed.\n\nLemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0).\nProof.\napply: (iffP idP) => [nz_p | [x]]; last first.\n  by apply: contraNneq => ->; apply: root0.\nhave [[x /rootP p1x0]|] := altP (closed_rootP (p - 1)).\n  by exists x; rewrite -[p](subrK 1) /root hornerD p1x0 add0r hornerC oner_eq0.\nrewrite negbK => /size_poly1P[c _ /(canRL (subrK 1)) Dp].\nby exists 0; rewrite Dp -raddfD polyC_eq0 rootC in nz_p *.\nQed.\n\nEnd UseAxiom.\nEnd PreClosedField.\n\nSection ClosedField.\n\nVariable F : closedFieldType.\nImplicit Type p : {poly F}.\n\nLet closedF := @solve_monicpoly F.\n\nLemma closed_rootP p : reflect (exists x, root p x) (size p != 1%N).\nProof. exact: PreClosedField.closed_rootP. Qed.\n\nLemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0).\nProof. exact: PreClosedField.closed_nonrootP. Qed.\n\nLemma closed_field_poly_normal p :\n  {r : seq F | p = lead_coef p *: \\prod_(z <- r) ('X - z%:P)}.\nProof.\napply: sig_eqW; have [r [q [->]]] /= := dec_factor_theorem p.\nhave [->|] := altP eqP; first by exists [::]; rewrite mul0r lead_coef0 scale0r.\nhave [[x rqx ? /(_ isT x) /negP /(_ rqx)] //|] := altP (closed_rootP q).\nrewrite negbK => /size_poly1P [c c_neq0-> _ _]; exists r.\nrewrite mul_polyC lead_coefZ (monicP _) ?mulr1 //.\nby rewrite monic_prod => // i; rewrite monicXsubC.\nQed.\n\nEnd ClosedField.\n", "meta": {"author": "gares", "repo": "mathcomp", "sha": "f4ea1abac523107baf16e3cf528752b22ad8fdb5", "save_path": "github-repos/coq/gares-mathcomp", "path": "github-repos/coq/gares-mathcomp/mathcomp-f4ea1abac523107baf16e3cf528752b22ad8fdb5/mathcomp/algebra/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7463452902332361}}
{"text": "(**********************  TD n°6  ***************************)\n(*Benjamin Bracquier et Lilian Soler*)\n(* Ce TD porte sur la sémantique naturelle codée en Coq    *)\n(* du petit langage impératif WHILE déjà vu précédemment.  *)\n(* On va l'utiliser pour faire des dérivations, montrer    *)\n(* des propriétés, étudier des extensions.                 *)\n(***********************************************************)\n\n(* On importe les bibliothèques de Coq utiles pour le TD   *)\n\nRequire Import Bool Arith List.\nImport List.ListNotations.\n\n(** * On choisit de définir ici un état comme une liste d'entiers naturels.\n      On utilise ici le type list de la bibliothèque standard de Coq.\n      Ce type est polymorphe. On le spécialise pour des éléments de type nat. *)\n\nCheck list.\nCheck list nat.\n\nPrint list.\n\nCheck 0::1::3::nil.\n\n(* Ici on observe que la notation des listes façon ocaml est gérée par Coq. *)\n\nCheck [0;1;3].\n\nRemark List_Notation: [0;1;3] = 0::1::3::nil.\nProof.\n  (* complétez ici NIVEAU 1 *)\n  reflexivity .\n  Qed.\n\n(** * On reprend ici les AST définis aux séances précédentes *)\n\n(** ** Syntaxe des expressions arithétiques *)\n\nInductive aexp :=\n| Aco : nat -> aexp (* constantes *)\n| Ava : nat -> aexp (* variables *)\n| Apl : aexp -> aexp -> aexp\n| Amu : aexp -> aexp -> aexp\n| Amo : aexp -> aexp -> aexp\n.\n\n(** ** Syntaxe des expressions booléennes *)\n\nInductive bexp :=\n| Btrue : bexp\n| Bfalse : bexp\n| Bnot : bexp -> bexp\n| Band : bexp -> bexp -> bexp\n| Bor : bexp -> bexp -> bexp\n| Beq : bexp -> bexp -> bexp (* test égalité de bexp *)\n| Beqnat : aexp -> aexp -> bexp (* test égalité d'aexp *)\n.\n\n(** ** Syntaxe du langage impératif WHILE *)\n\nInductive winstr :=\n| Skip   : winstr\n| Assign : nat -> aexp -> winstr\n| Seq    : winstr -> winstr -> winstr\n| If     : bexp -> winstr -> winstr -> winstr\n| While  : bexp -> winstr -> winstr\n.\n\n(** ** Quelques listes/états pour faire des tests *)\n(** Ci-dessous, S1 est un état dans lequel la variable numéro 0\n    vaut 1, la variable numéro 1 vaut 2, et toutes les autres\n    valent 0' (valeur par défaut).                                      *)\n(** Plus généralement, une variable (Ava i) étant représentée par le\n    numéro i, sa valeur dans un état S est la valeur en ieme position\n    de la liste qui représente cet état S. *)\n\nDefinition state := list nat.\n\nDefinition S1 := [1; 2].\nDefinition S2 := [0; 3].\nDefinition S3 := [0; 7; 5; 41].\n\n(** * Sémantique *)\n(** On reprend les sémantiques fonctionnelles\n    des expressions artihmétiques et booléennes      *)\n\n(** La fonction get x s rend la valeur de x dans s. *)\n(** Elle rend 0 par défaut, par exemple si la variable\n    n'est pas définie/initialisée    *)\n\nFixpoint get (x:nat) (s:state) : nat :=\nmatch x,s with\n| 0   , v::_      => v\n| S x1, _::l1 => get x1 l1\n| _   , _         => 0\nend.\n\n(** Exemples *)\n\nCompute (get 0 S3).\nCompute (get 1 S3).\nCompute (get 2 S3).\nCompute (get 3 S3).\nCompute (get 4 S3).\n\n(** La mise à jour d'une variable v par un nouvel entier n dans un état s\n    s'écrit 'update s v n'\n    Cette fonction n'échoue jamais et écrit la valeur à sa place même\n    si elle n'est pas encore définie dans l'état *)\n\nFixpoint update (s:state) (v:nat) (n:nat): state :=\n  match v,s with\n  | 0   , a :: l1 => n :: l1\n  | 0   , nil     => n :: nil\n  | S v1, a :: l1 => a :: (update l1 v1 n)\n  | S v1, nil     => 0 :: (update nil v1 n)\n  end.\n\nDefinition S4 := update (update (update (update (update S1 4 1) 3 2) 2 3) 1 4) 0 5.\n\nCompute S1.\nCompute S4.\n\n(** ** Sémantique fonctionnelle de aexp*)\nFixpoint evalA (a: aexp) (s: state) : nat :=\n  match a with\n  | Aco n => n\n  | Ava x => get x s\n  | Apl a1 a2 =>  evalA a1 s + evalA a2 s\n  | Amu a1 a2 =>  evalA a1 s * evalA a2 s\n  | Amo a1 a2 =>  evalA a1 s - evalA a2 s\n  end.\n\n\n(** ** Sémantique fonctionnelle de Baexp*)\n\nDefinition eqboolb b1 b2 : bool :=\n  match b1, b2  with\n  | true , true  => true\n  | false, false => true\n  | _    , _     => false\n  end.\n\nFixpoint eqnatb n1 n2 : bool :=\n  match n1, n2 with\n  | O    , O     => true\n  | S n1', S n2' => eqnatb n1' n2'\n  | _    , _     => false\n  end.\n\nFixpoint evalB (b : bexp) (s : state) : bool :=\n  match b with\n  | Btrue => true\n  | Bfalse => false\n  | Bnot b => negb (evalB b s)\n  | Band e1 e2 => (evalB e1 s) && (evalB e2 s)\n  | Bor e1 e2 => (evalB e1 s) || (evalB e2 s)\n  | Beq e1 e2 => eqboolb (evalB e1 s) (evalB e2 s)\n  | Beqnat n1 n2 => eqnatb (evalA n1 s) (evalA n2 s)\n  end.\n\n(** Pour définir plus facilement des expressions de test on prédéfinit\n    des constantes entières ... *)\n\nDefinition N0 := Aco 0.\nDefinition N1 := Aco 1.\nDefinition N2 := Aco 2.\nDefinition N3 := Aco 3.\nDefinition N4 := Aco 4.\n\n(** ...  et des variables *)\n\nDefinition X := Ava 1.\nDefinition Y := Ava 2.\nDefinition Z := Ava 3.\n\n\n(** Quelques expressions arithmétiques pour tester *)\n\n(** exp1 = x + 3 *)\nDefinition E1 := Apl X N3.\n\n(** exp2 = y - 1 *)\nDefinition E2 := Amo Y N1.\n\n(** exp3 = (x + y) * 2 *)\nDefinition E3 := Amu (Apl X Y) N2.\n\nCompute (evalA E1 S1).\nCompute (evalA E1 S2).\nCompute (evalA E2 S1).\nCompute (evalA E2 S2).\nCompute (evalA E3 S1).\nCompute (evalA E3 S2).\n\n(** Quelques expressions booléennes pour tester *)\n\n(** B1 :=  exp1 = 4 *)\nDefinition B1 := Beqnat E1 N4.\n\n(** B2 := not ( bexp1 /\\ (exp1 = 7) *)\nDefinition B2 := Bnot (Band B1 (Beqnat X N2)).\n\nCompute (evalB B1 S1).\nCompute (evalB B1 S2).\nCompute (evalB B2 S1).\nCompute (evalB B2 S2).\n\n(** Corrigé du travail effectué en TD5 *)\n\nFail Fixpoint evalW (i : winstr) (s : state) {struct i} : state :=\n  match i with\n  | Skip       => s\n  | Assign x e => update s x (evalA e s)\n  | Seq i1 i2  => let s1 := evalW i1 s in evalW i2 s1\n               (*   (evalW i2 (evalW i1 s) *)\n  | If e i1 i2 => match evalB e s with\n                  | true  => evalW i1 s\n                  | false => evalW i2 s\n                  end\n  | (While e i1) as i => match evalB e s with\n                  | true  =>\n                    let s1 := evalW i1 s in evalW (While e i1) s1\n               (*   let s1 := evalW i1 s in evalW i s1                *)\n                  | false => s\n                  end\n  end.\n\n\n\n(** ** Version relationnelle, appelée \"sémantique naturelle\" *)\n\n(** Vu dans le CM précédent.\n    La sémantique naturelle (ou sémantique opérationnelle à grands pas)\n    du langage WHILE est donnée sous la forme d'un prédicat inductif. *)\n\nInductive SN: winstr -> state -> state -> Prop :=\n| SN_Skip        : forall s,\n                   SN Skip s s\n| SN_Assign      : forall x a s,\n                   SN (Assign x a) s (update s x (evalA a s))\n| SN_Seq         : forall i1 i2 s s1 s2,\n                   SN i1 s s1 -> SN i2 s1 s2 -> SN (Seq i1 i2) s s2\n| SN_If_true     : forall b i1 i2 s s1,\n                   (evalB b s = true)  ->  SN i1 s s1 -> SN (If b i1 i2) s s1\n| SN_If_false    : forall b i1 i2 s s2,\n                   (evalB b s = false) ->  SN i2 s s2 -> SN (If b i1 i2) s s2\n| SN_While_false : forall b i s,\n                   (evalB b s = false) ->  SN (While b i) s s\n| SN_While_true  : forall b i s s1 s2,\n                   (evalB b s = true)  ->  SN i s s1 -> SN (While b i) s1 s2 ->\n                   SN (While b i) s s2\n.\n\n(** On code dans WHILE un programme P1 correspondant à\n    while not (i=0) do {i:=i-1;x:=1+x} *)\nDefinition Il := 0.\nDefinition Ir := Ava Il.\nDefinition Xl := 1.\nDefinition Xr := Ava Xl.\n\nDefinition corps_boucle := Seq (Assign Il (Amo Ir N1)) (Assign Xl (Apl N1 Xr)).\nDefinition P1 := While (Bnot (Beqnat Ir N0)) corps_boucle.\n\n(** On montre que P1 transforme l'état S1 en l'état S2  *)\n\nTheorem reduction1 : SN P1 S1 S2.\n(** Regarder les états courants tout au long de la preuve *)\nProof.\n  cbv [P1]. cbv [S1]. cbv [S2].\n  (** Ou de façon équivalente :\n  unfold P1. unfold S1. unfold S2. *)\n\n  (** Ce but devrait être prouvé par l'une des deux dernières règles de SN,\n      qui portent sur le cas While.\n      On peut deviner laquelle de tête, ou demander de l'aide ainsi : *)\n  Compute (evalB (Bnot (Beqnat Ir N0)) [1; 2]).\n  (** Ce sera donc avec SN_While_true.\n      On peut essayer d'avancer avec 'apply SN_While_true.'  ... mais ça échoue.\n      Ici Coq ne peut pas deviner ce que sera l'état intermédiaire s1. *)\n  Fail apply SN_While_true.\n  (** Une stratégie possible serait d'indiquer directement l'état\n      intermédiaire avec la variante 'apply ... with (s1:= ...)'.\n      Il faut deviner les paramètres corrects ce qui n'est pas toujours facile.\n      Dans notre cas cela serait : *)\n  apply SN_While_true with (s1:=[0;3]).\n  (** On va donc proposer une autre stratégie· *)\n  Undo 1.\n  (** Une première possibilité est avec refine, déjà connu :\n      ici on indique un joker '_' pour chacun des HUIT arguments ;\n      [b], [i], [s] et [s2] se trouvent déterminés par la forme du but,\n      [s1] sera déterminé par la preuve de [SN s i s s1] et ne donne donc\n      pas lieu à un sous-but. Il restera à prouver :\n      [evalB b s = true], [SN i s s1] et [SN (While b i) s1 s2].  *)\n  refine (SN_While_true _ _ _ _ _ _ _ _).\n  (** On obtient le même effet avec la tactique [eapply], plus commode. *)\n  Undo 1.\n  eapply SN_While_true.\n  - reflexivity.\n  - cbv [corps_boucle].\n    (** Un nouvel état intermédiaire est à deviner *)\n    eapply SN_Seq.\n    + apply SN_Assign.\n    (* En appliquant cette règle nous avons fixé la valeur de l'état d'arrivée *)\n    + (* L'état de départ vient du cas précédent ;\n         comme les états sont connus on peut simplifier. *)\n      cbn [evalA Ir Il N1 get minus update].\n      (** Ou, plus rapidement *)\n      Undo 1.\n      cbn.\n      apply SN_Assign.\n  - cbn.\n    (** SN_While_true ou SN_While_false ? *)\n    Compute (evalB (Bnot (Beqnat Ir N0)) [0; 3]).\n    apply SN_While_false.\n    cbn.\n    reflexivity.\nQed.\n\n(** À FAIRE (NIVEAU 1) : présenter reduction1 sous forme d'arbre *)\nDefinition AFAIRE_dessin_reduction1 : unit.\nAdmitted.\n(*vu en cours*)\n(** Une autre présentation de ce script, structurée par accolades.\n    Cela permet de gérer l'indentation autrement\n    (surtout utile quand le corps de boucle s'exécute plusieurs fois. *)\nTheorem reduction1_accolades : SN P1 S1 S2.\nProof.\n  cbv [P1]. cbv [S1]. cbv [S2].\n  eapply SN_While_true.\n  { cbn. reflexivity. }\n  { cbv [corps_boucle].\n    eapply SN_Seq.\n    + apply SN_Assign.\n    + cbn. apply SN_Assign. }\n  cbn.\n  Compute (evalB (Bnot (Beqnat Ir N0)) [0; 3]).\n  apply SN_While_false.\n  cbn. reflexivity.\nQed.\n\n(** Exercice d'entraînement *)\n\nTheorem entrainement_P1 : SN P1 [2; 5] [0; 7].\nProof.\n  (* complétez ici NIVEAU 1 *)\ncbv[P1].\neapply SN_While_true.\n{ cbn. reflexivity. }\n{ cbv [corps_boucle].\n  eapply SN_Seq.\n+ apply SN_Assign.\n+ cbn. apply SN_Assign.}\ncbn.\neapply SN_While_true.\n{ cbn. reflexivity. }\n{ cbv [corps_boucle].\n  eapply SN_Seq.\n+ apply SN_Assign.\n+ cbn. apply SN_Assign.}\ncbn.\napply SN_While_false.\ncbn.  reflexivity.\nQed.\n\n(** On veut montrer maintenant que P1 rend toujours un état où\n    i vaut 0 et x voit sa valeur augmenter de la valeur initiale de i. *)\n\n(** Rappel : En Coq les entiers naturels sont définis par un type inductif\n    comprenant les constructeurs O pour zéro et S pour le successeur. *)\n\nPrint nat.\n\n(** Les lemmes suivants de la bibliothèque Coq peuvent être utiles\n    - Lemma minus_n_O : forall n, n = n - 0.\n    - Lemma plus_n_Sm : forall n m, S (n + m) = n + S m. *)\n\nTheorem reduction2 : forall x y, SN P1 [x;y] [0;x+y].\nProof.\n  cbv[P1 Ir Il N1 Xr Xl]; intros x.\n  induction x as [ | x Hrec_x];\n    intros; cbn [evalA];cbn [evalB].\n  (** complétez ici NIVEAU 2 *)\n  -apply SN_While_false.\n   cbn . reflexivity.\n  -eapply SN_While_true.\nAdmitted.\n\n   (** *** Calcul du carré avec des additions *)\n(** On code dans While un programme Pcarre correspondant à\n    while not (i=n) do {i:= 1+i; x:= y+x ; y:= 2+y} *)\n(* (* *déjà définis *)\nDefinition Il := 0.\nDefinition Ir := Ava Il.\nDefinition Xl := 1.\nDefinition Xr := Ava Xl.*)\nDefinition Yl := 2.\nDefinition Yr := Ava Yl.\n\nDefinition incrI := Assign Il (Apl N1 Ir).\nDefinition incrX := Assign Xl (Apl Yr Xr).\nDefinition incrY := Assign Yl (Apl N2 Yr).\nDefinition corps_carre := Seq incrI (Seq incrX incrY).\nDefinition Pcarre_2 := While (Bnot (Beqnat Ir (Aco 2))) corps_carre.\nDefinition Pcarre n := While (Bnot (Beqnat Ir (Aco n))) corps_carre.\n\nTheorem reduction_Pcarre_2 : SN (Pcarre_2) [0;0;1] [2;4;5].\nProof.\n  (* complétez ici NIVEAU 1 *)\ncbv[Pcarre_2].\neapply SN_While_true.\n{ cbn. reflexivity.}\n{ cbv [corps_carre].\n  eapply SN_Seq.\n  + apply SN_Assign.\n  + cbn. eapply SN_Seq.\n -apply SN_Assign.\n -cbn. apply SN_Assign. }\n cbn. eapply SN_While_true.\n{ cbn. reflexivity . }\n{ cbv [corps_carre].\n  eapply SN_Seq.\n +apply SN_Assign.\n +cbn. eapply SN_Seq .\n - apply SN_Assign .\n -cbn. apply SN_Assign. }\n cbn. apply SN_While_false.\ncbn. reflexivity.\nQed.  \n(** Énoncer et démontrer que Pcarre n permet de calculer le carré de n *)\n(* Complétez ici NIVEAU 4\n   (pas de technique nouvelle, mais demande de la créativité *)\n\n(** Sur le même modèle, trouver un programme Pcube n'utilisant que des\n    additions, énoncer et démontrer qu'il est correct. *)\n(* Complétez ici NIVEAU 6\n   (pas de technique nouvelle, mais demande de la créativité *)\n\n(* -------------------------------------------------------------------------- *)\n(** ** Preuve par récurrence structurelle dans un prédicat inductif *)\n\n\n(** Transformation simple de programme :\n   -  if true  then X else Y ---> X\n   -  if false then X else Y ---> Y  *)\nFixpoint simpl_test_Btrue_Bfalse (i: winstr) : winstr :=\n  match i with\n  | Skip => Skip\n  | Assign v a => i\n  | Seq w1 w2 => Seq (simpl_test_Btrue_Bfalse w1)\n                     (simpl_test_Btrue_Bfalse w2)\n  | If Btrue i1 i2 => simpl_test_Btrue_Bfalse i1\n  | If Bfalse i1 i2 =>\n    (* complétez ici NIVEAU 1 *)\nend.\n(** Comme indiqué ci-dessus on va procéder par récurrence structurelle sur\n     les arbres de preuve de [SN i s s'] *)\nTheorem simpl_test_Btrue_Bfalse_correct :\n  forall i s s', SN i s s' -> SN (simpl_test_Btrue_Bfalse i) s s'.\nProof.\n  (** On essaie d'abord une récurrence sur i.\n      Même avec prudence, de la façon la plus générale possible\n      (les états [s] et [s'], ainsi que l'hypothèse [SN i s s'] sont\n      introduits APRÈS [induction i]), on verra que les buts ne sont\n      pas comme souhaité *)\n  intro i.\n  induction i as [ | | | | ]; (** sans nommer les composantes pour alléger *)\n    intros s s' sn (** les introductions sont effectuées systématiquement\n                         sur chaque sous-but *).\n  (** On observe que l'hypothèse [sn] devrait entraîner [s = s'],\n      mais on ne l'a pas obtenu directement ;\n      tous les autres sous-buts souffrent de problèmes analogues. *)\n  Undo 2.\n  (** Il est bien plus opportun de raisonner par récurrence sur [sn] car\n      on aura naturellement non seulement la décomposition de [i] mais en plus\n      les contraintes dictées par la définition de SN *)\n  intros i s s' sn.\n  induction sn as  [ (* SN_Skip *) s\n                   | (* SN_Assign *) x s a\n                   | (* SN_Seq *) i1 i2 s s1 s' sn1 hrec_sn1 sn2 hrec_sn2\n                   | (* SN_If_true *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_If_false *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_While_false *) (* complétez ici NIVEAU 1 *)\n                   | (* SN_While_true *) (* complétez ici NIVEAU 1 *)\n                   ]; cbn [simpl_test_Btrue_Bfalse].\n\n (** La preuve qui suit est un peu fastidieuse, on verra plus tard\n     des moyens de la fabriquer plus intelligemment. *)\n (** Certains buts contiendront en une hypothèse se convertissant en\n     [false = true] (plus visible en utilisant [cbn in ...].\n     On pourra se souvenir d'une technique vue auparavant (égalités contagieuses).\n  *)\n(** complétez ici\n     - nombreux sous-buts NIVEAU 2\n     - quelques sous-buts NIVEAU 3, utiliser admit si besoin *)\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** Une autre transformation simple (facultatif, pour l'entraînement)\n  -  if (Bnot b) then X else Y ---> if b then Y else X  *)\n\nFixpoint simpl_test_echange (i: winstr) : winstr.\n  (** complétez ici NIVEAU 1 *)\nAdmitted.\n\nLemma negb_negb : forall b, b = negb (negb b).\nProof.\n  (** complétez ici NIVEAU 1 *)\nAdmitted.\n\nLemma Bnot_negb : forall {B s b}, evalB (Bnot B) s = b -> evalB B s = negb b.\nProof.\n (** complétez ici NIVEAU 1 *)\nAdmitted.\n\n(** Suivre le même principe que pour simpl_test_Btrue_Bfalse_correct. *)\nTheorem simpl_test_echange_correct :\n  forall i s s', SN i s s' -> SN (simpl_test_echange i) s s'.\nProof.\n  (** complétez ici\n     - nombreux sous-buts NIVEAU 2\n     - quelques sous-buts NIVEAU 3, utiliser admit si besoin *)\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** ** Interlude sur l'inversion *)\n\n(** Dans l'exercice qui suit, on aura un but comprenant\n    une hypothèse de la forme [SN i s s2],\n    où [i] est lui-même de la forme [Seq i1 i2]    (1).\n    Sans la condition (1), il serait naturel de procéder par\n    cas sur [i], ce qui donnerait lieu aux 7 cas ;\n    mais avec la condition (1), on voit que seul un cas\n    est pertinent, correpondant à SN_Seq.\n    Cette technique de preuve est dite \"par inversion\".\n    On va se ramener à une situation plus simple au moyen du\n    prédicat auxiliaire suivant, qui isole le cas intéressant de SN.\n *)\n\nInductive SN1_Seq i1 i2 s s2 : Prop :=\n| SN1_Seq_intro : forall s1,\n                  SN i1 s s1 -> SN i2 s1 s2 -> SN1_Seq i1 i2 s s2\n.\n\n(** On peut alors démontrer la conséquence suivante d'une hypothèse\n    respectant la condition (1) ci-dessus *)\n\nLemma inv_Seq' : forall {i1 i2 s s2}, SN (Seq i1 i2) s s2 -> SN1_Seq i1 i2 s s2.\nProof.\n  intros i1 i2 s s2 sn.\n  (** Ici in utilise une tactique magique de Coq. *)\n  inversion sn.\n  (** Puis une autre, pour nettoyer les égalités. *)\n  subst.\n  apply (SN1_Seq_intro _ _ _ _ _ H1 H4).\nQed.\n\n(** Mode d'emploi. Devant ce but :\n\n H18 : SN (Seq i1 i2) s s2\n =========================\n conclusion\n\nAu lieu d'un\n  destruct H18\nqui donne 7 cas, on observe que\n[inv_Seq' H18]   est de type   [SN1_Seq i1 i2 s s2]\net donc on peut de manière plus adéquate utiliser\n  destruct (inv_Seq' H18) as [s1 sn1 sn2]\nqui ne prévoit qu'un cas, celui qui est pertinent.\n*)\n\n(** Voici une preuve par \"petites inversions\" du même théorème,\n    qui n'utilise que les connaissances élémentaires déjà acquises,\n    en particulier un programme à la \"ouf_ouf\" (voir coq3_B_A_BA_ouf.v\n    dans les supports de CM).\n    Il n'est pas indispensable de la comprendre avant de l'utiliser.\n    EXERCICES FACULTATIFS :\n    1) expliquer le fonctionnement cette preuve.\n    2) dans les scripts à suivre, utiliser SN_inv\n       au lieu de inv_Seq\n       (intérêt : cela pourra être généralisé).\n *)\nInductive SN1_trivial (s s1 : state) : Prop := Triv : SN1_trivial s s1.\n\nDefinition dispatch (i: winstr) : state -> state -> Prop :=\n  match i with\n  | Seq i1 i2 => SN1_Seq i1 i2\n  | _ => SN1_trivial\n  end.\n\nDefinition SN_inv {i s s2} (sn : SN i s s2) : dispatch i s s2 :=\n  match sn with\n  | SN_Seq i1 i2 s s1 s2 sn1 sn2 =>\n    SN1_Seq_intro _ _ _ _ s1 sn1 sn2\n  | _ => Triv _ _\n  end.\n\nLemma inv_Seq : forall {i1 i2 s s2}, SN (Seq i1 i2) s s2 -> SN1_Seq i1 i2 s s2.\nProof.\n  intros * sn. apply (SN_inv sn).\nQed.\n\n(** *** Illustration *)\n(** Une autre manière d'exprimer la sémantique de WHILE ;\n    on prouvera que SN et SN' sont équivalentes. *)\nInductive SN': winstr -> state -> state -> Prop :=\n| SN'_Skip        : forall s,\n                    SN' Skip s s\n| SN'_Assign      : forall x a s,\n                    SN' (Assign x a) s (update s x (evalA a s))\n| SN'_Seq         : forall i1 i2 s s1 s2,\n                    SN' i1 s s1 -> SN' i2 s1 s2 -> SN' (Seq i1 i2) s s2\n| SN'_If_true     : forall b i1 i2 s s1,\n                    (evalB b s = true)  ->  SN' i1 s s1 -> SN' (If b i1 i2) s s1\n| SN'_If_false    : forall b i1 i2 s s2,\n                    (evalB b s = false) ->  SN' i2 s s2 -> SN' (If b i1 i2) s s2\n| SN'_While_false : forall b i s,\n                    (evalB b s = false) ->  SN' (While b i) s s\n| SN'_While_true  : forall b i s s1,\n                    (evalB b s = true)  ->  SN' (Seq i (While b i)) s s1 ->\n                    SN' (While b i) s s1\n.\n\n\n(** La direction suivante ne pose pas de nouvelle difficulté *)\nLemma SN_SN' : forall i s s1, SN i s s1 -> SN' i s s1.\nProof.\n  intros i s s1 sn.\n  induction sn as  [ (* SN_Skip *) s\n                   | (* SN_Assign *) x s a\n                   | (* SN_Seq *) i1 i2 s s1 s' sn1 hrec_sn1 sn2 hrec_sn2\n                   | (* SN_If_true *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_If_false *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_While_false *) (* complétez ici NIVEAU 1 *)\n                   | (* SN_While_true *)  (* complétez ici NIVEAU 1 *)\n                   ].\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - (** Le sous-but le plus intéressant, où les formulations diffèrent entre\n        SN' et SN *)\n    apply SN'_While_true.\n    + admit (** complétez ici NIVEAU 1 *).\n    + eapply SN'_Seq.\n      -- admit (** complétez ici NIVEAU 2 *).\n      -- admit (** complétez ici NIVEAU 2 *).\nAdmitted.\n\n(** Pour la réciproque le script est semblable SAUF au dernier sous-but,\n    qui précisément demande une inversion. *)\nLemma SN'_SN : forall i s s1, SN' i s s1 -> SN i s s1.\nProof.\n  intros i s s1 sn'.\n  induction sn' as [ (* SN_Skip *) s\n                   | (* SN_Assign *) x s a\n                   | (* SN_Seq *) i1 i2 s s1 s' sn1 hrec_sn1 sn2 hrec_sn2\n                   | (* SN_If_true *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_If_false *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_While_false *) cond i s e\n                   | (* SN_While_true *)\n                     cond i s s' e sn hrec_sn\n                   ].\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - (** NIVEAU 4 *)\n    (** Ici il faut exploiter l'hypothèse\n        hrec_sn : SN (Seq i (While cond i)) s s'\n        On observe que cette hypothèse est de la forme SN (Seq i1 i2) s s'\n        qui est un cas particulier de SN i s s' ;\n        cependant un destruct de hrec_sn oublierait que l'on est\n        dans ce cas particulier *)\n    destruct hrec_sn as [ | | | | | | ].\n    + (** Le but obtenu ici correspond au cas où\n          [Seq i (While cond i)] serait en même temps [Skip]\n          un cas qui est hors propos. *)\n      Undo 1.\n    Undo 1.\n    (** Cela est résolu en utilisant\n        conséquence de hrec_sn indiquée par inv_Seq.\n        Voir le mode d'emploi indiqué ci-dessus.\n     *)\n    destruct (inv_Seq hrec_sn) as [s1 sn1 sn2].\n    (** On termine en utilisant ici SN_While_true *)\n    + eapply SN_While_true.\n      -- apply e.\n      -- apply sn1.\n      -- apply sn2.\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** ** Le langage REPEAT *)\n(** On considère maintenant un langage impératif sans la commande While,\n    mais comportant une autre instruction de boucle\n                       'repeat i until b\n    qui exécute i puis sort si b est vrai, et sinon recommence.\n *)\n\n(** Voici la syntaxe du langage REPEAT\n    (on redéfinit un nouveau type avec de nouveaux constructeurs.    *)\n\nInductive rinstr :=\n| RSkip   : rinstr\n| RAssign : nat -> aexp -> rinstr\n| RSeq    : rinstr -> rinstr -> rinstr\n| RIf     : bexp -> rinstr -> rinstr -> rinstr\n| Repeat  : rinstr -> bexp -> rinstr.\n\n(** Définir la sémantique naturelle du langage REPEAT *)\n\nInductive SNr: rinstr -> state -> state -> Prop :=\n| SNr_Skip        : forall s,\n                    SNr RSkip s s\n| SNr_Assign      : forall x e s,\n                    SNr (RAssign x e) s (update s x (evalA e s))\n| SNr_Seq         : forall i1 i2 s s1 s2,\n                    SNr i1 s s1 -> SNr i2 s1 s2 -> SNr (RSeq i1 i2) s s2\n| SNr_If_true     : forall b i1 i2 s s1,\n                    evalB b s = true -> SNr i1 s s1 -> SNr (RIf b i1 i2) s s1\n| SNr_If_false    : forall b i1 i2 s s2,\n                    evalB b s = false -> SNr i2 s s2 -> SNr (RIf b i1 i2) s s2\n| SNr_Repeat_true : (** complétez ici NIVEAU 2 *)\n| SNr_Repeat_false: (** complétez ici NIVEAU 2 *)\n.\n\n(** On code dans REPEAT un programme P2 correspondant à\n    repeat {i:=i-1;x:=1+x} until i=0 *)\n\nDefinition corps_boucleR : rinstr. Admitted.\nDefinition P2 := Repeat corps_boucleR (Beqnat Ir N0).\n\nLemma P2_test : SNr P2 [2; 5] [0; 7].\nProof.\nAdmitted.\n\n(** À FAIRE : présenter P2_test sous forme d'arbre *)\nDefinition AFAIRE_dessin_P2_test : unit.\nAdmitted.\n\n\n(** *** Preuves sur SNr *)\n(** On va maintenant montrer que : 'Repeat i until b'\n    peut être traduit  par       : 'i; while (not b) do i'     *)\n\n(** Ecrire une fonction qui traduit toute expression rinstr en winstr en\n    remplaçant les Repeat par l'expression équivalente ci-dessus\n *)\n\nFixpoint repeat_while (i:rinstr) : winstr :=\n    match i with\n    | RSkip        => Skip\n    | RAssign v a  => Assign v a\n    | RSeq i1 i2   =>\n      (** complétez ici NIVEAU 2 *)\n    end.\n\n(** Avant d'aborder la preuve suivante, il est recommandé de tester\n    sur un petit programme REPEAT qu'après transformation son exécution\n    à partir d'un état initial concret donne bien le même état final.\n*)\n\n(** Montrer que cette transformation préserve la sémantique c-a-d : *)\n\nTheorem repeat_while_correct : forall i s1 s2, SNr i s1 s2 -> SN (repeat_while i) s1 s2.\nProof.\n  intros i s1 s2 sn.\n            (* complétez ici NIVEAU 3 *)\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** Transformation inverse *)\nFixpoint while_repeat (i:winstr) : rinstr :=\n    match i with\n    | Skip        => RSkip\n    | Assign v a  => RAssign v a\n    | Seq i1 i2   =>\n      (* complétez ici NIVEAU 3 *)\n    end.\n\n(** Avant d'aborder la preuve suivante, il est recommandé de tester\n    sur un petit programme WHILE qu'après transformation son exécution\n    à partir d'un état initial concret donne bien le même état final.\n*)\n\n\n(** Montrer que cette transformation préserve la sémantique *)\n(** La preuve suivante requiert quelques techniques supplémentaires,\n    à considérer seulement après la semaine 7 *)\n\nTheorem while_repeat_correct :\n  forall i s1 s2, SN i s1 s2 -> SNr (while_repeat i) s1 s2.\nProof.\n  intros i s_1 s_2 sn.\n            (** complétez ici NIVEAU 4 *)\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** ** Le langage WHILE-REPEAT *)\n(** Remarque : on pourrait également considérer un langage WHILE_REPEAT\n    comprenant à la fois l'instruction While et l'instruction Repeat\n *)\n", "meta": {"author": "LilianSOLER", "repo": "PF7", "sha": "dbe343844a602990cc9061a37d175d4c46e3eef3", "save_path": "github-repos/coq/LilianSOLER-PF7", "path": "github-repos/coq/LilianSOLER-PF7/PF7-dbe343844a602990cc9061a37d175d4c46e3eef3/tps-lt/TD06_SN_winstr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7463209632069429}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  zNil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nLemma append_assoc: forall l1 l2 l3, \n  append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\ninduction l1.\n  - simpl. intros. rewrite IHl1. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem: forall l n, Cons n (rev l) = rev (append l (Cons n Nil)).\nProof.\nintros. induction l.\n  - simpl. rewrite <- IHl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem2: forall l, rev (rev l) = l.\nProof.\ninduction l.\n  - simpl. rewrite <- lem. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem3: forall l, append l Nil = l.\nProof.\ninduction l.\n  - simpl. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (rev (append (rev x) (rev y))) (append y x).\nProof.\n induction x.\n - intros. simpl. rewrite <- append_assoc. simpl. \n   rewrite lem. rewrite IHx. rewrite <- append_assoc. reflexivity.\n - intros. simpl. rewrite lem2. rewrite lem3. reflexivity.\nQed.\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7463209408337077}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (x : natural) : natural :=\n  plus lf1 (mult x lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj153_coqofml_g3kqGe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7462806109068613}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus y (mult x (Succ y)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj256_coqofml_O8D8cC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7462601041315267}}
{"text": "Require Import Relation_Definitions.\n\nSection Relations.\n  Context {T: Type}.\n  Variable R: relation T.\n  Definition reflexive: Prop := forall a, R a a.\n  Definition transitive: Prop := forall a b c, R a b -> R b c -> R a c.\n  Definition symmetric: Prop := forall a b, R a b -> R b a.\n  Definition equivalence: Prop := reflexive /\\ transitive /\\ symmetric.\n  Definition antisymmetric: Prop := forall a b, R a b -> R b a -> a = b.\n  Definition asymmetric: Prop := forall a b, R a b -> ~R b a.\n  Definition preorder: Prop := reflexive /\\ transitive.\n  Definition partial_order: Prop := preorder /\\ antisymmetric.\n  \n  (* Asymmetry is stronger than antisymmetry. *)\n  Theorem asym_implies_antisym: asymmetric -> antisymmetric.\n  Proof.\n    unfold asymmetric. unfold antisymmetric. unfold not.\n    intros asym a b Rab Rba. \n    apply asym in Rab. destruct Rab. apply Rba.\n  Qed.\nEnd Relations.\n", "meta": {"author": "thinkpad20", "repo": "simple-coq-classes", "sha": "ef2c84fa5a8c851e06831ac5623037a7c3971535", "save_path": "github-repos/coq/thinkpad20-simple-coq-classes", "path": "github-repos/coq/thinkpad20-simple-coq-classes/simple-coq-classes-ef2c84fa5a8c851e06831ac5623037a7c3971535/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.746260100853475}}
{"text": "Set Implicit Arguments.\nRequire Import Lists.List.\nImport ListNotations.\n\nCheck list.\n\n\nPrint rev.\n\n\nFixpoint is_sorted A (l : list A) (R : A -> A -> Prop) :=\n  match l with\n    [] => True\n  | x :: xs => match xs with\n                [] => True\n              | y :: ys => R x y /\\ is_sorted xs R\n              end\n  end.\n\n\nTheorem warm_up : is_sorted [3;5;9] le.\nProof.\n  firstorder.\n  (* alternatively: (...)\n  simpl.\n  split. repeat constructor. (* constructor. constructor. constructor. *)\n  repeat constructor.\n   (* constructor. constructor. constructor. constructor.\n      constructor. constructor. *) *)\nQed.\n\n\nLemma is_sorted' : forall A (l : list A) R a b, is_sorted (l ++ [a]) R -> R a b -> is_sorted (l ++ [a; b]) R.\nProof.\n  intros.\n  induction l.\n  - simpl. firstorder.\n  - simpl.\n    destruct l.\n    (* `simpl in *` simplifies the goal and all the premises.\n       it is not needed here, but will help you see why `firstorder`\n       works. *)\n    + simpl in *. firstorder.\n      (* alternatively:\n      split.\n      * apply H.\n      * apply IHl. constructor. *)\n    + simpl in *. firstorder.\n      (* alternatively:\n      split.\n      * apply H.\n      * apply IHl. apply H. *)\nQed.\n    \nTheorem rev_sorted : forall l, is_sorted l lt -> is_sorted (rev l) gt.\nProof.\n  induction l.\n  - intro; simpl. trivial.\n  - simpl. induction l.\n    + simpl. trivial.\n    + simpl. simpl in IHl. firstorder. rewrite <- app_assoc. apply is_sorted'.\n      * assumption.\n      * assumption.\nQed.\n\n", "meta": {"author": "corwin-of-amber", "repo": "various-proofs", "sha": "e7c19549f1d573487f9fb3ebd5d6b80b2c52184b", "save_path": "github-repos/coq/corwin-of-amber-various-proofs", "path": "github-repos/coq/corwin-of-amber-various-proofs/various-proofs-e7c19549f1d573487f9fb3ebd5d6b80b2c52184b/ssar-class/lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8519528057272544, "lm_q1q2_score": 0.7461291819918516}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Supplementary Coq material: subset types\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/\n  * Much of the material comes from CPDT <http://adam.chlipala.net/cpdt/> by the same author. *)\n\nRequire Import FrapWithoutSets.\n(* We import a pared-down version of the book library, to avoid notations that\n * clash with some we want to use here. *)\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n(* Compatibility flag that affects pattern matching for fancy types *)\n\n\n(* So far, we have seen many examples of what we might call \"classical program\n * verification.\"  We write programs, write their specifications, and then prove\n * that the programs satisfy their specifications.  The programs that we have\n * written in Coq have been normal functional programs that we could just as\n * well have written in Haskell or ML.  In this lecture, we start investigating\n * uses of _dependent types_ to integrate programming, specification, and\n * proving into a single phase.  The techniques we will learn make it possible\n * to reduce the cost of program verification dramatically. *)\n\n\n(** * Introducing Subset Types *)\n\n(** Let us consider several ways of implementing the natural-number-predecessor\n * function.  We start by displaying the definition from the standard library: *)\n\nCompute pred.\n\n(* We can use a new command, [Extraction], to produce an OCaml version of this\n * function. *)\n\nExtraction pred.\n\n(* Returning 0 as the predecessor of 0 can come across as somewhat of a hack.\n * In some situations, we might like to be sure that we never try to take the\n * predecessor of 0.  We can enforce this by giving [pred] a stronger, dependent\n * type. *)\n\nLemma zgtz : 0 > 0 -> False.\nProof.\n  linear_arithmetic.\nQed.\n\nDefinition pred_strong1 (n : nat) : n > 0 -> nat :=\n  match n with\n  | O => fun pf : 0 > 0 => match zgtz pf with end\n  | S n' => fun _ => n'\n  end.\n\n(* We expand the type of [pred] to include a _proof_ that its argument [n] is\n * greater than 0.  When [n] is 0, we use the proof to derive a contradiction,\n * which we can use to build a value of any type via a vacuous pattern match.\n * When [n] is a successor, we have no need for the proof and just return the\n * answer.  The proof argument can be said to have a _dependent_ type, because\n * its type depends on the _value_ of the argument [n].\n *\n * Coq's [Compute] command can execute particular invocations of [pred_strong1]\n * just as easily as it can execute more traditional functional programs. *)\n\nTheorem two_gt0 : 2 > 0.\nProof.\n  linear_arithmetic.\nQed.\n\nCompute pred_strong1 two_gt0.\n\n(* One aspect in particular of the definition of [pred_strong1] may be\n * surprising.  We took advantage of [Definition]'s syntactic sugar for defining\n * function arguments in the case of [n], but we bound the proofs later with\n * explicit [fun] expressions.  Let us see what happens if we write this\n * function in the way that at first seems most natural. *)\n\nFail Definition pred_strong1' (n : nat) (pf : n > 0) : nat :=\n  match n with\n  | O => match zgtz pf with end\n  | S n' => n'\n  end.\n\n(* The term [zgtz pf] fails to type-check.  Somehow the type checker has failed\n * to take into account information that follows from which [match] branch that\n * term appears in.  The problem is that, by default, [match] does not let us\n * use such implied information.  To get refined typing, we must always rely on\n * [match] annotations, either written explicitly or inferred.\n *\n * In this case, we must use a [return] annotation to declare the relationship\n * between the _value_ of the [match] discriminee and the _type_ of the result.\n * There is no annotation that lets us declare a relationship between the\n * discriminee and the type of a variable that is already in scope; hence, we\n * delay the binding of [pf], so that we can use the [return] annotation to\n * express the needed relationship.\n *\n * We are lucky that Coq's heuristics infer the [return] clause (specifically,\n * [return n > 0 -> nat]) for us in the definition of [pred_strong1], leading to\n * the following elaborated code: *)\n\nDefinition pred_strong1' (n : nat) : n > 0 -> nat :=\n  match n return n > 0 -> nat with\n  | O => fun pf : 0 > 0 => match zgtz pf with end\n  | S n' => fun _ => n'\n  end.\n\n(* By making explicit the functional relationship between value [n] and the\n * result type of the [match], we guide Coq toward proper type checking.  The\n * clause for this example follows by simple copying of the original annotation\n * on the definition.  In general, however, the [match] annotation inference\n * problem is undecidable.  The known undecidable problem of\n * _higher-order unification_ reduces to the [match] type inference problem.\n * Over time, Coq is enhanced with more and more heuristics to get around this\n * problem, but there must always exist [match]es whose types Coq cannot infer\n * without annotations.\n *\n * Let us now take a look at the OCaml code Coq generates for [pred_strong1]. *)\n\nExtraction pred_strong1.\n\n(* The proof argument has disappeared!  We get exactly the OCaml code we would\n * have written manually.  This is our first demonstration of the main\n * technically interesting feature of Coq program extraction: proofs are erased\n * systematically.\n *\n * We can reimplement our dependently typed [pred] based on _subset types_,\n * defined in the standard library with the type family [sig]. *)\n\nPrint sig.\n\n(* We rewrite [pred_strong1], using some syntactic sugar for subset types, after\n * we deactivate some clashing notations for set literals. *)\n\nLocate \"{ _ : _ | _ }\".\n\nDefinition pred_strong2 (s : {n : nat | n > 0} ) : nat :=\n  match s with\n  | exist O pf => match zgtz pf with end\n  | exist (S n') _ => n'\n  end.\n\n(* To build a value of a subset type, we use the [exist] constructor, and the\n * details of how to do that follow from the output of our earlier [Print sig]\n * command, where we elided the extra information that parameter [A] is\n * implicit.  We need an extra [_] here and not in the definition of\n * [pred_strong2] because _parameters_ of inductive types (like the predicate\n * [P] for [sig]) are not mentioned in pattern matching, but _are_ mentioned in\n * construction of terms (if they are not marked as implicit arguments).\n * (Actually, this behavior changed between Coq versions 8.4 and 8.5, hence the\n * command at the top of the file to revert to the old behavior.) *)\n\nCompute pred_strong2 (exist _ 2 two_gt0).\n\nExtraction pred_strong2.\n\n(* We arrive at the same OCaml code as was extracted from [pred_strong1], which\n * may seem surprising at first.  The reason is that a value of [sig] is a pair\n * of two pieces, a value and a proof about it.  Extraction erases the proof,\n * which reduces the constructor [exist] of [sig] to taking just a single\n * argument.  An optimization eliminates uses of datatypes with single\n * constructors taking single arguments, and we arrive back where we started.\n *\n * We can continue on in the process of refining [pred]'s type.  Let us change\n * its result type to capture that the output is really the predecessor of the\n * input. *)\n\nDefinition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=\n  match s return {m : nat | proj1_sig s = S m} with\n  | exist 0 pf => match zgtz pf with end\n  | exist (S n') pf => exist _ n' (eq_refl _)\n  end.\n\nCompute pred_strong3 (exist _ 2 two_gt0).\n\n(* A value in a subset type can be thought of as a _dependent pair_ (or\n * _sigma type_) of a base value and a proof about it.  The function [proj1_sig]\n * extracts the first component of the pair.  It turns out that we need to\n * include an explicit [return] clause here, since Coq's heuristics are not\n * smart enough to propagate the result type that we wrote earlier.\n *\n * By now, the reader is probably ready to believe that the new [pred_strong]\n * leads to the same OCaml code as we have seen several times so far, and Coq\n * does not disappoint. *)\n\nExtraction pred_strong3.\n\n(* We have managed to reach a type that is, in a formal sense, the most\n * expressive possible for [pred].  Any other implementation of the same type\n * must have the same input-output behavior.  However, there is still room for\n * improvement in making this kind of code easier to write.  Here is a version\n * that takes advantage of tactic-based theorem proving.  We switch back to\n * passing a separate proof argument instead of using a subset type for the\n * function's input, because this leads to cleaner code.  ([False_rec] is a\n * library function that can be used to produce a value in any type given a\n * proof of [False].  It's defined in terms of the vacuous pattern match we saw\n * earlier.) *)\n\nDefinition pred_strong4 : forall (n : nat), n > 0 -> {m : nat | n = S m}.\n  refine (fun n =>\n    match n with\n    | O => fun _ => False_rec _ _\n    | S n' => fun _ => exist _ n' _\n    end).\n\n  (* We build [pred_strong4] using tactic-based proving, beginning with a\n   * [Definition] command that ends in a period before a definition is given.\n   * Such a command enters the interactive proving mode, with the type given for\n   * the new identifier as our proof goal.\n   *\n   * We do most of the work with the [refine] tactic, to which we pass a partial\n   * \"proof\" of the type we are trying to prove.  There may be some pieces left\n   * to fill in, indicated by underscores.  Any underscore that Coq cannot\n   * reconstruct with type inference is added as a proof subgoal.  In this case,\n   * we have two subgoals.\n   *\n   * We can see that the first subgoal comes from the second underscore passed\n   * to [False_rec], and the second subgoal comes from the second underscore\n   * passed to [exist].  In the first case, we see that, though we bound the\n   * proof variable with an underscore, it is still available in our proof\n   * context.  Both subgoals are easy to discharge, so let us back up and ask to\n   * prove all subgoals automatically. *)\n\n  Undo.\n  refine (fun n =>\n    match n with\n    | O => fun _ => False_rec _ _\n    | S n' => fun _ => exist _ n' _\n    end); equality || linear_arithmetic.\nDefined.\n\n(* We end the \"proof\" with [Defined] instead of [Qed], so that the definition we\n * constructed remains visible.  This contrasts to the case of ending a proof\n * with [Qed], where the details of the proof are hidden afterward.  (More\n * formally, [Defined] marks an identifier as _transparent_, allowing it to be\n * unfolded; while [Qed] marks an identifier as _opaque_, preventing unfolding.)\n * Let us see what our proof script constructed. *)\n\nPrint pred_strong4.\n\n(* We see the code we entered, with some (pretty long!) proofs filled in. *)\n\nCompute pred_strong4 two_gt0.\n\n(* We are almost done with the ideal implementation of dependent predecessor.\n * We can use Coq's syntax-extension facility to arrive at code with almost no\n * complexity beyond a Haskell or ML program with a complete specification in a\n * comment.  In this book, we will not dwell on the details of syntax\n * extensions; the Coq manual gives a straightforward introduction to them. *)\n\nNotation \"!\" := (False_rec _ _).\nNotation \"[ e ]\" := (exist _ e _).\n\nDefinition pred_strong5 : forall (n : nat), n > 0 -> {m : nat | n = S m}.\n  refine (fun n =>\n    match n with\n    | O => fun _ => !\n    | S n' => fun _ => [n']\n    end); equality || linear_arithmetic.\nDefined.\n\n(* By default, notations are also used in pretty-printing terms, including\n * results of evaluation. *)\n\nCompute pred_strong5 two_gt0.\n\n\n(** * Decidable Proposition Types *)\n\n(* There is another type in the standard library that captures the idea of\n * a program value indicating which of two propositions is true. *)\n\nPrint sumbool.\n\n(* We have been using this type family behind the scenes for various equality\n * checks, for instance: *)\nCheck \"x\" ==v \"y\".\n\n(* Here, the constructors of [sumbool] have types written in terms of a\n * registered notation for [sumbool], such that the result type of each\n * constructor desugars to [sumbool A B].  We can define some notations of our\n * own to make working with [sumbool] more convenient. *)\n\nNotation \"'Yes'\" := (left _ _).\nNotation \"'No'\" := (right _ _).\nNotation \"'Reduce' x\" := (if x then Yes else No) (at level 50).\n\n(* The [Reduce] notation is notable because it demonstrates how [if] is\n * overloaded in Coq.  The [if] form actually works when the test expression has\n * any two-constructor inductive type.  Moreover, in the [then] and [else]\n * branches, the appropriate constructor arguments are bound.  This is important\n * when working with [sumbool]s, when we want to have the proof stored in the\n * test expression available when proving the proof obligations generated in the\n * appropriate branch.\n *\n * Now we can write [eq_nat_dec], which compares two natural numbers, returning\n * either a proof of their equality or a proof of their inequality. *)\n\nDefinition eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\n  refine (fix f (n m : nat) : {n = m} + {n <> m} :=\n    match n, m with\n    | O, O => Yes\n    | S n', S m' => Reduce (f n' m')\n    | _, _ => No\n    end); equality.\nDefined.\n\nCompute eq_nat_dec 2 2.\nCompute eq_nat_dec 2 3.\n\n(* Note that the [Yes] and [No] notations are hiding proofs establishing the\n * correctness of the outputs.\n *\n * Our definition extracts to reasonable OCaml code. *)\n\nExtraction eq_nat_dec.\n\n(* Proving this kind of decidable equality result is so common that Coq comes\n * with a tactic for automating it. *)\n\nDefinition eq_nat_dec' (n m : nat) : {n = m} + {n <> m}.\n  decide equality.\nDefined.\n\n(* Curious readers can verify that the [decide equality] version extracts to the\n * same OCaml code as our more manual version does.  That OCaml code had one\n * undesirable property, which is that it uses [Left] and [Right] constructors\n * instead of the Boolean values built into OCaml.  We can fix this, by using\n * Coq's facility for mapping Coq inductive types to OCaml variant types. *)\n\nExtract Inductive sumbool => \"bool\" [\"true\" \"false\"].\nExtraction eq_nat_dec'.\n\n(* We can build \"smart\" versions of the usual Boolean operators and put them to\n * good use in certified programming.  For instance, here is a [sumbool] version\n * of Boolean \"or.\" *)\n\nNotation \"x || y\" := (if x then Yes else Reduce y).\n\n(* Let us use it for building a function that decides list membership.  We need\n * to assume the existence of an equality decision procedure for the type of\n * list elements. *)\n\nSection In_dec.\n  Variable A : Set.\n  Variable A_eq_dec : forall x y : A, {x = y} + {x <> y}.\n\n  (* The final function is easy to write using the techniques we have developed\n   * so far. *)\n\n  Definition In_dec : forall (x : A) (ls : list A), {In x ls} + {~ In x ls}.\n    refine (fix f (x : A) (ls : list A) : {In x ls} + {~ In x ls} :=\n      match ls with\n      | nil => No\n      | x' :: ls' => A_eq_dec x x' || f x ls'\n      end); simplify; equality.\n  Defined.\nEnd In_dec.\n\nCompute In_dec eq_nat_dec 2 [1; 2].\nCompute In_dec eq_nat_dec 3 [1; 2].\n\n(* The [In_dec] function has a reasonable extraction to OCaml. *)\n\nExtraction In_dec.\n\n(* This is more or the less code for the corresponding function from the OCaml\n * standard library. *)\n\n\n(** * Partial Subset Types *)\n\n(* Our final implementation of dependent predecessor used a very specific\n * argument type to ensure that execution could always complete normally.\n * Sometimes we want to allow execution to fail, and we want a more principled\n * way of signaling failure than returning a default value, as [pred] does for\n * [0].  One approach is to define this type family [maybe], which is a version\n * of [sig] that allows obligation-free failure. *)\n\nInductive maybe (A : Set) (P : A -> Prop) : Set :=\n| Unknown : maybe P\n| Found : forall x : A, P x -> maybe P.\n\n(* We can define some new notations, analogous to those we defined for subset\n * types. *)\n\nNotation \"{{ x | P }}\" := (maybe (fun x => P)).\nNotation \"??\" := (Unknown _).\nNotation \"[| x |]\" := (Found _ x _).\n\n(* Now our next version of [pred] is trivial to write. *)\n\nDefinition pred_strong7 : forall n : nat, {{m | n = S m}}.\n  refine (fun n =>\n    match n return {{m | n = S m}} with\n    | O => ??\n    | S n' => [|n'|]\n    end); trivial.\nDefined.\n\nCompute pred_strong7 2.\nCompute pred_strong7 0.\n\n(* Because we used [maybe], one valid implementation of the type we gave\n * [pred_strong7] would return [??] in every case.  We can strengthen the type\n * to rule out such vacuous implementations, and the type family [sumor] from\n * the standard library provides the easiest starting point.  For type [A] and\n * proposition [B], [A + {B}] desugars to [sumor A B], whose values are either\n * values of [A] or proofs of [B]. *)\n\nPrint sumor.\n\n(* We add notations for easy use of the [sumor] constructors.  The second\n * notation is specialized to [sumor]s whose [A] parameters are instantiated\n * with regular subset types, since this is how we will use [sumor] below. *)\n\nNotation \"!!\" := (inright _ _).\nNotation \"[|| x ||]\" := (inleft _ [x]).\n\n(* Now we are ready to give the final version of possibly failing predecessor.\n * The [sumor]-based type that we use is maximally expressive; any\n * implementation of the type has the same input-output behavior. *)\n\nDefinition pred_strong8 : forall n : nat, {m : nat | n = S m} + {n = 0}.\n  refine (fun n =>\n    match n with\n    | O => !!\n    | S n' => [||n'||]\n    end); trivial.\nDefined.\n\nCompute pred_strong8 2.\nCompute pred_strong8 0.\n\n(* As with our other maximally expressive [pred] function, we arrive at quite\n * simple output values, thanks to notations. *)\n\n\n(** * Monadic Notations *)\n\n(* We can treat [maybe] like a monad, in the same way that the Haskell [Maybe]\n * type is interpreted as a failure monad.  Our [maybe] has the wrong type to be\n * a literal monad, but a \"bind\"-like notation will still be helpful. *)\n\nNotation \"x <- e1 ; e2\" := (match e1 with\n                            | Unknown => ??\n                            | Found x _ => e2\n                            end)\n(right associativity, at level 60).\n\n(* The meaning of [x <- e1; e2] is: First run [e1].  If it fails to find an\n * answer, then announce failure for our derived computation, too.  If [e1]\n * _does_ find an answer, pass that answer on to [e2] to find the final result.\n * The variable [x] can be considered bound in [e2].\n *\n * This notation is very helpful for composing richly typed procedures.  For\n * instance, here is a very simple implementation of a function to take the\n * predecessors of two naturals at once. *)\n\nDefinition doublePred : forall n1 n2 : nat, {{p | n1 = S (fst p) /\\ n2 = S (snd p)}}.\n  refine (fun n1 n2 =>\n    m1 <- pred_strong7 n1;\n    m2 <- pred_strong7 n2;\n    [|(m1, m2)|]); propositional.\nDefined.\n\n(* We can build a [sumor] version of the \"bind\" notation and use it to write a\n * similarly straightforward version of this function. *)\n\nNotation \"x <-- e1 ; e2\" := (match e1 with\n                             | inright _ => !!\n                             | inleft (exist x _) => e2\n                             end)\n(right associativity, at level 60).\n\nDefinition doublePred' : forall n1 n2 : nat,\n  {p : nat * nat | n1 = S (fst p) /\\ n2 = S (snd p)}\n  + {n1 = 0 \\/ n2 = 0}.\n  refine (fun n1 n2 =>\n    m1 <-- pred_strong8 n1;\n    m2 <-- pred_strong8 n2;\n    [||(m1, m2)||]); propositional.\nDefined.\n\n(* This example demonstrates how judicious selection of notations can hide\n * complexities in the rich types of programs. *)\n\n\n(** * A Type-Checking Example *)\n\n(* We can apply these specification types to build a certified type checker for\n * a simple expression language. *)\n\nInductive exp :=\n| Nat (n : nat)\n| Plus (e1 e2 : exp)\n| Bool (b : bool)\n| And (e1 e2 : exp).\n\n(* We define a simple language of types and its typing rules. *)\n\nInductive type := TNat | TBool.\n\nInductive hasType : exp -> type -> Prop :=\n| HtNat : forall n,\n  hasType (Nat n) TNat\n| HtPlus : forall e1 e2,\n  hasType e1 TNat\n  -> hasType e2 TNat\n  -> hasType (Plus e1 e2) TNat\n| HtBool : forall b,\n  hasType (Bool b) TBool\n| HtAnd : forall e1 e2,\n  hasType e1 TBool\n  -> hasType e2 TBool\n  -> hasType (And e1 e2) TBool.\n\n(* It will be helpful to have a function for comparing two types.  We build one\n * using [decide equality]. *)\n\nDefinition eq_type_dec : forall t1 t2 : type, {t1 = t2} + {t1 <> t2}.\n  decide equality.\nDefined.\n\n(* Another notation complements the monadic notation for [maybe] that we defined\n * earlier.  Sometimes we want to include \"assertions\" in our procedures.  That\n * is, we want to run a decision procedure and fail if it fails; otherwise, we\n * want to continue, with the proof that it produced made available to us.  This\n * infix notation captures that idea, for a procedure that returns an arbitrary\n * two-constructor type. *)\n\nNotation \"e1 ;; e2\" := (if e1 then e2 else ??)\n  (right associativity, at level 60).\n\n(* With that notation defined, we can implement a [typeCheck] function, whose\n * code is only more complex than what we would write in ML because it needs to\n * include some extra type annotations.  Every [[|e|]] expression adds a\n * [hasType] proof obligation, and [eauto] makes short work of them when we add\n * [hasType]'s constructors as hints. *)\n\nLocal Hint Constructors hasType : core.\n\nDefinition typeCheck : forall e : exp, {{t | hasType e t}}.\n  refine (fix F (e : exp) : {{t | hasType e t}} :=\n    match e return {{t | hasType e t}} with\n    | Nat _ => [|TNat|]\n    | Plus e1 e2 =>\n      t1 <- F e1;\n      t2 <- F e2;\n      eq_type_dec t1 TNat;;\n      eq_type_dec t2 TNat;;\n      [|TNat|]\n    | Bool _ => [|TBool|]\n    | And e1 e2 =>\n      t1 <- F e1;\n      t2 <- F e2;\n      eq_type_dec t1 TBool;;\n      eq_type_dec t2 TBool;;\n      [|TBool|]\n    end); subst; eauto.\nDefined.\n\n(* Despite manipulating proofs, our type checker is easy to run. *)\n\nCompute typeCheck (Nat 0).\nCompute typeCheck (Plus (Nat 1) (Nat 2)).\nCompute typeCheck (Plus (Nat 1) (Bool false)).\n\n(* The type checker also extracts to some reasonable OCaml code. *)\n\nExtraction typeCheck.\n\n(* We can adapt this implementation to use [sumor], so that we know our type-checker\n * only fails on ill-typed inputs.  First, we define an analogue to the\n * \"assertion\" notation. *)\n\nNotation \"e1 ;;; e2\" := (if e1 then e2 else !!)\n  (right associativity, at level 60).\n\n(* Next, we prove a helpful lemma, which states that a given expression can have\n * at most one type. *)\n\nLemma hasType_det : forall e t1,\n  hasType e t1\n  -> forall t2, hasType e t2\n    -> t1 = t2.\nProof.\n  induct 1; invert 1; equality.\nQed.\n\n(* Now we can define the type-checker.  Its type expresses that it only fails on\n * untypable expressions. *)\n\nLocal Hint Resolve hasType_det : core.\n(* The lemma [hasType_det] will also be useful for proving proof obligations\n * with contradictory contexts. *)\n\nDefinition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~ hasType e t}.\n  (* Finally, the implementation of [typeCheck] can be transcribed literally,\n   * simply switching notations as needed. *)\n\n  refine (fix F (e : exp) : {t : type | hasType e t} + {forall t, ~ hasType e t} :=\n    match e return {t : type | hasType e t} + {forall t, ~ hasType e t} with\n      | Nat _ => [||TNat||]\n      | Plus e1 e2 =>\n        t1 <-- F e1;\n        t2 <-- F e2;\n        eq_type_dec t1 TNat;;;\n        eq_type_dec t2 TNat;;;\n        [||TNat||]\n      | Bool _ => [||TBool||]\n      | And e1 e2 =>\n        t1 <-- F e1;\n        t2 <-- F e2;\n        eq_type_dec t1 TBool;;;\n        eq_type_dec t2 TBool;;;\n        [||TBool||]\n    end); simplify; propositional; subst; eauto;\n    match goal with\n    | [ H : hasType ?x _ |- _ ] =>\n      match goal with\n      | [ y : _ |- _ ] =>\n        match y with\n        | x => fail 2\n        end\n      | _ => invert2 H\n      end\n    end; eauto.\nDefined.\n\n(* The short implementation here hides just how time-saving automation is.\n * Every use of one of the notations adds a proof obligation, giving us 12 in\n * total.  Most of these obligations require inversions and either uses of\n * [hasType_det] or applications of [hasType] rules.\n *\n * Our new function remains easy to test: *)\n\nCompute typeCheck' (Nat 0).\nCompute typeCheck' (Plus (Nat 1) (Nat 2)).\nCompute typeCheck' (Plus (Nat 1) (Bool false)).\n\n(* The results of simplifying calls to [typeCheck'] look deceptively similar to\n * the results for [typeCheck], but now the types of the results provide more\n * information. *)\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/SubsetTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7461291759377695}}
{"text": "Require Import ZArith Vec3 Algebra Tactics Equal.\nOpen Scope Z_scope.\n\nInductive Matrix3x3 : Type :=\n| matrix : Vec3 -> Vec3 -> Vec3 -> Matrix3x3.\n\n(* Addition *)\n\nDefinition specification_of_add_matrix_3x3 (add : Matrix3x3 -> \n                                                  Matrix3x3 ->\n                                                  Matrix3x3) :=\n  forall v1 v2 v3 w1 w2 w3 : Vec3,\n    add (matrix v1 v2 v3) (matrix w1 w2 w3) = matrix (add_vec3 v1 w1)\n                                                     (add_vec3 v2 w2)\n                                                     (add_vec3 v3 w3).\n\nTheorem specification_of_add_matrix_3x3_is_unique :\n  forall add add' : Matrix3x3 -> Matrix3x3 -> Matrix3x3,\n    specification_of_add_matrix_3x3 add ->\n    specification_of_add_matrix_3x3 add' ->\n    forall A B : Matrix3x3,\n      add A B = add' A B.\nProof.\n  intros add add'.\n  unfold specification_of_add_matrix_3x3.\n  intros S_add S_add'.\n  intros [v1 v2 v3] [w1 w2 w3].\n  rewrite -> S_add.\n  symmetry.\n  exact (S_add' v1 v2 v3 w1 w2 w3).\nQed.\n\nFunction add_matrix (A B : Matrix3x3) : Matrix3x3 :=\n  match A, B with\n    | matrix v1 v2 v3, matrix w1 w2 w3 =>\n      matrix (add_vec3 v1 w1)\n             (add_vec3 v2 w2)\n             (add_vec3 v3 w3)\n  end.\n\nLemma unfold_add_matrix :\n  forall v1 v2 v3 w1 w2 w3 : Vec3,\n    add_matrix (matrix v1 v2 v3) (matrix w1 w2 w3) = matrix (add_vec3 v1 w1)\n                                                            (add_vec3 v2 w2)\n                                                            (add_vec3 v3 w3).\nProof.\n  unfold_tactic add_matrix.\nQed.\n\nTheorem add_matrix_satisfies_the_specification :\n  specification_of_add_matrix_3x3 add_matrix.\nProof.\n  unfold specification_of_add_matrix_3x3.\n  exact unfold_add_matrix.\nQed.\n\nTheorem Matrix3x3_and_addition_is_associative :\n  Associative Matrix3x3 add_matrix eq.\nProof.\n  unfold Associative.\n  intros [v1 v2 v3] [w1 w2 w3] [x1 x2 x3].\n  rewrite ->4 unfold_add_matrix.\n  rewrite ->3 Vec3_and_addition_is_associative.\n  reflexivity.\nQed.\n\nCorollary Matrix3x3_and_addition_is_a_semi_group :\n  Semi_Group Matrix3x3 add_matrix eq.\nProof.\n  unfold Semi_Group.\n  split.\n  exact (eq_is_a_valid_Equal Matrix3x3).\n  exact Matrix3x3_and_addition_is_associative.\nQed.\n\nDefinition O_matrix : Matrix3x3 := matrix O_vec3 O_vec3 O_vec3.\n\nLemma add_O_matrix_l :\n  forall A : Matrix3x3,\n    add_matrix O_matrix A = A.\nProof.\n  intros [a b c].\n  unfold O_matrix.\n  rewrite -> unfold_add_matrix.\n  rewrite ->3 add_O_vec3_l.\n  reflexivity.\nQed.\n\nLemma add_O_matrix_r :\n  forall A : Matrix3x3,\n    add_matrix A O_matrix = A.\nProof.\n  intros [a b c].\n  unfold O_matrix.\n  rewrite -> unfold_add_matrix.\n  rewrite ->3 add_O_vec3_r.\n  reflexivity.\nQed.\n\nTheorem Matrix3x3_and_addition_have_neutral_element :\n  exists O : Matrix3x3,\n    Neutral Matrix3x3 add_matrix O eq.\nProof.\n  unfold Neutral.\n  exists O_matrix.\n  intro A.\n  split.\n    exact (add_O_matrix_r A).\n    \n    exact (add_O_matrix_l A).\nQed.\n\nCorollary Matrix3x3_and_addition_is_a_monoid :\n  (exists O : Matrix3x3, Neutral Matrix3x3 add_matrix O eq) /\\\n  Semi_Group Matrix3x3 add_matrix eq.\nProof.\n  split.\n    exact Matrix3x3_and_addition_have_neutral_element.\n    exact Matrix3x3_and_addition_is_a_semi_group.\nQed.\n\nTheorem Matrix3x3_and_addition_is_commutative :\n  Commutative Matrix3x3 add_matrix eq.\nProof.\n  unfold Commutative.\n  intros [v1 w1 x1] [v2 w2 x2].\n  rewrite ->2 unfold_add_matrix.\n  symmetry.\n  rewrite -> (Vec3_and_addition_is_commutative v2 v1).\n  rewrite -> (Vec3_and_addition_is_commutative w2 w1).\n  rewrite -> (Vec3_and_addition_is_commutative x2 x1).\n  reflexivity.\nQed.\n\nDefinition opp_matrix (A : Matrix3x3) : Matrix3x3 :=\n  match A with\n    | matrix a b c => matrix (opp_vec3 a) (opp_vec3 b) (opp_vec3 c)\n  end.\n\nTheorem Matrix3x3_and_addition_have_an_inverse :\n  Inverse Matrix3x3 add_matrix eq.\nProof.\n  unfold Inverse.\n  intro A.\n  exists O_matrix.\n  exists (opp_matrix A).\n  unfold opp_matrix.\n  destruct A as [a b c].\n  rewrite -> unfold_add_matrix.\n  rewrite ->3 add_opp_vec3_r.\n  fold O_matrix.\n  reflexivity.\nQed.\n\nCorollary Matrix3x3_and_addition_is_an_abelian_group :\n  Abelian_Group Matrix3x3 add_matrix eq.\nProof.\n  unfold Abelian_Group.\n  split.\n    exact Matrix3x3_and_addition_is_commutative.\n    split.\n      exact Matrix3x3_and_addition_have_an_inverse.\n      exact Matrix3x3_and_addition_is_a_monoid.\nQed.\n\n(* Multiplication *)\n\nDefinition specification_of_3x3_matrix_multiplication (mult : Matrix3x3 ->\n                                                              Matrix3x3 ->\n                                                              Matrix3x3) :=\n  forall a11 a12 a13 a21 a22 a23 a31 a32 a33 b11 b12 b13 b21 b22 b23 b31 b32 b33 : Z,\n    mult (matrix (vec3 a11 a12 a13) \n                 (vec3 a21 a22 a23) \n                 (vec3 a31 a32 a33))\n         (matrix (vec3 b11 b12 b13)\n                 (vec3 b21 b22 b23)\n                 (vec3 b31 b32 b33)) =\n    matrix (vec3 (mult_vec3 (vec3 a11 a12 a13) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a11 a12 a13) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a11 a12 a13) (vec3 b13 b23 b33)))\n             (vec3 (mult_vec3 (vec3 a21 a22 a23) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a21 a22 a23) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a21 a22 a23) (vec3 b13 b23 b33)))\n             (vec3 (mult_vec3 (vec3 a31 a32 a33) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a31 a32 a33) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a31 a32 a33) (vec3 b13 b23 b33))).\n\nTheorem specification_of_3x3_matrix_multiplication_is_unique :\n  forall mult mult' : Matrix3x3 -> Matrix3x3 -> Matrix3x3,\n    specification_of_3x3_matrix_multiplication mult ->\n    specification_of_3x3_matrix_multiplication mult' ->\n    forall A B : Matrix3x3,\n      mult A B = mult' A B.\nProof.    \n  intros mult mult'.\n  unfold specification_of_3x3_matrix_multiplication.\n  intros S_mult S_mult'.\n  intros [[a11 a12 a13] \n          [a21 a22 a23] \n          [a31 a32 a33]]\n\n         [[b11 b12 b13] \n          [b21 b22 b23] \n          [b31 b32 b33]].\n  rewrite -> S_mult.\n  symmetry.\n  exact (S_mult' a11 a12 a13 a21 a22 a23 a31 a32 a33 b11 b12 b13 b21 b22 b23 b31 b32 b33).\nQed.\n\nFunction mult_matrix (A B : Matrix3x3) : Matrix3x3 :=\n  match A, B with\n    | (matrix (vec3 a11 a12 a13) \n              (vec3 a21 a22 a23) \n              (vec3 a31 a32 a33)),\n      (matrix (vec3 b11 b12 b13)\n              (vec3 b21 b22 b23)\n              (vec3 b31 b32 b33)) =>\n      matrix (vec3 (mult_vec3 (vec3 a11 a12 a13) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a11 a12 a13) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a11 a12 a13) (vec3 b13 b23 b33)))\n             (vec3 (mult_vec3 (vec3 a21 a22 a23) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a21 a22 a23) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a21 a22 a23) (vec3 b13 b23 b33)))\n             (vec3 (mult_vec3 (vec3 a31 a32 a33) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a31 a32 a33) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a31 a32 a33) (vec3 b13 b23 b33)))\n  end.\n\nLemma unfold_mult_matrix :\n  forall a11 a12 a13 a21 a22 a23 a31 a32 a33 b11 b12 b13 b21 b22 b23 b31 b32 b33 : Z,\n    mult_matrix (matrix (vec3 a11 a12 a13) \n                        (vec3 a21 a22 a23) \n                        (vec3 a31 a32 a33))\n                (matrix (vec3 b11 b12 b13)\n                        (vec3 b21 b22 b23)\n                        (vec3 b31 b32 b33)) =\n    matrix (vec3 (mult_vec3 (vec3 a11 a12 a13) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a11 a12 a13) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a11 a12 a13) (vec3 b13 b23 b33)))\n             (vec3 (mult_vec3 (vec3 a21 a22 a23) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a21 a22 a23) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a21 a22 a23) (vec3 b13 b23 b33)))\n             (vec3 (mult_vec3 (vec3 a31 a32 a33) (vec3 b11 b21 b31))\n                   (mult_vec3 (vec3 a31 a32 a33) (vec3 b12 b22 b32))\n                   (mult_vec3 (vec3 a31 a32 a33) (vec3 b13 b23 b33))).\nProof.\n  unfold_tactic mult_matrix.\nQed.\n\nTheorem mult_matrix_satifies_the_specification_of_matrix_multiplication :\n  specification_of_3x3_matrix_multiplication mult_matrix.\nProof.\n  unfold specification_of_3x3_matrix_multiplication.\n  exact unfold_mult_matrix.\nQed.\n\nTheorem Matrix3x3_and_multiplication_is_associative :\n  Associative Matrix3x3 mult_matrix eq.\nProof.\n  unfold Associative.\n  intros [[a11 a12 a13] \n          [a21 a22 a23] \n          [a31 a32 a33]]\n\n         [[b11 b12 b13] \n          [b21 b22 b23] \n          [b31 b32 b33]]\n\n         [[c11 c12 c13] \n          [c21 c22 c23] \n          [c31 c32 c33]].\n  rewrite ->4 unfold_mult_matrix.\n  assert (H_row : forall (a11 a12 a13 : Z)\n                         (b11 b12 b13 b21 b22 b23 b31 b32 b33 : Z)\n                         (c11 c21 c31 : Z),                            \n                    (vec3\n                       (mult_vec3 (vec3 a11 a12 a13)\n                                  (vec3 (mult_vec3 (vec3 b11 b12 b13) (vec3 c11 c21 c31))\n                                        (mult_vec3 (vec3 b21 b22 b23) (vec3 c11 c21 c31))\n                                        (mult_vec3 (vec3 b31 b32 b33) (vec3 c11 c21 c31))))\n                       (mult_vec3 (vec3 a11 a12 a13)\n                                  (vec3 (mult_vec3 (vec3 b11 b12 b13) (vec3 c12 c22 c32))\n                                        (mult_vec3 (vec3 b21 b22 b23) (vec3 c12 c22 c32))\n                                        (mult_vec3 (vec3 b31 b32 b33) (vec3 c12 c22 c32))))\n                       (mult_vec3 (vec3 a11 a12 a13)\n                                  (vec3 (mult_vec3 (vec3 b11 b12 b13) (vec3 c13 c23 c33))\n                                        (mult_vec3 (vec3 b21 b22 b23) (vec3 c13 c23 c33))\n                                        (mult_vec3 (vec3 b31 b32 b33) (vec3 c13 c23 c33))))) =\n                    (vec3\n                       (mult_vec3\n                          (vec3 (mult_vec3 (vec3 a11 a12 a13) (vec3 b11 b21 b31))\n                                (mult_vec3 (vec3 a11 a12 a13) (vec3 b12 b22 b32))\n                                (mult_vec3 (vec3 a11 a12 a13) (vec3 b13 b23 b33)))\n                          (vec3 c11 c21 c31))\n                       (mult_vec3\n                          (vec3 (mult_vec3 (vec3 a11 a12 a13) (vec3 b11 b21 b31))\n                                (mult_vec3 (vec3 a11 a12 a13) (vec3 b12 b22 b32))\n                                (mult_vec3 (vec3 a11 a12 a13) (vec3 b13 b23 b33)))\n                          (vec3 c12 c22 c32))\n                       (mult_vec3\n                          (vec3 (mult_vec3 (vec3 a11 a12 a13) (vec3 b11 b21 b31))\n                                (mult_vec3 (vec3 a11 a12 a13) (vec3 b12 b22 b32))\n                                (mult_vec3 (vec3 a11 a12 a13) (vec3 b13 b23 b33)))\n                          (vec3 c13 c23 c33)))).\n    intros a1 a2 a3 b1 b2 b3 b4 b5 b6 b7 b8 b9 c1 c2 c3.\n    unfold mult_vec3.\n    assert (H_entry : forall x1 x2 x3 y1 y2 y3 y4 y5 y6 y7 y8 y9 z1 z2 z3 : Z,\n                                (x1 * (y1 * z1 + y2 * z2 + y3 * z3) + \n                                 x2 * (y4 * z1 + y5 * z2 + y6 * z3) +\n                                 x3 * (y7 * z1 + y8 * z2 + y9 * z3)) =\n                                ((x1 * y1 + x2 * y4 + x3 * y7) * z1 + \n                                 (x1 * y2 + x2 * y5 + x3 * y8) * z2 +\n                                 (x1 * y3 + x2 * y6 + x3 * y9) * z3)).\n      intros; ring.                     \n\n    rewrite ->3 H_entry.\n    reflexivity.\n    rewrite ->3 H_row.\n    reflexivity.\n    Show Proof.\nQed.\n\nCorollary Matrix3x3_and_multiplication_is_a_semi_group :\n  Semi_Group Matrix3x3 mult_matrix eq.\nProof.\n  unfold Semi_Group.\n  split.\n  exact (eq_is_a_valid_Equal Matrix3x3).\n  exact Matrix3x3_and_multiplication_is_associative.\nQed.\n\nDefinition I : Matrix3x3 :=\n  matrix (vec3 1 0 0)\n         (vec3 0 1 0)\n         (vec3 0 0 1).\n\nLemma mult_matrix_I_l :\n  forall A : Matrix3x3,\n    mult_matrix I A = A.\nProof.\n  intros [[a b c]\n          [d e f]\n          [g h i]].\n  unfold I.\n  rewrite -> unfold_mult_matrix.\n  rewrite ->9 unfold_mult_vec3.\n  rewrite ->9 Z.mul_0_l.\n  rewrite ->10 Z.add_0_r.\n  rewrite ->6 Z.add_0_l.\n  rewrite ->9 Z.mul_1_l.\n  reflexivity.\nQed.\n\nLemma mult_matrix_I_r :\n  forall A : Matrix3x3,\n    mult_matrix A I = A.\nProof.\n  intros [[a b c]\n          [d e f]\n          [g h i]].\n  unfold I.\n  rewrite -> unfold_mult_matrix.\n  rewrite ->9 unfold_mult_vec3.\n  rewrite ->9 Z.mul_0_r.\n  rewrite ->10 Z.add_0_r.\n  rewrite ->6 Z.add_0_l.\n  rewrite ->9 Z.mul_1_r.\n  reflexivity.\nQed.\n\n\nTheorem Matrix3x3_and_multiplication_have_a_neutral_element :\n  (exists O : Matrix3x3,\n     Neutral Matrix3x3 mult_matrix O eq).\nProof.\n  unfold Neutral.\n  exists I.\n  intro A.\n  split.\n    exact (mult_matrix_I_r A).\n\n    exact (mult_matrix_I_l A).\nQed.\n\nCorollary Matrix3x3_and_multiplication_is_a_monoid :\n  Monoid Matrix3x3 mult_matrix eq.\nProof.\n  unfold Monoid.\n  split.\n  exact Matrix3x3_and_multiplication_have_a_neutral_element.\n  exact Matrix3x3_and_multiplication_is_a_semi_group.\nQed.\n\nProposition Matrix3x3_and_multiplication_is_NOT_in_the_Abelian_Group :\n  not (Abelian_Group Matrix3x3 mult_matrix eq).\nProof.  \n  unfold Abelian_Group.\n  unfold not.\n  intros [H_comm [H_inv H_Monoid]].\n  unfold Commutative in H_comm.\n  assert (H_comm_absurd := H_comm (matrix (vec3 1 0 1)\n                                          (vec3 0 1 0)\n                                          (vec3 0 0 1))\n                                  (matrix (vec3 1 0 0)\n                                          (vec3 1 1 0)\n                                          (vec3 0 0 1))).\n    rewrite ->2 unfold_mult_matrix in H_comm_absurd.\n    rewrite ->17 unfold_mult_vec3 in H_comm_absurd.\n    compute in H_comm_absurd.\n    discriminate.\nQed.\n\nLemma mult_matrix_distr_add_matrix_l :\n  forall A B C: Matrix3x3,\n    mult_matrix A (add_matrix B C) =\n    add_matrix (mult_matrix A B) (mult_matrix A C).\nProof.\n  intros [[a11 a12 a13] \n          [a21 a22 a23] \n          [a31 a32 a33]]\n\n         [[b11 b12 b13] \n          [b21 b22 b23] \n          [b31 b32 b33]]\n\n         [[c11 c12 c13] \n          [c21 c22 c23] \n          [c31 c32 c33]].\n  rewrite -> unfold_add_matrix.\n  rewrite ->3 unfold_add_vec3.\n  rewrite -> unfold_mult_matrix.\n  rewrite ->9 unfold_mult_vec3.\n  symmetry.\n  rewrite ->2 unfold_mult_matrix.\n  rewrite ->18 unfold_mult_vec3.\n  rewrite -> unfold_add_matrix.\n  rewrite ->3 unfold_add_vec3.\n  assert (H_row : forall a1 a2 a3 b1 b2 b3 c1 c2 c3 : Z,\n                    (a1 * b1 + a2 * b2 + a3 * b3 + (a1 * c1 + a2 * c2 + a3 * c3)) = \n                    (a1 * (b1 + c1) + a2 * (b2 + c2) + a3 * (b3 + c3))).\n   intros; ring.\n rewrite ->9 H_row.\n reflexivity.\nQed.\n\nLemma mult_matrix_distr_add_matrix_r :\n  forall A B C: Matrix3x3,\n    mult_matrix (add_matrix A B) C =\n    add_matrix (mult_matrix A C) (mult_matrix B C).\nProof.\n  intros [[a11 a12 a13] \n          [a21 a22 a23] \n          [a31 a32 a33]]\n\n         [[b11 b12 b13] \n          [b21 b22 b23] \n          [b31 b32 b33]]\n\n         [[c11 c12 c13] \n          [c21 c22 c23] \n          [c31 c32 c33]].\n  rewrite -> unfold_add_matrix.\n  rewrite ->3 unfold_add_vec3.\n  rewrite -> unfold_mult_matrix.\n  rewrite ->9 unfold_mult_vec3.\n  symmetry.\n  rewrite ->2 unfold_mult_matrix.\n  rewrite ->18 unfold_mult_vec3.\n  rewrite -> unfold_add_matrix.\n  rewrite ->3 unfold_add_vec3.\n  assert (H_row : forall a1 a2 a3 b1 b2 b3 c1 c2 c3 : Z,\n                     (a1 * c1 + a2 * c2 + a3 * c3 + (b1 * c1 + b2 * c2 + b3 * c3)) = \n                     ((a1 + b1) * c1 + (a2 + b2) * c2 + (a3 + b3) * c3)).\n   intros; ring.\n rewrite ->9 H_row.\n reflexivity.\nQed.\n\nTheorem Matrix3x3_multiplication_distributes_over_addition :\n  Distributive Matrix3x3 mult_matrix add_matrix eq.\nProof.\n  unfold Distributive.\n  intros A B C.\n  split.\n  exact (mult_matrix_distr_add_matrix_l A B C).\n  exact (mult_matrix_distr_add_matrix_r A B C).\nQed.\n\nCorollary Matrix3x3_forms_a_ring :\n  Ring Matrix3x3 mult_matrix add_matrix eq.\nProof.\n  unfold Ring.\n  split.\n    exact Matrix3x3_multiplication_distributes_over_addition.\n    split.\n    exact Matrix3x3_and_addition_is_an_abelian_group.\n    exact Matrix3x3_and_multiplication_is_a_monoid.\nQed.\n\n(* Please continue with Functions. *)\n", "meta": {"author": "klausfyhn", "repo": "A-Programming-Journey", "sha": "e8a669afd2cd0192c28639b5226fe8a1513d88c0", "save_path": "github-repos/coq/klausfyhn-A-Programming-Journey", "path": "github-repos/coq/klausfyhn-A-Programming-Journey/A-Programming-Journey-e8a669afd2cd0192c28639b5226fe8a1513d88c0/Matrix3x3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7461132086395369}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export ZArith.\n\nFixpoint fib (n:nat) : nat :=\n  match n with\n    0 => 1\n  | 1 => 1\n  | S ((S p) as q) => fib p + fib q\n  end.\n\nTheorem fib_ind :\n  forall P : nat -> Prop,\n    P 0 -> P 1 ->\n    (forall n, P n -> P (S n) -> P (S (S n)))->\n    forall n, P n.\nProof.\n intros P H0 H1 Hstep n.\n assert (P n/\\P(S n)).\n elim n; intuition.\n intuition.\nQed.\n\nTheorem fib_unroll : \n  forall n, fib (S (S n)) = fib n + fib (S n).\nProof.\n auto.\nQed.\n\nTheorem fib_n_p :\n  forall n p, fib (n + p + 2) =\n             fib (n + 1) * fib (p + 1) + fib n * fib p. \nProof.\n  intros n; elim n using fib_ind.\n  intros p; replace (0 + p+2) with (S (S p)).\n  replace (p+1) with (S p).\n  rewrite fib_unroll.\n  simpl (fib 0).\n  simpl (fib (0+1)).\n  ring.\n  ring.\n  ring.\n\n  intros p; replace (1+p+2) with (S (S (S p))).\n  repeat rewrite fib_unroll.\n  simpl (fib (1+1)).\n  simpl (fib 1).\n  replace (p+1) with (S p).\n  ring.\n  ring.\n  ring.\n\n  intros n' IHn' IHn'1 p.\n  replace (S (S n') + p + 2) with (S (S (n'+p + 2))).\n  simpl (S (S n') + 1).\n  repeat rewrite fib_unroll.\n  replace (S (n'+p+2)) with (S n' +p+2).\n  rewrite IHn'1.\n  rewrite IHn'.\n  replace (S n'+1) with (S (S n')).\n  replace (S (n'+1)) with (S (S n')).\n  rewrite fib_unroll.\n  ring.\n  ring.\n  ring.\n  ring.\n  ring.\nQed.\n\nTheorem fib_monotonic :  forall n, fib n <= fib (n+1).\nProof.\n intros n; elim n using fib_ind; auto with arith.\n intros n' H1 H2; replace (S (S n')+1) with (S (S (S n'))).\n rewrite (fib_unroll (S n')).\n auto with arith.\n ring.\nQed.\n\nTheorem fib_n_p' :\n  forall n p, fib (n + p) =\n     fib n * fib p + (fib (n+1) - fib n)*(fib (p+1) - fib p).\nProof.\n intros n; elim n using fib_ind.\n intros p; simpl; ring.\n\n intros p; replace (1 + p) with (p + 1); simpl.  ring_simplify.\n (*\n ring_simplify. *)\n (*rewrite <- (plus_comm (fib p)).*)\n rewrite le_plus_minus_r.\n auto.\n apply fib_monotonic.\n rewrite plus_comm.\n auto.\n intros n' IHn' IHn'1 p.\n simpl (S (S n') + p).\n rewrite fib_unroll.\n replace (S (n' + p)) with (S n' + p).\n rewrite IHn'.\n rewrite IHn'1.\n simpl (S (S n')+1).\n replace (S n' + 1) with (S (S n')).\n replace (S (n' + 1)) with (S (S n')).\n repeat rewrite fib_unroll.\n rewrite (plus_comm (fib (S n'))\n             (fib n' + fib (S n'))).\n rewrite minus_plus.\n rewrite (plus_comm (fib n')(fib (S n'))).\n rewrite minus_plus.\n rewrite mult_minus_distr_r.\n replace\n   (fib n' * fib p +\n   (fib (n' + 1) * (fib (p + 1) - fib p) - fib n' * (fib (p + 1) - fib p)) +\n   (fib (S n') * fib p + fib n' * (fib (p + 1) - fib p)))\n  with\n   (fib n' * fib p +\n   (fib n' * (fib (p + 1) - fib p) +\n   (fib (n' + 1) * (fib (p + 1) - fib p) - \n         fib n' * (fib (p + 1) - fib p))) +   fib (S n') * fib p).\n rewrite (le_plus_minus_r).\n replace (n' + 1) with (S n').\n ring.\n ring.\n apply mult_le_compat_r.\n apply fib_monotonic.\n ring.\n ring.\n ring.\n ring.\nQed.\n\nTheorem fib_2n :\n  forall n, fib (2*n) = fib (n) * fib (n) + \n           (fib (n+1) - fib n)*(fib (n+1) - fib n).\nProof.\n intros n; replace (2*n) with (n+n).\n apply fib_n_p'.\n ring.\nQed.\n\nTheorem fib_2n_plus_1 :\n  forall n, fib (2*n+1) = 2 * fib n * fib (n+1) - fib n * fib n.\nProof.\n intros n; replace (2*n+1) with (n + (n + 1)).\n rewrite fib_n_p'.\n replace (n + 1 + 1) with (S (S n)).\n rewrite fib_unroll.\n replace (S n) with (n + 1).\n rewrite (plus_comm (fib n) (fib (n + 1))).\n rewrite minus_plus.\n apply plus_reg_l with (fib n * fib n).\n rewrite le_plus_minus_r.\n rewrite plus_permute.\n rewrite mult_minus_distr_r.\n rewrite le_plus_minus_r.\n ring.\n apply mult_le_compat_r.\n apply fib_monotonic.\n replace (fib n * fib n) with (1 * (fib n * fib n)).\n rewrite mult_assoc_reverse.\n apply mult_le_compat.\n auto with arith.\n apply mult_le_compat_l.\n apply fib_monotonic.\n ring.\n ring.\n ring.\n ring.\nQed.\n\nTheorem fib_2n_plus_2 :\n  forall n, fib (S (2*n+1)) = fib (n+1) * (fib (n+1)) + fib n * fib n.\nProof.\n intros n; replace (S (2*n+1)) with ((n+1)+(n+1)).\n rewrite fib_n_p'.\n replace (n + 1 + 1) with (S (S n)).\n rewrite fib_unroll.\n replace (S n) with (n + 1).\n rewrite (plus_comm (fib n) (fib (n + 1))).\n rewrite minus_plus.\n auto.\n ring.\n ring.\n ring.\nQed.\n\nTheorem th_fib_positive1 :\n  forall p : positive,\n  forall u v : nat,\n    u = fib (nat_of_P p) /\\ v = fib (S (nat_of_P p)) ->\n      2*u*v - u*u = fib(nat_of_P (xI p)) /\\\n      v*v + u*u = fib(S (nat_of_P (xI p))).\nProof.\n intros p u v [Hu Hv]; rewrite Hu; rewrite Hv.\n rewrite nat_of_P_xI.\n replace (S (2* nat_of_P p)) with (2*nat_of_P p + 1).\n rewrite fib_2n_plus_1.\n rewrite fib_2n_plus_2.\n replace (S (nat_of_P p)) with (nat_of_P p + 1).\n auto.\n ring.\n ring.\nQed.\n          \nTheorem th_fib_positive0 :\n  forall p : positive,\n  forall u v : nat,\n    u = fib (nat_of_P p) /\\ v = fib (S (nat_of_P p)) ->\n    u*u + (v-u)*(v-u) = fib (nat_of_P (xO p)) /\\\n    2*u*v - u*u = fib (S (nat_of_P (xO p))).\nProof.\n intros p u v [Hu Hv]; subst.\n rewrite nat_of_P_xO.\n rewrite fib_2n.\n replace (S (nat_of_P p)) with (nat_of_P p + 1).\n replace (S (2*nat_of_P p)) with (2*nat_of_P p+1).\n rewrite fib_2n_plus_1.\n auto.\n ring.\n ring.\nQed.\n\nFixpoint fib_positive (p:positive) :\n  {u:nat & { v : nat | u = fib (nat_of_P p) /\\  v = fib (S (nat_of_P p))}} :=\nmatch p return \n   {u:nat & { v : nat | u = fib (nat_of_P p) /\\  v = fib (S (nat_of_P p))}}\n     with\n  xH => (existS (fun u=> { v : nat | u = 1 /\\  v = 2})\n              1 (exist (fun v => 1 = 1 /\\  v = 2)\n                    2 (conj (refl_equal 1) (refl_equal 2))))\n| xI p' =>\n   match fib_positive p' with\n     (existS u (exist v h)) =>\n       (existS (fun u =>\n                  { v: nat | u = fib (nat_of_P (xI p')) /\\\n                             v = fib (S (nat_of_P (xI p')))})\n           (2*u*v - u*u)\n          (exist (fun w=> 2*u*v-u*u = fib (nat_of_P (xI p')) /\\\n                            w= fib (S (nat_of_P (xI p'))))\n             (v*v + u*u) (th_fib_positive1 p' u v h)))\n   end\n| xO p' =>\n   match fib_positive p' with\n     (existS u (exist v h)) =>\n       (existS (fun u =>\n                  { v: nat | u = fib (nat_of_P (xO p')) /\\\n                             v = fib (S (nat_of_P (xO p')))})\n            (u*u+(v-u)*(v-u))\n          (exist (fun w => u*u+(v-u)*(v-u) = fib (nat_of_P (xO p'))/\\\n                           w = fib (S (nat_of_P (xO p'))))\n                (2*u*v-u*u) (th_fib_positive0 p' u v h)))\n   end\nend.\n\nDefinition fib' :\n  forall n:nat, {u : nat &{v : nat | u = fib n /\\ v = fib (S n)}}.\nProof.\n  intros n; case n.\n  exists 1; exists 1; auto.\n  intros n'; elim (fib_positive (P_of_succ_nat n'));\n  intros u [v [Hu Hv]].\n  exists u; exists v.\n  rewrite Hu; rewrite Hv; rewrite nat_of_P_o_P_of_succ_nat_eq_succ.\n  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_positive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7461131965804866}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nPrint unit.\n\nPrint True.\n\n(* Propositional Logic *)\n\nSection Propositional.\n  Variables P Q R : Prop.\n\n  Theorem obvious : True.\n    apply I.\n  Qed.\n\n  Theorem obvious' : True.\n    constructor.\n  Qed.\n\n  Theorem False_imp : False -> 2 + 2 = 5.\n    destruct 1.\n  Qed.\n\n  Theorem arith_neq : 2 + 2 = 5 -> 9 + 9 = 835.\n    intro.\n    elimtype False.\n    crush.\n  Qed.\n\n  Print not.\n\n  Theorem arith_neq' : ~ (2 + 2 = 5).\n    unfold not.\n    crush.\n  Qed.\n\n  Print and.\n\n  Theorem and_comm : P /\\ Q -> Q /\\ P.\n    destruct 1.\n    split.\n    assumption.\n    assumption.\n  Qed.\n\n  Print or.\n\n  Theorem or_comm : P \\/ Q -> Q \\/ P.\n    destruct 1.\n    right; assumption.\n    left; assumption.\n  Qed.\n\n  Theorem or_comm' : P \\/ Q -> Q \\/ P.\n    tauto.\n  Qed.\n\n  Theorem arith_comm : forall ls1 ls2 : list nat,\n      length ls1 = length ls2 \\/ length ls1 + length ls2 = 6\n      -> length (ls1 ++ ls2) = 6 \\/ length ls1 = length ls2.\n    intuition.\n    rewrite app_length.\n    tauto.\n  Qed.\n\n  Theorem arith_comm' : forall ls1 ls2 : list nat,\n      length ls1 = length ls2 \\/ length ls1 + length ls2 = 6\n      -> length (ls1 ++ ls2) = 6 \\/ length ls1 = length ls2.\n    Hint Rewrite app_length.\n    crush.\n  Qed.\nEnd Propositional.\n\n(* First Order Logic *)\n\nPrint ex.\n\nTheorem exist1 : exists x : nat, x + 1 = 2.\n  exists 1.\n  reflexivity.\nQed.\n\nTheorem exist2 : forall n m : nat, (exists x : nat, n + x = m) -> n <= m.\n  destruct 1.\n  crush.\nQed.\n\n(* Predicates with Implicit Equality *)\n\nInductive isZero : nat -> Prop :=\n| IsZero : isZero 0.\n\nTheorem isZero_zero : isZero 0.\n  constructor.\nQed.\n\nPrint eq.\n\nTheorem isZero_plus : forall n m : nat, isZero m -> n + m = n.\n  destruct 1.\n  crush.\nQed.\n\nTheorem isZero_contra : isZero 1 -> False.\n  inversion 1.\nQed.\n\nTheorem isZero_contra' : isZero 1 -> 2 + 2 = 5.\n  destruct 1.\nAbort.\n\nCheck isZero_ind.\n\n(* Recursive Predicates *)\n\nInductive even : nat -> Prop :=\n| EvenO : even 0\n| EvenSS : forall n, even n -> even (S (S n)).\n\nTheorem even_0 : even 0.\n  constructor.\nQed.\n\nTheorem even_4 : even 4.\n  constructor; constructor; constructor.\nQed.\n\nHint Constructors even.\n\nTheorem even_4' : even 4.\n  auto.\nQed.\n\nTheorem even_1_contra : even 1 -> False.\n  inversion 1.\nQed.\n\nTheorem even_3_contra : even 3 -> False.\n  inversion 1.\n  inversion H1.\nQed.\n\nTheorem even_plus : forall n m, even n -> even m -> even (n + m).\n  induction 1; crush.\nQed.\n\nLemma even_contra' : forall n', even n' -> forall n, n' = S (n + n) -> False.\n  Hint Rewrite <- plus_n_Sm.\n  induction 1; crush.\n  match goal with\n  | [H : S ?N = ?N0 + ?N0 |- _] => destruct N; destruct N0\n  end; crush.\nQed.\n\nTheorem even_contra : forall n, even (S (n + n)) -> False.\n  intros; eapply even_contra'; eauto.\nQed.\n\nLemma even_contra'' : forall n' n, even n' -> n' = S (n + n) -> False.\n  Hint Rewrite <- plus_n_Sm.\n  induction 1; crush.\n  match goal with\n  | [H : S ?N = ?N0 + ?N0 |- _] => destruct N; destruct N0\n  end; crush.\nAbort.\n", "meta": {"author": "manzyuk", "repo": "cpdt-exercises", "sha": "0966d7e2cb93f160834afa9bf5cb6dc6624cd145", "save_path": "github-repos/coq/manzyuk-cpdt-exercises", "path": "github-repos/coq/manzyuk-cpdt-exercises/cpdt-exercises-0966d7e2cb93f160834afa9bf5cb6dc6624cd145/Predicates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7461131961829921}}
{"text": "Require Export P03.\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\n\n\n(** **** Problem : 3 stars (mult_comm) *)\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 n.\n  - reflexivity.\n  - simpl. rewrite -> IHn. rewrite -> plus_assoc. reflexivity.\nQed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/02/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7461131924283049}}
{"text": "(* PREAMBLE *)\n\n(** * Algebraic laws and helpers *)\n\n(** ** Inverse in [Prop] *)\nSection Inverse.\n  (** [T__inv] is a transformation that is right inverse of [T] on a given domain Dom *)\n\n  Context {A} (T T__inv: A -> A).\n\n  Definition left_inverse_on (Dom: A -> Prop)  : Prop :=\n    forall a, Dom a -> T__inv (T a) = a.\n\n  (** If [T__inv] is the left inverse (i.e. [T__inv o T === id]). *)\n  Definition left_inverse : Prop :=\n    left_inverse_on (fun _ => True) .\n\n  Definition right_inverse_on (Dom: A -> Prop) : Prop :=\n    forall a, Dom a -> T (T__inv a) = a.\n\n  (** If [T__inv] is the right inverse (i.e. [T o T__inv === id]). *)\n\n  Definition right_inverse : Prop :=\n    right_inverse_on (fun _ => True).\n\n  Definition option_inverse  {U V:Type} (F: U -> option V) (G: V -> option U )\n    := forall u v, F u = Some v <-> G v = Some u.\n\n  Theorem option_inverse_symm:\n    forall {U} (f1 f2: U -> option U),\n      option_inverse f1 f2 -> option_inverse f2 f1.\n  Proof. unfold option_inverse. intros U f g H u v. split; intros; eapply H; auto. Qed.\n\nEnd Inverse.\n\nSection InverseProperties.\n\n  Lemma left_inverse_id: forall A, @left_inverse A (@id _) (@id _).\n  Proof.\n    intros ? ? _; reflexivity.\n  Qed.\n\n  Lemma right_inverse_id: forall A, @right_inverse A (@id _) (@id _).\n  Proof.\n    intros ? ? _; reflexivity.\n  Qed.\n\nEnd InverseProperties.\n\n\n(** ** Functions *)\nNotation \"g ∘ f\" := (fun x => g (f x)) (at level 51, right associativity).\n\nSection Functions.\n  (** Single valued means that for each first argument of [R] only one or zero\nvalues of the second argument make the relation [R] hold. *)\n\n\n  Definition single_valued {A B} (p:A -> B -> Prop) :=\n    forall x1 x2 x3,\n      p x1 x2 -> p x1 x3 -> x2 = x3.\n\n  (** Different arguments are mapped to different values. *)\n  Definition injectivity {A B} (p:A -> B -> Prop) :=\n    forall x1 x2 x3,\n      p x1 x3 -> p x2 x3 -> x1 = x2.\n\n  (** Different arguments are mapped to different values. *)\n  Definition option_injectivity {A B} (f:A -> option B) :=\n    forall x y x' y',\n      x <> y ->\n      f x = Some x' ->\n      f y = Some y' ->\n      x' <> y'.\n\n  (** Extensional equality *)\n  Definition ext_eq {T U} (f g: T -> U) := forall x, f x = g x.\n\n  Lemma ext_eq_symm {T U} (f g: T -> U) : ext_eq f g -> ext_eq g f.\n  Proof. intros H x. rewrite H. reflexivity. Qed.\n\n\n  Theorem eq_implies_ext_eq:\n    forall {T U} (f g: T -> U),\n      f = g -> ext_eq f g .\n  Proof. intros T U f g H. subst. intros ?. reflexivity. Qed.\n\n  Lemma option_inverse_extensional:\n    forall {A B} (f f': A -> option B) g,\n      option_inverse f g ->\n      ext_eq f f' ->\n      option_inverse f' g.\n  Proof. intros A B f f' g H H0 u v. rewrite <-H0. auto. Qed.\n\n  (** Flip arguments of a function with two arguments. *)\n  Definition flip {A B C} (p: A -> B -> C ) : B -> A -> C :=\n    fun a b => p b a.\n\n  (** Apply to the second component *)\n  Definition skip1 {A B C} (f: B->C) : (A*B) -> C := f ∘ snd.\n\n  Definition involution {A} (f: A->A) := forall x, f ( f x ) = x.\n\n  Definition True1 {A} := fun _:A => True.\n  Definition True2 {A B} := fun _:A =>  @True1 B.\n  Definition True3 {A B C} := fun _:A =>  @True2 B C.\n  Definition True4 {A B C D} := fun _:A =>  @True3 B C D.\nEnd Functions.\n\nHint Resolve option_inverse_extensional ext_eq_symm eq_implies_ext_eq : ext.\n\nNotation \"f ≃ g\" := (ext_eq f g) (at level 51, no associativity).\n\nSection Relations.\n\n  (** Flip arguments of a binary relation. *)\n  Definition converse {A B} (p: A -> B -> Prop) : B -> A -> Prop :=\n    fun a b => p b a.\n\n  Definition stability {T} (R: T -> Prop) (U: T -> T -> Prop) := forall x1 x2, R x1 -> U x1 x2 -> R x2.\n\n  Definition transitivity {A:Type} (R: A->A->Prop)  := forall a b c, R a b -> R b c -> R a c.\n\nEnd Relations.\n\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/lib/Algebraic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7460364332721565}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint drop (drop_arg0 : Nat) (drop_arg1 : Lst) : Lst\n           := match drop_arg0, drop_arg1 with\n              | x, nil => nil\n              | zero, x => x\n              | succ x, cons y z => drop x z\n              end.\n\nTheorem drop_nil: forall (x: Nat), drop x nil = nil.\nProof.\n  induction x ; simpl; reflexivity.\nQed.\n\nTheorem drop_cons: forall (x n: Nat) (l: Lst), drop (succ x) (cons n l) = drop x l.\n  induction l; induction x; simpl; reflexivity.\nQed.\n\nTheorem drop_cons_assoc: forall (x1 x2 x3: Nat) (l: Lst),\n    drop x1 (drop x2 (cons x3 l)) = drop x2 (drop x1 (cons x3 l)).\nProof.\n  induction x1; induction x2; try (simpl; reflexivity).\n  { induction l.\n    { rewrite 2 drop_cons. rewrite <- IHx1.\n      rewrite IHx2. rewrite 2 drop_cons.\n      induction l.\n      { rewrite IHx1. reflexivity. }\n      { rewrite 3 drop_nil. reflexivity. }\n    }\n    { simpl. rewrite 2 drop_nil. reflexivity. }\n  }\n  { intros. simpl. destruct (drop x1 l); reflexivity. }\n  { intros. simpl. destruct (drop x2 l); reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : Nat) (y : Nat) (z : Lst), eq (drop x (drop y z)) (drop y (drop x z)).\nProof.\n  induction z.\n  { rewrite 2 drop_cons_assoc. reflexivity. }\n  { rewrite 3 drop_nil. reflexivity. }\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7460266945560039}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) : natural :=\n  plus Zero (mult x lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj2410_coqofml_yZ2RO8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7460266925555821}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) : natural :=\n  plus Zero (mult lf1 x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj2410_coqofml_Kc5fhj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7460266845433138}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) : natural :=\n  plus lf3 (plus Zero lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj203_coqofml_56IG6R.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7459845079318033}}
{"text": "Require Import Arith.\n\nDefinition Var := nat.\n\nDefinition Env := Var -> nat.\n\nDefinition empty : Env := fun v => 0.\n\nDefinition update (env:Env) (v:Var) (n:nat) : Env :=\n    fun (x:Var) => if beq_nat x v then n else env x.\n\nInductive Exp : Set :=\n| EConst : nat -> Exp\n| EVar   : Var -> Exp\n| EPlus  : Exp -> Exp -> Exp\n.\n\n(* interpreter fixes the semantics *)\nFixpoint evalExp (env:Env) (e:Exp) : nat :=\n    match e with\n    | EConst n      => n\n    | EVar v        => env v\n    | EPlus e1 e2   => evalExp env e1 + evalExp env e2\n    end.\n\nExample test_evalExp1 : evalExp empty (EConst 5) = 5.\nProof. reflexivity. Qed.\n\nExample test_evalExp2 : evalExp (update empty 3 12) (EVar 3) = 12.\nProof. reflexivity. Qed.\n\nExample test_evalExp3 : evalExp (update empty 3 12)(EPlus(EConst 5)(EVar 3)) = 17.\nProof. reflexivity. Qed.\n\n\nInductive Cmd : Set :=\n| CAssign : Var -> Exp -> Cmd\n| CSeq    : Cmd -> Cmd -> Cmd\n| CWhile  : Exp -> Cmd -> Cmd\n.\n\n\nCoInductive evalCmd : Env -> Cmd -> Env -> Prop :=\n| EvalAssign : forall (env:Env) (v:Var) (e:Exp), \n    evalCmd env (CAssign v e) (update env v (evalExp env e))\n| EvalSeq : forall (e1 e2 e3:Env) (c1 c2:Cmd),\n    evalCmd e1 c1 e2 -> evalCmd e2 c2 e3 -> evalCmd e1 (CSeq c1 c2) e3\n| EvalWhileFalse : forall (env:Env) (e:Exp) (c:Cmd),\n    evalExp env e = 0 -> evalCmd env (CWhile e c) env\n| EvalWhileTrue : forall (e1 e2 e3:Env) (e:Exp) (c:Cmd),\n    evalExp e1 e <> 0 -> evalCmd e1 c e2 -> evalCmd e2 (CWhile e c) e3 -> \n        evalCmd e1 (CWhile e c) e3\n.\n\n(* Need to build a coinduction principle for evalCmd        *)\nTheorem evalCmd_coind : forall (R:Env -> Cmd -> Env -> Prop),\n    (forall (e1 e2:Env) (e:Exp) (v:Var), \n        R e1 (CAssign v e) e2 -> e2 = update e1 v (evalExp e1 e))    ->\n    (forall (e1 e3:Env) (c1 c2:Cmd),\n        R e1 (CSeq c1 c2) e3 -> exists e2, R e1 c1 e2 /\\ R e2 c2 e3) -> \n    (forall (e1 e3:Env) (e:Exp) (c:Cmd),\n        R e1 (CWhile e c) e3 -> (evalExp e1 e = 0 /\\ e3 = e1) \\/ \n        (exists (e2:Env), \n            evalExp e1 e <> 0 /\\ R e1 c e2 /\\ R e2 (CWhile e c) e3)) ->\n    (forall (e1 e2:Env) (c:Cmd), R e1 c e2 -> evalCmd e1 c e2).\nProof.\n    intros R H1 H2 H3. cofix coIH. intros e1 e2 c H. destruct c.\n    - apply H1 in H. rewrite H. constructor.\n    - rename e2 into e3. apply H2 in H. destruct H as [e2 [H12 H23]].\n      apply EvalSeq with e2; apply coIH; assumption.\n    - rename e2 into e3. apply H3 in H. destruct H as [H|H].\n        + destruct H as [E1 E2]. subst. apply EvalWhileFalse. assumption.\n        + destruct H as [e2 [E1 [E2 E3]]]. apply EvalWhileTrue with e2.\n            { assumption. }\n            { apply coIH. assumption. }\n            { apply coIH. assumption. }\nQed.\n\nFixpoint optExp (e:Exp) : Exp :=\n    match e with\n    | EPlus (EConst 0) e    => optExp e\n    | EPlus e1 e2           => EPlus (optExp e1) (optExp e2)\n    | _                     => e\n    end.\n\nFixpoint optCmd (c:Cmd) : Cmd :=\n    match c with\n    | CAssign v e   => CAssign v (optExp e)\n    | CSeq c1 c2    => CSeq (optCmd c1) (optCmd c2)\n    | CWhile e c    => CWhile (optExp e) (optCmd c)\n    end. \n\nLemma optExp_correct : forall (env:Env) (e:Exp), \n    evalExp env (optExp e) = evalExp env e. \nProof.\n    intros env. induction e as [n|v|e1 IH1 e2 IH2].\n    - reflexivity.\n    - reflexivity.\n    - destruct e1 as [n1|v1|e1' e2']. \n        + destruct n1 as [|n1].\n            { simpl. assumption. }\n            { simpl. rewrite IH2. reflexivity. }\n        + simpl. rewrite IH2. reflexivity.\n        + simpl in IH1. simpl. rewrite IH1, IH2. reflexivity. \nQed.\n\n\nLemma optCmd_correct1 : forall (e1 e2:Env) (c:Cmd),\n    evalCmd e1 c e2 -> evalCmd e1 (optCmd c) e2.\nProof.\n    intros e1 e2 c H.\n    apply (evalCmd_coind (fun e1 c' e2 => \n        exists c, c' = optCmd c /\\ evalCmd e1 c e2)). \n    - clear e1 e2 c H. intros e1 e2 e v [c [H1 H2]]. revert e v H1.\n      destruct H2.\n        + intros e' v' H. simpl in H. inversion H. subst.\n          rewrite optExp_correct. reflexivity.\n        + intros e v H. simpl in H. inversion H.\n        + intros e' v H'. simpl in H'. inversion H'.\n        + intros e' v H'. simpl in H'. inversion H'.\n    - clear e1 e2 c H. intros e1 e3 c1 c2 [c [H1 H2]].\n      revert c1 c2 H1. destruct H2.\n        + intros c1 c2 H. simpl in H. inversion H.\n        + intros c3 c4 H. simpl in H. inversion H. subst.\n          exists e2. split.\n            { exists c1. split. { reflexivity. } { assumption. } }\n            { exists c2. split. { reflexivity. } { assumption. } }\n        + intros c1 c2 H'. simpl in H'. inversion H'.\n        + intros c1 c2 H'. simpl in H'. inversion H'.\n    - clear e1 e2 c H. intros e1 e3 e c [c' [H1 H2]].\n      revert e c H1. destruct H2.     \n        + intros e' c H. simpl in H. inversion H.\n        + intros e c H. simpl in H. inversion H.\n        + intros e' c' H'. simpl in H'. inversion H'. subst.\n          left. split. \n            { rewrite optExp_correct. assumption. }\n            { reflexivity. }\n        + intros e' c' H'. simpl in H'. inversion H'. subst. right.\n          exists e2. split.\n            { rewrite optExp_correct. assumption. }\n            { split.\n                { exists c. split. { reflexivity. } { assumption. }}\n                { exists (CWhile e c). split. { reflexivity. } { assumption. }}}\n    - exists c. split. \n        + reflexivity.\n        + assumption.\nQed.\n\nLemma optCmd_correct2 : forall (e1 e2:Env) (c:Cmd),\n    evalCmd e1 (optCmd c) e2 -> evalCmd e1 c e2.\nProof.\n    apply (evalCmd_coind (fun e1 c e2 => evalCmd e1 (optCmd c) e2)).\n    -  intros e1 e2 e v H. simpl in H.\n       remember (CAssign v (optExp e)) as c' eqn:E. \n       revert e v E. destruct H.\n        + intros e' v' H. inversion H. subst. clear H.\n          rewrite optExp_correct. reflexivity.\n        + intros e v H'. inversion H'.\n        + intros e' v H'. inversion H'.\n        + intros e' v H'. inversion H'.\n    - intros e1 e3 c1 c2 H. simpl in H.\n      remember (CSeq (optCmd c1) (optCmd c2)) as c' eqn:E.\n      revert c1 c2 E. destruct H.\n        + intros c1 c2 H. inversion H.\n        + intros c1' c2' H'. inversion H'. subst. clear H'. exists e2. split; assumption.\n        + intros c1 c2 H'. inversion H'.\n        + intros c1 c2 H'. inversion H'.\n    - intros e1 e3 e c H. simpl in H.\n      remember (CWhile (optExp e) (optCmd c)) as c' eqn:E.\n      revert e c E. destruct H.\n        + intros e' c H. inversion H.\n        + intros e c H'. inversion H'.\n        + intros e' c' H'. inversion H'. subst. clear H'. left. split.\n            { rewrite optExp_correct in H. assumption. }\n            { reflexivity. }\n        + intros e' c' H'. inversion H'. subst. clear H'. right. exists e2. split.\n            { rewrite optExp_correct in H. assumption. }\n            { split; assumption. }\nQed.\n\nTheorem optCmd_correct : forall (e1 e2:Env) (c:Cmd), \n    evalCmd e1 (optCmd c) e2 <-> evalCmd e1 c e2.\nProof. \n    intros e1 e2 c. split.\n    - apply optCmd_correct2.\n    - apply optCmd_correct1.\nQed.\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/cpdt/coind_sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7459822503455227}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nFrom mathcomp\nRequire Import bigop ssralg binomial.\n\n(******************************************************************************)\n(* This file provides a library for univariate polynomials over ring          *)\n(* structures; it also provides an extended theory for polynomials whose      *)\n(* coefficients range over commutative rings and integral domains.            *)\n(*                                                                            *)\n(*           {poly R} == the type of polynomials with coefficients of type R, *)\n(*                       represented as lists with a non zero last element    *)\n(*                       (big endian representation); the coeficient type R   *)\n(*                       must have a canonical ringType structure cR. In fact *)\n(*                       {poly R} denotes the concrete type polynomial cR; R  *)\n(*                       is just a phantom argument that lets type inference  *)\n(*                       reconstruct the (hidden) ringType structure cR.      *)\n(*          p : seq R == the big-endian sequence of coefficients of p, via    *)\n(*                       the coercion polyseq : polynomial >-> seq.           *)\n(*             Poly s == the polynomial with coefficient sequence s (ignoring *)\n(*                       trailing zeroes).                                    *)\n(* \\poly_(i < n) E(i) == the polynomial of degree at most n - 1 whose         *)\n(*                       coefficients are given by the general term E(i)      *)\n(*  0, 1, - p, p + q, == the usual ring operations: {poly R} has a canonical  *)\n(* p * q, p ^+ n, ...    ringType structure, which is commutative / integral  *)\n(*                       when R is commutative / integral, respectively.      *)\n(*      polyC c, c%:P == the constant polynomial c                            *)\n(*                 'X == the (unique) variable                                *)\n(*               'X^n == a power of 'X; 'X^0 is 1, 'X^1 is convertible to 'X  *)\n(*               p`_i == the coefficient of 'X^i in p; this is in fact just   *)\n(*                       the ring_scope notation generic seq-indexing using   *)\n(*                       nth 0%R, combined with the polyseq coercion.         *)\n(*            coefp i == the linear function p |-> p`_i (self-exapanding).    *)\n(*             size p == 1 + the degree of p, or 0 if p = 0 (this is the      *)\n(*                       generic seq function combined with polyseq).         *)\n(*        lead_coef p == the coefficient of the highest monomial in p, or 0   *)\n(*                       if p = 0 (hence lead_coef p = 0 iff p = 0)           *)\n(*        p \\is monic <=> lead_coef p == 1 (0 is not monic).                  *)\n(* p \\is a polyOver S <=> the coefficients of p satisfy S; S should have a    *)\n(*                        key that should be (at least) an addrPred.          *)\n(*             p.[x]  == the evaluation of a polynomial p at a point x using  *)\n(*                       the Horner scheme                                    *)\n(*                   *** The multi-rule hornerE (resp., hornerE_comm) unwinds *)\n(*                       horner evaluation of a polynomial expression (resp., *)\n(*                       in a non commutative ring, with side conditions).    *)\n(*             p^`()  == formal derivative of p                               *)\n(*             p^`(n) == formal n-derivative of p                             *)\n(*            p^`N(n) == formal n-derivative of p divided by n!               *)\n(*            p \\Po q == polynomial composition; because this is naturally a  *)\n(*                       a linear morphism in the first argument, this        *)\n(*                       notation is transposed (q comes before p for redex   *)\n(*                       selection, etc).                                     *)\n(*                      := \\sum(i < size p) p`_i *: q ^+ i                    *)\n(*      comm_poly p x == x and p.[x] commute; this is a sufficient condition  *)\n(*                       for evaluating (q * p).[x] as q.[x] * p.[x] when R   *)\n(*                       is not commutative.                                  *)\n(*      comm_coef p x == x commutes with all the coefficients of p (clearly,  *)\n(*                       this implies comm_poly p x).                         *)\n(*           root p x == x is a root of p, i.e., p.[x] = 0                    *)\n(*    n.-unity_root x == x is an nth root of unity, i.e., a root of 'X^n - 1  *)\n(* n.-primitive_root x == x is a primitive nth root of unity, i.e., n is the  *)\n(*                       least positive integer m > 0 such that x ^+ m = 1.   *)\n(*                   *** The submodule poly.UnityRootTheory can be used to    *)\n(*                       import selectively the part of the theory of roots   *)\n(*                       of unity that doesn't mention polynomials explicitly *)\n(*       map_poly f p == the image of the polynomial by the function f (which *)\n(*     (locally, p^f)    is usually a ring morphism).                         *)\n(*               p^:P == p lifted to {poly {poly R}} (:= map_poly polyC p).   *)\n(*   commr_rmorph f u == u commutes with the image of f (i.e., with all f x). *)\n(*   horner_morph cfu == given cfu : commr_rmorph f u, the function mapping p *)\n(*                       to the value of map_poly f p at u; this is a ring    *)\n(*                       morphism from {poly R} to the codomain of f when f   *)\n(*                       is a ring morphism.                                  *)\n(*      horner_eval u == the function mapping p to p.[u]; this function can   *)\n(*                       only be used for u in a commutative ring, so it is   *)\n(*                       always a linear ring morphism from {poly R} to R.    *)\n(*     diff_roots x y == x and y are distinct roots; if R is a field, this    *)\n(*                       just means x != y, but this concept is generalized   *)\n(*                       to the case where R is only a ring with units (i.e., *)\n(*                       a unitRingType); in which case it means that x and y *)\n(*                       commute, and that the difference x - y is a unit     *)\n(*                       (i.e., has a multiplicative inverse) in R.           *)\n(*                       to just x != y).                                     *)\n(*       uniq_roots s == s is a sequence or pairwise distinct roots, in the   *)\n(*                       sense of diff_roots p above.                         *)\n(*   *** We only show that these operations and properties are transferred by *)\n(*       morphisms whose domain is a field (thus ensuring injectivity).       *)\n(* We prove the factor_theorem, and the max_poly_roots inequality relating    *)\n(* the number of distinct roots of a polynomial and its size.                 *)\n(*   The some polynomial lemmas use following suffix interpretation :         *)\n(*   C - constant polynomial (as in polyseqC : a%:P = nseq (a != 0) a).       *)\n(*   X - the polynomial variable 'X (as in coefX : 'X`_i = (i == 1%N)).       *)\n(*   Xn - power of 'X (as in monicXn : monic 'X^n).                           *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nReserved Notation \"{ 'poly' T }\" (at level 0, format \"{ 'poly'  T }\").\nReserved Notation \"c %:P\" (at level 2, format \"c %:P\").\nReserved Notation \"p ^:P\" (at level 2, format \"p ^:P\").\nReserved Notation \"'X\" (at level 0).\nReserved Notation \"''X^' n\" (at level 3, n at level 2, format \"''X^' n\").\nReserved Notation \"\\poly_ ( i < n ) E\"\n  (at level 36, E at level 36, i, n at level 50,\n   format \"\\poly_ ( i  <  n )  E\").\nReserved Notation \"p \\Po q\" (at level 50).\nReserved Notation \"p ^`N ( n )\" (at level 8, format \"p ^`N ( n )\").\nReserved Notation \"n .-unity_root\" (at level 2, format \"n .-unity_root\").\nReserved Notation \"n .-primitive_root\"\n  (at level 2, format \"n .-primitive_root\").\n\nLocal Notation simp := Monoid.simpm.\n\nSection Polynomial.\n\nVariable R : ringType.\n\n(* Defines a polynomial as a sequence with <> 0 last element *)\nRecord polynomial := Polynomial {polyseq :> seq R; _ : last 1 polyseq != 0}.\n\nCanonical polynomial_subType := Eval hnf in [subType for polyseq].\nDefinition polynomial_eqMixin := Eval hnf in [eqMixin of polynomial by <:].\nCanonical polynomial_eqType := Eval hnf in EqType polynomial polynomial_eqMixin.\nDefinition polynomial_choiceMixin := [choiceMixin of polynomial by <:].\nCanonical polynomial_choiceType :=\n  Eval hnf in ChoiceType polynomial polynomial_choiceMixin.\n\nLemma poly_inj : injective polyseq. Proof. exact: val_inj. Qed.\n\nDefinition poly_of of phant R := polynomial.\nIdentity Coercion type_poly_of : poly_of >-> polynomial.\n\nDefinition coefp_head h i (p : poly_of (Phant R)) := let: tt := h in p`_i.\n\nEnd Polynomial.\n\n(* We need to break off the section here to let the argument scope *)\n(* directives take effect.                                         *)\nBind Scope ring_scope with poly_of.\nBind Scope ring_scope with polynomial.\nArguments polyseq _ _%R.\nArguments poly_inj _ _%R _%R _.\nArguments coefp_head _ _ _%N _%R.\nNotation \"{ 'poly' T }\" := (poly_of (Phant T)).\nNotation coefp i := (coefp_head tt i).\n\nSection PolynomialTheory.\n\nVariable R : ringType.\nImplicit Types (a b c x y z : R) (p q r d : {poly R}).\n\nCanonical poly_subType := Eval hnf in [subType of {poly R}].\nCanonical poly_eqType := Eval hnf in [eqType of {poly R}].\nCanonical poly_choiceType := Eval hnf in [choiceType of {poly R}].\n\nDefinition lead_coef p := p`_(size p).-1.\nLemma lead_coefE p : lead_coef p = p`_(size p).-1. Proof. by []. Qed.\n\nDefinition poly_nil := @Polynomial R [::] (oner_neq0 R).\nDefinition polyC c : {poly R} := insubd poly_nil [:: c].\n\nLocal Notation \"c %:P\" := (polyC c).\n\n(* Remember the boolean (c != 0) is coerced to 1 if true and 0 if false *)\nLemma polyseqC c : c%:P = nseq (c != 0) c :> seq R.\nProof. by rewrite val_insubd /=; case: (c == 0). Qed.\n\nLemma size_polyC c : size c%:P = (c != 0).\nProof. by rewrite polyseqC size_nseq. Qed.\n\nLemma coefC c i : c%:P`_i = if i == 0%N then c else 0.\nProof. by rewrite polyseqC; case: i => [|[]]; case: eqP. Qed.\n\nLemma polyCK : cancel polyC (coefp 0).\nProof. by move=> c; rewrite [coefp 0 _]coefC. Qed.\n\nLemma polyC_inj : injective polyC.\nProof. by move=> c1 c2 eqc12; have:= coefC c2 0; rewrite -eqc12 coefC. Qed.\n\nLemma lead_coefC c : lead_coef c%:P = c.\nProof. by rewrite /lead_coef polyseqC; case: eqP. Qed.\n\n(* Extensional interpretation (poly <=> nat -> R) *)\nLemma polyP p q : nth 0 p =1 nth 0 q <-> p = q.\nProof.\nsplit=> [eq_pq | -> //]; apply: poly_inj.\nwithout loss lt_pq: p q eq_pq / size p < size q.\n  move=> IH; case: (ltngtP (size p) (size q)); try by move/IH->.\n  by move/(@eq_from_nth _ 0); apply.\ncase: q => q nz_q /= in lt_pq eq_pq *; case/eqP: nz_q.\nby rewrite (last_nth 0) -(subnKC lt_pq) /= -eq_pq nth_default ?leq_addr.\nQed.\n\nLemma size1_polyC p : size p <= 1 -> p = (p`_0)%:P.\nProof.\nmove=> le_p_1; apply/polyP=> i; rewrite coefC.\nby case: i => // i; rewrite nth_default // (leq_trans le_p_1).\nQed.\n\n(* Builds a polynomial by extension. *)\nDefinition cons_poly c p : {poly R} :=\n  if p is Polynomial ((_ :: _) as s) ns then\n    @Polynomial R (c :: s) ns\n  else c%:P.\n\nLemma polyseq_cons c p :\n  cons_poly c p = (if ~~ nilp p then c :: p else c%:P) :> seq R.\nProof. by case: p => [[]]. Qed.\n\nLemma size_cons_poly c p :\n  size (cons_poly c p) = (if nilp p && (c == 0) then 0%N else (size p).+1).\nProof. by case: p => [[|c' s] _] //=; rewrite size_polyC; case: eqP. Qed.\n\nLemma coef_cons c p i : (cons_poly c p)`_i = if i == 0%N then c else p`_i.-1.\nProof.\nby case: p i => [[|c' s] _] [] //=; rewrite polyseqC; case: eqP => //= _ [].\nQed.\n\n(* Build a polynomial directly from a list of coefficients. *)\nDefinition Poly := foldr cons_poly 0%:P.\n\nLemma PolyK c s : last c s != 0 -> Poly s = s :> seq R.\nProof.\ncase: s => {c}/= [_ |c s]; first by rewrite polyseqC eqxx.\nelim: s c => /= [|a s IHs] c nz_c; rewrite polyseq_cons ?{}IHs //.\nby rewrite !polyseqC !eqxx nz_c.\nQed.\n\nLemma polyseqK p : Poly p = p.\nProof. by apply: poly_inj; apply: PolyK (valP p). Qed.\n\nLemma size_Poly s : size (Poly s) <= size s.\nProof.\nelim: s => [|c s IHs] /=; first by rewrite polyseqC eqxx.\nby rewrite polyseq_cons; case: ifP => // _; rewrite size_polyC; case: (~~ _).\nQed.\n\nLemma coef_Poly s i : (Poly s)`_i = s`_i.\nProof.\nby elim: s i => [|c s IHs] /= [|i]; rewrite !(coefC, eqxx, coef_cons) /=.\nQed.\n\n(* Build a polynomial from an infinite sequence of coefficients and a bound. *)\nDefinition poly_expanded_def n E := Poly (mkseq E n).\nFact poly_key : unit. Proof. by []. Qed.\nDefinition poly := locked_with poly_key poly_expanded_def.\nCanonical poly_unlockable := [unlockable fun poly].\nLocal Notation \"\\poly_ ( i < n ) E\" := (poly n (fun i : nat => E)).\n\nLemma polyseq_poly n E :\n  E n.-1 != 0 -> \\poly_(i < n) E i = mkseq [eta E] n :> seq R.\nProof.\nrewrite unlock; case: n => [|n] nzEn; first by rewrite polyseqC eqxx.\nby rewrite (@PolyK 0) // -nth_last nth_mkseq size_mkseq.\nQed.\n\nLemma size_poly n E : size (\\poly_(i < n) E i) <= n.\nProof. by rewrite unlock (leq_trans (size_Poly _)) ?size_mkseq. Qed.\n\nLemma size_poly_eq n E : E n.-1 != 0 -> size (\\poly_(i < n) E i) = n.\nProof. by move/polyseq_poly->; apply: size_mkseq. Qed.\n\nLemma coef_poly n E k : (\\poly_(i < n) E i)`_k = (if k < n then E k else 0).\nProof.\nrewrite unlock coef_Poly.\nhave [lt_kn | le_nk] := ltnP k n; first by rewrite nth_mkseq.\nby rewrite nth_default // size_mkseq.\nQed.\n\nLemma lead_coef_poly n E :\n  n > 0 -> E n.-1 != 0 -> lead_coef (\\poly_(i < n) E i) = E n.-1.\nProof.\nby case: n => // n _ nzE; rewrite /lead_coef size_poly_eq // coef_poly leqnn.\nQed.\n\nLemma coefK p : \\poly_(i < size p) p`_i = p.\nProof.\nby apply/polyP=> i; rewrite coef_poly; case: ltnP => // /(nth_default 0)->.\nQed.\n\n(* Zmodule structure for polynomial *)\nDefinition add_poly_def p q := \\poly_(i < maxn (size p) (size q)) (p`_i + q`_i).\nFact add_poly_key : unit. Proof. by []. Qed.\nDefinition add_poly := locked_with add_poly_key add_poly_def.\nCanonical add_poly_unlockable := [unlockable fun add_poly].\n\nDefinition opp_poly_def p := \\poly_(i < size p) - p`_i.\nFact opp_poly_key : unit. Proof. by []. Qed.\nDefinition opp_poly := locked_with opp_poly_key opp_poly_def.\nCanonical opp_poly_unlockable := [unlockable fun opp_poly].\n\nFact coef_add_poly p q i : (add_poly p q)`_i = p`_i + q`_i.\nProof.\nrewrite unlock coef_poly; case: leqP => //.\nby rewrite geq_max => /andP[le_p_i le_q_i]; rewrite !nth_default ?add0r.\nQed.\n\nFact coef_opp_poly p i : (opp_poly p)`_i = - p`_i.\nProof.\nrewrite unlock coef_poly /=.\nby case: leqP => // le_p_i; rewrite nth_default ?oppr0.\nQed.\n\nFact add_polyA : associative add_poly.\nProof. by move=> p q r; apply/polyP=> i; rewrite !coef_add_poly addrA. Qed.\n\nFact add_polyC : commutative add_poly.\nProof. by move=> p q; apply/polyP=> i; rewrite !coef_add_poly addrC. Qed.\n\nFact add_poly0 : left_id 0%:P add_poly.\nProof.\nby move=> p; apply/polyP=> i; rewrite coef_add_poly coefC if_same add0r.\nQed.\n\nFact add_polyN : left_inverse 0%:P opp_poly add_poly.\nProof.\nmove=> p; apply/polyP=> i.\nby rewrite coef_add_poly coef_opp_poly coefC if_same addNr.\nQed.\n\nDefinition poly_zmodMixin :=\n  ZmodMixin add_polyA add_polyC add_poly0 add_polyN.\n\nCanonical poly_zmodType := Eval hnf in ZmodType {poly R} poly_zmodMixin.\nCanonical polynomial_zmodType :=\n  Eval hnf in ZmodType (polynomial R) poly_zmodMixin.\n\n(* Properties of the zero polynomial *)\nLemma polyC0 : 0%:P = 0 :> {poly R}. Proof. by []. Qed.\n\nLemma polyseq0 : (0 : {poly R}) = [::] :> seq R.\nProof. by rewrite polyseqC eqxx. Qed.\n\nLemma size_poly0 : size (0 : {poly R}) = 0%N.\nProof. by rewrite polyseq0. Qed.\n\nLemma coef0 i : (0 : {poly R})`_i = 0.\nProof. by rewrite coefC if_same. Qed.\n\nLemma lead_coef0 : lead_coef 0 = 0 :> R. Proof. exact: lead_coefC. Qed.\n\nLemma size_poly_eq0 p : (size p == 0%N) = (p == 0).\nProof. by rewrite size_eq0 -polyseq0. Qed.\n\nLemma size_poly_leq0 p : (size p <= 0) = (p == 0).\nProof. by rewrite leqn0 size_poly_eq0. Qed.\n\nLemma size_poly_leq0P p : reflect (p = 0) (size p <= 0%N).\nProof. by apply: (iffP idP); rewrite size_poly_leq0; move/eqP. Qed.\n\nLemma size_poly_gt0 p : (0 < size p) = (p != 0).\nProof. by rewrite lt0n size_poly_eq0. Qed.\n\nLemma nil_poly p : nilp p = (p == 0).\nProof. exact: size_poly_eq0. Qed.\n\nLemma poly0Vpos p : {p = 0} + {size p > 0}.\nProof. by rewrite lt0n size_poly_eq0; apply: eqVneq. Qed.\n\nLemma polySpred p : p != 0 -> size p = (size p).-1.+1.\nProof. by rewrite -size_poly_eq0 -lt0n => /prednK. Qed.\n\nLemma lead_coef_eq0 p : (lead_coef p == 0) = (p == 0).\nProof.\nrewrite -nil_poly /lead_coef nth_last.\nby case: p => [[|x s] /= /negbTE // _]; rewrite eqxx.\nQed.\n\nLemma polyC_eq0 (c : R) : (c%:P == 0) = (c == 0).\nProof. by rewrite -nil_poly polyseqC; case: (c == 0). Qed.\n\nLemma size_poly1P p : reflect (exists2 c, c != 0 & p = c%:P) (size p == 1%N).\nProof.\napply: (iffP eqP) => [pC | [c nz_c ->]]; last by rewrite size_polyC nz_c.\nhave def_p: p = (p`_0)%:P by rewrite -size1_polyC ?pC.\nby exists p`_0; rewrite // -polyC_eq0 -def_p -size_poly_eq0 pC.\nQed.\n\nLemma leq_sizeP p i : reflect (forall j, i <= j -> p`_j = 0) (size p <= i).\nProof.\napply: (iffP idP) => [hp j hij| hp].\n  by apply: nth_default; apply: leq_trans hij.\ncase p0: (p == 0); first by rewrite (eqP p0) size_poly0.\nmove: (lead_coef_eq0 p); rewrite p0 leqNgt; move/negbT; apply: contra => hs.\nby apply/eqP; apply: hp; rewrite -ltnS (ltn_predK hs).\nQed.\n\n(* Size, leading coef, morphism properties of coef *)\n\nLemma coefD p q i : (p + q)`_i = p`_i + q`_i.\nProof. exact: coef_add_poly. Qed.\n\nLemma coefN p i : (- p)`_i = - p`_i.\nProof. exact: coef_opp_poly. Qed.\n\nLemma coefB p q i : (p - q)`_i = p`_i - q`_i.\nProof. by rewrite coefD coefN. Qed.\n\nCanonical coefp_additive i :=\n  Additive ((fun p => (coefB p)^~ i) : additive (coefp i)).\n\nLemma coefMn p n i : (p *+ n)`_i = p`_i *+ n.\nProof. exact: (raddfMn (coefp_additive i)). Qed.\n\nLemma coefMNn p n i : (p *- n)`_i = p`_i *- n.\nProof. by rewrite coefN coefMn. Qed.\n\nLemma coef_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) k :\n  (\\sum_(i <- r | P i) F i)`_k = \\sum_(i <- r | P i) (F i)`_k.\nProof. exact: (raddf_sum (coefp_additive k)). Qed.\n\nLemma polyC_add : {morph polyC : a b / a + b}.\nProof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefD !coefC ?addr0. Qed.\n\nLemma polyC_opp : {morph polyC : c / - c}.\nProof. by move=> c; apply/polyP=> [[|i]]; rewrite coefN !coefC ?oppr0. Qed.\n\nLemma polyC_sub : {morph polyC : a b / a - b}.\nProof. by move=> a b; rewrite polyC_add polyC_opp. Qed.\n\nCanonical polyC_additive := Additive polyC_sub.\n\nLemma polyC_muln n : {morph polyC : c / c *+ n}.\nProof. exact: raddfMn. Qed.\n\nLemma size_opp p : size (- p) = size p.\nProof.\nby apply/eqP; rewrite eqn_leq -{3}(opprK p) -[-%R]/opp_poly unlock !size_poly.\nQed.\n\nLemma lead_coef_opp p : lead_coef (- p) = - lead_coef p.\nProof. by rewrite /lead_coef size_opp coefN. Qed.\n\nLemma size_add p q : size (p + q) <= maxn (size p) (size q).\nProof. by rewrite -[+%R]/add_poly unlock; apply: size_poly. Qed.\n\nLemma size_addl p q : size p > size q -> size (p + q) = size p.\nProof.\nmove=> ltqp; rewrite -[+%R]/add_poly unlock size_poly_eq (maxn_idPl (ltnW _))//.\nby rewrite addrC nth_default ?simp ?nth_last //; case: p ltqp => [[]].\nQed.\n\nLemma size_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) :\n  size (\\sum_(i <- r | P i) F i) <= \\max_(i <- r | P i) size (F i).\nProof.\nelim/big_rec2: _ => [|i p q _ IHp]; first by rewrite size_poly0.\nby rewrite -(maxn_idPr IHp) maxnA leq_max size_add.\nQed.\n\nLemma lead_coefDl p q : size p > size q -> lead_coef (p + q) = lead_coef p.\nProof.\nmove=> ltqp; rewrite /lead_coef coefD size_addl //.\nby rewrite addrC nth_default ?simp // -ltnS (ltn_predK ltqp).\nQed.\n\n(* Polynomial ring structure. *)\n\nDefinition mul_poly_def p q :=\n  \\poly_(i < (size p + size q).-1) (\\sum_(j < i.+1) p`_j * q`_(i - j)).\nFact mul_poly_key : unit. Proof. by []. Qed.\nDefinition mul_poly := locked_with mul_poly_key mul_poly_def.\nCanonical mul_poly_unlockable := [unlockable fun mul_poly].\n\nFact coef_mul_poly p q i :\n  (mul_poly p q)`_i = \\sum_(j < i.+1) p`_j * q`_(i - j)%N.\nProof.\nrewrite unlock coef_poly -subn1 ltn_subRL add1n; case: leqP => // le_pq_i1.\nrewrite big1 // => j _; have [lq_q_ij | gt_q_ij] := leqP (size q) (i - j).\n  by rewrite [q`__]nth_default ?mulr0.\nrewrite nth_default ?mul0r // -(leq_add2r (size q)) (leq_trans le_pq_i1) //.\nby rewrite -leq_subLR -subnSK.\nQed.\n\nFact coef_mul_poly_rev p q i :\n  (mul_poly p q)`_i = \\sum_(j < i.+1) p`_(i - j)%N * q`_j.\nProof.\nrewrite coef_mul_poly (reindex_inj rev_ord_inj) /=.\nby apply: eq_bigr => j _; rewrite (sub_ordK j).\nQed.\n\nFact mul_polyA : associative mul_poly.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coef_mul_poly coef_mul_poly_rev.\npose coef3 j k := p`_j * (q`_(i - j - k)%N * r`_k).\ntransitivity (\\sum_(j < i.+1) \\sum_(k < i.+1 | k <= i - j) coef3 j k).\n  apply: eq_bigr => /= j _; rewrite coef_mul_poly_rev big_distrr /=.\n  by rewrite (big_ord_narrow_leq (leq_subr _ _)).\nrewrite (exchange_big_dep predT) //=; apply: eq_bigr => k _.\ntransitivity (\\sum_(j < i.+1 | j <= i - k) coef3 j k).\n  apply: eq_bigl => j; rewrite -ltnS -(ltnS j) -!subSn ?leq_ord //.\n  by rewrite -subn_gt0 -(subn_gt0 j) -!subnDA addnC.\nrewrite (big_ord_narrow_leq (leq_subr _ _)) coef_mul_poly big_distrl /=.\nby apply: eq_bigr => j _; rewrite /coef3 -!subnDA addnC mulrA.\nQed.\n\nFact mul_1poly : left_id 1%:P mul_poly.\nProof.\nmove=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nFact mul_poly1 : right_id 1%:P mul_poly.\nProof.\nmove=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nFact mul_polyDl : left_distributive mul_poly +%R.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split.\nby apply: eq_bigr => j _; rewrite coefD mulrDl.\nQed.\n\nFact mul_polyDr : right_distributive mul_poly +%R.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split.\nby apply: eq_bigr => j _; rewrite coefD mulrDr.\nQed.\n\nFact poly1_neq0 : 1%:P != 0 :> {poly R}.\nProof. by rewrite polyC_eq0 oner_neq0. Qed.\n\nDefinition poly_ringMixin :=\n  RingMixin mul_polyA mul_1poly mul_poly1 mul_polyDl mul_polyDr poly1_neq0.\n\nCanonical poly_ringType := Eval hnf in RingType {poly R} poly_ringMixin.\nCanonical polynomial_ringType :=\n  Eval hnf in RingType (polynomial R) poly_ringMixin.\n\nLemma polyC1 : 1%:P = 1 :> {poly R}. Proof. by []. Qed.\n\nLemma polyseq1 : (1 : {poly R}) = [:: 1] :> seq R.\nProof. by rewrite polyseqC oner_neq0. Qed.\n\nLemma size_poly1 : size (1 : {poly R}) = 1%N.\nProof. by rewrite polyseq1. Qed.\n\nLemma coef1 i : (1 : {poly R})`_i = (i == 0%N)%:R.\nProof. by case: i => [|i]; rewrite polyseq1 /= ?nth_nil. Qed.\n\nLemma lead_coef1 : lead_coef 1 = 1 :> R. Proof. exact: lead_coefC. Qed.\n\nLemma coefM p q i : (p * q)`_i = \\sum_(j < i.+1) p`_j * q`_(i - j)%N.\nProof. exact: coef_mul_poly. Qed.\n\nLemma coefMr p q i : (p * q)`_i = \\sum_(j < i.+1) p`_(i - j)%N * q`_j.\nProof. exact: coef_mul_poly_rev. Qed.\n\nLemma size_mul_leq p q : size (p * q) <= (size p + size q).-1.\nProof. by rewrite -[*%R]/mul_poly unlock size_poly. Qed.\n\nLemma mul_lead_coef p q :\n  lead_coef p * lead_coef q = (p * q)`_(size p + size q).-2.\nProof.\npose dp := (size p).-1; pose dq := (size q).-1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 !mul0r coef0.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite lead_coef0 !mulr0 coef0.\nhave ->: (size p + size q).-2 = (dp + dq)%N.\n  by do 2!rewrite polySpred // addSn addnC.\nhave lt_p_pq: dp < (dp + dq).+1 by rewrite ltnS leq_addr.\nrewrite coefM (bigD1 (Ordinal lt_p_pq)) ?big1 ?simp ?addKn //= => i.\nrewrite -val_eqE neq_ltn /= => /orP[lt_i_p | gt_i_p]; last first.\n  by rewrite nth_default ?mul0r //; rewrite -polySpred in gt_i_p.\nrewrite [q`__]nth_default ?mulr0 //= -subSS -{1}addnS -polySpred //.\nby rewrite addnC -addnBA ?leq_addr.\nQed.\n\nLemma size_proper_mul p q :\n  lead_coef p * lead_coef q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\napply: contraNeq; rewrite mul_lead_coef eqn_leq size_mul_leq -ltnNge => lt_pq.\nby rewrite nth_default // -subn1 -(leq_add2l 1) -leq_subLR leq_sub2r.\nQed.\n\nLemma lead_coef_proper_mul p q :\n  let c := lead_coef p * lead_coef q in c != 0 -> lead_coef (p * q) = c.\nProof. by move=> /= nz_c; rewrite mul_lead_coef -size_proper_mul. Qed.\n\nLemma size_prod_leq (I : finType) (P : pred I) (F : I -> {poly R}) :\n  size (\\prod_(i | P i) F i) <= (\\sum_(i | P i) size (F i)).+1 - #|P|.\nProof.\nrewrite -sum1_card.\nelim/big_rec3: _ => [|i n m p _ IHp]; first by rewrite size_poly1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0.\nrewrite (leq_trans (size_mul_leq _ _)) // subnS -!subn1 leq_sub2r //.\nrewrite -addnS -addnBA ?leq_add2l // ltnW // -subn_gt0 (leq_trans _ IHp) //.\nby rewrite polySpred.\nQed.\n\nLemma coefCM c p i : (c%:P * p)`_i = c * p`_i.\nProof.\nrewrite coefM big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nLemma coefMC c p i : (p * c%:P)`_i = p`_i * c.\nProof.\nrewrite coefMr big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nLemma polyC_mul : {morph polyC : a b / a * b}.\nProof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefCM !coefC ?simp. Qed.\n\nFact polyC_multiplicative : multiplicative polyC.\nProof. by split; first apply: polyC_mul. Qed.\nCanonical polyC_rmorphism := AddRMorphism polyC_multiplicative.\n\nLemma polyC_exp n : {morph polyC : c / c ^+ n}.\nProof. exact: rmorphX. Qed.\n\nLemma size_exp_leq p n : size (p ^+ n) <= ((size p).-1 * n).+1.\nProof.\nelim: n => [|n IHn]; first by rewrite size_poly1.\nhave [-> | nzp] := poly0Vpos p; first by rewrite exprS mul0r size_poly0.\nrewrite exprS (leq_trans (size_mul_leq _ _)) //.\nby rewrite -{1}(prednK nzp) mulnS -addnS leq_add2l.\nQed.\n\nLemma size_Msign p n : size ((-1) ^+ n * p) = size p.\nProof.\nby rewrite -signr_odd; case: (odd n); rewrite ?mul1r // mulN1r size_opp.\nQed.\n\nFact coefp0_multiplicative : multiplicative (coefp 0 : {poly R} -> R).\nProof.\nsplit=> [p q|]; last by rewrite polyCK.\nby rewrite [coefp 0 _]coefM big_ord_recl big_ord0 addr0.\nQed.\n\nCanonical coefp0_rmorphism := AddRMorphism coefp0_multiplicative.\n\n(* Algebra structure of polynomials. *)\nDefinition scale_poly_def a (p : {poly R}) := \\poly_(i < size p) (a * p`_i).\nFact scale_poly_key : unit. Proof. by []. Qed.\nDefinition scale_poly := locked_with scale_poly_key scale_poly_def.\nCanonical scale_poly_unlockable := [unlockable fun scale_poly].\n\nFact scale_polyE a p : scale_poly a p = a%:P * p.\nProof.\napply/polyP=> n; rewrite unlock coef_poly coefCM.\nby case: leqP => // le_p_n; rewrite nth_default ?mulr0.\nQed.\n\nFact scale_polyA a b p : scale_poly a (scale_poly b p) = scale_poly (a * b) p.\nProof. by rewrite !scale_polyE mulrA polyC_mul. Qed.\n\nFact scale_1poly : left_id 1 scale_poly.\nProof. by move=> p; rewrite scale_polyE mul1r. Qed.\n\nFact scale_polyDr a : {morph scale_poly a : p q / p + q}.\nProof. by move=> p q; rewrite !scale_polyE mulrDr. Qed.\n\nFact scale_polyDl p : {morph scale_poly^~ p : a b / a + b}.\nProof. by move=> a b /=; rewrite !scale_polyE raddfD mulrDl. Qed.\n\nFact scale_polyAl a p q : scale_poly a (p * q) = scale_poly a p * q.\nProof. by rewrite !scale_polyE mulrA. Qed.\n\nDefinition poly_lmodMixin :=\n  LmodMixin scale_polyA scale_1poly scale_polyDr scale_polyDl.\n\nCanonical poly_lmodType :=\n  Eval hnf in LmodType R {poly R} poly_lmodMixin.\nCanonical polynomial_lmodType :=\n  Eval hnf in LmodType R (polynomial R) poly_lmodMixin.\nCanonical poly_lalgType :=\n  Eval hnf in LalgType R {poly R} scale_polyAl.\nCanonical polynomial_lalgType :=\n  Eval hnf in LalgType R (polynomial R) scale_polyAl.\n\nLemma mul_polyC a p : a%:P * p = a *: p.\nProof. by rewrite -scale_polyE. Qed.\n\nLemma alg_polyC a : a%:A = a%:P :> {poly R}.\nProof. by rewrite -mul_polyC mulr1. Qed.\n\nLemma coefZ a p i : (a *: p)`_i = a * p`_i.\nProof.\nrewrite -[*:%R]/scale_poly unlock coef_poly.\nby case: leqP => // le_p_n; rewrite nth_default ?mulr0.\nQed.\n\nLemma size_scale_leq a p : size (a *: p) <= size p.\nProof. by rewrite -[*:%R]/scale_poly unlock size_poly. Qed.\n\nCanonical coefp_linear i : {scalar {poly R}} :=\n  AddLinear ((fun a => (coefZ a) ^~ i) : scalable_for *%R (coefp i)).\nCanonical coefp0_lrmorphism := [lrmorphism of coefp 0].\n\n(* The indeterminate, at last! *)\nDefinition polyX_def := Poly [:: 0; 1].\nFact polyX_key : unit. Proof. by []. Qed.\nDefinition polyX : {poly R} := locked_with polyX_key polyX_def.\nCanonical polyX_unlockable := [unlockable of polyX].\nLocal Notation \"'X\" := polyX.\n\nLemma polyseqX : 'X = [:: 0; 1] :> seq R.\nProof. by rewrite unlock !polyseq_cons nil_poly eqxx /= polyseq1. Qed.\n\nLemma size_polyX : size 'X = 2. Proof. by rewrite polyseqX. Qed.\n\nLemma polyX_eq0 : ('X == 0) = false.\nProof. by rewrite -size_poly_eq0 size_polyX. Qed.\n\nLemma coefX i : 'X`_i = (i == 1%N)%:R.\nProof. by case: i => [|[|i]]; rewrite polyseqX //= nth_nil. Qed.\n\nLemma lead_coefX : lead_coef 'X = 1.\nProof. by rewrite /lead_coef polyseqX. Qed.\n\nLemma commr_polyX p : GRing.comm p 'X.\nProof.\napply/polyP=> i; rewrite coefMr coefM.\nby apply: eq_bigr => j _; rewrite coefX commr_nat.\nQed.\n\nLemma coefMX p i : (p * 'X)`_i = (if (i == 0)%N then 0 else p`_i.-1).\nProof.\nrewrite coefMr big_ord_recl coefX ?simp.\ncase: i => [|i]; rewrite ?big_ord0 //= big_ord_recl polyseqX subn1 /=.\nby rewrite big1 ?simp // => j _; rewrite nth_nil !simp.\nQed.\n\nLemma coefXM p i : ('X * p)`_i = (if (i == 0)%N then 0 else p`_i.-1).\nProof. by rewrite -commr_polyX coefMX. Qed.\n\nLemma cons_poly_def p a : cons_poly a p = p * 'X + a%:P.\nProof.\napply/polyP=> i; rewrite coef_cons coefD coefMX coefC.\nby case: ifP; rewrite !simp.\nQed.\n\nLemma poly_ind (K : {poly R} -> Type) :\n  K 0 -> (forall p c, K p -> K (p * 'X + c%:P)) -> (forall p, K p).\nProof.\nmove=> K0 Kcons p; rewrite -[p]polyseqK.\nby elim: {p}(p : seq R) => //= p c IHp; rewrite cons_poly_def; apply: Kcons.\nQed.\n\nLemma polyseqXsubC a : 'X - a%:P = [:: - a; 1] :> seq R.\nProof.\nby rewrite -['X]mul1r -polyC_opp -cons_poly_def polyseq_cons polyseq1.\nQed.\n\nLemma size_XsubC a : size ('X - a%:P) = 2%N.\nProof. by rewrite polyseqXsubC. Qed.\n\nLemma size_XaddC b : size ('X + b%:P) = 2.\nProof. by rewrite -[b]opprK rmorphN size_XsubC. Qed.\n\nLemma lead_coefXsubC a : lead_coef ('X - a%:P) = 1.\nProof. by rewrite lead_coefE polyseqXsubC. Qed.\n\nLemma polyXsubC_eq0 a : ('X - a%:P == 0) = false.\nProof. by rewrite -nil_poly polyseqXsubC. Qed.\n\nLemma size_MXaddC p c :\n  size (p * 'X + c%:P) = (if (p == 0) && (c == 0) then 0%N else (size p).+1).\nProof. by rewrite -cons_poly_def size_cons_poly nil_poly. Qed.\n\nLemma polyseqMX p : p != 0 -> p * 'X = 0 :: p :> seq R.\nProof.\nby move=> nz_p; rewrite -[p * _]addr0 -cons_poly_def polyseq_cons nil_poly nz_p.\nQed.\n\nLemma size_mulX p : p != 0 -> size (p * 'X) = (size p).+1.\nProof. by move/polyseqMX->. Qed.\n\nLemma lead_coefMX p : lead_coef (p * 'X) = lead_coef p.\nProof.\nhave [-> | nzp] := eqVneq p 0; first by rewrite mul0r.\nby rewrite /lead_coef !nth_last polyseqMX.\nQed.\n\nLemma size_XmulC a : a != 0 -> size ('X * a%:P) = 2.\nProof.\nby move=> nz_a; rewrite -commr_polyX size_mulX ?polyC_eq0 ?size_polyC nz_a.\nQed.\n\nLocal Notation \"''X^' n\" := ('X ^+ n).\n\nLemma coefXn n i : 'X^n`_i = (i == n)%:R.\nProof.\nby elim: n i => [|n IHn] [|i]; rewrite ?coef1 // exprS coefXM ?IHn.\nQed.\n\nLemma polyseqXn n : 'X^n = rcons (nseq n 0) 1 :> seq R.\nProof.\nelim: n => [|n IHn]; rewrite ?polyseq1 // exprSr.\nby rewrite polyseqMX -?size_poly_eq0 IHn ?size_rcons.\nQed.\n\nLemma size_polyXn n : size 'X^n = n.+1.\nProof. by rewrite polyseqXn size_rcons size_nseq. Qed.\n\nLemma commr_polyXn p n : GRing.comm p 'X^n.\nProof. by apply: commrX; apply: commr_polyX. Qed.\n\nLemma lead_coefXn n : lead_coef 'X^n = 1.\nProof. by rewrite /lead_coef nth_last polyseqXn last_rcons. Qed.\n\nLemma polyseqMXn n p : p != 0 -> p * 'X^n = ncons n 0 p :> seq R.\nProof.\ncase: n => [|n] nz_p; first by rewrite mulr1.\nelim: n => [|n IHn]; first exact: polyseqMX.\nby rewrite exprSr mulrA polyseqMX -?nil_poly IHn.\nQed.\n\nLemma coefMXn n p i : (p * 'X^n)`_i = if i < n then 0 else p`_(i - n).\nProof.\nhave [-> | /polyseqMXn->] := eqVneq p 0; last exact: nth_ncons.\nby rewrite mul0r !coef0 if_same.\nQed.\n\nLemma coefXnM n p i : ('X^n * p)`_i = if i < n then 0 else p`_(i - n).\nProof. by rewrite -commr_polyXn coefMXn. Qed.\n\n(* Expansion of a polynomial as an indexed sum *)\nLemma poly_def n E : \\poly_(i < n) E i = \\sum_(i < n) E i *: 'X^i.\nProof.\nrewrite unlock; elim: n => [|n IHn] in E *; first by rewrite big_ord0.\nrewrite big_ord_recl /= cons_poly_def addrC expr0 alg_polyC.\ncongr (_ + _); rewrite (iota_addl 1 0) -map_comp IHn big_distrl /=.\nby apply: eq_bigr => i _; rewrite -scalerAl exprSr.\nQed.\n\n(* Monic predicate *)\nDefinition monic := [qualify p | lead_coef p == 1].\nFact monic_key : pred_key monic. Proof. by []. Qed.\nCanonical monic_keyed := KeyedQualifier monic_key.\n\nLemma monicE p : (p \\is monic) = (lead_coef p == 1). Proof. by []. Qed.\nLemma monicP p : reflect (lead_coef p = 1) (p \\is monic).\nProof. exact: eqP. Qed.\n\nLemma monic1 : 1 \\is monic. Proof. exact/eqP/lead_coef1. Qed.\nLemma monicX : 'X \\is monic. Proof. exact/eqP/lead_coefX. Qed.\nLemma monicXn n : 'X^n \\is monic. Proof. exact/eqP/lead_coefXn. Qed.\n\nLemma monic_neq0 p : p \\is monic -> p != 0.\nProof. by rewrite -lead_coef_eq0 => /eqP->; apply: oner_neq0. Qed.\n\nLemma lead_coef_monicM p q : p \\is monic -> lead_coef (p * q) = lead_coef q.\nProof.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite mulr0.\nby move/monicP=> mon_p; rewrite lead_coef_proper_mul mon_p mul1r ?lead_coef_eq0.\nQed.\n\nLemma lead_coef_Mmonic p q : q \\is monic -> lead_coef (p * q) = lead_coef p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mul0r.\nby move/monicP=> mon_q; rewrite lead_coef_proper_mul mon_q mulr1 ?lead_coef_eq0.\nQed.\n\nLemma size_monicM p q :\n  p \\is monic -> q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nmove/monicP=> mon_p nz_q.\nby rewrite size_proper_mul // mon_p mul1r lead_coef_eq0.\nQed.\n\nLemma size_Mmonic p q :\n  p != 0 -> q \\is monic -> size (p * q) = (size p + size q).-1.\nProof.\nmove=> nz_p /monicP mon_q.\nby rewrite size_proper_mul // mon_q mulr1 lead_coef_eq0.\nQed.\n\nLemma monicMl p q : p \\is monic -> (p * q \\is monic) = (q \\is monic).\nProof. by move=> mon_p; rewrite !monicE lead_coef_monicM. Qed.\n\nLemma monicMr p q : q \\is monic -> (p * q \\is monic) = (p \\is monic).\nProof. by move=> mon_q; rewrite !monicE lead_coef_Mmonic. Qed.\n\nFact monic_mulr_closed : mulr_closed monic.\nProof. by split=> [|p q mon_p]; rewrite (monic1, monicMl). Qed.\nCanonical monic_mulrPred := MulrPred monic_mulr_closed.\n\nLemma monic_exp p n : p \\is monic -> p ^+ n \\is monic.\nProof. exact: rpredX. Qed.\n\nLemma monic_prod I rI (P : pred I) (F : I -> {poly R}):\n  (forall i, P i -> F i \\is monic) -> \\prod_(i <- rI | P i) F i \\is monic.\nProof. exact: rpred_prod. Qed.\n\nLemma monicXsubC c : 'X - c%:P \\is monic.\nProof. exact/eqP/lead_coefXsubC. Qed.\n\nLemma monic_prod_XsubC I rI (P : pred I) (F : I -> R) :\n  \\prod_(i <- rI | P i) ('X - (F i)%:P) \\is monic.\nProof. by apply: monic_prod => i _; apply: monicXsubC. Qed.\n\nLemma size_prod_XsubC I rI (F : I -> R) :\n  size (\\prod_(i <- rI) ('X - (F i)%:P)) = (size rI).+1.\nProof.\nelim: rI => [|i r /= <-]; rewrite ?big_nil ?size_poly1 // big_cons.\nrewrite size_monicM ?monicXsubC ?monic_neq0 ?monic_prod_XsubC //.\nby rewrite size_XsubC.\nQed.\n\nLemma size_exp_XsubC n a : size (('X - a%:P) ^+ n) = n.+1.\nProof. by rewrite -[n]card_ord -prodr_const size_prod_XsubC cardE enumT. Qed.\n\n(* Some facts about regular elements. *)\n\nLemma lreg_lead p : GRing.lreg (lead_coef p) -> GRing.lreg p.\nProof.\nmove/mulrI_eq0=> reg_p; apply: mulrI0_lreg => q /eqP; apply: contraTeq => nz_q.\nby rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0.\nQed.\n\nLemma rreg_lead p : GRing.rreg (lead_coef p) -> GRing.rreg p.\nProof.\nmove/mulIr_eq0=> reg_p; apply: mulIr0_rreg => q /eqP; apply: contraTeq => nz_q.\nby rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0.\nQed.\n\nLemma lreg_lead0 p : GRing.lreg (lead_coef p) -> p != 0.\nProof. by move/lreg_neq0; rewrite lead_coef_eq0. Qed.\n\nLemma rreg_lead0 p : GRing.rreg (lead_coef p) -> p != 0.\nProof. by move/rreg_neq0; rewrite lead_coef_eq0. Qed.\n\nLemma lreg_size c p : GRing.lreg c -> size (c *: p) = size p.\nProof.\nmove=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite scaler0.\nrewrite -mul_polyC size_proper_mul; first by rewrite size_polyC lreg_neq0.\nby rewrite lead_coefC mulrI_eq0 ?lead_coef_eq0.\nQed.\n\nLemma lreg_polyZ_eq0 c p : GRing.lreg c -> (c *: p == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /lreg_size->. Qed.\n\nLemma lead_coef_lreg c p :\n  GRing.lreg c -> lead_coef (c *: p) = c * lead_coef p.\nProof. by move=> reg_c; rewrite !lead_coefE coefZ lreg_size. Qed.\n\nLemma rreg_size c p : GRing.rreg c -> size (p * c%:P) =  size p.\nProof.\nmove=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r.\nrewrite size_proper_mul; first by rewrite size_polyC rreg_neq0 ?addn1.\nby rewrite lead_coefC mulIr_eq0 ?lead_coef_eq0.\nQed.\n\nLemma rreg_polyMC_eq0 c p : GRing.rreg c -> (p * c%:P == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /rreg_size->. Qed.\n\nLemma rreg_div0 q r d :\n    GRing.rreg (lead_coef d) -> size r < size d ->\n  (q * d + r == 0) = (q == 0) && (r == 0).\nProof.\nmove=> reg_d lt_r_d; rewrite addrC addr_eq0.\nhave [-> | nz_q] := altP (q =P 0); first by rewrite mul0r oppr0.\napply: contraTF lt_r_d => /eqP->; rewrite -leqNgt size_opp.\nrewrite size_proper_mul ?mulIr_eq0 ?lead_coef_eq0 //.\nby rewrite (polySpred nz_q) leq_addl.\nQed.\n\nLemma monic_comreg p :\n  p \\is monic -> GRing.comm p (lead_coef p)%:P /\\ GRing.rreg (lead_coef p).\nProof. by move/monicP->; split; [apply: commr1 | apply: rreg1]. Qed.\n\n(* Horner evaluation of polynomials *)\nImplicit Types s rs : seq R.\nFixpoint horner_rec s x := if s is a :: s' then horner_rec s' x * x + a else 0.\nDefinition horner p := horner_rec p.\n\nLocal Notation \"p .[ x ]\" := (horner p x) : ring_scope.\n\nLemma horner0 x : (0 : {poly R}).[x] = 0.\nProof. by rewrite /horner polyseq0. Qed.\n\nLemma hornerC c x : (c%:P).[x] = c.\nProof. by rewrite /horner polyseqC; case: eqP; rewrite /= ?simp. Qed.\n\nLemma hornerX x : 'X.[x] = x.\nProof. by rewrite /horner polyseqX /= !simp. Qed.\n\nLemma horner_cons p c x : (cons_poly c p).[x] = p.[x] * x + c.\nProof.\nrewrite /horner polyseq_cons; case: nilP => //= ->.\nby rewrite !simp -/(_.[x]) hornerC.\nQed.\n\nLemma horner_coef0 p : p.[0] = p`_0.\nProof. by rewrite /horner; case: (p : seq R) => //= c p'; rewrite !simp. Qed.\n\nLemma hornerMXaddC p c x : (p * 'X + c%:P).[x] = p.[x] * x + c.\nProof. by rewrite -cons_poly_def horner_cons. Qed.\n\nLemma hornerMX p x : (p * 'X).[x] = p.[x] * x.\nProof. by rewrite -[p * 'X]addr0 hornerMXaddC addr0. Qed.\n\nLemma horner_Poly s x : (Poly s).[x] = horner_rec s x.\nProof. by elim: s => [|a s /= <-]; rewrite (horner0, horner_cons). Qed.\n\nLemma horner_coef p x : p.[x] = \\sum_(i < size p) p`_i * x ^+ i.\nProof.\nrewrite /horner.\nelim: {p}(p : seq R) => /= [|a s ->]; first by rewrite big_ord0.\nrewrite big_ord_recl simp addrC big_distrl /=.\nby congr (_ + _); apply: eq_bigr => i _; rewrite -mulrA exprSr.\nQed.\n\nLemma horner_coef_wide n p x :\n  size p <= n -> p.[x] = \\sum_(i < n) p`_i * x ^+ i.\nProof.\nmove=> le_p_n.\nrewrite horner_coef (big_ord_widen n (fun i => p`_i * x ^+ i)) // big_mkcond.\nby apply: eq_bigr => i _; case: ltnP => // le_p_i; rewrite nth_default ?simp.\nQed.\n\nLemma horner_poly n E x : (\\poly_(i < n) E i).[x] = \\sum_(i < n) E i * x ^+ i.\nProof.\nrewrite (@horner_coef_wide n) ?size_poly //.\nby apply: eq_bigr => i _; rewrite coef_poly ltn_ord.\nQed.\n\nLemma hornerN p x : (- p).[x] = - p.[x].\nProof.\nrewrite -[-%R]/opp_poly unlock horner_poly horner_coef -sumrN /=.\nby apply: eq_bigr => i _; rewrite mulNr.\nQed.\n\nLemma hornerD p q x : (p + q).[x] = p.[x] + q.[x].\nProof.\nrewrite -[+%R]/add_poly unlock horner_poly; set m := maxn _ _.\nrewrite !(@horner_coef_wide m) ?leq_max ?leqnn ?orbT // -big_split /=.\nby apply: eq_bigr => i _; rewrite -mulrDl.\nQed.\n\nLemma hornerXsubC a x : ('X - a%:P).[x] = x - a.\nProof. by rewrite hornerD hornerN hornerC hornerX. Qed.\n\nLemma horner_sum I (r : seq I) (P : pred I) F x :\n  (\\sum_(i <- r | P i) F i).[x] = \\sum_(i <- r | P i) (F i).[x].\nProof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (horner0, hornerD). Qed.\n\nLemma hornerCM a p x : (a%:P * p).[x] = a * p.[x].\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(mulr0, horner0).\nby rewrite mulrDr mulrA -polyC_mul !hornerMXaddC IHp mulrDr mulrA.\nQed.\n\nLemma hornerZ c p x : (c *: p).[x] = c * p.[x].\nProof. by rewrite -mul_polyC hornerCM. Qed.\n\nLemma hornerMn n p x : (p *+ n).[x] = p.[x] *+ n.\nProof. by elim: n => [| n IHn]; rewrite ?horner0 // !mulrS hornerD IHn. Qed.\n\nDefinition comm_coef p x := forall i, p`_i * x = x * p`_i.\n\nDefinition comm_poly p x := x * p.[x] = p.[x] * x.\n\nLemma comm_coef_poly p x : comm_coef p x -> comm_poly p x.\nProof.\nmove=> cpx; rewrite /comm_poly !horner_coef big_distrl big_distrr /=.\nby apply: eq_bigr => i _; rewrite /= mulrA -cpx -!mulrA commrX.\nQed.\n\nLemma comm_poly0 x : comm_poly 0 x.\nProof. by rewrite /comm_poly !horner0 !simp. Qed.\n\nLemma comm_poly1 x : comm_poly 1 x.\nProof. by rewrite /comm_poly !hornerC !simp. Qed.\n\nLemma comm_polyX x : comm_poly 'X x.\nProof. by rewrite /comm_poly !hornerX. Qed.\n\nLemma hornerM_comm p q x : comm_poly q x -> (p * q).[x] = p.[x] * q.[x].\nProof.\nmove=> comm_qx.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(simp, horner0).\nrewrite mulrDl hornerD hornerCM -mulrA -commr_polyX mulrA hornerMX.\nby rewrite {}IHp -mulrA -comm_qx mulrA -mulrDl hornerMXaddC.\nQed.\n\nLemma horner_exp_comm p x n : comm_poly p x -> (p ^+ n).[x] = p.[x] ^+ n.\nProof.\nmove=> comm_px; elim: n => [|n IHn]; first by rewrite hornerC.\nby rewrite !exprSr -IHn hornerM_comm.\nQed.\n\nLemma hornerXn x n : ('X^n).[x] = x ^+ n.\nProof. by rewrite horner_exp_comm /comm_poly hornerX. Qed.\n\nDefinition hornerE_comm :=\n  (hornerD, hornerN, hornerX, hornerC, horner_cons,\n   simp, hornerCM, hornerZ,\n   (fun p x => hornerM_comm p (comm_polyX x))).\n\nDefinition root p : pred R := fun x => p.[x] == 0.\n\nLemma mem_root p x : x \\in root p = (p.[x] == 0).\nProof. by []. Qed.\n\nLemma rootE p x : (root p x = (p.[x] == 0)) * ((x \\in root p) = (p.[x] == 0)).\nProof. by []. Qed.\n\nLemma rootP p x : reflect (p.[x] = 0) (root p x).\nProof. exact: eqP. Qed.\n\nLemma rootPt p x : reflect (p.[x] == 0) (root p x).\nProof. exact: idP. Qed.\n\nLemma rootPf p x : reflect ((p.[x] == 0) = false) (~~ root p x).\nProof. exact: negPf. Qed.\n\nLemma rootC a x : root a%:P x = (a == 0).\nProof. by rewrite rootE hornerC. Qed.\n\nLemma root0 x : root 0 x.\nProof. by rewrite rootC. Qed.\n\nLemma root1 x : ~~ root 1 x.\nProof. by rewrite rootC oner_eq0. Qed.\n\nLemma rootX x : root 'X x = (x == 0).\nProof. by rewrite rootE hornerX. Qed.\n\nLemma rootN p x : root (- p) x = root p x.\nProof. by rewrite rootE hornerN oppr_eq0. Qed.\n\nLemma root_size_gt1 a p : p != 0 -> root p a -> 1 < size p.\nProof.\nrewrite ltnNge => nz_p; apply: contraL => /size1_polyC Dp.\nby rewrite Dp rootC -polyC_eq0 -Dp.\nQed.\n\nLemma root_XsubC a x : root ('X - a%:P) x = (x == a).\nProof. by rewrite rootE hornerXsubC subr_eq0. Qed.\n\nLemma root_XaddC a x : root ('X + a%:P) x = (x == - a).\nProof. by rewrite -root_XsubC rmorphN opprK. Qed.\n\nTheorem factor_theorem p a : reflect (exists q, p = q * ('X - a%:P)) (root p a).\nProof.\napply: (iffP eqP) => [pa0 | [q ->]]; last first.\n  by rewrite hornerM_comm /comm_poly hornerXsubC subrr ?simp.\nexists (\\poly_(i < size p) horner_rec (drop i.+1 p) a).\napply/polyP=> i; rewrite mulrBr coefB coefMX coefMC !coef_poly.\napply: canRL (addrK _) _; rewrite addrC; have [le_p_i | lt_i_p] := leqP.\n  rewrite nth_default // !simp drop_oversize ?if_same //.\n  exact: leq_trans (leqSpred _).\ncase: i => [|i] in lt_i_p *; last by rewrite ltnW // (drop_nth 0 lt_i_p).\nby rewrite drop1 /= -{}pa0 /horner; case: (p : seq R) lt_i_p.\nQed.\n\nLemma multiplicity_XsubC p a :\n  {m | exists2 q, (p != 0) ==> ~~ root q a & p = q * ('X - a%:P) ^+ m}.\nProof.\nelim: {p}(size p) {-2}p (eqxx (size p)) => [|n IHn] p.\n  by rewrite size_poly_eq0 => ->; exists 0%N, p; rewrite ?mulr1.\nhave [/sig_eqW[{p}p ->] sz_p | nz_pa] := altP (factor_theorem p a); last first.\n  by exists 0%N, p; rewrite ?mulr1 ?nz_pa ?implybT.\nhave nz_p: p != 0 by apply: contraTneq sz_p => ->; rewrite mul0r size_poly0.\nrewrite size_Mmonic ?monicXsubC // size_XsubC addn2 eqSS in sz_p.\nhave [m /sig2_eqW[q nz_qa Dp]] := IHn p sz_p; rewrite nz_p /= in nz_qa.\nby exists m.+1, q; rewrite ?nz_qa ?implybT // exprSr mulrA -Dp.\nQed.\n\n(* Roots of unity. *)\n\nLemma size_Xn_sub_1 n : n > 0 -> size ('X^n - 1 : {poly R}) = n.+1.\nProof.\nby move=> n_gt0; rewrite size_addl size_polyXn // size_opp size_poly1.\nQed.\n\nLemma monic_Xn_sub_1 n : n > 0 -> 'X^n - 1 \\is monic.\nProof.\nmove=> n_gt0; rewrite monicE lead_coefE size_Xn_sub_1 // coefB.\nby rewrite coefXn coef1 eqxx eqn0Ngt n_gt0 subr0.\nQed.\n\nDefinition root_of_unity n : pred R := root ('X^n - 1).\nLocal Notation \"n .-unity_root\" := (root_of_unity n) : ring_scope.\n\nLemma unity_rootE n z : n.-unity_root z = (z ^+ n == 1).\nProof.\nby rewrite /root_of_unity rootE hornerD hornerN hornerXn hornerC subr_eq0.\nQed.\n\nLemma unity_rootP n z : reflect (z ^+ n = 1) (n.-unity_root z).\nProof. by rewrite unity_rootE; apply: eqP. Qed.\n\nDefinition primitive_root_of_unity n z :=\n  (n > 0) && [forall i : 'I_n, i.+1.-unity_root z == (i.+1 == n)].\nLocal Notation \"n .-primitive_root\" := (primitive_root_of_unity n) : ring_scope.\n\nLemma prim_order_exists n z :\n  n > 0 -> z ^+ n = 1 -> {m | m.-primitive_root z & (m %| n)}.\nProof.\nmove=> n_gt0 zn1.\nhave: exists m, (m > 0) && (z ^+ m == 1) by exists n; rewrite n_gt0 /= zn1.\ncase/ex_minnP=> m /andP[m_gt0 /eqP zm1] m_min.\nexists m.\n  apply/andP; split=> //; apply/eqfunP=> [[i]] /=.\n  rewrite leq_eqVlt unity_rootE.\n  case: eqP => [-> _ | _]; first by rewrite zm1 eqxx.\n  by apply: contraTF => zi1; rewrite -leqNgt m_min.\nhave: n %% m < m by rewrite ltn_mod.\napply: contraLR; rewrite -lt0n -leqNgt => nm_gt0; apply: m_min.\nby rewrite nm_gt0 /= expr_mod ?zn1.\nQed.\n\nSection OnePrimitive.\n\nVariables (n : nat) (z : R).\nHypothesis prim_z : n.-primitive_root z.\n\nLemma prim_order_gt0 : n > 0. Proof. by case/andP: prim_z. Qed.\nLet n_gt0 := prim_order_gt0.\n\nLemma prim_expr_order : z ^+ n = 1.\nProof.\ncase/andP: prim_z => _; rewrite -(prednK n_gt0) => /forallP/(_ ord_max).\nby rewrite unity_rootE eqxx eqb_id => /eqP.\nQed.\n\nLemma prim_expr_mod i : z ^+ (i %% n) = z ^+ i.\nProof. exact: expr_mod prim_expr_order. Qed.\n\nLemma prim_order_dvd i : (n %| i) = (z ^+ i == 1).\nProof.\nmove: n_gt0; rewrite -prim_expr_mod /dvdn -(ltn_mod i).\ncase: {i}(i %% n)%N => [|i] lt_i; first by rewrite !eqxx.\ncase/andP: prim_z => _ /forallP/(_ (Ordinal (ltnW lt_i))).\nby move/eqP; rewrite unity_rootE eqn_leq andbC leqNgt lt_i.\nQed.\n\nLemma eq_prim_root_expr i j : (z ^+ i == z ^+ j) = (i == j %[mod n]).\nProof.\nwlog le_ji: i j / j <= i.\n  move=> IH; case: (leqP j i); last move/ltnW; move/IH=> //.\n  by rewrite eq_sym (eq_sym (j %% n)%N).\nrewrite -{1}(subnKC le_ji) exprD -prim_expr_mod eqn_mod_dvd //.\nrewrite prim_order_dvd; apply/eqP/eqP=> [|->]; last by rewrite mulr1.\nmove/(congr1 ( *%R (z ^+ (n - j %% n)))); rewrite mulrA -exprD.\nby rewrite subnK ?prim_expr_order ?mul1r // ltnW ?ltn_mod.\nQed.\n\nLemma exp_prim_root k : (n %/ gcdn k n).-primitive_root (z ^+ k).\nProof.\nset d := gcdn k n; have d_gt0: (0 < d)%N by rewrite gcdn_gt0 orbC n_gt0.\nhave [d_dv_k d_dv_n]: (d %| k /\\ d %| n)%N by rewrite dvdn_gcdl dvdn_gcdr.\nset q := (n %/ d)%N; rewrite /q.-primitive_root ltn_divRL // n_gt0.\napply/forallP=> i; rewrite unity_rootE -exprM -prim_order_dvd.\nrewrite -(divnK d_dv_n) -/q -(divnK d_dv_k) mulnAC dvdn_pmul2r //.\napply/eqP; apply/idP/idP=> [|/eqP->]; last by rewrite dvdn_mull.\nrewrite Gauss_dvdr; first by rewrite eqn_leq ltn_ord; apply: dvdn_leq.\nby rewrite /coprime gcdnC -(eqn_pmul2r d_gt0) mul1n muln_gcdl !divnK.\nQed.\n\nLemma dvdn_prim_root m : (m %| n)%N -> m.-primitive_root (z ^+ (n %/ m)).\nProof.\nset k := (n %/ m)%N => m_dv_n; rewrite -{1}(mulKn m n_gt0) -divnA // -/k.\nby rewrite -{1}(@gcdn_idPl k n _) ?exp_prim_root // -(divnK m_dv_n) dvdn_mulr.\nQed.\n\nEnd OnePrimitive.\n\nLemma prim_root_exp_coprime n z k :\n  n.-primitive_root z -> n.-primitive_root (z ^+ k) = coprime k n.\nProof.\nmove=> prim_z; have n_gt0 := prim_order_gt0 prim_z.\napply/idP/idP=> [prim_zk | co_k_n].\n  set d := gcdn k n; have dv_d_n: (d %| n)%N := dvdn_gcdr _ _.\n  rewrite /coprime -/d -(eqn_pmul2r n_gt0) mul1n -{2}(gcdnMl n d).\n  rewrite -{2}(divnK dv_d_n) (mulnC _ d) -muln_gcdr (gcdn_idPr _) //.\n  rewrite (prim_order_dvd prim_zk) -exprM -(prim_order_dvd prim_z).\n  by rewrite muln_divCA_gcd dvdn_mulr.\nhave zkn_1: z ^+ k ^+ n = 1 by rewrite exprAC (prim_expr_order prim_z) expr1n.\nhave{zkn_1} [m prim_zk dv_m_n]:= prim_order_exists n_gt0 zkn_1.\nsuffices /eqP <-: m == n by [].\nrewrite eqn_dvd dv_m_n -(@Gauss_dvdr n k m) 1?coprime_sym //=.\nby rewrite (prim_order_dvd prim_z) exprM (prim_expr_order prim_zk).\nQed.\n\n(* Lifting a ring predicate to polynomials. *)\n\nDefinition polyOver (S : pred_class) :=\n  [qualify a p : {poly R} | all (mem S) p].\n\nFact polyOver_key S : pred_key (polyOver S). Proof. by []. Qed.\nCanonical polyOver_keyed S := KeyedQualifier (polyOver_key S).\n\nLemma polyOverS (S1 S2 : pred_class) :\n  {subset S1 <= S2} -> {subset polyOver S1 <= polyOver S2}.\nProof.\nby move=> sS12 p /(all_nthP 0)S1p; apply/(all_nthP 0)=> i /S1p; apply: sS12.\nQed.\n\nLemma polyOver0 S : 0 \\is a polyOver S.\nProof. by rewrite qualifE polyseq0. Qed.\n\nLemma polyOver_poly (S : pred_class) n E :\n  (forall i, i < n -> E i \\in S) -> \\poly_(i < n) E i \\is a polyOver S.\nProof.\nmove=> S_E; apply/(all_nthP 0)=> i lt_i_p /=; rewrite coef_poly.\nby case: ifP => [/S_E// | /idP[]]; apply: leq_trans lt_i_p (size_poly n E).\nQed.\n\nSection PolyOverAdd.\n\nVariables (S : predPredType R) (addS : addrPred S) (kS : keyed_pred addS).\n\nLemma polyOverP {p} : reflect (forall i, p`_i \\in kS) (p \\in polyOver kS).\nProof.\napply: (iffP (all_nthP 0)) => [Sp i | Sp i _]; last exact: Sp.\nby have [/Sp // | /(nth_default 0)->] := ltnP i (size p); apply: rpred0.\nQed.\n\nLemma polyOverC c : (c%:P \\in polyOver kS) = (c \\in kS).\nProof.\nby rewrite qualifE polyseqC; case: eqP => [->|] /=; rewrite ?andbT ?rpred0.\nQed.\n\nFact polyOver_addr_closed : addr_closed (polyOver kS).\nProof.\nsplit=> [|p q Sp Sq]; first exact: polyOver0.\nby apply/polyOverP=> i; rewrite coefD rpredD ?(polyOverP _).\nQed.\nCanonical polyOver_addrPred := AddrPred polyOver_addr_closed.\n\nEnd PolyOverAdd.\n\nFact polyOverNr S (addS : zmodPred S) (kS : keyed_pred addS) :\n  oppr_closed (polyOver kS).\nProof.\nby move=> p /polyOverP Sp; apply/polyOverP=> i; rewrite coefN rpredN.\nQed.\nCanonical polyOver_opprPred S addS kS := OpprPred (@polyOverNr S addS kS).\nCanonical polyOver_zmodPred S addS kS := ZmodPred (@polyOverNr S addS kS).\n\nSection PolyOverSemiring.\n\nContext (S : pred_class) (ringS : @semiringPred R S) (kS : keyed_pred ringS).\n\nFact polyOver_mulr_closed : mulr_closed (polyOver kS).\nProof.\nsplit=> [|p q /polyOverP Sp /polyOverP Sq]; first by rewrite polyOverC rpred1.\nby apply/polyOverP=> i; rewrite coefM rpred_sum // => j _; apply: rpredM.\nQed.\nCanonical polyOver_mulrPred := MulrPred polyOver_mulr_closed.\nCanonical polyOver_semiringPred := SemiringPred polyOver_mulr_closed.\n\nLemma polyOverZ : {in kS & polyOver kS, forall c p, c *: p \\is a polyOver kS}.\nProof.\nby move=> c p Sc /polyOverP Sp; apply/polyOverP=> i; rewrite coefZ rpredM ?Sp.\nQed.\n\nLemma polyOverX : 'X \\in polyOver kS.\nProof. by rewrite qualifE polyseqX /= rpred0 rpred1. Qed.\n\nLemma rpred_horner : {in polyOver kS & kS, forall p x, p.[x] \\in kS}.\nProof.\nmove=> p x /polyOverP Sp Sx; rewrite horner_coef rpred_sum // => i _.\nby rewrite rpredM ?rpredX.\nQed.\n\nEnd PolyOverSemiring.\n\nSection PolyOverRing.\n\nContext (S : pred_class) (ringS : @subringPred R S) (kS : keyed_pred ringS).\nCanonical polyOver_smulrPred := SmulrPred (polyOver_mulr_closed kS).\nCanonical polyOver_subringPred := SubringPred (polyOver_mulr_closed kS).\n\nLemma polyOverXsubC c : ('X - c%:P \\in polyOver kS) = (c \\in kS).\nProof. by rewrite rpredBl ?polyOverX ?polyOverC. Qed.\n\nEnd PolyOverRing.\n\n(* Single derivative. *)\n\nDefinition deriv p := \\poly_(i < (size p).-1) (p`_i.+1 *+ i.+1).\n\nLocal Notation \"a ^` ()\" := (deriv a).\n\nLemma coef_deriv p i : p^`()`_i = p`_i.+1 *+ i.+1.\nProof.\nrewrite coef_poly -subn1 ltn_subRL.\nby case: leqP => // /(nth_default 0) ->; rewrite mul0rn.\nQed.\n\nLemma polyOver_deriv S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p, p^`() \\is a polyOver kS}.\nProof.\nby move=> p /polyOverP Kp; apply/polyOverP=> i; rewrite coef_deriv rpredMn ?Kp.\nQed.\n\nLemma derivC c : c%:P^`() = 0.\nProof. by apply/polyP=> i; rewrite coef_deriv coef0 coefC mul0rn. Qed.\n\nLemma derivX : ('X)^`() = 1.\nProof. by apply/polyP=> [[|i]]; rewrite coef_deriv coef1 coefX ?mul0rn. Qed.\n\nLemma derivXn n : 'X^n^`() = 'X^n.-1 *+ n.\nProof.\ncase: n => [|n]; first exact: derivC.\napply/polyP=> i; rewrite coef_deriv coefMn !coefXn eqSS.\nby case: eqP => [-> // | _]; rewrite !mul0rn.\nQed.\n\nFact deriv_is_linear : linear deriv.\nProof.\nmove=> k p q; apply/polyP=> i.\nby rewrite !(coef_deriv, coefD, coefZ) mulrnDl mulrnAr.\nQed.\nCanonical deriv_additive := Additive deriv_is_linear.\nCanonical deriv_linear := Linear deriv_is_linear.\n\nLemma deriv0 : 0^`() = 0.\nProof. exact: linear0. Qed.\n\nLemma derivD : {morph deriv : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma derivN : {morph deriv : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma derivB : {morph deriv : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma derivXsubC (a : R) : ('X - a%:P)^`() = 1.\nProof. by rewrite derivB derivX derivC subr0. Qed.\n\nLemma derivMn n p : (p *+ n)^`() = p^`() *+ n.\nProof. exact: linearMn. Qed.\n\nLemma derivMNn n p : (p *- n)^`() = p^`() *- n.\nProof. exact: linearMNn. Qed.\n\nLemma derivZ c p : (c *: p)^`() = c *: p^`().\nProof. by rewrite linearZ. Qed.\n\nLemma deriv_mulC c p : (c%:P * p)^`() = c%:P * p^`().\nProof. by rewrite !mul_polyC derivZ. Qed.\n\nLemma derivMXaddC p c : (p * 'X + c%:P)^`() = p + p^`() * 'X.\nProof.\napply/polyP=> i; rewrite raddfD /= derivC addr0 coefD !(coefMX, coef_deriv).\nby case: i; rewrite ?addr0.\nQed.\n\nLemma derivM p q : (p * q)^`() = p^`() * q + p * q^`().\nProof.\nelim/poly_ind: p => [|p b IHp]; first by rewrite !(mul0r, add0r, derivC).\nrewrite mulrDl -mulrA -commr_polyX mulrA -[_ * 'X]addr0 raddfD /= !derivMXaddC.\nby rewrite deriv_mulC IHp !mulrDl -!mulrA !commr_polyX !addrA.\nQed.\n\nDefinition derivE := Eval lazy beta delta [morphism_2 morphism_1] in\n  (derivZ, deriv_mulC, derivC, derivX, derivMXaddC, derivXsubC, derivM, derivB,\n   derivD, derivN, derivXn, derivM, derivMn).\n\n(* Iterated derivative. *)\nDefinition derivn n p := iter n deriv p.\n\nLocal Notation \"a ^` ( n )\" := (derivn n a) : ring_scope.\n\nLemma derivn0 p : p^`(0) = p.\nProof. by []. Qed.\n\nLemma derivn1 p : p^`(1) = p^`().\nProof. by []. Qed.\n\nLemma derivnS p n : p^`(n.+1) = p^`(n)^`().\nProof. by []. Qed.\n\nLemma derivSn p n : p^`(n.+1) = p^`()^`(n).\nProof. exact: iterSr. Qed.\n\nLemma coef_derivn n p i : p^`(n)`_i = p`_(n + i) *+ (n + i) ^_ n.\nProof.\nelim: n i => [|n IHn] i; first by rewrite ffactn0 mulr1n.\nby rewrite derivnS coef_deriv IHn -mulrnA ffactnSr addSnnS addKn.\nQed.\n\nLemma polyOver_derivn S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p n, p^`(n) \\is a polyOver kS}.\nProof.\nmove=> p /polyOverP Kp /= n; apply/polyOverP=> i.\nby rewrite coef_derivn rpredMn.\nQed.\n\nFact derivn_is_linear n : linear (derivn n).\nProof. by elim: n => // n IHn a p q; rewrite derivnS IHn linearP. Qed.\nCanonical derivn_additive n :=  Additive (derivn_is_linear n).\nCanonical derivn_linear n :=  Linear (derivn_is_linear n).\n\nLemma derivnC c n : c%:P^`(n) = if n == 0%N then c%:P else 0.\nProof. by case: n => // n; rewrite derivSn derivC linear0. Qed.\n\nLemma derivnD n : {morph derivn n : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma derivn_sub n : {morph derivn n : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma derivnMn n m p : (p *+ m)^`(n) = p^`(n) *+ m.\nProof. exact: linearMn. Qed.\n\nLemma derivnMNn n m p : (p *- m)^`(n) = p^`(n) *- m.\nProof. exact: linearMNn. Qed.\n\nLemma derivnN n : {morph derivn n : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma derivnZ n : scalable (derivn n).\nProof. exact: linearZZ. Qed.\n\nLemma derivnXn m n : 'X^m^`(n) = 'X^(m - n) *+ m ^_ n.\nProof.\napply/polyP=>i; rewrite coef_derivn coefMn !coefXn.\ncase: (ltnP m n) => [lt_m_n | le_m_n].\n  by rewrite eqn_leq leqNgt ltn_addr // mul0rn ffact_small.\nby rewrite -{1 3}(subnKC le_m_n) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn.\nQed.\n\nLemma derivnMXaddC n p c :\n  (p * 'X + c%:P)^`(n.+1) = p^`(n) *+ n.+1  + p^`(n.+1) * 'X.\nProof.\nelim: n => [|n IHn]; first by rewrite derivn1 derivMXaddC.\nrewrite derivnS IHn derivD derivM derivX mulr1 derivMn -!derivnS.\nby rewrite addrA addrAC -mulrSr.\nQed.\n\nLemma derivn_poly0 p n : size p <= n -> p^`(n) = 0.\nProof.\nmove=> le_p_n; apply/polyP=> i; rewrite coef_derivn.\nrewrite nth_default; first by rewrite mul0rn coef0.\nby apply: leq_trans le_p_n _; apply leq_addr.\nQed.\n\nLemma lt_size_deriv (p : {poly R}) : p != 0 -> size p^`() < size p.\nProof. by move=> /polySpred->; apply: size_poly. Qed.\n\n(* A normalising version of derivation to get the division by n! in Taylor *)\n\nDefinition nderivn n p := \\poly_(i < size p - n) (p`_(n + i) *+  'C(n + i, n)).\n\nLocal Notation \"a ^`N ( n )\" := (nderivn n a) : ring_scope.\n\nLemma coef_nderivn n p i : p^`N(n)`_i = p`_(n + i) *+  'C(n + i, n).\nProof.\nrewrite coef_poly ltn_subRL; case: leqP => // le_p_ni.\nby rewrite nth_default ?mul0rn.\nQed.\n\n(* Here is the division by n! *)\nLemma nderivn_def n p : p^`(n) = p^`N(n) *+ n`!.\nProof.\nby apply/polyP=> i; rewrite coefMn coef_nderivn coef_derivn -mulrnA bin_ffact.\nQed.\n\nLemma polyOver_nderivn S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p n, p^`N(n) \\in polyOver kS}.\nProof.\nmove=> p /polyOverP Sp /= n; apply/polyOverP=> i.\nby rewrite coef_nderivn rpredMn.\nQed.\n\nLemma nderivn0 p : p^`N(0) = p.\nProof. by rewrite -[p^`N(0)](nderivn_def 0). Qed.\n\nLemma nderivn1 p : p^`N(1) = p^`().\nProof. by rewrite -[p^`N(1)](nderivn_def 1). Qed.\n\nLemma nderivnC c n : (c%:P)^`N(n) = if n == 0%N then c%:P else 0.\nProof.\napply/polyP=> i; rewrite coef_nderivn.\nby case: n => [|n]; rewrite ?bin0 // coef0 coefC mul0rn.\nQed.\n\nLemma nderivnXn m n : 'X^m^`N(n) = 'X^(m - n) *+ 'C(m, n).\nProof.\napply/polyP=> i; rewrite coef_nderivn coefMn !coefXn.\nhave [lt_m_n | le_n_m] := ltnP m n.\n  by rewrite eqn_leq leqNgt ltn_addr // mul0rn bin_small.\nby rewrite -{1 3}(subnKC le_n_m) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn.\nQed.\n\nFact nderivn_is_linear n : linear (nderivn n).\nProof.\nmove=> k p q; apply/polyP=> i.\nby rewrite !(coef_nderivn, coefD, coefZ) mulrnDl mulrnAr.\nQed.\nCanonical nderivn_additive n := Additive(nderivn_is_linear n).\nCanonical nderivn_linear n := Linear (nderivn_is_linear n).\n\nLemma nderivnD n : {morph nderivn n : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma nderivnB n : {morph nderivn n : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma nderivnMn n m p : (p *+ m)^`N(n) = p^`N(n) *+ m.\nProof. exact: linearMn. Qed.\n\nLemma nderivnMNn n m p : (p *- m)^`N(n) = p^`N(n) *- m.\nProof. exact: linearMNn. Qed.\n\nLemma nderivnN n : {morph nderivn n : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma nderivnZ n : scalable (nderivn n).\nProof. exact: linearZZ. Qed.\n\nLemma nderivnMXaddC n p c :\n  (p * 'X + c%:P)^`N(n.+1) = p^`N(n) + p^`N(n.+1) * 'X.\nProof.\napply/polyP=> i; rewrite coef_nderivn !coefD !coefMX coefC.\nrewrite !addSn /= !coef_nderivn addr0 binS mulrnDr addrC; congr (_ + _).\nby rewrite addSnnS; case: i; rewrite // addn0 bin_small.\nQed.\n\nLemma nderivn_poly0 p n : size p <= n -> p^`N(n) = 0.\nProof.\nmove=> le_p_n; apply/polyP=> i; rewrite coef_nderivn.\nrewrite nth_default; first by rewrite mul0rn coef0.\nby apply: leq_trans le_p_n _; apply leq_addr.\nQed.\n\nLemma nderiv_taylor p x h :\n  GRing.comm x h -> p.[x + h] = \\sum_(i < size p) p^`N(i).[x] * h ^+ i.\nProof.\nmove/commrX=> cxh; elim/poly_ind: p => [|p c IHp].\n  by rewrite size_poly0 big_ord0 horner0.\nrewrite hornerMXaddC size_MXaddC.\nhave [-> | nz_p] := altP (p =P 0).\n  rewrite horner0 !simp; have [-> | _] := c =P 0; first by rewrite big_ord0.\n  by rewrite size_poly0 big_ord_recl big_ord0 nderivn0 hornerC !simp.\nrewrite big_ord_recl nderivn0 !simp hornerMXaddC addrAC; congr (_ + _).\nrewrite mulrDr {}IHp !big_distrl polySpred //= big_ord_recl /= mulr1 -addrA.\nrewrite nderivn0 /bump /(addn 1) /=; congr (_ + _).\nrewrite !big_ord_recr /= nderivnMXaddC -mulrA -exprSr -polySpred // !addrA.\ncongr (_ + _); last by rewrite (nderivn_poly0 (leqnn _)) !simp.\nrewrite addrC -big_split /=; apply: eq_bigr => i _.\nby rewrite nderivnMXaddC !hornerE_comm /= mulrDl -!mulrA -exprSr cxh.\nQed.\n\nLemma nderiv_taylor_wide n p x h :\n    GRing.comm x h -> size p <= n ->\n  p.[x + h] = \\sum_(i < n) p^`N(i).[x] * h ^+ i.\nProof.\nmove/nderiv_taylor=> -> le_p_n.\nrewrite (big_ord_widen n (fun i => p^`N(i).[x] * h ^+ i)) // big_mkcond.\napply: eq_bigr => i _; case: leqP => // /nderivn_poly0->.\nby rewrite horner0 simp.\nQed.\n\nEnd PolynomialTheory.\n\nPrenex Implicits polyC Poly lead_coef root horner polyOver.\nArguments monic {R}.\nNotation \"\\poly_ ( i < n ) E\" := (poly n (fun i => E)) : ring_scope.\nNotation \"c %:P\" := (polyC c) : ring_scope.\nNotation \"'X\" := (polyX _) : ring_scope.\nNotation \"''X^' n\" := ('X ^+ n) : ring_scope.\nNotation \"p .[ x ]\" := (horner p x) : ring_scope.\nNotation \"n .-unity_root\" := (root_of_unity n) : ring_scope.\nNotation \"n .-primitive_root\" := (primitive_root_of_unity n) : ring_scope.\nNotation \"a ^` ()\" := (deriv a) : ring_scope.\nNotation \"a ^` ( n )\" := (derivn n a) : ring_scope.\nNotation \"a ^`N ( n )\" := (nderivn n a) : ring_scope.\n\nArguments monicP [R p].\nArguments rootP [R p x].\nArguments rootPf [R p x].\nArguments rootPt [R p x].\nArguments unity_rootP [R n z].\nArguments polyOverP {R S0 addS kS p}.\n\n(* Container morphism. *)\nSection MapPoly.\n\nSection Definitions.\n\nVariables (aR rR : ringType) (f : aR -> rR).\n\nDefinition map_poly (p : {poly aR}) := \\poly_(i < size p) f p`_i.\n\n(* Alternative definition; the one above is more convenient because it lets *)\n(* us use the lemmas on \\poly, e.g., size (map_poly p) <= size p is an      *)\n(* instance of size_poly.                                                   *)\nLemma map_polyE p : map_poly p = Poly (map f p).\nProof.\nrewrite /map_poly unlock; congr Poly.\napply: (@eq_from_nth _ 0); rewrite size_mkseq ?size_map // => i lt_i_p.\nby rewrite (nth_map 0) ?nth_mkseq.\nQed.\n\nDefinition commr_rmorph u := forall x, GRing.comm u (f x).\n\nDefinition horner_morph u of commr_rmorph u := fun p => (map_poly p).[u].\n\nEnd Definitions.\n\nVariables aR rR : ringType.\n\nSection Combinatorial.\n\nVariables (iR : ringType) (f : aR -> rR).\nLocal Notation \"p ^f\" := (map_poly f p) : ring_scope.\n\nLemma map_poly0 : 0^f = 0.\nProof. by rewrite map_polyE polyseq0. Qed.\n\nLemma eq_map_poly (g : aR -> rR) : f =1 g -> map_poly f =1 map_poly g.\nProof. by move=> eq_fg p; rewrite !map_polyE (eq_map eq_fg). Qed.\n\nLemma map_poly_id g (p : {poly iR}) :\n  {in (p : seq iR), g =1 id} -> map_poly g p = p.\nProof. by move=> g_id; rewrite map_polyE map_id_in ?polyseqK. Qed.\n\nLemma coef_map_id0 p i : f 0 = 0 -> (p^f)`_i = f p`_i.\nProof.\nby move=> f0; rewrite coef_poly; case: ltnP => // le_p_i; rewrite nth_default.\nQed.\n\nLemma map_Poly_id0 s : f 0 = 0 -> (Poly s)^f = Poly (map f s).\nProof.\nmove=> f0; apply/polyP=> j; rewrite coef_map_id0 ?coef_Poly //.\nhave [/(nth_map 0 0)->// | le_s_j] := ltnP j (size s).\nby rewrite !nth_default ?size_map.\nQed.\n\nLemma map_poly_comp_id0 (g : iR -> aR) p :\n  f 0 = 0 -> map_poly (f \\o g) p = (map_poly g p)^f.\nProof. by move=> f0; rewrite map_polyE map_comp -map_Poly_id0 -?map_polyE. Qed.\n\nLemma size_map_poly_id0 p : f (lead_coef p) != 0 -> size p^f = size p.\nProof. by move=> nz_fp; apply: size_poly_eq. Qed.\n\nLemma map_poly_eq0_id0 p : f (lead_coef p) != 0 -> (p^f == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /size_map_poly_id0->. Qed.\n\nLemma lead_coef_map_id0 p :\n  f 0 = 0 -> f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p).\nProof.\nby move=> f0 nz_fp; rewrite lead_coefE coef_map_id0 ?size_map_poly_id0.\nQed.\n\nHypotheses (inj_f : injective f) (f_0 : f 0 = 0).\n\nLemma size_map_inj_poly p : size p^f = size p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite map_poly0 !size_poly0.\nby rewrite size_map_poly_id0 // -f_0 (inj_eq inj_f) lead_coef_eq0.\nQed.\n\nLemma map_inj_poly : injective (map_poly f).\nProof.\nmove=> p q /polyP eq_pq; apply/polyP=> i; apply: inj_f.\nby rewrite -!coef_map_id0 ?eq_pq.\nQed.\n\nLemma lead_coef_map_inj p : lead_coef p^f = f (lead_coef p).\nProof. by rewrite !lead_coefE size_map_inj_poly coef_map_id0. Qed.\n\nEnd Combinatorial.\n\nLemma map_polyK (f : aR -> rR) g :\n  cancel g f -> f 0 = 0 -> cancel (map_poly g) (map_poly f).\nProof.\nby move=> gK f_0 p; rewrite /= -map_poly_comp_id0 ?map_poly_id // => x _ //=.\nQed.\n\nSection Additive.\n\nVariables (iR : ringType) (f : {additive aR -> rR}).\n\nLocal Notation \"p ^f\" := (map_poly (GRing.Additive.apply f) p) : ring_scope.\n\nLemma coef_map p i : p^f`_i = f p`_i.\nProof. exact: coef_map_id0 (raddf0 f). Qed.\n\nLemma map_Poly s : (Poly s)^f = Poly (map f s).\nProof. exact: map_Poly_id0 (raddf0 f). Qed.\n\nLemma map_poly_comp (g : iR -> aR) p :\n  map_poly (f \\o g) p = map_poly f (map_poly g p).\nProof. exact: map_poly_comp_id0 (raddf0 f). Qed.\n\nFact map_poly_is_additive : additive (map_poly f).\nProof. by move=> p q; apply/polyP=> i; rewrite !(coef_map, coefB) raddfB. Qed.\nCanonical map_poly_additive := Additive map_poly_is_additive.\n\nLemma map_polyC a : (a%:P)^f = (f a)%:P.\nProof. by apply/polyP=> i; rewrite !(coef_map, coefC) -!mulrb raddfMn. Qed.\n\nLemma lead_coef_map_eq p :\n  f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p).\nProof. exact: lead_coef_map_id0 (raddf0 f). Qed.\n\nEnd Additive.\n\nVariable f : {rmorphism aR -> rR}.\nImplicit Types p : {poly aR}.\n\nLocal Notation \"p ^f\" := (map_poly (GRing.RMorphism.apply f) p) : ring_scope.\n\nFact map_poly_is_rmorphism : rmorphism (map_poly f).\nProof.\nsplit; first exact: map_poly_is_additive.\nsplit=> [p q|]; apply/polyP=> i; last first.\n  by rewrite !(coef_map, coef1) /= rmorph_nat.\nrewrite coef_map /= !coefM /= !rmorph_sum; apply: eq_bigr => j _.\nby rewrite !coef_map rmorphM.\nQed.\nCanonical map_poly_rmorphism := RMorphism map_poly_is_rmorphism.\n\nLemma map_polyZ c p : (c *: p)^f = f c *: p^f.\nProof. by apply/polyP=> i; rewrite !(coef_map, coefZ) /= rmorphM. Qed.\nCanonical map_poly_linear :=\n  AddLinear (map_polyZ : scalable_for (f \\; *:%R) (map_poly f)).\nCanonical map_poly_lrmorphism := [lrmorphism of map_poly f].\n\nLemma map_polyX : ('X)^f = 'X.\nProof. by apply/polyP=> i; rewrite coef_map !coefX /= rmorph_nat. Qed.\n\nLemma map_polyXn n : ('X^n)^f = 'X^n.\nProof. by rewrite rmorphX /= map_polyX. Qed.\n\nLemma monic_map p : p \\is monic -> p^f \\is monic.\nProof.\nmove/monicP=> mon_p; rewrite monicE.\nby rewrite lead_coef_map_eq mon_p /= rmorph1 ?oner_neq0.\nQed.\n\nLemma horner_map p x : p^f.[f x] = f p.[x].\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(rmorph0, horner0).\nrewrite hornerMXaddC !rmorphD !rmorphM /=.\nby rewrite map_polyX map_polyC hornerMXaddC IHp.\nQed.\n\nLemma map_comm_poly p x : comm_poly p x -> comm_poly p^f (f x).\nProof. by rewrite /comm_poly horner_map -!rmorphM // => ->. Qed.\n\nLemma map_comm_coef p x : comm_coef p x -> comm_coef p^f (f x).\nProof. by move=> cpx i; rewrite coef_map -!rmorphM ?cpx. Qed.\n\nLemma rmorph_root p x : root p x -> root p^f (f x).\nProof. by move/eqP=> px0; rewrite rootE horner_map px0 rmorph0. Qed.\n\nLemma rmorph_unity_root n z : n.-unity_root z -> n.-unity_root (f z).\nProof.\nmove/rmorph_root; rewrite rootE rmorphB hornerD hornerN.\nby rewrite /= map_polyXn rmorph1 hornerC hornerXn subr_eq0 unity_rootE.\nQed.\n\nSection HornerMorph.\n\nVariable u : rR.\nHypothesis cfu : commr_rmorph f u.\n\nLemma horner_morphC a : horner_morph cfu a%:P = f a.\nProof. by rewrite /horner_morph map_polyC hornerC. Qed.\n\nLemma horner_morphX : horner_morph cfu 'X = u.\nProof. by rewrite /horner_morph map_polyX hornerX. Qed.\n\nFact horner_is_lrmorphism : lrmorphism_for (f \\; *%R) (horner_morph cfu).\nProof.\nrewrite /horner_morph; split=> [|c p]; last by rewrite linearZ hornerZ.\nsplit=> [p q|]; first by rewrite /horner_morph rmorphB hornerD hornerN.\nsplit=> [p q|]; last by rewrite /horner_morph rmorph1 hornerC.\nrewrite /horner_morph rmorphM /= hornerM_comm //.\nby apply: comm_coef_poly => i; rewrite coef_map cfu.\nQed.\nCanonical horner_additive := Additive horner_is_lrmorphism.\nCanonical horner_rmorphism := RMorphism horner_is_lrmorphism.\nCanonical horner_linear := AddLinear horner_is_lrmorphism.\nCanonical horner_lrmorphism := [lrmorphism of horner_morph cfu].\n\nEnd HornerMorph.\n\nLemma deriv_map p : p^f^`() = (p^`())^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_deriv) //= rmorphMn. Qed.\n\nLemma derivn_map p n : p^f^`(n) = (p^`(n))^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_derivn) //= rmorphMn. Qed.\n\nLemma nderivn_map p n : p^f^`N(n) = (p^`N(n))^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_nderivn) //= rmorphMn. Qed.\n\nEnd MapPoly.\n\n(* Morphisms from the polynomial ring, and the initiality of polynomials  *)\n(* with respect to these.                                                 *)\nSection MorphPoly.\n\nVariable (aR rR : ringType) (pf : {rmorphism {poly aR} -> rR}).\n\nLemma poly_morphX_comm : commr_rmorph (pf \\o polyC) (pf 'X).\nProof. by move=> a; rewrite /GRing.comm /= -!rmorphM // commr_polyX. Qed.\n\nLemma poly_initial : pf =1 horner_morph poly_morphX_comm.\nProof.\napply: poly_ind => [|p a IHp]; first by rewrite !rmorph0.\nby rewrite !rmorphD !rmorphM /= -{}IHp horner_morphC ?horner_morphX.\nQed.\n\nEnd MorphPoly.\n\nNotation \"p ^:P\" := (map_poly polyC p) : ring_scope.\n\nSection PolyCompose.\n\nVariable R : ringType.\nImplicit Types p q : {poly R}.\n\nDefinition comp_poly q p := p^:P.[q].\n\nLocal Notation \"p \\Po q\" := (comp_poly q p) : ring_scope.\n\nLemma size_map_polyC p : size p^:P = size p.\nProof. exact: size_map_inj_poly (@polyC_inj R) _ _. Qed.\n\nLemma map_polyC_eq0 p : (p^:P == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 size_map_polyC. Qed.\n\nLemma root_polyC p x : root p^:P x%:P = root p x.\nProof. by rewrite rootE horner_map polyC_eq0. Qed.\n\nLemma comp_polyE p q : p \\Po q = \\sum_(i < size p) p`_i *: q^+i.\nProof.\nby rewrite [p \\Po q]horner_poly; apply: eq_bigr => i _; rewrite mul_polyC.\nQed.\n\nLemma polyOver_comp S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS &, forall p q, p \\Po q \\in polyOver kS}.\nProof.\nmove=> p q /polyOverP Sp Sq; rewrite comp_polyE rpred_sum // => i _.\nby rewrite polyOverZ ?rpredX.\nQed.\n\nLemma comp_polyCr p c : p \\Po c%:P = p.[c]%:P.\nProof. exact: horner_map. Qed.\n\nLemma comp_poly0r p : p \\Po 0 = (p`_0)%:P.\nProof. by rewrite comp_polyCr horner_coef0. Qed.\n\nLemma comp_polyC c p : c%:P \\Po p = c%:P.\nProof. by rewrite /(_ \\Po p) map_polyC hornerC. Qed.\n\nFact comp_poly_is_linear p : linear (comp_poly p).\nProof.\nmove=> a q r.\nby rewrite /comp_poly rmorphD /= map_polyZ !hornerE_comm mul_polyC.\nQed.\nCanonical comp_poly_additive p := Additive (comp_poly_is_linear p).\nCanonical comp_poly_linear p := Linear (comp_poly_is_linear p).\n\nLemma comp_poly0 p : 0 \\Po p = 0.\nProof. exact: raddf0. Qed.\n\nLemma comp_polyD p q r : (p + q) \\Po r = (p \\Po r) + (q \\Po r).\nProof. exact: raddfD. Qed.\n\nLemma comp_polyB p q r : (p - q) \\Po r = (p \\Po r) - (q \\Po r).\nProof. exact: raddfB. Qed.\n\nLemma comp_polyZ c p q : (c *: p) \\Po q = c *: (p \\Po q).\nProof. exact: linearZZ. Qed.\n\nLemma comp_polyXr p : p \\Po 'X = p.\nProof. by rewrite -{2}/(idfun p) poly_initial. Qed.\n\nLemma comp_polyX p : 'X \\Po p = p.\nProof. by rewrite /(_ \\Po p) map_polyX hornerX. Qed.\n\nLemma comp_poly_MXaddC c p q : (p * 'X + c%:P) \\Po q = (p \\Po q) * q + c%:P.\nProof.\nby rewrite /(_ \\Po q) rmorphD rmorphM /= map_polyX map_polyC hornerMXaddC.\nQed.\n\nLemma comp_polyXaddC_K p z : (p \\Po ('X + z%:P)) \\Po ('X - z%:P) = p.\nProof.\nhave addzK: ('X + z%:P) \\Po ('X - z%:P) = 'X.\n  by rewrite raddfD /= comp_polyC comp_polyX subrK.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !comp_poly0.\nrewrite comp_poly_MXaddC linearD /= comp_polyC {1}/comp_poly rmorphM /=.\nby rewrite hornerM_comm /comm_poly -!/(_ \\Po _) ?IHp ?addzK ?commr_polyX.\nQed.\n\nLemma size_comp_poly_leq p q :\n  size (p \\Po q) <= ((size p).-1 * (size q).-1).+1.\nProof.\nrewrite comp_polyE (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _.\nrewrite (leq_trans (size_scale_leq _ _)) // (leq_trans (size_exp_leq _ _)) //.\nby rewrite ltnS mulnC leq_mul // -{2}(subnKC (valP i)) leq_addr.\nQed.\n\nEnd PolyCompose.\n\nNotation \"p \\Po q\" := (comp_poly q p) : ring_scope.\n\nLemma map_comp_poly (aR rR : ringType) (f : {rmorphism aR -> rR}) p q :\n  map_poly f (p \\Po q) = map_poly f p \\Po map_poly f q.\nProof.\nelim/poly_ind: p => [|p a IHp]; first by rewrite !raddf0.\nrewrite comp_poly_MXaddC !rmorphD !rmorphM /= !map_polyC map_polyX.\nby rewrite comp_poly_MXaddC -IHp.\nQed.\n\nSection PolynomialComRing.\n\nVariable R : comRingType.\nImplicit Types p q : {poly R}.\n\nFact poly_mul_comm p q : p * q = q * p.\nProof.\napply/polyP=> i; rewrite coefM coefMr.\nby apply: eq_bigr => j _; rewrite mulrC.\nQed.\n\nCanonical poly_comRingType := Eval hnf in ComRingType {poly R} poly_mul_comm.\nCanonical polynomial_comRingType :=\n  Eval hnf in ComRingType (polynomial R) poly_mul_comm.\nCanonical poly_algType := Eval hnf in CommAlgType R {poly R}.\nCanonical polynomial_algType :=\n  Eval hnf in [algType R of polynomial R for poly_algType].\n\nLemma hornerM p q x : (p * q).[x] = p.[x] * q.[x].\nProof. by rewrite hornerM_comm //; apply: mulrC. Qed.\n\nLemma horner_exp p x n : (p ^+ n).[x] = p.[x] ^+ n.\nProof. by rewrite horner_exp_comm //; apply: mulrC. Qed.\n\nLemma horner_prod I r (P : pred I) (F : I -> {poly R}) x :\n  (\\prod_(i <- r | P i) F i).[x] = \\prod_(i <- r | P i) (F i).[x].\nProof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (hornerM, hornerC). Qed.\n\nDefinition hornerE :=\n  (hornerD, hornerN, hornerX, hornerC, horner_cons,\n   simp, hornerCM, hornerZ, hornerM).\n\nDefinition horner_eval (x : R) := horner^~ x.\nLemma horner_evalE x p : horner_eval x p = p.[x]. Proof. by []. Qed.\n\nFact horner_eval_is_lrmorphism x : lrmorphism_for *%R (horner_eval x).\nProof.\nhave cxid: commr_rmorph idfun x by apply: mulrC.\nhave evalE : horner_eval x =1 horner_morph cxid.\n  by move=> p; congr _.[x]; rewrite map_poly_id.\nsplit=> [|c p]; last by rewrite !evalE /= -linearZ.\nby do 2?split=> [p q|]; rewrite !evalE (rmorphB, rmorphM, rmorph1).\nQed.\nCanonical horner_eval_additive x := Additive (horner_eval_is_lrmorphism x).\nCanonical horner_eval_rmorphism x := RMorphism (horner_eval_is_lrmorphism x).\nCanonical horner_eval_linear x := AddLinear (horner_eval_is_lrmorphism x).\nCanonical horner_eval_lrmorphism x := [lrmorphism of horner_eval x].\n\nFact comp_poly_multiplicative q : multiplicative (comp_poly q).\nProof.\nsplit=> [p1 p2|]; last by rewrite comp_polyC.\nby rewrite /comp_poly rmorphM hornerM_comm //; apply: mulrC.\nQed.\nCanonical comp_poly_rmorphism q := AddRMorphism (comp_poly_multiplicative q).\nCanonical comp_poly_lrmorphism q := [lrmorphism of comp_poly q].\n\nLemma comp_polyM p q r : (p * q) \\Po r = (p \\Po r) * (q \\Po r).\nProof. exact: rmorphM. Qed.\n\nLemma comp_polyA p q r : p \\Po (q \\Po r) = (p \\Po q) \\Po r.\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !comp_polyC.\nby rewrite !comp_polyD !comp_polyM !comp_polyX IHp !comp_polyC.\nQed.\n\nLemma horner_comp p q x : (p \\Po q).[x] = p.[q.[x]].\nProof. by apply: polyC_inj; rewrite -!comp_polyCr comp_polyA. Qed.\n\nLemma root_comp p q x : root (p \\Po q) x = root p (q.[x]).\nProof. by rewrite !rootE horner_comp. Qed.\n\nLemma deriv_comp p q : (p \\Po q) ^`() = (p ^`() \\Po q) * q^`().\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(deriv0, comp_poly0) mul0r.\nrewrite comp_poly_MXaddC derivD derivC derivM IHp derivMXaddC comp_polyD.\nby rewrite comp_polyM comp_polyX addr0 addrC mulrAC -mulrDl.\nQed.\n\nLemma deriv_exp p n : (p ^+ n)^`() = p^`() * p ^+ n.-1 *+ n.\nProof.\nelim: n => [|n IHn]; first by rewrite expr0 mulr0n derivC.\nby rewrite exprS derivM {}IHn (mulrC p) mulrnAl -mulrA -exprSr mulrS; case n.\nQed.\n\nDefinition derivCE := (derivE, deriv_exp).\n\nEnd PolynomialComRing.\n\nSection PolynomialIdomain.\n\n(* Integral domain structure on poly *)\nVariable R : idomainType.\n\nImplicit Types (a b x y : R) (p q r m : {poly R}).\n\nLemma size_mul p q : p != 0 -> q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nby move=> nz_p nz_q; rewrite -size_proper_mul ?mulf_neq0 ?lead_coef_eq0.\nQed.\n\nFact poly_idomainAxiom p q : p * q = 0 -> (p == 0) || (q == 0).\nProof.\nmove=> pq0; apply/norP=> [[p_nz q_nz]]; move/eqP: (size_mul p_nz q_nz).\nby rewrite eq_sym pq0 size_poly0 (polySpred p_nz) (polySpred q_nz) addnS.\nQed.\n\nDefinition poly_unit : pred {poly R} :=\n  fun p => (size p == 1%N) && (p`_0 \\in GRing.unit).\n\nDefinition poly_inv p := if p \\in poly_unit then (p`_0)^-1%:P else p.\n\nFact poly_mulVp : {in poly_unit, left_inverse 1 poly_inv *%R}.\nProof.\nmove=> p Up; rewrite /poly_inv Up.\nby case/andP: Up => /size_poly1P[c _ ->]; rewrite coefC -polyC_mul => /mulVr->.\nQed.\n\nFact poly_intro_unit p q : q * p = 1 -> p \\in poly_unit.\nProof.\nmove=> pq1; apply/andP; split; last first.\n  apply/unitrP; exists q`_0.\n  by rewrite 2!mulrC -!/(coefp 0 _) -rmorphM pq1 rmorph1.\nhave: size (q * p) == 1%N by rewrite pq1 size_poly1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite mul0r size_poly0.\nrewrite size_mul // (polySpred nz_p) (polySpred nz_q) addnS addSn !eqSS.\nby rewrite addn_eq0 => /andP[].\nQed.\n\nFact poly_inv_out : {in [predC poly_unit], poly_inv =1 id}.\nProof. by rewrite /poly_inv => p /negbTE/= ->. Qed.\n\nDefinition poly_comUnitMixin :=\n  ComUnitRingMixin poly_mulVp poly_intro_unit poly_inv_out.\n\nCanonical poly_unitRingType :=\n  Eval hnf in UnitRingType {poly R} poly_comUnitMixin.\nCanonical polynomial_unitRingType :=\n  Eval hnf in [unitRingType of polynomial R for poly_unitRingType].\n\nCanonical poly_unitAlgType := Eval hnf in [unitAlgType R of {poly R}].\nCanonical polynomial_unitAlgType := Eval hnf in [unitAlgType R of polynomial R].\n\nCanonical poly_comUnitRingType := Eval hnf in [comUnitRingType of {poly R}].\nCanonical polynomial_comUnitRingType :=\n  Eval hnf in [comUnitRingType of polynomial R].\n\nCanonical poly_idomainType :=\n  Eval hnf in IdomainType {poly R} poly_idomainAxiom.\nCanonical polynomial_idomainType :=\n  Eval hnf in [idomainType of polynomial R for poly_idomainType].\n\nLemma poly_unitE p :\n  (p \\in GRing.unit) = (size p == 1%N) && (p`_0 \\in GRing.unit).\nProof. by []. Qed.\n\nLemma poly_invE p : p ^-1 = if p \\in GRing.unit then (p`_0)^-1%:P else p.\nProof. by []. Qed.\n\nLemma polyC_inv c : c%:P^-1 = (c^-1)%:P.\nProof.\nhave [/rmorphV-> // | nUc] := boolP (c \\in GRing.unit).\nby rewrite !invr_out // poly_unitE coefC (negbTE nUc) andbF.\nQed.\n\nLemma rootM p q x : root (p * q) x = root p x || root q x.\nProof. by rewrite !rootE hornerM mulf_eq0. Qed.\n\nLemma rootZ x a p : a != 0 -> root (a *: p) x = root p x.\nProof. by move=> nz_a; rewrite -mul_polyC rootM rootC (negPf nz_a). Qed.\n\nLemma size_scale a p : a != 0 -> size (a *: p) = size p.\nProof. by move/lregP/lreg_size->. Qed.\n\nLemma size_Cmul a p : a != 0 -> size (a%:P * p) = size p.\nProof. by rewrite mul_polyC => /size_scale->. Qed.\n\nLemma lead_coefM p q : lead_coef (p * q) = lead_coef p * lead_coef q.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, lead_coef0).\nhave [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, lead_coef0).\nby rewrite lead_coef_proper_mul // mulf_neq0 ?lead_coef_eq0.\nQed.\n\nLemma lead_coefZ a p : lead_coef (a *: p) = a * lead_coef p.\nProof. by rewrite -mul_polyC lead_coefM lead_coefC. Qed.\n\nLemma scale_poly_eq0 a p : (a *: p == 0) = (a == 0) || (p == 0).\nProof. by rewrite -mul_polyC mulf_eq0 polyC_eq0. Qed.\n\nLemma size_prod (I : finType) (P : pred I) (F : I -> {poly R}) :\n    (forall i, P i -> F i != 0) ->\n  size (\\prod_(i | P i) F i) = ((\\sum_(i | P i) size (F i)).+1 - #|P|)%N.\nProof.\nmove=> nzF; transitivity (\\sum_(i | P i) (size (F i)).-1).+1; last first.\n  apply: canRL (addKn _) _; rewrite addnS -sum1_card -big_split /=.\n  by congr _.+1; apply: eq_bigr => i /nzF/polySpred.\nelim/big_rec2: _ => [|i d p /nzF nzFi IHp]; first by rewrite size_poly1.\nby rewrite size_mul // -?size_poly_eq0 IHp // addnS polySpred.\nQed.\n\nLemma size_exp p n : (size (p ^+ n)).-1 = ((size p).-1 * n)%N.\nProof.\nelim: n => [|n IHn]; first by rewrite size_poly1 muln0.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite exprS mul0r size_poly0.\nrewrite exprS size_mul ?expf_neq0 // mulnS -{}IHn.\nby rewrite polySpred // [size (p ^+ n)]polySpred ?expf_neq0 ?addnS.\nQed.\n\nLemma lead_coef_exp p n : lead_coef (p ^+ n) = lead_coef p ^+ n.\nProof.\nelim: n => [|n IHn]; first by rewrite !expr0 lead_coef1.\nby rewrite !exprS lead_coefM IHn.\nQed.\n\nLemma root_prod_XsubC rs x :\n  root (\\prod_(a <- rs) ('X - a%:P)) x = (x \\in rs).\nProof.\nelim: rs => [|a rs IHrs]; first by rewrite rootE big_nil hornerC oner_eq0.\nby rewrite big_cons rootM IHrs root_XsubC.\nQed.\n\nLemma root_exp_XsubC n a x : root (('X - a%:P) ^+ n.+1) x = (x == a).\nProof. by rewrite rootE horner_exp expf_eq0 [_ == 0]root_XsubC. Qed.\n\nLemma size_comp_poly p q :\n  (size (p \\Po q)).-1 = ((size p).-1 * (size q).-1)%N.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite comp_poly0 size_poly0.\nhave [/size1_polyC-> | nc_q] := leqP (size q) 1.\n  by rewrite comp_polyCr !size_polyC -!sub1b -!subnS muln0.\nhave nz_q: q != 0 by rewrite -size_poly_eq0 -(subnKC nc_q).\nrewrite mulnC comp_polyE (polySpred nz_p) /= big_ord_recr /= addrC.\nrewrite size_addl size_scale ?lead_coef_eq0 ?size_exp //=.\nrewrite [X in _ < X]polySpred ?expf_neq0 // ltnS size_exp.\nrewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _.\nrewrite (leq_trans (size_scale_leq _ _)) // polySpred ?expf_neq0 //.\nby rewrite size_exp -(subnKC nc_q) ltn_pmul2l.\nQed.\n\nLemma size_comp_poly2 p q : size q = 2 -> size (p \\Po q) = size p.\nProof.\nhave [/size1_polyC->| p_gt1] := leqP (size p) 1; first by rewrite comp_polyC.\nmove=> lin_q; have{lin_q} sz_pq: (size (p \\Po q)).-1 = (size p).-1.\n  by rewrite size_comp_poly lin_q muln1.\nrewrite -(ltn_predK p_gt1) -sz_pq -polySpred // -size_poly_gt0 ltnW //.\nby rewrite -subn_gt0 subn1 sz_pq -subn1 subn_gt0.\nQed.\n\nLemma comp_poly2_eq0 p q : size q = 2 -> (p \\Po q == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /size_comp_poly2->. Qed.\n\nLemma lead_coef_comp p q :\n  size q > 1 -> lead_coef (p \\Po q) = lead_coef p * lead_coef q ^+ (size p).-1.\nProof.\nmove=> q_gt1; have nz_q: q != 0 by rewrite -size_poly_gt0 ltnW.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite comp_poly0 !lead_coef0 mul0r.\nrewrite comp_polyE polySpred //= big_ord_recr /= addrC -lead_coefE.\nrewrite lead_coefDl; first by rewrite lead_coefZ lead_coef_exp.\nrewrite size_scale ?lead_coef_eq0 // (polySpred (expf_neq0 _ nz_q)) ltnS.\napply/leq_sizeP=> i le_qp_i; rewrite coef_sum big1 // => j _.\nrewrite coefZ (nth_default 0 (leq_trans _ le_qp_i)) ?mulr0 //=.\nby rewrite polySpred ?expf_neq0 // !size_exp -(subnKC q_gt1) ltn_pmul2l.\nQed.\n\nTheorem max_poly_roots p rs :\n  p != 0 -> all (root p) rs -> uniq rs -> size rs < size p.\nProof.\nelim: rs p => [p pn0 _ _ | r rs ihrs p pn0] /=; first by rewrite size_poly_gt0.\ncase/andP => rpr arrs /andP [rnrs urs]; case/factor_theorem: rpr => q epq.\ncase: (altP (q =P 0)) => [q0 | ?]; first by move: pn0; rewrite epq q0 mul0r eqxx.\nhave -> : size p = (size q).+1.\n   by rewrite epq size_Mmonic ?monicXsubC // size_XsubC addnC.\nsuff /eq_in_all h : {in rs, root q =1 root p} by apply: ihrs => //; rewrite h.\nmove=> x xrs; rewrite epq rootM root_XsubC orbC; case: (altP (x =P r)) => // exr.\nby move: rnrs; rewrite -exr xrs.\nQed.\n\nEnd PolynomialIdomain.\n\nSection MapFieldPoly.\n\nVariables (F : fieldType) (R : ringType) (f : {rmorphism F -> R}).\n\nLocal Notation \"p ^f\" := (map_poly f p) : ring_scope.\n\nLemma size_map_poly p : size p^f = size p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite rmorph0 !size_poly0.\nby rewrite size_poly_eq // fmorph_eq0 // lead_coef_eq0.\nQed.\n\nLemma lead_coef_map p : lead_coef p^f = f (lead_coef p).\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !(rmorph0, lead_coef0).\nby rewrite lead_coef_map_eq // fmorph_eq0 // lead_coef_eq0.\nQed.\n\nLemma map_poly_eq0 p : (p^f == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 size_map_poly. Qed.\n\nLemma map_poly_inj : injective (map_poly f).\nProof.\nmove=> p q eqfpq; apply/eqP; rewrite -subr_eq0 -map_poly_eq0.\nby rewrite rmorphB /= eqfpq subrr.\nQed.\n\nLemma map_monic p : (p^f \\is monic) = (p \\is monic).\nProof. by rewrite monicE lead_coef_map fmorph_eq1. Qed.\n\nLemma map_poly_com p x : comm_poly p^f (f x).\nProof. exact: map_comm_poly (mulrC x _). Qed.\n\nLemma fmorph_root p x : root p^f (f x) = root p x.\nProof. by rewrite rootE horner_map // fmorph_eq0. Qed.\n\nLemma fmorph_unity_root n z : n.-unity_root (f z) = n.-unity_root z.\nProof. by rewrite !unity_rootE -(inj_eq (fmorph_inj f)) rmorphX ?rmorph1. Qed.\n\nLemma fmorph_primitive_root n z :\n  n.-primitive_root (f z) = n.-primitive_root z.\nProof.\nby congr (_ && _); apply: eq_forallb => i; rewrite fmorph_unity_root.\nQed.\n\nEnd MapFieldPoly.\n\nArguments map_poly_inj {F R} f [x1 x2].\n\nSection MaxRoots.\n\nVariable R : unitRingType.\nImplicit Types (x y : R) (rs : seq R) (p : {poly R}).\n\nDefinition diff_roots (x y : R) := (x * y == y * x) && (y - x \\in GRing.unit).\n\nFixpoint uniq_roots rs :=\n  if rs is x :: rs' then all (diff_roots x) rs' && uniq_roots rs' else true.\n\nLemma uniq_roots_prod_XsubC p rs :\n    all (root p) rs -> uniq_roots rs ->\n  exists q, p = q * \\prod_(z <- rs) ('X - z%:P).\nProof.\nelim: rs => [|z rs IHrs] /=; first by rewrite big_nil; exists p; rewrite mulr1.\ncase/andP=> rpz rprs /andP[drs urs]; case: IHrs => {urs rprs}// q def_p.\nhave [|q' def_q] := factor_theorem q z _; last first.\n  by exists q'; rewrite big_cons mulrA -def_q.\nrewrite {p}def_p in rpz.\nelim/last_ind: rs drs rpz => [|rs t IHrs] /=; first by rewrite big_nil mulr1.\nrewrite all_rcons => /andP[/andP[/eqP czt Uzt] /IHrs {IHrs}IHrs].\nrewrite -cats1 big_cat big_seq1 /= mulrA rootE hornerM_comm; last first.\n  by rewrite /comm_poly hornerXsubC mulrBl mulrBr czt.\nrewrite hornerXsubC -opprB mulrN oppr_eq0 -(mul0r (t - z)).\nby rewrite (inj_eq (mulIr Uzt)) => /IHrs.\nQed.\n\nTheorem max_ring_poly_roots p rs :\n  p != 0 -> all (root p) rs -> uniq_roots rs -> size rs < size p.\nProof.\nmove=> nz_p _ /(@uniq_roots_prod_XsubC p)[// | q def_p]; rewrite def_p in nz_p *.\nhave nz_q: q != 0 by apply: contraNneq nz_p => ->; rewrite mul0r.\nrewrite size_Mmonic ?monic_prod_XsubC // (polySpred nz_q) addSn /=.\nby rewrite size_prod_XsubC leq_addl.\nQed.\n\nLemma all_roots_prod_XsubC p rs :\n    size p = (size rs).+1 -> all (root p) rs -> uniq_roots rs ->\n  p = lead_coef p *: \\prod_(z <- rs) ('X - z%:P).\nProof.\nmove=> size_p /uniq_roots_prod_XsubC def_p Urs.\ncase/def_p: Urs => q -> {p def_p} in size_p *.\nhave [q0 | nz_q] := eqVneq q 0; first by rewrite q0 mul0r size_poly0 in size_p.\nhave{q nz_q size_p} /size_poly1P[c _ ->]: size q == 1%N.\n  rewrite -(eqn_add2r (size rs)) add1n -size_p.\n  by rewrite size_Mmonic ?monic_prod_XsubC // size_prod_XsubC addnS.\nby rewrite lead_coef_Mmonic ?monic_prod_XsubC // lead_coefC mul_polyC.\nQed.\n\nEnd MaxRoots.\n\nSection FieldRoots.\n\nVariable F : fieldType.\nImplicit Types (p : {poly F}) (rs : seq F).\n\nLemma poly2_root p : size p = 2 -> {r | root p r}.\nProof.\ncase: p => [[|p0 [|p1 []]] //= nz_p1]; exists (- p0 / p1).\nby rewrite /root addr_eq0 /= mul0r add0r mulrC divfK ?opprK.\nQed.\n\nLemma uniq_rootsE rs : uniq_roots rs = uniq rs.\nProof.\nelim: rs => //= r rs ->; congr (_ && _); rewrite -has_pred1 -all_predC.\nby apply: eq_all => t; rewrite /diff_roots mulrC eqxx unitfE subr_eq0.\nQed.\n\nSection UnityRoots.\n\nVariable n : nat.\n\nLemma max_unity_roots rs :\n  n > 0 -> all n.-unity_root rs -> uniq rs -> size rs <= n.\nProof.\nmove=> n_gt0 rs_n_1 Urs; have szPn := size_Xn_sub_1 F n_gt0.\nby rewrite -ltnS -szPn max_poly_roots -?size_poly_eq0 ?szPn.\nQed.\n\nLemma mem_unity_roots rs :\n    n > 0 -> all n.-unity_root rs -> uniq rs -> size rs = n ->\n  n.-unity_root =i rs.\nProof.\nmove=> n_gt0 rs_n_1 Urs sz_rs_n x; rewrite -topredE /=.\napply/idP/idP=> xn1; last exact: (allP rs_n_1).\napply: contraFT (ltnn n) => not_rs_x.\nby rewrite -{1}sz_rs_n (@max_unity_roots (x :: rs)) //= ?xn1 ?not_rs_x.\nQed.\n\n(* Showing the existence of a primitive root requires the theory in cyclic. *)\n\nVariable z : F.\nHypothesis prim_z : n.-primitive_root z.\n\nLet zn := [seq z ^+ i | i <- index_iota 0 n].\n\nLemma factor_Xn_sub_1 : \\prod_(0 <= i < n) ('X - (z ^+ i)%:P) = 'X^n - 1.\nProof.\ntransitivity (\\prod_(w <- zn) ('X - w%:P)); first by rewrite big_map.\nhave n_gt0: n > 0 := prim_order_gt0 prim_z.\nrewrite (@all_roots_prod_XsubC _ ('X^n - 1) zn); first 1 last.\n- by rewrite size_Xn_sub_1 // size_map size_iota subn0.\n- apply/allP=> _ /mapP[i _ ->] /=; rewrite rootE !hornerE hornerXn.\n  by rewrite exprAC (prim_expr_order prim_z) expr1n subrr.\n- rewrite uniq_rootsE map_inj_in_uniq ?iota_uniq // => i j.\n  rewrite !mem_index_iota => ltin ltjn /eqP.\n  by rewrite (eq_prim_root_expr prim_z) !modn_small // => /eqP.\nby rewrite (monicP (monic_Xn_sub_1 F n_gt0)) scale1r.\nQed.\n\nLemma prim_rootP x : x ^+ n = 1 -> {i : 'I_n | x = z ^+ i}.\nProof.\nmove=> xn1; pose logx := [pred i : 'I_n | x == z ^+ i].\ncase: (pickP logx) => [i /eqP-> | no_i]; first by exists i.\ncase: notF; suffices{no_i}: x \\in zn.\n  case/mapP=> i; rewrite mem_index_iota => lt_i_n def_x.\n  by rewrite -(no_i (Ordinal lt_i_n)) /= -def_x.\nrewrite -root_prod_XsubC big_map factor_Xn_sub_1.\nby rewrite [root _ x]unity_rootE xn1.\nQed.\n\nEnd UnityRoots.\n\nEnd FieldRoots.\n\nSection MapPolyRoots.\n\nVariables (F : fieldType) (R : unitRingType) (f : {rmorphism F -> R}).\n\nLemma map_diff_roots x y : diff_roots (f x) (f y) = (x != y).\nProof.\nrewrite /diff_roots -rmorphB // fmorph_unit // subr_eq0 //.\nby rewrite rmorph_comm // eqxx eq_sym.\nQed.\n\nLemma map_uniq_roots s : uniq_roots (map f s) = uniq s.\nProof.\nelim: s => //= x s ->; congr (_ && _); elim: s => //= y s ->.\nby rewrite map_diff_roots -negb_or.\nQed.\n\nEnd MapPolyRoots.\n\nSection AutPolyRoot.\n(* The action of automorphisms on roots of unity. *)\n\nVariable F : fieldType.\nImplicit Types u v : {rmorphism F -> F}.\n\nLemma aut_prim_rootP u z n :\n  n.-primitive_root z -> {k | coprime k n & u z = z ^+ k}.\nProof.\nmove=> prim_z; have:= prim_z; rewrite -(fmorph_primitive_root u) => prim_uz.\nhave [[k _] /= def_uz] := prim_rootP prim_z (prim_expr_order prim_uz).\nby exists k; rewrite // -(prim_root_exp_coprime _ prim_z) -def_uz.\nQed.\n\nLemma aut_unity_rootP u z n : n > 0 -> z ^+ n = 1 -> {k | u z = z ^+ k}.\nProof.\nby move=> _ /prim_order_exists[// | m /(aut_prim_rootP u)[k]]; exists k.\nQed.\n\nLemma aut_unity_rootC u v z n : n > 0 -> z ^+ n = 1 -> u (v z) = v (u z).\nProof.\nmove=> n_gt0 /(aut_unity_rootP _ n_gt0) def_z.\nhave [[i def_uz] [j def_vz]] := (def_z u, def_z v).\nby rewrite !(def_uz, def_vz, rmorphX) exprAC.\nQed.\n\nEnd AutPolyRoot.\n\nModule UnityRootTheory.\n\nNotation \"n .-unity_root\" := (root_of_unity n) : unity_root_scope.\nNotation \"n .-primitive_root\" := (primitive_root_of_unity n) : unity_root_scope.\nOpen Scope unity_root_scope.\n\nDefinition unity_rootE := unity_rootE.\nDefinition unity_rootP := @unity_rootP.\nArguments unity_rootP [R n z].\n\nDefinition prim_order_exists := prim_order_exists.\nNotation prim_order_gt0 :=  prim_order_gt0.\nNotation prim_expr_order := prim_expr_order.\nDefinition prim_expr_mod := prim_expr_mod.\nDefinition prim_order_dvd := prim_order_dvd.\nDefinition eq_prim_root_expr := eq_prim_root_expr.\n\nDefinition rmorph_unity_root := rmorph_unity_root.\nDefinition fmorph_unity_root := fmorph_unity_root.\nDefinition fmorph_primitive_root := fmorph_primitive_root.\nDefinition max_unity_roots := max_unity_roots.\nDefinition mem_unity_roots := mem_unity_roots.\nDefinition prim_rootP := prim_rootP.\n\nEnd UnityRootTheory.\n\nSection DecField.\n\nVariable F : decFieldType.\n\nLemma dec_factor_theorem (p : {poly F}) :\n  {s : seq F & {q : {poly F} | p = q * \\prod_(x <- s) ('X - x%:P)\n                             /\\ (q != 0 -> forall x, ~~ root q x)}}.\nProof.\npose polyT (p : seq F) := (foldr (fun c f => f * 'X_0 + c%:T) (0%R)%:T p)%T.\nhave eval_polyT (q : {poly F}) x : GRing.eval [:: x] (polyT q) = q.[x].\n  by rewrite /horner; elim: (val q) => //= ? ? ->.\nelim: size {-2}p (leqnn (size p)) => {p} [p|n IHn p].\n  by move=> /size_poly_leq0P->; exists [::], 0; rewrite mul0r eqxx.\nhave /decPcases /= := @satP F [::] ('exists 'X_0, polyT p == 0%T).\ncase: ifP => [_ /sig_eqW[x]|_ noroot]; last first.\n  exists [::], p; rewrite big_nil mulr1; split => // p_neq0 x.\n  by apply/negP=> /rootP rpx; apply noroot; exists x; rewrite eval_polyT.\nrewrite eval_polyT => /rootP /factor_theorem /sig_eqW [q ->].\nhave [->|q_neq0] := eqVneq q 0; first by exists [::], 0; rewrite !mul0r eqxx.\nrewrite size_mul ?polyXsubC_eq0 // ?size_XsubC addn2 /= ltnS => sq_le_n.\nhave [] // := IHn q => s [r [-> nr]]; exists (s ++ [::x]), r.\nby rewrite big_cat /= big_seq1 mulrA.\nQed.\n\nEnd DecField.\n\nModule PreClosedField.\nSection UseAxiom.\n\nVariable F : fieldType.\nHypothesis closedF : GRing.ClosedField.axiom F.\nImplicit Type p : {poly F}.\n\nLemma closed_rootP p : reflect (exists x, root p x) (size p != 1%N).\nProof.\nhave [-> | nz_p] := eqVneq p 0.\n  by rewrite size_poly0; left; exists 0; rewrite root0.\nrewrite neq_ltn {1}polySpred //=.\napply: (iffP idP) => [p_gt1 | [a]]; last exact: root_size_gt1.\npose n := (size p).-1; have n_gt0: n > 0 by rewrite -ltnS -polySpred.\nhave [a Dan] := closedF (fun i => - p`_i / lead_coef p) n_gt0.\nexists a; apply/rootP; rewrite horner_coef polySpred // big_ord_recr /= -/n.\nrewrite {}Dan mulr_sumr -big_split big1 //= => i _.\nby rewrite -!mulrA mulrCA mulNr mulVKf ?subrr ?lead_coef_eq0.\nQed.\n\nLemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0).\nProof.\napply: (iffP idP) => [nz_p | [x]]; last first.\n  by apply: contraNneq => ->; apply: root0.\nhave [[x /rootP p1x0]|] := altP (closed_rootP (p - 1)).\n  by exists x; rewrite -[p](subrK 1) /root hornerD p1x0 add0r hornerC oner_eq0.\nrewrite negbK => /size_poly1P[c _ /(canRL (subrK 1)) Dp].\nby exists 0; rewrite Dp -raddfD polyC_eq0 rootC in nz_p *.\nQed.\n\nEnd UseAxiom.\nEnd PreClosedField.\n\nSection ClosedField.\n\nVariable F : closedFieldType.\nImplicit Type p : {poly F}.\n\nLet closedF := @solve_monicpoly F.\n\nLemma closed_rootP p : reflect (exists x, root p x) (size p != 1%N).\nProof. exact: PreClosedField.closed_rootP. Qed.\n\nLemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0).\nProof. exact: PreClosedField.closed_nonrootP. Qed.\n\nLemma closed_field_poly_normal p :\n  {r : seq F | p = lead_coef p *: \\prod_(z <- r) ('X - z%:P)}.\nProof.\napply: sig_eqW; have [r [q [->]]] /= := dec_factor_theorem p.\nhave [->|] := altP eqP; first by exists [::]; rewrite mul0r lead_coef0 scale0r.\nhave [[x rqx ? /(_ isT x) /negP /(_ rqx)] //|] := altP (closed_rootP q).\nrewrite negbK => /size_poly1P [c c_neq0-> _ _]; exists r.\nrewrite mul_polyC lead_coefZ (monicP _) ?mulr1 //.\nby rewrite monic_prod => // i; rewrite monicXsubC.\nQed.\n\nEnd ClosedField.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-mathcomp/mathcomp/algebra/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7459822384862469}}
{"text": "Inductive bool:Type:=\n|true : bool\n|false : bool.\n\nDefinition not(x:bool):bool:=\nmatch x with\n|true => false\n|false => true\nend.\n\nDefinition and(x y : bool):bool:=\nmatch x with\n|true => y\n|false => false\nend.\n\nTheorem not_not: forall x:bool, not(not x) = x.\nProof.\nintros.\ndestruct x.\nsimpl. reflexivity.\nsimpl. reflexivity.\nQed.\n\nEval compute in (not_not false).\n\nEval compute in (and true false).", "meta": {"author": "psjyothiprasad", "repo": "Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "sha": "bda5df849ce973def8aa145660aa806e7743af35", "save_path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography/Software-Modelling---Theorem-Provers---Program-Verification---Cryptography-bda5df849ce973def8aa145660aa806e7743af35/notNot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7458776902089718}}
{"text": "Theorem left_or : (forall A B : Prop, A -> A \\/ B).\nProof.\n  intros A B.\n  intros proof_A.\n  pose (proof_A_or_B := or_introl proof_A : A \\/ B).\n  exact proof_A_or_B.\nQed.\n\nTheorem right_or : (forall A B : Prop, B -> A \\/ B).\nProof.\n  intros A B.\n  intros proof_B.\n  pose (proof_A_or_B := or_intror proof_B : A \\/ B).\n  exact proof_A_or_B.\nQed.\n\nTheorem alternative_right_or : (forall A B : Prop, B -> A \\/ B).\nProof.\n  intros A B.\n  intros proof_B.\n  refine (or_intror _).\n    exact proof_B.\nQed.\n\nTheorem or_commutes : (forall A B : Prop, A \\/ B -> B \\/ A).\nProof.\n  intros A B.\n  intros A_or_B.\n  case A_or_B.\n    (* suppose a is true *)\n    intros proof_A.\n    refine (or_intror _).\n      exact proof_A.\n    (* suppose b us true *)\n    intros proof_B.\n    refine (or_introl _).\n      exact proof_B.\nQed.", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/basic/or.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7458776850767109}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus (mult x y) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj257_coqofml_67utjJ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7458776782336958}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) : natural :=\n  plus lf2 (Succ lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj122_coqofml_PFRULy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7458569846172003}}
{"text": "From LF Require Export Basics.\n\nTheorem add_0_r: forall n : nat,\n    n + 0 = n.\nProof.\n    intros n. induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem minus_n_n: forall n : nat, \n    n - n = 0.\nProof.\n    intros n. induction n as [|n' IHn'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem mul_0_r : forall n:nat, \n    n * 0 = 0.\nProof.\n    intros n. induction n as [| n' IHn'].\n    - simpl. 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. induction n as [| n' IHn'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem add_comm : forall n m : nat, \n    n + m = m + n.\nProof.\n    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\nTheorem add_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) : nat :=\n    match n with\n    | 0 => 0\n    | S n' => S (S (double n'))\n    end.\n\nLemma double_plus: forall n, \n    double n = n + n.\nProof.\n    intros n. induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl. rewrite <- plus_n_Sm. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem even_S: forall n : nat, \n    even (S n) = negb (even n).\nProof.\n    intros n. induction n as [| n' IHn'].\n    - reflexivity.\n    - rewrite -> IHn'. rewrite -> negb_involutive. reflexivity.\nQed.\n\n\nTheorem add_shuffle3: forall n m p : nat, n + (m + p) = m + (n + p).\nProof.\n    intros n m p.\n    rewrite -> add_assoc.\n    rewrite -> add_assoc.\n    assert (H: n + m = m + n). {\n        rewrite -> add_comm.\n        reflexivity.\n    }\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem S_add: forall n m : nat,\n    n = m -> S n = S m.\nProof.\n    intros n m. induction n as [| n IHn'].\n    - intros H. rewrite <- H. reflexivity.\n    - intros H. rewrite -> H. reflexivity.\nQed.\n\n\nTheorem mul_n_Sm: forall n m : nat,\n    n + n * m = n * (S m).\nProof.\n    intros n m. induction n as [| n' IHn'].\n    - reflexivity.\n    - simpl. rewrite -> add_shuffle3. rewrite -> IHn'. reflexivity.\nQed.\n\n\nTheorem mul_comm : forall m n : nat,\n    m * n = n * m.\nProof.\n    intros m n. induction m as [| m' IHm'].\n    - rewrite -> mul_0_r. reflexivity. \n    - simpl. \n        rewrite -> IHm'.\n        rewrite -> mul_n_Sm.\n        reflexivity.\nQed.\n\n(* Exercise: 2 stars, standard, optional (eqb_refl) *)\nTheorem eqb_refl : forall n : nat,\n    (n =? n) = true.\nProof.\n    intros n. induction n as [|n' IHn'].\n    - reflexivity.\n    - simpl. rewrite IHn'. reflexivity.\nQed.\n\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    rewrite -> add_assoc.\n    replace (n + m) with (m + n).\n    - reflexivity.\n    - rewrite -> add_comm. reflexivity.\nQed.\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. induction b as [| b0 IHb0| b1 IHb1].\n    - reflexivity.\n    - simpl. reflexivity.\n    - simpl. \n        rewrite -> IHb1.\n        rewrite -> add_0_r.\n        rewrite -> add_0_r.\n        rewrite <- plus_1_l.\n        rewrite -> add_shuffle3.\n        reflexivity.\nQed.\n\nFixpoint nat_to_bin (n : nat) : bin :=\n    match n with\n    | 0 => 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 as [| n' IHn'].\n    - reflexivity.\n    - simpl. \n        rewrite -> bin_to_nat_pres_incr. \n        rewrite -> IHn'. \n        reflexivity.\nQed.\n\n(* No idea what is going on here. :(\n\nTheorem bin_nat_bin: forall b : bin,\n    nat_to_bin (bin_to_nat b) = b.\nProof.\n    intros b. induction b as [| b0 IHb0 | b1 IHb1].\n    - reflexivity.\n    - simpl. rewrite -> add_0_r.\nQed.\n\n\nFixpoint normalize (b : bin) : bin :=\n    match b with\n    | Z => .\n*)", "meta": {"author": "luisholanda", "repo": "software-foundations", "sha": "a9c5d7ddb3dca0465dee4ca8519b5de971e482de", "save_path": "github-repos/coq/luisholanda-software-foundations", "path": "github-repos/coq/luisholanda-software-foundations/software-foundations-a9c5d7ddb3dca0465dee4ca8519b5de971e482de/Volume1/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7458499202419469}}
{"text": "From mathcomp\n Require Import ssreflect.\n\nSection ModusPonens.\nVariable X Y : Prop.\n\nHypothesis XtoY_is_true : X -> Y.\nHypothesis X_is_true : X.\n\nTheorem MP : Y.\nProof.\n\nmove: X_is_true.\nby [].\nQed.\n\nEnd ModusPonens.\n\nSection HilbertSAxiom.\nVariables A B C : Prop.\n\nTheorem HS1 : (A -> (B -> C)) -> ((A -> B) -> (A -> C)).\nProof.\nmove=> AtoBtoC_is_true.\nmove=> AtoB_is_true.\nmove=> A_is_true.\n\napply: (MP B C).\n\napply: (MP A (B -> C)).\nby [].\nby [].\n\napply: (MP A B).\nby [].\nby [].\nQed.\n\nEnd HilbertSAxiom.\n\n", "meta": {"author": "elkel53930", "repo": "LearningCoq", "sha": "b209b86b07697b1d097c7fa78bcf4357af7aaeae", "save_path": "github-repos/coq/elkel53930-LearningCoq", "path": "github-repos/coq/elkel53930-LearningCoq/LearningCoq-b209b86b07697b1d097c7fa78bcf4357af7aaeae/HilbertSAxiom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7458499202419467}}
{"text": "\nRequire Export Relations.\n\n\n\n(*\nInductive nat : Set :=\n  | zero : nat\n  | succ : nat -> nat.\n*)\n\nInductive succR : nat -> nat -> Prop :=\n  | s1 : (forall a b : nat, S a = b -> succR a b).\n\nInductive immediatePredR : nat -> nat -> Prop :=\n  | p0 : (forall a b, succR a b -> immediatePredR b a)\n  | pi : (forall a b, forall c, immediatePredR b c -> succR a c\n                                -> immediatePredR b a).\n\nExample ex1 : immediatePredR 5 3.\nProof.\n  apply pi with (c:=4).\n  apply p0.\n  apply s1.\n  reflexivity.\n  apply s1.\n  reflexivity.\nQed.\n\n(* Peano's Axioms *)\n\nTheorem thm3 : forall a b, S a = S b -> a = b.\nProof.\n  intros.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem thm4 : forall a, ~(S a = 0).\nProof.\n  intros. intro.\n  inversion H.\nQed.\n\nTheorem thm5 : forall (p : nat -> Prop), p 0\n                                         -> (forall n, p n -> p (S n))\n                                         -> (forall n, p n).\nProof.\n  intros.\n  induction n.\n  (* n = 0 *)\n  assumption.\n  (* n = S n *)\n  apply H0.\n  assumption.\nQed.\n(* Prooving inductivity with inductive assumption is actually meaningless.\n   So they're just demonstrations *)\n\n\n(* page 25:\nA property is called “R-hereditary” when, if it belongs to a term x, and x\nhas the relation R to y, then it belongs to y.\n*)\nDefinition r_hereditary {X} (R : relation X) (p : X -> Prop) : Prop :=\n  forall x y, p x -> R x y -> p y.\n\n(*\nA term x is said to be an “R-ancestor” of the term y if y has every\nR-hereditary property that x has, provided x is a term which has the\nrelation R to something or to which something has the relation R.\n(This is only to exclude trivial cases.)\n*)\n\nDefinition r_ancestor {X} (R : relation X) (x : X) (y : X) :=\n  forall (p : X -> Prop), r_hereditary R p -> p x -> p y.\n\n(* My own understandings *)\nExample __ex1 : r_hereditary lt (fun x => x > 0).\nProof.\n  unfold r_hereditary.\n  unfold lt.\n  intros.\n  induction H0.\n  induction H. constructor. constructor.\n  constructor. apply IHle.\n  constructor. apply IHle.\nQed.\n\nExample __ex2 : r_ancestor lt 3 5.\nProof.\n  unfold r_ancestor.\n  unfold r_hereditary.\n  intros.\n  apply H with 3.\n  assumption. auto.\nQed.\n\n\n(* page 26:\nThe “R-posterity” of x is all the terms of which x is an R-ancestor.\n*)\n\nDefinition r_posterity {X} (R : relation X) (x : X) (y : X) := r_ancestor R y x.\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/imp/Chap3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7458299668306503}}
{"text": "Require Import ZArith List.\nRequire Import Lia.\nOpen Scope Z_scope.\nOpen Scope list_scope.\n\nInductive ext_Z :Type :=\n  cZ : Z -> ext_Z | minfty : ext_Z | pinfty : ext_Z.\n\nDefinition bot := (minfty, pinfty).\nDefinition comp_add (x y:ext_Z) : ext_Z :=\n  match x,y with\n    minfty, _ => minfty\n  | _, minfty => minfty\n  | pinfty, _ => pinfty\n  | _, pinfty => pinfty\n  | cZ x, cZ y => cZ(x+y)\n  end.\n\nDefinition plus (i1 i2:ext_Z*ext_Z) : ext_Z*ext_Z :=\n  let (l1,u1) := i1 in  let (l2,u2) := i2 in (comp_add l1 l2, comp_add u1 u2).\n\nDefinition of_int (x:Z) := (cZ x, cZ x).\n\n(* compute the minimum of two ext_Z *)\nDefinition cp_min (n1 n2:ext_Z) : ext_Z :=\n  match n1, n2 with\n    minfty, a => minfty\n  | cZ n1, cZ n2 => cZ (Z.min n1 n2)\n  | _, minfty => minfty\n  | a, pinfty => a\n  | pinfty, a => a\n  end.\n\n(* compute the maximum of two ext_Z *)\nDefinition cp_max (n1 n2:ext_Z) : ext_Z :=\n  match n1, n2 with\n    minfty, a => a\n  | cZ n1, cZ n2 => cZ (Z.max n1 n2)\n  | a, minfty => a\n  | pinfty, _ => pinfty\n  | a, pinfty => pinfty\n  end.\n\nLemma Zle_to_Zmin : forall n m, n <= m -> Z.min n m = n.\nintros n n'; unfold Z.min, Z.le.\ncase (n?=n'); intuition.\nQed.\n\nLemma Zle_to_Zmax : forall n m, m <= n -> Z.max n m = n.\nintros n n'; unfold Z.max.\nintros Hle; cut (n >= n').\nunfold Z.ge.\ncase_eq (n ?= n'); intros Heq H; try (elim H; auto; fail).\nrewrite Zcompare_Eq_eq with (1:=Heq); auto.\nauto.\nlia.\nQed.\n\nLemma cp_min_assoc :\n  forall a b c, cp_min (cp_min a b) c = cp_min a (cp_min b c).\nintros [a | | ]; simpl; auto; intros [b | |]; simpl; auto; intros [c| |]; simpl; auto.\nrewrite Z.min_assoc; auto.\nQed.\n\nLemma cp_max_assoc :\n  forall a b c, cp_max (cp_max a b) c = cp_max a (cp_max b c).\nintros [a | | ]; simpl; auto; intros [b | |]; simpl; auto; intros [c| |]; simpl; auto.\nrewrite Z.max_assoc; auto.\nQed.\n\nLemma cp_max_r_cp_min_l :\n  forall a b, cp_max a b = b -> cp_min a b = a.\nintros [a | | ][b | | ]; simpl; auto.\nintros H; injection H; intros H1.\nassert (a <= b) by (rewrite <- H1; apply Z.le_max_l).\nrewrite Zle_to_Zmin; auto.\nQed.\n\nLemma cp_min_r_cp_max_l :\n  forall a b, cp_min a b = b -> cp_max a b = a.\nintros [a | | ][b | | ]; simpl; auto.\nintros H; injection H; intros H1.\nassert (b <= a) by (rewrite <- H1; apply Z.le_min_l).\nrewrite Zle_to_Zmax; auto.\nQed.\n\nDefinition join (i1 i2:ext_Z*ext_Z) : ext_Z*ext_Z :=\n  let (l1, u1):= i1 in let (l2, u2) := i2 in (cp_min l1 l2, cp_max u1 u2).\n\nDefinition ext_eq : forall a b:ext_Z, {a=b}+{a<>b}.\nintros a b; destruct a as [na | | ]; destruct b as [nb | | ];\ntry (left; apply refl_equal); try (right; discriminate).\ncase (Z.eq_dec na nb); intros Heq; (left; rewrite Heq; apply refl_equal) ||\n (right; intros H'; elim Heq; injection H'; auto).\nDefined.\n\nDefinition add_test_constraint_right (d:bool) (i j:ext_Z*ext_Z) : option (ext_Z*ext_Z) :=\n  let (bi, ui):=i in let (bj, uj):=j in\n  (if d then\n    let ujm1 := comp_add uj (cZ (-1)) in\n    if ext_eq bi (cp_max bi uj) then None\n    else Some (bi, cp_min ui ujm1)\n  else\n    let v := cp_max ui bj in\n    if ext_eq bj v then\n      if ext_eq ui v then Some(cp_max bi bj,ui)\n      else None\n    else Some (cp_max bi bj, ui)).\n\nDefinition add_test_constraint_left (d:bool) (i j:ext_Z*ext_Z) : option (ext_Z*ext_Z) :=\n  let (bi, ui):=i in let (bj, uj):=j in\n  (if d then\n    let bip1 := comp_add bi (cZ 1) in\n    if ext_eq uj (cp_min bi uj) then None\n    else Some (cp_max bip1 bj, uj)\n  else\n    let v := cp_max ui bj in\n    if ext_eq bj v then\n      if ext_eq ui v then Some(bj,cp_min ui uj)\n      else None\n    else Some (bj, cp_min ui uj)).\n\nDefinition widen (i j:ext_Z*ext_Z) :=\n  let (bi, ui) := i in let (bj, uj) := j in\n  let b :=\n    if ext_eq (cp_min bi bj) bi then bi\n    else minfty in\n  let u :=\n    if ext_eq (cp_max ui uj) ui then ui\n    else pinfty in\n    (b,u).\n\nDefinition eq (i j:ext_Z*ext_Z) : bool :=\n  let (bi,ui) := i in let (bj,uj) := j in\n  if ext_eq bi bj then if ext_eq ui uj then true else false else false.\n\nDefinition thinner (i j : ext_Z*ext_Z) : Prop :=\n   let (bi,ui) := i in let (bj,uj) := j in\n   cp_min bi bj = bj /\\ cp_max ui uj = uj.\n\nLemma cp_min_comm : forall i j, cp_min i j = cp_min j i.\nintros [ni | | ] [nj | | ];simpl; auto.\nrewrite Z.min_comm; auto.\nQed.\n\nLemma cp_max_comm :\n   forall x y, cp_max x y = cp_max y x.\nProof.\nintros [x | | ] [y | | ]; simpl; auto.\nrewrite Z.max_comm; auto.\nQed.\n\nLemma thinner_refl : forall v, thinner v v.\nintros [[b | | ] [u| |]]; simpl; auto;\n  try rewrite Zmax_idempotent; try rewrite Zmin_idempotent; auto.\nQed.\n\nLemma cp_min_trans :\n  forall x y z, cp_min x y = x -> cp_min y z = y -> cp_min x z = x.\nintros [x | | ] [y| |]; try (simpl; intros; discriminate);\nintros [z | | ]; try(simpl; intros; discriminate); simpl; auto.\nintros H1 H2; injection H1; injection H2; intros H3 H4.\nrewrite Zle_to_Zmin; auto.\napply Z.le_trans with y.\nrewrite <-H4; auto with zarith.\nrewrite <- H3; auto with zarith.\nQed.\n\nLemma cp_max_trans :\n  forall x y z, cp_max x y = x -> cp_max y z = y -> cp_max x z = x.\nintros [x | | ] [y| |]; try (simpl; intros; discriminate);\nintros [z | | ]; try(simpl; intros; discriminate); simpl; auto.\nintros H1 H2; injection H1; injection H2; intros H3 H4.\nrewrite Zle_to_Zmax; auto.\napply Z.le_trans with y.\nrewrite <- H3; apply Z.le_max_r.\nrewrite <-H4; apply Z.le_max_r.\nQed.\n\nLemma thinner_trans : forall v1 v2 v3, thinner v1 v2 ->\n thinner v2 v3 -> thinner v1 v3.\nunfold thinner; intros [b1 u1] [b2 u2] [b3 u3] [H1 H2] [H3 H4].\nsplit.\nrewrite cp_min_comm; apply cp_min_trans with b2; rewrite cp_min_comm; auto.\nrewrite cp_max_comm; apply cp_max_trans with u2; rewrite cp_max_comm; auto.\nQed.\n\nLemma thinner_bot : forall v, thinner v bot.\nunfold bot; intros [[a | | ][b | | ]]; unfold thinner; simpl; auto.\nQed.\n\nLemma cp_min_plus :\n  forall x y z t,\n    cp_min x y = x -> cp_min z t = z ->\n    cp_min (comp_add x z)(comp_add y t)= comp_add x z.\nintros [x | | ] [y | | ];simpl;try (intros;discriminate);\nintros [z | | ] [t' | | ];simpl; try (intros; discriminate); auto.\nintros H1 H2; injection H1; injection H2; intros H4 H3.\napply f_equal with (f:=cZ); apply Zle_to_Zmin.\napply Z.le_trans with (x + t').\napply Zplus_le_compat_l; rewrite <- H4; apply Z.le_min_r.\napply Zplus_le_compat_r; rewrite <- H3; apply Z.le_min_r.\nQed.\n\nLemma cp_max_plus :\n  forall x y z t,\n    cp_max x y = x -> cp_max z t = z ->\n    cp_max (comp_add x z)(comp_add y t)= comp_add x z.\nintros [x | | ] [y | | ];simpl;try (intros;discriminate);\nintros [z | | ] [t' | | ];simpl; try (intros; discriminate); auto.\nintros H1 H2; injection H1; injection H2; intros H4 H3.\napply f_equal with (f:=cZ); apply Zle_to_Zmax.\napply Z.le_trans with (x + t').\napply Zplus_le_compat_r; rewrite <- H3; apply Z.le_max_r.\napply Zplus_le_compat_l; rewrite <- H4; apply Z.le_max_r.\nQed.\n\nLemma thinner_plus :\n   forall x y z t, thinner x y -> thinner z t ->\n     thinner (plus x z)(plus y t).\nintros [lx ux] [ly uy] [lz uz] [lt' ut] [H1 H2][H3 H4]; split; simpl.\nrewrite cp_min_comm; apply cp_min_plus; rewrite cp_min_comm; auto.\nrewrite cp_max_comm; apply cp_max_plus; rewrite cp_max_comm; auto.\nQed.\n\nLemma cp_max_refl : forall x, cp_max x x = x.\nintros [x | | ]; simpl; unfold Z.max; auto.\nrewrite Z.compare_refl; auto.\nQed.\n\nLemma cp_min_refl : forall x, cp_min x x = x.\nintros [x | | ]; simpl; unfold Z.min; auto.\nrewrite Z.compare_refl; auto.\nQed.\n\nLemma eq_sound : forall x y, eq x y = true -> x = y.\nintros [b1 u1][b2 u2]; unfold eq; case (ext_eq b1 b2); case (ext_eq u1 u2);\n try (intros; discriminate).\nintros; subst; auto.\nQed.\n\nLemma eq_complete : forall x, eq x x = true.\nintros [[l | |][u| |]]; simpl; auto;\ntry case (Z.eq_dec l l); try case (Z.eq_dec u u); intros; auto;\ntry match goal with id :~_ |- _ => case id; apply refl_equal end.\nQed.\n\nLemma join_bot : forall i, join i bot = bot.\nintros [[b | |]  [u | | ]]; unfold bot; simpl; auto.\nQed.\n\nLemma thinner_join :\n  forall e1 e2 e3 e4, thinner e1 e2 -> thinner e3 e4 ->\n  thinner (join e1 e3)(join e2 e4).\nintros [l1 u1] [l2 u2] [l3 u3][l4 u4]; unfold thinner; simpl;\n intros [H1 H2][H3 H4]; unfold join; split; simpl.\ndestruct l1 as [l1 | | ]; destruct  l2 as [l2 | | ];\n simpl in H1, H2, H3, H4 |- *; try discriminate; auto;\ndestruct l3 as [l3 | | ]; simpl in H1, H2, H3, H4 |- *; try discriminate; auto;\ndestruct l4 as [l4 | | ]; simpl in H1, H2, H3, H4 |- *; try discriminate; auto.\nrewrite Z.min_assoc; rewrite <- (Z.min_assoc l1 l3 l2); rewrite (Z.min_comm l3 l2).\ninjection H1; injection H3; clear H1 H3; intros H3 H1.\nrewrite Z.min_assoc; rewrite H1; rewrite <- Z.min_assoc; rewrite H3; auto.\ninjection H1; clear H1; intros H1; rewrite Z.min_assoc; rewrite H1; auto.\ninjection H3; clear H3; intros H3; rewrite Z.min_assoc; rewrite (Z.min_comm l3).\nrewrite <- Z.min_assoc; rewrite H3; auto.\n\ndestruct u1 as [u1 | | ]; destruct  u2 as [u2 | | ];\n simpl in H1, H2, H3, H4 |- *; try discriminate; auto;\ndestruct u3 as [u3 | | ]; simpl in H1, H2, H3, H4 |- *; try discriminate; auto;\ndestruct u4 as [u4 | | ]; simpl in H1, H2, H3, H4 |- *; try discriminate; auto.\ninjection H2; injection H4; clear H2 H4; intros H4 H2.\nrewrite Z.max_assoc; rewrite <- (Z.max_assoc u1); rewrite (Z.max_comm u3).\nrewrite Z.max_assoc; rewrite H2; rewrite <- Z.max_assoc; rewrite H4; auto.\ninjection H2; clear H2; intros H2; rewrite Z.max_assoc; rewrite H2; auto.\ninjection H4; clear H4; intros H4; rewrite Z.max_assoc; rewrite (Z.max_comm u3).\nrewrite <- Z.max_assoc; rewrite H4; auto.\nQed.\n\nLemma thinner_join_left :  forall i i', thinner i (join i i').\nintros [b1 u1] [b2 u2]; split.\ndestruct b1 as [l | | ]; destruct b2 as [l' | | ]; simpl; auto.\nrewrite Z.min_assoc; rewrite Zmin_idempotent; auto.\nrewrite Zmin_idempotent; auto.\ndestruct u1 as [l | | ]; destruct u2 as [l' | | ]; simpl; auto.\nrewrite Z.max_assoc; rewrite Zmax_idempotent; auto.\nrewrite Zmax_idempotent; auto.\nQed.\n\nLemma join_comm : forall i i', join i i' = join i' i.\nintros [u l] [u' l']; unfold join.\n rewrite cp_min_comm; rewrite cp_max_comm; auto.\nQed.\n\nLemma join_assoc : forall i i' i'', join (join i i') i'' = join i (join i' i'').\nintros [l u][l' u'][l'' u'']; unfold join; rewrite cp_min_assoc; rewrite cp_max_assoc.\nauto.\nQed.\n\nLemma join_involutive : forall i, join i i = i.\nintros [l u]; unfold join; rewrite cp_min_refl; rewrite cp_max_refl; auto.\nQed.\n\nLtac Zmin_max_to_le :=\n match goal with id : cZ (Z.min ?a ?b) = cZ ?a |- _ =>\n  assert (Dummy := id); clear id;\n  assert (id : a <= b) by\n    (injection Dummy; clear Dummy; intros Dummy; rewrite <- Dummy;\n     apply Z.le_min_r); clear Dummy\n| id : cZ (Z.min ?a ?b) = cZ ?b |- _ =>\n  assert (Dummy:= id); clear id;\n  assert (id : b <= a) by\n    (injection Dummy; clear Dummy; intros Dummy; rewrite <- Dummy;\n        apply Z.le_min_l); clear Dummy\n| id : cZ (Z.max ?a ?b) = cZ ?a |- _ =>\n  assert (Dummy := id); clear id;\n  assert (id : b <= a) by\n    (injection Dummy; clear Dummy; intros Dummy; rewrite <- Dummy;\n     apply Z.le_max_r); clear Dummy\n| id : cZ (Z.max ?a ?b) = cZ ?b |- _ =>\n  assert (Dummy:= id); clear id;\n  assert (id : a <= b) by\n    (injection Dummy; clear Dummy; intros Dummy; rewrite <- Dummy;\n        apply Z.le_max_l); clear Dummy\n end.\n\nLtac cp_max_min_diff :=\n  match goal with\n  | id : cZ ?a <> cp_max (cZ ?a) (cZ ?b) |- _ =>\n    assert (Dummy:=id); clear id ;\n    assert (id : a <> b) by\n      (intros Dummy';case Dummy; rewrite Dummy'; rewrite cp_max_refl; auto);\n    clear Dummy\n  | id : cZ ?a <> cp_max (cZ ?b) (cZ ?a) |- _ =>\n    assert (Dummy:=id); clear id;\n    assert (id : a <> b) by\n      (intros Dummy';case Dummy; rewrite Dummy'; rewrite cp_max_refl; auto)\n  | id : cZ ?a <> cp_min ?a ?b |- _ =>\n    assert (Dummy:=id); clear id;\n    assert (id : a <> b) by\n      (intros Dummy';case Dummy; rewrite Dummy'; rewrite cp_min_refl; auto)\n  | id : cZ ?a <> cp_min (cZ ?b) (cZ ?a) |- _ =>\n    assert (Dummy:=id); clear id;\n    assert (id : a <> b) by\n      (intros Dummy';case Dummy; rewrite Dummy'; rewrite cp_min_refl; auto)\n  end.\n\nLemma Zmax_le_compat :\n  forall a b c d, a <= b -> c <= d -> Z.max a c <= Z.max b d.\nintros; apply Z.max_lub.\napply Z.le_trans with b; auto; apply Z.le_max_l.\napply Z.le_trans with d; auto; apply Z.le_max_r.\nQed.\n\nLemma Zmin_le_compat :\n  forall a b c d, a <= b -> c <= d -> Z.min a c <= Z.min b d.\nintros; apply Z.min_glb.\napply Z.le_trans with a; auto; apply Z.le_min_l.\napply Z.le_trans with c; auto; apply Z.le_min_r.\nQed.\n\nLemma thinner_widen : forall v1 v2, thinner v1 (widen v1 v2).\nintros [[l1 | | ][u1 | | ]]\n  [[l2 | | ][u2 | | ]]; try (unfold thinner, widen; intuition; fail);\nmatch goal with |- thinner (?x, ?y) (widen _ (?z, ?t)) =>\n  unfold thinner, widen;\n  case (ext_eq (cp_min x z) x);case (ext_eq (cp_max y t) y);\n  try rewrite cp_max_refl; try rewrite cp_min_refl; try (intuition; fail)\nend.\nQed.\n\nDefinition to_p (v:ext_Z*ext_Z)(x:Z) : Prop :=\n  match v with\n    (minfty,pinfty) => True\n  | (minfty,cZ u) => x <= u\n  | (cZ l, cZ u) => l <= x <= u\n  | (cZ l, pinfty) => l <= x\n  | _ => False\n  end.\n\nLemma to_p_thinner : forall l u x, to_p (l,u) x ->\n    thinner (l, cZ x) (l, u)/\\ thinner (cZ x, u)(l,u).\nintros [l | |] [u | |] x ;unfold to_p, thinner; simpl; try(intuition;fail);\nrepeat rewrite Zmin_idempotent; repeat rewrite Zmax_idempotent.\nintros; rewrite Z.max_comm; rewrite Zle_to_Zmax; try lia;\n rewrite Z.min_comm; rewrite Zle_to_Zmin; auto; lia.\nintros; rewrite Z.min_comm; rewrite Zle_to_Zmin; auto.\nintros; rewrite Z.max_comm; rewrite Zle_to_Zmax; auto.\nQed.\n\nLemma plus_correct :\n  forall i1 i2 x1 x2, to_p i1 x1 -> to_p i2 x2 -> to_p (plus i1 i2) (x1+x2).\nProof.\nintros i1 i2 x1 x2 H1 H2.\ndestruct i1 as [[l1 | | ][u1 | | ]]; generalize H1; simpl;\n clear H1; intros H1; contradiction || auto;\ndestruct i2 as [[l2 | | ][u2 | | ]]; generalize H2; simpl;\n intros; contradiction || auto; try lia.\nQed.\n\nLemma of_int_correct : forall n, to_p (of_int n) n.\nintros; simpl; auto with zarith.\nQed.\n\nLemma to_p_cp_max_min :\n   forall l u x, to_p (l,u) x -> cp_max l (cZ x) = cZ x /\\\n                  cp_min (cZ x) u = cZ x.\nintros [l | | ][u | | ]; unfold to_p; simpl; try(intuition; fail).\nintros; rewrite Z.max_comm; rewrite Zle_to_Zmax;try rewrite Zle_to_Zmin;\n intuition.\nintros; rewrite Z.max_comm; rewrite Zle_to_Zmax; intuition.\nintros; rewrite Zle_to_Zmin; intuition.\nQed.\n\nLemma cp_max_min_to_p :\n  forall l u x, cp_max l (cZ x) = cZ x -> cp_min (cZ x) u = cZ x-> to_p (l,u) x.\nintros [l | | ][u | | ]; unfold to_p; simpl; try(intros; auto; discriminate).\nintros x H1 H2; injection H1; injection H2; intros H3 H4;split;\n [rewrite <- H4; apply Z.le_max_l | rewrite <- H3; apply Z.le_min_r].\nintros x H1 _ ; injection H1; intros H3;rewrite <- H3; apply Z.le_max_l.\nintros x _ H1; injection H1; intros H3; rewrite <- H3; apply Z.le_min_r.\nQed.\n\nLemma thinner_prop :\n  forall i1 i2 x, thinner i1 i2 -> to_p i1 x -> to_p i2 x.\nintros [l1 u1][l2 u2] x [H1 H2] H3.\ndestruct (to_p_cp_max_min _ _ _ H3).\napply cp_max_min_to_p.\nrewrite cp_max_comm; apply cp_max_trans with l1.\nrewrite cp_max_comm; auto.\napply cp_min_r_cp_max_l; auto.\napply cp_min_trans with u1; auto.\napply cp_max_r_cp_min_l; auto.\nQed.\n\nLemma bot_semantics : forall x, to_p bot x.\nsimpl; intuition.\nQed.\n\nLemma add_test_constraint_right_true_none :\n   forall v1 v2, add_test_constraint_right true v1 v2 = None ->\n     forall x1 x2, to_p v1 x1 ->\n     to_p v2 x2 -> ~x1 < x2.\nProof.\nintros [b1 u1] [b2 u2]; unfold add_test_constraint_right.\ncase (ext_eq b1 (cp_max b1 u2)); intros Heq.\nintros _; destruct b1 as [b1 | | ]; destruct u2 as [u2 | | ];\ntry (assert (H' : u2 <= b1) by(injection Heq;\n            intros h; rewrite h; apply Z.le_max_r));\n destruct u1 as [u1 | | ]; simpl in Heq;\n try discriminate heq; simpl; intros e1 e2 g; simpl;\n  try(intuition;fail); try discriminate;\ndestruct b2 as [b2 | | ]; simpl; try(intuition;fail).\nintros; discriminate.\nQed.\n\nLemma add_test_constraint_left_true_none :\n   forall v1 v2, add_test_constraint_left true v1 v2 = None ->\n     forall x1 x2, to_p v1 x1 -> to_p v2 x2 -> ~x1 < x2.\nProof.\nintros [b1 u1] [b2 u2]; unfold add_test_constraint_left.\ncase (ext_eq b1 (cp_max b1 u2)); intros Heq.\nintros _; destruct b1 as [b1 | | ]; destruct u2 as [u2 | | ];\ntry (assert (H' : u2 <= b1) by(injection Heq;\n            intros h; rewrite h; apply Z.le_max_r));\n destruct u1 as [u1 | | ]; simpl in Heq;\n try discriminate heq; simpl; intros e1 e2 g; simpl;\n try(intuition;fail); try discriminate;\ndestruct b2 as [b2 | | ]; simpl; try(intuition;fail).\ncase (ext_eq u2 (cp_min b1 u2)).\nintros Heq' _;destruct b1 as [b1 | | ];destruct u2 as [u2 | | ]; simpl in Heq';\ntry (assert (H' : u2 <= b1) by(injection Heq';\n            intros h; rewrite h; apply Z.le_min_l));\n destruct u1 as [u1 | | ]; simpl in Heq;\n try discriminate heq; simpl; intros e1 e2 g;  simpl;\n try(intuition;fail); try discriminate;\ndestruct b2 as [b2 | | ]; simpl; try(intuition;fail).\nintros; discriminate.\nQed.\n\nLemma add_test_constraint_right_false_none :\n  forall v1 v2, add_test_constraint_right false v1 v2 = None ->\n     forall x1 x2, to_p v1 x1 -> to_p v2 x2 -> x1 < x2.\nProof.\nintros [b1 u1] [b2 u2]; unfold add_test_constraint_right.\ncase (ext_eq b2 (cp_max u1 b2)); intros Heq;\ncase (ext_eq u1 (cp_max u1 b2)); intros Heq'; try (intros; discriminate).\nintros _; destruct b2 as [b2 | | ]; destruct u1 as [u1 | | ];\ntry (assert (H' : u1 <= b2) by\n (injection Heq; intros h; rewrite h; apply Z.le_max_l));\ntry (assert (H'' : ~u1 = b2)\n  by (intros h; subst u1; elim Heq'; rewrite cp_max_refl; auto));\n  simpl; try (intuition; fail);\ndestruct u2 as [u2 | | ];\n try discriminate Heq; simpl; intros e1 e2 g;  simpl;\n try(intuition;fail); try discriminate;\ndestruct b1 as [b1 | | ]; simpl; try(intuition;fail).\nQed.\n\nLemma add_test_constraint_left_false_none :\n   forall v1 v2, add_test_constraint_left false v1 v2 = None ->\n     forall x1 x2, to_p v1 x1 -> to_p v2 x2 -> x1 < x2.\nProof.\nintros [b1 u1] [b2 u2]; unfold add_test_constraint_left.\ncase (ext_eq b2 (cp_max u1 b2)); intros Heq;\ncase (ext_eq u1 (cp_max u1 b2)); intros Heq'; try (intros; discriminate).\nintros _; destruct b2 as [b2 | | ]; destruct u1 as [u1 | | ];\ntry (assert (H' : u1 <= b2) by\n (injection Heq; intros h; rewrite h; apply Z.le_max_l));\ntry (assert (H'' : ~u1 = b2)\n  by (intros h; subst u1; elim Heq'; rewrite cp_max_refl; auto));\n  simpl; try (intuition; fail);\ndestruct u2 as [u2 | | ];\n try discriminate Heq; simpl; intros e1 e2 g;  simpl;\n try(intuition;fail); try discriminate;\ndestruct b1 as [b1 | | ]; simpl; try(intuition;fail).\nQed.\n\nLemma add_test_constraint_right_true_sound :\n  forall v1 v2 v x1 x2,\n     add_test_constraint_right true v1 v2 = Some v ->\n     to_p v1 x1 -> to_p v2 x2 -> x1 < x2 -> to_p v x1.\nProof.\nintros [b1 u1][b2 u2] v x1 x2; unfold add_test_constraint_right.\ncase (ext_eq b1 (cp_max b1 u2)); intros Heq; try (intros; discriminate).\nintros Hres; injection Hres; intro; subst v.\nintros H1 H2 H'; destruct (to_p_cp_max_min _ _ _ H1) as [H3 H4].\ndestruct (to_p_cp_max_min _ _ _ H2) as [H5 H6].\napply cp_max_min_to_p; auto.\ndestruct u1 as [u1 | | ]; try (simpl; intuition;fail);\ndestruct u2 as [u2 | | ]; try (simpl; intuition; fail); simpl;\n try (intros; discriminate).\nassert (x1 <= u1) by (simpl in H4; injection H4; intros H7; rewrite <- H7;\n                      apply Z.le_min_r).\nassert (x2 <= u2) by (simpl in H6; injection H6; intros H7; rewrite <- H7;\n                      apply Z.le_min_r).\ndestruct (Zle_or_lt u1 (u2+ -1)).\nrewrite (Zle_to_Zmin u1); try lia.\nrewrite Zle_to_Zmin; auto.\nrewrite (Z.min_comm u1); rewrite (Zle_to_Zmin (u2+ -1)); try lia.\nrewrite Zle_to_Zmin; auto; lia.\nassert (x2 <= u2) by (simpl in H6; injection H6; intros H7; rewrite <- H7;\n                      apply Z.le_min_r).\nrewrite Zle_to_Zmin; auto; lia.\nQed.\n\n(* The next proof should be about the same, but is a textually shorter\nproof that was designed before (maybe longer in time.) *)\n\nLemma add_test_constraint_left_true_sound :\n  forall v1 v2 v x1 x2,\n     add_test_constraint_left true v1 v2 = Some v ->\n     to_p v1 x1 -> to_p v2 x2 -> x1 < x2 -> to_p v x2.\nProof.\nintros [b1 u1][b2 u2] v x1 x2; unfold add_test_constraint_left.\ncase (ext_eq u2 (cp_min b1 u2)); intros Heq; try (intros; discriminate).\nintros Hres; injection Hres; intro; subst v.\ndestruct b1 as [b1 | | ]; try (simpl; intuition;fail);\ndestruct u1 as [u1 | | ]; try (simpl; intuition;fail);\ndestruct b2 as [b2 | | ]; try (simpl; intuition;fail);\ndestruct u2 as [u2 | | ]; try (simpl; intuition; fail); simpl;\n try (assert (b1 <> u2) by\n     (intros h;subst u2; elim Heq; rewrite cp_min_refl; auto));\n   try (case (Zmax_irreducible_inf (b1+1) b2);(intros; lia));\n   try (intros; lia).\nQed.\n\nLemma add_test_constraint_right_false_sound :\n  forall v1 v2 v x1 x2,\n     add_test_constraint_right false v1 v2 = Some v ->\n     to_p v1 x1 -> to_p v2 x2 -> ~x1 < x2 -> to_p v x1.\nProof.\nintros [b1 u1][b2 u2] v x1 x2; unfold add_test_constraint_right.\ncase (ext_eq b2 (cp_max u1 b2)); intros Heq.\ncase (ext_eq u1 (cp_max u1 b2)); intros Heq'; try (intros; discriminate);\nintros H'; injection H'; intro ; subst v; clear H';\ndestruct b1 as [b1 | | ]; destruct u1 as [u1 | | ];\n simpl; try (simpl;intuition;fail);\ndestruct b2 as [b2 | | ]; destruct u2 as [u2 | | ];\n simpl; try (simpl;intuition;fail); try (intros;discriminate);\ntry (case (Zmax_irreducible_inf b1 b2); intros; lia).\nintros H'; injection H'; intro; subst v; clear H'.\ndestruct b1 as [b1 | | ]; destruct u1 as [u1 | | ];\n simpl; try (simpl;intuition;fail);\ndestruct b2 as [b2 | | ];\n try (assert (H': b2 <> u1)\n        by (intro; elim Heq; subst b2; rewrite cp_max_refl; auto));\ndestruct u2 as [u2 | | ];\n try case (Zmax_irreducible_inf b1 b2);\n simpl; try (simpl;intuition;fail); try (intros;discriminate).\nQed.\n\n\nLemma add_test_constraint_left_false_sound :\n  forall v1 v2 v x1 x2,\n     add_test_constraint_left false v1 v2 = Some v ->\n     to_p v1 x1 -> to_p v2 x2 -> ~ x1 < x2 -> to_p v x2.\nProof.\nintros [b1 u1][b2 u2] v x1 x2; unfold add_test_constraint_left.\ncase (ext_eq b2 (cp_max u1 b2)); intros Heq.\ncase (ext_eq u1 (cp_max u1 b2)); intros Heq'; try (intros; discriminate);\nintros H'; injection H'; intro ; subst v; clear H';\ndestruct b1 as [b1 | | ]; destruct u1 as [u1 | | ];\n simpl; try (simpl;intuition;fail);\ndestruct b2 as [b2 | | ]; destruct u2 as [u2 | | ];\n simpl; try (simpl;intuition;fail); try (intros;discriminate);\ntry (case (Zmin_irreducible u1 u2); lia).\nintros H'; injection H'; intro; subst v; clear H'.\ndestruct b1 as [b1 | | ]; destruct u1 as [u1 | | ];\n simpl; try (simpl;intuition;fail);\ndestruct b2 as [b2 | | ];\n try (assert (H': b2 <> u1)\n        by (intro; elim Heq; subst b2; rewrite cp_max_refl; auto));\ndestruct u2 as [u2 | | ];\n try case (Zmin_irreducible_inf u1 u2);\n simpl; try (simpl;intuition;fail); try (intros;discriminate).\nQed.\n\nLemma add_test_constraint_right_true_lb :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_right true (l1, u1) (l2, u2) = Some (l, u) ->\n    l = l1.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_right;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; intros; subst l; auto;fail).\nQed.\n\nLemma add_test_constraint_right_false_ub :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_right false (l1, u1) (l2, u2) = Some (l, u) ->\n    u = u1.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_right;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq'\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; intros; subst l; auto;fail).\nQed.\n\nLemma add_test_constraint_right_true_ub_no_cut :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_right true (l1, u1) (l2, u2) = Some (l, u) ->\n    cp_min u1 (comp_add u2 (cZ (-1))) = u1 ->\n    u = u1.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_right;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; intros; subst u; auto;fail).\nQed.\n\nLemma add_test_constraint_right_false_lb_no_cut :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_right false (l1, u1) (l2, u2) = Some (l, u) ->\n    cp_max l1 l2 = l1 -> l = l1.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_right;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq'\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; intros; subst u; auto;fail);\n  try (intros H1 H2; rewrite H2 in H1; injection H1; auto).\nQed.\n\nLemma add_test_constraint_right_true_ub_cut :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_right true (l1, u1) (l2, u2) = Some (l, u) ->\n    u1 <> cp_min u1 (comp_add u2 (cZ (-1))) ->\n    u = comp_add u2 (cZ (-1)).\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_right;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; do 2 intro; subst u; clear H');\n  try (simpl; intro Hneq;\n    destruct (Zmin_irreducible  u1 (u2+ -1)) as [H|H];\n    try (rewrite H in Hneq;case Hneq; auto;fail); rewrite H; auto; fail);\n  simpl; auto.\nQed.\n\nLemma add_test_constraint_right_false_lb_cut :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_right false (l1, u1) (l2, u2) = Some (l, u) ->\n    l1 <> cp_max l1 l2 -> l = l2.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_right;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq'\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; do 2 intro; subst u; clear H');\n  try (simpl; intro Hneq;\n    destruct (Zmax_irreducible_inf l1 l2) as [H|H];\n    try (rewrite H in Hneq;case Hneq; auto;fail); subst l;\n        rewrite H; auto; fail);\n  simpl; auto.\nQed.\n\nLemma not_cp_min_cp_max :\n  forall a b, ~cp_min a b = b->cp_max a b = b.\nintros [a | | ][b | | ]; simpl; try (intuition; fail).\ndestruct (Zle_or_lt a b).\nrewrite Z.max_comm; rewrite Zle_to_Zmax; auto.\nrewrite Z.min_comm; rewrite Zle_to_Zmin; auto with zarith.\nintros Hn; elim Hn; auto.\nQed.\n\nLemma add_test_constraint_right_true_monotonic :\n  forall v1 v2 v1' v2' v v',\n    add_test_constraint_right true v1 v2 = Some v ->\n    add_test_constraint_right true v1' v2' = Some v' ->\n    thinner v1 v1' -> thinner v2 v2' -> thinner v v'.\nintros [l1 u1][l2 u2][l1' u1'][l2' u2'][l u][l' u'] H H'.\nrewrite add_test_constraint_right_true_lb with (1:=H).\nrewrite add_test_constraint_right_true_lb with (1:=H').\ndestruct (ext_eq u1 (cp_min u1 (comp_add u2 (cZ (-1))))).\nrewrite add_test_constraint_right_true_ub_no_cut with (1:=H); auto.\ndestruct (ext_eq u1' (cp_min u1' (comp_add u2' (cZ (-1))))).\nrewrite add_test_constraint_right_true_ub_no_cut with (1:=H'); auto.\nrewrite add_test_constraint_right_true_ub_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_max_comm; apply cp_max_trans with (comp_add u2 (cZ (-1))).\ndestruct u2 as [u2 | | ]; destruct u2' as [u2' | | ]; simpl in *;\n  try discriminate; auto.\nassert (u2 <= u2') by (injection H4; intros a; rewrite <- a; apply Z.le_max_l).\nrewrite Zle_to_Zmax; auto; try lia.\napply cp_min_r_cp_max_l; rewrite cp_min_comm; auto.\nrewrite add_test_constraint_right_true_ub_cut with (1:=H); auto.\ndestruct (ext_eq u1' (cp_min u1' (comp_add u2' (cZ (-1))))).\nrewrite add_test_constraint_right_true_ub_no_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_max_comm; apply cp_max_trans with u1.\nrewrite cp_max_comm; auto.\nrewrite cp_max_comm; apply not_cp_min_cp_max; rewrite cp_min_comm; auto.\nrewrite add_test_constraint_right_true_ub_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_max_comm; rewrite cp_max_plus; auto.\nrewrite cp_max_comm; auto.\nQed.\n\nLemma cp_max_irreducible :\n  forall a b, cp_max a b = a \\/ cp_max a b = b.\nintros [a | | ][b | | ];try (intuition; fail).\nsimpl; case (Zmax_irreducible_inf a b); intros H; rewrite H; auto.\nQed.\n\nLemma cp_min_irreducible :\n  forall a b, cp_min a b = a \\/ cp_min a b = b.\nintros [a | | ][b | | ]; try (intuition;fail).\nsimpl; case (Zmin_irreducible a b); intros H; rewrite H; auto.\nQed.\n\nLemma add_test_constraint_right_false_monotonic :\n  forall v1 v2 v1' v2' v v',\n    add_test_constraint_right false v1 v2 = Some v ->\n    add_test_constraint_right false v1' v2' = Some v' ->\n    thinner v1 v1' -> thinner v2 v2' -> thinner v v'.\nintros [l1 u1][l2 u2][l1' u1'][l2' u2'][l u][l' u'] H H'.\nrewrite add_test_constraint_right_false_ub with (1:=H).\nrewrite add_test_constraint_right_false_ub with (1:=H').\ndestruct (ext_eq l1 (cp_max l1 l2)) as [Hl1l2 | Hl1l2].\nrewrite add_test_constraint_right_false_lb_no_cut with (1:=H); auto.\ndestruct (ext_eq l1' (cp_max l1' l2')).\nrewrite add_test_constraint_right_false_lb_no_cut with (1:=H'); auto.\nrewrite add_test_constraint_right_false_lb_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_min_comm; apply cp_min_trans with l2.\nrewrite cp_min_comm; auto.\napply cp_max_r_cp_min_l; rewrite cp_max_comm; auto.\nrewrite add_test_constraint_right_false_lb_cut with (1:=H); auto.\ndestruct (ext_eq l1' (cp_max l1' l2')).\nrewrite add_test_constraint_right_false_lb_no_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_min_comm; apply cp_min_trans with l1.\nrewrite cp_min_comm; auto.\napply cp_max_r_cp_min_l.\ncase (cp_max_irreducible l1 l2); auto; intros; case Hl1l2; auto.\nrewrite add_test_constraint_right_false_lb_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4];split; auto.\nQed.\n\nLemma add_test_constraint_right_monotonic :\n  forall neg v1 v2 v1' v2' v v',\n    add_test_constraint_right neg v1 v2 = Some v ->\n    add_test_constraint_right neg v1' v2' = Some v' ->\n    thinner v1 v1' -> thinner v2 v2' -> thinner v v'.\nintros [|].\napply add_test_constraint_right_true_monotonic.\napply add_test_constraint_right_false_monotonic.\nQed.\n\nLemma add_test_constraint_left_true_ub :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_left true (l1, u1) (l2, u2) = Some (l, u) ->\n    u = u2.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_left;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; intros; subst u; auto;fail).\nQed.\n\nLemma add_test_constraint_left_false_lb :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_left false (l1, u1) (l2, u2) = Some (l, u) ->\n    l = l2.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_left;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq'\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; intros; subst l; auto;fail).\nQed.\n\nLemma add_test_constraint_left_true_lb_no_cut :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_left true (l1, u1) (l2, u2) = Some (l, u) ->\n    cp_max (comp_add l1 (cZ 1)) l2 = l2 ->\n    l = l2.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_left;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; intros; subst l; auto;fail).\nQed.\n\nLemma add_test_constraint_left_false_lb_no_cut :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_left false (l1, u1) (l2, u2) = Some (l, u) ->\n    cp_min u1 u2 = u2 -> u = u2.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_left;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq'\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; intros; subst u; auto;fail).\nQed.\n\nLemma add_test_constraint_left_true_lb_cut :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_left true (l1, u1) (l2, u2) = Some (l, u) ->\n    l2 <> cp_max (comp_add l1 (cZ 1)) l2 ->\n    l = comp_add l1 (cZ 1).\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_left;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; do 2 intro; subst l u; clear H'); simpl; auto;\n (simpl; intro Hneq;\n    destruct (Zmax_irreducible_inf  (l1 + 1) l2) as [Hl1l2|Hl1l2];\n    try (rewrite Hl1l2 in Hneq;case Hneq; auto;fail); rewrite Hl1l2; auto; fail).\nQed.\n\nLemma add_test_constraint_left_false_lb_cut :\n  forall l1 u1 l2 u2 l u,\n    add_test_constraint_left false (l1, u1) (l2, u2) = Some (l, u) ->\n    u2 <> cp_min u1 u2 -> u = u1.\nintros [l1 | | ] [u1 | | ] [l2 | | ] [u2 | | ] l u;\n  unfold add_test_constraint_left;\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq\n       end);\n  try (match goal with |- context[ext_eq ?a ?b] =>\n         case (ext_eq a b); intros Heq'\n       end);\n  try (simpl; intros; intuition; discriminate);\n  try (intros H'; injection H'; do 2 intro; subst u l; clear H'); simpl; auto;\n  (simpl; intro Hneq;\n    destruct (Zmin_irreducible u1 u2) as [H|H];\n    try (rewrite H in Hneq;case Hneq; auto;fail);\n        rewrite H; auto; fail);\n  simpl; auto.\nQed.\n\nLemma add_test_constraint_left_true_monotonic :\n  forall v1 v2 v1' v2' v v',\n    add_test_constraint_left true v1 v2 = Some v ->\n    add_test_constraint_left true v1' v2' = Some v' ->\n    thinner v1 v1' -> thinner v2 v2' -> thinner v v'.\nintros [l1 u1][l2 u2][l1' u1'][l2' u2'][l u][l' u'] H H'.\nrewrite add_test_constraint_left_true_ub with (1:=H).\nrewrite add_test_constraint_left_true_ub with (1:=H').\ndestruct (ext_eq l2 (cp_max (comp_add l1 (cZ 1)) l2)) as [Hl2l1 | Hl2l1].\nrewrite add_test_constraint_left_true_lb_no_cut with (1:=H); auto.\ndestruct (ext_eq l2' (cp_max (comp_add l1' (cZ 1)) l2')).\nrewrite add_test_constraint_left_true_lb_no_cut with (1:=H'); auto.\nrewrite add_test_constraint_left_true_lb_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_min_comm; apply cp_min_trans with (comp_add l1 (cZ 1)).\ndestruct l1 as [l1 | | ]; destruct l1' as [l1' | | ]; simpl in *;\n  try discriminate; auto.\nassert (l1' <= l1) by (injection H1; intros a; rewrite <- a; apply Z.le_min_l).\nrewrite Zle_to_Zmin; auto; try lia.\napply cp_max_r_cp_min_l; auto.\nrewrite add_test_constraint_left_true_lb_cut with (1:=H); auto.\ndestruct (ext_eq l2' (cp_max (comp_add l1' (cZ 1)) l2')).\nrewrite add_test_constraint_left_true_lb_no_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_min_comm; apply cp_min_trans with l2.\nrewrite cp_min_comm; auto.\napply cp_max_r_cp_min_l; rewrite cp_max_comm;\n case (cp_max_irreducible (comp_add l1 (cZ 1)) l2);\n try (intros; case Hl2l1; auto; fail); auto.\nrewrite add_test_constraint_left_true_lb_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_min_comm; rewrite cp_min_plus; auto.\nrewrite cp_min_comm; auto.\nQed.\n\nLemma add_test_constraint_left_false_monotonic :\n  forall v1 v2 v1' v2' v v',\n    add_test_constraint_left false v1 v2 = Some v ->\n    add_test_constraint_left false v1' v2' = Some v' ->\n    thinner v1 v1' -> thinner v2 v2' -> thinner v v'.\nintros [l1 u1][l2 u2][l1' u1'][l2' u2'][l u][l' u'] H H'.\nrewrite add_test_constraint_left_false_lb with (1:=H).\nrewrite add_test_constraint_left_false_lb with (1:=H').\ndestruct (ext_eq u2 (cp_min u1 u2)) as [Hl1l2 | Hl1l2].\nrewrite add_test_constraint_left_false_lb_no_cut with (1:=H); auto.\ndestruct (ext_eq u2' (cp_min u1' u2')).\nrewrite add_test_constraint_left_false_lb_no_cut with (1:=H'); auto.\nrewrite add_test_constraint_left_false_lb_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_max_comm; apply cp_max_trans with u1.\nrewrite cp_max_comm; auto.\napply cp_min_r_cp_max_l; auto.\nrewrite add_test_constraint_left_false_lb_cut with (1:=H); auto.\ndestruct (ext_eq u2' (cp_min u1' u2')).\nrewrite add_test_constraint_left_false_lb_no_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4]; split; auto.\nrewrite cp_max_comm; apply cp_max_trans with u2.\nrewrite cp_max_comm; auto.\napply cp_min_r_cp_max_l.\nrewrite cp_min_comm.\ncase (cp_min_irreducible u1 u2); auto; intros; case Hl1l2; auto.\nrewrite add_test_constraint_left_false_lb_cut with (1:=H'); auto.\nintros [H1 H2][H3 H4];split; auto.\nQed.\n\nLemma add_test_constraint_left_monotonic :\n  forall neg v1 v2 v1' v2' v v',\n    add_test_constraint_left neg v1 v2 = Some v ->\n    add_test_constraint_left neg v1' v2' = Some v' ->\n    thinner v1 v1' -> thinner v2 v2' -> thinner v v'.\nintros [|].\napply add_test_constraint_left_true_monotonic.\napply add_test_constraint_left_false_monotonic.\nQed.\n\nLemma add_test_constraint_right_monotonic_none :\n  forall neg v1 v2 v1' v2' v,\n    add_test_constraint_right neg v1 v2 = Some v ->\n    thinner v1 v1' -> thinner v2 v2' ->\n    ~add_test_constraint_right neg v1' v2' = None.\nunfold add_test_constraint_right;\nintros [|] [l1 u1][l2 u2][l1' u1'][l2' u2'] [l u] Hadd [H1 H2][H3 H4].\ndestruct (ext_eq l1' (cp_max l1' u2')).\ndestruct (ext_eq l1 (cp_max l1 u2)) as [A | B]; try discriminate.\ndestruct B; symmetry.\napply cp_max_trans with l1'.\napply cp_min_r_cp_max_l; auto.\napply cp_max_trans with u2'; auto.\nrewrite cp_max_comm; auto.\ndiscriminate.\ndestruct (ext_eq l2' (cp_max u1' l2')) as [C | D]; try discriminate.\ndestruct (ext_eq u1' (cp_max u1' l2')) as [A | B]; try discriminate.\ndestruct B; symmetry.\ndestruct (ext_eq l2 (cp_max u1 l2)) as [A | B]; try discriminate.\ndestruct (ext_eq u1 (cp_max u1 l2)); try discriminate.\napply cp_max_trans with u1.\nrewrite cp_max_comm; auto.\napply cp_max_trans with l2; auto.\napply cp_min_r_cp_max_l; auto.\napply cp_max_trans with u1.\nrewrite cp_max_comm; auto.\napply cp_max_trans with l2.\ncase (cp_max_irreducible u1 l2); auto; intros; case B; auto.\napply cp_min_r_cp_max_l; auto.\nQed.\n\nLemma add_test_constraint_left_monotonic_none :\n  forall neg v1 v2 v1' v2' v,\n    add_test_constraint_left neg v1 v2 = Some v ->\n    thinner v1 v1' -> thinner v2 v2' ->\n    ~add_test_constraint_left neg v1' v2' = None.\nunfold add_test_constraint_left;\nintros [|] [l1 u1][l2 u2][l1' u1'][l2' u2'] [l u] Hadd [H1 H2][H3 H4].\ndestruct (ext_eq u2' (cp_min l1' u2')).\ndestruct (ext_eq u2 (cp_min l1 u2)) as [A | B]; try discriminate.\ndestruct B; symmetry.\nrewrite cp_min_comm; apply cp_min_trans with l1'; auto.\napply cp_min_trans with u2'; auto.\napply cp_max_r_cp_min_l; auto.\nrewrite cp_min_comm; auto.\nrewrite cp_min_comm; auto.\ndiscriminate.\ndestruct (ext_eq l2' (cp_max u1' l2')) as [C | D]; try discriminate.\ndestruct (ext_eq u1' (cp_max u1' l2')) as [A | B]; try discriminate.\ndestruct B; symmetry.\ndestruct (ext_eq l2 (cp_max u1 l2)) as [A | B]; try discriminate.\ndestruct (ext_eq u1 (cp_max u1 l2)); try discriminate.\napply cp_max_trans with u1.\nrewrite cp_max_comm; auto.\napply cp_max_trans with l2; auto.\napply cp_min_r_cp_max_l; auto.\napply cp_max_trans with u1.\nrewrite cp_max_comm; auto.\napply cp_max_trans with l2.\ncase (cp_max_irreducible u1 l2); auto; intros; case B; auto.\napply cp_min_r_cp_max_l; auto.\nQed.\n", "meta": {"author": "coq-community", "repo": "semantics", "sha": "576853c18a726233a6af27b8c285accfb170d751", "save_path": "github-repos/coq/coq-community-semantics", "path": "github-repos/coq/coq-community-semantics/semantics-576853c18a726233a6af27b8c285accfb170d751/intervals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678381, "lm_q2_score": 0.798186787341014, "lm_q1q2_score": 0.7458218743537434}}
{"text": "(* Exercise 67 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_067 : (forall x : D, ~ P x) -> ~ exists x : D, P x.\nProof.\nimp_i a1.\nneg_i (1=1) a2.\nexi_e (exists x:D, P x) a a3.\nhyp a2.\nneg_e (P a).\nall_e (forall x:D, ~P x) a.\nhyp a1.\nhyp a3.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred067.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.745821863250482}}
{"text": "(* Exercise 26 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_026 : (~A /\\ ~B) -> ~(A \\/ (~A /\\ B)).\nProof.\nimp_i a1.\nneg_i (1=1) a2.\ndis_e (A \\/ ~A /\\ B) a3 a3.\nhyp a2.\nneg_e A.\ncon_e1 (~B).\nhyp a1.\nhyp a3.\nneg_e B.\ncon_e2 (~A).\nhyp a1.\ncon_e2 (~A).\nhyp a3.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop026.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7457448538011675}}
{"text": "Require Import List.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nSection list_util.\n  Variables A : Type.\n\n  Lemma in_firstn : forall n (x : A) xs,\n      In x (firstn n xs) -> In x xs.\n  Proof using.\n    induction n; simpl; intuition.\n    destruct xs;simpl in *; intuition.\n  Qed.\n\n  Lemma firstn_NoDup : forall n (xs : list A),\n    NoDup xs ->\n    NoDup (firstn n xs).\n  Proof using.\n    induction n; intros; simpl; destruct xs; auto.\n    - apply NoDup_nil.\n    - inversion H; subst.\n      apply NoDup_cons.\n      * eauto 6 using in_firstn.\n      * apply IHn; auto.        \n  Qed.\nEnd list_util.\n", "meta": {"author": "proofengineering", "repo": "serapi-tests", "sha": "18b1debf9219077210b77ff3e5f0bd3feadeffd9", "save_path": "github-repos/coq/proofengineering-serapi-tests", "path": "github-repos/coq/proofengineering-serapi-tests/serapi-tests-18b1debf9219077210b77ff3e5f0bd3feadeffd9/eauto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7457282165032638}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Ext_Cons.Prod_Cat.Prod_Cat Ext_Cons.Prod_Cat.Operations.\nRequire Import Functor.Main.\n\nLocal Open Scope morphism_scope.\n\n(**\nGiven two objects a and b, their product a×b is an object such that there are\ntwo projections from it to a and b:\n\n#\n<pre>\n\n                    π₁        π₂\n                a <—–——– a×b ———–—> b\n</pre>\n#\nsuch that for any object z with two projections to a and b, there is a unique\narrow h that makes the following diagram commute:\n\n#\n<pre>\n                    π₁        π₂\n                a <—–——–– a×b –———–—> b\n                 ↖         ↑        ↗\n                  \\        |       /\n                   \\       |      /\n                    \\      |∃!h  /\n                     \\     |    /\n                      \\    |   /\n                       \\   |  /\n                           z\n</pre>\n#\n*)\nRecord Product {C : Category} (c d : C) : Type :=\n{\n  product : C;\n\n  Pi_1 : product –≻ c;\n\n  Pi_2 : product –≻ d;\n\n  Prod_morph_ex : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d), p' –≻ product;\n\n  Prod_morph_com_1 : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d),\n      (Pi_1 ∘ (Prod_morph_ex p' r1 r2))%morphism = r1;\n  \n  Prod_morph_com_2 : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d),\n      (Pi_2 ∘ (Prod_morph_ex p' r1 r2))%morphism = r2;\n  \n  Prod_morph_unique :\n    ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d) (f g : p' –≻ product),\n      Pi_1 ∘ f = r1\n      → Pi_2 ∘ f = r2\n      → Pi_1 ∘ g = r1\n      → Pi_2 ∘ g = r2\n      → f = g\n}.\n\nArguments Product _ _ _, {_} _ _.\n\nArguments Pi_1 {_ _ _ _}, {_ _ _} _.\nArguments Pi_2 {_ _ _ _}, {_ _ _} _.\nArguments Prod_morph_ex {_ _ _} _ _ _ _.\nArguments Prod_morph_com_1 {_ _ _} _ _ _ _.\nArguments Prod_morph_com_2 {_ _ _} _ _ _ _.\nArguments Prod_morph_unique {_ _ _} _ _ _ _ _ _ _ _ _ _.\n\nCoercion product : Product >-> Obj.\n\nNotation \"a × b\" := (Product a b) : object_scope.\n\nLocal Open Scope object_scope.\n\n(** for any pair of objects, their product is unique up to isomorphism. *)\nTheorem Product_iso {C : Category} (c d : Obj) (P : c × d) (P' : c × d)\n  : (P ≃ P')%isomorphism.\nProof.\n  eapply (Build_Isomorphism _ _ _\n                            (Prod_morph_ex P' P Pi_1 Pi_2)\n                            (Prod_morph_ex P P' Pi_1 Pi_2));\n  eapply Prod_morph_unique; eauto;\n  rewrite <- assoc;\n  repeat (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); auto.\nQed.\n\nDefinition Has_Products (C : Category) : Type := ∀ a b, a × b.\n\nExisting Class Has_Products.\n\n(**\nThe product functor maps each pair of objects (an object of the product\ncategory C×C) to their product in C.\n*)\nProgram Definition Prod_Func (C : Category) {HP : Has_Products C}\n  : ((C × C) –≻ C)%functor :=\n{|\n  FO := fun x => HP (fst x) (snd x); \n  FA := fun a b f => Prod_morph_ex _ _ ((fst f) ∘ Pi_1) ((snd f) ∘ Pi_2)\n|}.\n\nNext Obligation. (* F_id *)  \nProof.\n  eapply Prod_morph_unique;\n  try reflexivity; [rewrite Prod_morph_com_1|rewrite Prod_morph_com_2]; auto.\nQed.  \n\nNext Obligation. (* F_compose *)  \nProof.\n  eapply Prod_morph_unique;\n  try ((rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); reflexivity);\n  repeat rewrite <- assoc; (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2);\n  rewrite assoc; (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); auto.\nQed.\n\nArguments Prod_Func _ _, _ {_}.\n\nNotation \"×ᶠⁿᶜ\" := Prod_Func : functor_scope.\n\n(** Sum is the dual of product *)\nDefinition Sum (C : Category) := @Product (C^op).\n\nArguments Sum _ _ _, {_} _ _.\n\nNotation \"a + b\" := (Sum a b) : object_scope.\n\nDefinition Has_Sums (C : Category) : Type :=  ∀ (a b : C), (a + b)%object.\n\nExisting Class Has_Sums.\n\n(**\nThe sum functor maps each pair of objects (an object of the product category\nC×C) to their sum in C.\n*)\nDefinition Sum_Func {C : Category} {HS : Has_Sums C} : ((C × C) –≻ C)%functor :=\n  (×ᶠⁿᶜ (C^op) HS)^op.\n\nArguments Sum_Func _ _, _ {_}.\n\nNotation \"+ᶠⁿᶜ\" := Sum_Func : functor_scope.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Basic_Cons/Product.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7457282043125207}}
{"text": "Require Import ZArith FSets FSetAVL.\n\nModule M := FSetAVL.Make(Z_as_OT).\n\nOpen Scope Z_scope.\n\nDefinition ens1 := M.add 3 (M.add 0 (M.add 2 (M.empty))).\nDefinition ens2 := M.add 0 (M.add 2 (M.add 4 (M.empty))).\nDefinition ens3 := M.inter ens1 ens2.\nDefinition ens4 := M.union ens1 ens2.\n\nEval vm_compute in (M.mem 2 ens3).\nEval vm_compute in (M.elements ens3).\nEval vm_compute in (M.elements ens4).\nEval vm_compute in \n match (M.compare ens3 ens4) with EQ _ => 0 | LT _ => -1 | GT _ => 1 end.\n\n(* Sets by themselves are ugly (proof parts), but who cares *)\nEval vm_compute in ens1.\nEval vm_compute in ens3.\nEval vm_compute in ens4.\n\n(** Some more intense tests. *)\n\nFixpoint multiples (m:Z)(start:Z)(n:nat) {struct n} : list Z := \n  match n with \n   | O => nil\n   | S n => start::(multiples m (m+start) n)\n  end.\n\nEval vm_compute in (multiples 2 0 200%nat).\n\nDefinition bigens1 := fold_right M.add M.empty (multiples 2 0 400%nat).\nDefinition bigens2 := fold_right M.add M.empty (multiples 3 0 400%nat).\nTime Eval vm_compute in (M.elements (M.inter bigens1 bigens2)).\nTime Eval vm_compute in (M.elements (M.union bigens1 bigens2)).\n\nDefinition bigens3 := fold_right M.add M.empty (multiples 2 0 (100*100)%nat).\nDefinition bigens4 := fold_right M.add M.empty (multiples 3 0 (100*100)%nat).\nTime Eval vm_compute in (M.cardinal bigens3). (* computation of bigens3 done once and forall *)\nTime Eval vm_compute in (M.cardinal bigens4). (* computation of bigens4 done once and forall *)\nTime Eval vm_compute in (M.cardinal (M.inter bigens3 bigens4)).\nTime Eval vm_compute in (M.cardinal (M.union bigens3 bigens4)).\n\n(* Experimental illustration of the cardinal law: |AUB|+|A^B|=|A|+|B| *)\nTime Eval vm_compute in (M.cardinal (M.union bigens3 bigens4)\n                                         +M.cardinal (M.inter bigens3 bigens4))%nat.\n(*   = 20000%nat\n     : nat\n*)\n\n", "meta": {"author": "coq-contribs", "repo": "fsets", "sha": "18b21173b85da4b89892d2a90fe213717aa0ee6c", "save_path": "github-repos/coq/coq-contribs-fsets", "path": "github-repos/coq/coq-contribs-fsets/fsets-18b21173b85da4b89892d2a90fe213717aa0ee6c/FSetAVL_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7457282000699699}}
{"text": "Require Import Kami.Syntax.\n\nSection nat_string.\n  Unset Implicit Arguments.\n\n  (*\n    Accepts two arguments: radix and ns; and returns: ns[0] + radix *\n    ns[1] + radix^2 * ns[2] + ... radix^n * ns[n]\n\n    Ex: nat_decomp_nat 2 [1; 0; 1; 1] = 13.\n  *)\n  Local Fixpoint nat_decomp_nat (radix : nat) (ns : list nat) : nat\n    := match ns with\n       | [] => 0\n       | m :: ms => (radix * nat_decomp_nat radix ms) + m\n       end.\n\n  Local Fixpoint nat_decomp_prod (x : nat) (ns : list nat) : list nat\n    := match ns with\n       | [] => []\n       | m :: ms => x * m :: nat_decomp_prod x ms\n       end.\n\n  (* 0 = Nat.div x y ==> x < y ==> x = x mod y *)\n  Lemma div0_mod : forall x y : nat, y <> 0 -> 0 = Nat.div x y -> x = x mod y.\n  Proof.\n    exact\n      (fun x y H H0\n        => eq_sym (Nat.mod_small x y\n             (proj1 (Nat.div_small_iff x y H)\n               (eq_sym H0)))).\n  Qed.\n\n  Local Definition nat_decomp\n    (radix : nat) (* radix minus 2 *)\n    (n : nat)\n    :  {ms : list nat |\n         Forall (fun m => m < (S (S radix))) ms /\\\n         n = nat_decomp_nat (S (S radix)) ms}\n    := Fix_F\n         (fun n\n           => {ms : list nat |\n                Forall (fun m => m < (S (S radix))) ms /\\\n                n = nat_decomp_nat (S (S radix)) ms})\n         (fun n (F : forall r, r < n -> {ms : list nat | Forall (fun m => m < (S (S radix))) ms /\\ r = nat_decomp_nat (S (S radix)) ms})\n           => nat_rec\n                (fun q\n                  => q = Nat.div n (S (S radix)) ->\n                     {ms : list nat |\n                       Forall (fun m => m < (S (S radix))) ms /\\\n                       n = nat_decomp_nat (S (S radix)) ms})\n                (fun H : 0 = Nat.div n (S (S radix))\n                  => let H0 : n = nat_decomp_nat (S (S radix)) [n mod (S (S radix))]\n                       := ltac:(\n                            lazy [nat_decomp_nat list_rec list_rect];\n                            rewrite (Nat.mul_0_r (S (S radix)));\n                            rewrite (Nat.add_0_l _);\n                            apply (div0_mod n (S (S radix)) (Nat.neq_succ_0 (S radix)) H)) in\n                     exist\n                       (fun ms\n                         => Forall (fun m => m < (S (S radix))) ms /\\\n                            n = nat_decomp_nat (S (S radix)) ms)\n                       [n mod (S (S radix))]\n                       (conj\n                         (Forall_cons (n mod (S (S radix))) \n                           (Nat.mod_upper_bound n (S (S radix)) (Nat.neq_succ_0 (S radix)))\n                           (Forall_nil (fun m => m < S (S radix))))\n                         H0))\n                (fun q _ (H : S q = Nat.div n (S (S radix)))\n                  => let (ms, H0)\n                       := F (S q)\n                            (eq_ind_r\n                              (fun x => x < n)\n                              (Nat.div_lt n (S (S radix))\n                                (or_ind\n                                  (fun H0 : 0 < n => H0)\n                                  (fun H0 : 0 = n\n                                    => False_ind (0 < n)\n                                         (let H2 : Nat.div n (S (S radix)) = 0\n                                            := eq_ind\n                                                 0\n                                                 (fun x => Nat.div x (S (S radix)) = 0)\n                                                 (Nat.div_0_l (S (S radix)) (Nat.neq_succ_0 (S radix)))\n                                                 n\n                                                 H0 in\n                                          let H1 : S q = 0\n                                            := eq_ind_r (fun x => x = 0) H2 H in\n                                          Nat.neq_succ_0 q H1))\n                                  ((proj1 (Nat.lt_eq_cases 0 n))\n                                    (Nat.le_0_l n)))\n                                (le_n_S 1 (S radix) (le_n_S 0 radix (Nat.le_0_l radix)))) \n                              H) in\n                     let xs := n mod (S (S radix)) :: ms in\n                     let H1 : n = nat_decomp_nat (S (S radix)) xs\n                       := ltac:(\n                            unfold xs;\n                            lazy [nat_decomp_nat list_rec list_rect];\n                            fold (nat_decomp_nat (S (S radix)));\n                            rewrite <- (proj2 H0);\n                            rewrite H;\n                            rewrite <- (Nat.div_mod n (S (S radix)) (Nat.neq_succ_0 (S radix)));\n                            reflexivity) in\n                     let H2 : Forall (fun m => m < S (S radix)) xs\n                       := Forall_cons (n mod S (S radix))\n                           (Nat.mod_upper_bound n (S (S radix)) (Nat.neq_succ_0 (S radix)))\n                           (proj1 H0) in\n                     exist _ xs (conj H2 H1))\n                (Nat.div n (S (S radix)))\n                eq_refl)%nat\n         (lt_wf n).\n\n  (* Every function that has an inverse is injective. *)\n  Local Theorem inv_inj\n    : forall (A B : Type) (f : A -> B) (g : B -> A),\n        (forall x : A, g (f x) = x) ->\n        (forall x y : A, f x = f y -> x = y).\n  Proof.\n    intros A b f g Hg x y Hxy.\n    rewrite <- (Hg x).\n    rewrite <- (Hg y).\n    rewrite Hxy.\n    reflexivity.\n  Qed.\n\n  Local Theorem nat_decomp_inj\n    (radix : nat) (* radix minus 2 *)\n    :  forall n m : nat, proj1_sig (nat_decomp radix n) = proj1_sig (nat_decomp radix m) -> n = m.\n  Proof.\n    exact\n      (inv_inj _ _\n        (fun x => proj1_sig (nat_decomp radix x))\n        (nat_decomp_nat (S (S radix)))  \n        (fun x => eq_sym (proj2 (proj2_sig (nat_decomp radix x))))).\n  Qed.\n\n  Local Open Scope char_scope.\n\n  Local Fixpoint nat_decomp_chars\n    (radix : nat) (* radix minus 2 *)\n    (encoding : forall n, n < S (S radix) -> ascii)\n    (ns : list nat)\n    :  Forall (fun n => n < S (S radix)) ns -> list ascii\n    := match ns with\n       | [] => fun _ => []\n       | m :: ms\n         => fun H : Forall (fun n => n < S (S radix)) (m :: ms)\n              => nat_decomp_chars radix encoding ms (Forall_inv_tail H) ++\n                 [encoding m (Forall_inv H)]\n       end.\n\n  Local Theorem nat_decomp_chars_inj\n    (radix : nat)\n    (encoding : forall n, n < S (S radix) -> ascii)\n    (encoding_inj : forall n m (Hn : n < S (S radix)) (Hm : m < S (S radix)), encoding n Hn = encoding m Hm -> n = m)\n    : forall \n         (ns : list nat)\n         (ms : list nat)\n         (Hns : Forall (fun n => n < S (S radix)) ns)\n         (Hms : Forall (fun m => m < S (S radix)) ms),\n         nat_decomp_chars radix encoding ns Hns =\n         nat_decomp_chars radix encoding ms Hms ->\n         ns = ms.\n  Proof.\n    exact\n      (list_ind\n        (fun ns\n          => forall\n               (ms : list nat)\n               (Hns : Forall (fun n => n < S (S radix)) ns)\n               (Hms : Forall (fun m => m < S (S radix)) ms),\n               nat_decomp_chars radix encoding ns Hns =\n               nat_decomp_chars radix encoding ms Hms ->\n               ns = ms)\n        (list_ind\n          (fun ms\n            => forall\n                 (Hns : Forall (fun n => n < S (S radix)) [])\n                 (Hms : Forall (fun m => m < S (S radix)) ms),\n                 nat_decomp_chars radix encoding [] Hns =\n                 nat_decomp_chars radix encoding ms Hms ->\n                 [] = ms)\n          (fun _ _ _ => ltac:(reflexivity))\n          (fun _ _ _ _ _ H => False_ind _ (app_cons_not_nil _ _ _ H)))\n        (fun n ns F\n          => list_ind\n               (fun ms\n                 => forall\n                      (Hns : Forall (fun n => n < S (S radix)) (n :: ns))\n                      (Hms : Forall (fun m => m < S (S radix)) ms),\n                      nat_decomp_chars radix encoding (n :: ns) Hns =\n                      nat_decomp_chars radix encoding ms Hms ->\n                      (n :: ns) = ms)\n               (fun _ _ H => False_ind _ (app_cons_not_nil _ _ _ (eq_sym H)))\n               (fun m ms G Hns Hms H\n                 => let H0\n                      :  ns = ms\n                      := F ms\n                           (Forall_inv_tail Hns)\n                           (Forall_inv_tail Hms)\n                           (proj1 (app_inj_tail \n                             (nat_decomp_chars radix encoding ns (Forall_inv_tail Hns))\n                             (nat_decomp_chars radix encoding ms (Forall_inv_tail Hms))\n                             (encoding n (Forall_inv Hns))\n                             (encoding m (Forall_inv Hms))\n                             H)) in\n                    sumbool_ind\n                      (fun _ => _)\n                      (fun H1 : n = m\n                        => ltac:(rewrite H0; rewrite H1; reflexivity) : (n :: ns) = (m :: ms))\n                      (fun H1 : n <> m\n                        => let H2\n                             :  encoding n (Forall_inv Hns) = encoding m (Forall_inv Hms)\n                             := proj2 (app_inj_tail\n                                  (nat_decomp_chars radix encoding ns (Forall_inv_tail Hns))\n                                  (nat_decomp_chars radix encoding ms (Forall_inv_tail Hms))\n                                  (encoding n (Forall_inv Hns))\n                                  (encoding m (Forall_inv Hms))\n                                  H) in\n                           False_ind _\n                             (H1 (encoding_inj n m (Forall_inv Hns) (Forall_inv Hms) H2)))\n                       (Nat.eq_dec n m)))).\n  Qed.\n\n  Local Definition nat_chars\n    (radix : nat)\n    (encoding : forall n, n < S (S radix) -> ascii)\n    (n : nat)\n    :  list ascii\n    := nat_decomp_chars radix encoding\n         (proj1_sig (nat_decomp radix n))\n         (proj1 (proj2_sig (nat_decomp radix n))).\n\n  Local Theorem nat_chars_inj\n    (radix : nat)\n    (encoding : forall n, n < S (S radix) -> ascii)\n    (encoding_inj : forall n m (Hn : n < S (S radix)) (Hm : m < S (S radix)), encoding n Hn = encoding m Hm -> n = m)\n    :  forall n m : nat, nat_chars radix encoding n = nat_chars radix encoding m -> n = m.\n  Proof.\n    intros n m H.\n    assert ((proj1_sig (nat_decomp radix n)) = (proj1_sig (nat_decomp radix m))).\n    apply (nat_decomp_chars_inj radix encoding encoding_inj \n            (proj1_sig (nat_decomp radix n))\n            (proj1_sig (nat_decomp radix m))\n            (proj1 (proj2_sig (nat_decomp radix n)))\n            (proj1 (proj2_sig (nat_decomp radix m)))\n            H).\n    apply (nat_decomp_inj radix n m H0).\n  Qed.\n    \n  Local Definition nat_string\n    (radix : nat)\n    (encoding : forall n, n < S (S radix) -> ascii)\n    (n : nat)\n    :  string\n    := string_of_list_ascii (nat_chars radix encoding n).\n\n  Local Lemma string_of_list_ascii_inj\n    : forall xs ys : list ascii, string_of_list_ascii xs = string_of_list_ascii ys -> xs = ys.\n  Proof.\n    exact\n      (inv_inj _ _\n        string_of_list_ascii\n        list_ascii_of_string\n        list_ascii_of_string_of_list_ascii).\n  Qed.\n\n  Local Theorem nat_string_inj\n    (radix : nat)\n    (encoding : forall n, n < S (S radix) -> ascii)\n    (encoding_inj : forall n m (Hn : n < S (S radix)) (Hm : m < S (S radix)), encoding n Hn = encoding m Hm -> n = m)\n    :  forall n m : nat, nat_string radix encoding n = nat_string radix encoding m -> n = m.\n  Proof.\n    intros n m H.\n    assert (nat_chars radix encoding n = nat_chars radix encoding m).\n    apply (string_of_list_ascii_inj _ _ H).\n    assert ((proj1_sig (nat_decomp radix n)) = (proj1_sig (nat_decomp radix m))).\n    apply (nat_decomp_chars_inj radix encoding encoding_inj \n            (proj1_sig (nat_decomp radix n))\n            (proj1_sig (nat_decomp radix m))\n            (proj1 (proj2_sig (nat_decomp radix n)))\n            (proj1 (proj2_sig (nat_decomp radix m)))\n            H0).\n    apply (nat_decomp_inj radix n m H1).\n  Qed.\n\n  Local Ltac notIn H (* In x xs *) := repeat (destruct H; repeat (discriminate; assumption)).\n\n  Local Ltac encoding_NoDup xs\n    := lazymatch xs with\n       | nil => exact (NoDup_nil ascii)\n       | (cons ?X ?XS)%list\n         => exact\n              (NoDup_cons X \n                (fun H : In X XS => ltac:(notIn H))\n                (ltac:(encoding_NoDup XS)))\n       end.\n\n  Local Definition decode (encoding : list ascii) (n : nat) : ascii\n    := List.nth n encoding \" \".\n\n  Local Definition decode_safe (encoding : list ascii) (n : nat) (_ : n < List.length encoding)\n    := decode encoding n.\n\n  Local Ltac digit_encoding_inj encoding\n    := exact\n         (proj1 (NoDup_nth encoding \" \") \n            ltac:(encoding_NoDup encoding)\n           : forall n m : nat,\n               n < List.length encoding ->\n               m < List.length encoding ->\n               decode encoding n = decode encoding m ->\n               n = m).\n\n  Local Ltac encoding_inj radix encoding (* radix = encoding - 2 *)\n    := exact\n         (nat_string_inj\n           radix\n           (decode_safe encoding)\n           (ltac:(digit_encoding_inj encoding))).\n\n  Local Definition binary_encoding_list : list ascii := [\"0\"; \"1\"].\n\n  Definition natToBinStr : nat -> string\n    := nat_string 0 (decode_safe binary_encoding_list).\n\n  Definition natToBinStr_inj\n    :  forall n m, natToBinStr n = natToBinStr m -> n = m\n    := ltac:(encoding_inj 0 [\"0\"; \"1\"]%list).\n\n  Local Definition decimal_encoding_list : list ascii\n    := [\"0\"; \"1\"; \"2\"; \"3\"; \"4\"; \"5\"; \"6\"; \"7\"; \"8\"; \"9\"].\n\n  Definition natToDecStr : nat -> string\n    := nat_string 8 (decode_safe decimal_encoding_list).\n\n  Definition natToDecStr_inj\n    :  forall n m, natToDecStr n = natToDecStr m -> n = m\n    := ltac:(encoding_inj 8 [\"0\"; \"1\"; \"2\"; \"3\"; \"4\"; \"5\"; \"6\"; \"7\"; \"8\"; \"9\"]%list).\n\n  Local Definition hex_encoding_list : list ascii\n    := [\"0\"; \"1\"; \"2\"; \"3\"; \"4\"; \"5\"; \"6\"; \"7\"; \"8\"; \"9\"; \"A\"; \"B\"; \"C\"; \"D\"; \"E\"; \"F\"].\n\n  Definition natToHexStr : nat -> string\n    := nat_string 14 (decode_safe hex_encoding_list).\n\n  Definition natToHexStr_inj\n    :  forall n m, natToHexStr n = natToHexStr m -> n = m\n    := ltac:(encoding_inj 14 [\"0\"; \"1\"; \"2\"; \"3\"; \"4\"; \"5\"; \"6\"; \"7\"; \"8\"; \"9\"; \"A\"; \"B\"; \"C\"; \"D\"; \"E\"; \"F\"]%list).\n\n  Local Close Scope char_scope.\n\n  Local Open Scope string_scope.\n\n  (* Goal (natToHexStr 179 = \"B3\"). Proof. reflexivity. Qed. *)\n  Goal (natToDecStr 179 = \"179\"). Proof. reflexivity. Qed.\n  Goal (natToBinStr 179 = \"10110011\"). Proof. reflexivity. Qed.\n\n  Local Close Scope string_scope.\n\n  Local Close Scope list.\n\n  Set Implicit Arguments.\n\nEnd nat_string.\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Lib/NatStr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.74569935868675}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := zero : Nat | succ : Nat -> Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint plus (plus_arg0 : Nat) (plus_arg1 : Nat) : Nat\n           := match plus_arg0, plus_arg1 with\n              | zero, n => n\n              | succ n, m => succ (plus n m)\n              end.\n\nTheorem theorem0 : forall (x : Nat) (y : Nat) (z : Nat), eq (plus (plus x y) z) (plus x (plus y z)).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal74.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7456993531051481}}
{"text": "Require Import Arith.\nOpen Scope nat_scope.\n\nFixpoint fact (n:nat):nat:=\n  match n with\n  |O=>1\n  |S n'=>n*fact n'\n  end.\n\nEval vm_compute in fact 8.", "meta": {"author": "shij-hsu", "repo": "coq", "sha": "335711e36628d93d5723d8617b250e90be578d83", "save_path": "github-repos/coq/shij-hsu-coq", "path": "github-repos/coq/shij-hsu-coq/coq-335711e36628d93d5723d8617b250e90be578d83/fact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.7456706041139436}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export Logic.\nRequire Export Poly.\nRequire Coq.omega.Omega.\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 quantifiers.\n    In this chapter, we bring a new tool into the mix: _inductive\n    definitions_. *)\n\n(** Recall that we have seen two ways of stating that a number [n] is\n    even: We can say (1) [evenb n = true], or (2) [exists k, n =\n    double k].  Yet another possibility is to say that [n] is even if\n    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 definition of evenness works, let's\n    imagine using it to show that [4] is even. By rule [ev_SS], it\n    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: *)\n(**\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 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 [ev_SS] says that, if [n]\n    satisfies [ev], then [S (S n)] also does.  If a rule has no\n    premises above the line, then its conclusion holds\n    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\n                             ------  (ev_0)\n                              ev 0\n                             ------ (ev_SS)\n                              ev 2\n                             ------ (ev_SS)\n                              ev 4\n*)\n\n(** Why call this a \"tree\" (rather than a \"stack\", for example)?\n    Because, in general, inference rules can have multiple premises.\n    We will see examples of this below. *)\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(** This definition is different in one crucial respect from\n    previous uses of [Inductive]: its result is not a [Type], but\n    rather a function from [nat] to [Prop] -- that is, a property of\n    numbers.  Note that we've already seen other inductive definitions\n    that result in functions, such as [list], whose type is [Type ->\n    Type].  What is new here is that, because the [nat] argument of\n    [ev] appears _unnamed_, to the _right_ of the colon, it is allowed\n    to take different values in the types of different constructors:\n    [0] in the type of [ev_0] and [S (S n)] in the type of [ev_SS].\n\n    In contrast, the definition of [list] names the [X] parameter\n    _globally_, to the _left_ of the colon, forcing the result of\n    [nil] and [cons] to be the same ([list X]).  Had we tried to bring\n    [nat] to the left in defining [ev], we would have seen an error: *)\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).\n(* ===> Error: A parameter of an inductive type n is not\n        allowed to be used as a bound variable in the type\n        of its constructor. *)\n\n(** (\"Parameter\" here is Coq jargon for an argument on the left of the\n    colon in an [Inductive] definition; \"index\" is used to refer to\n    arguments on the right of the colon.) *)\n\n(** We can think of the definition of [ev] as defining a Coq property\n    [ev : nat -> Prop], together with primitive theorems [ev_0 : ev 0] and\n    [ev_SS : forall n, ev n -> ev (S (S n))]. *)\n\n(** Such \"constructor theorems\" have the same status as proven\n    theorems.  In particular, we can use Coq's [apply] tactic with the\n    rule names to prove [ev] for particular numbers... *)\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: *)\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\n(** We can also prove theorems that have hypotheses 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(** More generally, we can show that any number multiplied by 2 is even: *)\n\n(** **** Exercise: 1 star (ev_double)  *)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\ninduction n. \n-  simpl. apply ev_0.\n-  simpl. apply ev_SS. apply IHn.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Using Evidence in Proofs *)\n\n(** Besides _constructing_ evidence that numbers are even, we can also\n    _reason about_ such evidence.\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 even, but also that these two\n    constructors are the _only_ ways to build evidence that numbers\n    are even (in the sense of [ev]). *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [ev n], then we know that [E] must have one of two shapes:\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 hypothesis\n    of the form [ev n] much as we do inductively defined data\n    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 we\n    are given [ev n] as a hypothesis.  We already know how to perform\n    case analysis on [n] using the [inversion] tactic, generating\n    separate subgoals for the case where [n = O] and the case where [n\n    = S n'] for some [n'].  But for some proofs we may instead want to\n    analyze the evidence that [ev n] _directly_.\n\n    By the definition of [ev], there are two cases to consider:\n\n    - If the evidence is of the form [ev_0], we know that [n = 0].\n\n    - Otherwise, the evidence must have the form [ev_SS n' E'], where\n      [n = S (S n')] and [E'] is evidence for [ev n']. *)\n\n(** We can perform this kind of reasoning in Coq, again using\n    the [inversion] tactic.  Besides allowing us to reason about\n    equalities involving constructors, [inversion] provides a\n    case-analysis principle for inductively defined propositions.\n    When used in this way, its syntax is similar to [destruct]: We\n    pass it a list of identifiers separated by [|] characters to name\n    the arguments to each of the possible constructors.  *)\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  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\n(** In words, here is how the inversion reasoning works in this proof:\n\n    - If the evidence is of the form [ev_0], we know that [n = 0].\n      Therefore, it suffices to show that [ev (pred (pred 0))] holds.\n      By the definition of [pred], this is equivalent to showing that\n      [ev 0] holds, which directly follows from [ev_0].\n\n    - Otherwise, the evidence must have the form [ev_SS n' E'], where\n      [n = S (S n')] and [E'] is evidence for [ev n'].  We must then\n      show that [ev (pred (pred (S (S n'))))] holds, which, after\n      simplification, follows directly from [E']. *)\n\n(** This particular proof also works if we replace [inversion] by\n    [destruct]: *)\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\n(** The difference between the two forms is that [inversion] is more\n    convenient when used on a hypothesis that consists of an inductive\n    property applied to a complex expression (as opposed to a single\n    variable).  Here's is a concrete example.  Suppose that we wanted\n    to prove the following variation of [ev_minus2]: *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\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.  *)\n\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0. *)\n    (* We must prove that [n] is even from no assumptions! *)\nAbort.\n\n(** What happened, exactly?  Calling [destruct] has the effect of\n    replacing all occurrences of the property argument by the values\n    that correspond to each constructor.  This is enough in the case\n    of [ev_minus2'] because that argument, [n], is mentioned directly\n    in the final goal. However, it doesn't help in the case of\n    [evSS_ev] since the term that gets replaced ([S (S n)]) is not\n    mentioned anywhere. *)\n\n(** The [inversion] tactic, on the other hand, can detect (1) that the\n    first case does not apply, and (2) that the [n'] that appears on\n    the [ev_SS] case must be the same as [n].  This allows us to\n    complete the proof: *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  (* We are in the [E = ev_SS n' E'] case now. *)\n  apply E'.\nQed.\n\n(** By using [inversion], we can also apply the principle of explosion\n    to \"obviously contradictory\" hypotheses involving inductive\n    properties. For example: *)\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\n(** **** Exercise: 1 star (SSSSev__even)  *)\n(** Prove the following result using [inversion]. *)\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\nintros n H.\ninversion H.\napply evSS_ev in H1.  \nexact H1.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (even5_nonsense)  *)\n(** Prove the following result using [inversion]. *)\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\nintros contra. inversion contra. inversion H0. inversion H2.\nQed.  \n(** [] *)\n\n(** The way we've used [inversion] here may seem a bit\n    mysterious at first.  Until now, we've only used [inversion] on\n    equality propositions, to utilize injectivity of constructors or\n    to discriminate between different constructors.  But we see here\n    that [inversion] can also be applied to analyzing evidence for\n    inductively defined propositions.\n\n    Here's how [inversion] works in general.  Suppose the name [I]\n    refers to an assumption [P] in the current context, where [P] has\n    been defined by an [Inductive] declaration.  Then, for each of the\n    constructors of [P], [inversion I] generates a subgoal in which\n    [I] has been replaced by the exact, specific conditions under\n    which this constructor could have been used to prove [P].  Some of\n    these subgoals will be self-contradictory; [inversion] throws\n    these away.  The ones that are left represent the cases that must\n    be proved to establish the original goal.  For those, [inversion]\n    adds all equations into the proof context that must hold of the\n    arguments given to [P] (e.g., [S (S n') = n] in the proof of\n    [evSS_ev]). *)\n\n(** The [ev_double] exercise above shows that our new notion of\n    evenness is implied by the two earlier ones (since, by\n    [even_bool_prop] in chapter [Logic], we already know that\n    those are equivalent to each other). To show that all three\n    coincide, we just need the following lemma: *)\n\nLemma ev_even_firsttry : forall n,\n  ev n -> exists k, n = double k.\nProof.\n(* WORKED IN CLASS *)\n\n(** We could try to proceed by case analysis or induction on [n].  But\n    since [ev] is mentioned in a premise, this strategy would probably\n    lead to a dead end, as in the previous section.  Thus, it seems\n    better to first try inversion on the evidence for [ev].  Indeed,\n    the first case can be solved trivially. *)\n\n  intros n E. inversion E as [| n' E'].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E' *) simpl.\n\n(** Unfortunately, the second case is harder.  We need to show [exists\n    k, S (S n') = double k], but the only available assumption is\n    [E'], which states that [ev n'] holds.  Since this isn't directly\n    useful, it seems that we are stuck and that performing case\n    analysis on [E] was a waste of time.\n\n    If we look more closely at our second goal, however, we can see\n    that something interesting happened: By performing case analysis\n    on [E], we were able to reduce the original result to an similar\n    one that involves a _different_ piece of evidence for [ev]: [E'].\n    More formally, we can finish our proof by showing that\n\n        exists k', n' = double k',\n\n    which is the same as the original statement, but with [n'] instead\n    of [n].  Indeed, it is not difficult to convince Coq that this\n    intermediate result suffices. *)\n\n    assert (I : (exists k', n' = double k') ->\n                (exists k, S (S n') = double k)).\n    { intros [k' Hk']. rewrite Hk'. exists (S k'). simpl. reflexivity. }\n    apply I. (* reduce the original goal to the new one *)\n\nAdmitted.\n\n(* ================================================================= *)\n(** ** Induction on Evidence *)\n\n(** If this looks familiar, it is no coincidence: We've encountered\n    similar problems in the [Induction] chapter, when trying to use\n    case analysis to prove results that required induction.  And once\n    again the solution is... induction!\n\n    The behavior of [induction] on evidence is the same as its\n    behavior on data: It causes Coq to generate one subgoal for each\n    constructor that could have used to build that evidence, while\n    providing an induction hypotheses for each recursive occurrence of\n    the property in question. *)\n\n(** Let's try our current lemma again: *)\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  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       with IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). reflexivity.\nQed.\n\n(** Here, we can see that Coq produced an [IH] that corresponds to\n    [E'], the single recursive occurrence of [ev] in its own\n    definition.  Since [E'] mentions [n'], the induction hypothesis\n    talks about [n'], as opposed to [n] or some other number. *)\n\n(** The equivalence between the second and third definitions of\n    evenness now follows. *)\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. apply ev_double.\nQed.\n\n(** As we will see in later chapters, induction on evidence is a\n    recurring technique across many areas, and in particular when\n    formalizing the semantics of programming languages, where many\n    properties of interest are defined inductively. *)\n\n(** The following exercises provide simple examples of this\n    technique, to help you familiarize yourself with it. *)\n\n(** **** Exercise: 2 stars (ev_sum)  *)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\nintros n m H1 H2.\ninduction H1.\nsimpl. exact H2.\nsimpl. apply ev_SS. exact IHev.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (ev'_ev)  *)\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 : forall n m, ev' n -> ev' m -> ev' (n + m).\n\n(** Prove that this definition is logically equivalent to the old\n    one.  (You may want to look at the previous theorem when you get\n    to the induction step.) *)\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, recommended (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(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)\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(* FILL IN HERE *)\nAdmitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Inductive Relations *)\n\n(** A proposition parameterized by a number (such as [ev])\n    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 Playground.\n\n(** One useful example is the \"less than or equal to\" relation on\n    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(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [ev] above. 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) ->\n    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 Playground.\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 : 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(** **** Exercise: 2 stars, optional (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, optional (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: 3 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.\nintros m n o H1 H2.\nrewrite <- H1 in H2.\nexact H2.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\ninduction n.\napply le_n.\napply le_S.  \nexact IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\nintros n m H.\nrewrite <- PeanoNat.Nat.add_1_r.\nrewrite <- PeanoNat.Nat.add_1_r with m.\napply Plus.plus_le_compat_r.\nexact H.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\nintros n m H.\nrewrite <- PeanoNat.Nat.add_1_r in H.\nrewrite <- PeanoNat.Nat.add_1_r with m in H.\napply Plus.plus_le_reg_l with (p:=1).\nrewrite plus_comm.\nrewrite plus_comm with (m:=m).\nexact H.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\nintros a b.\nSearch (le ?a (?a + ?b)).\napply Plus.le_plus_l.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\nunfold lt.\nintros n1 n2 m H.\nsplit.\n-\nrewrite <- PeanoNat.Nat.add_succ_l in H.\nrewrite le_plus_l with (b:=n2).\nexact H.\n-\nrewrite <- PeanoNat.Nat.add_succ_r in H.\nrewrite le_plus_l with (b:=n1).\nrewrite plus_comm.\nexact H.\nQed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\nunfold lt.\nintros n m H.\nrewrite <- PeanoNat.Nat.add_1_l with (n:=m).\nrewrite plus_comm.\nrewrite <- le_plus_l.\nexact H.\nQed.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\ninduction n.\n-\ninduction m.\n+ reflexivity.\n+ intros H. apply O_le_n.\n-\ninduction m.\n+ intros H. inversion H.\n+ intros H. inversion H. apply IHn in H1. apply le_n_S in H1. exact H1.\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  leb n m = true.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** Hint: This theorem can easily be proved without using [induction]. *)\n\nTheorem leb_true_trans : forall n m o,\n  leb n m = true -> leb m o = true -> leb n o = true.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nModule R.\n\n(** **** Exercise: 3 stars, recommended (R_provability)  *)\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(** 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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd R.\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\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\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (R_provability2)  *)\n(** Suppose we give Coq the following definition:\n\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\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(** * Case Study: Regular Expressions *)\n\n(** The [ev] property provides a simple example for illustrating\n    inductive definitions and the basic techniques for reasoning about\n    them, but it is not terribly exciting -- after all, it is\n    equivalent to the two non-inductive definitions of evenness that\n    we had already seen, and does not seem to offer any concrete\n    benefit over them.  To give a better sense of the power of\n    inductive definitions, we now show how to use them to model a\n    classic concept in computer science: _regular expressions_. *)\n\n(** Regular expressions are a simple language for describing strings,\n    defined as follows: *)\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(** Note that this definition is _polymorphic_: Regular\n    expressions in [reg_exp T] describe strings with characters drawn\n    from [T] -- that is, lists of elements of [T].\n\n    (We depart slightly from standard practice in that we do not\n    require the type [T] to be finite.  This results in a somewhat\n    different theory of regular expressions, but the difference is not\n    significant for our purposes.) *)\n\n(** We connect regular expressions and strings via the following\n    rules, which define when a regular expression _matches_ some\n    string:\n\n      - The expression [EmptySet] does not match any string.\n\n      - The expression [EmptyStr] matches the empty string [[]].\n\n      - The expression [Char x] matches the one-character string [[x]].\n\n      - If [re1] matches [s1], and [re2] matches [s2], then [App re1\n        re2] matches [s1 ++ s2].\n\n      - If at least one of [re1] and [re2] matches [s], then [Union re1\n        re2] matches [s].\n\n      - Finally, if we can write some string [s] as the concatenation of\n        a sequence of strings [s = s_1 ++ ... ++ s_k], and the\n        expression [re] matches each one of the strings [s_i], then\n        [Star re] matches [s].\n\n        As a special case, the sequence of strings may be empty, so\n        [Star re] always matches the empty string [[]] no matter what\n        [re] is. *)\n\n(** We can easily translate this informal definition into an\n    [Inductive] one as follows: *)\n\nInductive 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(** Again, for readability, we can also display this definition using\n    inference-rule notation.  At the same time, let's introduce a more\n    readable infix notation. *)\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\n(**\n\n                          ----------------                    (MEmpty)\n                           [] =~ EmptyStr\n\n                          ---------------                      (MChar)\n                           [x] =~ Char x\n\n                       s1 =~ re1    s2 =~ re2\n                      -------------------------                 (MApp)\n                       s1 ++ s2 =~ App re1 re2\n\n                              s1 =~ re1\n                        ---------------------                (MUnionL)\n                         s1 =~ Union re1 re2\n\n                              s2 =~ re2\n                        ---------------------                (MUnionR)\n                         s2 =~ Union re1 re2\n\n                          ---------------                     (MStar0)\n                           [] =~ Star re\n\n                      s1 =~ re    s2 =~ Star re\n                     ---------------------------            (MStarApp)\n                        s1 ++ s2 =~ Star re\n*)\n\n(** Notice that these rules are not _quite_ the same as the informal\n    ones that we gave at the beginning of the section.  First, we\n    don't need to include a rule explicitly stating that no string\n    matches [EmptySet]; we just don't happen to include any rule that\n    would have the effect of some string matching [EmptySet].  (Indeed,\n    the syntax of inductive definitions doesn't even _allow_ us to\n    give such a \"negative rule.\")\n\n    Second, the informal rules for [Union] and [Star] correspond\n    to two constructors each: [MUnionL] / [MUnionR], and [MStar0] /\n    [MStarApp].  The result is logically equivalent to the original\n    rules but more convenient to use in Coq, since the recursive\n    occurrences of [exp_match] are given as direct arguments to the\n    constructors, making it easier to perform induction on evidence.\n    (The [exp_match_ex1] and [exp_match_ex2] exercises below ask you\n    to prove that the constructors given in the inductive declaration\n    and the ones that would arise from a more literal transcription of\n    the informal rules are indeed equivalent.)\n\n    Let's illustrate these rules with a few examples. *)\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2]).\n  - apply MChar.\n  - apply MChar.\nQed.\n\n(** (Notice how the last example applies [MApp] to the strings [[1]]\n    and [[2]] directly.  Since the goal mentions [[1; 2]] instead of\n    [[1] ++ [2]], Coq wouldn't be able to figure out how to split the\n    string on its own.)\n\n    Using [inversion], we can also show that certain strings do _not_\n    match a regular expression: *)\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. inversion H.\nQed.\n\n(** We can define helper functions for writing down regular\n    expressions. The [reg_exp_of_list] function constructs a regular\n    expression that matches exactly the list that it receives as an\n    argument: *)\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.\nQed.\n\n(** We can also prove general facts about [exp_match].  For instance,\n    the following lemma shows that every string [s] that matches [re]\n    also matches [Star re]. *)\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(** (Note the use of [app_nil_r] to change the goal of the theorem to\n    exactly the same shape expected by [MStarApp].) *)\n\n(** **** Exercise: 3 stars (exp_match_ex1)  *)\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.\nunfold not.\nintros T s H.\ninversion 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.\nintros T s re1 re2 H.\ndestruct H.\n- apply MUnionL. exact H.\n- apply MUnionR. exact 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\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n\nLemma MStar' : forall T (ss : list (list T)) (re : reg_exp),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (reg_exp_of_list_spec)  *)\n(** Prove that [reg_exp_of_list] satisfies the following\n    specification: *)\n\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Since the definition of [exp_match] has a recursive\n    structure, we might expect that proofs involving regular\n    expressions will often require induction on evidence. *)\n\n\n(** For example, suppose that we wanted to prove the following\n    intuitive result: If a regular expression [re] matches some string\n    [s], then all elements of [s] must occur as character literals\n    somewhere in [re].\n\n    To state this theorem, we first define a function [re_chars] that\n    lists all characters that occur in a regular expression: *)\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\n(** We can then phrase our theorem as follows: *)\n\nTheorem in_re_match : forall T (s : list T) (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 [| 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  (* WORKED IN CLASS *)\n  - (* MEmpty *)\n    apply Hin.\n  - (* MChar *)\n    apply Hin.\n  - simpl. 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\n(** Something interesting happens in the [MStarApp] case.  We obtain\n    _two_ induction hypotheses: One that applies when [x] occurs in\n    [s1] (which matches [re]), and a second one that applies when [x]\n    occurs in [s2] (which matches [Star re]).  This is a good\n    illustration of why we need induction on evidence for [exp_match],\n    as opposed to [re]: The latter would only provide an induction\n    hypothesis for strings that match [re], which would not allow us\n    to reason about the case [In x s2]. *)\n\n  - (* MStarApp *)\n    simpl. 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(** **** Exercise: 4 stars (re_not_empty)  *)\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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** The [remember] Tactic *)\n\n(** One potentially confusing feature of the [induction] tactic is\n    that it happily lets you try to set up an induction over a term\n    that isn't sufficiently general.  The effect of this is to lose\n    information (much as [destruct] can do), and leave you unable to\n    complete the proof.  Here's an example: *)\n\nLemma star_app: 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\n(** Just doing an [inversion] on [H1] won't get us very far in\n    the recursive cases. (Try it!). So we need induction (on\n    evidence!). Here is a naive first attempt: *)\n\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\n(** But now, although we get seven cases (as we would expect from the\n    definition of [exp_match]), we have lost a very important bit of\n    information from [H1]: the fact that [s1] matched something of the\n    form [Star re].  This means that we have to give proofs for _all_\n    seven constructors of this definition, even though all but two of\n    them ([MStar0] and [MStarApp]) are contradictory.  We can still\n    get the proof to go through for a few constructors, such as\n    [MEmpty]... *)\n\n  - (* MEmpty *)\n    simpl. intros H. apply H.\n\n(** ... but most cases get stuck.  For [MChar], for instance, we\n    must show that\n\n    s2 =~ Char x' -> x' :: s2 =~ Char x',\n\n    which is clearly impossible. *)\n\n  - (* MChar. Stuck... *)\nAbort.\n\n(** The problem is that [induction] over a Prop hypothesis only works\n    properly with hypotheses that are completely general, i.e., ones\n    in which all the arguments are variables, as opposed to more\n    complex expressions, such as [Star re].\n\n    (In this respect, [induction] on evidence behaves more like\n    [destruct] than like [inversion].)\n\n    We can solve this problem by generalizing over the problematic\n    expressions with an explicit equality: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp),\n  re' = Star re ->\n  s1 =~ re' ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\n\n(** We can now proceed by performing induction over evidence directly,\n    because the argument to the first hypothesis is sufficiently\n    general, which means that we can discharge most cases by inverting\n    the [re' = Star re] equality in the context.\n\n    This idiom is so common that Coq provides a tactic to\n    automatically generate such equations for us, avoiding thus the\n    need for changing the statements of our theorems. *)\n\nAbort.\n\n(** Invoking the tactic [remember e as x] causes Coq to (1) replace\n    all occurrences of the expression [e] by the variable [x], and (2)\n    add an equation [x = e] to the context.  Here's how we can use it\n    to show the above result: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re : reg_exp),\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\n(** We now have [Heqre' : re' = Star re]. *)\n\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\n(** The [Heqre'] is contradictory in most cases, which allows us to\n    conclude immediately. *)\n\n  - (* MEmpty *)  inversion Heqre'.\n  - (* MChar *)   inversion Heqre'.\n  - (* MApp *)    inversion Heqre'.\n  - (* MUnionL *) inversion Heqre'.\n  - (* MUnionR *) inversion Heqre'.\n\n(** The interesting cases are those that correspond to [Star].  Note\n    that the induction hypothesis [IH2] on the [MStarApp] case\n    mentions an additional premise [Star re'' = Star re'], which\n    results from the equality generated by [remember]. *)\n\n  - (* MStar0 *)\n    inversion Heqre'. intros s H. apply H.\n\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\n(** **** Exercise: 4 stars, 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),\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (pumping)  *)\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].\n\n    To begin, we need to define \"sufficiently long.\"  Since we are\n    working in a constructive logic, we actually need to be able to\n    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 => 0\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 _ => 1\n  end.\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\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\n(** Now, the 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 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(** To streamline the proof (which you are to fill in), the [omega]\n    tactic, which is enabled by the following [Require], is helpful in\n    several places for automatically completing tedious low-level\n    arguments involving equalities or inequalities over natural\n    numbers.  We'll return to [omega] in a later chapter, but feel\n    free to experiment with it now if you like.  The first case of the\n    induction gives an example of how it is used. *)\n\nImport Coq.omega.Omega.\n\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. omega.\n  (* FILL IN HERE *) Admitted.\n\nEnd Pumping.\n(** [] *)\n\n(* ################################################################# *)\n(** * Case Study: Improving Reflection *)\n\n(** We've seen in the [Logic] chapter that we often need to\n    relate boolean computations to statements in [Prop].  But\n    performing this conversion as we did it there can result in\n    tedious proof scripts.  Consider the proof of the following\n    theorem: *)\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  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_nat n m) eqn:H.\n    + (* beq_nat n m = true *)\n      intros _. rewrite beq_nat_true_iff in H. rewrite H.\n      left. reflexivity.\n    + (* beq_nat n m = false *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** In the first branch after [destruct], we explicitly apply\n    the [beq_nat_true_iff] lemma to the equation generated by\n    destructing [beq_nat n m], to convert the assumption [beq_nat n m\n    = true] into the assumption [n = m]; then we had to [rewrite]\n    using this assumption to complete the case. *)\n\n(** We can streamline this by defining an inductive proposition that\n    yields a better case-analysis principle for [beq_nat n m].\n    Instead of generating an equation such as [beq_nat n m = true],\n    which is generally not directly useful, this principle gives us\n    right away the assumption we really need: [n = m]. *)\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~ P -> reflect P false.\n\n(** The [reflect] property takes two arguments: a proposition\n    [P] and a boolean [b].  Intuitively, it states that the property\n    [P] is _reflected_ in (i.e., equivalent to) the boolean [b]: that\n    is, [P] holds if and only if [b = true].  To see this, notice\n    that, by definition, the only way we can produce evidence that\n    [reflect P true] holds is by showing that [P] is true and using\n    the [ReflectT] constructor.  If we invert this statement, this\n    means that it should be possible to extract evidence for [P] from\n    a proof of [reflect P true].  Conversely, the only way to show\n    [reflect P false] is by combining evidence for [~ P] with the\n    [ReflectF] constructor.\n\n    It is easy to formalize this intuition and show that the two\n    statements are indeed equivalent: *)\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  (* WORKED IN CLASS *)\n  intros P b H. destruct b.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. intros H'. inversion H'.\nQed.\n\n(** **** Exercise: 2 stars, recommended (reflect_iff)  *)\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n(* Fill IN HERE *) Admitted.\n(** [] *)\n\n(** The advantage of [reflect] over the normal \"if and only if\"\n    connective is that, by destructing a hypothesis or lemma of the\n    form [reflect P b], we can perform case analysis on [b] while at\n    the same time generating appropriate hypothesis in the two\n    branches ([P] in the first subgoal and [~ P] in the second). *)\n\n\nLemma beq_natP : forall n m, reflect (n = m) (beq_nat n m).\nProof.\n  intros n m. apply iff_reflect. rewrite beq_nat_true_iff. reflexivity.\nQed.\n\n(** The new proof of [filter_not_empty_In] now goes as follows.\n    Notice how the calls to [destruct] and [apply] are combined into a\n    single call to [destruct]. *)\n\n(** (To see this clearly, look at the two proofs of\n    [filter_not_empty_In] with Coq and observe the differences in\n    proof state at the beginning of the first case of the\n    [destruct].) *)\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  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_natP n m) as [H | H].\n    + (* n = m *)\n      intros _. rewrite H. left. reflexivity.\n    + (* n <> m *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** **** Exercise: 3 stars, recommended (beq_natP_practice)  *)\n(** Use [beq_natP] as above to prove the following: *)\n\nFixpoint count n l :=\n  match l with\n  | [] => 0\n  | m :: l' => (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 -> ~(In n l).\nProof.\n(* Fill IN HERE *) Admitted.\n(** [] *)\n\n(** In this small example, this technique gives us only a rather small\n    gain in convenience for the proofs we've seen; however, using\n    [reflect] consistently often leads to noticeably shorter and\n    clearer scripts as proofs get larger.  We'll see many more\n    examples in later chapters and in _Programming Language\n    Foundations_.\n\n    The use of the [reflect] property was popularized by _SSReflect_,\n    a Coq library that has been used to formalize important results in\n    mathematics, including as the 4-color theorem and the\n    Feit-Thompson theorem.  The name SSReflect stands for _small-scale\n    reflection_, i.e., the pervasive use of reflection to simplify\n    small proof steps with boolean computations. *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars, recommended (nostutter_defn)  *)\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 the [NoDup] property in \n    the exercise above: the sequence [1;4;1] repeats but does not\n    stutter.)  The property \"[nostutter mylist]\" means that\n    [mylist] does not stutter.  Formulate an inductive definition for\n    [nostutter]. *)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n (* FILL IN HERE *)\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(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n*)\n\nExample test_nostutter_2:  nostutter (@nil nat).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  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 (filter_challenge)  *)\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(** 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\n(** **** Exercise: 4 stars, optional (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 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, optional (palindrome_converse)  *)\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(** **** Exercise: 4 stars, advanced, optional (NoDup)  *)\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\n(** **** Exercise: 4 stars, advanced, optional (pigeonhole_principle)  *)\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** $Date: 2017-11-15 14:12:04 -0500 (Wed, 15 Nov 2017) $ *)\n", "meta": {"author": "ChengjieZheng", "repo": "sf", "sha": "5051720f5c2c596b4eda4d3202ad2c6b8b8d677a", "save_path": "github-repos/coq/ChengjieZheng-sf", "path": "github-repos/coq/ChengjieZheng-sf/sf-5051720f5c2c596b4eda4d3202ad2c6b8b8d677a/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137997, "lm_q2_score": 0.8333246015211009, "lm_q1q2_score": 0.7456500799611785}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Ext_Cons.Prod_Cat.Prod_Cat Ext_Cons.Prod_Cat.Operations.\nRequire Import Functor.Main.\n\nLocal Open Scope morphism_scope.\n\n(**\nGiven two objects a and b, their product a×b is an object such that there are two projections from it to a and b:\n\n#\n<pre>\n\n                    π₁        π₂\n                a <—–——– a×b ———–—> b\n</pre>\n#\nsuch that for any object z with two projections to a and b, there is a unique arrow h that makes the following diagram commute:\n\n#\n<pre>\n                    π₁        π₂\n                a <—–——–– a×b –———–—> b\n                 ↖         ↑        ↗\n                  \\        |       /\n                   \\       |      /\n                    \\      |∃!h  /\n                     \\     |    /\n                      \\    |   /\n                       \\   |  /\n                           z\n</pre>\n#\n*)\nRecord Product {C : Category} (c d : C) : Type :=\n{\n  product : C;\n\n  Pi_1 : product –≻ c;\n\n  Pi_2 : product –≻ d;\n\n  Prod_morph_ex : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d), p' –≻ product;\n\n  Prod_morph_com_1 : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d),\n      (Pi_1 ∘ (Prod_morph_ex p' r1 r2))%morphism = r1;\n  \n  Prod_morph_com_2 : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d),\n      (Pi_2 ∘ (Prod_morph_ex p' r1 r2))%morphism = r2;\n  \n  Prod_morph_unique : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d) (f g : p' –≻ product),\n      Pi_1 ∘ f = r1\n      → Pi_2 ∘ f = r2\n      → Pi_1 ∘ g = r1\n      → Pi_2 ∘ g = r2\n      → f = g\n}.\n\nArguments Product _ _ _, {_} _ _.\n\nArguments Pi_1 {_ _ _ _}, {_ _ _} _.\nArguments Pi_2 {_ _ _ _}, {_ _ _} _.\nArguments Prod_morph_ex {_ _ _} _ _ _ _.\nArguments Prod_morph_com_1 {_ _ _} _ _ _ _.\nArguments Prod_morph_com_2 {_ _ _} _ _ _ _.\nArguments Prod_morph_unique {_ _ _} _ _ _ _ _ _ _ _ _ _.\n\nCoercion product : Product >-> Obj.\n\n(** for any pair of objects, their product is unique up to isomorphism. *)\nTheorem Product_iso {C : Category} (c d : Obj) (P : Product c d) (P' : Product c d) : (P ≃ P')%isomorphism.\nProof.\n  eapply (Build_Isomorphism _ _ _ (Prod_morph_ex P' P Pi_1 Pi_2) (Prod_morph_ex P P' Pi_1 Pi_2));\n  eapply Prod_morph_unique; eauto;\n  rewrite <- assoc;\n  repeat (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); auto.\nQed.\n\nDefinition Has_Products (C : Category) : Type := ∀ a b, Product a b.\n\nExisting Class Has_Products.\n\n(**\nThe product functor maps each pair of objects (an object of the product category C×C) to their product in C.\n*)\nProgram Definition Prod_Func (C : Category) {HP : Has_Products C} : ((C × C) –≻ C)%functor :=\n{|\n  FO := fun x => HP (fst x) (snd x); \n  FA := fun a b f => Prod_morph_ex _ _ ((fst f) ∘ Pi_1) ((snd f) ∘ Pi_2)\n|}.\n\nNext Obligation. (* F_id *)  \nProof.\n  eapply Prod_morph_unique; try reflexivity; [rewrite Prod_morph_com_1|rewrite Prod_morph_com_2]; auto.\nQed.  \n\nNext Obligation. (* F_compose *)  \nProof.\n  eapply Prod_morph_unique; try ((rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); reflexivity);\n  repeat rewrite <- assoc; (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2);\n  rewrite assoc; (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); auto.\nQed.\n\nArguments Prod_Func _ _, _ {_}.\n\n(** Sum is the dual of product *)\nDefinition Sum (C : Category) := @Product (C^op).\n\nArguments Sum _ _ _, {_} _ _.\n\nDefinition Has_Sums (C : Category) : Type :=  ∀ (a b : C), Sum a b.\n\nExisting Class Has_Sums.\n\n(**\nThe sum functor maps each pair of objects (an object of the product category C×C) to their sum in C.\n*)\nDefinition Sum_Func {C : Category} {HS : Has_Sums C} : ((C × C) –≻ C)%functor := (Prod_Func (C^op) HS)^op.\n\nArguments Sum_Func _ _, _ {_}.", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/Basic_Cons/Product.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7456500683634838}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (z : natural) (x : natural) : natural :=\n  plus lf2 (mult x z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj192_coqofml_A6fRfK.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679977, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7456453538973532}}
{"text": "Require Import List Arith.\nImport ListNotations.\n\nInductive Subseq : list nat -> list nat -> Prop :=\n| Subseq_nil : Subseq [] []\n| Subseq_take : forall a xs ys, Subseq xs ys -> Subseq (a :: xs) (a :: ys)\n| Subseq_drop : forall a xs ys, Subseq xs ys -> Subseq xs (a :: ys).\n\nFixpoint subseq_match (xs ys : list nat) : bool :=\n  match xs with\n  | [] => true\n  | x :: xs' =>\n    (fix go (us : list nat) :=\n      match us with\n      | [] => false\n      | u :: us' =>\n          if x =? u\n          then subseq_match xs' us'\n          else go us'\n      end) ys\n  end.\n\nTheorem subseq_match_take xs ys a: subseq_match xs ys = subseq_match (a :: xs) (a :: ys).\nProof.\n  simpl.\n  rewrite (Nat.eqb_refl).\n  easy.\nQed.\n\nTheorem subseq_match_drop xs ys a: subseq_match xs ys = true -> subseq_match xs (a :: ys) = true.\nProof.\n  intros.\n  revert dependent ys.\n  revert dependent a.\n  induction xs; [easy| ]; intros.\n  simpl in *.\n  destruct (Nat.eqb_spec a a0); subst.\n  destruct ys; [easy | ].\n  destruct (Nat.eqb_spec a0 n); subst.\n  apply IHxs.\n  exact H.\n  apply IHxs.\n  destruct ys.\n  easy.\n\n\n\n\nQed.\n\nTheorem subseq_match_correct : forall (xs ys : list nat),\n  subseq_match xs ys = true <-> Subseq xs ys.\nProof.\n  intros.\n  generalize dependent xs.\n  induction ys; intros; split; intros.\n    - destruct xs.\n      + constructor.\n      + simpl in H.\n        discriminate.\n    - inversion H. simpl. easy.\n    - destruct xs.\n      + constructor.\n        apply IHys.\n        simpl.\n        easy.\n      + simpl in H.\n        destruct (Nat.eqb_spec n a); subst.\n        * constructor.\n          apply IHys.\n          exact H.\n        * constructor.\n          apply IHys.\n          exact H.\n    - destruct xs.\n      + simpl. easy.\n      + inversion H; subst.\n        simpl.\n        rewrite (Nat.eqb_refl a).\n        apply IHys.\n        exact H1.\n        apply IHys in H2.\n        simpl.\n        destruct (Nat.eqb_spec n a); subst.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/subseq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7456453410334722}}
{"text": "(*\nСерия семинаров по Coq.\n\nДомашние задания помечены комментарием с заголовком HW\nи являются одним из двух:\n- теоремы с доказательством admit.\n- определения без тела.\nСмыслом задания является приведение содержательного доказательства/определения.\n *)\n\n(*\nИерархия типов данных в Coq такова:\nSet - всякие данные (те самые сеты)\nProp - утверждения пропозициональной логики.\nType - тип для Set и Prop\nВообще, бывают Type(i) - всевозможных рангов до бесконечности, и работает\nследующее:\nSet : Type(1)\nProp : Type(1)\nType(i) : Type(i + 1)\n\nTO READ: Reference manual, 4.1.1\n\nВ Coq уже встроено большое количество стандартных структур данных,\nтаких как bool, nat, пары и +-типы. Про них уже доказано куча классных теорем в библиотеке.\nНо в образовательных целях мы переопределим их заново, а так же определим классные множества, \nпро которые рассказывал Миша. *)\n\n(* Для начала нам понадобятся собственные пропозициональные True и False *)\nInductive True' : Prop := I : True'.\nInductive False' : Prop :=.\n\nNotation \"~ A\" := (A -> False') : My_scope.\n\nOpen Scope My_scope.\n\n(* На самом деле, равенство в Coq реализовано именно так, Нет встроенного понятия равенства.\nЕсть только обычный дататайп и немного сахара.\nОтличие от нашего Id, как и раньше, будет заключаться в домене - не Set, а Prop.\n\nInductive eq (A:Type) (x:A) : A -> Prop :=\n    eq_refl : x = x :>A\n\nwhere \"x = y :> A\" := (@eq A x y) : type_scope.\n\nNotation \"x = y\" := (x = y :>_) : type_scope.\n*)\n\nInductive Id {A : Type} (a : A) : A -> Type :=\n  id : Id a a.\n\nInfix \"==\" := Id (at level 70) : My_scope.\nNotation \"x /= y\" := (~ (x == y)) (at level 70) : My_scope.\n\n(* Сделаем собственные пропозициональные Or и And *)\n\nInductive And (A B : Prop) : Prop :=\n  conj' : A -> B -> And A B.\n\nImplicit Arguments conj'.\n\nInductive Or (A B : Prop) : Prop :=\n  inl' : A -> Or A B\n| inr' : B -> Or A B.\n\nImplicit Arguments inl'.\nImplicit Arguments inr'.\n\nInfix \"/.\\\" := And (at level 80, right associativity) : My_scope.\nInfix \"\\./\" := Or (at level 85, right associativity) : My_scope.\n\n(* И теперь Bool *)\nInductive Bool : Set :=\n| true' : Bool\n| false' : Bool.\n\n(* Свой bool у нас есть, смоделируем собственную конструкцию if *)\nDefinition if' (C : Bool -> Set) (b : Bool) (c1 : C true') (c2 : C false') : C b :=\n  match b with\n    true' => c1\n  | false' => c2\n  end.\n\nSection Elimination_proof.\n  Variable C : Bool -> Set.\n  Variable b : Bool.\n  Variable c1 : C true'.\n  Variable c2 : C false'.\n\n  Theorem eliminate_if' : (if' C true' c1 c2) == c1 /.\\ (if' C false' c1 c2) == c2.\n  Proof.\n    simpl.\n    exact (conj' (id c1) (id c2)).\n  Qed.\nEnd Elimination_proof.\n\nDefinition Is_true (a : Bool) := if a then True' else False'.\n\nDefinition or' (a b : Bool) : Bool :=\n  match a with\n    true' => true'\n  | false' => b\n  end.\n\nDefinition and' (a b : Bool) : Bool :=\n  match a with\n    true' => b\n  | false' => false'\n  end.\n\nInfix \"||\" := or' : My_scope. \nInfix \"&&\" := and' : My_scope. \n\n(* Первая содержательная теорема - коммутативность || *)\nTheorem or_commutes : forall a b : Bool, a || b == b || a.\nProof.\n  intros a b.\n  case a, b.\n  simpl.\n  exact (id true').\n  simpl.\n  exact (id true').\n  simpl.\n  exact (id true').\n  simpl.\n  exact (id false').\nQed.\n(* То же можно доказать про * *)\n\n(* Empty set *)\n(* Это, по сути, то же самое, что встроенный False, только не из Prop, а из Set. -- необитаемый тип *)\nInductive Empty : Set :=.\n\n(* Числа Пеано *)\nInductive Nat : Set :=\n| zero : Nat\n| succ : Nat -> Nat.\n\nFixpoint natrec\n         (C : Nat -> Set)\n         (d : C zero)\n         (e : forall (x:Nat) (y:C x), C (succ x)) (n : Nat)\n  : C n :=\n  match n with\n    zero => d\n  | succ n' => e n' (natrec C d e n')\n  end.\n\nDefinition plus' (n m : Nat) : Nat :=\n  natrec (fun _ => Nat) n (fun _ y => succ y) m.\n\nDefinition mul' (n m : Nat) : Nat :=\n  natrec (fun _ => Nat) zero (fun _ y => plus' y n) m.\n\nInfix \"+\" := plus' : My_scope.\nInfix \"*\" := mul' : My_scope.\n\n(* Докажем пару классных теорем про чиселки *)\nTheorem zero_neutral_right : forall n : Nat, n + zero == n.\nProof.\n  intros n.\n  unfold plus'.\n  simpl.\n  exact (id n).\nQed.\n\n(* Это было просто, видимо, тут будет так же просто, верно? А вот не совсем! *)\nTheorem zero_neutral_left : forall n : Nat, zero + n == n.\nProof.\n  intros n.\n  unfold plus'.\n  elim n.\n  (* base *)\n  simpl.\n  exact (id zero).\n  (* shift *)\n  intros n0.\n  intros ind_hypo.\n  simpl.\n  rewrite ind_hypo.\n  exact (id (succ n0)).\nQed.\n\n(* Нам пришлось воспользоваться индукцией (правило elim), чтобы доказать это утверждение. Это из-за устройства функции natrec: она матчится по второму аргументу, поэтому, если второй аргумент равен 0, то ее можно легко упростить. *)\n\n(* Теперь теоремка повеселее. *)\nTheorem plus'_commutes : forall n m, n + m == m + n.\nProof.\n  intros n m.\n  elim n.\n  (* base *)\n  simpl.\n  exact (zero_neutral_left m).\n  (* shift *)\n  unfold plus'.\n  intros n0.\n  intros ind_hyp_n.\n  simpl.\n  rewrite <- ind_hyp_n.\n  elim m.\n  (* base *)\n  simpl.\n  exact (id (succ n0)).\n  (* shift *)\n  intros n1.\n  intros ind_hyp_m.\n  simpl.\n  rewrite ind_hyp_m.\n  exact (id (succ (succ (n0 + n1)))).\nQed.\n\n(* HW: Ассоциативность сложения *)\nTheorem plus'_associates : forall a b c, (a + b) + c == a + (b + c).\nProof.\n  admit.\nQed.\n\n(* HW: Коммутативность умножения *)\nTheorem mul'_commutes : forall a b, a * b == b * a.\nProof.\n  admit.\nQed.\n\n(* HW: Дистрибутивность умножения по отношению к сложению *)\nTheorem mul'_distributes_over_plus' : forall a b c, a * (b + c) == a * b + a * c.\nProof.\n  admit.\nQed.\n\n(* Простые пары *)\nInductive andS (A B : Set) : Set :=\n  conjS : A -> B -> andS A B.\n\nDefinition fst (A B : Set) (p : andS A B) :=\n  match p with conjS a _ => a end.\n\nDefinition snd (A B : Set) (p : andS A B) :=\n  match p with conjS _ b => b end.\n\n(* П-типы *)\nInductive Pi (A : Set) (B : A -> Set) : Set :=\n  lambda : (forall x : A, B x) -> Pi A B.\n\nDefinition apply' (A : Set) (B : A -> Set) (g : Pi A B) (a : A) : B a :=\n  match g with\n    lambda f => f a\n  end.\n\n(* Мы умеем делать синтаксический сахар для наших конструкций *)\n\nNotation \"A ~> B\" := (Pi A (fun _ => B)) (at level 90, right associativity) : My_scope.\nNotation \"~' A\" := (A ~> Empty) (at level 75, right associativity) : My_scope.\n\nDefinition lambda' (A:Set) (B:Set) (f: forall a: A, B) : A ~> B :=\n  lambda A (fun _ => B) f.\n\nDefinition apply'' (A:Set) (B:Set) (g: A ~> B) (a : A) : B :=\n  apply' A (fun _ => B) g a.\n\n(* Теперь докажем, что тип A -> ~~A обитаем! *)\nTheorem remove_double_not_inhabitable : forall A : Set, A ~> ~'~'A.\nProof.\n  intros A.\n  exact (lambda' A (~'~'A)\n                 (fun x => lambda' (~'A) Empty\n                                  (fun y => apply'' A Empty y x))).\nQed.\n(* Да, мы просто переписали Мишину конструкцию и все получилось! *)\n\n(* + - тип *)\nInductive orS (A B : Set) : Set :=\n| inlS : A -> orS A B\n| inrS : B -> orS A B.\n\nDefinition when\n           (A B : Set)\n           (C : orS A B -> Set) \n           (p : orS A B)\n           (f : forall x:A, C (inlS A B x))\n           (g : forall y:B, C (inrS A B y)) : C p\n  := match p with\n       inlS a => f a\n     | inrS b => g b\n     end.\n\n(* Sigma - тип *)\n(*\nНа самом деле, в Coq есть сигма-тип, но на Prop-ах. Только он не встроен в язык,\nкак forall, а определяется через него следующим образом:\n\nInductive ex (A:Type) (P:A -> Prop) : Prop :=\n  ex_intro : forall x:A, P x -> ex (A:=A) P.\n\nNotation \"'exists' x .. y , p\" := (ex (fun x => .. (ex (fun y => p)) ..))\n  (at level 200, x binder, right associativity,\n   format \"'[' 'exists'  '/  ' x  ..  y ,  '/  ' p ']'\")\n  : type_scope.\n\nМы сделаем сейчас то же самое, только Type и Prop поменяем на Set - это будет сигма-типа\n*)\n\nInductive Sigma (A : Set) (B : A -> Set) : Set :=\n  pair : forall a : A, forall b : B a, Sigma A B.\n\nDefinition split'\n           (A : Set)\n           (B : A -> Set)\n           (C : Sigma A B -> Set)\n           (d : forall a:A, forall b:B a, C (pair A B a b))\n           (p : Sigma A B) : C p\n  := match p with\n       pair a b => d a b\n     end.\n\nDefinition fst' (A : Set) (B : A -> Set) (p : Sigma A B) : A :=\n  split' A B (fun _ => A) (fun x _ => x) p.\n\nDefinition snd' (A : Set) (B : A -> Set) (p : Sigma A B) : B (fst' A B p) :=\n  split' A B (fun x => B (fst' A B x)) (fun _ y => y) p.\n\n(*\nМы знаем о таком утверждении на кванторах: forall x, ~(P x) -> ~(exists x, P x)\nДокажем такое утверждение для П и ∑ типов: если тип П(A, [x] ¬B(x)) обитаем, то каждому его\nэлементу можно привести в соответствие элемент типа ¬∑(A, B). \n*)\n\n(* HW: Правило замены кванторов для П и ∑-типов *)\nTheorem forall_exists :\n  forall (A:Set) (B : A -> Set),\n    (Pi A (fun x => ~'(B x))) ~> ~'(Sigma A B).\nProof.\n  admit.\nQed.\n\n(* Списки *)\n(*\nСписки есть в стандартной библиотеке Coq. Списки имеют 2 конструктора: nil и cons.\nОднако, мы сделаем свои\n *)\nInductive List (A : Set) : Set :=\n| nil' : List A\n| cons' : A -> List A -> List A.\n\n(* Дефолтный Head в Coq принимает аргумент default на случай пустого списка. *)\nDefinition head (A : Set) (def : A) (l : List A) : A :=\n  match l with\n    nil' => def\n  | cons' x xs => x\n  end.\n\n(* Можно также написать head, который возвращает Maybe A *)\nInductive Maybe (A : Set) : Set :=\n  Nothing : Maybe A\n| Just : A -> Maybe A.\n\nDefinition head' (A : Set) (l : List A) : Maybe A :=\n  match l with\n    nil' => Nothing A\n  | cons' x xs => Just A x\n  end.\n\n(* Однако только в Coq (и подобных ему языках) можно сделать никогда не падающий head,\nпринимающий доказательство непустоты списка *)\n(* HW: Написать всегда работающий head со следующей сигнатурой *)\nDefinition head'' (A : Set) (l : List A) (pr : l /= nil' A) : A.\nProof.\n  admit.\nQed.\n\nDefinition tail (A : Set) (l : List A) : List A :=\n  match l with\n    nil' => nil' A\n  | cons' x xs => xs\n  end.\n\nFixpoint foldr\n         (A : Set)\n         (C : List A -> Set)\n         (c : C (nil' A))\n         (e : forall (x:A) (y:List A) (z:C y), C (cons' A x y))\n         (l : List A) : C l\n  := match l with\n       nil' => c\n     | cons' a l' => e a l' (foldr A C c e l')\n     end.\n\n(*\nНаконец пошла нормальная теория.\nСейчас мы введем множество абстрактных математических понятий насчет отношений.\nИз этих очень абстрактных понятий мы сможем вывести массу полезнейших утверждений.\n*)\n\n(* Введем понятие *отношения* над множествами *)\nSection Relation_definitions.\n  Variable A : Type.\n  Definition Relation (S : Type) := S -> S -> Prop.\n  Variable R : Relation A.\n\n  (* Определим основные свойства отношений, которые нам нужны *)\n  Section General_Properties_of_Relations.\n    Definition reflexive : Prop := forall x:A, R x x.\n    Definition transitive : Prop := forall x y z:A, R x y -> R y z -> R x z.\n    Definition symmetric : Prop := forall x y:A, R x y -> R y x.\n    Definition antisymmetric : Prop := forall x y:A, R x y -> R y x -> x == y.\n    \n    (* Определение отношения эквивалентности *)\n    Definition equiv := reflexive /.\\ transitive /.\\ symmetric.\n  End General_Properties_of_Relations.\n\n  Section Meta_relations.\n    (* Определение отношения \"меньше\" (включения) на отношениях *)\n    Definition inclusion (R1 R2: Relation A) : Prop := forall x y:A, R1 x y -> R2 x y.\n\n    (* Равенство отношений *)\n    Definition equal_rels (R1 R2: Relation A) : Prop := inclusion R1 R2 /.\\ inclusion R2 R1.\n\n  End Meta_relations.\n\nEnd Relation_definitions.\n\n(* Экстенциональность функции - очень классное свойство, которое позволяет сохранять\nотношение эквивалентности между элементами при их отображении куда-то *)\nSection Extensionality_definition.\n  Variable A B : Type.\n  Variable R1 : Relation A.\n  Variable R2 : Relation B.\n  \n  Definition extensional (f:A -> B) := forall x y:A, R1 x y -> R2 (f x) (f y).\n\nEnd Extensionality_definition.\n\n(*\nHW: Доказать следующую теорему:\nМинимальное рефлексивное отношение\nа) является отношением эквивалентности\nб) таково, что для любого множества B и отношения эквивалентности на нем R2 любая функция f: A -> B экстенциональна по отношению к нашему отношению и отношению R2.\n*)\nSection Theorem_about_minimal_relations.\n  Variable A : Type.\n  Variable R : Relation A.\n  Hypothesis reflR : reflexive A R.\n  Hypothesis minR : forall S : Relation A, reflexive A S -> inclusion A R S.\n\n  Theorem min_refl_rel_is_equiv :\n    equiv A R /.\\ \n    forall (B:Type) (R2:Relation B), equiv B R2 -> forall f:A -> B, extensional A B R R2 f.\n  Proof.\n    admit.\n  Qed.\nEnd Theorem_about_minimal_relations.\n\n(* \nHW: Доказать, что отношения равенства отношений является отношением эквивалентности\nХинт: докажите несколько лемм про более простые свойства отношений inclusion и equal_rels \n*)\nTheorem rels_equality_is_equivalence : forall T:Type, equiv (Relation T) (equal_rels T).\nProof.\n  admit.\nQed.\n", "meta": {"author": "flyingleafe", "repo": "HoTT-coq-homeworks", "sha": "b138b109bf53e93f1f028398dfa5373952dafb71", "save_path": "github-repos/coq/flyingleafe-HoTT-coq-homeworks", "path": "github-repos/coq/flyingleafe-HoTT-coq-homeworks/HoTT-coq-homeworks-b138b109bf53e93f1f028398dfa5373952dafb71/HW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7455472853482792}}
{"text": "Theorem plus_id_example : forall n m :nat,\n                            n = m -> n + n = m + m.\nProof.\nintros n m.\nintros H.\nrewrite -> H.\nreflexivity.\nQed.\n\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.\nTheorem plus_1_neq : forall n: nat,\n                       beq_nat (n + 1) 0 = false.\nProof.\nintros n.\ndestruct n.                     (* as [| n'] *)\nreflexivity.\nreflexivity.\nQed.\n\n(* define my Case syntax *)\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\nTheorem andb_true_elim1: forall b c :bool,\n                           andb b c = true -> b = true.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    reflexivity.\n  Case \"b = false\".\n    rewrite <- H.\n    reflexivity.\n  Qed.\n\nTheorem plus_0_r : forall n:nat,\n                     n + 0 = n.\nProof.\n  intros n.\n  induction n as [| n'].\n  reflexivity.\n  simpl.\n  rewrite IHn'.\n  reflexivity.\n  Qed.\n\nTheorem mult_0_r : forall n:nat,\n                     n * 0 = 0.\nProof.\n  intros n.\n  induction n as [| n'].\n  reflexivity.\n  simpl.\n  rewrite IHn'.\n  reflexivity.\n  Qed.\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'].\n  trivial.\n  simpl.\n  rewrite IHn'.\n  reflexivity.\n  Qed.\n\nTheorem plus_comm : forall n m : nat,\n                              n+m=m+n.\nProof.\n  intros n m.\n  induction n as [| n'].\n  trivial.\n  simpl.\n  rewrite IHn'.\n  apply plus_n_Sm.\n  Qed.\n\nFixpoint double (n:nat) :=\n  match n with\n      | O => O\n      | S n' => S (S (double n'))\n  end.\n\n(* binary *)\nInductive binary: Type :=\n  | Z : binary\n  | D : binary -> binary\n  | E : binary -> binary.\n\nFixpoint incb (n:binary) : binary :=\n  match n with\n    | Z => E Z\n    | D x => E x\n    | E x => D (incb x)\n  end.\n\nFixpoint bin_to_nat (b:binary) : nat :=\n  match b with\n    | Z => O\n    | D x => 2 * (bin_to_nat x)\n    | E x => 1+2 * (bin_to_nat x)\n  end.\n\nTheorem incb_bin_to_nat_comm:\n  forall b : binary,\n    bin_to_nat (incb b) = S (bin_to_nat b).\nProof.\n  intros b.\n  induction b.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite IHb.\n  simpl.\n  assert (H: bin_to_nat b + S (bin_to_nat b + 0) = S (bin_to_nat b + (bin_to_nat b + 0))).\n  symmetry.\n  apply plus_n_Sm.\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  intros n.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  apply IHn.\nQed.\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", "meta": {"author": "egejjespersen", "repo": "software_foundation_exercise", "sha": "e2f788ff88b4b6a6cefc3f413e646c8a733232b2", "save_path": "github-repos/coq/egejjespersen-software_foundation_exercise", "path": "github-repos/coq/egejjespersen-software_foundation_exercise/software_foundation_exercise-e2f788ff88b4b6a6cefc3f413e646c8a733232b2/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7454881234741273}}
{"text": "(* Copyright (c) 2022, choukh <choukyuhei@gmail.com> *)\n\nRequire Export Coq.Unicode.Utf8_core.\n\nFixpoint 迭代 {A : Type} (F : A → A) (a : A) (n : nat) : A :=\n  match n with\n  | O => a\n  | S n => F (迭代 F a n)\n  end.\n\nFixpoint f (i : nat) (n : nat) : nat :=\n  match i with\n  | O => S n\n  | S j => 迭代 (f j) n n\n  end.\n\nFact f_0_n : ∀ n, f 0 n = S n.\nProof. reflexivity. Qed.\n\nFact f_1_3 : f 1 3 = f 0 (f 0 (f 0 3)).\nProof. reflexivity. Qed.\n\nFact f_2_3 : f 2 3 = f 1 (f 1 (f 1 3)).\nProof. reflexivity. Qed.\n\nCompute (f 2 10).\nCompute (f 3 2).\n\nFact f_Sn_3 : ∀ n, f (S n) 3 = f n (f n (f n 3)).\nProof. reflexivity. Qed.\n\nDefinition g n := f n n.\n\nDefinition h n := 迭代 g n n.\n", "meta": {"author": "choukh", "repo": "Googology", "sha": "10e283100a0c0d5eeef6e262e15023464c167c8f", "save_path": "github-repos/coq/choukh-Googology", "path": "github-repos/coq/choukh-Googology/Googology-10e283100a0c0d5eeef6e262e15023464c167c8f/Example/FGH_subOmega.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7454881177148005}}
{"text": "Set Implicit Arguments.\n\nRequire Import\n        Discrete.DiscreteType\n        Finite.FinType\n        Tactics.Tactics.\n\nImport ListNotations.\n\nFixpoint cartesian_product {A B : Type}(xs : list A)(ys : list B) :=\n  match xs with\n  | [] => []\n  | x :: xs' => map (fun y => (x , y)) ys ++ cartesian_product xs' ys\n  end.\n\nLemma cartesian_product_nil {A B : Type} (xs : list A) :\n  cartesian_product xs ([] : list B) = []. \nProof.\n  induction xs ; crush.\nQed.\n\n\nSection LEMMAS.\n  Variables A B : discType.\n\n  Lemma count_map (ys : list B) (x1 : A) y :\n    count (map (fun y => (x1,y)) ys) (x1, y) = count ys y.\n  Proof.\n    induction ys ; crush.\n    - simpl. dec ;  congruence.\n  Qed.\n\n  Lemma count_map_zero  (ys : list B) (x' x : A)  y\n    : x' <> x -> count  (map (fun y => (x,y)) ys) (x', y) = 0.\n  Proof.\n    intros ineq. induction ys ; repeat (crush ; dec).\n  Qed.\n\n  Lemma cartesian_product_count (xs : list A) (ys : list B)(x : A)(y : B)\n    : count (cartesian_product xs ys) (x,y) =  count xs x * count ys y.\n  Proof.\n    induction xs as [| x' xs] ; crush.\n    -\n      rewrite count_app. rewrite IHxs. decide (x = x') as [E | E] ; substs.\n      +\n        cbn. fequals*. apply count_map.\n      +\n        rewrite <- plus_O_n. fequals*. now apply count_map_zero.\n  Qed.\nEnd LEMMAS.\n\nLemma cartesian_product_enum_sound (A B : finType) (x : A * B)\n  : count (cartesian_product (elem A) (elem B)) x = 1.\nProof.\n  destruct x as [x y]. rewrite cartesian_product_count.\n  unfold elem. now rewrite !enum_sound.\nQed.\n\nInstance FinTypeC_Prod (A B : finType) : FinTypeC (A ** B).\nProof.\n  econstructor.  apply cartesian_product_enum_sound.\nDefined.\n\nCanonical Structure FinType_Prod (A B : finType) := FinType (A ** B).\n\nNotation \"A (x) B\" := (FinType_Prod A B) (at level 40, left associativity).\n\nLemma cardinality_cartesian_product {A B : finType}\n  : Cardinality (A (x) B) = Cardinality A * Cardinality B.\nProof.\n  cbn. unfold cartesian_product. unfold Cardinality.\n  induction (elem A) ; crush.\n  -\n    cbn.\n    rewrite app_length.\n    rewrite IHl. f_equal. apply map_length.\nQed.\n\n", "meta": {"author": "rodrigogribeiro", "repo": "finite_types", "sha": "27582ce97686654d741bca49a0f091a68a3dc89d", "save_path": "github-repos/coq/rodrigogribeiro-finite_types", "path": "github-repos/coq/rodrigogribeiro-finite_types/finite_types-27582ce97686654d741bca49a0f091a68a3dc89d/Finite/Constructions/CartesianProduct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7454881124305622}}
{"text": "(* We can define our own boolean type *)\nInductive bool : Type :=\n  | true\n  | false.\n\nDefinition negb (b_0:bool) : bool :=\n  match b_0 with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb (b_1:bool) (b_2:bool) : bool :=\n  match b_1 with\n  | true => b_2\n  | false => false\n  end.\n\nDefinition orb (b_1:bool) (b_2:bool) : bool :=\n  match b_1 with\n  | true => true\n  | false => b_2\n  end.\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb2: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb3: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb4: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(* We can also talk about conditionals *)\nDefinition negb' (b:bool) : bool := \n  if b then false\n  else true.\n\nExample test_negb: (negb' false) = true.\nProof. simpl. reflexivity. Qed.\n\n(* Excercises *)\nDefinition nandb (b_1:bool) (b_2:bool) : bool :=\n  negb (andb b_1 b_2).\n\nExample test_nandb1: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\nExample test_nandb2: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb3: (nandb true false) = true.\nProof. simpl. reflexivity. Qed.\nExample test_nandb4: (nandb false false) = true.\nProof. simpl. reflexivity. Qed.\n", "meta": {"author": "hanleyc01", "repo": "soft-foundations", "sha": "59f868db62de7629e8b14b449193c35f21debf12", "save_path": "github-repos/coq/hanleyc01-soft-foundations", "path": "github-repos/coq/hanleyc01-soft-foundations/soft-foundations-59f868db62de7629e8b14b449193c35f21debf12/src/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7454881073639488}}
{"text": "Module natlist.\nRequire Import Arith.\nCheck nat.\nCheck bool.\n\nInductive natlist: Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\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.\n\nFixpoint length (l: natlist): nat :=\n  match l with\n  | nil => O\n  | cons a l' => S (length l')\n  end.\nExample test_length1 : (length []) = 0.\nProof. reflexivity. Qed.\nExample test_length2: (length [1, 2, 3]) = 3.\nProof. reflexivity. Qed.\n\nFixpoint rev (l: natlist) : natlist :=\n  match l with\n  | nil => nil\n  | cons a l1' => (rev l1') ++ [a]\n  end.\nExample test_rev1: (rev [1, 2, 3]) = [3, 2, 1].\nProof. reflexivity. Qed.\nExample test_rev2: (rev [1]) = [1].\nProof. reflexivity. Qed.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2.\n  induction l1 as [| n l1'].\n  reflexivity.\n  simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem app_ass : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3). \nProof.\n  intros l1 l2 l3.\n  induction l1 as [| n l1']. reflexivity.\n  simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nTheorem one_length : forall n: nat,\n  length [n] = 1.\nProof.\n  intro n. simpl. reflexivity. Qed. \nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intro l.\n  induction l as [| n l']. reflexivity.\n  simpl. rewrite -> app_length.\n  SearchRewrite(_ + _ ).\n  rewrite -> Nat.add_comm.\n  rewrite -> one_length. simpl.\n  rewrite -> IHl'. reflexivity. Qed.\n \n\nTheorem app_nil_end : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intro l.\n  induction l as [| n l']. reflexivity.\n  simpl. rewrite -> IHl'. reflexivity. Qed.\n\nTheorem rev_one : forall n : nat,\n  rev [n] = [n].\n Proof. reflexivity. Qed. \n\nTheorem rev_rev_one : forall n : nat,\n  rev (rev [n]) = [n].\n Proof. 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 [| a l1']. simpl. rewrite -> app_nil_end. reflexivity.\n  simpl. rewrite -> IHl1'. rewrite -> app_ass. reflexivity. Qed.\n  \nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intro l.\n  induction l as [| n l']. reflexivity.\n  simpl. rewrite <-  rev_one.\n  rewrite -> distr_rev.\n  rewrite -> rev_rev_one. simpl.\n  rewrite -> IHl'. reflexivity. Qed.\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. reflexivity. Qed.\n\nEnd natlist.\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/natlist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357569, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.7454881049823651}}
{"text": "Record Category :=\n    {\n      (* Basic elements of every category\n         are obects and arrows (morphisms)\n         between them. *)\n\n      (* So we begin with Ob as set of objects *)\n      Ob:     Type;\n    \n      (* Then Hom as family of sets of arrows\n         parametrized by two objects –\n         the begin and the end of an arrow\n\n         For example for objects a and b\n         Hom(a,b) is the set of arrows\n         that starts at a and ends at b *)\n      Hom:    Ob -> Ob -> Type;\n      \n      (* Also there are some propositions about\n         category *)\n\n      (* For every object a there is\n         identity morphism id in Hom(a,a) *)\n      Id:     forall {a},\n                Hom a a;\n\n      (* We can compose arrow. \n         Suppose we have objects a, b, c.\n         And two arrows f in Hom(a,b) and\n         g in Hom(b,c).\n         So, end of f is the start of g.\n         Such arrows are composable.\n         By composing them we get some\n         new arrow h, h in Hom(a,c)\n         *)\n      Comp:   forall {a b c},\n                Hom a b -> Hom b c -> Hom a c;\n      \n      (* Composing any arrow f in Hom(a,b)\n         with Id  arrow we always get f arrow.\n         \n         Though, in Hom(a,a) can be\n         other arrows than Id. *)\n      idl:    forall a b\n                     (f: Hom a b),\n                Comp Id f = f;\n\n      idr:    forall a b\n                     (f: Hom a b),\n                Comp f Id = f;\n\n      (* Associativity rule for composition *)\n      assoc:  forall {a b c d}\n                     (f: Hom a b)\n                     (g: Hom b c)\n                     (h: Hom c d),\n                Comp f (Comp g h) = Comp (Comp f g) h\n    }.\n\n(*\n  Definition OpHom (C : Category) x y := Hom C y x.\n  Variable C : Category.\n  Variable x y : Ob C.\n  Check OpHom C x y.\n  Check Build_Category (Ob C) (OpHom C). *)", "meta": {"author": "vtols", "repo": "Categories", "sha": "e0b2a3e7cbae5fd311608f021f00394bdd1366e5", "save_path": "github-repos/coq/vtols-Categories", "path": "github-repos/coq/vtols-Categories/Categories-e0b2a3e7cbae5fd311608f021f00394bdd1366e5/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7454508581469176}}
{"text": "Require Import String.\nOpen Scope string_scope.\n\nInductive bird : Set :=\n  | app : bird -> bird -> bird.\n\nModule thm_9_2.\n\n  Variable M : bird. (* ものまね鳥を示す変数 *)\n  Variable E : bird. (* ものまね鳥が好きな鳥を示す変数 *)\n\n  (*\n    合成鳥の存在を示すのと同値な仮定\n    (鳥の合成ルールを示す仮定)\n  *)\n  Hypothesis Hc : forall (A B x : bird), app A (app B x) = app (app A B) x.\n\n  (* ものまね鳥の性質を示す仮定 *)\n  Hypothesis Hm : forall (x : bird), app M x = app x x.\n\n  (* ものまね鳥が好きな鳥を示す仮定 *)\n  Hypothesis He : app M E = E. (* ← app M E が、ものまね鳥の性質により、app E E と書けることがカギ *)\n\n  Theorem thm_9_2 :\n    exists (x : bird), app x x = x.\n      (*\n        結論：\n        ある x が存在して、 x x = x となる。\n      *)\n  Proof.\n    exists E.\n    rewrite <- He at 3.\n    rewrite Hm.\n    reflexivity.\n  Qed.\n\n  From mathcomp\n  Require Import ssreflect.\n\n  Theorem thm_9_2_ssr :\n    exists (x : bird), app x x = x.\n      (*\n        結論：\n        ある x が存在して、 x x = x となる。\n      *)\n  Proof.\n    exists E.\n    rewrite -{3} He. (* rewrite <- He at 3.と同じこと。 *)\n    rewrite Hm.\n    done.\n  Qed.\n\nEnd thm_9_2.\n", "meta": {"author": "wakaba2017", "repo": "To_mock_a_mockingbird", "sha": "400d7b452f9e9e8f0b4dff8e4947b731fc29a5bb", "save_path": "github-repos/coq/wakaba2017-To_mock_a_mockingbird", "path": "github-repos/coq/wakaba2017-To_mock_a_mockingbird/To_mock_a_mockingbird-400d7b452f9e9e8f0b4dff8e4947b731fc29a5bb/thm_9_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.745423603620292}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\n\n(**\nFro categories C and C', a functor F : C -> C' consists of an arrow map from\nobjects of C to objects of C' and an arrow map from arrows of C to arrows of C'\nsuch that an arrow h : a -> b is mapped to (F h) : F a -> F b.\n\nFurthermore, we require functors to map identitiies to identities. Additionally,\nthe immage of the coposition of two arrows must be the same as composition of\ntheir images.\n*)\nRecord Functor (C C' : Category) : Type :=\n{\n  (** Object map *)\n  FO : C → C';\n\n  (** Arrow map *)\n  FA : ∀ {a b}, (a –≻ b)%morphism → ((FO a) –≻ (FO b))%morphism;\n\n  (** Mapping of identities *)\n  F_id : ∀ c, FA (id c) = id (FO c);\n\n  (** Functor commuting with composition *)\n  F_compose : ∀ {a b c} (f : (a –≻ b)%morphism) (g : (b –≻ c)%morphism),\n      (FA (g ∘ f) = (FA g) ∘ (FA f))%morphism\n\n  (* F_id and F_compose together state the fact that functors are morphisms of\n categories (preserving the structure of categories!)*)\n}.\n\nArguments FO {_ _} _ _.\nArguments FA {_ _} _ {_ _} _, {_ _} _ _ _ _.\nArguments F_id {_ _} _ _.\nArguments F_compose {_ _} _ {_ _ _} _ _.\n\nNotation \"C –≻ D\" := (Functor C D) : functor_scope.\n\nBind Scope functor_scope with Functor.\n\nNotation \"F '_o'\" := (FO F) : object_scope.\n\nNotation \"F '@_a'\" := (@FA _ _ F) : morphism_scope.\n\nNotation \"F '_a'\" := (FA F) : morphism_scope.\n\nHint Extern 2 => (apply F_id).\n\nLocal Open Scope morphism_scope.\nLocal Open Scope object_scope.\n\nLtac Functor_Simplify :=\n  progress\n    (\n      repeat rewrite F_id;\n      (\n        repeat\n          match goal with\n          | [|- ?F _a ?A = id (?F _o ?x)] =>\n            (rewrite <- F_id; (cbn+idtac))\n          | [|- (id (?F _o ?x)) = ?F _a ?A] =>\n            (rewrite <- F_id; (cbn+idtac))\n          | [|- ?F _a ?A ∘ ?F _a ?B = ?F _a ?C ∘ ?F _a ?D] =>\n            (repeat rewrite <- F_compose; (cbn+idtac))\n          | [|- ?F _a ?A ∘ ?F _a ?B = ?F _a ?C] =>\n            (rewrite <- F_compose; (cbn+idtac))\n          | [|- ?F _a ?C = ?F _a ?A ∘ ?F _a ?B] =>\n            (rewrite <- F_compose; (cbn+idtac))\n          | [|- context [?F _a ?A ∘ ?F _a ?B]] =>\n            (rewrite <- F_compose; (cbn+idtac))\n          end\n      )\n    )\n.\n\nHint Extern 2 => Functor_Simplify.\n\nSection Functor_eq_simplification.\n\n  Context {C C' : Category} (F G : (C –≻ C')%functor).\n\n  (** Two functors are equal if their object maps and arrow maps are. *)\n  Lemma Functor_eq_simplify (Oeq : F _o = G _o) :\n    ((fun x y =>\n        match Oeq in _ = V return ((x –≻ y) → ((V x) –≻ (V y)))%morphism with\n          eq_refl => F  @_a x y\n        end) = G @_a) -> F = G.\n  Proof.\n    destruct F; destruct G.\n    basic_simpl.\n    ElimEq.\n    PIR.\n    trivial.\n  Qed.\n\n  (** Extensionality for arrow maps of functors. *)\n  Theorem FA_extensionality (Oeq : F _o = G _o) :\n    (\n      ∀ (a b : Obj)\n        (h : (a –≻ b)%morphism),\n        (\n          fun x y =>\n            match Oeq in _ = V return\n                  ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n            with\n              eq_refl => F  @_a x y\n            end\n        ) _ _ h = G _a h\n    )\n    →\n    (\n      fun x y =>\n        match Oeq in _ = V return\n              ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n        with\n          eq_refl => F  @_a x y\n        end\n    ) = G @_a.\n  Proof.\n    auto.\n  Qed.\n\n  (** Fucntor extensionality: two functors are equal of their object maps are\n      equal and their arrow maps are extensionally equal. *)\n  Lemma Functor_extensionality (Oeq : F _o = G _o) :\n    (\n      ∀ (a b : Obj) (h : (a –≻ b)%morphism),\n        (\n          fun x y =>\n            match Oeq in _ = V return\n                  ((x –≻ y) → ((V x) –≻ (V y)))%morphism\n            with\n              eq_refl => F  @_a x y\n            end\n        ) _ _ h = G _a h\n    ) → F = G.\n  Proof.\n    intros H.\n    apply (Functor_eq_simplify Oeq); trivial.\n    apply FA_extensionality; trivial.\n  Qed.\n\nEnd Functor_eq_simplification.\n\nHint Extern 2 => Functor_Simplify.\n\nLtac Func_eq_simpl :=\n  match goal with\n    [|- ?A = ?B :> Functor _ _] =>\n    (apply (Functor_eq_simplify A B (eq_refl : A _o = B _o)%object)) +\n    (cut (A _o = B _o)%object; [\n       let u := fresh \"H\" in\n       intros H;\n         apply (Functor_eq_simplify A B H)\n         |\n    ])\n  end.\n\nHint Extern 3 => Func_eq_simpl.\n\nSection Functor_eq.\n  Context {C C' : Category} (F G : (C –≻ C')%functor).\n\n  Lemma Functor_eq_morph (H : F = G) :\n    ∃ (H : ∀ x, F _o x = G _o x),\n    ∀ x y (h : (x –≻ y)%morphism),\n      match H x in _ = V return (V –≻ _)%morphism with\n         eq_refl =>\n         match H y in _ = V return (_ –≻ V)%morphism with\n           eq_refl => F _a h\n         end\n       end = G _a h.\n  Proof.\n    exists (equal_f (f_equal FO H)).\n    intros x y h.\n    destruct H; trivial.\n  Qed.\n\nEnd Functor_eq.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Functor/Functor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8652240704135291, "lm_q1q2_score": 0.7454235933047264}}
{"text": "\n\n\n(* -----------------Description------------------------------------------\n\nThis file contains useful results about reflection techniques in Coq. \nSome of the important concepts formalized are:\n\nDefinition Prop_bool_eq (P: Prop) (b: bool):= P <-> b=true.\nLemma reflect_intro (P:Prop)(b:bool): Prop_bool_eq P b -> reflect P b.\n\nLemma impP(p q:bool): reflect (p->q)((negb p) || q).\nLemma switch1(b:bool): b=false -> ~ b. \nLemma switch2(b:bool): ~ b -> b=false.\n\n\nSome useful Ltac defined terms:\n\n Ltac switch:=  (apply switch1||apply switch2).\n Ltac switch_in H:= (apply switch1 in H || apply switch2 in H).\n Ltac right_ := apply /orP; right.\n Ltac left_ := apply /orP; left.\n Ltac split_ := apply /andP; split.   \n\n--------------------- ------------------- ------------------------------*)\n\n\n\nFrom Coq Require Export ssreflect  ssrbool.\n\nRequire Export Omega.\n\n\nSet Implicit Arguments.\n\nSection GeneralReflections.\nDefinition Prop_bool_eq (P: Prop) (b: bool):= P <-> b=true.\n\n(* Inductive reflect (P : Prop) : bool -> Set :=  \n   ReflectT : P -> reflect P true | ReflectF : ~ P -> reflect P false *)\nLemma reflect_elim (P:Prop)(b: bool): reflect P b -> Prop_bool_eq P b.\nProof. { intro H.\n       split. case H; [ auto | discriminate || contradiction ].\n       case H; [ auto | discriminate || contradiction ]. } Qed. \nLemma reflect_intro (P:Prop)(b:bool): Prop_bool_eq P b -> reflect P b.\nProof. { intros. destruct H as  [H1 H2].\n         destruct b. constructor;auto.\n         constructor.  intro H. apply H1 in H;inversion H. } Qed.\n\nLemma reflect_dec P: forall b:bool, reflect P b -> {P} + {~P}.\nProof. intros b H; destruct b; inversion H; auto.  Qed.\nLemma reflect_EM P: forall b:bool, reflect P b -> P \\/ ~P.\nProof. intros b H. case H; tauto. Qed.\nLemma dec_EM P: {P}+{~P} -> P \\/ ~P.\n  Proof. intro H; destruct H as [Hl |Hr];tauto. Qed.\nLemma pbe_EM P: forall b:bool, Prop_bool_eq P b -> P \\/ ~P.\nProof. { intros b H; cut( reflect P b).\n         apply reflect_EM. apply reflect_intro;auto. } Qed.\n\n\n(* iffP : forall (P Q : Prop) (b : bool), reflect P b -> (P -> Q) -> (Q -> P) -> reflect Q b *)\n\n(* idP : forall b1 : bool, reflect b1 b1 *)\n\n(* negP\n     : reflect (~ ?b1) (~~ ?b1) *)\n\n(* andP\n     : reflect (?b1 /\\ ?b2) (?b1 && ?b2) *)\n\n(*orP\n     : reflect (?b1 \\/ ?b2) (?b1 || ?b2) *)\nLemma impP(p q:bool): reflect (p->q)((negb p) || q).\n  Proof. { case p eqn:pH; case q eqn:qH; simpl.\n       constructor. auto. \n       constructor. intro H2. cut (false=true). discriminate. apply H2. auto. \n       constructor. auto. \n       constructor. discriminate. } Qed. \nLemma impP1(P Q:Prop)(p q:bool)(HP: reflect P p)(HQ: reflect Q q):  reflect (P->Q)((negb p) || q).\nProof. { case p eqn:pH; case q eqn:qH; simpl.\n       constructor. move /HP. apply /HQ.\n       constructor. intro H2. absurd (Q). move /HQ. discriminate. apply H2; apply /HP;auto.\n       constructor. move /HP. discriminate.\n       constructor. move /HP. discriminate. } Qed.\nLemma switch1(b:bool): b=false -> ~ b.\nProof. intros H H1.  rewrite H1 in H. discriminate H. Qed.\nLemma switch2(b:bool): ~ b -> b=false.\nProof. intros H. case b eqn:H1. absurd (true);auto. auto. Qed.\n\nLemma bool_fun_equal (B1 B2: bool): (B1-> B2)-> (B2-> B1)-> B1=B2.\n    Proof. intros H1 H2. destruct B1; destruct B2; auto.\n           replace false with true. auto. symmetry; auto. Qed.\n\n    Hint Resolve bool_fun_equal: core.\n\nEnd GeneralReflections.\n\n\nHint Immediate reflect_intro reflect_elim  reflect_EM reflect_dec dec_EM: core.\nHint Resolve idP impP impP1: core.\nHint Resolve bool_fun_equal: core.\n\nLtac solve_dec := eapply reflect_dec; eauto.\nLtac solve_EM  := eapply reflect_EM; eauto.\n\nLtac switch:=  (apply switch1||apply switch2).\nLtac switch_in H:= (apply switch1 in H || apply switch2 in H).\n\nLtac right_ := apply /orP; right.\nLtac left_ := apply /orP; left.\nLtac split_ := apply /andP; split.\n\n\nSection NaturalNumbers.\n\nLemma ltP (x y:nat): reflect (x < y) (Nat.ltb x y).\nProof. { apply reflect_intro. split.\n       { unfold \"<\".  unfold \"<?\". \n         revert y. induction x. intro y; case y. simpl.\n         intro H. inversion H. simpl. auto.\n         intro y;case y.\n         intro H; inversion H. intros n H. \n         replace (S (S x) <=?  S n) with (S x <=? n). apply IHx. omega.\n         simpl. auto. }\n       { unfold \"<\"; unfold \"<?\".\n         revert y. induction x. intro y; case y. simpl.\n         intro H. inversion H. intros; omega.\n         intro y;case y. simpl. intro H; inversion H.\n         intro n. replace (S (S x) <=? S n) with (S x <=? n).\n         intro H; apply IHx in H. omega. simpl;auto. } } Qed.\n\nLemma leP (x y: nat): reflect (x <= y) (Nat.leb x y).\nProof. { apply reflect_intro. split.\n       { revert y. induction x. intro y; case y; simpl; auto.\n         intro y;case y.\n         intro H; inversion H. intros n H. \n         replace (S  x <=? S n) with ( x <=? n). apply IHx. omega.\n         simpl. auto. }\n       { revert y. induction x. intro y; case y; intros; omega. \n         intro y;case y. simpl. intro H; inversion H.\n         intro n. replace (S x <=? S n) with ( x <=? n).\n         intro H; apply IHx in H. omega. simpl;auto. } } Qed.\n\nLemma nat_reflexive: reflexive Nat.leb.\n  Proof. unfold reflexive; induction x; simpl; auto. Qed.\n\nLemma nat_transitive: transitive Nat.leb.\nProof. unfold transitive. intros x y z h1 h2. move /leP in h1. move /leP in h2.\n         apply /leP. omega. Qed.\n\nHint Resolve leP ltP nat_reflexive nat_transitive: core.\n\nEnd NaturalNumbers.\n\nHint Resolve leP ltP nat_reflexive nat_transitive: core.", "meta": {"author": "suneel-sarswat", "repo": "auction", "sha": "f63a5cd162be642c590db86c41ee855d9d761d49", "save_path": "github-repos/coq/suneel-sarswat-auction", "path": "github-repos/coq/suneel-sarswat-auction/auction-f63a5cd162be642c590db86c41ee855d9d761d49/GenReflect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.74542358557384}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint plus (plus_arg0 : Nat) (plus_arg1 : Nat) : Nat\n           := match plus_arg0, plus_arg1 with\n              | zero, n => n\n              | succ n, m => succ (plus n m)\n              end.\n\nFixpoint half (half_arg0 : Nat) : Nat\n           := match half_arg0 with\n              | zero => zero\n              | succ zero => zero\n              | succ (succ n) => succ (half n)\n              end.\n\nTheorem plus_comm: forall (n m: Nat), plus n m = plus m n.\nProof.\n  induction n; induction m.\n  { simpl. rewrite IHn. rewrite <- IHm. simpl. rewrite IHn. reflexivity. }\n  { simpl. rewrite IHn. simpl. reflexivity. }\n  { simpl. rewrite <- IHm. simpl. reflexivity. }\n  { reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : Nat) (y : Nat), eq (half (plus x y)) (half (plus y x)).\nProof.\n  intros.\n  rewrite plus_comm.\n  reflexivity.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal26.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7453950406260299}}
{"text": "(*this time w the ensembles library*)\nRequire Import Reals.\nRequire Import Lra.\nRequire Import Ensembles.\nRequire Image.\nLocal Open Scope R_scope.\nDefinition Image (A : Ensemble R) (f : R -> R) : Ensemble R :=\n  Image.Im R R A f.\n\n\nDefinition closed_unit_interval : Ensemble R :=\n  fun x => 0 <= x <= 1.\n\nDefinition three_x : R -> R := fun x => 3*x.\n(*continuity*)\nDefinition neighborhood (eps : R) (point : R) : Ensemble R :=\n  fun x =>\n    point - eps <= x <= point + eps.\n\nCheck In R (neighborhood 1 1).\n\n\n\nDefinition continuous_c (f : R -> R) (c : R) : Prop :=\n  forall (eps : R), exists (delt : R),\n      eps > 0 -> delt > 0 ->\n      forall x, (neighborhood delt c) x ->\n           (neighborhood eps (f c)) (f x).\n\nDefinition continuous (f : R -> R) (A : Ensemble R) : Prop :=\n  forall (c : R), A c -> continuous_c f c.\n\nTheorem three_x_continuous : continuous three_x closed_unit_interval.\nProof.\n  unfold continuous, continuous_c; intros.\n  exists (eps / 3). intros. unfold three_x.\n  unfold neighborhood in *.\n  lra.\nQed.\n\n(*compactness*)\nDefinition open (A : Ensemble R) : Prop :=\n  forall x, exists eps,\n      A x -> eps > 0 ->\n      Included R (neighborhood eps x) A.\n\nDefinition closed (A : Ensemble R) : Prop :=\n  open (Complement R A).\n\nTheorem closed_unit_interval_closed : closed closed_unit_interval.\nProof.\n  unfold closed, open, Complement, closed_unit_interval; intros.\n  assert (G : closed_unit_interval 1). { unfold closed_unit_interval. lra. }\n  exists 0.\n  unfold not, included, neighborhood, Included, In; intros.\n  lra.\nQed.\n\n\nDefinition bounded_above (A : Ensemble R) : Prop :=\n  exists (b : R), forall x, A x -> x <= b.\n\nDefinition bounded_below (A : Ensemble R) : Prop :=\n  exists (b : R), forall x, A x -> b <= x.\n\nDefinition bounded (A : Ensemble R) : Prop :=\n  bounded_above A /\\ bounded_below A.\n\nLtac show_boundedness bounded_side A x :=\n  unfold bounded_side, A; exists x; intros; lra.\n\nTheorem closed_unit_interval_bounded : bounded closed_unit_interval.\nProof.\n  unfold bounded; split.\n  - show_boundedness bounded_above closed_unit_interval 1.\n  - show_boundedness bounded_below closed_unit_interval 0.\nQed.\n\nDefinition compact (A : Ensemble R) : Prop :=\n  closed A /\\ bounded A.\n\nTheorem closed_unit_interval_compact : compact closed_unit_interval.\nProof.\n  unfold compact; split.\n  - apply closed_unit_interval_closed.\n  - apply closed_unit_interval_bounded.\nQed.\n\n(*preservation*)\nDefinition compact_image (f : R -> R) (A : Ensemble R) : Prop :=\n  (*won't be provable if f isn't continuous or A isn't compact*)\n  compact (Image A f).\n\nTheorem three_x_preserves_compactness : compact_image three_x closed_unit_interval.\nProof.\n  unfold compact_image.\n  unfold compact.\n  split.\n  { unfold closed.\n    unfold open, Complement.\n    intro x.\n    exists 0.\n    intros H1 H2.\n    lra.\n  }\n  { unfold bounded.\n    split.\n    - unfold bounded_above; exists 3; intros x H; unfold closed_unit_interval, three_x in H.\n      destruct H. unfold In in H. lra.\n    - unfold bounded_below; exists 0; intros x H; unfold closed_unit_interval, three_x in H.\n      destruct H. unfold In in H. lra.\n  }\nQed.\n\n\n\nDefinition f_attains_max_and_min (f : R -> R) (A : Ensemble R) : Prop :=\n  continuous f A -> compact A ->\n  exists (fmin fmax : R), forall (y : R), Image A f y -> fmin <= y <= fmax.\n\nTheorem three_x_attains_max_and_min :\n  f_attains_max_and_min three_x closed_unit_interval.\n  unfold f_attains_max_and_min.\n  intros H1 H2.\n  exists 0, 3;\n    intros.\n    inversion H;\n    unfold In, closed_unit_interval in H0;\n    unfold three_x in H3;\n    lra.\nQed.\n\nTheorem preservation_of_compactness :\n  forall (f : R -> R) (A : Ensemble R),\n    continuous f A -> compact A ->\n    compact_image f A.\nProof.\n  intros f A H G.\n  unfold compact_image.\n  unfold compact.\n  split.\n  { unfold closed, open, Complement.\n    intros x.\n    exists 0.\n    intros F E.\n    lra.\n  }\n  { assert (J : f_attains_max_and_min f A).\n    { unfold f_attains_max_and_min.\n      intros _ _.\n      unfold compact, bounded in G; destruct G as [G1 [G2 G3]].\n      destruct G2 as [b__up G2].\n      destruct G3 as [b__low G3].\n\n\n\n\n\n      eexists. eexists.\n      intros y F.\n      split.\n      - remember (y-1) as fmin.\n        assert (J1 : fmin <= y). lra.\n        give_up.\n      - give_up.\n    }\n    unfold f_attains_max_and_min in J.\n    specialize (J H G).\n    destruct J as [fmin [fmax J']].\n    unfold compact, bounded in G; destruct G as [G1 [G2 G3]].\n    destruct G2 as [b__up G2].\n    destruct G3 as [b__low G3].\n    split.\n    { unfold bounded_above;\n        exists fmax;\n        intros y F;\n        inversion F as [x' F1 y' F2 F3];\n        unfold In in F1.\n      destruct (J' y) as [J'1 J'2]. apply F.\n      apply J'2.\n    }\n    { unfold bounded_below;\n        exists fmin;\n        intros y F;\n        inversion F as [x' F1 y' F2 F3];\n        unfold In in F1.\n      destruct (J' y) as [J'1 J'2]. apply F.\n      apply J'1.\n    }\n  }\n", "meta": {"author": "quinn-dougherty", "repo": "rca", "sha": "e5d5344e2880e80a3ac395772db7fc193566a63c", "save_path": "github-repos/coq/quinn-dougherty-rca", "path": "github-repos/coq/quinn-dougherty-rca/rca-e5d5344e2880e80a3ac395772db7fc193566a63c/roll-my-own/preservation_of_compactness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7453950280033488}}
{"text": "Add LoadPath \"/Users/kfischer/Documents/CS250/cpdtlib\".\n\nRequire Import Bool Arith String List CpdtTactics.\nRequire Import FunctionalExtensionality.\nOpen Scope string_scope.\n\nDefinition var := string.\n\nInductive binop := Plus | Times | Minus.\n\nInductive aexp : Type := \n| Const : nat -> aexp\n| Var : var -> aexp\n| Binop : aexp -> binop -> aexp -> aexp.\n\nInductive bexp : Type := \n| Tt : bexp\n| Ff : bexp\n| Eq : aexp -> aexp -> bexp\n| Lt : aexp -> aexp -> bexp\n| And : bexp -> bexp -> bexp\n| Or : bexp -> bexp -> bexp\n| Not : bexp -> bexp.\n\nInductive com : Type := \n| Skip : com\n| Assign : var -> aexp -> com\n| Seq : com -> com -> com\n| If : bexp -> com -> com -> com\n| While : bexp -> com -> com.\n\nDefinition state := var -> nat.\n\nDefinition get (x:var) (s:state) : nat := s x.\n\nDefinition set (x:var) (n:nat) (s:state) : state := \n  fun y => if string_dec x y then n else get y s.\n\nDefinition eval_binop (b:binop) : nat -> nat -> nat := \n  match b with \n    | Plus => plus\n    | Times => mult\n    | Minus => minus\n  end.\n\nFixpoint eval_aexp (e:aexp) (s:state) : nat := \n  match e with \n    | Const n => n\n    | Var x => get x s\n    | Binop e1 b e2 => (eval_binop b) (eval_aexp e1 s) (eval_aexp e2 s)\n  end.\n\nFixpoint eval_bexp (b:bexp) (s:state) : bool := \n  match b with \n    | Tt => true\n    | Ff => false\n    | Eq e1 e2 => NPeano.Nat.eqb (eval_aexp e1 s) (eval_aexp e2 s)\n    | Lt e1 e2 => NPeano.ltb (eval_aexp e1 s) (eval_aexp e2 s)\n    | And b1 b2 => eval_bexp b1 s && eval_bexp b2 s\n    | Or b1 b2 => eval_bexp b1 s || eval_bexp b2 s\n    | Not b => negb (eval_bexp b s)\n  end.\n\nInductive eval_com : com -> state -> state -> Prop := \n| Eval_skip : forall s, eval_com Skip s s\n| Eval_assign : forall s x e, eval_com (Assign x e) s (set x (eval_aexp e s) s)\n| Eval_seq : forall c1 s0 s1 c2 s2, \n               eval_com c1 s0 s1 -> eval_com c2 s1 s2 -> \n               eval_com (Seq c1 c2) s0 s2\n| Eval_if_true : forall b c1 c2 s s',\n                   eval_bexp b s = true -> \n                   eval_com c1 s s' -> eval_com (If b c1 c2) s s'\n| Eval_if_false : forall b c1 c2 s s',\n                   eval_bexp b s = false -> \n                   eval_com c2 s s' -> eval_com (If b c1 c2) s s'\n| Eval_while_false : forall b c s, \n                       eval_bexp b s = false -> \n                       eval_com (While b c) s s\n| Eval_while_true : forall b c s1 s2 s3, \n                      eval_bexp b s1 = true -> \n                      eval_com c s1 s2 -> \n                      eval_com (While b c) s2 s3 -> \n                      eval_com (While b c) s1 s3.\n\nHint Constructors eval_com.\n\n(* Write a function ieval_com : nat -> com -> state -> option state\n   which takes \"fuel\" as an argument and tries to run the command\n   for fuel-number of steps.  If the command terminates in that time,\n   then you should return the resulting state, and if it doesn't\n   terminate in that time, you should return None.  \n*)\n\nFixpoint ieval_com (n:nat) (c:com) (s:state) : option state :=\nmatch n with \n| O => None\n| S m => match c with\n    | Skip => Some s\n    | Assign x e => Some (set x (eval_aexp e s) s)\n    | Seq c1 c2 => match (ieval_com m c1 s) with\n      | Some s' => (ieval_com m c2 s')\n      | None => None\n    end\n    | If b c1 c2 => if (eval_bexp b s) then \n      (ieval_com m c1 s) \n      else (ieval_com m c2 s)\n    | While b c1 => if (eval_bexp b s) then\n      (ieval_com m (Seq c1 c) s)\n      else Some s\n    end\nend.\n\n\n(* Prove that :\n\n   eval_com c s1 s2 -> exists n, ieval_com n c s1 = Some s2.\n\n*)\n\nLemma terminates : forall n c s1 s2, ieval_com n c s1 = Some s2 -> n<>0. crush. Qed.\nLemma neq : forall n, n<>0 <-> exists m, n = S m.\ncrush. destruct n. crush. exists n. reflexivity. Qed.\n\nLtac _aterm H id := assert (id := H); apply terminates in id.\nLtac aterm H := let id:=fresh in _aterm H id.\nLtac aterm2 H := let id:=fresh in _aterm H id; apply neq in id; destruct id; rewrite id in *.\n\nLemma ieval_seq : forall n c1 c2 s1 s2 s3,\n       ieval_com n c1 s1 = Some s3 -> ieval_com n c2 s3 = Some s2 -> ieval_com (S n) (Seq c1 c2) s1 = Some s2.\n  intros. crush.\nQed.\n\nLemma ieval_iseq : forall n c1 c2 s1 s2 s3,\n       ieval_com (S n) (Seq c1 c2) s1 = Some s3 -> ieval_com n c1 s1 = Some s2 -> ieval_com n c2 s2 = Some s3.\n  intros. rewrite <- H. crush.\nQed.\n\nHint Resolve ieval_seq.\n\nTactic Notation \"unroll_ieval_com\" \"in\" constr(H) := \n  match type of H with \n    | ieval_com (S ?X) _ _ = _ => let y:=fresh in let Heqy:=fresh in remember X as y eqn:Heqy; simpl ieval_com in H; rewrite Heqy in *; clear Heqy\n  end.\n\nLtac unroll_ieval_com := \n  match goal with\n    | [ |- ieval_com (S ?X) _ _ = _ ] => let y:=fresh in let Heqy:=fresh in remember X as y eqn:Heqy; simpl ieval_com; rewrite Heqy in *; clear Heqy\n    | [ H: context[ieval_com (S ?X) _ _] |- _ ] => unroll_ieval_com in H\n  end.\n\nLtac clean :=\n  repeat match goal with\n    | [ H: ?m = S ?n |- _ ] => rewrite H in *; clear H\n    | [ H: S ?m = ?n |- _ ] => rewrite <- H in *; clear H\nend.\n\nLtac cond_simpl c := let cond:=fresh in remember c as cond; destruct cond; simpl.\n\nLemma seq_term : forall n c1 c2 s1 s2, ieval_com (S n) (Seq c1 c2) s1 = Some s2 ->\n         exists s', ieval_com n c1 s1 = Some s'.\n  crush. cond_simpl (ieval_com n c1 s1). crush. exists s. crush. crush.\nQed.\n\nLemma ieval_plus : forall n c s1 s2, \n       ieval_com n c s1 = Some s2 -> \n         forall m, ieval_com (n + m) c s1 = Some s2.\nintros.\nLemma ieval_plus' : forall n c s1 s2, \n       ieval_com n c s1 = Some s2 -> ieval_com (n + 1) c s1 = Some s2.\n  intro n; induction n.\n  (* Base Case *)\n    intros. crush.\n  (* Induction *)\n    intros; rewrite plus_comm in *; rewrite NPeano.Nat.add_succ_r in *; \n      simpl plus in *.\n    unroll_ieval_com.\n    remember (S n) as m.\n    destruct c. crush. crush.\n    (* Begin SEQ *)\n      cond_simpl (ieval_com m c1 s1). clean.\n      assert (H2 := H). assert (IHn2 := IHn).\n      apply seq_term in H.\n      destruct H. assert (H3 := H).\n      specialize IHn with (c:=c1) (s1:=s1) (s2:=x).\n      apply IHn in H. rewrite <- HeqH1 in H.\n      injection H; intros; rewrite <- H1 in *; clear H1; clear H.\n      apply ieval_iseq with (c2:=c2) (s3:=s2) (s2:=s) in H2.\n      specialize IHn2 with (c:=c2) (s1:=s) (s2:=s2); apply IHn2 in H2;\n         assumption.\n      assumption.\n      clean; apply seq_term in H; destruct H.\n      specialize IHn with (c:=c1) (s1:=s1) (s2:=x); apply IHn in H.\n      contradict HeqH1. crush.\n    (* End SEQ *)\n      cond_simpl (eval_bexp b s1); clean; apply IHn with (s2:=s2); \n        rewrite <- H; simpl; rewrite <- HeqH1; reflexivity.\n    (* End IF *)\n      cond_simpl (eval_bexp b s1); clean.\n      remember ((Seq c (While b c))) as c2. apply IHn. rewrite <- H.\n      simpl. rewrite <- HeqH1. rewrite <- Heqc2. reflexivity.\n      rewrite <- H. simpl. rewrite <- HeqH1. reflexivity.\n  Qed.\n  induction m.\n  rewrite plus_comm; simpl; rewrite H; reflexivity.\n  assert ( n + S m = ((n + m) + 1) ). crush.\n  rewrite H0; apply ieval_plus'; assumption.\nQed.\n\nLtac destruct_inds IHeval_com1 IHeval_com2 :=\n  destruct IHeval_com1 as [x IH1]; destruct IHeval_com2 as [x0 IH2];\n  aterm IH1; aterm IH2; assert (x+x0 <> 0) as IS; [ omega | ];\n  apply neq in IS; destruct IS as [x1 Hyp].\n\nTactic Notation \"raise\" constr(x0) := eapply ieval_plus with (n := _) (m := x0).\nTactic Notation \"raise\" := raise 1; rewrite plus_comm; simpl plus.\nTactic Notation \"raise\" constr(x0) \"in\" constr(H) := eapply ieval_plus with (n := _) (m := x0) in H.\nTactic Notation \"raise\" \"in\" constr(H) := raise 1 in H; rewrite plus_comm in H; simpl plus in H.\n\nLemma EvalCom1 : forall c s1 s2, eval_com c s1 s2 -> exists n, ieval_com n c s1 = Some s2.\n    intros.\n    induction H; try solve [\n    (* Skip, Assign, While false *)\n        (exists 1; simpl; try rewrite H; reflexivity) |  \n    (* Ifs *)\n        destruct IHeval_com; exists (S x); simpl; \n        rewrite H; rewrite H1; reflexivity ];\n    (* Common Setup *)\n        destruct_inds IHeval_com1 IHeval_com2;\n    (* Seq *)\n       [( exists (S (S x1)); \n          rewrite <- Hyp; unroll_ieval_com )\n    (* While True *)\n       | (exists (S (S (S x1))); \n         unroll_ieval_com; rewrite <- Hyp; \n         rewrite H; unroll_ieval_com ) ];\n    (* Common cleanup *)\n       raise x0 in IH1; raise x in IH2; \n       rewrite <- plus_comm in IH2; \n       rewrite IH1; rewrite IH2; reflexivity.\nQed.\n\n\n(* Prove that : \n\n   ieval_com n c s1 = Some s2 -> eval_com c s1 s2\n\n*)\n\nLemma EvalCom2 : forall n c s1 s2, ieval_com n c s1 = Some s2 -> eval_com c s1 s2.\nLemma EvalCom2' : forall n c s1 s2, ieval_com (S n) c s1 = Some s2 -> eval_com c s1 s2.\n  intro n. induction n.\n  (* Base Case *)\n    intros; destruct c; crush; \n    remember (eval_bexp b s1) as x; destruct x; crush.\n  (* Induction *)\n    intros.\n    destruct c. crush. crush.\n  (* Seq *)\n    unroll_ieval_com in H.\n    remember (S n) as x in H; simpl ieval_com in H.\n    remember (ieval_com x c1 s1) as y.\n    destruct y. \n    rewrite Heqx in *.\n    assert (IHn2:=IHn).\n    specialize IHn with (c:=c2) (s1:=s) (s2:=s2).\n    specialize IHn2 with (c:=c1) (s1:=s1) (s2:=s).\n    apply IHn in H.\n    apply eq_sym in Heqy.\n    apply IHn2 in Heqy.\n    apply (Eval_seq c1 s1 s c2 s2); assumption.\n    contradict H. crush.\n  (* If *)\n    unroll_ieval_com.\n    cond_simpl (eval_bexp b s1); crush.\n  (* While *) \n    unroll_ieval_com.\n    cond_simpl (eval_bexp b s1).\n    unroll_ieval_com.\n    cond_simpl (ieval_com n c s1).\n    apply (Eval_while_true b c s1 s s2).\n    apply eq_sym; assumption.\n    apply eq_sym in HeqH2; raise in HeqH2; \n      eapply IHn in HeqH2; assumption. \n    raise in H; eapply IHn; assumption.\n    contradict H; crush.\n    crush.\nQed.\nintros; aterm2 H; apply EvalCom2' in H; assumption.\nQed.\n\n(* Write a function\n\n     optimize_com : com -> com\n\n   which tries to optimize a command and the sub-expressions \n   within it.  In particular, your optimizer should at least:\n\n   * replace (a + 0) and (0 + a) with a\n   * replace (a - 0) with a\n   * replace (a * 1) and (1 * a) with a\n   * replace (a * 0) and (0 * a) with 0\n\n   * replace (a == a) with Tt\n   * replace (a < a) with Ff\n   * replace (Tt && Tt) with Tt\n   * replace (Tt || b) and (b || Tt) with Tt\n   * replace (Ff && b) and (b && Ff) with Ff\n\n   * replace (skip ; c) and (c ; skip) with c\n   * replace (if Tt c1 else c2) with c1\n   * replace (if Ff c1 else c2) with c2\n*)\n\nFixpoint optimize_binop (b: binop) (x: aexp) (y: aexp) : aexp :=\n  match b with\n    | Times => match (x,y) with\n      | (a, Const 1) | (Const 1, a) => a\n      | (Const 0, _) | (_, Const 0) => Const 0\n      | (a,b) => (Binop a Times b)\n    end\n    | Plus => match (x,y) with\n      | (a, Const 0) | (Const 0, a) => a\n      | (a,b) => (Binop a Plus b)\n    end\n    | Minus => match (x,y) with\n      | (a, Const 0) => a\n      | (a,b) => (Binop a Minus b)\n    end\n  end.                           \n\nLtac Hammer n := try (destruct n; simpl; try omega).\n\nLemma binop_opt_correct : forall b x y s, eval_aexp (Binop x b y) s = eval_aexp (optimize_binop b x y) s.\n  intros.\n  destruct b; simpl optimize_binop; destruct x;\n  Hammer n; Hammer n0; destruct y;\n  Hammer n; Hammer n; Hammer n0; Hammer n0;\n  simpl; try omega.\nQed.\n \nFixpoint optimize_aexp (a: aexp) : aexp :=\n  match a with\n    | Binop x b y => optimize_binop b (optimize_aexp x) (optimize_aexp y)\n    | _ => a\n  end.\n\nLemma aexpopt_correct : forall a s, eval_aexp a s = eval_aexp (optimize_aexp a) s.\n  intros.\n  induction a; crush.\n  apply binop_opt_correct.\nQed.\n\nDefinition eq_aexp_dec (a1 a2:aexp) : {a1=a2} + {a1<>a2}.\n      decide equality.\n      apply (eq_nat_dec n n0).\n      apply (string_dec v v0).\n      decide equality.\n    Defined.\n\nFixpoint optimize_bexp (b: bexp) : bexp :=\n  match b with\n   | Eq aa ab => let (aa', bb') := ((optimize_aexp aa),(optimize_aexp ab)) in\n     match eq_aexp_dec aa' bb'  with\n        | left P => Tt\n        | right p => Eq aa' bb'\n     end\n   | Lt aa ab => let (aa', bb') := ((optimize_aexp aa),(optimize_aexp ab)) in\n     match eq_aexp_dec aa' bb' with\n      | left P => Ff\n      | right p => Lt aa' bb' \n     end\n   | Not x => match (optimize_bexp x) with\n      | Tt => Ff\n      | Ff => Tt\n      | x => Not x\n   end\n   | Or x y => match (optimize_bexp x, optimize_bexp y) with\n      | (Tt, _) | (_, Tt) => Tt\n      | (Ff, a) | (a, Ff) => a\n      | (a,b) => Or a b\n     end\n   | And x y => match (optimize_bexp x, optimize_bexp y) with\n      | (Tt, a) | (a, Tt) => a\n      | (Ff, _) | (_, Ff) => Ff\n      | (a,b) => And a b\n     end\n    | _ => b\n  end.\n\n(* These are probably in the library somewhere but I couldn't find them *)\nLemma eqb_true : forall x, NPeano.Nat.eqb x x = true.\n  induction x; crush.\nQed.\n\nLemma ltb_false : forall x, NPeano.Nat.ltb x x = false.\n  induction x; crush.\nQed.\n\nLemma bexp_opt_correct : forall b s, eval_bexp b s = eval_bexp (optimize_bexp b) s.\nintros. induction b; crush;\ntry (remember (eq_aexp_dec (optimize_aexp a) (optimize_aexp a0)) as cond;\ndestruct cond; [ simpl;\nrewrite aexpopt_correct at 1; rewrite e; rewrite <- aexpopt_correct at 1; try rewrite eqb_true; try rewrite ltb_false; reflexivity |\nsimpl; repeat rewrite <- aexpopt_correct; reflexivity ]); [ .. | remember (optimize_bexp b) as bb; destruct bb; crush ];\nremember (optimize_bexp b1) as bb1; remember (optimize_bexp b2) as bb2;\ndestruct bb1; solve[ simpl; reflexivity | destruct bb2; simpl; \n       solve [ crush | rewrite andb_true_r; reflexivity | rewrite andb_false_r; reflexivity ] ].\nQed.\n\nFixpoint optimize_com (c:com) : com :=\n  match c with\n      | Seq c1 c2 => match (optimize_com c1, optimize_com c2) with\n        | (Skip, Skip) => Skip\n        | (Skip, c2') => c2'\n        | (c1', Skip) => c1'\n        | (c1', c2') => (Seq c1' c2')\n      end\n      | Assign v a => Assign v (optimize_aexp a)\n      | If bb c1 c2 => match (optimize_bexp bb) with\n         | Tt => optimize_com c1\n         | Ff => optimize_com c2\n         | b => If b (optimize_com c1) (optimize_com c2)\n      end\n      | While bb c1 => match (optimize_bexp bb) with\n         | Ff => Skip\n         | b => While b (optimize_com c1)\n      end\n      | Skip => Skip\n  end.\n\n(* Construct a proof that optimizing a program doesn't change its\n   input/output behavior.  That is, show that if we start in state\n   s1 and evaluate c to get state s2, then if we evaluate \n   optimize_com(c) in state s1, we get out a state that is\n   extensionally equivalent to s2.  \n*)\n    \nLtac to_ieval H := apply EvalCom1 in H; destruct H; aterm2 H; simpl in H.\nLtac to_ieval_assign H := simpl ieval_com in H; rewrite <- aexpopt_correct in H.\n\nLemma eval_assign_correct : forall v a s' s1, eval_com (Assign v (optimize_aexp a)) s1 s' <-> eval_com (Assign v a) s1 s'.\nintros.\nsplit; intros; apply EvalCom2 with (n:=1); simpl; apply EvalCom1 in H; destruct H; aterm2 H; simpl in H.\nrewrite <- aexpopt_correct in H; assumption.\nrewrite aexpopt_correct in H; assumption.\nQed.\n\nLtac myinj H := let Hx := fresh in injection H as Hx; rewrite Hx in *; clear Hx; clear H.\n\nLtac magic :=\n  repeat match goal with\n      | [ H: context[eval_com (optimize_com Skip) _ _] |- _ ] =>  to_ieval H; (try myinj); try assumption\n      | [ H: context[eval_com Skip _ _] |- _ ] =>  to_ieval H; (try myinj); try assumption\n      | [ H: context[eval_com (Assign _ (optimize_aexp _)) _ _] |- _ ] => apply -> eval_assign_correct in H; try assumption\n      | [ |- eval_com (Assign _ (optimize_aexp _)) _ _ ] => apply eval_assign_correct; try assumption\n      | [ H: context[eval_com (optimize_com (Assign _ _)) _ _ ] |- _] => simpl optimize_com in H; try assumption\n      | [ H: eval_com (optimize_com (Seq ?c2 ?c3)) _ _ |- _ ] => remember (optimize_com (Seq c2 c3))\n      | [ H: eval_com (optimize_com (If ?b ?c2 ?c3)) _ _ |- _ ] => remember (optimize_com (If b c2 c3))\n      | [ H: eval_com (optimize_com (While ?b ?c2)) _ _ |- _ ] => remember (optimize_com (While b c2))\n      | [ H1: eval_com _ ?sx ?s3, H2: eval_com _ ?s3 ?s2 |- eval_com (Seq _ _) ?sx ?s2 ] => apply Eval_seq with (s1:=s3); magic; try assumption\n      | [ H: Some ?s1 = Some ?s2 |- _ ] => let Hx := fresh in injection H as Hx; rewrite Hx in *; clear Hx; clear H\n      | [ |- eval_com Skip ?s ?s ] => apply Eval_skip; assumption\n  end.\n\nLtac imagic :=\n  repeat match goal with\n      | [ H: ieval_com ?x ?c ?s1 = ?s2 |- ieval_com (S ?x) ?c ?s1 = ?s2 ] => raise in H; try assumption\n      | [ H: ieval_com ?x ?c ?s1 = ?s2, H2: ieval_com (S ?x) ?c ?s1 = ?s3 |- _ ] => \n          let H3:=fresh in assert(H3:=H); raise in H3; rewrite H3 in H2; myinj H2; subst; try assumption; try reflexivity\n      | [ H: ?x = ieval_com _ _ _ |- _ ] => apply eq_sym in H\n  end.\n\nLemma seq_correct : forall c1 c2 s1 s' s2, eval_com (optimize_com c1) s1 s' -> eval_com (optimize_com c2) s' s2 -> eval_com (optimize_com (Seq c1 c2)) s1 s2.\nintros.\nsimpl optimize_com.\ndestruct c1; destruct c2; magic; simpl; magic; destruct c; try destruct c0; magic; simpl; try assumption.\nQed.\n\nLtac remember_cond name := \n  match goal with\n      | [ |- context[ (If ?c _ _ )] ] => remember c as name\n      | [ |- context[ (While ?c _ )] ] => remember c as name\n  end.\n\nLtac ifc H Heqcond := contradict H; rewrite bexp_opt_correct; rewrite <- Heqcond; simpl; crush.\nLtac ifb H Heqcond s1 := let cond4:=fresh in  remember_cond cond4; unroll_ieval_com; remember (eval_bexp cond4 s1) as cond5 eqn:Heqcond5; destruct cond5; first [ \nassumption |\ncontradict H; rewrite bexp_opt_correct; rewrite <- Heqcond; rewrite <- Heqcond5; crush; try assumption ].\n\nLemma if_correct : forall b c1 c2 s1 s2, \n                     eval_bexp b s1 = false \\/ eval_com (optimize_com c1) s1 s2 -> \n                     eval_bexp b s1 = true \\/ eval_com (optimize_com c2) s1 s2 -> eval_com (optimize_com (If b c1 c2)) s1 s2.\nintros.\ndestruct H; destruct H0; \n[ contradict H; crush | .. ]; \ntry (apply EvalCom1 in H0; destruct H0);\ntry (apply EvalCom1 in H; destruct H);\ntry (apply EvalCom2 with (n:= x+x0));\ntry (apply EvalCom2 with (n:= S x)); simpl optimize_com; remember (optimize_bexp b) as cond.\ndestruct cond; [ ifc H Heqcond | imagic | .. ]; ifb H Heqcond s1.\ndestruct cond; [ imagic | ifc H0 Heqcond | .. ] ; ifb H0 Heqcond s1.\ndestruct cond; [ \nraise x in H; rewrite plus_comm in H; assumption |\nraise x0 in H0; assumption | .. ];\n(assert (x+x0 <> 0); [ aterm2 H0; crush | ]); apply neq in H1; destruct H1; rewrite H1;\nremember_cond cond4; unroll_ieval_com; remember (eval_bexp cond4 s1) as cond5 eqn:Heqcond5; (destruct cond5;\n[raise (x-1) in H; assert (x1 = (x0 + (x - 1))) as H3; [ aterm2 H0; crush | ]; rewrite H3; assumption |\nraise (x0-1) in H0; assert (x1 = (x + (x0 - 1))) as H3; [ aterm2 H; crush | ]; rewrite H3; assumption ] ).\nQed.\n\nLemma bexp_true_is_true : forall b, optimize_bexp b = Tt -> (forall s, (eval_bexp b s) = true).\nintros. rewrite bexp_opt_correct. rewrite H. simpl. reflexivity.\nQed.\n\nLemma ieval_minus : forall x c s, ieval_com (S x) c s = None -> ieval_com x c s = None.\nintros.\nspecialize ieval_plus with (n:=x) (m:=1) (c:=c) (s1:=s). intros.\ndestruct (ieval_com x c s).\nassert(Some s0 = Some s0). reflexivity. eapply H0 with (m:=1) in H1.\nrewrite plus_comm in H1. simpl plus in H1. congruence. reflexivity.\nQed.\n\nLemma while_inf : forall x b c s1, (forall s, eval_bexp b s = true) -> ieval_com x (While b c) s1 = None.\ninduction x; intros; [ crush | ..].\napply ieval_minus. unroll_ieval_com. erewrite H. unroll_ieval_com.\nremember (ieval_com x c s1) as cond. destruct cond.\neapply IHx. assumption.\nreflexivity.\nQed.\n\nTheorem opt_correct : forall c s1 s2, eval_com c s1 s2 -> eval_com (optimize_com c) s1 s2.\nintros.\ninduction H.\ncrush.\napply EvalCom2 with (n:=1); simpl. rewrite <- aexpopt_correct. reflexivity.\napply seq_correct with (s':=s1); assumption.\napply if_correct. right. assumption. left. assumption.\napply if_correct. left. assumption. right. assumption.\nsimpl. apply EvalCom2 with (n:=1). simpl. \nremember (optimize_bexp b) as cond.\ndestruct cond; try reflexivity; rewrite bexp_opt_correct in H; rewrite <- Heqcond in H; rewrite H; reflexivity.\nsimpl.\nremember (optimize_bexp b) as cond.\ndestruct cond;\napply EvalCom1 in H1; destruct H1; [\napply eq_sym in Heqcond;\npose proof bexp_true_is_true; specialize H2 with (b:=b); apply while_inf with (x:=x) (c:=c) (s1:=s2) in H2; \n[rewrite H2 in H1; contradict H1; crush | assumption ] |\ncontradict H; rewrite -> bexp_opt_correct; rewrite <- Heqcond; simpl; crush | .. ];\napply EvalCom1 in IHeval_com2; destruct IHeval_com2;\napply EvalCom1 in IHeval_com1; destruct IHeval_com1;\napply EvalCom2 with (n:=(S (S (x0+x1))));\nremember_cond ccc; unroll_ieval_com;\nrewrite Heqcond; rewrite <- bexp_opt_correct; rewrite H;\nsimpl ieval_com; raise x0 in H3; rewrite plus_comm in H3; rewrite H3;\nraise x1 in H2; simpl optimize_com in H2; rewrite <- Heqcond in H2; rewrite Heqccc in H2;\nrewrite <- Heqcond; rewrite Heqccc; assumption.\nQed.\n\n(* Hints:\n\n   * You *will* get stuck doing this assignment.  It is hard.\n     Don't hesitate to ask questions on Piazza or in class, \n     or collaborate with friends to solve this.  \n     \n   * When proving ieval_com is equivalent to eval_com, you will\n     find the following lemma very useful:\n\n     ieval_plus : forall n c s1 s2, \n       ieval_com n c s1 = Some s2 -> \n         forall m, ieval_com (n + m) c s1 = Some s2\n\n    This says that if it takes n steps to get an answer out,\n    then if you run for more than n steps, you still get the\n    same answer out.\n\n   * Write a simple optimizer first, and prove that correct.\n     Don't try to write a complicated optimizer first.  It's\n     easier to \"grow\" your development incrementally.  \n\n  * You will find the following tactic very useful:\n\n       remember(<exp>) as <id>\n\n    Consider a proof state like this:\n\n        H : P (foo + bar + baz)\n        -----------------------------------------\n        match foo + bar + baz with \n          | 0 => blah\n          | S n => blahblah\n        end\n\n    Executing the tactic\n\n        remember (foo + bar + baz) as x\n\n    will leave you in the state:\n\n        x : nat\n        Hxeq : x = foo + bar + baz\n        H : P x\n        -----------------------------------------\n        match x with \n          | 0 => blah\n          | S n => blahblah\n        end\n\n    So \"remember\" just helps you name a sub-expression in \n    a proof, and replace all occurrences of that sub-expression\n    with that name.  You can always undo the substitution by\n    rewriting by the Hxeq equation.\n\n  * There are many useful arithmetic facts in the libraries\n    (e.g., plus_0_r, NPeano.Nat.sub_0_r, mult_comm, etc.) \n    Don't forget to use \"SearchAbout\" to find them.\n\n  * If you [Require Import Omega.] then you can use the \"omega\"\n    tactic to solve some arithmetic questions.  \n\n  * You will want to define a comparison operation for arithmetic\n    expressions.  The natural thing to write is something like:\n\n       eq_aexp : aexp -> aexp -> bool\n\n    but you will then need to prove that this is actually correct\n    i.e., (eq_aexp a1 a2 = true) <-> (a1 = a2).\n\n    An alternative is to define something like:\n\n      eq_aexp_dec : forall (a1 a2:aexp), {a1 = a2} + {a1<>a2}.\n\n    and instead of trying to build it using explicit code, use\n    the \"decide quality\" tactic (two words.)  For instance:\n\n    Definition eq_aexp_dec (a1 a2:aexp) : {a1=a2} + {a1<>a2}.\n      decide quality.\n      apply (eq_nat_dec n n0).\n      apply (string_dec v v0).\n      decide equality.\n    Defined.\n\n    This tactic will take an inductive definition and try to\n    build the decidable equality term for you.  In the example\n    above, I had to tell it how to decide quality for some of\n    the types used within the definition (nats, strings, and\n    binops.)  \n\n  * You may also find the tactic:\n\n       replace (<exp1>) with (<exp2>) \n\n    useful.  As suggested, it lets you replace occurrences of \n    one expression with another.  It leaves you with two goals:\n    The first is the original goal with the substitution performed.\n    The second is a requirement to prove <exp1> = <exp2>. \n\n  * My solution for this whole file (not including these comments)\n    is about 400 lines of code.  Yours will be much, much bigger\n    unless you use a lot of automation.  \n\n*)\n    \n", "meta": {"author": "Keno", "repo": "CS250", "sha": "5865c43b99d3acee956d610475445894851397f6", "save_path": "github-repos/coq/Keno-CS250", "path": "github-repos/coq/Keno-CS250/CS250-5865c43b99d3acee956d610475445894851397f6/pset2/pset2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7453592143289091}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import Sumbool.\nRequire Import Rbase.\nRequire Import Rfunctions.\nRequire Import SeqSeries.\nRequire Import Ranalysis1.\nLocal Open Scope R_scope.\n\nFixpoint Dichotomy_lb (x y:R) (P:R -> bool) (N:nat) {struct N} : R :=\nmatch N with\n| O => x\n| S n =>\nlet down := Dichotomy_lb x y P n in\nlet up := Dichotomy_ub x y P n in\nlet z := (down + up) / 2 in if P z then down else z\nend\n\nwith Dichotomy_ub (x y:R) (P:R -> bool) (N:nat) {struct N} : R :=\nmatch N with\n| O => y\n| S n =>\nlet down := Dichotomy_lb x y P n in\nlet up := Dichotomy_ub x y P n in\nlet z := (down + up) / 2 in if P z then z else up\nend.\n\nDefinition dicho_lb (x y:R) (P:R -> bool) (N:nat) : R := Dichotomy_lb x y P N.\nDefinition dicho_up (x y:R) (P:R -> bool) (N:nat) : R := Dichotomy_ub x y P N.\n\n\nLemma dicho_comp :\nforall (x y:R) (P:R -> bool) (n:nat),\nx <= y -> dicho_lb x y P n <= dicho_up x y P n.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_comp\".  \nintros.\ninduction  n as [| n Hrecn].\nsimpl; assumption.\nsimpl.\ncase (P ((Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2)).\nunfold Rdiv; apply Rmult_le_reg_l with 2.\nprove_sup0.\npattern 2 at 1; rewrite Rmult_comm.\nrewrite Rmult_assoc; rewrite <- Rinv_l_sym; [ idtac | discrR ].\nrewrite Rmult_1_r.\nrewrite double.\napply Rplus_le_compat_l.\nassumption.\nunfold Rdiv; apply Rmult_le_reg_l with 2.\nprove_sup0.\nrewrite Rmult_comm.\nrewrite Rmult_assoc; rewrite <- Rinv_l_sym; [ idtac | discrR ].\nrewrite Rmult_1_r.\nrewrite double.\nrewrite <- (Rplus_comm (Dichotomy_ub x y P n)).\napply Rplus_le_compat_l.\nassumption.\nQed.\n\nLemma dicho_lb_growing :\nforall (x y:R) (P:R -> bool), x <= y -> Un_growing (dicho_lb x y P).\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_lb_growing\".  \nintros.\nunfold Un_growing.\nintro.\nsimpl.\ncase (P ((Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2)).\nright; reflexivity.\nunfold Rdiv; apply Rmult_le_reg_l with 2.\nprove_sup0.\npattern 2 at 1; rewrite Rmult_comm.\nrewrite Rmult_assoc; rewrite <- Rinv_l_sym; [ idtac | discrR ].\nrewrite Rmult_1_r.\nrewrite double.\napply Rplus_le_compat_l.\nreplace (Dichotomy_ub x y P n) with (dicho_up x y P n);\n[ apply dicho_comp; assumption | reflexivity ].\nQed.\n\nLemma dicho_up_decreasing :\nforall (x y:R) (P:R -> bool), x <= y -> Un_decreasing (dicho_up x y P).\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_up_decreasing\".  \nintros.\nunfold Un_decreasing.\nintro.\nsimpl.\ncase (P ((Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2)).\nunfold Rdiv; apply Rmult_le_reg_l with 2.\nprove_sup0.\nrewrite Rmult_comm.\nrewrite Rmult_assoc; rewrite <- Rinv_l_sym; [ idtac | discrR ].\nrewrite Rmult_1_r.\nrewrite double.\nreplace (Dichotomy_ub x y P n) with (dicho_up x y P n);\n[ idtac | reflexivity ].\nreplace (Dichotomy_lb x y P n) with (dicho_lb x y P n);\n[ idtac | reflexivity ].\nrewrite <- (Rplus_comm (dicho_up x y P n)).\napply Rplus_le_compat_l.\napply dicho_comp; assumption.\nright; reflexivity.\nQed.\n\nLemma dicho_lb_maj_y :\nforall (x y:R) (P:R -> bool), x <= y -> forall n:nat, dicho_lb x y P n <= y.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_lb_maj_y\".  \nintros.\ninduction  n as [| n Hrecn].\nsimpl; assumption.\nsimpl.\ncase (P ((Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2)).\nassumption.\nunfold Rdiv; apply Rmult_le_reg_l with 2.\nprove_sup0.\nrewrite Rmult_comm.\nrewrite Rmult_assoc; rewrite <- Rinv_l_sym; [ rewrite Rmult_1_r | discrR ].\nrewrite double; apply Rplus_le_compat.\nassumption.\npattern y at 2; replace y with (Dichotomy_ub x y P 0);\n[ idtac | reflexivity ].\napply decreasing_prop.\nassert (H0 := dicho_up_decreasing x y P H).\nassumption.\napply le_O_n.\nQed.\n\nLemma dicho_lb_maj :\nforall (x y:R) (P:R -> bool), x <= y -> has_ub (dicho_lb x y P).\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_lb_maj\".  \nintros.\ncut (forall n:nat, dicho_lb x y P n <= y).\nintro.\nunfold has_ub.\nunfold bound.\nexists y.\nunfold is_upper_bound.\nintros.\nelim H1; intros.\nrewrite H2; apply H0.\napply dicho_lb_maj_y; assumption.\nQed.\n\nLemma dicho_up_min_x :\nforall (x y:R) (P:R -> bool), x <= y -> forall n:nat, x <= dicho_up x y P n.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_up_min_x\".  \nintros.\ninduction  n as [| n Hrecn].\nsimpl; assumption.\nsimpl.\ncase (P ((Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2)).\nunfold Rdiv; apply Rmult_le_reg_l with 2.\nprove_sup0.\npattern 2 at 1; rewrite Rmult_comm.\nrewrite Rmult_assoc; rewrite <- Rinv_l_sym; [ rewrite Rmult_1_r | discrR ].\nrewrite double; apply Rplus_le_compat.\npattern x at 1; replace x with (Dichotomy_lb x y P 0);\n[ idtac | reflexivity ].\napply tech9.\nassert (H0 := dicho_lb_growing x y P H).\nassumption.\napply le_O_n.\nassumption.\nassumption.\nQed.\n\nLemma dicho_up_min :\nforall (x y:R) (P:R -> bool), x <= y -> has_lb (dicho_up x y P).\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_up_min\".  \nintros.\ncut (forall n:nat, x <= dicho_up x y P n).\nintro.\nunfold has_lb.\nunfold bound.\nexists (- x).\nunfold is_upper_bound.\nintros.\nelim H1; intros.\nrewrite H2.\nunfold opp_seq.\napply Ropp_le_contravar.\napply H0.\napply dicho_up_min_x; assumption.\nQed.\n\nLemma dicho_lb_cv :\nforall (x y:R) (P:R -> bool),\nx <= y -> { l:R | Un_cv (dicho_lb x y P) l }.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_lb_cv\".  \nintros.\napply growing_cv.\napply dicho_lb_growing; assumption.\napply dicho_lb_maj; assumption.\nQed.\n\nLemma dicho_up_cv :\nforall (x y:R) (P:R -> bool),\nx <= y -> { l:R | Un_cv (dicho_up x y P) l }.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_up_cv\".  \nintros.\napply decreasing_cv.\napply dicho_up_decreasing; assumption.\napply dicho_up_min; assumption.\nQed.\n\nLemma dicho_lb_dicho_up :\nforall (x y:R) (P:R -> bool) (n:nat),\nx <= y -> dicho_up x y P n - dicho_lb x y P n = (y - x) / 2 ^ n.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_lb_dicho_up\".  \nintros.\ninduction  n as [| n Hrecn].\nsimpl.\nunfold Rdiv; rewrite Rinv_1; ring.\nsimpl.\ncase (P ((Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2)).\nunfold Rdiv.\nreplace\n((Dichotomy_lb x y P n + Dichotomy_ub x y P n) * / 2 - Dichotomy_lb x y P n)\nwith ((dicho_up x y P n - dicho_lb x y P n) / 2).\nunfold Rdiv; rewrite Hrecn.\nunfold Rdiv.\nrewrite Rinv_mult_distr.\nring.\ndiscrR.\napply pow_nonzero; discrR.\npattern (Dichotomy_lb x y P n) at 2;\nrewrite (double_var (Dichotomy_lb x y P n));\nunfold dicho_up, dicho_lb, Rminus, Rdiv; ring.\nreplace\n(Dichotomy_ub x y P n - (Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2)\nwith ((dicho_up x y P n - dicho_lb x y P n) / 2).\nunfold Rdiv; rewrite Hrecn.\nunfold Rdiv.\nrewrite Rinv_mult_distr.\nring.\ndiscrR.\napply pow_nonzero; discrR.\npattern (Dichotomy_ub x y P n) at 1;\nrewrite (double_var (Dichotomy_ub x y P n));\nunfold dicho_up, dicho_lb, Rminus, Rdiv; ring.\nQed.\n\nDefinition pow_2_n (n:nat) := 2 ^ n.\n\nLemma pow_2_n_neq_R0 : forall n:nat, pow_2_n n <> 0.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.pow_2_n_neq_R0\".  \nintro.\nunfold pow_2_n.\napply pow_nonzero.\ndiscrR.\nQed.\n\nLemma pow_2_n_growing : Un_growing pow_2_n.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.pow_2_n_growing\".  \nunfold Un_growing.\nintro.\nreplace (S n) with (n + 1)%nat;\n[ unfold pow_2_n; rewrite pow_add | ring ].\npattern (2 ^ n) at 1; rewrite <- Rmult_1_r.\napply Rmult_le_compat_l.\nleft; apply pow_lt; prove_sup0.\nsimpl.\nrewrite Rmult_1_r.\npattern 1 at 1; rewrite <- Rplus_0_r; apply Rplus_le_compat_l; left;\napply Rlt_0_1.\nQed.\n\nLemma pow_2_n_infty : cv_infty pow_2_n.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.pow_2_n_infty\".  \ncut (forall N:nat, INR N <= 2 ^ N).\nintros.\nunfold cv_infty.\nintro.\ndestruct (total_order_T 0 M) as [[Hlt|<-]|Hgt].\nset (N := up M).\ncut (0 <= N)%Z.\nintro.\nelim (IZN N H0); intros N0 H1.\nexists N0.\nintros.\napply Rlt_le_trans with (INR N0).\nrewrite INR_IZR_INZ.\nrewrite <- H1.\nunfold N.\nassert (H3 := archimed M).\nelim H3; intros; assumption.\napply Rle_trans with (pow_2_n N0).\nunfold pow_2_n; apply H.\napply Rge_le.\napply growing_prop.\napply pow_2_n_growing.\nassumption.\napply le_IZR.\nunfold N.\nsimpl.\nassert (H0 := archimed M); elim H0; intros.\nleft; apply Rlt_trans with M; assumption.\nexists 0%nat; intros.\nunfold pow_2_n; apply pow_lt; prove_sup0.\nexists 0%nat; intros.\napply Rlt_trans with 0.\nassumption.\nunfold pow_2_n; apply pow_lt; prove_sup0.\nsimple induction N.\nsimpl.\nleft; apply Rlt_0_1.\nintros.\npattern (S n) at 2; replace (S n) with (n + 1)%nat; [ idtac | ring ].\nrewrite S_INR; rewrite pow_add.\nsimpl.\nrewrite Rmult_1_r.\napply Rle_trans with (2 ^ n).\nrewrite <- (Rplus_comm 1).\nrewrite <- (Rmult_1_r (INR n)).\napply (poly n 1).\napply Rlt_0_1.\npattern (2 ^ n) at 1; rewrite <- Rplus_0_r.\nrewrite <- (Rmult_comm 2).\nrewrite double.\napply Rplus_le_compat_l.\nleft; apply pow_lt; prove_sup0.\nQed.\n\nLemma cv_dicho :\nforall (x y l1 l2:R) (P:R -> bool),\nx <= y ->\nUn_cv (dicho_lb x y P) l1 -> Un_cv (dicho_up x y P) l2 -> l1 = l2.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.cv_dicho\".  \nintros.\nassert (H2 := CV_minus _ _ _ _ H0 H1).\ncut (Un_cv (fun i:nat => dicho_lb x y P i - dicho_up x y P i) 0).\nintro.\nassert (H4 := UL_sequence _ _ _ H2 H3).\nsymmetry ; apply Rminus_diag_uniq_sym; assumption.\nunfold Un_cv; unfold R_dist.\nintros.\nassert (H4 := cv_infty_cv_R0 pow_2_n pow_2_n_neq_R0 pow_2_n_infty).\ndestruct (total_order_T x y) as [[ Hlt | -> ]|Hgt].\nunfold Un_cv in H4; unfold R_dist in H4.\ncut (0 < y - x).\nintro Hyp.\ncut (0 < eps / (y - x)).\nintro.\nelim (H4 (eps / (y - x)) H5); intros N H6.\nexists N; intros.\nreplace (dicho_lb x y P n - dicho_up x y P n - 0) with\n(dicho_lb x y P n - dicho_up x y P n); [ idtac | ring ].\nrewrite <- Rabs_Ropp.\nrewrite Ropp_minus_distr'.\nrewrite dicho_lb_dicho_up.\nunfold Rdiv; rewrite Rabs_mult.\nrewrite (Rabs_right (y - x)).\napply Rmult_lt_reg_l with (/ (y - x)).\napply Rinv_0_lt_compat; assumption.\nrewrite <- Rmult_assoc; rewrite <- Rinv_l_sym.\nrewrite Rmult_1_l.\nreplace (/ 2 ^ n) with (/ 2 ^ n - 0);\n[ unfold pow_2_n, Rdiv in H6; rewrite <- (Rmult_comm eps); apply H6;\nassumption\n| ring ].\nred; intro; rewrite H8 in Hyp; elim (Rlt_irrefl _ Hyp).\napply Rle_ge.\napply Rplus_le_reg_l with x; rewrite Rplus_0_r.\nreplace (x + (y - x)) with y; [ assumption | ring ].\nassumption.\nunfold Rdiv; apply Rmult_lt_0_compat;\n[ assumption | apply Rinv_0_lt_compat; assumption ].\napply Rplus_lt_reg_l with x; rewrite Rplus_0_r.\nreplace (x + (y - x)) with y; [ assumption | ring ].\nexists 0%nat; intros.\nreplace (dicho_lb y y P n - dicho_up y y P n - 0) with\n(dicho_lb y y P n - dicho_up y y P n); [ idtac | ring ].\nrewrite <- Rabs_Ropp.\nrewrite Ropp_minus_distr'.\nrewrite dicho_lb_dicho_up.\nunfold Rminus, Rdiv; rewrite Rplus_opp_r; rewrite Rmult_0_l;\nrewrite Rabs_R0; assumption.\nassumption.\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H Hgt)).\nQed.\n\nDefinition cond_positivity (x:R) : bool :=\nmatch Rle_dec 0 x with\n| left _ => true\n| right _ => false\nend.\n\n\nLemma continuity_seq :\nforall (f:R -> R) (Un:nat -> R) (l:R),\ncontinuity_pt f l -> Un_cv Un l -> Un_cv (fun i:nat => f (Un i)) (f l).\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.continuity_seq\".  \nunfold continuity_pt, Un_cv; unfold continue_in.\nunfold limit1_in.\nunfold limit_in.\nunfold dist.\nsimpl.\nunfold R_dist.\nintros.\nelim (H eps H1); intros alp H2.\nelim H2; intros.\nelim (H0 alp H3); intros N H5.\nexists N; intros.\ncase (Req_dec (Un n) l); intro.\nrewrite H7; unfold Rminus; rewrite Rplus_opp_r; rewrite Rabs_R0;\nassumption.\napply H4.\nsplit.\nunfold D_x, no_cond.\nsplit.\ntrivial.\napply (not_eq_sym (A:=R)); assumption.\napply H5; assumption.\nQed.\n\nLemma dicho_lb_car :\nforall (x y:R) (P:R -> bool) (n:nat),\nP x = false -> P (dicho_lb x y P n) = false.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_lb_car\".  \nintros.\ninduction n as [| n Hrecn].\n- assumption.\n- simpl.\ndestruct\n(sumbool_of_bool (P ((Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2))) as [Heq|Heq].\n+ rewrite Heq.\nunfold dicho_lb in Hrecn; assumption.\n+ rewrite Heq.\nassumption.\nQed.\n\nLemma dicho_up_car :\nforall (x y:R) (P:R -> bool) (n:nat),\nP y = true -> P (dicho_up x y P n) = true.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.dicho_up_car\".  \nintros.\ninduction n as [| n Hrecn].\n- assumption.\n- simpl.\ndestruct\n(sumbool_of_bool (P ((Dichotomy_lb x y P n + Dichotomy_ub x y P n) / 2))) as [Heq|Heq].\n+ rewrite Heq.\nunfold dicho_lb in Hrecn; assumption.\n+ rewrite  Heq.\nassumption.\nQed.\n\n\nLemma cv_pow_half : forall a, Un_cv (fun n => a/2^n) 0.\nintros a; unfold Rdiv; replace 0 with (a * 0) by ring.\napply CV_mult.\nintros eps ep; exists 0%nat; rewrite R_dist_eq; intros n _; assumption.\nexact (cv_infty_cv_R0 pow_2_n pow_2_n_neq_R0 pow_2_n_infty).\nQed.\n\n\nLemma IVT :\nforall (f:R -> R) (x y:R),\ncontinuity f ->\nx < y -> f x < 0 -> 0 < f y -> { z:R | x <= z <= y /\\ f z = 0 }.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.IVT\".  \nintros.\nassert (x <= y) by (left; assumption).\ndestruct (dicho_lb_cv x y (fun z:R => cond_positivity (f z)) H3) as (x1,p0).\ndestruct (dicho_up_cv x y (fun z:R => cond_positivity (f z)) H3) as (x0,p).\nassert (H4 := cv_dicho _ _ _ _ _ H3 p0 p).\nrewrite H4 in p0.\nexists x0.\nsplit.\nsplit.\napply Rle_trans with (dicho_lb x y (fun z:R => cond_positivity (f z)) 0).\nsimpl.\nright; reflexivity.\napply growing_ineq.\napply dicho_lb_growing; assumption.\nassumption.\napply Rle_trans with (dicho_up x y (fun z:R => cond_positivity (f z)) 0).\napply decreasing_ineq.\napply dicho_up_decreasing; assumption.\nassumption.\nright; reflexivity.\nset (Vn := fun n:nat => dicho_lb x y (fun z:R => cond_positivity (f z)) n).\nset (Wn := fun n:nat => dicho_up x y (fun z:R => cond_positivity (f z)) n).\ncut ((forall n:nat, f (Vn n) <= 0) -> f x0 <= 0).\ncut ((forall n:nat, 0 <= f (Wn n)) -> 0 <= f x0).\nintros.\ncut (forall n:nat, f (Vn n) <= 0).\ncut (forall n:nat, 0 <= f (Wn n)).\nintros.\nassert (H9 := H6 H8).\nassert (H10 := H5 H7).\napply Rle_antisym; assumption.\nintro.\nunfold Wn.\ncut (forall z:R, cond_positivity z = true <-> 0 <= z).\nintro.\nassert (H8 := dicho_up_car x y (fun z:R => cond_positivity (f z)) n).\nelim (H7 (f (dicho_up x y (fun z:R => cond_positivity (f z)) n))); intros.\napply H9.\napply H8.\nelim (H7 (f y)); intros.\napply H12.\nleft; assumption.\nintro.\nunfold cond_positivity.\ncase (Rle_dec 0 z) as [Hle|Hnle].\nsplit.\nintro; assumption.\nintro; reflexivity.\nsplit.\nintro feqt;discriminate feqt.\nintro.\ncontradiction.\nunfold Vn.\ncut (forall z:R, cond_positivity z = false <-> z < 0).\nintros.\nassert (H8 := dicho_lb_car x y (fun z:R => cond_positivity (f z)) n).\nleft.\nelim (H7 (f (dicho_lb x y (fun z:R => cond_positivity (f z)) n))); intros.\napply H9.\napply H8.\nelim (H7 (f x)); intros.\napply H12.\nassumption.\nintro.\nunfold cond_positivity.\ncase (Rle_dec 0 z) as [Hle|Hnle].\nsplit.\nintro feqt; discriminate feqt.\nintro; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ Hle H7)).\nsplit.\nintro; auto with real.\nintro; reflexivity.\ncut (Un_cv Wn x0).\nintros.\nassert (H7 := continuity_seq f Wn x0 (H x0) H5).\ndestruct (total_order_T 0 (f x0)) as [[Hlt|<-]|Hgt].\nleft; assumption.\nright; reflexivity.\nunfold Un_cv in H7; unfold R_dist in H7.\ncut (0 < - f x0).\nintro.\nelim (H7 (- f x0) H8); intros.\ncut (x2 >= x2)%nat; [ intro | unfold ge; apply le_n ].\nassert (H11 := H9 x2 H10).\nrewrite Rabs_right in H11.\npattern (- f x0) at 1 in H11; rewrite <- Rplus_0_r in H11.\nunfold Rminus in H11; rewrite (Rplus_comm (f (Wn x2))) in H11.\nassert (H12 := Rplus_lt_reg_l _ _ _ H11).\nassert (H13 := H6 x2).\nelim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H13 H12)).\napply Rle_ge; left; unfold Rminus; apply Rplus_le_lt_0_compat.\napply H6.\nexact H8.\napply Ropp_0_gt_lt_contravar; assumption.\nunfold Wn; assumption.\ncut (Un_cv Vn x0).\nintros.\nassert (H7 := continuity_seq f Vn x0 (H x0) H5).\ndestruct (total_order_T 0 (f x0)) as [[Hlt|<-]|Hgt].\nunfold Un_cv in H7; unfold R_dist in H7.\nelim (H7 (f x0) Hlt); intros.\ncut (x2 >= x2)%nat; [ intro | unfold ge; apply le_n ].\nassert (H10 := H8 x2 H9).\nrewrite Rabs_left in H10.\npattern (f x0) at 2 in H10; rewrite <- Rplus_0_r in H10.\nrewrite Ropp_minus_distr' in H10.\nunfold Rminus in H10.\nassert (H11 := Rplus_lt_reg_l _ _ _ H10).\nassert (H12 := H6 x2).\ncut (0 < f (Vn x2)).\nintro.\nelim (Rlt_irrefl _ (Rlt_le_trans _ _ _ H13 H12)).\nrewrite <- (Ropp_involutive (f (Vn x2))).\napply Ropp_0_gt_lt_contravar; assumption.\napply Rplus_lt_reg_l with (f x0 - f (Vn x2)).\nrewrite Rplus_0_r; replace (f x0 - f (Vn x2) + (f (Vn x2) - f x0)) with 0;\n[ unfold Rminus; apply Rplus_lt_le_0_compat | ring ].\nassumption.\napply Ropp_0_ge_le_contravar; apply Rle_ge; apply H6.\nright; reflexivity.\nleft; assumption.\nunfold Vn; assumption.\nQed.\n\nLemma IVT_cor :\nforall (f:R -> R) (x y:R),\ncontinuity f ->\nx <= y -> f x * f y <= 0 -> { z:R | x <= z <= y /\\ f z = 0 }.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.IVT_cor\".  \nintros.\ndestruct (total_order_T 0 (f x)) as [[Hltx|Heqx]|Hgtx].\ndestruct (total_order_T 0 (f y)) as [[Hlty|Heqy]|Hgty].\ncut (0 < f x * f y);\n[ intro; elim (Rlt_irrefl _ (Rle_lt_trans _ _ _ H1 H2))\n| apply Rmult_lt_0_compat; assumption ].\nexists y.\nsplit.\nsplit; [ assumption | right; reflexivity ].\nsymmetry ; exact Heqy.\ncut (x < y).\nintro.\nassert (H3 := IVT (- f)%F x y (continuity_opp f H) H2).\ncut ((- f)%F x < 0).\ncut (0 < (- f)%F y).\nintros.\ndestruct (H3 H5 H4) as (x0,[]).\nexists x0.\nsplit.\nassumption.\nunfold opp_fct in H7.\nrewrite <- (Ropp_involutive (f x0)).\napply Ropp_eq_0_compat; assumption.\nunfold opp_fct; apply Ropp_0_gt_lt_contravar; assumption.\nunfold opp_fct.\napply Rplus_lt_reg_l with (f x); rewrite Rplus_opp_r; rewrite Rplus_0_r;\nassumption.\ninversion H0.\nassumption.\nrewrite H2 in Hltx.\nelim (Rlt_irrefl _ (Rlt_trans _ _ _ Hgty Hltx)).\nexists x.\nsplit.\nsplit; [ right; reflexivity | assumption ].\nsymmetry ; assumption.\ndestruct (total_order_T 0 (f y)) as [[Hlty|Heqy]|Hgty].\ncut (x < y).\nintro.\napply IVT; assumption.\ninversion H0.\nassumption.\nrewrite H2 in Hgtx.\nelim (Rlt_irrefl _ (Rlt_trans _ _ _ Hlty Hgtx)).\nexists y.\nsplit.\nsplit; [ assumption | right; reflexivity ].\nsymmetry ; assumption.\ncut (0 < f x * f y).\nintro.\nelim (Rlt_irrefl _ (Rlt_le_trans _ _ _ H2 H1)).\nrewrite <- Rmult_opp_opp; apply Rmult_lt_0_compat;\napply Ropp_0_gt_lt_contravar; assumption.\nQed.\n\n\nLemma Rsqrt_exists :\nforall y:R, 0 <= y -> { z:R | 0 <= z /\\ y = Rsqr z }.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.Rsqrt_exists\".  \nintros.\nset (f := fun x:R => Rsqr x - y).\ncut (f 0 <= 0).\nintro.\ncut (continuity f).\nintro.\ndestruct (total_order_T y 1) as [[Hlt| -> ]|Hgt].\ncut (0 <= f 1).\nintro.\ncut (f 0 * f 1 <= 0).\nintro.\nassert (X := IVT_cor f 0 1 H1 (Rlt_le _ _ Rlt_0_1) H3).\nelim X; intros t H4.\nexists t.\nelim H4; intros.\nsplit.\nelim H5; intros; assumption.\nunfold f in H6.\napply Rminus_diag_uniq_sym; exact H6.\nrewrite Rmult_comm; pattern 0 at 2; rewrite <- (Rmult_0_r (f 1)).\napply Rmult_le_compat_l; assumption.\nunfold f.\nrewrite Rsqr_1.\napply Rplus_le_reg_l with y.\nrewrite Rplus_0_r; rewrite Rplus_comm; unfold Rminus;\nrewrite Rplus_assoc; rewrite Rplus_opp_l; rewrite Rplus_0_r;\nleft; assumption.\nexists 1.\nsplit.\nleft; apply Rlt_0_1.\nsymmetry; apply Rsqr_1.\ncut (0 <= f y).\nintro.\ncut (f 0 * f y <= 0).\nintro.\nassert (X := IVT_cor f 0 y H1 H H3).\nelim X; intros t H4.\nexists t.\nelim H4; intros.\nsplit.\nelim H5; intros; assumption.\nunfold f in H6.\napply Rminus_diag_uniq_sym; exact H6.\nrewrite Rmult_comm; pattern 0 at 2; rewrite <- (Rmult_0_r (f y)).\napply Rmult_le_compat_l; assumption.\nunfold f.\napply Rplus_le_reg_l with y.\nrewrite Rplus_0_r; rewrite Rplus_comm; unfold Rminus;\nrewrite Rplus_assoc; rewrite Rplus_opp_l; rewrite Rplus_0_r.\npattern y at 1; rewrite <- Rmult_1_r.\nunfold Rsqr; apply Rmult_le_compat_l.\nassumption.\nleft; exact Hgt.\nreplace f with (Rsqr - fct_cte y)%F.\napply continuity_minus.\napply derivable_continuous; apply derivable_Rsqr.\napply derivable_continuous; apply derivable_const.\nreflexivity.\nunfold f; rewrite Rsqr_0.\nunfold Rminus; rewrite Rplus_0_l.\napply Rge_le.\napply Ropp_0_le_ge_contravar; assumption.\nQed.\n\n\nDefinition Rsqrt (y:nonnegreal) : R :=\nlet (a,_) := Rsqrt_exists (nonneg y) (cond_nonneg y) in a.\n\n\nLemma Rsqrt_positivity : forall x:nonnegreal, 0 <= Rsqrt x.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.Rsqrt_positivity\".  \nintro.\ndestruct (Rsqrt_exists (nonneg x) (cond_nonneg x)) as (x0 & H1 & H2).\ncut (x0 = Rsqrt x).\nintros.\nrewrite <- H; assumption.\nunfold Rsqrt.\ncase (Rsqrt_exists x (cond_nonneg x)) as (?,[]).\napply Rsqr_inj.\nassumption.\nassumption.\nrewrite <- H0, <- H2; reflexivity.\nQed.\n\n\nLemma Rsqrt_Rsqrt : forall x:nonnegreal, Rsqrt x * Rsqrt x = x.\nProof. hammer_hook \"Rsqrt_def\" \"Rsqrt_def.Rsqrt_Rsqrt\".  \nintros.\ndestruct (Rsqrt_exists (nonneg x) (cond_nonneg x)) as (x0 & H1 & H2).\ncut (x0 = Rsqrt x).\nintros.\nrewrite <- H.\nrewrite H2; reflexivity.\nunfold Rsqrt.\ncase (Rsqrt_exists x (cond_nonneg x)) as (x1 & ? & ?).\napply Rsqr_inj.\nassumption.\nassumption.\nrewrite <- H0, <- H2; reflexivity.\nQed.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Reals/Rsqrt_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.745359208421724}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\nRequire Import Arith Lia.\n\nSet Implicit Arguments.\n\nSet Default Proof Using \"Type\".\n\nSection nat_rev_ind.\n\n  (* A reverse recursion principle *)\n\n  Variables (P : nat -> Prop)\n            (HP : forall n, P (S n) -> P n).\n\n  Theorem nat_rev_ind x y : x <= y -> P y -> P x.\n  Proof using HP. induction 1; auto. Qed.\n\nEnd nat_rev_ind.\n\nSection nat_rev_ind'.\n\n  (* A reverse recursion principle *)\n\n  Variables (P : nat -> Prop) (k : nat)\n            (HP : forall n, n < k -> P (S n) -> P n).\n\n  Theorem nat_rev_ind' x y : x <= y <= k -> P y -> P x.\n  Proof using HP.\n    intros H1 H2. \n    set (Q n := n <= k /\\ P n).\n    assert (forall x y, x <= y -> Q y -> Q x) as H.\n      apply nat_rev_ind.\n      intros n (H3 & H4); split.\n      lia.\n      revert H4; apply HP, H3.\n    apply (H x y).\n    lia.\n    split; auto; lia.\n  Qed.\n\nEnd nat_rev_ind'.\n\nSection minimizer_pred.\n\n  Variable (P : nat -> Prop)\n           (HP : forall p: { n | P n \\/ ~ P n }, { P (proj1_sig p) } + { ~ P (proj1_sig p) }).\n\n  Definition minimizer n := P n /\\ forall i, i < n -> ~ P i.\n\n  Inductive bar n : Prop :=\n    | in_bar_0 : P n -> bar n\n    | in_bar_1 : ~ P n -> bar (S n) -> bar n.\n\n  Let bar_ex n : bar n -> P n \\/ ~ P n.\n  Proof. induction 1; auto. Qed.\n\n  Let loop : forall n, bar n -> { k | P k /\\ forall i, n <= i < k -> ~ P i }.\n  Proof.\n    refine (fix loop n Hn { struct Hn } := match HP (exist _ n (bar_ex Hn)) with\n      | left H => exist _ n _\n      | right H => match loop (S n) _ with \n        | exist _ k Hk => exist _ k _\n      end \n    end).\n    * split; auto; intros; lia.\n    * destruct Hn; [ destruct H | ]; assumption.\n    * destruct Hk as (H1 & H2).\n      split; trivial; intros i Hi.\n      destruct (eq_nat_dec i n).\n      - subst; trivial.\n      - apply H2; lia.\n  Qed.\n\n  Hypothesis Hmin : ex minimizer.\n\n  Let bar_0 : bar 0.\n  Proof.\n    destruct Hmin as (k & H1 & H2).\n    apply in_bar_0 in H1.\n    clear HP.\n    revert H1.\n    apply nat_rev_ind' with (k := k).\n    intros i H3.\n    apply in_bar_1, H2; trivial.\n    lia.\n  Qed.\n\n  Definition minimizer_pred : sig minimizer.\n  Proof using Hmin loop.\n    destruct (loop bar_0) as (k & H1 & H2).\n    exists k; split; auto.\n    intros; apply H2; lia.\n  Defined.\n\nEnd minimizer_pred.\n\n(* Check minimizer_pred. *)\n(* Print Assumptions minimizer_pred. *)\n\n(* (* Let P be a computable predicate: *)\n(*       - whenever P n has a value (P n or not P n) then that value can be computed *)\n(*     Then minimizer P is computable as well: *)\n(*       - whenever minimizer P holds for some n, then such an n can be computed *)\n(*  *) *)\n      \n\n(* Corollary minimizer_alt (P : nat -> Prop) : *)\n(*     (forall n, P n \\/ ~ P n -> { P n } + { ~ P n }) -> ex (minimizer P) -> sig (minimizer P). *)\n(* Proof. *)\n(*   intro H; apply minimizer_pred. *)\n(*   intros (n & Hn); apply H, Hn. *)\n(* Defined. *)\n\n(* Check minimizer_alt. *)\n(* Print Assumptions minimizer_alt. *)\n\n(* Section minimizer. *)\n\n(*   Variable (R : nat -> nat -> Prop) *)\n(*            (Rfun : forall n u v, R n u -> R n v -> u = v) *)\n(*            (HR : forall n, ex (R n) -> sig (R n)). *)\n\n(*   Definition minimizer' n := R n 0 /\\ forall i, i < n -> exists u, R i (S u). *)\n\n(*   Fact minimizer_fun n m : minimizer' n -> minimizer' m -> n = m. *)\n(*   Proof. *)\n(*     intros (H1 & H2) (H3 & H4). *)\n(*     destruct (lt_eq_lt_dec n m) as [ [ H | ] | H ]; auto;  *)\n(*       [ apply H4 in H | apply H2 in H ]; destruct H as (u & Hu); *)\n(*       [ generalize (Rfun H1 Hu) | generalize (Rfun H3 Hu) ]; discriminate. *)\n(*   Qed.  *)\n\n(*   Inductive bar n : Prop := *)\n(*     | in_bar_0 : R n 0 -> bar n *)\n(*     | in_bar_1 : (exists u, R n (S u)) -> bar (S n) -> bar n. *)\n\n(*   Let bar_ex n : bar n -> ex (R n). *)\n(*   Proof. *)\n(*     induction 1 as [ n Hn | n (k & Hk) _ _ ]. *)\n(*     exists 0; auto. *)\n(*     exists (S k); trivial. *)\n(*   Qed. *)\n\n(*   Let loop : forall n, bar n -> { k | R k 0 /\\ forall i, n <= i < k -> exists u, R i (S u) }. *)\n(*   Proof. *)\n(*     refine (fix loop n Hn { struct Hn } := match HR (bar_ex Hn) with *)\n(*         | exist _ u Hu => match u as m return R _ m -> _ with *)\n(*             | 0   => fun H => exist _ n _ *)\n(*             | S v => fun H => match loop (S n) _ with *)\n(*                 | exist _ k Hk => exist _ k _ *)\n(*               end *)\n(*           end Hu *)\n(*       end). *)\n(*     * split; auto; intros; lia. *)\n(*     * destruct Hn as [ Hn | ]; trivial; exfalso; generalize (Rfun H Hn); discriminate. *)\n(*     * destruct Hk as (H1 & H2); split; trivial; intros i Hi. *)\n(*       destruct (eq_nat_dec i n). *)\n(*       - subst; exists v; trivial. *)\n(*       - apply H2; lia. *)\n(*   Qed. *)\n\n(*   Hypothesis Hmin : ex minimizer. *)\n\n(*   Let bar_0 : bar 0. *)\n(*   Proof. *)\n(*     destruct Hmin as (k & H1 & H2). *)\n(*     apply in_bar_0 in H1. *)\n(*     clear Hmin HR. *)\n(*     revert H1. *)\n(*     apply nat_rev_ind' with (k := k). *)\n(*     intros i H3. *)\n(*     apply in_bar_1, H2; trivial. *)\n(*     lia. *)\n(*   Qed. *)\n\n(*   Definition minimizer_coq : sig minimizer. *)\n(*   Proof. *)\n(*     destruct (loop bar_0) as (k & H1 & H2). *)\n(*     exists k; split; auto. *)\n(*     intros; apply H2; lia. *)\n(*   Defined. *)\n\n(* End minimizer. *)\n\n(* Check minimizer_coq. *)\n(* Print Assumptions minimizer_coq. *)\n\n(* Extraction \"minimizer.ml\" minimizer_coq. *)\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/MuRec/minimizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7453508867055778}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus Zero (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj286_coqofml_SWuDY8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7453508742106093}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Lia List Permutation. \nRequire Vector.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils. \n\nFrom Undecidability.Shared.Libs.DLW.Vec \n  Require Import pos.\n\nSet Implicit Arguments.\nSet Default Goal Selector \"!\".\n\nNotation vec_nil := (@Vector.nil _).\nNotation \"x ## v\" := (@Vector.cons _ x _ v) (at level 60, right associativity).\n\nSection vector.\n\n  Variable X : Type.\n\n  Notation vec := (@Vector.t X).\n\n(* @DLW: former definition\n\n  Inductive vec : nat -> Type :=\n    | vec_nil  : vec 0\n    | vec_cons : forall n, X -> vec n -> vec (S n).\n*)\n\n  Let vec_decomp_type n := \n    match n with\n      | 0   => Prop\n      | S n => (X * vec n)%type\n    end.\n\n  Definition vec_decomp n (v : vec n) :=\n    match v in Vector.t _ k return vec_decomp_type k with\n      | vec_nil => False\n      | x ## v  => (x,v)\n    end.\n    \n  Definition vec_head n (v : vec (S n)) := match v with x ## _ => x end.\n  Definition vec_tail n (v : vec (S n)) := match v with _ ## w => w end.\n\n  Let vec_head_tail_type n : vec n -> Prop := \n    match n with\n      | 0   => fun v => v = vec_nil\n      | S n => fun v => v = vec_head v ## vec_tail v\n    end.\n\n  Let vec_head_tail_prop n v :  @vec_head_tail_type n v.\n  Proof. induction v; simpl; auto. Qed.\n\n  Fact vec_0_nil (v : vec 0) : v = vec_nil.\n  Proof. apply (vec_head_tail_prop v). Qed.\n\n  Fact vec_head_tail n (v : vec (S n)) : v = vec_head v ## vec_tail v.\n  Proof. apply (vec_head_tail_prop v). Qed.\n\n  Fact vec_cons_inv n x y (v w : vec n) : x ## v = y ## w -> x = y /\\ v = w.\n  Proof.\n    intros H1; generalize H1; intros H2.\n    apply f_equal with (f := @vec_head _) in H1.\n    apply f_equal with (f := @vec_tail _) in H2.\n    auto.\n  Qed.\n\n  Fixpoint vec_pos n (v : vec n) : pos n -> X.\n  Proof.\n    refine (match v with\n      | vec_nil => fun p => _\n      | x ## v => fun p => _\n    end); invert pos p.\n    + exact x.\n    + exact (vec_pos _ v p).\n  Defined.\n\n  Fact vec_pos0 n (v : vec (S n)) : vec_pos v pos0 = vec_head v.\n  Proof. \n    rewrite (vec_head_tail v).\n    reflexivity.\n  Qed.\n  \n  Fact vec_pos_tail n (v : vec (S n)) p : vec_pos (vec_tail v) p = vec_pos v (pos_nxt p).\n  Proof.\n    rewrite vec_head_tail at 2; simpl; auto.\n  Qed.\n  \n  Fact vec_pos1 n (v : vec (S (S n))) : vec_pos v pos1 = vec_head (vec_tail v).\n  Proof.\n    rewrite <- vec_pos0, vec_pos_tail; auto.\n  Qed.\n\n  Fact vec_pos_ext n (v w : vec n) : (forall p, vec_pos v p = vec_pos w p) -> v = w.\n  Proof.\n    revert v w; induction n as [ | n IHn ]; intros v w H.\n    1: rewrite (vec_0_nil v), (vec_0_nil w); auto.\n    revert H; rewrite (vec_head_tail v), (vec_head_tail w); f_equal.\n    intros H; f_equal.\n    + apply (H pos0).\n    + apply IHn.\n      intros p; apply (H (pos_nxt p)).\n  Qed.\n\n  Fixpoint vec_set_pos n : (pos n -> X) -> vec n :=\n    match n return (pos n -> X) -> vec n with \n      | 0   => fun _ => vec_nil\n      | S n => fun g => g pos0 ## vec_set_pos (fun p => g (pos_nxt p))\n    end.\n\n  Fact vec_pos_set n (g : pos n -> X) p : vec_pos (vec_set_pos g) p = g p. \n  Proof.\n    revert g p; induction n as [ | n IHn ]; intros g p; pos_inv p; auto.\n    apply IHn.\n  Qed.\n\n  Fixpoint vec_change n (v : vec n) : pos n -> X -> vec n.\n  Proof.\n    refine (match v with\n      | vec_nil => fun _ _ => vec_nil\n      | y ## v  => fun p x => _\n    end).\n    pos_inv p.\n    + exact (x ## v).\n    + exact (y ## vec_change _ v p x).\n  Defined.\n\n  Fact vec_change_eq n v p q x : p = q -> vec_pos (@vec_change n v p x) q = x.\n  Proof. \n    intro; subst q; revert p x.\n    induction v; intros p ?; invert pos p; auto.\n  Qed.\n\n  Fact vec_change_neq n v p q x : p <> q -> vec_pos (@vec_change n v p x) q = vec_pos v q.\n  Proof. \n    revert p q x.\n    induction v as [ | n y v IH ]; intros p q x H; invert pos p; invert pos q; auto.\n    + destruct H; auto.\n    + apply IH; contradict H; subst; auto.\n  Qed.\n\n  Fact vec_change_idem n v p x y : vec_change (@vec_change n v p x) p y = vec_change v p y.\n  Proof.\n    apply vec_pos_ext; intros q.\n    destruct (pos_eq_dec p q).\n    + repeat rewrite vec_change_eq; auto.\n    + repeat rewrite vec_change_neq; auto.\n  Qed.\n\n  Fact vec_change_same n v p : @vec_change n v p (vec_pos v p) = v.\n  Proof.\n    apply vec_pos_ext; intros q.\n    destruct (pos_eq_dec p q).\n    + repeat rewrite vec_change_eq; subst; auto.\n    + repeat rewrite vec_change_neq; auto.\n  Qed.\n\n  Section vec_eq_dec_pos.\n\n    Fixpoint vec_eq_dec_pos n (u v : vec n) { struct u } :\n         (forall p, { vec_pos u p = vec_pos v p } + { vec_pos u p <> vec_pos v p })\n      -> { u = v } + { u <> v }.\n    Proof.\n      destruct u as [ | x n u ].\n      + rewrite (vec_0_nil v); left; reflexivity.\n      + rewrite (vec_head_tail v); generalize (vec_head v) (vec_tail v); intros y w H.\n        destruct (H pos0) as [ G1 | G1 ]; simpl vec_pos in G1; subst.\n        2:{ right; contradict G1; apply vec_cons_inv in G1; tauto. }\n        destruct (vec_eq_dec_pos _ u w) as [ G2 | G2 ]; subst.\n        * intros p; apply (H (pos_nxt p)).\n        * left; reflexivity.\n        * right; contradict G2; apply vec_cons_inv in G2; tauto.\n    Qed.\n\n  End vec_eq_dec_pos.\n\n  Variable eq_X_dec : forall x y : X, { x = y } + { x <> y }.\n\n  Fact vec_eq_dec n (u v : vec n) : { u = v } + { u <> v }.\n  Proof using eq_X_dec. apply vec_eq_dec_pos; auto. Qed.\n  \n  Fixpoint vec_list n (v : vec n) := \n    match v with  \n      | vec_nil => nil\n      | x ## v  => x::vec_list v\n    end.\n\n  Fact vec_list_In n v p : In (vec_pos v p) (@vec_list n v).\n  Proof.\n    revert p; induction v; intros p; invert pos p; auto.\n  Qed.\n\n  Fact vec_list_vec_set_pos n f : vec_list (@vec_set_pos n f) = map f (pos_list n).\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f; simpl; f_equal; auto.\n    rewrite IHn, map_map; auto.\n  Qed.\n\n  Fact map_pos_list_vec n f : map f (pos_list n) = vec_list (@vec_set_pos n f).\n  Proof. rewrite vec_list_vec_set_pos; auto. Qed.\n    \n  Fact vec_list_length n v : length (@vec_list n v) = n.\n  Proof. induction v; simpl; f_equal; auto. Defined.\n\n  Fixpoint list_vec (l : list X) : vec (length l) := \n    match l with \n      | nil  => vec_nil\n      | x::l => x ## list_vec l\n    end.\n\n  Fact list_vec_iso l : vec_list (list_vec l) = l.\n  Proof. induction l; simpl; f_equal; auto. Qed.\n\n  (* The other part needs a transport *)\n\n  Fact vec_list_iso n v : list_vec (@vec_list n v) = eq_rect_r _ v (vec_list_length v).\n  Proof. \n    induction v; simpl; f_equal; auto.\n    rewrite IHv; unfold eq_rect_r; simpl.\n    generalize (length (vec_list v)) (vec_list_length v).\n    intros; subst; cbv; auto.\n  Qed.\n\n  Definition list_vec_full l : { v : vec (length l) | vec_list v = l }.\n  Proof. exists (list_vec l); apply list_vec_iso. Qed.\n\n  Fact vec_list_inv n v x : In x (@vec_list n v) -> exists p, x = vec_pos v p.\n  Proof.\n    induction v as [ | n y v IHl ].\n    1: intros [].\n    intros [ H | H ]; subst.\n    + exists pos0; auto.\n    + destruct IHl as (p & Hp); auto.\n      subst; exists (pos_nxt p); auto.\n  Qed.\n \n  Fact vec_list_In_iff n v x : In x (@vec_list n v) <-> exists p, x = vec_pos v p.\n  Proof.\n    split.\n    + apply vec_list_inv.\n    + intros (p & ->); apply vec_list_In.\n  Qed.\n\n  Variable x : X.\n\n  Fixpoint in_vec n (v : vec n) : Prop :=\n    match v with\n      | vec_nil => False\n      | y ## v  => y = x \\/ in_vec v\n    end.\n\n  Fact in_vec_list n v : @in_vec n v <-> In x (vec_list v).\n  Proof. induction v; simpl; tauto. Qed.\n\nEnd vector.\n\nNotation vec := Vector.t.\nNotation vec_cons := (fun x => @Vector.cons _ x _).\n\nFact in_vec_pos X n (v : vec X n) p : in_vec (vec_pos v p) v.\nProof. revert p; induction v; intros p; invert pos p; auto. Qed.\n\nFact in_vec_inv X n (v : vec X n) x : in_vec x v -> exists p, vec_pos v p = x.\nProof.\n  induction v as [ | n y v IHv ]; simpl in_vec; try tauto.\n  intros [ -> | H ].\n  + exists pos0; auto.\n  + destruct (IHv H) as (p & <-).\n    exists (pos_nxt p); auto.\nQed.\n\nFact in_vec_dec_inv X n (v : vec X n) : \n        (forall x y : X, { x = y } + { x <> y })\n     -> forall x, in_vec x v -> { p | vec_pos v p = x }.\nProof.\n  intros dec.\n  induction v as [ | x n v IHv ].\n  + intros _ [].\n  + intros y Hy.\n    destruct (dec x y) as [ H | H ].\n    * exists pos0; auto.\n    * destruct (IHv y) as (p & Hp).\n      - destruct Hy; tauto.\n      - exists (pos_nxt p); auto.\nQed.\n\n(* notations *)\n\nSection vec_app_split.\n\n  Variable (X : Type) (n m : nat).\n\n  Definition vec_app (v : vec X n) (w : vec X m) : vec X (n+m).\n  Proof. \n    apply vec_set_pos; intros p.\n    destruct (pos_both _ _ p) as [ q | q ]; refine (vec_pos _ q); assumption.\n  Defined.\n\n  Definition vec_split (v : vec X (n+m)) : vec X n * vec X m.\n  Proof.\n    split; apply vec_set_pos; intros p; refine (vec_pos v _).\n    + apply pos_left, p.\n    + apply pos_right, p.\n  Defined.\n\n  Fact vec_app_split u : let (v,w) := vec_split u in vec_app v w = u.\n  Proof.\n    case_eq (vec_split u); intros v w; unfold vec_split, vec_app; intros H.\n    injection H; clear H; intros Hw Hv.\n    apply vec_pos_ext; unfold vec_app; simpl.\n    intros p; rewrite vec_pos_set. \n    case_eq (pos_both n m p); intros q Hq.\n    + rewrite <- Hv, vec_pos_set; f_equal.\n      apply f_equal with (f := @pos_lr _ _) in Hq.\n      simpl in Hq; rewrite <- Hq; apply pos_lr_both.\n    + rewrite <- Hw, vec_pos_set; f_equal.\n      apply f_equal with (f := @pos_lr _ _) in Hq.\n      simpl in Hq; rewrite <- Hq; apply pos_lr_both.\n  Qed.\n\n  Fact vec_split_app v w : vec_split (vec_app v w) = (v,w).\n  Proof.\n    unfold vec_split, vec_app; f_equal; apply vec_pos_ext; intros p; repeat rewrite vec_pos_set.\n    + rewrite pos_both_left; auto.\n    + rewrite pos_both_right; auto.\n  Qed.\n\n  Fact vec_pos_app_left v w i : vec_pos (vec_app v w) (pos_left _ i) = vec_pos v i.\n  Proof. unfold vec_app; rewrite vec_pos_set, pos_both_left; auto. Qed.\n\n  Fact vec_pos_app_right v w i : vec_pos (vec_app v w) (pos_right _ i) = vec_pos w i.\n  Proof. unfold vec_app; rewrite vec_pos_set, pos_both_right; auto. Qed.\n\nEnd vec_app_split.\n\nFact vec_app_nil X n v : @vec_app X 0 n vec_nil v = v.\nProof.\n  apply vec_pos_ext; unfold vec_app; simpl; intros p.\n  rewrite vec_pos_set; auto.\nQed.\n\nFact vec_app_cons X n m x v w : @vec_app X (S n) m (x##v) w = x##vec_app v w.\nProof.\n  apply vec_pos_ext; unfold vec_app; intros p.\n  rewrite vec_pos_set; simpl in p.\n  analyse pos p.\n  + simpl; auto.\n  + simpl vec_pos at 3; rewrite vec_pos_set.\n    simpl pos_both.\n    destruct (pos_both n m p); auto.\nQed.\n\nFact vec_change_app_left X n m v w i x :\n  vec_change (@vec_app X n m v w) (pos_left m i) x = vec_app (vec_change v i x) w.\nProof.\n  revert v. induction i as [|?? IH].\n  - intros v. rewrite (Vector.eta v), vec_app_cons. simpl. now rewrite vec_app_cons. \n  - intros v. rewrite (Vector.eta v), vec_app_cons. simpl. now rewrite vec_app_cons, IH.\nQed.\n\nFact vec_change_app_right X n m v w i x :\n  vec_change (@vec_app X n m v w) (pos_right _ i) x = vec_app v (vec_change w i x).\nProof.\n  induction v as [|??? IH].\n  - now rewrite !vec_app_nil.\n  - now rewrite !vec_app_cons, <- IH.\nQed.\n\nSection vec_map_def.\n\nVariable (X Y : Type).\nVariable (f : X -> Y).\n\nFixpoint vec_map n (v : vec X n) :=\n  match v with \n    | vec_nil => vec_nil\n    | x ## v  => f x ## vec_map v \n  end.\n\nEnd vec_map_def.\n\n\nSection vec_map.\n\n  Variable (X Y : Type).\n\n  Fixpoint vec_in_map n v : (forall x, @in_vec X x n v -> Y) -> vec Y n.\n  Proof.\n    refine (match v with\n      | vec_nil  => fun _ => vec_nil\n      | x##v     => fun f => f x _ ## @vec_in_map _ v _\n    end).\n    + left; auto.\n    + intros y Hy; apply (f y); right; auto.\n  Defined.\n\n  Fact vec_in_map_vec_map_eq f n v : @vec_in_map n v (fun x _ => f x) = vec_map f v.\n  Proof. induction v; simpl; f_equal; auto. Qed.\n\n  Fact vec_in_map_ext n v f g : (forall x Hx, @f x Hx = @g x Hx) \n                             -> @vec_in_map n v f = vec_in_map v g.\n  Proof. revert f g; induction v; simpl; intros; f_equal; auto. Qed.\n\n  Fact vec_map_ext f g n v : (forall x, in_vec x v -> f x = g x) \n                          -> @vec_map X Y f n v = vec_map g v.\n  Proof.\n    intros H.\n    do 2 rewrite <- vec_in_map_vec_map_eq.\n    apply vec_in_map_ext, H.\n  Qed.\n\n  Fact vec_list_vec_map (f : X -> Y) n v : vec_list (@vec_map X Y f n v) = map f (vec_list v).\n  Proof. induction v; simpl; f_equal; auto. Qed.\n\nEnd vec_map.\n\nFact vec_map_map X Y Z (f : X -> Y) (g : Y -> Z) n (v : vec _ n) :\n          vec_map g (vec_map f v) = vec_map (fun x => g (f x)) v.\nProof. induction v; simpl; f_equal; auto. Qed. \n\nSection vec_map2.\n\n  (* Definitions taken from stdlib *)\n  \n  Definition case0 {A} (P:vec A 0 -> Type) (H:P (@Vector.nil A)) v:P v :=\n    match v with\n    |vec_nil => H\n    |_ => fun devil => False_ind (@IDProp) devil (* subterm !!! *)\n    end.\n\n  Definition caseS' {A} {n : nat} (v : vec A (S n)) : forall (P : vec A (S n) -> Type)\n                                                      (H : forall h t, P (h ## t)), P v :=\n    match v with\n    | h ## t => fun P H => H h t\n    | _ => fun devil => False_rect (@IDProp) devil\n    end.\n\n  Definition rect2 {A B} (P:forall {n}, vec A n -> vec B n -> Type)\n             (bas : P vec_nil vec_nil) (recvec : forall {n v1 v2}, P v1 v2 ->\n                                                              forall a b, P (a ## v1) (b ## v2)) :=\n    fix rect2_fix {n} (v1 : vec A n) : forall v2 : vec B n, P v1 v2 :=\n      match v1 with\n      | vec_nil  => fun v2 => case0 _ bas v2\n      | h1 ## t1 => fun v2 => caseS' v2 (fun v2' => P (h1##t1) v2') (fun h2 t2 => recvec (rect2_fix t1 t2) h1 h2)\n      end.\n\n  Definition vec_map2 {A B C} (g:A -> B -> C) :\n    forall (n : nat), vec A n -> vec B n -> vec C n :=\n    @rect2 _ _ (fun n _ _ => vec C n) vec_nil (fun _ _ _ H a b => (g a b) ## H).\n\n  Global Arguments vec_map2 {A B C} g {n} v1 v2.\n\nEnd vec_map2.\n\nFact vec_pos_map X Y (f : X -> Y) n (v : vec X n) p : vec_pos (vec_map f v) p = f (vec_pos v p).\nProof.\n  revert p; induction v; intros p; pos_inv p; simpl; auto.\nQed.\n\nFact vec_map_set_pos X Y f n s : @vec_map X Y f _ (@vec_set_pos _ n s)\n                               = vec_set_pos (fun p => f (s p)).\nProof.\n  apply vec_pos_ext; intros p.\n  rewrite vec_pos_map, vec_pos_set, vec_pos_set; auto.\nQed.\n\nSection vec_plus.\n\n  Variable n : nat.\n\n  Definition vec_plus (v w : vec nat n) := vec_set_pos (fun p => vec_pos v p + vec_pos w p).\n  Definition vec_zero : vec nat n := vec_set_pos (fun _ => 0).\n  \n  Fact vec_pos_plus v w p : vec_pos (vec_plus v w) p = vec_pos v p + vec_pos w p.\n  Proof.\n    unfold vec_plus; rewrite vec_pos_set; auto.\n  Qed.\n\n  Fact vec_zero_plus v : vec_plus vec_zero v = v.\n  Proof. \n    apply vec_pos_ext.\n    intros p; unfold vec_zero, vec_plus. \n    repeat rewrite vec_pos_set; auto.\n  Qed.\n  \n  Fact vec_zero_spec p : vec_pos vec_zero p = 0.\n  Proof. unfold vec_zero; rewrite vec_pos_set; trivial. Qed.\n\n  Fact vec_add_comm v w : vec_plus v w = vec_plus w v.\n  Proof.\n    apply vec_pos_ext.\n    intros p; unfold vec_zero, vec_plus.\n    repeat rewrite vec_pos_set; lia.\n  Qed.\n\n  Fact vec_add_assoc u v w : vec_plus u (vec_plus v w) = vec_plus (vec_plus u v) w.\n  Proof.\n    apply vec_pos_ext.\n    intros p; unfold vec_zero, vec_plus.\n    repeat rewrite vec_pos_set; lia.\n  Qed.\n\n  Fact vec_plus_is_zero u v : vec_zero = vec_plus u v -> u = vec_zero /\\ v = vec_zero.\n  Proof.\n   unfold vec_zero, vec_plus; intros H; split; apply vec_pos_ext;\n   intros p; apply f_equal with (f := fun v => vec_pos v p) in H;\n   repeat rewrite vec_pos_set in * |- *; lia.\n  Qed.\n  \n  Definition vec_one p : vec _ n := vec_set_pos (fun q => if pos_eq_dec p q then 1 else 0).\n  \n  Fact vec_one_spec_eq p q : p = q -> vec_pos (vec_one p) q = 1.\n  Proof.\n    intros [].\n    unfold vec_one; rewrite vec_pos_set.\n    destruct (pos_eq_dec p p) as [ | [] ]; auto.\n  Qed.\n  \n  Fact vec_one_spec_neq p q : p <> q -> vec_pos (vec_one p) q = 0.\n  Proof.\n    intros H.\n    unfold vec_one; rewrite vec_pos_set.\n    destruct (pos_eq_dec p q) as [ | ]; auto.\n    destruct H; auto.\n  Qed.\n  \nEnd vec_plus.\n\nArguments vec_plus {n}.\nArguments vec_zero {n}.\nArguments vec_one {n}.\n\nReserved Notation \" e '#>' x \" (at level 58, format \"e #> x\").\nReserved Notation \" e [ v / x ] \" (at level 57, v at level 0, x at level 0, \n                                   left associativity, format \"e [ v / x ]\").\n\nLocal Notation \" e '#>' x \" := (vec_pos e x).\nLocal Notation \" e [ v / x ] \" := (vec_change e x v).\n\nTactic Notation \"rew\" \"vec\" :=\n  repeat lazymatch goal with \n    |              |- context[ _[_/?x]#>?x ] => rewrite vec_change_eq with (p := x) (1 := eq_refl)\n    | _ : ?x = ?y  |- context[ _[_/?x]#>?y ] => rewrite vec_change_eq with (p := x) (q := y)\n    | _ : ?y = ?x  |- context[ _[_/?x]#>?y ] => rewrite vec_change_eq with (p := x) (q := y)\n    | _ : ?x <> ?y |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y)\n    | _ : ?y <> ?x |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y)\n    |              |- context[ vec_pos vec_zero ?x ] => rewrite vec_zero_spec with (p := x)\n    |              |- context[ vec_pos (vec_one ?x) ?x ] => rewrite vec_one_spec_eq with (p := x) (1 := eq_refl)\n    | _ : ?x = ?y  |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_eq with (p := x) (q := y)\n    | _ : ?y = ?x  |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_eq with (p := x) (q := y)\n    | _ : ?x <> ?y |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_neq with (p := x) (q := y)\n    | _ : ?y <> ?x |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_neq with (p := x) (q := y)\n    | |- context[ _[_/?x][_/?x] ] => rewrite vec_change_idem with (p := x) \n    | |- context[ ?v[(?v#>?x)/?x] ] => rewrite vec_change_same with (p := x)\n    | |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y); [ | discriminate ]\n    | |- context[ vec_plus vec_zero ?x ] => rewrite vec_zero_plus with (v := x)\n    | |- context[ vec_plus ?x vec_zero ] => rewrite (vec_add_comm x vec_zero); rewrite vec_zero_plus with (v := x)\n    | |- context[ (vec_set_pos ?f) #> ?p ] => rewrite (vec_pos_set f p)\n    | |- context[ (vec_map ?f ?v) #> ?p ] => rewrite (vec_pos_map f v p)\n    | |- vec_plus ?x ?y = vec_plus ?y ?x => apply vec_add_comm\n  end; auto.\n\nTactic Notation \"vec\" \"split\" hyp(v) \"with\" ident(n) :=\n  rewrite (vec_head_tail v); generalize (vec_head v) (vec_tail v); clear v; intros n v.\n\nTactic Notation \"vec\" \"nil\" hyp(v) := rewrite (vec_0_nil v).\n\nFact Forall2_vec_list X Y (R : X -> Y -> Prop) n v w : Forall2 R (@vec_list X n v) (vec_list w) <-> forall p, R (vec_pos v p) (vec_pos w p).\nProof.\n  revert v w; induction n as [ | n IHn ]; intros v w.\n  + vec nil v; vec nil w; split; simpl.\n    * intros _ p; invert pos p.\n    * constructor.\n  + vec split v with x; vec split w with y.\n    simpl vec_list; rewrite Forall2_cons_inv, IHn.\n    split.\n    * intros (H1 & H2) p; invert pos p; auto.\n    * intros H; split.\n      - apply (H pos0).\n      - intro; apply (H (pos_nxt _)).\nQed.\n\nFact vec_zero_S n : @vec_zero (S n) = 0##vec_zero.\nProof. auto. Qed.\n\nFact vec_one_fst n : @vec_one (S n) pos0 = 1##vec_zero.\nProof. apply vec_pos_ext; intros p; pos_inv p; rew vec. Qed.\n\nLemma vec_change_comm {X} n v p q x y : p <> q ->\nvec_change (@vec_change X n v p x) q y = vec_change (vec_change v q y) p x.\nProof.\n  intros Hpq. apply vec_pos_ext; intros r.\n  destruct (pos_eq_dec r p); destruct (pos_eq_dec r q); subst; now rew vec.\nQed.\n\nFact vec_one_nxt n p : @vec_one (S n) (pos_nxt p) = 0##vec_one p.\nProof.\n  apply vec_pos_ext.\n  unfold vec_one.\n  intros q; rewrite vec_pos_set.\n  pos_inv q.\n  + simpl; auto.\n  + rewrite <- vec_pos_tail.\n    simpl vec_tail.\n    rewrite vec_pos_set.\n    destruct (pos_eq_dec p q) as [ | C ].\n    * subst.\n      destruct (pos_eq_dec (pos_nxt q) (pos_nxt q)) as [ | [] ]; auto.\n    * destruct (pos_eq_dec (pos_nxt p) (pos_nxt q)) as [ | ]; auto.\n      destruct C; apply pos_nxt_inj; auto.\nQed.\n\nFact vec_plus_cons n x v y w : @vec_plus (S n) (x##v) (y##w) = x+y ## vec_plus v w.\nProof.\n  apply vec_pos_ext; unfold vec_plus.\n  intros p; pos_inv p; repeat (rewrite vec_pos_set; simpl; auto).\nQed.\n\nFact vec_change_succ n v p : v[(S (v#>p))/p] = @vec_plus n (vec_one p) v.\nProof.\n  apply vec_pos_ext.\n  intros q.\n  destruct (pos_eq_dec p q); rew vec;\n  rewrite vec_pos_plus; rew vec; subst; auto.\nQed.\n\nFact vec_change_pred n v p u : v#>p = S u -> v = @vec_plus n (vec_one p) (v[u/p]).\nProof.\n  intros Hu.\n  apply vec_pos_ext.\n  intros q.\n  destruct (pos_eq_dec p q); rew vec;\n  rewrite vec_pos_plus; rew vec; subst; auto.\nQed.\n\nFixpoint vec_sum n (v : vec nat n) := \n  match v with \n    | vec_nil => 0\n    | x##w    => x + vec_sum w\n  end.\n  \nFact vec_sum_plus n v w : @vec_sum n (vec_plus v w) = vec_sum v + vec_sum w.\nProof.\n  revert w; induction v; intros w.\n  1: rewrite (vec_0_nil (vec_plus _ _)), (vec_0_nil w); auto.\n  rewrite (vec_head_tail w), vec_plus_cons; simpl.\n  rewrite IHv; lia.\nQed.\n\nFact vec_sum_zero n : @vec_sum n vec_zero = 0.\nProof. induction n; simpl; auto. Qed.\n\nFact vec_sum_one n p : @vec_sum n (vec_one p) = 1.\nProof.\n  revert p; induction n as [ | n IHn ]; intros p.\n  1: invert pos p.\n  pos_inv p.\n  + rewrite vec_one_fst.\n    simpl; f_equal; apply vec_sum_zero.\n  + rewrite vec_one_nxt.\n    unfold vec_sum; fold vec_sum.\n    rewrite IHn; auto.\nQed.\n  \nFact vec_sum_is_zero n v : @vec_sum n v = 0 -> v = vec_zero.\nProof.\n  induction v as [ | n x v IHv ]; simpl; auto.\n  simpl; rewrite vec_zero_S; intros; f_equal.\n  + lia.\n  + apply IHv; lia.\nQed.\n\nFact vec_sum_is_nzero n v : 0 < @vec_sum n v -> { p : _ & { w | v = vec_plus (vec_one p) w } }.\nProof.\n  induction v as [ | [ | x] n v IHv ]; intros Hv; simpl in Hv.\n  + lia.\n  + apply IHv in Hv.\n    destruct Hv as (p & w & Hw).\n    exists (pos_nxt p), (0##w); rewrite vec_one_nxt.\n    rewrite vec_plus_cons; f_equal; auto.\n  + exists pos0, (x##v).\n    rewrite vec_one_fst, vec_plus_cons; rew vec.\nQed.\n\nSection vec_nat_induction.\n\n  (* Specialized induction on vec nat n, with constant n *)\n\n  Variable (n : nat) (P : vec nat n -> Type).\n  \n  Hypothesis HP0 : P vec_zero.\n  Hypothesis HP1 : forall p, P (vec_one p).\n  Hypothesis HP2 : forall v w, P v -> P w -> P (vec_plus v w).\n  \n  Theorem vec_nat_induction v : P v.\n  Proof using HP0 HP1 HP2.\n    induction v as [ v IHv ] using (measure_rect (@vec_sum n)).\n    case_eq (vec_sum v).\n    + intros Hv; apply vec_sum_is_zero in Hv; subst; auto.\n    + intros x Hx.\n      destruct (vec_sum_is_nzero v) as (p & w & Hw).\n      * lia.\n      * subst.\n        apply HP2; auto.\n        apply IHv.\n       rewrite vec_sum_plus, vec_sum_one; auto.\n  Qed.\n  \nEnd vec_nat_induction.\n\nSection vec_map_list.\n\n  Variable X : Type.\n\n  (* morphism between vec nat n and (list X)/~p *)\n\n  Fixpoint vec_map_list X n v : (pos n -> X) -> list X :=\n    match v in vec _ m return (pos m -> _) -> _ with\n      | vec_nil => fun _ => nil\n      | a##v    => fun f => list_repeat (f pos0) a ++ vec_map_list v (fun p => f (pos_nxt p))\n    end.\n\n  Fact vec_map_list_zero n f : vec_map_list (@vec_zero n) f = @nil X.\n  Proof. revert f; induction n; intros f; simpl; auto. Qed.\n\n  Fact vec_map_list_one n p f : vec_map_list (@vec_one n p) f = f p :: @nil X.\n  Proof.\n    revert f; induction p; intro.\n    + rewrite vec_one_fst; simpl; rewrite vec_map_list_zero; auto.\n    + rewrite vec_one_nxt; simpl; rewrite IHp; auto.\n  Qed.\n\n  (* The morphism *)\n\n  Fact vec_map_list_plus n v w f : @vec_map_list X n (vec_plus v w) f ~p vec_map_list v f ++ vec_map_list w f.\n  Proof.\n    revert v w f; induction n as [ | n IHn ]; intros v w f.\n    + rewrite (vec_0_nil (vec_plus v w)), (vec_0_nil v), (vec_0_nil w); simpl; auto.\n    + rewrite (vec_head_tail v), (vec_head_tail w), vec_plus_cons.\n      generalize (vec_head v) (vec_tail v) (vec_head w) (vec_tail w); clear v w; intros x v y w.\n      simpl.\n      rewrite list_repeat_plus.\n      solve list eq; apply Permutation_app; auto.\n      apply Permutation_trans with (list_repeat (f pos0) y \n                                 ++ vec_map_list v (fun p => f (pos_nxt p)) \n                                 ++ vec_map_list w (fun p => f (pos_nxt p))).\n      * apply Permutation_app; auto.\n      * do 2 rewrite <- app_ass.\n        apply Permutation_app; auto.\n       apply Permutation_app_comm.\n  Qed.\n\nEnd vec_map_list.\n\nFact map_vec_map_list X Y (f : X -> Y) n v g : map f (@vec_map_list _ n v g) = vec_map_list v (fun p => f (g p)).\nProof.\n  revert g; induction v; intro; simpl; auto.\n  rewrite map_app; f_equal; auto.\n  rewrite map_list_repeat; auto.\nQed.\n\nSection fun2vec.\n\n  Variable X : Type.\n\n  Fixpoint fun2vec i n f : vec X _ :=\n    match n with \n      | 0   => vec_nil\n      | S n => f i##fun2vec (S i) n f\n    end.\n\n  Fact fun2vec_id i n f : fun2vec i n f = vec_set_pos (fun p => f (i+pos2nat p)).\n  Proof.\n    revert i; induction n as [ | n IHn ]; intros i; simpl; f_equal; auto.\n    rewrite IHn.\n    apply vec_pos_ext; intros; do 2 rewrite vec_pos_set; f_equal.\n    rewrite pos2nat_nxt; lia.\n  Qed.\n\n  Fact fun2vec_lift i n f : fun2vec i n (fun j => f (S j)) = fun2vec (S i) n f.\n  Proof. revert i f; induction n; intros; simpl; f_equal; auto. Qed.\n\n  Fact vec_pos_fun2vec i n f p : vec_pos (fun2vec i n f) p = f (i+pos2nat p).\n  Proof. rewrite fun2vec_id, vec_pos_set; auto. Qed.\n\n  Definition vec2fun n (v : vec X n) x i := \n    match le_lt_dec n i with\n      | left  _ => x\n      | right H => vec_pos v (nat2pos H)\n    end.\n\n  Fact fun2vec_vec2fun n v x : fun2vec 0 n (@vec2fun n v x) = v.\n  Proof.\n    apply vec_pos_ext.\n    intros p; rewrite vec_pos_fun2vec; simpl.\n    unfold vec2fun.\n    generalize (pos2nat_prop p).\n    destruct (le_lt_dec n (pos2nat p)); try lia. \n    rewrite nat2pos_pos2nat; auto.\n  Qed.\n\n  Fact vec2fun_fun2vec n f x i : i < n -> @vec2fun n (fun2vec 0 n f) x i = f i.\n  Proof.\n    intros H.\n    unfold vec2fun.\n    destruct (le_lt_dec n i); try lia.\n    rewrite vec_pos_fun2vec, pos2nat_nat2pos; auto.\n  Qed. \n\nEnd fun2vec.\n\nSection map_vec_pos_equiv.\n\n  Variable (X : Type) (R : X -> X -> Prop)\n           (Y : Type) (T : Y -> Y -> Prop)\n           (T_refl : forall y, T y y)\n           (T_trans : forall x y z, T x y -> T y z -> T x z). \n\n  Theorem map_vec_pos_equiv n (f : vec X n -> Y) : \n           (forall p v x y, R x y -> T (f (v[x/p])) (f (v[y/p])))\n        -> forall v w, (forall p, R (v#>p) (w#>p)) -> T (f v) (f w).\n  Proof using T_refl T_trans.\n    revert f; induction n as [ | n IHn ]; intros f Hf v w H.\n    + vec nil v; vec nil w; auto.\n    + apply T_trans with (y := f (v[(w#>pos0)/pos0])).\n      * rewrite <- (vec_change_same v pos0) at 1; auto.\n      * revert H.\n        vec split v with a; vec split w with b; intros H; simpl.\n        apply IHn with (f := fun v => f(b##v)).\n        - intros p q x y Hxy.\n          apply (Hf (pos_nxt p) (b##q)); auto.\n        - intros p; apply (H (pos_nxt p)).\n  Qed. \n\nEnd map_vec_pos_equiv.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/Shared/Libs/DLW/Vec/vec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7453166150912012}}
{"text": "Set Implicit Arguments.\n\nSection PAIRS.\nVariable A:Type.\nVariable eq_dec : forall (v1 v2:A), {v1 = v2} + {v1 <> v2}.\n\nDefinition pair_In (x:A) (p:(A*A)%type) :=\n  x = fst p \\/ x = snd p.\n\nLemma pair_in_left:\n  forall (x y:A),\n  pair_In x (x, y).\nProof.\n  intros.\n  unfold pair_In.\n  auto.\nQed.\n\nLemma pair_in_right:\n  forall (x y:A),\n  pair_In y (x, y).\nProof.\n  intros.\n  unfold pair_In.\n  auto.\nQed.\n\nLemma pair_in_inv:\n  forall (v v1 v2:A),\n  pair_In v (v1, v2) ->\n  v = v1 \\/ v = v2.\nProof.\n  intros.\n  unfold pair_In in *.\n  simpl in *.\n  assumption.\nQed.\n\nDefinition pair_mem (x:A) (p:(A*A)%type) := let (y, z) := p in\n  if (eq_dec x y) then true else\n  if (eq_dec x z) then true else false.\n\nLemma pair_mem_prop:\n  forall x p,\n  pair_mem x p = true -> pair_In x p.\nProof.\n  intros.\n  unfold pair_mem in *.\n  destruct p.\n  destruct (eq_dec x a).\n  + subst.\n    apply pair_in_left.\n  + destruct (eq_dec x a0).\n    subst.\n    apply pair_in_right.\n    inversion H.\nQed.\n\nLemma pair_mem_from_prop:\n  forall x p,\n  pair_In x p ->\n  pair_mem x p = true.\nProof.\n  intros.\n  destruct p as (v1, v2).\n  inversion H.\n  - simpl in *.\n    subst.\n    destruct (eq_dec v1 v1).\n    + trivial.\n    + contradiction n. (* absurd *)\n      trivial.\n  - simpl in *; subst.\n    destruct (eq_dec v2 v1).\n    + trivial.\n    + destruct (eq_dec v2 v2).\n      * trivial.\n      * contradiction n0.\n        trivial.\nQed.\n\nLemma pair_eq_dec:\n  forall (v1 v2:(A*A)%type), {v1 = v2} + {v1 <> v2}.\nProof.\n  intros.\n  destruct v1 as (x1, x2).\n  destruct v2 as (y1, y2).\n  destruct (eq_dec x1 y1).\n  destruct (eq_dec x2 y2).\n  subst. left. auto.\n  subst. right. intuition. inversion H. apply n in H1. assumption.\n  subst. right. intuition. inversion H. apply n in H1. assumption.\nDefined.\n\nEnd PAIRS.\n\nLemma pair_eq_dec_2\n  {A B:Type}\n  (a_eq_dec:(forall (a a':A), {a = a'} + {a <> a'}))\n  (b_eq_dec:(forall (b b':B), {b = b'} + {b <> b'})):\n\n  forall (p p': A * B),\n  {p = p'} + {p <> p'}.\nProof.\n  intros.\n  destruct p as (a, b).\n  destruct p' as (a', b').\n  destruct (a_eq_dec a a'), (b_eq_dec b b').\n  - subst; left; auto.\n  - subst; right; intuition;\n    inversion H; subst; contradiction n; trivial.\n  - subst; right; intuition;\n    inversion H; subst; contradiction n; trivial.\n  - subst; right; intuition;\n    inversion H; subst; contradiction n; trivial.\nDefined.\n\n(*\nImplicit Arguments pair_In.\nImplicit Arguments pair_mem.\nImplicit Arguments pair_eq_dec.\n*)\n\nSection Flip.\n\n  (** Reverses a pair. *)\n\n  Definition flip {A:Type} {B:Type} (e:A*B) := (snd e, fst e).\n\n  Lemma flip_rw:\n    forall {A:Type} {B:Type} (x:A*B),\n    flip (flip x) = x.\n  Proof.\n    intros.\n    destruct x.\n    auto.\n  Qed.\nEnd Flip.", "meta": {"author": "cogumbreiro", "repo": "aniceto-coq", "sha": "a719321532dd55643f14ec99215891641ee912ec", "save_path": "github-repos/coq/cogumbreiro-aniceto-coq", "path": "github-repos/coq/cogumbreiro-aniceto-coq/aniceto-coq-a719321532dd55643f14ec99215891641ee912ec/src/Pair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7453166083690032}}
{"text": "Require Export Coq.omega.Omega.\nSection FiniteSet.\n\n  Class FiniteSet (A : Type) :=\n    {\n      t : Type;\n      contains : A -> t -> bool;\n      add : A -> t -> t;\n      union : t -> t -> t;\n      cardinal : t -> nat;\n      empty : t;\n      add_idemp : forall a b s, contains a s = true -> contains a (add b s) = true;\n      add_contains : forall a s, contains a (add a s) = true;\n      cardinal_bound : forall s s', cardinal (union s s') <= cardinal s + cardinal s';\n      empty_contains : forall a, contains a empty = false;\n      add_cardinal_bound : forall a s, cardinal (add a s) <= 1 + cardinal s;\n      cardinal_empty : cardinal empty = 0;\n      cardinal_not_in : forall a s, contains a s = false -> cardinal (add a s) = 1 + cardinal s;\n      union_empty : forall s, union s empty = s;\n    }.\n  Definition single {A } {FS : FiniteSet A} (a : A) := add a empty.\n  Notation \"s1 ∪ s2\" := (union s1 s2) (at level 60).\n\n\n  Lemma singleton_size : forall A (FS : FiniteSet A) a, cardinal (single a) = 1.\n    Proof.\n      intros. unfold single. specialize (cardinal_not_in a empty) as H.\n      specialize (H (empty_contains a)). rewrite cardinal_empty in H. auto.\n    Qed.\n\nEnd FiniteSet.\n\nSection PDL.\n  Context (prog prop : Type).\n  \n  Notation \"s1 ∪ s2\" := (union s1 s2) (at level 60).\n  Inductive pdl_formula := \n    | AtomF (p : prop)\n    | Box (α : pdl_program) (φ : pdl_formula)\n    | Imp (φ ψ : pdl_formula)\n    | Bot\n  with pdl_program :=\n    | AtomP (p : prog)\n    | Plus (α β : pdl_program)\n    | Seq (α β : pdl_program)\n    | Star (α : pdl_program)\n    | TestP (φ : pdl_formula)\n  .\n  Context (FS : FiniteSet pdl_formula).\n\n  Fixpoint formula_length (φ : pdl_formula) :=\n    match φ with\n    | AtomF _ => 1\n    | Box α φ => 1 + program_length α + formula_length φ\n    | Imp φ ψ => 1 + formula_length φ + formula_length ψ\n    | Bot => 1\n  end\n  with program_length (α : pdl_program) :=\n    match α with\n    | AtomP _ => 1\n    | Plus α β => 1 + program_length α + program_length β\n    | Seq α β => 1 + program_length α + program_length β\n    | Star α => 1 + program_length α\n    | TestP φ => 1 + formula_length φ\n  end.\n\n  Definition max x y := if x <? y then y else x.\n\n  Lemma max_le_plus : forall x y, max x y <= x + y.\n  Proof.\n    intros. unfold max. destruct (x <? y); omega.\n  Qed.\n\n  Fixpoint formula_height φ :=\n    match φ with\n    | AtomF _ | Bot => 1\n    | Imp ϕ ψ => 1 + max (formula_height ϕ) (formula_height ψ)\n    | Box α ψ => 1 + max (formula_height ψ) (program_height α) end\n   with program_height α :=\n    match α with\n    | AtomP _ => 1 \n    | Plus α β => 1 + max (program_height α) (program_height β)\n    | Seq α β  =>  1 + max (program_height α) (program_height β)\n    | Star α => 1 + program_height α\n    | TestP φ => 1 + formula_height φ end.\n\n  Ltac solve_hs :=\n    simpl;\n    do 30 match goal with\n    | |- context [ max ?x ?y  ] => unfold max\n    | |- context [ ?x <? ?y  ] => destruct (x <? y)\n    | _ => try omega end.\n\n\n  Lemma height_le_size_pdl : forall φ, formula_height φ <= formula_length φ.\n    Proof.\n      induction φ; intros; solve_hs.\n      enough (forall α, program_height α <= program_length α).\n      - specialize (H α). solve_hs.\n      - induction α0; solve_hs.\n        (* this is basically our original goal... inducting won't give new information  *)\n    Abort.\n\n  Scheme pdl_formula_program := Induction for pdl_formula Sort Prop \n                                                    with pdl_program_formula := Induction for pdl_program Sort Prop.\n  Combined Scheme pdl_formula_program_mutind from pdl_formula_program, pdl_program_formula.\n\n\n  (*So for one of the cases of formula, we needed a proposition on programs, and for one of the cases of\n    program we needed one for formula. Cases like these often get solved with mutual induction*)\n\n  Lemma height_le_size_pdl' : (forall φ, formula_height φ <= formula_length φ) /\\\n                             (forall α, program_height α <= program_length α).\n    Proof.\n      apply pdl_formula_program_mutind; intros; solve_hs.\n    Qed.\n\n  Lemma height_le_size_pdl : forall φ, formula_height φ <= formula_length φ.\n  Proof.\n    destruct height_le_size_pdl'. auto.\n  Qed.\n\n\n  Fixpoint fl_closure φ  : t :=\n    match φ with\n    | AtomF _ | Bot => single φ\n    | Imp ϕ ψ => (single φ) ∪ (fl_closure ϕ) ∪ (fl_closure ψ)\n    | Box α ψ => (fl_closure_box α ψ) ∪ fl_closure ψ\n    end\n  with fl_closure_box α φ:=\n    single (Box α φ) ∪\n    match α with\n    | AtomP p => empty\n    | Plus α β => fl_closure_box α φ ∪ fl_closure_box β φ\n    | Seq α β => fl_closure_box α (Box β φ) ∪ fl_closure_box β φ\n    | Star α => fl_closure_box α (Box (Star α) φ)\n    | TestP ψ => fl_closure ψ\n   end.\n\n(*tactic that accomplishes basic finite set size reasoning for the following proofs*)\n\nLtac union_len :=\n  simpl;\n  do 30 match goal with\n  | |- context [union ?s empty] => rewrite union_empty\n  | |- context [ (single ?x)  ] =>\n    specialize (singleton_size _ _ x); intros; remember (single x); try omega\n  | |- cardinal (?s1 ∪ ?s2) <= _ => rewrite (cardinal_bound s1 s2)\n  | |- context [union ?s1 ?s2] => specialize (cardinal_bound s1 s2); intros;\n                                  remember (union s1 s2); try omega\n  | _ => omega\nend.\n\n  (* write a tactic to do most reasoning  *)\n  Lemma size_bound : forall φ, cardinal (fl_closure φ) <= formula_length φ.\n    induction φ; try union_len. \n    simpl. \n    (*Now we need some condition bounding fl_closure_box α φ...*)\n    enough (H : forall φ, cardinal (fl_closure_box α φ) <= program_length α); try ( specialize (H φ); union_len).\n    (*  *)\n    induction α; intros.\n    - union_len.\n    - specialize (IHα1 φ0); specialize (IHα2 φ0); union_len.\n    - simpl. specialize (IHα1 (Box α2 φ0)). specialize (IHα2 φ0). union_len.\n    - simpl. specialize (IHα (Box (Star α) φ0)). union_len.\n    - simpl. rewrite cardinal_bound. rewrite singleton_size. simpl.\n      (* This is our original  goal...*)\n    Abort.\n\n\n  Lemma size_bound' : (forall φ, cardinal (fl_closure φ) <= formula_length φ) /\\\n                      (forall α φ, cardinal (fl_closure_box α φ) <= program_length α).\n    Proof.\n      apply pdl_formula_program_mutind; intros; try union_len.\n      (*Previously problematic box case*)\n      - specialize (H φ). union_len.\n      - specialize (H φ); specialize (H0 φ); union_len.\n      - specialize (H (Box β φ)). specialize (H0 φ). union_len.\n      - specialize (H (Box (Star α) φ)). union_len.\n    Qed.\n\n  Lemma size_bound : forall φ, cardinal (fl_closure φ) <= formula_length φ.\n    Proof.\n      destruct size_bound'. auto.\n    Qed.\n\nEnd PDL.\n\nSection HiddenMutualInduction.\n  Context (A : Type).\n          \n  Inductive Sexpr :=\n    | SexprList (l : list Sexpr)\n    | Atom (a : A) .\n\n  Fixpoint sum l := \n    match l with\n    | nil => 0\n    | (h :: t)%list => h + sum t end.\n\n  Fixpoint maxl l :=\n    match l with\n    | nil => 0\n    | (h :: t)%list => \n      let m := maxl t in\n      if (m <? h) then h else m end.\n\n  Lemma max_lt_sum : forall l, maxl l <= sum l.\n  Proof.\n    induction l; auto. simpl. destruct (maxl l <? a); try omega.\n  Qed.\n\n  Fixpoint size (s : Sexpr) :=\n    match s with\n    | Atom _ => 1\n    | SexprList l => 1 + sum (List.map size l) end.\n\n  Fixpoint height (s : Sexpr) :=\n    match s with\n    | Atom _ => 1\n    | SexprList l => 1 + maxl (List.map height l) end.\n\n\n  Lemma height_le_size : forall s, height s <= size s.\n    Proof.\n      induction s; auto.\n      induction l; auto. simpl. Fail omega.\n      (*no information about the height or size of the elements of l*)\n    Abort.\n    (*based on Chlipala sort of*)\n  Section sexpr_ind'.\n    Variable (P : Sexpr -> Prop).\n\n    Hypothesis (AtomCase : forall a, P (Atom a)).\n\n    Hypothesis (ListCase : forall l, List.Forall P l -> P (SexprList l)).\n\n    Fail Fixpoint sexpr_ind' (s : Sexpr) : P s :=\n      match s with\n      | Atom a => AtomCase a\n      | SexprList l => ListCase l (list_sexpr_ind l) end\n     with list_sexpr_ind (l : list Sexpr) : List.Forall P l :=\n      match l with\n      | nil => @List.Forall_nil Sexpr P\n      | (h :: t)%list => @List.Forall_cons Sexpr P h t (sexpr_ind' h) (list_sexpr_ind t) end.\n\n    Fixpoint sexpr_ind' (s : Sexpr) : P s :=\n      match s with\n      | Atom a => AtomCase a\n      | SexprList l => ListCase l (\n              (fix list_sexpr_ind (l : list Sexpr) :=\n                   match l with\n                   | nil => @List.Forall_nil Sexpr P\n                   | (h :: t)%list => @List.Forall_cons Sexpr P h t (sexpr_ind' h) (list_sexpr_ind t) end\n                                  ) l) end.\n   End sexpr_ind'.\n\n   Lemma height_le_size : forall s, height s <= size s.\n   Proof.\n     apply sexpr_ind'; auto.\n     intros. induction l; auto. inversion H. subst.\n     simpl. destruct (maxl (List.map height l) <? height a); try omega.\n     specialize (IHl H3). simpl in IHl. omega.\n   Qed.\n \nEnd HiddenMutualInduction.\n", "meta": {"author": "lag47", "repo": "Mutual-Induction-Tutorial", "sha": "9699ce60e503079259fa719c83fe411a74d2e175", "save_path": "github-repos/coq/lag47-Mutual-Induction-Tutorial", "path": "github-repos/coq/lag47-Mutual-Induction-Tutorial/Mutual-Induction-Tutorial-9699ce60e503079259fa719c83fe411a74d2e175/Tutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7453166071510093}}
{"text": "(* Implementation and correctness proof for insertion sort.\n  Andrew W. Appel, January 2010. *)\n\nRequire Import Permutation.\nRequire Import List.\nRequire Import Compare_dec.\n\n\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\nLocate le.\nPrint le.\n\nLocate le_lt_dec.\nCheck le_lt_dec.\n\nPrint le_lt_dec.\nPrint sumbool.\n\nLemma le_lt_dec': forall n m, {n<=m}+{m<n}.\nProof.\ninduction n; destruct m; intros.\nleft. apply le_n.\nleft. apply le_S.\n    induction m. apply le_n. apply le_S. auto.\nright. clear. unfold lt. apply Le.le_n_S.\n   apply Le.le_0_n.\ndestruct (IHn m).\nleft. apply Le.le_n_S. auto.\nright. apply Lt.lt_n_S. auto.\nDefined.\n\nLocate le_lt_dec.\nPrint le_lt_dec'.\nPrint le_lt_dec.\n\nFixpoint select (i: nat) (l: list nat) : nat * list nat :=\nmatch l with\n|  nil => (i, nil)\n|  h::t => if le_lt_dec i h \n               then let (j, l') := select i t in (j, h::l')\n               else let (j,l') := select h t in (j, i::l')\nend.\n\nFixpoint selsort l n :=\nmatch l, n with\n| i::r, S n' => let (j,r') := select i r\n               in j :: selsort r' n'\n| _, _ => nil\nend.\n\nDefinition selection_sort l := selsort l (length l).\n\n\nExample sort_pi: selection_sort [3,1,4,1,5,9,2,6,5,3,5] = [1,1,2,3,3,4,5,5,5,6,9].\nProof.\nunfold selection_sort.\nsimpl.\nreflexivity.\nQed.\n\nLemma select_perm: forall i l, \n  let (j,r) := select i l in\n   Permutation (i::l) (j::r).\nProof.\nintros i l; revert i.\ninduction l; intros; simpl in *.\napply Permutation_refl.\ndestruct (le_lt_dec i a).\nspecialize (IHl i).\ndestruct (select i l).\neapply perm_trans.\napply perm_swap.\napply Permutation_sym.\neapply perm_trans.\napply perm_swap.\napply Permutation_cons.\napply Permutation_sym.\napply IHl.\nspecialize (IHl a).\ndestruct (select a l).\napply Permutation_sym.\neapply perm_trans.\napply perm_swap.\napply Permutation_cons.\napply Permutation_sym.\napply IHl.\nQed.\n\nLtac inv H := inversion H; clear H; subst.\n\nLemma selsort_perm:\n  forall n l, length l = n -> Permutation l (selsort l n).\nProof.\ninduction n; destruct l; intros; inv H.\nsimpl. apply Permutation_refl.\nsimpl.\nassert (SP := select_perm n0 l).\ndestruct (select n0 l) as [j r].\neapply Permutation_trans; [ apply SP | ].\napply Permutation_cons.\napply IHn.\napply Permutation_length in SP.\nsimpl in SP.\ninv SP.\nauto.\nQed.\n\nTheorem selection_sort_perm:\n  forall l, Permutation l (selection_sort l).\nProof.\nunfold selection_sort.\nintro.\napply selsort_perm.\nreflexivity.\nQed.\n\n(* NOTE!  Proving that a sort function is correct has two parts:\n  1.  The output is a permutation of the input\n  2.  The output is in increasing order\n Only part 1 has been proved here.  The specification\n  and proof of part 2 is missing.\n\n*)\n\n", "meta": {"author": "jps8", "repo": "old_cs", "sha": "7afe6cb65b10d8e2418f3bd225283674286fa3a8", "save_path": "github-repos/coq/jps8-old_cs", "path": "github-repos/coq/jps8-old_cs/old_cs-7afe6cb65b10d8e2418f3bd225283674286fa3a8/510/Selection2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.8688267660487573, "lm_q1q2_score": 0.7452518981553347}}
{"text": "(**Some of the theorems are taken from Bertot and Casteran 2004**)\nRequire Import Omega.\n(**Type Checking of the Universes**)\nCheck Prop.\nCheck Set.\nCheck Type.\n\n(** Type Checking with Explicit Universes**)\nSet Printing Universes.\nCheck Prop. \nCheck Set.\nCheck Type.\nCheck forall P:Prop, Prop.\nCheck Prop.\nCheck forall P:Type, Type. \nCheck nat.\nCheck 1.\nCheck plus.\nCheck plus 3.\nCheck plus 3 4.\n\n\n(** Assumptions**)\nParameter H:Set.\nSection H1.\nVariable H1:Set.\nEnd H1.\nHypothesis H2: Set.\n\n(** Definition**)\nDefinition three:nat:= S (S(S((0)))).\nCheck three. \nTheorem three3: 3 = three. cbv.  reflexivity. Qed.\n\nEval compute in  S (S(S((0)))).\nParameter Montague_Grammar: Set. \nDefinition MG:= Montague_Grammar.\n\n(** Functions: simple function types and definitions using lambda abstraction**)\nParameter nat_1: nat->Prop.\nDefinition square:= fun n: nat=> n*n. (** fun is lambda. Note that Coq can infer the type nat->nat here.**)\nDefinition square1: nat->nat:= fun n: nat=> n*n.\nTheorem SQUARE: square = square1.\ncbv. reflexivity. Qed.\n(** Define a function that takes two nat arguments and returns their sum multiplied by the first nat**)\nDefinition sum_times:= fun n m: nat=> (n+m)*n.\nEval compute in sum_times 2 3.\n\n(** Inductive Types withour Recursion**)\nUnset Printing Universes. \nCheck bool. Print bool.\nInductive bool1 : Set := true | false. Print bool1_rect.\nInductive nat1 : Set :=\n| O : nat1\n| S1 : nat1 -> nat1.\nPrint nat1_ind. Print nat1_rect. Print nat1_rec. (**Peano's induction**)\n\n\n\n(** Propositional logic proofs**)\nVariables A B P Q R: Prop. \nTheorem trans: (P->Q)->(Q->R)->(P->R). \n                                         intro. intro. \nintro. \napply H1. apply H0. assumption. Qed.\nDefinition lem:= A \\/ ~ A.\nDefinition Peirce:= ((A->B)->A)->A.\nTheorem lemP: lem -> Peirce.  \n  unfold lem. unfold Peirce. intros.\nelim H0.\nintros. assumption. \nintro. apply H1.\nintro.   absurd A. assumption. assumption. Qed.\n\n\n(**Tactics**)\nTheorem CONJ: A/\\B->A.\nintro.  elim H0. (** applies the elimination rule for conjunction**) intros. assumption. Qed\n. \nTheorem CONJ2: B/\\(A/\\P)->A/\\B.\nintro. \nelim  H0.\nintros. \nelim H3. intros. split. \nassumption. assumption. Qed.\nTheorem DISJ: (B\\/(B\\/P))/\\(A/\\B)->A\\/B.\nintro. \ndestruct H0. destruct H1.  left. (**or right**)  assumption. Qed.\n\n\nTheorem IMPL: forall P: Prop, ( P -> Q) -> R -> P -> Q.\nintros. apply   H0.\nassumption. \nQed.\n\n\nTheorem NAT: exists x: nat, le 0 x.\nexists 1. \nomega.  Qed.\n\n(**Exact and Proof tactic**)\nTheorem D: (P->P->Q)->P->Q.\nexact (**or Proof**) (fun (H:P->P->Q)(p:P)=>H p p).\nQed. \n\n(**Idtac and try**)\nTheorem PQQ: P->Q->P.\nintros.   try elim H0.   try apply H0. Qed.\nVariable T: Prop.\nTheorem PQPR: (P->Q)->(P->R)->(P->Q->R->T)->P->T.  intros H H0 H1 H2.  idtac.  apply H1; [idtac|idtac |idtac]; idtac. assumption.  apply H;[idtac]; assumption. apply H0. assumption. Qed. \n\nTheorem PQPR2: (P->Q)->(P->R)->(P->Q->R->T)->P->T.\nintros H H0 H1 H2. apply H1;[idtac|apply H|apply H0]; assumption. Qed.\n\nTheorem PQPR3: (P->Q)->(P)->P. intros. assert Q. intuition. assumption. Qed.\n(**Assert**)\n\nSection assert.\nHypotheses (H : P -> Q)\n(H0 : Q -> R)\n(H1 : (P -> R) -> T -> Q)\n(H2 : (P -> R) -> T).\nLemma L8 : Q.\nassert (PR : P -> R). intro p; apply H0; apply H; assumption. apply H1; [ assumption | apply H2;assumption]. Qed. (**assert saves some time here, otherwise we would have to prove P->R twice**)\nEnd assert.\n\nSection generalize.\nHypotheses (x:nat)(y:nat).\nLemma GENERALIZE:   0 <= x + y + y.  omega. Qed.\nEnd generalize.\nLemma GENERALIZE2: forall x y  :nat, 0 <=  x + y + y. \nintro. intro. omega. Qed. \n\nSection cut.\nHypotheses (H : P->Q)\n(H0: Q->R)\n(H1 : (P->R)->T->Q)\n(H2 : (P->R)->T).\n\nTheorem cut: Q.\ncut (P->R). intros. apply H1. assumption. apply H2. assumption. intro. apply H0. apply H. assumption. Qed.\nEnd cut.\n", "meta": {"author": "StergiosCha", "repo": "CoqNL", "sha": "cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c", "save_path": "github-repos/coq/StergiosCha-CoqNL", "path": "github-repos/coq/StergiosCha-CoqNL/CoqNL-cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c/Code/Tutorial1_Intro_to_Coq/Oslo_basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.8688267694452331, "lm_q1q2_score": 0.7452518821146986}}
{"text": "Inductive nat: Set :=\n  | O: nat\n  | S: nat -> nat.\n\nFixpoint plus (m n: nat): nat :=\n  match m with\n    | O => n\n    | S p => S (plus p n)\n  end.\n\nInfix \"+\" := plus.\n\nLemma plus_comm:\n  forall m n, m + n = n + m.\nProof.\n\nQed.\n", "meta": {"author": "mbrcknl", "repo": "coq-fight-2017", "sha": "7f5ec82d47b79769d3b92ae7f0d8cb8e45891aba", "save_path": "github-repos/coq/mbrcknl-coq-fight-2017", "path": "github-repos/coq/mbrcknl-coq-fight-2017/coq-fight-2017-7f5ec82d47b79769d3b92ae7f0d8cb8e45891aba/plus-comm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9553191309994467, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7451421445421816}}
{"text": "Module Poly.\nFrom LF Require Export Lists.\nFrom LF Require Export Basics1.\nFrom LF Require Export Induction.\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\nCheck list.\nCheck nil.\nCheck cons.\nCheck (cons nat 3 (nil nat)) : list nat.\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | O => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(* make type param implicit *)\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 : rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\nExample test_rev2: rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n\n(* explicit type arg *)\nCheck @nil : forall X : Type, list X.\n\n\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof. \n  intros X l. \n  induction l as [| h t H ].\n  - reflexivity. \n  - simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A l m n.\n  induction l as [| h t H ].\n  - reflexivity.\n  - simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1 as [| h t H ].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1 as [| h t H ].\n  - simpl.\n    rewrite -> app_nil_r.\n    reflexivity.\n  - simpl.\n    rewrite -> H.\n    rewrite <- app_assoc.\n    reflexivity.\nQed.\n\nTheorem rev_involutive : forall (X : Type) (l : list X),\n  rev (rev l) = l.\nProof.\n  intros X l.\n  induction l as [| h t H ].\n  - reflexivity.\n  - simpl.\n    rewrite -> rev_app_distr.\n    rewrite -> H.\n    simpl.\n    reflexivity.\nQed.\n\n\n\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y}.\n\nNotation \"( x , y )\" := (pair x y).\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y): list (X * Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\nCompute (combine [1;2] [false;false;true;true]).\n\nFixpoint split {X Y : Type} (l : list (X*Y)) : (list X) * (list Y) :=\n  match l with\n  | nil => (nil, nil)\n  | cons (x,y) t =>\n    match split t with\n    | (lx, ly) => (x::lx, y::ly)\n    end\n  end.\n\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n\n\n\n\n\n\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\nArguments Some {X}.\nArguments None {X}.\n\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat): option X :=\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.\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | nil => None\n  | cons h t => Some h\n  end.\n\n\nCheck @hd_error : forall X : Type, list X -> option X.\nCheck hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error [[1];[2]] = Some [1].\nProof. reflexivity. Qed.\n\n\n\n\n\n\n\nDefinition doit3times {X : Type} (f : X -> X) (n : X) : X := f (f (f n)).\n\n\nCheck @doit3times : forall X : Type, (X -> X) -> X -> X.\n\nFixpoint filter {X: Type} (test: X -> bool) (l: list X) : list X :=\n  match l with\n  | []     => []\n  | h :: t =>\n    if test h \n    then h :: (filter test t)\n    else filter test t\n  end.\n\n(*\nDefinition countoddmembers' (l: list nat) : nat := length (filter odd l).\n*)\n\nExample test_anon_fun': doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun i => andb (negb (Induction.leb i 7)) (Induction.even i)) l.\n\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n  (filter (fun i => test i) l, filter (fun i => negb (test i)) l).\n\n\nExample test_partition1: partition (fun i => negb (Induction.even i)) [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\n\nFixpoint map {X Y : Type} (f : X -> Y) (l : list X) : list Y :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n\nLemma map_dist : forall (X Y : Type) (f : X -> Y) (l m : list X),\n  map f (l ++ m) = map f l ++ map f m.\nProof.\n  intros X Y f l m.\n  induction l as [| h t H ].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [| h t H ].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> map_dist.\n    simpl.\n    rewrite -> H.\n    reflexivity.\nQed.\n\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X): list Y :=\n  match l with \n  | nil => nil\n  | cons h t => f h ++ flat_map f t\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X): option Y :=\n  match xo with\n  | None   => None\n  | Some x => Some (f x)\n  end.\n\n\n\n\nFixpoint map' (X Y : Type) (f : X -> Y) (l : list X) : list Y :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map' X Y f t)\n  end.\n\nFixpoint filter' (X: Type) (test: X -> bool) (l: list X) : list X :=\n  match l with\n  | []     => []\n  | h :: t =>\n    if test h \n    then h :: (filter' X test t)\n    else filter test t\n  end.\n\n\n\n\nFixpoint fold {X Y: Type} (f : X -> Y -> Y) (l : list X) (b : Y): Y :=\n  match l with\n  | nil    => b\n  | h :: t => f h (fold f t b)\n  end.\n\nCheck (fold andb) : list bool -> bool -> bool.\nExample fold_example1 : fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\nExample fold_example2 : fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\nExample fold_example3 : fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [| h t H ].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite <- H.\n    reflexivity.\nQed.\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n  fold (fun i a => [f i] ++ a ) l [].\n\nTheorem fold_map_correct : forall X Y (f : X -> Y) (l : list X),\n  fold_map f l = map f l.\nProof.\n  intros X Y f l.\n  induction l as [| h t H ].\n  - reflexivity.\n  - simpl.\n    rewrite <- H.\n    reflexivity.\nQed.\n\n\n\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  match p with\n  | (x, y) => f x y\n  end.\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n\nCheck @prod_curry.\nCheck @prod_uncurry.\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z) x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z f x y.\n  unfold prod_uncurry.\n  unfold prod_curry.\n  reflexivity.\nQed.\n\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  unfold prod_uncurry.\n  unfold prod_curry.\n  simpl.\n  destruct p as [x y].\n  - reflexivity.\nQed.\n\nFixpoint nth_error' {X : Type} (l : list X) (n : nat) : option X :=\n  match l with\n  | []      => None\n  | a :: l' => if n =? O then Some a else nth_error' l' (pred n)\n  end.\n\nLemma len_0_for_empty: forall {X : Type} (l : list X), length l = 0 -> l = nil.\nProof.\n  intros X l.\n  induction l as [| h t H ].\n  - reflexivity.\n  - simpl.\nAdmitted.\n  \n\n\nTheorem tst : forall X l n, length l = n -> @nth_error X l n = None.\nProof.\n  intros X l n H.\nAdmitted.\n\n\n\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\nDefinition one  : cnat := fun (X : Type) (f : X -> X) (x : X) => f x.\nDefinition two  : cnat := fun (X : Type) (f : X -> X) (x : X) => f (f x).\nDefinition zero : cnat := fun (X : Type) (f : X -> X) (x : X) => x.\n\nDefinition three : cnat := @doit3times.\n\n\n\nDefinition succ (n : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\n  \nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\n\nDefinition plus (n m : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => n X f (m X f x).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\n\nDefinition mult (n m : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => n X (m X f) x.\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\nDefinition mult' (X : Type) (n m : (X -> X) -> X -> X) (f : X -> X) (x : X) := n (m f) x.\n\nDefinition exp (n m : cnat) : cnat := \n  fun (X : Type) (f : X -> X) (x : X) => (m _ (mult' X (n X)) (one X)) f x.\n\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\nExample exp_2 : exp three zero = one.\nProof. reflexivity. Qed.\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\nEnd Church.\n\nEnd Poly.\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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.7451036295658261}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n\n(** * Subtyping *)\n\n(** A subtype extends another type by adding\n    a property. The new type has a richer theory.\n    The new type should inherit all the original\n    theory. *)\n\n(* Let's define the type of homogeneous tuples *)\n\n(** ** Standard [sig] type *)\n\nPrint sig.\n(**\n  Inductive sig (A : Type) (P : A -> Prop) : Type :=\n    | exist : forall x:A, P x -> sig P.\n\n  Notation \"{ x : A  |  P }\" :=\n    (sig (A:=A) (fun x => P)) : type_scope.\n*)\n\n(** [sig] type is almost the same as the [ex] type encoding\n    existential quantifier *)\nPrint ex.\n(**\n  Inductive ex (A : Type) (P : A -> Prop) : Prop :=\n    | ex_intro : forall x:A, P x -> ex P.\n *)\n\n(** simple definition relying on the existing [pred] function *)\nDefinition predecessor (x : {n | 0 < n}) : nat :=\n  let: (exist m prf_m_gt_0) := x in\n  m.-1.\n\n(** The _convoy pattern_ : *)\nDefinition pred_dep (x : {n | 0 < n}) : nat :=\n  let: (exist n prf_n_gt_0) := x in\n  match n as n return (0 < n -> nat) with\n  | 0 =>\n      fun prf : 0 < 0 => False_rect _ (notF prf)\n  | n'.+1 =>\n      fun _ => n'\n  end prf_n_gt_0.\n\n(** ** Some issues *)\n\n(** Proof irrelevance *)\n\nLemma eq_sig T (P : T -> Prop) x (px : P x) (px' : P x) :\n  (exist P x px) = (exist P x px').\nProof.\nFail by done.\n(** we are stuck: we need proof irrelevance here *)\nAbort.\n\nAxiom proof_irrelevance :\n  forall (P : Prop) (pf1 pf2 : P), pf1 = pf2.\n\nLemma eq_sig T (P : T -> Prop) x (px : P x) (px' : P x) :\n  (exist P x px) = (exist P x px').\nProof.\nrewrite [px]proof_irrelevance.\ndone.\nQed.\n\n(** Decidable propositions _are_ proof irrelevant *)\n\nCheck eq_irrelevance.\n(**\neq_irrelevance\n     : forall (T : eqType) (x y : T)\n         (e1 e2 : x = y),\n         e1 = e2\n\nThis special case of proof irrelevance is called\n_Unicity of Identity Proofs_ principle (UIP).\n*)\n\n(** [sval] projection is injective for decidable propositions : *)\nLemma eq_n_gt0 (m n : {n | 0 < n}) :\n  sval m = sval n ->\n  m = n.\nProof.\ncase: m=> [m pfm]; case: n=> [n pfn] /=.\nFail move=> ->.  (* because of the dependencies *)\nmove=> eq_mn; move: eq_mn pfm pfn.\nmove=> -> *.\ncongr exist.\nexact: eq_irrelevance.\nQed.\n\n(** We cannot define [sval] (aka [proj1_sig]) as a coercion *)\n\n(**\nThis is because we cannot specify the target\nclass of this tentative coercion:\n  Coercion proj1_sig : sig >-> ???.\n *)\n\n\n(** ** Mathcomp's [subType]\n       (defined in [eqtype] library) *)\n\nPrint subType.\n(**\n  Structure subType (T : Type) (P : pred T) : Type :=\n    SubType {\n      (* new type *)\n      sub_sort : Type;\n\n      (* projection, like proj_sig1 *)\n      val : sub_sort -> T;\n\n      (* constructor *)\n      Sub : forall x : T, P x -> sub_sort;\n\n      (* elimination principle *)\n      _ : forall K : sub_sort -> Type,\n          (forall (x : T) (Px : P x), K (Sub x Px)) ->\n          forall u : sub_sort, K u;\n\n      (* projection is injective *)\n      _ : forall (x : T) (Px : P x),\n          val (Sub x Px) = x\n    }.\n*)\n\n\n(** An example of a [subType] *)\nSection PosSubtype.\n\nInductive pos := Positive m of 0 < m.\n\nCoercion nat_of_pos p :=\n  let: Positive n _ := p in n.\n\nVariables p1 p2 : pos.\n\n(** This is something not possible with\n    {n | 0 < n} type *)\nCheck p1.-1 + p2.\nSet Printing Coercions.\nCheck p1.-1 + p2.\nUnset Printing Coercions.\n\n(** Register [pos] as a [subType] *)\nCanonical pos_subType :=\n  [subType for nat_of_pos].\n\n(** Given that propositions are expressed as\n    booleans, we can use the fact that proofs of\n    these properties are irrelevant. *)\n\n(** Hence we can build subtypes and prove that\n    the projection to the supertype is injective,\n    which lets us inherit all of the theory of\n    the supertype. *)\n\n(** E.g. we can make [pos] inherit [eqType]\n    from [nat] type with a bit of boilerplate *)\n\nDefinition pos_eqMixin :=\n  Eval hnf in [eqMixin of pos by <:].\n\nCanonical pos_eqType :=\n  Eval hnf in EqType pos pos_eqMixin.\n\nCheck p1 == p2.\n\nEnd PosSubtype.\n\n\n(** * Some standard [subType]s *)\n\n(** ** [ordinal]: type of finite ordinals *)\n\n(**\n[ordinal n] = {0, 1, ... , n-1}\n\nInductive ordinal : predArgType :=\n  | Ordinal m of m < n.\n\nNotation \"''I_' n\" := (ordinal n)\n\n *)\n\nFrom mathcomp Require Import fintype.\n\nDefinition i1 : 'I_2 :=\n  Ordinal (erefl : 0 < 2).\n\nDefinition i2 : 'I_2 :=\n  Ordinal (erefl : 1 < 2).\n\nCompute i1 == i2.\n\n(** Note: [ordinal] is also a [finType] *)\n\n\n(** ** [tuple] type *)\n\nFrom mathcomp Require Import tuple.\n\nDefinition t : 3.-tuple nat :=\n  [tuple 5; 6; 7].\n\n(** It's not possible to take an out-of-bounds\n    element of a tuple, so there is no need\n    of a default element as for [nth] on [seq]s *)\nAbout tnth.\n\nCompute [tnth t 0].\nCompute [tnth t 1].\nCompute [tnth t 2].\nFail Compute [tnth t 3].\n\nAbout thead.\n(**\nthead :\n  forall (n : nat) (T : Type),\n    (n.+1).-tuple T -> T\n*)\n\nCompute thead t.  (** = 5 *)\n(** [thead] of empty tuple\n    does not even typecheck *)\nFail Check thead [tuple].\n\n(**\n  Structure tuple_of (n : nat) (T : Type) : Type :=\n    Tuple {\n    (* [:>] means \"is a coercion\" *)\n      tval :> seq T;\n      _ : size tval == n;\n    }.\n*)\n\nSection TupleExample.\nVariables (m n : nat) (T : Type).\nVariable t1 : m.-tuple T.\nVariable t2 : n.-tuple T.\n\nCheck [tuple of t1 ++ t2] : (m + n).-tuple T.\nFail Check [tuple of t1 ++ t2] : (n + m).-tuple T.\nEnd TupleExample.\n\n\nExample seq_on_tuple (n : nat) (t : n .-tuple nat) :\n  size (rev [seq 2 * x | x <- rev t]) = size t.\nProof.\n\nSet Printing Coercions.\nby rewrite map_rev revK size_map.\nUnset Printing Coercions.\n\nRestart.\n\nrewrite size_tuple.  (** this should work *)\nCheck size_tuple.\n(**\n  size_tuple : forall (n : nat) (T : Type)\n               (t : n.-tuple T), size t = n\n*)\n\n(** Why does this not fail? *)\n(** rev [seq 2 * x | x <- rev t] is a list,\n    not a tuple *)\nrewrite size_tuple.\nAbort.\n\nPrint Canonical Projections.\n(**\n  ...\n  map <- tval ( map_tuple )\n  ...\n  rev <- tval ( rev_tuple )\n  ...\n*)\n\n(**\nThis works because Coq is instrumented\nto automatically promote sequences to tuples\nusing the mechanism of Canonical Structures.\n\nLemma rev_tupleP n A (t : n .-tuple A) :\n  size (rev t) == n.\nProof. by rewrite size_rev size_tuple. Qed.\n\nCanonical rev_tuple n A (t : n .-tuple A) :=\n  Tuple (rev_tupleP t).\n\nLemma map_tupleP n A B (f:A -> B) (t: n.-tuple A) :\n   size (map f t) == n.\nProof. by rewrite size_map size_tuple. Qed.\n\nCanonical\n  map_tuple n A B (f:A -> B) (t: n.-tuple A) :=\n    Tuple (map_tupleP f t).\n *)\n\n(** Exercise: show in detail how\n    [rewrite size_tuple] from above works *)\n\n\n\n(**\nSince tuples are a subtype of lists, we\ncan reuse the theory of lists over equality types.\n*)\n\nExample test_eqtype (x y : 3.-tuple nat) :\n  x == y -> True.\nProof.\nmove=> /eqP.\nAbort.\n\n\n\n(** * Finite types *)\n\nFrom mathcomp Require Import choice fintype finfun.\n\n(**\nFig. 3 of \"Packaging Mathematical Structures\"\nby F. Garillot, G. Gonthier, A. Mahboubi,\nL. Rideau(2009)\n*)\n\n\n\n(** A [finType] structure is composed of\n    a list of elements of an [eqType] structure,\n    each element of the type being uniquely\n    represented in the list:\n\n(* simplified definition of [finType] *)\n  Structure finType : Type :=\n    FinType {\n        sort :> countType;\n        enum : seq sort;\n        enumP : forall x,\n                  count (pred1 x) enum = 1;\n    }.\n*)\n\n(**\nFinite sets are then sets taken in a [finType]\ndomain. In the library, the basic operations\nare provided.\nFor example, given [A] a finite set,\n[card A] (or #|A|) represents the cardinality\nof A. All these operations come with their\nbasic properties. For example, we have:\n\n  Lemma cardUI : ∀ (d: finType) (A B: {pred T}),\n    #|A ∪ B| + #|A ∩ B| = #|A| + #|B|.\n\n  Lemma card_image :\n    ∀ (T T': finType) (f : T -> T')\n      injective f -> forall A : {pred T},\n      #|image f A| = #|A|.\n*)\n\n\n\n(** ** How [finType] is actually organized *)\n\nPrint Finite.type.\n(**\n  Structure type : Type :=\n    Pack {\n      sort : Type;\n      _ : Finite.class_of sort\n    }.\n*)\n\n(** [finType] extends [choiceType] with a mixin *)\nPrint Finite.class_of.\n(**\n  Structure class_of (T : Type) : Type :=\n    Class {\n      base : Choice.class_of T;\n      mixin : Finite.mixin_of (EqType T base)\n    }\n*)\n\nPrint Finite.mixin_of.\n(** we mix in countable and two specific fields:\n    an enumeration and an axiom\n\n  Structure mixin_of (T : eqType) : Type :=\n    Mixin {\n      mixin_base : Countable.mixin_of T;\n      mixin_enum : seq T;\n      _ : Finite.axiom mixin_enum\n    }.\n*)\n\nPrint Finite.axiom.\n(**\n  Finite.axiom =\n    fun (T : eqType) (e : seq T) =>\n      forall x : T, count_mem x e = 1\n\nwhere\n  Notation count_mem x := (count (pred1 x)).\n*)\n\nEval cbv in count_mem 5 [:: 1; 5; 2; 5; 3; 5; 4].\n\n\nSection FinTypeExample.\n\nVariable T : finType.\n\n(** Cardinality of a finite type *)\nCheck #| T |.\n\n(** \"bounded\" quantification *)\nCheck [forall x : T, x == x] && false.\nFail Check (forall x : T, x == x) && false.\n\n(** We recover classical reasoning for\n    the bounded quantifiers: *)\nCheck negb_forall:\n  forall (T : finType) (P : pred T),\n    ~~ [forall x, P x] = [exists x, ~~ P x].\n\nCheck negb_exists:\n  forall (T : finType) (P : pred T),\n    ~~ [exists x, P x] = [forall x, ~~ P x].\n\n(** [negb_forall] does not hold\n    in intuitionistic setting *)\n\nEnd FinTypeExample.\n\n\n\n(** * Examples of interfaces *)\n\nFrom mathcomp Require Import finset.\n\nSection Interfaces.\n\nVariable chT : choiceType.\n\nCheck (@sigW chT).\n\nCheck [eqType of chT].\n\nVariable coT : countType.\n\nCheck [countType of nat].\nCheck [choiceType of coT].\nCheck [choiceType of nat * nat].\nCheck [choiceType of seq coT].\n\nVariable fT : finType.\n\nCheck [finType of bool].\nCheck [finType of 'I_10].\nCheck [finType of {ffun 'I_10 -> fT}].\nCheck [finType of bool * bool].\nCheck [finType of 3.-tuple bool].\nFail Check [finType of 3.-tuple nat].\n\nCheck {set 'I_4} : Type.\nCheck forall a : {set 'I_4},\n        (a == set0) || (1 < #|a| < 4).\nPrint set_type.\nCheck {ffun 'I_4 -> bool} : Type.\nPrint finfun_eqType.\nCheck [eqType of #| 'I_4 |.-tuple bool].\nCheck [finType of #| 'I_4 |.-tuple bool].\n\nCheck {ffun 'I_4 * 'I_6 -> nat} : Type.\nCheck [eqType of {ffun 'I_4 * 'I_6 -> nat}] : Type.\n\nEnd Interfaces.\n\n\n\n(** * Bonus *)\n\n(* The following requires\n   the coq-mathcomp-algebra package\n   from opam package manager *)\nFrom mathcomp Require Import all_algebra.\nOpen Scope ring_scope.\n\nPrint matrix.\n\nSection Rings.\n\nVariable R : ringType.\n\nCheck forall x : R, x * 1 == x.\n\n(** Matrices of size 4x4 over an arbitrary ring [R] *)\nCheck forall m : 'M[R]_(4,4), m == m * m.\n\nEnd Rings.\n\n\n\n", "meta": {"author": "anton-trunov", "repo": "coq-lecture-notes", "sha": "e012addae82da6d8d03f6e789e43f35140dcdfea", "save_path": "github-repos/coq/anton-trunov-coq-lecture-notes", "path": "github-repos/coq/anton-trunov-coq-lecture-notes/coq-lecture-notes-e012addae82da6d8d03f6e789e43f35140dcdfea/code/lecture08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.8705972616934406, "lm_q1q2_score": 0.7451016553640816}}
{"text": "Section ExProp.\n\nVariable A B C D P Q R S:Prop.\n\nGoal (P -> Q) -> (Q -> R) -> P -> R.\nProof.\nintros pq qr p.\napply qr. apply pq. exact p.\nQed.\n\nGoal ~False.\nProof.\nintro H. exact H.\nQed.\n\nGoal P -> ~~P.\nProof.\nintro p. intro np. elim np. exact p.\nQed.\n\nGoal (P -> Q) -> ~Q -> ~P.\nProof.\nintros pq nq. intro p.\nelim nq. apply pq. exact p.\nQed.\n\nGoal P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\nintro pqr. destruct pqr as [p [q r]].\nsplit.\n split.\n  exact p.\n  exact q.\n exact r.\nQed.\n\nGoal P /\\ (Q \\/ R) -> (P /\\ Q) \\/ (P /\\ R).\nProof.\nintro pqr.\ndestruct pqr as [p [q|r]].\n left. split.\n  exact p.\n  exact q.\n right. split.\n  exact p.\n  exact r.\nQed.\n\nGoal P -> ~P -> Q.\nProof.\nintros p np. elim np. exact p.\nQed.\n\nGoal (A \\/ B -> C) -> (A -> C)/\\(B -> C).\nProof.\nintro abc.\nsplit.\n intro a. apply abc. left. exact a.\n intro b. apply abc. right. exact b.\nQed.\n\nGoal (A \\/ B -> C) -> (A -> C) \\/ (B -> C).\nProof.\nintro abc.\n left. intro a. apply abc. left. exact a.\nQed.\n\nGoal (A -> (B -> C)) /\\ (A -> B) -> (A -> C).\nProof.\nintros H a. destruct H as [abc ab].\napply abc.\n exact a.\n apply ab. exact a.\nQed.\n\nGoal (~A /\\ ~B) -> ~(A \\/ (~A /\\ B)).\nProof.\nintro nanb. intro anab.\ndestruct nanb as [na nb].\ndestruct anab as [a|[na' b]].\n elim na. exact a.\n elim nb. exact b.\nQed.\n\nGoal (A -> ~A) -> ~A.\nProof.\nintro ana. intro a. elim ana.\n exact a.\n exact a.\nQed.\n\nGoal (~(A /\\ A) -> (~A \\/ ~A)).\nProof.\nintro naa. left. intro a. elim naa.\nsplit.\n exact a.\n exact a.\nQed.\n\nGoal (A -> B) -> (A -> ~B) -> A -> C.\nProof.\nintros ab anb a. elim anb.\n exact a.\n apply ab. exact a.\nQed.\n\nEnd ExProp.", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/tutorial20120209/tutorial3_2_ans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7450934508002013}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n(* Chapter 2. Some Quick Examples *)\n(* 2.1 Arithmetic Expressions Over Natural Numbers *)\nInductive binop : Set :=\n| Plus  : binop\n| Times : binop.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp.\n\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n  match b with\n  | Plus => plus\n  | Times => mult\n  end.\n\nFixpoint expDenote (e : exp) : nat :=\n  match e with\n  | Const n => n\n  | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n  end.\n\nEval simpl in expDenote (Const 42).\nEval simpl in expDenote (Binop Plus (Const 2) (Const 2)).\nEval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n\nInductive instr : Set :=\n| iConst : nat -> instr\n| iBinop : binop -> instr.\nDefinition prog := list instr.\nDefinition stack := list nat.\n\nDefinition instrDenote (i : instr) (s : stack) : option stack :=\n  match i with\n  | iConst n => Some (n :: s)\n  | iBinop b =>\n      match s with\n      | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')\n      | _ => None\n      end\n  end.\n\nFixpoint progDenote (p : prog) (s : stack) : option stack :=\n  match p with\n  | nil => Some s\n  | i :: p' =>\n      match instrDenote i s with\n      | None => None\n      | Some s' => progDenote p' s'\n      end\n  end.\n\nFixpoint compile (e : exp) : prog :=\n  match e with\n  | Const n => iConst n :: nil\n  | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil\n  end.\n\nEval simpl in compile (Const 42).\nEval simpl in compile (Binop Plus (Const 2) (Const 2)).\nEval simpl in compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\nEval simpl in progDenote (compile (Const 42)) nil.\nEval simpl in progDenote (compile (Binop Plus (Const 2) (Const 2))) nil.\nEval simpl in progDenote (compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7))).\n\nTheorem compile_correct : forall e,\n  progDenote (compile e) nil = Some (expDenote e :: nil).\nAbort.\n\nLemma compile_correct' : forall e p s,\n  progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\nProof.\n  induction e.\n  - intros. unfold compile. unfold expDenote. unfold progDenote at 1. simpl.\n    fold progDenote. reflexivity.\n  - intros.\n    unfold compile. fold compile. unfold expDenote. fold expDenote.\n    rewrite app_assoc_reverse. rewrite IHe2.\n    rewrite app_assoc_reverse. rewrite IHe1.\n    simpl. reflexivity.\nAbort.\n\nLemma compile_correct' : forall e p s,\n  progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\nProof.\n  induction e; crush.\nQed.\n\nTheorem compile_correct : forall e,\n  progDenote (compile e) nil = Some (expDenote e :: nil).\nProof.\n  intros. rewrite (app_nil_end (compile e)).\n  rewrite compile_correct'. reflexivity.\nQed.\n\n(* 2.2 Typed Expressions *)\nInductive type : Set :=\n| Nat : type\n| Bool : type.\n\nInductive tbinop : type -> type -> type -> Set :=\n| TPlus : tbinop Nat Nat Nat\n| TTimes : tbinop Nat Nat Nat\n| TEq : forall t, tbinop t t Bool\n| TLt : tbinop Nat Nat Bool.\nCheck tbinop_ind.\n\nInductive texp : type -> Set :=\n| TNConst : nat -> texp Nat\n| TBConst : bool -> texp Bool\n| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\nDefinition typeDenote (t : type) : Set :=\n  match t with\n  | Nat => nat\n  | Bool => bool\n  end.\n\nDefinition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b with\n  | TPlus => plus\n  | TTimes => mult\n  | TEq Nat => beq_nat\n  | TEq Bool => eqb\n  | TLt => leb\n  end.\n\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n  | TNConst n => n\n  | TBConst b => b\n  | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nCheck (TBinop).\n\nEval simpl in texpDenote (TNConst 42).\nEval simpl in texpDenote (TBConst true).\nEval simpl in texpDenote\n  (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\nEval simpl in texpDenote\n  (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\nEval simpl in texpDenote\n  (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\n\nDefinition tstack := list type.\n\n(* what initial stack type it expects and what final stack type it will produce *)\nInductive tinstr : tstack -> tstack -> Set :=\n| TiNConst : forall s, nat -> tinstr s (Nat :: s)\n| TiBConst : forall s, bool -> tinstr s (Bool :: s)\n| TiBinop : forall arg1 arg2 res s,\n    tbinop arg1 arg2 res -> tinstr (arg1 :: arg2 :: s) (res :: s).\n\nInductive tprog : tstack -> tstack -> Set :=\n| TNil : forall s, tprog s s\n| TCons : forall s1 s2 s3,\n    tinstr s1 s2 -> tprog s2 s3 -> tprog s1 s3.\n\n(* representation for stacks at runtime *)\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n  | nil => unit\n  | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n  | TiNConst _ n => fun s => (n, s)\n  | TiBConst _ b => fun s => (b, s)\n  | TiBinop _ _ _ _ b => fun s =>\n      let '(arg1, (arg2, s')) := s in\n      ((tbinopDenote b) arg1 arg2, s')\n  end.\n\nFixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n  | TNil _ => fun s => s\n  | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\nFixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n  | TNil _ => fun p' => p'\n  | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=\n  match e with\n  | TNConst n => TCons (TiNConst _ n) (TNil _)\n  | TBConst b => TCons (TiBConst _ b) (TNil _)\n  | TBinop _ _ _ b e1 e2 =>\n      tconcat (tcompile e2 _)\n      (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\nEval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.\nEval simpl in tprogDenote (tcompile (TBConst true) nil) tt.\nEval simpl in tprogDenote\n  (tcompile\n  (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7))\n  nil)\n  tt.\nEval simpl in tprogDenote\n  (tcompile\n  (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7))\n  nil)\n  tt.\nEval simpl in tprogDenote\n  (tcompile\n  (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7))\n  nil)\n  tt.\n\nTheorem tcompile_correct : forall t (e : texp t),\n  tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\nAbort.\n\nLemma tconcat_correct :\n  forall ts ts' ts''\n  (p : tprog ts ts') (p' : tprog ts' ts'') (s : vstack ts),\n  tprogDenote (tconcat p p') s = tprogDenote p' (tprogDenote p s).\nProof.\n  induction p; crush.\nQed.\n\nHint Rewrite tconcat_correct.\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n  tprogDenote (tcompile e ts) s = (texpDenote e, s).\nProof.\n  induction e; crush.\nQed.\n\nTheorem tcompile_correct : forall t (e : texp t),\n  tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\nProof.\n  intros. apply tcompile_correct'.\nQed.\n", "meta": {"author": "momohatt", "repo": "cpdt", "sha": "58ab808fbd6374b230f4123e3fa6c08fe9e93664", "save_path": "github-repos/coq/momohatt-cpdt", "path": "github-repos/coq/momohatt-cpdt/cpdt-58ab808fbd6374b230f4123e3fa6c08fe9e93664/textbook/StackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115783, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7450934376366343}}
{"text": "(* My first Coq theorem. *)\n\nDefinition pierce := forall (p q : Prop), ((p -> q) -> p) -> p.\n\nDefinition lem := forall (p : Prop), p \\/ ~ p.\n\nTheorem pierce_equiv_lem : pierce <-> lem.\n  unfold pierce, lem.\n  firstorder.\n  apply H with (q := ~(p \\/ ~p)).\n  tauto.\n  destruct (H p).\n  assumption.\n  tauto.\nQed.\n", "meta": {"author": "japiirainen", "repo": "coq_pg", "sha": "316161bd9656a270d4ef99d660531048323d6baa", "save_path": "github-repos/coq/japiirainen-coq_pg", "path": "github-repos/coq/japiirainen-coq_pg/coq_pg-316161bd9656a270d4ef99d660531048323d6baa/pierce_lem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7450521364953179}}
{"text": "Require Import Arith.\nImport Nat.\n\nDefinition EM := forall A : Prop, A \\/ ~ A.\n\nDefinition LPO := forall (f : nat -> bool),\n  (forall n : nat, f n = false) \\/ (exists n : nat, f n = true).\n\nDefinition LLPO := forall (f : nat -> bool),\n  (forall n m : nat, n <> m -> f n = false \\/ f m = false) ->\n    (forall n : nat, even n = true  -> f n = false) \\/\n    (forall n : nat, even n = false -> f n = false).\n\nTheorem EM_impl_LPO : EM -> LPO.\nProof. unfold EM. unfold LPO.\n  intros. destruct H with (exists n : nat, f n = true).\n  right. auto.\n  left. intros. destruct H with (f n = false).\n  auto. destruct H0. exists n. destruct (f n). auto. \n  exfalso. apply H1. auto.\nQed.\n\nTheorem LPO_impl_LLPO : LPO -> LLPO.\nProof.\n  unfold LPO. unfold LLPO.\n  intros. specialize (H f).\n  destruct H. left. auto.\n  destruct H. \n  assert (Hev: even x = false \\/ even x = true). { destruct (even x); eauto. }\n  destruct Hev. left. intros. destruct (Nat.eq_dec x n) eqn:Heq.\n  - subst. rewrite H2 in H1. inversion H1.\n  - clear Heq. apply H0 in n0. destruct n0. rewrite H3 in H. inversion H. auto.\n  - right. intros. destruct (Nat.eq_dec x n) eqn:Heq.\n    + subst. rewrite H2 in H1. inversion H1.\n    + clear Heq. apply H0 in n0. destruct n0. rewrite H3 in H. inversion H. auto.\nQed.", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/EM_LPO_LLPO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7450521320141997}}
{"text": "(*\n * Some basic functions and definitions\n *)\n\n(* Booleans *)\n\n(* True if all arguments are true *)\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1, b2, b3 with\n    | true, true, true => true\n    | _, _, _ => false\n  end.\n\n(* Natural Numbers *)\n\n(* True if n is equal to m *)\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\n(* True if n is less than or equal to m *)\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\n(* True if n is less than m *)\nDefinition blt_nat (n m : nat) : bool :=\n  match ble_nat n m with\n    | false => false\n    | true => negb (ble_nat m n)\n  end.\n\n(*\n * Lists, their notations and some useful functions on them\n *)\n\nRequire Import List.\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\n(* Determines if all elements of the list satisfy the predicate *)\nFixpoint all {A:Type} (f:A -> bool) (l:list A) : bool :=\n  match l with\n    | [] => true\n    | x :: xs => if f x then all f xs else false\n  end.\n\n(* Determines if any element of the list satisfies the predicate *)\nFixpoint any {A:Type} (f:A -> bool) (l:list A) : bool :=\n  match l with\n    | [] => false\n    | x :: xs => if f x then true else any f xs\n  end.\n\n(* Splits a list before the first element that fulfills the test  *)\nFixpoint break {A:Type} (f: A -> bool) (l:list A) : (list A * list A) :=\n  match l with\n    | nil => (nil, nil)\n    | x::xs => if f x then (nil, l) \n               else let (a, b) := (break f xs) in (x::a, b)\n  end.\n\n(* Combines two lists by prepending the elements of one list\n   to each sublist of the other list *)\nFixpoint combine_prepend {A:Type} (l:list A) (l':list (list A)) : list (list A) :=\n  match l, l' with\n    | x::xs, y::ys => (x :: y) :: (combine_prepend xs ys)\n    | _, _ => nil\n  end.\n\n(* As per http://coq.inria.fr/V8.1/stdlib/Coq.Lists.List.html *)\nFixpoint filter {A:Type} (f:A -> bool) (l:list A) : list A := \n  match l with \n    | nil => nil\n    | x :: l => if f x then x::(filter f l) else filter f l\n  end.\n\n(* Groups a list into chunks of size n *)\nFixpoint group_by {A:Type} (n:nat) (l:list A) : list (list A) :=\n  match l with\n    | [] => []\n    | x :: xs => match group_by n xs with\n      | [] => [[x]]\n      | y :: ys =>\n        if beq_nat (length y) n then [x] :: (y :: ys)\n        else (x :: y) :: ys\n    end\n  end.\n\n(* Returns the length of the list *)\nFixpoint list_size {A:Type} (l:list A) : nat :=\n  match l with\n    | nil => 0\n    | x::xs => S (list_size xs)\n  end.\n\n(* Returns the minimum of the list and 0 for the empty list *)\nFixpoint minimum (l:list nat) : nat :=\n  match l with\n    | [] => 0\n    | [x] => x\n    | x::xs => let m := minimum xs in if blt_nat m x then m else x\n  end.\n\n(* Test whether a list is empty *)\nDefinition null {A:Type} (l:list A) : bool :=\n  match l with\n    | [] => true\n    | _ => false\n  end.\n\n(* True if the list only contains one element *)\nDefinition single {A:Type} (l:list A) : bool :=\n  match l with\n    | [x] => true\n    | _ => false\n  end.\n\n(* Merges a list of lists into a single list *)\nFixpoint ungroup {A:Type} (l:list (list A)) : list A :=\n  match l with\n    | [] => []\n    | xs :: xss => xs ++ ungroup xss\n  end.\n\n(* Cartesian product of a list of lists *)\nFixpoint cp {A:Type} (l:list (list A)) : list (list A) :=\n  match l with\n    | [] => [[]]\n    | xs :: xss => ungroup (map (fun x => map (fun ys => x :: ys) (cp xss)) xs)\n  end.\n\n(* Matrix cartesian product *)\nDefinition mcp {A:Type} (l: list (list (list A))) : list (list (list A)) :=\n  cp (map cp l).", "meta": {"author": "robert-schmidtke", "repo": "dtp", "sha": "195eafa797fde351984b869bf2dc70f604b6b3ea", "save_path": "github-repos/coq/robert-schmidtke-dtp", "path": "github-repos/coq/robert-schmidtke-dtp/dtp-195eafa797fde351984b869bf2dc70f604b6b3ea/src/Misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7450158271598449}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus lf1 (mult y lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj304_coqofml_vABL9R.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7449748026071467}}
{"text": "\nRequire Export Iron.Data.List.Base.\nRequire Export Iron.Tactics.\n\n\nFixpoint max_list (xs : list nat) :=\n match xs with\n |  nil     => 0\n |  x :: xs => max x (max_list xs)\n end.\n\n\nLemma max_ge_left1\n : forall a b\n , max a b >= a.\nProof.\n intros. gen b.\n induction a; intros.\n  omega.\n  simpl. break b.\n   omega.\n   cut (max a X >= a). \n    intros. omega.\n   eauto.\nQed.\nHint Resolve max_ge_left1.\n\n\nLemma max_ge_right1\n : forall a b\n , max a b >= b.\nProof.\n intros. gen b. \n induction a; intros.\n  simpl. auto.\n  simpl. destruct b.\n   omega.\n   spec IHa b. omega.\nQed.\nHint Resolve max_ge_right1.\n\n\nLemma max_ge_left\n : forall a b c\n , c >= max a b -> c >= a.\nProof.\n intros. gen b c.\n induction a; intros.\n  simpl in *. omega.\n   simpl in *. break b.\n   subst. auto.\n   destruct c.\n    nope.\n    have (c >= max a X) by omega.\n    lets D: IHa H0. omega.\nQed.\nHint Resolve max_ge_left.\n\n\nLemma max_ge_right\n : forall a b c\n , c >= max a b -> c >= b.\nProof.\n intros. gen b c.\n induction a; intros.\n  simpl in *. subst. auto.\n  simpl in *. destruct b.\n   omega.\n   destruct c.\n    nope.\n    have (c >= max a b) by omega.\n    lets D: IHa H0. omega.\nQed.\nHint Resolve max_ge_right.\n\n\nLemma max_ge_above_left\n :  forall a b c\n ,  a >= b\n -> max a c >= b.\nProof.\n intros. gen c b.\n induction a; intros. \n  simpl. omega.\n  simpl. destruct c.\n   omega.\n   destruct b.\n    omega.   \n    cut (max a c >= b). \n     intros. omega.\n     eapply IHa. omega.\nQed. \nHint Resolve max_ge_above_left.\n\n\nLemma max_ge_above_right\n :  forall a b c\n ,  a >= b\n -> max c a >= b.\nProof.\n intros. gen a b.\n induction c; intros. \n  simpl. auto.\n  simpl. break a.\n   omega.\n   subst.\n   destruct b.   \n    omega.   \n    have (X >= b) by omega.\n    spec IHc H0. omega.\nQed. \nHint Resolve max_ge_above_right.\n\n\nLemma max_weaken_left\n :  forall a b c\n ,        a >= b\n -> max c a >= b.\nProof.\n intros. gen a b.\n induction c; intros.\n  simpl. auto.\n  simpl. destruct a.\n   omega.\n   destruct b.\n    omega.\n    cut (max c a >= b). intros. omega.\n     eapply IHc. omega.\nQed.\nHint Resolve max_weaken_left.\n\n\n(********************************************************************)\n(* Lemmas: max_list *)\n\nLemma max_list_above\n :  forall xs\n ,  Forall (fun x => max_list xs >= x) xs.\nProof.\n intros.\n induction xs; unfold not; intros.\n  - simpl. auto.\n  - eapply Forall_cons.\n    + simpl. eauto.\n\n    + eapply Forall_impl\n       with (P := (fun x => max_list xs >= x)); eauto.\n      intros.\n      simpl.\n      remember (max_list xs) as mx.\n      eapply max_weaken_left. auto.\nQed.\nHint Resolve max_list_above.\n\n\nLemma max_list_succ_not_in\n :  forall xs\n ,  not (In (S (max_list xs)) xs).\nProof.\n intros.\n unfold not. intros.\n lets D1: max_list_above xs.\n  rewrite Forall_forall in D1.\n spec D1 H. omega.\nQed.\nHint Resolve max_list_succ_not_in.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Data/List/Max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7449697626151968}}
{"text": "Require Import Bool.\nDefinition bool_not (b:bool) : bool := if b then false else true.\n\n\nDefinition bool_xor (b b':bool) : bool := if b then bool_not b' else b'.\n\nDefinition bool_and (b b':bool) : bool := if b then b' else false.\n\nDefinition bool_or (b b':bool) := if b then true else b'.\n\n\nDefinition bool_eq (b b':bool) := if b then b' else bool_not b'.\n             \n\nTheorem bool_xor_not_eq :\n forall b1 b2:bool, bool_xor b1 b2 = bool_not (bool_eq b1 b2).\nProof.\n  destruct b1, b2; reflexivity.\nQed.\n\nTheorem bool_not_and :\n forall b1 b2:bool,\n   bool_not (bool_and b1 b2) = bool_or (bool_not b1) (bool_not b2).\nProof.\n destruct b1, b2; reflexivity.\nQed.\n\nTheorem bool_not_not : forall b:bool, bool_not (bool_not b) = b.\nProof.\n now destruct b.\nQed.\n\nTheorem bool_ex_middle : forall b:bool, bool_or b (bool_not b) = true.\nProof.\n now destruct b.\nQed.\n\nTheorem bool_eq_reflect : forall b1 b2:bool, bool_eq b1 b2 = true -> b1 = b2.\nProof.\n  destruct  b1, b2; (reflexivity || discriminate).\nQed.\n\nTheorem bool_eq_reflect2 : forall b1 b2:bool, b1 = b2 -> bool_eq b1 b2 = true.\nProof.\n destruct b1, b2; trivial; discriminate.\nQed.\n\nTheorem bool_not_or :\n forall b1 b2:bool,\n   bool_not (bool_or b1 b2) = bool_and (bool_not b1) (bool_not b2).\nProof.\n   now destruct b1, b2.\nQed.\n\n\nTheorem bool_or_and_distr :\n forall b1 b2 b3:bool,\n   bool_or (bool_and b1 b3) (bool_and b2 b3) = bool_and (bool_or b1 b2) b3.\nProof.\n now destruct b1, b2, b3.  \nQed.\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/ch6_inductive_data/SRC/exobool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7449697604978431}}
{"text": "Require Export Elementary_Logic.\n\n(* THE CLASSIFICATION AXIOM SCHEME *)\n\nModule Classification.\n\n(* Class: the universe of discourse consists of classes. *)\n\nParameter Class : Type.\n\n\n(* ∈: is read 'is a member of' or 'belongs to.' *)\n\nParameter In : Class -> Class -> Prop.\n\nNotation \"x ∈ y\" := (In x y) (at level 10).\n\n\n(* I Axiom of extent  For each x and each y it is true that x=y if and only if\n   for each z, z∈x when and only when z∈y. *)\n\nAxiom Axiom_Extent : forall (x y: Class),\n  x = y <-> (forall z: Class, z∈x <-> z∈y).\n\nHint Resolve Axiom_Extent : set.\n\n\n(* 1 Definition  x is a set iff for some y, x∈y. *)\n\nDefinition Ensemble (x: Class) : Prop := exists y: Class, x∈y.\n\nLtac Ens := unfold Ensemble; eauto.\n\nLtac AssE x := assert (Ensemble x); Ens.\n\nHint Unfold Ensemble : set.\n\n\n(* {...:...} : the classifier. *)\n\nParameter Classifier : forall P: Class -> Prop, Class.\n\nNotation \"\\{ P \\}\" := (Classifier P) (at level 0).\n\n\n(* II Classification axiom-scheme  An axiom results if in the following 'a' and\n   'b' are replaced by variables, 'A' by a formula P and 'B' by the formula\n   obtained from P by replacing each occurrence of the variable which replaced\n   a by the variable which replaced b:\n   For each b, b ∈ { a : A } if and only if b is a set and B. *)\n\nAxiom Axiom_Scheme : forall (b: Class) (P: Class -> Prop),\n  b ∈ \\{ P \\} <-> Ensemble b /\\ (P b).\n\nHint Resolve Axiom_Scheme : set.\n\n\nEnd Classification.\n\nExport Classification.\n\n", "meta": {"author": "styzystyzy", "repo": "Axiomatic_Set_Theory", "sha": "2e5f5daa427bd9d6045c4a210c920680b6904f2f", "save_path": "github-repos/coq/styzystyzy-Axiomatic_Set_Theory", "path": "github-repos/coq/styzystyzy-Axiomatic_Set_Theory/Axiomatic_Set_Theory-2e5f5daa427bd9d6045c4a210c920680b6904f2f/theories/Classification_Axiom_Scheme.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7449697586460006}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith ZArith Lia List.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list gcd prime php utils_nat.\n\nFrom Undecidability.H10.ArithLibs \n  Require Import Zp.\n\nSet Implicit Arguments.\n\nSection utils.\n\n  Fact prime_2_or_odd p : prime p -> p = 2 \\/ exists n, 0 < n /\\ p = 2*n+1.\n  Proof.\n    intros Hp.\n    assert (H1 : p <> 0).\n    { generalize (prime_ge_2 Hp); lia. }\n    assert (H3 : 2 <> 0) by discriminate.\n    destruct (eq_nat_dec p 2) as [ | H2 ]; auto; right.\n    assert (rem p 2 = 1) as Hp1.\n    { generalize (div_rem_spec2 p H3).\n      case_eq (rem p 2).\n      + intros H _.\n        apply divides_rem_eq in H.\n        apply proj2 in Hp.\n        destruct (Hp _ H); subst; lia.\n      + intros; lia. }\n    exists (div p 2); split.\n    + generalize (div_rem_spec1 p 2) (prime_ge_2 Hp).\n      destruct (div p 2); intros; lia.\n    + rewrite Nat.mul_comm.\n      rewrite (div_rem_spec1 p 2) at 1.\n      f_equal; auto.\n  Qed.\n\n  Fact remarkable_id1_nat x y : (x+y)*(x+y) = x*x+2*(x*y)+y*y.\n  Proof. ring. Qed.\n\n  Fact remarkable_id1_Z (a b : Z) : ((a+b)*(a+b) = a*a + 2*a*b + b*b)%Z.\n  Proof. ring. Qed.\n\n  Fact Zsquare_bound x y : (-y <= x <= y -> x*x <= y*y)%Z.\n  Proof.\n    intros (H1 & H2).\n    destruct (Z_pos_or_neg x).\n    + apply Z.square_le_mono_nonneg; auto.\n    + replace (y*y)%Z with ((-y)*(-y))%Z by ring.\n      apply Z.square_le_mono_nonpos; lia.\n  Qed.\n\n  Local Fact bounded_upper_limit_4 a b c d m : \n           (a <= m \n         -> b <= m \n         -> c <= m \n         -> d <= m\n         -> a+b+c+d = 4*m \n         -> a = m \n         /\\ b = m \n         /\\ c = m \n         /\\ d = m)%Z.\n  Proof. lia. Qed.\n\n  Local Fact bounded_lower_limit_4 a b c d : \n           (0 <= a \n         -> 0 <= b \n         -> 0 <= c \n         -> 0 <= d \n         -> a+b+c+d = 0 \n         -> a = 0 \n         /\\ b = 0 \n         /\\ c = 0 \n         /\\ d = 0)%Z.\n  Proof. lia. Qed.\n\n  Local Fact four_squares_zero a b c d : \n           (a*a+b*b+c*c+d*d = 0 \n         -> a = 0 \n         /\\ b = 0 \n         /\\ c = 0 \n         /\\ d = 0)%Z.\n  Proof.\n    intros H.\n    apply bounded_lower_limit_4 in H; try apply Z.square_nonneg.\n    destruct H as (H1 & H2 & H3 & H4).\n    apply Zmult_integral in H1.\n    apply Zmult_integral in H2.\n    apply Zmult_integral in H3.\n    apply Zmult_integral in H4.\n    destruct H1; destruct H2; destruct H3; destruct H4; auto.\n  Qed.\n \n  Fact Zsquare_inj x y : (x*x = y*y -> { x = y } + { - x = y } )%Z.\n  Proof.\n    intros H.\n    assert ( (x+y)*(x-y) = 0 )%Z as E.\n    { rewrite Z.mul_sub_distr_l, !Z.mul_add_distr_r, H; ring. }\n    apply Zmult_integral in E.\n    destruct (Z.eq_dec x y); auto.\n    right; lia.\n  Qed.\n\n  Fact square_4_simpl x m : \n        (4*(x*x) = Z.of_nat m*Z.of_nat m)%Z \n     -> { n | m = 2*n \n           /\\   (x = Z.of_nat n \n             \\/ (x = - Z.of_nat n)%Z) }.\n  Proof.\n    intros H.\n    replace (4*(x*x))%Z with ((2*x)*(2*x))%Z in H by ring.\n    apply Zsquare_inj in H.\n    destruct H as [ H | H ].\n    + destruct Z_of_nat_complete_inf with x as (k & ->).\n      * generalize (Zle_0_nat m); lia.\n      * exists k; split; auto.\n        apply Nat2Z.inj.\n        rewrite Nat2Z.inj_mul, <- H; auto.\n    + destruct (Z_of_nat_complete_inf (Z.opp x)) as (k & Hk).\n      * generalize (Zle_0_nat m); lia.\n      * exists k; split.\n        - apply Nat2Z.inj.\n          rewrite Nat2Z.inj_mul, <- H, <- Hk; ring.\n        - right; rewrite <- Hk; ring.\n  Qed.\n\n  Fact square_4_simpl' x m : \n         (4*(x*x) = Z.of_nat (2*m)*Z.of_nat (2*m) \n       -> x = Z.of_nat m \\/ x = - Z.of_nat m)%Z.\n  Proof.\n    intros H.\n    replace (4*(x*x))%Z with ((2*x)*(2*x))%Z in H by ring.\n    apply Zsquare_inj in H.\n    destruct H as [ H | H  ]; rewrite Nat2Z.inj_mul in H; \n      change (Z.of_nat 2) with 2%Z in H; lia.\n  Qed.\n\n  (* We can find a small representative in absolute value *)\n\n  Lemma Zp_small_repr m (Hm : m <> 0) x : \n         exists y, Z2Zp Hm x = Z2Zp Hm y\n               /\\ (4*(y*y) <= Z.of_nat m * Z.of_nat m)%Z.\n  Proof.\n    destruct (euclid_2 m) as (p & [ H | H ]).\n    + destruct (Zp_repr_interval Hm (- Z.of_nat p)%Z (Z.of_nat p) x) as (y & H1 & H2).\n      * rewrite H, Nat2Z.inj_mul; simpl Z_of_nat; lia.\n      * exists y; split; auto.\n        rewrite H, Nat2Z.inj_mul.\n        simpl Z.of_nat.\n        replace (2*Z.of_nat p*(2*Z.of_nat p))%Z \n        with    (4*(Z.of_nat p*Z.of_nat p))%Z by ring.\n        nia.\n    + destruct (Zp_repr_interval Hm (- Z.of_nat p)%Z (1+Z.of_nat p) x) as (y & H1 & H2).\n      * rewrite H, Nat2Z.inj_add, Nat2Z.inj_mul; simpl Z_of_nat; lia.\n      * exists y; split; auto.\n        apply Z.le_trans with (Z.of_nat (2*p) * Z.of_nat (2*p))%Z.\n        - rewrite Nat2Z.inj_mul.\n          simpl Z.of_nat.\n          replace (2*Z.of_nat p*(2*Z.of_nat p))%Z \n          with    (4*(Z.of_nat p*Z.of_nat p))%Z by ring.\n          nia.\n        - apply Zsquare_bound; subst.\n          rewrite !Nat2Z.inj_add, !Nat2Z.inj_mul; simpl Z.of_nat; lia.\n  Qed.\n\n  Lemma Zp_square_zero m (Hm : m <> 0) (Hm2 : m*m <> 0) x :\n            Z2Zp Hm x      = Zp_zero Hm \n         -> Z2Zp Hm2 (x*x) = Zp_zero Hm2.\n  Proof.\n    intros H.\n    apply Z2Zp_zero_inv in H.\n    destruct H as (v & ->).\n    replace (Z.of_nat m*v*(Z.of_nat m*v))%Z\n    with    (Z.of_nat m*Z.of_nat m*(v*v))%Z by ring.\n    now rewrite <- Nat2Z.inj_mul, Z2Zp_mult, Z2Zp_of_nat, nat2Zp_p, Zp_mult_zero.\n  Qed.\n\nEnd utils.\n\nSection half_modulus_lemma.\n\n  (* If x = +- m [ 2m ] then x² = m² [4m²] *)\n\n  Variable (m : nat) (H2m : 2*m <> 0) (Hm2 : 4*m*m <> 0).\n\n  Let lemma1 x :\n          Z2Zp H2m x = nat2Zp H2m m \n       -> Z2Zp Hm2 (x*x) = nat2Zp Hm2 (m*m).\n  Proof.\n    intros H.\n    rewrite <- Z2Zp_of_nat in H.\n    apply Z2Zp_inj in H.\n    destruct H as (k & H).\n    assert (x = Z.of_nat m+2*k*Z.of_nat m)%Z as Hx.\n    { rewrite Nat2Z.inj_mul, Z.mul_assoc, (Z.mul_comm k) in H.\n      change 2%Z with (Z.of_nat 2); lia. }\n    rewrite Hx, remarkable_id1_Z, !Z2Zp_plus.\n    replace (2*Z.of_nat m * (2*k*Z.of_nat m))%Z\n    with    (Z.of_nat (4*m*m)*k)%Z.\n    2:{ rewrite !Nat2Z.inj_mul; ring. }\n    replace (2*k*Z.of_nat m * (2*k*Z.of_nat m))%Z\n    with    (Z.of_nat (4*m*m)*(k*k))%Z.\n    2:{ rewrite !Nat2Z.inj_mul; ring. }\n    rewrite (Z2Zp_mult _ _ k), Z2Zp_of_nat, nat2Zp_p, Zp_mult_zero.\n    rewrite (Z2Zp_mult _ _ (k*k)), Z2Zp_of_nat, nat2Zp_p, Zp_mult_zero.\n    rewrite !Zp_plus_zero_r, <- Nat2Z.inj_mul, Z2Zp_of_nat; auto.\n  Qed.\n\n  Let lemma2 x :\n        (Z2Zp H2m x = Zp_opp H2m (nat2Zp H2m m))%Z \n      -> Z2Zp Hm2 (x*x) = nat2Zp Hm2 (m*m).\n  Proof.\n    intros H.\n    replace (x*x)%Z with ((-x)*(-x))%Z by ring.\n    apply lemma1.\n    rewrite Z2Zp_opp, H, Zp_opp_inv; auto.\n  Qed.\n\n  Fact half_modulus_lemma' x :\n           Z2Zp H2m x = nat2Zp H2m m \n       \\/ (Z2Zp H2m x = Zp_opp H2m (nat2Zp H2m m))%Z\n       -> Z2Zp Hm2 (x*x) = nat2Zp Hm2 (m*m).\n  Proof. intros []; auto. Qed.\n\n  Fact half_modulus_lemma x y : \n           Z2Zp H2m x = Z2Zp H2m y\n        -> y = Z.of_nat m \n        \\/ y = (- Z.of_nat m)%Z\n        -> Z2Zp Hm2 (x*x) = nat2Zp Hm2 (m*m).\n  Proof.\n    intros H1 H2.\n    apply half_modulus_lemma'.\n    rewrite H1.\n    destruct H2; subst y; [ left | right ].\n    + rewrite Z2Zp_of_nat; auto.\n    + rewrite Z2Zp_opp, Z2Zp_of_nat; auto.\n  Qed.\n\nEnd half_modulus_lemma.\n\nSection lagrange_prelim_odd.\n\n  Variable (p n : nat) (Hp1 : prime p) (Hp2 : p = 2*n+1).\n\n  Let Hn : 0 < n.\n  Proof.\n    destruct n; try lia.\n    simpl in Hp2; subst.\n    exfalso; apply Hp1; trivial.\n  Qed.\n\n  Let Hp : p <> 0.\n  Proof. lia. Qed.\n\n  Let l := list_an 0 (1+n).\n\n  Let Hl : forall x, In x l <-> x <= n.\n  Proof.\n    unfold l; intros x; rewrite list_an_spec; lia.\n  Qed.\n\n  (* Let us defined two injective functions from [0,n] to Z/Z(2n+1) \n\n     f := x => x²\n     g := x => -(1+x²)\n\n   *)\n\n  Let f x := nat2Zp Hp (x*x).\n  Let g y := Zp_opp Hp (Zp_plus Hp (Zp_one Hp) (f y)).\n\n  Let Hf x y : In x l -> In y l -> f x = f y -> x = y.\n  Proof.\n    unfold f; intros G1 G2 H.\n    do 2 rewrite nat2Zp_mult in H.\n    apply Zp_prime_square_eq_square in H; auto.\n    destruct H as [ H | H ].\n    + rewrite nat2Zp_inj in H.\n      rewrite <- (@rem_idem x p), H, rem_idem; auto.\n      * apply Hl in G2; lia.\n      * apply Hl in G1; lia.\n    + apply f_equal with (f := @proj1_sig _ _) in H; simpl in H.\n      rewrite rem_idem in H.\n      2: apply Hl in G1; lia.\n      case_eq (rem y p).\n      * intros Hy.\n        rewrite Hy, Nat.sub_0_r, rem_diag in H; auto.\n        rewrite rem_idem in Hy; try lia.\n        apply Hl in G2; lia.\n      * intros w Hw.\n        rewrite rem_idem in H; try lia.\n        rewrite H.\n        apply Hl in G2.\n        apply Hl in G1.\n        rewrite rem_idem in H; lia.\n  Qed.\n\n  Let Hg x y : In x l -> In y l -> g x = g y -> x = y.\n  Proof. \n      unfold g; intros G1 G2 G3.\n      apply Zp_opp_inj, Zp_plus_inj_l in G3.\n      revert G3; apply Hf; auto.\n  Qed.\n\n  (* Since |map f l| = n+1 and |map g l| = n+1\n     and the domain has cardinal 2*n+1, they must intersect *)\n\n  Let intersection : exists y, In y (map f l) /\\ In y (map g l).\n  Proof.\n    destruct partition_intersection with (l := map f l) (m := map g l) (k := Zp_list Hp)\n        as [ G | [ G | ] ]; auto.\n    * rewrite Zp_list_length, app_length, map_length, map_length.\n      unfold l; rewrite list_an_length; lia.\n    * intros ? _; apply Zp_list_spec.\n    * apply list_has_dup_map_inv in G; auto.\n      apply not_list_has_dup_an in G; tauto.\n    * apply list_has_dup_map_inv in G; auto.\n      apply not_list_has_dup_an in G; tauto.\n  Qed.\n\n  Local Lemma lagrange_prelim_odd : \n              exists a b, divides p (1+a*a+b*b) \n                       /\\ 2*a <= p-1 \n                       /\\ 2*b <= p-1.\n  Proof using Hf.\n    destruct intersection as (u & G1 & G2).\n    rewrite in_map_iff in G1.\n    rewrite in_map_iff in G2.\n    destruct G1 as (a & G3 & G4).\n    destruct G2 as (b & G5 & G6).\n    exists a, b; msplit 2.\n    + rewrite divides_nat2Zp with (Hp := Hp),\n              (Nat.add_comm 1), <- Nat.add_assoc, \n              !nat2Zp_plus, nat2Zp_one.\n      fold (f a).\n      apply Zp_opp_plus_eq.\n      fold (f b); fold (g b).\n      now rewrite G3, G5, Zp_plus_zero.\n    + apply Hl in G4; lia.\n    + apply Hl in G6; lia.\n  Qed.\n\nEnd lagrange_prelim_odd.\n\n(* Preliminary lemma : any prime p has a (small) multiple n*p of the form 1+a²+b² with 0 < n < p *)\n\nLemma lagrange_prelim p : prime p -> exists n a b, n*p = 1+a*a+b*b /\\ 0 < n < p.\nProof.\n  intros Hp.\n  destruct (prime_2_or_odd Hp) as [ | (n & Hn1 & Hn2) ].\n  + exists 1, 1, 0; subst; auto.\n  + destruct (lagrange_prelim_odd _ Hp Hn2)\n      as (a & b & (k & Hk) & Ha & Hb).\n    exists k, a, b; split; auto.\n    split.\n    1: destruct k; simpl in Hk; try lia; discriminate.\n    assert (a <= n) as Ha' by lia.\n    assert (b <= n) as Hb' by lia.\n    destruct (le_lt_dec p k) as [ H | H ]; auto.\n    exfalso.\n    assert (a*a+2*(1*1)+b*b <= k*p) as C; try lia.\n    apply Nat.le_trans with ((n+n)*(n+n)).\n    2: apply Nat.mul_le_mono; lia.\n    rewrite remarkable_id1_nat.\n    apply Nat.add_le_mono; [ | apply Nat.mul_le_mono; auto ].\n    apply Nat.add_le_mono; [ apply Nat.mul_le_mono; auto | ].\n    apply Nat.mul_le_mono_l.\n    now apply Nat.mul_le_mono.\nQed.\n\nLocal Notation four_squares := (fun a b c d => a*a+b*b+c*c+d*d)%Z.\n\nFact Euler_squares x y a1 b1 c1 d1 a2 b2 c2 d2 :\n         (x = four_squares a1 b1 c1 d1\n       -> y = four_squares a2 b2 c2 d2\n       -> x*y = four_squares (a1*a2+b1*b2+c1*c2+d1*d2)\n                             (a1*b2-b1*a2+d1*c2-c1*d2)\n                             (a1*c2-c1*a2+b1*d2-d1*b2)\n                             (a1*d2-d1*a2+c1*b2-b1*c2))%Z.\nProof. intros -> ->; ring. Qed.\n\n(* The primes are sums of four square, the hard part *)\n\nSection lagrange_for_primes.\n\n  Variable (p : nat) (Hp : prime p).\n\n  (* P n is \"n*p is sum of four squares\" *)\n\n  Let P n := exists a b c d, Z.of_nat (n*p) = four_squares a b c d.\n\n  (* DLW: This one was a pain in the ... *)\n\n  Section lagrange_prime_step.\n\n    (* We show P m /\\ 1 < m < p -> P r for some 1 <= r < m *) \n\n    Variable (m : nat) (H1 : m < p) (H3 : 1 < m) (x1 x2 x3 x4 : Z) \n             (H2 : Z.of_nat (m*p) = four_squares x1 x2 x3 x4).\n\n    Let Hm : m <> 0.\n    Proof. lia. Qed.\n\n    Local Fact lagrange_prime_step' : exists r, 1 <= r < m /\\ P r.\n    Proof using H1 H2 H3 Hp.\n      (* we get small representatives for x1 ... x4 \n         as y1 ... y4 *)\n      generalize (Zp_small_repr Hm x1) (Zp_small_repr Hm x2)\n                 (Zp_small_repr Hm x3) (Zp_small_repr Hm x4).\n      intros (y1 & E1 & Q1) (y2 & E2 & Q2) (y3 & E3 & Q3) (y4 & E4 & Q4).\n      (* they satisfy the same eq for another value r *)\n      assert (Z2Zp Hm (y1*y1+y2*y2+y3*y3+y4*y4) = Zp_zero Hm) as H4.\n      { rewrite !Z2Zp_plus, !Z2Zp_mult, <- E1, <- E2, <- E3, <- E4.\n        rewrite <- !Z2Zp_mult, <- !Z2Zp_plus, <- H2.\n        rewrite Nat2Z.inj_mul, Z2Zp_mult.\n        rewrite Z2Zp_of_nat, nat2Zp_p, Zp_mult_zero; auto. }\n      apply Z2Zp_zero_inv in H4.\n      destruct H4 as (r' & Hr).\n      rewrite (Z.mul_comm _ r') in Hr.\n      (* r is smaller than m *)\n      assert (4 * (r' * Z.of_nat m) <= 4 * (Z.of_nat m * Z_of_nat m))%Z as Hr'.\n      { rewrite <- Hr, !Z.mul_add_distr_l; lia. }\n      rewrite !(Z.mul_comm 4) in Hr'.\n      apply Zmult_le_reg_r in Hr'; try lia.\n      apply Zmult_le_reg_r in Hr'; try lia.\n      (* r is positive *)\n      assert (0 <= r' * Z_of_nat m)%Z as Hr''.\n      { rewrite <- Hr; repeat apply Z.add_nonneg_nonneg; apply Z.square_nonneg. }\n      apply Zmult_le_0_reg_r in Hr''.\n      2:{ apply (inj_gt m 0); lia. }\n      (* So r is a nat below m *)\n      apply Z_of_nat_complete_inf in Hr''.\n      destruct Hr'' as (r & ?); subst r'.\n      apply Nat2Z.inj_le in Hr'.\n      (* Let us show r is not m *)\n      destruct (eq_nat_dec m r) as [ <- | Hr1 ].\n      { (* Because r = m implies an absurdity *)\n        (* first we show m = 2q and y1 ... y4 = +- q *)\n        clear Hr'.\n        apply f_equal with (f := fun i => (4*i)%Z) in Hr.\n        rewrite !Z.mul_add_distr_l in Hr.\n        apply bounded_upper_limit_4 in Hr; auto.\n        destruct Hr as (F1 & F2 & F3 & F4).\n        apply square_4_simpl in F1.\n        destruct F1 as (q & Hq & F1).\n        rewrite Hq in F2, F3, F4. \n        apply square_4_simpl' in F2.\n        apply square_4_simpl' in F3.\n        apply square_4_simpl' in F4.\n        (* then we show xi² = q² [4q²] *)\n        subst m. \n        assert (4*q*q <> 0) as Hq.\n        { destruct q; simpl; try discriminate; lia. }\n        apply half_modulus_lemma with (1 := E1) (Hm2 := Hq) in F1.\n        apply half_modulus_lemma with (1 := E2) (Hm2 := Hq) in F2.\n        apply half_modulus_lemma with (1 := E3) (Hm2 := Hq) in F3.\n        apply half_modulus_lemma with (1 := E4) (Hm2 := Hq) in F4.\n        (* thus 2q*p = m*p = x1²+...+x4² = 0 [4q²] *)\n        assert (Z2Zp Hq (Z.of_nat (2 * q * p)) = Zp_zero Hq) as C.\n        { rewrite H2, !Z2Zp_plus, F1, F2, F3, F4.\n          rewrite <- !nat2Zp_plus.\n          replace (q*q+q*q+q*q+q*q) with (4*q*q) by ring.\n          rewrite nat2Zp_p; auto. }\n        rewrite Z2Zp_of_nat in C.\n        apply divides_nat2Zp in C.\n        destruct C as (d & Hd).\n        (* thus 2q divides p *)\n        assert (divides (2*q) p) as C.\n        { replace (d*(4*q*q)) with (2*q*(d*(2*q))) in Hd by ring.\n          apply Nat.mul_cancel_l in Hd; try lia.\n          exists d; auto. }\n        (* Not possible because p is prime *)\n        apply Hp in C; destruct C; try lia. }\n      (* Let us show that r is not 0 *)\n      destruct (eq_nat_dec r 0) as [ -> | Hr2 ].\n      { (* all the yi are zero *)\n        apply four_squares_zero in Hr.\n        destruct Hr as (? & ? & ? & ?); subst y1 y2 y3 y4.\n        (* xi² = 0 [ m² ] *)\n        assert (Hm2 : m*m <> 0).\n        { destruct m; simpl; try discriminate; lia. }\n        rewrite Z2Zp_zero in E1; apply Zp_square_zero with (Hm2 := Hm2) in E1.\n        rewrite Z2Zp_zero in E2; apply Zp_square_zero with (Hm2 := Hm2) in E2.\n        rewrite Z2Zp_zero in E3; apply Zp_square_zero with (Hm2 := Hm2) in E3.\n        rewrite Z2Zp_zero in E4; apply Zp_square_zero with (Hm2 := Hm2) in E4.\n        (* mp = 0 [ m² ] *)\n        assert (Z2Zp Hm2 (Z.of_nat (m*p)) = Zp_zero Hm2) as C.\n        { rewrite H2, !Z2Zp_plus, E1, E2, E3, E4, !Zp_plus_zero; auto. }\n        (* m divides p *)\n        rewrite Z2Zp_of_nat in C.\n        apply divides_nat2Zp in C.\n        destruct C as (d & Hd).\n        assert (divides m p) as C.\n        { replace (d*(m*m)) with (m*(d*m)) in Hd by ring.\n          apply Nat.mul_cancel_l in Hd; try lia.\n          exists d; auto. }\n        (* impossible because p is prime *)\n        apply Hp in C.\n        destruct C as [ C | C ]; lia. }\n      (* Hence we have y1²+...+y4² = mr with 0 < r < m *)  \n      assert (0 < r < m) as Hk by lia.\n      clear Hr' Hr1 Hr2 Q1 Q2 Q3 Q4.\n      symmetry in Hr.\n      rewrite <- Nat2Z.inj_mul in Hr.\n      (* rpm² = a²+...+d² with m dividing a, b, c, d *)\n      assert (exists a b c d, Z.of_nat (r*p*m*m) = four_squares a b c d%Z\n                           /\\ Z2Zp Hm a = Zp_zero Hm\n                           /\\ Z2Zp Hm b = Zp_zero Hm\n                           /\\ Z2Zp Hm c = Zp_zero Hm\n                           /\\ Z2Zp Hm d = Zp_zero Hm) as Q.\n      { exists (x1 * y1 + x2 * y2 + x3 * y3 + x4 * y4)%Z,\n               (x1 * y2 - x2 * y1 + x4 * y3 - x3 * y4)%Z, \n               (x1 * y3 - x3 * y1 + x2 * y4 - x4 * y2)%Z,\n               (x1 * y4 - x4 * y1 + x3 * y2 - x2 * y3)%Z; msplit 4.\n        + rewrite <- (Euler_squares _ _ _ _ _ _ _ _ H2 Hr).\n          rewrite <- Nat2Z.inj_mul; f_equal; ring.\n        + rewrite !Z2Zp_plus, !Z2Zp_mult. \n          rewrite <- E1, <- E2, <- E3, <- E4.\n          rewrite <- !Z2Zp_mult, <- !Z2Zp_plus.\n          rewrite <- H2, Nat2Z.inj_mul, Z2Zp_mult, \n                  Z2Zp_of_nat, nat2Zp_p, Zp_mult_zero; auto.\n        + repeat (rewrite !Z2Zp_minus || rewrite !Z2Zp_plus). \n          rewrite !Z2Zp_mult.\n          rewrite <- E1, <- E2, <- E3, <- E4.\n          rewrite <- !Z2Zp_mult.\n          repeat (rewrite <- !Z2Zp_minus || rewrite <- !Z2Zp_plus).\n          rewrite <- Z2Zp_zero; f_equal; ring.\n        + repeat (rewrite !Z2Zp_minus || rewrite !Z2Zp_plus). \n          rewrite !Z2Zp_mult.\n          rewrite <- E1, <- E2, <- E3, <- E4.\n          rewrite <- !Z2Zp_mult.\n          repeat (rewrite <- !Z2Zp_minus || rewrite <- !Z2Zp_plus).\n          rewrite <- Z2Zp_zero; f_equal; ring.\n        + repeat (rewrite !Z2Zp_minus || rewrite !Z2Zp_plus). \n          rewrite !Z2Zp_mult.\n          rewrite <- E1, <- E2, <- E3, <- E4.\n          rewrite <- !Z2Zp_mult.\n          repeat (rewrite <- !Z2Zp_minus || rewrite <- !Z2Zp_plus).\n          rewrite <- Z2Zp_zero; f_equal; ring. }\n      clear x1 x2 x3 x4 H2 H3 y1 E1 y2 E2 y3 E3 y4 E4 Hr.\n      (* then we built a smaller solution *)\n      destruct Q as (a & b & c & d & H & Ha & Hb & Hc & Hd).\n      apply Z2Zp_zero_inv in Ha; destruct Ha as (x & ->).\n      apply Z2Zp_zero_inv in Hb; destruct Hb as (y & ->).\n      apply Z2Zp_zero_inv in Hc; destruct Hc as (z & ->).\n      apply Z2Zp_zero_inv in Hd; destruct Hd as (w & ->).\n      exists r; split; try lia.\n      exists x, y, z, w.\n      apply Z.mul_cancel_r with (p := Z.of_nat (m*m)).\n      { intros E.\n        apply Nat2Z.inj with (m := 0) in E.\n        destruct m; try discriminate; lia. }\n      rewrite <- Nat2Z.inj_mul, Nat.mul_assoc, H.\n      rewrite Nat2Z.inj_mul; ring.\n    Qed.\n\n  End lagrange_prime_step.\n\n  Let lagrange_prime_step m : 1 < m < p -> P m -> exists r, 1 <= r < m /\\ P r.\n  Proof.\n    intros H1 (x1 & x2 & x3 & x4 & H2); apply lagrange_prime_step' with (3 := H2); lia.\n  Qed.\n\n  (* Now that P 1 holfs ie p is sum of 4 squares *)\n\n  Lemma lagrange_prime : exists a b c d, Z.of_nat p = (a*a+b*b+c*c+d*d)%Z.\n  Proof using Hp.\n    replace p with (1*p) by lia; change (P 1).\n    destruct (lagrange_prelim Hp) as (n & a & b & H1 & H2 & H3).\n    cut (P n).\n    + revert H2 H3; clear H1.\n      induction on n as IH with measure n.\n      intros H2 H3 H.\n      destruct (le_lt_dec n 1) as [ | Hn ].\n      * now replace 1 with n by lia.\n      * destruct lagrange_prime_step with (2 := H) as (m & H4 & H5); auto.\n        generalize H5; destruct H5; apply IH; auto; lia.\n    + exists 0%Z, 1%Z, (Z.of_nat a), (Z.of_nat b).\n      rewrite H1, !Nat2Z.inj_add, !Nat2Z.inj_mul.\n      simpl Z.of_nat at 1; lia.\n  Qed.\n\nEnd lagrange_for_primes.\n\nSection lagrange.\n\n  Open Scope Z_scope.\n\n  Theorem lagrange_theorem_nat : forall n, exists a b c d, Z.of_nat n = a*a+b*b+c*c+d*d.\n  Proof.\n    induction n as [ | | p Hp | x y Hx Hy ] using prime_rect.\n    + exists 0, 0, 0, 0; auto.\n    + exists 1, 0, 0, 0; auto.\n    + apply lagrange_prime; auto.\n    + destruct Hx as (a1 & b1 & c1 & d1 & H1).\n      destruct Hy as (a2 & b2 & c2 & d2 & H2).\n      subst.\n      exists (a1*a2+b1*b2+c1*c2+d1*d2),\n             (a1*b2-b1*a2+d1*c2-c1*d2),\n             (a1*c2-c1*a2+b1*d2-d1*b2),\n             (a1*d2-d1*a2+c1*b2-b1*c2).\n      rewrite Nat2Z.inj_mul; apply Euler_squares; auto.\n  Qed.\n\n  (* An relative integer is positive iff it is the sum of four squares *)\n\n  Corollary lagrange_theorem_Z n : 0 <= n <-> exists a b c d, n = a*a+b*b+c*c+d*d.\n  Proof.\n    split.\n    + intros H.\n      destruct Z_of_nat_complete with (1 := H) as (m & ->).\n      apply lagrange_theorem_nat.\n    + intros (a & b & c & d & ->).\n      generalize (a*a) (b*b) (c*c) (d*d) \n                 (Z.square_nonneg a) (Z.square_nonneg b)\n                 (Z.square_nonneg c) (Z.square_nonneg d).\n      intros; lia.\n  Qed.\n\nEnd lagrange.\n\n(* Check lagrange_theorem_Z. *)\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/H10/ArithLibs/lagrange.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7449697525889523}}
{"text": "\nLemma ex1: forall A B C:Prop, A/\\(B/\\C)->(A/\\B)/\\C.\nProof.\n    intros A B C H.\n    destruct H as [H1 Ht].\n    destruct Ht as [H2 H3].\n    split.\n    split.\n    assumption.\n    assumption.\n    assumption.\nQed.\n\nLemma ex2: forall A B C D: Prop,(A->B)/\\(C->D)/\\A/\\C -> B/\\D.\nProof.\n    intros A B C D H.\n    destruct H as [ab [cd [a c]]].\n    split.\n    apply ab.\n    assumption.\n    apply cd.\n    assumption.\nQed.\n\nLemma ex3: forall A: Prop, ~(A/\\~A).\nProof.\n    intros a P.\n    destruct P as [A NA].\n    elim NA.\n    assumption.\nQed.\n\nLemma ex4: forall A B C: Prop, A\\/(B\\/C)->(A\\/B)\\/C.\nProof.\n    intros A B C H.\n    destruct H as [H1 | [H2 | H3]].\n    left; left.\n    assumption.\n    left; right.\n    assumption.\n    right.\n    assumption.\nQed.\n\nLemma ex5: forall A B: Prop, (A\\/B)/\\~A -> B.\nProof.\n    intros A B H.\n    destruct H as [[H1 | H2] H3].\n    elim H3.\n    assumption.\n    assumption.\nQed.\n\nLemma ex6: forall A:Type, forall P Q: A->Prop, \n(forall x, P x)\\/(forall y, Q y)->forall x, P x\\/Q x.\nProof.\n    intros A P Q H.\n    destruct H as [H1 | H2].\n    intros X.\n    left.\n    apply H1 with (x:=X).\n    intros X.\n    right.\n    apply H2 with (y:=X).\nQed.\n\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/Chapter3Ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.744957268162255}}
{"text": "(* Correct Definition of φ *)\n\nRequire Import Utf8 Arith.\nImport List List.ListNotations.\nRequire Import Misc Primes.\nRequire Import PTotient Primisc.\n\n\nDefinition coprimes n := filter (λ d, Nat.gcd n d =? 1) (seq 1 n).\nDefinition φ n := length (coprimes n).\n\nLemma coprimes_coprimes' :\n    ∀ n, 2 ≤ n → coprimes n = coprimes' n.\nProof.\n    intros. unfold coprimes, coprimes'.\n    replace n with ((n - 1) + 1) at 1 by flia H.\n    rewrite seq_app.\n    replace (1 + (n - 1)) with n at 1 by flia H.\n    rewrite filter_app. simpl.\n    destruct (Nat.eqb_spec (Nat.gcd n n) 1).\n    - rewrite Nat.gcd_diag in *. flia H e.\n    - rewrite app_nil_r. reflexivity.\nQed.\n\nLemma φ_φ' :\n    ∀ n, 2 ≤ n → φ n = φ' n.\nProof.\n    intros. unfold φ, φ'.\n    rewrite coprimes_coprimes' by flia H.\n    reflexivity.\nQed.\n\nTheorem prime_φ :\n    ∀ p, prime p → φ p = p - 1.\nProof.\n    intros.\n    rewrite <- prime_φ' by assumption.\n    apply φ_φ'. apply prime_ge_2. assumption.\nQed.\n\nTheorem φ_multiplicative :\n    ∀ m n, \n        Nat.gcd m n = 1 →\n        φ (m * n) = φ m * φ n.\nProof.\n    intros.\n    destruct (Nat.leb_spec 2 m).\n    destruct (Nat.leb_spec 2 n).\n    -   assert (2 ≤ m * n) by flia H0 H1.\n        repeat rewrite φ_φ' by assumption.\n        rewrite φ'_multiplicative by assumption.\n        reflexivity.\n    -   destruct n. rewrite Nat.gcd_0_r in H.\n        flia H H0. replace n with 0 by flia H1.\n        cbn. rewrite mult_1_r. rewrite mult_1_r.\n        reflexivity.\n    -   destruct m. rewrite Nat.gcd_0_l in H.\n        rewrite mult_0_l. cbn. reflexivity.\n        replace m with 0 by flia H0.\n        rewrite mult_1_l. cbn. rewrite plus_0_r.\n        reflexivity.\nQed.\n        \nTheorem prime_pow_φ :\n    ∀ p, prime p →\n        ∀ k, k ≠ 0 → φ (p ^ k) = p ^ (k - 1) * φ p.\nProof.\n    intros.\n    assert (2 ≤ p ^ k).\n    {\n        apply le_trans with p.\n        apply prime_ge_2.\n        assumption.\n        rewrite <- Nat.pow_1_r at 1.\n        apply Nat.pow_le_mono_r.\n        apply prime_ge_2 in H. flia H.\n        flia H0.\n    }\n    rewrite φ_φ' by assumption.\n    rewrite prime_pow_φ' by assumption.\n    rewrite φ_φ'. reflexivity.\n    apply prime_ge_2. assumption.\nQed.\n\n\n", "meta": {"author": "taorunz", "repo": "euler", "sha": "5fcf1db4d5a68f0d55118fb2733cede2cc515a23", "save_path": "github-repos/coq/taorunz-euler", "path": "github-repos/coq/taorunz-euler/euler-5fcf1db4d5a68f0d55118fb2733cede2cc515a23/Totient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7449131052520905}}
{"text": "Print negb.\n\nTheorem negb_involutive : forall b : bool,\n    negb (negb b) = b.\nProof.\n  intros. destruct b as [|] eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nPrint andb.\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b eqn:E.\n  - destruct c eqn:E1.  \n    + reflexivity.\n    + reflexivity.\n  - destruct c eqn:E1.\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", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/nebg_involutive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7449130922905065}}
{"text": "(* http://qnighy.github.io/coqex2014/ex2.html *)\nRequire Import Arith.\n\nGoal forall x y, x < y -> x + 10 < y + 10.\nProof.\n  intros.\n  apply plus_lt_compat_r.\n  apply H.\nQed.\n\nGoal forall P Q : nat -> Prop, P 0 -> (forall x, P x -> Q x) -> Q 0.\nProof.\n  intros.\n  apply H0.\n  apply H.\nQed.\n\nGoal forall P : nat -> Prop, P 2 -> (exists y, P (1 + y)).\nProof.\n  intros.\n  exists 1.\n  apply H.\nQed.\n\nGoal forall P : nat -> Prop, (forall n m, P n -> P m) -> (exists p, P p) -> forall q, P q.\nProof.\n  intros.\n  destruct H0.\n  apply (H x q).\n  apply H0.\nQed.\n\nRequire Import Arith.\nGoal forall m n : nat, (n * 10) + m = (10 * n) + m.\nProof.\n  intros.\n  assert (n * 10 = 10 * n).\n  apply Nat.mul_comm.\n  rewrite H.\n  reflexivity.\nQed.\n\nGoal forall n m p q : nat, (n + m) + (p + q) = (n + p) + (m + q).\nProof.\n  intros.\n  apply Nat.add_shuffle1.\nQed.\n\nGoal forall n m : nat, (n + m) * (n + m) = n * n + m * m + 2 * n * m.\nProof.\n  intros.\n  assert ((n + m) * (n + m) = n * (n + m) + m * (n + m)).\n  apply (Nat.mul_add_distr_r n m (n + m)).\n  rewrite H.\n  assert (n * (n + m) = n * n + n * m).\n  apply (Nat.mul_add_distr_l n n m).\n  assert (m * (n + m) = m * n + m * m).\n  apply (Nat.mul_add_distr_l m n m).\n  rewrite H0.\n  rewrite H1.\n  assert (m * n + m * m = m * m + m * n).\n  apply Nat.add_comm.\n  rewrite H2.\n  assert (n * n + n * m + (m * m + m * n) = n * n + m * m + (n * m + m * n)).  \n  apply Unnamed_thm4.\n  rewrite H3.\n  assert (n * m + m * n = n * m + n * m).\n  assert (m * n = n * m).\n  apply Nat.mul_comm.\n  rewrite H4.\n  reflexivity.\n  rewrite H4.\n  assert ((n + n) * m = n * m + n * m).\n  apply Nat.mul_add_distr_r.\n  rewrite <- H5.\n  simpl.\n  assert (n + n + 0 = n + (n + 0)).\n  apply (plus_assoc_reverse n n 0).\n  rewrite <- H6.\n  assert (n + n + 0 = n + n).\n  apply (Nat.add_0_r (n + n)).\n  rewrite H7.\n  reflexivity.\nQed.\n\nParameter G : Set.\nParameter mult : G -> G -> G.\nNotation \"x * y\" := (mult x y).\nParameter one : G.\nNotation \"1\" := one.\nParameter inv : G -> G.\nNotation \"/ x\" := (inv x).\n(* Notation \"x / y\" := (mult x (inv y)). *) (* 使ってもよい *)\n\nAxiom mult_assoc : forall x y z, x * (y * z) = (x * y) * z.\nAxiom one_unit_l : forall x, 1 * x = x.\nAxiom inv_l : forall x, /x * x = 1.\n\nLemma inv_r : forall x, x * / x = 1.\nProof.\n  intros.\n  assert (//x * /x = 1).\n  apply (inv_l (/ x)).\n  assert (//x * /x * x = //x * (/x * x)).\n  rewrite <- (mult_assoc (//x) (/x) x).\n  reflexivity.\n  rewrite H in H0.\n  rewrite inv_l in H0.\n  rewrite one_unit_l in H0.\n  assert (//x * (1 * /x) = 1).\n  rewrite one_unit_l.\n  apply H.\n  rewrite mult_assoc in H1.\n  rewrite <- H0 in H1.\n  apply H1.\nQed.\n\nLemma one_unit_r : forall x, x * 1 = x.\nProof.\n  intros.\n  rewrite <- (inv_l x).\n  rewrite mult_assoc.\n  rewrite inv_r.\n  rewrite one_unit_l.\n  reflexivity.\nQed.", "meta": {"author": "unaoya", "repo": "coq_intro", "sha": "c417320df036d96f22744c7bb90695160c012e91", "save_path": "github-repos/coq/unaoya-coq_intro", "path": "github-repos/coq/unaoya-coq_intro/coq_intro-c417320df036d96f22744c7bb90695160c012e91/exercise2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7449130895583624}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Matrix implemented with Dependent List\n  author    : ZhengPu Shi\n  date      : 2021.12\n  \n  remark    :\n  1. use Coq.Vectors.Vector\n  2. given more functions and properties\n  3. some design ideas com from CoLoR\n\n  rewrite command:\n  rewrite !A: rewriting A as long as possible (at least once)\n  rewrite ?A: rewriting A as long as possible (possibly never)\n  rewrite 3?A: rewriting A at most three times\n  rewrite 3 A or rewrite 3!A: rewriting A exact 3 times\n  \n *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Export SetoidListListExt.\nRequire Export Coq.Vectors.Fin.\nRequire Export Coq.Vectors.Vector.\nRequire Import Extraction.\nRequire Import Relations.\nRequire Import FunctionalExtensionality.\nRequire Import Lia.\n\nImport ListNotations.   (* list_scope, delimiting with list *)\nExport VectorNotations. (* vector_scope, delimiting with vector *)\n\nOpen Scope nat_scope.\nOpen Scope A_scope.\nOpen Scope vector_scope.\nOpen Scope mat_scope.\n\nGeneralizable Variable A B C Aeq Beq Ceq Aadd Aopp Amul Ainv.\n\n(** Example shows the definition of matrix *)\nModule Demo_matrix_def.\n\n  (* The definition of vector in Coq.Vectors.Vector *)\n  Inductive vec (A : Type) : nat -> Type :=\n  | nil : vec A 0 \n  | cons : A -> forall n : nat, vec A n -> vec A (S n).\n  \n  (* The definition of matrix *)\n  Definition matrix (A : Type) (r c : nat) := @vec (@vec A c) r.\n\nEnd Demo_matrix_def.\n\n(** Tips: an improvement for the definition of vec. It is a bit different to \n    the definition in standard library, and a convenient attribute it have. *)\nModule Demo_matrix_def_improve.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := Aeq : A_scope.\n\n  (** Vectors.Vector *)\n  Module Standard.\n\n    (** Definition of vector type *)\n    Inductive vec {A : Type} : nat -> Type :=\n    | nil : vec 0 \n    | cons : A -> forall n : nat, vec n -> vec (S n).\n\n    (** Notations *)\n    Notation \"[]\" := nil.\n    Notation \"a :: v\" := (cons a v).\n\n    (** Inductive property on two vectors *)\n    Inductive Forall2 (A B : Type) (P : A -> B -> Prop)\n      : forall n : nat, @vec A n -> @vec B n -> Prop :=\n    | Forall2_nil : Forall2 P nil nil\n    | Forall2_cons :\n      forall (m : nat) (x1 : A) (x2 : B) (v1 : vec m) (v2 : vec m),\n        P x1 x2 -> Forall2 P v1 v2 -> Forall2 P (x1 :: v1) (x2 :: v2).\n\n    (** Equality of vector *)\n    Definition veq {n} (v1 v2 : vec n) : Prop := Forall2 Aeq v1 v2.\n\n    (* Tips: we cann't write out the Proper morphism of cons *)\n    (* Fail Check forall n, Proper (Aeq ==> veq (n:=n) ==> veq (n:=S n)) (cons). *)\n    \n  End Standard.\n\n  (** Vectors.Vector (modified) *)\n  Module Modified.\n\n    (** Definition of vector type *)\n    Inductive vec {A : Type} : nat -> Type :=\n    | nil : vec 0 \n    | cons : forall n : nat, A -> vec n -> vec (S n).\n\n    (** Notations *)\n    Notation \"[]\" := nil.\n    Notation \"a :: v\" := (cons a v).\n\n    (** all vec 0 are same *)\n    Lemma vec_0 (v : @vec A 0) : v = nil.\n    Proof.\n      refine (match v with nil => _ end). auto.\n    Qed.\n\n    (** vec (S n) could be decomposed, exist: x:A, v':vec n *)\n    Lemma vec_S {n : nat} (v : @vec A (S n)) :\n      {x & {v' | v = cons x v'}}.  (* sig T *)\n    Proof.\n      refine (match v with | cons x v' => _ end); eauto.\n    Qed.\n\n    (** Inductive property on two vectors *)\n    Inductive Forall2 (A B : Type) (P : A -> B -> Prop)\n      : forall n : nat, @vec A n -> @vec B n -> Prop :=\n    | Forall2_nil : Forall2 P nil nil\n    | Forall2_cons :\n      forall (m : nat) (x1 : A) (x2 : B) (v1 : vec m) (v2 : vec m),\n        P x1 x2 -> Forall2 P v1 v2 -> Forall2 P (x1 :: v1) (x2 :: v2).\n\n    (** Equality of vector *)\n    Definition veq {n} (v1 v2 : vec n) : Prop := Forall2 Aeq v1 v2.\n\n    Infix \"==\" := veq : vector_scope.\n\n    (* Now. we can write out the Proper morphism of cons *)\n    (* Check forall n, Proper (Aeq ==> veq (n:=n) ==> veq (n:=S n)) (cons (n:=n)). *)\n    \n    Lemma cons_aeq_mor : forall n,\n        Proper (Aeq ==> veq (n:=n) ==> veq (n:=S n)) (cons (n:=n)).\n    Proof.\n      unfold Proper, respectful.\n      induction n; intros; constructor; auto.\n    Qed.\n\n    Global Existing Instance cons_aeq_mor.\n\n    Goal forall n (a1 a2 : A) (v1 v2 : vec n), (a1 == a2)%A -> v1 == v2 -> a1::v1 == a2::v2.\n      intros.\n      Fail rewrite H.\n      (* But, we still cannot rewrite. *)\n      constructor; auto.\n      (* In fact, constructor tactor can easily handle this job *)\n    Qed.\n    \n  End Modified.\n\nEnd Demo_matrix_def_improve.\n\n\n(** * Matrix Multiplication (from CoLoR) *)\n(* Module MatMultCoLoR. *)\n\n(*   Notation fin := Fin.t. *)\n\n(*   Notation vec := Vector.t. *)\n(*   Notation vnil := Vector.nil. *)\n\n(*   Notation vcons := Vector.cons. *)\n\n(*   (* Notation vhd := Vector.hd. *) *)\n(*   (* Notation vtl := Vector.tl. *) *)\n(*   (* Notation vconst := Vector.const. *) *)\n\n(*   Notation vnth := Vector.nth. *)\n(*   (* Notation vfoldl := fold_left. *) *)\n(*   (* Notation vfoldr := fold_right. *) *)\n(*   (* Notation vmap := map. *) *)\n(*   (* Notation vmap2 := map2. *) *)\n\n(*   Arguments vec {A}. *)\n(*   Arguments vnil {A}. *)\n(*   Arguments vcons [A] _ [n] _. *)\n(*   (* Arguments vhd [A n] _. *) *)\n(*   (* Arguments vtl [A n] _. *) *)\n(*   (* Arguments vconst [A] _ _. *) *)\n\n(*   Section fin. *)\n(* Lemma fin_0 (i : fin 0) : False. *)\n(* Proof.  *)\n(*   refine (match i with end).  *)\n(* Qed. *)\n    \n(*     (** Decompose \"fin (S n)\" object *) *)\n    (* Lemma fin_S (n : nat) (i : fin (S n)) : *)\n    (*   (i = Fin.F1) + { i' | i = Fin.FS i' }. *)\n    (* Proof. *)\n    (*   refine (match i with | F1 => _ | FS _ => _ end); eauto. *)\n    (* Qed. *)\n(*   End fin. *)\n\n(*   Section vec. *)\n(*     Context {A : Type}. *)\n    \n(*     (** all vec 0 are same *) *)\n(*     Lemma vec_0 (v : @vec A 0) : v = vnil. *)\n(*     Proof. refine (match v with vnil => _ end). auto. Qed. *)\n\n(*     (** vec (S n) could be decomposed, exist: x:A, v':vec n *) *)\n(*     Lemma vec_S {n : nat} (v : @vec A (S n)) : *)\n(*       {x & {v' | v = vcons x v'}}.  (* sig T *) *)\n(*     Proof. refine (match v with | vcons x v' => _ end); eauto. Qed. *)\n\n(*     Lemma veq_iff_nth : forall n (v1 v2 : @vec A n), *)\n(*         (forall f1 f2 : fin n, f1 = f2 -> vnth v1 f1 = vnth v2 f2) <-> v1 = v2. *)\n(*     Proof. *)\n(*       induction n; intros. *)\n(*       - rewrite (vec_0 v1), (vec_0 v2). split; intros; auto. subst; auto. *)\n(*       - pose proof vec_S v1 as [x1 [v1' ->]]. *)\n(*         pose proof vec_S v2 as [x2 [v2' ->]]. split; intros. *)\n(*         + f_equal. *)\n(*           * specialize (H F1 F1 eq_refl); simpl in H. auto. *)\n(*           * apply IHn; intros. subst. *)\n(*             specialize (H (FS f2) (FS f2) eq_refl). simpl in H. auto. *)\n(*         + inv H. apply inj_pair2 in H3. subst. auto. *)\n(*     Qed. *)\n    \n(*   End vec. *)\n\n(*   Section mat_mul. *)\n(*     Variable A : Type. *)\n(*     Variable A0 A1 : A. *)\n(*     Variable fopp : A -> A. *)\n(*     Variable fadd fmul : A -> A -> A. *)\n(*     Variable fadd_comm : forall x y, fadd x y = fadd y x. *)\n(*     Variable fadd_assoc : forall x y z, fadd (fadd x y) z = fadd x (fadd y z). *)\n(*     Variable fmul_comm : forall x y, fmul x y = fmul y x. *)\n(*     Variable fmul_assoc : forall x y z, fmul (fmul x y) z = fmul x (fmul y z). *)\n(*     Variable fadd_0_l : forall x, fadd A0 x = x. *)\n(*     Variable fadd_0_r : forall x, fadd x A0 = x. *)\n(*     Variable fmul_0_r : forall x, fmul x A0 = A0. *)\n(*     Variable fmul_0_l : forall x, fmul A0 x = A0. *)\n(*     Variable fmul_add_distl : forall x y z, *)\n(*         fmul x (fadd y z) = fadd (fmul x y) (fmul x z). *)\n(*     Variable fmul_add_distr : forall x y z, *)\n(*         fmul (fadd x y) z = fadd (fmul x z) (fmul y z). *)\n    \n(*     Infix \"+\" := fadd. *)\n(*     Infix \"*\" := fmul. *)\n\n(*     Definition mat r c := @vec (@vec A c) r. *)\n\n(*     Definition mnth {r c} (m : mat r c) fr fc := vnth (vnth m fr) fc. *)\n\n(*     (** Build vector with a function [gen: fin n -> A] *) *)\n(*     Fixpoint vmake {n} : (fin n -> A) -> vec n := *)\n(*       match n with *)\n(*       | O => fun _ => [] *)\n(*       | S n' => fun (gen : fin (S n') -> A) => *)\n(*                  (gen F1) :: (vmake (fun (fn':fin n') => gen (FS fn')))  *)\n(*       end. *)\n\n(*     (** nth element of a vector generated by vmake, equal to [gen i] *) *)\n(*     Lemma vmake_nth : forall n gen (fn : fin n), nth (vmake gen) fn = gen fn. *)\n(*     Proof. *)\n(*       induction n; intros gen fn. *)\n(*       - exfalso. apply (fin_0 fn). *)\n(*       - pose proof (fin_S fn) as [-> | (fr' & ->)]; simpl; auto. rewrite IHn. auto. *)\n(*     Qed. *)\n\n(*     Definition mrow {r c} (m : mat r c) (fr : fin r) := vnth m fr. *)\n    \n(*     Definition mcol {r c} (m : mat r c) := *)\n(*       fun fc : fin c => vmake (fun fr : fin r => nth (nth m fr) fc). *)\n\n(*     Definition vdot {n} (v1 v2 : vec n) := fold_left fadd A0 (map2 fmul v1 v2). *)\n\n    \n(*     Lemma mat_build_spec : forall {r c}  *)\n(*                              (gen : forall (fr : fin r) (fc : fin c), A),  *)\n(*         { m : mat r c | forall (fr : fin r) (fc : fin c),  *)\n(*             mnth m fr fc = gen fr fc }. *)\n(*     Proof. *)\n(*       induction r; intros c gen. *)\n(*       - (* case r = 0 *) *)\n(*         exists (vnil). intros. inversion fr. *)\n(*       - (* case m > 0 *) *)\n(*         set (gen' := fun (fr : fin r) (fc : fin c) => gen (FS fr) fc). *)\n(*         destruct (IHr c gen') as [Mtl Mtl_spec]. *)\n(*         set (gen_1 := fun (fc:fin c) => gen F1 fc). *)\n(*         set (Mhd := vmake gen_1). *)\n(*         set (Mhd_spec := vmake_nth gen_1). *)\n(*         exists (vcons Mhd Mtl). *)\n(*         intros fr fc. *)\n(*         unfold mnth in *. *)\n(*         pose proof fin_S fr as [-> | (fr' & ->)]. *)\n(*         + simpl. auto. *)\n(*         + simpl. rewrite Mtl_spec. auto. *)\n(*     Defined. *)\n\n(*     Definition mat_build {r c} gen : mat r c := proj1_sig (mat_build_spec gen). *)\n\n(*     Lemma meq_iff_nth : forall r c (m1 m2 : mat r c), *)\n(*         (forall (fr : fin r) (fc : fin c), mnth m1 fr fc = mnth m2 fr fc) -> m1 = m2. *)\n(*     Proof. *)\n(*       induction r; intros. *)\n(*       - rewrite (vec_0 m1), (vec_0 m2). easy. *)\n(*       - pose proof vec_S m1 as [v1 [m1' ->]]. *)\n(*         pose proof vec_S m2 as [v2 [m2' ->]]. *)\n(*         f_equal; auto. *)\n(*         + apply eq_nth_iff. intros. subst. *)\n(*           unfold mnth in H. specialize (H F1). simpl in *. auto. *)\n(*         + apply IHr. intros. apply (H (FS fr)). *)\n(*     Qed. *)\n\n(*     Lemma mat_build_elem : forall r c gen (fr : fin r) (fc : fin c),  *)\n(*         mnth (mat_build gen) fr fc = gen fr fc. *)\n(*     Proof. *)\n(*       intros. unfold mat_build. destruct (mat_build_spec gen). simpl. apply e. *)\n(*     Qed. *)\n\n(*     Lemma mat_build_nth : forall r c gen (fr : fin r) (fc : fin c), *)\n(*         vnth (vnth (mat_build gen) fr) fc = gen fr fc. *)\n(*     Proof. *)\n(*       intros. fold (mrow (mat_build gen) fr). *)\n(*       fold (mnth (mat_build gen) fr fc). *)\n(*       apply mat_build_elem. *)\n(*     Qed. *)\n    \n(*     Definition mat_transpose {r c} (m : mat r c) :=  *)\n(*       mat_build (fun fr fc => mnth m fc fr). *)\n\n(*     Lemma mat_transpose_idem : forall m n (m : mat m n), *)\n(*         mat_transpose (mat_transpose m) = m. *)\n(*     Proof. *)\n(*       intros. apply meq_iff_nth. intros. *)\n(*       unfold mat_transpose. rewrite !mat_build_elem. auto. *)\n(*     Qed. *)\n\n(*     Definition mat_mult {m n p} (L : mat m n) (R : mat n p) := *)\n(*       mat_build (fun fr fc => vdot (mrow L fr) (mcol R fc)). *)\n(*     Infix \"<*>\" := mat_mult (at level 40). *)\n\n(*     Lemma mat_mult_elem : forall r c s (m : mat r c) (n : mat c s) *)\n(*                             (fr : fin r) (fs : fin s),   *)\n(*         vnth (vnth (mat_mult m n) fr) fs = vdot (mrow m fr) (mcol n fs). *)\n(*     Proof. intros. unfold mat_mult. rewrite ?mat_build_nth. auto. Qed. *)\n\n(*     Lemma mat_mult_spec : forall r c s (m : mat r c) (n : mat c s) *)\n(*                             (fr : fin r) (fs : fin s), *)\n(*         mnth (mat_mult m n) fr fs =  vdot (mrow m fr) (mcol n fs). *)\n(*     Proof. *)\n(*       intros. unfold mnth,mcol,mrow. *)\n(*       rewrite mat_mult_elem. unfold mrow, mcol. auto. *)\n(*     Qed. *)\n    \n(*     Lemma mat_mult_row : forall r c s (m : mat r c) (n : mat c s) (fr : fin r), *)\n(*         mrow (m <*> n) fr = vmake (fun fc => vdot (mrow m fr) (mcol n fc)). *)\n(*     Proof. *)\n(*       intros. *)\n(*       apply veq_iff_nth. intros ? fp ->. *)\n(*       unfold mrow, mcol. rewrite vmake_nth. *)\n(*       rewrite mat_mult_elem. auto. *)\n(*     Qed. *)\n\n(*     Lemma mat_mult_col : forall r c s (m : mat r c) (n : mat c s) (fs : fin s), *)\n(*         mcol (m <*> n) fs = *)\n(*           vmake (fun fc => vdot (mrow m fc) (mcol n fs)). *)\n(*     Proof. *)\n(*       intros. *)\n(*       apply veq_iff_nth. intros ? fm ->. *)\n(*       unfold mrow, mcol. rewrite ?vmake_nth. *)\n(*       rewrite mat_mult_elem. auto. *)\n(*     Qed. *)\n\n(*     Lemma mat_mult_assoc : forall r c s t (m : mat r c) (n : mat c s) (p : mat s t), *)\n(*         m <*> (n <*> p) = (m <*> n) <*> p. *)\n(*     Proof. *)\n(*       intros. apply meq_iff_nth. intros. unfold mnth. *)\n(*       rewrite !mat_mult_elem, mat_mult_row, mat_mult_col. *)\n(*       (* apply vdot_vec_mat_vec_assoc; auto. *) *)\n(*       Abort. *)\n    \n(*   End mat_mul. *)\n\n(* End MatMultCoLoR. *)\n\n\n\n\n(** * Additional properties for operations of Vector.t *)\n\n(** ** Global Notations for familiar naming style *)\n\nNotation fin := Fin.t.\n\nNotation vec := Vector.t.\nNotation vnil := Vector.nil.\n\nNotation vcons := Vector.cons.\n\nNotation vhd := Vector.hd.\nNotation vtl := Vector.tl.\nNotation vconst := Vector.const.\n\nNotation vnth := Vector.nth.\nNotation vfoldl := fold_left.\nNotation vfoldr := fold_right.\nNotation vmap := map.\nNotation vmap2 := map2.\n\nArguments vec {A}.\nArguments vnil {A}.\nArguments vcons [A] _ [n] _.\nArguments vhd [A n] _.\nArguments vtl [A n] _.\nArguments vconst [A] _ _.\n\n(** ** fin decompose *)\nSection fin_decompose.\n\n  (** There isn't fin 0 *)\n  Lemma fin_0 (i : fin 0) : False.\n  Proof. \n    (* refine tactic:\n       1. behaves like exact,\n       2. the user can leave some holes in the term.\n       3. generate as many subgoals as there are remaining holes in the\n          elaborated term.\n    *)\n    refine (match i with end). \n  Qed.\n  \n  (** Decompose \"fin (S n)\" object *)\n  Lemma fin_S (n : nat) (i : fin (S n)) :\n    (i = Fin.F1) + { i' | i = Fin.FS i' }.\n  Proof.\n    (* eauto tactic:\n       1. generalizes auto.\n       2. it internally use a tactic close to [simple eapply]\n    *)\n    refine (match i with \n            | F1 => _\n            | FS _ => _ \n            end); eauto.\n  Qed.\n  \n  (** Construct a \"fin n\" object which equal to i *)\n\n  Fixpoint fin_gen (n i : nat) : option (fin n) :=\n    match n,i with\n    | O, _ => @None (Fin.t 0)\n    | S n', O => Some F1\n    | S n', S i' => \n      let a := fin_gen n' i' in\n        match a with\n        | None => None\n        | Some x => Some (FS x)\n        end\n    end.\n\n  Lemma fin_gen_S : forall n i f,\n      fin_gen n i = Some f -> fin_gen (S n) (S i) = Some (FS f).\n  Proof.\n    intros. simpl. rewrite H. auto.\n  Qed.\n\n  Lemma fin_gen_exist : forall (n ni : nat), ni < n -> exists fi, fin_gen n ni = Some fi.\n  Proof.\n    induction n. easy.\n    - induction ni; intros.\n      + simpl. exists F1. auto.\n      + assert (ni < n) by lia. apply IHn in H0. destruct H0.\n        exists (FS x). simpl. destruct (fin_gen n ni).\n        * inv H0. auto.\n        * inv H0.\n  Qed.\n  \nEnd fin_decompose.\n\nArguments fin_S {n}.\n\n(** Simplify the fin expression *)\nLtac finsimp :=\n  repeat match goal with\n  | f : fin 0 |- _ => exfalso; apply (fin_0 f)\n  | f : fin (S ?n) |- _ => pose proof fin_S f as [-> | (fi & ->)]\n  end.\n\n(** ** vec decompose *)\nSection vec_decompose.\n\n  Context {A:Type}.\n  (* Context `{Equiv_Aeq:Equivalence A Aeq}. *)\n  (* Infix \"==\" := Aeq : A_scope. *)\n  (* Print vec. *)\n  (* Print t. ? *)\n  \n  (** all vec 0 are same *)\n  Lemma vec_0 (v : @vec A 0) : v = vnil.\n  Proof.\n    refine (match v with vnil => _ end). auto.\n  Qed.\n\n  (** vec (S n) could be decomposed, exist: x:A, v':vec n *)\n  Lemma vec_S {n : nat} (v : @vec A (S n)) :\n    {x & {v' | v = vcons x v'}}.  (* sig T *)\n  Proof.\n    refine (match v with\n            | vcons x v' =>  _\n            end); eauto.\n  Qed.\n \nEnd vec_decompose.\n\nArguments vec_0 {A}.\nArguments vec_S {A n}.\n\n\n(** Simplify the vec expression *)\nLtac vsimp :=\n  repeat match goal with\n  | v : vec 0 |- _ => rewrite (vec_0 v) in *\n  | v : vec (S ?n) |- _ => pose proof vec_S v as [? [? ->]]\n  end.\n\n\n(** ** Forall2 *)\nGlobal Hint Constructors Forall2 : core.\nSection Forall2.\n\n  Lemma Forall2_cons_iff : forall {A} {P:relation A} {n} (a1 a2 : A) (v1 v2 : @vec A n),\n      Forall2 P (a1 :: v1) (a2 :: v2) <-> (P a1 a2 /\\ Forall2 P v1 v2).\n  Proof.\n    intros. split; intros.\n    - inv H. apply inj_pair2 in H2,H5. subst. auto.\n    - inv H. constructor; auto.  \n  Qed.\n\nEnd Forall2.\n\n\n(** ** Equality of vec *)\nSection veq.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := Aeq : A_scope.\n\n  Definition veq {n} (v1 v2 : @vec A n) : Prop :=\n    Forall2 Aeq v1 v2.\n  Infix \"==\" := (veq) : vector_scope.\n\n  (** veq is an equivalence relation *)\n\n  Lemma veq_refl : forall n, Reflexive (veq (n:=n)).\n  Proof.\n    unfold Reflexive.\n    intros. cbv. induction x; constructor; auto. easy.\n  Qed.\n\n  Lemma veq_sym : forall n, Symmetric (veq (n:=n)).\n  Proof.\n    unfold Symmetric.\n    unfold veq in *. induction n; intros; vsimp. easy.\n    apply Forall2_cons_iff in H as []. constructor; auto. easy.\n  Qed. \n\n  Lemma veq_trans : forall n, Transitive (veq (n:=n)).\n  Proof.\n    unfold Transitive.\n    unfold veq in *. induction n; intros; vsimp. easy.\n    apply Forall2_cons_iff in H as [], H0 as [].\n    apply Forall2_cons_iff. split.\n    rewrite H; auto. apply IHn with x3; auto.\n  Qed.\n\n  (** veq is equivalence relation *)\n  Lemma Equiv_veq : forall {n}, Equivalence (veq (n:=n)).\n  Proof.\n    constructor. apply veq_refl. apply veq_sym. apply veq_trans.\n  Qed.\n\n  Global Existing Instance Equiv_veq.\n\n  \n  (** Equality is decidable *)\n  Context {Dec_Aeq : Decidable Aeq}.\n  Lemma veq_dec : forall {n} (v1 v2 : @vec A n), {v1 == v2} + {~(v1 == v2)}.\n  Proof.\n    unfold veq in *. induction n; intros; vsimp. auto.\n    destruct (decidable x1 x), (IHn x2 x0); auto.\n    - right. intro. apply Forall2_cons_iff in H as []. easy.\n    - right. intro. apply Forall2_cons_iff in H as []. easy.\n    - right. intro. apply Forall2_cons_iff in H as []. easy.\n  Qed.\n\nEnd veq.\n\n(* Arguments veq {A} {n}. *)\nArguments veq_dec {A} _ _ {n}.\n\n\n\n(** ** vec0 *)\nSection vec0.\n\n  Context {A:Type} (A0:A).\n\n  Definition vec0 n : vec n := vconst A0 n.\n\nEnd vec0.\n(* Hint Unfold vec0 : core. *)\n\n\n(** ** Cons *)\nSection vcons.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** Method 1 : only could solving the form of \"vcons a v1 == vcons a v2\" *)\n  (* Lemma vcons_aeq_mor : forall (a : A) (n : nat), *)\n  (*     Proper (veq (Aeq:=Aeq) ==> veq (Aeq:=Aeq)) (vcons a (n:=n)). *)\n  (* Proof. *)\n  (*   unfold Proper, respectful. *)\n  (*   intros a n. induction n; intros; vsimp. easy. *)\n  (*   constructor; auto. easy. *)\n  (* Qed. *)\n\n  (** Method 2: Though method 1 is useful, but it still cannot rewrite now.\n      We can apply this lemma.\n      By the way, \"apply cons_aeq_mor\" couled be instead with \"constructor\".\n      Another purpose of this lemma, we can deal with hypothese, meanwhile,\n      the \"constructor\" tactic can not do it. *)\n  Lemma vcons_aeq_mor : forall (n:nat),\n      Proper (Aeq ==> veq (Aeq:=Aeq) (n:=n) ==> veq (Aeq:=Aeq) (n:=S n))\n        (fun (a:A) (v:vec n) => vcons a v).\n  Proof.\n    unfold Proper, respectful.\n    intros n x y H v1 v2. revert v1 v2.\n    induction n; intros; vsimp; constructor; auto.\n  Qed.\n\n  (** This is not useful yet, even we declare the instance. *)\n  Global Existing Instance vcons_aeq_mor.\n\n  (** a1 == a2 -> a1 :: v == a2 :: v *)\n  Lemma vcons_aeq_mor_part1 : forall (n : nat) (v : vec n),\n      Proper (Aeq ==> veq (Aeq:=Aeq)(n:=S n)) (fun a => vcons a v).\n  Proof.\n    unfold Proper, respectful.\n    intros. unfold veq in *. constructor; auto. f_equiv.\n  Qed.\n\n  (** This is not useful yet. *)\n  Global Existing Instance vcons_aeq_mor_part1.\n\n  (** v1 == v2 -> a :: v1 == a :: v2 *)\n  Lemma vcons_aeq_mor_part2 : forall (a : A) (n : nat),\n      Proper (veq (Aeq:=Aeq)(n:=n) ==> veq (Aeq:=Aeq)(n:=S n)) (vcons a (n:=n)).\n  Proof.\n    unfold Proper, respectful.\n    intros. unfold veq in *. constructor; auto. easy.\n  Qed.\n\n  Global Existing Instance vcons_aeq_mor_part2.\n\n  (** Equality of cons, iff both parts are equal *)\n  Lemma vcons_eq_iff : forall n (a1 a2 : A) (v1 v2 : @vec A n),\n      a1 :: v1 == a2 :: v2 <-> (a1 == a2)%A /\\ v1 == v2.\n  Proof.\n    intros. split; intros H.\n    - inv H. apply inj_pair2 in H2,H5. subst. easy.\n    - constructor; easy.\n  Qed.\n\n  (** Inequality of cons, iff at least one parts are not equal *)\n  Lemma vcons_neq_iff : forall n (a1 a2 : A) (v1 v2 : @vec A n),\n      ~(a1 :: v1 == a2 :: v2) <-> (~(a1 == a2)%A \\/ ~(v1 == v2)).\n  Proof.\n    intros n. destruct n; intros; split; intros; vsimp;\n      rewrite ?vcons_eq_iff in *.\n    - apply not_and_or; auto.\n    - apply or_not_and; auto.\n    - apply not_and_or in H. destruct H; auto.\n    - apply or_not_and. destruct H; auto.\n  Qed.\n\nEnd vcons.\n\n(** Properties for vhd and vtl *)\nSection vhd_vtl.\n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0:A}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** hd is a proper morphism *)\n  Lemma vhd_aeq_mor : forall n, Proper (veq (Aeq:=Aeq)(n:=S n) ==> Aeq) (vhd (n:=n)).\n  Proof.\n    unfold Proper, respectful.\n    induction n; intros; vsimp; simpl; apply vcons_eq_iff in H as []; auto.\n  Qed.\n  Global Existing Instance vhd_aeq_mor.\n\n  (** tl is a proper morphism *)\n  Lemma vtl_aeq_mor : forall n,\n      Proper (veq (Aeq:=Aeq)(n:=S n) ==> veq (Aeq:=Aeq)(n:=n)) (vtl (n:=n)).\n  Proof.\n    unfold Proper, respectful.\n    induction n; intros; vsimp; simpl; apply vcons_eq_iff in H as []; auto.\n  Qed.\n  Global Existing Instance vtl_aeq_mor.\n\nEnd vhd_vtl.\n\n\n(** ** Get n-th element with index of fin type *)\nSection vnth.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0:A}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  Lemma vnth_aeq_mor : forall n, Proper (veq (Aeq:=Aeq) (n:=n) ==> eq ==> Aeq) vnth.\n  Proof.\n    unfold Proper, respectful.\n    induction n; intros v1 v2 H fi fj; vsimp. finsimp.\n    apply vcons_eq_iff in H as [].\n    intros. subst. finsimp; simpl; auto.\n  Qed.\n\n  Global Existing Instance vnth_aeq_mor.\n\n  Lemma veq_iff_nth : forall {n} (v1 v2 : @vec A n),\n      v1 == v2 <->\n      (forall f1 f2 : fin n, f1 = f2 -> (vnth v1 f1 == vnth v2 f2)%A).\n  Proof.\n    induction n; intros; split; intros; vsimp; subst; try easy; try finsimp; simpl.\n    - apply vcons_eq_iff in H as []; auto.\n    - apply vcons_eq_iff in H as []; auto. apply IHn; auto.\n    - constructor.\n      + specialize (H F1 F1 eq_refl). simpl in H. auto.\n      + apply IHn. intros. subst. specialize (H (FS f2) (FS f2) eq_refl).\n        simpl in H. auto.\n  Qed. \n\n  Lemma vnth_head : forall n (v : @vec A (S n)), (vhd v == vnth v F1)%A.\n  Proof.\n    intros. vsimp. simpl. easy.\n  Qed.\n\n  Lemma vnth_tail : forall n (v : @vec A (S n)) (fn : fin n),\n    (vnth (vtl v) fn == vnth v (FS fn))%A.\n  Proof.\n    intros. vsimp. simpl. easy.\n  Qed.\n  \n  Lemma vnth_nil : forall (fn : fin 0), vnth vnil fn -> False.\n  Proof.\n    intros. finsimp.\n  Qed.\n\nEnd vnth.\n\n\n(** Get i-th element with index of nat type *)\nSection vnthNat.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0:A}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** Get i-th element of a vector *)  \n  Definition vnthNat {n} (v : vec n) (i : nat) :=\n    match (fin_gen n i) with\n    | Some fi => vnth v fi\n    | _ => A0\n    end.\n\n  (** vnthNat is a proper morphism *)\n  Lemma vnthNat_aeq_mor : forall (n:nat),\n      Proper (veq (Aeq:=Aeq)(n:=n) ==> eq ==> Aeq) vnthNat.\n  Proof.\n    unfold Proper, respectful, vnthNat.\n    induction n; intros; subst. easy.\n    destruct (fin_gen (S n) y0); try easy.\n    rewrite H. easy.\n  Qed.\n  \n  Lemma vnthNat_cons : forall n a (v : vec n) i,\n      (vnthNat (vcons a v) (S i) == vnthNat v i)%A.\n  Proof.\n    unfold vnthNat.\n    induction n; intros; vsimp; simpl. easy.\n    destruct i; simpl. easy.\n    destruct (fin_gen n i); try easy.\n  Qed.\n  \n  (** veq and vnthNat should satisfy this constraint *)\n  Lemma veq_iff_vnthNat : forall {n : nat} (v1 v2 : vec n),\n      v1 == v2 <-> (forall i, i < n -> (vnthNat v1 i == vnthNat v2 i)%A).\n  Proof.\n    induction n; intros; split; intros; try lia; vsimp; try easy.\n    - apply vcons_eq_iff in H as [].\n      apply vnthNat_aeq_mor; auto. apply vcons_eq_iff; split; auto.\n    - apply vcons_eq_iff; split.\n      + specialize (H 0 (Nat.lt_0_succ n)).\n        unfold vnthNat in H; simpl in H. easy.\n      + apply IHn. intros.\n        assert (S i < S n) by lia.\n        apply H in H1. rewrite ?vnthNat_cons in H1. auto.\n  Qed.\n\n  (** vnthNat is equivalent to vnth *)\n  Lemma vnthNat_eq_vnth : forall {n : nat} (v1 v2 : vec n),\n      (forall i : nat, i < n -> (vnthNat v1 i == vnthNat v2 i)%A) <->\n        (forall (fi : fin n), (vnth v1 fi == vnth v2 fi)%A).\n  Proof.\n    intros. split; intros.\n    - apply veq_iff_nth; auto. apply veq_iff_vnthNat. auto.\n    - apply veq_iff_vnthNat; auto. apply veq_iff_nth.\n      intros. subst. auto.\n  Qed.\n\nEnd vnthNat.\n\n(** ** vmap *)\nSection vmap.\n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n  \n  Lemma vmap_cons : forall n a (v : vec n) (f : A -> A), \n    vmap f (a :: v) == (f a) :: (vmap f v).\n  Proof.\n    intros. simpl. easy.\n  Qed.\n\nEnd vmap.\n\n\n(** ** vmap2 *)\nSection vmap2.\n  \n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  Lemma vmap2_cons : forall n a1 a2 (v1 v2 : vec n) (f : A -> A -> A), \n    vmap2 f (a1 :: v1) (a2 :: v2) == (f a1 a2) :: (vmap2 f v1 v2).\n  Proof.\n    intros. simpl. easy.\n  Qed.\n\n  (** vmap2 is respect veq *)\n  Context (Aadd : A -> A -> A).\n  Context {AaddProper : Proper (Aeq ==> Aeq ==> Aeq) Aadd}.\n  Lemma vmap2_aeq_mor : forall n,\n      Proper (veq (Aeq:=Aeq) ==> veq (Aeq:=Aeq) ==> veq (Aeq:=Aeq)) (vmap2 Aadd (n:=n)).\n  Proof.\n    unfold Proper, respectful.\n    induction n; intros v1 v2 H12 v3 v4 H34; vsimp. easy.\n    simpl. rewrite vcons_eq_iff in *. destruct H12,H34. split.\n    - apply AaddProper; auto.\n    - apply IHn; auto.\n  Qed.\n\n  Global Existing Instance vmap2_aeq_mor.\n\n  Context {Comm_Aadd : Commutative Aadd Aeq}.\n  Lemma vmap2_comm : forall n (v1 v2 : @vec A n),\n    vmap2 Aadd v1 v2 == vmap2 Aadd v2 v1.\n  Proof.\n    induction n; intros; simpl; vsimp. easy.\n    simpl. rewrite vcons_eq_iff; split; auto. apply commutative.\n  Qed.\n  \nEnd vmap2.\n\n\n(** ** Build vector with a function *)\nSection vmake.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0:A}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** Build vector with a function [gen: fin n -> A] *)\n  Fixpoint vmake {n} : (fin n -> A) -> vec n :=\n    match n with\n    | O => fun _ => []\n    | S n' => fun (gen : fin (S n') -> A) =>\n       (gen F1) :: (vmake (fun (fn':fin n') => gen (FS fn'))) \n    end.\n    \n  (** nth element of a vector generated by vmake, equal to [gen i] *)\n  Lemma vmake_nth : forall n gen (fn : fin n), (nth (vmake gen) fn == gen fn)%A.\n  Proof.\n    induction n; intros gen fn.\n    - finsimp.\n    - finsimp; simpl. easy. apply IHn.\n  Qed.\n  \n  (** head element of a vector generated by vmake, equal to [gen F1] *)\n  Lemma vmake_head : forall n (gen : fin (S n) -> A) ,\n    (vhd (vmake gen) == gen F1)%A.\n  Proof.\n    intros. rewrite vnth_head, vmake_nth. easy.\n  Qed.\n  \n  (** tail element of a vector generated by vmake, equal to a vector with \n    generated by vmake with the next position. eg, tail [1;2;3;4] = [2;3;4] *)\n  Lemma vmake_tail n (gen : fin (S n) -> A) :\n    vtl (vmake gen) == vmake (fun (fn : fin n) => gen (FS fn)).\n  Proof.\n    apply veq_iff_nth. intros; subst. rewrite vnth_tail, !vmake_nth. easy.\n  Qed.\n\n  (** A vector build with A0 equal to vec0 *)\n  Lemma vmake_0_eq_vec0 : forall n, vmake (fun _ : fin n => A0) == vec0 A0 n.\n  Proof.\n    intros. apply veq_iff_nth. intros ? p ->. rewrite vmake_nth, const_nth. easy.\n  Qed.\n\n  (** vmap2 f {gen} v = vmake {f (gen[i]) v[i]} *)\n  Lemma vmap2_vmake_l : forall (f : A -> A -> A) n gen (v : vec n),\n    vmap2 f (vmake (fun fn : fin n => gen fn)) v == \n    vmake (fun fn : fin n => f (gen fn) (vnth v fn)).\n  Proof.\n    intros f n. induction n; intros; vsimp; simpl. easy.\n    apply vcons_eq_iff; split; auto. easy.\n  Qed.\n\n  (* vmap2 f v {gen} = vmake {f v[i] (gen[i])} *)\n  Lemma vmap2_vmake_r : forall (f : A -> A -> A) n gen (v : vec n),\n    vmap2 f v (vmake (fun fn : fin n => gen fn)) == \n    vmake (fun fn : fin n => f (vnth v fn) (gen fn)).\n  Proof.\n    intros f n. induction n; intros; vsimp; simpl. easy.\n    apply vcons_eq_iff; split; auto. easy.\n  Qed.\n\nEnd vmake.\n\nArguments vmake {A n}.\nArguments vmake_nth {A Aeq} _ {n}.\n(* Arguments vmake_0_eq_vconst_0 {A}. *)\nArguments vmake_0_eq_vec0 {A}.\n\n\nSection vmake_vec_vec.\n  \n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := (veq (Aeq:=veq (Aeq:=Aeq))) : vector_scope.\n\n  (** If a matrix have r rows and its elements are vnil, then it is equal to vec0 *)\n  Lemma vmake_nil_eq_vec0 : forall r, \n      vmake (fun _ : fin r => @vnil A) == vec0 vnil r.\n  Proof.\n    intros. \n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    rewrite const_nth; easy. apply Equiv_veq.\n  Qed.\n\nEnd vmake_vec_vec.\n\n(* Arguments vmake_nil_eq_vconstnil {A}. *)\nArguments vmake_nil_eq_vec0 {A}.\n\n\n(** Extensional propertity of vmake *)\nSection vmake_ext.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** vmake extensional equality *)\n  Lemma vmake_ext : forall n (f g : fin n -> A),\n      (forall (fi : fin n), (f fi == g fi)%A) -> (vmake f == vmake g)%vector.\n  Proof.\n    induction n; simpl; intros. easy.\n    apply vcons_eq_iff; split; auto.\n  Qed.\n\nEnd vmake_ext.\n\n\n(** ** Properties of vfold on element with basic structure *)\n\nSection vfold_props_basic.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** extensional equality of vfoldl *)\n  Lemma vfoldl_ext : forall {n} f1 f2 (a1 a2 : A) (v1 v2 : vec n),\n      (forall (a1 a2 b1 b2 : A), (a1 == a2 -> b1 == b2 -> f1 a1 b1 == f2 a2 b2)%A) ->\n      (a1 == a2)%A ->\n      (v1 == v2) ->\n      (vfoldl f1 a1 v1 == vfoldl f2 a2 v2)%A.\n  Proof.\n    induction n; intros; vsimp; simpl in *; auto.\n    apply vcons_eq_iff in H1 as []; auto.\n  Qed.\n\n  (** extensional equality of vfoldl, with same function *)\n  Lemma vfoldl_ext_samef : forall {n} f (a1 a2 : A) (v1 v2 : vec n),\n      (Proper (Aeq ==> Aeq ==> Aeq) f) ->\n      (a1 == a2)%A ->\n      (v1 == v2) ->\n      (vfoldl f a1 v1 == vfoldl f a2 v2)%A.\n  Proof. intros. apply vfoldl_ext; try easy. intros. apply H; auto. Qed.\n\n  (** extensional equality of vfoldr *)\n  Lemma vfoldr_ext : forall {n} f1 f2 (a1 a2 : A) (v1 v2 : vec n),\n      (forall (a1 a2 b1 b2 : A), (a1 == a2 -> b1 == b2 -> f1 a1 b1 == f2 a2 b2)%A) ->\n      (a1 == a2)%A ->\n      v1 == v2 ->\n      (vfoldr f1 v1 a1 == vfoldr f2 v2 a2)%A.\n  Proof.\n    induction n; intros; vsimp; simpl in *; auto.\n    apply vcons_eq_iff in H1 as []; auto.\n  Qed.\n\n  (** extensional equality of vfoldr, with same function *)\n  Lemma vfoldr_ext_samef : forall {n} f (a1 a2 : A) (v1 v2 : vec n),\n      (Proper (Aeq ==> Aeq ==> Aeq) f) ->\n      (a1 == a2)%A ->\n      v1 == v2 ->\n      (vfoldr f v1 a1 == vfoldr f v2 a2)%A.\n  Proof.\n    intros. apply vfoldr_ext; try easy. intros. apply H; auto.\n  Qed.\n\nEnd vfold_props_basic.\n\n\n(** ** Properties of vfold on element with more strict structure. *)\nSection vfold_props_advanced.\n\n  (** *** Properties on Monoid *)\n  Context `{M:Monoid}.\n  Infix \"+\" := Aadd : A_scope.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** vfoldl (a + b) v = a + (vfoldl b v) *)\n  Lemma vfoldl_Aadd : forall n (a b : A) (v : @vec A n),\n    (vfoldl Aadd (a + b) v == a + (vfoldl Aadd b v))%A.\n  Proof.\n    induction n; intros; vsimp; simpl in *. easy.\n    rewrite IHn. rewrite associative. f_equiv. easy.\n  Qed.\n\n  (** vfoldl a vec0 = a *)\n  Lemma vfoldl_vec0 : forall n (a : A), (vfoldl Aadd a (vec0 A0 n) == a)%A.\n  Proof.\n    intros. induction n; simpl. easy.\n    rewrite vfoldl_ext_samef with (a2:=a) (v2:=vec0 A0 n); try easy.\n    apply monoidAaddProper. monoid_simpl.\n  Qed.\n\n  (** *** Properties on AMonoid *)\n  Context `{AM:AMonoid A Aadd A0 Aeq}.\n  (* Context `{AG:AGroup}. *)\n  (* Variable A : Type. *)\n  (* Variable A0 : A. *)\n  (* Variable fadd : A -> A -> A. *)\n  (* Variable fadd_comm : forall x y, fadd x y = fadd y x. *)\n  (* Variable fadd_assoc : forall x y z, fadd (fadd x y) z = fadd x (fadd y z). *)\n  (* Variable fadd_0_r : forall x, fadd x A0 = x. *)\n\n  (** vfoldr v (a + b) v = a + (vfoldr b v) *)\n  Lemma vfoldr_Aadd : forall n (a b : A) (v : @vec A n),\n    (vfoldr Aadd v (a + b) == a + (vfoldr Aadd v b))%A.\n  Proof.\n    induction n; intros; vsimp. simpl. easy.\n    simpl. rewrite <- IHn.\n    rewrite vfoldr_ext_samef with (a2:=a+(x+b)) (v2:=x0); try easy.\n    - rewrite ?IHn. easy.\n    - apply monoidAaddProper.\n    - rewrite <- ?associative. f_equiv. apply commutative. \n  Qed.\n\n  (** vfoldr vec0 a = a *)\n  Lemma vfoldr_vec0 : forall n (a : A), (vfoldr Aadd (vec0 A0 n) a == a)%A.\n  Proof.\n    intros. induction n; simpl. easy. monoid_simpl.\n  Qed.\n  \n  (** foldl a0 v = foldr a0 v*)\n  Lemma vfoldl_eq_vfoldr : forall {n} (a : A) (v : @vec A n), \n    (vfoldl Aadd a v == vfoldr Aadd v a)%A.\n  Proof.\n    induction n; intros; vsimp; simpl in *. easy.\n    rewrite vfoldl_ext with (f2:=Aadd) (a2:=x+a) (v2:=x0); try easy.\n    - rewrite vfoldl_Aadd. f_equiv; auto.\n    - intros. rewrite H,H0; easy.\n    - apply commutative. \n  Qed.\n  \nEnd vfold_props_advanced.\n\nNotation vfold := vfoldl.\nArguments vfoldl_Aadd {A}.\n\n\n(** get / set an element of a vector *)\nSection vget_vset.\n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0:A}.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  Fixpoint vget {n} (v:vec n) (i:nat) : A :=\n    match v, i with\n    | [], _ => A0\n    | a :: v', 0 => a\n    | a :: v', S i' => vget v' i'\n    end.\n\n  (** Note, this is not tail recursion *)\n  Fixpoint vset {n} (v:vec n) (i:nat) (x:A) : vec n :=\n    match v, i with\n    | [], _ => []\n    | a :: v', 0 => x :: v'\n    | a :: v', S i' => a :: (vset v' i' x)\n    end.\n\nEnd vget_vset.\n\n\n(** ** Arithmatic of vector *)\n\n(** Addition, Opposition, Subtraction of vectors *)\nSection varith.\n\n  (* Variable A : Type. *)\n  (* Variable A0 A1 : A. *)\n  (* Variable fopp : A -> A. *)\n  (* Variable fadd : A -> A -> A. *)\n  (* Variable fadd_comm : forall x y, fadd x y = fadd y x. *)\n  (* Variable fadd_assoc : forall x y z, fadd (fadd x y) z = fadd x (fadd y z). *)\n  (* Variable fadd_0_l : forall x, fadd A0 x = x. *)\n  (* Variable fadd_0_r : forall x, fadd x A0 = x. *)\n\n  Context `{G:AGroup}.\n  Infix \"+\" := Aadd : A_scope.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** *** Properties of vfold *)\n  \n  (** vfold (a + b) v = a + (fold b v) *)\n  Lemma vfold_Aadd : forall n a b (v : @vec A n),\n    (vfold Aadd (a + b) v == a + (vfold Aadd b v))%A.\n  Proof.\n    apply (vfoldl_Aadd _ A0). apply groupMonoid.\n  Qed.\n  \n  (** vfold (a + b) v = b + (fold a v) *)\n  Lemma vfold_Aadd_rev : forall n a b (v : @vec A n),\n    (vfold Aadd (a + b) v == b + (vfold Aadd a v))%A.\n  Proof.\n    intros. rewrite vfoldl_ext with (f2:=Aadd) (a2:=(b+a)%A) (v2:=v);\n      try easy; try apply commutative.\n    apply vfold_Aadd.\n    intros. f_equiv; auto.\n  Qed.\n  \n  (** vfold a (b::v) = vfold (a + b) v *)\n  Lemma vfold_cons : forall n (a b : A) (v : @vec A n),\n    (vfold Aadd a (b :: v) == vfold Aadd (a + b) v)%A.\n  Proof.\n    intros. simpl. easy.\n  Qed.\n  \n  (** vfold a (b::v) = a + (vfold b v) *)\n  Lemma vfold_cons_eq_add : forall n (a b : A) (v : @vec A n),\n    (vfold Aadd a (b :: v) == a + (vfold Aadd b v))%A.\n  Proof.\n    intros. simpl. rewrite vfold_Aadd. easy.\n  Qed.\n  \n  (* vfold a (b::v) = b + (vfold a v) *)\n  Lemma vfold_cons_eq_add_rev : forall n (a b : A) (v : @vec A n),\n    (vfold Aadd a (b :: v) == b + (vfold Aadd a v))%A.\n  Proof.\n    intros. simpl. rewrite vfold_Aadd_rev. easy.\n  Qed.\n\n  (** vfold a vec0 = a *)\n  Lemma vfold_vec0 : forall n (a : A), (vfold Aadd a (vec0 A0 n) == a)%A.\n  Proof.\n    apply vfoldl_vec0.\n  Qed.\n\n  (** vfold (a + b) (vmap2 f v1 v2) = f (vfold a v1) (vfold b v2) *)\n  Lemma vfold_Aadd_vmap2 : forall n a b (v1 v2 : @vec A n),\n    (vfold Aadd (a + b) (vmap2 Aadd v1 v2) == (vfold Aadd a v1) + (vfold Aadd b v2))%A.\n  Proof.\n    induction n; intros; vsimp; simpl. easy.\n    rewrite <- IHn. apply vfoldl_ext; try easy.\n    intros; f_equiv; easy.\n    rewrite ?associative; f_equiv.\n    rewrite <- ?associative; f_equiv. apply commutative.\n  Qed.\n  \n  (** vfold a (vmap2 f v1 v2) = f (vfold a v1) (vfold A0 v2) *)\n  Lemma vfold_vmap2_eq_left : forall n (a : A) (v1 v2 : @vec A n),\n    (vfold Aadd a (vmap2 Aadd v1 v2) == (vfold Aadd a v1) + (vfold Aadd A0 v2))%A.\n  Proof.\n    intros. rewrite <- vfold_Aadd_vmap2. apply vfoldl_ext; try easy.\n    intros; f_equiv; easy. monoid_simpl.\n  Qed.\n\n  (** vfold a (vmap2 f v1 v2) = f (vfold A0 v1) (vfold a v2) *)\n  Lemma vfold_vmap2_eq_right : forall n (a : A) (v1 v2 : @vec A n),\n    (vfold Aadd a (vmap2 Aadd v1 v2) == (vfold Aadd A0 v1) + (vfold Aadd a v2))%A.\n  Proof.\n    intros. rewrite <- vfold_Aadd_vmap2. apply vfoldl_ext; try easy.\n    intros; f_equiv; easy. monoid_simpl.\n  Qed.\n\n  (** *** Addition, opposition, subtraction of vector *)\n  \n  (** Addition of vectors *)\n  Definition vadd {n} (v1 v2 : vec n) := map2 Aadd v1 v2.\n  Infix \"+\" := vadd : vector_scope.\n\n  (** vadd is proper morphism *)\n  Lemma vadd_aeq_mor : forall n,\n      let r := veq (Aeq:=Aeq) (n:=n) in Proper (r ==> r ==> r) vadd.\n  Proof.\n    unfold Proper, respectful.\n    induction n; intros v1 v2 H12 v3 v4 H34; vsimp; simpl. easy.\n    apply vcons_eq_iff in H12 as [], H34 as [].\n    apply vcons_eq_iff; split; auto. rewrite H,H1. easy.\n  Qed.\n\n  Global Existing Instance vadd_aeq_mor.\n\n  (** Opposition of vector *)\n  Definition vopp {n} (v : vec n) := map Aopp v.\n  Notation \"- v\" := (vopp v) : vector_scope.\n  \n  (** vopp is proper morphism *)\n  Lemma vopp_aeq_mor : forall n,\n      let r := veq (Aeq:=Aeq) (n:=n) in Proper (r ==> r) vopp.\n  Proof.\n    unfold Proper, respectful.\n    induction n; intros v1 v2 H12; vsimp; simpl. easy.\n    apply vcons_eq_iff in H12 as [].\n    apply vcons_eq_iff; split; auto. rewrite H. easy.\n  Qed.\n\n  Global Existing Instance vopp_aeq_mor.\n\n  \n  (** v1 + v2 = v2 + v1 *)\n  Lemma vadd_comm (n : nat) (v1 v2 : vec n) : v1 + v2 == v2 + v1.\n  Proof.\n    unfold vadd.\n    apply veq_iff_nth; intros; subst.\n    (* nth_map2: vnth (map2 f v1 v2) p1 = f (nth v1 p) (nth v2 p) *)\n    rewrite ?nth_map2 with (p2:=f2) (p3:=f2); auto. apply commutative.\n  Qed.\n  \n  (** (v1 + v2) + v3 = v1 + (v2 + v3) *)\n  Lemma vadd_assoc (n : nat) (v1 v2 v3 : vec n) : (v1 + v2) + v3 == v1 + (v2 + v3).\n  Proof.\n    unfold vadd.\n    apply veq_iff_nth; intros; subst.\n    rewrite ?nth_map2 with (p2:=f2) (p3:=f2); auto.\n    rewrite associative. easy.\n  Qed.\n  \n  (* (** [] + v = v *) *)\n  (* Lemma vadd_nil_l : forall (v : vec 0), vnil + v == v. *)\n  (* Proof. intros. rewrite (vec_0 v). simpl. easy. Qed. *)\n\n  (* (** v + [] = v *) *)\n  (* Lemma vadd_nil_r : forall (v : vec 0), v + vnil == v. *)\n  (* Proof. intros. rewrite (vec_0 v). simpl. easy. Qed. *)\n  \n  (** vec0 + v = v *)\n  Lemma vadd_vec0_l : forall {n} (v : vec n), (vec0 A0 n) + v == v.\n  Proof.\n    induction n; intros; vsimp; simpl. easy.\n    apply vcons_eq_iff; split; auto. monoid_simpl.\n  Qed.\n\n  (** v + vec0 = v *)\n  Lemma vadd_vec0_r : forall {n} (v : vec n), v + (vec0 A0 n) == v.\n  Proof.\n    induction n; intros; vsimp; simpl. easy.\n    apply vcons_eq_iff; split; auto. monoid_simpl.\n  Qed.\n\n  (** (-v) + v = vec0 *)\n  Lemma vadd_vopp_l : forall {n} (v : vec n), (-v) + v == vec0 A0 n.\n  Proof.\n    induction n; intros; vsimp; simpl. easy.\n    apply vcons_eq_iff; split; auto. group_simpl.\n  Qed.\n\n  (** v + (-v) = vec0 *)\n  Lemma vadd_vopp_r : forall {n} (v : vec n), v + (-v) == vec0 A0 n.\n  Proof.\n    induction n; intros; vsimp; simpl. easy.\n    apply vcons_eq_iff; split; auto. group_simpl.\n  Qed.\n  \n  \n  (** (v1 + v2)[n] = v1[n] + v2[n] *)\n  Lemma vadd_nth : forall n (v1 v2 : @vec A n) (fn : fin n),\n    (vnth (v1 + v2)%vector fn == (vnth v1 fn) + (vnth v2 fn))%A.\n  Proof. \n    intros. unfold vadd.\n    rewrite nth_map2 with (p2:=fn) (p3:=fn); auto. easy.\n  Qed.\n  \n  (** (vmake gen1) + (vmake gen2) = vmake (gen1 + gen2) *)\n  Lemma vadd_vmake_vmake : forall n gen1 gen2,\n    (vmake gen1) + (vmake gen2) ==\n    vmake (fun fn : fin n => ((gen1 fn) + (gen2 fn))%A).\n  Proof.\n    induction n; intros; simpl. easy. apply vcons_eq_iff; split; auto. easy.\n  Qed.\n\n  (** vfold (a + b) (v1 + v2) = (vfold a v1) + (vfold b v2) *)\n  Lemma vfold_vadd : forall n (a b : A) (v1 v2 : @vec A n),\n    (vfold Aadd (a + b) (v1 + v2)%vector == (vfold Aadd a v1) + (vfold Aadd b v2))%A.\n  Proof.\n    induction n; intros; vsimp; simpl. easy.\n    rewrite vfoldl_ext with (f2:=Aadd) (a2:=((a+x1)+(b+x))%A) (v2:=x2+x0); try easy.\n    intros; f_equiv; auto.\n    rewrite ?associative; f_equiv.\n    rewrite <- ?associative; f_equiv. apply commutative.\n  Qed.\n  \nEnd varith.\n\nArguments vopp {A} Aopp {n}.\nArguments vadd {A} Aadd {n}.\nArguments vfold_vec0 {A}.\n\n\n(* =============================================================== *)\n(** ** (vec, vadd, vopp, veq) is a AGroup *)\nSection vec_AG.\n\n  Context `{G:AGroup}.\n  Infix \"+\" := Aadd : A_scope.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  Lemma vec_AG : forall n, @AGroup (vec n) (vadd Aadd) (vconst A0 n) (vopp Aopp)\n                    (veq (Aeq:=Aeq)).\n  Proof.\n    induction n; repeat constructor; intros\n    ; try (apply vadd_aeq_mor; easy)\n    ; try (apply vopp_aeq_mor; easy)\n    ; try apply Equiv_veq\n    ; try (rewrite vadd_assoc; easy)\n    ; try apply vadd_comm\n    ; try (rewrite vadd_vec0_l; easy)\n    ; try (rewrite vadd_vec0_r; easy)\n    ; try (rewrite vadd_vopp_l; easy)\n    ; try (rewrite vadd_vopp_r; easy)\n    .\n  Qed.\n  \n  Global Existing Instance vec_AG.\n\nEnd vec_AG.\n\n\n(* =============================================================== *)\n(** ** sum of vector *)\nSection vsum.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Context (A0:A) (Aadd : A -> A -> A). \n\n  Definition vsum {n} (v : @vec A n) := vfold Aadd A0 v.\n  \nEnd vsum.\n\n\n(** ** Matrix Definitions *)\n\nSection MatrixDefinition.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0:A}.\n  Infix \"==\" := Aeq : A_scope.\n\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (** Definition of matrix with r rows and c colums  *)\n  Definition mat r c := @vec (@vec A c) r.\n  \n  (** *** Matrix equality *)\n  \n  (** Definition of matrix equality *)\n  Definition meq {r c} (m1 m2 : mat r c) : Prop := veq (Aeq:=veq (Aeq:=Aeq)) m1 m2.\n  Infix \"==\" := meq : mat_scope.\n    \n  (** meq is a equivalence relation *)\n  Lemma meq_equiv : forall {r c : nat}, Equivalence (meq (r:=r) (c:=c)).\n  Proof.\n    intros. apply Equiv_veq.\n  Defined.\n\n  Global Existing Instance meq_equiv.\n\n  (** meq is decidable *)\n  Context (Dec_Aeq : Decidable Aeq).\n  Lemma meq_dec : forall {r c}, Decidable (meq (r:=r) (c:=c)).\n  Proof.\n    intros. constructor. intros. apply veq_dec.\n    constructor. apply veq_dec. auto.\n  Qed.\n\n  \n  (** *** Get element *)\n\n  (** Get an element *)\n  Definition mnth {r c} (m : mat r c) (fr : fin r) (fc : fin c) := \n    vnth (vnth m fr) fc.\n\n  (** mnth is a proper morphism *)\n  Lemma mnth_aeq_mor : forall r c,\n      Proper (meq (r:=r)(c:=c) ==> eq ==> eq ==> Aeq) mnth.\n  Proof.\n    unfold Proper, respectful.\n    intros. subst. unfold mnth,meq in *. rewrite H. easy.\n  Qed.\n\n  Global Existing Instance mnth_aeq_mor.\n\n  (** Two matrices are equal, iff its corresponding elements are equal *)\n  Lemma meq_iff_nth : forall r c (m n : mat r c), \n      m == n <->\n        (forall (fr : fin r) (fc : fin c), (mnth m fr fc == mnth n fr fc)%A).\n  Proof.\n    unfold mnth, mat, meq.\n    intros; split; intros.\n    - rewrite H. easy.\n    - apply veq_iff_nth; intros; subst.\n      apply veq_iff_nth; intros; subst. auto.\n  Qed.\n\n  (** mnth implemented with index of natural number *)\n  Section mnthNat.\n    \n    (** Get n-th element of a matrix *)  \n    Definition mnthNat {r c} (m : mat r c) (ri ci : nat) :=\n      vnthNat (vnthNat m ri (A0:=vec0 A0 c)) ci (A0:=A0).\n    \n    (** meq and mnthNat should satisfy this constraint *)\n    Lemma meq_iff_mnthNat : forall {r c : nat} (m1 m2 : mat r c),\n        m1 == m2 <->\n          (forall ri ci, ri < r -> ci < c -> (mnthNat m1 ri ci == mnthNat m2 ri ci)%A).\n    Proof.\n      intros. split; intros.\n      - apply veq_iff_vnthNat; auto.\n        apply (veq_iff_vnthNat (A0:=vec0 A0 c)); auto.\n      - apply (veq_iff_vnthNat (A0:=vec0 A0 c)).\n        intros. specialize (H i).\n        unfold mnthNat in H.\n        assert (forall ci, ci < c ->\n                      (vnthNat (vnthNat m1 i (A0:=vec0 A0 c)) ci (A0:=A0) ==\n                         vnthNat (vnthNat m2 i (A0:=vec0 A0 c)) ci (A0:=A0))%A).\n        { intros. apply H; auto. }\n        apply (veq_iff_vnthNat) in H1. auto.\n    Qed.\n\n    (** mnthNat is equivalent to mnth *)\n    Lemma mnthNat_eq_mnth : forall {r c : nat} (m1 m2 : mat r c),\n        (forall ri ci : nat, ri < r -> ci < c ->\n                      (mnthNat m1 ri ci == mnthNat m2 ri ci)%A) <->\n          (forall (fr : fin r) (fc : fin c), (mnth m1 fr fc == mnth m2 fr fc)%A).\n    Proof.\n      intros. split; intros.\n      - apply meq_iff_nth. apply meq_iff_mnthNat. auto.\n      - apply meq_iff_mnthNat; auto. apply meq_iff_nth. auto.\n    Qed.\n\n  End mnthNat.\n\n  (** (mmake f)[i,j] = f(i,j) *)\n  Lemma mnth_gen_iff : forall {r c} fr fc (gen : fin r -> fin c -> A),\n    (mnth (vmake (fun fr0 : fin r => vmake (fun fc0 : fin c => gen fr0 fc0))) \n      fr fc == gen fr fc)%A.\n  Proof.\n    intros. unfold mnth. rewrite vmake_nth; auto. rewrite vmake_nth; auto. easy.\n    apply Equiv_veq.\n  Qed.\n\n  (** get / set an element of a matrix *)\n  Definition mget {r c} (m:mat r c) (i j:nat) : A :=\n    vget (A0:=A0) (vget (A0:=vec0 A0 c) m i) j.\n  Definition mset {r c} (m:mat r c) (i j : nat) (x:A) : mat r c :=\n    @vset _ r m i (@vset _ c (@vget _ (vec0 A0 c) _ m i) j x).\n  \nEnd MatrixDefinition.\n\n(* Arguments mat {A}. *)\n(* (* Arguments meq {A r c}. *) *)\n(* Arguments mrow {A r c}. *)\n(* Arguments mcol {A r c}. *)\n(* Arguments mnth {A r c}. *)\n(* Arguments mget {A} A0 {r c}. *)\n(* Arguments mset {A} A0 {r c}. *)\n\n\n\n(** ** sum of matrix *)\nSection msum.\n\n  (* Context `{Equiv_Aeq : Equivalence A Aeq}. *)\n  (* Context (A0:A) (Aadd : A -> A -> A).  *)\n  Context `{G:AGroup}.\n  Infix \"+\" := Aadd : A_scope.\n  Infix \"==\" := Aeq : A_scope.\n\n  Infix \"+\" := (vadd Aadd) : vector_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  (* Variable A : Type. *)\n  (* Variable A0 : A. *)\n  (* Variable fadd : A -> A -> A. *)\n  (* Variable fadd_comm : forall x y, fadd x y = fadd y x. *)\n  (* Variable fadd_assoc : forall x y z, fadd (fadd x y) z = fadd x (fadd y z). *)\n  (* Variable fadd_0_r : forall x, fadd x A0 = x. *)\n  \n  (** Sum of a matrix: sum the result of sums of every row *)\n  Definition msum {r c} (m : @mat A r c) : A :=\n    vsum A0 Aadd (vsum (vec0 A0 c) (fun v1 v2 => v1 + v2) m).\n  \n  (** Sum of matrix generated by the generating function first column then row *)\n  Definition msumrc {r c} (gen : fin r -> fin c -> A) :=\n    vsum A0 Aadd (vsum (vec0 A0 c) (vadd Aadd) \n      (vmake (fun fr : fin r => (vmake (fun fc : fin c => gen fr fc))))).\n  \n  (** Sum of matrix generated by the generating function first row then column *)\n  Definition msumcr {r c} (gen : fin r -> fin c -> A) :=\n    vsum A0 Aadd (vsum (vec0 A0 r) (vadd Aadd) \n      (vmake (fun fc : fin c => (vmake (fun fr : fin r => gen fr fc))))).\n  \n  (** The matrices generated by the generating function first row then\n      column or first column then row have same sum *)\n  (** This two methods generate same result *)\n  Lemma msumrc_eq_msumcr : forall {r c : nat} f, (@msumrc r c f == @msumcr r c f)%A.\n  Proof.\n    unfold msumrc, msumcr, msum, vsum.\n    induction r.\n    - induction c; intros.\n      + simpl. easy.\n      + simpl. rewrite vfold_vec0.\n        * group_simpl.\n          clear -G. induction c; simpl; easy.\n        * apply G.\n    - induction c; intros.\n      + simpl.\n        rewrite (vec_0 (vfold (vadd Aadd) vnil (vmake (fun _ : fin r => vnil)))).\n        rewrite ?vfoldl_vec0. monoid_simpl.\n      + simpl.\n        Abort.\n\n  (* translated matrix won't change the sum *)\n(*   Lemma msum_trans : forall r c (m : @mat A r c), *)\n(*     msum m == msum (mtrans m). *)\n(*   Proof. *)\n(*     intros. unfold sumsum. unfold sum. unfold mtrans. *)\n(*     (* generalize dependent m. *)\n(*     generalize dependent c. *) *)\n(*     induction r; intros. *)\n(*     - simpl. rewrite (vec_0 m). simpl. *)\n(*       rewrite vmake_nil_eq_vconstnil. *)\n(*       rewrite ?vfold_constA0; auto. *)\n(*       apply vadd_nil_r. *)\n(*     - pose proof vec_S m as [x [v ->]]. simpl. *)\n(*       Check (fun v1 v2 : vec c => vadd fadd v1 v2). *)\n(*       Check (@vadd A fadd c). *)\n(*       replace (fun v1 v2 : vec c => vadd fadd v1 v2) with (@vadd A fadd c) in *. *)\n(*       2:{ unfold vadd. auto. } *)\n(* (*       rewrite vfold_cons_eq_add. *) *)\n(*       rewrite vfold_vadd. *)\n(*       Search vfold. f_equal. *)\n(*       Check vfold_cons. *)\n(*       rewrite vmap2_vmake_l. *)\n(*       rewrite vfold_vadd; auto. rewrite IHr. *)\n(*     Abort. *)\n\nEnd msum.\n\n(* Arguments msum {A} A0 fadd {r c}. *)\n(* Arguments msumrc {A} A0 fadd {r c}. *)\n(* Arguments msumcr {A} A0 fadd {r c}. *)\n\n\n\n(** ** Get row or column of a matrix *)\nSection mrow_mcol.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq} (A0:A).\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n  \n  (** *** Get row *)\n  \n  (** Get a row *)\n  Definition mrow {r c} (m : @mat A r c) (fr : fin r) := vnth m fr.\n\n  (** mrow is a proper morphism *)\n  Lemma mrow_aeq_mor : forall r c,\n      Proper (meq (Aeq:=Aeq)(r:=r)(c:=c) ==> eq ==> veq (Aeq:=Aeq)) mrow.\n  Proof.\n    unfold Proper, respectful.\n    intros. subst. unfold mrow,meq in *. rewrite H. easy.\n  Qed.\n\n  Global Existing Instance mrow_aeq_mor.\n\n  (** *** Get column *)\n  \n  (** Get a column *)\n  (* First definition: use make + nth *)\n  Definition mcol {r c} (m : @mat A r c) :=\n    fun fc : fin c => vmake (fun fr : fin r => nth (nth m fr) fc).\n\n  (* deprecated *)\n  (* Second definition: use map + nth *)\n  Definition mcol_deprecated r c (m : @mat A r c) (fc : fin c) := \n    map (fun v => vnth v fc) m.\n  \n  (** mcol is a proper morphism *)\n  Lemma mcol_aeq_mor : forall r c,\n      Proper (meq (Aeq:=Aeq)(r:=r)(c:=c) ==> eq ==> veq (Aeq:=Aeq)) mcol.\n  Proof.\n    unfold Proper, respectful.\n    intros. subst. unfold mcol,meq in *.\n    apply vmake_ext. intros.\n    rewrite H. easy.\n  Qed.\n\n  Global Existing Instance mcol_aeq_mor.\n\n  (** mcol (vcons v m) n = vcons (vnth v n) (mcol m n) *)\n  Lemma mcol_vcons : forall (r c : nat) (fc : fin c) (v : @vec A c) \n    (m : mat r c),\n    (mcol (vcons v m) fc == vcons (vnth v fc) (mcol m fc))%vector.\n  Proof.\n    destruct r; intros; simpl; easy.\n  Qed.\n  \n  (** mcol vec0 i = vec0 *)\n  Lemma mcol_vec0_eq_vec0 : forall r c fr,\n    (mcol (vec0 (vec0 A0 c) r) fr == vec0 A0 r)%vector.\n  Proof.\n    intros. unfold mcol.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    rewrite ?const_nth. easy.\n  Qed.\n\nEnd mrow_mcol.\n\n\n(** ** mat0, mat1 *)\nSection mat0_mat1.\n  Context {A:Type} (A0 A1 : A).\n\n  (** mat0 *)\n  Definition mat0 {r c} : @mat A r c :=\n    vmake (fun (fr : fin r) => (vmake (fun (fc : fin c) => A0))).\n\n  (** mat1 *)\n  Definition mat1 {n} : @mat A n n :=\n    vmake (fun (fr : fin n) => (vmake (fun (fc : fin n) =>\n      if Fin.eq_dec fr fc then A1 else A0))).\n    \nEnd mat0_mat1.\n\nArguments mat0 {A A0}.\nArguments mat1 {A A0 A1}.\n\n\n(* =============================================================== *)\n(** ** Matrix transpose *)\n\nSection MatTrans.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq}.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n  Infix \"==\" := (meq (Aeq:=Aeq)) : mat_scope.\n\n  (** Transpose a matrix : m[i][j] -> m[j][i]  *)\n  Definition mtrans {r c : nat} (m : @mat A r c) : mat c r :=\n    vmake (fun fc : fin c =>\n             vmake (fun fr : fin r =>\n                      vnth (vnth m fr) fc)).\n  \n  Notation \"m \\T\" := (mtrans m).\n\n  (** transpose is a proper morphism *)\n  Lemma mtrans_aeq_mor : forall r c : nat,\n      Proper (meq (Aeq:=Aeq)(r:=r)(c:=c) ==> meq (Aeq:=Aeq)(r:=c)(c:=r)) mtrans.\n  Proof.\n    unfold Proper, respectful.\n    intros. unfold mtrans, meq in *.\n    apply vmake_ext; intros.\n    apply vmake_ext; intros. rewrite H. easy.\n  Qed.\n\n  Global Existing Instance mtrans_aeq_mor.\n\n  (** The matrices generated by the generating function first row then\n      column or first column then row are mutual transpose *)\n  Lemma vmake_rc_eq_cr {r c} (gen : fin r -> fin c -> A) :\n    let m1 := vmake (fun fr : fin r => (vmake (fun fc : fin c => gen fr fc))) in\n    let m2 := vmake (fun fc : fin c => (vmake (fun fr : fin r => gen fr fc))) in\n      m1 == m2\\T.\n  Proof.\n    intros. unfold m1,m2,mtrans.\n    apply vmake_ext. intros.\n    apply vmake_ext. intros.\n    rewrite ?vmake_nth; auto. easy. apply Equiv_veq.\n  Qed.\n\n  (* i-th column of transposed mat equal to i-th row of original mat. *)\n  Lemma mcol_of_transed_eq_mrow (r c : nat) (m : @mat A r c) :\n    forall (i : Fin.t r), (mcol (m\\T) i == nth m i)%vector.\n  Proof.\n    intros i. unfold mcol,mtrans.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto. easy.\n    apply Equiv_veq.\n  Qed.\n  \n  (* i-th row of transposed mat equal to i-th column of original mat *)\n  Lemma mrow_of_transed_eq_mcol (r c : nat) (m : @mat A r c) :\n    forall (i : Fin.t c), (nth (m\\T) i == mcol m i)%vector.\n  Proof.\n    intros i. unfold mcol,mtrans.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto. easy.\n    apply Equiv_veq.\n  Qed.\n  \n  (** m\\T\\T = m *)\n  Theorem mtrans_trans (r c : nat) (m : @mat A r c) : m\\T\\T == m.\n  Proof.\n    unfold mtrans.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    easy. apply Equiv_veq. apply Equiv_veq.\n  Qed.\n  \n  (* m[i,j] = (m^T)[j,i] *)\n  Lemma mtrans_elem_inv (r c : nat) (m : @mat A r c) :\n    forall (fr : fin r) (fc : fin c), \n    (vnth (vnth m fr) fc == vnth (vnth (m\\T) fc) fr)%A.\n  Proof.\n    intros. unfold mtrans. rewrite ?vmake_nth; auto. easy. apply Equiv_veq.\n  Qed.\n\nEnd MatTrans.\n\n(* Arguments mtrans {A r c}. *)\n(* Arguments mtrans_trans {A r c}. *)\n(* Arguments mtrans_elem_inv {A r c}. *)\n\n\n(** ** Mapping matrix to matrix *)\nSection mmap.\n\n  Context {A:Type}.\n  \n  Definition mmap {r c} (m : mat r c) (f : A -> A) : mat r c :=\n    vmake (fun fr : fin r => vmake (fun fc : fin c => f (mnth m fr fc))).\n\n  Fixpoint mmap_old {r c} (m : mat r c) (f : A -> A) : mat r c :=\n    match m with\n    | vnil => vnil\n    | vcons x t => cons (vmap f x) (mmap_old t f)\n    end.\n    \nEnd mmap.\n\n\n(** ** Mapping two matrices to another matrix *)\nSection mmap2.\n  \n  Context `{Equiv_Aeq : Equivalence A Aeq} (Aadd : A -> A -> A).\n  Infix \"+\" := Aadd : A_scope.\n  Infix \"==\" := Aeq : A_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n  Infix \"==\" := (meq (Aeq:=Aeq)) : mat_scope.\n\n  (* Variable A : Type. *)\n  (* Variable f : A -> A -> A. *)\n  (* Variable f_comm : forall a b, f a b = f b a. *)\n  (* Variable f_assoc : forall a b c, f (f a b) c = f a (f b c).  *)\n\n  Definition mmap2 {r c} (m1 m2 : mat r c) : mat r c :=\n    vmake (fun fr : fin r => vmake (fun fc : fin c => (mnth m1 fr fc) + (mnth m2 fr fc))).\n\n  Lemma mmap2_comm {r c} (m1 m2 : mat r c) (Comm : Commutative Aadd Aeq) :\n    mmap2 m1 m2 == mmap2 m2 m1.\n  Proof.\n    unfold mmap2, mnth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply commutative.\n    apply Equiv_veq. apply Equiv_veq.\n  Qed.\n  \n  Lemma mmap2_assoc {r c} (m1 m2 m3 : mat r c) (Assoc : Associative Aadd Aeq) :\n    mmap2 (mmap2 m1 m2) m3 == mmap2 m1 (mmap2 m2 m3).\n  Proof.\n    unfold mmap2, mnth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    rewrite associative. easy.\n    all: try apply Equiv_veq; try apply eq_equivalence.\n  Qed.\n\nEnd mmap2.\n\n(** Arithmatic of matrix *)\nSection MatArith.\n\n  (* Variable A : Type. *)\n  (* Variable A0 A1 : A. *)\n  (* Variable fopp : A -> A. *)\n  (* Variable fadd fsub fmul : A -> A -> A. *)\n  (* Variable fadd_comm : forall x y, fadd x y = fadd y x. *)\n  (* Variable fadd_assoc : forall x y z, fadd (fadd x y) z = fadd x (fadd y z). *)\n  (* Variable fmul_comm : forall x y, fmul x y = fmul y x. *)\n  (* Variable fmul_assoc : forall x y z, fmul (fmul x y) z = fmul x (fmul y z). *)\n  (* Variable fadd_0_l : forall x, fadd A0 x = x. *)\n  (* Variable fadd_0_r : forall x, fadd x A0 = x. *)\n  (* Variable fmul_0_l : forall x, fmul A0 x = A0. *)\n  (* Variable fmul_0_r : forall x, fmul x A0 = A0. *)\n  (* Variable fmul_add_distl : forall x y z, *)\n  (*   fmul x (fadd y z) = fadd (fmul xnnn y) (fmul x z). *)\n  (* Variable fmul_add_distr : forall x y z, *)\n  (*   fmul (fadd x y) z = fadd (fmul x z) (fmul y z). *)\n  (* Variable fopp_opp : forall a, fopp (fopp a) = a. *)\n  (* Variable fadd_opp : forall a, fadd a (fopp a) = A0. *)\n  (* Variable fsub_comm : forall a b, fsub a b = fopp (fsub b a). *)\n  (* Variable fsub_assoc : forall a b c, fsub (fsub a b) c = fsub a (fadd b c). *)\n  (* Variable fsub_0_l : forall t, fsub A0 t = fopp t. *)\n  (* Variable fsub_0_r : forall t, fsub t A0 = t. *)\n  (* Variable fsub_self : forall t, fsub t t = A0. *)\n  (* Variable fmul_1_l : forall a, fmul A1 a = a. *)\n\n  Context `{R:Ring}.\n  Add Ring ring_inst : make_ring_theory.\n\n  Infix \"+\" := Aadd : A_scope.\n  Notation \"- a\" := (Aopp a) : A_scope.\n  Infix \"-\" := (fun a b => a + (-b)) : A_scope.\n  Infix \"*\" := Amul : A_scope.\n  Infix \"==\" := Aeq : A_scope.\n  \n  Infix \"+\" := (vadd Aadd) : vector_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n\n  Infix \"==\" := (meq (Aeq:=Aeq)) : mat_scope.\n  Notation \"m \\T\" := (mtrans m) : mat_scope.\n\n  \n  (** *** Operations *)\n  \n  (** vdot : vec n -> vec n -> A *)\n  Definition vdot {n} (v1 v2 : vec n) := vfold Aadd A0 (map2 Amul v1 v2).\n\n  (** vdotm : vec r -> mat r c -> vec c *)\n  Definition vdotm {r c} (v : vec r) (m : mat r c) : vec c :=\n    vmake (fun fc : fin c => vdot v (mcol m fc)). \n  \n  (** mdotv : mat r c -> vec c -> vec r *)\n  Definition mdotv {r c} (m : mat r c) (v : vec c) : vec r :=\n    vmake (fun fr : fin r => vdot (mrow m fr) v).\n  \n  (** matrix addition *)\n  Definition madd {r c} (m1 m2 : mat r c) : mat r c :=\n    vmake (fun fr : fin r =>\n             vmake (fun fc : fin c =>\n                      ((mnth m1 fr fc) + (mnth m2 fr fc))%A\n               )).\n  Infix \"+\" := madd : mat_scope.\n\n  (** matrix opposition *)\n  Definition mopp {r c} (m : mat r c) : mat r c :=\n    vmake (fun fr : fin r => vmake (fun fc : fin c => - (mnth m fr fc))).\n  Notation \"- a\" := (mopp a) : mat_scope.\n\n  (** subtraction *)\n  Definition msub {r c} (m1 m2 : mat r c) : mat r c :=\n    vmake (fun fr : fin r => vmake (fun fc : fin c => (mnth m1 fr fc) - (mnth m2 fr fc))).\n  Infix \"-\" := msub : mat_scope.\n  \n  (** matrix left scalar multiplication *)\n  Definition mcmul {r c} (a : A) (m : mat r c) : mat r c :=\n    vmake (fun fr : fin r => vmake (fun fc : fin c => a * (mnth m fr fc))).\n  Infix \"c*\" := mcmul : mat_scope.\n  \n  (** matrix right scalar multiplication *)\n  Definition mmulc {r c} (m : mat r c) (a : A) : mat r c :=\n    vmake (fun fr : fin r => vmake (fun fc : fin c => (mnth m fr fc) * a)).\n  Infix \"*c\" := mmulc : mat_scope.\n\n  (** multiplication *)\n  Definition mmul {r s c} (m1 : mat r s) (m2 : mat s c) : mat r c :=\n    vmake (fun fr : fin r => vmake (fun fc : fin c => vdot (nth m1 fr) (mcol m2 fc) )).\n  Infix \"*\" := mmul : mat_scope.\n\n  \n  (** *** Properties of mnth *)\n    \n  (** (vnth m1 fr) + (vnth m2 fr) = gen (m1[fr] + m2[fr]) *)\n  Lemma vadd_eq_vmake_mnth : forall r c fr (m1 m2 : mat r c),\n    (vnth m1 fr + vnth m2 fr ==\n      vmake (fun fc : fin c => (mnth m1 fr fc + mnth m2 fr fc)%A))%vector.\n  Proof.\n    intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    rewrite vadd_nth. easy. apply monoidEquiv.\n  Qed.\n\n\n  (** *** Properties of vdot *)\n\n  (** [a1;v1] . [a2;v2] = (a1 * a2) + (v1 . v2) *)\n  Lemma vdot_cons : forall n a1 a2 (v1 v2 : vec n),\n    (vdot (a1::v1) (a2::v2) == (a1 * a2) + (vdot v1 v2))%A.\n  Proof.\n    unfold vdot. \n    destruct n; intros a1 a2 v1 v2; vsimp; simpl in *. apply commutative.\n    rewrite vfold_Aadd. group_simpl. f_equiv.\n    apply vfoldl_ext_samef; try easy; try apply monoidAaddProper.\n    group_simpl.\n  Qed.\n\n  (** vdot is a proper morphism *)\n  Lemma vdot_aeq_mor : forall {n : nat},\n      let r := veq (Aeq:=Aeq) in Proper (r ==> r ==> Aeq) (vdot (n:=n)).\n  Proof.\n    unfold Proper, respectful.\n    induction n; intros; vsimp; simpl. cbv. easy.\n    simpl. rewrite ?vdot_cons.\n    apply vcons_eq_iff in H as [], H0 as [].\n    f_equiv; auto. f_equiv; easy.\n  Qed.\n\n  Global Existing Instance vdot_aeq_mor.\n\n  (** v1 . v2 = v2 . v1 *)\n  Lemma vdot_comm (n : nat) (v1 v2 : vec n) : (vdot v1 v2 == vdot v2 v1)%A.\n  Proof.\n    unfold vdot. destruct n; vsimp; simpl. easy.\n    apply vfoldl_ext_samef.\n    - apply monoidAaddProper.\n    - group_simpl. apply commutative.\n    - apply vmap2_comm. apply amonoidComm.\n  Qed.\n\n  (** [] . v = 0 *)\n  Lemma vdot_nil_l : forall (v : vec 0), (vdot nil v == A0)%A.\n  Proof.\n    intros. rewrite (vec_0 v). unfold vdot. simpl. easy.\n  Qed.\n\n  (** v . [] = 0 *)\n  Lemma vdot_nil_r : forall (v : vec 0), (vdot v nil == A0)%A.\n  Proof.\n    intros. rewrite (vec_0 v). unfold vdot. simpl. easy.\n  Qed.\n\n  (** vec0 . v = 0 *)\n  Lemma vdot_vec0_l : forall {n} (v : vec n), (vdot (vec0 A0 n) v == A0)%A.\n  Proof.\n    induction n; intros; vsimp; simpl. cbv. easy.\n    rewrite vdot_cons. rewrite IHn. ring.\n  Qed.\n\n  (** v . vec0 = 0 *)\n  Lemma vdot_vec0_r : forall {n} (v : vec n), (vdot v (vec0 A0 n) == A0)%A.\n  Proof.\n    induction n; intros; vsimp; simpl. cbv. easy.\n    rewrite vdot_cons. rewrite IHn. ring.\n  Qed.\n\n  (** v1 + v2) . v = v1 . v + v2 . v*)\n  Lemma vdot_vadd_distr_l n (v v1 v2 : vec n) :\n    (vdot (v1 + v2)%vector v == (vdot v1 v) + (vdot v2 v))%A.\n  Proof.\n    induction n; intros; vsimp; simpl. cbv. ring.\n    rewrite ?vdot_cons. rewrite IHn. ring.\n  Qed.\n  \n  (** v . (v1 + v2) = v . v1 + v . v2 *)\n  Lemma vdot_vadd_distr_r : forall n (v v1 v2 : vec n),\n    (vdot v (v1 + v2)%vector == (vdot v v1) + (vdot v v2))%A.\n  Proof.\n    induction n; intros; vsimp; simpl. cbv. ring.\n    rewrite ?vdot_cons. rewrite IHn. ring.\n  Qed.\n\n  (** a * (v1 . v2) = (a c* v1) . v2 *)\n  Lemma vdot_mult_distr_l : forall n a (v1 v2 : vec n),\n    (a * (vdot v1 v2) == vdot (vmake (fun fi => a * (vnth v1 fi))) v2)%A.\n  Proof.\n    induction n; intros; vsimp; simpl. cbv. ring.\n    rewrite ?vdot_cons.\n    rewrite <- IHn. ring.\n    (* Tips: the proof is simple than the proof of dot_product_distr_mult in \n       CoLoR Utils.Vecotr.VecArith.v *)\n  Qed.\n\n  (** v1 . (m . v2) = (v1 . m) . v2 *)\n  Lemma vdot_vec_mat_vec_assoc : forall r c (v1 : @vec A r) (m : mat r c) (v2 : vec c),\n    (vdot v1 (vmake (fun fr : fin r => vdot (mrow m fr) v2)) ==\n    vdot (vmake (fun fc : fin c => vdot v1 (mcol m fc))) v2)%A.\n  Proof.\n    unfold mat. induction r; intros.\n    - (* base case *)\n      vsimp. simpl. rewrite vdot_nil_l.\n      assert (vmake (fun fc : fin c => vdot vnil (mcol m fc)) == vec0 A0 c)%vector.\n      { apply veq_iff_nth. intros; subst. rewrite vmake_nth.\n        rewrite vdot_nil_l. rewrite const_nth. easy. apply monoidEquiv. }\n      rewrite H. rewrite vdot_vec0_l. easy.\n    - (* induction case *)\n      (* use \"eta, hd, tl, nth, cons\" to eliminate \"vec (S n)\" *)\n      rewrite (eta v1).\n      rewrite (eta (vmake (fun fr => vdot (mrow m fr) v2))).\n      rewrite vdot_cons; auto. rewrite !vnth_head.\n      rewrite vmake_nth. 2:{ apply monoidEquiv. } \n      rewrite vmake_tail. rewrite (eta m). simpl.\n      rewrite (IHr).\n      (* tail elements *)\n      set (va := (vmake (fun fc : fin c => vdot (vtl v1) (mcol (vtl m) fc)))).\n      (* head element *)\n      set (vb := vmake (fun (fc : fin c) => (vnth v1 F1 * (vnth (vhd m) fc))%A)).\n      (* whole *)\n      set (vc := (vmake (fun fc : fin c => vdot (vcons (vhd v1) (vtl v1))\n                                           (mcol (vcons (vhd m) (vtl m)) fc)))).\n      (* Tips: an importante relation: the dot product of vector and matrix are \n         splited to two parts *)\n      assert (vc == va + vb)%vector.\n      + apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n        unfold va,vb,vc. rewrite vadd_vmake_vmake. f_equiv.\n        apply vmake_ext; intros. rewrite mcol_vcons.\n        rewrite vdot_cons. rewrite vnth_head. apply commutative.\n      + rewrite H.\n        rewrite vdot_vadd_distr_l; auto. rewrite commutative. f_equiv.\n        unfold vb. rewrite vdot_mult_distr_l. easy.\n  Qed.\n    \n  (** *** Properties of madd,mopp,msub *)\n\n  (** - (- m) = m *)\n  Lemma mopp_mopp : forall {r c} (m : mat r c), - (- m) == m.\n  Proof.\n    intros.\n    unfold mopp, mnth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** m1 + m2 = m2 + m1 *)\n  Lemma madd_comm {r c} (m1 m2 : mat r c) : m1 + m2 == m2 + m1.\n  Proof.\n    unfold madd, mnth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** (m1 + m2) + m3 == m1 + (m2 + m3) *)\n  Lemma madd_assoc {r c} (m1 m2 m3 : mat r c) : (m1 + m2) + m3 == m1 + (m2 + m3).\n  Proof.\n    unfold madd, mnth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** mat0 + m = m *)\n  Lemma madd_0_l : forall {r c} (m : @mat A r c), mat0 (A0:=A0) r c + m == m.\n  Proof.\n    unfold madd, mnth, mat0. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** m + mat0 = m *)\n  Lemma madd_0_r : forall {r c} (m : @mat A r c), m + mat0 (A0:=A0) r c == m.\n  Proof.\n    unfold madd, mnth, mat0. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** m1 - m2 = - (m2 - m1) *)\n  Lemma msub_comm : forall {r c} (m1 m2 : mat r c), m1 - m2 == - (m2 - m1).\n  Proof.\n    unfold msub, mopp, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** (m1 - m2) - m3 == m1 - (m2 + m3) *)\n  Lemma msub_assoc : forall {r c} (m1 m2 m3 : mat r c), (m1 - m2) - m3 == m1 - (m2 + m3).\n  Proof.\n    unfold msub, madd, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** mat0 - m = - m *)\n  Lemma msub_0_l : forall {r c} (m : mat r c), mat0 (A0:=A0) r c - m == - m.\n  Proof.\n    unfold msub, mopp, mat0, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** m - mat0 = m *)\n  Lemma msub_0_r : forall {r c} (m : mat r c), m - mat0 (A0:=A0) r c == m.\n  Proof.\n    unfold msub, mat0, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** m - m = mat0 *)\n  Lemma msub_self : forall {r c} (m : mat r c), m - m == mat0 (A0:=A0) r c.\n  Proof.\n    unfold msub, mat0, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** m + (- m) = mat0 *)\n  Lemma madd_mopp : forall {r c} (m : mat r c), m + (- m) == mat0 (A0:=A0) r c.\n  Proof.\n    unfold madd, mopp, mat0, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** *** Properties of mcmul, mmulc. *)\n\n  (** mcmul is a proper morphism *)\n  Lemma mcmul_aeq_mor : forall r c: nat,\n      Proper (Aeq ==>\n                meq (Aeq:=Aeq)(r:=r)(c:=c) ==>\n                meq (Aeq:=Aeq)(r:=r)(c:=c)) mcmul.\n  Proof.\n    unfold Proper, respectful.\n    intros. unfold mcmul, meq in *.\n    apply vmake_ext; intros.\n    apply vmake_ext; intros. rewrite H,H0. easy.\n  Qed.\n\n  Global Existing Instance mcmul_aeq_mor.\n\n  (** mmulc is a proper morphism *)\n  Lemma mmulc_aeq_mor : forall r c: nat,\n      Proper (meq (Aeq:=Aeq)(r:=r)(c:=c) ==>\n                Aeq ==>\n                meq (Aeq:=Aeq)(r:=r)(c:=c)) mmulc.\n  Proof.\n    unfold Proper, respectful.\n    intros. unfold mmulc, meq in *.\n    apply vmake_ext; intros.\n    apply vmake_ext; intros. rewrite H,H0. easy.\n  Qed.\n\n  Global Existing Instance mmulc_aeq_mor.\n\n  (** m *c a = a c* m *)\n  Lemma mmulc_eq_mcmul : forall {r c} (a : A) (m : mat r c), m *c a == a c* m.\n  Proof.\n    unfold mcmul, mmulc, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** a c* (b c* m) = (a * b) c* m *)\n  Lemma mcmul_assoc : forall {r c} (a b : A) (m : mat r c),\n      a c* (b c* m) == (a * b)%A c* m.\n  Proof.\n    unfold mcmul, mmulc, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** a c* (b c* m) = b c* (a c* m) *)\n  Lemma mcmul_perm : forall {r c} (a b : A) (m : mat r c), a c* (b c* m) == b c* (a c* m).\n  Proof.\n    unfold mcmul, mmulc, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** a c* (m1 + m2) = (a c* m1) + (a c* m2) *)\n  Lemma mcmul_distr_l : forall {r c} (a : A) (m1 m2 : mat r c),\n      a c* (m1 + m2) == (a c* m1) + (a c* m2).\n  Proof.\n    unfold mcmul, madd, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n  \n  (** (a + b) c* m = (a c* m) + (b c* m) *)\n  Lemma mcmul_distr_r : forall {r c} (a b : A) (m : mat r c),\n      (a + b)%A c* m == (a c* m) + (b c* m).\n  Proof.\n    unfold mcmul, madd, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** 1 c* m = m *)\n  Lemma mcmul_1_l : forall {r c} (m : mat r c), A1 c* m == m.\n  Proof.\n    unfold mcmul, mnth. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** 0 c* m = mat0 *)\n  Lemma mcmul_0_l : forall {r c} (m : mat r c), A0 c* m == mat0 (A0:=A0) r c.\n  Proof.\n    unfold mcmul, mnth, mat0. intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    ring. all: try apply monoidEquiv.\n  Qed.\n\n  (** *** Properties of mmul. *)\n\n  (** (A * B)\\T = B\\T * A\\T *)\n  Lemma mmul_mtrans (r s c : nat) (m1 : mat r s) (m2 : mat s c) :\n    (m1 * m2)\\T == (m2\\T) * (m1\\T).\n  Proof.\n    unfold mmul.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    rewrite <- mtrans_elem_inv.    (* m[i][j] = (m\\T)[j][i] *)\n    rewrite ?vmake_nth.\n    rewrite mcol_of_transed_eq_mrow.\n    rewrite <- mrow_of_transed_eq_mcol. apply vdot_comm.\n    all: apply monoidEquiv.\n  Qed.\n\n  (** mmul is a proper morphism *)\n  Lemma mmul_aeq_mor : forall r c s: nat,\n      Proper (meq (Aeq:=Aeq)(r:=r)(c:=c) ==>\n                meq (Aeq:=Aeq)(r:=c)(c:=s) ==>\n                meq (Aeq:=Aeq)(r:=r)(c:=s)) mmul.\n  Proof.\n    unfold Proper, respectful.\n    intros. unfold mmul, meq in *.\n    apply vmake_ext; intros.\n    apply vmake_ext; intros.\n    rewrite H,H0. easy.\n  Qed.\n\n  Global Existing Instance mmul_aeq_mor.\n\n  (** (m1 * m2) * m3 == m1 * (m2 * m3) *)\n  Lemma mmul_assoc r s c t  (m1 : mat r s) (m2 : mat s c) (m3 : mat c t) :\n    (m1 * m2) * m3 == m1 * (m2 * m3).\n  Proof.\n    unfold mmul. unfold mat in *.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    rewrite <- vdot_vec_mat_vec_assoc; auto. f_equiv.\n    unfold mcol, mrow.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    easy. all: apply monoidEquiv.\n  Qed.\n\n  (** m1 * (m2 + m3) = m1 * m2 + m1 * m3 *)\n  Lemma mmul_madd_distr_l : forall {r c t} (m1 : mat r c) (m2 m3 : mat c t), \n      m1 * (m2 + m3) == m1 * m2 + m1 * m3.\n  Proof.\n    intros. unfold mmul, madd, mnth, mcol.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    rewrite <- vdot_vadd_distr_r; auto.\n    rewrite vadd_vmake_vmake. f_equiv.\n    apply vmake_ext; intros. rewrite ?vmake_nth.\n    easy. all: apply monoidEquiv.\n  Qed.\n  \n  (** (m1 + m2) * m3 = m1 * m3 + m2 * m3 *)\n  Lemma mmul_madd_distr_r : forall {r c s} (m1 m2 : mat r c) (m3 : mat c s), \n      (m1 + m2) * m3 == m1 * m3 + m2 * m3.\n  Proof.\n    intros. unfold mmul, madd, mnth, mcol.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth; auto.\n    rewrite <- vdot_vadd_distr_l; auto.\n    rewrite vadd_eq_vmake_mnth. unfold mnth.\n    easy. all: apply monoidEquiv.\n  Qed.\n  \n  (** mat0 * m = mat0 *)\n  Lemma mmul_0_l : forall {r c t} (m : mat c t), \n    (mat0 (A0:=A0) r c) * m == mat0 (A0:=A0) r t.\n  Proof.\n    intros. unfold mmul. unfold mat0. \n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    rewrite vmake_0_eq_vec0. rewrite vdot_vec0_l.\n    easy. all: apply monoidEquiv.\n  Qed.\n  \n  (** m * mat0 = mat0 *)\n  Lemma mmul_0_r : forall {r c t} (m : mat r c),\n      m * (mat0 (A0:=A0) c t) == mat0 (A0:=A0) r t.\n  Proof.\n    intros. unfold mmul. unfold mat0. \n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    rewrite vdot_aeq_mor. 2: reflexivity. apply vdot_vec0_r.\n    unfold mcol.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    rewrite const_nth. easy.\n    all: apply monoidEquiv.\n  Qed.\n  \n  (**  mcol of a generated matrix get exact column *)\n  Lemma mcol_vmake : forall r c fc0 (gen : fin r -> fin c -> A),\n    (mcol (vmake (fun fr : fin r => vmake (fun fc : fin c => gen fr fc))) fc0\n     == vmake (fun fr : fin r => gen fr fc0))%vector.\n  Proof.\n    intros.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    generalize dependent c.\n    generalize dependent f2.\n    destruct r; intros; vsimp; unfold mcol.\n    rewrite ?vmake_nth; try easy.\n    rewrite ?vmake_nth; try easy.\n    all: apply monoidEquiv.\n  Qed.\n\n  (** v . (col_of_mat1 fc) = v[fc] *)\n  Lemma vdot_mat1col_r : forall n (fn : fin n) v,\n    (vdot v \n      (vmake (fun fn' : fin n => if Fin.eq_dec fn' fn then A1 else A0)) == \n    vnth v fn)%A.\n  Proof.\n    induction n; intros; finsimp; vsimp; simpl.\n    - rewrite vdot_cons.\n      destruct (Fin.eq_dec); try easy.\n      rewrite vmake_0_eq_vec0. rewrite vdot_vec0_r. ring. apply monoidEquiv.\n    - rewrite vdot_cons. rewrite <- IHn.\n      ring_simplify. apply vdot_aeq_mor; try easy.\n      apply veq_iff_nth; intros; subst. rewrite ?vmake_nth.\n      destruct (Fin.eq_dec), Fin.eq_dec; try easy.\n      apply FS_inj in e. easy. subst. easy.\n      all: apply monoidEquiv.\n  Qed.\n  \n  (** mat1\\T = mat1 *)  \n  Lemma mtrans_mat1 : forall n, (@mat1 A A0 A1 n)\\T == (@mat1 A A0 A1 n).\n  Proof.\n    intros. unfold mtrans, mat1.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    destruct Fin.eq_dec; subst; destruct Fin.eq_dec; try easy. subst. easy.\n    all: apply monoidEquiv.\n  Qed.\n  \n  (** m * mat1 = m *)\n  Lemma mmul_1_r : forall {r c} (m : mat r c), m * (@mat1 A A0 A1 c) == m.\n  Proof.\n    intros. unfold mmul,mat1.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    apply veq_iff_nth; intros; subst; rewrite ?vmake_nth.\n    rewrite mcol_vmake. rewrite vdot_mat1col_r. easy.\n    all: apply monoidEquiv.\n  Qed.\n  \n  (** mat1 * m = m *)\n  Lemma mmul_1_l : forall {r c} (m : mat r c), (@mat1 A A0 A1 r) * m == m.\n  Proof.\n    (** mat1 * m = m\n        (mat1 * m)\\T\\T = m\n        (m\\T * mat1\\T)\\T = m\n        (m\\T * mat1)\\T = m\n        m\\T\\T = m\n        m = m *)\n    intros.\n    rewrite <- mtrans_trans at 1. rewrite mmul_mtrans.\n    rewrite mtrans_mat1. rewrite mmul_1_r. rewrite mtrans_trans. easy.\n  Qed.\n  \nEnd MatArith.\n\n\n(** Convert between vector and list *)\nSection v2l_l2v.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0 : A}.\n\n  Infix \"==\" := (eqlistA Aeq) : list_scope.\n  Infix \"==\" := (veq (Aeq:=Aeq)) : vector_scope.\n  \n  Fixpoint v2l {n} (v : @vec A n) : list A :=\n    match v with\n    | []%vector => []%list\n    | (x :: v')%vector => (x :: (v2l v'))%list\n    end.\n  \n  Fixpoint l2v (l : list A) (n : nat) : vec n :=\n    match n with\n    | 0 => []%vector\n    | S n' => (List.hd A0 l) :: (l2v (List.tl l) n')\n    end.\n  \n  Lemma v2l_length : forall n (v : @vec A n), length (v2l v) = n.\n  Proof.\n    intros. induction v; simpl; auto.\n  Qed.\n\n  (** v2l is a proper morphism *)\n  Lemma v2l_aeq_mor : forall n, Proper (@veq _ Aeq n ==> eqlistA Aeq) v2l.\n  Proof.\n    unfold Proper, respectful.\n    induction n; intros; vsimp. easy.\n    simpl. apply vcons_eq_iff in H as [].\n    f_equiv; auto.\n  Qed.\n\n  Global Existing Instance v2l_aeq_mor.\n\n  (** l2v is a proper morphism *)\n  (* ToDo: I cann't write a correct formalization of this proper morphism *)\n  (* Lemma l2v_aeq_mor : forall (n:nat), Proper (eqlistA Aeq ==> eq ==> veq) (l2v). *)\n  Lemma l2v_aeq_mor : forall (n:nat) (l1 l2 : list A),\n      (l1 == l2)%list -> l2v l1 n == l2v l2 n.\n  Proof.\n    induction n; intros; simpl. easy.\n    (* apply vcons_aeq_mor; auto. *)\n    constructor; auto.\n    + rewrite H. easy.\n    + apply IHn. rewrite H. easy.\n  Qed.\n\n  (* Global Existing Instance l2v_aeq_mor. *)\n\n  (** if l2v equal, then list equal *)\n  Lemma l2v_eq_imply_list_eq : forall n (l1 l2 : list A),\n      length l1 = n -> length l2 = n -> l2v l1 n == l2v l2 n ->\n      (l1 == l2)%list.\n  Proof.\n    induction n; intros.\n    - apply List.length_zero_iff_nil in H,H0. subst. easy.\n    - destruct l1,l2; try easy.\n      inv H. inv H0. simpl in *.\n      apply vcons_eq_iff in H1 as [].\n      apply (IHn l1) in H2; auto.\n  Qed.\n\n  (** if v2l equal, then vector equal *)\n  Lemma v2l_eq_imply_veq : forall n (v1 v2 : vec n),\n      (v2l v1 == v2l v2)%list -> v1 == v2.\n  Proof.\n    induction n; intros; vsimp; simpl in *. easy.\n    apply cons_eq_iff in H as []. apply IHn in H0.\n    apply vcons_eq_iff; split; auto.\n  Qed.\n\n  Lemma v2l_l2v_id : forall (n : nat) (l : list A), length l = n ->\n    (v2l (l2v l n) == l)%list.\n  Proof.\n    induction n; intros; simpl.\n    - apply (length_zero_iff_nil (Aeq:=Aeq)) in H. easy.\n    - destruct l; try easy. rewrite IHn; auto. f_equiv.\n  Qed.\n  \n  Lemma l2v_v2l_id : forall (n : nat) (v : vec n), l2v (v2l v) n == v.\n  Proof.\n    intros. induction v; simpl. easy.\n    (* apply vcons_aeq_mor; auto. *)\n    constructor; auto. easy.\n  Qed.\n  \nEnd v2l_l2v.\n\nArguments v2l {A n}.\nArguments l2v {A}.\n\n\n(** Convert between matrix and list list *)\nSection m2l_l2m.\n\n  Context `{Equiv_Aeq : Equivalence A Aeq} {A0 : A}.\n\n  Infix \"==\" := (eqlistA (eqlistA Aeq)) : dlist_scope.\n  Infix \"==\" := (meq (Aeq:=Aeq)) : mat_scope.\n  \n  Fixpoint m2l {r c} (m : @mat A r c) : list (list A) :=\n    match m with\n    | []%vector => []%list\n    | (x :: v')%vector => (v2l x) :: (m2l v')\n    end.\n\n  Fixpoint l2m (dl : list (list A)) (r c : nat) : @mat A r c :=\n    match r with\n    | 0 => Vector.nil\n    | S n' => Vector.cons (l2v A0 (List.hd List.nil dl) c) \n      (l2m (List.tl dl) n' c)\n    end.\n\n  (** m2l is a proper morphism *)\n  Lemma m2l_aeq_mor : forall r c, Proper (@meq A Aeq r c ==> eqlistA (eqlistA Aeq)) m2l.\n  Proof.\n    unfold Proper, respectful, mat.\n    induction r; intros; vsimp; simpl. easy.\n    apply vcons_eq_iff in H as []. f_equiv; auto.\n    rewrite H. easy.\n  Qed.\n\n  Global Existing Instance m2l_aeq_mor.\n\n  (** if l2m equal, then dlist equal *)\n  Lemma l2m_eq_imply_dlist_eq : forall r c (dl1 dl2 : list (list A)),\n      length dl1 = r -> length dl2 = r -> width dl1 c -> width dl2 c ->\n      l2m dl1 r c == l2m dl2 r c -> (dl1 == dl2)%dlist.\n  Proof.\n    induction r; intros; simpl in *; try easy.\n    - apply List.length_zero_iff_nil in H,H0. subst. easy.\n    - destruct dl1,dl2; try easy.\n      apply vcons_eq_iff in H3 as [].\n      inv H. inv H0. inv H1. inv H2.\n      simpl in *. f_equiv; auto.\n      + apply (l2v_eq_imply_list_eq (n:=length l) (A0:=A0)); auto.\n      + apply IHr with (c:=length l); auto.\n  Qed.\n\n  (** if m2l equal, then mat equal *)\n  Lemma m2l_eq_imply_mat_eq : forall r c (m1 m2 : mat r c),\n      (m2l m1 == m2l m2)%dlist -> m1 == m2.\n  Proof.\n    unfold mat.\n    induction r; intros; vsimp; simpl in *. easy.\n    apply cons_eq_iff in H as [].\n    apply IHr in H0. apply v2l_eq_imply_veq in H.\n    apply vcons_eq_iff; split; auto.\n  Qed.\n\n  Lemma m2l_l2m_id : forall {r c} (dl : list (list A)) (H1 : length dl = r)\n    (H2 : width dl c), (m2l (l2m dl r c) == dl)%dlist.\n  Proof.\n    induction r; intros.\n    - simpl. apply (length_zero_iff_nil (Aeq:=eqlistA Aeq)) in H1. easy.\n    - destruct dl. easy. simpl. inv H1. inv H2. rewrite IHr; auto.\n      f_equiv. apply v2l_l2v_id; auto.\n  Qed.\n  \n  Lemma l2m_m2l_id : forall {r c} (m : mat r c), l2m (m2l m) r c == m. \n  Proof.\n    intros. induction m; simpl. easy.\n    constructor; auto. apply l2v_v2l_id.\n  Qed.\n\n  Lemma l2m_inj : forall {r c} (d1 d2 : list (list A)),\n    length d1 = r -> width d1 c -> \n    length d2 = r -> width d2 c -> \n    ~(d1 == d2)%dlist -> ~(l2m d1 r c == l2m d2 r c).\n  Proof.\n    intros. intro. apply l2m_eq_imply_dlist_eq in H4; auto.\n  Qed.\n  \n  Lemma l2m_surj : forall {r c} (m : mat r c), \n    (exists d, l2m d r c == m).\n  Proof.\n    unfold mat in *.\n    induction r; intros; vsimp.\n    - exists List.nil. simpl. easy.\n    - simpl. destruct (IHr c x0).\n      exists (List.cons (v2l x) x1). simpl.\n      apply vcons_eq_iff; split; auto. apply l2v_v2l_id.\n  Qed.\n    \n  Lemma m2l_inj : forall {r c} (m1 m2 : mat r c),\n    ~(m1 == m2) -> ~(m2l m1 == m2l m2)%dlist.\n  Proof.\n    intros. intro. apply m2l_eq_imply_mat_eq in H0. easy.\n  Qed.\n  \n  Lemma m2l_surj : forall {r c} (d : list (list A)), \n    length d = r -> width d c -> \n    (exists m, @m2l r c m == d)%dlist.\n  Proof.\n    induction r; intros; simpl.\n    - apply List.length_zero_iff_nil in H. subst. exists []. simpl. easy.\n    - destruct d. easy. inv H. inv H0.\n      destruct (IHr (length l) d eq_refl H3).\n      exists ((l2v A0 l (length l)) :: x). simpl. f_equiv; auto.\n      apply v2l_l2v_id. auto.\n  Qed.\n  \nEnd m2l_l2m.\n\nArguments m2l {A r c}.\nArguments l2m {A} A0 dl r c.\n", "meta": {"author": "zhengpushi", "repo": "CoqMatrix", "sha": "28fa5f96e38a07659cfd373e09b0e75c24c22bfd", "save_path": "github-repos/coq/zhengpushi-CoqMatrix", "path": "github-repos/coq/zhengpushi-CoqMatrix/CoqMatrix-28fa5f96e38a07659cfd373e09b0e75c24c22bfd/CoqMatrix/DepList/Matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7449085490447327}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun ssrnat eqtype seq choice div fintype.\nRequire Import path tuple bigop finset prime ssralg poly polydiv mxpoly.\nRequire Import countalg ssrnum ssrint rat intdiv.\nRequire Import fingroup finalg zmodp cyclic pgroup sylow.\nRequire Import vector falgebra fieldext separable galois.\n\n(******************************************************************************)\n(*   The main result in this file is the existence theorem that underpins the *)\n(* construction of the algebraic numbers in file algC.v. This theorem simply  *)\n(* asserts the existence of an algebraically closed field with an             *)\n(* automorphism of order 2, and dubbed the Fundamental_Theorem_of_Algebraics  *)\n(* because it is essentially the Fundamental Theorem of Algebra for algebraic *)\n(* numbers (the more familiar version for complex numbers can be derived by   *)\n(* continuity).                                                               *)\n(*   Although our proof does indeed construct exactly the algebraics, we      *)\n(* choose not to expose this in the statement of our Theorem. In algC.v we    *)\n(* construct the norm and partial order of the \"complex field\" introduced by  *)\n(* the Theorem; as these imply is has characteristic 0, we then get the       *)\n(* algebraics as a subfield. To avoid some duplication a few basic properties *)\n(* of the algebraics, such as the existence of minimal polynomials, that are  *)\n(* required by the proof of the Theorem, are also proved here.                *)\n(*  The main theorem of countalg.v supplies us directly with an algebraic     *)\n(* closure of the rationals (as the rationals are a countable field), so all  *)\n(* we really need to construct is a conjugation automorphism that exchanges   *)\n(* the two roots (i and -i) of X^2 + 1, and fixes a (real) subfield of        *)\n(* index 2. This does not require actually constructing this field: the       *)\n(* kHomExtend construction from galois.v supplies us with an automorphism     *)\n(* conj_n of the number field Q[z_n] = Q[x_n, i] for any x_n such that Q[x_n] *)\n(* does not contain i (e.g., such that Q[x_n] is real). As conj_n will extend *)\n(* conj_m when Q[x_n] contains x_m, it therefore suffices to construct a      *)\n(* sequence x_n such that                                                     *)\n(* (1) For each n, Q[x_n] is a REAL field containing Q[x_m] for all m <= n.   *)\n(* (2) Each z in C belongs to Q[z_n] = Q[x_n, i] for large enough n.          *)\n(* This, of course, amounts to proving the Fundamental Theorem of Algebra.    *)\n(*   Indeed, we use a constructive variant of Artin's algebraic proof of that *)\n(* Theorem to replace (2) by                                                  *)\n(* (3) Each monic polynomial over Q[x_m] whose constant term is -c^2 for some *)\n(*     c in Q[x_m] has a root in Q[x_n] for large enough n.                   *)\n(* We then ensure (3) by setting Q[x_n+1] = Q[x_n, y] where y is the root of  *)\n(* of such a polynomial p found by dichotomy in some interval [0, b] with b   *)\n(* suitably large (such that p[b] >= 0), and p is obtained by decoding n into *)\n(* a triple (m, p, c) that satisfies the conditions of (3) (taking x_n+1=x_n  *)\n(* if this is not the case), thereby ensuring that all such triples are       *)\n(* ultimately considered.                                                     *)\n(*   In more detail, the 600-line proof consists in six (uneven) parts:       *)\n(* (A) - Construction of number fields (~ 100 lines): in order to make use of *)\n(*     the theory developped in falgebra, fieldext, separable and galois we   *)\n(*     construct a separate fielExtType Q z for the number field Q[z], with   *)\n(*     z in C, the closure of rat supplied by countable_algebraic_closure.    *)\n(*     The morphism (ofQ z) maps Q z to C, and the Primitive Element Theorem  *)\n(*     lets us define a predicate sQ z characterizing the image of (ofQ z),   *)\n(*     as well as a partial inverse (inQ z) to (ofQ z).                       *)\n(* (B) - Construction of the real extension Q[x, y] (~ 230 lines): here y has *)\n(*     to be a root of a polynomial p over Q[x] satisfying the conditions of  *)\n(*     (3), and Q[x] should be real and archimedean, which we represent by    *)\n(*     a morphism from Q x to some archimedean field R, as the ssrnum and     *)\n(*     fieldext structures are not compatible. The construction starts by     *)\n(*     weakening the condition p[0] = -c^2 to p[0] <= 0 (in R), then reducing *)\n(*     to the case where p is the minimal polynomial over Q[x] of some y (in  *)\n(*     some Q[w] that contains x and all roots of p). Then we only need to    *)\n(*     construct a realFieldType structure for Q[t] = Q[x,y] (we don't even   *)\n(*     need to show it is consistent with that of R). This amounts to fixing  *)\n(*     the sign of all z != 0 in Q[t], consistently with arithmetic in Q[t].  *)\n(*     Now any such z is equal to q[y] for some q in Q[x][X] coprime with p.  *)\n(*     Then up + vq = 1 for Bezout coefficients u and v. As p is monic, there *)\n(*     is some b0 >= 0 in R such that p changes sign in ab0 = [0; b0]. As R   *)\n(*     is archimedean, some iteration of the binary search for a root of p in *)\n(*     ab0 will yield an interval ab_n such that |up[d]| < 1/2 for d in ab_n. *)\n(*     Then |q[d]| > 1/2M > 0 for any upper bound M on |v[X]| in ab0, so q    *)\n(*     cannot change sign in ab_n (as then root-finding in ab_n would yield a *)\n(*     d with |Mq[d]| < 1/2), so we can fix the sign of z to that of q in     *)\n(*     ab_n.                                                                  *)\n(* (C) - Construction of the x_n and z_n (~50 lines): x_ n is obtained by     *)\n(*     iterating (B), starting with x_0 = 0, and then (A) and the PET yield   *)\n(*     z_ n. We establish (1) and (3), and that the minimal polynomial of the *)\n(*     preimage i_ n of i over the preimage R_ n of Q[x_n] is X^2 + 1.        *)\n(* (D) - Establish (2), i.e., prove the FTA (~180 lines). We must depart from *)\n(*     Artin's proof because deciding membership in the union of the Q[x_n]   *)\n(*     requires the FTA, i.e., we cannot (yet) construct a maximal real       *)\n(*     subfield of C. We work around this issue by first reducing to the case *)\n(*     where Q[z] is Galois over Q and contains i, then using induction over  *)\n(*     the degree of z over Q[z_ n] (i.e., the degree of a monic polynomial   *)\n(*     over Q[z_n] that has z as a root). We can assume that z is not in      *)\n(*     Q[z_n]; then it suffices to find some y in Q[z_n, z] \\ Q[z_n] that is  *)\n(*     also in Q[z_m] for some m > n, as then we can apply induction with the *)\n(*     minimal polynomial of z over Q[z_n, y]. In any Galois extension Q[t]   *)\n(*     of Q that contains both z and z_n, Q[x_n, z] = Q[z_n, z] is Galois     *)\n(*     over both Q[x_n] and Q[z_n]. If Gal(Q[x_n,z] / Q[x_n]) isn't a 2-group *)\n(*     take one of its Sylow 2-groups P; the minimal polynomial p of any      *)\n(*     generator of the fixed field F of P over Q[x_n] has odd degree, hence  *)\n(*     by (3) - p[X]p[-X] and thus p has a root y in some Q[x_m], hence in    *)\n(*     Q[z_m]. As F is normal, y is in F, with minimal polynomial p, and y    *)\n(*     is not in Q[z_n] = Q[x_n, i] since p has odd degree. Otherwise,        *)\n(*     Gal(Q[z_n,z] / Q[z_n]) is a proper 2-group, and has a maximal subgroup *)\n(*     P of index 2. The fixed field F of P has a generator w over Q[z_n]     *)\n(*     with w^2 in Q[z_n] \\ Q[x_n], i.e. w^2 = u + 2iv with v != 0. From (3)  *)\n(*     X^4 - uX^2 - v^2 has a root x in some Q[x_m]; then x != 0 as v != 0,   *)\n(*     hence w^2 = y^2 for y = x + iv/x in Q[z_m], and y generates F.         *)\n(* (E) - Construct conj and conclude (~40 lines): conj z is defined as        *)\n(*     conj_ n z with the n provided by (2); since each conj_ m is a morphism *)\n(*     of order 2 and conj z = conj_ m z for any m >= n, it follows that conj *)\n(*     is also a morphism of order 2.                                         *)\n(* Note that (C), (D) and (E) only depend on Q[x_n] not containing i; the     *)\n(* order structure is not used (hence we need not prove that the ordering of  *)\n(* Q[x_m] is consistent with that of Q[x_n] for m >= n).                      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n\nLocal Notation \"p ^ f\" := (map_poly f p) : ring_scope.\nLocal Notation \"p ^@\" := (p ^ in_alg _) (at level 2, format \"p ^@\"): ring_scope.\nLocal Notation \"<< E ; u >>\" := <<E; u>>%VS.\nLocal Notation Qmorphism C := {rmorphism rat -> C}.\n\nLemma rat_algebraic_archimedean (C : numFieldType) (QtoC : Qmorphism C) :\n  integralRange QtoC -> Num.archimedean_axiom C.\nProof.\nmove=> algC x.\nwithout loss x_ge0: x / 0 <= x by rewrite -normr_id; apply; apply: normr_ge0.\nhave [-> | nz_x] := eqVneq x 0; first by exists 1%N; rewrite normr0.\nhave [p mon_p px0] := algC x; exists (\\sum_(j < size p) `|numq p`_j|)%N.\nrewrite ger0_norm // real_ltrNge ?rpred_nat ?ger0_real //.\napply: contraL px0 => lb_x; rewrite rootE gtr_eqF // horner_coef size_map_poly.\nhave x_gt0 k: 0 < x ^+ k by rewrite exprn_gt0 // ltr_def nz_x.\nmove: lb_x; rewrite polySpred ?monic_neq0 // !big_ord_recr coef_map /=.\nrewrite -lead_coefE (monicP mon_p) natrD rmorph1 mul1r => lb_x.\ncase: _.-1 (lb_x) => [|n]; first by rewrite !big_ord0 !add0r ltr01.\nrewrite -ltr_subl_addl add0r -(ler_pmul2r (x_gt0 n)) -exprS.\napply: ltr_le_trans; rewrite mulrDl mul1r ltr_spaddr // -sumrN.\nrewrite natr_sum mulr_suml ler_sum // => j _.\nrewrite coef_map /= fmorph_eq_rat (ler_trans (real_ler_norm _)) //.\n  by rewrite rpredN rpredM ?rpred_rat ?rpredX // ger0_real.\nrewrite normrN normrM ler_pmul //=.\n  rewrite normf_div -!intr_norm -!abszE ler_pimulr ?ler0n //.\n  by rewrite invf_le1 ?ler1n ?ltr0n ?absz_gt0 ?denq_eq0.\nrewrite normrX ger0_norm ?(ltrW x_gt0) // ler_weexpn2l ?leq_ord //.\nby rewrite (ler_trans _ lb_x) // -natrD addn1 ler1n.\nQed.\n\nDefinition decidable_embedding sT T (f : sT -> T) :=\n  forall y, decidable (exists x, y = f x).\n\nLemma rat_algebraic_decidable (C : fieldType) (QtoC : Qmorphism C) :\n  integralRange QtoC -> decidable_embedding QtoC.\nProof.\nhave QtoCinj: injective QtoC by apply: fmorph_inj.\npose ZtoQ : int -> rat := intr; pose ZtoC : int -> C := intr.\nhave ZtoQinj: injective ZtoQ by apply: intr_inj.\nhave defZtoC: ZtoC =1 QtoC \\o ZtoQ by move=> m; rewrite /= rmorph_int.\nmove=> algC x; have /sig2_eqW[q mon_q qx0] := algC x; pose d := (size q).-1.\nhave [n ub_n]: {n | forall y, root q y -> `|y| < n}.\n  have [n1 ub_n1] := monic_Cauchy_bound mon_q.\n  have /monic_Cauchy_bound[n2 ub_n2]: (-1) ^+ d *: (q \\Po - 'X) \\is monic.\n    rewrite monicE lead_coefZ lead_coef_comp ?size_opp ?size_polyX // -/d.\n    by rewrite lead_coef_opp lead_coefX (monicP mon_q) (mulrC 1) signrMK.\n  exists (Num.max n1 n2) => y; rewrite ltrNge ler_normr !ler_maxl rootE.\n  apply: contraL => /orP[]/andP[] => [/ub_n1/gtr_eqF->// | _ /ub_n2/gtr_eqF].\n  by rewrite hornerZ horner_comp !hornerE opprK mulf_eq0 signr_eq0 => /= ->.\nhave [p [a nz_a Dq]] := rat_poly_scale q; pose N := Num.bound `|n * a%:~R|.\npose xa : seq rat := [seq (m%:R - N%:R) / a%:~R | m <- iota 0 N.*2].\nhave [/sig2_eqW[y _ ->] | xa'x] := @mapP _ _ QtoC xa x; first by left; exists y.\nright=> [[y Dx]]; case: xa'x; exists y => //.\nhave{x Dx qx0} qy0: root q y by rewrite Dx fmorph_root in qx0.\nhave /dvdzP[b Da]: (denq y %| a)%Z.\n  have /Gauss_dvdzl <-: coprimez (denq y) (numq y ^+ d).\n    by rewrite coprimez_sym coprimez_expl //; apply: coprime_num_den.\n  pose p1 : {poly int} := a *: 'X^d - p.\n  have Dp1: p1 ^ intr = a%:~R *: ('X^d - q).\n    by rewrite rmorphB linearZ /= map_polyXn scalerBr Dq scalerKV ?intr_eq0.\n  apply/dvdzP; exists (\\sum_(i < d) p1`_i * numq y ^+ i * denq y ^+ (d - i.+1)).\n  apply: ZtoQinj; rewrite /ZtoQ rmorphM mulr_suml rmorph_sum /=.\n  transitivity ((p1 ^ intr).[y] * (denq y ^+ d)%:~R).\n    rewrite Dp1 !hornerE hornerXn (rootP qy0) subr0.\n    by rewrite !rmorphX /= numqE exprMn mulrA.\n  have sz_p1: (size (p1 ^ ZtoQ)%R <= d)%N.\n    rewrite Dp1 size_scale ?intr_eq0 //; apply/leq_sizeP=> i.\n    rewrite leq_eqVlt eq_sym -polySpred ?monic_neq0 // coefB coefXn.\n    case: eqP => [-> _ | _ /(nth_default 0)->//].\n    by rewrite -lead_coefE (monicP mon_q).\n  rewrite (horner_coef_wide _ sz_p1) mulr_suml; apply: eq_bigr => i _.\n  rewrite -!mulrA -exprSr coef_map !rmorphM !rmorphX /= numqE exprMn -mulrA.\n  by rewrite -exprD -addSnnS subnKC.\npose m := `|(numq y * b + N)%R|%N.\nhave Dm: m%:R = `|y * a%:~R + N%:R|.\n  by rewrite pmulrn abszE intr_norm Da rmorphD !rmorphM /= numqE mulrAC mulrA.\nhave ltr_Qnat n1 n2 : (n1%:R < n2%:R :> rat = _) := ltr_nat _ n1 n2.\nhave ub_y: `|y * a%:~R| < N%:R.\n  apply: ler_lt_trans (archi_boundP (normr_ge0 _)); rewrite !normrM.\n  by rewrite ler_pmul ?normr_ge0 // (ler_trans _ (ler_norm n)) ?ltrW ?ub_n.\napply/mapP; exists m.\n  rewrite mem_iota /= add0n -addnn -ltr_Qnat Dm natrD.\n  by rewrite (ler_lt_trans (ler_norm_add _ _)) // normr_nat ltr_add2r.\nrewrite Dm ger0_norm ?addrK ?mulfK ?intr_eq0 // -ler_subl_addl sub0r.\nby rewrite (ler_trans (ler_norm _)) ?normrN ?ltrW.\nQed.\n\nLemma minPoly_decidable_closure\n  (F : fieldType) (L : closedFieldType) (FtoL : {rmorphism F -> L}) x :\n    decidable_embedding FtoL -> integralOver FtoL x ->\n  {p | [/\\ p \\is monic, root (p ^ FtoL) x & irreducible_poly p]}.\nProof.\nmove=> isF /sig2W[p /monicP mon_p px0].\nhave [r Dp] := closed_field_poly_normal (p ^ FtoL); pose n := size r.\nrewrite lead_coef_map {}mon_p rmorph1 scale1r in Dp.\npose Fpx q := (q \\is a polyOver isF) && root q x.\nhave FpxF q: Fpx (q ^ FtoL) = root (q ^ FtoL) x.\n  by rewrite /Fpx polyOver_poly // => j _; apply/sumboolP; exists q`_j.\npose p_ (I : {set 'I_n}) := \\prod_(i <- enum I) ('X - (r`_i)%:P).\nhave{px0 Dp} /ex_minset[I /minsetP[/andP[FpI pIx0] minI]]: exists I, Fpx (p_ I).\n  exists setT; suffices ->: p_ setT = p ^ FtoL by rewrite FpxF.\n  by rewrite Dp (big_nth 0) big_mkord /p_ (eq_enum (in_set _)) big_filter.\nhave{p} [p DpI]: {p | p_ I = p ^ FtoL}.\n  exists (p_ I ^ (fun y => if isF y is left Fy then sval (sig_eqW Fy) else 0)).\n  rewrite -map_poly_comp map_poly_id // => y /(allP FpI) /=.\n  by rewrite unfold_in; case: (isF y) => // Fy _; case: (sig_eqW _).\nhave mon_pI: p_ I \\is monic by apply: monic_prod_XsubC.\nhave mon_p: p \\is monic by rewrite -(map_monic FtoL) -DpI.\nexists p; rewrite -DpI; split=> //; split=> [|q nCq q_dv_p].\n  by rewrite -(size_map_poly FtoL) -DpI (root_size_gt1 _ pIx0) ?monic_neq0.\nrewrite -dvdp_size_eqp //; apply/eqP.\nwithout loss mon_q: q nCq q_dv_p / q \\is monic.\n  move=> IHq; pose a := lead_coef q; pose q1 := a^-1 *: q.\n  have nz_a: a != 0 by rewrite lead_coef_eq0 (dvdpN0 q_dv_p) ?monic_neq0.\n  have /IHq IHq1: q1 \\is monic by rewrite monicE lead_coefZ mulVf.\n  by rewrite -IHq1 ?size_scale ?dvdp_scalel ?invr_eq0.\nwithout loss{nCq} qx0: q mon_q q_dv_p / root (q ^ FtoL) x.\n  have /dvdpP[q1 Dp] := q_dv_p; rewrite DpI Dp rmorphM rootM -implyNb in pIx0.\n  have mon_q1: q1 \\is monic by rewrite Dp monicMr in mon_p.\n  move=> IH; apply: (IH) (implyP pIx0 _) => //; apply: contra nCq => /IH IHq1.\n  rewrite -(subnn (size q1)) {1}IHq1 ?Dp ?dvdp_mulr // polySpred ?monic_neq0 //.\n  by rewrite eqSS size_monicM ?monic_neq0 // -!subn1 subnAC addKn.\nhave /dvdp_prod_XsubC[m Dq]: q ^ FtoL %| p_ I by rewrite DpI dvdp_map.\npose B := [set j in mask m (enum I)]; have{Dq} Dq: q ^ FtoL = p_ B.\n  apply/eqP; rewrite -eqp_monic ?monic_map ?monic_prod_XsubC //.\n  congr (_ %= _): Dq; apply: eq_big_perm => //.\n  by rewrite uniq_perm_eq ?mask_uniq ?enum_uniq // => j; rewrite mem_enum inE.\nrewrite -!(size_map_poly FtoL) Dq -DpI (minI B) // -?Dq ?FpxF //.\nby apply/subsetP=> j; rewrite inE => /mem_mask; rewrite mem_enum.\nQed.\n\nLemma alg_integral (F : fieldType) (L : fieldExtType F) :\n  integralRange (in_alg L).\nProof.\nmove=> x; have [/polyOver1P[p Dp]] := (minPolyOver 1 x, monic_minPoly 1 x).\nby rewrite Dp map_monic; exists p; rewrite // -Dp root_minPoly.\nQed.\nPrenex Implicits alg_integral.\n\nLemma imaginary_exists (C : closedFieldType) : {i : C | i ^+ 2 = -1}.\nProof.\nhave /sig_eqW[i Di2] := @solve_monicpoly C 2 (nth 0 [:: -1]) isT.\nby exists i; rewrite Di2 big_ord_recl big_ord1 mul0r mulr1 !addr0.\nQed.\n\nImport DefaultKeying GRing.DefaultPred.\nImplicit Arguments map_poly_inj [[F] [R] x1 x2].\n\nTheorem Fundamental_Theorem_of_Algebraics :\n  {L : closedFieldType &\n     {conj : {rmorphism L -> L} | involutive conj & ~ conj =1 id}}.\nProof.\nhave maxn3 n1 n2 n3: {m | [/\\ n1 <= m, n2 <= m & n3 <= m]%N}.\n  by exists (maxn n1 (maxn n2 n3)); apply/and3P; rewrite -!geq_max.\nhave [C [/= QtoC algC]] := countable_algebraic_closure [countFieldType of rat].\nexists C; have [i Di2] := imaginary_exists C.\npose Qfield := fieldExtType rat; pose Cmorph (L : Qfield) := {rmorphism L -> C}.\nhave charQ (L : Qfield): [char L] =i pred0 := ftrans (char_lalg L) (char_num _).\nhave sepQ  (L : Qfield) (K E : {subfield L}): separable K E.\n  by apply/separableP=> u _; apply: charf0_separable.\npose genQfield z L := {LtoC : Cmorph L & {u | LtoC u = z & <<1; u>> = fullv}}.\nhave /all_tag[Q /all_tag[ofQ genQz]] z: {Qz : Qfield & genQfield z Qz}.\n  have [|p [/monic_neq0 nzp pz0 irr_p]] := minPoly_decidable_closure _ (algC z).\n    exact: rat_algebraic_decidable.\n  pose Qz := SubFieldExtType pz0 irr_p.\n  pose QzC := subfx_inj_rmorphism QtoC z p.\n  exists Qz, QzC, (subfx_root QtoC z p); first exact: subfx_inj_root.\n  apply/vspaceP=> u; rewrite memvf; apply/Fadjoin1_polyP.\n  by have [q] := subfxEroot pz0 nzp u; exists q.\nhave pQof z p: p^@ ^ ofQ z = p ^ QtoC.\n  by rewrite -map_poly_comp; apply: eq_map_poly => x; rewrite !fmorph_eq_rat.\nhave pQof2 z p u: ofQ z p^@.[u] = (p ^ QtoC).[ofQ z u].\n  by rewrite -horner_map pQof.\nhave PET_Qz z (E : {subfield Q z}): {u | <<1; u>> = E}.\n  exists (separable_generator 1 E).\n  by rewrite -eq_adjoin_separable_generator ?sub1v.\npose gen z x := exists q, x = (q ^ QtoC).[z].\nhave PET2 x y: {z | gen z x & gen z y}.\n  pose Gxy := (x, y) = let: (p, q, z) := _ in ((p ^ QtoC).[z], (q ^ QtoC).[z]).\n  suffices [[[p q] z] []]: {w | Gxy w} by exists z; [exists p | exists q].\n  apply/sig_eqW; have /integral_algebraic[px nz_px pxx0] := algC x.\n  have /integral_algebraic[py nz_py pyy0] := algC y.\n  have [n [[p Dx] [q Dy]]] := char0_PET nz_px pxx0 nz_py pyy0 (char_num _).\n  by exists (p, q, y *+ n - x); congr (_, _).\nhave gen_inQ z x: gen z x -> {u | ofQ z u = x}.\n  have [u Dz _] := genQz z => /sig_eqW[q ->].\n  by exists q^@.[u]; rewrite pQof2 Dz.\nhave gen_ofP z u v: reflect (gen (ofQ z u) (ofQ z v)) (v \\in <<1; u>>).\n  apply: (iffP Fadjoin1_polyP) => [[q ->]|]; first by rewrite pQof2; exists q.\n  by case=> q; rewrite -pQof2 => /fmorph_inj->; exists q.\nhave /all_tag[sQ genP] z: {s : pred C & forall x, reflect (gen z x) (x \\in s)}.\n  apply: all_tag (fun x => reflect (gen z x)) _ => x.\n  have [w /gen_inQ[u <-] /gen_inQ[v <-]] := PET2 z x.\n  by exists (v \\in <<1; u>>)%VS; apply: gen_ofP.\nhave sQtrans: transitive (fun x z => x \\in sQ z).\n  move=> x y z /genP[p ->] /genP[q ->]; apply/genP; exists (p \\Po q).\n  by rewrite map_comp_poly horner_comp.\nhave sQid z: z \\in sQ z by apply/genP; exists 'X; rewrite map_polyX hornerX.\nhave{gen_ofP} sQof2 z u v: (ofQ z u \\in sQ (ofQ z v)) = (u \\in <<1; v>>%VS).\n  exact/genP/(gen_ofP z).\nhave sQof z v: ofQ z v \\in sQ z.\n  by have [u Dz defQz] := genQz z; rewrite -[in sQ z]Dz sQof2 defQz memvf.\nhave{gen_inQ} sQ_inQ z x z_x := gen_inQ z x (genP z x z_x).\nhave /all_sig[inQ inQ_K] z: {inQ | {in sQ z, cancel inQ (ofQ z)}}.\n  by apply: all_sig_cond (fun x u => ofQ z u = x) 0 _ => x /sQ_inQ.\nhave ofQ_K z: cancel (ofQ z) (inQ z).\n  by move=> x; have /inQ_K/fmorph_inj := sQof z x.\nhave sQring z: divring_closed (sQ z).\n  have sQ_1: 1 \\in sQ z by rewrite -(rmorph1 (ofQ z)) sQof.\n  by split=> // x y /inQ_K<- /inQ_K<- /=; rewrite -(rmorphB, fmorph_div) sQof.\nhave sQopp z : oppr_closed (sQ z) := sQring z.\nhave sQadd z : addr_closed (sQ z) := sQring z.\nhave sQmul z : mulr_closed (sQ z) := sQring z.\nhave sQinv z : invr_closed (sQ z) := sQring z.\npose morph_ofQ x z Qxz := forall u, ofQ z (Qxz u) = ofQ x u.\nhave QtoQ z x: x \\in sQ z -> {Qxz : 'AHom(Q x, Q z) | morph_ofQ x z Qxz}.\n  move=> z_x; pose Qxz u := inQ z (ofQ x u).\n  have QxzE u: ofQ z (Qxz u) = ofQ x u by apply/inQ_K/(sQtrans x).\n  suffices /rat_lrmorphism QxzM: rmorphism Qxz.\n    by exists (linfun_ahom (LRMorphism QxzM)) => u; rewrite lfunE QxzE.\n  split=> [u v|]; first by apply: (canLR (ofQ_K z)); rewrite !rmorphB !QxzE.\n  by split=> [u v|]; apply: (canLR (ofQ_K z)); rewrite ?rmorph1 ?rmorphM ?QxzE.\npose sQs z s := all (mem (sQ z)) s.\nhave inQsK z s: sQs z s -> map (ofQ z) (map (inQ z) s) = s.\n  by rewrite -map_comp => /allP/(_ _ _)/inQ_K; apply: map_id_in.\nhave inQpK z p: p \\is a polyOver (sQ z) -> (p ^ inQ z) ^ ofQ z = p.\n  by move=> /allP/(_ _ _)/inQ_K/=/map_poly_id; rewrite -map_poly_comp.\nhave{gen PET2 genP} PET s: {z | sQs z s & <<1 & map (inQ z) s>>%VS = fullv}.\n  have [y /inQsK Ds]: {y | sQs y s}.\n    elim: s => [|x s /= [y IHs]]; first by exists 0.\n    have [z /genP z_x /genP z_y] := PET2 x y.\n    by exists z; rewrite /= {x}z_x; apply: sub_all IHs => x /sQtrans/= ->.\n  have [w defQs] := PET_Qz _ <<1 & map (inQ y) s>>%AS; pose z := ofQ y w.\n  have z_s: sQs z s.\n    rewrite -Ds /sQs all_map; apply/allP=> u s_u /=.\n    by rewrite sQof2 defQs seqv_sub_adjoin.\n  have [[u Dz defQz] [Qzy QzyE]] := (genQz z, QtoQ y z (sQof y w)).\n  exists z => //; apply/eqP; rewrite eqEsubv subvf /= -defQz.\n  rewrite -(limg_ker0 _ _ (AHom_lker0 Qzy)) aimg_adjoin_seq aimg_adjoin aimg1.\n  rewrite -[map _ _](mapK (ofQ_K y)) -(map_comp (ofQ y)) (eq_map QzyE) inQsK //.\n  by rewrite -defQs -(canLR (ofQ_K y) Dz) -QzyE ofQ_K.\npose rp s := \\prod_(z <- s) ('X - z%:P).\nhave map_rp (f : {rmorphism _}) s: rp _ s ^ f = rp _ (map f s).\n  rewrite rmorph_prod /rp big_map; apply: eq_bigr => x _.\n  by rewrite rmorphB /= map_polyX map_polyC.\npose is_Gal z := SplittingField.axiom (Q z).\nhave galQ x: {z | x \\in sQ z & is_Gal z}.\n  have /sig2W[p mon_p pz0] := algC x.\n  have [s Dp] := closed_field_poly_normal (p ^ QtoC).\n  rewrite (monicP _) ?monic_map // scale1r in Dp; have [z z_s defQz] := PET s.\n  exists z; first by apply/(allP z_s); rewrite -root_prod_XsubC -Dp.\n  exists p^@; first exact: alg_polyOver.\n  exists (map (inQ z) s); last by apply/vspaceP=> u; rewrite defQz memvf.\n  by rewrite -(eqp_map (ofQ z)) pQof Dp map_rp inQsK ?eqpxx.\npose is_realC x := {R : archiFieldType & {rmorphism Q x -> R}}.\npose realC := {x : C & is_realC x}.\npose has_Rroot (xR : realC) p c (Rx := sQ (tag xR)) :=\n  [&& p \\is a polyOver Rx, p \\is monic, c \\in Rx & p.[0] == - c ^+ 2].\npose root_in (xR : realC) p := exists2 w, w \\in sQ (tag xR) & root p w.\npose extendsR (xR yR : realC) := tag xR \\in sQ (tag yR).\nhave add_Rroot xR p c: {yR | extendsR xR yR & has_Rroot xR p c -> root_in yR p}.\n  rewrite {}/extendsR; case: (has_Rroot xR p c) / and4P; last by exists xR.\n  case: xR => x [R QxR] /= [/inQpK <-]; move: (p ^ _) => {p}p mon_p /inQ_K<- Dc.\n  have{c Dc} p0_le0: (p ^ QxR).[0] <= 0.\n    rewrite horner_coef0 coef_map -[p`_0]ofQ_K -coef_map -horner_coef0 (eqP Dc).\n    by rewrite -rmorphX -rmorphN ofQ_K /= rmorphN rmorphX oppr_le0 sqr_ge0.\n  have [s Dp] := closed_field_poly_normal (p ^ ofQ x).\n  have{Dp} /all_and2[s_p p_s] y: root (p ^ ofQ x) y <-> (y \\in s).\n    by rewrite Dp (monicP mon_p) scale1r root_prod_XsubC.\n  rewrite map_monic in mon_p; have [z /andP[z_x /allP/=z_s] _] := PET (x :: s).\n  have{z_x} [[Qxz QxzE] Dx] := (QtoQ z x z_x, inQ_K z x z_x).\n  pose Qx := <<1; inQ z x>>%AS; pose QxzM := [rmorphism of Qxz].\n  have pQwx q1: q1 \\is a polyOver Qx -> {q | q1 = q ^ Qxz}.\n    move/polyOverP=> Qx_q1; exists ((q1 ^ ofQ z) ^ inQ x).\n    apply: (map_poly_inj (ofQ z)); rewrite -map_poly_comp (eq_map_poly QxzE).\n    by rewrite inQpK ?polyOver_poly // => j _; rewrite -Dx sQof2 Qx_q1.\n  have /all_sig[t_ Dt] u: {t | <<1; t>> = <<Qx; u>>} by apply: PET_Qz.\n  suffices{p_s}[u Ry px0]: {u : Q z & is_realC (ofQ z (t_ u)) & ofQ z u \\in s}.\n    exists (Tagged is_realC Ry) => [|_] /=.\n      by rewrite -Dx sQof2 Dt subvP_adjoin ?memv_adjoin.\n    by exists (ofQ z u); rewrite ?p_s // sQof2 Dt memv_adjoin.\n  without loss{z_s s_p} [u Dp s_y]: p mon_p p0_le0 /\n    {u | minPoly Qx u = p ^ Qxz & ofQ z u \\in s}.\n  - move=> IHp; move: {2}_.+1 (ltnSn (size p)) => d.\n    elim: d => // d IHd in p mon_p s_p p0_le0 *; rewrite ltnS => le_p_d.\n    have /closed_rootP/sig_eqW[y py0]: size (p ^ ofQ x) != 1%N.\n      rewrite size_map_poly size_poly_eq1 eqp_monic ?rpred1 //.\n      by apply: contraTneq p0_le0 => ->; rewrite rmorph1 hornerC ltr_geF ?ltr01.\n    have /s_p s_y := py0; have /z_s/sQ_inQ[u Dy] := s_y.\n    have /pQwx[q Dq] := minPolyOver Qx u.\n    have mon_q: q \\is monic by have:= monic_minPoly Qx u; rewrite Dq map_monic.\n    have /dvdpP/sig_eqW[r Dp]: q %| p.\n      rewrite -(dvdp_map QxzM) -Dq minPoly_dvdp //.\n        by apply: polyOver_poly => j _; rewrite -sQof2 QxzE Dx.\n      by rewrite -(fmorph_root (ofQ z)) Dy -map_poly_comp (eq_map_poly QxzE).\n    have mon_r: r \\is monic by rewrite Dp monicMr in mon_p.\n    have [q0_le0 | q0_gt0] := lerP ((q ^ QxR).[0]) 0.\n      by apply: (IHp q) => //; exists u; rewrite ?Dy.\n    have r0_le0: (r ^ QxR).[0] <= 0.\n      by rewrite -(ler_pmul2r q0_gt0) mul0r -hornerM -rmorphM -Dp.\n    apply: (IHd r mon_r) => // [w rw0|].\n      by rewrite s_p // Dp rmorphM rootM rw0.\n    apply: leq_trans le_p_d; rewrite Dp size_Mmonic ?monic_neq0 // addnC.\n    by rewrite -(size_map_poly QxzM q) -Dq size_minPoly !ltnS leq_addl.\n  exists u => {s s_y}//; set y := ofQ z (t_ u); set p1 := minPoly Qx u in Dp.\n  have /QtoQ[Qyz QyzE]: y \\in sQ z := sQof z (t_ u).\n  pose q1_ v := Fadjoin_poly Qx u (Qyz v).\n  have{QyzE} QyzE v: Qyz v = (q1_ v).[u].\n    by rewrite Fadjoin_poly_eq // -Dt -sQof2 QyzE sQof.\n  have /all_sig2[q_ coqp Dq] v: {q | v != 0 -> coprimep p q & q ^ Qxz = q1_ v}.\n    have /pQwx[q Dq]: q1_ v \\is a polyOver Qx by apply: Fadjoin_polyOver.\n    exists q => // nz_v; rewrite -(coprimep_map QxzM) -Dp -Dq -gcdp_eqp1.\n    have /minPoly_irr/orP[] // := dvdp_gcdl p1 (q1_ v).\n      by rewrite gcdp_polyOver ?minPolyOver ?Fadjoin_polyOver.\n    rewrite -/p1 {1}/eqp dvdp_gcd => /and3P[_ _ /dvdp_leq/=/implyP].\n    rewrite size_minPoly ltnNge size_poly (contraNneq _ nz_v) // => q1v0.\n    by rewrite -(fmorph_eq0 [rmorphism of Qyz]) /= QyzE q1v0 horner0.\n  pose h2 : R := 2%:R^-1; have nz2: 2%:R != 0 :> R by rewrite pnatr_eq0.\n  pose itv ab := [pred c : R | ab.1 <= c <= ab.2].\n  pose wid ab : R := ab.2 - ab.1; pose mid ab := (ab.1 + ab.2) * h2.\n  pose sub_itv ab cd := cd.1 <= ab.1 :> R /\\ ab.2 <= cd.2 :> R.\n  pose xup q ab := [/\\ q.[ab.1] <= 0, q.[ab.2] >= 0 & ab.1 <= ab.2 :> R].\n  pose narrow q ab (c := mid ab) := if q.[c] >= 0 then (ab.1, c) else (c, ab.2).\n  pose find k q := iter k (narrow q).\n  have findP k q ab (cd := find k q ab):\n    xup q ab -> [/\\ xup q cd, sub_itv cd ab & wid cd = wid ab / (2 ^ k)%:R].\n  - rewrite {}/cd; case: ab => a b xq_ab.\n    elim: k => /= [|k]; first by rewrite divr1.\n    case: (find k q _) => c d [[/= qc_le0 qd_ge0 le_cd] [/= le_ac le_db] Dcd].\n    have [/= le_ce le_ed] := midf_le le_cd; set e := _ / _ in le_ce le_ed.\n    rewrite expnSr natrM invfM mulrA -{}Dcd /narrow /= -[mid _]/e.\n    have [qe_ge0 // | /ltrW qe_le0] := lerP 0 q.[e].\n      do ?split=> //=; [exact: (ler_trans le_ed) | apply: canRL (mulfK nz2) _].\n      by rewrite mulrBl divfK // mulr_natr opprD addrACA subrr add0r.\n    do ?split=> //=; [exact: (ler_trans le_ac) | apply: canRL (mulfK nz2) _].\n    by rewrite mulrBl divfK // mulr_natr opprD addrACA subrr addr0.\n  have find_root r q ab:\n    xup q ab -> {n | forall x, x \\in itv (find n q ab) ->`|(r * q).[x]| < h2}.\n  - move=> xab; have ub_ab := poly_itv_bound _ ab.1 ab.2.\n    have [Mu MuP] := ub_ab r; have /all_sig[Mq MqP] j := ub_ab q^`N(j).\n    pose d := wid ab; pose dq := \\poly_(i < (size q).-1) Mq i.+1.\n    have d_ge0: 0 <= d by rewrite subr_ge0; case: xab.\n    have [Mdq MdqP] := poly_disk_bound dq d.\n    pose n := Num.bound (Mu * Mdq * d); exists n => c /= /andP[].\n    have{xab} [[]] := findP n _ _ xab; case: (find n q ab) => a1 b1 /=.\n    rewrite -/d => qa1_le0 qb1_ge0 le_ab1 [/= le_aa1 le_b1b] Dab1 le_a1c le_cb1.\n    have /MuP lbMu: c \\in itv ab.\n      by rewrite !inE (ler_trans le_aa1) ?(ler_trans le_cb1).\n    have Mu_ge0: 0 <= Mu by rewrite (ler_trans _ lbMu) ?normr_ge0.\n    have Mdq_ge0: 0 <= Mdq.\n      by rewrite (ler_trans _ (MdqP 0 _)) ?normr_ge0 ?normr0.\n    suffices lb1 a2 b2 (ab1 := (a1, b1)) (ab2 := (a2, b2)) :\n      xup q ab2 /\\ sub_itv ab2 ab1 -> q.[b2] - q.[a2] <= Mdq * wid ab1.\n    + apply: ler_lt_trans (_ : Mu * Mdq * wid (a1, b1) < h2); last first.\n        rewrite {}Dab1 mulrA ltr_pdivr_mulr ?ltr0n ?expn_gt0 //.\n        rewrite (ltr_le_trans (archi_boundP _)) ?mulr_ge0 ?ltr_nat // -/n.\n        rewrite ler_pdivl_mull ?ltr0n // -natrM ler_nat.\n        by case: n => // n; rewrite expnS leq_pmul2l // ltn_expl.\n      rewrite -mulrA hornerM normrM ler_pmul ?normr_ge0 //.\n      have [/ltrW qc_le0 | qc_ge0] := ltrP q.[c] 0.\n        by apply: ler_trans (lb1 c b1 _); rewrite ?ler0_norm ?ler_paddl.\n      by apply: ler_trans (lb1 a1 c _); rewrite ?ger0_norm ?ler_paddr ?oppr_ge0.\n    case{c le_a1c le_cb1 lbMu}=> [[/=qa2_le0 qb2_ge0 le_ab2] [/=le_a12 le_b21]].\n    pose h := b2 - a2; have h_ge0: 0 <= h by rewrite subr_ge0.\n    have [-> | nz_q] := eqVneq q 0.\n      by rewrite !horner0 subrr mulr_ge0 ?subr_ge0.\n    rewrite -(subrK a2 b2) (addrC h) (nderiv_taylor q (mulrC a2 h)).\n    rewrite (polySpred nz_q) big_ord_recl /= mulr1 nderivn0 addrC addKr.\n    have [le_aa2 le_b2b] := (ler_trans le_aa1 le_a12, ler_trans le_b21 le_b1b).\n    have /MqP MqPx1: a2 \\in itv ab by rewrite inE le_aa2 (ler_trans le_ab2).\n    apply: ler_trans (ler_trans (ler_norm _) (ler_norm_sum _ _ _)) _.\n    apply: ler_trans (_ : `|dq.[h] * h| <= _); last first.\n      by rewrite normrM ler_pmul ?normr_ge0 ?MdqP // ?ger0_norm ?ler_sub ?h_ge0.\n    rewrite horner_poly ger0_norm ?mulr_ge0 ?sumr_ge0 // => [|j _]; last first.\n      by rewrite mulr_ge0 ?exprn_ge0 // (ler_trans _ (MqPx1 _)) ?normr_ge0.\n    rewrite mulr_suml ler_sum // => j _; rewrite normrM -mulrA -exprSr.\n    by rewrite ler_pmul ?normr_ge0 // normrX ger0_norm.\n  have [ab0 xab0]: {ab | xup (p ^ QxR) ab}.\n    have /monic_Cauchy_bound[b pb_gt0]: p ^ QxR \\is monic by apply: monic_map.\n    by exists (0, `|b|); rewrite /xup normr_ge0 p0_le0 ltrW ?pb_gt0 ?ler_norm.\n  pose ab_ n := find n (p ^ QxR) ab0; pose Iab_ n := itv (ab_ n).\n  pose lim v a := (q_ v ^ QxR).[a]; pose nlim v n := lim v (ab_ n).2.\n  have lim0 a: lim 0 a = 0.\n    rewrite /lim; suffices /eqP ->: q_ 0 == 0 by rewrite rmorph0 horner0.\n    by rewrite -(map_poly_eq0 QxzM) Dq /q1_ !raddf0.\n  have limN v a: lim (- v) a = - lim v a.\n    rewrite /lim; suffices ->: q_ (- v) = - q_ v by rewrite rmorphN hornerN.\n    by apply: (map_poly_inj QxzM); rewrite Dq /q1_ !raddfN /= Dq.\n  pose lim_nz n v := exists2 e, e > 0 & {in Iab_ n, forall a, e < `|lim v a| }.\n  have /(all_sig_cond 0%N)[n_ nzP] v: v != 0 -> {n | lim_nz n v}.\n    move=> nz_v; do [move/(_ v nz_v); rewrite -(coprimep_map QxR)] in coqp.\n    have /sig_eqW[r r_pq_1] := Bezout_eq1_coprimepP _ _ coqp.\n    have /(find_root r.1)[n ub_rp] := xab0; exists n.\n    have [M Mgt0 ubM]: {M | 0 < M & {in Iab_ n, forall a, `|r.2.[a]| <= M}}.\n      have [M ubM] := poly_itv_bound r.2 (ab_ n).1 (ab_ n).2.\n      exists (Num.max 1 M) => [|s /ubM vM]; first by rewrite ltr_maxr ltr01.\n      by rewrite ler_maxr orbC vM.\n    exists (h2 / M) => [|a xn_a]; first by rewrite divr_gt0 ?invr_gt0 ?ltr0n.\n    rewrite ltr_pdivr_mulr // -(ltr_add2l h2) -mulr2n -mulr_natl divff //.\n    rewrite -normr1 -(hornerC 1 a) -[1%:P]r_pq_1 hornerD.\n    rewrite ?(ler_lt_trans (ler_norm_add _ _)) ?ltr_le_add ?ub_rp //.\n    by rewrite mulrC hornerM normrM ler_wpmul2l ?ubM.\n  have ab_le m n: (m <= n)%N -> (ab_ n).2 \\in Iab_ m.\n    move/subnKC=> <-; move: {n}(n - m)%N => n; rewrite /ab_.\n    have /(findP m)[/(findP n)[[_ _]]] := xab0.\n    rewrite /find -iter_add -!/(find _ _) -!/(ab_ _) addnC !inE.\n    by move: (ab_ _) => /= ab_mn le_ab_mn [/ler_trans->].\n  pose lt v w := 0 < nlim (w - v) (n_ (w - v)).\n  have posN v: lt 0 (- v) = lt v 0 by rewrite /lt subr0 add0r.\n  have posB v w: lt 0 (w - v) = lt v w by rewrite /lt subr0.\n  have posE n v: (n_ v <= n)%N -> lt 0 v = (0 < nlim v n).\n    rewrite /lt subr0 /nlim => /ab_le; set a := _.2; set b := _.2 => Iv_a.\n    have [-> | /nzP[e e_gt0]] := eqVneq v 0; first by rewrite !lim0 ltrr.\n    move: (n_ v) => m in Iv_a b * => v_gte.\n    without loss lt0v: v v_gte / 0 < lim v b.\n      move=> IHv; apply/idP/idP => [v_gt0 | /ltrW]; first by rewrite -IHv.\n      rewrite ltr_def -normr_gt0 ?(ltr_trans _ (v_gte _ _)) ?ab_le //=.\n      rewrite !lerNgt -!oppr_gt0 -!limN; apply: contra => v_lt0.\n      by rewrite -IHv // => c /v_gte; rewrite limN normrN.\n    rewrite lt0v (ltr_trans e_gt0) ?(ltr_le_trans (v_gte a Iv_a)) //.\n    rewrite ger0_norm // lerNgt; apply/negP=> /ltrW lev0.\n    have [le_a le_ab] : _ /\\ a <= b := andP Iv_a.\n    have xab: xup (q_ v ^ QxR) (a, b) by move/ltrW in lt0v.\n    have /(find_root (h2 / e)%:P)[n1] := xab; have /(findP n1)[[_ _]] := xab.\n    case: (find _ _ _) => c d /= le_cd [/= le_ac le_db] _ /(_ c)/implyP.\n    rewrite inE lerr le_cd hornerM hornerC normrM ler_gtF //.\n    rewrite ger0_norm ?divr_ge0 ?invr_ge0 ?ler0n ?(ltrW e_gt0) // mulrAC.\n    rewrite ler_pdivl_mulr // ler_wpmul2l ?invr_ge0 ?ler0n // ltrW // v_gte //=.\n    by rewrite inE -/b (ler_trans le_a) //= (ler_trans le_cd).\n  pose lim_pos m v := exists2 e, e > 0 & forall n, (m <= n)%N -> e < nlim v n.\n  have posP v: reflect (exists m, lim_pos m v) (lt 0 v).\n    apply: (iffP idP) => [v_gt0|[m [e e_gt0 v_gte]]]; last first.\n      by rewrite (posE _ _ (leq_maxl _ m)) (ltr_trans e_gt0) ?v_gte ?leq_maxr.\n    have [|e e_gt0 v_gte] := nzP v.\n      by apply: contraTneq v_gt0 => ->; rewrite /lt subr0 /nlim lim0 ltrr.\n    exists (n_ v), e => // n le_vn; rewrite (posE n) // in v_gt0.\n    by rewrite -(ger0_norm (ltrW v_gt0)) v_gte ?ab_le.\n  have posNneg v: lt 0 v -> ~~ lt v 0.\n    case/posP=> m [d d_gt0 v_gtd]; rewrite -posN.\n    apply: contraL d_gt0 => /posP[n [e e_gt0 nv_gte]].\n    rewrite ltr_gtF // (ltr_trans (v_gtd _ (leq_maxl m n))) // -oppr_gt0.\n    by rewrite /nlim -limN (ltr_trans e_gt0) ?nv_gte ?leq_maxr.\n  have posVneg v: v != 0 -> lt 0 v || lt v 0.\n    case/nzP=> e e_gt0 v_gte; rewrite -posN; set w := - v.\n    have [m [le_vm le_wm _]] := maxn3 (n_ v) (n_ w) 0%N; rewrite !(posE m) //.\n    by rewrite /nlim limN -ltr_normr (ltr_trans e_gt0) ?v_gte ?ab_le.\n  have posD v w: lt 0 v -> lt 0 w -> lt 0 (v + w).\n    move=>  /posP[m [d d_gt0 v_gtd]] /posP[n [e e_gt0 w_gte]].\n    apply/posP; exists (maxn m n), (d + e) => [|k]; first exact: addr_gt0.\n    rewrite geq_max => /andP[le_mk le_nk]; rewrite /nlim /lim.\n    have ->: q_ (v + w) = q_ v + q_ w.\n      by apply: (map_poly_inj QxzM); rewrite rmorphD /= !{1}Dq /q1_ !raddfD.\n    by rewrite rmorphD hornerD ltr_add ?v_gtd ?w_gte.\n  have posM v w: lt 0 v -> lt 0 w -> lt 0 (v * w).\n    move=> /posP[m [d d_gt0 v_gtd]] /posP[n [e e_gt0 w_gte]].\n    have /dvdpP[r /(canRL (subrK _))Dqvw]: p %| q_ (v * w) - q_ v * q_ w.\n      rewrite -(dvdp_map QxzM) rmorphB rmorphM /= !Dq -Dp minPoly_dvdp //.\n        by rewrite rpredB 1?rpredM ?Fadjoin_polyOver.\n      by rewrite rootE !hornerE -!QyzE rmorphM subrr.\n    have /(find_root ((d * e)^-1 *: r ^ QxR))[N ub_rp] := xab0.\n    pose f := d * e * h2; apply/posP; exists (maxn N (maxn m n)), f => [|k].\n      by rewrite !mulr_gt0 ?invr_gt0 ?ltr0n.\n    rewrite !geq_max => /and3P[/ab_le/ub_rp{ub_rp}ub_rp le_mk le_nk].\n    rewrite -(ltr_add2r f) -mulr2n -mulr_natr divfK // /nlim /lim Dqvw.\n    rewrite rmorphD hornerD /= -addrA -ltr_subl_addl ler_lt_add //.\n      by rewrite rmorphM hornerM ler_pmul ?ltrW ?v_gtd ?w_gte.\n    rewrite -ltr_pdivr_mull ?mulr_gt0 // (ler_lt_trans _ ub_rp) //.\n    by rewrite -scalerAl hornerZ -rmorphM mulrN -normrN ler_norm.\n  pose le v w := (w == v) || lt v w.\n  pose abs v := if le 0 v then v else - v.\n  have absN v: abs (- v) = abs v.\n    rewrite /abs /le oppr_eq0 opprK posN.\n    have [-> | /posVneg/orP[v_gt0 | v_lt0]] := altP eqP; first by rewrite oppr0.\n      by rewrite v_gt0 /= -if_neg posNneg.\n    by rewrite v_lt0 /= -if_neg -(opprK v) posN posNneg ?posN.\n  have absE v: le 0 v -> abs v = v by rewrite /abs => ->.\n  pose QyNum := RealLtMixin posD posM posNneg posB posVneg absN absE (rrefl _).\n  pose QyNumField := [numFieldType of NumDomainType (Q y) QyNum].\n  pose Ry := [realFieldType of RealDomainType _ (RealLeAxiom QyNumField)].\n  have archiRy := @rat_algebraic_archimedean Ry _ alg_integral.\n  by exists (ArchiFieldType Ry archiRy); apply: [rmorphism of idfun].\nhave some_realC: realC.\n  suffices /all_sig[f QfK] x: {a | in_alg (Q 0) a = x}.\n    exists 0, [archiFieldType of rat], f.\n    exact: can2_rmorphism (inj_can_sym QfK (fmorph_inj _)) QfK.\n  have /Fadjoin1_polyP/sig_eqW[q]: x \\in <<1; 0>>%VS by rewrite -sQof2 rmorph0.\n  by exists q.[0]; rewrite -horner_map rmorph0.\npose fix xR n : realC :=\n  if n isn't n'.+1 then some_realC else\n  if unpickle (nth 0%N (CodeSeq.decode n') 1) isn't Some (p, c) then xR n' else\n  tag (add_Rroot (xR n') p c).\npose x_ n := tag (xR n).\nhave sRle m n: (m <= n)%N -> {subset sQ (x_ m) <= sQ (x_ n)}.\n  move/subnK <-; elim: {n}(n - m)%N => // n IHn x /IHn{IHn}Rx.\n  rewrite addSn /x_ /=; case: (unpickle _) => [[p c]|] //=.\n  by case: (add_Rroot _ _ _) => yR /= /(sQtrans _ x)->.\nhave xRroot n p c: has_Rroot (xR n) p c -> {m | n <= m & root_in (xR m) p}%N.\n  case/and4P=> Rp mon_p Rc Dc; pose m := CodeSeq.code [:: n; pickle (p, c)].\n  have le_n_m: (n <= m)%N by apply/ltnW/(allP (CodeSeq.ltn_code _))/mem_head.\n  exists m.+1; rewrite ?leqW /x_ //= CodeSeq.codeK pickleK.\n  case: (add_Rroot _ _ _) => yR /= _; apply; apply/and4P.\n  by split=> //; first apply: polyOverS Rp; apply: (sRle n).\nhave /all_sig[z_ /all_and3[Ri_R Ri_i defRi]] n (x := x_ n):\n  {z | [/\\ x \\in sQ z, i \\in sQ z & <<<<1; inQ z x>>; inQ z i>> = fullv]}.\n- have [z /and3P[z_x z_i _] Dzi] := PET [:: x; i].\n  by exists z; rewrite -adjoin_seq1 -adjoin_cons.\npose i_ n := inQ (z_ n) i; pose R_ n := <<1; inQ (z_ n) (x_ n)>>%AS.\nhave memRi n: <<R_ n; i_ n>> =i predT by move=> u; rewrite defRi memvf.\nhave sCle m n: (m <= n)%N -> {subset sQ (z_ m) <= sQ (z_ n)}.\n  move/sRle=> Rmn _ /sQ_inQ[u <-].\n  have /Fadjoin_polyP[p /polyOverP Rp ->] := memRi m u.\n  rewrite -horner_map inQ_K ?rpred_horner //=; apply/polyOver_poly=> j _.\n  by apply: sQtrans (Ri_R n); rewrite Rmn // -(inQ_K _ _ (Ri_R m)) sQof2.\nhave R'i n: i \\notin sQ (x_ n).\n  rewrite /x_; case: (xR n) => x [Rn QxR] /=.\n  apply: contraL (@ltr01 Rn) => /sQ_inQ[v Di].\n  suffices /eqP <-: - QxR v ^+ 2 == 1 by rewrite oppr_gt0 -lerNgt sqr_ge0.\n  rewrite -rmorphX -rmorphN fmorph_eq1 -(fmorph_eq1 (ofQ x)) rmorphN eqr_oppLR.\n  by rewrite rmorphX Di Di2.\nhave szX2_1: size ('X^2 + 1) = 3.\n  by move=> R; rewrite size_addl ?size_polyXn ?size_poly1.\nhave minp_i n (p_i := minPoly (R_ n) (i_ n)): p_i = 'X^2 + 1.\n  have p_dv_X2_1: p_i %| 'X^2 + 1.\n    rewrite minPoly_dvdp ?rpredD ?rpredX ?rpred1 ?polyOverX //.\n    rewrite -(fmorph_root (ofQ _)) inQ_K // rmorphD rmorph1 /= map_polyXn.\n    by rewrite rootE hornerD hornerXn hornerC Di2 addNr.\n  apply/eqP; rewrite -eqp_monic ?monic_minPoly //; last first.\n    by rewrite monicE lead_coefE szX2_1 coefD coefXn coefC addr0.\n  rewrite -dvdp_size_eqp // eqn_leq dvdp_leq -?size_poly_eq0 ?szX2_1 //= ltnNge.\n  by rewrite size_minPoly ltnS leq_eqVlt orbF adjoin_deg_eq1 -sQof2 !inQ_K.\nhave /all_sig[n_ FTA] z: {n | z \\in sQ (z_ n)}.\n  without loss [z_i gal_z]: z / i \\in sQ z /\\ is_Gal z.\n    have [y /and3P[/sQtrans y_z /sQtrans y_i _] _] := PET [:: z; i].\n    have [t /sQtrans t_y gal_t] := galQ y.\n    by case/(_ t)=> [|n]; last exists n; rewrite ?y_z ?y_i ?t_y.\n  apply/sig_eqW; have n := 0%N.\n  have [p]: exists p, [&& p \\is monic, root p z & p \\is a polyOver (sQ (z_ n))].\n    have [p mon_p pz0] := algC z; exists (p ^ QtoC).\n    by rewrite map_monic mon_p pz0 -(pQof (z_ n)); apply/polyOver_poly.\n  elim: {p}_.+1 {-2}p n (ltnSn (size p)) => // d IHd p n lepd pz0.\n  have [t [t_C t_z gal_t]]: exists t, [/\\ z_ n \\in sQ t, z \\in sQ t & is_Gal t].\n    have [y /and3P[y_C y_z _]] := PET [:: z_ n; z].\n    by have [t /(sQtrans y)t_y] := galQ y; exists t; rewrite !t_y.\n  pose Qt := SplittingFieldType rat (Q t) gal_t; have /QtoQ[CnQt CnQtE] := t_C.\n  pose Rn : {subfield Qt} := (CnQt @: R_ n)%AS; pose i_t : Qt := CnQt (i_ n).\n  pose Cn : {subfield Qt} := <<Rn; i_t>>%AS.\n  have defCn: Cn = limg CnQt :> {vspace Q t} by rewrite /= -aimg_adjoin defRi.\n  have memRn u: (u \\in Rn) = (ofQ t u \\in sQ (x_ n)).\n    by rewrite /= aimg_adjoin aimg1 -sQof2 CnQtE inQ_K.\n  have memCn u: (u \\in Cn) = (ofQ t u \\in sQ (z_ n)).\n    have [v Dv genCn] := genQz (z_ n).\n    by rewrite -Dv -CnQtE sQof2 defCn -genCn aimg_adjoin aimg1.\n  have Dit: ofQ t i_t = i by rewrite CnQtE inQ_K.\n  have Dit2: i_t ^+ 2 = -1.\n    by apply: (fmorph_inj (ofQ t)); rewrite rmorphX rmorphN1 Dit.\n  have dimCn: \\dim_Rn Cn = 2.\n    rewrite -adjoin_degreeE adjoin_degree_aimg.\n    by apply: succn_inj; rewrite -size_minPoly minp_i.\n  have /sQ_inQ[u_z Dz] := t_z; pose Rz := <<Cn; u_z>>%AS.\n  have{p lepd pz0} le_Rz_d: (\\dim_Cn Rz < d)%N.\n    rewrite -ltnS -adjoin_degreeE -size_minPoly (leq_trans _ lepd) // !ltnS.\n    have{pz0} [mon_p pz0 Cp] := and3P pz0.\n    have{Cp} Dp: ((p ^ inQ (z_ n)) ^ CnQt) ^ ofQ t = p.\n      by rewrite -map_poly_comp (eq_map_poly CnQtE) inQpK.\n    rewrite -Dp size_map_poly dvdp_leq ?monic_neq0 -?(map_monic (ofQ _)) ?Dp //.\n    rewrite defCn minPoly_dvdp //; try by rewrite -(fmorph_root (ofQ t)) Dz Dp.\n    by apply/polyOver_poly=> j _; rewrite memv_img ?memvf.\n  have [sRCn sCnRz]: (Rn <= Cn)%VS /\\ (Cn <= Rz)%VS by rewrite !subv_adjoin.\n  have sRnRz := subv_trans sRCn sCnRz.\n  have{gal_z} galRz: galois Rn Rz.\n    apply/and3P; split=> //; apply/splitting_normalField=> //.\n    pose u : SplittingFieldType rat (Q z) gal_z := inQ z z.\n    have /QtoQ[Qzt QztE] := t_z; exists (minPoly 1 u ^ Qzt).\n      have /polyOver1P[q ->] := minPolyOver 1 u; apply/polyOver_poly=> j _.\n      by rewrite coef_map linearZZ rmorph1 rpredZ ?rpred1.\n    have [s /eqP Ds] := splitting_field_normal 1 u.\n    rewrite Ds; exists (map Qzt s); first by rewrite map_rp eqpxx.\n    apply/eqP; rewrite eqEsubv; apply/andP; split.\n      apply/Fadjoin_seqP; split=> // _ /mapP[w s_w ->].\n      by rewrite (subvP (adjoinSl u_z (sub1v _))) // -sQof2 Dz QztE.\n    rewrite /= adjoinC (Fadjoin_idP _) -/Rz; last first.\n      by rewrite (subvP (adjoinSl _ (sub1v _))) // -sQof2 Dz Dit.\n    rewrite /= -adjoin_seq1 adjoin_seqSr //; apply/allP=> /=; rewrite andbT.\n    rewrite -(mem_map (fmorph_inj (ofQ _))) -map_comp (eq_map QztE); apply/mapP.\n    by exists u; rewrite ?inQ_K // -root_prod_XsubC -Ds root_minPoly.\n  have galCz: galois Cn Rz by rewrite (galoisS _ galRz) ?sRCn.\n  have [Cz | C'z]:= boolP (u_z \\in Cn); first by exists n; rewrite -Dz -memCn.\n  pose G := 'Gal(Rz / Cn)%G; have{C'z} ntG: G :!=: 1%g.\n    rewrite trivg_card1 -galois_dim 1?(galoisS _ galCz) ?subvv //=.\n    by rewrite -adjoin_degreeE adjoin_deg_eq1.\n  pose extRz m := exists2 w, ofQ t w \\in sQ (z_ m) & w \\in [predD Rz & Cn].\n  suffices [m le_n_m [w Cw /andP[C'w Rz_w]]]: exists2 m, (n <= m)%N & extRz m.\n    pose p := minPoly <<Cn; w>> u_z; apply: (IHd (p ^ ofQ t) m).\n      apply: leq_trans le_Rz_d; rewrite size_map_poly size_minPoly ltnS.\n      rewrite adjoin_degreeE adjoinC (addv_idPl Rz_w) agenv_id.\n      rewrite ltn_divLR ?adim_gt0 // mulnC.\n      rewrite muln_divCA ?field_dimS ?subv_adjoin // ltn_Pmulr ?adim_gt0 //.\n      by rewrite -adjoin_degreeE ltnNge leq_eqVlt orbF adjoin_deg_eq1.\n    rewrite map_monic monic_minPoly -Dz fmorph_root root_minPoly /=.\n    have /polyOverP Cw_p: p \\is a polyOver <<Cn; w>>%VS by apply: minPolyOver.\n    apply/polyOver_poly=> j _; have /Fadjoin_polyP[q Cq {j}->] := Cw_p j.\n    rewrite -horner_map rpred_horner //; apply/polyOver_poly=> j _.\n    by rewrite (sCle n) // -memCn (polyOverP Cq).\n  have [evenG | oddG] := boolP (2.-group G); last first.\n    have [P /and3P[sPG evenP oddPG]] := Sylow_exists 2 'Gal(Rz / Rn).\n    have [w defQw] := PET_Qz t [aspace of fixedField P].\n    pose pw := minPoly Rn w; pose p := (- pw * (pw \\Po - 'X)) ^ ofQ t.\n    have sz_pw: (size pw).-1 = #|'Gal(Rz / Rn) : P|.\n      rewrite size_minPoly adjoin_degreeE -dim_fixed_galois //= -defQw.\n      congr (\\dim_Rn _); apply/esym/eqP; rewrite eqEsubv adjoinSl ?sub1v //=.\n      by apply/FadjoinP; rewrite memv_adjoin /= defQw -galois_connection.\n    have mon_p: p \\is monic.\n      have mon_pw: pw \\is monic := monic_minPoly _ _.\n      rewrite map_monic mulNr -mulrN monicMl // monicE.\n      rewrite !(lead_coef_opp, lead_coef_comp) ?size_opp ?size_polyX //.\n      by rewrite lead_coefX sz_pw -signr_odd odd_2'nat oddPG mulrN1 opprK.\n    have Dp0: p.[0] = - ofQ t pw.[0] ^+ 2.\n      rewrite -(rmorph0 (ofQ t)) horner_map hornerM rmorphM.\n      by rewrite horner_comp !hornerN hornerX oppr0 rmorphN mulNr.\n    have Rpw: pw \\is a polyOver Rn by apply: minPolyOver.\n    have Rp: p \\is a polyOver (sQ (x_ n)).\n      apply/polyOver_poly=> j _; rewrite -memRn; apply: polyOverP j => /=.\n      by rewrite rpredM 1?polyOver_comp ?rpredN ?polyOverX.\n    have Rp0: ofQ t pw.[0] \\in sQ (x_ n) by rewrite -memRn rpred_horner ?rpred0.\n    have [|{mon_p Rp Rp0 Dp0}m lenm p_Rm_0] := xRroot n p (ofQ t pw.[0]).\n      by rewrite /has_Rroot mon_p Rp Rp0 -Dp0 /=.\n    have{p_Rm_0} [y Ry pw_y]: {y | y \\in sQ (x_ m) & root (pw ^ ofQ t) y}.\n      apply/sig2W; have [y Ry] := p_Rm_0.\n      rewrite [p]rmorphM /= map_comp_poly !rmorphN /= map_polyX.\n      rewrite rootM rootN root_comp hornerN hornerX.\n      by case/orP; [exists y | exists (- y)]; rewrite ?rpredN.\n    have [u Rz_u Dy]: exists2 u, u \\in Rz & y = ofQ t u.\n      have Rz_w: w \\in Rz by rewrite -sub_adjoin1v defQw capvSl.\n      have [sg [Gsg _ Dpw]] := galois_factors sRnRz galRz w Rz_w.\n      set s := map _ sg in Dpw.\n      have /mapP[u /mapP[g Gg Du] ->]: y \\in map (ofQ t) s.\n        by rewrite -root_prod_XsubC -/(rp C _) -map_rp -[rp _ _]Dpw.\n      by exists u; rewrite // Du memv_gal.\n    have{pw_y} pw_u: root pw u by rewrite -(fmorph_root (ofQ t)) -Dy.\n    exists m => //; exists u; first by rewrite -Dy; apply: sQtrans Ry _.\n    rewrite inE /= Rz_u andbT; apply: contra oddG => Cu.\n    suffices: 2.-group 'Gal(Rz / Rn).\n      apply: pnat_dvd; rewrite -!galois_dim // ?(galoisS _ galQr) ?sRCz //.\n      rewrite dvdn_divLR ?field_dimS ?adim_gt0 //.\n      by rewrite mulnC muln_divCA ?field_dimS ?dvdn_mulr.\n    congr (2.-group _): evenP; apply/eqP.\n    rewrite eqEsubset sPG -indexg_eq1 (pnat_1 _ oddPG) // -sz_pw.\n    have (pu := minPoly Rn u): (pu %= pw) || (pu %= 1).\n      by rewrite minPoly_irr ?minPoly_dvdp ?minPolyOver.\n    rewrite /= -size_poly_eq1 {1}size_minPoly orbF => /eqp_size <-.\n    rewrite size_minPoly /= adjoin_degreeE (@pnat_dvd _ 2) // -dimCn.\n    rewrite dvdn_divLR ?divnK ?adim_gt0 ?field_dimS ?subv_adjoin //.\n    exact/FadjoinP.\n  have [w Rz_w deg_w]: exists2 w, w \\in Rz & adjoin_degree Cn w = 2.\n    have [P sPG iPG]: exists2 P : {group gal_of Rz}, P \\subset G & #|G : P| = 2.\n      have [_ _ [k oG]] := pgroup_pdiv evenG ntG.\n      have [P [sPG _ oP]] := normal_pgroup evenG (normal_refl G) (leq_pred _).\n      by exists P => //; rewrite -divgS // oP oG pfactorK // -expnB ?subSnn.\n    have [w defQw] := PET_Qz _ [aspace of fixedField P].\n    exists w; first by rewrite -sub_adjoin1v defQw capvSl.\n    rewrite adjoin_degreeE -iPG -dim_fixed_galois // -defQw; congr (\\dim_Cn _).\n    apply/esym/eqP; rewrite eqEsubv adjoinSl ?sub1v //=; apply/FadjoinP.\n    by rewrite memv_adjoin /= defQw -galois_connection.\n  have nz2: 2%:R != 0 :> Qt by move/charf0P: (charQ (Q t)) => ->.\n  without loss{deg_w} [C'w Cw2]: w Rz_w / w \\notin Cn /\\ w ^+ 2 \\in Cn.\n    pose p := minPoly Cn w; pose v := p`_1 / 2%:R.\n    have /polyOverP Cp: p \\is a polyOver Cn := minPolyOver Cn w.\n    have Cv: v \\in Cn by rewrite rpred_div ?rpred_nat ?Cp.\n    move/(_ (v + w)); apply; first by rewrite rpredD // subvP_adjoin.\n    split; first by rewrite rpredDl // -adjoin_deg_eq1 deg_w.\n    rewrite addrC -[_ ^+ 2]subr0 -(rootP (root_minPoly Cn w)) -/p.\n    rewrite sqrrD [_ - _]addrAC rpredD ?rpredX // -mulr_natr -mulrA divfK //.\n    rewrite [w ^+ 2 + _]addrC mulrC -rpredN opprB horner_coef.\n    have /monicP := monic_minPoly Cn w; rewrite lead_coefE size_minPoly deg_w.\n    by rewrite 2!big_ord_recl big_ord1 => ->; rewrite mulr1 mul1r addrK Cp.\n  without loss R'w2: w Rz_w C'w Cw2 / w ^+ 2 \\notin Rn.\n    move=> IHw; have [Rw2 | /IHw] := boolP (w ^+ 2 \\in Rn); last exact.\n    have R'it: i_t \\notin Rn by rewrite memRn Dit.\n    pose v := 1 + i_t; have R'v: v \\notin Rn by rewrite rpredDl ?rpred1.\n    have Cv: v \\in Cn by rewrite rpredD ?rpred1 ?memv_adjoin.\n    have nz_v: v != 0 by rewrite (memPnC R'v) ?rpred0.\n    apply: (IHw (v * w)); last 1 [|] || by rewrite fpredMl // subvP_adjoin.\n      by rewrite exprMn rpredM // rpredX.\n    rewrite exprMn fpredMr //=; last by rewrite expf_eq0 (memPnC C'w) ?rpred0.\n    by rewrite sqrrD Dit2 expr1n addrC addKr -mulrnAl fpredMl ?rpred_nat.\n  pose rect_w2 u v := [/\\ u \\in Rn, v \\in Rn & u + i_t * (v * 2%:R) = w ^+ 2].\n  have{Cw2} [u [v [Ru Rv Dw2]]]: {u : Qt & {v | rect_w2 u v}}.\n    rewrite /rect_w2 -(Fadjoin_poly_eq Cw2); set p := Fadjoin_poly Rn i_t _.\n    have /polyOverP Rp: p \\is a polyOver Rn by apply: Fadjoin_polyOver.\n    exists p`_0, (p`_1 / 2%:R); split; rewrite ?rpred_div ?rpred_nat //.\n    rewrite divfK // (horner_coef_wide _ (size_Fadjoin_poly _ _ _)) -/p.\n    by rewrite adjoin_degreeE dimCn big_ord_recl big_ord1 mulr1 mulrC.\n  pose p := Poly [:: - (ofQ t v ^+ 2); 0; - ofQ t u; 0; 1].\n  have [|m lenm [x Rx px0]] := xRroot n p (ofQ t v).\n    rewrite /has_Rroot 2!unfold_in lead_coefE horner_coef0 -memRn Rv.\n    rewrite (@PolyK _ 1) ?oner_eq0 //= !eqxx !rpred0 ?rpred1 ?rpredN //=.\n    by rewrite !andbT rpredX -memRn.\n  suffices [y Cy Dy2]: {y | y \\in sQ (z_ m) & ofQ t w ^+ 2 == y ^+ 2}.\n    exists m => //; exists w; last by rewrite inE C'w.\n    by move: Dy2; rewrite eqf_sqr => /pred2P[]->; rewrite ?rpredN.\n  exists (x + i * (ofQ t v / x)).\n    rewrite rpredD 1?rpredM ?rpred_div //= (sQtrans (x_ m)) //.\n    by rewrite (sRle n) // -memRn.\n  rewrite rootE /horner (@PolyK _ 1) ?oner_eq0 //= ?addr0 ?mul0r in px0.\n  rewrite add0r mul1r -mulrA -expr2 subr_eq0 in px0.\n  have nz_x2: x ^+ 2 != 0.\n    apply: contraNneq R'w2 => y2_0; rewrite -Dw2 mulrCA.\n    suffices /eqP->: v == 0 by rewrite mul0r addr0.\n    by rewrite y2_0 mulr0 eq_sym sqrf_eq0 fmorph_eq0 in px0.\n  apply/eqP/esym/(mulIf nz_x2); rewrite -exprMn -rmorphX -Dw2 rmorphD rmorphM.\n  rewrite Dit mulrDl -expr2 mulrA divfK; last by rewrite expf_eq0 in nz_x2.\n  rewrite mulr_natr addrC sqrrD exprMn Di2 mulN1r -(eqP px0) -mulNr opprB.\n  by rewrite -mulrnAl -mulrnAr -rmorphMn -!mulrDl addrAC subrK.\nhave inFTA n z: (n_ z <= n)%N -> z = ofQ (z_ n) (inQ (z_ n) z).\n  by move/sCle=> le_zn; rewrite inQ_K ?le_zn.\npose is_cj n cj := {in R_ n, cj =1 id} /\\ cj (i_ n) = - i_ n.\nhave /all_sig[cj_ /all_and2[cj_R cj_i]] n: {cj : 'AEnd(Q (z_ n)) | is_cj n cj}.\n  have cj_P: root (minPoly (R_ n) (i_ n) ^ \\1%VF) (- i_ n).\n    rewrite minp_i -(fmorph_root (ofQ _)) !rmorphD !rmorph1 /= !map_polyXn.\n    by rewrite rmorphN inQ_K // rootE hornerD hornerXn hornerC sqrrN Di2 addNr.\n  have cj_M: ahom_in fullv (kHomExtend (R_ n) \\1 (i_ n) (- i_ n)).\n    by rewrite -defRi -k1HomE kHomExtendP ?sub1v ?kHom1.\n  exists (AHom cj_M); split=> [y /kHomExtend_id->|]; first by rewrite ?id_lfunE.\n  by rewrite (kHomExtend_val (kHom1 1 _)).\npose conj_ n z := ofQ _ (cj_ n (inQ _ z)); pose conj z := conj_ (n_ z) z.\nhave conjK n m z: (n_ z <= n)%N -> (n <= m)%N -> conj_ m (conj_ n z) = z.\n  move/sCle=> le_z_n le_n_m; have /le_z_n/sQ_inQ[u <-] := FTA z.\n  have /QtoQ[Qmn QmnE]: z_ n \\in sQ (z_ m) by rewrite (sCle n).\n  rewrite /conj_ ofQ_K -!QmnE !ofQ_K -!comp_lfunE; congr (ofQ _ _).\n  move: u (memRi n u); apply/eqlfun_inP/FadjoinP; split=> /=.\n    apply/eqlfun_inP=> y Ry; rewrite !comp_lfunE !cj_R //.\n    by move: Ry; rewrite -!sQof2 QmnE !inQ_K //; apply: sRle.\n  apply/eqlfunP; rewrite !comp_lfunE cj_i !linearN /=.\n  suffices ->: Qmn (i_ n) = i_ m by rewrite cj_i ?opprK.\n  by apply: (fmorph_inj (ofQ _)); rewrite QmnE !inQ_K.\nhave conjE n z: (n_ z <= n)%N -> conj z = conj_ n z.\n  move/leq_trans=> le_zn; set x := conj z; set y := conj_ n z.\n  have [m [le_xm le_ym le_nm]] := maxn3 (n_ x) (n_ y) n.\n  by have /conjK/=/can_in_inj := leqnn m; apply; rewrite ?conjK // le_zn.\nsuffices conjM: rmorphism conj.\n  exists (RMorphism conjM) => [z | /(_ i)/eqP/idPn[]] /=.\n    by have [n [/conjE-> /(conjK (n_ z))->]] := maxn3 (n_ (conj z)) (n_ z) 0%N.\n  rewrite /conj/conj_ cj_i rmorphN inQ_K // eq_sym -addr_eq0 -mulr2n -mulr_natl.\n  rewrite mulf_neq0 ?(memPnC (R'i 0%N)) ?rpred0 //.\n  by have /charf0P-> := ftrans (fmorph_char QtoC) (char_num _).\ndo 2?split=> [x y|]; last pose n1 := n_ 1.\n- have [m [le_xm le_ym le_xym]] := maxn3 (n_ x) (n_ y) (n_ (x - y)).\n  by rewrite !(conjE m) // (inFTA m x) // (inFTA m y) -?rmorphB /conj_ ?ofQ_K.\n- have [m [le_xm le_ym le_xym]] := maxn3 (n_ x) (n_ y) (n_ (x * y)).\n  by rewrite !(conjE m) // (inFTA m x) // (inFTA m y) -?rmorphM /conj_ ?ofQ_K.\nby rewrite /conj -/n1 -(rmorph1 (ofQ (z_ n1))) /conj_ ofQ_K !rmorph1.\nQed.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/theories/algebraics_fundamentals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7448949827961117}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\nRequire Import ZArith_base.\nRequire Import ZArithRing.\nRequire Import Zcomplements.\nRequire Import Zdiv.\nRequire Import Zgcd_def.\nRequire Import Wf_nat.\n\n(** For compatibility reasons, this Open Scope isn't local as it should *)\n\nOpen Scope Z_scope.\n\n(** This file contains some notions of number theory upon Z numbers:\n     - a divisibility predicate [Zdivide]\n     - a gcd predicate [gcd]\n     - Euclid algorithm [euclid]\n     - a relatively prime predicate [rel_prime]\n     - a prime predicate [prime]\n     - properties of the efficient [Zgcd] function defined in [Zgcd_def]\n*)\n\n(** * Divisibility *)\n\nInductive Zdivide (a b:Z) : Prop :=\n    Zdivide_intro : forall q:Z, b = q * a -> Zdivide a b.\n\n(** Syntax for divisibility *)\n\nNotation \"( a | b )\" := (Zdivide a b) (at level 0) : Z_scope.\n\n(** Results concerning divisibility*)\n\nLemma Zdivide_equiv : forall a b, Zdivide' a b <-> Zdivide a b.\nProof.\n intros a b; split; intros (c,H); exists c; rewrite Zmult_comm; auto.\nQed.\n\nLemma Zdivide_refl : forall a:Z, (a | a).\nProof.\n  intros; apply Zdivide_intro with 1; ring.\nQed.\n\nLemma Zone_divide : forall a:Z, (1 | a).\nProof.\n  intros; apply Zdivide_intro with a; ring.\nQed.\n\nLemma Zdivide_0 : forall a:Z, (a | 0).\nProof.\n  intros; apply Zdivide_intro with 0; ring.\nQed.\n\nHint Resolve Zdivide_refl Zone_divide Zdivide_0: zarith.\n\nLemma Zmult_divide_compat_l : forall a b c:Z, (a | b) -> (c * a | c * b).\nProof.\n  simple induction 1; intros; apply Zdivide_intro with q.\n  rewrite H0; ring.\nQed.\n\nLemma Zmult_divide_compat_r : forall a b c:Z, (a | b) -> (a * c | b * c).\nProof.\n  intros a b c; rewrite (Zmult_comm a c); rewrite (Zmult_comm b c).\n  apply Zmult_divide_compat_l; trivial.\nQed.\n\nHint Resolve Zmult_divide_compat_l Zmult_divide_compat_r: zarith.\n\nLemma Zdivide_plus_r : forall a b c:Z, (a | b) -> (a | c) -> (a | b + c).\nProof.\n  simple induction 1; intros q Hq; simple induction 1; intros q' Hq'.\n  apply Zdivide_intro with (q + q').\n  rewrite Hq; rewrite Hq'; ring.\nQed.\n\nLemma Zdivide_opp_r : forall a b:Z, (a | b) -> (a | - b).\nProof.\n  simple induction 1; intros; apply Zdivide_intro with (- q).\n  rewrite H0; ring.\nQed.\n\nLemma Zdivide_opp_r_rev : forall a b:Z, (a | - b) -> (a | b).\nProof.\n  intros; replace b with (- - b). apply Zdivide_opp_r; trivial. ring.\nQed.\n\nLemma Zdivide_opp_l : forall a b:Z, (a | b) -> (- a | b).\nProof.\n  simple induction 1; intros; apply Zdivide_intro with (- q).\n  rewrite H0; ring.\nQed.\n\nLemma Zdivide_opp_l_rev : forall a b:Z, (- a | b) -> (a | b).\nProof.\n  intros; replace a with (- - a). apply Zdivide_opp_l; trivial. ring.\nQed.\n\nLemma Zdivide_minus_l : forall a b c:Z, (a | b) -> (a | c) -> (a | b - c).\nProof.\n  simple induction 1; intros q Hq; simple induction 1; intros q' Hq'.\n  apply Zdivide_intro with (q - q').\n  rewrite Hq; rewrite Hq'; ring.\nQed.\n\nLemma Zdivide_mult_l : forall a b c:Z, (a | b) -> (a | b * c).\nProof.\n  simple induction 1; intros q Hq; apply Zdivide_intro with (q * c).\n  rewrite Hq; ring.\nQed.\n\nLemma Zdivide_mult_r : forall a b c:Z, (a | c) -> (a | b * c).\nProof.\n  simple induction 1; intros q Hq; apply Zdivide_intro with (q * b).\n  rewrite Hq; ring.\nQed.\n\nLemma Zdivide_factor_r : forall a b:Z, (a | a * b).\nProof.\n  intros; apply Zdivide_intro with b; ring.\nQed.\n\nLemma Zdivide_factor_l : forall a b:Z, (a | b * a).\nProof.\n  intros; apply Zdivide_intro with b; ring.\nQed.\n\nHint Resolve Zdivide_plus_r Zdivide_opp_r Zdivide_opp_r_rev Zdivide_opp_l\n  Zdivide_opp_l_rev Zdivide_minus_l Zdivide_mult_l Zdivide_mult_r\n  Zdivide_factor_r Zdivide_factor_l: zarith.\n\n(** Auxiliary result. *)\n\nLemma Zmult_one : forall x y:Z, x >= 0 -> x * y = 1 -> x = 1.\nProof.\n  intros x y H H0; destruct (Zmult_1_inversion_l _ _ H0) as [Hpos| Hneg].\n  assumption.\n  rewrite Hneg in H; simpl in H.\n  contradiction (Zle_not_lt 0 (-1)).\n    apply Zge_le; assumption.\n    apply Zorder.Zlt_neg_0.\nQed.\n\n(** Only [1] and [-1] divide [1]. *)\n\nLemma Zdivide_1 : forall x:Z, (x | 1) -> x = 1 \\/ x = -1.\nProof.\n  simple induction 1; intros.\n  elim (Z_lt_ge_dec 0 x); [ left | right ].\n  apply Zmult_one with q; auto with zarith; rewrite H0; ring.\n  assert (- x = 1); auto with zarith.\n  apply Zmult_one with (- q); auto with zarith; rewrite H0; ring.\nQed.\n\n(** If [a] divides [b] and [b] divides [a] then [a] is [b] or [-b]. *)\n\nLemma Zdivide_antisym : forall a b:Z, (a | b) -> (b | a) -> a = b \\/ a = - b.\nProof.\n  simple induction 1; intros.\n  inversion H1.\n  rewrite H0 in H2; clear H H1.\n  case (Z_zerop a); intro.\n  left; rewrite H0; rewrite e; ring.\n  assert (Hqq0 : q0 * q = 1).\n  apply Zmult_reg_l with a.\n  assumption.\n  ring_simplify.\n  pattern a at 2 in |- *; rewrite H2; ring.\n  assert (q | 1).\n  rewrite <- Hqq0; auto with zarith.\n  elim (Zdivide_1 q H); intros.\n  rewrite H1 in H0; left; omega.\n  rewrite H1 in H0; right; omega.\nQed.\n\nTheorem Zdivide_trans: forall a b c, (a | b) -> (b | c) ->  (a | c).\nProof.\n  intros a b c [d H1] [e H2]; exists (d * e); auto with zarith.\n  rewrite H2; rewrite H1; ring.\nQed.\n\n(** If [a] divides [b] and [b<>0] then [|a| <= |b|]. *)\n\nLemma Zdivide_bounds : forall a b:Z, (a | b) -> b <> 0 -> Zabs a <= Zabs b.\nProof.\n  simple induction 1; intros.\n  assert (Zabs b = Zabs q * Zabs a).\n  subst; apply Zabs_Zmult.\n  rewrite H2.\n  assert (H3 := Zabs_pos q).\n  assert (H4 := Zabs_pos a).\n  assert (Zabs q * Zabs a >= 1 * Zabs a); auto with zarith.\n  apply Zmult_ge_compat; auto with zarith.\n  elim (Z_lt_ge_dec (Zabs q) 1); [ intros | auto with zarith ].\n  assert (Zabs q = 0).\n  omega.\n  assert (q = 0).\n  rewrite <- (Zabs_Zsgn q).\n  rewrite H5; auto with zarith.\n  subst q; omega.\nQed.\n\n(** [Zdivide] can be expressed using [Zmod]. *)\n\nLemma Zmod_divide : forall a b, b<>0 -> a mod b = 0 -> (b | a).\nProof.\n intros a b NZ EQ.\n apply Zdivide_intro with (a/b).\n rewrite (Z_div_mod_eq_full a b NZ) at 1.\n rewrite EQ; ring.\nQed.\n\nLemma Zdivide_mod : forall a b, (b | a) -> a mod b = 0.\nProof.\n  intros a b (c,->); apply Z_mod_mult.\nQed.\n\n(** [Zdivide] is hence decidable *)\n\nLemma Zdivide_dec : forall a b:Z, {(a | b)} + {~ (a | b)}.\nProof.\n  intros a b; elim (Ztrichotomy_inf a 0).\n  (* a<0 *)\n  intros H; elim H; intros.\n  case (Z_eq_dec (b mod - a) 0).\n  left; apply Zdivide_opp_l_rev; apply Zmod_divide; auto with zarith.\n  intro H1; right; intro; elim H1; apply Zdivide_mod; auto with zarith.\n  (* a=0 *)\n  case (Z_eq_dec b 0); intro.\n  left; subst; auto with zarith.\n  right; subst; intro H0; inversion H0; omega.\n  (* a>0 *)\n  intro H; case (Z_eq_dec (b mod a) 0).\n  left; apply Zmod_divide; auto with zarith.\n  intro H1; right; intro; elim H1; apply Zdivide_mod; auto with zarith.\nQed.\n\nTheorem Zdivide_Zdiv_eq: forall a b : Z,\n 0 < a -> (a | b) ->  b = a * (b / a).\nProof.\n  intros a b Hb Hc.\n  pattern b at 1; rewrite (Z_div_mod_eq b a); auto with zarith.\n  rewrite (Zdivide_mod b a); auto with zarith.\nQed.\n\nTheorem Zdivide_Zdiv_eq_2: forall a b c : Z,\n 0 < a -> (a | b) -> (c * b)/a = c * (b / a).\nProof.\n  intros a b c H1 H2.\n  inversion H2 as [z Hz].\n  rewrite Hz; rewrite Zmult_assoc.\n  repeat rewrite Z_div_mult; auto with zarith.\nQed.\n\nTheorem Zdivide_Zabs_l: forall a b, (Zabs a | b) ->  (a | b).\nProof.\n  intros a b [x H]; subst b.\n  pattern (Zabs a); apply Zabs_intro.\n  exists (- x); ring.\n  exists x; ring.\nQed.\n\nTheorem Zdivide_Zabs_inv_l: forall a b, (a | b) ->  (Zabs a | b).\nProof.\n  intros a b [x H]; subst b.\n  pattern (Zabs a); apply Zabs_intro.\n  exists (- x);  ring.\n  exists x; ring.\nQed.\n\nTheorem Zdivide_le: forall a b : Z,\n 0 <= a -> 0 < b -> (a | b) ->  a <= b.\nProof.\n  intros a b H1 H2 [q H3]; subst b.\n  case (Zle_lt_or_eq 0 a); auto with zarith; intros H3.\n  case (Zle_lt_or_eq 0 q); auto with zarith.\n  apply (Zmult_le_0_reg_r a); auto with zarith.\n  intros H4; apply Zle_trans with (1 * a); auto with zarith.\n  intros H4; subst q; omega.\nQed.\n\nTheorem Zdivide_Zdiv_lt_pos: forall a b : Z,\n 1 < a -> 0 < b -> (a | b) ->  0 < b / a < b .\nProof.\n  intros a b H1 H2 H3; split.\n  apply Zmult_lt_reg_r with a; auto with zarith.\n  rewrite (Zmult_comm (Zdiv b a)); rewrite <- Zdivide_Zdiv_eq; auto with zarith.\n  apply Zmult_lt_reg_r with a; auto with zarith.\n  repeat rewrite (fun x => Zmult_comm x a); auto with zarith.\n  rewrite <- Zdivide_Zdiv_eq; auto with zarith.\n  pattern b at 1; replace b with (1 * b); auto with zarith.\n  apply Zmult_lt_compat_r; auto with zarith.\nQed.\n\nLemma Zmod_div_mod: forall n m a, 0 < n -> 0 < m ->\n (n | m) -> a mod n = (a mod m) mod n.\nProof.\n  intros n m a H1 H2 H3.\n  pattern a at 1; rewrite (Z_div_mod_eq a m); auto with zarith.\n  case H3; intros q Hq; pattern m at 1; rewrite Hq.\n  rewrite (Zmult_comm q).\n  rewrite Zplus_mod; auto with zarith.\n  rewrite <- Zmult_assoc; rewrite Zmult_mod; auto with zarith.\n  rewrite Z_mod_same; try rewrite Zmult_0_l; auto with zarith.\n  rewrite (Zmod_small 0); auto with zarith.\n  rewrite Zplus_0_l; rewrite Zmod_mod; auto with zarith.\nQed.\n\nLemma Zmod_divide_minus: forall a b c : Z, 0 < b ->\n a mod b = c -> (b | a - c).\nProof.\n  intros a b c H H1; apply Zmod_divide; auto with zarith.\n  rewrite Zminus_mod; auto with zarith.\n  rewrite H1; pattern c at 1; rewrite <- (Zmod_small c b); auto with zarith.\n  rewrite Zminus_diag; apply Zmod_small; auto with zarith.\n  subst; apply Z_mod_lt; auto with zarith.\nQed.\n\nLemma Zdivide_mod_minus: forall a b c : Z, 0 <= c < b ->\n (b | a - c) -> a mod b = c.\nProof.\n  intros a b c (H1, H2) H3; assert (0 < b); try apply Zle_lt_trans with c; auto.\n  replace a with ((a - c) + c); auto with zarith.\n  rewrite Zplus_mod; auto with zarith.\n  rewrite (Zdivide_mod (a -c) b); try rewrite Zplus_0_l; auto with zarith.\n  rewrite Zmod_mod; try apply Zmod_small; auto with zarith.\nQed.\n\n(** * Greatest common divisor (gcd). *)\n\n(** There is no unicity of the gcd; hence we define the predicate [gcd a b d]\n     expressing that [d] is a gcd of [a] and [b].\n     (We show later that the [gcd] is actually unique if we discard its sign.) *)\n\nInductive Zis_gcd (a b d:Z) : Prop :=\n  Zis_gcd_intro :\n  (d | a) ->\n  (d | b) -> (forall x:Z, (x | a) -> (x | b) -> (x | d)) -> Zis_gcd a b d.\n\n(** Trivial properties of [gcd] *)\n\nLemma Zis_gcd_sym : forall a b d:Z, Zis_gcd a b d -> Zis_gcd b a d.\nProof.\n  simple induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_0 : forall a:Z, Zis_gcd a 0 a.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_1 : forall a, Zis_gcd a 1 1.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_refl : forall a, Zis_gcd a a a.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_minus : forall a b d:Z, Zis_gcd a (- b) d -> Zis_gcd b a d.\nProof.\n  simple induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_opp : forall a b d:Z, Zis_gcd a b d -> Zis_gcd b a (- d).\nProof.\n  simple induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_0_abs : forall a:Z, Zis_gcd 0 a (Zabs a).\nProof.\n  intros a.\n  apply Zabs_ind.\n  intros; apply Zis_gcd_sym; apply Zis_gcd_0; auto.\n  intros; apply Zis_gcd_opp; apply Zis_gcd_0; auto.\nQed.\n\nHint Resolve Zis_gcd_sym Zis_gcd_0 Zis_gcd_minus Zis_gcd_opp: zarith.\n\nTheorem Zis_gcd_unique: forall a b c d : Z,\n Zis_gcd a b c -> Zis_gcd a b d ->  c = d \\/ c = (- d).\nProof.\nintros a b c d H1 H2.\ninversion_clear H1 as [Hc1 Hc2 Hc3].\ninversion_clear H2 as [Hd1 Hd2 Hd3].\nassert (H3: Zdivide c d); auto.\nassert (H4: Zdivide d c); auto.\napply Zdivide_antisym; auto.\nQed.\n\n\n(** * Extended Euclid algorithm. *)\n\n(** Euclid's algorithm to compute the [gcd] mainly relies on\n    the following property. *)\n\nLemma Zis_gcd_for_euclid :\n  forall a b d q:Z, Zis_gcd b (a - q * b) d -> Zis_gcd a b d.\nProof.\n  simple induction 1; constructor; intuition.\n  replace a with (a - q * b + q * b). auto with zarith. ring.\nQed.\n\nLemma Zis_gcd_for_euclid2 :\n  forall b d q r:Z, Zis_gcd r b d -> Zis_gcd b (b * q + r) d.\nProof.\n  simple induction 1; constructor; intuition.\n  apply H2; auto.\n  replace r with (b * q + r - b * q). auto with zarith. ring.\nQed.\n\n(** We implement the extended version of Euclid's algorithm,\n    i.e. the one computing Bezout's coefficients as it computes\n    the [gcd]. We follow the algorithm given in Knuth's\n    \"Art of Computer Programming\", vol 2, page 325. *)\n\nSection extended_euclid_algorithm.\n\n  Variables a b : Z.\n\n  (** The specification of Euclid's algorithm is the existence of\n      [u], [v] and [d] such that [ua+vb=d] and [(gcd a b d)]. *)\n\n  Inductive Euclid : Set :=\n    Euclid_intro :\n    forall u v d:Z, u * a + v * b = d -> Zis_gcd a b d -> Euclid.\n\n  (** The recursive part of Euclid's algorithm uses well-founded\n      recursion of non-negative integers. It maintains 6 integers\n      [u1,u2,u3,v1,v2,v3] such that the following invariant holds:\n      [u1*a+u2*b=u3] and [v1*a+v2*b=v3] and [gcd(u3,v3)=gcd(a,b)].\n      *)\n\n  Lemma euclid_rec :\n    forall v3:Z,\n      0 <= v3 ->\n      forall u1 u2 u3 v1 v2:Z,\n\tu1 * a + u2 * b = u3 ->\n\tv1 * a + v2 * b = v3 ->\n\t(forall d:Z, Zis_gcd u3 v3 d -> Zis_gcd a b d) -> Euclid.\n  Proof.\n    intros v3 Hv3; generalize Hv3; pattern v3 in |- *.\n    apply Zlt_0_rec.\n    clear v3 Hv3; intros.\n    elim (Z_zerop x); intro.\n    apply Euclid_intro with (u := u1) (v := u2) (d := u3).\n    assumption.\n    apply H3.\n    rewrite a0; auto with zarith.\n    set (q := u3 / x) in *.\n    assert (Hq : 0 <= u3 - q * x < x).\n    replace (u3 - q * x) with (u3 mod x).\n    apply Z_mod_lt; omega.\n    assert (xpos : x > 0). omega.\n    generalize (Z_div_mod_eq u3 x xpos).\n    unfold q in |- *.\n    intro eq; pattern u3 at 2 in |- *; rewrite eq; ring.\n    apply (H (u3 - q * x) Hq (proj1 Hq) v1 v2 x (u1 - q * v1) (u2 - q * v2)).\n    tauto.\n    replace ((u1 - q * v1) * a + (u2 - q * v2) * b) with\n      (u1 * a + u2 * b - q * (v1 * a + v2 * b)).\n    rewrite H1; rewrite H2; trivial.\n    ring.\n    intros; apply H3.\n    apply Zis_gcd_for_euclid with q; assumption.\n    assumption.\n  Qed.\n\n  (** We get Euclid's algorithm by applying [euclid_rec] on\n      [1,0,a,0,1,b] when [b>=0] and [1,0,a,0,-1,-b] when [b<0]. *)\n\n  Lemma euclid : Euclid.\n  Proof.\n    case (Z_le_gt_dec 0 b); intro.\n    intros;\n      apply euclid_rec with\n\t(u1 := 1) (u2 := 0) (u3 := a) (v1 := 0) (v2 := 1) (v3 := b);\n\tauto with zarith; ring.\n    intros;\n      apply euclid_rec with\n\t(u1 := 1) (u2 := 0) (u3 := a) (v1 := 0) (v2 := -1) (v3 := - b);\n\tauto with zarith; try ring.\n  Qed.\n\nEnd extended_euclid_algorithm.\n\nTheorem Zis_gcd_uniqueness_apart_sign :\n  forall a b d d':Z, Zis_gcd a b d -> Zis_gcd a b d' -> d = d' \\/ d = - d'.\nProof.\n  simple induction 1.\n  intros H1 H2 H3; simple induction 1; intros.\n  generalize (H3 d' H4 H5); intro Hd'd.\n  generalize (H6 d H1 H2); intro Hdd'.\n  exact (Zdivide_antisym d d' Hdd' Hd'd).\nQed.\n\n(** * Bezout's coefficients *)\n\nInductive Bezout (a b d:Z) : Prop :=\n  Bezout_intro : forall u v:Z, u * a + v * b = d -> Bezout a b d.\n\n(** Existence of Bezout's coefficients for the [gcd] of [a] and [b] *)\n\nLemma Zis_gcd_bezout : forall a b d:Z, Zis_gcd a b d -> Bezout a b d.\nProof.\n  intros a b d Hgcd.\n  elim (euclid a b); intros u v d0 e g.\n  generalize (Zis_gcd_uniqueness_apart_sign a b d d0 Hgcd g).\n  intro H; elim H; clear H; intros.\n  apply Bezout_intro with u v.\n  rewrite H; assumption.\n  apply Bezout_intro with (- u) (- v).\n  rewrite H; rewrite <- e; ring.\nQed.\n\n(** gcd of [ca] and [cb] is [c gcd(a,b)]. *)\n\nLemma Zis_gcd_mult :\n  forall a b c d:Z, Zis_gcd a b d -> Zis_gcd (c * a) (c * b) (c * d).\nProof.\n  intros a b c d; simple induction 1; constructor; intuition.\n  elim (Zis_gcd_bezout a b d H). intros.\n  elim H3; intros.\n  elim H4; intros.\n  apply Zdivide_intro with (u * q + v * q0).\n  rewrite <- H5.\n  replace (c * (u * a + v * b)) with (u * (c * a) + v * (c * b)).\n  rewrite H6; rewrite H7; ring.\n  ring.\nQed.\n\n\n(** * Relative primality *)\n\nDefinition rel_prime (a b:Z) : Prop := Zis_gcd a b 1.\n\n(** Bezout's theorem: [a] and [b] are relatively prime if and\n    only if there exist [u] and [v] such that [ua+vb = 1]. *)\n\nLemma rel_prime_bezout : forall a b:Z, rel_prime a b -> Bezout a b 1.\nProof.\n  intros a b; exact (Zis_gcd_bezout a b 1).\nQed.\n\nLemma bezout_rel_prime : forall a b:Z, Bezout a b 1 -> rel_prime a b.\nProof.\n  simple induction 1; constructor; auto with zarith.\n  intros. rewrite <- H0; auto with zarith.\nQed.\n\n(** Gauss's theorem: if [a] divides [bc] and if [a] and [b] are\n    relatively prime, then [a] divides [c]. *)\n\nTheorem Gauss : forall a b c:Z, (a | b * c) -> rel_prime a b -> (a | c).\nProof.\n  intros. elim (rel_prime_bezout a b H0); intros.\n  replace c with (c * 1); [ idtac | ring ].\n  rewrite <- H1.\n  replace (c * (u * a + v * b)) with (c * u * a + v * (b * c));\n    [ eauto with zarith | ring ].\nQed.\n\n(** If [a] is relatively prime to [b] and [c], then it is to [bc] *)\n\nLemma rel_prime_mult :\n  forall a b c:Z, rel_prime a b -> rel_prime a c -> rel_prime a (b * c).\nProof.\n  intros a b c Hb Hc.\n  elim (rel_prime_bezout a b Hb); intros.\n  elim (rel_prime_bezout a c Hc); intros.\n  apply bezout_rel_prime.\n  apply Bezout_intro with\n    (u := u * u0 * a + v0 * c * u + u0 * v * b) (v := v * v0).\n  rewrite <- H.\n  replace (u * a + v * b) with ((u * a + v * b) * 1); [ idtac | ring ].\n  rewrite <- H0.\n  ring.\nQed.\n\nLemma rel_prime_cross_prod :\n  forall a b c d:Z,\n    rel_prime a b ->\n    rel_prime c d -> b > 0 -> d > 0 -> a * d = b * c -> a = c /\\ b = d.\nProof.\n  intros a b c d; intros.\n  elim (Zdivide_antisym b d).\n  split; auto with zarith.\n  rewrite H4 in H3.\n  rewrite Zmult_comm in H3.\n  apply Zmult_reg_l with d; auto with zarith.\n  intros; omega.\n  apply Gauss with a.\n  rewrite H3.\n  auto with zarith.\n  red in |- *; auto with zarith.\n  apply Gauss with c.\n  rewrite Zmult_comm.\n  rewrite <- H3.\n  auto with zarith.\n  red in |- *; auto with zarith.\nQed.\n\n(** After factorization by a gcd, the original numbers are relatively prime. *)\n\nLemma Zis_gcd_rel_prime :\n  forall a b g:Z,\n    b > 0 -> g >= 0 -> Zis_gcd a b g -> rel_prime (a / g) (b / g).\nProof.\n  intros a b g; intros.\n  assert (g <> 0).\n  intro.\n  elim H1; intros.\n  elim H4; intros.\n  rewrite H2 in H6; subst b; omega.\n  unfold rel_prime in |- *.\n  destruct H1.\n  destruct H1 as (a',H1).\n  destruct H3 as (b',H3).\n  replace (a/g) with a';\n    [|rewrite H1; rewrite Z_div_mult; auto with zarith].\n  replace (b/g) with b';\n    [|rewrite H3; rewrite Z_div_mult; auto with zarith].\n  constructor.\n  exists a'; auto with zarith.\n  exists b'; auto with zarith.\n  intros x (xa,H5) (xb,H6).\n  destruct (H4 (x*g)).\n  exists xa; rewrite Zmult_assoc; rewrite <- H5; auto.\n  exists xb; rewrite Zmult_assoc; rewrite <- H6; auto.\n  replace g with (1*g) in H7; auto with zarith.\n  do 2 rewrite Zmult_assoc in H7.\n  generalize (Zmult_reg_r _ _ _ H2 H7); clear H7; intros.\n  rewrite Zmult_1_r in H7.\n  exists q; auto with zarith.\nQed.\n\nTheorem rel_prime_sym: forall a b, rel_prime a b -> rel_prime b a.\nProof.\n  intros a b H; auto with zarith.\n  red; apply Zis_gcd_sym; auto with zarith.\nQed.\n\nTheorem rel_prime_div: forall p q r,\n rel_prime p q -> (r | p) -> rel_prime r q.\nProof.\n  intros p q r H (u, H1); subst.\n  inversion_clear H as [H1 H2 H3].\n  red; apply Zis_gcd_intro; try apply Zone_divide.\n  intros x H4 H5; apply H3; auto.\n  apply Zdivide_mult_r; auto.\nQed.\n\nTheorem rel_prime_1: forall n, rel_prime 1 n.\nProof.\n  intros n; red; apply Zis_gcd_intro; auto.\n  exists 1; auto with zarith.\n  exists n; auto with zarith.\nQed.\n\nTheorem not_rel_prime_0: forall n, 1 < n -> ~ rel_prime 0 n.\nProof.\n  intros n H H1; absurd (n = 1 \\/ n = -1).\n  intros [H2 | H2]; subst; contradict H; auto with zarith.\n  case (Zis_gcd_unique  0 n n 1); auto.\n  apply Zis_gcd_intro; auto.\n  exists 0; auto with zarith.\n  exists 1; auto with zarith.\nQed.\n\nTheorem rel_prime_mod: forall p q, 0 < q ->\n rel_prime p q -> rel_prime (p mod q) q.\nProof.\n  intros p q H H0.\n  assert (H1: Bezout p q 1).\n  apply rel_prime_bezout; auto.\n  inversion_clear H1 as [q1 r1 H2].\n  apply bezout_rel_prime.\n  apply Bezout_intro with q1  (r1 + q1 * (p / q)).\n  rewrite <- H2.\n  pattern p at 3; rewrite (Z_div_mod_eq p q); try ring; auto with zarith.\nQed.\n\nTheorem rel_prime_mod_rev: forall p q, 0 < q ->\n rel_prime (p mod q) q -> rel_prime p q.\nProof.\n  intros p q H H0.\n  rewrite (Z_div_mod_eq p q); auto with zarith; red.\n  apply Zis_gcd_sym; apply Zis_gcd_for_euclid2; auto with zarith.\nQed.\n\nTheorem Zrel_prime_neq_mod_0: forall a b, 1 < b -> rel_prime a b -> a mod b <> 0.\nProof.\n  intros a b H H1 H2.\n  case (not_rel_prime_0 _ H).\n  rewrite <- H2.\n  apply rel_prime_mod; auto with zarith.\nQed.\n\n(** * Primality *)\n\nInductive prime (p:Z) : Prop :=\n  prime_intro :\n    1 < p -> (forall n:Z, 1 <= n < p -> rel_prime n p) -> prime p.\n\n(** The sole divisors of a prime number [p] are [-1], [1], [p] and [-p]. *)\n\nLemma prime_divisors :\n  forall p:Z,\n    prime p -> forall a:Z, (a | p) -> a = -1 \\/ a = 1 \\/ a = p \\/ a = - p.\nProof.\n  simple induction 1; intros.\n  assert\n    (a = - p \\/ - p < a < -1 \\/ a = -1 \\/ a = 0 \\/ a = 1 \\/ 1 < a < p \\/ a = p).\n  assert (Zabs a <= Zabs p). apply Zdivide_bounds; [ assumption | omega ].\n  generalize H3.\n  pattern (Zabs a) in |- *; apply Zabs_ind; pattern (Zabs p) in |- *;\n    apply Zabs_ind; intros; omega.\n  intuition idtac.\n  (* -p < a < -1 *)\n  absurd (rel_prime (- a) p); intuition.\n  inversion H3.\n  assert (- a | - a); auto with zarith.\n  assert (- a | p); auto with zarith.\n  generalize (H8 (- a) H9 H10); intuition idtac.\n  generalize (Zdivide_1 (- a) H11); intuition.\n  (* a = 0 *)\n  inversion H2. subst a; omega.\n  (* 1 < a < p *)\n  absurd (rel_prime a p); intuition.\n  inversion H3.\n  assert (a | a); auto with zarith.\n  assert (a | p); auto with zarith.\n  generalize (H8 a H9 H10); intuition idtac.\n  generalize (Zdivide_1 a H11); intuition.\nQed.\n\n(** A prime number is relatively prime with any number it does not divide *)\n\nLemma prime_rel_prime :\n  forall p:Z, prime p -> forall a:Z, ~ (p | a) -> rel_prime p a.\nProof.\n  simple induction 1; intros.\n  constructor; intuition.\n  elim (prime_divisors p H x H3); intuition; subst; auto with zarith.\n  absurd (p | a); auto with zarith.\n  absurd (p | a); intuition.\nQed.\n\nHint Resolve prime_rel_prime: zarith.\n\n(** As a consequence, a prime number is relatively prime with smaller numbers *)\n\nTheorem rel_prime_le_prime:\n forall a p, prime p -> 1 <=  a < p -> rel_prime a p.\nProof.\n  intros a p Hp [H1 H2].\n  apply rel_prime_sym; apply prime_rel_prime; auto.\n  intros [q Hq]; subst a.\n  case (Zle_or_lt q 0); intros Hl.\n  absurd (q * p <= 0 * p); auto with zarith.\n  absurd (1 * p <= q * p); auto with zarith.\nQed.\n\n\n(** If a prime [p] divides [ab] then it divides either [a] or [b] *)\n\nLemma prime_mult :\n  forall p:Z, prime p -> forall a b:Z, (p | a * b) -> (p | a) \\/ (p | b).\nProof.\n  intro p; simple induction 1; intros.\n  case (Zdivide_dec p a); intuition.\n  right; apply Gauss with a; auto with zarith.\nQed.\n\nLemma not_prime_0: ~ prime 0.\nProof.\n  intros H1; case (prime_divisors _ H1 2); auto with zarith.\nQed.\n\nLemma not_prime_1: ~ prime 1.\nProof.\n  intros H1; absurd (1 < 1); auto with zarith.\n  inversion H1; auto.\nQed.\n\nLemma prime_2: prime 2.\nProof.\n  apply prime_intro; auto with zarith.\n  intros n [H1 H2]; case Zle_lt_or_eq with ( 1 := H1 ); auto with zarith;\n   clear H1; intros H1.\n  contradict H2; auto with zarith.\n  subst n; red; auto with zarith.\n  apply Zis_gcd_intro; auto with zarith.\nQed.\n\nTheorem prime_3: prime 3.\nProof.\n  apply prime_intro; auto with zarith.\n  intros n [H1 H2]; case Zle_lt_or_eq with ( 1 := H1 ); auto with zarith;\n   clear H1; intros H1.\n  case (Zle_lt_or_eq 2 n); auto with zarith; clear H1; intros H1.\n  contradict H2; auto with zarith.\n  subst n; red; auto with zarith.\n  apply Zis_gcd_intro; auto with zarith.\n  intros x [q1 Hq1] [q2 Hq2].\n  exists (q2 - q1).\n  apply trans_equal with (3 - 2); auto with zarith.\n  rewrite Hq1; rewrite Hq2; ring.\n  subst n; red; auto with zarith.\n  apply Zis_gcd_intro; auto with zarith.\nQed.\n\nTheorem prime_ge_2: forall p, prime p ->  2 <= p.\nProof.\n  intros p Hp; inversion Hp; auto with zarith.\nQed.\n\nDefinition prime' p := 1<p /\\ (forall n, 1<n<p -> ~ (n|p)).\n\nTheorem prime_alt:\n forall p, prime' p <-> prime p.\nProof.\n  split; destruct 1; intros.\n  (* prime -> prime' *)\n  constructor; auto; intros.\n  red; apply Zis_gcd_intro; auto with zarith; intros.\n  case (Zle_lt_or_eq 0 (Zabs x)); auto with zarith; intros H6.\n  case (Zle_lt_or_eq 1 (Zabs x)); auto with zarith; intros H7.\n  case (Zle_lt_or_eq (Zabs x) p); auto with zarith.\n  apply Zdivide_le; auto with zarith.\n  apply Zdivide_Zabs_inv_l; auto.\n  intros H8; case (H0 (Zabs x)); auto.\n  apply Zdivide_Zabs_inv_l; auto.\n  intros H8; subst p; absurd (Zabs x <= n); auto with zarith.\n  apply Zdivide_le; auto with zarith.\n  apply Zdivide_Zabs_inv_l; auto.\n  rewrite H7; pattern (Zabs x); apply Zabs_intro; auto with zarith.\n  absurd (0%Z = p); auto with zarith.\n  assert (x=0) by (destruct x; simpl in *; now auto).\n  subst x; elim H3; intro q; rewrite Zmult_0_r; auto.\n  (* prime' -> prime *)\n  split; auto; intros.\n  intros H2.\n  case (Zis_gcd_unique n p n 1); auto with zarith.\n  apply Zis_gcd_intro; auto with zarith.\n  apply H0; auto with zarith.\nQed.\n\nTheorem square_not_prime: forall a, ~ prime (a * a).\nProof.\n  intros a Ha.\n  rewrite <- (Zabs_square a) in Ha.\n  assert (0 <= Zabs a) by auto with zarith.\n  set (b:=Zabs a) in *; clearbody b.\n  rewrite <- prime_alt in Ha; destruct Ha.\n  case (Zle_lt_or_eq 0 b); auto with zarith; intros Hza1; [ | subst; omega].\n  case (Zle_lt_or_eq 1 b); auto with zarith; intros Hza2; [ | subst; omega].\n  assert (Hza3 := Zmult_lt_compat_r 1 b b Hza1 Hza2).\n  rewrite Zmult_1_l in Hza3.\n  elim (H1 _ (conj Hza2 Hza3)).\n  exists b; auto.\nQed.\n\nTheorem prime_div_prime: forall p q,\n prime p -> prime q -> (p | q) -> p = q.\nProof.\n  intros p q H H1 H2;\n  assert (Hp: 0 < p); try apply Zlt_le_trans with 2; try apply prime_ge_2; auto with zarith.\n  assert (Hq: 0 < q); try apply Zlt_le_trans with 2; try apply prime_ge_2; auto with zarith.\n  case prime_divisors with (2 := H2); auto.\n  intros H4; contradict Hp; subst; auto with zarith.\n  intros [H4| [H4 | H4]]; subst; auto.\n  contradict H; auto; apply not_prime_1.\n  contradict Hp; auto with zarith.\nQed.\n\n(** we now prove that Zgcd (defined in Zgcd_def) is indeed a gcd in\n   the sense of Zis_gcd. *)\n\nNotation Zgcd_is_pos := Zgcd_nonneg (only parsing).\n\nLemma Zgcd_is_gcd : forall a b, Zis_gcd a b (Zgcd a b).\nProof.\n constructor; intros; apply Zdivide_equiv.\n apply Zgcd_divide_l.\n apply Zgcd_divide_r.\n apply Zgcd_greatest; now apply Zdivide_equiv.\nQed.\n\nTheorem Zgcd_spec : forall x y : Z, {z : Z | Zis_gcd x y z /\\ 0 <= z}.\nProof.\n  intros x y; exists (Zgcd x y).\n  split; [apply Zgcd_is_gcd  | apply Zgcd_is_pos].\nQed.\n\nTheorem Zdivide_Zgcd: forall p q r : Z,\n (p | q) -> (p | r) -> (p | Zgcd q r).\nProof.\n  intros p q r H1 H2.\n  assert (H3: (Zis_gcd q r (Zgcd q r))).\n  apply Zgcd_is_gcd.\n  inversion_clear H3; auto.\nQed.\n\nTheorem Zis_gcd_gcd: forall a b c : Z,\n 0 <= c ->  Zis_gcd a b c -> Zgcd a b = c.\nProof.\n  intros a b c H1 H2.\n  case (Zis_gcd_uniqueness_apart_sign a b c (Zgcd a b)); auto.\n  apply Zgcd_is_gcd; auto.\n  case Zle_lt_or_eq with (1 := H1); clear H1; intros H1; subst; auto.\n  intros H3; subst.\n  generalize (Zgcd_is_pos a b); auto with zarith.\n  case (Zgcd a b); simpl; auto; intros; discriminate.\nQed.\n\nTheorem Zgcd_inv_0_l: forall x y, Zgcd x y = 0 -> x = 0.\nProof.\n  intros x y H.\n  assert (F1: Zdivide 0 x).\n   rewrite <- H.\n   generalize (Zgcd_is_gcd x y); intros HH; inversion HH; auto.\n  inversion F1 as [z H1].\n  rewrite H1; ring.\nQed.\n\nTheorem Zgcd_inv_0_r: forall x y, Zgcd x y = 0 -> y = 0.\nProof.\n  intros x y H.\n  assert (F1: Zdivide 0 y).\n   rewrite <- H.\n   generalize (Zgcd_is_gcd x y); intros HH; inversion HH; auto.\n  inversion F1 as [z H1].\n  rewrite H1; ring.\nQed.\n\nTheorem Zgcd_div_swap0 : forall a b : Z,\n 0 < Zgcd a b ->\n 0 < b ->\n (a / Zgcd a b) * b = a * (b/Zgcd a b).\nProof.\n  intros a b Hg Hb.\n  assert (F := Zgcd_is_gcd a b); inversion F as [F1 F2 F3].\n  pattern b at 2; rewrite (Zdivide_Zdiv_eq (Zgcd a b) b); auto.\n  repeat rewrite Zmult_assoc; f_equal.\n  rewrite Zmult_comm.\n  rewrite <- Zdivide_Zdiv_eq; auto.\nQed.\n\nTheorem Zgcd_div_swap : forall a b c : Z,\n 0 < Zgcd a b ->\n 0 < b ->\n (c * a) / Zgcd a b * b = c * a * (b/Zgcd a b).\nProof.\n  intros a b c Hg Hb.\n  assert (F := Zgcd_is_gcd a b); inversion F as [F1 F2 F3].\n  pattern b at 2; rewrite (Zdivide_Zdiv_eq (Zgcd a b) b); auto.\n  repeat rewrite Zmult_assoc; f_equal.\n  rewrite Zdivide_Zdiv_eq_2; auto.\n  repeat rewrite <- Zmult_assoc; f_equal.\n  rewrite Zmult_comm.\n  rewrite <- Zdivide_Zdiv_eq; auto.\nQed.\n\nLemma Zgcd_comm : forall a b, Zgcd a b = Zgcd b a.\nProof.\n  intros.\n  apply Zis_gcd_gcd.\n  apply Zgcd_is_pos.\n  apply Zis_gcd_sym.\n  apply Zgcd_is_gcd.\nQed.\n\nLemma Zgcd_ass : forall a b c, Zgcd (Zgcd a b) c = Zgcd a (Zgcd b c).\nProof.\n  intros.\n  apply Zis_gcd_gcd.\n  apply Zgcd_is_pos.\n  destruct (Zgcd_is_gcd a b).\n  destruct (Zgcd_is_gcd b c).\n  destruct (Zgcd_is_gcd a (Zgcd b c)).\n  constructor; eauto using Zdivide_trans.\nQed.\n\nLemma Zgcd_Zabs : forall a b, Zgcd (Zabs a) b = Zgcd a b.\nProof.\n  destruct a; simpl; auto.\nQed.\n\nLemma Zgcd_0 : forall a, Zgcd a 0 = Zabs a.\nProof.\n  destruct a; simpl; auto.\nQed.\n\nLemma Zgcd_1 : forall a, Zgcd a 1 = 1.\nProof.\n  intros; apply Zis_gcd_gcd; auto with zarith; apply Zis_gcd_1.\nQed.\nHint Resolve Zgcd_0 Zgcd_1 : zarith.\n\nTheorem Zgcd_1_rel_prime : forall a b,\n Zgcd a b = 1 <-> rel_prime a b.\nProof.\n  unfold rel_prime; split; intro H.\n  rewrite <- H; apply Zgcd_is_gcd.\n  case (Zis_gcd_unique a b (Zgcd a b) 1); auto.\n  apply Zgcd_is_gcd.\n  intros H2; absurd (0 <= Zgcd a b); auto with zarith.\n  generalize (Zgcd_is_pos a b); auto with zarith.\nQed.\n\nDefinition rel_prime_dec: forall a b,\n { rel_prime a b }+{ ~ rel_prime a b }.\nProof.\n  intros a b; case (Z_eq_dec (Zgcd a b) 1); intros H1.\n  left; apply -> Zgcd_1_rel_prime; auto.\n  right; contradict H1; apply <- Zgcd_1_rel_prime; auto.\nDefined.\n\nDefinition prime_dec_aux:\n forall p m,\n  { forall n, 1 < n < m -> rel_prime n p } +\n  { exists n, 1 < n < m  /\\ ~ rel_prime n p }.\nProof.\n  intros p m.\n  case (Z_lt_dec 1 m); intros H1;\n   [ | left; intros; exfalso; omega ].\n  pattern m; apply natlike_rec; auto with zarith.\n  left; intros; exfalso; omega.\n  intros x Hx IH; destruct IH as [F|E].\n  destruct (rel_prime_dec x p) as [Y|N].\n  left; intros n [HH1 HH2].\n  case (Zgt_succ_gt_or_eq x n); auto with zarith.\n  intros HH3; subst x; auto.\n  case (Z_lt_dec 1 x); intros HH1.\n  right; exists x; split; auto with zarith.\n  left; intros n [HHH1 HHH2]; contradict HHH1; auto with zarith.\n  right; destruct E as (n,((H0,H2),H3)); exists n; auto with zarith.\nDefined.\n\nDefinition prime_dec: forall p, { prime p }+{ ~ prime p }.\nProof.\n  intros p; case (Z_lt_dec 1 p); intros H1.\n  case (prime_dec_aux p p); intros H2.\n  left; apply prime_intro; auto.\n  intros n [Hn1 Hn2]; case Zle_lt_or_eq with ( 1 := Hn1 ); auto.\n  intros HH; subst n.\n  red; apply Zis_gcd_intro; auto with zarith.\n  right; intros H3; inversion_clear H3 as [Hp1 Hp2].\n  case H2; intros n [Hn1 Hn2]; case Hn2; auto with zarith.\n  right; intros H3; inversion_clear H3 as [Hp1 Hp2]; case H1; auto.\nDefined.\n\nTheorem not_prime_divide:\n forall p, 1 < p -> ~ prime p -> exists n, 1 < n < p  /\\ (n | p).\nProof.\n  intros p Hp Hp1.\n  case (prime_dec_aux p p); intros H1.\n  elim Hp1; constructor; auto.\n  intros n [Hn1 Hn2].\n  case Zle_lt_or_eq with ( 1 := Hn1 ); auto with zarith.\n  intros H2; subst n; red; apply Zis_gcd_intro; auto with zarith.\n  case H1; intros n [Hn1 Hn2].\n  generalize (Zgcd_is_pos n p); intros Hpos.\n  case (Zle_lt_or_eq 0 (Zgcd n p)); auto with zarith; intros H3.\n  case (Zle_lt_or_eq 1 (Zgcd n p)); auto with zarith; intros H4.\n  exists (Zgcd n p); split; auto.\n  split; auto.\n  apply Zle_lt_trans with n; auto with zarith.\n  generalize (Zgcd_is_gcd n p); intros tmp; inversion_clear tmp as [Hr1 Hr2 Hr3].\n  case Hr1; intros q Hq.\n  case (Zle_or_lt q 0); auto with zarith; intros Ht.\n  absurd (n <= 0 * Zgcd n p) ; auto with zarith.\n  pattern n at 1; rewrite Hq; auto with zarith.\n  apply Zle_trans with (1 * Zgcd n p); auto with zarith.\n  pattern n at 2; rewrite Hq; auto with zarith.\n  generalize (Zgcd_is_gcd n p); intros Ht; inversion Ht; auto.\n  case Hn2; red.\n  rewrite H4; apply Zgcd_is_gcd.\n  generalize (Zgcd_is_gcd n p); rewrite <- H3; intros tmp;\n  inversion_clear tmp as [Hr1 Hr2 Hr3].\n  absurd (n = 0); auto with zarith.\n  case Hr1; auto with zarith.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/ZArith/Znumtheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7448587908811505}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural :=\n  plus (Succ lf1) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj141_coqofml_dcE0ip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7448587881577211}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (x : natural) : natural :=\n  plus lf3 (mult x lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj142_coqofml_XCNQAM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7448587787109829}}
{"text": "(*2.2.2 Booléens avec typage polymorphe *)\n\n(*1*)\n(* Définition des booléens *)\nDefinition pbool : Set := forall T : Set, T -> T -> T.\nDefinition ptr : pbool := fun T : Set => fun x : T => fun y : T => x. (* TRUE *)\nDefinition pfa :  pbool := fun T : Set => fun x : T => fun y : T => y. (* FALSE *)\n\nCompute ptr.\nCompute pfa.\n\n(*2*)\n(* Codage de la négation (Première version) *)\nDefinition neg_bool_1 : pbool->pbool := fun b => fun T : Set => fun x y => b T y x.\nCompute neg_bool_1 ptr. \nCompute neg_bool_1 pfa.\n\n(* Codage de la négation (Deuxième version) *)\nDefinition neg_bool_2 : pbool->pbool := fun b => fun T : Set => b(T->T->T)(fun x y => y)(fun x y => x).\nCompute neg_bool_2 ptr.\nCompute neg_bool_2 pfa.\n\n(*3*)\n(* Definition de la conjonction *)\nDefinition conj : pbool-> pbool->pbool := fun a b => fun T:Set => fun x y  => a T (b T x y) y.\nCompute conj ptr pfa.\nCompute conj ptr ptr.\nCompute conj pfa ptr.\nCompute conj pfa pfa.\n\n(* Definition de la disjonction *)\nDefinition disj : pbool->pbool->pbool := fun a b => fun T:Set => fun x y : T => a T x (b T x y).\nCompute disj ptr pfa.\nCompute disj pfa pfa.\nCompute disj pfa ptr.\nCompute disj ptr ptr.\n\n(*4*)\n(* Definition de la fonction pbool *)\nDefinition cond : pbool->nat := fun b : pbool => b nat 3 5.\nCompute cond ptr.\nCompute cond pfa.\nCompute cond (neg_bool_1 ptr).\nCompute cond (neg_bool_1 (neg_bool_2 ptr)). (* (!(!1)=1) => 3 *)\nCompute cond (conj ptr (neg_bool_1(neg_bool_2 ptr))). (* (1 & ((!(!1))=1)=>3) *)\nCompute cond (disj ptr (neg_bool_1(neg_bool_2 pfa))). (* (1 | ((!(!0))=0))=>3 *)\nCompute cond (disj pfa (neg_bool_1 ptr)). (* (0 | !1)=>5 *)\n\n(* 5 -- BONUS -- *)\n(* Définition de la fonction qui rend un booléen appliqué à lui même *)\nDefinition id_bool: pbool->pbool := fun b => b pbool b b.\nCompute id_bool ptr.\nCompute id_bool pfa.", "meta": {"author": "hediturki123", "repo": "LambdaCalculus", "sha": "5b7010f8649902f2c77d984a1ea106c11fd0900d", "save_path": "github-repos/coq/hediturki123-LambdaCalculus", "path": "github-repos/coq/hediturki123-LambdaCalculus/LambdaCalculus-5b7010f8649902f2c77d984a1ea106c11fd0900d/2.2.2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7448339091172033}}
{"text": "Require Import Extraction.\nRequire Import Bool List Arith Bool_nat. \nSet Implicit Arguments.\n\n\n(** * Typed Expressions *)\n\n(** In this section, we will build on the initial example by adding additional expression forms that depend on static typing of terms for safety. *)\n\n(** ** Source Language *)\n\nInductive type : Set := Tint | Tbool.\n\nInductive tbinop : type -> type -> type -> Set :=\n| TPlus : tbinop Tint Tint Tint\n| TTimes : tbinop Tint Tint Tint\n| TEq : forall t, tbinop t t Tbool\n| TLt : tbinop Tint Tint Tbool.\n\n\nInductive texp : type -> Set :=\n| TNConst : nat -> texp Tint\n| TBConst : bool -> texp Tbool\n| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\nDefinition typeDenote (t : type) : Set :=\n  match t with\n    | Tint => nat\n    | Tbool => bool\n  end.\n\nDefinition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b in tbinop arg1 arg2 res with\n    | TPlus => plus\n    | TTimes => mult\n    | TEq Tint => beq_nat\n    | TEq Tbool => eqb\n    | TLt => leb\n  end.\n\n\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n    | TNConst n => n\n    | TBConst b => b\n    | TBinop b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nEval simpl in texpDenote (TNConst 42).\n(** [= 42 : typeDenote Tint] *)\n\n(* begin hide *)\nEval simpl in texpDenote (TBConst false).\n(* end hide *)\nEval simpl in texpDenote (TBConst true).\n(** [= true : typeDenote Tbool] *)\n\nEval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2))\n  (TNConst 7)).\n(** [= 28 : typeDenote Tint] *)\n\nEval simpl in texpDenote (TBinop (TEq Tint) (TBinop TPlus (TNConst 2) (TNConst 2))\n  (TNConst 7)).\n(** [= false : typeDenote Tbool] *)\n\nEval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2))\n  (TNConst 7)).\n(** [= true : typeDenote Tbool] *)\n\n\n(** ** Target Language *)\n\nDefinition tstack := list type.\n\nInductive tinstr : tstack -> tstack -> Set :=\n| TiNConst : forall s, nat -> tinstr s (Tint :: s)\n| TiBConst : forall s, bool -> tinstr s (Tbool :: s)\n| TiBinop : forall arg1 arg2 res s,\n  tbinop arg1 arg2 res\n  -> tinstr (arg1 :: arg2 :: s) (res :: s).\n\nInductive tprog : tstack -> tstack -> Set :=\n| TNil : forall s, tprog s s\n| TCons : forall s1 s2 s3,\n  tinstr s1 s2\n  -> tprog s2 s3\n  -> tprog s1 s3.\n\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n    | nil => unit\n    | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n    | TiNConst _ n => fun s => (n, s)\n    | TiBConst _ b => fun s => (b, s)\n    | TiBinop _ b => fun s =>\n      let '(arg1, (arg2, s')) := s in\n        ((tbinopDenote b) arg1 arg2, s')\n  end.\n\n\nFixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n    | TNil _ => fun s => s\n    | TCons i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\n(** ** Translation *)\n\nFixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n    | TNil _ => fun p' => p'\n    | TCons i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=\n  match e with\n    | TNConst n => TCons (TiNConst _ n) (TNil _)\n    | TBConst b => TCons (TiBConst _ b) (TNil _)\n    | TBinop b e1 e2 => tconcat (tcompile e2 _)\n      (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\nEval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.\n(** [= (42, tt) : vstack (Tint :: nil)] *)\n\nEval simpl in tprogDenote (tcompile (TBConst true) nil) tt.\n(** [= (true, tt) : vstack (Tbool :: nil)] *)\n\nEval simpl in tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2)\n  (TNConst 2)) (TNConst 7)) nil) tt.\n(** [= (28, tt) : vstack (Tint :: nil)] *)\n\nEval simpl in tprogDenote (tcompile (TBinop (TEq Tint) (TBinop TPlus (TNConst 2)\n  (TNConst 2)) (TNConst 7)) nil) tt.\n(** [= (false, tt) : vstack (Tbool :: nil)] *)\n\nEval simpl in tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2))\n  (TNConst 7)) nil) tt.\n(** [= (true, tt) : vstack (Tbool :: nil)] *)\n\n(** %\\smallskip{}%The compiler seems to be working, so let us turn to proving that it _always_ works. *)\n\n\n(** ** Translation Correctness *)\n\n\n(** Again, we need to strengthen the theorem statement so that the induction will go through.  This time, to provide an excuse to demonstrate different tactics, I will develop an alternative approach to this kind of proof, stating the key lemma as: *)\n(* We need an analogue to the [app_assoc_reverse] theorem that we used to rewrite the goal in the last section.  We can abort this proof and prove such a lemma about [tconcat].\n*)\n\n\nLemma tconcat_correct : forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'')\n  (s : vstack ts),\n  tprogDenote (tconcat p p') s\n  = tprogDenote p' (tprogDenote p s).\nProof.\nAdmitted.\n\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n  tprogDenote (tcompile e ts) s = (texpDenote e, s).\nProof.\nAdmitted.\n\nTheorem tcompile_correct : forall t (e : texp t),\n  tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\nProof.\nAdmitted.\n\nExtraction tcompile.\n\n(* End: *)\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/Lab4/MultiSortStackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7447316716071258}}
{"text": "\nInductive 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\nEval compute in ( next_weekday friday ).\nEval compute in ( next_weekday ( next_weekday friday )).\n\nExample test_next_weekday :\n( next_weekday ( next_weekday saturday )) = tuesday.\n\nProof. simpl. reflexivity. Qed.\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 ( x : bool ) ( y : bool ) : bool :=\n  match x with\n  | true => y\n  | false => false\n  end.\n\nDefinition orb ( x : bool ) ( y : bool ) : bool :=\n  match x with\n  | false => y\n  | true => true\n  end.\n\n\nExample test_orb1 : ( orb true false ) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb2 : ( orb false false ) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition nandb ( x : bool ) ( y : bool ) : bool :=\n  match ( x, y ) with\n  | ( true, true ) => false\n  | ( _, _ ) => true\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\nDefinition andb3 ( x : bool ) ( y : bool ) ( z : bool ) : bool :=\n  match ( x, y, z ) with\n  | ( true, true, true ) => true\n  | ( _, _, _ ) => false\n  end.\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 true.\nCheck ( negb false ).\nCheck andb3.\n\nDefinition xorb ( x : bool ) ( y : bool ) : bool :=\n  match x, y with\n  | true, true => false\n  | false, false => false\n  | _, _  => true\n  end.\n\nTheorem xorb_equal : forall a : bool, xorb a a = false.\nProof.\nintros a. destruct a as [ | ].\nreflexivity. reflexivity.\nQed.\n\n\nTheorem xorb_equalleft : forall a b : bool, xorb a b = false -> a = b.\nProof.\nintros a b H. destruct a. destruct b.\nreflexivity. discriminate.\ndestruct b. discriminate. reflexivity.\nQed.\n\n(*\nTheorem xorb_notequal : forall a b : bool, xorb a b = true -> a <> b.\nProof.\nintros a b H.\ndestruct a. destruct b.\ndiscriminate.\nrewrite <- H.\n*)\n\nModule 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 m => m\n  end.\n\nEnd Playground1.\n\nDefinition minustwo ( n : nat ) : nat :=\n  match n with\n  | O => O\n  | S O => O\n  | S ( S m ) => m\n  end.\n\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 :=\n   negb ( evenb n ).\n\nExample test_oddb1: (oddb ( S ( S (S O ) ) ) ) = true.\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.\n\nEval compute in plus ( S O ) ( S ( S O ) ).\n\nExample plus_test : ( plus 3 4 ) = 7.\nProof. simpl. reflexivity. Qed.\n\n(*\nExample plus_comm : forall m n p : nat, plus m ( plus n p ) = plus ( plus m n ) p.\nProof.\nintros m n p.\ndestruct m as [ | ].\nreflexivity.\nsimpl.\nAdmitted.\n*) \n\nFixpoint mult ( m n : nat ) : nat :=\n  match m with\n  | O => O\n  | S m' => plus ( mult m' n ) n\n  end.\n\n\nEval compute in mult 4 9.\n\nExample test_mult : ( 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.\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\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 3) = 6.\nProof. simpl. reflexivity. Qed.\n\n(*\nNotation \"x + y\" := ( plus x y ) ( at level 50, left associativity) : nat_scope.\nNotation \"x - y\" := ( minus x y ) ( at level 50, left associativity) : nat_scope.\nNotation \"x * y\" := ( mult x y ) ( at level 40, left associativity) : nat_scope.\nNotation \"x ^ y\" := ( exp x y ) ( at level 30, right associativity) : nat_scope.\n\nEval simpl in 2^2^3.\n*)\n\nCheck ( 10 + 1 + 2 ).\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 _ => 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' => 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. reflexivity. Qed.\nExample test_ble_nat2: (ble_nat 2 4) = true.\nProof. reflexivity. Qed.\nExample test_ble_nat3: (ble_nat 4 2) = false.\nProof. reflexivity. Qed.\n\nDefinition blt_nat ( n m : nat ) : bool :=\n  andb ( ble_nat n m ) ( negb ( beq_nat n m ) ).\n\nExample test_blt_nat1 : ( blt_nat 3 3 ) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat2 : ( blt_nat 3 4 ) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat3: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat4: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_blt_nat5: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem plus_O_n : forall n : nat, O + n = n.\nProof. intros n. reflexivity. Qed.\n\nTheorem plus_1_n : forall n : nat, 1 + n = S n.\nProof. intros. reflexivity. Qed.\n\nTheorem mult_O_n : forall n : nat, O * n = O.\nProof. intros. reflexivity. Qed.\n\nTheorem plus_id_example : forall m n : nat, m = n -> n + n = m + m.\nProof. intros n m. intros H. rewrite -> H.\nreflexivity. Qed.\n\nTheorem plus_id_exercise : forall n m o : nat,\nn = m -> m = o -> n + m = m + o.\nProof. intros n m o. intros H1 H2.\nrewrite -> H1. rewrite -> H2.\nreflexivity. Qed.\n\nTheorem plus_id_exercise2 : forall n m o : nat,\n    n = m -> n + o = m + o.\nProof. intros n m o. intros H. rewrite -> H. reflexivity. Qed.\n\nTheorem mult_O_plus : forall m n : nat, ( O + n ) * m = n * m.\nProof. intros m n. rewrite -> plus_O_n. reflexivity. Qed.\n\n(*\n\nTheorem mult_comm : forall m n : nat, m * n = n * m.\nProof. Admitted.\n\n*)\n\nTheorem mult_S_1 : forall m n : nat, m = S n -> m * ( 1 + n ) = m * m.\nProof. intros m n. intros H. rewrite -> H. reflexivity. Qed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat, beq_nat (n + 1) 0 = false.\nProof. intros n. destruct n as [ | n']. reflexivity.\nreflexivity. Qed.\n\nTheorem negb_involuted : forall b : bool, negb ( negb b ) = b.\nProof. intros b. destruct b. reflexivity.\nreflexivity. Qed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat, beq_nat 0 ( n + 1 ) = false.\nProof. intros n. destruct n as [ | n' ]. reflexivity.\nreflexivity. Qed.\n\n\nTheorem identity_fn_applied_twice : forall ( f : bool -> bool ),\n          ( forall (x : bool), f x = x ) ->\n          forall (b : bool), f ( f b ) = b.\nProof. intros f H b. rewrite -> H. rewrite -> H. reflexivity. Qed.\n\nTheorem negation_fn_applied_twice : forall (f : bool -> bool),\n          ( forall (x : bool), f x = negb x ) ->\n          forall (b : bool), f (f b) = b.\nProof. intros f H b. rewrite -> H. rewrite -> H. destruct b.\nreflexivity. reflexivity. Qed.\n\nTheorem andb_eq_orb_rev : forall (b c : bool), b = c -> (andb b c = orb b c).\nProof. intros b c H. rewrite -> H. destruct c. reflexivity. reflexivity. Qed.\n\n\nTheorem andb_eq_orb_rev1 : forall (b c : bool), b = c -> (orb b c = orb b c).\nProof. intros b c H. rewrite -> H. destruct c. reflexivity. reflexivity. Qed.\n\nTheorem andb_eq_orb : forall ( a b : bool ), ( andb a b  = orb a b ) -> a = b.\nProof.\nintros a b. destruct a as [ false | true ].\nsimpl. intros H1. rewrite -> H1. reflexivity.\nsimpl. intros H2. rewrite -> H2. reflexivity.\nQed.\n\nInductive bin : Type :=\n  | O' : bin\n  | Twice : bin -> bin\n  | DPlusOne : bin -> bin.\n\nFixpoint inc ( b : bin ) : bin :=\n  match b with\n  | O' => DPlusOne O'\n  | Twice b' => DPlusOne b'\n  | DPlusOne b' => Twice ( inc b' )\n  end.\n\nFixpoint bintonat ( b : bin ) : nat :=\n  match b with\n  | O' => O\n  | Twice b' => plus ( bintonat b' ) ( bintonat b')\n  | DPlusOne b' => plus 1 ( plus ( bintonat b' ) ( bintonat b') )\n  end.\n\nEval compute in bintonat ( Twice ( DPlusOne ( DPlusOne O' ) )).\n\n", "meta": {"author": "tabtab777", "repo": "Coq", "sha": "4ffc37f0c970349ef1942a1519b729c6e5cba581", "save_path": "github-repos/coq/tabtab777-Coq", "path": "github-repos/coq/tabtab777-Coq/Coq-4ffc37f0c970349ef1942a1519b729c6e5cba581/Basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.88242786954645, "lm_q1q2_score": 0.7446765713256882}}
{"text": "(** * Logic: Logic in Coq *)\n\n(* $Date: 2011-06-22 10:06:32 -0400 (Wed, 22 Jun 2011) $ *)\n\nRequire Export \"Prop\". \n\n(** Coq's built-in logic is extremely small: [Inductive] definitions,\n    universal quantification ([forall]), and implication ([->]) are\n    primitive, but all the other familiar logical connectives --\n    conjunction, disjunction, negation, existential quantification,\n    even equality -- can be defined using just these. *)\n\n(* ########################################################### *)\n(** * Quantification and Implication *)\n\n(** In fact, [->] and [forall] are the _same_ primitive!  Coq's [->]\n    notation is actually just a shorthand for [forall].  The [forall]\n    notation is more general, because it allows us to _name_ the\n    hypothesis. *)\n\n(** For example, consider this proposition: *)\n\nDefinition funny_prop1 := forall n, forall (E : ev n), ev (n+4).\n\n(** If we had a proof term inhabiting this proposition, it would be a\n    function with two arguments: a number [n] and some evidence that\n    [n] is even.  But the name [E] for this evidence is not used in\n    the rest of the statement of [funny_prop1], so it's a bit silly to\n    bother making up a name.  We could write it like this instead: *)\n\nDefinition funny_prop1' := forall n, forall (_ : ev n), ev (n+4).\n\n(** Or we can write it in more familiar notation: *)\n\nDefinition funny_prop1'' := forall n, ev n -> ev (n+4).\n\n(** This illustrates that \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ########################################################### *)\n(** * Conjunction *)\n\n(** The logical conjunction of propositions [P] and [Q] is\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q). \n\n(** Note that, like the definition of [ev] in the previous\n    chapter, this definition is parameterized; however, in this case,\n    the parameters are themselves propositions, rather than numbers. *)\n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q]. \n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example : \n  (ev 0) /\\ (ev 4).\nProof.\n  apply conj.\n  (* Case \"left\". *) apply ev_0.\n  (* Case \"right\". *) apply ev_SS. apply ev_SS. apply ev_0.  Qed.\n\n(** Let's take a look at the proof object for the above theorem. *)\n\nPrint and_example. \n(* ===>  conj (ev 0) (ev 4) ev_0 (ev_SS 2 (ev_SS 0 ev_0))\n            : ev 0 /\\ ev 4 *)\n\n(** Note that the proof is of the form\n[[\n    conj (ev 0) (ev 4) (...pf of ev 0...) (...pf of ev 4...)\n]]\n    which is what you'd expect, given the type of [conj]. *)\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n    Case \"left\". apply ev_0.\n    Case \"right\". apply ev_SS. apply ev_SS. apply ev_0.  Qed.\n\n(** Conversely, the [inversion] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and put this evidence into the\n    proof context. *)\n\nTheorem proj1 : forall P Q : Prop, \n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ]. \n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2) *)\nTheorem proj2 : forall P Q : Prop, \n  P /\\ Q -> Q.\nProof.\n  intros.\n  inversion H.\n  assumption.\nQed.\n\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop, \n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HP HQ]. \n  split.  \n    (* Case \"left\". *) apply HQ. \n    (* Case \"right\".*) apply HP.  Qed.\n  \n(** Once again, we have commented out the [Case] tactics to make the\n    proof object for this theorem easy to understand.  Examining it\n    shows that all that is really happening is taking apart a record\n    containing evidence for [P] and [Q] and rebuilding it in the\n    opposite order: *)\n\nPrint and_commut.\n(* ===>\n   and_commut = \n     fun (P Q : Prop) (H : P /\\ Q) =>\n     let H0 := match H with\n               | conj HP HQ => conj Q P HQ HP\n               end in H0\n     : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\n\n(** **** Exercise: 2 stars (and_assoc) *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [inversion] breaks [H : P /\\ (Q /\\ R)] down into [HP: P], [HQ :\n    Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop, \n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n  split.\n  split.\n  assumption.\n  assumption.\n  assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (even_ev) *)\n(** Now we can prove the other direction of the equivalence of [even]\n   and [ev], which we left hanging in the last chapter.  Notice that\n   the left-hand conjunct here is the statement we are actually\n   interested in; the right-hand conjunct is needed in order to make\n   the induction hypothesis strong enough that we can carry out the\n   reasoning in the inductive step.  (To see why this is needed, try\n   proving the left conjunct by itself and observe where things get\n   stuck.) *)\n\nTheorem even_ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  (* Hint: Use induction on [n]. *)\n  intros.\n  induction n.\n  split.\n  intros.\n  apply ev_0.\n  intros.\n  inversion H.\n  split.\n  apply IHn.\n  intros.\n  apply ev_SS.\n  apply IHn.\n  unfold even.\n  inversion H.\n  reflexivity.\nQed.\n\n  \n\n  \n(** [] *)\n\n(** **** Exercise: 2 stars *)\n(** Construct a proof object demonstrating the following proposition. *)\n\n(**Definition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n(* FILL IN HERE *) admit.\n(** [] *)**)\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The familiar logical \"if and only if\" is just the\n    conjunction of two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) \n                      (at level 95, no associativity) : type_scope.\n\nTheorem iff_implies : forall P Q : Prop, \n  (P <-> Q) -> P -> Q.\nProof.  \n  intros P Q H. \n  inversion H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop, \n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. \n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star (iff_properties) *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop, \n  P <-> P.\nProof. \n  intros.\n  split.\n  intros.\n  assumption.\n  intros.\n  assumption.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros.\n  inversion H.\n  split.\n  inversion H0.\n  intros.\n  apply H3.\n  apply H1.\n  assumption.\n  intros.\n  apply H2.\n  inversion H0.\n  apply H5.\n  assumption.\nQed.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n(** **** Exercise: 2 stars (MyProp_iff_ev) *)\n(** We have seen that the families of propositions [MyProp] and [ev]\n    actually characterize the same set of numbers (the even ones).\n    Prove that [MyProp n <-> ev n] for all [n].  Just for fun, write\n    your proof as an explicit proof object, rather than using\n    tactics. (_Hint_: if you make use of previously defined thoerems,\n    you should only need a single line!) *)\n\n(** Definition MyProp_iff_ev : forall n, MyProp n <-> ev n :=\n  (* FILL IN HERE *) admit.**)\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q. \n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P],[Q] and\n    evidence of [P], and returns as output, the evidence of [P /\\ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for! -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** Since [P \\/ Q] has two constructors, doing [inversion] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"right\". apply or_intror. apply HP.\n    Case \"left\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"right\". right. apply HP.\n    Case \"left\". left. apply HQ.  Qed.\n\n(** **** Exercise: 2 stars, optional (or_commut'') *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof. \n  intros P Q R. intros H. inversion H as [HP | [HQ HR]]. \n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars, recommended (or_distributes_over_and_2) *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros.\n  destruct H.\n  destruct H.\n  left.\n  assumption.\n  destruct H0.\n  left.\n  assumption.\n  right.\n  split.\n  assumption.\n  assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (or_distributes_over_and) *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\nP \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\nintros.\nsplit.\nintros.\napply or_distributes_over_and_1.\nassumption.\nintros.\napply or_distributes_over_and_2 .\nassumption.\nQed.\n\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are obviously analogs, in some sense, of the logical connectives\n    [/\\] and [\\/].  This analogy can be made more precise by the\n    following theorems, which show how to translate knowledge about\n    [andb] and [orb]'s behaviors on certain inputs into propositional\n    facts about those inputs. *)\n\nTheorem andb_true__and : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n\nTheorem and__andb_true : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\n(** **** Exercise: 1 star (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  intros.\n  destruct b.\n  destruct c.\n  inversion H.\n  right.\n  reflexivity.\n  left.\n  reflexivity.\nQed.\n  \n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros.\n  destruct b.\n  left.\n  reflexivity.\n  destruct c.\n  right.\n  reflexivity.\n  inversion H.\nQed.\n\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  intros.\n  destruct b.\n  destruct c.\n  split.\n  inversion H.\n  inversion H.\n  inversion H.\n  split.\n  reflexivity.\n  destruct c.\n  inversion H.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := . \n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n(** **** Exercise: 1 star (False_ind_principle) *)\n(** Can you predict the induction principle for falsehood? *)\n\n(* Check False_ind. *)\n(** [] *)\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof. \n  intros contra.\n  inversion contra.  Qed. \n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, we might wonder whether it\n    is possible to define truth in the same way.  Naturally, the\n    answer is yes. *)\n\n(** **** Exercise: 2 stars (True_induction) *)\n(** Define [True] as another inductively defined proposition.  What\n    induction principle will Coq generate for your definition?  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.  Alternatively, you may find it easiest\n    to start with the induction principle and work backwards to the\n    inductive definition.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    just a theoretical curiosity: it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False : \n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof. \n  (* WORKED IN CLASS *)\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.\n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, recommended (double_neg_inf) *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros.\n  unfold not.\n  unfold not in H0.\n  intros.\n  apply H0.\n  apply H.\n  assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros.\n   unfold not.\n   intros.\n   inversion H.\n   apply H1.\n   assumption.\nQed.\n(** [] *)\n\nTheorem five_not_even :  \n  ~ ev 5.\nProof. \n  (* WORKED IN CLASS *)\n  unfold not. intros Hev5. inversion Hev5 as [|n Hev3 Heqn]. \n  inversion Hev3 as [|n' Hev1 Heqn']. inversion Hev1.  Qed.\n\n(** **** Exercise: 1 star ev_not_ev_S *)\n(** Theorem [five_not_even] confirms the unsurprising fact that five\n    is not an even number.  Prove this more interesting fact: *)\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof. \n  unfold not. intros n H. induction H. (* not n! *)\n  intros.\n  inversion H.\n  intros.\n  apply IHev.\n  inversion H0.\n  assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (informal_not_PNP) *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** Note that some theorems that are true in classical logic\n    are _not_ provable in Coq's \"built in\" constructive logic... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H. \n  (* But now what? There is no way to \"invent\" evidence for [P]. *) \n  Admitted.\n\n(** **** Exercise: 5 stars, optional (classical_axioms) *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop, \n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop, \n  ~~P -> P.\nDefinition excluded_middle := 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\n(* FILL IN HERE *)\n(** [] *)\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.  \n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n(** **** Exercise: 2 stars, recommended (not_eq_beq_false) *)\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof. \n  intro n.\n  induction n.\n  destruct n'.\n  intros.\n  unfold not in H.\n  apply ex_falso_quodlibet.\n  apply H.\n  reflexivity.\n  intros.\n  unfold not in H.\n  simpl.\n  reflexivity.\n  intros.\n  destruct n'.\n  reflexivity.\n  simpl.\n  apply IHn.\n  unfold not.\n  intros.\n  apply H.\n  apply eq_remove_S.\n  assumption.\nQed.\n\nTheorem remove_not_S : forall n m, (n = m -> False) = (S n = S m -> False).\nProof.\nAdmitted.\n\n(** **** Exercise: 2 stars, optional (beq_false_not_eq) *)\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  intros n m Hbeq.\n  intro Hnm.\n  rewrite Hnm in Hbeq.\n  SearchAbout beq_nat.\n  rewrite beq_nat_refl in Hbeq.\n  inversion Hbeq.\nQed.\n (**\n intro n.\n  induction n.\n  destruct m.\n  intros.\n  inversion H.\n  simpl in *.\n  unfold not.\n  intros.\n  inversion H0.\n  intros.\n  destruct m.\n  unfold not.\n  intros.\n  inversion H0.\n  simpl in *.\n  unfold not.\n  intros.\n  unfold not in IHn.\n  apply IHn.\n**)\n(** [] *)\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can capture what this means with the\n    following 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    For example, consider this existentially quantified proposition: *)\n\nDefinition some_nat_is_even : Prop := \n  ex nat ev.\n\n(** To prove this proposition, we need to choose a particular number\n    as witness -- say, 4 -- and give some evidence that that number is\n    even. *)\n\nDefinition snie : some_nat_is_even := \n  ex_intro _ ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** Coq's notation definition facility can be used to introduce\n    more 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(** We can use the same set of tactics as always for\n    manipulating existentials.  For example, if to prove an\n    existential, we [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, again, that we have to explicitly give the witness. *)\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 * n) = 6.\nProof.\n  exists 2. \n  reflexivity.  Qed.\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(** **** Exercise: 1 star (english_exists) *)\n(** In English, what does the proposition \n[[\n      ex nat (fun n => ev (S n))\n]] \n    mean? *)\n\n(* FILL IN HERE *)\n\n(** Complete the definition of the following proof object: *)\n\n(**Definition p : ex nat (fun n => ev (S n)) :=\n(* FILL IN HERE *) admit.**)\n(** [] *)\n\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" and \"there is no [x] for\n    which [P] does not hold\" are equivalent assertions. *)\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 Hfor.\n  unfold not.\n  intros.\n  inversion H.\n  apply H0.\n  apply Hfor.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** The other direction requires the classical \"law of the excluded\n    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  intros.\n  apply classic_double_neg.\n  red.\n  intros.\n  unfold not in H0.\n  apply H0.\n  exists x.\n  unfold not in H1.\n  assumption.\nQed.\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   intros.\n   split.\n   intros.\n   destruct H.\n   destruct H.\n   left.\n   exists witness.\n   assumption.\n   right.\n   exists witness.\n   assumption.\n   intros.\n   destruct H.\n   destruct H.\n   exists witness.\n   left.\n   assumption.\n   inversion H.\n   exists witness.\n   right.\n   assumption.\nQed.\n(** [] *)\n\n(* Print dist_exists_or. *)\n\n\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has the\n    following inductive definition.  (We enclose the definition in a\n    module to avoid confusion with the standard library equality,\n    which we have used extensively already.) *)\n\nModule MyEquality.\n\nInductive eq (X:Type) : X -> X -> Prop :=\n  refl_equal : forall x, eq X x x.\n\n(** Standard infix notation (using Coq's type argument synthesis): *)\n\nNotation \"x = y\" := (eq _ x y) \n                    (at level 70, no associativity) : type_scope.\n\n(** This is a bit subtle.  The way to think about it is that, given a\n    set [X], it defines a _family_ of propositions \"[x] is equal to\n    [y],\" indexed by pairs of values ([x] and [y]) from [X].  There is\n    just one way of constructing evidence for members of this family:\n    applying the constructor [refl_equal] to a type [X] and a value [x\n    : X] yields evidence that [x] is equal to [x]. *)\n\n(** Here is a slightly different definition -- the one that actually\n    appears in the Coq standard library. *)\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\nNotation \"x =' y\" := (eq' _ x y) \n                     (at level 70, no associativity) : type_scope.\n\n(** **** Exercise: 3 stars, optional (two_defs_of_eq_coincide) *)\n(** Verify that the two definitions of equality are equivalent. *)\n(**\nTheorem two_defs_of_eq_coincide : forall (X:Type) (x y : X),\n  x = y <-> x =' y.\nProof.\n  intros.\n  split.\n  intros.\n  inversion H.\n  **)\n(** [] *)\n\n(** The advantage of the second definition is that the induction\n    principle that Coq derives for it is precisely the familiar\n    principle of _Leibniz equality_: what we mean when we say \"[x] and\n    [y] are equal\" is that every property on [P] that is true of [x]\n    is also true of [y]. *)\n\nCheck eq'_ind.\n(* ===>  forall (X : Type) (x : X) (P : X -> Prop),\n             P x -> forall y : X, x =' y -> P y *)\n\n(** One important consideration remains.  Clearly, we can use\n    [refl_equal] to construct evidence that, for example, [2 = 2].\n    Can we also use it to construct evidence that [1 + 1 = 2]?  Yes.\n    Indeed, it is the very same piece of evidence!  The reason is that\n    Coq treats as \"the same\" any two terms that are _convertible_\n    according to a simple set of computation rules.  These rules,\n    which are similar to those used by [Eval simpl], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.\n    \n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).  But you can see them\n    directly at work in the following explicit proof objects: *)\n\nDefinition four : 2 + 2 = 1 + 3 :=  \n  refl_equal nat 4. \nDefinition singleton : forall (X:Set) (x:X), []++[x] = x::[]  :=\n  fun (X:Set) (x:X) => refl_equal (list X) [x]. \n\nEnd MyEquality.\n\n(* ####################################################### *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves...\n\n    In general, the [inversion] tactic\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n        \n      - adds these equalities to the context of the subgoal, and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal.\n\n   _Example_: If we invert a hypothesis built with [or], there are two\n   constructors, so two subgoals get generated.  The\n   conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.\n\n   _Example_: If we invert a hypothesis built with [and], there is\n   only one constructor, so only one subgoal gets generated.  Again,\n   the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.  The\n   constructor does have two arguments, though, and these can be seen\n   in the context in the subgoal.\n\n   _Example_: If we invert a hypothesis built with [eq], there is\n   again only one constructor, so only one subgoal gets generated.\n   Now, though, the form of the [refl_equal] constructor does give us\n   some extra information: it tells us that the two arguments to [eq]\n   must be the same!  The [inversion] tactic adds this fact to the\n   context.  *)\n\n(* ####################################################### *)\n(** * Relations as Propositions *)\n\n(** A proposition parameterized numbers (such as [ev]) can be\n    thought of as a _property_ -- i.e., it defines a subset of [nat],\n    namely those numbers for which the proposition is provable.  In\n    the same way, a two-argument proposition can be thought of as a\n    _relation_ -- i.e., it defines a set of pairs for which the\n    proposition is provable. *)\n\nModule LeFirstTry.  \n\n(** We've already seen an inductive definition of one\n    fundamental relation: equality.  Another useful one is the \"less\n    than or equal to\" relation on numbers: *)\n\n(** This definition should be fairly intuitive.  It says that\n    there are two ways to give evidence that one number is less than\n    or equal to another: either observe that they are the same number,\n    or give evidence that the first is less than or equal to the\n    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\nEnd LeFirstTry.\n\n(** This is a reasonable definition of the [<=] relation, but we\n    can streamline it a little by observing that the left-hand\n    argument [n] is the same everywhere in the definition, so we can\n    actually make it a \"general parameter\" to the whole definition,\n    rather than an argument to each constructor.  This is similar to\n    what we did in our second definition of the [eq] relation,\n    above. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. \n    (The same was true of our second version of [eq].) *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(** By contrast, the induction principle that Coq calculates for the\n    first definition has a lot of extra quantifiers, which makes it\n    messier to work with when proving things by induction.  Here is\n    the induction principle for the first [le]: *)\n\n(* le_ind : \n     forall P : nat -> nat -> Prop,\n     (forall n : nat, P n n) ->\n     (forall n m : nat, le n m -> P n m -> P n (S m)) ->\n     forall n n0 : nat, le n n0 -> P n n0 *)\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 the previous chapter.  We can [apply] the constructors to\n    prove [<=] goals (e.g., to show that [3<=3] or [3<=6]), and we can\n    use tactics like [inversion] to extract information from [<=]\n    hypotheses in the context (e.g., to prove that [~(2 <= 1)].) *)\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).\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H1.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\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, recommended (total_relation) *)\n(** Define an inductive 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 relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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(** State and prove an equivalent characterization of the relation\n    [R].  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(** **** Exercise: 3 stars, recommended (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_empty : all P []\n  | all_n_empty : forall (x : X) (l : list X), P x ->  all P l -> all P (x::l).\n\n(** Recall the function [forallb], from the exercise\n[forall_exists_challenge] in [Poly.v]: *)\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, optional (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[[\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    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, 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, optional (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  induction xs.\n  intros.\n  right.\n  simpl in *.\n  assumption.\n  intros.\n  destruct ys.\n  simpl in *.\n  inversion H.\n  rewrite <- H1.\n  left.\n  apply ai_here.\n  left.\n  apply ai_later.\n  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  intros.\n  destruct H.\n  induction ys.\n  simpl in *.\n  inversion H.\n  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(** ** Digression: More Facts about [<=] and [<] *)\n\n(** Let's pause briefly to record several facts about the [<=]\n    and [<] relations that we are going to need later in the\n    course.  The proofs make good practice exercises. *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros.\n  induction n.\n  apply le_n.\n  apply le_S.\n  assumption.\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  apply le_n.\n  apply le_S.\n  assumption.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  intros n m.  generalize dependent n.  induction m. \n  intros.\n  inversion H ; subst.\n  apply le_n.\n  inversion H1.\n  intros.\n  inversion H.\n  apply le_n.\n  apply IHm in H1.\n  apply le_S.\n  assumption.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof. \n  intros.\n  induction b.\nSearchAbout plus.\n  rewrite <- plus_n_O.\n  apply le_n.\n    rewrite <- plus_n_Sm.\n  apply le_S.\nassumption.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n induction n1 as [| n'].\n intros.\n Case \"n1 = 0\".\n split.\n destruct m.\n SCase \"m = 0 \".\n simpl in H.\n inversion H.\n SCase \"m = S m\".\n simpl in H.\n destruct n2.\n assumption.\n inversion H.\n apply le_S.\n subst.\n apply le_S. Admitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  intros.\n  induction H.\n  destruct n.\n  apply le_S.\n  apply le_n.\n  apply le_S.\n  apply le_n.\n  apply le_S.\n  apply le_S.\n  assumption.\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 m Heq.\n   apply O_le_n.\n Case \"n = S n'\".\n   intros m.\n   destruct m as [| m'].\n   SCase \"m = 0\".\n     simpl. intros H. inversion H.\n   SCase \"m = S m'\".\n     simpl. intros H. apply IHn' in H.\n     apply n_le_m__Sn_le_Sm ; assumption.\nQed.\n \n\n\nTheorem ble_nat_n_Sn_false : forall n m,\n  ble_nat n (S m) = false ->\n  ble_nat n m = false.\nProof.\ninduction n as [| n'].\nCase \"n' = 0\". \n  intros.\n  inversion H.\nCase \"n'= S n'\".\nintros.\ndestruct m.\nSCase \"m = 0\".\nreflexivity.\nSCase \"m= S m\".\nsimpl.\napply IHn'.\nsimpl in H.\nassumption.\nQed.\n\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  induction n as [| n'].\n  Case \"n=0\".\n  intros.\n  inversion H.\n  Case \"n =S n\".\n  intros.\n  destruct m.\n  SCase \"m = 0\".\n  unfold not.\n  intros.\n  inversion H0.\n  SCase \"m = S m\".\n  simpl in H.\n  apply IHn' in H.\n  unfold not.\n  intros.\n  apply Sn_le_Sm__n_le_m in H0.\n  unfold not in H.\n  apply H.\n  assumption.\nQed.\n\n  \n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (nostutter) *)\n(** Formulating inductive definitions of predicates is an important skill\n    you'll need in this course.\n\n    Try to solve this exercise without any help at all.   If you do receive \n    assistance from anyone, please say so specifically in a comment.\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*)\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_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_2:  nostutter [].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_false_not_eq; 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, optional (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 this 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 an\n   assignment of items to labels: if there are more items than labels,\n   at least two items must have the same label.  You will almost\n   certainly need to use 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.  intros X l1. induction l1.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(* ################################################### *)\n(** ** Induction Principles for [/\\] and [\\/] *)\n\n(** The induction principles for conjunction and disjunction are a\n    good illustration of Coq's way of generating simplified induction\n    principles for [Inductive]ly defined propositions, which we\n    discussed in the last chapter.  You try first: *)\n\n(** **** Exercise: 1 star (and_ind_principle) *)\n(** See if you can predict the induction principle for conjunction. *)\n\n(* Check and_ind. *)\n(** [] *)\n\n(** **** Exercise: 1 star (or_ind_principle) *)\n(** See if you can predict the induction principle for disjunction. *)\n\n(* Check or_ind. *)\n(** [] *)\n\nCheck and_ind.\n\n(** From the inductive definition of the proposition [and P Q]\n[[\n     Inductive and (P Q : Prop) : Prop :=\n       conj : P -> Q -> (and P Q).\n]]\n    we might expect Coq to generate this induction principle\n[[\n     and_ind_max :\n       forall (P Q : Prop) (P0 : P /\\ Q -> Prop),\n            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->\n            forall a : P /\\ Q, P0 a\n]]\n    but actually it generates this simpler and more useful one:\n[[\n     and_ind :\n       forall P Q P0 : Prop,\n            (P -> Q -> P0) ->\n            P /\\ Q -> P0\n]]\n    In the same way, when given the inductive definition of [or P Q]\n[[\n     Inductive or (P Q : Prop) : Prop :=\n       | or_introl : P -> or P Q\n       | or_intror : Q -> or P Q.\n]]\n    instead of the \"maximal induction principle\"\n[[\n     or_ind_max :\n       forall (P Q : Prop) (P0 : P \\/ Q -> Prop),\n            (forall a : P, P0 (or_introl P Q a)) ->\n            (forall b : Q, P0 (or_intror P Q b)) ->\n            forall o : P \\/ Q, P0 o\n]]\n    what Coq actually generates is this:\n[[\n     or_ind :\n       forall P Q P0 : Prop,\n            (P -> P0) ->\n            (Q -> P0) ->\n            P \\/ Q -> P0\n]] \n*)\n\n(* ######################################################### *)\n(** ** Explicit Proof Objects for Induction *)\n\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n    \n(** Recall the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\n(* Check nat_ind. *)\n(* ===> \n   nat_ind : forall P : nat -> Prop,\n      P 0%nat -> \n      (forall n : nat, P n -> P (S n)) -> \n      forall n : nat, P n  *)\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n \nPrint nat_ind.  Print nat_rect.\n(* ===> (after some manual inlining)\n   nat_ind =\n    fun (P : nat -> Type) \n        (f : P 0%nat) \n        (f0 : forall n : nat, P n -> P (S n)) =>\n          fix F (n : nat) : P n :=\n             match n as n0 return (P n0) with\n            | 0%nat => f\n            | S n0 => f0 n0 (F n0)\n            end.\n*)\n\n(** We can read this as follows: \n     Suppose we have evidence [f] that [P] holds on 0,  and \n     evidence [f0] that [forall n:nat, P n -> P (S n)].  \n     Then we can prove that [P] holds of an arbitrary nat [n] via \n     a recursive function [F] (here defined using the expression \n     form [Fix] rather than by a top-level [Fixpoint] \n     declaration).  [F] pattern matches on [n]: \n      - If it finds 0, [F] uses [f] to show that [P n] holds.\n      - If it finds [S n0], [F] applies itself recursively on [n0] \n         to obtain evidence that [P n0] holds; then it applies [f0] \n         on that evidence to show that [P (S n)] holds. \n    [F] is just an ordinary recursive function that happens to \n    operate on evidence in [Prop] rather than on terms in [Set].\n \n    Aside to those interested in functional programming: You may\n    notice that the [match] in [F] requires an annotation [as n0\n    return (P n0)] to help Coq's typechecker realize that the two arms\n    of the [match] actually return the same type (namely [P n]).  This\n    is essentially like matching over a GADT (generalized algebraic\n    datatype) in Haskell.  In fact, [F] has a _dependent_ type: its\n    result type depends on its argument; GADT's can be used to\n    describe simple dependent types like this.\n \n    We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  Recall our desire to\n    prove that\n\n    [forall n : nat, even n -> ev n].\n \n    Attempts to do this by standard induction on [n] fail, because the\n    induction principle only lets us proceed when we can prove that\n    [even n -> even (S n)] -- which is of course never provable.  What\n    we did earlier in this chapter was a bit of a hack:\n \n    [Theorem even_ev : forall n : nat,\n     (even n -> ev n) /\\ (even (S n) -> ev (S n))].\n \n    We can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n \n *)\n \n Definition nat_ind2 : \n    forall (P : nat -> Prop), \n    P 0 -> \n    P 1 -> \n    (forall n : nat, P n -> P (S(S n))) -> \n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS => \n          fix f (n:nat) := match n return P n with \n                             0 => P0 \n                           | 1 => P1 \n                           | S (S n') => PSS n' (f n') \n                          end.\n \n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive (try\n     it!).\n\n     The [induction ... using] tactic gives a convenient way to\n     specify a non-standard induction principle like this. *)\n \nLemma even_ev' : forall n, even n -> ev n.\nProof. \n intros.  \n induction n as [ | |n'] using nat_ind2. \n  Case \"even 0\". \n    apply ev_0.  \n  Case \"even 1\". \n    inversion H.\n  Case \"even (S(S n'))\". \n    apply ev_SS. \n    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H. \nQed. \n\n(* ######################################################### *)\n(** ** The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is \"why\n    trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard Correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on.\n\n    There are a few additional wrinkles:\n\n    - Since Coq types can themselves be expressions, the checker must\n      normalize these (by using the conversion rules) before\n      comparing them.\n\n    - The checker must make sure that [match] expressions are\n      _exhaustive_.  That is, there must be an arm for every possible\n      constructor.  To see why, consider the following alleged proof\n      object:\n[[\n      Definition or_bogus : forall P Q, P \\/ Q -> P :=\n        fun (P Q : Prop) (A : P \\/ Q) =>\n           match A with\n           | or_introl H => H\n           end. \n]]\n      All the types here match correctly, but the [match] only\n      considers one of the possible constructors for [or].  Coq's\n      exhaustiveness check will reject this definition.\n\n    - The checker must make sure that each [fix] expression\n      terminates.  It does this using a syntactic check to make sure\n      that each recursive call is on a subexpression of the original\n      argument.  To see why this is essential, consider this alleged\n      proof:\n[[\n          Definition nat_false : forall (n:nat), False :=\n             fix f (n:nat) : False := f n. \n]]\n      Again, this is perfectly well-typed, but (fortunately) Coq will\n      reject it. *)\n\n(** Note that the soundness of Coq depends only on the correctness of\n    this typechecking engine, not on the tactic machinery.  If there\n    is a bug in a tactic implementation (and this certainly does\n    happen!), that tactic might construct an invalid proof term.  But\n    when you type [Qed], Coq checks the term for validity from\n    scratch.  Only lemmas whose proofs pass the type-checker can be\n    used in further proof developments.  *)\n\n\n", "meta": {"author": "ramonmulia", "repo": "Coq", "sha": "f3a022140fa407352cce201f9bd81df4da4ddf02", "save_path": "github-repos/coq/ramonmulia-Coq", "path": "github-repos/coq/ramonmulia-Coq/Coq-f3a022140fa407352cce201f9bd81df4da4ddf02/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.744676553981535}}
{"text": "(* Ejercicio Semanal 3: Semántica y Verificación.\n  Javier Enríquez Mendoza \n  415000073 *)\n\nRequire Import List.\nRequire Import ArithRing.\nRequire Import Bool.\n\nVariable A : Type.\n\nFixpoint filterbool (p : A -> bool) (l : list A) : list A :=\n  match l with\n  | nil => nil\n  | a :: t => if p a then a :: filterbool p t else filterbool p t\n  end.\n\nCheck filterbool.\n\nFixpoint length (l: list A) : nat:=\n  match l with\n  | nil => 0\n  | x :: xs => 1 + (length xs)\n  end.\n\nVariable p q : A -> bool.\n\nLemma primero: forall (xs: list A), length(filterbool p xs) <= length xs.\nProof.\nintros.\ninduction xs.\nsimpl.\ntrivial.\ndestruct (bool_dec (p a) true).\nsimpl.\nrewrite e.\nsimpl.\nintuition.\napply not_true_is_false in n.\nsimpl.\nrewrite n.\nintuition.\nQed.\n\nFixpoint andB (a b: bool): bool :=\n  match a,b  with\n  | false, _ => false\n  | _, false => false\n  | true, true => true\n  end.\n\nDefinition andp (r q: A -> bool): A-> bool:= fun (x:A) => andB(r x)(q x).\n\nLemma segundo: forall (xs: list A), filterbool (andp p q) xs = filterbool p (filterbool q xs).\nProof.\nintros.\ninduction xs.\nsimpl.\ntrivial.\nunfold andp in IHxs.\ndestruct (bool_dec (p a) true).\ndestruct (bool_dec (q a) true).\nsimpl.\nunfold andp.\nrewrite e0.\nsimpl.\nrewrite e.\nsimpl.\nrewrite <- IHxs.\ntrivial.\napply not_true_is_false in n.\nsimpl.\nunfold andp.\nrewrite e.\nsimpl.\nrewrite n.\nexact IHxs.\napply not_true_is_false in n.\ndestruct (bool_dec (q a) true).\nsimpl.\nunfold andp.\nrewrite e.\nsimpl.\nrewrite n.\nsimpl.\nexact IHxs.\napply not_true_is_false in n0.\nsimpl.\nunfold andp.\nrewrite n0.\nrewrite n.\nsimpl.\nexact IHxs.\nQed.\n\nLemma tercero: forall (xs: list A), filterbool p (filterbool p xs)= filterbool p xs.\nProof.\nintros.\ninduction xs.\nsimpl.\ntrivial.\ndestruct (bool_dec (p a) true).\nsimpl.\nrewrite e.\nsimpl.\nrewrite e.\nrewrite IHxs.\ntrivial.\napply not_true_is_false in n.\nsimpl.\nrewrite n.\nexact IHxs.\nQed. \n\n\n\n\n", "meta": {"author": "jaeem006", "repo": "Semantica", "sha": "fdfdf544dd2d30b2f03a82849d78879762d48811", "save_path": "github-repos/coq/jaeem006-Semantica", "path": "github-repos/coq/jaeem006-Semantica/Semantica-fdfdf544dd2d30b2f03a82849d78879762d48811/javier_enriquez_ej3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7446765487629567}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (x : natural) : natural :=\n  mult z (plus x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_assoc/goal33conj254_coqofml_KG0p8U.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7446755725350026}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf3 : natural) : natural :=\n  plus lf2 (plus lf3 Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj82_coqofml_AUFwEC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7446755663054322}}
{"text": "(* Script de ejercicios de lógica minimal. *)\n\n(* Ejercicio 1a *)\nTheorem triple_neg_single: forall (a: Prop), ~~~a <-> ~a.\nProof.\nsplit.\n+ unfold not.\n  intros.\n  apply H.\n  intro.\n  apply H1.\n  trivial.\n+ unfold not.\n  intros.\n  apply H0.\n  intro.\n  apply H; trivial.\nQed.\n\n(* Ejercicio 1b *)\nTheorem double_neg_and: forall (a b: Prop), ~~(a/\\b) -> ~~a /\\ ~~b.\nProof.\nunfold not.\nintros.\nsplit.\n+ intro.\n  apply H.\n  intro.\n  apply H0.\n  destruct H1.\n  trivial.\n+ intro.\n  apply H.\n  intro.\n  apply H0.\n  destruct H1.\n  trivial.\nQed.\n\n(* Ejercicio 1c *)\nTheorem double_neg_forall: forall (T:Type) (a: T -> Prop), ~~(forall x:T, a x) -> forall x:T, ~~a x.\nProof.\nunfold not.\nintros.\napply H.\nintro.\napply H0.\napply H1.\nQed.\n\n\n", "meta": {"author": "victorz3", "repo": "Tarea3VF", "sha": "bfc5507760c435bae5358e4e70b14862e3f33ca1", "save_path": "github-repos/coq/victorz3-Tarea3VF", "path": "github-repos/coq/victorz3-Tarea3VF/Tarea3VF-bfc5507760c435bae5358e4e70b14862e3f33ca1/Props_LM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7446755600758616}}
{"text": "(**  by Evelyne Contejean, LRI *)\n\n\n(* Note by Pierre :\n  May be already in standard library ?\n *)\n\nSet Implicit Arguments. \n\nFrom  Coq Require Import Relations.\n\nInductive trans_clos (A : Set) (R : relation A) : relation A:=\n  | t_step : forall x y, R x y -> trans_clos R x y\n  | t_trans : forall x y z, R x y -> trans_clos R y z -> trans_clos R x z.\n\nLemma trans_clos_is_trans :\n  forall (A :Set) (R : relation A) a b c, \n  trans_clos R a b -> trans_clos R b c -> trans_clos R a c.\nProof.\n  intros A R a b c Hab; generalize c;\n  clear c; induction Hab as [a b Hab | a b c Hab Hbc].\n  intros c Hbc; apply t_trans with b; trivial.\n  intros d Hcd; apply t_trans with b; trivial.\n  apply IHHbc; trivial.\nQed.\n\nLemma acc_trans :\n forall (A : Set) (R : relation A) a, Acc R a -> Acc (trans_clos R) a.\nProof.\n  intros A R a Acc_R_a.\n  induction Acc_R_a as [a Acc_R_a IH].\n  apply Acc_intro.\n  intros b b_Rp_a; induction b_Rp_a.\n  apply IH; trivial.\n  apply Acc_inv with y.\n  apply IHb_Rp_a; trivial.\n  apply t_step; trivial.\nQed.\n\nLemma wf_trans :\n  forall (A : Set) (R : relation A) , well_founded R ->\n                                      well_founded (trans_clos R).\nProof.\n  unfold well_founded; intros A R WR.\n  intro; apply acc_trans; apply WR; trivial.\nQed.\n\nLemma inv_trans :\n  forall (A : Set) (R : relation A) (P : A -> Prop),\n  (forall a b, P a -> R a b -> P b) -> \n  forall a b, P a -> trans_clos R a b -> P b.\nProof.\n   intros A R P Inv a b Pa a_Rp_b; induction a_Rp_b.\n   apply Inv with x; trivial.\n   apply IHa_Rp_b; apply Inv with x; trivial.\nQed.\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/rpo/closure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.744672557358434}}
{"text": "\nRequire Import Lib BinNatDef BinIntDef.\n\nOpen Scope list_scope.\n\n(** We represent here number in base 10 by lists of decimal digits,\n    in big endian order (most significant digit comes first). *)\n\nInductive digit := D0 | D1 | D2 | D3 | D4 | D5 | D6 | D7 | D8 | D9.\n\nDefinition dec := list digit. (** big endian *)\n\nDefinition ten := D1 :: D0 :: nil. (** For example... *)\n\n(** This representation favors simplicity over canonicity :\n    we might need later to normalize by removing the leading zeros *)\n\nFixpoint norm l :=\n  match l with\n  | D0 :: l => norm l\n  | _ => l\n  end.\n\n\n\n(** Conversion between decimal and Peano nat representations *)\n\nModule DecNat.\n\nDefinition digit2nat d :=\n  match d with\n  | D0 => 0\n  | D1 => 1\n  | D2 => 2\n  | D3 => 3\n  | D4 => 4\n  | D5 => 5\n  | D6 => 6\n  | D7 => 7\n  | D8 => 8\n  | D9 => 9\n  end.\n\nDefinition nat2digit n :=\n  match n with\n  | 0 => D0\n  | 1 => D1\n  | 2 => D2\n  | 3 => D3\n  | 4 => D4\n  | 5 => D5\n  | 6 => D6\n  | 7 => D7\n  | 8 => D8\n  | _ => D9 (* n>9 shouldn't happen *)\n  end.\n\nFixpoint d2n (d:dec)(acc:nat) :=\n  match d with\n  | nil => acc\n  | d :: l => d2n l (TailNat.addmul (digit2nat d) 10 acc)\n  end.\n\nDefinition dec2nat d := d2n d 0.\n\nFixpoint n2d (n:nat)(acc:dec)(count:nat) :=\n match count, n with\n | 0, _ => acc\n | _, 0 => acc\n | S count', _ =>\n     let (q,r) := diveucl n 10 in\n     n2d q (nat2digit r :: acc) count'\n end.\n\nDefinition nat2dec n := n2d n nil n.\n\nEnd DecNat.\n\n\n(** Same for decimal and binary N numbers *)\n\nModule DecN.\n\nLocal Open Scope N.\n\nDefinition digit2n d : N :=\n  match d with\n  | D0 => 0\n  | D1 => 1\n  | D2 => 2\n  | D3 => 3\n  | D4 => 4\n  | D5 => 5\n  | D6 => 6\n  | D7 => 7\n  | D8 => 8\n  | D9 => 9\n  end.\n\nDefinition n2digit (n:N) :=\n  match n with\n  | 0 => D0\n  | 1 => D1\n  | 2 => D2\n  | 3 => D3\n  | 4 => D4\n  | 5 => D5\n  | 6 => D6\n  | 7 => D7\n  | 8 => D8\n  | _ => D9 (* n>9 shouldn't happen *)\n  end.\n\nFixpoint d2n (d:dec)(acc:N) :=\n  match d with\n  | nil => acc\n  | d :: l => d2n l (N.add (digit2n d) (N.mul 10 acc))\n  end.\n\nDefinition dec2n d := d2n d 0.\n\nFixpoint n2d (n:N)(acc:dec)(count:positive) :=\n match count, n with\n | xH, _ => acc\n | _, 0 => acc\n | xO count', _ | xI count', _ =>\n     let (q,r) := N.div_eucl n 10 in\n     n2d q (n2digit r :: acc) count'\n end.\n\nDefinition n2dec n :=\n  n2d n nil (match n with 0 => xH | Npos p => xO p end).\n\nEnd DecN.\n\n(** For positive and Z numbers, we simply go through N for the moment. *)\n\nModule DecPos.\n\nDefinition dec2pos d :=\n match DecN.dec2n d with\n | N0 => None\n | Npos p => Some p\n end.\n\nDefinition pos2dec p := DecN.n2dec (Npos p).\n\nEnd DecPos.\n\nModule DecZ.\n\nDefinition dec2z d :=\n match DecN.dec2n d with\n | N0 => Z0\n | Npos p => Zpos p\n end.\n\nDefinition z2dec z :=\n match z with\n | Zpos p => DecN.n2dec (Npos p)\n | _ => nil (* TODO : for now, we discard negative numbers *)\n end.\n\nEnd DecZ.\n\n\n(** A successor on decimal. Not really mandatory, just to state\n    that our conversions preserve the order of numbers *)\n\nFixpoint bounded_succ l :=\n match l with\n | nil => Carry nil\n | d::l =>\n   match bounded_succ l with\n   | NoCarry l' => NoCarry (d::l')\n   | Carry l' =>\n     match d with\n     | D0 => NoCarry (D1::l')\n     | D1 => NoCarry (D2::l')\n     | D2 => NoCarry (D3::l')\n     | D3 => NoCarry (D4::l')\n     | D4 => NoCarry (D5::l')\n     | D5 => NoCarry (D6::l')\n     | D6 => NoCarry (D7::l')\n     | D7 => NoCarry (D8::l')\n     | D8 => NoCarry (D9::l')\n     | D9 => Carry (D0::l')\n     end\n   end\n end.\n\nDefinition succ l :=\n match bounded_succ l with\n | NoCarry l' => l'\n | Carry l' => D1::l'\n end.\n\n(** The strict order on decimal numbers is the transitive\n    closure of the successor *)\n\nInductive lt : dec -> dec -> Prop :=\n | Succ x : lt x (succ x)\n | Trans x y z : lt x y -> lt y z -> lt x z.\n", "meta": {"author": "letouzey", "repo": "baseconv", "sha": "9acc385745c1ea27a2d7891726d190b6e50d3325", "save_path": "github-repos/coq/letouzey-baseconv", "path": "github-repos/coq/letouzey-baseconv/baseconv-9acc385745c1ea27a2d7891726d190b6e50d3325/Deci.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7446725496354228}}
{"text": "(* Exercise 27 *) \n\nRequire Import BenB.\n\nDefinition D := Z. (* Integers! *)\n\nVariables P Q S T : D -> Prop.\n\n(* Note that this theorem does not hold if D were \n   real numbers instead of integers. *)\n\n(* We have to tell Coq explicitly that we are dealing with integers: *)\nOpen Scope Z_scope. \n\nTheorem exercise_027 :\n  (forall x:D, x in [3,7] -> P x \\/ Q x)\n->\n  (forall x:D, x in (2,8) -> ~ P x -> Q x).\nProof.\nimp_i a1.\nall_i a.\nimp_i a2.\nimp_i a3.\ndis_e (P a \\/ Q a) a4 a4.\nimp_e (a in [3, 7]).\nall_e (forall x:D, x in [3, 7] -> P x \\/ Q x) a.\nhyp a1.\ninterval.\ncon_i.\nimp_e (2 < a).\nimp_i a4.\nlin_solve.\ncon_e1 (a < 8).\nhyp a2.\nimp_e (a < 8).\nimp_i a4.\nlin_solve.\ncon_e2 (2 < a).\nhyp a2.\nneg_e (P a).\nhyp a3.\nhyp a4.\nhyp a4.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_real027.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9579122684798184, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7445850733068963}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := zero : Nat | succ : Nat -> Nat.\n\nInductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint drop (drop_arg0 : Nat) (drop_arg1 : Lst) : Lst\n           := match drop_arg0, drop_arg1 with\n              | x, nil => nil\n              | zero, x => x\n              | succ x, cons y z => drop x z\n              end.\n\nFixpoint mem (mem_arg0 : Nat) (mem_arg1 : Lst) : Prop\n:= match mem_arg0, mem_arg1 with\n    | x, nil => False\n    | x, cons y z => x = y \\/ mem x z\n    end.\n\nTheorem theorem0 : forall (x : Nat) (y : Nat) (z : Lst), mem x (drop y z) -> mem x z.\nProof.\n  intros.\n  generalize dependent y.\n  induction z.\n  - intros. destruct y.\n    + contradiction.\n    + contradiction.\n  - intros. destruct y.\n    + assumption.\n    + simpl in H. apply IHz in H. simpl. auto.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal39.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7445183966218031}}
{"text": "Require Import Arith Lia List String.\nImport ListNotations.\nOpen Scope string.\n\nDefinition eq_dec (A : Type) :=\n  forall (x : A),\n    forall (y : A),\n      {x = y} + {x <> y}.\n\n\nNotation var := string.\nDefinition var_eq : eq_dec var := string_dec.\n\nInductive arith : Set :=\n| Const (n : nat)\n| Var (x : var)\n| Plus (e1 e2 : arith)\n| Minus (e1 e2 : arith)\n| Times (e1 e2 : arith).\n\nPrint arith.\n\n\nLemma syntax_is_not_semantics:\n    Plus (Const 1) (Const 1) <> Const 2.\nProof.\n    Locate \"<>\".\n    Print not.\n    unfold not.\n    (*No way to prove False means the thing on the left shouldn't be provable*)\n    intro Heq.\n    (*Now need to call Coq's bluff i.e. for every way it would prove Heq, we would prove False*)\n    (*Another flavor of destruct called inversion*)\n    inversion Heq.\nQed.\n\nFixpoint has_zero (e : arith) : bool :=\n  match e with\n  | Const n => Nat.eqb n 0\n  | Var x => false\n  | Plus e1 e2  => has_zero e1 || has_zero e2\n  | Minus e1 e2 => has_zero e1 || has_zero e2\n  | Times e1 e2 => has_zero e1 || has_zero e2\n  end.\n\nCompute has_zero (Const 0). (* true *)\nCompute has_zero (Const 1). (* false *)\nCompute has_zero (Plus (Var \"x\") (Var \"y\")). (* false *)\nCompute has_zero (Minus (Plus (Var \"x\") (Var \"y\")) (Const 0)). (* true *)\n\nDeclare Scope arith_scope. (* defines a name for our collection of notations *)\nCoercion Const : nat >-> arith.\nCoercion Var : var >-> arith.\nInfix \"+\" := Plus : arith_scope.\nInfix \"-\" := Minus : arith_scope.\nInfix \"*\" := Times : arith_scope.\nDelimit Scope arith_scope with arith. (* lets us use \"%arith\" annotations *)\nBind Scope arith_scope with arith.\n\n(* Now let's see those same examples again. *)\nCompute has_zero 0. (* true *)\nCompute has_zero 1. (* false *)\nCompute has_zero (\"x\" + \"y\")%arith. (* false *)\nCompute has_zero (\"x\" + \"y\" - 0)%arith. (* true *)\n\n(* memory *)\nDefinition valuation := list (var * nat).\n\nFixpoint lookup (x : var) (v : valuation) : option nat :=\n  match v with\n  | [] => None\n  | (y, n) :: v' =>\n    if var_eq x y\n    then Some n\n    else lookup x v'\n  end.\n\nFixpoint eval_arith (e : arith) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x =>\n    match lookup x v with\n    | None => 0  (* sorta bogus! *)\n    | Some n => n\n    end\n  | Plus  e1 e2 => eval_arith e1 v + eval_arith e2 v\n  | Minus e1 e2 => eval_arith e1 v - eval_arith e2 v\n  | Times e1 e2 => eval_arith e1 v * eval_arith e2 v\n  end.\n\nCompute eval_arith (1 + 1)%arith [].  (* 2 *)\nCompute eval_arith (2)%arith [].      (* also 2 *)\n\nLocate \"+\".\n\nLemma eval_one_plus_one_is_eval_two :\n  forall v,\n    eval_arith (1 + 1)%arith v = eval_arith 2 v.\nProof.\n  intro.\n  simpl.\n  reflexivity.\nQed.\n\n\n(* from expressions to commands *)\nInductive cmd :=\n| Skip\n| Assign (x : var) (e : arith)\n| Sequence (c1 c2 : cmd)\n| Repeat (e : arith) (body : cmd).\n\nFixpoint do_n_times {A} (f : A -> A) (n : nat) (x : A) : A :=\n  match n with\n  | O => x\n  | S n' => do_n_times f n' (f x)\n  end.\n\nCompute do_n_times (cons true) 7 [false; false]. (* 7 \"true\"s followed by 2 \"false\"s *)\n\nFixpoint eval_cmd (c : cmd) (v : valuation) : valuation :=\n  match c with\n  | Skip => v\n  | Assign x e => (x, eval_arith e v) :: v\n  | Sequence c1 c2 => eval_cmd c2 (eval_cmd c1 v) \n  | Repeat e body => do_n_times (eval_cmd body) (eval_arith e v) v\n  (* | Repeat e body => do_n_times (fun v => eval_cmd body v) (eval_arith e v) v *)\n  end.\n\n(* more notation *)\nDeclare Scope cmd_scope.\nDelimit Scope cmd_scope with cmd.\nBind Scope cmd_scope with cmd.\nNotation \"x <- e\" := (Assign x e%arith) (at level 75) : cmd_scope.\nInfix \";\" := Sequence (at level 76) : cmd_scope.\nNotation \"'repeat' e 'doing' body 'done'\" :=\n  (Repeat e%arith body) (at level 75) : cmd_scope.\n\nFixpoint factorial_tr (n : nat) (acc : nat) : nat :=\n  match n with\n  | O => acc\n  | S m => factorial_tr m (n * acc)\n  end.\n\nDefinition factorial_tailrec (n : nat) : nat :=\n  factorial_tr n 1.\n\n\n\n\n\n\nDefinition factorial : cmd :=\n  \"output\" <- 1;\n  repeat \"input\" doing\n    \"output\" <- \"output\" * \"input\";\n    \"input\" <- \"input\" - 1\n  done.\n\n\nPrint factorial.\n(* if we put 4 in \"input\", then will compute 4 * 3 * 2 * 1 in \"output\" *)\n\nFixpoint coq_factorial (n : nat) : nat :=\n  match n with\n  | 0 => 1\n  | S n' => n * coq_factorial n'\n  end.\n\nCompute coq_factorial 4.\n\nTheorem factorial_correct :\n  forall v n,\n    lookup \"input\" v = Some n ->\n    lookup \"output\" (eval_cmd factorial v) = Some (coq_factorial n).\nProof.\n  intros.\n  unfold factorial.\n  simpl.\nQed.\n\n\n\n\n\n\n\nDefinition factorial_loop_body : cmd :=\n  \"output\" <- \"output\" * \"input\";\n  \"input\" <- \"input\" - 1.\n\nTheorem factorial_ok :\n  forall v input,\n    lookup \"input\" v = Some input ->\n    lookup \"output\" (eval_cmd factorial v) = Some (factorial_tailrec input).\nProof.\n  (* motto... *)\n  intros v input Hinput.\n  unfold factorial, factorial_tailrec.\n  fold factorial_loop_body.\n  cbn -[factorial_loop_body].\n  (* do_n_times (eval_cmd factorial_loop_body) *)\nAbort.\n\nDefinition map_equiv m1 m2 := forall x, lookup x m1 = lookup x m2.\n\nExample map_equiv_example :\n  forall m,\n    map_equiv ((\"x\", 0) :: (\"y\", 1) :: m) ((\"y\", 1) :: (\"x\", 0) :: m).\nProof.\n  (* example of destructing on a non-variable *)\nAdmitted.\n\nLtac solve_map_cases :=\n  unfold map_equiv; intros; simpl;\n  repeat destruct (var_eq _ _); try congruence.\n\n(* key lemma for factorial *)\nLemma factorial_loop_body_ok :\n  forall n acc v,\n    lookup \"input\" v = Some n ->\n    lookup \"output\" v = Some acc ->\n    map_equiv\n      (do_n_times (eval_cmd factorial_loop_body) n v)\n      ((\"input\", 0) :: (\"output\", factorial_tr n acc) :: v).\nProof.\n  (* do_n_times is recursive on n. So is factorial_tr. Let's induct on n. *)\n  induction n; intros acc v Hinput Houtput x.\n  - simpl. solve_map_cases.\n  - cbn [do_n_times factorial_tr].\n    unfold map_equiv in *.\n    rewrite IHn with (acc := S n * acc); solve_map_cases.\n    + rewrite Hinput. f_equal. lia.\n    + rewrite Hinput, Houtput. f_equal. lia.\nQed.\n\nTheorem factorial_ok :\n  forall v input,\n    lookup \"input\" v = Some input ->\n    lookup \"output\" (eval_cmd factorial v) = Some (factorial_tailrec input).\nProof.\n  intros v input Hinput.\n  unfold factorial, factorial_tailrec.\n  fold factorial_loop_body.\n  cbn -[factorial_loop_body].\n  rewrite Hinput.\n  rewrite factorial_loop_body_ok with (acc := 1); solve_map_cases.\nQed.\n\n\n\n", "meta": {"author": "SharmaAjay19", "repo": "CSEP-505", "sha": "0a27b36dccac1f0308c1860303e6a2f8a61d3c8a", "save_path": "github-repos/coq/SharmaAjay19-CSEP-505", "path": "github-repos/coq/SharmaAjay19-CSEP-505/CSEP-505-0a27b36dccac1f0308c1860303e6a2f8a61d3c8a/TestSamples/Lecture3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.744478599224957}}
{"text": "From CoqAlgs Require Export WayOfTheCoq.\n\n(** * Not that easy *)\n\nModule NotEasy.\n\nFixpoint nth {A : Type} (n : nat) (l : list A) : option A :=\nmatch l with\n    | [] => None\n    | h :: t =>\n        match n with\n            | 0 => Some h\n            | S n' => nth n' t\n        end\nend.\n\nDefinition sorted {A : Type} (l : list nat) : Prop :=\n  forall i j : nat, i <= j ->\n    forall n m : nat,\n      nth i l = Some n -> nth j l = Some m -> n <= m.\n\nPrint nat.\n(*\nInductive nat : Set := O : nat | S : nat -> nat\n*)\n\nPrint le.\n(*\nInductive le (n : nat) : nat -> Prop :=\n    le_n : n <= n | le_S : forall m : nat, n <= m -> n <= S m\n*)\n\nPrint list.\n(*\nInductive list (A : Type) : Type :=\n    nil : list A | cons : A -> list A -> list A\n*)\n\nEnd NotEasy.\n\n(** * Improving patchwork definitions *)\n\nModule ImprovingPatchworkDefinitions1.\n\nInductive LessThanAll (n : nat) : list nat -> Prop :=\n    | LessThanAll_nil : LessThanAll n []\n    | LessThanAll_cons :\n        forall (h : nat) (t : list nat),\n          n <= h -> LessThanAll n t -> LessThanAll n (h :: t).\n\nInductive Sorted : list nat -> Prop :=\n    | Sorted_nil : Sorted []\n    | Sorted_cons :\n        forall (h : nat) (t : list nat),\n          LessThanAll h t -> Sorted t -> Sorted (h :: t).\n\nEnd ImprovingPatchworkDefinitions1.\n\nModule ImprovingPatchworkDefinitions2.\n\nInductive Sorted : list nat -> Prop :=\n    | Sorted_nil : Sorted []\n    | Sorted_singl : forall n : nat, Sorted [n]\n    | Sorted_cons :\n        forall (n m : nat) (l : list nat),\n          n <= m -> Sorted (m :: l) -> Sorted (n :: m :: l).\n\nEnd ImprovingPatchworkDefinitions2.\n\nInductive Sorted {A : Type} (R : A -> A -> Prop) : list A -> Prop :=\n    | Sorted_nil : Sorted R []\n    | Sorted_singl : forall x : A, Sorted R [x]\n    | Sorted_cons :\n        forall (x y : A) (l : list A),\n          R x y -> Sorted R (y :: l) -> Sorted R (x :: y :: l).\n\n(** * Just about right... or is it? Staying on the right track *)\n\nModule Generating.\n\nInductive Permutation {A : Type} : list A -> list A -> Prop :=\n  | perm_nil :\n      Permutation [] []\n  | perm_skip :\n      forall (x : A) (l1 l2 : list A),\n        Permutation l1 l2 -> Permutation (x :: l1) (x :: l2)\n  | perm_swap :\n      forall (x y : A) (l : list A),\n        Permutation (y :: x :: l) (x :: y :: l)\n  | perm_trans :\n      forall l1 l2 l3 : list A,\n        Permutation l1 l2 -> Permutation l2 l3 -> Permutation l1 l3.\n\nEnd Generating.\n\nModule Counting.\n\nFixpoint count {A : Type} (p : A -> bool) (l : list A) : nat :=\nmatch l with\n    | [] => 0\n    | h :: t => (if p h then 1 else 0) + count p t\nend.\n\nDefinition Permutation {A : Type} (l1 l2 : list A) : Prop :=\n  forall p : A -> bool, count p l1 = count p l2.\n\nEnd Counting.\n\nModule Moving.\n\nInductive Transposition {A : Type} : list A -> list A -> Prop :=\n    | Transposition' :\n        forall (x y : A) (l1 l2 l3 : list A),\n          Transposition (l1 ++ x :: l2 ++ y :: l3)\n                        (l1 ++ y :: l2 ++ x :: l3).\n\nInductive Permutation {A : Type} : list A -> list A -> Prop :=\n    | Permutation_refl :\n        forall l : list A, Permutation l l\n    | Permutation_step_trans :\n        forall l1 l2 l3 : list A,\n          Transposition l1 l2 ->\n            Permutation l2 l3 -> Permutation l1 l3.\n\nEnd Moving.\n\nModule Moving2.\n\nInductive AdjacentTransposition {A : Type} : list A -> list A -> Prop :=\n    | AdjacentTransposition' :\n        forall (x y : A) (l1 l2 : list A),\n          AdjacentTransposition (l1 ++ x :: y :: l2) (l1 ++ y :: x :: l2).\n\nInductive Permutation {A : Type} : list A -> list A -> Prop :=\n    | Permutation_refl   :\n        forall l : list A, Permutation l l\n    | Permutation_step_trans :\n        forall l1 l2 l3 : list A,\n          AdjacentTransposition l1 l2 -> Permutation l1 l2 -> Permutation l2 l3.\n\nEnd Moving2.\n\nClass Sort\n  {A : Type} (R : A -> A -> Prop) (f : list A -> list A) : Prop :=\n{\n    isSorted : forall l : list A, Sorted R (f l);\n    isPermutation : forall l : list A, Permutation l (f l)\n}.", "meta": {"author": "wkolowski", "repo": "coq-algs", "sha": "ee6c656314e3d93e3029dd5f845cfb5352c1b089", "save_path": "github-repos/coq/wkolowski-coq-algs", "path": "github-repos/coq/wkolowski-coq-algs/coq-algs-ee6c656314e3d93e3029dd5f845cfb5352c1b089/Thesis/Snippets/SpecifyTheProblem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7444166992886642}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (x : natural) : natural :=\n  plus y (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj186_coqofml_Tz5LJG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7444088721196813}}
{"text": "Definition plus (n : nat)(m : nat) : nat := n + m.\nDefinition plus': nat -> nat -> nat := fun n m => n + m.\nDefinition id (A: Type)(x: A): A := x.\nDefinition id' : forall (A: Type), A -> A := fun A x => x.\nDefinition prop0 : forall (A: Prop), A -> A := fun A x => x.\n\nDefinition prop1 : forall (A B C : Prop), (B -> C) -> (A -> B) -> A -> C\n  := fun A B C f g x => f (g x).\n\n(* 問0. 任意の命題 A B に対して、A ならば 「A ならば B」ならば Bが成り立つ。 *)\n\nDefinition q0 : forall (A B : Prop), A -> (A -> B) -> B\n  := fun A B a f => f a.\n\n(*問1. 任意の命題 A B C に対して、「A ならば B ならば C」ならば「B ならば A ならば C」が成り立つ*)\nDefinition q1 : forall (A B C : Prop), (A -> B -> C) -> (B -> A -> C)\n  := fun A B C f b a => f a b.", "meta": {"author": "kogai", "repo": "sandbox-coq", "sha": "e09bbf942cb1e21478368913293dbe831b48b276", "save_path": "github-repos/coq/kogai-sandbox-coq", "path": "github-repos/coq/kogai-sandbox-coq/sandbox-coq-e09bbf942cb1e21478368913293dbe831b48b276/first.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7444088610208173}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  plus lf2 (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj234_coqofml_4uKtgu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7444088600935379}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  plus lf2 (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj234_coqofml_HtWVHh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7444088501696672}}
{"text": "(* Exercise 74 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_074 : (A /\\ (B -> C)) -> B -> (A /\\ C).\nProof.\nimp_i a1.\nimp_i a2.\ncon_i.\ncon_e1 (B -> C).\nhyp a1.\nimp_e B.\ncon_e2 (A).\nhyp a1.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop074.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.744406177169673}}
{"text": "Require Import Arith.\n\nInductive List A :=\n | Nil : List A\n | Cons : A -> List A -> List A.\n\nImplicit Arguments Nil [A].\nImplicit Arguments Cons [A].\n\n\nFixpoint append {A} (xs ys: List A): List A :=\n  match xs with\n   | Nil => ys\n   | Cons x xs => Cons x (append xs ys)\n  end. \n\nFixpoint reverse {A} (xs: List A): List A :=\n  match xs with\n   | Nil => Nil\n   | Cons x xs => append (reverse xs) (Cons x Nil)\n  end.\n\nTheorem append_nil : forall (A: Type) (xs: List A),\n  append xs Nil = xs.\nProof.\n  intros A xs.\n  induction xs.\n    reflexivity.\n    \n    simpl.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\nTheorem append_assoc : forall (A: Type) (xs ys zs: List A),\n  append xs (append ys zs) = append (append xs ys) zs.\nProof.\n  intros A xs ys zs.\n  induction xs.\n    reflexivity.\n    \n    simpl.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\nTheorem rev_assoc : forall (A: Type) (xs ys: List A),\n  reverse (append xs ys) = append (reverse ys) (reverse xs).\nProof.\n  intros A xs ys.\n  induction xs.\n    simpl.\n    rewrite append_nil.\n    reflexivity.\n    \n    simpl.\n    rewrite append_assoc.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\nTheorem rev_rev : forall (A: Type) (xs: List A),\n  reverse (reverse xs) = xs.\nProof.\n  intros A xs.\n  induction xs.\n    reflexivity.\n    \n    simpl.\n    rewrite rev_assoc.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\n\nFixpoint get {A: Type} (xs: List A) (n: nat) (def: A): A :=\n  match xs, n with\n   | Cons x _, O => x\n   | Cons _ xs, S n => get xs n def\n   | _, _ => def\n  end.\n\nFixpoint length {A: Type} (xs: List A): nat :=\n  match xs with\n   | Nil => O\n   | Cons _ xs => S (length xs)\n  end.\n\nTheorem IFPH_4_2_12: forall (A: Type) (xs ys: List A) (k: nat) (def: A),\n  let n := length xs in\n  get (append xs ys) k def = match nat_compare k n with\n   | Lt => get xs k def \n   | _ => get ys (k - n) def\n  end.\nProof.\n  intros A xs ys k def.\n  simpl.\n  generalize k.\n  clear k.\n  induction xs.\n    intro k.\n    simpl.\n    destruct k.\n      simpl. reflexivity.\n      simpl. reflexivity.\n    \n    intro k.\n    destruct k.\n      simpl. reflexivity.\n      simpl. rewrite (IHxs k). reflexivity.\nQed.", "meta": {"author": "rf0444", "repo": "coq", "sha": "ea26e698cd68ccc051a309b856c7724181be6aae", "save_path": "github-repos/coq/rf0444-coq", "path": "github-repos/coq/rf0444-coq/coq-ea26e698cd68ccc051a309b856c7724181be6aae/ifph/list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7443937055193168}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\n(** \"_Algorithms are the computational content of proofs_.\"  --Robert Harper *)\n\nRequire Export IndProp.\n\n(** We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types like [nat] or [list] and functions over\n    these types, and for _proving_ properties of these programs, using\n    inductive propositions (like [ev]), implication, universal\n    quantification, and the like.  So far, we have mostly treated\n    these mechanisms as if they were quite separate, and for many\n    purposes this is a good way to think.  But we have also seen hints\n    that Coq's programming and proving facilities are closely related.\n    For example, the keyword [Inductive] is used to declare both data\n    types and propositions, and [->] is used both to describe the type\n    of functions on data and logical implication.  This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are\n    almost the same thing.  In this chapter we will study how this\n    works.\n\n    We have already seen the fundamental idea: provability in Coq is\n    represented by concrete _evidence_.  When we construct the proof\n    of a basic proposition, we are actually building a tree of\n    evidence, which can be thought of as a data structure.\n\n    If the proposition is an implication like [A -> B], then its proof\n    will be an evidence _transformer_: a recipe for converting\n    evidence for A into evidence for B.  So at a fundamental level,\n    proofs are simply programs that manipulate evidence. *)\n\n(** Question: If evidence is data, what are propositions themselves?\n\n    Answer: They are types!\n\n    Look again at the formal definition of the [ev] property.  *)\n\nPrint ev.\n(* ==>\n  Inductive ev : nat -> Prop :=\n    | ev_0 : ev 0\n    | ev_SS : forall n, ev n -> ev (S (S n)).\n*)\n\n(** Suppose we introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can say \"is a proof of.\"  For example,\n    the second line in the definition of [ev] declares that [ev_0 : ev\n    0].  Instead of \"[ev_0] has type [ev 0],\" we can say that \"[ev_0]\n    is a proof of [ev 0].\" *)\n\n(** This pun between types and propositions -- between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\" -- is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation:\n\n                 propositions  ~  types\n                 proofs        ~  data values\n\n    See [Wadler 2015] for a brief history and an up-to-date exposition.\n\n    Many useful insights follow from this connection.  To begin with,\n    it gives us a natural interpretation of the type of the [ev_SS]\n    constructor: *)\n\nCheck ev_SS.\n(* ===> ev_SS : forall n,\n                  ev n ->\n                  ev (S (S n)) *)\n\n(** This can be read \"[ev_SS] is a constructor that takes two\n    arguments -- a number [n] and evidence for the proposition [ev\n    n] -- and yields evidence for the proposition [ev (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [ev]. *)\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** As with ordinary data values and functions, we can use the [Print]\n    command to see the _proof object_ that results from this proof\n    script. *)\n\nPrint ev_4.\n(* ===> ev_4 = ev_SS 2 (ev_SS 0 ev_0)\n     : ev 4  *)\n\n(** As a matter of fact, we can also write down this proof object\n    _directly_, without the need for a separate proof script: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n(* ===> ev 4 *)\n\n(** The expression [ev_SS 2 (ev_SS 0 ev_0)] can be thought of as\n    instantiating the parameterized constructor [ev_SS] with the\n    specific arguments [2] and [0] plus the corresponding proof\n    objects for its premises [ev 2] and [ev 0].  Alternatively, we can\n    think of [ev_SS] as a primitive \"evidence constructor\" that, when\n    applied to a particular number, wants to be further applied to\n    evidence that that number is even; its type,\n\n      forall n, ev n -> ev (S (S n)),\n\n    expresses this functionality, in the same way that the polymorphic\n    type [forall X, list X] expresses the fact that the constructor\n    [nil] can be thought of as a function from types to empty lists\n    with elements of that type. *)\n\n(** You may recall (as seen in the [Logic] chapter) that we can\n    use function application syntax to instantiate universally\n    quantified variables in lemmas, as well as to supply evidence for\n    assumptions that these lemmas impose. For instance: *)\n\nTheorem ev_4': ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(** We can now see that this feature is a trivial consequence of the\n    status the Coq grants to proofs and propositions: Lemmas and\n    hypotheses can be combined in expressions (i.e., proof objects)\n    according to the same basic rules used for programs in the\n    language. *)\n\n(* ################################################################# *)\n(** * Proof Scripts *)\n\n(** The _proof objects_ we've been discussing lie at the core of how\n    Coq operates.  When Coq is following a proof script, what is\n    happening internally is that it is gradually constructing a proof\n    object -- a term whose type is the proposition being proved.  The\n    tactics between [Proof] and [Qed] tell it how to build up a term\n    of the required type.  To see this process in action, let's use\n    the [Show Proof] command to display the current state of the proof\n    tree at various points in the following tactic proof. *)\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with some\n    \"holes\" (indicated by [?1], [?2], and so on), and it knows what\n    type of evidence is needed at each hole.  *)\n\n(** Each of the holes corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    evidence we've built stored in the global context under the name\n    given in the [Theorem] command. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand, as shown above. Then we can use [Definition]\n    (rather than [Theorem]) to give a global name directly to a\n    piece of evidence. *)\n\nDefinition ev_4''' : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint ev_4.\n(* ===> ev_4    =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\n\n(** **** Exercise: 1 star (eight_is_even)  *)\n(** Give a tactic proof and a proof object showing that [ev 8]. *)\n\nTheorem ev_8 : ev 8.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nDefinition ev_8' : ev 8 \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Quantifiers, Implications, Functions *)\n\n(** In Coq's computational universe (where data structures and\n    programs live), there are two sorts of values with arrows in their\n    types: _constructors_ introduced by [Inductive]-ly defined data\n    types, and _functions_.\n\n    Similarly, in Coq's logical universe (where we carry out proofs),\n    there are two ways of giving evidence for an implication:\n    constructors introduced by [Inductive]-ly defined propositions,\n    and... functions!\n\n    For example, consider this statement: *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\n(** What is the proof object corresponding to [ev_plus4]?\n\n    We're looking for an expression whose _type_ is [forall n, ev n ->\n    ev (4 + n)] -- that is, a _function_ that takes two arguments (one\n    number and a piece of evidence) and returns a piece of evidence!\n    Here it is: *)\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4'.\n(* ===> ev_plus4' : forall n : nat, ev n -> ev (4 + n) *)\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah],\" and that Coq treats [4 + n] and [S (S (S (S n)))]\n    as synonyms. Another equivalent way to write this definition is: *)\n\nDefinition ev_plus4'' (n : nat) (H : ev n) : ev (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\n(* ===> ev_plus4'' : forall n : nat, ev n -> ev (4 + n) *)\n\n(** When we view the proposition being proved by [ev_plus4] as a\n    function type, one aspect of it may seem a little unusual. The\n    second argument's type, [ev n], mentions the _value_ of the first\n    argument, [n].  While such _dependent types_ are not found in\n    conventional programming languages, they can be useful in\n    programming too, as recent work in the functional programming\n    community demonstrates.\n\n    Notice that both implication ([->]) and quantification ([forall])\n    correspond to functions on evidence.  In fact, they are really the\n    same thing: [->] is just a shorthand for a degenerate use of\n    [forall] where there is no dependency, i.e., no need to give a\n    name to the type on the LHS of the arrow. *)\n\n(** For example, consider this proposition: *)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : ev n), ev (n + 2).\n\n(** A proof term inhabiting this proposition would be a function\n    with two arguments: a number [n] and some evidence [E] that [n] is\n    even.  But the name [E] for this evidence is not used in the rest\n    of the statement of [ev_plus2], so it's a bit silly to bother\n    making up a name for it.  We could write it like this instead,\n    using the dummy identifier [_] in place of a real name: *)\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : ev n), ev (n + 2).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, ev n -> ev (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Connectives as Inductive Types *)\n\n(** Inductive definitions are powerful enough to express most of the\n    connectives and quantifiers we have seen so far.  Indeed, only\n    universal quantification (and thus implication) is built into Coq;\n    all the others are defined inductively.  We study these\n    definitions in this section. *)\n\nModule Props.\n\n(** ** Conjunction\n\n    To prove that [P /\\ Q] holds, we must present evidence for both\n    [P] and [Q].  Thus, it makes sense to define a proof object for [P\n    /\\ Q] as consisting of a pair of two proofs: one for [P] and\n    another one for [Q]. This leads to the following definition. *)\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\n\nEnd And.\n\n(** Notice the similarity with the definition of the [prod] type,\n    given in chapter [Poly]; the only difference is that [prod] takes\n    [Type] arguments, whereas [and] takes [Prop] arguments. *)\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\n\n(** This should clarify why [destruct] and [intros] patterns can be\n    used on a conjunctive hypothesis.  Case analysis allows us to\n    consider all possible ways in which [P /\\ Q] was proved -- here\n    just one (the [conj] constructor).  Similarly, the [split] tactic\n    actually works for any inductively defined proposition with only\n    one constructor.  In particular, it works for [and]: *)\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\nQed.\n\n(** This shows why the inductive definition of [and] can be\n    manipulated by tactics as we've been doing.  We can also use it to\n    build proofs directly, using pattern-matching.  For instance: *)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, optional (conj_fact)  *)\n(** Construct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n(** [] *)\n\n(** ** Disjunction\n\n    The inductive definition of disjunction uses two constructors, one\n    for each side of the disjunct: *)\n\nModule Or.\n\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\n\nEnd Or.\n\n(** This declaration explains the behavior of the [destruct] tactic on\n    a disjunctive hypothesis, since the generated subgoals match the\n    shape of the [or_introl] and [or_intror] constructors.\n\n    Once again, we can also directly write proof objects for theorems\n    involving [or], without resorting to tactics. *)\n\n(** **** Exercise: 2 stars, optional (or_commut'')  *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n(** [] *)\n\n(** ** Existential Quantification\n\n    To give evidence for an existential quantifier, we package a\n    witness [x] together with a proof that [x] satisfies the property\n    [P]: *)\n\nModule Ex.\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro : forall x : A, P x -> ex P.\n\nEnd Ex.\n\n(** This may benefit from a little unpacking.  The core definition is\n    for a type former [ex] that can be used to build propositions of\n    the form [ex P], where [P] itself is a _function_ from witness\n    values in the type [A] to propositions.  The [ex_intro]\n    constructor then offers a way of constructing evidence for [ex P],\n    given a witness [x] and a proof of [P x].\n\n    The more familiar form [exists x, P x] desugars to an expression\n    involving [ex]: *)\n\nCheck ex (fun n => ev n).\n(* ===> exists n : nat, ev n\n        : Prop *)\n\n(** Here's how to define an explicit proof object involving [ex]: *)\n\nDefinition some_nat_is_even : exists n, ev n :=\n  ex_intro ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** **** Exercise: 2 stars, optional (ex_ev_Sn)  *)\n(** Complete the definition of the following proof object: *)\n\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) \n  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** [True] and [False] *)\n\n(** The inductive definition of the [True] proposition is simple: *)\n\nInductive True : Prop :=\n  I : True.\n\n(** It has one constructor (so every proof of [True] is the same, so\n    being given a proof of [True] is not informative.) *)\n\n(** [False] is equally simple -- indeed, so simple it may look\n    syntactically wrong at first glance! *)\n\nInductive False : Prop :=.\n\n(** That is, [False] is an inductive type with _no_ constructors --\n    i.e., no way to build evidence for it. *)\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\n(** If we can build proofs by giving explicit terms rather than\n    executing tactic scripts, you may be wondering whether we can\n    build _programs_ using _tactics_ rather than explicit terms.\n    Naturally, the answer is yes! *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n\nPrint add1.\n(* ==>\n    add1 = fun n : nat => S n\n         : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than\n    with [:=] followed by a term.  This tells Coq to enter _proof\n    scripting mode_ to build an object of type [nat -> nat].  Also, we\n    terminate the proof with [Defined] rather than [Qed]; this makes\n    the definition _transparent_ so that it can be used in computation\n    like a normally-defined function.  ([Qed]-defined objects are\n    opaque during computation.)\n\n    This feature is mainly useful for writing functions with dependent\n    types, which we won't explore much further in this book.  But it\n    does illustrate the uniformity and orthogonality of the basic\n    ideas in Coq. *)\n\n(* ################################################################# *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has the\n    following inductive definition.  (Actually, the definition in the\n    standard library is a small variant of this, which gives an\n    induction principle that is slightly easier to use.) *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n| eq_refl : forall x, eq x x.\n\nNotation \"x = y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\n(** The way to think about this definition is that, given a set [X],\n    it defines a _family_ of propositions \"[x] is equal to [y],\"\n    indexed by pairs of values ([x] and [y]) from [X].  There is just\n    one way of constructing evidence for each member of this family:\n    applying the constructor [eq_refl] to a type [X] and a value [x :\n    X] yields evidence that [x] is equal to [x]. *)\n\n(** **** Exercise: 2 stars (leibniz_equality)  *)\n(** The inductive definition of equality corresponds to _Leibniz\n    equality_: what we mean when we say \"[x] and [y] are equal\" is\n    that every property on [P] that is true of [x] is also true of\n    [y].  *)\n\nLemma leibniz_equality : forall (X : Type) (x y: X),\n  x = y -> forall P:X->Prop, P x -> P y.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We can use [eq_refl] to construct evidence that, for example, [2 =\n    2].  Can we also use it to construct evidence that [1 + 1 = 2]?\n    Yes, we can.  Indeed, it is the very same piece of evidence!  The\n    reason is that Coq treats as \"the same\" any two terms that are\n    _convertible_ according to a simple set of computation rules.\n    These rules, which are similar to those used by [Compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.  *)\n\nLemma four: 2 + 2 = 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove equalities up\n    to now is essentially just short-hand for [apply refl_equal].\n\n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).  But you can see them\n    directly at work in the following explicit proof objects: *)\n\nDefinition four' : 2 + 2 = 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Set) (x:X), []++[x] = x::[]  :=\n  fun (X:Set) (x:X) => eq_refl [x].\n\n\nEnd MyEquality.\n\nDefinition quiz6 : exists x,  x + 3 = 4\n  := ex_intro (fun z => (z + 3 = 4)) 1 (refl_equal 4).\n\n(* ================================================================= *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves.\n\n    In general, the [inversion] tactic...\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n\n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are two\n   constructors, so two subgoals get generated.  The\n   conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.\n\n   _Example_: If we invert a hypothesis built with [and], there is\n   only one constructor, so only one subgoal gets generated.  Again,\n   the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.  The\n   constructor does have two arguments, though, and these can be seen\n   in the context in the subgoal.\n\n   _Example_: If we invert a hypothesis built with [eq], there is\n   again only one constructor, so only one subgoal gets generated.\n   Now, though, the form of the [refl_equal] constructor does give us\n   some extra information: it tells us that the two arguments to [eq]\n   must be the same!  The [inversion] tactic adds this fact to the\n   context. *)\n\n(** $Date: 2016-07-14 17:02:35 -0400 (Thu, 14 Jul 2016) $ *)\n\n", "meta": {"author": "coqoon", "repo": "Software-Foundations", "sha": "a327b63aa8ff8543ae2cedee7a5960da05bbfaa7", "save_path": "github-repos/coq/coqoon-Software-Foundations", "path": "github-repos/coq/coqoon-Software-Foundations/Software-Foundations-a327b63aa8ff8543ae2cedee7a5960da05bbfaa7/Software Foundations/src/SF/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.7443937041954812}}
{"text": "Require Import Arith.\n\nFixpoint le_bool (n m: nat) {struct n}: bool :=\n  match n, m with\n  | O, _ => true\n  | S n1, S m1 => le_bool n1 m1\n  | _, _ => false\n  end.\n\nTheorem le_correct: forall n m, le_bool n m = true -> n <= m.\nProof. now induction n; destruct m; auto with arith. Qed.\n\nFixpoint lt_bool (n m: nat) {struct n}: bool :=\n  match n, m with\n  | O, S _ => true\n  | S n1, S m1 => lt_bool n1 m1\n  | _, _ => false\n  end.\n\nTheorem lt_correct: forall n m, lt_bool n m = true -> n <= m.\nProof. now induction n; destruct m; auto with arith. Qed.\n\nGlobal Hint Extern 4 (?X1 <= ?X2)%nat => \n   exact (le_correct X1 X2 (refl_equal true)) : core.\nGlobal Hint Extern 4 (?X1 < ?X2)%nat => \n   exact (lt_correct X1 X2 (refl_equal true)) : core.\n", "meta": {"author": "thery", "repo": "PolTac", "sha": "cb5e530fdd8a1c72882d33b49146d397363103f2", "save_path": "github-repos/coq/thery-PolTac", "path": "github-repos/coq/thery-PolTac/PolTac-cb5e530fdd8a1c72882d33b49146d397363103f2/NatGroundTac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7442160308515261}}
{"text": "Lemma silly_implication : (1 + 1) = 2 -> 0 * 3 = 0.\nProof. intros H. simpl. reflexivity. Qed.\n\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\nTheorem and_example : (0 = 0) /\\ (4 = mult 2 2).\nProof.\n\napply conj.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\nTheorem proj1 : forall P Q : Prop, P /\\ Q -> P.\nProof.\nintros.\ndestruct H.\napply H.\nQed.\n\nTheorem proj2 : forall P Q : Prop, P /\\ Q -> Q.\nProof.\nintros.\ndestruct H.\napply H0.\nQed.\n\nTheorem and_commut : forall P Q : Prop, P /\\ Q -> Q /\\ P.\nProof.\nintros.\nsplit.\ndestruct H.\napply H0.\ndestruct H.\napply H.\nQed.\n\n\nTheorem and_assoc : forall P Q R : Prop, P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\nintros.\nsplit.\ndestruct H.\nsplit.\napply H.\ndestruct H0.\napply H0.\ndestruct H as [H1 H2].\ndestruct H2.\napply H0.\nQed.\n\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) \n                      (at level 95, no associativity) \n                      : type_scope.\n\n\nTheorem iff_implies : forall P Q : Prop, (P <-> Q) -> P -> Q.\nProof.\nintros P Q H.\ndestruct H.\napply H.\nQed.\n\n\nTheorem iff_sym : forall P Q : Prop, (P <-> Q) -> (Q <-> P).\nProof.\nintros.\ndestruct H.\nsplit.\napply H0.\napply H.\nQed.\n\nTheorem iff_refl : forall P : Prop, P <-> P.\nProof.\nintros.\nsplit.\nintros H1.\napply H1.\nintros H2.\napply H2.\nQed.\n\nTheorem conj_trans : forall P Q R : Prop, P /\\ Q -> Q /\\ R -> P /\\ R.\nProof.\nintros.\nsplit.\ndestruct H.\napply H.\ndestruct H0.\napply H1.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop, (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\nintros P Q R HEPQ HEQR.\ninversion  HEPQ as [HPQ HQP].\ninversion HEQR as [HQR HRQ].\nsplit.\nintros HP. \napply HQR. \napply HPQ. \napply HP.\nintros HR. \napply HQP. \napply HRQ. \napply HR.\nQed.\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\nTheorem or_commut : forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof.\nintros.\ndestruct H as [H1 | H2].\napply or_intror.\napply H1.\napply or_introl.\napply H2.\nQed.\n\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\nintros P Q R H.\ninversion H as [ HP | [ HQ HR ] ].\nsplit.\nleft. apply HP.\nleft. apply HP.\nsplit.\nright.\napply HQ.\nright.\napply HR.\nQed.\n\nTheorem or_distributes_over_and_2 : forall P Q R : Prop, (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\nintros P Q R H.\ninversion H as [HPQ HPR].\ninversion HPQ as [ HP | HQ ].\nleft.\napply HP.\ninversion HPR as [HP | HR].\nleft.\napply HP.\nright.\napply conj.\napply HQ.\napply HR.\nQed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop, P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\nsplit.\napply or_distributes_over_and_1.\napply or_distributes_over_and_2.\nQed.\n\n\nTheorem andb_prop : forall b c, andb b c = true -> b = true /\\ c = true.\nProof.\nintros b c H.\ndestruct b.\ndestruct c.\napply conj. reflexivity. reflexivity.\ninversion H.\ninversion H. \nQed.\n\n\nTheorem andb_true_intro : forall b c, b = true /\\ c = true -> andb b c = true.\nProof.\nintros b c H.\ndestruct b.\ndestruct c.\nsimpl.\nreflexivity.\nsimpl.\ninversion H.\napply H1.\ndestruct c.\nsimpl.\ninversion H.\napply H0.\nsimpl.\ninversion H.\napply H0.\nQed.\n\n\nTheorem andb_false : forall b c, andb b c = false -> b = false \\/ c = false.\nProof.\nintros b c H.\ndestruct b. destruct c.\nleft.\ninversion H.\nright.\nreflexivity.\nleft.\nreflexivity.\nQed.\n\n\nTheorem orb_prop : forall b c, orb b c = true -> b = true \\/ c = true.\nProof.\nintros b c H.\ndestruct b.\nleft.\nreflexivity.\ndestruct c.\nright.\nreflexivity.\nsimpl.\nleft.\napply H.\nQed.\n\n\nTheorem orb_false_elim : forall b c, orb b c = false -> b = false /\\ c = false.\nProof.\nintros b c H.\ndestruct b.\nsplit.\napply H.\ndestruct c.\napply H.\nreflexivity.\nsplit.\nreflexivity.\ndestruct c.\napply H.\nreflexivity.\nQed.\n\nInductive False : Prop := .\n\nTheorem False_implies_nonsense : False -> 2 + 2 = 5.\nProof.\nintros.\ninversion H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop, (P /\\ ~P) -> Q.\nProof.\nintros.\ndestruct H.\nunfold not in H0.\napply H0 in H.\ninversion H.\nQed.\n\nTheorem double_neg : forall P : Prop, P -> ~~P.\nProof.\nintros.\nunfold not.\nintros.\napply H0 in H.\napply H.\nQed.\n\nTheorem contrapositive : forall P Q : Prop, (P -> Q) -> (~Q -> ~P).\nProof.\nintros P Q H. unfold not. intros notQ Pass.\napply notQ. apply H. apply Pass.\nQed.\n\n\nTheorem peirce : forall P Q: Prop, \n  ((P -> Q) -> P) -> P.\nintros.\napply H.\n\n\nTheorem first_eq : forall P Q : Prop, ((P -> Q) -> P) -> P -> ~~P -> P.\nProof.\nintros.\napply H0.\nQed.\n\nTheorem excluded_middle_irrefutable: forall (P:Prop), ~~(P \\/ ~ P).\nProof.\nunfold not.\nintros P f.\napply f.\nright.\nintro p.\napply f.\nleft.\napply p.\nDefined.\n", "meta": {"author": "DanielRrr", "repo": "Coq-Studies", "sha": "a7cd6bd7f61e91ca118a615e62dfe8fec50b70d3", "save_path": "github-repos/coq/DanielRrr-Coq-Studies", "path": "github-repos/coq/DanielRrr-Coq-Studies/Coq-Studies-a7cd6bd7f61e91ca118a615e62dfe8fec50b70d3/computational_logic9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7442069492036375}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Import injective.\nRequire Import incl.\n\nDefinition injective_on_list (v w:Type) (l:list v) (f:v -> w) : Prop :=\n    forall (x y:v), In x l -> In y l -> f x = f y -> x = y.\n\nArguments injective_on_list {v} {w} _ _.\n\nLemma inj_is_inj_on_list : forall (v w:Type) (l:list v) (f:v-> w),\n    injective f -> injective_on_list l f.\nProof.\n    intros v w l f H. intros x y Hx Hy H'. apply H. assumption.\nQed.\n\n\nLemma injective_on_list_appl : forall (v w:Type) (l1 l2:list v) (f:v -> w),\n    injective_on_list (l1 ++ l2) f -> injective_on_list l1 f.\nProof.\n    intros v w l1 l2 f H x y Hx Hy H'.\n    apply H; simpl.\n    - apply in_or_app. left. assumption.\n    - apply in_or_app. left. assumption.\n    - assumption.\nQed.\n\nLemma injective_on_list_appr : forall (v w:Type) (l1 l2:list v) (f:v -> w),\n    injective_on_list (l1 ++ l2) f -> injective_on_list l2 f.\nProof.\n    intros v w l1 l2 f H x y Hx Hy H'.\n    apply H; simpl.\n    - apply in_or_app. right. assumption.\n    - apply in_or_app. right. assumption.\n    - assumption.\nQed.\n\nLemma injective_on_list_cons : forall (v w:Type) (a:v) (l:list v) (f:v -> w),\n    injective_on_list (a :: l) f -> injective_on_list l f.\nProof.\n    intros v w a l f H x y Hx Hy H'.\n    apply H; simpl.\n    - right. assumption.\n    - right. assumption.\n    - assumption.\nQed.\n\nLemma injective_incl : forall (v w:Type) (l l':list v) (f:v -> w),\n    incl l l' -> injective_on_list l' f -> injective_on_list l f.\nProof.\n    intros v w l l' f H0 H1 x y Hx Hy H. apply H1.\n    - apply H0. assumption.\n    - apply H0. assumption.\n    - assumption.\nQed.\n\n\nLemma injective_not_in : forall (v w:Type) (f:v -> w),\n    forall (x:v) (l:list v),\n    injective_on_list (x :: l) f -> \n    ~In x l -> \n    ~In (f x) (map f l).\nProof.\n    intros v w f x l. revert x. \n    induction l as [|a l IH]; simpl; intros x H.\n    - intros H0 H1. assumption.\n    - intros Hp [Hq|Hq].\n        { apply Hp. left. apply H.\n            { right. left. reflexivity. }\n            { left. reflexivity. }\n            { assumption. }\n        }\n        { revert Hq. apply IH.\n            { apply injective_incl with (x :: a :: l).\n                { apply incl_cons2. apply incl_tl. apply incl_refl. }\n                { assumption. }\n            }\n            { intros H'. apply Hp. right. assumption. }\n        }\nQed.\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/lam/inj_on_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7442069439413914}}
{"text": "(** This file contains several basic logical theorems such as De Morgan's laws.\n*)\n\nRequire Export base_logic.\n\nLtac exfalso := elimtype False.\n\nTheorem contrapositive : ∀ {A B : Prop}, (A → B) → (¬B → ¬A).\nProof.\n    intros A B H b a.\n    specialize (H a).\n    contradiction (b H).\nQed.\n\nLtac contrapositive H := revert H; apply contrapositive.\n\nTheorem not_not : ∀ P, (¬¬P) ↔ P.\nProof.\n    intro P.\n    split; intro PH.\n    -   classic_case P as [PH'|PH'].\n        +   exact PH'.\n        +   contradiction (PH PH').\n    -   intro PH'.\n        contradiction (PH' PH).\nQed.\nLtac classic_contradiction_prop H := apply (land (not_not _)); intros H.\n\nTheorem contrapositive_iff : ∀ {A B : Prop}, (A → B) ↔ (¬B → ¬A).\nProof.\n    intros A B.\n    split; [>apply contrapositive|].\n    rewrite <- (not_not A) at 2.\n    rewrite <- (not_not B) at 2.\n    apply contrapositive.\nQed.\n\nTheorem not_impl : ∀ A B : Prop, (¬(A → B)) ↔ (A ∧ ¬B).\nProof.\n    intros A B.\n    split.\n    -   intros n.\n        classic_case B as [BH|nBH].\n        +   assert (A → B) by (intro; exact BH).\n            contradiction.\n        +   split; [>|exact nBH].\n            classic_case A as [AH|nAH]; [>exact AH|].\n            exfalso.\n            apply n.\n            intro; contradiction.\n    -   intros [a b] ab.\n        specialize (ab a).\n        contradiction.\nQed.\nTheorem not_and : ∀ A B, (¬(A ∧ B)) ↔ (¬A ∨ ¬B).\nProof.\n    intros A B.\n    split.\n    -   intros n.\n        classic_case A as [AH|nAH].\n        +   right.\n            intros b.\n            apply n.\n            split; assumption.\n        +   left; exact nAH.\n    -   intros [na|nb] [a b]; contradiction.\nQed.\nTheorem not_or : ∀ A B, (¬(A ∨ B)) ↔ (¬A ∧ ¬B).\nProof.\n    intros A B.\n    rewrite <- (not_not (¬A ∧ ¬B)).\n    rewrite not_and.\n    do 2 rewrite not_not.\n    reflexivity.\nQed.\nTheorem not_ex : ∀ {U} (P : U → Prop), (¬(∃ a, P a)) ↔ (∀ a, ¬P a).\nProof.\n    intros U P.\n    split.\n    -   intros not_ex a Pa.\n        apply not_ex.\n        exists a.\n        exact Pa.\n    -   intros all [a Pa].\n        specialize (all a).\n        contradiction.\nQed.\n\nTheorem not_all : ∀ {U} (P : U → Prop), (¬(∀ a, P a)) ↔ (∃ a, ¬P a).\nProof.\n    intros U P.\n    rewrite <- (not_not (∃ a, ¬P a)).\n    rewrite not_ex.\n    split.\n    all: intros not_all all.\n    all: apply not_all.\n    all: intros a.\n    -   rewrite <- not_not.\n        apply all.\n    -   rewrite not_not.\n        apply all.\nQed.\n\nTheorem not_and_impl : ∀ A B, (¬(A ∧ B)) ↔ (A → ¬B).\nProof.\n    intros A B.\n    rewrite <- (not_not (A → ¬B)).\n    rewrite not_impl.\n    rewrite not_not.\n    reflexivity.\nQed.\n\nTheorem and_assoc : ∀ A B C, A ∧ (B ∧ C) ↔ (A ∧ B) ∧ C.\nProof.\n    intros A B C.\n    split.\n    -   intros [P1 [P2 P3]].\n        split; [>split|]; assumption.\n    -   intros [[P1 P2] P3].\n        split; [>|split]; assumption.\nQed.\n\nTheorem or_assoc : ∀ A B C, A ∨ (B ∨ C) ↔ (A ∨ B) ∨ C.\nProof.\n    intros A B C.\n    split.\n    -   intros [P1|[P2|P3]].\n        +   left; left; exact P1.\n        +   left; right; exact P2.\n        +   right; exact P3.\n    -   intros [[P1|P2]|P3].\n        +   left; exact P1.\n        +   right; left; exact P2.\n        +   right; right; exact P3.\nQed.\n\nTheorem and_comm : ∀ A B, (A ∧ B) ↔ (B ∧ A).\nProof.\n    intros A B.\n    split.\n    all: intros [P1 P2].\n    all: split; assumption.\nQed.\n\nTheorem or_comm : ∀ A B, (A ∨ B) ↔ (B ∨ A).\nProof.\n    intros A B.\n    split.\n    all: intros [P1|P2].\n    -   right; exact P1.\n    -   left; exact P2.\n    -   right; exact P1.\n    -   left; exact P2.\nQed.\n\nTheorem and_or_ldist : ∀ A B C, (A ∧ (B ∨ C)) ↔ ((A ∧ B) ∨ (A ∧ C)).\nProof.\n    intros A B C.\n    split.\n    -   intros [PA [PB|PC]].\n        +   left; split; assumption.\n        +   right; split; assumption.\n    -   intros [[PA PB]|[PA PC]].\n        all: split; try assumption.\n        +   left; exact PB.\n        +   right; exact PC.\nQed.\nTheorem and_or_rdist : ∀ A B C, ((A ∨ B) ∧ C) ↔ ((A ∧ C) ∨ (B ∧ C)).\nProof.\n    intros A B C.\n    do 3 rewrite (and_comm _ C).\n    apply and_or_ldist.\nQed.\n\nTheorem or_and_ldist : ∀ A B C, (A ∨ (B ∧ C)) ↔ ((A ∨ B) ∧ (A ∨ C)).\nProof.\n    intros A B C.\n    split.\n    -   intros [PA|[PB PC]].\n        +   split; left; exact PA.\n        +   split; right; assumption.\n    -   intros [[PA|PB] [PA2|PC]].\n        all: try (left; assumption).\n        right; split; assumption.\nQed.\nTheorem or_and_rdist : ∀ A B C, ((A ∧ B) ∨ C) ↔ ((A ∨ C) ∧ (B ∨ C)).\nProof.\n    intros A B C.\n    do 3 rewrite (or_comm _ C).\n    apply or_and_ldist.\nQed.\n\nTheorem or_to_strong : ∀ P Q, P ∨ Q → {P} + {Q}.\nProof.\n    intros P Q PQ.\n    apply indefinite_description.\n    destruct PQ as [PQ|PQ].\n    -   split; left.\n        exact PQ.\n    -   split; right.\n        exact PQ.\nQed.\nTheorem or_from_strong : ∀ P Q, {P} + {Q} → P ∨ Q.\nProof.\n    intros P Q [PQ|PQ].\n    -   left; exact PQ.\n    -   right; exact PQ.\nQed.\n\nTheorem or_lfalse : ∀ P, False ∨ P ↔ P.\nProof.\n    intros P.\n    split.\n    -   intros [H|H].\n        +   contradiction H.\n        +   exact H.\n    -   intros H.\n        right.\n        exact H.\nQed.\n\nTheorem or_rfalse : ∀ P, P ∨ False ↔ P.\nProof.\n    intros P.\n    rewrite or_comm.\n    apply or_lfalse.\nQed.\n\nTheorem or_ltrue : ∀ P, True ∨ P ↔ True.\nProof.\n    intros P.\n    split.\n    -   intro; exact true.\n    -   intros; left; exact true.\nQed.\n\nTheorem or_rtrue : ∀ P, P ∨ True ↔ True.\nProof.\n    intros P.\n    rewrite or_comm.\n    apply or_ltrue.\nQed.\n\nTheorem and_lfalse : ∀ P, False ∧ P ↔ False.\nProof.\n    intros P.\n    split.\n    -   intros [H PH].\n        exact H.\n    -   intros H.\n        contradiction H.\nQed.\n\nTheorem and_rfalse : ∀ P, P ∧ False ↔ False.\nProof.\n    intros P.\n    rewrite and_comm.\n    apply and_lfalse.\nQed.\n\nTheorem and_ltrue : ∀ P, True ∧ P ↔ P.\nProof.\n    intros P.\n    split.\n    -   intros [H PH].\n        exact PH.\n    -   intros H.\n        split.\n        +   exact true.\n        +   exact H.\nQed.\n\nTheorem and_rtrue : ∀ P, P ∧ True ↔ P.\nProof.\n    intros P.\n    rewrite and_comm.\n    apply and_ltrue.\nQed.\n\nTheorem or_idemp : ∀ P, P ∨ P ↔ P.\nProof.\n    intros P.\n    split.\n    -   intros [H|H]; exact H.\n    -   intros H.\n        left; exact H.\nQed.\n\nTheorem and_idemp : ∀ P, P ∧ P ↔ P.\nProof.\n    intros P.\n    split.\n    -   intros [H H'].\n        exact H.\n    -   intros H.\n        split; exact H.\nQed.\n\nTheorem or_both : ∀ P, (P ∨ ¬P) ↔ True.\nProof.\n    intros P.\n    split; [>intro; exact true|].\n    intros I.\n    apply em.\nQed.\n\nTheorem and_both : ∀ P, (P ∧ ¬P) ↔ False.\nProof.\n    intros P.\n    split; [>|intro; contradiction].\n    intros [H nH].\n    contradiction.\nQed.\n\nTheorem not_true : (¬True) = False.\nProof.\n    apply propositional_ext; split.\n    -   intro H; apply H; exact true.\n    -   contradiction.\nQed.\n\nTheorem not_false : (¬False) = True.\nProof.\n    apply propositional_ext; split.\n    -   intro H; exact true.\n    -   intros H H2; contradiction.\nQed.\n\nTheorem not_not_type : ∀ P : Type, ((P → False) → False) → P.\nProof.\n    intros P Ps.\n    assert (∃ p : P, True).\n    {\n        rewrite <- (not_not (∃ _ : P, True)).\n        intros contr.\n        rewrite not_ex in contr.\n        rewrite not_true in contr.\n        exact (Ps contr).\n    }\n    destruct (ex_to_type H) as [p pH].\n    exact p.\nQed.\nLtac classic_contradiction H :=\n    classic_contradiction_prop H ||\n    (apply not_not_type; intros H).\n\nTheorem prop_eq_true : ∀ P : Prop, P = (P = True).\nProof.\n    intros P.\n    apply propositional_ext; split.\n    -   intro p.\n        apply propositional_ext; split; trivial.\n    -   intros P_eq.\n        rewrite P_eq.\n        exact true.\nQed.\nTheorem prop_eq_false : ∀ P, (¬P) = (P = False).\nProof.\n    intros P.\n    apply propositional_ext; split.\n    -   intros nP.\n        apply propositional_ext; split; contradiction.\n    -   intro eq.\n        rewrite eq.\n        rewrite not_false.\n        exact true.\nQed.\n\nTheorem neq_true_false : ∀ P, (P ≠ True) = (P = False).\nProof.\n    intros P.\n    rewrite <- prop_eq_true.\n    rewrite prop_eq_false.\n    reflexivity.\nQed.\nTheorem neq_false_true : ∀ P, (P ≠ False) = (P = True).\nProof.\n    intros P.\n    rewrite <- prop_eq_false.\n    rewrite not_not.\n    apply prop_eq_true.\nQed.\n\nTheorem prop_split : ∀ P, {P = True} + {P = False}.\nProof.\n    intros P.\n    rewrite <- prop_eq_true.\n    rewrite <- prop_eq_false.\n    apply sem.\nQed.\n\nTheorem prop_neq : True ≠ False.\nProof.\n    intros eq.\n    rewrite <- eq.\n    exact true.\nQed.\n\nTheorem any_prop_neq : ∀ P, P ≠ (¬P).\nProof.\n    intros P eq.\n    destruct (prop_split P); subst.\n    -   rewrite not_true in eq.\n        rewrite <- eq.\n        exact true.\n    -   rewrite eq.\n        rewrite not_false.\n        exact true.\nQed.\n\nTheorem not_eq_eq : ∀ A B, (¬A) = (¬B) → A = B.\nProof.\n    intros A B eq.\n    apply (f_equal not) in eq.\n    do 2 rewrite not_not in eq.\n    exact eq.\nQed.\n\nTheorem not_eq_iff : ∀ A B, (A ↔ B) ↔ (¬A ↔ ¬B).\nProof.\n    intros A B.\n    split.\n    -   intros AB.\n        apply propositional_ext in AB.\n        rewrite AB.\n        reflexivity.\n    -   intros AB.\n        apply propositional_ext in AB.\n        apply not_eq_eq in AB.\n        rewrite AB.\n        reflexivity.\nQed.\n\nTheorem prop_is_true : ∀ {P : Prop}, P → P = True.\nProof.\n    intros P H.\n    rewrite <- prop_eq_true.\n    exact H.\nQed.\n\nTheorem prop_is_false : ∀ {P : Prop}, ¬P → P = False.\nProof.\n    intros P H.\n    rewrite <- prop_eq_false.\n    exact H.\nQed.\n\nTheorem eq_iff {U} : ∀ a b : U, a = b ↔ b = a.\nProof.\n    intros a b.\n    split; intro eq; symmetry; exact eq.\nQed.\n\nTheorem or_left : ∀ A B : Prop, (¬B → A) → A ∨ B.\nProof.\n    intros A B H.\n    classic_case B as [BH|BH].\n    -   right; exact BH.\n    -   left; exact (H BH).\nQed.\n\nTheorem or_right : ∀ A B : Prop, (¬A → B) → A ∨ B.\nProof.\n    intros A B H.\n    classic_case A as [AH|AH].\n    -   left; exact AH.\n    -   right; exact (H AH).\nQed.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Init/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.884039278690883, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7442069379797622}}
{"text": "Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\n\n(* motivating example *)\n\nGoal forall n, n + n = 2 * n.\nelim.\n  by rewrite addn0 muln0.\nmove=> n IH.\nrewrite addSn.\nrewrite addnS.\nrewrite IH.\nrewrite mulnS.\nrewrite -addn2.\nrewrite addnC.\ndone.\nQed.\n\n(* a note an unification *)\n\nGoal forall a b c d,\n  a < b ->\n  a < b + c + d.\nmove=> a b c d.\n(* \nltn_addr : forall m n p : nat, m < n -> m < n + p \n*)\nFail apply ltn_addr.\n(* Error: Impossible to unify \"b + c\" with \"b\". *)\n(* match m<->a, n<->b, p<->d and thus b + c<->n !!! *)\nrewrite -addnA.\napply ltn_addr.\nQed.\n\nGoal False.\nevar (x : nat).\nhave : 2 + x = 4 + 5.\n  rewrite /x.\n  apply refl_equal.\nrewrite /= in x *.\nAbort.\n\nPrint nat.\n\nPrint nat_rect.\nPrint nat_ind.\nPrint nat_rec.\n\nDefinition mynat_ind_proof := fun (P : nat -> Prop) (f : P 0) (f0 : forall n : nat, P n -> P n.+1) =>\nfix F (n : nat) : P n :=\n  match n as n0 return (P n0) with\n  | 0 => f\n  | n0.+1 => f0 n0 (F n0)\n  end.\n\nLemma mynat_ind : forall (P : nat -> Prop), P 0 ->\n  (forall n : nat, P n -> P n.+1) ->\n  forall n, P n.\nexact mynat_ind_proof.\nQed.\n\n(* le vs. leq *)\n\nPrint le.\nPrint leq.\n\nGoal forall n, 0 <= n.\ndone.\nShow Proof.\nQed.\n\n(* compare with: *)\nPrint Le.le_0_n.\n\nGoal forall n m, n.+1 <= m.+1 -> n <= m.\ndone.\nShow Proof.\nQed.\n\n(* compare with: *)\nPrint le_S_n.\nPrint le_pred.\n\nGoal forall n, n <= n.\ndone.\nQed.\n\nGoal forall n, n <= n.+1.\ndone.\nQed.\n\nGoal forall n, n < n = false.\nby elim.\nQed.\n\n(* 加算の可換性: prove in one line (without using addnC of course) *)\n\nLemma exo16 n m : m + n = n + m.\nProof.\nAbort.\n\n(* about leqP *)\n\nGoal forall n : nat, (n <= 5 \\/ 5 < n)%coq_nat.\nmove=> n.\ndestruct (Compare_dec.le_gt_dec n 5).\n(* NB: does not replace n <= 5 with True *)\nauto.\nauto.\nShow Proof.\nQed.\n\nGoal forall n : nat, (n <= 5) || (5 < n).\nmove=> n.\ncase H : (n <= 5).\ndone.\nmove/negbT : H.\nrewrite -ltnNge.\nmove=> ->.\ndone.\n(* pros: replace (n <= 5) by true, etc.\n   cons: rewrite in the 2nd branch because of mismatch with standard library, \n     does not scale to three way case analysis *)\nQed.\n\nGoal forall n : nat, (n <= 5) || (5 < n).\nmove=> n.\ncase: (leqP n 5).\ndone.\ndone.\nQed.\n\n (* sum は (_ + _)%type *)\nDefinition rgb := sum unit bool.            (* (unit + bool)%type *)\nDefinition red : rgb := inl tt.\nDefinition green : rgb := inr false.\nDefinition blue : rgb := inr true.\n\nPrint rgb.                                  (* (unit + bool)%type *)\nDefinition nop (c : rgb) : rgb := \n  match c with\n  | inl _ => red\n  | inr false => green\n  | inr true => blue\n  end.\nCompute nop red = red.\nCompute nop green = green.\nCompute nop blue = blue.\n\nDefinition shift (c : rgb) : rgb := \n  match c with\n  | inl _ => green\n  | inr false => blue\n  | inr true => red\n  end.\n\n(* Prove the following: *)\nLemma exo17 c : shift (shift (shift c)) = c.\nProof.\nAbort.\n\nCoInductive rgb_spec : rgb -> bool -> bool -> bool -> Prop := \n| red_spec : rgb_spec red true false false\n| green_spec : rgb_spec green false true false\n| blue_spec : rgb_spec blue false false true.\n\n(* Prove the following: *)\nLemma rgbP c : rgb_spec c (c == red) (c == green) (c == blue).\nProof.\nAbort.\n\n(* same as exo17 but this time using rgbP: *)\nLemma exo18 c : shift (shift (shift c)) = c.\nProof.\nAbort.\n\n(* END *)\n", "meta": {"author": "ProofCafe", "repo": "AffeldtSsreflectTutorialNagoya", "sha": "4e4cb908306184e5c71e0e1b512836af3197bc26", "save_path": "github-repos/coq/ProofCafe-AffeldtSsreflectTutorialNagoya", "path": "github-repos/coq/ProofCafe-AffeldtSsreflectTutorialNagoya/AffeldtSsreflectTutorialNagoya-4e4cb908306184e5c71e0e1b512836af3197bc26/src/ssrnat_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7442069336537762}}
{"text": "Require Coq.QArith.QArith.\n\nModule Quaternions.\n\n    Import Coq.QArith.QArith.\n\n    Inductive H : Set :=\n        H_make (w x y z : Q) : H.\n\n    Definition H_from (w : Q) :=\n        H_make (w) (0) (0) (0).\n\n    Definition H_zero := H_from (0).\n    Definition H_one := H_from (1).\n    Definition H_neg_one := H_from (-1).\n\n    Definition i := H_make (0) (1) (0) (0).\n    Definition j := H_make (0) (0) (1) (0).\n    Definition k := H_make (0) (0) (0) (1).\n\n    Definition Re (left : H) :=\n        match (left) with H_make (w) (x) (y) (z) => w end.\n\n    Definition Icoeff (left : H) :=\n        match (left) with H_make (w) (x) (y) (z) => x end.\n\n    Definition Jcoeff (left : H) :=\n        match (left) with H_make (w) (x) (y) (z) => y end.\n\n    Definition Kcoeff (left : H) :=\n        match (left) with H_make (w) (x) (y) (z) => z end.\n\n    Definition H_plus (left: H) (right : H) : H\n        := match (left)\n        with H_make (wl) (xl) (yl) (zl)\n        => match (right)\n        with H_make (wr) (xr) (yr) (zr)\n        => H_make (wl + wr) (xl + xr) (yl + yr) (zl + zr)\n        end end.\n\n    Definition H_opp (right: H) : H\n        := match (right) with H_make (wr) (xr) (yr) (zr)\n        => H_make (- wr) (- xr) (- yr) (- zr) end.\n\n    Definition H_conj (right: H) : H\n        := match (right) with H_make (wr) (xr) (yr) (zr)\n        => H_make (wr) (- xr) (- yr) (- zr) end.\n\n    Definition H_norm_squared (right: H) : Q\n        := match (right)\n        with H_make (wr) (xr) (yr) (zr)\n        => (wr * wr) + (xr * xr)\n            + (yr * yr) + (zr * zr) end.\n\n    Definition H_mul (left: H) (right : H) : H\n        := match (left)\n        with H_make (wl) (xl) (yl) (zl)\n        => match (right)\n        with H_make (wr) (xr) (yr) (zr)\n        => H_make ((wl * wr) - (xl * xr)\n                             - (yl * yr) - (zl * zr))\n                  ((wl * xr) + (xl * wr)\n                             + (yl * zr) - (zl * yr))\n                  ((wl * yr) - (xl * zr)\n                             + (yl * wr) + (zl * xr))\n                  ((wl * zr) + (xl * yr)\n                             - (yl * xr) + (zl * wr)) end end.\n\n    Definition H_inv (left: H) : H\n        := match (left)\n        with H_make (0) (0) (0) (0) => H_zero\n        | H_make (wl) (xl) (yl) (zl)\n        =>  let den := wl * wl + xl * xl + yl * yl + zl * zl\n            in H_make (wl / den) (- xl / den)\n                (- yl / den) (- zl / den)\n        end.\n\n    Definition H_eq (left: H) (right: H) : Prop\n        := match (left)\n        with H_make (wl) (xl) (yl) (zl)\n        => match (right)\n        with H_make (wr) (xr) (yr) (zr)\n        => (and (and (Qeq (wl) (wr))\n                     (Qeq (xl) (xr)))\n                (and (Qeq (yl) (yr))\n                     (Qeq (zl) (zr)))) end end.\n\n    Section Required_properties.\n\n        Definition Q_zero_times_zero_equals_zero\n            : Qeq (Qmult (0%Q) (0%Q)) (0%Q)\n            := Qmult_0_l (0%Q).\n\n        Definition Q_zero_equals_zero_times_zero\n            : Qeq (0%Q) (Qmult (0%Q) (0%Q))\n            := Qeq_sym (Qmult (0%Q) (0%Q))\n                (0%Q)\n                (Q_zero_times_zero_equals_zero).\n\n        Definition Q_zero_times_one_equals_zero\n            : Qeq (Qmult (0%Q) (1%Q)) (0%Q)\n            := Qmult_0_l (1%Q).\n\n        Definition Q_zero_equals_zero_times_one\n            : Qeq (0%Q) (Qmult (0%Q) (1%Q))\n            := Qeq_sym (Qmult (0%Q) (1%Q))\n                (0%Q)\n                (Q_zero_times_one_equals_zero).\n\n        Definition Q_one_times_zero_equals_zero\n            : Qeq (Qmult (1%Q) (0%Q)) (0%Q)\n            := Qmult_1_l (0%Q).\n\n        Definition Q_zero_equals_one_times_zero\n            : Qeq (0%Q) (Qmult (1%Q) (0%Q))\n            := Qeq_sym (Qmult (1%Q) (0%Q))\n                (0%Q)\n                (Q_one_times_zero_equals_zero).\n\n        Definition Q_one_times_one_equals_one\n            : Qeq (Qmult (1%Q) (1%Q)) (1%Q)\n            := Qmult_1_l (1%Q).\n\n        Definition Q_one_equals_one_times_one\n            : Qeq (1%Q) (Qmult (1%Q) (1%Q))\n            := Qeq_sym (Qmult (1%Q) (1%Q))\n                (1%Q)\n                (Q_one_times_one_equals_one).\n\n        Lemma i_squared_equals_negative_one\n            : H_eq (H_mul i i) (H_neg_one).\n        Proof.\n            assert (Real_part := eq_refl\n                : 0*0 - 1*1 - 0*0 - 0*0 == -1).\n\n            assert (I_coeff_part := eq_refl\n                : 0*1 + 1*0 + 0*0 - 0*0 == 0).\n\n            assert (J_coeff_part := eq_refl\n                : 0*0 - 1*0 + 0*0 + 0*1 == 0).\n\n            assert (K_coeff_part := eq_refl\n                : 0*0 + 1*0 - 0*1 + 0*1 == 0).\n\n            exact (conj (conj (Real_part)\n                              (I_coeff_part))\n                        (conj (J_coeff_part)\n                              (K_coeff_part))).\n        Qed.\n\n        Theorem Add_is_commutative :\n            forall (left : H) (right : H),\n            H_eq (H_plus left right)\n                 (H_plus right left).\n        Proof.\n            intro left.\n            destruct left as [w_left x_left y_left z_left].\n            intro right.\n            destruct right as [w_right x_right y_right z_right].\n\n            exact (conj (conj (Qplus_comm (w_left) (w_right))\n                              (Qplus_comm (x_left) (x_right)))\n                        (conj (Qplus_comm (y_left) (y_right))\n                              (Qplus_comm (z_left) (z_right)))).\n        Qed.\n(*\n    Theorem Add_is_associative:\n        forall (left: H) (middle: H) (right: H),\n        eq (Add left (Add middle right))\n           (Add (Add left middle) right).\n    Proof.\n        intro left.\n        destruct left as [w_left x_left y_left z_left].\n        intro middle.\n        destruct middle as [w_middle x_middle y_middle z_middle].\n        intro right.\n        destruct right as [w_right x_right y_right z_right].\n        unfold Add.\n        unfold Re.\n        unfold Icoeff.\n        unfold Jcoeff.\n        unfold Kcoeff.\n        rewrite (Reals.Add_is_associative (w_left) (w_middle) (w_right)).\n        rewrite (Reals.Add_is_associative (x_left) (x_middle) (x_right)).\n        rewrite (Reals.Add_is_associative (y_left) (y_middle) (y_right)).\n        rewrite (Reals.Add_is_associative (z_left) (z_middle) (z_right)).\n        reflexivity.\n    Qed.\n\n    Theorem Add_identity_is_zero:\n        forall (right: H), eq (Add zero right) (right).\n    Proof.\n        intro right.\n        destruct right as [w_right x_right y_right z_right].\n        unfold Add.\n        unfold zero.\n        unfold Re.\n        unfold Icoeff.\n        unfold Jcoeff.\n        unfold Kcoeff.\n        rewrite (Reals.Add_identity_is_zero (w_right)).\n        rewrite (Reals.Add_identity_is_zero (x_right)).\n        rewrite (Reals.Add_identity_is_zero (y_right)).\n        rewrite (Reals.Add_identity_is_zero (z_right)).\n        reflexivity.\n    Qed.\n\n    Axiom Zero_is_add_identity:\n        forall (left: H), eq (Add left zero) (left).\n\n    Axiom Add_real_to_Neg_real:\n        forall (x : H), eq (Add (x) (Neg x)) (zero).\n\n    Axiom Add_Neg_real_to_real:\n        forall (x : H), eq (Add (Neg x) (x)) (zero).\n\n    Axiom Zero_is_Neg_zero: eq (zero) (Neg zero).\n\n    Axiom Neg_zero_is_zero: eq (Neg zero) (zero).\n\n    Axiom Mul_unique_left:\n        forall (left1: H) (left2: H) (right: H)\n        (sums_are_equal : eq (Mul left1 right) (Mul left2 right)),\n        eq left1 left2.\n\n    Axiom Mul_unique_right:\n        forall (left: H) (right1: H) (right2: H)\n        (sums_are_equal : eq (Mul left right1) (Mul left right2)),\n        eq right1 right2.\n\n    Axiom Mul_unique_product:\n        forall (left: H) (right: H) (product1: H) (product2: H)\n        (eq1: eq (Mul left right) product1)\n        (eq2: eq (Mul left right) product2),\n        eq product1 product2.\n\n    Axiom Mul_is_commutative:\n        forall (left: H) (right: H),\n        eq (Mul left right) (Mul right left).\n\n    Axiom Mul_is_associative:\n        forall (left: H) (middle: H) (right: H),\n        eq (Mul (left) (Mul middle right))\n           (Mul (Mul left middle) (right)).\n\n    Axiom Mul_is_distributive_left:\n        forall (left: H) (middle: H) (right: H),\n        eq (Mul (Add left middle) (right))\n           (Add (Mul left right) (Mul middle right)).\n\n    Axiom Mul_is_distributive_right:\n        forall (left: H) (middle: H) (right: H),\n        eq (Mul (left) (Add middle right))\n           (Add (Mul left middle) (Mul left right)).\n\n    Axiom Mul_identity_is_zero:\n        forall (right: H), eq (Mul one right) (right).\n\n    Axiom One_is_Mul_identity:\n        forall (left: H), eq (Mul left one) (left).\n\n    Axiom Mul_real_by_Inv_real:\n        forall (left: H) (not_zero : not (eq left zero)),\n        eq (Mul (left) (Inv left not_zero)) (one).\n\n    Axiom Mul_Inv_real_by_real:\n        forall (right: H) (not_zero : not (eq right zero)),\n        eq (Mul (Inv right not_zero) (right)) (one).\n*)\n\n    End Required_properties.\n\nEnd Quaternions.\n\n", "meta": {"author": "nullpointersetc", "repo": "Coq_sessions", "sha": "97c9cbae67d17a3ed91d4ce572690efe96a13f10", "save_path": "github-repos/coq/nullpointersetc-Coq_sessions", "path": "github-repos/coq/nullpointersetc-Coq_sessions/Coq_sessions-97c9cbae67d17a3ed91d4ce572690efe96a13f10/Quaternions/Quaternions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7441954973867594}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocate \"exists\".\n\n(* 10.1.1 *)\n(* Coq.Init.Logic - Props*)\nLemma tst_prop: forall x, exists n, x = n * 2 \\/ x = S(n * 2).\nProof.\n  elim => [| x [n IH]].\n    exists 0. by left.\n  case IH.\n    move => H.\n    exists n.\n    right.\n    by rewrite -H.\n  move => H.\n  exists (S n).\n  left.\n  by rewrite mulSn 2!addSn add0n -H.\nDefined.\n\nCompute (tst_prop 5).\n\n(* Coq.Init.Specif - various options arount sigma types *)\nLemma tst_type: forall x,  { n & {x = n * 2} + {x = S(n * 2)} }.\nProof.\n  elim => [| x [n IH]].\n    exists 0. by left.\n  case IH.\n    move => H.\n    exists n.\n    right.\n    by rewrite -H.\n  move => H.\n  exists (S n).\n  left.\n  by rewrite mulSn 2!addSn add0n -H.\nDefined.\n\nCompute (tst_type 5).\n\nDefinition tst (n: nat): nat :=\n  match (tst_type n) with\n  | existT a b => a\n  end.\n\nDefinition is_even (n: nat): bool := \n  match (tst_type n) with\n  | existT a (left _) => true\n  | existT a (right _) => false\n  end.\n\nCompute (tst 6).\nCompute (is_even 6).\n\n(* Prop in calculation *)\nFail Definition tst_prop (n: nat): nat :=\n  match (tst_prop n) with\n  | ex_intro a b => a\n  end.\n\n\nLocate \"+\".\nPrint sumor.\nPrint sumbool.\nPrint sum.\n\n(* 10.2.5 *)\nDefinition e1: forall b, (b = true) + (b = false) := \n  fun b =>\n    match b with\n    | true => inl erefl\n    | false => inr erefl\n    end.\n\nDefinition e2: forall n, (n = 0) + ({n' & n = S n'}) :=\n  fun n =>\n    match n return (n = 0) + ({n' & n = S n'}) with \n    | 0 => inl erefl\n    | S n' as n => inr (existT (fun x => n = S x) n' (erefl (S n')))\n    end.\n\nPrint prod.\nSearch ((_ -> _) * (_ -> _)).\nSearch (Type -> Type -> Prop).\n\n(* 10.2.8 *)\n(* Lemma sigma_bij X (p : X -> Prop): { x & p x } <-> (forall Z, (forall x, p x -> Z) -> Z). *)\n\n(* 10.2.9 *)\nLemma sigma_eq_fw X Y : X + Y -> { b & if b then X else Y }.\nProof.\n  case.\n    by exists true.\n  by exists false.\nDefined.\n\nLemma sigma_eq_bw X Y : { b & if b then X else Y } -> X + Y.\nProof.\n  move => [b p].\n  case: b p => H.\n    by left.\n  by right.\nDefined.\n\n(* 10.3 *)\nDefinition p1 X (p: X -> Type): {x & p x} -> X :=\n  fun p =>\n    match p with\n    | existT x p => x\n    end.\n\nDefinition p2 X (p: X -> Type): forall (a: {x & p x}), p (p1 a) :=\n  fun a =>\n    match a with\n    | existT x p' => p'\n    end.\n\n(* 10.3.1 *)\nLemma scolem_fw (X Y: Type) (p: X -> Y -> Type): \n  (forall x, { y & p x y}) -> { f & forall x, p x (f x) }.\nProof.\n  move => H.\n  exists (fun x => p1 (H x)).\n  move => x.\n  move : (H x) => hx.\n  case : hx => [y pxy].\n  by rewrite /p1.\nDefined.\n\nLemma scolem_bw (X Y: Type) (p: X -> Y -> Type): \n   { f & forall x, p x (f x) } -> forall x, { y & p x y}.\nProof.\n  move => [f H] x.\n  exists (f x).\n  by apply (H x).\nDefined.\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/model_and_prooving_CompTT/pt2/ch10_informative_types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7441344778000448}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export exercise6.\nFrom Coq Require Import Lia.\n\nFixpoint div2 (n : nat) :=\n  match n with\n  | 0 => 0\n  | 1 => 0\n  | S (S n) => S (div2 n)\n  end.\n\nDefinition f (n : nat) :=\n  if even n then div2 n\n  else 3 * n + 1.\n\nFail Fixpoint reaches_1_in (n : nat) :=\n  if n =? 1 then 0\n  else 1 + reaches_1_in (f n).\n\nInductive reaches_1 : nat -> Prop :=\n  | term_done : reaches_1 1\n  | term_more (n : nat) : reaches_1 (f n) -> reaches_1 n.\n\nConjecture collatz : forall n, reaches_1 n.\n\nModule LePlayground.\n\nInductive le : nat -> nat -> Prop :=\n| le_n (n : nat) : le n n\n| le_S (n m : nat) : le n m -> le n (S m).\n\nEnd LePlayground.\n\n(* Basic requirement for a closure : R \\subsetof C. *)\nInductive clos_trans {X : Type} (R : X -> X -> Prop) : X -> X -> Prop :=\n  | t_step (x y : X) :\n    R x y ->\n    clos_trans R x y\n  | t_trans (x y z : X) :\n    clos_trans R x y ->\n    clos_trans R y z ->\n    clos_trans R x z.\n\n(* Exercise: 1 star, standard, optional (close_refl_trans) *)\n(* How would you modify this definition so that it defines reflexive and\ntransitive closure? How about reflexive, symmetric, and transitive closure? *)\nInductive clos_refl_trans {X : Type} (R : X -> X -> Prop) : X -> X -> Prop :=\n  | rt_step (x y : X) : R x y -> clos_refl_trans R x y (* contain *)\n  | rt_refl (x : X) : clos_refl_trans R x x            (* reflexivity. *)\n  | rt_trans (x y z : X) :\n    clos_refl_trans R x y -> clos_refl_trans R y z -> clos_refl_trans R x z.\n    (* transivity. *)\n\nInductive clos_refl_trans_symm {X : Type} (R : X -> X -> Prop) :\n  X -> X -> Prop :=\n  | rts_step(x y : X) : R x y -> clos_refl_trans_symm R x y\n  | rts_symm(x y : X) : clos_refl_trans_symm R x y -> clos_refl_trans_symm R y x\n  | rts_refl(x : X) : clos_refl_trans_symm R x x\n  | rts_trans(x y z : X) : \n    clos_refl_trans_symm R x y ->\n    clos_refl_trans_symm R y z ->\n    clos_refl_trans_symm R x z.\n\nInductive Perm3 {X : Type}: list X -> list X -> Prop :=\n  | perm3_swap12 (x y z : X) :\n    Perm3 [x;y;z] [y;x;z]\n  | perm3_swap23 (x y z : X) :\n    Perm3 [x;y;z] [x;z;y]\n  | perm3_trans (l1 l2 l3 : list X) :\n    Perm3 l1 l2 -> Perm3 l2 l3 -> Perm3 l1 l3.\n\n(* These evidence constructors can be thought of as \"primitive evidence of\nevenness\", and they can be used just like proven theorems. *)\nInductive 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.\n  apply ev_SS. apply ev_SS. apply ev_0.\nQed.\n\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  intros. induction n as [| n' H].\n  - simpl. apply ev_0.\n  - rewrite double_incr. apply ev_SS. apply H.\nQed.\n\nTheorem ev_inversion : forall n : nat,\n  ev n ->\n  (n = 0) \\/ (exists n', n = S (S n') /\\ ev n').\nProof.\n  intros. destruct H.\n  - left. reflexivity.\n  - right. exists n. split. reflexivity. apply H.\nQed.\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros. apply ev_inversion in H. destruct H as [H1 | H2].\n  - discriminate.\n  - destruct H2 as [n' [H3 H4]]. injection H3. intros. rewrite H. apply H4.\nQed.\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  unfold not. intros. inversion H.\nQed.\n\n(** **** Exercise: 1 star, standard (inversion_practice) *)\n(* Prove the following result using inversion. (For extra practice, you can also\nprove it using the inversion lemma.) *)\nTheorem SSSSev_even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros. inversion H. inversion H1.\n  apply H3.\nQed.\n\n(** **** Exercise: 1 star, standard (ev5_nonsense) *)\n(* Prove the following result using inversion. *)\nTheorem ev5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros. inversion H.\n  inversion H1. inversion H3.\nQed.\n\nTheorem ev_Even : forall n,\n  ev n -> Even n.\nProof.\n  unfold Even. intros. induction H as [| n' H].\n  - exists 0. reflexivity.\n  - destruct IHH as [nd H'].\n    rewrite H'. rewrite <- double_incr. exists (S nd). reflexivity.\nQed.\n\nTheorem Even_ev : forall n,\n  Even n -> ev n.\nProof.\n  unfold Even. intros.\n  destruct H.\n  rewrite H. apply ev_double.\nQed.\n\nTheorem ev_Even_iff : forall n,\n  ev n <-> Even n.\nProof.\n  split. apply ev_Even. apply Even_ev.\nQed.\n\n(** **** Exercise: 2 stars, standard (ev_sum) *)\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.\nQed.\n\n\n(** **** Exercise: 4 stars, advanced, optional (ev'_ev) *)\n(* In general, there may be multiple ways of defining a property inductively. For\nexample, here's a (slightly contrived) alternative definition for ev: *)\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\nLemma plus_1_r : forall n,\n  S n = n + 1.\nProof.\n  intros. induction n.\n  - reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem ev'_ev : forall n,\n  ev' n <-> ev n.\nProof.\n  split.\n  - intros. induction H.\n    + apply ev_0.\n    + apply ev_SS. apply ev_0.\n    + apply ev_sum. apply IHev'1. apply IHev'2.\n  - intros. induction H.\n    + apply ev'_0.\n    + replace (S (S n)) with (n + 2).\n      * apply ev'_sum. apply IHev. apply ev'_2.\n      * rewrite plus_1_r. rewrite add_assoc.\n      rewrite <- plus_1_r. rewrite <- plus_1_r. reflexivity.\nQed.\n\n\n(** **** Exercise: 3 stars, advanced, especially useful (ev_ev__ev) *)\nTheorem ev_ev__ev : forall n m,\n  ev (n + m) -> ev n -> ev m.\n  (* Hint: There are two pieces of evidence you could attempt to induct upon\n      here. If one doesn't work, try the other. *)\nProof.\n  intros. induction H0.\n  - simpl in H. apply H.\n  - apply IHev. apply ev_sum. apply H0. simpl in H. apply evSS_ev in H.\n    apply IHev in H. apply H.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (ev_plus_plus) *)\n(* This exercise can be completed without induction or case analysis. But, you\nwill need a clever assertion and some tedious rewriting.\nHint: Is (n+m) + (n+p) even? <- acturally we can prove it by introduce another p *)\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  (* Do not introduce all. We need to take use of the previously proved theorem. *)\n  apply ev_ev__ev.\n  (* Organize all p's together. *)\n  rewrite <- add_assoc. rewrite (add_comm p (m + p)).\n  rewrite add_assoc. rewrite add_assoc. rewrite <- add_assoc.\n  (* Extract 2 terms. *)\n  apply ev_sum.\n  apply H.\n  (* trivial. *)\n  rewrite <- double_plus. apply ev_double.\nQed.\n\nModule Playground.\nInductive le : nat -> nat -> Prop :=\n\t| le_n (n : nat) : le n n \n\t| le_S (n m : nat) (H : le n m) : le n (S m).\n\nNotation \"n <= m \" := (le n m).\n\nTheorem test_le_1 : 3 <= 3.\nProof.\n  apply le_n.\nQed.\n\nTheorem test_l2_2: 3 <= 6.\nProof.\n  apply le_S.\n  apply le_S.\n  apply le_S.\n  apply le_n.\nQed.\n\nTheorem test_le_3 :\n  (2 <= 1) -> 2 + 2 = 5.\nProof.\n  intros.\n  inversion H.\n  inversion H2.\nQed.\n\nDefinition lt (n m : nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\nEnd Playground.\n\n(** **** Exercise: 2 stars, standard, optional (total_relation) *)\n(* Define an inductive binary relation total_relation that holds between every pair of natural numbers. *)\nInductive total_relation : nat -> nat -> Prop := total n m : total_relation n m.\n\n\nTheorem total_relation_is_total : forall n m, total_relation n m.\nProof.\n  intros. apply total.\nQed.\n\n\n(** **** Exercise: 2 stars, standard, optional (empty_relation) *)\n(* Define an inductive binary relation empty_relation (on numbers) that never holds. *)\nInductive empty_relation : nat -> nat -> Prop :=.\n\nTheorem empty_relation_is_empty : forall n m, ~ empty_relation n m.\nProof.\n  unfold not. intros. inversion H.\nQed.\n\nLemma le_trans : forall n m o, m <= n -> n <= o -> m <= o.\nProof.\n  intros. transitivity n. apply H. apply H0.\nQed.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros. induction n.\n  - reflexivity.\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. induction H.\n  - apply le_n.\n  - apply le_S. apply IHle.\nQed.\n\nLemma Sn_le_m__n_le_m : forall n m,\nS n <= m -> n <= m.\nProof.\n  intros. induction H.\n  - apply le_S. 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. inversion H.\n  - apply le_n.\n  - apply Sn_le_m__n_le_m. apply H1.\nQed.\n\nLemma O_lt_Sn : forall n,\n  0 < S n.\nProof.\n  intros. induction n.\n  - unfold lt. reflexivity.\n  - apply le_S. unfold lt in IHn. apply IHn.\nQed.\n\nLemma Sn_le_0_0 : forall n,\n  n <= 0 -> n = 0.\nProof.\n  intros. inversion H. reflexivity.\nQed.\n\nLemma n_lt_m__Sn_lt_Sm (n m : nat) : n < m -> S n < S m.\nProof.\n(* trivial. omit here. *)\nAdmitted.\n\nTheorem ge_two_meanings : forall n m,\n  n <= m -> n < m \\/ n = m.\nProof.\n  intros n. induction n.\n  - intros. destruct m.\n    + right. reflexivity.\n    + left. apply O_lt_Sn.\n  - intros. destruct m.\n    + apply Sn_le_0_0 in H. right. apply H.\n    + apply Sn_le_Sm__n_le_m in H. apply IHn in H. destruct H.\n      * left. apply n_lt_m__Sn_lt_Sm. apply H.\n      * right. rewrite H. reflexivity.\nQed.\n\nTheorem ge_two_meanings_strong : forall n m,\n  n <= m -> n < m \\/ n >= m.\nProof.\n  intros. apply ge_two_meanings in H.\n  destruct H.\n  * left. apply H.\n  * right. rewrite H. unfold ge. reflexivity.\nQed.\n\nTheorem lt_ge_cases : forall n m,\n  n < m \\/ n >= m.\nProof.\n  intros. induction n.\n  - destruct m.\n    + right. unfold ge. reflexivity.\n    + left. apply O_lt_Sn.\n  - destruct m.\n    + right. unfold ge. apply O_le_n.\n    + destruct IHn.\n      * apply ge_two_meanings_strong. unfold lt in H. apply H.\n      * right. unfold ge. unfold ge in H.\n        apply Sn_le_m__n_le_m in H. apply n_le_m__Sn_le_Sm. apply H.\nQed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros. induction b.\n  - rewrite add_0_r. reflexivity.\n  - rewrite plus_1_r. rewrite add_assoc. rewrite <- plus_1_r.\n    apply le_S. apply IHb.\nQed.\n\nTheorem plus_le : forall n1 n2 m,\n  n1 + n2 <= m ->\n  n1 <= m /\\ n2 <= m.\nProof.\n  intros. split.\n  - induction n2.\n    + rewrite add_0_r in H. apply H.\n    + rewrite plus_1_r in H. rewrite add_assoc in H. rewrite <- plus_1_r in H.\n      apply Sn_le_m__n_le_m in H. apply IHn2 in H. apply H.\n  - induction n1.\n    + simpl in H. apply H.\n    + simpl in H. apply Sn_le_m__n_le_m in H. apply IHn1 in H. 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. induction n.\n  - intros. left. apply O_le_n.\n  - intros. destruct p.\n    + simpl in H. apply Sn_le_m__n_le_m in H. right. \n      apply plus_le in H. destruct H as [_ H]. apply H.\n    + simpl in H. apply Sn_le_Sm__n_le_m in H. apply IHn in H.\n      destruct H.\n      * left. apply n_le_m__Sn_le_Sm in H. apply H.\n      * right. apply H.\nQed.\n\nTheorem plus_le_compat_l : forall n m p,\n  n <= m ->\n  p + n <= p + m.\nProof.\n  intros. induction p. generalize dependent n. generalize dependent m.\n  - simpl. intros. apply H.\n  - simpl. apply n_le_m__Sn_le_Sm in IHp. apply IHp.\nQed.\n\nTheorem plus_le_compat_r : forall n m p,\n  n <= m ->\n  n + p <= m + p.\nProof.\n  intros. induction p. generalize dependent n. generalize dependent m.\n  - intros. rewrite add_0_r. rewrite add_0_r. apply H.\n  - rewrite plus_1_r. rewrite (add_comm p 1). rewrite add_assoc. rewrite add_assoc.\n    replace (n + 1) with (S n). replace (m + 1) with (S m). simpl.\n    apply n_le_m__Sn_le_Sm in IHp. apply IHp.\n    apply plus_1_r. apply plus_1_r.\nQed.\n\nTheorem le_plus_trans : forall n m p,\n  n <= m ->\n  n <= m + p.\nProof.\n  intros. induction p.\n  - rewrite add_0_r. apply H.\n  - rewrite plus_1_r. rewrite add_assoc. rewrite <- plus_1_r.\n    apply le_S. apply IHp.\nQed.\n\nLemma Sn_lt_m__n_lt_m : forall n m,\n  S n < m -> n < m.\nProof.\n  unfold lt. intros.\n  apply Sn_le_m__n_le_m. apply H.\nQed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  intros. split.\n  - induction n2.\n    + rewrite add_0_r in H. apply H.\n    + rewrite plus_1_r in H. rewrite add_assoc in H. rewrite <- plus_1_r in H.\n      apply Sn_lt_m__n_lt_m in H. apply IHn2 in H. apply H.\n  - induction n1.\n    + simpl in H. apply H.\n    + simpl in H. apply Sn_lt_m__n_lt_m in H. apply IHn1 in H. apply H.\nQed.\n\n\n(** **** Exercise: 4 stars, standard, optional (more_le_exercises) *)\nTheorem leb_complete : forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  intros n. induction n.\n  - intros. apply O_le_n.\n  - intros. destruct m.\n    + inversion H.\n    + apply n_le_m__Sn_le_Sm. apply IHn. simpl in H. apply H.\nQed.\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  n <=? m = true.\nProof.\n  intros. generalize dependent n. induction m.\n  - intros. inversion H. reflexivity.\n  - destruct n.\n    + reflexivity.\n    + intros. apply Sn_le_Sm__n_le_m in H. apply IHm in H. simpl. apply H.\nQed.\n\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  intros. split. apply leb_complete. apply leb_correct.\nQed.\n\nTheorem leb_true_trans : forall n m o,\n  n <=? m = true -> m <=? o = true -> n <=? o = true.\nProof.\n  intros. rewrite leb_iff in H, H0. rewrite leb_iff.\n  transitivity m. apply H. apply H0.\nQed.\n\n(* R a b c <-> a + b = c. *)\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 :=\n  fun (a b : nat) => a + b.\n\nLemma R_0_n_n : forall n,\n  R 0 n n.\nProof.\n  intros. induction n.\n  - apply c1.\n  - apply c3. apply IHn.\nQed.\n\nLemma abc_R_abc : forall a b c,\n  a + b = c -> R a b c.\nProof.\n  intros a. induction a.\n  - simpl. intros. rewrite H. apply R_0_n_n.\n  - intros. destruct c.\n    + inversion H.\n    + simpl in H. injection H. intros.\n      apply IHa in H0. apply c2. apply H0.\nQed.\n\nTheorem R_equiv_fR : forall a b c, R a b c <-> fR a b = c.\n Proof.\n  split; unfold fR.\n  - intros. induction H.\n    + trivial.\n    + simpl. rewrite IHR. trivial.\n    + rewrite <- plus_n_Sm. rewrite IHR. trivial.\n    + simpl in IHR. rewrite <- plus_n_Sm in IHR. injection IHR. trivial.\n    + rewrite add_comm. apply IHR.\n  - apply abc_R_abc.\nQed.\n\nInductive subseq : list nat -> list nat -> Prop :=\n  | empty: subseq [] []\n  | add_r l1 l2 n (H : subseq l1 l2): subseq l1 (n :: l2)\n  | add_both l1 l2 n (H : subseq l1 l2): subseq (n :: l1) (n :: l2).\n\nLemma empty_subseq : forall l : list nat,\n  subseq [] l.\nProof.\n  intros. induction l.\n  - apply empty.\n  - apply add_r. apply IHl.\nQed.\n\nLemma add_right_list : forall l1 l2 l3,\n  subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  intros. induction H.\n  - simpl. apply empty_subseq.\n  - simpl. apply add_r. apply IHsubseq.\n  - simpl. apply add_both. apply IHsubseq.\nQed.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  intros.\n  induction l.\n  - apply empty.\n  - apply add_both. apply IHl.\nQed.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  destruct l1.\n  - intros. apply empty_subseq.\n  - intros. apply add_right_list. apply H.\nQed.\n\nTheorem subseq_trans : forall l1 l2 l3,\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n  intros l1 l2 l3 H1 H2. generalize dependent l1.\n  induction H2. (* We want to eliminate the middle one, so we do induction on it. *)\n  - auto.\n  - intros. apply add_r. apply IHsubseq. apply H1.\n  - intros. inversion H1.\n    + apply add_r. apply IHsubseq. apply H3.\n    + apply add_both. apply IHsubseq. apply H3.\nQed.\n\n", "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/exercise7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7440720387487235}}
{"text": "Require Import Basics.Overture Basics.Tactics.\nRequire Import Pos.Core.\n\nLocal Open Scope positive_scope.\n\n(** ** Specification of [succ] in term of [add] *)\n\nLemma pos_add_1_r p : p + 1 = pos_succ p.\nProof.\n  by destruct p.\nQed.\n\nLemma pos_add_1_l p : 1 + p = pos_succ p.\nProof.\n  by destruct p.\nQed.\n\n(** ** Specification of [add_carry] *)\n\nTheorem pos_add_carry_spec p q : pos_add_carry p q = pos_succ (p + q).\nProof.\n  revert q.\n  induction p; destruct q; simpl; by apply ap.\nQed.\n\n(** ** Commutativity of [add] *)\n\nTheorem pos_add_comm p q : p + q = q + p.\nProof.\n  revert q.\n  induction p; destruct q; simpl; apply ap; trivial.\n  rewrite 2 pos_add_carry_spec; by apply ap.\nQed.\n\n(** ** Permutation of [add] and [succ] *)\n\nTheorem pos_add_succ_r p q : p + pos_succ q = pos_succ (p + q).\nProof.\n  revert q.\n  induction p; destruct q; simpl; apply ap;\n   auto using pos_add_1_r; rewrite pos_add_carry_spec; auto.\nQed.\n\nTheorem pos_add_succ_l p q : pos_succ p + q = pos_succ (p + q).\nProof.\n  rewrite pos_add_comm, (pos_add_comm p). apply pos_add_succ_r.\nQed.\n\nDefinition pos_add_succ p q : p + pos_succ q = pos_succ p + q.\nProof.\n  by rewrite pos_add_succ_r, pos_add_succ_l.\nDefined.\n\nDefinition pos_add_carry_spec_l q r\n  : pos_add_carry q r = pos_succ q + r.\nProof.\n  by rewrite pos_add_carry_spec, pos_add_succ_l.\nQed.\n\nDefinition pos_add_carry_spec_r q r\n  : pos_add_carry q r = q + pos_succ r.\nProof.\n  by rewrite pos_add_carry_spec, pos_add_succ_r.\nDefined.\n\n(** ** No neutral elements for addition *)\nLemma pos_add_no_neutral p q : q + p <> p.\nProof.\n  revert q.\n  induction p as [ |p IHp|p IHp]; intros [ |q|q].\n  1,3: apply x0_neq_xH.\n  1: apply x1_neq_xH.\n  1,3: apply x1_neq_x0.\n  2,4: apply x0_neq_x1.\n  1,2: intro H; apply (IHp q).\n  1: apply x0_inj, H.\n  apply x1_inj, H.\nQed.\n\n(** * Injectivity of pos_succ *)\nLemma pos_succ_inj n m : pos_succ n = pos_succ m -> n = m.\nProof.\n  revert m.\n  induction n as [ | n x | n x]; induction m as [ | m y | m y].\n  + reflexivity.\n  + intro p.\n    destruct (x0_neq_x1 p).\n  + intro p.\n    simpl in p.\n    apply x0_inj in p.\n    destruct m.\n    1,3: destruct (xH_neq_x0 p).\n    destruct (xH_neq_x1 p).\n  + intro p.\n    destruct (x1_neq_x0 p).\n  + simpl.\n    intro p.\n    by apply ap, x1_inj.\n  + intro p.\n    destruct (x1_neq_x0 p).\n  + intro p.\n    cbn in p.\n    apply x0_inj in p.\n    destruct n.\n    1,3: destruct (x0_neq_xH p).\n    destruct (x1_neq_xH p).\n  + intro p.\n    cbn in p.\n    destruct (x0_neq_x1 p).\n  + intro p.\n    apply ap, x, x0_inj, p.\nDefined.\n\n(** ** Addition is associative *)\n\nTheorem pos_add_assoc p q r : p + (q + r) = p + q + r.\nProof.\n  revert q r.\n  induction p.\n  + intros [|q|q] [|r|r].\n    all: try reflexivity.\n    all: simpl.\n    1,2: by destruct r.\n    1,2: apply ap; symmetry.\n    1: apply pos_add_carry_spec.\n    1: apply pos_add_succ_l.\n    apply ap.\n    rewrite pos_add_succ_l.\n    apply pos_add_carry_spec.\n  + intros [|q|q] [|r|r].\n    all: try reflexivity.\n    all: cbn; apply ap.\n    3,4,6: apply IHp.\n    1: apply pos_add_1_r.\n    1: symmetry; apply pos_add_carry_spec_r.\n    1: apply pos_add_succ_r.\n    rewrite 2 pos_add_carry_spec_l.\n    rewrite <- pos_add_succ_r.\n    apply IHp.\n  + intros [|q|q] [|r|r].\n    all: cbn; apply ap.\n    1: apply pos_add_1_r.\n    1: apply pos_add_carry_spec_l.\n    1: apply pos_add_succ.\n    1: apply pos_add_carry_spec.\n    1: apply IHp.\n    2: symmetry; apply pos_add_carry_spec_r.\n    1,2: rewrite 2 pos_add_carry_spec, ?pos_add_succ_l.\n    1,2: apply ap, IHp.\n    rewrite ?pos_add_carry_spec_r.\n    rewrite pos_add_succ.\n    apply IHp.\nQed.\n\n(** ** One is neutral for multiplication *)\n\nLemma pos_mul_1_l p : 1 * p = p.\nProof.\n  reflexivity.\nQed.\n\nLemma pos_mul_1_r p : p * 1 = p.\nProof.\n  induction p; cbn; trivial; by apply ap.\nQed.\n\n(** pos_succ and doubling functions *)\n\nLemma pos_pred_double_succ n\n  : pos_pred_double (pos_succ n) = n~1.\nProof.\n  induction n as [|n|n nH].\n  all: trivial.\n  cbn; apply ap, nH.\nQed.\n\nLemma pos_succ_pred_double n\n  : pos_succ (pos_pred_double n) = n~0.\nProof.\n  induction n as [|n nH|n].\n  all: trivial.\n  cbn; apply ap, nH.\nQed.\n\n(** ** Iteration and pos_succ *)\nLemma pos_iter_succ_l {A} (f : A -> A) p a\n  : pos_iter f (pos_succ p) a = f (pos_iter f p a).\nProof.\n  unfold pos_iter.\n  by rewrite pos_peano_ind_beta_pos_succ.\nQed.\n\nLemma pos_iter_succ_r {A} (f : A -> A) p a\n  : pos_iter f (pos_succ p) a = pos_iter f p (f a).\nProof.\n  revert p f a.\n  srapply pos_peano_ind.\n  1: hnf; intros; trivial.\n  hnf; intros p q f a.\n  refine (_ @ _ @ _^).\n  1,3: unfold pos_iter;\n    by rewrite pos_peano_ind_beta_pos_succ.\n  apply ap.\n  apply q.\nQed.\n\n(** ** Right reduction properties for multiplication *)\nLemma mul_xO_r p q : p * q~0 = (p * q)~0.\nProof.\n  induction p; simpl; f_ap; f_ap; trivial.\nQed.\n\nLemma mul_xI_r p q : p * q~1 = p + (p * q)~0.\nProof.\n  induction p; simpl; trivial; f_ap.\n  rewrite IHp.\n  rewrite pos_add_assoc.\n  rewrite (pos_add_comm q p).\n  symmetry.\n  apply pos_add_assoc.\nQed.\n\n(** ** Commutativity of multiplication *)\nLemma pos_mul_comm p q : p * q = q * p.\nProof.\n  induction q; simpl.\n  1: apply pos_mul_1_r.\n  + rewrite mul_xO_r.\n    f_ap.\n  + rewrite mul_xI_r.\n    f_ap; f_ap.\nQed.\n\n(** ** Distributivity of addition over multiplication *)\nTheorem pos_mul_add_distr_l p q r :\n  p * (q + r) = p * q + p * r.\nProof.\n  induction p; cbn; [reflexivity | f_ap | ].\n  rewrite IHp.\n  set (m:=(p*q)~0).\n  set (n:=(p*r)~0).\n  change ((p*q+p*r)~0) with (m+n).\n  rewrite 2 pos_add_assoc; f_ap.\n  rewrite <- 2 pos_add_assoc; f_ap.\n  apply pos_add_comm.\nQed.\n\nTheorem pos_mul_add_distr_r p q r :\n  (p + q) * r = p * r + q * r.\nProof.\n  rewrite 3 (pos_mul_comm _ r); apply pos_mul_add_distr_l.\nQed.\n\n(** ** Associativity of multiplication *)\nTheorem pos_mul_assoc p q r : p * (q * r) = p * q * r.\nProof.\n  induction p; simpl; rewrite ?IHp; trivial.\n  by rewrite pos_mul_add_distr_r.\nQed.\n\n(** ** pos_succ and pos_mul *)\n\nLemma pos_mul_succ_l p q\n  : (pos_succ p) * q = p * q + q.\nProof.\n  by rewrite <- pos_add_1_r, pos_mul_add_distr_r, pos_mul_1_l.\nQed.\n\nLemma pos_mul_succ_r p q\n  : p * (pos_succ q) = p + p * q.\nProof.\n  by rewrite <- pos_add_1_l, pos_mul_add_distr_l, pos_mul_1_r.\nQed.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Spaces/Pos/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7440720278808786}}
{"text": "Require Import Nat.\nRequire Import Fin.\nRequire Import Vector.\nRequire Import Program.\n\n(****************)\n(* Isomorphisms *)\n(****************)\n\n(* isomorphism of Types *)\nRecord Iso (A B : Type) : Type :=\n  MkIso {\n      to :     A -> B;\n      from :   B -> A;\n      toFrom : forall (b : B), (to (from b) = b);\n      fromTo : forall (a : A), (from (to a) = a)\n  }.\n\nNotation \" A ≅ B \" := (Iso A B) (at level 9).\n\n(* identity isomorphism *)\nDefinition idIso (A : Type) : A ≅ A := \n  (MkIso _ _ id id (fun _ => eq_refl) (fun _ => eq_refl)).\n\n(* inversion of isomorphisms *)\nDefinition symIso {A B : Type} : A ≅ B -> B ≅ A.\nProof.\n  intro isoAB.\n  destruct isoAB as [to from toFrom fromTo].\n  exact (MkIso _ _ from to fromTo toFrom).\nDefined.\n\n(* we even have (but never use..) *)\nLemma symIsoIso {A B : Type} : (A ≅ B) ≅ (B ≅ A).\nProof.\n  apply (MkIso _ _ symIso symIso);\n  intro isoab; destruct isoab; simpl; reflexivity.\nDefined.\n  \n(* composition of isomorphisms *)\nDefinition transIso {A B C : Type} : B ≅ C -> A ≅ B -> A ≅ C.\nProof.\n  intros isoBC isoAB.  \n  destruct isoBC as [bc cb bccb cbbc].\n  destruct isoAB as [ab ba abba baab].\n  apply (MkIso _ _ (bc ∘ ab) (ba ∘ cb)).\n  + intro c; compute; rewrite (abba (cb c)); rewrite (bccb c); reflexivity.\n  + intro a; compute; rewrite (cbbc (ab a)); rewrite (baab a); reflexivity.\nDefined.      \n\n(* ∘≅  = \\circ\\cong *)\nNotation \" iso1 ∘≅ iso2 \" := (transIso iso1 iso2) (at level 20).\n\nDefinition flipTransIso {A B C : Type} : A ≅ B -> B ≅ C -> A ≅ C.\nProof.\n   intros isoAB isoBC.  \n   exact (isoBC ∘≅ isoAB).\nDefined.\n\n(* ⇛  = \\Rrightarrow , ⇚  = \\Lleftarrow *)\nNotation \" iso ⇛ \" := (transIso iso) (at level 19).\nNotation \" iso ⇚ \" := (transIso (symIso iso)) (at level 19).\nNotation \" ⇛ iso \" := (flipTransIso iso) (at level 19).\nNotation \" ⇚ iso \" := (flipTransIso (symIso iso)) (at level 19).\n  \n(*\n(* with function extensionality, we would even have: *)\nLemma transIsoIso (A B C : Type) (isoBC : B ≅ C) : (A ≅ B) ≅ (A ≅ C).\n\n  but not here... \n*)\n\n(****************)\n(* Finite Types *)\n(****************)\n\n(* property of a type to be finite *)\nRecord Finite (X : Type) : Type :=\n  MkFinite {\n      card : nat;\n      isoFin : Iso X (Fin.t card)\n  }.\n\n(* the type of finite types *)\nDefinition FiniteType : Type := sigT Finite.\n\n(* for any cardinality, we have the standard finite type\n   of that cardinality *)\nDefinition FinFinite (card : nat) : FiniteType.\nProof.\n  unfold FiniteType.\n  exists (Fin.t card).\n  apply (MkFinite (Fin.t card) card (idIso (Fin.t card))).\nDefined.\n\n(**************************************************)\n(* operations on FiniteType:                      *)\n(**************************************************)\n\n(* Many constructions producing a type from \n   some parameter types yield finite types if \n   the parameter types are finite.\n\n   Examples considered below are \n     option :    Type -> Type\n     sum, prod:  Type -> Type -> Type\n     Vect.t _ n: Type -> Type (for some n:nat)\n\n   The function type A -> B of finite types\n   A and B cannot be shown to be finite, although\n   of course any function f : A -> B is extensionally\n   determined by the list of values it takes on the\n   elements of A. That's why we take Vector.t B (card A)\n   as the type of functions between finite sets A and B,\n   see below. \n\n   Remark: Only the finiteness of A is necessary for \n   this indentification to be reasonable, so we will also\n   identify a type family on a finite type A - i.e. a \n   function A -> Type - with a Vector of types although \n   of course neither Type nor FiniteType are finite.\n\n*)   \n\n(* ---------------------------------------------*)\n(* operations on FiniteType: Option             *)\n(* ---------------------------------------------*)\n\n(* option preserves finiteness *)\n\nDefinition optionFinTo {n : nat} (f : Fin.t (S n)) : option (Fin.t n) :=\n  match f with\n    | F1 => None\n    | FS f' => Some f'\n  end.\n\nDefinition optionFinFrom {n : nat} (of : option (Fin.t n)) : Fin.t (S n) :=\n  match of with\n    | None => F1\n    | Some f' => FS f'\n  end.\n\nDefinition optionFinIso {n : nat} : Iso (Fin.t (S n)) (option (Fin.t n)).\nProof.\n  apply (MkIso _ _ (@optionFinTo n) (@optionFinFrom n)).\n  - induction n; intro b; destruct b; simpl; reflexivity.\n  - induction n; intro a; dependent destruction a; simpl; reflexivity.\nDefined.\n\n(* option is a functor: can define map *)\nDefinition mapOption {A B : Type} (f: A -> B) (oa : option A) : option B :=\n  match oa with\n    | None   => None\n    | Some a => Some (f a)\n  end.\n\n(* option is a functor: map respects isomorphisms *)\nLemma optionIso {A B : Type} : A ≅ B -> (option A) ≅ (option B).\nProof.\n  intro isoAB.\n  destruct isoAB as [ab ba abba baab].\n  apply (MkIso _ _ (mapOption ab) (mapOption ba)).\n  - intro ob; destruct ob as [ b | ]; simpl.\n    + rewrite (abba b); reflexivity.\n    + reflexivity.\n  - intro oa; destruct oa as [ a | ]; simpl.\n    + rewrite (baab a); reflexivity.\n    + reflexivity.\nDefined.\n\n(* option induces an endofunction on FiniteType *)\nDefinition optionFinite : FiniteType -> FiniteType.\nProof.\n  intro X.\n  destruct X as [X [cardX isoX]].\n  exists (option X).\n  exists (S cardX).\n  apply (optionFinIso ⇚).\n  exact (optionIso isoX).\nDefined.\n\n(* to be done: define Hom, id, comp,... to make FiniteType\n   a category and prove that optionFinite canonically extends\n   to a functor, i.e. define map, prove id-, comp- and iso-preservation!\n*)\n\n(* any finite type is either isomorphic to False or isomorphic to\n   optionFinite of some (Fin.t ..) \n   need's a nicer formulation\n   have to figure out how this can be used for \n   \"induction\" analoguous to nat induction\n *)\nLemma decideFin (X : Type) (Xfin : Finite X) : \n         (X ≅ (Fin.t 0)) + {n : nat & X ≅ (option (Fin.t n))}.\nProof.\n  destruct Xfin as [cardX isoX].\n  induction cardX.\n  + left; exact isoX.\n  + right.\n    exists cardX.\n    apply (optionFinIso ⇛).\n    exact isoX.\nDefined.\n\n(* universal property of sum *)\nDefinition univSum {X Y Z : Type} (f : X -> Z) (g : Y -> Z) (xy: X + Y) : Z :=\n  match xy with\n      | inl x => f x\n      | inr y => g y\n  end.\n\n(* \\triangledown *)\nNotation \" f ▿ g \" := (univSum f g) (at level 10). \n\n(* sum is a functor in both arguments *)\nDefinition sumMap {X Y Z W : Type} (f : X -> Z) (g : Y -> W) : \n                  (X + Y) -> (Z + W) := (inl ∘ f) ▿ (inr ∘ g).\n\n(* \\boxplus *)\nNotation \" f ⊞ g \" := (sumMap f g) (at level 10). \n\n(* towards optionSumIso *)\n\nFixpoint optionSumTo (X Y : Type) ( sumOXY : (option X) + Y) : option (X + Y) :=\n  match sumOXY with\n      | (inl None)      => None\n      | (inl (Some x))  => Some (inl x)\n      | (inr y)         => Some (inr y)\n  end.\n\nFixpoint optionSumFrom (X Y : Type) (oSumXY : option (X + Y)) : (option X) + Y :=\n  match oSumXY with\n      | None            => inl None\n      | Some (inl x)    => inl (Some x)\n      | Some (inr y)    => inr y\n  end.\n                               \nLemma optionSumIso (X Y : Type) : ((option X) + Y) ≅ (option (X + Y)).\nProof.\n  apply (MkIso _ _ (optionSumTo X Y) (optionSumFrom X Y)).  \n  + intro oxy; destruct oxy as [xy | ].    \n    - destruct xy; simpl; reflexivity.\n    - simpl; reflexivity.\n  + intro oxy; destruct oxy as [ox | y].\n    - destruct ox as [x | ]; simpl; reflexivity.\n    - simpl; reflexivity.\nDefined.\n\n(* sum is commutative (up to iso) *)\nLemma sumCommutative (X Y : Type) : (X + Y) ≅ (Y + X).\nProof.\n  apply (MkIso (X + Y) (Y + X) (inr ▿ inl) (inr ▿ inl));\n  intro xy; destruct xy; simpl; reflexivity.\nDefined.\n\n(* sum is a functor: it respects isomorphisms *)\nLemma sumIso {X Y Z W : Type} : X ≅ Y -> Z ≅ W -> (X + Z) ≅ (Y + W).\nProof.\n  intros isoXY isoZW.\n  destruct isoXY as [xy yx xyyx yxxy].\n  destruct isoZW as [zw wz zwwz wzzw].\n  apply (MkIso _ _ (xy ⊞ zw) (yx ⊞ wz)).\n  + intro sumYW; destruct sumYW as [y | w].\n    - compute; rewrite (xyyx y); reflexivity.\n    - compute; rewrite (zwwz w); reflexivity.\n  + intro sumXZ; destruct sumXZ as [x | z].\n    - compute; rewrite (yxxy x); reflexivity.\n    - compute; rewrite (wzzw z); reflexivity.\nDefined.\n\n(* name cases where iso on one side is identity *)\nDefinition sumIsoLeft {X Y : Type} (Z : Type) (isoXY: X ≅ Y) :\n    (X + Z) ≅ (Y + Z) := (sumIso isoXY (idIso Z)).\n\nDefinition sumIsoRight {X Y : Type} (Z : Type) (isoXY: X ≅ Y) :\n    (Z + X) ≅ (Z + Y) := (sumIso (idIso Z) isoXY).\n\n(* (Fin.t 0) is uninhabited, i.e. isomorphic to False *)\nLemma falseFromFin0 (x : Fin.t 0) : False.\nProof.\n  dependent destruction x.\nDefined.\n\nLemma isoFalseFin0 : False ≅ (Fin.t 0).\nProof.\n  apply (MkIso _ _ (False_rect (Fin.t 0)) falseFromFin0).\n  + intro x; dependent destruction x.\n  + intro a; destruct a.\nDefined.\n\n(* in particular, False is Finite *)\nLemma falseIsFinite : Finite False.\nProof.\n   exists 0.\n   exact isoFalseFin0.\nDefined.\n\n(* (Fin.t 1) is isomorphic to True *)\nLemma isoTrueFin1 : True ≅ (Fin.t 1).\nProof.\n  apply (MkIso _ _ (fun _ => F1) (fun _ => I)).\n  + intro i.\n    dependent destruction i.\n    - reflexivity.\n    - dependent destruction i.\n  + intro a; destruct a; reflexivity.      \nDefined.\n\nLemma trueIsFinite : Finite True.\nProof.\n  exists 1.\n  exact isoTrueFin1.\nDefined.\n\n(* False is neutral element for + *)\nLemma sumFalseIso (X : Type) : (False + X) ≅ X.\nProof.\n  apply (MkIso _ _ ((False_rect X) ▿ id) inr).\n  + intro x; simpl; reflexivity.\n  + intro fx; destruct fx as [f | x].\n    - destruct f.  \n    - simpl; reflexivity.\nDefined.\n\n(* (Fin.t 0) is also neutral for + *)\nLemma sumFin0Iso (X : Type) : ((Fin.t 0) + X) ≅ X.\nProof.\n  apply (sumFalseIso _ ⇛).\n  exact (sumIsoLeft _ (symIso isoFalseFin0)).\nDefined.\n\n(* adding (Fin.t 1) is option (up to iso) *)\n\nFixpoint sumFin1IsoTo (X : Type) (t1X : (Fin.t 1) + X) : (option X) := \n   match t1X with\n   | inl _ => None\n   | inr x => Some x\n   end.\n\nFixpoint sumFin1IsoFrom (X : Type) (OX : option X) : (Fin.t 1) + X  :=\n   match OX with\n   | None   => inl F1\n   | Some x => inr x\n   end.\n\nLemma sumFin1Iso (X : Type) : ((Fin.t 1) + X) ≅ (option X).\nProof.\n  apply (MkIso _ _ (sumFin1IsoTo X) (sumFin1IsoFrom X)).\n  + intro OX; destruct OX; simpl; reflexivity.\n  + intro sumt1X; destruct sumt1X as [t | x].\n    - simpl. \n      dependent destruction t. \n      * reflexivity.\n      * dependent destruction t.\n    - simpl; reflexivity.\nDefined.\n\nLemma sumFin1FinNIso (n : nat) : ((Fin.t 1) + (Fin.t n)) ≅ (Fin.t (S n)).\nProof.\n  apply (optionFinIso ⇚).\n  exact (sumFin1Iso _).\nDefined.\n\n(* the sum of two finite types is finite *)\n\nLemma sumIsFiniteLemma (n m : nat) : forall (X Y : Type),\n                          (X ≅ (Fin.t n)) -> (Y ≅ (Fin.t m)) ->\n                          ((X + Y) ≅ (Fin.t (n + m))).\nProof.\n  induction n.\n  + intros X Y isoXt0 isoYtm.\n    simpl.\n    apply ((sumFalseIso _) ⇛).\n    apply ((sumIsoLeft _ isoFalseFin0) ⇚).\n    exact (sumIso isoXt0 isoYtm).\n  + intros X Y isoXtSn isoYtm.\n    apply ((@optionFinIso (n + m)) ⇚).\n    apply ((optionIso (IHn _ _ (idIso (Fin.t n)) (idIso (Fin.t m)))) ⇛).\n    apply ((optionSumIso _ _) ⇛).\n    apply ((sumIsoLeft _ optionFinIso) ⇛).\n    exact (sumIso isoXtSn isoYtm).\nDefined.\n    \nLemma sumIsFinite (X Y : Type) (Xfin : Finite X) (Yfin : Finite Y) : Finite (X + Y).\nProof.\n  destruct Xfin as [cardX isoX].\n  destruct Yfin as [cardY isoY].\n  apply (MkFinite _ (cardX + cardY)).\n  apply (sumIsFiniteLemma cardX cardY X Y isoX isoY).\nDefined.\n      \nFixpoint sumFinite (X Y : FiniteType) : FiniteType.\nProof.\n   destruct X as [X Xfin].\n   destruct Y as [Y Yfin].\n   exists (sum X Y).\n   exact (sumIsFinite X Y Xfin Yfin).\nDefined.\n\n(* towards prodFinite *)\n(* universal property of prod *)\n\nDefinition univProd {X Y Z : Type} (f : X -> Y) (g : X -> Z) (x : X) : Y * Z := (f x , g x).\n\n(* \\triangle *)\nNotation \" f ▵ g \" := (univProd f g) (at level 10). \n\n(* prod is a functor in both arguments *)\n\nDefinition prodMap {X Y Z W : Type} (f : X -> Z) (g : Y -> W) : \n                              (X * Y) -> (Z * W) := (f ∘ fst) ▵ (g ∘ snd).\n\n(* \\boxtimes *)\nNotation \" f ⊠ g \" := (prodMap f g) (at level 10). \n\n(* prod is commutative (up to iso) *)\nLemma prodCommutative (X Y : Type) : (X * Y) ≅ (Y * X).\nProof.\n  apply (MkIso (X * Y) (Y * X) (snd ▵ fst) (snd ▵ fst));\n  intro pair; destruct pair; simpl; reflexivity.\nDefined.\n\n(* prod is a functor: it respects isomorphisms *)\nLemma prodIso {X Y Z W : Type} : X ≅ Y -> Z ≅ W -> (X * Z) ≅ (Y * W).\nProof.\n  intros isoXY isoZW. \n  destruct isoXY as [xy yx xyyx yxxy].\n  destruct isoZW as [zw wz zwwz wzzw].\n  apply (MkIso _ _ (xy ⊠ zw) (yx ⊠ wz)).\n  + intro pairYW; destruct pairYW as [y w];\n    compute; rewrite (xyyx y); rewrite (zwwz w); reflexivity.\n  + intro pairXZ; destruct pairXZ as [x z];\n    compute; rewrite (yxxy x); rewrite (wzzw z); reflexivity.\nDefined.\n\nDefinition prodIsoLeft {X Y : Type} (Z : Type) (isoXY : X ≅ Y) :\n                  (X * Z) ≅ (Y * Z) := prodIso isoXY (idIso Z).\n\nDefinition prodIsoRight {X Y : Type} (Z : Type) (isoXY : X ≅ Y) :\n                  (Z * X) ≅ (Z * Y) := prodIso (idIso Z) isoXY.\n\n(* product with False is False *)\nLemma prodFalseIso (X : Type) : (False * X) ≅ False.  \nProof.\n  apply (MkIso _ _ fst (id ▵ (False_rect X))).\n  + intro f; destruct f.\n  + intro fx; destruct fx as [f x]. destruct f.\nDefined.\n\n(* True is neutral for prod *)\nLemma prodTrueIso (X : Type) : (True * X) ≅ X.\nProof.\n  apply (MkIso _ _ snd ((fun _ => I) ▵ id)).\n  + intro x; simpl; reflexivity.\n  + intro tx; destruct tx as [t x]; destruct t; simpl; reflexivity.\nDefined.\n\n(* product distributes over sum *)\n\nDefinition prodDistSumIsoTo (X Y Z : Type) (xyz : X * (Y + Z)) : (X * Y) + (X * Z) :=\n  match xyz with\n  | (x , inl y) => inl (x , y)\n  | (x , inr z) => inr (x , z)\n  end.\n\nLemma prodDistSumIsoLeft (X Y Z : Type) : (X * (Y + Z)) ≅ ((X * Y) + (X * Z)).\nProof.\n  apply (MkIso _ _ (prodDistSumIsoTo X Y Z) ((id ⊠ inl) ▿ (id ⊠ inr))).\n  + intro sumXYXZ; destruct sumXYXZ as [pair | pair];\n    destruct pair; simpl; reflexivity.\n  + intro pairXSumYZ. \n    destruct pairXSumYZ as [x [y | z]]; simpl; reflexivity.\nDefined.\n\nLemma prodDistSumIsoRight (X Y Z : Type) : ((Y + Z) * X) ≅ ((Y * X) + (Z * X)). \nProof.\n  apply (⇚ (prodCommutative X (Y + Z))).\n  apply ((sumIso (prodCommutative X Y) (prodCommutative X Z)) ⇛).\n  exact (prodDistSumIsoLeft X Y Z).\nDefined.\n\nLemma prodIsFiniteLemma (n m : nat) : forall (X Y : Type),\n        (X ≅ (Fin.t n)) -> (Y ≅ (Fin.t m)) -> ((X * Y) ≅ (Fin.t (n * m))).\nProof.\n  induction n.\n  + intros X Y isoXt0 isoYtm.\n    simpl.\n    apply (isoFalseFin0 ⇛).\n    apply ((prodFalseIso (Fin.t m)) ⇛).\n    apply ((prodIsoLeft _ isoFalseFin0) ⇚).\n    exact (prodIso isoXt0 isoYtm).\n  + intros X Y isoXtSn isoYtm.\n    apply ((sumIsFiniteLemma _ _ _ _ (idIso (Fin.t m)) \n                                     (idIso (Fin.t (n * m)))) ⇛).\n    apply ((sumIsoRight _  (IHn (Fin.t n) (Fin.t m) (idIso _) (idIso _))) ⇛).\n    apply ((sumIsoLeft _ (prodTrueIso (Fin.t m))) ⇛).\n    apply ((sumIsoLeft _ (prodIsoLeft _ isoTrueFin1)) ⇚).\n    apply ((prodDistSumIsoRight _ _ _) ⇛).\n    apply ((prodIsoLeft _ (sumFin1FinNIso n)) ⇚).\n    exact (prodIso isoXtSn isoYtm).\nDefined.\n\nLemma prodIsFinite (X Y : Type) (Xfin : Finite X) (Yfin : Finite Y) : Finite (X * Y).\nProof.\n   destruct Xfin as [cardX isoX].\n   destruct Yfin as [cardY isoY].\n   apply (MkFinite _ (cardX * cardY)).\n   apply (prodIsFiniteLemma cardX cardY X Y isoX isoY).\nDefined.\n\nLemma prodFinite (X Y : FiniteType) : FiniteType.\nProof.\n   destruct X as [X Xfin].\n   destruct Y as [Y Yfin].\n   exists (prod X Y).\n   exact (prodIsFinite X Y Xfin Yfin).\nDefined.\n\n(* now for the exponential:\n\n   problem: we cannot show that for finite X and Y\n   X -> Y is finite: \n\n   The cardinality should of course be cardY ^ cardX. But then already for\n   X ≅ t 0 ≅ False, we would have to show that there is exactly one map \n   False -> Y for any type Y, so we'd have to show that any map \n   False -> Y is equal to False_rect Y, and since we don't have function \n   extensionality, there is no chance to do that.\n\n   Instead, we define Hom for finite types X, Y to be\n          Hom X Y  :=  Vect.t Y cardX\n\n   That looks strange since the right hand side does not depend\n   on X itself, but only on its cardinality.\n\n   However, since the finite set X comes with an isomorphisms to (t cardX),\n   we can define maps\n\n       X -> Y   --- toHom --->   Hom X Y\n                <-- fromHom --\n\n   Without function extensionality, we cannot prove\n\n            fromHom . toHom = id (X -> Y).\n\n   But it should be possible to prove \n\n            toHom . fromHom = id (Hom X Y).\n\n   And it shouldn't be hard to prove \n\n            (Vect Y cardX ) ≅ t (cardY ^ cardX)),\n\n   i.e. Hom X Y finite for finite X and Y.\n *)\n\n(* first, we define a type for Hom *)\nDefinition HomFinT (X Y : FiniteType) : Type.\nProof.\n  destruct X as [X [cardX isoX]].\n  destruct Y as [Y [cardY isoY]].\n  exact (Vector.t Y cardX).\nDefined.\n\nSearchAbout \"nth\".\nPrint VectorDef.nth.\nPrint VectorDef.nil.\nPrint VectorDef.cons.\n\nPrint \"::\".\nSearchPattern (nat -> nat -> nat).\n\n(* towards vectProdIso *)\n\nFixpoint vectProdTo (X : Type) (n : nat) (v : Vector.t X (S n)) : X * (Vector.t X n) :=\n  match v with\n  | (VectorDef.cons _ x _ xs) => (x , xs)\n  end.\n\nFixpoint vectProdFrom (X : Type) (n : nat) (p : X * (Vector.t X n)) : Vector.t X (S n) :=\n  match p with\n  | (x , xs) => VectorDef.cons X x n xs\n  end.\n\nLemma vectProdIso (X : Type) (n : nat) : (Vector.t X (S n)) ≅ (X * (Vector.t X n)).\nProof.\n  apply (MkIso _ _ (vectProdTo X n) (vectProdFrom X n)).\n  + intro pair.\n    destruct pair as [x v].\n    dependent destruction v; simpl; reflexivity.  \n  + intro v.\n    dependent destruction v.\n    dependent destruction v; simpl; reflexivity.  \nDefined.    \n\nFixpoint lemma1To (X : Type) (v : Vector.t X 0) : Fin.t 1 :=\n  match v with\n  | nil _ => F1\n  end.\n\nLemma lemma1From (X : Type) (i : Fin.t 1) : Vector.t X 0.\nProof.\n  exact (nil X).\nDefined.\n\nLemma lemma (n m : nat) : (Vector.t (Fin.t n) m) ≅ (Fin.t (n ^ m)).\nProof.\n  induction m.\n  + simpl.\n    apply (MkIso _ _ (lemma1To (Fin.t n)) (lemma1From (Fin.t n))).\n    - intro f; dependent destruction f.\n      * simpl; reflexivity.\n      * dependent destruction f; simpl.\n    - intro v; simpl; dependent destruction v; reflexivity.\n  + apply (transIso (prodIsFiniteLemma n (n ^ m)\n                        (Fin.t n) (Fin.t (n ^ m)) (idIso _) (idIso _))).\n    apply (transIso (prodIsoRight (Fin.t n) IHm)).\n    exact (vectProdIso (Fin.t n) m).\nDefined.", "meta": {"author": "margrit", "repo": "Code", "sha": "b3e89580b33732c23cdf4df8171d6c76ce9186e7", "save_path": "github-repos/coq/margrit-Code", "path": "github-repos/coq/margrit-Code/Code-b3e89580b33732c23cdf4df8171d6c76ce9186e7/Code/Finite_Set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7439828847358161}}
{"text": "Require Export SfLib.\nRequire Export WLImp.\nRequire Export Coq.Sets.Ensembles.\n\n(* Lemma that states that the intersection is commutative, B intersection C equals C intersection B.*)\nLemma intersect_commute: forall U B C, \n  (Intersection U B C) = (Intersection U C B).\nProof.\n  intros.\n  apply Extensionality_Ensembles.\n  unfold Same_set. split;\n  unfold Included; intros u H; inversion H; apply Intersection_intro; \n  assumption; assumption.\nQed.\n\nHint Resolve intersect_commute : ensemble.\n\n(* Lemma that states that the union is commutative, B union C equals C union B.*)\nLemma union_commute: forall U B C, \n  (Union U B C) = (Union U C B).\nProof.\n  intros.\n  apply Extensionality_Ensembles.\n  unfold Same_set. split;\n  unfold Included; intros u H; inversion H; \n  [apply Union_intror | apply Union_introl | apply Union_intror | apply Union_introl]; assumption.\nQed.\n\nHint Resolve union_commute : ensemble.\n\n(*Lemma that states that the intersection of an empty set with another set (B) is always the empty set.*)\nLemma empty_intersect: forall U B, \n  (Intersection U B (Empty_set U)) = Empty_set U.\nProof.\n  intros U B.\n  apply Extensionality_Ensembles. \n  unfold Same_set. split; unfold Included; intros x H; inversion H; try assumption.\nQed.\n\nHint Resolve empty_intersect : ensemble.\n\n(*Lemma that states that some set (S) minus an empty set is always that some set(S).*)\nLemma empty_S_minus: forall U S, \n  (Setminus U S (Empty_set U)) = S.\nProof.\n  intros. \n  apply Extensionality_Ensembles. \n  unfold Same_set. split; unfold Included; intros x H.\n  Case \"left\".\n    unfold Setminus in H. inversion H. assumption.\n  Case \"right\".\n    unfold Setminus. split. assumption.\n    intros Hcontra. inversion Hcontra.    \nQed.\n\nHint Resolve empty_S_minus : ensemble.\n\n(*Lemma that states that the some set (S) minus an empty set is always that set(S).*)\nLemma empty_minus: forall U, \n  (Setminus U (Empty_set U) (Empty_set U)) = Empty_set U.\nProof.  \n  intros U.\n  apply empty_S_minus.\nQed.\n\nHint Resolve empty_minus : ensemble.\n\n(* Lemma that states that some set (S) minus that same set (S) is always the empty set.*)\nLemma same_minus: forall U S, \n  (Setminus U S S) = Empty_set U.\nProof.\n  intros.\n  apply Extensionality_Ensembles.   \n  unfold Same_set. split; unfold Included; intros x H.\n  Case \"left\".\n    unfold Setminus in H. inversion H. contradiction.\n  Case \"right\".\n    inversion H.\nQed.\n\nHint Resolve same_minus : ensemble.\n\n(*Lemma that states that the empty set minus some set(S) is always the empty set.*)\nLemma empty_minus_S: forall U S, \n  (Setminus U (Empty_set U) (S)) = Empty_set U.\nProof.\n  intros.\n  apply Extensionality_Ensembles.   \n  unfold Same_set. split; unfold Included; intros x H.\n  Case \"left\".\n    unfold Setminus in H. inversion H. assumption.\n  Case \"right\".\n    inversion H.\nQed.\n\nHint Resolve empty_minus_S : ensemble.\n\n(*Lemma that states that the empty set union some set (S) is always that some set (S).*)\nLemma empty_S_union: forall U S, \n  (Union U (Empty_set U) S) = S.\nProof.\n  intros.\n  apply Extensionality_Ensembles.   \n  unfold Same_set. split; unfold Included; intros x H.\n  Case \"left\".\n    inversion H. inversion H0. assumption.\n  Case \"right\".\n    apply Union_intror. assumption.\nQed.\n\nHint Resolve empty_S_union : ensemble.\n\n(*Lemma that states that the union of two empty set is always de empty set*)\nLemma empty_union: forall U, \n  (Union U (Empty_set U) (Empty_set U)) = Empty_set U.\nProof.\n  intros U. rewrite empty_S_union. reflexivity. Qed.\n\nHint Resolve empty_union : ensemble.\n\n(*Lemma that states that if we know that union of some two sets (S1 and S2) is equal to the empty set.\n  Then we can conclude that the first of those sets (S1) is equal to empty set.*)\nLemma S_S_union_empty: forall U S1 S2,\n  Union U S1 S2 = (Empty_set U) -> \n  S1 = (Empty_set U).\nProof.\n  intros U S1 S2 H.\n  apply Extensionality_Ensembles. unfold Same_set. split.\n  unfold Included. intros w. rewrite <- H. apply Union_introl.\n  unfold Included. intros w. intros Hcontra. inversion Hcontra.\nQed.\n\nHint Resolve S_S_union_empty : ensemble.\n\n(* Lemma that states that a set (S1) plus and element (u) union another set (S2) \n   is the same as the union of the two sets (S1 and S2) and the addittion of the element (u) *)\nLemma add_union : forall U S1 S2 u,\n  Union U (Add U S1 u) S2 = Add U (Union U S1 S2) u.\nProof.\n  intros U S1 S2 u.\n  apply Extensionality_Ensembles.\n  unfold Same_set.\n  unfold Included.\n  unfold In.\n  unfold Add.\n  split.\n  intros. inversion H. inversion H0.   apply Union_introl. apply Union_introl. assumption.\n  apply Union_intror. assumption.\n  apply Union_introl. apply Union_intror. assumption.\n  intros. inversion H. inversion H0. apply Union_introl. apply Union_introl. assumption.\n  apply Union_intror. assumption.\n  apply Union_introl. apply Union_intror. assumption.\nQed.\n\nHint Resolve add_union : ensemble.\n\nLemma in_minus : forall X x y s,\n  x <> y ->\n  In X s y ->\n  In X (Setminus X s (Add X (Empty_set X) x)) y.\nProof.\n  intros X x y s Hxy Hin.\n  split.\n  assumption.\n  intros contra.\n  inversion contra; subst; inversion H; subst.\n  apply Hxy. reflexivity.\nQed.\n\nHint Resolve in_minus : ensemble.\n\nLemma same_union : forall X s,\n  Union X s s = s.\nProof.\n  intros.  \n  apply Extensionality_Ensembles.\n  unfold Same_set.\n  unfold Included.\n  split; intros.\n  inversion H; apply H0.\n  apply Union_intror.\n  assumption.\nQed.\n\nHint Resolve same_union : ensemble.\n\nAxiom de_morgan_not_and_not : forall P Q:Prop,\n  ~(P /\\ Q) -> (~P \\/ ~Q).\n\nLemma not_in_intersect : forall X x s1 s2,\n  ~ In X (Intersection X s1 s2) x <-> ~ (In X s1 x) \\/ ~ (In X s2 x).\nProof.\n  intros.\n  split.\n  intros.\n  (* -> *)  \n  apply de_morgan_not_and_not with (P:= (In X s1 x))(Q:= (In X s2 x)).\n  unfold not in *.\n  intros.\n  apply H.\n  inversion H0.\n  constructor; assumption.\n  (* <- *)\n  intros.\n  unfold not in *.\n  unfold In in *.\n  intros.\n  inversion H.\n  apply H1.\n  inversion H0.\n  assumption.\n  apply H1.\n  inversion H0.\n  assumption.\nQed.\n\nHint Resolve not_in_intersect : ensemble.\n\nLemma not_in_union : forall X x s1 s2,\n  ~ In X (Union X s1 s2) x <-> ~ In X s1 x /\\ ~ In X s2 x.\nProof.\n  intros.\n  split.\n  (*->*)\n  intros.\n  split.\n  unfold In in *.\n  unfold not in *.\n  intros.\n  apply H.\n  apply Union_introl.\n  assumption.\n  unfold not in *.\n  intros.\n  apply H.\n  apply Union_intror.\n  assumption.\n  (*<-*)\n  intros [Hleft Hright].\n  unfold not in *.\n  unfold In in *.\n  intros.\n  inversion H.\n  apply Hleft.\n  apply H0.\n  apply Hright. \n  apply H0.\nQed.\n\nHint Resolve not_in_union : ensemble.\n\n(** Invert all hypothesis interesting to proving that two sets are equal *)\nLtac invert_all :=\n  match goal with\n    | [ H1 : In _ (Union _ _ _) _ |- ?goal ] => \n                    inversion H1; subst; clear H1; invert_all\n    | [ H1 : In _ (Setminus _ _ _) _ |- ?goal ] => \n                    inversion H1; subst; clear H1; invert_all\n    | [ H1 : ~In _ (Union _ _ _) _ |- ?goal ] => \n                    apply not_in_union in H1; invert_all\n    | [ H1 : ~In _ (Intersection _ _ _) _ |- ?goal ] => \n                    apply not_in_intersect in H1; invert_all\n    | [ H1 : _ /\\ _ |- ?goal ] => \n                    inversion H1; subst; clear H1; invert_all\n    | [ H1 : _ \\/ _ |- ?goal ] => \n                    inversion H1; subst; clear H1; invert_all\n    | _ => idtac\n  end.\n\n(** Tactic to prove that two sets are equal *)\nTactic Notation \"set_eq\" :=\n  apply Extensionality_Ensembles;\n  split; intros w Hi;\n  invert_all;\n  try solve by inversion;\n  auto 10 with sets ensemble.\n\n", "meta": {"author": "codenet", "repo": "wl-no-sleep", "sha": "850db8fba4c089018a8cd0f02a093754afbabe15", "save_path": "github-repos/coq/codenet-wl-no-sleep", "path": "github-repos/coq/codenet-wl-no-sleep/wl-no-sleep-850db8fba4c089018a8cd0f02a093754afbabe15/Util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7439167558805463}}
{"text": "(* Grundsaetzliche Anpassungen: \n\n   - Benutzung des Fin.t aus der Standard Library \n   - Nicht mit Prop arbeiten sondern mit Type\n\n*)\n\n(** Wie in der Vorlesung Theoretische Informatik I werden die einzelne Komponenten eines\n deterministischen endlichen Automats (DEA, nachfolgend DFA genannt) als 5-Tupel beschrieben.\n\nDFA = (Q, Sigma, delta, q0, F) mit\n\n* Q, als nichtleere endliche Zustandsmenge\n* Sigma, als (endliches) Eingabealphabet\n* delta: Q x Sigma -> Q, als Zustandsüberführungsfunktion\n* q0, als Startzustand\n* F Teilmenge von Q, als Menge der akzeptierenden Zustände.\n\nDiese Komponenten werden nachfolgend definiert.*)\n\nRequire Import Fin.\n(* Load Pigeonhole_vector. *)\nLoad Word_Prop.\n\nSection Definitions.\n\n(** Die Anzahl der möglichen Zustände.*)\nParameter Q_size : nat.\n\n(** Der Typ der Zustände.*)\nDefinition Q := @Fin.t Q_size.\n\n(** Die Anzahl der Elemente des Eingabealphabets.*)\nParameter S_size : nat.\n\n(** Der Typ des Eingabealphabets.*)\nDefinition Sigma := @Fin.t S_size.\n\n(** Die Transitionsfunktion - delta.*)\nParameter delta : Q -> Sigma -> Q.\n\n(** Die Funktion, die entscheidet, ob ein Zustand ein akzeptierender Zustand ist. *)\nParameter is_accepting : Q -> Prop.\n\n(** Der Startzustand. *)\nParameter q0 : Q.\n\n(** Um zu definieren, wann ein Wort akzeptiert wird, mÜssen noch einige Vorüberlegungen\ngetroffen werden. Hierzu wird die erweiterte Transitionsfunktion [delta_hat] bzw. \n[delta_hat_cons] benötigt. Da im allgemeinen auf Wörtern gearbeitet werden soll, die [snoc] als\nKonstruktor haben, wird dies in den Funktionsnamen weggelassen, um diese kurz zu halten.\nNur wenn explizit auf Listen gearbeitet werden soll, wird der [cons] Konstruktor im Namen\nverwendet.*)\n\n(** Die erweiterte Überführungsfunktion [delta_hat], wie in der Vorlesung definiert.*)\nFixpoint delta_hat (q : Q) (w : @Word Sigma) : Q :=\n   match w with\n    | eps          => q\n    | snoc w' h => delta (delta_hat q w' ) h\n  end.\n\n(** Um ein zusätzliches Zeichen und ein Wort aus dem Eingabealphabet abzuarbeiten kann\nerst das Zeichen vor das Wort gehängt werden, um dann [delta_hat] von dem Ausgangszustand\ndarauf anzuwenden. Die andere Variante ist, dass zuerst der Folgezustand mit [delta] von dem\nZeichen und dem Ausgangszustand berechnet wird und davon ausgehend dann das Wort \nabgearbeitet wird.*)\nLemma delta_hat_Lemma (q : Q) (a : Sigma) (w : @Word Sigma) :\n  delta_hat q (concat_word (snoc eps a) w) = delta_hat (delta q a) w.\nProof.\ninduction w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw.\n    reflexivity.\nDefined.\n\nTheorem delta_hat_app : forall w v : @Word Sigma, forall q : Q,\n  delta_hat q (concat_word w v) = delta_hat (delta_hat q w) v.\nProof.\n  induction v.\n  - simpl.\n    intros q.\n    reflexivity.\n  - simpl.\n    intros.\n    rewrite <- IHv.\n    reflexivity.\nDefined.\n\nDefinition accepted_word (w : @Word Sigma) : Prop :=\n  is_accepting (delta_hat q0 w).\n\n(** Die von einem endlichen Automaten beschriebene Sprachen.*)\nDefinition DFA_Lang (w : @Word Sigma) : Prop :=\n  accepted_word w.\n\n(* Der Typ der Konfigurationen eines DFA, Conf_DFA = Q x @Word Sigma*.*)\n(*Definition Conf_DFA := Q * (list Sigma) : Type.*)\nDefinition Conf_DFA := Q * (@Word Sigma) : Type.\n\n(* Konfigurationsübergangsrelation mit Type*)\n\n(*### geht besser ###*)\n(* Ein einzelner Konfigurationsschritt. Ausgehend von einer Konfiguration, einem Zeichen\naus Sigma und einem Wort, wird das Zeichen durch [delta] abgearbeitet und führt zur\nnachfolgenden Konfiguration.*)\nInductive Conf_DFA_step : Conf_DFA -> Conf_DFA -> Type :=\n | one_step : forall (q : Q) (p : Q) (a : Sigma) (w : @Word Sigma) (eq : (delta q a) = p),\n                                    Conf_DFA_step (q, (snoc w a)) (p, w).\n\n(* Die reflexiv-transitive Hülle von Conf_rel_DFA_step.\nK ext_conf M <=> K = M (revlexiv) oder \nex L mit K ext_conf L und L conf_step M (reflexiv-transitive Hülle)*)\nInductive Conf_rel_DFA : Conf_DFA -> Conf_DFA -> Type :=\n  | refl    : forall (K : Conf_DFA), Conf_rel_DFA K K\n  | step  : forall (K L M : Conf_DFA),\n                                     Conf_rel_DFA K L ->\n                                     Conf_DFA_step L M ->\n                                     Conf_rel_DFA K M.\n\n(** Für die Anwendung des Pumping Lemmas muss die Abarbeitung eines Wortes in einer Liste\ngespeichert werden, da diese Informationen enthält, ob ein Zustand mehrfach durchlaufen wird.\nDies ist der Fall, wenn die Anzahl der Konfigurationen innerhalb der Liste länger ist, als die Anzahl\nder Zustände des Automaten.*)\n\n(* Ableiten der nächsten Konfiguration [next_Conf].*)\nFixpoint next_Conf  (conf : Conf_DFA) : option Conf_DFA :=\n  match conf with\n    | (q, eps)      => None\n    | (q, snoc w a) => Some (delta q a, w)\n  end.\n\n(*Konfigurationssequenz in einer Liste speichern.*)\nFixpoint conf_seq' (w : @Word Sigma) : Q -> list Conf_DFA :=\n  match w with\n    | eps        => fun q : Q => cons (q, eps) nil\n    | snoc w' a  => fun q : Q => cons (q, w) (conf_seq' w' (delta q a))\n  end.\n\nPrint conf_seq'.\n(* aber im 2. Fall muss (q, w) zur Liste hinzugefuegt werden, oder? *)\n\nFixpoint conf_seq (conf : Conf_DFA) : list Conf_DFA :=\n  match conf with\n    | (q, w) => conf_seq' w q\n  end.\n\n(*################# Alternativ ###################*)\n\n(* Ich habe auch nichts wirklich Besseres zu bieten. Man koennte vermutlich einen\n   anonymen Fixpunkt benutzen, aber dadurch wird es nicht lesbarer und \n   ich sehe auch sonst keinen Vorteil.\n   Die \"Wrapper\" Funktion muss dann natuerlich kein Fixpunkt sein. *)\n\nFixpoint conf_list (w : @Word Sigma) (q : Q) : list Conf_DFA :=\n let conf := (q, w) in\n  match w with\n    | eps       => cons conf nil\n    | snoc w' a => cons conf (conf_list w' (delta q a))\n  end.\n\nDefinition conf_to_conf_list (conf : Conf_DFA) : list Conf_DFA :=\n  let (q, w) := conf in conf_list w q.\n\nFixpoint state_letter_list (w : @Word Sigma) (q : Q) : list (Q * option Sigma) :=\n match w with \n  | eps => cons (q, None) nil\n  | snoc w' a => cons (q, Some a) (state_letter_list w' (delta q a))\n end.\n\n(*Definition der akzeptierten Sprache\nDefinition L_DFA (w : list Sigma) : Conf_DFA:=\nexists p : Q, Conf_rel_DFA (q0 , w) (p, nil).\n*)\n\nEnd Definitions.\n\n", "meta": {"author": "margrit", "repo": "Code", "sha": "b3e89580b33732c23cdf4df8171d6c76ce9186e7", "save_path": "github-repos/coq/margrit-Code", "path": "github-repos/coq/margrit-Code/Code-b3e89580b33732c23cdf4df8171d6c76ce9186e7/Code/alt/DFA_Def_accept_Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7439167477916356}}
{"text": "(* A proposition is (computationally) decidable                                 *)\nDefinition Dec (A:Prop) : Type := {A} + {~A}.\n\n(* A predicate is (computationally) decidable                                    *)\nDefinition pDec (a:Type) (p:a -> Prop) : Type := forall (x:a), Dec (p x).\n\nArguments pDec {a}.\n\n(* Two-fold decidable predicates                                                *)\nDefinition pDec2 (a b:Type) (p:a -> b -> Prop) := \n    forall (x:a) (y:b), Dec (p x y).\n\nArguments pDec2 {a} {b}.\n\nLemma pDec2Dec : forall (a b:Type) (p:a -> b ->Prop) (x:a),\n    pDec2 p -> pDec (p x).\nProof.\n    intros a b p x H1 y. apply H1.\nDefined.\n\nDefinition DeciderOf (a:Type) (p:a -> Prop) (f:a -> bool) : Prop :=\n    forall (x:a), p x <-> f x = true.\n\nArguments DeciderOf {a}.\n\nDefinition Decidable (a:Type) (p:a -> Prop) : Prop :=\n    exists (f:a -> bool), DeciderOf p f.\n\nArguments Decidable {a}.\n\nLemma pDecDecidable : forall (a:Type) (p:a -> Prop),\n    pDec p -> Decidable p.\nProof.\n    intros a p q. remember (fun x => \n        match (q x) with\n        | left _    => true\n        | right _   => false\n        end) as f eqn:E.\n    exists f. intros x. split; intros H1.\n    - rewrite E. destruct (q x) as [H2|H2].\n        + reflexivity.\n        + apply H2 in H1. contradiction.\n    - rewrite E in H1. destruct (q x) as [H2|H2].\n        + assumption.\n        + inversion H1.\nQed.\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/Logic/Axiom/Dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7439167457942338}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_ray2.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_rayimpliescollinear.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_collinearitypreserved.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_raystrict.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_equalanglesNC : \n   forall A B C a b c, \n   CongA A B C a b c ->\n   nCol a b c.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists U V u v, (Out B A U /\\ Out B C V /\\ Out b a u /\\ Out b c v /\\ Cong B U b u /\\ Cong B V b v /\\ Cong U V u v /\\ nCol A B C)) by (conclude_def CongA );destruct Tf as [U[V[u[v]]]];spliter.\nassert (neq b a) by (conclude lemma_ray2).\nassert (neq a b) by (conclude lemma_inequalitysymmetric).\nassert (Cong b u B U) by (conclude lemma_congruencesymmetric).\nassert (Cong b v B V) by (conclude lemma_congruencesymmetric).\nassert (Col B A U) by (conclude lemma_rayimpliescollinear).\nassert (Col B C V) by (conclude lemma_rayimpliescollinear).\nassert (Col b a u) by (conclude lemma_rayimpliescollinear).\nassert (Col b c v) by (conclude lemma_rayimpliescollinear).\nassert (Col a b u) by (forward_using lemma_collinearorder).\nassert (~ Col a b c).\n {\n intro.\n assert (Col b u c) by (conclude lemma_collinear4).\n assert (Col c b u) by (forward_using lemma_collinearorder).\n assert (Col c b v) by (forward_using lemma_collinearorder).\n assert (neq b c) by (conclude lemma_ray2).\n assert (neq c b) by (conclude lemma_inequalitysymmetric).\n assert (Col b u v) by (conclude lemma_collinear4).\n assert (Cong u v U V) by (conclude lemma_congruencesymmetric).\n assert (Col B U V) by (conclude lemma_collinearitypreserved).\n assert (Col B U A) by (forward_using lemma_collinearorder).\n assert (neq B U) by (conclude lemma_raystrict).\n assert (Col U V A) by (conclude lemma_collinear4).\n assert (Col U V B) by (forward_using lemma_collinearorder).\n assert (Col V A B).\n by cases on (eq U V \\/ neq U V).\n {\n  assert (Col B A V) by (conclude cn_equalitysub).\n  assert (Col V A B) by (forward_using lemma_collinearorder).\n  close.\n  }\n {\n  assert (Col V A B) by (conclude lemma_collinear4).\n  close.\n  }\n(** cases *)\n assert (Col V B A) by (forward_using lemma_collinearorder).\n assert (Col V B C) by (forward_using lemma_collinearorder).\n assert (neq B V) by (conclude lemma_raystrict).\n assert (neq V B) by (conclude lemma_inequalitysymmetric).\n assert (Col B A C) by (conclude lemma_collinear4).\n assert (Col A B C) by (forward_using lemma_collinearorder).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_equalanglesNC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7439167417497785}}
{"text": "Require Import FOL.\nRequire Import Deduction.\nRequire Import Tarski.\nRequire Import VectorTech.\nRequire Import List.\nRequire Import Lia.\n\n(* I follow the treatment of Peter Smith in \"Introduction to Gödel's Theorems\"\n (page 37) *)\n\n\n(* Define the non-logical symbols used in the language of PA *)\n\nInductive PA_funcs : Type :=\n  Zero : PA_funcs\n| Succ : PA_funcs\n| Plus : PA_funcs\n| Mult : PA_funcs.\n\nDefinition PA_funcs_ar (f : PA_funcs ) :=\nmatch f with\n | Zero => 0\n | Succ => 1\n | Plus => 2\n | Mult => 2\n end.\n\nInductive PA_preds : Type :=\n  Eq : PA_preds.\n\nDefinition PA_preds_ar (P : PA_preds) :=\nmatch P with\n | Eq => 2\nend.\n\n\nInstance PA_funcs_signature : funcs_signature :=\n{| syms := PA_funcs ; ar_syms := PA_funcs_ar |}.\n\nInstance PA_preds_signature : preds_signature :=\n{| preds := PA_preds ; ar_preds := PA_preds_ar |}.\n\n \nArguments Vector.cons {_} _ {_} _, _ _ _ _.\n\nDefinition zero := func Zero (Vector.nil term).\nNotation \"'σ' x\" := (@func PA_funcs_signature Succ (Vector.cons x (Vector.nil term))) (at level 37).\nNotation \"x '⊕' y\" := (@func PA_funcs_signature Plus (Vector.cons x (Vector.cons y (Vector.nil term))) ) (at level 39).\nNotation \"x '⊗' y\" := (@func PA_funcs_signature Mult (Vector.cons x (Vector.cons y (Vector.nil term))) ) (at level 38).\nNotation \"x '==' y\" := (@atom PA_funcs_signature PA_preds_signature _ Eq (Vector.cons term x 1 (Vector.cons term y 0 (Vector.nil term))) ) (at level 40).\n\n\n\nFixpoint num n :=\n  match n with\n    O => zero\n  | S x => σ (num x)\n  end.\n\n                      \n\n\n(* formulate axioms of PA (see page 92) *)\n\nDefinition ax_zero_succ := ∀    zero == σ $0 --> fal.\nDefinition ax_succ_inj :=  ∀ ∀  σ $1 == σ $0 --> $1 == $0.\nDefinition ax_add_zero :=  ∀    zero ⊕ $0 == $0.\nDefinition ax_add_rec :=   ∀ ∀  (σ $0) ⊕ $1 == σ ($0 ⊕ $1).\nDefinition ax_mult_zero := ∀    zero ⊗ $0 == zero.\nDefinition ax_mult_rec :=  ∀ ∀  σ $1 ⊗ $0 == $0 ⊕ $1 ⊗ $0.\n\nDefinition PA_induction (phi : form) :=\n  phi[zero..] --> (∀ phi --> phi[σ $0 .: S >> var]) --> ∀ phi.\n\nDefinition phi := $0 == $1.\n\nCompute (phi[zero..]).\nCompute (phi[zero .: S >> var]).\n\n(* substitutes t for the variable $0 and leaves all other variables unchanged *)\nDefinition var0_subst (t : term) : nat -> term :=\n  fun n => match n with 0 => t | S n => var (S n) end.\n\n\n(* var0_subst can be expressed with scons and funcomp *)\nLemma var0_subst_spec t n :\n  var0_subst t n = (t .: S >> var) n.\nProof.\n  now destruct n as [].\nQed.\n\n\n\n                                              \n\n(*** Working in models of PA ***)\n                                              \nSection Models.                                              \n  \n\n  Variable D : Type.\n  Variable I : interp D.\n\n  Definition Equality := forall v, @i_P _ _ D I Eq v <-> Vector.hd v = Vector.hd (Vector.tl v). \n  Hypothesis equality : forall v, @i_P _ _ D I Eq v <-> Vector.hd v = Vector.hd (Vector.tl v).\n\n  (* The following predicate expresses that a model satisfies the minimal axioms of PA i.e. all axioms except S x <> 0 *)\n  Definition sat_PA_minimal_axioms :=\n    forall rho,\n      rho ⊨_FOL ax_succ_inj\n      /\\ rho ⊨_FOL ax_add_zero\n      /\\ rho ⊨_FOL ax_add_rec\n      /\\ rho ⊨_FOL ax_mult_zero\n      /\\ rho ⊨_FOL ax_mult_rec\n      /\\ (forall phi, rho ⊨_FOL (PA_induction phi) ).      \n\n\n  Definition sat_PA_axioms :=\n    sat_PA_minimal_axioms /\\ forall rho, rho ⊨_FOL ax_zero_succ.\n\n\n\n\n  \n  Lemma PAeq_sym : forall rho a b, rho ⊨_FOL (a == b) -> rho ⊨_FOL (b == a).\n  Proof.\n    intros rho a b H. apply equality; cbn. apply equality in H; cbn in H. auto.\n  Qed.\n  \n  Lemma PAeq_trans : forall rho a b c, rho ⊨_FOL (a == b) /\\ rho ⊨_FOL (b == c) -> rho ⊨_FOL (a == c).\n  Proof.\n    intros rho a b c. cbn. rewrite !equality. cbn. intros [C B]. now rewrite C, B.\n  Qed.\n\n  Definition iO := i_f (f:=Zero) (Vector.nil D).\n  Notation \"'iσ' d\" := (i_f (f:=Succ) (Vector.cons d (Vector.nil D))) (at level 37).\n  Notation \"x 'i⊕' y\" := (i_f (f:=Plus) (Vector.cons x (Vector.cons y (Vector.nil D)))) (at level 39).\n  Notation \"x 'i⊗' y\" := (i_f (f:=Mult) (Vector.cons x (Vector.cons y (Vector.nil D)))) (at level 38).\n  Definition iμ k := iter (fun x => iσ x) k iO.\n\n\n\n  (* provide all axioms in a more useful form *)\n  Theorem succ_inj:\n    (forall rho, rho ⊨_FOL ax_succ_inj) -> forall n d, iσ d = iσ n -> d = n.\n  Proof.\n    intros H n d. specialize (H (fun _ => iO) d n).\n    cbn in H. rewrite !equality in H; now cbn in H.\n  Qed.\n\n  Theorem add_zero :\n    (forall rho, rho ⊨_FOL ax_add_zero) -> forall d, iO i⊕ d = d.\n  Proof.\n    intros H d. specialize (H (fun _ => iO) d).\n    cbn in H. rewrite equality in H; now cbn in H.\n  Qed.\n\n  Theorem add_rec :\n    (forall rho, rho ⊨_FOL ax_add_rec) -> forall n d, (iσ n) i⊕ d = iσ (n i⊕ d). \n  Proof.\n    intros H n d.\n    specialize (H (fun _ => iO) d n).\n    cbn in H. rewrite !equality in H; now cbn in H.\n  Qed.\n      \n  Theorem mult_zero :\n    (forall rho, rho ⊨_FOL ax_mult_zero) -> forall d, iO i⊗ d = iO.\n  Proof.\n    intros H d. specialize (H (fun _ => iO) d).\n    cbn in H. rewrite !equality in H. now cbn in H.\n  Qed.\n\n  Theorem mult_rec :\n    (forall rho, rho ⊨_FOL ax_mult_rec) -> forall n d, (iσ d) i⊗ n = n i⊕ (d i⊗ n).\n  Proof.\n    intros H n d. specialize (H (fun _ => iO) d n).\n    cbn in H. rewrite !equality in H; now cbn in H.\n  Qed.\n\n  \n  Variable AX : sat_PA_minimal_axioms.\n  \n  \n  Theorem PAinduction_weak (phi : form) rho :\n    rho ⊨_FOL phi[zero..] -> rho ⊨_FOL (∀ phi --> phi[σ $ 0 .: S >> var]) -> rho ⊨_FOL (∀ phi).\n  Proof.\n    destruct (AX rho) as (_&_&_&_&_&H). cbn. apply (H phi).\n  Qed.\n  \n  \n  Definition null := (fun _ : nat => iO).\n  Definition representable (P : D -> Prop) := exists phi rho, forall d, P d <-> (d.:rho) ⊨_FOL phi.\n\n  Lemma sat_single (rho : nat -> D) (Phi : form) (t : term) :\n    (eval rho t .: rho) ⊨_FOL Phi <-> rho ⊨_FOL subst_form (t..) Phi.\n  Proof.\n    rewrite sat_comp. apply sat_ext. now intros [].\n  Qed.\n\n  (** Useful induction principle *)\n  \n  Theorem PAinduction (P : D -> Prop) :\n    representable P -> P iO -> (forall d, P d -> P (iσ d)) -> forall d, P d.\n  Proof.\n    intros (phi & rho & repr) P0 IH. intros d. rewrite repr.\n    apply PAinduction_weak.\n    - apply sat_single. apply repr. apply P0.\n    - cbn. intros d' H. apply repr, IH, repr in H.\n      apply sat_comp. eapply sat_ext; try apply H. now intros [].\n  Qed.\n\n  (** Examples *)\n\n  Lemma add_exists : forall (phi : form) rho, rho ⊨_FOL phi -> exists sigma, sigma ⊨_FOL (∃ phi).\n  Proof.\n    intros phi rho H; cbn. exists (fun n => match n with\n                           | O => rho 1\n                           | S m => rho (S n)\n                                end); exists (rho 0).\n    unfold scons. eapply sat_ext; try apply H. now intros [|[|]].\n  Qed.\n\n  Definition exist_times n (phi : form) := iter (fun psi => ∃ psi) n phi.\n  \n  Lemma add_n_exists : forall n,\n      forall (phi : form) rho, rho ⊨_FOL phi -> exists sigma, sigma ⊨_FOL (exist_times n phi).\n  Proof.\n    induction n; intros phi rho H.\n    - exists rho. auto. \n    - destruct (IHn _ _ H) as [s Hs]. now refine (add_exists _ s _).\n  Qed.\n  \n  Lemma zero_or_succ : forall rho, rho ⊨_FOL (∀ zero == $0 ∨ ∃ $1 == σ $0).\n  Proof.\n    intros rho. apply PAinduction_weak.\n    - left. now apply equality.\n    - intros d _. right. exists d; now apply equality.\n  Qed.\n\n\n  Goal forall d, iO = d \\/ exists x, d = iσ x. \n  Proof.\n    enough (forall rho, rho ⊨_FOL (∀ zero == $0 ∨ ∃ $1 == σ $0)) as H. intros d.\n    specialize (H null). cbn in H. specialize (H d). revert H.\n    rewrite equality. cbn.\n    intros [<- | [x H]]. now left. right. rewrite equality in H. now exists x.\n    apply zero_or_succ.\n  Qed.\n\n  Goal forall d, iO = d \\/ exists x, d = iσ x. \n  Proof.\n    apply PAinduction.\n    pose (phi := zero == $0 ∨ ∃ $1 == σ $0).\n    - exists phi, (fun _ => iO). split.\n      + intros [<- | [x ->]].\n        * left. cbn. now rewrite equality.\n        * right. exists x. cbn. now rewrite equality.\n      + intros [H | [x H]].\n        * left. cbn in H. now rewrite equality in H.\n        * right. exists x. cbn in H. now rewrite equality in H.\n    - now left.\n    - intros d [<- |]; right. now exists iO. now exists d.\n  Qed.\n\n  Lemma add_rec_right :\n    forall d n, n i⊕ (iσ d) = iσ (n i⊕ d).\n  Proof.\n    intros n. apply PAinduction.\n    - pose (phi := ∀ $0 ⊕ σ $1 == σ ($0 ⊕ $1) ).\n      exists phi, (fun _ => iO). admit.\n    - rewrite !add_zero; try reflexivity. all: firstorder.\n    - intros d IH. rewrite !add_rec. now rewrite IH. all: firstorder.\n  Admitted.\n    \n  \n  \n  \n  Section TrivialModel.\n\n    Variable Bot : iμ 0 = iμ 1.\n    \n    Lemma ModelHasOnlyZero' rho : rho ⊨_FOL (∀ $0 == zero).\n    Proof.\n      apply PAinduction_weak.\n      - cbn; now apply equality.\n      - cbn. fold iO. intros d. rewrite !equality; cbn. intros IH.\n        now rewrite IH. \n    Qed.\n\n    \n    Fact ModelHasOnlyZero : forall d, d = iO.\n    Proof.\n      apply PAinduction.\n      pose (phi := $0 == zero).\n      - exists phi, (fun _ => iO). split.\n        + intros ->. cbn. now rewrite equality.\n        + intros H. cbn in H. now rewrite equality in H.\n      - reflexivity.\n      - intros d. now intros ->.\n    Qed.\n\n    \n    Lemma trivial_induction' rho phi : rho ⊨_FOL (phi[zero..] --> ∀ phi).\n    Proof.\n      cbn. intros H0. apply PAinduction_weak.\n      - exact H0.\n      - cbn. intros d IH. apply sat_comp.\n        refine (@sat_ext' _ _ _ _ (d.:rho) _ phi _ _).\n        destruct x; cbn; rewrite ModelHasOnlyZero; apply ModelHasOnlyZero.\n        exact IH.\n    Qed.\n      \n    \n    Fact trivial_induction : forall P, representable P -> P iO -> forall d, P d.\n    Proof.\n      intros P Rep P0. apply PAinduction; try auto.\n      intros. now rewrite ModelHasOnlyZero.  \n    Qed.\n    \n         \n  End TrivialModel.\n \nEnd Models.\n\n                           \n\n\n\n\n\n\n\n\n\n(*** Working with a Deduction System ***)\n\nSection ND.\n\n  Variable p : peirce.\n  Definition FA' := ax_add_zero::ax_add_rec::ax_mult_zero::ax_mult_rec::nil.\n\n  Definition ax_refl := (∀ $0 == $0).\n  Definition ax_sym := (∀ ∀ $0 == $1 --> $1 == $0).\n  Definition ax_trans := (∀∀∀ $0 == $1 --> $1 == $2 --> $0 == $2).\n\n  Definition ax_eq_succ := (∀∀ $0 == $1 --> σ $0 == σ $1).\n  Definition ax_eq_add := (∀∀∀∀ $0 == $1 --> $2 == $3 --> $0 ⊕ $2 == $1 ⊕ $3).\n  Definition ax_eq_mult := (∀∀∀∀ $0 == $1 --> $2 == $3 --> $0 ⊗ $2 == $1 ⊗ $3).\n\n  Definition FA := ax_refl::ax_sym::ax_trans::ax_eq_succ::ax_eq_add::ax_eq_mult::FA'.\n\n  Lemma numeral_subst_invariance : forall n rho, subst_term rho (num n) = num n.\n  Proof.\n    induction n.\n    - reflexivity.\n    - intros rho. cbn. now rewrite IHn.\n  Qed.\n\n  Lemma term_subst_invariance t : forall rho,\n      bound_term 0 t = true -> subst_term rho t = t.\n  Proof.\n    induction t.\n    - intros ? H. inversion H.\n    - intros rho HB. cbn. f_equal.\n      enough ( Vector.map (subst_term rho) v = Vector.map id v ) as eq.\n      cbn in eq. rewrite eq at 1. now rewrite (Vector.map_id _ _).\n      apply Vector.map_ext_in.\n      intros x Hx. cbv [id]. apply IH.\n      assumption. refine (bound_term_parts _ _).\n      apply HB. now apply vec_map_In.\n  Qed.\n\n  Lemma FA_refl t :\n    FA ⊢_MSFOL (t == t).\n  Proof.\n    assert (FA ⊢_MSFOL ax_refl). apply Ctx. firstorder.\n    eapply AllE in H. cbn in H. apply H.\n  Qed.\n\n  Lemma FA_sym t t' :\n    FA ⊢_MSFOL (t == t') -> FA ⊢_MSFOL (t' == t).\n  Proof.\n    intros H. assert (H' : FA ⊢_MSFOL ax_sym). apply Ctx. firstorder.\n    eapply (AllE _ t') in H'. cbn in H'. apply (AllE _ t) in H'. cbn in H'.\n    change (FA ⊢_MSFOL (t == t'`[↑]`[t..] --> t'`[↑]`[t..] == t)) in H'.\n    rewrite subst_term_shift in H'. apply (IE _ _ _ H'), H.\n  Qed.\n\n  Lemma FA_sym' t t' :\n    FA ⊢_MSFOL (t == t') -> FA ⊢_MSFOL (t' == t).\n  Proof.\n    intros H. assert (H' : FA ⊢_MSFOL ax_sym). apply Ctx. firstorder.\n    eapply (AllE _ t') in H'. cbn in H'.\n    change (FA ⊢_MSFOL (∀ $0 == t'`[↑] --> t'`[↑] == $0)) in H'.\n    apply (AllE _ t) in H'.\n    change (FA ⊢_MSFOL (t == t'`[↑]`[t..] --> t'`[↑]`[t..] == t)) in H'.\n    rewrite subst_term_shift in H'. apply (IE _ _ _ H'), H.\n  Qed.\n  \n\n  Lemma FA_tran a b c :\n    FA ⊢_MSFOL (a == b) -> FA ⊢_MSFOL (b == c) -> FA ⊢_MSFOL (a == c).\n  Proof.\n    intros H1 H2. assert (H : FA ⊢_MSFOL ax_trans). apply Ctx. firstorder.\n    apply (AllE _ c) in H. cbn in H.\n    change (FA ⊢_MSFOL ∀∀ $0 == $1 --> $1 == c`[↑]`[↑] --> $0 == c`[↑]`[↑]) in H.\n    apply (AllE _ b) in H. cbn in H.\n    change (FA ⊢_MSFOL ∀ $0 == b`[↑] --> b`[↑] == c`[↑]`[↑]`[up b..] --> $0 == c`[↑]`[↑]`[up b..]) in H.\n    apply (AllE _ a) in H. cbn in H.\n    change (FA ⊢_MSFOL (a == b`[↑]`[a..] --> b`[↑]`[a..] == c`[↑]`[↑]`[up b..]`[a..] --> a == c`[↑]`[↑]`[up b..]`[a..])) in H.\n    rewrite (up_term (c`[↑])) in H. rewrite !subst_term_shift in H.\n\n    enough (FA ⊢_MSFOL (b == c --> a == c)) as H'. apply (IE _ _ _ H'), H2.\n    apply (IE _ _ _ H), H1.\n  Qed.\n\n  (*\n    Definition ax_zero_succ := ∀    zero == σ var 0 --> fal.\n    Definition ax_succ_inj :=  ∀ ∀  σ $1 == σ $0 --> $1 == $0.\n    Definition ax_add_zero :=  ∀    zero ⊕ $0 == $0.\n    Definition ax_add_rec :=   ∀ ∀  (σ $0) ⊕ $1 == σ ($0 ⊕ $1).\n    Definition ax_mult_zero := ∀    zero ⊗ $0 == zero.\n    Definition ax_mult_rec :=  ∀ ∀  σ $1 ⊗ $0 == $0 ⊕ $1 ⊗ $0.\n\n    Definition ax_refl := (∀ $0 == $0).\n    Definition ax_sym := (∀ ∀ $0 == $1 --> $1 == $0).\n    Definition ax_trans := (∀∀∀ $0 == $1 --> $1 == $2 --> $0 == $2).\n\n    Definition ax_eq_succ := (∀∀ $0 == $1 --> σ $0 == σ $1).\n    Definition ax_eq_add := (∀∀∀∀ $0 == $1 --> $2 == $3 --> $0 ⊕ $2 == $1 ⊕ $3).\n    Definition ax_eq_mult := (∀∀∀∀ $0 == $1 --> $2 == $3 --> $0 ⊗ $2 == $1 ⊗ $3).\n  *)\n\n  Lemma num_add_homomorphism x y :\n    FA ⊢_MSFOL (num x ⊕ num y == num (x + y)).\n  Proof.\n    induction x.\n    - cbn. assert (H : FA ⊢_MSFOL ax_add_zero). apply Ctx. firstorder.\n      eapply AllE in H. apply H.\n    - cbn. assert (H1 : FA ⊢_MSFOL ax_add_rec). apply Ctx. firstorder.\n      eapply (AllE _ (num y)) in H1. \n      eapply (AllE _ (num x)) in H1. \n      cbn in H1. rewrite !numeral_subst_invariance in H1.\n\n      eapply FA_tran. exact H1.\n\n      assert (H2 : FA ⊢_MSFOL ax_eq_succ). apply Ctx. firstorder.\n      eapply (AllE _ ?[b]) in H2. eapply (AllE _ ?[a]) in H2. cbn in H2.\n      change (FA ⊢_MSFOL (?a == ?b`[↑]`[?a..] --> σ ?a == σ ?b`[↑]`[?a..])) in H2.\n      rewrite subst_term_shift in H2.\n\n      eapply IE. exact H2. exact IHx.\n  Qed.\n\n  (* Lemma num_mult_homomorphism x y : FA ⊢_MSFOL ( num x ⊗ num y == num (x * y) ).\n  Proof.\n    induction x.\n    - cbn. assert (H : FA ⊢_MSFOL ax_mult_zero). apply Ctx. firstorder.\n      eapply AllE in H. apply H.\n    - cbn.\n  Admitted.\n\n  Lemma leibniz phi t t' :\n    FA ⊢_MSFOL (t == t') -> FA ⊢_MSFOL phi[t..] -> FA ⊢_MSFOL phi[t'..].\n  Proof.\n    intros H1 H2. induction H2 in |-*.\n    - \n  Admitted. *)\n\n\n\n\nEnd ND.\n", "meta": {"author": "harp-project", "repo": "FOL-in-ML", "sha": "be1dc55efd966648ff2255e25018fc4e144b6961", "save_path": "github-repos/coq/harp-project-FOL-in-ML", "path": "github-repos/coq/harp-project-FOL-in-ML/FOL-in-ML-be1dc55efd966648ff2255e25018fc4e144b6961/PA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7438992518723849}}
{"text": "(* continuations.v *)\n(* dIFP 2014-2015, Q1 *)\n(* Teacher: Olivier Danvy <danvy@cs.au.dk> *)\n\n(* Student name: ... *)\n(* Student number: ... *)\n\n(* ********** *)\n\nRequire Import Arith NPeano String List unfold_tactic.\n\nCheck div.\nCompute (div 5 3, div 6 3, div 7 3, div 8 3, div 9 3).\n\n(* ********** *)\n\n(* The arithmetic expressions: *)\n\nInductive expression : Type :=\n  | Lit : nat -> expression\n  | Plus : expression -> expression -> expression\n  | Times : expression -> expression -> expression\n  | Minus : expression -> expression -> expression\n  | Divide : expression -> expression -> expression.\n\n(* ********** *)\n\n(* An expressible value is the result of evaluating an expression: *)\n\nDefinition expressible := nat.\n\n(* Type conversion between natural numbers and expressible values: *)\n\nDefinition nat_to_expressible (n : nat) : expressible :=\n  n.\n\nDefinition expressible_to_nat (v : expressible) : nat :=\n  v.\n\n(* Operations over expressible values: *)\n\nDefinition plus_expressible (v1 v2 : expressible) : expressible :=\n  nat_to_expressible (expressible_to_nat v1 + expressible_to_nat v2).\n\nDefinition times_expressible (v1 v2 : expressible) : expressible :=\n  nat_to_expressible (expressible_to_nat v1 * expressible_to_nat v2).\n\nDefinition ltb_expressible (v1 v2 : expressible) : bool :=\n  ltb (expressible_to_nat v1) (expressible_to_nat v2).\n\nDefinition minus_expressible (v1 v2 : expressible) : expressible :=\n  nat_to_expressible (expressible_to_nat v1 - expressible_to_nat v2).\n\nDefinition zerop_expressible (v : expressible) : bool :=\n  match expressible_to_nat v with\n    | 0 => true\n    | _ => false\n  end.\n\nDefinition divide_expressible (v1 v2 : expressible) : expressible :=\n  nat_to_expressible (div (expressible_to_nat v1) (expressible_to_nat v2)).\n\n(* ********** *)\n\n(* The result of interpreting an arithmetic expression :\n   * an expressible value, or\n   * an error message\n*)\n\nInductive result : Type :=\n  | Value : expressible -> result\n  | Error : string -> result.\n\n(* ********** *)\n\n(* Two useful lemmas: *)\n\nLemma same_Value :\n  forall v_1 v_2 : nat,\n    Value v_1 = Value v_2 -> v_1 = v_2.\nProof.\n  intros v_1 v_2 H_Value.\n  injection H_Value.  (* Ja, ja, we didn't see this one in class... *)\n  intro H_tmp.\n  exact H_tmp.\nQed.\n\n(* Note: you won't need \"injection\" in this term project. *)\n\nLemma same_Error :\n  forall s_1 s_2 : string,\n    Error s_1 = Error s_2 -> s_1 = s_2.\nProof.\n  intros s_1 s_2 H_Error.\n  injection H_Error.\n  intro H_tmp.\n  exact H_tmp.\nQed.\n\n(* ********** *)\n\n(* Specification of the interpreter: *)\n\nDefinition specification_of_interpret (interpret : expression -> result) :=\n  (forall n : nat,\n     interpret (Lit n) = Value (nat_to_expressible n))\n  /\\\n  ((forall (e1 e2 : expression) (s1 : string),\n      interpret e1 = Error s1 ->\n      interpret (Plus e1 e2) = Error s1)\n   /\\\n   (forall (e1 e2 : expression) (v1 : expressible) (s2 : string),\n      interpret e1 = Value v1 ->\n      interpret e2 = Error s2 ->\n      interpret (Plus e1 e2) = Error s2)\n   /\\\n   (forall (e1 e2 : expression) (v1 v2 : expressible),\n      interpret e1 = Value v1 ->\n      interpret e2 = Value v2 ->\n      interpret (Plus e1 e2) = Value (plus_expressible v1 v2)))\n  /\\\n  ((forall (e1 e2 : expression) (s1 : string),\n      interpret e1 = Error s1 ->\n      interpret (Times e1 e2) = Error s1)\n   /\\\n   (forall (e1 e2 : expression) (v1 : expressible) (s2 : string),\n      interpret e1 = Value v1 ->\n      interpret e2 = Error s2 ->\n      interpret (Times e1 e2) = Error s2)\n   /\\\n   (forall (e1 e2 : expression) (v1 v2 : expressible),\n      interpret e1 = Value v1 ->\n      interpret e2 = Value v2 ->\n      interpret (Times e1 e2) = Value (times_expressible v1 v2)))\n  /\\\n  ((forall (e1 e2 : expression) (s1 : string),\n      interpret e1 = Error s1 ->\n      interpret (Minus e1 e2) = Error s1)\n   /\\\n   (forall (e1 e2 : expression) (v1 : expressible) (s2 : string),\n      interpret e1 = Value v1 ->\n      interpret e2 = Error s2 ->\n      interpret (Minus e1 e2) = Error s2)\n   /\\\n   (forall (e1 e2 : expression) (v1 v2 : expressible),\n      interpret e1 = Value v1 ->\n      interpret e2 = Value v2 ->\n      ltb_expressible v1 v2 = true ->\n      interpret (Minus e1 e2) = Error \"numerical underflow\")\n  /\\\n   (forall (e1 e2 : expression) (v1 v2 : expressible),\n      interpret e1 = Value v1 ->\n      interpret e2 = Value v2 ->\n      ltb_expressible v1 v2 = false ->\n      interpret (Minus e1 e2) = Value (minus_expressible v1 v2)))\n   /\\\n  ((forall (e1 e2 : expression) (s1 : string),\n      interpret e1 = Error s1 ->\n      interpret (Divide e1 e2) = Error s1)\n   /\\\n   (forall (e1 e2 : expression) (v1 : expressible) (s2 : string),\n      interpret e1 = Value v1 ->\n      interpret e2 = Error s2 ->\n      interpret (Divide e1 e2) = Error s2)\n   /\\\n   (forall (e1 e2 : expression) (v1 v2 : expressible),\n      interpret e1 = Value v1 ->\n      interpret e2 = Value v2 ->\n      zerop_expressible v2 = true ->\n      interpret (Divide e1 e2) = Error \"division by zero\")\n   /\\\n   (forall (e1 e2 : expression) (v1 v2 : nat),\n      interpret e1 = Value v1 ->\n      interpret e2 = Value v2 ->\n      zerop_expressible v2 = false ->\n      interpret (Divide e1 e2) = Value (divide_expressible v1 v2))).\n\n(* ********** *)\n\n(* You are asked to:\n\n\n   * define unit tests of course;\n\n\n   * prove that the specification above specifies a unique function;\n\n\n   * implement an interpreter in direct style\n\n       Fixpoint interpreter_ds (e : expression) : result :=\n         ...\n  \n       Definition interpreter_v0 (e : expression) : result :=\n         interpreter_ds ...\n\n     and prove that it satisfies the specification of the interpreter;\n\n\n   * write an interpreter in continuation-passing style,\n\n       Fixpoint interpreter_cps (ans : Type)\n                                (e : expression)\n                                (k : result -> ans) : ans :=\n         ...\n  \n       Definition interpreter_v1 (e : expression) : result :=\n         interpreter_cps ...\n\n     and prove that it satisfies the specification of the interpreter;\n\n\n   * write an interpreter in continuation-passing style\n     with two continuations, one for values and the other for errors,     \n\n       Fixpoint interpreter_cps2 (ans : Type)\n                                 (e : expression)\n                                 (vk : expressible -> ans)\n                                 (ek : string -> ans) : ans :=\n         ...\n  \n       Definition interpreter_v2 (e : expression) : result :=\n         interpreter_cps2 ...\n\n     and prove that it satisfies the specification of the interpreter.\n\n\n   * write a continuation-based interpreter\n     with one continuation,\n\n       Fixpoint interpreter_cps' (e : expression)\n                                 (k : expressible -> result) : result :=\n         ...\n  \n       Definition interpreter_v3 (e : expression) : result :=\n         interpreter_cps' ...\n\n     and prove that it satisfies the specification of the interpreter.\n     (Note: \"continuation-based\" means that interpreter_cps' is using\n     a continuation and all of its calls are tail calls,\n     but the type of its result is not an abstract type of answers.)\n*)\n\n(* ********** *)\n\n(* end of continuations.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/difp/term-projects/continuations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7438992397767203}}
{"text": "Require Import Coq.omega.Omega.\n\n\nLemma min_def {x y} : min x y = x - (x - y).\nProof. apply Min.min_case_strong; omega. Qed.\nLemma max_def {x y} : max x y = x + (y - x).\nProof. apply Max.max_case_strong; omega. Qed.\n\nLemma min_minus_l x y\n  : min (x - y) x = x - y.\nProof. Time apply Min.min_case_strong; omega. Qed. (* Finished transaction in 0. secs (0.06u,0.004s) *)\n\nLemma min_minus_l' x y\n  : min (x - y) x = x - y.\nProof. Time rewrite min_def; omega. Qed. (* Finished transaction in 1. secs (1.128u,0.004s) *)\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_omega.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7438476024803978}}
{"text": "\n(*-------------Description ------------------------------------------------------  \n\nThis file implements powersets for ordered set of elements on ordered type.\nLet A be an OrdType. We first define ordering on lists of elements from A.\nHence we connect the domain (list A) to the OrdType. Then we define and operation\nto append an element a in front of each list present in a collection of lists.\nUsing this append (app) function we define a function (pw l) to generate a\nlist containing all the subsets of list l.\n \n\nFollowing are the notions defined in this file:\n\n Fixpoint pw (l: list A): list (list A):=\n                                       match l with\n                                          |nil => nil::nil\n                                          |a::l' => union (a [::] (pw l')) (pw l')\n                                       end.\n\n\n Predicate                  Boolean function                  Connecting Lemma\n Max_sub_in G I P           max_sub_in G I P                  max_sub_inP \n Min_sub_in G I P           min_sub_in G I P                  min_sub_inP\n\n\nFurthermore, we have results on existence of largest and smallest subsets with \nthe property P\n\nLemma exists_largest_inb (G: list A)(B: list A-> bool):\n    (exists X, In X (pw G) /\\ B X) ->\n    (exists I, In I (pw G) /\\ B I /\\ forall Y, In Y (pw G)-> B Y -> |Y| <=b |I|).\n\nLemma exists_largest_in (G: list A)(B: list A-> bool):\n    (exists X, In X (pw G) /\\ B X) ->\n    (exists I, In I (pw G) /\\ B I /\\ forall Y, In Y (pw G)-> B Y -> |Y| <= |I|).\n\nLemma exists_smallest_inb (G: list A)(B: list A-> bool):\n    (exists X, In X (pw G) /\\ B X) ->\n    (exists I, In I (pw G) /\\ B I /\\ forall Y, In Y (pw G)-> B Y -> |I| <=b |Y|).\n\nLemma exists_smallest_in (G: list A)(B: list A-> bool):\n    (exists X, In X (pw G) /\\ B X) ->\n    (exists I, In I (pw G) /\\ B I /\\ forall Y, In Y (pw G)-> B Y -> |I| <= |Y|).\n\n\n---------------------------------------------------------------------------------*)\n\nRequire Export Lists.List.\nRequire Export MinMax.\nRequire Export GenReflect SetSpecs OrdType.\nRequire Export SetReflect OrdList.\nRequire Export Omega.\nRequire Export OrdSet.\n\nSet Implicit Arguments.\n\n\n\nSection OrderOnPairs.\n\n  Context { A B: ordType }.\n\n  (* ------------ Definition of decidable equality on pair of elements from A*B ----------- *)\n  \n  Definition eqbp (p q: A*B):= (fst p == fst q) && (snd p == snd q).\n\n  Lemma eqbp_refl (p: A*B): eqbp p p.\n  Proof. unfold eqbp. split_; auto. Qed.\n  \n  Lemma eqbp_elim (p q: A*B): eqbp p q -> p = q.\n  Proof. unfold eqbp. move /andP. destruct p , q. simpl.\n         intro h1. destruct h1 as [h1 h2].\n         move /eqP in h1. move /eqP in h2.  subst e;subst e0. auto. Qed.\n  Lemma eqbp_intro (p q: A*B): p = q -> eqbp p q.\n  Proof. intro H; subst p; apply eqbp_refl. Qed.\n  Lemma eqbpP (p q: A*B): reflect (p = q)(eqbp p q).\n  Proof. apply reflect_intro. split. apply eqbp_intro. apply eqbp_elim. Qed.\n  \n  \n  Canonical pair_eqType: eqType:=\n    {| Decidable.E:= (A*B); Decidable.eqb:= eqbp; Decidable.eqP:=eqbpP |}.\n\n  \n  (*------------ Definition and properties of less than relation on lists of A----------- *)\n  \n  Definition ltbp (p q: A*B) := match (comp (fst p) (fst q)) with\n                                | Eq => (snd p) <b (snd q)\n                                | Lt => true\n                                | Gt => false\n                                end.\n\n  Lemma ltbp_elim (p q: A*B):\n    ltbp p q -> ((fst p <b fst q) \\/ (fst p = fst q /\\ snd p <b snd q )).\n  Proof. { unfold ltbp. destruct p as [p1 p2];destruct q as [q1 q2].\n           simpl. match_up p1 q1.\n           { intros h1. right; split;auto. }\n           { intros h1. left; auto. }\n           { intros h1; inversion h1. } } Qed.\n\n  Lemma ltbp_intro (p q: A*B):\n    ((fst p <b fst q) \\/ (fst p = fst q /\\ snd p <b snd q )) -> ltbp p q. \n  Proof. { unfold ltbp. destruct p as [p1 p2];destruct q as [q1 q2].\n           simpl. match_up p1 q1.\n           { intros h1. destruct h1 as [h1 |h1]. by_conflict. apply h1. }\n           { intros h1. auto.  }\n           { intros h1.  destruct h1 as [h1 |h1]. by_conflict.\n             destruct h1.  subst p1. by_conflict. } } Qed.\n\n   Lemma ltbp_intro1 (p q: A*B): (fst p <b fst q) -> ltbp p q.\n   Proof. intro h1. apply ltbp_intro. left;auto. Qed.\n\n    Lemma ltbp_intro2 (p q: A*B): (fst p = fst q /\\ snd p <b snd q ) -> ltbp p q.\n    Proof.  intro h1. apply ltbp_intro. right;auto. Qed.\n                  \n    \nLemma ltbp_irefl (p : A*B): ltbp p p = false.\nProof. destruct p. unfold ltbp. simpl.  match_up e e. switch; auto.\n       rewrite <-H. switch; auto. auto.  Qed.\n\nHint Resolve ltbp_irefl: core.\n\nLemma ltbp_antisym (x y: A*B):  x <> y -> ltbp x y = ~~ ltbp y x.\nProof. { destruct x as [x1 x2]. destruct y as [y1 y2].\n       unfold ltbp. simpl. intro h1. \n       match_up x1 y1; match_up y1 x1.\n       { cut (x2 <> y2).  eapply ltb_antisym0. intros h2.\n         subst x1;subst x2. auto. }\n       { subst x1; absurd (y1 <b y1);auto. }\n       { subst x1; absurd (y1 <b y1);auto. }\n       { subst x1; absurd (y1 <b y1);auto. }\n       { by_conflict. } \n       { simpl; auto. }\n       { subst x1; absurd (y1 <b y1);auto. }\n       { simpl; auto. }\n       { by_conflict. } } Qed.\n\nHint Resolve ltbp_antisym: core.\n\n\nLemma ltbp_trans (x y z: A*B):  ltbp x y -> ltbp y z -> ltbp x z.\nProof. { intros h1 h2.\n         specialize (ltbp_elim x y h1) as h1a.\n         specialize (ltbp_elim y z h2) as h2a.\n         destruct x as [x1 x2];destruct y as [y1 y2];destruct z as [z1 z2].\n         simpl in h1a, h2a. apply ltbp_intro. simpl.\n         destruct h1a as [h1a | h1b]; destruct h2a as [h2a | h2b].\n         { left; auto. }\n         { left. destruct h2b. subst y1;auto. }\n         { left. destruct h1b. subst y1;auto. }\n         { right. destruct h1b;destruct h2b. split;auto. subst x1;auto. } } Qed.\n\nHint Resolve ltbp_trans: core.\n\nCanonical pair_ordType: ordType:= {| Order.D:= pair_eqType;\n                                     Order.ltb:= ltbp;\n                                     Order.ltb_irefl:= ltbp_irefl;\n                                     Order.ltb_antisym := ltbp_antisym;\n                                     Order.ltb_trans := ltbp_trans  |}.\n\nHint Immediate ltbp_elim ltbp_intro: core.\n\nLemma ltbp_intro3 (a: A)(b c: B): b <b c -> (a, b) <b (a, c).\nProof.  intros h1. apply ltbp_intro. simpl. right. split;auto. Qed.\n\nLemma ltbp_intro4 (a b: A)(c d: B): a <b b -> (a, c) <b (b, d).\nProof. intros h1. apply ltbp_intro. simpl. left;auto. Qed.\n\n\nLemma ltbp_elim1  (a: A)(b c: B):(a, b) <b (a, c) -> (b <b c).\nProof. { intros h1. apply ltbp_elim in h1 as h2. simpl in h2.\n         destruct h2 as [h2 |h2].\n         by_conflict. apply h2. } Qed.\n\n\n  \nEnd OrderOnPairs.\n\nHint Immediate ltbp_elim ltbp_intro ltbp_intro1 ltbp_intro2 ltbp_intro4: core.\n\nHint Immediate ltbp_intro3 ltbp_elim1: core.\n\n\n\nSection OrderOnLists.\n\n  Context { A: ordType }.\n\n  (* ------------ Definition of decidable equality on list of elements from A ----------- *)\n  Fixpoint eqbl (l1 l2: list A): bool := match (l1 , l2) with\n                                      |(nil, nil)=> true\n                                      |(nil, b::l2')=> false\n                                      |(a::l1', nil)=> false\n                                      |(a::l1', b::l2')=> match (comp a b) with\n                                                         | Eq => eqbl l1' l2'\n                                                         |Lt => false\n                                                         |Gt => false\n                                                         end\n                                      end.\n\n  Lemma eqbl_refl (l: list A): eqbl l l.\n  Proof. induction l;simpl.  auto. match_up a a. all: (auto || by_conflict). Qed.\n  \n  Lemma eqbl_elim (l1 l2: list A): eqbl l1 l2 -> l1=l2.\n  Proof. { revert l2. induction l1.\n         { intros l2 H; destruct l2. auto. simpl in H; inversion H. }\n         { intro l2; destruct l2. simpl. intro H;inversion H.\n           simpl. match_up a e. subst a.\n           intro H. assert(H1: l1 =l2);auto. subst l1; auto.\n           all: intro H1;inversion H1. } } Qed.\n  Lemma eqbl_intro (l1 l2: list A): l1=l2 -> eqbl l1 l2.\n  Proof. intro H; subst l1; apply eqbl_refl. Qed.\n  Lemma eqblP (l1 l2: list A): reflect (l1=l2)(eqbl l1 l2).\n  Proof. apply reflect_intro. split. apply eqbl_intro. apply eqbl_elim. Qed.\n  \n  \n  Canonical list_eqType: eqType:=\n    {| Decidable.E:= list A; Decidable.eqb:= eqbl; Decidable.eqP:=eqblP |}.\n  \n  (*------------ Definition and properties of less than relation on lists of A----------- *)\n  Fixpoint ltbl (l1 l2: list A): bool := match (l1 , l2) with\n                                      |(nil, nil)=> false\n                                      |(nil, b::l2')=> true\n                                      |(a::l1', nil)=> false\n                                      |(a::l1', b::l2')=> match (comp a b) with\n                                                         |Eq => ltbl l1' l2'\n                                                         |Lt => true\n                                                         |Gt => false\n                                                         end\n                                      end.\n    \nLemma ltbl_irefl (x : list A): ltbl x x = false.\nProof. induction x. auto. simpl; match_up a a; (auto || by_conflict). Qed.\nHint Resolve ltbl_irefl: core.\n\nLemma ltbl_antisym (x y:list A):  x <> y -> ltbl x y = ~~ ltbl y x.\nProof. { revert y. induction x.\n       { intro y. case y. tauto. simpl. auto. }\n       { intro y. case y.  simpl. auto.\n         intros e l. intro H. simpl.\n         match_up a e; match_up e a.\n         subst a; apply IHx; intro H2; subst x;  apply H; auto.\n         all: (try (subst a; by_conflict) || by_conflict).\n         all: try (simpl;auto).  } } Qed.\n\nHint Resolve ltbl_antisym: core.\n\n\nLemma ltbl_trans (x y z:list A):  ltbl x y -> ltbl y z -> ltbl x z.\nProof. { revert y z. induction x.\n       { intros y z H H1. destruct y. simpl in H. inversion H.\n         destruct z. simpl in H1; inversion H1. simpl; auto. }\n       { intros y z H H1. destruct y. simpl in H; inversion H.\n         destruct z. simpl in H1; inversion H1.\n         simpl; simpl in H; simpl in H1.\n         match_up e e0.\n         { subst e. match_up a e0. eapply IHx; [exact H | exact H1]. auto. inversion H. }\n         { match_up a e0.\n           { subst e0. match_up a e. subst a; by_conflict. by_conflict. inversion H. }\n           { auto. }\n           { match_up a e. subst a;by_conflict.\n             assert (H4:e <b a). auto. by_conflict. inversion H. } }\n         { match_up a e0;inversion H1. } } } Qed.\n\nHint Resolve ltbl_trans: core.\n\nCanonical list_ordType: ordType:= {| Order.D:= list_eqType;\n                                     Order.ltb:= ltbl;\n                                     Order.ltb_irefl:= ltbl_irefl;\n                                     Order.ltb_antisym := ltbl_antisym;\n                                     Order.ltb_trans := ltbl_trans  |}.\n\nLemma ltbl_intro (a: A)(l1 l2: list A): l1 <b l2 -> (a::l1) <b (a::l2).\nProof. { intros h1. simpl. match_up a a. apply h1. auto. by_conflict. } Qed.\n\nLemma ltbl_intro1 (a b: A)(l1 l2: list A): a <b b -> (a::l1) <b (b::l2).\nProof. { intros h1. simpl. match_up a b. by_conflict. auto. by_conflict. } Qed.\n\nLemma ltbl_elim (a: A)(l1 l2: list A): (a::l1) <b (a::l2) -> (l1 <b l2).\nProof. { intros h1. simpl in h1. match_up a a. apply h1. all: by_conflict. } Qed.\n\n  \nEnd OrderOnLists.\n\nHint Immediate ltbl_intro ltbl_intro1 ltbl_elim: core.\n\n\nSection Append.\n  Context { A: Type }. (* to declare A as implicit outside the section *)\n   \n   Fixpoint app (a:A)(s: list (list A)): list (list A) :=\n     match s with\n     |nil=> nil\n     |l::s1 => (a::l)::(app a s1)\n     end.\n\n   Notation \"a [::] s\" := (app a s) (at level 70, no associativity).\n   \n   Lemma app_intro (a:A)(x: list A)(s: list (list A)): In x s -> In (a::x) (a [::] s).\n   Proof. { induction s. auto.\n          intro H. destruct H.\n          subst x; simpl; left; auto.\n          simpl; right;auto. } Qed.\n   Lemma app_elim (a:A)(x: list A)(s: list (list A)):\n     In x (a [::] s)-> (exists x', In x' s /\\ x = a::x').\n   Proof. { induction s. simpl. tauto.\n          simpl. intro H;destruct H.\n          { exists a0. split. left;auto. auto. }\n          { apply IHs in H as H1. destruct H1 as [x' H1].\n            exists x'. split. right;apply H1. apply H1. } } Qed.\n   Lemma app_elim1 (a:A)(x: list A)(s: list (list A)):  In (a::x) (a [::] s)-> In x s.\n   Proof. { induction s. simpl. auto.\n          simpl. intro H;destruct H. left. inversion H;auto. right;auto. } Qed.\n   Lemma app_size_same1 (a:A)(s: list (list A)): |s| = | a [::] s |.\n   Proof. induction s; simpl; auto. Qed. \n   Lemma app_size_same2 (a:A)(s: list (list A)): | a [::] s | = |s|.\n   Proof. induction s; simpl; auto. Qed.\n  \nEnd Append.\n\nNotation \"a [::] s\" := (app a s) (at level 70, no associativity).\nHint Immediate app_intro app_elim app_elim1 app_size_same1 app_size_same2: core.\n\n\n\n\nSection PowerSet.\n    Context { A: ordType }.  (* to declare A as implicit outside the section *)\n\n  (*-------- Function to generate powerset for a set l --------------------*)\n  Fixpoint pw (l: list A): list (list A):= match l with\n                                              |nil => nil::nil\n                                              |a::l' => union (a [::] (pw l')) (pw l')\n                                           end.\n\n   Lemma pw_is_ord (l: list A): IsOrd (pw l).\n   Proof.  induction l; simpl; [constructor | auto ].  Qed.\n\n  Lemma app_is_ord (a:A)(l:list (list A)): IsOrd l -> IsOrd (a[::]l).\n  Proof. { induction l. simpl; auto.\n         simpl. intro H.\n         destruct l. simpl;constructor.\n         simpl. constructor. simpl.\n         match_up a a. inversion H;auto. all: try by_conflict.\n         apply IHl; eauto. } Qed.\n    \n  Lemma pw_elim (x l: list A): In x (pw l) -> Subset x l.\n  Proof. { revert x. induction l; intro x.\n         { simpl;intro H;destruct H. subst x; auto. tauto. }\n         { simpl. intro H.\n           assert (Ha: In x (a[::] pw l) \\/ In x (pw l)); auto.\n           destruct Ha.\n           { assert (H0a: exists x', In x' (pw l) /\\ x = a::x'); auto.\n             destruct H0a as [x' H0a]. destruct H0a as [H0a H0b]. subst x; auto. }\n           { cut(x [<=] l); auto. } }  } Qed.\n  Lemma pw_elim1 (x l: list A): IsOrd l ->  In x (pw l) -> IsOrd x.\n  Proof.  { revert x. induction l.\n          { intro x. simpl. intros H H1. destruct H1. subst x. auto. tauto. }\n          { intros x H H1. simpl in H1.\n            assert (H2: In x ( a[::] pw l) \\/ In x (pw l)). auto.\n            destruct H2.\n            { (* when In x (a [::] pw l) *)\n              assert (H2: exists x', In x' (pw l) /\\ x = (a::x')). auto.\n              destruct H2 as [x' H2]. destruct H2 as [H2 H3].\n              assert (H4: IsOrd x'). eauto.\n              assert (H5: x' [<=] l). auto using pw_elim.\n              subst x. destruct x'. auto.\n              assert (H6: a <b e). eauto. apply  IsOrd_cons;auto. }\n            { (* when In x (pw l) *) eauto. } } } Qed.\n              \n  Lemma nil_in_pw (l: list A):  In nil (pw l).\n  Proof. induction l. simpl; left;auto. simpl; cut(In nil (pw l)); auto. Qed.\n\n  Lemma pw_intro (x l:list A): IsOrd x -> IsOrd l -> Subset x l -> In x (pw l).\n  Proof. { revert x. induction l.\n         { simpl. intros x H H1 H2. left. symmetry;auto. }\n         { intros x H H1 H2. destruct x.\n           { auto using nil_in_pw. }\n           { destruct (e==a) eqn:Hea.\n             { move /eqP in Hea. subst e.\n               simpl. cut (In (a::x) (a[::] pw l)). auto.\n               assert (H2a: x [<=] l). eauto.\n               apply app_intro; apply IHl; eauto. }\n             { assert (H2a: e::x [<=] l).  move /eqP in Hea.\n               eapply IsOrd_Subset_elim2. all: auto. auto. \n               simpl. cut(In (e::x) (pw l)). auto. apply IHl;eauto. } } } } Qed.\n                 \nEnd PowerSet.\n\n\nHint Resolve pw_is_ord app_is_ord nil_in_pw: core.\nHint Immediate pw_elim pw_elim1 pw_intro: core.\n\n\nLemma length_refl (A:Type): reflexive ( fun (l s:list A) => |l| <=b |s|).\nProof. unfold reflexive. intros. auto. Qed.\nLemma length_trans (A:Type): transitive ( fun (l s:list A) => |l| <=b |s|).\nProof.  unfold transitive. auto. Qed.\nLemma length_comparable (A:Type): comparable  ( fun (l s:list A) => |l| <=b |s|).\nProof.  unfold comparable. auto. Qed.\n\nHint Resolve length_refl length_trans length_comparable: core.\n\nSection PowerReflect.\n  \n  Context {A: ordType}.\n  Definition Max_sub_in (G I: list A)(P: list A-> Prop):=\n    I [<=] G /\\ IsOrd I /\\ P I /\\ (forall I', In I' (pw G) -> P I' -> |I'| <= |I|).\n  Definition max_sub_in (G I: list A)(B: list A-> bool):=\n    subset I G && isOrd I && B I && forallb ( fun I'=> (negb (B I') || |I'| <=? |I|)) (pw G).\n\n  Lemma Max_sub_in_elim1 (G I: list A)(B: list A -> bool):\n    Max_sub_in G I B -> I [<=] G.\n  Proof.  unfold Max_sub_in; tauto. Qed.\n  \n  Lemma Max_sub_in_elim2 (G I: list A)(B: list A -> bool):\n    Max_sub_in G I B -> IsOrd I.\n  Proof. unfold Max_sub_in; tauto. Qed.\n  Lemma Max_sub_in_elim3 (G I: list A)(B: list A -> bool):\n    Max_sub_in G I B -> B I.\n   Proof. unfold Max_sub_in; tauto. Qed.\n\n  Lemma max_has_biggest_size (G: list A)(B: list A-> bool)(X: list A)(M: list A):\n    IsOrd G -> Max_sub_in G M B -> X[<=]G -> IsOrd X -> B X -> |X| <= |M|.\n  Proof. unfold Max_sub_in. intros H H1 H2 H3 H4. apply H1;eauto.  Qed.\n  Lemma max_sub_same_size (G: list A)(B: list A-> bool)(X: list A)(Y: list A):\n    IsOrd G -> Max_sub_in G X B -> Max_sub_in G Y B -> |X|=|Y|.\n  Proof.  { intros H H1 H2. cut (|X| <= |Y|). cut (|Y| <= |X|). omega.\n          all: eapply max_has_biggest_size with (G:=G)(B:=B);\n          unfold Max_sub_in in H1; unfold Max_sub_in in H2; (auto || apply H2 || apply H1). } Qed.\n          \n  \n  Lemma max_sub_inbP (G I: list A)(B: list A-> bool):\n    reflect (Max_sub_in G I B)(max_sub_in G I B).\n  Proof. { apply reflect_intro. split.\n         { unfold Max_sub_in. unfold max_sub_in.\n           intro H. split_. split_. split_. apply /subsetP; apply H.\n           apply /isOrdP;apply H. apply H.\n           apply /forallbP. intros I' H2.\n           destruct H as [H0 H]. destruct H as [H1 H]. destruct H as [H' H].\n           apply /impP. intro H3.  apply /leP. auto. }\n         {  unfold Max_sub_in. unfold max_sub_in.\n            intro H. move /andP in H; destruct H as [H H2].\n            move /andP in H; destruct H as [H H1].\n            move /andP in H; destruct H as [H H'].\n            split. auto. split. apply /isOrdP;auto. split;auto.\n            move /forallbP in H2.\n            intros I' H3 H4. apply /leP. specialize (H2 I').\n            apply H2 in H3 as H5. move /impP in H5. auto. } } Qed.\n  \n  Lemma max_sub_inP (G I: list A)(P: list A-> Prop)(B: list A-> bool):\n    (forall x, reflect (P x)(B x))-> reflect (Max_sub_in G I P)(max_sub_in G I B).\n  Proof. { intro HP. eapply iffP with (P:= Max_sub_in G I B). \n         { apply max_sub_inbP. }\n         { unfold Max_sub_in. intro H. split. apply H. split.\n           apply H. split.  apply /HP;apply H.\n           destruct H as [H0 H]. destruct H as [H' H].\n           destruct H as [H1 H]. intros I' H2 H3.\n           apply H. auto. apply /HP;auto. }\n         { unfold Max_sub_in. intro H. split. apply H.\n           split. apply H.  split. apply /HP;apply H.\n           destruct H as [H0 H]. destruct H as [H' H].\n           destruct H as [H1 H]. intros I' H2 H3.\n           apply H. auto. apply /HP;auto. } } Qed.\n\n   Definition Min_sub_in (G I: list A)(P: list A-> Prop):=\n    I [<=] G /\\ IsOrd I /\\ P I /\\ (forall I', In I' (pw G) -> P I' -> |I| <= |I'|).\n   Definition min_sub_in (G I: list A)(B: list A-> bool):=\n     subset I G && isOrd I && B I && forallb ( fun I'=> (negb (B I') || |I| <=? |I'|)) (pw G).\n\n  Lemma Min_sub_in_elim1 (G I: list A)(B: list A -> bool):\n    Min_sub_in G I B -> I [<=] G.\n  Proof. unfold Min_sub_in;tauto. Qed.\n  \n  Lemma Min_sub_in_elim2 (G I: list A)(B: list A -> bool):\n    Min_sub_in G I B -> IsOrd I.\n  Proof.  unfold Min_sub_in;tauto. Qed.\n  Lemma Min_sub_in_elim3 (G I: list A)(B: list A -> bool):\n    Min_sub_in G I B -> B I.\n  Proof.  unfold Min_sub_in;tauto. Qed.\n\n   Lemma min_has_smallest_size (G: list A)(B: list A-> bool)(X: list A)(M: list A):\n    IsOrd G -> Min_sub_in G M B -> X[<=]G -> IsOrd X -> B X -> |M| <= |X|.\n  Proof. unfold Min_sub_in. intros H H1 H2 H3 H4. apply H1;eauto.  Qed.\n    \n  Lemma min_sub_same_size (G: list A)(B: list A-> bool)(X: list A)(Y: list A):\n    IsOrd G -> Min_sub_in G X B -> Min_sub_in G Y B -> |X|=|Y|.\n  Proof.  { intros H H1 H2. cut (|X| <= |Y|). cut (|Y| <= |X|). omega.\n          all: eapply min_has_smallest_size with (G:=G)(B:=B);\n          unfold Min_sub_in in H1; unfold Min_sub_in in H2; (auto || apply H2 || apply H1). } Qed.\n\n  Lemma min_sub_inbP (G I: list A)(B: list A-> bool):\n    reflect (Min_sub_in G I B)(min_sub_in G I B).\n  Proof. { apply reflect_intro. split.\n         { unfold Min_sub_in. unfold min_sub_in.\n           intro H. split_. split_. split_. apply /subsetP; apply H.\n           apply /isOrdP;apply H. apply H.\n           apply /forallbP. intros I' H2.\n           destruct H as [H0 H]. destruct H as [H1 H]. destruct H as [H' H].\n           apply /impP. intro H3.  apply /leP. auto. }\n         {  unfold Min_sub_in. unfold min_sub_in.\n            intro H. move /andP in H; destruct H as [H H2].\n            move /andP in H; destruct H as [H H1].\n            move /andP in H; destruct H as [H H'].\n            split. auto. split. apply /isOrdP;auto. split;auto.\n            move /forallbP in H2.\n            intros I' H3 H4. apply /leP. specialize (H2 I').\n            apply H2 in H3 as H5. move /impP in H5. auto. } } Qed.\n  Lemma min_sub_inP (G I: list A)(P: list A-> Prop)(B: list A-> bool):\n    (forall x, reflect (P x)(B x))-> reflect (Min_sub_in G I P)(min_sub_in G I B).\n  Proof. { intro HP. eapply iffP with (P:= Min_sub_in G I B). \n         { apply min_sub_inbP. }\n         { unfold Min_sub_in. intro H. split. apply H. split.\n           apply H. split. apply /HP;apply H.\n           destruct H as [H0 H]. destruct H as [H' H].\n           destruct H as [H1 H].  intros I' H2 H3.\n           apply H. auto. apply /HP;auto. }\n         { unfold Min_sub_in. intro H. split. apply H.\n           split. apply H. split.  apply /HP;apply H.\n           destruct H as [H0 H]. destruct H as [H' H].\n           destruct H as [H1 H]. intros I' H2 H3.\n           apply H. auto. apply /HP;auto. } } Qed.\n\n  Lemma exists_largest_inb (G: list A)(B: list A-> bool):\n    (exists X, In X (pw G) /\\ B X) ->\n    (exists I, In I (pw G) /\\ B I /\\ forall Y, In Y (pw G)-> B Y -> |Y| <=b |I|).\n  Proof. { intros. eapply max_withP_exists. all: auto. } Qed.\n\n  Lemma exists_largest_in (G: list A)(B: list A-> bool):\n    (exists X, In X (pw G) /\\ B X) ->\n    (exists I, In I (pw G) /\\ B I /\\ forall Y, In Y (pw G)-> B Y -> |Y| <= |I|).\n  Proof. { intros. apply exists_largest_inb in H as H1.\n           destruct H1 as [I H1]. exists I.\n           split. apply H1. split. apply H1.\n           intros Y H2 H3. apply /lebP. apply H1;auto. } Qed.\n\n  Lemma exists_smallest_inb (G: list A)(B: list A-> bool):\n    (exists X, In X (pw G) /\\ B X) ->\n    (exists I, In I (pw G) /\\ B I /\\ forall Y, In Y (pw G)-> B Y -> |I| <=b |Y|).\n  Proof. { intros. eapply min_withP_exists. all:auto. } Qed.\n\n   Lemma exists_smallest_in (G: list A)(B: list A-> bool):\n    (exists X, In X (pw G) /\\ B X) ->\n    (exists I, In I (pw G) /\\ B I /\\ forall Y, In Y (pw G)-> B Y -> |I| <= |Y|).\n  Proof. { intros. apply exists_smallest_inb in H as H1.\n           destruct H1 as [I H1]. exists I.\n           split. apply H1. split. apply H1.\n           intros Y H2 H3. apply /lebP. apply H1;auto. } Qed.\n  \n  \n \n  \n  \n    \nEnd PowerReflect.\n\nHint Resolve Max_sub_in_elim1 Max_sub_in_elim2 Max_sub_in_elim3 max_has_biggest_size: core.\nHint Resolve max_sub_inbP max_sub_inP: core.\n\nHint Resolve Min_sub_in_elim1 Min_sub_in_elim2 Min_sub_in_elim3  min_has_smallest_size: core.\nHint Resolve min_sub_inbP min_sub_inP: core.\n\nHint Resolve max_sub_same_size min_sub_same_size: core.\n\n(* Eval compute in (pw (1::2::3::nil)). *)\n\nSection MoreOnPower.\n\n  Context {A: ordType}.\n\n  Definition max_subs_of (G: list A)(B: list A -> bool):= filter (fun I => max_sub_in G I B) (pw G).\n\n  Lemma max_subs_of_IsOrd (G: list A)(B: list A -> bool): IsOrd G -> IsOrd (max_subs_of G B).\n  Proof. unfold max_subs_of. intro h1. cut (IsOrd (pw G)); auto. Qed.\n\n\n  Lemma max_subs_of_intro (G I: list A)(B: list A -> bool):\n    IsOrd G ->  Max_sub_in G I B-> In I (max_subs_of G B).\n    Proof. { unfold max_subs_of.  set (f:= (fun I0 : list A => max_sub_in G I0 B)).\n             intros h0 h1. move /max_sub_inbP in h1.\n             replace (max_sub_in G I B) with (f I) in h1.\n             cut (In I (pw G)). auto. unfold f in h1.\n             move /max_sub_inbP in h1. cut ( I [<=] G).\n             cut (IsOrd I). all: ( apply h1 || auto ). } Qed.\n\n  Lemma max_subs_of_intro1 (G I: list A)(B: list A -> bool):\n    IsOrd G -> max_sub_in G I B -> In I (max_subs_of G B).\n  Proof. { unfold max_subs_of.  set (f:= (fun I0 : list A => max_sub_in G I0 B)).\n           replace (max_sub_in G I B) with (f I). intros h0 h1.\n           cut (In I (pw G)). auto. unfold f in h1. move /max_sub_inbP in h1.\n           cut ( I [<=] G). cut (IsOrd I). all: ( apply h1 || auto ). } Qed.\n\n  Lemma max_subs_of_elim (G I: list A)(B: list A -> bool):\n    IsOrd G ->  In I (max_subs_of G B) -> Max_sub_in G I B.\n  Proof. { unfold max_subs_of. \n           set (f:= (fun I0 : list A => max_sub_in G I0 B)).\n           intros h1 h2.\n           assert (h3: f I). eauto. apply /max_sub_inbP. apply h3. } Qed.\n\n  Lemma max_subs_of_elim1 (G I: list A)(B: list A -> bool):\n    IsOrd G ->  In I (max_subs_of G B) -> max_sub_in G I B.\n  Proof. { unfold max_subs_of.\n           set (f:= (fun I0 : list A => max_sub_in G I0 B)).\n           intros h1 h2.\n           assert (h3: f I). eauto.  apply h3. } Qed.\n\n  Hint Immediate max_subs_of_intro max_subs_of_elim: core.\n\nEnd MoreOnPower.\n\nHint Immediate max_subs_of_intro max_subs_of_elim: core.\n\n\n\n\n", "meta": {"author": "Abhishek-TIFR", "repo": "wpgt", "sha": "48c612063cbfbe51d6eed41d244c044e43bf8d67", "save_path": "github-repos/coq/Abhishek-TIFR-wpgt", "path": "github-repos/coq/Abhishek-TIFR-wpgt/wpgt-48c612063cbfbe51d6eed41d244c044e43bf8d67/Powerset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7438476021598481}}
{"text": "Require Import rt.util.all.\nRequire Import rt.model.arrival.basic.task rt.model.arrival.basic.job rt.model.priority\n               rt.model.arrival.basic.task_arrival rt.model.arrival.basic.arrival_bounds.\nRequire Import rt.model.schedule.uni.schedule rt.model.schedule.uni.workload.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop div.\n\nModule WorkloadBoundFP.\n\n  Import Job SporadicTaskset UniprocessorSchedule Priority Workload\n         TaskArrival ArrivalBounds.\n\n  (* In this section, we define a bound for the workload of a single task\n     under uniprocessor FP scheduling. *)\n  Section SingleTask.\n\n    Context {Task: eqType}.\n    Variable task_cost: Task -> time.\n    Variable task_period: Task -> time.\n\n    (* Consider any task tsk that is to be scheduled in an interval of length delta. *)\n    Variable tsk: Task.\n    Variable delta: time.\n    \n    (* Based on the maximum number of jobs of tsk that can execute in the interval, ... *)\n    Definition max_jobs := div_ceil delta (task_period tsk).\n\n    (* ... we define the following workload bound for the task. *)\n    Definition task_workload_bound_FP := max_jobs * task_cost tsk. \n\n  End SingleTask.\n\n  (* In this section, we define a bound for the workload of multiple tasks. *)\n  Section AllTasks.\n    \n    Context {Task: eqType}.\n    Variable task_cost: Task -> time.\n    Variable task_period: Task -> time.\n\n    (* Assume any FP policy. *)\n    Variable higher_eq_priority: FP_policy Task.\n    \n    (* Consider a task set ts... *)\n    Variable ts: list Task.\n    \n    (* ...and let tsk be the task to be analyzed. *)\n    Variable tsk: Task.\n    \n    (* Let delta be the length of the interval of interest. *)\n    Variable delta: time.\n\n    (* Recall the definition of higher-or-equal-priority task and\n       the per-task workload bound for FP scheduling. *)\n    Let is_hep_task tsk_other := higher_eq_priority tsk_other tsk.\n    Let W tsk_other :=\n      task_workload_bound_FP task_cost task_period tsk_other delta.\n\n    (* Using the sum of individual workload bounds, we define the following bound\n       for the total workload of tasks of higher-or-equal priority (with respect\n       to tsk) in any interval of length delta. *)\n    Definition total_workload_bound_fp :=\n      \\sum_(tsk_other <- ts | is_hep_task tsk_other) W tsk_other.\n      \n  End AllTasks.\n\n  (* In this section, we prove some basic lemmas about the workload bound. *)\n  Section BasicLemmas.\n\n    Context {Task: eqType}.\n    Variable task_cost: Task -> time.\n    Variable task_period: Task -> time.\n    Variable task_deadline: Task -> time.\n\n    (* Assume any FP policy. *)\n    Variable higher_eq_priority: FP_policy Task.\n      \n    (* Consider a task set ts... *)\n    Variable ts: list Task.\n    \n    (* ...and let tsk be any task in ts. *)\n    Variable tsk: Task.\n    Hypothesis H_tsk_in_ts: tsk \\in ts.\n\n    (* Recall the workload bound for uniprocessor FP scheduling. *)\n    Let workload_bound :=\n      total_workload_bound_fp task_cost task_period higher_eq_priority ts tsk.\n\n    (* In this section we prove that the workload bound in a time window of\n       length (task_cost tsk) is as large as (task_cost tsk) time units.\n       (This is an important initial condition for the response-time analysis.) *)\n    Section NoSmallerThanCost.\n\n      (* Assume that the priority order is reflexive. *)\n      Hypothesis H_priority_is_reflexive: FP_is_reflexive higher_eq_priority.\n\n      (* Assume that cost and period of the task are positive. *)\n      Hypothesis H_cost_positive: task_cost tsk > 0.\n      Hypothesis H_period_positive: task_period tsk > 0.\n\n      (* We prove that the workload bound of an interval of size (task_cost tsk)\n         cannot be smaller than (task_cost tsk). *)\n      Lemma total_workload_bound_fp_ge_cost:\n        workload_bound (task_cost tsk) >= task_cost tsk.\n      Proof.\n        rename H_priority_is_reflexive into REFL.\n        unfold workload_bound, total_workload_bound_fp.\n        rewrite big_mkcond (big_rem tsk) /=; last by done.\n        rewrite REFL /task_workload_bound_FP.\n        apply leq_trans with (n := max_jobs task_period tsk (task_cost tsk) * task_cost tsk);\n          last by apply leq_addr.\n        rewrite -{1}[task_cost tsk]mul1n leq_mul2r; apply/orP; right.\n        by apply ceil_neq0.\n      Qed.\n\n    End NoSmallerThanCost.\n\n    (* In this section, we prove that the workload bound is monotonically non-decreasing. *)\n    Section NonDecreasing.\n\n      (* Assume that the period of every task in the task set is positive. *)\n      Hypothesis H_period_positive:\n        forall tsk,\n          tsk \\in ts ->\n          task_period tsk > 0.\n\n      (* Then, the workload bound is a monotonically non-decreasing function.\n         (This property is important for the fixed-point iteration.) *)\n      Lemma total_workload_bound_fp_non_decreasing:\n        forall delta1 delta2,\n          delta1 <= delta2 ->\n          workload_bound delta1 <= workload_bound delta2.\n      Proof.\n        unfold workload_bound, total_workload_bound_fp; intros d1 d2 LE.\n        apply leq_sum_seq; intros tsk' IN HP.\n        rewrite leq_mul2r; apply/orP; right.\n        apply leq_divceil2r; last by done.\n        by apply H_period_positive.\n      Qed.\n      \n    End NonDecreasing.\n\n  End BasicLemmas.\n  \n  (* In this section, we prove that any fixed point R = workload_bound R\n     is indeed a workload bound for an interval of length R. *)\n  Section ProofWorkloadBound.\n\n    Context {Task: eqType}.\n    Variable task_cost: Task -> time.\n    Variable task_period: Task -> time.\n    Variable task_deadline: Task -> time.\n    \n    Context {Job: eqType}.\n    Variable job_arrival: Job -> time.\n    Variable job_cost: Job -> time.\n    Variable job_deadline: Job -> time.\n    Variable job_task: Job -> Task.\n\n    (* Let ts be any task set with valid task parameters. *)\n    Variable ts: seq Task.\n    Hypothesis H_valid_task_parameters:\n      valid_sporadic_taskset task_cost task_period task_deadline ts.\n    \n    (* Consider any job arrival sequence with consistent, non-duplicate arrivals. *)\n    Variable arr_seq: arrival_sequence Job.\n    Hypothesis H_arrival_times_are_consistent: arrival_times_are_consistent job_arrival arr_seq.\n    Hypothesis H_arr_seq_is_a_set: arrival_sequence_is_a_set arr_seq.\n\n    (* Assume that all jobs come from the task set ...*)\n    Hypothesis H_all_jobs_from_taskset:\n      forall j, arrives_in arr_seq j -> job_task j \\in ts.\n\n    (* ...and have valid parameters. *)\n    Hypothesis H_valid_job_parameters:\n      forall j,\n        arrives_in arr_seq j ->\n        valid_sporadic_job task_cost task_deadline job_cost job_deadline job_task j.\n\n    (* Assume that jobs arrived sporadically. *)\n    Hypothesis H_sporadic_arrivals:\n      sporadic_task_model task_period job_arrival job_task arr_seq.\n\n    (* Let tsk be any task in ts. *)\n    Variable tsk: Task.\n    Hypothesis H_tsk_in_ts: tsk \\in ts.\n\n    (* Assume any fixed-priority policy. *)\n    Variable higher_eq_priority: FP_policy Task.\n    \n    (* First, let's define some local names for clarity. *)\n    Let arrivals_between := jobs_arrived_between arr_seq.\n    Let hp_workload t1 t2:=\n      workload_of_higher_or_equal_priority_tasks job_cost job_task (arrivals_between t1 t2)\n                                                 higher_eq_priority tsk.\n    Let workload_bound :=\n      total_workload_bound_fp task_cost task_period higher_eq_priority ts tsk.\n\n    (* Consider any R that is a fixed point of the following equation,\n       i.e., the claimed workload bound is equal to the interval length. *)\n    Variable R: time.\n    Hypothesis H_fixed_point: R = workload_bound R.\n\n    (* Then, we prove that R is indeed a workload bound. *)\n    Lemma fp_workload_bound_holds:\n      forall t,\n        hp_workload t (t + R) <= R.\n    Proof.\n      have BOUND := sporadic_task_arrival_bound task_period job_arrival job_task arr_seq.\n      feed_n 3 BOUND; try (by done).\n      rename H_fixed_point into FIX, H_all_jobs_from_taskset into FROMTS,\n             H_valid_job_parameters into JOBPARAMS,\n             H_valid_task_parameters into PARAMS.\n      unfold hp_workload, workload_of_higher_or_equal_priority_tasks,\n             valid_sporadic_job, valid_realtime_job,\n             valid_sporadic_taskset, is_valid_sporadic_task in *.\n      intro t.\n      rewrite {2}FIX /workload_bound /total_workload_bound_fp.\n      set l := jobs_arrived_between arr_seq t (t + R).\n      set hep := higher_eq_priority.\n      apply leq_trans with (n := \\sum_(tsk' <- ts | hep tsk' tsk)\n                                  (\\sum_(j0 <- l | job_task j0 == tsk') job_cost j0)).\n      {\n        have EXCHANGE := exchange_big_dep (fun x => hep (job_task x) tsk).\n        rewrite EXCHANGE /=; last by move => tsk0 j0 HEP /eqP JOB0; rewrite JOB0.\n        rewrite /workload_of_jobs -/l big_seq_cond [X in _ <= X]big_seq_cond.\n        apply leq_sum; move => j0 /andP [IN0 HP0].\n        rewrite big_mkcond (big_rem (job_task j0)) /=;\n          first by rewrite HP0 andTb eq_refl; apply leq_addr.\n        by apply in_arrivals_implies_arrived in IN0; apply FROMTS.\n      }\n      apply leq_sum_seq; intros tsk0 INtsk0 HP0.\n      apply leq_trans with (n := num_arrivals_of_task job_task arr_seq\n                                                      tsk0 t (t + R) * task_cost tsk0).\n      {\n        rewrite /num_arrivals_of_task -sum1_size big_distrl /= big_filter.\n        apply leq_sum_seq; move => j0 IN0 /eqP EQ.\n        rewrite -EQ mul1n.\n        feed (JOBPARAMS j0); first by eapply in_arrivals_implies_arrived; eauto 1.\n        by move: JOBPARAMS => [_ [LE _]].\n      }\n      rewrite /task_workload_bound_FP leq_mul2r; apply/orP; right.\n      feed (BOUND t (t + R) tsk0); first by feed (PARAMS tsk0); last by des.\n      by rewrite addKn in BOUND.\n    Qed.\n\n  End ProofWorkloadBound.\n  \nEnd WorkloadBoundFP.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/analysis/uni/basic/workload_bound_fp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.743847592560953}}
{"text": "(* exercise 8.5 *)\n(****************)\n\nRequire Export List.\nRequire Export Arith.\n(* In our exercises we consider strings with only opening and closing\n  parentheses. *)\n \nInductive par : Set :=\n  | open : par\n  | close : par.\n(* This is the definition of well-parenthesized expressions that is\n  probably the easiest to agree on. solution to \\ref{exo-wp-1} *)\n \nInductive wp : list par -> Prop :=\n  | wp_nil : wp nil\n  | wp_concat : forall l1 l2:list par, wp l1 -> wp l2 -> wp (l1 ++ l2)\n  | wp_encapsulate :\n      forall l:list par, wp l -> wp (open :: l ++ close :: nil).\n \nTheorem wp_oc : wp (open :: close :: nil).\nProof.\n change (wp (open :: nil ++ close :: nil)) in |- *.\n apply wp_encapsulate.\n apply wp_nil.\nQed.\n \nTheorem wp_o_head_c :\n forall l1 l2:list par, wp l1 -> wp l2 -> wp (open :: l1 ++ close :: l2).\nProof.\n intros l1 l2 H1 H2.\n replace (open :: l1 ++ close :: l2) with ((open :: l1 ++ close :: nil) ++ l2).\n -  apply wp_concat.\n    apply wp_encapsulate; trivial.\n    trivial.\n -  repeat (simpl in |- *; rewrite app_ass); simpl in |- *.\n    trivial.\nQed.\n \nTheorem wp_o_tail_c :\n forall l1 l2:list par,\n   wp l1 -> wp l2 -> wp (l1 ++ open :: l2 ++ close :: nil).\nProof. \n intros l1 l2 H1 H2;  apply wp_concat.\n -  trivial.\n - now  apply wp_encapsulate.\nQed.\n\n(* exercice 8.6 *)\n(****************)\n\n(* The structure of well-parenthesized expressions can actually be\n  represented by binary trees.*)\n \nInductive bin : Set :=\n  | L : bin\n  | N : bin -> bin -> bin.\n \nFixpoint bin_to_string (t:bin) : list par :=\n  match t with\n  | L => nil (A:=par)\n  | N u v => open :: bin_to_string u ++ close :: bin_to_string v\n  end.\n\n(**  Tests\n\nCompute bin_to_string (N (N L L) L).\n\nCompute bin_to_string (N (N L L) (N L L)).\n\n*)\n\nTheorem bin_to_string_wp : forall t:bin, wp (bin_to_string t).\nProof.\n simple induction t.\n -  simpl ; apply wp_nil.\n -  simpl ; intros t1 H1 t2 H2; apply wp_o_head_c; trivial.\nQed.\n\n#[export] Hint Resolve wp_nil wp_concat wp_encapsulate wp_o_head_c wp_o_tail_c wp_oc : core.\n\nFixpoint bin_to_string' (t:bin) : list par :=\n  match t with\n  | L => nil (A:=par)\n  | N u v =>\n      bin_to_string' u ++ open :: bin_to_string' v ++ close :: nil\n  end.\n\n(* This is the correction for exercise 8.7 *)\n \nTheorem bin_to_string'_wp : forall t:bin, wp (bin_to_string' t).\nProof.\n simple induction t; simpl ; auto.\nQed.\n \n(*  This is the correction for exercise 8.24 *)\n\nInductive parse_rel : list par -> list par -> bin -> Prop :=\n  | parse_node :\n      forall (l1 l2 l3:list par) (t1 t2:bin),\n        parse_rel l1 (close :: l2) t1 ->\n        parse_rel l2 l3 t2 -> parse_rel (open :: l1) l3 (N t1 t2)\n  | parse_leaf_nil : parse_rel nil nil L\n  | parse_leaf_close :\n      forall l:list par, parse_rel (close :: l) (close :: l) L.\n\n \nTheorem parse_rel_sound_aux :\n forall (l1 l2:list par) (t:bin),\n   parse_rel l1 l2 t -> l1 = bin_to_string t ++ l2.\nProof.\n intros l1 l2 t H; elim H; clear H l1 l2 t.\n -  intros l1 l2 l3 t1 t2 Hp Hr1 Hp2 Hr2; simpl.\n     rewrite app_ass, Hr1; simpl.\n     now      rewrite Hr2.\n -  reflexivity.\n -  reflexivity.\nQed.\n \n\nTheorem parse_rel_sound :\n forall l:list par, (exists t : bin, parse_rel l nil t) -> wp l.\nProof.\n intros l [t H]; replace l with (bin_to_string t).\n -  apply bin_to_string_wp.\n -  symmetry;\n   replace (bin_to_string t) with (bin_to_string t ++ nil).\n   +  apply parse_rel_sound_aux; auto.\n   +  rewrite app_nil_end; auto.\nQed.\n\n(* correction to exercise 8.19 *)\n\n(* This is another possible definition of well-parenthesized expressions,\n  actually better adapted to showing that a given parser is correct. *)\n \nInductive wp' : list par -> Prop :=\n  | wp'_nil : wp' nil\n  | wp'_cons :\n      forall l1 l2:list par,\n        wp' l1 -> wp' l2 -> wp' (open :: l1 ++ close :: l2).\n\n(* To prove that the two definitions of well-parenthesized expressions are\n  equivalent, we need to prove that each predicate satisfies the constructors\n  of the other. *)\n \nTheorem wp'_concat :\n forall l1 l2:list par, wp' l1 -> wp' l2 -> wp' (l1 ++ l2).\nProof.\n intros l1 l2 H; generalize l2; clear l2.\n elim H.\n -  simpl; auto.\n -  intros l1' l2' Hb1' Hr1 Hb2' Hr2 l2 Hb2; simpl; rewrite app_ass.\n    simpl; apply wp'_cons; auto.\nQed.\n\n#[export] Hint Resolve wp'_nil wp'_cons wp'_concat : core.\n\n(* This is the other constructor of wp, also satisfied by wp'. *)\n \nTheorem wp'_encapsulate :\n forall l:list par, wp' l -> wp' (open :: l ++ close :: nil).\nProof.\n intros l H; elim H; auto.\nQed.\n\n(* One interpretation of inductive definitions of predicates is that\n  the defined predicate is the least (with respect to implication) to\n  satisfy the constructors.  Thus, having proved that one of the predicates\n  satisfies the constructors of the other gives a simple way to prove\n  that one predicate implies the other.  The proof is done by induction\n  on the predicate. solution to \\ref{exo-wp-2}*)\n \nTheorem wp_imp_wp' : forall l:list par, wp l -> wp' l.\nProof.\n intros l H; elim H.\n -  apply wp'_nil.\n -  intros; apply wp'_concat; trivial.\n -  intros; apply wp'_encapsulate; trivial.\nQed.\n \nTheorem wp'_imp_wp : forall l:list par, wp' l -> wp l.\nProof.\n intros l H; elim H; auto.\nQed.\n\n(* correction of exercise 8.20 *)\n\n(* Here is an alternative definition, the same as before, but with the\n  second constructor that privileges parentheses on the right. *)\n \nInductive wp'' : list par -> Prop :=\n  | wp''_nil : wp'' nil\n  | wp''_cons :\n      forall l1 l2:list par,\n        wp'' l1 -> wp'' l2 -> wp'' (l1 ++ open :: l2 ++ close :: nil).\n\n#[export] Hint Resolve wp''_nil wp''_cons : core.\n\n(* Obviously this one also satisfies the concatenation property. *)\n \nLemma wp''_concat :\n forall l1 l2:list par, wp'' l1 -> wp'' l2 -> wp'' (l1 ++ l2).\nProof.\n (* Only a proof by induction on the fact that the second list is \n    well-parenthesized   is needed. *)\n intros l1 l2 H1 H2; generalize l1 H1; clear H1 l1; elim H2.\n -  intros; rewrite <- app_nil_end; trivial.\n -  intros; rewrite ass_app; auto.\nQed.\n \n\nTheorem wp''_encapsulate :\n forall l:list par, wp'' l -> wp'' (open :: l ++ close :: nil).\nProof.\n intros l H; change (wp'' (nil ++ open :: l ++ close :: nil));\n auto.\nQed.\n#[export] Hint Resolve wp''_concat wp''_encapsulate : core.\n\n(* solution to exercise \\ref{exo-wp-4} *)\n \nTheorem wp_imp_wp'' : forall l:list par, wp l -> wp'' l.\nProof.\n simple induction 1; auto.\nQed.\n \n\nTheorem wp''_imp_wp : forall l:list par, wp'' l -> wp l.\nProof.\n simple induction 1; auto.\nQed.\n\nFixpoint recognize (n:nat) (l:list par) {struct l} : bool :=\n  match l with\n  | nil => match n with\n           | O => true\n           | _ => false\n           end\n  | open :: l' => recognize (S n) l'\n  | close :: l' => match n with\n                   | O => false\n                   | S n' => recognize n' l'\n                   end\n  end.\n\n(* solution to exercise 8.21 *)\n \nTheorem recognize_complete_aux :\n forall l:list par,\n   wp l ->\n   forall (n:nat) (l':list par), recognize n (l ++ l') = recognize n l'.\nProof.\n intros l H; elim H.\n -  simpl; auto.\n -  intros l1 l2 H1 Hrec1 H2 Hrec2 n l'.\n    rewrite app_ass; transitivity (recognize n (l2 ++ l')); auto.\n -  intros l1 H1 Hrec n l'; simpl ; rewrite app_ass; rewrite Hrec;\n    simpl ; auto.\nQed.\n \nTheorem recognize_complete : forall l:list par, wp l -> recognize 0 l = true.\nProof.\n intros l H; rewrite (app_nil_end l),  recognize_complete_aux; auto.\nQed.\n\n(* solution of exercise 8.22 *)\n\nTheorem app_decompose :\n forall (A:Type) (l1 l2 l3 l4:list A),\n   l1 ++ l2 = l3 ++ l4 ->\n   (exists l1' : list A, l1 = l3 ++ l1' /\\ l4 = l1' ++ l2) \\/\n   (exists a : A,\n      exists l2' : list A, l3 = l1 ++ a :: l2' /\\ l2 = (a :: l2') ++ l4).\nProof.\n simple induction l1.\n -  intros l2 l3; case l3.\n   +  intros l4 H; left; exists (nil (A:=A)); auto.\n   +  intros a l3' Heq; right; exists a; exists l3'; auto.\n -  clear l1; intros a l1 Hrec l2 l3; case l3.\n   +  intros l4 H; left; exists (a :: l1); auto.\n   +  simpl ; intros a' l3' l4 Heq; injection Heq; intros Heq' Heq''.\n       elim Hrec with (1 := Heq').\n       intros [l1' [Heq3 Heq4]]; left; exists l1'; split; auto.\n       rewrite Heq''; rewrite Heq3; auto.\n       intros [a'' [l2' [Heq3 Heq4]]]; right; exists a'', l2'; split; auto.\n       rewrite Heq''; rewrite Heq3; auto.\nQed.\n\n\n(* length of lists is actually an abstract view of lists.  There is\n  a morphism between appending and addition.  This is already visible\n  in the structure of the two functions app and plus and the proof of\n  this theorem follows in a simple way the structure of app (and plus by\n  the same occasion). *)\n \nTheorem length_app :\n forall {A:Type} (l1 l2:list A), length (l1 ++ l2) = length l1 + length l2.\nProof.\n simple induction l1; simpl in |- *; auto.\nQed.\n \nTheorem length_rev : forall {A:Type} (l:list A), length l = length (rev l).\nProof.\n simple induction l; auto.\n -  intros a l' H; simpl in |- *.\n    rewrite length_app.\n    simpl in |- *; rewrite <- plus_n_Sm; rewrite H; auto with arith.\nQed.\n\n \nTheorem cons_to_app_end :\n forall {A:Type} (l:list A) (a:A),\n    exists b : A, exists l' : list A, a :: l = l' ++ b :: nil.\nProof.\n intros A l a.\n rewrite <- (rev_involutive (a :: l)).\n (* We want to use the first element of (rev (a :: l)) but we\n  need to say that this list has at least one element. *)\n assert (H : 0 < length (rev (a :: l)))\n  by  (rewrite <- length_rev; simpl ; auto with arith).\n \n destruct (rev (a :: l)) as [ | a0 l0].\n -  (* If (rev (cons a l)) was nil, then there would be a contradiction. *)\n   simpl ; elim (lt_n_O 0); auto.\n -  exists a0,  (rev l0); simpl ; auto.\nQed.\n \n\nTheorem last_same :\n forall {A:Type} (a b:A) (l1 l2:list A),\n   l1 ++ a :: nil = l2 ++ b :: nil -> l1 = l2 /\\ a = b.\nProof.\n intros A a b l1 l2 H.\n assert (e: a :: rev l1 = b :: rev l2).\n -  repeat rewrite <- rev_unit; now rewrite H.\n -  injection e; intros H1 H2; split; auto.\n    rewrite <- (rev_involutive l1), H1; apply rev_involutive.\nQed.\n \nTheorem wp_remove_oc_aux :\n forall l:list par,\n   wp l ->\n   forall l1 l2:list par, l1 ++ l2 = l -> wp (l1 ++ open :: close :: l2).\nProof.\n intros l H; elim H.\n -\n (* In the first case l is the empty list, there is only one way to insert\n  an open-string pair.  We use the theorem app_eq_nil to determine\n  l1 and l2.  This theorem has implicit arguments. *)\n \n intros l1 l2 H1; elim (app_eq_nil _ _ H1); auto.\n simpl in |- *; intros Heq1 Heq2; rewrite Heq1; rewrite Heq2; apply wp_oc.\n\n -  (* In the second case l is already a concatenation of two well-parenthesized\n    expressions l1 and l2.  We need to now whether the open-close pair is\n   inserted in l1' or in l2', the theorem app_decompose helps here. *)\n   intros l1 l2 Hp1 Hr1 Hp2 Hr2 l3 l4 Heq.\n   elim app_decompose with (1 := Heq).\n   intros [l1' [Heq1 Heq2]]; rewrite Heq1, app_ass;\n   apply wp_concat; auto.\n   intros [a' [l2' [Heq1 Heq2]]].\n   rewrite Heq2.\n   repeat rewrite app_comm_cons.\n   rewrite ass_app.\n  apply wp_concat; auto.\n\n- (* In the third case, we have to check three possibilities: either\n   the open-close pair has been inserted before the existing open character,\n  or between the two parentheses, or after. *)\n idtac.\n intros l' Hp'' Hrec l1; case l1.\n simpl ; intros l2 Heq; rewrite Heq.\n change (wp (open :: nil ++ close :: open :: l' ++ close :: nil));\n auto.\n simpl; intros c l1' l2; case l2.\n(* If l2 is nil, then the open-close pair was introduced after the\n  closing parenthesis. *)\n +  intros Heq; injection Heq; intros Heq1 Heq2.\n    rewrite <- app_nil_end in Heq1; rewrite Heq1; rewrite Heq2.\n    rewrite app_comm_cons.\n    apply wp_concat; auto.\n + (* if l2 is non nil then the open-close pair was introduced between the\n   parentheses *)\n intros c' l2'; elim (cons_to_app_end  l2' c').\n intros c'' [l2'' Heq]; rewrite Heq.\n rewrite ass_app; intros Heq1.\n injection Heq1; intros Heq2 Heq3; elim last_same with (1 := Heq2).\n intros Heq4 Heq5; rewrite Heq5; rewrite Heq3.\n change (wp (open :: l1' ++ (open :: close :: l2'') ++ close :: nil)) .\n rewrite ass_app; auto.\nQed.\n \nTheorem wp_remove_oc :\n forall l1 l2:list par, wp (l1 ++ l2) -> wp (l1 ++ open :: close :: l2).\nProof.\n intros; apply wp_remove_oc_aux with (l := l1 ++ l2); auto.\nQed.\n \nFixpoint make_list (A:Type) (a:A) (n:nat) {struct n} : \n list A := match n with\n           | O => nil (A:=A)\n           | S n' => a :: make_list A a n'\n           end.\n \nTheorem make_list_end :\n forall (A:Type) (a:A) (n:nat) (l:list A),\n   make_list A a (S n) ++ l = make_list A a n ++ a :: l.\nProof.\n simple induction n; simpl.\n -  trivial.\n-  intros n' H l; rewrite H; trivial.\nQed.\n\n(* Now we want to express that only well-parenthesized expressions are accepted.  Again,\n  we prove a more general statement, where n is understood as the number of\n  unmatched opening parentheses recognized so far. *)\n \nTheorem recognize_sound_aux :\n forall (l:list par) (n:nat),\n   recognize n l = true -> wp (make_list _ open n ++ l).\nProof.\n simple induction l; simpl.\n-  intros n; case n.\n   simpl ; intros; apply wp_nil.\n   intros n' H; discriminate H.\n-  intros a; case a; simpl ; clear a.\n   + intros l' H n H0.\n     rewrite <- make_list_end; auto.\n   +  intros l' H n; case n; clear n.\n      intros H'; discriminate H'.\n      intros n H0; rewrite make_list_end; apply wp_remove_oc;auto.\nQed.\n\n(* The soundness statement is the general statement specialized to value 0.\n *)\n \nTheorem recognize_sound : forall l:list par, recognize 0 l = true -> wp l.\nProof.\n intros l H; generalize (recognize_sound_aux _ _ H); simpl; auto.\nQed.\n\n(* Now we want to write a real parser, that is, a function that constructs \n  a term representing the structure of the string.\n  The parsing function is a tail-recursive representation of a stack automaton.\n   The argument s is the stack, the argument t is the tree representing the\n  the last well-formed expression that was recognized.  The return value is\n  None if the string is rejected and (Some t) if the string is accepted.  In\n  this case one should be able to reconstruct the recognized string from t,\n  but this is done later as another exercise. *)\n \n\n(* exercise 8.23 *)\nFixpoint parse (s:list bin) (t:bin) (l:list par) {struct l} : \n option bin :=\n  match l with\n  | nil => match s with\n           | nil => Some t\n           | _ => None (A:=bin)\n           end\n  | open :: l' => parse (t :: s) L l'\n  | close :: l' =>\n      match s with\n      | t' :: s' => parse s' (N t' t) l'\n      | _ => None (A:=bin)\n      end\n  end.\n\n(* The length of the stack plays the same role as argument n in the\n  function recognize. *)\n \nTheorem parse_reject_indep_t :\n forall (l:list par) (s:list bin) (t:bin),\n   parse s t l = None ->\n   forall (s':list bin) (t':bin),\n     length s' = length s -> parse s' t' l = None.\nProof.\n simple induction l.\n-  intros s; case s.\n   +  simpl; intros t H; discriminate H.\n   + intros t0 s0 t H s'; case s'.\n     *  simpl; intros t' Hle; discriminate Hle.\n     *  simpl; auto.\n-  intros a; case a; simpl; clear a; intros l' Hrec s.\n   + intros t H s' t' Hle.\n     apply Hrec with (1 := H).\n     simpl; auto with arith.\n   +  case s.\n      *  intros t H s'; case s'; simpl; auto.\n         intros t0 s0 t' Hle; discriminate Hle.\n      *  intros t0 s0 t H s'; case s'; simpl.\n         intros t' H0; discriminate H0.\n         intros t'0 s'0 t' Hle; apply Hrec with (1 := H).\n         simpl in Hle; auto with arith.\nQed.\n\n(* Rejected strings are those for which the return value is None. \n  In the completeness theorem we actually talk about the rejected strings.\n  Here it is more convenient to use wp' as the definition of well-parenthesized\n  expressions to organize the proof.*)\n \nTheorem parse_complete_aux :\n forall l:list par,\n   wp' l ->\n   forall (s:list bin) (t:bin) (l':list par),\n     parse s t (l ++ l') = None ->\n     forall (s':list bin) (t':bin),\n       length s' = length s -> parse s' t' l' = None.\nProof.\n simple induction 1.\n -  simpl; intros; eapply parse_reject_indep_t; eauto.\n -  intros l1 l2 Hp1 Hr1 Hp2 Hr2 s t l' Hrej s' t' Hle.\n    apply Hr2 with (s := s') (t := N t L).\n    change (parse (t :: s') L (close :: l2 ++ l') = None) in |- *.\n    simpl in Hrej.\n    rewrite app_ass in Hrej.\n    apply Hr1 with (1 := Hrej).\n    simpl; auto with arith.\n   auto.\nQed.\n \n\nTheorem parse_complete : forall l:list par, wp l -> parse nil L l <> None.\nProof.\n intros l H; replace l with (l ++ nil).\n red in |- *; intros H'.\n assert (e : parse nil L nil = None).\n -   apply parse_complete_aux with (2 := H'); auto.\n     apply wp_imp_wp'; auto.\n - discriminate.\n - rewrite <- app_nil_end; auto.\nQed.\n\n(* We will use bin_to_string' to map binary trees to strings of characters.\n  Stacks also represent strings. *)\n \nFixpoint unparse_stack (s:list bin) : list par :=\n  match s with\n  | nil => nil (A:=par)\n  | t :: s' => unparse_stack s' ++ bin_to_string' t ++ open :: nil\n  end.\n \nTheorem parse_invert_aux :\n forall (l:list par) (s:list bin) (t t':bin),\n   parse s t l = Some t' ->\n   bin_to_string' t' = unparse_stack s ++ bin_to_string' t ++ l.\nProof.\n simple induction l.\n-  intros s; case s.\n + simpl.\n   intros t t' H; injection H; intros Heq.\n   rewrite Heq; apply app_nil_end.\n +  simpl ; intros t0 s0 t t' H; discriminate H.\n-  intros a; case a; simpl; clear a; intros l' Hrec s.\n  +  intros t t' H; rewrite Hrec with (1 := H).\n     simpl; repeat (rewrite app_ass; simpl); auto.\n  + case s.\n   *  intros t t' H; discriminate H.\n   *  intros t0 s0 t t' Hp; rewrite Hrec with (1 := Hp);\n      simpl; repeat (rewrite app_ass; simpl); auto.\nQed.\n \nTheorem parse_invert :\n forall (l:list par) (t:bin), parse nil L l = Some t -> bin_to_string' t = l.\nProof.\n intros; replace l with (unparse_stack nil ++ bin_to_string' L ++ l); auto.\n apply parse_invert_aux; auto.\nQed.\n\n(* With this last theorem, we know that our parser is correct, that is\n  sound and complete. *)\n \nTheorem parse_sound :\n forall (l:list par) (t:bin), parse nil L l = Some t -> wp l.\nProof.\n intros l t H; rewrite <- parse_invert with (1 := H).\n apply bin_to_string'_wp.\nQed.\n\n(* Now, an exercise for which we do not give the solution is the exercise\n          where strings can also contain other characters that play no role\n          with  respect to parentheses, but should not be forgotten by the\n parser.*)\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch8_inductive_predicates/SRC/parsing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7438448602009452}}
{"text": "(* Rappel syntaxe Coq : les commentaires s'écrivent entre (* et *). *)\n\n(* TAPFA - Partie Coq - TP 1 *)\n\n(* Rappel de l'URL des supports de Cours :\n\n   https://pfitaxel.github.io/tapfa-coq-alectryon/ *)\n\n(* Le sujet des 2 TP TAPFA se présentent sous la forme d'un fichier .v\n   à compléter. Vous pouvez coder vos réponses :\n   - dans Emacs+ProofGeneral (environnement de TP recommandé :\n\n     https://moodle.univ-tlse3.fr/course/view.php?id=183#env-tp ;\n     https://github.com/erikmd/tapfa-init.el )\n\n   - ou dans JsCoq (éditeur en ligne, pratique mais moins performant :\n     https://jscoq.github.io/scratchpad.html )\n *)\n\n(* N'hésitez pas à solliciter votre encadrant de TP sur Discord\n   pour toute question. *)\n\n(* Pour évaluer les phrases dans Emacs+ProofGeneral :\n   - aller jusqu'au curseur en faisant \"C-c RET\" (<=> Ctrl+C Entrée)\n     ou \"C-c C-RET\"\n   - avancer/reculer d'un cran avec \"C-c C-n\" et \"C-c C-u\"\n   - et pour aller à la fin de la zone validée, faire \"C-c C-.\"\n\n  Pour évaluer les phrases dans l'éditeur en ligne,\n  utiliser les trois boutons adéquats (ou Alt+N, Alt+P, Alt+Entrée) *)\n\n(*********************************************************)\n(* D'abord un petit peu de programmation (fonctionnelle) *)\n(*********************************************************)\n\n(* Définissons la fonction qui à n, associe n + 1. *)\n\n(* En OCaml, on aurait écrit :\n\n   let f = fun n -> n + 1;;\n *)\n\n(* En Coq, on écrit : *)\n\nDefinition f := fun n => n + 1.\n\n(* En maths, on écrirait :\n\n   f : N ⟶ N\n       n ↦ n+1\n\n   \"↦\" (\"\\mapsto\" en LaTeX) s'écrira \"fun … => …\" en Coq.\n\n   La partie \"N ⟶ N\" existe aussi en Coq et est appelée «type» de la fonction.\n\n   Ici Coq l'a automatiquement inféré, on peut l'afficher avec : *)\n\nCheck f.\n\nPrint f.\n\n(* On aurait aussi pu le donner explicitement *)\nDefinition f2 : nat -> nat := fun n => n + 1.\n\n(* Contrairement à OCaml, il est impossible de définir en Coq deux\n   fonctions (ou types) ayant le même nom dans le même fichier ;\n   ainsi, cela permet d'éviter des confusions. *)\nFail Definition f2 := fun n => n + 2.\n(* La commande \"Fail\" vérifie que la phrase qui suit donne une erreur,\n   ignore celle-ci et permet de continuer tout de même.\n   Cette commande a donc essentiellement un but de «documentation». *)\n\n(* De manière générale, \"t : T\" se lit «t est de type T».\n   On peut mettre de telles «annotations de type» un peu partout et\n   t n'est pas nécessairement une fonction. *)\nDefinition f3 := fun (n : nat) => n + 1.\n\n(* Autre syntaxe : pour éviter d'avoir à écrire fun, on peut également\n   écrire le nom de l'argument après celui de la fonction, avant \":=\"\n   (et c'est dorénavant ce que l'on fera). *)\nDefinition f4 n := n + 1.\n\n(* La syntaxe change mais c'est exactement la même fonction, comme la\n   montre la commande Print. *)\nPrint f4.\nPrint f.  (* même résultat *)\n\n(* Comme avec tout langage de programmation, on peut évaluer les fonctions *)\nEval compute in f 2.\n(* Tout comme en OCaml, on pourrait écrire \"f(2)\", mais les parenthèses\n   ne servent à rien s'il n'y a pas de sous-expression à regrouper ;\n   on utilise donc généralement simplement un espace : \"f 2\" *)\n\n(* On peut aussi demander le type de f 2 *)\nCheck f 2.\n(* Bien sûr, il faut que le terme soit bien typé. Ceci échoue : *)\nFail Check f f.\n(* Commentez la ligne précédente (ou ajoutez la commande \"Fail\" devant)\npour pouvoir continuer *)\n\n(****************************************************)\n(* Petit rappel sur les fonctions d'ordre supérieur *)\n(****************************************************)\n\n(* Comme en OCaml, on peut définir des fonctions curryfiées\n(c.-à-d. prenant deux arguments ou plus) : *)\nDefinition g x y := x + 2 * y.\nPrint g.\n\n(* syntaxes équivalentes *)\nDefinition g2 := fun x y => x + 2 * y.\nDefinition g3 := fun x => (fun y => x + 2 * y).\n\n(* Regardons le type de g *)\nCheck g.\n(* on obtient «nat -> nat -> nat» qui se lit «nat -> (nat -> nat)»\n   c.-à-d. la fonction g est une fonction à un argument (x), qui\n   renvoie une fonction prenant un argument (y) et retournant x+2y. *)\nCheck g 1.\n\n(* pour l'évaluation, on peut donc écrire *)\nEval compute in (g 1) 3.\n(* ou plus simplement *)\nEval compute in g 1 3.\n\n(* On peut aussi définir des fonctionnelles, c.-à-d. des fonctions\nprenant des fonctions en argument : *)\nDefinition repeat_twice f (x : nat) := f (f x).\n\nDefinition rtwice := fun (f : nat -> nat) => fun (x : nat) => f (f x).\n\nCheck rtwice.\nCheck repeat_twice.\n(* repeat_twice *)\n(*      : (nat -> nat) -> nat -> nat *)\n\nPrint f.\nEval compute in repeat_twice f 2.\n\n(******************************************************************)\n(* Encore un peu de programmation, quelques structures de données *)\n(******************************************************************)\n\n(* un des types les plus simples : les booléens *)\nCheck true.\nCheck false.\n\n(* Les booléens sont définis dans la bibliothèque standard de Coq\ncomme un type utilisateur à 2 constructeurs :\n\nun booléen est soit true, soit false (et rien d'autre) *)\nPrint bool.\n\n(* true et false sont ainsi des constructeurs. Notez au passage qu'il\nn'y a pas de contrainte sur la «casse» des constructeurs dans Coq :\npas besoin qu'ils commencent par une majuscule. *)\n\n(* on peut examiner la valeur d'un booléen avec un match *)\n\nDefinition et a b :=\n  match a with\n  | true => b\n  | false => false\n  end.\n\n(* L'écriture \"if b then ct else cf\" est juste du sucre syntaxique\npour le match ci-dessus et c'est l'écriture simplifiée par défaut : *)\n\nPrint et.\n\n(* Mais on peut passer en mode \"affichage bas-niveau\" pour désactiver\ncette écriture simplifiée : *)\n\nSet Printing All.\n\nPrint et.\n\nUnset Printing All.\n\nEval compute in et true false.\n\nEval compute in et true true.\n\n(* Similairement à OCaml, on est obligé de définir tous les cas, mais\n   le «filtrage non-exhaustif» est une erreur, pas un warning\n   (commenter pour pouvoir continuer) *)\nFail Definition et_non_exhaustif a b :=\n  match a with\n  | true => b\n  end.\n\n(* La bibliothèque standard de Coq fournit des notations \"&&\", \"||\"\nassociée aux définitions \"andb\" (identique à notre définition \"et\"\ndonc dans la suite on utilisera donc \"andb\" plutôt que \"et\"), \"orb\",\net \"negb\" : *)\n\nCheck andb false true.\nCheck (false && true)%bool.\n\nCheck orb false true.\nCheck (false || true)%bool.\n\nCheck negb false.\n\n\nEval compute in negb false.\n\n(* Une invocation possible pour avoir des notations plus légères : *)\nOpen Scope bool_scope.\n\nCheck andb false true.\nCheck orb false true.\n\n(* un type un peu plus complexe : les entiers naturels.\n\nIls sont définis dans la bibliothèque standard de Coq comme un type\nutilisateur à 2 constructeurs :\n\nun entier est soit O, soit le successeur d'un entier. *)\nPrint nat.\n\n(* Notez que la syntaxe affichée par Coq est équivalente à la syntaxe\nsuivante, vue en cours :\n\nInductive nat :=\n  | O\n  | S (_ : nat). *)\n\n(* Au moment où ce type nat est défini dans la bibliothèque standard,\n   Coq génère automatiquement le principe d'induction \"nat_ind\", qui\n   coïncide naturellement avec le schéma de \"preuve par récurrence\",\n   que l'on (re)verra lors du TP2. *)\nCheck nat_ind.\n\n(* À noter, la représentation des entiers sous cette forme correspond\n   à une \"représentation en base 1\", c'est-à-dire que le nombre entier\n   16, même si Coq le \"lit\" et \"l'écrit\" en base 10 avec les options\n   d'affichage par défaut, en interne, il est stocké sous la forme\n   d'une expression inductive impliquant 17 constructeurs ! *)\n\nSet Printing All.\nCheck 16.\nUnset Printing All.\nCheck 17.\n\n(* Bien entendu, d'autres représentations plus compactes des entiers\n   naturels (en binaire…) et des entiers relatifs, sont disponibles\n   dans la bibliothèque standard de Coq, mais nous n'approfondirons\n   pas cet aspect durant ce TP TAPFA. *)\n\n(* Nous avons rappelé précédemment (fonction \"et\") la syntaxe de Coq\n   pour effectuer un filtrage (syntaxe très proche de celle d'OCaml !)\n\n   Quant à l'équivalent du \"let rec\" en Coq, il s'agit d'utiliser\n   la commande \"Fixpoint\".\n   En revanche, nous n'utiliserons pas l'équivalent Coq de la syntaxe\n   \"let rec … in\", puisqu'en pratique cela rendrait plus compliqué les\n   preuves de propriétés de la fonction définie localement... *)\n\n(* Définir la fonction \"factorielle\" de type \"nat -> nat\".\n   Puis calculer \"factorielle 3\".\n\n   Rappel sur la récursion : il faut que vous veilliez à ce que vos\n   définitions de fonctions récursives aient des appels récursifs dont\n   l'argument principal soit décroissant structurellement (pour\n   garantir la terminaison. Sinon, Coq refusera votre définition ! *)\n\n\nFixpoint factorielle (n : nat) :=\n  match n with\n  | 0 => 1\n  | S p => factorielle p * n\n  end.\n\nEval compute in factorielle 8.\n\n(* Définir le prédicat booléen \"pair\" de type \"nat -> bool\".\n   Puis calculer \"pair 6\". *)\n\nFixpoint pair n :=\n  match n with\n  | 0 => true\n  | S 0 => false\n  | S (S p) => pair p\n  end.\n\nEval compute in pair 6.\n\n\n(* Pour conclure sur cette revue du filtrage et de la récursion en Coq\n   voici un exemple de définition d'un prédicat booléen \"inf\",\n   testant si un entier n est plus petit ou égal à un autre entier m.\n   Pouvez-vous expliquer avec vos propres mots chacune des branches du\n   match ? (qui correspond ici à un filtrage simultané !) *)\nFixpoint inf n m :=\n  match n,m with\n  | O, _ => true            (* si n=0, alors ∀m, n<=m *)\n  | S n1, O => false        (* si n>0 et m=0, alors n>m *)\n  | S n1, S m1 => inf n1 m1 (* si n>0 et m>0, alors vérifier avec les préds de n et m *)\n  end.\n\nRequire Extraction.\n\nRecursive Extraction inf.\n\nCheck inf.\nEval compute in inf 2 3.\nEval compute in inf 1 0.\n\n(* Remarque : ne pas confondre les opérations booléennes «calculables»\n&&, || et negb, avec les connecteurs logiques /\\, \\/ et ~, qui ne\nprennent pas en argument des booléens mais des Propositions : *)\n\nCheck 0 = 0.\n(* 0 = 0 *)\n(*      : Prop *)\n\nCheck (0 = 0) /\\ (0 = 0).\n\nCheck 0 < 1 \\/ 0 = 1 \\/ 0 > 1.\n\n(* \"/\\\" est ainsi une notation pour and,\n   \"\\/\" pour or,\n   \"~\" pour not *)\n\nCheck and (0 = 0) (0 = 0).\nCheck or (0 < 1) (or (0 = 1) (0 > 1)).\n\n(* Q1. Qu'est-ce qu'une proposition dans Coq ?\n   Q2. comment montrer qu'une proposition est vraie ?\n\nAvant de faire des exercices spécifiques pour prouver des propositions\nsimples de 3 façons différentes (à la main, de façon semi-automatique\nou complètement automatique), deux réponses rapides :\n\n\nR1. Une proposition est une formule logique, et dans Coq c'est à la\nfois un objet de type Prop, et un type de données dont les expressions\nde ce type sont les preuves de la formule en question.\n\nCela correspond à la notion de «correspondance de Curry-Howard» vue en\ncours.\n\nPar exemple, on aura  (preuve que 0=0) : 0 = 0 : Prop\n\nAinsi, Prop est un \"type de type\", au même titre que le mot-clé Type\nvu en cours.\n\nIl y a quelques différences de sémantique entre Prop et Type que nous\nne détaillerons pas ici. (La principale idée étant que Type correspond\nau type des «types de données informatifs» (entiers,listes,fonctions),\nProp correspond au type des «formules purement logiques».)\n\n\nR2. Pour montrer qu'une proposition P est vraie, il s'agit d'exhiber\nune preuve, c'est-à-dire une expression p qui a le bon type (p : P).\n\nLe but de l'assistant de preuves Coq est de faciliter la construction\nde ces termes de preuve (p), puis au moment du \"Qed.\", de vérifier\nautomatiquement que le type du terme de preuve coïncide avec l'énoncé\nde la formule que l'on veut prouver.\n\nMaintenant, des exercices. *)\n\n(**************************************************************)\n(* Premières preuves \"à la main\", en logique propositionnelle *)\n(**************************************************************)\n\nSection PremieresPreuves.\n\n(* Dans cette section, supposons trois propositions A, B et C *)\nVariables A B C : Prop.\n\n(* une fonction est une preuve : par exemple, la fonction identité\n   \"prouve\" que A implique A *)\nDefinition identite : A -> A := fun a => a.\n\n(* prouver les propriétés suivantes *)\n\n\nDefinition ex0 : B -> B := fun b => b.\n\nDefinition ex1 : A -> B -> A := fun a => fun b => a.\n\nDefinition ex2 : A -> B -> B := fun a b => b.\n\nDefinition ex3 : A -> (A -> B) -> B := fun a ab => ab a.\n\nDefinition ex4 : (A -> B) -> (B -> C) -> A -> C := fun ab bc a => bc (ab a).\n\nDefinition ex5 : (A -> B) -> (A -> B -> C) -> A -> C := fun ab abc a => (abc a) (ab a).\n\n\nTheorem cinQ : (A -> B) -> (A -> B -> C) -> A -> C.\nintros H1.\nintros H2.\nintros H3.\napply H2.\nexact H3.\napply H1.\nexact H3.\nQed.\n(* auto. *)\n\n(*\nTheorem distr_and_or : (A /\\ B) \\/ (A /\\ C) -> A /\\ (B \\/ C).\nintros H.\ndestruct H as [H1 | H2].\nsplit.*)\n\n\n\n\n\n\n\n\n", "meta": {"author": "irinacake", "repo": "notesMaster1", "sha": "c6ea86ab79ccdec5f5b2201815cbc920e217f4b6", "save_path": "github-repos/coq/irinacake-notesMaster1", "path": "github-repos/coq/irinacake-notesMaster1/notesMaster1-c6ea86ab79ccdec5f5b2201815cbc920e217f4b6/Mementos_Et_TPs_OCaml_L3_Info/TAPFA_TP_CoQ/tp1_tapfa_coq_corrige.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8902942217558213, "lm_q1q2_score": 0.7438261727492237}}
{"text": "From sortalgs Require Export order.\nRequire Export Sorting.Permutation.\n\nImport List.ListNotations.\nOpen Scope list_scope.\n\nInductive Sorted {A} `{DecTotalOrder A} : list A -> Prop :=\n| Sorted_0 : Sorted []\n| Sorted_1 : forall x, Sorted [x]\n| Sorted_2 : forall x y l, Sorted (y :: l) -> leb x y ->\n                           Sorted (x :: y :: l).\n\nLemma lem_sorted_tail `{DecTotalOrder} :\n  forall l x, Sorted (x :: l) -> Sorted l.\nProof.\n  sauto.\nQed.\n\n(*********************************************************************)\n\nFixpoint sortedb {A} `{DecTotalOrder A} (l : list A) : bool :=\n  match l with\n  | [] => true\n  | [x] => true\n  | x :: (y :: l') as t => leb x y && sortedb t\n  end.\n\nLemma lem_sortedb_iff_sorted `{DecTotalOrder} :\n  forall l : list A, sortedb l <-> Sorted l.\nProof.\n  induction l; sauto brefl: on inv: Sorted.\nQed.\n\n(*********************************************************************)\n\nDefinition LeLst `{DecTotalOrder} x :=\n  List.Forall (leb x).\n\nLemma lem_lelst_nil `{DecTotalOrder} : forall x, LeLst x [].\nProof.\n  sauto.\nQed.\n\nLemma lem_lelst_cons `{DecTotalOrder} :\n  forall x y l, LeLst x l -> leb x y -> LeLst x (y :: l).\nProof.\n  sauto.\nQed.\n\nGlobal Hint Resolve lem_lelst_nil lem_lelst_cons : lelst.\n\nLemma lem_lelst_trans `{DecTotalOrder} :\n  forall l x y, LeLst y l -> leb x y -> LeLst x l.\nProof.\n  induction 1; sauto.\nQed.\n\nLemma lem_lelst_perm `{DecTotalOrder} :\n  forall l1 l2 x, Permutation l1 l2 -> LeLst x l1 -> LeLst x l2.\nProof.\n  induction 1; sauto lq: on.\nQed.\n\nLemma lem_lelst_perm_rev `{DecTotalOrder} :\n  forall l1 l2 x, Permutation l1 l2 -> LeLst x l2 -> LeLst x l1.\nProof.\n  induction 1; sauto lq: on.\nQed.\n\nLemma lem_lelst_app `{DecTotalOrder} :\n  forall l1 l2 x, LeLst x l1 -> LeLst x l2 -> LeLst x (l1 ++ l2).\nProof.\n  induction 1; sauto lq: on.\nQed.\n\nGlobal Hint Resolve lem_lelst_trans lem_lelst_perm lem_lelst_perm_rev\n       lem_lelst_app : lelst.\n\nLemma lem_lelst_sorted `{DecTotalOrder} :\n  forall l x, Sorted (x :: l) <-> LeLst x l /\\ Sorted l.\nProof.\n  induction l; sauto l: on use: lem_lelst_trans\n                     inv: Sorted, List.Forall ctrs: Sorted.\nQed.\n\n(*********************************************************************)\n\nDefinition GeLst `{DecTotalOrder} x l :=\n  List.Forall (fun y => leb y x) l.\n\nLemma lem_gelst_nil `{DecTotalOrder} : forall x, GeLst x [].\nProof.\n  sauto.\nQed.\n\nLemma lem_gelst_cons `{DecTotalOrder} :\n  forall x y l, GeLst x l -> leb y x -> GeLst x (y :: l).\nProof.\n  sauto.\nQed.\n\nGlobal Hint Resolve lem_gelst_nil lem_gelst_cons : gelst.\n\nLemma lem_gelst_trans `{DecTotalOrder} :\n  forall l x y, GeLst y l -> leb y x -> GeLst x l.\nProof.\n  induction 1; sauto.\nQed.\n\nLemma lem_gelst_perm `{DecTotalOrder} :\n  forall x l1 l2, Permutation l1 l2 -> GeLst x l1 -> GeLst x l2.\nProof.\n  induction 1; sauto lq: on.\nQed.\n\nLemma lem_gelst_perm_rev `{DecTotalOrder} :\n  forall l1 l2 x, Permutation l1 l2 -> GeLst x l2 -> GeLst x l1.\nProof.\n  induction 1; sauto lq: on.\nQed.\n\nLemma lem_gelst_app `{DecTotalOrder} :\n  forall l1 l2 x, GeLst x l1 -> GeLst x l2 -> GeLst x (l1 ++ l2).\nProof.\n  induction 1; sauto lq: on.\nQed.\n\nGlobal Hint Resolve lem_gelst_trans lem_gelst_perm lem_gelst_perm_rev\n     lem_gelst_app : gelst.\n", "meta": {"author": "lukaszcz", "repo": "sortalgs", "sha": "6e03cf693b6ed23565db0949d647efb96410ae09", "save_path": "github-repos/coq/lukaszcz-sortalgs", "path": "github-repos/coq/lukaszcz-sortalgs/sortalgs-6e03cf693b6ed23565db0949d647efb96410ae09/sorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.743801787390262}}
{"text": "(* Copyright (c) 2008-2012, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n *   http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import Arith List.\n\nRequire Import CpdtTactics.\n\nSet Implicit Arguments.\n(* end hide *)\n\n\n(** %\\chapter{Dependent Data Structures}% *)\n\n(** Our red-black tree example from the last chapter illustrated how dependent types enable static enforcement of data structure invariants.  To find interesting uses of dependent data structures, however, we need not look to the favorite examples of data structures and algorithms textbooks.  More basic examples like length-indexed and heterogeneous lists come up again and again as the building blocks of dependent programs.  There is a surprisingly large design space for this class of data structure, and we will spend this chapter exploring it. *)\n\n\n(** * More Length-Indexed Lists *)\n\n(** We begin with a deeper look at the length-indexed lists that began the last chapter.%\\index{Gallina terms!ilist}% *)\n\nSection ilist.\n  Variable A : Set.\n\n  Inductive ilist : nat -> Set :=\n  | Nil : ilist O\n  | Cons : forall n, A -> ilist n -> ilist (S n).\n\n  (** We might like to have a certified function for selecting an element of an [ilist] by position.  We could do this using subset types and explicit manipulation of proofs, but dependent types let us do it more directly.  It is helpful to define a type family %\\index{Gallina terms!fin}%[fin], where [fin n] is isomorphic to [{m : nat | m < n}].  The type family name stands for \"finite.\" *)\n\n  (* EX: Define a function [get] for extracting an [ilist] element by position. *)\n\n(* begin thide *)\n  Inductive fin : nat -> Set :=\n  | First : forall n, fin (S n)\n  | Next : forall n, fin n -> fin (S n).\n\n  (** An instance of [fin] is essentially a more richly typed copy of a prefix of the natural numbers.  Every element is a [First] iterated through applying [Next] a number of times that indicates which number is being selected.  For instance, the three values of type [fin 3] are [First 2], [Next (First 1)], and [Next (Next (First 0))].\n\n     Now it is easy to pick a [Prop]-free type for a selection function.  As usual, our first implementation attempt will not convince the type checker, and we will attack the deficiencies one at a time.\n     [[\n  Fixpoint get n (ls : ilist n) : fin n -> A :=\n    match ls with\n      | Nil => fun idx => ?\n      | Cons _ x ls' => fun idx =>\n        match idx with\n          | First _ => x\n          | Next _ idx' => get ls' idx'\n        end\n    end.\n    ]]\n    %\\vspace{-.15in}%We apply the usual wisdom of delaying arguments in [Fixpoint]s so that they may be included in [return] clauses.  This still leaves us with a quandary in each of the [match] cases.  First, we need to figure out how to take advantage of the contradiction in the [Nil] case.  Every [fin] has a type of the form [S n], which cannot unify with the [O] value that we learn for [n] in the [Nil] case.  The solution we adopt is another case of [match]-within-[return], with the [return] clause chosen carefully so that it returns the proper type [A] in case the [fin] index is [O], which we know is true here; and so that it returns an easy-to-inhabit type [unit] in the remaining, impossible cases, which nonetheless appear explicitly in the body of the [match].\n    [[\n  Fixpoint get n (ls : ilist n) : fin n -> A :=\n    match ls with\n      | Nil => fun idx =>\n        match idx in fin n' return (match n' with\n                                        | O => A\n                                        | S _ => unit\n                                      end) with\n          | First _ => tt\n          | Next _ _ => tt\n        end\n      | Cons _ x ls' => fun idx =>\n        match idx with\n          | First _ => x\n          | Next _ idx' => get ls' idx'\n        end\n    end.\n    ]]\n    %\\vspace{-.15in}%Now the first [match] case type-checks, and we see that the problem with the [Cons] case is that the pattern-bound variable [idx'] does not have an apparent type compatible with [ls'].  In fact, the error message Coq gives for this exact code can be confusing, thanks to an overenthusiastic type inference heuristic.  We are told that the [Nil] case body has type [match X with | O => A | S _ => unit end] for a unification variable [X], while it is expected to have type [A].  We can see that setting [X] to [O] resolves the conflict, but Coq is not yet smart enough to do this unification automatically.  Repeating the function's type in a [return] annotation, used with an [in] annotation, leads us to a more informative error message, saying that [idx'] has type [fin n1] while it is expected to have type [fin n0], where [n0] is bound by the [Cons] pattern and [n1] by the [Next] pattern.  As the code is written above, nothing forces these two natural numbers to be equal, though we know intuitively that they must be.\n\n    We need to use [match] annotations to make the relationship explicit.  Unfortunately, the usual trick of postponing argument binding will not help us here.  We need to match on both [ls] and [idx]; one or the other must be matched first.  To get around this, we apply the convoy pattern that we met last chapter.  This application is a little more clever than those we saw before; we use the natural number predecessor function [pred] to express the relationship between the types of these variables.\n    [[\n  Fixpoint get n (ls : ilist n) : fin n -> A :=\n    match ls with\n      | Nil => fun idx =>\n        match idx in fin n' return (match n' with\n                                        | O => A\n                                        | S _ => unit\n                                      end) with\n          | First _ => tt\n          | Next _ _ => tt\n        end\n      | Cons _ x ls' => fun idx =>\n        match idx in fin n' return ilist (pred n') -> A with\n          | First _ => fun _ => x\n          | Next _ idx' => fun ls' => get ls' idx'\n        end ls'\n    end.\n    ]]\n    %\\vspace{-.15in}%There is just one problem left with this implementation.  Though we know that the local [ls'] in the [Next] case is equal to the original [ls'], the type-checker is not satisfied that the recursive call to [get] does not introduce non-termination.  We solve the problem by convoy-binding the partial application of [get] to [ls'], rather than [ls'] by itself. *)\n\n  Fixpoint get n (ls : ilist n) : fin n -> A :=\n    match ls with\n      | Nil => fun idx =>\n        match idx in fin n' return (match n' with\n                                        | O => A\n                                        | S _ => unit\n                                      end) with\n          | First _ => tt\n          | Next _ _ => tt\n        end\n      | Cons _ x ls' => fun idx =>\n        match idx in fin n' return (fin (pred n') -> A) -> A with\n          | First _ => fun _ => x\n          | Next _ idx' => fun get_ls' => get_ls' idx'\n        end (get ls')\n    end.\n(* end thide *)\nEnd ilist.\n\nImplicit Arguments Nil [A].\nImplicit Arguments First [n].\n\n(** A few examples show how to make use of these definitions. *)\n\nCheck Cons 0 (Cons 1 (Cons 2 Nil)).\n(** %\\vspace{-.15in}% [[\n  Cons 0 (Cons 1 (Cons 2 Nil))\n     : ilist nat 3\n]]\n*)\n\n(* begin thide *)\nEval simpl in get (Cons 0 (Cons 1 (Cons 2 Nil))) First.\n(** %\\vspace{-.15in}% [[\n     = 0\n     : nat\n]]\n*)\n\nEval simpl in get (Cons 0 (Cons 1 (Cons 2 Nil))) (Next First).\n(** %\\vspace{-.15in}% [[\n     = 1\n     : nat\n]]\n*)\n\nEval simpl in get (Cons 0 (Cons 1 (Cons 2 Nil))) (Next (Next First)).\n(** %\\vspace{-.15in}% [[\n     = 2\n     : nat\n]]\n*)\n(* end thide *)\n\n(* begin hide *)\n(* begin thide *)\nDefinition map' := map.\n(* end thide *)\n(* end hide *)\n\n(** Our [get] function is also quite easy to reason about.  We show how with a short example about an analogue to the list [map] function. *)\n\nSection ilist_map.\n  Variables A B : Set.\n  Variable f : A -> B.\n\n  Fixpoint imap n (ls : ilist A n) : ilist B n :=\n    match ls with\n      | Nil => Nil\n      | Cons _ x ls' => Cons (f x) (imap ls')\n    end.\n\n  (** It is easy to prove that [get] \"distributes over\" [imap] calls. *)\n\n(* EX: Prove that [get] distributes over [imap]. *)\n\n(* begin thide *)\n  Theorem get_imap : forall n (idx : fin n) (ls : ilist A n),\n    get (imap ls) idx = f (get ls idx).\n    induction ls; dep_destruct idx; crush.\n  Qed.\n(* end thide *)\nEnd ilist_map.\n\n(** The only tricky bit is remembering to use our [dep_destruct] tactic in place of plain [destruct] when faced with a baffling tactic error message. *)\n\n(** * Heterogeneous Lists *)\n\n(** Programmers who move to statically typed functional languages from scripting languages often complain about the requirement that every element of a list have the same type.  With fancy type systems, we can partially lift this requirement.  We can index a list type with a \"type-level\" list that explains what type each element of the list should have.  This has been done in a variety of ways in Haskell using type classes, and we can do it much more cleanly and directly in Coq. *)\n\nSection hlist.\n  Variable A : Type.\n  Variable B : A -> Type.\n\n  (* EX: Define a type [hlist] indexed by a [list A], where the type of each element is determined by running [B] on the corresponding element of the index list. *)\n\n  (** We parameterize our heterogeneous lists by a type [A] and an [A]-indexed type [B].%\\index{Gallina terms!hlist}% *)\n\n(* begin thide *)\n  Inductive hlist : list A -> Type :=\n  | HNil : hlist nil\n  | HCons : forall (x : A) (ls : list A), B x -> hlist ls -> hlist (x :: ls).\n\n  (** We can implement a variant of the last section's [get] function for [hlist]s.  To get the dependent typing to work out, we will need to index our element selectors (in type family [member]) by the types of data that they point to.%\\index{Gallina terms!member}% *)\n\n(* end thide *)\n  (* EX: Define an analogue to [get] for [hlist]s. *)\n\n(* begin thide *)\n  Variable elm : A.\n\n  Inductive member : list A -> Type :=\n  | HFirst : forall ls, member (elm :: ls)\n  | HNext : forall x ls, member ls -> member (x :: ls).\n\n  (** Because the element [elm] that we are \"searching for\" in a list does not change across the constructors of [member], we simplify our definitions by making [elm] a local variable.  In the definition of [member], we say that [elm] is found in any list that begins with [elm], and, if removing the first element of a list leaves [elm] present, then [elm] is present in the original list, too.  The form looks much like a predicate for list membership, but we purposely define [member] in [Type] so that we may decompose its values to guide computations.\n\n     We can use [member] to adapt our definition of [get] to [hlist]s.  The same basic [match] tricks apply.  In the [HCons] case, we form a two-element convoy, passing both the data element [x] and the recursor for the sublist [mls'] to the result of the inner [match].  We did not need to do that in [get]'s definition because the types of list elements were not dependent there. *)\n\n  Fixpoint hget ls (mls : hlist ls) : member ls -> B elm :=\n    match mls with\n      | HNil => fun mem =>\n        match mem in member ls' return (match ls' with\n                                          | nil => B elm\n                                          | _ :: _ => unit\n                                        end) with\n          | HFirst _ => tt\n          | HNext _ _ _ => tt\n        end\n      | HCons _ _ x mls' => fun mem =>\n        match mem in member ls' return (match ls' with\n                                          | nil => Empty_set\n                                          | x' :: ls'' =>\n                                            B x' -> (member ls'' -> B elm)\n                                            -> B elm\n                                        end) with\n          | HFirst _ => fun x _ => x\n          | HNext _ _ mem' => fun _ get_mls' => get_mls' mem'\n        end x (hget mls')\n    end.\n(* end thide *)\nEnd hlist.\n\n(* begin thide *)\nImplicit Arguments HNil [A B].\nImplicit Arguments HCons [A B x ls].\n\nImplicit Arguments HFirst [A elm ls].\nImplicit Arguments HNext [A elm x ls].\n(* end thide *)\n\n(** By putting the parameters [A] and [B] in [Type], we enable fancier kinds of polymorphism than in mainstream functional languages.  For instance, one use of [hlist] is for the simple heterogeneous lists that we referred to earlier. *)\n\nDefinition someTypes : list Set := nat :: bool :: nil.\n\n(* begin thide *)\n\nExample someValues : hlist (fun T : Set => T) someTypes :=\n  HCons 5 (HCons true HNil).\n\nEval simpl in hget someValues HFirst.\n(** %\\vspace{-.15in}% [[\n     = 5\n     : (fun T : Set => T) nat\n]]\n*)\n\nEval simpl in hget someValues (HNext HFirst).\n(** %\\vspace{-.15in}% [[\n     = true\n     : (fun T : Set => T) bool\n]]\n*)\n\n(** We can also build indexed lists of pairs in this way. *)\n\nExample somePairs : hlist (fun T : Set => T * T)%type someTypes :=\n  HCons (1, 2) (HCons (true, false) HNil).\n\n(** There are many other useful applications of heterogeneous lists, based on different choices of the first argument to [hlist]. *)\n\n(* end thide *)\n\n\n(** ** A Lambda Calculus Interpreter *)\n\n(** Heterogeneous lists are very useful in implementing %\\index{interpreters}%interpreters for functional programming languages.  Using the types and operations we have already defined, it is trivial to write an interpreter for simply typed lambda calculus%\\index{lambda calculus}%.  Our interpreter can alternatively be thought of as a denotational semantics (but worry not if you are not familiar with such terminology from semantics).\n\n   We start with an algebraic datatype for types. *)\n\nInductive type : Set :=\n| Unit : type\n| Arrow : type -> type -> type.\n\n(** Now we can define a type family for expressions.  An [exp ts t] will stand for an expression that has type [t] and whose free variables have types in the list [ts].  We effectively use the de Bruijn index variable representation%~\\cite{DeBruijn}%.  Variables are represented as [member] values; that is, a variable is more or less a constructive proof that a particular type is found in the type environment. *)\n\nInductive exp : list type -> type -> Set :=\n| Const : forall ts, exp ts Unit\n(* begin thide *)\n| Var : forall ts t, member t ts -> exp ts t\n| App : forall ts dom ran, exp ts (Arrow dom ran) -> exp ts dom -> exp ts ran\n| Abs : forall ts dom ran, exp (dom :: ts) ran -> exp ts (Arrow dom ran).\n(* end thide *)\n\nImplicit Arguments Const [ts].\n\n(** We write a simple recursive function to translate [type]s into [Set]s. *)\n\nFixpoint typeDenote (t : type) : Set :=\n  match t with\n    | Unit => unit\n    | Arrow t1 t2 => typeDenote t1 -> typeDenote t2\n  end.\n\n(** Now it is straightforward to write an expression interpreter.  The type of the function, [expDenote], tells us that we translate expressions into functions from properly typed environments to final values.  An environment for a free variable list [ts] is simply an [hlist typeDenote ts].  That is, for each free variable, the heterogeneous list that is the environment must have a value of the variable's associated type.  We use [hget] to implement the [Var] case, and we use [HCons] to extend the environment in the [Abs] case. *)\n\n(* EX: Define an interpreter for [exp]s. *)\n\n(* begin thide *)\nFixpoint expDenote ts t (e : exp ts t) : hlist typeDenote ts -> typeDenote t :=\n  match e with\n    | Const _ => fun _ => tt\n\n    | Var _ _ mem => fun s => hget s mem\n    | App _ _ _ e1 e2 => fun s => (expDenote e1 s) (expDenote e2 s)\n    | Abs _ _ _ e' => fun s => fun x => expDenote e' (HCons x s)\n  end.\n\n(** Like for previous examples, our interpreter is easy to run with [simpl]. *)\n\nEval simpl in expDenote Const HNil.\n(** %\\vspace{-.15in}% [[\n    = tt\n     : typeDenote Unit\n]]\n*)\n\nEval simpl in expDenote (Abs (dom := Unit) (Var HFirst)) HNil.\n(** %\\vspace{-.15in}% [[\n     = fun x : unit => x\n     : typeDenote (Arrow Unit Unit)\n]]\n*)\n\nEval simpl in expDenote (Abs (dom := Unit)\n  (Abs (dom := Unit) (Var (HNext HFirst)))) HNil.\n(** %\\vspace{-.15in}% [[\n     = fun x _ : unit => x\n     : typeDenote (Arrow Unit (Arrow Unit Unit))\n]]\n*)\n\nEval simpl in expDenote (Abs (dom := Unit) (Abs (dom := Unit) (Var HFirst))) HNil.\n(** %\\vspace{-.15in}% [[\n     = fun _ x0 : unit => x0\n     : typeDenote (Arrow Unit (Arrow Unit Unit))\n]]\n*)\n\nEval simpl in expDenote (App (Abs (Var HFirst)) Const) HNil.\n(** %\\vspace{-.15in}% [[\n     = tt\n     : typeDenote Unit\n]]\n*)\n\n(* end thide *)\n\n(** We are starting to develop the tools behind dependent typing's amazing advantage over alternative approaches in several important areas.  Here, we have implemented complete syntax, typing rules, and evaluation semantics for simply typed lambda calculus without even needing to define a syntactic substitution operation.  We did it all without a single line of proof, and our implementation is manifestly executable.  Other, more common approaches to language formalization often state and prove explicit theorems about type safety of languages.  In the above example, we got type safety, termination, and other meta-theorems for free, by reduction to CIC, which we know has those properties. *)\n\n\n(** * Recursive Type Definitions *)\n\n(** %\\index{recursive type definition}%There is another style of datatype definition that leads to much simpler definitions of the [get] and [hget] definitions above.  Because Coq supports \"type-level computation,\" we can redo our inductive definitions as _recursive_ definitions.  Here we will preface type names with the letter [f] to indicate that they are based on explicit recursive _function_ definitions. *)\n\n(* EX: Come up with an alternate [ilist] definition that makes it easier to write [get]. *)\n\nSection filist.\n  Variable A : Set.\n\n(* begin thide *)\n  Fixpoint filist (n : nat) : Set :=\n    match n with\n      | O => unit\n      | S n' => A * filist n'\n    end%type.\n\n  (** We say that a list of length 0 has no contents, and a list of length [S n'] is a pair of a data value and a list of length [n']. *)\n\n  Fixpoint ffin (n : nat) : Set :=\n    match n with\n      | O => Empty_set\n      | S n' => option (ffin n')\n    end.\n\n  (** We express that there are no index values when [n = O], by defining such indices as type [Empty_set]; and we express that, at [n = S n'], there is a choice between picking the first element of the list (represented as [None]) or choosing a later element (represented by [Some idx], where [idx] is an index into the list tail).  For instance, the three values of type [ffin 3] are [None], [Some None], and [Some (Some None)]. *)\n\n  Fixpoint fget (n : nat) : filist n -> ffin n -> A :=\n    match n with\n      | O => fun _ idx => match idx with end\n      | S n' => fun ls idx =>\n        match idx with\n          | None => fst ls\n          | Some idx' => fget n' (snd ls) idx'\n        end\n    end.\n\n  (** Our new [get] implementation needs only one dependent [match], and its annotation is inferred for us.  Our choices of data structure implementations lead to just the right typing behavior for this new definition to work out. *)\n(* end thide *)\n\nEnd filist.\n\n(** Heterogeneous lists are a little trickier to define with recursion, but we then reap similar benefits in simplicity of use. *)\n\n(* EX: Come up with an alternate [hlist] definition that makes it easier to write [hget]. *)\n\nSection fhlist.\n  Variable A : Type.\n  Variable B : A -> Type.\n\n(* begin thide *)\n  Fixpoint fhlist (ls : list A) : Type :=\n    match ls with\n      | nil => unit\n      | x :: ls' => B x * fhlist ls'\n    end%type.\n\n  (** The definition of [fhlist] follows the definition of [filist], with the added wrinkle of dependently typed data elements. *)\n\n  Variable elm : A.\n\n  Fixpoint fmember (ls : list A) : Type :=\n    match ls with\n      | nil => Empty_set\n      | x :: ls' => (x = elm) + fmember ls'\n    end%type.\n\n  (** The definition of [fmember] follows the definition of [ffin].  Empty lists have no members, and member types for nonempty lists are built by adding one new option to the type of members of the list tail.  While for [ffin] we needed no new information associated with the option that we add, here we need to know that the head of the list equals the element we are searching for.  We express that idea with a sum type whose left branch is the appropriate equality proposition.  Since we define [fmember] to live in [Type], we can insert [Prop] types as needed, because [Prop] is a subtype of [Type].\n\n     We know all of the tricks needed to write a first attempt at a [get] function for [fhlist]s.\n     [[\n  Fixpoint fhget (ls : list A) : fhlist ls -> fmember ls -> B elm :=\n    match ls with\n      | nil => fun _ idx => match idx with end\n      | _ :: ls' => fun mls idx =>\n        match idx with\n          | inl _ => fst mls\n          | inr idx' => fhget ls' (snd mls) idx'\n        end\n    end.\n    ]]\n    %\\vspace{-.15in}%Only one problem remains.  The expression [fst mls] is not known to have the proper type.  To demonstrate that it does, we need to use the proof available in the [inl] case of the inner [match]. *)\n\n  Fixpoint fhget (ls : list A) : fhlist ls -> fmember ls -> B elm :=\n    match ls with\n      | nil => fun _ idx => match idx with end\n      | _ :: ls' => fun mls idx =>\n        match idx with\n          | inl pf => match pf with\n                        | eq_refl => fst mls\n                      end\n          | inr idx' => fhget ls' (snd mls) idx'\n        end\n    end.\n\n  (** By pattern-matching on the equality proof [pf], we make that equality known to the type-checker.  Exactly why this works can be seen by studying the definition of equality. *)\n\n  (* begin hide *)\n  (* begin thide *)\n  Definition foo := @eq_refl.\n  (* end thide *)\n  (* end hide *)\n\n  Print eq.\n  (** %\\vspace{-.15in}% [[\nInductive eq (A : Type) (x : A) : A -> Prop :=  eq_refl : x = x\n]]\n\nIn a proposition [x = y], we see that [x] is a parameter and [y] is a regular argument.  The type of the constructor [eq_refl] shows that [y] can only ever be instantiated to [x].  Thus, within a pattern-match with [eq_refl], occurrences of [y] can be replaced with occurrences of [x] for typing purposes. *)\n(* end thide *)\n\nEnd fhlist.\n\nImplicit Arguments fhget [A B elm ls].\n\n(** How does one choose between the two data structure encoding strategies we have presented so far?  Before answering that question in this chapter's final section, we introduce one further approach. *)\n\n\n(** * Data Structures as Index Functions *)\n\n(** %\\index{index function}%Indexed lists can be useful in defining other inductive types with constructors that take variable numbers of arguments.  In this section, we consider parameterized trees with arbitrary branching factor. *)\n\nSection tree.\n  Variable A : Set.\n\n  Inductive tree : Set :=\n  | Leaf : A -> tree\n  | Node : forall n, ilist tree n -> tree.\nEnd tree.\n\n(** Every [Node] of a [tree] has a natural number argument, which gives the number of child trees in the second argument, typed with [ilist].  We can define two operations on trees of naturals: summing their elements and incrementing their elements.  It is useful to define a generic fold function on [ilist]s first. *)\n\nSection ifoldr.\n  Variables A B : Set.\n  Variable f : A -> B -> B.\n  Variable i : B.\n\n  Fixpoint ifoldr n (ls : ilist A n) : B :=\n    match ls with\n      | Nil => i\n      | Cons _ x ls' => f x (ifoldr ls')\n    end.\nEnd ifoldr.\n\nFixpoint sum (t : tree nat) : nat :=\n  match t with\n    | Leaf n => n\n    | Node _ ls => ifoldr (fun t' n => sum t' + n) O ls\n  end.\n\nFixpoint inc (t : tree nat) : tree nat :=\n  match t with\n    | Leaf n => Leaf (S n)\n    | Node _ ls => Node (imap inc ls)\n  end.\n\n(** Now we might like to prove that [inc] does not decrease a tree's [sum]. *)\n\nTheorem sum_inc : forall t, sum (inc t) >= sum t.\n(* begin thide *)\n  induction t; crush.\n  (** [[\n  n : nat\n  i : ilist (tree nat) n\n  ============================\n   ifoldr (fun (t' : tree nat) (n0 : nat) => sum t' + n0) 0 (imap inc i) >=\n   ifoldr (fun (t' : tree nat) (n0 : nat) => sum t' + n0) 0 i\n \n   ]]\n\n   We are left with a single subgoal which does not seem provable directly.  This is the same problem that we met in Chapter 3 with other %\\index{nested inductive type}%nested inductive types. *)\n\n  Check tree_ind.\n  (** %\\vspace{-.15in}% [[\n  tree_ind\n     : forall (A : Set) (P : tree A -> Prop),\n       (forall a : A, P (Leaf a)) ->\n       (forall (n : nat) (i : ilist (tree A) n), P (Node i)) ->\n       forall t : tree A, P t\n]]\n\nThe automatically generated induction principle is too weak.  For the [Node] case, it gives us no inductive hypothesis.  We could write our own induction principle, as we did in Chapter 3, but there is an easier way, if we are willing to alter the definition of [tree]. *)\n\nAbort.\n\nReset tree.\n\n(** First, let us try using our recursive definition of [ilist]s instead of the inductive version. *)\n\nSection tree.\n  Variable A : Set.\n\n  (** %\\vspace{-.15in}% [[\n  Inductive tree : Set :=\n  | Leaf : A -> tree\n  | Node : forall n, filist tree n -> tree.\n]]\n\n<<\nError: Non strictly positive occurrence of \"tree\" in\n \"forall n : nat, filist tree n -> tree\"\n>>\n\n  The special-case rule for nested datatypes only works with nested uses of other inductive types, which could be replaced with uses of new mutually inductive types.  We defined [filist] recursively, so it may not be used in nested inductive definitions.\n\n  Our final solution uses yet another of the inductive definition techniques introduced in Chapter 3, %\\index{reflexive inductive type}%reflexive types.  Instead of merely using [fin] to get elements out of [ilist], we can _define_ [ilist] in terms of [fin].  For the reasons outlined above, it turns out to be easier to work with [ffin] in place of [fin]. *)\n\n  Inductive tree : Set :=\n  | Leaf : A -> tree\n  | Node : forall n, (ffin n -> tree) -> tree.\n\n  (** A [Node] is indexed by a natural number [n], and the node's [n] children are represented as a function from [ffin n] to trees, which is isomorphic to the [ilist]-based representation that we used above. *)\n\nEnd tree.\n\nImplicit Arguments Node [A n].\n\n(** We can redefine [sum] and [inc] for our new [tree] type.  Again, it is useful to define a generic fold function first.  This time, it takes in a function whose domain is some [ffin] type, and it folds another function over the results of calling the first function at every possible [ffin] value. *)\n\nSection rifoldr.\n  Variables A B : Set.\n  Variable f : A -> B -> B.\n  Variable i : B.\n\n  Fixpoint rifoldr (n : nat) : (ffin n -> A) -> B :=\n    match n with\n      | O => fun _ => i\n      | S n' => fun get => f (get None) (rifoldr n' (fun idx => get (Some idx)))\n    end.\nEnd rifoldr.\n\nImplicit Arguments rifoldr [A B n].\n\nFixpoint sum (t : tree nat) : nat :=\n  match t with\n    | Leaf n => n\n    | Node _ f => rifoldr plus O (fun idx => sum (f idx))\n  end.\n\nFixpoint inc (t : tree nat) : tree nat :=\n  match t with\n    | Leaf n => Leaf (S n)\n    | Node _ f => Node (fun idx => inc (f idx))\n  end.\n\n(** Now we are ready to prove the theorem where we got stuck before.  We will not need to define any new induction principle, but it _will_ be helpful to prove some lemmas. *)\n\nLemma plus_ge : forall x1 y1 x2 y2,\n  x1 >= x2\n  -> y1 >= y2\n  -> x1 + y1 >= x2 + y2.\n  crush.\nQed.\n\nLemma sum_inc' : forall n (f1 f2 : ffin n -> nat),\n  (forall idx, f1 idx >= f2 idx)\n  -> rifoldr plus O f1 >= rifoldr plus O f2.\n  Hint Resolve plus_ge.\n\n  induction n; crush.\nQed.\n\nTheorem sum_inc : forall t, sum (inc t) >= sum t.\n  Hint Resolve sum_inc'.\n\n  induction t; crush.\nQed.\n\n(* end thide *)\n\n(** Even if Coq would generate complete induction principles automatically for nested inductive definitions like the one we started with, there would still be advantages to using this style of reflexive encoding.  We see one of those advantages in the definition of [inc], where we did not need to use any kind of auxiliary function.  In general, reflexive encodings often admit direct implementations of operations that would require recursion if performed with more traditional inductive data structures. *)\n\n(** ** Another Interpreter Example *)\n\n(** We develop another example of variable-arity constructors, in the form of optimization of a small expression language with a construct like Scheme's <<cond>>.  Each of our conditional expressions takes a list of pairs of boolean tests and bodies.  The value of the conditional comes from the body of the first test in the list to evaluate to [true].  To simplify the %\\index{interpreters}%interpreter we will write, we force each conditional to include a final, default case. *)\n\nInductive type' : Type := Nat | Bool.\n\nInductive exp' : type' -> Type :=\n| NConst : nat -> exp' Nat\n| Plus : exp' Nat -> exp' Nat -> exp' Nat\n| Eq : exp' Nat -> exp' Nat -> exp' Bool\n\n| BConst : bool -> exp' Bool\n(* begin thide *)\n| Cond : forall n t, (ffin n -> exp' Bool)\n  -> (ffin n -> exp' t) -> exp' t -> exp' t.\n(* end thide *)\n\n(** A [Cond] is parameterized by a natural [n], which tells us how many cases this conditional has.  The test expressions are represented with a function of type [ffin n -> exp' Bool], and the bodies are represented with a function of type [ffin n -> exp' t], where [t] is the overall type.  The final [exp' t] argument is the default case.  For example, here is an expression that successively checks whether [2 + 2 = 5] (returning 0 if so) or if [1 + 1 = 2] (returning 1 if so), returning 2 otherwise. *)\n\nExample ex1 := Cond 2\n  (fun f => match f with\n              | None => Eq (Plus (NConst 2) (NConst 2)) (NConst 5)\n              | Some None => Eq (Plus (NConst 1) (NConst 1)) (NConst 2)\n              | Some (Some v) => match v with end\n            end)\n  (fun f => match f with\n              | None => NConst 0\n              | Some None => NConst 1\n              | Some (Some v) => match v with end\n            end)\n  (NConst 2).\n\n(** We start implementing our interpreter with a standard type denotation function. *)\n\nDefinition type'Denote (t : type') : Set :=\n  match t with\n    | Nat => nat\n    | Bool => bool\n  end.\n\n(** To implement the expression interpreter, it is useful to have the following function that implements the functionality of [Cond] without involving any syntax. *)\n\n(* begin thide *)\nSection cond.\n  Variable A : Set.\n  Variable default : A.\n\n  Fixpoint cond (n : nat) : (ffin n -> bool) -> (ffin n -> A) -> A :=\n    match n with\n      | O => fun _ _ => default\n      | S n' => fun tests bodies =>\n        if tests None\n          then bodies None\n          else cond n'\n            (fun idx => tests (Some idx))\n            (fun idx => bodies (Some idx))\n    end.\nEnd cond.\n\nImplicit Arguments cond [A n].\n(* end thide *)\n\n(** Now the expression interpreter is straightforward to write. *)\n\n(* begin thide *)\nFixpoint exp'Denote t (e : exp' t) : type'Denote t :=\n  match e with\n    | NConst n => n\n    | Plus e1 e2 => exp'Denote e1 + exp'Denote e2\n    | Eq e1 e2 =>\n      if eq_nat_dec (exp'Denote e1) (exp'Denote e2) then true else false\n\n    | BConst b => b\n    | Cond _ _ tests bodies default =>\n      cond\n      (exp'Denote default)\n      (fun idx => exp'Denote (tests idx))\n      (fun idx => exp'Denote (bodies idx))\n  end.\n(* begin hide *)\nReset exp'Denote.\n(* end hide *)\n(* end thide *)\n\n(* begin hide *)\nFixpoint exp'Denote t (e : exp' t) : type'Denote t :=\n  match e with\n    | NConst n => n\n    | Plus e1 e2 => exp'Denote e1 + exp'Denote e2\n    | Eq e1 e2 =>\n      if eq_nat_dec (exp'Denote e1) (exp'Denote e2) then true else false\n\n    | BConst b => b\n    | Cond _ _ tests bodies default =>\n(* begin thide *)\n      cond\n      (exp'Denote default)\n      (fun idx => exp'Denote (tests idx))\n      (fun idx => exp'Denote (bodies idx))\n(* end thide *)\n  end.\n(* end hide *)\n\n(** We will implement a constant-folding function that optimizes conditionals, removing cases with known-[false] tests and cases that come after known-[true] tests.  A function [cfoldCond] implements the heart of this logic.  The convoy pattern is used again near the end of the implementation. *)\n\n(* begin thide *)\nSection cfoldCond.\n  Variable t : type'.\n  Variable default : exp' t.\n\n  Fixpoint cfoldCond (n : nat)\n    : (ffin n -> exp' Bool) -> (ffin n -> exp' t) -> exp' t :=\n    match n with\n      | O => fun _ _ => default\n      | S n' => fun tests bodies =>\n        match tests None return _ with\n          | BConst true => bodies None\n          | BConst false => cfoldCond n'\n            (fun idx => tests (Some idx))\n            (fun idx => bodies (Some idx))\n          | _ =>\n            let e := cfoldCond n'\n              (fun idx => tests (Some idx))\n              (fun idx => bodies (Some idx)) in\n            match e in exp' t return exp' t -> exp' t with\n              | Cond n _ tests' bodies' default' => fun body =>\n                Cond\n                (S n)\n                (fun idx => match idx with\n                              | None => tests None\n                              | Some idx => tests' idx\n                            end)\n                (fun idx => match idx with\n                              | None => body\n                              | Some idx => bodies' idx\n                            end)\n                default'\n              | e => fun body =>\n                Cond\n                1\n                (fun _ => tests None)\n                (fun _ => body)\n                e\n            end (bodies None)\n        end\n    end.\nEnd cfoldCond.\n\nImplicit Arguments cfoldCond [t n].\n(* end thide *)\n\n(** Like for the interpreters, most of the action was in this helper function, and [cfold] itself is easy to write. *)\n\n(* begin thide *)\nFixpoint cfold t (e : exp' t) : exp' t :=\n  match e with\n    | NConst n => NConst n\n    | Plus e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold e2 in\n      match e1', e2' return exp' Nat with\n        | NConst n1, NConst n2 => NConst (n1 + n2)\n        | _, _ => Plus e1' e2'\n      end\n    | Eq e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold e2 in\n      match e1', e2' return exp' Bool with\n        | NConst n1, NConst n2 => BConst (if eq_nat_dec n1 n2 then true else false)\n        | _, _ => Eq e1' e2'\n      end\n\n    | BConst b => BConst b\n    | Cond _ _ tests bodies default =>\n      cfoldCond\n      (cfold default)\n      (fun idx => cfold (tests idx))\n      (fun idx => cfold (bodies idx))\n  end.\n(* end thide *)\n\n(* begin thide *)\n(** To prove our final correctness theorem, it is useful to know that [cfoldCond] preserves expression meanings.  The following lemma formalizes that property.  The proof is a standard mostly automated one, with the only wrinkle being a guided instantiation of the quantifiers in the induction hypothesis. *)\n\nLemma cfoldCond_correct : forall t (default : exp' t)\n  n (tests : ffin n -> exp' Bool) (bodies : ffin n -> exp' t),\n  exp'Denote (cfoldCond default tests bodies)\n  = exp'Denote (Cond n tests bodies default).\n  induction n; crush;\n    match goal with\n      | [ IHn : forall tests bodies, _, tests : _ -> _, bodies : _ -> _ |- _ ] =>\n        specialize (IHn (fun idx => tests (Some idx)) (fun idx => bodies (Some idx)))\n    end;\n    repeat (match goal with\n              | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n                dep_destruct E\n              | [ |- context[if ?B then _ else _] ] => destruct B\n            end; crush).\nQed.\n\n(** It is also useful to know that the result of a call to [cond] is not changed by substituting new tests and bodies functions, so long as the new functions have the same input-output behavior as the old.  It turns out that, in Coq, it is not possible to prove in general that functions related in this way are equal.  We treat this issue with our discussion of axioms in a later chapter.  For now, it suffices to prove that the particular function [cond] is _extensional_; that is, it is unaffected by substitution of functions with input-output equivalents. *)\n\nLemma cond_ext : forall (A : Set) (default : A) n (tests tests' : ffin n -> bool)\n  (bodies bodies' : ffin n -> A),\n  (forall idx, tests idx = tests' idx)\n  -> (forall idx, bodies idx = bodies' idx)\n  -> cond default tests bodies\n  = cond default tests' bodies'.\n  induction n; crush;\n    match goal with\n      | [ |- context[if ?E then _ else _] ] => destruct E\n    end; crush.\nQed.\n\n(** Now the final theorem is easy to prove. *)\n(* end thide *)\n\nTheorem cfold_correct : forall t (e : exp' t),\n  exp'Denote (cfold e) = exp'Denote e.\n(* begin thide *)\n  Hint Rewrite cfoldCond_correct.\n  Hint Resolve cond_ext.\n\n  induction e; crush;\n    repeat (match goal with\n              | [ |- context[cfold ?E] ] => dep_destruct (cfold E)\n            end; crush).\nQed.\n(* end thide *)\n\n(** We add our two lemmas as hints and perform standard automation with pattern-matching of subterms to destruct. *)\n\n(** * Choosing Between Representations *)\n\n(** It is not always clear which of these representation techniques to apply in a particular situation, but I will try to summarize the pros and cons of each.\n\n   Inductive types are often the most pleasant to work with, after someone has spent the time implementing some basic library functions for them, using fancy [match] annotations.  Many aspects of Coq's logic and tactic support are specialized to deal with inductive types, and you may miss out if you use alternate encodings.\n\n   Recursive types usually involve much less initial effort, but they can be less convenient to use with proof automation.  For instance, the [simpl] tactic (which is among the ingredients in [crush]) will sometimes be overzealous in simplifying uses of functions over recursive types.  Consider a call [get l f], where variable [l] has type [filist A (S n)].  The type of [l] would be simplified to an explicit pair type.  In a proof involving many recursive types, this kind of unhelpful \"simplification\" can lead to rapid bloat in the sizes of subgoals.  Even worse, it can prevent syntactic pattern-matching, like in cases where [filist] is expected but a pair type is found in the \"simplified\" version.  The same problem applies to applications of recursive functions to values in recursive types: the recursive function call may \"simplify\" when the top-level structure of the type index but not the recursive value is known, because such functions are generally defined by recursion on the index, not the value.\n\n   Another disadvantage of recursive types is that they only apply to type families whose indices determine their \"skeletons.\"  This is not true for all data structures; a good counterexample comes from the richly typed programming language syntax types we have used several times so far.  The fact that a piece of syntax has type [Nat] tells us nothing about the tree structure of that syntax.\n\n   Finally, Coq type inference can be more helpful in constructing values in inductive types.  Application of a particular constructor of that type tells Coq what to expect from the arguments, while, for instance, forming a generic pair does not make clear an intention to interpret the value as belonging to a particular recursive type.  This downside can be mitigated to an extent by writing \"constructor\" functions for a recursive type, mirroring the definition of the corresponding inductive type.\n\n   Reflexive encodings of data types are seen relatively rarely.  As our examples demonstrated, manipulating index values manually can lead to hard-to-read code.  A normal inductive type is generally easier to work with, once someone has gone through the trouble of implementing an induction principle manually with the techniques we studied in Chapter 3.  For small developments, avoiding that kind of coding can justify the use of reflexive data structures.  There are also some useful instances of %\\index{co-inductive types}%co-inductive definitions with nested data structures (e.g., lists of values in the co-inductive type) that can only be deconstructed effectively with reflexive encoding of the nested structures. *)\n", "meta": {"author": "jcnm", "repo": "cpdt", "sha": "f490857c85e92be67a66e0523b31b951a173036c", "save_path": "github-repos/coq/jcnm-cpdt", "path": "github-repos/coq/jcnm-cpdt/cpdt-f490857c85e92be67a66e0523b31b951a173036c/src/DataStruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7438017768721024}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq               *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later              *)\nFrom mathcomp Require Import all_ssreflect.\nRequire Import Reals Lra.\nRequire Import ssrR Reals_ext Ranalysis_ext logb.\n\n(******************************************************************************)\n(*                    The natural entropy function                            *)\n(*                                                                            *)\n(* Definitions:                                                               *)\n(*   H2ln p == the binary entropy function except that we replace the         *)\n(*             logarithm in base 2 by its natural version                     *)\n(*   H2 p == the binary entropy function                                      *)\n(*                                                                            *)\n(* Lemmas:                                                                    *)\n(*   H2ln_max == H2ln is upper bounded by ln 2                                *)\n(*   H2_max   == the binary entropy function is bounded by 1                  *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope R_scope.\n\nDefinition H2ln := fun p => - p * ln p - (1 - p) * ln (1 - p).\n\nLemma derivable_pt_ln_Rminus x : x < 1 -> derivable_pt ln (1 - x).\nProof.\nmove=> Hx.\nexists (/ (1 - x)).\napply derivable_pt_lim_ln, subR_gt0.\nassumption.\nDefined.\n\nLemma pderivable_H2ln : pderivable H2ln (fun x => 0 < x <= 1/2).\nProof.\nmove=> x /= [Hx0 Hx1].\napply derivable_pt_minus.\napply derivable_pt_mult.\napply derivable_pt_Ropp.\napply derivable_pt_ln.\nassumption.\napply derivable_pt_mult.\napply derivable_pt_Rminus.\napply derivable_pt_comp.\napply derivable_pt_Rminus.\napply derivable_pt_ln_Rminus.\nlra.\nDefined.\n\n(* NB: on peut pas utiliser derivable_pt_Ropp2? *)\nLemma pderivable_Ropp_H2ln : pderivable (fun x => - H2ln x) (fun x => 1/2 <= x < 1).\nProof.\nrewrite /H2ln /pderivable => x [Hx0 Hx1].\napply derivable_pt_comp.\napply derivable_pt_minus.\napply derivable_pt_mult.\napply derivable_pt_Ropp.\napply derivable_pt_ln.\nlra.\napply derivable_pt_mult.\napply derivable_pt_Rminus.\napply derivable_pt_comp.\napply derivable_pt_Rminus.\napply derivable_pt_ln_Rminus.\nassumption.\napply derivable_pt_Ropp.\nDefined.\n\nLemma increasing_on_0_to_half : forall x y,\n  0 < x <= 1/2 -> 0 < y <= 1/2 -> x <= y -> H2ln x <= H2ln y.\nProof.\napply pderive_increasing_open_closed with (pr := pderivable_H2ln); first lra.\nmove=> t [Ht1 Ht2].\nrewrite /H2ln /pderivable_H2ln derive_pt_minus 2!derive_pt_mult /=.\ndestruct (Rlt_le_dec 0 t) => /=; last by exfalso; lra.\nrewrite derive_pt_comp /= mulRA.\napply (@leR_trans (- ln t + ln (1 - t))); last first.\n  apply Req_le; field.\n  by split=> ?; lra.\nrewrite -ln_Rinv // -ln_mult; last 2 first.\n  exact/invR_gt0.\n  lra.\nrewrite -ln_1.\napply ln_increasing_le; first lra.\napply (@leR_pmul2l t) => //.\nby rewrite mulRA mulRV ?gtR_eqF // mulR1 mul1R; lra.\nQed.\n\nLemma decreasing_on_half_to_1 (x y : R) :\n  1/2 <= x < 1 -> 1/2 <= y < 1 -> x <= y -> H2ln y <= H2ln x.\nProof.\nmove=> Hx Hy xy.\nrewrite -[X in _ <= X]oppRK leR_oppr.\nmove: x y Hx Hy xy.\napply pderive_increasing_closed_open with (pr := pderivable_Ropp_H2ln); first lra.\nmove=> t [Ht1 Ht2].\nrewrite /H2ln /pderivable_Ropp_H2ln derive_pt_comp derive_pt_minus 2!derive_pt_mult /=.\ndestruct (Rlt_le_dec 0 t) => /=; last first.\n  by exfalso; lra.\nrewrite derive_pt_comp /= mulRA.\napply (@leR_trans (ln t - ln (1 - t))); last first.\n  apply Req_le; field.\n  by split => ?; lra.\nsuff : ln ( 1 - t) <= ln t by move=> ?; lra.\nby apply ln_increasing_le; lra.\nQed.\n\nLemma H2ln_max (q : R) : 0 < q < 1 -> - q * ln q - (1 - q) * ln (1 - q) <= ln 2.\nProof.\nmove=> [Hq0 Hq1].\napply (@leR_trans (H2ln (1/2))); last first.\n  apply Req_le.\n  rewrite /H2ln (_ : 1 - 1/2 = 1/2); last by field.\n  rewrite -mulRBl (_ : - _ - _ = - 1); last by field.\n  rewrite div1R ln_Rinv; [by field | lra].\nrewrite -/(H2ln q).\ncase: (Rlt_le_dec q (1/2)) => [H1|].\n- by apply increasing_on_0_to_half => //; lra.\n- case/Rle_lt_or_eq_dec => [H1|<-]; last exact: leRR.\n  by apply decreasing_on_half_to_1 => //; lra.\nQed.\n\nDefinition H2 p := - (p * log p) + - ((1 - p) * log (1 - p)).\n\nLemma bin_ent_0eq0 : H2 0 = 0.\nProof.\nrewrite /H2 /log.\nby rewrite !(Log_1, mulR0, mul0R, oppR0, mul1R, mulR1, add0R, addR0, subR0).\nQed.\n\nLemma bin_ent_1eq0 : H2 1 = 0.\nProof.\nrewrite /H2 /log.\nby rewrite !(Log_1, mulR0, mul0R, oppR0, mul1R, mulR1,\n                       add0R, addR0, subR0, subRR).\nQed.\n\nLemma H2_max : forall p, 0 < p < 1 -> H2 p <= 1.\nProof.\nmove=> p [Hp0 Hp1].\nrewrite /H2.\napply (@leR_pmul2l (ln 2)) => //.\nrewrite mulR1 mulRDr /log -!mulNR !(mulRC (ln 2)) -!mulRA.\nrewrite (mulVR _ ln2_neq0) !mulR1 (mulNR (1 - p)); exact/H2ln_max.\nQed.\n\nLemma H2_max' (x : R): 0 <= x <= 1 -> H2 x <= 1.\nProof.\nmove=> [x_0 x_1].\ncase: x_0 => [?|<-]; last by rewrite bin_ent_0eq0.\ncase: x_1 => [?|->]; last by rewrite bin_ent_1eq0.\nexact: H2_max.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/lib/binary_entropy_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7437938491338336}}
{"text": "Require Import Logic.Rel.R.\nRequire Import Logic.Rel.Include.\nRequire Import Logic.Rel.Properties.\n\nRequire Import Logic.Lam.Syntax.\nRequire Import Logic.Lam.Functor.\n\nDefinition congruent (v:Type) (r:Rel (T v)) : Prop := \n    (forall (s1 s2 t1 t2:T v), r s1 t1 -> r s2 t2 -> r (App s1 s2) (App t1 t2)) /\\\n    (forall (x:v) (s1 t1:T v), r s1 t1 -> r (Lam x s1) (Lam x t1)).\n\nArguments congruent {v} _.\n\nDefinition congruence (v:Type) (r:Rel (T v)) : Prop :=\n   equivalence r /\\ congruent r. \n\nArguments congruence {v} _.\n\n\nLemma fmap_congruence : forall (v w:Type) (f:v -> w) (r:Rel (T w)),\n    congruence r -> congruence (fun (s t:T v) => r (fmap f s) (fmap f t)).\nProof.\n    intros v w f r [H1 [HApp HLam]]. \n    unfold equivalence in H1. destruct H1 as [Refl [Symm Tran]].\n    unfold reflexive in Refl.\n    unfold symmetric in Symm.\n    unfold transitive in Tran.\n    split.\n    - split.\n        + unfold reflexive. intros x. apply Refl.\n        + split.\n            { unfold symmetric. intros x y. apply Symm. }\n            { unfold transitive.  intros x y z. apply Tran. }\n    - split.\n        + intros s1 s2 t1 t2. apply HApp.\n        + intros x s1 t1. apply HLam.\nQed. \n    \n(* Congruence relation generated by a given relation on T v.                    *)\nInductive Cong (v:Type) (r:Rel (T v)) : Rel (T v) :=\n| CongBase  : forall (p q:T v), r p q -> Cong v r p q\n| CongRefl  : forall (p:T v), Cong v r p p\n| CongSym   : forall (p q:T v), Cong v r p q -> Cong v r q p\n| CongTrans : forall (p q t:T v), Cong v r p q -> Cong v r q t -> Cong v r p t\n| CongApp   : forall (p1 p2 q1 q2:T v), \n    Cong v r p1 q1 -> \n    Cong v r p2 q2 ->\n    Cong v r (App p1 p2) (App q1 q2)\n| CongLam   : forall (x:v) (p1 q1:T v),\n    Cong v r p1 q1 ->\n    Cong v r (Lam x p1 )(Lam x q1)\n.\n\nArguments Cong      {v}.\nArguments CongBase  {v}.\nArguments CongRefl  {v}.\nArguments CongSym   {v}.\nArguments CongTrans {v}.\nArguments CongApp   {v}.\nArguments CongLam   {v}.\n\n(* The congruence relation generated by a given relation is reflexive.          *)\nLemma Cong_reflexive : forall (v:Type) (r:Rel (T v)), reflexive (Cong r).\nProof.\n    intros v r. unfold reflexive. intros x. apply CongRefl.\nQed.\n\n(* The congruence relation generated by a given relation is symmetric.          *)\nLemma Cong_symmetric : forall (v:Type) (r:Rel (T v)), symmetric (Cong r).\nProof.\n    intros v r. unfold symmetric. intros x y. apply CongSym.\nQed.\n\n(* The congruence relation generated by a given relation is transitive.         *)\nLemma Cong_transitive : forall (v:Type) (r:Rel (T v)), transitive (Cong r).\nProof.\n    intros v r. unfold transitive. intros x y. apply CongTrans.\nQed.\n\n(* The congruence relation generated by a given relation is an equivalence.     *)\nLemma Cong_equivalence : forall (v:Type) (r:Rel (T v)), equivalence (Cong r).\nProof.\n    intros v r. unfold equivalence. split.\n    - apply Cong_reflexive.\n    - split.\n        + apply Cong_symmetric.\n        + apply Cong_transitive.\nQed.\n\n(* The congruence relation generated by a given relation is congruent.         *)\nLemma Cong_congruent : forall (v:Type) (r:Rel (T v)), congruent (Cong r).\nProof.\n    intros v r. unfold congruent. split.\n    - apply CongApp.\n    - apply CongLam.\nQed.\n\n(* The congruence relation generated by a given relation is a congruence.       *)\nLemma Cong_congruence : forall (v:Type) (r:Rel (T v)), congruence (Cong r).\nProof.\n    intros v r. unfold congruence. split.\n    - apply Cong_equivalence.\n    - apply Cong_congruent.\nQed.\n\n(* The congruence relation generated by a given relation contains it.           *)\nLemma Cong_super : forall (v:Type) (r:Rel (T v)), r <= Cong r.\nProof.\n    intros v r. apply incl_charac. intros x y. apply CongBase.\nQed.\n\n(* The congruence relation generated by a given relation is the smallest.       *)\nLemma Cong_smallest : forall (v:Type) (r s:Rel (T v)), \n    congruence s -> r <= s -> Cong r <= s.\nProof.\n    intros v r s [[H1 [H2 H3]] [H4 H5]] H6. apply incl_charac. intros x y H7.\n    induction H7 as [p q H7|p|p q H7 IH|p q t H7 H8 H9 IH\n                    |p1 p2 q1 q2 H7 IH1 H8 IH2|x p1 q1 H7 IH].\n    - apply incl_charac_to with r; assumption.\n    - apply H1.\n    - apply H2. assumption.\n    - apply H3 with q; assumption.\n    - apply H4; assumption.\n    - apply H5. assumption.\nQed.\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/Logic/Lam/Congruence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7437938429359042}}
{"text": "Inductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nFixpoint app (l : lst) (m : lst) : lst :=\nmatch l with\n  | Nil => m\n  | Cons a l1 => Cons a (app l1 m)\nend.\n\nFixpoint rev (l : lst) : lst :=\n  match l with\n  | Nil => Nil\n  | Cons a l1 => app (rev l1) (Cons a Nil)\n  end. \n\nLemma app_nil : forall x : lst, app x Nil = x.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma app_assoc : forall x y z : lst, app x (app y z) = app (app x y) z.\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nTheorem rev_append: forall x y : lst,\n  (eq (rev (app x y)) (app (rev y) (rev x))).\nProof.\n  intros.\n  induction x.\n  - simpl. rewrite app_nil. reflexivity.\n  - simpl. rewrite IHx. rewrite app_assoc. reflexivity.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/list_rev_append.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8221891370573386, "lm_q1q2_score": 0.7437938406794699}}
{"text": "Require Import Recdef.\n\nInductive Z : Type :=\n| Zero : Z\n| MinusOne : Z\n| Next : Z -> Z.\n\nFunction abs (k : Z) : Z :=\nmatch k with\n| Zero => Zero\n| MinusOne => Next Zero\n| Next k' => Next (abs k')\nend.\n\nFunction succ (k : Z) : Z :=\nmatch k with\n| Zero => Next Zero\n| MinusOne => Zero\n| Next Zero => Next (Next Zero)\n| Next MinusOne => MinusOne\n| Next k' => Next (succ k')\nend.\n\nFunction pred (k : Z) : Z :=\nmatch k with\n| Zero => MinusOne\n| MinusOne => Next MinusOne\n| Next Zero => Zero\n| Next MinusOne => Next (Next MinusOne)\n| Next k' => Next (pred k')\nend.\n\nFunction neg' (k : Z) : Z :=\nmatch k with\n| Zero => MinusOne\n| MinusOne => Zero\n| Next k' => Next (neg' k')\nend.\n\nDefinition neg (k : Z) : Z :=\n  succ (neg' k).\n\nFunction isNegative (k : Z) : bool :=\nmatch k with\n| Zero     => false\n| MinusOne => true\n| Next k'  => isNegative k'\nend.\n\nDefinition isZero (k : Z) : bool :=\nmatch k with\n| Zero => true\n| _    => false\nend.\n\nFunction add (k1 k2 : Z) : Z :=\nmatch k1 with\n| Zero => k2\n| MinusOne => pred k2\n| Next k1' => if isNegative k1' then pred (add k1' k2) else succ (add k1' k2)\nend.\n\nFunction abs' (k : Z) : nat :=\nmatch k with\n| Zero     => 0\n| MinusOne => 1\n| Next k'  => S (abs' k')\nend.\n\nFunction add' (k1 k2 : Z) : Z :=\n  if isNegative k1 then iter _ (abs' k1) pred k2 else iter _ (abs' k1) succ k2.\n\nLemma abs_abs :\n  forall k : Z, abs (abs k) = abs k.\nProof.\n  intros k; functional induction (abs k)\n  ; cbn; rewrite ?IHz; reflexivity.\nQed.\n\nLemma succ_pred :\n  forall k : Z,\n    succ (pred k) = k.\nProof.\n  intros k; functional induction (pred k); cbn.\n  1-4: reflexivity.\n  rewrite IHz; clear IHz.\n  functional induction (pred k'); cbn in *.\n  1-2: contradiction.\n  1-3: reflexivity.\nQed.\n\nLemma pred_succ :\n  forall k : Z,\n    pred (succ k) = k.\nProof.\n  intros k; functional induction (succ k); cbn.\n  1-4: reflexivity.\n  rewrite IHz; clear IHz.\n  functional induction (succ k'); cbn in *.\n  1-2: contradiction.\n  1-3: reflexivity.\nQed.\n\nLemma neg'_succ :\n  forall k : Z, neg' (succ k) = pred (neg' k).\nProof.\n  intros k; functional induction (succ k); cbn.\n  1-4: reflexivity.\n  rewrite IHz; clear IHz.\n  functional induction (neg' k'); cbn.\n  1-2: contradiction.\n  reflexivity.\nQed.\n\nLemma pred_neg' :\n  forall k : Z, pred (neg' k) = neg' (succ k).\nProof.\n  intros k; rewrite neg'_succ; reflexivity.\nQed.\n\nLemma neg_succ :\n  forall k : Z, neg (succ k) = pred (neg k).\nProof.\n  intros k; unfold neg.\n  rewrite neg'_succ, succ_pred, pred_succ.\n  reflexivity.\nQed.\n\nLemma pred_neg :\n  forall k : Z, pred (neg k) = neg (succ k).\nProof.\n  intros k; rewrite neg_succ; reflexivity.\nQed.\n\nLemma neg'_pred :\n  forall k : Z, neg' (pred k) = succ (neg' k).\nProof.\n  intros k; functional induction (pred k); cbn.\n  1-4: reflexivity.\n  rewrite IHz; clear IHz.\n  functional induction (neg' k'); cbn.\n  1-2: contradiction.\n  reflexivity.\nQed.\n\nLemma succ_neg' :\n  forall k : Z, succ (neg' k) = neg' (pred k).\nProof.\n  intros k; rewrite neg'_pred; reflexivity.\nQed.\n\nLemma neg_pred :\n  forall k : Z, neg (pred k) = succ (neg k).\nProof.\n  intros k; unfold neg.\n  rewrite neg'_pred.\n  reflexivity.\nQed.\n\nLemma neg'_neg' :\n  forall k : Z, neg' (neg' k) = k.\nProof.\n  intros k; functional induction (neg' k)\n  ; cbn; rewrite ?IHz; reflexivity.\nQed.\n\nLemma neg_neg :\n  forall k : Z, neg (neg k) = k.\nProof.\n  intros k; unfold neg.\n  rewrite neg'_succ, succ_pred, neg'_neg'.\n  reflexivity.\nQed.\n\nLemma abs_neg :\n  forall k : Z,\n    abs (neg k) = abs k.\nProof.\n  unfold neg; intros k.\n  functional induction (neg' k); cbn.\n  1-2: reflexivity.\n  destruct (neg' k'); cbn in *; rewrite IHz; reflexivity.\nQed.\n\nLemma isNegative_abs :\n  forall k : Z,\n    isNegative (abs k) = false.\nProof.\n  intros k; functional induction (abs k)\n  ; cbn; rewrite ?IHz; reflexivity.\nQed.\n\nLemma isNegative_neg' :\n  forall k : Z,\n    isNegative (neg' k) = negb (isNegative k).\nProof.\n  intros k; functional induction (neg' k); cbn; auto.\nQed.\n\nLemma isNegative_pred :\n  forall k : Z,\n    isNegative (pred k) = orb (isNegative k) (isZero k).\nProof.\n  intros k; functional induction (pred k); cbn.\n  1-4: reflexivity.\n  destruct k'; cbn in *; try contradiction.\n  assumption.\nQed.\n\nLemma isNegative_succ :\n  forall k : Z,\n    isNegative (succ k) =\n    match k with\n    | MinusOne => false\n    | _ => isNegative k\n    end.\nProof.\n  intros k; functional induction (pred k); cbn.\n  1-4: reflexivity.\n  destruct k'; cbn in *; try contradiction.\n  assumption.\nQed.\n\nLemma abs_spec :\n  forall k : Z,\n    abs k = if isNegative k then neg k else k.\nProof.\n  intros k; functional induction (isNegative k); cbn.\n  1-2: reflexivity.\n  rewrite IHb.\n  destruct (isNegative k') eqn: Heq; [| reflexivity].\n  unfold neg; destruct (neg' k') eqn: Hneg.\n  all: try reflexivity.\n  functional inversion Hneg; subst.\n  inversion Heq.\nQed.\n\nLemma Next_spec :\n  forall k : Z,\n    Next k = if isNegative k then pred k else succ k.\nProof.\n  intros k; functional induction (isNegative k); cbn.\n  1-2: reflexivity.\n  rewrite IHb.\n  destruct (isNegative k') eqn: Hneg.\n  - functional inversion Hneg; cbn in *; reflexivity.\n  - functional inversion Hneg; cbn in *; reflexivity.\nQed.\n\nLemma add_Zero_r :\n  forall k : Z,\n    add k Zero = k.\nProof.\n  induction k as [| | k']; cbn.\n  1-2: reflexivity.\n  rewrite IHk', Next_spec.\n  reflexivity.\nQed.\n\nLemma add_MinusOne_r :\n  forall k : Z,\n    add k MinusOne = pred k.\nProof.\n  intros k; functional induction (pred k); cbn.\n  1-4: reflexivity.\n  destruct k'; cbn in *; try contradiction.\n  destruct (isNegative k') eqn: Hneg.\n  - functional inversion Hneg; subst.\n    + cbn. reflexivity.\n    + admit.\nAdmitted.\n\nLemma add_Next_r :\n  forall k1 k2 : Z,\n    add k1 (Next k2) = if isNegative k2 then pred (add k1 k2) else succ (add k1 k2).\nProof.\n  intros k1 k2.\n  rewrite Next_spec.\n  destruct (isNegative k2).\n  -\nAdmitted.\n\nLemma add_comm :\n  forall k1 k2 : Z,\n    add k1 k2 = add k2 k1.\nProof.\n  intros k1 k2; functional induction (add k1 k2); cbn.\n  - rewrite add_Zero_r; reflexivity.\n  - rewrite add_MinusOne_r; reflexivity.\n  - rewrite add_Next_r, e0, IHz; reflexivity.\n  - rewrite add_Next_r, e0, IHz; reflexivity.\nQed.\n\nLemma add_pred_l :\n  forall k1 k2 : Z,\n    add (pred k1) k2 = pred (add k1 k2).\nProof.\n  intros k1 k2; functional induction (pred k1); cbn.\n  1-2, 4: reflexivity.\n  - rewrite pred_succ; reflexivity.\n  - rewrite isNegative_pred, IHz, succ_pred.\n    destruct k'; try contradiction; cbn [isZero]; rewrite Bool.orb_false_r.\n    destruct (isNegative (Next k')).\n    + reflexivity.\n    + rewrite pred_succ. reflexivity.\nQed.\n\nLemma add_pred_r :\n  forall k1 k2 : Z,\n    add k1 (pred k2) = pred (add k1 k2).\nProof.\n  intros k1 k2.\n  rewrite add_comm, add_pred_l, add_comm.\n  reflexivity.\nQed.\n\nLemma add_succ_l :\n  forall k1 k2 : Z,\n    add (succ k1) k2 = succ (add k1 k2).\nProof.\n  intros k1 k2.\n  assert (H : add (pred (succ k1)) k2 = pred (succ (add k1 k2)))\n      by (rewrite !pred_succ; reflexivity).\n  apply (f_equal succ) in H.\n  rewrite add_pred_l, !succ_pred in H.\n  assumption.\nQed.\n\nLemma add_succ_r :\n  forall k1 k2 : Z,\n    add k1 (succ k2) = succ (add k1 k2).\nProof.\n  intros k1 k2.\n  rewrite add_comm, add_succ_l, add_comm.\n  reflexivity.\nQed.\n\nLemma add_assoc :\n  forall k1 k2 k3 : Z,\n    add (add k1 k2) k3 = add k1 (add k2 k3).\nProof.\n  intros k1 k2 k3.\n  functional induction (add k1 k2); cbn.\n  - reflexivity.\n  - rewrite add_pred_l; reflexivity.\n  - rewrite add_pred_l, e0, IHz; reflexivity.\n  - rewrite add_succ_l, e0, IHz; reflexivity.\nQed.\n\nLemma neg'_add :\n  forall k1 k2 : Z,\n    neg' (add k1 k2) = succ (add (neg' k1) (neg' k2)).\nProof.\n  intros k1 k2.\n  functional induction (add k1 k2); cbn.\n  - rewrite succ_pred. reflexivity.\n  - rewrite neg'_pred. reflexivity.\n  - rewrite neg'_pred, IHz, isNegative_neg', e0; cbn. reflexivity.\n  - rewrite neg'_succ, IHz, isNegative_neg', e0; cbn.\n    rewrite pred_succ, succ_pred. reflexivity.\nQed.\n\nLemma neg_add :\n  forall k1 k2 : Z,\n    neg (add k1 k2) = add (neg k1) (neg k2).\nProof.\n  intros k1 k2. unfold neg.\n  rewrite add_succ_l, add_succ_r, neg'_add.\n  reflexivity.\nQed.\n\nLemma add'_Zero_r :\n  forall k : Z,\n    add' k Zero = k.\nProof.\n  unfold add'; intros k.\n  functional induction (isNegative k); cbn.\n  1-2: reflexivity.\n  rewrite Next_spec.\n  destruct (isNegative k'); rewrite IHb; reflexivity.\nQed.", "meta": {"author": "wkolowski", "repo": "Typonomikon", "sha": "ff2166a3391f0fd77ba8de1b948dfe954fe9b997", "save_path": "github-repos/coq/wkolowski-Typonomikon", "path": "github-repos/coq/wkolowski-Typonomikon/Typonomikon-ff2166a3391f0fd77ba8de1b948dfe954fe9b997/code/Num/WeirdUnaryZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7437938364522877}}
{"text": "(* * Tarski Semantics *)\n\nRequire Import Undecidability.FOL.Syntax.Facts.\nRequire Export Undecidability.FOL.Semantics.Tarski.FullCore.\nFrom Undecidability Require Import Shared.ListAutomation.\nImport ListAutomationNotations.\nRequire Import Vector Lia.\n\n\nLocal Set Implicit Arguments.\nLocal Unset Strict Implicit.\n\n\nLocal Notation vec := Vector.t.\n\n\n(* Tarski Semantics ***)\n\n\nSection Tarski.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  (* Semantic notions *)\n  \n  Section Substs.\n    \n    Variable D : Type.\n    Variable I : interp D.\n        \n    Lemma eval_ext rho xi t :\n      (forall x, rho x = xi x) -> eval rho t = eval xi t.\n    Proof.\n      intros H. induction t; cbn.\n      - now apply H.\n      - f_equal. apply map_ext_in. now apply IH.\n    Qed.\n\n    Lemma eval_comp rho xi t :\n      eval rho (subst_term xi t) = eval (xi >> eval rho) t.\n    Proof.\n      induction t; cbn.\n      - reflexivity.\n      - f_equal. rewrite map_map. apply map_ext_in, IH.\n    Qed.\n    Lemma eval_up ρ s t :\n      eval (s .: ρ) t`[↑] = eval ρ t.\n    Proof.\n      rewrite eval_comp. apply eval_ext. reflexivity.\n    Qed.\n\n    Lemma sat_ext {ff : falsity_flag} rho xi phi :\n      (forall x, rho x = xi x) -> rho ⊨ phi <-> xi ⊨ phi.\n    Proof.\n      induction phi  as [ | b P v | | ] in rho, xi |- *; cbn; intros H.\n      - reflexivity.\n      - erewrite map_ext; try reflexivity. intros t. now apply eval_ext.\n      - specialize (IHphi1 rho xi). specialize (IHphi2 rho xi). destruct b0; intuition.\n      - destruct q.\n        + split; intros H' d; eapply IHphi; try apply (H' d). 1,2: intros []; cbn; intuition.\n        + split; intros [d H']; exists d; eapply IHphi; try apply H'. 1,2: intros []; cbn; intuition.\n    Qed.\n\n    Lemma sat_ext' {ff : falsity_flag} rho xi phi :\n      (forall x, rho x = xi x) -> rho ⊨ phi -> xi ⊨ phi.\n    Proof.\n      intros Hext H. rewrite sat_ext. exact H.\n      intros x. now rewrite (Hext x).\n    Qed.\n\n    Lemma sat_comp {ff : falsity_flag} rho xi phi :\n      rho ⊨ (subst_form xi phi) <-> (xi >> eval rho) ⊨ phi.\n    Proof.\n      induction phi as [ | b P v | | ] in rho, xi |- *; cbn.\n      - reflexivity.\n      - erewrite map_map, map_ext; try reflexivity. intros t. apply eval_comp.\n      - specialize (IHphi1 rho xi). specialize (IHphi2 rho xi). destruct b0; intuition.\n      - destruct q.\n        + setoid_rewrite IHphi. split; intros H d; eapply sat_ext. 2, 4: apply (H d).\n          all: intros []; cbn; trivial; now setoid_rewrite eval_comp.\n        + setoid_rewrite IHphi. split; intros [d H]; exists d; eapply sat_ext. 2, 4: apply H.\n          all: intros []; cbn; trivial; now setoid_rewrite eval_comp.\n    Qed.\n\n    Lemma sat_subst {ff : falsity_flag} rho sigma phi :\n      (forall x, eval rho (sigma x) = rho x) -> rho ⊨ phi <-> rho ⊨ (subst_form sigma phi).\n    Proof.\n      intros H. rewrite sat_comp. apply sat_ext. intros x. now rewrite <- H.\n    Qed.\n\n    Lemma sat_single {ff : falsity_flag} (rho : nat -> D) (Phi : form) (t : term) :\n      (eval rho t .: rho) ⊨ Phi <-> rho ⊨ subst_form (t..) Phi.\n    Proof.\n      rewrite sat_comp. apply sat_ext. now intros [].\n    Qed.\n\n    Lemma impl_sat {ff : falsity_flag} A rho phi :\n      sat rho (A ==> phi) <-> ((forall psi, psi el A -> sat rho psi) -> sat rho phi).\n    Proof.\n      induction A; cbn; firstorder congruence.\n    Qed.\n\n    Lemma impl_sat' {ff : falsity_flag} A rho phi :\n      sat rho (A ==> phi) -> ((forall psi, psi el A -> sat rho psi) -> sat rho phi).\n    Proof.\n      eapply impl_sat.\n    Qed.\n\n    Lemma bounded_eval_t n t sigma tau :\n      (forall k, n > k -> sigma k = tau k) -> bounded_t n t -> eval sigma t = eval tau t.\n    Proof.\n      intros H. induction 1; cbn; auto.\n      f_equal. now apply Vector.map_ext_in.\n    Qed.\n    \n    Lemma bound_ext {ff : falsity_flag} N phi rho sigma :\n      bounded N phi -> (forall n, n < N -> rho n = sigma n) -> (rho ⊨ phi <-> sigma ⊨ phi).\n    Proof.\n      induction 1 in sigma, rho |- *; cbn; intros HN; try tauto.\n      - enough (map (eval rho) v = map (eval sigma) v) as E. now setoid_rewrite E.\n        apply Vector.map_ext_in. intros t Ht.\n        eapply bounded_eval_t; try apply HN. now apply H.\n      - destruct binop; now rewrite (IHbounded1 rho sigma), (IHbounded2 rho sigma).\n      - destruct quantop.\n        + split; intros Hd d; eapply IHbounded.\n          all : try apply (Hd d); intros [] Hk; cbn; auto.\n          symmetry. all: apply HN; lia.\n        + split; intros [d Hd]; exists d; eapply IHbounded.\n          all : try apply Hd; intros [] Hk; cbn; auto.\n          symmetry. all: apply HN; lia.\n    Qed. \n\n    Corollary sat_closed {ff : falsity_flag} rho sigma phi :\n      bounded 0 phi -> rho ⊨ phi <-> sigma ⊨ phi.\n    Proof.\n      intros H. eapply bound_ext. apply H. lia.\n    Qed.\n\n    Lemma subst_exist_sat {ff : falsity_flag} rho phi N :\n      rho ⊨ phi -> bounded N phi -> forall rho, rho ⊨ (exist_times N phi).  \n    Proof.\n      induction N in phi, rho |-*; intros.\n      - cbn. eapply sat_closed; eassumption.\n      - cbn -[sat]. rewrite iter_switch. apply (IHN (S >> rho)).\n        exists (rho 0). eapply sat_ext. 2: apply H.\n        now intros [].\n        now apply bounded_S_quant.\n    Qed.\n\n    Fact subst_exist_sat2 {ff : falsity_flag} N :\n      forall rho phi, rho ⊨ (exist_times N phi) -> (exists sigma, sigma ⊨ phi).\n    Proof.\n      induction N.\n      - eauto.\n      - intros rho phi [? H]. now apply IHN in H.\n    Qed.\n\n    Lemma exists_close_form {ff : falsity_flag} N phi :\n      bounded 0 (exist_times N phi) <-> bounded N phi.\n    Proof.\n      induction N in phi |- *.\n      - reflexivity.\n      - cbn. rewrite iter_switch.\n        change (iter _ _ _) with (exist_times N (∃ phi)).\n        setoid_rewrite IHN. symmetry.\n        now apply bounded_S_quant.\n    Qed.\n    \n\n  End Substs.\n\nEnd Tarski.\n\n\n\n(* Trivial Model *)\n\nSection TM.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Instance TM : interp unit :=\n    {| i_func := fun _ _ => tt; i_atom := fun _ _ => True; |}.\n\n  Fact TM_sat (rho : nat -> unit) (phi : form falsity_off) :\n    rho ⊨ phi.\n  Proof.\n    revert rho. remember falsity_off as ff. induction phi; cbn; trivial.\n    - discriminate.\n    - destruct b0; auto.\n    - destruct q; firstorder. exact tt.\n  Qed.\n\n  Fact TM_sat_decidable {ff} (rho : nat -> unit) (phi : form ff) :\n    rho ⊨ phi \\/ ~(rho ⊨ phi).\n  Proof.\n    revert rho. induction phi as [|? ? ?|ff [| |] phi IHphi psi IHpsi|ff [|] phi IHphi]; cbn; intros rho; eauto; try tauto.\n    - destruct (IHphi rho), (IHpsi rho); tauto.\n    - destruct (IHphi rho), (IHpsi rho); tauto.\n    - destruct (IHphi rho), (IHpsi rho); tauto.\n    - destruct (IHphi (tt .: rho)).\n      + left; now intros [].\n      + right; intros Hcc. apply H, Hcc.\n    - destruct (IHphi (tt .: rho)).\n      + left; now exists tt.\n      + right; now intros [[] Hx].\n  Qed.\n\nEnd TM.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FOL/Semantics/Tarski/FullFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7437938329393231}}
{"text": "(* Exercise 109 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* de Morgans' disjunction law variant *)\n\nTheorem exercise_109 : ~(~A \\/ ~B) -> (A /\\ B).\nProof.\nimp_i a1.\ncon_i.\nneg_e' (~A \\/ ~B) a2.\nhyp a1.\ndis_i1.\nhyp a2.\nneg_e' (~A \\/ ~B) a2.\nhyp a1.\ndis_i2.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop109.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897426182322, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7437228196759781}}
{"text": "(* Reversing lists, abstractly. *)\n\nRequire Import List.\nImport ListNotations.\n\nSection rev_abstract.\n\n  Variables\n    (T: Type)\n    (f: list T -> list T).\n\n  Lemma app_tail_nil:\n    forall (xs ys: list T), xs = xs ++ ys -> ys = [].\n  Proof.\n\n  Qed.\n\n  Hypothesis app_rev: forall xs ys, f (xs ++ ys) = f ys ++ f xs.\n\n  (* Hint: `assert` something which allows you to\n     use a specialisation of app_rev, and then\n     use app_tail_nil. *)\n  Lemma nil_id: f [] = [].\n  Proof.\n\n  Qed.\n\n  Hypothesis single_id: forall x, f [x] = [x].\n\n  Lemma rev_spec_complete:\n    forall xs, f xs = rev xs.\n  Proof.\n\n  Qed.\n\nEnd rev_abstract.\n", "meta": {"author": "mbrcknl", "repo": "coq-fight-2016", "sha": "8925a35a86ba1d1cdd4dc69c91ad683db212bfd8", "save_path": "github-repos/coq/mbrcknl-coq-fight-2016", "path": "github-repos/coq/mbrcknl-coq-fight-2016/coq-fight-2016-8925a35a86ba1d1cdd4dc69c91ad683db212bfd8/submissions/L03-reverse-abstract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7437156328433059}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega Permutation.\n\nRequire Import list_focus utils_tac.\n\nSet Implicit Arguments.\n\nCreate HintDb length_db.\n\nTactic Notation \"rew\" \"length\" := autorewrite with length_db.\nTactic Notation \"rew\" \"length\" \"in\" hyp(H) := autorewrite with length_db in H.\n\nInfix \"~p\" := (@Permutation _) (at level 70).\n\nFact Permutation_map_inv X Y (f : X -> Y) l m : map f l ~p m -> exists l', m = map f l' /\\ l ~p l'.\nProof.\n  assert (forall m1 m2, m1 ~p m2 -> forall l1, m1 = map f l1 -> exists l2, m2 = map f l2 /\\ l1 ~p l2) as L.\n  + induction 1 as [ | y m1 m2 H1 IH1 | y1 y2 m1 | m1 m2 m3 H1 IH1 H2 IH2 ].\n    * intros [ | ]; exists nil; auto; discriminate.\n    * intros [ | x l1 ]; simpl; try discriminate.\n      intros H2; injection H2; clear H2; intros H2 H3; subst y.\n      destruct (IH1 _ H2) as (l2 & ? & ?).\n      exists (x::l2); simpl; subst; auto.\n    * intros [ | x2 [ | x1 l1 ] ]; try discriminate; simpl.\n      intros H2; injection H2; clear H2; intros H1 H2 H3; subst.\n      exists (x1::x2::l1); simpl; split; auto; constructor.\n    * intros l1 H3.\n      destruct IH1 with (1 := H3) as (l2 & H4 & H5).\n      destruct IH2 with (1 := H4) as (l3 & H6 & H7).\n      exists l3; split; auto.\n      constructor 4 with l2; auto.\n  + intros H1; apply L with (2 := eq_refl); auto.\nQed.\n\nSection length.\n   \n  Variable X : Type.\n\n  Implicit Type l : list X.\n\n  Fact length_nil : length (@nil X) = 0.\n  Proof. auto. Qed.\n\n  Fact length_cons x l : length (x::l) = S (length l).\n  Proof. auto. Qed.\n\nEnd length.\n\nHint Rewrite length_nil length_cons app_length map_length rev_length : length_db.\n\nSection list_an.\n\n  Fixpoint list_an a n :=\n    match n with \n      | 0   => nil\n      | S n => a::list_an (S a) n\n    end.\n\n  Fact list_an_S a n : list_an a (S n) = a::list_an (S a) n.\n  Proof. auto. Qed. \n\n  Fact list_an_plus a n m : list_an a (n+m) = list_an a n ++ list_an (n+a) m.\n  Proof.\n    revert a; induction n; intros a; simpl; auto.\n    rewrite IHn; do 3 f_equal; omega.\n  Qed.\n\n  Fact list_an_length a n : length (list_an a n) = n.\n  Proof.\n    revert a; induction n; intro; simpl; f_equal; auto.\n  Qed.\n  \n  Fact list_an_spec a n m : In m (list_an a n) <-> a <= m < a+n.\n  Proof.\n    revert a; induction n as [ | n IHn ]; simpl; intros a; [ | rewrite IHn ]; omega. \n  Qed.\n\n  Fact map_S_list_an a n : map S (list_an a n) = list_an (S a) n.\n  Proof. revert a; induction n; simpl; intro; f_equal; auto. Qed.\n\n  Fact list_an_app_inv a n l r : list_an a n = l++r -> l = list_an a (length l) /\\ r = list_an (a+length l) (length r).\n  Proof.\n    revert a l r; induction n as [ | n IHn ]; intros a l r; simpl.\n    + destruct l; destruct r; intros; auto; discriminate.\n    + destruct l as [ | x l ]; simpl; intros H1.\n      * split; auto.\n        rewrite <- H1; simpl; rewrite Nat.add_0_r, list_an_length; auto.\n      * injection H1; clear H1; intros H1 H0.\n        apply IHn in H1; destruct H1; split; f_equal; auto.\n        rewrite H1 at 1; f_equal; omega.\n  Qed.\n\nEnd list_an.\n\nHint Rewrite list_an_length : length_db.\n\nSection list_injective.\n\n  Variable X : Type.\n   \n  Definition list_injective (ll : list X) :=  forall l a m b r, ll = l ++ a :: m ++ b :: r -> a <> b.\n  \n  Fact in_list_injective_0 : list_injective nil.\n  Proof. intros [] ? ? ? ? ?; discriminate. Qed.\n  \n  Fact in_list_injective_1 x ll : ~ In x ll -> list_injective ll -> list_injective (x::ll).\n  Proof.\n    intros H1 H2 l a m b r H3.\n    destruct l as [ | u l ].\n    inversion H3; subst.\n    destruct m as [ | v m ].\n    contradict H1; subst; simpl; auto.\n    contradict H1; subst; simpl; right; apply in_or_app; right; left; auto.\n    inversion H3; subst.\n    apply (H2 l _ m _ r); auto.\n  Qed.\n  \n  Fact list_injective_inv x ll : list_injective (x::ll) -> ~ In x ll /\\ list_injective ll.\n  Proof.\n    split.\n    intros H1; apply in_split in H1; destruct H1 as (l & r & ?); subst.\n    apply (H nil x l x r); auto.\n    intros l a m b r ?; apply (H (x::l) a m b r); subst; solve list eq.\n  Qed.\n  \n  Variable P : list X -> Type.\n  \n  Hypothesis (HP0 : P nil).\n  Hypothesis (HP1 : forall x l, ~ In x l -> P l -> P (x::l)).\n  \n  Theorem list_injective_rect l : list_injective l -> P l.\n  Proof.\n    induction l as [ [ | x l ] IHl ] using (measure_rect (@length _)).\n    intro; apply HP0.\n    intros; apply HP1.\n    apply list_injective_inv, H.\n    apply IHl; simpl; auto.\n    apply list_injective_inv with (1 := H).\n  Qed.\n\nEnd list_injective.\n\nFact list_injective_map X Y (f : X -> Y) ll :\n       (forall x y, f x = f y -> x = y) -> list_injective ll -> list_injective (map f ll).\nProof.\n  intros Hf.\n  induction 1 as [ | x l Hl IHl ] using list_injective_rect.\n  apply in_list_injective_0.\n  simpl; apply in_list_injective_1; auto.\n  contradict Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (y & Hl & ?).\n  apply Hf in Hl; subst; auto.\nQed.\n\nSection iter.\n  \n  Variable (X : Type) (f : X -> X).\n\n  Fixpoint iter x n :=\n    match n with\n      | 0   => x\n      | S n => iter (f x) n\n    end.\n\n  Fact iter_plus x a b : iter x (a+b) = iter (iter x a) b.\n  Proof. revert x; induction a; intros x; simpl; auto. Qed.\n\nEnd iter.\n\nFixpoint list_repeat X (x : X) n :=\n  match n with\n    | 0   => nil\n    | S n => x::list_repeat x n\n  end.\n  \nFact list_repeat_plus X x a b : @list_repeat X x (a+b) = list_repeat x a ++ list_repeat x b.\nProof. induction a; simpl; f_equal; auto. Qed.\n  \nFact list_repeat_length X x n : length (@list_repeat X x n) = n.\nProof. induction n; simpl; f_equal; auto. Qed.\n\nFact In_list_repeat X (x y : X) n : In y (list_repeat x n) -> x = y /\\ 0 < n.\nProof.\n  induction n; simpl; intros [].\n  split; auto; omega.\n  split; try omega; apply IHn; auto.\nQed.\n\nFact map_list_repeat X Y f x n : @map X Y f (list_repeat x n) = list_repeat (f x) n.\nProof. induction n; simpl; f_equal; auto. Qed.\n\nFact map_cst_repeat X Y (y : Y) ll : map (fun _ : X => y) ll = list_repeat y (length ll).\nProof. induction ll; simpl; f_equal; auto. Qed.\n  \nFact map_cst_snoc X Y (y : Y) ll mm : y :: map (fun _ : X => y) ll++mm = map (fun _ => y) ll ++ y::mm.\nProof. induction ll; simpl; f_equal; auto. Qed.\n\nFact map_cst_rev  X Y (y : Y) ll : map (fun _ : X => y) (rev ll) = map (fun _ => y) ll.\nProof. do 2 rewrite map_cst_repeat; rewrite rev_length; auto. Qed.\n\nFact In_perm X (x : X) l : In x l -> exists m, x::m ~p l.\nProof.\n  intros H; apply in_split in H.\n  destruct H as (m & k & ?); subst.\n  exists (m++k).\n  apply Permutation_cons_app; auto.\nQed.\n\nFact list_app_eq_inv X (l1 l2 r1 r2 : list X) :\n       l1++r1 = l2++r2 -> { m | l1++m = l2 /\\ r1 = m++r2 } \n                        + { m | l2++m = l1 /\\ r2 = m++r1 }.\nProof.\n  revert l2 r1 r2; induction l1 as [ | x l1 IH ].\n  intros; left; exists l2; auto.\n  intros [ | y l2 ] r1 r2; simpl; intros H.\n  right; exists (x::l1); auto.\n  inversion H.\n  destruct (IH l2 r1 r2) as [ (m & Hm) | (m & Hm) ]; auto; \n    [ left | right ]; exists m; split; f_equal; tauto.\nQed.\n\nFact list_app_cons_eq_inv X (l1 l2 r1 r2 : list X) x :\n       l1++r1 = l2++x::r2 -> { m | l1++m = l2 /\\ r1 = m++x::r2 } \n                           + { m | l2++x::m = l1 /\\ r2 = m++r1 }.\nProof.\n  intros H.\n  apply list_app_eq_inv in H.\n  destruct H as [ H | (m & H1 & H2) ]; auto.\n  destruct m as [ | y m ].\n  left; exists nil; simpl in *; split; auto.\n  revert H1; do 2 rewrite <- app_nil_end; auto.\n  inversion H2; subst.\n  right; exists m; auto.\nQed.\n \nFact list_app_inj X (l1 l2 r1 r2 : list X) : length l1 = length l2 -> l1++r1 = l2++r2 -> l1 = l2 /\\ r1 = r2.\nProof.\n  revert l2; induction l1 as [ | x l1 IH ]; intros [ | y l2 ]; try discriminate.\n  simpl; auto.\n  intros H1 H2; inversion H1; inversion H2.\n  apply IH in H4; auto.\n  split; f_equal; tauto.\nQed.\n\nFact list_split_length X (ll : list X) k : k <= length ll -> { l : _ & { r | ll = l++r /\\ length l = k } }.\nProof.\n  revert k; induction ll as [ | x ll IHll ]; intros k.\n  exists nil, nil; split; simpl in * |- *; auto; omega.\n  destruct k as [ | k ]; intros Hk.\n  exists nil, (x::ll); simpl; split; auto.\n  destruct (IHll k) as (l & r & H1 & H2).\n  simpl in Hk; omega.\n  exists (x::l), r; split; simpl; auto; f_equal; auto.\nQed.\n\nFact list_pick X (ll : list X) k : k < length ll -> { x : _ & { l : _ & { r | ll = l++x::r /\\ length l = k } } }.\nProof.\n  revert k; induction ll as [ | x ll IHll ]; intros k.\n  simpl; omega.\n  destruct k as [ | k ]; intros H.\n  exists x, nil, ll; simpl; auto.\n  simpl in H.\n  destruct IHll with (k := k) as (y & l & r & ? & ?); try omega.\n  exists y, (x::l), r; subst; simpl; split; auto.\nQed.\n\nFact list_split_middle X l1 (x1 : X) r1 l2 x2 r2 : \n       ~ In x1 l2 -> ~ In x2 l1 -> l1++x1::r1 = l2++x2::r2 -> l1 = l2 /\\ x1 = x2 /\\ r1 = r2.\nProof.\n  intros H1 H2 H.\n  apply list_app_eq_inv in H.\n  destruct H as [ (m & H3 & H4) | (m & H3 & H4) ]; destruct m.\n  inversion H4; subst; rewrite <- app_nil_end; auto.\n  inversion H4; subst; destruct H1; apply in_or_app; right; left; auto.\n  inversion H4; subst; rewrite <- app_nil_end; auto.\n  inversion H4; subst; destruct H2; apply in_or_app; right; left; auto.\nQed.\n\nSection flat_map.\n\n  Variable (X Y : Type) (f : X -> list Y).\n\n  Fact flat_map_app l1 l2 : flat_map f (l1++l2) = flat_map f l1 ++ flat_map f l2.\n  Proof.\n    induction l1; simpl; auto; solve list eq; f_equal; auto.\n  Qed.\n\n  Fact flat_map_app_inv l r1 y r2 : flat_map f l = r1++y::r2 -> exists l1 m1 x m2 l2, l = l1++x::l2 /\\ f x = m1++y::m2 \n                                                                  /\\ r1 = flat_map f l1++m1 /\\ r2 = m2++flat_map f l2. \n  Proof.\n    revert r1 y r2.\n    induction l as [ | x l IHl ]; intros r1 y r2 H.\n    + destruct r1; discriminate.\n    + simpl in H.\n      apply list_app_cons_eq_inv in H.\n      destruct H as [ (m & Hm1 & Hm2) | (m & Hm1 & Hm2) ].\n      - apply IHl in Hm2.\n        destruct Hm2 as (l1 & m1 & x' & m2 & l2 & G1 & G2 & G3 & G4); subst.\n        exists (x::l1), m1, x', m2, l2; simpl; repeat (split; auto).\n        rewrite app_ass; auto.\n      - exists nil, r1, x, m, l; auto.\n  Qed.\n\nEnd flat_map.\n\nDefinition prefix X (l ll : list X) := exists r, ll = l++r.\n  \nInfix \"<p\" := (@prefix _) (at level 70, no associativity).\n  \nSection prefix. (* as an inductive predicate *)\n   \n  Variable X : Type.\n  \n  Implicit Types (l ll : list X).\n  \n  Fact in_prefix_0 ll : nil <p ll.\n  Proof.\n    exists ll; auto.\n  Qed.\n  \n  Fact in_prefix_1 x l ll : l <p ll -> x::l <p x::ll.\n  Proof.\n    intros (r & ?); subst; exists r; auto.\n  Qed.\n\n  Fact prefix_length l m : l <p m -> length l <= length m.\n  Proof. intros (? & ?); subst; rew length; omega. Qed.\n  \n  Fact prefix_app_lft l r1 r2 : r1 <p r2 -> l++r1 <p l++r2.\n  Proof.\n    intros (a & ?); subst.\n    exists a; rewrite app_ass; auto.\n  Qed.\n  \n  Fact prefix_inv x y l ll : x::l <p y::ll -> x = y /\\ l <p ll.\n  Proof.\n    intros (r & Hr).\n    inversion Hr; split; auto.\n    exists r; auto.\n  Qed.\n  \n  Fact prefix_list_inv l r rr : l++r <p l++rr -> r <p rr.\n  Proof.\n    induction l as [ | x l IHl ]; simpl; auto.\n    intros H; apply prefix_inv, proj2, IHl in H; auto.\n  Qed.\n\n  Fact prefix_refl l : l <p l.\n  Proof. exists nil; rewrite <- app_nil_end; auto. Qed.\n\n  Fact prefix_trans l1 l2 l3 : l1 <p l2 -> l2 <p l3 -> l1 <p l3.\n  Proof. intros (m1 & H1) (m2 & H2); subst; exists (m1++m2); solve list eq. Qed.\n\n  Section prefix_rect.\n\n    Variables (P : list X -> list X -> Type)\n              (HP0 : forall ll, P nil ll)\n              (HP1 : forall x l ll, l <p ll -> P l ll -> P (x::l) (x::ll)).\n              \n    Definition prefix_rect l ll : prefix l ll -> P l ll.\n    Proof.\n      revert l; induction ll as [ | x ll IHll ]; intros l H.\n      \n      replace l with (nil : list X).\n      apply HP0.\n      destruct H as (r & Hr).\n      destruct l; auto; discriminate.\n      \n      destruct l as [ | y l ].\n      apply HP0.\n      apply prefix_inv in H.\n      destruct H as (? & E); subst y.\n      apply HP1; [ | apply IHll ]; trivial.\n    Qed.\n   \n  End prefix_rect.\n\n  Fact prefix_app_inv l1 l2 r1 r2 : l1++l2 <p r1++r2 -> { l1 <p r1 } + { r1 <p l1 }.\n  Proof.\n    revert l2 r1 r2; induction l1 as [ | x l1 IH ].\n    left; apply in_prefix_0.\n    intros l2 [ | y r1 ] r2.\n    right; apply in_prefix_0.\n    simpl; intros H; apply prefix_inv in H.\n    destruct H as (E & H); subst y.\n    destruct IH with (1 := H); [ left | right ];\n      apply in_prefix_1; auto.\n  Qed. \n  \nEnd prefix.\n\nDefinition prefix_spec X (l ll : list X) : l <p ll -> { r | ll = l ++ r }.\nProof.\n  induction 1 as [ ll | x l ll _ (r & Hr) ] using prefix_rect.\n  exists ll; trivial.\n  exists r; simpl; f_equal; auto.\nQed.\n\nFact prefix_app_lft_inv X (l1 l2 m : list X) : l1++l2 <p m -> { m2 | m = l1++m2 /\\ l2 <p m2 }.\nProof.\n  intros H.\n  apply prefix_spec in H. \n  destruct H as (r & H).\n  exists (l2++r); simpl.\n  solve list eq in H; split; auto.\n  exists r; auto.\nQed.\n\nSection list_assoc.\n\n  Variables (X Y : Type) (eq_X_dec : eqdec X).\n\n  Fixpoint list_assoc x l : option Y :=\n    match l with \n      | nil  => None\n      | (y,a)::l => if eq_X_dec x y then Some a else list_assoc x l\n    end.\n\n  Fact list_assoc_eq x y l x' : x = x' -> list_assoc x' ((x,y)::l) = Some y.\n  Proof.    \n    intros []; simpl.\n    destruct (eq_X_dec x x) as [ | [] ]; auto.\n  Qed.\n\n  Fact list_assoc_neq x y l x' : x <> x' -> list_assoc x' ((x,y)::l) = list_assoc x' l.\n  Proof.    \n    intros H; simpl.\n    destruct (eq_X_dec x' x) as [ | ]; auto.\n    destruct H; auto.\n  Qed.\n\n  Fact list_assoc_In x l : \n    match list_assoc x l with \n      | None   => ~ In x (map fst l)\n      | Some y => In (x,y) l\n    end.\n  Proof.\n    induction l as  [ | (x',y) l IHl ]; simpl; auto.\n    destruct (eq_X_dec x x'); subst; auto.\n    destruct (list_assoc x l); auto.\n    intros [ ? | ]; subst; tauto.\n  Qed.\n\n  Fact In_list_assoc x l : In x (map fst l) -> { y | list_assoc x l = Some y /\\ In (x,y) l }.\n  Proof.\n    intros H.\n    generalize (list_assoc_In x l).\n    destruct (list_assoc x l) as [ y | ].\n    exists y; auto.\n    tauto.\n  Qed.\n  \n  Fact not_In_list_assoc x l : ~ In x (map fst l) -> list_assoc x l = None.\n  Proof.\n    intros H.\n    generalize (list_assoc_In x l).\n    destruct (list_assoc x l) as [ y | ]; auto.\n    intros H1; contradict H.\n    apply in_map_iff.\n    exists (x,y); simpl; auto.\n  Qed.\n\n  Fact list_assoc_app x ll mm : list_assoc x (ll++mm) \n                              = match list_assoc x ll with\n                                  | None   => list_assoc x mm\n                                  | Some y => Some y\n                                end.\n  Proof.\n    induction ll as [ | (x',?) ]; simpl; auto.\n    destruct (eq_X_dec x x'); auto.\n  Qed.\n\nEnd list_assoc.\n\nSection list_first_dec.\n\n  Variable (X : Type) (P : X -> Prop) (Pdec : forall x, { P x } + { ~ P x }).\n  \n  Theorem list_choose_dec ll : { l : _ & { x : _ & { r | ll = l++x::r /\\ P x /\\ forall y, In y l -> ~ P y } } }\n                             + { forall x, In x ll -> ~ P x }.\n  Proof.\n    induction ll as [ | a ll IH ];\n      [ | destruct (Pdec a) as [ Ha | Ha ]; [ | destruct IH as [ (l & x & r & H1 & H2 & H3) | H ]] ].\n    * right; intros _ [].\n    * left; exists nil, a, ll; repeat split; auto.\n    * left; exists (a::l), x, r; repeat split; subst; auto. \n      intros ? [ | ]; subst; auto.\n    * right; intros ? [ | ]; subst; auto.\n  Qed.\n  \n  Theorem list_first_dec a ll : P a -> In a ll -> { l : _ & { x : _ & { r | ll = l++x::r /\\ P x /\\ forall y, In y l -> ~ P y } } }.\n  Proof.\n    intros H1 H2.\n    destruct (list_choose_dec ll) as [ H | H ]; trivial.\n    destruct (H _ H2 H1).\n  Qed.\n  \nEnd list_first_dec.\n\nSection map.\n\n  Variable (X Y : Type) (f : X -> Y).\n  \n  Fact map_cons_inv ll y m : map f ll = y::m -> { x : _ & { l | ll = x::l /\\ f x = y /\\ map f l = m } }.\n  Proof.\n    destruct ll as [ | x l ]; try discriminate; simpl.\n    intros H; inversion H; subst; exists x, l; auto.\n  Qed.\n\n  Fact map_app_inv ll m n : map f ll = m++n -> { l : _  & { r | ll = l++r /\\ m = map f l /\\ n = map f r } }.\n  Proof.\n    revert m n; induction ll as [ | x ll IH ]; intros m n H.\n    * destruct m; destruct n; try discriminate; exists nil, nil; auto.\n    * destruct m as [ | y m ]; simpl in H.\n      + exists nil, (x::ll); auto.\n      + inversion H; subst y.\n        destruct IH with (1 := H2) as (l & r & H3 & H4 & H5); subst.\n        exists (x::l), r; auto.\n  Qed.\n  \n  Fact map_middle_inv ll m y n : map f ll = m++y::n -> { l : _ & { x : _ & { r | ll = l++x::r /\\ map f l = m /\\ f x = y /\\ map f r = n } } }.\n  Proof.\n    intros H.\n    destruct map_app_inv with (1 := H) as (l & r & H1 & H2 & H3).\n    symmetry in H3.\n    destruct map_cons_inv with (1 := H3) as (x & r' & H4 & H5 & H6); subst.\n    exists l, x, r'; auto.\n  Qed.\n  \nEnd map.\n\nFact Forall2_mono X Y (R S : X -> Y -> Prop) :\n         (forall x y, R x y -> S x y) -> forall l m, Forall2 R l m -> Forall2 S l m.\nProof.\n  induction 2; constructor; auto.\nQed. \n\nFact Forall2_nil_inv_l X Y R m : @Forall2 X Y R nil m -> m = nil.\nProof.\n  inversion_clear 1; reflexivity.\nQed.\n\nFact Forall2_nil_inv_r X Y R m : @Forall2 X Y R m nil -> m = nil.\nProof.\n  inversion_clear 1; reflexivity.\nQed.\n\nFact Forall2_cons_inv X Y R x l y m : @Forall2 X Y R (x::l) (y::m) <-> R x y /\\ Forall2 R l m.\nProof.\n  split.\n  inversion_clear 1; auto.\n  intros []; constructor; auto.\nQed.\n\nFact Forall2_app_inv_l X Y R l1 l2 m : \n    @Forall2 X Y R (l1++l2) m -> { m1 : _ & { m2 | Forall2 R l1 m1 /\\ Forall2 R l2 m2 /\\ m = m1++m2 } }.\nProof.\n  revert l2 m;\n  induction l1 as [ | x l1 IH ]; simpl; intros l2 m H.\n  exists nil, m; repeat split; auto.\n  destruct m as [ | y m ].\n  apply Forall2_nil_inv_r in H; discriminate H.\n  apply Forall2_cons_inv in H; destruct H as [ H1 H2 ].\n  apply IH in H2.\n  destruct H2 as (m1 & m2 & H2 & H3 & H4); subst m.\n  exists (y::m1), m2; repeat split; auto.\nQed.\n\nFact Forall2_app_inv_r X Y R l m1 m2 : \n    @Forall2 X Y R l (m1++m2) -> { l1 : _ & { l2 | Forall2 R l1 m1 /\\ Forall2 R l2 m2 /\\ l = l1++l2 } }.\nProof.\n  revert m2 l;\n  induction m1 as [ | y m1 IH ]; simpl; intros m2 l H.\n  exists nil, l; repeat split; auto.\n  destruct l as [ | x l ].\n  apply Forall2_nil_inv_l in H; discriminate H.\n  apply Forall2_cons_inv in H; destruct H as [ H1 H2 ].\n  apply IH in H2.\n  destruct H2 as (l1 & l2 & H2 & H3 & H4); subst l.\n  exists (x::l1), l2; repeat split; auto.\nQed.\n\nFact Forall2_cons_inv_l X Y R a ll mm : \n      @Forall2 X Y R (a::ll) mm \n   -> { b : _ & { mm' | R a b /\\ mm = b::mm' /\\ Forall2 R ll mm' } }.\nProof.\n  intros H.\n  apply Forall2_app_inv_l with (l1 := a::nil) (l2 := ll) in H.\n  destruct H as (l & mm' & H1 & H2 & H3).\n  destruct l as [ | y l ].\n  exfalso; inversion H1.\n  apply Forall2_cons_inv in H1.\n  destruct H1 as [ H1 H4 ].\n  apply Forall2_nil_inv_l in H4; subst l.\n  exists y, mm'; auto.\nQed.\n\nFact Forall2_cons_inv_r X Y R b ll mm : \n      @Forall2 X Y R ll (b::mm) \n   -> { a : _ & { ll' | R a b /\\ ll = a::ll' /\\ Forall2 R ll' mm } }.\nProof.\n  intros H.\n  apply Forall2_app_inv_r with (m1 := b::nil) (m2 := mm) in H.\n  destruct H as (l & ll' & H1 & H2 & H3).\n  destruct l as [ | x l  ].\n  exfalso; inversion H1.\n  apply Forall2_cons_inv in H1.\n  destruct H1 as [ H1 H4 ].\n  apply Forall2_nil_inv_r in H4; subst l.\n  exists x, ll'; auto.\nQed.\n\nFact Forall2_map_left X Y Z (R : Y -> X -> Prop) (f : Z -> Y) ll mm : Forall2 R (map f ll) mm <-> Forall2 (fun x y => R (f x) y) ll mm.\nProof.\n  split.\n  revert mm.\n  induction ll; intros [ | y mm ] H; simpl in H; auto; try (inversion H; fail).\n  apply Forall2_cons_inv in H; constructor. \n  tauto.\n  apply IHll; tauto.\n  induction 1; constructor; auto.\nQed.\n\nFact Forall2_map_right X Y Z (R : Y -> X -> Prop) (f : Z -> X) mm ll : Forall2 R mm (map f ll) <-> Forall2 (fun y x => R y (f x)) mm ll.\nProof.\n  split.\n  revert mm.\n  induction ll; intros [ | y mm ] H; simpl in H; auto; try (inversion H; fail).\n  apply Forall2_cons_inv in H; constructor. \n  tauto.\n  apply IHll; tauto.\n  induction 1; constructor; auto.\nQed.\n\nFact Forall2_map_both X Y X' Y' (R : X -> Y -> Prop) (f : X' -> X) (g : Y' -> Y) ll mm : Forall2 R (map f ll) (map g mm) <-> Forall2 (fun x y => R (f x) (g y)) ll mm.\nProof.\n  rewrite Forall2_map_left, Forall2_map_right; split; auto.\nQed.\n\nFact Forall2_Forall X (R : X -> X -> Prop) ll : Forall2 R ll ll <-> Forall (fun x => R x x) ll.\nProof.\n  split.\n  induction ll as [ | x ll ]; inversion_clear 1; auto.\n  induction 1; auto.\nQed.\n\nFact Forall_app X (P : X -> Prop) ll mm : Forall P (ll++mm) <-> Forall P ll /\\ Forall P mm.\nProof.\n  repeat rewrite Forall_forall.\n  split.\n  firstorder.\n  intros (H1 & H2) x Hx.\n  apply in_app_or in Hx; firstorder.\nQed.\n\nFact Forall_cons_inv X (P : X -> Prop) x ll : Forall P (x::ll) <-> P x /\\ Forall P ll.\nProof.\n  split.\n  + inversion 1; auto.\n  + constructor; tauto.\nQed.\n\nFact Forall_rev X (P : X -> Prop) ll : Forall P ll -> Forall P (rev ll).\nProof.\n  induction 1 as [ | x ll Hll IH ].\n  constructor.\n  simpl.\n  apply Forall_app; split; auto.\nQed.\n\nFact Forall_map X Y (f : X -> Y) (P : Y -> Prop) ll : Forall P (map f ll) <-> Forall (fun x => P (f x)) ll.\nProof.\n  split.\n  + induction ll; simpl; try rewrite Forall_cons_inv; constructor; tauto.\n  + induction 1; simpl; constructor; auto.\nQed.\n\nFact Forall_impl X (P Q : X -> Prop) ll : (forall x, In x ll -> P x -> Q x) -> Forall P ll -> Forall Q ll.\nProof.\n  intros H; induction 1 as [ | x ll Hx Hll IH ]; constructor.\n  + apply H; simpl; auto.\n  + apply IH; intros ? ?; apply H; simpl; auto.\nQed.\n\nFact Forall_filter X (P : X -> Prop) (f : X -> bool) ll : Forall P ll -> Forall P (filter f ll).\nProof. induction 1; simpl; auto; destruct (f x); auto. Qed.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Coq-Phase-Semantics", "sha": "52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17", "save_path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics", "path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics/Coq-Phase-Semantics-52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17/coq.prop/utils_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7437156310616473}}
{"text": "Require Import List.\nImport ListNotations.\n  \nFixpoint alternate (l1 l2 : list nat) : list nat :=\nmatch l1 with\n| [] => l2\n| h1 :: t1 =>\n  match l2 with\n  | [] => h1 :: t1\n  | h2 :: t2 => h1 :: h2 :: alternate t1 t2\n  end\nend.\n\nEval compute in alternate [1] [2].\nEval compute in alternate [1; 3; 5] [2; 4; 6].\n\nInductive alt : list nat -> list nat -> list nat -> Prop :=\n| alt_nil :\n    forall l, alt [] l l\n| alt_step :\n    forall a l t1 t2,\n    alt l t1 t2 ->\n    alt (a :: t1) l (a :: t2).\n\nLemma alt_one : alt [] [1] [1].\nProof.\napply alt_nil.\nQed.\n\nLemma alt_123456 : alt [1; 3; 5] [2; 4; 6] [1; 2; 3; 4; 5; 6].\nProof.\napply alt_step.\napply alt_step.\napply alt_step.\napply alt_step.\napply alt_step.\napply alt_step.\napply alt_nil.\nQed.\n\nPrint list_ind.\n\nLemma alt_alternate : \n  forall l1 l2 l3, alt l1 l2 l3 -> alternate l1 l2 = l3.\nProof.\ninduction l1; intros.\n- inversion H.\n  subst.\n  simpl.\n  reflexivity.\n- destruct l2; simpl.\n  * inversion H.\n    inversion H4.\n    reflexivity.\n  * inversion H.\n    inversion H4.\n    subst.\n    apply IHl1 in H9.\n    rewrite H9.\n    reflexivity.\nQed.\n\nLemma alternate_alt :\n  forall l1 l2 l3, alternate l1 l2 = l3 -> alt l1 l2 l3.\nProof.\ninduction l1; simpl; intros.\n- rewrite H. apply alt_nil.\n- destruct l2; subst; apply alt_step; try apply alt_nil.\n  apply alt_step. apply IHl1. reflexivity.\nQed.\n\nExtraction Language Ocaml.\n\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlNatInt.\n\nExtraction \"alternate.ml\" alternate.\n\n(*\nFixpoint alternate' (l1 l2 : list nat) : list nat :=\nmatch l1 with\n| [] => l2\n| h1 :: t1 => h1 :: alternate' l2 t1\nend.\n*)\n\nRequire Program.Wf.\nRequire Import Sorting.Permutation.\n\nProgram Fixpoint alternate' (l1 l2 : list nat) \n { measure (length (l1 ++ l2)) } : { l | alt l1 l2 l } :=\nmatch l1 with\n| [] => l2\n| h1 :: t1 => h1 :: alternate' l2 t1\nend.\n\nNext Obligation.\nProof.\napply alt_nil.\nDefined.\n\nNext Obligation.\nProof.\nsimpl.\nassert (H_l: length (l2 ++ t1) = length (t1 ++ l2)).\n  apply Permutation_length.\n  apply Permutation_app_swap.\nrewrite H_l.\nauto with arith.\nDefined.\n\nNext Obligation.\ncase alternate'.\nintros.\nsimpl.\napply alt_step.\nassumption.\nDefined.\n\nEval compute in proj1_sig (alternate' [1] [2]).\n\n", "meta": {"author": "palmskog", "repo": "coq-intro", "sha": "df63076ae11af53c8090c7cce66bb3a4cd2e29c5", "save_path": "github-repos/coq/palmskog-coq-intro", "path": "github-repos/coq/palmskog-coq-intro/coq-intro-df63076ae11af53c8090c7cce66bb3a4cd2e29c5/alternate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7437156070741854}}
{"text": "From Coq Require Import Arith.\n\nFixpoint sum_simple (f : nat -> nat) (n : nat) : nat :=\n  match n with\n  | 0 => f 0\n  | S m => f n + sum_simple f m\nend.\n\nFixpoint sum_aux (a : nat) (f : nat -> nat) (n : nat) : nat :=\n  match n with\n  | 0 => f 0 + a\n  | S m => sum_aux (f n + a) f m\nend.\n\nDefinition sum_tail := sum_aux 0.\n\nLemma sum_aux_rec: forall a f n,\n  sum_aux a f n = a + sum_aux 0 f n.\nProof.\n  intros. generalize dependent a.\n  induction n.\n  - intros. simpl. rewrite Nat.add_0_r. rewrite Nat.add_comm. reflexivity.\n  - intros. simpl. rewrite IHn. symmetry. rewrite IHn.\n    rewrite Nat.add_0_r. rewrite Nat.add_assoc. rewrite Nat.add_comm with (a) (f (S n)).\n    reflexivity.\nQed.", "meta": {"author": "d-krylov", "repo": "coq_examples", "sha": "c8556e538ff62eb46ba1dcd5e5bcf273b45935be", "save_path": "github-repos/coq/d-krylov-coq_examples", "path": "github-repos/coq/d-krylov-coq_examples/coq_examples-c8556e538ff62eb46ba1dcd5e5bcf273b45935be/Generalize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7436948316632338}}
{"text": "\n(* 4 Inductive Predicates *)\n\nRequire Import Cpdt.CpdtTactics.\nRequire Import List.\n\nPrint unit.\n\nPrint True.\n\n(* 4.1 Propositional Logic *)\n\nSection Propositional.\n  Variables P Q R : Prop.\n\n  Theorem obvious :\n    True.\n      apply I.\n  Qed.\n\n  Theorem obvious' :\n    True.\n      constructor.\n  Qed.\n\n  Print False.\n\n  Theorem False_imp : False -> 2 + 2 = 5.\n                                 destruct 1.\n  Qed.\n\n  Theorem ariyh_neq : 2 + 2 = 5 -> 9 + 9 = 835.\n                                     intro.\n                                     elimtype False.\n                                     crush.\n  Qed.\n\n  Print not.\n\n  Theorem arith_neq' : ~(2 + 2 = 5).\n                         unfold not.\n                         crush.\n  Qed.\n\n  Print and.\n\n  Theorem and_comm : P /\\ Q -> Q /\\ P .\n                                 destruct 1.\n                                 split.\n                                 assumption.\n                                 assumption.\n  Qed.\n\n  Print or.\n\n  Theorem or_comm : P \\/ Q -> Q \\/ P.\n                                destruct 1.\n                                right.\n                                assumption.\n                                left.\n                                assumption.\n  Qed.\n\n  Theorem or_comm' : P \\/ Q -> Q \\/ P.\n                                 tauto.\n  Qed.\n\n  Theorem arith_comm : forall ls1 ls2 : list nat ,\n      length ls1 = length ls2 \\/ length ls1 + length ls2 = 6\n      -> length (ls1 ++ ls2) = 6 \\/ length ls1 = length ls2.\n                                      intuition.\n                                      rewrite app_length.\n                                      tauto.\n  Qed.\n\n  Theorem arith_comm' : forall ls1 ls2 : list nat ,\n      length ls1 = length ls2 \\/ length ls1 + length ls2 = 6\n      -> length (ls1 ++ ls2) = 6 \\/ length ls1 = length ls2.\n                                      Hint Rewrite app_length.\n                                      crush.\n  Qed.\n\nEnd Propositional.\n\n(* 4.2 What Does It Mean to Be Constructive? *)\n\n(* 4.3 First-Order Logic *)\n\nPrint ex.\n\nTheorem exist1 : exists x : nat , x + 1 = 2.\n                                    exists 1.\n                                    reflexivity.\nQed.\n\nTheorem exist2 : forall n m : nat , (exists x : nat , n + x = m) -> n <= m.\n                                                                      destruct 1.\n                                                                      crush.\nQed.\n\n(* 4.4 Predicates with Implicit Equality *)\n\nInductive isZero : nat -> Prop :=\n| IsZero : isZero 0\n.\n\nTheorem isZero_zero : isZero 0.\n                        constructor.\nQed.\n\n(*\nThis can be interpreted as a Judgement, or natural deduction rule.\n\n-------- (IsZero)\nisZero 0\n\n *)\n\nPrint eq.\n\n(*\nAnother way of stating that definition is: equality is defined\nas the least reflexive relation.\n*)\n\nTheorem isZero_plus : forall n m : nat , isZero m -> n + m = n.\n                                                       destruct 1.\n                                                       crush.\nQed.\n\nTheorem isZero_contra : isZero 1 -> False.\n                          destruct 1.\n                          Undo.\n                          inversion 1.\nQed.\n\nTheorem isZero_contra' : isZero 1 -> 2 + 2 = 5.\n                                       destruct 1.\nAbort.\n\nCheck isZero_ind.\n\n(* 4.5 Recursive Predicates *)\n\nInductive even : nat -> Prop :=\n| EvenO : even O\n| EvenSS : forall n , even n -> even (S (S n))\n.\n\n(*\nNatural deduction rules:\n\n------ (EvenO)\neven 0\n\n\n    even n\n-------------- (EvenSS)\neven (S (S n))\n\n*)\n\nTheorem even_O : even 0.\n                   constructor.\nQed.\n\nTheorem even_4 : even 4.\n                   constructor.\n                   constructor.\n                   constructor.\nQed.\n\nHint Constructors even.\n\nTheorem even_4' : even 4.\n                    auto.\nQed.\n\nTheorem even_1_contra : even 1 -> False.\n                          inversion 1.\nQed.\n\nTheorem even_3_contra : even 3 -> False.\n                          inversion 1.\n                          inversion H1.\nQed.\n\nTheorem even_plus : forall n m, even n -> even m -> even (n + m).\n                                  induction n; crush.\n                                  inversion H.\n                                  simpl.\n                                  constructor.\n                                  Restart.\n                                  induction 1.\n                                  crush.\n                                  intro.\n                                  simpl; constructor.\n                                  apply IHeven; assumption.\n                                  Restart.\n                                  induction 1; crush.\nQed.\n\nTheorem even_contra : forall n , even (S (n + n)) -> False.\n                                   induction 1.\nAbort.\n\nLemma even_contra' : forall n' , even n' -> forall n, n' = S (n + n) -> False.\n                                                        induction 1; crush.\n                                                        destruct n; destruct n0; crush.\n                                                        SearchRewrite (_ + S _).\n                                                        rewrite <- plus_n_Sm in H0.\n                                                        apply IHeven with n0; assumption.\n                                                        Restart.\n                                                        Hint Rewrite <- plus_n_Sm.\n                                                        induction 1;crush;\n                                                        match goal with\n                                                        | [ H : S ?N = ?N0 + ?N0 |- _ ] => destruct N; destruct N0\n                                                        end; crush.\nQed.\n\nTheorem even_contra : forall n , even (S (n + n)) -> False.\n                                   intros; eapply even_contra'; eauto.\nQed.\n", "meta": {"author": "andorp", "repo": "cpdt", "sha": "dd2099eeae2f12e1379a8706420f072aa174adc5", "save_path": "github-repos/coq/andorp-cpdt", "path": "github-repos/coq/andorp-cpdt/cpdt-dd2099eeae2f12e1379a8706420f072aa174adc5/chapter04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7436948281111243}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** * Zgcd_alt : an alternate version of Z.gcd, based on Euclid's algorithm *)\n\n(**\nAuthor: Pierre Letouzey\n*)\n\n(** The alternate [Zgcd_alt] given here used to be the main [Z.gcd]\n    function (see file [Znumtheory]), but this main [Z.gcd] is now\n    based on a modern binary-efficient algorithm. This earlier\n    version, based on Euclid's algorithm of iterated modulo, is kept\n    here due to both its intrinsic interest and its use as reference\n    point when proving gcd on Int31 numbers *)\n\nRequire Import ZArith_base.\nRequire Import ZArithRing.\nRequire Import Zdiv.\nRequire Import Znumtheory.\nRequire Import Omega.\n\nOpen Scope Z_scope.\n\n(** In Coq, we need to control the number of iteration of modulo.\n   For that, we use an explicit measure in [nat], and we prove later\n   that using [2*d] is enough, where [d] is the number of binary\n   digits of the first argument. *)\n\n Fixpoint Zgcdn (n:nat) : Z -> Z -> Z := fun a b =>\n   match n with\n     | O => 1 (* arbitrary, since n should be big enough *)\n     | S n => match a with\n\t        | Z0 => Z.abs b\n\t        | Zpos _ => Zgcdn n (Z.modulo b a) a\n\t        | Zneg a => Zgcdn n (Z.modulo b (Zpos a)) (Zpos a)\n  \t      end\n   end.\n\n Definition Zgcd_bound (a:Z) :=\n   match a with\n     | Z0 => S O\n     | Zpos p => let n := Pos.size_nat p in (n+n)%nat\n     | Zneg p => let n := Pos.size_nat p in (n+n)%nat\n   end.\n\n Definition Zgcd_alt a b := Zgcdn (Zgcd_bound a) a b.\n\n (** A first obvious fact : [Z.gcd a b] is positive. *)\n\n Lemma Zgcdn_pos : forall n a b,\n   0 <= Zgcdn n a b.\n Proof.\n   induction n.\n   simpl; auto with zarith.\n   destruct a; simpl; intros; auto with zarith; auto.\n Qed.\n\n Lemma Zgcd_alt_pos : forall a b, 0 <= Zgcd_alt a b.\n Proof.\n   intros; unfold Z.gcd; apply Zgcdn_pos; auto.\n Qed.\n\n (** We now prove that Z.gcd is indeed a gcd. *)\n\n (** 1) We prove a weaker & easier bound. *)\n\n Lemma Zgcdn_linear_bound : forall n a b,\n   Z.abs a < Z.of_nat n -> Zis_gcd a b (Zgcdn n a b).\n Proof.\n   induction n.\n   simpl; intros.\n   exfalso; generalize (Z.abs_nonneg a); omega.\n   destruct a; intros; simpl;\n     [ generalize (Zis_gcd_0_abs b); intuition | | ];\n   unfold Z.modulo;\n   generalize (Z_div_mod b (Zpos p) (eq_refl Gt));\n   destruct (Z.div_eucl b (Zpos p)) as (q,r);\n   intros (H0,H1);\n   rewrite Nat2Z.inj_succ in H; simpl Z.abs in H;\n   (assert (H2: Z.abs r < Z.of_nat n) by\n    (rewrite Z.abs_eq; auto with zarith));\n    assert (IH:=IHn r (Zpos p) H2); clear IHn;\n    simpl in IH |- *;\n    rewrite H0.\n   apply Zis_gcd_for_euclid2; auto.\n   apply Zis_gcd_minus; apply Zis_gcd_sym.\n   apply Zis_gcd_for_euclid2; auto.\n Qed.\n\n (** 2) For Euclid's algorithm, the worst-case situation corresponds\n    to Fibonacci numbers. Let's define them: *)\n\n Fixpoint fibonacci (n:nat) : Z :=\n   match n with\n     | O => 1\n     | S O => 1\n     | S (S n as p) => fibonacci p + fibonacci n\n   end.\n\n Lemma fibonacci_pos : forall n, 0 <= fibonacci n.\n Proof.\n   enough (forall N n, (n<N)%nat -> 0<=fibonacci n) by eauto.\n   induction N.\n   inversion 1.\n   intros.\n   destruct n.\n   simpl; auto with zarith.\n   destruct n.\n   simpl; auto with zarith.\n   change (0 <= fibonacci (S n) + fibonacci n).\n   generalize (IHN n) (IHN (S n)); omega.\n Qed.\n\n Lemma fibonacci_incr :\n   forall n m, (n<=m)%nat -> fibonacci n <= fibonacci m.\n Proof.\n   induction 1.\n   auto with zarith.\n   apply Z.le_trans with (fibonacci m); auto.\n   clear.\n   destruct m.\n   simpl; auto with zarith.\n   change (fibonacci (S m) <= fibonacci (S m)+fibonacci m).\n   generalize (fibonacci_pos m); omega.\n Qed.\n\n (** 3) We prove that fibonacci numbers are indeed worst-case:\n    for a given number [n], if we reach a conclusion about [gcd(a,b)] in\n    exactly [n+1] loops, then [fibonacci (n+1)<=a /\\ fibonacci(n+2)<=b] *)\n\n Lemma Zgcdn_worst_is_fibonacci : forall n a b,\n   0 < a < b ->\n   Zis_gcd a b (Zgcdn (S n) a b) ->\n   Zgcdn n a b <> Zgcdn (S n) a b ->\n   fibonacci (S n) <= a /\\\n   fibonacci (S (S n)) <= b.\n Proof.\n   induction n.\n   intros [|a|a]; intros; simpl; omega.\n   intros [|a|a] b (Ha,Ha'); [simpl; omega | | easy ].\n   remember (S n) as m.\n   rewrite Heqm at 2. simpl Zgcdn.\n   unfold Z.modulo; generalize (Z_div_mod b (Zpos a) eq_refl).\n   destruct (Z.div_eucl b (Zpos a)) as (q,r).\n   intros (EQ,(Hr,Hr')).\n   Z.le_elim Hr.\n   - (* r > 0 *)\n     replace (fibonacci (S (S m))) with (fibonacci (S m) + fibonacci m) by auto.\n     intros.\n     destruct (IHn r (Zpos a) (conj Hr Hr')); auto.\n     + assert (EQ' : r = Zpos a * (-q) + b) by (rewrite EQ; ring).\n       rewrite EQ' at 1.\n       apply Zis_gcd_sym.\n       apply Zis_gcd_for_euclid2; auto.\n       apply Zis_gcd_sym; auto.\n     + split; auto.\n       rewrite EQ.\n       apply Z.add_le_mono; auto.\n       apply Z.le_trans with (Zpos a * 1); auto.\n       now rewrite Z.mul_1_r.\n       apply Z.mul_le_mono_nonneg_l; auto with zarith.\n       change 1 with (Z.succ 0). apply Z.le_succ_l.\n       destruct q; auto with zarith.\n       assert (Zpos a * Zneg p < 0) by now compute. omega.\n   - (* r = 0 *)\n     clear IHn EQ Hr'; intros _.\n     subst r; simpl; rewrite Heqm.\n     destruct n.\n     + simpl. omega.\n     + now destruct 1.\n Qed.\n\n (** 3b) We reformulate the previous result in a more positive way. *)\n\n Lemma Zgcdn_ok_before_fibonacci : forall n a b,\n   0 < a < b -> a < fibonacci (S n) ->\n   Zis_gcd a b (Zgcdn n a b).\n Proof.\n   destruct a; [ destruct 1; exfalso; omega | | destruct 1; discriminate].\n   cut (forall k n b,\n     k = (S (Pos.to_nat p) - n)%nat ->\n     0 < Zpos p < b -> Zpos p < fibonacci (S n) ->\n     Zis_gcd (Zpos p) b (Zgcdn n (Zpos p) b)).\n   destruct 2; eauto.\n   clear n; induction k.\n   intros.\n   assert (Pos.to_nat p < n)%nat by omega.\n   apply Zgcdn_linear_bound.\n   simpl.\n   generalize (inj_le _ _ H2).\n   rewrite Nat2Z.inj_succ.\n   rewrite positive_nat_Z; auto.\n   omega.\n   intros.\n   generalize (Zgcdn_worst_is_fibonacci n (Zpos p) b H0); intros.\n   assert (Zis_gcd (Zpos p) b (Zgcdn (S n) (Zpos p) b)).\n   apply IHk; auto.\n   omega.\n   replace (fibonacci (S (S n))) with (fibonacci (S n)+fibonacci n) by auto.\n   generalize (fibonacci_pos n); omega.\n   replace (Zgcdn n (Zpos p) b) with (Zgcdn (S n) (Zpos p) b); auto.\n   generalize (H2 H3); clear H2 H3; omega.\n Qed.\n\n (** 4) The proposed bound leads to a fibonacci number that is big enough. *)\n\n Lemma Zgcd_bound_fibonacci :\n   forall a, 0 < a -> a < fibonacci (Zgcd_bound a).\n Proof.\n   destruct a; [omega| | intro H; discriminate].\n   intros _.\n   induction p; [ | | compute; auto ];\n    simpl Zgcd_bound in *;\n    rewrite plus_comm; simpl plus;\n    set (n:= (Pos.size_nat p+Pos.size_nat p)%nat) in *; simpl;\n    assert (n <> O) by (unfold n; destruct p; simpl; auto).\n\n   destruct n as [ |m]; [elim H; auto| ].\n   generalize (fibonacci_pos m); rewrite Pos2Z.inj_xI; omega.\n\n   destruct n as [ |m]; [elim H; auto| ].\n   generalize (fibonacci_pos m); rewrite Pos2Z.inj_xO; omega.\n Qed.\n\n (* 5) the end: we glue everything together and take care of\n    situations not corresponding to [0<a<b]. *)\n\n Lemma Zgcd_bound_opp a : Zgcd_bound (-a) = Zgcd_bound a.\n Proof.\n  now destruct a.\n Qed.\n\n Lemma Zgcdn_opp n a b : Zgcdn n (-a) b = Zgcdn n a b.\n Proof.\n  induction n; simpl; auto.\n  destruct a; simpl; auto.\n Qed.\n\n Lemma Zgcdn_is_gcd_pos n a b : (Zgcd_bound (Zpos a) <= n)%nat ->\n   Zis_gcd (Zpos a) b (Zgcdn n (Zpos a) b).\n Proof.\n  intros.\n  generalize (Zgcd_bound_fibonacci (Zpos a)).\n  simpl Zgcd_bound in *.\n  remember (Pos.size_nat a+Pos.size_nat a)%nat as m.\n  assert (1 < m)%nat.\n  { rewrite Heqm; destruct a; simpl; rewrite 1?plus_comm;\n    auto with arith. }\n  destruct m as [ |m]; [inversion H0; auto| ].\n  destruct n as [ |n]; [inversion H; auto| ].\n  simpl Zgcdn.\n  unfold Z.modulo.\n  generalize (Z_div_mod b (Zpos a) (eq_refl Gt)).\n  destruct (Z.div_eucl b (Zpos a)) as (q,r).\n  intros (->,(H1,H2)) H3.\n  apply Zis_gcd_for_euclid2.\n  Z.le_elim H1.\n  + apply Zgcdn_ok_before_fibonacci; auto.\n    apply Z.lt_le_trans with (fibonacci (S m));\n    [ omega | apply fibonacci_incr; auto].\n  + subst r; simpl.\n    destruct m as [ |m]; [exfalso; omega| ].\n    destruct n as [ |n]; [exfalso; omega| ].\n    simpl; apply Zis_gcd_sym; apply Zis_gcd_0.\n Qed.\n\n Lemma Zgcdn_is_gcd n a b :\n   (Zgcd_bound a <= n)%nat -> Zis_gcd a b (Zgcdn n a b).\n Proof.\n   destruct a.\n   - simpl; intros.\n     destruct n; [exfalso; omega | ].\n     simpl; generalize (Zis_gcd_0_abs b); intuition.\n   - apply Zgcdn_is_gcd_pos.\n   - rewrite <- Zgcd_bound_opp, <- Zgcdn_opp.\n     intros. apply Zis_gcd_minus, Zis_gcd_sym. simpl Z.opp.\n     now apply Zgcdn_is_gcd_pos.\n Qed.\n\n Lemma Zgcd_is_gcd :\n   forall a b, Zis_gcd a b (Zgcd_alt a b).\n Proof.\n  unfold Zgcd_alt; intros; apply Zgcdn_is_gcd; auto.\n Qed.\n\n\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/ZArith/Zgcd_alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.74369482785265}}
{"text": "(*|\n############################\nWellfounded induction in Coq\n############################\n\n:Link: https://stackoverflow.com/q/37514716\n|*)\n\n(*|\nQuestion\n********\n\nLet's say that I know certain natural numbers are *good*. I know ``1``\nis good, if ``n`` is good then ``3n`` is, and if ``n`` is good then\n``n+5`` is, and those are only ways of constructing good numbers. It\nseems to me that the adequate formalization of this in Coq is\n|*)\n\nInductive good : nat -> Prop :=\n| g1 : good 1\n| g3 : forall n, good n -> good (n * 3)\n| g5 : forall n, good n -> good (n + 5).\n\n(*|\nHowever, despite being obvious, the fact that ``0`` is not good seems\nnot being provable using this definition (because when I invert, in\ncase of ``g3`` I only get the same thing in the hypothesis).\n\nNow it isn't so obvious what *exactly* are good numbers. And it really\nseems that I don't need to characterize them totally in order to know\nthat ``0`` is not good. For example, I can know that ``2`` is not good\njust by doing few inversions.\n|*)\n\n(*|\nAnswer (eponier)\n****************\n\nIndeed ``g3`` can be applied an unbounded number of times when trying\nto disprove ``good 0``. That is why we can think this proof requires\n``induction`` (and we can see that the auxiliary lemma needed in the\nsolution of @AntonTrunov uses induction). The same idea is used in\ntheorem ``loop_never_stop`` of\nhttp://www.cis.upenn.edu/~bcpierce/sf/current/Imp.html#lab428.\n|*)\n\nRequire Import Lia.\n\nExample not_good_0 : ~ good 0.\nProof.\n  intros contra. remember 0 as n. induction contra.\n  - discriminate.\n  - apply IHcontra. lia.\n  - lia.\nQed.\n\n(*|\n----\n\n**A:** And ``remember 0 as n`` is a crucial component of this\nsolution. It *sort of* replaces the original statement with ``forall\nn, n = 0 -> ~ good n.``. Great answer!\n|*)\n\n(*|\nAnswer (Anton Trunov)\n*********************\n\nThis problem needs induction. And induction needs some predicate ``P :\nnat -> Prop`` to work with. A primitive (constant) predicate like\n``(fun n => ~good 0)`` doesn't give you much: you won't be able to\nprove the base case for ``1`` (which corresponds to the constructor\n``g1``), because the predicate \"forgets\" its argument.\n\nSo you need to prove some logically equivalent (or stronger) statement\nwhich readily will give you the necessary predicate. An example of\nsuch equivalent statement is ``forall n, good n -> n > 0``, which you\ncan later use to disprove ``good 0``. The corresponding predicate\n``P`` is ``(fun n => n > 0)``.\n|*)\n\nReset Initial. (* .none *)\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.micromega.Lia.\n\nInductive good : nat -> Prop :=\n| g1 : good 1\n| g3 : forall n, good n -> good (n * 3)\n| g5 : forall n, good n -> good (n + 5).\n\nLemma good_gt_O : forall n, good n -> n > 0.\nProof.\n  intros n H. induction H; lia.\nQed.\n\nGoal ~ good 0.\n  intro H. now apply good_gt_O in H.\nQed.\n\n(*| Here is a proof of the aforementioned equivalence: |*)\n\nLemma not_good0_gt_zero_equiv_not_good0 :\n  (forall n, good n -> n > 0) <-> ~ good 0.\nProof.\n  split; intros ? ?.\n  - apply H in H0. lia.\n  - destruct n; [tauto | lia].\nQed.\n\n(*|\nAnd it's easy to show that ``forall n, n = 0 -> ~ good n`` which\nimplicitly appears in @eponier's answer is equivalent to ``~ good 0``\ntoo.\n|*)\n\nLemma not_good0_eq_zero_equiv_not_good0 :\n  (forall n, n = 0 -> ~ good n) <-> ~ good 0.\nProof.\n  split; intros; subst; auto.\nQed.\n\n(*|\nNow, the corresponding predicate used to prove ``forall n, n = 0 -> ~\ngood n`` is ``fun n => n = 0 -> False``. This can be shown by using\nmanual application of the ``goal_ind`` induction principle,\nautomatically generated by Coq:\n|*)\n\nExample not_good_0_manual : forall n, n = 0 -> ~ good n.\nProof.\n  intros n Eq contra.\n  generalize Eq.\n  refine (good_ind (fun n => n = 0 -> False) _ _ _ _ _);\n    try eassumption; intros; lia.\nQed.\n\n(*|\n``generalize Eq.`` introduces ``n = 0`` as a premise to the current\ngoal. Without it the goal to prove would be ``False`` and the\ncorresponding predicate would be the boring ``fun n => False`` again.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/wellfounded-induction-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.7436948260849113}}
{"text": "Require Import Unicode.Utf8.\n\nSection Task_4_8.\n  Variables A B C : Prop.\n  Variable P : nat → Prop.\n\n  Hypothesis EM: forall p : Prop, p ∨ ¬p.\n  Hypothesis DN: forall p : Prop, ¬¬p → p.\n\n  Lemma task1: (A → exists x, P x) → exists x, (A → P x).\n  Proof.\n    intros exists_P.\n    apply DN.\n    intro not_exists.\n\n    (* To reach false, let's prove a hypothesis - exists_P - is wrong: *)\n    elim exists_P.\n\n    intros x Px.\n    (* Again - for false, let's prove a hypothesis is wrong: *)\n    elim not_exists.\n\n    (* The 'x' and 'P x' we need are in the hypothesis: *)\n    exists x ; intro ; assumption.\n\n    (* Having proved that the consequent of the exists_P implication is wrong,\n       we've got to prove its antecedent is true.\n       Let's assume the opposite: *)\n    apply DN ; intro not_A.\n\n    (* For a contradiction, let's prove the opposite of a hypothesis: *)\n    elim not_exists.\n\n    (* Really, now's the hardest part of the proof.\n       Took me probably 20 minutes.\n       I initially proved the goal with 'forall' instead of 'exists',\n       which is a stronger claim, but couldn't integrate it here.\n\n       As the inner term (A → P x) is true for all x given our assumption (¬A),\n       we really need to give it just a single x: *)\n    exists 42 ; intro ; contradiction.\n  Qed.\n\n  Lemma task2: ((A → B) → C) → (A → C) → C.\n    intros A_B_impl_C A_impl_C.\n\n    apply DN ; intro not_C.\n\n    (* Now we have (¬C) and (A → C) as hypotheses.\n       Obviously, A can't be true.\n       Otherwise the implication would be false, because C is false. *)\n\n    (* As I need to reach a contradiction, it would be very useful to \n       have another hypothesis.\n\n       As 'A' is false by the above argument, I shall try to add\n       (¬A) to my hypotheses. *)\n\n    (* A very easy way to do so is to look at the 2 possibilities for A.\n       It might be possible to go without EM, but solving for 'A'\n       is straightforward and we can quickly move to ¬A: *)\n    elim EM with (p := A).\n\n    intro proof_A.\n    (* Having A and ¬C and (A → C), contradiction is easy: *)\n    apply not_C in A_impl_C ; assumption.\n\n    (* Now we're just as before the 'EM', but with '¬A' as hypothesis: *)\n    intro not_A.\n\n    (* ¬C forces ¬(A → B) because of '(A → B) → C': *)\n    apply not_C in A_B_impl_C .\n\n    (* A false goal and a false hypothesis? \n       Don't know where it came from, but it's easy: *)\n    assumption.\n\n    (* Need A → B while ¬A is available. Trivial: *)\n    intro proof_A ; contradiction.\n  Qed.\n\n  Lemma task3: (A → B) ∨ (B → A).\n  Proof.\n    (* Looking at both cases for 'A' makes this extremely easy: *)\n    elim EM with (p := A).\n\n    intro proof_A.\n    (* First, we have A. But there's a B → A on the right of the disjunction: *)\n    right; intro; assumption.\n\n    intro not_A.\n    (* Next, we have ¬A. But there's A → B on the left of the disjunction: *)\n    left; intro ; contradiction.\n  Qed.\n\n  Lemma task4: ((A → B) → A) → A.\n  Proof.\n    intro.\n    (* Obviously, A can't be false in (A → B) → A. *)\n    elim EM with (p := A).\n    (* The first case - A → A - is trivial *)\n    intros ; assumption.\n\n    intro not_A.\n    (* In the second case, we have '(A → B) → A' and a goal 'A'.\n       Let's prove (A → B) instead: *)\n    apply H.\n\n    (* But that's easy, because we assumed ¬A: *)\n    intro ; contradiction.\n  Qed.\n\nEnd Task_4_8.\n\n", "meta": {"author": "code-hunger", "repo": "fire-proofs", "sha": "6b9375239bff5c0d692350e702f2c8f35c3e1206", "save_path": "github-repos/coq/code-hunger-fire-proofs", "path": "github-repos/coq/code-hunger-fire-proofs/fire-proofs-6b9375239bff5c0d692350e702f2c8f35c3e1206/some-formulas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7436948184720601}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Nat Lia Relations.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list finite php.\n\nFrom Undecidability.FOL.TRAKHTENBROT\n  Require Import notations.\n\nSet Implicit Arguments.\n\n(* * Kleene's greatest fixpoint of lia-continous operators *)\n\nSection gfp.\n\n  (* We develop the theory of Kleene's greatest fixpoint for binary relations\n      and establish the fact that the gfp is an equivalence (under suitable hyps),\n      reached after lia many steps (under lia continuity) and\n      reached after finitely many steps (under finiteness of the domain and\n      preservation of decidability *)\n\n  Variable (M : Type). \n\n  Implicit Type (R T : M -> M -> Prop).\n\n  Notation \"R ⊆ T\" := (forall x y, R x y -> T x y).\n\n  Notation \"R 'o' T\" := (fun x z => exists y, R x y /\\ T y z) (at level 58).\n\n  Let incl_trans R S T : R ⊆ S -> S ⊆ T -> R ⊆ T.\n  Proof. firstorder. Qed.\n\n  Let comp_mono R R' T T' : R ⊆ R' -> T ⊆ T' -> R o T ⊆ R' o T'.\n  Proof. firstorder. Qed. \n\n  Variable (F : (M -> M -> Prop) -> M -> M -> Prop).\n\n  Hypothesis (HF0 : forall R T, R ⊆ T -> F R ⊆ F T).  (* Monotonicity *)\n\n  Let sym R := fun x y => R y x.\n\n  Let i := iter F (fun _ _ => True).\n\n  Let iS n : i (S n) = F (i n).\n  Proof. apply iter_S. Qed.\n\n  Let i0 : i 0 = fun _ _ => True.\n  Proof. auto. Qed.\n\n  Let i_S n : i (S n) ⊆ i n.\n  Proof.\n    unfold i.\n    induction n as [ | n IHn ].\n    + simpl; auto.\n    + intros ? ?.\n      rewrite iter_S with (n := n), iter_S.\n      apply HF0, IHn.\n  Qed.\n\n  Let i_decr n m : n <= m -> i m ⊆ i n.\n  Proof. induction 1; auto. Qed.\n\n  Definition gfp x y := forall n, i n x y.\n\n  Notation I := (@eq M).\n\n  Hypothesis HF1 : I ⊆ F I.    (* Reflexivity *)\n\n  Let i_refl n : I ⊆ i n.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite i0; auto.\n    + rewrite iS.\n      apply incl_trans with (1 := HF1), HF0, IHn.\n  Qed.\n  \n  Let gfp_refl : I ⊆ gfp.\n  Proof. intros ? ? [] ?; apply i_refl; auto. Qed.\n\n  Hypothesis HF2 : forall R, sym (F R) ⊆ F (sym R).   (* Symmetry *)\n\n  Let i_sym n : sym (i n) ⊆ i n.\n  Proof.\n    induction n as [ | n IHn ].\n    + intros ? ?; rewrite i0; simpl; auto.\n    + rewrite iS; apply incl_trans with (2 := HF0 _ IHn), HF2.\n  Qed.\n\n  Let gfp_sym : sym gfp ⊆ gfp.\n  Proof. intros ? ? H ?; apply i_sym, H. Qed.\n\n  Hypothesis HF3 : forall R, F R o F R ⊆ F (R o R).   (* Transitivity *)\n\n  Let i_trans n : i n o i n ⊆ i n.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite i0; auto.\n    + rewrite iS; apply incl_trans with (1 := @HF3 _), HF0, IHn.\n  Qed.\n\n  Let gfp_trans : gfp o gfp ⊆ gfp.\n  Proof.\n    intros ? ? H ?; apply i_trans.\n    revert H; apply comp_mono; auto.\n  Qed.\n\n  Fact gfp_equiv : equiv _ gfp.\n  Proof using i_trans i_sym i_refl gfp_trans gfp_sym gfp_refl HF3 HF2 HF1.\n    msplit 2.\n    + intro; apply gfp_refl; auto.\n    + intros ? y ? ? ?; apply gfp_trans; exists y; auto.\n    + intros ? ?; apply gfp_sym.\n  Qed.\n\n  Fact gfp_greatest R : R ⊆ F R -> R ⊆ gfp.\n  Proof using HF0.\n    intros HR x y H n; revert x y H.\n    induction n as [ | n IHn ].\n    + now auto.\n    + apply incl_trans with (1 := HR).\n      rewrite iS; apply HF0; auto.\n  Qed. \n\n  Let gfp_fix1 : F gfp ⊆ gfp.\n  Proof.\n    intros ? ? H ?.\n    apply i_S; rewrite iS.\n    revert H; apply HF0; auto.\n  Qed.\n\n  (* This is ω-continuity *)\n\n  Definition gfp_continuous := forall (s : nat -> M -> M -> Prop), \n                        (forall n m, n <= m -> s m ⊆ s n) \n                     -> (fun x y => forall n, F (s n) x y) ⊆ F (fun x y => forall n, s n x y).\n\n  Variable HF4 : gfp_continuous. \n\n  Let gfp_fix0 : gfp ⊆ F gfp.\n  Proof.\n    intros ? ? H.\n    apply HF4; auto.\n    intro; rewrite <- iS; apply H.\n  Qed.\n\n  Fact gfp_fix x y : F gfp x y <-> gfp x y.\n  Proof using i_decr i_S gfp_fix1 gfp_fix0 HF4 HF0. split; auto. Qed.\n\n  (* This is for decidability *)\n\n  Let dec R := forall x y, { R x y } + { ~ R x y }.\n\n  Variable HF5 : forall R, dec R -> dec (F R).       (* Preservation of decidability *)\n\n  Let i_dec n : dec (i n).\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite i0; left; auto.\n    + rewrite iS; apply HF5; auto.\n  Qed.\n\n  (* For the decidability of gfp, we need the finiteness\n      so that gfp = i n for a sufficiently large n *)\n\n  (* A good pair for i (ie n < m and i n ⊆ i m) means gfp is reached  at n *)\n\n  Let i_dup n m : n < m -> i n ⊆ i m -> forall k, n <= k -> forall x y, gfp x y <-> i k x y.\n  Proof.\n    intros H1 H2.\n    generalize (i_decr H1) (i_S n); rewrite iS; intros H3 H4.\n    generalize (incl_trans _ _ _ H2 H3); intros H5.\n    assert (forall p, i n ⊆ i (p+n)) as H6.\n    { induction p as [ | p IHp ]; auto.\n      simpl plus; rewrite iS.\n      apply incl_trans with (1 := H5), HF0; auto. }\n    intros k Hk x y; split; auto.\n    intros H a.\n    destruct (le_lt_dec a k).\n    + revert H; apply i_decr; auto.\n    + replace a with (a-n+n) by lia.\n      apply H6.\n      revert H; apply i_decr; auto.\n  Qed.\n\n  (* If there is a good pair below b, then gfp = i b *)\n\n  Let gfp_reached b : (exists n m, n < m <= b /\\ i n ⊆ i m) -> (forall x y, gfp x y <-> i b x y).\n  Proof.\n    intros (n & m & H1 & H2). \n    apply i_dup with (2 := H2); auto; try lia.\n  Qed.\n\n  Variable HF6 : finite_t M.     (* Finiteness of the domain *)\n\n  (** When M is finite, there is a list [T1;...;Tk] of relations of\n      type M -> M -> Prop which contains every weakly decidable relations \n      upto equivalence. \n\n      Hence, by the a generalized version of the PHP (proved w/o\n      assuming discreteness), for n greater than the length of\n      the list for M, one can find a duplicate\n      in the list [i 0; ...;i n] ie a < b <= n such\n      that i a ~ Tu ~ Tv ~ i b\n\n      Then one can deduce i n ~ gfp *)\n\n  Theorem gfp_finite_t : { n | forall x y, gfp x y <-> i n x y }.\n  Proof using i_dup i_decr i_dec i_S gfp_reached HF6 HF5 HF0.\n    destruct finite_t_weak_dec_rels with (1 := HF6)\n      as (mR & HmR).\n    exists (S (length mR)).\n    set (l := map i (list_an 0 (S (length mR)))).\n    apply (@gfp_reached (S (length mR))).\n    destruct php_upto \n      with (R := fun R T => forall x y, R x y <-> T x y)\n           (l := l) (m := mR)\n      as (a & R & b & T & c & H1 & H2).\n    + intros R S H ? ?; rewrite H; tauto.\n    + intros R S T H1 H2 ? ?; rewrite H1, H2; tauto.\n    + intros R HR.\n      unfold l in HR; apply in_map_iff in HR.\n      destruct HR as (n & <- & _).\n      destruct (HmR (i n)) as (T & H1 & H2).\n      * intros x y; destruct (i_dec n x y); tauto.\n      * exists T; auto.\n    + unfold l; rewrite map_length, list_an_length; auto.\n    + unfold l in H1; apply map_duplicate_inv in H1.\n      destruct H1 as (a' & n & b' & m & c' & H1 & H3 & H4 & H5 & H6 & H7).\n      exists n, m; rewrite <- H3, <- H5; split; try (intros ? ?; apply H2).\n      apply list_an_duplicate_inv in H7; lia.\n  Qed.\n\n  (* As a consequence of been reached after a finite number of steps, \n      gfp is one of the i n (for some computable n) and thus decidable *)\n\n  Theorem gfp_decidable : dec gfp.\n  Proof using i_dup i_decr i_dec i_S gfp_reached gfp_fix1 HF6 HF5 HF0.\n    destruct gfp_finite_t as (n & Hn).\n    intros x y; destruct (i_dec n x y); [ left | right ]; \n      rewrite Hn; tauto.\n  Qed.\n\nEnd gfp.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FOL/TRAKHTENBROT/gfp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7436930932919789}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List.\n\nRequire Import base.\n\nLocal Notation \"R ↓ x\" := (fun a b => R a b /\\ R b x).\n\nSet Implicit Arguments.\n\n(** The definition of R-homogeneous list for a binary relation R \n\n    homogeneous R (x1::...::xn::nil) <=> ∀ i < j, xi R xj\n    \n    see homogeneous_spec below \n*)\n\n(** Symbols for copy/paste: ∩ ∪ ⊆ ⊇ ⊔ ⊓ ⊑ ≡  ⋅ ↑ ↓ ⇑ ⇓ ∀ ∃ *)\n\nSection homogeneous.\n\n  Variable (X : Type) (R : X -> X -> Prop).\n\n  Inductive homogeneous : list X -> Prop :=\n    | in_homogeneous_0 : homogeneous nil\n    | in_homogeneous_1 : ∀ x l, homogeneous l -> Forall (R x) l -> homogeneous (x::l).\n    \n  Fact homogeneous_sg x : homogeneous (x::nil).\n  Proof. do 2 constructor. Qed.\n    \n  Fact homogeneous_inv x l : homogeneous (x::l) <-> Forall (R x) l /\\ homogeneous l.\n  Proof. \n    split. \n    * inversion 1; subst; auto.\n    * constructor; tauto. \n  Qed.\n  \n  Fact homogeneous_app_inv l m : \n         homogeneous (l++m) <-> homogeneous l \n                             /\\ homogeneous m \n                             /\\ ∀ x y, In x l -> In y m -> R x y.\n  Proof.\n    split.\n    + induction l as [ | x l IHl ]; simpl.\n      * repeat split; auto; try constructor; intros _ _ [].\n      * intros H.\n        apply homogeneous_inv in H.\n        destruct H as [ H1 H2 ].\n        apply IHl in H2.\n        destruct H2 as (H2 & H3 & H4).\n        apply Forall_app in H1.\n        destruct H1 as [ H0 H1 ].\n        repeat split; auto.\n        constructor; auto.\n        intros x' y [ | H' ] Hy; auto.\n        subst.\n        rewrite Forall_forall in H1; auto.\n    + intros (H1 & H2 & H3); revert H3.\n      induction H1 as [ | x l H1 IH1 H3 ]; intros H4; simpl; auto.\n      constructor.\n      * apply IH1; intros; apply H4; auto; right; auto.\n      * rewrite Forall_app; split; auto.\n        rewrite Forall_forall.\n        intros; apply H4; auto; left; auto.\n  Qed.\n \n  Fact homogeneous_two_inv x y l : homogeneous (x::y::l) -> R x y.\n  Proof.\n    inversion 1; subst.\n    inversion H3; subst; auto.\n  Qed.\n  \n  (* This is a non-inductive characterization of homogeneous *)\n  \n  Theorem homogeneous_spec ll : homogeneous ll <-> ∀ l x m y r, ll = l++x::m++y::r -> R x y.\n  Proof.\n    split.\n    + intros H l x m y r E; subst.\n      rewrite homogeneous_app_inv in H.\n      destruct H as (_ & H & _).\n      rewrite homogeneous_inv, Forall_app, Forall_cons_inv in H.\n      tauto.\n    + induction ll as [ | a ll IHll ]; intros Hll; constructor.\n      * apply IHll.\n        intros l x m y r E.\n        apply (Hll (a::l) x m y r); subst; auto.\n      * rewrite Forall_forall; intros u Hu.\n        apply in_split in Hu; destruct Hu as (l & r & Hu).\n        apply (Hll nil a l u r); subst; auto.\n  Qed.\n    \n  Hypothesis R_dec : forall x y, R x y \\/ ~ R x y.\n  \n  Theorem homogeneous_dec l : homogeneous l \\/ ~ homogeneous l.\n  Proof. \n    induction l as [ | x l [ H | H ] ].\n    + left; constructor.\n    + destruct Forall_l_dec with (P := R x) (l := l) as [ H1 | H1 ].\n      * intro; apply R_dec.\n      * left; constructor; auto.\n      * right; contradict H1; rewrite homogeneous_inv in H1; tauto.\n    + right; contradict H; rewrite homogeneous_inv in H; tauto.\n  Qed.\n\nEnd homogeneous.\n\nFact homogeneous_snoc X R ll x : @homogeneous X R (ll ++ x :: nil) -> homogeneous (R↓x) ll.\nProof.\n  intros H; apply homogeneous_app_inv in H.\n  destruct H as (H1 & _ & H2).\n  assert (Forall (fun y => R y x) ll) as H3.\n  { rewrite Forall_forall; intros y Hy; apply H2; simpl; auto. }\n  clear H2; revert H1 x H3.\n  induction 1 as [ | x ll H1 H2 IH2 ]; intros y Hy; simpl.\n  + constructor.\n  + rewrite Forall_cons_inv in Hy.\n    destruct Hy as [ H3 H4 ].\n    constructor 2; auto.\n    revert IH2 H4; repeat rewrite Forall_forall; firstorder.\nQed.\n\n", "meta": {"author": "DmxLarchey", "repo": "Ramsey", "sha": "24510f63d4290149c4944fe68267d342345621ed", "save_path": "github-repos/coq/DmxLarchey-Ramsey", "path": "github-repos/coq/DmxLarchey-Ramsey/Ramsey-24510f63d4290149c4944fe68267d342345621ed/src/homogeneous.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7436930915935297}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : Lst) : Nat\n           := match len_arg0 with\n              | nil => zero\n              | cons x y => succ (len y)\n              end.\n\nLemma lem : forall l1 l2 n, succ (len (append l1 l2)) = len (append l1 (cons n l2)).\nProof.\n   induction l1.\n   - intros. simpl. f_equal. apply IHl1.\n   - intros. reflexivity.\nQed.\n\nLemma lem2 : forall l, len l = len (append l nil).\nProof.\n   induction l.\n   - simpl. f_equal. apply IHl.\n   - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (len (append x y)) (len (append y x)).\nProof.\n   induction x.\n   - intros. simpl. rewrite IHx. apply lem.\n   - intros. simpl. apply lem2.\nQed.\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7436300538385178}}
{"text": "Require Import PeanoNat.\nLocal Open Scope nat_scope.\n\nInductive btree : Type :=\n  | empty : btree \n  | node : btree->nat->btree->btree.\n\nDefinition tree :=node (node empty 7 (node empty 2 empty)) 1 (node(node empty 10 empty)8 empty).\n\n(*OR(orb) - AND(andb)*)\n\nFixpoint searchBT(t:btree) (value:nat) : bool :=\n  match t with\n  |empty =>false\n  |node l v r => if v=? value \n                  then true\n                   else orb (searchBT l value) (searchBT r value)\nend.\n\nCompute (searchBT tree 10).\nCompute(searchBT tree 24).\n\n(*Oglinditul unui arbore binar de cautare*)\nFixpoint mirroredBT(t:btree):btree:=\n  match t with \n  | empty =>empty\n  | node l v r => node (mirroredBT r) v (mirroredBT l) \nend.\n \n\n(*Verificare arbore binar de cautare*)\nCompute (mirroredBT tree).\n(*Valoare unui nod*)\nFixpoint returnNodeValue(t :btree):nat :=\n  match t with\n  |empty=>0\n  |node l v r =>v  \nend.\n\n(*Este arbore binar de cautare?*)\nFixpoint isSearchBT(t:btree):bool := \n  match t with\n  | empty => true\n  | node empty v empty => true\n  | node l v empty =>(returnNodeValue l) <?v\n  | node empty v r => v <? (returnNodeValue r)\n  | node l v r =>andb ((returnNodeValue l)<?v) (v<?(returnNodeValue r))\n  \nend.\n\nCompute (isSearchBT tree).\n\nCompute (isSearchBT (node (node empty 3 empty) 2 (node empty 4 empty ))).\n\n(*Cautare intr-un arbore binar de cautare*)\nFixpoint searchInBST(t:btree) (n:nat):bool :=\n  match t with\n  |empty => false\n  |node l v r => if n=?v \n                  then true\n                  else if n<?v \n                        then searchInBST l n \n                        else searchInBST r n\nend.\n \n(*Inaltime unui arbore binar*)\nCompute searchInBST (tree) (1).\nFixpoint lengthSearchBT(t:btree):nat :=\n  match t with\n  | empty=>0\n  | node l v r => max (lengthSearchBT l) (lengthSearchBT r ) + 1\n end.\n\nCompute(lengthSearchBT tree).\n", "meta": {"author": "IonitaCatalin", "repo": "programming-language-principle", "sha": "e6a5b4f5284f28127707dc1b8838bad29f215c69", "save_path": "github-repos/coq/IonitaCatalin-programming-language-principle", "path": "github-repos/coq/IonitaCatalin-programming-language-principle/programming-language-principle-e6a5b4f5284f28127707dc1b8838bad29f215c69/Lab2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7436300525811009}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\n\nLocal Open Scope ring_scope.\n\nGoal 2%:Q + 2%:Q = 4%:Q.\nProof. reflexivity. Qed.\n\nGoal - 2%:Q = -1 * 2%:Q.\nProof. reflexivity. Qed.\n\nGoal 2%:Q ^+ 2 = 4%:Q.\nProof. reflexivity. Qed.\n\nGoal (-1)^-1 = -1 :> rat.\nProof. reflexivity. Qed.\n\nLocal Open Scope rat_scope.\n\nCheck 12.\nCheck 3.14.\nCheck -3.14.\nCheck 0.5.\nCheck 0.2.\n", "meta": {"author": "math-comp", "repo": "math-comp", "sha": "e39f9173b484f2e8e7f69f746a619dcc8f3abc1b", "save_path": "github-repos/coq/math-comp-math-comp", "path": "github-repos/coq/math-comp-math-comp/math-comp-e39f9173b484f2e8e7f69f746a619dcc8f3abc1b/mathcomp/test_suite/test_rat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750400464605, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7435477534752156}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (x : natural) : natural :=\n  plus (mult x lf3) lf3.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj143_coqofml_bTWgGN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7434544686920287}}
{"text": "Require Import Arith.\n\nTheorem plus_permute2 : forall n m p:nat, n + m + p = n + p + m.\nProof.\n intros n m p.\n rewrite plus_assoc_reverse.\n pattern (m + p); rewrite plus_comm.\n rewrite plus_assoc_reverse; reflexivity.\nQed.\n\n\n(** Note : using automatic tactics is better : \n\n*)\n\nTheorem plus_permute2' : forall n m p:nat, n + m + p = n + p + m.\nProof.\n intros n m p; ring.\nQed.\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/ch5_everydays_logic/SRC/plus_permute2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7434544639583115}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** \n\n----\n#<div class=\"slide\">#\n** Roadmap for lessons 3 and 4\n\n    - finite types\n    - big operators\n\n*)\n\n(**\n#</div>#\n----\n#<div class=\"slide\">#\n** Lesson 3 \n\n    - The math-comp library gives some support for finite types.\n    - ['I_n] is the the set of natural numbers smaller than n.\n    - [a : 'I_n] is composed of a value m and a proof that [m < n].\n\n    - Example : [oid] modifies the proof part with an equivalent one.\n\n#<div>#\n*)\n\nDefinition oid n (x : 'I_n) : 'I_n.\nProof.\npose v := nat_of_ord x.\npose H := ltn_ord x.\npose H1 := leq_trans H (leqnn n).\nexact: Ordinal H1.\nDefined.\n\n(** \n#</div>#\n** Note\n\n    - [nat_of_ord] is a coercion (see H)\n    - ['I_0] is an empty type\n#<div>#\n*)\n\nLemma empty_i0 (x : 'I_0) : false.\nProof. \ncase x. \nby [].\nQed.\n\n(** \n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Equality\n\n    - Every finite type is also an equality type.\n    - For ['I_n], only the value matters\n\n#<div>#\n*)\n\nDefinition i3 := Ordinal (isT : 3 < 4).\n\nLemma ieq : oid i3 == i3.\nProof.\nexact: eqxx.\nQed.\n\nLemma ieq' (h : 3 < 4) : Ordinal h == i3.\nProof.\napply/eqP.\npose H := val_inj.\napply:val_inj.\nrewrite /=.\nby [].\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n   ** An optimic map from [nat] to [ordinal] : [inord]\n\n    - If the expected type has shape 'I_n.+1\n    - Takes a natural number as input and return an element of 'I_n.+1\n    - The _same number_ if it is small enough, otherwise 0.\n\n#<div>#\n*)\n\nCheck inord.\n\nCheck inordK.\n\nCheck inord_val.\n\nExample inord_val_3_4 : inord 3 = (Ordinal (isT : 3 < 4)) :> 'I_4.\nProof.\napply:val_inj. rewrite /=. rewrite inordK. by []. by [].\nQed.\n\n(** \n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Sequence\n\n    - a finite type can be seen as a sequence\n    - [enum T] gives this sequence.\n    - it is duplicate free.\n    - it relates to the cardinal of a finite type\n\n#<div>#\n*)\n\nLemma iseq n (x : 'I_n) : x \\in 'I_n.\nProof.\nset l := enum 'I_n.\nmove: l; rewrite /= => l.\nhave ordinal_finType := ordinal_finType.\nhave mem_enum := mem_enum.\nhave enum_uniq := enum_uniq.\nhave cardT := cardT.\nhave cardE := cardE.\nby [].\nQed.\n\n(** \n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Boolean theory of finite types. \n\n    - for finite type, boolean reflection can be extended to quantifiers\n    - getting closer to classical logic!\n\n#<div>#\n*)\n\nLemma iforall (n : nat) : [forall x: 'I_n, x < n].\nProof. \napply/forallP.\nrewrite /=.\nmove=> x.\nexact: ltn_ord.\nQed.\n\nLemma iexists  (n : nat) : (n == 0) || [exists x: 'I_n, x == 0 :> nat].\nProof.\ncase: n.\nby [].\nmove=> n.\nrewrite /=. (* optional, try removing this line. *)\napply/existsP.\npose H : 0 < n.+1 := isT.\npose x := Ordinal H.\nexists x.\nby [].  (* mention function ord0. *)\nQed.\n\n(** \n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Selecting an element\n    - pick selects an element that has a given property\n    - pickP triggers the reflection\n#<div>#\n*)\nCheck pick.\n\nDefinition izero n (x : 'I_n) := odflt x [pick i : 'I_n | i == 0 :> nat].\n\nLemma izero_def n (x : 'I_n.+1) : izero x == 0 :> nat.\nProof.\nrewrite /izero.\ncase: pickP.\n  rewrite /=.\n  by [].\nrewrite /=.\nmove=> H.\nhave := H (Ordinal (isT : 0 < n.+1)).\nrewrite /=.\nby [].\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Building finite types\n    - SSR automatically discovers the pair of two finite types is finite\n    - For functions there is an explicit construction [ffun x => body]\n#<div>#\n*)\nCheck [finType of 'I_3 * 'I_4].\nFail Check [finType of 'I_3 * nat].\n\nLemma ipair : [forall x : 'I_3 * 'I_4, x.1 * x.2 < 12].\nProof.\napply/forallP.\nrewrite /=.\ncase.\nrewrite /=.\nmove=> a b.\nhave H := ltn_mul.\nrewrite -[12]/(3 * 4).\napply: H.\n  by [].\nby [].\nQed.\n\nLemma ifun : [exists f : {ffun 'I_3 -> 'I_4}, forall x, f x == x :> nat].\nProof.\napply/existsP.\nrewrite /=.\nhave H : forall n x, x < n -> x < n.+1.\n  move=> n x H.\n  rewrite ltnS.\n  by rewrite ltnW.\nexists [ffun x : 'I_3 => Ordinal (H 3 x (ltn_ord x))].\napply/forallP.\nmove=> x.\nhave ffunE' := ffunE.\nrewrite ffunE'.\nrewrite /=.\nby [].\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Installing the finite type structure for an arbitrary type\n    - When you have a type that you know is finite, you\n      need some work to make it recognized.\n\n#<div>#\n*)Inductive forest_monster :=\n  Lion | Tiger | Bear.\n\nFail Check [finType of forest_monster].\n\n(**\n#</div>#\n    - Solution: exhibit an injection into a finite type.\n#<div>#\n*)\nDefinition monster_ord m : 'I_3 :=\n  match m with\n    Lion => inord 0 | Tiger => inord 1 | _ => inord 2\n  end.\n\nDefinition ord_monster (n : 'I_3) : option forest_monster :=\n  match val n with 0 => Some Lion | 1 => Some Tiger | _ => Some Bear end.\n\nLemma monster_ord_can : pcancel monster_ord ord_monster.\nProof.\ncase.\nrewrite /=. rewrite /ord_monster. rewrite /= inordK. by []. by [].\nby rewrite /ord_monster /= inordK.\nby rewrite /ord_monster /= inordK.\nQed.\n\n(**\n#</div>#\n    - The lemma monster_ord_can means that there is an injection from\n      [forest_monster] into a known finite type. This gives a host of structure\n      bridges to [eqType], [choiceType], [countType], [finiteType].\n#<div>#\n*)\nCanonical fm_eqType := EqType forest_monster (PcanEqMixin monster_ord_can).\nCanonical fm_choiceType :=\n  ChoiceType forest_monster (PcanChoiceMixin monster_ord_can).\nCanonical fm_countType :=\n  CountType forest_monster (PcanCountMixin monster_ord_can).\nCanonical fm_finType := FinType forest_monster\n                                   (PcanFinMixin monster_ord_can).\n\nCheck [finType of forest_monster].\n\n(**\n#</div>#\n#</div>#\n   ----\n   ----\n#<div class=\"slide\">#\n  ** Big operators\n    - Big operators provide a library to manipulate iterations in math-comp\n    - this is an encapsulation of the fold function\n #<div>#\n*)\nSection F.\n\nDefinition f (x : nat) := 2 * x.\nDefinition g x y := x + y.\nDefinition r := [::1; 2; 3].\n\nLemma bfold : foldr (fun val res => g (f val) res) 0 r = 12.\nProof.\nrewrite /=.\nrewrite /f.\nrewrite /g.\nby [].\nQed.\n\nEnd F.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n   ** Notation\n\n    - iteration is provided by the \\big notation\n    - the basic operation is on list\n    - special notations are introduced for usual case (\\sum, \\prod, \\bigcap ..) \n#<div>#\n*)\nLemma bfoldl : \\big[addn/0]_(i <- [::1; 2; 3]) i.*2 = 12.\nProof.\nrewrite big_cons.\nrewrite big_cons.\nrewrite big_cons.\nrewrite big_nil.\nby [].\nQed.\n\nLemma bfoldlm : \\big[muln/1]_(i <- [::1; 2; 3]) i.*2 = 48.\nProof.\nrewrite big_cons.\nrewrite big_cons.\nrewrite big_cons.\nrewrite big_nil.\nby [].\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n   ** Range \n    - different ranges are provided\n#<div>#\n*)\nLemma bfoldl1 : \\sum_(1 <= i < 4) i.*2 = 12.\nProof.\nhave H := big_ltn.\nhave H1 := big_geq.\nrewrite big_ltn.\n  rewrite big_ltn.\n    rewrite big_ltn.\n      rewrite big_geq.\n        by [].\n      by [].\n    by [].\n  by [].\nby [].\nQed.\n\nLemma bfoldl2 : \\sum_(i < 4) i.*2 = 12.\nProof.\nrewrite big_ord_recl.\nrewrite /=.\nrewrite big_ord_recl.\nrewrite /=.\nrewrite big_ord_recl.\nrewrite big_ord_recl.\nrewrite big_ord0.\nby [].\nQed.\n\nLemma bfoldl3 : \\sum_(i : 'I_4) i.*2 = 12.\nProof.\nexact: bfoldl2.\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n   ** Filtering \n    - it is possible to filter elements from the range \n#<div>#\n*)\nLemma bfoldl4 : \\sum_(i <- [::1; 2; 3; 4; 5; 6] | ~~ odd i) i = 12.\nProof.\nhave big_pred0 := big_pred0.\nhave big_hasC := big_hasC.\npose x :=  \\sum_(i < 8 | ~~ odd i) i.\npose y :=  \\sum_(0 <= i < 8 | ~~ odd i) i.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_nil.\nby [].\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n   ** Switching range\n    - it is possible to change representation (big_nth, big_mkord).\n#<div>#\n*)\nLemma bswitch :  \\sum_(i <- [::1; 2; 3]) i.*2 = \\sum_(i < 3) (nth 0 [::1; 2; 3] i).*2.\nProof.\nhave H := big_nth.\nrewrite (big_nth 0).\nrewrite /=.\nhave H1 := big_mkord.\nrewrite big_mkord.\nby [].\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Big operators and equality\n    - one can exchange function and/or predicate\n #<div>#\n*)\nLemma beql : \n  \\sum_(i < 4 | odd i || ~~ odd i) i.*2 =  \\sum_(i < 4) i.*2.\nProof.\nhave H := eq_bigl.\napply: eq_bigl.\nmove=> u.\nby case: odd.\nQed.\n\nLemma beqr : \n  \\sum_(i < 4) i.*2 = \\sum_(i < 4) (i + i).\nProof.\nhave H := eq_bigr.\napply: eq_bigr.\nrewrite /=.\nmove=> u _.\nrewrite addnn.\nby [].\nQed.\n\nLemma beq : \n  \\sum_(i < 4 | odd i || ~~ odd i) i.*2 = \\sum_(i < 4) (i + i).\nProof.\nhave H := eq_big.\napply: eq_big => [u|i Hi]; first by case: odd.\nby rewrite addnn.\n\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Monoid structure\n    - one can use associativity to reorganize the bigop\n #<div>#\n*)\nLemma bmon1 : \\sum_(i <- [::1; 2; 3]) i.*2 = 12.\nProof.\nhave H := big_cat.\nrewrite -[[::1; 2; 3]]/([::1] ++ [::2; 3]).\nrewrite big_cat.\nrewrite /=.\nrewrite !big_cons !big_nil.\nby [].\nQed.\n\nLemma bmon2 : \\sum_(1 <= i < 4) i.*2 = 12.\nProof.\nhave H := big_cat_nat.\nrewrite (big_cat_nat _ _ _ (isT: 1 <= 2)).\n  rewrite /=.\n  rewrite big_ltn //=.\n  rewrite big_geq //.\n  by rewrite 2?big_ltn //= big_geq.\nby [].\nQed.\n\nLemma bmon3 : \\sum_(i < 4) i.*2 = 12.\nProof.\nhave H := big_ord_recl.\nhave H1 := big_ord_recr.\nrewrite big_ord_recr.\nrewrite /=.\nrewrite !big_ord_recr //=.\nrewrite big_ord0.\nby [].\nQed.\n\nLemma bmon4 : \\sum_(i < 8 | ~~ odd i) i = 12.\nProof.\nhave H := big_mkcond.\nrewrite big_mkcond.\nrewrite /=.\nrewrite !big_ord_recr /=.\nrewrite big_ord0.\nby [].\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Abelian Monoid structure\n    - one can use communitativity to massage the bigop\n #<div>#\n*)\n\nLemma bab : \\sum_(i < 4) i.*2 = 12.\nProof.\nhave H := bigD1.\npose x := Ordinal (isT: 2 < 4).\nrewrite (bigD1 x).\n  rewrite /=.\n  rewrite big_mkcond /=.\n  rewrite !big_ord_recr /= big_ord0.\n  by [].\nby [].\nQed.\n\nLemma bab1 : \\sum_(i < 4) (i + i.*2) = 18.\nProof.\nhave H := big_split.\nrewrite big_split /=.\nrewrite !big_ord_recr ?big_ord0 /=.\nby [].\nQed.\n\nLemma bab2 : \\sum_(i < 3) \\sum_(j < 4) (i + j) =\n                 \\sum_(i < 4) \\sum_(j < 3) (i + j).\nProof.\nhave H := exchange_big.\nhave H1 := reindex_inj.\nrewrite exchange_big.\nrewrite /=.\napply: eq_bigr.\nmove=> i _.\napply: eq_bigr.\nmove=> j _.\nby rewrite addnC.\nQed.\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Distributivity\n    - one can exchange sum and product\n #<div>#\n*)\nLemma bab3 : \\sum_(i < 4) (2 * i) = 2 * \\sum_(i < 4) i.\nProof.\nhave H := big_distrr.\nby rewrite big_distrr.\nQed.\n\nLemma bab4 : \n  (\\prod_(i < 3) \\sum_(j < 4) (i ^ j)) = \n  \\sum_(f : {ffun 'I_3 -> 'I_4}) \\prod_(i < 3) (i ^ (f i)).\nProof.\nhave H := big_distr_big.\nhave H1 := big_distr_big_dep.\nrewrite  (big_distr_big ord0).\nrewrite /=.\napply: eq_bigl.\nmove=> f.\nrewrite /=.\napply/forallP.\nrewrite /=.\nby [].\nQed.\n\n\n(**\n#</div>#\n#</div>#\n----\n#<div class=\"slide\">#\n  ** Property, Relation and Morphism\n #<div>#\n*)\nLemma bap n : ~~ odd (\\sum_(i < n) i.*2). \nProof.\nhave H := big_ind.\nhave H1 := big_ind2.\nhave H2 := big_morph.\nelim/big_ind: _.\n- by [].\n- move=> x y.\n  rewrite odd_add.\n  case: odd.\n     by [].\n  by [].\nmove=> i _.\nby rewrite odd_double.\nQed.\n(**\n#</div>#\n#</div>#\n*)\n\n\n", "meta": {"author": "gares", "repo": "COQWS17", "sha": "babcf965035f24fa00bbe69497361e9c8144ae97", "save_path": "github-repos/coq/gares-COQWS17", "path": "github-repos/coq/gares-COQWS17/COQWS17-babcf965035f24fa00bbe69497361e9c8144ae97/lesson3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7434544492999302}}
{"text": "(* 3 - Case Analysis and Pattern-matching *)\n\n\n(* 3.1 Non-dependent Case Analysis *)\n\n(* An elimination rule for the type A is some way to use an object a : A in\n   order to define an object in some type B. A natural elimination for an\n   inductive type is case analysis.\n\n   For instance, any value of type nat is built using either O or S. Thus, a\n   systematic way of building a value of type B from any value of type nat is\n   to associate to O a constant t0 : B, and to every term of the form 'S p'\n   a term ts : B. The following construction has type B:\n\n     match n return B with\n     | O => t0\n     | S p => ts\n     end\n\n    In most of the case, Coq is able to infer the type B of the object\n    defined, so the 'return B' part may be omitted. The computing rules\n    associated with construct are the expected ones:\n\n      match O return B with O => t0 | S p => ts end ==> to\n\n      match S q return B with O => t0 | S p => ts end ==> ts{q/p} *)\n\n\n(* 3.2 Dependent Case Analysis *)\n\n(* For a pattern matching construct of the form 'match n with ... end', a\n   more general typing rule is obtained considering that the type of the\n   whole expression may also depend on n. For instance, consider some\n   function Q : nat -> Set, and n : nat. In order to build a term of type Q n,\n   we can associate to the constructor O some term tO : Q O and to the pattern\n   'S p' some term tS : Q (S p). Note that the terms tO and tS do not have\n   the same type. The syntax of the dependent case analysis and its\n   associated typing rule are as follows:\n\n     Q : nat -> Set    tO : Q O    p : nat |- tp : Q (S p)    n : nat\n    ------------------------------------------------------------------\n     match n as nO return Q nO with | O => tO | S p => tS end : Q n\n\n   The former, non-dependent version of case analysis can be obtained from\n   this latter rule by taking Q as a constant function on n. *)\n\n(* Strong specification of the predecessor function *)\nDefinition pred_spec (n : nat) :=\n  { m : nat | n = O /\\ m = O \\/ n = S m }.\n\nDefinition predecessor : forall n : nat, pred_spec n.\n  intro n; case n.\n  unfold pred_spec; exists O; auto.\n  unfold pred_spec; intro n'; exists n'; auto.\nDefined.\n\nPrint predecessor.\nExtraction predecessor.\n\n(* Exercise 3.1 *)\nTheorem nat_expand : forall n : nat,\n  n = match n with\n      | O => O\n      | S p => S p\n      end.\nProof.\n  intro n; induction n; reflexivity.\nQed.\n\n(* The Empty type *)\n\n(* The rule of (non-dependent) case analysis for the type False is (for\n   s in Prop, Set or Type):\n\n     Q : s    p : False\n    --------------------\n     match p return Q with end : Q\n*)\n\nTheorem fromFalse : False -> 0 = 1.\nProof. intros; contradiction. Qed.\n\nPrint not.\n\nFact Nosense : O <> O -> 2 = 3.\nProof. intro H; case H; reflexivity. Qed.\n", "meta": {"author": "vishallama", "repo": "coinductive-types", "sha": "0bdea52f015b48f6bad8801f54c4acb3dc3acf70", "save_path": "github-repos/coq/vishallama-coinductive-types", "path": "github-repos/coq/vishallama-coinductive-types/coinductive-types-0bdea52f015b48f6bad8801f54c4acb3dc3acf70/src/CaseAnalysisAndPatternMatching.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7434141134154484}}
{"text": "(** * Phi : Hofstadter G function and the golden ratio *)\n\nRequire Import Arith Fourier R_Ifp R_sqrt Znumtheory Omega.\nRequire Import Fib FunG.\n\nOpen Scope Z.\nOpen Scope R.\n\n(** We consider again the function [g] defined by\n    [g 0 = 0] and [g (S n) = S n - g (g n)],\n    and we prove that it can also be directly defined\n    via primitives using reals numbers:\n\n    [g(n) = floor((n+1)/phi) = floor(tau*(n+1))]\n\n    where:\n     - [phi = (1+sqrt(5))/2]\n     - [tau = 1/phi = phi-1 = (sqrt(5)-1)/2]\n\n    In Coq, we'll use here by default operations on reals numbers,\n    and also:\n     - [INR] : the injection from [nat] to [R]\n     - [IZR] : the injection from [Z] to [R]\n     - [Int_part] : the integer part of a real, used as a [floor]\n       function. It produces a [Z] integer, that we can convert\n       to [nat] via [Z.to_nat] when necessary.\n     - [frac_part] : the faction part of a real, producing a [R]\n*)\n\n(** * Phi and tau *)\n\nDefinition phi := (sqrt 5 + 1)/2.\nDefinition tau := (sqrt 5 - 1)/2.\n\nLemma tau_1 : tau + 1 = phi.\nProof.\n unfold tau, phi. field.\nQed.\n\nLemma tau_phi : tau * phi = 1.\nProof.\nunfold tau, phi.\nreplace ((sqrt 5 - 1)/2 * ((sqrt 5 + 1)/2))\nwith ((sqrt 5 * sqrt 5 - 1)/4) by field.\nrewrite sqrt_def. field. fourier.\nQed.\n\nLemma tau_tau : tau * tau = 1 - tau.\nProof.\n rewrite <- tau_phi, <- tau_1. ring.\nQed.\n\nLemma tau_nz : tau <> 0.\nProof.\n intro E. generalize tau_phi. rewrite E. intros. fourier.\nQed.\n\nLemma phi_nz : phi <> 0.\nProof.\n intro E. generalize tau_phi. rewrite E. intros. fourier.\nQed.\n\nLemma tau_inv : tau = 1/phi.\nProof.\n rewrite <- tau_phi. field. apply phi_nz.\nQed.\n\nLemma tau_bound : 6/10 < tau < 7/10.\nProof.\n unfold tau.\n assert (11/5 < sqrt 5).\n { replace (11/5) with (sqrt ((11/5)*(11/5))).\n   apply sqrt_lt_1; fourier.\n   apply sqrt_Rsqr. fourier. }\n assert (sqrt 5 < 12/5).\n { replace (12/5) with (sqrt ((12/5)*(12/5))).\n   apply sqrt_lt_1; fourier.\n   apply sqrt_Rsqr. fourier. }\n split.\n - apply Rmult_lt_reg_l with 2. fourier.\n   apply Rplus_lt_reg_r with 1.\n   field_simplify. fourier.\n - apply Rmult_lt_reg_l with 2. fourier.\n   apply Rplus_lt_reg_r with 1.\n   field_simplify. fourier.\nQed.\n\n(** * A bit of irrationality theory *)\n\nLemma prime_5 : prime 5.\nProof.\n constructor.\n - omega.\n - intros n Hn. apply Zgcd_1_rel_prime.\n   assert (n=1 \\/ n=2 \\/ n=3 \\/ n=4)%Z by omega.\n   intuition; now subst.\nQed.\n\nLemma prime_irr (r:R) :\n (forall (p q:Z), Z.gcd p q = 1%Z -> r * IZR q <> IZR p) ->\n (forall (p q:Z), r * IZR q = IZR p -> q=0%Z).\nProof.\n intros H p q.\n generalize (Z.ggcd_gcd p q) (Z.ggcd_correct_divisors p q)\n (Z.gcd_nonneg p q).\n destruct (Z.ggcd p q) as (g,(p',q')). simpl.\n intros G (Hp,Hq) NN Eq. rewrite <- G in NN.\n subst p; subst q.\n destruct (Z.eq_dec g 0) as [E|N]; [subst; trivial|exfalso].\n apply (H p' q').\n - rewrite Z.gcd_mul_mono_l_nonneg in G by trivial.\n   apply Z.mul_reg_l with g; omega.\n - rewrite !mult_IZR in Eq.\n   apply Rmult_eq_reg_l with (IZR g). rewrite <- Eq. ring.\n   now apply not_0_IZR.\nQed.\n\nLemma sqrt5_irr (p q:Z) : sqrt 5 * IZR q = IZR p -> q = 0%Z.\nProof.\n apply prime_irr. clear p q. intros p q Hpq Eq.\n assert (Eq' : (p*p = 5 * q*q)%Z).\n { apply eq_IZR; rewrite !mult_IZR, <-!Eq.\n   replace (IZR 5) with 5 by (simpl; Rcompute).\n   rewrite <- (sqrt_def 5) at 3. ring. fourier. }\n assert (Hpp : (5 | p*p)). { exists (q*q)%Z. rewrite Eq'. ring. }\n assert (Hp : (5 | p)).\n { apply prime_mult in Hpp; intuition. apply prime_5. }\n case Hp. intros p' Hp'.\n assert (Hqq : (5 | q*q)).\n { exists (p'*p')%Z. apply Z.mul_reg_l with 5%Z. omega.\n   rewrite Z.mul_assoc, <- Eq', !Hp'. ring. }\n assert (Hq : (5 | q)).\n { apply prime_mult in Hqq; intuition. apply prime_5. }\n assert (H : (5 | 1)).\n { rewrite <- Hpq. apply Z.gcd_greatest; auto. }\n destruct H as (x,Hx). omega.\nQed.\n\nLemma tau_irr (p q:Z) : tau * IZR q = IZR p -> q = 0%Z.\nProof.\n unfold tau.\n intros Eq.\n apply sqrt5_irr with (2*p+q)%Z.\n rewrite plus_IZR, mult_IZR. simpl (IZR 2).\n rewrite <- Eq. field.\nQed.\n\n(** * Some complements about integer part and fractional part *)\n\nLemma int_part_iff (r:R)(k:Z) :\n 0 <= r-IZR k < 1 <-> Int_part r = k.\nProof.\n split.\n - unfold Int_part.\n   intros (H1,H2).\n   assert (k+1 = up r)%Z; [|omega].\n   apply tech_up; rewrite plus_IZR; simpl; fourier.\n - intros <-. destruct (base_Int_part r). split; fourier.\nQed.\n\nLemma int_part_carac (r:R)(k:Z) :\n 0 <= r-IZR k < 1 -> Int_part r = k.\nProof.\n apply int_part_iff.\nQed.\n\nLemma int_frac r : r = IZR (Int_part r) + frac_part r.\nProof.\n unfold frac_part. ring.\nQed.\n\nLemma int_part_le (r:R)(k:Z) : IZR k <= r <-> (k <= Int_part r)%Z.\nProof.\n split.\n - intros.\n   destruct (base_Int_part r).\n   assert (E : IZR k - 1 < IZR (Int_part r)) by fourier.\n   change 1 with (IZR 1) in E.\n   rewrite <- minus_IZR in E.\n   apply lt_IZR in E. omega.\n - destruct (base_Int_part r).\n   intros LE. apply IZR_le in LE. fourier.\nQed.\n\n(** * The main theorem *)\n\nLemma g_tau (n:nat) : g n = Z.to_nat (Int_part (tau * INR (S n))).\nProof.\ninduction n as [n IH] using lt_wf_rec.\ndestruct (eq_nat_dec n 0) as [Hn|Hn].\n- subst. change (g 0) with O. simpl.\n  replace (tau*1) with tau by ring.\n  rewrite (int_part_carac tau 0); simpl; trivial.\n  destruct tau_bound; split; fourier.\n- assert (0 < INR n). { apply (lt_INR 0). omega. }\n  assert (0 <= Int_part (tau * INR n))%Z.\n  { apply int_part_le. simpl. destruct tau_bound.\n    apply Rmult_le_pos; fourier. }\n  set (k:=Z.to_nat (Int_part (tau*INR n))).\n  set (d:=frac_part (tau*INR n)).\n  replace n with (S (n-1)) at 1 by omega.\n  rewrite g_S.\n  replace (S (n-1)) with n by omega.\n  assert (E : g (n-1) = k).\n  { rewrite IH by omega. now replace (S (n-1)) with n by omega. }\n  rewrite E.\n  assert (k <= n-1)%nat by (rewrite <-E; apply g_le).\n  assert (g k < n)%nat by (generalize (g_le k); omega).\n  symmetry. apply plus_minus.\n  rewrite IH by omega.\n  assert (Hd : d <> 0).\n  { unfold d. contradict Hn.\n    generalize (int_frac (tau*INR n)). rewrite Hn.\n    rewrite INR_IZR_INZ at 1. intros Eq.\n    apply Nat2Z.inj. simpl.\n    apply tau_irr with (Int_part (tau * INR n)).\n    rewrite Eq. ring. }\n  assert (Hd' : 0 < d < 1).\n  { unfold d. destruct (base_fp (tau*INR n)) as (Hd1,Hd2).\n    unfold d in *. destruct Hd1; intuition. }\n  destruct Hd' as (Hd1,Hd2).\n  destruct tau_bound.\n  generalize tau_1; intro.\n  assert (Eq : INR k = tau*INR n - d).\n  { unfold d, k. revert H0. generalize (tau * INR n). clear.\n    intros r Hr. rewrite INR_IZR_INZ. rewrite Z2Nat.id; auto.\n    rewrite (int_frac r) at 2. ring. }\n  destruct (Rle_or_lt d (1-tau)) as [[LT|EQ]|LT].\n  + rewrite (int_part_carac (tau*INR(S k)) (Z.of_nat (n-k))).\n    rewrite (int_part_carac (tau*INR(S n)) (Z.of_nat k)).\n    rewrite !Nat2Z.id. omega.\n    * rewrite <- INR_IZR_INZ.\n      rewrite S_INR. rewrite Rmult_plus_distr_l.\n      rewrite Eq. split; fourier.\n    * rewrite <- INR_IZR_INZ, minus_INR, S_INR, Eq by omega.\n      replace (_ - _) with (tau-(tau+1)*d) by (ring [tau_tau]).\n      rewrite tau_1.\n      assert (0 <= phi*d <= tau); [split|intuition fourier].\n      { apply Rmult_le_pos; fourier. }\n      { replace tau with (phi*(1-tau)).\n        apply Rmult_le_compat_l; fourier.\n        rewrite <- tau_1. ring [tau_tau]. }\n  + rewrite EQ in Eq.\n    assert (Z.of_nat n + 1 = 0)%Z.\n    apply tau_irr with (Z.of_nat k + 1)%Z.\n    rewrite !plus_IZR. simpl.\n    rewrite <- !INR_IZR_INZ.\n    rewrite Rmult_plus_distr_l. rewrite Eq. ring.\n    omega.\n  + rewrite (int_part_carac (tau*INR(S k)) (Z.of_nat (n-k-1))).\n    rewrite (int_part_carac (tau*INR(S n)) (Z.of_nat (S k))).\n    rewrite !Nat2Z.id. omega.\n    * rewrite <- INR_IZR_INZ.\n      rewrite !S_INR. rewrite Rmult_plus_distr_l.\n      rewrite Eq. split; fourier.\n    * rewrite <- INR_IZR_INZ, !minus_INR, S_INR, Eq by omega.\n      simpl INR.\n      replace (_ - _) with ((tau+1)*(1-d)) by (ring [tau_tau]).\n      split.\n      { apply Rmult_le_pos; fourier. }\n      { rewrite <- tau_phi at 3. rewrite Rmult_comm, tau_1.\n        apply Rmult_lt_compat_r; fourier. }\nQed.\n\nLemma g_phi (n:nat) : g n = Z.to_nat (Int_part (INR (S n)/phi)).\nProof.\n rewrite g_tau. do 2 f_equal. rewrite tau_inv. field.\n apply phi_nz.\nQed.\n", "meta": {"author": "letouzey", "repo": "hofstadter_g", "sha": "7854882e3ab8beb33b5a7c40499f64c5805a23af", "save_path": "github-repos/coq/letouzey-hofstadter_g", "path": "github-repos/coq/letouzey-hofstadter_g/hofstadter_g-7854882e3ab8beb33b5a7c40499f64c5805a23af/Phi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.743414098341252}}
{"text": "\nTheorem Ex018 (A B C: Prop): (A \\/ B) \\/ C <-> A \\/ (B \\/ C).\nProof.\n  split.\n  + intro.\n    destruct H.\n    - destruct H.\n      * left. exact H.\n      * right. left. exact H.\n    - right. right. exact H.\n  + intro. \n    destruct H.\n    - left. left. exact H.\n    - destruct H.\n      * left. right. exact H.\n      * right. exact H.\nQed.", "meta": {"author": "SvenWille", "repo": "CoqLogicExercises", "sha": "b4c1aea30abb95dc7ba81fa42ccb914d534d65e5", "save_path": "github-repos/coq/SvenWille-CoqLogicExercises", "path": "github-repos/coq/SvenWille-CoqLogicExercises/CoqLogicExercises-b4c1aea30abb95dc7ba81fa42ccb914d534d65e5/src/propLogic/Ex018.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7433695000368306}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type :=Zero : natural | Succ : natural -> natural .\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint exp (exp_arg0 : natural) (exp_arg1 : natural) : natural\n           := match exp_arg0, exp_arg1 with\n              | n, Zero => Succ Zero\n              | n, Succ m => mult (exp n m) n\n              end.\n\nFixpoint qexp (qexp_arg0 : natural) (qexp_arg1 : natural) (qexp_arg2 : natural) : natural\n           := match qexp_arg0, qexp_arg1, qexp_arg2 with\n              | n, Zero, m => m\n              | n, Succ m, p => qexp n m (mult p n)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\n   intros.\n   induction x.\nlfind.  reflexivity. \nAdmitted.\n\nLemma mult_zero : forall (x : natural), mult x Zero = Zero.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma mult_succ : forall (x y : natural), plus (mult x y) x = mult x (Succ y).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite plus_succ. rewrite plus_assoc. rewrite (plus_commut y x). rewrite <- plus_assoc. rewrite IHx. rewrite plus_succ. reflexivity.\nQed.\n\nLemma mult_commut : forall (x y : natural), mult x y = mult y x.\nProof.\n   intros.\n   induction x.\n   - rewrite mult_zero. reflexivity.\n   - simpl. rewrite IHx. rewrite mult_succ. reflexivity.\nQed.\n\nLemma distrib : forall (x y z : natural), mult (plus x y) z = plus (mult x z) (mult y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. rewrite plus_assoc. rewrite (plus_commut (mult y z) z). rewrite <- plus_assoc. reflexivity.\nQed.\n\nLemma mult_assoc : forall (x y z : natural), mult (mult x y) z = mult x (mult y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite distrib. rewrite IHx. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (z : natural), eq (mult (exp x y) z) (qexp x y z).\nProof.\n   intros.\n   generalize dependent z.\n   induction y.\n   - reflexivity.\n   - intros. simpl. rewrite <- IHy. rewrite mult_assoc. rewrite (mult_commut x z). reflexivity.\nQed.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal86_plus_commut_63_plus_zero/goal86.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7433142513595552}}
{"text": "(** Cheat sheet available at\n      #<a href='https://www-sop.inria.fr/teams/marelle/types18/cheatsheet.pdf'>https://www-sop.inria.fr/teams/marelle/types18/cheatsheet.pdf</a>#\n*)\n\nFrom mathcomp Require Import all_ssreflect.\n\nImplicit Type p q r : bool.\nImplicit Type m n a b c : nat.\n\n(**\n-----------------------------------------------------------------\n#<div class=\"slide\">#\n*** Exercise 1:\n    - prove this satement by induction\n#<div>#\n*)\nLemma iterSr A n (f : A -> A) x : iter n.+1 f x = iter n f (f x).\nAdmitted.\n\n(**\n#</div>#\n\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n\n*** Exercise 2:\n    - look up the definition of [iter] (note there is an accumulator varying\n      during recursion)\n    - prove the following statement by induction\n\n#<div>#\n*)\nLemma iter_predn m n : iter n predn m = m - n.\nProof.\nAdmitted.\n(**\n#</div>#\n\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n\n*** Exercise 3:\n\nProve the sum of the lists [odds n] of exercise 1 is [n ^ 2].\n\nYou can prove the following lemmas in any order, some are way easier\nthan others.\n\n- Recall from exercise 1.\n#<div>#\n\n*)\nDefinition add2list s := map (fun x => x.+2) s.\nDefinition odds n := iter n (fun s => 1 :: add2list s) [::].\n(**\n#</div>#\n\n- We define a sum operation [suml].\n\n#<div>#\n\n*)\nDefinition suml := foldl addn 0.\n(**\n#</div>#\n\n- Any [foldl addn] can be rexpressed as a sum.\n\n#<div>#\n*)\nLemma foldl_addE n s : foldl addn n s = n + suml s.\nProof.\nAdmitted.\n(**\n#</div>#\n\n\n- Not to break abstraction, prove [suml_cons].\n#<div>#\n*)\nLemma suml_cons n s : suml (n :: s) = n + suml s.\nAdmitted.\n(**\n#</div>#\n\n- Show how to sum a [add2list].\n\n#<div>#\n*)\nLemma suml_add2list s : suml (add2list s) = suml s + 2 * size s.\nProof.\nAdmitted.\n(**\n#</div>#\n\n- Show the size of a [add2list].\n\n#<div>#\n*)\nLemma size_add2list s : size (add2list s) = size s.\nAdmitted.\n(**\n#</div>#\n\n- Show how many elments [odds] have.\n\n#<div>#\n*)\nLemma size_odds n : size (odds n) = n.\nAdmitted.\n(**\n#</div>#\n- Show the final statment.\n#<div>#\n*)\nLemma eq_suml_odds n : suml (odds n) = n ^ 2.\nProof.\nAdmitted.\n(**\n#</div>#\n#<br/>#\n#<div class=\"note\">(hint)<div class=\"note-text\">#\nFor [eq_suml_odds], use [sqrnD]\n#</div></div>#\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n\n*** Exercise 4:\n\nProve the sum of the lists [odds n] is what you think.\n\nYou may want to have at least one itermediate lemma to prove [oddsE]\n#<div>#\n*)\nLemma oddsE n : odds n = [seq 2 * i + 1 | i <- iota 0 n].\nProof.\nAdmitted.\n(**\n#</div>#\n#<br/>#\n#<div class=\"note\">(hint)<div class=\"note-text\">#\nthis intermediate lemma would be:\n#<div>#\n*)\nLemma oddsE_aux n k :\n  iter n (fun s : seq nat => 2 * k + 1 :: add2list s) [::] =\n  [seq 2 * i + 1 | i <- iota k n].\nAdmitted.\n(**\n#</div>#\n#</div></div>#\n#<br/>#\n#<div>#\n*)\nLemma nth_odds n i : i < n -> nth 0 (odds n) i = 2 * i + 1.\nProof.\nAdmitted.\n(**\n#</div>#\n#<p><br/><p>#\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n\n*** Exercise 5:\n\nLet us prove directly formula\n#$$ \\sum_{i=0}^{n-1} (2 i + 1) = n ^ 2 $$#\nfrom lesson 1, slightly modified.\n\nLet us first define a custom sum operator:\n#<div>#\n*)\nDefinition mysum m n F := (foldr (fun i a => F i + a) 0 (iota m (n - m))).\n\nNotation \"\\mysum_ ( m <= i < n ) F\" := (mysum m n (fun i => F))\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\mysum_ ( m  <=  i  <  n ) '/  '  F ']'\").\n(**\n#</div>#\n- First prove a very useful lemma about summation\n#<div>#\n*)\nLemma mysum_recl m n F : m <= n ->\n  \\mysum_(m <= i < n.+1) F i = \\mysum_(m <= i < n) F i + F n.\nProof.\nAdmitted.\n(**\n#</div>#\n- Now prove the main result\n\nDo NOT use [eq_suml_odds] above, it would take much more time\n\n#<div>#\n*)\nLemma sum_odds n : \\mysum_(0 <= i < n) (2 * i + 1) = n ^ 2.\nProof.\nAdmitted.\n(**\n#</div>#\n#<p><br/><p>#\n#</div>#\n*)", "meta": {"author": "math-comp", "repo": "tutorial_material", "sha": "3e5fcef3a25d2a43115fb645645b437640624ad3", "save_path": "github-repos/coq/math-comp-tutorial_material", "path": "github-repos/coq/math-comp-tutorial_material/tutorial_material-3e5fcef3a25d2a43115fb645645b437640624ad3/SummerSchoolSophia/exercise3_todo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.8991213738910259, "lm_q1q2_score": 0.7433142364192078}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\n\n(* Why3 assumption *)\nDefinition even (n:Z): Prop := exists k:Z, (n = (2%Z * k)%Z).\n\n(* Why3 assumption *)\nDefinition odd (n:Z): Prop := exists k:Z, (n = ((2%Z * k)%Z + 1%Z)%Z).\n\nLemma even_is_Zeven :\n  forall n, even n <-> Zeven n.\nProof.\nintros n.\nrefine (conj _ (Zeven_ex n)).\nintros (k,H).\nrewrite H.\napply Zeven_2p.\nQed.\n\nLemma odd_is_Zodd :\n  forall n, odd n <-> Zodd n.\nProof.\nintros n.\nrefine (conj _ (Zodd_ex n)).\nintros (k,H).\nrewrite H.\napply Zodd_2p_plus_1.\nQed.\n\n(* Why3 goal *)\nLemma even_or_odd : forall (n:Z), (even n) \\/ (odd n).\nProof.\nintros n.\ndestruct (Zeven_odd_dec n).\nleft.\nnow apply <- even_is_Zeven.\nright.\nnow apply <- odd_is_Zodd.\nQed.\n\n(* Why3 goal *)\nLemma even_not_odd : forall (n:Z), (even n) -> ~ (odd n).\nProof.\nintros n H1 H2.\napply (Zeven_not_Zodd n).\nnow apply -> even_is_Zeven.\nnow apply -> odd_is_Zodd.\nQed.\n\n(* Why3 goal *)\nLemma odd_not_even : forall (n:Z), (odd n) -> ~ (even n).\nProof.\nintros n H1.\ncontradict H1.\nnow apply even_not_odd.\nQed.\n\n(* Why3 goal *)\nLemma even_odd : forall (n:Z), (even n) -> (odd (n + 1%Z)%Z).\nProof.\nintros n H.\napply <- odd_is_Zodd.\napply Zeven_plus_Zodd.\nnow apply -> even_is_Zeven.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma odd_even : forall (n:Z), (odd n) -> (even (n + 1%Z)%Z).\nProof.\nintros n H.\napply <- even_is_Zeven.\napply Zodd_plus_Zodd.\nnow apply -> odd_is_Zodd.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma even_even : forall (n:Z), (even n) -> (even (n + 2%Z)%Z).\nProof.\nintros n H.\napply <- even_is_Zeven.\napply Zeven_plus_Zeven.\nnow apply -> even_is_Zeven.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma odd_odd : forall (n:Z), (odd n) -> (odd (n + 2%Z)%Z).\nProof.\nintros n H.\napply <- odd_is_Zodd.\napply Zodd_plus_Zeven.\nnow apply -> odd_is_Zodd.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma even_2k : forall (k:Z), (even (2%Z * k)%Z).\nProof.\nintros k.\nnow exists k.\nQed.\n\n(* Why3 goal *)\nLemma odd_2k1 : forall (k:Z), (odd ((2%Z * k)%Z + 1%Z)%Z).\nProof.\nintros k.\nnow exists k.\nQed.\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/number/Parity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7433003247004456}}
{"text": "Require Import Reals Coquelicot.Coquelicot.\nRequire Import Streams.\n\nRequire Import Lra Lia.\n\nRequire Import Utils.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n(* main results:\n  Definition Standard_Gaussian_PDF (t:R) := (/ (sqrt (2*PI))) * exp (-t^2/2).\n\n  Lemma Standard_Gaussian_PDF_normed : \n     is_RInt_gen Standard_Gaussian_PDF (Rbar_locally m_infty) (Rbar_locally p_infty) 1.\n\n  Definition Standard_Gaussian_CDF (t:Rbar) := \n      RInt_gen Standard_Gaussian_PDF (Rbar_locally m_infty) (at_point t).\n\n  Lemma std_CDF_from_erf :\n     forall x:R, Standard_Gaussian_CDF x = (/ 2) + (/2)*erf (x/sqrt 2).\n\n  Lemma mean_standard_gaussian :\n     is_RInt_gen (fun t => t*Standard_Gaussian_PDF t) \n           (Rbar_locally m_infty) (Rbar_locally p_infty) 0.\n   \n  Lemma variance_standard_gaussian :\n     is_RInt_gen (fun t => t^2*Standard_Gaussian_PDF t) \n           (Rbar_locally m_infty) (Rbar_locally p_infty) 1.\n\n  CoFixpoint mkGaussianStream (uniformStream : Stream R) : Stream R\n\n  Lemma General_Gaussian_PDF_normed (mu sigma:R) : \n     sigma>0 ->\n     ex_RInt_gen Standard_Gaussian_PDF (Rbar_locally' m_infty) (at_point (- mu / sigma)) ->\n     ex_RInt_gen Standard_Gaussian_PDF (at_point (- mu / sigma)) (Rbar_locally' p_infty) ->\n     is_RInt_gen (General_Gaussian_PDF mu sigma) (Rbar_locally' m_infty) (Rbar_locally' p_infty) 1.\n\n  Lemma mean_general_gaussian (mu sigma:R) :\n    sigma > 0 ->\n    ex_RInt_gen Standard_Gaussian_PDF (Rbar_locally' m_infty) (at_point (- mu / sigma)) ->\n    ex_RInt_gen Standard_Gaussian_PDF (at_point (- mu / sigma)) (Rbar_locally' p_infty) ->\n\n    is_RInt_gen (fun t => t*General_Gaussian_PDF mu sigma t) \n                           (Rbar_locally' m_infty) (Rbar_locally' p_infty) mu.\n \n  Lemma variance_general_gaussian (mu sigma : R) :\n    sigma > 0 ->\n    ex_RInt_gen (fun t : R => sigma ^ 2 * t ^ 2 * Standard_Gaussian_PDF t)\n              (Rbar_locally' m_infty) (at_point (- mu / sigma)) ->\n    ex_RInt_gen (fun t : R => sigma ^ 2 * t ^ 2 * Standard_Gaussian_PDF t)\n              (at_point (- mu / sigma)) (Rbar_locally' p_infty) ->\n    is_RInt_gen (fun t => (t-mu)^2*General_Gaussian_PDF mu sigma t) \n              (Rbar_locally' m_infty) (Rbar_locally' p_infty) (sigma^2).\n\n  Lemma Uniform_normed (a b:R) :\n    a < b -> is_RInt_gen (Uniform_PDF a b) (Rbar_locally' m_infty) (Rbar_locally' p_infty) 1.\n\n  Lemma Uniform_mean (a b:R) :\n    a < b -> is_RInt_gen (fun t => t*(Uniform_PDF a b t)) (Rbar_locally' m_infty) (Rbar_locally' p_infty) ((b+a)/2).\n\n  Lemma Uniform_variance (a b:R) :\n    a < b -> is_RInt_gen (fun t => (t-(b+a)/2)^2*(Uniform_PDF a b t)) (Rbar_locally' m_infty) (Rbar_locally' p_infty) ((b-a)^2/12).\n\n*)\n\nLocal Open Scope R_scope.\nImplicit Type f : R -> R.\n\nSection Gaussian_defs.\n\nDefinition erf' (x:R) := (2 / sqrt PI) * exp(-x^2).\nDefinition erf (x:R) := RInt erf' 0 x.\n\n(* following is standard normal density, i.e. has mean 0 and std=1 *)\n(* CDF(x) = RInt_gen Standard_Gaussian_PDF (Rbar_locally m_infty) (Rbar_locally x) *)\nDefinition Standard_Gaussian_PDF (t:R) := (/ (sqrt (2*PI))) * exp (-t^2/2).\n\n(* general gaussian density with mean = mu and std = sigma *)\nDefinition General_Gaussian_PDF (mu sigma t : R) :=\n   (/ (sigma * (sqrt (2*PI)))) * exp (- (t - mu)^2/(2*sigma^2)).\n\nDefinition Standard_Gaussian_CDF (t:R) := \n  RInt_gen Standard_Gaussian_PDF (Rbar_locally m_infty) (at_point t).\n\nDefinition General_Gaussian_CDF (mu sigma : R) (t:R) := \n  RInt_gen (General_Gaussian_PDF mu sigma) (Rbar_locally m_infty) (at_point t).\n\nEnd Gaussian_defs.\n\nLemma continuous_Standard_Gaussian_PDF :\n  forall (x:R), continuous Standard_Gaussian_PDF x.\nProof.\n  intros.\n  unfold Standard_Gaussian_PDF.\n  apply (@ex_derive_continuous).\n  now auto_derive.\nQed.\n\n\nLtac solve_derive := try solve [auto_derive; trivial | lra].\nLtac equation_simplifier := apply Rminus_diag_uniq; unfold Rsqr; simpl; field_simplify; try lra; auto with Rarith.\n\nLtac cont_helper\n  :=\n    repeat (match goal with\n            | [|- continuous (fun _ => _ * _ ) _ ] => apply @continuous_scal\n            | [|- continuous (fun _ => _ ^ 2 ) _ ] => apply @continuous_scal\n            | [|- continuous (fun _ => Hierarchy.mult _ _ ) _ ] => apply @continuous_mult\n            | [|- continuous (fun _ => _ + _ ) _ ] => apply @continuous_plus\n            | [|- continuous (fun _ => _ - _ ) _ ] => apply @continuous_minus\n            end\n            || apply continuous_id\n            || apply continuous_const\n            || apply continuous_Standard_Gaussian_PDF).\n\n\nSection Uniform_Distribution.\n\nDefinition Indicator (a b t:R) :=\n  (if Rlt_dec t a then 0 else \n     (if Rgt_dec t b then 0 else 1)).\n\nDefinition Uniform_PDF (a b t:R) := \n  (/ (b-a)) * Indicator a b t.\n\nLemma Uniform_normed0 (a b:R) :\n  a < b -> is_RInt (fun t => (/ (b-a))) a b 1.\nProof.  \n  intros.\n  replace (1) with (scal (b-a) (/ (b-a))).\n  apply (@is_RInt_const).\n  compute; field_simplify; lra.\nQed.\n\nLemma Indicator_left (a b:R) (f : R -> R) :\n  a < b -> is_RInt_gen (fun t => (f t) * (Indicator a b t)) (Rbar_locally' m_infty) (at_point a) 0.\nProof.  \n    intros.\n    unfold Indicator.\n    apply (is_RInt_gen_ext (fun _ =>  0)).\n    + exists (fun y => y<a) (fun x => x=a).\n      unfold Rbar_locally'.\n      exists (a).\n      intros; assumption.\n      now unfold at_point.\n      intros x y H0 H1.\n      unfold fst, snd.\n      subst.\n      rewrite Rmin_left; try lra.\n      rewrite Rmax_right; try lra.\n      intros.\n      destruct (Rlt_dec x0 a); try lra.\n    + apply (is_RInt_gen_ext (Derive (fun _ => 0))).\n      * apply filter_forall.\n        intros.\n        apply Derive_const.\n      * replace (0) with (0 - 0) at 1 by lra.\n        apply (is_RInt_gen_Derive (fun _ => 0) 0 0).\n        - apply filter_forall.\n           intros.\n           apply ex_derive_const.\n        - apply filter_forall.\n           intros.\n           apply continuous_const.\n        - apply filterlim_const.\n        - apply filterlim_const.\nQed.\n\nLemma Indicator_right (a b:R) (f : R -> R) :\n  a < b -> is_RInt_gen (fun t => (f t) * (Indicator a b t)) (at_point b) (Rbar_locally' p_infty)  0.\nProof.  \n    intros.\n    unfold Indicator.\n    apply (is_RInt_gen_ext (fun _ =>  0)).\n    + exists (fun x => x=b) (fun y => b<y).\n      now unfold at_point.\n      unfold Rbar_locally'.\n      exists (b).\n      intros; trivial.\n      intros x y H0 H1.\n      unfold fst, snd.\n      subst.\n      rewrite Rmin_left; try lra.\n      rewrite Rmax_right; try lra.\n      intros.\n      destruct (Rlt_dec x a); try lra.\n      destruct (Rgt_dec x b); try lra.\n    + apply (is_RInt_gen_ext (Derive (fun _ => 0))).\n      apply filter_forall.\n      intros.\n      apply Derive_const.\n      replace (0) with (0 - 0) at 1 by lra.\n      apply (is_RInt_gen_Derive (fun _ => 0) 0 0).\n      * apply filter_forall.\n        intros.\n        apply ex_derive_const.\n      * apply filter_forall.\n        intros.\n        apply continuous_const.\n      * apply filterlim_const.\n      * apply filterlim_const.\nQed.\n\nLemma Indicator_full (a b:R) (f : R -> R) (l:R):\n  a < b -> is_RInt f a b l -> is_RInt_gen (fun t => (f t) * (Indicator a b t)) (Rbar_locally' m_infty) (Rbar_locally' p_infty) l.\nProof.\n    intros.\n    replace (l) with (0 + l) by lra.\n    apply (@is_RInt_gen_Chasles) with (b:=a).\n    + apply Rbar_locally'_filter.\n    + apply Rbar_locally'_filter.    \n    + apply (is_RInt_gen_ext (fun t => (f t) * (Indicator a b t))).\n      * apply filter_forall.\n        intros.\n        now apply Rmult_eq_compat_l.\n      * now apply Indicator_left with (f := f).\n    + replace (l) with (l + 0) by lra.\n      apply (@is_RInt_gen_Chasles) with (b:=b).\n      * apply at_point_filter.\n      * apply Rbar_locally'_filter.  \n      * apply is_RInt_gen_at_point.\n        apply (is_RInt_ext f).\n        rewrite Rmin_left; try lra.\n        rewrite Rmax_right; try lra.\n        intros.\n        - unfold Indicator.\n           destruct (Rlt_dec x a).\n           lra.\n           destruct (Rgt_dec x b).\n           lra.\n           lra.\n        - trivial.\n      * now apply Indicator_right.\nQed.\n\nLemma Uniform_full (a b:R) (f : R -> R) (l:R):\n  a < b -> is_RInt (fun t => (f t)*(/ (b-a))) a b l -> is_RInt_gen (fun t => (f t) * (Uniform_PDF a b t)) (Rbar_locally' m_infty) (Rbar_locally' p_infty) l.\nProof.\n  intros.\n  apply (is_RInt_gen_ext (fun t => (f t) * (/ (b-a)) * Indicator a b t)).\n  apply filter_forall.\n  intros.\n  unfold Uniform_PDF.\n  now ring_simplify.\n  now apply Indicator_full with (f := fun t => f t * (/ (b - a))).\nQed.\n\nLemma Uniform_PDF_non_neg (a b t :R) :\n  a < b -> Uniform_PDF a b t >= 0.\nProof.  \n  intros.\n  unfold Uniform_PDF.\n  replace (0) with ((/ (b-a)) * 0) by lra.\n  apply Rmult_ge_compat_l with (r2 := 0).\n  left.\n  apply Rinv_0_lt_compat; lra.\n  unfold Indicator.\n  destruct (Rlt_dec t a); try lra.\n  destruct (Rgt_dec t b); try lra.\nQed.\n\nLemma Uniform_normed (a b:R) :\n  a < b -> is_RInt_gen (Uniform_PDF a b) (Rbar_locally' m_infty) (Rbar_locally' p_infty) 1.\nProof.\n  intros.\n  apply (is_RInt_gen_ext (fun t => 1 * (Uniform_PDF a b t))).\n  apply filter_forall.\n  intros.\n  lra.\n  apply Uniform_full with (f := fun _ => 1) (l := 1); try lra.\n  apply (is_RInt_ext (fun t => (/ (b-a)))).\n  intros.\n  now ring_simplify.\n  now apply Uniform_normed0.\nQed.\n\nLemma Uniform_mean0 (a b:R) :\n  a < b -> is_RInt (fun t => t*(/ (b-a))) a b ((b+a)/2).\nProof.  \n    intros.\n    replace ((b+a)/2) with  (/(b-a)*(b^2/2) - (/(b-a)*(a^2/2))).\n    + apply (@is_RInt_derive) with (f := fun t => (/(b-a))*(t^2/2)).      \n      rewrite Rmin_left; try lra.\n      rewrite Rmax_right; try lra.\n      intros.\n      replace (x * (/ (b-a))) with (/(b-a) * x) by lra.\n      apply is_derive_scal with (k := /(b-a)) (f:= (fun t => t^2/2)).\n      apply (is_derive_ext (fun t => t * ((/2) * t))).\n      intros.\n      now field_simplify.\n      replace (x) with (1 * (/2 * x) + x * /2) at 2 by lra.\n      apply (@is_derive_mult) with (f := id) (g:= fun t => (/2) * t).\n      apply (@is_derive_id).\n      replace (/2) with (/2 * 1) at 1 by lra.\n      apply (@is_derive_scal).\n      apply (@is_derive_id).\n      intros.\n      apply Rmult_comm.\n      intros.\n      apply (@continuous_scal_l).\n      apply continuous_id.\n    + equation_simplifier.\nQed.\n\nLemma Uniform_mean (a b:R) :\n  a < b -> is_RInt_gen (fun t => t*(Uniform_PDF a b t)) (Rbar_locally' m_infty) (Rbar_locally' p_infty) ((b+a)/2).\nProof.\n  intros.\n  apply Uniform_full with (f := fun t => t); trivial.\n  now apply Uniform_mean0.\nQed.\n\nLemma Uniform_variance0 (a b:R) :\n  a < b -> is_RInt (fun t => (/ (b-a)) * (t-(b+a)/2)^2) a b ((b-a)^2/12).\nProof.\n    intros.\n    replace ((b-a)^2/12) with (scal (/(b-a)) ((b-a)^3/12)).\n    + apply (@is_RInt_scal) with (k := /(b-a)) (f := fun t => (t - (b+a)/2)^2) (If := (b-a)^3/12).\n      apply (is_RInt_ext (fun t => t^2 - (b+a)*t + (b+a)^2/4)).\n      * intros.\n        now field_simplify.\n      * replace ((b-a)^3/12) with ((a-b)*(b^2+4*a*b+a^2)/6 + ((b+a)^2/4)*(b-a)).\n        apply is_RInt_plus with (f:= fun t=> t^2 - (b+a)*t) (g := fun t=> (b+a)^2/4).\n        -  replace ((a - b) * (b ^ 2 + 4 * a * b + a ^ 2) / 6) with ((b^3/3-a^3/3) - (b-a)*(b+a)^2/2).\n           apply is_RInt_minus with (f := fun t => t^2) (g := fun t => (b+a)*t).\n           apply (@is_RInt_derive) with (f := fun t => t^3/3).\n           ++ intros.\n              apply (is_derive_ext (fun t => (/3) * t^3)).\n              intros; now field_simplify.\n              replace (x^2) with (/3 * (INR(3%nat) * 1 * x^2)).\n              apply is_derive_scal.\n              apply is_derive_pow with (f:=id) (n := 3%nat) (l:=1).\n              apply (@is_derive_id).\n              simpl; now field_simplify.\n           ++ rewrite Rmax_right; try lra.\n              rewrite Rmin_left; try lra.\n              intros.\n              cont_helper.\n           ++ replace ((b - a) * (b + a) ^ 2 / 2) with ((b+a)*((b^2/2-a^2/2))).\n              apply (@is_RInt_scal).\n              apply is_RInt_derive with (f:=fun x => x^2/2).\n              rewrite Rmax_right; try lra.\n              rewrite Rmin_left; try lra.\n              ** intros.\n                 apply (is_derive_ext (fun t => (/2) * t^2)).\n                 intros.\n                 now field_simplify.\n                 replace (x) with (/2 * (2 * x)) at 2 by lra.\n                 apply is_derive_scal.\n                 replace (2 * x) with (INR(2%nat) * 1 * x^1) by\n                 (simpl; field_simplify; lra).\n                 apply is_derive_pow with (f:=id) (n := 2%nat) (l:=1).\n                 apply (@is_derive_id).\n              ** rewrite Rmax_right; try lra.\n                 rewrite Rmin_left; try lra.\n                 intros.\n                 apply continuous_id.\n              ** now field_simplify.\n           ++\n              equation_simplifier.\n        -  replace ((b + a) ^ 2 / 4 * (b - a)) with (scal (b-a) ((b+a)^2/4)).\n           apply (@is_RInt_const).\n           compute; now field_simplify.\n        -  equation_simplifier.\n    + compute; field_simplify; lra.\nQed.\n\nLemma Uniform_variance (a b:R) :\n  a < b -> is_RInt_gen (fun t => (t-(b+a)/2)^2*(Uniform_PDF a b t)) (Rbar_locally' m_infty) (Rbar_locally' p_infty) ((b-a)^2/12).\nProof.\n  intros.\n  apply Uniform_full with (f := (fun t => (t-(b+a)/2)^2)); trivial.\n  apply (is_RInt_ext (fun t => (/ (b-a)) * (t-(b+a)/2)^2)).\n  intros.\n  now ring_simplify.\n  now apply Uniform_variance0.\nQed.\n\nEnd Uniform_Distribution.\n\nSection Gaussian_Distribution.\n(* standard normal distribution *)\n\nDefinition inf_sign (r:Rbar) :=\n  match r with\n  | p_infty => 1\n  | m_infty => -1\n  | _ => 0\n  end.                \n\nLemma ex_RInt_Standard_Gaussian_PDF (a b:R) :\n  ex_RInt Standard_Gaussian_PDF a b.\nProof.\n  intros.\n  apply (@ex_RInt_continuous).\n  intros.\n  apply continuous_Standard_Gaussian_PDF.\nQed.\n\nLemma Derive_exp g z : \n  ex_derive g z -> Derive (fun x => exp (g x)) z = Derive g z * exp (g z).\nProof.\n  intros.\n  rewrite Derive_comp; solve_derive; trivial.\n  rewrite <- Derive_Reals with (pr := derivable_pt_exp (g z)).\n  now rewrite derive_pt_exp.\nQed.\n\nLemma Derive_atan g z : \n  ex_derive g z -> Derive (fun x => atan (g x)) z = Derive g z / (1 + Rsqr (g z)).\nProof.\n  intros.\n  rewrite Derive_comp; solve_derive; trivial.\n  rewrite <- Derive_Reals with (pr := derivable_pt_atan (g z)).\n  rewrite derive_pt_atan.\n  unfold Rdiv.\n  now ring_simplify.\nQed.\n\nHint Resolve Rgt_not_eq : Rarith.\n\n(*                     || (rewrite Derive_div; [ | solve[solve_derive]..])*)\n\nLtac Derive_helper\n  := intros; repeat ((rewrite Derive_mult; [ | solve[solve_derive]..])\n                     || (rewrite Derive_div; solve_derive)\n                     || (rewrite Derive_plus; [ | solve[solve_derive]..])\n                     || (rewrite Derive_minus; [ | solve[solve_derive]..])\n                     || (rewrite Derive_pow; [ | solve[solve_derive]..])\n                     || rewrite Derive_id\n                     || rewrite Derive_const\n                     || (rewrite Derive_exp; [ | solve[solve_derive]..])\n                     || (rewrite Derive_atan; [ | solve[solve_derive]..])                  \n                     || rewrite Derive_opp\n                    )\n     ; try equation_simplifier; auto 3 with Rarith.\n\nLemma derive_xover_sqrt2 (x:R):\n  Derive (fun x => x/sqrt 2) x = /sqrt 2.\nProof.\n  generalize sqrt2_neq0; intros.\n  unfold Rdiv.\n  Derive_helper.\nQed.\n  \nLemma continuous_erf' :\n  forall (x:R), continuous erf' x.\nProof.\n  intros.\n  unfold erf'.\n  apply (@ex_derive_continuous).\n  now auto_derive.\nQed.\n\nLemma std_pdf_from_erf' (x:R):\n  Standard_Gaussian_PDF x = / (2*sqrt 2) * (erf' (x / sqrt 2)).\nProof.\n  unfold Standard_Gaussian_PDF.\n  unfold erf'.\n  field_simplify; auto with Rarith.\n  rewrite sqrt_mult_alt; trivial; try lra.\n  unfold Rdiv.\n  apply Rmult_eq_compat_r.\n  f_equal; field_simplify; auto with Rarith.\n  replace (sqrt 2 ^ 2) with (2); trivial.\n  rewrite <- Rsqr_pow2.  \n  rewrite -> Rsqr_sqrt with (x:=2); trivial; lra.\nQed.\n\nLemma std_pdf_from_erf (x:R):\n  Derive (fun t=> erf (t/sqrt 2)) x = 2 * Standard_Gaussian_PDF x.\nProof.\n  unfold erf.\n  assert (forall y:R, ex_RInt erf' 0 y).\n  intros.\n  apply (@ex_RInt_continuous).\n  intros.\n  apply continuous_erf'.\n  rewrite Derive_comp; solve_derive.\n  rewrite Derive_RInt.\n  rewrite derive_xover_sqrt2.\n  rewrite std_pdf_from_erf'.\n  equation_simplifier.\n  apply locally_open with (D:=fun _ => True); trivial.\n  apply open_true.\n  apply continuous_erf'.\n  unfold ex_derive.\n  exists (erf' (x / sqrt 2)).\n  apply is_derive_RInt with (a:=0).\n  apply locally_open with (D:=fun _ => True); trivial.\n  apply open_true.\n  intros.\n  now apply RInt_correct with (f:=erf') (a:=0) (b:=x0).\n  apply continuous_erf'.\nQed.\n\nHint Resolve Rlt_sqrt2_0 sqrt2_neq0 Rinv_pos : Rarith.\n\nLemma std_from_erf0 (x:R) : \n  RInt Standard_Gaussian_PDF 0 x = / 2 * erf(x/sqrt 2).\nProof.\n  unfold erf.\n  replace (/ 2 * RInt erf' 0 (x / sqrt 2)) with (scal (/ 2) (RInt erf' 0 (x / sqrt 2))).\n  - rewrite <- RInt_scal with (l := /2) (f:=erf') (a := 0) (b := x / sqrt 2).\n    + replace (0) with (/ sqrt 2 * 0 + 0) at 2 by lra.\n      replace (x / sqrt 2) with (/ sqrt 2 * x + 0) by lra.\n      rewrite <- RInt_comp_lin with (v:=0) (u:=/sqrt 2) (a:=0) (b:=x).\n      * apply RInt_ext.\n        intros.\n        rewrite std_pdf_from_erf'.\n        replace (/ sqrt 2 * x0 + 0) with  (x0/sqrt 2) by lra.\n        rewrite scal_assoc.\n        apply Rmult_eq_compat_r.\n        rewrite Rinv_mult_distr; auto with Rarith.\n        now rewrite Rmult_comm.\n      * apply ex_RInt_scal with (f := erf').\n        field_simplify; auto with Rarith.\n        apply (@ex_RInt_continuous).\n        intros.\n        apply continuous_erf'.\n    + apply (@ex_RInt_continuous).\n      intros.\n      apply continuous_erf'.\n  - reflexivity.\nQed.\n\n(* generates 2 gaussian samples from 2 uniform samples *)\n(* with mean 0 and variance 1 *)\nDefinition Box_Muller (uniform1 uniform2: R) : (R * R) :=\n  let r := sqrt (-2 * (ln uniform1)) in\n  let theta := 2 * PI * uniform2 in\n  (r * cos theta, r * sin theta).\n\nCoFixpoint mkGaussianStream (uniformStream : Stream R) : Stream R :=\n  let u1 := hd uniformStream in\n  let ust2 := tl uniformStream in\n  let u2 := hd ust2 in\n  let ust3 := tl ust2 in\n  let '(g1,g2) := Box_Muller u1 u2 in\n  Cons g1 (Cons g2 (mkGaussianStream ust3)).\n\nLemma ex_RInt_Standard_Gaussian_mean_PDF (a b:R) :\n    ex_RInt (fun t => t * (Standard_Gaussian_PDF t)) a b.\nProof.\n  intros.\n  apply (@ex_RInt_continuous).\n  intros.\n  cont_helper.\nQed.\n\nLemma ex_RInt_Standard_Gaussian_variance_PDF (a b:R) :\n    ex_RInt (fun t => t^2 * (Standard_Gaussian_PDF t)) a b.\nProof.\n  intros.\n  apply (@ex_RInt_continuous).\n  intros.\n  cont_helper.\nQed.\n\nLemma variance_exint0 (a b:Rbar) :\n  ex_RInt (fun t => (t^2-1)*Standard_Gaussian_PDF t) a b.\nProof.\n  intros.\n  assert (ex_RInt (fun t => t^2*Standard_Gaussian_PDF t - Standard_Gaussian_PDF t) a b).\n  apply ex_RInt_minus with (f := fun t=> t^2*Standard_Gaussian_PDF t)\n                           (g := Standard_Gaussian_PDF).\n  now apply ex_RInt_Standard_Gaussian_variance_PDF.\n  now apply ex_RInt_Standard_Gaussian_PDF.\n  apply ex_RInt_ext with (f := (fun t : R => t ^ 2 * Standard_Gaussian_PDF t - Standard_Gaussian_PDF t)) (g := (fun t : R => (t ^ 2 - 1) * Standard_Gaussian_PDF t)).\n  intros.\n  lra.\n  assumption.\nQed.  \n\nLemma variance_int0 (a b:Rbar) :\n  RInt (fun t => t^2*Standard_Gaussian_PDF t) a b =\n  RInt (fun t => (t^2-1)*Standard_Gaussian_PDF t) a b +\n  RInt (fun t => Standard_Gaussian_PDF t) a b.\nProof.\n  intros.\n  replace (RInt (fun t : R => t ^ 2 * Standard_Gaussian_PDF t) a b) with\n      (RInt (fun t : R => (t^2-1)*Standard_Gaussian_PDF t + Standard_Gaussian_PDF t) a b).\n  apply RInt_plus with (f := (fun t => (t^2-1)*Standard_Gaussian_PDF t))\n                       (g := (fun t => Standard_Gaussian_PDF t)).\n  apply variance_exint0; trivial.\n  now apply ex_RInt_Standard_Gaussian_PDF.\n  apply RInt_ext.\n  intros.\n  lra.\nQed.\n\n\nLemma variance_derive (x:R) : \n      Derive (fun t => -t*Standard_Gaussian_PDF t) x = (x^2-1)*Standard_Gaussian_PDF x.\nProof.\n  unfold Standard_Gaussian_PDF.\n  Derive_helper.\nQed.\n\nLemma limxexp_inv_inf : is_lim (fun t => exp(t^2/2) / t) p_infty p_infty.\nProof.\n  eapply is_lim_le_p_loc; [idtac | apply is_lim_div_exp_p].\n  unfold Rbar_locally'.\n  exists 3; intros.\n  apply Rmult_le_compat_r.\n  - left.\n    apply Rinv_0_lt_compat; lra.\n  - left.\n    apply exp_increasing.\n    simpl.\n    replace x with (x*1) at 1 by lra.\n    unfold Rdiv.\n    repeat rewrite Rmult_assoc.\n    apply Rmult_lt_compat_l; lra.\nQed.\n  \nLemma limxexp_inf : is_lim (fun t => t*exp(-t^2/2)) p_infty 0.\nProof.\n  generalize (limxexp_inv_inf); intros HH.\n  apply is_lim_inv in HH; try discriminate.\n  simpl in HH.\n  eapply is_lim_ext_loc; try apply HH.\n  intros.\n  simpl.\n  exists 0.\n  intros x xpos.\n  replace (- (x * (x * 1)) / 2) with (- ((x * (x * 1)) / 2)) by lra.\n  rewrite exp_Ropp; field.\n  split; try lra.\n  generalize (exp_pos (x * (x * 1) / 2)); lra.\nQed.\n\nLemma limxexp_minf : is_lim (fun t => t*exp(-t^2/2)) m_infty 0.\nProof.\n  generalize limxexp_inf; intros HH.\n  generalize (is_lim_comp (fun t => t*exp(-t^2/2)) Ropp m_infty 0 p_infty HH); intros HH2.\n  cut_to HH2.\n  - apply is_lim_opp in HH2.\n    simpl in HH2.\n    replace (- 0) with 0 in HH2 by lra.\n    eapply is_lim_ext; try eapply HH2.\n    intros; simpl; field_simplify.\n    do 3 f_equal.\n    lra.\n  - generalize (is_lim_id m_infty); intros HH3.\n    apply is_lim_opp in HH3.\n    simpl in HH3.\n    apply HH3.\n  - simpl.\n    exists 0; intros; discriminate.\nQed.\n\nLemma continuous_derive_gaussian_opp_mean x :\n  continuous (Derive (fun t : R => - t * Standard_Gaussian_PDF t)) x.\nProof.\n  apply (continuous_ext (fun t => (t^2-1)*Standard_Gaussian_PDF t)).\n  intros.\n  now rewrite variance_derive.\n  cont_helper.\nQed.\n\nLemma plim_gaussian_opp_mean : is_lim (fun t => - t*(Standard_Gaussian_PDF t)) p_infty 0.\nProof.\n  replace (0) with ((- / sqrt (2*PI)) * 0) by lra.  \n  unfold Standard_Gaussian_PDF.\n  apply (is_lim_ext (fun t : R => (- / sqrt (2 * PI)) * (t * exp (- t ^ 2 / 2)))).\n  intros.\n  equation_simplifier.\n  apply is_lim_scal_l with (a:=- / sqrt (2 * PI)) (l := 0).\n  apply limxexp_inf.  \nQed.  \n\nLemma mlim_gaussian_opp_mean : is_lim (fun t => - t*(Standard_Gaussian_PDF t)) m_infty 0.\nProof.\n  replace (0) with ((- / sqrt (2*PI)) * 0) by lra.  \n  unfold Standard_Gaussian_PDF.\n  apply (is_lim_ext (fun t : R => (- / sqrt (2 * PI)) * (t * exp (- t ^ 2 / 2)))).\n  intros.\n  equation_simplifier.\n  apply is_lim_scal_l with (a:=- / sqrt (2 * PI)) (l := 0).\n  apply limxexp_minf.  \nQed.\n\nLemma variance_int1_middle :\n  is_RInt_gen (fun t => (t^2-1)*Standard_Gaussian_PDF t) (Rbar_locally m_infty) (Rbar_locally p_infty) 0.\nProof.\n  apply (is_RInt_gen_ext (Derive (fun t : R => - t * Standard_Gaussian_PDF t))).\n  - simpl.\n    eapply (Filter_prod _ _ _ (fun _ => True) (fun _ => True))\n    ; simpl; eauto.\n    intros.\n    now rewrite variance_derive.\n  - replace 0 with (0 - 0) by lra.\n    apply is_RInt_gen_Derive.\n    + eapply (Filter_prod _ _ _ (fun _ => True) (fun _ => True))\n      ; simpl; eauto.\n      intros; simpl.\n      unfold Standard_Gaussian_PDF.\n      now auto_derive.\n    + eapply (Filter_prod _ _ _ (fun _ => True) (fun _ => True))\n      ; simpl; eauto.\n      intros; simpl.\n      apply continuous_derive_gaussian_opp_mean.\n    + apply mlim_gaussian_opp_mean.\n    + apply plim_gaussian_opp_mean.\n  Unshelve.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\nQed.\n\nLemma limexp_inf : is_lim (fun t => exp(t^2/2)) p_infty p_infty.\nProof.\n  eapply is_lim_le_p_loc; [idtac | apply is_lim_exp_p].\n  unfold Rbar_locally'.\n  exists 2; intros.\n  left.\n  apply exp_increasing.\n  simpl.\n  replace (x) with (x*1) at 1 by lra.\n  replace (x * (x * 1) / 2) with (x * (x / 2)) by lra.\n  apply Rmult_lt_compat_l; lra.\nQed.\n\nLemma limexp_neg_inf : is_lim (fun t => exp(-t^2/2)) p_infty 0.\nProof.\n  apply (is_lim_ext (fun t => / exp(t^2/2))).\n  intros.\n  symmetry.\n  replace (- y^2/2) with (- (y^2/2)).\n  apply exp_Ropp with (x:=y^2/2).\n  lra.\n  replace (Finite 0) with (Rbar_inv p_infty).\n  apply is_lim_inv.\n  apply limexp_inf.\n  discriminate.\n  now compute.\nQed.\n\nLemma limexp_neg_minf : is_lim (fun t => exp(-t^2/2)) m_infty 0.\nProof.\n  replace (0) with ((-1) * 0 + 0).\n  apply (is_lim_ext (fun t => exp(-(-1*t+0)^2/2))).\n  intros.\n  f_equal; now field_simplify.\n  apply is_lim_comp_lin with (a := -1) (b := 0) (f := fun t => exp(-t^2/2)).\n  replace (Rbar_plus (Rbar_mult (-1) m_infty) 0) with (p_infty).\n  replace (-1 * 0 + 0) with (0) by lra.\n  apply limexp_neg_inf.\n  rewrite Rbar_plus_0_r.\n  symmetry.\n  rewrite Rbar_mult_comm.\n  apply is_Rbar_mult_unique.\n  apply is_Rbar_mult_m_infty_neg.\n  compute; lra.\n  apply Rlt_not_eq; lra.\n  lra.\nQed.\n\nLemma Derive_opp_Standard_Gaussian_PDF (x:R):\n  Derive (fun t => - Standard_Gaussian_PDF t) x = x*Standard_Gaussian_PDF x.\nProof.\n  unfold Standard_Gaussian_PDF.\n  Derive_helper.\nQed.\n  \nLemma ex_derive_opp_Standard_Gaussian_PDF (x:R):\n  ex_derive (fun t => - Standard_Gaussian_PDF t) x.\nProof.\n  unfold Standard_Gaussian_PDF.\n  now auto_derive.\nQed.\n\nLemma continuous_Derive_opp_Standard_Gaussian_PDF (x:R):\n  continuous (Derive (fun t => - Standard_Gaussian_PDF t)) x.\nProof.\n  apply continuous_ext with (f:=fun t => t*Standard_Gaussian_PDF t).\n  symmetry.\n  apply Derive_opp_Standard_Gaussian_PDF.\n  cont_helper.\nQed.\n\nLemma mean_standard_gaussian :\n  is_RInt_gen (fun t => t*Standard_Gaussian_PDF t) \n           (Rbar_locally m_infty) (Rbar_locally p_infty) 0.\nProof.  \n  replace (0) with (0 - 0) by lra.\n  apply (is_RInt_gen_ext (Derive (fun t => - Standard_Gaussian_PDF t))).\n  apply filter_forall.\n  intros; trivial.\n  apply Derive_opp_Standard_Gaussian_PDF.\n  apply is_RInt_gen_Derive with (f := fun t => - Standard_Gaussian_PDF t) (la := 0) (lb := 0).\n  apply filter_forall.  \n  intros; trivial.\n  apply ex_derive_opp_Standard_Gaussian_PDF.\n  apply filter_forall.\n  intros; trivial.\n  apply continuous_Derive_opp_Standard_Gaussian_PDF.\n  replace (filterlim (fun t : R => - Standard_Gaussian_PDF t) (Rbar_locally m_infty) (locally 0)) with (is_lim (fun t : R => - Standard_Gaussian_PDF t) m_infty 0).\n  unfold Standard_Gaussian_PDF.\n  apply (is_lim_ext (fun t : R => (- / sqrt (2 * PI)) *  exp (- t ^ 2 / 2))).  \n  intros.\n  now ring_simplify.\n  replace (0) with ((- / sqrt (2*PI)) * 0) by lra.    \n  apply is_lim_scal_l with (a:=- / sqrt (2 * PI)) (l := 0).\n  apply limexp_neg_minf.\n  now unfold is_lim.\n  replace (filterlim (fun t : R => - Standard_Gaussian_PDF t) (Rbar_locally p_infty) (locally 0)) with (is_lim (fun t : R => - Standard_Gaussian_PDF t) p_infty 0).\n  unfold Standard_Gaussian_PDF.\n  apply (is_lim_ext (fun t : R => (- / sqrt (2 * PI)) *  exp (- t ^ 2 / 2))).\n  intros.\n  now ring_simplify.\n  replace (0) with ((- / sqrt (2*PI)) * 0) by lra.  \n  apply is_lim_scal_l with (a:=- / sqrt (2 * PI)) (l := 0).\n  apply limexp_neg_inf.\n  now unfold is_lim.\nQed.\n\nLemma gen_from_std (mu sigma : R) :\n   sigma > 0 -> forall x:R,  General_Gaussian_PDF mu sigma x = \n                             / sigma * Standard_Gaussian_PDF ((x-mu)/sigma).\nProof.\n  intros.\n  assert (sigma <> 0).\n  now apply Rgt_not_eq.\n  generalize sqrt_2PI_nzero; intros.\n\n  unfold General_Gaussian_PDF.\n  unfold Standard_Gaussian_PDF.\n  field_simplify.\n  unfold Rdiv.\n  apply Rmult_eq_compat_r.\n  f_equal; now field_simplify.\n  lra.\n  lra.\nQed.  \n\nLemma Positive_General_Gaussian_PDF (mu sigma x : R):\n  sigma > 0 -> General_Gaussian_PDF mu sigma x > 0.\nProof.  \n  intros.\n  unfold General_Gaussian_PDF.\n  apply Rmult_gt_0_compat.\n  apply Rinv_0_lt_compat.\n  apply Rmult_gt_0_compat; trivial.\n  apply sqrt_lt_R0.\n  apply Rmult_gt_0_compat.\n  apply Rle_lt_0_plus_1; lra.\n  apply PI_RGT_0.\n  apply exp_pos.\nQed.\n\nLemma Derive_General_Gaussian_PDF (mu sigma x:R):\n  sigma > 0 -> Derive (General_Gaussian_PDF mu sigma) x = / (sigma^2)*(mu-x)*General_Gaussian_PDF mu sigma x.\nProof.\n  unfold General_Gaussian_PDF.\n  Derive_helper.\n  apply Rgt_not_eq.\n  apply Rmult_gt_0_compat; try lra.\n  simpl.\n  apply Rmult_gt_0_compat; try lra.\nQed.\n\nLemma ex_derive_General_Gaussian_PDF (mu sigma:R) (x:R):\n  sigma > 0 -> ex_derive (General_Gaussian_PDF mu sigma) x.\nProof.\n  intros.\n  unfold General_Gaussian_PDF.\n  now auto_derive.\nQed.\n\nLemma continuous_Derive_General_Gaussian_PDF (mu sigma x:R):\n  sigma > 0 -> continuous (Derive (General_Gaussian_PDF mu sigma)) x.\nProof.\n  intros.\n  apply (continuous_ext (fun x => / (sigma^2)*((mu-x)*General_Gaussian_PDF mu sigma x))).\n  intros.\n  rewrite Derive_General_Gaussian_PDF.\n  now rewrite Rmult_assoc.\n  trivial.\n  unfold General_Gaussian_PDF.\n  apply (@ex_derive_continuous).\n  now auto_derive.\nQed.\n\n\nAxiom Fubini:\n  forall (a b c d: R) (f: R -> R -> R) (x y: R), \n    a < x < b -> c < y < d -> \n    continuity_2d_pt f x y -> \n    RInt (fun u => RInt (fun v => f u v) a b) c d =\n    RInt (fun v => RInt (fun u => f u v) c d) a b.\n\n(* the iterated integrals below are equal in the sense either they are both infinite, or they are both finite with the same value if you omit the ex_RInt_gen conditions\n as written they are both finite, and can be generalized to non-positive functions by requiring them to be absoluately integrable *)\n\nAxiom Fubini_gen :\n  forall (Fa Fb Fc Fd: (R -> Prop) -> Prop)\n         (f: R -> R -> R) ,\n  filter_prod Fa Fb\n    (fun ab => forall (x : R), Rmin (fst ab) (snd ab) <= x <= Rmax (fst ab) (snd ab) ->\n           filter_prod Fc Fd\n                       (fun bc => forall (y : R), \n                            Rmin (fst bc) (snd bc) <= y <= Rmax (fst bc) (snd bc) -> \n                            continuity_2d_pt f x y)) ->\n  filter_prod Fa Fb\n    (fun ab => forall (x : R), \n         Rmin (fst ab) (snd ab) <= x <= Rmax (fst ab) (snd ab) ->\n         filter_prod Fc Fd\n                     (fun bc => forall (y : R), \n                          Rmin (fst bc) (snd bc) <= y <= Rmax (fst bc) (snd bc) ->\n                          f x y >= 0)) ->    \n  ex_RInt_gen (fun u => RInt_gen (fun v => f u v) Fa Fb) Fc Fd ->\n  ex_RInt_gen (fun v => RInt_gen (fun u => f u v) Fc Fd) Fa Fb ->\n  RInt_gen (fun u => RInt_gen (fun v => f u v) Fa Fb) Fc Fd =\n    RInt_gen (fun v => RInt_gen (fun u => f u v) Fc Fd) Fa Fb.\n\nLemma sqr_plus1_gt (x:R):\n  x^2 + 1 > 0.\nProof.\n  intros.\n  apply Rplus_le_lt_0_compat.\n  apply pow2_ge_0.\n  lra.\nQed.  \n\nLemma sqr_plus1_neq (x:R):\n  x^2 + 1 <> 0.\nProof.\n  apply Rgt_not_eq.  \n  apply sqr_plus1_gt.\nQed.\n\nLemma deriv_erf00 (x0 x2:R) :\n  Derive (fun u : R => - / (2 * x0 ^ 2 + 2) * exp (- (u ^ 2 + (u * x0) ^ 2))) x2 =\n    x2 * exp (- (x2 ^ 2 + (x2 * x0) ^ 2)). \nProof.\n  Derive_helper.\n\n  replace (2*(x0 * x0) + 2) with (2*(x0^2 + 1)) by lra.\n  apply Rmult_integral_contrapositive_currified; try lra.\n  apply sqr_plus1_neq.\nQed.\n\nLemma atan_tan_inv (x:R) :\n  -PI/2 < x < PI/2 -> atan (tan x) = x.\nProof.\n  intros.\n  unfold atan.\n  destruct (pre_atan (tan x)) as [y [yrang yinv]].\n  now apply tan_is_inj in yinv.\nQed.\n\nLemma lim_atan_inf:\n  is_lim atan p_infty (PI/2).\nProof.\n  apply is_lim_spec.\n  unfold is_lim'.\n  intros.\n  assert(atan_upper:forall x, atan x < PI/2)\n    by apply atan_bound.\n  unfold Rbar_locally'.\n  destruct (Rlt_dec (PI/2-eps) 0).\n  - exists (0).\n    intros.\n    rewrite Rabs_left.\n    + assert (atan 0 < atan x)\n             by now apply atan_increasing.\n      rewrite atan_0 in H0; try lra.\n    + now apply Rlt_minus.\n  - exists (tan (PI/2 - eps)).\n    assert (eps > 0)\n      by now destruct eps.\n    intros.\n    rewrite Rabs_left; try lra.\n    + assert (atan (tan (PI/2 - eps)) < atan x)\n       by now apply atan_increasing.\n      rewrite atan_tan_inv in H1; try lra.\n    + now apply Rlt_minus.\nQed.\n                                          \nLemma erf_atan:\n  is_RInt_gen (fun s : R => / (2 * s ^ 2 + 2)) (at_point 0) \n              (Rbar_locally' p_infty) (PI / 4).\nProof.\n    + apply (is_RInt_gen_ext (Derive (fun s => /2 * atan s))).\n      * apply filter_forall.\n        intros.\n        replace (/ (2 * x0^2 + 2)) with ( (/2) * (/ (x0^2+1))).\n        rewrite Derive_scal.\n        apply Rmult_eq_compat_l.\n        rewrite <- Derive_Reals with (pr := derivable_pt_atan x0).\n        rewrite derive_pt_atan.\n        unfold Rsqr.\n        replace (1+x0*x0) with (x0^2+1) by lra.\n        unfold Rdiv.\n        lra.\n        field.\n        split.\n        replace (2*x0^2 + 2) with (2*(x0^2+1)) by lra.\n        apply Rmult_integral_contrapositive.\n        split.\n        lra.\n        apply sqr_plus1_neq.\n        apply sqr_plus1_neq.\n      * replace (PI/4) with (PI/4 - 0) by lra.\n        apply is_RInt_gen_Derive.\n        - apply filter_forall.\n           intros.\n           apply ex_derive_scal.\n           apply ex_derive_Reals_1.\n           apply derivable_pt_atan.\n        - apply filter_forall.\n           intros.\n           apply (continuous_ext (fun s => /2 * /(s^2+1))).\n           intros.\n           symmetry.\n           replace (/ (x1^2+1)) with (Derive atan x1).\n           apply Derive_scal with (f := atan ) (k := /2) (x := x1).\n           rewrite <- Derive_Reals with (pr := derivable_pt_atan x1).\n           rewrite derive_pt_atan.\n           unfold Rsqr.\n           replace (1 + x1*x1) with (x1^2 + 1) by lra; lra.\n           apply (@ex_derive_continuous).\n           auto_derive.\n           apply sqr_plus1_neq.\n        - unfold filterlim, filter_le.\n          intros.\n          unfold filtermap, at_point.\n          replace (/2 * atan 0) with (0).\n          now apply locally_singleton.\n          rewrite atan_0; lra.\n        - replace (filterlim (fun s : R => / 2 * atan s) (Rbar_locally' p_infty) (locally (PI / 4))) with (is_lim (fun s : R => / 2 * atan s) p_infty (Rbar_mult (/2) (PI/2))).\n           apply is_lim_scal_l with (a := /2) (f := atan).\n           apply lim_atan_inf.\n           replace (Rbar_mult (/2) (PI/2)) with (Finite (PI/4)).\n           now unfold is_lim.\n           f_equal; simpl; f_equal; field.\nQed.\n\nLemma erf_exp0 (x0:R) :\n   is_RInt_gen (fun u : R => u * exp (- (u ^ 2 + (u * x0) ^ 2))) \n               (at_point 0) (Rbar_locally' p_infty) (/ (2 * x0 ^ 2 + 2)).\nProof.\n      replace (/ (2*x0^2+2)) with (0 - (- / (2*x0^2+2))).\n      * apply (is_RInt_gen_ext (Derive (fun u => -/(2*x0^2+2) * exp(-(u^2+(u*x0)^2))))).\n        -- apply filter_forall.\n           intros.\n           apply deriv_erf00.\n        -- apply is_RInt_gen_Derive with (f := fun u => -/(2*x0^2+2)* exp(-(u^2+(u*x0)^2))) (lb:=0) (la := - / (2*x0^2+2)).\n           ++ apply filter_forall.\n              intros.\n              solve_derive.\n           ++ apply filter_forall.\n              intros.\n              apply (continuous_ext (fun x2 => x2 * exp (- (x2 ^ 2 + (x2 * x0) ^ 2)))).\n              ** intros.\n                 symmetry.\n                 apply deriv_erf00.\n              ** apply (@ex_derive_continuous).\n                 solve_derive.\n           ++ unfold filterlim, filter_le.\n              intros.\n              unfold filtermap, at_point.\n              replace (- / (2 * x0 ^ 2 + 2) * exp (- (0 ^ 2 + (0 * x0) ^ 2))) with (- / (2 * x0 ^ 2 + 2)).\n              now apply locally_singleton.\n              replace (- (0 ^ 2 + (0 * x0) ^ 2)) with (0) by lra.\n              rewrite exp_0; lra.\n           ++ replace (filterlim (fun u : R => - / (2 * x0 ^ 2 + 2) * exp (- (u ^ 2 + (u * x0) ^ 2)))\n                                 (Rbar_locally' p_infty) (locally 0)) with \n                  (is_lim (fun u : R => - / (2 * x0 ^ 2 + 2) * exp (- (u ^ 2 + (u * x0) ^ 2))) p_infty 0).\n              ** replace  (Finite 0) with (Rbar_mult  (- / (2 * x0 ^ 2 + 2)) 0).\n                 apply is_lim_scal_l with (a := - / (2 * x0 ^ 2 + 2) ).\n                 apply is_lim_comp with (l:=m_infty).\n                 apply is_lim_exp_m.\n                 replace (m_infty) with (Rbar_opp p_infty).\n                 apply is_lim_opp.\n                 apply (is_lim_ext (fun y => y * y * (1 + Rsqr x0))).\n                 intros.\n                 unfold Rsqr.\n                 now ring_simplify.\n                 replace (p_infty) with (Rbar_mult (Rbar_mult p_infty p_infty) (1 + Rsqr x0)) at 2.\n                 apply is_lim_mult.\n                 apply is_lim_mult.\n                 apply is_lim_id.\n                 apply is_lim_id.\n                 now compute.\n                 apply is_lim_const.\n                 compute.\n                 replace (x0 * x0) with (x0^2) by lra.\n                 rewrite Rplus_comm.\n                 apply sqr_plus1_neq.\n                 replace (Rbar_mult p_infty p_infty) with (p_infty).\n                 apply is_Rbar_mult_unique.\n                 apply is_Rbar_mult_p_infty_pos.                 \n                 simpl.\n                 rewrite Rsqr_pow2.\n                 rewrite Rplus_comm.\n                 apply sqr_plus1_gt.\n                 now compute.\n                 now compute.\n                 unfold Rbar_locally'.\n                 exists x0.\n                 intros.\n                 discriminate.\n                 simpl; f_equal; ring.\n              ** now unfold is_lim.\n      * now ring_simplify.\nQed.\n\nLemma erf_int00 : \n  is_RInt_gen (fun s => RInt_gen (fun u => u*exp(-(u^2+(u*s)^2))) (at_point 0)  (Rbar_locally' p_infty)) (at_point 0) (Rbar_locally' p_infty) (PI / 4).\nProof.\n    apply (is_RInt_gen_ext (fun s => / (2*s^2+2))).\n    apply filter_forall.\n    + intros.\n      symmetry.\n      apply is_RInt_gen_unique.\n      apply erf_exp0.\n    + apply erf_atan.\nQed.\n\nLemma erf_ex_RInt0 (x0:R):\n  ex_RInt_gen\n   (fun v : R =>\n    (if  (Rlt_dec v 1) then 1 else v * exp (- v ^ 2)) * exp (- x0 ^ 2))\n   (at_point 0) (Rbar_locally' p_infty).\nProof.\n  unfold ex_RInt_gen.\n  exists (exp(-x0^2) + / (2* exp 1) * exp(-x0^2)).\n  apply is_RInt_gen_Chasles with (b:=1) (l1 := exp(-x0^2)) (l2 := / (2 * exp 1) * exp(-x0^2))\n                                 (f :=    (fun v : R =>\n    (if (Rlt_dec v 1) then 1 else v * exp (- v ^ 2)) * exp (- x0 ^ 2))).\n  apply is_RInt_gen_at_point.\n  apply (is_RInt_ext (fun v => exp(-x0^2))).\n  intros.\n  rewrite Rmin_left in H; try lra.\n  rewrite Rmax_right in H; try lra.\n  destruct (Rlt_dec x 1); lra.\n  replace (exp(-x0^2)) with ((1 - 0) * (exp(-x0^2))) at 1.\n  apply (@is_RInt_const).\n  lra.\n  apply (is_RInt_gen_ext (fun v => v* exp(-v^2)*exp(-x0^2))).  \n  exists (fun a => a = 1) (fun b => b>1000).\n  now unfold at_point.\n  unfold Rbar_locally'; now exists 1000.\n  intros.\n  subst.\n  unfold fst, snd in H1.\n  rewrite Rmin_left in H1; try lra.\n  rewrite Rmax_right in H1; try lra.\n  destruct (Rlt_dec x1 1); try lra.\n  apply (is_RInt_gen_ext (Derive (fun v => -(/2)*exp(-x0^2) * exp(-v^2)))).  \n  apply filter_forall.\n  Derive_helper.\n\n  replace  (/ (2 * exp 1) * exp (- x0 ^ 2)) with (0 - -  (/ (2 * exp 1) * exp (- x0 ^ 2))) by lra.\n  apply is_RInt_gen_Derive.\n  apply filter_forall.\n  intros.\n  now auto_derive.\n  apply filter_forall.  \n  intros.\n  apply (continuous_ext (fun v => exp(-x0^2)*v*exp(-v^2))).\n  Derive_helper.\n\n  apply (@ex_derive_continuous).\n  now auto_derive.\n  unfold filterlim, filter_le.\n  intros.\n  unfold filtermap, at_point.\n  apply locally_singleton.\n  replace (- / 2 * exp (- x0 ^ 2) * exp (- 1 ^ 2)) with (- (/ (2 * exp 1) * exp (- x0 ^ 2))); trivial.\n  replace (exp(-1^2)) with (/ exp(1)).\n  equation_simplifier.\n  apply Rgt_not_eq.  \n  apply exp_pos.\n  replace (-1^2) with (-1) by lra.  \n  symmetry; apply exp_Ropp.\n  replace (filterlim (fun v : R => - / 2 * exp (- x0 ^ 2) * exp (- v ^ 2))\n    (Rbar_locally' p_infty) (locally 0)) with (is_lim (fun v : R => - / 2 * exp (- x0 ^ 2) * exp (- v ^ 2)) p_infty 0).\n  replace (Finite 0) with (Rbar_mult (-/2 * exp(-x0^2)) 0).\n  apply is_lim_scal_l.\n  apply (is_lim_ext (fun t => / exp(t^2))).\n  intros.\n  symmetry; apply exp_Ropp.\n  replace (Finite 0) with (Rbar_inv p_infty).\n  apply is_lim_inv.\n  eapply is_lim_le_p_loc; [idtac | apply is_lim_exp_p].\n  unfold Rbar_locally'.\n  exists 2; intros.\n  left.\n  apply exp_increasing.\n  replace (x) with (x*1) at 1 by lra.\n  replace (x^2) with (x*x) by lra.\n  apply Rmult_lt_compat_l; lra.\n  discriminate.\n  now compute.\n  apply Rbar_mult_0_r.\n  now unfold is_lim.\nQed.\n\nLemma erf_ex_RInt1 (x0:R):\n  ex_RInt_gen\n   (fun v : R => exp(-(x0^2 + v^2)))\n   (at_point 0) (Rbar_locally' p_infty).\nProof.\n    apply (ex_RInt_gen_ext (fun v => exp(-(x0^2))*exp(-v^2))).\n    apply filter_forall.\n    intros.\n    replace (-(x0^2 + x1^2)) with ((-x0^2) + (-x1^2)) by lra.\n    symmetry.\n    apply exp_plus.\n    apply ex_RInt_gen_bound with (g := fun v => (if (Rlt_dec v 1) then 1 else v*exp(-v^2))*exp(-x0^2)).\n    apply at_point_filter.\n    apply Rbar_locally'_filter.\n    unfold filter_Rlt.\n    exists 1.\n    exists (fun x => x=0) (fun y => y>1000).\n    now unfold at_point.\n    unfold Rbar_locally'; now exists 1000.\n    intros.\n    subst.\n    unfold fst, snd.\n    lra.\n    apply erf_ex_RInt0.\n    exists (fun x => x=0) (fun y => y>1000).\n    now unfold at_point.    \n    unfold Rbar_locally'; now exists 1000.\n    intros.\n    subst.\n    unfold fst, snd.\n    split.\n    intros.\n    split.\n    rewrite <- exp_plus.\n    left.\n    apply exp_pos.\n    rewrite Rmult_comm.\n    apply Rmult_le_compat_r.\n    left.\n    apply exp_pos.\n    destruct (Rlt_dec x 1).\n    rewrite exp_Ropp.\n    replace (1) with (/ 1) by lra.\n    apply Rinv_le_contravar; try lra.\n    replace (1) with (exp 0).\n    left.\n    apply exp_increasing.\n    rewrite <- Rsqr_pow2.\n    apply Rlt_0_sqr; lra.\n    apply exp_0.\n    replace (exp(-x^2)) with (1 * exp(-x^2)) at 1 by lra.\n    apply  Rmult_le_compat_r.\n    left.\n    apply exp_pos.\n    lra.\n    apply (@ex_RInt_continuous).\n    intros.\n    apply (@ex_derive_continuous).\n    now auto_derive.\nQed.\n\nLemma erf_ex_RInt2:\n  ex_RInt_gen\n   (fun v : R => exp(-v^2))\n   (at_point 0) (Rbar_locally' p_infty).\nProof.\n  apply (ex_RInt_gen_ext (fun v => exp(-(0^2 + v^2)))).  \n  apply filter_forall.\n  intros.\n  f_equal; lra.\n  apply erf_ex_RInt1.\nQed.  \n\nLemma erf_ex_bound1 (u:R) :\n  u>=0 -> exp (- (u ^ 2)) <= /(1+u^2).\nProof.\n  intros.\n  rewrite exp_Ropp.\n  destruct H.\n  left.\n  apply Rinv_1_lt_contravar.\n  apply Rplus_le_reg_l with (r:=-1).\n  replace (-1 + 1) with (0) by lra.\n  replace (-1 + (1 + u^2)) with (u^2) by lra.\n  apply pow2_ge_0.\n  apply exp_ineq1.\n  generalize (pow2_gt_0 u); lra.\n  subst.\n  replace (0^2) with (0) by lra.\n  replace (1 + 0) with (1) by lra.\n  rewrite exp_0; lra.\nQed.\n  \nLemma erf_ex_bound2 (u v:R) :\n  u*v>=0 -> exp (- ((u*v) ^ 2)) <= /(1+(u*v)^2).\nProof.\n  intros.\n  now apply erf_ex_bound1 with (u:=u*v).\nQed.\n\nLemma erf_ex_bound3 (u v:R) :\n  u>=0 -> v>=0 -> u * exp (- (u ^ 2 + (u * v) ^ 2)) <= u * ( / (1+u^2) * /(1 + (u*v)^2)).\nProof.\n  intros.\n  apply Rmult_le_compat_l; try lra.\n  replace (exp(-(u^2+(u*v)^2))) with (exp(-u^2)*exp(-(u*v)^2)).\n  apply Rmult_le_compat.\n  left.\n  apply exp_pos.\n  left.\n  apply exp_pos.\n  now apply erf_ex_bound1.\n  apply erf_ex_bound2.\n  replace (0) with (u * 0) by lra.\n  now apply Rmult_ge_compat_l.\n  rewrite <- exp_plus.\n  f_equal; ring.\nQed.\n\nLemma int_bound3 (u:R) :\n  u>0 -> is_RInt_gen (fun v : R =>   u / (1+u^2) * /(1 + (u*v)^2)) \n                      (at_point 0) (Rbar_locally' p_infty) (PI/(2*(u^2+1))).\nProof.\n  intros.\n  assert (forall x1 : R_UniformSpace,\n      / (1 + (u * x1) ^ 2) = Derive (fun y : R => atan (u * y) / u) x1).\n  intros.\n  symmetry.\n  Derive_helper.\n  split.\n  replace (u*x1*(u*x1)) with ((u*x1)^2).\n  apply Rgt_not_eq.\n  apply plus_Rsqr_gt_0.\n  now ring_simplify.\n  lra.\n  replace (PI/(2*(u^2+1))) with ((u/(1+u^2)) * (PI/(2*u))).\n  apply (@is_RInt_gen_scal).\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply (is_RInt_gen_ext (Derive (fun y => atan(u*y)/u))).\n  exists (fun a => a=0) (fun b => b>1000).\n  now unfold at_point.\n  unfold Rbar_locally'; now exists 1000.\n  intros.\n  symmetry.\n  apply H0.\n  replace (PI / (2*u)) with ((PI/(2*u)) - 0) by lra.\n  apply is_RInt_gen_Derive.\n  apply filter_forall.\n  intros.\n  solve_derive.\n  apply filter_forall.\n  intros.\n  apply (continuous_ext (fun y =>  / (1 + (u * y) ^ 2))).\n  apply H0.\n  apply (@ex_derive_continuous).  \n  auto_derive.\n  replace (u*x0*(u*x0*1)) with ((u*x0)^2).\n  apply Rgt_not_eq.\n  apply plus_Rsqr_gt_0.\n  now ring_simplify.\n  unfold filterlim, filter_le.\n  intros.\n  unfold filtermap, at_point.\n  replace (u * 0) with (0) by lra.\n  rewrite atan_0.\n  replace (0 / u) with (0) by lra.\n  now apply locally_singleton.\n  replace (filterlim (fun y : R => atan (u * y) / u) (Rbar_locally' p_infty)\n                     (locally (PI / (2 * u)))) with\n          (is_lim (fun y : R => atan (u * y) / u) p_infty (PI / (2 * u))).\n  apply (is_lim_ext (fun y => /u * atan(u*y+0))).\n  intros.\n  unfold Rdiv.\n  replace (u*y+0) with (u*y) by lra.\n  now rewrite Rmult_comm.\n  replace (Finite (PI / (2*u))) with (Rbar_mult (/u) (PI/2)).\n  apply (@is_lim_scal_l).\n  apply is_lim_comp_lin .\n  rewrite Rbar_plus_0_r.\n  rewrite Rbar_mult_comm.\n  rewrite Rbar_mult_p_infty_pos.\n  apply lim_atan_inf.\n  lra.\n  now apply Rgt_not_eq.\n  simpl.\n  f_equal; equation_simplifier.\n  now unfold is_lim.\n  equation_simplifier.\n  split.\n  replace (u * u) with (u^2) by lra.\n  now apply sqr_plus1_neq.  \n  now apply Rgt_not_eq.\nQed.\n\nLemma erf_ex_RInt33 (u:R) :\n  u >= 0 -> ex_RInt_gen (fun v : R => u * exp (- (u ^ 2 + (u * v) ^ 2))) (at_point 0)\n                       (Rbar_locally' p_infty).\nProof.\n  intros.\n  destruct H.\n  apply ex_RInt_gen_bound with (g:=(fun v : R =>   u / (1+u^2) * /(1 + (u*v)^2))).\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply filter_Rlt_at_point_p_infty.\n  unfold ex_RInt_gen.\n  exists (PI/(2*(u^2+1))).\n  now apply int_bound3.\n  exists (fun a => a=0) (fun b => b>1000).\n  now unfold at_point.\n  unfold Rbar_locally'; now exists 1000.\n  intros.\n  split.\n  intros.\n  split.\n  replace (0) with (u * 0) by lra.\n  apply Rmult_le_compat_l; try lra.\n  left; apply exp_pos.\n  unfold Rdiv.\n  rewrite Rmult_assoc.\n  apply erf_ex_bound3; try lra.\n  unfold fst in H2; lra.\n  unfold fst, snd.\n  apply (@ex_RInt_continuous).\n  intros.\n  apply (@ex_derive_continuous).\n  solve_derive.\n  subst.\n  apply (ex_RInt_gen_ext (Derive (fun v => 0))).\n  apply filter_forall.\n  intros.\n  rewrite Derive_const; lra.\n  unfold ex_RInt_gen.\n  exists (0 - 0).\n  apply is_RInt_gen_Derive.\n  apply filter_forall.\n  intros.\n  solve_derive.\n  apply filter_forall.\n  intros.\n  apply (continuous_ext (fun _ => 0)).\n  intros.\n  now rewrite Derive_const.\n  apply (@ex_derive_continuous).\n  solve_derive.\n  unfold filterlim, filter_le.\n  intros.\n  unfold filtermap, at_point.\n  now apply locally_singleton.\n  unfold filterlim, filter_le.\n  intros.\n  unfold filtermap, Rbar_locally'.\n  exists 0.\n  intros.\n  now apply locally_singleton.\nQed.  \n\nLemma erf_decr_RInt30 (b:R):\n   b >= 0 ->\n   interval_decreasing (fun u : R => RInt_gen (fun v : R => exp (- (u ^ 2 + v ^ 2))) (at_point 0) (Rbar_locally' p_infty)) 0 b.\nProof.\n  intros.\n  unfold interval_decreasing.\n  intros.\n  apply is_RInt_gen_Rle with (fl := RInt_gen (fun v : R => exp (- (y ^ 2 + v ^ 2)))\n                                             (at_point 0) (Rbar_locally' p_infty))\n                             (gl := RInt_gen (fun v : R => exp (- (x ^ 2 + v ^ 2)))\n                                             (at_point 0) (Rbar_locally' p_infty))                             \n                             (f := (fun v : R => exp (- (y ^ 2 + v ^ 2))))\n                             (g := (fun v : R => exp (- (x ^ 2 + v ^ 2))))           \n                             (F:= at_point 0) (G:= Rbar_locally' p_infty).\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply filter_Rlt_at_point_p_infty.  \n  apply (@RInt_gen_correct).\n  apply Proper_StrongProper, at_point_filter.\n  apply Proper_StrongProper, Rbar_locally'_filter.\n  apply erf_ex_RInt1.\n  apply (@RInt_gen_correct).\n  apply Proper_StrongProper, at_point_filter.\n  apply Proper_StrongProper, Rbar_locally'_filter.\n  apply erf_ex_RInt1.\n  exists (fun a => a=0) (fun b => b>1000).\n  now unfold at_point.\n  unfold Rbar_locally'; now exists 1000.\n  intros.\n  destruct H2.\n  left.\n  apply exp_increasing.\n  apply Ropp_gt_lt_contravar.\n  apply Rplus_lt_compat_r.\n  rewrite <- Rsqr_pow2; rewrite <- Rsqr_pow2.  \n  apply Rsqr_incrst_1; lra; lra.\n  subst; lra.\nQed.\n\nLemma erf_ex_RInt3_bound (u:R) :\n  u > 0 ->\n  ex_RInt_gen (fun v : R => u * exp (- (u ^ 2 + (u * v) ^ 2))) \n              (at_point 0) (Rbar_locally' p_infty)  ->\n  RInt_gen (fun v : R => u * exp (- (u ^ 2 + (u * v) ^ 2)))\n           (at_point 0) (Rbar_locally' p_infty) <= (PI/(2*(u^2+1))).\nProof.\n  intros.\n  apply is_RInt_gen_Rle with (fl := RInt_gen (fun v : R => u * exp (- (u ^ 2 + (u * v) ^ 2)))\n                                             (at_point 0) (Rbar_locally' p_infty))\n                             (gl := (PI/(2*(u^2+1))))\n                             (f := (fun v : R => u * exp (- (u ^ 2 + (u * v) ^ 2))))\n                             (g := (fun v =>   u / (1+u^2) * /(1 + (u*v)^2)) )\n                             (F:= at_point 0) (G:= Rbar_locally' p_infty).\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply filter_Rlt_at_point_p_infty.  \n  now apply int_bound3.\n  apply (@RInt_gen_correct).\n  apply Proper_StrongProper, at_point_filter.\n  apply Proper_StrongProper, Rbar_locally'_filter.\n  trivial.\n  exists (fun a => a = 0) (fun b => b>1000).\n  now unfold at_point.\n  unfold Rbar_locally'; now exists 1000.\n  intros.\n  subst.\n  unfold Rdiv.\n  rewrite Rmult_assoc.\n  apply erf_ex_bound3; try lra.\n  unfold fst in H3; try lra.\nQed.\n\nLemma erf_ex_RInt3_bound_int :\n  is_RInt_gen (fun u : R => PI/(2*(u^2+1))) (at_point 0) (Rbar_locally' p_infty) (PI^2/4).\nProof.\n  apply (is_RInt_gen_ext (Derive (fun u => (PI/2) * atan u))).\n  apply filter_forall.\n  intros.\n  rewrite Derive_scal.\n  rewrite <- Derive_Reals with (pr := derivable_pt_atan (x0)).\n  rewrite derive_pt_atan.\n  unfold Rsqr.\n  field_simplify; trivial.\n  apply Rgt_not_eq.  \n  now apply sqr_plus1_gt.  \n  replace (1 + x0*x0) with (x0^2+1).\n  now apply sqr_plus1_neq.  \n  ring.\n  replace (PI^2/4) with (PI^2/4 - 0).\n  apply is_RInt_gen_Derive.\n  apply filter_forall.\n  intros.\n  solve_derive.\n  apply filter_forall.\n  intros.\n  apply (continuous_ext (fun u => (PI/(2*(u^2+1))))).\n  intros.\n  rewrite Derive_scal.\n  rewrite <- Derive_Reals with (pr := derivable_pt_atan (x1)).\n  rewrite derive_pt_atan.\n  rewrite Rsqr_pow2.\n  field_simplify; trivial.\n  rewrite Rplus_comm.\n  now apply sqr_plus1_neq.  \n  now apply sqr_plus1_neq.  \n  apply (@ex_derive_continuous).\n  auto_derive.\n  apply Rgt_not_eq.  \n  ring_simplify.\n  replace (2 * x0 ^ 2 + 2) with (2*(x0^2+1)) by lra.\n  apply Rmult_gt_0_compat; try lra.\n  now apply sqr_plus1_gt.  \n  unfold filterlim, filter_le.\n  intros.\n  unfold filtermap, at_point.\n  replace (PI/2 * atan 0) with (0).\n  now apply locally_singleton.\n  rewrite atan_0; lra.\n  replace (filterlim (fun u : R => PI / 2 * atan u) (Rbar_locally' p_infty) (locally (PI ^ 2 / 4))\n) with (is_lim (fun u : R => PI / 2 * atan u) p_infty (PI^2/4)).\n  replace (Finite (PI^2/4)) with (Rbar_mult (PI/2) (PI/2)).\n  apply is_lim_scal_l.\n  apply lim_atan_inf.\n  simpl.\n  f_equal; now field_simplify.\n  now unfold is_lim.\n  now field_simplify.\nQed.\n\nLemma erf_ex_RInt3 :\n  ex_RInt_gen\n    (fun u : R =>\n     RInt_gen (fun v : R => u * exp (- (u ^ 2 + (u * v) ^ 2))) \n              (at_point 0) (Rbar_locally' p_infty)) (at_point 0) (Rbar_locally' p_infty).\nProof.  \n  apply ex_RInt_gen_bound with (g:=(fun u : R => (PI/(2*(u^2+1))))).\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply filter_Rlt_at_point_p_infty.\n  unfold ex_RInt_gen.\n  exists (PI^2/4).\n  apply erf_ex_RInt3_bound_int.\n  exists (fun a => a=0) (fun b => b>1000).\n  now unfold at_point.\n  unfold Rbar_locally'; now exists 1000.\n  intros.\n  split.\n  intros.\n  split.\n  apply RInt_gen_Rle0.\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply filter_Rlt_at_point_p_infty.\n  apply erf_ex_RInt33.\n  unfold fst in H1; try lra.\n  exists (fun a => a=0) (fun b => b>1000).\n  now unfold at_point.\n  unfold Rbar_locally'; now exists 1000.\n  intros.\n  unfold fst in H1.\n  left.\n  apply Rmult_lt_0_compat; try lra.\n  apply exp_pos.\n  apply erf_ex_RInt3_bound.\n  unfold fst in H1; try lra.\n  apply erf_ex_RInt33.\n  unfold fst in H1; try lra.\n  unfold fst, snd.\n  subst.\n  apply (ex_RInt_ext (fun u : R =>\n     RInt_gen (fun w : R => exp (- (u ^ 2 + w ^ 2))) (at_point 0)\n       (Rbar_locally' p_infty))).\n  intros.\n  rewrite Rmin_left in H; try lra.\n  rewrite Rmax_right in H; try lra.\n  symmetry.\n  apply is_RInt_gen_unique.\n  apply is_RInt_gen_comp_lin_point_0 with (u := x) (f := fun v => exp(-(x^2+v^2))).\n  lra.\n  intros.\n  apply (@ex_RInt_continuous).\n  intros.\n  apply (@ex_derive_continuous).\n  solve_derive.\n  replace (x*0) with (0) by lra.\n  replace (Rbar_mult x p_infty) with (p_infty).\n  apply (@RInt_gen_correct).\n  apply Proper_StrongProper, at_point_filter.\n  apply Proper_StrongProper, Rbar_locally'_filter.\n  apply erf_ex_RInt1.\n  symmetry.\n  apply Rbar_mult_p_infty_pos; try lra.\n  apply ex_RInt_Reals_1.\n  apply RiemannInt_decreasing; try lra.\n  apply erf_decr_RInt30; try lra.\nQed.\n\nLemma erf_int1  :\n  is_RInt_gen (fun u => RInt_gen (fun v => exp(-(u^2+v^2))) (at_point 0)  (Rbar_locally' p_infty)) (at_point 0) (Rbar_locally' p_infty) (PI / 4).\nProof.\n  apply (is_RInt_gen_ext (fun u => RInt_gen (fun v => u*exp(-(u^2+(u*v)^2))) (at_point 0) (Rbar_locally' p_infty))).\n  - exists (fun x => x=0) (fun y => y>1000).\n    + now unfold at_point.\n    + unfold Rbar_locally'; now exists 1000.\n    + intros.\n      unfold fst, snd in H1.\n      subst.\n      rewrite Rmin_left in H1; try lra.\n      rewrite Rmax_right in H1; try lra.\n      apply is_RInt_gen_unique.\n      apply is_RInt_gen_comp_lin_point_0 with (f := fun v => exp(-(x0^2 + v^2))); try lra.\n      * intros.\n        apply (@ex_RInt_continuous).\n        intros.\n        apply (@ex_derive_continuous).\n        now auto_derive.\n      * replace (x0*0) with (0) by lra.\n        replace (Rbar_mult x0 p_infty) with (p_infty).\n        ++ apply (@RInt_gen_correct).\n           apply Proper_StrongProper, at_point_filter.\n           apply Proper_StrongProper, Rbar_locally'_filter.\n           apply erf_ex_RInt1.\n        ++ rewrite Rbar_mult_comm.\n           now rewrite Rbar_mult_p_infty_pos.\n  - replace (PI/4) with \n        (RInt_gen\n           (fun u : R =>\n              RInt_gen (fun v : R => u * exp (- (u ^ 2 + (u * v) ^ 2))) \n                       (at_point 0) (Rbar_locally' p_infty)) (at_point 0) (Rbar_locally' p_infty)).\n    + apply RInt_gen_correct.\n      apply erf_ex_RInt3.\n    + rewrite -> Fubini_gen with (Fa := at_point 0) (Fc := at_point 0) (Fb := Rbar_locally' p_infty) (Fd := Rbar_locally' p_infty) (f := fun u => fun v => u* exp (- (u^2 + (u*v) ^ 2))).\n      * apply is_RInt_gen_unique.\n        apply erf_int00.\n      * apply filter_forall.  \n        intros.\n        apply filter_forall.  \n        intros.\n        apply continuity_2d_pt_mult.\n        apply continuity_2d_pt_id1.\n        apply continuity_1d_2d_pt_comp.\n        apply derivable_continuous_pt.\n        apply derivable_pt_exp.\n        repeat first [\n               apply continuity_2d_pt_opp\n             | apply continuity_2d_pt_plus\n             | apply continuity_2d_pt_mult\n             | apply continuity_2d_pt_id1\n             | apply continuity_2d_pt_id2\n             | apply continuity_2d_pt_const\n             ].\n      * eapply Filter_prod with (Q:=(eq 0)) (R:=fun x => x > 1000).\n        -- now red.\n        -- simpl;\n             now exists 1000.\n        -- intros.\n           simpl in *.\n           subst.\n           eapply Filter_prod with (Q:=(eq 0)) (R:=fun x => x > 1000).\n           now red.\n           simpl;\n             now exists 1000.\n           intros.\n           simpl in *.\n           subst.\n           rewrite Rmin_left in H1; try lra.\n           apply Rle_ge.\n           apply Rmult_le_pos; try lra.\n           left.\n           apply exp_pos.\n      * apply erf_ex_RInt3.\n      * unfold ex_RInt_gen.\n        exists (PI/4).\n        apply erf_int00.\nQed.\n\nLemma erf_int_sq :\n  Rsqr (RInt_gen (fun u => exp(-(u^2))) (at_point 0) (Rbar_locally' p_infty)) = PI/4.\nProof.\n  unfold Rsqr.\n  rewrite <- RInt_gen_scal.\n  rewrite <- (RInt_gen_ext (fun u => RInt_gen (fun v => exp(-(u^2+v^2))) (at_point 0)  (Rbar_locally' p_infty)) ).\n  apply is_RInt_gen_unique.\n  apply erf_int1.\n  apply filter_forall.\n  intros.\n  rewrite Rmult_comm.\n  rewrite <- RInt_gen_scal.\n  symmetry.\n  rewrite <- (RInt_gen_ext (fun y => exp (-(x0^2 + y^2)))).\n  reflexivity.\n  apply filter_forall.\n  intros.\n  replace (-(x0^2 + x2^2)) with ((-x0^2)+(-x2^2)).\n  apply exp_plus.\n  lra.\n  apply erf_ex_RInt1.\n  apply erf_ex_RInt2.  \n  unfold ex_RInt_gen.\n  exists (PI/4).\n  apply erf_int1.\n  apply erf_ex_RInt2.  \nQed.\n\nLemma erf_int2: \n  RInt_gen (fun u => exp(-(u^2))) (at_point 0) (Rbar_locally' p_infty) = (sqrt PI/2).\nProof.\n  replace (sqrt PI/2) with (Rabs (sqrt PI/2)).\n  replace ( RInt_gen (fun u => exp(-(u^2))) (at_point 0) (Rbar_locally' p_infty)) with\n      (Rabs ( RInt_gen (fun u => exp(-(u^2))) (at_point 0) (Rbar_locally' p_infty))).\n  apply Rsqr_eq_abs_0.\n  replace (Rsqr (sqrt PI/2)) with (PI/4).\n  apply erf_int_sq.\n  rewrite Rsqr_div.\n  rewrite Rsqr_sqrt.\n  unfold Rsqr; lra.\n  left; apply PI_RGT_0.\n  lra.\n  rewrite Rabs_pos_eq; trivial.\n  apply RInt_gen_Rle0.\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply filter_Rlt_at_point_p_infty.\n  apply erf_ex_RInt2.\n  apply filter_forall.\n  intros.\n  left; apply exp_pos.\n  rewrite Rabs_pos_eq; trivial.\n  apply Rle_div_r; try lra.\n  replace (0 * 2) with (0) by lra.\n  left; apply sqrt_lt_R0.\n  apply PI_RGT_0.\nQed.\n\nLemma erf_int21: \n  is_RInt_gen (fun u => exp(-(u^2))) (at_point 0) (Rbar_locally' p_infty) (sqrt PI/2).\nProof.\n  replace (sqrt PI/2) with (RInt_gen (fun u => exp(-(u^2))) (at_point 0) (Rbar_locally' p_infty)).\n  apply (@RInt_gen_correct).\n  apply Proper_StrongProper, at_point_filter.\n  apply Proper_StrongProper, Rbar_locally'_filter.\n  apply erf_ex_RInt2.\n  apply erf_int2.\nQed.\n\nLemma erf_int31: \n  is_RInt_gen (fun u => exp(-(u^2))) (at_point 0) (Rbar_locally' m_infty) ( -sqrt PI/2).\nProof.\n  apply (is_RInt_gen_ext (fun y => (-1) * ((-1) * (exp (-(-1*y)^2))))).\n  apply filter_forall.\n  intros.\n  replace ((-1*x0)^2) with (x0^2).\n  now ring_simplify.\n  now ring_simplify.\n  replace (-sqrt PI/2) with (scal  (-1) (sqrt PI/2)).\n  apply (@is_RInt_gen_scal).\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply is_RInt_gen_comp_lin_point_0 with (f := fun y => exp(-y^2)).\n  lra.\n  intros.\n  apply (@ex_RInt_continuous).\n  intros.\n  apply (@ex_derive_continuous).\n  now auto_derive.\n  replace (-1*0) with (0) by lra.\n  replace (Rbar_mult (-1) m_infty) with (p_infty).\n  apply erf_int21.\n  symmetry.\n  rewrite Rbar_mult_comm.\n  apply Rbar_mult_m_infty_neg; lra.\n  replace (- sqrt PI/2) with ((-1)*(sqrt PI/2)).\n  reflexivity.\n  lra.\nQed.\n\nLemma erf_int3 (r:Rbar): \n  r = p_infty \\/ r= m_infty ->\n  is_RInt_gen (fun u => exp(-(u^2))) (at_point 0) (Rbar_locally' r) ( inf_sign r * sqrt PI/2).\nProof.\n  intros.\n  destruct H.\n  subst.\n  unfold inf_sign.\n  replace (1 * sqrt PI /2) with (sqrt PI / 2) by lra.\n  apply erf_int21.\n  subst.\n  unfold inf_sign.\n  replace (-1 * sqrt PI /2) with (-sqrt PI / 2) by lra.  \n  apply erf_int31.\nQed.\n\nLemma erf_p_infty : \n  is_RInt_gen erf' (at_point 0) (Rbar_locally' p_infty) 1.\nProof.\n  unfold erf'.\n  replace (1) with ((2 / sqrt PI)*(sqrt PI/2)).\n  apply (@is_RInt_gen_scal).\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply erf_int21.\n  equation_simplifier.\nQed.\n\nLemma erf_m_infty : \n  is_RInt_gen erf' (at_point 0) (Rbar_locally' m_infty) (-1).\nProof.\n  unfold erf'.\n  replace (-1) with ((2 / sqrt PI)*(-sqrt PI/2)).\n  apply (@is_RInt_gen_scal).\n  apply at_point_filter.\n  apply Rbar_locally'_filter.\n  apply erf_int31.\n  equation_simplifier.\nQed.\n\nLemma Standard_Gaussian_PDF_int1_pm (r : Rbar): \n  r = p_infty \\/ r = m_infty -> is_RInt_gen Standard_Gaussian_PDF (at_point 0) (Rbar_locally' r)  (inf_sign r * /2).\nProof.\n  intros.\n  unfold Standard_Gaussian_PDF.\n  apply (is_RInt_gen_ext (fun y => /(sqrt 2) * ( (/sqrt PI) * exp (- ((/sqrt 2)*y)^2)))).\n  - apply filter_forall.\n    intros.\n    replace (/sqrt(2*PI)) with (/sqrt(2)*/sqrt(PI)).\n    + replace (-(/ sqrt 2 * x0) ^ 2) with (-x0^2/2).\n      equation_simplifier.\n      rewrite Rpow_mult_distr.\n      replace ((/ sqrt 2)^2) with (/2).\n      now field_simplify.\n      rewrite <- Rsqr_pow2.\n      rewrite Rsqr_inv.\n      rewrite Rsqr_sqrt; try easy.\n      lra.\n      auto with Rarith.\n    + rewrite sqrt_mult_alt; try lra.\n      symmetry; apply Rinv_mult_distr.\n      auto with Rarith.\n      auto with Rarith.\n  - apply is_RInt_gen_comp_lin_point_0 with (f := fun y => (/ sqrt PI) * exp (- y^2)).\n    + apply Rinv_neq_0_compat.\n      apply sqrt2_neq0.\n    + intros.\n      apply (@ex_RInt_continuous).\n      intros.\n      apply (@ex_derive_continuous).\n      now auto_derive.\n    + replace (/sqrt 2 * 0) with (0) by lra.\n      * replace (Rbar_mult (/ sqrt 2) r) with (r).\n        -- replace (inf_sign r * /2) with (/ sqrt PI * (inf_sign r * sqrt PI/2)).\n           ++ apply (@is_RInt_gen_scal).\n              apply at_point_filter.\n              apply Rbar_locally'_filter.\n              now apply erf_int3.\n           ++ equation_simplifier.\n        -- symmetry.\n           rewrite Rbar_mult_comm.\n           assert (0 < / sqrt 2).\n           apply Rgt_lt.\n           apply Rinv_0_lt_compat.\n           apply sqrt_lt_R0; lra.\n           destruct H.\n           subst.\n           now apply Rbar_mult_p_infty_pos.\n           subst.\n           now apply Rbar_mult_m_infty_pos.  \nQed.\n\nLemma std_CDF_from_erf0 :\n  forall x:R, is_RInt_gen Standard_Gaussian_PDF (Rbar_locally' m_infty) (at_point x)  ((/ 2) + (/2)*erf (x/sqrt 2)).\nProof.\n  intros.\n  apply (@is_RInt_gen_Chasles) with (b := 0) (l1 := /2) (l2 := /2 * erf (x / sqrt 2)).  \n  apply Rbar_locally'_filter.\n  apply at_point_filter.\n  replace (/2) with (opp (- /2)).\n  apply (@is_RInt_gen_swap).\n  apply Rbar_locally'_filter.\n  apply at_point_filter.\n  replace (- / 2) with (inf_sign m_infty * /2).\n  apply Standard_Gaussian_PDF_int1_pm.\n  now right.\n  compute; lra.\n  compute; lra.\n  rewrite is_RInt_gen_at_point.\n  replace (/ 2 * erf (x / sqrt 2)) with (RInt Standard_Gaussian_PDF 0 x).\n  apply (@RInt_correct).\n  apply ex_RInt_Standard_Gaussian_PDF.\n  apply std_from_erf0.\nQed.\n\nLemma std_CDF_from_erf :\n  forall x:R, Standard_Gaussian_CDF x =  (/ 2) + (/2)*erf (x/sqrt 2).\nProof.\n  intros.\n  unfold Standard_Gaussian_CDF.\n  apply is_RInt_gen_unique.\n  apply std_CDF_from_erf0.\nQed.\n\nLemma Standard_Gaussian_PDF_normed : \n  is_RInt_gen Standard_Gaussian_PDF (Rbar_locally m_infty) (Rbar_locally p_infty) 1.\nProof.  \n  replace (1) with (plus (/ 2) (/ 2)).\n  apply (@is_RInt_gen_Chasles) with (b := 0) (l1 := /2) (l2 := /2).\n  apply Rbar_locally_filter.\n  apply Rbar_locally_filter.  \n  replace (/ 2) with (opp (opp (/2))).\n  apply (@is_RInt_gen_swap) with (l := (opp (/2))).\n  apply Rbar_locally_filter.  \n  apply at_point_filter.\n  replace (opp (/ 2)) with (inf_sign m_infty * /2).  \n  apply Standard_Gaussian_PDF_int1_pm.\n  now right.\n  compute; lra.\n  apply opp_opp.\n  replace (/ 2) with (inf_sign p_infty * /2).\n  apply Standard_Gaussian_PDF_int1_pm.\n  now left.\n  compute; lra.\n  compute; lra.\nQed.\n\nLemma variance_standard_gaussian0 :\n  is_RInt_gen (fun t => (t^2-1)*Standard_Gaussian_PDF t + Standard_Gaussian_PDF t) (Rbar_locally m_infty) (Rbar_locally p_infty) 1.\nProof.\n  intros.\n  replace (1) with (0 + 1) at 1 by lra.\n  apply is_RInt_gen_plus with \n      (f:=(fun t => (t^2-1)*Standard_Gaussian_PDF t)) (lf :=0)\n      (g:=(fun t => Standard_Gaussian_PDF t)) (lg := 1).\n  apply variance_int1_middle.\n  apply Standard_Gaussian_PDF_normed.\nQed.\n\nLemma variance_standard_gaussian :\n  is_RInt_gen (fun t => t^2*Standard_Gaussian_PDF t) \n           (Rbar_locally m_infty) (Rbar_locally p_infty) 1.\nProof.\n  eapply is_RInt_gen_ext; try eapply variance_standard_gaussian0.\n  eapply (Filter_prod _ _ _ (fun _ => True) (fun _ => True))\n  ; simpl; eauto.\n  intros; simpl.\n  unfold Standard_Gaussian_PDF; lra.\n  Unshelve.\n  exact 0.\n  exact 0.\nQed.\n\nLemma variance_general_gaussian (mu sigma : R) :\n  sigma > 0 ->\n  ex_RInt_gen (fun t : R => sigma ^ 2 * t ^ 2 * Standard_Gaussian_PDF t)\n              (Rbar_locally' m_infty) (at_point (- mu / sigma)) ->\n  ex_RInt_gen (fun t : R => sigma ^ 2 * t ^ 2 * Standard_Gaussian_PDF t)\n              (at_point (- mu / sigma)) (Rbar_locally' p_infty) ->\n  is_RInt_gen (fun t => (t-mu)^2*General_Gaussian_PDF mu sigma t) \n              (Rbar_locally' m_infty) (Rbar_locally' p_infty) (sigma^2).\nProof.\n  intros.\n  assert (sigma <> 0).\n  now apply Rgt_not_eq.\n  assert (Rbar_plus (Rbar_mult (/ sigma) m_infty) (- mu / sigma) = m_infty).\n  rewrite Rbar_mult_comm.\n  rewrite Rbar_mult_m_infty_pos.\n  now compute.\n  apply Rinv_0_lt_compat; lra.  \n  assert (Rbar_plus (Rbar_mult (/ sigma) p_infty) (- mu / sigma) = p_infty).\n  rewrite Rbar_mult_comm.\n  rewrite Rbar_mult_p_infty_pos.\n  now compute.\n  apply Rinv_0_lt_compat; lra.  \n  apply (is_RInt_gen_ext (fun t => /sigma * (sigma^2 * (/sigma * t + (-mu/sigma))^2 * Standard_Gaussian_PDF(/sigma*t + (-mu/sigma))))).\n  apply filter_forall.\n  intros.\n  rewrite gen_from_std.\n  replace (/sigma * x0 + - mu/sigma) with ((x0-mu)/sigma) by lra.\n  equation_simplifier.\n  lra.\n  apply is_RInt_gen_comp_lin with (u := /sigma) (v := -mu/sigma) \n                                  (f:=fun t => sigma^2 * t^2 * Standard_Gaussian_PDF t).\n  now apply Rinv_neq_0_compat.\n  replace (Rbar_plus (Rbar_mult (/ sigma) m_infty) (- mu / sigma)) with\n          (m_infty).\n  replace (/ sigma * 0 + - mu / sigma) with (-mu/sigma) by lra.\n  assumption.\n  replace (/ sigma * 0 + - mu / sigma) with (-mu/sigma) by lra.\n  replace (Rbar_plus (Rbar_mult (/ sigma) p_infty) (- mu / sigma)) with\n          (p_infty).\n  assumption.\n  intros.\n  apply (ex_RInt_ext (fun t => sigma^2 * (t^2 * Standard_Gaussian_PDF t))).\n  intros.\n  lra.\n  apply (@ex_RInt_scal) with (k := sigma^2) (f := fun t => t^2 * Standard_Gaussian_PDF t).\n  apply ex_RInt_Standard_Gaussian_variance_PDF.\n  replace (sigma^2) with (sigma^2 * 1) at 1 by lra.\n  apply (is_RInt_gen_ext (fun t=>sigma^2 * (t^2 * Standard_Gaussian_PDF t))).\n  apply filter_forall.\n  intros.\n  lra.\n  apply (@is_RInt_gen_scal).\n  apply Rbar_locally'_filter.\n  apply Rbar_locally'_filter.      \n  replace (Rbar_plus (Rbar_mult (/ sigma) m_infty) (- mu / sigma)) with \n      (m_infty).\n  replace (Rbar_plus (Rbar_mult (/ sigma) p_infty) (- mu / sigma)) with \n      (p_infty).\n  apply variance_standard_gaussian.\nQed.\n\nLemma General_Gaussian_PDF_normed (mu sigma:R) : \n  sigma>0 ->\n  ex_RInt_gen Standard_Gaussian_PDF (Rbar_locally' m_infty) (at_point (- mu / sigma)) ->\n  ex_RInt_gen Standard_Gaussian_PDF (at_point (- mu / sigma)) (Rbar_locally' p_infty) ->\n  is_RInt_gen (General_Gaussian_PDF mu sigma) (Rbar_locally' m_infty) (Rbar_locally' p_infty) 1.\nProof.\n  intros.\n  assert (Rbar_plus (Rbar_mult (/ sigma) m_infty) (- mu / sigma) = m_infty).\n  rewrite Rbar_mult_comm.\n  rewrite Rbar_mult_m_infty_pos.\n  now compute.\n  apply Rinv_0_lt_compat; lra.  \n  assert (Rbar_plus (Rbar_mult (/ sigma) p_infty) (- mu / sigma) = p_infty).\n  rewrite Rbar_mult_comm.\n  rewrite Rbar_mult_p_infty_pos.\n  now compute.\n  apply Rinv_0_lt_compat; lra.  \n  \n  apply (is_RInt_gen_ext (fun x =>  / sigma * Standard_Gaussian_PDF (/sigma *x + (-mu/sigma)))).\n  apply filter_forall.\n  intros.\n  rewrite gen_from_std.\n  apply Rmult_eq_compat_l.\n  f_equal; lra.\n  trivial.\n  apply is_RInt_gen_comp_lin with (u := /sigma) (v := -mu/sigma) \n                                  (f:=Standard_Gaussian_PDF).\n  apply Rinv_neq_0_compat.\n  now apply Rgt_not_eq.\n  replace (Rbar_plus (Rbar_mult (/ sigma) m_infty) (- mu / sigma)) with\n          (m_infty).\n  replace (/ sigma * 0 + - mu / sigma) with (-mu/sigma) by lra.\n  trivial.\n  replace (/ sigma * 0 + - mu / sigma) with (-mu/sigma) by lra.  \n  replace (Rbar_plus (Rbar_mult (/ sigma) p_infty) (- mu / sigma)) with\n          (p_infty).\n  trivial.\n  apply ex_RInt_Standard_Gaussian_PDF.\n  replace (Rbar_plus (Rbar_mult (/ sigma) m_infty) (- mu / sigma)) with\n          (m_infty).\n  replace (Rbar_plus (Rbar_mult (/ sigma) p_infty) (- mu / sigma)) with\n          (p_infty).\n  apply Standard_Gaussian_PDF_normed.\nQed.  \n\nLemma mean_general_gaussian (mu sigma:R) :\n  sigma > 0 ->\n    ex_RInt_gen Standard_Gaussian_PDF (Rbar_locally' m_infty) (at_point (- mu / sigma)) ->\n    ex_RInt_gen Standard_Gaussian_PDF (at_point (- mu / sigma)) (Rbar_locally' p_infty) ->\n\n    is_RInt_gen (fun t => t*General_Gaussian_PDF mu sigma t) \n                           (Rbar_locally' m_infty) (Rbar_locally' p_infty) mu.\nProof.\n  intros.\n  assert (sigma <> 0).\n  now apply Rgt_not_eq.\n  apply (is_RInt_gen_ext (fun t => mu*General_Gaussian_PDF mu sigma t - (mu-t)*General_Gaussian_PDF mu sigma t)). \n  apply filter_forall.\n  intros.\n  apply Rminus_diag_uniq; lra.\n  replace (mu) with (mu*1 - 0) at 1 by lra.\n  apply (@is_RInt_gen_minus).\n  apply Rbar_locally'_filter.\n  apply Rbar_locally'_filter.  \n  apply (@is_RInt_gen_scal).\n  apply Rbar_locally'_filter.\n  apply Rbar_locally'_filter.  \n  now apply General_Gaussian_PDF_normed.\n  apply (is_RInt_gen_ext (fun t => sigma^2 * Derive (General_Gaussian_PDF mu sigma) t)).\n  apply filter_forall.\n  intros.\n  rewrite Derive_General_Gaussian_PDF.\n  equation_simplifier.\n  assumption.\n  replace (0) with (sigma^2 * 0) by lra.\n  apply (@is_RInt_gen_scal).\n  apply Rbar_locally'_filter.\n  apply Rbar_locally'_filter.    \n  replace (0) with (0 - 0) by lra.\n  apply is_RInt_gen_Derive.\n  apply filter_forall.\n  intros.\n  now apply ex_derive_General_Gaussian_PDF.\n  apply filter_forall.\n  intros.\n  apply continuous_Derive_General_Gaussian_PDF.\n  now unfold General_Gaussian_PDF.\n  replace (0) with ( / (sigma * sqrt (2*PI)) * 0) by lra.  \n  apply is_lim_scal_l with (a:= / (sigma * sqrt (2 * PI))) (l := 0).\n  apply (is_lim_ext (fun t => exp(-((/sigma * t)+ (-mu/sigma))^2/2))).\n  intros.\n  f_equal; now field_simplify.\n  apply is_lim_comp_lin with (f := fun t => exp(-t^2/2)) (a := /sigma) (b:= -mu/sigma).\n  replace (Rbar_plus (Rbar_mult (/ sigma) m_infty) (- mu / sigma)) with (m_infty).\n  apply limexp_neg_minf.\n  rewrite Rbar_mult_comm.\n  rewrite Rbar_mult_m_infty_pos.\n  now compute.\n  apply Rinv_0_lt_compat; lra.\n  now apply Rinv_neq_0_compat.\n  unfold General_Gaussian_PDF.\n  replace (0) with ( / (sigma * sqrt (2*PI)) * 0) by lra.  \n  apply is_lim_scal_l with (a:= / (sigma * sqrt (2 * PI))) (l := 0).\n  apply (is_lim_ext (fun t => exp(-((/sigma * t)+ (-mu/sigma))^2/2))).\n  intros.\n  f_equal; now field_simplify.\n  apply is_lim_comp_lin with (f := fun t => exp(-t^2/2)) (a := /sigma) (b:= -mu/sigma).\n  replace (Rbar_plus (Rbar_mult (/ sigma) p_infty) (- mu / sigma)) with (p_infty).  \n  apply limexp_neg_inf.\n  rewrite Rbar_mult_comm.\n  rewrite Rbar_mult_p_infty_pos.\n  now compute.\n  apply Rinv_0_lt_compat; lra.\n  now apply Rinv_neq_0_compat.\nQed.\n\nEnd Gaussian_Distribution.\n", "meta": {"author": "IBM", "repo": "FormalML", "sha": "e399d096f1ad572420dbd1c638d593eee2129cbe", "save_path": "github-repos/coq/IBM-FormalML", "path": "github-repos/coq/IBM-FormalML/FormalML-e399d096f1ad572420dbd1c638d593eee2129cbe/coq/ProbTheory/Gaussian.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.743292977897249}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import Permutation.\nLoad sorted.\n\n(* Auxiliar function: orderly insert a natural number in an ordered list *)\nFixpoint insert (x : nat) (xs : list nat) {struct xs} : list nat :=\nmatch xs with\n  | nil     => [x]\n  | z :: zs =>\n    match  x <=? z with       (* x <=? z = Nat.leb x z *)\n      | true  => x :: (z :: zs)\n      | false => z :: (insert x zs)\n    end\nend.\n\nFixpoint insert_sort (l : list nat) {struct l} : list nat :=\nmatch l with\n  | nil     => nil\n  | x :: xs => insert x (insert_sort xs)\nend.\n\nLemma insert_perm : forall (x : nat) (l : list nat), Permutation (insert x l) (x :: l).\nProof.\n  induction l as [|x' l' IHl']; auto.\n  simpl. destruct (x <=? x'); auto.\n  apply perm_trans with (x' :: x :: l'); auto. apply perm_swap.\nQed.\n\nTheorem permutation_insert_sort: forall l, Permutation l (insert_sort l).\nProof.\n  induction l as [|x' l' IHl']; auto.\n  assert (Permutation (x' :: l') (x' :: insert_sort l')); auto.\n  simpl. rewrite H. rewrite insert_perm. reflexivity.\nQed.\n\nLemma insert_sorted_preserve : forall x l, Sorted l -> Sorted (insert x l).\nProof.\n  intros x l H. induction H as [ | x' |x' x'' l' IHl' IHIHl']; simpl; auto.\n  + remember (x <=? x') as bh. symmetry in Heqbh. destruct bh. \n  \t- apply leb_complete in Heqbh. auto.\n  \t- apply leb_complete_conv in Heqbh. auto with *. \n\t+ remember (x <=? x') as bh.  symmetry in Heqbh. destruct bh. \n\t\t- apply leb_complete in Heqbh. auto.\n\t\t- remember (x <=? x'') as bh''. symmetry in Heqbh''. destruct bh''.\n\t\t\t* apply leb_complete in Heqbh''. apply leb_complete_conv in Heqbh. auto with *.\n\t\t\t* constructor; simpl in IHIHl'; rewrite Heqbh'' in IHIHl'; auto.\nQed.\nHint Resolve insert_sorted_preserve.\n\nTheorem insert_sort_sorted : forall l, Sorted (insert_sort l).\nProof.\n  intros. induction l as [|x' l']; simpl; auto.\nQed.\n\nTheorem insert_sort_correct : Sorting_correct insert_sort.\nProof.\n  constructor. split. apply insert_sort_sorted. apply permutation_insert_sort.\nQed.\n", "meta": {"author": "nico-rodriguez", "repo": "coq-sorting-algorithms", "sha": "2d757b335bef8a55a17ed8661251817c47bd60c7", "save_path": "github-repos/coq/nico-rodriguez-coq-sorting-algorithms", "path": "github-repos/coq/nico-rodriguez-coq-sorting-algorithms/coq-sorting-algorithms-2d757b335bef8a55a17ed8661251817c47bd60c7/insert_sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7431987908829114}}
{"text": "Require Import Arith.\n\nRequire Import NotationUtils.\n\nDefinition ble_nat := leb.\n\nDefinition max (l : list nat) : nat :=\n  fold_right max 0 l.\n\nLemma max_list_upperBound : forall l a ,\n  In a l ->\n  a <= max l.\nProof.\n  intros.\n  induction l; simpl.\n  - contradiction.\n  - apply Nat.max_le_iff.\n    destruct H; subst; auto.\nQed.\n", "meta": {"author": "atlanmod", "repo": "coqtl", "sha": "5daf5d915b66328ae5ec48f55c44731372563c87", "save_path": "github-repos/coq/atlanmod-coqtl", "path": "github-repos/coq/atlanmod-coqtl/coqtl-5daf5d915b66328ae5ec48f55c44731372563c87/core/utils/ArithUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7431680870182713}}
{"text": "Add LoadPath \".\" as OPAT.\nRequire Import OPAT.aula3.\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. 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\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 mult_0_plus : forall n m : nat,\n  (0 + n) * m = n * m.\nProof.\n  intros n m.\nAdmitted.\n\nTheorem mult_S_1 : forall n m : nat,\n  m = S n ->\n  m * (1 + n) = m * m.\nProof.\nAdmitted.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  simpl.  (* does nothing! *)\nAbort.\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\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.\n  - destruct c.\n    { destruct d. - reflexivity. - reflexivity. }\n    { destruct d. - reflexivity. - reflexivity. }\n  - destruct c.\n    { destruct d. - reflexivity. - reflexivity. }\n    { destruct d. - reflexivity. - reflexivity. }\nQed.\n", "meta": {"author": "bugarela", "repo": "Coq", "sha": "9f4973fec5b34ed836aa2239a009385e0549c024", "save_path": "github-repos/coq/bugarela-Coq", "path": "github-repos/coq/bugarela-Coq/Coq-9f4973fec5b34ed836aa2239a009385e0549c024/OPAT exercises/aula4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7431680857229056}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. You may distribute   *)\n(* under the terms of either the CeCILL-B License or the CeCILL        *)\n(* version 2 License, as specified in the README file.                 *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(**************************************************************************)\n(* This file deals with divisibility for natural numbers.                 *)\n(* It contains the definitions of:                                        *)\n(*      edivn m d   == the pair composed of the quotient and remainder    *)\n(*                     of the euclidian division of m by d                *)\n(*          m %/ d  == quotient of m by d                                 *)\n(*          m %% d  == remainder of m dy d                                *)\n(*  m = n %[mod d]  <=> m equals n modulo d                               *)\n(*  m == n %[mod d] <=> m equals n modulo d (boolean version)             *)\n(*  m <> n %[mod d] <=> m differs from n modulo d                         *)\n(*  m != n %[mod d] <=> m differs from n modulo d (boolean version)       *)\n(*           d %| m <=> d divides m                                       *)\n(*         gcdn m n == the GCD of m and n                                 *)\n(*        egcdn m n == the extended GCD of m and n                        *)\n(*         lcmn m n == the LCM of m and n                                 *)\n(*      coprime m n <=> m and n are coprime                               *)\n(*  chinese m n r s == witness of the chinese remainder theorem           *)\n(**************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** Euclidian division *)\n\nDefinition edivn_rec d := fix loop (m q : nat) {struct m} :=\n  if m - d is m'.+1 then loop m' q.+1 else (q, m).\n\nDefinition edivn m d := if d > 0 then edivn_rec d.-1 m 0 else (0, m).\n\nCoInductive edivn_spec (m d : nat) : nat * nat -> Type :=\n  EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r).\n\nLemma edivnP : forall m d, edivn_spec m d (edivn m d).\nProof.\nrewrite /edivn => m [|d] //=; rewrite -{1}[m]/(0 * d.+1 + m).\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=; rewrite ltnS => le_mn.\nrewrite subn_if_gt; case: ltnP => [// | le_dm].\nrewrite -{1}(subnKC le_dm) -addSn addnA -mulSnr; apply: IHn.\napply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_eq : forall d q r, r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> d q r lt_rd; have d_gt0: 0 < d by exact: leq_trans lt_rd.\ncase: edivnP lt_rd => q' r'; rewrite d_gt0 /=.\nwlog: q q' r r' / q <= q' by case (ltnP q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case: eqP => [-> _|_] /=; first by move/addnI->.\nrewrite -(leq_pmul2r d_gt0); move/leq_add=> Hqr Eqr _; move/Hqr {Hqr}.\nby rewrite addnS ltnNge mulSn -addnA Eqr addnCA addnA leq_addr.\nQed.\n\nDefinition divn m d := (edivn m d).1.\n\nNotation \"m %/ d\" := (divn m d) (at level 40, no associativity) : nat_scope.\n\n(* We redefine modn so that it is structurally decreasing. *)\n\nDefinition modn_rec d := fix loop (m : nat) :=\n  if m - d is m'.+1 then loop m' else m.\n\nDefinition modn m d := if d > 0 then modn_rec d.-1 m else m.\n\nNotation \"m %% d\" := (modn m d) (at level 40, no associativity) : nat_scope.\nNotation \"m = n %[mod d ]\" := (m %% d = n %% d)\n  (at level 70, n at next level,\n   format \"'[hv ' m '/'  =  n '/'  %[mod  d ] ']'\") : nat_scope.\nNotation \"m == n %[mod d ]\" := (m %% d == n %% d)\n  (at level 70, n at next level,\n   format \"'[hv ' m '/'  ==  n '/'  %[mod  d ] ']'\") : nat_scope.\nNotation \"m <> n %[mod d ]\" := (m %% d <> n %% d)\n  (at level 70, n at next level,\n   format \"'[hv ' m '/'  <>  n '/'  %[mod  d ] ']'\") : nat_scope.\nNotation \"m != n %[mod d ]\" := (m %% d != n %% d)\n  (at level 70, n at next level,\n   format \"'[hv ' m '/'  !=  n '/'  %[mod  d ] ']'\") : nat_scope.\n\nLemma modn_def : forall m d, m %% d = (edivn m d).2.\nProof.\nrewrite /modn /edivn => m [|d] //=.\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=.\nrewrite ltnS !subn_if_gt; case: (d <= m) => // le_mn.\nby apply: IHn; apply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_def : forall m d, edivn m d = (m %/ d, m %% d).\nProof. by move=> m d; rewrite /divn modn_def; case edivn. Qed.\n\nLemma divn_eq : forall m d, m = m %/ d * d + m %% d.\nProof. by move=> m d; rewrite /divn modn_def; case edivnP. Qed.\n\nLemma div0n : forall d, 0 %/ d = 0. Proof. by case. Qed.\nLemma divn0 : forall m, m %/ 0 = 0. Proof.  by []. Qed.\nLemma mod0n :  forall d, 0 %% d = 0. Proof. by case. Qed.\nLemma modn0 :  forall m, m %% 0 = m. Proof. by []. Qed.\n\nLemma divn_small : forall m d, m < d -> m %/ d = 0.\nProof. by move=> m d lt_md; rewrite /divn (edivn_eq 0). Qed.\n\nLemma divn_addl_mul : forall q m d, 0 < d -> (q * d + m) %/ d = q + m %/ d.\nProof.\nmove=> q m d d_gt0; rewrite {1}(divn_eq m d) addnA -muln_addl.\nby rewrite /divn edivn_eq // modn_def; case: edivnP; rewrite d_gt0.\nQed.\n\nLemma mulnK : forall m d, 0 < d -> m * d %/ d = m.\nProof.\nby move=> m d d_gt0; rewrite -[m * d]addn0 divn_addl_mul // div0n addn0.\nQed.\n\nLemma mulKn : forall m d, 0 < d -> d * m %/ d = m.\nProof. by move=> *; rewrite mulnC mulnK. Qed.\n\nLemma modn1 : forall m, m %% 1 = 0.\nProof. by move=> m; rewrite modn_def; case: edivnP => ? []. Qed.\n\nLemma divn1: forall m, m %/ 1 = m.\nProof. by move=> m; rewrite {2}(@divn_eq m 1) // modn1 addn0 muln1. Qed.\n\nLemma divnn : forall d, d %/ d = (0 < d).\nProof. by case=> // d; rewrite -{1}[d.+1]muln1 mulKn. Qed.\n\nLemma divn_pmul2l : forall p m d, p > 0 -> p * m %/ (p * d) = m %/ d.\nProof.\nmove=> p m d p_gt0; case: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nrewrite {2}/divn; case: edivnP; rewrite d_gt0 /= => q r ->{m} lt_rd.\nrewrite muln_addr mulnCA divn_addl_mul; last by rewrite muln_gt0 p_gt0.\nby rewrite addnC divn_small // ltn_pmul2l.\nQed.\nImplicit Arguments divn_pmul2l [p m d].\n\nLemma divn_pmul2r : forall p m d, p > 0 -> m * p %/ (d * p) = m %/ d.\nProof. by move=> p m d p_gt0; rewrite -!(mulnC p) divn_pmul2l. Qed.\nImplicit Arguments divn_pmul2r [p m d].\n\nLemma ltn_mod : forall m d, (m %% d < d) = (0 < d).\nProof. by move=> m [|d] //; rewrite modn_def; case: edivnP. Qed.\n\nLemma ltn_pmod : forall m d, 0 < d -> m %% d < d.\nProof. by move=> m d; rewrite ltn_mod. Qed.\n\nLemma leq_floor : forall m d, m %/ d * d <= m.\nProof. by move=> m d; rewrite {2}(divn_eq m d) leq_addr. Qed.\n\nLemma leq_mod : forall m d, m %% d  <= m.\nProof. by move=> m d; rewrite {2}(divn_eq m d) leq_addl. Qed.\n\nLemma leq_div : forall m d, m %/ d <= m.\nProof. move=> m [|d] //; exact: leq_trans (leq_pmulr _ _) (leq_floor _ _). Qed.\n\nLemma ltn_ceil : forall m d, 0 < d -> m < (m %/ d).+1 * d.\nProof.\nby move=> m d ? /=; rewrite {1}(divn_eq m d) -addnS mulSnr leq_add2l ltn_mod.\nQed.\n\nLemma ltn_divl : forall m n d, d > 0 -> (m %/ d < n) = (m < n * d).\nProof.\nmove=> m n d d_gt0; apply/idP/idP.\n  rewrite -(leq_pmul2r d_gt0); exact: leq_trans (ltn_ceil _ _).\nrewrite !ltnNge -(@leq_pmul2r d n) //; apply: contra => le_nd_floor.\nexact: leq_trans le_nd_floor (leq_floor _ _).\nQed.\n\nLemma leq_divr : forall m n d, d > 0 -> (m <= n %/ d) = (m * d <= n).\nProof. by move=> m n d d_gt0; rewrite leqNgt ltn_divl // -leqNgt. Qed.\n\nLemma ltn_Pdiv : forall m d, 1 < d -> 0 < m -> m %/ d < m.\nProof. by move=> m d d_gt1 m_gt0; rewrite ltn_divl ?ltn_Pmulr // ltnW. Qed.\n\nLemma divn_gt0 : forall d m, 0 < d -> (0 < m %/ d) = (d <= m).\nProof. by move=> d m d_gt0; rewrite leq_divr ?mul1n. Qed.\n\nLemma divn_divl : forall m n p, m %/ n %/ p = m %/ (n * p).\nProof.\nmove=> m [|n] [|p]; rewrite ?muln0 ?div0n //.\nrewrite {1}(divn_eq m (n.+1 * p.+1)) mulnA mulnAC !divn_addl_mul //.\nby rewrite addnC divn_small // ltn_divl // mulnC ltn_mod.\nQed.\n\nLemma divnAC : forall m n p, m %/ n %/ p =  m %/ p %/ n.\nProof. by move=> m n p; rewrite !divn_divl mulnC. Qed.\n\nLemma modn_small : forall m d, m < d -> m %% d = m.\nProof. by move=> m d lt_md; rewrite {2}(divn_eq m d) divn_small. Qed.\n\nLemma modn_mod : forall m d, m %% d = m %[mod d].\nProof. by move=> m [|d] //; apply: modn_small; rewrite ltn_mod. Qed.\n\nLemma modn_addl_mul : forall p m d, p * d + m = m %[mod d].\nProof.\nmove=> p m d; case: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nby rewrite {1}(divn_eq m d) addnA -muln_addl modn_def edivn_eq // ltn_mod.\nQed.\n\nLemma modn_pmul2l : forall p m d, 0 < p -> p * m %% (p * d) = p * (m %% d).\nProof.\nmove=> p m d p_gt0; apply: (@addnI (p * (m %/ d * d))).\nby rewrite -muln_addr -divn_eq mulnCA -(divn_pmul2l p_gt0) -divn_eq.\nQed.\nImplicit Arguments modn_pmul2l [p m d].\n\nLemma modn_addl : forall m d, d + m = m %[mod d].\nProof. by move=> m d; rewrite -{1}[d]mul1n modn_addl_mul. Qed.\n\nLemma modn_addr : forall m d, m + d = m %[mod d].\nProof. by move=> *; rewrite addnC modn_addl. Qed.\n\nLemma modnn : forall d, d %% d = 0.\nProof. by move=> d; rewrite -{1}[d]addn0 modn_addl mod0n. Qed.\n\nLemma modn_mull : forall p d, p * d %% d = 0.\nProof. by move=> p d; rewrite -[p * d]addn0 modn_addl_mul mod0n. Qed.\n\nLemma modn_mulr : forall p d, d * p %% d = 0.\nProof. by move=> p d; rewrite mulnC modn_mull. Qed.\n\nLemma modn_addml : forall m n d, m %% d + n = m + n %[mod d].\nProof. by move=> m n d; rewrite {2}(divn_eq m d) -addnA modn_addl_mul. Qed.\n\nLemma modn_addmr : forall m n d, m + n %% d = m + n %[mod d].\nProof. by move=> m n d; rewrite !(addnC m) modn_addml. Qed.\n\nLemma modn_add2m : forall m n d, m %% d  + n %% d = m + n %[mod d].\nProof. by move=> m n d; rewrite modn_addml modn_addmr. Qed.\n\nLemma modn_mulml : forall m n d, m %% d * n = m * n %[mod d].\nProof.\nby move=> m n d; rewrite {2}(divn_eq m d) muln_addl mulnAC modn_addl_mul.\nQed.\n\nLemma modn_mulmr : forall m n d, m * (n %% d) = m * n %[mod d].\nProof. by move=> m n d; rewrite !(mulnC m) modn_mulml. Qed.\n\nLemma modn_mul2m : forall m n d, m %% d * (n %% d) = m * n %[mod d].\nProof. by move=> m n d; rewrite modn_mulml modn_mulmr. Qed.\n\nLemma modn2 : forall m, m %% 2 = odd m.\nProof. by elim=> //= m IHm; rewrite -addn1 -modn_addml IHm; case odd. Qed.\n\nLemma divn2 : forall m, m %/ 2 = m./2.\nProof.\nby move=> m; rewrite {2}(divn_eq m 2) modn2 muln2 addnC half_bit_double.\nQed.\n\nLemma odd_mod : forall m d, odd d = false -> odd (m %% d) = odd m.\nProof.\nby move=> m d d_even; rewrite {2}(divn_eq m d) odd_add odd_mul d_even andbF.\nQed.\n\nLemma modn_exp: forall m n a, (a %% n) ^ m = a ^ m %[mod n].\nProof.\nby elim=> // m Hrec n a; rewrite !expnS -modn_mulmr Hrec modn_mulml modn_mulmr.\nQed.\n\n(** Divisibility **)\n\nDefinition dvdn d m := m %% d == 0.\n\nNotation \"m %| d\" := (dvdn m d) (at level 70, no associativity) : nat_scope.\n\nLemma dvdn2 : forall n, (2 %| n) = ~~ odd n.\nProof. by move=> n; rewrite /dvdn modn2; case (odd n). Qed.\n\nLemma dvdnP : forall d m, reflect (exists k, m = k * d) (d %| m).\nProof.\nmove=> d m; apply: (iffP eqP) => [Hm | [k ->]]; last by rewrite modn_mull.\nby exists (m %/ d); rewrite {1}(divn_eq m d) Hm addn0.\nQed.\nImplicit Arguments dvdnP [d m].\nPrenex Implicits dvdnP.\n\nLemma dvdn0 : forall d, d %| 0.\nProof. by case. Qed.\n\nLemma dvd0n : forall n, (0 %| n) = (n == 0).\nProof. by case. Qed.\n\nLemma dvdn1 : forall d, (d %| 1) = (d == 1).\nProof. by case=> [|[|n]] //; rewrite /dvdn modn_small. Qed.\n\nLemma dvd1n : forall m, 1 %| m.\nProof. by move=> m; rewrite /dvdn modn1. Qed.\n\nLemma dvdn_gt0 : forall d m, m > 0 -> d %| m -> d > 0.\nProof. by do 2!case. Qed.\n\nLemma dvdnn: forall m, m %| m.\nProof. by move=> m; rewrite /dvdn modnn. Qed.\n\nLemma dvdn_mull: forall d m n, d %| n -> d %| m * n.\nProof. by move=> d m n; case/dvdnP=> n' ->; rewrite /dvdn mulnA modn_mull. Qed.\n\nLemma dvdn_mulr: forall d m n, d %| m -> d %| m * n.\nProof. by move=> d m n d_m; rewrite mulnC dvdn_mull. Qed.\n\nHint Resolve dvdn0 dvd1n dvdnn dvdn_mull dvdn_mulr.\n\nLemma dvdn_mul: forall d1 d2 m1 m2, d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\nmove=> d1 d2 m1 m2; case/dvdnP=> q1 ->; case/dvdnP=> q2 ->.\nby rewrite mulnCA -mulnA 2?dvdn_mull.\nQed.\n\nLemma dvdn_trans: forall n d m, d %| n -> n %| m -> d %| m.\nProof. move=> n d m Hn; move/dvdnP => [n1 ->]; exact: dvdn_mull. Qed.\n\nLemma dvdn_eq : forall d m, (d %| m) = (m %/ d * d == m).\nProof.\nmove=> d m; apply/eqP/eqP=> [modm0 | <-]; last exact: modn_mull.\nby rewrite {2}(divn_eq m d) modm0 addn0.\nQed.\n\nLemma divnK : forall d m, d %| m -> m %/ d * d = m.\nProof. by move=> m d; rewrite dvdn_eq; move/eqP. Qed.\n\nLemma leq_divl : forall d m n, d %| m -> (m %/ d <= n) = (m <= n * d).\nProof. by case=> [[]//|d] m n dv_d_m; rewrite -(@leq_pmul2r d.+1) ?divnK. Qed.\n\nLemma ltn_divr : forall d m n, d %| m -> (n < m %/ d) = (n * d < m).\nProof. by move=> d m n dv_d_m; rewrite !ltnNge leq_divl. Qed.\n\nLemma eqn_div : forall d m n, d > 0 -> d %| m -> (n == m %/ d) = (n * d == m).\nProof. by move=> d m n d_gt0 dv_d_m; rewrite -(eqn_pmul2r d_gt0) divnK. Qed.\n\nLemma eqn_mul : forall d m n, d > 0 -> d %| m -> (m == n * d) = (m %/ d == n).\nProof. by move=> d m n d_gt0 dv_d_m; rewrite eq_sym -eqn_div // eq_sym. Qed.\n\nLemma divn_mulAC : forall d m n, d %| m -> m %/ d * n = m * n %/ d.\nProof.\ncase=> [[]//|d] m n dv_d_m; apply/eqP.\nby rewrite eqn_div ?dvdn_mulr // mulnAC divnK.\nQed.\n\nLemma divn_mulA : forall d m n, d %| n -> m * (n %/ d) = m * n %/ d.\nProof. by move=> d m n dv_d_m; rewrite !(mulnC m) divn_mulAC. Qed.\n\nLemma divn_mulCA : forall d m n,\n  d %| m -> d %| n -> m * (n %/ d) = n * (m %/ d).\nProof. by move=> d m n dv_d_m dv_d_n; rewrite mulnC divn_mulAC ?divn_mulA. Qed.\n\nLemma divn_divr : forall m n p, p %| n -> m %/ (n %/ p) = m * p %/ n.\nProof. by move=> m n [|p] dv_n; rewrite -{2}(divnK dv_n) // divn_pmul2r. Qed.\n\nLemma modn_dvdm : forall m n d, d %| m -> n %% m = n %[mod d].\nProof.\nmove=> m n d; case/dvdnP=> q def_m.\nby rewrite {2}(divn_eq n m) {3}def_m mulnA modn_addl_mul.\nQed.\n\nLemma dvdn_leq : forall d m, 0 < m -> d %| m -> d <= m.\nProof.\nby move=> d m m_gt0; case/dvdnP=> [[|k] Dm]; rewrite Dm // leq_addr in m_gt0 *.\nQed.\n\nLemma gtnNdvd : forall n d, 0 < n -> n < d -> (d %| n) = false.\nProof. by move=> n d n_gt0 ltnd; rewrite /dvdn eqn0Ngt modn_small ?n_gt0. Qed.\n\nLemma eqn_dvd : forall m n, (m == n) = (m %| n) && (n %| m).\nProof.\ncase=> [|m] [|n] //; apply/idP/andP; first by move/eqP->; auto.\nrewrite eqn_leq => [[Hmn Hnm]]; apply/andP; have:= dvdn_leq; auto.\nQed.\n\nLemma dvdn_pmul2l : forall p d m, 0 < p -> (p * d %| p * m) = (d %| m).\nProof. by case=> // p d m _; rewrite /dvdn modn_pmul2l // muln_eq0. Qed.\nImplicit Arguments dvdn_pmul2l [p m d].\n\nLemma dvdn_pmul2r : forall p d m, 0 < p -> (d * p %| m * p) = (d %| m).\nProof. by move=> n d m Hn; rewrite -!(mulnC n) dvdn_pmul2l. Qed.\nImplicit Arguments dvdn_pmul2r [p m d].\n\nLemma dvdn_addr : forall m d n, d %| m -> (d %| m + n) = (d %| n).\nProof. by move=> n d m; move/dvdnP=> [k ->]; rewrite /dvdn modn_addl_mul. Qed.\n\nLemma dvdn_addl : forall n d m, d %| n -> (d %| m + n) = (d %| m).\nProof. by move=> n d m; rewrite addnC; exact: dvdn_addr. Qed.\n\nLemma dvdn_add : forall d m n, d %| m -> d %| n -> d %| m + n.\nProof. by move=> n d m; move/dvdn_addr->. Qed.\n\nLemma dvdn_add_eq : forall d m n, d %| m + n -> (d %| m) = (d %| n).\nProof. by move=> *; apply/idP/idP; [move/dvdn_addr <-| move/dvdn_addl <-]. Qed.\n\nLemma dvdn_subr : forall d m n, n <= m -> d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> d m n le_n_m dv_d_m; apply: dvdn_add_eq; rewrite subnK. Qed.\n\nLemma dvdn_subl : forall d m n, n <= m -> d %| n -> (d %| m - n) = (d %| m).\nProof. by move=> d m n le_n_m dv_d_m; rewrite -(dvdn_addl _ dv_d_m) subnK. Qed.\n\nLemma dvdn_sub : forall d m n, d %|m -> d %| n -> d %| m - n.\nProof.\nmove=> d n m; case: (leqP m n) => Hm; first by move/dvdn_subr <-.\nby rewrite (eqnP (ltnW Hm)) dvdn0.\nQed.\n\nLemma dvdn_exp : forall k d m, 0 < k -> d %| m -> d %| (m ^ k).\nProof. by case=> // *; rewrite expnS dvdn_mulr. Qed.\n\nHint Resolve dvdn_add dvdn_sub dvdn_exp.\n\nLemma eqn_mod_dvd : forall d m n, n <= m -> (m == n %[mod d]) = (d %| m - n).\nProof.\nrewrite /dvdn => d m n le_nm; apply/eqP/eqP => [eq_mod | mod_mn_0]; last first.\n  by rewrite -(subnK le_nm) -modn_addml mod_mn_0.\nby rewrite (divn_eq m d) (divn_eq n d) eq_mod subn_add2r -muln_subl modn_mull.\nQed.\n\nLemma divn_addl : forall m n d, d %| m -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by move=> m n [//|d] dv_m; rewrite -{1}(divnK dv_m) divn_addl_mul. Qed.\n\nLemma divn_addr : forall m n d, d %| n -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by move=> m n d dv_n; rewrite addnC divn_addl // addnC. Qed.\n\n(***********************************************************************)\n(*   A function that computes the gcd of 2 numbers                     *)\n(***********************************************************************)\n\nFixpoint gcdn_rec (m n : nat) {struct m} :=\n  let n' := n %% m in if n' is 0 then m else\n  if m - n'.-1 is m'.+1 then gcdn_rec (m' %% n') n' else n'.\n\nDefinition gcdn := nosimpl gcdn_rec.\n\nLemma gcdnE : forall m n, gcdn m n = if m == 0 then n else gcdn (n %% m) m.\nProof.\nrewrite /gcdn => m; elim: m {-2}m (leqnn m) => [|s IHs] [|m] le_ms [|n] //=.\ncase def_n': (_ %% _) => // [n'].\nhave{def_n'} lt_n'm: n' < m by rewrite -def_n' -ltnS ltn_pmod.\nrewrite {}IHs ?(leq_trans lt_n'm) // subn_if_gt ltnW //=; congr gcdn_rec.\nby rewrite -{2}(subnK (ltnW lt_n'm)) -addnS modn_addr.\nQed.\n\nLemma gcdnn : idempotent gcdn.\nProof. by case=> // n; rewrite gcdnE modnn. Qed.\n\nLemma gcdnC : commutative gcdn.\nProof.\nmove=> m n; wlog lt_nm: m n / n < m.\n  by case: (ltngtP n m) => [||->]; [|symmetry|rewrite gcdnn]; auto.\nby rewrite gcdnE -{1}(ltn_predK lt_nm) modn_small.\nQed.\n\nLemma gcd0n : left_id 0 gcdn. Proof. by case. Qed.\nLemma gcdn0 : right_id 0 gcdn. Proof. by case. Qed.\n\nLemma gcd1n : left_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnE modn1. Qed.\n\nLemma gcdn1 : right_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnC gcd1n. Qed.\n\nLemma dvdn_gcdr : forall m n, gcdn m n %| n.\nProof.\nmove=> m; elim: m {-2}m (leqnn m) => [|s IHs] [|m] le_ms [|n] //.\nrewrite gcdnE; case def_n': (_ %% _) => [|n']; first by rewrite /dvdn def_n'.\nhave lt_n's: n' < s by rewrite -ltnS (leq_trans _ le_ms) // -def_n' ltn_pmod.\nrewrite /= (divn_eq n.+1 m.+1) def_n' dvdn_addr ?dvdn_mull //; last exact: IHs.\nby rewrite gcdnE /= IHs // (leq_trans _ lt_n's) // ltnW // ltn_pmod.\nQed.\n\nLemma dvdn_gcdl : forall m n, gcdn m n %| m.\nProof. by move=> m n; rewrite gcdnC dvdn_gcdr. Qed.\n\nLemma gcdn_gt0 : forall m n, (0 < gcdn m n) = (0 < m) || (0 < n).\nProof.\nmove=> [|m] [|n] //; apply: (@dvdn_gt0 _ m.+1) => //; exact: dvdn_gcdl.\nQed.\n\nLemma gcdn_addl_mul : forall k m n, gcdn m (k * m + n) = gcdn m n.\nProof. by move=> k m n; rewrite !(gcdnE m) modn_addl_mul mulnC; case: m. Qed.\n\nLemma gcdn_addl: forall m n, gcdn m (m + n) = gcdn m n.\nProof. by move => m n; rewrite -{2}(mul1n m) gcdn_addl_mul. Qed.\n\nLemma gcdn_addr: forall m n, gcdn m (n + m) = gcdn m n.\nProof. by move=> m n; rewrite addnC gcdn_addl. Qed.\n\nLemma gcdn_mull : forall n m, gcdn n (m * n) = n.\nProof. by move=> n m; rewrite gcdnE modn_mull gcd0n; case defn:n=> /=. Qed.\n\nLemma gcdn_mulr : forall n m, gcdn n (n * m) = n.\nProof. by move=> n m; rewrite mulnC gcdn_mull. Qed.\n\n(* Extended gcd, which computes Bezout coefficients. *)\n\nFixpoint bezout_rec (km kn : nat) (qs : seq nat) {struct qs} :=\n  if qs is q :: qs' then bezout_rec kn (NatTrec.add_mul q kn km) qs'\n  else (km, kn).\n\nFixpoint egcdn_rec (m n s : nat) (qs : seq nat) {struct s} :=\n  if s is s'.+1 then\n    let: (q, r) := edivn m n in\n    if r > 0 then egcdn_rec n r s' (q :: qs) else\n    if odd (size qs) then qs else q.-1 :: qs\n  else [::0].\n\nDefinition egcdn m n := bezout_rec 0 1 (egcdn_rec m n n [::]).\n\nCoInductive egcdn_spec (m n : nat) : nat * nat -> Type :=\n  EgcdnSpec km kn of km * m = kn * n + gcdn m n & kn * gcdn m n < m :\n    egcdn_spec m n (km, kn).\n\nLemma egcd0n : forall n, egcdn 0 n = (1, 0).\nProof. by case. Qed.\n\nLemma egcdnP : forall m n, m > 0 -> egcdn_spec m n (egcdn m n).\nProof.\nrewrite /egcdn => m0 n0; have: (n0, m0) = bezout_rec n0 m0 [::] by [].\ncase: (posnP n0) => [-> /=|]; first by split; rewrite // mul1n gcdn0.\nelim: {1 4}n0 {1 3 5 7}n0 {-1 4}m0 [::] (ltnSn n0) => [[]//|s IHs] n m qs /=.\nmove=> le_ns n_gt0 def_mn0 m_gt0.\ncase: edivnP => q r def_m; rewrite n_gt0 /= => lt_rn.\ncase: posnP => [r0 {s le_ns IHs lt_rn}|r_gt0]; last first.\n  by apply: IHs => //=; [rewrite (leq_trans lt_rn) | rewrite natTrecE -def_m].\nrewrite {r}r0 addn0 in def_m; set b := odd _; pose d := gcdn m n.\npose km := ~~ b : nat; pose kn := if b then 1 else q.-1.\nrewrite (_ : bezout_rec _ _ _ = bezout_rec km kn qs); last first.\n  by rewrite /kn /km; case b => //=; rewrite natTrecE addn0 muln1.\nhave def_d: d = n by rewrite /d def_m gcdnC gcdnE modn_mull gcd0n -[n]prednK.\nhave: km * m + 2 * b * d = kn * n + d.\n  rewrite {}/kn {}/km def_m def_d -mulSnr; case: b; rewrite //= addn0 mul1n.\n  by rewrite prednK //; apply: dvdn_gt0 m_gt0 _; rewrite def_m dvdn_mulr.\nhave{def_m}: kn * d <= m.\n  have q_gt0 : 0 < q by rewrite def_m muln_gt0 n_gt0 ?andbT in m_gt0.\n  by rewrite /kn; case b; rewrite def_d def_m leq_pmul2r // leq_pred.\nhave{def_d}: km * d <= n by rewrite -[n]mul1n def_d leq_pmul2r // leq_b1.\nmove: km {q}kn m_gt0 n_gt0 def_mn0; rewrite {}/d {}/b.\nelim: qs m n => [|q qs IHq] n r kn kr n_gt0 r_gt0 /=.\n  case=> -> -> {m0 n0}; rewrite !addn0 => le_kn_r _ def_d; split=> //.\n  have d_gt0: 0 < gcdn n r by rewrite gcdn_gt0 n_gt0.\n  have: 0 < kn * n by rewrite def_d addn_gt0 d_gt0 orbT.\n  rewrite muln_gt0 n_gt0 andbT; move/ltn_pmul2l <-.\n  by rewrite def_d -addn1 leq_add // mulnCA leq_mul2l le_kn_r orbT.\nrewrite !natTrecE; set m:= _ + r; set km := _ * _ + kn; pose d := gcdn m n.\nhave ->: gcdn n r = d by rewrite [d]gcdnC gcdn_addl_mul.\nhave m_gt0: 0 < m by rewrite addn_gt0 r_gt0 orbT.\nhave d_gt0: 0 < d by rewrite gcdn_gt0 m_gt0.\nmove/IHq=> {IHq} IHq le_kn_r le_kr_n def_d; apply: IHq => //; rewrite -/d.\n  by rewrite muln_addl leq_add // -mulnA leq_mul2l le_kr_n orbT.\napply: (@addIn d); rewrite -!addnA addnn addnCA muln_addr -addnA addnCA.\nrewrite /km muln_addl mulnCA mulnA -addnA; congr (_ + _).\nby rewrite -def_d addnC -addnA -muln_addl -muln_addr addn_negb -mul2n.\nQed.\n\nLemma bezoutl : forall m n, m > 0 -> {a | a < m & m %| gcdn m n + a * n}.\nProof.\nmove=> m n m_gt0; case: (egcdnP n m_gt0) => km kn def_d lt_kn_m.\nexists kn; last by rewrite addnC -def_d dvdn_mull.\napply: leq_ltn_trans lt_kn_m.\nby rewrite -{1}[kn]muln1 leq_mul2l gcdn_gt0 m_gt0 orbT.\nQed.\n\nLemma bezoutr : forall m n, n > 0 -> {a | a < n & n %| gcdn m n + a * m}.\nProof. by move=> m n; rewrite gcdnC; exact: bezoutl. Qed.\n\n(* Back to the gcd. *)\n\nLemma dvdn_gcd : forall p m n, p %| gcdn m n = (p %| m) && (p %| n).\nProof.\nmove=> p m n; apply/idP/andP=> [dv_pmn | [dv_pm dv_pn]].\n  by rewrite ?(dvdn_trans dv_pmn) ?dvdn_gcdl ?dvdn_gcdr.\ncase (posnP n) => [->|n_gt0]; first by rewrite gcdn0.\ncase: (bezoutr m n_gt0) => // km _; move/(dvdn_trans dv_pn).\nby rewrite dvdn_addl // dvdn_mull.\nQed.\n\nLemma gcdn_mul2l : forall p m n, gcdn (p * m) (p * n) = p * gcdn m n.\nProof.\nmove=> p m n; case: (posnP p) => [-> //| p_gt0].\nelim: {m}m.+1 {-2}m n (ltnSn m) => // s IHs m n; rewrite ltnS => le_ms.\nrewrite gcdnE (gcdnE m) muln_eq0 modn_pmul2l // eqn0Ngt p_gt0.\ncase: posnP => // m_gt0; apply: IHs; apply: leq_trans le_ms.\nexact: ltn_pmod.\nQed.\n\nLemma gcdn_modr : forall m n, gcdn m (n %% m) = gcdn m n.\nProof. by move=> m n; rewrite {2}(divn_eq n m) gcdn_addl_mul. Qed.\n\nLemma gcdn_modl: forall m n, gcdn (m %% n) n = gcdn m n.\nProof. by move=> m n; rewrite !(gcdnC _ n) gcdn_modr. Qed.\n\nLemma gcdnAC : right_commutative gcdn.\nProof.\nsuff dvd: forall m n p, gcdn (gcdn m n) p %| gcdn (gcdn m p) n.\n  by move=> m n p; apply/eqP; rewrite eqn_dvd !dvd.\nmove=> m n p; rewrite !dvdn_gcd dvdn_gcdr.\nby rewrite !(dvdn_trans (dvdn_gcdl _ p)) ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma gcdnA : associative gcdn.\nProof. by move=> m n p; rewrite !(gcdnC m) gcdnAC. Qed.\n\nLemma gcdnCA : left_commutative gcdn.\nProof. by move=> m n p; rewrite !gcdnA (gcdnC m). Qed.\n\nLemma muln_gcdl : left_distributive muln gcdn.\nProof. by move=> m n p; rewrite -!(mulnC p) gcdn_mul2l. Qed.\n\nLemma muln_gcdr : right_distributive muln gcdn.\nProof. by move=> m n p; rewrite gcdn_mul2l. Qed.\n\nLemma gcdn_def : forall d m n,\n    d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d)\n  -> gcdn m n = d.\nProof.\nmove=> d m n dv_dm dv_dn gdv_d; apply/eqP.\nby rewrite eqn_dvd dvdn_gcd dv_dm dv_dn gdv_d ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma gcdn_divnC : forall n m, n * (m %/ gcdn n m)  = m * (n %/ gcdn n m).\nProof. by move=> n m; rewrite divn_mulCA ?dvdn_gcdl ?dvdn_gcdr. Qed.\n\n(* We derive the lcm directly. *)\n\nDefinition lcmn m n := m * n %/ gcdn m n.\n\nLemma lcmnC : commutative lcmn.\nProof. by move=> m n; rewrite /lcmn mulnC gcdnC. Qed.\n\nLemma lcm0n : left_zero 0 lcmn. Proof. move=> n; exact: div0n. Qed.\nLemma lcmn0 : right_zero 0 lcmn. Proof. by move=> n; rewrite lcmnC lcm0n. Qed.\n\nLemma lcm1n : left_id 1 lcmn.\nProof. by move=> n; rewrite /lcmn gcd1n mul1n divn1. Qed.\n\nLemma lcmn1 : right_id 1 lcmn.\nProof. by move=> n; rewrite lcmnC lcm1n. Qed.\n\nLemma muln_lcm_gcd : forall m n, lcmn m n * gcdn m n = m * n.\nProof. by move=> m n; apply/eqP; rewrite divnK ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma lcmn_gt0 : forall m n, (0 < lcmn m n) = (0 < m) && (0 < n).\nProof. by move=> m n; rewrite -muln_gt0 ltn_divr ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma muln_lcmr : right_distributive muln lcmn.\nProof.\ncase=> // m n p; rewrite /lcmn -muln_gcdr -!mulnA divn_pmul2l // mulnCA.\nby rewrite divn_mulA ?dvdn_mull ?dvdn_gcdr.\nQed.\n\nLemma muln_lcml : left_distributive muln lcmn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_lcmr. Qed.\n\nLemma lcmnA : associative lcmn.\nProof.\nmove=> m n p; rewrite {1 3}/lcmn mulnC !divn_mulAC ?dvdn_mull ?dvdn_gcdr //.\nrewrite !divn_divl ?dvdn_mulr ?dvdn_gcdl // mulnC mulnA !muln_gcdr.\nby rewrite ![_ * lcmn _ _]mulnC !muln_lcm_gcd !muln_gcdl -!(mulnC m) gcdnA.\nQed.\n\nLemma dvdn_lcml : forall d1 d2, d1 %| lcmn d1 d2.\nProof. by move=> d1 d2; rewrite /lcmn -divn_mulA ?dvdn_gcdr ?dvdn_mulr. Qed.\n\nLemma dvdn_lcmr : forall d1 d2, d2 %| lcmn d1 d2.\nProof. by move=> d1 d2; rewrite lcmnC dvdn_lcml. Qed.\n\nLemma dvdn_lcm : forall d1 d2 m, lcmn d1 d2 %| m = (d1 %| m) && (d2 %| m).\nProof.\ncase=> [|d1] [|d2] m; try by case: m => [|m]; rewrite ?lcmn0 ?andbF.\nrewrite -(@dvdn_pmul2r (gcdn d1.+1 d2.+1)) ?gcdn_gt0 // muln_lcm_gcd.\nby rewrite muln_gcdr dvdn_gcd {1}mulnC andbC !dvdn_pmul2r.\nQed.\n\n(* Coprime factors *)\n\nDefinition coprime m n := gcdn m n == 1.\n\nLemma coprime1n : forall n, coprime 1 n.\nProof. by move=> n; rewrite /coprime gcd1n. Qed.\n\nLemma coprimen1 : forall n, coprime n 1.\nProof. by move=> n; rewrite /coprime gcdn1. Qed.\n\nLemma coprime_sym : forall m n, coprime m n = coprime n m.\nProof. by move => m n; rewrite /coprime gcdnC. Qed.\n\nLemma coprime_modl : forall m n, coprime (m %% n) n = coprime m n.\nProof. by move=> m n; rewrite /coprime gcdn_modl. Qed.\n\nLemma coprime_modr : forall m n, coprime m (n %% m) = coprime m n.\nProof. by move=> m n; rewrite /coprime gcdn_modr. Qed.\n\nLemma coprimeP : forall n m, n > 0 ->\n  reflect (exists u, u.1 * n - u.2 * m = 1) (coprime n m).\nProof.\nmove=> n m n_gt0; apply: (iffP eqP) => [<-| [[kn km] /= kn_km_1]].\n  by have [kn km kg _] := egcdnP m n_gt0; exists (kn, km); rewrite kg addKn.\napply gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m.\nby rewrite -kn_km_1 dvdn_subr ?dvdn_mull // ltnW // -subn_gt0 kn_km_1.\nQed.\n\nLemma modn_coprime : forall k n, O < k ->\n  (exists u, (k * u) %% n = 1%N) -> coprime k n.\nProof.\nmove=> k n Hpos [u Hu]; apply/coprimeP; first by [].\nby exists (u, k * u %/ n); rewrite /= mulnC {1}(divn_eq (k * u) n) addKn.\nQed.\n\nLemma gauss_inv : forall m n p,\n  coprime m n -> (m * n %| p) = (m %| p) && (n %| p).\nProof.\nby move=> m n p co_mn; rewrite -muln_lcm_gcd (eqnP co_mn) muln1 dvdn_lcm.\nQed.\n\nLemma gauss : forall m n p, coprime m n -> (m %| n * p) = (m %| p).\nProof.\nmove=> m [|n] p co_mn; first by case: m co_mn => [|[]] // _; rewrite !dvd1n.\nby symmetry; rewrite mulnC -(@dvdn_pmul2r n.+1) ?gauss_inv // andbC dvdn_mull.\nQed.\n\nLemma gauss_gcdr : forall p m n, coprime p m -> gcdn p (m * n) = gcdn p n.\nProof.\nmove=> p m n co_pm; apply/eqP; rewrite eqn_dvd !dvdn_gcd !dvdn_gcdl /=.\nrewrite andbC dvdn_mull ?dvdn_gcdr //= -(@gauss _ m) ?dvdn_gcdr //.\nby rewrite /coprime gcdnAC (eqnP co_pm) gcd1n.\nQed.\n\nLemma gauss_gcdl : forall p m n, coprime p n -> gcdn p (m * n) = gcdn p m.\nProof. by move=> *; rewrite mulnC gauss_gcdr. Qed.\n\nLemma coprime_mulr : forall p m n,\n  coprime p (m * n) = coprime p m && coprime p n.\nProof.\nmove=> p m n.\ncase co_pm: (coprime p m) => /=; first by rewrite /coprime gauss_gcdr.\napply/eqP=> co_p_mn; case/eqnP: co_pm; apply gcdn_def => // d dv_dp dv_dm.\nby rewrite -co_p_mn dvdn_gcd dv_dp dvdn_mulr.\nQed.\n\nLemma coprime_mull : forall p m n,\n  coprime (m * n) p = coprime m p && coprime n p.\nProof. move=> p m n; rewrite !(coprime_sym _ p); exact: coprime_mulr. Qed.\n\nLemma coprime_pexpl : forall k m n, 0 < k -> coprime (m ^ k) n = coprime m n.\nProof.\ncase=> // k m n _; elim: k => [|k IHk]; first by rewrite expn1.\nby rewrite expnS coprime_mull -IHk; case coprime.\nQed.\n\nLemma coprime_pexpr : forall k m n, 0 < k -> coprime m (n ^ k) = coprime m n.\nProof. by move=> k m n k_gt0; rewrite !(coprime_sym m) coprime_pexpl. Qed.\n\nLemma coprime_expl : forall k m n, coprime m n -> coprime (m ^ k) n.\nProof. by case=> [|k] p m co_pm; rewrite ?coprime1n // coprime_pexpl. Qed.\n\nLemma coprime_expr : forall k m n, coprime m n -> coprime m (n ^ k).\nProof. by move=> k m n; rewrite !(coprime_sym m); exact: coprime_expl. Qed.\n\nLemma coprime_egcdn : forall n m, n > 0 ->\n    coprime (egcdn n m).1 (egcdn n m).2.\nProof.\nmove=> n m n_gt0; case: (egcdnP m n_gt0) => kn km /=; move/eqP.\nhave [u defn] := dvdnP (dvdn_gcdl n m); have [v defm] := dvdnP (dvdn_gcdr n m).\nrewrite -[gcdn n m]mul1n {1}defm {1}defn !mulnA -muln_addl addnC.\nrewrite eqn_pmul2r ?gcdn_gt0 ?n_gt0 //; move/eqP; case: kn => // kn def_knu _.\nby apply/coprimeP=> //; exists (u, v); rewrite mulnC def_knu mulnC addnK.\nQed.\n\nSection Chinese.\n\n(***********************************************************************)\n(*   The chinese remainder theorem                                     *)\n(***********************************************************************)\n\nVariables m1 m2 : nat.\nHypothesis co_m12 : coprime m1 m2.\n\nLemma chinese_remainder : forall x y,\n  (x == y %[mod m1 * m2]) = (x == y %[mod m1]) && (x == y %[mod m2]).\nProof.\nmove=> x y; wlog le_yx : x y / y <= x.\n  by case/orP: (leq_total y x); last rewrite !(eq_sym (x %% _)); auto.\nby rewrite !eqn_mod_dvd // gauss_inv.\nQed.\n\n(***********************************************************************)\n(*   A function that solves the chinese remainder problem              *)\n(***********************************************************************)\n\nDefinition chinese r1 r2 :=\n  r1 * m2 * (egcdn m2 m1).1 + r2 * m1 * (egcdn m1 m2).1.\n\nLemma chinese_modl : forall r1 r2, chinese r1 r2 = r1 %[mod m1].\nProof.\nrewrite /chinese; case: (posnP m2) co_m12 => [->|m2_gt0 _].\n  by move/eqnP; rewrite gcdn0 => -> r1 r2 ; rewrite !modn1.\ncase: egcdnP=> // k2 k1 def_m1 _ r1 r2.\nrewrite mulnAC -mulnA def_m1 gcdnC (eqnP co_m12) muln_addr mulnA muln1.\nby rewrite addnAC (mulnAC _ m1) -muln_addl modn_addl_mul.\nQed.\n\nLemma chinese_modr : forall r1 r2, chinese r1 r2 = r2 %[mod m2].\nProof.\nrewrite /chinese; case: (posnP m1) co_m12 => [->|m1_gt0 _].\n  by move/eqnP; rewrite gcd0n => -> r1 r2 ; rewrite !modn1.\ncase: (egcdnP m2) => // k1 k2 def_m2 _ r1 r2.\nrewrite addnC mulnAC -mulnA def_m2 (eqnP co_m12) muln_addr mulnA muln1.\nby rewrite addnAC (mulnAC _ m2) -muln_addl modn_addl_mul.\nQed.\n\nLemma chinese_modlr : forall x, x = chinese (x %% m1) (x %% m2) %[mod m1 * m2].\nProof.\nmove=> x; apply/eqP.\nby rewrite chinese_remainder // chinese_modl chinese_modr !modn_mod !eqxx.\nQed.\n\nEnd Chinese.\n", "meta": {"author": "Wassasin", "repo": "ssreflect", "sha": "45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4", "save_path": "github-repos/coq/Wassasin-ssreflect", "path": "github-repos/coq/Wassasin-ssreflect/ssreflect-45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4/theories/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7431680798297207}}
{"text": "From Coq Require Import Sets.Ensembles.\nFrom Coq Require Import Sets.Powerset_facts.\n\n(*Formulas: *)\n\nInductive Formula : Type :=\n    | atom : nat -> Formula\n    | disj : Formula -> Formula -> Formula\n    | conj : Formula -> Formula -> Formula\n    | imp : Formula -> Formula -> Formula\n    | neg : Formula -> Formula\n    | bot : Formula. \n\n\n\n\n(*Natural Deduction: *)\n\nInductive ND : Ensemble Formula -> Formula -> Prop :=\n    | ax (C:Ensemble Formula) (f: Formula) (H:In Formula C  f) : ND C f\n    | conjE1 (C:Ensemble Formula) (f1 f2: Formula) (H:ND C (conj f1 f2)) : ND C f1\n    | conjE2 (C:Ensemble Formula) (f1 f2: Formula) (H:ND C (conj f1 f2)) : ND C f2\n    | conjI (C:Ensemble Formula) (f1 f2: Formula) (H1:ND C f1) (H2:ND C f2) : ND C (conj f1 f2)\n    | disjE (C:Ensemble Formula) (f1 f2 f:Formula) (H1:ND (Union Formula C (Singleton Formula f1)) f) \n        (H2:ND (Union Formula C (Singleton Formula f2)) f) (H3:ND C (disj f1 f2) ): ND C f \n    | disjI1 (C:Ensemble Formula) (f1 f2:Formula) (H:ND C f1):ND C (disj f1 f2)\n    | disjI2 (C:Ensemble Formula) (f1 f2:Formula) (H:ND C f2):ND C (disj f1 f2)\n    | impE (C:Ensemble Formula) (f1 f2:Formula) (H1:ND C (imp f1 f2)) (H2:ND C (f1)): ND C f2\n    | impI (C:Ensemble Formula) (f1 f2:Formula) (H:ND (Union Formula C (Singleton Formula f1)) f2): ND C (imp f1 f2)\n    | negE (C:Ensemble Formula) (f :Formula) (H1: ND C f) (H2: ND C (neg f)): ND C bot\n    | negI (C:Ensemble Formula) (f :Formula) (H: ND (Union Formula C (Singleton Formula f)) bot ): ND C (neg f) (*Momkene context ghalat bashe!!!*)\n    | botE (C:Ensemble Formula) (f:Formula) (H:ND C bot):ND C f\n    | RAA (C:Ensemble Formula) (f:Formula) (H:ND (Union Formula C (Singleton Formula (neg f))) bot):ND C f.\n\n\n\n\n(*Semantics: *)\n\nFixpoint val  (model : nat -> bool) (f: Formula) : bool:=\n    match f with\n    | atom n=> model n\n    | neg f1 =>  negb(val model f1)\n    | disj f1 f2 => orb (val model f1) (val model f2)\n    | conj f1 f2 =>andb (val model f1 ) (val model f2)\n    | imp f1 f2 => orb(negb(val model f1))  (val model f2)\n    | bot => false\n    end.\n\n(*a model satisfying a set of formulae*)\n(*model|=Gamma*)\nDefinition mSsf (model : nat -> bool) (Gamma:Ensemble Formula)  : Prop:=\n    forall (f:Formula), (In Formula Gamma f -> (val model f = true)).\n\n\n(*All models satisfying elements of Gamma are satisfying F*)\n(*Gamma|=f*)\nDefinition sfSf (Gamma: Ensemble Formula) (f:Formula) : Prop:=\n    forall (model: nat ->bool),( mSsf model Gamma -> val model f = true).\n\n\n\n\n\n\n\n\n(*Proof by Contradiction*)\nAxiom pbc : forall (P: Prop), (~P -> False) -> P.\nAxiom dnegE1 : forall P:Prop, (~~P->P).\nAxiom dnegE2 : forall P:Prop, (P->~~P).\nAxiom excluded_middle : forall P:Prop, P \\/ ~P.\n\nLemma Union_In : forall (U:Type) (A B : Ensemble U) (x:U),\nIn U A x \\/ In U B x -> In U (Union U A B) x.\nintros U A B x H. destruct H.\n+apply Union_introl. apply H.\n+apply Union_intror. apply H.\nQed.\n\n\n\n\n(*Consistency:*)\nDefinition Cons (Gamma : Ensemble Formula) : Prop :=\n~(ND Gamma bot).\n\nDefinition iCons (Gamma : Ensemble Formula) : Prop :=\n(ND Gamma bot).\n\n\n\nLemma iConsEqiv : forall(Gamma : Ensemble Formula),\n(exists f:Formula, In Formula Gamma f /\\ In Formula Gamma (neg f))->iCons Gamma.\nProof. intros Gamma H. unfold iCons. destruct H. rename x into f.\napply negE with (f:=f). +apply ax. apply H.\n+apply ax. apply H.\nQed.  \n\n\n\n(*needed to prove the next lemma*)\nLemma about_Union: forall (A:Ensemble Formula)(f1 f2: Formula),\n    Union Formula (Union Formula A (Singleton Formula f1)) (Singleton Formula  f2)=\n    Union Formula (Union Formula A (Singleton Formula  f2)) (Singleton Formula f1).\n    Proof. intros A f1 f2. rewrite ->Union_associative. \n    rewrite ->Union_commutative with (A:=(Singleton Formula f1)).\n    rewrite ->Union_associative. reflexivity.  \nQed.\n\nLemma Weakening: forall(C:Ensemble Formula) (f1 f2:Formula), ND C f1 -> ND (Union Formula C (Singleton Formula f2)) f1.\nProof.\n    intros C f1 f2 H. induction H.\n    +apply ax. apply Union_introl. apply H.\n    +apply conjE1 in IHND. apply IHND.\n    +apply conjE2 in IHND. apply IHND.\n    +apply conjI. -apply IHND1. -apply IHND2.\n    +apply disjE with (C:=Union Formula C (Singleton Formula f2)) (f1:=f1) (f2:=f0).\n        -rewrite ->about_Union. apply IHND1.\n        -rewrite ->about_Union. apply IHND2.\n        -apply IHND3.\n    +apply disjI1. apply IHND.\n    +apply disjI2. apply IHND.\n    +apply impE with (f1:=f1) (f2:=f0).\n        -apply IHND1. -apply IHND2.\n    +apply impI. rewrite ->about_Union. apply IHND.\n    +apply negE with(f:=f). -apply IHND1. -apply IHND2.\n    +apply negI. rewrite ->about_Union. apply IHND.\n    +apply botE. apply IHND.\n    +apply RAA. rewrite ->about_Union. apply IHND.\n    Qed. \n\n(*Lemma 1.4.5 (used in main proof!) *)\nLemma ConsSyns0: forall (Gamma:Ensemble Formula) (f:Formula),\niCons(Union Formula Gamma (Singleton Formula (neg f))) <-> ND Gamma f.\nProof.\n    intros Gamma f.\n    split.\n    +intros H. unfold iCons in H. apply RAA in H. apply H.\n    +intros H. unfold iCons. apply negE with (f:=f). -apply Weakening. apply H. \n        -apply ax. apply Union_intror. apply In_singleton.\n    Qed.\n\nAxiom contraposition : forall (P Q :Prop), (P <-> Q) -> (~P <-> ~Q).\nLemma ConsSyns: forall (Gamma:Ensemble Formula) (f:Formula),\n~iCons(Union Formula Gamma (Singleton Formula (neg f))) <-> ~ND Gamma f.\nProof.\n  intros Gamma f.\n  apply contraposition. apply ConsSyns0.\n  Qed.\n", "meta": {"author": "TypicalMath", "repo": "cpc", "sha": "a2041b156d0ab954f57f76fda7cd4e27d2f8881c", "save_path": "github-repos/coq/TypicalMath-cpc", "path": "github-repos/coq/TypicalMath-cpc/cpc-a2041b156d0ab954f57f76fda7cd4e27d2f8881c/Logic_and_Set_Theory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7431402860528176}}
{"text": "From Undecidability.L.Tactics Require Import LTactics.\nFrom Undecidability.L Require Import Functions.EqBool.\n\nFrom Undecidability.L.Datatypes Require Export List.List_enc.\n\nSection list_in.\n  Variable (X : Type). \n  Variable (eqb : X -> X -> bool). \n  Variable eqb_correct : forall a b,  a = b <-> eqb a b = true.  \n\n  Definition list_in_decb := fix rec (l : list X) (x : X) : bool :=\n  match l with [] => false\n          | (l :: ls) => eqb l x || rec ls x\n  end. \n\n  Lemma list_in_decb_iff (l : list X) : forall x, list_in_decb l x = true <-> x el l. \n  Proof using eqb_correct. \n    intros x. induction l.\n    - cbn. firstorder. \n    - split. \n      + intros [H1 | H1]%orb_true_elim. left. now apply eqb_correct. \n        apply IHl in H1. now right. \n      + intros [H | H].\n        cbn. apply orb_true_intro; left; now apply eqb_correct. \n        cbn. apply orb_true_intro; right; now apply IHl. \n  Qed.\n\n  Fixpoint list_incl_decb (a b : list X) := \n    match a with \n    | [] => true\n    | (x::a) => list_in_decb b x && list_incl_decb a b\n    end. \n\n\nEnd list_in.\n\nSection list_in_time.\n  Variable (X : Type).\n  Context {H : encodable X}.\n  Context (eqbX : X -> X -> bool).\n  Context {Xeq : eqbClass eqbX}. \n  Context {XeqbComp : eqbComp X}.\n\n  Global Instance term_list_in_decb : computable (@list_in_decb X eqbX).\n  Proof using XeqbComp Xeq. \n    extract.\n  Qed. \n\n  Global Instance term_list_incl_decb : computable (@list_incl_decb X eqbX). \n  Proof using XeqbComp Xeq. \n    extract.\n  Qed.\nEnd list_in_time. \n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/L/Datatypes/List/List_in.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7431402853528435}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to strengthen an induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\n(** Set Warnings \"-notation-overridden,-parsing\". *)\nRequire Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can achieve the same effect in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\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 eq1.\n  apply eq1.\nQed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (* (This [simpl] is optional, since [apply] will perform\n            simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [Search] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros.\n  rewrite -> H.\n  symmetry.\n  apply rev_involutive.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied?\n\n(* Ambas se utilizan cuando el goal a probar es igual a una hipótesis o a algo\nya probado, con la diferencia de que apply nos ahorra un reflexivity.  *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros.\n  rewrite <- H.\n  apply H0.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [inversion] Tactic *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n].\n\n    Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not\n    interesting.)  And so on. *)\n\n(** Coq provides a tactic called [inversion] that allows us to\n    exploit these principles in proofs. To see how to use it, let's\n    show explicitly that the [S] constructor is injective: *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [inversion H] at this point, we are asking Coq to\n    generate all equations that it can infer from [H] as additional\n    hypotheses, replacing variables in the goal as it goes. In the\n    present example, this amounts to adding a new hypothesis [H1 : n =\n    m] and replacing [n] by [m] in the goal. *)\n\n  inversion H.\n  reflexivity.\nQed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\n(** We can name the equations that [inversion] generates with an\n    [as ...] clause: *)\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros.\n  inversion H0.\n  reflexivity.\nQed.\n(** [] *)\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [inversion] solves the\n    goal immediately.  Consider the following proof: *)\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [beq_nat 0 (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [inversion] on this hypothesis, Coq notices that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. inversion H. Qed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything, even false things! *)\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that, if the\n    nonsensical situation described by the premise did somehow arise,\n    then the nonsensical conclusion would follow.  We'll explore the\n    principle of explosion of more detail in the next chapter. *)\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  intros.\n  inversion H.\nQed.\n(** [] *)\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n\n        c a1 a2 ... an = d b1 b2 ... bm\n\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] has the following effect:\n\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.  The [inversion H] adds these facts to the context and\n      tries to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered at all.  In this case, [inversion H] marks the\n      current goal as completed and pops it off the goal stack. *)\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find convenient in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [L1 -> L2] and a hypothesis matching [L1], it\n    produces a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [L1->L2] and we are\n    trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\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  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this proof.  (Hint: use\n    [plus_n_Sm].) *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n. induction n.\n  intros m H. destruct m. reflexivity. inversion H.\n  intros m. destruct m. intros. inversion H.\n  intros eq. inversion eq.\n  rewrite <- plus_n_Sm in H0. rewrite <- plus_n_Sm in H0.\n  inversion H0. apply IHn in H1. rewrite -> H1. reflexivity.\nQed.\n  \n\n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it maps different arguments to different results:\n\n    Theorem double_injective: forall n m,\n      double n = double m -> n = m.\n\n    The way we _start_ this proof is a bit delicate: if we begin with\n\n      intros n. induction n.\n\n    all is well.  But if we begin it with\n\n      intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *) apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a relation involving _every_ [n] but just a _single_ [m]. *)\n\n(** The successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      inversion eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: To prove a property of [n] and [m] by induction on [n],\n    it is sometimes important to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n.\n  induction n.\n  destruct m. reflexivity.\n  intros H. inversion H.\n  destruct m.\n  intros H. inversion H.\n  intros H.\n  apply f_equal. apply IHn.\n  inversion H.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by inversion that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises,\n    let's digress briefly and use [beq_nat_true] to prove a similar\n    property of identifiers that we'll need in later chapters: *)\n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply beq_nat_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  inversion H.\n  simpl.\n  induction l.\n  reflexivity.\n  apply IHl0.\n  simpl.\nAdmitted.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a Definition\n    so that we can manipulate its right-hand side.  For example, if we\n    define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we get stuck: [simpl] doesn't simplify anything at this point,\n    and since we haven't proved any other facts about [square], there\n    is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these facts it is not\n    hard to finish the proof. *)\n\n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, a deeper discussion of unfolding and simplification\n    is in order.\n\n    You may already have observed that tactics like [simpl],\n    [reflexivity], and [apply] will often unfold the definitions of\n    functions automatically when this allows them to make progress.  For\n    example, if we define [foo m] to be the constant [5]... *)\n\nDefinition foo (x: nat) := 5.\n\n(** then the [simpl] in the following proof (or the [reflexivity], if\n    we omit the [simpl]) will unfold [foo m] to [(fun x => 5) m] and\n    then further simplify this expression to just [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is rather conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  (It is not smart enough to notice that the\n    two branches of the [match] are identical.)  So it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that, itself, cannot be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone. *)\n\n(** At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress. *)\n\n(** A more straightforward way to make progress is to explicitly tell\n    Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\n(** Here is an implementation of the [split] function mentioned in\n    chapter [Poly]: *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x, y) :: t =>\n      match split t with\n      | (lx, ly) => (x :: lx, y :: ly)\n      end\n  end.\n\n(** Prove that [split] and [combine] are inverses in the following\n    sense: *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l.\n  induction l.\n  intros.\n  inversion H.\n  reflexivity.\n  intros.\n  rewrite -> IHl.\nAdmitted.\n   \n(** [] *)\n\n(** However, [destruct]ing compound expressions requires a bit of\n    care, as such [destruct]s can sometimes erase information we need\n    to complete a proof. *)\n(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution performed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that, since [beq_nat n 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\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  destruct (f true) eqn:ftrue.\n  rewrite -> ftrue. rewrite -> ftrue. reflexivity.\n  destruct (f false) eqn:ffalse.\n  rewrite -> ftrue. reflexivity.\n  rewrite -> ffalse. reflexivity.\n  destruct (f false) eqn:ffalse2.\n  destruct (f true) eqn:ftrue2.\n  rewrite -> ftrue2. reflexivity.\n  rewrite -> ffalse2. reflexivity.\n  rewrite -> ffalse2. rewrite -> ffalse2. reflexivity.\nQed.\n  \n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [inversion]: reason by injectivity and distinctness of\n        constructors\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  intros n.\n  induction n.\n  destruct m. reflexivity. reflexivity.\n  destruct m. reflexivity. simpl. apply IHn.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   \n   Hago inducción en n:\n     CB: beq_nat 0 m = beq_nat m 0\n         Hago casos en m:\n           m = 0: beq_nat 0 0 = beq_nat 0 0\n           m = m+1: beq_nat 0 (m+1) = beq_nat (m+1) 0\n             Por zero_nbeq_S (de Induction) sé que beq_nat 0 (m+1) = false, y por\n             S_nbeq_0 sé que beq_nat (m+1) 0 = false, con lo cual se demuestra el\n             caso m = m+1.\n     PI: Hago casos en m:\n           m = 0: Al igual que más arriba, uso zero_nbeq_S y S_nbeq_0 para demostrar\n             este caso.\n           m = m+1: beq_nat (n+1) (m+1) = beq_nat n m (se demuestra por el hecho\n             de que si aplico la misma operación, en este caso sumar 1, en cada\n             término, beq_nat sigue valiendo lo mismo).\n             Luego aplico la hipótesis de beq_nat n m = beq_nat m n y termina\n             la demostración.\n*)\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\n\nLemma beq_nat_n_n : forall n, beq_nat n n = true.\nProof.\n  intros n.\n  induction n.\n  reflexivity.\n  simpl. apply IHn.\nQed.\n\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  intros.\n  apply beq_nat_true in H.\n  apply beq_nat_true in H0.\n  rewrite H.\n  rewrite H0.\n  apply beq_nat_n_n.\nQed.\n  \n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop :=\n  forall X Y (l1: list X) (l2: list Y) l,\n  length l1 = length l2 ->\n  combine l1 l2 = l ->\n  split l = (l1, l2).\n\n(** Agrego la restricción de que ambas listas tengan el mismo largo\ndebido a que de no ser así no se cumpliría.\nEjemplo: combine [1; 2] [false; true; false] = [(1, false); (2, true)],\nmientras que split [(1, false); (2, true)] = [1; 2] [false; true] *)\n\nTheorem split_combine : split_combine_statement.\nProof.\n  induction l1.\n  simpl. destruct l2.\n  simpl. intros. rewrite <- H0. reflexivity.\n  simpl. intros. inversion H.\n  destruct l2.\n  simpl. intros. inversion H.\n  simpl. intros. inversion H. apply IHl1 with (l := combine l1 l2) in H2.\n  rewrite <- H0. simpl. rewrite -> H2. simpl. reflexivity. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  intros.\n  generalize dependent x.\n  induction l.\n  simpl. intros. inversion H.\n  simpl. intros. destruct (test x) eqn:ttrue.\n  inversion H.\n  rewrite <- H1. rewrite ttrue. reflexivity.\n  apply IHl in H. rewrite <- H. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *) \n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (beq_nat 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (beq_nat 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\nFixpoint forallb {X: Type} (p: X -> bool) (l: list X) : bool :=\n  match l with\n  | [] => true\n  | x :: xs => andb (p x) (forallb p xs)\n  end.\n\nFixpoint existsb {X: Type} (p: X -> bool) (l: list X) : bool :=\n  match l with\n  | [] => false\n  | x :: xs => orb (p x) (existsb p xs)\n  end.\n\nDefinition existsb' {X: Type} (p: X -> bool) (l: list X) : bool :=\n  negb (forallb (fun x => negb (p x)) l).\n\nTheorem existsb_equiv_existsb' : forall (X: Type ) (p: X -> bool) (l: list X),\n  (existsb p l) = (existsb' p l).\nProof.\n  intros.\n  unfold existsb'.\n  induction l.\n  simpl. reflexivity.\n  simpl. destruct (p x) eqn:pH. simpl. reflexivity.\n  simpl. apply IHl.\nQed.\n(** [] *)\n\n(** $Date: 2018-01-13 16:44:48 -0500 (Sat, 13 Jan 2018) $ *)\n\n\n ", "meta": {"author": "gobaldia", "repo": "logical-foundations", "sha": "8dd76b5f50c2397fb6b49f2873699d2cec9ac5d1", "save_path": "github-repos/coq/gobaldia-logical-foundations", "path": "github-repos/coq/gobaldia-logical-foundations/logical-foundations-8dd76b5f50c2397fb6b49f2873699d2cec9ac5d1/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.7431402769112254}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) (y : natural) : natural :=\n  plus Zero (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj236_coqofml_GUSDgY.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7431329854435696}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nInductive ex (T : Type) (p: T -> Prop): Prop := \n  | ex_intro (x: T) of p x.\n\nDefinition M_ex: forall (X: Type) (P: X -> Prop) (Z: Prop), ex P -> (forall x, P x -> Z) -> Z :=\n  fun X P Z e f =>\n    match e with \n    | ex_intro x px => f x px\n    end.\n\n(* 8.1.1 *)\nGoal forall T K (p: T -> K -> Prop), (exists x y, p x y) -> (exists y x, p x y).\nProof.\n  move => T K p.\n  move => [x [y pxy]].\n  exists y.\n  exists x.\n  apply pxy.\nQed.\n\n\nGoal forall T (p: T -> Prop), (exists x, p x) -> ~(forall x, ~ (p x)).\nProof.\n  move => T P [x px] H.\n  by apply (H x px).\nQed.\n\n(* 8.1.3 *)\nGoal forall T (x y : T), ~(x = y) -> exists p, p x /\\ ~(p y).\nProof.\n  move => T x y Hneq.\n  exists (fun a => a = x).\n  split.\n    done.\n  move => H.\n  apply Hneq.\n  by rewrite H.\nQed.\n\n(* 8.2.1 *)\nLemma russel_lemma: forall (P: Prop), ~(P <-> ~P).\nProof.\n  move => P [H H'].\n  apply H.\n    apply H'.\n    move => p.\n    apply H.\n      apply p.\n      apply p.\n  apply H'.\n  move => p.\n  apply H.\n    apply p.\n    apply p.\nQed.\n\nTheorem barber_theorem: forall (X : Type) (P: X -> X -> Prop),\n  ~(exists x, forall y, P x y <-> ~(P y y)).\nProof.\n  move => X P [x H].\n  set Hx := H x.\n  apply (russel_lemma Hx).\nQed.\n\n\nDefinition FixedPoint T (x: T) (f: T -> T) := f x = x.\n\nLemma negb_no_fp: ~ (exists x, FixedPoint x negb).\nProof.\n  move => [x].\n  case x.\n  - by rewrite /FixedPoint /=.\n  by rewrite /FixedPoint /=.\nQed.\n\nLemma neg_prop_no_fp: ~ (exists P, FixedPoint P (fun x => ~x)).\nProof.\n  move => [x].\n  rewrite /FixedPoint => P.\n  apply (@russel_lemma x).\n  by rewrite P.\nQed.\n\nDefinition surjective T K (f: T -> K) := forall (k: K), exists (t: T), f t = k.\n\nTheorem lawvere X Y: \n  (exists (f : X -> (X -> Y)), surjective f) -> \n    forall (g: Y -> Y), exists x, FixedPoint x g.\nProof.\n  rewrite /surjective /FixedPoint.\n  move => [f sf] g.\n  set tmp := sf (fun x => g(f x x)).\n  move : tmp => [a H].\n  exists (f a a).\n  by rewrite {2}H.\nQed.\n\n(* 8.3.4 *)\nCorollary t_834 X: ~(exists (f: X -> (X -> bool)), surjective f).\nProof.\n  move => H.\n  apply negb_no_fp.\n  apply (@lawvere X bool).\n  by apply H.\nQed.\n\n(* 8.3.5 *)\nCorollary t_835 X: ~(exists (f: X -> (X -> Prop)), surjective f).\nProof.\n  move => H.\n  apply neg_prop_no_fp.\n  apply (@lawvere X Prop).\n  by apply H.\nQed.\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/model_and_prooving_CompTT/pt1/ch8_exists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7431329829725011}}
{"text": "(**\nモナドがモノイドであることの証明\n\n@suharahiromichi\n\n2015_01_11\n2015_04_29 (Program Instance)\n*)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(*\nGeneralizable All Variables.\n個々に、Generalizable Variables で宣言する。\n*)\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\n\nReserved Notation \"x * y\" (at level 40, left associativity).\nReserved Notation \"c >>= f\" (at level 42, left associativity).\n\n\n(**\nMonoid モノイド\nMonoidの定義は文献[1]\n- carrier (台) A\n- binary, associative operation 'dot' on A\n- neutral element 1 ∈ A for 'dot'\n *)\nClass Monoid {M : Type} : Type :=\n  {\n    dot : M -> M -> M where \"x * y\" := (dot x y);\n    one : M;\n    dot_assoc : forall x y z: M, x * (y * z) = (x * y) * z;\n    one_left  : forall x, one * x = x;\n    one_right : forall x, x * one = x\n  }.\nNotation \"x * y\" := (dot x y).\n\nPrint Monoid.        (* 値コンストラクタの指定を省くと、Build_Monoid になる。 *)\nAbout one_left.      (* Arguments A, dot, one, Monoid are implicit *)\n(* Class ではなく、Record の場合は、dot one は implicit ではない。 *)\nAbout one_right.\n\n\n(**\nMonad モナド\nMonadの定義は文献[2]\n*)\nClass Monad {M : Type -> Type} :=\n  {\n    bind {A B} : M A -> (A -> M B) -> M B\n      where \"x >>= f\" := (bind x f);\n    ret {A} : A -> M A;\n    monad_1 : forall {A B} (f : A -> M B) (x : A),\n                (ret x >>= f) = (f x);\n    monad_2 : forall {A} (m : M A),\n                (m >>= ret) = m;\n    monad_3 : forall {A B C} (f : A -> M B) (g : B -> M C) (m : M A),\n                (m >>= f >>= g) = (m >>= (fun x => f x >>= g))\n}.\nNotation \"x >>= f\" := (@bind _ _ _ _ x f).\n\n\n(**\nモナドがモノイドであることを証明する。\n証明は文献[3]をもとの単純化した。\n *)\n\nRequire Import Coq.Logic.FunctionalExtensionality.\nCheck @functional_extensionality :\n  forall (A B : Type) (f g : A -> B), (forall x : A, f x = g x) -> f = g.\n\nGeneralizable Variables M F.                (* この場合が、M Fは自動判定される。 *)\n(*\n普通に型変数を宣言しても、この場合は同じである。\nVariable M : Type.\nVariable F : Type -> Type.\n*)\n\nProgram Instance MonMonoid `{MM : @Monoid M} `{MF : @Monad F} : @Monoid (F M) :=\n  {\n    one := ret one;\n    dot m n :=\n      m >>= (fun x => n >>= (fun y => ret (x * y)))\n  }.\nNext Obligation.                            (* 結合則 *)\nProof.\n  rewrite monad_3.\n  congr (x >>= _).\n  (* x >>= A ならよいが、A >>= B を分解してはいけない。 *)\n  apply functional_extensionality => m.\n  rewrite !monad_3.\n  congr (y >>= _).\n  apply functional_extensionality => m'.\n  rewrite monad_1 monad_3.\n  congr (z >>= _).\n  apply functional_extensionality => m''.\n  rewrite monad_1.\n    by rewrite dot_assoc.\nQed.\nNext Obligation.                            (* 左単位元 *)\nProof.\n  rewrite monad_1 -{2}(monad_2 x).\n  congr (x >>= _).\n  apply functional_extensionality => y.\n    by rewrite one_left.\nQed.\nNext Obligation.                            (* 右単位元 *)\nProof.\n  rewrite -{2}(monad_2 x).\n  congr (x >>= _).\n  apply functional_extensionality => y.\n  rewrite monad_1.\n    by rewrite one_right.\nQed.    \n\n(* END *)\n\n(**\n文献[1] A Gentle Introduction to Type Classes and Relations in Coq\n\n文献[2] Coq演習2014 第8回 課題39\nhttp://qnighy.github.io/coqex2014/ex8.html\n\n文献[3] Monadモノイドはモノイドである。\nhttp://qiita.com/minpou/items/20ba354b32af89b20c64\nhttps://gist.github.com/minpou/0f4c4a509c253cd7d555\n *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/gitcrc/ssr_monoid_monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7431329794131333}}
{"text": "Require Import List.\nRequire Import Bool.\nRequire Import ZArith.\nRequire Import Recdef.\nRequire Import sort_lectures.\n\n\nFunction minimum (lst : list Z) := \n   match lst with      \n      | m :: nil => m\n      | hd :: tl => let minimum_tail := minimum tl in if (hd <=? minimum_tail)%Z then hd else minimum_tail\n      | _ => 0%Z (* Error has occured *)\n   end.\n\nFunction remove (x : Z) (lst : list Z) :=\n   match lst with\n      | nil => nil\n      | hd :: tl => if (hd =? x)%Z then tl else hd :: (remove x tl)\n   end.\n\n\nFunction selectionSort (lst : list Z) :=\n   match lst with\n      | nil => nil\n      (* TODO: \"Recursive definition of selectionSort is ill-formed.\" *)\n      | _ => let min := minimum lst in min :: (selectionSort (remove min lst))       \n   end.\n               \n\nEval compute in (selectionSort (12 :: 2 :: 7 :: 46 :: 5 :: 6 :: 7 :: 28 :: 19 :: nil)%Z).\n\n\n\n(* SelectionSort always returns sorted list *)\nLemma returns_sorted_list :\n   forall l : list Z, urejen (selectionSort l).\nProof.\n   admit.\nQed.\n\n(* SelectionSort always returns same list (permutation of a list) *)\nLemma returns_permuted_list :\n   forall l : list Z, permutiran l (selectionSort l).\nProof.\n   admit.\nQed.\n", "meta": {"author": "MartinJakomin", "repo": "lvr-Coq", "sha": "fda54765a382a0c73fa81468a4ddd95c63cdb167", "save_path": "github-repos/coq/MartinJakomin-lvr-Coq", "path": "github-repos/coq/MartinJakomin-lvr-Coq/lvr-Coq-fda54765a382a0c73fa81468a4ddd95c63cdb167/Coq/selection_sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303292, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7431204620234156}}
{"text": "Require Export D.\n\n\n\n(** **** Exercise: 3 stars, optional (fold_bexp_Eq_informal)  *)\n(** Here is an informal proof of the [BEq] case of the soundness\n    argument for boolean expression constant folding.  Read it\n    carefully and compare it to the formal proof that follows.  Then\n    fill in the [BLe] case of the formal proof (without looking at the\n    [BEq] case, if possible).\n\n   _Theorem_: The constant folding function for booleans,\n   [fold_constants_bexp], is sound.\n\n   _Proof_: We must show that [b] is equivalent to [fold_constants_bexp],\n   for all boolean expressions [b].  Proceed by induction on [b].  We\n   show just the case where [b] has the form [BEq a1 a2].\n\n   In this case, we must show \n       beval st (BEq a1 a2) \n     = beval st (fold_constants_bexp (BEq a1 a2)).\n   There are two cases to consider:\n\n     - First, suppose [fold_constants_aexp a1 = ANum n1] and\n       [fold_constants_aexp a2 = ANum n2] for some [n1] and [n2].\n\n       In this case, we have\n           fold_constants_bexp (BEq a1 a2) \n         = if beq_nat n1 n2 then BTrue else BFalse\n       and\n           beval st (BEq a1 a2) \n         = beq_nat (aeval st a1) (aeval st a2).\n       By the soundness of constant folding for arithmetic\n       expressions (Lemma [fold_constants_aexp_sound]), we know\n           aeval st a1 \n         = aeval st (fold_constants_aexp a1) \n         = aeval st (ANum n1) \n         = n1\n       and\n           aeval st a2 \n         = aeval st (fold_constants_aexp a2) \n         = aeval st (ANum n2) \n         = n2,\n       so\n           beval st (BEq a1 a2) \n         = beq_nat (aeval a1) (aeval a2)\n         = beq_nat n1 n2.\n       Also, it is easy to see (by considering the cases [n1 = n2] and\n       [n1 <> n2] separately) that\n           beval st (if beq_nat n1 n2 then BTrue else BFalse)\n         = if beq_nat n1 n2 then beval st BTrue else beval st BFalse\n         = if beq_nat n1 n2 then true else false\n         = beq_nat n1 n2.\n       So\n           beval st (BEq a1 a2) \n         = beq_nat n1 n2.\n         = beval st (if beq_nat n1 n2 then BTrue else BFalse),\n]]         \n       as required.\n\n     - Otherwise, one of [fold_constants_aexp a1] and\n       [fold_constants_aexp a2] is not a constant.  In this case, we\n       must show\n           beval st (BEq a1 a2) \n         = beval st (BEq (fold_constants_aexp a1)\n                         (fold_constants_aexp a2)),\n       which, by the definition of [beval], is the same as showing\n           beq_nat (aeval st a1) (aeval st a2) \n         = beq_nat (aeval st (fold_constants_aexp a1))\n                   (aeval st (fold_constants_aexp a2)).\n       But the soundness of constant folding for arithmetic\n       expressions ([fold_constants_aexp_sound]) gives us\n         aeval st a1 = aeval st (fold_constants_aexp a1)\n         aeval st a2 = aeval st (fold_constants_aexp a2),\n       completing the case.  []\n*)\n\nLemma aeval_sound : forall a st,\n  aeval st a = aeval st (fold_constants_aexp a).\n  Proof. apply fold_constants_aexp_sound. Qed.\n\nTheorem fold_constants_bexp_sound: \n  btrans_sound fold_constants_bexp.\nProof.\n  unfold btrans_sound. intros b. unfold bequiv. intros st.\n  bexp_cases (induction b) Case; \n    (* BTrue and BFalse are immediate *)\n    try reflexivity. \n  Case \"BEq\". \n    (* Doing induction when there are a lot of constructors makes\n       specifying variable names a chore, but Coq doesn't always\n       choose nice variable names.  We can rename entries in the\n       context with the [rename] tactic: [rename a into a1] will\n       change [a] to [a1] in the current goal and context. *)\n    rename a into a1. rename a0 into a2. simpl.\n    remember (fold_constants_aexp a1) as a1' eqn:Heqa1'.\n    remember (fold_constants_aexp a2) as a2' eqn:Heqa2'.\n    replace (aeval st a1) with (aeval st a1') by\n       (subst a1'; rewrite <- fold_constants_aexp_sound; reflexivity).\n    replace (aeval st a2) with (aeval st a2') by\n       (subst a2'; rewrite <- fold_constants_aexp_sound; reflexivity).\n    destruct a1'; destruct a2'; try reflexivity.\n      (* The only interesting case is when both a1 and a2 \n         become constants after folding *)\n      simpl. destruct (beq_nat n n0); reflexivity.\n  Case \"BLe\". \n    simpl; destruct (fold_constants_aexp a) eqn:Ha; destruct (fold_constants_aexp a0) eqn:Ha0; rewrite (fold_constants_aexp_sound a);\n    rewrite (fold_constants_aexp_sound a0); rewrite Ha; rewrite Ha0; simpl; try reflexivity. \n    destruct (ble_nat n n0) eqn:Heq; try reflexivity. \n    Case \"BNot\". \n    simpl. remember (fold_constants_bexp b) as b' eqn:Heqb'. \n    rewrite IHb.\n    destruct b'; reflexivity. \n  Case \"BAnd\". \n    simpl. \n    remember (fold_constants_bexp b1) as b1' eqn:Heqb1'. \n    remember (fold_constants_bexp b2) as b2' eqn:Heqb2'.\n    rewrite IHb1. rewrite IHb2.\n    (***\n     Note how we use the tactic [eauto].\n     ***)\n    destruct b1'; destruct b2'; simpl; try reflexivity\n    ; eauto using andb_true_l, andb_true_r, andb_false_l, andb_false_r.\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/09/P01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.8962513821399044, "lm_q1q2_score": 0.742937552667474}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Import PeanoNat Plus Mult Lt.\nLocal Open Scope nat_scope.\n\n(** Factorial *)\n\nFixpoint fact (n:nat) : nat :=\n  match n with\n    | O => 1\n    | S n => S n * fact n\n  end.\n\nArguments fact n%nat.\n\nLemma lt_O_fact n : 0 < fact n.\nProof.\n  induction n; simpl; auto with arith.\nQed.\n\nLemma fact_neq_0 n : fact n <> 0.\nProof.\n apply Nat.neq_0_lt_0, lt_O_fact.\nQed.\n\nLemma fact_le n m : n <= m -> fact n <= fact m.\nProof.\n  induction 1.\n  - apply le_n.\n  - simpl. transitivity (fact m). trivial. apply Nat.le_add_r.\nQed.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Arith/Factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.8289388083214155, "lm_q1q2_score": 0.7429375474989413}}
{"text": "Require Import List.\n\nSet Implicit Arguments.\n\nFixpoint sum (l:list nat) {struct l} : nat :=\n  match l with\n  | nil => 0\n  | cons x xs => x + sum xs\n  end.\n\nTheorem ex31 : forall l1 l2, sum (l1 ++ l2) = sum l1 + sum l2.\nProof using.\n  intros.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1. apply PeanoNat.Nat.add_assoc.\nQed.\n\nTheorem ex32 : forall (A:Type) (l:list A), length (rev l) = length l.\nProof using.\n  intros A l.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite app_length. rewrite IHl.\n    simpl. apply PeanoNat.Nat.add_comm.\nQed.\n\nTheorem ex33 : forall (A B:Type) (f:A->B) (l1 l2:list A),\n    (map f l1)++(map f l2) = map f (l1++l2).\nProof using.\n  intros A B f l1 l2.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n\nTheorem ex34 : forall (A B:Type) (f:A->B) (l:list A),\n    rev (map f l) = map f (rev l).\nProof using.\n  intros A B f l.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl. rewrite map_app. simpl. reflexivity.\nQed.\n\nInductive In (A:Type) (y:A) : list A -> Prop :=\n| InHead : forall xs:list A, In y (cons y xs)\n| InTail : forall (x:A) (xs:list A), In y xs -> In y (cons x xs).\n\nLemma my_in_inv : forall (A:Type) (a b:A) (l:list A),\n    In b (a :: l) -> b=a \\/ (In b l).\nProof using.\n  intros.\n  inversion H.\n  - left. reflexivity.\n  - right. assumption.\nQed.\n\nLemma my_in_or_app : forall (A:Type) (l1 l2: list A) (x:A),\n    In x l1 \\/ In x l2 -> In x (l1 ++ l2).\nProof using.\n  intros A l1 l2 x H.\n  destruct H.\n  - induction H.\n    + simpl. constructor.\n    + simpl. constructor. assumption.\n  - induction l1.\n    + simpl. assumption.\n    + rewrite <- app_comm_cons. constructor. assumption.\nQed.\n\nTheorem ex41 : forall (A:Type) (x:A) (l:list A), In x l -> In x (rev l).\nProof using.\n  intros A x l H.\n  induction H.\n  - simpl. apply my_in_or_app. right. apply InHead.\n  - simpl. apply my_in_or_app. left. assumption.\nQed.\n\nTheorem ex42 : forall (A B:Type) (y:B) (f:A->B) (l:list A),\n    In y (map f l) -> exists x, In x l /\\ y = f x.\nProof using.\n  intros A B y f l H.\n  induction l.\n  - simpl in H. inversion H.\n  - simpl in H. inversion H.\n    * exists a. split.\n      -- constructor.\n      -- reflexivity.\n    * apply IHl in H1.\n      destruct H1.\n      exists x0. destruct H1. split.\n      -- constructor. assumption.\n      -- assumption.\nQed.\n\nTheorem ex43 : forall (A:Type) (x:A) (l : list A), In x l -> exists l1, exists l2, l = l1 ++ (x::l2).\nProof using.\n  intros A x l H.\n  induction H.\n  - exists nil. exists xs. reflexivity.\n  - destruct IHIn.\n    destruct H0.\n    rewrite H0.\n    exists (x0::x1). exists x2.\n    reflexivity.\nQed.\n\nInductive Prefix (A:Type) : list A -> list A -> Prop :=\n| PreNil : forall l:list A, Prefix nil l\n| PreCons : forall (x:A) (l1 l2:list A), Prefix l1 l2 -> Prefix (x::l1) (x::l2).\n\nTheorem ex51 : forall (A:Type) (l1 l2:list A), Prefix l1 l2 -> length l1 <= length l2.\nProof using.\n  intros.\n  induction H.\n  - firstorder.\n  - elim H.\n    + intros. simpl. firstorder.\n    + intros. simpl. firstorder.\nQed.\n\nTheorem ex52 : forall l1 l2, Prefix l1 l2 -> (sum l1 <= sum l2).\nProof using.\n  intros l1 l2 H.\n  induction H.\n  - simpl. firstorder.\n  - simpl. firstorder.\nQed.\n\nTheorem ex53 : forall (A:Type) (l1 l2:list A) (x:A),\n    (In x l1) /\\ (Prefix l1 l2) -> In x l2.\nProof using.\n  intros A l1 l2 x H.\n  destruct H.\n  induction H0.\n  - induction l.\n    + assumption.\n    + apply InTail. assumption.\n  - inversion H.\n    + apply InHead.\n    + apply InTail. apply IHPrefix. assumption.\nQed.\n\nInductive SubList (A:Type) : list A -> list A -> Prop :=\n| SLnil : forall l:list A, SubList nil l\n| SLcons1 : forall (x:A) (l1 l2:list A), SubList l1 l2 -> SubList (x::l1) (x::l2)\n| SLcons2 : forall (x:A) (l1 l2:list A), SubList l1 l2 -> SubList l1 (x::l2).\n\nTheorem ex61 : forall (A:Type)(l1 l2 l3 l4:list A),\n    SubList l1 l2 -> SubList l3 l4 -> SubList (l1++l3) (l2++l4).\nProof using.\n  intros A l1 l2 l3 l4 H H0.\n  induction H.\n  - induction l.\n    + induction l3.\n      * apply SLnil.\n      * simpl. assumption.\n    + simpl. simpl in IHl. constructor. assumption.\n  - simpl. apply SLcons1. assumption.\n  - simpl. constructor. assumption.\nQed.\n\nTheorem ex62 : forall (A:Type) (l1 l2:list A),\n    SubList l1 l2 -> SubList (rev l1) (rev l2).\nProof using.\n  intros A l1 l2 H.\n  induction H.\n  - simpl. apply SLnil.\n  - simpl. apply ex61.\n    + apply IHSubList.\n    + apply SLcons1. apply SLnil.\n  - simpl.\n    cut (SubList (rev l1 ++ nil) (rev l2 ++ x :: nil)).\n    + rewrite app_nil_r. trivial.\n    + apply ex61.\n      * assumption.\n      * apply SLnil.\nQed.\n\nTheorem ex63 : forall (A:Type) (x:A) (l1 l2:list A),\n    Prefix l1 l2 ->  SubList l1 l2.\nProof using.\n  intros.\n  induction H.\n  apply SLnil.\n  apply SLcons1.\n  apply IHPrefix.\nQed.\n\nTheorem ex64 : forall (A:Type) (x:A) (l1 l2:list A),\n    SubList l1 l2 -> In x l1 -> In x l2.\nProof using.\n  intros A x l1 l2 H.\n  induction H.\n  - intro. induction l.\n    + assumption.\n    + apply InTail. assumption.\n  - intro. inversion H0.\n    + apply InHead.\n    + apply InTail. apply IHSubList. assumption.\n  - intro. apply InTail. apply IHSubList. assumption.\nQed.\n", "meta": {"author": "lrpereira", "repo": "software-verification", "sha": "d732c6341c6fa581a367b839820f43e0488db5c2", "save_path": "github-repos/coq/lrpereira-software-verification", "path": "github-repos/coq/lrpereira-software-verification/software-verification-d732c6341c6fa581a367b839820f43e0488db5c2/coq/tpc2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8962513682840825, "lm_q1q2_score": 0.7429375336068234}}
{"text": "Require Import nat.\nRequire Import le.\nRequire Import list.\nRequire Import In.\nRequire Import disjoint.\n\nTheorem pigeon_hole_with_LEM : forall (a:Type)(l k:list a),\n    (forall (x y:a), x = y \\/ x <> y) ->\n    (forall x, In x l -> In x k) ->\n    length k < length l ->\n    repeats l.\nProof.\n    intros a l k EqDec I L.\n    assert (forall (x:a) (l:list a), In x l \\/ ~In x l) as InDec.\n    { apply In_Decidable. exact EqDec. } clear EqDec.\n    revert I. revert L. revert k. induction l as [|x xs IH]. \n    - intros k H. inversion H.\n    - intros k L I. destruct (InDec x xs) as [Hx|Hx]. \n        + apply repeat_In. exact Hx.\n        + apply repeat_cons.\n            assert (exists k1 k2, k = k1 ++ x :: k2) as [k1 [k2 H0]].\n            { apply In_split. apply I. left. reflexivity. }\n            apply (IH (k1++k2)).\n                { apply Sn_lt_Sm__n_lt_m. rewrite app_length.\n                    rewrite H0 in L. rewrite app_length in L.\n                    simpl in L. rewrite plus_n_Sm in L. exact L.\n                }\n                { intros y Hy. \n                    assert (y <> x) as Exy.\n                        { intros E. apply Hx. rewrite <- E. exact Hy. }\n                    assert (In y k) as Iyk. \n                        { apply I. right. exact Hy. }\n                    rewrite H0 in Iyk. rewrite In_app_iff.\n                    rewrite In_app_iff in Iyk. destruct Iyk as [H1|[H1|H1]]. \n                        { left. exact H1. }\n                        { exfalso. apply Exy. symmetry. exact H1. }\n                        { right. exact H1. }\n                }\nQed.\n\n(*\nLemma temp : forall (a:Type) (l k:list a) (x:a),\n    In x k -> length l = length k -> (forall u, In u l -> In u k) -> \n    repeats (x :: l).\nProof.\n\n\nShow.\n*)\n           \n\n (*\nTheorem pigeon_hole : forall (a:Type) (l k:list a),\n    (forall x, In x l -> In x k) ->\n    length k < length l ->\n    repeats l.\nProof.\n    intros a l. induction l as [|x xs IHl].\n    - intros k H H'. inversion H'.\n    - intros k. revert IHl. revert xs x. induction k as [|y ys IHk].\n        + intros xs x IHl H. assert (In x []) as H'.\n            { apply H. left. reflexivity. }\n            inversion H'.\n        + intros xs x H H' L. assert (In x (y::ys)) as H0.\n            { apply H'. left. reflexivity. }\n            destruct H0 as [H0|H0].\n                { \nShow.\n*)\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/sf/pigeon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7428628051837528}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) : natural :=\n  plus Zero (mult lf2 x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj196_coqofml_SGLMYJ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7428628031643902}}
{"text": "Require Import ssreflect.\nRequire Import Metalib.Metatheory.\n\n(* ------- these should be added to the metatheory library ------------------------- *)\n\n(* If we have identified a variable in the middle of a uniq environment, \n   it fixes the front and back. *)\nLemma uniq_mid A x (a a':A) G1 : forall G2 G1' G2',\n    uniq (G1 ++ (x ~ a) ++ G2) -> \n    (G1 ++ x ~ a ++ G2) = (G1' ++ x ~ a' ++ G2') ->\n    G1 = G1' /\\ a = a' /\\ G2 = G2'.\nProof.    \n  induction G1.\n  + intros.\n    destruct G1'; inversion H0; simpl_env in *. auto.\n    subst. destruct_uniq. fsetdec.\n  + intros.\n    destruct a0 as [y b].\n    simpl_env in *.\n    destruct_uniq.\n    have NE: not (y = x). fsetdec.\n    destruct G1' as [|[z c]]. simpl_env in H0. inversion H0. done.\n    inversion H0. subst.\n    simpl_env in *.\n    specialize (IHG1 G2 G1' G2').\n    destruct IHG1 as [E1 [E2 E3]]; auto.\n    subst. auto.\nQed.\n\n(* If x is in an environment, it is either in the front half or \n   the back half. *)\nLemma binds_split A x (a:A) G : binds x a G -> exists G1 G2, G = G2 ++ [(x, a)] ++ G1.\nProof.\n  move=>B. induction G.\n  + inversion B.\n  + destruct a0 as [y b].\n    apply binds_cons_1 in B.\n    destruct B as [[E1 E2]|E]. subst.\n    ++ exists G. exists nil. auto.\n    ++ destruct (IHG E) as [G1 [G2 E2]].\n       subst.\n       eexists. exists ((y ~ b) ++ G2). simpl_env. \n       eauto.\nQed.\n\n(* If we divide up a context containing a variable, it either appears in the \n   front half or the back half *)\nLemma ctx_align_eq A G1 G2 (x:atom) (a:A) G0 G3 :\n  uniq (G2 ++ x ~ a ++ G1) ->\n  G2 ++ x ~ a ++ G1 = G0 ++ G3 ->\n  (exists G0' G0'', G0 = G0' ++ x ~ a ++ G0'' /\\ G2 = G0' /\\ G1 = G0'' ++ G3) \\/\n  (exists G3' G3'', G3 = G3' ++ x ~ a ++ G3'' /\\ G2 = G0 ++ G3' /\\ G1 = G3''). \nProof.\n  intros U E.\n  have B: binds x a (G0 ++ G3). { rewrite <- E. auto. }\n  rewrite -> binds_app_iff in B.\n  destruct B as [h1|h1]. \n  + left.\n    destruct (binds_split _ _ _ _ h1) as [G0'' [G0' E2]].\n    exists G0'. exists G0''. split. auto.\n    subst.\n    simpl_env in E.\n    edestruct uniq_mid with (G1 := G2) (G1' := G0')\n                            (G2 := G1) (G2' := G0'' ++ G3); eauto.\n    tauto.\n  + right.\n    destruct (binds_split _ _ _ _ h1) as [G0'' [G0' E2]].\n    exists G0'. exists G0''. split. auto.\n    subst.\n    edestruct uniq_mid with (G1 := G2) (G1' := G0 ++ G0')\n                            (G2 := G1) (G2' := G0''); simpl_env; eauto.\n    tauto.\nQed.\n", "meta": {"author": "sweirich", "repo": "graded-haskell", "sha": "97eee95dfb6aedef81c81e8a64b9ad2b718c2815", "save_path": "github-repos/coq/sweirich-graded-haskell", "path": "github-repos/coq/sweirich-graded-haskell/graded-haskell-97eee95dfb6aedef81c81e8a64b9ad2b718c2815/GraD/src-def/metalib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7428627991256648}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (x : natural) : natural :=\n  plus Zero (mult lf3 x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj146_coqofml_8aSaXa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7428627970950546}}
{"text": "Require Import Recdef.\nRequire Import Integer.\n\nInductive ExoticZ : Type :=\n| Zero' : ExoticZ\n| MinusOne : ExoticZ\n| Next : ExoticZ -> ExoticZ.\n\n\n\n\n(* Add for ExoticZ *)\nFunction succ' (k : ExoticZ) : ExoticZ :=\nmatch k with\n| Zero' => Next Zero'\n| MinusOne => Zero'\n| Next Zero' => Next (Next Zero')\n| Next MinusOne => MinusOne\n| Next k' => Next (succ' k')\nend.\n\nFunction pred' (k : ExoticZ) : ExoticZ :=\nmatch k with\n| Zero' => MinusOne\n| MinusOne => Next MinusOne\n| Next Zero' => Zero'\n| Next MinusOne => Next (Next MinusOne)\n| Next k' => Next (pred' k')\nend.\n\nFunction abs (k: ExoticZ) : nat :=\nmatch k with\n| Zero'    => 0\n| MinusOne => 1\n| Next k'  => S (abs k')\nend.\n\nFunction pos (k: ExoticZ) : bool :=\nmatch k with\n| Zero'    => true\n| MinusOne => false\n| Next k'  => pos k'\nend.\n\nDefinition add' (a b : ExoticZ) : ExoticZ :=\nmatch pos a with \n| true  => map_n (abs a) succ' b\n| false => map_n (abs a) pred' b\nend.\n\nLemma next_pos_is_same : forall z: ExoticZ, pos z = pos (Next z).\nProof.\n  intros z. induction z; auto.\nQed.\n\nLemma if_pos_next_is_succ : forall z: ExoticZ, pos z = true -> Next z = succ' z.\nProof.\n  intro z. induction z; auto.\n  - intros H. cbn in *. discriminate H.\n  - intros H. assert (P: pos z = true) by (rewrite <- H; apply next_pos_is_same; auto).\n    cbn. specialize (IHz P). rewrite <- IHz. destruct z; auto. cbn in P. discriminate.\nQed.\n\nLemma if_neg_next_is_pred : forall z: ExoticZ, pos z = false -> Next z = pred' z.\nProof.\n  intro z. induction z; auto.\n  - intros H. cbn in *. discriminate H.\n  - intros H. assert (P: pos z = false) by (rewrite <- H; apply next_pos_is_same; auto).\n    cbn. specialize (IHz P). rewrite <- IHz. destruct z; auto. cbn in P. discriminate.\nQed.\n\nTheorem ExoticZ_ind' (P : ExoticZ -> Prop) (base: P Zero') (suc: forall z: ExoticZ, P z -> P (succ' z)) \n  (pre: forall z: ExoticZ, P z -> P (pred' z)) : forall z: ExoticZ, P z.\nProof.\n  intro z. induction z; auto.\n  - apply (pre _ base).\n  - destruct (pos z) eqn:pos.\n    + rewrite (if_pos_next_is_succ z pos). apply (suc _ IHz).\n    + rewrite (if_neg_next_is_pred z pos). apply (pre _ IHz).\nQed.\n\n\n\n\n(* Izomorphism *)\nDefinition h (n: ExoticZ) : Z :=\nmatch n with\n| Zero'    => Zero\n| MinusOne => Neg O\n| Next n'  => if pos n' \n              then Pos (abs n')\n              else Neg (abs n')\nend.\n\nDefinition h_inv (n: Z) : ExoticZ :=\nmatch n with\n| Pos n' => map_n (S n') Next Zero'\n| Zero   => Zero'\n| Neg n' => map_n n' Next MinusOne\nend.\n\n\n\n\nLemma abs_for_map_n : forall n: nat, abs (map_n n Next Zero') = n.\nProof.\n  intros n. induction n; auto. cbn. f_equal. assumption.\nQed.\n\nLemma abs_for_map_n' : forall n: nat, abs (map_n n Next MinusOne) = S n.\nProof.\n  intros n. induction n; auto. cbn. f_equal. assumption.\nQed.\n\nLemma pos_for_map_n : forall n: nat, pos (map_n n Next Zero') = true.\nProof.\n  intros n. induction n; auto.\nQed.\n\nLemma pos_for_map_n' : forall n: nat, pos (map_n n Next MinusOne) = false.\nProof.\n  intros n. induction n; auto.\nQed.\n\nLemma map_n_abs_pos : forall n: ExoticZ, pos n = true -> map_n (abs n) Next Zero' = n.\nProof.\n  intros n H. induction n; auto.\n  - cbn in *. discriminate.\n  - cbn in *. f_equal. apply IHn. assumption. \nQed.\n\nLemma map_n_abs_neg : forall n: ExoticZ, pos n = false -> map_n (abs n) Next MinusOne = Next n.\nProof.\n  intros n H. induction n; auto.\n  - cbn in *. discriminate.\n  - cbn in *. f_equal. apply IHn. assumption. \nQed.\n\n\n\n(* Bijection of h function *)\nTheorem h_bijection : forall x : Z, h (h_inv x) = x.\nProof.\n  intros x. induction x using Z_ind''; [auto| auto | auto |..]; cbn.\n  - now rewrite pos_for_map_n, abs_for_map_n.\n  - now rewrite pos_for_map_n', abs_for_map_n'.\nQed.\n\nTheorem h_bijection' : forall x : ExoticZ, h_inv (h x) = x.\nProof.\n  intros x. destruct x; auto. cbn. destruct (pos x) eqn:P; cbn.\n  - f_equal. now apply map_n_abs_pos.\n  - now apply map_n_abs_neg.\nQed.\n\nLemma h_surjection : forall y: Z, exists x: ExoticZ, h x = y.\nProof.\n  intros y. exists (h_inv y). apply h_bijection.\nQed.\n\nLemma h_iniection : forall x y: ExoticZ, h x = h y -> x = y.\nProof.\n  intros x y H. rewrite <- (h_bijection' x), <- (h_bijection' y). f_equal. assumption.\nQed.\n\n\n\nLemma pred'_for_pos : forall x : ExoticZ, pos x = true -> pred' (Next x) = x.\nProof.\n  intros x P. induction x; cbn in *; [auto | discriminate |]. specialize (IHx P).\n  now rewrite IHx.\nQed.\n\nLemma succ'_for_neg : forall x : ExoticZ, pos x = false -> succ' (Next x) = x.\nProof.\n  intros x P. induction x; cbn in *; [discriminate | auto |]. specialize (IHx P).\n  now rewrite IHx.\nQed.\n\nLemma pred'_for_neg : forall x : ExoticZ, pos x = false -> pred' x = Next x.\nProof.\n  intros x P. induction x; cbn in *; [discriminate | auto |]. specialize (IHx P).\n  rewrite IHx. destruct x; [| auto | auto]. cbn in *. discriminate.\nQed.\n\nLemma succ'_for_pos : forall x : ExoticZ, pos x = true -> succ' x = Next x.\nProof.\n  intros x P. induction x; cbn in *; [auto | discriminate |]. specialize (IHx P).\n  rewrite IHx. destruct x; [auto | | auto]. cbn in *. discriminate.\nQed.\n\nLemma succ'_pred': forall k : ExoticZ, succ' (pred' k) = k.\nProof.\n  intros x. functional induction (pred' x); cbn; [auto | auto | auto | auto |]. \n  rewrite IHe. functional induction (pred' k'); cbn; auto. contradiction.\nQed.\n\nLemma pred'_succ' : forall k : ExoticZ, pred' (succ' k) = k.\nProof.\n  intros k; functional induction (succ' k); cbn; [auto | auto | auto | auto |]. \n  rewrite IHe. functional induction (succ' k'); cbn in *; auto.\n  contradiction.\nQed.\n\nLemma pred_h : forall x: ExoticZ, pred (h x) = h (pred' x).\nProof.\n  intro x. destruct (pos x) eqn:P; destruct x; auto; cbn in P.\n  - rewrite pred'_for_pos; auto. cbn. rewrite P.\n    destruct x; cbn in *; [auto | discriminate|]. now rewrite P.\n  - rewrite pred'_for_neg; auto. cbn. now rewrite P.\nQed.\n\nLemma succ_h : forall x: ExoticZ, succ (h x) = h (succ' x).\nProof.\n  intro x. destruct (pos x) eqn:P; destruct x; auto; cbn in P.\n  - rewrite succ'_for_pos; auto. cbn. now rewrite P.\n  - rewrite succ'_for_neg; auto. cbn. rewrite P. \n    destruct x; cbn in *; [auto | auto |]. now rewrite P.\nQed.\n\nLemma add'_l_succ' : forall x y: ExoticZ, add' (succ' x) y = succ' (add' x y).\nProof.\n  intros x y. induction y using ExoticZ_ind'.\n  - destruct x; auto. unfold add'. destruct (pos x) eqn:P.\n    + rewrite succ'_for_pos; auto. cbn. now rewrite P.\n    + rewrite succ'_for_neg; auto. cbn. now rewrite P, succ'_pred'.\n  - destruct x; auto.\n    + cbn. now  rewrite succ'_pred'.\n    + unfold add'. destruct (pos x) eqn:P.\n      * rewrite succ'_for_pos; auto. cbn. now rewrite P.\n      * rewrite succ'_for_neg; auto. cbn. now rewrite P, succ'_pred'.\n  - destruct x; auto.\n    + cbn. now rewrite succ'_pred'.\n    + unfold add'. destruct (pos x) eqn:P.\n      * rewrite succ'_for_pos; auto. cbn. now rewrite P.\n      * rewrite succ'_for_neg; auto. cbn. now rewrite P, succ'_pred'.\nQed.\n\nLemma add'_l_pred' : forall x y: ExoticZ, add' (pred' x) y = pred' (add' x y).\nProof.\n  intros x y. induction y using ExoticZ_ind'.\n  - destruct x; auto. unfold add'. destruct (pos x) eqn:P.\n    + rewrite pred'_for_pos; auto. cbn. now rewrite P, pred'_succ'.\n    + rewrite pred'_for_neg; auto. cbn. now rewrite P.\n  - destruct x; auto. unfold add'. destruct (pos x) eqn:P.\n    + rewrite pred'_for_pos; auto. cbn. now rewrite P, pred'_succ'.\n    + rewrite pred'_for_neg; auto. cbn. now rewrite P.\n  - destruct x; auto. unfold add'. destruct (pos x) eqn:P.\n    + rewrite pred'_for_pos; auto. cbn. now rewrite P, pred'_succ'.\n    + rewrite pred'_for_neg; auto. cbn. now rewrite P.\nQed.\n\n(* Homomorphism of algebraic structures *)\nTheorem Z_ExoticZ_homo : forall x y: ExoticZ, add (h x) (h y) = h (add' x y).\nProof.\n  intros x y. induction x using ExoticZ_ind'; [auto|..].\n  - now rewrite add'_l_succ', <- succ_h, <- succ_h, <- IHx, add_l_succ.\n  - now rewrite add'_l_pred', <- pred_h, <- pred_h, <- IHx, add_l_pred.\nQed.\n\n\n\n\n\n", "meta": {"author": "speederking07", "repo": "magisterka", "sha": "602d1e328ac4a396c282e241744d129573a65381", "save_path": "github-repos/coq/speederking07-magisterka", "path": "github-repos/coq/speederking07-magisterka/magisterka-602d1e328ac4a396c282e241744d129573a65381/Master/ExoticInteger.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7428504176395433}}
{"text": "(***************************************************************************\n* Generic Variables for Programming Language Metatheory                    *\n* Brian Aydemir & Arthur Charguéraud, July 2007, Coq v8.1      é            *\n***************************************************************************)\n\nSet Implicit Arguments.\nRequire Import List Max Omega OrderedType OrderedTypeEx.\nRequire Import Lib_Tactic Lib_ListFacts Lib_FinSet Lib_FinSetImpl.\nRequire Export Lib_ListFactsMore.\n\n(* ********************************************************************** *)\n(** * Abstract Definition of Variables *)\n\nModule Type VARIABLES.\n\n(** We leave the type of variables abstract. *)\n\nParameter var : Set.\n\n(** This type is inhabited. *)\n\nParameter var_default : var.\n\n(** Variables are ordered. *)\n\nDeclare Module Var_as_OT : UsualOrderedType with Definition t := var.\n\n(** We can form sets of variables. *)\n\nDeclare Module Import VarSet : FinSet with Module E := Var_as_OT.\nOpen Local Scope set_scope.\n\nDefinition vars := VarSet.S.t.\n\n(** Finally, we have a means of generating fresh variables. *)\n\nParameter var_generate : vars -> var.\nParameter var_generate_spec : forall E, (var_generate E) \\notin E.\nParameter var_fresh : forall (L : vars), { x : var | x \\notin L }.\n\nEnd VARIABLES.\n\n\n(* ********************************************************************** *)\n(** * Concrete Implementation of Variables *)\n\nModule Variables : VARIABLES.\n\nDefinition var := nat.\n\nDefinition var_default : var := O.\n\nModule Var_as_OT := Nat_as_OT.\n\nModule Import VarSet : FinSet with Module E := Var_as_OT :=\n  Lib_FinSetImpl.Make Var_as_OT.\nOpen Local Scope set_scope.\n\nDefinition vars := VarSet.S.t.\n\nOpen Scope nat_scope.\n\nLemma max_lt_l :\n  forall (x y z : nat), x <= y -> x <= max y z.\nProof.\n  induction x; auto with arith.\n  induction y; induction z; simpl; auto with arith.\nQed.\n\nLemma finite_nat_list_max : forall (l : list nat),\n  { n : nat | forall x, In x l -> x <= n }.\nProof.\n  induction l as [ | l ls IHl ].\n  exists 0; intros x H; inversion H.\n  inversion IHl as [x H].\n  exists (max x l); intros y J; simpl in J; inversion J.\n    subst; auto with arith.\n    assert (y <= x); auto using max_lt_l.\nQed.\n\nLemma finite_nat_list_max' : forall (l : list nat),\n  { n : nat | ~ In n l }.\nProof.\n  intros l.\n  case (finite_nat_list_max l); intros x H.\n  exists (S x).\n  intros J.\n  assert (K := H _ J); omega.\nQed.\n\nDefinition var_generate (L : vars) : var :=\n  proj1_sig (finite_nat_list_max' (S.elements L)).\n\nLemma var_generate_spec : forall E, (var_generate E) \\notin E.\nProof.\n  unfold var_generate. intros E.\n  destruct (finite_nat_list_max' (S.elements E)) as [n pf].\n  simpl. intros a.\n  assert (In n (S.elements E)). rewrite <- InA_iff_In.\n  auto using S.elements_1.\n  intuition.\nQed.\n\nLemma var_fresh : forall (L : vars), { x : var | x \\notin L }.\nProof.\n  intros L. exists (var_generate L). apply var_generate_spec.\nQed.\n\nEnd Variables.\n\n\n(* ********************************************************************** *)\n(** * Properties of variables *)\n\nExport Variables.\nExport Variables.VarSet.\nModule Export VarSetFacts := FinSetFacts VarSet.\n\nOpen Scope set_scope.\n\n(** Equality on variables is decidable. *)\n\nModule Import Var_as_OT_Facts := OrderedTypeFacts Variables.Var_as_OT.\n\nLemma eq_var_dec : forall x y : var, {x = y} + {x <> y}.\nProof.\n  exact Var_as_OT_Facts.eq_dec.\nQed.\n\n(* ********************************************************************** *)\n(** ** Dealing with list of variables *)\n\n(** Freshness of n variables from a set L and from one another. *)\n\nFixpoint fresh (L : vars) (n : nat) (xs : list var) {struct xs} : Prop :=\n  match xs, n with\n  | nil, O => True\n  | x::xs', S n' => x \\notin L /\\ fresh (L \\u {{x}}) n' xs'\n  | _,_ => False\n  end.\n\nHint Extern 1 (fresh _ _ _) => simpl.\n\n(** Triviality : If a list xs contains n fresh variables, then\n    the length of xs is n. *)\n\nLemma fresh_length : forall xs L n,\n  fresh L n xs -> n = length xs.\nProof.\n  induction xs; simpl; intros; destruct n;\n  try solve [ contradictions* | f_equal* ].\nQed.\n\n(* It is possible to build a list of n fresh variables. *)\n\nLemma var_freshes : forall L n,\n  { xs : list var | fresh L n xs }.\nProof.\n  intros. gen L. induction n; intros L.\n  exists* (nil : list var).\n  destruct (var_fresh L) as [x Fr].\n   destruct (IHn (L \\u {{x}})) as [xs Frs].\n   exists* (x::xs).\nQed.\n\n\n(* ********************************************************************** *)\n(** ** Tactics: Case Analysis on Variables *)\n\n(** We define notations for the equality of variables (our free variables)\n  and for the equality of naturals (our bound variables represented using\n  de Bruijn indices). *)\n\nNotation \"x == y\" := (eq_var_dec x y) (at level 67).\nNotation \"i === j\" := (Peano_dec.eq_nat_dec i j) (at level 67).\n\n(** Tactic for comparing two bound or free variables. *)\n\nLtac case_nat :=\n  let destr x y := destruct (x === y); [try subst x | idtac] in\n  match goal with\n  | H: context [?x === ?y] |- _ => destr x y\n  | |- context [?x === ?y]      => destr x y\n  end.\n\nTactic Notation \"case_nat\" \"*\" := case_nat; auto*.\n\nTactic Notation \"case_var\" :=\n  let destr x y := destruct (x == y); [try subst x | idtac] in\n  match goal with\n  | H: context [?x == ?y] |- _ => destr x y\n  | |- context [?x == ?y]      => destr x y\n  end.\n\nTactic Notation \"case_var\" \"*\" := case_var; auto*.\n\n\n(* ********************************************************************** *)\n(** ** Tactics: Picking Names Fresh from the Context *)\n\n(** [gather_vars_for_type T F] return the union of all the finite sets\n  of variables [F x] where [x] is a variable from the context such that\n  [F x] type checks. In other words [x] has to be of the type of the\n  argument of [F]. The resulting union of sets does not contain any\n  duplicated item. This tactic is an extreme piece of hacking necessary\n  because the tactic language does not support a \"fold\" operation on\n  the context. *)\n\nLtac gather_vars_with F :=\n  let rec gather V :=\n    match goal with\n    | H: ?S |- _ =>\n      let FH := constr:(F H) in\n      match V with\n      | {} => gather FH\n      | context [FH] => fail 1\n      | _ => gather (FH \\u V)\n      end\n    | _ => V\n    end in\n  let L := gather {} in eval simpl in L.\n\n(** [beautify_fset V] assumes that [V] is built as a union of finite\n  sets and return the same set cleaned up: empty sets are removed and\n  items are laid out in a nicely parenthesized way *)\n\nLtac beautify_fset V :=\n  let rec go Acc E :=\n     match E with\n     | ?E1 \\u ?E2 => let Acc1 := go Acc E1 in\n                     go Acc1 E2\n     | {}  => Acc\n     | ?E1 => match Acc with\n              | {} => E1\n              | _ => constr:(Acc \\u E1)\n              end\n     end\n  in go {} V.\n\n(** [pick_fresh_gen L Y] expects [L] to be a finite set of variables\n  and adds to the context a variable with name [Y] and a proof that\n  [Y] is fresh for [L]. *)\n\nLtac pick_fresh_gen L Y :=\n  let Fr := fresh \"Fr\" in\n  let L := beautify_fset L in\n  (destruct (var_fresh L) as [Y Fr]).\n\n(** [pick_fresh_gens L n Y] expects [L] to be a finite set of variables\n  and adds to the context a list of variables with name [Y] and a proof\n  that [Y] is of length [n] and contains variable fresh for [L] and\n  distinct from one another. *)\n\nLtac pick_freshes_gen L n Y :=\n  let Fr := fresh \"Fr\" in\n  let L := beautify_fset L in\n  (destruct (var_freshes L n) as [Y Fr]).\n\n(** Demo of pick_fresh_gen *)\n\nLtac test_pick_fresh_filter Y :=\n  let A := gather_vars_with (fun x : vars => x) in\n  let B := gather_vars_with (fun x : var => {{ x }}) in\n  let C := gather_vars_with (fun x : var => {}) in\n  pick_fresh_gen (A \\u B \\u C) Y.\n\nLemma test_pick_fresh : forall (x y z : var) (L1 L2 L3: vars), True.\nProof.\n  intros. test_pick_fresh_filter k. auto.\nQed.\n\n(** The above invokation of [pick_fresh] generates a\n  variable [k] and the hypothesis\n  [k \\notin L1 \\u L2 \\u L3 \\u {{x}} \\u {{y}} \\u {{z}}] *)\n\n\n(* ********************************************************************** *)\n(** ** Tactics: Applying Lemmas With Quantification Over Cofinite Sets *)\n\n(** [apply_fresh_base] tactic is a helper to build tactics that apply an\n  inductive constructor whose first argument should be instanciated\n  by the set of names already used in the context. Those names should\n  be returned by the [gather] tactic given in argument. For each premise\n  of the inductive rule starting with an universal quantification of names\n  outside the set of names instanciated, a subgoal with be generated by\n  the application of the rule, and in those subgoal we introduce the name\n  quantified as well as its proof of freshness. *)\n\nLtac apply_fresh_base_simple lemma gather :=\n  let L0 := gather in let L := beautify_fset L0 in\n  first [apply (@lemma L) | eapply (@lemma L)].\n\nLtac apply_fresh_base lemma gather var_name :=\n  apply_fresh_base_simple lemma gather;\n  try match goal with |- forall _, _ \\notin _ -> _ =>\n    let Fr := fresh \"Fr\" in intros var_name Fr end.\n\n\n(** [inst_notin H y as H'] expects [H] to be of the form\n  [forall x, x \\notin L, P x] and creates an hypothesis [H']\n  of type [P y]. It tries to prove the subgoal [y \\notin L]\n  by [auto]. This tactic is very useful to apply induction\n  hypotheses given in the cases with binders. *)\n\nTactic Notation \"inst_notin\" constr(lemma) constr(var)\n                \"as\" ident(hyp_name) :=\n  let go L := let Fr := fresh in assert (Fr : var \\notin L);\n     [ auto | poses hyp_name (@lemma var Fr); clear Fr ] in\n  match type of lemma with\n  | forall _, _ \\notin ?L -> _ => go L\n  | forall _, (_ \\in ?L -> False) -> _ => go L\n  end.\n\nTactic Notation \"inst_notin\" \"*\" constr(lemma) constr(var)\n                \"as\" ident(hyp_name) :=\n  inst_notin lemma var as hyp_name; auto*.\n\n\n", "meta": {"author": "spl", "repo": "formal_binders", "sha": "392d6e5c52d54d9b0bddc22f9ccbd2a0d765acbb", "save_path": "github-repos/coq/spl-formal_binders", "path": "github-repos/coq/spl-formal_binders/formal_binders-392d6e5c52d54d9b0bddc22f9ccbd2a0d765acbb/Metatheory_Var.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7428504158886585}}
{"text": "(* Running Example: Commutativity of Addition *)\n\nLemma add_comm (x y : nat) :\n  x + y = y + x.\nProof.\n  induction x.\n  - cbn. rewrite <- plus_n_O. reflexivity.\n  - cbn. rewrite IHx, plus_n_Sm. reflexivity.\nQed.\n\n\n(* Defining commutativity as first-order formula *)\n(* Variant 1: de Bruijn formula *)\n\nFrom Undecidability.FOL Require Import Syntax PA.\nImport FullSyntax.\n\nDefinition add_comm_fol : form :=\n  ∀ ∀ $1 ⊕ $0 == $0 ⊕ $1.\n\n(* Variant 2: HOAS formula *)\n\nFrom Undecidability.FOL Require Import Hoas.\nRequire Import Vector.\nImport VectorNotations.\n\nNotation \"x '⊕' y\" := (bFunc Plus ([x; y])) (at level 39) : hoas_scope.\nNotation \"x '==' y\" := (bAtom Eq ([x; y])) (at level 40) : hoas_scope.\n\nDefinition add_comm_hoas : form :=\n  << ∀' x y, x ⊕ y == y ⊕ x.\n\nPrint add_comm_hoas.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/FOL/Proofmode/Demo1_InputLanguage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7428504158886585}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Poly.\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n    l = rev l' -> l' = rev l.\nProof.\n  intros. rewrite H. rewrite rev_involutive. reflexivity.\nQed.\n\nTheorem trans_eq : forall (X : Type) (n m o : X),\n    n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite eq1, <- eq2. reflexivity.\nQed.\n\nExample trans_eq_example : forall (a b c d e f : nat),\n    [a;b] = [c;d] -> [c;d] = [e;f] -> [a;b] = [e;f].\nProof.\n  intros a b c d e f. apply trans_eq. Qed.\n\nExample trans_eq_exercise : forall (n m o p : nat),\n    m = (minustwo o) ->\n    (n + p) = m ->\n    (n + p) = (minustwo o).\nProof.\n  intros. apply trans_eq with (m := m).\n  - assumption.\n  - assumption.\nQed.\n\nTheorem S_injective : forall n m : nat,\n    S n = S m -> n = m.\nProof.\n  intros n m H. injection H. intros Hnm. apply Hnm.\nQed.\n\nTheorem injection_ex1 : forall (n m o : nat),\n    [n; m] = [o; o] -> [n] = [m].\nProof.\n  intros. injection H. intros. rewrite H0, H1. reflexivity.\nQed.\n\nTheorem injection_ex2 : forall (n m : nat),\n    [n] = [m] -> n = m.\nProof.\n  intros n m H. injection H as Hnm. rewrite Hnm.\n  reflexivity.\nQed.\n\nExample injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = z :: j ->\n    y :: l = x :: j ->\n    x = y.\nProof.\n  intros. injection H0 as Hyx. symmetry. apply Hyx.\nQed.\n\nTheorem eqb_O_l : forall n, 0 =? n = true -> n = 0.\nProof.\n  intros. simpl in H. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - discriminate H.\nQed.\n\nTheorem discriminate_ex1 : forall n : nat,\n    S n = O -> 2 + 2 = 5.\nProof.\n  intros n H. discriminate H.\nQed.\n\nTheorem discrimiante_ex2: forall (n m : nat),\n    false = true -> [n] = [m].\nProof. intros. discriminate H. Qed.\n\nExample discrimiate_ex3 :\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] -> x = z.\nProof. intros. discriminate H. Qed.\n\nTheorem f_equal : forall (A B : Type) (f : A -> B) (x y : A),\n    x = y -> f x = f y.\nProof. intros. rewrite H. reflexivity. Qed.\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n    (S n) =? (S m) = b -> n =? m = b.\nProof. intros. simpl in H. apply H. Qed.\n\nTheorem plus_n_n_injective : forall n m,\n    n + n = m + m -> n = m.\nProof.\n  intro n. induction n as [| n' IHn'].\n  - intros m H. simpl in H.\n    induction m as [| m' IHm'].\n    + reflexivity.\n    + simpl in *. discriminate H.\n  - intros m H. simpl in H.\n    induction m as [| m' IHm'].\n    + simpl in H. discriminate H.\n    + simpl in *. injection H as H'.\n      Search plus. rewrite <- plus_n_Sm in H'.\n      rewrite <- plus_n_Sm in H'.\n      injection H' as H''. apply IHn' in H''.\n      rewrite H''. reflexivity.\nQed.\n\nTheorem double_injective : forall n m,\n    double n = double m -> n = m.\nProof.\n  intros n m. rewrite double_plus, double_plus.\n  apply plus_n_n_injective.\nQed.\n\nTheorem eqb_true : forall n m, n =? m = true -> n = m.\nProof.\n  intro n. induction n.\n  - intros m H. destruct m as [| m'] eqn:E.\n    + reflexivity.\n    + discriminate H.\n  - intros m H. destruct m as [| m'] eqn:E.\n    + discriminate H.\n    + simpl in H. apply IHn in H. rewrite H.\n      reflexivity.\nQed.\n\nTheorem eqb_refl : forall n, n =? n = true.\nProof.\n  intro n. induction n.\n  - reflexivity.\n  - simpl. apply IHn.\nQed.\n\nTheorem double_injective_take2 : forall n m,\n    double n = double m -> n = m.\nProof.\n  intros n m.\n  (* n and m are both in the context *)\n  generalize dependent n.\n  (* Now n is back in the goal and we can do induction on\n     m and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - simpl. intros n eq. destruct n as [| n' ] eqn:E.\n    + reflexivity.\n    + discriminate eq.\n  - simpl. intros n eq. destruct n as [| n' ] eqn:E.\n    + discriminate eq.\n    + simpl in eq. injection eq as eq. apply IHm' in eq.\n      rewrite eq. reflexivity.\nQed.\n\nTheorem eqb_id_true : forall x y,\n    eqb_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intro H.\n  apply eqb_true in H.\n  rewrite H. reflexivity.\nQed.\n\nTheorem nth_error_after_last : forall (n : nat) (X : Type) (l : list X),\n    length l = n -> nth_error l n = None.\nProof.\n  intros n X l. generalize n. induction l.\n  - reflexivity.\n  - intros n0 H. induction n0.\n    + discriminate H.\n    + simpl in H. injection H as H. apply IHl in H.\n      simpl. apply H.\nQed.\n\nDefinition square n := n * n.\n\nLemma plus_mult_l : forall a b c, (a + b) * c = a * c + b * c.\nProof.\n  intros a b c. induction a.\n  - simpl. reflexivity.\n  - simpl. rewrite IHa. rewrite plus_assoc. reflexivity.\nQed.\n\nLemma mult_assoc : forall a b c, a * b * c = a * (b * c).\nProof.\n  intros a b c. induction a.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHa. rewrite plus_mult_l. reflexivity.\nQed.\n\nLemma mult_comm : forall n m, n * m = m * n.\nProof.\n  intros n m. induction n.\n  - simpl. rewrite <- mult_n_O. reflexivity.\n  - simpl. rewrite IHn. rewrite plus_comm. rewrite mult_n_Sm.\n    reflexivity.\nQed.\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m. unfold square. rewrite <- mult_assoc.\n  rewrite <- mult_assoc.\n  assert (H: n * m * n = n * n * m).\n  { rewrite mult_comm. rewrite mult_assoc. reflexivity. }\n  rewrite H. reflexivity.\nQed.\n\nDefinition foo (x : nat) := 5.\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof. intro m. simpl. reflexivity. Qed.\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intro m. destruct m as [| m'] eqn:E.\n  - reflexivity.\n  - simpl. reflexivity.\nQed.\n\nDefinition sillyfun (n : nat) : bool :=\n  if n =? 3 then false\n  else if n =? 5 then false\n  else false.\n\nTheorem sillyfun_false : forall n : nat,\n    sillyfun n = false.\nProof.\n  intro n. unfold sillyfun.\n  destruct (n =? 3) eqn:E1.\n  - reflexivity.\n  - destruct (n =? 5) eqn:E2.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n    split l = (l1, l2) -> combine l1 l2 = l.\nProof.\n  intros X Y l. induction l as [| h t IHt].\n  - intros l1 l2 H. inversion H. reflexivity.\n  - intros l1 l2 H. destruct h as [a b] eqn:E in H. simpl in H.\n    destruct (split t) as [l1' l2'] eqn:Et in H. inversion H.\n    simpl. inversion E.\n    assert (Heq : forall (X : Type) (x : X) (l1 l2 : list X),\n               l1 = l2 -> x :: l1 = x::l2).\n    { intros. rewrite H3. reflexivity. }\n    apply Heq. apply IHt. apply Et.\nQed.\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? 3 then true\n  else if n =? 5 then true\n       else false.\n\nTheorem sillyfun1_odd : forall (n : nat),\n    sillyfun1 n = true -> oddb n = true.\nProof.\n  intros n H.\n  unfold sillyfun1 in H.\n  destruct (n =? 3) eqn:E3 in H.\n  - apply eqb_true in E3. rewrite E3. reflexivity.\n  - destruct (n =? 5) eqn:E5 in H.\n    + apply eqb_true in E5. rewrite E5. reflexivity.\n    + discriminate H.\nQed.\n\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool), f (f (f b)) = f b.\nProof.\n  intros f b. destruct b eqn:Eb.\n  - destruct (f true) eqn:Eft.\n    + rewrite Eft. apply Eft.\n    + destruct (f false) eqn:Eff.\n      * apply Eft.\n      * apply Eff.\n  - destruct (f false) eqn:Eff.\n    + destruct (f true) eqn:Eft.\n      * apply Eft.\n      * apply Eff.\n    + rewrite Eff. apply Eff.\nQed.\n\nTheorem eqb_sym : forall n m : nat, (n =? m) = (m =? n).\nProof.\n  intro n. induction n as [| n' IHn'].\n  - intro m. simpl. destruct m as [| m'] eqn:Em.\n    + reflexivity.\n    + simpl. reflexivity.\n  - intro m. destruct m as [| m'] eqn:Em.\n    + simpl. reflexivity.\n    + simpl. apply IHn'.\nQed.\n\nTheorem eqb_trans : forall n m p,\n    n =? m = true ->\n    m =? p = true ->\n    n =? p = true.\nProof.\n  intro n. induction n as [| n' IHn'].\n  - intro m. induction m as [| m' IHm'].\n    + intro p. intro H1. destruct p as [| p'] eqn:Ep.\n      * reflexivity.\n      * simpl. intro H2. apply H2.\n    + intro p. intro H1. simpl in H1. discriminate H1.\n  - intro m. induction m as [| m' IHm'].\n    + intro p. intro H1. simpl in H1. discriminate H1.\n    + intro p. intro H1. simpl in H1. destruct p as [| p'] eqn:Ep.\n      * intro H2. simpl in H2. discriminate H2.\n      * intro H2. simpl in H2. simpl. apply IHn' with m'.\n        apply H1. apply H2.\nQed.\n\nDefinition split_combine_statement : Prop :=\n  forall X Y (l1 : list X) (l2 : list Y),\n    length l1 = length l2 -> split (combine l1 l2) = (l1, l2).\n\nTheorem split_combine : split_combine_statement.\nProof.\n  unfold split_combine_statement.\n  intros X Y l1. induction l1 as [| h1 l1' IHl1'].\n  - intros l2 H. destruct l2 as [| h2 l2'] eqn:El2.\n    + reflexivity.\n    + simpl in H. discriminate H.\n  - intros l2 H. destruct l2 as [| h2 l2'] eqn:El2.\n    + simpl in H. discriminate H.\n    + simpl in H. injection H as H. apply IHl1' in H.\n      simpl. rewrite H. reflexivity.\nQed.\n\nTheorem filter_exercise :\n  forall (X : Type) (test : X -> bool) (x : X) (l lf : list X),\n    filter test l = x :: lf -> test x = true.\nProof.\n  intros X test x l. induction l as [| h l' IHl'].\n  - intros lf H. simpl in H. discriminate H.\n  - intros lf H. simpl in H. destruct (test h) eqn:E in H.\n    + inversion H. rewrite H1 in E. apply E.\n    + apply IHl' with lf. apply H.\nQed.\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => true\n  | h :: t => if test h then forallb test t else false\n  end.\n\nExample test_forallb_1 : forallb oddb [1;3;5;7;9] = true.\nProof. reflexivity. Qed.\nExample test_forallb_2 : forallb negb [false;false] = true.\nProof. reflexivity. Qed.\nExample test_forallb_3 : forallb evenb [0;2;4;5] = false.\nProof. reflexivity. Qed.\nExample test_forallb_4 : forallb (eqb 5) [] = true.\nProof. reflexivity. Qed.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | [] => false\n  | h :: t => if test h then true else existsb test t\n  end.\n\nExample test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\nExample test_existsb_2 : existsb (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\nExample test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\nExample test_existsb_4 : existsb evenb [] = false.\nProof. reflexivity. Qed.\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=\n  negb (forallb (fun x => negb (test x)) l).\n\nTheorem existsb_existsb' :\n  forall (X : Type) (test : X -> bool) (l : list X),\n    existsb test l = existsb' test l.\nProof.\n  intros. induction l as [| h t IHt].\n  - reflexivity.\n  - simpl. destruct (test h) eqn:E.\n    + unfold existsb'. simpl. rewrite E.\n      simpl. reflexivity.\n    + unfold existsb'. simpl. rewrite E.\n      simpl. fold (existsb' test t). apply IHt.\nQed.", "meta": {"author": "kailiangji", "repo": "software-foundation-exercise", "sha": "1538f43bcf240d3f9f2502aa4164cecf821da61b", "save_path": "github-repos/coq/kailiangji-software-foundation-exercise", "path": "github-repos/coq/kailiangji-software-foundation-exercise/software-foundation-exercise-1538f43bcf240d3f9f2502aa4164cecf821da61b/logic_foundation/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8824278540866547, "lm_q1q2_score": 0.742850406422849}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf3 : natural) : natural :=\n  plus lf2 (plus Zero lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj82_coqofml_AxhULS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7428233113417974}}
{"text": "\nSection NetKAT.\n  Variable (Fields: Type).\n  Variable (Vals: Type).\n\n  Inductive test := \n  | t_unit | t_fail (* 1 and 0 *)\n  | t_check : Fields -> Vals -> test (* f = v *)\n  | t_or : test -> test -> test (* l + r *)\n  | t_and : test -> test -> test (* l . r *)\n  | t_neg : test -> test. (* ! t *)\n\n  Inductive kat := \n  | k_test : test -> kat\n  | k_put : Fields -> Vals -> kat (* f <- v *)\n  | k_or : kat -> kat -> kat (* l + r *)\n  | k_and : kat -> kat -> kat (* l . r *)\n  | k_star : kat -> kat  (* x^* *)\n  | k_dup : kat.\n\n  (* non-empty lists *)\n  Inductive ne_list (V: Type) : Type := \n  | ne_nil : V -> ne_list V (* p :: <> *)\n  | ne_cons : V -> ne_list V -> ne_list V. (* p :: h *)\n\n  Arguments ne_nil {_}.\n  Arguments ne_cons {_}.\n\n  Fixpoint ne_app {V} (l r: ne_list V) := \n    match l with \n    | ne_nil x => ne_cons x r\n    | ne_cons x l => \n      ne_cons x (ne_app l r)\n    end.\n\n  (* packets are maps from fields to values *)\n  Definition pkt := Fields -> Vals.\n  Definition history := ne_list pkt.\n\n  (* An interpretation relates tests/kats with input/output histories.\n     Notice that the original paper maps to a powerset; the intuition here is that interp_test t pre post is true for all possible histories post in the powerset of the paper's interp definition.\n  *)\n  (* #[ bypass_check(positivity=yes) ] *)\n  Fixpoint interp_test (t: test) (h: history) := \n    match t with \n    | t_unit => True\n    | t_fail => False\n    | t_check f v => (* syntax for pkt . f = v *)\n      match h with \n      | ne_nil p => \n        p f = v  (* semantics for pkt . f = v when the history is pkt :: <> *)\n      | ne_cons p _ => \n        p f = v  (* semantics for pkt . f = v when the history is pkt :: h' *)\n      end\n    | t_or t_l t_r => \n      interp_test t_l h \\/ interp_test t_r h\n    | t_and t_l t_r => \n      interp_test t_l h /\\ interp_test t_r h\n    | t_neg t => \n      ~ interp_test t h\n    end.\n  \n\n  (* Two tests are equivalent (i.e. KAT equal) if they have identical behavior on histories *)\n  Definition equiv_test (l r : test) : Prop := \n    forall h, \n      interp_test l h <-> interp_test r h.\n\n  Lemma ba_seq_idem : \n    forall x, \n      equiv_test (t_and x x) x.\n  Proof.\n    unfold equiv_test.\n    intros.\n    split; intros.\n    - simpl in H.\n      intuition.\n    - simpl.\n      intuition.\n  Qed.\n\n  Require Import Coq.Classes.EquivDec.\n\n  Context `{FEqDec: EquivDec.EqDec Fields eq}.\n\n  Definition pkt_put (p: pkt) f v := fun f' => \n    if f' == f then v else p f'.\n\n  Inductive interp_kat : kat -> history -> history -> Prop := \n  | interp_k_test : \n    forall t h, \n      interp_test t h -> \n      interp_kat (k_test t) h h\n  | interp_put_nil : \n    forall p f v, \n      interp_kat (k_put f v) (ne_nil p) (ne_nil (pkt_put p f v))\n  | interp_put_cons : \n    forall p h f v, \n      interp_kat (k_put f v) (ne_cons p h) (ne_cons (pkt_put p f v) h)\n  | interp_k_or : \n    forall k_l k_r pre post,\n      interp_kat k_l pre post \\/ interp_kat k_r pre post ->\n      interp_kat (k_or k_l k_r) pre post\n  | interp_k_and : \n    forall k_l k_r pre post post',\n      interp_kat k_l pre post /\\ interp_kat k_r post post' -> \n      interp_kat (k_and k_l k_r) pre post'\n  | interp_star_one : \n    forall k pre post,\n      interp_kat k pre post -> \n      interp_kat (k_star k) pre post\n  | interp_star_many : \n    forall k pre post post',\n      interp_kat k pre post -> \n      interp_kat (k_star k) post post' -> \n      interp_kat (k_star k) pre post'\n  | interp_dup_nil : \n    forall p, interp_kat k_dup (ne_nil p) (ne_cons p (ne_nil p))\n  | interp_dup_cons : \n    forall p h, interp_kat k_dup (ne_cons p h) (ne_cons p (ne_cons p h)).\n\n  Definition equiv_kat l r :=\n    forall pre post, \n      interp_kat l pre post <-> interp_kat r pre post.\n\n  Require Import Coq.Logic.FunctionalExtensionality.\n\n  Lemma put_pkt_iota : \n    forall p f,\n      pkt_put p f (p f) = p.\n  Proof.\n    intros.\n    extensionality x.\n    unfold pkt_put.\n    destruct (_ == _) eqn:?.\n    - inversion e;\n      subst.\n      trivial.\n    - trivial.\n  Qed.\n\n  Lemma check_put : \n    forall f v h,\n      interp_test (t_check f v) h -> \n      interp_kat (k_put f v) h h.\n  Proof.\n    intros.\n    simpl in H.\n    destruct h;\n    subst.\n    - assert (p = pkt_put p f (p f)) by now erewrite put_pkt_iota.\n      erewrite H at 3.\n      econstructor.\n    - assert (p = pkt_put p f (p f)) by now erewrite put_pkt_iota.\n      erewrite H at 3.\n      econstructor.\n  Qed.\n\n  Lemma put_inj:\n    forall f v pre post post', \n      interp_kat (k_put f v) pre post -> \n      interp_kat (k_put f v) pre post' -> \n      post = post'.\n  Proof.\n    destruct pre;\n    intros;\n    inversion H; subst;\n    inversion H0; subst;\n    trivial.\n  Qed.\n\n  Lemma pa_filter_mod : \n    forall f v,\n      equiv_kat \n        (k_and (k_test (t_check f v)) (k_put f v)) \n        (k_test (t_check f v)).\n  Proof.\n    unfold equiv_kat.\n    intros;\n    split;\n    intros.\n    - inversion H; subst;\n      clear H.\n      destruct H4.\n      inversion H; subst.\n      pose proof (check_put _ _ _ H2).\n      assert (post = post0) by (eapply put_inj; eauto).\n      subst.\n      econstructor.\n      trivial.\n    - inversion H; subst.\n      clear H.\n      econstructor.\n      split; try econstructor;\n      try eapply check_put;\n      trivial.\n  Qed.\nEnd NetKAT.\n\nArguments t_unit {_ _}.\nArguments t_fail {_ _}.\nArguments t_check {_ _}.\nArguments t_or {_ _}.\nArguments t_and {_ _}.\nArguments t_neg {_ _}.\n\nArguments k_test {_ _}.\nArguments k_put {_ _}.\nArguments k_or {_ _}.\nArguments k_and {_ _}.\nArguments k_star {_ _}.\nArguments k_dup {_ _}.", "meta": {"author": "jsarracino", "repo": "mech-kat", "sha": "5392943c1da22690bd7fc43ae03cec1759cbb8cd", "save_path": "github-repos/coq/jsarracino-mech-kat", "path": "github-repos/coq/jsarracino-mech-kat/mech-kat-5392943c1da22690bd7fc43ae03cec1759cbb8cd/theories/NetKAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7428233051273742}}
{"text": "Require Import Coq.Logic.Classical_Prop.\nRequire Import Coq.Logic.Classical_Pred_Type.\nRequire Import Coq.Logic.ClassicalUniqueChoice.\n\nRequire Import Types.\n\n\nModule Type MapCtxMonoid  \n  ( KM : Types.ModuleType ) \n  ( VM : Types.ModuleType ).\n\n  Definition K : Type := KM.T.\n  Definition V : Type := VM.T.\n\n  Definition T : Type := K -> V -> Prop.\n\n  Definition contains (A : T) (k : K) (v : V) : Prop := A k v.\n\n  Definition subseteq (A B : T) : Prop := \n    forall (k : K) (v : V), contains A k v -> contains B k v.\n\n  (* Equivalence, Equality, and Extionsionality *)\n  Definition eq (A B : T) : Prop := subseteq A B /\\ subseteq B A.\n  \n  Lemma eq_refl : forall A : T, eq A A.\n  Proof.\n    intros. unfold eq. assert (H : subseteq A A).\n    { unfold subseteq. intros. apply H. } split; apply H.\n  Qed.\n\n  Axiom extensionality : forall (A B : T), eq A B -> A = B.\n\n  Lemma extensionality_converse : forall (A B : T), A = B -> eq A B.\n  Proof.\n    intros. rewrite <- H. apply eq_refl.\n  Qed.\n\n  Lemma extensionality_inverse : forall (A B : T), ~ eq A B -> A <> B.\n  Proof.\n    intros. unfold not. intros Hf. apply extensionality_converse in Hf.\n    apply H in Hf. apply Hf.\n  Qed.\n\n  Lemma extensionality_contraposition : forall (A B : T), A <> B -> ~ eq A B.\n  Proof.\n    intros. unfold not. intros Hf. apply extensionality in Hf.\n    unfold not in H. apply H in Hf. apply Hf.\n  Qed.\n\n  (* Empty, Singleton, Union *)\n  Inductive empty : T := .\n\n  Inductive singleton (k : K) (v : V) : T :=\n    singleton_contains : contains (singleton k v) k v.\n\n  Inductive union (B C : T) : T :=\n  | union_l : forall (k : K) (v : V), contains B k v -> contains (union B C) k v\n  | union_r : forall (k : K) (v : V), contains C k v -> contains (union B C) k v.\n\n  (* Commutativity *)\n  Lemma commut : forall (B C : T), union B C = union C B.\n  Proof.\n    intros B C. apply extensionality. unfold eq. split.\n    - unfold subseteq. intros. inversion H.\n      + apply union_r. apply H0.\n      + apply union_l. apply H0.\n    - unfold subseteq. intros. inversion H.\n      + apply union_r. apply H0.\n      + apply union_l. apply H0.\n  Qed.\n\n  (* Notations *)\n  Notation \"s1 'o' s2\" := (union s1 s2) (at level 20, left associativity).\n  Notation \"'Ø'\" := (empty).\n\n  (* Empty Union *)\n  Lemma empty_union : forall A B : T, A o B = Ø -> A = Ø /\\ B = Ø.\n  Proof.\n    intros. apply extensionality_converse in H. inversion H as [Hl Hr].\n    unfold subseteq in Hl. split.\n    - apply extensionality. unfold eq. split.\n      + unfold subseteq. intros. apply Hl. apply union_l. apply H0.\n      + unfold subseteq. intros. inversion H0.\n    - apply extensionality. unfold eq. split.\n      + unfold subseteq. intros. apply Hl. apply union_r. apply H0.\n      + unfold subseteq. intros. inversion H0.\n  Qed.\n\n  (* Associativity of Union *)\n  Lemma assoc : forall A B C : T, (A o B) o C = A o (B o C).\n  Proof.\n    intros. apply extensionality. unfold eq. split; unfold subseteq.\n    - intros. inversion H.\n      + inversion H0.\n        * apply union_l. apply H3.\n        * apply union_r. apply union_l. apply H3.\n      + apply union_r. apply union_r. apply H0.\n    - intros. inversion H.\n      + apply union_l. apply union_l. apply H0.\n      + inversion H0.\n        * apply union_l. apply union_r. apply H3.\n        * apply union_r. apply H3.\n  Qed.\n\n  (* Exchange *)\n  Lemma exchange : forall A B C D, A o B o C o D = A o C o B o D.\n  Proof.\n    intros.\n    assert (H : B o C = C o B). { apply commut. }\n    assert (H' : B o (C o D) = C o (B o D)). \n      { repeat rewrite <- assoc. rewrite -> H. reflexivity. }\n    repeat rewrite -> assoc. rewrite -> H'. reflexivity.\n  Qed.\n\n  (* Identity Element of Union *)\n  Lemma id_l : forall A : T, Ø o A = A.\n  Proof.\n    intros. apply extensionality. unfold eq. split; unfold subseteq.\n    - intros. inversion H.\n      + inversion H0.\n      + apply H0.\n    - intros. apply union_r. apply H.\n  Qed.\n\n  Lemma id_r : forall A : T, A o Ø = A.\n  Proof.\n    intros. apply extensionality. unfold eq. split; unfold subseteq.\n    - intros. inversion H.\n      + apply H0.\n      + inversion H0.\n    - intros. apply union_l. apply H.\n  Qed.\n\n  (* Append *)\n  Definition append (A : T) (k : K) (v : V) : T := union A (singleton k v).\n\n  Lemma singleton_empty : forall (k : K) (v : V), singleton k v = append Ø k v.\n  Proof.\n    intros. apply extensionality. unfold eq. split; unfold subseteq.\n    - intros k' v' H. inversion H. subst k' v'. apply union_r. apply H.\n    - intros k' v' H. inversion H as [k'' v'' H' | k'' v'' H'].\n      + inversion H'.\n      + apply H'.\n  Qed.\n\n  (* Set Minus *)\n  Inductive setminus (B C : T) : T :=\n    contains_setminus : forall (k : K) (v : V),\n      contains B k v /\\ ~ contains C k v -> contains (setminus B C) k v.\n\n  (* Remove *)\n  Definition subtract (B : T) (k : K) (v : V) : T := setminus B (singleton k v).\n\n  Lemma append_subtract : forall (B : T) (k : K) (v : V),\n    contains B k v -> append (subtract B k v) k v = B.\n  Proof.\n    intros. apply extensionality. unfold eq. split; unfold subseteq.\n    - intros k' v' H'. inversion H'.\n      + inversion H0. apply H3.\n      + inversion H0. subst k0 v0 k' v'. apply H.\n    - intros k' v' H'. unfold append. unfold subtract.\n      assert (H'' : (k = k' /\\ v = v') \\/ ~ (k = k' /\\ v = v')).\n      { apply classic. } inversion H'' as [H''l | H''r].\n      + inversion H''l as [Hk Hv]. subst k' v'.\n        apply union_r. apply singleton_contains.\n      + apply union_l. apply contains_setminus. split; try apply H'.\n        unfold not. intros Hf. inversion Hf. subst k' v'. unfold not in H''r.\n        assert (Ht : k = k /\\ v = v). { split; reflexivity. }\n        apply H''r in Ht. apply Ht.\n  Qed.\n\n  Lemma decide_contains_subtract : forall (B : T) (k : K) (v : V),\n    contains B k v -> exists A, append A k v = B /\\ A = subtract B k v.\n  Proof.\n    intros. exists (subtract B k v). split; try reflexivity.\n    apply append_subtract. apply H.\n  Qed.\n\n  Lemma decide_append : forall (B : T), \n    B <> Ø -> \n    exists (A : T) (k : K) (v : V), B = append A k v.\n  Proof.\n    intros. apply extensionality_contraposition in H. unfold eq in H.\n    apply not_and_or in H. inversion H as [Hl | Hr].\n    - unfold subseteq in Hl. apply not_all_ex_not in Hl.\n      inversion Hl as [k Hl']. apply not_all_ex_not in Hl'.\n      inversion Hl' as [v Hl'']. apply imply_to_and in Hl''.\n      inversion Hl'' as [H' H'']. apply decide_contains_subtract in H'.\n      inversion H' as [A HA]. inversion HA as [HAl HAr].\n      exists A. exists k. exists v. rewrite -> HAl. reflexivity.\n    - unfold subseteq in Hr. apply not_all_ex_not in Hr.\n      inversion Hr as [k Hr']. apply not_all_ex_not in Hr'.\n      inversion Hr' as [v Hr'']. apply not_imply_elim in Hr''.\n      inversion Hr''.\n  Qed.\n\n  (* Contains Key *)\n  Inductive contains_key : T -> K -> Prop :=\n    contains_key_contains : forall (A : T) (k : K) (v : V),\n      contains A k v -> contains_key A k.\n\n  (* Duplicate Keys *)\n  Inductive duplicated : T -> Prop :=\n    duplicate_keys : forall (A : T) (k : K) (v v' : V),\n      contains A k v -> contains A k v' -> v <> v' -> duplicated A.\n\n  Definition well_defined (A : T) : Prop := ~ duplicated A.\n\n  Lemma contains_unique : forall (A : T) (k : K),\n    well_defined A -> contains_key A k -> (exists! (v : V), contains A k v).\n  Proof.\n    intros A k H H'. inversion H'. subst A0 k0. exists v. unfold unique. split.\n    - apply H0.\n    - intros v'. unfold well_defined in H. unfold not in H. intros.\n      (* reductio ad absurdum *)\n      assert (Hx : v = v' \\/ v <> v'). { apply classic. }\n      inversion Hx; try apply H2. assert (Hf : duplicated A). \n      { eapply duplicate_keys. apply H0. apply H1. apply H2. }\n      apply H in Hf. inversion Hf.\n  Qed.\n\n  (* Pair Uniqueness *)\n  Lemma unique_append : forall (A : T) (k : K) (v : V), \n    contains A k v -> append A k v = A.\n  Proof.\n    intros. apply extensionality. unfold eq. split; unfold subseteq; intros k' v'.\n    - intros H'. unfold append in H'. inversion H'.\n      + subst k0 v0. apply H0.\n      + subst k0 v0. inversion H0. subst k' v'. apply H.\n    - intros H'. unfold append. apply union_l. apply H'.\n  Qed.\n\n  (* Alloc *)\n  \n\n\n\n", "meta": {"author": "aerabi", "repo": "llc", "sha": "66193df6fbc0aee0b1111720399ab6efc60d2ac5", "save_path": "github-repos/coq/aerabi-llc", "path": "github-repos/coq/aerabi-llc/llc-66193df6fbc0aee0b1111720399ab6efc60d2ac5/Legacy/MapCtx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.742823303318858}}
{"text": "Require Import Reals.\nRequire Import Interval.Tactic.\n\nOpen Scope R_scope.\n\nGoal\n  forall x, -1 <= x <= 1 ->\n  sqrt (1 - x) <= 3/2.\nProof.\n  intros.\n  interval.\nQed.\n\nGoal\n  forall x, -1 <= x <= 1 ->\n  sqrt (1 - x) <= 141422/100000.\nProof.\n  intros.\n  interval.\nQed.\n\nGoal\n  forall x, -1 <= x <= 1 ->\n  sqrt (1 - x) <= 141422/100000.\nProof.\n  intros.\n  interval_intro (sqrt (1 - x)) upper as H'.\n  apply Rle_trans with (1 := H').\n  interval.\nQed.\n\nGoal\n  forall x, 3/2 <= x <= 2 ->\n  forall y, 1 <= y <= 33/32 ->\n  Rabs (sqrt(1 + x/sqrt(x+y)) - 144/1000*x - 118/100) <= 71/32768.\nProof.\n  intros.\n  interval with (i_prec 19, i_bisect x).\nQed.\n\nGoal\n  forall x, 1/2 <= x <= 2 ->\n  Rabs (sqrt x - (((((122 / 7397 * x + (-1733) / 13547) * x\n                   + 529 / 1274) * x + (-767) / 999) * x\n                   + 407 / 334) * x + 227 / 925))\n    <= 5/65536.\nProof.\n  intros.\n  interval with (i_bisect x, i_taylor x, i_degree 3).\nQed.\n\nGoal\n  forall x, -1 <= x ->\n  x < 1 + powerRZ x 3.\nProof.\n  intros.\n  apply Rminus_lt.\n  interval with (i_bisect x, i_autodiff x).\nQed.\n\nRequire Import Coquelicot.Coquelicot.\n\nGoal\n  Rabs (RInt (fun x => atan (sqrt (x*x + 2)) / (sqrt (x*x + 2) * (x*x + 1))) 0 1\n        - 5/96*PI*PI) <= 1/1000.\nProof.\n  integral with (i_fuel 2, i_degree 5).\nQed.\n\nGoal\n  RInt_gen (fun x => 1 * (powerRZ x 3 * ln x^2))\n           (at_right 0) (at_point 1) = 1/32.\nProof.\n  refine ((fun H => Rle_antisym _ _ (proj2 H) (proj1 H)) _).\n  integral.\nQed.\n\n(*\nGoal\n  Rabs (RInt_gen (fun t => 1/sqrt t * exp (-(1*t)))\n                 (at_point 1) (Rbar_locally p_infty)\n        - 2788/10000) <= 1/1000.\nProof.\n  interval.\nQed.\n*)\n", "meta": {"author": "validsdp", "repo": "coq-interval", "sha": "4035680e718ae256601e00454279f1770e5c15e8", "save_path": "github-repos/coq/validsdp-coq-interval", "path": "github-repos/coq/validsdp-coq-interval/coq-interval-4035680e718ae256601e00454279f1770e5c15e8/testsuite/example-20071016.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7428233030821956}}
{"text": "Require Import Category.\nRequire Import Monoid.\n\n(* given a monoid m, we define the data necessary to create a category *)\n\n\n(* the source of any arrow is the identity of the monoid *)\n\nDefinition source_  (A:Type) (m:Monoid A) (x:A) : A := identity m.\n\nArguments source_ {A} _ _. (* type argument is inferred *)\n\n\n\n(* the target of any arrow is the identity of the monoid *) \n\nDefinition target_  (A:Type) (m:Monoid A) (x:A) : A := identity m.\n\nArguments target_ {A} _ _. (* type argument is inferred *)\n\n\n\n(* composition of arrows coincides with the monoid product *)\n\nDefinition compose_ (A:Type) (m:Monoid A) (x y: A) : option A := \n    Some (product m x y).\n\nArguments compose_ {A} _ _ _. (* type argument is inferred *)\n\n\n\n(* source of source is source *)\n\nDefinition proof_ss_ (A:Type) (m:Monoid A) : forall f:A, \n    source_ m (source_ m f) = source_ m f.\nProof. reflexivity. Qed.\n\n\n(* target of source is source *)\n\nDefinition proof_ts_ (A:Type) (m:Monoid A) : forall f:A,\n    target_ m (source_ m f) = source_ m f.\nProof. reflexivity. Qed.\n\n\n\n(* target of target is target *)\n\nDefinition proof_tt_ (A:Type) (m:Monoid A) : forall f:A,\n    target_ m (target_ m f) = target_ m f.\nProof. reflexivity. Qed.\n\n\n\n(* source of target is target *)\n\nDefinition proof_st_ (A:Type) (m:Monoid A) : forall f:A,\n    source_ m (target_ m f) = target_ m f.\nProof. reflexivity. Qed.\n\n\n\n(* composition is defined iff target and source line up *) \n\nDefinition proof_dom_ (A:Type) (m:Monoid A) : forall f g:A,\n    target_ m f = source_ m g <-> compose_ m f g <> None.\nProof.\n    intros f g. split.\n    - intros. discriminate. \n    - intros. reflexivity.\nQed.\n\n\n\n(* the source of composed arrow is source of first argument *)\n\nDefinition proof_src_ (A:Type) (m:Monoid A) : forall f g h: A,\n    compose_ m f g = Some h -> source_ m h = source_ m f.\nProof. intros f g h H. clear H. reflexivity. Qed.\n\n\n\n(* the target of composed arrow is target of second argument *)\n\nDefinition proof_tgt_ (A:Type) (m:Monoid A) : forall f g h: A,\n    compose_ m f g = Some h -> target_ m h = target_ m g.\nProof. intros f g h H. clear H. reflexivity. Qed.\n\n\n\n(* composing from the left with an object (= identity arrow) has no effect *) \n\nDefinition proof_idl_ (A:Type) (m:Monoid A) : forall a f: A,\n    a = source_ m f -> compose_ m a f = Some f.\nProof.\n    intros a f H.\n    unfold compose_. unfold source_ in H. rewrite H.\n    rewrite (proof_idl m). reflexivity.\nQed.\n\n\n\n(* composing from the right with an object (= identity arrow) has no effect *)\n\nDefinition proof_idr_ (A:Type) (m:Monoid A) : forall a f: A,\n    a = target_ m f -> compose_ m f a = Some f.\nProof.\n    intros a f H.\n    unfold compose_. unfold source_ in H. rewrite H.\n    rewrite (proof_idr m). reflexivity.\nQed.\n\n\n\n(* composition is associative *)\n\nDefinition proof_asc_ (A:Type) (m:Monoid A) : forall f g h fg gh: A,\n    compose_ m f g = Some fg ->\n    compose_ m g h = Some gh ->\n    compose_ m f gh = compose_ m fg h. \nProof.\n    intros f g h fg gh H H'. unfold compose_ in H. unfold compose_ in H'.\n    injection H. clear H. intro H.\n    injection H'. clear H'. intro H'.\n    rewrite <- H. rewrite <- H'. unfold compose_. \n    rewrite (proof_asc m). reflexivity.\nQed.\n\n\n(* A monoid with support A, can be turned into a category with support A *)\n\nDefinition toCategory (A:Type) (m:Monoid A) : Category A := category\n    (source_      m)\n    (target_      m)\n    (compose_     m)\n    (proof_ss_  A m)\n    (proof_ts_  A m)\n    (proof_tt_  A m)\n    (proof_st_  A m)\n    (proof_dom_ A m)\n    (proof_src_ A m)\n    (proof_tgt_ A m)\n    (proof_idl_ A m)\n    (proof_idr_ A m)\n    (proof_asc_ A m).\n\nArguments toCategory {A} _.\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/cat/MonoidAsCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7428233030033078}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Yannick Forster            [+]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [+] Affiliation Saarland Univ. *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* ** Two infinite sequences of primes *)\n\nRequire Import List Arith Lia Bool Permutation.\n\nFrom Undecidability.Shared.Libs.DLW \n  Require Import utils utils_tac utils_list utils_nat gcd rel_iter prime pos vec.\n\nSet Implicit Arguments.\n\nLocal Notation \"e #> x\" := (vec_pos e x).\nLocal Notation \"e [ v / x ]\" := (vec_change e x v).\n\nSet Implicit Arguments.\n\n(* Unique decomposition with a prime *)\n\nLemma prime_neq_0 p : prime p -> p <> 0.\nProof.\n  intros ? % prime_ge_2; lia.\nQed.\n\n#[export] Hint Resolve prime_neq_0 : core.\n\nLemma power_factor_lt_neq p i j x y : \n         p <> 0 \n      -> i < j \n      -> ~ divides p x \n      -> p^i * x <> p^j * y.\nProof.\n  intros H1 H2 H3 H5.\n  replace j with (i+S (j-i-1)) in H5 by lia.\n  rewrite Nat.pow_add_r, <- Nat.mul_assoc in H5.\n  rewrite Nat.mul_cancel_l in H5.\n  2: apply Nat.pow_nonzero; auto.\n  apply H3; subst x; simpl. \n  do 2 apply divides_mult_r; apply divides_refl.\nQed.\n\nLemma power_factor_uniq p i j x y : \n         p <> 0  \n      -> ~ divides p x\n      -> ~ divides p y \n      -> p^i * x = p^j * y\n      -> i = j /\\ x = y.\nProof.\n  intros H1 H2 H3 H4.\n  destruct (lt_eq_lt_dec i j) as [ [ H | H ] | H ].\n  + exfalso; revert H4; apply power_factor_lt_neq; auto.\n  + split; auto; subst j.\n    rewrite Nat.mul_cancel_l in H4; auto.\n    apply Nat.pow_nonzero; auto.\n  + exfalso; symmetry in H4; revert H4; apply power_factor_lt_neq; auto.\nQed.\n\n(* The unboundedness of primes *)\n\nLemma prime_above m : { p | m < p /\\ prime p }.\nProof.\n  destruct (prime_factor (n := fact m + 1)) as (p & ? & ?).\n  - pose proof (lt_O_fact m); lia.\n  - exists p; eauto. destruct (Nat.lt_ge_cases m p); eauto.\n    eapply divides_plus_inv in H0.\n    + eapply divides_1_inv in H0; subst. destruct H; lia.\n    + eapply divides_fact. eapply prime_ge_2 in H; eauto.\nQed.\n\nLemma prime_dec p : { prime p } + { ~ prime p }.\nProof.\n  destruct (le_lt_dec 2 p) as [ H | H ].\n  + destruct (prime_or_div H) as [ (q & H1 & H2) | ? ]; auto.\n    right; intros C; apply C in H2; lia.\n  + right; intros (H1 & H2).\n    destruct (H2 2); try lia.\n    exists 0; simpl; lia.\nQed.\n\nLemma first_prime_above m : { p | m < p /\\ prime p /\\ forall q, m < q -> prime q -> p <= q }.\nProof.\n  destruct min_dec with (P := fun p => m < p /\\ prime p)\n    as (p & H1 & H2).\n  + intros n.\n    destruct (lt_dec m n); destruct (prime_dec n); tauto.\n  + destruct (prime_above m) as (p & ?); exists p; auto.\n  + exists p; firstorder.\nQed.\n\nLemma prime_divides p q :\n  prime p -> prime q -> divides p q -> p = q.\nProof.\n  now intros Hp Hq [ [] % Hp | ] % Hq.\nQed.\n\nDefinition nxtprime n := proj1_sig (first_prime_above n).\n\nFact nxtprime_spec1 n : n < nxtprime n.\nProof. apply (proj2_sig (first_prime_above n)). Qed.\n\nFact nxtprime_spec2 n : prime (nxtprime n).\nProof. apply (proj2_sig (first_prime_above n)). Qed.\n\n#[export] Hint Resolve nxtprime_spec1 nxtprime_spec2 prime_2 : core.\n\nFixpoint notprime_bool_rec n k :=\n  match k with\n    | 0   => true\n    | S k' => negb (prime_bool n) && notprime_bool_rec (S n) k'\n  end.\n\nTheorem prime_bool_spec' p : prime_bool p = false <-> ~ prime p.\nProof.\n  rewrite <- not_true_iff_false, prime_bool_spec; tauto.\nQed.\n\nFact notprime_bool_rec_spec n k : notprime_bool_rec n k = true <-> forall i, n <= i < k+n -> ~ prime i.\nProof.\n  revert n; induction k as [ | k IHk ]; intros n; simpl.\n  + split; auto; intros; lia.\n  + rewrite andb_true_iff, negb_true_iff, \n            <- not_true_iff_false, prime_bool_spec, IHk.\n    split.\n    * intros (H1 & H2) i Hi.\n      destruct (eq_nat_dec n i); subst; auto.\n      apply H2; lia.\n    * intros H; split; intros; apply H; lia.\nQed.\n\nDefinition nxtprime_bool n p := Nat.leb (S n) p && notprime_bool_rec (S n) (p - S n) && prime_bool p.\n\nFact nxtprime_bool_spec n p : nxtprime_bool n p = true <-> nxtprime n = p.\nProof.\n  unfold nxtprime_bool.\n  rewrite !andb_true_iff, Nat.leb_le, notprime_bool_rec_spec, prime_bool_spec.\n  unfold nxtprime.\n  destruct (first_prime_above n) as (q & G1 & G2 & G3); simpl.\n  split.\n  + intros ((H1 & H2) & H3).\n    apply Nat.le_antisymm.\n    * apply G3; auto.\n    * apply Nat.nlt_ge. \n      intro; apply (H2 q); auto; lia.\n  + intros ->; lsplit 2; auto.\n    intros q Hq C; apply G3 in C; lia.\nQed.\n\nDefinition nthprime (n : nat) := iter nxtprime 2 n.\n\nLemma nthprime_prime n : prime (nthprime n).\nProof. unfold nthprime; destruct n; simpl; auto; rewrite iter_swap; auto. Qed. \n\n#[export] Hint Resolve nthprime_prime : core.\n\nLemma nthprime_ge n m : n < m -> nthprime n < nthprime m.\nProof.\n  unfold nthprime.\n  induction 1; simpl iter; rewrite iter_swap; auto.\n  apply Nat.lt_trans with (2 := nxtprime_spec1 _); auto.  \nQed.\n\nLemma nthprime_inj n m : nthprime n = nthprime m -> n = m.\nProof.\n  destruct (lt_eq_lt_dec n m) as [ [ H | ] | H ]; auto; \n    intros; eapply nthprime_ge in H; lia.\nQed.\n\nFact nthprime_nxt i p q : nthprime i = p -> nxtprime p = q -> nthprime (S i) = q.\nProof.\n  replace (S i) with (i+1) by lia.\n  unfold nthprime at 2.\n  rewrite iter_plus; fold (nthprime i).\n  intros -> ?; simpl; auto.\nQed.\n\n(* Certified Erastosthene sieve would be helpfull here *)\n\nFact nthprime_0 : nthprime 0 = 2.\nProof. auto. Qed.\n\nLocal Ltac nth_prime_tac H := \n  apply nthprime_nxt with (1 := H);\n  apply nxtprime_bool_spec; auto.\n\nFact nthprime_1 : nthprime 1 = 3.    Proof. nth_prime_tac nthprime_0. Qed.\nFact nthprime_2 : nthprime 2 = 5.    Proof. nth_prime_tac nthprime_1. Qed.\nFact nthprime_3 : nthprime 3 = 7.    Proof. nth_prime_tac nthprime_2. Qed.\nFact nthprime_4 : nthprime 4 = 11.   Proof. nth_prime_tac nthprime_3. Qed.\nFact nthprime_5 : nthprime 5 = 13.   Proof. nth_prime_tac nthprime_4. Qed.\nFact nthprime_6 : nthprime 6 = 17.   Proof. nth_prime_tac nthprime_5. Qed.\n\nRecord primestream :=\n  {\n    str :> nat -> nat;\n    str_inj : forall n m, str n = str m -> n = m;\n    str_prime : forall n, prime (str n);\n  }.\n\n#[export] Hint Immediate str_prime : core.\n#[export] Hint Resolve str_inj : core.\n\nLemma primestream_divides (ps : primestream) n m :  divides (ps n) (ps m) -> n = m.\nProof.\n  destruct ps as [ str H1 H2 ]; simpl.\n  intros ? % prime_divides; eauto.\nQed.\n\nDefinition ps : primestream.\nProof.\n  exists (fun n => nthprime (2 * n)); auto.\n  intros; apply nthprime_inj in H; lia.\nDefined.\n\nFact ps_1 : ps 1 = 5.\nProof. simpl; apply nthprime_2. Qed.\n\nDefinition qs : primestream.\nProof.\n  exists (fun n => nthprime (1 + 2 * n)); auto.\n  intros; apply nthprime_inj in H; lia.\nDefined.\n\nFact qs_1 : qs 1 = 7.\nProof. simpl; apply nthprime_3. Qed.\n\nLemma ps_qs : forall n m, ps n = qs m -> False.\nProof. intros ? ? ? % nthprime_inj; lia. Qed. \n\n#[export] Hint Resolve ps_qs : core.\n\nLemma ps_qs_div n m : ~ divides (ps n) (qs m).\nProof. intros ? % prime_divides; eauto. Qed.\n\nLemma qs_ps_div n m : ~ divides (qs n) (ps m).\nProof. intros ? % prime_divides; eauto. Qed.\n\nFixpoint exp {n} (i : nat) (v : vec nat n) : nat :=\n  match v with\n    | vec_nil => 1\n    | x##v    => qs i ^ x * exp (S i) v\n  end.\n\nFact exp_nil i : exp i vec_nil = 1.\nProof. auto. Qed.\n\nFact exp_cons n i x v : @exp (S n) i (x##v) = qs i^x*exp (S i) v.\nProof. auto. Qed.\n\nFact exp_zero n i : @exp n i vec_zero = 1.\nProof.\n  revert i; induction n as [ | n IHn ]; intros i; simpl; auto.\n  rewrite IHn; ring.\nQed.\n\nFact exp_app n m i v w : @exp (n+m) i (vec_app v w) = exp i v * exp (n+i) w.\nProof.\n  revert i; induction v as [ | x n v IHv ]; intros i.\n  + rewrite vec_app_nil, exp_zero; simpl; ring.\n  + rewrite vec_app_cons, exp_cons.\n    simpl plus; rewrite exp_cons, IHv.\n    replace (n+S i) with (S (n+i)) by lia; ring.\nQed.\n\nLocal Notation divides_mult_inv := prime_div_mult.\n\nLemma not_prime_1 : ~ prime 1.\nProof. intros [ [] ]; auto. Qed.\n\nLemma not_ps_1 n : ~ ps n = 1.\nProof.\n  intros H; generalize (str_prime ps n).\n  rewrite H; apply not_prime_1.\nQed. \n\nLemma not_qs_1 n : ~ qs n = 1.\nProof.\n  intros H; generalize (str_prime qs n).\n  rewrite H; apply not_prime_1.\nQed. \n\n#[export] Hint Resolve not_prime_1 not_qs_1 : core.\n\nLemma divides_pow p n k : prime p -> divides p (n ^ k) -> divides p n.\nProof.\n  induction k.\n  - cbn; intros H H0 % divides_1_inv; subst; exfalso; revert H; apply not_prime_1.\n  - cbn; intros ? [ | ] % divides_mult_inv; eauto.\nQed.  \n\nOpaque ps qs.\n\nLemma ps_exp n m (v : vec nat m) i : ~ divides (ps n) (exp i v).\nProof.\n  revert i; induction v as [ | m x v IHv ]; intros i; simpl.\n  - intros H % divides_1_inv; revert H; apply not_ps_1.\n  - intros [H % divides_pow | ] % divides_mult_inv; eauto.\n    + now eapply ps_qs_div in H.\n    + eapply IHv; eauto.\nQed.\n\nCoercion tonat {n} := @pos2nat n.\n\nLemma vec_prod_div m (v : vec nat m) (u0 : nat) (p : pos m) i :\n    vec_pos v p = S u0 -> qs (p + i) * exp i (vec_change v p u0) = exp i v.\nProof.\n  revert p i; induction v; intros p i; analyse pos p; simpl; intros H.\n  - rewrite pos2nat_fst; subst; simpl; ring.\n  - rewrite pos2nat_nxt; simpl.\n    rewrite <- IHv with (1 := H).\n    unfold tonat.\n    replace (S (pos2nat p + i)) with (pos2nat p+S i); ring.\nQed.         \n\nLemma qs_exp_div i j n v : i < j -> ~ divides (qs i) (@exp n j v).\nProof with eauto.\n  revert i j; induction v; intros i j Hi.\n  + cbn; intros ? % divides_1_inv % not_qs_1; auto.\n  + cbn; intros [ H % divides_pow | H  ] % divides_mult_inv; eauto.\n    * eapply primestream_divides in H; lia.\n    * eapply IHv in H; eauto.\nQed.\n\nLemma qs_shift n m j k (v : vec nat k) :\n  divides (qs n) (exp j v) <-> divides (qs (m + n)) (exp (m + j) v).\nProof.\n  revert m n j; induction v as [ | x k v IHv ]; intros m n j.\n  - cbn; split; intros ? % divides_1_inv % not_qs_1; tauto.\n  - cbn. split.\n    + intros [ | ] % divides_mult_inv; auto.\n      * destruct x.\n        -- cbn in H; revert H.\n           intros ? % divides_1_inv % not_qs_1; tauto.\n        -- eapply divides_pow in H; auto. \n           eapply primestream_divides in H as ->.\n           cbn; do 2 apply divides_mult_r; apply divides_refl.\n      * eapply divides_mult. \n        rewrite IHv with (m := m) in H.\n        rewrite <- plus_n_Sm in H; auto.\n    + intros [ | ] % divides_mult_inv; auto.\n      * destruct x.\n        -- cbn in H; revert H.\n           intros ? % divides_1_inv % not_qs_1; tauto.\n        -- eapply divides_pow in H; auto. \n           eapply primestream_divides in H.\n           assert (n = j) by lia. subst.\n           cbn; do 2 apply divides_mult_r; apply divides_refl.\n      * eapply divides_mult. replace (S (m + j)) with (m + S j) in H by lia.\n        rewrite <- IHv in H. eauto.\nQed.\n\nLemma vec_prod_mult m v (u : pos m) i : @exp m i (vec_change v u (1 + vec_pos v u)) = qs (u + i) * exp i v.\nProof.\n  revert i; induction v; analyse pos u; intros.\n  + rewrite pos2nat_fst; simpl; ring.\n  + rewrite pos2nat_nxt; simpl; rewrite IHv.\n    unfold tonat.\n    replace (pos2nat u+S i) with (S (pos2nat u+i)) by lia; ring.\nQed.\n\nLemma inv_exp q p1 p2 x y : \n         q <> 0 \n      -> ~ divides q p1 \n      -> ~ divides q p2 \n      -> q ^ x * p1 = q ^ y * p2 \n      -> x = y.\nProof.\n  intros H1 H2 H3 H4.\n  apply power_factor_uniq in H4; tauto.\nQed.\n\nLemma exp_inj n i v1 v2 :\n  @exp n i v1 = exp i v2 -> v1 = v2.\nProof.\n  revert i v2; induction v1 as [ | x n v1 IH ]; intros i v2.\n  + vec nil v2; auto.\n  + vec split v2 with y.\n    simpl; intros H.\n    assert (forall v, ~ divides (qs i) (@exp n (S i) v)) as G.\n    { intros v; apply qs_exp_div; auto. }\n    apply power_factor_uniq in H; auto.\n    destruct H; f_equal; subst; eauto.\nQed.\n\nLemma exp_inv_inc n u v1 :\n  @exp n 0 (vec_change v1 u (S (vec_pos v1 u))) = qs u * exp 0 v1.\nProof.\n  enough (forall i, exp i (vec_change v1 u (S (vec_pos v1 u))) = qs (i + u) * exp i v1). eapply H.\n  induction v1 as [ | n x v1 IHv1 ]; analyse pos u; intros.\n  + rewrite pos2nat_fst, Nat.add_0_r; cbn; ring.\n  + intros; rewrite pos2nat_nxt; simpl; rewrite IHv1; unfold tonat.\n    replace (S i+pos2nat u) with (i+S (pos2nat u)) by lia; ring.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FRACTRAN/Util/prime_seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7427299080350616}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import img_example.\nRequire Import Coq.Sets.Relations_3_facts.\n\nSection RelationExample.\n\nDefinition ID (U:Type): Relation U := fun x:U => fun y:U => x = y.\nDefinition ID' (U:Type): U -> U -> Prop := fun x:U => fun y:U => x = y.\n\nCheck (forall (U:Type) (x:U), (ID U x x)).\n\nCheck Equivalence.\nCheck ID.\nCheck ID'.\n\nCheck (forall (U:Type) (x:U), ID U x x).\n\nGoal forall (U:Type), Equivalence U (ID U).\nProof.\n  move => U.\n  split.\n  unfold Reflexive.\n  move => x.\n  unfold ID.\n  reflexivity.\n  unfold Transitive.\n  move => x y z.\n  unfold ID.\n  move => H0 H1.\n  rewrite H0.\n  apply H1.\n  unfold Symmetric.\n  move => x y.\n  unfold ID.\n  move => H.\n  rewrite H.\n  reflexivity.\nQed.\n\nGoal forall (U:Type), Equivalence U (ID' U).\nProof.\n  move => U.\n  split.\n  unfold Reflexive.\n  move => x.\n  unfold ID'.\n  reflexivity.\n  unfold Transitive.\n  move => x y z.\n  unfold ID'.\n  move => H0 H1.\n  rewrite H0.\n  apply H1.\n  unfold Symmetric.\n  move => x y.\n  unfold ID'.\n  move => H.\n  rewrite H.\n  reflexivity.\nQed.\n\nEnd RelationExample.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "coq_ssreflect_practice", "sha": "96e1d440c8c69673209ae0d86046b6b9305f8bab", "save_path": "github-repos/coq/seisyuu-hantatsushi-coq_ssreflect_practice", "path": "github-repos/coq/seisyuu-hantatsushi-coq_ssreflect_practice/coq_ssreflect_practice-96e1d440c8c69673209ae0d86046b6b9305f8bab/practices/relation_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.742697796903585}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) : natural :=\n  plus lf3 (Succ lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj122_coqofml_NQu0FT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7426977792263948}}
{"text": "Require Import List.\nSet Implicit Arguments.\n\nSection A_fixed.\n\nVariable A: Type. \n\nInductive lfactor  : list A -> list A -> Prop :=\n  | lf1 : forall u:list A, lfactor nil u\n  | lf2 : forall (a:A) (u v:list A), lfactor u v ->\n                                     lfactor (a :: u) (a :: v).\n\n Lemma lfactor_inv_head : forall a b  u v, lfactor (a::u) (b::v) ->\n                                           a = b.\n Proof.\n   now inversion_clear 1.\n Qed.\n\nDefinition lfactor_suffix :\n  forall  u v:list A, lfactor u v -> {w : list A | v = u ++ w}.\n intros  u; induction  u as [| a u IHu].\n - intros v; now exists v.\n - intro v; case v.\n    + intros Hf; exfalso; inversion_clear Hf.\n    + intros b v' Hv';  generalize (lfactor_inv_head Hv'); intro;subst b.\n      destruct (IHu v') as [w Hw].\n      * now  inversion_clear Hv'.\n      * exists w; rewrite Hw;auto.\nDefined.\n\n\nEnd A_fixed.\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/ch14_fundations_of_inductive_types/SRC/factor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.798186787341014, "lm_q1q2_score": 0.7426794841686102}}
{"text": "(* Cap. 1: Funciones y computación *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(* =====================================================================\n   § 1. Funciones\n   ================================================================== *)\n\n(* =====================================================================\n   §§ 1.1. Definición de funciones y evaluación de expresiones\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      f : nat -> nat\n   tal que (f n) es el sigiente de n. Por ejemplo,\n      f 3 == 4.\n   ------------------------------------------------------------------ *)\n\nDefinition f := fun n => n + 1.\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Calcular información sobre la función `f`.\n   ------------------------------------------------------------------ *)\n\nAbout f.\n\n(* Se obtiene\n      f : nat -> nat\n\n      f is not universe polymorphic\n      Arguments f _%nat_scope\n      f is transparent\n      Expands to: Constant T1_Computacion.f\n *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Obtener la definición de `f`.\n   ------------------------------------------------------------------ *)\n\nPrint f.\n\n(* Se obtiene\n      f = addn^~ 1\n           : nat -> nat\n\n      Arguments f _%nat_scope\n *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Obtener información sobre ^~\n   ------------------------------------------------------------------ *)\n\nLocate \"_ ^~ _\".\n\n(* Se obtiene\n      Notation \"f ^~ y\" := (fun x => f x y) : fun_scope (default interpretation)\n *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Calcular el tipo de `f 3`.\n   ------------------------------------------------------------------ *)\n\nCheck f 3.\n\n(* Se obtiene\n      f 3\n           : nat\n *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Calcular el valor de `f 3`.\n   ------------------------------------------------------------------ *)\n\nEval compute in f 3.\n\n(* Se obtiene\n           = 4\n           : nat\n *)\n\n(* =====================================================================\n   §§ 1.2 Funciones con varios argumentos\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      g : nat -> nat -> nat\n   tal que (g n m) es n+m*2. Por ejemplo,\n      g 4 5 = 14\n   ------------------------------------------------------------------ *)\n\nDefinition g (n m : nat) : nat := n + m * 2.\n\nEval compute in g 4 5.\n\n(* =====================================================================\n   §§ 1.3. Funciones de orden superior\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      repeat_twice : (nat -> nat) -> nat -> nat\n   tal que (repeat_twice g) es la función obtenida aplicando dos veces\n   la función `g`. Por ejemplo,\n      repeat_twice f 2 = 4\n   ------------------------------------------------------------------ *)\n\nDefinition repeat_twice (g : nat -> nat) : nat -> nat :=\n  fun x => g (g x).\n\nEval compute in repeat_twice f 2.\n\n(* =====================================================================\n   §§ 1.4. Definiciones locales\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Calcular el valor de\n      let n := 33 : nat in\n      let e := n + n + n in\n      e + e + e.\n   ------------------------------------------------------------------ *)\n\nCompute\n  let n := 33 : nat in\n  let e := n + n + n in\n  e + e + e.\n\n(* Se obtiene\n         = 297\n         : nat\n*)\n\n(* =====================================================================\n   § 2. Tipos de datos\n   ================================================================== *)\n\n(* =====================================================================\n   §§ 2.1. Valores booleanos\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Calcular el tipo de `true`\n   ------------------------------------------------------------------ *)\n\nCheck true.\n\n(* Se obtiene\n      true\n           : bool\n *)\n\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      f23 : bool -> nat\n   tal que (f23 b) es 2 si b es verdadero y 3 en caso contrario. Por\n   ejemplo,\n      Ejemplos\n   ------------------------------------------------------------------ *)\n\nDefinition f23 b := if b then 2 else 3.\n\nEval compute in f23 true.  (* da 2 *)\nEval compute in f23 false. (* da 3*)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      andb ; bool -> bool -> bool\n   tal que (andb b1 b2) es la conjunción de b1 y b2. Por ejemplo,\n      andb true false = false\n   ------------------------------------------------------------------ *)\n\nDefinition andb b1 b2 := if b1 then b2 else false.\n\nEval compute in andb true false.\n\n(* =====================================================================\n   §§ 2.2. Números naturales\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      pred : nat -> nat\n   tal que (pred n) es el predecesor de n. Por ejemplo,\n      pred 6 = 5\n   ------------------------------------------------------------------ *)\n\nDefinition pred n := if n is u.+1 then u else n.\n\nEval compute in pred 6. (* da 5 *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      pred5 : nat -> nat\n   tal que (pred5 n) es n-5. Por ejemplo,\n      pred5 8 = 3\n      pred5 4 = 0\n   ------------------------------------------------------------------ *)\n\nDefinition pred5 n :=\n  if n is u.+1.+1.+1.+1.+1 then u else 0.\n\nEval compute in pred5 8. (* da 3 *)\nEval compute in pred5 4. (* da 0 *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      three_patterns : nat -> nat\n   tal que (three_patterns) es n-5, si n >= 5, n-1 si n pertenece a\n   {1,2,3,4] y 0 en caso contrario. Por ejemplo,\n      Ejemplos\n   ------------------------------------------------------------------ *)\n\nDefinition three_patterns n :=\n  match n with\n    u.+1.+1.+1.+1.+1 => u\n  | v.+1 => v\n  | 0 => n\n  end.\n\nEval compute in three_patterns 8. (* da 3 *)\nEval compute in three_patterns 3. (* da 2 *)\nEval compute in three_patterns 0. (* da 0 *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      same_bool : bool -> bool -> bool\n   tal que (same_bool b1 b2) se verifica si b1 y b2 son iguales. Por\n   ejemplo,\n   ------------------------------------------------------------------ *)\n\nDefinition same_bool b1 b2 :=\n  match b1, b2 with\n  | true, true => true\n  | _, _ => false\n  end.\n\nDefinition same_bool2 b1 b2 :=\n  match b1 with\n  | true => match b2 with true => true | _ => false end\n  | _ => false\n  end.\n\n(* =====================================================================\n   §§ 2.3. Recursión sobre los números naturales\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      addn : nat -> nat -> nat\n   tal que (addn n m) es la suma de n y m. Por ejemplo,\n      addn 2 3 = 5\n   ------------------------------------------------------------------ *)\n\nFixpoint addn n m :=\n  if n is p.+1 then (addn p m).+1 else m.\n\nFixpoint addn2 n m :=\n  match n with\n  | 0 => m\n  | p.+1 => (addn2 p m).+1\n  end.\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      subn : nat -> nat -> nat\n   tal que (subn m n) es m menos n. Por ejemplo,\n      subn 5 3 = 2\n      subn 3 5 = 0\n   ------------------------------------------------------------------ *)\n\nFixpoint subn m n : nat :=\n  match m, n with\n  | p.+1, q.+1 => subn p q\n  | _ , _ => m\n  end.\n\nEval compute in subn 5 3. (* da 2 *)\nEval compute in subn 3 5. (* da 0 *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio. Definir la función\n      eqn : nat -> nat -> bool\n   tal que (eqn m n) que se verifica si m y n son iguales. Por ejemplo,\n      eqn 2 2 = true\n      eqn 2 3 = false\n\n   Usar la notación `x == y` para `eqn x y`.\n   ------------------------------------------------------------------ *)\n\nFixpoint eqn m n :=\n  match m, n with\n  | 0, 0 => true\n  | p.+1, q.+1 => eqn p q\n  | _, _ => false\n  end.\nNotation \"x == y\" := (eqn x y).\n\nEval compute in 2 == 2. (* da true *)\nEval compute in 2 == 3. (* da false *)\n\nCompute 2 == 2. (* da true *)\nCompute 2 == 3. (* da false *)\n\n(* =====================================================================\n   § 3. Contenedores\n   ================================================================== *)\n\nAbout cons.\nCheck cons 2 nil.\nCheck 1 :: 2 :: 3 :: nil.\nCheck fun l => 1 :: 2 :: 3 :: l.\nDefinition first_element_or_0 (s : seq nat) :=\n  if s is a :: _ then a else 0.\n\nFixpoint size A (s : seq A) :=\n  if s is _ :: tl then (size tl).+1 else 0.\nFixpoint map A B (f : A -> B) s :=\n  if s is e :: tl then f e :: map f tl else nil.\nEval compute in [seq i.+1 | i <- [:: 2; 3]].\nCheck (3, false).\nEval compute in (true, false).1.\n\nDefinition only_odd (n : nat) : option nat :=\n  if odd n then Some n else None.\n\nDefinition ohead (A : Type) (s : seq A) :=\n  if s is x :: _ then Some x else None.\n\n(* section *)\nSection iterators.\n Variables (T : Type) (A : Type).\n Variables (f : T -> A -> A).\n Implicit Type x : T.\n Fixpoint iter n op x :=\n   if n is p.+1 then op (iter p op x) else x.\n Fixpoint foldr a s :=\n   if s is x :: xs then f x (foldr a xs) else a.\n About foldr.\n Variable init : A.\n Variables x1 x2 x3 : T.\n  Eval compute in foldr init [:: x1; x2; x3].\nEnd iterators.\nAbout iter.\nAbout foldr.\nEval compute in iter 5 pred 7.\nEval compute in foldr addn 0 [:: 1; 2; 3].\nFixpoint addn_alt m n := if m is u.+1 then addn_alt u n.+1 else n.\nSection symbolic.\n  Variable n : nat.\n  Eval simpl in pred (addn_alt n.+1 7).\n  Eval simpl in pred (addn n.+1 7).\nEnd symbolic.\n\n(* iterated ops *)\nFixpoint iota m n := if n is u.+1 then m :: iota m.+1 u else [::].\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (foldr (fun i a => F + a) 0 (iota m (n-m))).\nEval compute in \\sum_( 1 <= i < 5 ) (i * 2 - 1).\nEval compute in \\sum_( 1 <= i < 5 ) i.\n\n(* aggregated data *)\nRecord point := Point { x : nat; y : nat; z : nat }.\nEval compute in x (Point 3 0 2).\nEval compute in y (Point 3 0 2).\n\n(** Exercises *************************************** *)\n\nModule exercises.\n(* pair *)\n\n\n\n\nEval compute in fst (4,5).\n\n(* iter add *)\nDefinition addn n1 n2 := iter n1 S n2.\n\nEval compute in addn 3 4.\n\n(* iter mul *)\nDefinition muln n1 n2 := iter n1 (addn n2) 0.\n\nEval compute in muln 3 4.\n\n(* nth *)\nFixpoint nth T (def : T) (s : seq T) n :=\n  if s is x :: s' then if n is n'.+1 then nth def s' n' else x else def.\n\nEval compute in nth 0 [:: 3; 7; 11; 22] 2.\nEval compute in nth 0 [:: 3; 7; 11; 22] 7.\n\n(* rev *)\nFixpoint catrev T (s1 s2 : seq T) :=\n  if s1 is x :: xs then catrev xs (x :: s2) else s2.\n\nDefinition rev T (s : seq T) := catrev s [::].\n\nEval compute in rev [:: 1; 2; 3].\n\n(* flatten *)\nDefinition flatten T (s : seq (seq T)) := foldr cat [::] s.\n\nEval compute in\n  flatten [:: [:: 1; 2; 3]; [:: 4; 5] ].\n\n(* all_words *)\nDefinition all_words n T (alphabet : seq T) :=\n  let prepend x wl := [seq x :: w | w <- wl] in\n  let extend wl := flatten [seq prepend x wl | x <- alphabet] in\n  iter n extend [::[::]].\n\nEval compute in all_words 2 [:: 1; 2; 3].\n\nEnd exercises.\n", "meta": {"author": "jaalonso", "repo": "DAO_con_Coq_y_MathComp", "sha": "5237c4a41f14efc45029febfc41c8454f53e5ce7", "save_path": "github-repos/coq/jaalonso-DAO_con_Coq_y_MathComp", "path": "github-repos/coq/jaalonso-DAO_con_Coq_y_MathComp/DAO_con_Coq_y_MathComp-5237c4a41f14efc45029febfc41c8454f53e5ce7/teorias/T1_Computacion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7426391215786611}}
{"text": "(* Exercise 69 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_069 : (exists x : D, ~ P x) -> ~ (forall x : D, P x).\nProof.\nimp_i a1.\nneg_i (1=1) a2.\nexi_e (exists x:D, ~P x) a a3.\nhyp a1.\nneg_e (P a).\nhyp a3.\nall_e (forall x:D, P x) a.\nhyp a2.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred069.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850004144266, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7425732127010743}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nTheorem theorem0 : forall (x : Lst) (y : Nat) (z : Lst), eq (append (append x (cons y nil)) z) (append x (cons y z)).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal61.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850110816424, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7425732097146833}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, beq_nat_sym *)\n\nLemma nat_eqb_succ: forall n m: nat,\n  Nat.eqb (S n) (S m) = Nat.eqb n m.\nProof.\n    intros. simpl. reflexivity.\nQed.\n\nTheorem beq_nat_sym : forall (n m : nat), Nat.eqb n m=Nat.eqb m n.\nProof.\n    induction n as [|n']. induction m as [|m'].\n    simpl. reflexivity.\n    simpl. reflexivity.\n    intros. simpl. destruct m as [|m'].\n    simpl. reflexivity. rewrite nat_eqb_succ. apply IHn'.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter7_Library_MoreCoq/beq_nat_sym.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7425433477002003}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_collinear_ABC_ABD_BCD.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_collinear_ABC_ABD_ABE_CDE :\n\tforall A B C D E,\n\tneq A B ->\n\tCol A B C ->\n\tCol A B D ->\n\tCol A B E ->\n\tCol C D E.\nProof.\n\tintros A B C D E.\n\tintros neq_A_B.\n\tintros Col_A_B_C.\n\tintros Col_A_B_D.\n\tintros Col_A_B_E.\n\n\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_A_B_C Col_A_B_D neq_A_B) as Col_B_C_D.\n\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_A_B_C Col_A_B_E neq_A_B) as Col_B_C_E.\n\tassert (eq B C \\/ neq B C) as [eq_B_C|neq_B_C] by (apply Classical_Prop.classic).\n\t{\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_A_B_D Col_A_B_E neq_A_B) as Col_B_D_E.\n\t\tassert (Col C D E) as Col_C_D_E by (rewrite <- eq_B_C; exact Col_B_D_E).\n\t\texact Col_C_D_E.\n\t}\n\t{\n\t\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_B_C_D Col_B_C_E neq_B_C) as Col_C_D_E.\n\t\texact Col_C_D_E.\n\t}\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_collinear_ABC_ABD_ABE_CDE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7425433404188608}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) : natural :=\n  plus (Succ lf3) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj132_coqofml_WOGUfi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7424875317038282}}
{"text": "(* コンストラクタの名前は例えば、SOとSにするとよい。 *)\nInductive pos : Set :=\n  | SO : pos\n  | S  : pos -> pos\n  (* posの定義を書く *) .\n\nFixpoint plus(n m:pos) : pos := \n  match n with\n  | SO => S m\n  | S p => S (plus p m)\n  end.\n\nInfix \"+\" := plus.\n\nTheorem plus_assoc : forall n m p, 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": "odanado", "repo": "coq", "sha": "6524eb11b64fc6703af806e94b5405279d099ef2", "save_path": "github-repos/coq/odanado-coq", "path": "github-repos/coq/odanado-coq/coq-6524eb11b64fc6703af806e94b5405279d099ef2/coqex2014/3/kadai3_13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.742487529847514}}
{"text": "Require Export Basics.\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  - 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. induction n as [| n' IHn'].\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. induction n as [| n' IHn'].\n  - induction m as [| m' IHm''].\n    + reflexivity.\n    + simpl. rewrite <- IHm''. simpl. 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  - simpl. reflexivity.\n  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. 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  - simpl. reflexivity.\n  - rewrite -> IHn'. simpl. rewrite -> negb_involutive. reflexivity.\nQed.\n\n(******************************* Proof within Proofs ***************************)\n\n(* why can't rewrite recur down the tree? *)\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\n(************************* Formal vs Informal Proofs ***************************)\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\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  assert (n + p = p + n) as H.\n    rewrite plus_comm. simpl. reflexivity.\n  rewrite plus_comm.\nrewrite -> H. rewrite plus_assoc. simpl. reflexivity. Qed.\n\nTheorem mult_n_Sm : forall n m : nat,\n  n * S m = n + n * m.\nProof.\n  intros. induction n as [].\n  - simpl. reflexivity.\n  - simpl. rewrite IHn. rewrite <- plus_swap. reflexivity. Qed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros. induction n as [].\n  - simpl. apply mult_0_r.\n  - rewrite -> mult_n_Sm. simpl. rewrite -> IHn. reflexivity. Qed.\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 n as [].\n  - reflexivity.\n  - simpl. rewrite IHn. rewrite plus_assoc. reflexivity. Qed.\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  - reflexivity.\n  - simpl. rewrite IHn. rewrite mult_plus_distr_r. reflexivity. Qed.", "meta": {"author": "doyougnu", "repo": "Software_Foundations_Sol_2018", "sha": "b69460baaff4b717d25201ef06def803105b74d7", "save_path": "github-repos/coq/doyougnu-Software_Foundations_Sol_2018", "path": "github-repos/coq/doyougnu-Software_Foundations_Sol_2018/Software_Foundations_Sol_2018-b69460baaff4b717d25201ef06def803105b74d7/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7424678991847711}}
{"text": "Set Implicit Arguments.\nSet Strict Implicit.\nRequire Export Setoid.\nRequire Omega.\n\n(** * Sets.v: Definition of sets as predicates over a type A *)\n\nSection sets.\nVariable A : Type.\nVariable decA : forall x y :A, {x=y}+{x<>y}. \n\nDefinition set := A->Prop.\nDefinition full : set := fun (x:A) => True.\nDefinition empty : set := fun (x:A) => False.\nDefinition add (a:A) (P:set) : set := fun (x:A) => x=a \\/ (P x).\nDefinition singl (a:A) :set := fun (x:A) => x=a.\nDefinition union (P Q:set) :set := fun (x:A) => (P x) \\/ (Q x).\nDefinition compl (P:set) :set := fun (x:A) => ~P x.\nDefinition inter (P Q:set) :set := fun (x:A) => (P x) /\\ (Q x).\nDefinition rem (a:A) (P:set) :set := fun (x:A) => x<>a /\\ (P x).\n\n(** ** Equivalence *)\nDefinition equiv (P Q:set) := forall (x:A), P x <-> Q x.\n\nImplicit Arguments full [].\nImplicit Arguments empty [].\n\nLemma equiv_refl : forall P:set, equiv P P.\nunfold equiv; intuition.\nSave.\n\nLemma equiv_sym : forall P Q:set, equiv P Q -> equiv Q P.\nunfold equiv; firstorder.\nSave.\n\nLemma equiv_trans : forall P Q R:set, \n   equiv P Q -> equiv Q R -> equiv P R.\nunfold equiv; firstorder.\nSave.\n\nHint Resolve equiv_refl.\nHint Immediate equiv_sym.\n\n(** ** Setoid structure *)\nLemma set_setoid : Setoid_Theory set equiv.\nsplit; red; auto.\nexact equiv_trans.\nQed.\n\nAdd Setoid set equiv set_setoid as Set_setoid.\n\nAdd Morphism add : equiv_add.\nunfold equiv,add; firstorder.\nSave.\n\nAdd Morphism rem : equiv_rem.\nunfold equiv,rem; firstorder.\nSave.\nHint Resolve equiv_add equiv_rem.\n\nAdd Morphism union : equiv_union.\nunfold equiv,union; firstorder.\nSave.\nHint Immediate equiv_union.\n\nLemma equiv_union_left : \n  forall P1 Q P2,\n   equiv P1 P2 -> equiv (union P1 Q) (union P2 Q).\nauto.\nSave.\n\nLemma equiv_union_right : \n  forall P Q1 Q2 ,\n   equiv Q1 Q2 -> equiv (union P Q1) (union P Q2).\nauto.\nSave.\n\nHint Resolve equiv_union_left equiv_union_right.\n\nAdd Morphism inter : equiv_inter.\nunfold equiv,inter; firstorder.\nSave.\nHint Immediate equiv_inter.\n\nAdd Morphism compl : equiv_compl.\nunfold equiv,compl; firstorder.\nSave.\nHint Resolve equiv_compl.\n\nLemma equiv_add_empty : forall (a:A) (P:set), ~equiv (add a P) empty.\nred; unfold equiv,empty,add; intros a P eqH; assert (H:=eqH a);  intuition.\nSave.\n\n(** ** Finite sets given as an enumeration of elements *)\n\nInductive finite (P: set) : Type := \n   fin_eq_empty : equiv P empty -> finite P\n | fin_eq_add : forall (x:A)(Q:set),\n             ~ Q x-> finite Q -> equiv P (add x Q) -> finite P.\nHint Constructors finite.\n\nLemma fin_empty : (finite empty).\nauto.\nDefined.\n\nLemma fin_add : forall (x:A)(P:set),\n             ~ P x -> finite P -> finite (add x P).\neauto.\nDefined.\n\nLemma fin_equiv: forall (P Q : set), (equiv P Q)->(finite P)->(finite Q).\ninduction 2.\napply fin_eq_empty.\napply equiv_trans with P; auto.\napply fin_eq_add with x Q0; auto.\napply equiv_trans with P; auto.\nDefined.\n\nHint Resolve fin_empty fin_add.\n\n(** *** Emptyness is decidable for finite sets *)\nDefinition isempty (P:set) := equiv P empty.\nDefinition notempty (P:set) := not (equiv P empty).\n\nLemma isempty_dec : forall P, finite P -> {isempty P}+{notempty P}.\nunfold isempty,notempty; destruct 1; auto.\nright; red; intros.\napply (@equiv_add_empty x Q); auto.\napply equiv_trans with P; auto.\nSave.\n\n(** *** Size of a finite set *)\nFixpoint size (P:set) (f:finite P) {struct f}: nat :=\n   match f with fin_eq_empty _ => 0%nat\n              | fin_eq_add _ Q _ f' _ => S (size f')\n   end.\n\nLemma size_equiv : forall P Q  (f:finite P) (e:equiv P Q),\n    (size (fin_equiv e f)) = (size f).\ninduction f; simpl; intros; auto.\nSave.\n\n(** ** Inclusion *)\nDefinition incl (P Q:set) := forall x, P x -> Q x.\n\nLemma incl_refl : forall (P:set), incl P P.\nunfold incl; intuition.\nSave.\n\nLemma incl_trans : forall (P Q R:set), \nincl P Q -> incl Q R -> incl P R.\nunfold incl; intuition.\nSave.\n\nLemma equiv_incl : forall (P Q : set),  equiv P Q -> incl P Q.\nunfold equiv, incl; firstorder.\nSave.\n\nLemma equiv_incl_sym : forall (P Q : set), equiv P Q -> incl Q P.\nunfold equiv, incl; firstorder.\nSave.\n\nLemma equiv_incl_intro : \nforall (P Q : set), incl P Q -> incl Q P -> equiv P Q.\nunfold equiv, incl; firstorder.\nSave.\n\nHint Resolve incl_refl incl_trans equiv_incl_intro. \nHint Immediate equiv_incl equiv_incl_sym. \n\n(** ** Properties of operations on sets *)\n\nLemma incl_empty : forall P, incl empty P.\nunfold incl,empty; intuition.\nSave.\n\n\nLemma incl_empty_false : forall P a, incl P empty -> ~ P a.\nunfold incl; firstorder.\nSave.\n\nLemma incl_add_empty : forall (a:A) (P:set), ~ incl (add a P) empty.\nred; unfold incl,empty,add; intros a P eqH; assert (H:=eqH a);  intuition.\nSave.\n\nLemma equiv_empty_false : forall P a, equiv P empty -> P a -> False.\nunfold equiv; firstorder.\nSave.\n\nHint Immediate incl_empty_false equiv_empty_false incl_add_empty.\n\nLemma incl_rem_stable :   forall a P Q, incl P Q -> incl (rem a P) (rem a Q).\nunfold incl,rem;intuition.\nSave.\n\nLemma incl_add_stable :   forall a P Q, incl P Q -> incl (add a P) (add a Q).\nunfold incl,add;intuition.\nSave.\n\nLemma incl_rem_add_iff : \n  forall a P Q, incl (rem a P) Q <-> incl P (add a Q).\nunfold rem, add, incl; intuition.\ncase (decA x a); auto.\ncase (H x); intuition.\nSave.\n\nLemma incl_rem_add: \n  forall (a:A) (P Q:set), \n     (P a) -> incl Q (rem a P) -> incl (add a Q) P.\nunfold rem, add, incl; intros; auto.\ncase H1; intro; subst; auto.\ncase (H0 x); auto.\nSave.\n\nLemma incl_add_rem : \n  forall (a:A) (P Q:set), \n     ~ Q a -> incl (add a Q) P -> incl Q (rem a P) .\nunfold rem, add, incl; intros; auto.\ncase (decA x a); intros; auto.\nsubst; case H; auto.\nSave.\n\nHint Immediate incl_rem_add incl_add_rem.\n\nLemma equiv_rem_add : \n forall (a:A) (P Q:set), \n     (P a) -> equiv Q (rem a P)  -> equiv (add a Q) P.\nintros; assert (incl Q (rem a P)); auto.\nassert (incl (rem a P) Q); auto.\ncase (incl_rem_add_iff a P Q); auto.\nSave.\n\nLemma equiv_add_rem : \n forall (a:A) (P Q:set), \n     ~ Q a -> equiv (add a Q) P -> equiv Q (rem a P).\nintros; assert (incl (add a Q) P); auto.\nassert (incl P (add a Q)); auto.\ncase (incl_rem_add_iff a P Q); auto.\nSave.\n\nHint Immediate equiv_rem_add equiv_add_rem.\n\nLemma add_rem_eq_equiv : \n  forall x (P:set), equiv (add x (rem x P)) (add x P).\nunfold equiv, add, rem; intuition.\ncase (decA x0 x); intuition.\nSave.\n\nLemma add_rem_diff_equiv : \n  forall x y (P:set), \n  x<>y -> equiv (add x (rem y P)) (rem y (add x P)).\nunfold equiv, add, rem; intuition.\nsubst; auto.\nSave.\n\nLemma add_equiv_in : \n  forall x (P:set), P x -> equiv (add x P) P.\nunfold equiv, add; intuition.\nsubst;auto.\nSave.\n\nHint Resolve add_rem_eq_equiv add_rem_diff_equiv add_equiv_in.\n\n\nLemma add_rem_equiv_in : \n  forall x (P:set), P x -> equiv (add x (rem x P)) P.\nintros; apply equiv_trans with (add x P); auto.\nSave.\n\nHint Resolve add_rem_equiv_in.\n\nLemma rem_add_eq_equiv : \n  forall x (P:set), equiv (rem x (add x P)) (rem x P).\nunfold equiv, add, rem; intuition.\nSave.\n\nLemma rem_add_diff_equiv : \n  forall x y (P:set), \n  x<>y -> equiv (rem x (add y P)) (add y (rem x P)).\nintros; apply equiv_sym; auto.\nSave.\n\nLemma rem_equiv_notin : \n  forall x (P:set), ~P x -> equiv (rem x P) P.\nunfold equiv, rem; intuition.\nsubst;auto.\nSave.\n\nHint Resolve rem_add_eq_equiv rem_add_diff_equiv rem_equiv_notin.\n\nLemma rem_add_equiv_notin : \n  forall x (P:set), ~P x -> equiv (rem x (add x P)) P.\nintros; apply equiv_trans with (rem x P); auto.\nSave.\n\nHint Resolve rem_add_equiv_notin.\n\n\nLemma rem_not_in : forall x (P:set), ~ rem x P x.\nunfold rem; intuition.\nSave.\n\nLemma add_in : forall x (P:set), add x P x.\nunfold add; intuition.\nSave.\n\nLemma add_in_eq : forall x y P, x=y -> add x P y.\nunfold add; intuition.\nSave.\n\nLemma add_intro : forall x (P:set) y, P y -> add x P y.\nunfold add; intuition.\nSave.\n\nLemma add_incl : forall x (P:set), incl P (add x P).\nunfold incl,add; intuition.\nSave.\n\nLemma add_incl_intro : forall x (P Q:set), (Q x) -> (incl P Q) -> (incl (add x P) Q).\nunfold incl,add; intuition; subst; intuition.\nSave.\n\nLemma rem_incl : forall x (P:set), incl (rem x P) P.\nunfold incl, rem; intuition.\nSave.\n\nHint Resolve rem_not_in add_in rem_incl add_incl.\n\nLemma union_sym : forall P Q : set,\n      equiv (union P Q) (union Q P).\nunfold equiv, union; intuition.\nSave.\n\nLemma union_empty_left : forall P : set,\n      equiv P (union P empty).\nunfold equiv, union, empty; intuition.\nSave.\n\nLemma union_empty_right : forall P : set,\n      equiv P (union empty P).\nunfold equiv, union, empty; intuition.\nSave.\n\nLemma union_add_left : forall (a:A) (P Q: set),\n      equiv (add a (union P Q)) (union P (add a Q)).\nunfold equiv, union, add; intuition.\nSave.\n\nLemma union_add_right : forall (a:A) (P Q: set),\n      equiv (add a (union P Q)) (union (add a P) Q).\nunfold equiv, union, add; intuition.\nSave.\n\nHint Resolve union_sym union_empty_left union_empty_right\nunion_add_left union_add_right.\n\nLemma union_incl_left : forall P Q, incl P (union P Q).\nunfold incl,union; intuition.\nSave.\n\nLemma union_incl_right : forall P Q, incl Q (union P Q).\nunfold incl,union; intuition.\nSave.\n\nLemma union_incl_intro : forall P Q R, incl P R -> incl Q R -> incl (union P Q) R.\nunfold incl,union; intuition.\nSave.\n\nHint Resolve union_incl_left union_incl_right union_incl_intro.\n\nLemma incl_union_stable : forall P1 P2 Q1 Q2,\n\tincl P1 P2 -> incl Q1 Q2 -> incl (union P1 Q1) (union P2 Q2).\nintros; apply union_incl_intro; unfold incl,union; intuition.\nSave.\nHint Immediate incl_union_stable.\n\nLemma inter_sym : forall P Q : set,\n      equiv (inter P Q) (inter Q P).\nunfold equiv, inter; intuition.\nSave.\n\nLemma inter_empty_left : forall P : set,\n      equiv empty (inter P empty).\nunfold equiv, inter, empty; intuition.\nSave.\n\nLemma inter_empty_right : forall P : set,\n      equiv empty (inter empty P).\nunfold equiv, inter, empty; intuition.\nSave.\n\nLemma inter_add_left_in : forall (a:A) (P Q: set),\n      (P a) -> equiv (add a (inter P Q)) (inter P (add a Q)).\nunfold equiv, inter, add; split; intuition.\nsubst; auto.\nSave.\n\nLemma inter_add_left_out : forall (a:A) (P Q: set),\n      ~ P a -> equiv (inter P Q) (inter P (add a Q)).\nunfold equiv, inter, add; split; intuition.\nsubst; case H; auto.\nSave.\n\nLemma inter_add_right_in : forall (a:A) (P Q: set),\n      Q a -> equiv (add a (inter P Q)) (inter (add a P) Q).\nunfold equiv, inter, add; split; intuition.\nsubst; auto.\nSave.\n\nLemma inter_add_right_out : forall (a:A) (P Q: set),\n      ~ Q a -> equiv (inter P Q) (inter (add a P) Q).\nunfold equiv, inter, add; split; intuition.\nsubst; case H; auto.\nSave.\n\nHint Resolve inter_sym inter_empty_left inter_empty_right\ninter_add_left_in inter_add_left_out inter_add_right_in inter_add_right_out.\n\n(** ** Generalized union *)\nDefinition gunion (I:Type)(F:I->set) : set := fun z => exists i, F i z.\n\nLemma gunion_intro : forall I (F:I->set) i, incl (F i) (gunion F). \nred; intros; exists i; auto.\nSave.\n\nLemma gunion_elim : forall I (F:I->set) (P:set), (forall i, incl (F i) P) -> incl (gunion F) P.\nred; intros I F P H x (i,Hi).\napply (H i x); auto.\nSave.\n\nLemma gunion_monotonic : forall I (F G : I -> set), \n      (forall i, incl (F i) (G i))-> incl (gunion F) (gunion G).\nintros I F G H x (i,Hi).\nexists i; apply (H i x); trivial.\nSave.\n\n\n(** ** Removing an element from a finite set *)\n\nLemma finite_rem :  forall (P:set) (a:A),\n   finite P -> finite (rem a P).\ninduction 1; intuition.\napply fin_eq_empty.\nunfold rem,empty,equiv; intuition.\napply (equiv_empty_false x e); auto.\ncase (decA x a); intros.\napply fin_equiv with Q; subst; auto.\napply equiv_add_rem; auto.\napply fin_eq_add with x (rem a Q); auto.\nsubst; unfold rem; intuition.\napply equiv_trans with (rem a (add x Q)); auto.\nDefined.\n\nLemma size_finite_rem: \n   forall (P:set) (a:A) (f:finite P), \n    (P a) -> size f = S (size (finite_rem a f)).\ninduction f;  intros.\ncase (equiv_empty_false a e H).\nsimpl; case (decA x a); simpl; intros.\ncase e0; unfold eq_rect_r;simpl; auto.\nrewrite size_equiv; auto.\nrewrite IHf; auto.\ncase (e a); unfold add; intuition.\ncase n0; auto.\nSave.\n\n(* bug lie a intuition\nLemma size_finite_rem: \n   forall (P:set) (a:A) (f:finite P), \n    (P a) -> size f = S (size (finite_rem a f)).\ninduction f;  intuition.\ncase (equiv_empty_false a e H).\nsimpl; case (decA x a); simpl; intros.\ncase e0; unfold eq_rect_r;simpl; auto.\nrewrite size_equiv; auto.\nrewrite IHf; auto.\ncase (e a); unfold add; intuition.\ncase f0; auto.\nSave.\n*)\nRequire Import Arith.\n\nLemma size_incl : \n  forall (P:set)(f:finite P) (Q:set)(g:finite Q), \n  (incl P Q)-> size f <= size g.\ninduction f; simpl; intros; auto with arith.\napply le_trans with (S (size (finite_rem x g))).\napply le_n_S.\napply IHf with (g:= finite_rem x g); auto.\napply incl_trans with (rem x P); auto.\napply incl_add_rem; auto.\napply incl_rem_stable; auto.\nrewrite <- size_finite_rem; auto.\ncase (e x); intuition.\nSave.\n\nLemma size_unique : \n  forall (P:set)(f:finite P) (Q:set)(g:finite Q), \n  (equiv P Q)-> size f = size g.\nintros; apply le_antisym; apply size_incl; auto.\nSave.\n\n(** ** Decidable sets *)\nDefinition dec (P:set) := forall x, {P x}+{~ P x}.\n\nLemma finite_incl : forall P:set,\n   finite P -> forall Q:set, dec Q -> incl Q P -> finite Q.\nintros P FP; elim FP; intros; auto.\napply fin_eq_empty.\nunfold empty,equiv in *|-*; intuition.\ncase (e x); auto.\ncase (X0 x); intros.\napply fin_eq_add with (x:=x) (Q:=(rem x Q0)); auto.\napply X.\nunfold dec,rem.\nintro y; case (decA x y); intro.\ncase (X0 y); subst; intuition.\ncase (X0 y); intuition.\ncase (incl_rem_add_iff x Q0 Q); intuition.\napply H1; apply incl_trans with P0; auto.\napply equiv_sym; auto.\napply X; auto.\nred; intros.\ncase (e x0); intuition.\ncase H1; intuition; subst; auto.\ncase n0; auto.\nSave.\n\nLemma finite_dec : forall P:set, finite P -> dec P.\nred; intros P FP; elim FP; intros.\nright; intro; apply (equiv_empty_false x e); auto.\ncase (e x0); unfold add; intuition.\ncase (X x0); intuition.\ncase (decA x0 x); intuition.\nSave.\n\nLemma fin_add_in : forall (a:A) (P:set), finite P -> finite (add a P).\nintros a P FP; case (finite_dec FP a); intro.\napply fin_equiv with P; auto.\napply equiv_sym; auto.\napply fin_add; auto.\nDefined.\n\nLemma finite_union : \n     forall P Q, finite P -> finite Q -> finite (union P Q).\nintros P Q FP FQ; elim FP; intros.\napply fin_equiv with Q; auto.\napply equiv_trans with (union empty Q); auto.\napply fin_equiv with (add x (union Q0 Q)); auto.\napply equiv_trans with (union (add x Q0) Q); auto. \napply fin_add_in; auto.\nDefined.\n \nLemma finite_full_dec : forall P:set, finite full -> dec P -> finite P.\nintros; apply finite_incl with full; auto.\nunfold full,incl; auto.\nSave.\n\nRequire Import Lt.\n\n(** *** Filter operation *)\n\nLemma finite_inter : forall P Q, dec P -> finite Q -> finite (inter P Q).\nintros P Q decP FQ.\ninduction FQ.\nconstructor 1.\napply equiv_trans with (inter P empty); auto.\ncase (decP x); intro.\nconstructor 2 with x (inter P Q); auto.\nunfold inter; intuition.\nrewrite e.\nunfold add,inter; red; intuition.\nsubst; auto.\napply fin_equiv with (inter P Q); auto.\nrewrite e.\nunfold add,inter; red; intuition.\nsubst; intuition.\nDefined.\n\nLemma size_inter_empty : forall P Q (decP:dec P) (e:equiv Q empty), \n   size (finite_inter decP (fin_eq_empty e))=O.\ntrivial.\nSave.\n\nLemma size_inter_add_in : \n     forall P Q R (decP:dec P)(x:A)(nq:~Q x)(FQ:finite Q)(e:equiv R (add x Q)),\n      P x ->size (finite_inter decP (fin_eq_add nq FQ e))=S (size (finite_inter decP FQ)).\nintros; simpl.\ncase (decP x); intro; trivial; contradiction.\nSave.\n\nLemma size_inter_add_notin : \n     forall P Q R (decP:dec P)(x:A)(nq:~Q x)(FQ:finite Q)(e:equiv R (add x Q)),\n   ~ P x -> size (finite_inter decP (fin_eq_add nq FQ e))=size (finite_inter decP FQ).\nintros; simpl.\ncase (decP x); intro; try contradiction.\nrewrite size_equiv; trivial.\nSave.\n\nLemma size_inter_incl : forall P Q (decP:dec P)(FP:finite P)(FQ:finite Q), \n    (incl P Q) -> size (finite_inter decP FQ)=size FP.\nintros; apply size_unique.\nunfold inter; intro.\ngeneralize (H x); intuition.\nSave.\n\n(** *** Selecting elements in a finite set *)\n\nFixpoint nth_finite (P:set) (k:nat) (PF : finite P) {struct PF}: (k < size PF) -> A := \n  match PF as F return (k < size F) -> A with \n       fin_eq_empty H => (fun (e : k<0) => match lt_n_O k e with end)\n     | fin_eq_add x Q nqx fq eqq => \n           match k as k0 return k0<S (size fq)->A with \n                O => fun e => x\n         | (S k1) => fun (e:S k1<S (size fq)) => nth_finite fq (lt_S_n k1 (size fq) e)\n           end\n  end.\n\n\n(** A set with size > 1 contains at least 2 different elements **)\n\nLemma select_non_empty : forall (P:set), finite P -> notempty P -> sigT P.\ndestruct 1; intros.\ncase H; auto.\nexists x; case (e x); intuition.\nDefined.\n\nLemma select_diff : forall (P:set) (FP:finite P),\n     (1 < size FP)%nat -> sigT (fun x => sigT (fun y => P x /\\ P y /\\ x<>y)).\ndestruct FP; simpl; intros.\nabsurd (1<0); omega.\nexists x; destruct FP; simpl in H.\nabsurd (1<1); omega.\nexists x0; intuition.\ncase (e x); auto.\ncase (e0 x0); case (e x0); unfold add; intuition.\nsubst; case (e0 x0); intuition.\nSave.\n\nEnd sets.\n\nHint Resolve equiv_refl.\nHint Resolve equiv_add equiv_rem.\nHint Immediate equiv_sym finite_dec finite_full_dec equiv_incl equiv_incl_sym equiv_incl_intro.\n\nHint Resolve incl_refl.\nHint Immediate incl_union_stable.\nHint Resolve union_incl_left union_incl_right union_incl_intro incl_empty rem_incl\nincl_rem_stable incl_add_stable.\n\nHint Constructors finite.\nHint Resolve add_in add_in_eq add_intro add_incl add_incl_intro union_sym union_empty_left union_empty_right\nunion_add_left union_add_right finite_union equiv_union_left \nequiv_union_right.\nImplicit Arguments full [].\nImplicit Arguments empty [].\n\nAdd Parametric Relation (A:Type) : (set A) (equiv (A:=A))\n      reflexivity proved by (equiv_refl (A:=A))\n      symmetry proved by (equiv_sym (A:=A))\n      transitivity proved by (equiv_trans (A:=A))\nas equiv_rel.\n\nAdd Parametric Relation (A:Type) : (set A) (incl (A:=A))\n      reflexivity proved by (incl_refl (A:=A))\n      transitivity proved by (incl_trans (A:=A))\nas incl_rel.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/ALEA/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7424525343923508}}
{"text": "Require Export P04.\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 f.\n  intros H.\n  intros b.\n  rewrite -> H.\n  rewrite -> H.\n  destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n", "meta": {"author": "norangLemon", "repo": "plHW", "sha": "ca142b892b3dcb25cd7a3a29c14233061bca4c84", "save_path": "github-repos/coq/norangLemon-plHW", "path": "github-repos/coq/norangLemon-plHW/plHW-ca142b892b3dcb25cd7a3a29c14233061bca4c84/01/P05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7424525266241561}}
{"text": "(* From the standard library. *)\nRequire Import ZArith.\nLocal Open Scope Z_scope.\n\n(** * Set theory\n *\n * A fragment of set theory using predicates.  This file contains definitions\n * and notations.  Automation is provided in Automation.v, while properties are\n * proved in SetsFacts.v.\n *)\n\nDefinition set U := U -> Prop.\n\n(** Membership predicate. *)\nInductive is_in {U} : U -> set U -> Prop :=\n  Is_in : forall x (A : set U), A x -> is_in x A.\nInfix \"∈\" := is_in (at level 70, no associativity) : set_scope.\nLocal Open Scope set_scope.\n\n(** Set inclusion. *)\nDefinition subset {U} (A B : set U) : Prop :=\n  forall x, x ∈ A -> x ∈ B.\nInfix \"⊆\" := subset (at level 70, no associativity) : set_scope.\n\n(** Set equivalence.  In SetsFacts.v, we register it as a setoid, with an\n * associated database of rewriting rules. *)\nDefinition same {U} (A B : U -> Prop) :=\n  forall x, x ∈ A <-> x ∈ B.\nInfix \"≡\" := same (at level 79, no associativity) : set_scope.\n\n(** Empty sets. *)\nDefinition empty {U} : set U := fun _ : U => False.\nNotation \"∅\" := (@empty _) : set_scope.\n\n(** Singletons. *)\nDefinition singleton {U} (x : U) : set U := fun y => y = x.\nNotation \"⎨ a ⎬\" := (singleton a) : set_scope.\n\n(** Sets of the form { n integer | a <= n <= b }. *)\nDefinition segment (x y : Z) : set Z :=\n  fun n => x <= n <= y.\nNotation \"〚 x , y 〛\" :=\n  (segment x y) (at level 0, format \"'〚' x ','  '/' y '〛'\") : set_scope.\n\n(** Cartesian product. *)\nDefinition times {U V} (A : set U) (B : set V) : set (U * V) :=\n  fun p => (fst p ∈ A /\\ snd p ∈ B).\nInfix \"×\" := times (at level 39, left associativity) : set_scope.\n\n(** Binary unions. *)\nDefinition bin_union {U} (A B : set U) : set U :=\n  fun x => x ∈ A \\/ x ∈ B.\nInfix \"∪\" := bin_union (at level 41, right associativity) : set_scope.\n\n(** Union of a family of sets indexed by integers [n] such that\n * [a <= n <= b]. *)\nDefinition param_union {U} (a b : Z) (X : Z -> set U) :=\n  fun x => exists i, a <= i <= b /\\ x ∈ X i.\nNotation \"⋃ ⎨ A , k ∈ 〚 a , b 〛 ⎬\" :=\n  (param_union a b (fun k => A))\n    (at level 0, k at next level, A at next level) : set_scope.", "meta": {"author": "mit-plv", "repo": "stencils", "sha": "02d87db4dd9fac1b1625394acf8d5bf455b1d166", "save_path": "github-repos/coq/mit-plv-stencils", "path": "github-repos/coq/mit-plv-stencils/stencils-02d87db4dd9fac1b1625394acf8d5bf455b1d166/sources/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7423578179770883}}
{"text": "Require Import List.\n\nSection ListLexOrder.\n  Variable T : Type.\n  Variable cmp : T -> T -> comparison.\n\n  Fixpoint list_lex_cmp (ls rs : list T) : comparison :=\n    match ls , rs with\n      | nil , nil => Eq\n      | nil , _ => Lt\n      | _ , nil => Gt\n      | l :: ls , r :: rs =>\n        match cmp l r with\n          | Eq => list_lex_cmp ls rs\n          | x => x\n        end\n    end.\nEnd ListLexOrder.\n\nSection Sorting.\n  Variable T : Type.\n  Variable cmp : T -> T -> comparison.\n\n  Section insert. \n    Variable val : T.\n\n    Fixpoint insert_in_order (ls : list T) : list T :=\n      match ls with\n        | nil => val :: nil\n        | l :: ls' =>\n          match cmp val l with\n            | Gt => l :: insert_in_order ls' \n            | _ => val :: ls \n          end\n      end.\n  End insert.\n\n  Fixpoint sort (ls : list T) : list T :=\n    match ls with\n      | nil => nil \n      | l :: ls => \n        insert_in_order l (sort ls)\n    end.\n\nEnd Sorting.\n\nLemma insert_in_order_inserts : forall T C x l,\n  exists h t, insert_in_order T C x l = h ++ x :: t /\\ l = h ++ t.\nProof.\n  clear. induction l; simpl; intros.\n  exists nil; exists nil; eauto.\n  destruct (C x a). \n  exists nil; simpl. eauto.\n  exists nil; simpl. eauto.\n  destruct IHl. destruct H. intuition. subst.\n  rewrite H0. exists (a :: x0). exists x1. simpl; eauto.\nQed.\n\nRequire Import Permutation.\n\nLemma sort_permutation : forall T (C : T -> T -> _) x,\n  Permutation (sort _ C x) x.\nProof.\n  induction x; simpl.\n  { reflexivity. }\n  { destruct (insert_in_order_inserts T C a (sort T C x)) as [ ? [ ? ? ] ].\n    destruct H. rewrite H. rewrite <- Permutation_cons_app. reflexivity. rewrite H0 in *. symmetry; auto. }\nQed.\n", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/src/Ordering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7423578152240162}}
{"text": "Require Import Reals.\nRequire Import PolTac.\n\nOpen Scope R_scope.\n\nTheorem pols_test1 x y :\n  x < y -> x + x < y + x.\nProof.\nintros.\npols.\nauto.\nQed.\n\nTheorem pols_test2 x y :\n  0 < y -> x < x + y.\nProof.\nintros.\npols.\nauto.\nQed.\n\nTheorem pols_test3 x y :\n  0 < y * y ->\n  (x + y) * (x - y) < x * x.\nProof.\nintros.\npols.\nauto with real.\nQed.\n\nTheorem pols_test4 x y :\n  x * x < y * y ->\n  (x + y) * (x + y) < 2 * (x * y + y * y).\nProof.\nintros.\npols.\nauto.\nQed.\n\nTheorem pols_test5 x y z :\n  x * (z + 2) < y * (2 * x + 1) ->\n  x * (z + y + 2) < y * (3 * x + 1).\nProof.\nintros.\npols.\nauto.\nQed.\n\nTheorem polf_test1 x y :\n  0 <= x -> 1 <= y -> x <= x * y.\nProof.\nintros.\npolf.\nQed.\n\nTheorem polf_test2 x y :\n  0 < x -> x <= x * y -> 1 <= y.\nProof.\nintros H1 H2.\nhyp_polf H2.\nQed.\n\nTheorem polr_test1 x y z :\n  x + z < y ->\n  x + y + z < 2 * y.\nProof.\nintros H.\npolr H.\npols.\nauto.\npols.\nauto with real.\nQed.\n\nTheorem polr_test2 x y z t u :\n  t < 0 -> y = u ->\n  x + z < y ->\n  2 * y * t < x * t + t * u + z * t.\nProof.\nintros H1 H2 H3.\npolf.\npolr H2; auto with real.\npolr H3.\npols.\nauto.\npols.\nauto with real.\nQed.", "meta": {"author": "thery", "repo": "PolTac", "sha": "cb5e530fdd8a1c72882d33b49146d397363103f2", "save_path": "github-repos/coq/thery-PolTac", "path": "github-repos/coq/thery-PolTac/PolTac-cb5e530fdd8a1c72882d33b49146d397363103f2/Rex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7423275941436689}}
{"text": "Require Export Poly.\n\nTheorem silly1 : forall(n m o p : nat),\n    n = m ->\n    [n;o] = [n;p] ->\n    [n;o] = [m;p].\nProof.\n    intros n m o p eq1 eq2.\n    rewrite <- eq1.\n    apply eq2.\nQed.\n\nTheorem silly2 : forall(n m o p : nat),\n    n = m ->\n    (forall(q r : nat), q = r -> [q;o] = [r;p]) ->\n    [n;o] = [m;p].\nProof.\n    intros n m o p eq1 eq2.\n    apply eq2. apply eq1.\nQed.\n\nTheorem silly2a : forall(n m : nat),\n    (n, n) = (m, m) ->\n    (forall(q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n    [n] = [m].\nProof.\n    intros n m eq1 eq2.\n    apply eq2. apply eq1.\nQed.\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    apply H0.\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    symmetry.\n    simpl.\n    apply H.\nQed.\n\nTheorem rev_exercise1: forall (l l' : list nat),\n    l = rev l' ->\n    l' = rev l.\nProof.\n    intros.\n    rewrite H.\n    symmetry.\n    apply rev_involutive.\nQed.\n\nExample trans_eq_example : forall(a b c d e f : nat),\n    [a;b] = [c;d] ->\n    [c;d] = [e;f] ->\n    [a;b] = [e;f].\nProof.\n    intros a b c d e f eq1 eq2.\n    rewrite -> eq1. rewrite -> eq2. reflexivity.\nQed.\n\nTheorem trans_eq : forall(X:Type) (n m o : X),\n    n = m -> m = o -> n = o.\nProof.\n    intros X n m o eq1 eq2. rewrite -> eq1.\n    rewrite -> eq2. reflexivity.\nQed.\n\nExample trans_eq_example' : forall(a b c d e f : nat),\n    [a;b] = [c;d] ->\n    [c;d] = [e;f] ->\n    [a;b] = [e;f].\nProof.\n    intros a b c d e f eq1 eq2.\n    apply trans_eq with (m:=[c;d]).\n    apply eq1.\n    apply eq2.\nQed.\n\nExample trans_eq_exercise : forall(n m o p : nat),\n    m = (minustwo o) ->\n    (n + p) = m ->\n    (n + p) = (minustwo o).\nProof.\n    intros n m o p eq1 eq2.\n    apply trans_eq with (m := m).\n    apply eq2.\n    apply eq1.\nQed.\n\nTheorem eq_add_S : forall(n m : nat),\n    S n = S m ->\n    n = m.\nProof.\n    intros n m eq. inversion eq. reflexivity.\nQed.\n\nTheorem silly4 : forall(n m : nat),\n    [n] = [m] ->\n    n = m.\nProof.\n    intros n o eq. inversion eq. reflexivity.\nQed.\n\nTheorem silly5 : forall(n m o : nat),\n    [n;m] = [o;o] ->\n    [n] = [m].\nProof.\n    intros n m o eq. inversion eq. reflexivity.\nQed.\n\nExample sillyex1 : forall(X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = z :: j ->\n    y :: l = x :: j ->\n    x = y.\nProof.\n    intros.\n    inversion H0.\n    reflexivity.\nQed.\n\nTheorem silly6 : forall(n : nat),\n    S n = O ->\n    2 + 2 = 5.\nProof.\n    intros n contra. inversion contra.\nQed.\n\nTheorem silly7 : forall(n m : nat),\n    false = true ->\n    [n] = [m].\nProof.\n    intros n m contra. inversion contra.\nQed.\n\nExample sillyex2 : forall(X:Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] ->\n    y :: l = z :: j ->\n    x = z.\nProof.\n    intros X x y z l j contra1 contra2.\n    inversion contra1.\nQed.\n\nTheorem f_equal : forall(A B : Type) (f: A -> B) (x y : A),\n    x = y -> f x = f y.\nProof.\n    intros A B f x y eq.\n    rewrite eq.\n    reflexivity.\nQed.\n\nTheorem length_snoc' : forall(X : Type) (v : X)\n    (l : list X) (n : nat),\n    length l = n ->\n    length (snoc l v) = S n.\nProof.\n    intros X v l. induction l as [| v' l'].\n    Case \"l = []\". intros n eq. rewrite <- eq. reflexivity.\n    Case \"l = v' :: l'\". intros n eq. simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\napply f_equal. apply IHl'. inversion eq. reflexivity.\nQed.\n\nTheorem beq_nat_0_l : forall n,\n    beq_nat 0 n = true -> n = 0.\nProof.\n    intros n eq1.\n    induction n as [| n'].\n    Case \"n = 0\".\n        reflexivity.\n    Case \"n = S n'\".\n        inversion eq1.\nQed.\n\nTheorem beq_nat_0_r : forall n,\n    beq_nat n 0 = true -> n = 0.\nProof.\n    intros n eq1.\n    induction n as [| n'].\n    Case \"n = 0\".\n        reflexivity.\n\n    Case \"n = S n'\".\n        inversion eq1.\nQed.\n\nTheorem S_inj : forall(n m : nat) (b : bool),\n    beq_nat (S n) (S m) = b ->\n    beq_nat n m = b.\nProof.\n    intros n m b H.\n    simpl in H.\n    apply H.\nQed.\n\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    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    intros.\n    simpl in H.\n    destruct m.\n        reflexivity.\n        inversion H.\n\n    intros.\n    destruct m.\n    inversion H.\n    simpl in H.\n    rewrite <- plus_n_Sm in H.\n    rewrite <- plus_n_Sm in H.\n    apply eq_add_S in H.\n    apply eq_add_S in H.\n    assert (n' = m) as Heq. apply IHn'. assumption.\n    rewrite Heq.\n    reflexivity.\nQed.\n\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n    intros n.\n    induction n as [| n'].\n    intros m eq.\n    destruct m.\n    reflexivity.\n\n    inversion eq.\n\n    intros m eq.\n    destruct m as [| m'].\n    inversion eq.\n\n    apply f_equal.\n    apply IHn'.\n    inversion eq.\n    rewrite -> H0.\n    reflexivity.\nQed.\n\nTheorem double_injective_take2 : forall n m,\n    double n = double m ->\n    n = m.\nProof.\n    intros n m.\n    (* n and m are both in the context *)\n    generalize dependent n.\n    (* Now n is back in the goal and we can do induction on\n    m and get a sufficiently general IH. *)\n    induction m as [| m'].\n    Case \"m = O\". simpl. intros n eq. destruct n as [| n'].\n        SCase \"n = O\". reflexivity.\n        SCase \"n = S n'\". inversion eq.\n    Case \"m = S m'\". intros n eq. destruct n as [| n'].\n        SCase \"n = O\". inversion eq.\n        SCase \"n = S n'\". apply f_equal.\n            apply IHm'. inversion eq. reflexivity.\nQed.\n\nTheorem index_after_last : forall(n : nat) (X : Type) (l : list X),\n    length l = n ->\n    index n l = None.\nProof.\n    intros n X l.\n    generalize dependent n.\n    induction l as [| h' l'].\n    Case \"l = nil\".\n        reflexivity.\n\n    Case \"l = h l'\".\n        destruct n as [| n'].\n        SCase \"n = 0\".\n            simpl. intros eq. inversion eq.\n\n        SCase \"n = S n'\".\n            intros eq. symmetry in eq. rewrite eq. simpl.\n            apply IHl'. reflexivity.\nQed.\n\nTheorem length_snoc''' : forall(n : nat) (X : Type)\n                        (v : X) (l : list X),\n            length l = n ->\n            length (snoc l v) = S n.\nProof.\n    intros n X v l.\n    generalize dependent n.\n    generalize dependent v.\n    induction l as [| h l'].\n    Case \"l = nil\".\n        intros v n. intros eq. simpl in eq. symmetry in eq. rewrite eq. reflexivity.\n\n    Case \"n = h n'\".\n        intros v n.\n        intros eq.\n        simpl.\n        symmetry in eq.\n        rewrite eq.\n        apply f_equal.\n        simpl.\n        apply IHl'.\n        reflexivity.\nQed.\n", "meta": {"author": "montekki", "repo": "sf", "sha": "f91b70058bfeca1427fd402f0be158f6c779dffe", "save_path": "github-repos/coq/montekki-sf", "path": "github-repos/coq/montekki-sf/sf-f91b70058bfeca1427fd402f0be158f6c779dffe/MoreCoq/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7421616276658963}}
{"text": "Set Implicit Arguments.\nRequire Import ZArith.\n\n\nInductive Z_btree : Set :=\n  | Z_leaf : Z_btree\n  | Z_bnode : Z -> Z_btree -> Z_btree -> Z_btree.\n\nCheck Z_btree_ind.\n\n(*\nOpen Scope Z_scope.\n*)\n\nFixpoint sum_all_values (t: Z_btree) : Z :=\n  (match t with\n    | Z_leaf          => 0\n    | Z_bnode v t1 t2 => v + sum_all_values t1 + sum_all_values t2\n  end)%Z.  (* (...)%Z or else you need to open Z_scope *)\n\nFixpoint zero_present (t: Z_btree) : bool :=\n  match t with\n    | Z_leaf              => false\n    | Z_bnode (0%Z) t1 t2 => true\n    | Z_bnode _ t1 t2     => if zero_present t1 then true else zero_present t2\n  end.\n\nInductive Z_fbtree : Set :=\n  | Z_fleaf : Z_fbtree\n  | Z_fnode : Z -> (bool->Z_fbtree) -> Z_fbtree.\n\n\nDefinition right_son (t: Z_btree) : Z_btree :=\n  match t with\n    | Z_leaf            => Z_leaf\n    | Z_bnode a t1 t2   => t2\n  end.\n\nDefinition fright_son (t: Z_fbtree) : Z_fbtree :=\n  match t with \n    | Z_fleaf           => Z_fleaf\n    | Z_fnode a f       => f false\n  end.\n\nFixpoint fsum_all_values (t:Z_fbtree) : Z :=\n  (match t with \n    | Z_fleaf           => 0\n    | Z_fnode v f       => v + fsum_all_values (f true) + fsum_all_values (f false)\n  end)%Z.\n\n\nFixpoint fzero_present (t:Z_fbtree) : bool :=\n  match t with\n    | Z_fleaf           => false\n    | Z_fnode (0%Z) f   => true\n    | Z_fnode _     f   => if fzero_present (f true) then true else fzero_present (f false) \n  end.\n\n\nInductive Z_inf_branch_tree : Set :=\n  | Z_inf_leaf : Z_inf_branch_tree\n  | Z_inf_node : Z -> (nat -> Z_inf_branch_tree) -> Z_inf_branch_tree. \n\n\nFixpoint sum_f_acc (n:nat)(f: nat->Z)(acc: Z) :Z :=\n  match n with\n    | 0     => acc\n    | S p   => sum_f_acc p f (acc + (f p))\n  end.\n\nDefinition sum_f (n:nat)(f:nat->Z) : Z  := sum_f_acc n f 0%Z.\n\nFixpoint n_sum_all_values (n:nat)(t: Z_inf_branch_tree) : Z :=\n  (match t with \n    | Z_inf_leaf          => 0\n    | Z_inf_node v f      => v + sum_f n (fun x:nat => n_sum_all_values n (f x))\n  end)%Z.\n\nTheorem plus_assoc' : forall x y z:nat, x+y+z = x+(y+z).\nProof.\n  intros x y z. elim x. simpl. trivial.\n  intros n H. simpl. rewrite H. trivial.\nQed.\n\nCheck eq_ind.\n(* \nforall (A : Type) (x : A) (P : A -> Prop),\n       P x -> forall y : A, x = y -> P y\n*)\n\n\nLemma plus_n_0' : forall (n:nat), n = n + 0.\nProof.\n  intro n. elim n. simpl. reflexivity.\n  clear n. intros n IH. simpl. pattern (n+0).\n  apply eq_ind with (y:=(n+0))(x:=n).\n  reflexivity. exact IH.\nQed.\n\nFixpoint f1 (t:Z_btree) : Z_fbtree :=\n  match t with\n    | Z_leaf            => Z_fleaf\n    | Z_bnode v t1 t2   => \n      Z_fnode v (fun b  => \n        match b with\n          | true  => (f1 t1)\n          | false => (f1 t2)   \n         end)\n   end.\n\nFixpoint f2 (t:Z_fbtree) : Z_btree :=\n  match t with\n    | Z_fleaf           => Z_leaf\n    | Z_fnode v f       => Z_bnode v (f2 (f true)) (f2 (f false))\n  end.\n\nTheorem f2of1: forall (t:Z_btree), f2 (f1 t) = t.\nProof.\n  intro t. elim t. simpl. reflexivity.\n  clear t. intro v. intro t1. intro H1. intro t2. intro H2. \n  simpl. rewrite H1. rewrite H2. reflexivity.\nQed.\n\nInductive btree (A:Type) : Type :=\n  | leaf : btree A\n  | node : A -> btree A -> btree A -> btree A.\n\nFixpoint translate (t:Z_btree) : btree Z :=\n  match t with\n    | Z_leaf          => leaf Z\n    | Z_bnode v t1 t2 => node v (translate t1) (translate t2)\n  end. \n\nFixpoint specialize (t:btree Z) : Z_btree :=\n  match t with\n    | leaf            => Z_leaf\n    | node v t1 t2    => Z_bnode v (specialize t1) (specialize t2)\n  end.\n\nLemma translate_specialize : forall (t:btree Z),\n  translate (specialize t) = t.\nProof.\n  intro t. elim t. simpl. reflexivity. clear t. intros a t1 IH1 t2 IH2. simpl.\n  rewrite IH1, IH2. reflexivity.\nQed.\n\n(* identical proof *)\nLemma specialize_translate : forall (t:Z_btree),\n  specialize (translate t) = t.\nProof.\n  intro t. elim t. simpl. reflexivity. clear t. intros a t1 IH1 t2 IH2. simpl.\n  rewrite IH1, IH2. reflexivity.\nQed.\n\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/btree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7421616262578564}}
{"text": "Inductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\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\nCompute (next_weekday friday).\n\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.\n\nInductive bool : Type :=\n  | true\n  | false.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nCompute (negb true).\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nCompute (andb true false).\n\nDefinition orb (b1:bool) (b2:bool) :bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\nCompute (orb true false).\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_and1:\n  (true && false && true) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition negb' (b:bool) : bool :=\n  if b then false\n  else true.\n\nCompute (negb' true).\n\nDefinition andb' (b1:bool) (b2:bool) : bool :=\n  if b1 then b2\n  else false.\n\nCompute (andb' true true).\n\n\nDefinition nandb (b1:bool) (b2:bool) :bool :=\n  match b1 with\n  | true => (negb b2)\n  | false => true\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\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n  | true => (andb b2 b3)\n  | false => false\n  end.\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 true.\n\nCheck true\n    : bool.\nCheck (negb true)\n    : bool.\n\nCheck negb.\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\nDefinition monochrome (c : color): bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\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\nInductive bit : Type :=\n  | B0\n  | B1.\n\nInductive nybble : Type :=\n  | bits (b0 b1 b2 b3 : bit).\n\nCheck (bits B1 B0 B1 B0)\n    : nybble.\n\nDefinition all_zero (nb : nybble) : bool :=\n  match nb with\n    | (bits B0 B0 B0 B0) => true\n    | (bits _ _ _ _) => false\n  end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\n\nCompute (all_zero (bits B0 B0 B0 B0)).\n\nModule NatPlayground.\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\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\nCheck S.\nCheck pred.\nCheck minustwo.\n\nCompute (pred 3).\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\nCompute (evenb 4).\nCompute (evenb 5).\nCompute (evenb (S (S O))).\n\nDefinition oddb (n:nat) : bool :=\n  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 NatPlayground2.\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 5 3).\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\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 NatPlayground2.\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\nCompute (exp 3 5).\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S p => mult (plus p 1) (factorial p)\n  end.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y).\nNotation \"x - y\" := (minus x y).\nNotation \"x * y\" := (mult x y).\n\nCheck ((0 + 1) + 1).\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\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\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nExample test_leb3': (4 <=? 2) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition ltb (n m : nat) : bool:=\n  match (minus n m) with \n  | O => (negb(eqb n m))\n  | _ => false\n  end.\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1: (ltb 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_ltb2: (ltb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ltb3: (ltb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nCompute (minus 3 5).\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. 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\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\nProof.\n  (* 将两个量词移到上下文中： *)\n  intros n m.\n  (* 将前提移到上下文中： *)\n  intros H.\n  (* 用前提改写目标： *)\n  rewrite -> H.\n  reflexivity. Qed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> \n  m = o -> \n  n + m = m + o.\nProof.\n  intros n m o.\n  intros H J.\n  rewrite -> H.\n  rewrite -> J.\n  reflexivity. Qed.\n\nCheck mult_n_O.\n\nCheck mult_n_Sm.\n\nTheorem mult_n_0_m_0 : forall n m : nat,\n  (n * 0) + (m * 0) = 0.\n\nProof.\n  intros n m.\n  rewrite <- mult_n_O.\n  rewrite <- mult_n_O.\n  reflexivity. Qed.\n\nTheorem mult_n_1 : forall n : nat,\n  n * 1 = n.\nProof.\n  intros.\n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_O.\n  reflexivity. Qed.\n\nTheorem mult_n_2 : forall n : nat,\n  n * 2 = n + n.\nProof.\n  intros.\n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_O.\n  reflexivity. Qed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n  simpl. (* 无能为力! *)\nAbort.\n\nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  - reflexivity.\n  - reflexivity. 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 plus_1_neq_0' : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem andb_commutative'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c. destruct c.\n  - simpl. intros H. reflexivity.\n  - rewrite -> andb_commutative.\n               simpl.\n               intros H.\n               rewrite H.\n               reflexivity. Qed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(*\nFixpoint funny_func (n : nat) (m : nat) : nat :=\n  match n with\n  | 0 => (funny_func (minus m 1) 1)\n  | S n' => (funny_func (minus m 1) (funny_func m (minus n' 1)))\n  end.\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 f.\n  intros H.\n  intros x. destruct x eqn : Ex.\n  - rewrite H. rewrite H. reflexivity.\n  - rewrite H. rewrite H. 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 f.\n  intros H.\n  intros x. destruct x eqn : Ex.\n  - rewrite H. rewrite H. reflexivity.\n  - rewrite H. rewrite H. reflexivity.\nQed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros b. destruct b eqn : Eb.\n  intros c. destruct c eqn : Ec.\n  - reflexivity. \n  - simpl.\n    * intros H.\n      + rewrite H. reflexivity.\n  - intros c. destruct c eqn : Ec.\n    * simpl.\n      + intros H.\n        rewrite H. reflexivity.\n    * reflexivity. \nQed.\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 m' => B m'\n  | B m' => A (incr m')\n  end.\n\nCompute (incr (A (B (B Z)))).\n\nFixpoint bin_to_nat (m:bin) : nat :=\n  match m with\n  | Z => O\n  | A m' => plus (bin_to_nat m') (bin_to_nat m')\n  | B m' => S (plus (bin_to_nat m') (bin_to_nat m'))\n  end.\n\nCompute (bin_to_nat (A (A (B Z)))).\n\nExample test_bin_incr1 : (incr (B Z)) = A (B Z).\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr2 : (incr (A (B Z))) = B (B Z).\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr3 : (incr (B (B Z))) = A (A (B Z)).\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr4 : bin_to_nat (A (B Z)) = 2.\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr5 :\n        bin_to_nat (incr (B Z)) = 1 + bin_to_nat (B Z).\nProof. simpl. reflexivity. Qed.\nExample test_bin_incr6 :\n        bin_to_nat (incr (incr (B Z))) = 2 + bin_to_nat (B Z).\nProof. simpl. reflexivity. Qed.\n", "meta": {"author": "cipherkint", "repo": "COQplayground", "sha": "8aad2b923b55c17922b99c3be1a4d1963bd06105", "save_path": "github-repos/coq/cipherkint-COQplayground", "path": "github-repos/coq/cipherkint-COQplayground/COQplayground-8aad2b923b55c17922b99c3be1a4d1963bd06105/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8577680977182186, "lm_q1q2_score": 0.7421616183930938}}
{"text": "(* week_40c_flatten.v *)\n(* dIFP 2014-2015, Q1, Week 40 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\nRequire Import Arith Bool unfold_tactic.\n\n(* ********** *)\n\n(* Data type of binary trees of natural numbers: *)\n\nInductive binary_tree_nat : Type :=\n  | Leaf : nat -> binary_tree_nat\n  | Node : binary_tree_nat -> binary_tree_nat -> binary_tree_nat.\n\n(* There is one base case: leaves.\n   There is one induction case, with two subtrees.\n*)\n\n(* ********** *)\n\n(* Sample of binary trees of natural numbers: *)\n\nDefinition bt_0 :=\n  Leaf 42.\n\nDefinition bt_1 :=\n  Node (Leaf 10)\n       (Leaf 20).\n\nDefinition bt_2 :=\n  Node (Node (Leaf 10)\n             (Leaf 20))\n       (Leaf 30).\n\n(* ********** *)\n(*\nDefinition unit_test_for_flatten (candidate : binary_tree_nat -> nat) :=\n  (candidate bt_0 =n= 1)\n  &&\n  (candidate bt_1 =n= 2)\n  &&\n  (candidate bt_2 =n= 3)\n  &&\n  (candidate (Node bt_1 bt_2) =n= 5)\n  .\n*)\n(* ********** *)\n\nDefinition specification_of_flatten (flatten : binary_tree_nat -> list nat) :=\n  (forall n : nat,\n     flatten (Leaf n) = n :: nil)\n  /\\\n  (forall t1 t2 : binary_tree_nat,\n     flatten (Node t1 t2) = (flatten t1) ++ (flatten t2)).\n\nTheorem there_is_only_one_flatten :\n  forall flatten1 flatten2 : binary_tree_nat -> list nat,\n    specification_of_flatten flatten1 ->\n    specification_of_flatten flatten2 ->\n    forall t : binary_tree_nat,\n      flatten1 t = flatten2 t.\nProof.\n  intros flatten1 flatten2.\n  unfold specification_of_flatten.\n  intros [H1_leaf H1_node] [H2_leaf H2_node].\n  intro t.\n  induction t as [n | t1 IHt1 t2 IHt2].\n\n  rewrite -> H2_leaf.\n  apply H1_leaf.\n\n  rewrite -> H1_node.\n  rewrite -> H2_node.\n  rewrite -> IHt1.\n  rewrite -> IHt2.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Version with append: *)\n\nFixpoint flatten_ds (t : binary_tree_nat) : list nat :=\n  match t with\n    | Leaf n => n :: nil\n    | Node t1 t2 => (flatten_ds t1) ++ (flatten_ds t2)\n  end.\n\nDefinition flatten_v0 (t : binary_tree_nat) : list nat :=\n  flatten_ds t.\n\n(* ********** *)\n\n(* Version with an accumulator: *)\n\nFixpoint flatten_acc (t : binary_tree_nat) (a : list nat) : list nat :=\n  match t with\n    | Leaf n => n :: a\n    | Node t1 t2 => flatten_acc t1 (flatten_acc t2 a)\n  end.\n\nDefinition flatten_v1 (t : binary_tree_nat) : list nat :=\n  flatten_acc t nil.\n\n(* ********** *)\n\nFixpoint swap_ds (t : binary_tree_nat) : binary_tree_nat :=\n  match t with\n    | Leaf n => Leaf in\n    | Node t1 t2 => Node (swap_ds t2) (swap_ds t1)\n  end.\n\nDefinition swap_v0 (t : binary_tree_nat) : binary_tree_nat :=\n  swap_ds t.\n\n(* Prove that composing swap_v0 with itself yields the identity function. *)\n\n(* ********** *)\n\n(* What is the result of applying flatten_v0\n   to the result of applying swap_v0 to a tree?\n*)\n\n(* ********** *)\n\n(* end of week_40c_flatten.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/week_40c_flatten.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.7421616180632683}}
{"text": "(* I will denote D- as a defined type. \n   For example, DTrue is defined True. *)\n\n(* -- True -- *)\n\n(* True is a single object, 1. *)\n\nInductive DTrue : Type :=\n| DTrue_I : DTrue.\n\nTheorem absurdity :\n  True.\nProof.\n  apply I. (* I is a unique object of True. *)\n  Qed.\n\nTheorem Dabsurdity :\n  DTrue.\nProof.\n  apply DTrue_I. Qed.\n\nTheorem true_useless : forall A : Prop,\n  True -> A.\nProof.\n  intro A. intro HTrue. Abort.\n  (* We can't create anything from True. *)\n\n(* -- False -- *)\n\nInductive DFalse : Type := . \n(* False is type with no element. *)\n\nTheorem false_not_provable : \n  False.\nProof.\n  Abort.\n  (* We can't prove something is false. *)\n\nTheorem false_always_true : forall A : Prop,\n  False -> A.\nProof.\n  intro A. intro HFalse. inversion HFalse. Qed.\n\nTheorem Dfalse_always_true : forall A : Prop,\n  DFalse -> A.\nProof.\n  intro A. intro HFalse. inversion HFalse. Qed.\n\nTheorem false_always_true2 : forall A : Prop,\n  1 = 2 -> A.\nProof.\n  intro A. intro Hneq. discriminate. Qed.\n\nTheorem false_is_false :\n  ~ False.\nProof.\n  intro f. apply f. Qed.\n\n(* -- Imply -- *)\n\n(* Imply is a function. \n   Actually, it is *computable* function. *)\nDefinition DImply (A : Type) (B : Type) := A -> B.\n\nTheorem Imply_prove :\n  forall (n m : nat), n = m -> S n = S m.\nProof.\n  intros n m Heq. rewrite Heq. reflexivity. Qed.\n\nTheorem Imply_left : forall (A B : Prop),\n  A -> (A -> B) -> B.\nProof.\n  intros A B HA HAB.\n  apply HAB in HA. apply HA. Qed.\n\nTheorem Imply_right : forall (A B : Prop),\n  A -> (A -> B) -> B.\nProof.\n  intros A B HA HAB.\n  apply HAB. apply HA. Qed.\n\n(* -- And -- *)\n\n(* And is simply a pair of two type. *)\nInductive DAnd (A : Type) (B : Type) :=\n| DPair (a : A) (b : B).\n\nTheorem And_left : forall A B : Prop,\n  A /\\ B -> A.\nProof.\n  intros A B HAB. destruct HAB as [HA HB]. apply HA. Qed.\n\nTheorem And_right : forall A B : Prop,\n  A /\\ B -> B.\nProof.\n  intros A B HAB. destruct HAB as [HA HB]. apply HB. Qed.\n\nTheorem And_construct : forall A B : Prop,\n  A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\n  Qed.\n\nTheorem And_commute : forall A B : Prop,\n  A /\\ B -> B /\\ A.\nProof.\n  intros A B HAB. destruct HAB as [HA HB]. split.\n  - apply HB.\n  - apply HA.\n  Qed.\n\nAxiom le_trans : forall n m l,\n  n <= m -> m <= l -> n <= l.\n\nAxiom le_false : forall n,\n  S n <= n -> False.\n\nTheorem And_ex : forall n m,\n  n <= m /\\ m <= n -> n = m.\nProof.\n  intros. destruct H as [H1 H2].\n  inversion H1.\n  - reflexivity.\n  - subst. apply le_trans with (S m0) n m0 in H2.\n    + apply le_false in H2. inversion H2.\n    + apply H.\n  Qed.\n\n(* -- Or -- *)\n\n(* Or is either a left type or right type. \n   You can think it as disjoint union.\n   More category theoritic explanation is sum. *)\nInductive DOr (A : Type) (B : Type) :=\n| DLeft (a : A)\n| DRight (b : B).\n\nTheorem Or_left : forall A B : Prop,\n  A -> A \\/ B.\nProof.\n  intros A B HA. left. apply HA. Qed.\n\nTheorem Or_right : forall A B : Prop,\n  B -> A \\/ B.\nProof.\n  intros A B HB. right. apply HB. Qed.\n\nTheorem Or_Prove : forall A B C : Prop,\n  (A -> C) -> (B -> C) -> (A \\/ B) -> C.\nProof.\n  intros A B C HAC HBC HAB.\n  destruct HAB as [HA | HB].\n  - apply HAC. apply HA.\n  - apply HBC. apply HB.\n  Qed.\n\nTheorem Or_commute : forall A B : Prop,\n  A \\/ B -> B \\/ A.\nProof.\n  intros A B HAB.\n  destruct HAB as [HA | HB].\n  - right. apply HA.\n  - left. apply HB.\n  Qed.\n\nTheorem Or_ex : forall n m,\n  n < m \\/ n = m \\/ n > m.\nProof.\n  intros. induction n.\n  - destruct m.\n    + right. left. reflexivity.\n    + left. unfold lt. apply le_n_S. apply le_0_n.\n  - destruct IHn as [H1 | [H2 | H3]].\n    + unfold lt in H1. inversion H1.\n      * right. left. reflexivity.\n      * subst. left. unfold lt. apply le_n_S. apply H.\n    + subst. right. right. unfold gt. unfold lt. apply le_n.\n    + right. right. unfold gt in *. unfold lt in *.\n      apply le_S. apply H3.\n  Qed.\n\n(* Forall *)\n\n(* Forall is a dependent function. \n   But to implement forall, you need to use forall. *)\n\n(* And you've seen all the examples before! *)\n\n(* Exists *)\n\n(* Exists is a dependent pair. *)\nInductive DExists (A : Type) (t : A -> Type) :=\n| DepPair (a : A) (b : t a).\n\nTheorem nat_0_or_minus :\n  forall (n : nat), n = 0 \\/ exists n', n = S n'.\nProof.\n  intro. destruct n.\n  - left. reflexivity.\n  - right. exists n. reflexivity.\n  Qed.\n\n(* Induction *)\nInductive even : nat -> Prop :=\n| ev_0 : even 0\n| ev_SS (n : nat) (H : even n) : even (S (S 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\nTheorem ev_4 : even 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem even_spec :\n  forall n, even n -> exists k, n = 2 * k.\nProof.\n  intros n Heven. induction Heven.\n  - exists 0. simpl. reflexivity.\n  - destruct IHHeven as [k Hk]. rewrite Hk. exists (S k).\n    simpl. apply eq_S. rewrite <- plus_n_O. apply plus_n_Sm.\n  Qed.\n\nTheorem le_spec :\n  forall n m, n <= m -> exists k, m = n + k.\nProof.\n  intros. induction H.\n  - exists 0. apply plus_n_O.\n  - destruct IHle as [k Hk].\n    exists (S k). rewrite Hk. apply plus_n_Sm.\n  Qed.\n\nCheck nat_ind.\n\n(* Recursive Functions *)\n\nFixpoint add (n m : nat) : nat :=\n  match n with\n  | 0 => m\n  | S n' => S (add n' m)\n  end.\n\n(* add is recursively defined (decreasing on 1st argument) *)\n\nFail Fixpoint false_proof (n : nat) : False :=\n  false_proof n.\n\n(* Coinduction *)\nCoInductive Seq : Type :=\n| CCons (n : nat) (S : Seq) : Seq.\n\nCoFixpoint increase (n : nat) : Seq :=\n  CCons n (increase (S n)).\n\nFail CoFixpoint wrong (n : nat) : Seq :=\n  wrong (S n).\n\n(* Equality *)\n\n(* Equality is Refl for all element of type. *)\nInductive DEqual (A : Type) :=\n| DRefl (a : A). \n\nTheorem eq_refl' : forall (A : Type) (a : A),\n  a = a.\nProof.\n  intros A a. reflexivity. Qed.\n\nTheorem eq_sym' : forall (A : Type) (a b : A) (H : a = b),\n  b = a.\nProof.\n  intros A a b Heq. rewrite Heq. reflexivity. Qed.\n\nTheorem eq_trans' : forall (A : Type) (a b c : A) \n  (H1 : a = b) (H2 : b = c),\n  a = c.\nProof.\n  intros A a b c Heq1 Heq2. rewrite Heq1. apply Heq2. Qed.\n\nTheorem homotopy_lifting_property : \n  forall (A : Type) (a b : A) (P : A -> Prop),\n  a = b -> P a -> P b.\nProof.\n  intros A a b P Heq HPa. rewrite Heq in HPa. apply HPa. Qed.\n\n(* What is unprovable? *)\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\n\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\n\nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\nTheorem em_irrefutable : forall P : Prop,\n  ~~ (P \\/ ~ P).\nProof.\n  intros P H. apply H.\n  right. intros p. apply H. left. apply p. Qed.\n\nRequire Export Coq.omega.Omega.\n\nTheorem And_auto : forall n m,\n  n <= m /\\ m <= n -> n = m.\nProof.\n  intros. omega. Qed.\n\nTheorem Or_auto : forall n m,\n  n < m \\/ n = m \\/ n > m.\nProof.\n  intros. omega. Qed.\n\n\n\n\n", "meta": {"author": "mekty2012", "repo": "sumunyeon", "sha": "cbf4f5404f582b0f7a3103950da7317dd85e84fd", "save_path": "github-repos/coq/mekty2012-sumunyeon", "path": "github-repos/coq/mekty2012-sumunyeon/sumunyeon-cbf4f5404f582b0f7a3103950da7317dd85e84fd/coq_seminar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7421352938249578}}
{"text": "(** Exercise: 2 starsM (if_minus_plus_reloaded) **)\n\n(** Fill in valid decorations for the following program:\n\n   {{ True }}\n  IFB X <= Y THEN\n      {{ True /\\ X <= Y }} ->>\n      {{ Y = X + (Y - X) }}\n    Z ::= Y - X\n      {{ Y = X + Z }}\n  ELSE\n      {{ True /\\ ~(X <= Y)}} ->>\n      {{ (X + Z) = X + Z }}\n    Y ::= X + Z\n      {{ Y = X + Z }}\n  FI\n    {{ Y = X + Z }}\n*)\n\n(* 1 -> \n{{ True /\\ X <= Y }} ->>\n      {{ Y = X + (Y - X) }}\nSi X <= Y entonces Y-X > 0, e Y-X+X = Y\n\n2 ->\n{{ True /\\ ~(X <= Y)}} ->>\n      {{ (X + Z) = X + Z }}\nSe sigue directamente.\n*)\n\n\n(** Exercise: 2 starsM (slow_assignment) **)\n\n(** (slow_assignment)  *)\n(** A roundabout way of assigning a number currently stored in [X] to\n    the variable [Y] is to start [Y] at [0], then decrement [X] until\n    it hits [0], incrementing [Y] at each step. Here is a program that\n    implements this idea:\n\n        {{ X = m }}\n      Y ::= 0;;\n      WHILE X <> 0 DO\n        X ::= X - 1;;\n        Y ::= Y + 1\n      END\n        {{ Y = m }}\n\n    Write an informal decorated program showing that this procedure \n    is correct. *)\n\n(* FILL IN HERE *)\n(* ESQUELETO *)\n(**\n      {{ X = m }} ->>\n      {{ I [Y |-> 0] }}\n      Y ::= 0;\n      WHILE X <> 0 DO\n          {{ I /\\ X <> 0 }} ->>\n          {{ I [Y |-> Y + 1] [X |-> X - 1] }}\n        X ::= X - 1;;\n          {{ I [Y |-> Y + 1]\n        Y ::= Y + 1\n          {{ I }}\n      END\n        {{ I /\\ ~(X <> 0) }}\n        {{ Y = m }}\n**)\n(* SOLUCION: Y+X=m *)\n(**\n      {{ X = m }} \n      Y :: = 0\n      {{ X = m /\\ Y = 0 }} ->>\n      {{ X + Y = m }}\n      WHILE X <> 0 DO\n          {{ Y + X = m /\\ X <> 0 }} ->>\n          {{ (Y + 1) + (X - 1) = m  }}\n        X ::= X - 1;;\n          {{ (Y + 1) + X = m }}\n        Y ::= Y + 1\n          {{ Y + X = m }}\n      END\n        {{ Y + X = m /\\ ~ (X <> 0) }}\n        {{ Y = m }}\n**)\n\n\n(** Exercise: 3 stars, optional (add_slowly_decoration) **)\n\n(** ** Exercise: Slow Addition *)\n\n(** **** Exercise: 3 stars, optional (add_slowly_decoration)  *)\n(** The following program adds the variable X into the variable Z\n    by repeatedly decrementing X and incrementing Z.\n\n      WHILE X <> 0 DO\n         Z ::= Z + 1;;\n         X ::= X - 1\n      END\n\n    Following the pattern of the [subtract_slowly] example above, pick\n    a precondition and postcondition that give an appropriate\n    specification of [add_slowly]; then (informally) decorate the\n    program accordingly. *)\n\n(* FILL IN HERE *)\n(**\n      {{ X = m /\\ Z = n }}\n      WHILE X <> 0 DO\n         Z ::= Z + 1;;\n         X ::= X - 1\n      END\n      {{ Z = n + m }} **)\n\n(* ESQUELETO: *)\n(**\n      {{ X = m /\\ Z = n }} ->>\n      {{ I }}\n      WHILE X <> 0 DO\n          {{ I /\\ X <> 0 }}\n          {{ I [X |-> X-1] [Z |-> Z +1 ] }}\n         Z ::= Z + 1;;\n          {{ I [X |-> X-1] }}\n         X ::= X - 1\n          {{ I }}\n      END\n      {{ I /\\ ~ (X <> 0) }} ->>\n      {{ Z = n + m }} **)\n      \n(* SOLUCION: I = Z + X = n + m *)\n(**\n      {{ X = m /\\ Z = n }} ->>\n      {{ Z + X = n + m }}\n      WHILE X <> 0 DO\n          {{ Z + X = n + m /\\ X <> 0 }} ->>\n          {{ (Z + 1) + (X - 1) = n + m }}\n         Z ::= Z + 1;;\n          {{ Z + (X - 1) = n + m }}\n         X ::= X - 1\n          {{ Z + X = n + m }}\n      END\n      {{ Z + X = n + m /\\ ~ (X <> 0) }} ->>\n      {{ Z = n + m }} \n**)\n\n\n\n(** Exercise: 3 stars, optional (add_slowly_decoration) **)\n\n(** ** Exercise: Slow Addition *)\n\n(** **** Exercise: 3 stars, optional (add_slowly_decoration)  *)\n(** The following program adds the variable X into the variable Z\n    by repeatedly decrementing X and incrementing Z.\n\n      WHILE X <> 0 DO\n         Z ::= Z + 1;;\n         X ::= X - 1\n      END\n\n    Following the pattern of the [subtract_slowly] example above, pick\n    a precondition and postcondition that give an appropriate\n    specification of [add_slowly]; then (informally) decorate the\n    program accordingly. *)\n\n(* FILL IN HERE *)\n(**\n      {{ X = m /\\ Z = n }}\n      WHILE X <> 0 DO\n         Z ::= Z + 1;;\n         X ::= X - 1\n      END\n      {{ Z = n + m }} **)\n\n(* ESQUELETO: *)\n(**\n      {{ X = m /\\ Z = n }} ->>\n      {{ I }}\n      WHILE X <> 0 DO\n          {{ I /\\ X <> 0 }}\n          {{ I [X |-> X-1] [Z |-> Z +1 ] }}\n         Z ::= Z + 1;;\n          {{ I [X |-> X-1] }}\n         X ::= X - 1\n          {{ I }}\n      END\n      {{ I /\\ ~ (X <> 0) }} ->>\n      {{ Z = n + m }} **)\n      \n(* SOLUCION: I = Z + X = n + m *)\n(**\n      {{ X = m /\\ Z = n }} ->>\n      {{ Z + X = n + m }}\n      WHILE X <> 0 DO\n          {{ Z + X = n + m /\\ X <> 0 }} ->>\n          {{ (Z + 1) + (X - 1) = n + m }}\n         Z ::= Z + 1;;\n          {{ Z + (X - 1) = n + m }}\n         X ::= X - 1\n          {{ Z + X = n + m }}\n      END\n      {{ Z + X = n + m /\\ ~ (X <> 0) }} ->>\n      {{ Z = n + m }} \n**)\n\n\n(** Exercise: 3 stars, optional (parity_formal) **)\n\n(** Translate this proof to Coq. Refer to the reduce-to-zero example\n    for ideas. You may find the following two lemmas useful: *)\n\nLemma parity_ge_2 : forall x,\n  2 <= x ->\n  parity (x - 2) = parity x.\nProof.\n  induction x; intro. reflexivity.\n  destruct x. inversion H. inversion H1.\n  simpl. rewrite <- minus_n_O. reflexivity.\nQed.\n\nLemma parity_lt_2 : forall x,\n  ~ 2 <= x ->\n  parity (x) = x.\nProof.\n  intros. induction x. reflexivity. destruct x. reflexivity.\n    exfalso. apply H. omega.\nQed.\n\nTheorem parity_correct : forall m,\n    {{ fun st => st X = m }}\n  WHILE BLe (ANum 2) (AId X) DO\n    X ::= AMinus (AId X) (ANum 2)\n  END\n    {{ fun st => st X = parity m }}.\nProof.\n  intros.\n  eapply hoare_consequence_pre with (fun st => parity (st X) = parity m).\n  eapply hoare_consequence_post.\n  apply hoare_while.\n  - eapply hoare_consequence_pre.\n  apply hoare_asgn.\n  intros st H. unfold assn_sub, t_update. simpl.\n  inversion H. rewrite -> parity_ge_2. \n  assumption. \n  unfold bassn in H1.\n  apply ble_nat_true in H1. \n  assumption.\n  - intros st [H1 H2]. \n    rewrite <- H1. symmetry. apply parity_lt_2.\n    unfold not. intros. unfold bassn in H2; simpl in H2.\n    destruct (st X). omega. destruct n. omega. apply H2. reflexivity.\n  - intros st H. rewrite H; reflexivity.\nQed.\n\n\n\n(** Exercise: 3 starsM (factorial) **)\n(** Recall that [n!] denotes the factorial of [n] (i.e., [n! =\n    1*2*...*n]).  Here is an Imp program that calculates the factorial\n    of the number initially stored in the variable [X] and puts it in\n    the variable [Y]:\n\n    {{ X = m }}\n  Y ::= 1 ;;\n  WHILE X <> 0\n  DO\n     Y ::= Y * X ;;\n     X ::= X - 1\n  END\n    {{ Y = m! }}\n\n\n    Fill in the blanks in following decorated program:\n\n    {{ X = m }} ->>\n    {{ X! = m! }}\n  Y ::= 1;;\n    {{ X! * Y = m! }}\n  WHILE X <> 0 DO   \n       {{ X! * Y = m! /\\ X <> 0 }} ->>\n       {{ (X - 1)! * Y*X = m! }}                                     }}\n     Y ::= Y * X;;\n       {{ (X - 1)! * Y = m! }}\n     X ::= X - 1\n       {{ X! * Y = m! }}                                }}\n  END\n    {{ X! * Y = m! ~ (X <> 0) }} ->>\n    {{ Y = m! }}\n*)\n\n\n\n\n(** Exercise: 3 starsM (Min_Hoare) **)\n(* ================================================================= *)\n(** ** Exercise: Min *)\n\n(** **** Exercise: 3 stars (Min_Hoare)  *)\n(** Fill in valid decorations for the following program.\n  For the [=>] steps in your annotations, you may rely (silently) \n  on the following facts about min **)\n\n  Lemma lemma1 : forall x y,\n    (x=0 \\/ y=0) -> min x y = 0.\n  Lemma lemma2 : forall x y,\n    min (x-1) (y-1) = (min x y) - 1.\n\n(**\n  plus standard high-school algebra, as always.\n\n\n  {{ True }} ->>\n  {{ min (a,b) = min (a,b) }}\n  X ::= a;;\n  {{ min (X,b) = min (a,b) }}\n  Y ::= b;;\n  {{ 0 + min (X,Y) = min (a,b) }}\n  Z ::= 0;;\n  {{ Z + min (X,Y) = min (a,b) }}\n  WHILE (X <> 0 /\\ Y <> 0) DO\n      {{ Z + min (X,Y) = min (a,b)\n            /\\ X <> 0 /\\ Y <> 0 }} ->>\n      {{ Z+1 + min (X-1,Y-1) = min (a,b) }}\n    X := X - 1;;\n      {{ Z+1 + min (X,Y-1) = min (a,b) }}\n    Y := Y - 1;;\n      {{ Z+1 + min (X,Y) = min (a,b) }}\n    Z := Z + 1\n      {{ Z + min (X,Y) = min (a,b) }}\n  END\n    {{ Z + min (X,Y) = min (a,b) \n              /\\ (X = 0 \\/ Y = 0) }} ->>\n    {{ Z = min a b }}\n*)\n\n(* INVARIANTE: Z + min (X,Y) = min (a,b) *)\n\n(* A lo largo del bucle, siempre se cumple\nque al sumar Z conel mínimo de X e Y este valor\ncoincide con el mínimo de los valores iniciales\nde X e Y (en este caso a y b).\nPor eso probamos esta opcion *)\n\n\n\n\n(** Exercise: 3 starsM (two_loops) **)\n(** Here is a very inefficient way of adding 3 numbers:\n\n  X ::= 0;;\n  Y ::= 0;;\n  Z ::= c;;\n  WHILE X <> a DO\n    X ::= X + 1;;\n    Z ::= Z + 1\n  END;;\n  WHILE Y <> b DO\n    Y ::= Y + 1;;\n    Z ::= Z + 1\n  END\n\n\n    Show that it does what it should by filling in the blanks in the\n    following decorated program.\n\n\n    {{ True }} ->>\n    {{ c = c }}\n  X ::= 0;;\n    {{ c = X + c }}\n  Y ::= 0;;\n    {{ c = X + Y + c }}\n  Z ::= c;;\n    {{ Z = X + Y + c }}\n  WHILE X <> a DO\n      {{ Z = X + Y + c /\\ X <> a }} ->>\n      {{ (Z+1) = (X+1) + Y + c }}\n    X ::= X + 1;;\n      {{ (Z+1) = X + Y + c }}\n    Z ::= Z + 1\n      {{ Z = X + Y + c }}\n  END;;\n    {{ Z = X + Y + c /\\ X = a }} ->>\n    {{ Z = a + Y + c }}\n  WHILE Y <> b DO\n      {{ Z = a + Y + c /\\ Y <> b }} ->>\n      {{ Z+1 = a + Y+1 + c }}\n    Y ::= Y + 1;;\n      {{ Z+1 = a + Y + c }}\n    Z ::= Z + 1\n      {{ Z = a + Y + c }}\n  END\n    {{ Z = a + Y + c /\\ Y = b }} ->>\n    {{ Z = a + b + c }}\n*)\n\n(** [] *)\n\n(* INVARIANTE 1: Z = X + Y + c *)\n(* INVARIANTE 2: Z = a + Y + c *)\n\n(* Al final del primer bucle X vale a,\nluego permanece invariante en el segundo. \nAl final del segundo Y valdrá b,\npero Y y Z cambian. \nLa c siempre permanece inalterada *)\n\n\n\n\n(** \"EJERCICIO: \" Power Series *)\n(** Exercise: 4 stars, optional (dpow2_down) **)\n(** Here is a program that computes the series:\n    [1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1]\n\n  X ::= 0;;\n  Y ::= 1;;\n  Z ::= 1;;\n  WHILE X <> m DO\n    Z ::= 2 * Z;;\n    Y ::= Y + Z;;\n    X ::= X + 1\n  END\n\n    Write a decorated program for this. *)\n\n(* FILL IN HERE *)\n\n(* Haciendo cuentas en papel con ejemplos\nllegamos a la posibilidad del siguiente\ninvariante:\n  Y = 2 * Z - 1 /\\ Z = 2 ^ X \n*)\n(*\n    {{ True }} ->>\n    {{ 1 = 1 /\\ 1 = 2^0 }}\n  X ::= 0;;\n    {{ 1 = 1 /\\ 1 = 2 ^ X  }}\n  Y ::= 1;;\n    {{ Y = 2 - 1 /\\ 1 = 2 ^ X  }}\n  Z ::= 1;;\n    {{ Y = 2 * Z - 1 /\\ Z = 2 ^ X  }}\n  WHILE X <> m DO\n      {{ Y = 2 * Z - 1 /\\ Z = 2 ^ X\n               /\\ X <> m }} ->>\n      {{ Y + 2 * Z = 2 * 2 * Z - 1 \n           /\\ 2 * Z = 2 ^ (X + 1) }}\n    Z ::= 2 * Z ;;\n      {{ Y + Z = 2 * Z - 1 \n           /\\ Z = 2 ^ (X + 1) }}\n    Y ::= Y + Z;;\n      {{ Y = 2 * Z - 1 /\\ Z = 2 ^ (X + 1) }}\n    X ::= X + 1\n      {{ Y = 2 * Z - 1 /\\ Z = 2 ^ X }}\n  END\n    {{ Y = 2 * Z - 1 /\\ Z = 2 ^ X\n           /\\ X = m }} ->>\n    {{ Y = 2 * Z - 1 /\\ Z = 2 ^ m }}\n*)\n\n(* Efectivamente, y es la suma de las potencias\nde 2 y, además, en la posconticion\nse cumple que Y = 2*(m+1)-1.\nPor lo tanto, este invariante es válido\n(comprobando que, además,\nse cumplen todas las implicaciones ->> *)\n\n\n(** Exercise: 1 star, optional (wp) **)\n\n(** \"EJERCICIO: \" **)\n(** What are the weakest preconditions of the following commands\n   for the following postconditions?\n\n  1) {{ ? }}  SKIP  {{ X = 5 }}\n      X = 5\n\n  2) {{ ? }}  X ::= Y + Z {{ X = 5 }}\n      Y + Z = 5\n\n  3) {{ ? }}  X ::= Y  {{ X = Y }}\n      True\n\n  4) {{ ? }}\n     IFB X == 0 THEN Y ::= Z + 1 ELSE Y ::= W + 2 FI\n     {{ Y = 5 }}\n      (X = 0 /\\ Z = 4) \\/ (X <> 0 /\\ W = 3)\n\n  5) {{ ? }}\n     X ::= 5\n     {{ X = 0 }}\n      False\n\n  6) {{ ? }}\n     WHILE True DO X ::= 0 END\n     {{ X = 0 }}\n      True\n*)\n\n\n\n\n(** Exercise: 3 stars, advanced, optional (is_wp_formal) **)\n(** Prove formally, using the definition of [hoare_triple], that [Y <= 4]\n   is indeed the weakest precondition of [X ::= Y + 1] with respect to\n   postcondition [X <= 5]. *)\n\nTheorem is_wp_example :\n  is_wp (fun st => st Y <= 4)\n    (X ::= APlus (AId Y) (ANum 1)) (fun st => st X <= 5).\nProof.\n  unfold is_wp. split.\n  - eapply hoare_consequence_pre.\n    apply hoare_asgn. intros st H.\n    unfold assn_sub, t_update. simpl.\n    omega.\n  - intros P' H. \n    unfold assert_implies. intros st HP'.\n    unfold hoare_triple in H.\n    apply H with \n      (st' := t_update st X (st Y + 1)) in HP'.\n    + unfold t_update in HP'. simpl in HP'. \n      omega.\n    + constructor. simpl. reflexivity.\nQed.\n    \n    \n    \n(** Exercise: 2 stars, advanced, optional (hoare_asgn_weakest) **)\n(** Show that the precondition in the rule [hoare_asgn] is in fact the\n    weakest precondition. *)\n\nTheorem hoare_asgn_weakest : forall Q X a,\n  is_wp (Q [X |-> a]) (X ::= a) Q.\nProof.\n  intros Q X a. \n  unfold is_wp. split.\n  - apply hoare_asgn.\n  - intros P' H. unfold assert_implies.\n    intros st HP'.\n    unfold hoare_triple in H.\n    apply H with \n      (st' := t_update st X (aeval st a)) in HP'.\n    + apply HP'.\n    + constructor. reflexivity.\nQed.\n\n\n\n(** Exercise: 3 stars, advanced (slow_assignment_dec) **)\n(** In the [slow_assignment] exercise above, we saw a roundabout way\n    of assigning a number currently stored in [X] to the variable [Y]:\n    start [Y] at [0], then decrement [X] until it hits [0],\n    incrementing [Y] at each step.  Write a formal version of this\n    decorated program and prove it correct. *)\n\n(**\n      {{ X = m }} \n      Y :: = 0\n      {{ X = m /\\ Y = 0 }} ->>\n      {{ X + Y = m }}\n      WHILE X <> 0 DO\n          {{ Y + X = m /\\ X <> 0 }} ->>\n          {{ (Y + 1) + (X - 1) = m  }}\n        X ::= X - 1;;\n          {{ (Y + 1) + X = m }}\n        Y ::= Y + 1\n          {{ Y + X = m }}\n      END\n        {{ Y + X = m /\\ ~ (X <> 0) }}\n        {{ Y = m }}\n**)\n\nExample slow_assignment_dec (m:nat) : dcom := (\n    {{ fun st => st X = m }}\n  Y ::= ANum 0\n    {{ fun st => st X = m  /\\ st Y = 0}} ->>\n    {{ fun st => st X + st Y = m }} ;;\n  WHILE BNot (BEq (AId X) (ANum 0))\n  DO {{ fun st => st Y + st X = m /\\ st X <> 0 }} ->>\n     {{ fun st => (st Y + 1) + (st X - 1) = m }}\n    X ::= AMinus (AId X) (ANum 1)\n     {{ fun st => (st Y + 1) + st X = m }} ;;\n    Y ::= APlus (AId Y) (ANum 1)\n     {{ fun st => st Y + st X = m }}\n  END\n    {{ fun st => st Y + st X = m /\\ st X = 0 }} ->>\n    {{ fun st => st Y = m }}\n) % dcom.\n\nTheorem slow_assignment_dec_correct : forall m,\n  dec_correct (slow_assignment_dec m).\nProof.\n  intros m. verify. Qed.\n\n", "meta": {"author": "mm04", "repo": "Ejercicios-Coq-tfg", "sha": "0ee5b9195b749fe458653d67549df399afc9c87d", "save_path": "github-repos/coq/mm04-Ejercicios-Coq-tfg", "path": "github-repos/coq/mm04-Ejercicios-Coq-tfg/Ejercicios-Coq-tfg-0ee5b9195b749fe458653d67549df399afc9c87d/Hoare2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.742135285466862}}
{"text": "From Coq Require Import List.\nFrom StructTact Require Import StructTactics ListUtil.\nFrom Coq Require Import OrderedType OrderedTypeEx.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nFixpoint fin (n : nat) : Type :=\n  match n with\n    | 0 => False\n    | S n' => option (fin n')\n  end.\n\nFixpoint fin_eq_dec (n : nat) : forall (a b : fin n), {a = b} + {a <> b}.\n  refine\n   (match n with\n      | 0 => fun a b : fin 0 => right (match b with end)\n      | S n' => fun a b : fin (S n') =>\n                 match a, b with\n                   | Some a', Some b' =>\n                     match fin_eq_dec n' a' b' with\n                       | left _ _ => left _\n                       | right _ _ => right _\n                     end\n                   | Some a', None => right _\n                   | None, Some b' => right _\n                   | None, None => left eq_refl\n                 end\n    end); congruence.\nDefined.\n\nFixpoint all_fin (n : nat) : list (fin n) :=\n  match n with\n    | 0 => []\n    | S n' => None :: map (fun x => Some x) (all_fin n')\n  end.\n\nLemma all_fin_all :\n  forall n (x : fin n),\n    In x (all_fin n).\nProof.\n  induction n; intros.\n  - solve_by_inversion.\n  - simpl in *. destruct x; auto using in_map.\nQed.\n\nLemma all_fin_NoDup :\n  forall n, NoDup (all_fin n).\nProof.\n  induction n; intros; simpl; constructor.\n  - intro. apply in_map_iff in H. firstorder. discriminate.\n  - apply NoDup_map_injective; auto. congruence.\nQed.\n\nFixpoint fin_to_nat {n : nat} : fin n -> nat :=\n  match n with\n  | 0 => fun x : fin 0 => match x with end\n  | S n' => fun x : fin (S n') =>\n             match x with\n             | None => 0\n             | Some y => S (fin_to_nat y)\n             end\n  end.\n\nDefinition fin_lt {n : nat} (a b : fin n) : Prop := lt (fin_to_nat a) (fin_to_nat b).\n\nLemma fin_lt_Some_elim :\n  forall n (a b : fin n), \n    @fin_lt (S n) (Some a) (Some b) -> fin_lt a b.\nProof.\n  intros.\n  unfold fin_lt.\n  intuition auto with arith.\nQed.\n\nLemma fin_lt_Some_intro :\n  forall n (a b : fin n), \n    fin_lt a b -> @fin_lt (S n) (Some a) (Some b).\nProof.\n  intros.\n  unfold fin_lt. simpl.\n  intuition auto with arith.\nQed.\n\nLemma None_lt_Some :\n  forall n (x : fin n),\n    @fin_lt (S n) None (Some x).\nProof.\n  unfold fin_lt. simpl. auto with arith.\nQed.\n\nLemma fin_lt_trans : \n  forall n (x y z : fin n),\n    fin_lt x y -> fin_lt y z -> fin_lt x z.\nProof.\n  induction n; intros.\n  - destruct x.\n  - destruct x, y, z; simpl in *;\n    repeat match goal with\n    | [ H : fin_lt (Some _) (Some _) |- _ ] => apply fin_lt_Some_elim in H\n    | [ |- fin_lt (Some _) (Some _) ] => apply fin_lt_Some_intro\n    end; eauto using None_lt_Some; solve_by_inversion.\nQed.\n\nLemma fin_lt_not_eq : \n  forall n (x y : fin n), \n    fin_lt x y -> x <> y.\nProof.\n  induction n; intros.\n  - destruct x.\n  - destruct x, y;\n    repeat match goal with\n    | [ H : fin_lt (Some _) (Some _) |- _ ] => apply fin_lt_Some_elim in H\n    | [ |- fin_lt (Some _) (Some _) ] => apply fin_lt_Some_intro\n    end; try congruence.\n    + specialize (IHn f f0). concludes. congruence.\n    + solve_by_inversion.\nQed.\n\nFixpoint fin_compare_compat (n : nat) : forall (x y : fin n), Compare fin_lt eq x y :=\n  match n with\n    | 0 => fun x y : fin 0 => match x with end\n    | S n' => fun x y : fin (S n') =>\n               match x, y with\n                 | Some x', Some y' =>\n                   match fin_compare_compat n' x' y' with\n                     | LT pf => LT (fin_lt_Some_intro pf)\n                     | EQ pf => EQ (f_equal _ pf)\n                     | GT pf => GT (fin_lt_Some_intro pf)\n                   end\n                 | Some x', None => GT (None_lt_Some n' x')\n                 | None, Some y' => LT (None_lt_Some n' y')\n                 | None, None => EQ eq_refl\n               end\n  end.\n\nModule Type NatValue.\n  Parameter n : nat.\nEnd NatValue.\n\nModule fin_OT_compat (Import N : NatValue) <: UsualOrderedType.\n  Definition t := fin n.\n  Definition eq := @eq (fin n).\n  Definition lt := @fin_lt n.\n  Definition eq_refl := @eq_refl (fin n).\n  Definition eq_sym := @eq_sym (fin n).\n  Definition eq_trans := @eq_trans (fin n).\n  Definition lt_trans := @fin_lt_trans n.\n  Definition lt_not_eq := @fin_lt_not_eq n.\n  Definition compare := fin_compare_compat n.\n  Definition eq_dec := fin_eq_dec n.\nEnd fin_OT_compat.\n\nFrom Coq Require Import Arith Orders.\n\nLemma fin_lt_irrefl : \n  forall n, Irreflexive (@fin_lt n).\nProof.\n  intros.\n  unfold Irreflexive, complement, Reflexive, fin_lt.\n  intros x.\n  apply Nat.lt_irrefl.\nQed.\n\nLemma fin_lt_strorder :\n  forall n, StrictOrder (@fin_lt n).\nProof.\n  intros.\n  apply (Build_StrictOrder _ (@fin_lt_irrefl n) (@fin_lt_trans n)).\nQed.\n\nLemma fin_lt_lt_compat : \n  forall n, Proper (eq ==> eq ==> iff) (@fin_lt n).\nProof.\n  intros; split; intros; repeat find_rewrite; assumption.\nQed.\n\nLemma CompSpec_Eq_Some : \n  forall n' (x' y' : fin n'),\n    CompSpec eq fin_lt x' y' Eq ->\n    Some x' = Some y'.\nProof.\n  intros.\n  apply f_equal.\n  solve_by_inversion.\nQed.\n\nLemma CompSpec_Lt : \n  forall n' (x' y' : fin n'),\n    CompSpec eq fin_lt x' y' Lt ->\n    fin_lt x' y'.\nProof.\n  intros.\n  solve_by_inversion.\nQed.\n\nLemma CompSpec_Gt : \n  forall n' (x' y' : fin n'),\n    CompSpec eq fin_lt x' y' Gt ->\n    fin_lt y' x'.\nProof.\n  intros.\n  solve_by_inversion.\nQed.\n\nFixpoint fin_compare (n : nat) :\n  forall (x y : fin n), { cmp : comparison | CompSpec eq fin_lt x y cmp } :=\n  match n with\n    | 0 => fun x y : fin 0 => match x with end\n    | S n' => fun x y : fin (S n') =>\n             match x, y with\n               | Some x', Some y' =>\n                 match fin_compare n' x' y' with\n                   | exist _ Lt Hc => exist _ Lt (CompLt _ _ (fin_lt_Some_intro (CompSpec_Lt Hc)))\n                   | exist _ Eq Hc => exist _ Eq (CompEq _ _ (CompSpec_Eq_Some Hc))\n                   | exist _ Gt Hc => exist _ Gt (CompGt _ _ (fin_lt_Some_intro (CompSpec_Gt Hc)))\n                 end\n               | Some x', None => exist _ Gt (CompGt _ _ (None_lt_Some n' x'))\n               | None, Some y' => exist _ Lt (CompLt _ _ (None_lt_Some n' y'))\n               | None, None => exist _ Eq (CompEq _ _ eq_refl)\n             end\n  end.\n\nModule fin_OT (Import N : NatValue) <: UsualOrderedType.\n  Definition t := fin n.\n  Definition eq := @eq (fin n).\n  Definition eq_equiv := @eq_equivalence (fin n).\n  Definition lt := @fin_lt n.\n  Definition lt_strorder := fin_lt_strorder n.\n  Definition lt_compat := fin_lt_lt_compat n.\n  Definition compare := fun x y => proj1_sig (fin_compare n x y).\n  Definition compare_spec := fun x y => proj2_sig (fin_compare n x y).\n  Definition eq_dec := fin_eq_dec n.\nEnd fin_OT.\n\nFixpoint fin_of_nat (m n : nat) : fin n + {exists p, m = n + p} :=\n  match n with\n    | 0 => inright (ex_intro _ _ eq_refl)\n    | S n' =>\n      match m with\n        | 0 => inleft None\n        | S m' =>\n          match fin_of_nat m' n' with\n            | inleft f => inleft (Some f)\n            | inright pf =>\n              inright (match pf with\n                         | ex_intro _ x H => ex_intro _ x (f_equal _ H)\n                       end)\n          end\n    end\n  end.\n\nLemma fin_of_nat_fin_to_nat :\n  forall (n : nat) (a : fin n),\n    fin_of_nat (fin_to_nat a) n = inleft a.\nProof.\n  induction n; simpl; intuition.\n  destruct a; simpl in *; auto.\n  now rewrite IHn.\nQed.\n", "meta": {"author": "uwplse", "repo": "StructTact", "sha": "2f2ff253be29bb09f36cab96d036419b18a95b00", "save_path": "github-repos/coq/uwplse-StructTact", "path": "github-repos/coq/uwplse-StructTact/StructTact-2f2ff253be29bb09f36cab96d036419b18a95b00/theories/Fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7421352774551372}}
{"text": "Require Import Nat.\nRequire Import ZArith.\nRequire Import Lia.\n\n\nTheorem thm1: forall n m,\n n <= m -> exists k, n + k = m.\nintros n m H. generalize dependent n.\ninduction m as [| m' IH].\n- intros n H. inversion H.\n  exists 0. lia.\n- intros n H.\n  inversion H.\n  exists 0. lia.\n  apply IH in H1. destruct H1 as [k H1].\n  exists (S k). lia.\nQed.\n", "meta": {"author": "1995hnagamin", "repo": "proof", "sha": "10dd0b6a46dd25e890059915a35b6d6156cc658b", "save_path": "github-repos/coq/1995hnagamin-proof", "path": "github-repos/coq/1995hnagamin-proof/proof-10dd0b6a46dd25e890059915a35b6d6156cc658b/2022/2022-09-12-nat/leqexist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474142844408, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.7420472927441654}}
{"text": "(* A stub library on generalized harmonic numbers. *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nRequire Import tactics shift bigopz.\n\nImport Order.TTheory GRing.Theory Num.Theory.\n\nLocal Open Scope ring_scope.\n\n(* Definition of the generalized harmonic numbers, indexed by ints. *)\n(* The first argument stays in nat. *)\nDefinition ghn (m : nat) (n : int) : rat :=\n  \\sum_(1 <= k < n + 1 :> int) (k %:Q ^ m)^-1.\n\nLemma ghn_Sn_inhom m n : n >= 0 ->\n  ghn m (int.shift 1 n) = ghn m n + ((n%:Q + 1)^m)^-1.\nProof.\nmove=> pn. \nrewrite /ghn int.shift2Z big_int_recr /= ?rmorphD //=.\nby rewrite -ler_subl_addr.\nQed.\n\nLemma ghn_small (m : nat) (n : int) : n <= 0 -> ghn m n = 0.\nProof. by move=> hn; rewrite /ghn big_geqz // ger_addr. Qed.\n\nLemma ghn1 (m : nat) : ghn m 1 = 1.\nProof. by rewrite /ghn big_int_recr //= big_nil add0r exp1rz. Qed.\n\nLemma ghn_Sn2 m (n_ : int) (n := n_%:Q) :  n_ + 1 != 0 -> \n  ghn m (int.shift 2 n_) =\n    ((n + 1) ^ m / (n + 2%:Q) ^ m + 1) * ghn m (int.shift 1 n_)\n    - (n + 1) ^ m / (n + 2%:Q) ^ m * ghn m n_.\nProof.\nmove=> pn2.\ncase: (leP n_ 0) => hn.\n  rewrite [in X in _ = _ - X]ghn_small // mulr0 subr0.\n  rewrite {}/n; case: n_ pn2 hn => [ [] //  _ _ | n hn2].\n    rewrite -[int.shift  2 0]/(int.shift 1 (int.shift 1 0)) [LHS]ghn_Sn_inhom //.\n    by rewrite !int.shift2Z !add0r exp1rz mulrDl !mul1r addrC ghn1 mulr1.\n  case: n hn2 => [| n] hn //.\n  by rewrite !ghn_small ?mulr0 // NegzE int.shift2Z addrC !subzSS add0r oppr_le0.\nrewrite ?ghn_Sn_inhom ?ltW ?addr_gt0 //=.\nrewrite int.shift2R -/n.\nmove: (ghn m n_) => x.\napply/eqP; rewrite -subr_eq0 -!addrA addr_eq0; apply/eqP.\nelim: m => [|m ->]; first by field => //.\n(* The ring tactic is not able to reason under (_ ^ m) where m is a variable:\n   we have to expand (_ ^_.+1) and identify p2 and p3 by hand... *)\nrewrite !exprSz.\nby field; rewrite /= !expfz_eq0; ring_lia.\nQed.\n", "meta": {"author": "coq-community", "repo": "apery", "sha": "305046d98025d75ca426cc44283302963389f1dc", "save_path": "github-repos/coq/coq-community-apery", "path": "github-repos/coq/coq-community-apery/apery-305046d98025d75ca426cc44283302963389f1dc/theories/harmonic_numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.843895100591521, "lm_q1q2_score": 0.7419076578185664}}
{"text": "Require Export Basics.\n\nModule NatList.\n\nInductive natprod : Type :=\n  pair : nat -> nat -> natprod.\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\nNotation \"( x , y )\" := (pair x y).\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\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAdmitted.\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\nRequire Unicode.Utf8.\n\nTheorem snd_fst_is_swap : ∀p:natprod,\n  (snd p,fst p) = swap_pair p.\nProof.\n  intros p. \n  destruct p.\n  simpl. reflexivity.\n  Qed.\n\nTheorem fst_swap_is_snd :∀p:natprod,\n  fst (swap_pair p) = snd p.\nProof.\n  intros p.\n  destruct p.\n  simpl. reflexivity.\n  Qed.\n\nInductive natlist : Type :=\n  | nil: natlist\n  | cons: nat -> natlist -> natlist.\n\nDefinition mylist:=cons 1 (cons 2 (cons 3 nil)).\n\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1,2,3].\n\nEval simpl in 1+2.\n\nEval simpl in 1+2::[3].\n\nFixpoint repeat (n count:nat):natlist:=\n  match count with\n  | 0=> nil\n  | S count'=>n::(repeat n count')\n  end.\n\nEval simpl in repeat 2 10.\n\nFixpoint length (l:natlist):nat:=\n  match l with\n  | nil =>0\n  | h::t=>S (length t)\n  end.\n\nEval simpl in length (repeat 2 19).\n\n\nFixpoint app (l1 l2:natlist) :natlist:=\n  match l1 with\n  | nil=>l2\n  |h::t=>h::(app t l2)\n  end.\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\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\nFixpoint nonzeros(l:natlist):natlist:=\n  match l with\n  | nil=>nil\n  | 0::t=>nonzeros t\n  | h::t=>h::nonzeros t\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:=\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. simpl. 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\n\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\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\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\nDefinition bag:=natlist.\n\nFixpoint count(v:nat)(s:bag):nat:=\n  match s with\n  |nil=>0\n  |h::t => \n    match beq_nat v h with\n    | true => 1+count v t\n    | false => count v t\n    end\n  end.\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\nDefinition sum : bag -> bag -> bag := app.\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 := cons 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 0 (count v s)).\n\nExample test_member1: member 1 [1,4,1] = true.\n  Proof. simpl. reflexivity. Qed.\nExample test_member2: member 2 [1,4,1] = false.\n  Proof. simpl. reflexivity. Qed.\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 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  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:\n  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=>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.\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 => 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.\n  Proof. simpl. reflexivity. Qed.\nExample test_subset2: subset [1,2,2] [2,1,4,1] = false.\n  Proof. simpl. reflexivity. Qed.\n\nTheorem count_nil:∀n:nat, count n []=0.\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem add_nil:∀n:nat,add n []=[n].\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem beq_true:∀n:nat,beq_nat n n=true.\nProof. intros. induction n.\n Case \"n=0\". simpl. reflexivity.\n Case\"n=Sn\".  simpl. rewrite->IHn. reflexivity. Qed.\n\n\nTheorem bag_count_add:∀n:nat,∀s:bag,\ncount n (add n s)= S (count n s).\nProof.\n  intros n s.\n  induction n as [|n'].\n  Case \"n=0\". simpl. reflexivity.\n  Case \"n=S n'\". simpl. rewrite->beq_true. reflexivity.\nQed.\n\n(**************** Reasoning About Lists ****************)\n\nTheorem nil_app : ∀l:natlist,\n  [] ++ l = l.\nProof.\n   reflexivity. Qed.\n\nTheorem tl_length_pred : ∀l:natlist,\n  pred (length l) = length (tail l).\nProof.\n  intros l. (* why not induction? ie induction l as [|l'].*)\n destruct l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\".\n    reflexivity. Qed.\n\n\n(* ###################################################### *)\n(** ** Induction on Lists *)\n\n\nTheorem app_ass : ∀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\nTheorem app_length : ∀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\". simpl.\n    reflexivity.\n  Case \"l1 = cons\".\n    simpl. rewrite -> IHl1'. reflexivity. Qed.\n\n(*Fixpoint rev (l:natlist):natlist :=\n  match l with\n  |nil=>nil\n  |h::t=>rev t++cons h nil\nend.*)\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    simpl. 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\nTheorem snoc_append : ∀l:natlist, ∀n:nat,\n  snoc l n = l ++ [n].\nProof.\n  intros l n. induction l as [|n' l'].\n  Case \"l=[]\". simpl. reflexivity.\n  Case \"l=n'::l'\". simpl. rewrite <- IHl'. reflexivity. Qed.\n\n\nSearchAbout rev.\n\n(* ###################################################### *)\n(** ** List Exercises, Part 1 *)\n\nTheorem app_nil_end : ∀l : natlist,\n  l ++ [] = l.\nProof.\n intros l. induction l as [|n l'].\n  Case \"l=[]\". simpl. reflexivity.\n  Case \"l= n::l'\".\n    simpl. rewrite -> IHl'. reflexivity. Qed.\n\nTheorem rev_id :∀n:nat,rev [n]=[n].\nProof. intros n. simpl. reflexivity. Qed.\n\n\nTheorem rev_dist :∀l1 l2:natlist,\nrev(l1++l2)=rev l2++rev l1.\nProof. intros l1 l2. induction l1 as [|n l1'].\n  Case \"l1=[]\". simpl. rewrite->app_nil_end. reflexivity.\n  Case \"l1=n::l1'\".\n  simpl. rewrite->IHl1'. \n  rewrite->snoc_append. rewrite->snoc_append. \n  rewrite->app_ass. reflexivity. Qed.\n\n\nTheorem rev_involutive : ∀l : natlist,\n  rev (rev l) = l.\nProof.\n intros l. induction l as [|n l'].\n Case\"l=[]\". simpl. reflexivity.\n Case\"l=n::l'\".\n simpl. rewrite->snoc_append. \n rewrite->rev_dist. rewrite->IHl'. simpl. reflexivity. Qed.\n\nTheorem distr_rev : ∀l1 l2 : natlist,\n  rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  intros l1 l2. rewrite->rev_dist. reflexivity. Qed.\n\nTheorem app_ass4 : ∀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. Qed.\n\n\nLemma nonzeros_length : ∀l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [|n l1'].\n  Case \"l1=[]\". simpl. reflexivity.\n  Case \"l1=n::l1'\". induction n.\n    SCase \"n=0\". simpl. rewrite->IHl1'. reflexivity.\n    SCase \"n=Sn\". simpl. rewrite->IHl1'. reflexivity. Qed.\n\n(* ###################################################### *)\n(** ** List Exercises, Part 2 *)\n\nTheorem cons_snoc_append:∀l1 l2:natlist,∀n1 n2:nat,\n  cons n1 l1++snoc l2 n2 = snoc (cons n1 (l1++l2)) n2.\nProof.\n  intros l1 l2 n1 n2. induction l1 as [|n1' l1'].\n  Case \"l1=[]\". simpl. reflexivity.\n  Case \"l1=n1'::l1'\".\n  simpl. \n  rewrite->snoc_append. rewrite->snoc_append. rewrite->app_ass. \n  reflexivity. Qed.\n\nTheorem count_member_nonzero : ∀s : bag,\n  ble_nat 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s. induction s as [|n l].\n  Case \"s=[]\". simpl. reflexivity.\n  Case \"s=n::l\". simpl. 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 s. induction s as [|n l].\n simpl. reflexivity.\n destruct n. simpl. apply ble_n_Sn.\n simpl. apply IHl. Qed.\n\nTheorem rev_nil: rev [] = [].\nProof. simpl. reflexivity. Qed.\n\n(*\nTheorem rev_inj_conv :∀l1 l2:natlist,not (l1=l2)-> not (rev l1=rev l2).\nProof.\n  intros l1 l2. induction l1 as [|n1 l1'].\n  Case \"l1=[]\". simpl. intros H. induction l2 as [|n2 l2']. rewrite->rev_nil.*)\n\n(* skipping this for now until I learn more coq tactics *)\n\nTheorem rev_rev:∀l l': natlist, l=l'->rev l = rev l'.\nProof. intros l l' H. rewrite ->H. reflexivity. Qed.\n\nTheorem flip_rev:∀l l':natlist,\nrev l = l' -> l = rev l'.\nProof.\n  intros l l' H. apply rev_rev in H. SearchAbout rev. rewrite-> rev_involutive in H. apply H. Qed.\n\n(*Theorem rev_nil_inj : ∀l:natlist,rev l=[] -> l=[].\nProof.\n intros l H.\n induction l as [|n l']. reflexivity.\n inversion H. inversion H1. \n reflexivity. \n simpl. rewrite->snoc_append. destruct l'. simpl. intros H. inversion H.\n  simpl. rewrite->snoc_append.\n unfold app. intros H. inversion H. simpl.\n *)\n(*Theorem snoc_rev : ∀l:natlist, ∀n:nat,*)\n  \n\nTheorem rev_injective : ∀l1 l2 : natlist, rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H. apply rev_rev in H. rewrite->rev_involutive in H. rewrite->rev_involutive in H. apply H. Qed.\n", "meta": {"author": "stchang", "repo": "swf", "sha": "285e4c10d0343db3de6af22fec1b28b8a5846634", "save_path": "github-repos/coq/stchang-swf", "path": "github-repos/coq/stchang-swf/swf-285e4c10d0343db3de6af22fec1b28b8a5846634/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.843895098628499, "lm_q1q2_score": 0.7419076560927819}}
{"text": "\nRequire Import Arith. \nRequire Import Omega. \nRequire Import List.\nRequire Import LambdaSyntax.\n\n(** Representation using DeBruijn indices. *)\n\nSet Implicit Arguments. \n\nInductive db_term (A : Type) : Type := \n| db_const : A -> db_term A\n| db_var : var -> db_term A\n| db_app : db_term A -> db_term A -> db_term A\n| db_abs : db_term A -> db_term A.\n\nArguments db_var [A] _. \n\nNotation \"\\\\ M\" := (db_abs M) (at level 60, right associativity). \nNotation \"M $$ N\" := (db_app M N) (at level 50, left associativity). \nNotation \"[ v ]\" := (db_var v) (at level 40, no associativity). \nNotation \"[ v # T ]\" := (db_var (A := T) v) (at level 40, no associativity). \n\nDefinition binders := list var.\n\n(** * Conversion to DeBruijn form *)\n\nFixpoint find_var_in_binders (bs : binders) (v : var) (i : nat) : option nat := \n  match bs with\n    | nil => None\n    | v' :: bs' => if beq_nat v v' then Some i \n                   else find_var_in_binders bs' v (S i)\n  end.\n\nDefinition map_var (v : var) (lv : nat) (bs : binders) : var := \n  match find_var_in_binders bs v 0 with\n    | None => v + lv\n    | Some i => i\n  end. \n\nFixpoint term_to_db_aux {A : Type} (t : term A) (bs : binders) (lv : nat) : db_term A := \n  match t with\n    | Const a => db_const a \n    | Var v => db_var (map_var v lv bs)\n    | App m n => db_app (term_to_db_aux m bs lv) (term_to_db_aux n bs lv)\n    | Abs x body => db_abs (term_to_db_aux body (x::bs) (S lv))\n  end.\n\nDefinition term_to_db {A : Type} (t : term A) : db_term A := \n  term_to_db_aux t nil 0.\n\n(** ** Conversion examples *)\n\nExample term_to_db_ex1 : \n  term_to_db (\\X # nat --> Var X) = (\\\\ (db_var 0)).\nProof. reflexivity. Qed. \n\nExample term_to_db_ex2 : \n  term_to_db (\\X # nat --> (Var X) $ (Var Y)) = \n  \\\\ ((db_var 0) $$ (db_var 2)).\nProof. reflexivity. Qed. \n\nExample term_to_db_ex3 : \n  term_to_db (\\Y # nat --> Var Y) = (\\\\ (db_var 0)).\nProof. reflexivity. Qed. \n\nExample term_to_db_ex4 : \n  term_to_db (\\Y # nat --> (Var Y) $ (Var Z)) = \n  (\\\\ ((db_var 0) $$ (db_var (S Z)))).\nProof. reflexivity. Qed. \n\nExample term_to_db_ex5 : \n  term_to_db ((Var 4) $ ((Var 3) $ (Var 2))) =\n  ((db_var 4) $$ ((db_var 3) $$ [2 # nat])).\nProof. reflexivity. Qed. \n\nExample term_to_db_ex6 : \n  term_to_db (\\ 7 --> (Var 3) $ (Var 7)) = \n  (\\\\ [4 # nat] $$ [0]).\nProof. reflexivity. Qed. \n\nExample term_to_db_ex7 : \n  term_to_db (\\ 7 --> (\\ 8 --> (Var 4))) = \n  (\\\\ (\\\\ [6 # nat])). \nProof. reflexivity. Qed. \n\n(** * Conversion from DeBruijn form *)\n\nDefinition db_var_to_var (n i v : var) : var := \n  if leb (S n) i then (v + i - n) else (n - i). \n\nFixpoint db_to_term_aux {A : Type} (dt : db_term A) (i v : var) : term A := \n  match dt with\n    | db_const a => Const a\n    | db_var n => Var (db_var_to_var n i v)\n    | db_app m n => App (db_to_term_aux m i v) (db_to_term_aux n i v)\n    | db_abs body => Abs (v + (S i)) (db_to_term_aux body (S i) v)\n  end. \n\nFixpoint max_free_var {A : Type} (dt : db_term A) (lv : nat) : nat := \n  match dt with\n    | db_const _ => 0\n    | db_var v => (v - lv)\n    | db_app m n => max (max_free_var m lv) (max_free_var n lv) \n    | db_abs body => max_free_var body (S lv)\n  end. \n\nDefinition db_to_term {A : Type} (dt : db_term A) : term A := \n  db_to_term_aux dt 0 (max_free_var dt 0).\n\n(** ** Examples *)\n\nExample dbv_to_term_1 : db_to_term (\\\\ [0 # nat]) = (Abs 1 (Var 1)).\nProof. reflexivity. Qed. \n\nExample dbv_to_term_2 : \n  db_to_term (\\\\ ([0 # nat] $$ [2])) = \n  (\\2 --> (Var 2) $ (Var 1)). \nProof. reflexivity. Qed. \n\n(** * Auxiliary lemmas and theorems *)\n\nLemma dbvar_to_var_zero : forall (n v : var), \n                            db_var_to_var n 0 v = n. \nProof. \n  intros n v. \n  unfold db_var_to_var. \n  replace (leb (S n) 0) with (false). apply eq_sym. apply minus_n_O. \n  apply eq_sym. apply leb_correct_conv. apply lt_0_Sn. \nQed. \n\nLemma mapvar_nil : forall v lv, map_var v lv nil = v + lv. \nProof. \n  intros v lv. unfold map_var. simpl. reflexivity. \nQed. \n\nLemma maxvar_app : forall (A : Type) v n (dt1 dt2 : db_term A),\n                     v >= max_free_var (dt1 $$ dt2) n -> \n                     v >= max_free_var dt1 n /\\ v >= max_free_var dt2 n. \nProof. \n  intros A v n dt1 dt2 Hgeq. simpl in Hgeq. \n  apply NPeano.Nat.max_lub_iff in Hgeq. assumption. \nQed. \n\n(** Generate a list [[v + n; v + n - 1; ...; v]]. *)\n\nFixpoint range_n_v (n : nat) (v : var) : list var := \n  match n with \n    | 0 => nil\n    | S n' => (v + n) :: (range_n_v n' v)\n  end.\n\nLemma n_gt_0_Sn : forall n, \n                    n > 0 -> (exists n', n = S n'). \nProof. \n  intros n H. destruct n eqn:E. inversion H. \n  exists n0. reflexivity. \nQed. \n\nLemma n_gt_Sv_Sn : forall n v,\n                     n > S v -> (exists n', n = S n').\nProof. \n  intros n v H. destruct n eqn:E. inversion H. exists n0. reflexivity. \nQed. \n\nLemma v_lt_n_0 : forall n v, v < n -> 0 < n - v. \nProof. \n  intros; omega. \nQed. \n  \nLemma range_struct : forall n n' v,\n                       n = S n' -> \n                       range_n_v n v = (v + n) :: range_n_v n' v. \nProof. \n  intros. rewrite H. reflexivity. \nQed. \n\nLemma find_in_range_v : forall v0 n v,\n                        v < n ->\n                        find_var_in_binders (range_n_v (n - v) v0) (v0 + n - v) v = Some v.\nProof. \n  intros. destruct v. \n\n  (* Case v = 0 *)\n  apply n_gt_0_Sn in H. inversion H. rewrite <- minus_n_O. \n  apply range_struct with (v := v0) in H0. rewrite H0. \n  simpl. replace (beq_nat (v0 + n - 0) (v0 + n)) with (true). reflexivity. \n  rewrite <- minus_n_O. apply beq_nat_refl. \n\n  (* Case v = S v *)\n  assert (H': S v < n). assumption. \n  apply v_lt_n_0 in H. apply n_gt_0_Sn in H. inversion H. \n  apply range_struct with (v := v0) (n := n - S v) in H0. rewrite H0. \n  simpl. replace (beq_nat (v0 + n - S v) (v0 + (n - S v))) with (true). reflexivity. \n  replace (v0 + (n - S v)) with (v0 + n - S v). apply beq_nat_refl. \n  omega.\nQed. \n\nLemma minus_pred : forall n m, n > m -> m > 0 -> n - pred m = S (n - m). \nProof. \n  intros n m Hnm Hm0. destruct m. inversion Hm0. \n  simpl. rewrite NPeano.Nat.sub_succ_r. omega. \nQed. \n\nLemma minus_minus_Sn : forall n v i, \n                         n > v - i -> v - i > 0 -> (n - (v - S i)) = S (n - (v - i)).\nProof. \n  intros. simpl. rewrite NPeano.Nat.sub_succ_r. apply minus_pred; assumption. \nQed. \n\nLemma find_in_range_aux : \n  forall v0 n v i,\n    v < n -> i <= v -> \n    find_var_in_binders (range_n_v (n - (v-i)) v0) (v0 + n - v) (v-i) = Some v.\nProof. \n  intros. induction i. \n  (* Case i = 0 *)\n  rewrite <- minus_n_O. apply find_in_range_v. assumption. \n\n  (* Case i = S i *)\n  assert (Hnvi: n > v - i); try omega. \n  assert (Hvi0: v - i > 0); try omega. \n  apply minus_minus_Sn in Hnvi. \n  apply range_struct with (v := v0) (n := n - (v - S i)) in Hnvi. rewrite Hnvi. \n  simpl. \n  replace (beq_nat (v0 + n - v) (v0 + (n - (v - S i)))) with (false). \n  replace (S (v - S i)) with (v - i); try omega. \n  apply IHi; omega. apply eq_sym. apply beq_nat_false_iff. omega. \n  assumption. \nQed. \n\nLemma find_in_range : forall v0 n v,\n                        v < n -> \n                        find_var_in_binders (range_n_v n v0) (v0 + n - v) 0 = Some v.\nProof. \n  intros. replace (range_n_v n v0) with (range_n_v (n - 0) v0).\n  replace 0 with (v-v). apply find_in_range_aux with (i := v). assumption. \n  apply le_refl. apply minus_diag. rewrite <- minus_n_O. reflexivity. \nQed. \n\nLemma mapvar_in_range : forall v0 n v, \n                          (S v) <= n ->  \n                          map_var (v0 + n - v) n (range_n_v n v0) = v.\nProof. \n  intros. unfold map_var. rewrite find_in_range. reflexivity. \n  omega. \nQed. \n\nLemma find_out_of_range : forall v0 n v i,\n                            v <= v0 -> \n                            find_var_in_binders (range_n_v n v0) v i = None. \nProof. \n  intros. generalize dependent i. induction n. reflexivity. \n  intros. simpl. replace (beq_nat v (v0 + S n)) with (false). \n  apply IHn. apply eq_sym. apply beq_nat_false_iff. omega. \nQed. \n\nLemma mapvar_out_of_range : forall v n v0, \n                              v >= n -> \n                              (v - n) <= v0 -> \n                              map_var (v - n) n (range_n_v n v0) = v. \nProof. \n  intros. unfold map_var. rewrite find_out_of_range. \n  rewrite plus_comm. apply le_plus_minus_r. omega. assumption.  \nQed. \n\n(** * Converting from DeBruijn to standard and back is the identity  *)\nTheorem from_to_dbv_aux : \n  forall (A : Type) (dt : db_term A) v n,\n    v >= (max_free_var dt n) -> \n    term_to_db_aux (db_to_term_aux dt n v) (range_n_v n v) n = dt.\nProof. \n  intros A dt. \n  induction dt. \n\n  (* Case dt = db_const *) reflexivity. \n\n  (* Case dt = db_var *)\n  intros. simpl in H. \n  simpl. unfold db_var_to_var. destruct (leb (S v) n) eqn:E. \n  apply leb_complete in E. rewrite mapvar_in_range. reflexivity. assumption.\n  apply leb_complete_conv in E. \n  rewrite mapvar_out_of_range. reflexivity. omega. assumption. \n\n  (* Case dt = dt_app *)\n  intros. simpl. apply maxvar_app in H. \n  rewrite IHdt1; try rewrite IHdt2; try reflexivity; tauto. \n\n  (* Case dt = db_abs *)\n  intros. simpl. f_equal. apply IHdt. simpl in H. assumption. \nQed. \n\nTheorem from_to_dbv : forall (A : Type) (dt : db_term A),\n                        term_to_db (db_to_term dt) = dt. \nProof. \n  intros. unfold term_to_db. unfold db_to_term. apply from_to_dbv_aux. auto. \nQed. \n\n(** * Substitution *)\n\n(** Shifting function, needed to preserve the identity of free variables \n    after substitution. *)\n\nFixpoint shift_aux {A : Type} (dt : db_term A) d c : db_term A := \n  match dt with\n    | db_const _ => dt\n    | db_var k => db_var (if leb (S k) c then k else k + d)\n    | db_abs body => db_abs (shift_aux body d (S c))\n    | db_app m n => db_app (shift_aux m d c) (shift_aux n d c)\n  end. \n\nDefinition shift {A : Type} (dt : db_term A) d : db_term A :=\n  shift_aux dt d 0.\n\nExample shift_ex1 : \n  shift (\\\\ (\\\\ [1 # nat] $$ ([0] $$ [2]))) 2 = (\\\\ (\\\\ [1 # nat] $$ ([0] $$ [4]))).\nProof. reflexivity. Qed. \n\nExample shift_ex2 : \n  shift (\\\\ ([0 # nat] $$ [2]) $$ (\\\\ ([0] $$ [1]) $$ [2])) 2 = \n  (\\\\ ([0 # nat] $$ [4]) $$ (\\\\ ([0] $$ [1]) $$ [4])). \nProof. reflexivity. Qed. \n\n(** Substitute [dt] for variable [v] in term [orig]. *)\n\nFixpoint subst {A : Type} (orig : db_term A) v (dt : db_term A) : db_term A :=\n  match orig with\n    | db_const _ => orig\n    | db_var x => if eq_nat_dec v x then dt else orig\n    | db_abs body => db_abs (subst body (S v) (shift dt 1))\n    | db_app m n => db_app (subst m v dt) (subst n v dt)\n  end. \n\n(** Module to localize substitution notation for DeBruijn terms. *)\n\nModule SubstNotation.\n  Notation \"M [ v :-> N ]\" := (subst M v N) (at level 50, left associativity). \nEnd SubstNotation.\n\nImport SubstNotation. \n\n(** ** Free and bound variables *)\n\nFixpoint var_free_in_term {A : Type} (dt : db_term A) v : bool := \n  match dt with\n    | db_const _ => false\n    | db_var v' => beq_nat v v'\n    | db_abs body => var_free_in_term body (S v)\n    | db_app m n => orb (var_free_in_term m v) (var_free_in_term n v)\n  end. \n\nInductive freeIn {A : Type} : db_term A -> var -> Prop := \n| freeIn_var : forall (v : var), freeIn (db_var v) v\n| freeIn_app_l : forall (m n : db_term A) (v : var), freeIn m v -> freeIn (db_app m n) v\n| freeIn_app_r : forall (m n : db_term A) (v : var), freeIn n v -> freeIn (db_app m n) v\n| freeIn_abs : forall (body : db_term A) (v : var), freeIn body (S v) -> freeIn (db_abs body) v. \n\nExample freeIn_ex1 : freeIn (\\\\ [1 # nat]) 0. \nProof. \n  apply freeIn_abs. apply freeIn_var. \nQed. \n\nLemma not_free_in_var : forall (A : Type) v v',\n                          ~(freeIn (db_var (A := A) v) v') -> v <> v'. \nProof. \n  intros A v v' Hnfree. \n  intro Hcontra. apply Hnfree. rewrite Hcontra. apply freeIn_var. \nQed. \n\nLemma not_free_in_app : forall (A : Type) (dt1 dt2 : db_term A) v,\n                          ~(freeIn (dt1 $$ dt2) v) -> ~(freeIn dt1 v) /\\ ~(freeIn dt2 v). \nProof. \n  intros A dt1 dt2 v Hnfree. \n  split; intro Hcontra; apply Hnfree; \n    [ apply freeIn_app_l | apply freeIn_app_r ]; assumption. \nQed. \n\nLemma not_free_abs_succ_body : forall (A : Type) (dt : db_term A) v,\n                                 ~(freeIn (\\\\ dt) v) -> \n                                 ~(freeIn dt (S v)). \nProof. \n  intros A dt v Hnfree. intro Hcontra; apply Hnfree. \n  apply freeIn_abs. assumption. \nQed. \n\nLemma free_abs_succ_body : forall (A : Type) (t : db_term A) v,\n                             freeIn (\\\\ t) v -> freeIn t (S v). \nProof. \n  intros A t v Hfabs. inversion Hfabs. assumption. \nQed. \n\nLemma free_vars_abs : \n  forall (A : Type) (t : db_term A) c1 c2 v1,\n    freeIn (\\\\ t) v1 -> v1 >= c1 /\\ v1 >= c2 -> S v1 >= S c1 /\\ S v1 >= S c2. \nProof. \n  intros A t c1 c2 v1 Hfabs Hgeq. \n  split; apply le_n_S; apply Hgeq. \nQed. \n\nLemma free_app_contra : forall (A : Type) (t1 t2 : db_term A) v,\n                          freeIn (t1 $$ t2) v -> freeIn t1 v \\/ freeIn t2 v. \nProof. \n  intros A t1 t2 v Hfree. \n  inversion Hfree; [ left | right ]; assumption. \nQed. \n\n  \n(** ** The substitution lemma for DeBruijn terms *)\n\nLemma subst_same_var : forall (A : Type) (dt : db_term A) v,\n                         (db_var v)[v :-> dt] = dt. \nProof. \n  intros A dt v. \n  simpl. destruct (eq_nat_dec v v). reflexivity. congruence. \nQed. \n\nLemma subst_diff_var : forall (A : Type) (dt : db_term A) v v',\n                    v <> v' -> (db_var v)[v' :-> dt] = (db_var v). \nProof. \n  intros A dt v v' Hneq. \n  simpl. destruct (eq_nat_dec v' v). contra_equality. reflexivity. \nQed. \n\nLemma subst_non_free : forall (A : Type) (dt1 dt2 : db_term A) v,\n                         ~(freeIn dt1 v) -> dt1 [v :-> dt2] = dt1. \nProof. \n  intros A dt1. induction dt1; try reflexivity. \n\n  (* Case dt1 = db_var *)\n  intros dt2 v0 Hnfree. \n  apply not_free_in_var in Hnfree. rewrite subst_diff_var. reflexivity. assumption. \n\n  (* Case dt1 = db_app *)\n  intros dt2 v Hnfree. apply not_free_in_app in Hnfree. \n  simpl; f_equal; [ apply IHdt1_1 | apply IHdt1_2 ]; tauto. \n\n  (* Case dt1 = dt_abs *)\n  intros dt2 v Hnfree. simpl. f_equal. apply IHdt1. \n  apply not_free_abs_succ_body. assumption. \nQed. \n\nLemma shift_aux_geq : forall (A : Type) v d c,\n                       v >= c -> shift_aux (db_var (A := A) v) d c = db_var (v + d).\nProof. \n  intros A v d c Hgt. destruct c. simpl. reflexivity. simpl. \n  replace (leb v c) with (false). reflexivity. \n  apply eq_sym. apply leb_correct_conv. omega. \nQed. \n\nLemma shift_aux_lt : forall (A : Type) v d c,\n                       v < c -> shift_aux (db_var (A := A) v) d c = db_var v. \nProof. \n  intros A v d c Hlt. destruct c. inversion Hlt. \n  simpl. replace (leb v c) with (true). reflexivity. \n  apply eq_sym. apply leb_correct. apply gt_S_le. assumption. \nQed. \n\nLemma free_shift_aux : forall (A : Type) (t : db_term A) v c,\n                         v >= c -> freeIn t v -> freeIn (shift_aux t 1 c) (S v). \nProof. \n  intros A t v c v_geq_c Hfree. generalize dependent c. \n  induction Hfree. \n\n  (* Case freeIn_var *)\n  intros. rewrite shift_aux_geq; try assumption. \n  rewrite NPeano.Nat.add_1_r. apply freeIn_var. \n\n  (* Case freeIn_app_l *)\n  intros. simpl. apply freeIn_app_l. apply IHHfree; assumption. \n\n  (* Case freeIn_app_r *)\n  intros. simpl. apply freeIn_app_r. apply IHHfree; assumption. \n\n  (* Case freeIn_abs *)\n  intros. simpl. apply freeIn_abs. apply IHHfree. apply le_n_S; assumption. \nQed. \n\nLemma free_shift : forall (A : Type) (t : db_term A) v,\n                     freeIn t v -> freeIn (shift t 1) (S v). \nProof. \n  intros. unfold shift. apply free_shift_aux; try assumption. apply le_0_n. \nQed.\n\nLemma lt_Sn_m_n_m : forall n m, S n < m -> n < m.\nProof. \n  intros. assert (Hn : n < S n). apply lt_n_Sn. \n  apply lt_trans with (m := S n) (p := m) in Hn; assumption. \nQed. \n\nLemma free_shift_aux_free : forall (A : Type) (t : db_term A) v c,\n                              v >= c -> freeIn (shift_aux t 1 c) (S v) -> freeIn t v. \nProof. \n  intros A t. induction t. \n  \n  (* Case t = db_const *)\n  intros v c v_geq_c Hfree. simpl in Hfree. inversion Hfree. \n\n  (* Case t = db_var *)\n  intros v0 c v0_geq_c Hfree. destruct (eq_nat_dec v v0) as [ v_eq_v0 | v_neq_v0 ]. \n    (* Case v = v0 *) rewrite v_eq_v0. apply freeIn_var. \n    (* Case v <> v0 *)\n    destruct (le_lt_dec c v) as [ v_geq_c | v_lt_c ]. \n      (* Case v >= c *) \n      rewrite shift_aux_geq in Hfree; try assumption. \n      rewrite NPeano.Nat.add_1_r in Hfree. inversion Hfree. apply freeIn_var. \n      (* Case v < c *)\n      rewrite shift_aux_lt in Hfree; try assumption. inversion Hfree. \n      rewrite H1 in v_lt_c. apply lt_Sn_m_n_m in v_lt_c. \n      assert (Hcontra := le_lt_trans _ _ _ v0_geq_c v_lt_c). \n      apply lt_irrefl in Hcontra. exfalso; assumption. \n\n  (* Case t = db_app *)\n  intros v c v_geq_c Hfree. simpl in Hfree. apply free_app_contra in Hfree.   \n  elim Hfree.\n  intro H; apply freeIn_app_l; apply IHt1 with (c := c); assumption. \n  intro H; apply freeIn_app_r; apply IHt2 with (c := c); assumption. \n\n  (* Case t = db_abs *)\n  intros v c v_geq_c Hfree. apply freeIn_abs. simpl in Hfree. \n  apply IHt with (c := S c). apply le_n_S; assumption. apply free_abs_succ_body. \n  assumption. \nQed. \n\nLemma free_shift_free : forall (A : Type) (t : db_term A) v,\n                          freeIn (shift t 1) (S v) -> freeIn t v. \nProof. \n  intros. unfold shift. apply free_shift_aux_free with (c := 0). \n  apply le_0_n. assumption. \nQed. \n\nLemma shift_shift : \n  forall (A : Type) (t : db_term A) c1 c2,\n    c1 >= c2 -> \n    shift_aux (shift_aux t 1 c1) 1 c2 = shift_aux (shift_aux t 1 c2) 1 (S c1). \nProof. \n  intros A t. induction t. reflexivity. \n\n  (* Case t = db_var *)\n  intros c1 c2 c1_geq_c2. destruct (le_lt_dec c1 v). \n    (* Case v >= c1 *)\n    repeat rewrite shift_aux_geq; try omega. reflexivity. \n    (* Case v < c1 *)\n    destruct (le_lt_dec c2 v). \n      (* Case v >= c2 *)\n      rewrite shift_aux_lt; try assumption. rewrite shift_aux_geq; try assumption. \n      rewrite shift_aux_lt. reflexivity. omega. \n      (* Case v < c2 *)\n      repeat rewrite shift_aux_lt; try omega. reflexivity. \n\n  (* Case t = db_app *)\n  intros c1 c2 c1_geq_c2. \n  simpl; f_equal; [ apply IHt1 | apply IHt2 ]; assumption. \n\n  (* Case t = db_abs *) \n  intros c1 c2 c1_geq_c2.\n  simpl. f_equal. apply IHt. apply le_n_S. assumption. \nQed. \n\nLemma shift_aux_subst_xchg : \n  forall (A : Type) (dt1 dt2 : db_term A) v c, \n    v >= c ->\n    (shift_aux dt1 1 c)[S v :-> shift_aux dt2 1 c] = shift_aux (dt1 [v :-> dt2]) 1 c. \nProof. \n  intros A dt1.\n  induction dt1; try reflexivity. \n\n  (* Case dt1 = db_var *)\n  intros dt2 v0 c v0_geq_c. \n  destruct (eq_nat_dec v v0) as [ v0_eq_v | v0_diff_v ]. \n    (* Case v0 = v *) \n    rewrite v0_eq_v. rewrite shift_aux_geq; try assumption. \n    rewrite NPeano.Nat.add_1_r. repeat rewrite subst_same_var. reflexivity. \n    \n    (* Case v0 <> v *)\n    rewrite subst_diff_var; try assumption.\n    destruct (le_lt_dec c v). \n      (* Case v >= c *)\n      rewrite shift_aux_geq; try apply le_0_n; try assumption. rewrite NPeano.Nat.add_1_r. \n      rewrite subst_diff_var; auto with arith. \n      (* Case v < c *)\n      rewrite shift_aux_lt; try assumption. rewrite subst_diff_var. reflexivity.\n      omega. \n\n  (* Case dt1 = db_app *)\n  intros dt2 v c v_geq_c. \n  simpl; f_equal; [ apply IHdt1_1 | apply IHdt1_2 ]; try assumption. \n\n  (* Case dt1 = db_abs *)\n  intros dt2 v c v_geq_c. \n  simpl. f_equal. rewrite <- IHdt1. f_equal. unfold shift. \n  apply shift_shift. apply le_0_n. apply le_n_S; assumption. \nQed. \n\nLemma shift_subst_xchg : forall (A : Type) (dt1 dt2 : db_term A) v, \n                           (shift dt1 1)[S v :-> shift dt2 1] = shift (dt1 [v :-> dt2]) 1. \nProof. \n  intros A dt1 dt2 v. unfold shift. apply shift_aux_subst_xchg. apply le_0_n. \nQed. \n\nLemma subst_lemma : forall (A : Type) (M N L : db_term A) x y,\n                      x <> y -> ~(freeIn L x) -> \n                      M[x :-> N][y :-> L] = M[y :-> L][x :-> N[y :-> L]].\nProof. \n  intros A M. induction M.\n\n  (* Case M = db_const *) reflexivity. \n\n  (* Case M = db_var *)\n  intros N L x y Hneq Hnfree. \n  destruct (eq_nat_dec v x) as [ v_eq_x | v_neq_x ]. \n    (* Case v = x *)\n    rewrite v_eq_x. rewrite subst_same_var. \n    rewrite subst_diff_var. rewrite subst_same_var. reflexivity. assumption. \n\n    (* Case v <> x *)\n    rewrite subst_diff_var; try assumption. \n    destruct (eq_nat_dec v y) as [ v_eq_y | v_neq_y ]. \n      (* Case v = y *)\n      rewrite v_eq_y. repeat rewrite subst_same_var. \n      rewrite subst_non_free. reflexivity. assumption. \n\n      (* Case v <> y *)\n      repeat rewrite subst_diff_var; try assumption. reflexivity. \n\n  (* Case M = db_app *)\n  intros N L x y Hneq Hnfree. simpl. f_equal; [ apply IHM1 | apply IHM2 ]; assumption. \n\n  (* Case M = db_abs *)\n  intros N L x y Hneq Hnfree. \n  simpl. f_equal. rewrite IHM. f_equal. apply shift_subst_xchg. \n  apply not_eq_S; assumption. \n  intro Hcontra. apply Hnfree. \n  apply free_shift_free. assumption. \nQed. \n", "meta": {"author": "tautologico", "repo": "semtypes", "sha": "6a727332e35123fd96fd76fe1c2ab92677d13826", "save_path": "github-repos/coq/tautologico-semtypes", "path": "github-repos/coq/tautologico-semtypes/semtypes-6a727332e35123fd96fd76fe1c2ab92677d13826/lambda-v-cs/DeBruijn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7419040781174165}}
{"text": "(* ************************************************************** *)\nSection pred1.\n\nVariable Terms : Set.\nVariable M : Terms.\n\n(* predicates *)\nVariable A : Prop.\nVariable P : Terms -> Prop.\nVariable Q : Terms -> Prop.\nVariable R : Terms -> Terms -> Prop.\n\n(* example *)\nTheorem example0 : (forall x:Terms, (P x)) -> (P M).\nProof.\nintro u.\napply u.\nQed.\n\nPrint example0.\n(* \\u: Pi x:Terms. Px. (u M) *)\n\n\n(* example *)\nTheorem example1 : forall x:Terms, (P x) -> (forall y:Terms, (P y) -> A) -> A.\nProof.\nintro x.\nintro h.\nintro i.\napply i with x.\nassumption.\nQed.\n\nPrint example1.\n(* \\x:Terms. \\h:(P x). \\i:(Pi y:Terms. Py -> A). (i x h) *)\n\n(* example, see slide 35 of week 6 *)\nTheorem example2 :\n  (forall x : Terms , P x -> Q x)\n  ->\n  (forall x : Terms , P x)\n  ->\n  forall y : Terms , Q y.\n\nProof.\nintro h.\nintro i.\nintro y.\napply h.\napply i.\nQed.\nPrint example2.\n(* \\h: (Pi x:Terms. Px -> Qx). \\i: (Pi x:Terms Px). \\y: Terms. h y (i y) *)\n\n(* exercise 1: prove the lemma and inspect the proof term *)\nLemma one : (forall x : Terms, P x) -> P M.\nProof.\nintro u.\napply u.\nQed.\nPrint one.\n\n(* exercise 2: prove the lemma and inspect the proof term *)\nLemma two : (A -> forall x : Terms, P x) -> (forall y : Terms, A -> P y).\nProof.\nintro H.\nintro y.\nintro x.\napply H.\nexact x.\nQed.\nPrint two.\n\n(* exercise 3: prove the lemma and inspect the proof term *)\nLemma three : A -> forall x : Terms, A.\nProof.\nintro x.\nintro y.\nexact x.\nQed.\nPrint three.\n\n(* example, see slides 13-14-15 of week 7 *)\nDefinition AS :=\n  forall x y : Terms, (R x y) -> ~(R y x).\nDefinition IR :=\n  forall x:Terms, ~(R x x).\n\nTheorem AS_implies_IR : AS -> IR.\nProof.\nunfold AS.\nunfold IR.\nunfold not.\nintro h.\nintro x.\nintro i.\napply h with x x.\n  (* alternative: apply (h x x ) *)\nexact i.\nexact i.\nQed.\nPrint AS_implies_IR.\n\n(* given *)\nDefinition reflif := forall x : Terms, (exists y : Terms, R x y) -> R x x.\n\n(* exercise 4:\n   define sym as the proposition stating that\n   R is symmetric, that is,\n   if x and y are related via R, then y and x are related via R *)\nDefinition sym := forall x y : Terms, R x y -> R y x.\n\n(* exercise 5:\n   define trans as the proposition stating that\n   R is transitive, that is,\n   if x and y are related via R, and y and z are related via R,\n   then x and z are related via R  *)\nDefinition trans := forall x y z : Terms, (R x y /\\ R y z) -> R x z.\n\n(* exercise 6: prove the following Lemma *)\nLemma str : sym -> trans -> reflif.\nProof.\nunfold sym, trans, reflif.\nintro sym.\nintro trans.\nintro.\nintro.\nelim H.\nintro.\nintro.\napply trans with x0.\nsplit.\nexact H0.\napply sym.\napply H0.\nQed.\n\nEnd pred1.\n\n(* ************************************************************** *)\n\nSection logical_framework.\n\n(* we encode propositional logic\n   source: webpage Herman Geuvers\n   handbook article Henk Barendregt *)\n\n(* prop representing the propositions is declared as a Set *)\nParameter prop : Set.\n\n(* implication on prop is a binary operator *)\nParameter imp : prop -> prop -> prop.\n\n(* we can use infix notation => for imp *)\nInfix \"=>\" := imp (right associativity, at level 85).\n\n(* T expresses if a proposion in prop is valid\n   if (T p) is inhabited then p is valid\n   if (T p) is not inhabited then p is not valid *)\nParameter T : prop -> Prop.\n\n(* the variable imp_introduction models the introduction rule for imp *)\nParameter imp_introduction : forall p q : prop, (T p -> T q) -> T (p => q).\n\n(* the variable imp_elimination models the elimination rule for imp *)\nParameter imp_elimination : forall p q : prop, T (p => q) -> T p -> T q.\n\n(* exercise 7 : prove the following lemma *)\nLemma I : forall p : prop, T (p => p).\nProof.\nintro p. apply imp_introduction. intro Tp. apply Tp.\nQed.\n\n(* exercise 8 : prove the following lemma *)\nLemma transitivity :\n forall p q r : prop, T (p => q) -> T (q => r) -> T (p => r).\nProof.\nintros p q r.\nintros p_implies_q q_implies_r.\napply imp_introduction. intro Tp.\napply imp_elimination with q. assumption.\napply imp_elimination with p. assumption.\nassumption.\nQed.\n\nParameter conjunction : prop -> prop -> prop.\nInfix \"X\" := conjunction (no associativity, at level 90).\n\n(* exercise 9 : define variables that model the introduction\n   rule for conjuction on prop, and both elimination rules *)\n\nParameter conjunction_introduction :\n  forall p q : prop, T p -> T q -> T (p X q).\n\nParameter conjunction_elimination_l :\n  forall p q : prop, T (p X q) -> T p.\n\nParameter conjunction_elimination_r :\n  forall p q : prop, T (p X q) -> T q.\n\n(* exercise 10: prove the following lemma *)\nLemma weak : forall a b c : prop, T (a => c) -> T ((a X b) => c).\nProof.\nintros a b c a_implies_c.\napply imp_introduction. intro a_conj_b.\napply imp_elimination with a. assumption.\napply conjunction_elimination_l with b.\nassumption.\nQed.\n\n\n(* the remainder is not obligatory *)\n\n(* bot represents falsum in prop *)\nParameter bot : prop.\n\n(* not represents negation in prop *)\nDefinition not (p : prop) := p => bot.\n\n(* not obligatory *)\n(* exercise 11 : prove the following lemma *)\nLemma contrapositive : forall p q : prop, T (p => q) -> T (not q => not p).\nProof.\nintros p q p_implies_q.\napply imp_introduction. unfold not. intro not_q.\napply imp_introduction. intro Tp.\napply imp_elimination with q. apply not_q.\napply imp_elimination with p. assumption.\nassumption.\nQed.\n\nEnd logical_framework.\n\n(*\nvim: filetype=coq\n*)\n", "meta": {"author": "mklinik", "repo": "radboud", "sha": "1b79730dbf7979221ca0de97fc369db82c405331", "save_path": "github-repos/coq/mklinik-radboud", "path": "github-repos/coq/mklinik-radboud/radboud-1b79730dbf7979221ca0de97fc369db82c405331/type-theory-IMC010/pw07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7419040684148339}}
{"text": "\n(* Add some trivial facts about nats to the auto hint database,\n   so we don't have to use omega as much. *)\nRequire Import FiatFormal.Tactics.\n\n\nLemma nat_eq_cases\n :  forall (n m : nat)\n ,  n = m \\/ ~(n = m).\nProof. intros. omega. Qed.\nHint Resolve nat_eq_cases.\n\n\nLemma nat_zero_le_all\n : forall n, 0 <= n.\nProof.\n intros. omega.\nQed.\nHint Resolve nat_zero_le_all.\n\n\nLemma nat_zero_lt_succ\n : forall n, 0 < S n.\nProof.\n intros. omega.\nQed.\nHint Resolve nat_zero_lt_succ.\n\n\n(* Don't add transitivity lemmas to the hints database as it\n   can severely degrade performance. *)\nLemma nat_trans_le\n : forall a b c\n , a <= b -> b <= c -> a <= c.\nProof.\n intros. omega.\nQed.\n\n\n(* Normalise naturals to use successor representation instead\n   of addition. *)\nLemma nat_plus_zero\n : forall n, n + 0 = n.\nProof. auto. Qed.\nHint Rewrite nat_plus_zero : global.\n\n\nLemma nat_zero_plus\n :  forall n, 0 + n = n.\nProof. auto. Qed.\nHint Rewrite nat_zero_plus : global.\n\n\nLemma nat_minus_zero\n : forall n, n - 0 = n.\nProof. intros. omega. Qed.\nHint Rewrite nat_minus_zero : global.\n\n\nLemma nat_plus_one\n : forall n, n + 1 = S n.\nProof. intros. omega. Qed.\n\n\n(* Tactics **********************************************************)\n(* Normalise naturals. *)\nTactic Notation \"norm_nat\"\n := first\n    [ rewrite nat_plus_zero\n    | rewrite nat_minus_zero\n    | rewrite nat_plus_one ].\n\n\n(* Convert boolean (in)equalities *)\nLtac eqs_beq_nat\n := repeat match goal with\n    | [ H : true = beq_nat ?n ?m |- _]\n    => symmetry in H; apply beq_nat_true in H\n\n    | [H : false = beq_nat ?n ?m |- _]\n    => symmetry in H; apply beq_nat_false in H\n    end.\n\n\n(* Break on boolean equality *)\nLtac break_beq_nat\n := match goal with\n     |  [ |- context [beq_nat ?n ?m] ]\n     => let X := fresh in remember (beq_nat n m) as X; destruct X\n    end; eqs_beq_nat.\n", "meta": {"author": "paulkrog", "repo": "formalized-fiat", "sha": "8f9022980c038f500aeea9b2f85062f0bfc33eb6", "save_path": "github-repos/coq/paulkrog-formalized-fiat", "path": "github-repos/coq/paulkrog-formalized-fiat/formalized-fiat-8f9022980c038f500aeea9b2f85062f0bfc33eb6/FiatFormal/Data/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7419022688510207}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\nRequire Import List Arith Nat Lia Relations.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list finite php.\n\nFrom Undecidability.TRAKHTENBROT\n  Require Import notations.\n\nSet Default Proof Using \"Type\".\n\nSet Implicit Arguments.\n\n(* * Kleene's greatest fixpoint of lia-continous operators *)\n\nSection gfp.\n\n  (* We develop the theory of Kleene's greatest fixpoint for binary relations\n      and establish the fact that the gfp is an equivalence (under suitable hyps),\n      reached after lia many steps (under lia continuity) and\n      reached after finitely many steps (under finiteness of the domain and\n      preservation of decidability *)\n\n  Variable (M : Type). \n\n  Implicit Type (R T : M -> M -> Prop).\n\n  Notation \"R ⊆ T\" := (forall x y, R x y -> T x y).\n\n  Notation \"R 'o' T\" := (fun x z => exists y, R x y /\\ T y z) (at level 58).\n\n  Let incl_trans R S T : R ⊆ S -> S ⊆ T -> R ⊆ T.\n  Proof. firstorder. Qed.\n\n  Let comp_mono R R' T T' : R ⊆ R' -> T ⊆ T' -> R o T ⊆ R' o T'.\n  Proof. firstorder. Qed. \n\n  Variable (F : (M -> M -> Prop) -> M -> M -> Prop).\n\n  Hypothesis (HF0 : forall R T, R ⊆ T -> F R ⊆ F T).  (* Monotonicity *)\n\n  Let sym R := fun x y => R y x.\n\n  Let i := iter F (fun _ _ => True).\n\n  Let iS n : i (S n) = F (i n).\n  Proof. apply iter_S. Qed.\n\n  Let i0 : i 0 = fun _ _ => True.\n  Proof. auto. Qed.\n\n  Let i_S n : i (S n) ⊆ i n.\n  Proof.\n    unfold i.\n    induction n as [ | n IHn ].\n    + simpl; auto.\n    + intros ? ?.\n      rewrite iter_S with (n := n), iter_S.\n      apply HF0, IHn.\n  Qed.\n\n  Let i_decr n m : n <= m -> i m ⊆ i n.\n  Proof. induction 1; auto. Qed.\n\n  Definition gfp x y := forall n, i n x y.\n\n  Notation I := (@eq M).\n\n  Hypothesis HF1 : I ⊆ F I.    (* Reflexivity *)\n\n  Let i_refl n : I ⊆ i n.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite i0; auto.\n    + rewrite iS.\n      apply incl_trans with (1 := HF1), HF0, IHn.\n  Qed.\n  \n  Let gfp_refl : I ⊆ gfp.\n  Proof. intros ? ? [] ?; apply i_refl; auto. Qed.\n\n  Hypothesis HF2 : forall R, sym (F R) ⊆ F (sym R).   (* Symmetry *)\n\n  Let i_sym n : sym (i n) ⊆ i n.\n  Proof.\n    induction n as [ | n IHn ].\n    + intros ? ?; rewrite i0; simpl; auto.\n    + rewrite iS; apply incl_trans with (2 := HF0 _ IHn), HF2.\n  Qed.\n\n  Let gfp_sym : sym gfp ⊆ gfp.\n  Proof. intros ? ? H ?; apply i_sym, H. Qed.\n\n  Hypothesis HF3 : forall R, F R o F R ⊆ F (R o R).   (* Transitivity *)\n\n  Let i_trans n : i n o i n ⊆ i n.\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite i0; auto.\n    + rewrite iS; apply incl_trans with (1 := @HF3 _), HF0, IHn.\n  Qed.\n\n  Let gfp_trans : gfp o gfp ⊆ gfp.\n  Proof.\n    intros ? ? H ?; apply i_trans.\n    revert H; apply comp_mono; auto.\n  Qed.\n\n  Fact gfp_equiv : equiv _ gfp.\n  Proof using i_trans i_sym i_refl gfp_trans gfp_sym gfp_refl HF3 HF2 HF1.\n    msplit 2.\n    + intro; apply gfp_refl; auto.\n    + intros ? y ? ? ?; apply gfp_trans; exists y; auto.\n    + intros ? ?; apply gfp_sym.\n  Qed.\n\n  Fact gfp_greatest R : R ⊆ F R -> R ⊆ gfp.\n  Proof using HF0.\n    intros HR x y H n; revert x y H.\n    induction n as [ | n IHn ].\n    + now auto.\n    + apply incl_trans with (1 := HR).\n      rewrite iS; apply HF0; auto.\n  Qed. \n\n  Let gfp_fix1 : F gfp ⊆ gfp.\n  Proof.\n    intros ? ? H ?.\n    apply i_S; rewrite iS.\n    revert H; apply HF0; auto.\n  Qed.\n\n  (* This is ω-continuity *)\n\n  Definition gfp_continuous := forall (s : nat -> M -> M -> Prop), \n                        (forall n m, n <= m -> s m ⊆ s n) \n                     -> (fun x y => forall n, F (s n) x y) ⊆ F (fun x y => forall n, s n x y).\n\n  Variable HF4 : gfp_continuous. \n\n  Let gfp_fix0 : gfp ⊆ F gfp.\n  Proof.\n    intros ? ? H.\n    apply HF4; auto.\n    intro; rewrite <- iS; apply H.\n  Qed.\n\n  Fact gfp_fix x y : F gfp x y <-> gfp x y.\n  Proof using i_decr i_S gfp_fix1 gfp_fix0 HF4 HF0. split; auto. Qed.\n\n  (* This is for decidability *)\n\n  Let dec R := forall x y, { R x y } + { ~ R x y }.\n\n  Variable HF5 : forall R, dec R -> dec (F R).       (* Preservation of decidability *)\n\n  Let i_dec n : dec (i n).\n  Proof.\n    induction n as [ | n IHn ].\n    + rewrite i0; left; auto.\n    + rewrite iS; apply HF5; auto.\n  Qed.\n\n  (* For the decidability of gfp, we need the finiteness\n      so that gfp = i n for a sufficiently large n *)\n\n  (* A good pair for i (ie n < m and i n ⊆ i m) means gfp is reached  at n *)\n\n  Let i_dup n m : n < m -> i n ⊆ i m -> forall k, n <= k -> forall x y, gfp x y <-> i k x y.\n  Proof.\n    intros H1 H2.\n    generalize (i_decr H1) (i_S n); rewrite iS; intros H3 H4.\n    generalize (incl_trans _ _ _ H2 H3); intros H5.\n    assert (forall p, i n ⊆ i (p+n)) as H6.\n    { induction p as [ | p IHp ]; auto.\n      simpl plus; rewrite iS.\n      apply incl_trans with (1 := H5), HF0; auto. }\n    intros k Hk x y; split; auto.\n    intros H a.\n    destruct (le_lt_dec a k).\n    + revert H; apply i_decr; auto.\n    + replace a with (a-n+n) by lia.\n      apply H6.\n      revert H; apply i_decr; auto.\n  Qed.\n\n  (* If there is a good pair below b, then gfp = i b *)\n\n  Let gfp_reached b : (exists n m, n < m <= b /\\ i n ⊆ i m) -> (forall x y, gfp x y <-> i b x y).\n  Proof.\n    intros (n & m & H1 & H2). \n    apply i_dup with (2 := H2); auto; try lia.\n  Qed.\n\n  Variable HF6 : finite_t M.     (* Finiteness of the domain *)\n\n  (* When M is finite, there is a list [T1;...;Tk] of relations of\n      type M -> M -> Prop which contains every weakly decidable relations \n      upto equivalence. \n\n      Hence, by the a generalized version of the PHP (proved w/o\n      assuming discreteness), for n greater than the length of\n      the list for M, one can find a duplicate\n      in the list [i 0; ...;i n] ie a < b <= n such\n      that i a ~ Tu ~ Tv ~ i b\n\n      Then one can deduce i n ~ gfp *)\n\n  Theorem gfp_finite_t : { n | forall x y, gfp x y <-> i n x y }.\n  Proof using i_dup i_decr i_dec i_S gfp_reached HF6 HF5 HF0.\n    destruct finite_t_weak_dec_rels with (1 := HF6)\n      as (mR & HmR).\n    exists (S (length mR)).\n    set (l := map i (list_an 0 (S (length mR)))).\n    apply (@gfp_reached (S (length mR))).\n    destruct php_upto \n      with (R := fun R T => forall x y, R x y <-> T x y)\n           (l := l) (m := mR)\n      as (a & R & b & T & c & H1 & H2).\n    + intros R S H ? ?; rewrite H; tauto.\n    + intros R S T H1 H2 ? ?; rewrite H1, H2; tauto.\n    + intros R HR.\n      unfold l in HR; apply in_map_iff in HR.\n      destruct HR as (n & <- & _).\n      destruct (HmR (i n)) as (T & H1 & H2).\n      * intros x y; destruct (i_dec n x y); tauto.\n      * exists T; auto.\n    + unfold l; rewrite map_length, list_an_length; auto.\n    + unfold l in H1; apply map_duplicate_inv in H1.\n      destruct H1 as (a' & n & b' & m & c' & H1 & H3 & H4 & H5 & H6 & H7).\n      exists n, m; rewrite <- H3, <- H5; split; try (intros ? ?; apply H2).\n      apply list_an_duplicate_inv in H7; lia.\n  Qed.\n\n  (* As a consequence of been reached after a finite number of steps, \n      gfp is one of the i n (for some computable n) and thus decidable *)\n\n  Theorem gfp_decidable : dec gfp.\n  Proof using i_dup i_decr i_dec i_S gfp_reached gfp_fix1 HF6 HF5 HF0.\n    destruct gfp_finite_t as (n & Hn).\n    intros x y; destruct (i_dec n x y); [ left | right ]; \n      rewrite Hn; tauto.\n  Qed.\n\nEnd gfp.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/TRAKHTENBROT/gfp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7418670303182051}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat div seq choice fintype.\nRequire Import bigops.\n\n(*****************************************************************************)\n(*   The algebraic part of the Algebraic Hierarchy, as described in          *)\n(*           \"Packaging mathematical structures\", TPHOLs09, by               *)\n(*   Francois Garillot, Georges Gonthier, Assia Mahboubi, Laurence Rideau    *)\n(*                                                                           *)\n(* This file defines for each Structure (Zmodule, Ring, etc ...) its type,   *)\n(* its packers and its canonical properties :                                *)\n(*                                                                           *)\n(*  * Zmodule                                                                *)\n(*      zmodType        == type for Zmodule structure                        *)\n(*      ZmodMixin       == builds the mixin containing the definition        *)\n(*                         of a Zmodule                                      *)\n(*      ZmodType M      == packs the mixin M to build a Zmodule of type      *)\n(*                         zmodType. (The underlying type should have a      *)\n(*                         choiceType canonical structure)                   *)\n(*      0               == the additive identity element of a Zmodule        *)\n(*      x + y           == the addition operation of a Zmodule               *)\n(*      - x             == the opposite operation of a Zmodule               *)\n(*      x - y           == the substraction operation of a Zmodule           *)\n(*                      := x + - y                                           *)\n(*      x +* n , x -* n == the generic multiplication by a nat               *)\n(*      \\sum_<range> e  == iterated sum for a Zmodule (cf bigops.v)          *)\n(*      e`_i            == nth 0 e i, when e : seq M and M is a zmodType     *)\n(*      ... and a many classical Lemmas on these Zmodule laws                *)\n(*                                                                           *)\n(*  * Ring                                                                   *)\n(*      ringType      == type for ring structure                             *)\n(*      RingMixin     == builds the mixin containing the definitions of a    *)\n(*                       ring (the underlying type should have a zmodType    *)\n(*                       structure)                                          *)\n(*      RingType M    == packs the ring mixin M to build a ring              *)\n(*      RevRingType T == repacks T to build the ring where the               *)\n(*                       multiplicative law is reversed ( x *' y = y * x )   *)\n(*      1             == the multiplicative identity element of a Ring       *)\n(*      n%:R          == the ring image of a nat n (e.g., 1%:R := 1%R)       *)\n(*      x * y         == the multiplication operation of a ring              *)\n(*    \\prod_<range> e == iterated product for a ring (cf bigops.v)           *)\n(*      x ^+ y        == the exponentiation operation of a ring              *)\n(*      GRing.comm x y <=> x and y commute, i.e., x * y = y * x              *)\n(*                                                                           *)\n(*  * Commutative Ring                                                       *)\n(*      comRingType      == type for commutative ring structure              *)\n(*      ComRingMixin     == builds the mixin containing the definitions of a *)\n(*                          *non commutative* ring, but using                *)\n(*                         commutative ring mixin mulC. (The underlying type *)\n(*                         should have a Zmodule canonical structure)        *)\n(*      ComRingType mulC == packs mulC to build a commutative ring.          *)\n(*                          (The underlying type should have a ring          *)\n(*                          canonical structure)                             *)\n(*                                                                           *)\n(*  * Unit Ring                                                              *)\n(*      unitRingType   == type for unit ring structure                       *)\n(*      UnitRingMixin  == builds the mixin containing the definitions        *)\n(*                        of a unit ring. (The underlying type should        *)\n(*                        have a ring canonical structure)                   *)\n(*      UnitRingType M == packs the unit ring mixin M to build a unit ring   *)\n(*      GRing.unit x   == x is a unit (i.e., has an inverse)                 *)\n(*      x^-1           == the inversion operation element of a unit ring     *)\n(*                        (returns x if is x is not an unit)                 *)\n(*      x / y          := x * y^-1                                           *)\n(*      x ^- n         := (x ^+ n)^-1                                        *)\n(*                                                                           *)\n(*  * Commutative Unit Ring                                                  *)\n(*      comUnitRingType   == type for unit ring structure                    *)\n(*      ComUnitRingMixin  == builds the mixin containing the definitions     *)\n(*                           of a *non commutative unit ring*, but using     *)\n(*                           the commutative property. (The underlying type  *)\n(*                           should have a ring canonical structure)         *)\n(*      ComUnitRingType M == packs the *unit ring mixin* M to build a unit   *)\n(*                           ring. (The underlying type should have a        *)\n(*                           commutative ring canonical structure)           *)\n(*                                                                           *)\n(*  * Integral Domain (integral, commutative, unit ring)                     *)\n(*      idomainType       == type for integral domain structure              *)\n(*      IdomainType M     == packs the idomain mixin M to build a integral   *)\n(*                           domain. (The underlying type should have a      *)\n(*                           commutative unit ring canonical structure)      *)\n(*                                                                           *)\n(*  * Field                                                                  *)\n(*      fieldType         == type for field structure                        *)\n(*      FieldUnitMixin    == builds a *non commutative unit ring* mixin,     *)\n(*                           using some field properties. (The underlying    *)\n(*                           type should have a *commutative ring* canonical *)\n(*                           structure)                                      *)\n(*      FieldMixin        == builds the field mixin. (The underlying type    *)\n(*                           should have a *commutative ring* canonical      *)\n(*                           structure)                                      *)\n(*      FieldIdomainMixin == builds an *idomain* mixin, using a field mixin  *)\n(*      FieldType M       == packs the field mixin M to build a field        *)\n(*                           (The underlying type should have a              *)\n(*                           integral domain canonical structure)            *)\n(*                                                                           *)\n(*  * Decidable Field                                                        *)\n(*      decFieldType      == type for decidable field structure              *)\n(*      DecFieldMixin     == builds the mixin containing the definitions of  *)\n(*                           a decidable Field. (The underlying type should  *)\n(*                           have a unit ring canonical structure)           *)\n(*      DecFieldType M    == packs the decidable field mixin M to build a    *)\n(*                           decidable field. (The underlying type should    *)\n(*                           have a field canonical structure)               *)\n(*      GRing.term R      == the type of formal expressions in a unit ring R *)\n(*                           with formal variables 'X_i, i : nat             *)\n(*      GRing.formula R   == the type of first order formulas over R         *)\n(*      GRing.eval t e    == the value of term t with valuation e : seq R    *)\n(*                           (e maps 'X_i to e`_i)                           *)\n(*      GRing.holds f e   == the intuitionistic CiC interpretation of the    *)\n(*                           formula f holds with valuation e                *)\n(*      GRing.sat f e     == valuation e satisfies f                         *)\n(*      GRing.sol f n     == a sequence e of size n such that e satisfies f, *)\n(*                           if one exists, or nil if there is no such e     *)\n(*                                                                           *)\n(*  * Closed Field                                                           *)\n(*      closedFieldType   == type for closed field structure                 *)\n(*      ClosedFieldType M == packs the closed field mixin M to build a       *)\n(*                           closed field. (The underlying type should have  *)\n(*                           a decidable field canonical structure)          *)\n(*                                                                           *)\n(* The Lemmas about theses structures are all contained in GRing.Theory.     *)\n(* Notations are defined in scope ring_scope (delimiter %R), except term and *)\n(* formula notations, which are in term_scope (delimiter %T).                *)\n(*                                                                           *)\n(* NB: The module GRing should not be imported, only the main module and     *)\n(*     GRing.Theory should be.                                               *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Abstract algebra framework for ssreflect.                        *)\n(* We define a number of structures that \"package\" common algebraic *)\n(* properties of operations. These extend the combinatorial classes *)\n(* with notation and theory for classical algebraic structures.     *)\n\nReserved Notation \"+%R\" (at level 0).\nReserved Notation \"-%R\" (at level 0).\nReserved Notation \"*%R\" (at level 0).\nReserved Notation \"n %:R\"\n  (at level 2, R at level 1, left associativity, format \"n %:R\").\n\nDelimit Scope ring_scope with R.\nDelimit Scope term_scope with T.\n\nModule GRing.\n\nImport Monoid.Theory.\n\nModule Zmodule.\n\nRecord mixin_of (M : Type) : Type := Mixin {\n  zero : M;\n  opp : M -> M;\n  add : M -> M -> M;\n  _ : associative add;\n  _ : commutative add;\n  _ : left_id zero add;\n  _ : left_inverse zero opp add\n}.\n\nRecord class_of (M : Type) : Type :=\n  Class { base :> Choice.class_of M; ext :> mixin_of M }.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack := let k T c m := Pack (@Class T c m) T in Choice.unpack k.\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nCoercion choiceType cT := Choice.Pack (class cT) cT.\n\nEnd Zmodule.\n\nCanonical Structure Zmodule.eqType.\nCanonical Structure Zmodule.choiceType.\nBind Scope ring_scope with Zmodule.sort.\n\nDefinition zero M := Zmodule.zero (Zmodule.class M).\nDefinition opp M := Zmodule.opp (Zmodule.class M).\nDefinition add M := Zmodule.add (Zmodule.class M).\n\nNotation Local \"0\" := (zero _).\nNotation Local \"-%R\" := (@opp _).\nNotation Local \"- x\" := (opp x).\nNotation Local \"+%R\" := (@add _).\nNotation Local \"x + y\" := (add x y).\nNotation Local \"x - y\" := (x + - y).\n\nDefinition natmul M x n := nosimpl iterop _ n +%R x (zero M).\n\nNotation Local \"x *+ n\" := (natmul x n).\nNotation Local \"x *- n\" := ((- x) *+ n).\n\nNotation \"\\sum_ ( i <- r | P ) F\" := (\\big[+%R/0]_(i <- r | P) F).\nNotation \"\\sum_ ( m <= i < n ) F\" := (\\big[+%R/0]_(m <= i < n) F).\nNotation \"\\sum_ ( i < n ) F\" := (\\big[+%R/0]_(i < n) F).\nNotation \"\\sum_ ( i \\in A ) F\" := (\\big[+%R/0]_(i \\in A) F).\n\nSection ZmoduleTheory.\n\nVariable M : Zmodule.type.\nImplicit Types x y : M.\n\nLemma addrA : @associative M +%R. Proof. by case M => T [? []]. Qed.\nLemma addrC : @commutative M +%R. Proof. by case M => T [? []]. Qed.\nLemma add0r : @left_id M 0 +%R. Proof. by case M => T [? []]. Qed.\nLemma addNr : @left_inverse M 0 -%R +%R. Proof. by case M => T [? []]. Qed.\n\nLemma addr0 : @right_id M 0 +%R.\nProof. by move=> x; rewrite addrC add0r. Qed.\nLemma addrN : @right_inverse M 0 -%R +%R.\nProof. by move=> x; rewrite addrC addNr. Qed.\nDefinition subrr := addrN.\n\nCanonical Structure add_monoid := Monoid.Law addrA add0r addr0.\nCanonical Structure add_comoid := Monoid.ComLaw addrC.\n\nLemma addrCA : @left_commutative M +%R. Proof. exact: mulmCA. Qed.\nLemma addrAC : @right_commutative M +%R. Proof. exact: mulmAC. Qed.\n\nLemma addKr : forall x, cancel ( +%R x) ( +%R (- x)).\nProof. by move=> x y; rewrite addrA addNr add0r. Qed.\nLemma addNKr : forall x, cancel ( +%R (- x)) ( +%R x).\nProof. by move=> x y; rewrite addrA addrN add0r. Qed.\nLemma addrK : forall x, cancel ( +%R^~ x) ( +%R^~ (- x)).\nProof. by move=> x y; rewrite -addrA addrN addr0. Qed.\nLemma addrNK : forall x, cancel ( +%R^~ (- x)) ( +%R^~ x).\nProof. by move=> x y; rewrite -addrA addNr addr0. Qed.\nDefinition subrK := addrNK.\nLemma addrI : forall y, injective (add y).\nProof. move=> x; exact: can_inj (addKr x). Qed.\nLemma addIr : forall y, injective ( +%R^~ y).\nProof. move=> y; exact: can_inj (addrK y). Qed.\nLemma opprK : @involutive M -%R.\nProof. by move=> x; apply: (@addIr (- x)); rewrite addNr addrN. Qed.\nLemma oppr0 : -0 = 0 :> M.\nProof. by rewrite -[-0]add0r subrr. Qed.\nLemma oppr_eq0 : forall x, (- x == 0) = (x == 0).\nProof. by move=> x; rewrite (inv_eq opprK) oppr0. Qed.\n\nLemma oppr_add : {morph -%R: x y / x + y : M}.\nProof.\nby move=> x y; apply: (@addrI (x + y)); rewrite addrA subrr addrAC addrK subrr.\nQed.\n\nLemma oppr_sub : forall x y, - (x - y) = y - x.\nProof. by move=> x y; rewrite oppr_add addrC opprK. Qed.\n\nLemma subr_eq : forall x y z, (x - z == y) = (x == y + z).\nProof. by move=> x y z; rewrite (can2_eq (subrK _) (addrK _)). Qed.\n\nLemma subr_eq0 : forall x y, (x - y == 0) = (x == y).\nProof. by move=> x y; rewrite subr_eq add0r. Qed.\n\nLemma mulr0n : forall x, x *+ 0 = 0. Proof. by []. Qed.\nLemma mulr1n : forall x, x *+ 1 = x. Proof. by []. Qed.\n\nLemma mulrS : forall x n, x *+ n.+1 = x + x *+ n.\nProof. by move=> x [|n] //=; rewrite addr0. Qed.\n\nLemma mulrSr : forall x n, x *+ n.+1 = x *+ n + x.\nProof. by move=> x n; rewrite addrC mulrS. Qed.\n\nLemma mul0rn : forall n, 0 *+ n = 0 :> M.\nProof. by elim=> // n IHn; rewrite mulrS add0r. Qed.\n\nLemma oppr_muln : forall x n, - (x *+ n) = x *- n :> M.\nProof.\nby move=> x; elim=> [|n IHn]; rewrite ?oppr0 // !mulrS oppr_add IHn.\nQed.\n\nLemma mulrn_addl : forall n, {morph (fun x => x *+ n) : x y / x + y}.\nProof.\nmove=> n x y; elim: n => [|n IHn]; rewrite ?addr0 // !mulrS.\nby rewrite addrCA -!addrA -IHn -addrCA.\nQed.\n\nLemma mulrn_addr : forall x m n, x *+ (m + n) = x *+ m + x *+ n.\nProof.\nmove=> x n m; elim: n => [|n IHn]; first by rewrite add0r.\nby rewrite !mulrS IHn addrA.\nQed.\n\nLemma mulrnA : forall x m n, x *+ (m * n) = x *+ m *+ n.\nProof.\nmove=> x m n; rewrite mulnC.\nby elim: n => //= n IHn; rewrite mulrS mulrn_addr IHn.\nQed.\n\nLemma mulrnAC : forall x m n, x *+ m *+ n = x *+ n *+ m.\nProof. by move=> x m n; rewrite -!mulrnA mulnC. Qed.\n\nLemma sumr_opp : forall I r P (F : I -> M),\n  (\\sum_(i <- r | P i) - F i = - (\\sum_(i <- r | P i) F i)).\nProof. by move=> I r P F; rewrite (big_morph _ oppr_add oppr0). Qed.\n\nLemma sumr_sub : forall I r (P : pred I) (F1 F2 : I -> M),\n  \\sum_(i <- r | P i) (F1 i - F2 i)\n     = \\sum_(i <- r | P i) F1 i - \\sum_(i <- r | P i) F2 i.\nProof. by move=> *; rewrite -sumr_opp -big_split /=. Qed.\n\nLemma sumr_muln :  forall I r P (F : I -> M) n,\n  \\sum_(i <- r | P i) F i *+ n = (\\sum_(i <- r | P i) F i) *+ n.\nProof.\nby move=> I r P F n; rewrite (big_morph _ (mulrn_addl n) (mul0rn _)).\nQed.\n\nLemma sumr_const : forall (I : finType) (A : pred I) (x : M),\n  \\sum_(i \\in A) x = x *+ #|A|.\nProof. by move=> I A x; rewrite big_const -iteropE. Qed.\n\nEnd ZmoduleTheory.\n\nModule Ring.\n\nRecord mixin_of (R : Zmodule.type) : Type := Mixin {\n  one : R;\n  mul : R -> R -> R;\n  _ : associative mul;\n  _ : left_id one mul;\n  _ : right_id one mul;\n  _ : left_distributive mul +%R;\n  _ : right_distributive mul +%R;\n  _ : one != 0\n}.\n\nDefinition EtaMixin R one mul mulA mul1x mulx1 mul_addl mul_addr nz1 :=\n  let _ := @Mixin R one mul mulA mul1x mulx1 mul_addl mul_addr nz1 in\n  @Mixin (Zmodule.Pack (Zmodule.class R) R) _ _\n     mulA mul1x mulx1 mul_addl mul_addr nz1.\n\nRecord class_of (R : Type) : Type := Class {\n  base :> Zmodule.class_of R;\n  ext :> mixin_of (Zmodule.Pack base R)\n}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack := let k T c m := Pack (@Class T c m) T in Zmodule.unpack k.\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nCoercion zmodType cT := Zmodule.Pack (class cT) cT.\n\nEnd Ring.\n\nBind Scope ring_scope with Ring.sort.\nCanonical Structure Ring.eqType.\nCanonical Structure Ring.choiceType.\nCanonical Structure Ring.zmodType.\n\nDefinition one (R : Ring.type) : R := Ring.one (Ring.class R).\nDefinition mul (R : Ring.type) : R -> R -> R := Ring.mul (Ring.class R).\nDefinition exp R x n := nosimpl iterop _ n (@mul R) x (one R).\n\nNotation Local \"1\" := (one _).\nNotation Local \"- 1\" := (- (1)).\nNotation Local \"n %:R\" := (1 *+ n).\nNotation Local \"*%R\" := (@mul _).\nNotation Local \"x * y\" := (mul x y).\nNotation Local \"x ^+ n\" := (exp x n).\n\nNotation \"\\prod_ ( i <- r | P ) F\" := (\\big[*%R/1]_(i <- r | P) F).\nNotation \"\\prod_ ( i \\in A ) F\" := (\\big[*%R/1]_(i \\in A) F).\n\nSection RingTheory.\n\nVariable R : Ring.type.\nImplicit Types x y : R.\n\nLemma mulrA : @associative R *%R. Proof. by case R => T [? []]. Qed.\nLemma mul1r : @left_id R 1 *%R. Proof. by case R => T [? []]. Qed.\nLemma mulr1 : @right_id R 1 *%R. Proof. by case R => T [? []]. Qed.\nLemma mulr_addl : @left_distributive R *%R +%R.\nProof. by case R => T [? []]. Qed.\nLemma mulr_addr : @right_distributive R *%R +%R.\nProof. by case R => T [? []]. Qed.\nLemma nonzero1r : 1 != 0 :> R. Proof. by case R => T [? []]. Qed.\nLemma oner_eq0 : (1 == 0 :> R) = false. Proof. exact: negbTE nonzero1r. Qed.\n\nLemma mul0r : @left_zero R 0 *%R.\nProof.\nby move=> x; apply: (@addIr _ (1 * x)); rewrite -mulr_addl !add0r mul1r.\nQed.\nLemma mulr0 : @right_zero R 0 *%R.\nProof.\nby move=> x; apply: (@addIr _ (x * 1)); rewrite -mulr_addr !add0r mulr1.\nQed.\nLemma mulrN : forall x y, x * (- y) = - (x * y).\nProof.\nby move=> x y; apply: (@addrI _ (x * y)); rewrite -mulr_addr !subrr mulr0.\nQed.\nLemma mulNr : forall x y, (- x) * y = - (x * y).\nProof.\nby move=> x y; apply: (@addrI _ (x * y)); rewrite -mulr_addl !subrr mul0r.\nQed.\nLemma mulrNN : forall x y, (- x) * (- y) = x * y.\nProof. by move=> x y; rewrite mulrN mulNr opprK. Qed.\nLemma mulN1r : forall x, -1 * x = - x.\nProof. by move=> x; rewrite mulNr mul1r. Qed.\nLemma mulrN1 : forall x, x * -1 = - x.\nProof. by move=> x; rewrite mulrN mulr1. Qed.\n\nCanonical Structure mul_monoid := Monoid.Law mulrA mul1r mulr1.\nCanonical Structure muloid := Monoid.MulLaw mul0r mulr0.\nCanonical Structure addoid := Monoid.AddLaw mulr_addl mulr_addr.\n\nLemma mulr_natr : forall x n, x * n%:R = x *+ n.\nProof.\nby move=> x; elim=> [|n IHn]; rewrite ?mulr0 // !mulrS mulr_addr IHn mulr1.\nQed.\n\nLemma mulr_natl : forall n x, n%:R * x = x *+ n.\nProof.\nmove=> n x; elim: n => [|n IHn]; first exact: mul0r.\nby rewrite !mulrS mulr_addl mul1r IHn.\nQed.\n\nLemma natr_add : forall m n, (m + n)%:R = m%:R + n%:R :> R.\nProof. by move=> m n; exact: mulrn_addr. Qed.\n\nLemma natr_mul : forall m n, (m * n)%:R = m%:R * n%:R :> R.\nProof. by move=> m n; rewrite mulrnA -mulr_natr. Qed.\n\nLemma expr0 : forall x, x ^+ 0 = 1. Proof. by []. Qed.\nLemma expr1 : forall x, x ^+ 1 = x. Proof. by []. Qed.\n\nLemma exprS : forall x n, x ^+ n.+1 = x * x ^+ n.\nProof. by move=> x [] //; rewrite mulr1. Qed.\n\nLemma exp1rn : forall n, 1 ^+ n = 1 :> R.\nProof. by elim=> // n IHn; rewrite exprS mul1r. Qed.\n\nLemma exprn_addr : forall x m n, x ^+ (m + n) = x ^+ m * x ^+ n.\nProof.\nby move=> x m n; elim: m => [|m IHm]; rewrite ?mul1r // !exprS -mulrA -IHm.\nQed.\n\nLemma exprSr : forall x n, x ^+ n.+1 = x ^+ n * x.\nProof. by move=> x n; rewrite -addn1 exprn_addr expr1. Qed.\n\nDefinition commDef x y := x * y = y * x.\nNotation comm := commDef.\n\nLemma commr_sym : forall x y, comm x y -> comm y x. Proof. done. Qed.\nLemma commr_refl : forall x, comm x x. Proof. done. Qed.\n\nLemma commr0 : forall x, comm x 0.\nProof. by move=> x; rewrite /comm mulr0 mul0r. Qed.\n\nLemma commr1 : forall x, comm x 1.\nProof. by move=> x; rewrite /comm mulr1 mul1r. Qed.\n\nLemma commr_opp : forall x y, comm x y -> comm x (- y).\nProof. by move=> x y com_xy; rewrite /comm mulrN com_xy mulNr. Qed.\n\nLemma commrN1 : forall x, comm x (-1).\nProof. move=> x; apply: commr_opp; exact: commr1. Qed.\n\nLemma commr_add : forall x y z,\n  comm x y -> comm x z -> comm x (y + z).\nProof. by move=> x y z; rewrite /comm mulr_addl mulr_addr => -> ->. Qed.\n\nLemma commr_muln : forall x y n, comm x y -> comm x (y *+ n).\nProof.\nrewrite /comm => x y n com_xy.\nby elim: n => [|n IHn]; rewrite ?commr0 // mulrS commr_add.\nQed.\n\nLemma commr_mul : forall x y z,\n  comm x y -> comm x z -> comm x (y * z).\nProof.\nby move=> x y z com_xy; rewrite /comm mulrA com_xy -!mulrA => ->.\nQed.\n\nLemma commr_nat : forall x n, comm x n%:R.\nProof. move=> x n; apply: commr_muln; exact: commr1. Qed.\n\nLemma commr_exp : forall x y n, comm x y -> comm x (y ^+ n).\nProof.\nrewrite /comm => x y n com_xy.\nby elim: n => [|n IHn]; rewrite ?commr1 // exprS commr_mul.\nQed.\n\nLemma commr_exp_mull : forall x y n,\n  comm x y -> (x * y) ^+ n = x ^+ n * y ^+ n.\nProof.\nmove=> x y n com_xy; elim: n => /= [|n IHn]; first by rewrite mulr1.\nby rewrite !exprS IHn !mulrA; congr (_ * _); rewrite -!mulrA -commr_exp.\nQed.\n\nLemma exprn_mulnl : forall x m n, (x *+ m) ^+ n = x ^+ n *+ (m ^ n) :> R.\nProof.\nmove=> x m; elim=> [|n IHn]; first by rewrite mulr1n.\nrewrite exprS IHn -mulr_natr -mulrA -commr_nat mulr_natr -mulrnA -expnSr.\nby rewrite -mulr_natr mulrA -exprS mulr_natr.\nQed.\n\nLemma exprn_mulr : forall x m n, x ^+ (m * n) = x ^+ m ^+ n.\nProof.\nmove=> x m n; elim: m => [|m IHm]; first by rewrite exp1rn.\nby rewrite mulSn exprn_addr IHm exprS commr_exp_mull //; exact: commr_exp.\nQed.\n\nLemma signr_odd : forall n, (-1) ^+ (odd n) = (-1) ^+ n :> R.\nProof.\nelim=> //= n IHn; rewrite exprS -{}IHn.\nby case/odd: n; rewrite !mulN1r ?opprK.\nQed.\n\nLemma signr_eq0 :  forall n, ((-1) ^+ n == 0 :> R) = false.\nProof.\nby move=> n; rewrite -signr_odd; case: odd; rewrite ?oppr_eq0 oner_eq0.\nQed.\n\nLemma signr_addb : forall b1 b2,\n  (-1) ^+ (b1 (+) b2) = (-1) ^+ b1 * (-1) ^+ b2 :> R.\nProof. by do 2!case; rewrite ?expr1 ?mulN1r ?mul1r ?opprK. Qed.\n\nLemma exprN : forall x n, (- x) ^+ n = (-1) ^+ n * x ^+ n :> R.\nProof.\nby move=> x n; rewrite -mulN1r commr_exp_mull // /comm mulN1r mulrN mulr1.\nQed.\n\nLemma prodr_const : forall (I : finType) (A : pred I) (x : R),\n  \\prod_(i \\in A) x = x ^+ #|A|.\nProof. by move=> I A x; rewrite big_const -iteropE. Qed.\n\nDefinition RevRingMixin :=\n  let mul' x y := y * x in\n  let mulrA' x y z := esym (mulrA z y x) in\n  let mulr_addl' x y z := mulr_addr z x y in\n  let mulr_addr' x y z := mulr_addl y z x in\n  @Ring.Mixin R 1 mul' mulrA' mulr1 mul1r mulr_addl' mulr_addr' nonzero1r.\n\nDefinition RevRingType := Ring.Pack (Ring.Class RevRingMixin) R.\n\n\nEnd RingTheory.\n\nNotation comm := (@commDef _).\n\nNotation rev :=\n  (let R := _ in fun (x : Ring.sort R) => x : Ring.sort (RevRingType R)).\n\nDefinition ring_morphism (aR rR : Ring.type) (f : aR -> rR) :=\n  [/\\ {morph f : x y / x - y}, {morph f : x y / x * y} & f 1 = 1].\n\nSection RingMorphTheory.\n\nVariables aR' aR rR : Ring.type.\nVariables (f : aR -> rR) (g : aR' -> aR).\nHypotheses (fM : ring_morphism f) (gM : ring_morphism g).\n\nLemma ringM_sub : {morph f : x y / x - y}.\nProof. by case fM. Qed.\n\nLemma ringM_0 : f 0 = 0.\nProof. by rewrite -(subrr 0) ringM_sub subrr. Qed.\n\nLemma ringM_1 : f 1 = 1.\nProof. by case fM. Qed.\n\nLemma ringM_opp : {morph f : x / - x}.\nProof. by move=> x /=; rewrite -[-x]add0r ringM_sub ringM_0 add0r. Qed.\n\nLemma ringM_add : {morph f : x y / x + y}.\nProof. by move=> x y /=; rewrite -(opprK y) ringM_opp ringM_sub. Qed.\n\nDefinition ringM_sum := big_morph f ringM_add ringM_0.\n\nLemma ringM_mul : {morph f : x y / x * y}.\nProof. by case fM. Qed.\n\nDefinition ringM_prod := big_morph f ringM_mul ringM_1.\n\nLemma ringM_nat : forall n, f n%:R = n %:R.\nProof.\nby elim=> [|n IHn]; rewrite ?ringM_0 // !mulrS ringM_add IHn ringM_1.\nQed.\n\nLemma ringM_exp : forall n, {morph f : x / x ^+ n}.\nProof.  by elim=> [|n IHn] x; rewrite ?ringM_1 //  !exprS ringM_mul IHn. Qed.\n\nLemma comp_ringM : ring_morphism (f \\o g).\nProof.\ncase: fM gM => [fsub fmul f1] [gsub gmul g1].\nby split=> [x y | x y |] /=; rewrite ?g1 ?gsub ?gmul.\nQed.\n\n\nEnd RingMorphTheory.\n\n\n\nModule ComRing.\n\nRecord class_of (R : Type) : Type :=\n  Class {base :> Ring.class_of R; _ : commutative (Ring.mul base)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack : forall R, commutative *%R -> type :=\n  let k T c m := Pack (@Class T c m) T in Ring.unpack k.\n\nDefinition RingMixin R one mul mulA mulC mul1x mul_addl :=\n  let mulx1 := Monoid.mulC_id mulC mul1x in\n  let mul_addr := Monoid.mulC_dist mulC mul_addl in\n  @Ring.EtaMixin R one mul mulA mul1x mulx1 mul_addl mul_addr.\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nDefinition zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\n\nEnd ComRing.\n\nCanonical Structure ComRing.eqType.\nCanonical Structure ComRing.choiceType.\nCanonical Structure ComRing.zmodType.\nCanonical Structure ComRing.ringType.\nBind Scope ring_scope with ComRing.sort.\n\nSection ComRingTheory.\n\nVariable R : ComRing.type.\nImplicit Types x y : R.\n\nLemma mulrC : @commutative R *%R. Proof. by case: R => T []. Qed.\nCanonical Structure mul_comoid := Monoid.ComLaw mulrC.\nLemma mulrCA : @left_commutative R *%R. Proof. exact: mulmCA. Qed.\nLemma mulrAC : @right_commutative R *%R. Proof. exact: mulmAC. Qed.\n\nLemma exprn_mull : forall n, {morph (fun x => x ^+ n) : x y / x * y}.\nProof. move=> n x y; apply: commr_exp_mull; exact: mulrC. Qed.\n\nLemma prodr_exp : forall n I r (P : pred I) (F : I -> R),\n  \\prod_(i <- r | P i) F i ^+ n = (\\prod_(i <- r | P i) F i) ^+ n.\nProof.\nby move=> n I r P F; rewrite (big_morph _ (exprn_mull n) (exp1rn _ n)).\nQed.\n\nEnd ComRingTheory.\n\nModule UnitRing.\n\nRecord mixin_of (R : Ring.type) : Type := Mixin {\n  unit : pred R;\n  inv : R -> R;\n  _ : {in unit, left_inverse 1 inv *%R};\n  _ : {in unit, right_inverse 1 inv *%R};\n  _ : forall x y, y * x = 1 /\\ x * y = 1 -> unit x;\n  _ : {in predC unit, inv =1 id}\n}.\n\nDefinition EtaMixin R unit inv mulVr mulrV unitP inv_out :=\n  let _ := @Mixin R unit inv mulVr mulrV unitP inv_out in\n  @Mixin (Ring.Pack (Ring.class R) R) unit inv mulVr mulrV unitP inv_out.\n\nRecord class_of (R : Type) : Type := Class {\n  base :> Ring.class_of R;\n  mixin :> mixin_of (Ring.Pack base R)\n}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack := let k T c m := Pack (@Class T c m) T in Ring.unpack k.\nDefinition comPack := (* pack ComUnitRing mixin *)\n  let k T cc :=\n    let: ComRing.Class c _ := cc return mixin_of (Ring.Pack cc T) -> type\n    in fun m => Pack (Class m) T\n  in ComRing.unpack k.\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nDefinition zmodType cT := Zmodule.Pack (class cT) cT.\nCoercion ringType cT := Ring.Pack (class cT) cT.\n\nEnd UnitRing.\n\nCanonical Structure UnitRing.eqType.\nCanonical Structure UnitRing.zmodType.\nCanonical Structure UnitRing.ringType.\nBind Scope ring_scope with UnitRing.sort.\n\nDefinition unitDef (R : UnitRing.type) : pred R :=\n  UnitRing.unit (UnitRing.class R).\nNotation unit := (@unitDef _).\nDefinition inv (R : UnitRing.type) : R -> R := UnitRing.inv (UnitRing.class R).\n\nNotation Local \"x ^-1\" := (inv x).\nNotation Local \"x / y\" := (x * y^-1).\nNotation Local \"x ^- n\" := ((x ^+ n)^-1).\n\nSection UnitRingTheory.\n\nVariable R : UnitRing.type.\nImplicit Types x y : R.\n\nLemma divrr : forall x, unit x -> x / x = 1.\nProof. by case: R => T [? []]. Qed.\nDefinition mulrV := divrr.\n\nLemma mulVr : forall x, unit x -> x^-1 * x = 1.\nProof. by case: R => T [? []]. Qed.\n\nLemma invr_out : forall x, ~~ unit x -> x^-1 = x.\nProof. by case: R => T [? []]. Qed.\n\nLemma unitrP : forall x, reflect (exists y, y * x = 1 /\\ x * y = 1) (unit x).\nProof.\nmove=> x; apply: (iffP idP) => [Ux | []]; last by case: R x => T [? []].\nby exists x^-1; rewrite divrr ?mulVr.\nQed.\n\nLemma mulKr : forall x, unit x -> cancel (mul x) (mul x^-1).\nProof. by move=> x Ux y; rewrite mulrA mulVr ?mul1r. Qed.\n\nLemma mulVKr : forall x, unit x -> cancel (mul x^-1) (mul x).\nProof. by move=> x Ux y; rewrite mulrA mulrV ?mul1r. Qed.\n\nLemma mulrK : forall x, unit x -> cancel ( *%R^~ x) ( *%R^~ x^-1).\nProof. by move=> x Ux y; rewrite -mulrA divrr ?mulr1. Qed.\n\nLemma mulrVK : forall x, unit x -> cancel ( *%R^~ x^-1) ( *%R^~ x).\nProof. by move=> x Ux y; rewrite -mulrA mulVr ?mulr1. Qed.\nDefinition divrK := mulrVK.\n\nLemma mulrI : forall x, unit x -> injective (mul x).\nProof. move=> x Ux; exact: can_inj (mulKr Ux). Qed.\n\nLemma mulIr : forall x, unit x -> injective ( *%R^~ x).\nProof. move=> x Ux; exact: can_inj (mulrK Ux). Qed.\n\nLemma commr_inv : forall x, comm x x^-1.\nProof.\nmove=> x; case Ux: (unit x); last by rewrite invr_out ?Ux.\nby rewrite /comm mulVr ?divrr.\nQed.\n\nLemma unitrE : forall x, unit x = (x / x == 1).\nProof.\nmove=> x; apply/idP/eqP=> [Ux | xx1]; first exact: divrr.\nby apply/unitrP; exists x^-1; rewrite -commr_inv.\nQed.\n\nLemma invrK : involutive (@inv R).\nProof.\nmove=> x; case Ux: (unit x); last by rewrite !invr_out ?Ux.\nrewrite -(mulrK Ux _^-1) -mulrA commr_inv mulKr //.\nby apply/unitrP; exists x; rewrite divrr ?mulVr.\nQed.\n\nLemma invr_inj : injective (@inv R).\nProof. exact: inv_inj invrK. Qed.\n\nLemma unitr_inv : forall x, unit x^-1 = unit x.\nProof. by move=> x; rewrite !unitrE invrK commr_inv. Qed.\n\nLemma unitr1 : unit (1 : R).\nProof. by apply/unitrP; exists (1 : R); rewrite mulr1. Qed.\n\nLemma invr1 : 1^-1 = 1 :> R.\nProof. by rewrite -{2}(mulVr unitr1) mulr1. Qed.\n\nLemma unitr0 : unit (0 : R) = false.\nProof.\nby apply/unitrP=> [[x [_]]]; apply/eqP; rewrite mul0r eq_sym nonzero1r.\nQed.\n\nLemma invr0 : 0^-1 = 0 :> R.\nProof. by rewrite invr_out ?unitr0. Qed.\n\nLemma unitr_opp : forall x, unit (- x) = unit x.\nProof.\nmove=> x; wlog Ux: x / unit x.\n  by move=> WHx; apply/idP/idP=> Ux; first rewrite -(opprK x); rewrite WHx.\nby rewrite Ux; apply/unitrP; exists (- x^-1); rewrite !mulrNN mulVr ?divrr.\nQed.\n\nLemma invrN : forall x, (- x)^-1 = - x^-1.\nProof.\nmove=> x; case Ux: (unit x) (unitr_opp x) => [] Unx.\n  by apply: (mulrI Unx); rewrite mulrNN !divrr.\nby rewrite !invr_out ?Ux ?Unx.\nQed.\n\nLemma unitr_mull : forall x y, unit y -> unit (x * y) = unit x.\nProof.\nmove=> x y Uy; wlog Ux: x y Uy / unit x => [WHxy|].\n  by apply/idP/idP=> Ux; first rewrite -(mulrK Uy x); rewrite WHxy ?unitr_inv.\nrewrite Ux; apply/unitrP; exists (y^-1 * x^-1).\nby rewrite -!mulrA mulKr ?mulrA ?mulrK ?divrr ?mulVr.\nQed.\n\nLemma unitr_mulr : forall x y, unit x -> unit (x * y) = unit y.\nProof.\nmove=> x y Ux; apply/idP/idP=> [Uxy | Uy]; last by rewrite unitr_mull.\nby rewrite -(mulKr Ux y) unitr_mull ?unitr_inv.\nQed.\n\nLemma invr_mul : forall x y, unit x -> unit y -> (x * y)^-1 = y^-1 * x^-1.\nProof.\nmove=> x y Ux Uy; have Uxy: unit (x * y) by rewrite unitr_mull.\nby apply: (mulrI Uxy); rewrite divrr ?mulrA ?mulrK ?divrr.\nQed.\n\nLemma commr_unit_mul : forall x y, comm x y -> unit (x * y) = unit x && unit y.\nProof.\nmove=> x y cxy; apply/idP/andP=> [Uxy | [Ux Uy]]; last by rewrite unitr_mull.\nsuffices Ux: unit x by rewrite unitr_mulr in Uxy.\napply/unitrP; case/unitrP: Uxy => z [zxy xyz]; exists (y * z).\nrewrite mulrA xyz -{1}[y]mul1r -{1}zxy cxy -!mulrA (mulrA x) (mulrA _ z) xyz.\nby rewrite mul1r -cxy.\nQed.\n\nLemma unitr_exp : forall x n, unit x -> unit (x ^+ n).\nProof.\nby move=> x n Ux; elim: n => [|n IHn]; rewrite ?unitr1 // exprS unitr_mull.\nQed.\n\nLemma unitr_pexp : forall x n, n > 0 -> unit (x ^+ n) = unit x.\nProof.\nmove=> x [//|n] _; rewrite exprS commr_unit_mul; last exact: commr_exp.\nby case Ux: (unit x); rewrite // unitr_exp.\nQed.\n\nLemma expr_inv : forall x n, x^-1 ^+ n = x ^- n.\nProof.\nmove=> x; elim=> [|n IHn]; first by rewrite !expr0 ?invr1.\ncase Ux: (unit x); first by rewrite exprSr exprS IHn -invr_mul // unitr_exp.\nby rewrite !invr_out ?unitr_pexp ?Ux.\nQed.\n\nLemma invr_neq0 : forall x, x != 0 -> x^-1 != 0.\nProof.\nmove=> x nx0; case Ux: (unit x); last by rewrite invr_out ?Ux.\nby apply/eqP=> x'0; rewrite -unitr_inv x'0 unitr0 in Ux.\nQed.\n\nLemma invr_eq0 : forall x, (x^-1 == 0) = (x == 0).\nProof.\nby move=> x; apply: negb_inj; apply/idP/idP; move/invr_neq0; rewrite ?invrK.\nQed.\n\nEnd UnitRingTheory.\n\n(* Reification of the theory of rings with units, in named style  *)\nSection TermDef.\n\nVariable R : Type.\n\nInductive term : Type :=\n| Var of nat\n| Const of R\n| NatConst of nat\n| Add of term & term\n| Opp of term\n| NatMul of term & nat\n| Mul of term & term\n| Inv of term\n| Exp of term & nat.\n\nInductive formula : Type :=\n| Equal of term & term\n| Unit of term\n| And of formula & formula\n| Or of formula & formula\n| Implies of formula & formula\n| Not of formula\n| Exists of nat & formula\n| Forall of nat & formula.\n\nFixpoint tsubst (t : term) (s : nat * term) {struct t} :=\n  match t with\n  | Var i => if i == s.1 then s.2 else t\n  | Const _ | NatConst _ => t\n  | Add t1 t2 => Add (tsubst t1 s) (tsubst t2 s)\n  | Opp t1 => Opp (tsubst t1 s)\n  | NatMul t1 n => NatMul (tsubst t1 s) n\n  | Mul t1 t2 => Mul (tsubst t1 s) (tsubst t2 s)\n  | Inv t1 => Inv (tsubst t1 s)\n  | Exp t1 n => Exp (tsubst t1 s) n\n  end.\n\nFixpoint fsubst (f : formula) (s : nat * term) {struct f} :=\n  match f with\n  | Equal t1 t2 => Equal (tsubst t1 s) (tsubst t2 s)\n  | Unit t1 => Unit (tsubst t1 s)\n  | And f1 f2 => And (fsubst f1 s) (fsubst f2 s)\n  | Or f1 f2 => Or (fsubst f1 s) (fsubst f2 s)\n  | Implies f1 f2 => Implies (fsubst f1 s) (fsubst f2 s)\n  | Not f1 => Not (fsubst f1 s)\n  | Exists i f1 => Exists i (if i == s.1 then f1 else fsubst f1 s)\n  | Forall i f1 => Forall i (if i == s.1 then f1 else fsubst f1 s)\n  end.\n\nEnd TermDef.\n\nBind Scope term_scope with term.\nBind Scope term_scope with formula.\nArguments Scope Add [_ term_scope term_scope].\nArguments Scope Opp [_ term_scope].\nArguments Scope NatMul [_ term_scope nat_scope].\nArguments Scope Mul [_ term_scope term_scope].\nArguments Scope Mul [_ term_scope term_scope].\nArguments Scope Inv [_ term_scope].\nArguments Scope Exp [_ term_scope nat_scope].\nArguments Scope Equal [_ term_scope term_scope].\nArguments Scope Unit [_ term_scope].\nArguments Scope And [_ term_scope term_scope].\nArguments Scope Or [_ term_scope term_scope].\nArguments Scope Implies [_ term_scope term_scope].\nArguments Scope Not [_ term_scope].\nArguments Scope Exists [_ nat_scope term_scope].\nArguments Scope Forall [_ nat_scope term_scope].\nArguments Scope tsubst [_ term_scope _].\nArguments Scope fsubst [_ term_scope _].\n\nNotation Local \"s `_ i\" := (nth 0 s i).\n\nNotation \"''X_' i\" := (Var _ i)\n  (at level 8, i at level 2, format \"''X_' i\") : term_scope.\nNotation \"n %:R\" := (NatConst _ n) : term_scope.\nInfix \"+\" := Add : term_scope.\nNotation \"- t\" := (Opp t) : term_scope.\nNotation \"t - u\" := (Add t (- u)) : term_scope.\nInfix \"*\" := Mul : term_scope.\nInfix \"*+\" := NatMul : term_scope.\nNotation \"t ^-1\" := (Inv t) : term_scope.\nNotation \"t / u\" := (Mul t u^-1) : term_scope.\nInfix \"^+\" := Exp : term_scope.\nInfix \"==\" := Equal : term_scope.\nInfix \"/\\\" := And : term_scope.\nInfix \"\\/\" := Or : term_scope.\nInfix \"==>\" := Implies : term_scope.\nNotation \"~ f\" := (Not f) : term_scope.\nNotation \"'exists' ''X_' i , f\" := (Exists i f)\n  (at level 200, i at level 2, right associativity,\n   format \"'[hv' 'exists'  ''X_' i , '/ '  f ']'\") : term_scope.\nNotation \"'forall' ''X_' i , f\" := (Forall i f)\n  (at level 200, i at level 2,\n   format \"'[hv' 'forall'  ''X_' i , '/ '  f ']'\") : term_scope.\n\n\nSection EvalTerm.\n\nVariable R : UnitRing.type.\n\n(* Evaluation of a reified term into R a ring with units *)\nFixpoint eval (t : term R) (e : seq R) {struct t} : R :=\n  match t with\n  | Var i => e`_i\n  | Const x => x\n  | NatConst n => n%:R\n  | Add t1 t2 => eval t1 e + eval t2 e\n  | Opp t1 => - eval t1 e\n  | NatMul t1 n => eval t1 e *+ n\n  | Mul t1 t2 => eval t1 e * eval t2 e\n  | Inv t1 => (eval t1 e)^-1\n  | Exp t1 n => eval t1 e ^+ n\n  end.\n\nLemma eq_eval : forall t e e', nth 0 e =1 nth 0 e' -> eval t e = eval t e'.\nProof. by move=> t e e' eq_e; elim: t => //= t1 -> // t2 ->. Qed.\n\nLemma eval_tsubst : forall t e s,\n  eval (tsubst t s) e = eval t (set_nth 0 e s.1 (eval s.2 e)).\nProof.\nmove=> t e [i u]; elim: t => //=; do 2?[move=> ? -> //] => j.\nby rewrite nth_set_nth /=; case: eq_op.\nQed.\n\n(* Evaluation of a reified formula *)\nFixpoint holds (f : formula R) (e : seq R) {struct f} : Prop :=\n  match f with\n  | Equal t1 t2 => eval t1 e = eval t2 e\n  | Unit t1 => unit (eval t1 e)\n  | And f1 f2 => holds f1 e /\\ holds f2 e\n  | Or f1 f2 => holds f1 e \\/ holds f2 e\n  | Implies f1 f2 => holds f1 e -> holds f2 e\n  | Not f1 => ~ holds f1 e\n  | Exists i f1 => exists x, holds f1 (set_nth 0 e i x)\n  | Forall i f1 => forall x, holds f1 (set_nth 0 e i x)\n  end.\n\n(* Extensionality of formula evaluation *)\nLemma eq_holds : forall f e e',\n  nth 0 e =1 nth 0 e' -> (holds f e <-> holds f e').\nProof.\npose es1 e e' := @nth R 0 e =1 nth 0 e'.\nhave eq_i: forall i v, let sv e := set_nth 0 e i v in\n           forall e e', es1 e e' -> es1 (sv e) (sv e').\n  by move=> i v /= e e' eq_e j; rewrite !nth_set_nth /= eq_e.\nelim=> /=.\n- by move=> t1 t2 e e' eq_e; rewrite !(eq_eval _ eq_e).\n- by move=> t e e' eq_e; rewrite (eq_eval _ eq_e).\n- move=> ? IH ? IH' ? ? E; move: (IH _ _ E) (IH' _ _ E); tauto.\n- move=> ? IH ? IH' ? ? E; move: (IH _ _ E) (IH' _ _ E); tauto.\n- move=> ? IH ? IH' ? ? E; move: (IH _ _ E) (IH' _ _ E); tauto.\n- move=> ? IH ? ? E; move: (IH _ _ E); tauto.\n- move=> i f IHf e e' E; have{IHf} IHf := IHf _ _ (eq_i i _ _ _ E).\n  split=> [] [x]; exists x; move: (IHf x); tauto.\n- move=> i f IHf e e' E; have{IHf} IHf := IHf _ _ (eq_i i _ _ _ E).\n  split=> [] f_e x; move: (f_e x) (IHf x); tauto.\nQed.\n\n(* Evaluation and substitution by a constant *)\nLemma holds_fsubst : forall f e i v,\n  holds (fsubst f (i, Const v)) e <-> holds f (set_nth 0 e i v).\nProof.\nmove=> f e i v; elim: f e => /=; do [\n  by move=> *; rewrite !eval_tsubst\n| move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto\n| move=> f IHf e; move: (IHf e); tauto\n| move=> j f IHf e].\n- case eq_ji: (j == i); first rewrite (eqP eq_ji).\n    by split=> [] [x f_x]; exists x; rewrite set_set_nth eqxx in f_x *.\n  split=> [] [x f_x]; exists x; move: f_x; rewrite set_set_nth eq_sym eq_ji;\n     have:= IHf (set_nth 0 e j x); tauto.\ncase eq_ji: (j == i); first rewrite (eqP eq_ji).\n  by split=> [] f_ x; move: (f_ x); rewrite set_set_nth eqxx.\nsplit=> [] f_ x; move: (f_ x); rewrite set_set_nth eq_sym eq_ji;\n     have:= IHf (set_nth 0 e j x); tauto.\nQed.\n\n(* Boolean test selecting terms in the language of rings *)\nFixpoint rterm (t : term R) :=\n  match t with\n  | Inv _ => false\n  | Add t1 t2 | Mul t1 t2 => rterm t1 && rterm t2\n  | Opp t1 | NatMul t1 _ | Exp t1 _ => rterm t1\n  | _ => true\n  end.\n\n(* Boolean test selecting formulas in the theory of rings *)\nFixpoint rformula (f : formula R) :=\n  match f with\n  | Equal t1 t2 => rterm t1 && rterm t2\n  | Unit t1 => false\n  | And f1 f2 | Or f1 f2 | Implies f1 f2 => rformula f1 && rformula f2\n  | Not f1 | Exists _ f1 | Forall _ f1 => rformula f1\n  end.\n\n(* Upper bound of the names used in a term *)\nFixpoint ub_var (t : term R) :=\n  match t with\n  | Var i => i.+1\n  | Add t1 t2 | Mul t1 t2 => maxn (ub_var t1) (ub_var t2)\n  | Opp t1 | NatMul t1 _ | Exp t1 _ | Inv t1 => ub_var t1\n  | _ => 0%N\n  end.\n\n(* Replaces inverses in the term t  by fresh variables *)\nFixpoint to_rterm (t : term R) (r : seq (term R)) (n : nat) {struct t} :=\n  match t with\n  | Inv t1 =>\n    let: (t1', r1) := to_rterm t1 r n in\n      (Var _ (n + size r1), rcons r1 t1')\n  | Add t1 t2 =>\n    let: (t1', r1) := to_rterm t1 r n in\n    let: (t2', r2) := to_rterm t2 r1 n in\n      (Add t1' t2', r2)\n  | Opp t1 =>\n   let: (t1', r1) := to_rterm t1 r n in\n     (Opp t1', r1)\n  | NatMul t1 m =>\n   let: (t1', r1) := to_rterm t1 r n in\n     (NatMul t1' m, r1)\n  | Mul t1 t2 =>\n    let: (t1', r1) := to_rterm t1 r n in\n    let: (t2', r2) := to_rterm t2 r1 n in\n      (Mul t1' t2', r2)\n  | Exp t1 m =>\n       let: (t1', r1) := to_rterm t1 r n in\n     (Exp t1' m, r1)\n  | _ => (t, r)\n  end.\n\n(* A ring formula stating that t1 is equal to 0 in the ring *)\n(*theory. Also applies to non commutative rings *)\nDefinition eq0_rformula t1 :=\n  let m := ub_var t1 in\n  let: (t1', r1) := to_rterm t1 [::] m in\n  let fix loop (r : seq (term R)) (i : nat) {struct r}:=\n    (match r with\n      | [::] => Equal t1' (NatConst _ 0)\n      | t :: r' =>\n        let f := 'X_i * t == 1%:R /\\ t * 'X_i == 1%:R in\n          forall 'X_i, (f \\/ 'X_i == t /\\ ~ (exists 'X_i,  f)) ==> loop r' i.+1\n    end)%T\n    in loop r1 m.\n\n(* Transformation of a formula in the theory of rings with units into an *)\n(*  equivalent formula in the sub-theory of rings : *)\nFixpoint to_rformula f :=\n  match f with\n  | t1 == t2 =>\n      eq0_rformula (t1 - t2)\n  | Unit t1 => eq0_rformula (t1 * t1^-1 - 1%:R)\n  | f1 /\\ f2 => to_rformula f1 /\\ to_rformula f2\n  | f1 \\/ f2 =>  to_rformula f1 \\/ to_rformula f2\n  | f1 ==> f2 => to_rformula f1 ==> to_rformula f2\n  | ~ f1 => ~ to_rformula f1\n  | Exists i f1 => exists 'X_i, to_rformula f1\n  | Forall i f1 => forall 'X_i, to_rformula f1\n  end%T.\n\n(* The transformation gives a ring formula.*)\nLemma rformula_to_rformula : forall f, rformula (to_rformula f).\nProof.\nsuff eq0_ring : rformula (eq0_rformula _) by elim=> //= => f1 ->.\nmove=> t1; rewrite /eq0_rformula; move: (ub_var t1) => m.\nset tr := _ m.\nsuff : all rterm (tr.1 :: tr.2).\n  case: tr => {t1} t1 r /=; case/andP=> t1_r.\n  elim: r m => [| t r IHr] m; rewrite /= ?andbT //.\n  case/andP=> ->; exact: IHr.\nhave : all rterm [::] by [].\nrewrite {}/tr; elim: t1 [::] => //=.\n- move=> t1 IHt1 t2 IHt2 r.\n  move/IHt1; case: to_rterm=> {t1 r IHt1} t1 r /=; case/andP=> t1_r.\n  move/IHt2; case: to_rterm=> {t2 r IHt2} t2 r /=; case/andP=> t2_r.\n  by rewrite t1_r t2_r.\n- by move=> t1 IHt1 r; move/IHt1; case: to_rterm.\n- by move=> t1 IHt1 n r; move/IHt1; case: to_rterm.\n- move=> t1 IHt1 t2 IHt2 r.\n  move/IHt1; case: to_rterm=> {t1 r IHt1} t1 r /=; case/andP=> t1_r.\n  move/IHt2; case: to_rterm=> {t2 r IHt2} t2 r /=; case/andP=> t2_r.\n  by rewrite t1_r t2_r.\n- move=> t1 IHt1 r.\n  by move/IHt1; case: to_rterm=> {t1 r IHt1} t1 r /=; rewrite all_rcons.\n- by move=> t1 IHt1 n r; move/IHt1; case: to_rterm.\nQed.\n\n(* Correctness of the transformation. *)\nLemma to_rformula_equiv : forall f e,\n  holds (to_rformula f) e <-> holds f e.\nProof.\nsuff equal0_equiv : forall t1 t2 e,\n  holds (eq0_rformula (t1 - t2)) e <-> (eval t1 e == eval t2 e).\n- elim => /= ; try tauto.\n  + move => t1 t2 e.\n    by split; [move/equal0_equiv; move/eqP | move/eqP; move/equal0_equiv].\n  + move=> t1 e; rewrite unitrE; exact: equal0_equiv.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 e; move: (IHf1 e); tauto.\n  + by move=> n f1 IHf1 e; split=> [] [x]; move/IHf1; exists x.\n  + by move=> n f1 IHf1 e; split=> Hx x; apply/IHf1.\nmove=> t1 t2 e; rewrite -(add0r (eval t2 e)) -(can2_eq (subrK _) (addrK _)).\nrewrite -/(eval (t1 - t2) e); move: (t1 - t2)%T => {t1 t2} t.\nhave sub_var_tsubst : forall s t, s.1 >= ub_var t -> tsubst t s = t.\n  move=> s; elim=> //=.\n  - by move=> n; case: ltngtP.\n  - move=> t1 IHt1 t2 IHt2; rewrite leq_maxl.\n    by case/andP; move/IHt1->; move/IHt2->.\n  - by move=> t1 IHt1; move/IHt1->.\n  - by move=> t1 IHt1 n; move/IHt1->.\n  - move=> t1 IHt1 t2 IHt2; rewrite leq_maxl.\n    by case/andP; move/IHt1->; move/IHt2->.\n  - by move=> t1 IHt1; move/IHt1->.\n  - by move=> t1 IHt1 n; move/IHt1->.\npose rsub  t' := fix rsub m (r : seq (term R))  :=\n  if r is u :: r' then tsubst (rsub m.+1 r') (m, u^-1)%T else t'.\npose ub_sub := fix ub_sub m (r : seq (term R))  :=\n  if r is u :: r' then ub_var u <= m /\\ ub_sub m.+1 r' else True.\nsuff rsub_to_r : forall t0 r0 m, m >= ub_var t0 -> ub_sub m r0 ->\n  let: (t', r) := to_rterm t0 r0 m in\n  [/\\ take (size r0) r = r0,\n    ub_var t' <= m + size r, ub_sub m r & rsub t' m r = t0].\n- have:= rsub_to_r t [::] _ (leqnn _).\n  rewrite /eq0_rformula.\n  case: (to_rterm _ _ _) => [t1' r1] [//|_ _ ub_r1 def_t].\n  rewrite -{2}def_t {def_t}.\n  elim: r1 (ub_var t) e ub_r1 => [|u r1 IHr1] m e /= => [_|[ub_u ub_r1]].\n    by split; move/eqP.\n  rewrite eval_tsubst /=; set y := eval u e; split=> t_eq0.\n    apply/IHr1=> //; apply: t_eq0.\n    rewrite nth_set_nth /= eqxx -(eval_tsubst u e (m, Const _)).\n    rewrite sub_var_tsubst //= -/y.\n    case Uy: (unit y); [left | right]; first by rewrite mulVr ?divrr.\n    split; first by rewrite invr_out ?Uy.\n    case=> z; rewrite nth_set_nth /= eqxx.\n    rewrite -!(eval_tsubst _ _ (m, Const _)) !sub_var_tsubst // -/y => yz1.\n    by case/unitrP: Uy; exists z.\n  move=> x def_x; apply/IHr1=> //; suff ->: x = y^-1 by []; move: def_x.\n  rewrite nth_set_nth /= eqxx -(eval_tsubst u e (m, Const _)).\n  rewrite sub_var_tsubst //= -/y; case=> [[xy1 yx1] | [xy nUy]].\n    by rewrite -[y^-1]mul1r -[1]xy1 mulrK //; apply/unitrP; exists x.\n  rewrite invr_out //; apply/unitrP=> [[z yz1]]; case: nUy; exists z.\n  by rewrite nth_set_nth /= eqxx -!(eval_tsubst _ _ (m, Const _))\n     !sub_var_tsubst.\nhave rsub_id : forall r t n, (ub_var t)<= n -> rsub t n r = t.\n  elim=> //= t0 r IHr t1 n hn; rewrite IHr ?sub_var_tsubst  ?(ltnW hn) //.\n  by  rewrite (leq_trans hn).\nhave rsub_acc : forall r s t1 m,\n  ub_var t1 <= m + size r -> rsub t1 m (r ++ s) = rsub t1 m r.\n  elim=> [|t1 r IHr] s t2 m /=; first by rewrite addn0; apply: rsub_id.\n  by move=> hleq; rewrite IHr // addSnnS.\nelim=> /=; try do [\n  by move=> n r m hlt hub; rewrite take_size (ltn_addr _ hlt) rsub_id\n| by move=> n r m hlt hub; rewrite leq0n take_size rsub_id\n| move=> t1 IHt1 t2 IHt2 r m; rewrite leq_maxl; case/andP=> hub1 hub2 hmr;\n  case: to_rterm {IHt1 hub1 hmr}(IHt1 r m hub1 hmr) => t1' r1;\n  case=> htake1 hub1' hsub1 <-;\n  case: to_rterm {IHt2 hub2 hsub1}(IHt2 r1 m hub2 hsub1) => t2' r2 /=;\n  rewrite leq_maxl; case=> htake2 -> hsub2 /= <-;\n  rewrite -{1 2}(cat_take_drop (size r1) r2) htake2; set r3 := drop _ _;\n  rewrite size_cat addnA (leq_trans _ (leq_addr _ _)) //;\n  split=> {hsub2}//;\n   first by [rewrite takel_cat // -htake1 size_take leq_minl leqnn orbT];\n  rewrite -(rsub_acc r1 r3 t1') {hub1'}// -{htake1}htake2 {r3}cat_take_drop;\n  by elim: r2 m => //= u r2 IHr2 m; rewrite IHr2\n| do [ move=> t1 IHt1 r m; do 2!move/IHt1=> {IHt1}IHt1\n     | move=> t1 IHt1 n r m; do 2!move/IHt1=> {IHt1}IHt1];\n  case: to_rterm IHt1 => t1' r1 [-> -> hsub1 <-]; split=> {hsub1}//;\n  by elim: r1 m => //= u r1 IHr1 m; rewrite IHr1].\nmove=> t1 IHt1 r m; do 2!move/IHt1=> {IHt1}IHt1.\ncase: to_rterm IHt1 => t1' r1 /= [def_r ub_t1' ub_r1 <-].\nrewrite size_rcons addnS leqnn -{1}cats1 takel_cat ?def_r; last first.\n  by rewrite -def_r size_take leq_minl leqnn orbT.\nelim: r1 m ub_r1 ub_t1' {def_r} => /= [|u r1 IHr1] m => [_|[->]].\n  by rewrite addn0 eqxx.\nby rewrite -addSnnS; move/IHr1=> IH; case/IH=> _ _ ub_r1 ->.\nQed.\n\n(* Boolean test selecting formulas which describe a constructable set, *)\n(* i.e. formulas without quantifiers. Here we also require that zero be the *)\n(* rhs in equalities. *)\n\n(* The job of qfree is to check that all the terms in the dnf are rterms..*)\n(* May be should we separate this check from bare quantifier elimination *)\nFixpoint qfree (f : formula R) :=\n  match f with\n  | Equal t1 (NatConst 0) => rterm t1\n  | And f1 f2 | Or f1 f2 => qfree f1 && qfree f2\n  | Not f1 => qfree f1\n  | _ => false\n  end.\n\n(* Boolean holds predicate for quantifier free formulas *)\nDefinition qfree_eval e := fix loop (f : formula R) : bool :=\n  match f with\n    | Equal t1 (NatConst 0) => (eval t1 e == 0)\n    | And f1 f2 => loop f1 && loop f2\n    | Or f1 f2 => loop f1 || loop f2\n    | Not f1 => ~~ loop f1\n    |_ => false\n  end.\n\n(* qfree_eval is equivalent to holds *)\nLemma qfree_eval_holds : forall f e,\n  qfree f -> reflect (holds f e) (qfree_eval e f).\nProof.\nelim=> //.\n- move=> t1 t2 e cet12; case: t2 cet12=> //= [[|n]] // _; exact: eqP.\n- move=> f1 IHf1 f2 IHf2 e /=; case/andP => cf1 cf2.\n  by apply: (iffP andP); case; move/(IHf1 _ cf1)=> r1; move/(IHf2 _ cf2); split.\n- move=> f1 IHf1 f2 IHf2 e /=; case/andP => cf1 cf2.\n  by apply: (iffP orP);\n    (case; [move/(IHf1 _ cf1)=> H1; left | move/(IHf2 _ cf2); right]).\n- by move=> f IHf e /= cf; apply: (iffP negP)=> H; move/(IHf _ cf).\nQed.\n\n(* The T truth formula *)\nDefinition tt_form : formula R := (0%:R == 0%:R)%T.\n\nImplicit Type bc : seq (term R) * seq (term R).\n\n(* Quantifier-free formula are normalized into DNF. A DNF is *)\n(* represented by the type seq (seq (term R) * seq (term R)), where we *)\n(* separate positive and negative literals *)\n\n(* DNF preserving conjunction *)\nDefinition and_dnf bcs1 bcs2 :=\n  \\big[cat/nil]_(bc1 <- bcs1)\n     map (fun bc2 => (bc1.1 ++ bc2.1, bc1.2 ++ bc2.2)) bcs2.\n\n(* Computes a DNF from a qfree formula *)\nFixpoint qfree_to_dnf (f : formula R) (neg : bool) {struct f} :=\n  match f with\n    | Equal t1 _ => [:: if neg then ([::], [:: t1]) else ([:: t1], [::])]\n    | And f1 f2 => (if neg then cat else and_dnf) [rec f1, neg] [rec f2, neg]\n    | Or f1 f2 => (if neg then and_dnf else cat) [rec f1, neg] [rec f2, neg]\n    | Not f1 => [rec f1, (~~ neg)]\n    |_ =>  [:: ([::], [::])]\n  end where \"[ 'rec' f , neg ]\" := (qfree_to_dnf f neg).\n\n\n(* Conversely, transforms a DNF into a formula *)\nDefinition dnf_to_formula :=\n  foldr (fun bc =>\n         Or (foldr (fun t => And (t == 0%:R)) tt_form bc.1\n             /\\ foldr (fun t => And (~ (t == 0%:R))) tt_form bc.2))\n        (Not tt_form).\n\n\n(* Catenation of dnf is the Or of formulas *)\nLemma dnf_to_formula_cat : forall bcs1 bcs2 e,\n  qfree_eval e (dnf_to_formula (bcs1 ++ bcs2))\n = qfree_eval e ((dnf_to_formula bcs1) \\/ (dnf_to_formula bcs2)).\nProof.\nelim=> [|bc1 bcs1 IH1] bcs2 e /=; first by rewrite eqxx.\nby rewrite -orbA; congr orb; rewrite IH1.\nQed.\n\n(* and_dnf is the And of formulas *)\nLemma and_dnf_correct : forall bcs1 bcs2 e,\n  qfree_eval e (dnf_to_formula (and_dnf bcs1 bcs2))\n  = qfree_eval e ((dnf_to_formula bcs1) /\\ (dnf_to_formula bcs2)).\nProof.\nelim=>[|bc1 bcs1 IH1] bcs2 /= e; first by rewrite /and_dnf big_nil /= eqxx.\nrewrite /and_dnf big_cons -/(and_dnf bcs1 bcs2) dnf_to_formula_cat  /=.\nrewrite {}IH1 /= andb_orl; congr orb.\nelim: bcs2 bc1 {bcs1} => [| bc2 bcs2 IH] bc1 /=; first by rewrite eqxx andbF.\nrewrite {}IH /= andb_orr; congr orb; rewrite {bcs2}.\nsuff aux : forall (l1 l2 : seq (term R)) g,\n  qfree_eval e (foldr (fun t => And (g t)) tt_form (l1 ++ l2)) =\n  qfree_eval e (And (foldr (fun t => And (g t)) tt_form l1)\n                    (foldr (fun t => And (g t)) tt_form l2)).\n  by rewrite 2!aux /= 2!andbA -andbA -andbCA andbA andbCA andbA.\nby elim=> [| ? ? IHl1] * /=; [rewrite eqxx | rewrite -andbA IHl1 /=].\nQed.\n\n\nLemma qfree_to_dnf_correct : forall f, (qfree f) ->\n  (forall e, qfree_eval e f =\n    qfree_eval e (dnf_to_formula (qfree_to_dnf f false))).\nProof.\nelim => //=.\n- by move=> t1 t2; case: t2 => //= [[|n]] // _ e; rewrite eqxx /= orbF !andbT.\n- move=> f1 IHf1 f2 IHf2; case/andP=> cf1 cf2 e; rewrite IHf1 // IHf2 //=.\n  by rewrite and_dnf_correct.\n- move=> f1 IHf1 f2 IHf2; case/andP=> cf1 cf2 e; rewrite IHf1 // IHf2 //=.\n  by rewrite dnf_to_formula_cat.\n- move=> f IHf cf e; rewrite {}IHf //; elim: f cf => //.\n  + by move=> t1 [] ? //=; rewrite eqxx /= 2!orbF !andbT.\n  + move=> f1 IHf1 f2 IHf2 /=; case/andP=> cf1 cf2.\n    by rewrite and_dnf_correct /= dnf_to_formula_cat /= -IHf1 // negb_and IHf2.\n  + move=> f1 IHf1 f2 IHf2 /=; case/andP=> cf1 cf2.\n    by rewrite and_dnf_correct /= dnf_to_formula_cat /= -IHf1 // negb_or -IHf2.\n  + by move=> f IHf /= cf; rewrite -IHf // negbK.\nQed.\n\nLemma qfree_dnf_to_formula : forall f,\n  qfree f -> qfree (dnf_to_formula (qfree_to_dnf f false)).\nProof.\nhave aux1 : forall bcs1 bcs2,\n  qfree (dnf_to_formula (bcs1 ++ bcs2))\n  = qfree (dnf_to_formula bcs1) && (qfree (dnf_to_formula bcs2)).\n  by elim=> [|bc1 bcs1 IH1] bcs2 //=; rewrite IH1 andbA.\nhave aux2 : forall bcs1 bcs2,\n  qfree (dnf_to_formula bcs1) ->\n  qfree (dnf_to_formula bcs2) ->\n  qfree (dnf_to_formula (and_dnf bcs1 bcs2)).\n- elim=>[|bc1 bcs1 IH1] bcs2 /=; first by rewrite /and_dnf big_nil.\n  rewrite /and_dnf big_cons -/(and_dnf bcs1 bcs2) aux1.\n  do 2![case/andP] => cf1 cf2 cbf1 cbf2; rewrite {}IH1 //= andbT.\n  elim: bcs2 cbf2 {cbf1} => [| bsc2 bcf2 IH] //=.\n  do 2![case/andP] => h1 h2; move/IH->.\n  elim: bc1.1 cf1 => /= [_|t bc ?]; last by case/andP=> -> /=.\n  elim: bc1.2 cf2 => /= [_|t bc ?]; last by case/andP=> -> /=.\n  by rewrite h1 h2.\nmove=> f; elim: f false => //; last by move=> f IHf b; exact: IHf.\n- by move=> t1 [] // [] [] //= ->.\n- move=> f1 IHf1 f2 IHf2 [] /=; case/andP; auto; rewrite aux1; move/IHf1->.\n  exact: IHf2.\nmove=> f1 IHf1 f2 IHf2 [] /=; case/andP; auto; rewrite aux1; move/IHf1->.\nexact: IHf2.\nQed.\n\n\nLemma to_rterm_rterm : forall t r n, rterm t -> to_rterm t r n = (t, r).\nProof.\nelim=> //.\n- by move=> t1 IHt1 t2 IHt2 r n /=; case/andP=> rt1 rt2; rewrite {}IHt1 // IHt2.\n- by move=> t IHt r n /= rt; rewrite {}IHt.\n- by move=> t IHt r n m /= rt; rewrite {}IHt.\n- by move=> t1 IHt1 t2 IHt2 r n /=; case/andP=> rt1 rt2; rewrite {}IHt1 // IHt2.\n- by move=> t IHt r n m /= rt; rewrite {}IHt.\nQed.\n\n\nEnd EvalTerm.\n\nModule ComUnitRing.\n\nRecord class_of (R : Type) : Type := Class {\n  base1 :> ComRing.class_of R;\n  ext :> UnitRing.mixin_of (Ring.Pack base1 R)\n}.\n\nCoercion base2 R m := UnitRing.Class (@ext R m).\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nSection Mixin.\n\nVariables (R : ComRing.type) (unit : pred R) (inv : R -> R).\nHypothesis mulVx : {in unit, left_inverse 1 inv *%R}.\nHypothesis unitPl : forall x y, y * x = 1 -> unit x.\n\nLemma mulC_mulrV : {in unit, right_inverse 1 inv *%R}.\nProof. by move=> x Ux /=; rewrite mulrC mulVx. Qed.\n\nLemma mulC_unitP : forall x y, y * x = 1 /\\ x * y = 1 -> unit x.\nProof. move=> x y [yx _]; exact: unitPl yx. Qed.\n\nDefinition Mixin := UnitRing.EtaMixin mulVx mulC_mulrV mulC_unitP.\n\nEnd Mixin.\n\nDefinition pack := let k T c m := Pack (@Class T c m) T in ComRing.unpack k.\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nDefinition zmodType cT := Zmodule.Pack (class cT) cT.\nDefinition ringType cT := Ring.Pack (class cT) cT.\nCoercion comRingType cT := ComRing.Pack (class cT) cT.\nCoercion unitRingType cT := UnitRing.Pack (class cT) cT.\nDefinition com_unitRingType cT :=\n  @UnitRing.Pack (comRingType cT) (class cT) cT.\n\nEnd ComUnitRing.\n\nCanonical Structure ComUnitRing.eqType.\nCanonical Structure ComUnitRing.choiceType.\nCanonical Structure ComUnitRing.zmodType.\nCanonical Structure ComUnitRing.ringType.\nCanonical Structure ComUnitRing.unitRingType.\nCanonical Structure ComUnitRing.comRingType.\nBind Scope ring_scope with ComUnitRing.sort.\n\nSection ComUnitRingTheory.\n\nVariable R : ComUnitRing.type.\nImplicit Types x y : R.\n\nLemma unitr_mul : forall x y, unit (x * y) = unit x && unit y.\nProof. move=> x y; apply: commr_unit_mul; exact: mulrC. Qed.\n\nEnd ComUnitRingTheory.\n\nModule IntegralDomain.\n\nDefinition axiom (R : Ring.type) :=\n  forall x y : R, x * y = 0 -> (x == 0) || (y == 0).\n\nRecord class_of (R : Type) : Type :=\n  Class {base :> ComUnitRing.class_of R; ext : axiom (Ring.Pack base R)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack : forall R : ComUnitRing.type, axiom R -> type :=\n  let k T c ax := Pack (@Class T c ax) T in ComUnitRing.unpack k.\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nDefinition zmodType cT := Zmodule.Pack (class cT) cT.\nDefinition ringType cT := Ring.Pack (class cT) cT.\nDefinition comRingType cT := ComRing.Pack (class cT) cT.\nDefinition unitRingType cT := UnitRing.Pack (class cT) cT.\nCoercion comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\n\nEnd IntegralDomain.\n\nCanonical Structure IntegralDomain.eqType.\nCanonical Structure IntegralDomain.choiceType.\nCanonical Structure IntegralDomain.zmodType.\nCanonical Structure IntegralDomain.ringType.\nCanonical Structure IntegralDomain.unitRingType.\nCanonical Structure IntegralDomain.comRingType.\nCanonical Structure IntegralDomain.comUnitRingType.\nBind Scope ring_scope with IntegralDomain.sort.\n\nSection IntegralDomainTheory.\n\nVariable R : IntegralDomain.type.\nImplicit Types x y : R.\n\nLemma mulf_eq0 : forall x y, (x * y == 0) = (x == 0) || (y == 0).\nProof.\nmove=> x y; apply/eqP/idP; first by case: R x y => T [].\nby case/pred2P=> ->; rewrite (mulr0, mul0r).\nQed.\n\nLemma mulf_neq0 : forall x y, x != 0 -> y != 0 -> x * y != 0.\nProof. move=> x y x0 y0; rewrite mulf_eq0; exact/norP. Qed.\n\nLemma expf_eq0 : forall x n, (x ^+ n == 0) = (n > 0) && (x == 0).\nProof.\nmove=> x; elim=> [|n IHn]; first by rewrite oner_eq0.\nby rewrite exprS mulf_eq0 IHn andKb.\nQed.\n\nLemma expf_neq0 : forall x m, x != 0 -> x ^+ m != 0.\nProof. by move=> x n x_nz; rewrite expf_eq0; apply/nandP; right. Qed.\n\nLemma mulfI : forall x, x != 0 -> injective ( *%R x).\nProof.\nmove=> x nz_x y z; rewrite -[x * z]add0r; move/(canLR (addrK _)).\nmove/eqP; rewrite -mulrN -mulr_addr mulf_eq0 (negbTE nz_x) /=; move/eqP.\nby move/(canRL (subrK _)); rewrite add0r.\nQed.\n\nLemma mulIf : forall x, x != 0 -> injective ( *%R^~ x).\nProof. move=> x nz_x y z; rewrite -!(mulrC x); exact: mulfI. Qed.\n\nEnd IntegralDomainTheory.\n\nModule Field.\n\nDefinition mixin_of (F : UnitRing.type) := forall x : F, x != 0 -> unit x.\n\nRecord class_of (F : Type) : Type := Class {\n  base :> IntegralDomain.class_of F;\n  ext: mixin_of (UnitRing.Pack base F)\n}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack : forall F : IntegralDomain.type, mixin_of F -> type :=\n  let k T c m := Pack (@Class T c m) T in IntegralDomain.unpack k.\n\nLemma IdomainMixin : forall R, mixin_of R -> IntegralDomain.axiom R.\nProof.\nmove=> R m x y xy0; apply/norP=> [[]]; move/m=> Ux; move/m.\nby rewrite -(unitr_mulr _ Ux) xy0 unitr0.\nQed.\n\nSection Mixins.\n\nVariables (R : ComRing.type) (inv : R -> R).\n\nDefinition axiom := forall x, x != 0 -> inv x * x = 1.\nHypothesis mulVx : axiom.\nHypothesis inv0 : inv 0 = 0.\n\nLemma intro_unit : forall x y : R, y * x = 1 -> x != 0.\nProof.\nmove=> x y yx1; apply: contra (nonzero1r R); move/eqP=> x0.\nby rewrite -yx1 x0 mulr0.\nQed.\n\nLemma inv_out : {in predC (predC1 0), inv =1 id}.\nProof. by move=> x; move/negbNE; move/eqP->. Qed.\n\nDefinition UnitMixin := ComUnitRing.Mixin mulVx intro_unit inv_out.\n\nLemma Mixin : mixin_of (UnitRing.Pack (UnitRing.Class UnitMixin) R).\nProof. by []. Qed.\n\nEnd Mixins.\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nDefinition zmodType cT := Zmodule.Pack (class cT) cT.\nDefinition ringType cT := Ring.Pack (class cT) cT.\nDefinition comRingType cT := ComRing.Pack (class cT) cT.\nDefinition unitRingType cT := UnitRing.Pack (class cT) cT.\nDefinition comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\nCoercion idomainType cT := IntegralDomain.Pack (class cT) cT.\n\nEnd Field.\n\nCanonical Structure Field.eqType.\nCanonical Structure Field.choiceType.\nCanonical Structure Field.zmodType.\nCanonical Structure Field.ringType.\nCanonical Structure Field.unitRingType.\nCanonical Structure Field.comRingType.\nCanonical Structure Field.comUnitRingType.\nCanonical Structure Field.idomainType.\nBind Scope ring_scope with Field.sort.\n\nSection FieldTheory.\n\nVariable F : Field.type.\nImplicit Types x y : F.\n\nLemma unitfE : forall x, unit x = (x != 0).\nProof.\nmove=> x; apply/idP/idP=> [Ux |]; last by case: F x => T [].\nby apply/eqP=> x0; rewrite x0 unitr0 in Ux.\nQed.\n\nLemma mulVf: forall x, x != 0 -> x^-1 * x = 1.\nProof. by move=> x; rewrite -unitfE; exact: mulVr. Qed.\nLemma divff: forall x, x != 0 -> x / x = 1.\nProof. by move=> x; rewrite -unitfE; exact: divrr. Qed.\nDefinition mulfV := divff.\nLemma mulKf : forall x, x != 0 -> cancel ( *%R x) ( *%R x^-1).\nProof. by move=> x; rewrite -unitfE; exact: mulKr. Qed.\nLemma mulVKf : forall x, x != 0 -> cancel ( *%R x^-1) ( *%R x).\nProof. by move=> x; rewrite -unitfE; exact: mulVKr. Qed.\nLemma mulfK : forall x, x != 0 -> cancel ( *%R^~ x) ( *%R^~ x^-1).\nProof. by move=> x; rewrite -unitfE; exact: mulrK. Qed.\nLemma mulfVK : forall x, x != 0 -> cancel ( *%R^~ x^-1) ( *%R^~ x).\nProof. by move=> x; rewrite -unitfE; exact: divrK. Qed.\nDefinition divfK := mulfVK.\n\nLemma invf_mul : {morph (fun x => x^-1) : x y / x * y}.\nProof.\nmove=> x y; case: (eqVneq x 0) => [-> |nzx]; first by rewrite !(mul0r, invr0).\ncase: (eqVneq y 0) => [-> |nzy]; first by rewrite !(mulr0, invr0).\nby rewrite mulrC invr_mul ?unitfE.\nQed.\n\nLemma prodf_inv : forall I r (P : pred I) (E : I -> F),\n  \\prod_(i <- r | P i) (E i)^-1 = (\\prod_(i <- r | P i) E i)^-1.\nProof. by move=> I r P E; rewrite (big_morph _ invf_mul (invr1 _)). Qed.\n\nEnd FieldTheory.\n\nModule DecidableField.\n\nDefinition axiom (R : UnitRing.type) (s : formula R -> pred (seq R)) :=\n  forall f e, reflect (holds f e) (s f e).\n\nRecord mixin_of (R : UnitRing.type) : Type :=\n  Mixin { sat : formula R -> pred (seq R); satP : axiom sat}.\n\nRecord class_of (F : Type) : Type :=\n  Class {base :> Field.class_of F; mixin:> mixin_of (UnitRing.Pack base F)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack := let k T c m := Pack (@Class T c m) T in Field.unpack k.\n\n(* Ultimately, there should be a QE Mixin constructor *)\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nDefinition zmodType cT := Zmodule.Pack (class cT) cT.\nDefinition ringType cT := Ring.Pack (class cT) cT.\nDefinition comRingType cT := ComRing.Pack (class cT) cT.\nDefinition unitRingType cT := UnitRing.Pack (class cT) cT.\nDefinition comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\nDefinition idomainType cT := IntegralDomain.Pack (class cT) cT.\nCoercion fieldType cT := Field.Pack (class cT) cT.\n\nEnd DecidableField.\n\nCanonical Structure DecidableField.eqType.\nCanonical Structure DecidableField.choiceType.\nCanonical Structure DecidableField.zmodType.\nCanonical Structure DecidableField.ringType.\nCanonical Structure DecidableField.unitRingType.\nCanonical Structure DecidableField.comRingType.\nCanonical Structure DecidableField.comUnitRingType.\nCanonical Structure DecidableField.idomainType.\nCanonical Structure DecidableField.fieldType.\nBind Scope ring_scope with DecidableField.sort.\n\nSection DecidableFieldTheory.\n\nVariable F : DecidableField.type.\n\nDefinition sat := DecidableField.sat (DecidableField.class F).\n\nLemma satP : DecidableField.axiom sat.\nProof. exact: DecidableField.satP. Qed.\n\nDefinition nExists R n f : formula R := iteri n (fun i => Exists i) f.\n\nLemma nExistsP : forall f n e,\n  reflect (exists s, (size s == n) && (sat f (s ++ drop n e)))\n          (sat (nExists n f) e).\nProof.\nhave drop_set_nth:\n  forall e n x, @drop F n (set_nth 0 e n x) = x :: drop n.+1 e.\n- move=> /= e n x; apply: (@eq_from_nth _ 0) => [|i _].\n    by rewrite /= !size_drop size_set_nth -add_sub_maxn addSnnS addKn.\n  rewrite nth_drop nth_set_nth /= -{2}[n]addn0 eqn_addl.\n  by case: i => //= i; rewrite nth_drop addSnnS.\nmove=> f n e; elim: n e => [|n IHn] e /=.\n  by rewrite drop0; apply: (iffP idP) => [f_e | [[|] //]]; exists (Nil F).\ncase: satP => [sol | no_sol]; constructor.\n  case: sol => x; move/satP; case/IHn=> /= s; case/andP=> sz_s.\n  rewrite drop_set_nth -cat_rcons => f_s; exists (rcons s x).\n  by rewrite size_rcons eqSS sz_s.\ncase; case/lastP=> // s x; rewrite size_rcons eqSS cat_rcons => f_sx.\ncase: no_sol; exists x; apply/satP; apply/IHn.\nby exists s; rewrite drop_set_nth.\nQed.\n\nDefinition sol f n :=\n  if insub [::] : {? e | sat (nExists n f) e} is Some u then\n    @xchoose _ (fun x => _) (nExistsP _ _ _ (valP u))\n  else nseq n 0.\n\nLemma solP : forall f n,\n  reflect (exists2 s, size s = n & holds f s) (sat f (sol f n)).\nProof.\nrewrite /sol => f n; case: insubP=> [u /= _ val_u | no_sol].\n  set uP := nExistsP _ _ _ _; case/andP: (xchooseP uP).\n  move: {uP}(xchoose _) => s; rewrite {u}val_u cats0.\n  move/eqP=> s_n f_s; rewrite f_s; left; exists s => //; exact/satP.\napply: (iffP idP) => [f0 | [s s_n f_s]]; case/nExistsP: no_sol.\n  by exists (@nseq F n 0); rewrite cats0 size_nseq eqxx.\nexists s; rewrite cats0 s_n eqxx; exact/satP.\nQed.\n\nLemma size_sol : forall f n, size (sol f n) = n.\nProof.\nrewrite /sol => f n; case: insubP=> [u /= _ _ | _]; last exact: size_nseq.\nby set uP := nExistsP _ _ _ _; case/andP: (xchooseP uP); move/eqP.\nQed.\n\nLemma eq_sat : forall f1 f2,\n  (forall e, holds f1 e <-> holds f2 e) -> sat f1 =1 sat f2.\nProof. by move=> f1 f2 eqf12 e; apply/satP/satP; case: (eqf12 e). Qed.\n\nLemma eq_sol : forall f1 f2,\n  (forall e, holds f1 e <-> holds f2 e) -> sol f1 =1 sol f2.\nProof.\nrewrite /sol => f1 f2; move/eq_sat=> eqf12 n.\ncase: insubP=> [u /= _ val_u | no_sol].\n  have u2P: sat (nExists n f2) [::].\n    apply/nExistsP; case/nExistsP: (valP u) => s.\n    by rewrite eqf12 /= val_u; exists s.\n  rewrite (insubT (sat _) u2P); apply: eq_xchoose => s.\n  by rewrite /= val_u eqf12.\nrewrite insubN //; apply: contra no_sol; case/nExistsP=> s f2_s.\nby apply/nExistsP; exists s; rewrite eqf12.\nQed.\n\nEnd DecidableFieldTheory.\n\nImplicit Arguments satP [F f e].\nImplicit Arguments solP [F f n].\n\n(* Structure of field with quantifier elimination *)\nModule QE.\n\n(* p is the elimination of a single existential quantifier *)\nDefinition qfree_proj_axiom (R : UnitRing.type)\n  (p : nat -> (seq (term R) * seq (term R)) -> formula R) :=\n  forall i dnf, qfree (p i dnf).\n\n(* The elimination operator p preserves  validity *)\nDefinition holds_proj_axiom (R : UnitRing.type)\n  (p : nat -> (seq (term R) * seq (term R)) -> formula R) :=\n  forall i bc e,  qfree (dnf_to_formula [:: bc]) ->\n    reflect  (holds (Exists i (dnf_to_formula [:: bc])) e)\n             (qfree_eval e (p i bc)).\n\nRecord mixin_of (R : UnitRing.type) : Type := Mixin {\n  proj : nat -> (seq (term R) * seq (term R)) -> formula R;\n  qfree_proj : qfree_proj_axiom proj;\n  holds_proj : holds_proj_axiom proj\n}.\n\nRecord class_of (F : Type) : Type :=\n  Class {base :> Field.class_of F; mixin:> mixin_of (UnitRing.Pack base F)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack := let k T c m := Pack (@Class T c m) T in Field.unpack k.\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nDefinition zmodType cT := Zmodule.Pack (class cT) cT.\nDefinition ringType cT := Ring.Pack (class cT) cT.\nDefinition comRingType cT := ComRing.Pack (class cT) cT.\nDefinition unitRingType cT := UnitRing.Pack (class cT) cT.\nDefinition comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\nDefinition idomainType cT := IntegralDomain.Pack (class cT) cT.\nCoercion fieldType cT := Field.Pack (class cT) cT.\n\nEnd QE.\n\nCanonical Structure QE.eqType.\nCanonical Structure QE.choiceType.\nCanonical Structure QE.zmodType.\nCanonical Structure QE.ringType.\nCanonical Structure QE.unitRingType.\nCanonical Structure QE.comRingType.\nCanonical Structure QE.comUnitRingType.\nCanonical Structure QE.idomainType.\nCanonical Structure QE.fieldType.\nBind Scope ring_scope with QE.sort.\n\nSection QE_theory.\n\nVariable F : QE.type.\n\nDefinition proj := QE.proj (QE.class F).\n\nLemma qfree_proj : QE.qfree_proj_axiom proj.\nProof. exact: QE.qfree_proj. Qed.\n\nLemma holds_proj : QE.holds_proj_axiom proj.\nProof. exact: QE.holds_proj. Qed.\n\nNotation Local true_f := (tt_form F).\n\nImplicit Type f : (formula F).\n\nDefinition elim_aux f n := foldr (@Or F) (Not true_f)\n      (map (proj n)\n      (qfree_to_dnf f false)).\n\nFixpoint quantifier_elim (f : formula F) : formula F :=\n  match f with\n    | t1 == t2 => t1 - t2 == 0%:R\n    | Unit _ => f\n    | f1 /\\ f2 => (quantifier_elim f1) /\\ (quantifier_elim f2)\n    | f1 \\/ f2 => (quantifier_elim f1) \\/ (quantifier_elim f2)\n    | f1 ==> f2 => (~ quantifier_elim f1) \\/ (quantifier_elim f2)\n    | ~ f => ~ (quantifier_elim f)\n    | Exists n f => elim_aux (quantifier_elim f) n\n    | Forall n f => ~ elim_aux (~ quantifier_elim f) n\n  end%T.\n\nLemma qfree_quantifier_elim : forall f,\n  rformula f -> qfree (quantifier_elim f).\nProof.\nhave aux : forall f n, qfree (elim_aux f n).\n  move=> f n; rewrite /elim_aux; elim: qfree_to_dnf => //= x l ->.\n  by rewrite qfree_proj.\nby elim=> //= f1 IHf1 f2 IHf2 /=; case/andP=> rf1 rf2; rewrite IHf1 // IHf2.\nQed.\n\n\nLemma quantifier_elim_ringf : forall f e, rformula f ->\n  reflect (holds f e) (qfree_eval e (quantifier_elim f)).\nProof.\npose rc e n f := exists x, qfree_eval (set_nth 0 e n x) f.\nhave aux : forall f e n, qfree f ->\n  reflect  (rc e n f) (qfree_eval e (elim_aux f n)).\n  rewrite /elim_aux => f e n cf.\n  apply: (@iffP (rc e n (dnf_to_formula (qfree_to_dnf f false)))); last first.\n  - by case=> x; rewrite qfree_to_dnf_correct //; exists x.\n  - by case=> x; rewrite -qfree_to_dnf_correct //; exists x.\n  have := (qfree_dnf_to_formula cf).\n  elim: {f cf} (qfree_to_dnf f false) => [| bc l IHl] /=.\n    by rewrite eqxx; right; case; rewrite /= eqxx.\n  case/andP=> hc.\n  have {hc} hc : qfree (dnf_to_formula [:: bc]) by rewrite /= hc.\n  move/IHl=> {IHl} IHl /=; case: holds_proj; rewrite // ?orTb ?orFb.\n    move=> hx; left; case: hx => x; move/(qfree_eval_holds _ hc).\n    by rewrite /= eqxx orbF; exists x; apply/orP; left.\n  move=> hbf; apply: (iffP IHl).\n    by case=> x hx; exists x; apply/orP; right.\n  case=> x /=; case/orP=> hx; last by exists x.\n  by case: hbf; exists x; apply/(qfree_eval_holds _ hc); rewrite /= hx.\nelim=> //.\n- move=> ? ? //= e _; rewrite (can2_eq (subrK _) (addrK _)) add0r; exact: eqP.\n- move=> ? IHf1 ? IHf2 e /=; case/andP; case/(IHf1 e) => ?; last by right; case.\n  by case/(IHf2 e); constructor; tauto.\n- move=> ? IHf1 ? IHf2 e /=; case/andP; case/(IHf1 e) => ?; first by left; left.\n  by case/(IHf2 e); constructor; tauto.\n- move=> ? IHf1 ? IHf2 e /=; case/andP; case/(IHf1 e) => ?; last by left.\n  by case/(IHf2 e); constructor; tauto.\n- by move=> f IHf e /=; case/(IHf e); constructor; tauto.\n- move=> n f IHf e /= rf.\n  by apply: (iffP (aux _ _ _ (qfree_quantifier_elim rf)));\n    case=> x hx; exists x; apply/IHf.\n- move=> n f IHf e /= rf; case: (aux (~_)%T e n (qfree_quantifier_elim rf)).\n    by move=> hf; right; case : hf => x hx; move/(_ x)=> hx'; case/IHf: hx.\nby move=> hf; left=> x; apply/IHf=> //; apply/idPn=> hx; case: hf; exists x.\nQed.\n\nDefinition proj_sat f e := qfree_eval e (quantifier_elim (to_rformula f)).\n\nLemma proj_satP : DecidableField.axiom proj_sat.\nProof.\nrewrite /DecidableField.axiom /proj_sat; move=> f e.\nby apply: (iffP (quantifier_elim_ringf _ ( rformula_to_rformula _)));\nmove/to_rformula_equiv.\nQed.\n\nDefinition QEDecidableFieldMixin := DecidableField.Mixin proj_satP.\n\nCanonical Structure QEDecidableField :=\n  Eval hnf in DecidableField.pack QEDecidableFieldMixin.\n\nEnd QE_theory.\n\n\nModule ClosedField.\n\n(* Axiom == all non-constant monic polynomials have a root *)\nDefinition axiom (R : Ring.type) :=\n  forall n (P : nat -> R), n > 0 ->\n   exists x : R, x ^+ n = \\sum_(i < n) P i * (x ^+ i).\n\nRecord class_of (F : Type) : Type :=\n  Class {base :> DecidableField.class_of F; _ : axiom (Ring.Pack base F)}.\n\nStructure type : Type := Pack {sort :> Type; _ : class_of sort; _ : Type}.\nDefinition class cT := let: Pack _ c _ := cT return class_of cT in c.\nDefinition unpack K (k : forall T (c : class_of T), K T c) cT :=\n  let: Pack T c _ := cT return K _ (class cT) in k _ c.\nDefinition repack cT : _ -> Type -> type := let k T c p := p c in unpack k cT.\n\nDefinition pack :=\n  let k T c ax := Pack (@Class T c ax) T in DecidableField.unpack k.\n\n(* There should eventually be a constructor from polynomial resolution *)\n(* that builds the DecidableField mixin using QE.                      *)\n\nDefinition eqType cT := Equality.Pack (class cT) cT.\nDefinition choiceType cT := Choice.Pack (class cT) cT.\nDefinition zmodType cT := Zmodule.Pack (class cT) cT.\nDefinition ringType cT := Ring.Pack (class cT) cT.\nDefinition comRingType cT := ComRing.Pack (class cT) cT.\nDefinition unitRingType cT := UnitRing.Pack (class cT) cT.\nDefinition comUnitRingType cT := ComUnitRing.Pack (class cT) cT.\nDefinition idomainType cT := IntegralDomain.Pack (class cT) cT.\nDefinition fieldType cT := Field.Pack (class cT) cT.\nCoercion decFieldType cT := DecidableField.Pack (class cT) cT.\n\nEnd ClosedField.\n\nCanonical Structure ClosedField.eqType.\nCanonical Structure ClosedField.choiceType.\nCanonical Structure ClosedField.zmodType.\nCanonical Structure ClosedField.ringType.\nCanonical Structure ClosedField.unitRingType.\nCanonical Structure ClosedField.comRingType.\nCanonical Structure ClosedField.comUnitRingType.\nCanonical Structure ClosedField.idomainType.\nCanonical Structure ClosedField.fieldType.\nCanonical Structure ClosedField.decFieldType.\n\nBind Scope ring_scope with ClosedField.sort.\n\nSection ClosedFieldTheory.\n\nVariable F : ClosedField.type.\n\nLemma solve_monicpoly : ClosedField.axiom F.\nProof. by case: F => ? []. Qed.\n\nEnd ClosedFieldTheory.\n\nModule Theory.\n\nDefinition addrA := addrA.\nDefinition addrC := addrC.\nDefinition add0r := add0r.\nDefinition addNr := addNr.\nDefinition addr0 := addr0.\nDefinition addrN := addrN.\nDefinition subrr := subrr.\nDefinition addrCA := addrCA.\nDefinition addrAC := addrAC.\nDefinition addKr := addKr.\nDefinition addNKr := addNKr.\nDefinition addrK := addrK.\nDefinition addrNK := addrNK.\nDefinition subrK := subrK.\nDefinition addrI := addrI.\nDefinition addIr := addIr.\nDefinition opprK := opprK.\nDefinition oppr0 := oppr0.\nDefinition oppr_eq0 := oppr_eq0.\nDefinition oppr_add := oppr_add.\nDefinition oppr_sub := oppr_sub.\nDefinition subr_eq := subr_eq.\nDefinition subr_eq0 := subr_eq0.\nDefinition sumr_opp := sumr_opp.\nDefinition sumr_sub := sumr_sub.\nDefinition sumr_muln := sumr_muln.\nDefinition sumr_const := sumr_const.\nDefinition mulr0n := mulr0n.\nDefinition mulrS := mulrS.\nDefinition mulr1n := mulr1n.\nDefinition mulrSr := mulrSr.\nDefinition mul0rn := mul0rn.\nDefinition oppr_muln := oppr_muln.\nDefinition mulrn_addl := mulrn_addl.\nDefinition mulrn_addr := mulrn_addr.\nDefinition mulrnA := mulrnA.\nDefinition mulrnAC := mulrnAC.\nDefinition mulrA := mulrA.\nDefinition mul1r := mul1r.\nDefinition mulr1 := mulr1.\nDefinition mulr_addl := mulr_addl.\nDefinition mulr_addr := mulr_addr.\nDefinition nonzero1r := nonzero1r.\nDefinition oner_eq0 := oner_eq0.\nDefinition mul0r := mul0r.\nDefinition mulr0 := mulr0.\nDefinition mulrN := mulrN.\nDefinition mulNr := mulNr.\nDefinition mulrNN := mulrNN.\nDefinition mulN1r := mulN1r.\nDefinition mulrN1 := mulrN1.\nDefinition mulr_natr := mulr_natr.\nDefinition mulr_natl := mulr_natl.\nDefinition natr_add := natr_add.\nDefinition natr_mul := natr_mul.\nDefinition expr0 := expr0.\nDefinition exprS := exprS.\nDefinition expr1 := expr1.\nDefinition exp1rn := exp1rn.\nDefinition exprn_addr := exprn_addr.\nDefinition exprSr := exprSr.\nDefinition commr_sym := commr_sym.\nDefinition commr_refl := commr_refl.\nDefinition commr0 := commr0.\nDefinition commr1 := commr1.\nDefinition commr_opp := commr_opp.\nDefinition commrN1 := commrN1.\nDefinition commr_add := commr_add.\nDefinition commr_muln := commr_muln.\nDefinition commr_mul := commr_mul.\nDefinition commr_nat := commr_nat.\nDefinition commr_exp := commr_exp.\nDefinition commr_exp_mull := commr_exp_mull.\nDefinition exprn_mulnl := exprn_mulnl.\nDefinition exprn_mulr := exprn_mulr.\nDefinition signr_odd := signr_odd.\nDefinition signr_eq0 := signr_eq0.\nDefinition signr_addb := signr_addb.\nDefinition exprN := exprN.\nDefinition prodr_const := prodr_const.\nDefinition mulrC := mulrC.\nDefinition mulrCA := mulrCA.\nDefinition mulrAC := mulrAC.\nDefinition exprn_mull := exprn_mull.\nDefinition prodr_exp := prodr_exp.\nDefinition mulrV := mulrV.\nDefinition divrr := divrr.\nDefinition mulVr := mulVr.\nDefinition invr_out := invr_out.\nDefinition unitrP := unitrP.\nDefinition mulKr := mulKr.\nDefinition mulVKr := mulVKr.\nDefinition mulrK := mulrK.\nDefinition mulrVK := mulrVK.\nDefinition divrK := divrK.\nDefinition mulrI := mulrI.\nDefinition mulIr := mulIr.\nDefinition commr_inv := commr_inv.\nDefinition unitrE := unitrE.\nDefinition invrK := invrK.\nDefinition invr_inj := invr_inj.\nDefinition unitr_inv := unitr_inv.\nDefinition unitr1 := unitr1.\nDefinition invr1 := invr1.\nDefinition unitr0 := unitr0.\nDefinition invr0 := invr0.\nDefinition unitr_opp := unitr_opp.\nDefinition invrN := invrN.\nDefinition unitr_mull := unitr_mull.\nDefinition unitr_mulr := unitr_mulr.\nDefinition invr_mul := invr_mul.\nDefinition invr_eq0 := invr_eq0.\nDefinition invr_neq0 := invr_neq0.\nDefinition commr_unit_mul := commr_unit_mul.\nDefinition unitr_exp := unitr_exp.\nDefinition unitr_pexp := unitr_pexp.\nDefinition expr_inv := expr_inv.\nDefinition eq_eval := eq_eval.\nDefinition eval_tsubst := eval_tsubst.\nDefinition eq_holds := eq_holds.\nDefinition holds_fsubst := holds_fsubst.\nDefinition unitr_mul := unitr_mul.\nDefinition mulf_eq0 := mulf_eq0.\nDefinition mulf_neq0 := mulf_neq0.\nDefinition expf_eq0 := expf_eq0.\nDefinition expf_neq0 := expf_neq0.\nDefinition mulfI := mulfI.\nDefinition mulIf := mulIf.\nDefinition unitfE := unitfE.\nDefinition mulVf := mulVf.\nDefinition mulfV := mulfV.\nDefinition divff := divff.\nDefinition mulKf := mulKf.\nDefinition mulVKf := mulVKf.\nDefinition mulfK := mulfK.\nDefinition mulfVK := mulfVK.\nDefinition divfK := divfK.\nDefinition invf_mul := invf_mul.\nDefinition prodf_inv := prodf_inv.\nDefinition satP := @satP.\nDefinition eq_sat := eq_sat.\nDefinition solP := @solP.\nDefinition eq_sol := eq_sol.\nDefinition size_sol := size_sol.\nDefinition ring_morphism := ring_morphism.\nDefinition solve_monicpoly := solve_monicpoly.\n\nLemma ringM_sub : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f -> {morph f : x y / x - y >-> x - y}.\nProof. exact: ringM_sub. Qed.\n\nLemma ringM_0 : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f -> f 0 = 0.\nProof. exact: ringM_0. Qed.\n\nLemma ringM_1 : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f -> f 1 = 1.\nProof. exact: ringM_1. Qed.\n\nLemma ringM_opp : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f -> {morph f : x / - x >-> - x}.\nProof. exact: ringM_opp. Qed.\n\nLemma ringM_add : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f -> {morph f : x y / x + y >-> x + y}.\nProof. exact: ringM_add. Qed.\n\nLemma ringM_sum : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f ->\n       forall (I : Type) (r : seq I) (P : pred I) (F : I -> aR),\n       f (\\sum_(i <- r | P i) F i) = \\sum_(i <- r | P i) f (F i).\nProof. exact: ringM_sum. Qed.\n\nLemma ringM_mul : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f -> {morph f : x y / x * y >-> x * y}.\nProof. exact: ringM_mul. Qed.\n\nLemma ringM_prod : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f ->\n       forall (I : Type) (r : seq I) (P : pred I) (F : I -> aR),\n       f (\\prod_(i <- r | P i) F i) = \\prod_(i <- r | P i) f (F i).\nProof. exact: ringM_prod. Qed.\n\nLemma ringM_nat : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f -> forall n : nat, f n%:R = n%:R.\nProof. exact: ringM_nat. Qed.\n\nLemma ringM_exp : forall (aR rR : Ring.type) (f : aR -> rR),\n       ring_morphism f ->\n       forall n : nat, {morph f : x / x ^+ n >-> x ^+ n}.\nProof. exact: ringM_exp. Qed.\n\nLemma comp_ringM :\n forall (aR' aR rR : Ring.type) (f : aR -> rR) (g : aR' -> aR),\n       ring_morphism f -> ring_morphism g -> ring_morphism (f \\o g).\nProof. exact: comp_ringM. Qed.\n\n\nImplicit Arguments satP [F f e].\nImplicit Arguments solP [F f n].\nPrenex Implicits satP solP.\n\nEnd Theory.\n\nEnd GRing.\n\nCanonical Structure GRing.Zmodule.eqType.\nCanonical Structure GRing.Zmodule.choiceType.\nCanonical Structure GRing.Ring.eqType.\nCanonical Structure GRing.Ring.choiceType.\nCanonical Structure GRing.Ring.zmodType.\nCanonical Structure GRing.UnitRing.eqType.\nCanonical Structure GRing.UnitRing.choiceType.\nCanonical Structure GRing.UnitRing.zmodType.\nCanonical Structure GRing.UnitRing.ringType.\nCanonical Structure GRing.ComRing.eqType.\nCanonical Structure GRing.ComRing.choiceType.\nCanonical Structure GRing.ComRing.zmodType.\nCanonical Structure GRing.ComRing.ringType.\nCanonical Structure GRing.ComUnitRing.eqType.\nCanonical Structure GRing.ComUnitRing.choiceType.\nCanonical Structure GRing.ComUnitRing.zmodType.\nCanonical Structure GRing.ComUnitRing.ringType.\nCanonical Structure GRing.ComUnitRing.unitRingType.\nCanonical Structure GRing.ComUnitRing.comRingType.\nCanonical Structure GRing.ComUnitRing.com_unitRingType.\nCanonical Structure GRing.IntegralDomain.eqType.\nCanonical Structure GRing.IntegralDomain.choiceType.\nCanonical Structure GRing.IntegralDomain.zmodType.\nCanonical Structure GRing.IntegralDomain.ringType.\nCanonical Structure GRing.IntegralDomain.unitRingType.\nCanonical Structure GRing.IntegralDomain.comRingType.\nCanonical Structure GRing.IntegralDomain.comUnitRingType.\nCanonical Structure GRing.Field.eqType.\nCanonical Structure GRing.Field.choiceType.\nCanonical Structure GRing.Field.zmodType.\nCanonical Structure GRing.Field.ringType.\nCanonical Structure GRing.Field.unitRingType.\nCanonical Structure GRing.Field.comRingType.\nCanonical Structure GRing.Field.comUnitRingType.\nCanonical Structure GRing.Field.idomainType.\nCanonical Structure GRing.DecidableField.eqType.\nCanonical Structure GRing.DecidableField.choiceType.\nCanonical Structure GRing.DecidableField.zmodType.\nCanonical Structure GRing.DecidableField.ringType.\nCanonical Structure GRing.DecidableField.unitRingType.\nCanonical Structure GRing.DecidableField.comRingType.\nCanonical Structure GRing.DecidableField.comUnitRingType.\nCanonical Structure GRing.DecidableField.idomainType.\nCanonical Structure GRing.DecidableField.fieldType.\nCanonical Structure GRing.ClosedField.eqType.\nCanonical Structure GRing.ClosedField.choiceType.\nCanonical Structure GRing.ClosedField.zmodType.\nCanonical Structure GRing.ClosedField.ringType.\nCanonical Structure GRing.ClosedField.unitRingType.\nCanonical Structure GRing.ClosedField.comRingType.\nCanonical Structure GRing.ClosedField.comUnitRingType.\nCanonical Structure GRing.ClosedField.idomainType.\nCanonical Structure GRing.ClosedField.fieldType.\nCanonical Structure GRing.ClosedField.decFieldType.\n\nCanonical Structure GRing.add_monoid.\nCanonical Structure GRing.add_comoid.\nCanonical Structure GRing.mul_monoid.\nCanonical Structure GRing.mul_comoid.\nCanonical Structure GRing.muloid.\nCanonical Structure GRing.addoid.\n\nBind Scope ring_scope with GRing.Zmodule.sort.\nBind Scope ring_scope with GRing.Ring.sort.\nBind Scope ring_scope with GRing.ComRing.sort.\nBind Scope ring_scope with GRing.UnitRing.sort.\nBind Scope ring_scope with GRing.ComUnitRing.sort.\nBind Scope ring_scope with GRing.IntegralDomain.sort.\nBind Scope ring_scope with GRing.Field.sort.\nBind Scope ring_scope with GRing.DecidableField.sort.\nBind Scope ring_scope with GRing.ClosedField.sort.\n\nNotation \"0\" := (GRing.zero _) : ring_scope.\nNotation \"-%R\" := (@GRing.opp _) : ring_scope.\nNotation \"- x\" := (GRing.opp x) : ring_scope.\nNotation \"+%R\" := (@GRing.add _).\nNotation \"x + y\" := (GRing.add x y) : ring_scope.\nNotation \"x - y\" := (GRing.add x (- y)) : ring_scope.\nNotation \"x *+ n\" := (GRing.natmul x n) : ring_scope.\nNotation \"x *- n\" := (GRing.natmul (- x) n) : ring_scope.\n\nNotation \"1\" := (GRing.one _) : ring_scope.\nNotation \"- 1\" := (- (1))%R : ring_scope.\n\nNotation \"n %:R\" := (GRing.natmul 1 n) : ring_scope.\nNotation \"*%R\" := (@GRing.mul _).\nNotation \"x * y\" := (GRing.mul x y) : ring_scope.\nNotation \"x ^+ n\" := (GRing.exp x n) : ring_scope.\nNotation \"x ^-1\" := (GRing.inv x) : ring_scope.\nNotation \"x ^- n\" := (x ^+ n)^-1%R : ring_scope.\nNotation \"x / y\" := (GRing.mul x y^-1) : ring_scope.\nNotation \"s `_ i\" := (seq.nth 0%R s%R i) : ring_scope.\n\nImplicit Arguments GRing.unitDef [].\n\nBind Scope term_scope with GRing.term.\nBind Scope term_scope with GRing.formula.\n\nNotation \"''X_' i\" := (GRing.Var _ i)\n  (at level 8, i at level 2, format \"''X_' i\") : term_scope.\nNotation \"n %:R\" := (GRing.NatConst _ n) : term_scope.\nInfix \"+\" := GRing.Add : term_scope.\nNotation \"- t\" := (GRing.Opp t) : term_scope.\nNotation \"t - u\" := (GRing.Add t (- u)) : term_scope.\nInfix \"*\" := GRing.Mul : term_scope.\nInfix \"*+\" := GRing.NatMul : term_scope.\nNotation \"t ^-1\" := (GRing.Inv t) : term_scope.\nNotation \"t / u\" := (GRing.Mul t u^-1) : term_scope.\nInfix \"^+\" := GRing.Exp : term_scope.\nInfix \"==\" := GRing.Equal : term_scope.\nInfix \"/\\\" := GRing.And : term_scope.\nInfix \"\\/\" := GRing.Or : term_scope.\nInfix \"==>\" := GRing.Implies : term_scope.\nNotation \"~ f\" := (GRing.Not f) : term_scope.\nNotation \"'exists' ''X_' i , f\" := (GRing.Exists i f)\n  (at level 200, i at level 2,\n   format \"'[hv' 'exists'  ''X_' i , '/ '  f ']'\") : term_scope.\nNotation \"'forall' ''X_' i , f\" := (GRing.Forall i f)\n  (at level 200, i at level 2,\n   format \"'[hv' 'forall'  ''X_' i , '/ '  f ']'\") : term_scope.\n\nNotation \"\\sum_ ( <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(<- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r ) F\" :=\n  (\\big[+%R/0%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i | P ) F\" :=\n  (\\big[+%R/0%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\sum_ i F\" :=\n  (\\big[+%R/0%R]_i F%R) : ring_scope.\nNotation \"\\sum_ ( i : t | P ) F\" :=\n  (\\big[+%R/0%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i : t ) F\" :=\n  (\\big[+%R/0%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i < n ) F\" :=\n  (\\big[+%R/0%R]_(i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i \\in A | P ) F\" :=\n  (\\big[+%R/0%R]_(i \\in A | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i \\in A ) F\" :=\n  (\\big[+%R/0%R]_(i \\in A) F%R) : ring_scope.\n\nNotation \"\\prod_ ( <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(<- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[*%R/1%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[*%R/1%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[*%R/1%R]_i F%R) : ring_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[*%R/1%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[*%R/1%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[*%R/1%R]_(i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i \\in A | P ) F\" :=\n  (\\big[*%R/1%R]_(i \\in A | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i \\in A ) F\" :=\n  (\\big[*%R/1%R]_(i \\in A) F%R) : ring_scope.\n\nNotation zmodType := GRing.Zmodule.type.\nNotation ZmodType := GRing.Zmodule.pack.\nNotation ZmodMixin := GRing.Zmodule.Mixin.\nNotation \"[ 'zmodType' 'of' T 'for' cT ]\" :=\n    (@GRing.Zmodule.repack cT (@GRing.Zmodule.Pack T) T)\n  (at level 0, format \"[ 'zmodType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'zmodType' 'of' T ]\" :=\n    (GRing.Zmodule.repack (fun c => @GRing.Zmodule.Pack T c) T)\n  (at level 0, format \"[ 'zmodType'  'of'  T ]\") : form_scope.\n\nNotation ringType := GRing.Ring.type.\nNotation RingType := GRing.Ring.pack.\nNotation RingMixin := GRing.Ring.Mixin.\nNotation RevRingType := GRing.RevRingType.\nNotation \"[ 'ringType' 'of' T 'for' cT ]\" :=\n    (@GRing.Ring.repack cT (@GRing.Ring.Pack T) T)\n  (at level 0, format \"[ 'ringType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'ringType' 'of' T ]\" :=\n    (GRing.Ring.repack (fun c => @GRing.Ring.Pack T c) T)\n  (at level 0, format \"[ 'ringType'  'of'  T ]\") : form_scope.\n\nNotation comRingType := GRing.ComRing.type.\nNotation ComRingType := GRing.ComRing.pack.\nNotation ComRingMixin := GRing.ComRing.RingMixin.\nNotation \"[ 'comRingType' 'of' T 'for' cT ]\" :=\n    (@GRing.ComRing.repack cT (@GRing.ComRing.Pack T) T)\n  (at level 0, format \"[ 'comRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'comRingType' 'of' T ]\" :=\n    (GRing.ComRing.repack (fun c => @GRing.ComRing.Pack T c) T)\n  (at level 0, format \"[ 'comRingType'  'of'  T ]\") : form_scope.\n\nNotation unitRingType := GRing.UnitRing.type.\nNotation UnitRingType := GRing.UnitRing.pack.\nNotation UnitRingMixin := GRing.UnitRing.EtaMixin.\nNotation Com_UnitRingType := GRing.UnitRing.comPack.\nNotation \"[ 'unitRingType' 'of' T 'for' cT ]\" :=\n    (@GRing.UnitRing.repack cT (@GRing.UnitRing.Pack T) T)\n  (at level 0, format \"[ 'unitRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'unitRingType' 'of' T ]\" :=\n    (GRing.UnitRing.repack (fun c => @GRing.UnitRing.Pack T c) T)\n  (at level 0, format \"[ 'unitRingType'  'of'  T ]\") : form_scope.\n\nNotation comUnitRingType := GRing.ComUnitRing.type.\nNotation ComUnitRingType := GRing.ComUnitRing.pack.\nNotation ComUnitRingMixin := GRing.ComUnitRing.Mixin.\nNotation \"[ 'comUnitRingType' 'of' T 'for' cT ]\" :=\n    (@GRing.ComUnitRing.repack cT (@GRing.ComUnitRing.Pack T) T)\n  (at level 0,\n   format \"[ 'comUnitRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'comUnitRingType' 'of' T ]\" :=\n    (GRing.ComUnitRing.repack (fun c => @GRing.ComUnitRing.Pack T c) T)\n  (at level 0, format \"[ 'comUnitRingType'  'of'  T ]\") : form_scope.\n\nNotation idomainType := GRing.IntegralDomain.type.\nNotation IdomainType := GRing.IntegralDomain.pack.\nNotation \"[ 'idomainType' 'of' T 'for' cT ]\" :=\n    (@GRing.IntegralDomain.repack cT (@GRing.IntegralDomain.Pack T) T)\n  (at level 0, format \"[ 'idomainType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'idomainType' 'of' T ]\" :=\n    (GRing.IntegralDomain.repack (fun c => @GRing.IntegralDomain.Pack T c) T)\n  (at level 0, format \"[ 'idomainType'  'of'  T ]\") : form_scope.\n\nNotation fieldType := GRing.Field.type.\nNotation FieldType := GRing.Field.pack.\nNotation FieldUnitMixin := GRing.Field.UnitMixin.\nNotation FieldIdomainMixin := GRing.Field.IdomainMixin.\nNotation FieldMixin := GRing.Field.Mixin.\nNotation \"[ 'fieldType' 'of' T 'for' cT ]\" :=\n    (@GRing.Field.repack cT (@GRing.Field.Pack T) T)\n  (at level 0, format \"[ 'fieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'fieldType' 'of' T ]\" :=\n    (GRing.Field.repack (fun c => @GRing.Field.Pack T c) T)\n  (at level 0, format \"[ 'fieldType'  'of'  T ]\") : form_scope.\n\nNotation decFieldType := GRing.DecidableField.type.\nNotation DecFieldType := GRing.DecidableField.pack.\nNotation DecFieldMixin := GRing.DecidableField.Mixin.\nNotation \"[ 'decFieldType' 'of' T 'for' cT ]\" :=\n    (@GRing.DecidableField.repack cT (@GRing.DecidableField.Pack T) T)\n  (at level 0, format \"[ 'decFieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'decFieldType' 'of' T ]\" :=\n    (GRing.DecidableField.repack (fun c => @GRing.DecidableField.Pack T c) T)\n  (at level 0, format \"[ 'decFieldType'  'of'  T ]\") : form_scope.\n\nNotation closedFieldType := GRing.ClosedField.type.\nNotation ClosedFieldType := GRing.ClosedField.pack.\nNotation \"[ 'closedFieldType' 'of' T 'for' cT ]\" :=\n    (@GRing.ClosedField.repack cT (@GRing.ClosedField.Pack T) T)\n  (at level 0,\n   format \"[ 'closedFieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'closedFieldType' 'of' T ]\" :=\n    (GRing.ClosedField.repack (fun c => @GRing.ClosedField.Pack T c) T)\n  (at level 0, format \"[ 'closedFieldType'  'of'  T ]\") : form_scope.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect12/theories/ssralg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7418288945238153}}
{"text": "(* Basic workflow:\n  1. Represent your data using Coq data types\n  2. Express computation as Coq programs that operate on the data type\n  3. State and prove theorems about computation\n*)\n\n(* Note: you can follow along the first module using the JsCoq\n  online IDE: https://coq.vercel.app/ *)\n\nModule MyNat.\n\nInductive nat :=\n  | O: nat\n  | S: nat -> nat.\n\nFixpoint add (n m: nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (add n' m)\n  end.\n\nNotation \"1\" := (S O).\nNotation \"2\" := (S 1).\nNotation \"3\" := (S 2).\n\nFact add_2_1: add 2 1 = 3.\nProof.\n  simpl. reflexivity.\nQed.\n\nLemma add_0_r: forall (n: nat), add n O = n.\nProof.\nAdmitted.\n\nLemma add_m_Sn: forall (m n: nat), add m (S n) = S (add m n).\nProof.\nAdmitted.\n\nTheorem add_comm: forall n m, add n m = add m n.\nProof.\n  induction n.\n  - intros. simpl. rewrite add_0_r. reflexivity.\n  - intros. simpl. rewrite IHn. rewrite add_m_Sn. reflexivity.\nQed.\n\nEnd MyNat.\n\n\n\n\n(* Let's now nstantiate the recipe to prove circom circuits! *)\n(* Note that the following must be run as part of the circom-coq project:\n * https://github.com/Veridise/circom-coq *)\n\nSection circom.\n\n(* 1. Represent your data using Coq data types *)\n\n(* Relies on existing formalizations in Coq and the Fiat-Crypto project *)\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Init.Peano.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.PArith.BinPosDef.\nRequire Import Coq.ZArith.BinInt Coq.ZArith.ZArith Coq.ZArith.Zdiv Coq.ZArith.Znumtheory Coq.NArith.NArith. (* import Zdiv before Znumtheory *)\nRequire Import Coq.NArith.Nnat.\nRequire Import Crypto.Spec.ModularArithmetic.\nRequire Import Crypto.Spec.ModularArithmetic.\nRequire Import Crypto.Arithmetic.PrimeFieldTheorems Crypto.Algebra.Field.\nRequire Import Crypto.Util.Tuple.\nRequire Import Crypto.Util.Decidable Crypto.Util.Notations.\nRequire Import BabyJubjub.\nRequire Import Coq.setoid_ring.Ring_theory Coq.setoid_ring.Field_theory Coq.setoid_ring.Field_tac.\nRequire Import Util.\n\n(* Some prep work... *)\n\nLocal Open Scope list_scope.\nLocal Open Scope F_scope.\n\nLtac fqsatz := fsatz_safe; autorewrite with core; auto.\nContext (q:positive) (k:Z) {prime_q: prime q} {two_lt_q: 2 < q} {k_positive: 1 < k} {q_lb: 2^k < q}.\n\nLemma q_gtb_1: (1 <? q)%positive = true.\nProof.\n  apply Pos.ltb_lt. lia.\nQed.\n\nLemma q_gt_2: 2 < q.\nProof.\n  replace 2%Z with (2^1)%Z by lia.\n  apply Z.le_lt_trans with (m := (2 ^ k)%Z); try lia.\n  eapply Zpow_facts.Zpower_le_monotone; try lia.\nQed.\n\nHint Rewrite q_gtb_1 : core.\n\n(* test whether a field element is binary *)\nDefinition binary (x: F q) := x = 0 \\/ x = 1.\nDefinition two : F q := 1 + 1.\nNotation \"2\" := two.\nNotation \"x [ i ]\" := (Tuple.nth_default 0 i x).\n\n\n\n(* 2. Express computation as Coq programs that operate on the data type *)\n\n(***********************\n *      Num2Bits\n ***********************)\n\n(* Circuit:\n* https://github.com/iden3/circomlib/blob/master/circuits/bitify.circom\n*)\n\nDefinition Num2Bits (n: nat) (_in: F q) (_out: tuple (F q) n) : Prop :=\n  let lc1 := 0 in\n  let e2 := 1 in\n  let '(lc1, e2, _C) := (iter n (fun (i: nat) '(lc1, e2, _C) =>\n      (* circom: lc += out[i] * e2 *)\n      (lc1 + _out[i] * e2,\n      (* circom: e2 = e2 + e2 *)\n      e2 + e2,\n      (* circom: out[i] * (out[i] -1 ) === 0 *)\n      (_out[i] * (_out[i] - 1) = 0) /\\ _C))\n    (lc1, e2, True)) in\n  _C /\\ (lc1 = _in).\nPrint Num2Bits.\n\n\n\n(* 3. State and prove theorems about computation *)\n\n(* All output signals are binary *)\nTheorem Num2Bits_is_binary n _in _out:\n  Num2Bits n _in _out ->\n  (forall i, (i < n)%nat -> binary (_out[i])).\nProof.\n  unfold Num2Bits.\n  (* provide the loop invariant *)\n  pose (Inv := fun i '((lc1, e2, _C): (F.F q * F.F q * Prop)) =>\n    (_C -> (forall j, Nat.lt j i -> binary (_out[j])))).\n  (* iter initialization *)\n  remember (0, 1, True) as a0.\n  intros prog i H_i_lt_n.\n  (* iter function *)\n  match goal with\n  | [ H: context[match ?it ?n ?f ?init with _ => _ end] |- _ ] =>\n    let x := fresh \"f\" in remember f as x\n  end.\n  (* Prove that the invariant holds *)\n  assert (Hinv: forall i, Inv i (iter i f a0)). {\n  intros. apply iter_inv; unfold Inv.\n  - (* base case *) \n    subst. intros _ j impossible. lia.\n  - (* inductive case *)\n    intros j res Hprev.\n    destruct res. destruct p.\n    rewrite Heqf.\n    intros Hstep j0 H_j0_lt.\n    destruct Hstep as [Hstep HP].\n    specialize  (Hprev HP).\n    assert (H_j0_leq: (j0 <= j)%nat) by lia.\n    destruct (dec (j0 < j)%nat).\n    + auto.\n    + unfold binary.\n      replace j0 with j by lia.\n      destruct (dec (Tuple.nth_default 0 j _out = 0)).\n      * auto.\n      * right. fqsatz.\n   }\n  unfold Inv in Hinv.\n  specialize (Hinv n).\n  destruct (iter n f a0).\n  destruct p.\n  (* This is a big hammer for proving things that are _obviously_ true *)\n  intuition.\nQed.", "meta": {"author": "Veridise", "repo": "Coda", "sha": "d22d56c09ac541f012adae34820850ce6cd10270", "save_path": "github-repos/coq/Veridise-Coda", "path": "github-repos/coq/Veridise-Coda/Coda-d22d56c09ac541f012adae34820850ce6cd10270/BigInt/src/Demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7418288876627256}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Import R_sqrt.\nRequire BuiltIn.\nRequire real.Real.\nRequire real.Square.\n\n(* Why3 assumption *)\nDefinition dot (x1:R) (x2:R) (y1:R) (y2:R): R :=\n  ((x1 * y1)%R + (x2 * y2)%R)%R.\n\n(* Why3 assumption *)\nDefinition norm2 (x1:R) (x2:R): R := ((Rsqr x1) + (Rsqr x2))%R.\n\nAxiom norm2_pos : forall (x1:R) (x2:R), (0%R <= (norm2 x1 x2))%R.\n\nAxiom Lagrange : forall (a1:R) (a2:R) (b1:R) (b2:R), (((norm2 a1\n  a2) * (norm2 b1 b2))%R = ((Rsqr (dot a1 a2 b1\n  b2)) + (Rsqr ((a1 * b2)%R - (a2 * b1)%R)%R))%R).\n\nAxiom CauchySchwarz_aux : forall (x1:R) (x2:R) (y1:R) (y2:R), ((Rsqr (dot x1\n  x2 y1 y2)) <= ((norm2 x1 x2) * (norm2 y1 y2))%R)%R.\n\n(* Why3 assumption *)\nDefinition norm (x1:R) (x2:R): R := (sqrt (norm2 x1 x2)).\n\nAxiom norm_pos : forall (x1:R) (x2:R), (0%R <= (norm x1 x2))%R.\n\nAxiom sqr_le_sqrt : forall (x:R) (y:R), ((Rsqr x) <= y)%R ->\n  (x <= (sqrt y))%R.\n\nAxiom CauchySchwarz : forall (x1:R) (x2:R) (y1:R) (y2:R), ((dot x1 x2 y1\n  y2) <= ((norm x1 x2) * (norm y1 y2))%R)%R.\n\nAxiom triangle_aux : forall (x1:R) (x2:R) (y1:R) (y2:R), ((norm2 (x1 + y1)%R\n  (x2 + y2)%R) <= (Rsqr ((norm x1 x2) + (norm y1 y2))%R))%R.\n\nAxiom sqr_sqrt_le : forall (x:R) (y:R), ((0%R <= y)%R /\\ ((0%R <= x)%R /\\\n  (x <= (Rsqr y))%R)) -> ((sqrt x) <= y)%R.\n\n(* Why3 goal *)\nTheorem triangle : forall (x1:R) (x2:R) (y1:R) (y2:R), ((norm (x1 + y1)%R\n  (x2 + y2)%R) <= ((norm x1 x2) + (norm y1 y2))%R)%R.\nintros x1 x2 y1 y2.\napply sqr_sqrt_le.\nsplit.\napply Rplus_le_le_0_compat; apply norm_pos.\nsplit.\napply Rplus_le_le_0_compat; apply Rle_0_sqr.\napply triangle_aux.\nQed.\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/examples/logic/lagrange_inequality/lagrange_inequality_TriangleInequality_triangle_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7418226084168354}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (x : natural) : natural :=\n  plus (mult x y) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj186_coqofml_0wU4Av.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7418177951746935}}
{"text": "(**\n\nThis file contains temporary definitions that will eventually\nget merged into the various files from the TLC library.\n\nAuthor: Arthur Charguéraud.\nLicense: CC-by 4.0.\n\n*)\n\nSet Implicit Arguments.\nFrom SLF (* TLC *) Require Import LibTactics LibLogic LibList LibReflect.\nFrom SLF (* TLC *) Require LibListZ LibWf LibMultiset.\nGeneralizable Variables A B.\n\n(*----------------------*)\n(* Nat *)\n\nFrom SLF (* TLC *) Require Import LibNat LibInt.\nOpen Scope Int_scope.\n\nSection NatSimpl.\nOpen Scope nat_scope.\nImplicit Types n : nat.\n\nLemma nat_zero_plus : forall n,\n  0 + n = n.\nProof using. intros. math. Qed.\n\nLemma nat_plus_zero : forall n,\n  n + 0 = n.\nProof using. intros. math. Qed.\n\nLemma nat_plus_succ : forall n1 n2,\n  n1 + S n2 = S (n1 + n2).\nProof using. intros. math. Qed.\n\nLemma nat_minus_zero : forall n,\n  n - 0 = n.\nProof using. intros. math. Qed.\n\nLemma nat_succ_minus_succ : forall n1 n2,\n  S n1 - S n2 = n1 - n2.\nProof using. intros. math. Qed.\n\nLemma nat_minus_same : forall n,\n  n - n = 0.\nProof using. intros. math. Qed.\n\nLemma nat_plus_minus_same : forall n1 n2,\n  n1 + n2 - n1 = n2.\nProof using. intros. math. Qed.\n\nEnd NatSimpl.\n\nHint Rewrite nat_zero_plus nat_plus_zero nat_plus_succ\n  nat_minus_zero nat_succ_minus_succ\n  nat_minus_same nat_plus_minus_same : rew_nat.\n\n(** [nat_seq i n] generates a list of variables [x1;x2;..;xn]\n    with [x1=i] and [xn=i+n-1]. Such lists are useful for\n    generic programming. *)\n\nFixpoint nat_seq (start:nat) (nb:nat) :=\n  match nb with\n  | O => nil\n  | S nb' => start :: nat_seq (S start) nb'\n  end.\n\nLemma length_nat_seq : forall start nb,\n  length (nat_seq start nb) = nb.\nProof using.\n  intros. gen start. induction nb; simpl; intros.\n  { auto. } { rew_list. rewrite~ IHnb. }\nQed.\n\n(*----------------------*)\n(*--LATER: move to TLC LibNatExec *)\n\nFixpoint nat_compare (x y : nat) :=\n  match x, y with\n  | O, O => true\n  | S x', S y' => nat_compare x' y'\n  | _, _ => false\n  end.\n\nLemma nat_compare_eq : forall n1 n2,\n  nat_compare n1 n2 = isTrue (n1 = n2).\nProof using.\n  intros n1. induction n1; intros; destruct n2; simpl; rew_bool_eq; auto_false.\n  rewrite IHn1. extens. rew_istrue. math.\nQed.\n\n(*----------------------*)\n(* LibInt *)\n\nDefinition max (n m:int) : int :=\n  If n > m then n else m.\n\nLemma max_nonpos : forall n,\n  n <= 0 ->\n  max 0 n = 0.\nProof using. introv M. unfold max. case_if; math. Qed.\n\nLemma max_nonneg : forall n,\n  n >= 0 ->\n  max 0 n = n.\nProof using. introv M. unfold max. case_if; math. Qed.\n\nLemma max_l : forall n m,\n  n >= m ->\n  max n m = n.\nProof using. introv M. unfold max. case_if; math. Qed.\n\nLemma max_r : forall n m,\n  n <= m ->\n  max n m = m.\nProof using. introv M. unfold max. case_if; math. Qed.\n\n(*----------------------*)\n(* LibLogic *)\n\nLemma if_classicT_eq_if_isTrue : forall A (X Y:A) (P:Prop),\n  (If P then X else Y) = (if isTrue P then X else Y).\nProof using. intros. do 2 case_if~. Qed.\n\n(*----------------------*)\n(* TLCExec *)\n\nDefinition eq_exec A (cmp:A->A->bool) : Prop :=\n  forall x y, cmp x y = isTrue (x = y).\n\n\n(*----------------------*)\n(* ListAssoc *)\n\nModule LibListAssoc.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Lookup *)\n\nFixpoint get_opt A B (x:A) (E:list(A*B)) : option B :=\n  match E with\n  | nil => None\n  | (y,v)::E1 => If y = x\n                   then Some v\n                   else get_opt x E1\n  end.\n\nSection GetOpt.\nVariables (A B : Type).\nImplicit Types a x y : A.\nImplicit Types v : B.\nImplicit Types l : list (A*B).\n\nLemma get_opt_nil : forall a,\n  get_opt a (nil:list(A*B)) = None.\nProof using. auto. Qed.\n\nLemma get_opt_cons : forall x v l a,\n  get_opt a ((x,v)::l) = (If x = a then Some v else get_opt a l).\nProof using. auto. Qed.\n\nLemma get_opt_app : forall l1 l2 a,\n  get_opt a (l1 ++ l2) = match get_opt a l1 with\n                         | None => get_opt a l2\n                         | Some v => Some v\n                         end.\nProof using.\n  introv. induction l1 as [|(y,w) l1']; rew_list; simpl.\n  { auto. }\n  { case_if~. }\nQed.\n\nEnd GetOpt.\n\nHint Rewrite get_opt_nil get_opt_cons get_opt_app : rew_listx.\n\nGlobal Opaque get_opt.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Equivalence *)\n\nDefinition equiv A B (l1 l2:list(A*B)) :=\n  forall x, get_opt x l1 = get_opt x l2.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Disjointness *)\n\nDefinition disjoint A B (l1 l2:list(A*B)) :=\n  forall x v1 v2, get_opt x l1 = Some v1 -> get_opt x l2 = Some v2 -> False.\n\n(* --TODO: equivalent definitions of disjoint using mem *)\n\nSection Disjoint.\nVariables (A B : Type).\nImplicit Types l : list (A*B).\n\nLemma disjoint_cons_l_inv : forall x v l1 l2,\n  disjoint ((x,v)::l1) l2 ->\n  disjoint l1 l2.\nProof using.\n  introv M. intros y v1 v2 K1 K2. tests C: (x = y).\n  { applys M v v2 K2. rewrite get_opt_cons. case_if~. }\n  { applys M v1 v2 K2. rewrite get_opt_cons. case_if~. }\nQed.\n\nEnd Disjoint.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Remove key *)\n\nDefinition rem A B (x:A) (l:list(A*B)) :=\n  LibList.filter (fun '(y,v) => x <> y) l.\n\nSection Rem.\nVariables (A B : Type).\nImplicit Types a x y : A.\nImplicit Types v : B.\nImplicit Types l : list (A*B).\n\nLemma rem_as_filter : forall a l,\n  rem a l = LibList.filter (fun '(x,v) => a <> x) l.\nProof using. auto. Qed.\n\nLemma rem_nil : forall a,\n  rem a (nil:list(A*B)) = nil.\nProof using. auto. Qed.\n\nLemma rem_cons : forall x v l a,\n  rem a ((x,v)::l) = (If x = a then rem a l else (x,v) :: rem a l).\nProof using. intros. unfold rem. rewrite filter_cons. repeat case_if~. Qed.\n\nLemma rem_app : forall l1 l2 a,\n  rem a (l1 ++ l2) = rem a l1 ++ rem a l2.\nProof using. intros. unfold rem. rewrite~ filter_app. Qed.\n\nLemma rem_last : forall x v l a,\n  rem a (l & (x,v)) = rem a l ++ (If x = a then nil else (x,v)::nil).\nProof using. intros. unfold rem. rewrite filter_last. repeat case_if~. Qed.\n\nLemma get_opt_rem : forall x a l,\n  get_opt x (rem a l) = (If x = a then None else get_opt x l).\nProof using.\n  intros. induction l as [|(y,v) l']; simpl.\n  { do 2 rewrite~ get_opt_nil. case_if~. }\n  { rewrite rem_cons. rewrite get_opt_cons.\n    case_if; try rewrite get_opt_cons; repeat case_if; auto. }\nQed.\n\nLemma equiv_rem : forall a l1 l2,\n  equiv l1 l2 ->\n  equiv (rem a l1) (rem a l2).\nProof using.\n  introv M. unfolds equiv. intros y.\n  do 2 rewrite get_opt_rem. case_if~.\nQed.\n\nLemma disjoint_rem : forall a l1 l2,\n  disjoint l1 l2 ->\n  disjoint (rem a l1) (rem a l2).\nProof using.\n  introv D. intros y v1 v2 K1 K2. rewrite get_opt_rem in *.\n  case_if~. applys* D K1 K2.\nQed.\n\nEnd Rem.\n\nHint Rewrite rem_nil rem_cons rem_app rem_last : rew_listx.\n\nGlobal Opaque rem.\n\nEnd LibListAssoc.\n\nModule LibListAssocExec.\nImport LibListAssoc.\n\nDefinition is_beq A (beq:A->A->bool) :=\n  forall x y, beq x y = isTrue (x = y).\n\nFixpoint get_opt A (beq:A->A->bool) B (a:A) (l:list(A*B)) : option B :=\n  match l with\n  | nil => None\n  | (x,v)::l' => if beq x a\n                   then Some v\n                   else get_opt beq a l'\n  end.\n\nLemma get_opt_eq : forall A beq B a (l:list(A*B)),\n  is_beq beq ->\n  get_opt beq a l = LibListAssoc.get_opt a l.\nProof using.\n  introv M. induction l as [|(x,v) l']; simpl.\n  { rewrite~ get_opt_nil. }\n  { rewrite~ get_opt_cons. rewrite M. repeat case_if; auto. }\nQed.\n\nFixpoint rem A (beq:A->A->bool) B (x:A) (E:list(A*B)) : list(A*B) :=\n  match E with\n  | nil => nil\n  | (y,v)::E' =>\n      let E'' := rem beq x E' in\n      if beq x y then E'' else (y,v)::E''\n  end.\n\nLemma rem_eq : forall A beq B a (l:list(A*B)),\n  is_beq beq ->\n  rem beq a l = LibListAssoc.rem a l.\nProof using.\n  introv M. induction l as [|(x,v) l']; simpl.\n  { rewrite~ rem_nil. }\n  { rewrite~ rem_cons. rewrite M. repeat case_if; fequals. }\nQed.\n\nEnd LibListAssocExec.\n\n(*----------------------*)\n(* List *)\n\nSection ListSub.\nVariable (A:Type).\n\n(** Sub-list well-founded order *)\n\nInductive list_sub : list A -> list A -> Prop :=\n  | list_sub_cons : forall x l,\n      list_sub l (x::l)\n  | list_sub_tail : forall x l1 l2,\n      list_sub l1 l2 ->\n      list_sub l1 (x::l2).\n\nHint Constructors list_sub.\n\nLemma list_sub_wf : LibWf.wf list_sub.\nProof using.\n  intros l. induction l; apply Acc_intro; introv H.\n  { inverts~ H. }\n  { inverts~ H. applys~ IHl. }\nQed.\n\nEnd ListSub.\n\nArguments list_sub {A}.\nHint Constructors list_sub.\nHint Resolve list_sub_wf : wf.\n\n\n\nLemma length_zero_inv : forall A (L:list A),\n  length L = 0%nat ->\n  L = nil.\nProof using.\n  introv N. destruct L as [|]; rew_list in *; tryfalse. eauto.\nQed.\n\nLemma length_one_inv : forall A (L:list A),\n  length L = 1%nat ->\n  exists x, L = x::nil.\nProof using.\n  introv N. destruct L as [|x [|]]; rew_list in *; tryfalse. eauto.\nQed.\n\nLemma update_cons_case : forall (n:nat) A (v:A) (x:A) (l:list A),\n  LibList.update n v (x::l) = (If n = 0%nat then v::l else x::(LibList.update (n-1) v l)).\nProof using.\n  intros. destruct n as [|n']; case_if.\n  { applys update_zero. }\n  { rewrite update_cons. fequals_rec. math. }\nQed.\n\nLemma update_nth_same : forall A `{Inhab A} (n:nat) (l:list A),\n  n < length l ->\n  LibList.update n (LibList.nth n l) l = l.\nProof using.\n  introv E. gen n. induction l as [|x l']; intros.\n  { rewrite length_nil in E. false. math. }\n  { rewrite length_cons in E. rewrite update_cons_case.\n    destruct n as [|n']; case_if.\n    { subst. rewrite* nth_zero. }\n    { fequals. rewrite nth_cons. math_rewrite (S n' - 1 = n')%nat.\n      rewrite* IHl'. math. } }\nQed.\n\nGlobal Opaque LibList.update.\n\n(*----------------------*)\n(* ListExec *)\n\nFrom SLF (* TLC *) Require Import LibLogic. (* needed? *)\nFrom SLF (* TLC *) Require Import LibReflect.\n\nLemma not_mem_inv : forall A x y (l:list A),\n  ~ mem x (y::l) ->\n  x <> y /\\ ~ mem x l.\nProof using.\n  introv M. split.\n  { intro_subst. false* M. }\n  { intros N. false* M. }\nQed.\n\nDefinition is_nil A (l:list A) : bool :=\n  match l with\n  | nil => true\n  | _ => false\n  end.\n\nLemma is_nil_eq : forall A (l:list A),\n  is_nil l = isTrue (l = nil).\nProof using. intros. destruct l; simpl; rew_bool_eq; auto_false. Qed.\n\nDefinition is_not_nil A (l:list A) : bool :=\n  match l with\n  | nil => false\n  | _ => true\n  end.\n\nLemma is_not_nil_eq : forall A (l:list A),\n  is_not_nil l = isTrue (l <> nil).\nProof.\n  intros. destruct l; simpl; rew_bool_eq; auto_false.\nQed.\n\nLemma List_length_eq :\n  List.length = LibList.length.\nProof using. extens ;=> A l. induction l; simpl; rew_list; auto. Qed.\n\nLemma List_fold_right_eq : forall A B (f:A->B->B) (l:list A) (b:B),\n  List.fold_right f b l = LibList.fold_right f b l.\nProof using. intros. induction l; simpl; rew_list; fequals. Qed.\n\nLemma List_app_eq :\n  List.app = LibList.app.\nProof using.\n  extens ;=> A L1 L2. induction L1; simpl; rew_list; congruence.\nQed.\n\nLemma List_rev_eq : forall A, (* --LATER: why fails if A is not quantified here? *)\n  @List.rev A = @LibList.rev A.\nProof using.\n  extens ;=> L. induction L; simpl; rew_list. { auto. }\n  { rewrite List_app_eq. simpl. congruence. }\nQed.\n\nLemma List_map_eq :\n  List.map = LibList.map.\nProof using.\n  extens ;=> A B f L. induction L; simpl; rew_listx; congruence.\nQed.\n\nLemma List_combine_eq : forall A B (L1:list A) (L2:list B),\n  length L1 = length L2 ->\n  List.combine L1 L2 = LibList.combine L1 L2.\nProof using. (* --LATER: redo proof using list2_ind *)\n  introv E. gen L2.\n  induction L1 as [|x1 L1']; intros; destruct L2 as [|x2 L2']; tryfalse.\n  { auto. }\n  { rew_list in E. simpl. fequals~. }\nQed.\n\nHint Rewrite LibList.length_map : rew_listx.\n\n(* --TODO: replace all List_foo_eq with a rew_list_exec tactic *)\n\nFixpoint mem_exec A (cmp:A->A->bool) (x:A) (l:list A) : bool :=\n  match l with\n  | nil => false\n  | y::l' => cmp x y || mem_exec cmp x l'\n  end.\n\nLemma mem_exec_eq : forall A (cmp:A->A->bool) x l,\n  eq_exec cmp ->\n  mem_exec cmp x l = isTrue (mem x l).\nProof using.\n  introv Xcmp. induction l as [|y l']; simpl; rew_listx; rew_isTrue; fequals.\nQed.\n\n(*----------------------*)\n(* Hint for LibListZ *)\n\nHint Rewrite LibListZ.length_map LibListZ.index_map_eq : rew_arr.\n\n\n\n(*----------------------*)\n(* LibList *)\n\n(** The congruence rule for [map] on lists *)\n\nLemma map_congr : forall A B (f1 f2 : A->B) l,\n  (forall x, mem x l -> f1 x = f2 x) ->\n  LibList.map f1 l = LibList.map f2 l.\nProof using.\n  introv H. induction l. { auto. } { rew_listx. fequals~. }\nQed.\n\nLemma map_map : forall A B C (l:list A) (f:A->B) (g:B->C),\n  map g (map f l) = map (fun x => g (f x)) l.\nProof using.\n  intros. induction l as [|x l'].\n  { auto. }\n  { repeat rewrite map_cons. fequals. }\nQed.\n\nLemma mem_map' : forall A B (l : list A) (f:A->B) (x:A) (y:B),\n  mem x l ->\n  y = f x ->\n  mem y (LibList.map f l).\nProof using. intros. subst. applys* mem_map. Qed.\n\nLemma LibListZ_length_zero_eq_eq_nil : forall A (l:list A),\n  (LibListZ.length l = 0) = (l = nil).\nProof using.\n  intros. rewrite <- length_zero_eq_eq_nil.\n  unfold LibListZ.length. extens. math.\nQed.\n\n(*----------------------*)\n(* LibInt *)\n\nGlobal Opaque Z.mul.\nGlobal Opaque Z.add.\n\n(*----------------------*)\n(* LibEqual *)\n\nSection FuncExtDep.\nVariables (A1 : Type).\nVariables (A2 : forall (x1 : A1), Type).\nVariables (A3 : forall (x1 : A1) (x2 : A2 x1), Type).\nVariables (A4 : forall (x1 : A1) (x2 : A2 x1) (x3 : A3 x2), Type).\n\nLemma fun_eta_dep_3 : forall (f : forall (x1:A1) (x2:A2 x1) (x3:A3 x2), A4 x3),\n  (fun x1 x2 x3 => f x1 x2 x3) = f.\nProof using. intros. apply~ fun_ext_3. Qed.\n\nEnd FuncExtDep.\n\n\n(* ---------------------------------------------------------------------- *)\n(* LibTactics *)\n\n(* problematic to prove [(forall h, H1 h <-> H2 h) -> (H1 h <-> H2 h)]\nLtac jauto_set_goal ::=\n  repeat match goal with\n  | |- exists a, _ => esplit\n  | |- _ /\\ _ => split\n  | |- _ <-> _ => split\n  end. *)\n\nLtac fequal_base ::=\n  let go := f_equal_fixed; [ fequal_base | ] in\n  match goal with\n  | |- exist _ _ = exist _ _ => apply exist_eq_exist\n  | |- (_,_,_) = (_,_,_) => go\n  | |- (_,_,_,_) = (_,_,_,_) => go\n  | |- (_,_,_,_,_) = (_,_,_,_,_) => go\n  | |- (_,_,_,_,_,_) = (_,_,_,_,_,_) => go\n  | |- _ => f_equal_fixed\n  end.\n\n(* [isubst] generalizes [intro_subst]\n  DEPRECATED : should use [intros ? ->] *)\n\nLtac isbust_core tt :=\n  match goal with |- forall _, _ = _ -> _ =>\n    let X := fresh \"TEMP\" in\n    let HX := fresh \"E\" X in\n    intros X HX; subst X\n  end.\n\nTactic Notation \"isubst\" :=\n  isbust_core tt.\n\n(** [get_head E] implemented recursively *)\n\nLtac get_head E :=\n  match E with\n  | ?E' ?x => get_head E'\n  | _ => constr:(E)\n  end.\n\n(** [has_no_evar E] succeeds if [M] contains no evars. *)\n\nLtac has_no_evar E :=\n  first [ has_evar E; fail 1 | idtac ].\n\n(* ---------------------------------------------------------------------- *)\n(* Cases *)\n\nTactic Notation \"cases\" constr(E) :=\n  let H := fresh \"Eq\" in cases E as H.\n\n\n\n(* ---------------------------------------------------------------------- *)\n(* Induction on pairs of lists *)\n\nLemma list2_ind : forall A B (P:list A->list B->Prop) l1 l2,\n  length l1 = length l2 ->\n  P nil nil ->\n  (forall x1 xs1 x2 xs2,\n     length xs1 = length xs2 -> P xs1 xs2 -> P (x1::xs1) (x2::xs2)) ->\n  P l1 l2.\nProof using.\n  introv E M1 M2. gen l2. induction l1 as [|x1 l1']; intros;\n   destruct l2 as [|x2 l2']; try solve [false; math]; auto.\nQed.\n\nTactic Notation \"list2_ind\" constr(l1) constr(l2) :=\n  pattern l2; pattern l1;\n  match goal with |- (fun a => (fun b => @?P a b) _) _ =>\n   (* applys list2_ind P *)\n   let X := fresh \"P\" in set (X := P); applys list2_ind X; unfold X; try clear X\n end.\n\nTactic Notation \"list2_ind\" \"~\" constr(l1) constr(l2) :=\n  list2_ind l1 l2; auto_tilde.\n\nTactic Notation \"list2_ind\" \"*\" constr(l1) constr(l2) :=\n  list2_ind l1 l2; auto_star.\n\nTactic Notation \"list2_ind\" constr(E) :=\n  match type of E with length ?l1 = length ?l2 =>\n    list2_ind l1 l2; [ apply E | | ] end.\n\n(** Same, but on last element *)\n\nLemma list2_ind_last : forall A B (P:list A->list B->Prop) l1 l2,\n  length l1 = length l2 ->\n  P nil nil ->\n  (forall x1 xs1 x2 xs2,\n     length xs1 = length xs2 -> P xs1 xs2 -> P (xs1&x1) (xs2&x2)) ->\n  P l1 l2.\nProof using.\n  introv E M1 M2. gen l2. induction l1 using list_ind_last;\n   [| rename a into x1, l1 into l1']; intros;\n   destruct (last_case l2) as [|(x2&l2'&E2)]; subst; rew_list in *;\n   try solve [false; math]; auto.\nQed.\n\nTactic Notation \"list2_ind_last\" constr(l1) constr(l2) :=\n  pattern l2; pattern l1;\n  match goal with |- (fun a => (fun b => @?P a b) _) _ =>\n   (* applys list2_ind P *)\n   let X := fresh \"P\" in set (X := P); applys list2_ind_last X; unfold X; try clear X\n end.\n\nTactic Notation \"list2_ind_last\" \"~\" constr(l1) constr(l2) :=\n  list2_ind_last l1 l2; auto_tilde.\n\nTactic Notation \"list2_ind_last\" \"*\" constr(l1) constr(l2) :=\n  list2_ind_last l1 l2; auto_star.\n\nTactic Notation \"list2_ind_last\" constr(E) :=\n  match type of E with length ?l1 = length ?l2 =>\n    list2_ind_last l1 l2; [ apply E | | ] end.\n\n(* ---------------------------------------------------------------------- *)\n(* LibMultiset *)\n\nTactic Notation \"multiset_eq\" := (* --TODO: move to TLC *)\n  check_noevar_goal; LibMultiset.permut_simpl.\n\n(* ---------------------------------------------------------------------- *)\n(* LibList *)\n\nHint Rewrite fold_nil fold_cons fold_app : rew_listx.\n\nLemma list_same_length_inv_nil : forall A1 A2 (l1:list A1) (l2:list A2),\n  length l1 = length l2 ->\n  l1 = nil <-> l2 = nil.\nProof using. intros. destruct l1; destruct l2; auto_false*. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(* LibTactics, temporary for Coq < 8.11 *)\n\nLtac nrapply H :=\n  first\n  [ notypeclasses refine (H)\n  | notypeclasses refine (H _)\n  | notypeclasses refine (H _ _)\n  | notypeclasses refine (H _ _ _)\n  | notypeclasses refine (H _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _ _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _ _ _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _ _ _ _ _ _ _ _)\n  | notypeclasses refine (H _ _ _ _ _ _ _ _ _ _ _ _ _ _) ].\n\n\n\n(* ---------------------------------------------------------------------- *)\n(* LibWf *)\n\nFrom SLF (* TLC *) Require Import LibWf.\n\nLtac induction_wf_core_then IH E X cont ::=\n  let clearX tt :=\n    first [ clear X | fail 3 \"the variable on which the induction is done appears in the hypotheses\" ] in\n  first [ pattern X;\n          first [ eapply (@well_founded_ind _ E)\n                | eapply (@well_founded_ind _ (E _))\n                | eapply (@well_founded_ind _ (E _ _))\n                | eapply (@well_founded_ind _ (E _ _ _))\n                | applys well_founded_ind (wf_measure E)\n                | applys well_founded_ind E ];\n          clearX tt;\n          match goal with\n          | |- wf _ => auto with wf\n          | |- well_founded _ => change well_founded with wf; auto with wf\n          | |- _ => intros X IH; cont tt\n          end ].\n\nGlobal Arguments list_sub [A].\n\n(* 2020-03-09 15:04:14 (UTC+01) *)\n", "meta": {"author": "PKUTCS-CBS", "repo": "CBSVerifi", "sha": "2a71f58046fd77a9d13a4ab567417248eac34c43", "save_path": "github-repos/coq/PKUTCS-CBS-CBSVerifi", "path": "github-repos/coq/PKUTCS-CBS-CBSVerifi/CBSVerifi-2a71f58046fd77a9d13a4ab567417248eac34c43/TLC/TLCbuffer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7417953223192806}}
{"text": "Require Import init.\n\nRequire Export topology_base.\nRequire Export topology_order.\nRequire Export topology_order2.\nRequire Export topology_connected.\nRequire Export real.\nRequire Import rat.\nRequire Import rat_abstract.\nRequire Import order_minmax.\nRequire Import card_types.\n\nDefinition real_order_topology := order_topology (U := real).\n\n(* begin hide *)\nSection RealOrderTopology.\n\nExisting Instance real_order_topology.\n(* end hide *)\nTheorem real_open_interval : ∀ B, top_basis B → ∃ a b, B = open_interval a b.\nProof.\n    intros B B_basis.\n    destruct B_basis as [B_basis|[B_basis|B_basis]].\n    -   exact B_basis.\n    -   destruct B_basis as [a [b [B_eq b_max]]].\n        specialize (b_max (b + 1)).\n        rewrite <- nlt_le in b_max.\n        exfalso; apply b_max.\n        apply lt_plus_one.\n    -   destruct B_basis as [a [b [B_eq a_min]]].\n        specialize (a_min (a - 1)).\n        apply le_plus_rrmove in a_min.\n        rewrite neg_neg in a_min.\n        rewrite <- nlt_le in a_min.\n        exfalso; apply a_min.\n        apply lt_plus_one.\nQed.\n\nTheorem real_open_interval_eq : ∀ B, top_basis B ↔ ∃ a b, B = open_interval a b.\nProof.\n    intros B.\n    split.\n    -   apply real_open_interval.\n    -   intros B_basis.\n        left.\n        exact B_basis.\nQed.\n\nTheorem real_connected : connected real.\nProof.\n    apply complete_connected.\nQed.\n\nGlobal Instance real_hausdorff : HausdorffSpace real.\nProof.\n    split.\n    assert (∀ a b, a < b → ∃ S1 S2, open S1 ∧ open S2 ∧ S1 a ∧ S2 b\n        ∧ disjoint S1 S2) as wlog.\n    {\n        intros a b ltq.\n        exists (open_interval (a - 1) ((a + b)/2)),\n               (open_interval ((a + b)/2) (b + 1)).\n        split; [>|split; [>|split; [>|split]]].\n        -   apply open_interval_open.\n        -   apply open_interval_open.\n        -   split.\n            +   apply lt_minus_one.\n            +   apply average_leq1.\n                exact ltq.\n        -   split.\n            +   apply average_leq2.\n                exact ltq.\n            +   apply lt_plus_one.\n        -   apply empty_eq.\n            intros x [[lt1 lt2] [lt3 lt4]].\n            pose proof (trans lt2 lt3) as lt.\n            contradiction (irrefl _ lt).\n    }\n    intros a b neq.\n    destruct (trichotomy a b) as [[leq|eq]|leq]; [>|contradiction|].\n    -   exact (wlog a b leq).\n    -   specialize (wlog b a leq)\n            as [S1 [S2 [S1_open [S2_open [S1a [S2a dis]]]]]].\n        exists S2, S1.\n        repeat split; try assumption.\n        unfold disjoint.\n        rewrite inter_comm.\n        exact dis.\nQed.\n\nDefinition real_rat_basis (S : real → Prop) := ∃ a b : rat,\n    a < b ∧ S = open_interval (rat_to_abstract a) (rat_to_abstract b).\n\nTheorem real_rat_basis_countable : countable (|set_type real_rat_basis|)%card.\nProof.\n    unfold countable.\n    rewrite <- nat_mult_nat.\n    rewrite <- rat_size.\n    unfold le, mult; equiv_simpl.\n    exists (λ S, (ex_val [|S], ex_val (ex_proof [|S]))).\n    split.\n    intros A B.\n    unfold ex_val at 1 3, ex_proof.\n    destruct (ex_to_type [|A]) as [a C0]; cbn.\n    destruct (ex_to_type [|B]) as [a2 C1]; cbn.\n    rewrite_ex_val b [ab A_eq].\n    rewrite_ex_val b2 [ab2 B_eq].\n    clear C0 C1.\n    intros eq.\n    inversion eq; clear eq.\n    subst a2 b2.\n    rewrite <- B_eq in A_eq.\n    rewrite set_type_eq in A_eq.\n    exact A_eq.\nQed.\n\nTheorem real_rat_basis_open : real_rat_basis ⊆ open.\nProof.\n    intros S [a [b [ab S_eq]]]; subst S.\n    apply open_interval_open.\nQed.\n\nTheorem real_rat_basis_contains :\n    ∀ S x, open S → S x → ∃ B, real_rat_basis B ∧ B ⊆ S ∧ B x.\nProof.\n    intros S x S_open Sx.\n    rewrite <- open_all_basis in S_open.\n    specialize (S_open x Sx) as [B [B_basis [Bx B_sub]]].\n    apply real_open_interval in B_basis as [a [b B_eq]]; subst B.\n    destruct Bx as [ax xb].\n    pose proof (rat_dense_in_arch a x ax) as [a' [a'_gt a'_lt]].\n    pose proof (rat_dense_in_arch x b xb) as [b' [b'_gt b'_lt]].\n    exists (open_interval (rat_to_abstract a') (rat_to_abstract b')).\n    split; [>|split].\n    -   exists a', b'.\n        split; [>|reflexivity].\n        rewrite <- rat_to_abstract_lt.\n        exact (trans a'_lt b'_gt).\n    -   intros y [y_gt y_lt].\n        apply B_sub.\n        split.\n        +   exact (trans a'_gt y_gt).\n        +   exact (trans y_lt b'_lt).\n    -   split; assumption.\nQed.\n\nDefinition real_rat_topology := make_basis_topology\n    real_rat_basis real_rat_basis_open real_rat_basis_contains.\n\n(* begin hide *)\nEnd RealOrderTopology.\n\nSection LowerLimit.\n(* end hide *)\nProgram Instance real_lower_limit_topology : TopologyBasis real := {\n    top_basis S := ∃ a b, S = closed_open_interval a b\n}.\nNext Obligation.\n    exists (closed_open_interval x (x + 1)).\n    split.\n    -   exists x, (x + 1).\n        reflexivity.\n    -   split.\n        +   apply refl.\n        +   apply lt_plus_one.\nQed.\nNext Obligation.\n    rename H into a1, H5 into b1, H0 into a2, H3 into b2.\n    rename H1 into S1, H2 into S2.\n    exists (closed_open_interval (max a1 a2) (min b1 b2)).\n    split.\n    2: split.\n    -   exists (max a1 a2), (min b1 b2).\n        reflexivity.\n    -   split.\n        +   unfold max; case_if.\n            *   apply S2.\n            *   apply S1.\n        +   unfold min; case_if.\n            *   apply S1.\n            *   apply S2.\n    -   intros y [y_ge y_lt].\n        split; split.\n        +   exact (trans (lmax _ _) y_ge).\n        +   exact (lt_le_trans y_lt (lmin _ _)).\n        +   exact (trans (rmax _ _) y_ge).\n        +   exact (lt_le_trans y_lt (rmin _ _)).\nQed.\n\n(* begin hide *)\nEnd LowerLimit.\n\nSection KTop.\n(* end hide *)\nDefinition real_K x := ∃ n, x = /(from_nat (nat_suc n)).\n\nProgram Instance real_k_topology : TopologyBasis real := {\n    top_basis S := ∃ a b,\n        (S = open_interval a b) ∨\n        (S = (open_interval a b - real_K)%set)\n}.\nNext Obligation.\n    exists (open_interval (x - 1) (x + 1)).\n    split.\n    -   exists (x - 1), (x + 1).\n        left.\n        reflexivity.\n    -   split.\n        1: apply lt_plus_rrmove.\n        all: apply lt_plus_one.\nQed.\nNext Obligation.\n    rename H into a1, H5 into b1, H0 into a2, H3 into b2.\n    rename H6 into B1_open, H4 into B2_open.\n    rename H1 into B1x, H2 into B2x.\n    assert (open_interval a1 b1 x) as x_in1 by\n        (destruct B1_open; subst; apply B1x).\n    assert (open_interval a2 b2 x) as x_in2 by\n        (destruct B2_open; subst; apply B2x).\n    classic_case (real_K x) as [Kx|nKx].\n    -   destruct B1_open as [B1_open|contr].\n        2: {\n            rewrite contr in B1x.\n            destruct B1x; contradiction.\n        }\n        destruct B2_open as [B2_open|contr].\n        2: {\n            rewrite contr in B2x.\n            destruct B2x; contradiction.\n        }\n        subst; clear B1x B2x.\n        exists (open_interval (max a1 a2) (min b1 b2)).\n        split.\n        2: split.\n        +   exists (max a1 a2), (min b1 b2).\n            left.\n            reflexivity.\n        +   split.\n            *   unfold max; case_if.\n                --  apply x_in2.\n                --  apply x_in1.\n            *   unfold min; case_if.\n                --  apply x_in1.\n                --  apply x_in2.\n        +   intros y [y_gt y_lt].\n            split; split.\n            *   exact (le_lt_trans (lmax _ _) y_gt).\n            *   exact (lt_le_trans y_lt (lmin _ _)).\n            *   exact (le_lt_trans (rmax _ _) y_gt).\n            *   exact (lt_le_trans y_lt (rmin _ _)).\n    -   exists (open_interval (max a1 a2) (min b1 b2) - real_K)%set.\n        split.\n        2: split.\n        +   exists (max a1 a2), (min b1 b2).\n            right.\n            reflexivity.\n        +   split.\n            1: split.\n            *   unfold max; case_if.\n                --  apply x_in2.\n                --  apply x_in1.\n            *   unfold min; case_if.\n                --  apply x_in1.\n                --  apply x_in2.\n            *   exact nKx.\n        +   intros y [[y_gt y_lt] nKy].\n            assert (open_interval a1 b1 y) as y_in1.\n            {\n                split.\n                -   exact (le_lt_trans (lmax _ _) y_gt).\n                -   exact (lt_le_trans y_lt (lmin _ _)).\n            }\n            assert (open_interval a2 b2 y) as y_in2.\n            {\n                split.\n                -   exact (le_lt_trans (rmax _ _) y_gt).\n                -   exact (lt_le_trans y_lt (rmin _ _)).\n            }\n            split.\n            *   destruct B1_open; subst.\n                2: split.\n                1, 2: exact y_in1.\n                exact nKy.\n            *   destruct B2_open; subst.\n                2: split.\n                1, 2: exact y_in2.\n                exact nKy.\nQed.\n\n(* begin hide *)\nEnd KTop.\n(* end hide *)\nTheorem real_lower_limit_finer : topology_strictly_finer\n    (@basis_topology _ real_lower_limit_topology)\n    (@basis_topology _ real_order_topology).\nProof.\n    apply topology_not_finer_strict.\n    -   apply topology_basis_finer.\n        intros x B2 B2_basis B2x.\n        apply real_open_interval in B2_basis.\n        destruct B2_basis as [a [b B2_eq]].\n        subst B2.\n        exists (closed_open_interval x b).\n        split.\n        2: split.\n        +   exists x, b.\n            reflexivity.\n        +   split.\n            *   apply refl.\n            *   apply B2x.\n        +   intros y [y_gt y_lt].\n            split.\n            *   exact (lt_le_trans (land B2x) y_gt).\n            *   exact y_lt.\n    -   intros contr.\n        rewrite topology_basis_finer in contr.\n        pose (B2 := closed_open_interval 0 1).\n        assert (@top_basis real real_lower_limit_topology B2) as B2_basis.\n        {\n            exists 0, 1.\n            reflexivity.\n        }\n        assert (B2 0) as B20.\n        {\n            split.\n            -   apply refl.\n            -   exact one_pos.\n        }\n        specialize (contr 0 B2 B2_basis B20) as [B1 [B1_basis [B10 B1_sub]]].\n        apply real_open_interval in B1_basis.\n        destruct B1_basis as [a [b B1_eq]]; subst B1.\n        unfold B2 in *.\n        clear B2 B2_basis B20.\n        destruct B10 as [a_neg b_pos].\n        assert (a/2 < 0) as a2_neg.\n        {\n            apply half_neg.\n            exact a_neg.\n        }\n        assert (open_interval a b (a/2)) as a2_in.\n        {\n            split.\n            -   apply lt_mult_rcancel_pos with 2; try exact two_pos.\n                rewrite mult_rlinv by apply two_pos.\n                rewrite ldist; rewrite mult_rid.\n                rewrite <- (plus_rid a) at 3.\n                apply lt_lplus.\n                exact a_neg.\n            -   exact (trans a2_neg b_pos).\n        }\n        apply B1_sub in a2_in.\n        destruct a2_in as [a2_pos].\n        destruct (lt_le_trans a2_neg a2_pos); contradiction.\nQed.\n\nTheorem real_k_finer : topology_strictly_finer\n    (@basis_topology _ real_k_topology)\n    (@basis_topology _ real_order_topology).\nProof.\n    apply topology_not_finer_strict.\n    -   apply topology_basis_finer.\n        intros x B2 B2_basis B2x.\n        exists B2.\n        split.\n        2: split.\n        +   apply real_open_interval in B2_basis.\n            destruct B2_basis as [a [b B2_eq]]; subst B2.\n            exists a, b.\n            left.\n            reflexivity.\n        +   exact B2x.\n        +   apply refl.\n    -   intros contr.\n        rewrite topology_basis_finer in contr.\n        pose (B2 := (open_interval (-(1)) 1 - real_K)%set).\n        assert (@top_basis real real_k_topology B2) as B2_basis.\n        {\n            unfold top_basis; cbn.\n            exists (-(1)), 1.\n            right.\n            reflexivity.\n        }\n        assert (B2 0) as B20.\n        {\n            split.\n            -   split.\n                1: apply pos_neg2.\n                all: exact one_pos.\n            -   unfold real_K.\n                rewrite not_ex.\n                intros n.\n                apply real_n_div_pos.\n        }\n        specialize (contr 0 B2 B2_basis B20) as [B1 [B1_basis [B1x B1_sub]]].\n        apply real_open_interval in B1_basis.\n        destruct B1_basis as [a [b B1_eq]]; subst B1.\n        unfold B2 in B1_sub; clear B2 B2_basis B20.\n        destruct B1x as [a_neg b_pos].\n        pose proof (archimedean2 b b_pos) as [n n_ltq].\n        assert (open_interval a b (/from_nat (nat_suc n))) as n_in.\n        {\n            split.\n            -   apply (trans a_neg).\n                apply real_n_div_pos.\n            -   exact n_ltq.\n        }\n        apply B1_sub in n_in.\n        destruct n_in as [n_in1 n_in2].\n        apply n_in2.\n        exists n.\n        reflexivity.\nQed.\n\nTheorem real_lower_limit_k_incomparable : ¬topology_comparable\n    (@basis_topology _ real_lower_limit_topology)\n    (@basis_topology _ real_k_topology).\nProof.\n    intros [finer|finer].\n    -   rewrite topology_basis_finer in finer.\n        pose (B2 := (open_interval (-(1)) 1 - real_K)%set).\n        assert (@top_basis real real_k_topology B2) as B2_basis.\n        {\n            unfold top_basis; cbn.\n            exists (-(1)), 1.\n            right.\n            reflexivity.\n        }\n        assert (B2 0) as B20.\n        {\n            split.\n            -   split.\n                1: apply pos_neg2.\n                all: exact one_pos.\n            -   unfold real_K.\n                rewrite not_ex.\n                intros n.\n                apply real_n_div_pos.\n        }\n        specialize (finer 0 B2 B2_basis B20) as [B1 [B1_basis [B1x B1_sub]]].\n        destruct B1_basis as [a [b B1_eq]]; subst B1.\n        unfold B2 in B1_sub; clear B2 B2_basis B20.\n        destruct B1x as [a_neg b_pos].\n        pose proof (archimedean2 b b_pos) as [n n_ltq].\n        assert (closed_open_interval a b (/from_nat (nat_suc n))) as n_in.\n        {\n            split.\n            -   apply (trans a_neg).\n                apply real_n_div_pos.\n            -   exact n_ltq.\n        }\n        apply B1_sub in n_in.\n        destruct n_in as [n_in1 n_in2].\n        apply n_in2.\n        exists n.\n        reflexivity.\n    -   rewrite topology_basis_finer in finer.\n        pose (B2 := closed_open_interval 0 1).\n        assert (@top_basis real real_lower_limit_topology B2) as B2_basis.\n        {\n            exists 0, 1.\n            reflexivity.\n        }\n        assert (B2 0) as B20.\n        {\n            split.\n            -   apply refl.\n            -   exact one_pos.\n        }\n        specialize (finer 0 B2 B2_basis B20) as [B1 [B1_basis [B10 B1_sub]]].\n        destruct B1_basis as [a [b B1_eq]].\n        assert (open_interval a b 0) as B10'.\n        {\n            destruct B1_eq; subst B1.\n            -   exact B10.\n            -   apply B10.\n        }\n        unfold B2 in *.\n        clear B2 B2_basis B20 B10.\n        destruct B10' as [a_neg b_pos].\n        classic_case (real_K (a/2)) as [Ka|nKa].\n        +   destruct Ka as [n n_eq].\n            assert (0 < a) as a_pos.\n            {\n                apply lt_mult_rcancel_pos with (/2).\n                1: apply div_pos; exact two_pos.\n                rewrite mult_lanni.\n                rewrite n_eq.\n                apply real_n_div_pos.\n            }\n            destruct (trans a_neg a_pos); contradiction.\n        +   assert (a/2 < 0) as a2_neg.\n            {\n                apply half_neg.\n                exact a_neg.\n            }\n            assert (open_interval a b (a/2)) as a2_in'.\n            {\n                split.\n                -   apply lt_mult_rcancel_pos with 2; try exact two_pos.\n                    rewrite mult_rlinv by apply two_pos.\n                    rewrite ldist; rewrite mult_rid.\n                    rewrite <- (plus_rid a) at 3.\n                    apply lt_lplus.\n                    exact a_neg.\n                -   exact (trans a2_neg b_pos).\n            }\n            assert (B1 (a/2)) as a2_in.\n            {\n                destruct B1_eq; subst B1.\n                2: split.\n                1, 2: exact a2_in'.\n                exact nKa.\n            }\n            apply B1_sub in a2_in.\n            destruct a2_in as [a2_pos].\n            destruct (lt_le_trans a2_neg a2_pos); contradiction.\nQed.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Topology/topology_real.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7417953121065425}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) : natural :=\n  plus Zero (mult y lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj52_coqofml_uSMa7i.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.741785755704187}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus x (plus lf1 y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj205_coqofml_Qv70GV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7417857556535452}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import cl.\n\nSet Implicit Arguments.\n\nSection cl_equivalence.\n\n  (* Now the definition of equivalence between the terms\n     of combinatory algebras. It is the least equivalence\n     relation (reflexive, symmetry and transitive) which\n     is congruent with composition o and such that\n       I o x ~~ x, K o x o y ~~ x and \n       S o x o y o z ~~ x o z o (y o z)\n  *)\n\n  Reserved Notation \"x '~cl' y\" (at level 70).\n\n  Inductive cl_eq : clterm -> clterm -> Prop :=\n  \n    | in_cl_eq_I : forall x,               I o x ~cl x \n    \n    | in_cl_eq_K : forall x y,         K o x o y ~cl x\n    \n    | in_cl_eq_S : forall x y z,   S o x o y o z ~cl x o z o (y o z)\n\n    | in_cl_eq_0 : forall x,                   x ~cl x\n    \n    | in_cl_eq_1 : forall x y,                 x ~cl y \n                              ->               y ~cl x\n                             \n    | in_cl_eq_2 : forall x y z,               x ~cl y \n                              ->               y ~cl z \n                              ->               x ~cl z\n                              \n    | in_cl_eq_3 : forall x y z,           x     ~cl y \n                              ->           x o z ~cl y o z\n                              \n    | in_cl_eq_4 : forall x y z,               y ~cl     z \n                              ->           x o y ~cl x o z\n                                \n  where \"x ~cl y\" := (cl_eq x y).\n  \n  (* Some exercices with cl_term equivalence *)\n  \n  Fact cl_eq_refl f g : f = g -> f ~cl g.\n  Proof.\n  Admitted.\n  \n  Definition cl_eq_sym := in_cl_eq_1.\n\n  Definition cl_eq_trans := in_cl_eq_2.\n  \n  Fact cl_eq_app x y a b : x ~cl y -> a ~cl b -> x o a ~cl y o b.\n  Proof.\n  Admitted.\n  \n  Fact cl_I_prop x : I o x ~cl x.\n  Proof.\n    apply in_cl_eq_I.\n  Qed.\n  \n  Fact cl_K_prop x y : K o x o y ~cl x.\n  Proof.\n    apply in_cl_eq_K.\n  Qed.\n  \n  Fact cl_S_prop x y z : S o x o y o z ~cl x o z o (y o z).\n  Proof.\n    apply in_cl_eq_S.\n  Qed. \n  \n  Fact cl_SKI_prop x : S o K o I o x ~cl x.\n  Proof.\n    apply cl_eq_trans with (1 := cl_S_prop _ _ _).\n  Admitted.\n  \n  Corollary cl_SKI_I : forall x, S o K o I o x ~cl I o x.\n  Proof.\n  Admitted.\n\n  Definition cl_D := S o I o I.\n  \n  Notation D := cl_D.\n  \n  Fact cl_D_prop x : D o x ~cl x o x.\n  Proof.\n  Admitted.\n  \n  Definition cl_B := S o (K o S) o K.\n  \n  Notation B := cl_B.\n  \n  Hint Resolve in_cl_eq_0.\n  \n  Fact cl_B_prop f g x : B o f o g o x ~cl f o (g o x).\n  Proof.\n    unfold cl_B.\n    apply cl_eq_trans with (K  o S o f o (K o f) o g o x).\n    do 2 (apply cl_eq_app; auto); apply cl_S_prop.\n    apply cl_eq_trans with (S o (K o f) o g o x).\n    do 3 (apply cl_eq_app; auto); apply cl_K_prop.\n    apply cl_eq_trans with (1 := cl_S_prop _ _ _).\n    apply cl_eq_app; auto.\n    apply cl_K_prop.\n  Qed.\n  \n  Definition cl_L := D o (B o D o D).\n  \n  Notation L := cl_L.\n  \n  Fact cl_L_prop : L ~cl L o L.\n  Proof.\n  Admitted.\n  \nEnd cl_equivalence.\n\nNotation \"x '~cl' y\" := (cl_eq x y) (at level 70).", "meta": {"author": "DmxLarchey", "repo": "Combinatory-Logic-for-students", "sha": "0bceaae5f102ce59b3f6bc872beaf728f371ba59", "save_path": "github-repos/coq/DmxLarchey-Combinatory-Logic-for-students", "path": "github-repos/coq/DmxLarchey-Combinatory-Logic-for-students/Combinatory-Logic-for-students-0bceaae5f102ce59b3f6bc872beaf728f371ba59/cl_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7417257127089864}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import vds_sort.\nRequire Import Coq.Sorting.Permutation.\n\nSection Define.\n\n  Inductive color : Type := Red | Black.\n\n  Inductive tree : Type :=\n  | E : tree\n  | T : color -> tree -> nat -> tree -> tree.\n\n  Definition empty := E.\n\n  Fixpoint flatten t :=\n    match t with\n    | E => [::]\n    | T _ l v r => flatten l ++ (v :: flatten r)\n    end.\n  \nEnd Define.\n\nSection Query.\n\n  Fixpoint member (n : nat)  (t : tree) : bool :=\n    match t with\n    | E => false\n    | T _ l v r => if n < v\n                   then member n l\n                   else if n == v then true\n                        else member n r\n    end.\n\n  Lemma member_in t n : member n t -> n \\in (flatten t).\n  Proof.\n    elim: t => [|c l IHl v r IHr] //=.\n    case: ifP => Hlt.\n    move => H. rewrite mem_cat IHl. by rewrite orTb. exact.\n    case: ifP => Heq. move => H {H}.\n    by rewrite mem_cat in_cons Heq //= orbT.\n    move => H. rewrite mem_cat in_cons IHr. by rewrite orbA orbT. exact.\n  Qed.\n  \n  Fixpoint height t : nat :=\n    match t with\n    | E => 0\n    | T _ l _ r => 1 + max (height l) (height r)\n    end.\n\n  Fixpoint tree_size t : nat :=\n    match t with\n    | E => 0\n    | T _ l _ r => 1 + tree_size l + tree_size r\n    end.\n\n  Lemma tree_sizeK t : tree_size t = size (flatten t).\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=.\n    rewrite size_cat //= IHl IHr. rewrite -[in RHS]addn1.\n    by rewrite addnA -[in LHS]addnA [in LHS]addnC.\n  Qed.\n\nEnd Query.\n\n(* tactic written by Jacques Garrigue *)\nLtac decompose_rewrite :=\n  let H := fresh \"H\" in\n  move/andP=>[] || (move=>H; try rewrite H; try rewrite (eqP H)).\n\nSection Insert.\n\n  Definition balanceL c l v r :=\n    match c, l with\n    | Black, T Red (T Red a x b) y c\n    | Black, T Red a x (T Red b y c)\n      => T Red (T Black a x b) y (T Black c v r)\n    | _, _ => T c l v r\n    end.\n\n  Definition balanceR c l v r :=\n    match c, r with\n    | Black, T Red (T Red b y c) z d\n    | Black, T Red b y (T Red c z d)\n      => T Red (T Black l v b) y (T Black c z d)\n    | _, _ => T c l v r\n    end.\n\n  Fixpoint ins x t :=\n    match t with\n    | E => T Red E x E\n    | T c l v r as s =>\n      if x < v\n      then balanceL c (ins x l) v r\n      else if x > v\n           then balanceR c l v (ins x r)\n           else s\n    end.\n\n  Definition insert x t :=\n    match ins x t with\n    | E => E (* impossible *)\n    | T _ l v r => T Black l v r\n    end.\n\n  Fixpoint is_redblack (t : tree) ctxt bh :=\n    match t with\n    | E => bh == 0\n    | T c l _ r =>\n      match c, ctxt with\n      | Red, Red => false (* red child can't have red parent *)\n      | Red, Black => is_redblack l Red bh && is_redblack r Red bh\n      | Black, _ => (bh > 0) && is_redblack l Black (bh.-1) && is_redblack r Black (bh.-1)\n      end\n    end.\n\n  Definition nearly_redblack (t : tree) bh :=\n    match t with\n    | T Red l _ r => is_redblack l Black bh && is_redblack r Black bh\n    | _ => is_redblack t Black bh\n    end.\n\n  Lemma is_redblack_red_black t n : is_redblack t Red n -> is_redblack t Black n.\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=. case: c => //=.\n  Qed.\n\n  Lemma is_redblack_nearly_redblack c t n : is_redblack t c n -> \n                                            nearly_redblack t n.\n  Proof.\n    case: c; elim: t => [| tc l IHl v r IHr] //=; case: tc => //=.\n    move/andP => [Hl Hr]. by rewrite !is_redblack_red_black.\n  Qed.\n\n  Lemma balanceL_black_is_redblack l r v n :\n    nearly_redblack l n -> is_redblack r Black n ->\n    is_redblack (balanceL Black l v r) Black n.+1.\n  Proof.\n    case: l => [| [] [| [] lll llval llr] lval [| [] lrl lrval lrr]] //=;\n    repeat decompose_rewrite => //=;\n    try (by rewrite !is_redblack_red_black).\n    move/eqP in H1. by rewrite -!H1 !is_redblack_red_black.\n  Qed.\n\n  Lemma balanceR_black_is_redblack l r v n :\n    is_redblack l Black n -> nearly_redblack r n ->\n    is_redblack (balanceR Black l v r) Black n.+1.\n  Proof.\n    case: r => [| [] [| [] rll rlval rlr] rval [| [] rrl rrval rrr]] //=;\n    repeat decompose_rewrite => //=;\n    try (by rewrite !is_redblack_red_black).\n    move/eqP in H2. by rewrite -!H2 !is_redblack_red_black.\n  Qed.\n     \n  Lemma ins_is_redblack (t : tree) x n :\n    (is_redblack t Black n -> nearly_redblack (ins x t) n) /\\\n    (is_redblack t Red n -> is_redblack (ins x t) Black n).\n  Proof.\n    elim: t n => [| c l IHl v r IHr] n //.\n    rewrite //=. split => -> //.\n    have ins_black: (is_redblack (T Black l v r) Black n -> is_redblack (ins x (T Black l v r)) Black n).\n    { rewrite {3}[Black]lock /= -lock => /andP [/andP [/prednK <- Hl] Hr].\n      case: ifP => _. \n      rewrite balanceL_black_is_redblack //; by apply IHl.\n      case: ifP => _. rewrite balanceR_black_is_redblack //; by apply IHr.\n      rewrite //=. rewrite succnK in Hl. rewrite succnK in Hr. by rewrite Hl Hr. }\n    split; case: c => //.\n    specialize IHl with n. specialize IHr with n.\n    move: IHl => [IHl_b IHl_r]. move: IHr => [IHr_b IHr_r].\n    move=> /= /andP [Hl Hr] //=.\n    case: ifP => _ //=. rewrite IHl_r. by rewrite is_redblack_red_black. exact.\n    case: ifP => _ //=. rewrite IHr_r. by rewrite is_redblack_red_black. exact.\n    rewrite !is_redblack_red_black; exact.\n    move/ins_black => H. by apply: (is_redblack_nearly_redblack Black).\n  Qed.\n    \n  Lemma insert_is_redblack (t : tree) x n :\n    is_redblack t Red n -> exists n', is_redblack (insert x t) Red n'.\n  Proof.\n    exists (if (ins x t) is T Red _ _ _ then n.+1 else n).\n    move/(proj2 (ins_is_redblack t x n)): H.\n    rewrite /insert => //=. destruct ins => //=.\n    case: c => //= /andP [Hd1 Hd2].\n    by rewrite !is_redblack_red_black.\n  Qed.\n\nEnd Insert.\n\nSection BST.\n\n  Definition is_bst t := sorted (flatten t).\n  \n  Lemma empty_is_bst : is_bst empty.\n  Proof. exact. Qed.\n\n  Fixpoint tree_all (pred : nat -> bool) t :=\n    match t with\n    | E => true\n    | T _ l v r => pred v && tree_all pred l && tree_all pred r\n    end.\n\n  Lemma tree_allK pred t : tree_all pred t = all pred (flatten t).\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=.\n    by rewrite all_cat //= IHl IHr andbCA andbA.\n  Qed.\n  \n  Fixpoint is_bst_rec (t : tree) :=\n    match t with\n    | E => true\n    | T _ l v r => is_bst_rec l && is_bst_rec r && tree_all (leq^~ v) l &&\n                   tree_all [eta leq v] r\n    end.\n                   \n  Lemma is_bst_is_bst_rec : is_bst =1 is_bst_rec.\n  Proof.\n    rewrite /eqfun. move => t. elim: t => [| c l IHl v r IHr] //=.\n    rewrite -IHl -IHr /is_bst /= -sorted_cat_cons_e.\n    rewrite -sorted_cons_e. rewrite !tree_allK. rewrite -!andbA.\n    case: (all (leq^~ v) (flatten l)) => //=. by rewrite !andbF.\n  Qed.\n\n  Lemma balanceLK c l v r : flatten (balanceL c l v r) = flatten l ++ v :: flatten r.\n  Proof.\n    rewrite /balanceL; case c => //=; \n    case: l => [| [] [| [] lll llval llr] lval [| [] lrl lrval lrr]] //=;\n    try rewrite -!cat_cons; try rewrite !catA; try exact. \n    by rewrite -!catA cat_cons.\n  Qed.\n\n  Lemma balanceRK c l v r : flatten (balanceR c l v r) = flatten l ++ v :: flatten r.\n  Proof.\n    rewrite /balanceR; case c => //=; \n    case: r => [| [] [| [] rll rlval rlr] rval [| [] rrl rrval rrr]] //=;\n    try rewrite -!cat_cons; try rewrite !catA; try exact. \n    by rewrite -!catA cat_cons.\n  Qed.\n      \n  Lemma insK x (t : tree) : is_bst t -> flatten (ins x t) = seq_insert x (flatten t).\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=. move => H.\n    case Hlt: (x < v). rewrite balanceLK insert_cat_cons_l. rewrite IHl //=.\n    rewrite is_bst_is_bst_rec. rewrite is_bst_is_bst_rec /= -!andbA in H.\n    by move/and4P: H => [-> _ _ _]. by rewrite /is_bst in H.\n    by rewrite Hlt.\n    rewrite ltnNge leq_eqVlt Hlt orbF. case Heq: (x == v) => //=.\n    by rewrite (eqP Heq) insert_same.\n    rewrite balanceRK insert_cat_cons_r. rewrite IHr //=.\n    rewrite is_bst_is_bst_rec. rewrite is_bst_is_bst_rec /= -!andbA in H.\n    by move/and4P: H => [_ -> _ _]. by rewrite /is_bst in H.\n    by rewrite ltnNge leq_eqVlt Hlt Heq.   \n  Qed.\n\n  Lemma insertK x (t : tree) : is_bst t -> flatten (insert x t) = seq_insert x (flatten t).\n  Proof.\n    move => H. rewrite /insert -insK. by case: ins. exact.\n  Qed.\n\n  Lemma insert_is_bst x t : is_bst t -> is_bst (insert x t).\n  Proof.\n    move => H. rewrite /is_bst. rewrite insertK. apply: sorted_insert.\n    by rewrite /is_bst in H. exact.\n  Qed.  \n  \n  Lemma tree_all_geq_trans t x y : tree_all (geq^~ x) t -> y <= x -> tree_all (geq^~ y) t.\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=. rewrite -andbA.\n    move/and3P => [Hxv Hl Hr] Hyx. rewrite IHl; try (rewrite IHr); try exact.\n    rewrite !andbT. apply: leq_trans. apply: Hyx. apply: Hxv.\n  Qed.\n\n  Lemma tree_all_leq_trans t x y : tree_all (leq^~ x) t -> x <= y -> tree_all (leq^~ y) t.\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=. rewrite -andbA.\n    move/and3P => [Hvx Hl Hr] Hxy. rewrite IHl; try (rewrite IHr); try exact.\n    rewrite !andbT. apply: leq_trans. apply: Hvx. apply: Hxy.\n  Qed.\n    \n  Lemma balanceL_is_bst c l r x : is_bst_rec l -> is_bst_rec r -> tree_all (leq^~ x) l -> tree_all (geq^~ x) r -> is_bst_rec (balanceL c l x r).\n  Proof.\n    rewrite /balanceL. case: c => //=; case: l => [| [] [| [] lll llval llr] lval [| [] lrl lrval lrr]] //=; repeat decompose_rewrite; try exact.\n    by rewrite (@tree_all_geq_trans r x lrval).\n    by rewrite (@tree_all_geq_trans r x lval).\n    by rewrite (@tree_all_geq_trans r x lval).\n    by rewrite (@tree_all_geq_trans r x lval).\n    rewrite (@tree_all_leq_trans lll llval lrval).\n    rewrite (@tree_all_leq_trans llr lval lrval) //=.\n    rewrite (@tree_all_geq_trans r x lrval) //= !andbT.\n    all: (try apply: leq_trans; try apply: H7; try apply: H10; try exact). \n  Qed.\n\n  Lemma balanceR_is_bst c l r x : is_bst_rec l -> is_bst_rec r -> tree_all (leq^~ x) l -> tree_all (geq^~ x) r -> is_bst_rec (balanceR c l x r).\n  Proof.\n    rewrite /balanceR. case: c => //=; case: r => [| [] [| [] rll rlval rlr] rval [| [] rrl rrval rrr]] //=; repeat decompose_rewrite; try exact.\n    by rewrite (@tree_all_leq_trans l x rval).\n    by rewrite (@tree_all_leq_trans l x rlval).\n    rewrite (@tree_all_leq_trans l x rlval).\n    rewrite (@tree_all_geq_trans rrl rval rlval).\n    rewrite (@tree_all_geq_trans rrr rval rlval) //=. rewrite !andbT.\n    apply: leq_trans. apply: H8. apply: H11. all: try exact.\n    rewrite (@tree_all_leq_trans l x rlval).\n    rewrite (@tree_all_geq_trans rrl rval rlval).\n    rewrite (@tree_all_geq_trans rrr rval rlval) //= !andbT.\n    apply: leq_trans. apply: H8. apply: H11. all: try exact.\n    by rewrite (@tree_all_leq_trans l x rval).\n  Qed.\n\n  Lemma tree_all_balanceL pred c l r v : tree_all pred l && tree_all pred r &&\n    pred v = tree_all pred (balanceL c l v r).\n  Proof.\n    rewrite /balanceL. case: c => //=; case: l => [| [] [| [] lll llval llr] lval [| [] lrl lrval lrr]] //=;\n    repeat decompose_rewrite; try (rewrite !andbT); try (rewrite andbC);\n    try (rewrite -!andbA); try exact;\n    case: (pred v) => //=; try (by rewrite !andbF). by rewrite andbCA.\n    case: (pred lval) => //=; case: (pred lrval) => //=; case: (pred llval) => //=.\n    by rewrite !andbF.\n  Qed.\n\n  Lemma tree_all_balanceR pred c l r v : tree_all pred l && tree_all pred r &&\n    pred v = tree_all pred (balanceR c l v r).\n  Proof.\n    rewrite /balanceR. case: c => //=; case: r => [| [] [| [] rll rlval rlr] rval [| [] rrl rrval rrr]] //=; repeat decompose_rewrite;\n    try (rewrite !andbT); try (rewrite andbC);\n    try (rewrite -!andbA); try exact; case: (pred v) => //=; \n    try (case: (pred rval) => //=; case: (pred rlval) => //=); \n    try (by rewrite !andbF).\n    by rewrite andbCA.\n  Qed.\n    \n  Lemma tree_all_ins pred t x : tree_all pred t && pred x = tree_all pred (ins x t).\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=. by rewrite !andbT.\n    case: ifP => H; try (case: ifP => H'); try (rewrite -tree_all_balanceL -IHl);\n    try (rewrite -tree_all_balanceR -IHr);\n    case pv: (pred v) => //=; case px: (pred x) => //=; try (by rewrite !andbT); try (by rewrite !andbF).\n    by rewrite pv andbT.\n    have He: (v == x). apply: negbNE. by rewrite neq_ltn H H'.\n    by rewrite -(eqP He) pv in px.\n    by rewrite pv. by rewrite pv. \n  Qed.\n    \n  Lemma ins_is_bst (t : tree) x : is_bst_rec t -> is_bst_rec (ins x t).\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=.\n    rewrite -!andbA. move/and4P => [Hl Hr Hleq Hgeq].\n    case: ifP => Hlt.\n    apply: balanceL_is_bst; try exact. by apply: IHl.\n    by rewrite -tree_all_ins Hleq //= leq_eqVlt Hlt orbT.\n    case: ifP => Hlt'. apply: balanceR_is_bst; try exact. by apply: IHr.\n    rewrite -tree_all_ins. rewrite ltnNge in Hlt. move/negbFE in Hlt.\n    by rewrite /geq //= Hlt Hgeq.\n    by rewrite //= Hl Hr Hleq Hgeq.\n  Qed.\n\n  Lemma insert_is_bst_rec (t : tree) x : is_bst_rec t -> is_bst_rec (insert x t).\n  Proof.\n    move/(ins_is_bst t x). rewrite /insert => //=.\n    destruct ins => //=.\n  Qed.\n  \nEnd BST.\n\nSection Membership.\n\n  Lemma all_gt_not_in x s : all [eta ltn x] s -> x \\notin s.\n  Proof.\n    elim: s => [| h s IHs] //=. move/andP => [Hltn Hs].\n    rewrite in_cons negb_or. rewrite IHs. by rewrite neq_ltn Hltn. \n    exact.\n  Qed.\n  \n  Lemma all_geq_gt_trans x y s : all [eta leq y] s -> x < y -> all [eta ltn x] s.\n  Proof.\n    elim: s => [| h s IHs] //=. move => /andP [Hyh Hy] Hxy.\n    rewrite IHs. rewrite andbT. apply: leq_trans. apply: Hxy. apply: Hyh. exact.\n    exact.\n  Qed.\n\n  Lemma all_lt_not_in x s : all (ltn^~ x) s -> x \\notin s.\n  Proof.\n    elim: s => [| h s IHs] //=. move/andP => [Hltn Hs].\n    rewrite in_cons negb_or. rewrite IHs. by rewrite neq_ltn Hltn orbT. \n    exact.\n  Qed.\n\n  Lemma all_leq_lt_trans x y s : all (leq^~ x) s -> x < y -> all (ltn^~ y) s.\n  Proof.\n    elim: s => [| h s IHs] //=. move => /andP [Hyh Hy] Hxy.\n    rewrite IHs. rewrite andbT. apply: leq_ltn_trans. apply: Hyh. apply: Hxy.\n    exact. exact.\n  Qed.\n  \n  Lemma memberK x t : (is_bst_rec t) -> member x t = (x \\in (flatten t)).\n  Proof.\n    elim: t => [| c l IHl v r IHr] //=.\n    rewrite -!andbA. move/and4P => [Hl Hr Hleq Hgeq].\n    case: ifP => x_lt_v. rewrite mem_cat IHl.\n    have not_r: member x r = false. \n    { apply/negbTE. rewrite tree_allK in Hgeq. rewrite IHr.\n      apply: all_gt_not_in. apply: all_geq_gt_trans. apply: Hgeq. exact.\n      exact. }\n    rewrite in_cons. rewrite -IHr. rewrite not_r orbF.\n    have neq_xv: (x == v) = false. apply/negbTE. by rewrite neq_ltn x_lt_v.\n    by rewrite neq_xv orbF. exact. exact.\n    case: ifP => Heq_xv. by rewrite mem_cat in_cons Heq_xv orbC.  \n    rewrite mem_cat IHr.\n    have not_l: member x l = false.\n    { apply/negbTE. rewrite tree_allK in Hleq. rewrite IHl.\n      apply: all_lt_not_in. apply: all_leq_lt_trans. apply: Hleq.\n      rewrite ltn_neqAle. by rewrite eq_sym negbT //= leqNgt x_lt_v. exact. }\n    rewrite in_cons. rewrite -IHl. by rewrite not_l //= Heq_xv.\n    exact. exact.\n  Qed.\n\nEnd Membership.\n\nSection TreeSort.\n  \n  Fixpoint build_tree s :=\n    match s with\n    | [::] => E\n    | h :: t => insert h (build_tree t)\n    end.\n\n  Definition tree_sort s := flatten (build_tree s).\n\n  Lemma bst_sorted (t : tree) : is_bst_rec t = sorted (flatten t).\n  Proof. by rewrite -is_bst_is_bst_rec /is_bst. Qed.\n\n  Lemma tree_sort_sorted s : sorted (tree_sort s).\n  Proof.\n    rewrite /tree_sort. rewrite -bst_sorted.\n    elim: s => [| h s IHs] //=. by apply: insert_is_bst_rec.\n  Qed.\n\nEnd TreeSort.", "meta": {"author": "xuanruiqi", "repo": "verified-data-structures", "sha": "f9aacf46e9f7a8a6a9574c9546bc23ef4e7ab21a", "save_path": "github-repos/coq/xuanruiqi-verified-data-structures", "path": "github-repos/coq/xuanruiqi-verified-data-structures/verified-data-structures-f9aacf46e9f7a8a6a9574c9546bc23ef4e7ab21a/red_black.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912849, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7417257034062084}}
{"text": "(* Definition and basic facts about distributive lattices. *)\nStructure Lattice :={\n  lt_carrier :> Type;\n  lt_and : lt_carrier -> lt_carrier -> lt_carrier;\n  lt_or : lt_carrier -> lt_carrier -> lt_carrier;\n  lt_zero : lt_carrier;\n  lt_one : lt_carrier;\n  lt_and_commute : forall x y, lt_and x y = lt_and y x;\n  lt_or_commute : forall x y, lt_or x y = lt_or y x;\n  lt_and_associate : forall x y z, lt_and x (lt_and y z) = lt_and (lt_and x y) z;\n  lt_or_associate : forall x y z, lt_or x (lt_or y z) = lt_or (lt_or x y) z;\n  lt_or_absorb : forall x y, lt_or x (lt_and x y) = x;\n  lt_and_absorb : forall x y, lt_and x (lt_or x y) = x;\n  lt_zero_identity_r : forall x, lt_or x lt_zero = x;\n  lt_one_identity_r : forall x, lt_and x lt_one = x;\n  lt_distribute_or : forall x y z, lt_or x (lt_and y z) = lt_and (lt_or x y) (lt_or x z);\n  lt_distribute_and : forall x y z, lt_and x (lt_or y z) = lt_or (lt_and x y) (lt_and x z)\n}.\n\nHint Resolve lt_and_commute : lt_hints.\nHint Resolve lt_or_commute : lt_hints.\nHint Resolve lt_and_associate : lt_hints.\nHint Resolve lt_or_associate : lt_hints.\nHint Resolve lt_or_absorb : lt_hints.\nHint Resolve lt_and_absorb : lt_hints.\nHint Resolve lt_zero_identity_r : lt_hints.\nHint Resolve lt_one_identity_r : lt_hints.\nHint Resolve lt_distribute_or : lt_hints.\nHint Resolve lt_distribute_and : lt_hints.\n\nNotation \"p && q\" := (lt_and _ p q) (at level 40, left associativity).\nNotation \"p || q\" := (lt_or _ p q) (at level 50, left associativity).\nNotation \"1\" := (lt_one _).\nNotation \"0\" := (lt_zero _).\n\nStructure LatticeHom (A B : Lattice) :=\n  {\n    lt_hom :> A -> B ;\n    lt_hom_and : forall x y , lt_hom (x && y) = lt_hom x && lt_hom y;\n    lt_hom_or : forall x y , lt_hom (x || y) = lt_hom x || lt_hom y;\n    lt_hom_zero : lt_hom 0 = 0;\n    lt_hom_one : lt_hom 1 = 1\n  }.\n\nDefinition lt_id {A : Lattice}: LatticeHom A A.\nProof.\n  refine {| lt_hom := fun x => x |} ; reflexivity.\nDefined.\n\nDefinition lt_comp {A B C:Lattice}: LatticeHom B C -> LatticeHom A B -> LatticeHom A C.\nProof.\n  intros g f.\n  refine {| lt_hom := fun x => g (f x) |}.\n  - intros. rewrite lt_hom_and. rewrite lt_hom_and. reflexivity.\n  - intros; repeat (rewrite lt_hom_or). reflexivity.\n  - intros. repeat (rewrite lt_hom_zero). reflexivity.\n  - intros. repeat (rewrite lt_hom_one). reflexivity.\nDefined.\n\nNotation \"g 'o' f\" := (lt_comp g f) (at level 65, left associativity).\n\nLemma lt_id_left (A B : Lattice) (f : LatticeHom A B) (x: A): (lt_id o f) x  = f x.\nProof.\n  reflexivity.\nQed.\n\nLemma comp_assoc\n      (A B C D : Lattice)\n      (f : LatticeHom A B)\n      (g : LatticeHom B C) (h : LatticeHom C D) (x : A) :\n  (h o (g o f)) x = ((h o g) o f) x.\nProof.\n  reflexivity.\nQed.\n", "meta": {"author": "mmaleki", "repo": "LogicalDifferentiation", "sha": "2a46afc6ae55680fb4416dadbe295c0b617bc4f4", "save_path": "github-repos/coq/mmaleki-LogicalDifferentiation", "path": "github-repos/coq/mmaleki-LogicalDifferentiation/LogicalDifferentiation-2a46afc6ae55680fb4416dadbe295c0b617bc4f4/Lattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7417169471675238}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nRequire Import Wf_nat Recdef.\n\nCheck lt_wf : well_founded lt.\n\n(* 自己確認(ここから) *)\nCheck well_founded lt : Prop.\nPrint well_founded.\n(*\nwell_founded = \n  fun (A : Type) (R : A -> A -> Prop) =>\n    forall a : A, Acc R a\n  : forall A : Type, (A -> A -> Prop) -> Prop\n*)\nPrint Acc.\n(*\nInductive Acc (A : Type) (R : A -> A -> Prop) (x : A) : Prop :=\n    Acc_intro : (forall y : A, R y x -> Acc R y) -> Acc R x\n*)\nCheck lt : nat -> nat -> Prop.\n(* 自己確認(ここまで) *)\n\nCheck lt_wf_ind :\n        forall (n : nat) (P : nat -> Prop),\n          (forall n0 : nat, (forall m : nat, (m < n0)%coq_nat -> P m) -> P n0) ->\n          P n. (* 不等号の定義がスタンダードCoqとMathCompで違うということを覚えておく *)\n\nCheck leP. (* <= *)\nCheck ltP. (* < congr (_ + _). *)\n\nFunction gcd (m n : nat) {wf lt m} : nat :=\n  if m is 0\n  then n\n  else gcd (modn n m) m.\nProof.\n  - move=> m n m0 _. apply/ltP.\n      by rewrite ltn_mod.\n  - exact: lt_wf.\n  Restart.\n  (* 自己確認(ここから) *)\n  - (* 本題の証明 *)\n    move=> m n n0 Hm.\n    Check ltP. (* : reflect (?m < ?n)%coq_nat (?m < ?n) *)\n    apply/ltP.\n    Check ltn_mod : forall m d : nat, (m %% d < d) = (0 < d).\n    rewrite ltn_mod.\n    Check ltn0Sn : forall n : nat, 0 < n.+1.\n    by apply: ltn0Sn.\n  - (* well_founded lt の証明 *)\n    by apply: lt_wf.\n  (* 自己確認(ここまで) *)\nQed.\n\nCheck gcd_equation :\n  forall m n : nat,\n    gcd m n = match m with\n              | 0 => n\n              | _.+1 => gcd (n %% m) m\n              end.\n\nCheck gcd_ind :\n        forall P : nat -> nat -> nat -> Prop,\n          (forall m n : nat, m = 0 -> P 0 n n) ->\n          (forall m n _x : nat,\n             m = _x ->\n             match _x with\n             | 0    => False\n             | _.+1 => True\n             end ->\n             P (n %% m) m (gcd (n %% m) m) ->\n             P _x n (gcd (n %% m) m)) ->\n          forall m n : nat, P m n (gcd m n).\n\nPrint gcd_terminate.\n(*\n  とても理解できる代物じゃない。\n*)\n\nRequire Import Extraction.\n\nExtraction gcd.                             (* wf が消える*)\n(*\nFetching opaque proofs from disk for mathcomp.ssreflect.ssrnat\nFetching opaque proofs from disk for Coq.ssr.ssrbool\nThe extraction is currently set to bypass opacity, the following opaque constant bodies have\nbeen accessed : eqnP iffP idP.\n [extraction-opaque-accessed,extraction]\n(** val gcd : nat -> nat -> nat **)\n\nlet rec gcd m n =\n  match m with\n  | O -> n\n  | S n0 -> gcd (modn n (S n0)) (S n0)\n*)\n\nCheck divn_eq :\n        forall m d : nat,\n          m = m %/ d * d + m %% d.\n\nTheorem gcd_divides m n :\n  (gcd m n %| m) && (gcd m n %| n).\nProof.\n  functional induction (gcd m n).\n  - (* m = 0 の場合 *)\n    by rewrite dvdn0 dvdnn.\n  - (* m = _.+1 の場合 *)\n    move: IHn0 => /andP [H1 H2].\n    apply/andP; split.\n    + (* gcd (n %% m) m %| m の証明 *)\n      by apply: H2.\n    + (* gcd (n %% m) m %| n の証明 *)\n      Check divn_eq n m : n = n %/ m * m + n %% m.\n      rewrite {2}(divn_eq n m).\n      Check dvdn_add : forall d m n : nat, d %| m -> d %| n -> d %| m + n.\n      apply: dvdn_add; last done.\n      Check dvdn_mull : forall d m n : nat, d %| n -> d %| m * n.\n      by apply: dvdn_mull.\nQed.\n\nCheck addKn :\n        forall n : nat,\n          cancel (addn n) (subn^~ n).\n\nCheck gcd_equation :\n        forall m n : nat,\n          gcd m n = match m with\n                    | 0 => n\n                    | _.+1 => gcd (n %% m) m\n                    end.\n\nCheck muln_modl :\n        forall p m d : nat,\n          m %% d * p = (m * p) %% (d * p).\n\nLemma gcd_max_sub g k1 k2 :\n  gcd (k1 * g) (k2 * g) = (gcd k1 k2) * g.\nProof.\n  functional induction (gcd k1 k2).\n  - (* k1 = 0 *)\n    rewrite mul0n.\n    rewrite gcd_equation.\n    by [].\n  - (* k1 = _.+1 *)\n    rewrite -IHn.\n    rewrite (@muln_modl g n m).\n    rewrite gcd_equation.\n    case: (m * g); last done.\n    rewrite modn0.\n    case: (n * g).\n    + (* n * g = 0 *)\n      rewrite gcd_equation.\n      by [].\n    + (* n * g = _.+1 *)\n      move=> n'.\n      rewrite gcd_equation.\n      rewrite mod0n.\n      rewrite gcd_equation.\n      by [].\n  Restart.\n  functional induction (gcd k1 k2).\n  - (* k1 = 0 *)\n    by rewrite mul0n gcd_equation.\n  - (* k1 = _.+1 *)\n    rewrite -IHn (@muln_modl g n m) gcd_equation.\n    case: (m * g); last done.\n    rewrite modn0; case: (n * g) => [| n'].\n    + (* n * g = 0 *)\n      by rewrite gcd_equation.\n    + (* n * g = _.+1 *)\n      by rewrite gcd_equation mod0n gcd_equation.\n  Restart.\n  (* ProofCafe 須原様が示された証明 *)\n  (* 古い MathComp では muln_modl に 0 < p の前提があるため、対応する。 *)\n  case H : (0 < g).\n  - functional induction (gcd k1 k2).\n    + by rewrite mul0n gcd_equation.\n    + rewrite -IHn (@muln_modl g n m) => //=.\n      rewrite gcd_equation.\n      case: (m * g); last done.\n      rewrite modn0.\n      case: (n * g) => [| n'].\n      * by rewrite gcd_equation.\n      * by rewrite gcd_equation mod0n gcd_equation.\n  (* g = 0 の場合。新しい MathComp では不要である。 *)\n  - move/negP/negP : H.\n    rewrite -eqn0Ngt.\n    move/eqP => ->.\n    rewrite 3!muln0.\n      by rewrite gcd_equation.\nQed.\n\nTheorem gcd_max g m n :\n  g %| m ->\n  g %| n ->\n  g %| gcd m n.\nProof.\n  (*\n    g %| m が成り立つなら、m = k1 * g が成り立つはず。\n    g %| n が成り立つなら、n = k2 * g が成り立つはず。\n    m = k1 * g, n = k2 * g が成り立つなら、\n    gcd m n = gcd (k1 * g) (k2 * g) = (gcd k1 k2) * g が成り立つはず。\n    そうしたら、g %| gcd m n が成り立つはず。\n  *)\n  rewrite dvdn_eq => /eqP <-.\n  rewrite dvdn_eq => /eqP <-.\n  rewrite gcd_max_sub.\n  by apply: dvdn_mull.\nQed.\n\nLemma odd_square n :\n  odd n = odd (n * n).\nProof.\n  rewrite oddM.\n  by case (odd n).\n  Restart.\n  (* ProofCafe 須原様が示された別解 *)\n  rewrite odd_mul.\n  apply/idP/idP. (* = (boolの必要十分ｎ条件) を -> と <- に分ける定石 by 須原様 *)\n  - move=> H.\n    apply/andP.\n    by split.\n  - case => /andP.\n    by case.\nQed.\n\nLemma even_double_half n :\n  ~~odd n -> \n  n./2.*2 = n.\nProof.\n  move=> Hnoddn.\n  rewrite -[RHS]odd_double_half.\n  rewrite -[LHS]add0n.\n  apply/eqP.\n  rewrite eqn_add2r.\n  move: Hnoddn.\n  rewrite -eqb0.\n  move/eqP ->.\n  by [].\n  Restart.\n  (* ProofCafe 須原様、盛田様の証明 *)\n  move=> H.\n  rewrite -[RHS]odd_double_half.\n  move/negbTE in H.\n  by rewrite H.\nQed.\n\n(* 本定理*)\n\n(*\nまずは自然数で以下の定理を証明する．\n定理1\n  任意の自然数n とp について，\n  n · n = 2(p · p) ならばp = 0\n\n証明はn の関する整礎帰納法を使う．\n n = 0 のとき，p = 0\n n ̸= 0 のとき，\n   n とp が偶数でなければならないので，n = 2n′, p = 2p′ とおける\n   再び，n′ · n′ = 2(p′ · p′) が得られ，n′ < n\n   帰納法の仮定よりp′ = 0\n   すなわち，p = 0\n*)\n\n(*\nLemma main_thm_sub1 n :\n  ~~ odd n -> exists k, n = k.*2.\nProof.\n  move=> Hevn.\n  exists (n./2).\n  by rewrite (@even_double_half n); last done.\nQed.\n\nCheck even_double_half : forall n : nat, ~~ odd n -> (n./2).*2 = n.\n\nLemma main_thm_sub2 n :\n  ~~ odd (n * n) = ~~ odd n.\nProof.\n  by rewrite -odd_square.\nQed.\n\nCheck odd_square : forall n : nat, odd n = odd (n * n).\n*)\n\nTheorem main_thm (n p : nat) :\n  n * n = (p * p).*2 ->\n  p = 0.\nProof.\n  elim/lt_wf_ind: n p => n.                 (* 整礎帰納法*)\n  case: (posnP n) => [-> _ [] // | Hn IH p Hnp].\n  (* 解答開始はここから *)\n  move: (@odd_double (p * p)).\n  rewrite -Hnp.\n  move/negbT.\n  rewrite -odd_square.\n  move/even_double_half => Hnev. (* この時点で、(n./2).*2 = n を証明できた。 *)\n\n  move: (Hnp).\n  rewrite -Hnev.\n  rewrite -{2}muln2 mulnA -[RHS]muln2.\n  rewrite [(n./2).*2 * n./2]mulnC -[(n./2).*2]muln2 mulnA [n./2 * n./2 * 2]muln2.\n  move/eqP.\n  rewrite eqn_mul2r => /orP [H2eq0 | Hpn] //.\n  move: Hpn => /eqP Hpn.\n  move: (@odd_double (n./2 * n./2)).\n  rewrite Hpn.\n  move/negbT.\n  rewrite -odd_square.\n  move/even_double_half => Hpev. (* この時点で、(p./2).*2 = p を証明できた。 *)\n\n  have H : n./2 * n./2 = (p./2 * p./2).*2.\n    move: (Hpn).\n    rewrite -Hpev.\n    rewrite -[in RHS]muln2 [RHS]mulnA [p./2 * 2 * p./2]mulnC [p./2 * (p./2 * 2)]mulnA.\n    rewrite [p./2 * p./2 * 2]muln2 -[LHS]muln2.\n    move/eqP.\n    rewrite eqn_mul2r => /orP [H2e0 | Hhnhp] //.\n    move: Hhnhp => /eqP Hhnhp.\n    rewrite Hhnhp Hpev.\n    by []. (* この時点で、n./2 * n./2 = (p./2 * p./2).*2 を証明できた。 *)\n\n  rewrite -Hpev -muln2 -[RHS](mul0n 2).\n  apply/eqP.\n  rewrite eqn_mul2r.\n  apply/orP.\n  right. (* この時点で、ゴールを p./2 == 0 に書き換えることができた。 *)\n\n  Check (IH n./2) :\n          (n./2 < n)%coq_nat ->\n          forall p : nat,\n            n./2 * n./2 = (p * p).*2 ->\n            p = 0.\n\n  apply/eqP/(IH n./2); last done.\n  (* この時点で、ゴールを (n./2 < n)%coq_nat に書き換えることができた。 *)\n\n  rewrite -divn2.\n\n  Check ltP. (* : reflect (?m < ?n)%coq_nat (?m < ?n) *)\n  Check ltn_Pdiv :\n          forall m d : nat,\n            1 < d ->\n            0 < m ->\n            m %/ d < m.\n  Check (@ltn_Pdiv n 2) :\n          1 < 2 ->\n          0 < n ->\n          n %/ 2 < n.\n\n  by apply/ltP/(@ltn_Pdiv n 2).\nQed.\n\nLemma main_thm'_lm1 (n p : nat) :\n  n * n = (p * p).*2 ->\n  (n./2).*2 = n.\nProof.\n  move=> Hnp.\n  move: (@odd_double (p * p)).\n  rewrite -Hnp => /negbT.\n  by rewrite -odd_square => /even_double_half.\nQed.\n(*\npが2で割り切れるか割り切れないかの場合分けが必要なはず。\nどこで行っているか？\n*)\nLemma main_thm'_lm2 (n p : nat) :\n  n * n = (p * p).*2 ->\n  p * p = (n./2 * n./2).*2.\nProof.\n  move=> Hnp.\n  move: (Hnp) => /main_thm'_lm1 => Hnev.\n  move: (Hnp).\n  rewrite -Hnev -{2}muln2 mulnA -[RHS]muln2\n          [(n./2).*2 * n./2]mulnC -[(n./2).*2]muln2 mulnA\n          [n./2 * n./2 * 2]muln2 => /eqP.\n  rewrite eqn_mul2r => /orP [H2eq0 | Hpn] //.\n  rewrite muln2 Hnev.\n  by move: Hpn => /eqP.\nQed.\n\nTheorem main_thm' (n p : nat) :\n  n * n = (p * p).*2 ->\n  p = 0.\nProof.\n  elim/lt_wf_ind: n p => n.                 (* 整礎帰納法*)\n  case: (posnP n) => [-> _ [] // | Hn IH p Hnp].\n  (* 解答開始はここから *)\n\n  (* n * n = (p * p).*2 から p * p = (n./2 * n./2).*2 を導く。 *)\n  move: (@main_thm'_lm2 n p Hnp) => Hpn.\n\n  (* p * p = (n./2 * n./2).*2 から (p./2).*2 = p を導き、\n     ゴールを (p./2).*2 = 0 に書き換える。 *)\n  move: (@main_thm'_lm1 p n./2 Hpn) => <-.\n\n  (* ゴールを p./2 == 0 に書き換える。 *)\n  rewrite -muln2 -[RHS](mul0n 2).\n  apply/eqP; rewrite eqn_mul2r; apply/orP; right.\n\n  (* (IH n./2) を apply することで必要になる\n     命題 n./2 * n./2 = (p./2 * p./2).*2 を証明する。 *)\n  move: (@main_thm'_lm2 p n./2 Hpn) => H.\n\n  (* (IH n./2) を apply して、ゴールを (n./2 < n)%coq_nat に書き換える。 *)\n  apply/eqP/(IH n./2); last done.\n  apply/ltP.\n  (*\n    ( )%coq_natのスコープをなくしてMathCompに統一するために、\n    なるべく早くapply/ltPを実行するべき。 by 須原様\n  *)\n\n  (* (@ltn_Pdiv n 2) を apply して、証明を完了する。 *)\n  rewrite -divn2.\n  by apply(*/ltP*)/(@ltn_Pdiv n 2).\nQed.\n\n(* 無理数*)\nRequire Import Reals Field.      (* 実数とそのためのfield タクティク*)\n\n(*\n定理 main_thm : n * n = (p * p).*2 -> p = 0 を使って、\n√2 が無理数であることを証明する。\nもしも √2 が有理数なら、ある n と p が存在し、√2 = n/p、すなわち n ^ 2 = 2 * p ^ 2 となる。\nしかし上の定理から p = 0 となるので矛盾。\n*)\n\nCheck INR : nat -> R.\n\nDefinition irrational (x : R) : Prop :=  (* x が有理数でないという主張の定義らしい。 *)\n  forall (p q : nat),\n    q <> 0 ->\n    x <> (INR p / INR q)%R.\n\nTheorem irrational_sqrt_2:\n  irrational (sqrt (INR 2)).\nProof.\n  rewrite /irrational /not. (* わかりやすくするために定義を展開。 *)\n  move=> p q Hq Hrt. (* これにより、ゴールが False となる。 *)\n  apply: (Hq). (* これにより、ゴールが q = 0 となる。 *)\n\n  Check (main_thm p) :\n          forall p0 : nat,\n            p * p = (p0 * p0).*2 ->\n            p0 = 0.\n\n  apply: (main_thm p). (* これにより、ゴールが p * p = (q * q).*2 となる。 *)\n\n  Check INR_eq :\n          forall n m : nat,\n            INR n = INR m ->\n            n = m.\n\n  apply: INR_eq. (* これにより、ゴールが INR (p * p) = INR (q * q).*2 となる。 *)\n  rewrite -mul2n. (* これにより、ゴールが INR (p * p) = INR (2 * (q * q)) となる。 *)\n\n  Check mult_INR :\n          forall n m : nat,\n            INR (n * m)%coq_nat = (INR n * INR m)%R.\n\n  rewrite !mult_INR.\n    (* これにより、ゴールが (INR p * INR p)%R = (INR 2 * (INR q * INR q))%R となる。 *)\n\n  Check sqrt_def (INR 2) :\n          (0 <= INR 2)%R ->\n          (sqrt (INR 2) * sqrt (INR 2))%R = INR 2.\n\n  rewrite -(sqrt_def (INR 2)).\n  - (* 本題の証明 *)\n    rewrite Hrt.\n    field.\n    (*\n      ここで、ゴールが INR q <> 0%R に変わるのは、分母が0でないことが新たなゴールとなるため。\n      「分母が0でないなら、体の要素として等しい」という形の補題を適用することになるため、\n      分母が0でないことが新たなゴールとなるとのこと。by 盛田様\n    *)\n    (*\n      環は、乗算について逆元の存在を要求していないので、除算ができない。\n      体は、0以外は乗算について逆元の存在を要求するので、除算ができる。\n      とのこと。\n    *)\n    have : INR q <> 0%R.\n      by auto with real.\n    by apply.\n  - (* (0 <= INR 2)%R の証明 *)\n    auto with real.\n  Restart.\n  move=> p q Hq Hrt.\n  apply /Hq /(main_thm p) /INR_eq.\n  rewrite -mul2n !mult_INR -(sqrt_def (INR 2)) ?{}Hrt; last by auto with real.\n  have Hqr : INR q <> 0%R by auto with real.\n    by field.\nQed.\n", "meta": {"author": "wakaba2017", "repo": "ProofCafe", "sha": "f2dd32225e2a9ed38577621e228d0adc1e1cd0b5", "save_path": "github-repos/coq/wakaba2017-ProofCafe", "path": "github-repos/coq/wakaba2017-ProofCafe/ProofCafe-f2dd32225e2a9ed38577621e228d0adc1e1cd0b5/ssrcoq6-self_learning.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7416895386012989}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus y (plus Zero x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj263_coqofml_lWgS7G.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7416895340668656}}
{"text": "From mathcomp\n     Require Import ssreflect.\nSection ModusPonens.\n  Variables X Y : Prop.\n  Hypothesis XtoY_is_true : X -> Y.\n  Hypothesis X_is_true : X.\n\n\n  Theorem MP : Y.\n  Proof.\n    move: X_is_true.\n      by [].\n  Qed.\nEnd ModusPonens.\n\nSection HilbertSAxiom.\n  Variables A B C : Prop.\n  Theorem HS1 : (A -> (B -> C)) -> ((A -> B) -> (A -> C)).\n  Proof.\n    move => AtoBtoC_is_true.\n    move => AtoB_is_true.\n    move => A_is_true.\n\n    apply: (MP B C).\n\n    apply: (MP A (B -> C)).\n      by [].\n        by [].\n\n        apply: (MP A B).\n          by [].\n            by [].\n  Qed.\n  \n  Theorem HS2 : (A -> (B -> C)) -> ((A -> B) -> (A -> C)).\n  Proof.\n    move => AtoBtoC_is_true AtoB_is_true A_is_true.\n      by apply: (MP B C); [apply: (MP A (B -> C)) | apply: (MP A B)].\n  Qed.\n\n  Theorem HS3 : (A -> (B -> C)) -> ((A -> B) -> (A -> C)).\n  Proof.\n    move => AtoBtoC_is_true AtoB_is_true A_is_true.\n      by move: A_is_true (AtoB_is_true A_is_true).\n  Qed.\n  \nEnd HilbertSAxiom.\n\n  \n  ", "meta": {"author": "denjiry", "repo": "pgeneral", "sha": "190a607a5071af6d41d1abe2af85b86dc085b9ea", "save_path": "github-repos/coq/denjiry-pgeneral", "path": "github-repos/coq/denjiry-pgeneral/pgeneral-190a607a5071af6d41d1abe2af85b86dc085b9ea/modus_ponens.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7416839954476835}}
{"text": "\n(**\n  Various auxiliary things\n*)\n\nRequire Import Nat Bool Arith Omega.\nRequire Import Coq.Structures.Equalities.\nRequire Import Coq.Arith.Wf_nat.\n\n(** * Insert and Remove\n  To describe some operations we need we have to define what is to \"insert\" or to\n  \"remove\" an element at nth position to or from the list.\n  The existing Coq functions use Option A as a return type, but we want to keep\n  things as simple as possible. So our functions \"work\" even when incorrect values\n  are passed in.\n*)\n\nRequire Import List.\nImport ListNotations.\nModule NthInserterRemover (Import T : Typ).\n\nDefinition A := T.t.\n\n(**\n  It works as we want when n < length l\n  See lemmas below\n*)\n\nFixpoint nth_remove n l : list A :=\n  match n, l with\n  | _, [] => []\n  | 0, h::t => t\n  | S n', h::t => h :: nth_remove n' t\n  end.\n\nLemma nth_remove_length: forall n (l: list A),\n  n < length l ->\n  length (nth_remove n l) = (length l) - 1.\nProof.\n  intros. generalize dependent n.\n  induction l; intros; simpl in *; destruct n; intuition.\n  assert (e: n < length l) by omega. apply IHl in e. simpl. rewrite e.\n  omega.\nQed.\n\nLemma nth_remove_representation: forall n (l: list A),\n  n < length l ->\n  exists x lh lt, Some x = nth_error l n /\\\n    l = lh ++ x::lt /\\ nth_remove n l = lh ++ lt\n    /\\ length lh = n /\\ length lt = (length l) - n - 1.\nProof.\n  intros.\n  generalize dependent n; induction l; intros; simpl in *.\n  - easy.\n  - destruct n; simpl in *. exists a, [], l; intuition.\n    assert (e: n < length l) by omega; apply IHl in e; destruct e as [q0 [q1 [q3 ]]].\n    intuition. exists q0, (a::q1), q3. rewrite H1, H2, H0. rewrite <- H3.\n    ssimpl_list. intuition.\nQed.\n\nLemma nth_remove_overflow: forall n l,\n  n >= length l <->\n  nth_remove n l = l.\nProof.\n  induction n; destruct l; intros; simpl in *; intuition.\n  - easy.\n  - apply f_equal with (B := nat) (f:=@length A) in H. simpl in H.\n    intuition.\n  - assert (e: n >= length l) by omega; apply (IHn _) in e; rewrite e.\n    auto.\n  - inversion H as [H']; rewrite H'; apply IHn in H'. omega.\nQed.\n\n(**\n  It works as we want when n <= length l\n  See lemmas below\n*)\n\nFixpoint nth_insert n l x : list A :=\n  match n, l with\n  | 0, _ => x::l\n  | _, [] => []\n  | S n', h::t => h::(nth_insert n' t x)\n  end.\n\nLemma nth_insert_length: forall n l x,\n  n <= length l ->\n  length (nth_insert n l x) = S (length l).\nProof.\n  intros.\n  generalize dependent n; induction l; intros; simpl in *.\n  - inversion H. intuition.\n  - destruct n; auto.\n    simpl.\n    assert (e: n <= length l) by omega; apply IHl in e; rewrite e.\n    reflexivity.\nQed.\n\nLemma nth_insert_representation: forall n (l: list A) x,\n  n <= length l ->\n  Some x = nth_error (nth_insert n l x) n /\\\n  exists lh lt, nth_insert n l x = lh ++ x::lt /\\ l = lh ++ lt\n    /\\ length lh = n /\\ length lt = (length l) - n.\nProof.\n  intros.\n  generalize dependent n; induction l; intros; simpl in *.\n  - inversion H. simpl. split; [auto | exists [], []]. intuition.\n  - destruct n; simpl in *. split; [auto | exists [], (a::l)]; intuition.\n    assert (e: n <= length l) by omega; apply IHl in e; destruct e as [q0 [q1 [q3 ]]].\n    intuition. exists (a::q1), q3; simpl. rewrite H1, H4, H0. auto.\nQed.\n\nLemma nth_insert_overflow: forall n l x,\n  n > length l <->\n  nth_insert n l x = l.\nProof.\n  induction n; destruct l; intros; simpl in *; intuition; try easy.\n  - apply f_equal with (B := nat) (f:=@length A) in H. simpl in H.\n    intuition.\n  - assert (e: n > length l) by omega; apply (IHn _ x) in e; rewrite e.\n    auto.\n  - inversion H as [H']; rewrite H'; apply IHn in H'. omega.\nQed.\n\nLemma nth_insert_app: forall l1 l2 x,\n  nth_insert (length l1) (l1 ++ l2) x = l1 ++ x::l2.\nProof.\n  intros. induction l1; auto.\n  simpl; rewrite IHl1; auto.\nQed.\n\n(**\n  A link between nth_insert and nth_remove functions\n*)\n\nLemma nth_insert_remove: forall n l x,\n  n < length l ->\n  Some x = nth_error l n ->\n  (nth_insert n (nth_remove n l) x) = l.\nProof.\n  intros.\n  remember H as H' eqn: Heq; clear Heq.\n  assert (n <= length (nth_remove n l)).\n    apply nth_remove_length in H; rewrite H; omega.\n  apply nth_insert_representation with (x:=x) in H1. firstorder.\n  apply nth_remove_representation in H. firstorder.\n  rewrite H3 in H7. rewrite <- H0 in H. inversion H. rewrite H2, H6. subst.\n  apply f_equal with (f := fun l => (nth_insert (length x0) l x)) in H7.\n  rewrite <- H8 in H7 at 2.\n  repeat rewrite nth_insert_app in H7.\n  auto.\nQed.\n\nEnd NthInserterRemover.\n", "meta": {"author": "holmuk", "repo": "coq-zipper", "sha": "6fac9b369a43d4a7f8b26186a797dd5e66821336", "save_path": "github-repos/coq/holmuk-coq-zipper", "path": "github-repos/coq/holmuk-coq-zipper/coq-zipper-6fac9b369a43d4a7f8b26186a797dd5e66821336/src/Auxiliaries.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7415493790031343}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) : natural :=\n  plus (Succ lf2) lf3.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj122_coqofml_Gn6Jmi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7415079231424779}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (x : natural) : natural :=\n  mult z (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj156_coqofml_3JeoDQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7415079158336849}}
{"text": "(** * Suprema and infima\n\nAuthors:\n    - Jim Portegies\n\nThis file is part of Waterproof-lib.\n\nWaterproof-lib is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nWaterproof-lib is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Waterproof-lib.  If not, see <https://www.gnu.org/licenses/>.\n*)\n\nRequire Import Reals.\n(*\nRequire Import Classical.\nRequire Import Classical_Prop.\nRequire Import Classical_Pred_Type.\n*)\n\nRequire Import Waterproof.AllTactics.\nRequire Import Waterproof.notations.notations.\nRequire Import Waterproof.load.\nImport databases_RealsAndIntegers.\n\nRequire Import Waterproof.set_search_depth.To_5.\n(* Require Import Waterproof.load_database.Intuition. *)\nRequire Import Coq.Logic.Classical.\n\nDeclare Scope sup_and_inf_scope.\n\nDefinition is_in {D : Set} := fun (A : (D → Prop)) ↦ (fun (x : D) ↦ A x).\nNotation \"x ∈ A\" := (@is_in _ A x) (at level 50) : sup_and_inf_scope.\n(** ## Suprema and infima*)\nNotation is_sup := is_lub.\nNotation is_bdd_above := bound.\n\nOpen Scope R_scope.\nOpen Scope sup_and_inf_scope.\n\n(** ## Upper bounds\n\nA number $M : ℝ$ is called an **upper bound** of a subset $A : ℝ \\to \\mathsf{Prop}$ of the real numbers, if for all $a : ℝ$, if $a ∈ A$ then $a ≤ M$.\n\n```\nDefinition is_upper_bound (A : ℝ → Prop) (M : ℝ) :=\n  ∀ a : A, a ∈ A ⇒ a ≤ M.\n```\n\nWe say that a subset $A : ℝ \\to \\mathsf{Prop}$ is bounded above if there exists an $M : ℝ$ such that $M$ is an upper bound of $A$.\n\n```\nDefinition is_bounded_above (A : ℝ → Prop) :=\n  ∃ M : ℝ, is_upper_bound A M.\n```\n\n## The supremum\n\nA real number $L : ℝ$ is called the **supremum** of a subset $A : ℝ \\to \\mathsf{Prop}$ if it is the smallest upper bound.\n```\nDefinition is_sup (A : ℝ → Prop) (L : ℝ) :=\n  (is_upper_bound A L) ∧ (∀ M : ℝ, is_upper_bound A M ⇒ (L ≤ M) ).\n```\n\n## The completeness axiom\n\nThe completeness axiom of the real numbers says that when a subset $A$ of the real numbers is bounded from above, and when there exists an element in the set, then there exists an $L$ such that $L$ is the supremum of $A$.\n\n```\nAxiom completeness : ∀ A : ℝ → Prop,\n      is_bounded_above A ⇒ \n        ((∃ x : ℝ, x ∈ A) ⇒ { M : ℝ | is_sup A M }).\n```*)\n(** ## Lower bounds\n\nA number $m : ℝ$ is called a lower bound of a subset $A : ℝ → \\mathsf{Prop}$, if for all $a : \\mathbb{R}$, if $a \\in A$ then $a ≥ m$.*)\nDefinition is_lower_bound (A : ℝ → Prop) (m : ℝ) :=\n  ∀ a : ℝ, a ∈ A ⇒ m ≤ a.\n(** We say that a subset $A : ℝ → \\mathsf{Prop}$ is bounded below if there exists an $m : ℝ$ such that $m$ is a lower bound of $A$.*)\nDefinition is_bdd_below (A : ℝ → Prop) :=\n  ∃ m : ℝ, is_lower_bound A m.\n(** ## The infimum\n\nA real number $m : ℝ$ is called the **infimum** of a subset $A : ℝ → \\mathsf{Prop}$ if it is the largest lower bound.*)\nDefinition is_inf :=\n  fun (A : ℝ → Prop) m \n    ↦ (is_lower_bound A m) ∧ (∀ l : ℝ, is_lower_bound A l ⇒ l ≤ m).\n(** ## Reflection of a subset of ℝ in the origin\n\nBefore we continue showing properties of the infimum, we first introduce the reflection of subsets of $\\mathbb{R}$ in the origin. Given a subset $A : ℝ → \\mathsf{Prop}$, we consider the set $-A$ (which we write as $\\mathsf{set\\_opp} A$), defined by*)\nDefinition set_opp (A : ℝ → Prop)  :=\n  fun (x : ℝ) ↦ (A (-x)).\n\nLemma upp_bd_set_to_low_bd_set_opp :\n  ∀ (A : ℝ → Prop) (M : ℝ),\n    is_upper_bound A M ⇒ \n      is_lower_bound (set_opp A) (-M).\nProof.\n    Take A : (ℝ → Prop). \n    Take M : ℝ.\n    Assume that (is_upper_bound A M) (i).\n    Expand the definition of is_lower_bound.\n    That is, write the goal as (for all a : ℝ, a ∈ set_opp A ⇨ -M ≤ a).\n    We need to show that (∀ a : ℝ, (-a ∈ A) ⇒ -M ≤ a).\n    Take a : ℝ.\n    Assume that (-a ∈ A).\n    By (i) it holds that (-a ≤ M).\n    It follows that (-M ≤ a).\nQed.\n\nLemma low_bd_set_to_upp_bd_set_opp :\n  ∀ (A : ℝ → Prop) (m : ℝ),\n    is_lower_bound A m ⇒\n      is_upper_bound (set_opp A) (-m).\nProof.\n    Take A : (ℝ → Prop).\n    Take m : ℝ.\n    Assume that (is_lower_bound A m) (i).\n    Expand the definition of is_upper_bound.\n    That is, write the goal as (for all x : ℝ, set_opp A x ⇨ x ≤ -m).\n    We need to show that (∀ a : ℝ, (-a ∈ A) ⇒ a ≤ -m).\n    Take a : ℝ. \n    Assume that (-a ∈ A).\n    By (i) it holds that (m ≤ -a).\n    It follows that (a ≤ -m).\nQed.\n\nLemma low_bd_set_opp_to_upp_bd_set :\n  ∀ (A : ℝ → Prop) (m : ℝ),\n    is_lower_bound (set_opp A) m ⇒ \n      is_upper_bound A (-m).\nProof.\n    Take A : (ℝ → Prop). \n    Take m : ℝ.\n    Assume that (is_lower_bound (set_opp A) m).\n    Expand the definition of is_upper_bound.\n    That is, write the goal as (for all x : ℝ, A x ⇨ x ≤ - m).\n    Take a : ℝ.\n    Assume that (a ∈ A) (i).\n    It holds that (for all x : R, (-x) ∈ A -> m <= x).\n    We claim that (--a ∈ A).\n    { It holds that (--a = a) (ii).\n      (* TODO: We conclude that (--a ∈ A). should work *)\n      exact (eq_ind_r(_,_,(fun x => x ∈ A),(i),_,(ii))).\n    }\n    It holds that (m ≤ -a).\n    It follows that (a ≤ -m).\nQed.\n\nLemma upp_bd_set_opp_to_low_bd_set :\n  ∀ (A : ℝ → Prop) (M : ℝ),\n    is_upper_bound (set_opp A) M ⇒\n      is_lower_bound A (-M).\nProof.\n    Take A : (ℝ → Prop).\n    Take M : ℝ.\n    Assume that (is_upper_bound (set_opp A) M).\n    Expand the definition of is_lower_bound.\n    That is, write the goal as (for all a : ℝ, a ∈ A ⇨ - M ≤ a).\n    Take a : ℝ.\n    Assume that (a ∈ A) (i).\n    We claim that (--a ∈ A).\n    { It holds that (--a = a) (ii).\n      (* TODO: We conclude that (--a ∈ A). should work *)\n      exact (eq_ind_r(_,_,(fun x => x ∈ A),(i),_,(ii))).\n    }\n    It holds that (-a ≤ M).\n    It follows that (-M ≤ a).\nQed.\n\n\nLemma bdd_below_to_bdd_above_set_opp :\n  ∀ (A : ℝ → Prop),\n    is_bdd_below A ⇒ is_bdd_above (set_opp A).\nProof.\n    Take A : (ℝ → Prop).\n    Assume that (is_bdd_below A) (i).\n    We need to show that (∃ M : ℝ, is_upper_bound (set_opp A) M).\n    Expand the definition of is_bdd_below in (i).\n    That is, write (i) as (∃ m : ℝ, is_lower_bound A m).\n    Obtain m according to (i), so for m : R it holds that (is_lower_bound A m).\n    Choose M := (-m).\n    We need to show that (is_upper_bound (set_opp A) M).\n    By low_bd_set_to_upp_bd_set_opp we conclude that (is_upper_bound (set_opp A) M).\nQed.\n\n\nLemma sup_set_opp_is_inf_set :\n  ∀ (A : ℝ → Prop) (M : ℝ),\n    is_sup (set_opp A) M ⇒ is_inf A (-M).\nProof.\n    Take A : (ℝ → Prop).\n    Take M : ℝ.\n    Assume that (is_sup (set_opp A) M) (i).\n    Expand the definition of is_inf.\n    That is, write the goal as (is_lower_bound A (- M) \n      ∧ (for all l : ℝ, is_lower_bound A l ⇨ l ≤ - M)).\n    We show both statements.\n    - We need to show that ( is_lower_bound A (- M) ).\n      Expand the definition of is_lub in (i).\n      That is, write (i) as (is_upper_bound (set_opp A) M \n        ∧ (for all b : ℝ, is_upper_bound (set_opp A) b ⇨ M ≤ b)).\n      Because (i) both (is_upper_bound (set_opp A) M) and\n        (for all b : ℝ, is_upper_bound (set_opp A) b ⇨ M ≤ b) hold.\n      By upp_bd_set_opp_to_low_bd_set we conclude that (is_lower_bound A (-M)).\n    - We need to show that (∀ l : ℝ, is_lower_bound A l ⇒ l ≤ -M).\n      Expand the definition of is_lower_bound.\n      That is, write the goal as (for all l : ℝ, (for all a : ℝ, a ∈ A ⇨ l ≤ a) ⇨ l ≤ - M).\n      Take l : ℝ.\n      Assume that (is_lower_bound A l).\n      Expand the definition of is_lub in (i).\n      That is, write (i) as (is_upper_bound (set_opp A) M \n        ∧ (for all b : ℝ, is_upper_bound (set_opp A) b ⇨ M ≤ b)).\n      Because (i) both (is_upper_bound (set_opp A) M)\n        and (for all b : ℝ, is_upper_bound (set_opp A) b ⇨ M ≤ b) (ii) hold.\n      By low_bd_set_to_upp_bd_set_opp it holds that (is_upper_bound (set_opp A) (-l)).\n      By (ii) it holds that (M ≤ -l).\n      We conclude that (l <= -M).\nQed.\n\nLemma exists_inf :\n  ∀ A : (ℝ →  Prop), is_bdd_below A ⇒\n    ((∃ x : ℝ, x ∈ A) ⇒ { m | is_inf A m }).\nProof.\n    Take A : (ℝ → Prop).\n    Assume that (is_bdd_below A).\n    Assume that (∃ x : ℝ, x ∈ A) (i).\n    Define B := (set_opp A).\n    We claim that (for all s : ℝ, (A s) -> (B (-s))) (ii).\n    { Take s : ℝ.\n      Assume that (A s).\n      (* TODO: make nicer *)\n      We need to show that (A (--s)).\n      It holds that (A (--s) = A s) (iii).\n      Fail We conclude that (A (--s)).\n      rewrite iii.\n      We conclude that (A s).\n    }\n    By bdd_below_to_bdd_above_set_opp it holds that (is_bdd_above B).\n    We claim that (∃ y : ℝ, y ∈ B).\n    { Obtain x according to (i), so for x : R it holds that (A x).\n      Choose y := (-x).\n      We need to show that (B (-x)).\n      By (ii) we conclude that (B (-x)).\n    }\n    By completeness it holds that ({L | is_sup B L}) (iv).\n    Obtain L according to (iv), so for L : R it holds that (is_sup B L).\n    By sup_set_opp_is_inf_set it holds that (is_inf A (-L)).\n    We conclude that ({m | is_inf A m}). (*TODO: make solvable with 'Choose ...'.*)\nQed.\n\n\n\n(** ### A supremum is an upper bound\n\nIf $M$ is the supremum of a set $A$, it is also an upper bound.*)\nLemma sup_is_upp_bd :\n  ∀ A : ℝ → Prop,\n    ∀ M : ℝ,\n      is_sup A M ⇒ is_upper_bound A M.\nProof.\n    Take A : (ℝ → Prop) and M : ℝ. \n    Assume that (is_sup A M).\n    It holds that (is_upper_bound A M ∧ (∀ L : ℝ, is_upper_bound A L ⇒ M ≤ L)) (i).\n    Because (i) both (is_upper_bound A M) and\n      (∀ L : ℝ, is_upper_bound A L ⇒ M ≤ L) hold.\n    It follows that (is_upper_bound A M).\nQed.\n\n\n(** ### Any upper bound is greater than or equal to the supremum*)\nLemma any_upp_bd_ge_sup :\n  ∀ A : ℝ → Prop,\n    ∀ M L : ℝ,\n      is_sup A M ⇒ (is_upper_bound A L ⇒ M ≤ L).\nProof.\n    Take A : (ℝ → Prop) and M, l : ℝ.\n    Assume that (is_sup A M) and (is_upper_bound A l).\n    It holds that (is_upper_bound A M ∧ (∀ L : ℝ, is_upper_bound A L ⇒ M ≤ L)) (i).\n    Because (i) both (is_upper_bound A M) and\n      (∀ L : ℝ, is_upper_bound A L ⇒ M ≤ L) hold.\n    (** We need to show that $M \\leq L$.*)\n    We conclude that (M <= l).\nQed.\n\n\n\n(** ## Infima*)\n(** ## An infimum is a lower bound*)\nLemma inf_is_low_bd :\n  ∀ A : ℝ → Prop,\n    ∀ m : ℝ,\n      is_inf A m ⇒ is_lower_bound A m.\nProof.\n    Take A : (ℝ → Prop) and m : R.\n    Assume that (is_inf A m).\n    It holds that (is_lower_bound A m ∧ (∀ l : ℝ, is_lower_bound A l ⇒ l ≤ m)) (i).\n    Because (i) both (is_lower_bound A m) and\n      (∀ l : ℝ, is_lower_bound A l ⇒ l ≤ m).\n    We conclude that (is_lower_bound A m).\nQed.\n\n\n(** ## Any lower bound is less than or equal to the infimum*)\nLemma any_low_bd_ge_inf :\n  ∀ A : ℝ → Prop,\n    ∀ m l : ℝ,\n      is_inf A m ⇒ is_lower_bound A l ⇒ l ≤ m.\nProof.\n    Take A : (R → Prop) and m, l : R.\n    Assume that (is_inf A m) and (is_lower_bound A l).\n    It holds that (is_lower_bound A m ∧ (∀ l : ℝ, is_lower_bound A l ⇒ l ≤ m)) (i).\n    Because (i) both (is_lower_bound A m) and (∀ l : ℝ, is_lower_bound A l ⇒ l ≤ m) (ii) hold.\n    By (ii) we conclude that (l ≤ m).\nQed.\n\n(** ### $\\varepsilon$-characterizations*)\nLemma exists_almost_maximizer :\n  ∀ (A : ℝ -> Prop) (M : ℝ),\n    is_sup A M ⇒\n      ∀ (L : ℝ), L < M ⇒ \n        ∃ a : ℝ, A a ∧ L < a.\nProof.\n    Take A : (ℝ -> Prop) and M : ℝ.\n    Assume that (is_sup A M).\n    Take L : ℝ. \n    Assume that (L < M).\n    We argue by contradiction.\n    Assume that (¬ (there exists a : ℝ, A a ∧ L < a)).\n    It holds that (∀ x : ℝ, A x ⇒ (x <= L)).\n    It holds that (is_upper_bound A L).\n    By any_upp_bd_ge_sup it holds that (M ≤ L).\n    It holds that (¬(M ≤ L)).\n    Contradiction.\nQed.\n\n\nLemma exists_almost_maximizer_ε :\n  ∀ (A : ℝ -> Prop) (M : ℝ),\n    is_sup A M ⇒\n      ∀ (ε : ℝ), ε > 0 ⇒ \n        ∃ a : ℝ, A a ∧ M - ε < a.\nProof.\n    Take A : (ℝ -> Prop) and M : ℝ.\n    Assume that (is_sup A M).\n    Take ε : ℝ; such that (ε > 0).\n    It holds that (M - ε < M).\n    apply exists_almost_maximizer with (L := M- ε) (M := M).\n    - We conclude that (is_sup A M).\n    - We conclude that (M - ε < M).\nQed.\n\n\nLemma max_or_strict :\n  ∀ (A : ℝ → Prop) (M : ℝ),\n    is_sup A M ⇒ \n      (A M) ∨ (∀ a : ℝ, A a ⇒ a < M).\nProof.\n    Take A : (ℝ → Prop) and M : ℝ.\n    Assume that (is_sup A M).\n    We argue by contradiction.\n    Assume that ( ¬ (A M ∨ (for all a : ℝ, A a ⇨ a < M))).\n    It holds that ((¬ (A M)) ∧ ¬(∀ a : ℝ, A a ⇒ a < M)) (i).\n    Because (i) both (¬ (A M)) and  (¬(∀ a : ℝ, A a ⇒ a < M)) hold.\n    (** We only show the proposition on the *)\n    (** hand side of the or-sign, i.e. we will show that for all $a \\in \\mathbb{R}$, if $a \\in A$ then $a < M$*)\n    We claim that (∀ a : ℝ, A a ⇒ a < M).\n    { Take a : ℝ.\n      Assume that (A a).\n      By sup_is_upp_bd it holds that (is_upper_bound A M).\n      It holds that (a ≤ M).\n      We claim that (¬(a = M)).\n      { Assume that (a = M) (eq_1).\n        We claim that (A M).\n        { (* TODO: improve*)\n          rewrite <- eq_1.\n          We conclude that (A a).\n        }\n        Contradiction.\n      }\n      We conclude that (a < M).\n    }\n    Contradiction.\nQed.\n\n\n(** ## Suprema and sequences*)\nLemma seq_ex_almost_maximizer_ε :\n  ∀ (a : ℕ → ℝ) (pr : has_ub a) (ε : ℝ), \n    ε > 0 ⇒ ∃ k : ℕ, a k > lub a pr - ε.\nProof.\n    Take a : (ℕ → ℝ).\n    Assume that (has_ub a) (i).\n    Expand the definition of lub.\n    That is, write the goal as (for all ε : ℝ,  ε > 0 \n      ⇨ there exists k : ℕ, a k > (let (a0, _) := ub_to_lub a (i) in a0) - ε).\n    Define lub_a_prf := (ub_to_lub a (i)).\n    Obtain l according to (lub_a_prf), so for l : R it holds that (is_sup (EUn a) l).\n    Take ε : ℝ; such that (ε > 0).\n    By exists_almost_maximizer_ε it holds that (∃ y : ℝ, (EUn a) y ∧ y > l - ε) (iv).\n    Obtain y according to (iv), so for y : R it holds that \n      ((EUn a) y ∧ y > l - ε) (v).\n    Because (v) both (EUn a y) (vi) and (y > l - ε) hold.\n    Expand the definition of EUn in (vi).\n    That is, write (vi) as (there exists n : ℕ , y = a n).\n    Obtain n according to (vi), so for n : nat it holds that (y = a n).\n    Choose k := n.\n    We need to show that (l - ε < a n).\n    We conclude that (& l - ε < y = a n).\nQed.\n\n\nLemma seq_ex_almost_maximizer_m :\n  ∀ (a : ℕ → ℝ) (pr : has_ub a) (m : ℕ), \n    ∃ k : ℕ, a k > lub a pr - 1 / (INR(m) + 1).\nProof.\n    Take a : (ℕ → ℝ).\n    Assume that (has_ub a).\n    Take m : ℕ.\n    By seq_ex_almost_maximizer_ε it suffices to show that (1 / (m + 1) > 0).\n    (** We need to show that $1/(m+1) > 0$.*)\n    It holds that (0 < m + 1)%R.\n    We conclude that (1 / (m+1) > 0).\nQed.\n\n\nLemma exists_almost_lim_sup_aux :\n  ∀ (a : ℕ → ℝ) (pr : has_ub a) (m : ℕ) (N : ℕ),\n    ∃ k : ℕ, (k ≥ N)%nat ∧ a k > sequence_ub a pr N - 1 / (INR(m) + 1).\nProof.\n    Take a : (ℕ → ℝ).\n    Assume that (has_ub a) (i).\n    Take m, Nn : ℕ.\n    By seq_ex_almost_maximizer_m it holds that\n      (∃ k : ℕ, a (Nn + k)%nat > sequence_ub a (i) Nn - 1 / (INR m + 1)) (ii).\n    Obtain k according to (ii), so for k : nat it holds that\n      (a (Nn + k)%nat > sequence_ub a i Nn - 1 / (m + 1)).\n    Choose l := (Nn+k)%nat.\n    We show both statements.\n    - We need to show that (l ≥ Nn)%nat.\n      We conclude that (l ≥ Nn)%nat.\n    - We need to show that ( a l > sequence_ub a (i) Nn - 1 / (m + 1) ).\n      We conclude that ( a l > sequence_ub a (i) Nn - 1 / (m + 1) ).\nQed.\n\nClose Scope sup_and_inf_scope.\nClose Scope R_scope.\n", "meta": {"author": "impermeable", "repo": "coq-waterproof", "sha": "a32bad4e44fedb4038065d2b55660cd967c2d1fd", "save_path": "github-repos/coq/impermeable-coq-waterproof", "path": "github-repos/coq/impermeable-coq-waterproof/coq-waterproof-a32bad4e44fedb4038065d2b55660cd967c2d1fd/waterproof/theory/analysis/sup_and_inf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7414775737866055}}
{"text": "Inductive nat :=\n| O\n| S : nat -> nat.\n\nFixpoint plus (n m: nat) :=\n    match n with\n    | S n' => S (plus n' m)\n    | O => m\n    end.\n\n(* A magma is a set with a binary (closed) operation. *)\nModule Type Magma.\n    Parameter T: Set.\n    Parameter op: T -> T -> T.\nEnd Magma.\n\n\n(* Natural numbers with plus form a magma. *)\nModule Nat: Magma.\n    Definition T := nat.\n    Definition op := plus.\nEnd Nat.\n\nModule Type M := Magma.\nModule MyNat: M := Nat.\n\n(* A functor transforming a magma into another magma. *)\nModule DoubleMagma (M: Magma): Magma.\n    Definition T := M.T.\n    Definition op x y := M.op (M.op x y) (M.op x y).\nEnd DoubleMagma.\n\nModule NatWithDoublePlus := DoubleMagma Nat.\n", "meta": {"author": "SwampertX", "repo": "undergraduate-thesis", "sha": "b0c78984b94e56f1372a7195bd0babaab10fca8d", "save_path": "github-repos/coq/SwampertX-undergraduate-thesis", "path": "github-repos/coq/SwampertX-undergraduate-thesis/undergraduate-thesis-b0c78984b94e56f1372a7195bd0babaab10fca8d/ca-presentation/code/module_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768525822309, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7414701889525724}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Max Omega Wellfounded Bool.\n\nRequire Import list_focus utils_tac utils_list utils_nat.\n\nSet Implicit Arguments.\n\n(** We show that unbounded decidable predicates are exactly\n    the direct images of strictly increasing sequences nat -> nat \n\n    Hence, this gives an easy construction of the sequence\n    of all primes ...\n\n*)\n\nSection sinc_decidable.\n\n  Variable (P : nat -> Prop)\n           (f : nat -> nat) \n           (Hf : forall n, f n < f (S n))\n           (HP : forall n, P n <-> exists k, n = f k).\n\n  Let f_mono x y : x <= y -> f x <= f y.\n  Proof.\n    induction 1 as [ | y H IH ]; auto.\n    apply le_trans with (1 := IH), lt_le_weak, Hf.\n  Qed.\n\n  Let f_smono x y : x < y -> f x < f y.\n  Proof.\n    intros H; apply f_mono in H.\n    apply lt_le_trans with (2 := H), Hf.\n  Qed.\n\n  Let f_ge_n n : n <= f n.\n  Proof.\n    induction n as [ | n IHn ]; try omega.\n    apply le_trans with (2 := Hf _); omega.\n  Qed.\n\n  Let unbounded n : exists k, n <= k /\\ P k.\n  Proof. exists (f n); split; auto; rewrite HP; exists n; auto. Qed.\n\n  Let decidable n : { P n } + { ~ P n }.\n  Proof.\n    destruct (@bounded_search (S n) (fun i => f i = n))\n      as [ (i & H1 & H2) | H1 ].\n    + intros i _; destruct (eq_nat_dec (f i) n); tauto.\n    + left; rewrite HP; eauto.\n    + right; rewrite HP; intros (k & Hk).\n      symmetry in Hk; generalize Hk; apply H1.\n      rewrite <- Hk; apply le_n_S; auto.\n  Qed.\n\n  Theorem sinc_decidable : (forall n, exists k, n <= k /\\ P k)\n                         * (forall n, { P n } + { ~ P n }).\n  Proof. split; auto. Qed.\n\nEnd sinc_decidable.\n\nSection decidable_sinc.\n\n  Variable (P    : nat -> Prop)\n           (Punb : forall n, exists k, n <= k /\\ P k)\n           (Pdec : forall n, { P n } + { ~ P n }).\n\n  Let next n : { k | P k /\\ n <= k /\\ forall x, P x -> x < n \\/ k <= x }.\n  Proof.\n    destruct min_dec with (P := fun k => P k /\\ n <= k)\n      as (k & (H1 & H2) & H3).\n    + intros i; destruct (Pdec i); destruct (le_lt_dec n i); try tauto; right; intro; omega.\n    + destruct (Punb (S n)) as (k & H1 & H2).\n      exists k; split; auto; omega.\n    + exists k; repeat (split; auto).\n      intros x Hx.\n      destruct (le_lt_dec n x); try omega.\n      right; apply H3; auto.\n  Qed.\n\n  Let f := fix f n := match n with \n    | 0   => proj1_sig (next 0)\n    | S n => proj1_sig (next (S (f n)))\n  end.\n\n  Let f_sinc n : f n < f (S n).\n  Proof.\n    simpl.\n    destruct (next (S (f n))) as (?&?&?&?); auto.\n  Qed.\n\n  Let f_select x : { n | f n <= x < f (S n) } + { x < f 0 }.\n  Proof.\n    induction x as [ | x IHx ].\n    + destruct (eq_nat_dec 0 (f 0)) as [ H | H ].\n      * left; exists 0; rewrite H at 2 3; split; auto.\n      * right; omega.\n    + destruct IHx as [ (n & Hn) | Hx ].\n      * destruct (eq_nat_dec (S x) (f (S n))) as [ H | H ].\n        - left; exists (S n); rewrite H; split; auto.\n        - left; exists n; omega.\n      * destruct (eq_nat_dec (S x) (f 0)) as [ H | H ].\n        - left; exists 0; rewrite H; split; auto.\n        - right; omega.\n  Qed.\n \n  Let f_P n : P n <-> exists k, n = f k.\n  Proof.\n    split.\n    + intros Hn.\n      destruct (f_select n) as [ (k & Hk) | C ].\n      * simpl in Hk.\n        destruct (next (S (f k))) as (m & H1 & H2 & H3); simpl in Hk.\n        apply H3 in Hn.\n        destruct Hn as [ Hn | Hn ]; try omega.\n        exists k; omega.\n      * simpl in C.\n        destruct (next 0) as (m & H1 & H2 & H3); simpl in C.\n        apply H3 in Hn; omega.\n    + intros (k & Hk); subst.\n      induction k as [ | k IHk ]; simpl.\n      * destruct (next 0) as (m & H1 & H2 & H3); simpl; auto.\n      * destruct (next (S (f k))) as (m & H1 & H2 & H3); simpl; auto.\n  Qed.\n\n  Theorem decidable_sinc : { f | (forall n, f n < f (S n))\n                              /\\ (forall n, P n <-> exists k, n = f k) }.\n  Proof. exists f; auto. Qed.\n\nEnd decidable_sinc.\n   \nCheck sinc_decidable.\nCheck decidable_sinc.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/Shared/Libs/DLW/Utils/utils_decidable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768588653856, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7414701796543351}}
{"text": "Require Import List Arith Lia. \nImport ListNotations.\nFrom Undecidability.HOU Require Import std.tactics std.lists.basics std.decidable. \n\n(* nth *)\nNotation nth := nth_error. \nSection Nth.\n\n  Variable (X Y: Type).\n\n  Lemma nth_error_map_option n (f: X -> Y) (A: list X):\n    nth_error (map f A) n = option_map f (nth_error A n).\n  Proof.\n    destruct (nth_error A n) eqn: H1.\n    + eapply map_nth_error in H1. rewrite H1. reflexivity.\n    + eapply nth_error_None in H1.\n      eapply nth_error_None. now rewrite map_length. \n  Qed.\n\n\n\n  Lemma nth_error_lt_Some Z m (L: list Z):\n    m < length L -> exists a, nth L m = Some a.\n  Proof.\n    intros H % nth_error_Some.\n    destruct nth; intuition idtac. now (exists z).\n  Qed.\n\n  Lemma nth_error_Some_lt Z m a (L: list Z):\n    nth L m = Some a -> m < length L.\n  Proof.\n    intros H; eapply nth_error_Some; rewrite H; discriminate. \n  Qed.    \n\nEnd Nth.\n\n\n(* nats *)\nSection Nats.\n\n  Fixpoint nats (n: nat) :=\n    match n with\n    | 0 => nil\n    | S n => 0 :: map S (nats n)\n    end.\n\n  Lemma nats_lt: forall k i, i ∈ nats k -> i < k.\n  Proof.\n    induction k; cbn; intuition idtac. lia.\n    eapply in_map_iff in H0. destruct H0; intuition idtac; subst.\n    specialize (IHk x H1); lia.\n  Qed.\n\n  Lemma nth_nats m k:\n    m < k -> nth (nats k) m = Some m.\n  Proof.\n    induction k in m |-*.\n    - lia.\n    - intros; destruct m; cbn in *; eauto.\n      erewrite map_nth_error; eauto.\n      eapply IHk; lia.\n  Qed.\n  \n  Lemma lt_nats x k:\n    x < k -> x ∈ nats k.\n  Proof.\n    now intros H % nth_nats % nth_error_In. \n  Qed.\n\n  Lemma incl_nats I k:\n    I ⊆ nats k -> forall i, i ∈ I -> i < k.\n  Proof.\n    firstorder using nats_lt.\n  Qed.\n\n  Lemma nats_incl I k:\n    (forall i, i ∈ I -> i < k) -> I ⊆ nats k.\n  Proof.\n    firstorder using lt_nats.\n  Qed.\n\n\n  Lemma length_nats k: length (nats k) = k.\n  Proof.\n    induction k; cbn; lsimpl; congruence.\n  Qed.\n\nEnd Nats.\n#[export] Hint Rewrite length_nats : listdb.\n\n\n\n(* tabulate *)\nSection Tabulate.\n  Implicit Type  X: Type.\n\n  Fixpoint tab {X} (f: nat -> X) k  :=\n    match k with\n    | 0 => nil\n    | S n => tab f n ++ [f n]\n    end.\n  \n  Lemma tab_length X (f: nat -> X) k: length (tab f k) = k.\n  Proof.\n    induction k; cbn; lsimpl; cbn; lsimpl; lia. \n  Qed.\n\n  Lemma tab_map X Y (f: nat -> X) (g: X -> Y) k:\n    map g (tab f k) = tab (fun x => g (f x)) k.\n  Proof.\n    induction k; cbn; eauto; lsimpl; now rewrite IHk.\n  Qed.\n\n  Lemma tab_S X (f: nat -> X) n:\n    tab f (S n) = f 0 :: tab (fun k => f (S k)) n.\n  Proof.\n    induction n; cbn; eauto.\n    cbn in *; now rewrite IHn.\n  Qed.\n   \n  Lemma tab_plus X (f: nat -> X) n m:\n    tab f (n + m) = tab f n ++ tab (fun k => f (n + k)) m.\n  Proof.\n    induction n in f |-*; eauto.  \n    cbn [plus]; now rewrite tab_S, IHn, tab_S.\n  Qed.\n\n  Lemma tab_map_nats X k (f: nat -> X): tab f k = map f (nats k).\n  Proof.\n    induction k in f |-*; eauto.\n    cbn [nats map]; now rewrite tab_S, IHk, map_map.\n  Qed.\n\n  Lemma tab_id_nats k: tab id k = nats k.\n  Proof.\n    rewrite tab_map_nats; now lsimpl. \n  Qed.\n\n\n  Lemma tab_nth {X} n m (f: nat -> X):\n    n < m -> nth (tab f m) n = Some (f n).\n  Proof.\n    induction 1; cbn.\n    + rewrite nth_error_app2, tab_length, Nat.sub_diag; cbn; eauto.\n      rewrite tab_length; eauto.\n    + rewrite nth_error_app1; eauto.\n      now rewrite tab_length. \n  Qed.\n\n\n  Lemma tab_ext {X} (f g: nat -> X) n: (forall x, f x = g x) -> tab f n = tab g n.\n  Proof.\n    rewrite !tab_map_nats. intros; now apply map_ext.\n  Qed.\n\n\n\n\nEnd Tabulate.\n#[export] Hint Rewrite tab_length tab_id_nats : listdb. \n\n\n\n\n\n(* Repeated *)\nSection Repeated.\n  Variable (X Y: Type).\n  Implicit Types (x y: X) (n m: nat) (f: X -> Y). \n\n  Lemma repeated_in x n y: y ∈ repeat x n -> x = y.\n  Proof.\n    induction n; cbn; firstorder.\n  Qed.\n\n  Lemma repeated_plus n m x:\n    repeat x (n + m) = repeat x n ++ repeat x m.\n  Proof.\n    induction n; cbn; congruence.\n  Qed.\n  \n  Lemma repeated_rev n x: rev (repeat x n) = repeat x n.\n  Proof.\n    induction n; cbn; eauto.\n    rewrite IHn. change [x] with (repeat x 1).\n    rewrite <-repeated_plus.\n    rewrite Nat.add_comm. reflexivity.\n  Qed.\n\n  Lemma repeated_map n x f:\n    map f (repeat x n) = repeat (f x) n.\n  Proof.\n    induction n; cbn; congruence.\n  Qed.\n  \n  Lemma repeated_length n x: length (repeat x n) = n.\n  Proof.\n    induction n; cbn; congruence.\n  Qed.\n  \n\n  Lemma repeated_equal n y A:\n    (forall x, x ∈ A -> x = y) -> length A = n -> repeat y n = A.\n  Proof.\n    induction A in n |-*; destruct n; cbn; eauto; try discriminate.\n    injection 2. rewrite IHA; eauto.\n    intros. erewrite <-H; intuition easy.\n  Qed.\n\n  Lemma repeated_incl x n A:\n    x ∈ A -> repeat x n ⊆ A.\n  Proof.\n    intros ? ? ? % repeated_in; subst; eauto.\n  Qed.\n\n  \n  Lemma repeated_tab (x: X) n:\n    repeat x n = tab (Basics.const x) n.\n  Proof.\n    induction n; eauto; cbn [tab].\n    replace (S n) with (n + 1) by lia.\n    rewrite repeated_plus; cbn.\n    rewrite IHn; reflexivity. \n  Qed.\n\n\n\n  Lemma nth_error_repeated (x: X) n k :\n    k < n -> nth (repeat x n) k = Some x.\n  Proof.\n    intros H.\n    erewrite repeated_tab, tab_map_nats, map_nth_error; eauto.\n    now eapply nth_nats.\n  Qed.\n\n\n  Lemma repeated_app_inv n x A B:\n    repeat x n = A ++ B ->\n    n = length A + length B /\\\n    A = repeat x (length A) /\\\n    B = repeat x (length B).\n  Proof.\n    induction n in A, B |-*.\n    - cbn; destruct A, B; try discriminate. intuition easy.\n    - destruct A; cbn; try discriminate.\n      + destruct B; try discriminate. \n        injection 1. intuition idtac. cbn; now rewrite <-H0, repeated_length.\n        subst. cbn; now rewrite repeated_length.\n      + injection 1; intros; edestruct IHn; eauto. \n        intuition auto. f_equal; eauto. \n  Qed.         \n\nEnd Repeated.\n\n\n#[export] Hint Rewrite  repeated_length repeated_map repeated_plus repeated_rev: listdb.\n\n\n\n\n\n\n\n(* select *)\nSection Select.\n\n  Context {X: Type}.\n\n  Fixpoint select (A: list nat) (B: list X)  :=\n    match A with\n    | nil => nil\n    | i :: A => match nth B i with\n               | Some x => x :: select A B\n               | None => select A B \n               end\n    end.\n  \n  Lemma select_nil I:\n    select I nil = nil.\n  Proof.\n    induction I; cbn.\n    - reflexivity.\n    - destruct nth eqn: H; eauto.\n      eapply nth_error_In in H; cbn in H; intuition easy.\n  Qed.\n\n  Lemma select_S I (x: X) A:\n    select (map S I) (x :: A) = select I A.\n  Proof.\n    induction I.\n    - reflexivity.\n    - cbn. rewrite IHI. reflexivity. \n  Qed.\n  \n\n  Lemma select_nats k A:\n    select (nats k) A = firstn k A.\n  Proof.\n    induction k in A |-*.\n    - reflexivity.\n    - destruct A.\n      + rewrite select_nil; reflexivity.\n      + cbn. rewrite select_S, IHk. reflexivity.\n  Qed.\n\n\n  Lemma select_repeated n I x:\n    I ⊆ nats n -> select I (repeat x n) = repeat x (length I).\n  Proof.\n    induction I; cbn; eauto; intros.\n    rewrite IHI; eauto with listdb.\n    edestruct (nth_error_lt_Some) as [y H']; try rewrite H'.\n    eapply nats_lt; lsimpl; firstorder.\n    now eapply nth_error_In, repeated_in in H'; subst.\n  Qed.\n\n  Lemma select_incl I A: select I A ⊆ A.\n  Proof.\n    induction I; cbn; intuition (try easy).\n    destruct nth eqn: H1; intuition idtac.\n    eapply nth_error_In in H1. intuition (auto with datatypes).\n  Qed.\n\n  Lemma incl_select A B: A ⊆ B -> exists I, I ⊆ nats (length B) /\\ select I B = A.\n  Proof.\n    induction A.\n     + exists nil. lauto.\n     + intros; destruct IHA as [I []]; lauto. specialize (H a). mp H; lauto.\n        eapply In_nth_error in H as [i].\n        exists (i::I). cbn. rewrite H, H1. split; lauto.\n        eapply nth_error_Some_lt, lt_nats in H; lauto.\n  Qed.\nEnd Select.\n\n\nLemma select_map X Y (f: X -> Y) I A:\n  map f (select I A) = select I (map f A).\nProof.\n  induction I in A |-*; cbn; eauto.\n  rewrite nth_error_map_option.\n  destruct nth; cbn; now rewrite IHI.\nQed.\n    \n\n\n\n\n\n(* find *)\nSection Find.\n  \n  Context {X: Type}.\n  Context {D: Dis X}.\n\n  Fixpoint find (x: X) (A: list X) : option nat :=\n    match A with\n    | nil => None\n    | y :: A => if x == y then Some 0 else option_map S (find x A)\n    end.\n\n  Lemma find_Some x A n:\n    find x A = Some n -> nth A n = Some x.\n  Proof.\n    induction A in n |-*; cbn.\n    - discriminate.\n    - destruct (x == a).\n      injection 1; intros; subst. reflexivity.\n      destruct find; try discriminate.\n      cbn; injection 1; intros; subst.\n      cbn. now rewrite IHA.\n  Qed.\n\n\n  Lemma find_in x A:\n    x ∈ A -> exists n, find x A = Some n.\n  Proof.\n    induction A; cbn; intuition idtac.  \n    - exists 0. destruct (x == a); subst; intuition easy.\n    - destruct (x == a).\n      + subst; exists 0; intuition easy.\n      + destruct H as [m]; exists (S m); intuition idtac.\n        rewrite H; reflexivity.\n  Qed.\n\n  Lemma find_not_in x A:\n    find x A = None -> ~ x ∈ A.\n  Proof.\n    intros H [n H'] % find_in; rewrite H in H'; discriminate.\n  Qed.\n\nEnd Find.\n\nSection Remove.\n\n  Variable (X: Type) (D: Dis X).\n\n  Lemma remove_remain  (x y: X) A:\n    x ∈ A -> x <> y -> x ∈ remove eq_dec y A.\n  Proof.\n    induction A; cbn; intuition idtac; subst.\n    - destruct (y == x); subst; intuition (auto with datatypes).\n    - destruct (y == a); subst; intuition (auto with datatypes).\n  Qed.\n\n\n  Lemma remove_prev (x y: X) (A: list X):\n    y ∈ remove eq_dec x A -> y ∈ A.\n  Proof.\n    induction A; intuition idtac.\n    cbn in H. destruct (x == a); subst; intuition (auto with datatypes).\n    cbn in *; intuition easy.\n  Qed.\n\nEnd Remove.\n\n\nSection FlatMap.\n\n  Variable (X Y: Type).\n  Implicit Types (A B: list X) (f: X -> list Y).\n\n  Lemma flat_map_incl (f: X -> list Y) A B:\n    A ⊆ B -> flat_map f A ⊆ flat_map f B.\n  Proof.\n    intros H x [y []] % in_flat_map.\n    eapply in_flat_map; exists y; intuition auto.\n  Qed.\n\n  Lemma flat_map_in_incl f a A:\n    a ∈ A -> f a ⊆ flat_map f A.\n  Proof.\n    revert A; eapply in_ind; cbn; intuition (auto with datatypes).\n  Qed.\n\nEnd FlatMap.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/HOU/std/lists/advanced.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7414701398931678}}
{"text": "(* KENO FISCHER *)\n\n(* Collaborators: Jao-ke Chin-Lee *)\n\n(* CS250 Problem Set 0:  Basic Functional Programming in Coq \n\nDue:  Tuesday 9/9 at Midnight\n\nThe goal of this problem set is to just get you comfortable\nwith the basic syntax of Coq, using ProofGeneral or the CoqIDE\nin an interactive fashion, and to remember some basic functional\nprogramming.  \n\nFeel free to collaborate with each other, but make sure to do\nthe exercises yourself so you start to become familiar with the\nsyntax and the environment.  If you get stuck, as questions\non Piazza, or come see me (MD151) or one of the students in MD309\nto get un-stuck. \n\nComplete each of the definitions below, and add some test cases\n(using [Eval compute in <exp>.] to make sure they are working\nproperly.\n\nMake sure to push your solution back to your cloned repository,\nbut only after you've added your name!  \n*)\nRequire Import Arith.\nRequire Import List.\nImport ListNotations.\n\n\n(* 0. Write a function [length] to compute the length of list.\n      [length : forall {A:Type}, list A -> nat]\n*)\nFixpoint length {A:Type} (l:list A) : nat :=\n  match l with\n    | [] => 0\n    | (_::tl) => S (length tl)\n  end.\n\nEval compute in (length [1;2;3;4]).\n\n(* 1. Write a function [rev] that reverses a list.\n      [rev : forall {A:Type}, list A -> list A]\n*)\n\nFixpoint rev {A:Type} (l:list A) : list A :=\n  match l with\n    | [] => []\n    | (hd::tl) => (rev tl) ++ [hd]\n  end.\n\nEval compute in (rev [1;2;3;4]).\n\n(* 2. Write a function [ith] that returns the ith element of a list,\n      if the list has enough elements, and otherwise returns None.\n      We are working zero-based, so for instance, \n      [ith 2 (1::2::3::4::nil)] should return [Some 3], whereas\n      [ith 4 (1::2::3::4::nil)] should return None.\n\n      [ith : forall {A:type}, nat -> list A -> option A]\n*)\n\nFixpoint ith {A:Type} (n:nat) (l:list A) : option A :=\n  match n with\n    | 0 => find (fun (x:A) => true) l\n    | S k => (ith k (tail l))\n  end.\n\nEval compute in (ith 2 (1::2::3::4::nil)).\nEval compute in (ith 4 (1::2::3::4::nil)).\n\n(* 3. Write a generic function [comp] to compose two functions.\n      [comp : forall {A B C:Type}, (A -> B) -> (B -> C) -> (A -> C)]\n*)\nDefinition comp {A B C: Type} (f:A->B) (g:B->C) : (A->C) :=\n  (fun (x:A) => (g (f x))).\n\nDefinition add_pair (x:nat*nat) :=\n  (fst x)+(snd x).\n\nEval compute in ((comp (fun (x:nat*nat) => ((fst x),(add_pair x))) add_pair) (1,2)).\n\n(* 4. Write a function [sum] that adds up all of the [nat]s in a list.\n      [sum : list nat -> nat]\n*)\nFixpoint sum (l: list nat) : nat :=\n  match l with\n    | [] => 0\n    | hd::tl => hd + (sum tl)\n  end.\n\nEval compute in (sum [1;2;3;4]).\n\n(* 5. Write a function that [map] that maps a function over the \n      elements in a list, producing a new list.\n      [map : forall {A B:Type}, (A -> B) -> list A -> list B]\n*)\nFixpoint map {A B:Type} (f:A->B) (l:list A) : list B :=\n  match l with\n    | [] => []\n    | hd::tl => [(f hd)] ++ (map f tl)\n  end.\n\nEval compute in (map (fun (x:nat) => match x with\n    | 0 => 0\n    | S k => k\n    end) [0;1;2;3;4]).\n\n\n(* 6. Write a generic \"fold-right\" for a list such that, for instance.\n      [fold (fun x y => x + y) 0 (1::2::3::nil)] evaluates to [6].  \n      [fold : forall {A B:Type}, (A -> B -> B) -> B -> list A -> B] \n*)\nFixpoint fold {A B:Type} (f:(A->B->B)) (acc:B) (l:list A) : B :=\n  match l with\n    (* Not part of the recursion but for the empty case *)\n    | [] => acc\n    | (hd::tl) => (f hd (fold f acc tl))\n  end.\n\nEval compute in (fold (fun x y => x + y) 0 (1::2::3::nil)).\n\n(* 7. Write a function add_pairs that takes a list of pairs of nats and \n      returns the list of the corresponding sums.  For instance,\n      [add_pairs ((1,2)::(3,4)::nil)] should return [3::7::nil].\n      [add_pairs : list (nat * nat) -> list nat] \n*)\nDefinition add_pairs (l:list (nat * nat)) : list nat :=\n  (map (fun (p:(nat*nat)) => (add_pair p)) l).\n\nEval compute in (add_pairs ((1,2)::(3,4)::nil)).\n\n\n(* 8. Given the following definition for trees: *)\nInductive tree (A:Type) : Type := \n| Leaf : tree A\n| Node : tree A -> A -> tree A -> tree A.\n\nImplicit Arguments Leaf [A].  (* Ask Coq to synthesis the type argument to Leaf *)\nImplicit Arguments Node [A].  (* Ditto for Node *)\n\n(* 9. Write a function which flattens the tree into a list.\n      For instance, flatten on the tree:\n\n                   3\n                 /   \\\n                1     7\n              /  \\   /  \\\n             o    o o    o\n\n   should yield [1::3::7::nil].\n   [flatten : forall {A:Type}, tree A -> list A]\n*)\nFixpoint flatten {A:Type} (t:tree A) : list A :=\n  match t with\n    | Leaf => []\n    | (Node t1 x t2) => (flatten t1) ++ [x] ++ (flatten t2)\n  end.\n\nDefinition tree1:tree nat := (Node (Node Leaf 1 Leaf) 3 (Node Leaf 7 Leaf)).\nDefinition tree2 := (Node (Node Leaf 5 Leaf) 3 (Node Leaf 7 Leaf)).\nDefinition tree3 := (Node tree1 8 tree2).\n\nEval compute in (flatten tree1).\nEval compute in (flatten tree2).\nEval compute in (flatten tree3).\nEval compute in (flatten (@Leaf nat)).\n\nInductive order : Type := \n| Less \n| Equal\n| Greater.\n\n(* 11. Write a function which when given two numbers n and m,\n       returns [Less] if n < m, [Equal] if n = m, and otherwise\n       returns [Greater].  \n       [nat_cmp : nat -> nat -> order] *)\n\nFixpoint nat_cmp (a:nat) (b:nat) : order :=\n  match a,b with \n    | 0, S k    => Less\n    | 0, 0      => Equal\n    | S k, 0    => Greater\n    | S x, S y  => (nat_cmp x y)\n  end.\n\nNotation \"a < b\" :=\n  match (nat_cmp a b) with Less => true | _ => false end.\n\nEval compute in (1 < 2).\nEval compute in (nat_cmp 2 2).\nEval compute in (nat_cmp 3 2).\n\n(* 12. Write a function that determines whether a [tree nat] is\n       a valid search tree in the sense that for a given node\n       with value [n], all elements in the left sub-tree should \n       be less than [n] and all elements in the right sub-tree\n       should be greater than [n].  \n       [search_tree : tree nat -> bool]\n*)\n\nDefinition helper (a:nat) (p:bool*nat*bool) :=\n  let '(acc,b,first) := p in ((orb first (andb acc (a<b))),a,false).\n\nDefinition search_tree (t: tree nat) : bool :=\n  (fst (fst (fold helper (true,0,true) (flatten t)))).\n\nEval compute in (search_tree tree1).\nEval compute in (search_tree tree2).\nEval compute in (search_tree tree3).\n\n", "meta": {"author": "Keno", "repo": "CS250", "sha": "5865c43b99d3acee956d610475445894851397f6", "save_path": "github-repos/coq/Keno-CS250", "path": "github-repos/coq/Keno-CS250/CS250-5865c43b99d3acee956d610475445894851397f6/pset0/pset0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7414701397189108}}
{"text": "(*Javier Enríquez Mendoza*)\n\nRequire Import Arith.\n\nFixpoint compara (n m : nat) : comparison :=\nmatch n, m with\n| 0, 0 => Eq\n| S n', 0 => Gt\n| 0 , S m' => Lt\n| S n', S m' => compara n' m'\nend.\n\nTheorem eq : forall (n m : nat),compara n m = Eq <-> n = m.\nProof.\ninduction n.\ndestruct m; split;trivial.\ndiscriminate.\ndiscriminate.\ndestruct m.\nsplit; discriminate.\nsimpl.\ndestruct IHn with m.\nsplit.\nintros.\napply H in H1.\nrewrite H1.\ntrivial.\nintros.\ninversion H1.\nrewrite H3 in H0.\napply H0.\ntrivial.\nQed.\n\nTheorem Lt : forall (n m : nat), compara n m = Lt <-> n < m.\nProof.\ninduction n; destruct m; split; intro.\ndiscriminate H.\nunfold lt in H.\ninversion H.\nunfold lt.\napply le_n_S.\napply le_0_n.\nreflexivity.\nsimpl in H.\ndiscriminate H.\ninversion H.\nsimpl in H.\nunfold lt.\nunfold lt in IHn.\napply le_n_S.\napply IHn.\ntrivial.\nunfold lt in IHn.\ndestruct IHn with m.\nunfold lt in H.\napply le_S_n in H.\napply H1 in H.\nsimpl.\ntrivial.\nQed.\n\nTheorem Gt : forall (n m : nat), compara n m = Gt <-> n > m.\nProof.\ninduction n; destruct m; split; intro.\ndiscriminate H.\nunfold gt in H.\nunfold lt in H.\ninversion H.\ndiscriminate H.\nunfold gt in H.\nunfold lt in H.\ninversion H.\nunfold gt.\nunfold lt.\napply le_n_S.\napply le_0_n.\nreflexivity.\ndestruct IHn with m.\nsimpl in H.\napply H0 in H.\nunfold gt in H.\nunfold gt.\nunfold lt in H.\nunfold lt.\napply le_n_S.\ntrivial.\nsimpl.\nunfold gt in H.\nunfold gt in IHn.\nunfold lt in H.\nunfold lt in IHn.\napply le_S_n in H.\napply IHn in H.\ntrivial.\nQed.\n", "meta": {"author": "jaeem006", "repo": "Semantica", "sha": "fdfdf544dd2d30b2f03a82849d78879762d48811", "save_path": "github-repos/coq/jaeem006-Semantica", "path": "github-repos/coq/jaeem006-Semantica/Semantica-fdfdf544dd2d30b2f03a82849d78879762d48811/javier_Enriquez_ejs7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7413608707280689}}
{"text": "Require Import ZArith Arith Bool Omega.\n\nLtac caseEq f :=\n  generalize (refl_equal f); pattern f at -1; case f.\n\nOpen Scope Z_scope.\n\n(* The key to this corollary is that if s=Zsqrt_plain x, then\n  s*s < (s+1) * (s+1), as stated by the companion theorem\n  Zsqrt_interval, and the squaring operation is monotonic only\n  for positive values. *)\nTheorem sqrt_plain_pos : forall x:Z, 0 <= Zsqrt_plain x.\nProof.\n intros x; case x.\n simpl; auto with zarith.\n\n intros p.\n cut (0 < 2* Zsqrt_plain(Zpos p) + 1).\n intros; omega.\n\n replace (2* Zsqrt_plain(Zpos p) + 1) with\n   ((Zsqrt_plain (Zpos p) + 1)*(Zsqrt_plain (Zpos p) + 1) -\n   Zsqrt_plain (Zpos p) * Zsqrt_plain (Zpos p)).\n lapply (Zsqrt_interval (Zpos p)).\n omega.\n auto with zarith.\n ring.\n\n simpl; auto with zarith.\nQed.\n\n\n\nTheorem div_Zsqrt :\n forall m n p:Z, 0 < m < n ->\n  n=m*p-> 0 < m <= Zsqrt_plain n \\/ 0 < p <= Zsqrt_plain n.\nProof.\n intros m n p Hint Heq.\n elim (Z_lt_le_dec (Zsqrt_plain n) m); \n elim (Z_lt_le_dec (Zsqrt_plain n) p).\n intros Hltm Hltp.\n assert (Hlem : (Zsqrt_plain n)+1 <= m).\n omega.\n assert (Hlep : (Zsqrt_plain n)+1 <= p).\n omega.\n elim (Zlt_irrefl n).\n apply Zlt_le_trans with (((Zsqrt_plain n)+1)*((Zsqrt_plain n)+1)).\n assert (Hposn : 0 <= n).\n omega.\n Check Zsqrt_interval.\n generalize (Zsqrt_interval n); intuition.\n pattern n at 3; rewrite Heq.\n\n apply Zmult_le_compat; try omega.\n\n generalize (sqrt_plain_pos n); omega.\n\n generalize (sqrt_plain_pos n); omega.\n\n intros Hple _; right; split; auto.\n\n apply Zmult_lt_0_reg_r with m; try tauto.\n rewrite Zmult_comm; omega.\n\n intros _ Hmle; left; split; tauto.\n intros _ Hmle; left; split; tauto.\nQed.\n\nDefinition divides_bool (p t:Z) : bool :=\n match t mod p with\n   0 => true\n | _ => false\n end.\n\nFixpoint test_odds (n:nat) (p t:Z) {struct n} : bool :=\n match n with\n   0%nat => negb (divides_bool 2 t)\n | S n' =>\n   if test_odds n' (p - 2) t then negb (divides_bool p t) else false\n end.\n\n\nDefinition prime_test (n:nat) : bool :=\n match n with\n   0%nat => false\n | 1%nat => false\n | S (S n) => \n  let x := (Z_of_nat (S (S n))) in\n  let s := (Zsqrt_plain x) in\n  let (half_s, even_bit) :=\n    match s with\n    | Zpos(xI h) => (Zpos h, 0)\n    | Zpos(xO h) => (Zpos h, 1)\n    | Zpos xH => (0, 0)\n    | _ => (0, 1)  \n    end  in\n  test_odds (Zabs_nat half_s) (s + even_bit) x\n end.\n\nTime Eval lazy beta iota delta zeta in (prime_test 2333).\n\n(* Time Eval compute in (prime_test 2333). \n \n  This command takes a much longer time.  The reason is that Zsqrt_plain\n  calls a strongly specified function, which builds a proof term that is\n  large, but is discarded later.  Lazy computation avoid the useless \n  work. *)\n\n(* we use the same axiom as in the book, it is corrected in another exercise.\n *)\n\nAxiom verif_divide :\n  (forall m p:nat, 0 < m -> 0 < p ->\n   (exists q:nat, m = q*p) ->(Z_of_nat m mod Z_of_nat p = 0)%Z )%nat.\n\n(* This axiom is actually a lemma used in the same other exercise. *)\n\nAxiom Z_to_nat_and_back :\n forall x:Z, (0 <= x)%Z -> (Z_of_nat (Zabs_nat x))=x.\n\nTheorem test_odds_correct2 :\n  forall n x:nat,\n    (1 < x)%nat ->\n  forall p:Z,\n    test_odds n p (Z_of_nat x) = true ->\n    ~(exists y:nat, x = y*2)%nat.\nProof.\n intros n; elim n.\n unfold test_odds, divides_bool; intros x H1ltx _ Heq Hex.\n assert (Heq' : Z_of_nat x mod Z_of_nat 2 = 0).\n apply verif_divide; auto with zarith.\n simpl (Z_of_nat 2) in Heq'; rewrite Heq' in Heq; simpl in Heq; discriminate.\n\n clear n; intros n IHn x H1ltx p; simpl.\n caseEq (test_odds n (p - 2) (Z_of_nat x)).\n intros Htest' _ ; apply (IHn x H1ltx (p -2)); auto.\n intros; discriminate.\nQed.\n\nTheorem Z_of_nat_le :\n  forall x y, Z_of_nat x <= Z_of_nat y -> (x <= y)%nat.\nProof.\n intros; omega.\nQed.\n\n\nTheorem test_odds_correct :\n  forall (n x:nat)(p:Z),\n   p = 2*(Z_of_nat n)+1 ->\n   (1 < x)%nat -> test_odds n p (Z_of_nat x) = true -> \n   forall q:nat, (1 < q <= 2*n+1)%nat -> ~(exists y:nat, x = q*y)%nat.\nProof.\n induction n.\n intros x p Hp1 H1ltx Hn q Hint.\n assert (H:False).\n omega.\n elim H.\n\n intros x p Hp H1ltx; simpl (test_odds (S n) p (Z_of_nat x));\n intros Htest q (H1ltq, Hqle).\n caseEq (test_odds n (p -2) (Z_of_nat x)).\n intros Htest'true.\n rewrite Htest'true in Htest.\n unfold divides_bool in Htest.\n elim (le_lt_or_eq q (2*S n + 1)%nat Hqle).\n intros Hqlt.\n assert (Hqle': (q <= (2* S n))%nat).\n omega.\n elim (le_lt_or_eq q (2 * S n)%nat Hqle').\n replace (2*S n)%nat with (2*n +2)%nat.\n intros Hqlt'.\n assert (Hqle'' : (q <= 2*n +1)%nat).\n omega.\n apply (IHn x (p - 2)); auto with zarith arith.\n rewrite Hp; rewrite inj_S; unfold Zsucc; ring.\n ring.\n intros Hq (y, Hdiv); elim (test_odds_correct2 n x H1ltx (p - 2)); auto.\n exists (S n * y)%nat; rewrite Hdiv; rewrite Hq; ring.\n\n intros Hq Hex; assert (Hp' : p = Z_of_nat q).\n rewrite Hp; rewrite Hq; rewrite inj_plus; rewrite inj_mult; auto.\n rewrite Hp' in Htest; rewrite (verif_divide x q) in Htest.\n simpl in Htest; discriminate.\n omega.\n omega.\n elim Hex; intros y Hdiv; exists y; rewrite Hdiv; ring.\n intros Htest'; rewrite Htest' in Htest; simpl in Htest; discriminate.\nQed.\n\nAxiom divisor_smaller :\n  (forall m p:nat, 0 < m -> forall q:nat, m = q*p -> q <= m)%nat.\n\n\nTheorem lt_Zpos : forall p:positive, 0 < Zpos p.\nProof.\n intros p; elim p.\n intros; rewrite Zpos_xI; omega.\n intros; rewrite Zpos_xO; omega.\n auto with zarith.\nQed.\n\nTheorem Zneg_lt : forall p:positive, Zneg p < 0.\nProof.\n intros p; elim p.\n intros; rewrite Zneg_xI; omega.\n intros; rewrite Zneg_xO; omega.\n auto with zarith.\nQed.\n\n\nTheorem prime_test_correct :\n forall n:nat, prime_test n = true ->\n ~(exists k:nat, k <> 1 /\\ k <> n /\\ (exists q:nat, n = q*k))%nat.\nProof.\n intros n.\n caseEq n.\n\n simpl;  intros Heq Hd; discriminate.\n intros n0; caseEq n0.\n simpl; intros Heq1 Heq2 Hd; discriminate.\n\n unfold prime_test; intros n1 Heqn0 Heqn.\n assert (H1ltn : (1 < n)%nat).\n rewrite Heqn; auto with arith.\n\n rewrite <- Heqn.\n lazy beta zeta delta [prime_test].\n caseEq (Zsqrt_plain (Z_of_nat n)).\n intros Hsqrt_eq.\n elim (Zlt_asym 1 (Z_of_nat n)).\n omega.\n lapply (Zsqrt_interval (Z_of_nat n)).\n rewrite Hsqrt_eq; simpl.\n omega.\n omega.\n\n intros p Hsqrt_eq Htest_eq (k, (Hn1, (Hnn, (q,Heq)))).\n assert (H0ltn:(0 < n)%nat).\n omega.\n\n assert (Hkltn:(k < n)%nat).\n assert (Heq' : n=(k*q)%nat).\n rewrite Heq; ring.\n\n generalize (divisor_smaller n q H0ltn k Heq'). \n omega.\n\n assert (Hex: exists k':nat, (1 < (Z_of_nat k') <= (Zsqrt_plain (Z_of_nat n))) /\\\n               (exists q':nat, n=(k'*q')%nat)).\n elim (div_Zsqrt (Z_of_nat k) (Z_of_nat n) (Z_of_nat q)).\n\n intros Hint1; exists k;split.\n omega.\n exists q; rewrite Heq; ring.\n\n intros Hint2; exists q; split.\n split.\n elim (Zle_or_lt (Z_of_nat q) 1); auto.\n\n intros hqle1.\n assert (Hq1: q = 1%nat).\n omega.\n\n rewrite Hq1 in Heq; simpl in Heq; elim Hnn; rewrite Heq; ring.\n tauto.\n\n exists k; auto.\n\n split.\n caseEq k.\n intros Hk0; rewrite Hk0 in Heq; rewrite Heq in H1ltn; rewrite mult_0_r in H1ltn;\n omega.\n\n intros; unfold Zlt; simpl; auto.\n\n omega.\n\n rewrite Zmult_comm; rewrite <- inj_mult; rewrite Heq;auto.\n\n elim Hex; intros k' ((H1ltk', Hk'ltsqrt), Hex'); clear Hex.\n\n caseEq p.\n\n intros p' Hp; rewrite Hp in Htest_eq.\n\n elim (test_odds_correct (Zabs_nat (Zpos p'))\n           n (Zpos p)) with k'.\n\n rewrite Z_to_nat_and_back.\n\n rewrite Hp.\n auto with zarith.\n auto with zarith.\n auto.\n\n repeat rewrite Zminus_0_r in Htest_eq.\n rewrite Hp; auto.\n split.\n omega.\n\n apply Z_of_nat_le.\n\n rewrite inj_plus.\n rewrite inj_mult.\n rewrite Z_to_nat_and_back.\n simpl (Z_of_nat 2).\n simpl (Z_of_nat 1).\n rewrite <- Zpos_xI.\n rewrite <- Hp.\n rewrite <- Hsqrt_eq; auto.\n\n auto with zarith.\n auto.\n\n intros p' Hp; rewrite Hp in Htest_eq.\n\n elim (test_odds_correct (Zabs_nat (Zpos p')) n (Zpos p + 1))\n  with k'.\n\n rewrite Z_to_nat_and_back.\n rewrite Hp; rewrite Zpos_xO; ring.\n\n generalize (lt_Zpos p'); intros; omega.\n \n auto.\n\n rewrite <- Hp in Htest_eq; auto.\n\n split; try omega.\n\n apply Z_of_nat_le.\n\n rewrite inj_plus.\n rewrite inj_mult.\n rewrite Z_to_nat_and_back.\n\n simpl (Z_of_nat 2); simpl (Z_of_nat 1).\n rewrite <- Zpos_xO.\n rewrite <- Hp; omega.\n\n auto with zarith.\n auto.\n\n intros Hp; rewrite Hp in Hsqrt_eq.\n rewrite Hsqrt_eq in Hk'ltsqrt.\n\n omega.\n\n intros p Hsqrt_eq.\n elim (Zle_not_lt 0 (Zsqrt_plain (Z_of_nat n))).\n\n apply sqrt_plain_pos.\n\n rewrite Hsqrt_eq.\n\n apply Zneg_lt.\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/reflection/SRC/prime_sqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7413608668533087}}
{"text": "Require Export Lci.\nRequire Export misc.\n\nSection groups.\n\nVariable S : Set.\nVariable G : S -> Prop.\nVariable Add : S -> S -> S.\nVariable O : S.\nVariable Opp : S -> S.\n\nDefinition is_group :=\n  intern S G Add /\\\n  associativity S Add /\\ neutral S G Add O /\\ opposite S G Add O Opp. \n\nLemma regular_l :\n is_group ->\n forall y z : S,\n G y -> G z -> forall x : S, G x -> Add x y = Add x z -> y = z.\nProof.\nintros.\nelim H; intros; elim H5; intros; elim H7; intros; elim H8; intros. \nclear H4 H5 H7 H10.\n(* use of neutral *)\nelim (H11 y H0); intros; elim H5; clear H4 H5.\nelim (H11 z H1); intros; elim H5; clear H4 H5 H8 H11.\n(* use of opposite *)\nelim (H9 x H2); intros; elim H5; intros; elim H8; intros; elim H11. \nclear H4 H5 H7 H8 H9 H10 H11.\n(* use of associativity *)\nelim (H6 (Opp x) x y); elim (H6 (Opp x) x z).\nelim H3; reflexivity.\nQed.\n\nLemma add_add :\n commutativity S Add ->\n associativity S Add ->\n forall x1 y1 x2 y2 : S,\n Add (Add x1 y1) (Add x2 y2) = Add (Add x1 x2) (Add y1 y2).\nProof.\nintros com ass x1 y1 x2 y2.\nrewrite (ass (Add x1 y1) x2 y2); elim (ass x1 y1 x2); elim (com x2 y1).\nrewrite (ass x1 x2 y1); elim (ass (Add x1 x2) y1 y2); reflexivity.\nQed.\n\nLemma opp_unicity :\n is_group -> forall x y : S, is_opposite S G Add O x y -> y = Opp x.\nProof.\nintros.\n(* [G y] *)\nelim H0; intros; elim H2; intros.\n(* [y = 0+y] *)\nelim H; intros; elim H6; intros; elim H8; intros; elim H9; intros.\nelim (H12 y H3); intros; elim H14; clear H H2 H3 H5 H6 H8 H11 H12 H13 H14.\n(* [0=(-x)+x] *)\nelim (H10 x H1); intros; elim H2; intros; elim H5; intros; elim H8.\nclear H H1 H2 H5 H6 H8 H10.\n(* [((-x)+x)+y=(-x)+(x+y)] *)\nelim (H7 (Opp x) x y).\n(* [x+y = 0] *)\nelim H4; intros; rewrite H; clear H H0 H1 H4 H7.\n(* [(-x)+0=(-x)] *)\nelim H9; intros; elim (H0 (Opp x) H3); intros. exact H1.\nQed.\n\nLemma opp_opp : is_group -> forall x : S, G x -> x = Opp (Opp x).\nProof.\nintros.\napply (opp_unicity H (Opp x) x).\nunfold is_opposite in |- *; split.\nelim H; intros; elim H2; intros; elim H4; intros; elim (H6 x H0); intros. \nelim H8; trivial.\nelim H; intros; elim H2; intros; elim H4; intros; elim (H6 x H0); intros.\nelim H8; intros; elim H10; auto.\nQed.\n\nLemma opp_add :\n is_group ->\n commutativity S Add ->\n forall x y : S, G x -> G y -> Opp (Add x y) = Add (Opp x) (Opp y).\nProof.\nintros; symmetry  in |- *;\n apply (opp_unicity H (Add x y) (Add (Opp x) (Opp y))).\nunfold is_opposite in |- *; split.\n(* [G (x+y)] *)\nelim H; intros; apply (H3 x y H1 H2).\nsplit.\n(* [G ((-x)+(-y))] *)\nelim H; intros; elim H4; intros; elim H6; intros; clear H4 H5 H6 H7.\nelim (H8 x H1); intros; elim H5; intros; clear H4 H5 H7.\nelim (H8 y H2); intros; elim H5; intros.\napply (H3 (Opp x) (Opp y) H6 H7).\n(* [(x+y)+((-x)+(-y)) = 0 & ((-x)+(-y))+(x+y) = 0] *)\nelim H; intros; elim H4; intros; clear H3 H4 H6.\nrewrite (add_add H0 H5 x y (Opp x) (Opp y)).\nrewrite (add_add H0 H5 (Opp x) (Opp y) x y); clear H5.\nelim H; intros; elim H4; intros; elim H6; intros. \n  (* [x+(-x) = 0 (-x)+x = 0] *)\nelim (H8 x H1); intros; elim H10; intros; elim H12; intros. \nrewrite H13; rewrite H14.\nclear H H0 H1 H3 H4 H5 H6 H9 H10 H11 H12 H13 H14.\n  (* [y+(-y) = 0 (-y)+y = 0] *)\nelim (H8 y H2); intros; elim H0; intros; elim H3; intros. \nrewrite H4; rewrite H5.\nclear H H0 H1 H2 H3 H4 H5 H8.\n  (* [0+0 = 0] *)\nelim H7; intros; exact (H0 O H).\nQed.\n\nLemma opp_neutral : is_group -> Opp O = O.\nProof.\nintros.\nelim (opp_unicity H O O).\nreflexivity.\nunfold is_opposite in |- *.\nelim H; intros; elim H1; intros; elim H3; intros; elim H4; intros.\nelim (H7 O H6); auto.\nQed.\n\nEnd groups.\n", "meta": {"author": "coq-contribs", "repo": "zchinese", "sha": "dcf20f2c95bcd026b1c49d658cd6ae5283b43655", "save_path": "github-repos/coq/coq-contribs-zchinese", "path": "github-repos/coq/coq-contribs-zchinese/zchinese-dcf20f2c95bcd026b1c49d658cd6ae5283b43655/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7412448314185949}}
{"text": "(* Implementation and correctness proof for insertion sort.\n  Andrew W. Appel, January 2010. *)\n\nRequire Import Permutation.\nRequire Import SfLib.\n\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\nTheorem ble_nat_refl: forall m, ble_nat m m = true.\nProof.\n  intros. induction m as [| m'].\n  Case \"m = 0\".\n  reflexivity.\n  Case \"m = S m'\".\n  apply IHm'.\nQed.\n\nTheorem ble_nat_i: forall n m, n <= m -> ble_nat n m = true.\nProof.\ninduction n as [|n']; intros; simpl; auto.\ndestruct m.\nelimtype False.\nomega.\napply IHn'.\nomega.\nQed.\n\nTheorem false_ble_nat_i:  forall n m, n > m -> ble_nat n m = false.\nProof.\nintros.\nremember (ble_nat n m) as p; destruct p; auto.\nsymmetry in Heqp; apply ble_nat_true in Heqp; elimtype False; omega.\nQed.\n\nTheorem false_ble_nat_e: forall n m, ble_nat n m = false -> n > m.\nProof.\nintros.\nassert (n <= m \\/ n > m) by omega.\ndestruct H0; auto.\napply ble_nat_i in H0.\nrewrite H0 in H.\ninversion H.\nQed.\n\n(* PART I.   Prove correctness of functional program for insertion sort  *)\n\nFixpoint insert (i:nat) (l: list nat) :=\n  match l with\n  | nil => i::nil\n  | h::t => if ble_nat i h then i::h::t else h :: insert i t\n end.\n\nFixpoint sort (l: list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h::t => insert h (sort t)\nend.\n\nExample sort_pi: sort [3,1,4,1,5,9,2,6,5,3,5] = [1,1,2,3,3,4,5,5,5,6,9].\nProof.\nsimpl.\nreflexivity.\nQed.\n\n(** **** Exercise: 3 stars *)\n\n(* Prove an auxiliary lemma insert_perm, useful for proving sort_perm.\n  You may want to get into the proof of sort_perm first, to see what you'll need.  *)\nTheorem insert_perm_l: forall l i, Permutation (i::l) (insert i l).\nProof.\n  intros. induction l as [| x xs].\n  reflexivity.\n  simpl. destruct (ble_nat i x).\n    reflexivity.\n    rewrite <- IHxs. apply perm_swap.\nQed.\n\nTheorem insert_perm: forall l l' i,\n  Permutation l l' -> Permutation (i::l) (insert i l').\nProof.\n  intros. destruct l' as [| y ys].\n    simpl. apply perm_skip. apply H.\n    destruct l.\n      apply Permutation_nil in H. rewrite H. reflexivity.\n      rewrite H. apply insert_perm_l.\nQed.\n\n(** **** Exercise: 3 stars *)\n(* Now prove the main theorem. *)\nTheorem sort_perm: forall l, Permutation l (sort l).\nProof.\n  intros. induction l as [| x xs].\n    reflexivity.\n    apply insert_perm. assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars *)\n(* Define an inductive predicate \"sorted\" that tells whether a list of nats is in nondecreasing order.\n   Then prove that \"sort\" produces a sorted list.\n*)\nInductive sorted: list nat -> Prop :=\n  | sorted_nil : sorted []\n  | sorted_cons1 x : sorted [x]\n  | sorted_cons x y l : sorted (y::l) -> ble_nat x y = true -> sorted (x::y::l).\n\nTheorem sorted_zero: forall l, sorted l -> sorted (0 :: l).\nProof.\n  intros. induction l as [| x xs].\n    apply sorted_cons1.\n    inversion H.\n      apply sorted_cons.\n        apply sorted_cons1.\n        reflexivity.\n      rewrite H1.\n      apply sorted_cons.\n        apply H.\n        reflexivity.\nQed.\n\nTheorem sorted_rest: forall l i, sorted (i :: l) -> sorted l.\nProof.\n  intros. induction l as [| x xs].\n    apply sorted_nil.\n    inversion H. apply H2.\nQed.\n\nTheorem ble_nat_flip: forall i x, ble_nat i x = false -> ble_nat x i = true.\nProof.\n  intros. generalize dependent x.\n  induction i as [| i'].\n  Case \"i = 0\".\n  destruct x.\n    reflexivity.\n    intros. inversion H.\n  Case \"i = S i'\".\n  induction x.\n    reflexivity.\n    intros. simpl. apply IHi'.\n    inversion H. reflexivity.\nQed.\n\nTheorem insert_sorted: forall l i, sorted l -> sorted (insert i l).\nProof.\n  intros.\n  induction l as [| x xs].\n    simpl. constructor.\n    simpl. destruct (ble_nat i x) eqn:Heqe.\n      constructor. assumption. assumption.\n      inversion H; subst.\n        simpl. constructor. constructor.\n          apply ble_nat_flip. apply Heqe.\n        simpl. simpl in IHxs.\n        simpl. destruct (ble_nat i y) eqn:Heqe2.\n          constructor.\n          constructor. apply H2. apply Heqe2.\n          apply ble_nat_flip. apply Heqe.\n          constructor. apply IHxs. apply H2. apply H3.\nQed.\n\n(* You may want to first prove an auxiliary lemma about inserting an element\n   into a sorted list.  *)\nTheorem sort_sorted: forall l, sorted (sort l).\nProof.\n  intros. induction l as [| x xs].\n    apply sorted_nil.\n    apply insert_sorted. apply IHxs.\nQed.\n(** [] *)\n", "meta": {"author": "B-Rich", "repo": "vfa", "sha": "30fb3e6b13f949ce8b88c0159f7d2a4e726136c7", "save_path": "github-repos/coq/B-Rich-vfa", "path": "github-repos/coq/B-Rich-vfa/vfa-30fb3e6b13f949ce8b88c0159f7d2a4e726136c7/Sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.8872046011730964, "lm_q1q2_score": 0.7412448310539361}}
{"text": "(* Basics *)\n\n(* Days of week *)\nInductive 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\nCompute (next_weekday friday).\n\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday :\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\n(*\n* The assertion we've just made can be proved by observing \n* that both sides of the equality evaluate to the same thing, \n* after some simplification.\n*)\n\n(* Booleans *)\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\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\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise: nandb *)\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  negb (b1 && b2).\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\n(* Exercise: andb3 *)\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  (andb (andb b1 b2) b3).\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\n(* Function Types *)\n\nCheck true.\n\nCheck (negb true).\n\nCheck negb.\n\nModule Playground1.\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\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\nCheck (S (S (S (S O)))).\nCompute (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 1 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_oddb2: oddb 2 = 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.\n\nCompute (plus 3 2).\n\nFixpoint mult (n m : nat) : nat := \nmatch 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\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\n(* Exercise: factorial *)\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => mult (S n') (fact n')\n  end.\n\nNotation \"x + y\" := (plus x y)\n  (at level 50, left associativity)\n  : nat_scope.\n\nNotation \"x - y\" := (minus x y)\n  (at level 50, left associativity)\n  : nat_scope.\n\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\nend.\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.\nCheck leb.\n\nExample test_leb1: (leb 2 2) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_leb2: (leb 2 4) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_leb3: (leb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise: blt_nat *)\nDefinition blt_nat (n m : nat) : bool :=\n  (leb n m) && (negb (beq_nat n m)).\n\nExample test_blt_nat1: (blt_nat 2 2) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat2: (blt_nat 2 4) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat3: (blt_nat 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Proof by Simplification *)\n(* use simpl to simplify both sides of the equation, then use reflexivity to check that both sides contain identical values. *)\n\nTheorem plus_0_n' : forall n : nat, 0 + n = n.\nProof. intros n. simpl. reflexivity. Qed.\n\nTheorem plus_1_l : forall n : nat, 1 + n = S n.\nProof. intros n. reflexivity. Qed.\n\nTheorem mult_0_l : forall n : nat, 0 * n = 0.\nProof. intros n. reflexivity. Qed.\n\n(* Proof by Rewriting *)\nTheorem plus_id_example : forall n m : nat,\n  n = m -> n + n = m + m.\nProof.\n  (* move both the quantifiers into the context *)\n  intros n m.\n  (* move the hypothesis into the context *)\n  intros H.\n  (* rewrite the goal using the hypothesis *)\n  rewrite -> H.\n  reflexivity. \nQed.\n\n(*\nThe first line of the proof moves the universally quantified variables n and m into the context. \nThe second moves the hypothesis n = m into the context and gives it the name H. \nThe third tells Coq to rewrite the current goal (n + n = m + m) by replacing the left side of the equality hypothesis H with the right side. \n*)\n\n(* Exercise 1*)\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.\n  rewrite -> H2.\n  reflexivity. \nQed.\n\n(* Exercise 2*)\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  reflexivity. \nQed.\n\n(* Proof by Case Analysis *)\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. \nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b.\n  destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative : 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(* Exercise *)\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct c.\n    - reflexivity. \n    - rewrite <- H.\n      destruct b.\n      + reflexivity. \n      + reflexivity.\nQed.\n\n(*\nIt tells Coq what variable names to introduce in each subgoal. In general, what goes between the square brackets is a list of lists of names, separated by |. In this case, the first component is empty, since the O constructor is nullary (it doesn't have any arguments). The second component gives a single name, n', since S is a unary constructor.  *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  destruct n as [| n']. (* intro pattern *)\n  - reflexivity.\n  - reflexivity.\nQed.\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 f H.\n  destruct b.\n  - rewrite H. rewrite H. reflexivity.\n  - rewrite H. rewrite H. 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 f H.\n  destruct b.\n  - rewrite H. rewrite H. reflexivity.\n  - rewrite H. rewrite H. reflexivity.\nQed.\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  unfold andb.\n  intros H.\n  destruct b.\n  - rewrite H. reflexivity.\n  - rewrite H. reflexivity.\nQed.\n\nInductive bin : Type :=\n| Zero : bin\n| TwiceOf : bin -> bin\n| OneMoreTwiceOf : bin-> bin.\n\nFixpoint incr (b : bin) : bin :=\nmatch b with\n| Zero => OneMoreTwiceOf Zero\n| TwiceOf b' => OneMoreTwiceOf b'\n| OneMoreTwiceOf b' => TwiceOf (incr b')\nend.\n\n(* \n0 => Zero\n1 => OneMoreTwiceOf Zero\n10 => TwiceOf (OneMoreTwiceOf Zero)\n11 => OneMoreTwiceOf (OneMoreTwiceOf Zero)\n*)\n\nFixpoint bin_to_nat (b : bin) : nat :=\nmatch b with\n| Zero => O\n| TwiceOf b' => 2 * (bin_to_nat b')\n| OneMoreTwiceOf b' => 1 + 2 * (bin_to_nat b')\nend.\n\nExample test_bin_incr1 : (bin_to_nat Zero) = 0.\nProof. reflexivity. Qed.\nExample test_bin_incr2 : (bin_to_nat (incr Zero)) = 1.\nProof. reflexivity. Qed.\nExample test_bin_incr3 : (bin_to_nat (incr (incr Zero))) = 2.\nProof. reflexivity. Qed.\nExample test_bin_incr4 : (bin_to_nat (incr (incr (incr Zero)))) = 3.\nProof. reflexivity. Qed.\nExample test_bin_incr5 : (bin_to_nat (incr (incr (incr (incr Zero))))) = 4.\nProof. reflexivity. Qed.\n", "meta": {"author": "Kraks", "repo": "playground", "sha": "677da3823615d4e241f7d1de05ee9b79ddabb118", "save_path": "github-repos/coq/Kraks-playground", "path": "github-repos/coq/Kraks-playground/playground-677da3823615d4e241f7d1de05ee9b79ddabb118/coq/sf_sol/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7412448302760344}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf1 : natural) : natural :=\n  plus lf1 (mult z y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj281_coqofml_XieM5C.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.741242213836445}}
{"text": "Require Import Arith.\nRequire Import Omega.\n\nPrint nat_rect.\n\nDefinition mod3_rect:=\n  fun (P:nat -> Type) \n      (f0:P 0) \n      (f1:P 1)\n      (f2:P 2)\n      (fk:forall k,P k -> P (S (S (S k)))) => \n    fix F (n:nat) :P n:=\n       match n as i return (P i) with\n         | 0 => f0\n         | 1 => f1\n         | 2 => f2\n         | (S (S (S i))) => fk i (F i)\n       end.\n\nDefinition mod3_ind:=\n  fun (P:nat -> Prop)=> mod3_rect P.\n\nFixpoint mod3 n:=\n  match n with\n    | S (S (S k)) => mod3 k\n    | _ => n\n  end.\n\nDefinition pow2 (n:nat):= n*n.\n\nLemma mod3_lt_3:\n  forall n,mod3 n < 3.\nProof.\n  induction n using mod3_ind;simpl;omega.\nQed.\n\nLemma mod3_dec:\n  forall n,{mod3 n = 0} + {mod3 n = 1} + {mod3 n = 2}.\nProof.\n  intros n.\n  induction n using mod3_rect.\n  - left;left;reflexivity.\n  - left;right;reflexivity.\n  - right;reflexivity.\n  - simpl.\n    exact IHn.\nQed.\n\nLemma mod3_exists:\n  forall m n,mod3 m = n -> exists k,m = 3 * k + n.\nProof.\n  intros m.\n  induction m using mod3_ind;simpl;\n  intros n H;try (rewrite <-H; exists 0;simpl;omega).\n  cut (mod3 m = n).\n  intros H'.\n  apply IHm in H.\n  destruct H as [k H].\n  exists (S k).\n  omega.\n  exact H.\nQed.\n\nLemma mod3_mult3:\n  forall m n,mod3 (3 * m + n) = mod3 n.\nProof.\n  intros m.\n  induction m.\n  - intros;reflexivity.\n  - intros n.\n    replace (3 * S m + n) with (3 + (3 * m + n)).\n    change (mod3 (3 + (3 * m + n))) with\n      (mod3 (3 * m + n)).\n    apply IHm.\n    ring.\nQed.\n\nLemma mod3_eq:\n  forall m n,m = n -> mod3 m = mod3 n.\nProof.\n  intros m n.\n  case (mod3_dec m) as [[Hm|Hm]|Hm];\n  case (mod3_dec n) as [[Hn|Hn]|Hn];\n  apply mod3_exists in Hm;destruct Hm as [m' Hm];\n  apply mod3_exists in Hn;destruct Hn as [n' Hn];\n  subst m;subst n ;repeat rewrite mod3_mult3;simpl;omega.\nQed.\n\nLemma mod3_distr:\n  forall m n,mod3 (m + n) = mod3 ((mod3 m)+ (mod3 n)).\nProof.\n  intros m n.\n  assert (forall r s t u v,\n            (r*s + u) + (r*t+v) =\n               r*(s+t) + (u+v)) as P.\n  intros;ring.\n\n  case (mod3_dec m) as [[Hm |Hm]|Hm];\n  case (mod3_dec n) as [[Hn |Hn]|Hn];\n  rewrite Hm;rewrite Hn;\n  apply mod3_exists in Hm;destruct Hm as [m' Hm];\n  apply mod3_exists in Hn;destruct Hn as [n' Hn];\n  rewrite Hm;rewrite Hn;rewrite P;apply mod3_mult3. \nQed.\n\nLemma square_expand :\n  forall n m,pow2 (3 * m + n) = (3 * (3 * m * m + 2*m*n) + n*n).\nProof.\n  intros;unfold pow2;ring.\nQed.\n\nLemma mod3_sq:\n  forall a,mod3 (pow2 a) = 0 -> mod3 a = 0.\nProof.\n  intros a.\n  case (mod3_dec a)  as [[H|H]|H];\n  apply mod3_exists in H;destruct H as [t H];\n  subst a;\n  rewrite square_expand;\n  repeat rewrite mod3_mult3;\n  simpl;omega.\nQed.    \n\n\nLemma square_plus_expand :\n  forall n m s t,\n    pow2 (3 * m + s) + pow2 (3*n+t) =\n    3 * (3 * (m * m + n*n) + 2*(m*s +n*t)) + (s*s + t*t).\nProof.\n  intros;unfold pow2;ring.\nQed.\n\nLemma Quest2_sub:\n   forall a b,mod3 (pow2 a + pow2 b) = 0 -> mod3 a = 0/\\mod3 b = 0 .\nProof.\n  intros a b.\n  case (mod3_dec a) as [[Ha|Ha]|Ha];\n  case (mod3_dec b) as [[Hb|Hb]|Hb];\n  apply mod3_exists in Ha;destruct Ha as [a' Ha];\n  apply mod3_exists in Hb;destruct Hb as [b' Hb];\n  subst a;subst b;rewrite square_plus_expand;\n  repeat rewrite mod3_mult3;\n  simpl;omega.\nQed.\n\n\n  \nTheorem Quest2:\n  forall a b c,pow2 a + pow2 b = 3 * pow2 c -> mod3 a = 0/\\mod3 b = 0 /\\ mod3 c=0.\nProof.\n  intros a b c H.\n  cut (mod3 a =0/\\mod3 b = 0).\n  intros P.\n  destruct P as [Pa Pb].\n  split.\n  exact Pa.\n  split.\n  exact Pb.\n  apply mod3_exists in Pa;destruct Pa as [a' Pa].\n  apply mod3_exists in Pb;destruct Pb as [b' Pb].\n  rewrite plus_0_r in Pa.\n  rewrite plus_0_r in Pb.\n  subst a;subst b.\n  replace (pow2 (3 * a') + pow2 (3 * b')) with\n  (3 * (3 * (a'*a' + b'*b') + 0)) in H.\n  rewrite NPeano.Nat.mul_cancel_l in H.\n  symmetry in H.\n  apply mod3_eq in H.\n  rewrite mod3_mult3 in H.\n  simpl in H.\n  apply mod3_sq in H.\n  exact H.\n  omega.\n  unfold pow2.\n  ring.\n  apply Quest2_sub.\n  rewrite H.\n  replace (3*pow2 c) with (3*pow2 c + 0).\n  rewrite mod3_mult3.\n  reflexivity.\n  ring.\nQed.\n\nLemma plus_eq_0:\n  forall m n:nat,m+n=0 -> m=0/\\n=0.\nProof.\n  intros ;omega.\nQed.\n\nLemma sq_eq_0:\n  forall m,m*m = 0 -> m=0.\nProof.\n  intros m.\n  destruct m.\n  omega.\n  simpl.\n  intros H.\n  inversion H.\nQed.\n\nTheorem Quest3:\n  forall a b c,pow2 a + pow2 b = 3 * pow2 c -> a = 0/\\b = 0 /\\ c=0.\nProof.\n  intros a b c.\n  generalize dependent b.\n  generalize dependent a.\n\n  apply lt_wf_ind with (n:=c).\n  intros n P a b.\n  destruct n as [|n].\n  simpl.\n  intros H.\n  apply plus_eq_0 in H.\n  destruct H as [Ha Hb].\n  apply sq_eq_0 in Ha.\n  apply sq_eq_0 in Hb.\n  omega.\n  remember (S n) as k.\n  intros H.\n  cut (mod3 a = 0/\\mod3 b = 0 /\\ mod3 k=0).\n  intros Hm.\n  destruct Hm as [Ha [Hb Hk]].\n  apply mod3_exists in Ha;destruct Ha as [a' Ha].\n  apply mod3_exists in Hb;destruct Hb as [b' Hb].\n  apply mod3_exists in Hk;destruct Hk as [k' Hk].\n  rewrite plus_0_r in Ha.\n  rewrite plus_0_r in Hb.\n  rewrite plus_0_r in Hk.\n  subst a;subst b.\n  rewrite Hk.\n  cut ((a' = 0 /\\ b' = 0 /\\ k' = 0)->\n       (3 * a' = 0 /\\ 3 * b' = 0 /\\ 3 * k' = 0)).\n  intros T.\n  apply T.\n  apply P.\n  omega.\n  rewrite Hk in H.\n  replace (pow2 (3 * a') + pow2 (3 * b'))\n    with (9 * ( pow2 a' + pow2 b')) in H.\n  replace (3 * pow2 (3 * k'))\n    with (9 * (3 * ( pow2 k'))) in H.\n  apply NPeano.Nat.mul_cancel_l in H.\n  exact H.\n  omega.\n  unfold pow2;ring.\n  unfold pow2;ring.\n  intros;omega.\n  apply Quest2 in H.\n  exact H.\nQed.\n", "meta": {"author": "KyushuUniversityMathematics", "repo": "TPP2014", "sha": "8439769862a9619cdb4e0af1597d447c7cca2325", "save_path": "github-repos/coq/KyushuUniversityMathematics-TPP2014", "path": "github-repos/coq/KyushuUniversityMathematics-TPP2014/TPP2014-8439769862a9619cdb4e0af1597d447c7cca2325/DaisukeSato/TPPmake2014_by_coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7412422089421551}}
{"text": "(** * IndPrinciples: Induction Principles *)\n\n(** With the Curry-Howard correspondence and its realization in Coq in\n    mind, we can now take a deeper look at induction principles. *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export ProofObjects.\n\n(* ################################################################# *)\n(** * Basics *)\n\n(** Every time we declare a new [Inductive] datatype, Coq\n    automatically generates an _induction principle_ for this type.\n    This induction principle is a theorem like any other: If [t] is\n    defined inductively, the corresponding induction principle is\n    called [t_ind].  Here is the one for natural numbers: *)\n\nCheck nat_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, P n -> P (S n)) ->\n    forall n : nat, P n.\n\n(** In English: Suppose [P] is a property of natural numbers (that is,\n      [P n] is a [Prop] for every [n]). To show that [P n] holds of all\n      [n], it suffices to show:\n\n      - [P] holds of [0]\n      - for any [n], if [P] holds of [n], then [P] holds of [S n]. *)\n\n(** The [induction] tactic is a straightforward wrapper that, at its\n    core, simply performs [apply t_ind].  To see this more clearly,\n    let's experiment with directly using [apply nat_ind], instead of\n    the [induction] tactic, to carry out some proofs.  Here, for\n    example, is an alternate proof of a theorem that we saw in the\n    [Induction] chapter. *)\n\nTheorem mul_0_r' : forall n:nat,\n  n * 0 = 0.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *) simpl. intros n' IHn'. rewrite -> IHn'.\n    reflexivity.  Qed.\n\n(** This proof is basically the same as the earlier one, but a\n    few minor differences are worth noting.\n\n    First, in the induction step of the proof (the [S] case), we\n    have to do a little bookkeeping manually (the [intros]) that\n    [induction] does automatically.\n\n    Second, we do not introduce [n] into the context before applying\n    [nat_ind] -- the conclusion of [nat_ind] is a quantified formula,\n    and [apply] needs this conclusion to exactly match the shape of\n    the goal state, including the quantifier.  By contrast, the\n    [induction] tactic works either with a variable in the context or\n    a quantified variable in the goal.\n\n    Third, we had to manually supply the name of the induction principle\n    with [apply], but [induction] figures that out itself.\n\n    These conveniences make [induction] nicer to use in practice than\n    applying induction principles like [nat_ind] directly.  But it is\n    important to realize that, modulo these bits of bookkeeping,\n    applying [nat_ind] is what we are really doing. *)\n\n(** **** Exercise: 2 stars, standard (plus_one_r')\n\n    Complete this proof without using the [induction] tactic. *)\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - intros. simpl. auto.\nQed.\n(** [] *)\n\n(** Coq generates induction principles for every datatype\n    defined with [Inductive], including those that aren't recursive.\n    Although of course we don't need the proof technique of induction\n    to prove properties of non-recursive datatypes, the idea of an\n    induction principle still makes sense for them: it gives a way to\n    prove that a property holds for all values of the type. *)\n\n(** These generated principles follow a similar pattern. If we\n    define a type [t] with constructors [c1] ... [cn], Coq generates a\n    theorem with this shape:\n\n    t_ind : forall P : t -> Prop,\n              ... case for c1 ... ->\n              ... case for c2 ... -> ...\n              ... case for cn ... ->\n              forall n : t, P n\n\n    The specific shape of each case depends on the arguments to the\n    corresponding constructor. *)\n\n(** Before trying to write down a general rule, let's look at\n    some more examples. First, an example where the constructors take\n    no arguments: *)\n\nInductive time : Type :=\n  | day\n  | night.\n\nCheck time_ind :\n  forall P : time -> Prop,\n    P day ->\n    P night ->\n    forall t : time, P t.\n\n(** **** Exercise: 1 star, standard, optional (rgb)\n\n    Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\nCheck rgb_ind.\n(** [] *)\n\n(** Here's another example, this time with one of the constructors\n    taking some arguments. *)\n\nInductive natlist : Type :=\n  | nnil\n  | ncons (n : nat) (l : natlist).\n\nCheck natlist_ind :\n  forall P : natlist -> Prop,\n    P nnil  ->\n    (forall (n : nat) (l : natlist),\n        P l -> P (ncons n l)) ->\n    forall l : natlist, P l.\n\n(** In general, the automatically generated induction principle for\n    inductive type [t] is formed as follows:\n\n    - Each constructor [c] generates one case of the principle.\n    - If [c] takes no arguments, that case is:\n\n      \"P holds of c\"\n\n    - If [c] takes arguments [x1:a1] ... [xn:an], that case is:\n\n      \"For all x1:a1 ... xn:an,\n          if [P] holds of each of the arguments of type [t],\n          then [P] holds of [c x1 ... xn]\"\n\n      But that oversimplifies a little.  An assumption about [P]\n      holding of an argument [x] of type [t] actually occurs\n      immediately after the quantification of [x].\n*)\n\n(** For example, suppose we had written the definition of [natlist] a little\n    differently: *)\n\nInductive natlist' : Type :=\n  | nnil'\n  | nsnoc (l : natlist') (n : nat).\n\n(** Now the induction principle case for [nsnoc1] is a bit different\n    than the earlier case for [ncons]: *)\n\nCheck natlist'_ind :\n  forall P : natlist' -> Prop,\n    P nnil' ->\n    (forall l : natlist', P l -> forall n : nat, P (nsnoc l n)) ->\n    forall n : natlist', P n.\n\n(** **** Exercise: 1 star, standard (booltree_ind)\n\n    In the comment below, write out the induction principle that Coq\n    will generate for the following datatype. *)\n\nInductive booltree : Type :=\n  | bt_empty\n  | bt_leaf (b : bool)\n  | bt_branch (b : bool) (t1 t2 : booltree).\n\nCheck booltree_ind.\n(* \nforall P : booltree -> Prop,\n  (P bt_empty) ->\n  (forall b : bool, P (bt_leaf b)) ->\n  (forall (b : bool) (t1 t2 : booltree), P t1 -> P t2 -> P (bt_branch b t1 t2)) ->\n  forall t : booltree, P t\n   ... *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_booltree_ind : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (toy_ind)\n\n    Here is an induction principle for a toy type:\n\n  forall P : Toy -> Prop,\n    (forall b : bool, P (con1 b)) ->\n    (forall (n : nat) (t : Toy), P t -> P (con2 n t)) ->\n    forall t : Toy, P t\n\n    Give an [Inductive] definition of [Toy], such that the induction\n    principle Coq generates is that given above: *)\n\nInductive Toy : Type :=\n  | con1 (b : bool)\n  | con2 (n : nat) (t : Toy).   \n  (* FILL IN HERE *)\n\nCheck Toy_ind.\n(* Do not modify the following line: *)\nDefinition manual_grade_for_toy_ind : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** What about polymorphic datatypes?\n\n    The inductive definition of polymorphic lists\n\n      Inductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\n\n    is very similar to that of [natlist].  The main difference is\n    that, here, the whole definition is _parameterized_ on a set [X]:\n    that is, we are defining a _family_ of inductive types [list X],\n    one for each [X].  (Note that, wherever [list] appears in the body\n    of the declaration, it is always applied to the parameter [X].)\n*)\n\n(**  The induction principle is likewise parameterized on [X]:\n\n      list_ind :\n        forall (X : Type) (P : list X -> Prop),\n           P [] ->\n           (forall (x : X) (l : list X), P l -> P (x :: l)) ->\n           forall l : list X, P l\n\n    Note that the _whole_ induction principle is parameterized on\n    [X].  That is, [list_ind] can be thought of as a polymorphic\n    function that, when applied to a type [X], gives us back an\n    induction principle specialized to the type [list X]. *)\n\n(** **** Exercise: 1 star, standard, optional (tree)\n\n    Write out the induction principle that Coq will generate for\n   the following datatype.  Compare your answer with what Coq\n   prints. *)\n\nInductive tree (X:Type) : Type :=\n  | leaf (x : X)\n  | node (t1 t2 : tree X).\nCheck tree_ind.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (mytype)\n\n    Find an inductive definition that gives rise to the\n    following induction principle:\n\n      mytype_ind :\n        forall (X : Type) (P : mytype X -> Prop),\n            (forall x : X, P (constr1 X x)) ->\n            (forall n : nat, P (constr2 X n)) ->\n            (forall m : mytype X, P m ->\n               forall n : nat, P (constr3 X m n)) ->\n            forall m : mytype X, P m\n*) \n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (foo)\n\n    Find an inductive definition that gives rise to the\n    following induction principle:\n\n      foo_ind :\n        forall (X Y : Type) (P : foo X Y -> Prop),\n             (forall x : X, P (bar X Y x)) ->\n             (forall y : Y, P (baz X Y y)) ->\n             (forall f1 : nat -> foo X Y,\n               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n             forall f2 : foo X Y, P f2\n*) \n(** [] *)\nInductive foo (X Y:Type) : Type :=\n| bar (x : X)\n| baz (y : Y)\n| quux (f1 : forall n:nat, foo X Y).\n\nCheck foo_ind.\n\n(** **** Exercise: 1 star, standard, optional (foo')\n\n    Consider the following inductive definition: *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 (l : list X) (f : foo' X)\n  | C2.\n\nCheck foo'_ind.\n(** What induction principle will Coq generate for [foo']?  (Fill\n   in the blanks, then check your answer with Coq.)\n\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    P f -> P (C1 X l f)) -> \n                    P (C2 X) ->\n             forall f : foo' X, P f\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?\n\n    The induction principle for numbers\n\n       forall P : nat -> Prop,\n            P 0  ->\n            (forall n : nat, P n -> P (S n))  ->\n            forall n : nat, P n\n\n   is a generic statement that holds for all propositions\n   [P] (or rather, strictly speaking, for all families of\n   propositions [P] indexed by a number [n]).  Each time we\n   use this principle, we are choosing [P] to be a particular\n   expression of type [nat -> Prop].\n\n   We can make proofs by induction more explicit by giving\n   this expression a name.  For example, instead of stating\n   the theorem [mul_0_r] as \"[forall n, n * 0 = 0],\" we can\n   write it as \"[forall n, P_m0r n]\", where [P_m0r] is defined\n   as... *)\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\n\n(** ... or equivalently: *)\n\nDefinition P_m0r' : nat -> Prop :=\n  fun n => n * 0 = 0.\n\n(** Now it is easier to see where [P_m0r] appears in the proof. *)\n\nTheorem mul_0_r'' : forall n:nat,\n  P_m0r n.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    (* Note the proof state at this point! *)\n    intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n(** This extra naming step isn't something that we do in\n    normal proofs, but it is useful to do it explicitly for an example\n    or two, because it allows us to see exactly what the induction\n    hypothesis is.  If we prove [forall n, P_m0r n] by induction on\n    [n] (using either [induction] or [apply nat_ind]), we see that the\n    first subgoal requires us to prove [P_m0r 0] (\"[P] holds for\n    zero\"), while the second subgoal requires us to prove [forall n',\n    P_m0r n' -> P_m0r (S n')] (that is \"[P] holds of [S n'] if it\n    holds of [n']\" or, more elegantly, \"[P] is preserved by [S]\").\n    The _induction hypothesis_ is the premise of this latter\n    implication -- the assumption that [P] holds of [n'], which we are\n    allowed to use in proving that [P] holds for [S n']. *)\n\n(* ################################################################# *)\n(** * More on the [induction] Tactic *)\n\n(** The [induction] tactic actually does even more low-level\n    bookkeeping for us than we discussed above.\n\n    Recall the informal statement of the induction principle for\n    natural numbers:\n      - If [P n] is some proposition involving a natural number n, and\n        we want to show that P holds for _all_ numbers n, we can\n        reason like this:\n          - show that [P O] holds\n          - show that, if [P n'] holds, then so does [P (S n')]\n          - conclude that [P n] holds for all n.\n    So, when we begin a proof with [intros n] and then [induction n],\n    we are first telling Coq to consider a _particular_ [n] (by\n    introducing it into the context) and then telling it to prove\n    something about _all_ numbers (by using induction).\n*)\n\n(**  What Coq actually does in this situation, internally, is it\n    \"re-generalizes\" the variable we perform induction on.  For\n    example, in our original proof that [plus] is associative... *)\n\nTheorem add_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  (* ...we first introduce all 3 variables into the context,\n     which amounts to saying \"Consider an arbitrary [n], [m], and\n     [p]...\" *)\n  intros n m p.\n  (* ...We now use the [induction] tactic to prove [P n] (that\n     is, [n + (m + p) = (n + m) + p]) for _all_ [n],\n     and hence also for the particular [n] that is in the context\n     at the moment. *)\n  induction n as [| n'].\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** It also works to apply [induction] to a variable that is\n    quantified in the goal. *)\n\nTheorem add_comm' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [| n'].\n  - (* n = O *) intros m. rewrite -> add_0_r. reflexivity.\n  - (* n = S n' *) intros m. simpl. rewrite -> IHn'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** Note that [induction n] leaves [m] still bound in the goal --\n    i.e., what we are proving inductively is a statement beginning\n    with [forall m].\n\n    If we do [induction] on a variable that is quantified in the goal\n    _after_ some other quantifiers, the [induction] tactic will\n    automatically introduce the variables bound by these quantifiers\n    into the context. *)\n\nTheorem add_comm'' : forall n m : nat,\n  n + m = m + n.\nProof.\n  (* Let's do induction on [m] this time, instead of [n]... *)\n  induction m as [| m']. (* [n] is already introduced into the context *)\n  - (* m = O *) simpl. rewrite -> add_0_r. reflexivity.\n  - (* m = S m' *) simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nTheorem add_comm3 : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros.\n  generalize dependent n.\n  induction m as [ | m']; intros. \n  - (* m = O *) simpl. rewrite -> add_0_r. reflexivity.\n  - (* m = S m' *) simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n(** **** Exercise: 1 star, standard, optional (plus_explicit_prop)\n\n    Rewrite both [add_assoc'] and [add_comm'] and their proofs in\n    the same style as [mul_0_r''] above -- that is, for each theorem,\n    give an explicit [Definition] of the proposition being proved by\n    induction, and state the theorem and proof in terms of this\n    defined proposition.  *)\n\nCheck nat_ind.\n\nDefinition P_add_assoc : nat -> Prop :=\n  fun n => (forall m p, n + (m + p) = (n + m) + p).\n\n\nTheorem add_assoc'' : forall n : nat,\n P_add_assoc n.\nProof.\n  apply nat_ind; unfold P_add_assoc; intros.\n  - reflexivity.\n  - simpl. rewrite (H m p). reflexivity.\nQed.\n\nDefinition P_add_comm : nat -> Prop :=\n  fun n => (forall m, n + m = m + n).\n\nTheorem add_comm4 : forall n, P_add_comm n.\nProof.\n  apply nat_ind; unfold P_add_comm; simpl; intros.\n  - rewrite add_0_r. reflexivity.\n  - rewrite (H m). rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Induction Principles for Propositions *)\n\n(** Inductive definitions of propositions also cause Coq to generate\n    induction priniciples.  For example, recall our proposition [ev]\n    from [IndProp]: *)\n\nPrint ev.\n\n(* ===>\n\n  Inductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall n : nat, ev n -> ev (S (S n)))\n\n*)\n\nCheck ev_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, ev n -> P n -> P (S (S n))) ->\n    forall n : nat, ev n -> P n.\n\n(** In English, [ev_ind] says: Suppose [P] is a property of natural\n    numbers.  To show that [P n] holds whenever [n] is even, it suffices\n    to show:\n\n      - [P] holds for [0],\n\n      - for any [n], if [n] is even and [P] holds for [n], then [P]\n        holds for [S (S n)]. *)\n\n(** As expected, we can apply [ev_ind] directly instead of using\n    [induction].  For example, we can use it to show that [ev'] (the\n    slightly awkward alternate definition of evenness that we saw in\n    an exercise in the [IndProp] chapter) is equivalent to the\n    cleaner inductive definition [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\nTheorem ev_ev' : forall n, ev n -> ev' n.\nProof.\n  apply ev_ind.\n  - (* ev_0 *)\n    apply ev'_0.\n  - (* ev_SS *)\n    intros m Hm IH.\n    apply (ev'_sum 2 m).\n    + apply ev'_2.\n    + apply IH.\nQed.\n\n(** The precise form of an [Inductive] definition can affect the\n    induction principle Coq generates. *)\n\nInductive le1 : nat -> nat -> Prop :=\n  | le1_n : forall n, le1 n n\n  | le1_S : forall n m, (le1 n m) -> (le1 n (S m)).\n\nNotation \"m <=1 n\" := (le1 m n) (at level 70).\n\n(** This definition can be streamlined a little by observing that the\n    left-hand argument [n] is the same everywhere in the definition,\n    so we can actually make it a \"general parameter\" to the whole\n    definition, rather than an argument to each constructor. *)\n\nInductive le2 (n:nat) : nat -> Prop :=\n  | le2_n : le2 n n\n  | le2_S m (H : le2 n m) : le2 n (S m).\n\nNotation \"m <=2 n\" := (le2 m n) (at level 70).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. *)\n\nCheck le1_ind :\n  forall P : nat -> nat -> Prop,\n    (forall n : nat, P n n) ->\n    (forall n m : nat, n <=1 m -> P n m -> P n (S m)) ->\n    forall n n0 : nat, n <=1 n0 -> P n n0.\n\nCheck le2_ind :\n  forall (n : nat) (P : nat -> Prop),\n    P n ->\n    (forall m : nat, n <=2 m -> P m -> P (S m)) ->\n    forall n0 : nat, n <=2 n0 -> P n0.\n\n(* ################################################################# *)\n(** * Another Form of Induction Principles on Propositions (Optional) *)\n\n(** The induction principle that Coq generated for [ev] was parameterized\n    on a natural number [n].  It could have additionally been parameterized\n    on the evidence that [n] was even, which would have led to this\n    induction principle:\n\n    forall P : (forall n : nat, ev'' n -> Prop),\n      P O ev_0 ->\n      (forall (m : nat) (E : ev'' m),\n        P m E -> P (S (S m)) (ev_SS m E)) ->\n      forall (n : nat) (E : ev'' n), P n E\n*)\n\n(**   ... because:\n\n     - Since [ev] is indexed by a number [n] (every [ev] object [E] is\n       a piece of evidence that some particular number [n] is even),\n       the proposition [P] is parameterized by both [n] and [E] --\n       that is, the induction principle can be used to prove\n       assertions involving both an even number and the evidence that\n       it is even.\n\n     - Since there are two ways of giving evidence of evenness ([even]\n       has two constructors), applying the induction principle\n       generates two subgoals:\n\n         - We must prove that [P] holds for [O] and [ev_0].\n\n         - We must prove that, whenever [m] is an even number and [E]\n           is an evidence of its evenness, if [P] holds of [m] and\n           [E], then it also holds of [S (S m)] and [ev_SS m E].\n\n     - If these subgoals can be proved, then the induction principle\n       tells us that [P] is true for _all_ even numbers [n] and\n       evidence [E] of their evenness.\n\n    This is more flexibility than we normally need or want: it is\n    giving us a way to prove logical assertions where the assertion\n    involves properties of some piece of _evidence_ of evenness, while\n    all we really care about is proving properties of _numbers_ that\n    are even -- we are interested in assertions about numbers, not\n    about evidence.  It would therefore be more convenient to have an\n    induction principle for proving propositions [P] that are\n    parameterized just by [n] and whose conclusion establishes [P] for\n    all even numbers [n]:\n\n       forall P : nat -> Prop,\n         ... ->\n       forall n : nat,\n         even n -> P n\n\n    That is why Coq actually generates the induction principle\n    [ev_ind] that we saw before. *)\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proofs by Induction *)\n\n(** Question: What is the relation between a formal proof of a\n    proposition [P] and an informal proof of the same proposition [P]?\n\n    Answer: The latter should _teach_ the reader everything they would\n    need to understand to be able to produce the former.\n\n    Question: How much detail does that require?\n\n    Unfortunately, there is no single right answer; rather, there is a\n    range of choices.\n\n    At one end of the spectrum, we can essentially give the reader the\n    whole formal proof (i.e., the \"informal\" proof will amount to just\n    transcribing the formal one into words).  This may give the reader\n    the ability to reproduce the formal one for themselves, but it\n    probably doesn't _teach_ them anything much.\n\n   At the other end of the spectrum, we can say \"The theorem is true\n   and you can figure out why for yourself if you think about it hard\n   enough.\"  This is also not a good teaching strategy, because often\n   writing the proof requires one or more significant insights into\n   the thing we're proving, and most readers will give up before they\n   rediscover all the same insights as we did.\n\n   In the middle is the golden mean -- a proof that includes all of\n   the essential insights (saving the reader the hard work that we\n   went through to find the proof in the first place) plus high-level\n   suggestions for the more routine parts to save the reader from\n   spending too much time reconstructing these (e.g., what the IH says\n   and what must be shown in each case of an inductive proof), but not\n   so much detail that the main ideas are obscured.\n\n   Since we've spent much of this chapter looking \"under the hood\" at\n   formal proofs by induction, now is a good moment to talk a little\n   about _informal_ proofs by induction.\n\n   In the real world of mathematical communication, written proofs\n   range from extremely longwinded and pedantic to extremely brief and\n   telegraphic.  Although the ideal is somewhere in between, while one\n   is getting used to the style it is better to start out at the\n   pedantic end.  Also, during the learning phase, it is probably\n   helpful to have a clear standard to compare against.  With this in\n   mind, we offer two templates -- one for proofs by induction over\n   _data_ (i.e., where the thing we're doing induction on lives in\n   [Type]) and one for proofs by induction over _evidence_ (i.e.,\n   where the inductively defined thing lives in [Prop]). *)\n\n(* ================================================================= *)\n(** ** Induction Over an Inductively Defined Set *)\n\n(** _Template_:\n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_:\n\n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if [length [] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of [index].\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n\n            length l = length (x::l') = S (length l'),\n\n          it suffices to show that\n\n            index (S (length l')) l' = None.\n\n          But this follows directly from the induction hypothesis,\n          picking [n'] to be [length l'].  [] *)\n\n(* ================================================================= *)\n(** ** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_.\n\n    _Template_:\n\n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n\n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n(* ################################################################# *)\n(** * Explicit Proof Objects for Induction (Optional) *)\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n\n(** Recall again the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declaration for [nat]. *)\n\nCheck nat_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, P n -> P (S n)) ->\n    forall n : nat, P n.\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n\nPrint nat_ind.\n\n(** We can rewrite that more tidily as follows: *)\nFixpoint build_proof\n         (P : nat -> Prop)\n         (evPO : P 0)\n         (evPS : forall n : nat, P n -> P (S n))\n         (n : nat) : P n :=\n  match n with\n  | 0 => evPO\n  | S k => evPS k (build_proof P evPO evPS k)\n  end.\n\nDefinition nat_ind_tidy := build_proof.\n\n(** We can read [build_proof] as follows: Suppose we have\n    evidence [evPO] that [P] holds on 0, and evidence [evPS] that [forall\n    n:nat, P n -> P (S n)].  Then we can prove that [P] holds of an\n    arbitrary nat [n] using recursive function [build_proof], which\n    pattern matches on [n]:\n\n      - If [n] is 0, [build_proof] returns [evPO] to show that [P n]\n        holds.\n\n      - If [n] is [S k], [build_proof] applies itself recursively on\n        [k] to obtain evidence that [P k] holds; then it applies\n        [evPS] on that evidence to show that [P (S n)] holds. *)\n\n(** Recursive function [build_proof] thus pattern matches against\n    [n], recursing all the way down to 0, and building up a proof\n    as it returns. *)\n\n(** The actual [nat_ind] that Coq generates uses a recursive\n    function [F] defined with [fix] instead of [Fixpoint]. *)\n\n(** We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  As a motivating example,\n    suppose that we want to prove the following lemma, directly\n    relating the [ev] predicate we defined in [IndProp]\n    to the [even] function defined in [Basics]. *)\n\nLemma even_ev : forall n: nat, even n = true -> ev n.\nProof.\n  induction n; intros.\n  - apply ev_0.\n  - destruct n.\n    + simpl in H. inversion H.\n    + simpl in H.\n      apply ev_SS.\nAbort.\n\n(** Attempts to prove this by standard induction on [n] fail in the case for\n    [S (S n)], because the induction hypothesis only tells us something about\n    [S n], which is useless. There are various ways to hack around this problem;\n    for example, we _can_ use ordinary induction on [n] to prove this (try it!):\n\n    [Lemma even_ev' : forall n : nat,\n     (even n = true -> ev n) /\\ (even (S n) = true -> ev (S n))].\n\n    But we can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n *)\n\nDefinition nat_ind2 :\n  forall (P : nat -> Prop),\n  P 0 ->\n  P 1 ->\n  (forall n : nat, P n -> P (S(S n))) ->\n  forall n : nat , P n :=\n    fun P => fun P0 => fun P1 => fun PSS =>\n      fix f (n:nat) := match n with\n                         0 => P0\n                       | 1 => P1\n                       | S (S n') => PSS n' (f n')\n                       end.\n\n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive.\n\n     The [induction ... using] tactic variant gives a convenient way to\n     utilize a non-standard induction principle like this. *)\n\nLemma even_ev : forall n, even n = true -> ev n.\nProof.\n  intros.\n  induction n as [ | |n'] using nat_ind2.\n  - apply ev_0.\n  - simpl in H.\n    inversion H.\n  - simpl in H.\n    apply ev_SS.\n    apply IHn'.\n    apply H.\nQed.\n\n\n(* 2021-08-11 15:08 *)\n\n\n\n  \n  \n", "meta": {"author": "jiangsy", "repo": "fp_course", "sha": "b724bc18ae1587bf4bfdb7ebfb6c1852f14c4b88", "save_path": "github-repos/coq/jiangsy-fp_course", "path": "github-repos/coq/jiangsy-fp_course/fp_course-b724bc18ae1587bf4bfdb7ebfb6c1852f14c4b88/sf/lf/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.7411893093422558}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (x : natural) : natural :=\n  mult y (mult (Succ x) z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj173_coqofml_LLeMt4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979619, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7410436269981822}}
{"text": "(** * SearchTree: Binary Search Trees *)\n\n(** We have implemented maps twice so far: with lists in\n    [Lists], and with higher-order functions in [Maps].\n    Those are simple but inefficient implementations: looking up the\n    value bound to a given key takes time linear in the number of\n    bindings, both in the worst and expected case. *)\n\n(** If the type of keys can be totally ordered -- that is, it supports\n    a well-behaved [<=] comparison -- then maps can be implemented with\n    _binary search trees_ (BSTs).  Insert and lookup operations on\n    BSTs take time proportional to the height of the tree.  If the\n    tree is balanced, the operations therefore take logarithmic time. *)\n\n(** If you don't recall BSTs or haven't seen them in awhile, see\n    Wikipedia or read any standard textbook; for example:\n\n    - Section 3.2 of _Algorithms, Fourth Edition_, by Sedgewick and\n      Wayne, Addison Wesley 2011; or\n\n    - Chapter 12 of _Introduction to Algorithms, 3rd Edition_, by\n      Cormen, Leiserson, and Rivest, MIT Press 2009. *)\n\nFrom Coq Require Import String.  (* for an example, and manual grading *)\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom VFA Require Import Perm.\nFrom VFA Require Import Maps.\nFrom VFA Require Import Sort.\n\n(* ################################################################# *)\n(** * BST Implementation *)\n\n(** We use [nat] as the key type in our implementation of BSTs,\n    since it has a convenient total order [<=?] with lots of theorems\n    and automation available. *)\n\nDefinition key := nat.\n\n(** [E] represents the empty map.  [T l k v r] represents the\n    map that binds [k] to [v], along with all the bindings in [l] and\n    [r].  No key may be bound more than once in the map. *)\n\nInductive tree (V : Type) : Type :=\n| E\n| T (l : tree V) (k : key) (v : V) (r : tree V).\n\nArguments E {V}.\nArguments T {V}.\n\n(** An example tree:\n\n      4 -> \"four\"\n      /        \\\n     /          \\\n  2 -> \"two\"   5 -> \"five\"\n*)\n\nDefinition ex_tree : tree string :=\n  (T (T E 2 \"two\" E) 4 \"four\" (T E 5 \"five\" E))%string.\n\n(** [empty_tree] contains no bindings. *)\n\nDefinition empty_tree {V : Type} : tree V :=\n  E.\n\n(** [bound k t] is whether [k] is bound in [t]. *)\n\nFixpoint bound {V : Type} (x : key) (t : tree V) :=\n  match t with\n  | E => false\n  | T l y v r => if x <? y then bound x l\n                else if x >? y then bound x r\n                     else true\n  end.\n\n(** [lookup d k t] is the value bound to [k] in [t], or is default\n    value [d] if [k] is not bound in [t]. *)\n\nFixpoint lookup {V : Type} (d : V) (x : key) (t : tree V) : V :=\n  match t with\n  | E => d\n  | T l y v r => if x <? y then lookup d x l\n                else if x >? y then lookup d x r\n                     else v\n  end.\n\n(** [insert k v t] is the map containing all the bindings of [t] along\n    with a binding of [k] to [v]. *)\n\nFixpoint insert {V : Type} (x : key) (v : V) (t : tree V) : tree V :=\n  match t with\n  | E => T E x v E\n  | T l y v' r => if x <? y then T (insert x v l) y v' r\n                 else if x >? y then T l y v' (insert x v r)\n                      else T l x v r\n  end.\n\n(** Note that [insert] is a _functional_ aka _persistent_\n    implementation: [t] is not changed. *)\n\nModule Tests.\n\n(** Here are some unit tests to check that BSTs behave the way we\n    expect. *)\n\n  Open Scope string_scope.\n\n  Example bst_ex1 :\n    insert 5 \"five\" (insert 2 \"two\" (insert 4 \"four\" empty_tree)) = ex_tree.\n  Proof. reflexivity. Qed.\n\n  Example bst_ex2 : lookup \"\" 5 ex_tree = \"five\".\n  Proof. reflexivity. Qed.\n\n  Example bst_ex3 : lookup \"\" 3 ex_tree = \"\".\n  Proof. reflexivity. Qed.\n\n  Example bst_ex4 : bound 3 ex_tree = false.\n  Proof. reflexivity. Qed.\n\nEnd Tests.\n\n(** Although we can spot-check the behavior of BST operations with\n    unit tests like these, we of course should prove general theorems\n    about their correctness.  We will do that later in the chapter. *)\n\n(* ################################################################# *)\n(** * BST Invariant *)\n\n(** The implementations of [lookup] and [insert] assume that\n    values of type [tree] obey the _BST invariant_: for any non-empty\n    node with key [k], all the values of the left subtree are less\n    than [k] and all the values of the right subtree are greater than\n    [k].  But that invariant is not part of the definition of\n    [tree]. For example, the following tree is not a BST: *)\n\nModule NotBst.\n  Open Scope string_scope.\n\n  Definition t : tree string :=\n    T (T E 5 \"five\" E) 4 \"four\" (T E 2 \"two\" E).\n\n  (** The [insert] function we wrote above would never produce\n      such a tree, but we can still construct it by manually applying\n      [T]. When we try to lookup [2] in that tree, we get the wrong\n      answer, because [lookup] assumes [2] is in the left subtree: *)\n\n  Example not_bst_lookup_wrong :\n    lookup \"\" 2 t <> \"two\".\n  Proof.\n    simpl. unfold not. intros contra. discriminate.\n  Qed.\nEnd NotBst.\n\n(** So, let's formalize the BST invariant. Here's one way to do\n    so.  First, we define a helper [ForallT] to express that idea that\n    a predicate holds at every node of a tree: *)\n\nFixpoint ForallT {V : Type} (P: key -> V -> Prop) (t: tree V) : Prop :=\n  match t with\n  | E => True\n  | T l k v r => P k v /\\ ForallT P l /\\ ForallT P r\n  end.\n\n(** Second, we define the BST invariant:\n\n    - An empty tree is a BST.\n\n    - A non-empty tree is a BST if all its left nodes have a lesser\n      key, its right nodes have a greater key, and the left and\n      right subtrees are themselves BSTs. *)\n\nInductive BST {V : Type} : tree V -> Prop :=\n| BST_E : BST E\n| BST_T : forall l x v r,\n    ForallT (fun y _ => y < x) l ->\n    ForallT (fun y _ => y > x) r ->\n    BST l ->\n    BST r ->\n    BST (T l x v r).\n\nHint Constructors BST.\n\n(** Let's check that [BST] correctly classifies a couple example\n    trees: *)\n\nExample is_BST_ex :\n  BST ex_tree.\nProof.\n  unfold ex_tree.\n  repeat (constructor; try omega).\nQed.\n\nExample not_BST_ex :\n  ~ BST NotBst.t.\nProof.\n  unfold NotBst.t. intros contra.\n  inv contra. inv H3. omega.\nQed.\n\n(** **** Exercise: 1 star, standard (empty_tree_BST)  *)\n\n(** Prove that the empty tree is a BST. *)\n\nTheorem empty_tree_BST : forall (V : Type),\n    BST (@empty_tree V).\nProof.\n  unfold empty_tree.\n  constructor.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, standard (insert_BST)  *)\n\n(** Prove that [insert] produces a BST, assuming it is given one.\n\n    Start by proving this helper lemma, which says that [insert]\n    preserves any node predicate. Proceed by induction on [t]. *)\n\nLemma ForallT_insert : forall (V : Type) (P : key -> V -> Prop) (t : tree V),\n    ForallT P t -> forall (k : key) (v : V),\n      P k v -> ForallT P (insert k v t).\nProof.\n  intros V P t H k v H1. induction t.\n  - unfold insert. unfold ForallT. split. assumption. split; repeat apply I.\n  - intros. inversion H. destruct H2. simpl.\n    bdestruct (k0 >? k).  simpl. split. apply H0. split.\n    apply IHt1. apply H2. apply H3.\n    bdestruct (k >? k0). simpl. split. apply H0. split.\n    apply H2. apply IHt2. apply H3.\n    simpl. split. assumption. split; repeat assumption.\nQed.\n\n(** Now prove the main theorem. Proceed by induction on the evidence\n    that [t] is a BST. *)\n\nTheorem insert_BST : forall (V : Type) (k : key) (v : V) (t : tree V),\n    BST t -> BST (insert k v t).\nProof.\n  intros. induction t.\n  - repeat constructor.\n  - inv H. simpl. \n    bdestruct (k0 >? k).\n    constructor; try apply ForallT_insert; repeat assumption.\n    apply IHt1. apply H6.\n    bdestruct (k >? k0).\n    constructor; try apply ForallT_insert; repeat assumption.\n    apply IHt2. apply H7.\n    constructor. inversion H. subst. apply H4.\n    subst. omega.\n    inversion H0. subst. apply H5.\n    subst. omega.\n    apply H6. apply H7.\nQed.\n\n(** [] *)\n\n(** Since [empty_tree] and [insert] are the only operations that\n    create BSTs, we are guaranteed that any [tree] is a BST -- unless\n    it was constructed manually with [T].  It would therefore make\n    sense to limit the use of [T] to only within the tree operations,\n    rather than expose it.  Coq, like OCaml and other functional\n    languages, can do this with its module system.  See [ADT] for\n    details. *)\n\n(* ################################################################# *)\n(** * Correctness of BST Operations *)\n\n(** To prove the correctness of [lookup] and [bound], we need\n    specifications for them.  We'll study two different techniques for\n    that in this chapter. *)\n\n(** The first is called _algebraic specification_.  With it, we write\n    down equations relating the results of operations.  For example,\n    we could write down equations like the following to specify the\n    [+] and [*] operations:\n\n      (a + b) + c = a + (b + c)\n      a + b = b + a\n      a + 0 = a\n      (a * b) * c = a * (b * c)\n      a * b = b * a\n      a * 1 = a\n      a * 0 = 0\n      a * (b + c) = a * b + a * c\n\n    For BSTs, let's examine how [lookup] should interact with\n    when applied to other operations.  It is easy to see what needs to\n    be true for [empty_tree]: looking up any value at all in the empty\n    tree should fail and return the default value:\n\n      lookup d k empty_tree = d\n\n    What about non-empty trees?  The only way to build a non-empty\n    tree is by applying [insert k v t] to an existing tree [t]. So it\n    suffices to describe the behavior of [lookup] on the result of an\n    arbitrary [insert] operation. There are two cases.  If we look up\n    the same key that was just inserted, we should get the value that\n    was inserted with it:\n\n      lookup d k (insert k v t) = v\n\n    If we look up a different key than was just inserted, the insert\n    should not affect the answer -- which should be the same as if we\n    did the lookup in the original tree before the insert occured:\n\n      lookup d k' (insert k v t) = lookup d k' t      if k <> k'\n\n    These three basic equations specify the correct behavior of maps.\n    Let's prove that they hold. *)\n\nTheorem lookup_empty : forall (V : Type) (d : V) (k : key),\n    lookup d k empty_tree = d.\nProof.\n  auto.\nQed.\n\nTheorem lookup_insert_eq : forall (V : Type) (t : tree V) (d : V) (k : key) (v : V),\n    lookup d k (insert k v t)  = v.\nProof.\n  induction t; intros; simpl.\n  - bdestruct (k <? k); try omega; auto.\n  - bdestruct (k <? k0); bdestruct (k0 <? k); simpl; try omega; auto.\n    + bdestruct (k <? k0); bdestruct (k0 <? k); try omega; auto.\n    + bdestruct (k <? k0); bdestruct (k0 <? k); try omega; auto.\n    + bdestruct (k0 <? k0); try omega; auto.\nQed.\n\n(** The basic method of that proof is to repeatedly [bdestruct]\n    everything in sight, followed by generous use of [omega] and\n    [auto]. Let's automate that. *)\n\nLtac bdestruct_guard :=\n  match goal with\n  | |- context [ if ?X =? ?Y then _ else _ ] => bdestruct (X =? Y)\n  | |- context [ if ?X <=? ?Y then _ else _ ] => bdestruct (X <=? Y)\n  | |- context [ if ?X <? ?Y then _ else _ ] => bdestruct (X <? Y)\n  end.\n\nLtac bdall :=\n  repeat (simpl; bdestruct_guard; try omega; auto).\n\nTheorem lookup_insert_eq' :\n  forall (V : Type) (t : tree V) (d : V) (k : key) (v : V),\n    lookup d k (insert k v t) = v.\nProof.\n  induction t; intros; bdall.\nQed.\n\n(** The tactic immediately pays off in proving the third\n    equation. *)\n\nTheorem lookup_insert_neq :\n  forall (V : Type) (t : tree V) (d : V) (k k' : key) (v : V),\n   k <> k' -> lookup d k' (insert k v t) = lookup d k' t.\nProof.\n  induction t; intros; bdall.\nQed.\n\n(** Perhaps surprisingly, the proofs of these results do not\n    depend on whether [t] satisfies the BST invariant.  That's because\n    [lookup] and [insert] follow the same path through the tree, so\n    even if nodes are in the \"wrong\" place, they are consistently\n    \"wrong\". *)\n\n(** **** Exercise: 3 stars, standard, optional (bound_correct)  *)\n\n(** Specify and prove the correctness of [bound]. State and prove\n    three theorems, inspired by those we just proved for [lookup]. If\n    you have the right theorem statements, the proofs should all be\n    quite easy -- thanks to [bdall]. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_bound_correct : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (bound_default)  *)\n\n(** Prove that if [bound] returns [false], then [lookup] returns\n    the default value. Proced by induction on the tree. *)\n\nTheorem bound_default :\n  forall (V : Type) (k : key) (d : V) (t : tree V),\n    bound k t = false ->\n    lookup d k t = d.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * BSTs vs. Higher-order Functions (Optional) *)\n\n(** The three theorems we just proved for [lookup] should seem\n    familiar: we proved equivalent theorems in [Maps] for maps\n    defined as higher-order functions. *)\n\n(** - [lookup_empty] and [t_apply_empty] both state that the empty map\n      binds all keys to the default value. *)\n\nCheck lookup_empty : forall (V : Type) (d : V) (k : key),\n    lookup d k empty_tree = d.\n\nCheck t_apply_empty : forall (V : Type) (k : key) (d : V),\n    t_empty d k = d.\n\n(** - [lookup_insert_eq] and [t_update_eq] both state that updating a map\n      then looking for the updated key produces the updated value. *)\n\nCheck lookup_insert_eq : forall (V : Type) (t : tree V) (d : V) (k : key) (v : V),\n    lookup d k (insert k v t) = v.\n\nCheck t_update_eq : forall (V : Type) (m : total_map V) (k : key) (v : V),\n    (t_update m k v) k = v.\n\n(** - [lookup_insert_neq] and [t_update_neq] both state that updating\n      a map then looking for a different key produces the same value\n      as the original map. *)\n\nCheck lookup_insert_neq :\n  forall (V : Type) (t : tree V) (d : V) (k k' : key) (v : V),\n    k <> k' -> lookup d k' (insert k v t) = lookup d k' t.\n\nCheck t_update_neq : forall (V : Type) (v : V) (k k' : key) (m : total_map V),\n    k <> k' -> (t_update m k v) k' = m k'.\n\n(** In [Maps], we also proved three other theorems about the\n    behavior of functional maps on various combinations of updates and\n    lookups: *)\n\nCheck t_update_shadow : forall (V : Type) (m : total_map V) (v1 v2 : V) (k : key),\n    t_update (t_update m k v1) k v2 = t_update m k v2.\n\nCheck t_update_same : forall (V : Type) (k : key) (m : total_map V),\n    t_update m k (m k) = m.\n\nCheck t_update_permute :\n  forall (V : Type) (v1 v2 : V) (k1 k2 : key) (m : total_map V),\n    k2 <> k1 ->\n    t_update (t_update m k2 v2) k1 v1 = t_update (t_update m k1 v1) k2 v2.\n\n(** Let's prove analogues to these three theorems for search trees.\n\n    Hint: you do not need to unfold the definitions of [empty_tree],\n    [insert], or [lookup].  Instead, use [lookup_insert_eq] and\n    [lookup_insert_neq]. *)\n\n(** **** Exercise: 2 stars, standard, optional (lookup_insert_shadow)  *)\n\nLemma lookup_insert_shadow :\n  forall (V : Type) (t : tree V) (v v' d: V) (k k' : key),\n    lookup d k' (insert k v (insert k v' t)) = lookup d k' (insert k v t).\nProof.\n  intros. bdestruct (k =? k').\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (lookup_insert_same)  *)\n\nLemma lookup_insert_same :\n  forall (V : Type) (k k' : key) (d : V) (t : tree V),\n    lookup d k' (insert k (lookup d k t) t) = lookup d k' t.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (lookup_insert_permute)  *)\n\nLemma lookup_insert_permute :\n  forall (V : Type) (v1 v2 d : V) (k1 k2 k': key) (t : tree V),\n    k1 <> k2 ->\n    lookup d k' (insert k1 v1 (insert k2 v2 t))\n    = lookup d k' (insert k2 v2 (insert k1 v1 t)).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** Our ability to prove these lemmas without reference to the\n    underlying tree implementation demonstrates they hold for any map\n    implementation that satisfies the three basic equations. *)\n\n(** Each of these lemmas just proved was phrased as an equality\n    between the results of looking up an arbitrary key [k'] in two\n    maps.  But the lemmas for the function-based maps were phrased as\n    direct equalities between the maps themselves.\n\n    Could we state the tree lemmas with direct equalities?  For\n    [insert_shadow], the answer is yes: *)\n\nLemma insert_shadow_equality : forall (V : Type) (t : tree V) (k : key) (v v' : V),\n    insert k v (insert k v' t) = insert k v t.\nProof.\n  induction t; intros; bdall.\n  - rewrite IHt1; auto.\n  - rewrite IHt2; auto.\nQed.\n\n(** But the other two direct equalities on BSTs do not necessarily\n    hold. *)\n\n(** **** Exercise: 3 stars, standard, optional (direct_equalities_break)  *)\n\n(** Prove that the other equalities do not hold.  Hint: find a counterexample\n    first on paper, then use the [exists] tactic to instantiate the theorem\n    on your counterexample.  The simpler your counterexample, the simpler\n    the rest of the proof will be. *)\n\nLemma insert_same_equality_breaks :\n  exists (V : Type) (d : V) (t : tree V) (k : key),\n      insert k (lookup d k t) t <> t.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nLemma insert_permute_equality_breaks :\n  exists (V : Type) (v1 v2 : V) (k1 k2 : key) (t : tree V),\n    k1 <> k2 /\\ insert k1 v1 (insert k2 v2 t) <> insert k2 v2 (insert k1 v1 t).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Converting a BST to a List *)\n\n(** Let's add a new operation to our BST: converting it to an\n    _association list_ that contains the key--value bindings from the\n    tree stored as pairs.  If that list is sorted by the keys, then\n    any two trees that represent the same map would be converted to\n    the same list. Here's a function that does so with an in-order\n    traversal of the tree: *)\n\nFixpoint elements {V : Type} (t : tree V) : list (key * V) :=\n  match t with\n  | E => []\n  | T l k v r => elements l ++ [(k, v)] ++ elements r\n  end.\n\nExample elements_ex :\n    elements ex_tree = [(2, \"two\"); (4, \"four\"); (5, \"five\")]%string.\nProof. reflexivity. Qed.\n\n(** Here are three desirable properties for [elements]:\n\n    1. The list has the same bindings as the tree.\n\n    2. The list is sorted by keys.\n\n    3. The list contains no duplicates.\n\n    Let's formally specify and verify them. *)\n\n(* ================================================================= *)\n(** ** Part 1: Same Bindings *)\n\n(** We want to show that a binding is in [elements t] iff it's in\n    [t]. We'll prove the two directions of that bi-implication\n    separately:\n\n    - [elements] is _complete_: if a binding is in [t] then it's in\n      [elements t].\n\n    - [elements] is _correct_: if a binding is in [elements t] then\n      it's in [t].  *)\n\n(** Getting the specification of completeness right is a little\n    tricky.  It's tempting to start off with something too simple like\n    this: *)\n\nDefinition elements_complete_broken_spec :=\n  forall (V : Type) (k : key) (v d : V) (t : tree V),\n    BST t ->\n    lookup d k t = v ->\n    In (k, v) (elements t).\n\n(** The problem with that specification is how it handles the default\n    element [d]: the specification would incorrectly require [elements\n    t] to contain a binding [(k, d)] for all keys [k] unbound in\n    [t]. That would force [elements t] to be infinitely long, since\n    it would have to contain a binding for every natural number. We can\n    observe this problem right away if we begin the proof: *)\n\nTheorem elements_complete_broken : elements_complete_broken_spec.\nProof.\n  unfold elements_complete_broken_spec. intros. induction t.\n  - (* t = E *) simpl.\n    (** We have nothing to work with, since [elements E] is [[]]. *)\nAbort.\n\n(** The solution is to check first to see whether [k] is bound in [t].\n    Only bound keys need be in the list of elements: *)\n\nDefinition elements_complete_spec :=\n  forall (V : Type) (k : key) (v d : V) (t : tree V),\n    BST t ->\n    bound k t = true ->\n    lookup d k t = v ->\n    In (k, v) (elements t).\n\n(** **** Exercise: 3 stars, standard (elements_complete)  *)\n\n(** Prove that [elements] is complete. Proceed by induction on [t]. *)\nLemma geimpeq : forall (m : nat) (n : nat), (n >= m ) -> ( m >= n) -> (m = n).\nProof.\n intros. omega.\nQed.\n\nTheorem elements_complete : elements_complete_spec.\nProof.\n  unfold elements_complete_spec. intros. bdall. induction t.\n  - simpl. discriminate. \n  - simpl. apply in_app_iff. simpl. inv H. inv H0. \n    simpl in IHt2. simpl in IHt1. bdall. right. left. \n    apply geimpeq in H0. rewrite H0. reflexivity.\n    apply H.\nQed.\n(** [] *)\n\n(** The specification for correctness likewise mentions that the\n    key must be bound: *)\n\nDefinition elements_correct_spec :=\n  forall (V : Type) (k : key) (v d : V) (t : tree V),\n    BST t ->\n    In (k, v) (elements t) ->\n    bound k t = true /\\ lookup d k t = v.\n\n(** Proving correctness requires more work than completeness.\n\n    [BST] uses [ForallT] to say that all nodes in the left/right\n    subtree have smaller/greater keys than the root.  We need to\n    relate [ForallT], which expresses that all nodes satisfy a\n    property, to [Forall], which expresses that all list elements\n    satisfy a property.\n\n    We begin with this lemma about [Forall], which is missing from the\n    standard library. *)\n\nLemma Forall_app : forall (A: Type) (P : A -> Prop) (l1 l2 : list A),\n    Forall P l1 -> Forall P l2 -> Forall P (l1 ++ l2).\nProof.\n  induction l1; intros; simpl; auto; inv H; constructor; auto.\nQed.\n\n(** **** Exercise: 2 stars, standard (elements_preserves_forall)  *)\n\n(** Prove that if a property [P] holds of every node in a tree [t],\n    then that property holds of every pair in [elements t]. Proceed\n    by induction on [t].\n\n    There is a little mismatch between the type of [P] in [ForallT]\n    and the type of the property accepted by [Forall], so we have to\n    _uncurry_ [P] when we pass it to [Forall]. (See [Poly] for\n    more about uncurrying.) The single quote used below is the Coq\n    syntax for doing a pattern match in the function arguments. *)\n\nDefinition uncurry {X Y Z : Type} (f : X -> Y -> Z) '(a, b) :=\n  f a b.\n\nHint Transparent uncurry.\n\nLemma elements_preserves_forall : forall (V : Type) (P : key -> V -> Prop) (t : tree V),\n    ForallT P t ->\n    Forall (uncurry P) (elements t).\nProof.\n  intros. induction t.\n  - simpl. constructor.\n  - simpl. inversion H. destruct H1. apply Forall_app. apply IHt1. apply H.\n    constructor. unfold uncurry. apply H0.\n    apply IHt2. apply H2.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (elements_preserves_relation)  *)\n\n(** Prove that if all the keys in [t] are in a relation [R] with a\n    distinguished key [k'], then any key [k] in [elements t] is also\n    related by [R] to [k']. For example, [R] could be [<], in which\n    case the lemma says that if all the keys in [t] are less than\n    [k'], then all the keys in [elements t] are also less than\n    [k'].\n\n    Hint: you don't need induction.  Immediately look for a way\n    to use [elements_preserves_forall] and library theorem\n    [Forall_forall]. *)\n\nLemma elements_preserves_relation :\n  forall (V : Type) (k k' : key) (v : V) (t : tree V) (R : key -> key -> Prop),\n    ForallT (fun y _ => R y k') t\n    -> In (k, v) (elements t)\n    -> R k k'.\nProof.\n  intros. apply elements_preserves_forall in H.\n  Search \"Forall_forall\". rewrite Forall_forall in H.\n  apply H in H0. apply H0.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 4 stars, standard (elements_correct)  *)\n\n(** Prove that [elements] is correct. Proceed by induction on the\n    evidence that [t] is a BST. *)\n\nTheorem elements_correct : elements_correct_spec.\nProof.\n  unfold elements_correct_spec. intros. induction t.\n  -  simpl in H0. inversion H0.\n  - inv H.\n    simpl in H0. apply in_app_iff in H0. simpl in H0.\n    simpl. bdall.\n    + destruct H0.  \n    apply IHt1. apply H7.  assumption. \n    apply IHt1. apply H7. \n    apply elements_preserves_relation with (k := k) (v := v) in H6.\n    omega.\n    destruct H0.  apply Nat.lt_neq in H. \n    unfold not in H. inversion H0. symmetry in H2. apply H in H2. \n    inversion H2.\n    apply H0.\n    + inv H0. apply elements_preserves_relation with (k := k) (v := v) in H5.\n    omega.\n    apply H2.\n    apply IHt2. apply H8. destruct H2. inv H0.\n    omega.\n    apply H0.\n    + split. reflexivity.\n      inv H0. apply elements_preserves_relation with (k := k) (v := v) in H5.\n      omega. apply H2.\n      inv H2. inv H0. reflexivity.\n      apply elements_preserves_relation with (k := k) (v := v) in H6.\n      omega. apply H0.\nQed.\n\n(** [] *)\n\n(** The inverses of completeness and correctness also should hold:\n\n    - inverse completeness: if a binding is not in [t] then it's not\n      in [elements t].\n\n    - inverse correctness: if a binding is not in [elements t] then\n      it's not in [t].\n\n    Let's prove that they do. *)\n\n(** **** Exercise: 2 stars, advanced (elements_complete_inverse)  *)\n\n(** This inverse doesn't require induction.  Look for a way to use\n    [elements_correct] to quickly prove the result. *)\n\nTheorem elements_complete_inverse :\n  forall (V : Type) (k : key) (v : V) (t : tree V),\n    BST t ->\n    bound k t = false ->\n    ~ In (k, v) (elements t).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (elements_correct_inverse)  *)\n\n(** Prove the inverse.  First, prove this helper lemma by induction on\n    [t]. *)\n\nLemma bound_value : forall (V : Type) (k : key) (t : tree V),\n    bound k t = true -> exists v, forall d, lookup d k t = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Prove the main result.  You don't need induction. *)\n\nTheorem elements_correct_inverse :\n  forall (V : Type) (k : key) (t : tree V),\n    BST t ->\n    (forall v, ~ In (k, v) (elements t)) ->\n    bound k t = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Part 2: Sorted (Advanced) *)\n\n(** We want to show that [elements] is sorted by keys.  We follow a\n    proof technique contributed by Lydia Symmons et al.*)\n\n(** **** Exercise: 3 stars, advanced (sorted_app)  *)\n\n(** Prove that inserting an intermediate value between two lists\n    maintains sortedness. Proceed by induction on the evidence\n    that [l1] is sorted. *)\n\nLemma sorted_app: forall l1 l2 x,\n  Sort.sorted l1 -> Sort.sorted l2 ->\n  Forall (fun n => n < x) l1 -> Forall (fun n => n > x) l2 ->\n  Sort.sorted (l1 ++ x :: l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (sorted_elements)  *)\n\n(** The keys in an association list are the first elements of every\n    pair: *)\n\nDefinition list_keys {V : Type} (lst : list (key * V)) :=\n  map fst lst.\n\n(** Prove that [elements t] is sorted by keys. Proceed by induction\n    on the evidence that [t] is a BST. *)\n\nTheorem sorted_elements : forall (V : Type) (t : tree V),\n    BST t -> Sort.sorted (list_keys (elements t)).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Part 3: No Duplicates (Advanced and Optional) *)\n\n(** We want to show that [elements t] contains no duplicate\n    bindings. Tree [t] itself cannot contain any duplicates, so the\n    list that [elements] produces shouldn't either. The standard\n    library already contains a helpful inductive proposition,\n    [NoDup]. *)\n\nPrint NoDup.\n\n(** The library is missing a theorem, though, about [NoDup] and [++].\n    To state that theorem, we first need to formalize what it means\n    for two lists to be disjoint: *)\n\nDefinition disjoint {X:Type} (l1 l2: list X) := forall (x : X),\n    In x l1 -> ~ In x l2.\n\n(** **** Exercise: 3 stars, advanced, optional (NoDup_append)  *)\n\n(** Prove that if two lists are disjoint, appending them preserves\n    [NoDup].  Hint: You might already have proved this theorem in an\n    advanced exercise in [IndProp]. *)\n\nLemma NoDup_append : forall (X:Type) (l1 l2: list X),\n  NoDup l1 -> NoDup l2 -> disjoint l1 l2 ->\n  NoDup (l1 ++ l2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (elements_nodup_keys)  *)\n\n(** Prove that there are no duplicate keys in the list returned\n    by [elements]. Proceed by induction on the evidence that [t] is a\n    BST. Make use of library theorems about [map] as needed. *)\n\nTheorem elements_nodup_keys : forall (V : Type) (t : tree V),\n    BST t ->\n    NoDup (list_keys (elements t)).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** That concludes the proof of correctness of [elements]. *)\n\n(* ################################################################# *)\n(** * A Faster [elements] Implementation *)\n\n(** The implemention of [elements] is inefficient because of how\n    it uses the [++] operator.  On a balanced tree its running time is\n    linearithmic, because it does a linear number of concatentations\n    at each level of the tree. On an unbalanced tree it's quadratic\n    time.  Here's a tail-recursive implementation than runs in linear\n    time, regardless of whether the tree is balanced: *)\n\nFixpoint fast_elements_tr {V : Type} (t : tree V)\n         (acc : list (key * V)) : list (key * V) :=\n  match t with\n  | E => acc\n  | T l k v r => fast_elements_tr l ((k, v) :: fast_elements_tr r acc)\n  end.\n\nDefinition fast_elements {V : Type} (t : tree V) : list (key * V) :=\n  fast_elements_tr t [].\n\n(** **** Exercise: 3 stars, standard (fast_elements_eq_elements)  *)\n\n(** Prove that [fast_elements] and [elements] compute the same\n    function. *)\n\nLemma fast_elements_tr_helper :\n  forall (V : Type) (t : tree V) (lst : list (key * V)),\n    fast_elements_tr t lst = elements t ++ lst.\nProof.\n  intros. generalize dependent lst. induction t.\n  - simpl. reflexivity.\n  - simpl. intros. rewrite IHt1. rewrite IHt2. rewrite <- app_assoc.\n    reflexivity.\nQed.\n\nLemma fast_elements_eq_elements : forall (V : Type) (t : tree V),\n    fast_elements t = elements t.\nProof.\n  intros. unfold fast_elements. rewrite fast_elements_tr_helper.\n  rewrite app_nil_r. reflexivity.\nQed.\n\n(** [] *)\n\n(** Since the two implementations compute the same function, all\n    the results we proved about the correctness of [elements]\n    also hold for [fast_elements].  For example: *)\n\nCorollary fast_elements_correct :\n  forall (V : Type) (k : key) (v d : V) (t : tree V),\n    BST t ->\n    In (k, v) (fast_elements t) ->\n    bound k t = true /\\ lookup d k t = v.\nProof.\n  intros. rewrite fast_elements_eq_elements in *.\n  apply elements_correct; assumption.\nQed.\n\n(** This corollary illustrates a general technique:  prove the correctness\n    of a simple, slow implementation; then prove that the slow version\n    is functionally equivalent to a fast implementation.  The proof of\n    correctness for the fast implementation then comes \"for free\". *)\n\n(* ################################################################# *)\n(** * An Algebraic Specification of [elements] *)\n\n(** The verification of [elements] we did above did not adhere to the\n    algebraic specifcation approach, which would suggest that we look\n    for equations of the form\n\n      elements empty_tree = ...\n      elements (insert k v t) = ... (elements t) ...\n\n    The first of these is easy; we can trivially prove the following:\n    *)\n\nLemma elements_empty : forall (V : Type),\n    @elements V empty_tree = [].\nProof.\n  intros. simpl. reflexivity.\nQed.\n\n(** But for the second equation, we have to express the result of\n    inserting [(k, v)] into the elements list for [t], accounting for\n    ordering and the possibility that [t] may already contain a pair\n    [(k, v')] which must be replaced.  The following rather ugly\n    function will do the trick: *)\n\nFixpoint kvs_insert {V : Type} (k : key) (v : V) (kvs : list (key * V)) :=\n  match kvs with\n  | [] => [(k, v)]\n  | (k', v') :: kvs' =>\n    if k <? k' then (k, v) :: kvs\n    else if k >? k' then (k', v') :: kvs_insert k v kvs'\n         else (k, v) :: kvs'\n  end.\n\n(** That's not satisfactory, because the definition of\n    [kvs_insert] is so complex. Moreover, this equation doesn't tell\n    us anything directly about the overall properties of [elements t]\n    for a given tree [t].  Nonetheless, we can proceed with a rather\n    ugly verification. *)\n\n(** **** Exercise: 3 stars, standard, optional (kvs_insert_split)  *)\nLemma kvs_insert_split :\n  forall (V : Type) (v v0 : V) (e1 e2 : list (key * V)) (k k0 : key),\n    Forall (fun '(k',_) => k' < k0) e1 ->\n    Forall (fun '(k',_) => k' > k0) e2 ->\n    kvs_insert k v (e1 ++ (k0,v0):: e2) =\n    if k <? k0 then\n      (kvs_insert k v e1) ++ (k0,v0)::e2\n    else if k >? k0 then\n           e1 ++ (k0,v0)::(kvs_insert k v e2)\n         else\n           e1 ++ (k,v)::e2.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (kvs_insert_elements)  *)\nLemma kvs_insert_elements : forall (V : Type) (t : tree V),\n    BST t ->\n    forall (k : key) (v : V),\n      elements (insert k v t) = kvs_insert k v (elements t).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Model-based Specifications *)\n\n(** At the outset, we mentioned studying two techniques for\n    specifying the correctness of BST operations in this chapter.  The\n    first was algebraic specification.\n\n    Another approach to proving correctness of search trees is to\n    relate them to our existing implementation of functional partial\n    maps, as developed in [Maps]. To prove the correctness of a\n    search-tree algorithm, we can prove:\n\n    - Any search tree corresponds to some functional partial map,\n      using a function or relation that we write down.\n\n    - The [lookup] operation on trees gives the same result as the\n      [find] operation on the corresponding map.\n\n    - Given a tree and corresponding map, if we [insert] on the tree\n      and [update] the map with the same key and value, the resulting\n      tree and map are in correspondence.\n\n    This approach is sometimes called _model-based specification_: we\n    show that our implementation of a data type corresponds to a more\n    more abstract _model_ type that we already understand. To reason\n    about programs that use the implementation, it suffices to reason\n    about the behavior of the abstract type, which may be\n    significantly easier.  For example, we can take advantage of laws\n    that we proved for the abstract type, like [update_eq] for\n    functional maps, without having to prove them again for the\n    concrete tree type.\n\n    We also need to be careful here, because the type of functional\n    maps as defined in [Maps] do not actually behave quite like\n    our tree-based maps. For one thing, functional maps can be defined\n    on an infinite number of keys, and there is no mechanism for\n    enumerating over the key set. To maintain correspondence with our\n    finite trees, we need to make sure that we consider only\n    functional maps built by finitely many applications of constructor\n    functions ([empty] and [update]). Also, thanks to functional\n    extensionality, functional maps obey stronger equality laws than\n    our trees do (as we investigated in the [direct_equalities]\n    exercise above), so we should not be misled into thinking that\n    every fact we can prove about abstract maps necessarily holds for\n    concrete ones.\n\n    Compared to the algebraic-specification approach described earlier\n    in this chapter, the model-based approach can save some proof\n    effort, especially if we already have a well-developed theory for\n    the abstract model type.  On the other hand, we have to give an\n    explicit _abstraction_ relation between trees and maps, and show\n    that it is maintained by all operations. In the end, about the\n    same amount of work is needed to show correctness, though the work\n    shows up in different places depending on how the abstraction\n    relation is defined. *)\n\n(** We now give a model-based specification for trees in terms\n    of functional partial maps. It is based on a simple abstraction\n    relation that builds a functional map element by element. *)\n\nFixpoint map_of_list {V : Type} (el : list (key * V)) : partial_map V :=\n  match el with\n  | [] => empty\n  | (k, v) :: el' => update (map_of_list el') k v\n  end.\n\nDefinition Abs {V : Type} (t : tree V) : partial_map V :=\n  map_of_list (elements t).\n\n(** In general, model-based specifications may use an abstraction\n    relation, allowing each concrete value to be related to multiple\n    abstract values.  But in this case a simple abstraction _function_\n    will do, assigning a unique abstract value to each concrete\n    one. *)\n\n(** One small difference between trees and functional maps is that\n    applying the latter returns an [option V] which might be [None],\n    whereas [lookup] returns a default value if key is not bound\n    lookup fails.  We can easily provide a function on functional\n    partial maps having the latter behavior. *)\n\nDefinition find {V : Type} (d : V) (k : key) (m : partial_map V) : V :=\n  match m k with\n  | Some v => v\n  | None => d\n  end.\n\n(** We also need a [bound] operation on maps. *)\n\nDefinition map_bound {V : Type} (k : key) (m : partial_map V) : bool :=\n  match m k with\n  | Some _ => true\n  | None => false\n  end.\n\n(** We now proceed to prove that each operation preserves (or establishes)\n    the abstraction relationship in an appropriate way:\n\n    concrete        abstract\n    --------        --------\n    empty_tree      empty\n    bound           map_bound\n    lookup          find\n    insert          update\n*)\n\n(** The following lemmas will be useful, though you are not required\n    to prove them. They can all be proved by induction on the list. *)\n\n(** **** Exercise: 2 stars, standard, optional (in_fst)  *)\nLemma in_fst : forall (X Y : Type) (lst : list (X * Y)) (x : X) (y : Y),\n    In (x, y) lst -> In x (map fst lst).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (in_map_of_list)  *)\nLemma in_map_of_list : forall (V : Type) (el : list (key * V)) (k : key) (v : V),\n    NoDup (map fst el) ->\n    In (k,v) el -> (map_of_list el) k = Some v.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (not_in_map_of_list)  *)\nLemma not_in_map_of_list : forall (V : Type) (el : list (key * V)) (k : key),\n    ~ In k (map fst el) -> (map_of_list el) k = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nLemma empty_relate : forall (V : Type),\n    @Abs V empty_tree = empty.\nProof.\n  reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard, optional (bound_relate)  *)\n\nTheorem bound_relate : forall (V : Type) (t : tree V) (k : key),\n    BST t ->\n    map_bound k (Abs t) = bound k t.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (lookup_relate)  *)\n\nLemma lookup_relate : forall (V : Type) (t : tree V) (d : V) (k : key),\n    BST t -> find d k (Abs t) = lookup d k t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (insert_relate)  *)\nLemma insert_relate : forall (V : Type) (t : tree V) (k : key) (v : V),\n  BST t -> Abs (insert k v t) = update (Abs t) k v.\nProof.\n  (* TODO: find a direct proof that doesn't rely on [kvs_insert_elements] *)\n    unfold Abs.\n  intros.\n  rewrite kvs_insert_elements; auto.\n  remember (elements t) as l.\n  clear -l. (* clear everything not about [l] *)\n  (* Hint: proceed by induction on [l]. *)\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The previous three lemmas are in essence saying that the following\n    diagrams commute.\n\n             bound k\n      t -------------------+\n      |                    |\n  Abs |                    |\n      V                    V\n      m -----------------> b\n           map_bound k\n\n            lookup d k\n      t -----------------> v\n      |                    |\n  Abs |                    | Some\n      V                    V\n      m -----------------> Some v\n             find d k\n\n            insert k v\n      t -----------------> t'\n      |                    |\n  Abs |                    | Abs\n      V                    V\n      m -----------------> m'\n            update' k v\n\n    Where we define:\n\n      update' k v m = update m k v\n\n*)\n\n(** Functional partial maps lack a way to extract or iterate\n    over their elements, so we cannot give an analogous abstract\n    operation for [elements]. Instead, we can prove this trivial\n    little lemma. *)\n\nLemma elements_relate : forall (V : Type) (t : tree V),\n  BST t ->\n  map_of_list (elements t) = Abs t.\nProof.\n  unfold Abs. intros. reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * An Alternative Abstraction Relation (Optional, Advanced) *)\n\n(** There is often more than one way to specify a suitable abstraction\n    relation between given concrete and abstract datatypes. The\n    following exercises explore another way to relate search trees to\n    functional partial maps without using [elements] as an\n    intermediate step.\n\n    We extend our definition of functional partial maps by adding a\n    new primitive for combining two partial maps, which we call\n    [union].  Our intention is that it only be used to combine maps\n    with disjoint key sets; to keep the operation symmetric, we make\n    the result be undefined on any key they have in common.  *)\n\nDefinition union {X} (m1 m2: partial_map X) : partial_map X :=\n  fun k =>\n    match (m1 k, m2 k) with\n    | (None, None) => None\n    | (None, Some v) => Some v\n    | (Some v, None) => Some v\n    | (Some _, Some _) => None\n    end.\n\n(** We can prove some simple properties of lookup and update on unions,\n    which will prove useful later. *)\n\n(** **** Exercise: 2 stars, standard, optional (union_collapse)  *)\nLemma union_left : forall {X} (m1 m2: partial_map X) k,\n    m2 k = None -> union m1 m2 k = m1 k.\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma union_right : forall {X} (m1 m2: partial_map X) k,\n    m1 k = None ->\n    union m1 m2 k = m2 k.\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma union_both : forall {X} (m1 m2 : partial_map X) k v1 v2,\n    m1 k = Some v1 ->\n    m2 k = Some v2 ->\n    union m1 m2 k = None.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (union_update)  *)\nLemma union_update_right : forall {X} (m1 m2: partial_map X) k v,\n    m1 k = None ->\n    update (union m1 m2) k v = union m1 (update m2 k v).\nProof.\n(* FILL IN HERE *) Admitted.\n\nLemma union_update_left : forall {X} (m1 m2: partial_map X) k v,\n    m2 k = None ->\n    update (union m1 m2) k v = union (update m1 k v) m2.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We can now write a direct conversion function from trees to maps\n    based on the structure of the tree, and prove a basic property\n    preservation result. *)\n\nFixpoint map_of_tree {V : Type} (t: tree V) : partial_map V :=\n  match t with\n  | E => empty\n  | T l k v r => update (union (map_of_tree l) (map_of_tree r)) k v\n  end.\n\n(** **** Exercise: 3 stars, advanced, optional (map_of_tree_prop)  *)\nLemma map_of_tree_prop : forall (V : Type) (P : key -> V -> Prop) (t : tree V),\n    ForallT P t ->\n    forall k v, (map_of_tree t) k = Some v ->\n           P k v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Finally, we define our new abstraction function, and prove the\n    same lemmas as before. *)\n\nDefinition Abs' {V : Type} (t: tree V) : partial_map V :=\n  map_of_tree t.\n\nLemma empty_relate' : forall (V : Type),\n    @Abs' V empty_tree = empty.\nProof.\n  reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, advanced, optional (bound_relate')  *)\nTheorem bound_relate' : forall (V : Type) (t : tree V) (k : key),\n    BST t ->\n    map_bound k (Abs' t) = bound k t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (lookup_relate')  *)\nLemma lookup_relate' : forall (V : Type) (d : V) (t : tree V) (k : key),\n    BST t -> find d k (Abs' t) = lookup d k t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (insert_relate')  *)\nLemma insert_relate' : forall (V : Type) (k : key) (v : V) (t : tree V),\n   BST t -> Abs' (insert k v t) = update (Abs' t) k v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The [elements_relate] lemma, which was trivial for our previous [Abs]\n    function, is considerably harder this time.  We suggest starting with\n    an auxiliary lemma. *)\n\n(** **** Exercise: 3 stars, advanced, optional (map_of_list_app)  *)\nLemma map_of_list_app : forall (V : Type) (el1 el2: list (key * V)),\n   disjoint (map fst el1) (map fst el2) ->\n   map_of_list (el1 ++ el2) = union (map_of_list el1) (map_of_list el2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (elements_relate')  *)\nLemma elements_relate' : forall (V : Type) (t : tree V),\n  BST t ->\n  map_of_list (elements t) = Abs' t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Efficiency of Search Trees *)\n\n(** All the theory we've developed so far has been about correctness.\n    But the reason we use binary search trees is that they are\n    efficient.  That is, if there are [N] elements in a (reasonably\n    well balanced) BST, each insertion or lookup takes about [log N]\n    time.\n\n    What could go wrong?\n\n     1. The search tree might not be balanced.  In that case, each\n        insertion or lookup will take as much as linear time.\n\n        - SOLUTION: use an algorithm that ensures the trees stay\n          balanced.  We'll do that in [Redblack].\n\n     2. Our keys are natural numbers, and Coq's [nat] type takes linear\n        time per comparison.  That is, computing (j <? k) takes time\n        proportional to the value of [k-j].\n\n        - SOLUTION: represent keys by a data type that has a more\n          efficient comparison operator.  We used [nat] in this chapter\n          because it's something easy to work with.\n\n     3. There's no notion of running time in Coq.  That is, we can't\n        say what it means that a Coq function \"takes N steps to\n        evaluate.\"  Therefore, we can't prove that binary search trees\n        are efficient.\n\n        - SOLUTION 1: Don't prove (in Coq) that they're efficient;\n          just prove that they are correct.  Prove things about their\n          efficiency the old-fashioned way, on pencil and paper.\n\n        - SOLUTION 2: Prove in Coq some facts about the height of the\n          trees, which have direct bearing on their efficiency.  We'll\n          explore that in [Redblack].\n\n        - SOLUTION 3: Apply bleeding-edge frameworks for reasoning\n          about run-time of programs represented in Coq.\n\n      4. Our functions in Coq are models of implementations in \"real\"\n         programming languages.  What if the real implementations\n         differ from the Coq models?\n\n         - SOLUTION: Use Coq's [extraction] feature to derive the real\n\t   implementation (in Ocaml or Haskell) automatically from the\n\t   Coq function.  Or, use Coq's [Compute] or [Eval\n\t   native_compute] feature to compile and run the programs\n\t   efficiently inside Coq.  We'll explore [extraction] in a\n\t   [Extract]. *)\n\n(* Mon May 11 23:21:35 EDT 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/finalsrc/SearchTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8824278556326344, "lm_q1q2_score": 0.741004644394898}}
{"text": "Require Export GeoCoq.Tarski_dev.Definitions.\nRequire Export GeoCoq.Tactics.finish.\n\nLtac prolong A B x C D :=\n assert (sg:= segment_construction A B C D);\n ex_and sg x.\n\nSection T1_1.\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\nLemma cong_reflexivity : forall A B,\n Cong A B A B.\nProof.\n    intros.\n    apply (cong_inner_transitivity B A A B); apply cong_pseudo_reflexivity.\nQed.\n\nLemma cong_symmetry : forall A B C D : Tpoint,\n Cong A B C D -> Cong C D A B.\nProof.\n    intros.\n    eapply cong_inner_transitivity.\n      apply H.\n    apply cong_reflexivity.\nQed.\n\nLemma cong_transitivity : forall A B C D E F : Tpoint,\n Cong A B C D -> Cong C D E F -> Cong A B E F.\nProof.\n    intros.\n    eapply cong_inner_transitivity; eauto using cong_symmetry.\nQed.\n\nLemma cong_left_commutativity : forall A B C D,\n Cong A B C D -> Cong B A C D.\nProof.\n    intros.\n    eapply cong_inner_transitivity.\n      apply cong_symmetry.\n      apply cong_pseudo_reflexivity.\n    assumption.\nQed.\n\nLemma cong_right_commutativity : forall A B C D,\n Cong A B C D -> Cong A B D C.\nProof.\n    intros.\n    apply cong_symmetry.\n    apply cong_symmetry in H.\n    apply cong_left_commutativity.\n    assumption.\nQed.\n\nLemma cong_3421 : forall A B C D,\n Cong A B C D -> Cong C D B A.\nProof.\n    auto using cong_symmetry, cong_right_commutativity.\nQed.\n\nLemma cong_4312 : forall A B C D,\n Cong A B C D -> Cong D C A B.\nProof.\n    auto using cong_symmetry, cong_right_commutativity.\nQed.\n\nLemma cong_4321 : forall A B C D,\n Cong A B C D -> Cong D C B A.\nProof.\n    auto using cong_symmetry, cong_right_commutativity.\nQed.\n\n\nLemma cong_trivial_identity : forall A B : Tpoint,\n Cong A A B B.\nProof.\n    intros.\n    prolong A B E A A.\n    eapply cong_inner_transitivity.\n      apply H0.\n    assert(B=E).\n      eapply cong_identity.\n      apply H0.\n    subst.\n    apply cong_reflexivity.\nQed.\n\nLemma cong_reverse_identity : forall A C D,\n Cong A A C D -> C=D.\nProof.\n    intros.\n    apply cong_symmetry in H.\n    eapply cong_identity.\n    apply H.\nQed.\n\nLemma cong_commutativity : forall A B C D,\n Cong A B C D -> Cong B A D C.\nProof.\n    intros.\n    apply cong_left_commutativity.\n    apply cong_right_commutativity.\n    assumption.\nQed.\n\nEnd T1_1.\n\nHint Resolve cong_commutativity cong_3421 cong_4312 cong_4321 cong_trivial_identity\n             cong_left_commutativity cong_right_commutativity\n             cong_transitivity cong_symmetry cong_reflexivity : cong.\n\nLtac Cong := auto 4 with cong.\nLtac eCong := eauto with cong.\n\nSection T1_2.\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\n(* We pre-compute some trivial lemmas to have more efficient automatic proofs. *)\n\nLemma not_cong_2134 : forall A B C D, ~ Cong A B C D -> ~ Cong B A C D.\nProof.\nauto with cong.\nQed.\n\nLemma not_cong_1243 : forall A B C D, ~ Cong A B C D -> ~ Cong A B D C.\nProof.\nauto with cong.\nQed.\n\nLemma not_cong_2143 : forall A B C D, ~ Cong A B C D -> ~ Cong B A D C.\nProof.\nauto with cong.\nQed.\n\nLemma not_cong_3412 : forall A B C D, ~ Cong A B C D -> ~ Cong C D A B.\nProof.\nauto with cong.\nQed.\n\nLemma not_cong_4312 : forall A B C D, ~ Cong A B C D -> ~ Cong D C A B.\nProof.\nauto with cong.\nQed.\n\nLemma not_cong_3421 : forall A B C D, ~ Cong A B C D -> ~ Cong C D B A.\nProof.\nauto with cong.\nQed.\n\nLemma not_cong_4321 : forall A B C D, ~ Cong A B C D -> ~ Cong D C B A.\nProof.\nauto with cong.\nQed.\n\nEnd T1_2.\n\nHint Resolve not_cong_2134 not_cong_1243 not_cong_2143\n             not_cong_3412 not_cong_4312 not_cong_3421 not_cong_4321 : cong.\n\nSection T1_3.\n\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\nLemma five_segment_with_def : forall A B C D A' B' C' D',\n OFSC A B C D A' B' C' D' -> A<>B -> Cong C D C' D'.\nProof.\n    unfold OFSC.\n    intros;spliter.\n    apply (five_segment A A' B B'); assumption.\nQed.\n\nLemma cong_diff : forall A B C D : Tpoint,\n A <> B -> Cong A B C D -> C <> D.\nProof.\n    intros.\n    intro.\n    subst.\n    apply H.\n    eauto using cong_identity.\nQed.\n\nLemma cong_diff_2 : forall A B C D ,\n B <> A -> Cong A B C D -> C <> D.\nProof.\n    intros.\n    intro;subst.\n    apply H.\n    symmetry.\n    eauto using cong_identity, cong_symmetry.\nQed.\n\nLemma cong_diff_3 : forall A B C D ,\n C <> D -> Cong A B C D -> A <> B.\nProof.\n    intros.\n    intro;subst.\n    apply H.\n    eauto using cong_identity, cong_symmetry.\nQed.\n\nLemma cong_diff_4 : forall A B C D ,\n D <> C -> Cong A B C D -> A <> B.\nProof.\n    intros.\n    intro;subst.\n    apply H.\n    symmetry.\n    eauto using cong_identity, cong_symmetry.\nQed.\n\nLemma cong_3_sym : forall A B C A' B' C',\n Cong_3 A B C A' B' C' -> Cong_3 A' B' C' A B C.\nProof.\n    unfold Cong_3.\n    intuition.\nQed.\n\nLemma cong_3_swap : forall A B C A' B' C',\n  Cong_3 A B C A' B' C' -> Cong_3 B A C B' A' C'.\nProof.\n    unfold Cong_3.\n    intuition.\nQed.\n\nLemma cong_3_swap_2 : forall A B C A' B' C',\n Cong_3 A B C A' B' C' -> Cong_3 A C B A' C' B'.\nProof.\n    unfold Cong_3.\n    intuition.\nQed.\n\nLemma cong3_transitivity : forall A0 B0 C0 A1 B1 C1 A2 B2 C2,\n Cong_3 A0 B0 C0 A1 B1 C1 -> Cong_3 A1 B1 C1 A2 B2 C2 -> Cong_3 A0 B0 C0 A2 B2 C2.\nProof.\n    unfold Cong_3.\n    intros.\n    spliter.\n    repeat split; eapply cong_transitivity; eCong.\nQed.\n\nEnd T1_3.\n\nHint Resolve cong_3_sym : cong.\nHint Resolve cong_3_swap cong_3_swap_2 cong3_transitivity : cong3.\nHint Unfold Cong_3 : cong3.\n\nSection T1_4.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma eq_dec_points : forall A B : Tpoint, A=B \\/ ~ A=B.\nProof. exact point_equality_decidability. Qed.\n\nLemma distinct : forall P Q R : Tpoint, P <> Q -> (R <> P \\/ R <> Q).\nProof.\n    intros.\n    induction (eq_dec_points R P).\n      subst R.\n      right.\n      assumption.\n    left.\n    assumption.\nQed.\n\nLemma l2_11 : forall A B C A' B' C',\n Bet A B C -> Bet A' B' C' -> Cong A B A' B' -> Cong B C B' C' -> Cong A C A' C'.\nProof.\n    intros.\n    induction (eq_dec_points A B).\n      subst B.\n      assert (A' = B') by\n     (apply (cong_identity A' B' A); Cong).\n      subst; Cong.\n    apply cong_commutativity; apply (five_segment A A' B B' C C' A A'); Cong.\nQed.\n\nLemma bet_cong3 : forall A B C A' B',  Bet A B C -> Cong A B A' B' -> exists C', Cong_3 A B C A' B' C'.\nProof.\n    intros.\n    assert (exists x, Bet A' B' x /\\ Cong B' x B C) by (apply segment_construction).\n    ex_and H1 x.\n    assert (Cong A C A' x).\n      eapply l2_11.\n        apply H.\n        apply H1.\n        assumption.\n      Cong.\n    exists x;unfold Cong_3; repeat split;Cong.\nQed.\n\nLemma construction_uniqueness : forall Q A B C X Y,\n Q <> A -> Bet Q A X -> Cong A X B C -> Bet Q A Y -> Cong A Y B C -> X=Y.\nProof.\n    intros.\n    assert (Cong A X A Y) by (apply cong_transitivity with B C; Cong).\n    assert (Cong Q X Q Y) by (apply (l2_11 Q A X Q A Y);Cong).\n    assert(OFSC Q A X Y Q A X X) by (unfold OFSC;repeat split;Cong).\n    apply five_segment_with_def in H6; try assumption.\n    apply cong_identity with X; Cong.\nQed.\n\nLemma Cong_cases :\n forall A B C D,\n Cong A B C D \\/ Cong A B D C \\/ Cong B A C D \\/ Cong B A D C \\/\n Cong C D A B \\/ Cong C D B A \\/ Cong D C A B \\/ Cong D C B A ->\n Cong A B C D.\nProof.\n    intros.\n    decompose [or] H;clear H; Cong.\nQed.\n\nLemma Cong_perm :\n forall A B C D,\n Cong A B C D ->\n Cong A B C D /\\ Cong A B D C /\\ Cong B A C D /\\ Cong B A D C /\\\n Cong C D A B /\\ Cong C D B A /\\ Cong D C A B /\\ Cong D C B A.\nProof.\n    intros.\n    repeat split; Cong.\nQed.\n\nEnd T1_4.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Tarski_dev/Ch02_cong.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7409415916986727}}
{"text": "(* This file contains floating point functional models for the summation of\n  two lists, as well as theorems regarding their equivalence. *)\n\nRequire Import vcfloat.VCFloat.\nRequire Import List.\nImport List ListNotations.\n\nRequire Import Sorting Permutation.\n\nRequire Import common.\n\nRequire Import Reals.\nOpen Scope R.\n\n\nDefinition sum {A: Type} (sum_op : A -> A -> A) (a b : A) : A := sum_op a b.\n\nInductive sum_rel {A : Type} (default: A) (sum_op : A -> A -> A) : list A -> A -> Prop :=\n| sum_rel_nil  : sum_rel default sum_op [] default\n| sum_rel_cons : forall l a s,\n    sum_rel default sum_op l s ->\n    sum_rel default sum_op (a::l) (sum sum_op a s).\n\nDefinition sum_rel_R := @sum_rel R 0%R Rplus.\n\nLemma sum_rel_R_abs :\nforall l s1 s2,\nsum_rel_R l s1 -> sum_rel_R (map Rabs l) s2 -> s1 <= s2.\nProof.\ninduction l.\n-\nintros.\ninversion H.\ninversion H0.\nnra.\n-\nintros.\ninversion H; subst; clear H.\ninversion H0; subst; clear H0.\nunfold sum.\neapply Rplus_le_compat.\napply Rle_abs.\nfold sum_rel_R in H4.\nfold sum_rel_R in H3.\napply IHl;\nauto.\nQed.\n\nLemma sum_rel_R_Rabs_pos : \nforall l s,\nsum_rel_R (map Rabs l) s -> 0 <= s.\nProof.\ninduction  l.\n-\nintros.\ninversion H; nra.\n-\nintros.\ninversion H; subst; clear H.\nunfold sum.\nfold sum_rel_R in H3.\nspecialize (IHl s0 H3).\napply Rplus_le_le_0_compat; auto;\n  try apply Rabs_pos.\nQed.\n\nLemma sum_rel_R_Rabs_eq :\nforall l s,\nsum_rel_R (map Rabs l) s -> Rabs s = s.\nProof.\ninduction  l.\n-\nintros.\ninversion H.\nrewrite Rabs_R0.\nnra.\n-\nintros.\ninversion H; subst; clear H.\nunfold sum.\nreplace (Rabs(Rabs a + s0)) with \n  (Rabs a  + s0); try nra.\nsymmetry.\nrewrite Rabs_pos_eq; try nra.\napply Rplus_le_le_0_compat.\napply Rabs_pos.\neapply Rle_trans with (Rabs s0).\napply Rabs_pos.\neapply Req_le.\napply IHl.\nfold sum_rel_R in H3.\nauto.\nQed.\n\n\nLemma sum_rel_R_Rabs :\nforall l s1 s2,\nsum_rel_R l s1 -> sum_rel_R (map Rabs l) s2 -> Rabs s1 <= Rabs s2.\nProof.\ninduction l.\n-\nintros.\ninversion H.\ninversion H0.\nnra.\n-\nintros.\ninversion H; subst; clear H.\ninversion H0; subst; clear H0.\nfold sum_rel_R in H4.\nfold sum_rel_R in H3.\nunfold sum.\neapply Rle_trans.\napply Rabs_triang.\nreplace (Rabs(Rabs a + s0)) with \n  (Rabs a  + s0).\neapply Rplus_le_compat; try nra.\neapply Rle_trans with (Rabs s0).\nfold sum_rel_R in H4.\nfold sum_rel_R in H3.\napply IHl; auto.\napply Req_le.\neapply sum_rel_R_Rabs_eq; apply H3.\nsymmetry.\nrewrite Rabs_pos_eq; try nra.\napply Rplus_le_le_0_compat.\napply Rabs_pos.\neapply Rle_trans with (Rabs s0).\napply Rabs_pos.\napply Req_le.\neapply sum_rel_R_Rabs_eq; apply H3.\nQed.\n\n\nLemma sum_rel_R_single :\nforall (a : R) (fs : R), sum_rel_R [a] fs -> fs = a.\nProof.\nintros.\ninversion H; auto.\ninversion H3. subst.\nunfold sum; nra.\nQed.\n\nLemma sum_rel_R_single' :\nforall (a : R) , sum_rel_R [a] a.\nProof.\nintros.\nunfold sum_rel_R.\nreplace a with (a + 0) at 2 by nra. \napply sum_rel_cons. apply sum_rel_nil.\nQed. \n\nLemma sum_rel_R_app_cons :\nforall l' l'' a s,\nsum_rel_R (l' ++  l'') s ->\nsum_rel_R (l' ++ a :: l'') (a + s).\nProof.\ninduction l'; simpl.  \n{ intros; apply sum_rel_cons; auto. }\nintros. \ninversion H; subst; clear H.\nspecialize (IHl' l'' a0 s0 H3).\nunfold sum.\nreplace (a0 + (a + s0)) with (a + (a0 + s0)) by nra.\napply sum_rel_cons; auto.\nQed.\n\nLemma sum_rel_bound  :\n  forall (l : list R) (rs a: R)\n  (Hrs : sum_rel_R l rs)\n  (Hin : forall x, In x l -> Rabs x <= a),\n  Rabs rs <= INR (length l) * a.\nProof.\ninduction l; intros.\n{ inversion Hrs; subst; simpl; rewrite Rabs_R0; nra. }\n  inversion Hrs; subst. \n  unfold sum; eapply Rle_trans; [apply Rabs_triang|].\n  eapply Rle_trans; [apply Rplus_le_compat;\n  [apply Hin; simpl; auto| apply IHl; \n                        [ apply H2 | intros; apply Hin; simpl; auto ] ] | ].\n  apply Req_le. replace (length (a :: l)) with (length l + 1)%nat by (simpl; lia).\n  rewrite plus_INR; simpl; nra.\nQed.\n  \nLemma sum_rel_R_permute :\n  forall (l l0: list R)\n  (Hper: Permutation l l0) (rs: R)\n  (Hrs: sum_rel_R l rs),\n  sum_rel_R l0 rs.\nProof.\nintros ?.\ninduction l.\n{ intros; inversion Hrs; subst.\napply Permutation_nil in Hper; subst; simpl; auto. }\nintros.\napply Permutation_sym in Hper.\npose proof Permutation_vs_cons_inv Hper as H.\ndestruct H as (l' & l'' & H); subst.\napply Permutation_sym in Hper.\npose proof (@Permutation_cons_app_inv R l l' l'' a Hper).\ninversion Hrs; subst. fold sum_rel_R in H3.\nspecialize (IHl (l' ++ l'') H s H3).\nunfold sum; clear Hrs.\napply sum_rel_R_app_cons; auto.\nQed.\n\nLemma sum_rel_R_permute_t :\n  forall (t: type) (l l0: list (ftype t))\n  (Hper: Permutation l l0) (rs: R)\n  (Hrs: sum_rel_R (map FT2R l) rs),\n  sum_rel_R (map FT2R l0) rs.\nProof.\nintros;\napply sum_rel_R_permute with (map FT2R l); auto.\napply Permutation_map; auto.\nQed.\n\nSection NAN.\n\n\nFrom vcfloat Require Import IEEE754_extra.\n\nLemma plus_zero {NAN: Nans}  a:\nBinary.is_finite _ _ a = true -> \n(a + -0)%F32 = a.\nProof.\ndestruct a; simpl; auto;\nintros; try discriminate; auto;\ndestruct s;\ncbv; auto.\nQed.\n\nLemma sum_rel_bound'  :\n  forall (t : type) (l : list (ftype t)) (rs a: R)\n  (Hrs : sum_rel_R (map FT2R l) rs)\n  (Hin : forall x, In x l -> Rabs (FT2R x) <= a),\n  Rabs rs <= INR (length l) * a.\nProof.\ninduction l; intros.\n{ inversion Hrs; subst; simpl; rewrite Rabs_R0; nra. }\n  inversion Hrs; subst. \n  unfold sum; eapply Rle_trans; [apply Rabs_triang|].\n  eapply Rle_trans; [apply Rplus_le_compat;\n  [apply Hin; simpl; auto| apply IHl; \n                        [ apply H2 | intros; apply Hin; simpl; auto ] ] | ].\n  apply Req_le. replace (length (a :: l)) with (length l + 1)%nat by (simpl; lia).\n  rewrite plus_INR; simpl; nra.\nQed.\n\nLemma sum_rel_bound''  :\n  forall (t : type) (l : list (ftype t)) (rs_abs a: R)\n  (Hrs : sum_rel_R (map Rabs (map FT2R l)) rs_abs)\n  (Hin : forall x, In x l -> Rabs (FT2R x) <= a),\n  rs_abs <= INR (length l) * a.\nProof.\ninduction l; intros.\n{ inversion Hrs; subst; simpl; nra. }\n  inversion Hrs; subst.\n  unfold sum. fold sum_rel_R in H2.\n  eapply Rle_trans; [apply Rplus_le_compat;\n  [apply Hin; simpl; auto| apply IHl; \n                        [ apply H2 | intros; apply Hin; simpl; auto ] ] | ].\n  apply Req_le. replace (length (a :: l)) with (length l + 1)%nat by (simpl; lia).\n  rewrite plus_INR; simpl; nra.\nQed. \n\n\nLemma sum_rel_R_fold : forall l rs, \n   sum_rel_R l rs -> rs = fold_right Rplus 0 l.\nProof. \ninduction l.\nintros; inversion H; simpl; auto.\nintros; inversion H. \nfold sum_rel_R in H3.\nspecialize (IHl s H3).\nsubst; simpl.\nunfold sum; auto.\nQed.\n\nLemma sum_map_Rmult (l : list R) (s a: R):\nsum_rel_R l s -> \nsum_rel_R (map (Rmult a) l) (a * s). \nProof. \nrevert l s a. induction l.\n{ intros. simpl. inversion H; subst; rewrite Rmult_0_r; auto. }\nintros. inversion H. destruct l.\n{ simpl; unfold sum. inversion H3; subst. rewrite Rplus_0_r.\n  apply sum_rel_R_single'. }\nfold sum_rel_R in H3. specialize (IHl s0 a0 H3).\nunfold sum; simpl. rewrite Rmult_plus_distr_l; apply sum_rel_cons.\nfold sum_rel_R. simpl in IHl; auto.\nQed.\n\n\nDefinition sum_rel_Ft {NAN: Nans} (t: type) := @sum_rel (ftype t) neg_zero (BPLUS ).\n\nLemma sum_rel_Ft_single {NAN: Nans} t fs a:\nBinary.is_finite _ _ fs = true ->\nsum_rel_Ft t [a] fs -> fs = a.\nProof.\nintros.\ninversion H0.\ninversion H4; subst.\nunfold sum, BPLUS; destruct a; try discriminate; \n  simpl; auto.\ndestruct s; simpl; auto.\nQed.\n\nLemma sum_rel_R_exists {NAN: Nans}:\n  forall (t : type) (l : list (ftype t)) (fs : ftype t)\n  (Hfs : sum_rel_Ft t l fs),\n  exists rs, sum_rel_R (map FT2R l) rs.\nProof.\nintros ?. induction l.\n{ simpl; exists 0. apply sum_rel_nil. }\nintros. inversion Hfs; subst. \nfold (@sum_rel_Ft NAN t) in H2.\ndestruct (IHl s H2) as (rs & Hrs); clear IHl.\nexists (FT2R a + rs); simpl. \napply sum_rel_cons; auto.\nQed.\n\nLemma sum_rel_R_abs_exists {NAN: Nans}:\n  forall (t : type) (l : list (ftype t)) (fs : ftype t)\n  (Hfs : sum_rel_Ft t l fs),\n  exists rs, sum_rel_R (map Rabs (map FT2R l)) rs.\nProof.\nintros ?. induction l.\n{ simpl; exists 0. apply sum_rel_nil. }\nintros. inversion Hfs; subst. \nfold (@sum_rel_Ft NAN t) in H2.\ndestruct (IHl s H2) as (rs & Hrs); clear IHl.\nexists (Rabs (FT2R a) + rs); simpl. \napply sum_rel_cons; auto.\nQed.\n \nLemma is_finite_in {NAN: Nans} (t : type) :\n  forall (l : list (ftype t)) fs,\n  sum_rel_Ft t l fs ->\n  let e  := @default_abs t in\n  let d  := @default_rel t in \n  let ov := powerRZ 2 (femax t) in\n  Binary.is_finite (fprec t) (femax t) fs = true ->\n  forall a, In a l -> Binary.is_finite (fprec t) (femax t) a = true.\nProof.\ninduction l.\nsimpl; intros; auto.\nintros. \ndestruct H1; subst.\ninversion H.\nrewrite <- H2 in H0. clear H2.\nunfold sum in H0.\ndestruct a0, s; auto.\ndestruct s, s0; simpl in H0; try discriminate.\ninversion H.\nfold (@sum_rel_Ft NAN t) in H5.\nassert (Binary.is_finite (fprec t) (femax t) s = true).\nunfold sum in H3.\nrewrite <- H3 in H0. clear H3.\ndestruct a, s; auto.\ndestruct s, s0; simpl in H0; try discriminate.\nspecialize (IHl s H5 H6).\napply IHl; auto.\nQed.\n\n\n\nLemma sum_rel_Ft_fold {NAN: Nans} : forall t l fs, \n   sum_rel_Ft t l fs -> fs = fold_right (BPLUS ) neg_zero l.\nProof. \ninduction l.\nintros; inversion H; simpl; auto.\nintros; inversion H. \nfold (@sum_rel_Ft NAN t) in H3.\nspecialize (IHl s H3).\nsubst; simpl.\nunfold sum; auto.\nQed.\n\n\n\nEnd NAN.", "meta": {"author": "ak-2485", "repo": "BLAS_fp_error", "sha": "286db6fc51f4160fc74abc2f129ea05f0a37cc54", "save_path": "github-repos/coq/ak-2485-BLAS_fp_error", "path": "github-repos/coq/ak-2485-BLAS_fp_error/BLAS_fp_error-286db6fc51f4160fc74abc2f129ea05f0a37cc54/accuracy_proofs/sum_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7409415748818317}}
{"text": "Require Import Arith Lia ZArith.Znat ZArith.Zdiv.\n\nRequire Import ssreflect ssrbool ssrfun.\n\nSet Default Goal Selector \"!\".\n\nDefinition nat_norm := (Nat.add_0_r, Nat.add_succ_r, Nat.sub_0_r, Nat.mul_1_r, Nat.div_1_r).\n\nLemma div_exact (a b : nat) : a = b * (a / b) <-> a mod b = 0.\nProof.\n  rewrite [X in X = _](Nat.div_mod_eq a b). lia.\nQed.\n\nLemma add_mod (a b n : nat) : (a + b) mod n = (a mod n + b mod n) mod n.\nProof.\n  apply: Nat2Z.inj. do ? rewrite !(Nat2Z.inj_mod, Nat2Z.inj_add).\n  apply: Zplus_mod.\nQed.\n\nLemma mod_same (a : nat) : a mod a = 0.\nProof.\n  apply: Nat2Z.inj. rewrite Nat2Z.inj_mod.\n  apply: Z_mod_same_full.\nQed.\n\nLemma mod_mod (a n : nat) : (a mod n) mod n = a mod n.\nProof.\n  apply: Nat2Z.inj. rewrite !Nat2Z.inj_mod.\n  apply: Zmod_mod.\nQed.\n\nLemma div_mod_pos {n m: nat} : S m / (1 + n) + S m mod (1 + n) <> 0.\nProof.\n  move=> ?.\n  have /Nat.div_small_iff : S m / (1 + n) = 0 by lia. move /(_ ltac:(lia)).\n  have /div_exact : S m mod (1 + n) = 0 by lia.\n  by lia.\nQed.\n\nLemma divides_frac_diff {m n} : m mod (n + 1) = 0 -> (m * (n + 2) / (n + 1) - m) * (1 + n) = m.\nProof.\n  rewrite Nat.mul_sub_distr_r.\n  move=> /div_exact => ?.\n  have -> : m * (n + 2) = ((n+2) * (m / (n + 1))) * (n + 1) by lia.\n  by rewrite Nat.div_mul; lia.\nQed.\n\nLemma div_mul_le m n : (m / n) * n <= m.\nProof. have := Nat.div_mod_eq m n. by lia. Qed.\n\nLemma transition_le_gt (f: nat -> nat) (x n1 n2: nat): \n  n1 <= n2 -> f n1 <= x -> x < f n2 -> exists n, n < n2 /\\ f n <= x /\\ x < f (1+n).\nProof.\n  move=> H Hfn1 Hfn2. have : n1 < n2.\n  { suff : n1 <> n2 by lia. by move=> ?; subst; lia. }\n  clear H. elim: n2 Hfn2; first by lia.\n  move=> n2 IH ??.\n  have [?|?] : f n2 <= x \\/ x < f n2 by lia.\n  - exists n2 => /=. lia.\n  - have ? : n1 <> n2 by (move=> ?; subst; lia).\n    have [n ?] := IH ltac:(lia) ltac:(lia).\n    exists n. lia.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/StackMachines/Util/Nat_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.740941573371038}}
{"text": "Require Export TopologicalSpaces.\nRequire Export DirectedSets.\nRequire Export InteriorsClosures.\nRequire Export Continuity.\n\nLocal Unset Standard Proposition Elimination Names.\nSet Asymmetric Patterns.\n\nSection Net.\n\nVariable I:DirectedSet.\nVariable X:TopologicalSpace.\n\nDefinition Net := DS_set I -> point_set X.\n\nDefinition net_limit (x:Net) (x0:point_set X) : Prop :=\n  forall U:Ensemble (point_set X), open U -> In U x0 ->\n  for large i:DS_set I, In U (x i).\n\nDefinition net_cluster_point (x:Net) (x0:point_set X) : Prop :=\n  forall U:Ensemble (point_set X), open U -> In U x0 ->\n  exists arbitrarily large i:DS_set I, In U (x i).\n\nLemma net_limit_is_cluster_point: forall (x:Net) (x0:point_set X),\n  net_limit x x0 -> net_cluster_point x x0.\nProof.\nintros.\nred; intros.\nred; intros.\npose proof (H U H0 H1).\ndestruct H2.\ndestruct (DS_join_cond i x1).\ndestruct H3.\nexists x2; split; trivial.\napply H2; trivial.\nQed.\n\nLemma net_limit_in_closure: forall (S:Ensemble (point_set X))\n  (x:Net) (x0:point_set X),\n  (exists arbitrarily large i:DS_set I, In S (x i)) ->\n  net_limit x x0 -> In (closure S) x0.\nProof.\nintros.\napply NNPP.\nred; intro.\npose proof (H0 (Complement (closure S))).\nmatch type of H2 with | ?A -> ?B -> ?C => assert (C) end.\napply H2.\napply closure_closed.\nassumption.\ndestruct H3.\npose proof (H x1).\ndestruct H4.\ncontradiction (H3 x2).\ntauto.\napply closure_inflationary; tauto.\nQed.\n\nLemma net_cluster_point_in_closure: forall (S:Ensemble (point_set X))\n  (x:Net) (x0:point_set X),\n  (for large i:DS_set I, In S (x i)) ->\n  net_cluster_point x x0 -> In (closure S) x0.\nProof.\nintros.\napply NNPP.\nred; intro.\npose proof (H0 (Complement (closure S))).\nmatch type of H2 with | ?A -> ?B -> ?C => assert (C) end.\napply H2.\napply closure_closed.\nassumption.\ndestruct H.\ndestruct (H3 x1).\ndestruct H4.\ncontradiction H5.\napply closure_inflationary.\napply H; trivial.\nQed.\n\nEnd Net.\n\nArguments net_limit [I] [X].\nArguments net_cluster_point [I] [X].\nArguments net_limit_is_cluster_point [I] [X].\nArguments net_limit_in_closure [I] [X].\n(*Implicit Arguments net_cluster_point_in_closure [[I] [X]].*)\nArguments net_cluster_point_in_closure [I] [X].\n\nSection neighborhood_net.\n\nVariable X:TopologicalSpace.\nVariable x:point_set X.\n\nInductive neighborhood_net_DS_set : Type :=\n  | intro_neighborhood_net_DS :\n    forall (U:Ensemble (point_set X)) (y:point_set X),\n    open U -> In U x -> In U y -> neighborhood_net_DS_set.\n\nDefinition neighborhood_net_DS_ord\n  (Uy Vz:neighborhood_net_DS_set) : Prop :=\n  match Uy, Vz with\n  | intro_neighborhood_net_DS U _ _ _ _,\n    intro_neighborhood_net_DS V _ _ _ _ =>\n    Included V U\n  end.\n\nDefinition neighborhood_net_DS : DirectedSet.\nrefine (Build_DirectedSet neighborhood_net_DS_set\n  neighborhood_net_DS_ord _ _).\nconstructor.\nred; intros.\ndestruct x0.\nsimpl; auto with sets.\nred; intros.\ndestruct x0; destruct y; destruct z.\nsimpl in H; simpl in H0; simpl.\nauto with sets.\n\nintros.\ndestruct i; destruct j.\nassert (open (Intersection U U0)).\napply open_intersection2; trivial.\nassert (In (Intersection U U0) x); auto with sets.\n\nexists (intro_neighborhood_net_DS (Intersection U U0) x\n  H H0 H0).\nsimpl; auto with sets.\nDefined.\n\nDefinition neighborhood_net : Net neighborhood_net_DS X :=\n  fun (x:neighborhood_net_DS_set) => match x with\n  | intro_neighborhood_net_DS _ y _ _ _ => y\n  end.\n\nLemma neighborhood_net_limit: net_limit neighborhood_net x.\nProof.\nred; intros.\nexists (intro_neighborhood_net_DS U x H H0 H0).\nintros.\ndestruct j.\nsimpl in H1.\nsimpl.\nauto with sets.\nQed.\n\nEnd neighborhood_net.\n\nLemma net_limits_determine_topology:\n  forall {X:TopologicalSpace} (S:Ensemble (point_set X))\n  (x0:point_set X), In (closure S) x0 ->\n  exists I:DirectedSet, exists x:Net I X,\n  (forall i:DS_set I, In S (x i)) /\\ net_limit x x0.\nProof.\nintros.\nassert (forall U:Ensemble (point_set X), open U -> In U x0 ->\n  Inhabited (Intersection S U)).\nintros.\napply NNPP; red; intro.\nassert (Included (closure S) (Complement U)).\napply closure_minimal.\nred; rewrite Complement_Complement; assumption.\nred; intros.\nred; red; red; intros.\ncontradiction H2.\nexists x; auto with sets.\ncontradict H1.\napply H3.\nassumption.\npose (Ssel := fun n:neighborhood_net_DS_set X x0 =>\n  match n with\n  | intro_neighborhood_net_DS V y _ _ _ => (In S y)\n  end).\npose (our_DS_set := {n:neighborhood_net_DS_set X x0 | Ssel n}).\npose (our_DS_ord := fun (n1 n2:our_DS_set) =>\n  neighborhood_net_DS_ord X x0 (proj1_sig n1) (proj1_sig n2)).\nassert (preorder our_DS_ord).\nconstructor; red.\nintros; red.\napply preord_refl.\napply (@DS_ord_cond (neighborhood_net_DS X x0)).\nintros x y z.\nunfold our_DS_ord; apply preord_trans.\napply (@DS_ord_cond (neighborhood_net_DS X x0)).\nassert (forall i j:our_DS_set, exists k:our_DS_set,\n  our_DS_ord i k /\\ our_DS_ord j k).\ndestruct i.\ndestruct x.\ndestruct j.\ndestruct x.\nassert (open (Intersection U U0)).\napply open_intersection2; trivial.\nassert (In (Intersection U U0) x0).\nauto with sets.\nassert (Inhabited (Intersection S (Intersection U U0))).\napply H0; trivial.\ndestruct H4.\ndestruct H4.\npose (k0 := intro_neighborhood_net_DS X x0\n  (Intersection U U0) x H2 H3 H5).\nassert (Ssel k0).\nred; unfold k0; simpl.\nassumption.\nexists (exist _ k0 H6).\nsplit; red; simpl; auto with sets.\n\npose (our_DS := Build_DirectedSet our_DS_set our_DS_ord H1 H2).\nexists our_DS.\nexists (fun i:our_DS_set => neighborhood_net X x0 (proj1_sig i)).\nsplit.\nintros.\ndestruct i.\ndestruct x.\nsimpl.\nsimpl in s.\nassumption.\n\nred; intros.\nassert (Inhabited (Intersection S U)).\napply H0; trivial.\ndestruct H5.\ndestruct H5.\npose (i0 := intro_neighborhood_net_DS X x0\n  U x H3 H4 H6).\nassert (Ssel i0).\nsimpl; assumption.\nexists (exist _ i0 H7).\nintros.\ndestruct j.\ndestruct x1.\nsimpl in H8.\nred in H8; simpl in H8.\nsimpl.\nauto with sets.\nQed.\n\nSection Nets_and_continuity.\n\nVariable X Y:TopologicalSpace.\nVariable f:point_set X -> point_set Y.\n\nLemma continuous_func_preserves_net_limits:\n  forall {I:DirectedSet} (x:Net I X) (x0:point_set X),\n    net_limit x x0 -> continuous_at f x0 ->\n    net_limit (fun i:DS_set I => f (x i)) (f x0).\nProof.\nintros.\nred; intros V ? ?.\nassert (neighborhood V (f x0)).\napply open_neighborhood_is_neighborhood; split; trivial.\npose proof (H0 V H3).\ndestruct H4 as [U [? ?]].\ndestruct H4.\npose proof (H U H4 H6).\napply eventually_impl_base with (fun i:DS_set I => In U (x i));\n  trivial.\nintros.\nassert (In (inverse_image f V) (x i)); auto with sets.\ndestruct H9; trivial.\nQed.\n\nLemma func_preserving_net_limits_is_continuous:\n  forall x0:point_set X,\n  (forall (I:DirectedSet) (x:Net I X),\n    net_limit x x0 -> net_limit (fun i:DS_set I => f (x i)) (f x0))\n  -> continuous_at f x0.\nProof.\nintros.\npose proof (H (neighborhood_net_DS X x0)\n  (neighborhood_net X x0)\n  (neighborhood_net_limit X x0)).\napply continuous_at_open_neighborhoods; intros.\ndestruct H1.\npose proof (H0 V H1 H2).\ndestruct H3.\ndestruct x as [U].\nexists U; repeat split; trivial.\npose proof (H3 (intro_neighborhood_net_DS X x0 U x o i H4)).\napply H5.\nsimpl; auto with sets.\nQed.\n\nEnd Nets_and_continuity.\n\nSection Subnet.\n\nVariable X:TopologicalSpace.\nVariable I:DirectedSet.\nVariable x:Net I X.\n\nInductive Subnet {J:DirectedSet} : Net J X -> Prop :=\n  | intro_subnet: forall h:DS_set J -> DS_set I,\n    (forall j1 j2:DS_set J, DS_ord j1 j2 ->\n       DS_ord (h j1) (h j2)) ->\n    (exists arbitrarily large i:DS_set I,\n       exists j:DS_set J, h j = i) ->\n    Subnet (fun j:DS_set J => x (h j)).\n\nLemma subnet_limit: forall (x0:point_set X) {J:DirectedSet}\n  (y:Net J X), net_limit x x0 -> Subnet y ->\n  net_limit y x0.\nProof.\nintros.\ndestruct H0.\nred; intros.\npose proof (H U H2 H3).\ndestruct H4.\ndestruct (H1 x1).\ndestruct H5.\ndestruct H6.\nexists x3.\nintros.\napply H4.\napply preord_trans with x2.\napply DS_ord_cond.\nassumption.\nrewrite <- H6.\napply H0.\nassumption.\nQed.\n\nLemma subnet_cluster_point: forall (x0:point_set X) {J:DirectedSet}\n  (y:Net J X), net_cluster_point y x0 ->\n  Subnet y -> net_cluster_point x x0.\nProof.\nintros.\ndestruct H0 as [h h_increasing h_dominant].\nred; intros.\nred; intros.\npose proof (h_dominant i).\ndestruct H2.\ndestruct H2.\ndestruct H3.\npose proof (H U H0 H1 x2).\ndestruct H4.\ndestruct H4.\nexists (h x3).\nsplit; trivial.\napply preord_trans with x1.\napply DS_ord_cond.\nassumption.\nrewrite <- H3.\napply h_increasing; assumption.\nQed.\n\nSection cluster_point_subnet.\n\nVariable x0:point_set X.\nHypothesis x0_cluster_point: net_cluster_point x x0.\nHypothesis I_nonempty: inhabited (DS_set I).\n\nRecord cluster_point_subnet_DS_set : Type := {\n  cps_i:DS_set I;\n  cps_U:Ensemble (point_set X);\n  cps_U_open_neigh: open_neighborhood cps_U x0;\n  cps_xi_in_U: In cps_U (x cps_i)\n}.\n\nDefinition cluster_point_subnet_DS_ord\n  (iU1 iU2 : cluster_point_subnet_DS_set) : Prop :=\n  DS_ord (cps_i iU1) (cps_i iU2) /\\\n  Included (cps_U iU2) (cps_U iU1).\n\nDefinition cluster_point_subnet_DS : DirectedSet.\nrefine (Build_DirectedSet\n  cluster_point_subnet_DS_set\n  cluster_point_subnet_DS_ord\n  _ _).\nconstructor.\nred; intros; split; auto with sets.\napply preord_refl.\napply DS_ord_cond.\nred; intros.\ndestruct H; destruct H0.\nred; split; auto with sets.\napply preord_trans with (cps_i y); trivial.\napply DS_ord_cond.\n\nintros.\ndestruct i as [i0 U0 ? ?]; destruct j as [i1 U1 ? ?].\ndestruct (DS_join_cond i0 i1).\ndestruct H.\npose proof (x0_cluster_point\n  (Intersection U0 U1)).\nmatch type of H1 with | _ -> _ -> ?C =>\n  assert C end.\napply H1.\napply open_intersection2;\n  (apply cps_U_open_neigh0 ||\n   apply cps_U_open_neigh1).\nconstructor;\n  (apply cps_U_open_neigh0 ||\n   apply cps_U_open_neigh1).\ndestruct (H2 x1).\ndestruct H3.\npose (ki := x2).\npose (kU := Intersection U0 U1).\nassert (open_neighborhood kU x0).\nsplit.\napply open_intersection2.\napply cps_U_open_neigh0.\napply cps_U_open_neigh1.\nconstructor; (apply cps_U_open_neigh0 ||\n              apply cps_U_open_neigh1).\nassert (In kU (x ki)).\nexact H4.\n\nexists (Build_cluster_point_subnet_DS_set\n  ki kU H5 H6).\nsplit; red; simpl; split.\napply preord_trans with x1; trivial.\napply DS_ord_cond.\nred; intros.\ndestruct H7; trivial.\napply preord_trans with x1; trivial.\napply DS_ord_cond.\nred; intros.\ndestruct H7; trivial.\nDefined.\n\nDefinition cluster_point_subnet : Net\n  cluster_point_subnet_DS X :=\n  fun (iU:DS_set cluster_point_subnet_DS) =>\n  x (cps_i iU).\n\nLemma cluster_point_subnet_is_subnet:\n  Subnet cluster_point_subnet.\nProof.\nconstructor.\nintros.\ndestruct j1; destruct j2.\nsimpl in H; simpl.\nred in H; tauto.\n\nred; intros.\nexists i; split.\napply preord_refl; apply DS_ord_cond.\nassert (open_neighborhood Full_set x0).\nsplit.\napply open_full.\nconstructor.\nassert (In Full_set (x i)).\nconstructor.\nexists (Build_cluster_point_subnet_DS_set\n  i Full_set H H0).\ntrivial.\nQed.\n\nLemma cluster_point_subnet_converges:\n  net_limit cluster_point_subnet x0.\nProof.\nred; intros.\ndestruct I_nonempty as [i0].\ndestruct (x0_cluster_point U H H0 i0).\ndestruct H1.\nassert (open_neighborhood U x0).\nsplit; trivial.\nexists (Build_cluster_point_subnet_DS_set\n  x1 U H3 H2).\nintros.\ndestruct j.\nred in H4; simpl in H4.\nred in H4; simpl in H4.\nunfold cluster_point_subnet; simpl.\ndestruct H4; auto with sets.\nQed.\n\nLemma net_cluster_point_impl_subnet_converges:\n  exists J:DirectedSet, exists y:Net J X,\n  Subnet y /\\ net_limit y x0.\nProof.\nexists cluster_point_subnet_DS.\nexists cluster_point_subnet.\nsplit.\nexact cluster_point_subnet_is_subnet.\nexact cluster_point_subnet_converges.\nQed.\n\nEnd cluster_point_subnet.\n\nEnd Subnet.\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/Nets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.740893541429208}}
{"text": "Require Import ZArith.\n\nOpen Scope Z_scope.\n\nInductive dtree (A : Type) : nat -> Type :=\n  | dleaf : A -> dtree A O\n  | dbranch : forall n, dtree A n -> dtree A n -> dtree A (S n).\n\nArguments dleaf {A} x.\nArguments dbranch {A} {n} l r.\n\nCheck dbranch (dbranch (dleaf 42) (dleaf 13)) (dbranch (dleaf 7) (dleaf 20)).\n\nInductive stree (A : Type) : nat -> Type :=\n  | sleaf : A -> stree A O\n  | sbranch : forall n m, stree A n -> stree A m -> stree A (S (max n m)).\n\nArguments sleaf {A} x.\nArguments sbranch {A} {n m} l r.\n\nCheck sbranch (sbranch (sleaf 42) (sleaf 13)) (sleaf 7).\n\n(** This is a balanced binary tree with elements only in the leaves. *)\nInductive tree (A : Type) : nat -> Type :=\n  | leaf : A -> tree A O\n  | branch : forall n, tree A n -> tree A n -> tree A (S n).\n\nArguments leaf {A} x.\nArguments branch {A} {n} l r.\n\nCheck leaf 42.\nCheck branch (leaf 42) (leaf 13).\nCheck branch (branch (leaf 42) (leaf 13)) (branch (leaf 7) (leaf 20)).\nFail Check branch (leaf 42) (branch (leaf 7) (leaf 20)).\n\nDefinition lx {A : Type} (t : tree A O) : A :=\n  match t with\n  | leaf x => x\n  end.\n\nDefinition bl {A : Type} {n : nat} (t : tree A (S n)) : tree A n :=\n  match t with\n  | branch l _ => l\n  end.\n\nDefinition br {A : Type} {n : nat} (t : tree A (S n)) : tree A n :=\n  match t with\n  | branch _ r => r\n  end.\n\nFixpoint map {A B : Type} (f : A -> B)\n  {n : nat} (t : tree A n) : tree B n :=\n  match t with\n  | leaf x => leaf (f x)\n  | branch l r => branch (map f l) (map f r)\n  end.\n\n(** This is called the _convoy pattern_. *)\nFixpoint zip' {A1 A2 B : Type} (f : A1 -> A2 -> B)\n  {n : nat} (t1 : tree A1 n) (t2 : tree A2 n) : tree B n :=\n  match t1 in tree _ n return tree A2 n -> tree B n with\n  | leaf x1 => fun t2 => leaf (f x1 (lx t2))\n  | branch l1 r1 => fun t2 => branch (zip' f l1 (bl t2)) (zip' f r1 (br t2))\n  end t2.\n\n(** This is a second-order convoy. *)\nFixpoint zip {A1 A2 B : Type} (f : A1 -> A2 -> B)\n  {n : nat} (t1 : tree A1 n) (t2 : tree A2 n) : tree B n :=\n  match n return tree A1 n -> tree A2 n -> tree B n with\n  | O => fun t1 t2 => leaf (f (lx t1) (lx t2))\n  | S _ => fun t1 t2 => branch (zip f (bl t1) (bl t2)) (zip f (br t1) (br t2))\n  end t1 t2.\n\nCompute zip Zplus (leaf 42) (leaf 13).\nCompute zip Zplus (branch (leaf 42) (leaf 13)) (branch (leaf 7) (leaf 20)).\nFail Compute zip Zplus (leaf 42) (branch (leaf 7) (leaf 20)).\n\nNotation \"x + y\" := (zip Zplus x y).\nNotation \"x * y\" := (map (Zmult x) y).\n\n(* ~ x = x\n   ~ (l, r) = (~ l, - (~ r)) *)\nFixpoint aux {A : Type} (fneg : A -> A)\n  {n : nat} (t : tree A n) : tree A n :=\n  match t with\n  | leaf x => leaf x\n  | branch l r => branch (aux fneg l) (map fneg (aux fneg r))\n  end.\n\nNotation \"~ x\" := (aux Zopp x).\n\nCompute aux Zopp (branch (branch (leaf 42) (leaf 13)) (branch (leaf 7) (leaf 20))).\n\n(* x1 /\\ x2 = x1 * x2\n   (l1, r1) /\\ (l2, r2) = (l1 /\\ l2, r1 /\\ l2 + l1 /\\ r2) *)\n(** We must run the convoy in reverse here. *)\nFixpoint outer {A : Type} (fadd fmul : A -> A -> A) (fneg : A -> A)\n  {n : nat} (t1 : tree A n) (t2 : tree A n) : tree A n :=\n  match t2 in tree _ n return tree A n -> tree A n with\n  | leaf x2 => fun t1 => leaf (fmul (lx t1) x2)\n  | branch l2 r2 => fun t1 => branch\n    (outer fadd fmul fneg (bl t1) l2) (zip fadd\n    (outer fadd fmul fneg (br t1) l2)\n    (outer fadd fmul fneg (aux fneg (bl t1)) r2))\n  end t1.\n\nNotation \"x /\\ y\" := (outer Zplus Zmult Zopp x y).\n\n(* x1 ** x2 = x1 * x2\n   (l1, r1) ** (l2, r2) = (l1 ** l2) + (r1 ** (~ r2)) *)\nFixpoint inner {A : Type} (fadd fmul : A -> A -> A) (fneg : A -> A)\n  {n : nat} (t1 : tree A n) (t2 : tree A n) : A :=\n  match t1 in tree _ n return tree A n -> A with\n  | leaf x1 => fun t2 => fmul x1 (lx t2)\n  | branch l1 r1 => fun t2 => fadd\n    (inner fadd fmul fneg l1 (bl t2))\n    (* metric signature here *) (inner fadd fmul fneg r1 (aux fneg (br t2)))\n  end t2.\n\nNotation \"x '.*' y\" := (inner Zplus Zmult Zopp x y) (at level 42).\n\nCompute inner Zplus Zmult Zopp\n  (branch (branch (leaf 42) (leaf 13)) (branch (leaf 7) (leaf 69)))\n  (branch (branch (leaf 42) (leaf 13)) (branch (leaf 7) (leaf (Zopp 69)))).\n\n(* Fixpoint flapr {A : Type} (f : forall n, tree A n -> tree A n)\n  {n : nat} (t : tree A n) : tree A n :=\n  match t with\n  | leaf x => leaf x\n  | branch l r => branch (flapr f l) (flapr f (f _ r))\n  end. *)\nFixpoint flapr {A : Type} (f : forall n, tree A n -> tree A n)\n  {n : nat} (t : tree A n) : tree A n :=\n  match n in nat return tree A n -> tree A n with\n  | O => fun t => leaf (lx t)\n  | S n => fun t => branch (flapr f (bl t)) (flapr f (f _ (br t)))\n  end t.\n\n(* >< x = x\n   >< (l, r) = (>< l, >< (~ r)) *)\nFixpoint rev {A : Type} (fneg : A -> A)\n  {n : nat} (t : tree A n) : tree A n :=\n  match n in nat return tree A n -> tree A n with\n  | O => fun t => leaf (lx t)\n  | S n => fun t => branch (rev fneg (bl t)) (rev fneg (aux fneg (br t)))\n  end t.\n\nNotation \">< x\" := (flapr (aux Zopp) x) (at level 13).\n\nCompute let x := branch (branch (leaf 42) (leaf 13)) (branch (leaf 7) (leaf 69)) in\n  inner Zplus Zmult Zopp x (rev Zopp x).\n\nFixpoint const {A : Type} (z : A)\n  {n : nat} : tree A n :=\n  match n with\n  | O => leaf z\n  | S _ => let b := const z in branch b b\n  end.\n\nCompute @const _ 0 2.\n\nDefinition inject1 {A : Type} (z : A)\n  {n : nat} (t : tree A n) : tree A (S n) :=\n  branch t (const z).\n\nFixpoint inject {A : Type} (z : A)\n  {n m : nat} (t : tree A n) : tree A (m + n) :=\n  match m in nat return tree A n -> tree A (m + n) with\n  | O => fun t => t\n  | S _ => fun t => branch (inject z t) (inject z (const z))\n  end t.\n\nCompute @inject _ 0 _ 2 (branch (leaf 42) (leaf 13)).\n\n(* This is just [bl]. *)\nDefinition project1 {A : Type}\n  {n : nat} (t : tree A (S n)) : tree A n :=\n  match t with\n  | branch l r => l\n  end.\n\nFixpoint project {A : Type}\n  {n m : nat} (t : tree A (m + n)) : tree A n :=\n  match m in nat return tree A (m + n) -> tree A n with\n  | O => fun t => t\n  | S k => fun t => project (bl t)\n  end t.\n\nCompute @project _ _ 1 (branch (branch (leaf 42) (leaf 13)) (branch (leaf 7) (leaf 69))).\n\n(* Now define the free algebra and compute specializations. *)\n\nInductive free (A : Type) (z : A) : Type :=\n  | f_lift : A -> free A z\n  | f_add : free A z -> free A z -> free A z\n  | f_neg : free A z -> free A z\n  | f_mul : free A z -> free A z -> free A z.\n\nArguments f_lift {A} {z} x.\nArguments f_add {A} {z} x y.\nArguments f_neg {A} {z} x.\nArguments f_mul {A} {z} x y.\n\nCheck (@f_lift Z 0 42).\n\nNotation \"x + y\" := (f_add x y).\nNotation \"- x\" := (f_neg x).\nNotation \"x * y\" := (f_mul x y).\n\nRequire Import String.\n\nOpen Scope string_scope.\n\nCheck (@f_lift string \"0\" \"x\").\nCompute (f_mul (f_lift \"x\") (f_add (f_lift \"y\") (f_lift \"0\")) : free string \"0\").\n\n(* Structural equality. *)\nFixpoint f_eq {A : Type} (eq : A -> A -> bool)\n  {z : A} (a1 a2 : free A z) : bool :=\n  match a1, a2 with\n  | f_lift x1, f_lift x2 => eq x1 x2\n  | f_add x1 y1, f_add x2 y2 => f_eq eq x1 x2 && f_eq eq y1 y2\n  | f_neg x1, f_neg x2 => f_eq eq x1 x2\n  | f_mul x1 y1, f_mul x2 y2 => f_eq eq x1 x2 && f_eq eq y1 y2\n  | _, _ => false\n  end.\n\n(* This is weak. *)\nFixpoint simpl {A : Type} {z : A}\n  (eq : A -> A -> bool) (a : free A z) : free A z :=\n  match a with\n  | f_lift x => f_lift x\n  | f_add x y => if f_eq eq (f_lift z) x then simpl eq y else\n    if f_eq eq (f_lift z) y then simpl eq x else\n    f_add (simpl eq x) (simpl eq y)\n  | f_neg x => f_neg (simpl eq x)\n  | f_mul x y => if f_eq eq (f_lift z) x then f_lift z else\n    if f_eq eq (f_lift z) y then f_lift z else\n    f_add (simpl eq x) (simpl eq y)\n  end.\n\nDefinition string_eq (s1 s2 : string) : bool :=\n  if string_dec s1 s2 then true else false.\n\nCompute simpl string_eq\n  (f_mul (f_lift \"x\") (f_add (f_lift \"y\") (f_lift \"0\")) : free string \"0\").\n\nCompute outer f_add f_mul f_neg\n  (branch (leaf (f_lift \"a\")) (leaf (f_lift \"x\")))\n  (branch (leaf (f_lift \"b\")) (leaf (f_lift \"y\"))) : tree (free string \"0\") 1.\n", "meta": {"author": "Tuplanolla", "repo": "dez", "sha": "c2eadc2e032094c3504ec3803c000dba4feb547e", "save_path": "github-repos/coq/Tuplanolla-dez", "path": "github-repos/coq/Tuplanolla-dez/dez-c2eadc2e032094c3504ec3803c000dba4feb547e/garbage/GA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7408653911643952}}
{"text": "(* Copyright (c) 2008-2012, 2015, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n *   http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import List.\n\nRequire Import Cpdt.CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n(* end hide *)\n\nCheck (fun x: nat => x).\n\nCheck (fun x: True => x).\n\nCheck I.\n\nCheck (fun _: False => I).\n\nCheck (fun x: False => x).\n\nInductive unit: Set :=\n| tt.\n\nCheck unit.\n\nCheck tt.\n\nTheorem unit_singleton: forall x: unit, x = tt.\nProof.\n  destruct x. reflexivity.\nQed.\n\nCheck unit_ind.\n\nInductive Empty_set : Set := .\n\nTheorem the_sky_is_faling: forall x: Empty_set, 2 + 2 = 5.\nProof.\n  destruct 1.\nQed.\n\nCheck Empty_set_ind.\n\nDefinition e2u (e: Empty_set) : unit := match e with end.\n\nCheck e2u.\n\nInductive bool: Set :=\n| true\n| false.\n\nCheck bool_ind.\n\nDefinition negb (b: bool) : bool :=\n  match b with\n  | true => false\n  | fales => true\n  end.\n\nDefinition negb' (b : bool) : bool :=\n  if b then false else true.\n\nTheorem negb_inverse : forall b : bool, negb (negb b) = b.\nProof.\n  destruct b; reflexivity.\nQed.\n\nTheorem negb_ineq' : forall b : bool, negb b = b -> False.\nProof.\n  destruct b; discriminate.\nQed.\n\nTheorem negb_ineq : forall b : bool, negb b <> b.\nProof.\n  destruct b; discriminate.\nQed.\n\nCheck bool_ind.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nDefinition isZero (n : nat) : bool :=\n  match n with\n  | O => true\n  | S _ => false\n  end.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\n\n\nFixpoint plus (n m : nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nTheorem O_plus_n : forall n : nat, plus O n = n.\nProof.\n  intros. reflexivity.\nQed.\n\nTheorem n_plus_O : forall n : nat, plus n O = n.\n  induction n.\n  reflexivity.\n  simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem n_plus_O' : forall n : nat, plus n O = n.\n  induction n; crush.\nQed.\n\nCheck nat_ind.\n\nTheorem S_inj : forall n m : nat, S n = S m -> n = m.\nProof.\n  injection 1; trivial.\nQed.\n\nInductive nat_list : Set :=\n| NNil : nat_list\n| NCons : nat -> nat_list -> nat_list.\n\nCheck nat_list_ind.\n\nFixpoint nlength (ls : nat_list) : nat :=\n  match ls with\n  | NNil => O\n  | NCons _ ls' => S (nlength ls')\n  end.\n\nFixpoint napp (ls1 ls2 : nat_list) : nat_list :=\n  match ls1 with\n  | NNil => ls2\n  | NCons n ls' => NCons n (napp ls' ls2)\n  end.\n\nTheorem nlength_napp : forall ls1 ls2 : nat_list, nlength (napp ls1 ls2) = plus (nlength ls1) (nlength ls2).\nProof.\n  induction ls1; crush.\nQed.\n\n\nInductive nat_btree : Set :=\n| NLeaf : nat_btree\n| NNode : nat_btree -> nat -> nat_btree -> nat_btree.\n\nCheck nat_btree_ind.\n\nFixpoint nsize (tr : nat_btree) : nat :=\n  match tr with\n  | NLeaf => S O\n  | NNode tr1' _ tr2' => plus (nsize tr1') (nsize tr2')\n  end.\n\nFixpoint nsplice (tr1 tr2 : nat_btree) : nat_btree :=\n  match tr1 with\n  | NLeaf => NNode tr2 O NLeaf\n  | NNode tr1' n tr2' => NNode (nsplice tr1' tr2) n tr2'\n  end.\n\nTheorem plus_assoc : forall n1 n2 n3 : nat, plus (plus n1 n2) n3 = plus n1 (plus n2 n3).\nProof.\n  induction n1; crush.\nQed.\n\nHint Rewrite n_plus_O plus_assoc.\n\nTheorem nsize_nsplice : forall tr1 tr2 : nat_btree, nsize (nsplice tr1 tr2) = plus (nsize tr2) (nsize tr1).\n  induction tr1; crush.\nQed.\n\nCheck nat_btree_ind.\n\nInductive list (T : Set) : Set :=\n| Nil : list T\n| Cons : T -> list T -> list T.\n\nFixpoint length T (ls : list T) : nat :=\n  match ls with\n  | Nil => O\n  | Cons _ ls' => S (length ls')\n  end.\n\nFixpoint app T (ls1 ls2 : list T) : list T :=\n  match ls1 with\n  | Nil => ls2\n  | Cons n ls' => Cons n (app ls' ls2)\n  end.\n\n\nTheorem length_app : forall (T : Set) (ls1 ls2 : list T), plus (length ls1) (length ls2) = length (app ls1 ls2).\nProof.\n  induction ls1; crush.\nQed.\n\nArguments Nil [T].\n\nPrint list.\n\nCheck length.\n\nCheck list_ind.\n\nInductive even_list : Set :=\n| ENil : even_list\n| ECons : nat -> odd_list -> even_list\n\nwith odd_list : Set :=\n| OCons : nat -> even_list -> odd_list.\n\nCheck even_list_ind.\n\nCheck odd_list_ind.\n\nFixpoint elength (el : even_list) : nat :=\n  match el with\n  | ENil => O\n  | ECons _ ol => S (olength ol)\n  end\n    \n\nwith olength (ol : odd_list) : nat :=\n       match ol with\n       | OCons _ el => S (elength el)\n       end.\n\nFixpoint eapp (el1 el2 : even_list) : even_list :=\n  match el1 with\n  | ENil => el2\n  | ECons n ol => ECons n (oapp ol el2)\n  end\n\nwith oapp (ol : odd_list) (el : even_list) : odd_list :=\n       match ol with\n       | OCons n el' => OCons n (eapp el' el)\n       end.\n\nTheorem elength_eapp : forall (el1 el2 : even_list), plus (elength el1) (elength el2) = elength (eapp el1 el2).\n  induction el1; crush.\nAbort.\n\nScheme even_list_mut := Induction for even_list Sort Prop\n  with odd_list_mut := Induction for odd_list Sort Prop.\n\nTheorem elength_eapp : forall (el1 el2 : even_list), plus (elength el1) (elength el2) = elength (eapp el1 el2).\nProof.\n  apply (even_list_mut\n           (fun el1 => forall (el2 : even_list), plus (elength el1) (elength el2) = elength (eapp el1 el2))\n           (fun ol => forall (el : even_list), plus (olength ol) (elength el) = olength (oapp ol el))); crush.\nQed.\n\nInductive pformula : Set :=\n| Truth : pformula\n| Falsehood : pformula\n| Conjuction : pformula -> pformula -> pformula.\n\nFixpoint pformulaDenote (f : pformula) : Prop :=\n  match f with\n  | Truth => True\n  | Falsehood => False\n  | Conjuction f1 f2 => pformulaDenote f1 /\\ pformulaDenote f2\n  end.\n\nInductive formula : Set :=\n| Eq : nat -> nat -> formula\n| And : formula -> formula -> formula\n| Forall :  (nat -> formula) -> formula.\n\nFixpoint formulaDenote (f : formula) : Prop :=\n  match f with\n  | Eq x y => x = y\n  | And f1 f2 => (formulaDenote f1) /\\ (formulaDenote f2)\n  | Forall f' => forall n : nat, formulaDenote (f' n)\n  end.\n\nFixpoint swapper (f : formula) : formula :=\n  match f with\n  | Eq x y => Eq y x\n  | And f1 f2 => And f2 f1\n  | Forall f' => Forall (fun n => swapper (f' n))\n  end.\n\n\nTheorem swapper_preserves_truth : forall f, formulaDenote f -> formulaDenote (swapper f).\n  induction f; crush.\nQed.\n\nCheck formula_ind.\n\nPrint nat_ind.\n                                 \nPrint nat_rect.\n\nDefinition nat_ind' : forall P : nat -> Prop, P O -> (forall n : nat,  P n -> P (S n)) -> forall n : nat,  P n := fun P : nat -> Prop => nat_rect P.\n\nPrint nat_rec.\n\nDefinition nat_rec' : forall P : nat -> Set, P O -> (forall n : nat,  P n -> P (S n)) -> forall n : nat, P n := fun P => nat_rect P.\n\nFixpoint plus_recursive (n : nat) : nat -> nat :=\n  match n with\n  | O => fun m => m\n  | S n' => fun m => S (plus_recursive n' m)\n  end.\n\nDefinition plus_rec : nat -> nat -> nat :=\n  nat_rec (fun _ : nat => nat -> nat) (fun m => m) (fun n f =>  (fun m =>  S (f m))).\n\nDefinition plus_rec' : nat -> nat -> nat :=\n  nat_rec (fun _ : nat => nat -> nat) (fun m => m) (fun _ r m => S (r m)).\n\nTheorem plus_equivalent : plus_recursive = plus_rec.\nProof.\n  unfold plus_recursive.\n  unfold plus_rec.\n  unfold nat_rec.\n  unfold nat_rect.\n  reflexivity.\nQed.\n\nPrint nat_rect.\n\nFixpoint nat_rect' (P: nat -> Type)\n         (HO : P O)\n         (HS : forall n, P n -> P (S n)) (n : nat) :=\n  match n return P n with\n  | O => HO\n  | S n' => HS n' (nat_rect' P HO HS n')\n  end.\n\nFixpoint even_list_ind' (PE : even_list -> Prop)\n         (PO : odd_list -> Prop)\n         (H0 : PE ENil)\n         (H1 : forall (n : nat) (lo : odd_list), PO lo -> PE (ECons n lo))\n         (H2 : forall (n: nat) (le : even_list), PE le -> PO (OCons n le))\n         (le : even_list) :=\n  match le return PE le with\n  | ENil => H0\n  | ECons n lo => H1 n lo (odd_list_ind' PE PO H0 H1 H2 lo)\n  end\n\nwith odd_list_ind' (PE : even_list -> Prop)\n         (PO : odd_list -> Prop)\n         (H0 : PE ENil)\n         (H1 : forall (n : nat) (lo : odd_list), PO lo -> PE (ECons n lo))\n         (H2 : forall (n: nat) (le : even_list), PE le -> PO (OCons n le))\n         (lo : odd_list) :=\n       match lo return PO lo with\n       | OCons n le => H2 n le (even_list_ind' PE PO H0 H1 H2 le)\n       end.\n\nSection even_list_mut_from_the_book'.\n  Variable Peven : even_list -> Prop.\n  Variable Podd : odd_list -> Prop.\n\n  Hypothesis ENil_case : Peven ENil.\n  Hypothesis ECons_case : forall (n : nat) (o : odd_list), Podd o -> Peven (ECons n o).\n  Hypothesis OCons_case : forall (n : nat) (e : even_list), Peven e -> Podd (OCons n e).\n\n  Fixpoint even_list_mut' (e : even_list) : Peven e :=\n    match e with\n    | ENil => ENil_case\n    | ECons n o => ECons_case n (odd_list_mut' o)\n    end\n  with odd_list_mut' (o : odd_list) : Podd o :=\n         match o with\n         | OCons n e => OCons_case n (even_list_mut' e)\n         end.\nEnd even_list_mut_from_the_book'.\n\nFixpoint formula_ind' (P : formula -> Prop)\n         (H0 : forall (n0 n1 : nat), P (Eq n0 n1))\n         (H1 : forall (f0 f1 : formula), P f0 -> P f1 -> P (And f0 f1))\n         (H2 : forall (f : nat -> formula), (forall n : nat, P (f n)) -> P (Forall f))\n                                                                         (f : formula) :=\n            match f return P f with\n            | Eq n0 n1 => H0 n0 n1\n            | And f0 f1 => H1 f0 f1 (formula_ind' P H0 H1 H2 f0) (formula_ind' P H0 H1 H2 f1)\n            | Forall func => H2 func (fun n => formula_ind' P H0 H1 H2 (func n))\n            end.\n\nInductive nat_tree : Set :=\n| NNode' : nat -> list nat_tree -> nat_tree.\n\nCheck nat_tree_ind.\n\nSection All.\n  Variable T : Set.\n  Variable P : T -> Prop.\n  Fixpoint All (ls : list T) : Prop :=\n    match ls with\n    | Nil => True\n    | Cons h t => (P h) /\\ All t\n    end.\nEnd All.\n\nLocate \"/\\\".\n\nPrint and.\n\nPrint All.\n\nSection nat_tree_ind'.\n  Variable P : nat_tree -> Prop.\n  Hypothesis NNode'_case : forall (n : nat) (ls : list nat_tree), All P ls -> P (NNode' n ls).\nFixpoint nat_tree_ind' (tr : nat_tree) : P tr :=\n  match tr with\n  | NNode' n ls => NNode'_case n ls\n                               ((fix list_nat_tree_ind (ls : list nat_tree) : All P ls :=\n                                   match ls with\n                                   | Nil => I\n                                   | Cons tr' rest => conj (nat_tree_ind' tr') (list_nat_tree_ind rest)\n                                   end\n                                ) ls)\n  end.  \nEnd nat_tree_ind'.    \n\nCheck nat_tree_ind'.                                                                         \nSection map.\n  Variables T T' : Set.\n  Variable F : T -> T'.\n\n  Fixpoint map (ls : list T) : list T' :=\n    match ls with\n    | Nil => Nil\n    | Cons h t => Cons (F h) (map t)\n    end.\nEnd map.\n\nFixpoint sum (ls : list nat) : nat :=\n  match ls with\n  | Nil => O\n  | Cons n t => plus n (sum t)\n  end.\n\nFixpoint ntsize (tr : nat_tree) : nat :=\n  match tr with\n  | NNode' _ trs => S (sum (map ntsize trs))\n  end.\n\nFixpoint ntsize' (tr : nat_tree) : nat :=\n  match tr with\n  | NNode' _ Nil => S O\n  | NNode' _ (Cons tr rest) => S (sum (Cons (ntsize' tr) (map ntsize' rest)))\n  end.\n\n\nFixpoint ntsplice (tr1 tr2 : nat_tree) : nat_tree :=\n  match tr1 with\n  | NNode' n Nil => NNode' n (Cons tr2 Nil)\n  | NNode' n (Cons tr rest) => NNode' n (Cons (ntsplice tr tr2) rest)\n  end.\n\nLemma plus_S : forall n1 n2 : nat, plus n1 (S n2) = S (plus n1 n2).\n  induction n1; crush.\nQed.\n\nHint Rewrite plus_S.\n\nTheorem ntsize_ntsplice' : forall tr1 tr2 : nat_tree, ntsize' (ntsplice tr1 tr2) = plus (ntsize' tr2) (ntsize' tr1).\n  induction tr1 using nat_tree_ind'; crush.\n  induction ls; crush.\nQed.\n  \nTheorem ntsize_ntsplice : forall tr1 tr2 : nat_tree, ntsize (ntsplice tr1 tr2) = plus (ntsize tr2) (ntsize tr1).\n  induction tr1 using nat_tree_ind'; crush.\n  Restart.\n  Hint Extern 1 (ntsize (match ?LS with Nil => _ | Cons _ _ => _ end) = _) => destruct LS; crush.\n  induction tr1 using nat_tree_ind'; crush.\nQed.\n\nTheorem true_neq_false : true <> false.\n  red.\n  intro H.\n  Definition toProp (b : bool) := if b then True else False.\n  change (toProp false).\n  rewrite <- H.\n  simpl.\n  trivial.\nQed.\n\nTheorem S_inj' : forall n m : nat, S n = S m -> n = m.\n  intros n m H.\n  change (pred (S n) = pred (S m)).\n  rewrite H.\n  reflexivity.\nQed.\n\nPrint False_ind.\n  \n  \n\n                     \n                                     \n", "meta": {"author": "duanjp8617", "repo": "cpdt", "sha": "de9529388da34632c540ef6f6def1960c6780d67", "save_path": "github-repos/coq/duanjp8617-cpdt", "path": "github-repos/coq/duanjp8617-cpdt/cpdt-de9529388da34632c540ef6f6def1960c6780d67/src/InductiveTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.740865378217287}}
{"text": "\nRequire Import PeanoNat.\n\nRequire Import Coq.Init.Wf.\nRequire Import Coq.Arith.Wf_nat.\nRequire Import Wellfounded.Inverse_Image.\n\nRequire Import Lt.\n\nRequire Import wf_cruft.\n\n\nLtac dismiss := eexists; reflexivity.  (* used to finish a goal {y | y = ...} in the obvious way *)\n\n\nSection Euclid.\n\n  Definition absdiff a b := max a b - min a b.\n\n  Definition ltnz (ab' ab : nat * nat) :=\n    let (a', b') := ab' in\n    let (a, b) := ab in\n    b <> 0 /\\ (b' = 0 \\/ max a' b' < max a b).\n\n  Require Import Wellfounded.Lexicographic_Product.\n  Require Import Relations.Relation_Operators.\n  \n  Check wf_symprod.\n  Check symprod.\n\n  Definition measure1 (ab : nat*nat) :=\n    match ab with\n    | (_, 0) => 0\n    | (0, _) => 1\n    | _ => 2\n    end.\n  Definition measure2 (ab : nat*nat) := let (a,b) := ab in max a b.\n\n  Definition measure12 ab := (measure1 ab, measure2 ab).\n\n  Print sigT.\n  Definition lt12 ab' ab := lexprod_pair _ _ lt lt (measure12 ab') (measure12 ab).\n\n\n  Lemma lt12_wf : well_founded lt12.\n    apply wf_inverse_image with (f := measure12).\n    - apply wf_lexprod_pair; apply lt_wf.\n  Defined.\n\n  Notation \"A <>? B\" := (negb (Nat.eqb A B)) (at level 70).\n  \n  Definition measure1' (ab : nat*nat) := let (a,b) := ab in b <>? 0.\n  Definition measure2' (ab : nat*nat) := let (a,b) := ab in a <>? 0.\n  Definition measure3' (ab : nat*nat) := let (a,b) := ab in max a b.\n\n  Definition measure123' (ab : nat*nat) := (measure1' ab, measure2' ab, measure3' ab).\n\n  Definition bool_lt a b := a = false /\\ b = true.\n\n  Let f := (fun (b:bool) => if b then 1 else 0).  (* used for following proof *)\n\n  Lemma bool_lt_wf : well_founded bool_lt.\n    Check ltof.\n    apply wf_prune with (R := ltof bool f).\n    - destruct a,b; unfold bool_lt; intro H; destruct H; try (discriminate H || discriminate H0). constructor.\n    - apply wf_inverse_image with (f := f).\n      Check lt_wf.\n      apply lt_wf.\n  Defined.\n    \n  Definition lt123' ab' ab := lexprod_triple _ _ _ bool_lt bool_lt lt (measure123' ab') (measure123' ab).\n\n  Lemma lt123'_wf : well_founded lt123'.\n    apply wf_inverse_image with (f := measure123').\n    apply wf_lexprod_triple; apply bool_lt_wf || apply lt_wf.\n  Defined.\n\n      \n  Lemma ltnz_wf : well_founded ltnz.\n    eapply wf_elax with (P := fun x => snd x = 0) (R := fun x y => max (fst x) (snd x) < max (fst y) (snd y)).\n    - intro; apply Nat.eq_dec.\n    - case a,b; unfold PR; simpl. tauto.\n    - apply well_founded_ltof.\n  Defined.\n\n  Require Import Compare_dec.\n\n  Lemma neq_minmax_gt {a b} : a <> b -> max a b > min a b.\n    intro neq.\n    destruct (lt_eq_lt_dec a b); try destruct s; try tauto.  (* a = b is impossible *)\n    - (* a < b *)\n      rewrite max_r, min_l; try ( apply Le.le_Sn_le; assumption ).\n      assumption.\n    - (* b < a *)\n      rewrite max_l, min_r; try ( apply Le.le_Sn_le; assumption ).\n      assumption.\n  Qed.\n\n  Lemma neq_absdiff_nz {a b} : a <> b -> absdiff a b <> 0.\n    intro neq.\n    apply Nat.sub_gt.\n    apply neq_minmax_gt.\n    assumption.\n  Qed.\n\n  Lemma S_not_eq n m : S n <> S m -> n <> m.\n    intros K H.\n    absurd (S n = S m).\n    - assumption.\n    - rewrite H; reflexivity.\n  Qed.\n\n  Lemma eq_absdiff_z {a} : absdiff a a = 0.\n    unfold absdiff.\n    rewrite min_l, max_l; try constructor.\n    apply Nat.sub_diag.\n  Qed.\n\n  Require Import Psatz.\n\n  Lemma absdiff_0_n n : absdiff 0 n = n.\n    unfold absdiff; lia.\n  Qed.\n  \n  Definition gcd : forall (a b : nat), nat.\n    intros.\n    refine (Fix lt123'_wf (fun _ => nat)\n\n                (fun (ab:nat*nat) gcd' =>\n                   (let '(a,b) as k := ab return (ab = k -> _) in\n                    fun Hab =>\n                    match b as k return (b = k -> _) with\n                    | O => fun _ => a\n                    | S _ => fun Hb => gcd' (absdiff a b, min a b) _ \n                    end eq_refl) eq_refl\n\n           ) (a, b)).\n\n    (* Extract the whole thing as a lemma so that it does not get expanded\n     * when unfolding gcd *)\n    Lemma gcd_d a b ab (Hab : ab = (a, b)) n (Hb : b = S n) : lt123' (absdiff a b, min a b) ab.\n      subst.\n      destruct a as [|a'].\n      + (* a = 0 /\\ b <> 0 *)\n        apply left_lex, left_lex. simpl.\n        red; split; reflexivity.     (* first component of measure123' is decreasing *)\n      + (* a <> 0 /\\ b <> 0 *)\n        red.\n        case (Nat.eq_dec a' n).\n        * intro; subst. simpl.   (* a = b *)\n          apply left_lex, right_lex. simpl. rewrite eq_absdiff_z. simpl.\n          red; split; reflexivity.   (* second component is decreasing *)\n        * intro a_neq_b.                             (* a <> b *)\n          subst.\n          unfold measure123'.\n          simpl. replace (_ <>? 0) with true.\n          (**) apply right_lex.      (* third component is decreasing *)\n               unfold absdiff; lia.  (* <- very impressive *)\n          (**) symmetry.\n               rewrite Bool.negb_true_iff. (* negb b = true  -->  b = false *)\n               rewrite Nat.eqb_neq.        (* (n =? m) = false  -->  n <> m *)\n               auto using neq_absdiff_nz.\n    Defined.\n      \n    apply (gcd_d a b ab Hab n Hb).\n  Defined.\n\n  Lemma gcd_unroll_once a b :\n    gcd a b = match b with\n              | 0 => a\n              | S _ => gcd (absdiff a b) (min a b)\n              end.\n    unfold gcd.\n    rewrite Fix_eq at 1.\n    - destruct b; reflexivity.\n    - (* extensionality proof *)\n      admit.\n  Admitted.\n  \n  Lemma gcd_k a b k : k >= 1 -> a >= k * b -> gcd a b = gcd (a - k * b) b.\n    destruct b.\n    - (* b = 0  is a degenerate case *)\n      intros.\n      rewrite gcd_unroll_once, gcd_unroll_once.\n      lia.\n    - intro H; induction H.\n      + (* k = 1 *)\n        intro.\n        rewrite gcd_unroll_once.\n        unfold absdiff; f_equal; lia.\n      + (* k > 1 *)\n        intro; rewrite IHle; try lia.\n        rewrite gcd_unroll_once.\n        unfold absdiff; f_equal; lia.\n  Qed.\n\n  (*\n     Nat.div_mod:\n       forall x y : nat, y <> 0 -> x = y * (x / y) + x mod y\n   *)\n\n  Lemma div_mul_le a b : b <> 0 -> (a / b) * b <= a.\n    intro.\n    rewrite Nat.mul_comm.\n    erewrite (Nat.div_mod a b) at 2; try assumption.\n    apply Plus.le_plus_l.\n  Qed.\n\n  Check right_lex.\n\n  Lemma right_lex_pair A B ltA (ltB : _ -> _ -> Prop) x y y' :\n    ltB y y' -> lexprod_pair A B ltA ltB (x, y) (x, y').\n    intros; apply right_lex; assumption.\n  Qed.\n    \n  Lemma right_lex_pair' A B ltA (ltB : _ -> _ -> Prop) x x' y y' :\n    x = x' -> ltB y y' -> lexprod_pair A B ltA ltB (x, y) (x', y').\n    intro; subst. apply right_lex_pair.\n  Qed.\n\n  Lemma lt123'_hole a b : lt123' a b.  (** obviously false **)\n  Admitted.\n\n  Lemma gcd_comm a b : gcd a b = gcd b a.\n    induction (lt123'_wf (a,b)).\n    rewrite gcd_unroll_once.\n    rewrite (gcd_unroll_once b).\n    case b; case a; try reflexivity.\n    - intro; rewrite min_l; try apply le_0_n.\n      rewrite gcd_unroll_once; compute; reflexivity.\n    - intro; rewrite min_l; try apply le_0_n.\n      rewrite gcd_unroll_once; compute; reflexivity.\n    - intros; f_equal.\n      unfold absdiff;lia. lia.\n  Qed.\n  \n  Lemma gcd' a b : {y | y = gcd a b}.\n    pose (lt123'_wf (a,b)) as acc.\n    generalize a b acc; fix h 3.\n    intros.\n    destruct (Nat.eq_dec b0 0).\n    - subst; rewrite gcd_unroll_once; dismiss.\n    - destruct (le_lt_dec b0 a0).\n      + erewrite gcd_k.      \n        Focus 3.\n        * apply div_mul_le; assumption.\n        * edestruct h as [r R]. Focus 2. rewrite <- R. dismiss.\n          destruct acc0.\n          apply H. (**) apply lt123'_hole. (**)\n        * (* a >= b |- a / b >= 1 *)\n          apply Nat.div_le_lower_bound; try assumption.\n          rewrite Nat.mul_1_r; assumption.\n      + rewrite gcd_unroll_once.\n        generalize n; destruct b0 at 1 2; try tauto.\n        intro. unfold absdiff. rewrite max_r, min_l.\n\n  Defined.\n        \nEnd Euclid.\n\n\nExtraction gcd.\n\nExtraction gcd'.", "meta": {"author": "corwin-of-amber", "repo": "various-proofs", "sha": "e7c19549f1d573487f9fb3ebd5d6b80b2c52184b", "save_path": "github-repos/coq/corwin-of-amber-various-proofs", "path": "github-repos/coq/corwin-of-amber-various-proofs/various-proofs-e7c19549f1d573487f9fb3ebd5d6b80b2c52184b/funcprogs/euclid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7407348299199922}}
{"text": "\nRequire Import Unicode.Utf8.\n\nOpen Scope nat_scope.\n\nTheorem NAdditionAssociative : (forall x y z : nat, (x + y) + z = x + (y + z)).\nProof.\n  intro x.\n  intro y.\n  intro z.\n  \n  induction x.\n  \n  rewrite plus_O_n.\n  rewrite plus_O_n.\n  \n  reflexivity.\n  \n  rewrite (plus_Sn_m x y).\n  rewrite (plus_Sn_m (x + y) z).\n  rewrite (plus_Sn_m).\n  rewrite IHx.\n  \n  reflexivity.\nQed.\n", "meta": {"author": "jflopezfernandez", "repo": "Coq-Math-Modules", "sha": "d75d3cf04acbedb5e2cb738c6925cb21ea7b37ea", "save_path": "github-repos/coq/jflopezfernandez-Coq-Math-Modules", "path": "github-repos/coq/jflopezfernandez-Coq-Math-Modules/Coq-Math-Modules-d75d3cf04acbedb5e2cb738c6925cb21ea7b37ea/src/NaturalNumbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7407348259074719}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\nRequire int.Abs.\nRequire int.EuclideanDivision.\nRequire int.ComputerDivision.\nRequire number.Parity.\nRequire number.Divisibility.\nRequire number.Gcd.\nRequire number.Prime.\n\n(* Why3 assumption *)\nDefinition coprime (a:Z) (b:Z): Prop := ((number.Gcd.gcd a b) = 1%Z).\n\nLemma coprime_is_Zrel_prime :\n  forall a b, coprime a b <-> Znumtheory.rel_prime a b.\nintros.\nunfold coprime.\nunfold Znumtheory.rel_prime.\nsplit; intro h.\nrewrite <- h; apply Znumtheory.Zgcd_is_gcd.\napply Znumtheory.Zis_gcd_gcd; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma prime_coprime : forall (p:Z), (number.Prime.prime p) <->\n  ((2%Z <= p)%Z /\\ forall (n:Z), ((1%Z <= n)%Z /\\ (n < p)%Z) -> (coprime n\n  p)).\nintros p.\n(*\nZnumtheory.prime_intro:\n  forall p : int,\n  (1 < p)%Z ->\n  (forall n : int, (1 <= n < p)%Z -> Znumtheory.rel_prime n p) ->\n  Znumtheory.prime p\n*)\nrewrite Prime.prime_is_Zprime.\nsplit.\nintro h; inversion h; clear h.\nsplit; auto with zarith.\nintros n h.\nrewrite coprime_is_Zrel_prime.\napply H0; auto.\nintros (h1,h2).\nconstructor; auto with zarith.\nintros n h.\nrewrite <- coprime_is_Zrel_prime.\napply h2; auto.\nQed.\n\n(* Why3 goal *)\nLemma Gauss : forall (a:Z) (b:Z) (c:Z), ((number.Divisibility.divides a\n  (b * c)%Z) /\\ (coprime a b)) -> (number.Divisibility.divides a c).\nintros a b c (h1,h2).\napply Znumtheory.Gauss with b; auto.\nrewrite <- coprime_is_Zrel_prime; auto.\nQed.\n\n(* Why3 goal *)\nLemma Euclid : forall (p:Z) (a:Z) (b:Z), ((number.Prime.prime p) /\\\n  (number.Divisibility.divides p (a * b)%Z)) -> ((number.Divisibility.divides\n  p a) \\/ (number.Divisibility.divides p b)).\nintros p a b (h1,h2).\napply Znumtheory.prime_mult; auto.\nnow rewrite <- Prime.prime_is_Zprime.\nQed.\n\n(* Why3 goal *)\nLemma gcd_coprime : forall (a:Z) (b:Z) (c:Z), (coprime a b) ->\n  ((number.Gcd.gcd a (b * c)%Z) = (number.Gcd.gcd a c)).\nintros a b c h1.\napply Z.gcd_unique.\n- apply Z.gcd_nonneg.\n- apply Gcd.gcd_def1.\n- apply Divisibility.divides_multl.\n  apply Gcd.gcd_def2.\n- intros q h2 h3.\n  apply Gcd.gcd_def3.\n  trivial.\n  apply Gauss with b; split; auto.\n  rewrite coprime_is_Zrel_prime.\n  rewrite coprime_is_Zrel_prime in h1.\n  now apply Znumtheory.rel_prime_div with (2:=h2).\nQed.\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/number/Coprime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.740668203233679}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf4 : natural) (lf2 : natural) : natural :=\n  plus Zero (plus lf2 lf4).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj92_coqofml_3eim4b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7406681928021714}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith List Omega.\n\nRequire Import tacs.\n\nSet Implicit Arguments.\n\nDefinition app_split X (l1 : list X) : forall l2 r1 r2, l1++r1 = l2++r2\n                                      -> { m | l2 = l1++m /\\ r1 = m++r2 }\n                                       + { m | l1 = l2++m /\\ r2 = m++r1 }.\nProof.\n  induction l1 as [ | x l1 Hl1 ].\n  left; exists l2; auto.\n  intros [ | y l2 ] r1 r2 H.\n  right; exists (x::l1); auto.\n  simpl in H; injection H; clear H; intros H ?; subst.\n  apply Hl1 in H.\n  destruct H as [ (m & H1 & H2) | (m & H1 & H2) ].\n  left; exists m; subst; auto.\n  right; exists m; subst; auto.\nQed.\n\nFact list_split_first_half U (ll : list U) x : x <= length ll -> { l : _ & { r | ll = l++r /\\ length l = x } }.\nProof.\n  revert ll; induction x as [ | x IHx ]; intros [ | u ll ] Hx.\n  exists nil, nil; simpl; auto.\n  exists nil, (u::ll); auto.\n  simpl in Hx; omega.\n  destruct (IHx ll) as (l & r & H1 & H2).\n  simpl in Hx; omega.\n  exists (u::l), r; simpl; split; f_equal; auto.\nQed.\n    \nFact list_split_second_half U (ll : list U) x : x <= length ll -> { l : _ & { r | ll = l++r /\\ length r = x } }.\nProof.\n  intros Hx.\n  destruct list_split_first_half with (ll := ll) (x := length ll - x)\n    as (l & r & H1 & H2).\n  omega.\n  exists l, r; split; auto.\n  apply f_equal with (f := @length _) in H1.\n  rewrite app_length in H1.\n  omega.\nQed.  \n\nSection list_prefix. \n\n  Variables (X : Type).\n\n  Fixpoint pfx (f : nat -> X) n :=\n      match n with\n        | 0   => nil\n      | S n => f 0 :: pfx (fun n => f (S n)) n\n    end.\n\n  Fact pfx_length f n : length (pfx f n) = n.\n  Proof.\n    revert f; induction n; intros f; simpl; auto.\n  Qed.\n    \n  Fact pfx_plus f a b : pfx f (a+b) = pfx f a ++ pfx (fun n => f (a+n)) b.\n  Proof.\n    revert f;\n    induction a; intros f; simpl; auto.\n    f_equal; apply IHa.\n  Qed.\n\n  Fact pfx_In f n x : In x (pfx f n) <-> exists i, i < n /\\ x = f i.\n  Proof.\n    split.\n\n    revert f; induction n as [ | n IHn ]; intros f; simpl.\n    intros [].\n    intros [ H | H ].\n    subst; exists 0; split; auto; omega.\n    destruct (IHn _ H) as (i & H1 & H2).\n    exists (S i); split; auto; omega.\n    \n    intros (i & H1 & H2); subst x.\n    revert f i H1.\n    induction n as [ | n IH ]; intros f i Hi; try omega; simpl.\n    destruct i.\n    left; auto.\n    right. \n    apply (IH (fun x => f (S x))); omega.\n  Qed.\n\n  Fact pfx_eq f n l x r : pfx f n = l++x::r -> f (length l) = x.\n  Proof.\n    revert f l x r; induction n as [ | n IH ]; intros f l x r; simpl.\n    destruct l; discriminate 1.\n    destruct l as [ | y l ]; simpl;\n    intros H; injection H; clear H; intros H1 H2; auto.\n    apply IH in H1; auto.\n  Qed.\n\n  Fixpoint list_fun_concat l f n : X :=\n    match l with \n      | nil  => f n\n      | x::l => \n      match n with \n        | 0   => x\n        | S n => list_fun_concat l f n\n      end\n    end.\n\n  Fact lf_concat_pfx_lt ll f n : n < length ll -> exists l r, l ++ r = ll /\\ l = pfx (list_fun_concat ll f) n.\n  Proof.\n    revert n; induction ll as [ | x ll IH ]; intros [ | n ] Hn; simpl in Hn; try (exfalso; omega); simpl.\n    exists nil, (x::ll); auto.\n    destruct (IH n) as (l & r & H1 & H2).\n    omega.\n    exists (x::l), r; simpl; split; f_equal; auto.\n  Qed.\n  \n  Fact lf_concat_pfx_ge ll f n : length ll <= n -> pfx (list_fun_concat ll f) n = ll ++ pfx f (n - length ll).\n  Proof.\n    revert n; induction ll as [ | x ll IH ]; intros n Hn.\n    simpl; f_equal; omega.\n    destruct n.\n    simpl in Hn; omega.\n    simpl.\n    f_equal.\n    apply IH.\n    simpl in Hn; omega.\n  Qed.\n\nEnd list_prefix.\n\nFact pfx_map X Y (h : X -> Y) f n : pfx (fun n => h (f n)) n = map h (pfx f n).\nProof.\n  revert f; induction n; intros f; simpl; f_equal; auto.\nQed.\n\n(* prefix of an infinite sequence, in reverse order *)\n   \nSection list_prefix_rev.\n \n  Variable X : Type.\n\n  Fixpoint pfx_rev f n : list X := \n    match n with \n      | 0   => nil\n      | S n => (f n)::(pfx_rev f n)\n    end.\n\n  Fact pfx_rev_plus f a b : pfx_rev f (a+b) = pfx_rev (fun n => f (b+n)) a ++ pfx_rev f b.\n  Proof.\n    induction a; simpl; auto.\n    f_equal; auto.\n    f_equal; apply plus_comm.\n  Qed.\n  \n  Fact pfx_rev_S f a : pfx_rev f (S a) = pfx_rev (fun n => f (S n)) a ++ f 0 :: nil.\n  Proof.\n    generalize (pfx_rev_plus f a 1); intros H.\n    replace_with H; f_equal; rewrite plus_comm; auto.\n  Qed.\n\n  Fact pfx_pfx_rev_eq f n : pfx_rev f n = rev (pfx f n).\n  Proof.\n    revert f.\n    induction n as [ | n IHn ]; intros f.\n    simpl; auto.\n    simpl pfx.\n    cutrewrite (S n = n+1); try omega.\n    rewrite pfx_rev_plus; simpl.\n    f_equal; auto.\n  Qed.  \n\n  Fact pfx_rev_ext f g n : (forall x, x < n -> f x = g x) -> pfx_rev f n = pfx_rev g n.\n  Proof.\n    induction n; simpl; auto; \n    intros H.\n    rewrite H; try omega.\n    f_equal; auto.\n  Qed.\n  \n  Fact pfx_rev_minus f n : pfx_rev f n = pfx (fun x => f (n - S x)) n.\n  Proof.\n    revert f; induction n as [ | n IHn ]; intros f; simpl; auto.\n    do 2 f_equal. omega.\n    apply IHn.\n  Qed.    \n\n  Fact pfx_rev_In f n x : In x (pfx_rev f n) <-> exists i, i < n /\\ x = f i.\n  Proof.\n    split.\n\n    induction n as [ | n IHn ]; simpl.\n    intros [].\n    intros [ H | H ].\n    subst; exists n; auto.\n    destruct (IHn H) as (i & H1 & H2).\n    exists i; split; auto.\n    \n    intros (i & H1 & H2); subst x.\n    revert i H1.\n    induction n as [ | n IH ]; intros i Hi; try omega; simpl.\n    destruct (le_lt_dec n i).\n    left; f_equal; omega.\n    right; apply IH; auto.\n  Qed.\n\n  Fact pfx_rev_length f n : length (pfx_rev f n) = n.\n  Proof.\n    induction n; simpl; auto.\n  Qed.\n\n  Fact pfx_rev_eq f n l x r : pfx_rev f n = l++x::r -> f (length r) = x.\n  Proof.\n    revert l x r; induction n as [ | n IH ]; intros l x r; simpl.\n    destruct l; discriminate 1.\n    destruct l as [ | y l ]; simpl;\n    intros H; injection H; clear H; intros H1 H2.\n    replace_with H2; f_equal.\n    subst r; apply pfx_rev_length.\n    apply IH with (1 := H1).\n  Qed.\n\nEnd list_prefix_rev.\n\nFact pfx_rev_map X Y (h : X -> Y) f n : pfx_rev (fun n => h (f n)) n = map h (pfx_rev f n).\nProof.\n  induction n; simpl; f_equal; auto.\nQed.\n \nDefinition list_prefix X (ll : list X) n : n <= length ll -> { l : _ & { r | ll = l++r /\\ length l = n } }.\nProof.\n  revert n; induction ll as [ | x ll IH ].\n  intros [ | n ] Hn; exists nil, nil; split; auto.\n  exfalso; simpl in Hn; omega.\n  intros [ | n ] Hn.\n  exists nil, (x::ll); auto.\n  simpl in Hn.\n  destruct (IH n) as (l & r & H1 & H2).\n  omega.\n  subst.\n  exists (x::l), r; auto.\nQed.\n\nDefinition list_suffix X (ll : list X) n : n <= length ll -> { l : _ & { r | ll = l++r /\\ length r = n } }.\nProof.\n  intros H.\n  destruct (@list_prefix _ ll (length ll - n)) as (l & r & H1 & H2).\n  omega.\n  exists l, r; repeat split; auto.\n  apply f_equal with (f := @length _) in H1.\n  rewrite app_length in H1.\n  omega.\nQed.\n\nFact list_prefix_eq X (l r l' r' : list X) : l++r = l'++r' -> length l = length l' -> l = l' /\\ r = r'.\nProof.\n  revert l'; induction l as [ | x l IHl ]; intros [ | y l' ] H1 H2; auto; simpl in H2; try discriminate H2.\n  simpl in H1; injection H1; clear H1; intros H1 H3; subst.\n  destruct IHl with (1 := H1).\n  omega.\n  subst; auto.\nQed.\n\nFact list_suffix_eq X (l r l' r' : list X) : l++r = l'++r' -> length r = length r' -> l = l' /\\ r = r'.\nProof.\n  intros H1 H2; apply list_prefix_eq; auto.\n  apply f_equal with (f := @length _) in H1.\n  do 2 rewrite app_length in H1.\n  omega.\nQed.\n\nFact list_suffix_split X (l r l' r' : list X) : l++r = l'++r' -> length r <= length r' -> { m | l = l'++m /\\ r' = m++r }.\nProof.\n  revert r l' r'; induction l as [ | x l IHl ]; intros r [ | y l' ] r' H1 H2; simpl in H1.\n  exists nil; auto.\n  apply f_equal with (f := @length _) in H1.\n  simpl in H1.\n  rewrite app_length in H1.\n  exfalso; omega.\n  exists (x::l); auto.\n  injection H1; clear H1; intros H1 ?; subst y.\n  destruct IHl with (1 := H1) as (m & H3 & H4); auto.\n  exists m; subst; auto.\nQed.\n", "meta": {"author": "DmxLarchey", "repo": "Relevant-decidability", "sha": "6b1c4d48f734c4d440d9756630998d231b2cc02f", "save_path": "github-repos/coq/DmxLarchey-Relevant-decidability", "path": "github-repos/coq/DmxLarchey-Relevant-decidability/Relevant-decidability-6b1c4d48f734c4d440d9756630998d231b2cc02f/list_prefix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7406331621319135}}
{"text": "Require Import Contractive ContractiveFacts CS CSFacts Equiv Free FreeFacts\n  NonEquiv Rel Sty StyInd Subst SubstFacts Shape Tac Msg Var Wf WfFacts.\nRequire Import TLC.LibRelation TLC.LibLogic.\n\n\n(* ------------------------------------------------------------------------- *)\n(* Reflexivity *)\n\nInductive R_Sequiv_reflexive : Sty -> Sty -> Prop :=\n| R_Sequiv_reflexive_refl :\n    forall S,\n    Wf S ->\n    R_Sequiv_reflexive S S\n| R_Sequiv_reflexive_mu1 :\n    forall X S,\n    Wf (subst X (mu X S) S) ->\n    R_Sequiv_reflexive (mu X S) (subst X (mu X S) S)\n| R_Sequiv_reflexive_mu2 :\n    forall X S,\n    Wf (subst X (mu X S) S) ->\n    R_Sequiv_reflexive (subst X (mu X S) S) (mu X S)\n.\n\nTheorem Sequiv_reflexive :\n  forall S,\n  Wf S ->\n  Sequiv S S.\nProof.\n  intros. apply Sequiv_coind with (R := R_Sequiv_reflexive);\n    [|constructor; auto].\n  clear. introv H. inverts1 H; [destruct S'|..];\n    try (constructor; constructor); auto with wf.\nQed.\n\n\n(* ------------------------------------------------------------------------- *)\n(* Symmetry *)\n\n\nTheorem Sequiv_symmetric : forall S S',\n  Sequiv S S' -> Sequiv S' S.\nProof with auto.\n  apply clos_sym_sym. unfold inclusion. apply Sequiv_coind.\n  intros S S' H.\n  inversion_clear H. inversion_clear H0.\n  inversion H; constructor; subst; constructor...\nQed.\n\n\n(* ------------------------------------------------------------------------- *)\n(* Transitivity *)\n\nSection Transitivity.\n\n\nInductive R_Sequiv_transitive : Sty -> Sty -> Prop :=\n| R_Sequiv_transitive_intro :\n    forall S T U,\n    Wf S ->\n    Wf T ->\n    Wf U ->\n    Sequiv S T ->\n    Sequiv T U ->\n    R_Sequiv_transitive S U\n.\nHint Constructors R_Sequiv_transitive.\n\n\nTheorem Sequiv_transitive :\n  forall S T U,\n  Wf S ->\n  Wf T ->\n  Wf U ->\n  Sequiv S T ->\n  Sequiv T U ->\n  Sequiv S U.\nProof.\n  intros. apply Sequiv_coind with (R := R_Sequiv_transitive);\n    [|eauto].\n  clear. introv H. rename S' into U. inverts H.\n\n  assert (Sequiv S (cs T)) as HSeqT by (\n    eapply cs_preserves_Sequiv_r; auto with wf\n  ).\n\n  assert (Sequiv (cs T) U) as HTeqU by (\n    eapply cs_preserves_Sequiv_l; auto with wf\n  ).\n\n  Hint Extern 3 (Wf _) =>\n    match goal with\n    | HWfT : Wf ?T, Heq : ?S = cs ?T |- _ =>\n        solve [\n          apply cs_preserves_Wf in HWfT; rewrite <- Heq in HWfT; auto with wf\n        ]\n    end\n  .\n\n  Local Ltac finish T1 :=\n    apply R_Sequiv_transitive_intro with (T := T1); auto with wf\n  .\n\n  clear H3 H4. inverts2 HSeqT; inverts2 HTeqU; subst; try solve [false].\n  - auto.\n  - constructor. rewrite <- HSeqT in *. eauto with wf.\n  - rewrite <- H4 in H3. injection H3; intros; subst. constructor. finish S.\n  - rewrite <- H3 in *. constructor. finish (send B S').\n  - rewrite <- H4 in H3. injection H3; intros; subst. constructor. finish S.\n  - rewrite <- H3 in *. constructor. finish (recv B S').\n  - rewrite <- H4 in H3. injection H3; intros; subst. constructor.\n    * finish S0.\n    * finish S3.\n  - rewrite <- H3 in *. constructor. finish (echoice S1' S2').\n  - rewrite <- H4 in H3. injection H3; intros; subst. constructor.\n    * finish S0.\n    * finish S3.\n  - rewrite <- H3 in *. constructor. finish (ichoice S1' S2').\n  - rewrite <- HTeqU in *. constructor. eauto with wf.\n  - rewrite <- H3 in *. constructor. finish (send B S).\n  - rewrite <- H3 in *. constructor. finish (recv B S).\n  - rewrite <- H3 in *. constructor. finish (echoice S1 S2).\n  - rewrite <- H3 in *. constructor. finish (ichoice S1 S2).\n  - exfalso; auto with subst wf.\n  - assert (Sequiv (cs T) (mu X0 S')) as HTeqU' by auto.\n    constructor. finish (cs T).\n  - exfalso; auto with subst wf.\n  - exfalso; auto with subst wf.\nQed.\n\nEnd Transitivity.\n\n\n(* ------------------------------------------------------------------------- *)\n(* NSequiv -> ~ Sequiv *)\n\n\nLemma NSequiv_not_Sequiv :\n  forall S S',\n  Contractive S ->\n  Contractive S' ->\n  NSequiv S S' ->\n  ~ Sequiv S S'.\nProof.\n  introv Hok Hok' H. induction H; introv contra; try solve\n    [ inverts2 contra; auto\n    | inverts2 contra; inverts Hok; inverts Hok';\n      unfold not in *; eauto with nsequiv\n    ].\n  - apply cs_preserves_Sequiv_r in contra; inverts2 contra;\n    [apply IHNSequiv|..];\n    auto using uncs_preserves_Sequiv_r with contractive subst.\n  - apply cs_preserves_Sequiv_l in contra; inverts2 contra;\n    [|apply IHNSequiv|..];\n    auto using uncs_preserves_Sequiv_l with contractive subst.\nQed.\n\n\n(* ------------------------------------------------------------------------- *)\n(* ~ NSequiv -> Sequiv *)\n\n\nInductive R_not_NSequiv_Sequiv : Sty -> Sty -> Prop :=\n| R_not_NSequiv_Sequiv_intro :\n    forall S S',\n    Closed S ->\n    Closed S' ->\n    ~ NSequiv S S' ->\n    R_not_NSequiv_Sequiv S S'\n.\nHint Constructors R_not_NSequiv_Sequiv : nsequiv.\n\n\nLemma not_NSequiv_Sequiv' :\n  forall S S',\n  R_not_NSequiv_Sequiv S S' ->\n  Sequiv_gen R_not_NSequiv_Sequiv S S'.\nProof.\n  introv H. inverts H as Hcl Hcl' H. destruct S; destruct S'; try solve\n    [ exfalso; apply H; constructor; intro; discriminate ];\n    try match goal with\n    | B : Msg, B' : Msg |- _ =>\n      destruct (eq_Msg_dec B B'); [subst | exfalso; auto with nsequiv]\n    end;\n    auto 8 with free nsequiv.\nQed.\n\nLemma not_NSequiv_Sequiv :\n  forall S S',\n  Closed S ->\n  Closed S' ->\n  ~ NSequiv S S' ->\n  Sequiv S S'.\nProof.\n  intros. apply Sequiv_coind with (R := R_not_NSequiv_Sequiv);\n  auto using not_NSequiv_Sequiv' with nsequiv.\nQed.\n\n\n(* ------------------------------------------------------------------------- *)\n(* NSequiv <-> ~ Sequiv *)\n\nLemma NSequiv_iff_not_Sequiv :\n  forall S S',\n  Wf S ->\n  Wf S' ->\n  (NSequiv S S' <-> ~ Sequiv S S').\nProof.\n  introv Hok Hok'. split; introv H; unfold Wf in *.\n  + eapply NSequiv_not_Sequiv; eauto.\n  + gen H. apply contrapose_elim. introv H. apply not_not_intro.\n    apply not_NSequiv_Sequiv; auto.\nQed.\n", "meta": {"author": "JLimperg", "repo": "SessionTypes", "sha": "3cee38f62a153e5b04a6836e57ab0c851fcf44dd", "save_path": "github-repos/coq/JLimperg-SessionTypes", "path": "github-repos/coq/JLimperg-SessionTypes/SessionTypes-3cee38f62a153e5b04a6836e57ab0c851fcf44dd/src/EquivFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7406049001521512}}
{"text": "Require Export P08.\n\n\n\n(** **** Exercise: 4 stars, advanced (pigeonhole principle)  *)\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 lt_S: forall n m,\n    S n < S m -> n < m.\nProof.\nintros.\ninduction m.\n- inversion H. inversion H1.\n- inversion H. auto.\n  apply IHm in H1.\n  constructor.\n  assumption.\nQed.\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.\nintros.\ninduction l.\n- inversion H.\n- inversion H.\n  + rewrite H0 in *.\n    exists [], l.\n    reflexivity.\n  + apply IHl in H0.\n    inversion H0.\n    inversion H1.\n    exists (a::x0).\n    exists x1.\n    simpl.\n    rewrite H2.\n    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| rp_base: forall x l, In x l -> repeats (x::l)\n| rp_next: forall x l, repeats l -> repeats (x::l)\n.\n\nTheorem len_plus: forall (X:Type) (l1:list X) (l2:list X),\n    length (l1++l2) = length l1 + length l2.\nProof.\nintros.\ninduction l1.\n- reflexivity.\n- simpl. rewrite IHl1. auto.\nQed.\n\nTheorem in_case_diff:forall (X:Type) (x:X) (x2:X) (l1 l2:list X),\n  In x2 (l1++x::l2) -> x <> x2 -> In x2 (l1++l2).\nProof.\nintros.\ninduction l1.\n- simpl. simpl in H. destruct H.\n  + apply H0 in H. inversion H.\n  + assumption.\n- simpl. simpl in H.\n  destruct H.\n  + auto.\n  + right. auto.\nQed.\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   - simpl. intros. inversion H1.\n   - intros l2 H_excluded H1 H2. unfold excluded_middle in *.\n     assert (H' := H_excluded (In x l1')).\n     destruct H'.\n     + apply rp_base. assumption.\n     + apply rp_next. destruct (in_split X x l2).\n       * apply H1. simpl. left. reflexivity.\n       * inversion H0. apply IHl1' with (l2 := x0++x1).\n         ++ assumption.\n         ++ intros. destruct (H_excluded (x = x2)) eqn:Heqxx2.\n            +++ subst. apply H in H4. contradiction.\n            +++ apply in_case_diff with (x := x). subst. apply H1.\n                simpl. right. assumption. assumption.\n         ++ subst. rewrite len_plus in H2. simpl in H2. rewrite <- plus_n_Sm in H2.\n            rewrite len_plus. apply lt_S. assumption.\nQed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/06/P09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7405897973361788}}
{"text": "Require Import Omega.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nFrom q3_2001 Require Export misc.\n\n(* As elsewhere, no difference to work over a general type with decidable\n   equality except that we'd have to litter the codebase with lots of \n   'decA' terms so let's just stick with nat. *)\nDefinition nunique := compose (@length nat) (nodup Nat.eq_dec).\n\nLemma nunique_spec_0 : forall (l : list nat),\n  nunique l = length (nodup Nat.eq_dec l).\nProof. auto. Qed.\n\nLemma nunique_spec_1 : forall (l : list nat),\n  nunique l = 0 <-> l = [].\nProof. intros l. rewrite nunique_spec_0. rewrite length_zero_iff_nil. apply nodup_empty_spec. Qed.\n\nLemma nunique_spec_2 : forall (l : list nat),\n  nunique l <> 0 <-> l <> [].\nProof. intros l. split; apply contrapositive; rewrite nunique_spec_1; trivial. Qed.\n\nLemma nunique_spec_3 : forall (l : list nat) (x : nat),\n  In x l -> nunique (x::l) = nunique l.\nProof.\n  intros l x Hx. unfold nunique. unfold compose.\n  assert (H_incl : incl (nodup Nat.eq_dec (x::l)) (nodup Nat.eq_dec l)). {\n    unfold incl. intros x' Hx'. rewrite -> nodup_In. rewrite -> nodup_In in Hx'.\n    destruct Hx'; [subst |]; assumption.\n  }\n  assert (H_incl' : incl (nodup Nat.eq_dec l) (nodup Nat.eq_dec (x::l))). {\n    unfold incl. intros x' Hx'. rewrite -> nodup_In. rewrite -> nodup_In in Hx'. right. assumption.\n  }\n  apply NoDup_incl_length in H_incl; try (apply NoDup_nodup).\n  apply NoDup_incl_length in H_incl'; try (apply NoDup_nodup).\n  omega.\nQed.\n\nLemma nunique_spec_4 : forall (l : list nat) (x : nat),\n  ~In x l -> nunique (x::l) = 1 + nunique l.\nProof.\n  intros l x Hx. unfold nunique. unfold compose.\n  assert (H_incl : incl (nodup Nat.eq_dec (x::l)) (x::(nodup Nat.eq_dec l))). {\n    unfold incl. intros x' Hx'. simpl. rewrite -> nodup_In. rewrite -> nodup_In in Hx'. simpl in Hx'. assumption.\n  }\n  assert (H_incl' : incl (x::(nodup Nat.eq_dec l)) (nodup Nat.eq_dec (x::l))). {\n    unfold incl. intros x' Hx'. rewrite -> nodup_In. simpl in Hx'. rewrite -> nodup_In in Hx'. simpl. assumption.\n  }\n  apply NoDup_incl_length in H_incl; try (apply NoDup_nodup).\n  apply NoDup_incl_length in H_incl'; try (rewrite NoDup_cons_iff).\n  - assert (H : length (nodup Nat.eq_dec (x :: l)) = length (x :: nodup Nat.eq_dec l)). { omega. }\n    rewrite -> H. reflexivity.\n  - split.\n    + rewrite -> nodup_In. assumption.\n    + apply NoDup_nodup.\nQed.\n\nLemma nunique_spec_5 : forall (l : list nat),\n  l = [] <-> nunique l = 0.\nProof.\n  intros l.\n  split; intros H.\n  - subst. auto.\n  - rewrite nunique_spec_0 in H. rewrite length_zero_iff_nil in H.\n    rewrite nodup_empty_spec in H. assumption.\nQed.\n", "meta": {"author": "ocfnash", "repo": "imo-coq", "sha": "f6d2e8337fadf00583fd09f86faf9cba62a25677", "save_path": "github-repos/coq/ocfnash-imo-coq", "path": "github-repos/coq/ocfnash-imo-coq/imo-coq-f6d2e8337fadf00583fd09f86faf9cba62a25677/q3_2001/nunique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7405897898604278}}
{"text": "Print le.\n\n\nLemma Z_le_n : forall n, le 0 n.\nProof.\ninduction n.\n- constructor.\n- constructor.\n  assumption.\nQed.\n\n\nLemma le_S: forall n m, le n m -> le (S n) (S m).\nProof.\ninduction 1.\n- constructor.\n- constructor;assumption.\nQed.\n\n\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\n\nPrint pred.\nPrint Nat.pred.\n\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n(*\n  intros n E.\n  induction E.\n  - simpl; constructor.\n  - simpl.\n    assumption.\n*)\n  intros n E.\n  inversion E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'. \n\nQed.\n\nSection A_dec.\n\nVariable A : Type.\nVariable eq_dec : forall (x y:A), {x=y}+{~ x=y}.\n\nLocate \"+\".\nPrint sumbool.\n\nPrint list.\n\nFixpoint count_occ (x:A)(l:list A) :=\nmatch l with\n| nil => 0\n| cons y l' => let n:= count_occ x l' in\n             match eq_dec x y with\n             | left _ => 1 + n\n             | right _ => n\n             end\nend.\n\n\nLemma AtLeastOne: forall (x:A)(l:list A),count_occ x l > 0 -> l<> nil.\nProof.\nintros x l.\ndestruct l.\n- simpl.\n  intros.\n  inversion H.\n- simpl.\n  destruct (eq_dec x a); intros; congruence.\nQed.\n\nEnd A_dec.\n\n\nCheck AtLeastOne.\n\nLemma nat_dec: forall (x y:nat), {x=y}+{~ x=y}.\nProof.\ninduction x; destruct y.\n - left; reflexivity.\n - right; congruence.\n - right; congruence.\n - destruct (IHx y).\n   * left; congruence.\n   * right; congruence.\nQed.\n\nCheck AtLeastOne nat nat_dec.\n\n\n\n\n\n\n\n\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/Lab4/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.7405897728428317}}
{"text": "(******************************************************************************)\n(* Solutions of exercises : Small scale reflection, first examples            *)\n(******************************************************************************)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.\nFrom mathcomp Require Import path choice fintype tuple finset.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\n(******************************************************************************)\n(* Exercise 4.1.1                                                             *)\n(******************************************************************************)\n\n(* The proof goes by case analysis on the truth table, applying the *)\n(*appropriate constructor of the reflect predicate in every meaningful *)\n(*case. The other case ask a proof of False in a conctext where False *)\n(*can be obtained as a hypothesis after destructing a conjunction (the *)\n(*last case tactic) *)\n\nLemma tuto_andP : forall b1 b2 : bool, reflect (b1 /\\ b2) (b1 && b2).\nProof. by case; case; constructor; auto; case. Qed.\n\n(* Again this lemma is a macro for a cacse analysis on the truth table *)\n(*of b1 b2 and (b1 || b2) *)\n\nLemma tuto_orP : forall b1 b2 : bool, reflect (b1 \\/ b2) (b1 || b2).\nProof. by case; case; constructor; auto; case. Qed.\n\n(******************************************************************************)\n(* Exercise 4.1.2                                                             *)\n(******************************************************************************)\n\n(* The first solution follows the hint given in the tutorial. In fact *)\n(* it is sufficient to perform case analysis on the constructor of the *)\n(*reflect hypothesis as done in the second solution. *)\nLemma tuto_iffP : forall (P Q : Prop) (b : bool),\n      reflect P b -> (P -> Q) -> (Q -> P) -> reflect Q b.\nProof. by move=> P Q; case; case; constructor; auto. Qed.\n\n\nLemma alternate_tuto_iffP : forall (P Q : Prop) (b : bool),\n      reflect P b -> (P -> Q) -> (Q -> P) -> reflect Q b.\nProof. by move=> P Q b; case; constructor; auto. Qed.\n\n(******************************************************************************)\n(* Exercise 4.2.1                                                             *)\n(******************************************************************************)\n\n(*We use a section to factorize the type of elements in the *)\n(*sequences*)\n\nSection Exo_4_2_1.\n\nVariable A : Type.\n\n(* We use implicit type annotations to avoid casting quantified *)\n(*variables : *)\nImplicit Types s : seq A.\nImplicit Types x : A.\n\n(* The type of x has been declared implicit, hence the type of s1 and *)\n(*s2 and inferred: *)\nFixpoint tuto_cat s1 s2 :=\nmatch s1 with\n  |[::] => s2\n  | x :: s' => x :: (tuto_cat s' s2)\nend.\n\n(* Using the ssreflect pattern conditional this code can be shrinked *)\n(*into the actual program present in the seq library:*)\nFixpoint alternate_tuto s1 s2 :=\n  if s1 is x :: s' then x :: (tuto_cat s' s2) else s2.\n\n\n(* The proof goes by induction on the first list. We do not need to be *)\n(*general with respect to the second list, hence we introduce it *)\n(*before the induction. The first case is solved on the fly by the //= *)\n(*simple+solve switch, and x and s1 are introduced in the remaining *)\n(*goal. The last hypothesis is directly rewritten without being *)\n(*introduced, generating an equality between convertible terms. This *)\n(*equality being trivial it is solved by the prenex 'by' tactic *)\nLemma tuto_size_cat : forall s1 s2,\n   size (s1 ++ s2) = size s1 + size s2.\nProof. by move=> s1 s2; elim: s1 => //= x s1 ->. Qed.\n\n(* We use again a pattern conditional *)\nFixpoint tuto_last (A : Type)(x : A)(s : seq A) {struct s} := \n  if s is x' :: s' then tuto_last x' s' else x.\n\n(* Again an induction on the first list *)\nLemma tuto_last_cat : forall x s1 s2,\n  last x (s1 ++ s2) = last (last x s1) s2.\nProof. by move=> x s1 s2; elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed.\n\nFixpoint tuto_take n s {struct s} :=\n  match s, n with\n  | x :: s', n'.+1 => x :: take n' s'\n  | _, _ => [::]\n  end.\n\n\n(* Here we have two options: a recursion on the nat or on the seq.*)\n(* Decreazing on the seq has better compositional properties: it *)\n(*allows more fixpoints further defined to decrease structurally *)\nFixpoint tuto_drop n s {struct s} :=\n  match s, n with\n  | _ :: s', n'.+1 => drop n' s'\n  | _, _ => s\n  end.\n\nDefinition tuto_rot n s := drop n s ++ take n s.\n\nLemma tuto_rot_addn : forall m n s, m + n <= size s ->\n  rot (m + n) s = rot m (rot n s).\nProof.\n(* We first transform the inequality hypothesis into a case *)\n(*disjunction between equality or strict inequality. *)\nmove=> m n s; rewrite leq_eqVlt. \n(* Then a view allows to proceed to the case analysis by generating *)\n(* two goals *)\ncase/predU1P=> [Emn|Hmn].\n(*  1st case: equality. We rewrite the hypothesis, then the rot_size *)\n(*lemma (try to guess the name of the lemma according to the ssr *)\n(*discipline, or use the Search command, for instance:\nSearch _ rot size.*)\nrewrite Emn rot_size.\n(* Again, use the Search command:*)\nSearch _ (rot _ (rot _ _) = _).\n  rewrite rot_add_mod -Emn ?leq_addr ?leq_addl //.\n  by rewrite  Emn leqnn rot_size.\n(* a more elegant proof of this last step would be:\n  by rewrite  -{1}(rotrK m s) /rotr -Emn addKn.\n  It is worth also browsing the source of the library to discover new\n  functions that could help you, like rotr is this case *)\n(* Remember rot is programmed from cat take and drop:\nSearch _ cat take drop.*)\nrewrite -{1}(cat_take_drop n s) /rot !take_cat !drop_cat.\nSearch _ (size (take _ _) = _).\nhave Hns : n <= size s by apply: leq_trans (leq_addl _ _) (ltnW Hmn).\nrewrite !(size_takel Hns).\n(* We directly rewrite the condition proved forward *)\nhave -> : m + n < n = false by rewrite ltnNge leq_addl.  \nrewrite size_drop.\nhave -> :  m < size s - n by rewrite ltnNge leq_subLR -ltnNge addnC.\nby rewrite addnK catA.\nQed.\n\n(* Look at the source of the seq.v file for a shorter proof! *)\n\nEnd Exo_4_2_1.\n(******************************************************************************)\n(* Exercise 4.2.2                                                             *)\n(******************************************************************************)\n\nSection Exo_4_2_2.\n\nVariable A : Type.\n\n(* We use implicit type annotations to avoid casting quantified *)\n(*variables : *)\nImplicit Types s : seq A.\nImplicit Types x : A.\n\n(* We fix an arbitrary predicate a *)\nVariable a : pred A.\n\n(* We use again a pattern conditional *)\nFixpoint tuto_count s := if s is x :: s' then a x + tuto_count s' else 0.\n\nLemma tuto_count_predUI : forall a1 a2 s,\n count (predU a1 a2) s + count (predI a1 a2) s = count a1 s + count a2 s.\nProof.\nmove=> a1 a2. \n(* The proof goes by induction on the list. In the inductive case, we *)\n(*introduce the head, the tail, and the induction hypothesis. After\n simplification, the case case is trivial, and since simplification is\n also usefull in the inductive case, the //= swith both simplifies and\n closes the first goal.*)\nelim=> [|x s IHs] //=. \n(* Now a couple of arithmetic rewriting before using the inductive hypothesis*)\nrewrite addnCA -addnA  addnA addnC IHs -!addnA.\n(* The nat_congr tactic (and Ltac tactic defined in ssrnat) normalizes *)\n(*both sides of a nat equality to be able to use some congruence, here *)\n(*with count a1 s + _ *)\nnat_congr.\n(* We use it a second time to eliminate (count a2 s) *)\nnat_congr.\n(* Now it is only a matter of truth table *)\nby case (a1 x); case (a2 x).\nQed.\n\n(* After closing the section, tuto_count_filter has the type required *)\n(* by the exercise *)\nLemma tuto_count_filter : forall s, count a s = size (filter a s).\nProof. by elim=> [|x s IHs] //=; rewrite IHs; case (a x). Qed.\n\nEnd Exo_4_2_2.\n\n(******************************************************************************)\n(* Exercise 4.3.1                                                             *)\n(******************************************************************************)\n\nSection Exo_4_3_1.\n\n(* We fix an arbitrary eqType T *)\nVariable T : eqType.\n\n(* We use implicit type annotations to avoid casting quantified *)\n(*variables *)\nImplicit Types x y : T.\nImplicit Type b : bool.\n\nLemma tuto_eqxx : forall x, x == x.\nProof. by move=> x; apply/eqP. Qed.\n\n(* First solution *)\nLemma tuto_predU1l : forall x y b, x = y -> (x == y) || b.\nProof. by move=> x y b exy; rewrite exy eqxx. Qed.\n\n(* Second solution. The syntax move/eqP-> is equivalent to *)\n(*move/eqP => ->, i.e. it applies the view to the top element of the *)\n(*goal stack and rewrites the term obtains immediatly without *)\n(*introducing it in the context. Similarily, move-> is equaivalent to *)\n(*move=> -> and rewrite the top element of the goal (which should be *)\n(*an equality) in the rest of the goal, without introducing it in the context *)\n\nLemma tuto_predU1l_alt_proof : forall x y b, x = y -> (x == y) || b.\nProof. by move=> x y b; move/eqP->. Qed.\n\n(* The proof script is the same in both branches thanks to the *)\n(* symmetry of the view mechanism. Remeber the 'by' tactical contains *)\n(* the 'split' tactic and hence solves the goal after the last *)\n(* assumption interpretation move/eqP. *)\nLemma tuto_predD1P : forall x y b, reflect (x <> y /\\ b) ((x != y) && b).\nProof.\nby move=> x y b; apply: (iffP andP) => [] []; move/eqP.\nQed.\n\n(* Remember that _ != _ denotes the boolean disequality *)\n(* Coq's unification is able to infer from the goal the arguments to *)\n(* provide to the eqP lemma*)\nLemma tuto_eqVneq : forall x y, {x = y} + {x != y}.\nProof. by move=> x y; case: eqP; [left | right]. Qed.\n\nEnd Exo_4_3_1.", "meta": {"author": "math-comp", "repo": "tutorial_material", "sha": "3e5fcef3a25d2a43115fb645645b437640624ad3", "save_path": "github-repos/coq/math-comp-tutorial_material", "path": "github-repos/coq/math-comp-tutorial_material/tutorial_material-3e5fcef3a25d2a43115fb645645b437640624ad3/AnIntroductionToSmallScaleReflectionInCoq/section4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.9136765251766503, "lm_q1q2_score": 0.740515553002864}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural :=\n  plus (Succ lf2) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj141_coqofml_INEAi9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7405155519464506}}
{"text": "(* Two solutions are implemented, with n = nb of rectangles\n   (i.e., input size):\n   - [day03_1_simple.ml], naive O(grid_size * n)\n   - [day03_1.ml], O(n log(n))\n *)\n\nSet Warnings \"-extraction-opaque-accessed\".\n\nFrom Coq Require Import\n     List Arith NArith ZArith Ascii String\n     OrderedTypeEx FSetAVL FMapAVL\n     extraction.ExtrOcamlIntConv\n     Lia.\nImport ListNotations.\n\nFrom SimpleIO Require SimpleIO.\n\nFrom ExtLib Require Import\n     Structures.Monads.\nImport MonadNotation.\nLocal Open Scope monad.\n\nFrom advent Require Import lib.\n\n(* Sets indexed by natural numbers. *)\nModule NatSet := FSetAVL.Make Nat_as_OT.\n\n(* Maps indexed by (binary) natural numbers. *)\nModule NMap := FMapAVL.Make N_as_OT.\n\n\n(* A naive solution. *)\n\nVariant rectangle : Type :=\n| Rectangle (id : N) (left top width height : N)\n.\n\nDefinition matrix := list (list nat).\n\nDefinition rectangle_matrix (r : rectangle) : matrix :=\n  let '(Rectangle _ l t w h) := r in\n  let row := N.iter l (cons 0) (N.iter w (cons 1) []) in\n  N.iter t (cons []) (N.iter h (cons row) []).\n\nFixpoint union {A : Type}\n         (merge : A -> A -> A) (xs ys : list A) : list A :=\n  match xs, ys with\n  | [], _ => ys\n  | _, [] => xs\n  | x :: xs, y :: ys => merge x y :: union merge xs ys\n  end.\n\nDefinition union1 : list nat -> list nat -> list nat := union plus.\nDefinition union2 : matrix -> matrix -> matrix := union union1.\n\nDefinition union_rectangles (rs : list rectangle) : matrix :=\n  fold_left (fun x r => union2 x (rectangle_matrix r)) rs [].\n\nDefinition count_overlaps (x : matrix) : N :=\n  fold_left (fun p row =>\n    fold_left (fun p c => if 2 <=? c then (1 + p)%N else p) row p)\n    x 0%N.\n\n(* Then [fun rs : rectangle => count_overlaps (union_rectangles rs)]\n   computes the expected answer: the area of the plane covered by\n   at least two rectangles in [rs]. *)\n\n\n(* A less naive solution. *)\n\n(* First, there's a neat scanning algorithm bounding the complexity\n   by O(matrix_sz + n_rectangles) (with an extra log factor because\n   we don't have O(1) random access), but we can also avoid a boring\n   array iteration by only traversing rectangle corners.\n   We get O(n log(n)) where n = n_rectangles.\n *)\n\n(* The high-level idea is thus: put 1 and -1 on/near the corners of\n   a rectangle (i,j)×(a,b) as follows (the top row and leftmost\n   column are coordinate axes, every other entry in the matrix is 0):\n\n       i       j  j+1\n\n  a    1 0 ... 0  -1\n       0           0\n       .           .\n       .           .\n  b    0           0\n  b+1 -1 0 ... 0   1\n\n   then, 1. do a scan (cumulative sum) for each column,\n         2. do a scan for each row of the matrix resulting from 1,\n   that fills the rectangle with 1, and sets the rest of the\n   matrix to 0.\n\n       i       j  j+1\n  a    1 1 ... 1   0\n       .       .   .\n       .       .   .\n       .       .   .\n  b    1 1 ... 1   0\n  b+1  0   ... 0   0\n\n   this formula is linear, so that if you add multiple rectangles\n   in the same matrix, the scan will give you a matrix where each\n   entry says how many rectangles contain it.\n *)\n\n(* A sparse infinite matrix as a map [N -> N -> Z] ([N * N -> Z]),\n   where all unbound keys are mapped to 0. *)\nDefinition smatrix := NMap.t (NMap.t Z).\n\n(* Modify the entry at row [i], column [j]. *)\nDefinition set_point (f : Z -> Z) (i j : N) (x : smatrix) : smatrix :=\n  let '(row, u') :=\n      match NMap.find i x with\n      | None => (NMap.empty _, f 0%Z)\n      | Some row => (row, match NMap.find j row with\n                          | None => f 0%Z\n                          | Some u => f u\n                          end)\n      end in\n  NMap.add i (NMap.add j u' row) x.\n\n(* Print a rectangle into the matrix. *)\nDefinition add_rectangle (r : rectangle) (x : smatrix) : smatrix :=\n  let '(Rectangle _ l t w h) := r in\n  set_point Z.succ t l (\n  set_point Z.pred t (l + w) (\n  set_point Z.pred (t + h) l (\n  set_point Z.succ (t + h) (l + w) x))).\n\nDefinition sunion_rectangles (rs : list rectangle) : smatrix :=\n  fold_left (fun x r => add_rectangle r x) rs (NMap.empty _).\n\nDefinition Row : Type := list (N * Z).\n\nNotation conspair' i z t :=\n  (if (z =? 0)%Z then\n     t\n   else\n     (i, z%Z) :: t).\n\nFixpoint add_rows (r1 r2 : list (N * Z)) : list (N * Z) :=\n  match r1 with\n  | [] => r2\n  | (i1, z1) :: tl_r1 =>\n    let fix add_row2 r2 :=\n        match r2 with\n        | [] => r1\n        | (i2, z2) :: tl_r2 =>\n          match N_as_OT.compare i1 i2 with\n          | OrderedType.LT _ =>\n            conspair' i1 z1 (add_rows tl_r1 r2)\n          | OrderedType.EQ _ =>\n            let z' := (z1 + z2)%Z in\n            conspair' i1 z' (add_rows tl_r1 tl_r2)\n          | OrderedType.GT _ =>\n            conspair' i2 z2 (add_row2 tl_r2)\n          end\n        end in\n    add_row2 r2\n  end.\n\n(* Scan a row, looking for areas covered by overlapping rectangles\n   (z0 > 2). *)\nFixpoint scan_row_aux\n         (n : N) (i0 : N) (z0 : Z) (r : list (N * Z)) : N :=\n  match r with\n  | [] => n\n  | (i, z) :: r =>\n    let n' := if (2 <=? z0)%Z then (n + i - i0)%N else n in\n    scan_row_aux n' i (z0 + z)%Z r\n  end.\n\nDefinition scan_row : list (N * Z) -> N := scan_row_aux 0 0 0.\n\n(* 0         5         0\n   0 0 2 0 0-1 0 0 0 0 1-2 (row)\n   0 0 2 2 2 1 1 1 1 1 2 0 (scanned row) (four 2's)\n *)\n\nExample scan_row_ex :\n  scan_row [(2%N, 2%Z); (5%N, (-1)%Z); (10%N, 1%Z); (11%N, (-2)%Z)]\n  = 4%N.\nProof. reflexivity. Qed.\n\nFixpoint scan_aux\n         (n : N) (r0 : list (N * Z))\n         (rs : list (N * list (N * Z))) : N :=\n  match rs with\n  | (i1, r1) :: ((i2, _) :: _) as rs =>\n    let r1' := add_rows r0 r1 in\n    scan_aux (n + (i2 - i1) * scan_row r1') r1' rs\n  | [_] | [] => n (* The last row should be empty *)\n  end.\n\nDefinition scan : list (N * list (N * Z)) -> N := scan_aux 0 [].\n\nDefinition count_overlaps2 (rs : list rectangle) : N :=\n  scan (NMap.elements\n          (NMap.map (@NMap.elements _)\n                    (sunion_rectangles rs))).\n\n(* For debugging. *)\nSection debug.\n\nContext {m : Type -> Type} `{Monad m} `{MonadFix m}\n        `{MonadI rectangle m}\n        `{MonadO (list ascii) m}.\n\nDefinition print_matrix (x : matrix) : m unit :=\n  for' x (fun row =>\n    print (map (fun n =>\n      match n with\n      | 0 => \"0\"\n      | 1 => \"1\"\n      | 2 => \"2\"\n      | 3 => \"3\"\n      | 4 => \"4\"\n      | 5 => \"5\"\n      | _ => \"#\"\n      end%char) row)).\n\nDefinition show_matrix (w h : nat) : m unit :=\n  rs <- read_all;;\n  let x := fold_left\n             (fun m r => union2 m (rectangle_matrix r)) rs [] in\n  print_matrix (map (firstn w) (firstn h x)).\n\nEnd debug.\n\nSection main.\n\nContext {m : Type -> Type} `{Monad m} `{MonadFix m}\n        `{MonadI rectangle m}\n        `{MonadO N m}.\n\nDefinition main1 : m unit :=\n  rs <- read_all;;\n  print (count_overlaps (union_rectangles rs)).\n\nDefinition main2 : m unit :=\n  rs <- read_all;;\n  print (count_overlaps2 rs).\n\nEnd main.\n\nModule io.\n\nImport SimpleIO.\nImport IO.Notations.\n\nParameter parse_rectangle : ocaml_string -> int * int * int * int * int.\nExtract Constant parse_rectangle =>\n  \"fun s -> Scanf.sscanf s \"\"#%d @ %d,%d: %dx%d\"\"\n              (fun i l t w h -> (((i, l), t), w), h)\".\n\nInstance MonadI_rectangle_IO : MonadI rectangle IO := {\n  read := catch_eof (\n    s <- read_line';;\n    let '(i, l, t, w, h) := parse_rectangle s in\n    ret (Rectangle (n_of_int i) (n_of_int l) (n_of_int t) (n_of_int w) (n_of_int h)))\n}.\n\nEnd io.\n\nImport SimpleIO.\n\n(* DEBUG *)\n(*\nDefinition show_matrix_exec : io_unit := unsafe_run (show_matrix 0 0).\nExtraction \"day03_1_show_matrix.ml\" show_matrix_exec.\n*)\n\nDefinition exec1 : io_unit := IO.unsafe_run main1.\nExtraction \"day03_1_basic.ml\" exec1.\n\nDefinition exec2 : io_unit := IO.unsafe_run main2.\nExtraction \"day03_1.ml\" exec2.\n\n(* We first verify the naive solution. *)\n\n(* Points are given by their coordinates; shapes are sets of points. *)\nDefinition point : Type := nat * nat.\nDefinition shape : Type := point -> Prop.\nDefinition eq_shape (s1 s2 : shape) : Prop :=\n  forall p, s1 p <-> s2 p.\n\n(* And of course, rectangles are shapes. *)\nDefinition rectangle_shape (r : rectangle) : shape :=\n  let '(Rectangle _ l t w h) := r in\n  fun p => N.to_nat l <= fst p < N.to_nat l + N.to_nat w /\\\n           N.to_nat t <= snd p < N.to_nat t + N.to_nat h.\n\nLemma sumbool_right_de_morgan P Q R :\n  { P } + { ~ Q \\/ ~ R } -> { P } + { ~ (Q /\\ R) }.\nProof. firstorder. Qed.\n\nDefinition rectangle_shape_dec (r : rectangle) (p : point) :\n  {rectangle_shape r p} + {~ rectangle_shape r p}.\nProof.\n  destruct r; simpl.\n  repeat (apply sumbool_right_de_morgan; apply Sumbool.sumbool_and);\n    apply le_dec.\nQed.\n\nDefinition sum (xs : list nat) : nat :=\n  fold_left plus xs 0.\n\n(* This function counts the number of rectangles in a list [rs]\n   covering a given point [p]. *)\nDefinition count_covering_rectangles\n           (rs : list rectangle) (p : point) : nat :=\n  sum (map (fun r => if rectangle_shape_dec r p then 1 else 0) rs).\n\nDefinition matrix_ix (x : matrix) (p : point) : nat :=\n  nth (fst p) (nth (snd p) x []) 0.\n\n(* Matrices produced by [rectangle_points] define shapes too. *)\nDefinition matrix_shape (x : matrix) : shape :=\n  fun p => 0 < matrix_ix x p.\n\nLtac simpl_length :=\n  repeat rewrite repeat_length in *.\n\nLtac split_nth :=\n  match goal with\n  | [ |- context [nth ?x (app ?t1 ?t2)] ] =>\n    let Hx := fresh \"Hx\" in\n    destruct (Nat.lt_ge_cases x (List.length t1)) as [Hx | Hx];\n    [ rewrite app_nth1 with (n := x)\n    | rewrite app_nth2 with (n := x)\n    ]\n  | [ |- context [ nth ?m (repeat ?a ?n) ?b ]] =>\n    let Hl := fresh \"Hl\" in\n    destruct (Nat.lt_ge_cases m n) as [Hl | Hl];\n    [ rewrite (repeat_nth1 m n a b)\n    | rewrite (repeat_nth2 m n a b)\n    ]\n  | [ |- context [ nth ?m [] ?b ]] =>\n    rewrite nth_nil\n  end; auto; simpl_length.\n\nLemma rectangle_shape_matrix1 (r : rectangle) (p : point) :\n  rectangle_shape r p -> matrix_ix (rectangle_matrix r) p = 1.\nProof.\n  destruct r, p as [i j].\n  unfold matrix_ix; simpl.\n  repeat rewrite N2Nat.inj_iter.\n  repeat rewrite iter_cons.\n  intros [[Hleft Hwidth] [Htop Hheight]].\n  repeat\n    ((rewrite repeat_nth1 + rewrite app_nth2 + rewrite app_nth1);\n     simpl_length; [|lia]).\n    lia.\nQed.\n\nLemma rectangle_shape_matrix2 (r : rectangle) (p : point) :\n  ~rectangle_shape r p -> matrix_ix (rectangle_matrix r) p = 0.\nProof.\n  destruct r, p as [i j].\n  unfold matrix_ix; simpl.\n  repeat rewrite N2Nat.inj_iter.\n  repeat rewrite iter_cons.\n  intros H.\n  repeat split_nth.\n  exfalso; apply H; lia.\nQed.\n\n(* [matrix_ix] is a monoid homomorphism, between [union2] and [plus].\n *)\n\nLemma matrix_ix_hom x1 x2 p :\n  matrix_ix (union2 x1 x2) p = matrix_ix x1 p + matrix_ix x2 p.\nProof.\n  destruct p as [i j].\n  revert x1; revert x2.\n  revert i. unfold matrix_ix.\n  simpl.\n  induction j.\n  - destruct x1 as [ | t1 x1 ], x2 as [ | t2 x2];\n      repeat rewrite nth_nil; simpl; auto.\n    destruct i; auto.\n    clear. revert t2; revert t1.\n    induction i.\n    + destruct t1, t2; simpl; auto.\n    + destruct t1, t2; simpl; auto.\n  - destruct x1, x2; repeat rewrite nth_nil; simpl; auto.\n    destruct i; auto.\nQed.\n\nTheorem union_rectangles_count rs p :\n  matrix_ix (union_rectangles rs) p = count_covering_rectangles rs p.\nProof.\n  unfold union_rectangles.\n  pose proof\n       (fold_left_hom\n          (fun x r => union2 x (rectangle_matrix r))\n          (fun n r => n + if rectangle_shape_dec r p then 1 else 0)\n          (fun x => matrix_ix x p)).\n  simpl in H; rewrite H; clear H.\n  { rewrite fold_left_map. unfold count_covering_rectangles.\n    unfold matrix_ix; repeat rewrite nth_nil; auto.\n  }\n  { intros; rewrite matrix_ix_hom.\n    destruct rectangle_shape_dec.\n    - rewrite rectangle_shape_matrix1; auto.\n    - rewrite rectangle_shape_matrix2; auto.\n  }\nQed.\n", "meta": {"author": "Lysxia", "repo": "advent-of-coq-2018", "sha": "cbc4b260095544015f69ff39af1a71536e8daa51", "save_path": "github-repos/coq/Lysxia-advent-of-coq-2018", "path": "github-repos/coq/Lysxia-advent-of-coq-2018/advent-of-coq-2018-cbc4b260095544015f69ff39af1a71536e8daa51/sol/day03_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7405155498551722}}
{"text": "Require Import init.\n\nRequire Export nat_base.\nRequire Export nat_plus.\nRequire Export nat_order.\n\nRequire Import order_minmax.\n\nFixpoint nat_minus a b := match a, b with\n    | a', nat_zero => opt_val a'\n    | nat_zero, _ => opt_nil nat\n    | nat_suc a', nat_suc b' => nat_minus a' b'\n    end.\n\n(** This is \\bar *)\nInfix \"¯\" := nat_minus (at level 50) : nat_scope.\n\nOpen Scope nat_scope.\n\nTheorem nat_minus_eq : ∀ a, a ¯ a = opt_val 0.\nProof.\n    intros a.\n    nat_induction a.\n    -   unfold zero; cbn.\n        reflexivity.\n    -   cbn.\n        exact IHa.\nQed.\n\nTheorem nat_minus_zero : ∀ a, a ¯ 0 = opt_val a.\nProof.\n    intros a.\n    nat_destruct a.\n    -   apply nat_minus_eq.\n    -   unfold zero; cbn.\n        reflexivity.\nQed.\n\nTheorem nat_minus_lt : ∀ a b, a < b → a ¯ b = opt_nil nat.\nProof.\n    intros a b ltq.\n    apply nat_lt_ex in ltq as [c eq].\n    subst b.\n    rewrite nat_plus_rsuc.\n    nat_induction a.\n    -   unfold zero at 1; cbn.\n        reflexivity.\n    -   cbn.\n        rewrite nat_plus_lsuc.\n        exact IHa.\nQed.\n\nTheorem nat_minus_plus : ∀ a b, (a + b) ¯ a = opt_val b.\nProof.\n    intros a b.\n    nat_induction a.\n    -   rewrite plus_lid.\n        apply nat_minus_zero.\n    -   rewrite nat_plus_lsuc.\n        cbn.\n        exact IHa.\nQed.\n\nFixpoint nat_abs_minus a b := match a, b with\n    | a', nat_zero => a'\n    | nat_zero, b' => b'\n    | nat_suc a', nat_suc b' => nat_abs_minus a' b'\n    end.\n\nInfix \"⊖\" := (nat_abs_minus) (at level 50) : nat_scope.\n\nTheorem nat_abs_minus_eq : ∀ a, a ⊖ a = 0.\nProof.\n    intros a.\n    nat_induction a.\n    -   unfold zero; cbn.\n        reflexivity.\n    -   cbn.\n        exact IHa.\nQed.\n\nTheorem nat_abs_minus_lid : ∀ a, 0 ⊖ a = a.\nProof.\n    intros a.\n    destruct a; reflexivity.\nQed.\n\nTheorem nat_abs_minus_rid : ∀ a, a ⊖ 0 = a.\nProof.\n    intros a.\n    destruct a; reflexivity.\nQed.\n\nTheorem nat_abs_minus_comm : ∀ a b, a ⊖ b = b ⊖ a.\nProof.\n    intros a.\n    nat_induction a; intros b.\n    -   rewrite nat_abs_minus_lid, nat_abs_minus_rid.\n        reflexivity.\n    -   destruct b.\n        +   cbn.\n            reflexivity.\n        +   cbn.\n            apply IHa.\nQed.\n\nTheorem nat_abs_minus_plus : ∀ a b, (a + b) ⊖ a = b.\nProof.\n    intros a b.\n    nat_induction a.\n    -   rewrite plus_lid.\n        apply nat_abs_minus_rid.\n    -   rewrite nat_plus_lsuc.\n        cbn.\n        exact IHa.\nQed.\n\nTheorem nat_abs_minus_min : ∀ a b, a ⊖ b + min a b = max a b.\nProof.\n    intros a b.\n    unfold min, max; case_if [leq|leq].\n    -   apply nat_le_ex in leq as [c eq]; subst.\n        rewrite nat_abs_minus_comm.\n        rewrite nat_abs_minus_plus.\n        apply plus_comm.\n    -   rewrite nle_lt in leq.\n        apply nat_lt_ex in leq as [c eq]; subst.\n        rewrite nat_abs_minus_plus.\n        apply plus_comm.\nQed.\n\nTheorem nat_abs_minus_eq_zero : ∀ a b, 0 = a ⊖ b → a = b.\nProof.\n    nat_induction a; intros b eq.\n    -   rewrite nat_abs_minus_lid in eq.\n        exact eq.\n    -   nat_destruct b.\n        +   rewrite nat_abs_minus_rid in eq.\n            symmetry; exact eq.\n        +   cbn in eq.\n            rewrite (IHa b eq).\n            reflexivity.\nQed.\n\nClose Scope nat_scope.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Number/Nat/nat_minus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7405155475776956}}
{"text": "Require Import Program Arith String List.\nRequire Import Recdef.\nOpen Scope string_scope.\nOpen Scope list_scope.\n\nRequire Import PFDS.common.Util.\nRequire Import PFDS.common.DecidableOrder.\nRequire Import PFDS.common.Result.\n\nDeclare Module Seed : DecidableOrder.Seed.\nModule Elem := DecidableOrder.Make(Seed).\nImport Elem.Op.\n\n(**\n   ** 二項木(Binomial Tree)\n *)\n\n(**\n   二項木は以下のように帰納的に定義される (p.30)\n   - ランク [0] の二項木は 単一ノード\n   - ランク [r+1] の二項木 はランク [r]の２つの二項木を [link]して作られる、\n   このとき片方の木をもう片方の木の最左の子としてつなげる。\n *)\nInductive tree : Set :=\n| Node : nat -> Elem.T -> list tree -> tree.\n\nDefinition rank t :=\n  match t with\n  | Node r _ _ => r\n  end.\n\n(**\n   *** 二項木の具体例\n   二項木の具体例は以下の通り\n   - ランク [0] : [Tree 0 x []]\n   - ランク [1] : [Tree 1 y [(Tree 0 x [])]]\n   - ランク [2] : [Tree 2 z [(Tree 1 y [(Tree 0 x [])]); (Tree 0 p [])]]\n   (要素の数はランク[r]に従ってちょうど [2^r] 個となる)\n *)\n\n(**\n   *** [link] 関数の実装\n   リンクするのはランクの等しい木だけ。\n   引数の木は、上記の二項木の制約を満たすもののみを想定すれば良いっぽい。\n   できる木は必ず子要素がランクの昇順に並んでいるはず\n *)\nDefinition link t1 t2 :=\n  match (t1, t2) with\n  | (Node r x1 c1, Node _ x2 c2) =>\n    if Elem.leq_bool x1 x2 then\n      Node (r+1) x1 (t2 :: c1)\n    else\n      Node (r+1) x2 (t1 :: c2)\n  end.\n\nInductive BinomialTree : tree -> Prop :=\n| BT_O: forall x, BinomialTree (Node 0 x [])\n| BT_S: forall r t1 t2, BinomialTree t1 -> BinomialTree t2 -> rank t1 = r -> rank t2 = r -> BinomialTree (link t1 t2)\n.\n\n(**\n   ** 二項ヒープ(Binomial Heap)\n *)\n\n(**\n   二項木をランクに関して昇順に並べたリストとして二項ヒープを定義。\n   ランクが同じ二項木は存在しないものとする。\n *)\nDefinition heap := list tree.\n\n(*TODOソート済みと重複無しも\nDefinition BinomialHeap ts : Prop := List.Forall BinomialTree ts.\n*)\n\n(**\n   *** [insert] の実装\n   ヒープに[Elem.T]型の要素を１つだけ追加する[insert]関数の定義。(p.31)\n   [insert]は要素数1の二項木を追加するというアルゴリズムで実現する。\n *)\nFixpoint insTree t heap :=\n  match heap with\n  | [] => [t]\n  | t' :: ts =>\n    if (rank t <? rank t')%nat then\n      t :: ts\n    else\n      insTree(link t t') ts\n  end.\n\nDefinition insert x heap := insTree (Node 0 x []) heap.\n\n(**\n   *** [merge] の実装\n *)\nFunction merge ts1_ts2 {measure (pair_size (@List.length tree) (@List.length tree)) ts1_ts2} :=\n  match (ts1_ts2) with\n  | (ts1, []) => ts1\n  | ([], ts2) => ts2\n  | (t1 :: ts1' as ts1, t2 :: ts2' as ts2) =>\n    if (rank t1 <? rank t2)%nat then\n      t1 :: merge (ts1', ts2)\n    else if (rank t2 <? rank t1)%nat then\n      t2 :: merge (ts1, ts2')\n    else\n      insTree (link t1 t2) (merge (ts1', ts2'))\n  end.\nProof.\n  - simpl. now auto with arith.\n  - simpl. now auto with arith.\n  - simpl. now auto with arith.\nDefined.\n\n(**\n   *** [findMin], [deleteMin]の定義\n   *)\n\n(**\n   二項木から根っこの値をとる関数。この木の中に含まれる最小の値が取れるはず。\n *)\nDefinition root tree : Elem.T :=\n  let '(Node _ x _) := tree in x.\n\n(**\n   ヒープから最小のroot値を持つ木を抜き出して、その木と残ったヒープを組みで返す。\n   ヒープがからの場合を想定して[Result]型を返す\n   [map]と[fold]でもかける気がするが教科書に合わせて再帰で書いた。\n *)\nFixpoint removeMinTree (h: heap) : Result (tree * heap) :=\n  match h with\n  | [] => Error \"empty\"\n  | [t] => Ok (t, [])\n  | t :: ts =>\n    removeMinTree ts >>= fun t'_ts' =>\n    let '(t', ts') := t'_ts' in\n    if root t <=? root t' then\n      ret(t, ts)\n    else\n      ret(t', t::ts')\n  end.\n\n(**\n   ヒープに含まれる最小のElem.Tの値を返す\n *)\nDefinition findMin ts : Result(Elem.T) :=\n  removeMinTree ts >>= fun '(t, _) =>\n  Ok (root t).\n\n(**\n   二項木の子要素[ts1]は二項ヒープとなっているはずなので、mergeできる。\n *)\nDefinition deleteMin ts :=\n  removeMinTree ts >>= fun '(Node _ x ts1, ts2) =>\n  Ok (merge(List.rev ts1, ts2)).\n\n(**\n ** 演習問題3.5\n   [removeMinTree]の呼び出しを経由せず、findMinを直接的に定義してみよう\n *)\nDefinition findMin' ts :=\n  ts\n  |> map root\n  |> reduce Elem.min\n.\n\nLemma findMin'_correct_aux: forall t0 ts,\n    Ok (fold_right Elem.min (root t0) (map root ts)) =\n    (removeMinTree ((ts ++ [t0])%list) >>= fun '(tx, _) => Ok (root tx)).\nProof.\n induction ts.\n - now simpl.\n - simpl. revert IHts. case_eq (removeMinTree (ts ++ [t0])%list); [|discriminate].\n   intros s_ss. destruct s_ss as [s ss]. simpl. intros eq IH. injection IH. intros IH'.\n   destruct (Elem.leq_dec (root a) (root s)).\n   + rewrite IH'. rewrite (Elem.min_l _ _ l). now destruct (ts ++ [t0])%list; simpl.\n   + rewrite IH'. rewrite Elem.min_r; [| now apply Elem.Ord.lt_le_incl, Elem.Ord.not_le_lt].\n     now destruct (ts ++ [t0])%list; simpl.\nQed.\n\nTheorem findMin'_correct: forall ts,\n  findMin' ts = findMin ts.\nProof.\n destruct ts.\n - now auto.\n - unfold findMin, findMin', pipeline, reduce, reduce_right.\n   (* t::ts = us++[u] となるような us, uが存在する *)\n   cut (exists u us, t :: ts = (us ++ [u])%list).\n   + intros Exu. destruct Exu as [u Exus]. destruct Exus as [us eq]. rewrite eq at 2.\n     simpl. rewrite <- findMin'_correct_aux.\n     f_equal. apply Util.fold_right_cons_tail.\n     * apply Elem.min_assoc.\n     * apply Elem.min_comm.\n     * rewrite <- map_cons. rewrite eq. now rewrite map_app.\n   + destruct (@List.exists_last tree (t::ts)) as [us Exu]; [discriminate|].\n     destruct Exu as [u  eq]. now exists u, us.\nQed.\n\n(**\n ** 演習問題3.6\n\n    treeの代わりにheapでrankを持ったらどうなるかっていうこと\n\n    (treeのノードで持つ代わりに,heapの中で [(rank, tree)] のタプルリストみたいにして持つようにする。)\n<<\n    link: (rank * tree) -> (rank * tree) -> (rank * tree) のような型になる\n    insTree: (rank * tree) -> heap -> heap\n    merge : heap -> heap -> heap だから型は変わらない。\n>>\n    removeMinTree とか findMin とかはもうrank関係ないからこのままで。\n\n    link, insTree, insert, mergeの実装を修正すればよさそう\n *)\n\n\n(**\n ** 演習問題3.7\n\n    例えばinsertはScalaで次のような感じかな:\n<<\n    def insert (x: Elem.T, h: Heap) = {\n      h match {\n        case E => NE(x, H.singleton(x))\n        case NE(m, ih) =>\n          NE(min(m, x), H.insert(x, ih))\n      }\n    }\n>>\n    mergeなども同様にできそう。\n\n    `NE(x, ih)` で `ih`の中に `x` を含まない流派 (a.mutake派)と 含む派 (y.oshihiro503派) がある。(上記は含む派)\n *)\n\n(**\n ** 3.2節まとめ\n\n<<\ninsert : O(log n)\nmerge: O(log n)\nfindMin: O(log n)\ndeleteMin: O(log n)\n>>\n\nただし、ちょっとした拡張でfindMinはO(1)にできる (ExplicitMinファンクタ)\n *)\n", "meta": {"author": "yoshihiro503", "repo": "pfds_coq", "sha": "e7bf965ddeb329886210811e05f1bd4a1e7ccf53", "save_path": "github-repos/coq/yoshihiro503-pfds_coq", "path": "github-repos/coq/yoshihiro503-pfds_coq/pfds_coq-e7bf965ddeb329886210811e05f1bd4a1e7ccf53/3/BinomialHeap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758842, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7405030067881655}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Ralph Matthes [+]                              *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [*] Affiliation IRIT -- CNRS   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega Wellfounded Extraction.\n\nSet Implicit Arguments.\n\nSection llist.\n\n\n  (** An implementation of lazy lists as co-inductive lists/streams\n      with a finiteness predicate in Prop\n\n      Inspired by  G54DTP Dependently Typed Programming.\n                   Introduction to coinductive types.\n                   Venanzio Capretta, March 2011.\n  *)\n\n  Variable X : Type.\n\n  CoInductive llist : Type :=\n    | lnil: llist\n    | lcons: X -> llist -> llist.\n\n  Implicit Types (n: nat) (a: X) (ll: llist) (l: list X).\n\n  (* We must define an explicit unfold operation. *)\n\n  Definition lunfold ll : llist :=\n    match ll with\n      | lnil => lnil\n      | lcons a ll' => lcons a ll'\n    end.\n \n  (* The next function unfolds a lazy list several times:\n     the natural number n says how many.\n  *)\n\n  Fixpoint lunfold_many ll n : llist :=\n    match n with\n      | O    => ll\n      | S n => match ll with\n          | lnil      => lnil\n          | lcons a ll => lcons a (lunfold_many ll n)\n          end\n    end.\n\n  (* We can prove that the unfolding is equal to the original list. *)\n\n  Lemma lunfold_many_eq: forall n ll, ll = lunfold_many ll n.\n  Proof.\n    induction n as [ | n IHn ].\n    + reflexivity.\n    + intros [ | x ll ].\n      * reflexivity.\n      * simpl; f_equal; auto.\n  Qed.\n\n  (* Every finite list can be transformed into a lazy list. *)\n\n  Fixpoint list_llist l : llist :=\n    match l with\n      | nil  => lnil\n      | a::l => lcons a (list_llist l)\n    end.\n    \n  Fact list_llist_inj l1 l2 : list_llist l1 = list_llist l2 -> l1 = l2.\n  Proof.\n    revert l2; induction l1 as [ | x l IHl ]; intros [ | y m ]; auto; try discriminate.\n    simpl; intros H; inversion H; f_equal; auto.\n  Qed.\n    \n  Inductive lfin : llist -> Prop :=\n    | lfin_lnil :  lfin lnil\n    | lfin_lcons : forall a ll, lfin ll -> lfin (lcons a ll).\n    \n  Fact lfin_inv a ll : lfin (lcons a ll) -> lfin ll.\n  Proof. inversion 1; assumption. Defined.\n\n  Fact lfin_list_llist l : lfin (list_llist l).\n  Proof. induction l; simpl; constructor; trivial. Qed.\n\n  Section llist_list.\n\n    Let llist_list_rec : forall ll, lfin ll -> { l | ll = list_llist l }.\n    Proof.\n      refine (fix loop ll Hll { struct Hll } :=\n        match ll as ll' return lfin ll' -> { l | ll' = list_llist l } with\n          | lnil      => fun H => exist _ nil _\n          | lcons x ll => fun H => let (l',Hl') := loop ll _ in exist _ (x::l') _\n        end Hll); subst; trivial.\n      inversion H; trivial.\n    Qed.\n  \n    Definition llist_list ll Hll: list X := proj1_sig (@llist_list_rec ll Hll).\n  \n    Fact llist_list_spec ll Hll : ll = list_llist (@llist_list ll Hll).\n    Proof. apply (proj2_sig (@llist_list_rec ll Hll)). Qed.\n\n  End llist_list.\n  \n  Arguments llist_list : clear implicits.\n\n  Fact llist_list_eq ll (H1 H2: lfin ll) : @llist_list ll H1 = @llist_list ll H2.\n  Proof.\n    apply list_llist_inj; do 2 rewrite <- llist_list_spec; reflexivity.\n  Qed.\n\n  Fact llist_list_fix_0 H : llist_list lnil H = nil.\n  Proof.\n    generalize (llist_list_spec H); simpl.\n    generalize (llist_list _ H).\n    intros [|]; try discriminate; auto.\n  Qed.\n  \n  Fact llist_list_fix_1 x ll (H: lfin (lcons x ll)):\n    llist_list (lcons x ll) H = x::llist_list ll (lfin_inv H).\n  Proof.\n    generalize (llist_list_spec H); simpl.\n    generalize (llist_list _ H).\n    intros [|]; try discriminate.\n    simpl.\n    intros G; inversion G; f_equal; auto.\n    apply list_llist_inj; rewrite <- H2.\n    apply llist_list_spec.\n  Qed.\n\n  Definition lfin_length ll (Hll: lfin ll): nat := length (llist_list ll Hll).\n\n  Arguments lfin_length : clear implicits.\n\n  Fact lfin_length_eq ll (H1 H2: lfin ll) : lfin_length ll H1 = lfin_length ll H2.\n  Proof. unfold lfin_length; f_equal; apply llist_list_eq. Qed.\n  \n  Fact lfin_length_fix_0 (H: lfin lnil): lfin_length lnil H = 0.\n  Proof. unfold lfin_length; rewrite llist_list_fix_0; auto. Qed.\n  \n  Fact lfin_length_fix_1 x ll (H: lfin (lcons x ll)):\n    lfin_length (lcons x ll) H = S (lfin_length ll (lfin_inv H)).\n  Proof. unfold lfin_length; rewrite llist_list_fix_1; auto. Qed.\n  \nEnd llist.\n\nArguments lnil {X}.\nArguments llist_list {X}.\nArguments lfin_length {X}.\n\nSection Append.\n\n  Variable (X : Type).\n  \n  Implicit Type (l m k : llist X).\n\n  Section def.\n\n    Let llist_app_rec : forall l m (Hl : lfin l) (Hm : lfin m), { k | k = list_llist (llist_list _ Hl ++ llist_list _ Hm) }.\n    Proof.\n      refine (fix loop l m Hl Hm { struct Hl } := _).\n      revert Hl; refine (match l with \n        | lnil      => fun _  => exist _ m _\n        | lcons x l => fun Hl => let (r,Hr) := loop l m (lfin_inv Hl) Hm in exist _ (lcons x r) _\n      end).\n      + rewrite llist_list_fix_0; simpl; apply llist_list_spec.\n      + rewrite llist_list_fix_1; simpl; f_equal; assumption.\n    Qed.\n\n    Definition llist_app l m (Hl : lfin l) (Hm : lfin m): llist X := proj1_sig (@llist_app_rec l m Hl Hm).\n\n    Fact llist_app_spec l m (Hl : lfin l) (Hm : lfin m) : @llist_app l m Hl Hm = list_llist (llist_list _ Hl ++ llist_list _ Hm).\n    Proof. apply (proj2_sig (@llist_app_rec l m Hl Hm)). Qed.\n\n  End def.\n\n  Arguments llist_app : clear implicits.\n\nEnd Append.\n\nSection Rotate.\n\n  (* Rotate with lazy lists (with a non-informative \"finiteness\" predicate \n     It seems the algorithm manipulates f a as lazy lists and r as a list ... no sure\n     or three lazy lists ? *)\n\n  Variable (X : Type).\n  \n  Implicit Type (l r m a: llist X).\n  \n  Section def.\n\n\n    Let prec l (Hl : lfin l) r (Hr : lfin r) : Prop :=\n      lfin_length r Hr = 1 + lfin_length l Hl.\n    Let rspec l (Hl : lfin l) r (Hr : lfin r) a (Ha : lfin a) m: Prop :=\n      m = list_llist (llist_list l Hl ++ rev (llist_list r Hr) ++ llist_list a Ha).\n\n    (** the following definition aims at having as extracted code the function rot on p.587 in Okasaki, \n              Simple and efficient purely functional queues and deques, JFP 1995 *)\n\n    Let llist_rotate_rec : forall l r a (Hl : lfin l) (Hr : lfin r) (Ha : lfin a),\n        @prec l Hl r Hr -> sig (@rspec l Hl r Hr a Ha).\n    Proof.\n      refine (fix loop l r a Hl Hr Ha { struct Hl } := _). \n      revert Hr.\n      refine (match r as r' return forall (Hr : lfin r'), @prec l Hl _ Hr  -> sig (@rspec l Hl r' Hr a Ha) with\n        | lnil       => _\n        | lcons y r' => _ \n      end); intros Hr' H.\n      { exfalso; red in H; rewrite lfin_length_fix_0 in H; discriminate. }\n      revert Hl H.\n      refine (match l as l' return forall (Hl' : lfin l'), @prec l' Hl' _ Hr' -> sig (rspec Hl' Hr' Ha) with\n        | lnil       => _\n        | lcons x l' => _\n      end); intros Hl' H.\n      + exists (lcons y a).\n        red in H |- *; revert H.\n        rewrite llist_list_fix_0, llist_list_fix_1, lfin_length_fix_0, lfin_length_fix_1.\n        destruct r'.\n        * rewrite llist_list_fix_0; simpl. \n          rewrite <- llist_list_spec; reflexivity.\n        * rewrite lfin_length_fix_1; discriminate.\n      + refine (let (ro,Hro) := loop l' r' (lcons y a) (lfin_inv Hl') (lfin_inv Hr') (lfin_lcons _ Ha) _ in exist _ (lcons x ro) _).\n        * red in H |- *; revert H.\n          do 2 rewrite lfin_length_fix_1; intros; omega.\n        * red in Hro |- *; revert Hro.\n          do 3 rewrite llist_list_fix_1; intros; subst.\n          simpl; rewrite app_ass; simpl; reflexivity.\n    Qed.\n\n    Definition llist_rotate l r a Hl Hr Ha (H: prec Hl Hr): llist X := proj1_sig (@llist_rotate_rec l r a Hl Hr Ha H).\n\n    Fact llist_rotate_spec l r a Hl Hr Ha H : @rspec l Hl r Hr a Ha (@llist_rotate l r a Hl Hr Ha H).\n    Proof. apply (proj2_sig (@llist_rotate_rec l r a Hl Hr Ha H)). Qed.\n\n  End def.\n\n  Arguments llist_rotate : clear implicits.\n\n  Fact lfin_rotate l r a Hl Hr Ha H : lfin (llist_rotate l r a Hl Hr Ha H).\n  Proof.\n    generalize (llist_rotate_spec Ha H); intros E.\n    rewrite E; apply lfin_list_llist.\n  Qed.\n\n  Fact llist_rotate_eq l r a Hl Hr Ha H : llist_list _ (@lfin_rotate l r a Hl Hr Ha H) = llist_list l Hl ++ rev (llist_list r Hr) ++ llist_list a Ha.\n  Proof.\n    apply list_llist_inj.\n    rewrite <- (@llist_rotate_spec l r a Hl Hr Ha H).\n    generalize (llist_rotate l r a Hl Hr Ha H) (lfin_rotate Hl Hr Ha H).\n    symmetry; apply llist_list_spec.\n  Qed.\n\n  Fact llist_rotate_length l r a Hl Hr Ha H : lfin_length _ (@lfin_rotate l r a Hl Hr Ha H) = lfin_length _ Hl + lfin_length _ Hr + lfin_length _ Ha.\n  Proof.\n    unfold lfin_length.\n    rewrite llist_rotate_eq.\n    do 2 rewrite app_length.\n    rewrite rev_length; omega.\n  Qed.\n \nEnd Rotate.\n\n(* Recursive Extraction llist_list list_llist llist_app llist_rotate.\n\nCheck llist_rotate.\nCheck llist_rotate_spec.\n\n*)\n", "meta": {"author": "DmxLarchey", "repo": "Breadth-First-Numbering", "sha": "7f0fa3561968bef7f927d6bae4b1da6a67236762", "save_path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering", "path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering/Breadth-First-Numbering-7f0fa3561968bef7f927d6bae4b1da6a67236762/llist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7404988349839746}}
{"text": "Require Import Coq.Arith.Arith.\n\nDefinition Z := nat.\n\nDefinition Even (x : Z) := { y : Z & y + y = x }.\nDefinition Odd (x : Z) := { y : Z & S (y + y) = x }.\n\nDefinition Even_or_Odd : forall x, Even x + Odd x.\nProof.\n  induction x.\n  left.\n  exists 0.\n  reflexivity.\n  induction IHx.\n  right.\n  exists (projT1 a).\n  apply f_equal.\n  apply (projT2 a).\n  left.\n  exists (S (projT1 b)).\n  simpl.\n  apply f_equal.\n  induction (plus_n_Sm (projT1 b) (projT1 b)).\n  apply (projT2 b).\nDefined.\n\nDefinition even (n : nat) : Z := n + n.\nDefinition odd (n : nat) : Z := S (n + n).\n\nDefinition Zsplit' (P : Z -> Type)\n (e : forall n, P (even n)) (o : forall n, P (odd n)) (x : Z) : P x.\nProof.\n  destruct (Even_or_Odd x).\n  rewrite <- (projT2 e0).\n  apply (e (projT1 e0)).\n  rewrite <- (projT2 o0).\n  apply (o (projT1 o0)).\nDefined.\n\nDefinition zero := 0.\nDefinition pos (n : nat) : Z := S (S (n + n)).\nDefinition neg (n : nat) : Z := S (n + n).\n\nDefinition Zsplit (P : Z -> Type) (z : P 0)\n (p : forall n, P (pos n)) (n : forall n, P (neg n)) (x : Z) : P x.\nProof.\n  destruct x.\n  apply z.\n  apply (Zsplit' (fun x => P (S x))).\n  apply n.\n  apply p.\nDefined.\n\nDefinition Zsucc : Z -> Z :=\n  Zsplit (fun _ => Z) (pos 0) (fun x => pos (S x)) (fun y =>\n    match y with O => zero | S y => neg y end).\n\nDefinition Zpred : Z -> Z :=\n  Zsplit (fun _ => Z) (neg 0) (fun x =>\n    match x with O => zero | S x => pos x end) (fun y => neg (S y)).\n\nLemma pos_S n : pos (S n) = S (S (pos n)).\nProof.\n  unfold pos.\n  simpl.\n  apply f_equal.\n  apply f_equal.\n  apply f_equal.\n  symmetry.\n  apply plus_n_Sm.\nQed.\n\nDefinition lem : forall x y, x + x = y + y -> x = y.\nProof.\n  induction x.\n  simpl.\n  induction y.\n  reflexivity.\n  discriminate.\n  induction y.\n  discriminate.\n  simpl.\n  intros.\n  apply f_equal.\n  rewrite <- plus_n_Sm in H.\n  rewrite <- plus_n_Sm in H.\n  apply (f_equal pred) in H.\n  apply (f_equal pred) in H.\n  simpl in H.\n  apply IHx.\n  apply H.\nDefined.\n\nRequire Import Coq.Arith.Peano_dec.\n\nLemma lem2 : forall a b, S a = b + b -> b <> 0.\nProof.\n  intros.\n  intro.\n  rewrite H0 in H.\n  discriminate.\nQed.\n\nLemma neq_0_r : forall n : nat, n <> 0 -> { m : nat & n = S m }.\nProof.\n  intros.\n  induction n.\n  exfalso.\n  apply H.\n  reflexivity.\n  exists n.\n  reflexivity.\nQed.\n\nLemma even_is_not_odd x : Odd (even x) -> False.\nProof.\n  induction x.\n  intro.\n  destruct H.\n  discriminate.\n  intro.\n  destruct H.\n  apply (f_equal pred) in e.\n  simpl in e.\n  rewrite <- plus_n_Sm in e.\n  specialize (lem2 _ _ (eq_sym e)).\n  intro.\n  specialize (neq_0_r x0).\n  intro.\n  specialize (H0 H).\n  destruct H0.\n  rewrite e0 in e.\n  rewrite <- plus_n_Sm in e.\n  apply (f_equal pred) in e.\n  simpl in e.\n  apply IHx.\n  exists x1.\n  apply e.\nQed.\n\nLemma odd_is_not_even x : Even (odd x) -> False.\nProof.\n  intro.\n  induction x.\n  induction H.\n  unfold odd in p.\n  induction x.\n  discriminate.\n  rewrite <- plus_n_Sm in p.\n  discriminate.\n  unfold Even, odd in *.\n  induction H.\n  rewrite <- plus_n_Sm in p.\n  simpl in p.\n  specialize (lem2 _ _ (eq_sym p)).\n  specialize (neq_0_r x0).\n  intros.\n  specialize (H H0).\n  destruct H.\n  rewrite e in p.\n  simpl in p.\n  rewrite <- plus_n_Sm in p.\n  do 2 apply (f_equal pred) in p.\n  simpl in p.\n  apply IHx.\n  exists x1.\n  apply p.\nQed.\n\nLemma Zsplit'_beta_even : forall P e o x, Zsplit' P e o (even x) = e x.\nProof.\n  intros.\n  unfold Zsplit'.\n  destruct (Even_or_Odd (even x)).\n  destruct e0.\n  simpl.\n  specialize (lem _ _ e0).\n  intro.\n  induction H.\n  induction (UIP_nat _ _ eq_refl e0).\n  reflexivity.\n  exfalso.\n  apply (even_is_not_odd x).\n  apply o0.\nQed.\n\nLemma Zsplit'_beta_odd : forall P e o x, Zsplit' P e o (odd x) = o x.\nProof.\n  intros.\n  unfold Zsplit'.\n  destruct (Even_or_Odd (odd x)).\n  exfalso.\n  apply (odd_is_not_even x).\n  apply e0.\n  destruct o0.\n  simpl.\n  unfold odd in e0.\n  generalize e0.\n  apply (f_equal pred) in e0.\n  simpl in e0.\n  apply lem in e0.\n  destruct e0.\n  intro.\n  induction (UIP_nat _ _ eq_refl e0).\n  reflexivity.\nQed.\n\nLemma Zsplit_beta_pos : forall P z p n x, Zsplit P z p n (pos x) = p x.\nProof.\n  intros.\n  simpl.\n  apply (Zsplit'_beta_odd (fun x0 : Z => P (S x0)) n p x).\nQed.\n\nLemma Zsplit_beta_neg : forall P z p n x, Zsplit P z p n (neg x) = n x.\nProof.\n  intros.\n  simpl.\n  apply (Zsplit'_beta_even (fun x0 : Z => P (S x0)) n p x).\nQed.\n\nLemma Zsucc_pos_S n : Zsucc (pos n) = pos (S n).\nProof.\n  apply (Zsplit_beta_pos (fun _ : Z => Z) _ (fun x : nat => pos (S x)) _).\nQed.\n\nLemma Zpred_neg_S n : Zpred (neg n) = neg (S n).\nProof.\n  apply (Zsplit_beta_neg (fun _ : Z => Z) _ _ (fun y : nat => neg (S y))).\nQed.\n\nDefinition Zind (P : Z -> Type) (z : P 0) (s : forall n, P n -> P (Zsucc n))\n(p : forall n, P n -> P (Zpred n)) (n : Z) : P n.\nProof.\n  apply Zsplit.\n  apply z.\n  induction n0.\n  apply (s 0 z).\n  rewrite <- Zsucc_pos_S.\n  apply (s _ IHn0).\n  induction n0.\n  apply (p 0 z).\n  rewrite <- Zpred_neg_S.\n  apply (p _ IHn0).\nDefined.\n\nDefinition Zrec (P : Type) (z : P) (s : P -> P) (p : P -> P) : Z -> P :=\n  Zind (fun _ => P) z (fun _ => s) (fun _ => p).\n\nLemma Zrec_beta_succ (P : Type) (z : P) (s : P -> P) (p : P -> P) \n              (i2 : forall (m : P), m = s (p m)) (n : Z)\n: Zrec P z s p (Zsucc n) = s (Zrec P z s p n).\nProof.\n  apply (Zsplit (fun n => Zrec P z s p (Zsucc n) = s (Zrec P z s p n))).\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ 0).\n  reflexivity.\n  intro.\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  rewrite (Zsplit'_beta_odd _ _ _ (S n0)).\n  simpl.\n  destruct (Zsucc_pos_S n0).\n  simpl.\n  reflexivity.\n  intro.\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ n0).\n  rewrite (Zsplit'_beta_even _ _ _ n0).\n  simpl.\n  destruct n0.\n  simpl.\n  apply i2.\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ n0).\n  destruct (Zpred_neg_S n0).\n  simpl.\n  apply i2.\nQed.\n\nLemma Zrec_beta_pred (P : Type) (z : P) (s : P -> P) (p : P -> P) \n              (i1 : forall (m : P), m = p (s m)) (n : Z)\n: Zrec P z s p (Zpred n) = p (Zrec P z s p n).\nProof.\n  apply (Zsplit (fun n => Zrec P z s p (Zpred n) = p (Zrec P z s p n))).\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ 0).\n  reflexivity.\n  intro.\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  destruct n0.\n  simpl.\n  apply i1.\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  destruct (Zsucc_pos_S n0).\n  simpl.\n  apply i1.\n  intro.\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ n0).\n  rewrite (Zsplit'_beta_even _ _ _ n0).\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ (S n0)).\n  simpl.\n  destruct (Zpred_neg_S n0).\n  reflexivity.\nQed.\n\nDefinition Zplus x : Z -> Z :=\n  Zrec Z x Zsucc Zpred.\n\nLemma Zsucc_Zpred x : x = Zsucc (Zpred x).\nProof.\n  apply (Zsplit (fun x => x = Zsucc (Zpred x))).\n  reflexivity.\n  intros.\n  symmetry.\n  unfold Zpred.\n  rewrite Zsplit_beta_pos.\n  destruct n.\n  reflexivity.\n  apply Zsucc_pos_S.\n  unfold Zsucc.\n  intros.\n  symmetry.\n  unfold Zpred.\n  rewrite Zsplit_beta_neg.\n  apply (Zsplit_beta_neg (fun _ : Z => Z) _ _\n  (fun y : nat => match y with\n                  | 0 => zero\n                  | S y0 => neg y0\n                  end)).\nQed.\n\nLemma Zpred_Zsucc x : x = Zpred (Zsucc x).\nProof.\n  apply (Zsplit (fun x => x = Zpred (Zsucc x))).\n  reflexivity.\n  unfold Zsucc.\n  symmetry.\n  rewrite Zsplit_beta_pos.\n  unfold Zpred.\n  apply (Zsplit_beta_pos (fun _ : Z => Z) _\n  (fun x0 : nat => match x0 with\n                   | 0 => zero\n                   | S x1 => pos x1\n                   end) _).\n  symmetry.\n  unfold Zsucc.\n  rewrite Zsplit_beta_neg.\n  destruct n.\n  reflexivity.\n  apply Zpred_neg_S.\nQed.\n\nLemma Zplus_x_Sy (x y : Z) : Zplus x (Zsucc y) = Zsucc (Zplus x y).\nProof.\n  unfold Zplus.\n  apply Zrec_beta_succ.\n  apply Zsucc_Zpred.\nQed.\n\nLemma Zplus_x_Py (x y : Z) : Zplus x (Zpred y) = Zpred (Zplus x y).\nProof.\n  unfold Zplus.\n  apply Zrec_beta_pred.\n  apply Zpred_Zsucc.\nQed.\n\nLemma Zplus_0n : forall n, Zplus zero n = n.\nProof.\n  apply Zind.\n  reflexivity.\n  simpl.\n  intros.\n  rewrite Zplus_x_Sy.\n  apply f_equal.\n  apply H.\n  intros.\n  rewrite Zplus_x_Py.\n  apply f_equal.\n  apply H.\nQed.\n\nLemma Zplus_Sx_y (x y : Z) : Zplus (Zsucc x) y = Zsucc (Zplus x y).\nProof.\n  apply (Zind (fun y => Zplus (Zsucc x) y = Zsucc (Zplus x y))).\n  reflexivity.\n  intros.\n  rewrite Zplus_x_Sy.\n  rewrite Zplus_x_Sy.\n  apply f_equal.\n  apply H.\n  intros.\n  rewrite Zplus_x_Py.\n  rewrite Zplus_x_Py.\n  rewrite H.\n  rewrite <- Zpred_Zsucc.\n  apply Zsucc_Zpred.\nQed.\n\nLemma Zplus_Px_y (x y : Z) : Zplus (Zpred x) y = Zpred (Zplus x y).\nProof.\n  apply (Zind (fun y => Zplus (Zpred x) y = Zpred (Zplus x y))).\n  reflexivity.\n  intros.\n  rewrite Zplus_x_Sy.\n  rewrite Zplus_x_Sy.\n  rewrite H.\n  rewrite <- Zsucc_Zpred.\n  apply Zpred_Zsucc.\n  intros.\n  rewrite Zplus_x_Py.\n  rewrite Zplus_x_Py.\n  apply f_equal.\n  apply H.\nQed.\n\nLemma Zplus_comm : forall x y, Zplus x y = Zplus y x.\nProof.\n  intros.\n  apply (Zind (fun x => Zplus x y = Zplus y x)).\n  simpl.\n  apply Zplus_0n.\n  intros.\n  rewrite Zplus_x_Sy.\n  rewrite Zplus_Sx_y.\n  apply f_equal.\n  apply H.\n  intros.\n  rewrite Zplus_x_Py.\n  rewrite Zplus_Px_y.\n  apply f_equal.\n  apply H.\nQed.\n\nLemma Zplus_assoc : forall x y z, Zplus (Zplus x y) z = Zplus x (Zplus y z).\nProof.\n  intros.\n  apply (Zind (fun z => Zplus (Zplus x y) z = Zplus x (Zplus y z))).\n  reflexivity.\n  intros.\n  do 3 rewrite Zplus_x_Sy.\n  apply f_equal.\n  apply H.\n  intros.\n  do 3 rewrite Zplus_x_Py.\n  apply f_equal.\n  apply H.\nQed.\n\nDefinition Zneg : Z -> Z := Zsplit (fun _ => Z) zero neg pos.\n\nLemma Zneg_S n : Zneg (Zsucc n) = Zpred (Zneg n).\nProof.\n  apply (Zsplit (fun n => Zneg (Zsucc n) = Zpred (Zneg n))).\n  simpl.\n  apply (Zsplit'_beta_odd (fun _ : Z => Z) _ _ 0).\n  simpl.\n  intros.\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ (S n0)).\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ n0).\n  reflexivity.\n  simpl.\n  intros.\n  rewrite (Zsplit'_beta_even _ _ _ n0).\n  destruct n0.\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ 0).\n  reflexivity.\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ n0).\n  rewrite (Zsplit'_beta_even _ _ _ (S n0)).\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ (S n0)).\n  reflexivity.\nQed.\n\nLemma Zneg_P n : Zneg (Zpred n) = Zsucc (Zneg n).\nProof.\n  apply (Zsplit (fun n => Zneg (Zpred n) = Zsucc (Zneg n))).\n  reflexivity.\n  simpl.\n  intros.\n  do 2 rewrite (Zsplit'_beta_odd _ _ _ n0).\n  destruct n0.\n  reflexivity.\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  rewrite (Zsplit'_beta_even _ _ _ (S n0)).\n  reflexivity.\n  simpl.\n  intro.\n  do 2 rewrite (Zsplit'_beta_even _ _ _ n0).\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ (S n0)).\n  rewrite (Zsplit'_beta_odd _ _ _ n0).\n  reflexivity.\nQed.\n\nLemma Zplus_neg_x : forall x, Zplus (Zneg x) x = zero.\nProof.\n  intro.\n  apply (Zind (fun x => Zplus (Zneg x) x = zero)).\n  simpl.\n  reflexivity.\n  simpl.\n  intros.\n  rewrite Zplus_x_Sy.\n  rewrite Zneg_S.\n  rewrite Zplus_Px_y.\n  rewrite <- Zsucc_Zpred.\n  apply H.\n  intros.\n  rewrite Zplus_x_Py.\n  rewrite Zneg_P.\n  rewrite Zplus_Sx_y.\n  rewrite <- Zpred_Zsucc.\n  apply H.\nQed.\n\nLemma Zplus_x_neg : forall x, Zplus x (Zneg x) = zero.\nProof.\n  intro.\n  rewrite Zplus_comm.\n  apply Zplus_neg_x.\nQed.\n\nLemma Zneg_neg x : Zneg (Zneg x) = x.\nProof.\n  apply (Zsplit (fun x => Zneg (Zneg x) = x)).\n  reflexivity.\n  intro.\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ n).\n  simpl.\n  apply (Zsplit'_beta_even (fun _ => Z)).\n  intro.\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ n).\n  simpl.\n  apply (Zsplit'_beta_odd (fun _ => Z)).\nQed.\n\nDefinition Zmult (x : Z) : Z -> Z := Zrec Z zero (Zplus x) (Zplus (Zneg x)).\n\nInfix \"+\" := Zplus.\nInfix \"*\" := Zmult.\nNotation \"- x\" := (Zneg x).\n\nLemma Zmult_x_Sy x y : Zmult x (Zsucc y) = Zplus x (Zmult x y).\nProof.\n  unfold Zmult.\n  apply Zrec_beta_succ.\n  intro.\n  apply (Zind (fun x => m = Zplus x (Zplus (Zneg x) m))).\n  simpl.\n  symmetry.\n  rewrite Zplus_0n.\n  apply Zplus_0n.\n  intros.\n  rewrite Zplus_Sx_y.\n  rewrite Zneg_S.\n  rewrite Zplus_Px_y.\n  rewrite Zplus_x_Py.\n  rewrite <- Zsucc_Zpred.\n  apply H.\n  intros.\n  rewrite Zplus_Px_y.\n  rewrite Zneg_P.\n  rewrite Zplus_Sx_y.\n  rewrite Zplus_x_Sy.\n  rewrite <- Zpred_Zsucc.\n  apply H.\nQed.\n\nDefinition Zmult_x_Py x y : Zmult x (Zpred y) = Zplus (Zneg x) (Zmult x y).\nProof.\n  unfold Zmult.\n  apply Zrec_beta_pred.\n  intro.\n  apply (Zind (fun x => m = Zplus (Zneg x) (Zplus x m))).\n  simpl.\n  symmetry.\n  rewrite Zplus_0n.\n  apply Zplus_0n.\n  intros.\n  rewrite Zneg_S.\n  rewrite Zplus_Px_y.\n  rewrite Zplus_Sx_y.\n  rewrite Zplus_x_Sy.\n  rewrite <- Zpred_Zsucc.\n  apply H.\n  intros.\n  rewrite Zneg_P.\n  rewrite Zplus_Sx_y.\n  rewrite Zplus_Px_y.\n  rewrite Zplus_x_Py.\n  rewrite <- Zsucc_Zpred.\n  apply H.\nQed.\n\nLemma Zmult_0n n : Zmult 0 n = 0.\nProof.\n  apply (Zind (fun n => Zmult 0 n = 0)).\n  reflexivity.\n  intros.\n  rewrite Zmult_x_Sy.\n  rewrite Zplus_0n.\n  apply H.\n  intros.\n  rewrite Zmult_x_Py.\n  simpl.\n  rewrite Zplus_0n.\n  apply H.\nQed.\n\nLemma Zmult_1n n : Zmult (pos 0) n = n.\nProof.\n  apply (Zind (fun n => Zmult (pos 0) n = n)).\n  simpl.\n  reflexivity.\n  intros.\n  rewrite Zmult_x_Sy.\n  rewrite H.\n  rewrite Zplus_comm.\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ 0).\n  reflexivity.\n  intros.\n  rewrite Zmult_x_Py.\n  simpl.\n  rewrite (Zsplit'_beta_odd _ _ _ 0).\n  rewrite Zplus_comm.\n  simpl.\n  rewrite (Zsplit'_beta_even _ _ _ 0).\n  simpl.\n  apply f_equal.\n  apply H.\nQed.\n\nLemma Zmult_Sx_y x y : Zmult (Zsucc x) y = Zplus y (Zmult x y).\nProof.\n  intros.\n  apply (Zind (fun y => Zmult (Zsucc x) y = Zplus y (Zmult x y))).\n  reflexivity.\n  intros.\n  repeat rewrite Zmult_x_Sy.\n  repeat rewrite Zplus_Sx_y.\n  apply f_equal.\n  rewrite H.\n  rewrite <- Zplus_assoc.\n  replace (Zplus x n) with (Zplus n x).\n  apply Zplus_assoc.\n  apply Zplus_comm.\n  intros.\n  repeat rewrite Zmult_x_Py.\n  rewrite Zneg_S.\n  repeat rewrite Zplus_Px_y.\n  apply f_equal.\n  rewrite H.\n  rewrite <- Zplus_assoc.\n  replace (Zplus (- x) n) with (Zplus n (- x)).\n  apply Zplus_assoc.\n  apply Zplus_comm.\nQed.\n\nLemma Zmult_Px_y x y : Zmult (Zpred x) y = Zplus (Zneg y) (Zmult x y).\nProof.\n  apply (Zind (fun y => Zmult (Zpred x) y = Zplus (Zneg y) (Zmult x y))).\n  reflexivity.\n  intros.\n  repeat rewrite Zmult_x_Sy.\n  rewrite Zneg_S.\n  repeat rewrite Zplus_Px_y.\n  apply f_equal.\n  rewrite H.\n  rewrite <- Zplus_assoc.\n  replace (Zplus x (- n)) with (Zplus (- n) x).\n  apply Zplus_assoc.\n  apply Zplus_comm.\n  intros.\n  repeat rewrite Zmult_x_Py.\n  repeat rewrite Zneg_P.\n  repeat rewrite Zplus_Sx_y.\n  apply f_equal.\n  rewrite H.\n  rewrite <- Zplus_assoc.\n  replace (Zplus (- x) (- n)) with (Zplus (- n) (- x)).\n  apply Zplus_assoc.\n  apply Zplus_comm.\nQed.\n\nLemma Zmult_comm x y : Zmult x y = Zmult y x.\nProof.\n  apply (Zind (fun x => Zmult x y = Zmult y x)).\n  simpl.\n  apply Zmult_0n.\n  intros.\n  rewrite Zmult_Sx_y.\n  rewrite Zmult_x_Sy.\n  apply f_equal.\n  apply H.\n  intros.\n  rewrite Zmult_Px_y.\n  rewrite Zmult_x_Py.\n  apply f_equal.\n  apply H.\nQed.\n\nLemma Zmult_plus_distr_r x y z :\n Zmult (Zplus x y) z = Zplus (Zmult x z) (Zmult y z).\nProof.\n  apply (Zind (fun x => Zmult (Zplus x y) z = Zplus (Zmult x z) (Zmult y z))).\n  rewrite Zmult_0n.\n  rewrite Zplus_0n.\n  symmetry.\n  apply Zplus_0n.\n  intros.\n  rewrite Zplus_Sx_y.\n  repeat rewrite Zmult_Sx_y.\n  rewrite H.\n  symmetry.\n  apply Zplus_assoc.\n  intros.\n  rewrite Zplus_Px_y.\n  repeat rewrite Zmult_Px_y.\n  rewrite H.\n  symmetry.\n  apply Zplus_assoc.\nQed.\n\nLemma Zmult_plus_distr_l x y z :\nZmult x (Zplus y z) = Zplus (Zmult x y) (Zmult x z).\nProof.\n  rewrite Zmult_comm.\n  replace (Zmult x y) with (Zmult y x).\n  replace (Zmult x z) with (Zmult z x).\n  apply Zmult_plus_distr_r.\n  apply Zmult_comm.\n  apply Zmult_comm.\nQed.\n\nLemma Zplus_neg x y : Zplus (Zneg x) (Zneg y) = Zneg (Zplus x y).\nProof.\n  apply (Zind (fun y => Zplus (- x) (- y) = - Zplus x y)).\n  reflexivity.\n  intros.\n  rewrite Zneg_S.\n  rewrite Zplus_x_Py.\n  rewrite Zplus_x_Sy.\n  rewrite Zneg_S.\n  apply f_equal.\n  apply H.\n  intros.\n  rewrite Zneg_P.\n  rewrite Zplus_x_Sy.\n  rewrite Zplus_x_Py.\n  rewrite Zneg_P.\n  apply f_equal.\n  apply H.\nQed.\n\nLemma Zmult_neg_l x y : Zmult (Zneg x) y = Zneg (Zmult x y).\nProof.\n  apply (Zind (fun y => Zmult (- x) y = - Zmult x y)).\n  reflexivity.\n  intros.\n  rewrite Zmult_x_Sy.\n  rewrite Zmult_x_Sy.\n  rewrite H.\n  apply Zplus_neg.\n  intros.\n  repeat rewrite Zmult_x_Py.\n  rewrite H.\n  apply Zplus_neg.\nQed.\n\nLemma Zmult_neg_r x y : Zmult x (Zneg y) = Zneg (Zmult x y).\nProof.\n  rewrite Zmult_comm.\n  rewrite Zmult_neg_l.\n  apply f_equal.\n  apply Zmult_comm.\nQed.\n\nLemma Zmult_assoc x y z : Zmult (Zmult x y) z = Zmult x (Zmult y z).\nProof.\n  apply (Zind (fun z => Zmult (Zmult x y) z = Zmult x (Zmult y z))).\n  reflexivity.\n  intros.\n  repeat rewrite Zmult_x_Sy.\n  rewrite H.\n  symmetry.\n  apply Zmult_plus_distr_l.\n  intros.\n  repeat rewrite Zmult_x_Py.\n  rewrite H.\n  rewrite Zmult_plus_distr_l.\n  rewrite Zmult_neg_r.\n  reflexivity.\nQed.", "meta": {"author": "juu0374", "repo": "coq-sandbox", "sha": "2fc1390563e2b5b01555464776cc0740f1920c92", "save_path": "github-repos/coq/juu0374-coq-sandbox", "path": "github-repos/coq/juu0374-coq-sandbox/coq-sandbox-2fc1390563e2b5b01555464776cc0740f1920c92/nat_is_Z.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.7404988302749539}}
{"text": "(* énoncé identique à TD03_nat_Exp.v, avec\n  - suppression des entraînements sur les listes et sur nat\n  - une correction de get\n  - des tests devant fonctionner sur eval\n  - renomme, decale, bexp à faire \n  *)\n\n(**\nDeux objectifs dans ce TD :\n- deux structures linéaires qui serviront constamment,\n  les listes et les entiers naturels,\n  et les pricipes de récurrence associés\n- extensions des expressions arithmétiques\n*)\n\n(** * Entiers naturels *)\n\n(** En mathématiques, les entiers ne sont plus une notion primitive depuis\n    les travaux de Dedekind et Peano au 19e siècle : ils sont obtenus\n    à partir de deux constructions élémentaires :\n    - l'entier nul, que l'on notera O ;\n    - le successeur d'un entier [n] déjà construit, que l'on notera [S n].\n    C'est exactement ce que l'on obtient avec le type inductif suivant.\n*)\n\nPrint nat.\n\nFact deux : 2 = S (S O).\nProof. (** regarder le but écrit par Coq *) reflexivity. Qed.\n\n(** * Quelques commandes de recherche d'information *)\n\n(** Quelle est la fonction qui est derrière le symbole \"+\" ? *)\nLocate \"+\".\n(**  Print est connu *)\nPrint Nat.add.\n(** Intégration de l'espace de nommage Nat *)\nImport Nat.\nLocate \"+\".\n(* Quelles fonctions de type [nat -> nat -> nat] sot disponibles ? *)\nSearch (nat -> nat -> nat).\n\n(** * AST d'expressions arithmétiques, le retour *)\n\n(** On considère des expressions arithmétiques comprenant\n    non seulement des opération et des constantes, mais aussi des noms\n    de variables.\n    Pour simplifier on considère que ces variables s'écriraient \"x0\", \"x1\",\n    \"x2\", etc., ce qui permet de les représenter par un simple entier naturel.\n    Noter que les constructeurs [Ana] et [Ava] permettent de distinguer\n    la constante 2 de la variable x2.\n*)\n\nInductive aexp :=\n| Aco : nat -> aexp (* constantes *)\n| Ava : nat -> aexp (* variables *)\n| Apl : aexp -> aexp -> aexp\n| Amu : aexp -> aexp -> aexp\n| Amo : aexp -> aexp -> aexp\n.\n\n(* Définir les expressions aexp correspondant à\n  (1 + x2) * 3 et  (x0 * 2) + x3\n *)\n\nDefinition exp_1 := Amu (Apl (Aco 1) (Ava 2)) (Aco 3).\nDefinition exp_2 := Apl (Amu (Ava 0) (Aco 2)) (Ava 3).\n\n(** Pour évaluer une expression représentée par un tel AST,\n    on considère un *état*, c'est à dire une association entre\n    chaque nom de variable et un valeur dans [nat].\n    On choisit de représenter un tel état par une liste d'entiers,\n    avec comme convention :\n    - le premier élément de cette liste est la valeur associée à x0\n    - le second élément de cette liste est la valeur associée à x1\n    - et ainsi de suite ;\n    - pour les noms restants, la valeur associée est 0.\n    Par exemple, dans l'état Cons 3 (Cons 0 (Cons 8 Nil)),\n    la valeur associée à x0 est 3, la valeur associée à x1 est 0,\n    la valeur associée à x2 est 8, et la valeur associée à x3, x4, etc.\n    est 0.\n *)\n\nInductive state :=\n  | Nil : state\n  | Cons : nat -> state -> state\n.\n\nDefinition s_ex1 : state := Cons 3 (Cons 0 (Cons 8 Nil)).\n\n(* ----------------------------------------------------------------------- *)\n(** Définition d'une fonction [get] qui rend la valeur associée à xi dans l'état s *)\n\nFixpoint get (i: nat) (s: state) : nat :=\n  match s with\n  | Nil => 0\n  | Cons v s' => \n    match i with\n    | O => v\n    | S i' => get i' s'\n    end\n  end.\n\nExample get_ex1 : get 2 s_ex1 = 8.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------------- *)\n\n(** Définir une fonction [eval] qui rend la valeur d'une aexp dans l'état s *)\n\n(** Même si la fonction get ci-dessus a été laissée 'Admitted\", elle est \n    utilisable dans les questions suivantes.  *)\n\nFixpoint eval (a: aexp) (s: state) : nat :=\n  match a with\n  | Ava n => get n s\n  | Aco n => n\n  | Apl n x => (eval n s) + (eval x s)\n  | Amu n x => (eval n s) * (eval x s)\n  | Amo n x => (eval n s) - (eval x s)\n  end.\n\nDefinition aexp_ex1 := Amu (Apl (Aco 1) (Ava 2)) (Aco 3).\nDefinition aexp_ex2 := Apl (Amu (Ava 0) (Aco 2)) (Ava 3).\n\nExample eval_ex1_ex1 : eval aexp_ex1 s_ex1 = 27.\nProof. reflexivity. Qed. \nExample eval_ex2_ex1 : eval aexp_ex2 s_ex1 = 6.\nProof. reflexivity. Qed.\n\n\n(* ----------------------------------------------------------------------- *)\n\n(** Définir une fonction [renomme] qui prend une aexp [a] et rend [a] où\n    les variables correspondant à x0, x1, x2... ont été respectivement\n    renommées en x1, x2, x3...  *)\n\nFixpoint renomme (a: aexp) : aexp :=\n  match a with\n  | Ava n => Ava (S n)\n  | Aco n => Aco n\n  | Apl n x => Apl (renomme n) (renomme x)\n  | Amu n x => Amu (renomme n) (renomme x)\n  | Amo n x => Amo (renomme n) (renomme x)\n  end.               \n  \n\n(** Définir une fonction [decale] qui prend un état [s] et rend\n    l'état dans lequel la valeur de x0 est 0, \n    la valeur de x1 est la valeur de x0 dans [s],\n    la valeur de x2 est la valeur de x1 dans [s], \n    la valeur de x3 est la valeur de x2 dans [s], etc. \n    Indication : ce n'est PAS un Fixpoint *)\n\nDefinition decale (s : state) : state := Cons 0 s.\n\n(** Démontrer qu'évaluer une expression renommée dans un environnement\n    décalé rend la même chose qu'avant *)\n\nExample ex_dec_ren: eval (renomme aexp_ex1) (decale s_ex1) = eval aexp_ex1 s_ex1.\nProof. reflexivity. Qed.\n\nTheorem dec_ren: forall a s, eval (renomme a) (decale s) = eval a s.\nProof.\n  intros a s.\n  induction a.\n  - reflexivity. \n  - reflexivity.\n  - cbn [renomme]. cbn [eval]. rewrite IHa1. rewrite IHa2. reflexivity.\n  - cbn [renomme]. cbn [eval]. rewrite IHa1. rewrite IHa2. reflexivity.\n  - cbn [renomme]. cbn [eval]. rewrite IHa1. rewrite IHa2. reflexivity.\n    Qed.\n(* ----------------------------------------------------------------------- *)\n(** ** Expressions booléennes *)\n\n(** Définir un type d'AST nommé bexp pour des expressions booléennes\n    comprenant :\n    - les constantes booléennes Btrue et Bfalse\n    - un opérateur booléen unaire Bnot\n    - des opérateurs booléens binaires Band et Bor\n    - un opérateur de comparaison représentant le test d'égalité\n      entre deux expressions arithmétiques\n *)\n\nInductive bexp :=\n| Btrue : bexp\n| Bfalse : bexp\n| Bnot : bexp -> bexp\n| Band : bexp -> bexp -> bexp\n| Bor : bexp -> bexp -> bexp\n| Beq : bexp -> bexp -> bexp\n| Bcomp : aexp -> aexp -> bexp\n.\n\n\n(** L'environnenent initial de Coq comprend, en plus de [nat],\n    un type énuméré nommé [bool à deux valeurs nommées [true] et [false] \n    ainsi que des fonctions telles que la disjonction entre deux valeurs\n    de type [bool].\n    Vous pouvez découvrir tout cela au moyen de la commande \"Print bool\"\n    et de la commande Search indiquée ci-dessus, mais on vous demande de \n    reprogrammer les fonctions booléennes par vous-même en utilisant, comme \n    pour [coulfeu], match with suivant le schéma :\n\n      match blabla_booléen with\n      | true => ...\n      | false => ...\n      end\n\n    L'opération de comparaison entre deux entiers devra aussi être programmée.\n\n    Définir une fonction d'évaluation sur bexp en s'appuyant sur ces fonctions.\n *)\n\nPrint bool.\nSearch bool.\n\n\nDefinition b_neg (a: bool) : bool :=\n  match a with\n  | true =>  false\n  | false => true\n  end.\n\nDefinition b_and (a: bool) (b:bool) : bool :=\n  match (a,b) with\n  | (true, true) => true\n  | _ => false\n  end.\n\nDefinition b_or (a:bool) (b:bool) : bool :=\n  match (a,b) with\n  | (false, false) => false\n  | _ => true\n  end.\n\nDefinition b_eq (a:bool) (b:bool) : bool :=\n  match (a,b) with\n  | (true, true) => true\n  | (false, false) => true\n  | _ => false\n  end.\n\nFixpoint n_eq (a: nat) (b: nat) : bool :=\n  match (a,b) with\n  | (0,0) => true\n  | (S n1, S n2) => n_eq n1 n2\n  | (_, _) => false\n  end.\n\nFixpoint beval (b: bexp) (s: state) : bool :=\n  match b with\n  | Btrue => true\n  | Bfalse => false\n  | Bnot a => b_neg (beval a s) \n  | Band a1 a2 => b_and (beval a1 s) (beval a2 s)\n  | Bor a1 a2 => b_or (beval a1 s) (beval a2 s)\n  | Beq a1 a2 => b_eq (beval a1 s) (beval a2 s)\n  | Bcomp ae1 ae2 => n_eq (eval ae1 s) (eval ae2 s)\nend.\n\n\n\n\n(* ----------------------------------------------------------------------- *)\n", "meta": {"author": "jamilelleite", "repo": "LT-INFO4", "sha": "b06dcaf65b0e48f75db80f11b2495ba5b3eb4e4f", "save_path": "github-repos/coq/jamilelleite-LT-INFO4", "path": "github-repos/coq/jamilelleite-LT-INFO4/LT-INFO4-b06dcaf65b0e48f75db80f11b2495ba5b3eb4e4f/TD03_2/TD03_nat_Exp_2e_rendu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7404988194363435}}
{"text": "Require Import Arith.\n\nParameters (prime_divisor : nat -> nat)\n           (prime : nat -> Prop)\n           (divides : nat -> nat -> Prop).\n\nOpen Scope nat_scope.\n\n\nCheck (prime (prime_divisor 220)).\nCheck (divides (prime_divisor 220) 20).\n\nCheck (divides 3).\n\nParameter binary_word : nat -> Set.\n\nDefinition short : Set := binary_word 32.\nDefinition long : Set := binary_word 64.\n\n(* I have a hard time understanding the difference between Prop and Set.\nI currently have the sense that Prop is the sort used for logic. While Set is the sort\nused for programs.\nWhich, would mean that \"not\" could not be applied to Set. Which makes sense:\nwhat's the negation of a program?\n*)\n\nCheck not.\n\nCheck (let d := prime_divisor 220 in prime d /\\ divides d 220).\n\nRequire Import List.\n\nParameters (decomp1 : nat -> list nat)\n           (decomp2 : nat -> nat*nat).\n\nCheck (decomp1 220).\nCheck list nat.\nCheck (decomp2 2123).\n\n(* OK. The type of pair is A*B while the term of pairs uses the \"standard\" notation\n(A,B). *)\nCheck (4,2).\n\n(* I guess prod is the non infix operator version of *? but only on the type level? *)\nCheck prod.\nCheck (prod nat nat).\n\n(* How can I check what the * type operator is then? *)\n\nCheck pair.\nCheck (pair 4 3).\nCheck (pair 4 3 : prod nat nat).\n\nCheck le_n.\nCheck le_S.\nCheck (le_n 36).\nDefinition le_36_37 := le_S 36 36 (le_n 36).\nCheck le_36_37.\nDefinition le_36_38 := le_S 36 37 le_36_37.\nCheck le_36_38.\nCheck (le_S _ _ (le_S _ _ (le_n 36))).\n\nParameter iterate : forall A:Set, (A->A) -> nat -> A -> A.\nCheck (iterate nat).\nCheck (iterate _ (mult 2)).\n\n(* twice if a function that applies a function twice to a given value.\nWe have to explicitly account for the application of the type to the function.\n *)\n\nDefinition twice : forall A:Set, (A->A) -> A -> A\n  := fun A f a => f (f a).\n\nCheck mult.\nCheck (mult 2).\nCheck (twice nat (mult 2)).\n\nEval compute in\n    (twice nat (mult 2) 2).\nEval compute in\n    (twice _ (twice _ (mult 2)) 2).\nEval compute in\n    (twice (nat->nat) (fun f x => f (f x)) (mult 3) 1).\n\nTheorem le_i_SSi : forall i : nat, i <= S (S i).\n  Proof (fun i:nat => le_S _ _ (le_S _ _ (le_n i))).\n\nDefinition compose : forall A B C : Set, (A->B) -> (B->C) -> A -> C\n  := fun A B C f g x => g (f x).\n\nPrint compose.\n\nRequire Import ZArith.\n\nCheck (fun (A:Set) (f: Z-> A) => compose _ _ _ Z_of_nat f).\n\nCheck (compose _ _ _ Zabs_nat (plus 32) (-45)%Z).\n\nEval compute in\n    (compose _ _ _ Zabs_nat (plus 32) (-45)%Z).\n\nCheck (le_i_SSi 1515).\n\nCheck (le_S _ _ (le_i_SSi 1515)).\n\n(* The book claims that this will fail. In the version of Coq I'm using, 8.4, the\njoker is replaced by an existential variable. At least that's what I think is happening\nI'm not entirely sure...\n*)\nCheck (iterate _ (fun x => x) 23).\n\n(* With at least Coq 8.4 the implicit argument system is much improved IMO.\nImplicit arguments can be defined a priori by surrounding the arguments with curly\nbrackets. The book was written when this was the standard method:\n\nImplicit Arguments compose [A B C].\n\nWhich is an posteriori method. With at least coq 8.4 there is a new posteriori method.\nThis method better matches the a priori method of curly brackets IMO.\n*)\nArguments compose {A B C} f g x.\nCheck (compose Zabs_nat (plus 34)).\n\nEval compute in\n    (compose Zabs_nat (plus 34) 223%Z).\n\n(* how nice! *)\n\nCheck (compose (C := Z) S).\n\n(* The follow also works with coq 8.4 but inserts an existential variable *)\nCheck (compose S).\n\n(* I wonder how to use these existential variables? *)\n\n(* Lets try with.. *)\nReset compose.\nSet Implicit Arguments.\n\nDefinition compose (A B C : Set) (f : A -> B) (g : B -> C) (a:A) := g (f a).\nDefinition thrice (A:Set) (f:A->A) := compose f (compose f f ).\nUnset Implicit Arguments.\n\nPrint compose.\n\n(* Ah neat! The print tells me which arguments are implicit!.\nLets try using the curly bracket method.\n*)\nReset compose.\nDefinition compose {A B C} (f : A->B) (g : B->C) (a:A) := g (f a).\nPrint compose.\n\n(* Well, that was almost the same but A B C are \"maximally inserted\".\nI presume this means that the types are the upper bounds of the inferred sort?\nDoes the Arguments square brackets for implicit arguments which are not maximally\ninserted work as well?\n*)\nReset compose.\n(* nope! The following does not compile.\nDefinition compose [A B C] (f : A->B) (g : B->C) (a:A) := g (f a).\n*)\n\nDefinition compose {A B C : Set} (f : A->B) (g : B->C) (a:A) := g (f a).\nPrint compose.\n\n(* Well, that was the same as before when I didn't specify : Set *)\n\n(* Strange... I've already imported ZArith. I had to import ZArith again. Perhaps\ndue to the previous Reset?\n*)\nRequire Import ZArith.\nCheck (list Z). (* sort Set *)\n\nSection A_declared.\n  Variables (A:Set)(P Q:A -> Prop)(R:A->A->Prop).\n\n  Theorem all_perm : (forall a b :A, R a b) -> forall a b:A, R b a.\n    intro.\n    exact (fun a b : A => H b a).\n  Qed.\n\n  Theorem all_imp_dist : (forall a:A, P a -> Q a) -> (forall a:A, P a) -> forall a:A, Q a.\n    intros H0 H1.\n    exact (fun a : A => H0 a (H1 a)).\n  Qed.\n\n  Theorem all_delta : (forall a b:A, R a b) -> (forall a:A, R a a).\n    intros H0.\n    exact (fun a : A => H0 a a).\n  Qed.\nEnd A_declared.\n\nDefinition my_plus : nat->nat->nat := iterate nat S.\nEval compute in (my_plus 3 4).\n\n(* We never defined iterate. Just declared it. So Eval resulted in\n\"iterate nat S 3 4\"\nwhich is as good as we can do with just a declaration.\nNeat!\n*)\n\nDefinition my_mult (n p:nat) : nat := iterate nat (my_plus n) p 0.\nEval compute in (my_mult 3 4).\n\nDefinition my_expo (x n:nat) : nat := iterate nat (my_mult x) n 1.\n\nDefinition ackermann (n:nat) : nat -> nat :=\n  iterate (nat -> nat)\n          (fun (f:nat -> nat) (p:nat) => iterate nat f (S p) 1)\n          n\n          S.\n\n(* Well, now I do some strange stuff. I want to check that a term when interpreted as a proposition\nhas a given type.\nSo I define the term. Then check that the term as a proposition has a type.\nThen I prove the term can be inhabited.\nThis is weird, but hey, it works. I'm sure there is a better way.\n*)\nSection Exercise_4_4.\n  Definition id := forall A:Set, A -> A.\n  Check (id -> Prop) : Type.\n  Theorem id_spec : id.\n  Proof.\n    unfold id.\n    intros.\n    apply H.\n  Qed.\n\n  Print id_spec.\n\n  Definition diag := forall A B:Set, (A->A->B)->A->B.\n\n  Check (diag -> Prop) : Type.\n\n  Theorem diag_spec : diag.\n  Proof.\n    unfold diag.\n    exact (fun (A B : Set) (f : A->A->B) A => f A A).\n  Qed.\n\n\n  Definition permute := forall A B C:Set, (A->B->C)->B->A->C.\n  Check (permute -> Prop) : Type.\n\n  Theorem permute_spec : permute.\n  Proof.\n    unfold permute.\n    exact (fun (A B C:Set) (f : A->B->C) B A => f A B).\n  Qed.\n\n  Print permute_spec.\n\nEnd Exercise_4_4.\n\nCheck (forall P:Prop, P->P).\nCheck (fun (P:Prop) (p:P) => p).\n\nSection Exercise_4_5.\n  Definition all_perm_def := forall (A:Type) (P:A->A->Prop), (forall x y:A, P x y)\n                                                             -> forall x y:A, P y x.\n\n  Theorem all_perm_4_5 : all_perm_def.\n  Proof.\n    unfold all_perm_def.\n    intros H_A H_P H_0.\n    exact (fun (x y:H_A) => H_0 y x).\n  Qed.\n\n  Print all_perm_4_5.\n  \n  Definition resolution_def :=\n    forall (A:Type) (P Q R S:A -> Prop), (forall a:A, Q a -> R a -> S a)\n                                           -> (forall b:A, P b -> Q b)\n                                                -> (forall c:A, P c -> R c -> S c).\n\n  Theorem resolution_4_5 : resolution_def.\n  Proof.\n    unfold resolution_def.\n    intros.\n    apply H.\n    apply H0.\n    assumption.\n    assumption.\n  Qed.\n\n  Print resolution_4_5.\nEnd Exercise_4_5.\n\n\nTheorem thirty_six : 9*4=6*6.\n  apply (refl_equal 36).\nQed.\n\nPrint thirty_six.\n\n", "meta": {"author": "coreyoconnor", "repo": "learn-coq", "sha": "b7fbafcd65ad948e10d5fdd3571e6ecdb8a1d268", "save_path": "github-repos/coq/coreyoconnor-learn-coq", "path": "github-repos/coq/coreyoconnor-learn-coq/learn-coq-b7fbafcd65ad948e10d5fdd3571e6ecdb8a1d268/dependent_products_chap_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7404889645809682}}
{"text": "Require Import SfLib.\nRequire Import Maps.\nRequire Import Types.\nRequire Import STLCWA.\n\nModule SubTest.\n\nInductive ty : Type :=\n    | TNat : ty\n    | TTop : ty \n    | TProd : ty -> ty -> ty\n    | TArrow : ty -> ty -> ty.\n\nReserved Notation \"x '<:' y\" (at level 40).\n\nInductive subtype_of : ty -> ty -> Prop :=\n    | refl_sub : forall x, x <: x\n    | trans_sub : forall x y z,\n                        x <: y ->\n                        y <: z ->\n                        x <: z\n    | prod_sub : forall x x' y y',\n                    x <: x' ->\n                    y <: y' ->\n                    (TProd x y) <: (TProd x' y')\n    | arrow_sub : forall x x' y y',\n                    x' <: x ->\n                    y <: y' ->\n                    (TArrow x y) <: (TArrow x' y')\n    | sub_top : forall x,\n                    x <: TTop\n    where \"x '<:' y \" := (subtype_of x y).\n\nHint Constructors subtype_of.\n\nParameter (S T U V A B C: ty).\n\nParameter (Rule1 : S <: T) (Rule2 : U <: V).\n\nHint Resolve Rule1 Rule2 : example_database1.\n\nExample\n    ex1_1:\n        TArrow S T <: TArrow S T.\n    eauto.\n\nQed.\n\nExample ex1_2 :\n        TArrow TTop U <: TArrow S TTop.\n\n    eauto.\nQed.\n\nExample ex1_3 :\n        TArrow (TArrow C C) (TProd A B) <: TArrow (TArrow C C) (TProd TTop B).\n        eauto.\nQed.\n\nExample ex1_4 :\n        TArrow T (TArrow T U) <: TArrow S (TArrow S V).\n        eauto with example_database1.\nQed.\n\nTheorem subtype_dec :\n    forall A B,\n        {A <: B} + {~ A <: B}.\n\n    intro A; induction A; intro B; induction B; eauto.\n    destruct IHB1; destruct IHB2.\n    right; intro. inversion H; subst. inversion H0; subst.\nAbort.\n\n(* I think this definition has some problem. Because it's not decidable. *)\n\nExample ex1_5:\n    ~TArrow (TArrow T T) U <: TArrow (TArrow S S) V.\n\n    Abort.\n\nExample ex1_6:\n    TArrow (TArrow (TArrow T S) T) U <:\n    TArrow (TArrow (TArrow S T) S) V.\n    eauto with example_database1.\nQed.\n\nExample ex1_7:\n    ~TProd S V <: TProd T U.\n    Abort.\n\nParameter (Student Person : ty).\nParameter (Rule3 : Student <: Person).\n\nHint Resolve Rule3 : example1_database.\nExample ex2:\n        (TArrow TTop Student) <:\n        (TArrow Person Student) /\\\n        (TArrow Person Student) <:\n        (TArrow Student Person) /\\\n        (TArrow Student Person) <:\n        (TArrow Student TTop) /\\\n        (TArrow Student TTop) <:\n        TTop.\n        repeat (split; eauto with example1_database).\nQed.\n\nExample ex3:\n    ~(forall S T,\n        S <: T ->\n        (TArrow S S) <: (TArrow T T)).\nAdmitted. \n\nExample ex3_2:\n    ~(forall S,\n        S <: (TArrow A A) ->\n        exists T,\n            S = TArrow T T /\\ T <: A).\nAdmitted.\n\n\nExample ex3_3:\n    forall S T1 T2,\n        (S <: TArrow T1 T2) ->\n        exists S1 S2,\n            S = TArrow S1 S2 /\\\n            T1 <: S1 /\\\n            S2 <: T2.\n\n    intros S T1 T2 h.\n    remember S as s.\n    remember (TArrow T1 T2) as q.\n    generalize Heqs. induction h; subst.\n    eauto.\n\n    intros.\n    Abort.\n\nExample ex3_4:\n    ~(exists S,\n        S <: (TArrow S S)).\nAdmitted.\n\n\nExample ex3_5:\n    exists S,\n        (TArrow S S) <: S.\n    exists TTop; eauto.\nQed.\n\nExample ex3_6:\n    forall S T1 T2,\n        S <: (TProd T1 T2) ->\n        exists S1 S2,\n            S = (TProd S1 S2) /\\\n            S1 <: T1 /\\\n            S2 <: T2.\nAdmitted.\n\n(** **** Exercise: 2 stars (small_large_4)  *)\n(**\n   - What is the _smallest_ type [T] that makes the following\n     assertion true?\n       exists S,\n         empty |- (\\p:(A*T). (p.snd) (p.fst)) : S\n   ?????\n   - What is the _largest_ type [T] that makes the same\n     assertion true?\n   ?????\n[] *)\n\n(** **** Exercise: 2 stars (smallest_1)  *)\n(** What is the _smallest_ type [T] that makes the following\n    assertion true?\n      exists S, exists t,\n        empty |- (\\x:T. x x) t : S\n    ?????\n]]\n[] *)\n\n(** **** Exercise: 3 stars, optional (count_supertypes)  *)\n(** How many supertypes does the record type [{x:A, y:C->C}] have?  That is,\n    how many different types [T] are there such that [{x:A, y:C->C} <:\n    T]?  (We consider two types to be different if they are written\n    differently, even if each is a subtype of the other.  For example,\n    [{x:A,y:B}] and [{y:B,x:A}] are different.) *)\n\n\nEnd SubTest.\n", "meta": {"author": "DKXXXL", "repo": "SoftwareFoundations-AfterCh15", "sha": "f9fbacb555970fdf42dd834f29c4a6289d5acb59", "save_path": "github-repos/coq/DKXXXL-SoftwareFoundations-AfterCh15", "path": "github-repos/coq/DKXXXL-SoftwareFoundations-AfterCh15/SoftwareFoundations-AfterCh15-f9fbacb555970fdf42dd834f29c4a6289d5acb59/Sub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7404889535774194}}
{"text": "Require Import QArith.\n\n(** ##############################################################################\nQARITH LEMMAS \n################################################################################*)\n\nLemma Qplus_neg: forall a b, a - b == a + (-b).\nProof.\n  intros.\n  ring.\nQed.\n\nLemma Qplus_opp_l : forall q, -q + q == 0.\nProof. intros; ring. Qed.\n\n\nLemma Qdiv_mult_inv: forall a b, a / b == a * /b.\nProof.\n  intros.\n  auto with qarith.\nQed.\n\nLemma Qmult_neg_1: forall a, a * -(1) == -a.\nProof.\n  intros.\n  ring.\nQed.\n\nLemma Qmult_inv_l: forall a, ~ a == 0 -> /a * a == 1.\nProof.\n  intros.\n  rewrite Qmult_comm.\n  rewrite Qmult_inv_r; auto with qarith.\nQed.\n\nLemma Qplus_double: forall a, a + a == (2 # 1)*a.\nProof.\n  intros.\n  ring.\nQed.\n\nLemma Qplus_half: forall a, a/(2#1) + a/(2#1) == a.\nProof.\n  intros.\n  rewrite Qplus_double.\n  rewrite Qmult_div_r; [|unfold Qeq]; auto with qarith.\nQed.\n\nLemma Qneg_0: - 0 == 0.\nProof.\n  ring.\nQed.\n\nLemma Qeq_neg : forall a b, - a == b <-> a == -b.\nProof.\n  intros.\n  split; intros; \n    rewrite <- Qmult_neg_1;\n    apply Qmult_inj_r with (z:=-(1)); auto with qarith;\n    rewrite !Qmult_neg_1, Qopp_opp; trivial.\nQed.\n\nLemma Qdiv_neg_l: forall a b, (-a)/b == -(a/b).\nProof.\n  intros.\n  rewrite Qdiv_mult_inv.\n  rewrite <- Qmult_neg_1.\n  rewrite <- Qmult_assoc.\n  rewrite Qmult_comm.\n  rewrite <- Qmult_assoc.\n  rewrite Qmult_comm.\n  rewrite Qmult_neg_1.\n  rewrite Qmult_comm.\n  rewrite Qdiv_mult_inv.\n  reflexivity.\nQed.\n\nLemma Qmult_neg_l: forall a b, (-a)*b == -(a*b).\nProof.\n  intros *.\n  rewrite <- Qmult_neg_1, Qmult_comm, Qmult_assoc, Qmult_neg_1, Qmult_comm.\n  reflexivity.\nQed.\n\nLemma Qopp_lt_compat : forall p q, p<q -> -q < -p.\nProof.\n  intros (a1,a2) (b1,b2); unfold Qlt; simpl.\n  rewrite !Z.mul_opp_l. omega.\nQed.\n\nLemma Qlt_0_neg_lt_not_r: forall a, 0 < -a -> ~ 0 < a.\nProof.\n  intros.\n  intuition.\n  apply Qopp_lt_compat in H0.\n  rewrite Qneg_0 in H0.\n  apply Qlt_trans with (x:=0) (y:=-a) (z:=0) in H; trivial.\n  apply Qlt_irrefl in H as G.\n  contradiction.\nQed.\n\nLemma Qlt_0_pos_lt_not_l: forall a, a < 0 -> ~ -a < 0.\nProof.\n  intros.\n  intuition.\n  apply Qopp_lt_compat in H0.\n  rewrite Qneg_0 in H0.\n  rewrite Qopp_opp in H0.\n  apply Qlt_trans with (x:=0) (y:=a) (z:=0) in H; trivial.\n  apply Qlt_irrefl in H as G.\n  contradiction.\nQed.\n\nLemma Qlt_0_neg_lt_not_l: forall a, -a < 0 -> ~ a < 0.\nProof.\n  intros.\n  intuition.\n  apply Qopp_lt_compat in H0.\n  rewrite Qneg_0 in H0.\n  apply Qlt_trans with (x:=0) (y:=-a) (z:=0) in H; trivial.\n  apply Qlt_irrefl in H as G.\n  contradiction.\nQed.\n\nLemma Qlt_not_lt: forall a b, a < b -> ~ b < a.\nProof.\n  intros.\n  auto with qarith.\nQed.\n\n\nLemma Qmult_lt_0 : forall a b, b > 0 -> a * b < 0 <-> a < 0.\nProof.\n  intros * Hb.\n  split; intros H.\n  {\n    apply Qmult_lt_r with (z:=/b) in H.\n    - rewrite <- !Qdiv_mult_inv, Qdiv_mult_l in H; auto with qarith.\n      rewrite Qdiv_mult_inv, Qmult_0_l in H; trivial.\n    - apply Qinv_lt_0_compat; trivial.\n  }\n  apply Qmult_lt_r with (z:=/b).\n  - apply Qinv_lt_0_compat; trivial.\n  - rewrite <- !Qdiv_mult_inv, Qdiv_mult_l; auto with qarith.\n    rewrite Qdiv_mult_inv, Qmult_0_l; trivial.\nQed.\n\nLemma Qmult_0_lt : forall a b, b > 0 -> a * b > 0 <-> a > 0.\nProof.\n  intros * Hb.\n  split; intros H.\n  {\n    apply Qmult_lt_r with (z:=/b) in H.\n    - rewrite <- !Qdiv_mult_inv, Qdiv_mult_l in H; auto with qarith.\n      rewrite Qdiv_mult_inv, Qmult_0_l in H; trivial.\n    - apply Qinv_lt_0_compat; trivial.\n  }\n  apply Qmult_lt_r with (z:=/b).\n  - apply Qinv_lt_0_compat; trivial.\n  - rewrite <- !Qdiv_mult_inv, Qdiv_mult_l; auto with qarith.\n    rewrite Qdiv_mult_inv, Qmult_0_l; trivial.\nQed.\n\nLemma Qmult_eq_0_l : forall a b, b > 0 -> a * b == 0 <-> a == 0.\nProof.\n  intros * Hb.\n  split; intros H.\n  {\n    apply Qmult_inj_r with (z:=b); auto with qarith.\n    rewrite Qmult_0_l; trivial.\n  }\n  apply Qmult_inj_r with (z:=b) in H; auto with qarith.\n  rewrite Qmult_0_l in H; trivial.\nQed.\n\n\nLemma Qeq_by_elim : forall a, ~ a < 0 -> ~ 0 < a -> a == 0.\nProof.\n  intros.\n  destruct (Q_dec (a) 0) as [[? | ?] | ?]; try contradiction.\n  trivial.\nQed.\n\nLemma Qeq_0_by_eq_neg : forall a b, - a == b -> a == b -> a == 0.\nProof.\n  intros * Hn He.\n  rewrite He in Hn.\n  destruct (Q_dec (b) 0) as [[C | C] | C].\n  - apply Qlt_not_lt in C as C0.\n    rewrite <- Hn in C.\n    apply Qlt_0_neg_lt_not_l in C.\n    apply Qeq_by_elim in C; trivial.\n    rewrite <- He in C; trivial.\n  - apply Qlt_not_lt in C as C0.\n    rewrite <- Hn in C.\n    apply Qlt_0_neg_lt_not_r in C.\n    apply Qeq_by_elim in C; trivial.\n    rewrite <- He in C; trivial.\n  - rewrite <- He in C; trivial.\nQed.\n\nLemma Qplus_l_equ_sub_r: forall a b c, a + b == c <-> a == c - b.\nProof.\n  intros.\n  split; intros H.\n  - rewrite <- Qplus_inj_r with (x:=a) (y:=c-b) (z:=b).\n    rewrite Qplus_neg.\n    rewrite <- Qplus_assoc with (x:=c) (y:=-b) (z:= b).\n    rewrite Qplus_opp_l.\n    rewrite Qplus_0_r.\n    exact H.\n  - rewrite <- Qplus_inj_r with (x:=a+b) (y:=c) (z:=-b).\n    rewrite <- Qplus_assoc with (x:=a) (y:=b) (z:=-b).\n    rewrite Qplus_opp_r.\n    rewrite Qplus_0_r.\n    rewrite <- Qplus_neg.\n    exact H.\nQed.\n\nLemma Qplus_l_equ_sub_l: forall a b c, a + b == c <-> b == c - a.\nProof.\n  intros.\n  split; intros H.\n  - apply Qplus_l_equ_sub_r.\n    rewrite Qplus_comm.\n    exact H.\n  - apply Qplus_l_equ_sub_r in H.\n    rewrite Qplus_comm in H.\n    exact H.\nQed.\n\nLemma Qplus_r_equ_sub_r: forall a b c, c == a + b <-> c - b == a.\nProof.\n  intros.\n  split; intros H; apply Qeq_sym; apply Qeq_sym in H; apply Qplus_l_equ_sub_r; exact H.\nQed.\n\nLemma Qplus_r_equ_sub_l: forall a b c, c == a + b <-> c - a == b.\nProof.\n  intros.\n  split; intros H; apply Qeq_sym; apply Qeq_sym in H; apply Qplus_l_equ_sub_l; exact H.\nQed.\n\n\nLemma Qplus_l_lt_sub_r: forall a b c, a + b < c <-> a < c - b.\nProof.\n  intros.\n  split; intros H.\n  - apply Qplus_lt_le_compat with (z:=-b) (t:=-b) in H; auto with qarith.\n    rewrite <- Qplus_assoc in H.\n    rewrite Qplus_opp_r in H.\n    rewrite Qplus_0_r in H.\n    rewrite Qplus_neg.\n    assumption.\n  - apply Qplus_lt_le_compat with (z:=b) (t:=b) in H; auto with qarith.\n    rewrite Qplus_neg in H.\n    rewrite <- Qplus_assoc in H.\n    rewrite Qplus_opp_l in H.\n    rewrite Qplus_0_r in H.\n    assumption.\nQed.\n\nLemma Qplus_l_lt_sub_l: forall a b c, a + b < c <-> b < c - a.\nProof.\n  intros.\n  split; intros H.\n  - apply Qplus_l_lt_sub_r.\n    rewrite Qplus_comm.\n    exact H.\n  - apply Qplus_l_lt_sub_r in H.\n    rewrite Qplus_comm in H.\n    exact H.\nQed.\n\n\nLemma Qlt_r_sub_le_weak_l : forall a a' b c, c < a - b -> a <= a' -> c < a' - b.\nProof.\n  intros * H H0.\n  apply Qplus_le_compat with (z:=-b) (t:=-b) in H0; auto with qarith.\n  rewrite <- !Qplus_neg in H0.\n  apply Qlt_le_trans with (y:=a - b); trivial.\nQed.\n\nLemma Qlt_l_plus_le_weak_l: forall a a' b c, a + b < c -> a' <= a -> a' + b < c.\nProof.\n  intros * H H0.\n  apply Qplus_le_compat with (z:=b) (t:=b) in H0; auto with qarith.\n  apply Qle_lt_trans with (z:=c) in H0; trivial.\nQed.\n\nLemma Qlt_l_plus_le_weak_r: forall a b b' c, a + b < c -> b' <= b -> a + b' < c.\nProof.\n  intros * H H0.\n  rewrite Qplus_comm.\n  apply Qlt_l_plus_le_weak_l with (a:=b); trivial.\n  rewrite Qplus_comm; trivial.\nQed.\n\n\nLemma Qlt_r_plus_le_weak_l: forall a a' b c, c < a + b -> a <= a' -> c < a' + b.\nProof.\n  intros * H H0.\n  apply Qplus_le_compat with (z:=b) (t:=b) in H0; auto with qarith.\n  apply Qlt_le_trans with (z:=a'+b) in H; trivial.\nQed.\n\nLemma Qlt_r_plus_le_weak_r: forall a b b' c, c < a + b -> b <= b' -> c < a + b'.\nProof.\n  intros * H H0.\n  rewrite Qplus_comm.\n  apply Qlt_r_plus_le_weak_l with (a:=b); [rewrite Qplus_comm|]; trivial.\nQed.\n\n\nLemma Qplus_neg_half_l: forall a, -a + a/(2#1) == -(a/(2#1)).\nProof.\n  intros.\n  rewrite Qplus_l_equ_sub_r.\n  rewrite Qplus_neg.\n  apply Qeq_sym.\n  rewrite <- Qdiv_neg_l.\n  rewrite Qplus_half.\n  reflexivity.\nQed.\n\n\nLemma Qmult_l_equ_div_r: forall a b c, ~ b == 0 -> a * b == c <-> a == c/b.\nProof.\n  intros * Hb.\n  split; intros H.\n  - rewrite <- Qmult_inj_r with (x:=a) (y:=c/b) (z:=b); trivial.\n    rewrite Qmult_comm with (x:=c/b).\n    rewrite Qmult_div_r; trivial.\n  - rewrite <- Qmult_inj_r with (x:=a) (y:=c/b) (z:=b) in H; trivial.\n    rewrite Qmult_comm with (x:=c/b) in H.\n    rewrite Qmult_div_r in H; trivial.\nQed.\n\n\nLemma Qdiv_inj: forall a b c, ~ c == 0 -> a == b <-> a/c == b/c.\nProof.\n  intros * Hc.\n  split; intros Heq.\n  - rewrite <- Qmult_inj_l with (z:=c); [rewrite Qmult_div_r; [rewrite Qmult_div_r|]|]; trivial.\n  - rewrite <- Qmult_inj_l with (z:=c) in Heq; [rewrite Qmult_div_r in Heq; [rewrite Qmult_div_r in Heq|]|]; trivial.\nQed.\n\n\nLemma Qmult_dist_div: forall a b c, c * (a / b) == ((c*a)/b).\nProof.\n  intros.\n  apply Qeq_sym.\n  rewrite Qdiv_mult_inv.\n  rewrite <- Qmult_assoc.\n  rewrite <- Qdiv_mult_inv.\n  reflexivity.\nQed.\n\nLemma Qsquare: forall a, a ^ 2 == a * a.\nProof.\n  intros.\n  auto with qarith.\nQed.\n\nLemma Qdiv_squared: forall a b, (a / b) ^ 2 == (a*a)/(b*b).\nProof.\n  intros.\n  rewrite Qsquare.\n  rewrite Qdiv_mult_inv.\n  rewrite Qmult_assoc.\n  rewrite <- Qmult_assoc with (n:=a) (m:=/b) (p:=a).\n  rewrite Qmult_comm with (x:=/b) (y:=a).\n  rewrite Qmult_assoc with (n:=a) (m:=a) (p:=/b).\n  rewrite <- Qmult_assoc.\n  rewrite <- Qinv_mult_distr.\n  reflexivity.\nQed.\n\nLemma Qdiv_dist_mult: forall a b, a / b  == /(/a*b).\nProof.\n  intros.\n  rewrite Qinv_mult_distr.\n  rewrite Qinv_involutive.\n  rewrite Qdiv_mult_inv.\n  reflexivity.\nQed.\n\nLemma Qdiv_div: forall a b c, a / b / c == a/(b*c).\nProof.\n  intros.\n  rewrite Qdiv_mult_inv.\n  rewrite Qdiv_mult_inv.\n  rewrite <- Qmult_assoc.\n  rewrite <- Qinv_mult_distr.\n  rewrite <- Qdiv_mult_inv.\n  reflexivity.\nQed.\n\nLemma Qpoly2_sub_dist: forall a b, (a - b)*(a - b) == a*a - (2#1)*a*b + b*b.\nProof. intros. ring. Qed.\n\n\n\nLemma Qmult_sum2_dist_l: forall a b c, c*(a + b) == a*c + b*c.\nProof. intros. ring. Qed.\n\nLemma Qmult_sum2_dist_r: forall a b c, (a + b)*c == a*c + b*c.\nProof. intros. ring. Qed.\n\nLemma Qmult_sub2_dist_l: forall a b c, c*(a - b) == a*c - b*c.\nProof. intros. ring. Qed.\n\nLemma Qmult_sub2_dist_r: forall a b c, (a - b)*c == a*c - b*c.\nProof. intros. ring. Qed.\n\nLemma Qdiv_sum2_dist_r: forall a b c, (a + b)/c == a/c + b/c.\nProof.\n  intros.\n  rewrite Qdiv_mult_inv.\n  rewrite Qmult_sum2_dist_r.\n  rewrite <- Qdiv_mult_inv.\n  rewrite <- Qdiv_mult_inv.\n  reflexivity.\nQed.\n\nLemma Qdiv_diff2_dist_r: forall a b c, (a - b)/c == a/c - b/c.\nProof.\n  intros.\n  rewrite Qplus_neg.\n  rewrite Qplus_neg.\n  rewrite Qdiv_sum2_dist_r.\n  rewrite Qdiv_neg_l.\n  reflexivity.\nQed.\n\n\nLemma Qmult_sum3_dist_r: forall a b c d, (a + b + c)*d == a*d + b*d + c*d.\nProof. intros. ring. Qed.\n\nLemma Qmult_sub_sum3_dist_r: forall a b c d, (a - b + c)*d == a*d - b*d + c*d.\nProof. intros. ring. Qed.\n\nLemma Qdiv_sub_sum3_dist_r: forall a b c d, (a - b + c)/d == a/d - b/d + c/d.\nProof.\n  intros.\n  rewrite Qdiv_mult_inv.\n  rewrite Qmult_sub_sum3_dist_r.\n  rewrite <- Qdiv_mult_inv.\n  rewrite <- Qdiv_mult_inv.\n  rewrite <- Qdiv_mult_inv.\n  reflexivity.\nQed.\n\nLemma Qdiv_mult3_cancel_1: forall a b c, ~ a == 0 -> (a*b*c)/a == b*c.\nProof.\n  intros.\n  rewrite Qdiv_mult_inv.\n  rewrite <- Qmult_assoc.\n  rewrite <- Qmult_comm.\n  rewrite Qmult_assoc.\n  rewrite <- Qmult_comm.\n  rewrite <- Qmult_assoc with (n:=c).\n  rewrite  Qmult_comm with (x:=/a) (y:= a).\n  rewrite Qmult_inv_r; trivial.\n  rewrite Qmult_1_r.\n  reflexivity.\nQed.\n\nLemma Qdiv_mult4_cancel_1: forall a b c d, ~ a == 0 -> (a*b*c*d)/a == b*c*d.\nProof.\n  intros.\n  rewrite <- Qmult_assoc.\n  rewrite Qdiv_mult3_cancel_1; trivial.\n  rewrite Qmult_assoc.\n  reflexivity.\nQed.\n\n\n\nLtac plus_minus :=\n  repeat match goal with\n  | |- context[?x + ?y] =>\n      match y with\n      | context[-x] =>\n          match y with\n          | -x => rewrite (Qplus_assoc x (-x))\n          | -x + _ => rewrite (Qplus_assoc x (-x))\n          | ?a + ?z => rewrite (Qplus_assoc x a), (Qplus_comm x a), <- (Qplus_assoc a x)\n          end\n      end\n  end.\nLtac minus_plus :=\n  repeat match goal with\n  | |- context[-?x + ?y] =>\n      match y with\n      | context[x] =>\n          match y with\n          | x => rewrite (Qplus_assoc (-x) x)\n          | x + _ => rewrite (Qplus_assoc (-x) x)\n          | ?a + ?z => rewrite (Qplus_assoc (-x) a), (Qplus_comm (-x) a), <- (Qplus_assoc a (-x))\n          end\n      end\n  end.\nLtac plus_opp_simpl :=\n  first [progress plus_minus | progress minus_plus]; rewrite ?Qplus_opp_l, ?Qplus_opp_r, ?Qplus_0_r, ?Qplus_0_l.\n\n\n\n(*Hint Resolve*)\n\nHint Rewrite\n  Qplus_neg\n  Qdiv_mult_inv\n  Qmult_neg_1\n  Qmult_inv_l\n  Qplus_double\n  Qplus_half\n  Qdiv_neg_l\n  Qplus_l_equ_sub_r\n  Qplus_l_equ_sub_l\n  Qplus_r_equ_sub_r\n  Qplus_r_equ_sub_l\n  Qplus_neg_half_l\n  Qmult_l_equ_div_r\n  Qdiv_inj\n  Qmult_dist_div\n  Qsquare\n  Qdiv_squared\n  Qdiv_dist_mult\n  Qdiv_div\n  Qpoly2_sub_dist\n  Qmult_sum2_dist_l\n  Qmult_sum2_dist_r\n  Qmult_sub2_dist_l\n  Qmult_sub2_dist_r\n  Qdiv_sum2_dist_r\n  Qdiv_diff2_dist_r\n  Qmult_sum3_dist_r\n  Qmult_sub_sum3_dist_r\n  Qdiv_sub_sum3_dist_r\n  Qdiv_mult4_cancel_1\n  Qdiv_mult3_cancel_1 : q_math_hints.\n\nLtac q_math := ring || autorewrite with q_math_hints; auto with qarith.\n", "meta": {"author": "RichardHabeeb", "repo": "avsim", "sha": "6be883eb53e6f454221d23659acd3e3341278ac5", "save_path": "github-repos/coq/RichardHabeeb-avsim", "path": "github-repos/coq/RichardHabeeb-avsim/avsim-6be883eb53e6f454221d23659acd3e3341278ac5/proof/Qlemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7404889479451796}}
{"text": "Add Rec LoadPath \"../src/\" as evm_compute.  \nAdd ML Path \"../src/\". \n\nRequire Evm_compute. \nRequire Import ZArith. \n\n(* factorisation as an example of non-trivial computation *)\n\nSection fold. \n  Variable A : Type. \n  Variable f : Z -> A -> A. \n  Fixpoint fold n acc:= match n with \n                          | 0 => acc\n                          | S k => fold k (f (Z.of_nat k) acc)\n                        end. \nEnd fold. \n\n\nOpen Scope Z_scope. \n\nDefinition divide x y :=\n  Z.modulo x y =? 0 . \n\nDefinition try n z acc :=\n  match acc with \n    | None => \n      if z <? 2 then \n        None \n      else if divide n z then \n             Some (z,Z.div n z)\n           else None\n    | Some x => acc\n  end. \n\n\nDefinition factor n :=\n  match fold _ (try (Z.of_nat n)) n None with \n    | Some x => x\n    | None => (Z.of_nat n,1)\n  end.\n   \nEval compute in factor 9. \n  \nRemark factorisable :  forall x:nat, (let (a,b) := factor x in (a * b)%Z) = Z.of_nat x.\nAdmitted. \n\nDefinition k : nat := 1111%nat. Definition ka := 101. Definition kb := 11. \n\nRequire Import String. \n\nCheck (\"evm_compute without witnesses\")%string. \nGoal exists e1 e2, Z.of_nat k = e1 * e2. \nintros. eexists. eexists.\nrewrite <- factorisable. \nTime evm blacklist [Zmult;].   reflexivity.  \nTime Qed. \n\nCheck (\"evm_compute in H\")%string. \nGoal exists e1 e2, (Z.of_nat k = e1 * e2 -> e1 * e2 = ka * kb). \nintros. eexists. eexists. intros H.\nrewrite <- factorisable in H. \nTime evm in H blacklist [Zmult;]. \napply H. \nTime Qed. \n\nCheck (\"vm_compute with witnesses\")%string. \nGoal exists e1 e2, Z.of_nat k = e1 * e2. \nintros.  exists ka. exists kb. \nTime vm_compute; reflexivity. \nTime Qed. \n\nCheck (\"cbv with witnesses\")%string. \nGoal exists e1 e2, Z.of_nat k = e1 * e2. \nintros.  exists ka.  exists kb. \nTime cbv; reflexivity. \nTime Qed. \n\n\n(* it works even if there are lets in the hyps *)\nGoal exists e1 e2, Z.of_nat k = e1 * e2. \nintros. eexists.   eexists.\n match goal with |- _ = ?x * ?y => \n                 let Hx := fresh in\n                 let Hy := fresh in \n                 set (Hx:=x);\n                 set (Hy:=y) end.  \n(* Fail vm_compute. *)\nrewrite <- factorisable. \nevm blacklist [Zmult]. \nunfold H, H0. reflexivity. \nQed. \n\n\n\n(* An example of a proof that blows up at Qed time, because the proof term does not provide enough information *)\n(* \nCheck (\"cbv without witnesses\")%string. \nGoal exists e1 e2, Z.of_nat k = e1 * e2. \nintros. eexists. eexists.\nrewrite <- factorisable. \nset (f :=Z.mul).  \nTime cbv - [f]; unfold f;  reflexivity. (* 4 s *)\nTime Qed.                               (* 154 s !! *)\n*)\n\nFixpoint nexists n P :=\n  match n with \n    | 0 => P \n    | S n => exists x, nexists n (P /\\ x = 1)\n  end%nat. \n\nCheck (\"cbv with witnesses\")%string. \nGoal exists e1 e2, nexists 10  (Z.of_nat k = e1 * e2).\nunfold nexists; do 12 eexists.    \nrewrite <- (factorisable). \nevm blacklist [Zmult].\nrepeat split. \nTime Qed. \n\n", "meta": {"author": "braibant", "repo": "evm_compute", "sha": "170b0b533918625ce2bfd3bdd635732edc8ce89f", "save_path": "github-repos/coq/braibant-evm_compute", "path": "github-repos/coq/braibant-evm_compute/evm_compute-170b0b533918625ce2bfd3bdd635732edc8ce89f/test-suite/Example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7404634592193412}}
{"text": "(*********************)\n(** * Bool data type *)\n(*********************)\nInductive bool := true | false.\n\n(*********************)\n(** * Bool function  *)\n(*********************)\nDefinition inverse(b : bool) : bool := match b with\n    | true  => false\n    | false => true\n    end.\n\nDefinition and(a b : bool) : bool := match a with\n    | false => false\n    | true  => match b with\n        | false => false\n        | true  => true\n        end\n    end\n.\n\nDefinition or(a b : bool) : bool := match a with\n    | true  => true\n    | false => match b with\n        | true  => true\n        | false => false\n        end\n    end\n.\n\n(*********************)\n(** * Bool notation  *)\n(*********************)\nNotation \"¬ a\" := (inverse a) (at level 50) : type_scope.\nNotation \"a ∧ b\" := (and a b) (at level 50) : type_scope.\nNotation \"a ∨ b\" := (or a b) (at level 50) : type_scope.\n\n(*********************)\n(** * Bool Theorem   *)\n(*********************)\nTheorem basic_bool_theorem: forall a b : bool,\n    (a ∧ b) ∨ (¬(a ∧ b)) = true.\n    \n", "meta": {"author": "mox692", "repo": "theorem-prove-example", "sha": "393c4c00eb2e9e458f0873fc97fa151b5760342e", "save_path": "github-repos/coq/mox692-theorem-prove-example", "path": "github-repos/coq/mox692-theorem-prove-example/theorem-prove-example-393c4c00eb2e9e458f0873fc97fa151b5760342e/Bool/Bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7404634557013818}}
{"text": "(*\n Copyright 2022 ZhengPu Shi\n  This file is part of coq-matrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Test for matrix.\n  author    : ZhengPu Shi\n  date      : 2021.12\n*)\n\nFrom FCS Require Export MatrixAll.\n\n\n(** 以 【 实数 + MLL实现 】 为例 *)\nModule Test_Mat_R_MLL.\n  Import MatrixAllR.MLL.\n  Open Scope R.\n\n  Check T.\n  Check 3 : T.\n  \n  Parameter m1 : mat 3 4.\n  Parameter m2 : mat 3 4.\n  Check m1 == m2.\n  \n  (* 构造具体的矩阵 *)\n  Definition ex_m_1_1 : mat 1 1 := mat_1_1 2.\n  Definition ex_m_3_3 : mat 3 3 := mat_3_3 1 2 3 4 5 6 7 8 9.\n  Compute ex_m_1_1.\n  Compute ex_m_3_3.\n  \n  (* 零矩阵和单位矩阵 *)\n  Compute mat0 3 4.\n  Compute mat1 3.\n  \n  (* 矩阵映射 *)\n  Compute mmap (fun x => x * 2) (ex_m_3_3).\n  Compute mmap2 (Rminus) ex_m_3_3 ex_m_3_3.\n  \n  (* 矩阵加法 *)\n  Check madd m1 m2.\n  Compute madd ex_m_3_3 ex_m_3_3.\n  Example ex_madd : forall r c (m1 m2 : mat r c), madd m1 m2 == madd m2 m1.\n  intros. apply madd_comm. Qed.\n  \n  (* 矩阵减法 *)\n  Compute msub ex_m_3_3 (mat1 3).\n  \n  (* 矩阵数乘 *)\n  Compute mcmul 3 ex_m_3_3.\n  Compute mmulc ex_m_3_3 3.\n  \n  (* 矩阵转置 *)\n  Compute mtrans ex_m_3_3.\n  \n  (* 矩阵乘法 *)\n  Compute mmul ex_m_3_3 (mtrans ex_m_3_3).\n  Compute mmul ex_m_3_3 ex_m_3_3.\n\n  (* 坐标转换的一个例子 *)\n  \n(*   Import List.\n  Import ListNotations. *)\n  \n  Section coordinate_transform_test.\n    Variable θ ψ φ : R.\n    Definition Rx (α : R) : mat 3 3 := mat_3_3\n      1         0           0\n      0         (cos α)     (sin α)\n      0         (-sin α)    (cos α).\n\n    Definition Ry (β : R) : mat 3 3 := mat_3_3\n      (cos β)   0           (-sin β)\n      0         1           0\n      (sin β)   0           (cos β).\n\n    Definition Rz (γ : R) : mat 3 3 := mat_3_3 \n      (cos γ)   (sin γ)   0\n      (-sin γ)  (cos γ)   0\n      0         0         1.\n    \n    Definition R_b_e_direct : mat 3 3 := mat_3_3\n      (cos θ * cos ψ) \n      (cos ψ * sin θ * sin φ - sin ψ * cos φ)\n      (cos ψ * sin θ * cos φ + sin φ * sin ψ)\n      \n      (cos θ * sin ψ) \n      (sin ψ * sin θ * sin φ + cos ψ * cos φ)\n      (sin ψ * sin θ * cos φ - cos ψ * sin φ)\n      \n      (-sin θ)\n      (sin φ * cos θ)\n      (cos φ * cos θ).\n    \n    Open Scope M.\n    Opaque cos sin.\n    Lemma Rx_Ry_Rz_eq_Rbe : (Rz ψ)⊤ × (Ry θ)⊤ × (Rx φ)⊤ == R_b_e_direct.\n    Proof. lma. Qed.\n    \n  End coordinate_transform_test.\n  \nEnd Test_Mat_R_MLL.\n", "meta": {"author": "zhengpushi", "repo": "coq-matrix", "sha": "b0f5a3463d7f1973fd29be8b6b85e4a700297a34", "save_path": "github-repos/coq/zhengpushi-coq-matrix", "path": "github-repos/coq/zhengpushi-coq-matrix/coq-matrix-b0f5a3463d7f1973fd29be8b6b85e4a700297a34/MatrixComparison/src/Matrix/MatrixTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7404058062471705}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, gen_dep_practice *)\nFixpoint index{X: Type}(n: nat)(l: list X):=\n    match l with\n    |nil      => None\n    |cons h t => if Nat.eqb n 0 then Some h else index (pred n) t\n    end.\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X ),\n    length l =n  ->index n l = None.\nProof.\n    intros.\n    generalize dependent n.\n    induction l as [|l'].\n    intros. simpl. reflexivity.\n    intros. simpl. destruct n as [|n'].\n    simpl. inversion H.\n    simpl. apply IHl. simpl in H. inversion H. reflexivity.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter7_Library_MoreCoq/gen_dep_practice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.740405802323629}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega.\nRequire Import utils_tac utils_list sums php.\n\nSet Implicit Arguments.\n\nLocal Notation \"∑\" := (msum plus 0).\n\nSection nat_swap.\n\n  Variables (i j : nat).\n\n  Definition swap n := if eq_nat_dec n i then j else\n                       if eq_nat_dec n j then i else n.\n\n  Fact swap_spec_i : swap i = j.\n  Proof. unfold swap; destruct (eq_nat_dec i i); auto; omega. Qed.\n\n  Fact swap_spec_j : swap j = i.\n  Proof. \n    unfold swap. \n    destruct (eq_nat_dec j i); auto.\n    destruct (eq_nat_dec j j); auto; omega. \n  Qed.\n\n  Fact swap_spec n : n <> i -> n <> j -> swap n = n.\n  Proof. \n    unfold swap; intros.\n    destruct (eq_nat_dec n i); try omega.\n    destruct (eq_nat_dec n j); omega. \n  Qed.\n\n  Fact swap_involutive n : swap (swap n) = n.\n  Proof.\n    destruct (eq_nat_dec n i).\n    { subst n; rewrite swap_spec_i, swap_spec_j; auto. }\n    destruct (eq_nat_dec n j).\n    { subst n; rewrite swap_spec_j, swap_spec_i; auto. }\n    { do 2 (rewrite swap_spec; auto). }\n  Qed.\n\n  Fact swap_inj n m : swap n = swap m -> n = m.\n  Proof.\n    intros; rewrite <- (swap_involutive n), H.\n    apply swap_involutive.\n  Qed.\n  \nEnd nat_swap.\n\nOpaque swap.\n\nSection php_fun.\n\n  Variable (n : nat) (f : nat -> nat) (Hf : forall i, i <= n -> f i < n).\n\n  Theorem php_fun : exists i j, i < j <= n /\\ f i = f j.\n  Proof.\n    destruct PHP_rel with (S := fun x y => y = f x) (l := list_an 0 (S n)) (m := list_an 0 n)\n      as (a & i & b & j & c & v & H1 & H2 & H3 & H4).\n    + intros x; rewrite list_an_spec; simpl; intros [ _ H ].\n      exists (f x); split; auto; rewrite list_an_spec; simpl; split; try omega.\n      apply Hf; omega.\n    + do 2 rewrite list_an_length; auto.\n    + exists i, j; split; try omega.\n      generalize H1; intros G1.\n      apply list_an_app_inv in G1.\n      destruct G1 as (G0 & G1); simpl in G1.\n      injection G1; clear G1; intros G1 G2.\n      symmetry in G1; apply list_an_app_inv in G1.\n      destruct G1 as (G3 & G1); simpl in G1.\n      injection G1; clear G1; intros G4 G1.\n      apply f_equal with (f := @length _) in H1.\n      revert H1; rew length; intros H1.\n      omega.\n  Qed.\n\nEnd php_fun.\n\nSection split_interval.\n\n  (* [0,i[ U {i} U ]i,n] ~~ [0,n[ U {n} *)\n\n  Variables (n i : nat) (Hi : i <= n).\n\n  Let g j := if le_lt_dec (S n) j then j else     (* j > n  *)\n             if le_lt_dec i j then                  \n             if le_lt_dec j i then n              (* j = i *)\n             else j-1                             (* i < j <= n *)\n             else j.                              (* j < i *)\n\n  Let h j := if le_lt_dec (S n) j then j else     (* j > n  *)\n             if le_lt_dec n j then i else         (* j = n  *) \n             if le_lt_dec i j then j+1            (* i <= j < n *)\n             else j.                              (* j < i *)\n\n  Let Hg1 : forall j, j <= n -> g j <= n.\n  Proof.\n    intros j Hj; unfold g.\n    destruct (le_lt_dec (S n) j); try omega.\n    destruct (le_lt_dec i j); try omega.\n    destruct (le_lt_dec j i); omega.\n  Qed.\n\n  Let Hg2 j : n < j -> g j = j.\n  Proof.\n    unfold g; destruct (le_lt_dec (S n) j); intros; omega.\n  Qed.\n\n  Let Hh1 : forall j, j <= n -> h j <= n.\n  Proof.\n    intros j Hj; unfold h.\n    destruct (le_lt_dec (S n) j); try omega.\n    destruct (le_lt_dec n j); try omega.\n    destruct (le_lt_dec i j); omega.\n  Qed.\n\n  Let Hh2 j : n < j -> h j = j.\n  Proof.\n    unfold h; destruct (le_lt_dec (S n) j); intros; omega.\n  Qed.\n\n  Ltac mydestruct H := \n    match goal with\n      |- if ?c then _ else _ = _ => destruct c as [ H | H ]; try omega; auto\n    end.\n\n  Theorem split_interval : { g : nat -> nat & { h | (forall j, j <= n -> g j <= n)\n                                                 /\\ (forall j, j <= n -> h j <= n)\n                                                 /\\ (forall j, g (h j) = j)\n                                                 /\\ (forall j, h (g j) = j) \n                                                 /\\ g i = n } }.\n  Proof.\n    exists g, h.\n    split; [ | split; [ | split; [ | split ] ] ]; auto.\n    + intros j; unfold h. \n      destruct (le_lt_dec (S n) j) as [ | H1 ]; auto.\n      destruct (le_lt_dec n j) as [ H2 | H2 ].\n      { unfold g.\n        destruct (le_lt_dec (S n) i); try omega.\n        destruct (le_lt_dec i i); omega. }\n      destruct (le_lt_dec i j) as [ H3 | H3 ].\n      { unfold g.\n        destruct (le_lt_dec (S n) (j+1)); try omega.\n        destruct (le_lt_dec i (j+1)); try omega.\n        destruct (le_lt_dec (j+1) i); omega. }\n      { unfold g.\n        destruct (le_lt_dec (S n) j); try omega.\n        destruct (le_lt_dec i j); try omega. }\n    + intros j; unfold g. \n      destruct (le_lt_dec (S n) j) as [ | H1 ]; auto.\n      destruct (le_lt_dec i j) as [ H2 | H2 ].\n      destruct (le_lt_dec j i) as [ H3 | H3 ].\n      { unfold h.\n        destruct (le_lt_dec (S n) n); try omega.\n        destruct (le_lt_dec n n); omega. }\n      { unfold h.\n        destruct (le_lt_dec (S n) (j-1)); try omega.\n        destruct (le_lt_dec n (j-1)); try omega.\n        destruct (le_lt_dec i (j-1)); omega. }\n      { unfold h.\n        destruct (le_lt_dec (S n) j); try omega.\n        destruct (le_lt_dec n j); try omega.\n        destruct (le_lt_dec i j); omega. }\n    + unfold g.\n      destruct (le_lt_dec (S n) i); try omega.\n      destruct (le_lt_dec i i); omega.\n  Qed.\n\nEnd split_interval.\n\nDefinition find_max_fun n f : { i | i <= n /\\ forall j, j <= n -> f j <= f i }.\nProof.\n  revert f; induction n as [ | n IHn ]; intros f.\n  + exists 0; split; auto.\n    intros [ | ]; auto; omega.\n  + destruct (IHn f) as (i & H1 & H2).\n    destruct (le_lt_dec (f i) (f (S n))) as [ H | H ].\n    * exists (S n); split; auto.\n      intros j Hj.\n      destruct (le_lt_dec j n) as [ H0 | H0 ].\n      - apply le_trans with (2 := H); auto.\n      - cutrewrite (j = S n); auto; omega.\n    * exists i; split; auto.\n      intros j Hj.\n      destruct (le_lt_dec j n) as [ H0 | H0 ]; auto.\n      cutrewrite (j = S n); auto; omega.\nQed.\n\nSection sum_bounded_permutation.\n\n  Let sigma_sum_split i n f : i < n -> ∑ (S n) f = f i + f n + ∑ i f + ∑ (n-S i) (fun j => f (S i+j)).\n  Proof.\n    intros Hi.\n    replace (S n) with (i+1+(n- S i)+1) by omega.\n    repeat (rewrite msum_plus; auto).\n    do 2 rewrite msum_S, msum_0.\n    repeat rewrite <- plus_assoc.\n    rewrite (plus_comm). \n    repeat rewrite <- plus_assoc.\n    f_equal.\n    { f_equal; omega. }\n    simpl.\n    rewrite (plus_comm).\n    repeat rewrite <- plus_assoc.\n    f_equal.\n    { f_equal; omega. }\n    f_equal.\n    apply msum_ext.\n    intros; f_equal; omega.\n  Qed.\n\n  Let sum_permutation_1 n i j g f : \n            i < j < n \n         -> g i = j \n         -> g j = i\n         -> (forall k, k <> i -> k <> j -> k < n -> g k = k)\n         -> ∑ n f = ∑ n (fun i => f (g i)).\n  Proof.\n    revert i j g; induction n as [ | n IHn ]; intros i j g (H1 & H2) H3 H4 H5.\n    + do 2 rewrite msum_0; auto.\n    + destruct (eq_nat_dec j n) as [ H7 | H7 ].\n      * rewrite H7 in *; clear j H7 H2.\n        do 2 rewrite sigma_sum_split with (1 := H1).\n        rewrite H3, H4; f_equal; [ f_equal | ]; try omega;\n          apply msum_ext; intros; symmetry; f_equal; apply H5; omega.\n      * do 2 (rewrite msum_plus1; auto); f_equal.\n        - apply IHn with i j; auto; split; auto; omega.\n        - symmetry; f_equal; apply H5; omega.\n  Qed.\n\n  Inductive bounded_permut n (i j : nat) g : Prop :=\n    | in_nat_perm : \n          i < n -> j < n -> g i = j -> g j = i\n       -> (forall k, k <> i -> k <> j -> k < n -> g k = k)\n       -> bounded_permut n i j g.\n\n  Hint Resolve swap_spec_i swap_spec_j swap_spec.\n\n  Fact swap_bounded_permut n i j : i < n -> j < n -> bounded_permut n i j (swap i j).\n  Proof. constructor; auto. Qed.\n \n  Inductive composed_permutation n g : Prop :=\n    | in_cp_0 : (forall i, i < n -> g i = i) -> composed_permutation n g\n    | in_cp_1 : forall i j f h, \n                                bounded_permut n i j f \n                             -> composed_permutation n h \n                             -> (forall i, i < n -> g i = h (f i))\n                             -> composed_permutation n g.\n\n  Fact composed_permutation_ext n f g : \n       (forall i, i < n -> f i = g i) -> composed_permutation n f -> composed_permutation n g.\n  Proof.\n    intros H1 H2; revert H2 g H1.\n    induction 1 as [ f Hg | f i j p q H1 H2 IH2 H3 ]; intros g H4.\n    + constructor 1; intros; rewrite <- H4; auto.\n    + constructor 2 with i j p q; auto.\n      intros; rewrite <- H4; auto.\n  Qed.\n\n  Let flat n f i := if le_lt_dec n i then n else f i.\n\n  Let flat_left n f i : i < n -> flat n f i = f i.\n  Proof. unfold flat; intro; destruct (le_lt_dec n i); auto; omega. Qed.\n\n  Let flat_right n f i : n <= i -> flat n f i = n.\n  Proof. unfold flat; intro; destruct (le_lt_dec n i); auto; omega. Qed.\n\n  Fact composed_permutation_extends n f g : \n         (forall i, i < n -> f i = g i) -> g n = n -> composed_permutation n f -> composed_permutation (S n) g.\n  Proof.\n    intros H1 H2 H3; revert H3 g H1 H2.\n    induction 1 as [ f Hg | f i j p q H1 H2 IH2 H3 ]; intros g H4 H5.\n    + constructor 1; intros j Hj.\n      destruct (eq_nat_dec j n); subst; auto.\n      rewrite <- H4, Hg; auto; omega.\n    + constructor 2 with i j (flat n p) (flat n q).\n      * destruct H1 as [ G1 G2 G3 G4 G5 ]; constructor; try omega.\n        - rewrite flat_left; auto; omega.\n        - rewrite flat_left; auto; omega.\n        - intros k ? ? ?.\n          destruct (eq_nat_dec k n); subst.\n          ++ rewrite flat_right; auto.\n          ++ rewrite flat_left, G5; omega.\n      * apply IH2.\n        - intros l Hl; rewrite flat_left; auto.\n        - rewrite flat_right; omega.\n      * intros k Hk.\n        destruct (eq_nat_dec k n); subst.\n        - rewrite (flat_right p), flat_right; omega.\n        - rewrite (flat_left p); try omega.\n          rewrite flat_left, <- H4; try omega.\n          ++ apply H3; omega.\n          ++ destruct H1 as [ G1 G2 G3 G4 G5 ].\n             destruct (eq_nat_dec k i). \n             { subst; auto. }\n             destruct (eq_nat_dec k j).\n             { subst k; omega. }\n             rewrite G5; omega.\n  Qed.\n\n  Fact composed_permutation_S n g : g n = n -> composed_permutation n g -> composed_permutation (S n) g.\n  Proof. intro; apply  composed_permutation_extends; auto. Qed.\n\n  Inductive bounded_injective n f : Prop :=\n    | in_bounded_inj : (forall i, i < n -> f i < n)\n                    -> (forall i j, i < n -> j < n -> f i = f j -> i = j)\n                    -> bounded_injective n f.\n\n  Fact injective_composed_permutation n f : bounded_injective n f\n                                         -> composed_permutation n f.\n  Proof.\n    intros [ H1 H2 ].\n    revert f H1 H2; induction n as [ | n IHn ]; intros f H1 H2.\n    + constructor 1; intros; omega.\n    + destruct (find_max_fun n f) as (i & H3 & H4).\n      destruct (le_lt_dec n (f i)) as [ C | C ].\n      - assert (f i = n) as Hf1.\n        { apply le_antisym; auto; apply le_S_n, H1; omega. }\n        assert (forall j, j <= n -> j <> i -> f j < n) as Hf2.\n        { intros j G1 G2.\n          destruct (eq_nat_dec (f j) n).\n          + contradict G2; apply H2; omega.\n          + specialize (H1 j); omega. }\n        specialize (IHn (fun x => f (swap i n x))).\n        spec in IHn.\n        { intros j Hj.\n          destruct (eq_nat_dec j i).\n          + subst j; rewrite swap_spec_i; apply Hf2; omega.\n          + rewrite swap_spec; try omega; apply Hf2; omega. }\n        spec in IHn.\n        { intros u v G1 G2 G3.\n          apply H2 in G3.\n          + revert G3; apply swap_inj.\n          + destruct (eq_nat_dec u i).\n            - subst; rewrite swap_spec_i; omega.\n            - rewrite swap_spec; omega.\n          + destruct (eq_nat_dec v i).\n            - subst; rewrite swap_spec_i; omega.\n            - rewrite swap_spec; omega. }\n        apply composed_permutation_S in IHn.\n        2: rewrite swap_spec_j, Hf1; auto.\n        generalize (@swap_bounded_permut (S n) i n); intros G.\n        do 2 (spec in G; try omega).\n        constructor 2 with (1 := G) (2 := IHn).\n        intros; rewrite swap_involutive; auto.\n      - destruct (@php_fun n f) as (u & v & G1 & G2).\n        { intros; apply le_lt_trans with (2 := C); auto. }\n        apply H2 in G2; omega.\n  Qed.\n\n  Theorem sum_bounded_permutation n i j g f : bounded_permut n i j g -> ∑ n f = ∑ n (fun i => f (g i)).\n  Proof.\n    intros [ H1 H2 H3 H4 H5 ].\n    destruct (lt_eq_lt_dec i j) as [ [ G1 | G1 ] | G1 ].\n    + apply sum_permutation_1 with i j; auto; split; auto.\n    + apply msum_ext; rewrite <- G1 in *; clear j G1.\n      intros j Hj; f_equal.\n      destruct (eq_nat_dec j i); subst; auto.\n      rewrite H5; auto.\n    + apply sum_permutation_1 with j i; auto; split; auto.\n  Qed.\n\n  Theorem sum_composed_permutation n f g : composed_permutation n g -> ∑ n f = ∑ n (fun i => f (g i)).\n  Proof.\n    induction 1 as [ g Hg | g i j p q H1 H2 IH2 H3 ].\n    + symmetry; apply msum_ext; intros; f_equal; apply Hg; auto.\n    + rewrite IH2, sum_bounded_permutation with (1 := H1).\n      symmetry; apply msum_ext; intros; f_equal; auto.\n  Qed.\n\n  Theorem sum_injective n f g : bounded_injective n g -> ∑ n f = ∑ n (fun i => f (g i)).\n  Proof.\n    intros; apply sum_composed_permutation, injective_composed_permutation; trivial.\n  Qed.\n\nEnd sum_bounded_permutation.\n\nSection sum_bijection.\n\n  Inductive bijection n g h : Type :=\n    | in_bij : (forall i, i < n -> g i < n)\n            -> (forall i, i < n -> h i < n) \n            -> (forall i, i < n -> g (h i) = i)\n            -> (forall i, i < n -> h (g i) = i)\n           -> bijection n g h.\n\n  Theorem sum_bijection n f g h : bijection n g h -> ∑ n f = ∑ n (fun i => f (g i)).\n  Proof.\n    intros [ H1 H2 H3 H4 ].\n    apply sum_injective.\n    constructor; auto.\n    intros i j G1 G2 G3; rewrite <- (H4 i), G3; auto.\n  Qed.\n\n\n  Inductive triangle_bijection n k g h : Prop :=\n    | in_tb : (forall i j, j < i < n -> h (i,j) < k /\\ g (h (i,j)) = (i,j))\n           -> (forall q, q < k -> snd (g q) < fst (g q) < n /\\ h (g q) = q) \n           -> triangle_bijection n k g h.\n\n  Fact sum_triangle_bijection n f k g h :\n         triangle_bijection n k g h \n      -> ∑ n (fun i => ∑ i (fun j => f i j)) = ∑ k (fun i => f (fst (g i)) (snd (g i))).\n  Proof.\n  Admitted.\n \n\n  (* ∑ n (fun i => ∑ i (fun j => f i j * power (e i j) r) = ∑ k *)\n\nEnd sum_bijection.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/Shared/Libs/DLW/Utils/sorting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7403729061968304}}
{"text": "(* Exercise coq_list_06 *)\n\n(* Those are the definitions from the previous exercise: *)\n\nInductive natlist : Set :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nFixpoint append (l m : natlist) {struct l} : natlist :=\n  match l with\n  | nil => m\n  | cons x xs => cons x (append xs m)\n  end.\n\nFixpoint length (l : natlist) : nat :=\n  match l with\n  | nil => 0\n  | cons ele rem => 1 + (length rem)\n  end.\n\nFixpoint reverse (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | cons ele rem => append (reverse rem) (cons ele nil)\n  end.\n\n(* Now let us prove that reverse does not change the length\n   of a list *)\n\n(* For this we may need a result proven in one of the previous\n   exercises and some results about natural numbers (remember\n   the exercises concerning natural numbers?) *)\nAxiom append_length : forall l m,\n  length (append l m) = length l + length m.\nRequire Import Arith.\n\nLemma reverse_length : forall l,\n  length l = length (reverse l).\n  \nProof.\n  intros.\n  induction l.\n  simpl; reflexivity.\n  simpl.\n  rewrite append_length.\n  simpl.\n  rewrite Nat.add_1_r.\n  rewrite IHl.\n  reflexivity.  \nQed.", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_list_07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7403728925602444}}
{"text": "Theorem 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.\n  - split.\n    -- apply HP.\n    -- apply HQ.\n  - apply HR.\nQed.", "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/Chapter6/and_assoc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7403095379345896}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Export Fiat.Common.Coq__8_4__8_5__Compat.\n\nHint Rewrite <- nat_compare_lt : hints.\nHint Rewrite <- nat_compare_gt : hints.\nHint Rewrite Nat.compare_eq_iff : hints.\nHint Rewrite <- Nat.compare_eq_iff : hints.\n\nLtac autorewrite_nat_compare :=\n  autorewrite with hints.\n\nLemma nat_compare_eq_refl : forall x, Nat.compare x x = Eq.\n  intros; apply Nat.compare_eq_iff; trivial.\nQed.\n\nLemma nat_compare_consistent :\n  forall n0 n1,\n    { Nat.compare n0 n1 = Lt /\\ Nat.compare n1 n0 = Gt }\n    + { Nat.compare n0 n1 = Eq /\\ Nat.compare n1 n0 = Eq }\n    + { Nat.compare n0 n1 = Gt /\\ Nat.compare n1 n0 = Lt }.\nProof.\n  intros n0 n1;\n  destruct (lt_eq_lt_dec n0 n1) as [ [_lt | _eq] | _lt ];\n  [ constructor 1; constructor 1  | constructor 1; constructor 2 | constructor 2 ];\n  split;\n  autorewrite_nat_compare;\n  intuition.\nQed.\n", "meta": {"author": "scuellar", "repo": "narcissus_errors", "sha": "8c547389030165e8620b43bb38ad87b9b65e5471", "save_path": "github-repos/coq/scuellar-narcissus_errors", "path": "github-repos/coq/scuellar-narcissus_errors/narcissus_errors-8c547389030165e8620b43bb38ad87b9b65e5471/src/QueryStructure/Implementation/DataStructures/Bags/NatCompare_Facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7402781467301031}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (x : natural) : natural :=\n  mult z (plus (Succ x) y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj283_coqofml_wDHBY3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7402091274242322}}
{"text": "(* week-13_fib.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of Fri 10 Nov 2017 *)\n\n(* ********** *)\n\n(* Paraphernalia: *)\n\nLtac unfold_tactic name := intros; unfold name; (* fold name; *) reflexivity.\n\nRequire Import Arith Bool.\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\n(* ********** *)\n\n(* Specialized induction principle: *)\n\nLemma nat_ind2 :\n  forall P : nat -> Prop,\n    P 0 ->\n    P 1 ->\n    (forall i : nat,\n      P i -> P (S i) -> P (S (S i))) ->\n    forall n : nat,\n      P n.\nProof.\n  intros P H_bc0 H_bc1 H_ic n.\n  assert (H_Pn_PSn : P n /\\ P (S n)).\n    induction n as [ | n' [IH_n' IH_Sn']].\n  \n    split.\n\n      apply H_bc0.\n\n    apply H_bc1.\n  \n    split.\n\n      apply IH_Sn'.\n\n    apply (H_ic n' IH_n' IH_Sn').\n\n  destruct H_Pn_PSn as [H_Pn _].\n  apply H_Pn.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_fibonacci (fib : nat -> nat) :=\n  fib 0 = 0\n  /\\\n  fib 1 = 1\n  /\\\n  forall n'' : nat,\n    fib (S (S n'')) = fib (S n'') + fib n''.\n\nTheorem there_is_only_one_fibonacci :\n  forall fib1 fib2 : nat -> nat,\n    specification_of_fibonacci fib1 ->\n    specification_of_fibonacci fib2 ->\n    forall n : nat,\n      fib1 n = fib2 n.\nProof.\n  intros fib1 fib2.\n  unfold specification_of_fibonacci.\n  intros [H_fib1_bc0 [H_fib1_bc1 H_fib1_ic]]\n         [H_fib2_bc0 [H_fib2_bc1 H_fib2_ic]]\n         n.\n  induction n as [ | | n'' IHn'' IHSn''] using nat_ind2.\n\n  rewrite -> H_fib2_bc0.\n  apply H_fib1_bc0.\n\n  rewrite -> H_fib2_bc1.\n  apply H_fib1_bc1.\n\n  rewrite -> H_fib1_ic.\n  rewrite -> IHSn''.\n  rewrite -> IHn''.\n  rewrite <- H_fib2_ic.\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* Standard unit-test function: *)\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\n(* ********** *)\n\n(* The fibonacci function in direct style: *)\n\nFixpoint fib_ds (n : nat) : nat :=\n  match n with\n    | 0 => 0\n    | S n' => match n' with\n                | 0 => 1\n                | S n'' => fib_ds n' + fib_ds n''\n              end\n  end.\n\nCompute (test_fib fib_ds).\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_ds_0 :\n  fib_ds 0 = 0.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma unfold_fib_ds_1 :\n  fib_ds 1 = 1.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma unfold_fib_ds_SS :\n  forall n'' : nat,\n    fib_ds (S (S n'')) = fib_ds (S n'') + fib_ds n''.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\n(* Main definition: *)\n\nDefinition fib_v1 (n : nat) : nat :=\n  fib_ds n.\n\nCompute (test_fib fib_v1).\n\n(* Associated unfold lemma: *)\n\nLemma unfold_fib_v1 :\n  forall n : nat,\n    fib_v1 n = fib_ds n.\nProof.\n  unfold_tactic fib_v1.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v1_fits_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v1.\nProof.\n  unfold specification_of_fibonacci.\n  split.\n\n    rewrite -> unfold_fib_v1.\n    apply unfold_fib_ds_0.\n\n  split.\n\n    rewrite -> unfold_fib_v1.\n    apply unfold_fib_ds_1.\n\n  intro n''.\n  rewrite -> unfold_fib_v1.\n  apply unfold_fib_ds_SS.\nQed.\n\n(* ********** *)\n\n(* The fibonacci function in continuation-passing style: *)\n\nFixpoint fib_cps (ans : Type) (n : nat) (k : nat -> ans) : ans :=\n  match n with\n    | 0 => k 0\n    | S n' =>\n      match n' with\n        | 0 => k 1\n        | S n'' =>\n          fib_cps ans n' (fun v1 =>\n                            fib_cps ans n'' (fun v2 =>\n                                               k (v1 + v2)))\n      end\n  end.\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_cps_0 :\n  forall (ans : Type) (k : nat -> ans),\n    fib_cps ans 0 k = k 0.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma unfold_fib_cps_1 :\n  forall (ans : Type) (k : nat -> ans),\n    fib_cps ans 1 k = k 1.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma unfold_fib_cps_SS :\n  forall (ans : Type) (n'' : nat) (k : nat -> ans),\n    fib_cps ans (S (S n'')) k =\n    fib_cps ans (S n'') (fun v1 => fib_cps ans n'' (fun v2 => k (v1 + v2))).\nProof.\n  unfold_tactic fib_ds.\nQed.\n\n(* Lemma about resetting the continuation: *)\n\nLemma about_fib_cps :\n  forall (n : nat) (ans: Type) (k : nat -> ans),\n    fib_cps ans n k = k (fib_cps nat n (fun a => a)).\nProof.\n  intro n.\n  induction n as [ | | n' IHn' IHn''] using nat_ind2.\n  intros ans k.\n  rewrite ->2 unfold_fib_cps_0.\n  reflexivity.\n  \n  intros ans k.\n  rewrite ->2 unfold_fib_cps_1.\n  reflexivity.\n\n  intros ans k.\n  rewrite ->2 unfold_fib_cps_SS.\n  rewrite -> IHn''.\n  rewrite -> IHn'.\n  rewrite -> (IHn'' nat (fun v1 : nat => fib_cps nat n' (fun v2 : nat => v1 + v2))).\n  rewrite -> (IHn' nat (fun v2 : nat => fib_cps nat (S n') (fun a : nat => a) + v2)).\n  reflexivity.\nQed.\n      \n(* Main definition: *)\n\nDefinition fib_v2 (n : nat) : nat :=\n  fib_cps nat n (fun v => v).\n\nCompute (test_fib fib_v2).\n\n(* Associated unfold lemma: *)\n\nLemma unfold_fib_v2 :\n  forall n : nat,\n    fib_v2 n = fib_cps nat n (fun v => v).\nProof.\n  unfold_tactic fib_v2.\nQed.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v2_fits_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v2.\nProof.\nAbort.\n\n(* ********** *)\n\n(* The fibonacci function with an accumulator: *)\n\nFixpoint fib_acc (n a1 a0 : nat) : nat :=\n  match n with\n    | 0 => a0\n    | S n' => fib_acc n' (a1 + a0) a1\n  end.\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_acc_0 :\n  forall a1 a0 : nat,\n    fib_acc 0 a1 a0 = a0.\nProof.\n  unfold_tactic fib_acc.\nQed.\n\nLemma unfold_fib_acc_S :\n  forall n' a1 a0 : nat,\n    fib_acc (S n') a1 a0 = fib_acc n' (a1 + a0) a1.\nProof.\n  unfold_tactic fib_acc.\nQed.\n\n(* Main definition: *)\n\nDefinition fib_v3 (n : nat) : nat :=\n  fib_acc n 1 0.\n\nCompute (test_fib fib_v3).\n\n(* Associated unfold lemma: *)\n\nLemma unfold_fib_v3 :\n  forall n : nat,\n    fib_v3 n = fib_acc n 1 0.\nProof.\n  unfold_tactic fib_v3.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_acc :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall j i : nat,\n      fib_acc j (fib (S i)) (fib i) = fib (j + i).\nProof.\nAbort.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v3_fits_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v3.\nProof.\nAbort.\n\n(* ********** *)\n\n(* The fibonacci function with an accumulator in CPS: *)\n\nFixpoint fib_acc_cps (ans : Type) (n a1 a0 : nat) (k : nat -> ans) : ans :=\n  match n with\n    | 0 => k a0\n    | S n' => fib_acc_cps ans n' (a1 + a0) a1 k\n  end.\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_acc_cps_0 :\n  forall (ans: Type)\n         (a1 a0 : nat)\n         (k : nat -> ans),\n    fib_acc_cps ans 0 a1 a0 k = k a0.\nProof.\n  unfold_tactic fib_acc_cps.\nQed.\n\nLemma unfold_fib_acc_cps_S :\n  forall (ans: Type)\n         (n' a1 a0 : nat)\n         (k : nat -> ans),\n    fib_acc_cps ans (S n') a1 a0 k =\n    fib_acc_cps ans n' (a1 + a0) a1 k.\nProof.\n  unfold_tactic fib_acc_cps.\nQed.\n\n(* Main definition: *)\n\nDefinition fib_v4 (n : nat) : nat :=\n  fib_acc_cps nat n 1 0 (fun a => a).\n\nCompute (test_fib fib_v4).\n\n(* Associated unfold lemma: *)\n\nLemma unfold_fib_v4 :\n  forall (n : nat),\n    fib_v4 n = fib_acc_cps nat n 1 0 (fun a => a).\nProof.\n  unfold_tactic fib_v4.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_acc_cps :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall (ans : Type)\n           (j i : nat)\n           (k : nat -> ans),\n      fib_acc_cps ans j (fib (S i)) (fib i) k =\n      k (fib (j + i)).\nProof.\nAbort.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v4_fits_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v4.\nProof.\nAbort.\n\n(* ********** *)\n\n(* The fibonacci function with a co-accumulator: *)\n\nFixpoint fib_co_acc (n : nat) : nat * nat :=\n  match n with\n    | O => (1, 0)\n    | S n' => let (a1, a0) := fib_co_acc n'\n              in (a1 + a0, a1)\n  end.\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_co_acc_0 :\n  fib_co_acc 0 = (1, 0).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\nLemma unfold_fib_co_acc_S :\n  forall n' : nat,\n    fib_co_acc (S n') = let (a1, a0) := fib_co_acc n'\n                        in (a1 + a0, a1).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\n(* Main definition: *)\n\nDefinition fib_v5 (n : nat) : nat :=\n  let (a1, a0) := fib_co_acc n\n  in a0.\n\nCompute (test_fib fib_v5).\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_v5 :\n  forall n : nat,\n    fib_v5 n =\n    let (a1, a0) := fib_co_acc n\n  in a0.\nProof.\n  unfold_tactic fib_v5.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_co_acc :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      fib_co_acc n = (fib (S n), fib n).\nProof.\nAbort.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v5_fits_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v5.\nProof.\nAbort.\n\n(* ********** *)\n\n(* The fibonacci function with a co-accumulator in CPS: *)\n\nFixpoint fib_co_acc_cps (ans : Type) (n : nat) (k : nat * nat -> ans) : ans :=\n  match n with\n    | O =>\n      k (1, 0)\n    | S n' =>\n      fib_co_acc_cps ans\n                     n'\n                     (fun p =>\n                        match p with\n                          | (a1, a0) =>\n                            k (a1 + a0, a1)\n                        end)\n  end.\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_co_acc_cps_0 :\n  forall (ans : Type)\n         (k : nat * nat -> ans),\n    fib_co_acc_cps ans 0 k = k (1, 0).\nProof.\n  unfold_tactic fib_co_acc_cps.\nQed.\n\nLemma unfold_fib_co_acc_cps_S :\n  forall (ans : Type)\n         (n' : nat)\n         (k : nat * nat -> ans),\n    fib_co_acc_cps ans (S n') k =\n    fib_co_acc_cps ans\n                   n'\n                   (fun p =>\n                      match p with\n                        | (a1, a0) =>\n                          k (a1 + a0, a1)\n                      end).\nProof.\n  unfold_tactic fib_co_acc_cps.\nQed.\n\n(* Main definition: *)\n\nDefinition fib_v6 (n : nat) : nat :=\n  fib_co_acc_cps nat\n                 n\n                 (fun p =>\n                    match p with\n                    | (a1, a0) =>\n                      a0\n                    end).\n\nCompute (test_fib fib_v6).\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_v6_0 :\n  fib_v6 0 = 0.\nProof.\n  unfold_tactic fib_v6.\nQed.\n\nLemma unfold_fib_v6_S :\n  forall n' : nat,\n    fib_v6 (S n') =\n    fib_co_acc_cps nat\n                   n'\n                   (fun p =>\n                      match p with\n                        | (a1, a0) =>\n                          a1\n                      end).\nProof.\n  unfold_tactic fib_v6.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_co_acc_cps :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall (ans : Type)\n           (n : nat)\n           (k : nat * nat -> ans),\n      fib_co_acc_cps ans n k =\n      k (fib (S n), fib n).\nProof.\nAbort.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v6_fits_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v6.\nProof.\nAbort.\n\n(* ********** *)\n\n(* The fibonacci function with a co-accumulator in CPS with a curried continuation: *)\n\nFixpoint fib_co_acc_cps' (ans : Type) (n : nat) (k : nat -> nat -> ans) : ans :=\n  match n with\n    | O =>\n      k 1 0\n    | S n' =>\n      fib_co_acc_cps' ans\n                     n'\n                     (fun a1 a0 =>\n                        k (a1 + a0) a1)\n  end.\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_co_acc_cps'_0 :\n  forall (ans : Type)\n         (k : nat -> nat -> ans),\n    fib_co_acc_cps' ans 0 k = k 1 0.\nProof.\n  unfold_tactic fib_co_acc_cps'.\nQed.\n\nLemma unfold_fib_co_acc_cps'_S :\n  forall (ans : Type)\n         (n' : nat)\n         (k : nat -> nat -> ans),\n    fib_co_acc_cps' ans (S n') k =\n    fib_co_acc_cps' ans\n                   n'\n                   (fun a1 a0 =>\n                      k (a1 + a0) a1).\nProof.\n  unfold_tactic fib_co_acc_cps'.\nQed.\n\n(* Main definition: *)\n\nDefinition fib_v7 (n : nat) : nat :=\n  match n with\n    | O => 0\n    | S n' => \n      fib_co_acc_cps' nat\n                     n'\n                     (fun a1 a0 =>\n                        a1)\n  end.\n\nCompute (test_fib fib_v7).\n\n(* Associated unfold lemmas: *)\n\nLemma unfold_fib_v7_0 :\n  fib_v7 0 = 0.\nProof.\n  unfold_tactic fib_v7.\nQed.\n\nLemma unfold_fib_v7_S :\n  forall n' : nat,\n    fib_v7 (S n') =\n    fib_co_acc_cps' nat\n                   n'\n                   (fun a1 a0 =>\n                      a1).\nProof.\n  unfold_tactic fib_v7.\nQed.\n\n(* Eureka lemma: *)\n\nLemma about_fib_co_acc_cps' :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall (ans : Type)\n           (n : nat)\n           (k : nat -> nat -> ans),\n      fib_co_acc_cps' ans n k =\n      k (fib (S n)) (fib n).\nProof.\nAbort.\n\n(* The main definition satisfies the specification: *)\n\nTheorem fib_v7_fits_the_specification_of_fibonacci :\n  specification_of_fibonacci fib_v7.\nProof.\nAbort.\n\n(* ********** *)\n\n(* end of week-13_fib.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/week-13_fib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.7401994064412155}}
{"text": "(** * Selection:  Selection Sort, With Specification and Proof of Correctness*)\n(**\n  This sorting algorithm works by choosing (and deleting) the smallest\n  element, then doing it again, and so on.  It takes O(N^2) time.\n\n  You should never* use a selection sort.  If you want a simple\n  quadratic-time sorting algorithm (for small input sizes) you should\n  use insertion sort.  Insertion sort is simpler to implement, runs\n  faster, and is simpler to prove correct.   We use selection sort here\n  only to illustrate the proof techniques.\n\n     *Well, hardly ever.  If the cost of \"moving\" an element is _much_\n  larger than the cost of comparing two keys, then selection sort is\n  better than insertion sort.  But this consideration does not apply in our\n  setting, where the elements are  represented as pointers into the\n  heap, and only the pointers need to be moved.\n\n  What you should really never use is bubble sort.  Bubble sort\n  would be the wrong way to go.  Everybody knows that!\n  https://www.youtube.com/watch?v=k4RRi_ntQc8\n*)\n\n(* ################################################################# *)\n(** * The Selection-Sort Program  *)\n\nRequire Export Coq.Lists.List.\nFrom VFA Require Import Perm.\n\n(** Find (and delete) the smallest element in a list. *)\n\nFixpoint select (x: nat) (l: list nat) : nat * list nat :=\nmatch l with\n|  nil => (x, nil)\n|  h::t => if x <=? h\n               then let (j, l') := select x t in (j, h::l')\n               else let (j,l') := select h t in (j, x::l')\nend.\n\n(** Now, selection-sort works by repeatedly extracting the smallest element,\n   and making a list of the results. *)\n\n(* Uncomment this function, and try it.\nFixpoint selsort l :=\nmatch l with\n| i::r => let (j,r') := select i r\n               in j :: selsort r'\n| nil => nil\nend.\n*)\n\n(** _Error: Recursive call to selsort has principal argument equal\n  to [r'] instead of [r]_.  That is, the recursion is not _structural_, since\n  the list r' is not a structural sublist of (i::r).  One way to fix the\n  problem is to use Coq's [Function] feature, and prove that\n  [length(r')<length(i::r)].  Later in this chapter, we'll show that approach.\n\n  Instead, here we solve this problem is by providing \"fuel\", an additional\n  argument that has no use in the algorithm except to bound the\n  amount of recursion.  The [n] argument, below, is the fuel. *)\n\nFixpoint selsort l n {struct n} :=\nmatch l, n with\n| x::r, S n' => let (y,r') := select x r\n               in y :: selsort r' n'\n| nil, _ => nil\n| _::_, O => nil  (* Oops!  Ran out of fuel! *)\nend.\n\n(** What happens if we run out of fuel before we reach the end\n   of the list?  Then WE GET THE WRONG ANSWER. *)\n\nExample out_of_gas: selsort [3;1;4;1;5] 3 <> [1;1;3;4;5].\nProof.\nsimpl.\nintro. inversion H.\nQed.\n\n(** What happens if we have have too much fuel?  No problem. *)\n\nExample too_much_gas: selsort [3;1;4;1;5] 10 = [1;1;3;4;5].\nProof.\nsimpl.\nauto.\nQed.\n\n(** The selection_sort algorithm provides just enough fuel. *)\n\nDefinition selection_sort l := selsort l (length l).\n\nExample sort_pi: selection_sort [3;1;4;1;5;9;2;6;5;3;5] = [1;1;2;3;3;4;5;5;5;6;9].\nProof.\nunfold selection_sort.\nsimpl.\nreflexivity.\nQed.\n\n(** Specification of correctness of a sorting algorithm:\n   it rearranges the elements into a list that is totally ordered. *)\n\nInductive sorted: list nat -> Prop :=\n | sorted_nil: sorted nil\n | sorted_1: forall i, sorted (i::nil)\n | sorted_cons: forall i j l, i <= j -> sorted (j::l) -> sorted (i::j::l).\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) :=\n  forall al, Permutation al (f al) /\\ sorted (f al).\n\n(* ################################################################# *)\n(** * Proof of Correctness of Selection sort *)\n\n(** Here's what we want to prove. *)\n\nDefinition selection_sort_correct : Prop :=\n    is_a_sorting_algorithm selection_sort.\n\n(** We'll start by working on part 1, permutations. *)\n\n(** **** Exercise: 3 stars (select_perm)  *)\nLemma select_perm: forall x l,\n  let (y,r) := select x l in\n   Permutation (x::l) (y::r).\nProof.\n\n(** NOTE: If you wish, you may [Require Import Multiset] and use the  multiset\n  method, along with the theorem [contents_perm].  If you do,\n  you'll still leave the statement of this theorem unchanged. *)\n\nintros x l; revert x.\ninduction l; intros; simpl in *.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (selection_sort_perm)  *)\nLemma selsort_perm:\n  forall n,\n  forall l, length l = n -> Permutation l (selsort l n).\nProof.\n\n(** NOTE: If you wish, you may [Require Import Multiset] and use the  multiset\n  method, along with the theorem [same_contents_iff_perm]. *)\n\n(* FILL IN HERE *) Admitted.\n\nTheorem selection_sort_perm:\n  forall l, Permutation l (selection_sort l).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (select_smallest)  *)\nLemma select_smallest_aux:\n  forall x al y bl,\n    Forall (fun z => y <= z) bl ->\n    select x al = (y,bl) ->\n    y <= x.\nProof.\n(* Hint: no induction needed in this lemma.\n   Just use existing lemmas about select, along with [Forall_perm] *)\n(* FILL IN HERE *) Admitted.\n\nTheorem select_smallest:\n  forall x al y bl, select x al = (y,bl) ->\n     Forall (fun z => y <= z) bl.\nProof.\nintros x al; revert x; induction al; intros; simpl in *.\n (* FILL IN HERE *) admit.\nbdestruct (x <=? a).\n*\ndestruct (select x al) eqn:?H.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (selection_sort_sorted)  *)\nLemma selection_sort_sorted_aux:\n  forall  y bl,\n   sorted (selsort bl (length bl)) ->\n   Forall (fun z : nat => y <= z) bl ->\n   sorted (y :: selsort bl (length bl)).\nProof.\n (* Hint: no induction needed.  Use lemmas selsort_perm and Forall_perm.*)\n (* FILL IN HERE *) Admitted.\n\nTheorem selection_sort_sorted: forall al, sorted (selection_sort al).\nProof.\nintros.\nunfold selection_sort.\n(* Hint: do induction on the [length] of al.\n    In the inductive case, use [select_smallest], [select_perm],\n    and [selection_sort_sorted_aux]. *)\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now we wrap it all up.  *)\n\nTheorem selection_sort_is_correct: selection_sort_correct.\nProof.\nsplit. apply selection_sort_perm. apply selection_sort_sorted.\nQed.\n\n(* ################################################################# *)\n(** * Recursive Functions That are Not Structurally Recursive *)\n\n(** [Fixpoint] in Coq allows for recursive functions where some\n  parameter is structurally recursive: in every call, the argument\n  passed at that parameter position is an immediate substructure\n  of the corresponding formal parameter.  For recursive functions\n  where that is not the case -- but for which you can still prove\n  that they terminate -- you can use a more advanced feature of\n  Coq, called [Function]. *)\n\nRequire Import Recdef.  (* needed for [Function] feature *)\n\nFunction selsort' l {measure length l} :=\nmatch l with\n| x::r => let (y,r') := select x r\n               in y :: selsort' r'\n| nil => nil\nend.\n\n(** When you use [Function] with [measure], it's your\n  obligation to prove that the measure actually decreases,\n  before you can use the function. *)\n\nProof.\nintros.\npose proof (select_perm x r).\nrewrite teq0 in H.\napply Permutation_length in H.\nsimpl in *; omega.\nDefined.  (* Use [Defined] instead of [Qed], otherwise you\n  can't compute with the function in Coq. *)\n\n(** **** Exercise: 3 stars (selsort'_perm)  *)\nLemma selsort'_perm:\n  forall n,\n  forall l, length l = n -> Permutation l (selsort' l).\nProof.\n\n(** NOTE: If you wish, you may [Require Import Multiset]\n  and use the  multiset method, along with the\n  theorem [same_contents_iff_perm]. *)\n\n(** Important!  Don't unfold [selsort'], or in general, never\n  unfold anything defined with [Function]. Instead, use the\n  recursion equation [selsort'_equation] that is automatically\n  defined by the [Function] command. *)\n\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nEval compute in selsort' [3;1;4;1;5;9;2;6;5].\n\n(** $Date$ *)\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/libs/vfa/Selection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8976953023710936, "lm_q1q2_score": 0.7401156060358138}}
{"text": "Module Type GROUP.\n    Parameter G   : Set.\n    Parameter f   : G -> G -> G.\n    Parameter e   : G.\n    Parameter i   : G -> G.\n    Axiom assoc   : forall (a b c:G), f (f a b) c = f a (f b c).\n    Axiom ident   : forall (a:G), f e a = a.   (* left identity enough ? *)\n    Axiom inverse : forall (a:G), f (i a) a = e.    (* left side enough ? *)\nEnd GROUP.\n\nModule Type GROUP_THEOREMS.\n    Declare Module M : GROUP.\n    Import M.\n    Axiom ident' : forall (a:M.G), M.f a (M.e) = a.\n    Axiom inverse' : forall (a:G), f a (i a) = e.   (* Import M !! *)\n    Axiom unique_e : forall e', (forall a, f e' a = a) -> e' = e.\nEnd GROUP_THEOREMS.\n\nModule GROUP_PROOFS (M:GROUP) : GROUP_THEOREMS with Module M := M.\nModule M := M.\nImport M.\nTheorem inverse' : forall a, f a (i a) = e.\nProof.\n    intros a.\n    rewrite <- (ident (f a (i a))).\n    remember (f e (f a (i a))) as x eqn:E.\n    rewrite <- (inverse (f a (i a))) in E.\n    rewrite assoc in E.\n    rewrite assoc in E.\n    rewrite <- (assoc (i a) a (i a)) in E.\n    rewrite inverse in E.\n    rewrite ident in E.\n    rewrite inverse in E.\n    assumption.\nQed.\n\nTheorem ident' : forall (a:G), f a e = a.\nProof.\n    intros a.\n    rewrite <- (inverse a).\n    rewrite <- assoc.\n    rewrite inverse'.\n    rewrite ident.\n    reflexivity.\nQed.\n\n\nTheorem unique_e : forall (e':G), (forall (a:G), f e' a = a) -> e' = e.\nProof.\n    intros e' H. rewrite <- (ident' e'), H. reflexivity.\nQed.\nEnd GROUP_PROOFS.\n\nRequire Import ZArith.\nOpen Scope Z_scope.\nModule INT.\n    Definition G := Z.\n    Definition f x y := x + y.\n    Definition e := 0.\n    Definition i x := -x.\n    Theorem assoc : forall a b c, f (f a b) c = f a (f b c).\n    Proof. intros a b c. unfold f. ring. Qed.\n    Theorem ident : forall a, f e a = a.\n    Proof. intros a. unfold f. unfold e. ring. Qed.\n    Theorem inverse : forall a, f (i a) a = e.\n        intros a. unfold f, i, e. ring. Qed.\nEnd INT.\n\nModule INT_PROOFS := GROUP_PROOFS(INT).\nImport INT_PROOFS.\n\nCheck unique_e.\n\n\n\n\n\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/cpdt/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7400883098177001}}
{"text": "(* Chap 9 ProofObjects *)\n(* The Curry-Howard Correspondence *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\nPrint even.\n\nCheck ev_SS.\n\nPrint ev_4.\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n\nTheorem ev_4': even 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(* Chap 9.1 Proof Scripts *)\nTheorem ev_4'': even 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\nDefinition ev_4''': even 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\nPrint ev_4.\nPrint ev_4'.\nPrint ev_4''.\nPrint ev_4'''.\n\nTheorem ev_8: even 8.\nProof.\n  apply (ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0)))).\nQed.\n\nDefinition ev_8': even 8 :=\n  (ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0)))).\n\n(* Chap 9.2 Quantifiers, Implications, Functions *)\nTheorem ev_plus4: forall n, even n -> even (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\nDefinition ev_plus4': forall n, even n -> even (4 + n) :=\n  fun (n: nat) => fun (H: even n) => ev_SS (S (S n)) (ev_SS n H).\n\nDefinition ev_plus2: Prop :=\n  forall n, forall (E: even n), even (n + 2).\n\nDefinition ev_plus2': Prop :=\n  forall n, forall (_: even n), even (n + 2).\n\nDefinition ev_plus2'': Prop :=\n  forall n, even n -> even (n + 2).\n\n(* Chap 9.3 Programming with Tactics *)\nDefinition add1: nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n.\nShow Proof.\nDefined.\n\nPrint add1.\n\n(* Chap 9.4 Logical Connectives as Inductive Types *)\nModule Props.\n\n(* Chap 9.4.1 Conjunction *)\nModule And.\n\nInductive and (P Q: Prop) : Prop :=\n  | conj: P -> Q -> and P Q.\n\nEnd And.\n\nPrint prod.\n\nLemma and_comm: forall P Q: Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\nQed.\n\nDefinition and_comm'_aux P Q (H: P /\\ Q) : Q /\\ P :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q: P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(* Exercise conj_fact *)\nDefinition conj_fact: forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun (P Q R: Prop) (H1: P /\\ Q) (H2: Q /\\ R) =>\n  match H1, H2 with\n  | conj p q, conj q' r => conj p r\n  end.\n\n(* Chap 9.4.2 Disjunction *)\nModule Or.\n\nInductive or (P Q: Prop) : Prop :=\n  | or_introl: P -> or P Q\n  | or_intror: Q -> or P Q.\n\nEnd Or.\n\n(* Exercise op_commut'' *)\nDefinition or_comm: forall P Q, P \\/ Q -> Q \\/ P :=\n  fun (P Q: Prop) (H: P \\/ Q) =>\n  match H with\n  | or_introl P => or_intror P\n  | or_intror P => or_introl P\n  end.\n\n(* Chap 9.4.3 Existential Quantification *)\nModule Ex.\n\nInductive ex {A: Type} (P: A -> Prop) :=\n  | ex_intro: forall x: A, P x -> ex P.\n\nEnd Ex.\n\nCheck ex (fun n => even n).\n\nDefinition some_nat_is_even: exists n, even n :=\n  ex_intro even 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(* Exercise ex_ev_Sn *)\nDefinition ex_ev_Sn: ex (fun n => even (S n)) :=\n  ex_intro (fun n => even (S n)) 1 (ev_SS 0 ev_0).\n\n(* Chap 9.4.4 True and False *)\nInductive True : Prop :=\n  | I: True.\n\nInductive False: Prop := .\n\nEnd Props.\n\n(* Chap 9.5 Equality *)\nModule MyEquality.\n\nInductive eq {X: Type}: X -> X -> Prop :=\n  | eq_refl: forall x, eq x x.\n\nNotation \"x == y\" := (eq x y)\n  (at level 70, no associativity) : type_scope.\n\nLemma four: 2 + 2 == 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\nDefinition four': 2 + 2 == 1 + 3 := eq_refl 4.\n\nDefinition singleton: forall (X: Type) (x: X),\n  [] ++ [x] == x :: [] :=\n  fun (X: Type) (x: X) => eq_refl [x].\n\n(* Exercise equality__leibniz_equality *)\nLemma equality__leibniz_equality: forall (X: Type) (x y: X),\n  x == y -> forall P: X -> Prop, P x -> P y.\nProof.\n  intros X x y.\n  intros.\n  inversion H.\n  rewrite H2 in H0.\n  apply H0.\nQed.\n\n(* Exercise leibniz_equality__equality *)\nLemma leibniz_equality__equality: forall (X: Type) (x y: X),\n  (forall P: X -> Prop, P x -> P y) -> x == y.\nProof.\n  intros.\n  assert(I: x = x -> x = y).\n  { apply H. }\n  replace y with x.\n  apply eq_refl.\n  apply I.\n  reflexivity.\nQed.\n\nEnd MyEquality.\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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7399618603134566}}
{"text": "From LF Require Export exercise3.\nFrom LF Require Export exercise2.\nFrom LF Require Export exercise1.\n\nInductive list (X: Type) : Type :=\n  | nil\n  | cons (x: X) (l : list X).\n\nArguments nil {X}.\nArguments cons {X}.\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nDefinition mynil := @nil nat.\nCheck mynil.\nFail Definition mynil' := nil nat.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** **** Exercise: 2 stars, standard (poly_exercises)\nHere are a few simple exercises, just like ones in the Lists chapter, for practice with polymorphism. Complete the proofs below. *)\nTheorem app_nil_r : forall (X : Type), forall l : list X,\n  l ++ [] = l.\nProof.\n  intros X l.\n  induction l as [| n l' H].\n  - reflexivity.\n  - simpl. rewrite H. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n : list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma app_length : forall (X : Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros. induction l1.\n  - reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard (more_poly_exercises) *)\n(* Here are some slightly more interesting ones... *)\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros. induction l1.\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite IHl1. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl. reflexivity.\nQed.\n\nInductive prod (X Y : Type) : Type :=\n  | pair (x : X) (y : Y).\nArguments pair {X} {Y}.\n\nNotation \"( x , y )\" := (pair x y).\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n  : list (X * Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(* Prints @pair: forall X Y, Type, X -> Y -> X * Y. *)\nCheck @pair.\n(* Prints  [(1, false); (2, false)] *)\nCompute (combine [1;2] [false;false;true;true]).\n\n(** **** Exercise: 2 stars, standard, especially useful (split) *)\n(* The function split is the right inverse of combine: it takes a list of pairs and returns a pair of lists. In many functional languages, it is called unzip. *)\n(* Fill in the definition of split below. Make sure it passes the given unit test. *)\nFixpoint split {X Y : Type} (l : list (X * Y)) : (list X) * (list Y) := \n  match l with\n  | [] => ([], [])\n  | (x, y) :: l' => ((x :: fst (split l')), (y :: snd (split l')))\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. simpl. reflexivity. Qed.\n\nFixpoint filter {X : Type} (pred : X -> bool) (l : list X) : list X :=\n  match l with\n  | nil => nil\n  | h :: t => \n    if pred h then h :: (filter pred t)\n    else (filter pred t)\n  end.\n\nExample test_filter2:\n  filter (fun l => (length l) =? 1 )\n         [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. simpl. reflexivity. Qed.\n\n(** **** Exercise: 3 stars, standard (partition) *)\n(* Use filter to write a Coq function partition:\n      partition : ∀ X : Type,\n                  (X → bool) → list X → list X × list X\nGiven a set X, a predicate of type X → bool and a list X, partition should return a pair of lists. The first\nmember of the pair is the sublist of the original list containing the elements that satisfy the test, and the\nsecond is the sublist containing those that fail the test. The order of elements in the two sublists should be\nthe same as their order in the original list. *)\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n  match l with\n  | [] => ([], [])\n  | _ => ((filter test l), (filter (fun X => negb (test X)) (l)))\n  end.\n\nExample test_partition1: partition odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. simpl. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. simpl. reflexivity. Qed.\n\n(* It takes a function f and a list l = [n1, n2, n3, ...] and returns the list [f n1, f n2, f n3,...]. *)\nFixpoint map {X Y : Type} (f : X -> Y) (l : list X) : list Y :=\n  match l with\n  | [] => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** **** Exercise: 3 stars, standard (map_rev) *)\n(* Show that map and rev commute. You may need to define an auxiliary lemma. *)\nLemma map_f_assoc: forall (X Y: Type) (f : X -> Y) (l1 l2: list X),\n  map f (l1 ++ l2) = (map f l1) ++ (map f l2).\nProof.\n  intros. induction l1.\n  - reflexivity.\n  - simpl. rewrite IHl1. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. rewrite <- IHl. rewrite -> map_f_assoc. reflexivity.\nQed.\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\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\n(** **** Exercise: 2 stars, standard, especially useful (flat_map) *)\n(* The function map maps a list X to a list Y using a function of type X → Y. We can define a similar function,\nflat_map, which maps a list X to a list Y using a function f of type X → list Y. Your definition should work by\n'flattening' the results of f, like so:\n        flat_map (fun n ⇒ [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12]. *)\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : list Y :=\n  match l with\n  | [] => []\n  | h :: t => ((f h) ++ (flat_map f t))\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. simpl. reflexivity. Qed.\n\nFixpoint fold {X Y: Type} (f : X -> Y -> Y) (l : list X) (b : Y)\n                         : Y :=\n  match l with\n  | [] => b\n  | h :: t => f h (fold f t b)\n  end.\n", "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/exercise4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.7399618602186683}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (x : natural) : natural :=\n  plus y (mult x (Succ y)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj144_coqofml_bTjJhz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7399529695040982}}
{"text": "Require Export Shared.Prelim.\n\nDefinition reduces X Y (p : X -> Prop) (q : Y -> Prop) := exists f : X -> Y, forall x, p x <-> q (f x).\nNotation \"p ⪯ q\" := (reduces p q) (at level 50).\n\nLemma reduces_reflexive X (p : X -> Prop) : p ⪯ p.\nProof. exists (fun x => x); tauto. Qed.\n\nLemma reduces_transitive X Y Z (p : X -> Prop) (q : Y -> Prop) (r : Z -> Prop) :\n  p ⪯ q -> q ⪯ r -> p ⪯ r.\nProof.\n  intros [f ?] [g ?]. exists (fun x => g (f x)). firstorder.\nQed.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/Problems/Reduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7399305094577906}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Continuity.\n\nInductive homeomorphism {X Y:TopologicalSpace}\n  (f:point_set X -> point_set Y) : Prop :=\n| intro_homeomorphism: forall g:point_set Y -> point_set X,\n  continuous f -> continuous g ->\n  (forall x:point_set X, g (f x) = x) ->\n  (forall y:point_set Y, f (g y) = y) -> homeomorphism f.\n\nLemma homeomorphism_is_invertible: forall {X Y:TopologicalSpace}\n  (f:point_set X -> point_set Y),\n  homeomorphism f -> invertible f.\nProof.\nintros.\ndestruct H as [g].\nexists g; trivial.\nQed.\n\nDefinition open_map {X Y:TopologicalSpace}\n  (f:point_set X -> point_set Y) : Prop :=\nforall U:Ensemble (point_set X), open U -> open (Im U f).\n\nLemma homeomorphism_is_open_map: forall {X Y:TopologicalSpace}\n  (f:point_set X -> point_set Y),\n  homeomorphism f -> open_map f.\nProof.\nintros.\ndestruct H as [g].\nred; intros.\nassert (Im U f = inverse_image g U).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H4.\nrewrite H5.\nconstructor.\nrewrite H1; trivial.\ndestruct H4.\nexists (g x); trivial.\nsymmetry; apply H2.\nrewrite H4; apply H0; trivial.\nQed.\n\nLemma invertible_open_map_is_homeomorphism: forall {X Y:TopologicalSpace}\n  (f:point_set X -> point_set Y),\n  invertible f -> continuous f -> open_map f -> homeomorphism f.\nProof.\nintros.\ndestruct H as [g].\nexists g; trivial.\nred; intros.\nassert (inverse_image g V = Im V f).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H4.\nexists (g x); trivial.\nsymmetry; apply H2.\ndestruct H4.\nconstructor.\nrewrite H5.\nrewrite H; trivial.\nrewrite H4; apply H1; trivial.\nQed.\n\nInductive homeomorphic (X Y:TopologicalSpace) : Prop :=\n| intro_homeomorphic: forall f:point_set X -> point_set Y,\n    homeomorphism f -> homeomorphic X Y.\n\nRequire Export Relation_Definitions.\nRequire Import Relation_Definitions_Implicit.\n\nLemma homeomorphic_equiv: equivalence homeomorphic.\nProof.\nconstructor.\nred; intros X.\nexists (fun x:point_set X => x).\nexists (fun x:point_set X => x); trivial;\n  apply continuous_identity.\n\nred; intros X Y Z ? ?.\ndestruct H as [f [finv]].\ndestruct H0 as [g [ginv]].\nexists (fun x:point_set X => g (f x)).\nexists (fun z:point_set Z => finv (ginv z)); (congruence ||\n  apply continuous_composition; trivial).\n\nred; intros X Y ?.\ndestruct H as [f [finv]].\nexists finv; exists f; trivial.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/Homeomorphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7397330090667543}}
{"text": "(* A typeclass representing an upper semilattice. A small number\n   of useful lemmas are proven that we end up using in\n   type_system.v to show non-interference *)\n\n(* See poset.v for more discussion around typeclasses and what\n   we use them for. *)\n\n(* TODO: move these citations to poset.v? *)\n\n(* lattice stuff influenced by A reflection-based\nproof tactic for lattices in Coq by Daniel James\nand Ralf Hinze *)\n\n(* also: A Gentle Introducton to Type Classes and\n    Relations in Coq by Pierre Casteran *)\n\n\n\n(* An upper semilattice is a poset with additional properties *)\n\nRequire Import poset.\n\nClass UpperSemilattice\n  {A} {precedes} (P : Poset A precedes)\n  (join : A -> A -> A) (bottom : A) := {\n    join_commutative : forall a b, join a b = join b a;\n    join_associative : forall a b c,\n      join (join a b) c = join a (join b c);\n    join_idempotent : forall a, join a a = a;\n    bottom_prop : forall a, join bottom a = a;\n    order_induction : forall a b, precedes a b <-> join a b = b\n}.\n\nLemma precedes_join\n  {A} {precedes} {P : Poset A precedes}\n  {join} {bottom} {USL : UpperSemilattice P join bottom}\n  a b :\n  precedes a (join a b).\nProof.\n  apply order_induction.\n  rewrite <- join_associative. now rewrite join_idempotent.\nQed.\n\nLemma precedes_join2\n  {A} {precedes} {P : Poset A precedes}\n  {join} {bottom} {USL : UpperSemilattice P join bottom}\n  a b c :\n  precedes a b -> precedes a (join b c).\nProof.\n  intros H. apply order_induction in H.\n  apply order_induction.\n  rewrite <- join_associative. now rewrite H.\nQed.\n\nLemma precedes_join3\n  {A} {precedes} {P : Poset A precedes}\n  {join} {bottom} {USL : UpperSemilattice P join bottom}\n  a b c :\n  precedes a c -> precedes a (join b c).\nProof.\n  intros. apply order_induction. rewrite <- join_associative.\n  assert (join a b = join b a) as Hab_comm by apply join_commutative.\n  rewrite Hab_comm, join_associative.\n  apply order_induction in H. now rewrite H.\nQed.\n", "meta": {"author": "adamsmasher", "repo": "thesis", "sha": "98e4e77c80be04e2256ee52d0f5a024edf2bdb93", "save_path": "github-repos/coq/adamsmasher-thesis", "path": "github-repos/coq/adamsmasher-thesis/thesis-98e4e77c80be04e2256ee52d0f5a024edf2bdb93/semilattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7397330041549705}}
{"text": "Require Export MoreLogic.\n\nTheorem six_is_beautiful: beautiful 6.\nProof.\n  apply b_sum with (n:=3) (m:=3).\n  apply b_3.\n  apply b_3.\nQed.\n\nDefinition six_is_beautiful': beautiful 6 :=\n  b_sum 3 3 b_3 b_3.\n\nTheorem nine_is_beautiful: beautiful 9.\nProof.\n  apply b_sum with (n:=3) (m:=6).\n  apply b_3.\n  apply six_is_beautiful.\nQed.\n\nDefinition nine_is_beautiful': beautiful 9 :=\n  b_sum 3 6 b_3 six_is_beautiful.\n\nTheorem b_plus3: forall n, beautiful n -> beautiful (3+n).\nProof.\n  intros n H.\n  apply b_sum.\n  apply b_3.\n  apply H.\nQed.\n\nDefinition b_plus3': forall n, beautiful n -> beautiful (3+n) :=\n  fun (n:nat) => fun (H:beautiful n) =>\n                   b_sum 3 n b_3 H.\n\nDefinition b_plus3'' (n:nat) (H:beautiful n) : beautiful (3+n) :=\n  b_sum 3 n b_3 H.\n\nDefinition b_times2' : forall n, beautiful n -> beautiful (2*n) :=\n  fun (n:nat) => fun (H:beautiful n) =>\n                   b_sum n (n + 0) H (b_sum n 0 H b_0).\n\nDefinition gorgeous_plus13_po : forall n, gorgeous n -> gorgeous (13 + n) :=\n  fun (n:nat) => fun (H:gorgeous n) =>\n                   g_plus3 (10 + n)\n                           (g_plus5 (5 + n)\n                                    (g_plus5 n H)).\n\nDefinition conj_fact : forall P Q R, P /\\ Q  -> Q /\\ R -> P /\\ R :=\n  fun (P Q R : Prop) (H1: P /\\ Q) =>\n    fun (H2: Q /\\ R) =>\n      match H1 with\n        | conj HP HQ =>\n          match H2 with\n            | conj HQ HR => conj P R HP HR\n          end\n      end.\n\nDefinition beautiful_iff_gorgeous : forall n, beautiful n <-> gorgeous n :=\n  fun (n:nat) =>\n    conj (beautiful n -> gorgeous n)\n         (gorgeous n -> beautiful n)\n         (beautiful__gorgeous n)\n         (gorgeous__beautiful n).\n\nDefinition or_commut'' : forall P Q, P \\/ Q -> Q \\/ P :=\n  fun (P Q : Prop) =>\n    fun (HPQ : P \\/ Q) =>\n      match HPQ with\n        | or_introl HP => or_intror Q P HP\n        | or_intror HQ => or_introl Q P HQ\n      end.\n\nLemma plus_comm_r : forall a b c, c + (b + a) = c + (a + b).\nProof.\n  intros a b c.\n  rewrite (plus_comm b a).\n  reflexivity.\nQed.\n\nLemma plus_comm_r' : forall a b c, c + (b + a) = c + (a + b).\nProof.\n  intros a b c.\n  rewrite (plus_comm b).\n  reflexivity.\nQed.\n\nLemma plus_comm_r'' : forall a b c, c + (b + a) = c + (a + b).\nProof.\n  intros a b c.\n  rewrite (plus_comm _ a).\n  reflexivity.\nQed.\n\nLemma plus_comm_r''' : forall a b c, c + (b + a) = c + (a + b).\nProof.\n  intros a b c.\n  rewrite plus_comm with (n := b).\n  reflexivity.\nQed.\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n                              [a;b] = [c;d] ->\n                              [c;d] = [e;f] ->\n                              [a;b] = [e;f].\nProof.\n  intros a b c d e f H1 H2.\n  apply (trans_eq _ _ [c;d]).\n  apply H1.\n  apply H2.\nQed.\n", "meta": {"author": "micxjo", "repo": "sf", "sha": "a3a841e52ba88baddedea691259086520d0b85bd", "save_path": "github-repos/coq/micxjo-sf", "path": "github-repos/coq/micxjo-sf/sf-a3a841e52ba88baddedea691259086520d0b85bd/src/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7397330037456595}}
{"text": "(** * Conceptual Foundations *)\n\nRequire Coq.Arith.EqNat.\n\nSection ConceptualFoundations.\n\n(** ** Thought Experiment\n\n    Consider a proposition [is_my_favorite_number]. *)\n\nVariable is_my_favorite_number : nat -> Prop.\n\n(** Let's assume that [3] is my favorite number. *)\n\nVariable three_is_my_favorite_number : is_my_favorite_number 3.\n\n(** Now we'll prove a simple fact about my favorite number. *)\n\nFact one_plus_my_favorite_number_is_four :\n  forall n,\n  is_my_favorite_number n ->\n  1 + n = 4.\nProof.\n  intros n H.\n  Fail inversion H.\n  Abort.\n\n(** Oops. Something went wrong. Intuitively, using [inversion] on [H]\n    should yield a hypothesis of type [n = 3]. However, the [inversion]\n    tactic fails with \"Error: The type of H is not inductive.\" We are\n    forced to [Abort] the proof.\n\n    Why did this happen? The error indicates it has something to do with\n    induction.\n\n    Let's try another proof to better understand the issue. *)\n\nFact zero_is_not_my_favorite_number :\n  ~(is_my_favorite_number 0).\nProof.\n  intros H.\n  Fail inversion H.\n  Abort.\n\n(** Interesting. We cannot prove that zero is not my favorite number,\n    and we know it has something to do with induction.\n\n    The root of the problem is that we can prove the following: *)\n\nFact three_implies_is_my_favorite_number :\n  forall n,\n  n = 3 ->\n  is_my_favorite_number n.\nProof.\n  intros. subst n.\n  apply three_is_my_favorite_number.\n  Qed.\n\n(** But we cannot prove its inverse: *)\n\nFact is_my_favorite_number_implies_three :\n  forall n,\n  is_my_favorite_number n ->\n  n = 3.\nProof.\n  intros.\n  Fail inversion H.\n  Abort.\n\n(** Let's try again with an inductive definition of\n    [is_my_favorite_number]. *)\n\nInductive is_my_favorite_number_inductive : nat -> Prop :=\n  | three_is_my_favorite_number_inductive : is_my_favorite_number_inductive 3.\n\n(** And let's try those same proofs again. *)\n\nFact one_plus_my_favorite_number_is_four' :\n  forall n,\n  is_my_favorite_number_inductive n ->\n  1 + n = 4.\nProof.\n  intros n H.\n  inversion H.\n  reflexivity.\n  Qed.\n\nFact zero_is_not_my_favorite_number' :\n  ~(is_my_favorite_number_inductive 0).\nProof.\n  intros H.\n  inversion H.\n  Qed.\n\n(** The proofs succeed. But why?\n\n    The key is that our inductive definition says more than just [3] is\n    my favorite number. It also says that [3] is the _ONLY_ number that\n    is my favorite number. In other words, no other number satisfies the\n    [is_my_favorite_number_inductive] proposition.\n\n    In more mathematical terms, the only inhabitants of the proof type\n    [is_my_favorite_number_inductive n] are those listed in the\n    inductive definition. In this case, the only inhabitant of the proof\n    type is [three_is_my_favorite_number_inductive]. Note that\n    [three_is_my_favorite_number_inductive] is literally a proof of\n    [is_my_favorite_number_inductive 3].\n\n    We are able to use the [inversion] tactic on an inductive definition\n    because the inductive definition enumerates _ALL_ the proofs which\n    inhabit the proof type. Therefore, we can do case analysis by\n    looking at each possible inhabitant one at a time.\n\n    Note that we can achieve a similar effect without induction by\n    defining cases when [is_my_favorite_number] is [False]. *)\n\nVariable no_number_besides_three_is_my_favorite_number:\n  forall n,\n  n <> 3 -> ~(is_my_favorite_number n).\n\nFact one_plus_my_favorite_number_is_four'' :\n  forall n,\n  is_my_favorite_number n ->\n  1 + n = 4.\nProof.\n  intros n H.\n  destruct (EqNat.beq_nat n 3) eqn:H0.\n  - apply EqNat.beq_nat_true_iff in H0. subst n. reflexivity.\n  - apply EqNat.beq_nat_false_iff in H0.\n    apply no_number_besides_three_is_my_favorite_number in H0.\n    apply H0 in H. inversion H.\n  Qed.\n\nFact zero_is_not_my_favorite_number'' :\n  ~(is_my_favorite_number 0).\nProof.\n  apply no_number_besides_three_is_my_favorite_number.\n  intros H. inversion H.\n  Qed.\n\n(** Without induction, the proofs are more convoluted.\n\n    Note that inductive definitions also have other advantages besides\n    simpler proofs. Namely, Coq auto generates induction rules for\n    inductive definitions.\n\n    ** Inductive Definitions, Concrete Classes\n\n    Conceptually, an inductive definition fully defines and constrains\n    all inhabitants of its type. After an inductive definition is\n    established, we cannot define any additional inhabitants of the\n    type. This has important consequences for modelling object oriented\n    software in Coq.\n\n    Consider what happens when we use an inductive definition to define\n    the behavior of a class. The inductive definition says everything\n    that the class does. Furthermore, it says that the class does not do\n    anything else. The latter restriction means that we cannot implement\n    _any_ variant or additional behavior in a subclass. Therefore,\n    inductive definitions are not suitable for abstract classes and\n    interfaces. They are only suitable for concrete classes. To put it\n    another way: once we have an inductive definition of a class, we\n    have explicitly defined all members of the class. No additional\n    members (subclasses) can be added after that point.\n\n    It is important to note that by defining class behavior inductively,\n    we are relieved of the burden of stating what the class does _not_\n    do. This is just like the example above: to use the non-inductive\n    definition of [is_my_favorite_number] we had to define all cases\n    where [is_my_favorite_number] is [False]. With the inductive\n    definition, we did not need to enumerate the [False] cases; the\n    inductive definition takes care of that for us. If we apply this\n    concept to class definitions, this is good news. There are\n    infinitely many things that a class does _not_ do, so it's a good\n    thing that we don't have to enumerate them.\n\n    Consider further that enumerating both [True] and [False] cases is\n    inherently error-prone and dangerous. What if we accidentally\n    introduce some overlap between the [True] and [False] cases? Then\n    we have an inconsistency, and the principle of explosion applies.\n\n    ** Regular Definitions, Abstract Classes\n\n    Contrast an inductive definition with a regular definition. When we\n    define a type with a regular definition, we do not know how many\n    inhabitants the type has. In fact, the inhabitants of the type may\n    be uncountable. We can define inhabitants later, and verify that\n    they satisfy the definition.\n\n    This means regular definitions are suitable for defining the\n    behavior of abstract classes and interfaces. We define certain\n    constraints, certain propositions that must be satisified by the\n    class. We define _some_ of the things that the class must do. But\n    unlike the inductive definition, we allow the class to have variant\n    behavior. As long as our constraints are still met, the class can do\n    whatever else it wants. This enables subclassing.\n\n    Unlike an inductive definition, a regular definition allows us to\n    enumerate both [True] and [False] cases. This opens the door for us\n    to introduce inconsistencies. But in this case, we do not get \"ex\n    falso quodlibet.\" Instead, we get a logically inconsistent abstract\n    specification which cannot be inhabited by any concrete class.\n\n    The flexibility of a regular definition is both a blessing and a\n    curse. As long as our constraints are met, a subclass can do\n    whatever else it wants. This means a subclass could set all\n    variables to null in every object presently in memory, as long as\n    our specification does not specifically preclude it.\n\n    Aside: To make another analogy, inductive definitions and regular\n    definitions are like two different ways to interpret the law: the\n    _inductive_ man says \"If the law does not explicitly allow it, then\n    it is illegal,\" while the _regular_ man says \"If the law does not\n    explicitly forbid it, then it is perfectly legal.\" It's the\n    difference between a blacklist (regular definition) and a whitelist\n    (inductive definition).\n\n    ** Consequences\n\n    What are the consequences for software modelling? Should our\n    abstract specifications preclude all undesired behavior? No. There\n    are infinitely many things that a class should _not_ do, so we\n    cannot hope to enumerate them. Furthermore, when we define an\n    abstract specification, we cannot possibly envision all variant\n    implementations of that specification, so we cannot clearly define\n    what is \"undesired behavior.\" Consider for example, an abstract\n    specification for a function that is expected to be side-effect\n    free. One way to express this is to specify that the function\n    terminates in the same state that it started in. But this precludes\n    a subclass from, for example, logging the function call to an\n    external log. Certainly it is not acceptable for an abstract\n    specification to preclude this.\n\n    So, abstract specifications cannot preclude all undesired behavior.\n    This leads to an important question: can we prove properties of a\n    class that is client to an abstract class and guarantee that those\n    properties will hold for any implementation of the abstract class?\n    And the answer is: in some cases we can, but in the general case\n    we cannot. Consider for example an IteratorConcatenator class that\n    takes two abstract Iterators and iterates over one, then the\n    other. Can we prove that the IteratorConcatenator behaves as\n    expected for any abstract Iterator? No, we cannot. Here is a counter\n    example: if we pass in the same Iterator twice, the expected\n    behavior fails. Even if we add in an extra precondition that says\n    \"the two Iterators are not the same object,\" then we can break\n    the behavior by passing in two objects which are wrappers around\n    the same internal Iterator object. The list of possible failure\n    conditions is infinite. However, we can prove that the\n    IteratorConcatenator behaves as expected for a specific set of\n    concrete Iterators. In other words, we can prove that\n    IteratorConcatenator behaves as expected for a single, fully-defined\n    state.\n\n    Therefore, while there are some properties we can verify over a\n    range of states, in the general case we can only verify the behavior\n    of a class in a particular, fully-defined state. This means in order\n    to verify behavior, we have to select concrete classes for all\n    abstractions, instantiate all the needed objects, configure all\n    client-supplier dependencies (dependency injection), and then we can\n    prove properties of the resulting state. Indeed this fact will shape\n    much of our verification efforts.\n\n    But how useful is the method if we can only verify against specific\n    states? There are several advantages over traditional testing.\n\n    - We can rigorously prove that an object in a particular state\n      conforms to an entire abstract specification. This is something\n      that is impossible to do in traditional testing.\n    - We can reuse abstract specifications to verify multiple classes.\n    - We can make stronger assertions about the behavior of our\n      software. For example, we can verify that a function terminates in\n      the same state that it was called in. We can verify that a\n      particular program does not leak memory. These things are\n      impossible to do in traditional testing.\n    - Finally, sometimes we are not restricted to a fully fixed state.\n      Sometimes we can prove properties over a range of states.\n\n\n    These limitations apply also to the input to our program: sometimes\n    we can prove a property for any input, but in the general case we\n    can prove a property only for a specific input. Bear in mind that to\n    prove a property for any input, we have to do case analysis on the\n    input. Such case analysis is only possible if we can define the\n    input inductively.\n\n    In conclusion, some properties can be proven over a range of states,\n    but in the general case, we can only prove a property for a specific\n    state. In other words, we cannot prove that a class always conforms\n    to an abstract specification, but we can prove that _there exists_ a\n    state in which the class conforms to the abstract specification. *)\n\nEnd ConceptualFoundations.\n\n", "meta": {"author": "jlapolla", "repo": "coq-oo", "sha": "510e5e471d06c1fa805528cff305e6a287e74686", "save_path": "github-repos/coq/jlapolla-coq-oo", "path": "github-repos/coq/jlapolla-coq-oo/coq-oo-510e5e471d06c1fa805528cff305e6a287e74686/Software/Doc/ConceptualFoundations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.8723473730188542, "lm_q1q2_score": 0.7397224464255828}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : Lst) (qreva_arg1 : Lst) : Lst\n           := match qreva_arg0, qreva_arg1 with\n              | nil, x => x\n              | cons z x, y => qreva x (cons z y)\n              end.\n\nLemma append_assoc : forall (x y z : Lst), append (append x y) z = append x (append y z).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma qreva_rev : forall (x y : Lst), qreva x y = append (rev x) y.\nProof.\n  induction x.\n  - reflexivity.\n  - intros. simpl. rewrite IHx. rewrite append_assoc. simpl. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (qreva (qreva x y) nil) (append (rev y) x).\nProof.\n  induction x.\n  - intros. simpl. rewrite qreva_rev. reflexivity.\n  - intros. simpl. rewrite IHx. simpl. rewrite append_assoc. simpl. reflexivity.\nQed.\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal81.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7397224405285346}}
{"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    admit.\nQed.\n\n\nLemma length_map {A B} (lst : list A) (f : A -> B):\n    length (map f lst) = length lst.\nProof.\n    admit.\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    admit.\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    admit.\nQed.\n\nLemma concat_assoc {A} (lst1 lst2 lst3 : list A):\n    concat (concat lst1 lst2) lst3 = concat lst1 (concat lst2 lst3).\nProof.\n    admit.\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    admit.\nQed.\n\n\n(* -------------------------------------------------------------------------- *]\n Induction needs to be performed at a general enough level in order to complete\n the following proof. If we try to first introduce all hypotheses, we get an\n 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    admit.\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    admit.\nQed.\n\n\nLemma mirror_mirror {A} (t : @tree A) :\n    mirror (mirror t) = t.\nProof.\n    admit.\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/proving_things_we_know.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7397224405285346}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Euclid Omega.\n\nRequire Import utils.\n\nSet Implicit Arguments.\n\nLocal Infix \"div\" := (nat_divides) (at level 70). \n\nSection Floyd_cycle_finding_algo.\n\n  Variables (X : Type) (eqdec : forall x y : X, { x = y } + { x <> y }).\n  \n  Variables (f : X -> X) (x0 : X) (Hx0 : exists τ, 0 < τ /\\ f↑τ x0 = f↑(2*τ) x0).\n  \n  (** the sequence starting at x leads to a cycle *)\n                \n  Let ends_in_cycle x := exists λ μ, 0 < μ /\\ f↑λ x = f↑(λ+μ) x.\n  \n  (** the tortoise and the hare will meet *)\n    \n  Let tortoise_meets_hare x := exists τ, 0 < τ /\\ f↑τ x = f↑(2*τ) x.\n  \n  (** x is a loop of f *)\n  \n  Definition iter_in_cycle x := exists k, 0 < k /\\ x = f↑k x.\n\n  (** k is a period of the loop when starting from x *)\n\n  Definition iter_is_period x k := 0 < k /\\ exists l, f↑l x = f↑(k+l) x.\n  \n  Ltac iter_in_cycle_tac :=\n    match goal with \n      | H: f↑?n ?x = f↑(?a+?n) ?x |- iter_in_cycle (f↑?n ?x) => exists a; split; auto; finish with H \n      | H: ?x = f↑?a ?x           |- iter_in_cycle ?x        => exists a; split; auto; finish with H\n      end.\n      \n  Ltac iter_is_period_tac :=\n    match goal with \n      | H: f↑?n ?x = f↑(?a+?n) ?x   |- iter_is_period ?x ?a => split; auto; try omega; exists n; finish with H\n      | H: f↑?n ?x = f↑?a (f↑?n ?x) |- iter_is_period ?x ?a => split; auto; try omega; exists n; finish with H\n    end.\n    \n  Hint Extern 4 (iter_in_cycle _)    => iter_in_cycle_tac.\n  Hint Extern 4 (iter_is_period _ _) => iter_is_period_tac.\n  \n  Fact iter_in_cycle_period x l k : \n         iter_in_cycle (f↑l x) \n      -> iter_is_period x k\n      -> f↑l x = f↑(l+k) x.  \n  Proof.\n    intros (p & Hp1 & Hp2) (Hk1 & m & Hm).\n    rewrite <- iter_plus in Hp2.\n    rewrite plus_comm; revert Hm Hp2; apply iter_xchg; auto.\n  Qed.\n\n  Section compute_meeting_point.\n\n    Inductive bar_th x y : Prop :=\n      | in_bar_th_0 : x = y                  -> bar_th x y \n      | in_bar_th_1 : bar_th (f x) (f (f y)) -> bar_th x y.\n\n    Let bar_th_meet : forall x y, bar_th x y -> { c | exists k, c = f↑k x /\\ c = f↑(2*k) y }.\n    Proof.\n      refine(fix loop x y H {struct H} := \n           match eqdec x y with\n               | left E  => exist _ x _\n               | right C => match loop (f x) (f (f y)) _ with\n                              | exist _ c Hc => exist _ c _\n                            end\n           end).\n      * exists 0; subst; simpl; split; trivial.\n      * destruct H; auto; contradict C; trivial.\n      * destruct Hc as (k & H1 & H2).\n        exists (S k).\n        rewrite H1 at 1; rewrite H2.\n        split; eq iter.\n    Qed.\n\n    Let bar_th_fx0_ffx0 : bar_th (f x0) (f (f x0)).\n    Proof.\n      destruct Hx0 as (k & H3 & H4).\n      apply in_bar_th_0 in H4.\n      revert k H3 H4; apply nat_rev_ind.\n      intros ? H; apply in_bar_th_1; finish with H.\n    Qed.\n\n    Definition floyd_meeting_pt : { c | exists τ, 0 < τ /\\ c = f↑τ x0 /\\ c = f↑(2*τ) x0 }.\n    Proof.\n      refine (match bar_th_meet bar_th_fx0_ffx0 with\n                | exist _ c Hc => exist _ c _\n              end).\n      destruct Hc as (k & H1 & H2).\n      exists (S k); split; try omega.\n      rewrite H1 at 1; rewrite H2.\n      split; eq iter.\n    Defined.\n    \n  End compute_meeting_point.\n  \n  Section compute_index.\n  \n    Inductive bar_in i x y : Prop :=\n      | in_bar_in_0 : x = y                    -> bar_in i x y\n      | in_bar_in_1 : bar_in (S i) (f x) (f y) -> bar_in i x y.\n      \n    Let iter_bar_in n x y : bar_in n (f↑n x) (f↑n y) -> bar_in 0 x y.\n    Proof.\n      generalize n (le_O_n n); apply nat_rev_ind.\n      constructor 2; auto.\n    Qed.\n      \n    Let bar_in_inv : forall i x y, bar_in i x y -> least_le (fun n => i <= n /\\ f↑(n-i) x = f↑(n-i) y).\n    Proof.\n      refine (fix loop i x y H { struct H } := \n            match eqdec x y with\n              | left  E => exist _ i _\n              | right N => match loop (S i) (f x) (f y) _ with\n                             | exist _ n Hn => exist _ n _\n                           end\n            end).\n      * split; subst; auto.\n        intros ? []; auto.\n      * destruct H; auto; destruct N; auto.\n      * destruct Hn as ((H1 & H2) & H3); split.\n        - split; try omega; finish with H2.\n        - intros k (H4 & H5).\n          destruct (eq_nat_dec i k).\n          + subst; destruct N.\n            repeat rewrite minus_diag in H5; auto.\n          + apply H3.\n            split; try omega.\n            finish with H5.\n    Qed.\n \n    Variable (c : X) (Hc : exists τ, 0 < τ /\\ c = f↑τ x0 /\\ c = f↑(2*τ) x0).\n    \n    Let bar_in_0_x0_c : bar_in 0 x0 c.\n    Proof.\n      destruct Hc as (n & _ & Hn1 & Hn2).\n      rewrite Hn1.\n      apply iter_bar_in with n, in_bar_in_0.\n      rewrite <- Hn1 at 1; finish with Hn2.\n    Qed.\n    \n    Definition floyd_index : least_le (fun l => iter_in_cycle (f↑l x0)). \n    Proof.\n      refine (match bar_in_inv bar_in_0_x0_c with\n                | exist _ n Hn => exist _ n _\n              end).\n      destruct Hn as ((H0 & H1) & H2).\n      destruct Hc as (m & H3 & H4 & H5).\n      repeat rewrite <- minus_n_O in H1.\n      split.\n      \n      exists m; split; auto.\n      rewrite H1, <- iter_plus, plus_comm, iter_plus; f_equal.\n      rewrite H4 at 2; finish with H5.\n    \n      intros k (p & H6 & H7).\n      apply H2.\n      split; try omega.\n      repeat rewrite <- minus_n_O.\n      rewrite <- iter_plus in H7.\n      generalize (iter_loop_gen _ _ _ _ H7 0); clear H7; simpl; intros H7.\n      rewrite H4 in H5; replace (2*m) with (m+m) in H5 by omega.\n      generalize (iter_loop_gen _ _ _ _ H5 0); clear H5; simpl; intros H5.\n      rewrite H4.\n      rewrite H7 with (j := m).\n      rewrite H5 with (j := p-1), <- iter_plus.\n      f_equal.\n      replace p with (p-1+1) at 1 by omega.\n      rewrite Nat.mul_add_distr_l, mult_comm; omega.\n    Defined.\n    \n  End compute_index.\n  \n  Section compute_period.\n  \n    Variable (c : X) (Hx : exists k, 0 < k /\\ c = f↑k c).\n\n    Inductive bar_pe i y : Prop :=\n      | in_bar_pe_0 : c = y              -> bar_pe i y\n      | in_bar_pe_1 : bar_pe (S i) (f y) -> bar_pe i y.\n      \n    Let iter_bar_pe n y : 0 < n -> bar_pe n (f↑n y) -> bar_pe 1 (f y).\n    Proof.\n      generalize n; apply nat_rev_ind.\n      constructor 2; auto.\n    Qed.\n  \n    Let bar_pe_inv : forall i y, bar_pe i y -> least_le (fun n => i <= n /\\ c = f↑(n-i) y). \n    Proof.\n      refine (fix loop i y H { struct H } :=\n            match eqdec c y with\n              | left  E => exist _ i _\n              | right N => match loop (S i) (f y) _ with\n                             | exist _ n Hn => exist _ n _\n                           end\n            end).\n      * split.\n        split; try omega; rewrite minus_diag; auto.\n        intros ? []; auto.\n      * destruct H; auto; destruct N; auto.\n      * destruct Hn as ((H0 & H1) & H2); split.\n        split; try omega; finish with H1.\n        intros k (H3 & H4).\n        destruct (eq_nat_dec k i).\n        subst k; rewrite minus_diag in H4; destruct N; auto.\n        apply H2; split.\n        omega.\n        finish with H4.\n    Qed.\n\n    Let bar_pe_c_fc : bar_pe 1 (f c).\n    Proof.\n      destruct Hx as (n & H1 & H2).\n      apply iter_bar_pe with n; auto.\n      apply in_bar_pe_0; auto.\n    Qed.\n  \n    Definition floyd_period : least_div (fun n => 0 < n /\\ c = f↑n c).\n    Proof.\n      refine (match bar_pe_inv bar_pe_c_fc with\n                | exist _ n Hn => exist _ n _\n              end).\n              \n      destruct Hn as ((H0 & H1) & H2).\n      split.\n      split; try omega; finish with H1.\n      intros [|k] (H3 & H4); try omega.\n      destruct eucl_dev with (n := n) (m := S k) as [ q [|r] H5 H6 ]; try omega.\n      exists q; omega.\n      \n      rewrite H6 in H4.\n      replace (q*n+ S r) \n        with  (S r+(q*n+0)) in H4 by omega.\n      rewrite <- iter_loop_gen in H4.\n      2: finish with H1.\n      replace (S r + 0) \n         with ((S r-1)+1) in H4 by omega.\n      rewrite iter_plus in H4.\n      generalize (H2 _ (conj (Nat.lt_0_succ _) H4)).\n      intro; omega.\n    Defined.\n    \n  End compute_period.\n  \n  (** The output of the cycle finding algorithm is a pair i (for index) and p (for period) such that\n        1/ 0 < p\n        2/ f↑i x is a fixpoint of f↑p (ie f↑i x belongs to a p-loop)\n        3/ f↑i x is first belonging to a loop (ie the entry point of the loop)\n        4/ p divides any period \n    *)\n \n  Let cycle_spec λ μ :=     0 < μ \n                         /\\ f↑λ x0 = f↑(λ+μ) x0\n                         /\\ forall i j, i < j -> f↑i x0 = f↑j x0 -> λ <= i /\\ μ div (j-i).\n                \n  Definition floyd_find_cycle : { λ : nat & { μ | cycle_spec λ μ } }.\n  Proof.\n    refine (\n      match floyd_meeting_pt with exist _ c Hc => \n        match floyd_index Hc with exist _ l Hl =>\n          match @floyd_period c _ with exist _ m Hm => \n            existT _ l (exist _ m _) \n          end\n        end\n      end); destruct Hc as (k & H1 & H2 & H3); \n            destruct Hl as (Hl1 & Hl2). \n      \n    - exists k; split; auto.\n      rewrite H2 at 2; finish with H3.\n      \n    - destruct Hm as ((Hm0 & Hm1) & Hm2).\n      split; [ | split ].\n      * auto.\n      * apply iter_in_cycle_period; subst c; auto.\n      * intros i j H4 H5; split.\n        + apply Hl2.\n          exists (j-i); split; try omega.\n          finish with H5.\n        + apply Hm2; split; try omega.\n          rewrite H2, <- iter_plus, plus_comm.\n          apply iter_in_cycle_period.\n          exists k; rewrite <- H2 at 1.\n          split; auto; finish with H3.\n          split; try omega.\n          exists i; finish with H5.\n  Defined.\n\nEnd Floyd_cycle_finding_algo.\n\nCheck floyd_find_cycle.\nPrint Assumptions floyd_find_cycle.\nRecursive Extraction floyd_find_cycle.\n\n", "meta": {"author": "DmxLarchey", "repo": "The-Tortoise-and-the-Hare", "sha": "8aa3a897271cf8f61c9d9530bf9efd363eb2a574", "save_path": "github-repos/coq/DmxLarchey-The-Tortoise-and-the-Hare", "path": "github-repos/coq/DmxLarchey-The-Tortoise-and-the-Hare/The-Tortoise-and-the-Hare-8aa3a897271cf8f61c9d9530bf9efd363eb2a574/floyd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7396703988028166}}
{"text": "(* Implementation and correctness proof for insertion sort.\n  Andrew W. Appel, January 2010. *)\n\nRequire Import Permutation.\nRequire Import SfLib.\n\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\nTheorem ble_nat_i: forall n m, n <= m -> ble_nat n m = true.\nProof.\ninduction n as [|n']; intros; simpl; auto.\ndestruct m.\nelimtype False.\nomega.\napply IHn'.\nomega.\nQed.\n\nTheorem false_ble_nat_i:  forall n m, n > m -> ble_nat n m = false.\nProof.\nintros.\nremember (ble_nat n m) as p; destruct p; auto.\nsymmetry in Heqp; apply ble_nat_true in Heqp; elimtype False; omega.\nQed.\n\nTheorem false_ble_nat_e: forall n m, ble_nat n m = false -> n > m.\nProof.\nintros.\nassert (n <= m \\/ n > m) by omega.\ndestruct H0; auto.\napply ble_nat_i in H0.\nrewrite H0 in H.\ninversion H.\nQed.\n\n(* PART I.   Prove correctness of functional program for insertion sort  *)\n\nFixpoint insert (i:nat) (l: list nat) := \n  match l with\n  | nil => i::nil\n  | h::t => if ble_nat i h then i::h::t else h :: insert i t\n end.\n\nFixpoint sort (l: list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h::t => insert h (sort t)\nend.\n\nExample sort_pi: sort [3,1,4,1,5,9,2,6,5,3,5] = [1,1,2,3,3,4,5,5,5,6,9].\nProof.\nsimpl.\nreflexivity.\nQed.\n\n(** **** Exercise: 3 stars (sort_perm) *)\n\n(* Prove an auxiliary lemma insert_perm, useful for proving sort_perm.\n  You may want to get into the proof of sort_perm first, to see what you'll need.  *)\nLemma insert_perm: True.\nProof. \n(* FILL IN HERE *) Admitted.\n\n(* Now prove the main theorem. *)\nTheorem sort_perm: forall l, Permutation l (sort l).\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (sort_sorted) *)\n(* Define an inductive predicate \"sorted\" that tells whether a list of nats is in nondecreasing order.\n   Then prove that \"sort\" produces a sorted list.\n*)\nInductive sorted: list nat -> Prop := \n (* FILL IN HERE *)\n.\n\n(* You may want to first prove an auxiliary lemma about inserting an element\n   into a sorted list.  *)\nTheorem sort_sorted: forall l, sorted (sort l).\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n", "meta": {"author": "jps8", "repo": "old_cs", "sha": "7afe6cb65b10d8e2418f3bd225283674286fa3a8", "save_path": "github-repos/coq/jps8-old_cs", "path": "github-repos/coq/jps8-old_cs/old_cs-7afe6cb65b10d8e2418f3bd225283674286fa3a8/510/Sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7396352197493382}}
{"text": "(* -*- coq-prog-args: (\"-emacs-U\" \"-R\" \"../monads\" \"); compile-command: \"./makedoc.sh\" -*- *)\n(* begin hide *)\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Export MyPrelude.\n(* end hide *)\n(** printing epsilon $\\varepsilon$ *)(** printing cdot $\\cdot$ *)\n(** We first introduce the monoid laws we just described. \n   We will use the section mechanism of Coq extensively in the following. \n   Sections permit to write a bunch of definitions which are parameterized by some variables,\n   e.g. for types and operations.\n   When closing a section, every definition inside it is quantified over the variables it used.\n   *)\n\nSection Monoid_Laws.\n\n  (** The carrier [m] type may be any type. *)\n\n  Variable m : Type.\n\n  (** The identity element [mempty] and the operation [mappend]. *)\n\n  Variables (mempty : m) (mappend : m -> m -> m).\n\n  (** We define fancy notations for the element and operation. *)\n\n  Notation epsilon := mempty.\n  Infix \"cdot\" := mappend (right associativity, at level 20).\n\n  (** We now state the properties. *)\n\n  Definition monoid_id_l_t : Prop := forall x, epsilon cdot x = x.\n  Definition monoid_id_r_t := forall x, x cdot epsilon = x.\n  Definition monoid_assoc_t := forall x y z, (x cdot y) cdot z = x cdot y cdot z.\nEnd Monoid_Laws.\n\n(** Every variable in [Monoid_Laws] has been discharged by now, so we must apply each definition \n   to particular [mempty] and [mappend] objects.\n   We can finally define the dependent record which represents monoids on [m]:\n   %\\label{def:monoid}%\n*)\n\nRecord monoid (m : Type) : Type := mkMonoid \n  { mempty : m ; mappend : m -> m -> m\n  ; monoid_id_l : monoid_id_l_t mempty mappend\n  ; monoid_id_r : monoid_id_r_t mempty mappend\n  ; monoid_assoc : monoid_assoc_t mappend }.\n\n(* begin hide *)\n(* Notation \" x 'cdot' y \" := (monoid_append _ x y) (right associativity, at level 20). *)\n(* Notation \" 'varepsilon' \" := (monoid_empty _) (no associativity, at level 20). *)\nHint Unfold  monoid_id_l_t  monoid_id_r_t  monoid_assoc_t.\n\nRequire Import Plus.\n\nLtac monoid_tac_in H := repeat rewrite monoid_id_r in H ; repeat rewrite monoid_id_l in H ; repeat rewrite monoid_assoc in H.\n\nLtac monoid_tac := repeat rewrite monoid_id_r ; repeat rewrite monoid_id_l ; repeat rewrite monoid_assoc.\n(* end hide *)\n", "meta": {"author": "coq-contribs", "repo": "finger-tree", "sha": "cf0c7c74df63bd3eea88b4b60f3a062cf01ad791", "save_path": "github-repos/coq/coq-contribs-finger-tree", "path": "github-repos/coq/coq-contribs-finger-tree/finger-tree-cf0c7c74df63bd3eea88b4b60f3a062cf01ad791/MonoidExample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.739635205618459}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (x : natural) : natural :=\n  plus lf3 (mult lf3 x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj143_coqofml_L32xoB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7396336756530596}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint drop (drop_arg0 : Nat) (drop_arg1 : Lst) : Lst\n           := match drop_arg0, drop_arg1 with\n              | x, nil => nil\n              | zero, x => x\n              | succ x, cons y z => drop x z\n              end.\n\n(* No helper lemma needed. *)\nTheorem theorem0 : forall (v : Nat) (w : Nat) (x : Nat) (y : Nat) (z : Lst),\n  eq (drop (succ v) (drop (succ w) (cons x (cons y z)))) (drop (succ v) (drop w (cons x z))).\nProof.\nintros. assert (forall n x l, drop (succ n) (cons x l) = drop n l). \n  - intros. reflexivity.\n  - rewrite H. induction w.\n    + rewrite H. rewrite H. reflexivity.\n    + reflexivity.\nQed. \n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal55.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7396336614454967}}
{"text": "Check mult_n_O.\n(* ===> forall n : nat, 0 = n * 0 *)\n\nCheck mult_n_Sm.\n(* ===> forall n m : nat, n * m + n = n * S m *)\n\nTheorem mult_n_1 : forall p : nat,\n  p * 1 = p.\nProof.\n  intros p.\n  rewrite <- mult_n_Sm.\n  rewrite <-  mult_n_O.\n  simpl.\n  reflexivity.\nQed.", "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/Chapter1/Standard_mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7396191771383174}}
{"text": "Require Import QArith.\nRequire Import JoinSemiLattice.\nRequire Import PreorderEquiv.\nRequire Import MathClasses.interfaces.canonical_names.\n\nSection Rationals.\n\nInstance q_le : Le Q := Qle.\nInstance q_equiv : Equiv Q := Qeq.\nInstance q_lt : Lt Q := Qlt.\nInstance q_zero : Zero Q := 0#1.\nInstance q_plus : Plus Q := Qplus.\nInstance q_mult : Mult Q := Qmult.\n\nInstance q_Preorder : Preorder q_le :=\n  MkPreorder\n    Q\n    Qle\n    Qle_refl\n    Qle_trans.\n\nDefinition Qmax (x y :Q) : Q :=\n  match x ?= y with\n  | Gt => x\n  | Lt => y\n  end.\n\nInstance q_join : Join Q := Qmax.\n\nLemma Qmax_l : forall x y, x ≤ x ⊔ y.\nProof.\n  intros.\n  unfold join, q_join, Qmax.\n  destruct (x ?= y) eqn:?.\n  - rewrite <- Qeq_alt in Heqc.\n    rewrite Heqc.\n    apply le_refl.\n  - rewrite <- Qlt_alt in Heqc.\n    apply Qlt_le_weak. assumption.\n  - apply le_refl.\nQed.\n\nLemma Qmax_r : forall x y, y ≤ x ⊔ y.\nProof.\n  intros.\n  unfold join, q_join, Qmax.\n  destruct (x ?= y) eqn:?.\n  - apply le_refl.\n  - apply le_refl.\n  - rewrite <- Qgt_alt in Heqc.\n    apply Qlt_le_weak. assumption.\nQed.\n\nLemma Qmax_univ : forall x y z, x ≤ z -> y ≤ z -> x ⊔ y ≤ z.\nProof.\n  intros.\n  unfold join, q_join, Qmax.\n  destruct (x ?= y) eqn:?.\n  - rewrite <- Qeq_alt in Heqc. assumption.\n  - assumption.\n  - assumption.\nQed.\n\nInstance q_JSL : JoinSemiLattice q_le :=\n  MkJSL\n    Q\n    q_le\n    q_Preorder\n    Qmax\n    Qmax_l\n    Qmax_r\n    Qmax_univ.\n\nEnd Rationals.\n", "meta": {"author": "wetneb", "repo": "sigmalocales", "sha": "a42975000c9e505103e4321f7413af992fea5e0c", "save_path": "github-repos/coq/wetneb-sigmalocales", "path": "github-repos/coq/wetneb-sigmalocales/sigmalocales-a42975000c9e505103e4321f7413af992fea5e0c/Rationals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7395541409013079}}
{"text": "From algebra Require Import preamble semigroup monoid.\nFrom HB Require Import structures.\nFrom Coq Require Import ZArith Lia.\n\nHB.mixin Record monoid_is_group G of Monoid G :=\n { opp : G -> G;\n   subrr : forall x, add x (opp x) = zero;\n   addNr : forall x, add (opp x) x = zero }.\n\nHB.factory Record is_group G :=\n { zero : G;\n   add : G -> G -> G;\n   opp : G -> G;\n   addrA : associative add;\n   add0r : left_id zero add;\n   subrr : forall x, add x (opp x) = zero;\n   addNr : forall x, add (opp x) x = zero }.\n\nHB.builders Context G of is_group G.\n  Let addr0 : forall x, add x zero = x.\n  Proof. by move=> x; rewrite -(addNr x) addrA subrr add0r. Qed.\n  HB.instance Definition _ := is_monoid.Build G zero add addrA add0r addr0.\n  HB.instance Definition _ := monoid_is_group.Build G opp subrr addNr.\nHB.end.\n\nHB.structure Definition Group := {G of is_group G}.\n\n\nHB.mixin Record is_abgroup G of Group G :=\n  { addC : commutative (add : G -> G -> G) }.\n\n\nHB.structure Definition AbGroup := {G of is_abgroup G &}.\n\n\nDefinition Z_is_group : monoid_is_group Z.\nProof.\n  build.\n  - by apply: Z.opp.\n  - abstract by move=> ?; rewrite /add /zero //=; lia.\n  - abstract by move=> ?; rewrite /add /zero //=; lia.\nDefined.\n\nHB.instance Definition _ := Z_is_group.\nHB.instance Definition _ := is_abgroup.Build Z Z.add_comm.\n\n\n\nHB.mixin Record submonoid_is_subgroup (G : Group.type) S of Submonoid G S :=\n  { has_opp : forall u : G, S u -> S (opp u) }.\n\nHB.factory Record is_subgroup (G : Group.type) (S : G -> Prop) :=\n  { has_zero : S zero;\n    has_add : forall u v : G, S u -> S v -> S (add u v);\n    has_opp : forall u : G, S u -> S (opp u) }.\n\nHB.structure Definition Subgroup (G : Group.type) := {S of submonoid_is_subgroup G S &}.\n\nHB.builders Context G S of is_subgroup G S.\n  HB.instance Definition _ := is_subsemigroup.Build G S has_add.\n  HB.instance Definition _ := subsemigroup_is_submonoid.Build G S has_zero.\nHB.end.\n\n\nSection Subgroup.\n  Context (G : Group.type) (S : Subgroup.type G).\n\n  Definition opp' : {x : G | S x} -> {x : G | S x}.\n  Proof. by move=> u; esplit; apply: has_opp; apply: pi2 u. Defined.\n\n  Fact subrr' : forall x, add x (opp' x) = zero.\n  Proof.\n    move=> u.\n    apply: sigE=> //=.\n    by rewrite subrr.\n  Qed.\n\n  Fact addNr' : forall x, add (opp' x) x = zero.\n  Proof.\n    move=> u.\n    apply: sigE=> //=.\n    by rewrite addNr.\n  Qed.\n\n  HB.instance Definition _ := monoid_is_group.Build {x : G | S x} opp' subrr' addNr'.\nEnd Subgroup.\n", "meta": {"author": "jonsterling", "repo": "coq-algebra", "sha": "3a755dbc58d1c1b20281084b5bdb0027122dba9e", "save_path": "github-repos/coq/jonsterling-coq-algebra", "path": "github-repos/coq/jonsterling-coq-algebra/coq-algebra-3a755dbc58d1c1b20281084b5bdb0027122dba9e/theories/group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7395102675929602}}
{"text": "Inductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS (n : nat) (H : ev n) : ev (S (S 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\nInductive CE : nat -> nat -> Prop :=\n  | CE_0: CE 0 2\n  | CE_SSnm (n m : nat) (H : CE n m ): CE (S (S n)) (S (S m)).\n\nExample test_CE : CE 4 6.\nProof.\n  apply CE_SSnm.\n  apply CE_SSnm.\n  apply CE_0.\nQed.\n\nTheorem CE_SS : forall n m, CE (S (S n)) (S (S m)) -> CE n m.\nProof. \n  intros n m H.\n  inversion H.\n  apply H2.\nQed.\n\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  intros n m H1 H2.\n  induction H1.\n  - simpl.\n    apply H2.\n  - apply ev_SS.\n    apply IHev.\nQed.\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  intros m n o H1 H2.\n  induction H2.\n  - apply H1.\n  - apply le_S.\n    apply IHle.\n    apply H1.\nQed.\n", "meta": {"author": "pikapikapikaori", "repo": "Coq", "sha": "d2af0d21f12b45ee70c3298882b219a133ba9425", "save_path": "github-repos/coq/pikapikapikaori-Coq", "path": "github-repos/coq/pikapikapikaori-Coq/Coq-d2af0d21f12b45ee70c3298882b219a133ba9425/Homework/week11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.73947875851679}}
{"text": "Inductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n\nFixpoint append(m n :natlist) : natlist :=\nmatch m with\n|[] => n\n|a :: b => a::(append b n)\nend.\n\nNotation \"x ++ y\" := (append x y)(at level 60, right associativity).\n\nFixpoint snoc(m:natlist)(n:nat) :natlist:=\nmatch m with\n|[] => [n]\n|a::b => a:: (snoc b n)\nend.\n\nFixpoint reverse(n:natlist) : natlist :=\nmatch n with\n|[] => []\n|a::b => snoc(reverse b) a\nend.\n\nTheorem associative_L3 : forall n o p : natlist, n++(o++p) = (n++o)++p.\nProof.\nintros n o p.\ninduction n.\nsimpl. reflexivity.\nsimpl. rewrite -> IHn.\nreflexivity.\nQed.\n\nTheorem appendList : forall (list : natlist) (n : nat), snoc list n = list ++ [n].   \nProof.\n  intros.    \n    induction list as [| x xs].\n    simpl.\n    reflexivity.\n    simpl. \n    rewrite -> IHxs.\n    reflexivity.\nQed.\n\nTheorem appendEmptyList : forall list : natlist, list ++ [] = list.   \nProof.\n  intros.\n    induction list as [| x xs].\n    simpl.\n    reflexivity.\n    simpl. \n    rewrite -> IHxs.\n    reflexivity.\nQed.\n\n\nTheorem reverseDistributive : forall l1 l2 : natlist, reverse (l1 ++ l2 ) = (reverse l2 ) ++ (reverse l1 ).\nProof.\nintros l1 l2.\ninduction l1.\nsimpl. rewrite appendEmptyList.\nsimpl. reflexivity.\nsimpl. rewrite IHl1.\nsimpl. rewrite appendList.\nsimpl. rewrite appendList.\nsimpl. rewrite associative_L3.\nreflexivity.\nQed.\n\nEval compute in( reverse [1;2;3;4;5;6]).\nEval compute in( reverseDistributive [1;2;3;4;5;6] [7;8;9]).\n", "meta": {"author": "psjyothiprasad", "repo": "Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "sha": "bda5df849ce973def8aa145660aa806e7743af35", "save_path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography", "path": "github-repos/coq/psjyothiprasad-Software-Modelling---Theorem-Provers---Program-Verification---Cryptography/Software-Modelling---Theorem-Provers---Program-Verification---Cryptography-bda5df849ce973def8aa145660aa806e7743af35/Exercise1/Project1_JyothiPrasad_2853401/5_distr_rev/reverseDistributive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7394787560015432}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria.                       *)\n(* You may distribute this file under the terms of the CeCILL-B license *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nRequire Import bigop ssralg binomial.\n\n(******************************************************************************)\n(* This file provides a library for univariate polynomials over ring          *)\n(* structures; it also provides an extended theory for polynomials whose      *)\n(* coefficients range over commutative rings and integral domains.            *)\n(*                                                                            *)\n(*           {poly R} == the type of polynomials with coefficients of type R, *)\n(*                       represented as lists with a non zero last element    *)\n(*                       (big endian representation); the coeficient type R   *)\n(*                       must have a canonical ringType structure cR. In fact *)\n(*                       {poly R} denotes the concrete type polynomial cR; R  *)\n(*                       is just a phantom argument that lets type inference  *)\n(*                       reconstruct the (hidden) ringType structure cR.      *)\n(*          p : seq R == the big-endian sequence of coefficients of p, via    *)\n(*                       the coercion polyseq : polynomial >-> seq.           *)\n(*             Poly s == the polynomial with coefficient sequence s (ignoring *)\n(*                       trailing zeroes).                                    *)\n(* \\poly_(i < n) E(i) == the polynomial of degree at most n - 1 whose         *)\n(*                       coefficients are given by the general term E(i)      *)\n(*  0, 1, - p, p + q, == the usual ring operations: {poly R} has a canonical  *)\n(* p * q, p ^+ n, ...    ringType structure, which is commutative / integral  *)\n(*                       when R is commutative / integral, respectively.      *)\n(*      polyC c, c%:P == the constant polynomial c                            *)\n(*                 'X == the (unique) variable                                *)\n(*               'X^n == a power of 'X; 'X^0 is 1, 'X^1 is convertible to 'X  *)\n(*               p`_i == the coefficient of 'X^i in p; this is in fact just   *)\n(*                       the ring_scope notation generic seq-indexing using   *)\n(*                       nth 0%R, combined with the polyseq coercion.         *)\n(*            coefp i == the linear function p |-> p`_i (self-exapanding).    *)\n(*             size p == 1 + the degree of p, or 0 if p = 0 (this is the      *)\n(*                       generic seq function combined with polyseq).         *)\n(*        lead_coef p == the coefficient of the highest monomial in p, or 0   *)\n(*                       if p = 0 (hence lead_coef p = 0 iff p = 0)           *)\n(*        p \\is monic <=> lead_coef p == 1 (0 is not monic).                  *)\n(* p \\is a polyOver S <=> the coefficients of p satisfy S; S should have a    *)\n(*                        key that should be (at least) an addrPred.          *)\n(*             p.[x]  == the evaluation of a polynomial p at a point x using  *)\n(*                       the Horner scheme                                    *)\n(*                   *** The multi-rule hornerE (resp., hornerE_comm) unwinds *)\n(*                       horner evaluation of a polynomial expression (resp., *)\n(*                       in a non commutative ring, with side conditions).    *)\n(*             p^`()  == formal derivative of p                               *)\n(*             p^`(n) == formal n-derivative of p                             *)\n(*            p^`N(n) == formal n-derivative of p divided by n!               *)\n(*            p \\Po q == polynomial composition; because this is naturally a  *)\n(*                       a linear morphism in the first argument, this        *)\n(*                       notation is transposed (q comes before p for redex   *)\n(*                       selection, etc).                                     *)\n(*                      := \\sum(i < size p) p`_i *: q ^+ i                    *)\n(*      comm_poly p x == x and p.[x] commute; this is a sufficient condition  *)\n(*                       for evaluating (q * p).[x] as q.[x] * p.[x] when R   *)\n(*                       is not commutative.                                  *)\n(*      comm_coef p x == x commutes with all the coefficients of p (clearly,  *)\n(*                       this implies comm_poly p x).                         *)\n(*           root p x == x is a root of p, i.e., p.[x] = 0                    *)\n(*    n.-unity_root x == x is an nth root of unity, i.e., a root of 'X^n - 1  *)\n(* n.-primitive_root x == x is a primitive nth root of unity, i.e., n is the  *)\n(*                       least positive integer m > 0 such that x ^+ m = 1.   *)\n(*                   *** The submodule poly.UnityRootTheory can be used to    *)\n(*                       import selectively the part of the theory of roots   *)\n(*                       of unity that doesn't mention polynomials explicitly *)\n(*       map_poly f p == the image of the polynomial by the function f (which *)\n(*                       should be a ring morphism).                          *)\n(*     comm_ringM f u == u commutes with the image of f (i.e., with all f x)  *)\n(*   horner_morph cfu == given cfu : comm_ringM f u, the function mapping p   *)\n(*                       to the value of map_poly f p at u; this is a ring    *)\n(*                       morphism from {poly R} to the codomain of f when f   *)\n(*                       is a ring morphism.                                  *)\n(*      horner_eval u == the function mapping p to p.[u]; this function can   *)\n(*                       only be used for u in a commutative ring, so it is   *)\n(*                       always a linear ring morphism from {poly R} to R.    *)\n(*     diff_roots x y == x and y are distinct roots; if R is a field, this    *)\n(*                       just means x != y, but this concept is generalized   *)\n(*                       to the case where R is only a ring with units (i.e., *)\n(*                       a unitRingType); in which case it means that x and y *)\n(*                       commute, and that the difference x - y is a unit     *)\n(*                       (i.e., has a multiplicative inverse) in R.           *)\n(*                       to just x != y).                                     *)\n(*       uniq_roots s == s is a sequence or pairwise distinct roots, in the   *)\n(*                       sense of diff_roots p above.                         *)\n(*   *** We only show that these operations and properties are transferred by *)\n(*       morphisms whose domain is a field (thus ensuring injectivity).       *)\n(* We prove the factor_theorem, and the max_poly_roots inequality relating    *)\n(* the number of distinct roots of a polynomial and its size.                 *)\n(*   The some polynomial lemmas use following suffix interpretation :         *)\n(*   C - constant polynomial (as in polyseqC : a%:P = nseq (a != 0) a).       *)\n(*   X - the polynomial variable 'X (as in coefX : 'X`_i = (i == 1%N)).       *)\n(*   Xn - power of 'X (as in monicXn : monic 'X^n).                           *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nOpen Local Scope ring_scope.\n\nReserved Notation \"{ 'poly' T }\" (at level 0, format \"{ 'poly'  T }\").\nReserved Notation \"c %:P\" (at level 2, format \"c %:P\").\nReserved Notation \"'X\" (at level 0).\nReserved Notation \"''X^' n\" (at level 3, n at level 2, format \"''X^' n\").\nReserved Notation \"\\poly_ ( i < n ) E\"\n  (at level 36, E at level 36, i, n at level 50,\n   format \"\\poly_ ( i  <  n )  E\").\nReserved Notation \"p \\Po q\" (at level 50).\nReserved Notation \"a ^`N ( n )\" (at level 8, format \"a ^`N ( n )\").\nReserved Notation \"n .-unity_root\" (at level 2, format \"n .-unity_root\").\nReserved Notation \"n .-primitive_root\"\n  (at level 2, format \"n .-primitive_root\").\n\nLocal Notation simp := Monoid.simpm.\n\nSection Polynomial.\n\nVariable R : ringType.\n\n(* Defines a polynomial as a sequence with <> 0 last element *)\nRecord polynomial := Polynomial {polyseq :> seq R; _ : last 1 polyseq != 0}.\n\nCanonical polynomial_subType := Eval hnf in [subType for polyseq].\nDefinition polynomial_eqMixin := Eval hnf in [eqMixin of polynomial by <:].\nCanonical polynomial_eqType := Eval hnf in EqType polynomial polynomial_eqMixin.\nDefinition polynomial_choiceMixin := [choiceMixin of polynomial by <:].\nCanonical polynomial_choiceType :=\n  Eval hnf in ChoiceType polynomial polynomial_choiceMixin.\n\nLemma poly_inj : injective polyseq. Proof. exact: val_inj. Qed.\n\nDefinition poly_of of phant R := polynomial.\nIdentity Coercion type_poly_of : poly_of >-> polynomial.\n\nDefinition coefp_head h i (p : poly_of (Phant R)) := let: tt := h in p`_i.\n\nEnd Polynomial.\n\n(* We need to break off the section here to let the argument scope *)\n(* directives take effect.                                         *)\nBind Scope ring_scope with poly_of.\nBind Scope ring_scope with polynomial.\nArguments Scope polyseq [_ ring_scope].\nArguments Scope poly_inj [_ ring_scope ring_scope _].\nArguments Scope coefp_head [_ _ nat_scope ring_scope _].\nNotation \"{ 'poly' T }\" := (poly_of (Phant T)).\nNotation coefp i := (coefp_head tt i).\n\nSection PolynomialTheory.\n\nVariable R : ringType.\nImplicit Types (a b c x y z : R) (p q r d : {poly R}).\n\nCanonical poly_subType := Eval hnf in [subType of {poly R}].\nCanonical poly_eqType := Eval hnf in [eqType of {poly R}].\nCanonical poly_choiceType := Eval hnf in [choiceType of {poly R}].\n\nDefinition lead_coef p := p`_(size p).-1.\nLemma lead_coefE p : lead_coef p = p`_(size p).-1. Proof. by []. Qed.\n\nDefinition poly_nil := @Polynomial R [::] (oner_neq0 R).\nDefinition polyC c : {poly R} := insubd poly_nil [:: c].\n\nLocal Notation \"c %:P\" := (polyC c).\n\n(* Remember the boolean (c != 0) is coerced to 1 if true and 0 if false *)\nLemma polyseqC c : c%:P = nseq (c != 0) c :> seq R.\nProof. by rewrite val_insubd /=; case: (c == 0). Qed.\n\nLemma size_polyC c : size c%:P = (c != 0).\nProof. by rewrite polyseqC size_nseq. Qed.\n\nLemma coefC c i : c%:P`_i = if i == 0%N then c else 0.\nProof. by rewrite polyseqC; case: i => [|[]]; case: eqP. Qed.\n\nLemma polyCK : cancel polyC (coefp 0).\nProof. by move=> c; rewrite [coefp 0 _]coefC. Qed.\n\nLemma polyC_inj : injective polyC.\nProof. by move=> c1 c2 eqc12; have:= coefC c2 0; rewrite -eqc12 coefC. Qed.\n\nLemma lead_coefC c : lead_coef c%:P = c.\nProof. by rewrite /lead_coef polyseqC; case: eqP. Qed.\n\n(* Extensional interpretation (poly <=> nat -> R) *)\nLemma polyP p q : nth 0 p =1 nth 0 q <-> p = q.\nProof.\nsplit=> [eq_pq | -> //]; apply: poly_inj.\nwithout loss lt_pq: p q eq_pq / size p < size q.\n  move=> IH; case: (ltngtP (size p) (size q)); try by move/IH->.\n  move/(@eq_from_nth _ 0); exact.\ncase: q => q nz_q /= in lt_pq eq_pq *; case/eqP: nz_q.\nby rewrite (last_nth 0) -(subnKC lt_pq) /= -eq_pq nth_default ?leq_addr.\nQed.\n\nLemma size1_polyC p : size p <= 1 -> p = (p`_0)%:P.\nProof.\nmove=> le_p_1; apply/polyP=> i; rewrite coefC.\nby case: i => // i; rewrite nth_default // (leq_trans le_p_1).\nQed.\n\n(* Builds a polynomial by extension. *)\nDefinition cons_poly c p : {poly R} :=\n  if p is Polynomial ((_ :: _) as s) ns then\n    @Polynomial R (c :: s) ns\n  else c%:P.\n\nLemma polyseq_cons c p :\n  cons_poly c p = (if ~~ nilp p then c :: p else c%:P) :> seq R.\nProof. by case: p => [[]]. Qed.\n\nLemma size_cons_poly c p :\n  size (cons_poly c p) = (if nilp p && (c == 0) then 0%N else (size p).+1).\nProof. by case: p => [[|c' s] _] //=; rewrite size_polyC; case: eqP. Qed.\n\nLemma coef_cons c p i : (cons_poly c p)`_i = if i == 0%N then c else p`_i.-1.\nProof.\nby case: p i => [[|c' s] _] [] //=; rewrite polyseqC; case: eqP => //= _ [].\nQed.\n\n(* Build a polynomial directly from a list of coefficients. *)\nDefinition Poly := foldr cons_poly 0%:P.\n\nLemma PolyK c s : last c s != 0 -> Poly s = s :> seq R.\nProof.\ncase: s => {c}/= [_ |c s]; first by rewrite polyseqC eqxx.\nelim: s c => /= [|a s IHs] c nz_c; rewrite polyseq_cons ?{}IHs //.\nby rewrite !polyseqC !eqxx nz_c.\nQed.\n\nLemma polyseqK p : Poly p = p.\nProof. by apply: poly_inj; exact: PolyK (valP p). Qed.\n\nLemma size_Poly s : size (Poly s) <= size s.\nProof.\nelim: s => [|c s IHs] /=; first by rewrite polyseqC eqxx.\nby rewrite polyseq_cons; case: ifP => // _; rewrite size_polyC; case: (~~ _).\nQed.\n\nLemma coef_Poly s i : (Poly s)`_i = s`_i.\nProof.\nby elim: s i => [|c s IHs] /= [|i]; rewrite !(coefC, eqxx, coef_cons) /=.\nQed.\n\n(* Build a polynomial from an infinite sequence of coefficients and a bound. *)\nDefinition poly_expanded_def n E := Poly (mkseq E n).\nFact poly_key : unit. Proof. by []. Qed.\nDefinition poly := locked_with poly_key poly_expanded_def.\nCanonical poly_unlockable := [unlockable fun poly].\nLocal Notation \"\\poly_ ( i < n ) E\" := (poly n (fun i : nat => E)).\n\nLemma polyseq_poly n E :\n  E n.-1 != 0 -> \\poly_(i < n) E i = mkseq [eta E] n :> seq R.\nProof.\nrewrite unlock; case: n => [|n] nzEn; first by rewrite polyseqC eqxx.\nby rewrite (@PolyK 0) // -nth_last nth_mkseq size_mkseq.\nQed.\n\nLemma size_poly n E : size (\\poly_(i < n) E i) <= n.\nProof. by rewrite unlock (leq_trans (size_Poly _)) ?size_mkseq. Qed.\n\nLemma size_poly_eq n E : E n.-1 != 0 -> size (\\poly_(i < n) E i) = n.\nProof. by move/polyseq_poly->; apply: size_mkseq. Qed.\n\nLemma coef_poly n E k : (\\poly_(i < n) E i)`_k = (if k < n then E k else 0).\nProof.\nrewrite unlock coef_Poly.\nhave [lt_kn | le_nk] := ltnP k n; first by rewrite nth_mkseq.\nby rewrite nth_default // size_mkseq.\nQed.\n\nLemma lead_coef_poly n E :\n  n > 0 -> E n.-1 != 0 -> lead_coef (\\poly_(i < n) E i) = E n.-1.\nProof.\nby case: n => // n _ nzE; rewrite /lead_coef size_poly_eq // coef_poly leqnn.\nQed.\n\nLemma coefK p : \\poly_(i < size p) p`_i = p.\nProof.\nby apply/polyP=> i; rewrite coef_poly; case: ltnP => // /(nth_default 0)->.\nQed.\n\n(* Zmodule structure for polynomial *)\nDefinition add_poly_def p q := \\poly_(i < maxn (size p) (size q)) (p`_i + q`_i).\nFact add_poly_key : unit. Proof. by []. Qed.\nDefinition add_poly := locked_with add_poly_key add_poly_def.\nCanonical add_poly_unlockable := [unlockable fun add_poly].\n\nDefinition opp_poly_def p := \\poly_(i < size p) - p`_i.\nFact opp_poly_key : unit. Proof. by []. Qed.\nDefinition opp_poly := locked_with opp_poly_key opp_poly_def.\nCanonical opp_poly_unlockable := [unlockable fun opp_poly].\n\nFact coef_add_poly p q i : (add_poly p q)`_i = p`_i + q`_i.\nProof.\nrewrite unlock coef_poly; case: leqP => //.\nby rewrite geq_max => /andP[le_p_i le_q_i]; rewrite !nth_default ?add0r.\nQed.\n\nFact coef_opp_poly p i : (opp_poly p)`_i = - p`_i.\nProof.\nrewrite unlock coef_poly /=.\nby case: leqP => // le_p_i; rewrite nth_default ?oppr0.\nQed.\n\nFact add_polyA : associative add_poly.\nProof. by move=> p q r; apply/polyP=> i; rewrite !coef_add_poly addrA. Qed.\n\nFact add_polyC : commutative add_poly.\nProof. by move=> p q; apply/polyP=> i; rewrite !coef_add_poly addrC. Qed.\n\nFact add_poly0 : left_id 0%:P add_poly.\nProof.\nby move=> p; apply/polyP=> i; rewrite coef_add_poly coefC if_same add0r.\nQed.\n\nFact add_polyN : left_inverse 0%:P opp_poly add_poly.\nProof.\nmove=> p; apply/polyP=> i.\nby rewrite coef_add_poly coef_opp_poly coefC if_same addNr.\nQed.\n\nDefinition poly_zmodMixin :=\n  ZmodMixin add_polyA add_polyC add_poly0 add_polyN.\n\nCanonical poly_zmodType := Eval hnf in ZmodType {poly R} poly_zmodMixin.\nCanonical polynomial_zmodType :=\n  Eval hnf in ZmodType (polynomial R) poly_zmodMixin.\n\n(* Properties of the zero polynomial *)\nLemma polyC0 : 0%:P = 0 :> {poly R}. Proof. by []. Qed.\n\nLemma polyseq0 : (0 : {poly R}) = [::] :> seq R.\nProof. by rewrite polyseqC eqxx. Qed.\n\nLemma size_poly0 : size (0 : {poly R}) = 0%N.\nProof. by rewrite polyseq0. Qed.\n\nLemma coef0 i : (0 : {poly R})`_i = 0.\nProof. by rewrite coefC if_same. Qed.\n\nLemma lead_coef0 : lead_coef 0 = 0 :> R. Proof. exact: lead_coefC. Qed.\n\nLemma size_poly_eq0 p : (size p == 0%N) = (p == 0).\nProof. by rewrite size_eq0 -polyseq0. Qed.\n\nLemma size_poly_leq0 p : (size p <= 0) = (p == 0).\nProof. by rewrite leqn0 size_poly_eq0. Qed.\n\nLemma size_poly_leq0P p : reflect (p = 0) (size p <= 0%N).\nProof. by apply: (iffP idP); rewrite size_poly_leq0; move/eqP. Qed.\n\nLemma size_poly_gt0 p : (0 < size p) = (p != 0).\nProof. by rewrite lt0n size_poly_eq0. Qed.\n\nLemma nil_poly p : nilp p = (p == 0).\nProof. exact: size_poly_eq0. Qed.\n\nLemma poly0Vpos p : {p = 0} + {size p > 0}.\nProof. by rewrite lt0n size_poly_eq0; exact: eqVneq. Qed.\n\nLemma polySpred p : p != 0 -> size p = (size p).-1.+1.\nProof. by rewrite -size_poly_eq0 -lt0n => /prednK. Qed.\n\nLemma lead_coef_eq0 p : (lead_coef p == 0) = (p == 0).\nProof.\nrewrite -nil_poly /lead_coef nth_last.\nby case: p => [[|x s] /= /negbTE // _]; rewrite eqxx.\nQed.\n\nLemma polyC_eq0 (c : R) : (c%:P == 0) = (c == 0).\nProof. by rewrite -nil_poly polyseqC; case: (c == 0). Qed.\n\nLemma size_poly1P p : reflect (exists2 c, c != 0 & p = c%:P) (size p == 1%N).\nProof.\napply: (iffP eqP) => [pC | [c nz_c ->]]; last by rewrite size_polyC nz_c.\nhave def_p: p = (p`_0)%:P by rewrite -size1_polyC ?pC.\nby exists p`_0; rewrite // -polyC_eq0 -def_p -size_poly_eq0 pC.\nQed.\n\nLemma leq_sizeP p i : reflect (forall j, i <= j -> p`_j = 0) (size p <= i).\nProof.\napply: (iffP idP) => [hp j hij| hp].\n  by apply: nth_default; apply: leq_trans hij.\ncase p0: (p == 0); first by rewrite (eqP p0) size_poly0.\nmove: (lead_coef_eq0 p); rewrite p0 leqNgt; move/negbT; apply: contra => hs.\nby apply/eqP; apply: hp; rewrite -ltnS (ltn_predK hs).\nQed.\n\n(* Size, leading coef, morphism properties of coef *)\n\nLemma coefD p q i : (p + q)`_i = p`_i + q`_i.\nProof. exact: coef_add_poly. Qed.\n\nLemma coefN p i : (- p)`_i = - p`_i.\nProof. exact: coef_opp_poly. Qed.\n\nLemma coefB p q i : (p - q)`_i = p`_i - q`_i.\nProof. by rewrite coefD coefN. Qed.\n\nCanonical coefp_additive i :=\n  Additive ((fun p => (coefB p)^~ i) : additive (coefp i)).\n\nLemma coefMn p n i : (p *+ n)`_i = p`_i *+ n.\nProof. exact: (raddfMn (coefp_additive i)). Qed.\n\nLemma coefMNn p n i : (p *- n)`_i = p`_i *- n.\nProof. by rewrite coefN coefMn. Qed.\n\nLemma coef_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) k :\n  (\\sum_(i <- r | P i) F i)`_k = \\sum_(i <- r | P i) (F i)`_k.\nProof. exact: (raddf_sum (coefp_additive k)). Qed.\n\nLemma polyC_add : {morph polyC : a b / a + b}.\nProof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefD !coefC ?addr0. Qed.\n\nLemma polyC_opp : {morph polyC : c / - c}.\nProof. by move=> c; apply/polyP=> [[|i]]; rewrite coefN !coefC ?oppr0. Qed.\n\nLemma polyC_sub : {morph polyC : a b / a - b}.\nProof. by move=> a b; rewrite polyC_add polyC_opp. Qed.\n\nCanonical polyC_additive := Additive polyC_sub.\n\nLemma polyC_muln n : {morph polyC : c / c *+ n}.\nProof. exact: raddfMn. Qed.\n\nLemma size_opp p : size (- p) = size p.\nProof.\nby apply/eqP; rewrite eqn_leq -{3}(opprK p) -[-%R]/opp_poly unlock !size_poly.\nQed.\n\nLemma lead_coef_opp p : lead_coef (- p) = - lead_coef p.\nProof. by rewrite /lead_coef size_opp coefN. Qed.\n\nLemma size_add p q : size (p + q) <= maxn (size p) (size q).\nProof. by rewrite -[+%R]/add_poly unlock; apply: size_poly. Qed.\n\nLemma size_addl p q : size p > size q -> size (p + q) = size p.\nProof.\nmove=> ltqp; rewrite -[+%R]/add_poly unlock size_poly_eq (maxn_idPl (ltnW _))//.\nby rewrite addrC nth_default ?simp ?nth_last //; case: p ltqp => [[]].\nQed.\n\nLemma size_sum I (r : seq I) (P : pred I) (F : I -> {poly R}) :\n  size (\\sum_(i <- r | P i) F i) <= \\max_(i <- r | P i) size (F i).\nProof.\nelim/big_rec2: _ => [|i p q _ IHp]; first by rewrite size_poly0.\nby rewrite -(maxn_idPr IHp) maxnA leq_max size_add.\nQed.\n\nLemma lead_coefDl p q : size p > size q -> lead_coef (p + q) = lead_coef p.\nProof.\nmove=> ltqp; rewrite /lead_coef coefD size_addl //.\nby rewrite addrC nth_default ?simp // -ltnS (ltn_predK ltqp).\nQed.\n\n(* Polynomial ring structure. *)\n\nDefinition mul_poly_def p q :=\n  \\poly_(i < (size p + size q).-1) (\\sum_(j < i.+1) p`_j * q`_(i - j)).\nFact mul_poly_key : unit. Proof. by []. Qed.\nDefinition mul_poly := locked_with mul_poly_key mul_poly_def.\nCanonical mul_poly_unlockable := [unlockable fun mul_poly].\n\nFact coef_mul_poly p q i :\n  (mul_poly p q)`_i = \\sum_(j < i.+1) p`_j * q`_(i - j)%N.\nProof.\nrewrite unlock coef_poly -subn1 ltn_subRL add1n; case: leqP => // le_pq_i1.\nrewrite big1 // => j _; have [lq_q_ij | gt_q_ij] := leqP (size q) (i - j).\n  by rewrite [q`__]nth_default ?mulr0.\nrewrite nth_default ?mul0r // -(leq_add2r (size q)) (leq_trans le_pq_i1) //.\nby rewrite -leq_subLR -subnSK.\nQed.\n\nFact coef_mul_poly_rev p q i :\n  (mul_poly p q)`_i = \\sum_(j < i.+1) p`_(i - j)%N * q`_j.\nProof.\nrewrite coef_mul_poly (reindex_inj rev_ord_inj) /=.\nby apply: eq_bigr => j _; rewrite (sub_ordK j).\nQed.\n\nFact mul_polyA : associative mul_poly.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coef_mul_poly coef_mul_poly_rev.\npose coef3 j k := p`_j * (q`_(i - j - k)%N * r`_k).\ntransitivity (\\sum_(j < i.+1) \\sum_(k < i.+1 | k <= i - j) coef3 j k).\n  apply: eq_bigr => /= j _; rewrite coef_mul_poly_rev big_distrr /=.\n  by rewrite (big_ord_narrow_leq (leq_subr _ _)).\nrewrite (exchange_big_dep predT) //=; apply: eq_bigr => k _.\ntransitivity (\\sum_(j < i.+1 | j <= i - k) coef3 j k).\n  apply: eq_bigl => j; rewrite -ltnS -(ltnS j) -!subSn ?leq_ord //.\n  by rewrite -subn_gt0 -(subn_gt0 j) -!subnDA addnC.\nrewrite (big_ord_narrow_leq (leq_subr _ _)) coef_mul_poly big_distrl /=.\nby apply: eq_bigr => j _; rewrite /coef3 -!subnDA addnC mulrA.\nQed.\n\nFact mul_1poly : left_id 1%:P mul_poly.\nProof.\nmove=> p; apply/polyP => i; rewrite coef_mul_poly big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nFact mul_poly1 : right_id 1%:P mul_poly.\nProof.\nmove=> p; apply/polyP => i; rewrite coef_mul_poly_rev big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nFact mul_polyDl : left_distributive mul_poly +%R.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split.\nby apply: eq_bigr => j _; rewrite coefD mulrDl.\nQed.\n\nFact mul_polyDr : right_distributive mul_poly +%R.\nProof.\nmove=> p q r; apply/polyP=> i; rewrite coefD !coef_mul_poly -big_split.\nby apply: eq_bigr => j _; rewrite coefD mulrDr.\nQed.\n\nFact poly1_neq0 : 1%:P != 0 :> {poly R}.\nProof. by rewrite polyC_eq0 oner_neq0. Qed.\n\nDefinition poly_ringMixin :=\n  RingMixin mul_polyA mul_1poly mul_poly1 mul_polyDl mul_polyDr poly1_neq0.\n\nCanonical poly_ringType := Eval hnf in RingType {poly R} poly_ringMixin.\nCanonical polynomial_ringType :=\n  Eval hnf in RingType (polynomial R) poly_ringMixin.\n\nLemma polyC1 : 1%:P = 1 :> {poly R}. Proof. by []. Qed.\n\nLemma polyseq1 : (1 : {poly R}) = [:: 1] :> seq R.\nProof. by rewrite polyseqC oner_neq0. Qed.\n\nLemma size_poly1 : size (1 : {poly R}) = 1%N.\nProof. by rewrite polyseq1. Qed.\n\nLemma coef1 i : (1 : {poly R})`_i = (i == 0%N)%:R.\nProof. by case: i => [|i]; rewrite polyseq1 /= ?nth_nil. Qed.\n\nLemma lead_coef1 : lead_coef 1 = 1 :> R. Proof. exact: lead_coefC. Qed.\n\nLemma coefM p q i : (p * q)`_i = \\sum_(j < i.+1) p`_j * q`_(i - j)%N.\nProof. exact: coef_mul_poly. Qed.\n\nLemma coefMr p q i : (p * q)`_i = \\sum_(j < i.+1) p`_(i - j)%N * q`_j.\nProof. exact: coef_mul_poly_rev. Qed.\n\nLemma size_mul_leq p q : size (p * q) <= (size p + size q).-1.\nProof. by rewrite -[*%R]/mul_poly unlock size_poly. Qed.\n\nLemma mul_lead_coef p q :\n  lead_coef p * lead_coef q = (p * q)`_(size p + size q).-2.\nProof.\npose dp := (size p).-1; pose dq := (size q).-1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite lead_coef0 !mul0r coef0.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite lead_coef0 !mulr0 coef0.\nhave ->: (size p + size q).-2 = (dp + dq)%N.\n  by do 2! rewrite polySpred // addSn addnC.\nhave lt_p_pq: dp < (dp + dq).+1 by rewrite ltnS leq_addr.\nrewrite coefM (bigD1 (Ordinal lt_p_pq)) ?big1 ?simp ?addKn //= => i.\nrewrite -val_eqE neq_ltn /= => /orP[lt_i_p | gt_i_p]; last first.\n  by rewrite nth_default ?mul0r //; rewrite -polySpred in gt_i_p.\nrewrite [q`__]nth_default ?mulr0 //= -subSS -{1}addnS -polySpred //.\nby rewrite addnC -addnBA ?leq_addr.\nQed.\n\nLemma size_proper_mul p q :\n  lead_coef p * lead_coef q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\napply: contraNeq; rewrite mul_lead_coef eqn_leq size_mul_leq -ltnNge => lt_pq.\nby rewrite nth_default // -subn1 -(leq_add2l 1) -leq_subLR leq_sub2r.\nQed.\n\nLemma lead_coef_proper_mul p q :\n  let c := lead_coef p * lead_coef q in c != 0 -> lead_coef (p * q) = c.\nProof. by move=> /= nz_c; rewrite mul_lead_coef -size_proper_mul. Qed.\n\nLemma size_prod_leq (I : finType) (P : pred I) (F : I -> {poly R}) :\n  size (\\prod_(i | P i) F i) <= (\\sum_(i | P i) size (F i)).+1 - #|P|.\nProof.\nrewrite -sum1_card.\nelim/big_rec3: _ => [|i n m p _ IHp]; first by rewrite size_poly1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0.\nrewrite (leq_trans (size_mul_leq _ _)) // subnS -!subn1 leq_sub2r //.\nrewrite -addnS -addnBA ?leq_add2l // ltnW // -subn_gt0 (leq_trans _ IHp) //.\nby rewrite polySpred.\nQed.\n\nLemma coefCM c p i : (c%:P * p)`_i = c * p`_i.\nProof.\nrewrite coefM big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nLemma coefMC c p i : (p * c%:P)`_i = p`_i * c.\nProof.\nrewrite coefMr big_ord_recl subn0.\nby rewrite big1 => [|j _]; rewrite coefC !simp.\nQed.\n\nLemma polyC_mul : {morph polyC : a b / a * b}.\nProof. by move=> a b; apply/polyP=> [[|i]]; rewrite coefCM !coefC ?simp. Qed.\n\nFact polyC_multiplicative : multiplicative polyC.\nProof. by split; first exact: polyC_mul. Qed.\nCanonical polyC_rmorphism := AddRMorphism polyC_multiplicative.\n\nLemma polyC_exp n : {morph polyC : c / c ^+ n}.\nProof. exact: rmorphX. Qed.\n\nLemma size_exp_leq p n : size (p ^+ n) <= ((size p).-1 * n).+1.\nProof.\nelim: n => [|n IHn]; first by rewrite size_poly1.\nhave [-> | nzp] := poly0Vpos p; first by rewrite exprS mul0r size_poly0.\nrewrite exprS (leq_trans (size_mul_leq _ _)) //.\nby rewrite -{1}(prednK nzp) mulnS -addnS leq_add2l.\nQed.\n\nLemma size_Msign p n : size ((-1) ^+ n * p) = size p.\nProof.\nby rewrite -signr_odd; case: (odd n); rewrite ?mul1r // mulN1r size_opp.\nQed.\n\nFact coefp0_multiplicative : multiplicative (coefp 0 : {poly R} -> R).\nProof.\nsplit=> [p q|]; last by rewrite polyCK.\nby rewrite [coefp 0 _]coefM big_ord_recl big_ord0 addr0.\nQed.\n\nCanonical coefp0_rmorphism := AddRMorphism coefp0_multiplicative.\n\n(* Algebra structure of polynomials. *)\nDefinition scale_poly_def a (p : {poly R}) := \\poly_(i < size p) (a * p`_i).\nFact scale_poly_key : unit. Proof. by []. Qed.\nDefinition scale_poly := locked_with scale_poly_key scale_poly_def.\nCanonical scale_poly_unlockable := [unlockable fun scale_poly].\n\nFact scale_polyE a p : scale_poly a p = a%:P * p.\nProof.\napply/polyP=> n; rewrite unlock coef_poly coefCM.\nby case: leqP => // le_p_n; rewrite nth_default ?mulr0.\nQed.\n\nFact scale_polyA a b p : scale_poly a (scale_poly b p) = scale_poly (a * b) p.\nProof. by rewrite !scale_polyE mulrA polyC_mul. Qed.\n\nFact scale_1poly : left_id 1 scale_poly.\nProof. by move=> p; rewrite scale_polyE mul1r. Qed.\n\nFact scale_polyDr a : {morph scale_poly a : p q / p + q}.\nProof. by move=> p q; rewrite !scale_polyE mulrDr. Qed.\n\nFact scale_polyDl p : {morph scale_poly^~ p : a b / a + b}.\nProof. by move=> a b /=; rewrite !scale_polyE raddfD mulrDl. Qed.\n\nFact scale_polyAl a p q : scale_poly a (p * q) = scale_poly a p * q.\nProof. by rewrite !scale_polyE mulrA. Qed.\n\nDefinition poly_lmodMixin :=\n  LmodMixin scale_polyA scale_1poly scale_polyDr scale_polyDl.\n\nCanonical poly_lmodType :=\n  Eval hnf in LmodType R {poly R} poly_lmodMixin.\nCanonical polynomial_lmodType :=\n  Eval hnf in LmodType R (polynomial R) poly_lmodMixin.\nCanonical poly_lalgType :=\n  Eval hnf in LalgType R {poly R} scale_polyAl.\nCanonical polynomial_lalgType :=\n  Eval hnf in LalgType R (polynomial R) scale_polyAl.\n\nLemma mul_polyC a p : a%:P * p = a *: p.\nProof. by rewrite -scale_polyE. Qed.\n\nLemma alg_polyC a : a%:A = a%:P :> {poly R}.\nProof. by rewrite -mul_polyC mulr1. Qed.\n\nLemma coefZ a p i : (a *: p)`_i = a * p`_i.\nProof.\nrewrite -[*:%R]/scale_poly unlock coef_poly.\nby case: leqP => // le_p_n; rewrite nth_default ?mulr0.\nQed.\n\nLemma size_scale_leq a p : size (a *: p) <= size p.\nProof. by rewrite -[*:%R]/scale_poly unlock size_poly. Qed.\n\nCanonical coefp_linear i : {scalar {poly R}} :=\n  AddLinear ((fun a => (coefZ a) ^~ i) : scalable_for *%R (coefp i)).\nCanonical coefp0_lrmorphism := [lrmorphism of coefp 0].\n\n(* The indeterminate, at last! *)\nDefinition polyX_def := Poly [:: 0; 1].\nFact polyX_key : unit. Proof. by []. Qed.\nDefinition polyX : {poly R} := locked_with polyX_key polyX_def.\nCanonical polyX_unlockable := [unlockable of polyX].\nLocal Notation \"'X\" := polyX.\n\nLemma polyseqX : 'X = [:: 0; 1] :> seq R.\nProof. by rewrite unlock !polyseq_cons nil_poly eqxx /= polyseq1. Qed.\n\nLemma size_polyX : size 'X = 2. Proof. by rewrite polyseqX. Qed.\n\nLemma polyX_eq0 : ('X == 0) = false.\nProof. by rewrite -size_poly_eq0 size_polyX. Qed.\n\nLemma coefX i : 'X`_i = (i == 1%N)%:R.\nProof. by case: i => [|[|i]]; rewrite polyseqX //= nth_nil. Qed.\n\nLemma lead_coefX : lead_coef 'X = 1.\nProof. by rewrite /lead_coef polyseqX. Qed.\n\nLemma commr_polyX p : GRing.comm p 'X.\nProof.\napply/polyP=> i; rewrite coefMr coefM.\nby apply: eq_bigr => j _; rewrite coefX commr_nat.\nQed.\n\nLemma coefMX p i : (p * 'X)`_i = (if (i == 0)%N then 0 else p`_i.-1).\nProof.\nrewrite coefMr big_ord_recl coefX ?simp.\ncase: i => [|i]; rewrite ?big_ord0 //= big_ord_recl polyseqX subn1 /=.\nby rewrite big1 ?simp // => j _; rewrite nth_nil !simp.\nQed.\n\nLemma coefXM p i : ('X * p)`_i = (if (i == 0)%N then 0 else p`_i.-1).\nProof. by rewrite -commr_polyX coefMX. Qed.\n\nLemma cons_poly_def p a : cons_poly a p = p * 'X + a%:P.\nProof.\napply/polyP=> i; rewrite coef_cons coefD coefMX coefC.\nby case: ifP; rewrite !simp.\nQed.\n\nLemma poly_ind (K : {poly R} -> Type) :\n  K 0 -> (forall p c, K p -> K (p * 'X + c%:P)) -> (forall p, K p).\nProof.\nmove=> K0 Kcons p; rewrite -[p]polyseqK.\nelim: {p}(p : seq R) => //= p c IHp; rewrite cons_poly_def; exact: Kcons.\nQed.\n\nLemma polyseqXsubC a : 'X - a%:P = [:: - a; 1] :> seq R.\nProof.\nby rewrite -['X]mul1r -polyC_opp -cons_poly_def polyseq_cons polyseq1.\nQed.\n\nLemma size_XsubC a : size ('X - a%:P) = 2%N.\nProof. by rewrite polyseqXsubC. Qed.\n\nLemma size_XaddC b : size ('X + b%:P) = 2.\nProof. by rewrite -[b]opprK rmorphN size_XsubC. Qed.\n\nLemma lead_coefXsubC a : lead_coef ('X - a%:P) = 1.\nProof. by rewrite lead_coefE polyseqXsubC. Qed.\n\nLemma polyXsubC_eq0 a : ('X - a%:P == 0) = false.\nProof. by rewrite -nil_poly polyseqXsubC. Qed.\n\nLemma size_MXaddC p c :\n  size (p * 'X + c%:P) = (if (p == 0) && (c == 0) then 0%N else (size p).+1).\nProof. by rewrite -cons_poly_def size_cons_poly nil_poly. Qed.\n\nLemma polyseqMX p : p != 0 -> p * 'X = 0 :: p :> seq R.\nProof.\nby move=> nz_p; rewrite -[p * _]addr0 -cons_poly_def polyseq_cons nil_poly nz_p.\nQed.\n\nLemma size_mulX p : p != 0 -> size (p * 'X) = (size p).+1.\nProof. by move/polyseqMX->. Qed.\n\nLemma lead_coefMX p : lead_coef (p * 'X) = lead_coef p.\nProof.\nhave [-> | nzp] := eqVneq p 0; first by rewrite mul0r.\nby rewrite /lead_coef !nth_last polyseqMX.\nQed.\n\nLemma size_XmulC a : a != 0 -> size ('X * a%:P) = 2.\nProof.\nby move=> nz_a; rewrite -commr_polyX size_mulX ?polyC_eq0 ?size_polyC nz_a.\nQed.\n\nLocal Notation \"''X^' n\" := ('X ^+ n).\n\nLemma coefXn n i : 'X^n`_i = (i == n)%:R.\nProof.\nby elim: n i => [|n IHn] [|i]; rewrite ?coef1 // exprS coefXM ?IHn.\nQed.\n\nLemma polyseqXn n : 'X^n = rcons (nseq n 0) 1 :> seq R.\nProof.\nelim: n => [|n IHn]; rewrite ?polyseq1 // exprSr.\nby rewrite polyseqMX -?size_poly_eq0 IHn ?size_rcons.\nQed.\n\nLemma size_polyXn n : size 'X^n = n.+1.\nProof. by rewrite polyseqXn size_rcons size_nseq. Qed.\n\nLemma commr_polyXn p n : GRing.comm p 'X^n.\nProof. by apply: commrX; exact: commr_polyX. Qed.\n\nLemma lead_coefXn n : lead_coef 'X^n = 1.\nProof. by rewrite /lead_coef nth_last polyseqXn last_rcons. Qed.\n\nLemma polyseqMXn n p : p != 0 -> p * 'X^n = ncons n 0 p :> seq R.\nProof.\ncase: n => [|n] nz_p; first by rewrite mulr1.\nelim: n => [|n IHn]; first exact: polyseqMX.\nby rewrite exprSr mulrA polyseqMX -?nil_poly IHn.\nQed.\n\nLemma coefMXn n p i : (p * 'X^n)`_i = if i < n then 0 else p`_(i - n).\nProof.\nhave [-> | /polyseqMXn->] := eqVneq p 0; last exact: nth_ncons.\nby rewrite mul0r !coef0 if_same.\nQed.\n\nLemma coefXnM n p i : ('X^n * p)`_i = if i < n then 0 else p`_(i - n).\nProof. by rewrite -commr_polyXn coefMXn. Qed.\n\n(* Expansion of a polynomial as an indexed sum *)\nLemma poly_def n E : \\poly_(i < n) E i = \\sum_(i < n) E i *: 'X^i.\nProof.\nrewrite unlock; elim: n => [|n IHn] in E *; first by rewrite big_ord0.\nrewrite big_ord_recl /= cons_poly_def addrC expr0 alg_polyC.\ncongr (_ + _); rewrite (iota_addl 1 0) -map_comp IHn big_distrl /=.\nby apply: eq_bigr => i _; rewrite -scalerAl exprSr.\nQed.\n\n(* Monic predicate *)\nDefinition monic := [qualify p | lead_coef p == 1].\nFact monic_key : pred_key monic. Proof. by []. Qed.\nCanonical monic_keyed := KeyedQualifier monic_key.\n\nLemma monicE p : (p \\is monic) = (lead_coef p == 1). Proof. by []. Qed.\nLemma monicP p : reflect (lead_coef p = 1) (p \\is monic).\nProof. exact: eqP. Qed.\n\nLemma monic1 : 1 \\is monic. Proof. exact/eqP/lead_coef1. Qed.\nLemma monicX : 'X \\is monic. Proof. exact/eqP/lead_coefX. Qed.\nLemma monicXn n : 'X^n \\is monic. Proof. exact/eqP/lead_coefXn. Qed.\n\nLemma monic_neq0 p : p \\is monic -> p != 0.\nProof. by rewrite -lead_coef_eq0 => /eqP->; exact: oner_neq0. Qed.\n\nLemma lead_coef_monicM p q : p \\is monic -> lead_coef (p * q) = lead_coef q.\nProof.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite mulr0.\nby move/monicP=> mon_p; rewrite lead_coef_proper_mul mon_p mul1r ?lead_coef_eq0.\nQed.\n\nLemma lead_coef_Mmonic p q : q \\is monic -> lead_coef (p * q) = lead_coef p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mul0r.\nby move/monicP=> mon_q; rewrite lead_coef_proper_mul mon_q mulr1 ?lead_coef_eq0.\nQed.\n\nLemma size_monicM p q :\n  p \\is monic -> q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nmove/monicP=> mon_p nz_q.\nby rewrite size_proper_mul // mon_p mul1r lead_coef_eq0.\nQed.\n\nLemma size_Mmonic p q :\n  p != 0 -> q \\is monic -> size (p * q) = (size p + size q).-1.\nProof.\nmove=> nz_p /monicP mon_q.\nby rewrite size_proper_mul // mon_q mulr1 lead_coef_eq0.\nQed.\n\nLemma monicMl p q : p \\is monic -> (p * q \\is monic) = (q \\is monic).\nProof. by move=> mon_p; rewrite !monicE lead_coef_monicM. Qed.\n\nLemma monicMr p q : q \\is monic -> (p * q \\is monic) = (p \\is monic).\nProof. by move=> mon_q; rewrite !monicE lead_coef_Mmonic. Qed.\n\nFact monic_mulr_closed : mulr_closed monic.\nProof. by split=> [|p q mon_p]; rewrite (monic1, monicMl). Qed.\nCanonical monic_mulrPred := MulrPred monic_mulr_closed.\n\nLemma monic_exp p n : p \\is monic -> p ^+ n \\is monic.\nProof. exact: rpredX. Qed.\n\nLemma monic_prod I rI (P : pred I) (F : I -> {poly R}):\n  (forall i, P i -> F i \\is monic) -> \\prod_(i <- rI | P i) F i \\is monic.\nProof. exact: rpred_prod. Qed.\n\nLemma monicXsubC c : 'X - c%:P \\is monic.\nProof. exact/eqP/lead_coefXsubC. Qed.\n\nLemma monic_prod_XsubC I rI (P : pred I) (F : I -> R) :\n  \\prod_(i <- rI | P i) ('X - (F i)%:P) \\is monic.\nProof. by apply: monic_prod => i _; exact: monicXsubC. Qed.\n\nLemma size_prod_XsubC I rI (F : I -> R) :\n  size (\\prod_(i <- rI) ('X - (F i)%:P)) = (size rI).+1.\nProof.\nelim: rI => [|i r /= <-]; rewrite ?big_nil ?size_poly1 // big_cons.\nrewrite size_monicM ?monicXsubC ?monic_neq0 ?monic_prod_XsubC //.\nby rewrite size_XsubC.\nQed.\n\nLemma size_exp_XsubC n a : size (('X - a%:P) ^+ n) = n.+1.\nProof. by rewrite -[n]card_ord -prodr_const size_prod_XsubC cardE enumT. Qed.\n\n(* Some facts about regular elements. *)\n\nLemma lreg_lead p : GRing.lreg (lead_coef p) -> GRing.lreg p.\nProof.\nmove/mulrI_eq0=> reg_p; apply: mulrI0_lreg => q /eqP; apply: contraTeq => nz_q.\nby rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0.\nQed.\n\nLemma rreg_lead p : GRing.rreg (lead_coef p) -> GRing.rreg p.\nProof.\nmove/mulIr_eq0=> reg_p; apply: mulIr0_rreg => q /eqP; apply: contraTeq => nz_q.\nby rewrite -lead_coef_eq0 lead_coef_proper_mul reg_p lead_coef_eq0.\nQed.\n\nLemma lreg_lead0 p : GRing.lreg (lead_coef p) -> p != 0.\nProof. by move/lreg_neq0; rewrite lead_coef_eq0. Qed.\n\nLemma rreg_lead0 p : GRing.rreg (lead_coef p) -> p != 0.\nProof. by move/rreg_neq0; rewrite lead_coef_eq0. Qed.\n\nLemma lreg_size c p : GRing.lreg c -> size (c *: p) = size p.\nProof.\nmove=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite scaler0.\nrewrite -mul_polyC size_proper_mul; first by rewrite size_polyC lreg_neq0.\nby rewrite lead_coefC mulrI_eq0 ?lead_coef_eq0.\nQed.\n\nLemma lreg_polyZ_eq0 c p : GRing.lreg c -> (c *: p == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /lreg_size->. Qed.\n\nLemma lead_coef_lreg c p :\n  GRing.lreg c -> lead_coef (c *: p) = c * lead_coef p.\nProof. by move=> reg_c; rewrite !lead_coefE coefZ lreg_size. Qed.\n\nLemma rreg_size c p : GRing.rreg c -> size (p * c%:P) =  size p.\nProof.\nmove=> reg_c; have [-> | nz_p] := eqVneq p 0; first by rewrite mul0r.\nrewrite size_proper_mul; first by rewrite size_polyC rreg_neq0 ?addn1.\nby rewrite lead_coefC mulIr_eq0 ?lead_coef_eq0.\nQed.\n\nLemma rreg_polyMC_eq0 c p : GRing.rreg c -> (p * c%:P == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /rreg_size->. Qed.\n\nLemma rreg_div0 q r d :\n    GRing.rreg (lead_coef d) -> size r < size d ->\n  (q * d + r == 0) = (q == 0) && (r == 0).\nProof.\nmove=> reg_d lt_r_d; rewrite addrC addr_eq0.\nhave [-> | nz_q] := altP (q =P 0); first by rewrite mul0r oppr0.\napply: contraTF lt_r_d => /eqP->; rewrite -leqNgt size_opp.\nrewrite size_proper_mul ?mulIr_eq0 ?lead_coef_eq0 //.\nby rewrite (polySpred nz_q) leq_addl.\nQed.\n\nLemma monic_comreg p :\n  p \\is monic -> GRing.comm p (lead_coef p)%:P /\\ GRing.rreg (lead_coef p).\nProof. by move/monicP->; split; [exact: commr1 | exact: rreg1]. Qed.\n\n(* Horner evaluation of polynomials *)\nImplicit Types s rs : seq R.\nFixpoint horner_rec s x := if s is a :: s' then horner_rec s' x * x + a else 0.\nDefinition horner p := horner_rec p.\n\nLocal Notation \"p .[ x ]\" := (horner p x) : ring_scope.\n\nLemma horner0 x : (0 : {poly R}).[x] = 0.\nProof. by rewrite /horner polyseq0. Qed.\n\nLemma hornerC c x : (c%:P).[x] = c.\nProof. by rewrite /horner polyseqC; case: eqP; rewrite /= ?simp. Qed.\n\nLemma hornerX x : 'X.[x] = x.\nProof. by rewrite /horner polyseqX /= !simp. Qed.\n\nLemma horner_cons p c x : (cons_poly c p).[x] = p.[x] * x + c.\nProof.\nrewrite /horner polyseq_cons; case: nilP => //= ->.\nby rewrite !simp -/(_.[x]) hornerC.\nQed.\n\nLemma horner_coef0 p : p.[0] = p`_0.\nProof. by rewrite /horner; case: (p : seq R) => //= c p'; rewrite !simp. Qed.\n\nLemma hornerMXaddC p c x : (p * 'X + c%:P).[x] = p.[x] * x + c.\nProof. by rewrite -cons_poly_def horner_cons. Qed.\n\nLemma hornerMX p x : (p * 'X).[x] = p.[x] * x.\nProof. by rewrite -[p * 'X]addr0 hornerMXaddC addr0. Qed.\n\nLemma horner_Poly s x : (Poly s).[x] = horner_rec s x.\nProof. by elim: s => [|a s /= <-]; rewrite (horner0, horner_cons). Qed.\n\nLemma horner_coef p x : p.[x] = \\sum_(i < size p) p`_i * x ^+ i.\nProof.\nrewrite /horner.\nelim: {p}(p : seq R) => /= [|a s ->]; first by rewrite big_ord0.\nrewrite big_ord_recl simp addrC big_distrl /=.\nby congr (_ + _); apply: eq_bigr => i _; rewrite -mulrA exprSr.\nQed.\n\nLemma horner_coef_wide n p x :\n  size p <= n -> p.[x] = \\sum_(i < n) p`_i * x ^+ i.\nProof.\nmove=> le_p_n.\nrewrite horner_coef (big_ord_widen n (fun i => p`_i * x ^+ i)) // big_mkcond.\nby apply: eq_bigr => i _; case: ltnP => // le_p_i; rewrite nth_default ?simp.\nQed.\n\nLemma horner_poly n E x : (\\poly_(i < n) E i).[x] = \\sum_(i < n) E i * x ^+ i.\nProof.\nrewrite (@horner_coef_wide n) ?size_poly //.\nby apply: eq_bigr => i _; rewrite coef_poly ltn_ord.\nQed.\n\nLemma hornerN p x : (- p).[x] = - p.[x].\nProof.\nrewrite -[-%R]/opp_poly unlock horner_poly horner_coef -sumrN /=.\nby apply: eq_bigr => i _; rewrite mulNr.\nQed.\n\nLemma hornerD p q x : (p + q).[x] = p.[x] + q.[x].\nProof.\nrewrite -[+%R]/add_poly unlock horner_poly; set m := maxn _ _.\nrewrite !(@horner_coef_wide m) ?leq_max ?leqnn ?orbT // -big_split /=.\nby apply: eq_bigr => i _; rewrite -mulrDl.\nQed.\n\nLemma hornerXsubC a x : ('X - a%:P).[x] = x - a.\nProof. by rewrite hornerD hornerN hornerC hornerX. Qed.\n\nLemma horner_sum I (r : seq I) (P : pred I) F x :\n  (\\sum_(i <- r | P i) F i).[x] = \\sum_(i <- r | P i) (F i).[x].\nProof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (horner0, hornerD). Qed.\n\nLemma hornerCM a p x : (a%:P * p).[x] = a * p.[x].\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(mulr0, horner0).\nby rewrite mulrDr mulrA -polyC_mul !hornerMXaddC IHp mulrDr mulrA.\nQed.\n\nLemma hornerZ c p x : (c *: p).[x] = c * p.[x].\nProof. by rewrite -mul_polyC hornerCM. Qed.\n\nLemma hornerMn n p x : (p *+ n).[x] = p.[x] *+ n.\nProof. by elim: n => [| n IHn]; rewrite ?horner0 // !mulrS hornerD IHn. Qed.\n\nDefinition comm_coef p x := forall i, p`_i * x = x * p`_i.\n\nDefinition comm_poly p x := x * p.[x] = p.[x] * x.\n\nLemma comm_coef_poly p x : comm_coef p x -> comm_poly p x.\nProof.\nmove=> cpx; rewrite /comm_poly !horner_coef big_distrl big_distrr /=.\nby apply: eq_bigr => i _; rewrite /= mulrA -cpx -!mulrA commrX.\nQed.\n\nLemma comm_poly0 x : comm_poly 0 x.\nProof. by rewrite /comm_poly !horner0 !simp. Qed.\n\nLemma comm_poly1 x : comm_poly 1 x.\nProof. by rewrite /comm_poly !hornerC !simp. Qed.\n\nLemma comm_polyX x : comm_poly 'X x.\nProof. by rewrite /comm_poly !hornerX. Qed.\n\nLemma hornerM_comm p q x : comm_poly q x -> (p * q).[x] = p.[x] * q.[x].\nProof.\nmove=> comm_qx.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(simp, horner0).\nrewrite mulrDl hornerD hornerCM -mulrA -commr_polyX mulrA hornerMX.\nby rewrite {}IHp -mulrA -comm_qx mulrA -mulrDl hornerMXaddC.\nQed.\n\nLemma horner_exp_comm p x n : comm_poly p x -> (p ^+ n).[x] = p.[x] ^+ n.\nProof.\nmove=> comm_px; elim: n => [|n IHn]; first by rewrite hornerC.\nby rewrite !exprSr -IHn hornerM_comm.\nQed.\n\nLemma hornerXn x n : ('X^n).[x] = x ^+ n.\nProof. by rewrite horner_exp_comm /comm_poly hornerX. Qed.\n\nDefinition hornerE_comm :=\n  (hornerD, hornerN, hornerX, hornerC, horner_cons,\n   simp, hornerCM, hornerZ,\n   (fun p x => hornerM_comm p (comm_polyX x))).\n\nDefinition root p : pred R := fun x => p.[x] == 0.\n\nLemma mem_root p x : x \\in root p = (p.[x] == 0).\nProof. by []. Qed.\n\nLemma rootE p x : (root p x = (p.[x] == 0)) * ((x \\in root p) = (p.[x] == 0)).\nProof. by []. Qed.\n\nLemma rootP p x : reflect (p.[x] = 0) (root p x).\nProof. exact: eqP. Qed.\n\nLemma rootPt p x : reflect (p.[x] == 0) (root p x).\nProof. exact: idP. Qed.\n\nLemma rootPf p x : reflect ((p.[x] == 0) = false) (~~ root p x).\nProof. exact: negPf. Qed.\n\nLemma rootC a x : root a%:P x = (a == 0).\nProof. by rewrite rootE hornerC. Qed.\n\nLemma root0 x : root 0 x.\nProof. by rewrite rootC. Qed.\n\nLemma root1 x : ~~ root 1 x.\nProof. by rewrite rootC oner_eq0. Qed.\n\nLemma rootX x : root 'X x = (x == 0).\nProof. by rewrite rootE hornerX. Qed.\n\nLemma rootN p x : root (- p) x = root p x.\nProof. by rewrite rootE hornerN oppr_eq0. Qed.\n\nLemma root_size_gt1 a p : p != 0 -> root p a -> 1 < size p.\nProof.\nrewrite ltnNge => nz_p; apply: contraL => /size1_polyC Dp.\nby rewrite Dp rootC -polyC_eq0 -Dp.\nQed.\n\nLemma root_XsubC a x : root ('X - a%:P) x = (x == a).\nProof. by rewrite rootE hornerXsubC subr_eq0. Qed.\n\nLemma root_XaddC a x : root ('X + a%:P) x = (x == - a).\nProof. by rewrite -root_XsubC rmorphN opprK. Qed.\n\nTheorem factor_theorem p a : reflect (exists q, p = q * ('X - a%:P)) (root p a).\nProof.\napply: (iffP eqP) => [pa0 | [q ->]]; last first.\n  by rewrite hornerM_comm /comm_poly hornerXsubC subrr ?simp.\nexists (\\poly_(i < size p) horner_rec (drop i.+1 p) a).\napply/polyP=> i; rewrite mulrBr coefB coefMX coefMC !coef_poly.\napply: canRL (addrK _) _; rewrite addrC; have [le_p_i | lt_i_p] := leqP.\n  rewrite nth_default // !simp drop_oversize ?if_same //.\n  exact: leq_trans (leqSpred _).\ncase: i => [|i] in lt_i_p *; last by rewrite ltnW // (drop_nth 0 lt_i_p).\nby rewrite drop1 /= -{}pa0 /horner; case: (p : seq R) lt_i_p.\nQed.\n\nLemma multiplicity_XsubC p a :\n  {m | exists2 q, (p != 0) ==> ~~ root q a & p = q * ('X - a%:P) ^+ m}.\nProof.\nelim: {p}(size p) {-2}p (eqxx (size p)) => [|n IHn] p.\n  by rewrite size_poly_eq0 => ->; exists 0%N, p; rewrite ?mulr1.\nhave [/sig_eqW[{p}p ->] sz_p | nz_pa] := altP (factor_theorem p a); last first.\n  by exists 0%N, p; rewrite ?mulr1 ?nz_pa ?implybT.\nhave nz_p: p != 0 by apply: contraTneq sz_p => ->; rewrite mul0r size_poly0.\nrewrite size_Mmonic ?monicXsubC // size_XsubC addn2 eqSS in sz_p.\nhave [m /sig2_eqW[q nz_qa Dp]] := IHn p sz_p; rewrite nz_p /= in nz_qa.\nby exists m.+1, q; rewrite ?nz_qa ?implybT // exprSr mulrA -Dp.\nQed.\n\n(* Roots of unity. *)\n\nLemma size_Xn_sub_1 n : n > 0 -> size ('X^n - 1 : {poly R}) = n.+1.\nProof.\nby move=> n_gt0; rewrite size_addl size_polyXn // size_opp size_poly1.\nQed.\n\nLemma monic_Xn_sub_1 n : n > 0 -> 'X^n - 1 \\is monic.\nProof.\nmove=> n_gt0; rewrite monicE lead_coefE size_Xn_sub_1 // coefB.\nby rewrite coefXn coef1 eqxx eqn0Ngt n_gt0 subr0.\nQed.\n\nDefinition root_of_unity n : pred R := root ('X^n - 1).\nLocal Notation \"n .-unity_root\" := (root_of_unity n) : ring_scope.\n\nLemma unity_rootE n z : n.-unity_root z = (z ^+ n == 1).\nProof.\nby rewrite /root_of_unity rootE hornerD hornerN hornerXn hornerC subr_eq0.\nQed.\n\nLemma unity_rootP n z : reflect (z ^+ n = 1) (n.-unity_root z).\nProof. by rewrite unity_rootE; exact: eqP. Qed.\n\nDefinition primitive_root_of_unity n z :=\n  (n > 0) && [forall i : 'I_n, i.+1.-unity_root z == (i.+1 == n)].\nLocal Notation \"n .-primitive_root\" := (primitive_root_of_unity n) : ring_scope.\n\nLemma prim_order_exists n z :\n  n > 0 -> z ^+ n = 1 -> {m | m.-primitive_root z & (m %| n)}.\nProof.\nmove=> n_gt0 zn1.\nhave: exists m, (m > 0) && (z ^+ m == 1) by exists n; rewrite n_gt0 /= zn1.\ncase/ex_minnP=> m /andP[m_gt0 /eqP zm1] m_min.\nexists m.\n  apply/andP; split=> //; apply/eqfunP=> [[i]] /=.\n  rewrite leq_eqVlt unity_rootE.\n  case: eqP => [-> _ | _]; first by rewrite zm1 eqxx.\n  by apply: contraTF => zi1; rewrite -leqNgt m_min.\nhave: n %% m < m by rewrite ltn_mod.\napply: contraLR; rewrite -lt0n -leqNgt => nm_gt0; apply: m_min.\nby rewrite nm_gt0 /= expr_mod ?zn1.\nQed.\n\nSection OnePrimitive.\n\nVariables (n : nat) (z : R).\nHypothesis prim_z : n.-primitive_root z.\n\nLemma prim_order_gt0 : n > 0. Proof. by case/andP: prim_z. Qed.\nLet n_gt0 := prim_order_gt0.\n\nLemma prim_expr_order : z ^+ n = 1.\nProof.\ncase/andP: prim_z => _; rewrite -(prednK n_gt0); move/forallP; move/(_ ord_max).\nby rewrite unity_rootE eqxx; do 2!move/eqP.\nQed.\n\nLemma prim_expr_mod i : z ^+ (i %% n) = z ^+ i.\nProof. exact: expr_mod prim_expr_order. Qed.\n\nLemma prim_order_dvd i : (n %| i) = (z ^+ i == 1).\nProof.\nmove: n_gt0; rewrite -prim_expr_mod /dvdn -(ltn_mod i).\ncase: {i}(i %% n)%N => [|i] lt_i; first by rewrite !eqxx.\ncase/andP: prim_z => _; move/forallP; move/(_ (Ordinal (ltnW lt_i))).\nby move/eqP; rewrite unity_rootE eqn_leq andbC leqNgt lt_i.\nQed.\n\nLemma eq_prim_root_expr i j : (z ^+ i == z ^+ j) = (i == j %[mod n]).\nProof.\nwlog le_ji: i j / j <= i.\n  move=> IH; case: (leqP j i); last move/ltnW; move/IH=> //.\n  by rewrite eq_sym (eq_sym (j %% n)%N).\nrewrite -{1}(subnKC le_ji) exprD -prim_expr_mod eqn_mod_dvd //.\nrewrite prim_order_dvd; apply/eqP/eqP=> [|->]; last by rewrite mulr1.\nmove/(congr1 ( *%R (z ^+ (n - j %% n)))); rewrite mulrA -exprD.\nby rewrite subnK ?prim_expr_order ?mul1r // ltnW ?ltn_mod.\nQed.\n\nLemma exp_prim_root k : (n %/ gcdn k n).-primitive_root (z ^+ k).\nProof.\nset d := gcdn k n; have d_gt0: (0 < d)%N by rewrite gcdn_gt0 orbC n_gt0.\nhave [d_dv_k d_dv_n]: (d %| k /\\ d %| n)%N by rewrite dvdn_gcdl dvdn_gcdr.\nset q := (n %/ d)%N; rewrite /q.-primitive_root ltn_divRL // n_gt0.\napply/forallP=> i; rewrite unity_rootE -exprM -prim_order_dvd.\nrewrite -(divnK d_dv_n) -/q -(divnK d_dv_k) mulnAC dvdn_pmul2r //.\napply/eqP; apply/idP/idP=> [|/eqP->]; last by rewrite dvdn_mull.\nrewrite Gauss_dvdr; first by rewrite eqn_leq ltn_ord; exact: dvdn_leq.\nby rewrite /coprime gcdnC -(eqn_pmul2r d_gt0) mul1n muln_gcdl !divnK.\nQed.\n\nLemma dvdn_prim_root m : (m %| n)%N -> m.-primitive_root (z ^+ (n %/ m)).\nProof.\nset k := (n %/ m)%N => m_dv_n; rewrite -{1}(mulKn m n_gt0) -divnA // -/k.\nby rewrite -{1}(@gcdn_idPl k n _) ?exp_prim_root // -(divnK m_dv_n) dvdn_mulr.\nQed.\n\nEnd OnePrimitive.\n\nLemma prim_root_exp_coprime n z k :\n  n.-primitive_root z -> n.-primitive_root (z ^+ k) = coprime k n.\nProof.\nmove=> prim_z;have n_gt0 := prim_order_gt0 prim_z.\napply/idP/idP=> [prim_zk | co_k_n].\n  set d := gcdn k n; have dv_d_n: (d %| n)%N := dvdn_gcdr _ _.\n  rewrite /coprime -/d -(eqn_pmul2r n_gt0) mul1n -{2}(gcdnMl n d).\n  rewrite -{2}(divnK dv_d_n) (mulnC _ d) -muln_gcdr (gcdn_idPr _) //.\n  rewrite (prim_order_dvd prim_zk) -exprM -(prim_order_dvd prim_z).\n  by rewrite muln_divCA_gcd dvdn_mulr.\nhave zkn_1: z ^+ k ^+ n = 1 by rewrite exprAC (prim_expr_order prim_z) expr1n.\nhave{zkn_1} [m prim_zk dv_m_n]:= prim_order_exists n_gt0 zkn_1.\nsuffices /eqP <-: m == n by [].\nrewrite eqn_dvd dv_m_n -(@Gauss_dvdr n k m) 1?coprime_sym //=.\nby rewrite (prim_order_dvd prim_z) exprM (prim_expr_order prim_zk).\nQed.\n\n(* Lifting a ring predicate to polynomials. *)\n\nDefinition polyOver (S : pred_class) :=\n  [qualify a p : {poly R} | all (mem S) p].\n\nFact polyOver_key S : pred_key (polyOver S). Proof. by []. Qed.\nCanonical polyOver_keyed S := KeyedQualifier (polyOver_key S).\n\nLemma polyOverS (S1 S2 : pred_class) :\n  {subset S1 <= S2} -> {subset polyOver S1 <= polyOver S2}.\nProof.\nby move=> sS12 p /(all_nthP 0)S1p; apply/(all_nthP 0)=> i /S1p; apply: sS12.\nQed.\n\nLemma polyOver0 S : 0 \\is a polyOver S.\nProof. by rewrite qualifE polyseq0. Qed.\n\nLemma polyOver_poly (S : pred_class) n E :\n  (forall i, i < n -> E i \\in S) -> \\poly_(i < n) E i \\is a polyOver S.\nProof.\nmove=> S_E; apply/(all_nthP 0)=> i lt_i_p /=; rewrite coef_poly.\nby case: ifP => [/S_E// | /idP[]]; apply: leq_trans lt_i_p (size_poly n E).\nQed.\n\nSection PolyOverAdd.\n\nVariables (S : predPredType R) (addS : addrPred S) (kS : keyed_pred addS).\n\nLemma polyOverP {p} : reflect (forall i, p`_i \\in kS) (p \\in polyOver kS).\nProof.\napply: (iffP (all_nthP 0)) => [Sp i | Sp i _]; last exact: Sp.\nby have [/Sp // | /(nth_default 0)->] := ltnP i (size p); apply: rpred0.\nQed.\n\nLemma polyOverC c : (c%:P \\in polyOver kS) = (c \\in kS).\nProof.\nby rewrite qualifE polyseqC; case: eqP => [->|] /=; rewrite ?andbT ?rpred0.\nQed.\n\nFact polyOver_addr_closed : addr_closed (polyOver kS).\nProof. \nsplit=> [|p q Sp Sq]; first exact: polyOver0.\nby apply/polyOverP=> i; rewrite coefD rpredD ?(polyOverP _).\nQed.\nCanonical polyOver_addrPred := AddrPred polyOver_addr_closed.\n\nEnd PolyOverAdd.\n\nFact polyOverNr S (addS : zmodPred S) (kS : keyed_pred addS) :\n  oppr_closed (polyOver kS).\nProof.\nby move=> p /polyOverP Sp; apply/polyOverP=> i; rewrite coefN rpredN.\nQed.\nCanonical polyOver_opprPred S addS kS := OpprPred (@polyOverNr S addS kS).\nCanonical polyOver_zmodPred S addS kS := ZmodPred (@polyOverNr S addS kS).\n\nSection PolyOverSemiring.\n\nContext (S : pred_class) (ringS : @semiringPred R S) (kS : keyed_pred ringS).\n\nFact polyOver_mulr_closed : mulr_closed (polyOver kS).\nProof.\nsplit=> [|p q /polyOverP Sp /polyOverP Sq]; first by rewrite polyOverC rpred1.\nby apply/polyOverP=> i; rewrite coefM rpred_sum // => j _; apply: rpredM.\nQed.\nCanonical polyOver_mulrPred := MulrPred polyOver_mulr_closed.\nCanonical polyOver_semiringPred := SemiringPred polyOver_mulr_closed.\n\nLemma polyOverZ : {in kS & polyOver kS, forall c p, c *: p \\is a polyOver kS}.\nProof.\nby move=> c p Sc /polyOverP Sp; apply/polyOverP=> i; rewrite coefZ rpredM ?Sp. \nQed.\n\nLemma polyOverX : 'X \\in polyOver kS.\nProof. by rewrite qualifE polyseqX /= rpred0 rpred1. Qed.\n\nLemma rpred_horner : {in polyOver kS & kS, forall p x, p.[x] \\in kS}.\nProof.\nmove=> p x /polyOverP Sp Sx; rewrite horner_coef rpred_sum // => i _.\nby rewrite rpredM ?rpredX.\nQed.\n\nEnd PolyOverSemiring.\n\nSection PolyOverRing.\n\nContext (S : pred_class) (ringS : @subringPred R S) (kS : keyed_pred ringS).\nCanonical polyOver_smulrPred := SmulrPred (polyOver_mulr_closed kS).\nCanonical polyOver_subringPred := SubringPred (polyOver_mulr_closed kS).\n\nLemma polyOverXsubC c : ('X - c%:P \\in polyOver kS) = (c \\in kS).\nProof. by rewrite rpredBl ?polyOverX ?polyOverC. Qed.\n\nEnd PolyOverRing.\n\n(* Single derivative. *)\n\nDefinition deriv p := \\poly_(i < (size p).-1) (p`_i.+1 *+ i.+1).\n\nLocal Notation \"a ^` ()\" := (deriv a).\n\nLemma coef_deriv p i : p^`()`_i = p`_i.+1 *+ i.+1.\nProof.\nrewrite coef_poly -subn1 ltn_subRL.\nby case: leqP => // /(nth_default 0) ->; rewrite mul0rn.\nQed.\n\nLemma polyOver_deriv S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p, p^`() \\is a polyOver kS}.\nProof.\nby move=> p /polyOverP Kp; apply/polyOverP=> i; rewrite coef_deriv rpredMn ?Kp.\nQed.\n\nLemma derivC c : c%:P^`() = 0.\nProof. by apply/polyP=> i; rewrite coef_deriv coef0 coefC mul0rn. Qed.\n\nLemma derivX : ('X)^`() = 1.\nProof. by apply/polyP=> [[|i]]; rewrite coef_deriv coef1 coefX ?mul0rn. Qed.\n\nLemma derivXn n : 'X^n^`() = 'X^n.-1 *+ n.\nProof.\ncase: n => [|n]; first exact: derivC.\napply/polyP=> i; rewrite coef_deriv coefMn !coefXn eqSS.\nby case: eqP => [-> // | _]; rewrite !mul0rn.\nQed.\n\nFact deriv_is_linear : linear deriv.\nProof.\nmove=> k p q; apply/polyP=> i.\nby rewrite !(coef_deriv, coefD, coefZ) mulrnDl mulrnAr.\nQed.\nCanonical deriv_additive := Additive deriv_is_linear.\nCanonical deriv_linear := Linear deriv_is_linear.\n\nLemma deriv0 : 0^`() = 0.\nProof. exact: linear0. Qed.\n\nLemma derivD : {morph deriv : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma derivN : {morph deriv : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma derivB : {morph deriv : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma derivXsubC (a : R) : ('X - a%:P)^`() = 1.\nProof. by rewrite derivB derivX derivC subr0. Qed.\n\nLemma derivMn n p : (p *+ n)^`() = p^`() *+ n.\nProof. exact: linearMn. Qed.\n\nLemma derivMNn n p : (p *- n)^`() = p^`() *- n.\nProof. exact: linearMNn. Qed.\n\nLemma derivZ c p : (c *: p)^`() = c *: p^`().\nProof. by rewrite linearZ. Qed.\n\nLemma deriv_mulC c p : (c%:P * p)^`() = c%:P * p^`().\nProof. by rewrite !mul_polyC derivZ. Qed.\n\nLemma derivMXaddC p c : (p * 'X + c%:P)^`() = p + p^`() * 'X.\nProof.\napply/polyP=> i; rewrite raddfD /= derivC addr0 coefD !(coefMX, coef_deriv).\nby case: i; rewrite ?addr0.\nQed.\n\nLemma derivM p q : (p * q)^`() = p^`() * q + p * q^`().\nProof.\nelim/poly_ind: p => [|p b IHp]; first by rewrite !(mul0r, add0r, derivC).\nrewrite mulrDl -mulrA -commr_polyX mulrA -[_ * 'X]addr0 raddfD /= !derivMXaddC.\nby rewrite deriv_mulC IHp !mulrDl -!mulrA !commr_polyX !addrA.\nQed.\n\nDefinition derivE := Eval lazy beta delta [morphism_2 morphism_1] in\n  (derivZ, deriv_mulC, derivC, derivX, derivMXaddC, derivXsubC, derivM, derivB, \n   derivD, derivN, derivXn, derivM, derivMn).\n\n(* Iterated derivative. *)\nDefinition derivn n p := iter n deriv p.\n\nLocal Notation \"a ^` ( n )\" := (derivn n a) : ring_scope.\n\nLemma derivn0 p : p^`(0) = p.\nProof. by []. Qed.\n\nLemma derivn1 p : p^`(1) = p^`().\nProof. by []. Qed.\n\nLemma derivnS p n : p^`(n.+1) = p^`(n)^`().\nProof. by []. Qed.\n\nLemma derivSn p n : p^`(n.+1) = p^`()^`(n).\nProof. exact: iterSr. Qed.\n\nLemma coef_derivn n p i : p^`(n)`_i = p`_(n + i) *+ (n + i) ^_ n.\nProof.\nelim: n i => [|n IHn] i; first by rewrite ffactn0 mulr1n.\nby rewrite derivnS coef_deriv IHn -mulrnA ffactnSr addSnnS addKn.\nQed.\n\nLemma polyOver_derivn S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p n, p^`(n) \\is a polyOver kS}.\nProof.\nmove=> p /polyOverP Kp /= n; apply/polyOverP=> i.\nby rewrite coef_derivn rpredMn.\nQed.\n\nFact derivn_is_linear n : linear (derivn n).\nProof. by elim: n => // n IHn a p q; rewrite derivnS IHn linearP. Qed.\nCanonical derivn_additive n :=  Additive (derivn_is_linear n).\nCanonical derivn_linear n :=  Linear (derivn_is_linear n).\n\nLemma derivnC c n : c%:P^`(n) = if n == 0%N then c%:P else 0.\nProof. by case: n => // n; rewrite derivSn derivC linear0. Qed.\n\nLemma derivnD n : {morph derivn n : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma derivn_sub n : {morph derivn n : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma derivnMn n m p : (p *+ m)^`(n) = p^`(n) *+ m.\nProof. exact: linearMn. Qed.\n\nLemma derivnMNn n m p : (p *- m)^`(n) = p^`(n) *- m.\nProof. exact: linearMNn. Qed.\n\nLemma derivnN n : {morph derivn n : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma derivnZ n : scalable (derivn n).\nProof. exact: linearZZ. Qed.\n\nLemma derivnXn m n : 'X^m^`(n) = 'X^(m - n) *+ m ^_ n.\nProof.\napply/polyP=>i; rewrite coef_derivn coefMn !coefXn.\ncase: (ltnP m n) => [lt_m_n | le_m_n].\n  by rewrite eqn_leq leqNgt ltn_addr // mul0rn ffact_small.\nby rewrite -{1 3}(subnKC le_m_n) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn.\nQed.\n\nLemma derivnMXaddC n p c :\n  (p * 'X + c%:P)^`(n.+1) = p^`(n) *+ n.+1  + p^`(n.+1) * 'X.\nProof.\nelim: n => [|n IHn]; first by rewrite derivn1 derivMXaddC.\nrewrite derivnS IHn derivD derivM derivX mulr1 derivMn -!derivnS.\nby rewrite addrA addrAC -mulrSr.\nQed.\n\nLemma derivn_poly0 p n : size p <= n -> p^`(n) = 0.\nProof.\nmove=> le_p_n; apply/polyP=> i; rewrite coef_derivn.\nrewrite nth_default; first by rewrite mul0rn coef0.\nby apply: leq_trans le_p_n _; apply leq_addr.\nQed.\n\nLemma lt_size_deriv (p : {poly R}) : p != 0 -> size p^`() < size p.\nProof. by move=> /polySpred->; exact: size_poly. Qed.\n\n(* A normalising version of derivation to get the division by n! in Taylor *)\n\nDefinition nderivn n p := \\poly_(i < size p - n) (p`_(n + i) *+  'C(n + i, n)).\n\nLocal Notation \"a ^`N ( n )\" := (nderivn n a) : ring_scope.\n\nLemma coef_nderivn n p i : p^`N(n)`_i = p`_(n + i) *+  'C(n + i, n).\nProof.\nrewrite coef_poly ltn_subRL; case: leqP => // le_p_ni.\nby rewrite nth_default ?mul0rn.\nQed.\n\n(* Here is the division by n! *)\nLemma nderivn_def n p : p^`(n) = p^`N(n) *+ n`!.\nProof.\nby apply/polyP=> i; rewrite coefMn coef_nderivn coef_derivn -mulrnA bin_ffact.\nQed.\n\nLemma polyOver_nderivn S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS, forall p n, p^`N(n) \\in polyOver kS}.\nProof.\nmove=> p /polyOverP Sp /= n; apply/polyOverP=> i.\nby rewrite coef_nderivn rpredMn.\nQed.\n\nLemma nderivn0 p : p^`N(0) = p.\nProof. by rewrite -[p^`N(0)](nderivn_def 0). Qed.\n\nLemma nderivn1 p : p^`N(1) = p^`().\nProof. by rewrite -[p^`N(1)](nderivn_def 1). Qed.\n\nLemma nderivnC c n : (c%:P)^`N(n) = if n == 0%N then c%:P else 0.\nProof.\napply/polyP=> i; rewrite coef_nderivn.\nby case: n => [|n]; rewrite ?bin0 // coef0 coefC mul0rn.\nQed.\n\nLemma nderivnXn m n : 'X^m^`N(n) = 'X^(m - n) *+ 'C(m, n).\nProof.\napply/polyP=> i; rewrite coef_nderivn coefMn !coefXn.\nhave [lt_m_n | le_n_m] := ltnP m n.\n  by rewrite eqn_leq leqNgt ltn_addr // mul0rn bin_small.\nby rewrite -{1 3}(subnKC le_n_m) eqn_add2l; case: eqP => [->|]; rewrite ?mul0rn.\nQed.\n\nFact nderivn_is_linear n : linear (nderivn n).\nProof.\nmove=> k p q; apply/polyP=> i.\nby rewrite !(coef_nderivn, coefD, coefZ) mulrnDl mulrnAr.\nQed.\nCanonical nderivn_additive n := Additive(nderivn_is_linear n).\nCanonical nderivn_linear n := Linear (nderivn_is_linear n).\n\nLemma nderivnD n : {morph nderivn n : p q / p + q}.\nProof. exact: linearD. Qed.\n\nLemma nderivnB n : {morph nderivn n : p q / p - q}.\nProof. exact: linearB. Qed.\n\nLemma nderivnMn n m p : (p *+ m)^`N(n) = p^`N(n) *+ m.\nProof. exact: linearMn. Qed.\n\nLemma nderivnMNn n m p : (p *- m)^`N(n) = p^`N(n) *- m.\nProof. exact: linearMNn. Qed.\n\nLemma nderivnN n : {morph nderivn n : p / - p}.\nProof. exact: linearN. Qed.\n\nLemma nderivnZ n : scalable (nderivn n).\nProof. exact: linearZZ. Qed.\n\nLemma nderivnMXaddC n p c :\n  (p * 'X + c%:P)^`N(n.+1) = p^`N(n) + p^`N(n.+1) * 'X.\nProof.\napply/polyP=> i; rewrite coef_nderivn !coefD !coefMX coefC.\nrewrite !addSn /= !coef_nderivn addr0 binS mulrnDr addrC; congr (_ + _).\nby rewrite addSnnS; case: i; rewrite // addn0 bin_small.\nQed.\n\nLemma nderivn_poly0 p n : size p <= n -> p^`N(n) = 0.\nProof.\nmove=> le_p_n; apply/polyP=> i; rewrite coef_nderivn.\nrewrite nth_default; first by rewrite mul0rn coef0.\nby apply: leq_trans le_p_n _; apply leq_addr.\nQed.\n\nLemma nderiv_taylor p x h :\n  GRing.comm x h -> p.[x + h] = \\sum_(i < size p) p^`N(i).[x] * h ^+ i.\nProof.\nmove/commrX=> cxh; elim/poly_ind: p => [|p c IHp].\n  by rewrite size_poly0 big_ord0 horner0.\nrewrite hornerMXaddC size_MXaddC.\nhave [-> | nz_p] := altP (p =P 0).\n  rewrite horner0 !simp; have [-> | _] := c =P 0; first by rewrite big_ord0.\n  by rewrite size_poly0 big_ord_recl big_ord0 nderivn0 hornerC !simp.\nrewrite big_ord_recl nderivn0 !simp hornerMXaddC addrAC; congr (_ + _).\nrewrite mulrDr {}IHp !big_distrl polySpred //= big_ord_recl /= mulr1 -addrA.\nrewrite nderivn0 /bump /(addn 1) /=; congr (_ + _).\nrewrite !big_ord_recr /= nderivnMXaddC -mulrA -exprSr -polySpred // !addrA.\ncongr (_ + _); last by rewrite (nderivn_poly0 (leqnn _)) !simp.\nrewrite addrC -big_split /=; apply: eq_bigr => i _.\nby rewrite nderivnMXaddC !hornerE_comm /= mulrDl -!mulrA -exprSr cxh.\nQed.\n\nLemma nderiv_taylor_wide n p x h :\n    GRing.comm x h -> size p <= n ->\n  p.[x + h] = \\sum_(i < n) p^`N(i).[x] * h ^+ i.\nProof.\nmove/nderiv_taylor=> -> le_p_n.\nrewrite (big_ord_widen n (fun i => p^`N(i).[x] * h ^+ i)) // big_mkcond.\napply: eq_bigr => i _; case: leqP => // /nderivn_poly0->.\nby rewrite horner0 simp.\nQed.\n\nEnd PolynomialTheory.\n\nPrenex Implicits polyC Poly lead_coef root horner polyOver.\nImplicit Arguments monic [[R]].\nNotation \"\\poly_ ( i < n ) E\" := (poly n (fun i => E)) : ring_scope.\nNotation \"c %:P\" := (polyC c) : ring_scope.\nNotation \"'X\" := (polyX _) : ring_scope.\nNotation \"''X^' n\" := ('X ^+ n) : ring_scope.\nNotation \"p .[ x ]\" := (horner p x) : ring_scope.\nNotation \"n .-unity_root\" := (root_of_unity n) : ring_scope.\nNotation \"n .-primitive_root\" := (primitive_root_of_unity n) : ring_scope.\nNotation \"a ^` ()\" := (deriv a) : ring_scope.\nNotation \"a ^` ( n )\" := (derivn n a) : ring_scope.\nNotation \"a ^`N ( n )\" := (nderivn n a) : ring_scope.\n\nImplicit Arguments monicP [R p].\nImplicit Arguments rootP [R p x].\nImplicit Arguments rootPf [R p x].\nImplicit Arguments rootPt [R p x].\nImplicit Arguments unity_rootP [R n z].\nImplicit Arguments polyOverP [[R] [S0] [addS] [kS] [p]].\n\n(* Container morphism. *)\nSection MapPoly.\n\nSection Definitions.\n\nVariables (aR rR : ringType) (f : aR -> rR).\n\nDefinition map_poly (p : {poly aR}) := \\poly_(i < size p) f p`_i.\n\n(* Alternative definition; the one above is more convenient because it lets *)\n(* us use the lemmas on \\poly, e.g., size (map_poly p) <= size p is an      *)\n(* instance of size_poly.                                                   *)\nLemma map_polyE p : map_poly p = Poly (map f p).\nProof.\nrewrite /map_poly unlock; congr Poly.\napply: (@eq_from_nth _ 0); rewrite size_mkseq ?size_map // => i lt_i_p.\nby rewrite (nth_map 0) ?nth_mkseq.\nQed.\n\nDefinition commr_rmorph u := forall x, GRing.comm u (f x).\n\nDefinition horner_morph u of commr_rmorph u := fun p => (map_poly p).[u].\n\nEnd Definitions.\n\nVariables aR rR : ringType.\n\nSection Combinatorial.\n\nVariables (iR : ringType) (f : aR -> rR).\nLocal Notation \"p ^f\" := (map_poly f p) : ring_scope.\n\nLemma map_poly0 : 0^f = 0.\nProof. by rewrite map_polyE polyseq0. Qed.\n\nLemma eq_map_poly (g : aR -> rR) : f =1 g -> map_poly f =1 map_poly g.\nProof. by move=> eq_fg p; rewrite !map_polyE (eq_map eq_fg). Qed.\n\nLemma map_poly_id g (p : {poly iR}) :\n  {in (p : seq iR), g =1 id} -> map_poly g p = p.\nProof. by move=> g_id; rewrite map_polyE map_id_in ?polyseqK. Qed.\n\nLemma coef_map_id0 p i : f 0 = 0 -> (p^f)`_i = f p`_i.\nProof.\nby move=> f0; rewrite coef_poly; case: ltnP => // le_p_i; rewrite nth_default.\nQed.\n\nLemma map_poly_comp_id0 (g : iR -> aR) p :\n  f 0 = 0 -> map_poly (f \\o g) p = (map_poly g p)^f.\nProof.\nmove=> f0; apply/polyP => i; rewrite !coef_poly.\nhave [lt_i_p | _] := ifP; last by rewrite f0 if_same.\ncase: ifPn => //=; rewrite -leqNgt; move/leq_sizeP; move/(_ _ (leqnn _)).\nby rewrite coef_poly lt_i_p; move->.\nQed.\n\nLemma size_map_poly_id0 p : f (lead_coef p) != 0 -> size p^f = size p.\nProof. by move=> nz_fp; apply: size_poly_eq. Qed.\n\nLemma map_poly_eq0_id0 p : f (lead_coef p) != 0 -> (p^f == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /size_map_poly_id0->. Qed.\n\nLemma lead_coef_map_id0 p :\n  f 0 = 0 -> f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p).\nProof.\nby move=> f0 nz_fp; rewrite lead_coefE coef_map_id0 ?size_map_poly_id0.\nQed.\n\nHypotheses (inj_f : injective f) (f_0 : f 0 = 0).\n\nLemma size_map_inj_poly p : size p^f = size p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite map_poly0 !size_poly0.\nby rewrite size_map_poly_id0 // -f_0 (inj_eq inj_f) lead_coef_eq0.\nQed.\n\nLemma map_inj_poly : injective (map_poly f).\nProof.\nmove=> p q /polyP eq_pq; apply/polyP=> i; apply: inj_f.\nby rewrite -!coef_map_id0 ?eq_pq.\nQed.\n\nLemma lead_coef_map_inj p : lead_coef p^f = f (lead_coef p).\nProof. by rewrite !lead_coefE size_map_inj_poly coef_map_id0. Qed.\n\nEnd Combinatorial.\n\nLemma map_polyK (f : aR -> rR) g :\n  cancel g f -> f 0 = 0 -> cancel (map_poly g) (map_poly f).\nProof.\nby move=> gK f_0 p; rewrite /= -map_poly_comp_id0 ?map_poly_id // => x _ //=.\nQed.\n\nSection Additive.\n\nVariables (iR : ringType) (f : {additive aR -> rR}).\n\nLocal Notation \"p ^f\" := (map_poly (GRing.Additive.apply f) p) : ring_scope.\n\nLemma coef_map p i : p^f`_i = f p`_i.\nProof. exact: coef_map_id0 (raddf0 f). Qed.\n\nLemma map_poly_comp (g : iR -> aR) p :\n  map_poly (f \\o g) p = map_poly f (map_poly g p).\nProof. exact: map_poly_comp_id0 (raddf0 f). Qed.\n\nFact map_poly_is_additive : additive (map_poly f).\nProof. by move=> p q; apply/polyP=> i; rewrite !(coef_map, coefB) raddfB. Qed.\nCanonical map_poly_additive := Additive map_poly_is_additive.\n\nLemma map_polyC a : (a%:P)^f = (f a)%:P.\nProof. by apply/polyP=> i; rewrite !(coef_map, coefC) -!mulrb raddfMn. Qed.\n\nLemma lead_coef_map_eq p :\n  f (lead_coef p) != 0 -> lead_coef p^f = f (lead_coef p).\nProof. exact: lead_coef_map_id0 (raddf0 f). Qed.\n\nEnd Additive.\n\nVariable f : {rmorphism aR -> rR}.\nImplicit Types p : {poly aR}.\n\nLocal Notation \"p ^f\" := (map_poly (GRing.RMorphism.apply f) p) : ring_scope.\n\nFact map_poly_is_rmorphism : rmorphism (map_poly f).\nProof.\nsplit; first exact: map_poly_is_additive.\nsplit=> [p q|]; apply/polyP=> i; last first.\n  by rewrite !(coef_map, coef1) /= rmorph_nat.\nrewrite coef_map /= !coefM /= !rmorph_sum; apply: eq_bigr => j _.\nby rewrite !coef_map rmorphM.\nQed.\nCanonical map_poly_rmorphism := RMorphism map_poly_is_rmorphism.\n\nLemma map_polyZ c p : (c *: p)^f = f c *: p^f.\nProof. by apply/polyP=> i; rewrite !(coef_map, coefZ) /= rmorphM. Qed.\nCanonical map_poly_linear :=\n  AddLinear (map_polyZ : scalable_for (f \\; *:%R) (map_poly f)).\nCanonical map_poly_lrmorphism := [lrmorphism of map_poly f].\n\nLemma map_polyX : ('X)^f = 'X.\nProof. by apply/polyP=> i; rewrite coef_map !coefX /= rmorph_nat. Qed.\n\nLemma map_polyXn n : ('X^n)^f = 'X^n.\nProof. by rewrite rmorphX /= map_polyX. Qed.\n\nLemma monic_map p : p \\is monic -> p^f \\is monic.\nProof.\nmove/monicP=> mon_p; rewrite monicE.\nby rewrite lead_coef_map_eq mon_p /= rmorph1 ?oner_neq0.\nQed.\n\nLemma horner_map p x : p^f.[f x] = f p.[x].\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(rmorph0, horner0).\nrewrite hornerMXaddC !rmorphD !rmorphM /=.\nby rewrite map_polyX map_polyC hornerMXaddC IHp.\nQed.\n\nLemma map_comm_poly p x : comm_poly p x -> comm_poly p^f (f x).\nProof. by rewrite /comm_poly horner_map -!rmorphM // => ->. Qed.\n\nLemma map_comm_coef p x : comm_coef p x -> comm_coef p^f (f x).\nProof. by move=> cpx i; rewrite coef_map -!rmorphM ?cpx. Qed.\n\nLemma rmorph_root p x : root p x -> root p^f (f x).\nProof. by move/eqP=> px0; rewrite rootE horner_map px0 rmorph0. Qed.\n\nLemma rmorph_unity_root n z : n.-unity_root z -> n.-unity_root (f z).\nProof.\nmove/rmorph_root; rewrite rootE rmorphB hornerD hornerN.\nby rewrite /= map_polyXn rmorph1 hornerC hornerXn subr_eq0 unity_rootE.\nQed.\n\nSection HornerMorph.\n\nVariable u : rR.\nHypothesis cfu : commr_rmorph f u.\n\nLemma horner_morphC a : horner_morph cfu a%:P = f a.\nProof. by rewrite /horner_morph map_polyC hornerC. Qed.\n\nLemma horner_morphX : horner_morph cfu 'X = u.\nProof. by rewrite /horner_morph map_polyX hornerX. Qed.\n\nFact horner_is_lrmorphism : lrmorphism_for (f \\; *%R) (horner_morph cfu).\nProof.\nrewrite /horner_morph; split=> [|c p]; last by rewrite linearZ hornerZ.\nsplit=> [p q|]; first by rewrite /horner_morph rmorphB hornerD hornerN.\nsplit=> [p q|]; last by rewrite /horner_morph rmorph1 hornerC.\nrewrite /horner_morph rmorphM /= hornerM_comm //.\nby apply: comm_coef_poly => i; rewrite coef_map cfu.\nQed.\nCanonical horner_additive := Additive horner_is_lrmorphism.\nCanonical horner_rmorphism := RMorphism horner_is_lrmorphism.\nCanonical horner_linear := AddLinear horner_is_lrmorphism.\nCanonical horner_lrmorphism := [lrmorphism of horner_morph cfu].\n\nEnd HornerMorph.\n\nLemma deriv_map p : p^f^`() = (p^`())^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_deriv) //= rmorphMn. Qed.\n\nLemma derivn_map p n : p^f^`(n) = (p^`(n))^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_derivn) //= rmorphMn. Qed.\n\nLemma nderivn_map p n : p^f^`N(n) = (p^`N(n))^f.\nProof. by apply/polyP => i; rewrite !(coef_map, coef_nderivn) //= rmorphMn. Qed.\n\nEnd MapPoly.\n\n(* Morphisms from the polynomial ring, and the initiality of polynomials  *)\n(* with respect to these.                                                 *)\nSection MorphPoly.\n\nVariable (aR rR : ringType) (pf : {rmorphism {poly aR} -> rR}).\n\nLemma poly_morphX_comm : commr_rmorph (pf \\o polyC) (pf 'X).\nProof. by move=> a; rewrite /GRing.comm /= -!rmorphM // commr_polyX. Qed.\n\nLemma poly_initial : pf =1 horner_morph poly_morphX_comm.\nProof.\napply: poly_ind => [|p a IHp]; first by rewrite !rmorph0.\nby rewrite !rmorphD !rmorphM /= -{}IHp horner_morphC ?horner_morphX.\nQed.\n\nEnd MorphPoly.\n\nSection PolyCompose.\n\nVariable R : ringType.\nImplicit Types p q : {poly R}.\n\nDefinition comp_poly q p := (map_poly polyC p).[q].\n\nLocal Notation \"p \\Po q\" := (comp_poly q p) : ring_scope.\n\nLemma size_map_polyC p : size (map_poly polyC p) = size p.\nProof. exact: size_map_inj_poly (@polyC_inj R) _ _. Qed.\n\nLemma map_polyC_eq0 p : (map_poly polyC p == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 size_map_polyC. Qed.\n\nLemma comp_polyE p q : p \\Po q = \\sum_(i < size p) p`_i *: q^+i.\nProof.\nby rewrite [p \\Po q]horner_poly; apply: eq_bigr => i _; rewrite mul_polyC.\nQed.\n\nLemma polyOver_comp S (ringS : semiringPred S) (kS : keyed_pred ringS) :\n  {in polyOver kS &, forall p q, p \\Po q \\in polyOver kS}.\nProof.\nmove=> p q /polyOverP Sp Sq; rewrite comp_polyE rpred_sum // => i _.\nby rewrite polyOverZ ?rpredX.\nQed.\n\nLemma comp_polyCr p c : p \\Po c%:P = p.[c]%:P.\nProof. exact: horner_map. Qed.\n\nLemma comp_poly0r p : p \\Po 0 = (p`_0)%:P.\nProof. by rewrite comp_polyCr horner_coef0. Qed.\n\nLemma comp_polyC c p : c%:P \\Po p = c%:P.\nProof. by rewrite /(_ \\Po p) map_polyC hornerC. Qed.\n\nFact comp_poly_is_linear p : linear (comp_poly p).\nProof.\nmove=> a q r.\nby rewrite /comp_poly rmorphD /= map_polyZ !hornerE_comm mul_polyC.\nQed.\nCanonical comp_poly_additive p := Additive (comp_poly_is_linear p).\nCanonical comp_poly_linear p := Linear (comp_poly_is_linear p).\n\nLemma comp_poly0 p : 0 \\Po p = 0.\nProof. exact: raddf0. Qed.\n\nLemma comp_polyD p q r : (p + q) \\Po r = (p \\Po r) + (q \\Po r).\nProof. exact: raddfD. Qed.\n\nLemma comp_polyB p q r : (p - q) \\Po r = (p \\Po r) - (q \\Po r).\nProof. exact: raddfB. Qed.\n\nLemma comp_polyZ c p q : (c *: p) \\Po q = c *: (p \\Po q).\nProof. exact: linearZZ. Qed.\n\nLemma comp_polyXr p : p \\Po 'X = p.\nProof. by rewrite -{2}/(idfun p) poly_initial. Qed.\n\nLemma comp_polyX p : 'X \\Po p = p.\nProof. by rewrite /(_ \\Po p) map_polyX hornerX. Qed.\n\nLemma comp_poly_MXaddC c p q : (p * 'X + c%:P) \\Po q = (p \\Po q) * q + c%:P.\nProof.\nby rewrite /(_ \\Po q) rmorphD rmorphM /= map_polyX map_polyC hornerMXaddC.\nQed.\n\nLemma comp_polyXaddC_K p z : (p \\Po ('X + z%:P)) \\Po ('X - z%:P) = p.\nProof.\nhave addzK: ('X + z%:P) \\Po ('X - z%:P) = 'X.\n  by rewrite raddfD /= comp_polyC comp_polyX subrK.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !comp_poly0.\nrewrite comp_poly_MXaddC linearD /= comp_polyC {1}/comp_poly rmorphM /=.\nby rewrite hornerM_comm /comm_poly -!/(_ \\Po _) ?IHp ?addzK ?commr_polyX.\nQed.\n\nLemma size_comp_poly_leq p q :\n  size (p \\Po q) <= ((size p).-1 * (size q).-1).+1.\nProof.\nrewrite comp_polyE (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _.\nrewrite (leq_trans (size_scale_leq _ _)) // (leq_trans (size_exp_leq _ _)) //.\nby rewrite ltnS mulnC leq_mul // -{2}(subnKC (valP i)) leq_addr.\nQed.\n\nEnd PolyCompose.\n\nNotation \"p \\Po q\" := (comp_poly q p) : ring_scope.\n\nLemma map_comp_poly (aR rR : ringType) (f : {rmorphism aR -> rR}) p q :\n  map_poly f (p \\Po q) = map_poly f p \\Po map_poly f q.\nProof.\nelim/poly_ind: p => [|p a IHp]; first by rewrite !raddf0.\nrewrite comp_poly_MXaddC !rmorphD !rmorphM /= !map_polyC map_polyX.\nby rewrite comp_poly_MXaddC -IHp.\nQed.\n\nSection PolynomialComRing.\n\nVariable R : comRingType.\nImplicit Types p q : {poly R}.\n\nFact poly_mul_comm p q : p * q = q * p.\nProof.\napply/polyP=> i; rewrite coefM coefMr.\nby apply: eq_bigr => j _; rewrite mulrC.\nQed.\n\nCanonical poly_comRingType := Eval hnf in ComRingType {poly R} poly_mul_comm.\nCanonical polynomial_comRingType :=\n  Eval hnf in ComRingType (polynomial R) poly_mul_comm.\nCanonical poly_algType := Eval hnf in CommAlgType R {poly R}.\nCanonical polynomial_algType :=\n  Eval hnf in [algType R of polynomial R for poly_algType].\n\nLemma hornerM p q x : (p * q).[x] = p.[x] * q.[x].\nProof. by rewrite hornerM_comm //; exact: mulrC. Qed.\n\nLemma horner_exp p x n : (p ^+ n).[x] = p.[x] ^+ n.\nProof. by rewrite horner_exp_comm //; exact: mulrC. Qed.\n\nLemma horner_prod I r (P : pred I) (F : I -> {poly R}) x :\n  (\\prod_(i <- r | P i) F i).[x] = \\prod_(i <- r | P i) (F i).[x].\nProof. by elim/big_rec2: _ => [|i _ p _ <-]; rewrite (hornerM, hornerC). Qed.\n\nDefinition hornerE :=\n  (hornerD, hornerN, hornerX, hornerC, horner_cons,\n   simp, hornerCM, hornerZ, hornerM).\n\nDefinition horner_eval (x : R) := horner^~ x.\nLemma horner_evalE x p : horner_eval x p = p.[x]. Proof. by []. Qed.\n\nFact horner_eval_is_lrmorphism x : lrmorphism_for *%R (horner_eval x).\nProof.\nhave cxid: commr_rmorph idfun x by exact: mulrC.\nhave evalE : horner_eval x =1 horner_morph cxid.\n  by move=> p; congr _.[x]; rewrite map_poly_id.\nsplit=> [|c p]; last by rewrite !evalE /= -linearZ.\nby do 2?split=> [p q|]; rewrite !evalE (rmorphB, rmorphM, rmorph1).\nQed.\nCanonical horner_eval_additive x := Additive (horner_eval_is_lrmorphism x).\nCanonical horner_eval_rmorphism x := RMorphism (horner_eval_is_lrmorphism x).\nCanonical horner_eval_linear x := AddLinear (horner_eval_is_lrmorphism x).\nCanonical horner_eval_lrmorphism x := [lrmorphism of horner_eval x].\n\nFact comp_poly_multiplicative q : multiplicative (comp_poly q).\nProof.\nsplit=> [p1 p2|]; last by rewrite comp_polyC.\nby rewrite /comp_poly rmorphM hornerM_comm //; exact: mulrC.\nQed.\nCanonical comp_poly_rmorphism q := AddRMorphism (comp_poly_multiplicative q).\nCanonical comp_poly_lrmorphism q := [lrmorphism of comp_poly q].\n\nLemma comp_polyM p q r : (p * q) \\Po r = (p \\Po r) * (q \\Po r).\nProof. exact: rmorphM. Qed.\n\nLemma comp_polyA p q r : p \\Po (q \\Po r) = (p \\Po q) \\Po r.\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !comp_polyC.\nby rewrite !comp_polyD !comp_polyM !comp_polyX IHp !comp_polyC.\nQed.\n\nLemma horner_comp p q x : (p \\Po q).[x] = p.[q.[x]].\nProof. by apply: polyC_inj; rewrite -!comp_polyCr comp_polyA. Qed.\n\nLemma root_comp p q x : root (p \\Po q) x = root p (q.[x]).\nProof. by rewrite !rootE horner_comp. Qed.\n\nLemma deriv_comp p q : (p \\Po q) ^`() = (p ^`() \\Po q) * q^`().\nProof.\nelim/poly_ind: p => [|p c IHp]; first by rewrite !(deriv0, comp_poly0) mul0r.\nrewrite comp_poly_MXaddC derivD derivC derivM IHp derivMXaddC comp_polyD.\nby rewrite comp_polyM comp_polyX addr0 addrC mulrAC -mulrDl.\nQed.\n\nLemma deriv_exp p n : (p ^+ n)^`() = p^`() * p ^+ n.-1 *+ n.\nProof.\nelim: n => [|n IHn]; first by rewrite expr0 mulr0n derivC.\nby rewrite exprS derivM {}IHn (mulrC p) mulrnAl -mulrA -exprSr mulrS; case n.\nQed.\n\nDefinition derivCE := (derivE, deriv_exp).\n\nEnd PolynomialComRing.\n\nSection PolynomialIdomain.\n\n(* Integral domain structure on poly *)\nVariable R : idomainType.\n\nImplicit Types (a b x y : R) (p q r m : {poly R}).\n\nLemma size_mul p q : p != 0 -> q != 0 -> size (p * q) = (size p + size q).-1.\nProof.\nby move=> nz_p nz_q; rewrite -size_proper_mul ?mulf_neq0 ?lead_coef_eq0.\nQed.\n\nFact poly_idomainAxiom p q : p * q = 0 -> (p == 0) || (q == 0).\nProof.\nmove=> pq0; apply/norP=> [[p_nz q_nz]]; move/eqP: (size_mul p_nz q_nz).\nby rewrite eq_sym pq0 size_poly0 (polySpred p_nz) (polySpred q_nz) addnS.\nQed.\n\nDefinition poly_unit : pred {poly R} :=\n  fun p => (size p == 1%N) && (p`_0 \\in GRing.unit).\n\nDefinition poly_inv p := if p \\in poly_unit then (p`_0)^-1%:P else p.\n\nFact poly_mulVp : {in poly_unit, left_inverse 1 poly_inv *%R}.\nProof.\nmove=> p Up; rewrite /poly_inv Up.\nby case/andP: Up => /size_poly1P[c _ ->]; rewrite coefC -polyC_mul => /mulVr->.\nQed.\n\nFact poly_intro_unit p q : q * p = 1 -> p \\in poly_unit.\nProof.\nmove=> pq1; apply/andP; split; last first.\n  apply/unitrP; exists q`_0.\n  by rewrite 2!mulrC -!/(coefp 0 _) -rmorphM pq1 rmorph1.\nhave: size (q * p) == 1%N by rewrite pq1 size_poly1.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite mulr0 size_poly0.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite mul0r size_poly0.\nrewrite size_mul // (polySpred nz_p) (polySpred nz_q) addnS addSn !eqSS.\nby rewrite addn_eq0 => /andP[].\nQed.\n\nFact poly_inv_out : {in [predC poly_unit], poly_inv =1 id}.\nProof. by rewrite /poly_inv => p /negbTE/= ->. Qed.\n\nDefinition poly_comUnitMixin :=\n  ComUnitRingMixin poly_mulVp poly_intro_unit poly_inv_out.\n\nCanonical poly_unitRingType :=\n  Eval hnf in UnitRingType {poly R} poly_comUnitMixin.\nCanonical polynomial_unitRingType :=\n  Eval hnf in [unitRingType of polynomial R for poly_unitRingType].\n\nCanonical poly_unitAlgType := Eval hnf in [unitAlgType R of {poly R}].\nCanonical polynomial_unitAlgType := Eval hnf in [unitAlgType R of polynomial R].\n\nCanonical poly_comUnitRingType := Eval hnf in [comUnitRingType of {poly R}].\nCanonical polynomial_comUnitRingType :=\n  Eval hnf in [comUnitRingType of polynomial R].\n\nCanonical poly_idomainType :=\n  Eval hnf in IdomainType {poly R} poly_idomainAxiom.\nCanonical polynomial_idomainType :=\n  Eval hnf in [idomainType of polynomial R for poly_idomainType].\n\nLemma poly_unitE p :\n  (p \\in GRing.unit) = (size p == 1%N) && (p`_0 \\in GRing.unit).\nProof. by []. Qed.\n\nLemma poly_invE p : p ^-1 = if p \\in GRing.unit then (p`_0)^-1%:P else p.\nProof. by []. Qed.\n\nLemma polyC_inv c : c%:P^-1 = (c^-1)%:P.\nProof.\nhave [/rmorphV-> // | nUc] := boolP (c \\in GRing.unit).\nby rewrite !invr_out // poly_unitE coefC (negbTE nUc) andbF.\nQed.\n\nLemma rootM p q x : root (p * q) x = root p x || root q x.\nProof. by rewrite !rootE hornerM mulf_eq0. Qed.\n\nLemma rootZ x a p : a != 0 -> root (a *: p) x = root p x.\nProof. by move=> nz_a; rewrite -mul_polyC rootM rootC (negPf nz_a). Qed.\n\nLemma size_scale a p : a != 0 -> size (a *: p) = size p.\nProof. by move/lregP/lreg_size->. Qed.\n\nLemma size_Cmul a p : a != 0 -> size (a%:P * p) = size p.\nProof. by rewrite mul_polyC => /size_scale->. Qed.\n\nLemma lead_coefM p q : lead_coef (p * q) = lead_coef p * lead_coef q.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !(mul0r, lead_coef0).\nhave [-> | nz_q] := eqVneq q 0; first by rewrite !(mulr0, lead_coef0).\nby rewrite lead_coef_proper_mul // mulf_neq0 ?lead_coef_eq0.\nQed.\n\nLemma lead_coefZ a p : lead_coef (a *: p) = a * lead_coef p.\nProof. by rewrite -mul_polyC lead_coefM lead_coefC. Qed.\n\nLemma scale_poly_eq0 a p : (a *: p == 0) = (a == 0) || (p == 0).\nProof. by rewrite -mul_polyC mulf_eq0 polyC_eq0. Qed.\n\nLemma size_prod (I : finType) (P : pred I) (F : I -> {poly R}) :\n    (forall i, P i -> F i != 0) ->\n  size (\\prod_(i | P i) F i) = ((\\sum_(i | P i) size (F i)).+1 - #|P|)%N.\nProof.\nmove=> nzF; transitivity (\\sum_(i | P i) (size (F i)).-1).+1; last first.\n  apply: canRL (addKn _) _; rewrite addnS -sum1_card -big_split /=.\n  by congr _.+1; apply: eq_bigr => i /nzF/polySpred.\nelim/big_rec2: _ => [|i d p /nzF nzFi IHp]; first by rewrite size_poly1.\nby rewrite size_mul // -?size_poly_eq0 IHp // addnS polySpred.\nQed.\n\nLemma size_exp p n : (size (p ^+ n)).-1 = ((size p).-1 * n)%N.\nProof.\nelim: n => [|n IHn]; first by rewrite size_poly1 muln0.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite exprS mul0r size_poly0.\nrewrite exprS size_mul ?expf_neq0 // mulnS -{}IHn.\nby rewrite polySpred // [size (p ^+ n)]polySpred ?expf_neq0 ?addnS.\nQed.\n\nLemma lead_coef_exp p n : lead_coef (p ^+ n) = lead_coef p ^+ n.\nProof.\nelim: n => [|n IHn]; first by rewrite !expr0 lead_coef1.\nby rewrite !exprS lead_coefM IHn.\nQed.\n\nLemma root_prod_XsubC rs x :\n  root (\\prod_(a <- rs) ('X - a%:P)) x = (x \\in rs).\nProof.\nelim: rs => [|a rs IHrs]; first by rewrite rootE big_nil hornerC oner_eq0.\nby rewrite big_cons rootM IHrs root_XsubC.\nQed.\n\nLemma root_exp_XsubC n a x : root (('X - a%:P) ^+ n.+1) x = (x == a).\nProof. by rewrite rootE horner_exp expf_eq0 [_ == 0]root_XsubC. Qed.\n\nLemma size_comp_poly p q :\n  (size (p \\Po q)).-1 = ((size p).-1 * (size q).-1)%N.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite comp_poly0 size_poly0.\nhave [/size1_polyC-> | nc_q] := leqP (size q) 1.\n  by rewrite comp_polyCr !size_polyC -!sub1b -!subnS muln0.\nhave nz_q: q != 0 by rewrite -size_poly_eq0 -(subnKC nc_q).\nrewrite mulnC comp_polyE (polySpred nz_p) /= big_ord_recr /= addrC.\nrewrite size_addl size_scale ?lead_coef_eq0 ?size_exp //=.\nrewrite [X in _ < X]polySpred ?expf_neq0 // ltnS size_exp.\nrewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP => i _.\nrewrite (leq_trans (size_scale_leq _ _)) // polySpred ?expf_neq0 //.\nby rewrite size_exp -(subnKC nc_q) ltn_pmul2l.\nQed.\n\nLemma size_comp_poly2 p q : size q = 2 -> size (p \\Po q) = size p.\nProof.\nhave [/size1_polyC->| p_gt1] := leqP (size p) 1; first by rewrite comp_polyC.\nmove=> lin_q; have{lin_q} sz_pq: (size (p \\Po q)).-1 = (size p).-1.\n  by rewrite size_comp_poly lin_q muln1.\nrewrite -(ltn_predK p_gt1) -sz_pq -polySpred // -size_poly_gt0 ltnW //.\nby rewrite -subn_gt0 subn1 sz_pq -subn1 subn_gt0.\nQed.\n\nLemma comp_poly2_eq0 p q : size q = 2 -> (p \\Po q == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 => /size_comp_poly2->. Qed.\n\nEnd PolynomialIdomain.\n\nSection MapFieldPoly.\n\nVariables (F : fieldType) (R : ringType) (f : {rmorphism F -> R}).\n\nLocal Notation \"p ^f\" := (map_poly f p) : ring_scope.\n\nLemma size_map_poly p : size p^f = size p.\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite rmorph0 !size_poly0.\nby rewrite size_poly_eq // fmorph_eq0 // lead_coef_eq0.\nQed.\n\nLemma lead_coef_map p : lead_coef p^f = f (lead_coef p).\nProof.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite !(rmorph0, lead_coef0).\nby rewrite lead_coef_map_eq // fmorph_eq0 // lead_coef_eq0.\nQed.\n\nLemma map_poly_eq0 p : (p^f == 0) = (p == 0).\nProof. by rewrite -!size_poly_eq0 size_map_poly. Qed.\n\nLemma map_poly_inj : injective (map_poly f).\nProof.\nmove=> p q eqfpq; apply/eqP; rewrite -subr_eq0 -map_poly_eq0.\nby rewrite rmorphB /= eqfpq subrr.\nQed.\n\nLemma map_monic p : (p^f \\is monic) = (p \\is monic).\nProof. by rewrite monicE lead_coef_map fmorph_eq1. Qed.\n\nLemma map_poly_com p x : comm_poly p^f (f x).\nProof. exact: map_comm_poly (mulrC x _). Qed.\n\nLemma fmorph_root p x : root p^f (f x) = root p x.\nProof. by rewrite rootE horner_map // fmorph_eq0. Qed.\n\nLemma fmorph_unity_root n z : n.-unity_root (f z) = n.-unity_root z.\nProof. by rewrite !unity_rootE -(inj_eq (fmorph_inj f)) rmorphX ?rmorph1. Qed.\n\nLemma fmorph_primitive_root n z :\n  n.-primitive_root (f z) = n.-primitive_root z.\nProof.\nby congr (_ && _); apply: eq_forallb => i; rewrite fmorph_unity_root.\nQed.\n\nEnd MapFieldPoly.\n\nSection MaxRoots.\n\nVariable R : unitRingType.\nImplicit Types (x y : R) (rs : seq R) (p : {poly R}).\n\nDefinition diff_roots (x y : R) := (x * y == y * x) && (y - x \\in GRing.unit).\n\nFixpoint uniq_roots rs :=\n  if rs is x :: rs' then all (diff_roots x) rs' && uniq_roots rs' else true.\n\nLemma uniq_roots_prod_XsubC p rs :\n    all (root p) rs -> uniq_roots rs ->\n  exists q, p = q * \\prod_(z <- rs) ('X - z%:P).\nProof.\nelim: rs => [|z rs IHrs] /=; first by rewrite big_nil; exists p; rewrite mulr1.\ncase/andP=> rpz rprs /andP[drs urs]; case: IHrs => {urs rprs}// q def_p.\nhave [|q' def_q] := factor_theorem q z _; last first.\n  by exists q'; rewrite big_cons mulrA -def_q.\nrewrite {p}def_p in rpz.\nelim/last_ind: rs drs rpz => [|rs t IHrs] /=; first by rewrite big_nil mulr1.\nrewrite all_rcons => /andP[/andP[/eqP czt Uzt] /IHrs {IHrs}IHrs].\nrewrite -cats1 big_cat big_seq1 /= mulrA rootE hornerM_comm; last first.\n  by rewrite /comm_poly hornerXsubC mulrBl mulrBr czt.\nrewrite hornerXsubC -opprB mulrN oppr_eq0 -(mul0r (t - z)).\nby rewrite (inj_eq (mulIr Uzt)) => /IHrs.\nQed.\n\nTheorem max_ring_poly_roots p rs :\n  p != 0 -> all (root p) rs -> uniq_roots rs -> size rs < size p.\nProof.\nmove=> nz_p _ /(@uniq_roots_prod_XsubC p)[// | q def_p]; rewrite def_p in nz_p *.\nhave nz_q: q != 0 by apply: contraNneq nz_p => ->; rewrite mul0r.\nrewrite size_Mmonic ?monic_prod_XsubC // (polySpred nz_q) addSn /=.\nby rewrite size_prod_XsubC leq_addl.\nQed.\n\nLemma all_roots_prod_XsubC p rs :\n    size p = (size rs).+1 -> all (root p) rs -> uniq_roots rs ->\n  p = lead_coef p *: \\prod_(z <- rs) ('X - z%:P).\nProof.\nmove=> size_p /uniq_roots_prod_XsubC def_p Urs.\ncase/def_p: Urs => q -> {p def_p} in size_p *.\nhave [q0 | nz_q] := eqVneq q 0; first by rewrite q0 mul0r size_poly0 in size_p.\nhave{q nz_q size_p} /size_poly1P[c _ ->]: size q == 1%N.\n  rewrite -(eqn_add2r (size rs)) add1n -size_p.\n  by rewrite size_Mmonic ?monic_prod_XsubC // size_prod_XsubC addnS.\nby rewrite lead_coef_Mmonic ?monic_prod_XsubC // lead_coefC mul_polyC.\nQed.\n\nEnd MaxRoots.\n\nSection FieldRoots.\n\nVariable F : fieldType.\nImplicit Types (p : {poly F}) (rs : seq F).\n\nLemma poly2_root p : size p = 2 -> {r | root p r}.\nProof.\ncase: p => [[|p0 [|p1 []]] //= nz_p1]; exists (- p0 / p1).\nby rewrite /root addr_eq0 mul0r add0r mulrC divfK ?opprK.\nQed.\n\nLemma uniq_rootsE rs : uniq_roots rs = uniq rs.\nProof.\nelim: rs => //= r rs ->; congr (_ && _); rewrite -has_pred1 -all_predC.\nby apply: eq_all => t; rewrite /diff_roots mulrC eqxx unitfE subr_eq0.\nQed.\n\nTheorem max_poly_roots p rs :\n  p != 0 -> all (root p) rs -> uniq rs -> size rs < size p.\nProof. by rewrite -uniq_rootsE; exact: max_ring_poly_roots. Qed.\n\nSection UnityRoots.\n\nVariable n : nat.\n\nLemma max_unity_roots rs :\n  n > 0 -> all n.-unity_root rs -> uniq rs -> size rs <= n.\nProof.\nmove=> n_gt0 rs_n_1 Urs; have szPn := size_Xn_sub_1 F n_gt0.\nby rewrite -ltnS -szPn max_poly_roots -?size_poly_eq0 ?szPn.\nQed.\n\nLemma mem_unity_roots rs :\n    n > 0 -> all n.-unity_root rs -> uniq rs -> size rs = n ->\n  n.-unity_root =i rs.\nProof.\nmove=> n_gt0 rs_n_1 Urs sz_rs_n x; rewrite -topredE /=.\napply/idP/idP=> xn1; last exact: (allP rs_n_1).\napply: contraFT (ltnn n) => not_rs_x.\nby rewrite -{1}sz_rs_n (@max_unity_roots (x :: rs)) //= ?xn1 ?not_rs_x.\nQed.\n\n(* Showing the existence of a primitive root requires the theory in cyclic. *)\n\nVariable z : F.\nHypothesis prim_z : n.-primitive_root z.\n\nLet zn := [seq z ^+ i | i <- index_iota 0 n].\n\nLemma factor_Xn_sub_1 : \\prod_(0 <= i < n) ('X - (z ^+ i)%:P) = 'X^n - 1.\nProof.\ntransitivity (\\prod_(w <- zn) ('X - w%:P)); first by rewrite big_map.\nhave n_gt0: n > 0 := prim_order_gt0 prim_z.\nrewrite (@all_roots_prod_XsubC _ ('X^n - 1) zn); first 1 last.\n- by rewrite size_Xn_sub_1 // size_map size_iota subn0.\n- apply/allP=> _ /mapP[i _ ->] /=; rewrite rootE !hornerE hornerXn.\n  by rewrite exprAC (prim_expr_order prim_z) expr1n subrr.\n- rewrite uniq_rootsE map_inj_in_uniq ?iota_uniq // => i j.\n  rewrite !mem_index_iota => ltin ltjn /eqP.\n  by rewrite (eq_prim_root_expr prim_z) !modn_small // => /eqP.\nby rewrite (monicP (monic_Xn_sub_1 F n_gt0)) scale1r.\nQed.\n\nLemma prim_rootP x : x ^+ n = 1 -> {i : 'I_n | x = z ^+ i}.\nProof.\nmove=> xn1; pose logx := [pred i : 'I_n | x == z ^+ i].\ncase: (pickP logx) => [i /eqP-> | no_i]; first by exists i.\ncase: notF; suffices{no_i}: x \\in zn.\n  case/mapP=> i; rewrite mem_index_iota => lt_i_n def_x.\n  by rewrite -(no_i (Ordinal lt_i_n)) /= -def_x.\nrewrite -root_prod_XsubC big_map factor_Xn_sub_1.\nby rewrite [root _ x]unity_rootE xn1.\nQed.\n\nEnd UnityRoots.\n\nEnd FieldRoots.\n\nSection MapPolyRoots.\n\nVariables (F : fieldType) (R : unitRingType) (f : {rmorphism F -> R}).\n\nLemma map_diff_roots x y : diff_roots (f x) (f y) = (x != y).\nProof.\nrewrite /diff_roots -rmorphB // fmorph_unit // subr_eq0 //.\nby rewrite rmorph_comm // eqxx eq_sym.\nQed.\n\nLemma map_uniq_roots s : uniq_roots (map f s) = uniq s.\nProof.\nelim: s => //= x s ->; congr (_ && _); elim: s => //= y s ->.\nby rewrite map_diff_roots -negb_or.\nQed.\n\nEnd MapPolyRoots.\n\nSection AutPolyRoot.\n(* The action of automorphisms on roots of unity. *)\n\nVariable F : fieldType.\nImplicit Types u v : {rmorphism F -> F}.\n\nLemma aut_prim_rootP u z n :\n  n.-primitive_root z -> {k | coprime k n & u z = z ^+ k}.\nProof.\nmove=> prim_z; have:= prim_z; rewrite -(fmorph_primitive_root u) => prim_uz.\nhave [[k _] /= def_uz] := prim_rootP prim_z (prim_expr_order prim_uz).\nby exists k; rewrite // -(prim_root_exp_coprime _ prim_z) -def_uz.\nQed.\n\nLemma aut_unity_rootP u z n : n > 0 -> z ^+ n = 1 -> {k | u z = z ^+ k}.\nProof.\nby move=> _ /prim_order_exists[// | m /(aut_prim_rootP u)[k]]; exists k.\nQed.\n\nLemma aut_unity_rootC u v z n : n > 0 -> z ^+ n = 1 -> u (v z) = v (u z).\nProof.\nmove=> n_gt0 /(aut_unity_rootP _ n_gt0) def_z.\nhave [[i def_uz] [j def_vz]] := (def_z u, def_z v).\nby rewrite !(def_uz, def_vz, rmorphX) exprAC.\nQed.\n\nEnd AutPolyRoot.\n\nModule UnityRootTheory.\n\nNotation \"n .-unity_root\" := (root_of_unity n) : unity_root_scope.\nNotation \"n .-primitive_root\" := (primitive_root_of_unity n) : unity_root_scope.\nOpen Scope unity_root_scope.\n\nDefinition unity_rootE := unity_rootE.\nDefinition unity_rootP := @unity_rootP.\nImplicit Arguments unity_rootP [R n z].\n\nDefinition prim_order_exists := prim_order_exists.\nNotation prim_order_gt0 :=  prim_order_gt0.\nNotation prim_expr_order := prim_expr_order.\nDefinition prim_expr_mod := prim_expr_mod.\nDefinition prim_order_dvd := prim_order_dvd.\nDefinition eq_prim_root_expr := eq_prim_root_expr.\n\nDefinition rmorph_unity_root := rmorph_unity_root.\nDefinition fmorph_unity_root := fmorph_unity_root.\nDefinition fmorph_primitive_root := fmorph_primitive_root.\nDefinition max_unity_roots := max_unity_roots.\nDefinition mem_unity_roots := mem_unity_roots.\nDefinition prim_rootP := prim_rootP.\n\nEnd UnityRootTheory.\n\nModule PreClosedField.\nSection UseAxiom.\n\nVariable F : fieldType.\nHypothesis closedF : GRing.ClosedField.axiom F.\nImplicit Type p : {poly F}.\n\nLemma closed_rootP p : reflect (exists x, root p x) (size p != 1%N).\nProof.\nhave [-> | nz_p] := eqVneq p 0.\n  by rewrite size_poly0; left; exists 0; rewrite root0.\nrewrite neq_ltn {1}polySpred //=.\napply: (iffP idP) => [p_gt1 | [a]]; last exact: root_size_gt1.\npose n := (size p).-1; have n_gt0: n > 0 by rewrite -ltnS -polySpred.\nhave [a Dan] := closedF (fun i => - p`_i / lead_coef p) n_gt0.\nexists a; apply/rootP; rewrite horner_coef polySpred // big_ord_recr /= -/n.\nrewrite {}Dan mulr_sumr -big_split big1 //= => i _.\nby rewrite -!mulrA mulrCA mulNr mulVKf ?subrr ?lead_coef_eq0.\nQed.\n\nLemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0).\nProof.\napply: (iffP idP) => [nz_p | [x]]; last first.\n  by apply: contraNneq => ->; apply: root0.\nhave [[x /rootP p1x0]|] := altP (closed_rootP (p - 1)).\n  by exists x; rewrite -[p](subrK 1) /root hornerD p1x0 add0r hornerC oner_eq0.\nrewrite negbK => /size_poly1P[c _ /(canRL (subrK 1)) Dp].\nby exists 0; rewrite Dp -raddfD polyC_eq0 rootC in nz_p *.\nQed.\n\nEnd UseAxiom.\nEnd PreClosedField.\n\nSection ClosedField.\n\nVariable F : closedFieldType.\nImplicit Type p : {poly F}.\n\nLet closedF := @solve_monicpoly F.\n\nLemma closed_rootP p : reflect (exists x, root p x) (size p != 1%N).\nProof. exact: PreClosedField.closed_rootP. Qed.\n\nLemma closed_nonrootP p : reflect (exists x, ~~ root p x) (p != 0).\nProof. exact: PreClosedField.closed_nonrootP. Qed.\n\nLemma closed_field_poly_normal p :\n  {r : seq F | p = lead_coef p *: \\prod_(z <- r) ('X - z%:P)}.\nProof.\napply: sig_eqW; elim: {p}_.+1 {-2}p (ltnSn (size p)) => // n IHn p le_p_n.\nhave [/size1_polyC-> | p_gt1] := leqP (size p) 1.\n  by exists nil; rewrite big_nil lead_coefC alg_polyC.\nhave [|x /factor_theorem[q Dp]] := closed_rootP p _; first by rewrite gtn_eqF.\nhave nz_p: p != 0 by rewrite -size_poly_eq0 -(subnKC p_gt1).\nhave:= nz_p; rewrite Dp mulf_eq0 lead_coefM => /norP[nz_q nz_Xx].\nrewrite ltnS polySpred // Dp size_mul // size_XsubC addn2 in le_p_n.\nhave [r {1}->] := IHn q le_p_n; exists (x :: r).\nby rewrite lead_coefXsubC mulr1 big_cons -scalerAl mulrC.\nQed.\n\nEnd ClosedField.\n", "meta": {"author": "beta-ziliani", "repo": "ssreflect-1.4", "sha": "2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571", "save_path": "github-repos/coq/beta-ziliani-ssreflect-1.4", "path": "github-repos/coq/beta-ziliani-ssreflect-1.4/ssreflect-1.4-2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571/theories/poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7394787464322401}}
{"text": "(* Exercise 27 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_027 :\n  (forall x, P x \\/ Q x)\n->\n  (forall x, ~ P x -> Q x).\nProof.\nimp_i a1.\nall_i y.\nimp_i a2.\ndis_e (P y \\/ Q y) a3 a3.\nall_e (forall x:D, P x \\/ Q x) y.\nhyp a1.\nneg_e (P y).\nhyp a2.\nhyp a3.\nhyp a3.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak11/Taak11_pred027.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7394197805322862}}
{"text": "(**************************************\n  not Finish reading, not Finish exercise\n**************************************)\n\nRequire Import Coq.Setoids.Setoid List Nat.\nImport ListNotations.\n\n(** **** Exercise: 2 stars (and_exercise)  *)\nExample and_exercise: forall n m: nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m P.\n  split.\n  - destruct n.\n    + reflexivity.\n    + inversion P.\n  - destruct n.\n    + simpl in P. \n      rewrite P.\n      reflexivity.\n    + inversion P.\nQed.\n\n\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nLemma proj2: forall P Q: Prop, P /\\ Q -> Q.\nProof.\n  intros P Q [H1 H2].\n  apply H2.\nQed.\n\n\n\n\n(** **** Exercise: 2 stars (and_assoc)  *)\nTheorem and_assoc: forall P Q R: Prop, P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]].\n  split.\n  - split.\n    apply HP.\n    apply HQ.\n  - apply HR.\nQed.\n\n\n\n\n\n(** **** Exercise: 1 star (mult_eq_0)  *)\nLemma mult_eq_0: forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros [|n] [|m] P.\n  - left. reflexivity.\n  - left. reflexivity.\n  - right. reflexivity.\n  - inversion P.\nQed.\n\n\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut: forall P Q: Prop, P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q [HP|HQ].\n  - right.\n    apply HP.\n  - left.\n    apply HQ.\nQed.\n\n\n\n\n\n\n(** **** Exercise: 2 stars, optional (not_implies_our_not)  *)\nFact not_implies_our_not: forall (P: Prop),~P -> (forall (Q: Prop), P -> Q).\nProof.\n  intros P nP Q xP.\n  destruct nP.\n  apply xP.\nQed.\n\n\n\n\n\n(** **** Exercise: 2 stars, advanced, recommended (double_neg_inf)  *)\n(* not do it *)\n\n\n(** **** Exercise: 2 stars, recommended (contrapositive)  *)\nTheorem contrapositive: forall P Q: Prop, (P -> Q) -> (~Q -> ~P).\nProof.\n  unfold not.\n  intros P Q H1 H2 H3.\n  apply H1 in H3.\n  apply H2 in H3.\n  apply H3.\nQed.\n\n\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false: forall P: Prop, ~ (P /\\ ~P).\nProof.\n  intros P.\n  unfold not.\n  intros H.\n  destruct H as [H1 H2].\n  apply H2 in H1.\n  apply H1.\nQed.\n\n\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(* not do it *)\n\n\n\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\nTheorem iff_refl: forall P: Prop, P <-> P.\nProof.\n  intros P.\n  split.\n  - intros.\n    apply H.\n  - intros.\n    apply H.\nQed.      \n\n\n\nTheorem iff_trans: forall P Q R: Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R [H1 H2] [H3 H4].\n  split.\n  - intros.\n    apply H3.\n    apply H1.\n    apply H.\n  - intros.\n    apply H2.\n    apply H4.\n    apply H.\nQed.\n\n\n(** **** Exercise: 3 stars (or_distributes_over_and)  *)\nTheorem or_distributes_over_and: forall P Q R: Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n  - intros [H1 | H2].\n    + split.\n      * left. assumption.\n      * left. assumption.\n    + assert (Q). { apply proj1 in H2. assumption. }\n      assert (R). { apply proj2 in H2. assumption. }\n      split.\n      * right. assumption.\n      * right. assumption.\n  - intros [[H1|H2] [H3|H4]].\n    + left. apply H1.\n    + left. apply H1.\n    + left. apply H3.\n    + right. split. assumption. assumption.\nQed.\n\n\n\n(** **** Exercise: 1 star (dist_not_exists)  *)\nTheorem dist_not_exists: forall (X: Type)(P: X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  unfold not.\n  intros X P S [x].\n  apply H.\n  apply S.\nQed.\n  \n\n(** **** Exercise: 2 stars (dist_exists_or)  *)\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 X P Q.\n  split.\n  - intros [x0 [H1|H2]].\n    + left. exists x0. assumption.\n    + right. exists x0. assumption.\n  - intros [[x0 H] | [x0 H]].\n    + exists x0. left. assumption.\n    + exists x0. right. assumption.\nQed.\n\n\nFixpoint In {A: Type}(x: A)(l: list A): Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\n\n\n(** **** Exercise: 2 stars (In_map_iff)  *)\nLemma 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.\n  split.\n  - intros H.\n    induction l as [|a l R].\n    + simpl in H.\n      destruct H.\n    + simpl.\n      simpl in H.\n      destruct H as [H|H].\n      * exists a.\n        split.\n        apply H.\n        left. reflexivity.\n      * apply R in H.\n        destruct H as [x0 H].\n        exists x0.\n        destruct H as [H0 H1].\n        split.\n        apply H0.\n        right.\n        apply H1.\n  - intros [x [H P]].\n    induction l as [|a l R].\n    + destruct P.\n    + simpl.\n      simpl in P.\n      destruct P as [P|P].\n      * left.\n        subst.\n        reflexivity.\n      * right.\n        apply R in P.\n        apply P.\nQed.\n\n\n\n(** **** Exercise: 2 stars (in_app_iff)  *)\nLemma in_app_iff: forall A l l' (a: A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a.\n  split.\n  - induction l as [|x l H].\n    + simpl.\n      intros P.\n      right.\n      apply P.\n    + simpl.\n      intros P.\n      destruct P as [P|P].\n      * left.\n        left.\n        apply P.\n      * apply H in P.\n        destruct P as [P|P].\n        left.\n        right.\n        apply P.\n        right.\n        apply P.\n  - intros [H|H].\n    + induction l as [|x l P].\n      * destruct H.\n      * simpl.\n        simpl in H.\n        destruct H as [H|H].\n        left. apply H.\n        right. apply P in H. apply H.\n    + induction l as [|x l P].\n      * simpl.\n        apply H.\n      * simpl.\n        right.\n        apply P.\nQed.\n\n\n\n(** **** Exercise: 3 stars (All)  *)\n\nFixpoint All {T: Type}(P: T -> Prop)(l: list T): Prop :=\n  match l with\n  | nil => True\n  | h :: t => P h /\\ All P t\n  end.\n  \nLemma All_In:\n  forall T (P: T -> Prop)(l: list T), (forall x, In x l -> P x) <-> All P l.\nProof.\n  intros T P l.\n  split.\n  - intros H.\n    induction l as [|t l Q].\n    + simpl.\n      apply I.\n    + simpl.\n      simpl in H.\n      split.\n      * apply H.\n        left.\n        reflexivity.\n      * apply Q.\n        intros y R.\n        apply H.\n        right.\n        apply R.\n  - intros H x R.\n    induction l as [|t l Q].\n    + simpl in R.\n      destruct R.\n    + simpl in H.\n      simpl in R.\n      destruct R.\n      * subst.\n        destruct H as [H0 H1].\n        apply H0.\n      * apply Q.\n        destruct H.\n        apply H1.\n        apply H0.\nQed.\n\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\nDefinition combine_odd_even_imp (Podd Peven: nat -> Prop)(n: nat): Prop :=\n  if odd n then Podd n else Peven n.\n  \nDefinition combine_odd_even (Podd Peven: nat -> Prop): nat -> Prop :=\n  combine_odd_even_imp Podd Peven.\n\n(** To test your definition, prove the following facts: *)\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 Podd Peven n H P.\n  unfold combine_odd_even.\n  unfold combine_odd_even_imp.\n  destruct (odd n).\n  - apply H.\n    reflexivity.\n  - apply P.\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    odd n = true ->\n    Podd n.\nProof.\n  intros Podd Peven n H P.\n  unfold combine_odd_even in H.\n  unfold combine_odd_even_imp in H.\n  destruct (odd n).\n  - apply H.\n  - inversion P.\nQed.\n\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 Podd Peven n P Q.\n  unfold combine_odd_even in P.\n  unfold combine_odd_even_imp in P.\n  destruct (odd n).\n  - inversion Q.\n  - apply P.\nQed.\n\n\n\n\n(** **** Exercise: 4 stars (tr_rev)  *)\nAxiom functional_extensionality: forall {X Y: Type}{f g: X -> Y},\n  (forall (x: X), f x = g x) -> f = g.\n\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 := rev_append l [].\n\nLemma xyz: forall (X: Type)(l1 l2: list X), rev_append l1 l2 = rev_append l1 [] ++ l2.\nProof.\n  intros X l1 l2.\n  induction l1 as [|x l H].\n  - reflexivity.\n  - simpl.\n    induction l2 as [|y l2 H2].\n    + rewrite app_nil_r.\n      reflexivity.\n    + simpl.\nAdmitted.    \n\nLemma tr_rev_correct: forall X, @tr_rev X = @rev X.\nProof.\n  intros X.\n  apply functional_extensionality.\n  intros l.\n  induction l as [|x l H].\n  - reflexivity.\n  - simpl.\n    rewrite <- H.\n    unfold tr_rev.\n    simpl.\n    clear H.\n    generalize dependent x.\n    induction l as [|y l P].\n    + reflexivity.\n    + simpl.\n      intros x.\n      rewrite P.\n      simpl.\nAdmitted.\n\n\n(** **** Exercise: 3 stars (evenb_double_conv)  *)\nTheorem evenb_S: forall n: nat, even (S n) = negb (even n).\nProof. Admitted.\n\nTheorem double_negb: forall b: bool, negb (negb b) = b.\nProof. Admitted.\n\nTheorem evenb_double_conv: forall n,\n  exists k, n = if even n then double k\n                else S (double k).\nProof.\n  intros n.\n  induction n as [|n [k0 H]].\n  - simpl.\n    exists 0.\n    reflexivity.\n  - simpl.\n    destruct (even n) eqn:P.\n    + exists k0.\n      rewrite <- H.\n      simpl.\n      destruct n.\n      * reflexivity.\n      * rewrite evenb_S in P.\n        destruct (even n).\n        simpl in P.\n        inversion P.\n        reflexivity.\n    + exists (k0+1).\n      unfold double.\n      unfold double in H.\n      destruct n.\n      * inversion H.\n      * rewrite evenb_S in P.\n        destruct (even n).\n        rewrite H.\nAdmitted. (* use omega? *)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8740772335247532, "lm_q1q2_score": 0.7394190185340638}}
{"text": "Require Import Relations.\nSection Sequences.\n Variable A : Type.\n\n Variable R : A -> A -> Prop. \n\n Lemma not_acc : forall a b:A, R a b -> ~ Acc R a -> ~ Acc R b.\n Proof.\n  intros a b H H0 H1;  absurd (Acc R a); auto.\n  generalize a H; now induction H1.\n Qed.\n\n Lemma acc_imp : forall a b:A, R a b -> Acc R b -> Acc R a.\n Proof.\n  intros a b H H0;  generalize a H; now induction H0.\n Qed.\n\n Hypothesis W : well_founded R.\n #[local] Hint Resolve W : core.\n\t\n Section seq_intro.\n  Variable seq : nat -> A. \n\n  Let is_in_seq (x:A) :=  exists i : nat, x = seq i.\n\n  Lemma not_decreasing_aux : ~ (forall n:nat, R (seq (S n)) (seq n)). \n  Proof.\n   unfold not in |- *; intro Hseq.\n  assert  (H : forall a:A, is_in_seq a -> ~ Acc R a).\n  -   intro a; pattern a in |- *; apply well_founded_ind with A R; auto.\n      intros x Hx [i Hi]; generalize (Hseq i); intro H0; rewrite Hi.\n      apply not_acc with (seq (S i)); auto.\n      apply Hx.\n      +  rewrite Hi; auto.\n      +  exists (S i); auto.\n  - apply (H (seq 0)). \n    +  exists 0; trivial. \n    + apply W.\n Qed.\n\n\n End seq_intro.\n\n Theorem not_decreasing :\n  ~ (exists seq : nat -> A, (forall i:nat, R (seq (S i)) (seq i))).\n Proof.\n   intros [s Hs];  now apply (not_decreasing_aux s).\n Qed.\n\nEnd Sequences.\n\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch15_general_recursion/SRC/not_decreasing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7393633902910933}}
{"text": "Require Export ct04.\n\nSection DivConq.\n\nVariable A : Type.\nImplicit Type l : list A.\n\n(* div_conq_pair:\n * - works similar to induction (i.e. list_rect), but instead of cutting just\n *   head of the list in each recursive step, this induction principle cut two\n *   heads of the list in each recursive step.\n * - To prove some proposition P holds for all lists ls, one needs to prove the\n *   following:\n *   1. P holds for empty list, nil.\n *   2. P holds for one-element list, (a :: nil).\n *   3. P holds for two-elements list, (a1 :: a2 :: nil).\n *   4. If P hold (a1 :: a2 :: nil) and l, then P must also hold for\n *      (a1 :: a2 :: l).\n *)\n\nLemma div_conq_pair : forall (P : list A -> Type),\n    P nil -> (forall (a : A), P (a :: nil))\n    -> (forall (a1 a2 : A), P (a1 :: a2 :: nil))\n    -> (forall (a1 a2 : A) (l : list A), P (a1 :: a2 :: nil) -> P l \n       -> P (a1 :: a2 :: l)) \n    -> forall (l : list A), P l.\nProof.\nintros; eapply well_founded_induction_type. eapply lengthOrder_wf.\ndestruct x; auto; destruct x; auto. intros; apply X2; auto.\napply X3; unfold lengthOrder; simpl; auto.\nDefined.\n\nEnd DivConq.\n\nLtac div_conq_pair := eapply div_conq_pair.\n", "meta": {"author": "jinxinglim", "repo": "coq-chain", "sha": "e237c6b5f797f2af43237b68ff599d6cc0a8d60e", "save_path": "github-repos/coq/jinxinglim-coq-chain", "path": "github-repos/coq/jinxinglim-coq-chain/coq-chain-e237c6b5f797f2af43237b68ff599d6cc0a8d60e/contributions/ct16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7393294201466691}}
{"text": "(* Exercise coq_nat_10 *)\n\n(* Multiplication distributes over addition *)\n\nRequire Import Arith.\n\nPrint Nat.add_assoc.\nPrint Nat.add_comm.\n\nLemma mult_plus_distr : forall m n p, m * (n + p) = m * n + m * p.\n\nProof.\n intros.\n induction m.\n rewrite Nat.mul_0_l.\n reflexivity.\n simpl.\n rewrite IHm.\n rewrite Nat.add_assoc.\n rewrite Nat.add_assoc with (m := p).\n rewrite Nat.add_comm with (n := n+p).\n rewrite Nat.add_assoc.\n rewrite Nat.add_comm with (n := m*n).\n reflexivity.\nQed.\n", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_nat_10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.73930147710669}}
{"text": "Require Import ssreflect ssrfun ssrbool.\nRequire Import Generic.lemmas Generic.wlog.\nRequire Import Generic.pg3x_spec.\n\nRequire Import  PG33.pg33_inductive.\n\nModule PS : ProjectiveSpace.\n\n  Definition Point := Point.\n  Definition Line := Line.\n\n  Definition incid_lp := incid_lp. \n  Definition eqP := eqP.\n  Definition eqL := eqL.\n\n  (** a1_exists : existence of a line generated from 2 points *)\n\n  Check l_from_points.\n  \n  Ltac prove_a1_exists :=\n    let A:=fresh in\n    let B:=fresh in\n    intros A B;  pose (l:=(l_from_points A B));\n                   revert l;case A; case B; intros l; exists l; exact (erefl true).\n\n  Lemma a1_exists : forall A B : Point,\n      {l : Line | incid_lp A l && incid_lp B l}.\n  Proof.\n    idtac \"-> proving a1_exists\".\n    time (prove_a1_exists).\n    Time Qed.\n  Check a1_exists.\n\n  (** a3_1 : every line has at least three distinct points *)\n  \n  Ltac exists_p3 t u v :=\n    exact (existT _ t \n                  (existT _  u \n                          (exist _   v (erefl true)))).\n  \n  Ltac prove_a3_1 := let l := fresh \"l\" in\n                     let x := fresh \"x\" in\n                     intros l; pose (x:= points_from_line l); revert x;\n                     case l; intros x;\n                     exists_p3 (fst (fst (fst x))) (snd (fst (fst x))) (snd (fst x)).\n\n  Definition dist_3p  (A B C :Point) : bool := (negb (eqP A B)) && (negb (eqP A C)) && (negb (eqP B C)).\n\n  Lemma a3_1 : \n    forall l:Line,{A:Point &{B:Point &{ C:Point| \n            dist_3p A B C && (incid_lp A l && incid_lp B l && incid_lp C l)}}}.\n    Proof.\n    idtac \"-> proving a3_1\".\n    time (prove_a3_1).\n    Time Qed. \n\n    Check a3_1.\n\n  (** a1_unique : unicity of the line generated from 2 points *)\n  (** l_from_points is actually a1_exists *)\n  Check l_from_points.\n  Check a1_exists.\n\n  Lemma points_line : forall T Z:Point, forall x:Line,\n        incid_lp T x -> incid_lp Z x -> (T<>Z) -> x = (l_from_points T Z).\n  Proof.\n    idtac \"-> proving points_line\".\n    time (intros T Z x;\n          case x; case T; intros HTx;\n          first [ discriminate | \n                 case Z; intros HZx HTZ;\n                 solve  [ discriminate |  exact (@erefl Line _) | apply False_rect; auto ] ]).\n    Time Qed.\n\n  Check points_line.\n  \n  Ltac handle x :=\n    match goal with Ht  : is_true (incid_lp ?T x),\n                    Hz  : is_true (incid_lp ?Z x),\n                    Htz : (not (@eq Point ?T ?Z))  |- _ =>\n                    let HP := fresh in pose proof (points_line T Z x Ht Hz Htz) as HP;\n                                       clear Ht Hz; rewrite HP(*; subst*)  end.\n\n  Ltac prove_a1_unique :=\n    let A:=fresh in\n    let B:= fresh in\n    let HAB' := fresh in \n    let l1:=fresh in\n    let l2:=fresh in\n    let HAB:=fresh in\n    let HAl1:=fresh in\n    let HBl1:= fresh in\n    let HAl2 := fresh in\n    let HBl2 := fresh in\n    intros A B l1 l2 HAB HAl1 HBl1 HAl2 HBl2;\n    revert A B HAB l1 HAl1 HBl1 l2 HAl2 HBl2;\n    intros  X; case X;\n    intros Y;case Y; intros HAB;\n    solve [apply False_rect; auto\n          | discriminate\n          | intros l1 HAl1 HBl1; handle l1; intros l2 HAl2 HBl2; handle l2; exact (@erefl Line _)].\n  \n  Lemma a1_unique:forall (A B :Point)(l1 l2:Line),\n      ~A=B -> incid_lp A l1 -> incid_lp B l1  -> incid_lp A l2 -> incid_lp B l2 -> l1=l2.\n  Proof.\n    idtac \"-> proving a1_unique\".\n    time(prove_a1_unique).\n    Time Qed.\n  \n  Check a1_unique.\n\n  Lemma Point_dec : forall T U:Point, {T=U}+{~T=U}.\n  Proof.\n    intros T U; case T; case U;\n      solve [left; exact (@erefl Point _) | right; discriminate].\n  Qed. \n\n  Ltac prove_uniqueness :=\n    let P:= fresh in\n    let Q:= fresh in\n    let hypP := fresh in\n    let HPQdiff := fresh in \n    let hypQ := fresh in\n    let HPQ := fresh in \n    let l := fresh in\n    let m := fresh in\n    let Hl := fresh in\n    let Hl' := fresh in\n    let Hm := fresh in\n    let Hm' := fresh in\n    intros P Q l m Hl Hl' Hm Hm';\n    revert l Hl Hl' m Hm Hm';\n    destruct (Point_dec P Q) as [HPQdiff | HPQdiff];\n    [left; rewrite HPQdiff; exact (@erefl Point _) | idtac]; revert HPQdiff;\n    case P; case Q; intros HPQdiff;\n    solve [discriminate |  \n      intros  l Hl Hl';handle l; intros m Hm Hm'; handle m; right; exact (@erefl Line _)].\n\n  Lemma uniqueness : forall (A B :Point)(l1 l2:Line),\n      incid_lp A l1 -> incid_lp B l1  -> incid_lp A l2 -> incid_lp B l2 -> A = B \\/ l1 = l2.\n  Proof.\n    idtac \"-> proving uniqueness\".\n    time(prove_uniqueness).\n    Time Qed.\n  Check uniqueness.\n  \n  (** a3_2 : there exists 2 lines which do not intersect, i.e. dim >= 3  *)\n\n  Ltac solve_a3_2 := let p:= fresh in\n                     intros p; case p;\n                     let hypp:=fresh in let t := fresh in intros hypp t; discriminate.\n\n  (*Ltac prove_a3_2 := try_all_l ltac:(fun l1 => exists l1; try_all_l ltac:(fun l2 => exists l2; solve_a3_2)).*)\n  \n  Lemma a3_2 : exists l1:Line, exists l2:Line, forall p:Point, ~(incid_lp p l1 && incid_lp p l2). \n  Proof.\n    idtac \"-> proving a3_2\".\n    exists L0; exists L34;intros p; case p; \n      let hypp:=fresh in let t := fresh in intros t; discriminate.\n    (*Time (prove_a3_2).*) (* we could have chosen GKL and EHM for instance:  exists (o 35 0); exists (o 35 34)).*)\n    Time Qed.\n  Check a3_2.\n\n(* a3_3 : given 3 lines, there exists a line which intersects these 3 lines *)\n\n  Definition Intersect_In (l1 l2 :Line) (P:Point) := incid_lp P l1 && incid_lp P l2.\n \n  (** points_from_l is actually a3_1 *)\n  \n  Definition points_from_l (l:Line) := points_from_line l.\n\n  Ltac exists_lppp l t u v :=\n    exact (ex_intro _  l \n                 (ex_intro _  t\n                  (ex_intro _ u \n                          (ex_intro _  v  (erefl true))))).\n\n  Definition dist_3l (A B C :Line) : bool :=\n    (negb (eqL A B)) && (negb (eqL A C)) && (negb (eqL B C)).\n\n  Lemma a3_3_simple :\n    forall v1 v2 v3:Line,\n      leL v1 v2-> leL v2 v3 ->\n      dist_3l v1 v2 v3 ->\n      exists v4 :Line, exists T1:Point, exists T2:Point, exists T3:Point,\n              (Intersect_In v1 v4 T1) && (Intersect_In v2 v4 T2) && (Intersect_In v3 v4 T3).\n   Proof.\n     idtac \"-> proving a3_3_simple\".\n     unfold dist_3l; intros v1 v2 v3 Hv1v2 Hv2v3 Hd;\n       pose (t:=f_a3_3 v1 v2 v3) ;\npose(l:=fst t); pose (x:= fst (fst (snd t))); pose (y:= snd (fst (snd t))); pose (z:=snd (snd t));\n       revert Hv1v2 Hv2v3 Hd t l x y z.\n\n     case v1.\n\n(*case v2;\n                  intros hp1p2;try exact (degen_bool _ hp1p2) .\n\ncase v3;intros hp1p3 hdist l x y z.*)\n\n    par: abstract\n           (time (case v2;\n                  intros hp1p2;\n                  first [exact (degen_bool _ hp1p2) | \n                         (case v3;\n                          intros hp1p3 hdist t l x y z;\n                          solve [ (exact (degen_bool _ hp1p3))\n                                | (exact (degen_bool _ hdist))\n                                | exists_lppp l x y z ])])).\n\n      Time Qed.\n(*233s*)\n   Lemma eqL_sym : forall x y:Line, eqL x y = eqL y x.\n    Proof.\n      idtac \"proving eqL_sym\".\n      time (intros; apply PeanoNat.Nat.eqb_sym). \n    Time Qed.\n    Check eqL_sym.\n    \n    Lemma eqP_sym : forall x y:Point, eqP x y = eqP y x.\n    Proof. \n      idtac \"proving eqP_sym\".\n      time (intros;apply PeanoNat.Nat.eqb_sym).\n    Time Qed.\n    Check eqP_sym.\n    \n    Lemma exchL: forall x y B C, ~~eqL y x && B &&C-> ~~eqL x y && B && C.\n    Proof.\n      intros x y b c H.\n      apply ab_bool in H.      \n      destruct H as [Hx Hy].\n      apply ab_bool in Hx.\n      destruct Hx.\n      apply ab_bool; split.\n      apply ab_bool; split.\n      rewrite eqL_sym.\n      assumption.\n      assumption.\n      assumption.\n    Qed.\n    \n    Lemma exchP: forall x y B C D E F,\n        ~~eqP y x && B &&C &&D &&E &&F-> ~~eqP x y && B && C && D && E &&F.\n    Proof.\n      intros x y b c d e f H.\n      apply ab_bool in H.\n      destruct H as [Ha Hf]; apply ab_bool in Ha;\n        destruct Ha as [Ha He]; apply ab_bool in Ha;\n          destruct Ha as [Ha Hd]; apply ab_bool in Ha;\n            destruct Ha as [Ha Hc]; apply ab_bool in Ha;\n              destruct Ha as [Ha Hb].\n      apply ab_bool; split.\n      apply ab_bool; split.\n      apply ab_bool; split.\n      apply ab_bool; split.\n      apply ab_bool; split.\n      rewrite eqP_sym.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n    Qed.\n\n   Lemma a3_3 : forall v1 v2 v3:Line,\n      dist_3l v1 v2 v3 -> exists v4 :Line,  exists T1:Point, exists T2:Point, exists T3:Point,\n             (Intersect_In v1 v4 T1) && (Intersect_In v2 v4 T2) && (Intersect_In v3 v4 T3).\n  Proof.\n    idtac \"-> proving a3_3\".\n    intros v1 v2 v3.\n    wlog3 v1 v2 v3 leL leL_total idtac idtac.\n\n    intros; apply a3_3_simple.\n    destruct (ab_bool_lr _ _  H) as [Ha1 Ha2]; exact Ha1.\n    destruct (ab_bool_lr _ _  H) as [Ha1 Ha2]; exact Ha2.\n    assumption.\n\n    intros.\n    assert (Hd: dist_3l x z y).\n    unfold dist_3l in *;\n      apply circ3;apply circ3;apply exchL;apply circ3; apply comm12L; assumption.\n    destruct (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t1; exists t3; exists t2.\n    apply circ3; apply circ3; apply comm12L; assumption.\n    \n    intros.\n    assert (Hd: dist_3l y x z).\n    unfold dist_3l in *; apply exchL; apply circ3; apply circ3; apply comm12L; assumption.\n    destruct (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t2; exists t1; exists t3.\n    apply comm12L; assumption.\n    \n    intros.\n    assert (Hd: dist_3l y z x).\n    unfold dist_3l in *.\n    apply circ3; apply exchL; apply circ3; apply exchL; apply circ3; apply circ3; assumption.\n    destruct (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t3; exists t1; exists t2.\n    apply circ3; assumption.\n    \n    intros.\n    assert (Hd: dist_3l z x y).\n    unfold dist_3l in *.\n    apply exchL; apply circ3; apply exchL; apply circ3; assumption.\n    destruct (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t2; exists t3; exists t1.\n    apply circ3; apply circ3; assumption.\n    \n    intros.\n    assert (Hd: dist_3l z y x).\n    unfold dist_3l in *.\n    apply exchL; apply circ3; apply exchL; apply circ3; apply exchL;\n      apply circ3; apply circ3; apply comm12L; assumption.\n    destruct  (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t3; exists t2; exists t1.\n    apply comm12L; apply circ3;apply circ3; assumption. \n    Time Qed.\n  \n  (** a2 : Pasch's axiom *)\n\n  Definition dist_4p  (A B C D:Point) : bool :=\n    (negb (eqP A B)) && (negb (eqP A C)) && (negb (eqP A D))\n                     && (negb (eqP B C)) && (negb (eqP B D)) && (negb (eqP C D)).\n\n  Ltac findp' := match goal with\n                  |-  (@ex Point (fun J:Point => \n                                       is_true (andb (incid_lp J ?m) \n                                                     (incid_lp J ?p))))\n                  /\\ (@ex Point (fun K:Point => \n                                       is_true (andb (incid_lp K ?q) \n                                                     (incid_lp K ?r))))=> \n                  exact (conj (ex_intro _  ((*pg33_ind.*)f_a2 m p) (erefl true))\n                              (ex_intro _  ((*pg33_ind.*)f_a2 q r) (erefl true)))\n                 end.\n  \n  Lemma a2_conj_specific :\n    forall A B C D:Point, leP A B -> leP C D ->\n        let lAB := l_from_points A B in\n        let lCD := l_from_points C D in\n        let lAC := l_from_points A C in\n        let lBD := l_from_points B D in\n        let lAD := l_from_points A D in\n        let lBC := l_from_points B C in \n        \n        dist_4p A B C D -> \n        incid_lp A lAB && incid_lp B lAB ->  \n        incid_lp C lCD && incid_lp D lCD -> \n        incid_lp A lAC && incid_lp C lAC -> \n        incid_lp B lBD && incid_lp D lBD ->\n        incid_lp A lAD && incid_lp D lAD ->\n        incid_lp B lBC && incid_lp C lBC ->\n        \n        (exists I:Point, incid_lp I lAB && incid_lp I lCD) ->\n        (exists J:Point, (incid_lp J lAC && incid_lp J lBD)) /\\\n        (exists K:Point, (incid_lp K lAD && incid_lp K lBC)).\n  Proof.\n  idtac \"-> proving a2_conj_specific\".\n     intros A B C D HleAB HleCD lAB lCD lAC lBD lAD lBC Hdist HlAB HlCD HlAC HlBD HlAD HlBC Hex;\n       destruct (ab_bool_lr _ _ Hdist) as [Hdist1 HCD]; clear Hdist;\n         destruct (ab_bool_lr _ _ Hdist1) as [Hdist2 HBD]; clear Hdist1;\n           destruct (ab_bool_lr _ _ Hdist2) as [Hdist3 HBC]; clear Hdist2;\n             destruct (ab_bool_lr _ _ Hdist3) as [Hdist4 HAD]; clear Hdist3;\n               destruct (ab_bool_lr _ _ Hdist4) as [HAB HAC]; clear Hdist4;\n        revert A B HleAB HAB lAB HlAB C HBC HAC lBC HlBC lAC HlAC D HleCD HAD HBD HCD lAD HlAD lBD HlBD lCD HlCD Hex.\n\n     time (intros A B; case A; case B; intros HlePAB HAB lAB HlAB). \n     par: abstract (time (first [exact (degen_bool _ HlePAB) |exact (degen_bool _ HAB) | exact (degen_bool _ HlAB)| \n\n\n\n      (intros C; case C; intros HBC HAC lBC HlBC lAC HlAC; \n           first [  exact (degen_bool _ HBC) | exact (degen_bool _ HAC)\n                        |\n           \n                        (intros D; case D; intros HleCD HAD HBD HCD lAD HlAD lBD HlBD lCD HlCD Hex;\n\n                         first [ exact (degen_bool _ HleCD) | exact (degen_bool _ HAD)\n                                 | exact (degen_bool _ HBD) | exact (degen_bool _ HCD)\n                                 \n                                 | case Hex; intros t; case t; intros Ht;\n                                 first [exact (degen_bool _ Ht) | findp'] ])])])).\n  Qed.\n  Check a2_conj_specific.\n  \n  Lemma l_from_points_sym : forall x y:Point, l_from_points x y = l_from_points y x.\n  Proof.\n    intros x y; case x; case y; reflexivity.\n  Qed.\n\nLemma a2_conj :\n    forall A B C D:Point, dist_4p A B C D -> \n         let lAB := l_from_points A B in\n         let lCD := l_from_points C D in\n         let lAC := l_from_points A C in\n         let lBD := l_from_points B D in\n         let lAD := l_from_points A D in\n         let lBC := l_from_points B C in \n         \n         incid_lp A lAB && incid_lp B lAB ->  \n         incid_lp C lCD && incid_lp D lCD -> \n         incid_lp A lAC && incid_lp C lAC -> \n         incid_lp B lBD && incid_lp D lBD ->\n         incid_lp A lAD && incid_lp D lAD ->\n         incid_lp B lBC && incid_lp C lBC ->\n         \n         (exists I:Point, incid_lp I lAB && incid_lp I lCD) ->\n         (exists J:Point, (incid_lp J lAC && incid_lp J lBD)) /\\\n         (exists J:Point, (incid_lp J lAD && incid_lp J lBC)).\n  Proof.\n    intros A B.\n    wlog2 A B leP leP_total idtac idtac.\n    intros A B HleAB.\n    intros C D.\n    wlog2 C D leP leP_total idtac ltac:(intros; apply a2_conj_specific; assumption || exact I).\n    (* other cases *)\n\n    intros C D Hr.\n\n    intros lAB lCD lAC lBD lAD lBC Hdist HlAB HlCD HlAC HlBD HlAD HlBC Hex.\n    assert (Hd' : dist_4p A B D C).\n    unfold dist_4p in *.\n    apply circ6; apply comm12P; apply circ6; apply circ6 ; apply comm12P; apply circ6;\n    apply circ6; apply exchP; apply circ6; assumption.\n\n    assert (HlDC:(incid_lp D (l_from_points D C) && incid_lp C (l_from_points D C))).\n    apply circ2; rewrite l_from_points_sym; assumption. \n    assert (Hex': (exists I : Point, incid_lp I (l_from_points A B) && incid_lp I (l_from_points D C))).\n    rewrite (l_from_points_sym D C); assumption.\n    generalize (Hr Hd' HlAB HlDC HlAD HlBC HlAC HlBD Hex').\n    solve [intuition].\n\n    intros A B Hr C D.\n    intros Hd lAB lCD lAC lBD lAD lBC HlAB HlCD HlAC HlBD HlAD HlBC Hex.\n    assert (Hd':  dist_4p B A C D).\n    unfold dist_4p in *.\n    apply exchP; apply circ6; apply circ6; apply comm12P; apply circ6; apply comm12P;\n      apply circ6; apply circ6; apply circ6; apply circ6; apply comm12P; apply circ6;\n        apply comm12P; apply circ6; apply circ6; apply circ6; apply circ6; assumption.\n\n    assert (HlBA:incid_lp B (l_from_points B A) && incid_lp A (l_from_points B A)).\n    apply circ2; rewrite l_from_points_sym; assumption.\n    assert (HlDB:(incid_lp D (l_from_points D B) && incid_lp B (l_from_points D B))).\n    apply circ2; rewrite l_from_points_sym; assumption.\n    assert (Hex':(exists I : Point, incid_lp I (l_from_points B A) && incid_lp I (l_from_points C D))).\n    rewrite (l_from_points_sym B A); assumption.\n\n    generalize (Hr C D Hd' HlBA HlCD HlBC HlAD HlBD HlAC Hex').\n    intros (He1,He2).\n    split.\n    destruct He2 as [e2 He2]; apply circ2 in He2; exists e2; assumption.\n    destruct He1 as [e1 He1]; apply circ2 in He1; exists e1; assumption.\n  Qed.\n\n  Check a2_conj.\n\n  \n  Lemma points_line' : forall T Z:Point, forall x:Line,\n        incid_lp T x -> incid_lp Z x -> ~~ eqP T Z -> x = (l_from_points T Z).\n  Proof.\n    idtac \"-> proving points_line\".\n    time (intros T Z x;\n           case x ; \n           case T; intros  HTx;\n           first [ discriminate | \n                   case Z; intros  HZx HTZ;\n                   solve [discriminate | apply False_rect; auto | exact (@erefl Line _)]]).\n    Time Qed.\n\n  Ltac handle' x :=\n    match goal with Ht  : is_true (incid_lp ?T x),\n                          Hz  : is_true (incid_lp ?Z x),\n                                Htz : is_true (negb (eqP ?T ?Z)) |- _ =>\n                    let HP := fresh in pose proof (points_line' T Z x Ht Hz Htz) as HP;\n                                       clear Ht Hz; rewrite HP(*; subst*)  end.\n\n  \n  Ltac handle_eff l P Q HlAB:= assert (l=l_from_points P Q);[\n                                 assert (incid_lp P l) by ( solve [intuition]);\n                                 assert (incid_lp Q l) by ( solve [intuition]);\n                                 handle' l; reflexivity | idtac].\n\n  Lemma incid_lp_l_from_point1 : forall x y, incid_lp x (l_from_points x y).\n  Proof.\n    intros x y; case x; case y; trivial.\n  Qed.\n\n  Lemma incid_lp_l_from_point2 : forall x y, incid_lp y (l_from_points x y).\n  Proof.\n    intros x y; case x; case y; trivial.\n  Qed.\n\n  Lemma a2 : forall A B C D:Point, forall lAB lCD lAC lBD :Line,\n        dist_4p A B C D -> \n        incid_lp A lAB && incid_lp B lAB ->\n        incid_lp C lCD && incid_lp D lCD ->\n        incid_lp A lAC && incid_lp C lAC ->\n        incid_lp B lBD && incid_lp D lBD ->\n        (exists I:Point, incid_lp I lAB && incid_lp I lCD) ->\n        exists J:Point, incid_lp J lAC && incid_lp J lBD.\n  Proof.\n    intros A B C D lAB lCD lAC lBD Hdist HlAB HlCD HlAC HlBD Hex.\n    destruct (ab_bool_lr _ _ HlAB) as [HlAB1 HlAB2]; \n      destruct (ab_bool_lr _ _ HlCD) as [HlCD1 HlCD2]; \n      destruct (ab_bool_lr _ _ HlAC) as [HlAC1 HlAC2]; \n      destruct (ab_bool_lr _ _ HlBD) as [HlBD1 HlBD2]; \n      destruct (ab_bool_lr _ _ Hdist) as [Hdist1 HCD]; \n      destruct (ab_bool_lr _ _ Hdist1) as [Hdist2 HBD]; \n      destruct (ab_bool_lr _ _ Hdist2) as [Hdist3 HBC]; \n      destruct (ab_bool_lr _ _ Hdist3) as [Hdist4 HAD]; \n      destruct (ab_bool_lr _ _ Hdist4) as [HAB HAC].\n    \n    handle_eff lAB A B HlAB.\n    handle_eff lCD C D HlCD.\n    handle_eff lAC A C HlAC.\n    handle_eff lBD B D HlBD.\n    rewrite H in HlAB.\n    rewrite H0 in HlCD.\n    rewrite H1 in HlAC.\n    rewrite H2 in HlBD.\n    rewrite H in Hex.\n    rewrite H0 in Hex.\n    assert (HlAD:(incid_lp A (l_from_points A D) && incid_lp D (l_from_points A D))).\n    apply Bool.andb_true_iff; split;\n      [apply incid_lp_l_from_point1 | apply incid_lp_l_from_point2].\n    \n    assert (HlBC: (incid_lp B (l_from_points B C) && incid_lp C (l_from_points B C))).\n    apply Bool.andb_true_iff; split;\n      [apply incid_lp_l_from_point1 | apply incid_lp_l_from_point2].\n    \n    rewrite H1.\n    rewrite H2.\n    elim (a2_conj A B C D Hdist HlAB HlCD HlAC HlBD HlAD HlBC Hex).\n    intros; assumption.\n  Qed.\n  Check a2.\n  \nEnd PS.\n\n(* Local Variables: *)\n(* coq-prog-name: \"/Users/magaud/.opam/4.11.1/bin/coqtop\" *)\n(* coq-load-path: ((\".\" \"Top\") ) *)\n(* suffixes: .v *)\n(* End: *)\n", "meta": {"author": "magaud", "repo": "PG3q", "sha": "d34bc2a8b4f42610952a65840b724a69f5a926a1", "save_path": "github-repos/coq/magaud-PG3q", "path": "github-repos/coq/magaud-PG3q/PG3q-d34bc2a8b4f42610952a65840b724a69f5a926a1/pg33/pg33_proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7393014733567327}}
{"text": "Require Import Vector.\nRequire Import JMeq.\n\nSection Null_vectors.\n Variable A:Set.\n\n Fact F1 : forall (n:nat)(v:t A n), n=0 -> JMeq v (nil A).\n Proof.\n  intros n  v; case v.\n  reflexivity.\n  discriminate 1.\n Qed.\n\n\n Lemma V0_JMeq_Vnil:  forall (v:t A 0), JMeq v (nil A).\n Proof.\n  intro v; apply F1.\n  trivial.\n Qed.\n\n Lemma  V0_eq_Vnil : forall (v:t A  0), eq v (nil A).\n Proof.\n  intros  v.\n  apply JMeq_eq.\n  apply V0_JMeq_Vnil.\n Qed.\n\nEnd Null_vectors.\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/ch8_inductive_predicates/SRC/JMeqSolution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7393014717211932}}
{"text": "Require Import Coq.omega.Omega.\n\nHint Rewrite <- nat_compare_lt : hints.\nHint Rewrite <- nat_compare_gt : hints.\nHint Rewrite nat_compare_eq_iff : hints.\nHint Rewrite <- nat_compare_eq_iff : hints.\n\nLtac autorewrite_nat_compare :=\n  autorewrite with hints.\n\nLemma nat_compare_eq_refl : forall x, nat_compare x x = Eq.\n  intros; apply nat_compare_eq_iff; trivial.\nQed.\n\nLemma nat_compare_consistent :\n  forall n0 n1,\n    { nat_compare n0 n1 = Lt /\\ nat_compare n1 n0 = Gt }\n    + { nat_compare n0 n1 = Eq /\\ nat_compare n1 n0 = Eq }\n    + { nat_compare n0 n1 = Gt /\\ nat_compare n1 n0 = Lt }.\nProof.\n  intros n0 n1;\n  destruct (lt_eq_lt_dec n0 n1) as [ [_lt | _eq] | _lt ];\n  [ constructor 1; constructor 1  | constructor 1; constructor 2 | constructor 2 ];\n  split;\n  autorewrite_nat_compare;\n  intuition.\nQed.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/QueryStructure/Implementation/DataStructures/Bags/NatCompare_Facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7393014552847273}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint less (less_arg0 : natural) (less_arg1 : natural) : bool\n           := match less_arg0, less_arg1 with\n              | x, Zero => false\n              | Zero, Succ x => true\n              | Succ x, Succ y => less x y\n              end.\nFixpoint eqb (n m: natural) : bool :=\nmatch n, m with\n   | Zero, Zero => true\n   | Zero, Succ _ => false\n   | Succ _, Zero => false\n   | Succ n', Succ m' => eqb n' m'\nend.\nFixpoint count (count_arg0 : natural) (count_arg1 : lst) : natural\n           := match count_arg0, count_arg1 with\n              | x, Nil => Zero\n              | x, Cons y z => if eqb x y then Succ (count x z) else count x z\n              end.\n\nFixpoint insort (insort_arg0 : natural) (insort_arg1 : lst) : lst\n           := match insort_arg0, insort_arg1 with\n              | i, Nil => Cons i Nil\n              | i, Cons x y => if less i x then Cons i (Cons x y) else Cons x (insort i y)\n              end.\n\nFixpoint sort (sort_arg0 : lst) : lst\n           := match sort_arg0 with\n              | Nil => Nil\n              | Cons x y => insort x (sort y)\n              end.\n\nLemma Nat_beq_eq : forall (x y : natural), eqb x y = true -> x = y.\nProof.\n   intros.\n   generalize dependent y.\n   induction x.\n   - intros. destruct y.\n   + simpl in H. apply IHx in H. rewrite H. reflexivity.\n   + discriminate.\n   \n   - intros. destruct y.\n\n   + discriminate.\n   + reflexivity.\n   \nQed.           \n\nTheorem theorem0 : forall (x : natural) (y : natural) (z : lst), not (eq x y) -> eq (count x (insort y z)) (count x z).\nProof.\n   intros.\n  induction z.  \n  - simpl. destruct (eqb x n) eqn:?.\n    + destruct (less y n) eqn:?.\n      * simpl. destruct (eqb x y) eqn:?.\n        -- \n         apply Nat_beq_eq in Heqb1. contradiction.\n        -- rewrite Heqb. reflexivity.\n      * simpl. rewrite Heqb. rewrite IHz. reflexivity.\n    + destruct (less y n) eqn:?.\n      * simpl. destruct (eqb x y) eqn:?.\n        -- apply Nat_beq_eq in Heqb1. contradiction.\n        -- rewrite Heqb. reflexivity.\n      * simpl. rewrite Heqb. assumption.\n   - simpl. destruct (eqb x y) eqn:?.\n   + apply Nat_beq_eq in Heqb. contradiction.\n      + reflexivity.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal71.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7392567929031092}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Lia.\n\nSet Implicit Arguments.\n\nSection wf_chains.\n\n  Variables (X : Type) (R : X -> X -> Prop).\n  \n  Inductive chain : nat -> X -> X -> Prop :=\n    | in_chain_0 : forall x, chain 0 x x\n    | in_chain_1 : forall n x y z, R x y -> chain n y z -> chain (S n) x z.\n    \n  Fact chain_plus a b x y z : chain a x y -> chain b y z -> chain (a+b) x z.\n  Proof.\n    induction 1 as [ | ? ? y ]; simpl; auto.\n    constructor 2 with y; auto.\n  Qed.\n\n  Fact chain_rev n x y z : chain n x y -> R y z -> chain (S n) x z.\n  Proof.\n    intros H1 H2.\n    replace (S n) with (n+1) by lia.\n    apply chain_plus with y; auto.\n    constructor 2 with z; auto.\n    constructor 1.\n  Qed.\n\n  (* If chains to x have bounded length then x is R-accessible *)\n  \n  Lemma Acc_chains k x : (forall n y, chain n y x -> n <= k) -> Acc R x.\n  Proof.\n    revert x; induction k as [ | k IHk ]; intros x Hx.\n    + constructor 1; intros y Hy.\n      generalize (Hx _ _ (in_chain_1 Hy (in_chain_0 x))); lia.\n    + constructor 1; intros y Hy.\n      apply IHk; intros n z Hn.\n      apply le_S_n, (Hx _ z), chain_rev with y; auto.\n  Qed.\n\n  (* If every x has bounded chains to itself then R is WF *)\n  \n  Hypothesis (HR : forall x, exists k, forall n y, chain n y x -> n <= k). \n\n  Theorem wf_chains : well_founded R.\n  Proof.\n    intros x.\n    destruct (HR x) as (k & Hk).\n    revert Hk; apply Acc_chains.\n  Qed.\n  \nEnd wf_chains.\n", "meta": {"author": "DmxLarchey", "repo": "The-Braga-Method", "sha": "e4f51add22a73681103454ad94a05aeeda332c50", "save_path": "github-repos/coq/DmxLarchey-The-Braga-Method", "path": "github-repos/coq/DmxLarchey-The-Braga-Method/The-Braga-Method-e4f51add22a73681103454ad94a05aeeda332c50/theories/utils/chains_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.73925678336882}}
{"text": "(* An alternate nat induction principle. *)\n\nSection nat_ind_alt_sect.\n\n  Variables\n    (P: nat -> Prop).\n\n  Hypotheses\n    (P_0: P 0)\n    (P_1: P 1)\n    (P_2: forall n, P n -> P (S (S n))).\n\n  (* You'll need to strengthen the goal before induction,\n     to get a stronger induction hypothesis.\n     Use `assert something` first to achieve this.\n     The `something` must be weak enough to be true in the base case,\n     and strong enough to leapfrog alternate nats in the inductive case.\n     Start by thinking about what you already know in the base case. *)\n  Lemma nat_ind_alt (n: nat): P n.\n  Proof.\n\n  Qed.\n\nEnd nat_ind_alt_sect.\n", "meta": {"author": "mbrcknl", "repo": "coq-fight-2016", "sha": "8925a35a86ba1d1cdd4dc69c91ad683db212bfd8", "save_path": "github-repos/coq/mbrcknl-coq-fight-2016", "path": "github-repos/coq/mbrcknl-coq-fight-2016/coq-fight-2016-8925a35a86ba1d1cdd4dc69c91ad683db212bfd8/submissions/L04-list-induct-alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7392567776032763}}
{"text": "Require Import String ZArith List.\nOpen Scope Z_scope.\n\nInductive aexpr : Type :=\n | anum ( x : Z ) : aexpr\n | avar ( s : string ) : aexpr\n | aplus ( e1 e2 : aexpr ) : aexpr.\n\nInductive bexpr : Type :=\n | blt ( e1 e2 : aexpr ) : bexpr.\n\nInductive instr : Type :=\n | assign ( x : string ) ( e : aexpr )\n | seq ( i1 i2 : instr ) : instr\n | while ( b : bexpr ) ( i : instr ) : instr.\n\nFixpoint af ( g : string -> Z ) ( e : aexpr ) : Z :=\n match e with\n | anum n => n\n | avar x => g x\n | aplus e1 e2 => af g e1 + af g e2\n end.\n\nSearchAbout ( Z -> Z -> bool ).\nFixpoint bf ( g : string -> Z ) ( b : bexpr )  :=\n match b with\n | blt b1 b2 => Z.ltb ( af g b1 ) ( af g b2 )\n end.\n\n\nInductive assert : Type :=\n | pred ( p : string ) ( l : list aexpr )\n | a_b ( b : bexpr )\n | a_conj ( a1 a2 : assert )\n | a_not ( a : assert )\n | a_true\n | a_false.\n\nFixpoint ia  ( m : string -> list Z -> Prop ) ( g : string -> Z )\n  ( a : assert ) : Prop :=\n match a with\n | pred s l => m s ( map ( af g ) l )\n | a_b b => bf g b = true\n | a_conj a1 a2 => ( ia m g a1 ) /\\ ( ia m g a2 )\n | a_not a => not ( ia m g a )\n | a_true => True\n | a_false => False\n end.\n\nInductive a_instr : Type :=\n | pre ( a : assert ) ( i : a_instr )\n | a_assign ( x : string ) ( e : aexpr )\n | a_seq ( i1 i2 : a_instr )\n | a_while ( b : bexpr ) ( a : assert ) ( i : a_instr ).\n\nFixpoint asubst ( x : string ) ( s : aexpr ) ( e : aexpr ) : aexpr :=\n match e with\n | anum n => anum n\n | avar x1 => if string_dec x x1 then s else e\n | aplus e1 e2 => aplus ( asubst x s e1 ) ( asubst x s e2 )\n end.\n\nDefinition bsubst ( x : string ) ( s : aexpr ) ( b : bexpr ) : bexpr :=\n match b with\n | blt e1 e2 => blt ( asubst x s e1 ) ( asubst x s e2 )\n end.\n\nFixpoint subst ( x : string )  ( s : aexpr ) ( a : assert ) : assert :=\n match a with\n | pred p l => pred p ( map ( asubst x s ) l )\n | a_b b => a_b ( bsubst x s b )\n | a_conj a1 a2 => a_conj ( subst x s a1 ) ( subst x s a2 )\n | a_not a => a_not ( subst x s a)\n | any => any\n end.\n", "meta": {"author": "tabtab777", "repo": "Coq", "sha": "4ffc37f0c970349ef1942a1519b729c6e5cba581", "save_path": "github-repos/coq/tabtab777-Coq", "path": "github-repos/coq/tabtab777-Coq/Coq-4ffc37f0c970349ef1942a1519b729c6e5cba581/AbstractInter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.8221891392358014, "lm_q1q2_score": 0.7392478379135452}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export Lia.\nRequire Export Zwf.\n\n\n(* taken from chapter 5 *)\n\nInductive plane : Set :=\n    point : Z->Z->plane.\n\nInductive htree (A:Type) : nat->Type :=\n  | hleaf : A -> htree A 0%nat\n  | hnode : forall n:nat, A -> htree A n -> htree A n -> htree A (S n).\n\n\nInductive south_west : plane->plane->Prop :=\n  south_west_def :\n  forall a1 a2 b1 b2:Z, (a1 <= b1)%Z -> (a2 <= b2)%Z -> \n        south_west (point a1 a2)(point b1 b2).\n\nInductive even : nat->Prop :=\n  | O_even : even 0\n  | plus_2_even : forall n:nat, even n -> even (S (S n)).\n\nInductive sorted {A:Type}(R:A->A->Prop) : list A -> Prop :=\n  | sorted0 : sorted  R nil\n  | sorted1 : forall x:A, sorted  R (x :: nil)\n  | sorted2 :\n      forall (x y:A)(l:list A),\n        R x y ->\n        sorted  R (y :: l)-> sorted  R (x  ::  y :: l).\n\n\n#[export] Hint Constructors sorted :  sorted_base.\n\nRequire Export Relations.\n\n\nInductive clos_trans {A:Type}(R:relation A) : A->A->Prop :=\n  | t_step : forall x y:A, R x y -> clos_trans  R x y\n  | t_trans :\n    forall x y z:A, clos_trans  R x y -> clos_trans  R y z -> \n        clos_trans  R x z.\n\n\nTheorem sorted_nat_123 : sorted le (1::2::3::nil).\nProof.\n auto with sorted_base arith.\nQed.\n\nTheorem xy_ord :\n forall x y:nat, le x y -> sorted  le (x::y::nil).\nProof.\n auto with sorted_base.\nQed.\n\nTheorem zero_cons_ord :\n forall l:list nat, sorted le l -> sorted le (cons 0 l).\nProof.\n induction 1; auto with sorted_base arith.\nQed.\n\nTheorem sorted1_inv {A:Type}{le : relation A} { x l} (H: sorted le (x::l))  :\n  sorted le l.\nProof.\n inversion H;  auto with sorted_base.\nQed.\n\nTheorem sorted2_inv {A:Type}{le : relation A} {x y  l}\n        (H: sorted le (x::y::l)): le x y.\nProof.\n inversion H; auto with sorted_base.\nQed.\n\nTheorem not_sorted_132 :  ~ sorted le (1::3::2::nil).\nProof.\n intros H; generalize  (sorted1_inv   H); intro H0. \n generalize (sorted2_inv H0).\n lia.\nQed.\n\n(** Tests :\nCheck True_ind.\n\nCheck False_ind.\n\nCheck and_ind.\n\nCheck or_ind.\n\nCheck ex_ind.\n\nCheck eq_ind.\n*)\n\nRequire Import JMeq.\n\n(** Tests : \nCheck JMeq_eq.\n\nCheck JMeq_ind.\n\n*)\n\nInductive ahtree(A:Type) : Type :=\n  any_height : forall n:nat, htree A n -> ahtree A.\n\nArguments any_height {A} n _.\n\nTheorem any_height_inj2 {A:Type} :\n forall (n1 n2:nat)(t1:htree A n1)(t2:htree A n2),\n   any_height n1 t1 = any_height   n2 t2 -> JMeq t1 t2.\nProof.\n intros  n1 n2 t1 t2 H.\n injection H; intros H1 H2.\n dependent rewrite <- H1.\n trivial.\nQed.\n\n\nTheorem any_height_inj2' {A:Type} :\n forall (n1 n2:nat)(t1:htree A n1)(t2:htree A n2),\n   any_height n1 t1 = any_height   n2 t2 -> JMeq t1 t2.\nProof. \n intros  n1 n2 t1 t2 H.\n change (match any_height n2 t2 with\n        | any_height  n t => JMeq t1 t\n        end);\n   now rewrite <- H.\nQed.\n\nRequire Import List  Vector.\n\nSection vectors_and_lists.\n Variable A : Type. \n (** Note :\n    The type of A-vectors of length n is just (t A n)\n    or (Vector.t A n)\n\n    Since the Vector library overloads nil and cons, we use qualified names\n    for the operations on lists *)\n\n Fixpoint vector_to_list (n:nat)(v:t A n){struct v} \n  : list A :=\n  match v with\n  | nil _ => List.nil \n  | cons _ a p tl => List.cons a (vector_to_list p tl)\n  end.\n\n Fixpoint list_to_vector (l:list A) : t A (length l) :=\n   match l as x return t A (length x) with\n   | List.nil => nil A\n   | List.cons a tl => cons A a (length tl)(list_to_vector tl)\n   end.\n\n Theorem keep_length :\n  forall (n:nat)(v:t A n), length (vector_to_list n v) = n.\n Proof.\n   intros n v; induction  v; simpl; auto.\n Qed.\n\n Lemma Vconseq :\n  forall (a:A)(n m:nat),\n   n = m ->\n   forall (v:t A n)(w:t A m),\n     JMeq v w -> JMeq (cons A a n v)(cons A a m w).\n Proof.\n  intros a n m Heq; rewrite Heq.\n  intros v w HJeq.\n  rewrite HJeq; reflexivity.\nQed.\n\n Theorem vect_to_list_and_back :\n  forall n (v:t A n),\n    JMeq v (list_to_vector (vector_to_list n v)).\n Proof.\n  intros n v; induction  v as [ | h n v IHv].\n -   reflexivity.\n -    simpl;  apply Vconseq.\n   +    now rewrite  keep_length.\n   +   assumption.\n Qed.\n\nEnd vectors_and_lists.\n\nTheorem structured_intro_example1 : forall A B C:Prop, A/\\B/\\C->A.\nProof.\n intros A B C [Ha [Hb Hc]];\n assumption.\nQed.\n\nTheorem structured_intro_example2 : forall A B:Prop, A \\/ B/\\(B->A)->A.\nProof.\n intros A B [Ha | [Hb Hi]].\n - assumption.  \n - now apply Hi. \nQed.\n\nTheorem sum_even : forall n p:nat, even n -> even p -> even (n+p).\nProof.\n(** False start\n intros n; elim n.\n auto.\n intros n' Hrec p Heven_Sn' Heven_p.\nRestart.\n*)\n\n intros n p Heven_n; induction Heven_n.  \n -  trivial.\n -  intro H0; simpl;  constructor; auto. \nQed.\n\n(** \nCheck le_ind.\n\n*)\n\nTheorem lt_le : forall n p:nat, n < p -> n <= p.\nProof.\n intros n p H; induction H; repeat constructor; assumption.\nQed.\n\n\nOpen Scope Z_scope.\n\nInductive Pfact : Z->Z->Prop :=\n  Pfact0 : Pfact 0 1\n| Pfact1 : forall n v:Z, n <> 0 -> Pfact (n-1) v -> Pfact n (n*v).\n\nTheorem pfact3 : Pfact 3 6.\nProof.\n apply Pfact1 with (n := 3)(v := 2).\n discriminate.\n apply (Pfact1 2 1).\n discriminate.\n apply (Pfact1 1 1).\n discriminate.\n apply Pfact0.\nQed.\n \nTheorem fact_def_pos : forall x y:Z, Pfact x y ->  0 <= x.\nProof.\n intros x y H; induction  H.\n -  auto with zarith.\n -  lia.\nQed.\n\n\n(**\nCheck Zwf_well_founded. \n\nCheck well_founded_ind. \n*)\n\nTheorem Zle_Pfact : forall x:Z, 0 <= x -> exists y:Z, Pfact x y.\nProof.\n intros x; induction  x using (well_founded_ind (Zwf_well_founded 0)).\n intros  Hle; destruct  (Zle_lt_or_eq  _ _ Hle).\n - destruct (H (x-1)).\n   +  unfold Zwf; lia.\n   +  lia.\n   + exists (x*x0); apply Pfact1; auto with zarith.\n -  subst x; exists 1; constructor.\n\nQed.\n\nSection little_semantics.\n Variables Var aExp bExp : Set.\n Inductive inst : Set :=\n | Skip : inst\n | Assign : Var->aExp->inst\n | Sequence : inst->inst->inst\n | WhileDo : bExp->inst->inst.\n\n Variables\n  (state : Set)\n  (update : state->Var->Z -> option state)\n  (evalA : state->aExp -> option Z)\n  (evalB : state->bExp -> option bool).\n\n Inductive exec : state->inst->state->Prop :=\n | execSkip : forall s:state, exec s Skip s\n | execAssign :\n    forall (s s1:state)(v:Var)(n:Z)(a:aExp),\n     evalA s a = Some n -> update s v n = Some s1 ->\n     exec s (Assign v a) s1\n | execSequence :\n    forall (s s1 s2:state)(i1 i2:inst),\n     exec s i1 s1 -> exec s1 i2 s2 ->\n     exec s (Sequence i1 i2) s2\n | execWhileFalse :\n    forall (s:state)(i:inst)(e:bExp),\n     evalB s e = Some false -> exec s (WhileDo e i) s\n | execWhileTrue :\n    forall (s s1 s2:state)(i:inst)(e:bExp),\n     evalB s e = Some true ->\n     exec s i s1 ->\n     exec s1 (WhileDo e i) s2 ->\n     exec s (WhileDo e i) s2.\n\n Theorem HoareWhileRule :\n  forall (P:state->Prop)(b:bExp)(i:inst)(s s':state),\n    (forall s1 s2:state,\n      P s1 -> evalB s1 b = Some true -> exec s1 i s2 -> P s2)->\n    P s -> exec s (WhileDo b i) s' ->\n    P s' /\\ evalB s' b = Some false.\n Proof.\n(*  intros P b i s s' H Hp Hexec; elim Hexec.\n Restart.\n  intros P b i s s' H Hp Hexec; generalize H Hp; elim Hexec.\n Restart. *)\n   \n  intros P b i s s' H.\n  cut\n   (forall i':inst,\n     exec s i' s' ->\n     i' = WhileDo b i -> P s -> P s' /\\ evalB s' b = Some false); \n   eauto.\n  intros i' Hexec; elim Hexec; try (intros; discriminate).\n  intros s0 i0 e Heval Heq; injection Heq; intros H1 H2.\n  match goal  with\n  | id:(e = b) |- _ => rewrite <- id; auto\n  end.\n  intros;\n   match goal with\n   | id:(_ = _) |- _ => injection id; intros H' H''\n   end.\n    subst i0 b;eauto.\n Qed.\n\nEnd little_semantics.\n\nOpen Scope nat_scope.\n\nInductive is_0_1 : nat->Prop :=\n  is_0 : is_0_1 0 | is_1 : is_0_1 1.\n\n#[export] Hint Resolve is_0 is_1 : core.\n\nLemma sqr_01 : forall x:nat, is_0_1 x -> is_0_1 (x * x).\nProof.\n  induction 1; simpl; auto.\nQed.\n\nTheorem elim_example : forall n:nat, n <= 1 -> n*n <= 1.\nProof.\n intros n H.\n destruct (sqr_01 n); auto.\n inversion_clear H; auto.\n inversion_clear H0; auto.\nQed.\n\n\n(** bad attempt \nSection bad_proof_for_inversion.\n\n Theorem not_1_even : ~even 1.\n Proof.\n  red; intros H; elim H.\n Abort.\n\nEnd bad_proof_for_inversion.\n\n*)\n\nTheorem not_even_1 : ~even 1.\nProof.\n unfold not; intros H.\n inversion H.\nQed.\n\nTheorem plus_2_even_inv : forall n:nat, even (S (S n))-> even n.\nProof.\n intros n H; inversion H; assumption.\nQed.\n\n\n(** Same theorems, but using basic tactics only \n*)\n\nTheorem not_even_1' : ~even 1.\nProof.\n intro H.\n generalize (refl_equal 1).\n pattern 1 at -2.\n induction H.\n - discriminate.\n - discriminate.\nQed.\n\nTheorem plus_2_even_inv' : forall n:nat, even (S (S n))-> even n.\nProof.\n intros n H.\n generalize (refl_equal (S (S n))); pattern (S (S n)) at -2.\n induction  H.\n -  discriminate.\n -  intros H0 ; injection H0; intro; now subst n0.\nQed.\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch8_inductive_predicates/SRC/chap8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8438951045175642, "lm_q1q2_score": 0.7390723493800174}}
{"text": "(* From the chapter entitled Inductive Predicates in CPDT *)\nRequire Import Bool Arith List CpdtTactics.\n\nPrint ex.\n\nLemma exist1 : exists x : nat, x + 1 = 2.\nProof.\n  exists 1.\n  reflexivity.\nQed.\n\nLemma exist2 : forall (n m:nat), (exists x, n + x = m) -> n <= m.\nProof.\n  destruct 1.\n  crush.\nQed.\n\nInductive isZero : nat -> Prop :=\n| IsZero : isZero 0.\n\nTheorem isZero_zero : isZero 0.\n  constructor.\nQed.\n\nLemma isZero_plus : forall n m : nat, isZero m -> n + m = n.\nProof.\n  destruct 1.\n  crush.\nQed.\n\nLemma isZero_contra : isZero 1 -> False.\nProof.\n  inversion 1.\nQed.\n\nInductive even : nat -> Prop := \n| Even0 : even 0\n| EvenSS : forall n, even n -> even (S (S n)).\n\nTheorem even_0 : even 0.\n  constructor.\nQed.\n\nDefinition even_4 : even 4.\n  repeat constructor.\nQed.\nPrint even_4.\n\n(*Hint Constructors even.\n\nTheorem even_4' : even 4.\n  auto.\nQed.\n\n*)\nTheorem even_1_contra : even 1 -> False.\n  intro H.\n  inversion H.\nQed.\nPrint even_1_contra.\n\nTheorem even_3_contr : even 3 -> False.\n  intro H.\n  inversion H.\n  inversion H1.\nQed.\n\nHint Constructors even.\nTheorem even_plus : forall n m, even n -> even m -> even (n + m).\nProof.\n  induction 1 ; crush.\nQed.\n\n(*\nTheorem even_contra : forall n, even (S (n + n)) -> False.\n  induction 1.\n*)\n\nTheorem even_contra : forall n, even (S (n + n)) -> False.\nProof.\n  assert (forall n', even n' -> forall n, n' = S (n + n) -> False).\n  Focus 2.\n  intros.\n  apply (H _ H0 _ eq_refl).\n  induction 1 ; crush.\n  destruct n ; destruct n0 ; crush.\n  rewrite <- plus_n_Sm in H0.\n  apply (IHeven _ H0).\nQed.\n\nPrint even_contra.\n", "meta": {"author": "Keno", "repo": "CS250", "sha": "5865c43b99d3acee956d610475445894851397f6", "save_path": "github-repos/coq/Keno-CS250", "path": "github-repos/coq/Keno-CS250/CS250-5865c43b99d3acee956d610475445894851397f6/notes/lecture5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8438951025545427, "lm_q1q2_score": 0.7390723449249038}}
{"text": "\nRequire Import Arith.\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint less (less_arg0 : natural) (less_arg1 : natural) : bool\n           := match less_arg0, less_arg1 with\n              | x, Zero => false\n              | Zero, Succ x => true\n              | Succ x, Succ y => less x y\n              end.\nFixpoint eqb (n m: natural) : bool :=\nmatch n, m with\n   | Zero, Zero => true\n   | Zero, Succ _ => false\n   | Succ _, Zero => false\n   | Succ n', Succ m' => eqb n' m'\nend.\nDefinition leq (x : natural) (y : natural) : bool :=\neqb x y || less x y.\n(* \nFixpoint leq (n m : natural) : bool :=\nmatch n, m with\n| Zero  , x   => true\n| x , Zero   => false\n| Succ x, Succ y => leq x y\nend. *)\n\nFixpoint insort (insort_arg0 : natural) (insort_arg1 : lst) : lst\n           := match insort_arg0, insort_arg1 with\n              | i, Nil => Cons i Nil\n              | i, Cons x y => if less i x then Cons i (Cons x y) else Cons x (insort i y)\n              end.\n\nFixpoint sorted (sorted_arg0 : lst) : bool\n:= match sorted_arg0 with\n   | Nil => true\n   | Cons x l => match l with\n      | Nil => true\n      | Cons z y => andb (sorted l) (leq x z)\n      end\n   end.\n\nFixpoint sort (sort_arg0 : lst) : lst\n           := match sort_arg0 with\n              | Nil => Nil\n              | Cons x y => insort x (sort y)\n              end.\nLemma not_less : forall (x y : natural), less x y = false -> leq y x = true.\nProof.\n   intros.\n   generalize dependent y.\n   induction x.\n   - intros. unfold leq. destruct y.\n   + simpl in H. apply IHx in H. unfold leq in H. simpl. assumption.\n   + reflexivity.\n   - intros. unfold leq. destruct y.\n   + discriminate.\n   + reflexivity.\nQed.\n              \nTheorem theorem0 : forall (x : lst) (y : natural), eq (sorted x) true -> eq (sorted (insort y x)) true.\nProof.\n   (* intros.\n  induction x.\n  - destruct x.\n    + simpl. destruct (less y n) eqn:?.\n      * simpl. unfold leq. rewrite Heqb. admit.\n      * simpl. apply not_less. assumption.\n    + simpl in H. apply andb_true_iff in H. destruct H. simpl in IHx. simpl. destruct (less y n) eqn:?.\n      * simpl. rewrite H. rewrite H0. unfold leq. rewrite Heqb. apply orb_true_r.\n      * destruct (less y n0) eqn:?.\n        -- simpl. rewrite H. apply not_less in Heqb. rewrite Heqb. unfold leq. rewrite Heqb0. rewrite orb_true_r. reflexivity.\n        -- simpl. apply IHx in H. simpl in H. rewrite H. rewrite H0. reflexivity.\n     - reflexivity. *)\nAdmitted.\n\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal62.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7390700648091676}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (x : natural) : natural :=\n  mult (plus x y) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_assoc/goal33conj254_coqofml_4vbZJp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7390085514217115}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf1 : natural) : natural :=\n  plus lf1 (mult y z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj171_coqofml_87iVWY.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7390085505575347}}
{"text": "\nRequire Import Ascii.\nRequire Import Bool.\nRequire Import Omega. \nRequire Import Peano. \n\nInductive eq_ascii : ascii -> ascii -> Prop := \n| ascii_eq : forall (a b:ascii), \n  (nat_of_ascii a) = (nat_of_ascii b) -> eq_ascii a b.\n\nLemma bit_significant_r : forall n m, 2*n+1 <> 2*m+0.\nProof. \n  intros n m. omega.\nDefined.\n\nLemma bit_significant_l : forall n m, 2*n+0 <> 2*m+1.\nProof. \n  intros n m. omega.\nDefined.\n\nLemma bit_reg_l : forall n m, 2*n = 2*m -> n = m.\nProof. \n  intros n m. omega.\nDefined.\n\nLemma plus_reg_r : forall n m p, n + p = m + p -> n = m.\n  intros. omega.\nDefined.  \n\nLtac simplify_nat := \n  match goal with \n    | H: 2*?m + ?p = 2*?n + ?p |- _ => eapply plus_reg_r in H ; simplify_nat\n    | H: 2*?m = 2*?n |- _ => eapply bit_reg_l in H ; simplify_nat\n    | H: 2*?m + 0 = 2*?n + 1 |- _ => eapply bit_significant_l in H ; simplify_nat\n    | H: 2*?m + 1 = 2*?n + 0 |- _ => eapply bit_significant_r in H ; simplify_nat\n    | H: False |- _ => inversion H\n    | H: true <> true |- _ => congruence\n    | H: false <> false |- _ => congruence\n    | H: true = false |- _ => congruence\n    | H: false = true |- _ => congruence\n    | H: ?b <> ?b', b : bool, b' : bool |- _ => destruct b ; destruct b' ; simplify_nat\n    | _ : _ |- _ => idtac\n  end.\n\nTheorem eq_ascii_eq : forall a b, eq_ascii a b -> a = b.\nProof.\n  intros a b. \n  destruct a as [b1 b2 b3 b4 b5 b6 b7 b8].\n  destruct b as [b1' b2' b3' b4' b5' b6' b7' b8'].\n  intros H ; inversion H ; clear H ; subst ; unfold nat_of_ascii in *. \n  (* bit 1 *)\n  case (bool_dec b1 b1') ; intro H' ; subst ; simplify_nat.\n  case (bool_dec b2 b2') ; intro H' ; subst ; simplify_nat.\n  case (bool_dec b3 b3') ; intro H' ; subst ; simplify_nat.\n  case (bool_dec b4 b4') ; intro H' ; subst ; simplify_nat.\n  case (bool_dec b5 b5') ; intro H' ; subst ; simplify_nat.\n  case (bool_dec b6 b6') ; intro H' ; subst ; simplify_nat.\n  case (bool_dec b7 b7') ; intro H' ; subst ; simplify_nat.\n  case (bool_dec b8 b8') ; intro H' ; subst ; auto.  \n  destruct b8 ; destruct b8' ; auto ; congruence.\nQed.\n\n\nPrint eq_ascii_eq. \n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/TestStrings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7390085468218669}}
{"text": "Require Import ssreflect.\n\nSection Socrates.\nVariable A : Set.\nVariables human mortal : A -> Prop.\nVariable socrates : A.\n\nHypothesis hm : forall x, human x -> mortal x.\nHypothesis hs : human socrates.\n\nTheorem ms : mortal socrates.\nProof.\n  apply: (hm socrates).\n  assumption.\nQed.\n\nPrint ms.\nEnd Socrates.\n\nSection Eq.\n  Variable T : Type.\n\n  Lemma symmetry : forall x y : T, x = y -> y = x.\n  Proof.\n    move=> x y exy.\n    rewrite exy.\n    done.\n  Restart.\n    by move=> x y ->.\n  Restart.\n    by move=> x y <-. (* <- だと逆に書き換え *)\n  Qed.\n\n  Lemma transitivity : forall x y z : T, x = y -> y = z -> x = z.\n  Proof.\n    by move=> x y z xy <-.\n  Restart.\n    by move=> x y z <-.\n  Qed.\nEnd Eq.\n\nSection Group.\n  Variable G : Set.\n  Variable e : G.\n  Variable op : G -> G -> G.\n  Notation \"a * b\" := (op a b).\n  Variable inv : G -> G.\n  Hypothesis associativity : forall a b c, (a * b) * c = a * (b * c).\n  Hypothesis left_identity : forall a, e * a = a.\n  Hypothesis right_identity : forall a, a * e = a.\n  Hypothesis left_inverse : forall a, inv a * a = e.\n  Hypothesis right_inverse : forall a, a * inv a = e.\n\n  Lemma unit_unique : forall e', (forall a, a * e' = a) -> e' = e.\n  Proof.\n    move=> e' He'.\n    rewrite -[RHS]He'.\n    rewrite (left_identity e').\n    done.\n  Qed.\n\n  Lemma inv_unique : forall a b, a * b = e -> a = inv b.\n  Proof.\n    move=> a b.\n    Check f_equal.\n    move/(f_equal (fun x => x * inv b)).\n    rewrite associativity right_inverse left_identity right_identity.\n    (*\n    rewrite associativity.\n    rewrite right_inverse.\n    rewrite left_identity.\n    rewrite right_identity.\n    *)\n    done.\n  Qed.\n\n  Lemma inv_involutive : forall a, inv (inv a) = a.\n  Proof.\n    move=> a.\n    by rewrite <- (inv_unique a (inv a)).\n  Restart.\n    move=>a.\n    move/inv_unique :(right_inverse a).\n  Restart.\n    move=> a.\n    by rewrite <- (inv_unique _ _ (right_inverse _)).\n  Qed.\nEnd Group.\nCheck unit_unique.\n\nSection Laws.\nVariables (A:Set) (P Q : A->Prop).\n\nLemma DeMorgan2 : (~ exists x, P x) -> forall x, ~ P x.\nProof.\n  move=> N x Px. elim: N. by exists x.\nQed.\n\nTheorem exists_or :\n  (exists x, P x \\/ Q x) -> (exists x, P x) \\/ (exists x, Q x).\nProof.\n  move=> [x [Px | Qx]]; [left|right]; by exists x.\nQed.\n\nHypothesis EM : forall P, P \\/ ~P.\n\nLemma DeMorgan2' : ~ (forall x, P x) -> exists x, ~ P x.\nProof.\n  move=> nap.\n  (*\n  move: (EM (exists x, ~ P x)).\n  case; move => //.\n  *)\n  case: (EM (exists x, ~ P x)) => //. (* 片方の分岐を解決 *)\n  move=> nnpx.\n  elim: nap => x.\n  (*\n  case: (EM (P x)) => // => npx.\n  *)\n  case: (EM (P x)) => //.\n  move => npx.\n  elim: nnpx.\n  by exists x.\nQed.\n\nEnd Laws.\n\nSection Coq3.\n  Variable A : Set.\n  Variable R : A -> A -> Prop.\n  Variables P Q : A -> Prop.\n\n  Theorem exists_postpone :\n    (exists x, forall y, R x y) -> (forall y, exists x, R x y).\n  Proof.\n    case => x H y. by exists x.\n  Restart.\n    move=> [x H] y. by exists x.\n  Qed.\n\n  Theorem exists_mp : (forall x, P x -> Q x) -> ex P -> ex Q.\n  Proof.\n    move => H [y Py]. exists y. by apply H.\n  Restart.\n    move => H [y /H Qy]. by exists y.\n  Qed.\n\n  Theorem or_exists :\n    (exists x, P x) \\/ (exists x, Q x) -> exists x, P x \\/ Q x.\n  Proof.\n    by move => [[x Px]|[x Qx]]; exists x; [left|right].\n  Restart.\n    by case => [[x Px]|[x Qx]]; exists x; [left|right].\n  Qed.\n\n  Hypothesis EM : forall P, P \\/ ~P.\n\n  Variables InPub Drinker : A -> Prop.\n  Theorem drinkers_paradox :\n    (exists consumer, InPub consumer) ->\n    exists man, InPub man /\\ Drinker man ->\n    forall other, InPub other -> Drinker other.\n  Proof.\n    case => consumer Hc.\n    case : (EM (forall man, InPub man -> Drinker man))\n      => [H|/(DeMorgan2' _ _ EM) [man H]]; [ by exists consumer|].\n      by exists man => [[]].\n  Restart.\n    move=> [c Ic].\n    case: (EM (exists x, ~ Drinker x)).\n      move=> [nd nDnd].\n      exists nd. move=> [Ind Dnd]. by elim: nDnd.\n    move=> nenD. exists c.\n    case: (EM (~Drinker c)).\n      move=> nDc [_ Dc]. by elim nDc.\n    move=> nnDc [_ Dc] o Io.\n    case: (EM (Drinker o)) => //.\n    move=> nDo. elim: nenD. by exists o.\n  Restart.\n  Abort.\n\n  Theorem remove_c : forall a,\n    (forall x y, Q x -> Q y) ->\n    (forall c, ((exists x, P x) -> P c) -> Q c) -> Q a.\n  Proof.\n    move=> a allQ H.\n    case : (EM (exists x, P x)) =>[[c pc]|np].\n    - by apply : allQ (H c _).\n    - by apply : H.\n  Restart.\n    move=> a Qxy H.\n    case: (EM (exists x, P x)).\n      move=> [b Pb]. move: (H b). move=> H2.\n      apply: (Qxy b).\n      apply: H2. by move=> //.\n    move=> neP. apply : H. move=> [b Pb].\n    elim: neP. by exists b.\n  Restart.\n  Abort.\nEnd Coq3.", "meta": {"author": "yak1ex", "repo": "ssreflect_study", "sha": "a28ac45bba327df674ceedf45564d91e3fe6dc77", "save_path": "github-repos/coq/yak1ex-ssreflect_study", "path": "github-repos/coq/yak1ex-ssreflect_study/ssreflect_study-a28ac45bba327df674ceedf45564d91e3fe6dc77/ssreflect02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.8615382076534743, "lm_q1q2_score": 0.7389999863579808}}
{"text": "Require Import Omega.\n\nInductive Plus : nat -> nat -> nat -> Prop :=\n| PlusZero\n  : forall m, Plus 0 m m\n| PlusSucc\n  : forall n m r,\n    Plus n m r ->\n    Plus (S n) m (S r).\n\nHint Constructors Plus.\n\nDefinition plus_cert : forall (n m : nat), {r : nat | Plus n m r}.\n  refine (fix plus_cert (n m : nat) : {r | Plus n m r} :=\n            match n return {r | Plus n m r} with\n            | O    => exist _ m _\n            | S n1 =>\n              match plus_cert n1 m with\n              | exist _ r1 _ => exist _ (S r1) _\n              end\n            end) ; clear plus_cert ; auto.\nDefined.\n\nDefinition pred_cert : forall (n : nat), n > 0 -> {r | n = 1 + r}.\n  refine (fun n =>\n            match n return n > 0 -> {r | n = 1 + r} with\n            | O => fun _ => False_rec _ _\n            | S n' => fun _ => exist _ n' _\n            end) ; omega.\nDefined.\n\nNotation \"!\" := (False_rec _ _).\nNotation \"[ e ]\" := (exist _ e _).\n\nDefinition pred_cert1 : forall (n : nat), n > 0 -> {r | n = 1 + r}.\n  refine (fun n =>\n            match n return n > 0 -> {r | n = 1 + r} with\n            | O => fun _ => !\n            | S n' => fun _ => [ n' ]\n            end) ; omega.\nDefined.\n\nNotation \"'Yes'\" := (left _ _).\nNotation \"'No'\" := (right _ _).\nNotation \"'Reduce' x\" := (if x then Yes else No) (at level 50).\n\nDefinition eq_nat_dec : forall (n m : nat), {n = m} + {n <> m}.\n  refine (fix eq_nat n m : {n = m} + {n <> m} :=\n            match n , m with\n            | O    , O    => Yes\n            | S n' , S m' => Reduce (eq_nat n' m')\n            | _    , _    => No\n            end) ; clear eq_nat ; congruence.\nDefined.\n\n(** exercício 44 *)\n\nDefinition eq_bool_dec : forall (a b : bool), {a = b} + {a <> b}.\nAdmitted.\n\n(** exercício 45 *)\n\nDefinition eq_list_dec\n           {A : Type}\n           (eqAdec : forall (x y : A), {x = y} + {x <> y})\n  : forall (xs ys : list A), {xs = ys} + {xs <> ys}.\nAdmitted.\n\n\nNotation \"!!\" := (inright _ _).\nNotation \"[|| x ||]\" := (inleft _ [x]).\n\n\nDefinition pred_cert_full : forall n, {r | n = 1 + r} + {n = 0}.\n  refine (fun n =>\n            match n return {r | n = 1 + r} + {n = 0} with\n            | O => !!\n            | S n' => [|| n' ||] \n            end) ; auto.\nDefined.\n\nLtac inverts H := inversion H ; subst ; clear H.\n\nSection MAP.\n  Variable Key : Type.\n  Variable Value : Type.\n  Variable eqKeyDec : forall (x y : Key), {x = y} + {x <> y}.\n\n  Inductive Map : Type :=\n  | nil : Map\n  | cons : Key -> Value -> Map -> Map.\n\n  Inductive MapsTo : Key -> Value -> Map -> Prop :=\n  | Here  : forall k v m, MapsTo k v (cons k v m)\n  | There : forall k v m k' v', k <> k' ->\n            MapsTo k v m -> MapsTo k v (cons k' v' m).\n  \n  Hint Constructors MapsTo.\n  \n  Definition lookupMap\n    : forall (k : Key)(m : Map), {v | MapsTo k v m} + {forall v, ~ MapsTo k v m}.\n    refine (fix look k m : {v | MapsTo k v m} + {forall v, ~ MapsTo k v m} :=\n              match m return {v | MapsTo k v m} + {forall v, ~ MapsTo k v m} with\n              | nil => !!\n              | cons k' v' m' =>\n                match eqKeyDec k k' with\n                | Yes => [|| v' ||]\n                | No  =>\n                  match look k m' with\n                  | !! => !!\n                  | [|| v ||] => [|| v ||]\n                  end\n                end\n              end) ;\n      clear look ; subst ;\n        try (repeat (match goal with\n                     | [H : MapsTo _ _ nil |- _] => inverts H\n                     | [H : MapsTo _ _ (cons _ _ _) |- _] => inverts H\n                     | [|- forall x, ~ _ ] => unfold not ; intros\n                     | [ H : forall x, ~ (MapsTo _ _ _)\n                         , H1 : MapsTo _ _ _ |- _] => apply H in H1\n                     end)) ; auto.\n  Defined.\n\n  (** exercício 46 *)\n\n  Definition insertMap : forall (k : Key)(v : Value)(m : Map), {m' | MapsTo k v m'}.\n  Admitted.\n  \n  (** exercício 47 *)\n\n  Definition removeMap : forall (k : Key)(m : Map), {m' | forall v, ~ MapsTo k v m'}.\n  Admitted.\nEnd MAP.  \n\n\nSection VEC.\n\n  Inductive vector (A : Set) : nat -> Type :=\n  | vnil  : vector A 0\n  | vcons : forall n, A -> vector A n -> vector A (S n).\n\n  Fixpoint app {A : Set}{n1 n2}(ls1 : vector A n1)(ls2 : vector A n2) : vector A (n1 + n2) :=\n    match ls1 with\n    | vnil _ => ls2\n    | vcons _ _ x ls1' => vcons _ _ x (app ls1' ls2)\n    end.\n\n  Definition vhead {A : Set}{n}(v : vector A (S n)) : A :=\n    match v with\n    | vcons _ _ x _ => x  \n    end.\n\n  (** exercício 48 *)\n\n  Fixpoint vmap {A B : Set}{n}(f : A -> B)(v : vector A n) : vector B n.\n  Admitted.  \n\n  (** exercício 49 \n      Enuncie um teorema sobre a associatividade da \n      concatenação de vectors e o prove. *)\n\n  Inductive fin : nat -> Set :=\n  | fzero : forall {n}, fin (S n)\n  | fsucc : forall {n}, fin n -> fin (S n).                          \n\n  Fixpoint get {A}{n}(ls : vector A n) : fin n -> A :=\n    match ls with\n      | vnil _ => fun idx =>\n        match idx in fin n' return (match n' with\n                                        | O => A\n                                        | S _ => unit\n                                      end) with\n          | fzero => tt\n          | fsucc _ => tt\n        end\n      | vcons _ _ x ls' => fun idx =>\n        match idx in fin n' return (fin (pred n') -> A) -> A with\n          | fzero => fun _ => x\n          | fsucc idx' => fun get_ls' => get_ls' idx'\n        end (get ls')\n    end.\nEnd VEC.  \n", "meta": {"author": "rodrigogribeiro", "repo": "coqcourse", "sha": "1e39614285522cba5045b0a190e3bd19c560a2f7", "save_path": "github-repos/coq/rodrigogribeiro-coqcourse", "path": "github-repos/coq/rodrigogribeiro-coqcourse/coqcourse-1e39614285522cba5045b0a190e3bd19c560a2f7/code/dependenttypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7389999850823425}}
{"text": "Module Sets.\nDefinition full {A : Type} : A -> Prop := fun _ => True.\nDefinition empty {A : Type} : A -> Prop := fun _ => False.\nDefinition union {A : Type} (X Y : A -> Prop) : A -> Prop := fun a => X a \\/ Y a.\nDefinition intersect {A : Type} (X Y : A -> Prop) : A -> Prop := fun a => X a /\\ Y a.\nDefinition omega_union {A : Type} (X : nat -> A -> Prop) : A -> Prop := fun a => exists n, X n a.\nEnd Sets.\n\nModule BinRel.\nDefinition id {A : Type} : A -> A -> Prop := fun x y => x = y.\nDefinition empty {A : Type} : A -> A -> Prop := fun x y => False.\nDefinition concat {A : Type} (r1 r2 : A -> A -> Prop) : A -> A -> Prop := fun x z => exists y, r1 x y /\\ r2 y z.\nDefinition union {A : Type} (r1 r2 : A -> A -> Prop) : A -> A -> Prop := fun x y => r1 x y \\/ r2 x y.\nDefinition intersection {A : Type} (r1 r2 : A -> A -> Prop) : A -> A -> Prop := fun x y => r1 x y /\\ r2 x y.\nDefinition testrel {A : Type} (r : A -> Prop) := fun x y => x = y /\\ r x.\nDefinition omega_union {A : Type} (r : nat -> A -> A -> Prop) : A -> A -> Prop := fun x y => exists n, r n x y.\nDefinition dia {A : Type} (r : A -> A -> Prop) (s : A -> Prop) : A -> Prop := fun x => exists y, r x y /\\ s y.\nEnd BinRel.\n", "meta": {"author": "TaoYC0904", "repo": "Toy-Language-Address", "sha": "cabf1d8ef0fd11dd5bf4d61b2df2322a296f710c", "save_path": "github-repos/coq/TaoYC0904-Toy-Language-Address", "path": "github-repos/coq/TaoYC0904-Toy-Language-Address/Toy-Language-Address-cabf1d8ef0fd11dd5bf4d61b2df2322a296f710c/2-FP/lib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810421953309, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.7389504770575078}}
{"text": "(** Structured Data *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\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\nNotation \"( x , y )\" := (pair x y).\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\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.  Qed.\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  simpl.\nAbort.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.  destruct p as [n m].  simpl.  reflexivity. \nQed.\n\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros[ n m ]; simpl; reflexivity.\nQed.\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros[ n m ]; simpl; reflexivity.\nQed.\n\n(** * Lists of Numbers *)\n\n\nInductive natlist : Set :=\n| nil  : natlist\n| cons : nat -> natlist -> natlist.\n\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"[ ]\" := nil.\n\nNotation \"n :: l\" := (cons n l)\n                     (at level 60, right associativity).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\nCompute (repeat 7 20).\n\nFixpoint length (l : natlist) : nat :=\nmatch l with\n| [] => O\n| n :: l' => S (length l')\nend.\n\n\nFixpoint app (l1 l2 : natlist) : natlist :=\nmatch l1 with\n| []      => l2\n| h :: t  => h :: app t l2\nend.\n\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\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\nFixpoint nonzeros (l : natlist) : natlist :=\nmatch l with\n| nil => nil\n| h :: t =>   match h with\n              | O   => nonzeros t\n              | S _ => h :: nonzeros t\n              end\nend.\n\nCompute (nonzeros [0;1;0;2;3;0;0]).\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\n  reflexivity.\nQed.\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\nFixpoint oddmembers (l : natlist) : natlist :=\nmatch l with\n| nil     => nil\n| h :: t  =>  if evenb h \n              then oddmembers t \n              else h :: oddmembers t\nend.\n\nFixpoint oddmembers' (l : natlist) : natlist :=\nmatch l with\n| nil     => nil\n| h :: t  =>  match evenb h with\n              | true => oddmembers t \n              | false => h :: oddmembers t\n              end\nend.\n\nExample test_oddmembers:\n  oddmembers' [0;1;0;2;3;0;0] = [1;3].\nProof.\n  simpl. reflexivity.\nQed.\n\nFixpoint countoddmembers (l : natlist) : nat :=\nmatch l with\n| nil     => O\n| h :: t  =>  if oddb h \n              then S (countoddmembers t)\n              else countoddmembers t\nend.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof.\n  reflexivity.\nQed.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. \n   reflexivity.\nQed.\n  \nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof.\n  reflexivity.\nQed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\nmatch 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\nCompute (alternate [1;2;3] [4;5;6]).\n\nExample test_alternate1:\n  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof.\n  reflexivity.\nQed.\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\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof.\n  reflexivity.\nQed.\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S m => m\n  end.\n\nTheorem tl_length_pred : \n  forall l : natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l. destruct l as [| n l'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.  \nQed.\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3. \n  induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons n l1' *)\n    simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nFixpoint rev (l : natlist) : natlist :=\nmatch l with \n| nil => nil\n| h :: t => (rev t) ++ [h]\nend.\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\nTheorem rev_length_firsttry : \n  forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. \n  induction l as [| n l' IHl'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite <- IHl'.\nAbort.\n\nTheorem app_length : \n  forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. \n  induction l1 as [| n l1' IHl1'].\n  - simpl.\n    reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : \n  forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\nintros *.\ninduction n as [| n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_comm : \n  forall n m : nat,\n  n + m = m + n.\nProof.\n  intros*.\n  induction n as [| n' IHn']; simpl.\n  -apply plus_n_O.\n  -rewrite IHn'. apply plus_n_Sm.\nQed.\n\n\nTheorem rev_length : \n  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    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros*.\n  induction l; simpl. reflexivity.\n  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; simpl.\n  -rewrite app_nil_r. reflexivity.\n  - 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; simpl. reflexivity.\n  rewrite rev_app_distr. rewrite IHl. simpl. reflexivity.\nQed.\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; simpl.\n  -rewrite app_assoc. reflexivity.\n  -rewrite <- IHl1. reflexivity.\nQed.\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  - induction n as [| n IHn ]; simpl.\n    + rewrite IHl1. reflexivity.\n    + rewrite IHl1. reflexivity. \n  \nQed.\n\nFixpoint ravno (n m : nat) : bool :=\nmatch n , m with\n|O , O => true\n|O , _ => false\n|_ , O => false\n|S n' , S m' => (ravno n' m')\nend.\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 ravno h1 h2 \n                        then beq_natlist t1 t2\n                        else false\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 : \n  forall l : natlist,\n  true = beq_natlist l l.\nProof.\n  intros *.\n  induction l; simpl. reflexivity.\n  replace (ravno n n) with true. rewrite IHl. reflexivity.\n  induction n; simpl. reflexivity.\n  rewrite IHn. reflexivity.\nQed.\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\nTheorem ble_n_Sn : \n  forall n : nat,\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.  \nQed.\n", "meta": {"author": "Buratinox", "repo": "CoqBook", "sha": "39047256c43afa4b491f4a0408e03ed7e78d1806", "save_path": "github-repos/coq/Buratinox-CoqBook", "path": "github-repos/coq/Buratinox-CoqBook/CoqBook-39047256c43afa4b491f4a0408e03ed7e78d1806/04_structured_data.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7389347000100802}}
{"text": "Add LoadPath \".\".\nRequire Import Nat Arith Cpdt.CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nDefinition var := nat.\nDefinition vars := var -> nat.\nDefinition set (vs : vars) (v1 : var) (n : nat) : vars :=\n  fun v2 => if beq_nat v1 v2 then n else vs n.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Var : var -> exp\n| Plus : exp -> exp -> exp\n| Times : exp -> exp -> exp.\n\nFixpoint evalExp (vs : vars) (e : exp) : nat :=\n  match e with\n  | Const n => n\n  | Var v => vs v\n  | Plus e1 e2 => evalExp vs e1 + evalExp vs e2\n  | Times e1 e2 => evalExp vs e1 * evalExp vs e2\n  end.\n\nInductive cmd : Set :=\n| Assign : var -> exp -> cmd\n| Seq : cmd -> cmd -> cmd\n| While : exp -> cmd -> cmd\n| If : exp -> cmd -> cmd -> cmd.\n\nCoInductive evalCmd : vars -> cmd -> vars -> Prop :=\n| EvalAssign : forall vs v e,\n    evalCmd vs (Assign v e) (set vs v (evalExp vs e))\n| EvalSeq : forall vs1 vs2 vs3 c1 c2,\n    evalCmd vs1 c1 vs2 ->\n    evalCmd vs2 c2 vs3 ->\n    evalCmd vs1 (Seq c1 c2) vs3\n| EvalWhileFalse : forall vs e c,\n    evalExp vs e = 0 ->\n    evalCmd vs (While e c) vs\n| EvalWhileTrue : forall vs1 vs2 vs3 e c,\n    evalExp vs1 e <> 0 ->\n    evalCmd vs1 c vs2 ->\n    evalCmd vs2 (While e c) vs3 ->\n    evalCmd vs1 (While e c) vs3\n| EvalIfFalse : forall vs1 vs2 e c1 c2,\n    evalExp vs1 e = 0 ->\n    evalCmd vs1 c2 vs2 ->\n    evalCmd vs1 (If e c1 c2) vs2\n| EvalIfTrue : forall vs1 vs2 e c1 c2,\n    evalExp vs1 e <> 0 ->\n    evalCmd vs1 c1 vs2 ->\n    evalCmd vs1 (If e c1 c2) vs2.\n\nSection evalCmd_coind.\n  Variable R : vars -> cmd -> vars -> Prop.\n\n  Hypothesis AssignCase : forall vs1 vs2 v e,\n      R vs1 (Assign v e) vs2 ->\n      vs2 = set vs1 v (evalExp vs1 e).\n\n  Hypothesis SeqCase : forall vs1 vs3 c1 c2,\n      R vs1 (Seq c1 c2) vs3 ->\n      exists vs2, R vs1 c1 vs2 /\\ R vs2 c2 vs3.\n\n  Hypothesis WhileCase : forall vs1 vs3 e c,\n      R vs1 (While e c) vs3 ->\n      (evalExp vs1 e = 0 /\\ vs1 = vs3) \\/\n      exists vs2, evalExp vs1 e <> 0 /\\ R vs1 c vs2 /\\ R vs2 (While e c) vs3.\n\n  Hypothesis IfCase : forall vs1 vs2 e c1 c2,\n      R vs1 (If e c1 c2) vs2 ->\n      (evalExp vs1 e = 0 /\\ R vs1 c2 vs2) \\/\n      (evalExp vs1 e <> 0 /\\ R vs1 c1 vs2).\n\n  Theorem evalCmd_coind : forall vs1 c vs2, R vs1 c vs2 -> evalCmd vs1 c vs2.\n    cofix; intros ? ? ? H; destruct c.\n    - rewrite (AssignCase H); constructor.\n    - destruct (SeqCase H) as [? [? ?]]; econstructor; eauto.\n    - destruct (WhileCase H) as [[? ?] | [? [? [? ?]]]]; subst; econstructor; eauto.\n    - destruct (IfCase H) as [[? ?] | [? ?]].\n      + apply EvalIfFalse; auto.\n      + apply EvalIfTrue; auto.\n  Qed.\nEnd evalCmd_coind.\n\nFixpoint optExp (e : exp) : exp :=\n  match e with\n  | Plus (Const 0) e => optExp e\n  | Plus e (Const 0) => optExp e\n  | Plus e1 e2 => Plus (optExp e1) (optExp e2)\n  | Times (Const 0) _ => Const 0\n  | Times _ (Const 0) => Const 0\n  (* | Times (Const 1) e => optExp e *)\n  (* | Times e (Const 1) => optExp e *)\n  | Times e1 e2 => Times (optExp e1) (optExp e2)\n  | e => e\n  end.\n\nFixpoint optCmd (c : cmd) : cmd :=\n  match c with\n  | Assign v e => Assign v (optExp e)\n  | Seq c1 c2 => Seq (optCmd c1) (optCmd c2)\n  | While e c => While (optExp e) (optCmd c)\n  | If e c1 c2 => If (optExp e) (optCmd c1) (optCmd c2)\n  end.\n\nLemma optExp_plus_dist : forall vs e1 e2,\n    evalExp vs (optExp (Plus e1 e2)) = evalExp vs (Plus (optExp e1) (optExp e2)).\n  induction e1; induction e2; auto; induction n; simpl; auto; induction n0; simpl; auto.\nQed.\n\nLemma optExp_plus : forall vs e1 e2,\n    evalExp vs (optExp (Plus e1 e2)) = evalExp vs (optExp e1) + evalExp vs (optExp e2).\n  induction e1; induction e2; auto; induction n; simpl; auto; induction n0; simpl; auto.\nQed.\n\n(*\nLemma optExp_times_const : forall vs e n,\n    evalExp vs (optExp (Times e (Const n))) = evalExp vs (optExp e) * n.\n  intros; induction e; simpl; crush.\nAdmitted.\n\nLemma optExp_const_times : forall vs e n,\n    evalExp vs (optExp (Times (Const n) e)) = n * evalExp vs (optExp e).\nAdmitted.\n*)\n\nLemma optExp_times : forall vs e1 e2,\n    evalExp vs (optExp (Times e1 e2)) = evalExp vs (optExp e1) * evalExp vs (optExp e2).\n  (* Hint Rewrite optExp_times_const optExp_const_times. *)\n  induction e1; induction e2; auto; induction n; auto; induction n0; auto.\n    (* rewrite ? optExp_times_const, ? optExp_const_times; auto. *)\nQed.\n\nLemma optExp_correct : forall vs e, evalExp vs (optExp e) = evalExp vs e.\n  induction e; auto; (rewrite optExp_plus || rewrite optExp_times); rewrite IHe1, IHe2; auto.\n  (*\n  induction e; crush;\n    repeat (match goal with\n            | [ |- context[match ?E with Const _ => _ | Plus _ _ => _ | _ => _ end] ] =>\n              destruct E\n            | [ |- context[match ?E with O => _ | S _ => _ end] ] =>\n              destruct E\n            end; crush).\n   *)\nQed.\n\nHint Rewrite optExp_correct.\n\nLtac finisher :=\n  match goal with\n  | [ H : evalCmd _ _ _ |- _ ] => ((inversion H; []) || (inversion H; [|])); subst\n  end; crush; eauto 10.\n\nLemma optCmd_correct1 : forall vs1 c vs2, evalCmd vs1 c vs2 -> evalCmd vs1 (optCmd c) vs2.\n  intros;\n    apply (evalCmd_coind (fun vs1 c vs2 => exists c', evalCmd vs1 c' vs2 /\\ c = optCmd c'));\n    eauto; crush;\n      match goal with\n      | [ H : _ = optCmd ?E |- _ ] =>\n        destruct E; simpl in *; discriminate || injection H; intros; subst\n      end; finisher.\nQed.\n\nLemma optCmd_correct2 : forall vs1 c vs2, evalCmd vs1 (optCmd c) vs2 -> evalCmd vs1 c vs2.\n  intros; apply (evalCmd_coind (fun vs1 c vs2 => evalCmd vs1 (optCmd c) vs2));\n    crush; finisher.\nQed.\n\nTheorem optCmd_correct : forall vs1 c vs2, evalCmd vs1 (optCmd c) vs2 <-> evalCmd vs1 c vs2.\n  intuition; apply optCmd_correct1 || apply optCmd_correct2; assumption.\nQed.", "meta": {"author": "porglezomp", "repo": "learn-languages", "sha": "753463cef897112aa5d11f236910c84bc79d30d2", "save_path": "github-repos/coq/porglezomp-learn-languages", "path": "github-repos/coq/porglezomp-learn-languages/learn-languages-753463cef897112aa5d11f236910c84bc79d30d2/coq/CoInductive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.73892512482441}}
{"text": "Require Import String.\nRequire Import List.\nImport ListNotations.\n\nDefinition Var := string.\nOpen Scope string_scope.\n\nInductive BExp :=\n| btrue : BExp\n| bfalse : BExp\n| bvar : string -> BExp\n| bor : BExp -> BExp ->BExp\n| bnot : BExp -> BExp\n| band : BExp -> BExp -> BExp.\n\nFixpoint interpretB (e : BExp) (env : Var -> bool) : bool :=\n  match e with\n  | btrue => true\n  | bfalse => false\n  | bvar a => env a\n  | bor e1 e2 => orb (interpretB e1 env)  (interpretB e2 env )\n  | bnot e1 => negb (interpretB e1 env)\n  | band e1 e2 => andb (interpretB e1 env ) (interpretB e2 env)\n  end.\n\nDefinition env1 := fun x => if string_dec x \"n\" then true else false.\nCheck env1.\n\nCompute (interpretB (bor (bnot (bvar \"x\")) bfalse) env1).\n\nInductive Instructionb :=\n| push_con : bool -> Instructionb\n| push_bvar : Var -> Instructionb\n| or' : Instructionb\n| not' : Instructionb\n| and' :Instructionb.\n\nDefinition Stackb := list bool.\nFixpoint run_instructionb (i : Instructionb)\n         (env : Var -> bool) (stack : Stackb) : Stackb :=\n  match i with\n  | push_con c => (c :: stack)\n  | push_bvar x => ((env x) :: stack)\n  | or' => match stack with\n           | n1 :: n2 :: stack' => (orb n1  n2) :: stack'\n           | _ => stack\n           end\n  | not' => match stack with\n           | n1 :: stack' => (negb n1) :: stack'\n           | _ => stack\n           end\n  | and'  => match stack with\n           | n1 :: n2 :: stack' => (andb n1 n2) :: stack'\n           | _ => stack\n           end\n  end.\n\nCompute (run_instructionb (push_con true) env1 []).\nCompute (run_instructionb (push_bvar \"x\") env1 []).\nCompute (run_instructionb or' env1 [ true ; false ; true]).\nCompute (run_instructionb and' env1 [ false ; true ; true]).\n\nFixpoint run_instructionsb (is' : list Instructionb)\n         (env : Var -> bool) (stack : Stackb) : Stackb :=\n  match is' with\n  | [] => stack\n  | i :: is'' => run_instructionsb is'' env (run_instructionb i env stack)\n  end.\n\nDefinition pgm1b := [\n                    push_con true ;\n                    push_bvar \"x\"\n                  ].\nCompute run_instructionsb pgm1b env1 [].\n\n\nFixpoint compileb (e : BExp) : list Instructionb :=\n  match e with\n  | btrue => [push_con true]\n  | bfalse => [push_con false]\n  | bvar x => [push_bvar x]\n  | bor e1 e2 => (compileb e1) ++ (compileb e2) ++ [or']\n  | band e1 e2 => (compileb e1) ++ (compileb e2) ++ [and']\n  | bnot e1 => (compileb e1) ++ [not']\n  end.\n\n\nCompute compileb (btrue).\nCompute compileb (band (bvar \"x\") btrue).\nCompute compileb (band (bnot (band btrue (bor btrue bfalse)))(band (bvar \"x\") btrue)).\n\nCompute interpretB (band (bnot (band btrue (bor btrue bfalse)))(band (bvar \"x\") btrue)) env1.\nCompute run_instructionsb\n        (compileb (band (bnot (band btrue (bor btrue bfalse)))(band (bvar \"x\") btrue)))\n        env1\n        [].\n\nLemma orb_comm : forall b1 b2:bool, orb b1 b2 = orb b2 b1.\nProof.\n intros. induction b1. - unfold orb. induction b2. eauto. eauto.\n-unfold orb. induction b2. eauto. eauto.\nQed.\n\nLemma andb_comm : forall b1 b2:bool, andb b1 b2 =andb b2 b1.\nProof.\n intros. induction b1. - unfold andb. induction b2. eauto. eauto.\n-unfold orb. induction b2. eauto. eauto.\nQed.\n\n Lemma soundness_helper :\n  forall e env stack is',\n    run_instructionsb (compileb e ++ is') env stack =\n    run_instructionsb is' env ((interpretB e env) :: stack).\n\nProof.\n  induction e; intros; simpl; trivial.\n  - rewrite <- app_assoc.\n    rewrite <- app_assoc.\n    rewrite IHe1.\n    rewrite IHe2.\n    simpl.\n    eauto. trivial. rewrite orb_comm. reflexivity.\n  - rewrite <- app_assoc. induction e.\n    rewrite IHe. simpl. eauto. rewrite IHe. simpl. eauto.\n    rewrite IHe. simpl. eauto. rewrite IHe. simpl. eauto.\nrewrite IHe. simpl. eauto. rewrite IHe. simpl. eauto.\n  -rewrite <- app_assoc. rewrite <- app_assoc. \nrewrite IHe1. rewrite IHe2. simpl. rewrite andb_comm. reflexivity. \nQed.\n\n\n", "meta": {"author": "andreea1603", "repo": "mylanguage", "sha": "19f8b0ce91b6690532e6b5714cc39ea02ac2dec3", "save_path": "github-repos/coq/andreea1603-mylanguage", "path": "github-repos/coq/andreea1603-mylanguage/mylanguage-19f8b0ce91b6690532e6b5714cc39ea02ac2dec3/compliation_bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.7388258822373133}}
{"text": "Fixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => mult (S n') (factorial n')\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", "meta": {"author": "Asap7772", "repo": "coq_softwarefoundations", "sha": "a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d", "save_path": "github-repos/coq/Asap7772-coq_softwarefoundations", "path": "github-repos/coq/Asap7772-coq_softwarefoundations/coq_softwarefoundations-a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d/chapter1/factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.738748450776817}}
{"text": "Require Import NArith.\nRequire Import Setoid.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nGeneralizable All Variables.\n\nClass has_mul A :=\n  { mul : A -> A -> A }.\n\nInfix \"*\" := mul (left associativity, at level 40).\n\nClass is_assoc {A} (r : A -> A -> A) :=\n  { assoc : `(r a (r b c) = r (r a b) c) }.\n\nClass semigroup `(has_mul A) `(is_assoc _ mul).\n\n(* TODO: Complete the following in the same vein. *)\n\n(** * Monoids *)\nModule Type monoid.\n  Include semigroup.\n\n  (** The neutral (unit) element *)\n  Variable e : elt.\n\n  (** Multiplication by the unit is identity *)\n  Axiom lunit_id : forall a, e * a = a.\n  Axiom runit_id : forall a, a * e = a.\n\n  Hint Resolve lunit_id runit_id : monoid.\n\n  (** Exponentiation *)\n  Fixpoint pow (a : elt) (n : nat) :=\n    match n with\n    | 0    => e\n    | S n' => pow a n' * a\n    end.\n\n  Definition order a n := (forall i, 1 <= i < n -> pow a i <> e) /\\ pow a n = e.\n\n  Require Import Coq.Lists.List.\n  Import List.ListNotations.\n\n  Fixpoint prod (xs : list elt) :=\n    match xs with\n    | [] => e\n    | x :: xs => prod xs * x\n    end.\nEnd monoid.\n\nModule monoid_facts (Import M : monoid).\n  (** Square of the unit is unit *)\n  Lemma unit2_unit : M.e * M.e = M.e.\n  Proof. now rewrite lunit_id. Qed.\n\n  Lemma pow_O : forall a, pow a 0 = M.e.\n  Proof. now cbn. Qed.\n\n  Lemma pow_1 : forall a, pow a 1 = a.\n  Proof. now intro; cbn; rewrite M.lunit_id. Qed.\n\n  Lemma pow_unit_unit : forall n, pow M.e n = M.e.\n  Proof.\n    induction n; [trivial |].\n    cbn.\n    rewrite IHn.\n    apply unit2_unit.\n  Qed.\n\n  Lemma pow_lmul : forall a n, a * pow a n = pow a (S n).\n  Proof.\n    induction n; cbn.\n    - now rewrite runit_id, lunit_id.\n    - rewrite <- assoc, IHn.\n      now cbn.\n  Qed.\n\n  Lemma pow_rmul : forall a n, pow a n * a = pow a (S n).\n  Proof. reflexivity. Qed.\n\n  Lemma pow_sum : forall a m n, pow a m * pow a n = pow a (m + n).\n  Proof.\n    induction m; intro.\n    - apply lunit_id.\n    - cbn.\n      rewrite assoc, pow_lmul.\n      cbn.\n      now rewrite <- assoc, IHm.\n  Qed.\n\n  Lemma pow_prod : forall a m n, pow (pow a m) n = pow a (m * n).\n  Proof.\n    induction n.\n    - now rewrite Nat.mul_0_r; cbn. (* now cbn; rewrite pow_unit_unit. *)\n    - rewrite Nat.mul_succ_r.\n      cbn.\n      now rewrite IHn,  pow_sum.\n  Qed.\nEnd monoid_facts.\n\n(** * Groups *)\nModule Type group.\n  Include monoid.\n\n  (** The inverse of an element *)\n  Variable inv : elt -> elt.\n  Notation \"a '⁻¹'\" := (inv a) (at level 10, format \"a '⁻¹'\").\n\n  (** The inverse of an element times the element equals the unit *)\n  Axiom linv_unit : forall a, a⁻¹ * a = e.\nEnd group.\n\nModule group_facts (Import G : group).\n  Module MFacts := monoid_facts G.\n  Include MFacts.\n\n  Lemma lcancel : forall a b c, a * b = a * c -> b = c.\n  Proof.\n    intros.\n    rewrite <- (lunit_id b), <- (lunit_id c), <- (linv_unit a).\n    now rewrite assoc, H, <- assoc.\n  Qed.\n\n  Lemma runit_id : forall a, a * G.e = a.\n  Proof.\n    intro a.\n    apply (lcancel (G.inv a)).\n    rewrite <- assoc, linv_unit.\n    apply unit2_unit.\n  Qed.\n\n  Lemma rinv_unit : forall a, a * a⁻¹ = G.e.\n  Proof.\n    intros.\n    apply (lcancel (G.inv a)).\n    rewrite <- assoc, linv_unit.\n    now rewrite lunit_id, runit_id.\n  Qed.\n\n  Lemma rcancel : forall a b c, b * a = c * a -> b = c.\n  Proof.\n    intros.\n    rewrite <- (runit_id b), <- (runit_id c), <- (rinv_unit a).\n    now rewrite <- assoc, <- assoc, H.\n  Qed.\n\n  Lemma unit_inv_unit : (G.e)⁻¹ = G.e.\n  Proof.\n    now rewrite <- (linv_unit G.e) at 2; rewrite runit_id.\n  Qed.\n\n  Lemma inv_inv : forall x, (x⁻¹)⁻¹ = x.\n  Proof.\n    intro x.\n    rewrite <- (lunit_id x) at 2; rewrite <- (linv_unit (G.inv x)).\n    now rewrite assoc, linv_unit, runit_id.\n  Qed.\n\n  Lemma inv_dist : forall a b, (a * b)⁻¹ = b⁻¹ * a⁻¹.\n  Proof.\n    intros a b.\n    apply (lcancel (a * b)).\n    rewrite rinv_unit.\n    rewrite assoc, <- (assoc _ (G.inv _) (G.inv _)), rinv_unit, lunit_id.\n    now rewrite rinv_unit.\n  Qed.\n\n  Lemma lmul_unit_is_inv : forall a b, b * a = G.e -> b = G.inv a.\n  Proof.\n    intros a b H.\n    apply (rcancel a).\n    now rewrite H, linv_unit.\n  Qed.\n\n  Lemma rmul_unit_is_inv : forall a b, a * b = G.e -> b = G.inv a.\n  Proof.\n    intros a b H.\n    apply (lcancel a).\n    now rewrite H, rinv_unit.\n  Qed.\n\n  Lemma commut_iff : forall a b, a * b * a⁻¹ * b⁻¹ = G.e <-> a * b = b * a.\n  Proof.\n    split; intro H.\n    - rewrite <- lunit_id, <- H.\n      rewrite assoc, <- (assoc _ b a), linv_unit, lunit_id.\n      now rewrite assoc, linv_unit, runit_id.\n    - rewrite assoc, <- inv_dist, H.\n      now rewrite rinv_unit.\n  Qed.\n\n  Lemma inv_pow : forall a n, pow (a⁻¹) n = (pow a n)⁻¹.\n  Proof.\n    induction n.\n    - cbn.\n      now rewrite unit_inv_unit.\n    - cbn.\n      rewrite IHn, <- inv_dist.\n      now rewrite pow_lmul, pow_rmul.\n  Qed.\nEnd group_facts.\n\nModule Type group_homo (G H : group).\n  Infix \"*\" := G.op (left associativity, at level 40).\n  Infix \"#\" := H.op (left associativity, at level 40).\n\n  Parameter f : G.elt -> H.elt.\n\n  Axiom homo_spec : forall a b, f (a * b) = f a # f b.\nEnd group_homo.\n\nModule group_homo_facts (G H : group) (Import Homo : group_homo G H).\n  Module GFacts := group_facts G.\n  Module HFacts := group_facts H.\n\n  Lemma unit_to_unit : f G.e = H.e.\n  Proof.\n    apply (HFacts.lcancel (f G.e)).\n    rewrite <- homo_spec, GFacts.unit2_unit.\n    now rewrite HFacts.runit_id.\n  Qed.\n\n  Lemma inv_to_inv : forall a, f (G.inv a) = H.inv (f a).\n  Proof.\n    intro a.\n    apply (HFacts.lcancel (f a)).\n    rewrite <- homo_spec, GFacts.rinv_unit.\n    now rewrite HFacts.rinv_unit, unit_to_unit.\n  Qed.\nEnd group_homo_facts.\n\nModule Type group_direct_prod (G H : group) <: group.\n  Definition elt := (G.elt * H.elt)%type.\n  Definition e := (G.e, H.e).\n\n  Definition op g h :=\n    match g, h with\n    | (a, b), (c, d) => (G.op a c, H.op b d)\n    end.\n\n  Definition inv a :=\n    match a with\n    | (g, h) => (G.inv g, H.inv h)\n    end.\n\n  Local Infix \"*\" := op (left associativity, at level 40).\n\n  Lemma assoc : forall a b c, a * b * c = a * (b * c).\n  Proof.\n    intros [a b] [c d] [e f]; cbn.\n    now rewrite G.assoc, H.assoc.\n  Qed.\n\n  Lemma lunit_id : forall a, e * a = a.\n  Proof.\n    intros [a b]; cbn.\n    now rewrite G.lunit_id, H.lunit_id.\n  Qed.\n\n  Lemma linv_unit : forall a, inv a * a = e.\n  Proof.\n    intros [a b]; cbn.\n    now rewrite G.linv_unit, H.linv_unit.\n  Qed.\n\nEnd group_direct_prod.\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/BasicAlgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7386856937025856}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\nClassical logic is somewhat surprising!\nProve that given two arbitrary propositions\na and b, either a implies b or the converse *)\n\nLemma CL_is_wrong_and_boolrefl_is_nice (A B : (*D*)bool(*D*)) :\n  (A -> B) \\/ (B -> A).\n(*A*)Proof. case: A; case: B; by [left | right]. Qed.\n\n(** Enrico is a lazy student.  When asked to reverse and filter\na list he comes up with the following ugly code. *)\n\nFixpoint filtrev T (p : pred T) (acc : seq T) (l : seq T) : seq T :=\n  if l is x :: xs then\n    if p x then filtrev p (x :: acc) xs\n           else filtrev p       acc  xs\n  else acc.\n\n(**  The teacher asks him to prove that his ugly code is equivalent\n to the nicer code [[seq x <- rev l | p x]] he could have written\nby reusing the seq library.\n\nSuch proof is not trivial:\n  - [filtrev] has an accumulator, [rev] (at least apparently)\n    does not.\n  - which is the invariant linking the accumulator [acc] and [p]\n    in the code of [filtrev]?  Depending on how you expose\n    the accumulator on the right hand side of the goal,\n    such invariant may need to be taken into account by the induction.\n\nRelevant keywords for [Search] are: rev cons cat filter rcons\nHint: it is perfectly fine to state intermediate lemmas\n*)\n\nLemma filterrev_ok T p (l : seq T) :\n  filtrev p [::] l = [seq x <- rev l | p x ].\nProof.\n(*X*)rewrite -[RHS]cats0; elim: l [::] => [|x l ihl] l' //=.\n(*X*)by case: ifP => px; rewrite ihl rev_cons filter_rcons ?px ?cat_rcons.\n(*A*)Qed.\n\n(** Prove the equivalence of these two sums.\n    E.g. (n=8)\n<<\n    1 + 3 + 5 + 7 = 7-0 + 7-2 + 7-4 + 7-6\n>>\n*)\nLemma sum_odd n :\n  ~~ odd n -> \\sum_(i < n | odd i) i = \\sum_(i < n | ~~ odd i) (n.-1 - i).\nProof.\n(*X*)rewrite (reindex_inj rev_ord_inj) /= => /negPf n_oddF.\n(*X*)by apply: eq_big => i; rewrite odd_sub ?n_oddF //; case: n i {n_oddF}.\n(*A*)Qed.\n\n(** Even the Mathematical Components library misses some theorems,\n    for example the following one.\n\n    Would you help us improve the library with this lemma? \n\n    Hint: check out the theory of [iota]\n*)\n\nLemma big_nat_shift (T : Type) (op: T -> T -> T) (idx : T)\n  m c n (Pr : pred nat) (f : nat -> T):\n  \\big[op/idx]_(m + c <= i < n + c | Pr i) f i =\n  \\big[op/idx]_(m <= i < n | Pr (i + c)%N) f (i + c)%N.\n(*A*)Proof. by rewrite big_addn addnK. Qed.\n(**\n\nNow, some algebra.\n\n*)\nFrom mathcomp Require Import all_algebra.\nFrom mathcomp Require Import algC zmodp.\n\nSection AlgebraicHierarchy.\nSection GaussIntegers.\nImport GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n\n(** Big operations and [zmodType]. Now that [ring_scope] is open we are in\n    an algebraic setting.  Think about the meaning of [+] now, and find\n    the right injectivity lemma. *)\nLemma big_ord_shift1 (T : Type) (idx : T) (op : Monoid.com_law idx) n\n P F : \\big[op/idx]_(i < n.+2 | P i) F i =\n       \\big[op/idx]_(i < n.+2 | P (i + 1)) F (i + 1).\nProof.\n(*X*)apply: reindex_inj; apply: addIr.\n(*A*)Qed.\n\n(**\n\nWe remind what Gauss integer are and recall some theory about it.\n\n*)\nDefinition gaussInteger := [qualify a x | ('Re x \\in Cint) && ('Im x \\in Cint)].\nAxiom Cint_GI : forall (x : algC), x \\in Cint -> x \\is a gaussInteger.\nAxiom GI_subring : subring_closed gaussInteger.\n\nFact GI_key : pred_key gaussInteger. Proof. by []. Qed.\nCanonical GI_keyed := KeyedQualifier GI_key.\nCanonical GI_opprPred := OpprPred GI_subring.\nCanonical GI_addrPred := AddrPred GI_subring.\nCanonical GI_mulrPred := MulrPred GI_subring.\nCanonical GI_zmodPred := ZmodPred GI_subring.\nCanonical GI_semiringPred := SemiringPred GI_subring.\nCanonical GI_smulrPred := SmulrPred GI_subring.\nCanonical GI_subringPred := SubringPred GI_subring.\n\nRecord GI := GIof {algGI : algC; algGIP : algGI \\is a gaussInteger }.\nHint Resolve algGIP.\n\nCanonical GI_subType := [subType for algGI].\nDefinition GI_eqMixin := [eqMixin of GI by <:].\nCanonical GI_eqType := EqType GI GI_eqMixin.\nDefinition GI_choiceMixin := [choiceMixin of GI by <:].\nCanonical GI_choiceType := ChoiceType GI GI_choiceMixin.\nDefinition GI_countMixin := [countMixin of GI by <:].\nCanonical GI_countType := CountType GI GI_countMixin.\nDefinition GI_zmodMixin := [zmodMixin of GI by <:].\nCanonical GI_zmodType := ZmodType GI GI_zmodMixin.\nDefinition GI_ringMixin := [ringMixin of GI by <:].\nCanonical GI_ringType := RingType GI GI_ringMixin.\nDefinition GI_comRingMixin := [comRingMixin of GI by <:].\nCanonical GI_comRingType := ComRingType GI GI_comRingMixin.\n\nLemma conjGIE x : (x^* \\is a gaussInteger) = (x \\is a gaussInteger).\nProof. by rewrite ![_ \\is a _]qualifE algRe_conj algIm_conj rpredN. Qed.\n\nFact conjGI_subproof (x : GI) : (val x)^* \\is a gaussInteger.\nProof. by rewrite conjGIE. Qed.\n\nCanonical conjGI x := GIof (conjGI_subproof x).\n\nDefinition gaussNorm (x : algC) := x * x^*.\n\nAxiom gaussNormE : forall x, gaussNorm x = `|x| ^+ 2.\nAxiom gaussNormCnat : forall (x : GI), gaussNorm (val x) \\in Cnat.\n(**\n\nProve these two facts. (Hint: conjugation is a morphism)\n\n*)\nLemma gaussNorm1 : gaussNorm 1 = 1.\n(*A*)Proof. by rewrite /gaussNorm rmorph1 mulr1. Qed.\n\nLemma gaussNormM : {morph gaussNorm : x y / x * y}.\n(*A*)Proof. by move=> x y; rewrite /gaussNorm rmorphM mulrACA. Qed.\n(**\n\n** Question: Prove that GI euclidean for the stasm gaussNorm.\n\n - i.e. ∀ (a, b) ∈ GI × GI*, ∃ (q, r) ∈ GI² s.t. a = q b + r and φ(r) < φ(b)\n - Suggested strategy: sketch the proof on a paper first, don't let Coq\n   divert you from your proofsketch\n - We first sketch the \"paper proof\" here and then do it in Coq:\n  - take a / b = x + i y\n  - take u the closest integer to x, and v the closest integer to y\n  - satisfy the existential with q = u + i v and r = a - q b,\n    which are both Gauss integers.\n  - We want to show that |a - q b|² < |b|².\n  - It suffices to show |a / b - q|² < 1\n  - But |a / b - q|² = (u - x)² + (v - x)² ≤ ‌½² + ½² < 1\n - Now we give a Coq proof with holes, fill in the holes.\n*)\nLemma euclideanGI (a b : GI) : b != 0 ->\n  exists2 qr : GI * GI, a = qr.1 * b + qr.2\n                      & (gaussNorm (val qr.2) < gaussNorm (val b)).\nProof.\nmove=> b_neq0.\n\n(* Trivial preliminaries *)\nhave oneV2 : 1 = 2%:R^-1 + 2%:R^-1 :> algC.\n  by rewrite -mulr2n -[_ *+ 2]mulr_natr mulVf ?pnatr_eq0.\nhave V2ge0 : 0 <= 2%:R^-1 :> algC by (*a*)rewrite invr_ge0 ler0n.\nhave V2real : (2%:R^-1 : algC) \\is Num.real by (*a*)rewrite realE V2ge0.\n\n(* Closest integer to x, when x is real *)\npose approx (x : algC) : int :=\n  floorC x + (if `|x - (floorC x)%:~R| <= 2%:R^-1 then 0 else 1).\nhave approxP x : x \\is Creal -> `|x - (approx x)%:~R| <= 2%:R^-1.\n  rewrite /approx => x_real; have /andP [x_ge x_le] := floorC_itv x_real.\n  have [] // := @real_lerP _  `|_ - (floorC _)%:~R| _;\n    first by rewrite addr0.\n  rewrite [`|_ - (_ + 1)%:~R|]distrC !ger0_norm ?subr_ge0 //=;\n     last by rewrite ltrW.\n  move=> Dx1_gtV2; rewrite real_lerNgt ?rpredB // ?Creal_Cint ?Cint_int //.\n  apply/negP=> /ltr_add /(_ Dx1_gtV2); rewrite -oneV2 !addrA addrNK.\n  by rewrite [_ + 1]addrC rmorphD /= addrK ltrr.\nhave approxP2 x (_ : x \\is Creal) : `|x - (approx x)%:~R| ^+ 2 < 2%:R^-1.\n  rewrite (@ler_lt_trans _ (2%:R^-1 ^+ 2)) // ?ler_expn2r ?qualifE ?approxP //.\n  by rewrite exprVn -natrX ltf_pinv ?qualifE ?ltr_nat ?ltr0n.\n\n(* Proper proof *)\npose u := 'Re (val a / val b); pose v := 'Im (val a / val b).\nhave qGI : (approx u)%:~R + algCi * (approx v)%:~R \\is a gaussInteger.\n  (* Hint: use qualifE, alg*_rect and lemmas about Creal, Cint and _%:~R *)\n  (*a*)by rewrite qualifE /= algRe_rect ?algIm_rect // ?Creal_Cint ?Cint_int.\npose q := GIof qGI.\nexists (q, a - q * b); first by rewrite addrC addrNK.\nrewrite !gaussNormE /=.\nrewrite -(@ltr_pmul2r _ (`|val b| ^-2)) ?invr_gt0 ?exprn_gt0 ?normr_gt0 //.\nrewrite mulfV ?expf_eq0 /= ?normr_eq0 // -exprVn -exprMn.\nrewrite -normfV -normrM mulrBl mulfK //.\nsuff uvP : `|u - (approx u)%:~R + 'i * (v - (approx v)%:~R)| ^+ 2 < 1.\n  (* Hint: use algCrect and algebraic transformations *)\n  (*a*)by rewrite [X in X - _]algCrect opprD addrACA -mulrBr.\nset Du := _ - _; set Dv := _ - _.\nhave /andP [DuReal DvReal] : (Du \\is Creal) && (Dv \\is Creal).\n(* Hint: use rpred*, Creal_*, normC2_rect, ream_normK and approxP2 *)\n(*a*)  by rewrite ?rpredB ?Creal_Re ?Creal_Im ?Creal_Cint ?Cint_int.\n(*X*)rewrite normC2_rect // oneV2.\n(*X*)by rewrite ltr_add // -real_normK // approxP2 ?Creal_Re ?Creal_Im.\n(*A*)Qed.\n\nEnd GaussIntegers.\nEnd AlgebraicHierarchy.\n\nSection PolynomialsLagrange.\n\nOpen Scope ring_scope.\nImport GRing.Theory Num.Theory.\n(**\n\n* Definition and properties of Lagrange polynomials.\n\nProve only one of the following lemmas\n*)\nVariables (n : nat) (x : algC ^ n).\n\nDefinition lagrange (i : 'I_n) : {poly algC} :=\n  let p := \\prod_(j < n | j != i) ('X - (x j)%:P) in (p.[x i]^-1)%:P * p.\n\nHypothesis n_gt0 : (0 < n)%N.\nHypothesis x_inj : injective x.\n\nLemma lagrangeE (i j : 'I_n) : (lagrange i).[x j] = (i == j)%:R.\nProof using x_inj.\n(*X*)rewrite /lagrange hornerM hornerC; set p := (\\prod_(_ < _ | _) _).\n(*X*)have [<-|neq_ij] /= := altP eqP.\n(*X*)  rewrite mulVf // horner_prod; apply/prodf_neq0 => k neq_ki.\n(*X*)  by rewrite hornerXsubC subr_eq0 inj_eq // eq_sym.\n(*X*)rewrite [X in _ * X]horner_prod (bigD1 j) 1?eq_sym //=.\n(*X*)by rewrite hornerXsubC subrr mul0r mulr0.\n(*A*)Qed.\n\n\nLemma size_lagrange i : size (lagrange i) = n.\nProof using n_gt0 x_inj.\n(*X*)rewrite size_Cmul; last first.\n(*X*)  suff : (lagrange i).[x i] != 0 by rewrite hornerE mulf_eq0 => /norP [].\n(*X*)  by rewrite lagrangeE ?eqxx ?oner_eq0.\n(*X*)rewrite size_prod /=; last first.\n(*X*)  by move=> j neq_ji; rewrite polyXsubC_eq0.\n(*X*)rewrite (eq_bigr (fun=> (2 * 1)%N)); last first.\n(*X*)  by move=> j neq_ji; rewrite size_XsubC.\n(*X*)rewrite -big_distrr /= sum1_card cardC1 card_ord /=.\n(*X*)by case: (n) {i} n_gt0 => ?; rewrite mul2n -addnn -addSn addnK.\n(*A*)Qed.\n\nLemma lagrange_free (lambda : 'rV_n):\n  \\sum_i (lambda 0 i)%:P * lagrange i = 0 -> lambda = 0.\nProof using x_inj.\n(*X*)move=> eq_l; apply/rowP=> i; rewrite mxE.\n(*X*)have /(congr1 (fun p => p.[x i])) := eq_l.\n(*X*)rewrite horner_sum horner0 (bigD1 i) //= hornerE lagrangeE // eqxx mulr1.\n(*X*)rewrite big1 ?addr0 // => j neq_ji.\n(*X*)by rewrite hornerM lagrangeE // (negPf neq_ji) mulr0.\n(*A*)Qed.\n\nLemma lagrange_gen (p : {poly algC}) :\n   (size p <= n)%N -> p = \\sum_i p.[x i]%:P * lagrange i.\nProof using n_gt0 x_inj.\n(*X*)(* fancy proof using marix spaces *)\n(*X*)move=> sp_le_n; pose L := \\matrix_(i < n) @poly_rV _ n (lagrange i).\n(*X*)suff /(congr1 rVpoly) : poly_rV p = \\row_i p.[x i] *m L.\n(*X*)  rewrite poly_rV_K // => {1}->; rewrite mulmx_sum_row raddf_sum /=.\n(*X*)  apply: eq_bigr=> i _; rewrite linearZ /= mxE mul_polyC.\n(*X*)  by rewrite rowK poly_rV_K ?size_lagrange.\n(*X*)have /submxP [u puL]: (poly_rV p <= L)%MS.\n(*X*)  rewrite (submx_trans (submx1 _)) // sub1mx row_full_unit -row_free_unit.\n(*X*)  rewrite -kermx_eq0; apply/rowV0P => v /sub_kermxP.\n(*X*)  move=> /(congr1 rVpoly); rewrite !raddf0 mulmx_sum_row raddf_sum /= => vL0.\n(*X*)  rewrite [v]lagrange_free // -[RHS]vL0; apply: eq_bigr => i _.\n(*X*)  by rewrite linearZ rowK mul_polyC /= poly_rV_K ?size_lagrange.\n(*X*)rewrite puL; congr (_ *m _); apply/rowP=> i; rewrite mxE.\n(*X*)have /(congr1 (fun v => (rVpoly v).[x i])) := puL.\n(*X*)rewrite poly_rV_K // mulmx_sum_row raddf_sum /=.\n(*X*)rewrite (bigD1 i) //= linearZ /= rowK poly_rV_K ?size_lagrange //.\n(*X*)rewrite 2!hornerE lagrangeE eqxx mulr1 horner_sum big1 ?addr0 //.\n(*X*)move=> j neq_ji; rewrite linearZ rowK /= ?poly_rV_K ?size_lagrange //.\n(*X*)by rewrite hornerZ lagrangeE (negPf neq_ji) mulr0.\n\n(*X*)Restart. (* shorter proof, direct *)\n\n(*X*)move=> sp_le_n; apply/eqP; rewrite -subr_eq0; apply: contraTT isT.\n(*X*)move=> /max_poly_roots - /(_ [seq x i | i <- enum 'I_n]).\n(*X*)rewrite size_map size_enum_ord map_inj_uniq ?enum_uniq //.\n(*X*)rewrite [(n < _)%N]negbTE; [apply=>//|rewrite -leqNgt].\n(*X*)  apply/allP=> /= _ /imageP [/= i _ ->].\n(*X*)  rewrite rootE !hornerE horner_sum (bigD1 i) //=.\n(*X*)  rewrite hornerM hornerC lagrangeE // eqxx mulr1 opprD addNKr.\n(*X*)  rewrite big1 ?oppr0 // => j neq_ji.\n(*X*)  by rewrite hornerM lagrangeE // (negPf neq_ji) mulr0.\n(*X*)rewrite (leq_trans (size_add _ _)) // size_opp geq_max sp_le_n /=.\n(*X*)rewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP=> j _.\n(*X*)rewrite (leq_trans (size_mul_leq _ _)) // size_polyC size_lagrange //.\n(*X*)by move: (n) n_gt0 (_ == _) => [] // ? _ [].\n(*A*)Qed.\n\nEnd PolynomialsLagrange.\n\nSection PolynomialsTaylor.\n(**\nTaylor formula for polynomials\n\n*)\nImport GRing.Theory.\nOpen Scope ring_scope.\nVariable R: idomainType.\n\n(*X*)(* This is the strongest statement I could prove *)\n(*X*)(* uses max_poly_roots and nderiv_taylor *)\n(*X*)Lemma Taylor_formula_strong (p : {poly R}) (x : R) (rs : seq R) :\n(*X*)  (size p <= size rs)%N -> uniq rs ->\n(*X*)  p = \\sum_ (i < size p) p^`N(i).[x] *: ('X - x%:P) ^+ i.\n(*X*)Proof.\n(*X*)move=> sprs /max_poly_roots prs; apply/eqP; rewrite -subr_eq0.\n(*X*)apply: contraTT isT => /prs; rewrite [(_ < _)%N]negbTE; [apply|rewrite -leqNgt].\n(*X*)  apply/allP=> y y_rs; rewrite rootE hornerD hornerN subr_eq0; apply/eqP.\n(*X*)  rewrite -[y in X in p.[X]](addrNK x) [_ + x]addrC.\n(*X*)  rewrite nderiv_taylor; last exact: mulrC.\n(*X*)  by rewrite horner_sum; apply: eq_bigr=> i _; rewrite !(hornerE, horner_exp).\n(*X*)rewrite (leq_trans (size_add _ _)) // geq_max sprs /= size_opp.\n(*X*)rewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP=> i _.\n(*X*)rewrite (leq_trans (size_scale_leq _ _)) //.\n(*X*)by rewrite size_exp_XsubC (leq_trans _ sprs).\n(*X*)Qed.\n\n(*X*)Lemma natr_injP (D : idomainType) :\n(*X*)  (forall n, (n%:R == 0 :> D) = (n == 0)%N) <-> injective (@GRing.natmul D 1).\n(*X*)Proof.\n(*X*)split=> [natr_eq0 i j|natr_inj n]; last by rewrite -(inj_eq natr_inj).\n(*X*)wlog: i j / (j <= i)%N => [hwlog|].\n(*X*)  by have [/hwlog//|/ltnW/hwlog/(_ (esym _))/esym] := leqP j i.\n(*X*)by move=> /subnK<- /eqP; rewrite -subr_eq0 natrD addrK natr_eq0 => /eqP->.\n(*X*)Qed.\n\n(*X*) (* This is the statement we ask the students to prove *)\nHypothesis charR_eq0 : [char R] =i pred0.\nLemma Taylor_formula (p : {poly R}) (x : R) :\n  p = \\sum_ (i < size p) p^`N(i).[x] *: ('X - x%:P) ^+ i.\n(*X*)Proof. (* Proof using the stronger version *)\n(*X*)apply: (@Taylor_formula_strong _ _ [seq i%:R | i <- iota 0 (size p)]).\n(*X*)  by rewrite size_map size_iota.\n(*X*)by rewrite map_inj_uniq ?iota_uniq //; apply/natr_injP/charf0P.\n(*X*)\n(*X*)Restart. (* Proof for the students *)\n(*X*)\nProof.\nwlog: p x / x = 0 => [hwlog|->]; rewrite ?subr0; last first.\n(*X*)  transitivity (\\poly_(i < size p) p^`N(i).[0]);\n(*X*)    last by rewrite poly_def.\n(*X*)  apply/polyP=> /= i; rewrite coef_poly.\n(*X*)  have [i_small|i_big]:= ltnP; last by rewrite nth_default.\n  (*a*)by rewrite horner_coef0 coef_nderivn addn0 binn mulr1n.\nrewrite -[LHS](comp_polyXaddC_K _ x) -[RHS](comp_polyXaddC_K _ x).\ncongr (_ \\Po _); rewrite [LHS](hwlog _ 0 erefl) ?subr0 [RHS]raddf_sum /=.\nrewrite size_comp_poly2; last first.\n  by rewrite -[x%:P as X in 'X + X]opprK -[- x%:P]raddfN /= size_XsubC.\n(*X*)apply: eq_bigr => i _.\n(*X*)have nderivn_compXD q (a : R) j :\n(*X*)  (q \\Po ('X + a%:P))^`N(j) = q^`N(j) \\Po ('X + a%:P).\n       have /charf0P/natr_injP natr_inj := charR_eq0.\n(*X*)  apply: (@mulfI _ j`!%:R%:P).\n(*X*)     rewrite polyC_eq0; have/charf0P -> := charR_eq0.\n     (*a*)by rewrite -lt0n fact_gt0.\n(*X*)  rewrite !mul_polyC !scaler_nat -rmorphMn /= -!nderivn_def.\n  (*a*)by elim: j => //= j ->; rewrite deriv_comp !derivE addr0 mulr1.\n(*X*)rewrite nderivn_compXD horner_comp !hornerE // linearZ rmorphX /=.\n(*X*)rewrite -['X - x%:P]comp_polyX -[x%:P as X in 'X + X]opprK.\n(*X*)by rewrite -[- x%:P]raddfN /= comp_polyXaddC_K.\n(*A*)Qed.\n\nEnd PolynomialsTaylor.\n\nSection LinearAlgebra.\nImport GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n(**\n\n* Endomorphisms u such that Ker u ⊕ Im u = E.\n\nThe endomorphisms of a space E of finite dimension n, such that u o v\n= 0 and v + u is invertible are exactly the endomorphisms such that\nKer u ⊕ Im u = E.\n\n - Assume u o v = 0 and v + u is invertible,\n  - we have rank (v + u) = n\n  - we have rank v + rank u = n and we have Im v ⊂ Ker u\n  - Hence we have Im v = Ker u\n  - We deduce that Ker u ⊕ Im u = Im v ⊕ Im u = E\n\n*)\nVariables (F : fieldType) (n' : nat).\nLet n := n'.+1.\n\nLemma ex_6_13 (u : 'M[F]_n):\n  reflect (exists2 v : 'M_n, v * u = 0 & v + u \\is a GRing.unit)\n          ((kermx u + u == 1)%MS && mxdirect (kermx u + u)).\nProof.\n(* Hint: use mxrank* lemmas and search on addsmx, submx and eqmx\nsometimes. Don't forget about mxdirect_addsP and sub_kermxP. *)\napply: (iffP idP) => [|[v vMu vDu]]; last first.\n  have rkvDu: \\rank (v + u)%R = n by (*a*)rewrite mxrank_unit.\n  have /eqP rkvDrku : (\\rank v + \\rank u)%N == n.\n    by rewrite eqn_leq; (*a*)rewrite mulmx0_rank_max //= -{1}rkvDu mxrank_add.\n  have sub_v_ku : (v <= kermx u)%MS by (*a*)apply/sub_kermxP.\n  have /eqmxP/eqmx_sym eq_vu: (v == kermx u)%MS.\n    rewrite -(geq_leqif (mxrank_leqif_eq _)) //.\n(*X*)    rewrite -(leq_add2r (\\rank u)) rkvDrku.\n    (*a*)by rewrite mxrank_ker subnK // rank_leq_row.\n  rewrite submx1 sub1mx -col_leq_rank mxdirectEgeq /=.\n  (* use adds_eqmx to lift eq_vu to a sum *)\n(*X*)  rewrite eq_vu (adds_eqmx eq_vu (eqmx_refl _)).\n  (* Warning: - (u + v)%R  is a sum of matrices\n              - (u + v)%MS is a sum of spaces\n     use addmx_sub_adds and mxrankS\n     to compare the rank (u + v) with dim (Im u + Im v) *)\n(*X*)  have /mxrankS leq_rk := addmx_sub_adds (submx_refl v) (submx_refl u).\n  (* finish using hypothesis *)\n  (*a*)by rewrite !(leq_trans _ leq_rk) //= ?rkvDu ?rkvDrku.\nmove=> /andP [/eqmxP kuDu_eq1 /mxdirect_addsP kvDu_direct].\npose v := proj_mx (kermx u) u; exists v.\n  (*a*)by apply/sub_kermxP; rewrite -[X in (X <= _)%MS]mul1r proj_mx_sub.\nrewrite -row_free_unit -kermx_eq0.\napply/negP => /negP /rowV0Pn [x /sub_kermxP]; rewrite mulmxDr.\nmove=> /(canRL (addrK _)); rewrite sub0r => eq_xv_Nxu.\napply/negP; rewrite negbK; apply/eqP.\nhave : (x *m v <= kermx u :&: u)%MS.\n(* Hint: use sub_*, proj_mx*, eqmx_*, mxdirect_addsP, *)\n  (*a*)by rewrite sub_capmx proj_mx_sub eq_xv_Nxu eqmx_opp submxMl.\n(*X*)rewrite kvDu_direct ?submx0 // => /eqP xv_eq0.\n(*X*)move/eqP : eq_xv_Nxu; rewrite xv_eq0 eq_sym oppr_eq0 => /eqP.\n(*X*)by move=> /sub_kermxP x_in_keru; move: xv_eq0; rewrite proj_mx_id.\n(*A*)Qed.\n\nEnd LinearAlgebra.\n\n(*X*)(*\n(*X*)*** Local Variables: ***\n(*X*)*** coq-prog-args: (\"-emacs-U\" \"-R\" \"/Users/lrg/coq/math-comp/mathcomp\" \"mathcomp\" \"-I\" \"/Users/lrg/coq/math-comp/mathcomp\" ) ***\n(*X*)*** End: ***\n(*X*)*)\n", "meta": {"author": "gares", "repo": "COQWS17", "sha": "babcf965035f24fa00bbe69497361e9c8144ae97", "save_path": "github-repos/coq/gares-COQWS17", "path": "github-repos/coq/gares-COQWS17/COQWS17-babcf965035f24fa00bbe69497361e9c8144ae97/exam.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.877476793890012, "lm_q1q2_score": 0.7386824699646903}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\n\nSection Repeat.\n  Context {A : Type}.\n\n  Fixpoint rep (f : A -> A) (n : nat) (z : A) : A :=\n    match n with\n    | O => z\n    | S m => f (rep f m z)\n    end.\n\n  Theorem rep_l : forall f n z,\n      f (rep f n z) = rep f (S n) z.\n  Proof. reflexivity. Qed.\n\n  Theorem rep_r  : forall f n z,\n      rep f n (f z) = rep f (S n) z.\n  Proof.\n    induction n; intros.\n    - reflexivity.\n    - simpl rep at 1. rewrite IHn. easy.\n  Qed.\n\n  Theorem rep_split : forall f n m z,\n      rep f n (rep f m z) = rep f (n + m) z.\n  Proof.\n    intros.\n    induction m.\n    - simpl.\n      rewrite Nat.add_0_r. reflexivity.\n    - simpl; rewrite rep_r. simpl; rewrite IHm.\n      rewrite rep_l.\n      f_equal. omega.\n  Qed.\nEnd Repeat.\n\nSection Invertible.\n  Context {A : Type} (f g : A -> A).\n  Hypothesis HI: forall x, g (f x) = x.\n\n  Lemma rep_inv1_l : forall n z,\n      g (rep f (S n) z) = rep f n z.\n  Proof.\n    intros.\n    simpl. rewrite HI.\n    easy.\n  Qed.\n\n  Lemma rep_inv1_r : forall n z,\n      rep g (S n) (f z) = rep g n z.\n  Proof.\n    intros. induction n.\n    - simpl. auto.\n    - remember (S n) as n'; simpl; subst.\n      rewrite IHn. apply rep_l.\n  Qed.\n\n  Theorem rep_inv_l : forall n m z,\n      n >= m -> rep g m (rep f n z) = rep f (n - m) z.\n  Proof.\n    intros n m. revert n. induction m; intros.\n    - simpl. rewrite Nat.sub_0_r. reflexivity.\n    - simpl. rewrite IHm by omega.\n      destruct (n - m) as [|x] eqn:Hn; try omega.\n      rewrite rep_inv1_l by auto.\n      replace (n - S m) with x by omega.\n      reflexivity.\n  Qed.\n\n  Theorem rep_inv_r : forall n m z,\n      m >= n -> rep g m (rep f n z) = rep g (m - n) z.\n  Proof.\n    intros n m. induction n; intros.\n    - simpl. rewrite Nat.sub_0_r.\n      reflexivity.\n    - rewrite <- rep_r, IHn by omega.\n      destruct (m - n) as [|x] eqn:Hm; try omega.\n      rewrite rep_inv1_r by auto.\n      replace (m - S n) with x by omega.\n      reflexivity.\n  Qed.\nEnd Invertible.\n\nSection Preserves.\n  Context {A : Type} (P : A -> Prop) (f : A -> A).\n  Hypothesis HP : forall x, P x -> P (f x).\n\n  Theorem rep_preserves : forall z n,\n      P z -> P (rep f n z).\n  Proof.\n    intros z n Pz; revert z Pz.\n    induction n; auto; intros.\n    simpl. auto.\n  Qed.\nEnd Preserves.\n\nSection Map.\n  Context {A : Type}.\n\n  Variable f : A -> A.\n\n  Lemma rep_map_cons : forall n a l,\n      rep (map f) n (a :: l) = rep f n a :: rep (map f) n l.\n  Proof.\n    induction n; intros a l; [reflexivity|].\n    cbn. rewrite IHn. cbn. reflexivity.\n  Qed.\n\n  Theorem rep_map : forall n l,\n      rep (map f) n l = map (rep f n) l.\n  Proof.\n    induction l.\n    - cbn. apply rep_preserves; [|reflexivity].\n      intros; subst; reflexivity.\n    - cbn. rewrite <- IHl.\n      apply rep_map_cons.\n  Qed.\nEnd Map.\n", "meta": {"author": "jbaum98", "repo": "verified_bzip2", "sha": "d8ffd2e181f4951f588cce596b68fb2d0ebe7964", "save_path": "github-repos/coq/jbaum98-verified_bzip2", "path": "github-repos/coq/jbaum98-verified_bzip2/verified_bzip2-d8ffd2e181f4951f588cce596b68fb2d0ebe7964/theories/BWT/Lib/Repeat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7386824582193436}}
{"text": "(** * Coinduction: Infinite Data and Proofs *)\n(* CIS670, Homework assignments 6 and 7 *)\n\n(* This material builds on:\n   - sections 7.1 from the tutorial by Giménez and Castéran\n   - sections 5.1-5.2 from the CPDT book by Adam Chlipala\n*)\n\nRequire Import Bool.\nRequire Import List.\n\nRequire Import CpdtTactics.\n\nSet Implicit Arguments.\n\n(* ------------------------------------------------------------ *)\n(** ** Computing with Infinite Data *)\n\n(** The most basic type of infinite data is infinite lists, usually\n    known as _streams_ *)\n\nCoInductive stream (A : Type) : Type :=\n  | Cons : A -> stream A -> stream A.\n\n(** If we want _both_ finite and infinite lists, then we can also keep\n    the cons *)\n\nCoInductive llist (A: Type) : Type :=\n|  LNil : llist A\n|  LCons : A -> llist A -> llist A.\n\n(** Exercise (easy): define the coinductive types representing the\n    following 3 infinite data structures: *)\n\n(* 1. infinite binary trees *)\nCoInductive ibtree (A : Type) : Type :=\n  | IBNode : A -> ibtree A -> ibtree A -> ibtree A.\n\n(* 2. infinitely branching infinite trees\n      (i.e. infinitely wide and infinitely deep) *)\nCoInductive itree (A : Type) : Type :=\n  | INode : A -> (nat -> itree A) -> itree A.\n\n(* 3. finitely and infinitely branching infinite trees\n      (i.e. finitely or infinitely wide and infinitely deep *)\nCoInductive iftree (A : Type) : Type :=\n  | IINode : A -> llist (iftree A) -> iftree A.\n\n(** Pattern matching on coinductive values works as usual *)\n\nDefinition head (A:Type) (s : stream A) :=\n  match s with\n  | Cons a s' => a\n  end.\n\nDefinition tail (A : Type)(s : stream A) :=\n  match s with\n  | Cons a s' => s'\n  end.\n\n(* Exercise (easy): Using the functions head and tail, define a\n   recursive function which takes the n-th element of an infinite\n   stream. *)\nFixpoint nth (A : Type) (n : nat) (s : stream A) : A :=\n  match n with\n  | O => head s\n  | S n' => nth n' (tail s)\n  end.\n\n(* Infinite objects are defined using the CoFixpoint command *)\n\nCoFixpoint repeat (A : Type) (a : A) : stream A := Cons a (repeat a).\n\n(** Note: whereas recursive definitions (fixpoints) were necessary to\n    _use_ values of recursive inductive types effectively, we need\n    co-recursive definitions (co-fixpoints) to _build_ (infinite)\n    values of co-inductive types *)\n\n(** Every CoFixpoint has to return a coinductive type (in the same way\n    every Fixpoint has to take and break up an inductive argument). *)\n\n(*\nCoFixpoint to_bool (x : stream nat) : bool := to_bool x.\n\nError:\nRecursive definition of to_bool is ill-formed.\nIn environment\nto_bool : stream nat -> bool\nx : stream nat\nThe codomain is \"bool\"\nwhich should be a coinductive type.\nRecursive definition is: \"fun x : stream nat => to_bool x\".\n*)\n\n(** Co-inductive values can be arguments to recursive functions.\n    However, there also needs to be an inductive argument in order to\n    convince Coq that the function is terminating. We can use this to\n    write a function that computes the finite approximation of a\n    stream: *)\n\nFixpoint approx A (n : nat) (s : stream A) {struct n} : list A :=\n  match n with\n    | O => nil\n    | S n' =>\n      match s with\n        | Cons h t => h :: approx n' t\n      end\n  end.\n\nDefinition ones := repeat 1.\n\nEval simpl in approx 10 ones.\n\n(** We can of course also define [ones] directly, without using\n    [iterate] *)\n\nCoFixpoint ones' : stream nat := Cons 1 ones'.\n\nEval simpl in approx 10 ones'.\n\n(** In order to prevent non-termination, co-fixpoints are evaluated\n    lazily. They are unfolded _only_ when they appear as the argument\n    of a match expression. We can check this using Eval. *)\n\nEval simpl in (repeat 4).\n\nEval simpl in (head (repeat 4)).\n\n(** Here are three useful co-recursive functions on streams: *)\n\nCoFixpoint iterate (A : Type) (f : A -> A) (a : A) : stream A :=\n  Cons a (iterate f (f a)).\n\nCoFixpoint map (A B : Type) (f : A -> B) (s : stream A) : stream B :=\n  match s with\n  | Cons a tl => Cons (f a) (map f tl)\n  end.\n\nCoFixpoint interleave (A : Type) (s1 s2 : stream A) : stream A :=\n  match s1, s2 with\n  | Cons n1 s1', Cons n2 s2' => Cons n1 (Cons n2 (interleave s1' s2'))\n  end.\n\n(** Using [iterate] we can define the stream of natural numbers: *)\n\nDefinition nats : stream nat := iterate S 0.\nEval simpl in approx 10 nats.\n\n(* We can of course also define nats more directly: *)\nCoFixpoint nats_from_n (n : nat) : stream nat :=\n  Cons n (nats_from_n (S n)).\nDefinition nats' := nats_from_n 0.\n\nEval simpl in approx 10 nats.\n\n(** We can define a stream that alternates between [true] and [false]\n    using a mutual co-fixpoint (there are simpler ways, though). *)\n\nCoFixpoint trues_falses : stream bool := Cons true  falses_trues\n      with falses_trues : stream bool := Cons false trues_falses.\n\n(* Exercise (easy): Find two more ways for constructing the stream\n   which infinitely alternates the values true and false. *)\nDefinition trues_falses' : stream bool := iterate negb true.\nDefinition trues_falses'' : stream bool := interleave (repeat true) (repeat false).\n\n(* Not every co-fixpoint is accepted by Coq, though: there are\n   important restrictions that are dual to the restrictions on the use\n   of inductive types. Fixpoints _consume_ values of inductive types,\n   with restrictions on which _arguments_ may be passed in recursive\n   calls. Dually, co-fixpoints _produce_ values of co-inductive types,\n   with restrictions on what may be done with the _results_ of\n   co-recursive calls. *)\n\n(* Coq enforces that every co-recursive call must be guarded by a\n   constructor; that is, every co-recursive call must be a direct\n   argument to a constructor of the co-inductive type we are\n   generating. For instance, the following co-fixpoint does not pass\n   Coq's guardedness condition:\n\nCoFixpoint looper : stream nat := looper.\n\n<<\nError:\nRecursive definition of looper is ill-formed.\nIn environment\nlooper : stream nat\n\nunguarded recursive call in \"looper\"\n>> *)\n\n(* It is a good thing that this guardedness condition is enforced. If\n   the definition of [looper] were accepted, our [approx] function\n   would run forever when passed [looper], and we would have fallen\n   into inconsistency. *)\n\n(* Many other standard functions on lazy data structures (like [map],\n   [iterate] and [iterate] above) can be implemented easily in Coq.\n   Some, others like [filter], cannot be implemented.  (Why?) *)\n\n(* ------------------------------------------------------------ *)\n(** ** Finite Proofs about Infinite Objects *)\n\n(* We saw that we can define recursive functions on infinite (or\n   potentially infinite) objects -- e.g., approx.  We can also use the\n   standard Inductive machinery to define (some) useful properties of\n   potentially infinite objects. *)\n\nInductive finite A : llist A -> Prop :=\n| fin_LNil : finite (LNil A)\n| fin_LCons : forall l x, finite l -> finite (LCons x l).\n\n(* What about defining a similar predicate [infinite]? *)\n\n(* ------------------------------------------------------------ *)\n(** ** Infinite Proofs *)\n\n(** Suppose that we wanted to prove formally that the streams [nats]\n    and [nats'] from above are equivalent. The naive way to do this is\n    to state it as the following equality: *)\n\nTheorem nats_eq : nats = nats'.\nAbort.\n\n(** However, faced with the initial subgoal, it is not at all clear\n    how this theorem can be proved.  In fact, it is unprovable. The\n    [eq] predicate that we use is fundamentally limited to equalities\n    that can be demonstrated by finite arguments. All we can prove\n    this way is that any finite approximation of [nats] and [nats']\n    are equal. *)\n\n(* First try: *)\nLemma approx_nats_eq : forall k,\n  approx k nats = approx k nats'.\nProof. induction k; intros. reflexivity. simpl. Abort.\n\n(** For this we need to work we need to first generalize the induction\n    hypothesis and consider increasing streams of naturals starting\n    at any natural number. *)\n\nLemma approx_nats_eq_helper : forall k n,\n  approx k (iterate S n) = approx k (nats_from_n n).\nProof. induction k; crush. Qed.\n\nLemma approx_nats_eq : forall k,\n  approx k nats = approx k nats'.\nProof. intros. eapply approx_nats_eq_helper. Qed.\n\n(** In order to deal with interesting properties of infinite objects,\n    it is necessary to construct infinite proofs. What we need for\n    that is a _co-inductive proposition_.  That is, we want to define\n    a proposition whose _proofs_ may be infinite (subject to the\n    guardedness condition, of course). *)\n\nCoInductive stream_eq (A : Type) : stream A -> stream A -> Prop :=\n| Stream_eq : forall (h : A) t1 t2,\n        stream_eq t1 t2\n     -> stream_eq (Cons h t1) (Cons h t2).\n\n(** We say that two streams are equal if and only if they have the\n    same heads and their tails are equal.  We use normal\n    finite/syntactic equality for the heads, and we refer to our new\n    equality (co-)recursively for the tails. *)\n\n(** In order to construct infinite proof terms we need to use a\n    co-fixpoint, in the same way as we did for constructing infinite\n    program terms. While in programming mode we used [CoFixpoint]; in\n    tactic mode we can use the related [cofix] tactic for building\n    co-fixpoints. *)\n\n(** Before attacking the slightly harder problem of proving [nats] and\n    [nats'] in the [stream_eq] relation, we first try to prove that\n    [ones] and [ones'] are in [stream_eq]. We start by doing this\n    directly using the [cofix] tactic. *)\n\nTheorem ones_eq : stream_eq ones ones'.\n  cofix.\n  assumption. (* \"proof completed\" *)\n(* Qed. --> Unguarded recursive call in \"ones_eq\" *)\n\n(** The same guardedness condition applies to our co-inductive proofs\n    as to our co-inductive data structures. We should be grateful that\n    this proof is rejected, because, if it were not, the same proof\n    structure could be used to prove any co-inductive theorem\n    vacuously, by direct appeal to itself! *)\n\n(** Looking at the proof term Coq generates from the proof script\n    above, we see that the problem is that we are violating the\n    guardedness condition. *)\n\nShow Proof.\n(** (cofix ones_eq  : stream_eq ones ones' := ones_eq) *)\n\n(** During our proofs, Coq can help us check whether we have yet gone\n    wrong in this way. We can run the command [Guarded] in any\n    context to see if it is possible to finish the proof in a way that\n    will yield a properly guarded proof term.\n\n    Running [Guarded] here gives us the same error message that we got\n    when we tried to run [Qed]. In larger proofs, [Guarded] can be\n    helpful in detecting problems _before_ we think we are ready to\n    run [Qed]. *)\n\nRestart.\n\n(** We need to start the co-induction by applying [stream_eq]'s\n    constructor. To do that, we need to know that both arguments to\n    the predicate are [Cons]es. Informally, this is trivial, but\n    [simpl] is not able to help us, because co-fixpoint have to be\n    evaluated lazily. *)\n\n  cofix.\n  simpl. (* does nothing *)\n \nAbort.\n\n(** It turns out that the simplest way to get off the ground with this\n    proof is a commonly used hack. First, we need to define an\n    identity function that seems pointless on first glance. *)\n\nDefinition id_force A (s : stream A) : stream A :=\n  match s with\n    | Cons h t => Cons h t\n  end.\n\n(** Next, we need to prove a theorem that seems equally pointless. *)\n\nTheorem id_force_eq : forall A (s : stream A), s = id_force s.\nProof. destruct s; reflexivity. Qed.\n\n(** But, miraculously, this theorem turns out to be just what we needed. *)\n\nTheorem ones_eq : stream_eq ones ones'.\n  cofix.\n\n  (** We can use the theorem to rewrite the two streams. *)\n  rewrite (id_force_eq ones).\n  rewrite (id_force_eq ones').\n\n  (** Now [simpl] is able to reduce the streams. *)\n  simpl.\n\n  (** Why did this silly-looking trick help?  The answer has to do\n      with the constraints placed on Coq's evaluation rules by the\n      need for termination.  The [cofix]-related restriction that\n      foiled our first attempt at using [simpl] is dual to a\n      restriction for [fix].  In particular, an application of an\n      anonymous [fix] only reduces when the top-level structure of the\n      recursive argument is known.  Otherwise, we would be unfolding\n      the recursive definition ad infinitum.\n\n      Fixpoints only reduce when enough is known about the\n      _definitions_ of their arguments.  Dually, co-fixpoints only\n      reduce when enough is known about _how their results will be\n      used_.  In particular, a [cofix] is only expanded when it is the\n      discriminee of a [match].  Rewriting with our superficially\n      silly lemma wrapped new [match]es around the two [cofix]es,\n      triggering reduction.\n\n      If [cofix]es reduced haphazardly, it would be easy to run into\n      infinite loops in evaluation, since we are, after all, building\n      infinite objects. *)\n\n  (** Since we have exposed the [Cons] structure of each stream, we\n     can apply the constructor of [stream_eq]. *)\n\n  constructor.\n  assumption.\nQed.\n\n(** The example above shows that one can construct infinite proofs by\n    directly using [cofix], but there are two important problems with\n    this. First, it's hard to keep guardedness in mind when building\n    large proofs. Second, using [cofix] directly interacts very badly\n    with Coq's standard automation machinery. If we try to prove\n    [ones_eq] with automation we get an invalid proof. *)\n\nTheorem ones_eq' : stream_eq ones ones'.\n  cofix.\nProof.\n  cofix; auto.\n  (** [[\n  Guarded.\n  ]]\n  *)\nAbort.\n\n(** The standard [auto] machinery sees that our goal matches an\n    assumption and so applies that assumption, even though this\n    violates guardedness.  One usually starts a proof like this by\n    [destruct]ing some parameter and running a custom tactic to figure\n    out the first proof rule to apply for each case.  Alternatively,\n    there are tricks that can be played with \"hiding\" the co-inductive\n    hypothesis. *)\n\n(** However, we can devise a more principled solution to this problem\n    by looking at how the dual version of the problem is generally\n    solved for induction. It's equally hard to build inductive proofs\n    directly using [fix], but one almost never does that. Instead one\n    uses [fix] to proving general _induction principles_, and then\n    simply applies those principles. *)\n\n(** It turns out that we can usually do the same with _co-induction\n    principles_. Coq will not generate co-induction principles for us\n    though, so we need to define them by hand using co-fixpoints. *)\n\nSection stream_eq_coind1.\n  Variable A : Type.\n  Variable R : stream A -> stream A -> Prop.\n\n  (* This is mechanically extracted from the definition of stream_eq *)\n  Hypothesis H : forall s1 s2, R s1 s2 ->\n    exists h, exists t1, exists t2,\n      s1 = Cons h t1 /\\ s2 = Cons h t2 /\\ R t1 t2.\n\n  Theorem stream_eq_coind1 : forall s1 s2 : stream A,\n    R s1 s2 -> stream_eq s1 s2.\n  Proof. cofix. intros s1 s2 H0. apply H in H0.\n    destruct H0 as [h [t1 [t2 [H1 [H2 HR]]]]]. subst.\n    apply Stream_eq. apply stream_eq_coind1. assumption.\n  Qed.\nEnd stream_eq_coind1.\n\n(** We can now return to the proof of [ones_eq] *)\n\nTheorem ones_eq' : stream_eq ones ones'.\nProof.\n  apply stream_eq_coind1 with\n    (R := fun s1 s2 => s1 = ones /\\ s2 = ones'); [clear | tauto].\n    (* We'll return later on how to mechanically construct the R\n       from the statement of the theorem we're trying to prove.\n       In this case what we do here corresponds to the [remember]\n       we do before inducting on compound terms. *)\n  intros s1 s2 [? ?]. subst. repeat esplit.\n  rewrite (id_force_eq ones) at 1. simpl. reflexivity.\n  rewrite (id_force_eq ones') at 1. simpl. reflexivity.\nQed.\n\n(** The previous coinduction principle works, but it can be further\n    simplified to reach a more standard formulation (commonly called\n    Park's principle) that's easier to use in automated proofs. *)\n\nSection stream_eq_coind.\n  Variable A : Type.\n  Variable R : stream A -> stream A -> Prop.\n\n  (* We use head and tail instead of existential quantification *)\n  Hypothesis H1 : forall s1 s2,\n    R s1 s2 -> head s1 = head s2.\n  Hypothesis H2 : forall s1 s2,\n    R s1 s2 -> R (tail s1) (tail s2).\n\n  (* We show that H1 /\\ H2 is in equivalent the same as the previous H\n     using existential quantification *)\n  Lemma equiv : forall s1 s2, R s1 s2 ->\n    ((exists h, exists t1, exists t2,\n      s1 = Cons h t1 /\\ s2 = Cons h t2 /\\ R t1 t2)\n    <->\n    (head s1 = head s2 /\\ R (tail s1) (tail s2))).\n  Proof. clear; split; intros.\n    destruct H0 as [h [t1 [t2 [H1 [H2 H3]]]]].\n      subst. simpl. eauto.\n    destruct H0 as [H1 H2]. \n      exists (head s1). exists (tail s1). exists (tail s2).\n      destruct s1; destruct s2; simpl in *; subst; intuition.\n  Qed.\n\n  (* The proof of the coinduction principle is different; e.g. we\n     don't need to use the id_force_eq trick *)\n  Theorem stream_eq_coind : forall s1 s2 : stream A,\n    R s1 s2 -> stream_eq s1 s2.\n  Proof. cofix. intros s1 s2 H0. destruct s1. destruct s2.\n    pose proof (H1 H0). simpl in *. subst.\n    pose proof (H2 H0). simpl in *.\n    apply Stream_eq. apply stream_eq_coind. assumption.\n  Qed. (* Note: we didn't need to use the  *)\n\nEnd stream_eq_coind.\n\n(** We return again to the proof of [ones_eq] *)\n\nTheorem ones_eq'' : stream_eq ones ones'.\nProof.\n  apply stream_eq_coind with\n    (R := fun s1 s2 => s1 = ones /\\ s2 = ones'); crush. \nQed.\n\n(** This principle is better in terms of automation. Let's try to\n    use it to prove that [nats] and [nats'] are in [stream_eq].*)\n\nLemma nats_eq : stream_eq nats nats'.\nProof.\n  apply stream_eq_coind with (R := fun s1 s2 => s1 = nats /\\ s2 = nats');\n    crush.\n  (* At this point we get two goals that are wrong:\n     [iterate S 1 = nats] and [nats_from_n 1 = nats'] \n     The co-induction hypothesis is not general enough! *)\nAbort.\n\n(** In the same way we had to strengthen the inductive hypothesis in\n    [approx_nats_eq_helper], here we have to strengthen the\n    co-inductive hypothesis *)\n\nLemma nats_eq_helper : forall n,\n  stream_eq (iterate S n) (nats_from_n n).\nProof.\n  intro n. apply stream_eq_coind with\n    (R := fun s1 s2 => exists n, s1 = iterate S n /\\ s2 = nats_from_n n);\n      [crush | clear | eauto].\n    intros ? ? [n [? ?]]. exists (S n); crush.\nQed.\n\nTheorem nats_eq : stream_eq nats nats'.\nProof. apply nats_eq_helper. Qed.\n\n(** Recipe for constructing the \"bisimulation\" relation\n\nYou have a goal of the form:\nforall x1, ..., xn,\n  H1 -> ... -> Hm ->\n  P t1 ... tl\n\nWhere P is a coinductively defined predicate for which you've already\ndefined a coinduction principle P_coind. In order to call P_coind you\nneed to provide a predicate R. Here is a receipe to build R.\n\n** Step 1 (remember)\n\nReplace any argument tj that's not a variable from xs with a fresh\nvariable yj, universally quantify over yj at the top and add an\nadditional hypothesis Hj : yj = tk. Repeat this until the goal looks\nlike this:\n\nforall x1, ..., xn,\n  H1' -> ... -> Hm' ->\n  P y1 ... yl\n\n** Step 2 (linearize)\n\nIf a certain y appears twice in the proposition replace one of the\noccurrences with a fresh variable y' and add an equality of the form\ny = y' as a hypothesis.\n\n[You don't really need to change your goal to this, just construct\nthis proposition in your mind.]\n\n[This step corresponds to \"remember\"-ing compound terms before\n applying induction ]\n \n** Step 3 (conjunction + existentials)\n\nConstruct the conjunction of all premises H1' /\\ ... /\\ Hm',\nand existentially quantify over all xs that are not ys:\nexists x1', exists x2', ... exists xn', H1' /\\ ... /\\ Hm'\n\n** Step 4 (add a lambda on top)\n\nChose R to be (fun y1 ... yl => \n                 exists x1', exists x2', ... exists xn',\n\t           H1' /\\ ... /\\ Hm') and you're done.\n*)\n\n(* Exercise (medium): prove that ...*)\nTheorem map_iterate : forall (A:Type) (f:A->A) (x:A),\n                       stream_eq (iterate f (f x)) (map f (iterate f x)).\nProof.\n  cofix; intros.\n  apply (stream_eq_coind (fun s1 s2 : stream A => exists f : A -> A, exists x : A,\n       s1 = iterate f (f x) /\\ s2 = map f (iterate f x))). Guarded.\n  intros. inversion H as [fe [xe ?]]. inversion_clear H0.\n    rewrite H1; rewrite H2. reflexivity.\n  Guarded.\n  intros. inversion H as [fe [xe ?]]; inversion_clear H0. exists fe, (fe xe). rewrite H1, H2.\n    constructor; reflexivity.\n  Guarded.\n    exists f, x. constructor; reflexivity. Guarded.\nQed.\n\n(* Exercise: Define a co-inductive type Nat containing non-standard\nnatural numbers - this is, verifying\nexists m : Nat, forall n : Nat, n < m. *)\n\n(* Exercise: Prove that the equality of streams is an equivalence\n   relation using the co-induction principle.  (Hint: try reflexivity\n   first, then symmetry, then transitivity.) *)\n\nSection stream_eq_eqv.\n  Variable A : Type.\n\n  Theorem stream_eq_refl : forall (s : stream A), stream_eq s s.\n  Proof. (* it is longer with coinduction *)\n    cofix; intros; destruct s; constructor. apply stream_eq_refl.\n  Qed.\n\n  Theorem stream_eq_symm : forall (s1 s2 : stream A), stream_eq s2 s1 -> stream_eq s1 s2.\n  Proof.\n    cofix; apply (stream_eq_coind (fun s1 s2 : stream A => stream_eq s2 s1));\n    intros; destruct s1; destruct s2; inversion H; [ reflexivity | simpl; assumption ].\n  Qed.\n\n  (* tried to make this predicate 2-arity *)\n  Theorem stream_eq_trans : forall (s1 s3: stream A), (exists s2, stream_eq s1 s2 /\\ stream_eq s2 s3) -> stream_eq s1 s3.\n  Proof.\n    cofix;\n    apply (stream_eq_coind (fun s1 s3 => exists s2, stream_eq s1 s2 /\\ stream_eq s2 s3)); \n    intros; inversion H as [x H0]; inversion H0 as [H1 H2]; destruct x, s1, s2;\n    inversion H1; inversion H2; [ reflexivity | exists x; auto ].\n  Qed.\nEnd stream_eq_eqv.\n\n(* Exercise: Provide a suitable definition of \"being an ordered list\"\n   for infinite lists and define a principle (similar to the Park\n   principle) for proving that an infinite list is ordered.  Apply\n   this method to the stream [nats].\n\n   Hint: There are different ways of formulating the definition.  If\n   you find yourself having trouble proving things, back up and see if\n   you can state the definition a different way. *)\n\nCoInductive ordered : stream nat -> Prop :=\n  | OrdCons : forall s a, a <= head s -> ordered s -> ordered (Cons a s).\n\nSection ordered_coind.\n  Variable P : stream nat -> Prop.\n\n  Hypothesis Head_case : forall a s, P (Cons a s) -> a <= head s.\n  Hypothesis Tail_case : forall a s, P (Cons a s) -> P s.\n\n  Theorem ordered_coind : forall s, P s -> ordered s.\n  Proof.\n    cofix; intros; destruct s;\n      apply (OrdCons (Head_case H));\n      apply Tail_case in H;\n      apply ordered_coind.\n    assumption.\n  Qed.\nEnd ordered_coind.\n\nRequire Import Arith.\n\nLemma ord_nats_S : forall n, ordered (iterate S n).\nProof.\n  cofix; intros; rewrite id_force_eq; constructor;\n  [ simpl; apply le_S; apply le_n | apply ord_nats_S ].\nQed.\n\nTheorem ord_nats : ordered nats.\nProof.\n  apply (ord_nats_S 0).\nQed.", "meta": {"author": "fyrchik", "repo": "cpdt_hw", "sha": "4b207b9edf448c344463700a48d83c09f72a8592", "save_path": "github-repos/coq/fyrchik-cpdt_hw", "path": "github-repos/coq/fyrchik-cpdt_hw/cpdt_hw-4b207b9edf448c344463700a48d83c09f72a8592/HW6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7386735527859901}}
{"text": "From mathcomp Require Import all_ssreflect.\n\n(** ** case\n\ncase というのは場合分けを行う tactic です。\n\n証明項では match 式によって場合分けが行われるので、\ncase は証明項に match を構築する tactic といえます。\n\n*)\n\n(**\n\nまず、bool 型の二重否定の除去の証明を見てみましょう。\n(なお、難しい話を知っているひとに注意しておきますが、\nこれは bool の話であり、命題の話ではないので、直観主義論理でも問題なく証明できます。)\n\n*)\n\nGoal forall b, ~~ ~~ b = b.\nProof.\n(**\nSSReflect では、単に case. と指示すると、\n証明すべき命題の最も外側の引数を場合分けします。\n今回の場合、証明すべき命題は forall b : bool, ... という形なので、\nこの b を場合分けします。\n*)\n  case.\n(**\nこのように場合分けすると、以下のようにふたつの subgoal が生成されます。\n<<\n2 subgoals\n______________________________________(1/2)\n~~ ~~ true = true\n______________________________________(2/2)\n~~ ~~ false = false\n>>\n\nこの状態で証明項を表示すると以下のようになります。\n*)\n  Show Proof.\n(**\n<<\n(fun _top_assumption_ : bool =>\n (fun (_evar_0_ : (fun b : bool => ~~ ~~ b = b) true)\n    (_evar_0_0 : (fun b : bool => ~~ ~~ b = b) false) =>\n  if _top_assumption_ as b return ((fun b0 : bool => ~~ ~~ b0 = b0) b)\n  then _evar_0_\n  else _evar_0_0) ?Goal ?Goal0)\n>>\n\nmatch じゃなくて if と表示されてしまったので、\nDisplay all low-level contents を有効にして\nShow Proof をやりなおすと以下のようになります。\n\n<<\n(fun _top_assumption_ : bool =>\n (fun (_evar_0_ : (fun b : bool => @eq bool (negb (negb b)) b) true)\n    (_evar_0_0 : (fun b : bool => @eq bool (negb (negb b)) b) false) =>\n  match\n    _top_assumption_ as b\n    return ((fun b0 : bool => @eq bool (negb (negb b0)) b0) b)\n  with\n  | true => _evar_0_\n  | false => _evar_0_0\n  end) ?Goal ?Goal0)\n>>\n\nこれで、case が match を構築することが確認できました。\n\n証明項をみると、まず、?Goal と ?Goal0 というふたつの未知の部分があることがわかります。\nこれは subgoal がふたつあることに対応しています。\n\nまた、?Goal は <<_evar_0_>> に束縛され、その型は (fun b : bool => ~~ ~~ b = b) true です。\nこの型はちょっと計算を進めると（ベータ展開すると）~~ ~~ true = true になるので、\n?Goal は最初の subgoal に対応することが分かります。\n\n同様に、?Goal0 は <<_evar_0_0>> に束縛され、最後の subgoal に対応することが分かります。\n\n証明項全体は <<fun _top_assumption_ : bool => ...>> という形なので、\n場合分けの対象の bool 値は <<_top_assumption_>> に束縛されます。\n\nそして、（<<_evar_0_>> と <<_evar_0_0>> に今後行う証明を受け取った後）\n以下の match で場合分けが行われます。\n<<\nmatch\n  _top_assumption_ as b\n  return ((fun b0 : bool => ~~ ~~ b0 = b0) b)\nwith\n| true => _evar_0_\n| false => _evar_0_0\nend\n>>\n\nこの match では <<_top_assumption_>> で場合分けを行い、\n場合分けを行った値を b という変数に束縛した上で、\ntrue もしくは false の分岐を評価します。\n今回の場合は <<_evar_0_>> と <<_evar_0_0>> のどちらかの値（証明）を返すだけです。\n\nそして、return のところに書いてある ((fun b0 : bool => ~~ ~~ b0 = b0) b) が\nこの match 式の型であり、また、各分岐の型にもなっています。\n\n((fun b0 : bool => ~~ ~~ b0 = b0) b) は計算を進めると（ベータ展開すると）\n~~ ~~ b = b となり、もともと証明すべき命題になっています。\n\ntrue が選ばれたときを考えると、b は true になるので、\n((fun b0 : bool => ~~ ~~ b0 = b0) true) が true の分岐の型であり、\nちょっと計算を進めると、~~ ~~ true = true になるので\n分岐本体の <<_evar_0_>> と型が一致します。\n\n同様に、false が選ばれたときは ((fun b0 : bool => ~~ ~~ b0 = b0) false) という型になり、\n分岐本体の <<_evar_0_0>> と型が一致します。\n\nというわけでどっちの分岐が選ばれても型は合うので、match 式自体の型は\n（b は <<_top_asssumption_>> なので）、<<~~ ~~ _top_assumption_ = _top_assumption_>> になります。\n\nこれの外側を <<fun _top_assumption_ : bool => ...>> という関数抽象でくくってあるので、\n全体の型は <<forall _top_assumption_ : bool, ~~ ~~ _top_assumption_ = _top_assumption_>>\nであり、ローカル変数の名前を変換（アルファ変換）すると、<<forall b : bool, ~~ ~~ b = b>> という\nもともと証明しようとしている命題と同じになることがわかります。\n\nというわけで、あとは場合分けした結果の ~~ ~~ true = true と ~~ ~~ false = false の\n証明を行えば証明項を完成できます。\n\n~~ ~~ true と ~~ ~~ false には変数が含まれておらず、実際に計算を進めれば\ntrue と false になります。\nつまり、命題はすでに reflexivity で証明できるようになっています。\n*)\n    reflexivity.\n  reflexivity.\n  Show Proof.\n(**\n<<\n(fun _top_assumption_ : bool =>\n (fun (_evar_0_ : (fun b : bool => ~~ ~~ b = b) true)\n    (_evar_0_0 : (fun b : bool => ~~ ~~ b = b) false) =>\n  if _top_assumption_ as b return ((fun b0 : bool => ~~ ~~ b0 = b0) b)\n  then _evar_0_\n  else _evar_0_0) (erefl true) (erefl false))\n>>\n\n証明項をみると、?Goal と ?Goal0 だったところに\nreflexivity が構築した (erefl true) と (erefl false) が入っていることがわかります。\n*)\nQed.\n\n\n", "meta": {"author": "akr", "repo": "coq-curry-howard", "sha": "37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5", "save_path": "github-repos/coq/akr-coq-curry-howard", "path": "github-repos/coq/akr-coq-curry-howard/coq-curry-howard-37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5/theories/ssr_case.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914788, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.7386735337292163}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega.\n\nRequire Import utils pos vec. \nRequire Import subcode sss.\n\nSet Implicit Arguments.\n\nTactic Notation \"rew\" \"length\" := autorewrite with length_db.\n\nLocal Notation \"e #> x\" := (vec_pos e x).\nLocal Notation \"e [ v / x ]\" := (vec_change e x v).\n\n(** * Minsky Machines\n\n    A Minsky machine has n registers and there are just two instructions\n \n    1/ INC x   : increment register x by 1\n    2/ DEC x k : decrement register x by 1 if x > 0\n                 or jump to k if x = 0\n\n  *)\n\nInductive mm_instr n : Set :=\n  | mm_inc : pos n -> mm_instr n\n  | mm_dec : pos n -> nat -> mm_instr n\n  .\n\nNotation INC := mm_inc.\nNotation DEC := mm_dec.\n\n(** ** Semantics for MM *)\n\nSection Minsky_Machine.\n\n  Variable (n : nat).\n\n  Definition mm_state := (nat*vec nat n)%type.\n\n  (* Minsky machine small step semantics *)\n\n  Inductive mm_sss : mm_instr n -> mm_state -> mm_state -> Prop :=\n    | in_mm_sss_inc   : forall i x v,                   INC x   // (i,v) -1> (1+i,v[(S (v#>x))/x])\n    | in_mm_sss_dec_0 : forall i x k v,   v#>x = O   -> DEC x k // (i,v) -1> (k,v)\n    | in_mm_sss_dec_1 : forall i x k v u, v#>x = S u -> DEC x k // (i,v) -1> (1+i,v[u/x])\n  where \"i // s -1> t\" := (mm_sss i s t).\n\n  Fact mm_sss_fun i s t1 t2 : i // s -1> t1 -> i // s -1> t2 -> t1 = t2.\n  Proof.\n    intros []; subst.\n    inversion 1; subst; auto.\n    inversion 1; subst; auto.\n    rewrite H in H6; discriminate.\n    inversion 1; subst; auto.\n    rewrite H in H6; discriminate.\n    rewrite H in H6; inversion H6; subst; auto.\n  Qed.\n  \n  Fact mm_sss_total ii s : { t | ii // s -1> t }.\n  Proof.\n    destruct s as (i,v).\n    destruct ii as [ x | x j ]; [ | case_eq (v#>x); [ | intros k ]; intros E ].\n    * exists (1+i,v[(S (v#>x))/x]); constructor.\n    * exists (j,v); constructor; auto.\n    * exists (1+i,v[k/x]); constructor; auto.\n  Qed.\n  \n  Fact mm_sss_INC_inv x i v j w : INC x // (i,v) -1> (j,w) -> j=1+i /\\ w = v[(S (v#>x))/x].\n  Proof. inversion 1; subst; auto. Qed.\n  \n  Fact mm_sss_DEC0_inv x k i v j w : v#>x = O -> DEC x k // (i,v) -1> (j,w) -> j = k /\\ w = v.\n  Proof. \n    intros H; inversion 1; subst; auto; rewrite H in H2; try discriminate.\n  Qed.\n  \n  Fact mm_sss_DEC1_inv x k u i v j w : v#>x = S u -> DEC x k // (i,v) -1> (j,w) -> j=1+i /\\ w = v[u/x].\n  Proof. \n    intros H; inversion 1; subst; auto; rewrite H in H2; try discriminate.\n    inversion H2; subst; auto.\n  Qed.\n\n(*\n  Definition mm_step_stall := sss_step_stall mm_sss.\n  Definition mm_program := (nat*list (mm_instr n))%type.\n  Definition mm_steps := sss_steps mm_sss.\n  Definition mm_compute := sss_compute mm_sss.\n*)\n\n  Notation \"P // s -[ k ]-> t\" := (sss_steps mm_sss P k s t).\n  Notation \"P // s -+> t\" := (sss_progress mm_sss P s t).\n  Notation \"P // s ->> t\" := (sss_compute mm_sss P s t).\n  \n  Fact mm_progress_INC P i x v st :\n         (i,INC x::nil) <sc P\n      -> P // (1+i,v[(S (v#>x))/x]) ->> st\n      -> P // (i,v) -+> st.\n  Proof.\n    intros H1 H2.\n    apply sss_progress_compute_trans with (2 := H2).\n    apply subcode_sss_progress with (1 := H1).\n    exists 1; split; auto; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; omega.\n    constructor; auto.\n  Qed.\n  \n  Corollary mm_compute_INC P i x v st : (i,INC x::nil) <sc P -> P // (1+i,v[(S (v#>x))/x]) ->> st -> P // (i,v) ->> st.\n  Proof. intros; apply sss_progress_compute; eapply mm_progress_INC; eauto. Qed.\n  \n  Fact mm_progress_DEC_0 P i x k v st :\n         (i,DEC x k::nil) <sc P\n      -> v#>x = O \n      -> P // (k,v) ->> st\n      -> P // (i,v) -+> st.\n  Proof.\n    intros H1 H2 H3.\n    apply sss_progress_compute_trans with (2 := H3).\n    apply subcode_sss_progress with (1 := H1).\n    exists 1; split; auto; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; omega.\n    constructor; auto.\n  Qed.\n  \n  Corollary mm_compute_DEC_0 P i x k v st : (i,DEC x k::nil) <sc P -> v#>x = O -> P // (k,v) ->> st -> P // (i,v) ->> st.\n  Proof. intros; apply sss_progress_compute; eapply mm_progress_DEC_0; eauto. Qed.\n  \n  Fact mm_progress_DEC_S P i x k v u st :\n         (i,DEC x k::nil) <sc P\n      -> v#>x = S u \n      -> P // (1+i,v[u/x]) ->> st\n      -> P // (i,v) -+> st.\n  Proof.\n    intros H1 H2 H3.\n    apply sss_progress_compute_trans with (2 := H3).\n    apply subcode_sss_progress with (1 := H1).\n    exists 1; split; auto; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; omega.\n    constructor; auto.\n  Qed.\n  \n  Corollary mm_compute_DEC_S P i x k v u st : (i,DEC x k::nil) <sc P -> v#>x = S u -> P // (1+i,v[u/x]) ->> st -> P // (i,v) ->> st.\n  Proof. intros; apply sss_progress_compute; eapply mm_progress_DEC_S; eauto. Qed.\n  \n  Fact mm_steps_INC_inv k P i x v st :\n         (i,INC x::nil) <sc P\n      -> k <> 0\n      -> P // (i,v) -[k]-> st\n      -> exists k', k' < k /\\ P // (1+i,v[(S (v#>x))/x]) -[k']-> st.\n  Proof.\n    intros H1 H2 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (? & ?) | (k' & st2 & ? & H4 & H5) ]; subst; auto.\n    destruct H2; auto.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    exists k'; split.\n    omega.\n    inversion H4; subst; auto.\n  Qed.\n  \n  Fact mm_steps_DEC_0_inv k P i x p v st :\n         (i,DEC x p::nil) <sc P\n      -> k <> 0\n      -> v#>x = 0\n      -> P // (i,v) -[k]-> st\n      -> exists k', k' < k /\\ P // (p,v) -[k']-> st.\n  Proof.\n    intros H1 H2 H3 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (? & ?) | (k' & st2 & ? & H4 & H5) ]; subst; auto.\n    destruct H2; auto.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    exists k'; split.\n    omega.\n    inversion H4; subst; auto.\n    rewrite H3 in H9; discriminate.\n  Qed.\n  \n  Fact mm_steps_DEC_1_inv k P i x p v u st :\n         (i,DEC x p::nil) <sc P\n      -> k <> 0\n      -> v#>x = S u\n      -> P // (i,v) -[k]-> st\n      -> exists k', k' < k /\\ P // (1+i,v[u/x]) -[k']-> st.\n  Proof.\n    intros H1 H2 H3 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (? & ?) | (k' & st2 & ? & H4 & H5) ]; subst; auto.\n    destruct H2; auto.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    exists k'; split.\n    omega.\n    inversion H4; subst; auto; rewrite H3 in H9.\n    discriminate.\n    inversion H9; subst; auto.\n  Qed.\n  \nEnd Minsky_Machine.\n\nLocal Notation \"P // s -[ k ]-> t\" := (sss_steps (@mm_sss _) P k s t).\nLocal Notation \"P // s -+> t\" := (sss_progress (@mm_sss _) P s t).\nLocal Notation \"P // s ->> t\" := (sss_compute (@mm_sss _) P s t).\n\nTactic Notation \"mm\" \"sss\" \"INC\" \"with\" uconstr(a) := \n  match goal with\n    | |- _ // _ -+> _ => apply mm_progress_INC with (x := a)\n    | |- _ // _ ->> _ => apply mm_compute_INC with (x := a)\n  end; auto.\n\nTactic Notation \"mm\" \"sss\" \"DEC\" \"0\" \"with\" uconstr(a) uconstr(b) := \n  match goal with\n    | |- _ // _ -+> _ => apply mm_progress_DEC_0 with (x := a) (k := b)\n    | |- _ // _ ->> _ => apply mm_compute_DEC_0 with (x := a) (k := b)\n  end; auto.\n\nTactic Notation \"mm\" \"sss\" \"DEC\" \"S\" \"with\" uconstr(a) uconstr(b) uconstr(c) := \n  match goal with\n    | |- _ // _ -+> _ => apply mm_progress_DEC_S with (x := a) (k := b) (u := c)\n    | |- _ // _ ->> _ => apply mm_compute_DEC_S with (x := a) (k := b) (u := c)\n  end; auto.\n    \nTactic Notation \"mm\" \"sss\" \"stop\" := exists 0; apply sss_steps_0; auto.\n\n(* The Halting problem for MM, for linear logic encoding, we restrict\n   to a very specific halting problem. Starting from (1,v), does the\n   MM halt at state (0,vec_zero) *)\n\nDefinition MM_PROBLEM := { n : nat & { P : list (mm_instr n) & vec nat n } }.\n\nLocal Notation \"P // s ~~> t\" := (sss_output (@mm_sss _) P s t).\n\nDefinition MM_HALTING (P : MM_PROBLEM) := \n  match P with existT _ n (existT _ P v) => (1,P) // (1,v) ~~> (0,vec_zero) end.\n\n\n", "meta": {"author": "uds-psl", "repo": "ill-undecidability", "sha": "0bfda1a33cb3411c8f2c0263e15d5c85c090721d", "save_path": "github-repos/coq/uds-psl-ill-undecidability", "path": "github-repos/coq/uds-psl-ill-undecidability/ill-undecidability-0bfda1a33cb3411c8f2c0263e15d5c85c090721d/coq/Mm/mm_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7386327948631528}}
{"text": "From Coq Require Import Arith.\n\nFixpoint le_bool (n m : nat ) : bool := \n  match n,m with \n    | 0,_ => true\n    | _,0 => false \n    | S n, S m => le_bool n m\n  end.\n\nLemma le_bool_ok_true : \n  forall n m, le_bool n m = true -> le n m.\nProof.\n  induction n.\n\n  intros m _;induction m.\n  constructor.\n  constructor;exact IHm.\n\n  intros [|m].\n  intros abs;discriminate abs.\n  simpl;intros h.\n  apply le_n_S.\n  apply IHn. exact h.\nQed.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Coccinelle/examples/cime_trace/arith_extension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7386327844287865}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq fintype.\n\nSection SeqSet.\n\n  (* Let T be any type with decidable equality. *)\n  Context {T: eqType}.\n\n  (* We define a set as a sequence that has no duplicates. *)\n  Record set :=\n  {\n    _set_seq :> seq T ;\n    _ : uniq _set_seq (* no duplicates *)\n  }.\n\n  (* Now we add the [ssreflect] boilerplate code. *)\n  Canonical Structure setSubType := [subType for _set_seq].\n  Definition set_eqMixin := [eqMixin of set by <:].\n  Canonical Structure set_eqType := EqType set set_eqMixin.\n  Canonical Structure mem_set_predType := PredType (fun (l : set) => mem_seq (_set_seq l)).\n  Definition set_of of phant T := set.\n\nEnd SeqSet.\n\nNotation \" {set R } \" := (set_of (Phant R)).\n\nSection Lemmas.\n\n  Context {T: eqType}.\n  Variable s: {set T}.\n\n  Lemma set_uniq : uniq s.\n  Proof.\n    by destruct s.\n  Qed.\n\nEnd Lemmas.\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/util/seqset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730007, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7386327795195244}}
{"text": "Goal forall n : nat, n * 1 = n.\nintros.\nelim n.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nrewrite H.\nreflexivity.\n\nFixpoint f (n : nat) : nat :=\nmatch n with\n| 0 => 1\n| S p => (2 * (f p)) \nend.\n\nGoal f(10) = 1024.\nsimpl.\nreflexivity.\n\nOpen Scope list.\nRequire Import List.\nImport ListNotations.\n\nLemma P1 : forall E : Type, forall l : (list E) , forall e : E, rev(l ++ [e]) = e :: rev l. \nintros.\nelim l.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nrewrite H.\nsimpl.\nreflexivity.\n\nSave.\n\n\nLemma P2 : forall E : Type, forall l : (list E), rev( rev( l) ) = l.\nintros.\nelim l.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nrewrite (P1 E (rev l0) a).\nrewrite H.\nreflexivity.\n\nSave.\n\nLemma my_eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\ndouble induction n m.\nleft.\nreflexivity.\nintros.\nright.\ndiscriminate.\nintros.\nright.\ndiscriminate.\nintros.\nelim (H0 n0).\nleft.\nelim a.\nreflexivity.\nright.\ncongruence.\n\nSave.\n\nLemma my_eq_nat_dec2  : forall n m : nat, {n = m} + {n <> m}.\nintros.\ndecide equality.\n\nSave.\n\nFixpoint function_equality (a b : nat) : bool := \nmatch a with \n| 0 => match b with\n       | 0 =>  true\n       | S p => false\n       end\n| S p1 => match b with \n          | 0 => false\n          | S p2 => (function_equality p1 p2)\n          end\nend.\n\nSave.\n\n\nEval compute in (function_equality 0 0).\nEval compute in (function_equality (S 0) 0).\nEval compute in (function_equality (S 0) (S 0)).\n\nInductive BinTree : Set :=\n| Leaf : nat -> BinTree\n| Node : nat -> BinTree -> BinTree -> BinTree.\n\n\nSave.\n\nLemma my_eq_nat_Tree : forall n m : BinTree, {n = m} + {n <> m}.\ninduction n.\ninduction m.\nelim (my_eq_nat_dec n n0).\nleft.\nrewrite a.\nreflexivity.\nright.\ncongruence.\nright.\ndiscriminate.\ninduction m.\nright.\ndiscriminate.\nelim (my_eq_nat_dec n1 n).\nintros.\nrewrite a.\nelim (IHn1 m1).\nintros.\nrewrite a0.\nelim (IHn2 m2).\nintros.\nrewrite a1.\nleft.\nreflexivity.\nintros.\nright.\ncongruence.\nright.\ncongruence.\nright.\ncongruence.\n\nSave.\n\nLemma my_eq_nat_Tree2 : forall n m : BinTree, {n = m} + {n <> m}.\nintros.\ndecide equality.\nelim (my_eq_nat_dec2 n0 n1).\nleft.\nrewrite a.\nreflexivity.\nright.\ncongruence.\nelim (my_eq_nat_dec2 n0 n1).\nleft.\nrewrite a.\nreflexivity.\nright.\ncongruence.\n\nInductive is_even : nat -> Prop :=\n| is_even_0 : is_even 0\n| is_even_S : forall n : nat, is_even n -> is_even (S (S n)).\n\nFixpoint is_even_tac (n : nat) : bool := \nmatch n with \n| 0 => true\n| 1 => false\n| S (S p) => (is_even_tac p)\nend. \n\nLtac is_event_tac :=\nrepeat apply is_even_S;\napply is_even_0.\n\n\nEval compute in (is_even_tac (S (S 0))).\nEval compute in (is_even_tac (S (S (S 0)))).\n\nOpen Scope nat_scope.\nCheck (S (S 0)).\n\nSave.\n\nLemma test_even : (is_even (S(S(S(S 0))))).\nis_event_tac.\n\nSave.\n\nGoal ~(is_even 7).\nintro.\ninversion_clear H.\ninversion_clear H0.\ninversion_clear H.\ninversion_clear H0.\n\nLtac is_event_tac_tild := \nintro;\nrepeat (match goal with \n| H : is_even ?e |- _ => inversion_clear H\nend).\n\n\n\nGoal ~(is_even 9).\nis_event_tac_tild.\n \n\nInductive is_perm : list nat -> list nat -> Prop := \n| is_perm_append : forall n : nat, forall l : list nat, (is_perm (n::l) (l++[n]))\n| is_perm_syme : forall l1 : list nat, forall l2 : list nat, (is_perm l1 l2) -> (is_perm l2 l1)\n| is_perm_refl : forall l : list nat, is_perm l l\n| is_perm_trans : forall l1 l2 l3 : list nat , is_perm l1 l2 -> is_perm l2 l3 -> is_perm l1 l3\n| is_perm_cons : forall n : nat, forall l1 l2 : list nat, is_perm l1 l2 -> is_perm (n::l1) (n::l2)\n.\n\nLemma is_perm_ex1 : is_perm (1::2::3::nil) (3::2::1::nil).\nProof.\napply (is_perm_trans (1::2::3::nil) ((2::3::nil) ++ 1::nil) (3::2::1::nil)).\napply is_perm_append.\nsimpl.\napply (is_perm_trans (2::3::1::nil) ((3::1::nil) ++ 2::nil) (3::2::1::nil)).\napply is_perm_append.\nsimpl.\napply is_perm_cons.\napply (is_perm_trans (1::2::nil) ((2::nil) ++ 1::nil) (2::1::nil)).\napply is_perm_append.\nsimpl.\napply is_perm_cons.\napply is_perm_refl.\n\nSave.\n\n\n", "meta": {"author": "Falindir", "repo": "Coq", "sha": "5b92164ff0886df4c52e395825d0cf9d8bc3e96a", "save_path": "github-repos/coq/Falindir-Coq", "path": "github-repos/coq/Falindir-Coq/Coq-5b92164ff0886df4c52e395825d0cf9d8bc3e96a/tp3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7386002682771349}}
{"text": "From Nominal Require Export Name.\n\nDefinition Swap: Type := (Name * Name).\n\nDefinition swap '(a,b): Name → Name :=\n  λ c, if decide (a = c) then b else if decide (b = c) then a else c.\n\nNotation \"⟨ a , b ⟩\" := (@cons Swap (a,b) nil).\n\nSection SwapProperties.\n  Context (a b c d: Name).\n\n  Lemma swap_left: swap (a,b) a = b.\n  Proof. simpl; repeat case_decide; congruence. Qed.\n\n  Lemma swap_right: swap (a,b) b = a.\n  Proof. simpl; repeat case_decide; congruence. Qed.\n\n  Lemma swap_neither1: a ≠ c → b ≠ c → swap (a, b) c = c.\n  Proof. intros; simpl; repeat case_decide; congruence. Qed.\n\n  Lemma swap_neither2: swap (a, b) c = c → (a ≠ c ∧ b ≠ c) ∨ (a = c ∧ b = c).\n  Proof. \n    intros; simpl in *; try repeat case_decide; subst;\n        [right | congruence | left]; auto.\n  Qed.\n\n  Lemma swap_neq: a ≠ b → swap (c, d) a ≠ swap (c, d) b.\n  Proof. intros; simpl; repeat case_decide; congruence. Qed.\n\n  Lemma swap_id: swap (a,a) c = c.\n  Proof. simpl; case_decide; congruence. Qed.\n\n  Lemma swap_involutive p: swap p (swap p a) = a.\n  Proof. destruct p; simpl; repeat case_decide; congruence. Qed.\nEnd SwapProperties.\n\n", "meta": {"author": "fasapa", "repo": "nominal", "sha": "fa998a69041ca44315e7400c91ad59ae9556a63f", "save_path": "github-repos/coq/fasapa-nominal", "path": "github-repos/coq/fasapa-nominal/nominal-fa998a69041ca44315e7400c91ad59ae9556a63f/theories/Swap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.738592336670354}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype.\nRequire Import BinNat.\nRequire BinPos Ndec.\nRequire Export Ring.\n\n(******************************************************************************)\n(* A version of arithmetic on nat (natural numbers) that is better suited to  *)\n(* small scale reflection than the Coq Arith library. It contains an          *)\n(* extensive equational theory (including, e.g., the AGM inequality), as well *)\n(* as support for the ring tactic, and congruence tactics.                    *)\n(*   The following operations and notations are provided:                     *)\n(*                                                                            *)\n(*   successor and predecessor                                                *)\n(*     n.+1, n.+2, n.+3, n.+4 and n.-1, n.-2                                  *)\n(*     this frees the names \"S\" and \"pred\"                                    *)\n(*                                                                            *)\n(*   basic arithmetic                                                         *)\n(*     m + n, m - n, m * n                                                    *)\n(*   Important: m - n denotes TRUNCATED subtraction: m - n = 0 if m <= n.     *)\n(*   The definitions use the nosimpl tag to prevent undesirable computation   *)\n(*   computation during simplification, but remain compatible with the ones   *)\n(*   provided in the Coq.Init.Peano prelude.                                  *)\n(*     For computation, a module NatTrec rebinds all arithmetic notations     *)\n(*   to less convenient but also less inefficient tail-recursive functions;   *)\n(*   the auxiliary functions used by these versions are flagged with %Nrec.   *)\n(*     Also, there is support for input and output of large nat values.       *)\n(*       Num 3 082 241 inputs the number 3082241                              *)\n(*         [Num of n]  outputs the value n                                    *)\n(*   There are coercions num >-> BinNat.N >-> nat; ssrnat rebinds the scope   *)\n(*   delimiter for BinNat.N to %num, as it uses the shorter %N for its own    *)\n(*   notations (Peano notations are flagged with %coq_nat).                   *)\n(*                                                                            *)\n(*   doubling, halving, and parity                                            *)\n(*      n.*2, n./2, odd n, uphalf n,  with uphalf n = n.+1./2                 *)\n(*   bool coerces to nat so we can write, e.g., n = odd n + n./2.*2.          *)\n(*                                                                            *)\n(*   iteration                                                                *)\n(*             iter n f x0  == f ( .. (f x0))                                 *)\n(*             iteri n g x0 == g n.-1 (g ... (g 0 x0))                        *)\n(*         iterop n op x x0 == op x (... op x x) (n x's) or x0 if n = 0       *)\n(*                                                                            *)\n(*   exponentiation, factorial                                                *)\n(*        m ^ n, n`!                                                          *)\n(*        m ^ 1 is convertible to m, and m ^ 2 to m * m                       *)\n(*                                                                            *)\n(*   comparison                                                               *)\n(*      m <= n, m < n, m >= n, m > n, m == n, m <= n <= p, etc.,              *)\n(*   comparisons are BOOLEAN operators, and m == n is the generic eqType      *)\n(*   operation.                                                               *)\n(*     Most compatibility lemmas are stated as boolean equalities; this keeps *)\n(*   the size of the library down. All the inequalities refer to the same     *)\n(*   constant \"leq\"; in particular m < n is identical to m.+1 <= n.           *)\n(*                                                                            *)\n(* -> patterns for contextual rewriting:                                      *)\n(*      leqLHS := (X in (X <= _)%N)%pattern                                   *)\n(*      leqRHS := (X in (_ <= X)%N)%pattern                                   *)\n(*      ltnLHS := (X in (X < _)%N)%pattern                                    *)\n(*      ltnRHS := (X in (_ < X)%N)%pattern                                    *)\n(*                                                                            *)\n(*   conditionally strict inequality `leqif'                                  *)\n(*      m <= n ?= iff condition   ==   (m <= n) and ((m == n) = condition)    *)\n(*   This is actually a pair of boolean equalities, so rewriting with an      *)\n(*   `leqif' lemma can affect several kinds of comparison. The transitivity   *)\n(*   lemma for leqif aggregates the conditions, allowing for arguments of     *)\n(*   the form ``m <= n <= p <= m, so equality holds throughout''.             *)\n(*                                                                            *)\n(*   maximum and minimum                                                      *)\n(*      maxn m n, minn m n                                                    *)\n(*   Note that maxn m n = m + (n - m), due to the truncating subtraction.     *)\n(*   Absolute difference (linear distance) between nats is defined in the int *)\n(*   library (in the int.IntDist sublibrary), with the syntax `|m - n|. The   *)\n(*   '-' in this notation is the signed integer difference.                   *)\n(*                                                                            *)\n(*   countable choice                                                         *)\n(*     ex_minn : forall P : pred nat, (exists n, P n) -> nat                  *)\n(*   This returns the smallest n such that P n holds.                         *)\n(*     ex_maxn : forall (P : pred nat) m,                                     *)\n(*        (exists n, P n) -> (forall n, P n -> n <= m) -> nat                 *)\n(*   This returns the largest n such that P n holds (given an explicit upper  *)\n(*   bound).                                                                  *)\n(*                                                                            *)\n(*  This file adds the following suffix conventions to those documented in    *)\n(* ssrbool.v and eqtype.v:                                                    *)\n(*   A (infix) -- conjunction, as in                                          *)\n(*      ltn_neqAle : (m < n) = (m != n) && (m <= n).                          *)\n(*   B -- subtraction, as in subBn : (m - n) - p = m - (n + p).               *)\n(*   D -- addition, as in mulnDl : (m + n) * p = m * p + n * p.               *)\n(*   M -- multiplication, as in expnMn : (m * n) ^ p = m ^ p * n ^ p.         *)\n(*   p (prefix) -- positive, as in                                            *)\n(*      eqn_pmul2l : m > 0 -> (m * n1 == m * n2) = (n1 == n2).                *)\n(*   P  -- greater than 1, as in                                              *)\n(*      ltn_Pmull : 1 < n -> 0 < m -> m < n * m.                              *)\n(*   S -- successor, as in addSn : n.+1 + m = (n + m).+1.                     *)\n(*   V (infix) -- disjunction, as in                                          *)\n(*      leq_eqVlt : (m <= n) = (m == n) || (m < n).                           *)\n(*   X - exponentiation, as in lognX : logn p (m ^ n) = logn p m * n in       *)\n(*         file prime.v (the suffix is not used in this file).                 *)\n(* Suffixes that abbreviate operations (D, B, M and X) are used to abbreviate *)\n(* second-rank operations in equational lemma names that describe left-hand   *)\n(* sides (e.g., mulnDl); they are not used to abbreviate the main operation   *)\n(* of relational lemmas (e.g., leq_add2l).                                    *)\n(*   For the asymmetrical exponentiation operator expn (m ^ n) a right suffix *)\n(* indicates an operation on the exponent, e.g., expnM : m ^ (n1 * n2) = ...; *)\n(* a trailing \"n\" is used to indicate the left operand, e.g.,                 *)\n(* expnMn : (m1 * m2) ^ n = ... The operands of other operators are selected  *)\n(* using the l/r suffixes.                                                    *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDeclare Scope coq_nat_scope.\nDeclare Scope nat_rec_scope.\n\n(* Disable Coq prelude hints to improve proof script robustness. *)\n\n#[global] Remove Hints plus_n_O plus_n_Sm mult_n_O mult_n_Sm : core.\n\n(* Declare legacy Arith operators in new scope. *)\n\nDelimit Scope coq_nat_scope with coq_nat.\n\nNotation \"m + n\" := (plus m n) : coq_nat_scope.\nNotation \"m - n\" := (minus m n) : coq_nat_scope.\nNotation \"m * n\" := (mult m n) : coq_nat_scope.\nNotation \"m <= n\" := (le m n) : coq_nat_scope.\nNotation \"m < n\" := (lt m n) : coq_nat_scope.\nNotation \"m >= n\" := (ge m n) : coq_nat_scope.\nNotation \"m > n\" := (gt m n) : coq_nat_scope.\n\n(* Rebind scope delimiters, reserving a scope for the \"recursive\",     *)\n(* i.e., unprotected version of operators.                             *)\n\nDelimit Scope N_scope with num.\nDelimit Scope nat_scope with N.\nDelimit Scope nat_rec_scope with Nrec.\n\n(* Postfix notation for the successor and predecessor functions.  *)\n(* SSreflect uses \"pred\" for the generic predicate type, and S as *)\n(* a local bound variable.                                        *)\n\nNotation succn := Datatypes.S.\nNotation predn := Peano.pred.\n\nNotation \"n .+1\" := (succn n) (at level 2, left associativity,\n  format \"n .+1\") : nat_scope.\nNotation \"n .+2\" := n.+1.+1 (at level 2, left associativity,\n  format \"n .+2\") : nat_scope.\nNotation \"n .+3\" := n.+2.+1 (at level 2, left associativity,\n  format \"n .+3\") : nat_scope.\nNotation \"n .+4\" := n.+2.+2 (at level 2, left associativity,\n  format \"n .+4\") : nat_scope.\n\nNotation \"n .-1\" := (predn n) (at level 2, left associativity,\n  format \"n .-1\") : nat_scope.\nNotation \"n .-2\" := n.-1.-1 (at level 2, left associativity,\n  format \"n .-2\") : nat_scope.\n\nLemma succnK : cancel succn predn. Proof. by []. Qed.\nLemma succn_inj : injective succn. Proof. by move=> n m []. Qed.\n\n(* Predeclare postfix doubling/halving operators. *)\n\nReserved Notation \"n .*2\" (at level 2, left associativity, format \"n .*2\").\nReserved Notation \"n ./2\" (at level 2, left associativity, format \"n ./2\").\n\n(* Canonical comparison and eqType for nat.                                *)\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\nLemma eqnP : Equality.axiom eqn.\nProof.\nmove=> n m; apply: (iffP idP) => [|<-]; last by elim n.\nby elim: n m => [|n IHn] [|m] //= /IHn->.\nQed.\n\nCanonical nat_eqMixin := EqMixin eqnP.\nCanonical nat_eqType := Eval hnf in EqType nat nat_eqMixin.\n\nArguments eqn !m !n.\nArguments eqnP {x y}.\n\nLemma eqnE : eqn = eq_op. Proof. by []. Qed.\n\nLemma eqSS m n : (m.+1 == n.+1) = (m == n). Proof. by []. Qed.\n\nLemma nat_irrelevance (x y : nat) (E E' : x = y) : E = E'.\nProof. exact: eq_irrelevance. Qed.\n\n(* Protected addition, with a more systematic set of lemmas.                *)\n\nDefinition addn_rec := plus.\nNotation \"m + n\" := (addn_rec m n) : nat_rec_scope.\n\nDefinition addn := nosimpl addn_rec.\nNotation \"m + n\" := (addn m n) : nat_scope.\n\nLemma addnE : addn = addn_rec. Proof. by []. Qed.\n\nLemma plusE : plus = addn. Proof. by []. Qed.\n\nLemma add0n : left_id 0 addn.            Proof. by []. Qed.\nLemma addSn m n : m.+1 + n = (m + n).+1. Proof. by []. Qed.\nLemma add1n n : 1 + n = n.+1.            Proof. by []. Qed.\n\nLemma addn0 : right_id 0 addn. Proof. by move=> n; apply/eqP; elim: n. Qed.\n\nLemma addnS m n : m + n.+1 = (m + n).+1. Proof. by apply/eqP; elim: m. Qed.\n\nLemma addSnnS m n : m.+1 + n = m + n.+1. Proof. by rewrite addnS. Qed.\n\nLemma addnCA : left_commutative addn.\nProof. by move=> m n p; elim: m => //= m; rewrite addnS => <-. Qed.\n\nLemma addnC : commutative addn.\nProof. by move=> m n; rewrite -[n in LHS]addn0 addnCA addn0. Qed.\n\nLemma addn1 n : n + 1 = n.+1. Proof. by rewrite addnC. Qed.\n\nLemma addnA : associative addn.\nProof. by move=> m n p; rewrite (addnC n) addnCA addnC. Qed.\n\nLemma addnAC : right_commutative addn.\nProof. by move=> m n p; rewrite -!addnA (addnC n). Qed.\n\nLemma addnCAC m n p : m + n + p = p + n + m.\nProof. by rewrite addnC addnA addnAC. Qed.\n\nLemma addnACl m n p: m + n + p = n + (p + m).\nProof. by rewrite (addnC m) addnC addnCA. Qed.\n\nLemma addnACA : interchange addn addn.\nProof. by move=> m n p q; rewrite -!addnA (addnCA n). Qed.\n\nLemma addn_eq0 m n : (m + n == 0) = (m == 0) && (n == 0).\nProof. by case: m; case: n. Qed.\n\nLemma eqn_add2l p m n : (p + m == p + n) = (m == n).\nProof. by elim: p. Qed.\n\nLemma eqn_add2r p m n : (m + p == n + p) = (m == n).\nProof. by rewrite -!(addnC p) eqn_add2l. Qed.\n\nLemma addnI : right_injective addn.\nProof. by move=> p m n Heq; apply: eqP; rewrite -(eqn_add2l p) Heq eqxx. Qed.\n\nLemma addIn : left_injective addn.\nProof. move=> p m n; rewrite -!(addnC p); apply addnI. Qed.\n\nLemma addn2 m : m + 2 = m.+2. Proof. by rewrite addnC. Qed.\nLemma add2n m : 2 + m = m.+2. Proof. by []. Qed.\nLemma addn3 m : m + 3 = m.+3. Proof. by rewrite addnC. Qed.\nLemma add3n m : 3 + m = m.+3. Proof. by []. Qed.\nLemma addn4 m : m + 4 = m.+4. Proof. by rewrite addnC. Qed.\nLemma add4n m : 4 + m = m.+4. Proof. by []. Qed.\n\n(* Protected, structurally decreasing subtraction, and basic lemmas.  *)\n(* Further properties depend on ordering conditions.                  *)\n\nDefinition subn_rec := minus.\nArguments subn_rec : simpl nomatch.\nNotation \"m - n\" := (subn_rec m n) : nat_rec_scope.\n\nDefinition subn := nosimpl subn_rec.\nNotation \"m - n\" := (subn m n) : nat_scope.\n\nLemma subnE : subn = subn_rec. Proof. by []. Qed.\nLemma minusE : minus = subn.   Proof. by []. Qed.\n\nLemma sub0n : left_zero 0 subn.    Proof. by []. Qed.\nLemma subn0 : right_id 0 subn.   Proof. by case. Qed.\nLemma subnn : self_inverse 0 subn. Proof. by elim. Qed.\n\nLemma subSS n m : m.+1 - n.+1 = m - n. Proof. by []. Qed.\nLemma subn1 n : n - 1 = n.-1.          Proof. by case: n => [|[]]. Qed.\nLemma subn2 n : (n - 2)%N = n.-2.      Proof. by case: n => [|[|[]]]. Qed.\n\nLemma subnDl p m n : (p + m) - (p + n) = m - n.\nProof. by elim: p. Qed.\n\nLemma subnDr p m n : (m + p) - (n + p) = m - n.\nProof. by rewrite -!(addnC p) subnDl. Qed.\n\nLemma addnK n : cancel (addn^~ n) (subn^~ n).\nProof. by move=> m; rewrite (subnDr n m 0) subn0. Qed.\n\nLemma addKn n : cancel (addn n) (subn^~ n).\nProof. by move=> m; rewrite addnC addnK. Qed.\n\nLemma subSnn n : n.+1 - n = 1.\nProof. exact (addnK n 1). Qed.\n\nLemma subnDA m n p : n - (m + p) = (n - m) - p.\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma subnAC : right_commutative subn.\nProof. by move=> m n p; rewrite -!subnDA addnC. Qed.\n\nLemma subnS m n : m - n.+1 = (m - n).-1.\nProof. by rewrite -addn1 subnDA subn1. Qed.\n\nLemma subSKn m n : (m.+1 - n).-1 = m - n.\nProof. by rewrite -subnS. Qed.\n\n(* Integer ordering, and its interaction with the other operations.       *)\n\nDefinition leq m n := m - n == 0.\n\nNotation \"m <= n\" := (leq m n) : nat_scope.\nNotation \"m < n\"  := (m.+1 <= n) : nat_scope.\nNotation \"m >= n\" := (n <= m) (only parsing) : nat_scope.\nNotation \"m > n\"  := (n < m) (only parsing)  : nat_scope.\n\n(* For sorting, etc. *)\nDefinition geq := [rel m n | m >= n].\nDefinition ltn := [rel m n | m < n].\nDefinition gtn := [rel m n | m > n].\n\nNotation \"m <= n <= p\" := ((m <= n) && (n <= p)) : nat_scope.\nNotation \"m < n <= p\" := ((m < n) && (n <= p)) : nat_scope.\nNotation \"m <= n < p\" := ((m <= n) && (n < p)) : nat_scope.\nNotation \"m < n < p\" := ((m < n) && (n < p)) : nat_scope.\n\nLemma ltnS m n : (m < n.+1) = (m <= n). Proof. by []. Qed.\nLemma leq0n n : 0 <= n.                 Proof. by []. Qed.\nLemma ltn0Sn n : 0 < n.+1.              Proof. by []. Qed.\nLemma ltn0 n : n < 0 = false.           Proof. by []. Qed.\nLemma leqnn n : n <= n.                 Proof. by elim: n. Qed.\n#[global] Hint Resolve leqnn : core.\nLemma ltnSn n : n < n.+1.               Proof. by []. Qed.\nLemma eq_leq m n : m = n -> m <= n.     Proof. by move->. Qed.\nLemma leqnSn n : n <= n.+1.             Proof. by elim: n. Qed.\n#[global] Hint Resolve leqnSn : core.\nLemma leq_pred n : n.-1 <= n.           Proof. by case: n => /=. Qed.\nLemma leqSpred n : n <= n.-1.+1.        Proof. by case: n => /=. Qed.\n\nLemma ltn_predL n : (n.-1 < n) = (0 < n).\nProof. by case: n => [//|n]; rewrite ltnSn. Qed.\n\nLemma ltn_predRL m n : (m < n.-1) = (m.+1 < n).\nProof. by case: n => [//|n]; rewrite succnK. Qed.\n\nLemma ltn_predK m n : m < n -> n.-1.+1 = n.\nProof. by case: n. Qed.\n\nLemma prednK n : 0 < n -> n.-1.+1 = n.\nProof. exact: ltn_predK. Qed.\n\nLemma leqNgt m n : (m <= n) = ~~ (n < m).\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma leqVgt m n : (m <= n) || (n < m). Proof. by rewrite leqNgt orNb. Qed.\n\nLemma ltnNge m n : (m < n) = ~~ (n <= m).\nProof. by rewrite leqNgt. Qed.\n\nLemma ltnn n : n < n = false.\nProof. by rewrite ltnNge leqnn. Qed.\n\nLemma leqn0 n : (n <= 0) = (n == 0).           Proof. by case: n. Qed.\nLemma lt0n n : (0 < n) = (n != 0).             Proof. by case: n. Qed.\nLemma lt0n_neq0 n : 0 < n -> n != 0.           Proof. by case: n. Qed.\nLemma eqn0Ngt n : (n == 0) = ~~ (n > 0).       Proof. by case: n. Qed.\nLemma neq0_lt0n n : (n == 0) = false -> 0 < n. Proof. by case: n. Qed.\n#[global] Hint Resolve lt0n_neq0 neq0_lt0n : core.\n\nLemma eqn_leq m n : (m == n) = (m <= n <= m).\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma anti_leq : antisymmetric leq.\nProof. by move=> m n; rewrite -eqn_leq => /eqP. Qed.\n\nLemma neq_ltn m n : (m != n) = (m < n) || (n < m).\nProof. by rewrite eqn_leq negb_and orbC -!ltnNge. Qed.\n\nLemma gtn_eqF m n : m < n -> n == m = false.\nProof. by rewrite eqn_leq (leqNgt n) => ->. Qed.\n\nLemma ltn_eqF m n : m < n -> m == n = false.\nProof. by move/gtn_eqF; rewrite eq_sym. Qed.\n\nLemma ltn_geF m n : m < n -> m >= n = false.\nProof. by rewrite (leqNgt n) => ->. Qed.\n\nLemma leq_gtF m n : m <= n -> m > n = false.\nProof. by rewrite (ltnNge n) => ->. Qed.\n\nLemma leq_eqVlt m n : (m <= n) = (m == n) || (m < n).\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma ltn_neqAle m n : (m < n) = (m != n) && (m <= n).\nProof. by rewrite ltnNge leq_eqVlt negb_or -leqNgt eq_sym. Qed.\n\nLemma leq_trans n m p : m <= n -> n <= p -> m <= p.\nProof. by elim: n m p => [|i IHn] [|m] [|p] //; apply: IHn m p. Qed.\n\nLemma leq_ltn_trans n m p : m <= n -> n < p -> m < p.\nProof. by move=> Hmn; apply: leq_trans. Qed.\n\nLemma ltnW m n : m < n -> m <= n.\nProof. exact: leq_trans. Qed.\n#[global] Hint Resolve ltnW : core.\n\nLemma leqW m n : m <= n -> m <= n.+1.\nProof. by move=> le_mn; apply: ltnW. Qed.\n\nLemma ltn_trans n m p : m < n -> n < p -> m < p.\nProof. by move=> lt_mn /ltnW; apply: leq_trans. Qed.\n\nLemma leq_total m n : (m <= n) || (m >= n).\nProof. by rewrite -implyNb -ltnNge; apply/implyP; apply: ltnW. Qed.\n\n(* Helper lemmas to support generalized induction over a nat measure.         *)\n(* The idiom for a proof by induction over a measure Mxy : nat involving      *)\n(* variables x, y, ... (e.g., size x + size y) is                             *)\n(*   have [n leMn] := ubnP Mxy; elim: n => // n IHn in x y ... leMn ... *.    *)\n(* after which the current goal (possibly modified by generalizations in the  *)\n(* in ... part) can be proven with the extra context assumptions              *)\n(*  n : nat                                                                   *)\n(*  IHn : forall x y ..., Mxy < n -> ... -> the_initial_goal                  *)\n(*  leMn : Mxy < n.+1                                                         *)\n(* This is preferable to the legacy idiom relying on numerical occurrence     *)\n(* selection, which is fragile if there can be multiple occurrences of x, y,  *)\n(* ... in the measure expression Mxy (e.g., in #|y| with x : finType and      *)\n(* y : {set x}).                                                              *)\n(*  The leMn statement is convertible to Mxy <= n; if it is necessary to      *)\n(* have _exactly_ leMn : Mxy <= n, the ltnSE helper lemma may be used as      *)\n(* follows                                                                    *)\n(*   have [n] := ubnP Mxy; elim: n => // n IHn in x y ... * => /ltnSE-leMn.   *)\n(*  We also provide alternative helper lemmas for proofs where the upper      *)\n(* bound appears in the goal, and we assume nonstrict (in)equality.           *)\n(* In either case the proof will have to dispatch an Mxy = 0 case.            *)\n(*  have [n defM] := ubnPleq Mxy; elim: n => [|n IHn] in x y ... defM ... *.  *)\n(* yields two subgoals, in which Mxy has been replaced by 0 and n.+1,         *)\n(* with the extra assumption defM : Mxy <= 0 / Mxy <= n.+1, respectively.     *)\n(* The second goal also has the inductive assumption                          *)\n(*   IHn : forall x y ..., Mxy <= n -> ... -> the_initial_goal[n / Mxy].      *)\n(* Using ubnPgeq or ubnPeq instead of ubnPleq yields assumptions with         *)\n(* Mxy >= 0/n.+1 or Mxy == 0/n.+1 instead of Mxy <= 0/n.+1, respectively.     *)\n(* These introduce a different kind of induction; for example ubnPgeq M lets  *)\n(* us remember that n < M throughout the induction.                           *)\n(*   Finally, the ltn_ind lemma provides a generalized induction view for a   *)\n(* property of a single integer (i.e., the case Mxy := x).                    *)\nLemma ubnP m : {n | m < n}.             Proof. by exists m.+1. Qed.\nLemma ltnSE m n : m < n.+1 -> m <= n.   Proof. by []. Qed.\nVariant ubn_leq_spec m : nat -> Type := UbnLeq n of m <= n : ubn_leq_spec m n.\nVariant ubn_geq_spec m : nat -> Type := UbnGeq n of m >= n : ubn_geq_spec m n.\nVariant ubn_eq_spec m : nat -> Type := UbnEq n of m == n : ubn_eq_spec m n.\nLemma ubnPleq m : ubn_leq_spec m m.    Proof. by []. Qed.\nLemma ubnPgeq m : ubn_geq_spec m m.    Proof. by []. Qed.\nLemma ubnPeq m : ubn_eq_spec m m.      Proof. by []. Qed.\nLemma ltn_ind P : (forall n, (forall m, m < n -> P m) -> P n) -> forall n, P n.\nProof.\nmove=> accP M; have [n leMn] := ubnP M; elim: n => // n IHn in M leMn *.\nby apply/accP=> p /leq_trans/(_ leMn)/IHn.\nQed.\n\n(* Link to the legacy comparison predicates. *)\n\nLemma leP m n : reflect (m <= n)%coq_nat (m <= n).\nProof.\napply: (iffP idP); last by elim: n / => // n _ /leq_trans->.\nelim: n => [|n IHn]; first by case: m.\nby rewrite leq_eqVlt ltnS => /predU1P[<- // | /IHn]; right.\nQed.\nArguments leP {m n}.\n\nLemma le_irrelevance m n le_mn1 le_mn2 : le_mn1 = le_mn2 :> (m <= n)%coq_nat.\nProof.\nelim/ltn_ind: n => n IHn in le_mn1 le_mn2 *; set n1 := n in le_mn1 *.\npose def_n : n = n1 := erefl n; transitivity (eq_ind _ _ le_mn2 _ def_n) => //.\ncase: n1 / le_mn1 le_mn2 => [|n1 le_mn1] {n}[|n le_mn2] in (def_n) IHn *.\n- by rewrite [def_n]eq_axiomK.\n- by case/leP/idPn: (le_mn2); rewrite -def_n ltnn.\n- by case/leP/idPn: (le_mn1); rewrite def_n ltnn.\ncase: def_n (def_n) => <-{n1} def_n in le_mn1 *.\nby rewrite [def_n]eq_axiomK /=; congr le_S; apply: IHn.\nQed.\n\nLemma ltP m n : reflect (m < n)%coq_nat (m < n).\nProof. exact leP. Qed.\nArguments ltP {m n}.\n\nLemma lt_irrelevance m n lt_mn1 lt_mn2 : lt_mn1 = lt_mn2 :> (m < n)%coq_nat.\nProof. exact: (@le_irrelevance m.+1). Qed.\n\n(* Monotonicity lemmas *)\n\nLemma leq_add2l p m n : (p + m <= p + n) = (m <= n).\nProof. by elim: p. Qed.\n\nLemma ltn_add2l p m n : (p + m < p + n) = (m < n).\nProof. by rewrite -addnS; apply: leq_add2l. Qed.\n\nLemma leq_add2r p m n : (m + p <= n + p) = (m <= n).\nProof. by rewrite -!(addnC p); apply: leq_add2l. Qed.\n\nLemma ltn_add2r p m n : (m + p < n + p) = (m < n).\nProof. exact: leq_add2r p m.+1 n. Qed.\n\nLemma leq_add m1 m2 n1 n2 : m1 <= n1 -> m2 <= n2 -> m1 + m2 <= n1 + n2.\nProof.\nby move=> le_mn1 le_mn2; rewrite (@leq_trans (m1 + n2)) ?leq_add2l ?leq_add2r.\nQed.\n\nLemma leq_addl m n : n <= m + n. Proof. exact: (leq_add2r n 0). Qed.\n\nLemma leq_addr m n : n <= n + m. Proof. by rewrite addnC leq_addl. Qed.\n\nLemma ltn_addl m n p : m < n -> m < p + n.\nProof. by move/leq_trans=> -> //; apply: leq_addl. Qed.\n\nLemma ltn_addr m n p : m < n -> m < n + p.\nProof. by move/leq_trans=> -> //; apply: leq_addr. Qed.\n\nLemma addn_gt0 m n : (0 < m + n) = (0 < m) || (0 < n).\nProof. by rewrite !lt0n -negb_and addn_eq0. Qed.\n\nLemma subn_gt0 m n : (0 < n - m) = (m < n).\nProof. by elim: m n => [|m IHm] [|n] //; apply: IHm n. Qed.\n\nLemma subn_eq0 m n : (m - n == 0) = (m <= n).\nProof. by []. Qed.\n\nLemma leq_subLR m n p : (m - n <= p) = (m <= n + p).\nProof. by rewrite -subn_eq0 -subnDA. Qed.\n\nLemma leq_subr m n : n - m <= n.\nProof. by rewrite leq_subLR leq_addl. Qed.\n\nLemma ltn_subrR m n : (n < n - m) = false.\nProof. by rewrite ltnNge leq_subr. Qed.\n\nLemma leq_subrR m n : (n <= n - m) = (m == 0) || (n == 0).\nProof. by case: m n => [|m] [|n]; rewrite ?subn0 ?leqnn ?ltn_subrR. Qed.\n\nLemma ltn_subrL m n : (n - m < n) = (0 < m) && (0 < n).\nProof. by rewrite ltnNge leq_subrR negb_or !lt0n. Qed.\n\nLemma subnKC m n : m <= n -> m + (n - m) = n.\nProof. by elim: m n => [|m IHm] [|n] // /(IHm n) {2}<-. Qed.\n\nLemma addnBn m n : m + (n - m) = m - n + n.\nProof. by elim: m n => [|m IHm] [|n] //; rewrite addSn addnS IHm. Qed.\n\nLemma subnK m n : m <= n -> (n - m) + m = n.\nProof. by rewrite addnC; apply: subnKC. Qed.\n\nLemma addnBA m n p : p <= n -> m + (n - p) = m + n - p.\nProof. by move=> le_pn; rewrite -[in RHS](subnK le_pn) addnA addnK. Qed.\n\nLemma addnBAC m n p : n <= m -> m - n + p = m + p - n.\nProof. by move=> le_nm; rewrite addnC addnBA // addnC. Qed.\n\nLemma addnBCA m n p : p <= m -> p <= n -> m + (n - p) = n + (m - p).\nProof. by move=> le_pm le_pn; rewrite !addnBA // addnC. Qed.\n\nLemma addnABC m n p : p <= m -> p <= n -> m + (n - p) = m - p + n.\nProof. by move=> le_pm le_pn; rewrite addnBA // addnBAC. Qed.\n\nLemma subnBA m n p : p <= n -> m - (n - p) = m + p - n.\nProof. by move=> le_pn; rewrite -[in RHS](subnK le_pn) subnDr. Qed.\n\nLemma subnA m n p : p <= n -> n <= m -> m - (n - p) = m - n + p.\nProof. by move=> le_pn lr_nm; rewrite addnBAC // subnBA. Qed.\n\nLemma subKn m n : m <= n -> n - (n - m) = m.\nProof. by move/subnBA->; rewrite addKn. Qed.\n\nLemma subSn m n : m <= n -> n.+1 - m = (n - m).+1.\nProof. by rewrite -add1n => /addnBA <-. Qed.\n\nLemma subnSK m n : m < n -> (n - m.+1).+1 = n - m. Proof. by move/subSn. Qed.\n\nLemma predn_sub m n : (m - n).-1 = (m.-1 - n).\nProof. by case: m => // m; rewrite subSKn. Qed.\n\nLemma leq_sub2r p m n : m <= n -> m - p <= n - p.\nProof. by move=> le_mn; rewrite leq_subLR (leq_trans le_mn) // -leq_subLR. Qed.\n\nLemma leq_sub2l p m n : m <= n -> p - n <= p - m.\nProof.\nrewrite -(leq_add2r (p - m)) leq_subLR.\nby apply: leq_trans; rewrite -leq_subLR.\nQed.\n\nLemma leq_sub m1 m2 n1 n2 : m1 <= m2 -> n2 <= n1 -> m1 - n1 <= m2 - n2.\nProof. by move/(leq_sub2r n1)=> le_m12 /(leq_sub2l m2); apply: leq_trans. Qed.\n\nLemma ltn_sub2r p m n : p < n -> m < n -> m - p < n - p.\nProof. by move/subnSK <-; apply: (@leq_sub2r p.+1). Qed.\n\nLemma ltn_sub2l p m n : m < p -> m < n -> p - n < p - m.\nProof. by move/subnSK <-; apply: leq_sub2l. Qed.\n\nLemma ltn_subRL m n p : (n < p - m) = (m + n < p).\nProof. by rewrite !ltnNge leq_subLR. Qed.\n\nLemma leq_psubRL m n p : 0 < n -> (n <= p - m) = (m + n <= p).\nProof. by move=> /prednK<-; rewrite ltn_subRL addnS. Qed.\n\nLemma ltn_psubLR m n p : 0 < p -> (m - n < p) = (m < n + p).\nProof. by move=> /prednK<-; rewrite ltnS leq_subLR addnS. Qed.\n\nLemma leq_subRL m n p : m <= p -> (n <= p - m) = (m + n <= p).\nProof. by move=> /subnKC{2}<-; rewrite leq_add2l. Qed.\n\nLemma ltn_subLR m n p : n <= m -> (m - n < p) = (m < n + p).\nProof. by move=> /subnKC{2}<-; rewrite ltn_add2l. Qed.\n\nLemma leq_subCl m n p : (m - n <= p) = (m - p <= n).\nProof. by rewrite !leq_subLR // addnC. Qed.\n\nLemma ltn_subCr m n p : (p < m - n) = (n < m - p).\nProof. by rewrite !ltn_subRL // addnC. Qed.\n\nLemma leq_psubCr m n p : 0 < p -> 0 < n -> (p <= m - n) = (n <= m - p).\nProof. by move=> p_gt0 n_gt0; rewrite !leq_psubRL // addnC. Qed.\n\nLemma ltn_psubCl m n p : 0 < p -> 0 < n -> (m - n < p) = (m - p < n).\nProof. by move=> p_gt0 n_gt0; rewrite !ltn_psubLR // addnC. Qed.\n\nLemma leq_subCr m n p : n <= m -> p <= m -> (p <= m - n) = (n <= m - p).\nProof. by move=> np pm; rewrite !leq_subRL // addnC. Qed.\n\nLemma ltn_subCl m n p : n <= m -> p <= m -> (m - n < p) = (m - p < n).\nProof. by move=> nm pm; rewrite !ltn_subLR // addnC. Qed.\n\nLemma leq_sub2rE p m n : p <= n -> (m - p <= n - p) = (m <= n).\nProof. by move=> pn; rewrite leq_subLR subnKC. Qed.\n\nLemma leq_sub2lE m n p : n <= m -> (m - p <= m - n) = (n <= p).\nProof. by move=> nm; rewrite leq_subCl subKn. Qed.\n\nLemma ltn_sub2rE p m n : p <= m -> (m - p < n - p) = (m < n).\nProof. by move=> pn; rewrite ltn_subRL addnC subnK. Qed.\n\nLemma ltn_sub2lE m n p : p <= m -> (m - p < m - n) = (n < p).\nProof. by move=> pm; rewrite ltn_subCr subKn. Qed.\n\n(* Max and min. *)\n\nDefinition maxn m n := if m < n then n else m.\n\nDefinition minn m n := if m < n then m else n.\n\nLemma max0n : left_id 0 maxn.  Proof. by case. Qed.\nLemma maxn0 : right_id 0 maxn. Proof. by []. Qed.\n\nLemma maxnC : commutative maxn.\nProof. by rewrite /maxn; elim=> [|m ih] [] // n; rewrite !ltnS -!fun_if ih. Qed.\n\nLemma maxnE m n : maxn m n = m + (n - m).\nProof.\nrewrite /maxn; elim: m n => [|m ih] [|n]; rewrite ?addn0 //.\nby rewrite ltnS subSS addSn -ih; case: leq.\nQed.\n\nLemma maxnAC : right_commutative maxn.\nProof. by move=> m n p; rewrite !maxnE -!addnA !subnDA -!maxnE maxnC. Qed.\n\nLemma maxnA : associative maxn.\nProof. by move=> m n p; rewrite !(maxnC m) maxnAC. Qed.\n\nLemma maxnCA : left_commutative maxn.\nProof. by move=> m n p; rewrite !maxnA (maxnC m). Qed.\n\nLemma maxnACA : interchange maxn maxn.\nProof. by move=> m n p q; rewrite -!maxnA (maxnCA n). Qed.\n\nLemma maxn_idPl {m n} : reflect (maxn m n = m) (m >= n).\nProof. by rewrite -subn_eq0 -(eqn_add2l m) addn0 -maxnE; apply: eqP. Qed.\n\nLemma maxn_idPr {m n} : reflect (maxn m n = n) (m <= n).\nProof. by rewrite maxnC; apply: maxn_idPl. Qed.\n\nLemma maxnn : idempotent maxn.\nProof. by move=> n; apply/maxn_idPl. Qed.\n\nLemma leq_max m n1 n2 : (m <= maxn n1 n2) = (m <= n1) || (m <= n2).\nProof.\nwithout loss le_n21: n1 n2 / n2 <= n1.\n  by case/orP: (leq_total n2 n1) => le_n12; last rewrite maxnC orbC; apply.\nby rewrite (maxn_idPl le_n21) orb_idr // => /leq_trans->.\nQed.\nLemma leq_maxl m n : m <= maxn m n. Proof. by rewrite leq_max leqnn. Qed.\nLemma leq_maxr m n : n <= maxn m n. Proof. by rewrite maxnC leq_maxl. Qed.\n\nLemma gtn_max m n1 n2 : (m > maxn n1 n2) = (m > n1) && (m > n2).\nProof. by rewrite !ltnNge leq_max negb_or. Qed.\n\nLemma geq_max m n1 n2 : (m >= maxn n1 n2) = (m >= n1) && (m >= n2).\nProof. by rewrite -ltnS gtn_max. Qed.\n\nLemma maxnSS m n : maxn m.+1 n.+1 = (maxn m n).+1.\nProof. by rewrite !maxnE. Qed.\n\nLemma addn_maxl : left_distributive addn maxn.\nProof. by move=> m1 m2 n; rewrite !maxnE subnDr addnAC. Qed.\n\nLemma addn_maxr : right_distributive addn maxn.\nProof. by move=> m n1 n2; rewrite !(addnC m) addn_maxl. Qed.\n\nLemma subn_maxl : left_distributive subn maxn.\nProof.\nmove=> m n p; apply/eqP.\nrewrite eqn_leq !geq_max !leq_sub2r leq_max ?leqnn ?andbT ?orbT // /maxn.\nby case: (_ < _); rewrite leqnn // orbT.\nQed.\n\nLemma min0n : left_zero 0 minn. Proof. by case. Qed.\nLemma minn0 : right_zero 0 minn. Proof. by []. Qed.\n\nLemma minnC : commutative minn.\nProof. by rewrite /minn; elim=> [|m ih] [] // n; rewrite !ltnS -!fun_if ih. Qed.\n\nLemma addn_min_max m n : minn m n + maxn m n = m + n.\nProof. by rewrite /minn /maxn; case: (m < n) => //; exact: addnC. Qed.\n\nLemma minnE m n : minn m n = m - (m - n).\nProof. by rewrite -(subnDl n) -maxnE -addn_min_max addnK minnC. Qed.\n\nLemma minnAC : right_commutative minn.\nProof.\nby move=> m n p; rewrite !minnE -subnDA subnAC -maxnE maxnC maxnE subnAC subnDA.\nQed.\n\nLemma minnA : associative minn.\nProof. by move=> m n p; rewrite minnC minnAC (minnC n). Qed.\n\nLemma minnCA : left_commutative minn.\nProof. by move=> m n p; rewrite !minnA (minnC n). Qed.\n\nLemma minnACA : interchange minn minn.\nProof. by move=> m n p q; rewrite -!minnA (minnCA n). Qed.\n\nLemma minn_idPl {m n} : reflect (minn m n = m) (m <= n).\nProof.\nrewrite (sameP maxn_idPr eqP) -(eqn_add2l m) eq_sym -addn_min_max eqn_add2r.\nexact: eqP.\nQed.\n\nLemma minn_idPr {m n} : reflect (minn m n = n) (m >= n).\nProof. by rewrite minnC; apply: minn_idPl. Qed.\n\nLemma minnn : idempotent minn.\nProof. by move=> n; apply/minn_idPl. Qed.\n\nLemma leq_min m n1 n2 : (m <= minn n1 n2) = (m <= n1) && (m <= n2).\nProof.\nwlog le_n21: n1 n2 / n2 <= n1.\n  by case/orP: (leq_total n2 n1) => ?; last rewrite minnC andbC; apply.\nrewrite /minn ltnNge le_n21 /=; case le_m_n1: (m <= n1) => //=.\napply/contraFF: le_m_n1 => /leq_trans; exact.\nQed.\n\nLemma gtn_min m n1 n2 : (m > minn n1 n2) = (m > n1) || (m > n2).\nProof. by rewrite !ltnNge leq_min negb_and. Qed.\n\nLemma geq_min m n1 n2 : (m >= minn n1 n2) = (m >= n1) || (m >= n2).\nProof. by rewrite -ltnS gtn_min. Qed.\n\nLemma geq_minl m n : minn m n <= m. Proof. by rewrite geq_min leqnn. Qed.\nLemma geq_minr m n : minn m n <= n. Proof. by rewrite minnC geq_minl. Qed.\n\nLemma addn_minr : right_distributive addn minn.\nProof. by move=> m1 m2 n; rewrite !minnE subnDl addnBA ?leq_subr. Qed.\n\nLemma addn_minl : left_distributive addn minn.\nProof. by move=> m1 m2 n; rewrite -!(addnC n) addn_minr. Qed.\n\nLemma subn_minl : left_distributive subn minn.\nProof.\nmove=> m n p; apply/eqP.\nrewrite eqn_leq !leq_min !leq_sub2r geq_min ?leqnn ?orbT //= /minn.\nby case: (_ < _); rewrite leqnn // orbT.\nQed.\n\nLemma minnSS m n : minn m.+1 n.+1 = (minn m n).+1.\nProof. by rewrite -(addn_minr 1). Qed.\n\n(* Quasi-cancellation (really, absorption) lemmas *)\nLemma maxnK m n : minn (maxn m n) m = m.\nProof. exact/minn_idPr/leq_maxl. Qed.\n\nLemma maxKn m n : minn n (maxn m n) = n.\nProof. exact/minn_idPl/leq_maxr. Qed.\n\nLemma minnK m n : maxn (minn m n) m = m.\nProof. exact/maxn_idPr/geq_minl. Qed.\n\nLemma minKn m n : maxn n (minn m n) = n.\nProof. exact/maxn_idPl/geq_minr. Qed.\n\n(* Distributivity. *)\nLemma maxn_minl : left_distributive maxn minn.\nProof.\nmove=> m1 m2 n; wlog le_m21: m1 m2 / m2 <= m1.\n  move=> IH; case/orP: (leq_total m2 m1) => /IH //.\n  by rewrite minnC [in R in _ = R]minnC.\nrewrite (minn_idPr le_m21); apply/esym/minn_idPr.\nby rewrite geq_max leq_maxr leq_max le_m21.\nQed.\n\nLemma maxn_minr : right_distributive maxn minn.\nProof. by move=> m n1 n2; rewrite !(maxnC m) maxn_minl. Qed.\n\nLemma minn_maxl : left_distributive minn maxn.\nProof.\nby move=> m1 m2 n; rewrite maxn_minr !maxn_minl -minnA maxnn (maxnC _ n) !maxnK.\nQed.\n\nLemma minn_maxr : right_distributive minn maxn.\nProof. by move=> m n1 n2; rewrite !(minnC m) minn_maxl. Qed.\n\n(* Comparison predicates. *)\n\nVariant leq_xor_gtn m n : nat -> nat -> nat -> nat -> bool -> bool -> Set :=\n  | LeqNotGtn of m <= n : leq_xor_gtn m n m m n n true false\n  | GtnNotLeq of n < m  : leq_xor_gtn m n n n m m false true.\n\nLemma leqP m n : leq_xor_gtn m n (minn n m) (minn m n) (maxn n m) (maxn m n)\n                                 (m <= n) (n < m).\nProof.\nrewrite (minnC m) /minn (maxnC m) /maxn ltnNge.\nby case le_mn: (m <= n); constructor; rewrite //= ltnNge le_mn.\nQed.\n\nVariant ltn_xor_geq m n : nat -> nat -> nat -> nat -> bool -> bool -> Set :=\n  | LtnNotGeq of m < n  : ltn_xor_geq m n m m n n false true\n  | GeqNotLtn of n <= m : ltn_xor_geq m n n n m m true false.\n\nLemma ltnP m n : ltn_xor_geq m n (minn n m) (minn m n) (maxn n m) (maxn m n)\n                                 (n <= m) (m < n).\nProof. by case: leqP; constructor. Qed.\n\nVariant eqn0_xor_gt0 n : bool -> bool -> Set :=\n  | Eq0NotPos of n = 0 : eqn0_xor_gt0 n true false\n  | PosNotEq0 of n > 0 : eqn0_xor_gt0 n false true.\n\nLemma posnP n : eqn0_xor_gt0 n (n == 0) (0 < n).\nProof. by case: n; constructor. Qed.\n\nVariant compare_nat m n : nat -> nat -> nat -> nat ->\n                          bool -> bool -> bool -> bool -> bool -> bool -> Set :=\n  | CompareNatLt of m < n :\n      compare_nat m n m m n n false false false true false true\n  | CompareNatGt of m > n :\n      compare_nat m n n n m m false false true false true false\n  | CompareNatEq of m = n :\n      compare_nat m n m m m m true true true true false false.\n\nLemma ltngtP m n :\n  compare_nat m n (minn n m) (minn m n) (maxn n m) (maxn m n)\n                  (n == m) (m == n) (n <= m) (m <= n) (n < m) (m < n).\nProof.\nrewrite !ltn_neqAle [_ == n]eq_sym; have [mn|] := ltnP m n.\n  by rewrite ltnW // gtn_eqF //; constructor.\nrewrite leq_eqVlt; case: ltnP; rewrite ?(orbT, orbF) => //= lt_nm eq_nm.\n  by rewrite ltn_eqF //; constructor.\nby rewrite eq_nm (eqP eq_nm); constructor.\nQed.\n\n(* Eliminating the idiom for structurally decreasing compare and subtract. *)\nLemma subn_if_gt T m n F (E : T) :\n  (if m.+1 - n is m'.+1 then F m' else E) = (if n <= m then F (m - n) else E).\nProof.\nby have [le_nm|/eqnP-> //] := leqP; rewrite -{1}(subnK le_nm) -addSn addnK.\nQed.\n\nNotation leqLHS := (X in (X <= _)%N)%pattern.\nNotation leqRHS := (X in (_ <= X)%N)%pattern.\nNotation ltnLHS := (X in (X < _)%N)%pattern.\nNotation ltnRHS := (X in (_ < X)%N)%pattern.\n\n(* Getting a concrete value from an abstract existence proof. *)\n\nSection ExMinn.\n\nVariable P : pred nat.\nHypothesis exP : exists n, P n.\n\nInductive acc_nat i : Prop := AccNat0 of P i | AccNatS of acc_nat i.+1.\n\nLemma find_ex_minn : {m | P m & forall n, P n -> n >= m}.\nProof.\nhave: forall n, P n -> n >= 0 by [].\nhave: acc_nat 0.\n  case exP => n; rewrite -(addn0 n); elim: n 0 => [|n IHn] j; first by left.\n  by rewrite addSnnS; right; apply: IHn.\nmove: 0; fix find_ex_minn 2 => m IHm m_lb; case Pm: (P m); first by exists m.\napply: find_ex_minn m.+1 _ _ => [|n Pn]; first by case: IHm; rewrite ?Pm.\nby rewrite ltn_neqAle m_lb //; case: eqP Pm => // -> /idP[].\nQed.\n\nDefinition ex_minn := s2val find_ex_minn.\n\nInductive ex_minn_spec : nat -> Type :=\n  ExMinnSpec m of P m & (forall n, P n -> n >= m) : ex_minn_spec m.\n\nLemma ex_minnP : ex_minn_spec ex_minn.\nProof. by rewrite /ex_minn; case: find_ex_minn. Qed.\n\nEnd ExMinn.\n\nSection ExMaxn.\n\nVariables (P : pred nat) (m : nat).\nHypotheses (exP : exists i, P i) (ubP : forall i, P i -> i <= m).\n\nLemma ex_maxn_subproof : exists i, P (m - i).\nProof. by case: exP => i Pi; exists (m - i); rewrite subKn ?ubP. Qed.\n\nDefinition ex_maxn := m - ex_minn ex_maxn_subproof.\n\nVariant ex_maxn_spec : nat -> Type :=\n  ExMaxnSpec i of P i & (forall j, P j -> j <= i) : ex_maxn_spec i.\n\nLemma ex_maxnP : ex_maxn_spec ex_maxn.\nProof.\nrewrite /ex_maxn; case: ex_minnP => i Pmi min_i; split=> // j Pj.\nhave le_i_mj: i <= m - j by rewrite min_i // subKn // ubP.\nrewrite -subn_eq0 subnBA ?(leq_trans le_i_mj) ?leq_subr //.\nby rewrite addnC -subnBA ?ubP.\nQed.\n\nEnd ExMaxn.\n\nLemma eq_ex_minn P Q exP exQ : P =1 Q -> @ex_minn P exP = @ex_minn Q exQ.\nProof.\nmove=> eqPQ; case: ex_minnP => m1 Pm1 m1_lb; case: ex_minnP => m2 Pm2 m2_lb.\nby apply/eqP; rewrite eqn_leq m1_lb (m2_lb, eqPQ) // -eqPQ.\nQed.\n\nLemma eq_ex_maxn (P Q : pred nat) m n exP ubP exQ ubQ :\n  P =1 Q -> @ex_maxn P m exP ubP = @ex_maxn Q n exQ ubQ.\nProof.\nmove=> eqPQ; case: ex_maxnP => i Pi max_i; case: ex_maxnP => j Pj max_j.\nby apply/eqP; rewrite eqn_leq max_i ?eqPQ // max_j -?eqPQ.\nQed.\n\nSection Iteration.\n\nVariable T : Type.\nImplicit Types m n : nat.\nImplicit Types x y : T.\nImplicit Types S : {pred T}.\n\nDefinition iter n f x :=\n  let fix loop m := if m is i.+1 then f (loop i) else x in loop n.\n\nDefinition iteri n f x :=\n  let fix loop m := if m is i.+1 then f i (loop i) else x in loop n.\n\nDefinition iterop n op x :=\n  let f i y := if i is 0 then x else op x y in iteri n f.\n\nLemma iterSr n f x : iter n.+1 f x = iter n f (f x).\nProof. by elim: n => //= n <-. Qed.\n\nLemma iterS n f x : iter n.+1 f x = f (iter n f x). Proof. by []. Qed.\n\nLemma iterD n m f x : iter (n + m) f x = iter n f (iter m f x).\nProof. by elim: n => //= n ->. Qed.\n\nLemma iteriS n f x : iteri n.+1 f x = f n (iteri n f x).\nProof. by []. Qed.\n\nLemma iteropS idx n op x : iterop n.+1 op x idx = iter n (op x) x.\nProof. by elim: n => //= n ->. Qed.\n\nLemma eq_iter f f' : f =1 f' -> forall n, iter n f =1 iter n f'.\nProof. by move=> eq_f n x; elim: n => //= n ->; rewrite eq_f. Qed.\n\nLemma iter_fix n f x : f x = x -> iter n f x = x.\nProof. by move=> fixf; elim: n => //= n ->. Qed.\n\nLemma eq_iteri f f' : f =2 f' -> forall n, iteri n f =1 iteri n f'.\nProof. by move=> eq_f n x; elim: n => //= n ->; rewrite eq_f. Qed.\n\nLemma eq_iterop n op op' : op =2 op' -> iterop n op =2 iterop n op'.\nProof. by move=> eq_op x; apply: eq_iteri; case. Qed.\n\nLemma iter_in f S i : {homo f : x / x \\in S} -> {homo iter i f : x / x \\in S}.\nProof. by move=> f_in x xS; elim: i => [|i /f_in]. Qed.\n\nEnd Iteration.\n\nLemma iter_succn m n : iter n succn m = m + n.\nProof. by rewrite addnC; elim: n => //= n ->. Qed.\n\nLemma iter_succn_0 n : iter n succn 0 = n.\nProof. exact: iter_succn. Qed.\n\nLemma iter_predn m n : iter n predn m = m - n.\nProof. by elim: n m => /= [|n IHn] m; rewrite ?subn0 // IHn subnS. Qed.\n\n(* Multiplication. *)\n\nDefinition muln_rec := mult.\nNotation \"m * n\" := (muln_rec m n) : nat_rec_scope.\n\nDefinition muln := nosimpl muln_rec.\nNotation \"m * n\" := (muln m n) : nat_scope.\n\nLemma multE : mult = muln.     Proof. by []. Qed.\nLemma mulnE : muln = muln_rec. Proof. by []. Qed.\n\nLemma mul0n : left_zero 0 muln.          Proof. by []. Qed.\nLemma muln0 : right_zero 0 muln.         Proof. by elim. Qed.\nLemma mul1n : left_id 1 muln.            Proof. exact: addn0. Qed.\nLemma mulSn m n : m.+1 * n = n + m * n.  Proof. by []. Qed.\nLemma mulSnr m n : m.+1 * n = m * n + n. Proof. exact: addnC. Qed.\n\nLemma mulnS m n : m * n.+1 = m + m * n.\nProof. by elim: m => // m; rewrite !mulSn !addSn addnCA => ->. Qed.\nLemma mulnSr m n : m * n.+1 = m * n + m.\nProof. by rewrite addnC mulnS. Qed.\n\nLemma iter_addn m n p : iter n (addn m) p = m * n + p.\nProof. by elim: n => /= [|n ->]; rewrite ?muln0 // mulnS addnA. Qed.\n\nLemma iter_addn_0 m n : iter n (addn m) 0 = m * n.\nProof. by rewrite iter_addn addn0. Qed.\n\nLemma muln1 : right_id 1 muln.\nProof. by move=> n; rewrite mulnSr muln0. Qed.\n\nLemma mulnC : commutative muln.\nProof.\nby move=> m n; elim: m => [|m]; rewrite (muln0, mulnS) // mulSn => ->.\nQed.\n\nLemma mulnDl : left_distributive muln addn.\nProof. by move=> m1 m2 n; elim: m1 => //= m1 IHm; rewrite -addnA -IHm. Qed.\n\nLemma mulnDr : right_distributive muln addn.\nProof. by move=> m n1 n2; rewrite !(mulnC m) mulnDl. Qed.\n\nLemma mulnBl : left_distributive muln subn.\nProof.\nmove=> m n [|p]; first by rewrite !muln0.\nby elim: m n => // [m IHm] [|n] //; rewrite mulSn subnDl -IHm.\nQed.\n\nLemma mulnBr : right_distributive muln subn.\nProof. by move=> m n p; rewrite !(mulnC m) mulnBl. Qed.\n\nLemma mulnA : associative muln.\nProof. by move=> m n p; elim: m => //= m; rewrite mulSn mulnDl => ->. Qed.\n\nLemma mulnCA : left_commutative muln.\nProof. by move=> m n1 n2; rewrite !mulnA (mulnC m). Qed.\n\nLemma mulnAC : right_commutative muln.\nProof. by move=> m n p; rewrite -!mulnA (mulnC n). Qed.\n\nLemma mulnACA : interchange muln muln.\nProof. by move=> m n p q; rewrite -!mulnA (mulnCA n). Qed.\n\nLemma muln_eq0 m n : (m * n == 0) = (m == 0) || (n == 0).\nProof. by case: m n => // m [|n] //=; rewrite muln0. Qed.\n\nLemma muln_eq1 m n : (m * n == 1) = (m == 1) && (n == 1).\nProof. by case: m n => [|[|m]] [|[|n]] //; rewrite muln0. Qed.\n\nLemma muln_gt0 m n : (0 < m * n) = (0 < m) && (0 < n).\nProof. by case: m n => // m [|n] //=; rewrite muln0. Qed.\n\nLemma leq_pmull m n : n > 0 -> m <= n * m.\nProof. by move/prednK <-; apply: leq_addr. Qed.\n\nLemma leq_pmulr m n : n > 0 -> m <= m * n.\nProof. by move/leq_pmull; rewrite mulnC. Qed.\n\nLemma leq_mul2l m n1 n2 : (m * n1 <= m * n2) = (m == 0) || (n1 <= n2).\nProof. by rewrite [LHS]/leq -mulnBr muln_eq0. Qed.\n\nLemma leq_mul2r m n1 n2 : (n1 * m <= n2 * m) = (m == 0) || (n1 <= n2).\nProof. by rewrite -!(mulnC m) leq_mul2l. Qed.\n\nLemma leq_mul m1 m2 n1 n2 : m1 <= n1 -> m2 <= n2 -> m1 * m2 <= n1 * n2.\nProof.\nmove=> le_mn1 le_mn2; apply (@leq_trans (m1 * n2)).\n  by rewrite leq_mul2l le_mn2 orbT.\nby rewrite leq_mul2r le_mn1 orbT.\nQed.\n\nLemma eqn_mul2l m n1 n2 : (m * n1 == m * n2) = (m == 0) || (n1 == n2).\nProof. by rewrite eqn_leq !leq_mul2l -orb_andr -eqn_leq. Qed.\n\nLemma eqn_mul2r m n1 n2 : (n1 * m == n2 * m) = (m == 0) || (n1 == n2).\nProof. by rewrite eqn_leq !leq_mul2r -orb_andr -eqn_leq. Qed.\n\nLemma leq_pmul2l m n1 n2 : 0 < m -> (m * n1 <= m * n2) = (n1 <= n2).\nProof. by move/prednK=> <-; rewrite leq_mul2l. Qed.\nArguments leq_pmul2l [m n1 n2].\n\nLemma leq_pmul2r m n1 n2 : 0 < m -> (n1 * m <= n2 * m) = (n1 <= n2).\nProof. by move/prednK <-; rewrite leq_mul2r. Qed.\nArguments leq_pmul2r [m n1 n2].\n\nLemma eqn_pmul2l m n1 n2 : 0 < m -> (m * n1 == m * n2) = (n1 == n2).\nProof. by move/prednK <-; rewrite eqn_mul2l. Qed.\nArguments eqn_pmul2l [m n1 n2].\n\nLemma eqn_pmul2r m n1 n2 : 0 < m -> (n1 * m == n2 * m) = (n1 == n2).\nProof. by move/prednK <-; rewrite eqn_mul2r. Qed.\nArguments eqn_pmul2r [m n1 n2].\n\nLemma ltn_mul2l m n1 n2 : (m * n1 < m * n2) = (0 < m) && (n1 < n2).\nProof. by rewrite lt0n !ltnNge leq_mul2l negb_or. Qed.\n\nLemma ltn_mul2r m n1 n2 : (n1 * m < n2 * m) = (0 < m) && (n1 < n2).\nProof. by rewrite lt0n !ltnNge leq_mul2r negb_or. Qed.\n\nLemma ltn_pmul2l m n1 n2 : 0 < m -> (m * n1 < m * n2) = (n1 < n2).\nProof. by move/prednK <-; rewrite ltn_mul2l. Qed.\nArguments ltn_pmul2l [m n1 n2].\n\nLemma ltn_pmul2r m n1 n2 : 0 < m -> (n1 * m < n2 * m) = (n1 < n2).\nProof. by move/prednK <-; rewrite ltn_mul2r. Qed.\nArguments ltn_pmul2r [m n1 n2].\n\nLemma ltn_Pmull m n : 1 < n -> 0 < m -> m < n * m.\nProof. by move=> lt1n m_gt0; rewrite -[ltnLHS]mul1n ltn_pmul2r. Qed.\n\nLemma ltn_Pmulr m n : 1 < n -> 0 < m -> m < m * n.\nProof. by move=> lt1n m_gt0; rewrite mulnC ltn_Pmull. Qed.\n\nLemma ltn_mul m1 m2 n1 n2 : m1 < n1 -> m2 < n2 -> m1 * m2 < n1 * n2.\nProof.\nmove=> lt_mn1 lt_mn2; apply (@leq_ltn_trans (m1 * n2)).\n  by rewrite leq_mul2l orbC ltnW.\nby rewrite ltn_pmul2r // (leq_trans _ lt_mn2).\nQed.\n\nLemma maxnMr : right_distributive muln maxn.\nProof. by case=> // m n1 n2; rewrite /maxn (fun_if (muln _)) ltn_pmul2l. Qed.\n\nLemma maxnMl : left_distributive muln maxn.\nProof. by move=> m1 m2 n; rewrite -!(mulnC n) maxnMr. Qed.\n\nLemma minnMr : right_distributive muln minn.\nProof. by case=> // m n1 n2; rewrite /minn (fun_if (muln _)) ltn_pmul2l. Qed.\n\nLemma minnMl : left_distributive muln minn.\nProof. by move=> m1 m2 n; rewrite -!(mulnC n) minnMr. Qed.\n\nLemma iterM (T : Type) (n m : nat) (f : T -> T) :\n  iter (n * m) f =1 iter n (iter m f).\nProof. by move=> x; elim: n => //= n <-; rewrite mulSn iterD. Qed.\n\n(* Exponentiation. *)\n\nDefinition expn_rec m n := iterop n muln m 1.\nNotation \"m ^ n\" := (expn_rec m n) : nat_rec_scope.\nDefinition expn := nosimpl expn_rec.\nNotation \"m ^ n\" := (expn m n) : nat_scope.\n\nLemma expnE : expn = expn_rec. Proof. by []. Qed.\n\nLemma expn0 m : m ^ 0 = 1. Proof. by []. Qed.\nLemma expn1 m : m ^ 1 = m. Proof. by []. Qed.\nLemma expnS m n : m ^ n.+1 = m * m ^ n. Proof. by case: n; rewrite ?muln1. Qed.\nLemma expnSr m n : m ^ n.+1 = m ^ n * m. Proof. by rewrite mulnC expnS. Qed.\n\nLemma iter_muln m n p : iter n (muln m) p = m ^ n * p.\nProof. by elim: n => /= [|n ->]; rewrite ?mul1n // expnS mulnA. Qed.\n\nLemma iter_muln_1 m n : iter n (muln m) 1 = m ^ n.\nProof. by rewrite iter_muln muln1. Qed.\n\nLemma exp0n n : 0 < n -> 0 ^ n = 0. Proof. by case: n => [|[]]. Qed.\n\nLemma exp1n n : 1 ^ n = 1.\nProof. by elim: n => // n; rewrite expnS mul1n. Qed.\n\nLemma expnD m n1 n2 : m ^ (n1 + n2) = m ^ n1 * m ^ n2.\nProof. by elim: n1 => [|n1 IHn]; rewrite !(mul1n, expnS) // IHn mulnA. Qed.\n\nLemma expnMn m1 m2 n : (m1 * m2) ^ n = m1 ^ n * m2 ^ n.\nProof. by elim: n => // n IHn; rewrite !expnS IHn -!mulnA (mulnCA m2). Qed.\n\nLemma expnM m n1 n2 : m ^ (n1 * n2) = (m ^ n1) ^ n2.\nProof.\nelim: n1 => [|n1 IHn]; first by rewrite exp1n.\nby rewrite expnD expnS expnMn IHn.\nQed.\n\nLemma expnAC m n1 n2 : (m ^ n1) ^ n2 = (m ^ n2) ^ n1.\nProof. by rewrite -!expnM mulnC. Qed.\n\nLemma expn_gt0 m n : (0 < m ^ n) = (0 < m) || (n == 0).\nProof.\nby case: m => [|m]; elim: n => //= n IHn; rewrite expnS // addn_gt0 IHn.\nQed.\n\nLemma expn_eq0 m e : (m ^ e == 0) = (m == 0) && (e > 0).\nProof. by rewrite !eqn0Ngt expn_gt0 negb_or -lt0n. Qed.\n\nLemma ltn_expl m n : 1 < m -> n < m ^ n.\nProof.\nmove=> m_gt1; elim: n => //= n; rewrite -(leq_pmul2l (ltnW m_gt1)) expnS.\nby apply: leq_trans; apply: ltn_Pmull.\nQed.\n\nLemma leq_exp2l m n1 n2 : 1 < m -> (m ^ n1 <= m ^ n2) = (n1 <= n2).\nProof.\nmove=> m_gt1; elim: n1 n2 => [|n1 IHn] [|n2] //; last 1 first.\n- by rewrite !expnS leq_pmul2l ?IHn // ltnW.\n- by rewrite expn_gt0 ltnW.\nby rewrite leqNgt (leq_trans m_gt1) // expnS leq_pmulr // expn_gt0 ltnW.\nQed.\n\nLemma ltn_exp2l m n1 n2 : 1 < m -> (m ^ n1 < m ^ n2) = (n1 < n2).\nProof. by move=> m_gt1; rewrite !ltnNge leq_exp2l. Qed.\n\nLemma eqn_exp2l m n1 n2 : 1 < m -> (m ^ n1 == m ^ n2) = (n1 == n2).\nProof. by move=> m_gt1; rewrite !eqn_leq !leq_exp2l. Qed.\n\nLemma expnI m : 1 < m -> injective (expn m).\nProof. by move=> m_gt1 e1 e2 /eqP; rewrite eqn_exp2l // => /eqP. Qed.\n\nLemma leq_pexp2l m n1 n2 : 0 < m -> n1 <= n2 -> m ^ n1 <= m ^ n2.\nProof. by case: m => [|[|m]] // _; [rewrite !exp1n | rewrite leq_exp2l]. Qed.\n\nLemma ltn_pexp2l m n1 n2 : 0 < m -> m ^ n1 < m ^ n2 -> n1 < n2.\nProof. by case: m => [|[|m]] // _; [rewrite !exp1n | rewrite ltn_exp2l]. Qed.\n\nLemma ltn_exp2r m n e : e > 0 -> (m ^ e < n ^ e) = (m < n).\nProof.\nmove=> e_gt0; apply/idP/idP=> [|ltmn].\n  rewrite !ltnNge; apply: contra => lemn.\n  by elim: e {e_gt0} => // e IHe; rewrite !expnS leq_mul.\nby elim: e e_gt0 => // [[|e] IHe] _; rewrite ?expn1 // ltn_mul // IHe.\nQed.\n\nLemma leq_exp2r m n e : e > 0 -> (m ^ e <= n ^ e) = (m <= n).\nProof. by move=> e_gt0; rewrite leqNgt ltn_exp2r // -leqNgt. Qed.\n\nLemma eqn_exp2r m n e : e > 0 -> (m ^ e == n ^ e) = (m == n).\nProof. by move=> e_gt0; rewrite !eqn_leq !leq_exp2r. Qed.\n\nLemma expIn e : e > 0 -> injective (expn^~ e).\nProof. by move=> e_gt1 m n /eqP; rewrite eqn_exp2r // => /eqP. Qed.\n\nLemma iterX (T : Type) (n m : nat) (f : T -> T) :\n  iter (n ^ m) f =1 iter m (iter n) f.\nProof. elim: m => //= m ihm x; rewrite expnS iterM; exact/eq_iter. Qed.\n\n(* Factorial. *)\n\nFixpoint fact_rec n := if n is n'.+1 then n * fact_rec n' else 1.\n\nDefinition factorial := nosimpl fact_rec.\n\nNotation \"n `!\" := (factorial n) (at level 2, format \"n `!\") : nat_scope.\n\nLemma factE : factorial = fact_rec. Proof. by []. Qed.\n\nLemma fact0 : 0`! = 1. Proof. by []. Qed.\n\nLemma factS n : (n.+1)`!  = n.+1 * n`!. Proof. by []. Qed.\n\nLemma fact_gt0 n : n`! > 0.\nProof. by elim: n => //= n IHn; rewrite muln_gt0. Qed.\n\nLemma fact_geq n : n <= n`!.\nProof. by case: n => // n; rewrite factS -(addn1 n) leq_pmulr ?fact_gt0. Qed.\n\nLemma ltn_fact m n : 0 < m -> m < n -> m`! < n`!.\nProof.\ncase: m n => // m n _; elim: n m => // n ih [|m] ?; last by rewrite ltn_mul ?ih.\nby rewrite -[_.+1]muln1 leq_mul ?fact_gt0.\nQed.\n\n(* Parity and bits. *)\n\nCoercion nat_of_bool (b : bool) := if b then 1 else 0.\n\nLemma leq_b1 (b : bool) : b <= 1. Proof. by case: b. Qed.\n\nLemma addn_negb (b : bool) : ~~ b + b = 1. Proof. by case: b. Qed.\n\nLemma eqb0 (b : bool) : (b == 0 :> nat) = ~~ b. Proof. by case: b. Qed.\n\nLemma eqb1 (b : bool) : (b == 1 :> nat) = b. Proof. by case: b. Qed.\n\nLemma lt0b (b : bool) : (b > 0) = b. Proof. by case: b. Qed.\n\nLemma sub1b (b : bool) : 1 - b = ~~ b. Proof. by case: b. Qed.\n\nLemma mulnb (b1 b2 : bool) : b1 * b2 = b1 && b2.\nProof. by case: b1; case: b2. Qed.\n\nLemma mulnbl (b : bool) n : b * n = (if b then n else 0).\nProof. by case: b; rewrite ?mul1n. Qed.\n\nLemma mulnbr (b : bool) n : n * b = (if b then n else 0).\nProof. by rewrite mulnC mulnbl. Qed.\n\nFixpoint odd n := if n is n'.+1 then ~~ odd n' else false.\n\nLemma oddS n : odd n.+1 = ~~ odd n. Proof. by []. Qed.\n\nLemma oddb (b : bool) : odd b = b. Proof. by case: b. Qed.\n\nLemma oddD m n : odd (m + n) = odd m (+) odd n.\nProof. by elim: m => [|m IHn] //=; rewrite -addTb IHn addbA addTb. Qed.\n\nLemma oddB m n : n <= m -> odd (m - n) = odd m (+) odd n.\nProof.\nby move=> le_nm; apply: (@canRL bool) (addbK _) _; rewrite -oddD subnK.\nQed.\n\nLemma oddN i m : odd m = false -> i <= m -> odd (m - i) = odd i.\nProof. by move=> oddm /oddB ->; rewrite oddm. Qed.\n\nLemma oddM m n : odd (m * n) = odd m && odd n.\nProof. by elim: m => //= m IHm; rewrite oddD -addTb andb_addl -IHm. Qed.\n\nLemma oddX m n : odd (m ^ n) = (n == 0) || odd m.\nProof. by elim: n => // n IHn; rewrite expnS oddM {}IHn orbC; case odd. Qed.\n\n(* Doubling. *)\n\nFixpoint double_rec n := if n is n'.+1 then n'.*2%Nrec.+2 else 0\nwhere \"n .*2\" := (double_rec n) : nat_rec_scope.\n\nDefinition double := nosimpl double_rec.\nNotation \"n .*2\" := (double n) : nat_scope.\n\nLemma doubleE : double = double_rec. Proof. by []. Qed.\n\nLemma double0 : 0.*2 = 0. Proof. by []. Qed.\n\nLemma doubleS n : n.+1.*2 = n.*2.+2. Proof. by []. Qed.\n\nLemma double_pred n : n.-1.*2 = n.*2.-2. Proof. by case: n. Qed.\n\nLemma addnn n : n + n = n.*2.\nProof. by apply: eqP; elim: n => // n IHn; rewrite addnS. Qed.\n\nLemma mul2n m : 2 * m = m.*2.\nProof. by rewrite mulSn mul1n addnn. Qed.\n\nLemma muln2 m : m * 2 = m.*2.\nProof. by rewrite mulnC mul2n. Qed.\n\nLemma doubleD m n : (m + n).*2 = m.*2 + n.*2.\nProof. by rewrite -!mul2n mulnDr. Qed.\n\nLemma doubleB m n : (m - n).*2 = m.*2 - n.*2.\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma leq_double m n : (m.*2 <= n.*2) = (m <= n).\nProof. by rewrite /leq -doubleB; case (m - n). Qed.\n\nLemma ltn_double m n : (m.*2 < n.*2) = (m < n).\nProof. by rewrite 2!ltnNge leq_double. Qed.\n\nLemma ltn_Sdouble m n : (m.*2.+1 < n.*2) = (m < n).\nProof. by rewrite -doubleS leq_double. Qed.\n\nLemma leq_Sdouble m n : (m.*2 <= n.*2.+1) = (m <= n).\nProof. by rewrite leqNgt ltn_Sdouble -leqNgt. Qed.\n\nLemma odd_double n : odd n.*2 = false.\nProof. by rewrite -addnn oddD addbb. Qed.\n\nLemma double_gt0 n : (0 < n.*2) = (0 < n).\nProof. by case: n. Qed.\n\nLemma double_eq0 n : (n.*2 == 0) = (n == 0).\nProof. by case: n. Qed.\n\nLemma doubleMl m n : (m * n).*2 = m.*2 * n.\nProof. by rewrite -!mul2n mulnA. Qed.\n\nLemma doubleMr m n : (m * n).*2 = m * n.*2.\nProof. by rewrite -!muln2 mulnA. Qed.\n\n(* Halving. *)\n\nFixpoint half (n : nat) : nat := if n is n'.+1 then uphalf n' else n\nwith   uphalf (n : nat) : nat := if n is n'.+1 then n'./2.+1 else n\nwhere \"n ./2\" := (half n) : nat_scope.\n\nLemma uphalfE n : uphalf n = n.+1./2.\nProof. by []. Qed.\n\nLemma doubleK : cancel double half.\nProof. by elim=> //= n ->. Qed.\n\nDefinition half_double := doubleK.\nDefinition double_inj := can_inj doubleK.\n\nLemma uphalf_double n : uphalf n.*2 = n.\nProof. by elim: n => //= n ->. Qed.\n\nLemma uphalf_half n : uphalf n = odd n + n./2.\nProof. by elim: n => //= n ->; rewrite addnA addn_negb. Qed.\n\nLemma odd_double_half n : odd n + n./2.*2 = n.\nProof.\nby elim: n => //= n {3}<-; rewrite uphalf_half doubleD; case (odd n).\nQed.\n\nLemma halfK n : n./2.*2 = n - odd n.\nProof. by rewrite -[n in n - _]odd_double_half addnC addnK. Qed.\n\nLemma uphalfK n : (uphalf n).*2 = odd n + n.\nProof. by rewrite uphalfE halfK/=; case: odd; rewrite ?subn1. Qed.\n\nLemma odd_halfK n : odd n -> n./2.*2 = n.-1.\nProof. by rewrite halfK => ->; rewrite subn1. Qed.\n\nLemma even_halfK n : ~~ odd n -> n./2.*2 = n.\nProof. by rewrite halfK => /negbTE->; rewrite subn0. Qed.\n\nLemma odd_uphalfK n : odd n -> (uphalf n).*2 = n.+1.\nProof. by rewrite uphalfK => ->. Qed.\n\nLemma even_uphalfK n : ~~ odd n -> (uphalf n).*2 = n.\nProof. by rewrite uphalfK => /negbTE->. Qed.\n\nLemma half_bit_double n (b : bool) : (b + n.*2)./2 = n.\nProof. by case: b; rewrite /= (half_double, uphalf_double). Qed.\n\nLemma halfD m n : (m + n)./2 = (odd m && odd n) + (m./2 + n./2).\nProof.\nrewrite -[n in LHS]odd_double_half addnCA.\nrewrite -[m in LHS]odd_double_half -addnA -doubleD.\nby do 2!case: odd; rewrite /= ?add0n ?half_double ?uphalf_double.\nQed.\n\nLemma half_leq m n : m <= n -> m./2 <= n./2.\nProof. by move/subnK <-; rewrite halfD addnA leq_addl. Qed.\n\nLemma geq_half_double m n : (m <= n./2) = (m.*2 <= n).\nProof.\nrewrite -[X in _.*2 <= X]odd_double_half.\ncase: odd; last by rewrite leq_double.\nby case: m => // m; rewrite doubleS ltnS ltn_double.\nQed.\n\nLemma ltn_half_double m n : (m./2 < n) = (m < n.*2).\nProof. by rewrite ltnNge geq_half_double -ltnNge. Qed.\n\nLemma leq_half_double m n : (m./2 <= n) = (m <= n.*2.+1).\nProof. by case: m => [|[|m]] //; rewrite ltnS ltn_half_double. Qed.\n\nLemma gtn_half_double m n : (n < m./2) = (n.*2.+1 < m).\nProof. by rewrite ltnNge leq_half_double -ltnNge. Qed.\n\nLemma half_gt0 n : (0 < n./2) = (1 < n).\nProof. by case: n => [|[]]. Qed.\n\nLemma uphalf_leq m n : m <= n -> uphalf m <= uphalf n.\nProof.\nmove/subnK <-; rewrite !uphalf_half oddD halfD !addnA.\nby do 2 case: odd; apply: leq_addl.\nQed.\n\nLemma leq_uphalf_double m n : (uphalf m <= n) = (m <= n.*2).\nProof. by rewrite uphalfE leq_half_double. Qed.\n\nLemma geq_uphalf_double m n : (m <= uphalf n) = (m.*2 <= n.+1).\nProof. by rewrite uphalfE geq_half_double. Qed.\n\nLemma gtn_uphalf_double m n : (n < uphalf m) = (n.*2 < m).\nProof. by rewrite uphalfE gtn_half_double. Qed.\n\nLemma ltn_uphalf_double m n : (uphalf m < n) = (m.+1 < n.*2).\nProof. by rewrite uphalfE ltn_half_double. Qed.\n\nLemma uphalf_gt0 n : (0 < uphalf n) = (0 < n).\nProof. by case: n. Qed.\n\nLemma odd_geq m n : odd n -> (m <= n) = (m./2.*2 <= n).\nProof.\nmove=> odd_n; rewrite -[m in LHS]odd_double_half -[n]odd_double_half odd_n.\nby case: (odd m); rewrite // leq_Sdouble ltnS leq_double.\nQed.\n\nLemma odd_ltn m n : odd n -> (n < m) = (n < m./2.*2).\nProof. by move=> odd_n; rewrite !ltnNge odd_geq. Qed.\n\nLemma odd_gt0 n : odd n -> n > 0. Proof. by case: n. Qed.\n\nLemma odd_gt2 n : odd n -> n > 1 -> n > 2.\nProof. by move=> odd_n n_gt1; rewrite odd_geq. Qed.\n\n(* Squares and square identities. *)\n\nLemma mulnn m : m * m = m ^ 2.\nProof. by rewrite !expnS muln1. Qed.\n\nLemma sqrnD m n : (m + n) ^ 2 = m ^ 2 + n ^ 2 + 2 * (m * n).\nProof.\nrewrite -!mulnn mul2n mulnDr !mulnDl (mulnC n) -!addnA.\nby congr (_ + _); rewrite addnA addnn addnC.\nQed.\n\nLemma sqrnB m n : n <= m -> (m - n) ^ 2 = m ^ 2 + n ^ 2 - 2 * (m * n).\nProof.\nmove/subnK <-; rewrite addnK sqrnD -addnA -addnACA -addnA.\nby rewrite addnn -mul2n -mulnDr -mulnDl addnK.\nQed.\n\nLemma sqrnD_sub m n : n <= m -> (m + n) ^ 2 - 4 * (m * n) = (m - n) ^ 2.\nProof.\nmove=> le_nm; rewrite -[4]/(2 * 2) -mulnA mul2n -addnn subnDA.\nby rewrite sqrnD addnK sqrnB.\nQed.\n\nLemma subn_sqr m n : m ^ 2 - n ^ 2 = (m - n) * (m + n).\nProof. by rewrite mulnBl !mulnDr addnC (mulnC m) subnDl. Qed.\n\nLemma ltn_sqr m n : (m ^ 2 < n ^ 2) = (m < n).\nProof. by rewrite ltn_exp2r. Qed.\n\nLemma leq_sqr m n : (m ^ 2 <= n ^ 2) = (m <= n).\nProof. by rewrite leq_exp2r. Qed.\n\nLemma sqrn_gt0 n : (0 < n ^ 2) = (0 < n).\nProof. exact: (ltn_sqr 0). Qed.\n\nLemma eqn_sqr m n : (m ^ 2 == n ^ 2) = (m == n).\nProof. by rewrite eqn_exp2r. Qed.\n\nLemma sqrn_inj : injective (expn ^~ 2).\nProof. exact: expIn. Qed.\n\n(* Almost strict inequality: an inequality that is strict unless some    *)\n(* specific condition holds, such as the Cauchy-Schwartz or the AGM      *)\n(* inequality (we only prove the order-2 AGM here; the general one       *)\n(* requires sequences).                                                  *)\n(*   We formalize the concept as a rewrite multirule, that can be used   *)\n(* both to rewrite the non-strict inequality to true, and the equality   *)\n(* to the specific condition (for strict inequalities use the ltn_neqAle *)\n(* lemma); in addition, the conditional equality also coerces to a       *)\n(* non-strict one.                                                       *)\n\nDefinition leqif m n C := ((m <= n) * ((m == n) = C))%type.\n\nNotation \"m <= n ?= 'iff' C\" := (leqif m n C) : nat_scope.\n\nCoercion leq_of_leqif m n C (H : m <= n ?= iff C) := H.1 : m <= n.\n\nLemma leqifP m n C : reflect (m <= n ?= iff C) (if C then m == n else m < n).\nProof.\nrewrite ltn_neqAle; apply: (iffP idP) => [|lte]; last by rewrite !lte; case C.\nby case C => [/eqP-> | /andP[/negPf]]; split=> //; apply: eqxx.\nQed.\n\nLemma leqif_refl m C : reflect (m <= m ?= iff C) C.\nProof. by apply: (iffP idP) => [-> | <-] //; split; rewrite ?eqxx. Qed.\n\nLemma leqif_trans m1 m2 m3 C12 C23 :\n  m1 <= m2 ?= iff C12 -> m2 <= m3 ?= iff C23 -> m1 <= m3 ?= iff C12 && C23.\nProof.\nmove=> ltm12 ltm23; apply/leqifP; rewrite -ltm12.\nhave [->|eqm12] := eqVneq; first by rewrite ltn_neqAle !ltm23 andbT; case C23.\nby rewrite (@leq_trans m2) ?ltm23 // ltn_neqAle eqm12 ltm12.\nQed.\n\nLemma mono_leqif f : {mono f : m n / m <= n} ->\n  forall m n C, (f m <= f n ?= iff C) = (m <= n ?= iff C).\nProof. by move=> f_mono m n C; rewrite /leqif !eqn_leq !f_mono. Qed.\n\nLemma leqif_geq m n : m <= n -> m <= n ?= iff (m >= n).\nProof. by move=> lemn; split=> //; rewrite eqn_leq lemn. Qed.\n\nLemma leqif_eq m n : m <= n -> m <= n ?= iff (m == n).\nProof. by []. Qed.\n\nLemma geq_leqif a b C : a <= b ?= iff C -> (b <= a) = C.\nProof. by case=> le_ab; rewrite eqn_leq le_ab. Qed.\n\nLemma ltn_leqif a b C : a <= b ?= iff C -> (a < b) = ~~ C.\nProof. by move=> le_ab; rewrite ltnNge (geq_leqif le_ab). Qed.\n\nLemma ltnNleqif x y C : x <= y ?= iff ~~ C -> (x < y) = C.\nProof. by move=> /ltn_leqif; rewrite negbK. Qed.\n\nLemma eq_leqif x y C : x <= y ?= iff C -> (x == y) = C.\nProof. by move=> /leqifP; case: C ltngtP => [] []. Qed.\n\nLemma eqTleqif x y C : x <= y ?= iff C -> C -> x = y.\nProof. by move=> /eq_leqif<-/eqP. Qed.\n\nLemma leqif_add m1 n1 C1 m2 n2 C2 :\n    m1 <= n1 ?= iff C1 -> m2 <= n2 ?= iff C2 ->\n  m1 + m2 <= n1 + n2 ?= iff C1 && C2.\nProof.\nrewrite -(mono_leqif (leq_add2r m2)) -(mono_leqif (leq_add2l n1) m2).\nexact: leqif_trans.\nQed.\n\nLemma leqif_mul m1 n1 C1 m2 n2 C2 :\n    m1 <= n1 ?= iff C1 -> m2 <= n2 ?= iff C2 ->\n  m1 * m2 <= n1 * n2 ?= iff (n1 * n2 == 0) || (C1 && C2).\nProof.\ncase: n1 => [|n1] le1; first by case: m1 le1 => [|m1] [_ <-] //.\ncase: n2 m2 => [|n2] [|m2] /=; try by case=> // _ <-; rewrite !muln0 ?andbF.\nhave /leq_pmul2l-/mono_leqif<-: 0 < n1.+1 by [].\nby apply: leqif_trans; have /leq_pmul2r-/mono_leqif->: 0 < m2.+1.\nQed.\n\nLemma nat_Cauchy m n : 2 * (m * n) <= m ^ 2 + n ^ 2 ?= iff (m == n).\nProof.\nwithout loss le_nm: m n / n <= m.\n  by have [?|/ltnW ?] := leqP n m; last rewrite eq_sym addnC (mulnC m); apply.\napply/leqifP; have [-> | ne_mn] := eqVneq; first by rewrite addnn mul2n.\nby rewrite -subn_gt0 -sqrnB // sqrn_gt0 subn_gt0 ltn_neqAle eq_sym ne_mn.\nQed.\n\nLemma nat_AGM2 m n : 4 * (m * n) <= (m + n) ^ 2 ?= iff (m == n).\nProof.\nrewrite -[4]/(2 * 2) -mulnA mul2n -addnn sqrnD; apply/leqifP.\nby rewrite ltn_add2r eqn_add2r ltn_neqAle !nat_Cauchy; case: eqVneq.\nQed.\n\nSection ContraLeq.\nImplicit Types (b : bool) (m n : nat) (P : Prop).\n\nLemma contraTleq b m n : (n < m -> ~~ b) -> (b -> m <= n).\nProof. by rewrite ltnNge; apply: contraTT. Qed.\n\nLemma contraTltn b m n : (n <= m -> ~~ b) -> (b -> m < n).\nProof. by rewrite ltnNge; apply: contraTN. Qed.\n\nLemma contraPleq P m n : (n < m -> ~ P) -> (P -> m <= n).\nProof. by rewrite ltnNge; apply: contraPT. Qed.\n\nLemma contraPltn P m n : (n <= m -> ~ P) -> (P -> m < n).\nProof. by rewrite ltnNge; apply: contraPN. Qed.\n\nLemma contraNleq b m n : (n < m -> b) -> (~~ b -> m <= n).\nProof. by rewrite ltnNge; apply: contraNT. Qed.\n\nLemma contraNltn b m n : (n <= m -> b) -> (~~ b -> m < n).\nProof. by rewrite ltnNge; apply: contraNN. Qed.\n\nLemma contra_not_leq P m n : (n < m -> P) -> (~ P -> m <= n).\nProof. by rewrite ltnNge; apply: contra_notT. Qed.\n\nLemma contra_not_ltn P m n : (n <= m -> P) -> (~ P -> m < n).\nProof. by rewrite ltnNge; apply: contra_notN. Qed.\n\nLemma contraFleq b m n : (n < m -> b) -> (b = false -> m <= n).\nProof. by rewrite ltnNge; apply: contraFT. Qed.\n\nLemma contraFltn b m n : (n <= m -> b) -> (b = false -> m < n).\nProof. by rewrite ltnNge; apply: contraFN. Qed.\n\nLemma contra_leqT b m n : (~~ b -> m < n) -> (n <= m -> b).\nProof. by rewrite ltnNge; apply: contraTT. Qed.\n\nLemma contra_ltnT b m n : (~~ b -> m <= n) -> (n < m -> b).\nProof. by rewrite ltnNge; apply: contraNT. Qed.\n\nLemma contra_leqN b m n : (b -> m < n) -> (n <= m -> ~~ b).\nProof. by rewrite ltnNge; apply: contraTN. Qed.\n\nLemma contra_ltnN b m n : (b -> m <= n) -> (n < m -> ~~ b).\nProof. by rewrite ltnNge; apply: contraNN. Qed.\n\nLemma contra_leq_not P m n : (P -> m < n) -> (n <= m -> ~ P).\nProof. by rewrite ltnNge; apply: contraTnot. Qed.\n\nLemma contra_ltn_not P m n : (P -> m <= n) -> (n < m -> ~ P).\nProof. by rewrite ltnNge; apply: contraNnot. Qed.\n\nLemma contra_leqF b m n : (b -> m < n) -> (n <= m -> b = false).\nProof. by rewrite ltnNge; apply: contraTF. Qed.\n\nLemma contra_ltnF b m n : (b -> m <= n) -> (n < m -> b = false).\nProof. by rewrite ltnNge; apply: contraNF. Qed.\n\nLemma contra_leq m n p q : (q < p -> n < m) -> (m <= n -> p <= q).\nProof. by rewrite !ltnNge; apply: contraTT. Qed.\n\nLemma contra_leq_ltn m n p q : (q <= p -> n < m) -> (m <= n -> p < q).\nProof. by rewrite !ltnNge; apply: contraTN. Qed.\n\nLemma contra_ltn_leq m n p q : (q < p -> n <= m) -> (m < n -> p <= q).\nProof. by rewrite !ltnNge; apply: contraNT. Qed.\n\nLemma contra_ltn m n p q : (q <= p -> n <= m) -> (m < n -> p < q).\nProof. by rewrite !ltnNge; apply: contraNN. Qed.\n\nEnd ContraLeq.\n\nSection Monotonicity.\nVariable T : Type.\n\nLemma homo_ltn_in (D : {pred nat}) (f : nat -> T) (r : T -> T -> Prop) :\n  (forall y x z, r x y -> r y z -> r x z) ->\n  {in D &, forall i j k, i < k < j -> k \\in D} ->\n  {in D, forall i, i.+1 \\in D -> r (f i) (f i.+1)} ->\n  {in D &, {homo f : i j / i < j >-> r i j}}.\nProof.\nmove=> r_trans Dcx r_incr i j iD jD lt_ij; move: (lt_ij) (jD) => /subnKC<-.\nelim: (_ - _) => [|k ihk]; first by rewrite addn0 => Dsi; apply: r_incr.\nmove=> DSiSk [: DSik]; apply: (r_trans _ _ _ (ihk _)); rewrite ?addnS.\n  by abstract: DSik; apply: (Dcx _ _ iD DSiSk); rewrite ltn_addr ?addnS /=.\nby apply: r_incr; rewrite -?addnS.\nQed.\n\nLemma homo_ltn (f : nat -> T) (r : T -> T -> Prop) :\n  (forall y x z, r x y -> r y z -> r x z) ->\n  (forall i, r (f i) (f i.+1)) -> {homo f : i j / i < j >-> r i j}.\nProof. by move=> /(@homo_ltn_in predT f) fr fS i j; apply: fr. Qed.\n\nLemma homo_leq_in (D : {pred nat}) (f : nat -> T) (r : T -> T -> Prop) :\n  (forall x, r x x) -> (forall y x z, r x y -> r y z -> r x z) ->\n  {in D &, forall i j k, i < k < j -> k \\in D} ->\n  {in D, forall i, i.+1 \\in D -> r (f i) (f i.+1)} ->\n  {in D &, {homo f : i j / i <= j >-> r i j}}.\nProof.\nmove=> r_refl r_trans Dcx /(homo_ltn_in r_trans Dcx) lt_r i j iD jD.\ncase: ltngtP => [? _||->] //; exact: lt_r.\nQed.\n\nLemma homo_leq (f : nat -> T) (r : T -> T -> Prop) :\n   (forall x, r x x) -> (forall y x z, r x y -> r y z -> r x z) ->\n  (forall i, r (f i) (f i.+1)) -> {homo f : i j / i <= j >-> r i j}.\nProof. by move=> rrefl /(@homo_leq_in predT f r) fr fS i j; apply: fr. Qed.\n\nSection NatToNat.\nVariable (f : nat -> nat).\n\n(****************************************************************************)\n(* This listing of \"Let\"s factor out the required premises for the          *)\n(* subsequent lemmas, putting them in the context so that \"done\" solves the *)\n(* goals quickly                                                            *)\n(****************************************************************************)\n\nLet ltn_neqAle := ltn_neqAle.\nLet gtn_neqAge x y : (y < x) = (x != y) && (y <= x).\nProof. by rewrite ltn_neqAle eq_sym. Qed.\nLet anti_leq := anti_leq.\nLet anti_geq : antisymmetric geq.\nProof. by move=> m n /=; rewrite andbC => /anti_leq. Qed.\nLet leq_total := leq_total.\n\nLemma ltnW_homo : {homo f : m n / m < n} -> {homo f : m n / m <= n}.\nProof. exact: homoW. Qed.\n\nLemma inj_homo_ltn : injective f -> {homo f : m n / m <= n} ->\n  {homo f : m n / m < n}.\nProof. exact: inj_homo. Qed.\n\nLemma ltnW_nhomo : {homo f : m n /~ m < n} -> {homo f : m n /~ m <= n}.\nProof. exact: homoW. Qed.\n\nLemma inj_nhomo_ltn : injective f -> {homo f : m n /~ m <= n} ->\n  {homo f : m n /~ m < n}.\nProof. exact: inj_homo. Qed.\n\nLemma incn_inj : {mono f : m n / m <= n} -> injective f.\nProof. exact: mono_inj. Qed.\n\nLemma decn_inj : {mono f : m n /~ m <= n} -> injective f.\nProof. exact: mono_inj. Qed.\n\nLemma leqW_mono : {mono f : m n / m <= n} -> {mono f : m n / m < n}.\nProof. exact: anti_mono. Qed.\n\nLemma leqW_nmono : {mono f : m n /~ m <= n} -> {mono f : m n /~ m < n}.\nProof. exact: anti_mono. Qed.\n\nLemma leq_mono : {homo f : m n / m < n} -> {mono f : m n / m <= n}.\nProof. exact: total_homo_mono. Qed.\n\nLemma leq_nmono : {homo f : m n /~ m < n} -> {mono f : m n /~ m <= n}.\nProof. exact: total_homo_mono. Qed.\n\nVariables (D D' : {pred nat}).\n\nLemma ltnW_homo_in : {in D & D', {homo f : m n / m < n}} ->\n  {in D & D', {homo f : m n / m <= n}}.\nProof. exact: homoW_in. Qed.\n\nLemma ltnW_nhomo_in : {in D & D', {homo f : m n /~ m < n}} ->\n                 {in D & D', {homo f : m n /~ m <= n}}.\nProof. exact: homoW_in. Qed.\n\nLemma inj_homo_ltn_in : {in D & D', injective f} ->\n                        {in D & D', {homo f : m n / m <= n}} ->\n  {in D & D', {homo f : m n / m < n}}.\nProof. exact: inj_homo_in. Qed.\n\nLemma inj_nhomo_ltn_in : {in D & D', injective f} ->\n                        {in D & D', {homo f : m n /~ m <= n}} ->\n  {in D & D', {homo f : m n /~ m < n}}.\nProof. exact: inj_homo_in. Qed.\n\nLemma incn_inj_in : {in D &, {mono f : m n / m <= n}} ->\n  {in D &, injective f}.\nProof. exact: mono_inj_in. Qed.\n\nLemma decn_inj_in : {in D &, {mono f : m n /~ m <= n}} ->\n  {in D &, injective f}.\nProof. exact: mono_inj_in. Qed.\n\nLemma leqW_mono_in : {in D &, {mono f : m n / m <= n}} ->\n  {in D &, {mono f : m n / m < n}}.\nProof. exact: anti_mono_in. Qed.\n\nLemma leqW_nmono_in : {in D &, {mono f : m n /~ m <= n}} ->\n  {in D &, {mono f : m n /~ m < n}}.\nProof. exact: anti_mono_in. Qed.\n\nLemma leq_mono_in : {in D &, {homo f : m n / m < n}} ->\n  {in D &, {mono f : m n / m <= n}}.\nProof. exact: total_homo_mono_in. Qed.\n\nLemma leq_nmono_in : {in D &, {homo f : m n /~ m < n}} ->\n  {in D &, {mono f : m n /~ m <= n}}.\nProof. exact: total_homo_mono_in. Qed.\n\nEnd NatToNat.\nEnd Monotonicity.\n\nLemma leq_pfact : {in [pred n | 0 < n] &, {mono factorial : m n / m <= n}}.\nProof. by apply: leq_mono_in => n m n0 m0; apply: ltn_fact. Qed.\n\nLemma leq_fact : {homo factorial : m n / m <= n}.\nProof.\nby move=> [m|m n mn]; rewrite ?fact_gt0// leq_pfact// inE (leq_trans _ mn).\nQed.\n\nLemma ltn_pfact : {in [pred n | 0 < n] &, {mono factorial : m n / m < n}}.\nProof. exact/leqW_mono_in/leq_pfact. Qed.\n\n(* Support for larger integers. The normal definitions of +, - and even  *)\n(* IO are unsuitable for Peano integers larger than 2000 or so because   *)\n(* they are not tail-recursive. We provide a workaround module, along    *)\n(* with a rewrite multirule to change the tailrec operators to the       *)\n(* normal ones. We handle IO via the NatBin module, but provide our      *)\n(* own (more efficient) conversion functions.                            *)\n\nModule NatTrec.\n\n(*   Usage:                                             *)\n(*     Import NatTrec.                                  *)\n(*        in section defining functions, rebinds all    *)\n(*        non-tail recursive operators.                 *)\n(*     rewrite !trecE.                                  *)\n(*        in the correctness proof, restores operators  *)\n\nFixpoint add m n := if m is m'.+1 then m' + n.+1 else n\nwhere \"n + m\" := (add n m) : nat_scope.\n\nFixpoint add_mul m n s := if m is m'.+1 then add_mul m' n (n + s) else s.\n\nDefinition mul m n := if m is m'.+1 then add_mul m' n n else 0.\n\nNotation \"n * m\" := (mul n m) : nat_scope.\n\nFixpoint mul_exp m n p := if n is n'.+1 then mul_exp m n' (m * p) else p.\n\nDefinition exp m n := if n is n'.+1 then mul_exp m n' m else 1.\n\nNotation \"n ^ m\" := (exp n m) : nat_scope.\n\nLocal Notation oddn := odd.\nFixpoint odd n := if n is n'.+2 then odd n' else eqn n 1.\n\nLocal Notation doublen := double.\nDefinition double n := if n is n'.+1 then n' + n.+1 else 0.\nNotation \"n .*2\" := (double n) : nat_scope.\n\nLemma addE : add =2 addn.\nProof. by elim=> //= n IHn m; rewrite IHn addSnnS. Qed.\n\nLemma doubleE : double =1 doublen.\nProof. by case=> // n; rewrite -addnn -addE. Qed.\n\nLemma add_mulE n m s : add_mul n m s = addn (muln n m) s.\nProof. by elim: n => //= n IHn in m s *; rewrite IHn addE addnCA addnA. Qed.\n\nLemma mulE : mul =2 muln.\nProof. by case=> //= n m; rewrite add_mulE addnC. Qed.\n\nLemma mul_expE m n p : mul_exp m n p = muln (expn m n) p.\nProof.\nby elim: n => [|n IHn] in p *; rewrite ?mul1n //= expnS IHn mulE mulnCA mulnA.\nQed.\n\nLemma expE : exp =2 expn.\nProof. by move=> m [|n] //=; rewrite mul_expE expnS mulnC. Qed.\n\nLemma oddE : odd =1 oddn.\nProof.\nmove=> n; rewrite -[n in LHS]odd_double_half addnC.\nby elim: n./2 => //=; case (oddn n).\nQed.\n\nDefinition trecE := (addE, (doubleE, oddE), (mulE, add_mulE, (expE, mul_expE))).\n\nEnd NatTrec.\n\nNotation natTrecE := NatTrec.trecE.\n\nLemma eq_binP : Equality.axiom N.eqb.\nProof.\nmove=> p q; apply: (iffP idP) => [|<-]; last by case: p => //; elim.\nby case: q; case: p => //; elim=> [p IHp|p IHp|] [q|q|] //= /IHp [->].\nQed.\n\nCanonical bin_nat_eqMixin := EqMixin eq_binP.\nCanonical bin_nat_eqType := Eval hnf in EqType N bin_nat_eqMixin.\n\nArguments N.eqb !n !m.\n\nSection NumberInterpretation.\n\nImport BinPos.\n\nSection Trec.\n\nImport NatTrec.\n\nFixpoint nat_of_pos p0 :=\n  match p0 with\n  | xO p => (nat_of_pos p).*2\n  | xI p => (nat_of_pos p).*2.+1\n  | xH   => 1\n  end.\n\nEnd Trec.\n\nLocal Coercion nat_of_pos : positive >-> nat.\n\nCoercion nat_of_bin b := if b is Npos p then p : nat else 0.\n\nFixpoint pos_of_nat n0 m0 :=\n  match n0, m0 with\n  | n.+1, m.+2 => pos_of_nat n m\n  | n.+1,    1 => xO (pos_of_nat n n)\n  | n.+1,    0 => xI (pos_of_nat n n)\n  |    0,    _ => xH\n  end.\n\nDefinition bin_of_nat n0 := if n0 is n.+1 then Npos (pos_of_nat n n) else 0%num.\n\nLemma bin_of_natK : cancel bin_of_nat nat_of_bin.\nProof.\nhave sub2nn n : n.*2 - n = n by rewrite -addnn addKn.\ncase=> //= n; rewrite -[n in RHS]sub2nn.\nby elim: n {2 4}n => // m IHm [|[|n]] //=; rewrite IHm // natTrecE sub2nn.\nQed.\n\nLemma nat_of_binK : cancel nat_of_bin bin_of_nat.\nProof.\ncase=> //=; elim=> //= p; case: (nat_of_pos p) => //= n [<-].\n  by rewrite natTrecE !addnS {2}addnn; elim: {1 3}n.\nby rewrite natTrecE addnS /= addnS {2}addnn; elim: {1 3}n.\nQed.\n\nLemma nat_of_succ_pos p : Pos.succ p = p.+1 :> nat.\nProof. by elim: p => //= p ->; rewrite !natTrecE. Qed.\n\nLemma nat_of_add_pos p q : (p + q)%positive = p + q :> nat.\nProof.\napply: @fst _ (Pplus_carry p q = (p + q).+1 :> nat) _.\nelim: p q => [p IHp|p IHp|] [q|q|] //=; rewrite !natTrecE //;\n  by rewrite ?IHp ?nat_of_succ_pos ?(doubleS, doubleD, addn1, addnS).\nQed.\n\nLemma nat_of_mul_pos p q : (p * q)%positive = p * q :> nat.\nProof.\nelim: p => [p IHp|p IHp|] /=; rewrite ?mul1n //;\n  by rewrite ?nat_of_add_pos /= !natTrecE IHp doubleMl.\nQed.\n\nLemma nat_of_add_bin b1 b2 : (b1 + b2)%num = b1 + b2 :> nat.\nProof. by case: b1 b2 => [|p] [|q]; rewrite ?addn0 //= nat_of_add_pos. Qed.\n\nLemma nat_of_mul_bin b1 b2 : (b1 * b2)%num = b1 * b2 :> nat.\nProof. by case: b1 b2 => [|p] [|q]; rewrite ?muln0 //= nat_of_mul_pos. Qed.\n\nLemma nat_of_exp_bin n (b : N) : n ^ b = pow_N 1 muln n b.\nProof.\nby case: b; last (elim=> //= p <-; rewrite natTrecE mulnn -expnM muln2 ?expnS).\nQed.\n\nEnd NumberInterpretation.\n\n(* Big(ger) nat IO; usage:                              *)\n(*     Num 1 072 399                                    *)\n(*        to create large numbers for test cases        *)\n(* Eval compute in [Num of some expression]             *)\n(*        to display the result of an expression that   *)\n(*        returns a larger integer.                     *)\n\nRecord number : Type := Num {bin_of_number :> N}.\n\nDefinition extend_number (nn : number) m := Num (nn * 1000 + bin_of_nat m).\n\nCoercion extend_number : number >-> Funclass.\n\nCanonical number_subType := [newType for bin_of_number].\nDefinition number_eqMixin := Eval hnf in [eqMixin of number by <:].\nCanonical number_eqType := Eval hnf in EqType number number_eqMixin.\n\nNotation \"[ 'Num' 'of' e ]\" := (Num (bin_of_nat e))\n  (at level 0, format \"[ 'Num'  'of'  e ]\") : nat_scope.\n\n(* Interface to ring/ring_simplify tactics *)\n\nLemma nat_semi_ring : semi_ring_theory 0 1 addn muln (@eq _).\nProof. exact: mk_srt add0n addnC addnA mul1n mul0n mulnC mulnA mulnDl. Qed.\n\nLemma nat_semi_morph :\n  semi_morph 0 1 addn muln (@eq _) 0%num 1%num Nplus Nmult pred1 nat_of_bin.\nProof. by move: nat_of_add_bin nat_of_mul_bin; split=> //= m n /eqP ->. Qed.\n\nLemma nat_power_theory : power_theory 1 muln (@eq _) nat_of_bin expn.\nProof. by split; apply: nat_of_exp_bin. Qed.\n\n(* Interface to the ring tactic machinery. *)\n\nFixpoint pop_succn e := if e is e'.+1 then fun n => pop_succn e' n.+1 else id.\n\nLtac pop_succn e := eval lazy beta iota delta [pop_succn] in (pop_succn e 1).\n\nLtac nat_litteral e :=\n  match pop_succn e with\n  | ?n.+1 => constr: (bin_of_nat n)\n  |     _ => NotConstant\n  end.\n\nLtac succn_to_add :=\n  match goal with\n  | |- context G [?e.+1] =>\n    let x := fresh \"NatLit0\" in\n    match pop_succn e with\n    | ?n.+1 => pose x := n.+1; let G' := context G [x] in change G'\n    | _ ?e' ?n => pose x := n; let G' := context G [x + e'] in change G'\n    end; succn_to_add; rewrite {}/x\n  | _ => idtac\n  end.\n\nAdd Ring nat_ring_ssr : nat_semi_ring (morphism nat_semi_morph,\n   constants [nat_litteral], preprocess [succn_to_add],\n   power_tac nat_power_theory [nat_litteral]).\n\n(* A congruence tactic, similar to the boolean one, along with an .+1/+  *)\n(* normalization tactic.                                                 *)\n\nLtac nat_norm :=\n  succn_to_add; rewrite ?add0n ?addn0 -?addnA ?(addSn, addnS, add0n, addn0).\n\nLtac nat_congr := first\n [ apply: (congr1 succn _)\n | apply: (congr1 predn _)\n | apply: (congr1 (addn _) _)\n | apply: (congr1 (subn _) _)\n | apply: (congr1 (addn^~ _) _)\n | match goal with |- (?X1 + ?X2 = ?X3) =>\n     symmetry;\n     rewrite -1?(addnC X1) -?(addnCA X1);\n     apply: (congr1 (addn X1) _);\n     symmetry\n   end ].\n", "meta": {"author": "math-comp", "repo": "math-comp", "sha": "e39f9173b484f2e8e7f69f746a619dcc8f3abc1b", "save_path": "github-repos/coq/math-comp-math-comp", "path": "github-repos/coq/math-comp-math-comp/math-comp-e39f9173b484f2e8e7f69f746a619dcc8f3abc1b/mathcomp/ssreflect/ssrnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7385923326032944}}
{"text": "   Theorem z2_1_a: forall A : Prop, \n                   (A \\/ A) <-> (A /\\ A).\n   Proof.\n      intros. split.\n      intros. elim H. intros. split. assumption. assumption.\n      intros. split. assumption. assumption.\n      intros. left. apply H.\n   Qed.\n   Theorem z2_1_a': forall A : Prop, \n                   (A /\\ A) <-> (A).\n   Proof.\n      intros. split.\n      intros. elim H. intros. assumption.\n      intros. split. assumption. assumption.\n   Qed.\n\n   Theorem z2_1_a'': forall A : Prop, \n                   (A \\/ A) <-> (A).\n   Proof.\n      intros. split.\n      intros. elim H. intros. assumption. apply id.\n      intros. left. assumption.\n   Qed.\n\n   Theorem z2_2_a: forall A : Prop, \n                   (~~A) <-> (A).\n   Proof.\n      Require Import Classical.\n      intros. split.\n      intros. apply NNPP. intro. contradiction. \n      intros. intro. contradiction.\n   Qed.\n\n   Theorem z2_3_a: forall (A B C : Type -> Prop),\n           (forall x : Type, (A x \\/ B x) -> C x) <->\n               (forall x : Type,  A x -> C x)\n                   /\\ forall x : Type,  B x -> C x.\n   Proof.\n      intros. split. intros. split. intros. apply H. left. assumption.\n                     intros. apply H. right. assumption.\n      intros. elim H0. elim H. clear H. intros. revert H2. apply H.\n              intros. revert H1. elim H. intros. revert H3. apply H2.\n  Qed.\n", "meta": {"author": "ko-petrov", "repo": "lessons", "sha": "3524fd9f0a98923f3ef471114bba52d6bbbfcf2f", "save_path": "github-repos/coq/ko-petrov-lessons", "path": "github-repos/coq/ko-petrov-lessons/lessons-3524fd9f0a98923f3ef471114bba52d6bbbfcf2f/coq/Lab2/PetrovPrPrLab2-z1-3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7385857967938538}}
{"text": "(* Exercise coq_nat_07 *)\n\n(* So far we were dealing with addition on natural numbers. How\n   about multiplication? Not surprisingly it is defined in the\n   standard library of Coq, but before seeing the definition\n   try to think of how would you define that (using addition). *)\nPrint mult.\nCheck mult.\n\n(* Here is this definition for reference (and in the way you would\n   type it in, which slightly differs from the way Coq presents it)\n   \nFixpoint mult (n m:nat) {struct n} : nat :=\n  match n with\n  | O => 0\n  | S p => m + mult p m\n  end\n*)\n\n(* Let us prove the 0 properties of multiplication *)\n\nLemma mult_0_l : forall n, 0 * n = 0.\n\nProof.\nintros.\nunfold mult.\nreflexivity.\n \nQed.\n\nLemma mult_0_r : forall n, n * 0 = 0.\n\nProof.\nintros.\ninduction n.\nsimpl; reflexivity.\nsimpl.\nassumption.\nQed.", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_nat_07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7385857949266258}}
{"text": "Require Export TopologicalSpaces.\nRequire Export OrderTopology.\nRequire Export Reals.\n\nLocal Unset Standard Proposition Elimination Names.\n\nDefinition RTop := OrderTopology Rle.\n\nRequire Export MetricSpaces.\n\nDefinition R_metric (x y:R) : R := Rabs (y-x).\n\nLemma R_metric_is_metric: metric R_metric.\nProof.\nconstructor.\nintros.\nunfold R_metric.\npose proof (Rabs_pos (y-x)).\nauto with *.\n\nintros.\nunfold R_metric.\nreplace (y-x) with (-(x-y)); try ring.\napply Rabs_Ropp.\n\nintros.\nunfold R_metric.\nreplace (z-x) with ((y-x) + (z-y)); try ring.\napply Rabs_triang.\n\nintros.\nunfold R_metric.\nreplace (x-x) with 0; try ring.\nexact Rabs_R0.\n\nintros.\nassert (y-x=0).\napply NNPP.\ncontradict H.\napply Rabs_no_R0; assumption.\nauto with *.\nQed.\n\nLemma Rmetric_bound: forall x y z:R, R_metric x z < y - x ->\n  z < y.\nProof.\nintros.\nreplace z with (x + (z-x)); try ring.\napply Rle_lt_trans with (x + R_metric x z).\nassert (z - x <= R_metric x z).\napply Rle_abs.\nauto with real.\nreplace y with (x + (y-x)); try ring.\nauto with real.\nQed.\n\nLemma Rmetric_bound2: forall x y z:R, R_metric y z < y - x ->\n  x < z.\nProof.\nintros.\nreplace z with (y + (z-y)); try ring.\napply Rlt_le_trans with (y - R_metric y z).\napply Rlt_minus in H.\napply Rminus_lt.\nreplace (x - (y - R_metric y z)) with\n  (R_metric y z - (y - x)); try ring.\ntrivial.\nassert (y - z <= R_metric y z).\nrewrite (metric_sym _ _ R_metric_is_metric y z).\napply Rle_abs.\napply Rle_minus in H0.\napply Rminus_le.\nreplace (y - R_metric y z - (y + (z - y))) with\n  (y - z - R_metric y z); trivial; ring.\nQed.\n\nLemma RTop_metrization: metrizes RTop R_metric.\nProof.\nrefine (let Hsubbasis := Build_TopologicalSpace_from_subbasis_subbasis\n  _ (order_topology_subbasis _ Rle) in _).\nclearbody Hsubbasis.\nred; intros.\nconstructor.\nintros.\ndestruct H.\nassert (open_ball (point_set RTop) R_metric x r = Intersection\n  [ y:R | x-r <= y /\\ y <> x-r ]\n  [ y:R | y <= x+r /\\ y <> x+r ]).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H0.\nassert (x - r < x0).\napply Rmetric_bound2 with x.\nring_simplify; trivial.\nassert (x + r > x0).\napply Rmetric_bound with x.\nring_simplify; trivial.\nrepeat split; auto with real.\nconstructor.\ndestruct H0.\ndestruct H0.\ndestruct H0.\ndestruct H1.\ndestruct H1.\napply Rabs_def1.\nassert (x0-x <= r).\napply Rminus_le.\napply Rle_minus in H1.\nreplace (x0 - x - r) with (x0 - (x + r)); trivial; ring.\nassert (x0 - x <> r).\nintro.\ncontradiction H3.\nrewrite <- H5.\nring.\ndestruct (total_order_T (x0 - x) r) as [[|]|]; try tauto.\nassert (r < r).\napply Rlt_le_trans with (x0 - x); trivial.\ncontradict H6.\napply Rlt_irrefl.\nassert (-r <= x0 - x).\napply Rle_minus in H0.\napply Rminus_le.\nreplace (-r - (x0 - x)) with (x - r - x0); try ring; trivial.\nassert (-r <> x0 - x).\nintro.\ncontradiction H2.\nreplace r with (- -r); try ring.\nrewrite H5; ring.\ndestruct (total_order_T (-r) (x0 - x)) as [[|]|]; try tauto.\nassert (-r < -r).\napply Rle_lt_trans with (x0 - x); trivial.\ncontradict H6.\napply Rlt_irrefl.\n\nrewrite H0.\nconstructor.\napply (@open_intersection2 RTop).\napply Hsubbasis; constructor.\napply Hsubbasis; constructor.\nassert (x-r < x).\napply Rminus_lt.\nring_simplify.\nauto with real.\nassert (x+r > x).\napply Rminus_gt.\nring_simplify; trivial.\nrepeat split; auto with real.\n\nintros.\ndestruct H.\ndestruct H.\ndestruct H0.\npose proof (H _ H0).\nassert (exists eps:R, eps > 0 /\\ Included (open_ball _ R_metric x eps) S).\nclear H0.\ninduction H2.\nexists 1.\nsplit.\nred.\nauto with real.\nintro; constructor.\ndestruct H0.\ndestruct H1.\ndestruct H0.\nexists (x0-x).\nsplit.\ndestruct (total_order_T x0 x) as [[]|].\nassert (x < x).\napply Rle_lt_trans with x0; trivial.\ncontradict H2.\napply Rlt_irrefl.\ncongruence.\napply Rgt_minus; trivial.\nred; intros y ?.\ndestruct H2.\nconstructor.\nassert (y < x0).\napply Rmetric_bound with x; trivial.\nsplit; auto with real.\n\ndestruct H1.\ndestruct H0.\nexists (x - x0).\nsplit.\ndestruct (total_order_T x0 x) as [[]|].\napply Rgt_minus; trivial.\ncongruence.\nassert (x < x).\napply Rlt_le_trans with x0; trivial.\ncontradict H2.\napply Rlt_irrefl.\nintros y ?.\ndestruct H2.\nconstructor.\nassert (x0 < y).\napply Rmetric_bound2 with x; trivial.\nsplit; auto with real.\ndestruct H1.\napply IHfinite_intersections in H1.\napply IHfinite_intersections0 in H3.\ndestruct H1 as [eps1 []].\ndestruct H3 as [eps2 []].\nexists (Rmin eps1 eps2).\nsplit.\nunfold Rmin.\ndestruct Rle_dec; trivial.\nred; intros y ?.\ndestruct H6.\nconstructor.\napply H4.\nconstructor.\napply Rlt_le_trans with (Rmin eps1 eps2); trivial.\nunfold Rmin; destruct Rle_dec; auto with real.\napply H5.\nconstructor.\napply Rlt_le_trans with (Rmin eps1 eps2); trivial.\nunfold Rmin; destruct Rle_dec; auto with real.\n\ndestruct H3 as [eps []].\nexists (open_ball R R_metric x eps).\nsplit.\nconstructor.\ntrivial.\nassert (Included S (FamilyUnion F)).\nintros y ?.\nexists S; trivial.\nauto with sets.\nQed.\n\nCorollary RTop_metrizable: metrizable RTop.\nProof.\nexists R_metric.\nexact R_metric_is_metric.\nexact RTop_metrization.\nQed.\n\nLemma RTop_separable: separable RTop.\nProof.\nRequire Import RationalsInReals.\nexists (Im Full_set Q2R).\napply countable_img.\napply countable_type_ensemble.\nexact Q_countable.\n\napply meets_every_nonempty_open_impl_dense.\nintros.\ndestruct H0 as [x].\ndestruct (RTop_metrization x).\ndestruct (open_neighborhood_basis_cond U) as [V []].\nsplit; trivial.\ndestruct H1.\ndestruct (rationals_dense_in_reals (x-r) (x+r)) as [q].\napply Rminus_gt.\nreplace (x+r-(x-r)) with (r+r); try ring.\napply Rgt_trans with r; auto with real.\npattern r at 3.\nreplace r with (r+0); try ring.\nauto with real.\n\nexists (Q2R q).\nconstructor.\nexists q; trivial.\nconstructor.\napply H2.\nconstructor.\ndestruct H3.\napply Rabs_def1.\napply Rminus_lt.\napply Rlt_minus in H4.\nreplace (Q2R q - x - r) with (Q2R q - (x + r)); trivial; ring.\napply Rminus_lt.\napply Rlt_minus in H3.\nreplace (-r - (Q2R q - x)) with (x - r - Q2R q); trivial; ring.\nQed.\n\nRequire Export Compactness.\n\nLemma bounded_real_net_has_cluster_point: forall (I:DirectedSet)\n  (x:Net I RTop) (a b:R), (forall i:DS_set I, a <= x i <= b) ->\n  exists x0:point_set RTop, net_cluster_point x x0.\nProof.\n(* idea: the liminf is a cluster point *)\nintros.\ndestruct (classic (inhabited (DS_set I))) as [Hinh|Hempty].\nassert (forall i:DS_set I, { y:R | is_glb\n                             (Im [ j:DS_set I | DS_ord i j ] x) y }).\nintro.\napply inf.\nexists a.\nred; intros.\ndestruct H0.\ndestruct (H x0).\nrewrite H1.\nauto with real.\nexists (x i).\nexists i; trivial.\nconstructor.\napply preord_refl.\napply DS_ord_cond.\n\nassert ({ x0:R | is_lub (Im Full_set (fun i:DS_set I => proj1_sig (X i)))\n                        x0 }).\napply sup.\nexists b.\nred; intros.\ndestruct H0 as [i].\ndestruct (X i).\nsimpl in H1.\nrewrite H1.\ndestruct i0.\ncut (b >= x0).\nauto with real.\napply Rge_trans with (x i).\ndestruct (H i).\nauto with real.\napply H2.\nexists i; trivial.\nconstructor.\napply preord_refl.\napply DS_ord_cond.\n\ndestruct Hinh as [i0].\nexists (proj1_sig (X i0)).\nexists i0; trivial.\nconstructor.\n\ndestruct H0 as [x0].\nexists x0.\nassert (forall i j:DS_set I, DS_ord i j ->\n  proj1_sig (X i) <= proj1_sig (X j)).\nintros.\ndestruct (X i0).\ndestruct (X j).\nsimpl.\ndestruct i1.\ndestruct i2.\napply H4.\nred; intros.\ndestruct H5.\ndestruct H5.\napply H1.\nexists x3; trivial.\nconstructor.\napply preord_trans with j; trivial.\napply DS_ord_cond.\n\nred; intros.\ndestruct (RTop_metrization x0).\ndestruct (open_neighborhood_basis_cond U).\nsplit; trivial.\ndestruct H3.\ndestruct H3.\ndestruct (lub_approx _ _ r i).\ntrivial.\ndestruct H5.\ndestruct H5.\ndestruct H6.\nred; intros.\ndestruct (DS_join_cond x1 i0).\ndestruct H9.\nremember (X x2) as y2.\ndestruct y2.\ndestruct (glb_approx _ _ r i1).\ntrivial.\ndestruct H11.\ndestruct H11.\ndestruct H11.\ndestruct H12.\nexists x4.\nsplit.\napply preord_trans with x2; trivial.\napply DS_ord_cond.\napply H4.\nconstructor.\nassert (y <= proj1_sig (X x2)).\nrewrite H7.\napply H0; trivial.\nrewrite <- Heqy2 in H15.\nsimpl in H15.\nassert (proj1_sig (X x2) <= x0).\napply i.\nexists x2; trivial.\nconstructor.\nrewrite <- Heqy2 in H16.\nsimpl in H16.\nrewrite <- H13.\napply Rabs_def1.\n\ncut (y0 < x0 + r).\nintro.\napply Rlt_minus in H17.\napply Rminus_lt.\nreplace (y0 - x0 - r) with (y0-(x0+r)); trivial; ring.\napply Rlt_le_trans with (x3 + r).\ntrivial.\nauto with real.\n\ncut (y0 > x0 - r).\nintro.\napply Rlt_minus in H17.\napply Rminus_lt.\nreplace (-r - (y0-x0)) with (x0-r-y0); trivial; ring.\napply Rge_gt_trans with y.\napply Rge_trans with x3; auto with real.\ntrivial.\n\nexists a.\nred; intros.\nred; intros.\ncontradiction Hempty.\nexists; exact i.\nQed.\n\nLemma R_closed_interval_compact: forall a b:R, a <= b ->\n  compact (SubspaceTopology ([x:point_set RTop | a <= x <= b])).\nProof.\nintros a b Hbound.\napply net_cluster_point_impl_compact.\nintros.\npose (y := fun i:DS_set I => proj1_sig (x i)).\ndestruct (bounded_real_net_has_cluster_point _ y a b).\nintros.\nunfold y.\ndestruct (x i).\ndestruct i0.\nsimpl.\ntrivial.\n\nassert (closed [x:point_set RTop | a <= x <= b]).\nassert ([x:point_set RTop | a <= x <= b] = Intersection\n                [ x:point_set RTop | a <= x ]\n                [ x:point_set RTop | x <= b ]).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\ndestruct H1.\nconstructor; constructor; trivial.\ndestruct H1.\ndestruct H1.\ndestruct H2.\nconstructor.\nauto.\nrewrite H1.\napply closed_intersection2.\napply upper_closed_interval_closed.\nconstructor; red; intros; auto with real.\napply Rle_trans with y0; trivial.\nintros.\ndestruct (total_order_T x1 y0) as [[|]|]; auto with real.\napply lower_closed_interval_closed.\nconstructor; red; intros; auto with real.\napply Rle_trans with y0; trivial.\nintros.\ndestruct (total_order_T x1 y0) as [[|]|]; auto with real.\n\nassert (Ensembles.In [x:point_set RTop | a <= x <= b] x0).\nrewrite <- (closure_fixes_closed _ H1).\napply net_cluster_point_in_closure with _ y.\ndestruct H as [i0].\nexists i0.\nintros.\nconstructor.\nunfold y.\ndestruct (x j).\nsimpl.\ndestruct i.\ntrivial.\ntrivial.\n\nexists (exist _ x0 H2).\nred; intros.\ndestruct (subspace_topology_topology _ _ _ H3) as [V].\ndestruct H5.\nred; intros.\nassert (Ensembles.In V x0).\nrewrite H6 in H4.\ndestruct H4.\nsimpl in H4.\ntrivial.\n\ndestruct (H0 V H5 H7 i) as [j []].\nexists j.\nsplit; trivial.\nrewrite H6.\nconstructor.\nsimpl.\nexact H9.\nQed.\n\nLemma R_compact_subset_bounded: forall A:Ensemble (point_set RTop),\n  compact (SubspaceTopology A) -> bound A.\nProof.\nintros.\ndestruct (H (Im Full_set (fun y:R => inverse_image (subspace_inc _)\n                   [ x:point_set RTop | y - 1 < x < y + 1 ]))).\nintros.\ndestruct H0.\nrewrite H1.\napply subspace_inc_continuous.\nreplace [x0:point_set RTop | x-1 < x0 < x+1] with\n  (Intersection [x0:point_set RTop | x-1 <= x0 /\\ x0 <> x-1]\n                [x0:point_set RTop | x0 <= x+1 /\\ x0 <> x+1]).\npose proof (Build_TopologicalSpace_from_subbasis_subbasis\n  _ (order_topology_subbasis _ Rle)).\napply open_intersection2.\napply H2.\nconstructor.\napply H2.\nconstructor.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H2.\ndestruct H2.\ndestruct H2.\ndestruct H3.\ndestruct H3.\nconstructor.\nsplit.\ndestruct (total_order_T (x-1) x0) as [[|]|]; auto with real.\ncontradiction H4; symmetry; trivial.\nassert (x0 < x0).\napply Rlt_le_trans with (x-1); auto with real.\ncontradict H6; apply Rlt_irrefl.\ndestruct (total_order_T x0 (x+1)) as [[|]|]; auto with real.\ncontradiction H5.\nassert (x0 < x0).\napply Rle_lt_trans with (x+1); auto with real.\ncontradict H6; apply Rlt_irrefl.\ndestruct H2.\ndestruct H2.\nconstructor; constructor; split; auto with real.\n\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\neexists.\nexists (proj1_sig x).\nconstructor.\nreflexivity.\nconstructor.\nconstructor.\ndestruct x.\nsimpl.\nsplit; apply Rminus_lt; auto with real.\nreplace (x-1-x) with (-1); try ring.\napply Ropp_lt_gt_0_contravar.\nexact Rlt_0_1.\n\ndestruct H0.\ndestruct H1.\nassert (exists a:R, forall S:Ensemble (point_set (SubspaceTopology A)),\n  forall b:point_set (SubspaceTopology A),\n  Ensembles.In x S -> Ensembles.In S b -> proj1_sig b < a).\nclear H2.\ninduction H0.\nexists 0.\nintros.\ndestruct H0.\ndestruct IHFinite.\ncut (Included A0 (Add A0 x)); auto with sets.\nassert (Ensembles.In (Add A0 x) x).\nright.\nconstructor.\napply H1 in H4.\ndestruct H4.\nexists (Rmax x0 (x+1)).\nintros.\ndestruct H6.\napply Rlt_le_trans with x0.\napply H3 with x1; trivial.\nunfold Rmax.\ndestruct Rle_dec; auto with real.\ndestruct H6.\nrewrite H5 in H7.\ndestruct H7.\ndestruct H6.\napply Rlt_le_trans with (x+1).\napply H6.\nunfold Rmax; destruct Rle_dec; auto with real.\n\ndestruct H3 as [a].\nexists a.\nred; intros.\nassert (Ensembles.In (FamilyUnion x)\n  (exist (fun x:R => Ensembles.In A x) x0 H4)).\nrewrite H2; constructor.\ninversion H5.\npose proof (H3 _ _ H6 H7).\nsimpl in H9.\nauto with real.\nQed.\n\nLemma Ropp_continuous: continuous Ropp (X:=RTop) (Y:=RTop).\nProof.\napply pointwise_continuity.\nintro.\napply metric_space_fun_continuity with R_metric R_metric;\n  try apply RTop_metrization.\nintros.\nexists eps.\nsplit; trivial.\nintros.\nunfold R_metric.\nreplace (-x' - -x) with (x-x'); try ring.\nrewrite Rabs_minus_sym; trivial.\nQed.\n\nRequire Export Connectedness.\n\nLemma R_connected: connected RTop.\nProof.\ncut (forall S:Ensemble (point_set RTop),\n  clopen S -> Ensembles.In S 0 -> S = Full_set).\nintro.\nred; intros.\ndestruct (classic (Ensembles.In S 0)).\nright.\napply H; trivial.\nleft.\nassert (Complement S = Full_set).\napply H; trivial.\ndestruct H0; split; trivial.\nred; rewrite Complement_Complement; trivial.\napply Extensionality_Ensembles; split; red; intros.\nassert (Ensembles.In (Complement S) x).\nrewrite H2; constructor.\ncontradiction H4.\ndestruct H3.\n\ncut (forall S:Ensemble (point_set RTop),\n  clopen S -> Ensembles.In S 0 -> forall x:R, x > 0 ->\n                                  Ensembles.In S x).\nintro.\nassert (forall S:Ensemble (point_set RTop),\n  clopen S -> Ensembles.In S 0 -> forall x:R, x < 0 ->\n                                  Ensembles.In S x).\nintros.\npose (T := inverse_image Ropp S).\n\nassert (Ensembles.In T (-x)).\napply H.\ndestruct H0; split.\napply Ropp_continuous; trivial.\nred.\nsubst T.\nrewrite <- inverse_image_complement.\napply Ropp_continuous; trivial.\nconstructor.\nreplace (-0) with 0; trivial; ring.\ncut (0 < -x); auto with real.\ndestruct H3.\nrewrite Ropp_involutive in H3; trivial.\n\nintros.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\ndestruct (total_order_T x 0) as [[|]|].\napply H0; trivial.\ncongruence.\napply H; trivial.\n\nintros.\napply NNPP; intro.\npose (T := [ y:R | forall z:R, 0 <= z <= y -> Ensembles.In S z ]).\nassert (Ensembles.In T 0).\nconstructor.\nintros.\nassert (z = 0).\ndestruct H3; auto with real.\nrewrite H4; trivial.\n\ndestruct (sup T).\nexists x.\nred; intros.\ncut (~ x0>x).\napply Rnot_lt_le; auto with real.\nintro.\ndestruct H4.\napply H2.\napply H4.\nsplit; auto with real.\nexists 0.\nexact H3.\n\nassert (0 <= x0).\napply i.\nexact H3.\n\ndestruct (RTop_metrization x0).\nassert (Ensembles.In S x0).\nrewrite <- (closure_fixes_closed S); try apply H.\napply meets_every_open_neighborhood_impl_closure.\nintros.\ndestruct (open_neighborhood_basis_cond U).\nsplit; trivial.\ndestruct H7.\ndestruct H7.\ndestruct (lub_approx _ _ r i).\ntrivial.\ndestruct H9.\nexists (Rmax x1 0).\nconstructor.\nunfold Rmax.\ndestruct Rle_dec.\ntrivial.\napply H9.\nauto with real.\n\napply H8.\nconstructor.\nunfold Rmax.\ndestruct Rle_dec.\nunfold R_metric.\nrewrite Rabs_minus_sym.\nreplace (x0-0) with x0; try ring.\napply Rabs_def1.\napply Rminus_lt.\ndestruct H10.\napply Rlt_le_trans with x1; trivial.\napply Rlt_le_trans with 0; auto with real.\n\napply Rabs_def1.\napply Rle_lt_trans with 0; auto with real.\ndestruct H10.\napply Rle_minus; trivial.\ndestruct H10.\napply Rminus_lt.\napply Rlt_minus in H10.\nreplace (-r - (x1-x0)) with (x0-r-x1); trivial; ring.\n\ndestruct (open_neighborhood_basis_cond S).\nsplit; trivial.\napply H.\ndestruct H6.\ndestruct H6.\n\ndestruct (lub_approx _ _ r i).\ntrivial.\ndestruct H8.\n\nassert (Ensembles.In T (x0+r/2)).\nconstructor.\nintros.\ndestruct H10.\ndestruct (total_order_T z x1) as [[|]|].\napply H8.\nsplit; auto with real.\napply H8.\nsplit; auto with real.\napply H7.\nconstructor.\napply Rabs_def1.\napply Rle_lt_trans with (r/2).\napply Rminus_le.\napply Rle_minus in H11.\nreplace (z-x0-r/2) with (z-(x0+r/2)); trivial; ring.\napply Rminus_gt.\nreplace (r-r/2) with (r/2); try field.\napply Rmult_gt_0_compat; auto with real.\nauto with *.\napply Rlt_trans with (x1 - x0).\ndestruct H9.\napply Rlt_minus in H9.\napply Rminus_lt.\nreplace (-r - (x1-x0)) with (x0-r-x1); trivial; ring.\ncut (x1<z); trivial.\nintro.\nunfold Rminus.\nauto with real.\n\nassert (x0 + r/2 <= x0).\napply i.\nexact H10.\n\nabsurd (x0 + r/2 > x0).\napply Rge_not_gt; auto with real.\napply Rminus_gt.\nring_simplify.\napply Rmult_gt_0_compat; auto with real.\napply Rinv_0_lt_compat.\nauto with real.\nQed.\n\nRequire Export Completeness.\n\nLemma R_cauchy_sequence_bounded: forall x:nat->R,\n  cauchy R_metric x -> bound (Im Full_set x).\nProof.\nintros.\ndestruct (H 1) as [N].\nred; auto with real.\nassert (exists y:R, forall n:nat, (n<N)%nat -> x n <= y).\nclear H0; induction N.\nexists 0.\nintros.\ncontradict H0.\nauto with arith.\ndestruct IHN as [y].\nexists (Rmax y (x N)).\nintros.\napply lt_n_Sm_le in H1.\ndestruct (le_lt_or_eq _ _ H1).\napply Rle_trans with y.\napply H0; trivial.\napply Rmax_l.\nrewrite H2.\napply Rmax_r.\n\ndestruct H1 as [y].\nexists (Rmax y (x N + 1)).\nred; intros.\ndestruct H2 as [n].\nrewrite H3; clear y0 H3.\ndestruct (le_or_lt N n).\napply Rle_trans with (x N + 1).\nassert (R_metric (x n) (x N) < 1).\napply H0; auto with arith.\napply Rabs_def2 in H4.\ndestruct H4.\nRequire Import Fourier.\nfourier.\napply Rmax_r.\napply Rle_trans with y; auto.\napply Rmax_l.\nQed.\n\nLemma R_cauchy_sequence_lower_bound: forall x:nat->R,\n  cauchy R_metric x -> lower_bound (Im Full_set x).\nProof.\nintros.\nassert (cauchy R_metric (fun n:nat => - x n)).\nred; intros.\ndestruct (H eps H0) as [N].\nexists N.\nintros.\nreplace (R_metric (- x m) (- x n)) with (R_metric (x m) (x n)).\napply H1; trivial.\nunfold R_metric.\nreplace (x n - x m) with (- (- x n - - x m)) by ring.\napply Rabs_Ropp.\ndestruct (R_cauchy_sequence_bounded _ H0) as [m].\nexists (-m).\nred; intros.\ncut (-x0 <= m).\nintros; fourier.\napply H1.\ndestruct H2 as [n].\nexists n; trivial.\nf_equal; trivial.\nQed.\n\nLemma R_metric_complete: complete R_metric R_metric_is_metric.\nProof.\nred; intros.\ndestruct (R_cauchy_sequence_bounded _ H) as [b].\ndestruct (R_cauchy_sequence_lower_bound _ H) as [a].\ndestruct (bounded_real_net_has_cluster_point nat_DS x a b) as [x0].\nintros; split; [ cut (x i >= a); auto with real; apply H1 | apply H0 ];\n  exists i; trivial; constructor.\nexists x0.\napply cauchy_sequence_with_cluster_point_converges; trivial.\napply metric_space_net_cluster_point with R_metric;\n  try apply MetricTopology_metrizable.\nintros.\napply metric_space_net_cluster_point_converse with RTop; trivial.\napply RTop_metrization.\nQed.\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/RTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7385857909036981}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus y (plus lf1 x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj205_coqofml_MTd4yj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7385857887960775}}
{"text": "Require Export Reals Omega.\nRequire Export Classical_Prop.\n\nDefinition Complex : Set := R*R.\n\nDelimit Scope C_scope with C.\n\nDefinition Cplus ( x y : Complex ) : Complex := match x, y with\n                                | (a,b) , (c,d) => (a+c,b+d)%R \n                              end.\n\nDefinition Cmult ( x y : Complex ) : Complex := match x, y with\n                                | (a,b) , (c,d) => (a*c-b*d,a*d+b*c)%R \n                              end.\n\nDefinition C0 : Complex := (0,0)%R.\nDefinition C1 : Complex := (1,0)%R.\nDefinition Ci : Complex := (0,1)%R.\n\nDefinition Copp ( x: Complex ) : Complex := match x with\n                                | (a,b) => (-a,-b)%R \n                              end. \nDefinition Cinv ( x: Complex ) : Complex := match x with\n                                | (a,b) => (a/(a*a+b*b),-b/(a*a+b*b))%R \n                              end. \n\nTheorem Real_eq_dec : forall r1 r2 : R , ({ r1 = r2 } + { r1 <> r2 })%R.\nProof.\n  \n  intros.\n  assert ({r1 < r2} + {r1 = r2} + {r1 > r2})%R.\n  apply total_order_T.\n  destruct H in H.\n  destruct s.\n  right.\nAdmitted.  \n\n\nDefinition Clt ( x y : Complex ) : Prop := match x, y with\n                                | (a,b) , (c,d) => if (Real_eq_dec a c)%R then (b<d)%R else (a<c)%R \n                              end.\n\n\nInfix \"+\" := Cplus : C_scope.\nInfix \"*\" := Cmult : C_scope.\nNotation \"- x\" := (Copp x) : C_scope.\nNotation \"/ x\" := (Cinv x) : C_scope.\n\n\nInfix \"<\" := Clt : C_scope.\n\n\nDefinition Cgt (r1 r2:Complex) : Prop := (r2 < r1)%C.\n\nDefinition Cle (r1 r2:Complex) : Prop := (r1 < r2 \\/ r1 = r2)%C.\n\nDefinition Cge (r1 r2:Complex) : Prop := (Cgt r1 r2 \\/ r1 = r2)%C.\n\nDefinition Cminus (r1 r2:Complex) : Complex := (r1 + - r2)%C.\n\nDefinition Cdiv (r1 r2:Complex) : Complex := (r1 * / r2)%C.\n\n\nInfix \"-\" := Cminus : C_scope.\nInfix \"/\" := Cdiv : C_scope.\n\nInfix \"<=\" := Cle : C_scope.\nInfix \">=\" := Cge : C_scope.\nInfix \">\" := Cgt : C_scope.\n\nNotation \"x <= y <= z\" := (x <= y /\\ y <= z) : C_scope.\nNotation \"x <= y < z\" := (x <= y /\\ y < z) : C_scope.\nNotation \"x < y < z\" := (x < y /\\ y < z) : C_scope.\nNotation \"x < y <= z\" := (x < y /\\ y <= z) : C_scope.\n\n(* end Cdefinition *)\n\nDefinition real_p ( z: Complex ) := fst z.\nDefinition imag_p ( z: Complex ) := snd z.\n\nLemma Cdecompose : forall z : Complex , z = ( real_p z , imag_p z ).\nProof.\n  intros.\n  apply surjective_pairing.\nQed.\n\nLemma Cplus_decompose : forall z1 z2 : Complex , ( z1 + z2 )%C = ( real_p z1 + real_p z2 , imag_p z1 + imag_p z2 )%R.\nProof.\n  intros.\n  replace (z1 + z2)%C with (( real_p z1 , imag_p z1 )+( real_p z2 , imag_p z2 ))%C.\n  unfold Cplus.\n  auto.\n  rewrite <- ! Cdecompose.\n  auto.\nQed. \n\nLemma Cplus_comm : forall z1 z2:Complex, (z1 + z2 = z2 + z1)%C.\nProof.\n  intros.\n  rewrite ! Cplus_decompose.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\nQed.\n\nHint Resolve Cplus_comm : complex.\n\nLemma Cplus_assoc : forall r1 r2 r3:Complex , (r1 + (r2 + r3) = r1 + r2 + r3)%C.\nProof.\n  intros.\n  rewrite ! Cplus_decompose.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\nQed.\n\nHint Resolve Cplus_assoc: complex.\n\nLemma Cplus_opp_r : forall r:Complex, (r + -r = C0 )%C.\nProof.\n  intros.\n  replace (r) with ( real_p r , imag_p r ).\n  unfold Copp.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\n  apply eq_sym.\n  apply Cdecompose.\nQed.\nHint Resolve Cplus_opp_r: complex.\n\nLemma Cplus_0_l : forall r:Complex , (C0 + r = r)%C.\nProof.\n  intros.\n  rewrite ! Cplus_decompose.\n  unfold real_p.\n  unfold imag_p.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\nQed.\n\nHint Resolve Cplus_0_l: complex.\n\nLemma Cmult_decompose : forall z1 z2 : Complex , ( z1 * z2 )%C = ( real_p z1 * real_p z2 - imag_p z1 * imag_p z2 , real_p z1 * imag_p z2 + imag_p z1 * real_p z2 )%R.\nProof.\n  intros.\n  replace (z1 * z2)%C with (( real_p z1 , imag_p z1 )*( real_p z2 , imag_p z2 ))%C.\n  unfold Cplus.\n  auto.\n  rewrite <- ! Cdecompose.\n  auto.\nQed. \n\nLemma Cmult_comm : forall r1 r2:Complex, (r1 * r2 = r2 * r1)%C.\nProof.\n  intros.\n  rewrite ! Cmult_decompose.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\nQed.\nHint Resolve Cmult_comm: complex.\n\nLemma Cmult_assoc : forall r1 r2 r3:Complex, (r1 * (r2 * r3) = r1 * r2 * r3)%C.\nProof.\n  intros.\n  rewrite ! Cmult_decompose.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\nQed.\nHint Resolve Cmult_assoc: complex.\n\nLocal Open Scope R_scope.\n\nLemma Ra2b2n0 : forall a b : R , a<>0 \\/ b<>0 -> 0<a*a+b*b.\nProof.\n  intros.\n  assert ( 0 <= a * a ).\n  replace ( a * a ) with (a^2) ; [idtac | ring ].\n  apply pow2_ge_0 with ( x := a ).\n  assert ( 0 <= b * b ).\n  replace ( b * b ) with (b^2) ; [idtac | ring ].\n  apply pow2_ge_0 with ( x := b ).\n  unfold Rle in H0.\n  case H0.\n  intros.\n  replace 0 with (0+0); [ idtac | ring ].\n  apply Rplus_gt_ge_compat.\n  auto.\n  apply Rle_ge.\n  auto.\n  intros.\n  assert (b<>0).\n  assert ( a=0).\n  apply eq_sym in H2.\n  apply Rmult_integral in H2.\n  case H2.\n  auto.\n  auto.\n  case H.\n  contradiction.\n  auto.\n  assert ( b * b <> 0).\n  auto.\n  assert ( 0 < b * b ).\n  case H1.\n  auto.\n  intros.\n  apply eq_sym in H5.\n  contradiction.\n  replace 0 with (0+0); [ idtac | ring ].\n  apply Rplus_ge_gt_compat.\n  rewrite <- H2.\n  auto with real.\n  auto with real.\nQed.\n\nLocal Close Scope R_scope.\n\nLemma Cinv_l : forall r:Complex, (r <> C0 -> / r * r = C1)%C.\nProof.\n  intros.\n  replace (r) with ( real_p r , imag_p r ).\n  assert ( real_p r <> 0 \\/ imag_p r <> 0)%R as orenq.\n  apply Peirce.\n  intros.\n  apply not_or_and in H0.\n  destruct H0 as [rp0 ip0].\n  apply NNPP in rp0.\n  apply NNPP in ip0.\n  elim H.\n  replace (r) with ( real_p r , imag_p r ).\n  unfold C0.\n  apply injective_projections.\n  auto.\n  auto.\n  apply eq_sym.\n  apply Cdecompose.\n  \n  assert((real_p r * real_p r + imag_p r * imag_p r)%R <> 0%R).\n  unfold not.\n  intros.\n  assert ( 0<(real_p r * real_p r + imag_p r * imag_p r)%R )%R. \n  apply Ra2b2n0.\n  auto.\n  rewrite H0 in H1.\n  apply Rlt_irrefl in H1.\n  auto.\n\n  unfold Cinv.\n  unfold C1.\n  apply injective_projections.\n  simpl.\n  field.\n  auto.\n  simpl.\n  field.\n  auto.\n  rewrite Cdecompose.\n  auto.\nQed.\nHint Resolve Cinv_l: complex.\n\nLemma Cmult_1_l : forall r:Complex, (C1 * r = r)%C.\nProof.\n  intros.\n  replace (r) with ( real_p r , imag_p r ).\n  rewrite ! Cmult_decompose.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\n  rewrite Cdecompose.\n  auto.\nQed.\nHint Resolve Cmult_1_l: complex.\n\nLemma Cmult_0_l : forall r:Complex, (C0 * r = C0)%C.\nProof.\n  intros.\n  unfold C0.\n  replace (r) with ( real_p r , imag_p r ).\n  rewrite ! Cmult_decompose.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\n  rewrite Cdecompose.\n  auto.\nQed.\nHint Resolve Cmult_0_l: complex.\n\n\nLemma C1_neq_C0 : C1 <> C0.\nProof.\n  unfold not.\n  intros.\n  assert ( real_p C1 = 1 )%R.\n  auto.\n  assert ( real_p C1 = 0 )%R.\n  rewrite H.\n  auto.\n  auto with real.\nQed.\nHint Resolve C1_neq_C0: complex.\n\nLemma Cmult_plus_distr_r : forall r2 r3 r1:Complex, ((r2 + r3)*r1 = r2*r1 + r3 * r1)%C.\nProof.\n  intros.\n  rewrite ! Cplus_decompose.\n  rewrite ! Cmult_decompose.\n  apply injective_projections.\n  simpl.\n  ring.\n  simpl.\n  ring.\nQed.\nHint Resolve Cmult_plus_distr_r: complex.\n\nLemma complexSRth : ring_theory C0 C1 Cplus Cmult Cminus Copp (@eq Complex).\n Proof.\n  constructor. exact Cplus_0_l. exact Cplus_comm. exact Cplus_assoc.\n  exact Cmult_1_l. exact Cmult_comm. exact Cmult_assoc.\n  exact Cmult_plus_distr_r. auto. exact Cplus_opp_r.\n Qed.\n\nAdd Ring complexr : complexSRth.\n", "meta": {"author": "HKalbasi", "repo": "complexGeo", "sha": "990bca7f797d1f018d84d3ce421cc73ca03e64d4", "save_path": "github-repos/coq/HKalbasi-complexGeo", "path": "github-repos/coq/HKalbasi-complexGeo/complexGeo-990bca7f797d1f018d84d3ce421cc73ca03e64d4/Cbase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7385102841214097}}
{"text": "Require Export Elementary_Logic.\n\nModule ElementSet.\n\n(* ELEMENTARY ALGEBRA OF CLASSES *)\n\n(* 2 Definition  x∪y = { z : z∈x or z∈y }. *)\n\nDefinition Union x y : Class := \\{ λ z, z∈x \\/ z∈y \\}.\n\nNotation \"x ∪ y\" := (Union x y) (at level 65, right associativity).\n\nHint Unfold Union : set.\n\n\n(* 3 Definition  x∩y = { z : z∈x and z∈y }. *)\n\nDefinition Intersection x y : Class := \\{ λ z, z∈x /\\ z∈y \\}.\n\nNotation \"x ∩ y\" := (Intersection x y) (at level 60, right associativity).\n\nHint Unfold Intersection : set.\n\n\n(* 4 Theorem  z∈x∪y if and only if z∈x or z∈y, and z∈x∩y if and only if\n   z∈x and z∈y. *)\n\nTheorem Theorem4 : forall (x y: Class) (z: Class),\n  z∈x \\/ z∈y <-> z ∈ (x ∪ y).\nProof.\n  intros.\n  split; intros.\n  - apply Axiom_Scheme; split.\n    + destruct H; Ens.\n    + apply H.\n  - apply Axiom_Scheme in H.\n    apply H.\nQed.\n\nTheorem Theorem4' : forall x y z, z∈x /\\ z∈y <-> z∈(x∩y).\nProof.\n  intros; unfold Intersection; split; intros.\n  - apply Axiom_Scheme; split; Ens; exists y; apply H.\n  - apply Axiom_Scheme in H; apply H.\nQed.\n\nHint Resolve Theorem4 Theorem4' : set.\n\n\n(* 5 Theorem  x∪x=x and x∩x=x. *)\n\nTheorem Theorem5 : forall x, x ∪ x = x.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Theorem4 in H; tauto.\n  - apply Theorem4; tauto.\nQed.\n\nTheorem Theorem5' : forall x, x ∩ x = x.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Theorem4' in H; tauto.\n  - apply Theorem4'; tauto.\nQed.\n\nHint Rewrite Theorem5 Theorem5' : set.\n\n\n(* 6 Theorem  x∪y=y∪x and x∩y=y∩x. *)\n\nTheorem Theorem6 : forall x y, x ∪ y = y ∪ x.\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Theorem4 in H; apply Theorem4; tauto.\n  - apply Theorem4 in H; apply Theorem4; tauto.\nQed.\n\nTheorem Theorem6' : forall x y, x ∩ y = y ∩ x.\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Theorem4' in H; apply Theorem4'; tauto.\n  - apply Theorem4' in H; apply Theorem4'; tauto.\nQed.\n\nHint Rewrite Theorem6 Theorem6' : set.\n\n\n(* 7 Theorem  (x∪y)∪z=x∪(y∪z) and (x∩y)∩z=x∩(y∩z). *)\n\nTheorem Theorem7 : forall x y z, (x ∪ y) ∪ z = x ∪ (y ∪ z).\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Theorem4 in H; apply Theorem4; destruct H.\n    + apply Theorem4 in H; destruct H; try tauto.\n      right; apply Theorem4; auto.\n    + right; apply Theorem4; auto.\n  - apply Theorem4 in H; apply Theorem4; destruct H.\n    + left; apply Theorem4; auto.\n    + apply Theorem4 in H; destruct H; try tauto.\n      left; apply Theorem4; tauto.\nQed.\n\nTheorem Theorem7' : forall x y z, (x ∩ y) ∩ z = x ∩ (y ∩ z).\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - repeat (apply Theorem4' in H; destruct H).\n    apply Theorem4'; split; auto; apply Theorem4'; auto.\n  - apply Theorem4' in H; destruct H; apply Theorem4'.\n    apply Theorem4' in H0; destruct H0; split; auto.\n    apply Theorem4'; split; auto.\nQed.\n\nHint Rewrite Theorem7 Theorem7' : set.\n\n\n(* 8 Theorem  x∩(y∪z)=(x∩y)∪(x∩z) and x∪(y∩z)=(x∪y)∩(x∪z). *)\n\nTheorem Theorem8 : forall x y z, x ∩ (y ∪ z) = (x ∩ y) ∪ (x ∩ z).\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Theorem4; apply Theorem4' in H; destruct H.\n    apply Theorem4 in H0; destruct H0.\n    + left; apply Theorem4'; split; auto.\n    + right; apply Theorem4'; split; auto.\n  - apply Theorem4 in H; apply Theorem4'; destruct H.\n    + apply Theorem4' in H; destruct H; split; auto.\n      apply Theorem4; left; auto.\n    + apply Theorem4' in H; destruct H; split; auto.\n      apply Theorem4; right; auto.\nQed.\n\n\nTheorem Theorem8' : forall x y z, x ∪ (y ∩ z) = (x ∪ y) ∩ (x ∪ z).\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Theorem4'; apply Theorem4 in H.\n    destruct H; split; try apply Theorem4; auto.\n    + apply Theorem4' in H; tauto.\n    + apply Theorem4' in H; tauto.\n  - apply Theorem4; apply Theorem4' in H; destruct H.\n    apply Theorem4 in H; apply Theorem4 in H0.\n    destruct H, H0; auto; right; apply Theorem4'; auto.\nQed.\n\nHint Rewrite Theorem8 Theorem8' : set.\n\n\n(* 9 Definition  x∉y if and only if it is false that x∈y. *)\n\nDefinition NotIn x y : Prop := ~ x∈y.\n\nNotation \"x ∉ y\" := (NotIn x y) (at level 10).\n\nHint Unfold NotIn : set.\n\n\n(* 10 Definition  ¬x = { y : y ∉ x }. *)\n\nDefinition Complement x : Class := \\{λ y, y ∉ x \\}.\n\nNotation \"¬ x\" := (Complement x) (at level 5, right associativity).\n\nHint Unfold Complement : set.\n\n\n(* 11 Theorem  ¬ (¬ x) = x *)\n\nTheorem Theorem11: forall x, ¬ (¬ x) = x.\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Axiom_Scheme in H; unfold NotIn in H; destruct H.\n    assert (z ∈ ¬ x <-> Ensemble z /\\ z∉x ).\n    { split; intros.\n      - apply Axiom_Scheme in H1; auto.\n      - apply Axiom_Scheme; auto. }\n    apply definition_not in H1; auto.\n    apply not_and_or in H1; destruct H1; tauto.\n  - apply Axiom_Scheme; split; Ens; unfold NotIn; intro.\n    apply Axiom_Scheme in H0; destruct H0; contradiction.\nQed.\n\nHint Rewrite Theorem11 : set.\n\n\n(* 12 Theorem (De Morgan)  ¬(x∪y)=(¬x)∩(¬y) and ¬(x∩y)=(¬x)∪(¬y). *)\n\nTheorem Theorem12 : forall x y, ¬ (x ∪ y) = (¬ x) ∩ (¬ y).\nProof.\n  intros; generalize (Theorem4 x y); intros.\n  apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H0; destruct H0; unfold NotIn in H1.\n    apply definition_not with (B:= z∈x \\/ z∈y ) in H1.\n    + apply not_or_and in H1; apply Theorem4'; split.\n      * apply Axiom_Scheme; split; auto; unfold NotIn; tauto.\n      * apply Axiom_Scheme; split; auto; unfold NotIn; tauto.\n    + split; apply H.\n  - apply Theorem4' in H0; destruct H0.\n    apply Axiom_Scheme in H0; apply Axiom_Scheme in H1.\n    apply Axiom_Scheme; split; try tauto.\n    destruct H0, H1; unfold NotIn in H2,H3; unfold NotIn.\n    apply definition_not with (A:= z∈x \\/ z∈y ); auto.\n    apply and_not_or; split; auto.\nQed.\n\nTheorem Theorem12' : forall x y, ¬ (x ∩ y) = (¬ x) ∪ (¬ y).\nProof.\n  intros; generalize (Theorem4' x y); intros.\n  apply Axiom_Extent; split; intro.\n  - apply Axiom_Scheme in H0; unfold NotIn in H0; destruct H0.\n    apply definition_not with (B:= z∈x /\\ z∈y) in H1.\n    + apply Theorem4; apply not_and_or in H1; destruct H1.\n      * left; apply Axiom_Scheme; split; auto.\n      * right; apply Axiom_Scheme; split; auto.\n    + split; apply H.\n  - apply Axiom_Scheme; split; Ens.\n    unfold NotIn; apply definition_not with (A:= z∈x /\\ z∈y); auto.\n    apply or_not_and; apply Theorem4 in H0; destruct H0.\n    + apply Axiom_Scheme in H0; unfold NotIn in H0; tauto.\n    + apply Axiom_Scheme in H0; unfold NotIn in H0; tauto.\nQed.\n\nHint Rewrite Theorem12 Theorem12' : set.\n\n\n(* 13 Definition  x~y = x ∩ (¬ y). *)\n\nDefinition Difference x y : Class := x ∩ (¬ y).\n\nNotation \"x ~ y\" := (Difference x y) (at level 50, left associativity).\n\nHint Unfold Difference : set.\n\n\n(* 14 Theorem  x ∩ (y~z) = (x∩y) ~ z. *)\n\nTheorem Theorem14 : forall x y z, x ∩ (y ~ z) = (x ∩ y) ~ z.\nProof.\n  intros; unfold Difference; rewrite Theorem7'; auto.\nQed.\n\nHint Rewrite Theorem14 : set.\n\n\n(* Definition (85)  x≠y if and only if it is false that x=y. *)\n\nDefinition Inequality (x y: Class) : Prop := ~ (x = y).\n\nNotation \"x ≠ y\" := (Inequality x y) (at level 70).\n\nCorollary Property_Ineq : forall x y, (x ≠ y) <-> (y ≠ x).\nProof.\n intros; split; intros; intro; apply H; auto.\nQed.\n\nHint Unfold Inequality: set.\nHint Resolve Property_Ineq: set.\n\n\n(* 15 Definition  Φ = { x : x ≠ x }. *)\n\nDefinition Φ : Class := \\{λ x, x ≠ x \\}.\n\nHint Unfold Φ : set.\n\n\n(* 16 Theorem  x ∉ Φ. *)\n\nTheorem Theorem16 : forall x, x ∉ Φ.\nProof.\n  intros; unfold NotIn; intro.\n  apply Axiom_Scheme in H; destruct H; contradiction.\nQed.\n\nHint Resolve Theorem16 : set. \n\n\n(* 17 Theorem  Φ ∪ x = x and Φ ∩ x = Φ. *)\n\nTheorem Theorem17 : forall x, Φ ∪ x = x.\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Theorem4 in H; destruct H; try tauto.\n    generalize (Theorem16 z); contradiction.\n  - apply Theorem4; tauto.\nQed.\n\nTheorem Theorem17' : forall x, Φ ∩ x = Φ.\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Theorem4' in H; destruct H; auto.\n  - generalize (Theorem16 z); contradiction.\nQed.\n\nHint Rewrite Theorem17 Theorem17' : set.\n\n\n(* 18 Definition  μ = { x : x = x }. *)\n\nDefinition μ : Class := \\{ λ x, x = x \\}.\n\nCorollary Property_μ : forall x, x ∪ (¬ x) = μ.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme; split; Ens.\n  - apply Axiom_Scheme in H; destruct H; apply Theorem4.\n    generalize (classic (z∈x)); intros; destruct H1; try tauto.\n    right; apply Axiom_Scheme; split; auto.\nQed.\n\nHint Unfold μ : set.\nHint Rewrite Property_μ : set.\n\n\n(* 19 Theorem  x∈μ if and only if x is a set.  *)\n\nTheorem Theorem19 : forall x, x ∈ μ <-> Ensemble x.\nProof.\n  intros; split; intro.\n  - apply Axiom_Scheme in H; destruct H; tauto.\n  - apply Axiom_Scheme; split; auto.\nQed.\n\nHint Resolve Theorem19 : set.\n\n\n(* 20 Theorem  x ∪ μ = μ and x ∩ μ = x. *)\n\nTheorem Theorem20 : forall x, x ∪ μ = μ.\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Theorem4 in H; destruct H; try tauto.\n    apply Theorem19; Ens.\n  - apply Theorem4; tauto.\nQed.\n\nTheorem Theorem20' : forall x, x ∩ μ = x.\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Theorem4' in H; tauto.\n  - apply Theorem4'; split; auto.\n    apply Theorem19; Ens.\nQed.\n\nHint Rewrite Theorem20 Theorem20' : set.\n\n\n(* 21 Theorem  ¬ Φ = μ and ¬ μ = Φ. *)\n\nTheorem Theorem21 : ¬ Φ = μ.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Theorem19; Ens.\n  - apply Theorem19 in H; apply Axiom_Scheme; split; auto.\n    apply Theorem16; auto.\nQed.\n\nTheorem Theorem21' : ¬ μ = Φ.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H; destruct H.\n    apply Theorem19 in H; contradiction.\n  - apply Axiom_Scheme in H; destruct H; contradiction.\nQed.\n\nHint Rewrite Theorem21 Theorem21' : set.\n\n\n(* 22 Definition  ∩x = { z : for each y, if y∈x, then z∈y }. *)\n\nDefinition Element_I x : Class := \\{ λ z, forall y, y ∈ x -> z ∈ y \\}.\n\nNotation \"∩ x\" := (Element_I x) (at level 66).\n\nHint Unfold Element_I : set.\n\n\n(* 23 Definition  ∪x = { z : for some y, z∈y and y∈x }. *)\n\nDefinition Element_U x : Class := \\{ λ z, exists y, z ∈ y /\\ y ∈ x \\}.\n\nNotation \"∪ x\" := (Element_U x) (at level 66).\n\nHint Unfold Element_U : set.\n\n\n(* 24 Theorem  ∩Φ = μ and ∪Φ = Φ. *)\n\nTheorem Theorem24 : ∩ Φ = μ.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Theorem19; Ens.\n  - apply Axiom_Scheme; apply Theorem19 in H; split; auto.\n    intros; generalize (Theorem16 y); contradiction.\nQed.\n\nTheorem Theorem24' : ∪ Φ = Φ.\nProof.\n  intros; apply Axiom_Extent; split; intro.\n  - apply Axiom_Scheme in H; destruct H, H0, H0.\n    generalize (Theorem16 x); contradiction.\n  - generalize (Theorem16 z); contradiction.\nQed.\n\nHint Rewrite Theorem24 Theorem24' : set. \n\n\n(* 25 Definition  x ⊂ y iff for each z, if z∈x, then z∈y. *)\n\nDefinition Subclass x y : Prop := forall z, z∈x -> z∈y.\n\nNotation \"x ⊂ y\" := (Subclass x y) (at level 70).\n\nHint Unfold Subclass : set.\n\n\n(* 26 Theorem  Φ ⊂ x and x ⊂ μ. *)\n\nTheorem Theorem26 : forall x, Φ ⊂ x.\nProof.\n  intros; unfold Subclass; intros.\n  generalize (Theorem16 z); contradiction.\nQed.\n\nTheorem Theorem26' : forall x, x ⊂ μ.\nProof.\n  intros; unfold Subclass; intros; apply Theorem19; Ens.\nQed.\n\nHint Resolve Theorem26 Theorem26' : set.\n\n\n(* 27 Theorem  x=y iff x⊂y and y⊂x. *)\n\nTheorem Theorem27 : forall x y, (x ⊂ y /\\ y ⊂ x) <-> x=y.\nProof.\n  intros; split; intros.\n  - destruct H; intros; apply Axiom_Extent; split; auto.\n  - rewrite <- H; split; unfold Subclass; auto.\nQed.\n\nHint Resolve Theorem27 : set.\n\n\n(* 28 Theorem  If x⊂y and y⊂z, then x⊂z. *)\n\nTheorem Theorem28 : forall x y z, x ⊂ y /\\ y ⊂ z -> x ⊂ z.\nProof.\n  intros; destruct H; unfold Subclass; auto.\nQed.\n\nHint Resolve Theorem28 : set.\n\n\n(* 29 Theorem  x⊂y iff x∪y = y. *)\n\nTheorem Theorem29 : forall x y, x ∪ y = y <-> x ⊂ y.\nProof.\n  intros; split; intros.\n  - unfold Subclass; intros; apply Axiom_Extent with (z:=z) in H.\n    apply H; apply Theorem4; tauto.\n  - apply Axiom_Extent; split; intros.\n    + apply Theorem4 in H0; destruct H0; auto.\n    + apply Theorem4; tauto.\nQed.\n\nHint Resolve Theorem29 : set.\n\n\n(* 30 Theorem  x⊂y iff x∩y = x. *)\n\nTheorem Theorem30 : forall x y, x ∩ y = x <-> x ⊂ y.\nProof.\n  intros; split; intros.\n  - unfold Subclass; intros; apply Axiom_Extent with (z:=z) in H.\n    apply H in H0; apply Theorem4' in H0; tauto.\n  - apply Axiom_Extent; split; intros.\n    + apply Theorem4' in H0; tauto.\n    + apply Theorem4'; split; auto.\nQed.\n\nHint Resolve Theorem30 : set.\n\n\n(* 31 Theorem  If x ⊂ y, then ∪x ⊂ ∪y and ∩y ⊂ ∩x. *)\n\nTheorem Theorem31 : forall x y, x ⊂ y -> (∪x ⊂ ∪y) /\\ (∩y ⊂ ∩x).\nProof.\n  intros; split.\n  - unfold Subclass; intros; apply Axiom_Scheme in H0; destruct H0.\n    apply Axiom_Scheme; split; auto; intros; destruct H1.\n    exists x0; split; unfold Subclass in H; destruct H1; auto.\n  - unfold Subclass in H; unfold Subclass; intros.\n    apply Axiom_Scheme in H0; destruct H0; apply Axiom_Scheme; split; auto.\nQed.\n\nHint Resolve Theorem31 : set.\n\n\n(* 32 Theorem  If x∈y, then x ⊂ ∪y and ∩y ⊂ x. *)\n\nTheorem Theorem32 : forall x y, x ∈ y -> (x ⊂ ∪y) /\\ (∩y ⊂ x).\nProof.\n  intros; split.\n  - unfold Subclass; intros; apply Axiom_Scheme; split; Ens.\n  - unfold Subclass; intros; apply Axiom_Scheme in H0.\n    destruct H0; apply H1; auto.\nQed.\n\nHint Resolve Theorem32 : set.\n\n\n(* Proper Subclass *)\n\nDefinition ProperSubclass x y : Prop := x ⊂ y /\\ x ≠ y.\n\nNotation \"x ⊊ y\" := (ProperSubclass x y) (at level 70).\n\nCorollary Property_ProperSubclass : forall (x y: Class),\n  x ⊂ y -> (x ⊊ y) \\/ x = y.\nProof.\n  intros.\n  generalize (classic (x = y)); intros.\n  destruct H0; auto.\n  left; unfold ProperSubclass; auto.\nQed.\n\nCorollary Property_ProperSubclass' : forall (x y: Class),\n  x ⊊ y -> exists z, z ∈ y /\\ z ∉ x.\nProof.\n  intros.\n  unfold ProperSubclass in H; destruct H.\n  generalize (Theorem27 x y); intros.\n  apply definition_not with (B:= (x ⊂ y /\\ y ⊂ x)) in H0; try tauto.\n  apply not_and_or in H0; destruct H0; try tauto.\n  unfold Subclass in H0; apply not_all_ex_not in H0; destruct H0.\n  apply imply_to_and in H0; Ens.\nQed.\n\nHint Unfold ProperSubclass : set.\nHint Resolve Property_ProperSubclass Property_ProperSubclass' : set.\n\n\n(* Property_Φ *)\n\nLemma Property_Φ : forall x y, y ⊂ x -> x ~ y = Φ <-> x = y.\nProof.\n  intros; split; intros.\n  - apply Property_ProperSubclass in H; destruct H; auto.\n    apply Property_ProperSubclass' in H; destruct H as [z H], H.\n    assert (z ∈ (x ~ y)).\n    { unfold Difference; apply Theorem4'; split; auto.\n      unfold Complement; apply Axiom_Scheme; split; Ens. }\n    rewrite H0 in H2; generalize (Theorem16 z); intros.\n    contradiction.\n  - rewrite <- H0; apply Axiom_Extent; split; intros.\n    + unfold Difference in H1; apply Theorem4' in H1.\n      destruct H1; unfold Complement in H2.\n      apply Axiom_Scheme in H2; destruct H2; contradiction.\n    + generalize (Theorem16 z); intros; contradiction.\nQed.\n\nHint Resolve Property_Φ : set.\n\n\n(* EXISTENCE OF SETS *)\n\n(* III Axiom of subsets  If x is a set there is a set y such that for each z,\n   if z⊂x, then z∈y. *)\n\nAxiom Axiom_Subsets : forall (x: Class),\n  Ensemble x -> exists y, Ensemble y /\\ (forall z, z⊂x -> z∈y).\n\nHint Resolve Axiom_Subsets : set.\n\n\n(* 33 Theorem  If x is a set and z⊂x, then z is a set. *)\n\nTheorem Theorem33 : forall x z,\n  Ensemble x -> z ⊂ x -> Ensemble z.\nProof.\n  intros; apply Axiom_Subsets in H; destruct H.\n  apply H in H0; Ens.\nQed.\n\nHint Resolve Theorem33 : set.\n\n\n(* 34 Theorem  Φ = ∩μ and ∪μ = μ. *)\n\nTheorem Theorem34 : Φ = ∩μ.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - generalize (Theorem16 z); contradiction.\n  - apply Axiom_Scheme in H; destruct H; apply H0.\n    apply Theorem19; generalize (Theorem26 z); intros.\n    apply Theorem33 in H1; auto.\nQed.\n\nTheorem Theorem34' : μ = ∪μ.\nProof.\n  apply Axiom_Extent; split; intros.\n  - apply Lemma_x in H; destruct H; apply Axiom_Scheme in H.\n    destruct H; apply Axiom_Scheme; split; try auto.\n    generalize (Axiom_Subsets z H); intros.\n    destruct H2; destruct H2; exists x; split.\n    + apply H3; unfold Subclass; auto.\n    + apply Theorem19; auto.\n  - apply Axiom_Scheme in H; destruct H; apply Theorem19; auto.\nQed.\n\nHint Rewrite Theorem34 Theorem34' : set.\n\n\n(* 35 Theorem  If x ≠ Φ, then ∩x is a set. *)\n\nLemma Lemma35 : forall x, x ≠ Φ <-> exists z, z∈x.\nProof.\n  intros; assert (x = Φ <-> ~ (exists y, y∈x)).\n  { split; intros.\n    - intro; destruct H0; rewrite H in H0.\n      apply Axiom_Scheme in H0; destruct H0; case H1; auto.\n    - apply Axiom_Extent; split; intros.\n      + elim H; exists z; auto.\n      + generalize (Theorem16 z); contradiction. }\n  split; intros.\n  - apply definition_not with (B:= ~(exists y, y∈x)) in H0; auto.\n    apply NNPP in H0; destruct H0; exists x0; auto.\n  - apply definition_not with (A:=(~ (exists y, y∈x))); auto.\n    destruct H; split; auto.\nQed.\n\nTheorem Theorem35 : forall x, x ≠ Φ -> Ensemble (∩x).\nProof.\n  intros; apply Lemma35 in H; destruct H; AssE x0.\n  generalize (Theorem32 x0 x H); intros.\n  destruct H1; apply Theorem33 in H2; auto.\nQed.\n\nHint Resolve Lemma35 Theorem35 : set.\n\n\n(* 36 Definition  pow(x) = { y : y ⊂ x }. *)\n\nDefinition PowerClass x : Class := \\{ λ y, y ⊂ x \\}.\n\nNotation \"pow( x )\" := (PowerClass x) (at level 0, right associativity).\n\nHint Unfold PowerClass : set.\n\n\n(* 37 Theorem  μ = pow(μ). *)\n\nTheorem Theorem37 : μ = pow(μ).\nProof.\n  apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme; split; Ens; apply Theorem26'.\n  - apply Axiom_Scheme in H; destruct H; apply Theorem19; auto.\nQed.\n\nHint Rewrite Theorem37 : set.\n\n\n(* 38 Theorem  If x is a set, then pow(x) is a set, and for each y, y ⊂ x iff\n   y ∈ pow(x). *)\n\nTheorem Theorem38 : forall x y,\n  Ensemble x -> Ensemble pow(x) /\\ (y ⊂ x <-> y ∈ pow(x)).\nProof.\n  intros; split.\n  - apply Axiom_Subsets in H; destruct H, H.\n    assert (pow(x) ⊂ x0).\n    { unfold Subclass; intros; apply Axiom_Scheme in H1.\n      destruct H1; apply H0 in H2; auto. }\n    apply Theorem33 in H1; auto.\n  - split; intros.\n    + apply Theorem33 with (z:=y) in H; auto.\n      apply Axiom_Scheme; split; auto.\n    + apply Axiom_Scheme in H0; apply H0.\nQed.\n\nHint Resolve Theorem38 : set.\n\n\n(* 39 Theorem  μ is not a set. *)\n\n(* Russell paradox *)\n\nLemma Lemma_N : ~ Ensemble \\{ λ x, x ∉ x \\}.\nProof.\n  generalize (classic (\\{ λ x, x ∉ x \\} ∈ \\{ λ x, x ∉ x \\})).\n  intros; destruct H.\n  - double H; apply Axiom_Scheme in H; destruct H; contradiction.\n  - intro; elim H; apply Axiom_Scheme; split; auto.\nQed.\n\nTheorem Theorem39 : ~ Ensemble μ.\nProof.\n  unfold not; generalize Lemma_N; intros.\n  generalize (Theorem26' \\{ λ x, x ∉ x \\}); intros.\n  apply Theorem33 in H1; auto.\nQed.\n\nHint Resolve Lemma_N Theorem39 : set.\n\n\n(* 40 Definition  [x] = { z : if x∈μ, then z=x }. *)\n\nDefinition Singleton x : Class := \\{ λ z, x∈μ -> z=x \\}.\n\nNotation \"[ x ]\" := (Singleton x) (at level 0, right associativity).\n\nHint Unfold Singleton : set.\n\n\n(* 41 Theorem  If x is a set, for each y, y∈[x] iff y=x. *)\n\nTheorem Theorem41 : forall x, Ensemble x -> (forall y, y∈[x] <-> y=x).\nProof.\n  intros; split; intros.\n  - apply Axiom_Scheme in H0; destruct H0; apply H1.\n    apply Theorem19 in H; auto.\n  - apply Axiom_Scheme; split; intros; auto.\n    rewrite <- H0 in H; auto.\nQed.\n\nHint Resolve Theorem41 : set.\n\n\n(* 42 Theorem  If x is a set, then [x] is a set. *)\n\nTheorem Theorem42 : forall x, Ensemble x -> Ensemble [x].\nProof.\n  intros; double H; apply Theorem33 with (x:= pow(x)).\n  - apply Theorem38 with (y:=x) in H0; destruct H0; auto.\n  - unfold Subclass; intros.\n    apply Theorem38 with (y:=z) in H0; destruct H0.\n    apply H2; apply Axiom_Scheme in H1; destruct H1.\n    apply Theorem19 in H; apply H3 in H.\n    rewrite H; unfold Subclass; auto.\nQed.\n\nHint Resolve Theorem42 : set.\n\n\n(* 43 Theorem  [x] = μ if and only if x is not a set. *)\n\nTheorem Theorem43 : forall x, [x] = μ <-> ~ Ensemble x.\nProof.\n  split; intros.\n  - unfold not; intros; apply Theorem42 in H0.\n    rewrite H in H0; generalize Theorem39; contradiction.\n  - generalize (Theorem19 x); intros.\n    apply definition_not with (B:= x∈μ) in H; try tauto.\n    apply Axiom_Extent; split; intros.\n    * apply Axiom_Scheme in H1; destruct H1; apply Theorem19; auto.\n    * apply Axiom_Scheme; split; try contradiction.\n      apply Theorem19 in H1; auto.\nQed.\n\nHint Rewrite Theorem43 : set.\n\n\n(* 42' Theorem  If [x] is a set, then x is a set. *)\n\nTheorem Theorem42' : forall x, Ensemble [x] -> Ensemble x.\nProof.\n  intros.\n  generalize (classic (Ensemble x)); intros.\n  destruct H0; auto; generalize (Theorem39); intros.\n  apply Theorem43 in H0; auto.\n  rewrite H0 in H; contradiction.\nQed.\n\nHint Resolve Theorem42' : set.\n\n\n(* 44 Theorem  If x is a set, then ∩[x] = x and ∪[x] = x; if x is not a set,\n   then ∩[x] = Φ and ∪[x] = μ. *)\n\nTheorem Theorem44 : forall x, Ensemble x -> ∩[x] = x /\\ ∪[x] = x.\nProof.\n  intros; generalize (Theorem41 x H); intros.\n  split; apply Axiom_Extent.\n  - split; intros.\n    + apply Axiom_Scheme in H1; destruct H1; apply H2; apply H0; auto.\n    + apply Axiom_Scheme; split; Ens; intros.\n      apply H0 in H2; rewrite H2; auto.\n  - split; intros.\n    + apply Axiom_Scheme in H1; destruct H1, H2, H2.\n      unfold Singleton in H3; apply Axiom_Scheme in H3; destruct H3.\n      rewrite H4 in H2; auto; apply Theorem19; auto.\n    + apply Axiom_Scheme; split; Ens; exists x; split; auto.\n      unfold Singleton; apply Axiom_Scheme; auto.\nQed.\n\nTheorem Theorem44' : forall x, ~ Ensemble x -> ∩[x] = Φ /\\ ∪[x] = μ.\nProof.\n  intros; apply Theorem43 in H; split; rewrite H.\n  - rewrite Theorem34; auto.\n  - rewrite <- Theorem34'; auto.\nQed.\n\nHint Resolve Theorem44 Theorem44' : set.\n\n\n(* IV Axiom of union  If x is a set and y is a set so is x∪y. *)\n\nAxiom Axiom_Union : forall (x y: Class),\n  Ensemble x /\\ Ensemble y -> Ensemble (x∪y).\n\nCorollary Axiom_Union': forall x y,\n  Ensemble (x∪y) -> Ensemble x /\\ Ensemble y.\nProof.\n  intros; split.\n  - assert (x ⊂ (x∪y)).\n    { unfold Subclass; intros; apply Theorem4; tauto. }\n    apply Theorem33 in H0; auto.\n  - assert (y ⊂ (x∪y)).\n    { unfold Subclass; intros; apply Theorem4; tauto. }\n    apply Theorem33 in H0; auto.\nQed.\n\nHint Resolve Axiom_Union Axiom_Union' : set.\n\n\n(* 45 Definition  [x|y] = [x] ∪ [y]. *)\n\nDefinition Unordered x y : Class := [x]∪[y].\n\nNotation \"[ x | y ]\" := (Unordered x y) (at level 0).\n\nHint Unfold Unordered : set.\n\n\n(* 46 Theorem  If x is a set and y is a set, then [x|y] is a set and z∈[x|y]\n   iff z=x or z=y; [x|y] = μ iff x is not a set or y is not a set. *)\n\nTheorem Theorem46 : forall x y z,\n  Ensemble x /\\ Ensemble y -> Ensemble [x|y] /\\ (z∈[x|y] <-> (z=x \\/ z=y)).\nProof.\n  split; intros; destruct H.\n  - apply Theorem42 in H; apply Theorem42 in H0; apply Axiom_Union; auto.\n  - split; intros.\n    + apply Axiom_Scheme in H1; destruct H1.\n      destruct H2; apply Axiom_Scheme in H2; destruct H2.\n      * left; apply H3; apply Theorem19; auto.\n      * right; apply H3; apply Theorem19; auto.\n    + apply Axiom_Scheme; split.\n      * destruct H1; try rewrite <- H1 in H; auto.\n        rewrite <- H1 in H0; auto.\n      * destruct H1.\n        -- left; apply Axiom_Scheme; split; rewrite <- H1 in H; auto.\n        -- right; apply Axiom_Scheme; split; rewrite <- H1 in H0; auto.\nQed.\n\nTheorem Theorem46' : forall x y, [x|y] = μ <-> ~ Ensemble x \\/ ~ Ensemble y.\nProof.\n  unfold Unordered; split; intros.\n  - generalize (Theorem43 ([x] ∪ [y])); intros.\n    destruct H0; rewrite H in H0.\n    assert ([μ] = μ); try apply Theorem43; try apply Theorem39.\n    apply H0 in H2; rewrite <- H in H2.\n    assert (Ensemble([x]∪[y]) <-> Ensemble [x] /\\ Ensemble [y]).\n    { split; try apply Axiom_Union; try apply Axiom_Union'. }\n    apply definition_not in H3; auto.\n    generalize (not_and_or (Ensemble [x]) (Ensemble [y])); intros.\n    apply H4 in H3; destruct H3.\n    + assert (Ensemble [x] <-> Ensemble x).\n      { split; try apply Theorem42'; try apply Theorem42; auto. }\n      apply definition_not in H5; auto.\n    + assert (Ensemble [y] <-> Ensemble y).\n      { split; try apply Theorem42'; try apply Theorem42; auto. }\n      apply definition_not in H5; auto.\n  - destruct H; apply Theorem43 in H; rewrite H; try apply Theorem20.\n    generalize (Theorem6 μ [y]); intros; rewrite H0; apply Theorem20.\nQed.\n\nHint Resolve Theorem46 Theorem46' : set.\n\n\n(* 47 Theorem  If x and y are sets, then ∩[x|y] = x ∩ y and ∪[x|y] = x ∪ y;\n   if either x or y is not a set, then ∩[x|y] = Φ and ∪[x|y] = μ. *)\n\nTheorem Theorem47 : forall x y,\n  Ensemble x /\\ Ensemble y -> (∩[x|y] = x ∩ y) /\\ (∪[x|y] = x ∪ y).\nProof.\n  intros; split; apply Axiom_Extent; intros.\n  - split; intros.\n    + apply Theorem4'.\n      split; apply Axiom_Scheme in H0; destruct H0; apply H1; apply Theorem4.\n      * left; apply Axiom_Scheme; split; try apply H; auto.\n      * right; apply Axiom_Scheme; split; try apply H; auto.\n    + apply Theorem4' in H0; destruct H0.\n      apply Axiom_Scheme; split; intros; try AssE z.\n      apply Theorem4 in H2; destruct H2.\n      * apply Axiom_Scheme in H2; destruct H2; destruct H.\n        apply Theorem19 in H; apply H4 in H; rewrite H; auto.\n      * apply Axiom_Scheme in H2; destruct H2; destruct H.\n        apply Theorem19 in H5; apply H4 in H5; rewrite H5; auto.\n  - split; intros.\n    + apply Axiom_Scheme in H0; destruct H0; destruct H1; destruct H1.\n      apply Theorem4 in H2; apply Theorem4.\n      destruct H2; apply Axiom_Scheme in H2; destruct H2.\n      * left; destruct H; apply Theorem19 in H.\n        apply H3 in H; rewrite H in H1; auto.\n      * right; destruct H; apply Theorem19 in H4.\n        apply H3 in H4; rewrite H4 in H1; auto.\n    + apply Theorem4 in H0; apply Axiom_Scheme.\n      split; destruct H0; try AssE z.\n      * exists x; split; auto; apply Theorem4; left.\n        apply Axiom_Scheme; split; try apply H; trivial.\n      * exists y; split; auto; apply Theorem4; right.\n        apply Axiom_Scheme; split; try apply H; trivial.\nQed.\n\nTheorem Theorem47' : forall x y,\n  ~ Ensemble x \\/ ~ Ensemble y -> (∩[x|y] = Φ) /\\ (∪[x|y] = μ).\nProof.\n  intros; split; apply Theorem46' in H; rewrite H.\n  - rewrite Theorem34; auto.\n  - rewrite <- Theorem34'; auto.\nQed.\n\nHint Resolve Theorem47 Theorem47' : set.\n\n\n(* ORDERED PAIRS: RELATIONS *)\n\n(* 48 Definition  [x,y] = [[x]|[x|y]] *)\n\nDefinition Ordered x y : Class := [ [x] | [x|y]].\n\nNotation \"[ x , y ]\" := (Ordered x y) (at level 0).\n\nHint Unfold Ordered : set.\n\n\n(* 49 Theorem  [x,y] is a set if and only if x is a set and y is a set;\n   if [x,y] is not a set, then [x,y] = μ. *)\n\nTheorem Theorem49 : forall (x y: Class),\n  Ensemble [x,y] <-> Ensemble x /\\ Ensemble y.\nProof.\n  intros; split; intro.\n  - unfold Ordered in H; unfold Unordered in H.\n    apply Axiom_Union' in H; destruct H; apply Theorem42' in H.\n    apply Theorem42' in H; apply Theorem42' in H0; split; auto.\n    unfold Unordered in H0; apply Axiom_Union' in H0.\n    destruct H0; apply Theorem42' in H1; auto.\n  - destruct H; unfold Ordered, Unordered; apply Axiom_Union; split.\n    + apply Theorem42; auto; apply Theorem42; auto.\n    + apply Theorem42; auto; apply Theorem46; auto.\nQed.\n\nTheorem Theorem49' : forall (x y: Class),\n  ~ Ensemble [x,y] -> [x,y] = μ.\nProof.\n  intros; generalize (Theorem49 x y); intros.\n  apply definition_not with (B:= Ensemble x /\\ Ensemble y) in H; try tauto.\n  apply not_and_or in H; apply Theorem46' in H; auto.\n  generalize Theorem39; intros; rewrite <-H in H1.\n  unfold Ordered; apply Theorem46'; auto.\nQed.\n\nHint Resolve Theorem49 Theorem49' : set.\n\n\n(* 50 Theorem  If x and y are sets, then ∪[x,y]=[x|y], ∩[x,y]=[x], ∪∩[x,y]=x,\n   ∩∩[x,y]=x, ∪∪[x,y]=x∪y, ∩∪[x,y]=x∩y. If either x or y is not a set,\n   then ∪∩[x,y]=Φ, ∩∩[x,y]=Φ, ∪∪[x,y]=Φ, ∩∪[x,y]=Φ. *)\n\nLemma Lemma50 : forall (x y: Class),\n  Ensemble x /\\ Ensemble y -> Ensemble [x] /\\ Ensemble [x | y].\nProof.\n  intros; apply Theorem49 in H; auto.\n  unfold Ordered in H; unfold Unordered in H.\n  apply Axiom_Union' in H; destruct H.\n  apply Theorem42' in H; auto.\n  apply Theorem42' in H0; auto.\nQed.\n\nTheorem Theorem50 : forall (x y: Class),\n  Ensemble x /\\ Ensemble y -> (∪[x,y] = [x|y]) /\\ (∩[x,y] = [x]) /\\\n  (∪(∩[x,y]) = x) /\\ (∩(∩[x,y]) = x) /\\ (∪(∪[x,y]) = x∪y) /\\ (∩(∪[x,y]) = x∩y).\nProof.\n  intros; elim H; intros.\n  repeat unfold Ordered; apply Lemma50 in H.\n  apply Theorem47 in H; auto; elim H; intros; repeat split.\n  - rewrite H3; apply Axiom_Extent; split; intros; try (apply Theorem4; tauto).\n    apply Theorem4 in H4; destruct H4; auto; apply Theorem4; tauto.\n  - rewrite H2; apply Axiom_Extent; split; intros.\n    + apply Theorem4' in H4; apply H4.\n    + apply Theorem4'; split; auto; apply Theorem4; tauto.\n  - rewrite H2; apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H4; destruct H4, H5, H5. \n      apply Theorem4' in H6; destruct H6; apply Axiom_Scheme in H6.\n      destruct H6; rewrite <- H8; auto.\n      apply Theorem19; auto.\n    + apply Axiom_Scheme; split; Ens; exists x. \n      split; auto; apply Theorem4'; split.\n      * apply Axiom_Scheme; split; auto.\n      * apply Theorem4; left; apply Axiom_Scheme.\n        split; try apply H0; trivial.\n  - rewrite H2; apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H4; destruct H4.\n      apply H5; apply Theorem4'; split.\n      * apply Axiom_Scheme; split; auto.\n      * apply Theorem4; left; apply Axiom_Scheme; split; auto.\n    + apply Axiom_Scheme; split; Ens.\n      intros; apply Theorem4' in H5. destruct H5. \n      apply Axiom_Scheme in H5. destruct H5. rewrite H7; auto. \n      apply Theorem19; auto.\n  - rewrite H3; apply Axiom_Extent; split; intros.\n    + apply Theorem4; apply Axiom_Scheme in H4; destruct H4, H5, H5. \n      apply Theorem4 in H6; destruct H6.\n      * apply Axiom_Scheme in H6; destruct H6; left; rewrite <- H7; auto. \n        apply Theorem19; auto.\n      * apply Theorem4 in H6; destruct H6. \n        -- apply Axiom_Scheme in H6; destruct H6.\n           left; rewrite <- H7; auto; apply Theorem19; auto.\n        -- apply Axiom_Scheme in H6; destruct H6.\n           right; rewrite <- H7; auto; apply Theorem19; auto.\n    + apply Axiom_Scheme; apply Theorem4 in H4; split.\n      * unfold Ensemble; destruct H4; Ens.\n      * destruct H4.\n        -- exists x; split; auto; apply Theorem4; left.\n           apply Axiom_Scheme; split; auto.\n        -- exists y; split; auto; apply Theorem4; right.\n           apply Theorem4; right; apply Axiom_Scheme; split; auto.\n  - rewrite H3; apply Axiom_Extent; split; intros.\n    + apply Lemma_x in H4; elim H4; intros.\n      apply Axiom_Scheme in H5; apply Axiom_Scheme in H6.\n      destruct H4; apply Theorem4'; split; auto.\n      * apply H5; apply Theorem4; left.\n        apply Axiom_Scheme; split; auto.\n      * apply H6; apply Theorem4; right.\n        apply Theorem4; right.\n        apply Axiom_Scheme; split; auto.\n    + apply Theorem4' in H4; destruct H4. \n      apply Axiom_Scheme; split; Ens.\n      intros; apply Theorem4 in H6; destruct H6.\n      * apply Axiom_Scheme in H6; destruct H6; rewrite H7; auto.\n        apply Theorem19; auto.\n      * apply Axiom_Scheme in H6; destruct H6, H7.\n        -- apply Axiom_Scheme in H7; destruct H7. \n           rewrite H8; auto; apply Theorem19; auto.\n        -- apply Axiom_Scheme in H7; destruct H7.\n           rewrite H8; auto; apply Theorem19; auto.\nQed.\n\nLemma Lemma50' : forall (x y: Class),\n  ~Ensemble x \\/ ~Ensemble y -> ~Ensemble [x] \\/ ~Ensemble [x | y].\nProof.\n  intros; elim H; intros. \n  - left; apply Theorem43 in H0; auto.\n    rewrite H0; apply Theorem39; auto.\n  - right; apply Theorem46' in H; auto.\n    rewrite H; apply Theorem39; auto.\nQed.\n\nTheorem Theorem50' : forall (x y: Class),\n  ~Ensemble x \\/ ~Ensemble y -> (∪(∩[x,y]) = Φ) /\\ (∩(∩[x,y]) = μ)\n  /\\ (∪(∪[x,y]) = μ) /\\ (∩(∪[x,y]) = Φ).\nProof.\n  intros; apply Lemma50' in H; auto.\n  apply Theorem47' in H; destruct H.\n  repeat unfold Ordered; repeat split.\n  - rewrite H; apply Theorem24'; auto.\n  - rewrite H; apply Theorem24; auto.\n  - rewrite H0; rewrite <- Theorem34'; auto.\n  - rewrite H0; rewrite <- Theorem34; auto.\nQed.\n\nHint Resolve Theorem50 Theorem50' : set.\n\n\n(* 51 Definition  1st coord z = ∩∩z. *)\n\nDefinition First z := ∩∩z.\n\nHint Unfold First : set.\n\n\n(* 52 Definition  2nd coord z = (∩∪z)∪(∪∪z)~(∪∩z). *)\n\nDefinition Second z := (∩∪z)∪(∪∪z)~(∪∩z).\n\nHint Unfold Second : set.\n\n\n(* 53 Theorem  2nd coord μ = μ. *)\n\nLemma Lemma53 : μ ~ Φ = μ.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Theorem4' in H; destruct H; auto.\n  - apply Theorem4'; split; auto.\n    apply Axiom_Scheme; split.\n    * apply Theorem19 in H; auto.\n    * apply Theorem16; auto.\nQed.\n\nTheorem Theorem53 : Second μ = μ.\nProof.\n  intros; unfold Second.\n  repeat rewrite <-Theorem34'; auto.\n  repeat rewrite <-Theorem34 ; auto.\n  rewrite Theorem24'; auto.\n  rewrite Lemma53; auto.\n  apply Theorem20; auto.\nQed.\n\nHint Rewrite Theorem53 : set.\n\n\n(* 54 Theorem  If x and y are sets, 1st coord [x,y] = x and 2nd coord [x,y] = y.\n   If either of x and y is not a set, then 1st coord [x,y] = μ and\n   2nd coord [x,y] = μ. *)\n\nLemma Lemma54 : forall (x y: Class),\n  (x ∪ y) ~ x = y ~ x.\nProof.\n  intros.\n  apply Axiom_Extent; split; intros.\n  - apply Theorem4' in H; apply Theorem4'.\n    destruct H; apply Theorem4 in H; split; auto.\n    destruct H; auto; apply Axiom_Scheme in H0.\n    destruct H0; elim H1; auto.\n  - apply Theorem4' in H; apply Theorem4'.\n    destruct H; split; auto.\n    apply Theorem4; tauto.\nQed.\n\nTheorem Theorem54 : forall (x y: Class),\n  Ensemble x /\\ Ensemble y -> First [x,y] = x /\\ Second [x,y] = y.\nProof.\n  intros; apply Theorem50 in H; auto; split.\n  - unfold First; apply H.\n  - destruct H, H0, H1, H2, H3; unfold Second.\n    rewrite H4; rewrite H3; rewrite H1.\n    rewrite Lemma54; auto; unfold Difference.\n    rewrite Theorem6'; auto; rewrite <- Theorem8; auto.\n    rewrite Property_μ; auto; rewrite Theorem20'; auto.\nQed.\n\n\nTheorem Theorem54' : forall (x y: Class),\n  ~Ensemble x \\/ ~Ensemble y -> First [x,y] = μ /\\ Second [x,y] = μ.\nProof.\n  intros; apply Theorem50' in H; auto; split.\n  - unfold First; apply H.\n  - destruct H, H0, H1; unfold Second.\n    rewrite H2; rewrite H1; rewrite H.\n    rewrite Lemma53; auto.\n    apply Theorem20; auto.\nQed.\n\nHint Resolve Theorem54 Theorem54' : set.\n\n\n(* 55 Theorem  If x and y are sets and [x,y] = [u,v], then x=u and y=v. *)\n\nTheorem Theorem55 : forall (x y u v: Class),\n  Ensemble x /\\ Ensemble y -> ([x,y] = [u,v] <-> x = u /\\ y = v).\nProof.\n  intros; split; intros.\n  - double H; apply Theorem49 in H; apply Theorem54 in H1; destruct H1.\n    rewrite H0 in H, H1, H2; apply Theorem49 in H; apply Theorem54 in H.\n    destruct H; rewrite H1 in H; rewrite H2 in H3; split; auto.\n  - destruct H0; rewrite H0, H1; auto.\nQed.\n\nHint Resolve Theorem55 : set.\n\n\n(* 56 Definition  r is a relation if and only if for each member z of r there\n   is x and y such that z = [x,y]. *)\n\nDefinition Relation r : Prop :=\n  forall z, z∈r -> exists x y, z = [x,y].\n\nHint Unfold Relation: set.\n\n\n(* II Classification axiom-scheme  For each b, b ∈ { a : A } if and only if\n   b is a set and B. *)\n\n(* { [x,y] : ... }  If the member is a ordered pair, then { [x,y] : ... } is\n   used. The definition of { [x,y] : ... } is to avoid excessive notation. We\n   agree that { [x,y] : ... } is to be identical with { u : for some x, some y,\n   u = (x,y) and ... }. *)\n\nParameter Classifier_P : (Class -> Class -> Prop) -> Class.\n\nNotation \"\\{\\ P \\}\\\" := (Classifier_P P) (at level 0).\n\nAxiom Axiom_SchemeP : forall (a b: Class) (P: Class -> Class -> Prop),\n  [a,b] ∈ \\{\\ P \\}\\ <-> Ensemble [a,b] /\\ (P a b).\n\nAxiom Property_P : forall (z: Class) (P: Class -> Class -> Prop),\n  z ∈ \\{\\ P \\}\\ -> (exists a b, z = [a,b]) /\\ z ∈ \\{\\ P \\}\\.\n\nLtac PP H a b := apply Property_P in H; destruct H as [[a [b H]]];\n  rewrite H in *.\n\nHint Resolve Axiom_SchemeP Property_P : set.\n\n\n(* 57 Definition  r ∘ s = { [x,z] : for some y, [x,y]∈s and [y,z]∈r }. *)\n\nDefinition Composition r s : Class :=\n \\{\\ λ x z, exists y, [x,y]∈s /\\ [y,z]∈r \\}\\.\n\nNotation \"r ∘ s\" := (Composition r s) (at level 50, no associativity).\n\n(* r∘s = {u : for some x, some y and some z, u=[x,z], [x,y]∈s and [y,z]∈r}. *)\n\nDefinition Composition' r s : Class :=\n  \\{ λ u, exists x y z, u = [x,z] /\\ [x,y] ∈ s /\\ [y,z] ∈ r \\}.\n\nHint Unfold Composition Composition' : set.\n\n\n(* 58 Theorem  (r∘s)∘t = r∘(s∘t). *)\n\nTheorem Theorem58 : forall (r s t: Class),\n  (r ∘ s) ∘ t = r ∘ (s ∘ t).\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - PP H a b. apply Axiom_SchemeP in H0; destruct H0, H1 as [y H1], H1.\n    apply Axiom_SchemeP in H2; destruct H2, H3, H3.\n    apply Axiom_SchemeP; split; auto.\n    exists x; split; try tauto; apply Axiom_SchemeP; split; Ens.\n    AssE [a,y]; AssE [y,x]; apply Theorem49 in H5; apply Theorem49 in H6.\n    destruct H5, H6; apply Theorem49; auto.\n  - PP H a b; apply Axiom_SchemeP in H0; destruct H0, H1 as [y H1], H1.\n    apply Axiom_SchemeP in H1; destruct H1, H3, H3.\n    apply Axiom_SchemeP; split; auto.\n    exists x; split; auto; apply Axiom_SchemeP; split; Ens.\n    AssE [a,x]; AssE [y,b]; apply Theorem49 in H5; apply Theorem49 in H6.\n    destruct H5, H6; apply Theorem49; Ens.\nQed.\n\nHint Rewrite Theorem58 : set.\n\n\n(* 59 Theorem  r∘(s∪t) = r∘s ∪ r∘t and r∘(s∩t) ⊂ r∘s ∩ r∘t. *)\n\nTheorem Theorem59 : forall (r s t: Class),\n  Relation r /\\ Relation s -> r ∘ (s ∪ t) = (r ∘ s) ∪ (r ∘ t) /\\ \n  r ∘ (s ∩ t) ⊂ (r ∘ s) ∩ (r ∘ t).\nProof.\n  intros; split.\n  - apply Axiom_Extent; split; intros.\n    + PP H0 a b; apply Axiom_SchemeP in H1; destruct H1.\n      apply Theorem4.\n      destruct H2 as [y H2]; destruct H2.\n      apply Theorem4 in H2; destruct H2.\n      * left; apply Axiom_SchemeP; split; auto.\n        exists y; split; auto.\n      * right; apply Axiom_SchemeP; split; auto.\n        exists y; split; auto.\n    + apply Theorem4 in H0; destruct H0; PP H0 a b; apply Axiom_SchemeP.\n      * apply Axiom_SchemeP in H1; destruct H1.\n        destruct H2 as [y H2]; destruct H2; split; auto.\n        exists y; split; auto; apply Theorem4; try tauto.\n      * apply Axiom_SchemeP in H1; destruct H1.\n        destruct H2 as [y H2]; destruct H2; split; auto.\n        exists y; split; auto; apply Theorem4; try tauto.\n  - unfold Subclass; intros; PP H0 a b.\n    apply Axiom_SchemeP in H1; destruct H1.\n    destruct H2 as [y H2]; destruct H2.\n    apply Theorem4' in H2; apply Theorem4'; split.\n    + apply Axiom_SchemeP; split; auto.\n      exists y; split; try apply H2; auto.\n    + apply Axiom_SchemeP; split; auto.\n      exists y; split; try apply H2; auto.\nQed.\n\nHint Resolve Theorem59 : set.\n\n\n(* 60 Definition  r⁻¹ = { [x,y] : [y,x] ∈ r }. *)\n\nDefinition Inverse r : Class := \\{\\ λ x y, [y,x]∈r \\}\\.\n\nNotation \"r ⁻¹\" := (Inverse r)(at level 5).\n\nHint Unfold Inverse : set.\n\n\n(* 61 Theorem  If r is a relation, then (r⁻¹)⁻¹ = r. *)\n\nLemma Lemma61 : forall (x y: Class),\n  Ensemble [x,y] <-> Ensemble [y,x].\nProof.\n  intros; split; intros.\n  - apply Theorem49 in H; auto.\n    destruct H; apply Theorem49; auto.\n  - apply Theorem49 in H; auto.\n    destruct H; apply Theorem49; auto.\nQed.\n\nTheorem Theorem61 : forall (r: Class),\n  Relation r -> (r ⁻¹)⁻¹ = r.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - PP H0 a b; apply Axiom_SchemeP in H1; destruct H1.\n    apply Axiom_SchemeP in H2; apply H2.\n  - unfold Relation in H; double H0; apply H in H1.\n    destruct H1 as [a [b H1]]; rewrite H1 in *; clear H1.\n    apply Axiom_SchemeP; split; Ens; apply Axiom_SchemeP; split; auto.\n    apply Lemma61; auto; Ens.\nQed.\n\nHint Rewrite Theorem61 : set.\n\n\n(* 62 Theorem  (r∘s)⁻¹ = (s⁻¹) ∘ (r⁻¹). *)\n\nTheorem Theorem62 : forall (r s: Class),\n  (r ∘ s)⁻¹ = (s⁻¹) ∘ (r⁻¹).\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - PP H a b; apply Axiom_SchemeP in H0; destruct H0 as [H0 H1].\n    apply Axiom_SchemeP; split; auto.\n    apply Axiom_SchemeP in H1; destruct H1, H2, H2.\n    exists x; split.\n    + apply Axiom_SchemeP; split; auto. \n      apply Lemma61; Ens; exists r; auto.\n    + apply Axiom_SchemeP; split; auto.\n      apply Lemma61; Ens.\n  - PP H a b; apply Axiom_SchemeP in H0; destruct H0, H1, H1.\n    apply Axiom_SchemeP; split; auto.\n    apply Axiom_SchemeP in H1; apply Axiom_SchemeP in H2.\n    apply Axiom_SchemeP; split.\n    + apply Lemma61; auto.\n    + exists x; split; try apply H0; try apply H2.\n      destruct H1; auto.\nQed.\n\nHint Rewrite Theorem62 : set.\n\n\n(* FUNCTIONS *)\n\n(* 63 Definition  f is a function if and only if f is a relation and for each x,\n   each y, each z, if [x,y]∈f and [x,z]∈f, then y = z. *)\n\nDefinition Function f : Prop :=\n  Relation f /\\ (forall x y z, [x,y] ∈ f /\\ [x,z] ∈ f -> y=z).\n\nHint Unfold Function : set.\n\n\n(* 64 Theorem  If f is a function and g is a function so is f∘g. *)\n\nTheorem Theorem64 : forall f g,\n  Function f /\\ Function g -> Function (f ∘ g).\nProof.\n  intros; destruct H.\n  unfold Function; split; intros.\n  - unfold Relation; intros; PP H1 a b; eauto.\n  - destruct H1; apply Axiom_SchemeP in H1; apply Axiom_SchemeP in H2.\n    destruct H1, H2, H3, H4, H3, H4.\n    unfold Function in H, H0; destruct H; destruct H0.\n    assert (x0=x1). { apply H8 with x; split; auto. }\n    rewrite H9 in H5; apply H7 with x1; split; auto.\nQed.\n\nHint Resolve Theorem64 : set.\n\n\n(* 65 Definition  domain f = { x : for some y, [x,y]∈f }. *)\n\nDefinition Domain f : Class := \\{ λ x, exists y, [x,y] ∈ f \\}.\n\nNotation \"dom( f )\" := (Domain f)(at level 5).\n\nCorollary Property_dom : forall x y f,\n  [x,y] ∈ f -> x ∈ dom( f ).\nProof.\n  intros; unfold Domain; apply Axiom_Scheme; split; eauto.\n  AssE [x,y]; apply Theorem49 in H0; apply H0.\nQed.\n\nHint Unfold Domain : set.\n\n\n(* 66 Definition  range f = { y : for some x, [x,y]∈f }. *)\n\nDefinition Range f : Class := \\{ λ y, exists x, [x,y] ∈ f \\}.\n\nNotation \"ran( f )\" := (Range f)(at level 5).\n\nCorollary Property_ran : forall x y f,\n  [x,y] ∈ f -> y ∈ ran( f ).\nProof.\n  intros; apply Axiom_Scheme.\n  split; eauto; AssE [x,y].\n  apply Theorem49 in H0; apply H0.\nQed.\n\nHint Unfold Range : set.\n\n\n(* 67 Theorem  domain μ = μ and range μ = μ. *)\n\nTheorem Theorem67 : dom( μ ) = μ /\\ ran( μ ) = μ.\nProof.\n  intros; split; apply Axiom_Extent; split; intros.\n  - AssE z; apply Theorem19; auto.\n  - apply Theorem19 in H.\n    unfold Domain; apply Axiom_Scheme; split; auto.\n    exists z; apply Theorem19.\n    apply Theorem49; split; auto.\n  - AssE z; apply Theorem19; auto.\n  - apply Theorem19 in H.\n    unfold Range; apply Axiom_Scheme; split; auto.\n    exists z; apply Theorem19.\n    apply Theorem49; split; auto.\nQed.\n\nHint Rewrite Theorem67 : set.\n\n\n(* 68 Definition  f[x] = ∩{ y : [x,y]∈f }. *)\n\nDefinition Value f x : Class := ∩ \\{ λ y, [x,y] ∈ f \\}.\n\nNotation \"f [ x ]\" := (Value f x)(at level 5).\n\nCorollary Property_Value : forall f x,\n  Function f -> x ∈ dom( f ) -> [x,f[x]] ∈ f.\nProof.\n  intros; unfold Function in H;destruct H as [_ H].\n  apply Axiom_Scheme in H0; destruct H0, H1.\n  assert (x0=f[x]).\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme; split; intros; try Ens.\n      apply Axiom_Scheme in H3; destruct H3.\n      assert (x0=y). { apply H with x; split; auto. }\n      rewrite <- H5; auto.\n    + apply Axiom_Scheme in H2; destruct H2 as [_ H2].\n      apply H2; apply Axiom_Scheme; split; auto.\n      AssE [x, x0]; apply Theorem49 in H3; apply H3.\n  - rewrite <- H2; auto.\nQed.\n\nHint Unfold Value : set.\nHint Resolve Property_Value : set.\n\n\n(* 69 Theorem  If x ∉ domain f, then f[x]=μ; if x ∈ domain f, then f[x]∈μ. *)\n\nLemma Lemma69 : forall x f,\n  Function f -> (x ∉ dom(f) -> \\{ λ y, [x,y] ∈ f \\} = Φ) /\\\n  (x ∈ dom(f) -> \\{ λ y, [x,y] ∈ f \\} <> Φ).\nProof.\n  intros; split; intros.\n  - generalize (classic (\\{ λ y0, [x, y0] ∈ f \\} = Φ)); intro.\n    destruct H1; auto; apply Lemma35 in H1; auto.\n    elim H1; intro z; intros; apply Axiom_Scheme in H2.\n    destruct H2 as [H2 H3]; apply Property_dom in H3; contradiction.\n  - apply Lemma35; auto; exists f[x].\n    apply Axiom_Scheme; eapply Property_Value in H0; auto.\n    split; auto; apply Property_ran in H0; Ens.\nQed.\n\nTheorem Theorem69 : forall x f,\n  ( x ∉ dom( f ) -> f[x] = μ ) /\\ ( x ∈ dom( f ) -> f[x] ∈  μ ).\nProof.\n  intros; split; intros.\n  - assert (\\{ λ y, [x,y] ∈ f \\} = Φ).\n    { apply Axiom_Extent; split; intros.\n      apply Axiom_Scheme in H0; destruct H0.\n      apply Property_dom in H1; contradiction.\n      generalize (Theorem16 z); intro; contradiction. }\n    unfold Value; rewrite H0; apply Theorem24.\n  - assert (\\{ λ y, [x,y] ∈ f \\} <> Φ).\n    { intro; apply Axiom_Scheme in H; destruct H, H1.\n      generalize (Axiom_Extent \\{ λ y, [x, y] ∈ f \\} Φ); intro.\n      destruct H2; apply H2 with x0 in H0; destruct H0.\n      assert (x0 ∈ Φ).\n      { apply H0; apply Axiom_Scheme; split; auto.\n        AssE [x, x0];  apply Theorem49 in H5; tauto. }\n      eapply Theorem16; eauto. }\n    apply Theorem35 in H0; apply Theorem19; auto.\nQed.\n\nCorollary Property_Value' : forall f x,\n  Function f -> f[x] ∈ ran(f) -> [x,f[x]] ∈ f.\nProof.\n  intros; apply Property_Value; auto.\n  apply Axiom_Scheme in H0; destruct H0, H1.\n  generalize (classic (x ∈ dom( f))); intros.\n  destruct H2; auto; apply Theorem69 in H2; auto.\n  rewrite H2 in H0; generalize (Theorem39); intro; contradiction.\nQed.\n\nHint Resolve Theorem69 : set.\nHint Resolve Property_Value' : set.\n\n\n(* 70 Theorem  If f is a function, then f = { [x,y] : y = f[x] }. *)\n\nTheorem Theorem70 : forall f,\n  Function f -> f = \\{\\ λ x y, y = f[x] \\}\\.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - double H0; unfold Function, Relation in H; destruct H.\n    apply H in H1; destruct H1 as [a [b H1]]; rewrite H1 in *; clear H1.\n    apply Axiom_SchemeP; split; try Ens; apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme; split; intros; try Ens.\n      apply Axiom_Scheme in H3; destruct H3.\n      apply Lemma_xy with (y:=[a, y] ∈ f) in H0; auto.\n      apply H2 in H0; rewrite <- H0; auto.\n    + unfold Value, Element_I in H1; apply Axiom_Scheme in H1; destruct H1.\n      apply H3; apply Axiom_Scheme; split; auto; AssE [a,b].\n      apply Theorem49 in H4; try apply H4.\n  - PP H0 a b; apply Axiom_SchemeP in H1; destruct H1.\n    generalize (classic (a ∈ dom( f ))); intros; destruct H3.\n    + apply Property_Value in H3; auto; rewrite H2; auto.\n    + apply Theorem69 in H3; auto.\n      rewrite H3 in H2; rewrite H2 in H1.\n      apply Theorem49 in H1; destruct H1 as [_ H1].\n      generalize Theorem39; intro; contradiction.\nQed.\n\nHint Resolve Theorem70 : set.\n\n\n(* 71 Theorem  If f and g are functions, then f=g iff f[x]=g[x] for each x. *)\n\nTheorem Theorem71 : forall f g,\n  Function f /\\ Function g -> (f = g <-> forall x, f[x] = g[x]).\nProof.\n  intros; split; intros; try rewrite H0; trivial.\n  destruct H; intros; apply (Theorem70 f) in H; apply (Theorem70 g) in H1.\n  rewrite H; rewrite H1; apply Axiom_Extent; split; intros.\n  - PP H2 a b; apply Axiom_SchemeP in H3; apply Axiom_SchemeP.\n    destruct H3; split; auto; rewrite <- H0; auto.\n  - PP H2 a b; apply Axiom_SchemeP in H3; apply Axiom_SchemeP.\n    destruct H3; split; auto; rewrite -> H0; auto.\nQed.\n\nHint Resolve Theorem71 : set.\n\n\n(* V Axiom of substitution  If f is a function and domain f is a set, then \n   range f is a set. *)\n\nAxiom Axiom_Substitution : forall f,\n  Function f -> Ensemble dom(f) -> Ensemble ran(f).\n\nHint Resolve Axiom_Substitution : set.\n\n\n(* VI Axiom of amalgamation  If x is a set so is ∪x. *)\n\nAxiom Axiom_Amalgamation : forall x, Ensemble x -> Ensemble (∪ x).\n\nHint Resolve Axiom_Amalgamation : set.\n\n\n(* 72 Definition  x × y = { [u,v] : u∈x /\\ v∈y }. *)\n\nDefinition Cartesian x y : Class := \\{\\ λ u v, u∈x /\\ v∈y \\}\\.\n\nNotation \"x × y\" := (Cartesian x y)(at level 2, right associativity).\n\nHint Unfold Cartesian : set.\n\n\n(* 73 Theorem  If u and y are sets so is [u] × y. *)\n\nLemma Ex_Lemma73 : forall u y,\n  Ensemble u /\\ Ensemble y ->\n  exists f, Function f /\\ dom(f) = y /\\ ran(f) = [u] × y.\nProof.\n  intros; destruct H.\n  exists (\\{\\ λ w z, w∈y /\\ z = [u,w] \\}\\).\n  repeat split; intros.\n  - red; intros; PP H1 a b; Ens.\n  - destruct H1; apply Axiom_SchemeP in H1; apply Axiom_SchemeP in H2.\n    destruct H1 as [_ [_ H1]]; destruct H2 as [_ [_ H2]].\n    rewrite H2; auto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H1; destruct H1 as [_ [t H1]].\n      apply Axiom_SchemeP in H1; tauto.\n    + apply Axiom_Scheme; split; try Ens.\n      exists [u,z]; apply Axiom_SchemeP; split; auto.\n      AssE z; apply Theorem49; split; auto.\n      apply Theorem49; tauto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H1; destruct H1, H1, H2.\n      apply Axiom_SchemeP in H2; destruct H2, H3.\n      rewrite H4; apply Axiom_SchemeP; repeat split; auto.\n      * apply Theorem49; split; auto; AssE x0.\n      * apply Axiom_Scheme; split; auto.\n    + PP H1 a b; apply Axiom_SchemeP in H2; destruct H2, H3.\n      apply Axiom_Scheme; split; auto; exists b.\n      apply Axiom_SchemeP; repeat split; auto.\n      * apply Theorem49; split; auto; AssE b.\n      * apply Theorem19 in H; apply Axiom_Scheme in H3.\n        destruct H3; rewrite H5; auto.\nQed.\n\nTheorem Theorem73 : forall u y,\n  Ensemble u /\\ Ensemble y -> Ensemble ([u] × y).\nProof.\n  intros.\n  elim H; intros; apply Ex_Lemma73 in H; auto.\n  destruct H, H, H2; rewrite <- H3; apply Axiom_Substitution; auto.\n  rewrite H2; auto.\nQed.\n\nHint Resolve Theorem73 : set.\n\n\n(* 74 Theorem  If x and y are sets so is x × y. *)\n\nLemma Ex_Lemma74 : forall x y,\n  Ensemble x /\\ Ensemble y -> exists f, Function f /\\ dom( f ) = x /\\\n  ran( f ) = \\{ λ z, exists u, u∈x /\\ z = [u] × y \\}.\nProof.\n  intros; destruct H.\n  exists (\\{\\ λ u z, u∈x /\\ z = [u] × y \\}\\).\n  repeat split; intros.\n  - red; intros; PP H1 a b; Ens.\n  - destruct H1; apply Axiom_SchemeP in H1; apply Axiom_SchemeP in H2.\n    destruct H1, H2, H3, H4; subst z; auto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H1; destruct H1, H2.\n      apply Axiom_SchemeP in H2; tauto.\n    + apply Axiom_Scheme; split; try AssE z.\n      exists (([z]) × y); apply Axiom_SchemeP.\n      repeat split; auto; apply Theorem49; split; auto.\n      apply Theorem73; auto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H1; destruct H1, H2.\n      apply Axiom_SchemeP in H2; apply Axiom_Scheme.\n      split; auto; exists x0; tauto.\n    + apply Axiom_Scheme in H1; destruct H1, H2, H2.\n      apply Axiom_Scheme; split; auto.\n      exists x0; apply Axiom_SchemeP; repeat split; auto.\n      apply Theorem49; split; auto; AssE x0.\nQed.\n\nLemma Lemma74 : forall x y,\n  Ensemble x /\\ Ensemble y ->\n  ∪ \\{ λ z, exists u, u∈x /\\ z = [u] × y \\} = x × y.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H0; destruct H0, H1, H1.\n    apply Axiom_Scheme in H2; destruct H2, H3, H3.\n    rewrite H4 in H1; PP H1 a b.\n    apply Axiom_SchemeP in H5; destruct H5, H6.\n    apply Axiom_SchemeP; repeat split; auto.\n    apply Axiom_Scheme in H6; destruct H6 as [_ H6].\n    AssE x1; apply Theorem19 in H8.\n    rewrite <- H6 in H3; auto.\n  - PP H0 a b; apply Axiom_SchemeP in H1; destruct H1, H2.\n    apply Axiom_Scheme; split; auto.\n    exists (([a]) × y); split; AssE a.\n    + apply Axiom_SchemeP; repeat split; auto.\n      apply Axiom_Scheme; intros; auto.\n    + apply Axiom_Scheme; split.\n      * apply Theorem73; split; try apply H; auto.\n      * exists a; split; auto.\nQed.\n\nTheorem Theorem74 : forall x y,\n  Ensemble x /\\ Ensemble y -> Ensemble x × y.\nProof.\n  intros; double H; double H0; destruct H0.\n  apply Ex_Lemma74 in H; destruct H, H, H3.\n  rewrite <- H3 in H0; apply Axiom_Substitution in H0; auto.\n  rewrite H4 in H0; apply Axiom_Amalgamation in H0.\n  rewrite Lemma74 in H0; auto.\nQed.\n\nHint Resolve Theorem74 : set.\n\n\n(* 75 Theorem  If f is a function and domain f is a set, then f is a set. *)\n\nTheorem Theorem75 : forall f,\n  Function f /\\ Ensemble dom( f ) -> Ensemble f.\nProof.\n  intros; destruct H.\n  assert (Ensemble ran(f)); try apply Axiom_Substitution; auto.\n  assert (Ensemble (dom(f) × ran(f))).\n  { apply Theorem74; split; auto. }\n  apply Theorem33 with (x:=(dom( f ) × ran( f ))); auto.\n  unfold Subclass; intros; rewrite Theorem70 in H3; auto.\n  PP H3 a b; rewrite <- Theorem70 in H4; auto; AssE [a,b].\n  repeat split; auto; apply Axiom_SchemeP; split; auto.\n  generalize (Property_dom a b f H4); intro.\n  generalize (Property_ran a b f H4); intro; tauto.\nQed.\n\nHint Resolve Theorem75 : set.\n\n\n(* 76 Definition  Exponent y x = { f : f is a function, domain f = x and\n   range f ⊂ y }. *)\n\nDefinition Exponent y x : Class :=\n  \\{ λ f, Function f /\\ dom( f ) = x /\\ ran( f ) ⊂ y \\}.\n\nHint Unfold Exponent : set.\n\n\n(* 77 Theorem  If x and y are sets so is Exponent y x. *)\n\nTheorem Theorem77 : forall x y,\n  Ensemble x /\\ Ensemble y -> Ensemble (Exponent y x).\nProof.\n  intros; apply Theorem33 with (x:=(pow(x × y))).\n  - apply Theorem38; auto; apply Theorem74; auto.\n  - unfold Subclass; intros; apply Theorem38.\n    + apply Theorem74; auto.\n    + apply Axiom_Scheme in H0; destruct H0, H1, H2.\n    unfold Subclass; intros; rewrite Theorem70 in H4; auto.\n    PP H4 a b; rewrite <- Theorem70 in H5; auto.\n    AssE [a,b]; apply Axiom_SchemeP; split; auto.\n    generalize (Property_dom a b z H5); intro; rewrite H2 in H7.\n    generalize (Property_ran a b z H5); intro.\n    unfold Subclass in H3; apply H3 in H8; split; auto.\nQed.\n\nHint Resolve Theorem77 : set.\n\n\n(* 78 Definition  f is on x if and only if f is a function and x = domain f. *)\n\nDefinition On f x : Prop := Function f /\\ dom( f ) = x.\n\nHint Unfold On : set.\n\n\n(* 79 Definition  f is to y if and only if f is a function and rang f ⊂ y. *)\n\nDefinition To f y : Prop := Function f /\\ ran(f) ⊂ y.\n\nHint Unfold To : set.\n\n\n(* 80 Definition  f is onto y if and only if f is a function and range f = y. *)\n\nDefinition Onto f y : Prop := Function f /\\ ran(f) = y.\n\nHint Unfold Onto : set.\n\n\nEnd ElementSet.\n\nExport ElementSet.\n\n", "meta": {"author": "styzystyzy", "repo": "Transfinite_Induction", "sha": "f512bdae24d9fdc9d815246b613a305d4869743c", "save_path": "github-repos/coq/styzystyzy-Transfinite_Induction", "path": "github-repos/coq/styzystyzy-Transfinite_Induction/Transfinite_Induction-f512bdae24d9fdc9d815246b613a305d4869743c/theories/Elementary_Set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7385102733583672}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus lf1 (Succ (mult y x)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj251_coqofml_yQCXHw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7385063230563493}}
{"text": "Parameter G : Set.\nParameter mult : G -> G -> G.\nNotation \"x * y\" := (mult x y).\nParameter one : G.\nNotation \"1\" := one.\nParameter inv : G -> G.\nNotation \"/ x\" := (inv x).\nNotation \"x / y\" := (mult x (inv y)).\n\nAxiom mult_assoc : forall x y z, x * (y * z) = (x * y) * z.\nAxiom one_unit_l : forall x, 1 * x = x.\nAxiom inv_l : forall x, /x * x = 1.\n\nLemma inv_r : forall x, x * / x = 1.\nProof.\n  intros.\n  replace (x / x) with (1 * x / x).\n  replace (1 * x / x) with (/ x * x * x / x).\n  replace (/ x * x * x / x) with (/ / x * (/ x) * x / x).\n  replace (/ / x * (/ x) * x / x) with ( / / x * ( / x * x ) / x).\n  rewrite inv_l.\n  rewrite <-mult_assoc.\n  rewrite one_unit_l.\n  rewrite inv_l.\n  reflexivity.\n  \n  rewrite mult_assoc.\n  rewrite inv_l.\n  rewrite one_unit_l.\n  reflexivity.\n  \n  rewrite inv_l.\n  rewrite one_unit_l.\n  rewrite inv_l.\n  rewrite one_unit_l.\n  reflexivity.\n\n  rewrite inv_l.\n  reflexivity.\n\n  rewrite one_unit_l.\n  reflexivity.\n\nQed.\n\nLemma one_unit_r : forall x, x * 1 = x.\nProof.\n  intros.\n  replace (x * 1) with (x / x * x).\n  rewrite inv_r.\n  rewrite one_unit_l.\n  reflexivity.\n  \n  rewrite <-mult_assoc.\n  rewrite inv_l.\n  reflexivity.\nQed.", "meta": {"author": "odanado", "repo": "coq", "sha": "6524eb11b64fc6703af806e94b5405279d099ef2", "save_path": "github-repos/coq/odanado-coq", "path": "github-repos/coq/odanado-coq/coq-6524eb11b64fc6703af806e94b5405279d099ef2/coqex2014/2/kadai2_10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303292, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7385063209155812}}
{"text": "(* Exercise 16 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_016 :\n  (forall x : D, P x \\/ R x x)\n->\n    (forall x : D, P x -> (exists y : D, R x y /\\ R y x))\n  ->\n    forall x : D, exists y : D, R x y.\nProof.\nimp_i a1.\nimp_i a2.\nall_i a.\ndis_e (P a \\/ R a a) a3 a3.\nall_e (forall x:D, P x \\/ R x x) a.\nhyp a1.\nexi_e (exists y:D, R a y /\\ R y a) b a4.\nimp_e (P a).\nall_e (forall x:D, P x -> exists y:D, R x y /\\ R y x) a.\nhyp a2.\nhyp a3.\nexi_i b.\ncon_e1 (R b a).\nhyp a4.\nexi_i a.\nhyp a3.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak11/Taak11_pred016.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7385063181194623}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (x : natural) : natural :=\n  plus y (mult x (Succ y)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj156_coqofml_9Y7ADJ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7385063181194623}}
{"text": "Require Export Logic.\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\nPrint even.\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nTheorem double_even:\n  forall n : nat,\n    ev (double n).\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n    simpl. apply ev_0.\n  Case \"n = S n'\".\n    simpl.\n    apply ev_SS.\n    apply IHn'.\nQed.\n\nTheorem ev__even:\n  forall n,\n    ev n -> even n.\nProof.\n  intros n H.\n  induction H as [| n' H'].\n  Case \"E = ev_0\".\n    unfold even. reflexivity.\n  Case \"E = ev_SS n' H'\".\n    unfold even.\n    apply IHH'.\nQed.\n\nTheorem l:\n  forall n,\n    ev n.\nProof.\n  intros n.\n  induction n.\n  Case \"0\".\n    simpl. apply ev_0.\n  Case \"S n\".\n    simpl.\nAbort.\n\nTheorem ev_sum:\n  forall n m,\n    ev n -> ev m -> ev (n+m).\nProof.\n  intros n m H.\n  induction H as [| n' H'].\n  Case \"ev_0\".\n    intros H.\n    simpl. apply H.\n  Case \"ev_SS n' H'\".\n    intros H.\n    simpl.\n    apply ev_SS.\n    apply IHH'.\n    apply H.\nQed.\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\nTheorem three_is_beautiful: beautiful 3.\nProof.\n  apply b_3.\nQed.\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\n  apply b_sum with (n:=3) (m:=5).\n  apply b_3.\n  apply b_5.\nQed.\n\nTheorem beautiful_plus_eight:\n  forall n,\n    beautiful n -> beautiful (8+n).\nProof.\n  intros n H.\n  apply b_sum with (n:=8) (m:=n).\n  apply eight_is_beautiful.\n  apply H.\nQed.\n\nTheorem beautiful_plus_zero:\n  forall n,\n    beautiful n -> beautiful (n + 0).\nProof.\n  intros n H.\n  apply b_sum with (n:=n) (m:=0).\n  apply H.\n  apply b_0.\nQed.\n\nTheorem b_times2:\n  forall n,\n    beautiful n -> beautiful (2 * n).\nProof.\n  intros n H.\n  simpl.\n  apply b_sum with (n:=n) (m:=n+0).\n  apply H.\n  apply beautiful_plus_zero.\n  apply H.\nQed.\n\nTheorem beautiful_times_zero:\n  forall n,\n    beautiful 0 -> beautiful (n * 0).\nProof.\n  intros n H.\n  induction n as [| n].\n    simpl.\n    apply b_0.\n\n    simpl.\n    apply IHn.\nQed.\n\nTheorem b_timesm:\n  forall n m,\n    beautiful n -> beautiful (m * n).\nProof.\n  intros n m H.\n  generalize dependent n.\n  induction m as [| m'].\n  Case \"m = 0\".\n    intros n H.\n    simpl.\n    apply b_0.\n  Case \"m = S m'\".\n    intros n H.\n    simpl.\n\n    apply b_sum with (n:=n) (m:=m' * n).\n      apply H.\n\n      apply IHm'. apply H.\nQed.\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\nTheorem gorgeous_plus13:\n  forall n,\n    gorgeous n -> gorgeous (13+n).\nProof.\n  intros n H.\n  induction n as [| n'].\n  Case \"n = 0\".\n    simpl.\n    apply g_plus5 with (n:=8).\n    apply g_plus5 with (n:=3).\n    apply g_plus3 with (n:=0).\n    apply H.\n  Case \"n = S n'\".\n    apply g_plus5 with (n:=8 + S n').\n    apply g_plus5 with (n:=3 + S n').\n    apply g_plus3 with (n:=S n').\n    apply H.\nQed.\n", "meta": {"author": "abm", "repo": "software-foundations", "sha": "fcc4a39b688893ffd1744bff851590d28ddf8d68", "save_path": "github-repos/coq/abm-software-foundations", "path": "github-repos/coq/abm-software-foundations/software-foundations-fcc4a39b688893ffd1744bff851590d28ddf8d68/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7385063098112108}}
{"text": "(* Exercise 107 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* de Morgan's conjunction law variant *)\n\nTheorem exercise_107 : ~(A /\\ B) -> ~~ (~A \\/ ~B).\nProof.\nimp_i a1.\nneg_i (A /\\ B) a2.\nhyp a1.\ncon_i.\nneg_e' (~A \\/ ~B) a3.\nhyp a2.\ndis_i1.\nhyp a3.\nneg_e' (~A \\/ ~B) a3.\nhyp a2.\ndis_i2.\nhyp a3.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak10/Taak10_prop107.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7384919428373989}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma mul_split_at_bitwidth_mod bw x y : fst (Z.mul_split_at_bitwidth bw x y)  = (x * y) mod 2^bw.\n  Proof.\n    unfold Z.mul_split_at_bitwidth, LetIn.Let_In; break_innermost_match; Z.ltb_to_lt; try reflexivity;\n      apply Z.land_ones; lia.\n  Qed.\n  Lemma mul_split_at_bitwidth_div bw x y : snd (Z.mul_split_at_bitwidth bw x y)  = (x * y) / 2^bw.\n  Proof.\n    unfold Z.mul_split_at_bitwidth, LetIn.Let_In; break_innermost_match; Z.ltb_to_lt; try reflexivity;\n      apply Z.shiftr_div_pow2; lia.\n  Qed.\n  Lemma mul_split_mod s x y : fst (Z.mul_split s x y)  = (x * y) mod s.\n  Proof.\n    unfold Z.mul_split; break_match; Z.ltb_to_lt;\n      [ rewrite mul_split_at_bitwidth_mod; congruence | reflexivity ].\n  Qed.\n#[global]\n  Hint Rewrite mul_split_mod : to_div_mod.\n  Lemma mul_split_div s x y : snd (Z.mul_split s x y)  = (x * y) / s.\n  Proof.\n    unfold Z.mul_split; break_match; Z.ltb_to_lt;\n      [ rewrite mul_split_at_bitwidth_div; congruence | reflexivity ].\n  Qed.\n#[global]\n  Hint Rewrite mul_split_div : to_div_mod.\n\n  Lemma mul_high_div s x y : Z.mul_high s x y = (x * y) / s.\n  Proof. cbv [Z.mul_high]; now apply mul_split_div. Qed.\n#[global]\n  Hint Rewrite mul_high_div : to_div_mod.\n\n  Lemma mul_split_high s x y : snd (Z.mul_split s x y) = Z.mul_high s x y.\n  Proof. reflexivity. Qed.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/MulSplit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7384919394506982}}
{"text": "Require Import Bool List Arith Bool_nat. \nSet Implicit Arguments.\n\n\n(** * Typed Expressions *)\n\n(** In this section, we will build on the initial example by adding additional expression forms that depend on static typing of terms for safety. *)\n\n(** ** Source Language *)\n\nInductive type : Set := Tint | Tbool.\n\nInductive tbinop : type -> type -> type -> Set :=\n| TPlus : tbinop Tint Tint Tint\n| TTimes : tbinop Tint Tint Tint\n| TEq : forall t, tbinop t t Tbool\n| TLt : tbinop Tint Tint Tbool.\n\n\nInductive texp : type -> Set :=\n| TNConst : nat -> texp Tint\n| TBConst : bool -> texp Tbool\n| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\nDefinition typeDenote (t : type) : Set :=\n  match t with\n    | Tint => nat\n    | Tbool => bool\n  end.\n\nDefinition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b in tbinop arg1 arg2 res with\n    | TPlus => plus\n    | TTimes => mult\n    | TEq Tint => beq_nat\n    | TEq Tbool => eqb\n    | TLt => leb\n  end.\n\n\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n    | TNConst n => n\n    | TBConst b => b\n    | TBinop b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nEval simpl in texpDenote (TNConst 42).\n(** [= 42 : typeDenote Tint] *)\n\n(* begin hide *)\nEval simpl in texpDenote (TBConst false).\n(* end hide *)\nEval simpl in texpDenote (TBConst true).\n(** [= true : typeDenote Tbool] *)\n\nEval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2))\n  (TNConst 7)).\n(** [= 28 : typeDenote Tint] *)\n\nEval simpl in texpDenote (TBinop (TEq Tint) (TBinop TPlus (TNConst 2) (TNConst 2))\n  (TNConst 7)).\n(** [= false : typeDenote Tbool] *)\n\nEval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2))\n  (TNConst 7)).\n(** [= true : typeDenote Tbool] *)\n\n\n(** ** Target Language *)\n\nDefinition tstack := list type.\n\nInductive tinstr : tstack -> tstack -> Set :=\n| TiNConst : forall s, nat -> tinstr s (Tint :: s)\n| TiBConst : forall s, bool -> tinstr s (Tbool :: s)\n| TiBinop : forall arg1 arg2 res s,\n  tbinop arg1 arg2 res\n  -> tinstr (arg1 :: arg2 :: s) (res :: s).\n\nInductive tprog : tstack -> tstack -> Set :=\n| TNil : forall s, tprog s s\n| TCons : forall s1 s2 s3,\n  tinstr s1 s2\n  -> tprog s2 s3\n  -> tprog s1 s3.\n\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n    | nil => unit\n    | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n    | TiNConst _ n => fun s => (n, s)\n    | TiBConst _ b => fun s => (b, s)\n    | TiBinop _ b => fun s =>\n      let '(arg1, (arg2, s')) := s in\n        ((tbinopDenote b) arg1 arg2, s')\n  end.\n\n\nFixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n    | TNil _ => fun s => s\n    | TCons i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\n(** ** Translation *)\n\nFixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n    | TNil _ => fun p' => p'\n    | TCons i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=\n  match e with\n    | TNConst n => TCons (TiNConst _ n) (TNil _)\n    | TBConst b => TCons (TiBConst _ b) (TNil _)\n    | TBinop b e1 e2 => tconcat (tcompile e2 _)\n      (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\nEval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.\n(** [= (42, tt) : vstack (Tint :: nil)] *)\n\nEval simpl in tprogDenote (tcompile (TBConst true) nil) tt.\n(** [= (true, tt) : vstack (Tbool :: nil)] *)\n\nEval simpl in tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2)\n  (TNConst 2)) (TNConst 7)) nil) tt.\n(** [= (28, tt) : vstack (Tint :: nil)] *)\n\nEval simpl in tprogDenote (tcompile (TBinop (TEq Tint) (TBinop TPlus (TNConst 2)\n  (TNConst 2)) (TNConst 7)) nil) tt.\n(** [= (false, tt) : vstack (Tbool :: nil)] *)\n\nEval simpl in tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2))\n  (TNConst 7)) nil) tt.\n(** [= (true, tt) : vstack (Tbool :: nil)] *)\n\n(** %\\smallskip{}%The compiler seems to be working, so let us turn to proving that it _always_ works. *)\n\n\n(** ** Translation Correctness *)\n\n\n(** Again, we need to strengthen the theorem statement so that the induction will go through.  This time, to provide an excuse to demonstrate different tactics, I will develop an alternative approach to this kind of proof, stating the key lemma as: *)\n(* We need an analogue to the [app_assoc_reverse] theorem that we used to rewrite the goal in the last section.  We can abort this proof and prove such a lemma about [tconcat].\n*)\n\n\nLemma tconcat_correct : forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'')\n  (s : vstack ts),\n  tprogDenote (tconcat p p') s\n  = tprogDenote p' (tprogDenote p s).\nProof.\n  induction p; intros.\n  * reflexivity.\n  * intros.\n    simpl.\n    apply IHp.\nQed.\n\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n  tprogDenote (tcompile e ts) s = (texpDenote e, s).\nProof.\n  induction e; intros; try reflexivity.\n  * simpl.\n    rewrite tconcat_correct.\n    rewrite tconcat_correct.\n    rewrite IHe1.\n    rewrite IHe2.\n    reflexivity.\nQed.\n\nTheorem tcompile_correct : forall t (e : texp t),\n  tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\nProof.\n  intros.\n  apply (tcompile_correct' e nil tt).\nQed.\n\nExtraction tcompile.\n\n(* End: *)\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/MultiSortStackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7384919354103088}}
{"text": "Theorem id: forall A:Prop, A -> A.\nProof.\n  exact (fun A:Prop => fun x:A => x).\nQed.\n\nTheorem id2: forall A:Prop, A -> A.\nProof.\n  intros.\n  exact H.\nQed.\n\nTheorem syllogism: forall A B:Prop,\n  A->((A->B)->B).\nProof.\n  intros.\n  apply H0.\n  apply H.\nQed.\n\nTheorem cap: forall A B:Prop,\n  (A/\\B)->A.\nProof.\n  intros.\n  apply H.\nQed.\n\nSection contraposition.\n\nHypothesis classical:forall A:Prop,\n  ~~A->A.\n\nTheorem contraposition1: forall A B:Prop,\n  (A->B)->(~B->~A).\nProof.\n  intros A B ab notb a.\n  apply notb.\n  apply ab.\n  apply a.\nQed.\n\nTheorem contraposition2: forall A B:Prop,\n  (~B->~A)->(A->B).\nProof.\n  intros A B nbna a.\n  apply classical.\n  intros nb.\n  apply nbna.\n  apply nb.\n  apply a.\nQed.\n  \nEnd contraposition.\n\nSection contraposition'.\nHypothesis classical':forall A:Prop,\n  A\\/~A.\n\nTheorem contraposition2':forall A B:Prop,\n  (~B->~A)->(A->B).\nProof.\n  intros A B nbna a.\n  destruct (classical' B) as [b|nb].\n  -apply b.\n  -elimtype False.\n  apply nbna.\n  apply nb.\n  apply a.\nQed.\n\nEnd contraposition'.\n\nTheorem dnot: forall A:Prop,\n  A->~~A.\nProof.\n  intros A a na.\n  apply na.\n  apply a.\nQed.\n\nTheorem final: forall A:Prop,\n  ~~(A\\/~A).\nProof.\n  intros A naorna.\n  apply naorna.\n  right.\n  intros a.\n  apply naorna.\n  left.\n  apply a.\nQed.\n\nInductive mynat: Set:=\n  Z:mynat\n  | S:mynat -> mynat.\n\nFixpoint plus (m n:mynat){struct m}:mynat:=\n  match m with\n    Z=>n\n    | S m' => S(plus m' n)\n  end.\nCompute plus (S Z) (S Z).\n\n", "meta": {"author": "elle-et-noire", "repo": "coq", "sha": "fd253f245131883ee55ff9f1824d4bb417b6e7b7", "save_path": "github-repos/coq/elle-et-noire-coq", "path": "github-repos/coq/elle-et-noire-coq/coq-fd253f245131883ee55ff9f1824d4bb417b6e7b7/lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7384919249824915}}
{"text": "From Coq Require Import Reals.\n\n(** * Real number utility lemmas *)\n\n(** This lemma is needed in fault_weight_state_backwards **)\nLemma Rplusminus_assoc : forall r1 r2 r3,\n  (r1 + r2 - r3)%R = (r1 + (r2 - r3))%R.\nProof.\n  intros. unfold Rminus.\n  apply Rplus_assoc.\nQed.\n\n(** This lemma is needed in fault_weight_state_sorted_subset **)\nLemma Rplusminus_assoc_r : forall r1 r2 r3,\n  (r1 - r2 + r3)%R = (r1 + (- r2 + r3))%R.\nProof.\n  intros. unfold Rminus.\n  apply Rplus_assoc.\nQed.\n\n(** This lemma is needed in fault_weight_state_sorted_subset **)\nLemma Rplus_opp_l : forall r, (Ropp r + r)%R = 0%R.\nProof.\n  intros.\n  rewrite Rplus_comm.\n  apply Rplus_opp_r.\nQed.\n\n(** This lemma is needed in fault_weight_state_sorted_subset **)\nLemma Rplus_ge_reg_neg_r : forall r1 r2 r3,\n  (r2 <= 0)%R -> (r3 <= r1 + r2)%R -> (r3 <= r1)%R.\nProof.\n  intros.\n  apply Rge_le.\n  apply Rle_ge in H.\n  apply Rle_ge in H0.\n  apply (Rplus_ge_reg_neg_r r1 r2 r3 H H0).\nQed.\n\n(** This lemma is needed in fault_weight_state_sorted_subset **)\nLemma Rminus_lt_r : forall r1 r2,\n  (0 <= r2)%R -> (r1 - r2 <= r1)%R.\nProof.\n  intros.\n  rewrite <- Rplus_0_r.\n  unfold Rminus.\n  apply Rplus_le_compat_l.\n  apply Rge_le.\n  apply Ropp_0_le_ge_contravar.\n  assumption.\nQed.\n\nLemma Rminus_lt_r_strict : forall r1 r2,\n  (0 < r2)%R -> (r1 - r2 <= r1)%R.\nProof.\n  intros.\n  rewrite <- Rplus_0_r.\n  unfold Rminus.\n  apply Rplus_le_compat_l.\n  apply Rge_le.\n  apply Ropp_0_le_ge_contravar.\n  apply Rlt_le in H.\n  assumption.\nQed.\n\nLemma Rtotal_le_gt : forall x y,\n  (x <= y)%R \\/ (x > y)%R.\nProof.\n  intros.\n  destruct (Rtotal_order x y) as [Hlt | [Heq | Hgt]].\n  - left. unfold Rle. left. assumption.\n  - left. unfold Rle. right. assumption.\n  - right. assumption.\nQed.\n", "meta": {"author": "zunction", "repo": "casper-cbc-proofs", "sha": "92493810dd32a8301882f9eb8a0488a6ac9d0cd1", "save_path": "github-repos/coq/zunction-casper-cbc-proofs", "path": "github-repos/coq/zunction-casper-cbc-proofs/casper-cbc-proofs-92493810dd32a8301882f9eb8a0488a6ac9d0cd1/Lib/RealsExtras.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7384777069512698}}
{"text": "(**\nフィボナッチ数列の和\n========================\n\n@suharahiromichi\n\n2020/07/01\n\n\n2020/07/02 構成をみなおした。\n\n\n2020/07/03 総和を0からにした。\n*)\n\nFrom mathcomp Require Import all_ssreflect.\nRequire Import ssromega.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\n# はじめに\n\nフィボナッチ ffibonacci 数列の和はいくつかのおもしろい性質があります（文献[1]）。\nどれも、中学の数学で証明できるものですが、\nここでは、``Σ``の定義と関連する\n補題を含む MathComp の bigop.v ライブラリ（文献[3][4]）を使って証明してみましょう。\n\n扱う数は、0以上の整数だけとします。\n\nこのファイルは、以下にあります。\n\nhttps://github.com/suharahiromichi/coq/blob/master/math/ssr_fib_sum.v\n\n\nまた、\n\nhttps://github.com/suharahiromichi/coq/blob/master/common/ssromega.v\n\n\nも必要です。\n *)\n\n(**\n# Σの補題\n\nbigop.v は、モノイド則の成り立つ演算子と単位元に対して、繰返し演算を提供するものです。\n自然数の加算 addn と 0 に対応するのが ``Σ`` (``sum``) ですが、\n補題は繰返し演算(``big``)の一般で示されているので、必要なもを探すのが大変です。\n\n今回は、もっぱら``Σ``を通して bigop.v に慣れることを目標にしますから、\n煩瑣になりますが、``Σ``についてだけの補題を証明して置きます。\n慣れたならば、直接 bigop.v の補題を使うほうがよいかもしれません。\n\nなお、本節において $a_n$ は任意の数列の項を示します（フィボナッチ数列に\n限定しません）。\n *)\n\nSection Summation.\n(**\n## 総和の結合と分配\n\n高校で習う、総和についての公式です。\n\n総和の範囲は、$m \\lt n$ としてmからnとします。\n$m \\ge n$ の場合は、Σの中身が単位元となり成立しません。\n\n```math\n\n\\sum_{i=m}^{n-1}a_i + \\sum_{i=m}^{n-1}b_i = \\sum_{i=m}^{n-1}(a_i + b_i) \\\\\n\n\\sum_{i=m}^{n-1}c a_i = c \\sum_{i=m}^{n-1}a_i \\\\\n\n\\sum_{i=m}^{n-1}(a_i c) = (\\sum_{i=m}^{n-1}a_i) c \\\\\n\n```\n*)\n  Lemma sum_split m n a b :\n    m < n ->\n    \\sum_(m <= i < n)(a i) + \\sum_(m <= i < n)(b i) = \\sum_(m <= i < n)(a i + b i).\n  Proof. by rewrite big_split. Qed.\n\n  Lemma sum_distrr m n c a :\n    m < n ->\n    \\sum_(m <= i < n)(c * (a i)) = c * (\\sum_(m <= i < n)(a i)).\n  Proof. by rewrite big_distrr. Qed.\n\n  Lemma sum_distrl m n a c :\n    m < n ->\n    \\sum_(m <= i < n)((a i) * c) = (\\sum_(m <= i < n)(a i)) * c.\n  Proof. by rewrite big_distrl. Qed.\n\n(**\n## 0を取り出す。\n\n$$ \\sum_{i \\in \\emptyset}a_i = 0 $$\n\n総和をとる範囲が無い場合（0以上0未満）は、単位元``0``になります。\n *)\n  Lemma sum_nil' a : \\sum_(0 <= i < 0)(a i) = 0.\n  Proof.\n      by rewrite big_nil.\n  Qed.\n  \n(**\n上記の補題は、1以上1未満などの場合にも適用できてしまいますが、任意のmとnで証明しておきます。\n*)\n  Lemma sum_nil m n a : n <= m -> \\sum_(m <= i < n)(a i) = 0.\n  Proof.\n    move=> Hmn.\n    have H : \\sum_(m <= i < n)(a i) = \\sum_(i <- [::])(a i).\n    - apply: congr_big => //=.\n      rewrite /index_iota.\n      have -> : n - m = 0 by ssromega. (* apply/eqP; rewrite subn_eq0. *)\n      done.\n    - rewrite H.\n        by rewrite big_nil.\n  Qed.\n  \n(**\n## ``a n``項を取り出す。\n\n$$ \\sum_{i=n}^{n}a_i = a_n $$\n\n総和をとる範囲がひとつの項の場合（n以上n以下）は、``a n`` となります。\n *)\n  Lemma sum_nat1 n a :\n    \\sum_(n <= i < n.+1)(a i) = a n.\n  Proof. by rewrite big_nat1. Qed.\n  \n(**\n## 総和の範囲を0起源に振りなおす。\n\n項のインデックスを調整して（ずらして）、mからn+mまでの総和の範囲を0からnまでにします。\n\n$$ \\sum_{i=m}^{n+m-1}a_i = \\sum_{i=0}^{n-1}a_{i+m} $$\n *)\n  Lemma sum_addn (m n : nat) a :\n    \\sum_(m <= i < n + m)(a i) = \\sum_(0 <= i < n)(a (i + m)).\n  Proof.\n    rewrite -{1}[m]add0n.\n    rewrite big_addn.\n    have -> : n + m - m = n by ssromega.\n    done.\n  Qed.\n\n(**\nこれは、任意のmで成り立ちますが、``Σ``の中の項のインデックスの``i.+1``を\n``i + 1`` に書き換えられないため、``i.+1`` と ``i.+2`` の場合については、\n個別に用意する必要があります。実際はこちらの方を使います。\n*)\n  Lemma sum_add1 n a :\n    \\sum_(1 <= i < n.+1)(a i) = \\sum_(0 <= i < n)(a i.+1).\n  Proof. by rewrite big_add1 succnK. Qed.\n\n  Lemma sum_add2 n a :\n    \\sum_(2 <= i < n.+2)(a i) = \\sum_(0 <= i < n)(a i.+2).\n  Proof. by rewrite 2!big_add1 2!succnK. Qed.\n  \n(**\n## 最初の項をΣの外に出す。\n\n$$ \\sum_{i=m}^{n-1}a_i = a_m + \\sum_{i=m+1}^{n-1}a_i $$\n *)\n  Lemma sum_first m n a :\n    m < n ->\n    \\sum_(m <= i < n)(a i) = a m + \\sum_(m.+1 <= i < n)(a i).\n  Proof.\n    move=> Hn.\n      by rewrite big_ltn.\n  Qed.\n\n(**\n総和の範囲の起点を変えずに、インデックスをずらす補題もあります。\n\n$$ \\sum_{i=m}^{n}a_i = a_m + \\sum_{i=m}^{n-1}a_{i + 1} $$\n*)\n  Lemma sum_first' m n a :\n    m <= n ->\n    \\sum_(m <= i < n.+1)(a i) = a m + \\sum_(m <= i < n)(a i.+1).\n  Proof.\n    move=> Hn.\n      by rewrite big_nat_recl.\n  Qed.\n  \n(**\n## 最後の項をΣの外に出す。\n\n$$ \\sum_{i=m}^{n}a_i = \\sum_{i=m}^{n-1}a_i + a_n $$\n *)\n  Lemma sum_last m n a :\n    m <= n ->\n    \\sum_(m <= i < n.+1)(a i) = \\sum_(m <= i < n)(a i) + a n.\n  Proof.\n    move=> Hmn.\n      by rewrite big_nat_recr.\n  Qed.\nEnd Summation.  \n\nSection Fib_1.\n(**\n# フィボナッチ fibonacci 数列の定義\n\nフィボナッチ数列 $ a_n $ を index についての関数として定義します。\n\n```math\n\n\\begin{eqnarray}\nF_0 &=& 0 \\\\\nF_1 &=& 1 \\\\\nF_n &=& F_{n - 2} + F_{n - 1} \\\\\n\\end{eqnarray}\n\n```\n\nフィボナッチ数列の定義そのままなので、再帰関数になります。\n\n*)\n  Fixpoint fib n : nat :=\n    match n with\n    | 0 => 0\n    | 1 => 1\n    | (m.+1 as n).+1 => fib m + fib n (* fib n.-2 + fib n.-1 *)\n    end.\n \n(**\n# 簡単な補題\n\n定義から導かれる補題を証明しておきます。\n*)\n  Lemma fib_n n : fib n.+2 = fib n + fib n.+1.\n  Proof. done. Qed.\n\n  Lemma fibn1_ge_1 n : 1 <= fib n.+1.\n  Proof.\n    elim: n => // n IHn.\n    rewrite fib_n.\n    rewrite addn_gt0.\n      by apply/orP/or_intror.\n  Qed.\n  \n  Lemma fibn2_ge_1 n : 1 <= fib n.+2.\n  Proof.\n    elim: n => // n IHn.\n    rewrite fib_n.\n    rewrite addn_gt0.\n      by apply/orP/or_intror.\n  Qed.\n  \n(**\n# フィボナッチ数列の性質\n\n定理は、概ね文献[2]にそいます。n は $ 0 \\le n $ の自然数として、\n総和の範囲は 0 から n とします（$ \\sum_{i=0}^{n}a_i $）。\nMathCompでは ``\\sum_(0 <= i < n.+1)(a i)`` となります。\n\n$F_0 = 0$なので、1からの総和でも結果に変わりがないのですが（奇数の和をのぞく）、\nnに対する数学的帰納法を使うときなどで、$n=0$の\n場合に、$\\sum_{i=0}^{0}a_i = a_0$ であるようにすると気持ちがよいからです。\n\n1からの場合は、(1から0の)空の総和となり、$\\sum_{i=1}^{0}a_i = 0$ \nと単位元になってしまいます（それでも、成立する場合があります）。\n*)\n\n(**\n## 性質0 (数列の和の加算)\n\n$$ \\sum_{i=0}^{n}F_i + \\sum_{i=0}^{n}F_{i+1} = \\sum_{i=0}^{n}F_{i+2} $$\n*)\n  Lemma add_of_sum_of_seq_of_fib n :\n    \\sum_(0 <= i < n.+1)(fib i) + \\sum_(0 <= i < n.+1)(fib i.+1) =\n    \\sum_(0 <= i < n.+1)(fib i.+2).\n  Proof. by rewrite sum_split. Qed.\n  \n(**\n## 性質1 (フィボナッチ数列の和)\n\n$$ \\sum_{i=0}^{n}F_i = F_{n+2} - 1 $$\n *)\n  Lemma sum_of_seq_of_fib n :\n    \\sum_(0 <= i < n.+1)(fib i) = fib n.+2 - 1.\n  Proof.  \n    have H := add_of_sum_of_seq_of_fib n.\n    rewrite -sum_add1 -sum_add2 in H.\n    rewrite [\\sum_(1 <= i < n.+2)(fib i)]sum_first in H; last done.\n    rewrite [\\sum_(2 <= i < n.+3)(fib i)]sum_last in H; last done.\n    rewrite addnA in H.\n    rewrite [\\sum_(2 <= i < n.+2) fib i + fib n.+2]addnC in H.\n    \n    (* 前提 H の両辺の共通項を消す。 *)\n    move/eqP in H.\n    rewrite eqn_add2r in H.\n    move/eqP in H.\n\n    rewrite -H.\n    rewrite [fib 1]/=.\n      by ssromega.                   (* rewrite addn1 subn1 succnK. *)\n  Qed.\n  \n(**\n別証明として、n についての数学的帰納法で解いてみます。\n\nこちらのほうが随分簡単そうなので、\n以降の性質も帰納法で証明してみます。\n *)\n  Lemma sum_of_seq_of_fib' n :\n    \\sum_(0 <= i < n.+1)(fib i) = fib n.+2 - 1.\n  Proof.  \n    elim: n => [| n IHn].\n    - by rewrite sum_nat1.\n    - rewrite sum_last; last done.\n      rewrite IHn.\n      rewrite addnBAC; last by rewrite fibn2_ge_1.\n      congr (_ - _).\n        by rewrite addnC.\n  Qed.\n\n(**\n## 性質2 (二乗の和)\n\n$$ \\sum_{i=0}^{n}(F_i)^2 = F_{n} F_{n + 1} $$\n\n*)\n  Lemma sum_of_seq_of_sqr_of_fib n :\n    \\sum_(0 <= i < n.+1)((fib i)^2) = fib n * fib n.+1.\n  Proof.\n    elim: n => [| n IHn].\n    - by rewrite sum_nat1.\n    - rewrite sum_last; last done.\n      rewrite IHn.\n      rewrite -mulnDl.\n      rewrite mulnC.\n        by congr (_ * _).\n  Qed.\n\n(**\n## 性質3 (奇数の和)\n\nこれは、0からの総和と、1からの総和で結果が異なるので、両方証明しておきます。\n\n```math\n\n\\sum_{i=0}^{n-1}F_{2 i + 1} = F_{2n} \\\\\n\n\\sum_{i=1}^{n}F_{2 i - 1} = F_{2n}\n```\n\n*)  \n  Lemma sum_of_seq_of_odd_index_of_fib n :\n    \\sum_(0 <= i < n)(fib i.*2.+1) = fib n.*2.\n    elim: n => [| n IHn].\n    - by rewrite sum_nil.\n    - have -> : n.+1.*2 = n.*2.+2\n        by rewrite -addn1 -!muln2; ssromega.\n      rewrite fib_n.                        (* 右辺 *)\n      rewrite sum_last; last done.          (* 左辺 *)\n      rewrite IHn.\n        by congr (_ + _).\n  Qed.\n\n  Lemma sum_of_seq_of_odd_index_of_fib' n :\n    \\sum_(1 <= i < n.+1)(fib i.*2.-1) = fib n.*2.\n  Proof.\n    elim: n => [| n IHn].\n    - by rewrite sum_nil.\n    - have -> : n.+1.*2 = n.*2.+2\n        by rewrite -addn1 -!muln2; ssromega.\n      rewrite fib_n.                        (* 右辺 *)\n      rewrite sum_last; last done.          (* 左辺 *)\n      rewrite IHn.\n        by congr (_ + _).\n  Qed.\n  \n(**\n## 性質4 (偶数の和)\n\n$$ \\sum_{i=0}^{n}F_{2 i} = F_{2 n + 1} - 1 $$\n\n*)\n  Lemma l_sum_of_seq_of_even_index_of_fib n :\n    \\sum_(0 <= i < n.+1)(fib i.*2) + 1 = fib n.*2.+1.\n  Proof.\n    elim: n => [| n IHn].\n    - by rewrite sum_nat1.\n    - have H : n.+1.*2 = n.*2.+2\n        by rewrite doubleS; ssromega.\n      (* rewrite -addn1 -!muln2 addn1 2!muln2 doubleS. *)\n      \n      (* 右辺 *)\n      rewrite H !fib_n -{1}IHn -addnA -fib_n.\n      rewrite [1 + fib n.*2.+2]addnC.\n      \n      (* 左辺 *)      \n      rewrite sum_last; last done.\n      rewrite -H -addnA.\n      done.\n  Qed.\n  \n  Lemma sum_of_seq_of_even_index_of_fib n :\n    \\sum_(0 <= i < n.+1)(fib i.*2) = fib n.*2.+1 - 1.\n  Proof.\n    rewrite -l_sum_of_seq_of_even_index_of_fib.\n      by rewrite addn1 subn1 -pred_Sn.\n  Qed.\n  \n(**\n# おまけ\n\n## 性質5 (となりどうしのフィボナッチ数列は互いに素である)\n *)\n  Lemma coprime_cons_fibs n : coprime (fib n) (fib n.+1).\n  Proof.\n    rewrite /coprime.\n    elim: n => [//= | n IHn].\n    rewrite fib_n.\n      by rewrite gcdnDr gcdnC.\n  Qed.\nEnd Fib_1.\n\n(**\n# 文献\n\n[1] フィボナッチ数列と中学入試問題\n\nhttp://www.suguru.jp/Fibonacci/\n\n\n[2] ProofWiki\n- https://proofwiki.org/wiki/Sum_of_Sequence_of_Fibonacci_Numbers\n- https://proofwiki.org/wiki/Sum_of_Sequence_of_Squares_of_Fibonacci_Numbers\n- https://proofwiki.org/wiki/Sum_of_Sequence_of_Odd_Index_Fibonacci_Numbers\n- https://proofwiki.org/wiki/Sum_of_Sequence_of_Even_Index_Fibonacci_Numbers\n- https://proofwiki.org/wiki/Consecutive_Fibonacci_Numbers_are_Coprime\n\n\n[3] 萩原学 アフェルト・レナルド、「Coq/SSReflect/MathCompによる定理証明」、森北出版\n\n\n[4] Reynald Affeldt, cheat sheet bigop.v\n\nhttps://staff.aist.go.jp/reynald.affeldt/ssrcoq/bigop_doc.pdf\n*)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/math/ssr_fib_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7384777028284004}}
{"text": "Require Import List Relations ZArith Lia Program ssreflect.\n\nSection Maximum.\n  Variable A : Set.\n  Variable max : A -> A -> A.\n  Definition maximum x xs := fold_left max xs x.\n\n  Hypothesis max_select : forall x y, max x y = x \\/ max x y = y.\n\n  Theorem maximum_select : forall xs x, In (maximum x xs) (x :: xs).\n  Proof.\n    elim => /= [ | x ? IH x' ]; eauto.\n    case (max_select x' x) => ->; [ case (IH x') | case (IH x) ]; eauto.\n  Qed.\n\n  Variable le : relation A.\n  Hypothesis le_refl : forall x, le x x.\n  Hypothesis le_trans : forall x y z, le x y -> le y z -> le x z.\n  Hypothesis max_left : forall x y, le x (max x y).\n  Hypothesis max_right : forall x y, le y (max x y).\n\n  Theorem maximum_join : forall xs x y, In y (x :: xs) -> le y (maximum x xs).\n  Proof.\n    elim => /= [ ? ? [ -> | [ ] ] | x xs IHxs x' y [ -> | [ -> | ] ] ]; eauto.\n  Qed.\n\n  Definition maximum_spec x xs := conj (maximum_select xs x) (maximum_join xs x).\n\n  Definition maximum_concrete x xs :\n    fold_left max xs x = maximum x xs := eq_refl.\nEnd Maximum.\n\nSection ZMaximum.\n  Local Open Scope Z_scope.\n\n  Definition Zmaximum := maximum _ Z.max.\n  Definition Zminimum := maximum _ Z.min.\n\n  Corollary Zmaximum_spec : forall x xs,\n    (In (Zmaximum x xs) (x :: xs)) /\\\n    (forall y, In y (x :: xs) -> y <= Zmaximum x xs).\n  Proof. by apply /maximum_spec; lia. Qed.\n\n  Corollary Zminimum_spec : forall x xs,\n    In (Zminimum x xs) (x :: xs) /\\\n    (forall y, In y (x :: xs) -> y >= Zminimum x xs).\n  Proof. by apply /maximum_spec; lia. Qed.\n\n  Corollary neg_Zmaximum_distr x xs :\n    - Zmaximum x xs = Zminimum (- x) (map Z.opp xs).\n  Proof.\n    case (Zmaximum_spec x xs) => HmaxIn Hmax.\n    case (Zminimum_spec (- x) (map Z.opp xs)) => HminIn Hmin.\n    have /Hmin : In (- Zmaximum x xs) (map Z.opp (x :: xs)) by apply /in_map.\n    have : In (- Zminimum (- x) (map Z.opp xs)) (map Z.opp (map Z.opp (x :: xs))) by apply /in_map.\n    rewrite map_map (map_ext (fun x => - - x) id) /id ?map_id => [ | /Hmax ]; lia.\n  Qed.\n\n  Corollary neg_Zminimum_distr x xs :\n    - Zminimum x xs = Zmaximum (- x) (map Z.opp xs).\n  Proof.\n    have -> : Zminimum x xs = Zminimum (- - x) (map Z.opp (map Z.opp xs)).\n    { congr (Zminimum _ _).\n      - by lia.\n      - rewrite map_map -(map_ext id) ?map_id // /id. by lia. }\n    rewrite -neg_Zmaximum_distr. by lia.\n  Qed.\n\n  Corollary Zmaximum_concrete : forall x xs,\n    fold_left Z.max xs x = Zmaximum x xs.\n  Proof. exact /maximum_concrete. Qed.\nEnd ZMaximum.\n\nSection MinMax.\n  Local Open Scope Z_scope.\n\n  Variable board : Set.\n  Variable succ : board -> list board.\n  Variable eval : board -> Z.\n\n  Fixpoint minimax b n :=\n    match n with\n    | O => eval b\n    | S n =>\n        match succ b with\n        | nil => eval b\n        | b :: bs =>\n            Zmaximum\n              (minimax' b n)\n              (map (fun b => minimax' b n) bs)\n        end\n    end\n  with minimax' b n :=\n    match n with\n    | O => eval b\n    | S n =>\n        match succ b with\n        | nil => eval b\n        | b :: bs =>\n            Zminimum\n              (minimax b n)\n              (map (fun b => minimax b n) bs)\n        end\n    end.\n\n  Fixpoint negmax (turn : bool) b n :=\n    match n with\n    | O =>\n        if turn then eval b\n        else - eval b\n    | S n =>\n        match succ b with\n        | nil =>\n            if turn then eval b\n            else - eval b\n        | b :: bs =>\n            Zmaximum\n              (- negmax (negb turn) b n)\n              (map Z.opp (map (fun b => negmax (negb turn) b n) bs))\n        end\n    end.\n\n  Theorem negmax_corresponds_minimax : forall n b turn,\n    negmax turn b n = if turn then minimax b n else - minimax' b n.\n  Proof.\n    elim => /= [ ? [ ] | ? IH b [ ] ] //; case (succ b) => // ? ?.\n    - rewrite map_map.\n      congr (Zmaximum _ _); [ | apply /map_ext => ? ]; rewrite IH /=; by lia.\n    - rewrite -neg_Zminimum_distr.\n      congr (- Zminimum _ _); [ | apply /map_ext => ? ]; rewrite IH /=; by lia.\n  Qed.\n\n  Definition Zmaximum_with_alpha {A} alphabeta alpha beta := (fix Zmaximum_with_alpha alpha (xs : list A) :=\n    match xs with\n    | nil => alpha\n    | x :: xs =>\n        let value := alphabeta alpha x in\n        match Z_le_dec beta value with\n        | left _ => value\n        | right _ => Zmaximum_with_alpha (Z.max alpha value) xs\n        end\n    end) alpha.\n\n  Lemma Zmaximum_with_alpha_spec_aux A minimax alphabeta beta\n    (Halphabeta_spec : forall alpha (x : A),\n      alpha < beta ->\n      minimax x <= alpha /\\ alphabeta alpha x <= alpha \\/\n      alpha <= minimax x /\\ minimax x = alphabeta alpha x /\\ minimax x < beta \\/\n      beta <= minimax x /\\ beta <= alphabeta alpha x) :\n    forall xs alpha,\n    alpha < beta ->\n    fold_left Z.max (map minimax xs) alpha = Zmaximum_with_alpha alphabeta alpha beta xs /\\\n    fold_left Z.max (map minimax xs) alpha < beta \\/\n    beta <= fold_left Z.max (map minimax xs) alpha /\\ beta <= Zmaximum_with_alpha alphabeta alpha beta xs.\n  Proof.\n    elim => /= [ | x xs IH alpha ? ].\n    - lia.\n    - case (Halphabeta_spec alpha x) => //= [ [ ? ? ] | [ [ ? [ <- ? ] ] | [ ? ? ] ] ].\n      + case (Z_le_dec beta (alphabeta alpha x)) => ?; try lia.\n        rewrite !Z.max_l; try lia.\n        exact /IH.\n      + case (Z_le_dec beta (minimax x)) => ?; try lia.\n        rewrite !Z.max_r; try lia.\n        exact /IH.\n      + case (Z_le_dec beta (alphabeta alpha x)) => ?; try lia.\n        rewrite Zmaximum_concrete !Z.max_r; try lia.\n        move: (proj2 (Zmaximum_spec (minimax x) (map minimax xs)) _ (or_introl eq_refl)).\n        lia.\n  Qed.\n\n  Corollary Zmaximum_with_alpha_spec A minimax alphabeta alpha beta xs\n    (Halphabeta : alpha < beta)\n    (Halphabeta_spec : forall alpha (x : A),\n      alpha < beta ->\n      minimax x <= alpha /\\ alphabeta alpha x <= alpha \\/\n      alpha <= minimax x /\\ minimax x = alphabeta alpha x /\\ minimax x < beta \\/\n      beta <= minimax x /\\ beta <= alphabeta alpha x) :\n    alpha <= Zmaximum alpha (map minimax xs) /\\\n    Zmaximum alpha (map minimax xs) = Zmaximum_with_alpha alphabeta alpha beta xs /\\\n    Zmaximum alpha (map minimax xs) < beta \\/\n    beta <= Zmaximum alpha (map minimax xs) /\\ beta <= Zmaximum_with_alpha alphabeta alpha beta xs.\n  Proof.\n    rewrite -Zmaximum_concrete.\n    move: (Zmaximum_with_alpha_spec_aux _ _ _ _ Halphabeta_spec xs _ Halphabeta) => [ ] [ ? ? ]; [ left | right ]; repeat split; eauto.\n    rewrite Zmaximum_concrete.\n    apply /(proj2 (Zmaximum_spec _ _)). by left.\n  Qed.\n\n  Fixpoint alphabeta (turn : bool) alpha beta b n :=\n    match n with\n    | O =>\n        if turn then eval b\n        else - eval b\n    | S n =>\n        match succ b with\n        | nil =>\n            if turn then eval b\n            else - eval b\n        | bs =>\n            Zmaximum_with_alpha\n              (fun alpha b => - alphabeta (negb turn) (- beta) (- alpha) b n)\n              alpha beta bs\n        end\n    end.\n\n  Theorem alphabeta_corresponds_negmax : forall n b beta turn alpha,\n    alpha < beta ->\n    negmax turn b n <= alpha /\\ alphabeta turn alpha beta b n <= alpha \\/\n    alpha <= negmax turn b n /\\\n    negmax turn b n = alphabeta turn alpha beta b n /\\\n    negmax turn b n < beta \\/\n    beta <= negmax turn b n /\\ beta <= alphabeta turn alpha beta b n.\n  Proof.\n    elim => /= [ | n IHn b beta ]; try lia.\n    case (succ b) => [ | b_ bs ] turn alpha ?; try lia.\n    rewrite map_map.\n    case (Z_lt_dec alpha (Zmaximum (- negmax (negb turn) b_ n) (map (fun b => - negmax (negb turn) b n) bs))) => ?.\n    - right.\n      have -> : Zmaximum (- negmax (negb turn) b_ n) (map (fun x => - negmax (negb turn) x n) bs) = Zmaximum alpha (map (fun x => - negmax (negb turn) x n) (b_ :: bs)).\n      { case (Zmaximum_spec (- negmax (negb turn) b_ n) (map (fun b => - negmax (negb turn) b n) bs)) => HIn1 Hmax1.\n        case (Zmaximum_spec alpha (map (fun b => - negmax (negb turn) b n) (b_ :: bs))) => [ [ ? | HIn2 ] Hmax2 ]; have := Hmax2 _ (or_intror HIn1); [ | have := (Hmax1 _ HIn2) ]; lia. }\n      { apply /(Zmaximum_with_alpha_spec _ _ (fun alpha b => - alphabeta (negb turn) (- beta) (- alpha) b n) _ beta (b_ :: bs)) => // alpha0 b0 ?.\n        case (IHn b0 (- alpha0) (negb turn) (- beta)) => [ | [ ] | [ [ ? [ ] ] | [ ] ] ]; lia. }\n    - left.\n      have : Zmaximum alpha (map (fun b => - negmax (negb turn) b n) (b_ :: bs)) = alpha.\n      { case (Zmaximum_spec (- negmax (negb turn) b_ n) (map (fun b => - negmax (negb turn) b n) bs)) => HIn1 Hmax1.\n        case (Zmaximum_spec alpha (map (fun b => - negmax (negb turn) b n) (b_ :: bs))) => [ [ | HIn2 ] Hmax2 ];\n        [ | move: (Hmax2 _ (or_intror HIn1)) (Hmax2 _ (or_introl eq_refl)) (Hmax1 _ HIn2) ]; lia. }\n      case (Zmaximum_with_alpha_spec _\n        (fun b => - negmax (negb turn) b n)\n        (fun alpha b => - alphabeta (negb turn) (- beta) (- alpha) b n) alpha beta (b_ :: bs)) => /= [ | alpha0 b0 ? | | ]; try lia.\n      case (IHn b0 (- alpha0) (negb turn) (- beta)) => [ | [ ] | [ [ ? [ ] ] | [ ] ] ]; lia.\n  Qed.\nEnd MinMax.\n", "meta": {"author": "fetburner", "repo": "Misc", "sha": "c48f9166e922dee111c98157d6da45b77cda5ea6", "save_path": "github-repos/coq/fetburner-Misc", "path": "github-repos/coq/fetburner-Misc/Misc-c48f9166e922dee111c98157d6da45b77cda5ea6/MinMax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.738457612868932}}
{"text": "Require Import Nat.\n\nDefinition task :=\n  forall (f : nat -> nat) (n m x : nat),\n    iter (m^n) (A:=nat) f x = iter n (A:=nat->nat) (iter m (A:=nat)) f x.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/028/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566341999997376, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7383718971215398}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_lessthancongruence.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_03 : \n   forall A B C D E F, \n   Lt C D A B -> Cong E F A B ->\n   exists X, BetS E X F /\\ Cong E X C D.\nProof.\nintros.\nassert (Cong A B E F) by (conclude lemma_congruencesymmetric).\nassert (Lt C D E F) by (conclude lemma_lessthancongruence).\nlet Tf:=fresh in\nassert (Tf:exists G, (BetS E G F /\\ Cong E G C D)) by (conclude_def Lt );destruct Tf as [G];spliter.\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7383383625034967}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (z : natural) : natural :=\n  plus y (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj157_coqofml_9sY4fA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7383120486982732}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) : natural :=\n  plus (mult lf1 x) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj246_coqofml_Hec3iL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7383120440507426}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype tuple.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** * Prop and Type *)\n\nLemma sig_exists A (P : A -> Prop) :\n  {x : A | P x} -> exists x : A, P x.\nProof.\ncase=> x px.\nby exists x.\nQed.\n\nDefinition exists_sig A (P : A -> Prop) :\n  (exists x : A, P x) ->\n  {x : A | P x}.\nProof.\nFail case=> x px.\n(**\nError: ...\nCase analysis on sort [Type] is not allowed\nfor inductive definition [ex].\n*)\nAbort.\n(** Recall that [exists x : A, P x] is a notation\n    for [ex P] *)\nCheck ex :  forall A : Type, (A -> Prop) -> Prop.\nCheck sig : forall A : Type, (A -> Prop) -> Type.\n\n(** This happens because [ex] lives in [Prop] --\n    the universe of logical proposititons and\n    [sig] belongs to [Type] -- the universe of\n    computations.\n    If Coq wants to stay compatible with classical\n    logic it needs to prohibit information flow\n    from [Prop] to [Type].\n    In other words, one can use proofs _only_ to\n    build other proofs.\n*)\n\n(** ** But why exactly this restriction? *)\n\n(** First of all, we should mention that [Prop]\n    is _impredicative_, meaning the following\n    typechecks just fine:\n *)\nSection Impredicativity.\n\nCheck (forall P : Prop, P) : Prop.\n\n(**\nThis formula quantifies over all formulas,\nincluding itself:\n *)\n\nVariable p : (forall P : Prop, P).\nCheck p (forall P : Prop, P).\n\nEnd Impredicativity.\n\n\nSection TypeInType.\n(** But what about [Type]? Doesn't it have\n    the same property?  *)\n\nCheck (forall P : Type, P) : Type.\n\n(** Well, no. [Type] is not a primitive universe,\n    in fact, it's a family of indexed universes\n    but the indices are hidden by default.\n    We can recover those like so: *)\n\nSet Printing Universes.\nCheck (forall P : Type, P) : Type.\n(**\n(forall P : Type@{Top.246}, P) : Type@{Top.245}\n     : Type@{Top.245}\n(* {Top.246 Top.245} |= Top.246 < Top.245 *)\n*)\n\n(** To make this more readable we can declare\n    explicit universe levels: *)\nUniverse i j.\nCheck (forall P : Type@{i}, P) : ( Type@{j} ).\n(** Coq infers [i < j] in this case, so following\n    predictably fails: *)\nFail Check (forall P : Type@{i}, P) : ( Type@{i} ).\n(**\nuniverse inconsistency:\nCannot enforce i < i because i = i.\n*)\n\n(** This restriction prevents us from getting\n    the so-called \"type-in-type\" paradox --\n    had we not introduced this hierarchy of\n    universes we would get\n    [Type : Type] which leads to inconsistency\n    as famously shown by Girard.\n *)\n\nCheck Type@{i}.\n(** Type@{i} : Type@{i+1} *)\n\n(** Some more examples: *)\n\nCheck nat.\n(** nat : Set *)\n\nCheck Set.\n(** Set : Type@{Set+1} *)\n\nCheck Prop.\n(** Prop : Type@{Set+1} *)\n\nUnset Printing Universes.\nEnd TypeInType.\n\n\n\n(** * Large elimination *)\n\n(**\nNext, let's look at _large elimination_\nLarge elimination is the ability to build values\nof type [Type] by eliminating an inductive value.\n\nWe used it to prove the disjointness of constructors\nin Lecture 03:\n*)\n\nDefinition false_implies_False_term :\n  false = true -> False\n:=\n  fun     eq :  false = true =>\n    match eq in (_    = b)\n             return (if b then False else True)\n                    (* ^^^^^^^^^^^^^^^^^^^^^^^ *)\n                    (* large elimination       *)\n    with\n    | erefl => I\n    end.\n\n\n(** Now, Coq is known to be consistent with the\n    Law of Excluded Middle, i.e. the following\n    axiom can be safely added\n *)\n\nAxiom LEM : forall P : Prop, P \\/ ~ P.\n\n(** But, as shown by Berardi in the 1990s,\n  impredicativity + excluded middle\n  => proof irrelevance\n\nSee the paper \"Proof-irrelevance out of\nExcluded-middle and Choice in the Calculus of\nConstructions\" - F. Barbanera, S. Berardi(1996)\n *)\n\n(** Had we not prohibited large elimination for\n    the impredicative universe [Prop],\n    we would get a means to proving disjointness\n    of constructors, i.e. that proofs can differ\n    from each other. *)\nInductive Bool : Prop := T : Bool | F : Bool.\n\nFail Definition prf_rel_Bool (Eq : T = F) : False :=\n  match Eq in (_ = y)\n        return (match y with\n                | T => True\n                | F => False\n                end)\n  with\n  | eq_refl => I\n  end.\n\n(** no large elimination for [Prop] *)\nFail Check match F with T => True | F => False end.\n\n(** no such restriction for [Type] *)\nCheck\n  match false with true => True | false => False end.\n\n(**\n  Upshot:\n  proof irrelevance + large elimination\n  => False\n\n  Hence\n  impredicative [Prop] + large elimination + excluded middle\n  => False\n\n  Overall, this lets [Prop] be impredicative\n  and Coq compatible with the law of excluded\n  middle, which is commonly used in mathematics.\n\n  See also https://github.com/FStarLang/FStar/issues/360\n\n*)\n\n\n(** It's now easy to see that some exceptions\n    that won't result in proof _relevance_\n    are fine:\n *)\nDefinition False_to_nat (prf : False) : nat :=\n  match prf with end.\n\nDefinition true_to_nat (prf : True) : nat :=\n  match prf with | I => 0 end.\n\n(** The above examples work because\n    the corresponding inductive types have only\n    zero or one constructors, i.e. not enough\n    to prove the disjointness *)\n\nFail Definition or_to_nat (prf : True \\/ True) : nat :=\n  match prf with\n  | or_introl _ => 0\n  | or_intror _ => 1\n  end.\n(**\nIncorrect elimination of \"prf\" in the inductive type \"or\":\nthe return type has sort \"Set\" while it should be \"Prop\".\nElimination of an inductive object of sort Prop\nis not allowed on a predicate in sort Set\nbecause proofs can be eliminated only to build proofs.\n*)\n\n\n\n(** * Totality and termination *)\n\n(** There is a plugin to control\n    - the guardedness check,\n    - strict positivity rule, and\n    - universe inconsistency check\n    It's not needed with the latest\n    versions of Coq (8.10+).\n    For Coq versions 8.7 - 8.9 it can be installed\n    with opam package manager:\n      opam install coq-typing-flags\n    or compiled manually using instructions from\n    the plugin's homepage:\n    https://github.com/SimonBoulier/TypingFlags\n    To start using the plugin in a Coq file:\n      From TypingFlags Require Import Loader.\n    This adds\n    Set Type In Type / Unset Type In Type\n    and\n    Set Guard Checking / Unset Guard Checking.\n    vernacular commands.\n *)\n\nFrom TypingFlags Require Import Loader.\n\n\n\n(** We already mentioned earlier that\n    Coq is a total language.\n    This ensures its consistency as a logic\n    because it rules out things like the following:\n *)\n\n(** Disable termination checker *)\nUnset Guard Checking.\n\nFixpoint proof_of_False (n : nat) : False :=\n  proof_of_False n.\n\nCheck proof_of_False 0 : False.\n\n(** The following vernacular reveals that\n    the proof of falsehood was obtained due to\n    bypassing of one of the checkers *)\nPrint Assumptions proof_of_False.\n(** Axioms:\n    proof_of_False is positive. *)\n\n\n(** Remark: Coq's implementation does not enforce\n    _strong_ normalization, only weak one *)\n\n(** Enable termination checker again *)\nSet Guard Checking.\n\nFixpoint weak_normalization (n : nat) : nat :=\n  let bar := weak_normalization n in\n  0.\n\nPrint Assumptions weak_normalization.\n(** [Closed under the global context]\n    This means neither axioms were used nor any checker was disabled *)\n\n\n\n(** * Intermezzo: [interleave] function *)\n\n(** ** Elegant, but non-structurally recursive [interleave] function *)\n\nUnset Guard Checking.\nFixpoint interleave_ns {T} (xs ys : seq T)\n           {struct xs} : seq T :=\n  if xs is (x :: xs') then x :: interleave_ns ys xs'\n  else ys.\n\n(** A simple unit test. *)\nCheck erefl :\ninterleave_ns [:: 1; 3] [:: 2; 4] = [:: 1; 2; 3; 4].\n(** As you can see the evaluator does not care\n    if the function passes the guardedness check\n    or not *)\n\nPrint Assumptions interleave_ns.\n(**\n  Axioms:\n  interleave_ns is positive.\n*)\n\n\n(** Here is how [interleave] can be actually defined in Coq: *)\nSet Guard Checking.\nFixpoint interleave {T} (xs ys : seq T) : seq T :=\n  match xs, ys with\n  | (x :: xs'), (y :: ys') =>\n       x :: y :: interleave xs' ys'\n  | [::], _ => ys\n  | _, [::] => xs\n  end.\n\n(** We can even prove the two implementations\n    are \"the same\" *)\nLemma interleave_ns_eq_interleave {T} :\n  (@interleave_ns T) =2 (@interleave T).\nProof.\nby elim=> // x xs IHxs [|y ys] //=; rewrite IHxs.\nQed.\n\n\n(** Coq offers more ways of defining [interleave]\n    function *)\n\n(** ** 1. Using the builtin [Function] plugin *)\n\n(** Activate [Function] plugin,\n    this makes available a new piece of vernacular:\n    [Function] *)\nFrom Coq Require Import Recdef.\n\nDefinition sum_len {T} (xs_ys : seq T * seq T) : nat :=\n  length xs_ys.1 + length xs_ys.2.\n\nFunction interleave_f' {T} (xs_ys : (seq T * seq T))\n         {measure sum_len xs_ys} : seq T :=\n  if xs_ys is (x :: xs', ys) then\n    x :: interleave_f' (ys, xs')\n  else [::].\nProof.\nmove=> X xs_ys xs ys x xs' _ _.\nby rewrite /sum_len /= addnC.\nQed.\n(**\nNotice a bunch of autogenerated definitions:\n\ninterleave_f'_tcc is defined\ninterleave_f'_terminate is defined\ninterleave_f'_ind is defined\ninterleave_f'_rec is defined\ninterleave_f'_rect is defined\nR_interleave_f'_correct is defined\nR_interleave_f'_complete is defined\n *)\n\nFail Check erefl :\n  interleave_f' ([:: 1; 3], [:: 2; 4]) =\n  [:: 1; 2; 3; 4].\nEval hnf in interleave_f' ([:: 1; 3], [:: 2; 4]).\n(**\nThe above gets stuck on:\n  = let (v, _) :=\n      interleave_f'_terminate ([:: 1; 3], [:: 2; 4])\n    in v\n  : seq nat\n*)\nAbout interleave_f'_terminate.\n(**\n...\ninterleave_f'_terminate is opaque\n...\n *)\n\n(** First, we are going to fix evaluation\n    by making [interleave_f_terminate]\n    transparent: *)\nFunction interleave_f {T} (xs_ys : (seq T * seq T))\n         {measure sum_len xs_ys} : seq T :=\n  if xs_ys is (x :: xs', ys) then\n    x :: interleave_f (ys, xs')\n  else [::].\nProof.\nmove=> X xs_ys xs ys x xs' _ _.\nby rewrite /sum_len /= addnC.\n(** [Defined] makes [interleave_f_terminate]\n    transparent *)\nDefined.\n\n(** Now evaluation works: *)\nCheck erefl :\n  interleave_f ([:: 1; 3], [:: 2; 4]) =\n  [:: 1; 2; 3; 4].\nAbout interleave_f_terminate.\n(**\n...\ninterleave_f_terminate is transparent\n...\n*)\n\n\n(** Now let us see how [interleave_f] is built *)\nPrint interleave_f.\n(**\ninterleave_f =\nfun (x : Type) (x0 : seq x * seq x) =>\n  let (v, _) := interleave_f_terminate x0 in v\n     : forall x : Type, seq x * seq x -> seq x\n*)\nAbout interleave_f_terminate.\n(**\ninterleave_f_terminate :\nforall (T : Type) (xs_ys : seq T * seq T),\n{v : seq T |\nexists p : nat,\n  forall k : nat,\n  (p < k)%coq_nat ->\n  forall def : forall T0 : Type,\n                 seq T0 * seq T0 -> seq T0,\n  iter (forall T0 : Type, seq T0 * seq T0 -> seq T0)\n       k\n       interleave_f_F\n       def\n       T\n       xs_ys\n  = v}\n*)\n\n(** Under the hood [interleave_f_terminate]\n    is (of course) a structurally recursive function.\n    To understand what type we do recursion over,\n    let's print the definition of the function and\n    search for [fix] *)\nPrint interleave_f_terminate.\n(**\n...\nfix hrec (T0 : Type) (xs_ys0 : seq T0 * seq T0)\n         (Acc_xs_ys0 : Acc (Wf_nat.ltof\n                              (seq T0 * seq T0)\n                              [eta sum_len])\n                           xs_ys0)\n         {struct Acc_xs_ys0} :\n...\n*)\n\n(** Here we meet the accessibility predicate [Acc]\n    which can be used to define well-founded\n    induction principles *)\nPrint Acc.\n(**\nInductive Acc (A : Type)\n              (R : A -> A -> Prop)\n              (x : A) : Prop :=\n  | Acc_intro :\n      (forall y : A, R y x -> Acc R y) -> Acc R x\n\n[Acc R x] can be read as \"x is accessible under\nrelation R if all elements staying in relation R\nwith it are also accessible\"\n*)\n\n(** Notice that Coq allows us do structural\n    recursion on a term of type [Acc]\n    which lives in [Prop] while building\n    a term of a type living in [Type].\n    (structural recursion involves pattern-matching).\n    But the accessibility predicate is defined\n    to be non-informative (one constructor!).\n *)\n\n\n\n(** ** More on choice operator *)\nSection Find.\n\n(** Getting a concrete value from\n    an abstract existence proof. *)\n\nVariable (P : pred nat).\n\n(** This construction lets us count up *)\nInductive acc_nat i : Prop :=\n| AccNat0 of P i\n| AccNatS of acc_nat i.+1.\n\nLemma find_ex :\n  (exists n, P n) -> {m | P m}.\nProof.\nmove=> exP.\n\nhave: acc_nat 0.\n  case exP => n; rewrite -(addn0 n); elim: n 0 => [|n IHn] j; first by left.\n  by rewrite addSnnS; right; apply: IHn.\n\nmove: 0.\nfix find_ex 2 => m IHm.\ncase Pm: (P m).\n- by exists m.\napply: find_ex m.+1 _.\ncase: IHm.\n- by rewrite Pm.\nby [].\nDefined.\n\nEnd Find.\n\n\n\n(** ** 2. Using the builtin [Program] mechanism *)\n\nFrom Coq Require Import Program.\n\nProgram Fixpoint interleave_p {A} (xs ys : seq A)\n  {measure (length xs + length ys)} : list A :=\n  if xs is (x :: xs') then\n    x :: interleave_p ys xs'\n  else ys.\nNext Obligation. by rewrite addnC. Qed.\n\nCheck erefl :\n  interleave_p [:: 1; 3] [:: 2; 4] =\n  [:: 1; 2; 3; 4].\n\n(** [Program] also relies on [Acc] predicate *)\n\nPrint Assumptions interleave_p.\n(** [Closed under the global context]\n\n    But sometimes [Program] relies on\n    [JMeq_eq] axiom to do dependent pattern\n    matching.\n *)\nCheck JMeq_eq.\n(**\nJMeq_eq : forall (A : Type) (x y : A),\n            x ~= y -> x = y\n*)\nPrint JMeq.\n(**\n\"JMeq\" means \"John Major equality\", a.k.a.\nheterogenous equality.\n\nInductive JMeq (A : Type) (x : A) :\n  forall B : Type, B -> Prop :=\n| JMeq_refl : x ~= x\n\n[~=] is a notation for [JMeq]\n*)\n\n\n(** ** 3. Using the [Equations] plugin *)\n\n(** The plugin can be installed via opam:\n      opam install coq-equations *)\n\nFrom Equations Require Import Equations.\n\nEquations interleave_e {T} (xs ys : seq T) : seq T\n  by wf (length xs + length ys) lt :=\ninterleave_e (x :: xs) ys :=\n  x :: (interleave_e ys xs);\ninterleave_e [::] ys :=\n  ys.\nNext Obligation. by rewrite addnC. Qed.\n\nCheck erefl :\n  interleave_e [:: 1; 3] [:: 2; 4] =\n  [:: 1; 2; 3; 4].\n\n\n(** One more trick to teach Coq termination:\n    nested [fix] *)\n\n(** Ackermann's function *)\n\nFixpoint ack (n m : nat) : nat :=\n  if n is n'.+1 then\n    let fix ackn (m : nat) :=\n        if m is m'.+1 then ack n' (ackn m')\n        else ack n' 1\n    in ackn m\n  else m.+1.\n\n\n\n\n(** * Strict positivity rule *)\n\nPrint Typing Flags.\n\nFail Inductive prop :=\n  RemoveNegation of (prop -> False).\n(**\nNon strictly positive occurrence of \"prop\" in\n\"(prop -> False) -> prop\".\n*)\n\nUnset Guard Checking.\nPrint Typing Flags.\n\nInductive prop :=\n  RemoveNegation of (prop -> False).\nPrint Assumptions prop.\n(**\nAxioms:\nprop is positive.\n*)\n\nDefinition not_prop (p : prop) : False :=\n  let '(RemoveNegation not_p) := p in not_p p.\nCheck not_prop : prop -> False.\n\nCheck RemoveNegation not_prop : prop.\n\nDefinition yet_another_proof_of_False : False :=\n  not_prop (RemoveNegation not_prop).\n\nPrint Assumptions yet_another_proof_of_False.\n(**\nAxioms:\nyet_another_proof_of_False is positive.\nnot_prop is positive.\nprop is positive.\n*)\nSet Guard Checking.\n\n(**\nRoughly, the positivity condition says that\nconstructors for an inductive data type can\nonly depend on maps to the data type but not on\nmaps from it.\n*)\n\n\n\n(** * Bonus: Universe polymorphism *)\n\nDefinition idf {A} : A -> A := fun x => x.\nFail Definition selfidfun := idf (@idf).\n(**\nThe term \"@idf\" has type \"forall A : Type, A -> A\"\nwhile it is expected to have type \"?A\"\n(unable to find a well-typed instantiation for \"?A\": cannot ensure that\n\"Type@{Top.1849+1}\" is a subtype of \"Type@{Top.1849}\").\n*)\n\nSet Universe Polymorphism.\n\nDefinition idf' {A} : A -> A := fun x => x.\nDefinition selfidfun' := idf' (@idf').\nPrint selfidfun'.\n\n(** See more examples in the Coq Reference Manual *)\n", "meta": {"author": "anton-trunov", "repo": "coq-lecture-notes", "sha": "e012addae82da6d8d03f6e789e43f35140dcdfea", "save_path": "github-repos/coq/anton-trunov-coq-lecture-notes", "path": "github-repos/coq/anton-trunov-coq-lecture-notes/coq-lecture-notes-e012addae82da6d8d03f6e789e43f35140dcdfea/code/lecture09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7382494067731015}}
{"text": "(*\n\nRequire Export cat_INDEXED_TYPE.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n(* *)\nSection pcf_syntax.\n\n(*Inductive base_type := Bool | Nat.*)\n\nInductive TY := \n | Bool : TY\n | Nat : TY\n | arrow: TY -> TY -> TY.\n\nInductive PCF_consts : TY -> Type :=\n | Nats : nat -> PCF_consts Nat\n | tt : PCF_consts Bool\n | ff : PCF_consts Bool\n | succ : PCF_consts (arrow Nat Nat)\n | zero : PCF_consts (arrow Nat Bool)\n | condN: PCF_consts (arrow Bool (arrow Nat (arrow Nat Nat)))\n | condB: PCF_consts (arrow Bool (arrow Bool (arrow Bool Bool))).\n\nInductive PCF (V:TY -> Type) : TY -> Type:=\n | Bottom: forall t, PCF V t\n | Const : forall t, PCF_consts t -> PCF V t\n | PCFVar : forall t, V t -> PCF V t\n | PApp : forall t s, PCF V (arrow s t) -> PCF V s -> PCF V t\n | PLam : forall t s, PCF (opt_T t V) s -> PCF V (arrow t s)\n | PRec : forall t, PCF V (arrow t t) -> PCF V t.\n\n\n\nDefinition PCF_varmap (V W: TY -> Type) := \n        forall t:TY, V t -> W t.\n\nFixpoint PCF_rename (V W:TY -> Type) (f:PCF_varmap V W) \n         (t:TY)(v:PCF V t): PCF W t :=\n    match v with\n    | Bottom t => Bottom W t\n    | Const t c => Const W c\n    | PCFVar t v => PCFVar (f t v)\n    | PApp t s u v => PApp (PCF_rename f u) (PCF_rename f v)\n    | PLam t s u => PLam (PCF_rename (lift (M:=opt_T_monad _ )(*u:=t*) f) u)\n    | PRec t u => PRec (PCF_rename f u)\n    end.\n\nLemma PCF_rename_eq (V:TY -> Type)(t:TY)(v: PCF V t) \n  (W: TY -> Type) (f g: PCF_varmap V W)(H: forall t x, f t x = g t x):\n           PCF_rename f v = PCF_rename g v.\nProof. intros V t v; induction v; simpl; auto.\n       \n       intros; rewrite H; auto.\n       \n       intros. rewrite (IHv1 W f g); auto.\n               rewrite (IHv2 W f g); auto.\n               \n       intros. \n       apply f_equal.\n       set (H':=IHv (opt_T t W) (lift (M:=opt_T_monad _ ) f) \n                                (lift (M:=opt_T_monad _ ) g)).\n       simpl in *. rewrite H'; auto.\n       set (H'':= lift_eq (opt_T_monad t )).\n       simpl in *. apply H''; auto.\n        \n       intros; rewrite (IHv W f g H); auto.\nQed.\n\nLemma PCF_rename_id (V:TY -> Type)(t:TY)(v: PCF V t) \n  (f: PCF_varmap V V)(H: forall t x, f t x = x):\n           PCF_rename f v = v.\nProof. intros V t v; induction v; simpl; auto.\n       intros f H; rewrite H; auto.\n       intros f H; rewrite IHv1; try rewrite IHv2; auto.\n       intros f H; rewrite IHv; auto.\n       unfold lift. unfold kleisli. simpl.\n       intros t0 x; destruct x; simpl; \n       try rewrite H; auto.\n       intros f H; rewrite IHv; auto.\nQed.\n\nLemma PCF_rename_comp (V:TY -> Type) (t: TY) (v: PCF V t)\n      (W X: TY -> Type) (f: PCF_varmap V W) (g: PCF_varmap W X):\n      PCF_rename (fun t x => g t (f t x)) v = \n           PCF_rename g (PCF_rename f v).\nProof. intros V t v; induction v; simpl; auto.\n       intros W X f g; rewrite IHv1; rewrite IHv2; auto.\n       intros W X f g. apply f_equal. \n       rewrite <- (IHv _ (opt_T t X)).\n       apply PCF_rename_eq.\n       intros to x.\n       set (H:= lift_lift (opt_T_monad t)).\n       simpl in *. rewrite H; auto.\n       intros W X f g; rewrite IHv; auto.\nQed.\n\n\n(* injection of terms into terms with one variable more, of type u *)\nDefinition PCF_inj(u:TY)(V:TY -> Type)(t:TY)(v:PCF V t): \n           PCF (opt_T u V) t :=\n    PCF_rename (@Some_T TY u V) v.\n\n\n\n\nDefinition PCF_shift (u:TY) (V W:TY -> Type)(f: forall t:TY, V t-> PCF W t) \n              (t:TY) (v: opt_T u V t): PCF (opt_T u W) t :=\n            match v in opt_T _ _ t' return PCF (opt_T u W) t' with\n            | None_T => PCFVar (None_T u W)\n            | Some_T t v => PCF_inj u (f t v)\n            end.\n\nLemma PCF_shift_eq (u:TY) (V:TY -> Type)(t:TY)(v:opt_T u V t)\n          (W:TY -> Type)(f g: forall t, V t -> PCF W t)\n          (H: forall t x, f t x = g t x):\n          PCF_shift f v = PCF_shift g v.\nProof. intros u V t v; induction v; simpl; intros; try rewrite H; auto.\nQed.\n\nLemma PCF_shift_var (u:TY)(V:TY -> Type)(t:TY)(v: opt_T u V t):\n       PCF_shift (fun t x => PCFVar x) v = PCFVar v.\nProof. induction v; intros; simpl; auto. Qed.\n\nLemma PCF_var_lift_shift_eq (u:TY) (V: TY -> Type) (t: TY) (v: opt_T u V t)\n               (W:TY -> Type) (f: forall t, V t -> W t):\n    PCFVar (lift (M:=opt_T_monad u) f _ v) = \n         PCF_shift (fun t x0 => PCFVar (f t x0)) v.\nProof. induction v; simpl; intros; auto. Qed.\n\nLemma PCF_shift_lift (u:TY) (V: TY -> Type) (t:TY)(v:opt_T u V t)\n           (W:TY -> Type)(f: forall t, V t -> W t) (X: TY -> Type)\n                    (g: forall t, W t -> PCF X t): \n   PCF_shift g (lift (M:=opt_T_monad u) f _ v) = \n         PCF_shift (fun t x0 => g t (f t x0)) v.\nProof. induction v; simpl; intros; auto. Qed.\n\n\n\nFixpoint PCF_subst (V W: TY -> Type) (t:TY) (v: PCF V t) \n       (f: forall t, V t -> PCF W t) : PCF W t :=\n    match v with\n    | Bottom t => Bottom W t\n    | Const t c => Const W c\n    | PCFVar t v => f t v\n    | PApp t s u v => PApp (PCF_subst u f) (PCF_subst v f)\n    | PLam t s u => PLam (PCF_subst u (PCF_shift (*u:=t*) f))\n    | PRec t u => PRec (PCF_subst u f)\n    end.\n\nDefinition PCF_substar (u:TY)(V: TY -> Type) (t:TY)(v:PCF (opt_T u V) t) \n      (M:PCF V u): PCF V t := PCF_subst (*V:= opt_T u V*) v \n  (fun t x => match x with  \n            | None_T => M\n            | Some_T _ v => PCFVar v\n            end) .\n\n\nLemma PCF_subst_eq (V:TY -> Type)(t:TY)(v:PCF V t) (W:TY -> Type)\n       (f g: forall t, V t -> PCF W t)\n       (H: forall t x, f t x = g t x) :\n       PCF_subst v f = PCF_subst v g.\nProof. induction v; intros; simpl;  auto.\n  \n       try rewrite (IHv1 W f g);\n       try rewrite (IHv2 W f g); \n       try rewrite (IHv W f g); auto.\n       \n       rewrite (IHv _ (PCF_shift f) (PCF_shift g)); auto.\n       intros; apply PCF_shift_eq; auto.\n       \n       rewrite (IHv W f g); auto.\nQed.\n\nLemma PCF_subst_var (V:TY -> Type)(t:TY)(v:PCF V t):\n       PCF_subst v (fun t x0 => PCFVar x0) = v.\nProof. induction v; intros; simpl; auto.\n       rewrite IHv1. rewrite IHv2; auto.\n       rewrite <- IHv at 2.\n       apply f_equal. apply PCF_subst_eq.\n       intros; apply PCF_shift_var.\n       rewrite IHv; auto.\nQed.\n\nLemma PCF_subst_eq_rename (V:TY -> Type)(t:TY)(v:PCF V t)(W:TY->Type)\n           (f:forall t, V t -> W t):\n        PCF_rename f v = PCF_subst v (fun t x0 => PCFVar (f t x0)).\nProof. induction v; intros; simpl; auto.\n       rewrite IHv1; rewrite IHv2; auto.\n       rewrite IHv. apply f_equal. apply PCF_subst_eq.\n       intros; apply PCF_var_lift_shift_eq.\n       rewrite IHv; auto.\nQed.\n\n\nLemma PCF_rename_term_inj (u:TY)(V:TY -> Type)(t:TY)(v:PCF V t) \n    (W:TY -> Type) (g: forall t, V t -> W t):\n       PCF_rename (opt_T_map (u:=u) g) (PCF_inj u v) = \n                  PCF_inj u (PCF_rename g v).\nProof. induction v; simpl; intros; auto.\n       rewrite IHv1; rewrite IHv2; auto.\n       unfold PCF_inj. simpl.\n       apply f_equal. \n       rewrite <- PCF_rename_comp.\n       rewrite <- PCF_rename_comp.\n       apply PCF_rename_eq.\n       induction x; simpl; auto.\n       rewrite IHv. unfold PCF_inj. simpl. auto.\nQed.\n\nLemma PCF_rename_subst (V:TY -> Type) (t:TY)(v: PCF V t) (W:TY -> Type)\n     (f:forall t, V t -> PCF W t)(X:TY -> Type)(g:forall t, W t -> X t):\n   PCF_rename g (PCF_subst v f) = \n           PCF_subst v (fun t x => PCF_rename g (f t x)).\nProof. induction v; intros; simpl; auto.\n       rewrite IHv1; rewrite IHv2; auto.\n       \n       rewrite IHv. apply f_equal. apply PCF_subst_eq.\n       induction x; simpl; auto.\n       apply PCF_rename_term_inj. \n       \n       rewrite IHv. auto.\nQed.\n\n\nLemma PCF_subst_rename (V:TY -> Type) (t:TY)(v: PCF V t) (W:TY -> Type)\n     (f:forall t, V t -> W t)(X:TY -> Type)(g:forall t, W t -> PCF X t):\n   PCF_subst (PCF_rename f v) g = \n           PCF_subst v (fun t x =>  g t (f t x)).\nProof. induction v; simpl; intros; auto.\n       rewrite IHv1; rewrite IHv2; auto.\n       \n       rewrite IHv. apply f_equal.\n       apply PCF_subst_eq. intros.\n       apply PCF_shift_lift.\n       \n       rewrite IHv. auto.\nQed.\n       \nLemma PCF_subst_term_inj (u:TY)(V:TY -> Type)(t:TY)(v:PCF V t)(W:TY -> Type)\n      (g:forall t, V t -> PCF W t):\n    PCF_subst (PCF_inj u v) (PCF_shift g) = PCF_inj u (PCF_subst v g).\nProof. induction v; simpl; intros; auto.\n       rewrite IHv1; rewrite IHv2; auto.\n       \n       unfold PCF_inj. simpl. apply f_equal.\n       rewrite PCF_rename_subst.\n       rewrite PCF_subst_rename.\n       apply PCF_subst_eq.\n       induction x; simpl; auto.\n       rewrite PCF_rename_term_inj. auto.\n       \n       rewrite IHv; auto.\nQed.\n\n\nLemma PCF_subst_shift_shift (u:TY) (V:TY -> Type) (t:TY)(v:opt_T u V t)\n (W:TY -> Type)\n (f: forall t, V t -> PCF W t) (X:TY -> Type)(g:forall t, W t -> PCF X t):\n  PCF_subst (PCF_shift f v) (PCF_shift g) = \n          PCF_shift (fun t x0 => PCF_subst (f t x0) g) v.\nProof. induction v; simpl; intros; try apply PCF_subst_term_inj; auto.\nQed.\n\nLemma PCF_subst_subst (V:TY -> Type)(t:TY)(v:PCF V t) (W X: TY -> Type)\n         (f:forall t, V t -> PCF W t)(g:forall t, W t -> PCF X t):\nPCF_subst (PCF_subst v f) g = PCF_subst v (fun t x0 => PCF_subst (f t x0) g).\nProof. induction v; simpl; intros; auto.\n       rewrite IHv1; rewrite IHv2; auto.\n\n       rewrite IHv. apply f_equal.\n       apply PCF_subst_eq.\n       intros; simpl.\n       apply PCF_subst_shift_shift.\n       \n       rewrite IHv; auto.\nQed.\n\n\nRequire Export monad_haskell.\n\n\nProgram Instance syntax_monad_h: Monad_struct (ITYPE TY) \n        (fun V => PCF V) := {\n  weta V t v:= PCFVar v;\n  kleisli V W f := fun t x => PCF_subst x f\n}.\n  \n  Next Obligation.\n    Proof. unfold Proper; red. \n           intros. apply PCF_subst_eq. auto.\n    Qed.\n    \n  (*Next Obligation.\n    Proof.  \n           simpl. auto.\n    Qed.\n*)\n  Next Obligation.\n    Proof.\n           intros; apply PCF_subst_var.\n    Qed.\n \n  Next Obligation.\n    Proof.\n           intros; apply PCF_subst_subst.\n    Qed.\n\n\nEnd pcf_syntax.\n\n*)\n\n\n", "meta": {"author": "JasonGross", "repo": "benediktahrens-coq-fossil", "sha": "834bc904a07549ac3f659e68d94a3f1c73c5b72a", "save_path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil", "path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil/benediktahrens-coq-fossil-834bc904a07549ac3f659e68d94a3f1c73c5b72a/PCF/pcf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7382494058771935}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\nRequire Import ZAxioms ZMulOrder ZSgnAbs NZDiv.\n\n(** * Euclidean Division for integers, Euclid convention\n\n    We use here the \"usual\" formulation of the Euclid Theorem\n    [forall a b, b<>0 -> exists b q, a = b*q+r /\\ 0 < r < |b| ]\n\n    The outcome of the modulo function is hence always positive.\n    This corresponds to convention \"E\" in the following paper:\n\n    R. Boute, \"The Euclidean definition of the functions div and mod\",\n    ACM Transactions on Programming Languages and Systems,\n    Vol. 14, No.2, pp. 127-144, April 1992.\n\n    See files [ZDivTrunc] and [ZDivFloor] for others conventions.\n\n    We simply extend NZDiv with a bound for modulo that holds\n    regardless of the sign of a and b. This new specification\n    subsume mod_bound_pos, which nonetheless stays there for\n    subtyping. Note also that ZAxiomSig now already contain\n    a div and a modulo (that follow the Floor convention).\n    We just ignore them here.\n*)\n\nModule Type EuclidSpec (Import A : ZAxiomsSig')(Import B : DivMod' A).\n Axiom mod_always_pos : forall a b, b ~= 0 -> 0 <= a mod b < abs b.\nEnd EuclidSpec.\n\nModule Type ZEuclid (Z:ZAxiomsSig) := NZDiv.NZDiv Z <+ EuclidSpec Z.\nModule Type ZEuclid' (Z:ZAxiomsSig) := NZDiv.NZDiv' Z <+ EuclidSpec Z.\n\nModule ZEuclidProp\n (Import A : ZAxiomsSig')\n (Import B : ZMulOrderProp A)\n (Import C : ZSgnAbsProp A B)\n (Import D : ZEuclid' A).\n\n Module Import NZDivP := Nop <+ NZDivProp A D B.\n\n(** Another formulation of the main equation *)\n\nLemma mod_eq :\n forall a b, b~=0 -> a mod b == a - b*(a/b).\nProof.\nintros.\nrewrite <- add_move_l.\nsymmetry. now apply div_mod.\nQed.\n\nLtac pos_or_neg a :=\n let LT := fresh \"LT\" in\n let LE := fresh \"LE\" in\n destruct (le_gt_cases 0 a) as [LE|LT]; [|rewrite <- opp_pos_neg in LT].\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique : forall b q1 q2 r1 r2 : t,\n  0<=r1<abs b -> 0<=r2<abs b ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof.\nintros b q1 q2 r1 r2 Hr1 Hr2 EQ.\npos_or_neg b.\nrewrite abs_eq in * by trivial.\napply div_mod_unique with b; trivial.\nrewrite abs_neq' in * by auto using lt_le_incl.\nrewrite eq_sym_iff. apply div_mod_unique with (-b); trivial.\nrewrite 2 mul_opp_l.\nrewrite add_move_l, sub_opp_r.\nrewrite <-add_assoc.\nsymmetry. rewrite add_move_l, sub_opp_r.\nnow rewrite (add_comm r2), (add_comm r1).\nQed.\n\nTheorem div_unique:\n forall a b q r, 0<=r<abs b -> a == b*q + r -> q == a/b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0).\n pos_or_neg b.\n rewrite abs_eq in Hr; intuition; order.\n rewrite <- opp_0, eq_opp_r. rewrite abs_neq' in Hr; intuition; order.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\nnow apply mod_always_pos.\nnow rewrite <- div_mod.\nQed.\n\nTheorem mod_unique:\n forall a b q r, 0<=r<abs b -> a == b*q + r -> r == a mod b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0).\n pos_or_neg b.\n rewrite abs_eq in Hr; intuition; order.\n rewrite <- opp_0, eq_opp_r. rewrite abs_neq' in Hr; intuition; order.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\nnow apply mod_always_pos.\nnow rewrite <- div_mod.\nQed.\n\n(** Sign rules *)\n\nLemma div_opp_r : forall a b, b~=0 -> a/(-b) == -(a/b).\nProof.\nintros. symmetry.\napply div_unique with (a mod b).\nrewrite abs_opp; now apply mod_always_pos.\nrewrite mul_opp_opp; now apply div_mod.\nQed.\n\nLemma mod_opp_r : forall a b, b~=0 -> a mod (-b) == a mod b.\nProof.\nintros. symmetry.\napply mod_unique with (-(a/b)).\nrewrite abs_opp; now apply mod_always_pos.\nrewrite mul_opp_opp; now apply div_mod.\nQed.\n\nLemma div_opp_l_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a)/b == -(a/b).\nProof.\nintros a b Hb Hab. symmetry.\napply div_unique with (-(a mod b)).\nrewrite Hab, opp_0. split; [order|].\npos_or_neg b; [rewrite abs_eq | rewrite abs_neq']; order.\nnow rewrite mul_opp_r, <-opp_add_distr, <-div_mod.\nQed.\n\nLemma div_opp_l_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a)/b == -(a/b)-sgn b.\nProof.\nintros a b Hb Hab. symmetry.\napply div_unique with (abs b -(a mod b)).\nrewrite lt_sub_lt_add_l.\nrewrite <- le_add_le_sub_l. nzsimpl.\nrewrite <- (add_0_l (abs b)) at 2.\nrewrite <- add_lt_mono_r.\ndestruct (mod_always_pos a b); intuition order.\nrewrite <- 2 add_opp_r, mul_add_distr_l, 2 mul_opp_r.\nrewrite sgn_abs.\nrewrite add_shuffle2, add_opp_diag_l; nzsimpl.\nrewrite <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma mod_opp_l_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a) mod b == 0.\nProof.\nintros a b Hb Hab. symmetry.\napply mod_unique with (-(a/b)).\nsplit; [order|now rewrite abs_pos].\nnow rewrite <-opp_0, <-Hab, mul_opp_r, <-opp_add_distr, <-div_mod.\nQed.\n\nLemma mod_opp_l_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a) mod b == abs b - (a mod b).\nProof.\nintros a b Hb Hab. symmetry.\napply mod_unique with (-(a/b)-sgn b).\nrewrite lt_sub_lt_add_l.\nrewrite <- le_add_le_sub_l. nzsimpl.\nrewrite <- (add_0_l (abs b)) at 2.\nrewrite <- add_lt_mono_r.\ndestruct (mod_always_pos a b); intuition order.\nrewrite <- 2 add_opp_r, mul_add_distr_l, 2 mul_opp_r.\nrewrite sgn_abs.\nrewrite add_shuffle2, add_opp_diag_l; nzsimpl.\nrewrite <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma div_opp_opp_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a)/(-b) == a/b.\nProof.\nintros. now rewrite div_opp_r, div_opp_l_z, opp_involutive.\nQed.\n\nLemma div_opp_opp_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a)/(-b) == a/b + sgn(b).\nProof.\nintros. rewrite div_opp_r, div_opp_l_nz by trivial.\nnow rewrite opp_sub_distr, opp_involutive.\nQed.\n\nLemma mod_opp_opp_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a) mod (-b) == 0.\nProof.\nintros. now rewrite mod_opp_r, mod_opp_l_z.\nQed.\n\nLemma mod_opp_opp_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a) mod (-b) == abs b - a mod b.\nProof.\nintros. now rewrite mod_opp_r, mod_opp_l_nz.\nQed.\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, a~=0 -> a/a == 1.\nProof.\nintros. symmetry. apply div_unique with 0.\nsplit; [order|now rewrite abs_pos].\nnow nzsimpl.\nQed.\n\nLemma mod_same : forall a, a~=0 -> a mod a == 0.\nProof.\nintros.\nrewrite mod_eq, div_same by trivial. nzsimpl. apply sub_diag.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, 0<=a<b -> a/b == 0.\nProof. exact div_small. Qed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, 0<=a<b -> a mod b == a.\nProof. exact mod_small. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, a~=0 -> 0/a == 0.\nProof.\nintros. pos_or_neg a. apply div_0_l; order.\napply opp_inj. rewrite <- div_opp_r, opp_0 by trivial. now apply div_0_l.\nQed.\n\nLemma mod_0_l: forall a, a~=0 -> 0 mod a == 0.\nProof.\nintros; rewrite mod_eq, div_0_l; now nzsimpl.\nQed.\n\nLemma div_1_r: forall a, a/1 == a.\nProof.\nintros. symmetry. apply div_unique with 0.\nassert (H:=lt_0_1); rewrite abs_pos; intuition; order.\nnow nzsimpl.\nQed.\n\nLemma mod_1_r: forall a, a mod 1 == 0.\nProof.\nintros. rewrite mod_eq, div_1_r; nzsimpl; auto using sub_diag.\napply neq_sym, lt_neq; apply lt_0_1.\nQed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof. exact div_1_l. Qed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof. exact mod_1_l. Qed.\n\nLemma div_mul : forall a b, b~=0 -> (a*b)/b == a.\nProof.\nintros. symmetry. apply div_unique with 0.\nsplit; [order|now rewrite abs_pos].\nnzsimpl; apply mul_comm.\nQed.\n\nLemma mod_mul : forall a b, b~=0 -> (a*b) mod b == 0.\nProof.\nintros. rewrite mod_eq, div_mul by trivial. rewrite mul_comm; apply sub_diag.\nQed.\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, 0<=a -> b~=0 -> a mod b <= a.\nProof.\nintros. pos_or_neg b. apply mod_le; order.\nrewrite <- mod_opp_r by trivial. apply mod_le; order.\nQed.\n\nTheorem div_pos : forall a b, 0<=a -> 0<b -> 0<= a/b.\nProof. exact div_pos. Qed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof. exact div_str_pos. Qed.\n\nLemma div_small_iff : forall a b, b~=0 -> (a/b==0 <-> 0<=a<abs b).\nProof.\nintros a b Hb.\nsplit.\nintros EQ.\nrewrite (div_mod a b Hb), EQ; nzsimpl.\nnow apply mod_always_pos.\nintros. pos_or_neg b.\napply div_small.\nnow rewrite <- (abs_eq b).\napply opp_inj; rewrite opp_0, <- div_opp_r by trivial.\napply div_small.\nrewrite <- (abs_neq' b) by order. trivial.\nQed.\n\nLemma mod_small_iff : forall a b, b~=0 -> (a mod b == a <-> 0<=a<abs b).\nProof.\nintros.\nrewrite <- div_small_iff, mod_eq by trivial.\nrewrite sub_move_r, <- (add_0_r a) at 1. rewrite add_cancel_l.\nrewrite eq_sym_iff, eq_mul_0. tauto.\nQed.\n\n(** As soon as the divisor is strictly greater than 1,\n    the division is strictly decreasing. *)\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof. exact div_lt. Qed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, 0<c -> a<=b -> a/c <= b/c.\nProof.\nintros a b c Hc Hab.\nrewrite lt_eq_cases in Hab. destruct Hab as [LT|EQ];\n [|rewrite EQ; order].\nrewrite <- lt_succ_r.\nrewrite (mul_lt_mono_pos_l c) by order.\nnzsimpl.\nrewrite (add_lt_mono_r _ _ (a mod c)).\nrewrite <- div_mod by order.\napply lt_le_trans with b; trivial.\nrewrite (div_mod b c) at 1 by order.\nrewrite <- add_assoc, <- add_le_mono_l.\napply le_trans with (c+0).\nnzsimpl; destruct (mod_always_pos b c); try order.\nrewrite abs_eq in *; order.\nrewrite <- add_le_mono_l. destruct (mod_always_pos a c); order.\nQed.\n\n(** In this convention, [div] performs Rounding-Toward-Bottom\n    when divisor is positive, and Rounding-Toward-Top otherwise.\n\n    Since we cannot speak of rational values here, we express this\n    fact by multiplying back by [b], and this leads to a nice\n    unique statement.\n*)\n\nLemma mul_div_le : forall a b, b~=0 -> b*(a/b) <= a.\nProof.\nintros.\nrewrite (div_mod a b) at 2; trivial.\nrewrite <- (add_0_r (b*(a/b))) at 1.\nrewrite <- add_le_mono_l.\nnow destruct (mod_always_pos a b).\nQed.\n\n(** Giving a reversed bound is slightly more complex *)\n\nLemma mul_succ_div_gt: forall a b, 0<b -> a < b*(S (a/b)).\nProof.\nintros.\nnzsimpl.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_always_pos a b). order.\nrewrite abs_eq in *; order.\nQed.\n\nLemma mul_pred_div_gt: forall a b, b<0 -> a < b*(P (a/b)).\nProof.\nintros a b Hb.\nrewrite mul_pred_r, <- add_opp_r.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_always_pos a b). order.\nrewrite <- opp_pos_neg in Hb. rewrite abs_neq' in *; order.\nQed.\n\n(** NB: The three previous properties could be used as\n    specifications for [div]. *)\n\n(** Inequality [mul_div_le] is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, b~=0 -> (a == b*(a/b) <-> a mod b == 0).\nProof.\nintros.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- (add_0_r (b*(a/b))) at 2.\napply add_cancel_l.\nQed.\n\n(** Some additionnal inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, 0<b -> a < b*q -> a/b < q.\nProof.\nintros.\nrewrite (mul_lt_mono_pos_l b) by trivial.\napply le_lt_trans with a; trivial.\napply mul_div_le; order.\nQed.\n\nTheorem div_le_upper_bound:\n  forall a b q, 0<b -> a <= b*q -> a/b <= q.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\nTheorem div_le_lower_bound:\n  forall a b q, 0<b -> b*q <= a -> q <= a/b.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<=p -> 0<q<=r -> p/r <= p/q.\nProof. exact div_le_compat_l. Qed.\n\n(** * Relations between usual operations and mod and div *)\n\nLemma mod_add : forall a b c, c~=0 ->\n (a + b * c) mod c == a mod c.\nProof.\nintros.\nsymmetry.\napply mod_unique with (a/c+b); trivial.\nnow apply mod_always_pos.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add : forall a b c, c~=0 ->\n (a + b * c) / c == a / c + b.\nProof.\nintros.\napply (mul_cancel_l _ _ c); try order.\napply (add_cancel_r _ _ ((a+b*c) mod c)).\nrewrite <- div_mod, mod_add by order.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add_l: forall a b c, b~=0 ->\n (a * b + c) / b == a + c / b.\nProof.\n intros a b c. rewrite (add_comm _ c), (add_comm a).\n now apply div_add.\nQed.\n\n(** Cancellations. *)\n\n(** With the current convention, the following isn't always true\n    when [c<0]: [-3*-1 / -2*-1 = 3/2 = 1] while [-3/-2 = 2] *)\n\nLemma div_mul_cancel_r : forall a b c, b~=0 -> 0<c ->\n (a*c)/(b*c) == a/b.\nProof.\nintros.\nsymmetry.\napply div_unique with ((a mod b)*c).\n(* ineqs *)\nrewrite abs_mul, (abs_eq c) by order.\nrewrite <-(mul_0_l c), <-mul_lt_mono_pos_r, <-mul_le_mono_pos_r by trivial.\nnow apply mod_always_pos.\n(* equation *)\nrewrite (div_mod a b) at 1 by order.\nrewrite mul_add_distr_r.\nrewrite add_cancel_r.\nrewrite <- 2 mul_assoc. now rewrite (mul_comm c).\nQed.\n\nLemma div_mul_cancel_l : forall a b c, b~=0 -> 0<c ->\n (c*a)/(c*b) == a/b.\nProof.\nintros. rewrite !(mul_comm c); now apply div_mul_cancel_r.\nQed.\n\nLemma mul_mod_distr_l: forall a b c, b~=0 -> 0<c ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof.\nintros.\nrewrite <- (add_cancel_l _ _ ((c*b)* ((c*a)/(c*b)))).\nrewrite <- div_mod.\nrewrite div_mul_cancel_l by trivial.\nrewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\napply div_mod; order.\nrewrite <- neq_mul_0; intuition; order.\nQed.\n\nLemma mul_mod_distr_r: forall a b c, b~=0 -> 0<c ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof.\n intros. rewrite !(mul_comm _ c); now rewrite mul_mod_distr_l.\nQed.\n\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, n~=0 ->\n (a mod n) mod n == a mod n.\nProof.\nintros. rewrite mod_small_iff by trivial.\nnow apply mod_always_pos.\nQed.\n\nLemma mul_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite add_comm, (mul_comm n), (mul_comm _ b).\n rewrite mul_add_distr_l, mul_assoc.\n rewrite mod_add by trivial.\n now rewrite mul_comm.\nQed.\n\nLemma mul_mod_idemp_r : forall a b n, n~=0 ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof.\n intros. rewrite !(mul_comm a). now apply mul_mod_idemp_l.\nQed.\n\nTheorem mul_mod: forall a b n, n~=0 ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof.\n intros. now rewrite mul_mod_idemp_l, mul_mod_idemp_r.\nQed.\n\nLemma add_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite <- add_assoc, add_comm, mul_comm.\n now rewrite mod_add.\nQed.\n\nLemma add_mod_idemp_r : forall a b n, n~=0 ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof.\n intros. rewrite !(add_comm a). now apply add_mod_idemp_l.\nQed.\n\nTheorem add_mod: forall a b n, n~=0 ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof.\n intros. now rewrite add_mod_idemp_l, add_mod_idemp_r.\nQed.\n\n(** With the current convention, the following result isn't always\n    true with a negative intermediate divisor. For instance\n    [ 3/(-2)/(-2) = 1 <> 0 = 3 / (-2*-2) ] and\n    [ 3/(-2)/2 = -1 <> 0 = 3 / (-2*2) ]. *)\n\nLemma div_div : forall a b c, 0<b -> c~=0 ->\n (a/b)/c == a/(b*c).\nProof.\n intros a b c Hb Hc.\n apply div_unique with (b*((a/b) mod c) + a mod b).\n (* begin 0<= ... <abs(b*c) *)\n rewrite abs_mul.\n destruct (mod_always_pos (a/b) c), (mod_always_pos a b); try order.\n split.\n apply add_nonneg_nonneg; trivial.\n apply mul_nonneg_nonneg; order.\n apply lt_le_trans with (b*((a/b) mod c) + abs b).\n now rewrite <- add_lt_mono_l.\n rewrite (abs_eq b) by order.\n now rewrite <- mul_succ_r, <- mul_le_mono_pos_l, le_succ_l.\n (* end 0<= ... < abs(b*c) *)\n rewrite (div_mod a b) at 1 by order.\n rewrite add_assoc, add_cancel_r.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\nQed.\n\n(** Similarly, the following result doesn't always hold when [b<0].\n    For instance [3 mod (-2*-2)) = 3] while\n    [3 mod (-2) + (-2)*((3/-2) mod -2) = -1]. *)\n\nLemma mod_mul_r : forall a b c, 0<b -> c~=0 ->\n a mod (b*c) == a mod b + b*((a/b) mod c).\nProof.\n intros a b c Hb Hc.\n apply add_cancel_l with (b*c*(a/(b*c))).\n rewrite <- div_mod by (apply neq_mul_0; split; order).\n rewrite <- div_div by trivial.\n rewrite add_assoc, add_shuffle0, <- mul_assoc, <- mul_add_distr_l.\n rewrite <- div_mod by order.\n apply div_mod; order.\nQed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a/b) <= (c*a)/b.\nProof. exact div_mul_le. Qed.\n\n(** mod is related to divisibility *)\n\nLemma mod_divides : forall a b, b~=0 ->\n (a mod b == 0 <-> (b|a)).\nProof.\nintros a b Hb. split.\nintros Hab. exists (a/b). rewrite (div_mod a b Hb) at 2.\n rewrite Hab; now nzsimpl.\nintros (c,Hc).\nrewrite <- Hc, mul_comm.\nnow apply mod_mul.\nQed.\n\nEnd ZEuclidProp.\n\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/Integer/Abstract/ZDivEucl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7382494032757658}}
{"text": "Require Import Arith.\nImport Nat.\n\nFixpoint evenb (n: nat): bool :=\n  match n with\n    | O => true\n    | S p => negb (evenb p)\n  end.\n\n(* Some useful lemmas from the standard library. *)\nCheck even_succ: forall n, even (S n) = odd n.\nCheck negb_even: forall n, negb (even n) = odd n.\n\nLemma evenb_even:\n  forall n, evenb n = even n.\nProof.\n\nQed.\n", "meta": {"author": "mbrcknl", "repo": "coq-fight-2017", "sha": "7f5ec82d47b79769d3b92ae7f0d8cb8e45891aba", "save_path": "github-repos/coq/mbrcknl-coq-fight-2017", "path": "github-repos/coq/mbrcknl-coq-fight-2017/coq-fight-2017-7f5ec82d47b79769d3b92ae7f0d8cb8e45891aba/evenb-even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259923, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7381220189093088}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (lf1 : natural) (y : natural) : natural :=\n  plus Zero (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj308_coqofml_aWT2ME.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109622750986, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.73804740286128}}
{"text": "\n\n(** Anthony Bordg, February 2017 ************************************************\n\nContents:\n\n- The ring of endomorphisms of an abelian group ([rngofendabgr])\n- (left) modules over a ring ([module]) and module homomorphisms ([modulefun])\n- Submodules of a module ([submodule])\n- Univalence for modules over a ring ([modules_univalence])\n- Precategory of modules over a ring ([Mod])\n- Category of modules over a ring ([category_Mod])\n- Mod is a univalent category ([Mod_is_univalent])\n\n***************************************************)\n\nRequire Import UniMath.Algebra.Rigs_and_Rings.\nRequire Import UniMath.Algebra.Monoids_and_Groups.\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.Foundations.PartA.\nRequire Import UniMath.Foundations.Preamble.\nRequire Import UniMath.Algebra.Domains_and_Fields.\nRequire Import UniMath.Foundations.PartD.\nRequire Import Types_and_groups_with_operators.v\nRequire Import UniMath.CategoryTheory.Categories.\n\n\nLocal Open Scope addmonoid_scope.\n\n(** * The ring of endomorphisms of an abelian group *)\n\n(** Two binary operations on the set of endomorphisms of an abelian group *)\n\nDefinition monoidfun_to_isbinopfun {G : abgr} (f : monoidfun G G) : isbinopfun f := pr1 (pr2 f).\n\nDefinition rngofendabgr_op1 {G: abgr} : binop (monoidfun G G).\nProof.\n  intros f g.\n  apply (@monoidfunconstr _ _ (λ x : G, f x + g x)).\n  apply tpair.\n  - intros x x'.\n    rewrite (monoidfun_to_isbinopfun f).\n    rewrite (monoidfun_to_isbinopfun g).\n    apply (abmonoidrer G).\n  - rewrite (monoidfununel f).\n    rewrite (monoidfununel g).\n    rewrite (lunax G).\n    reflexivity.\nDefined.\n\nDefinition rngofendabgr_op2 {G : abgr} : binop (monoidfun G G).\nProof.\n  intros f g.\n  apply (monoidfuncomp f g).\nDefined.\n\nNotation \"f + g\" := (rngofendabgr_op1 f g) : abgr_scope.\n\n(** the composition below uses the diagrammatic order following the general convention used in UniMath *)\n\nNotation \"f ∘ g\" := (rngofendabgr_op2 f g) : abgr_scope.\n\n(** The underlying set of the ring of endomorphisms of an abelian group *)\n\nDefinition setofendabgr (G : abgr) : hSet :=\n   hSetpair (monoidfun G G) (isasetmonoidfun G G).\n\n(** A few access functions *)\n\nDefinition pr1setofendabgr {G : abgr} (f : setofendabgr G) : G -> G := pr1 f.\n\nDefinition pr2setofendabgr {G : abgr} (f : setofendabgr G) : ismonoidfun (pr1 f) := pr2 f.\n\nDefinition setofendabgr_to_isbinopfun {G : abgr} (f : setofendabgr G) : isbinopfun (pr1setofendabgr f) := pr1 (pr2 f).\n\nDefinition setofendabgr_to_unel {G : abgr} (f : setofendabgr G) : pr1setofendabgr f 0 = 0 := pr2 (pr2setofendabgr f).\n\n(** We endow setofendabgr with the two binary operations defined above *)\n\nDefinition setwith2binopofendabgr (G : abgr) : setwith2binop :=\n   setwith2binoppair (setofendabgr G) (dirprodpair (rngofendabgr_op1) (rngofendabgr_op2)).\n\n(** rngofendabgr_op1 G and rngofendabgr_op2 G are ring operations *)\n\n(** rngofendabgr_op1 is a monoid operation *)\n\nLocal Open Scope abgr_scope.\n\nDefinition isassoc_rngofendabgr_op1 {G : abgr} : isassoc (@rngofendabgr_op1 G).\nProof.\n   intros f g h.\n   use total2_paths_f.\n   - apply funextfun.\n     intro.\n     apply (pr2 G).\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition setofendabgr_un0 {G: abgr} : monoidfun G G.\nProof.\n   apply (@monoidfunconstr _ _ (λ x : G, 0)).\n   apply dirprodpair.\n     - intros x x'.\n       rewrite (lunax G).\n       reflexivity.\n     - reflexivity.\nDefined.\n\nDefinition islunit_setofendabgr_un0 {G : abgr} : islunit (@rngofendabgr_op1 G) setofendabgr_un0.\nProof.\n   intro f.\n   use total2_paths_f.\n   - apply funextfun. intro x.\n     apply (lunax G (pr1setofendabgr f x)).\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition isrunit_setofendabgr_un0 {G : abgr} : isrunit (@rngofendabgr_op1 G) setofendabgr_un0.\nProof.\n   intros f.\n   use total2_paths_f.\n   - apply funextfun. intro x.\n     apply (runax G (pr1setofendabgr f x)).\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition isunit_setofendabgr_un0 {G : abgr} : isunit (@rngofendabgr_op1 G) setofendabgr_un0 :=\n  isunitpair islunit_setofendabgr_un0 isrunit_setofendabgr_un0.\n\nDefinition isunital_rngofendabgr_op1 {G : abgr} : isunital (@rngofendabgr_op1 G) :=\n  isunitalpair setofendabgr_un0 isunit_setofendabgr_un0.\n\nDefinition ismonoidop_rngofendabgr_op1 {G : abgr} : ismonoidop (@rngofendabgr_op1 G) :=\n   mk_ismonoidop isassoc_rngofendabgr_op1 isunital_rngofendabgr_op1.\n\nLocal Close Scope abgr_scope.\n\n(** rngofendabgr_op1 is a group operation *)\n\nDefinition setofendabgr_inv {G : abgr} : monoidfun G G -> monoidfun G G.\nProof.\n   intro f.\n   apply (@monoidfunconstr G G (λ x : G, grinv G (pr1setofendabgr f x))).\n   apply dirprodpair.\n   - intros x x'.\n     rewrite (setofendabgr_to_isbinopfun f).\n     rewrite (grinvop G).\n     apply (commax G).\n   - rewrite (setofendabgr_to_unel f).\n     apply (grinvunel G).\nDefined.\n\nLocal Open Scope abgr_scope.\n\nDefinition islinv_setofendabgr_inv {G : abgr} : islinv (@rngofendabgr_op1 G) setofendabgr_un0 setofendabgr_inv.\nProof.\n   intro f.\n   use total2_paths_f.\n   - apply funextfun. intro x.\n     apply (grlinvax G).\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition isrinv_setofendabgr_inv {G : abgr} : isrinv (@rngofendabgr_op1 G) setofendabgr_un0 setofendabgr_inv.\nProof.\n   intro f.\n   use total2_paths_f.\n   - apply funextfun. intro x.\n     apply (grrinvax G).\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition isinv_setofendabgr_inv {G : abgr} : isinv (@rngofendabgr_op1 G) (unel_is (@ismonoidop_rngofendabgr_op1 G)) setofendabgr_inv :=\n  mk_isinv islinv_setofendabgr_inv isrinv_setofendabgr_inv.\n\nDefinition invstruct_setofendabgr_inv {G : abgr} : invstruct (@rngofendabgr_op1 G) ismonoidop_rngofendabgr_op1 :=\n   mk_invstruct (@setofendabgr_inv G) (@isinv_setofendabgr_inv G).\n\nDefinition isgrop_rngofendabgr_op1 {G : abgr} : isgrop (@rngofendabgr_op1 G) :=\n   isgroppair ismonoidop_rngofendabgr_op1 invstruct_setofendabgr_inv.\n\nDefinition iscomm_rngofendabgr_op1 {G : abgr} : iscomm (@rngofendabgr_op1 G).\nProof.\n   intros f g.\n   use total2_paths_f.\n   - apply funextfun. intro x.\n     apply (commax G).\n   - apply (isapropismonoidfun).\nDefined.\n\nDefinition isabgrop_rngofendabgr_op1 {G : abgr} : isabgrop (@rngofendabgr_op1 G) :=\n  mk_isabgrop isgrop_rngofendabgr_op1 iscomm_rngofendabgr_op1.\n\n(** rngofendabgr_op2 is a monoid operation *)\n\nDefinition isassoc_rngofendabgr_op2 {G : abgr} : isassoc (@rngofendabgr_op2 G).\nProof.\n  intros f g h.\n  use total2_paths_f.\n  - apply funcomp_assoc.\n  - apply isapropismonoidfun.\nDefined.\n\nDefinition setofendabgr_un1 {G: abgr} : monoidfun G G.\nProof.\n   apply (@monoidfunconstr _ _ (idfun G)).\n   apply dirprodpair.\n   - intros x x'. reflexivity.\n   - reflexivity.\nDefined.\n\nDefinition islunit_setofendabgr_un1 {G : abgr} : islunit (@rngofendabgr_op2 G) setofendabgr_un1.\nProof.\n   intro f.\n   use total2_paths_f.\n   - apply funextfun. intro x. reflexivity.\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition isrunit_setofendabgr_un1 {G : abgr} : isrunit (@rngofendabgr_op2 G) setofendabgr_un1.\nProof.\n   intros f.\n   use total2_paths_f.\n   - apply funextfun. intro x. reflexivity.\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition isunit_setofendabgr_un1 {G : abgr} : isunit (@rngofendabgr_op2 G) setofendabgr_un1 :=\n  isunitpair islunit_setofendabgr_un1 isrunit_setofendabgr_un1.\n\nDefinition isunital_rngofendabgr_op2 {G : abgr} : isunital (@rngofendabgr_op2 G) :=\n  isunitalpair setofendabgr_un1 isunit_setofendabgr_un1.\n\nDefinition ismonoidop_rngofendabgr_op2 {G : abgr} : ismonoidop (@rngofendabgr_op2 G) :=\n   mk_ismonoidop isassoc_rngofendabgr_op2 isunital_rngofendabgr_op2.\n\n(** rngofendabgr_op2 is distributive over rngofendabgr_op1 *)\n\nDefinition isldistr_setofendabgr_op {G : abgr} : isldistr (@rngofendabgr_op1 G) (@rngofendabgr_op2 G).\nProof.\n   intros f g h.\n   use total2_paths_f.\n   - apply funextfun. intro x. reflexivity.\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition isrdistr_setofendabgr_op {G : abgr} : isrdistr (@rngofendabgr_op1 G) (@rngofendabgr_op2 G).\nProof.\n   intros f g h.\n   use total2_paths_f.\n   - apply funextfun. intro x.\n     apply (setofendabgr_to_isbinopfun h).\n   - apply isapropismonoidfun.\nDefined.\n\nDefinition isdistr_setofendabgr_op {G : abgr} : isdistr (@rngofendabgr_op1 G) (@rngofendabgr_op2 G) :=\n   dirprodpair isldistr_setofendabgr_op isrdistr_setofendabgr_op.\n\nDefinition isrngops_setofendabgr_op {G : abgr} : isrngops (@rngofendabgr_op1 G) (@rngofendabgr_op2 G) :=\n   mk_isrngops isabgrop_rngofendabgr_op1 ismonoidop_rngofendabgr_op2 isdistr_setofendabgr_op.\n\n(** The set of endomorphisms of an abelian group is a ring *)\n\nDefinition rngofendabgr (G : abgr) : rng :=\n   @rngpair (setwith2binopofendabgr G) (@isrngops_setofendabgr_op G).\n\n\n(** * The definition of the small type of (left) R-modules over a ring R *)\n\nDefinition module_struct (R : rng) (G : abgr) : UU := rngfun R (rngofendabgr G).\n\nDefinition module (R : rng) : UU := ∑ G, module_struct R G.\n\nDefinition pr1module {R : rng} (M : module R) : abgr := pr1 M.\n\nCoercion pr1module : module >-> abgr.\n\nDefinition pr2module {R : rng} (M : module R) : module_struct R (pr1module M) := pr2 M.\n\nIdentity Coercion id_module_struct : module_struct >-> rngfun.\n\nDefinition modulepair {R : rng} (G : abgr) (f : module_struct R G) : module R := tpair _ G f.\n\n(** The multiplication defined from a module *)\n\nDefinition module_mult {R : rng} (M : module R) : R -> M -> M := λ r : R, λ x : M, (pr1setofendabgr (pr2module M r) x).\n\nNotation \"r * x\" := (module_mult _ r x) : module_scope.\n\nDelimit Scope module_scope with module.\n\nLocal Open Scope rig_scope.\n\nDefinition rigfun_to_unel_rigaddmonoid {X Y : rig} (f : rigfun X Y) : f 0 = 0 := pr2 (pr1 (pr2 f)).\n\nLocal Close Scope rig_scope.\n\nLocal Open Scope module.\n\nDefinition module_mult_0_to_0 {R : rng} {M : module R} (x : M) : rngunel1 * x = @unel M.\nProof.\n   unfold module_mult. cbn.\n   assert (pr2module M rngunel1 = @rngunel1 (rngofendabgr M)).\n   - exact (rigfun_to_unel_rigaddmonoid (pr2module M)).\n   - rewrite X.\n     reflexivity.\nDefined.\n\n(** To construct a module from a left action satisfying four axioms *)\n\nLocal Open Scope addmonoid.\n\nDefinition mult_isldistr_wrt_grop {R : rng} {G : abgr} (m : R -> G -> G) : UU := ∏ r : R, ∏ x y : G, m r (x + y) = (m r x) + (m r y).\n\nDefinition mult_isrdistr_wrt_rngop1 {R : rng} {G : abgr} (m : R -> G -> G) : UU := ∏ r s : R, ∏ x : G, m (op1 r s) x = (m r x) + (m s x).\n\nDefinition mult_isrdistr_wrt_rngop2 {R : rng} {G : abgr} (m : R -> G -> G) : UU := ∏ r s : R, ∏ x : G, m (op2 r s) x = m s (m r x).\n\nDefinition mult_unel {R : rng} {G : abgr} (m : R -> G -> G) : UU := ∏ x : G, m rngunel2 x = x.\n\nLocal Close Scope addmonoid.\n\nDefinition mult_to_rngofendabgr {R : rng} {G : abgr} {m : R -> G -> G} (ax1 : mult_isldistr_wrt_grop m) (r : R) : rngofendabgr G.\nProof.\n    use monoidfunconstr.\n    intro x. exact (m r x).\n    apply dirprodpair.\n    + intros x y. apply ax1.\n    + apply (grlcan G (m r (unel G))).\n      rewrite runax.\n      rewrite <- (ax1 r (unel G) (unel G)).\n      rewrite runax.\n      apply idpath.\nDefined.\n\nDefinition mult_to_module_struct {R : rng} {G : abgr} {m : R -> G -> G} (ax1 : mult_isldistr_wrt_grop m) (ax2 : mult_isrdistr_wrt_rngop1 m)\n  (ax3 : mult_isrdistr_wrt_rngop2 m) (ax4 : mult_unel m) : module_struct R G.\nProof.\n  split with (λ r : R, mult_to_rngofendabgr ax1 r).\n  apply dirprodpair.\n  - apply dirprodpair.\n    + intros r s.\n      use total2_paths2_f.\n      * apply funextfun. intro x. apply ax2.\n      * apply isapropismonoidfun.\n    + use total2_paths2_f.\n      * apply funextfun. intro x. change (m rngunel1 x = unel G). apply (grlcan G (m (rngunel1) x)). rewrite runax.\n        rewrite <- (ax2 rngunel1 rngunel1 x). rewrite rngrunax1. apply idpath.\n      * apply isapropismonoidfun.\n  -  apply dirprodpair.\n     + intros r s.\n       use total2_paths2_f.\n       * apply funextfun. intro x. apply ax3.\n       * apply isapropismonoidfun.\n     + use total2_paths2_f.\n       * apply funextfun. intro x. apply ax4.\n       * apply isapropismonoidfun.\nDefined.\n\nDefinition mult_to_module {R : rng} {G : abgr} {m : R -> G -> G} (ax1 : mult_isldistr_wrt_grop m) (ax2 : mult_isrdistr_wrt_rngop1 m)\n  (ax3 : mult_isrdistr_wrt_rngop2 m) (ax4 : mult_unel m) : module R := modulepair G (mult_to_module_struct ax1 ax2 ax3 ax4).\n\n(** (left) R-module homomorphism *)\n\nDefinition islinear {R : rng} {M N : module R} (f : M -> N) :=\n  ∏ r : R, ∏ x : M, f (r * x) = r * (f x).\n\nDefinition isaprop_islinear {R : rng} {M N : module R} (f : M -> N) : isaprop (islinear f).\nProof.\n   use impred. intro r.\n   use impred. intro x.\n   apply setproperty.\nDefined.\n\nDefinition islinear_id {R : rng} (M : module R) : islinear (idfun M).\nProof.\n  intros r x.\n  unfold idfun. apply idpath.\nDefined.\n\nDefinition linearfun {R : rng} (M N : module R) : UU := ∑ f : M -> N, islinear f.\n\nDefinition linearfunpair {R : rng} {M N : module R} (f : M -> N) (is : islinear f) : linearfun M N := tpair _ f is.\n\nDefinition pr1linearfun {R : rng} {M N : module R} (f : linearfun M N) : M -> N := pr1 f.\n\nCoercion pr1linearfun : linearfun >-> Funclass.\n\nDefinition islinearfuncomp {R : rng} {M N P : module R} (f : linearfun M N) (g : linearfun N P) : islinear (funcomp (pr1 f) (pr1 g)).\nProof.\n  intros r x.\n  unfold funcomp.\n  rewrite (pr2 f).\n  rewrite (pr2 g).\n  apply idpath.\nDefined.\n\nDefinition linearfuncomp {R : rng} {M N P : module R} (f : linearfun M N) (g : linearfun N P) : linearfun M P :=\n  tpair _ (funcomp f g) (islinearfuncomp f g).\n\nDefinition ismodulefun {R : rng} {M N : module R} (f : M -> N) : UU :=\n   (isbinopfun f) × (islinear f).\n\nLemma isapropismodulefun {R : rng} {M N : module R} (f : M -> N) : isaprop (ismodulefun f).\nProof.\n   refine (@isofhleveldirprod 1 (isbinopfun f) (islinear f) _ _).\n   exact (isapropisbinopfun f).\n   exact (isaprop_islinear f).\nDefined.\n\nDefinition ismodulefun_id {R : rng} (M : module R) : ismodulefun (idfun M).\nProof.\n  apply dirprodpair.\n  - intros x y. apply idpath.\n  - intros. apply  islinear_id.\nDefined.\n\nDefinition modulefun {R : rng} (M N : module R) : UU := ∑ f : M -> N, ismodulefun f.\n\nDefinition modulefunpair {R : rng} {M N : module R} (f : M -> N) (is : ismodulefun f) : modulefun M N :=\n   tpair _ f is.\n\nDefinition pr1modulefun {R : rng} {M N : module R} (f : modulefun M N) : M -> N := pr1 f.\n\nCoercion pr1modulefun : modulefun >-> Funclass.\n\nDefinition modulefun_to_isbinopfun {R : rng} {M N : module R} (f : modulefun M N) : isbinopfun (pr1modulefun f) := pr1 (pr2 f).\n\nDefinition modulefun_to_binopfun {R : rng} {M N : module R} (f : modulefun M N) : binopfun M N :=\n  binopfunpair (pr1modulefun f) (modulefun_to_isbinopfun f).\n\nDefinition modulefun_to_islinear {R : rng} {M N : module R} (f : modulefun M N): islinear (pr1modulefun f) := pr2 (pr2 f).\n\nDefinition modulefun_to_linearfun {R : rng} {M N : module R} (f : modulefun M N) : linearfun M N :=\n  linearfunpair f (modulefun_to_islinear f).\n\nDefinition modulefun_unel {R : rng} {M N : module R} (f : modulefun M N) : f (unel M) = unel N.\nProof.\n   rewrite <- (module_mult_0_to_0 (unel M)).\n   rewrite ((modulefun_to_islinear f) rngunel1 (unel M)).\n   rewrite (module_mult_0_to_0 _).\n   reflexivity.\nDefined.\n\n(** From modules to abelian groups with operators *)\n\nDefinition module_to_grwithaction {R : rng} (M : module R) : grwithaction R := tpair (λ G : gr, action R G) (pr1module M) (module_mult M).\n\nDefinition module_to_ishdistr_action {R : rng} (M : module R) :\n  ishdistr_action (@op (gr_to_typewithbinop M)) (module_mult M).\nProof.\n  intros r x y.\n  apply (pr1 (pr2 (pr2 M r))).\nDefined.\n\nDefinition module_to_grwithoperators {R : rng} (M : module R) : grwithoperators R :=\n  tpair _ (module_to_grwithaction M) (module_to_ishdistr_action M).\n\nCoercion module_to_grwithoperators : module >-> grwithoperators .\n\n\n(** Submodules of a module *)\n\nDefinition submodule {R : rng} (M : module R) : UU := stable_subgr M.\n\nDefinition submodule_to_gr {R : rng} {M : module R} (N : submodule M) : gr := stable_subgr_to_gr N.\n\nDefinition submodule_to_abgr {R : rng} {M : module R} (N : submodule M) : abgr.\nProof.\n  use abgrpair.\n  - exact (pr1 (submodule_to_gr N)).\n  - apply dirprodpair.\n    + exact (pr2 (submodule_to_gr N)).\n    + intros x y. use total2_paths_f.\n      * apply (dirprod_pr2 (pr2 (pr1module M))).\n      * apply propproperty.\nDefined.\n\nDefinition submodule_to_module_struct {R : rng} {M : module R} (N : submodule M) : module_struct R (submodule_to_abgr N).\nProof.\n  use rngfunconstr.\n  - intro r.\n    use monoidfunconstr.\n    + intro x.\n      split with (module_mult M r (pr1 x)).\n      apply (pr2 (pr2 N) r (pr1 x)).\n      apply (pr2 x).\n    + apply dirprodpair.\n      * intros x y.\n        use total2_paths2_f.\n        apply (pr1 (pr2 (pr2 M r))).\n        apply propproperty.\n      * use total2_paths2_f.\n        apply (pr2 (pr2 (pr2 M r))).\n        apply propproperty.\n  - apply dirprodpair.\n    + apply dirprodpair.\n      * intros r s.\n        use total2_paths2_f.\n        apply funextfun. intro x.\n        use total2_paths2_f.\n        assert (p : pr1 (pr1 (pr2 M) (@op1 R r s)) ~ pr1 (@op1 (rngofendabgr (pr1 M)) (pr1 (pr2 M) r) (pr1 (pr2 M) s))).\n        use eqtohomot. apply (base_paths _ _ (dirprod_pr1 (dirprod_pr1 (pr2 (pr2 M))) r s)).\n        apply (p (pr1 x)).\n        apply propproperty.\n        apply isapropismonoidfun.\n      * use total2_paths2_f.\n        apply funextfun. intro x.\n        use total2_paths2_f.\n        assert (p : pr1 (pr1 (pr2 M) (@rngunel1 R)) ~ pr1 (@rngunel1 (rngofendabgr (pr1 M)))).\n        use eqtohomot. apply (base_paths _ _ (dirprod_pr2 (dirprod_pr1 (pr2 (pr2 M))))).\n        apply (p (pr1 x)).\n        apply propproperty.\n        apply isapropismonoidfun.\n    + apply dirprodpair.\n      * intros r s.\n        use total2_paths2_f.\n        apply funextfun. intro x.\n        use total2_paths2_f.\n        assert (p : pr1 (pr1 (pr2 M) (@op2 R r s)) ~ pr1 (@op2 (rngofendabgr (pr1 M)) (pr1 (pr2 M) r) (pr1 (pr2 M) s))).\n        use eqtohomot. apply (base_paths _ _ (dirprod_pr1 (dirprod_pr2 (pr2 (pr2 M))) r s)).\n        apply (p (pr1 x)).\n        apply propproperty.\n        apply isapropismonoidfun.\n      * use total2_paths2_f.\n        apply funextfun. intro x.\n        use total2_paths2_f.\n        assert (p : pr1 (pr1 (pr2 M) (@rngunel2 R)) ~ pr1 (@rngunel2 (rngofendabgr (pr1 M)))).\n        use eqtohomot. apply (base_paths _ _ (dirprod_pr2 (dirprod_pr2 (pr2 (pr2 M))))).\n        apply (p (pr1 x)).\n        apply propproperty.\n        apply isapropismonoidfun.\nDefined.\n\nDefinition submodule_to_module {R : rng} {M : module R} (N : submodule M) : module R :=\n  modulepair (submodule_to_abgr N) (submodule_to_module_struct N).\n\n(** * Univalence for R-modules *)\n\nDefinition moduleiso {R : rng} (M N : module R) : UU := ∑ w : M ≃ N, ismodulefun w.\n\nDefinition moduleiso_to_modulefun {R : rng} (M N : module R) : moduleiso M N -> modulefun M N.\nProof.\n   intro f.\n   exact (tpair _ (pr1weq (pr1 f)) (pr2 f)).\nDefined.\n\nCoercion moduleiso_to_modulefun : moduleiso >-> modulefun.\n\nDefinition pr1moduleiso {R : rng} {M N : module R} (f : moduleiso M N) : M ≃ N := pr1 f.\n\nCoercion pr1moduleiso : moduleiso >-> weq.\n\nDefinition moduleisopair {R : rng} {M N : module R} (f : M ≃ N) (is : ismodulefun f) : moduleiso M N :=\n   tpair _ f is.\n\nDefinition idmoduleiso {R : rng} (M : module R) : moduleiso M M.\nProof.\n   use moduleisopair.\n   - exact (idweq (pr1module M)).\n   - apply dirprodpair.\n     + intros x y. apply idpath.\n     + intros r x. apply idpath.\nDefined.\n\nDefinition isbinopfuninvmap {R : rng} {M N : module R} (f : moduleiso M N) : isbinopfun (invmap f).\nProof.\n   intros x y.\n   apply (invmaponpathsweq f).\n   rewrite (homotweqinvweq f (op x y)).\n   symmetry.\n   transitivity (op ((pr1moduleiso f) (invmap f x)) ((pr1moduleiso f) (invmap f y))).\n   apply (modulefun_to_isbinopfun f (invmap f x) (invmap f y)).\n   rewrite 2 (homotweqinvweq f).\n   apply idpath.\nDefined.\n\nDefinition islinearinvmap {R : rng} {M N : module R} (f : moduleiso M N) : islinear (invmap f).\nProof.\n   intros r x.\n   apply (invmaponpathsweq f).\n   transitivity (module_mult N r x).\n   exact (homotweqinvweq f (module_mult N r x)).\n   transitivity (module_mult N r (pr1 f (invmap (pr1 f) x))).\n   rewrite (homotweqinvweq (pr1 f) x).\n   apply idpath.\n   symmetry.\n   apply (pr2 (pr2 f) r (invmap f x)).\nDefined.\n\nDefinition invmoduleiso {R : rng} {M N : module R} (f : moduleiso M N) : moduleiso N M.\nProof.\n   use moduleisopair.\n   - exact (invweq f).\n   - apply dirprodpair.\n     + exact (isbinopfuninvmap f).\n     + exact (islinearinvmap f).\nDefined.\n\nDefinition moduleiso' {R : rng} (M N : module R) : UU := ∑ w : monoidiso (pr1module M) (pr1module N), islinear w.\n\nDefinition moduleiso_to_moduleiso' {R : rng} (M N : module R) : moduleiso M N -> moduleiso' M N.\nProof.\n   intro w.\n   use tpair.\n   - use tpair.\n     + exact w.\n     + use tpair.\n       * exact (modulefun_to_isbinopfun w).\n       * apply (modulefun_unel w).\n   - exact (modulefun_to_islinear w).\nDefined.\n\nDefinition moduleiso'_to_moduleiso {R : rng} (M N : module R) : moduleiso' M N -> moduleiso M N.\nProof.\n   intro w.\n   use tpair.\n   - exact (pr1 w).\n   - apply dirprodpair.\n     + exact (pr1 (pr2 (pr1 w))).\n     + exact (pr2 w).\nDefined.\n\nLemma modulefun_unel_uniqueness {R : rng} {M N : module R} {f : pr1module M -> pr1module N} {is: ismodulefun f}\n       (p : f (@unel (pr1module M)) = @unel (pr1module N)) : modulefun_unel (f,,is) = p.\nProof.\n   apply (setproperty (pr1module N)).\nDefined.\n\nDefinition moduleiso'_to_moduleiso_isweq {R : rng} (M N : module R) : isweq (moduleiso'_to_moduleiso M N).\nProof.\n   use (gradth _ (moduleiso_to_moduleiso' M N)). intro w.\n   unfold moduleiso'_to_moduleiso, moduleiso_to_moduleiso'. cbn.\n   rewrite (modulefun_unel_uniqueness (dirprod_pr2 (pr2 (pr1 w)))).\n   apply idpath.\n   intro w. apply idpath.\nDefined.\n\nDefinition moduleiso'_to_moduleiso_weq {R : rng} (M N : module R) : (moduleiso' M N) ≃ (moduleiso M N) :=\n   weqpair (moduleiso'_to_moduleiso M N) (moduleiso'_to_moduleiso_isweq M N).\n\n(* The next lemma below should be moved to Rigs_and_Rings.v *)\n\nLemma isaset_rngfun (X Y : rng) : isaset (rngfun X Y).\nProof.\n   apply (isofhleveltotal2 2).\n   - use impred_isaset. intro x.\n     apply setproperty.\n   - intro f.\n     apply (isasetaprop (isapropisrigfun f)).\nDefined.\n\nDefinition modules_univalence_weq {R : rng} (M N : module R) : (M ╝ N) ≃ (moduleiso' M N).\nProof.\n   use weqbandf.\n   - apply abgr_univalence.\n   - intro e.\n     use invweq.\n     induction M. induction N. cbn in e. induction e.\n     use weqimplimpl.\n     + intro i.\n       use total2_paths2_f.\n       * use funextfun. intro r.\n         use total2_paths2_f.\n           apply funextfun. intro x. exact (i r x).\n           apply isapropismonoidfun.\n       * apply isapropisrigfun.\n     + intro i. cbn.\n       intros r x.\n       unfold idmonoidiso. cbn in i.\n       induction i.\n       apply idpath.\n     + apply isaprop_islinear.\n     + apply isaset_rngfun.\nDefined.\n\nDefinition modules_univalence_map {R : rng} (M N : module R) : (M = N) -> (moduleiso M N).\nProof.\n   intro p.\n   induction p.\n   exact (idmoduleiso M).\nDefined.\n\nDefinition modules_univalence_map_isweq {R : rng} (M N : module R) : isweq (modules_univalence_map M N).\nProof.\n   use isweqhomot.\n   - exact (weqcomp (weqcomp (total2_paths_equiv _ M N) (modules_univalence_weq M N)) (moduleiso'_to_moduleiso_weq M N)).\n   - intro p.\n     induction p.\n     apply (pathscomp0 weqcomp_to_funcomp_app).\n     apply idpath.\n   - apply weqproperty.\nDefined.\n\nDefinition modules_univalence {R : rng} (M N : module R) : (M = N) ≃ (moduleiso M N).\nProof.\n   use weqpair.\n   - exact (modules_univalence_map M N).\n   - exact (modules_univalence_map_isweq M N).\nDefined.\n\n\nSection univalent_category_modules.\n\n(** * The precategory of (left) R-modules and R-modules homomorphisms *)\n\n\nVariable R : rng.\n\nDefinition precategory_ob_mor_module : precategory_ob_mor :=\n   precategory_ob_mor_pair (module R) (λ M N, modulefun M N).\n\nLocal Open Scope Cat.\n\nDefinition modulefun_id : ∏ M : precategory_ob_mor_module, M --> M.\nProof.\n  intro M.\n  exists (idfun (pr1module M)).\n  exact (ismodulefun_id M).\nDefined.\n\nDefinition ismodulefun_comp {M N P : precategory_ob_mor_module} (f : M --> N) (g : N --> P) :\n  ismodulefun (funcomp (pr1modulefun f) (pr1modulefun g)) :=\n    dirprodpair (isbinopfuncomp (modulefun_to_binopfun f) (modulefun_to_binopfun g))\n                (islinearfuncomp (modulefun_to_linearfun f) (modulefun_to_linearfun g)).\n\nDefinition modulefun_comp : ∏ M N P : precategory_ob_mor_module, M --> N → N --> P → M --> P.\nProof.\n    intros  M N P f g.\n    exists (funcomp (pr1modulefun f) (pr1modulefun g)).\n    exact (ismodulefun_comp f g).\nDefined.\n\nDefinition precategory_id_comp_module : precategory_id_comp (precategory_ob_mor_module) :=\n  dirprodpair (modulefun_id) (modulefun_comp).\n\nDefinition precategory_data_module : precategory_data :=\n   tpair _ (precategory_ob_mor_module) (precategory_id_comp_module).\n\nDefinition is_precategory_precategory_data_module : is_precategory (precategory_data_module).\nProof.\n   apply dirprodpair.\n   - apply dirprodpair.\n     + intros M N f.\n       use total2_paths_f.\n       * apply funextfun. intro x. apply idpath.\n       * apply isapropismodulefun.\n     + intros M N f.\n       use total2_paths_f.\n       * apply funextfun. intro x. apply idpath.\n       * apply isapropismodulefun.\n   - intros M N P Q f g h.\n     use total2_paths_f.\n     + apply funextfun. intro x.\n       unfold compose. cbn.\n       rewrite funcomp_assoc.\n       apply idpath.\n     + apply isapropismodulefun.\nDefined.\n\nDefinition Mod : precategory :=\n   mk_precategory (precategory_data_module) (is_precategory_precategory_data_module).\n\n\n(** * The category of (left) R-modules and R-modules homomorphisms *)\n\n(** The precategory of R-modules has homsets *)\n\nDefinition has_homsets_Mod : has_homsets Mod.\nProof.\n   intros M N. unfold isaset. intros f g. unfold isaprop.\n   apply (isofhlevelweqb 1 (total2_paths_equiv (λ x :  pr1module M ->  pr1module N, ismodulefun x) f g)).\n   refine (isofhleveltotal2 1 _ _ _).\n   - assert (p : isofhlevel 2 (pr1module M ->  pr1module N)).\n     + apply impred. intro.\n       exact (setproperty (pr1module N)).\n     + exact (p (pr1 f) (pr1 g)).\n   - intro p.\n     assert (q : isaset (ismodulefun (pr1 g))).\n     + exact (isasetaprop (isapropismodulefun (pr1 g))).\n     + apply q.\nDefined.\n\nDefinition category_Mod : category := category_pair Mod has_homsets_Mod.\n\n\n(** * The univalent category of (left) R-modules and R-modules homomorphisms *)\n\n(** Equivalence between isomorphisms and moduleiso in Mod R *)\n\nLemma iso_isweq {M N : ob Mod} (f : iso M N) : isweq (pr1 (pr1 f)).\nProof.\n   use (gradth (pr1 (pr1 f))).\n   - exact (pr1 (inv_from_iso f)).\n   - intro x.\n     set (T:= iso_inv_after_iso f).\n     apply subtypeInjectivity in T.\n     + set (T':= toforallpaths _ _ _ T).\n       apply T'.\n     + intro g.\n       apply isapropismodulefun.\n   - intro y.\n     set (T:= iso_after_iso_inv f).\n     apply subtypeInjectivity in T.\n     + set (T':= toforallpaths _ _ _ T).\n       apply T'.\n     + intro g.\n       apply isapropismodulefun.\nDefined.\n\nLemma iso_moduleiso (M N : ob Mod) : iso M N -> moduleiso M N.\nProof.\n   intro f.\n   use moduleisopair.\n   - use weqpair.\n     + exact (pr1 (pr1 f)).\n     + exact (iso_isweq f).\n   - exact (pr2 (pr1 f)).\nDefined.\n\nLemma moduleiso_is_iso {M N : ob Mod} (f : moduleiso M N) : @is_iso Mod M N (modulefunpair f (pr2 f)).\nProof.\n   apply (is_iso_qinv (C:= Mod) _ (modulefunpair (invmoduleiso f) (pr2 (invmoduleiso f)))).\n   split.\n   - use total2_paths_f.\n     + apply funextfun. intro x.\n       unfold funcomp, idfun.\n       apply homotinvweqweq.\n     + apply isapropismodulefun.\n   - use total2_paths_f.\n     + apply funextfun. intro y.\n       apply homotweqinvweq.\n     + apply isapropismodulefun.\nDefined.\n\nLemma moduleiso_iso (M N : ob Mod) : moduleiso M N -> iso M N.\nProof.\n   intro f.\n   use isopair.\n   - use tpair.\n     + exact f.\n     + exact (pr2 f).\n   - exact (moduleiso_is_iso f).\nDefined.\n\nLemma moduleiso_iso_isweq (M N : ob Mod) : isweq (@moduleiso_iso M N).\nProof.\n   apply (gradth _ (iso_moduleiso M N)).\n   - intro f.\n     apply subtypeEquality.\n     + intro w.\n       apply isapropismodulefun.\n     + unfold moduleiso_iso, iso_moduleiso.\n       use total2_paths_f.\n       * apply idpath.\n       * apply isapropisweq.\n   - intro f.\n     unfold iso_moduleiso, moduleiso_iso.\n     use total2_paths_f.\n     + apply idpath.\n     + apply isaprop_is_iso.\nDefined.\n\nDefinition moduleiso_iso_weq (M N : Mod) : (moduleiso M N) ≃ (iso M N) :=\n   weqpair (moduleiso_iso M N) (moduleiso_iso_isweq M N).\n\nDefinition Mod_idtoiso_isweq : ∏ M N : ob Mod, isweq (fun p : M = N => idtoiso p).\nProof.\n   intros M N.\n   use (isweqhomot (weqcomp (modules_univalence M N) (moduleiso_iso_weq M N)) _).\n   - intro p.\n     induction p.\n     use (pathscomp0 weqcomp_to_funcomp_app). cbn.\n     use total2_paths_f.\n     + apply idpath.\n     + apply isaprop_is_iso.\n   - apply weqproperty.\nDefined.\n\nDefinition Mod_is_univalent : is_univalent Mod :=\n  mk_is_univalent Mod_idtoiso_isweq has_homsets_Mod.\n\nDefinition univalent_category_Mod : univalent_category := mk_category Mod Mod_is_univalent.\n\nEnd univalent_category_modules.", "meta": {"author": "AnthonyBordg", "repo": "UniLab", "sha": "0e470d57a045bd93c4fa7dbe40332771f37e0761", "save_path": "github-repos/coq/AnthonyBordg-UniLab", "path": "github-repos/coq/AnthonyBordg-UniLab/UniLab-0e470d57a045bd93c4fa7dbe40332771f37e0761/UniLab/UniMath/Modules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7380473899447877}}
{"text": "(*\n Copyright 2022 ZhengPu Shi\n  This file is part of coq-matrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : auxiliary library for sequence.\n  author    : ZhengPu Shi\n  date      : 2022.06\n*)\n\nRequire Import Nat PeanoNat Lia Bool.\nRequire Import FieldStruct.\n\n\n(* ######################################################################### *)\n(** * Sequence by function, f : nat -> X *)\n\nModule Sequence (F : FieldSig).\n\n  Module Export FieldThyInst := FieldThy F.\n  \n  Open Scope nat.\n  Open Scope X_scope.\n  \n  (* ======================================================================= *)\n  (** ** Equality of sequence *)\n  Section Equality.\n  \n    (** Equality of two sequence *)\n    Definition seqeq n (f g : nat -> X) := forall i, i < n -> f i = g i.\n    \n    (** seqeq of Sn has a equivalent form. *)\n    Lemma seqeq_Sn : forall n (f g : nat -> X), \n      seqeq (S n) f g <->\n      (seqeq n f g) /\\ (f n = g n).\n    Proof.\n      split.\n      - intros. split; auto. unfold seqeq. auto.\n      - unfold seqeq. intros. destruct H. destruct (i =? n)%nat eqn : E1.\n        + apply Nat.eqb_eq in E1. subst; auto.\n        + apply Nat.eqb_neq in E1. apply H. lia.\n    Qed.\n    \n    (** Boolean equality of two sequence *)\n    Fixpoint seqeqb n (f g : nat -> X) : bool :=\n      match n with\n      | O => true\n      | 1 => Xeqb (f 0)%nat (g 0)%nat\n      | S n' => (seqeqb n' f g) && Xeqb (f n') (g n')\n      end.\n    \n    (** seqeqb of Sn has a equivalent form. *)\n    Lemma seqeqb_Sn : forall {n} (f g : nat -> X), \n      seqeqb (S n) f g = (seqeqb n f g) && (Xeqb (f n) (g n)).\n    Proof. intros. destruct n; auto. Qed.\n    \n    (** seqeqb = true <-> seqeq *)\n    Lemma seqeqb_true_iff : forall n f g, seqeqb n f g = true <-> seqeq n f g.\n    Proof.\n      induction n; intros.\n      - unfold seqeqb, seqeq. split; intros; auto. lia.\n      - rewrite seqeqb_Sn. rewrite seqeq_Sn.\n        rewrite andb_true_iff.\n        (* s1 <-> t1 -> s2 <-> t2 -> s1 /\\ s2 <-> t1 /\\ t2 *)\n        apply ZifyClasses.and_morph; auto.\n        apply Xeqb_true_iff.\n    Qed.\n    \n    (** seqeqb = false <-> ~seqeq *)\n    Lemma seqeqb_false_iff : forall n f g, \n      seqeqb n f g = false <-> ~(seqeq n f g).\n    Proof.\n      induction n; intros.\n      - unfold seqeqb, seqeq. split; intros; try easy. destruct H. easy.\n      - rewrite seqeqb_Sn. rewrite seqeq_Sn.\n        rewrite andb_false_iff.\n        rewrite IHn. rewrite Xeqb_false_iff. split; intros H.\n        + apply Classical_Prop.or_not_and; auto.\n        + apply Classical_Prop.not_and_or in H; auto.\n    Qed.\n    \n    (** seqeq is decidable *)\n    Lemma seqeq_dec : forall n f g, {@seqeq n f g} + {~(@seqeq n f g)}.\n    Proof.\n      intros. destruct (seqeqb n f g) eqn:E1.\n      - left. apply seqeqb_true_iff in E1. auto.\n      - right. apply seqeqb_false_iff in E1. auto.\n    Qed.\n    \n  End Equality.\n\n  \n  (* ======================================================================= *)\n  (** ** Equality of sequence with two index *)\n  Section Equality2.\n  \n    (** Equality of two sequence *)\n    Definition seq2eq r c (f g : nat -> nat -> X) := \n      forall ri ci, ri < r -> ci < c -> f ri ci = g ri ci.\n    \n    (** seq2eq of Sr has a equivalent form. *)\n    Lemma seq2eq_Sr : forall r c (f g : nat -> nat -> X), \n      seq2eq (S r) c f g <->\n      (seq2eq r c f g) /\\ (seqeq c (f r) (g r)).\n    Proof.\n      split.\n      - intros. split; auto.\n        + unfold seq2eq in *. intros. apply H; auto.\n        + unfold seq2eq, seqeq in *. intros. auto.\n      - unfold seq2eq,seqeq. intros. destruct H.\n        destruct (ri =? r)%nat eqn : E1.\n        + apply Nat.eqb_eq in E1. subst; auto.\n        + apply Nat.eqb_neq in E1. apply H; auto. lia.\n    Qed.\n    \n    (** Boolean equality of two sequence *)\n    Fixpoint seq2eqb r c (f g : nat -> nat -> X) : bool :=\n      match r with\n      | O => true\n      | 1 => seqeqb c (f 0)%nat (g 0)%nat\n      | S r' => (seq2eqb r' c f g) && (seqeqb c (f r') (g r')) \n      end.\n    \n    (** seq2eqb of Sr has a equivalent form. *)\n    Lemma seq2eqb_Sr : forall r c (f g : nat -> nat -> X), \n      seq2eqb (S r) c f g = (seq2eqb r c f g) && (seqeqb c (f r) (g r)).\n    Proof. intros. destruct r; auto. Qed.\n    \n    (** seq2eqb = true <-> seq2eq *)\n    Lemma seq2eqb_true_iff : forall r c f g, \n      seq2eqb r c f g = true <-> seq2eq r c f g.\n    Proof.\n      induction r; intros.\n      - unfold seq2eqb, seq2eq. split; intros; auto. lia.\n      - rewrite seq2eqb_Sr. rewrite seq2eq_Sr.\n        rewrite andb_true_iff.\n        (* s1 <-> t1 -> s2 <-> t2 -> s1 /\\ s2 <-> t1 /\\ t2 *)\n        apply ZifyClasses.and_morph; auto.\n        apply seqeqb_true_iff.\n    Qed.\n    \n    (** seq2eqb = false <-> ~seq2eq *)\n    Lemma seq2eqb_false_iff : forall r c f g, \n      seq2eqb r c f g = false <-> ~(seq2eq r c f g).\n    Proof.\n      induction r; intros.\n      - unfold seq2eqb, seq2eq. split; intros; try easy. destruct H. easy.\n      - rewrite seq2eqb_Sr. rewrite seq2eq_Sr.\n        rewrite andb_false_iff.\n        rewrite IHr. rewrite seqeqb_false_iff. split; intros H.\n        + apply Classical_Prop.or_not_and; auto.\n        + apply Classical_Prop.not_and_or in H; auto.\n    Qed.\n    \n    (** seq2eq is decidable *)\n    Lemma seq2eq_dec : forall r c f g, {seq2eq r c f g} + {~(seq2eq r c f g)}.\n    Proof.\n      intros. destruct (seq2eqb r c f g) eqn:E1.\n      - left. apply seq2eqb_true_iff in E1. auto.\n      - right. apply seq2eqb_false_iff in E1. auto.\n    Qed.\n    \n  End Equality2.\n  \n  \n  (* ======================================================================= *)\n  (** ** Sum of a sequence *)\n  Section Sum.\n  \n    (** Same sequence and same index get same element *)\n    Lemma f_equal_gen : forall {X B} (f g : X -> B) a b, \n      f = g -> a = b -> f a = g b.\n    Proof. intros. subst. reflexivity. Qed.\n    \n    (** Sum of a sequence *)\n    Fixpoint seqsum (f : nat -> X) (n : nat) : X := \n      match n with\n      | O => X0\n      | S n' => seqsum f n' + f n'\n      end.\n    \n    (** Sum of a sequence which every element is zero get zero. *)\n    Lemma seqsum_seq0 : forall (f : nat -> X) (n : nat), \n      (forall i, (i < n) -> f i = X0) -> seqsum f n = X0.\n    Proof.\n      intros f n H. induction n; auto.\n      simpl. rewrite H; auto. rewrite IHn; auto. ring.\n    Qed.\n    \n    (** Corresponding elements of two sequences are equal, imply the sum are \n      equal. *)\n    Lemma seqsum_eq : forall (f g : nat -> X) (n : nat),\n      (forall i, i < n -> f i = g i) ->\n      seqsum f n = seqsum g n.\n    Proof. \n      intros f g n H. \n      induction n; simpl; auto.\n      rewrite H, IHn; auto.\n    Qed.\n      \n    (** Sum with plus of two sequence equal to plus with two sum. *)\n    Lemma seqsum_plusSeq : forall (f g : nat -> X) (n : nat),\n      seqsum (fun i => f i + g i) n = seqsum f n + seqsum g n.  \n    Proof. \n      intros f g n. induction n; simpl. ring.\n      rewrite IHn. ring.\n    Qed.\n\n    (** Constant left multiply to the sum of a sequence. *)\n    Lemma seqsum_cmul_l : forall c (f : nat -> X) (n : nat),\n      c * seqsum f n = seqsum (fun i => c * f i) n.  \n    Proof.  \n      intros c f n. induction n; simpl; try ring.\n      ring_simplify. rewrite IHn. ring.\n    Qed.\n\n    (** Constant right multiply to the sum of a sequence. *)\n    Lemma seqsum_cmul_r : forall c (f : nat -> X) (n : nat),\n      seqsum f n * c = seqsum (fun i => f i * c) n.  \n    Proof.\n      intros c f n. induction n; simpl; try ring.\n      ring_simplify. rewrite IHn. ring.\n    Qed.\n\n    (** Sum a sequence which only one item in nonzero, then got this item. *)\n    Lemma seqsum_unique : forall (f : nat -> X) (k : X) (n i : nat), \n      (i < n) -> f i = k -> (forall j, i <> j -> f j = X0) ->\n      seqsum f n = k.\n    Proof.\n      (* key idea: induction n, and case {x =? n} *)\n      intros f k n. induction n; intros. easy. simpl.\n      destruct (i =? n)%nat eqn : E1.\n      - apply Nat.eqb_eq in E1. subst.\n        assert (seqsum f n = X0).\n        { apply seqsum_seq0. intros. apply H1. subst. lia. }\n        rewrite H0. ring.\n      - apply Nat.eqb_neq in E1.\n        assert (f n = X0).\n        { apply H1; auto. }\n        assert (seqsum f n = k).\n        { apply IHn with i; auto. lia. }\n        rewrite H3,H2. ring.\n    Qed.\n    \n    (** Add the sum and a tail element *)\n    Lemma seqsum_extend_r : forall n f, \n      seqsum f n + f n = seqsum f (S n).\n    Proof. reflexivity. Qed.\n    \n    (** Add a head element and the sum *)\n    Lemma seqsum_extend_l : forall n f, \n      f O + seqsum (fun i => f (S i)) n = seqsum f (S n).\n    Proof.\n      intros n f. induction n.\n      - simpl. ring.\n      - simpl. ring_simplify. rewrite IHn. simpl. ring.\n    Qed.\n\n    (** Sum the m+n elements equal to plus of two parts.\n      Σ[i,0,(m+n)] f(i) = Σ[i,0,m] f(i) + Σ[i,0,n] f(m + i). *)\n    Lemma seqsum_plusIdx : forall m n f, seqsum f (m + n) =\n      seqsum f m + seqsum (fun i => f (m + i)%nat) n. \n    Proof.\n      intros m n f.\n      induction m.\n      - simpl. ring_simplify. auto.\n      - simpl. rewrite IHm.\n        rewrite ?add_assoc. f_equal.\n        remember (fun x => f (m + x)%nat) as g.\n        replace (f (m + n)%nat) with (g n).\n        2:{ subst. auto. }\n        replace (f m) with (g 0%nat).\n        2:{ subst. f_equal. auto. }\n        rewrite seqsum_extend_r.\n        replace (seqsum (fun x : nat => f (S (m + x))) n) with\n                (seqsum (fun x : nat => g (S x)) n).\n        2:{ subst. apply seqsum_eq. intros. f_equal. auto. }\n        rewrite seqsum_extend_l.\n        auto.\n    Qed.\n\n    (** Product two sum equal to sum of products.\n      Σ[i,0,m] f(i) * Σ[i,0,n] g(i) = Σ[i,0,m*n] f(i/n)*g(i%n).\n    \n      For example:\n        (a + b + c) * (x + y) = a*x + a*y + b*x + b*y + c*x + c*y\n    *)\n    Lemma seqsum_product : forall m n f g, n <> O ->\n      seqsum f m * seqsum g n = \n      seqsum (fun i => f (i / n)%nat * g (i mod n)%nat) (m * n). \n    Proof.\n      intros.\n      induction m.\n      - simpl. ring.\n      - simpl. ring_simplify. rewrite IHm. clear IHm.\n        remember ((fun i : nat => f (i / n)%nat * g (i mod n)%nat)) as h.\n        rewrite seqsum_cmul_l.\n        (* Σ[i,0,n] f(m)*g(i) = Σ[i,0,n] f((m*n+i)/n)*g((m*n+i)%n) *)\n        replace (seqsum (fun i : nat => f m * g i) n) \n           with (seqsum (fun i : nat => h ((m * n) + i)%nat) n).\n        + rewrite <- seqsum_plusIdx. f_equal. apply Nat.add_comm.\n        + subst.\n          apply seqsum_eq.\n          intros i Hi. f_equal.\n          * f_equal.\n            (* (m * n + i) / n = m *)\n            rewrite Nat.div_add_l; auto.  (* a * b + c) / b = a + c / b *)\n            rewrite Nat.div_small; auto.  (* a < b -> a / b = 0 *)\n          * f_equal.\n            (* (m * n + i) % n = i *)\n            rewrite Nat.add_mod; auto.  (* (a + b) % n = a % n + b % n) % n *)\n            rewrite Nat.mod_mul; auto.  (* (a * b) mod b = 0 *)\n            rewrite Nat.add_0_l.\n            repeat rewrite Nat.mod_small; auto. (* a < b -> a % b = 0 *)\n    Qed.\n    \n  End Sum.\n\nEnd Sequence.\n\n\nModule Sequence_test.\n  \n  Import Reals.\n  Module Import SequenceR := Sequence (FieldR.FieldDefR).\n  Open Scope R_scope.\n  \n(*   Example seq1 := fun n => R_of_ Z.of_nat n. *)\n(*   Compute seqsum seq1 3. *)\n  \n(*   Print Aeqb. *)\n(*   Eval simpl in seqeqb 5 seq1 seq1. *)\n(*   Compute seqeqb 5 seq1 seq1. *)\n  \n(*   Example seq2 := fun i j => Z.of_nat i + Z.of_nat j. *)\n(*   Eval simpl in seq2eqb 2 3 seq2 seq2. *)\n(*   Compute seq2eqb 2 3 seq2 seq2. *)\n    \nEnd Sequence_test. \n\n", "meta": {"author": "zhengpushi", "repo": "coq-matrix", "sha": "b0f5a3463d7f1973fd29be8b6b85e4a700297a34", "save_path": "github-repos/coq/zhengpushi-coq-matrix", "path": "github-repos/coq/zhengpushi-coq-matrix/coq-matrix-b0f5a3463d7f1973fd29be8b6b85e4a700297a34/MatrixComparison/src/Matrix/NatFun/Sequence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.738018495228639}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nModule Test_ssrnat.\n  Fixpoint sum n :=\n    if n is m.+1 then n + sum m else 0.\n  \n  Theorem double_sum n : 2 * sum n = n * n.+1.\n  Proof.\n    elim: n => [|n IHn] //=.\n    rewrite -[n.+2]addn2 !mulnDr.\n    rewrite addnC !(mulnC n.+1).\n    by rewrite IHn.\n  Qed.\nEnd Test_ssrnat.\n\nPrint reflect.\n\nModule Test_ssrbool.\n  Variables a b c : bool.\n  Print andb.\n  \n  Lemma andb_intro : a -> b -> a && b.\n  Proof.\n    move=> a b.\n    rewrite a.\n    move=> /=.\n    done.\n    Restart.\n    by move ->.\n  Qed.\n\n  Lemma andbC : a && b -> b && a.\n  Proof.\n    case: a => /=.\n      by rewrite andbT.\n      done.\n      Restart.\n      by case: a => //= ->.\n      Restart.\n      by case: a; case: b.\n  Qed.\n  \n  Lemma orbC : a || b -> b || a.\n  Proof.\n    case: a => /=.\n      by rewrite orbT.\n      by rewrite orbF.\n      Restart.\n      move/orP => H.\n      apply/orP.\n      move: H => [Ha|Hb].\n      by right.\n      by left.\n      Restart.\n        by case: a; case: b.\n  Qed.\n\n  Lemma test_if x : if x == 3 then x*x == 9 else x !=3.\n  Proof.\n    case Hx: (x == 3).\n    by rewrite (eqP Hx).\n    done.\n    Restart.\n    case: ifP.\n    by move/eqP ->.\n    move/negbT. done.\n  Qed.\nEnd Test_ssrbool.\n\n(* 自己反映があると自然数の証明もスムーズになる．*)\nTheorem avg_prod2 m n p : m+n = p+p -> (p - n) * (p - m) = 0.\nProof.\n  move=> Hmn.\n  have Hp0 q: p <= q -> p-q = 0.\n  rewrite -subn_eq0. by move/eqP.\n  suff /orP[Hpm|Hpn]: (p <= m) || (p <= n).\n  - by rewrite (Hp0 m) // muln0.\n  - by rewrite (Hp0 n).\n    case: (leqP p m) => Hpm //=.\n    case: (leqP p n) => Hpn //=.\n    suff: m + n < p + p.\n    by rewrite Hmn ltnn.\n    by rewrite -addnS leq_add // ltnW.\nQed.\n\n(* 練習問題 1.1 以下の等式を証明しなさい．タクティクは rewrite のみでできる．\n  ssrnat_doc.v の補題でほぼ足りるが, leq_mul も便利．*)\nModule Equalities.\n  Theorem square_sum a b : (a + b)^2 = a^2 + 2 * a * b + b^2.\n  Abort.\n\n  Theorem diff_square m n : m >= n -> m^2 - n^2 = (m+n) * (m-n).\n  Abort.\n\n  Theorem square_diff m n : m >= n -> (m-n)^2 = m^2 + n^2 - 2 * m * n.\n  Abort.\nEnd Equalities.\n\n\nLemma test x : 1 + x = x + 1.\n  Check [eta addnC].\n  (*: ∀ x y : nat, x + y = y + x *)\n  apply: addnC.\nAbort.      (* 定理を登録せずに証明を終わらせる *)\n\n(* Coq 本来の apply で変数が定まらないと，エラーになる．しかし，SSReflect の apply: や\napply/ を使えば，変数が残せる．*)\nLemma test x y z : x + y + z = z + y + x.\n  Check etrans.\n  (* : ∀ (A : Type) (x y z : A), x = y -> y = z -> x = z *)\n  (* apply etrans.\n     Error: Unable to find an instance for the variable y. *)\n  apply: etrans. (* y が結論に現れないので，apply: に変える *)\n  (* x + y + z = ?Goal *)\n  apply: addnC.\n  apply: etrans.\n  Check f_equal.\n  (* : ∀ (A B : Type) (f : A -> B) (x y : A), x = y -> f x = f y *)\n  apply: f_equal. (* x + y = ?Goal0 *)\n  apply: addnC.\n  apply: addnA.\n  Restart. (* 証明を元に戻す *)\n  rewrite addnC. (* rewrite も単一化を使う *)\n  rewrite (addnC x).\n  apply: addnA.\nAbort.\n\nGoal\n  (forall P : nat -> Prop, P 0 -> (forall n, P n -> P (S n)) -> forall n, P n) ->\nforall n m, n + m = m + n.\n  move=> H n m. (* 全ての変数を仮定に *)\n  apply: H. (* n + m = 0 *)\n  Restart.\n  move=> H n m.\n  pattern n. (* pattern で正しい述語を構成する *)\n  apply: H. (* 0 + m = m + 0 *)\n  Restart.\n  move=> H n. (* forall n を残すとうまくいく *)\n  apply: H. (* n + 0 = 0 + n *)\nAbort.\n", "meta": {"author": "nagaet", "repo": "garrigue-lecture-2020_AW", "sha": "e8d108a151d785629e8f29e035572038a8d23a6d", "save_path": "github-repos/coq/nagaet-garrigue-lecture-2020_AW", "path": "github-repos/coq/nagaet-garrigue-lecture-2020_AW/garrigue-lecture-2020_AW-e8d108a151d785629e8f29e035572038a8d23a6d/ssrcoq05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7380184901976444}}
{"text": "Require Import List.\nRequire Import ZArith.\n\nSection AUXLIST.\n\n Variable A:Set.\n Variable default:A.\n\n\n Definition hd l := match l with hd :: _ => hd | _ => default end. \n\n Definition tl (l: list A) := match l with _ :: tl => tl | _ => nil end. \n\n Fixpoint jump (p:positive) (l:list A) {struct p} : (list A) :=\n  match p with\n  | xH => tl l\n  | xO p => jump p (jump p l)\n  | xI p  => jump p (jump p (tl l))\n  end.\n\n Fixpoint pos_nth (p:positive) (l:list A) {struct p} : A:=\n  match p with\n  | xH => hd l\n  | xO p => pos_nth p (jump p l)\n  | xI p => pos_nth p (jump p (tl l))\n  end. \n\nEnd AUXLIST.\n\nArguments pos_nth [A] _ _ _.\n\n Ltac Trev l :=  \n  let rec rev_append rev l :=\n   match l with\n   |  nil  => constr:(rev)\n   | (cons ?h ?t) => let rev := constr:(cons h rev) in rev_append rev t \n   end in\n match type of l with\n  (list ?X) => rev_append (@nil X) l\n end.\n\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/PolTac/PolAuxList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7379994453262951}}
{"text": "Require Import List  Arith Omega.\n\nSection mirror.\n\n Variable A : Type.\n\n Inductive remove_last (a:A) : list A -> list A -> Prop :=\n   | remove_last_hd : remove_last a (a :: nil) nil\n   | remove_last_tl :\n       forall (b:A) (l m:list A),\n         remove_last a l m -> remove_last a (b :: l) (b :: m). \n\n Inductive palindrome : list A -> Prop :=\n   | empty_pal : palindrome nil\n   | single_pal : forall a:A, palindrome (a :: nil)\n   | cons_pal :\n       forall (a:A) (l m:list A),\n         palindrome l -> remove_last a m l -> palindrome (a :: m).\n \n Hint Constructors remove_last palindrome.  \n\n\n Lemma ababa : forall a b:A, palindrome (a :: b :: a :: b :: a :: nil).\n Proof.\n  eauto 7.\n Qed.\n\n\n(* more about palindromes *)\n\nLemma remove_last_inv :\n forall (a:A) (l m:list A), remove_last a m l -> m = l ++ a :: nil.\nProof.\n intros a l m H; elim H; simpl; auto with datatypes.\n intros b l0 m0 H0 e; rewrite e; trivial.\nQed.\n\nLemma rev_app : forall l m:list A, rev (l ++ m) = rev m ++ rev l.\nProof.\n intros l m; elim l; simpl; auto with datatypes.\n intros a l0 H0; rewrite ass_app; rewrite H0; auto.\nQed.\n\nLemma palindrome_rev : forall l:list A, palindrome l -> rev l = l.\nProof.\n intros l H; elim H; simpl; auto with datatypes.\n intros a l0 m H0 H1 H2; generalize H1; inversion_clear H2.\n -  simpl; auto.\n -  rewrite (remove_last_inv _ _  _ H3); simpl; repeat (rewrite rev_app; simpl).\n    intro eg; rewrite eg;  simpl; auto.\nQed.\n\n(* A new induction principle for lists *)\n\n(* preliminaries *)\n\nLemma length_app :\n forall l l':list A, length (l ++ l') = length l + length l'.\nProof.\n  intro l; elim l; simpl; auto.\nQed.\n\nLemma fib_ind :\n forall P:nat -> Prop,\n   P 0 ->\n   P 1 -> \n  (forall n:nat, P n -> P (S n) -> P (S (S n))) -> \n  forall n:nat, P n.\nProof.\n intros P H0 H1 HSSn n.\n assert (H2 : P n /\\ P (S n)).\n - induction n ;[tauto | ].\n   destruct IHn;split;auto.\n -  destruct H2; auto.\nQed.\n\nSection Proof_of_list_new_ind.\nVariables (P : list A -> Prop).\n\nHypotheses (H0 : P nil)\n           (H1 : forall a: A, P (a::nil))\n           (H2 : forall (a b:A) (l:list A), P l -> P (a :: l ++ b :: nil)).  \n   \nLemma list_cut : \nforall (l:list A) (x:A),\n            exists b : A, exists l' : list A, x :: l = l' ++ b :: nil.\nProof.\nintro l; elim l; simpl.\n intro x; exists x; exists (nil (A:=A)); auto.\n intros a1 l3 H x.\n case (H a1).\n intros x0 H7.\n case H7; intros b Hb.\n rewrite Hb.\n exists x0.\n exists (x :: b); auto.\nQed.\n\n\n\nLemma list_new_ind_length :\nforall (n:nat) (l:list A), length l = n -> P l.\nProof.\nintro n; pattern n; apply fib_ind.\n  -  intro l; case l; [simpl; auto with datatypes |  discriminate].\n  -  intro l; case l; simpl; [ discriminate | ].\n     +  intros a l0; case l0; simpl; [auto | discriminate].\n  -  intros n0 H3 H4 l; case l; simpl;[discriminate |].\n     +  intros a l0 H5; generalize H5; case l0. \n       *   simpl; discriminate 1.\n       *   intros a0 l1 H6; destruct (list_cut l1 a0) as [x [l' Hx]];\n           rewrite Hx; apply H2.\n           apply H3.\n           rewrite Hx in H6.\n           rewrite length_app in H6.\n           simpl in H6; omega.\nQed.\n\n\nLemma list_new_ind :\n   forall l:list A, P l.\nProof.\n intro l; now apply list_new_ind_length with (length l).\nQed. \n\n\nEnd Proof_of_list_new_ind.\n\n\n\nLemma app_left_reg : forall l l1 l2:list A, l ++ l1 = l ++ l2 -> l1 = l2.\nProof.\n intro l; elim l; simpl; auto.\n intros a l0 H0 l1 l2 H; injection H; auto.\nQed.\n\nLemma app_right_reg : forall l l1 l2:list A, l1 ++ l = l2 ++ l -> l1 = l2.\nProof.\n intros l l1 l2 e.\n assert (H: rev (l1 ++ l) = rev (l2 ++ l)).\n - now rewrite e.\n -  repeat rewrite rev_app in H.\n    generalize (app_left_reg _ _ _ H).\n    intro H1;  rewrite <- (rev_involutive  l1) ; \n    rewrite <- (rev_involutive l2);\n    rewrite H1; auto.\n    Qed.\n\nTheorem rev_pal : forall l:list A, rev l = l -> palindrome  l. \nProof.\n intro l; elim l using list_new_ind; auto.\n -  intros a b l0 H H0.\n    apply cons_pal with l0.\n   +  apply H;  simpl in H0;  rewrite rev_app in H0.\n      simpl in H0; injection H0.\n      intros H1 e; generalize H1; rewrite e.\n      intro H2; generalize (app_right_reg _ _ _ H2); auto.\n   +  simpl in H0; rewrite rev_app in H0; simpl in H0.\n      injection H0; intros H1 H2; rewrite <- H2.\n      generalize l0; intro l1; induction l1; simpl; auto.\nQed.\n\n\nEnd mirror.\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/ch8_inductive_predicates/SRC/palindrome.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7379994423817047}}
{"text": "Module Play.\n  \n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\nDefinition or (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\nDefinition not (b1: bool) : bool :=\n  match b1 with\n  | true => false\n  | false => true\n  end.\n\nDefinition nandb (b1: bool) (b2 : bool) : bool :=\n  match b1 with\n    | false => true\n    | true => (not b2)\n  end.\n\nExample test_nandb1 : (nandb true false) = true.\nProof. reflexivity. Qed.\n\nExample test_nandb2 : (nandb false false) = true.\nProof. reflexivity. Qed.\n\nExample test_nandb3 : (nandb false true) = true.\nreflexivity. Qed.\n\nExample test_nandb4 : (nandb true true) = false.\nreflexivity. Qed.\n\nDefinition andb2 (b1 : bool) (b2 : bool) : bool :=\n  match b1 with\n    | false => false\n    | true => b2\n  end.\n\nDefinition andb3 (b1 : bool) (b2 :bool) (b3 : bool) :bool :=\n  andb2 (andb2 b1 b2) b3.\n\nExample test_andb31: (andb3 true true true) = true.\nreflexivity. Qed.\n\nExample test_andb32: (andb3 false true true) = false.\nreflexivity. Qed.\n\nExample test_andb33: (andb3 true false true) = false.\nreflexivity. Qed.\n\nExample test_andb34: (andb3 true true false) = false.\nreflexivity. Qed.\n\n", "meta": {"author": "DKXXXL", "repo": "SoftwareFoundations-BeforeCh15", "sha": "fa69bb170f91e5e358747575815f03ad8846646f", "save_path": "github-repos/coq/DKXXXL-SoftwareFoundations-BeforeCh15", "path": "github-repos/coq/DKXXXL-SoftwareFoundations-BeforeCh15/SoftwareFoundations-BeforeCh15-fa69bb170f91e5e358747575815f03ad8846646f/08182016.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7379994176808407}}
{"text": " (* by Evelyne Contejean *)\n(** * Permutation over lists, and finite multisets. *)\n\nSet Implicit Arguments.\n\nFrom Cyclic_PA.Casteran Require Import decidable_set.\nRequire Import List.\nFrom Cyclic_PA.Casteran Require Import more_list.\nRequire Import Multiset.\nRequire Import Arith.\nRequire Import Setoid.\n\nModule Type Permut.\n\nDeclare Module DS : decidable_set.S.\n\nDefinition elt := DS.A.\nDefinition eq_elt_dec := DS.eq_A_dec.\n\nFixpoint list_to_multiset (l : list elt) {struct l} : multiset elt :=\n  match l with\n  | nil => EmptyBag elt\n  | h :: tl =>\n      munion (SingletonBag _ eq_elt_dec h) (list_to_multiset tl)\n  end.\n\nDefinition list_permut (l1 l2:list elt) : Prop :=\n  meq (list_to_multiset l1) (list_to_multiset l2).\n\nEnd Permut.\n\n(** ** Definition of permutation over lists. *)\nModule Make (DS1 : decidable_set.S) <: Permut with Module DS:= DS1.\n\nModule DS := DS1.\nImport DS1.\n\nDefinition elt := DS.A.\nDefinition eq_elt_dec : forall t1 t2 : elt, {t1 = t2} + {t1 <> t2} := DS.eq_A_dec.\n\nFixpoint list_to_multiset (l : list elt) {struct l} : multiset elt :=\n  match l with\n  | nil => EmptyBag elt\n  | h :: tl =>\n      munion (SingletonBag _ eq_elt_dec h) (list_to_multiset tl)\n  end.\n\nDefinition list_permut (l1 l2:list elt) : Prop :=\n  meq (list_to_multiset l1) (list_to_multiset l2).\n\n(** Properties over the multiplicity. *)\nLemma multiplicity_app :\n forall (l1 l2:list elt) (t : elt),\n   multiplicity (list_to_multiset (l1 ++ l2)) t =\n   multiplicity (list_to_multiset l1) t + multiplicity (list_to_multiset l2) t.\nProof.\ninduction l1; intros; trivial.\nsimpl; intros; rewrite (IHl1 l2 t); auto with arith.\nQed.\n\nLemma out_mult_O :\n  forall (t : elt) (l:list elt), ~ In t l -> multiplicity (list_to_multiset l) t = 0.\nProof.\nintro t; unfold list_to_multiset; induction l.\nintros _; trivial.\nintro H; simpl; elim (eq_elt_dec a t).\nintro; subst t; absurd (In a (a :: l)); trivial; left; trivial.\nintros _; apply IHl;\nunfold not; intros; apply H;\nsimpl; right; assumption.\nQed.\n\nLemma in_mult_S :\n forall (t : elt) (l : list elt), In t l -> multiplicity (list_to_multiset l) t >= 1.\nProof.\nintro t; unfold list_to_multiset; induction l.\ncontradiction.\nsimpl; intro H; elim H; clear H.\nintro H; subst t; elim (eq_elt_dec a a).\nintros _ ; auto with arith.\nintro; absurd (a=a); trivial.\nelim (eq_elt_dec a t).\nintros _ _; auto with arith. \nintros; simpl; apply IHl; assumption.\nQed.\n\n\n(** ** Permutation is a equivalence relation. \nReflexivity. *)\nTheorem list_permut_refl :\n forall (l : list elt), list_permut l l.\nProof.\nunfold list_permut, meq; intros; trivial.\nQed.\n\n(** Symetry. *)\nTheorem list_permut_sym :\n forall l1 l2 : list elt, list_permut l1 l2 -> list_permut l2 l1.\nProof.\nunfold list_permut, meq; intros; apply sym_eq; trivial.\nQed.\n\nHint Immediate list_permut_refl.\nHint Resolve list_permut_sym.\n\n(** Transitivity. *)\nTheorem list_permut_trans :\n  forall l1 l2 l3 : list elt, list_permut l1 l2 -> list_permut l2 l3 -> list_permut l1 l3.\nProof.\nunfold list_permut, meq; intros;\napply trans_eq with (multiplicity (list_to_multiset l2) a); trivial.\nQed.\n\nAdd Relation (list elt) list_permut \nreflexivity proved by list_permut_refl\nsymmetry proved by list_permut_sym\ntransitivity proved by list_permut_trans as LP.\n\n(** Permutation of an empty list. *)\nLemma list_permut_nil :\n forall l, list_permut l nil -> l = nil.\nProof.\nintro l; destruct l as [ | e l ]; trivial.\nintros Abs; absurd (list_permut (e :: l) nil); trivial.\nunfold not; unfold list_permut, meq; intro H; \ngeneralize (H e); simpl; elim (eq_elt_dec e e).\nintros _; discriminate.\nintro; absurd (e=e); trivial.\nQed.\n\n\n(** ** Compatibility Properties. \n Permutation is compatible with In. *)\nLemma in_permut_in :\n  forall l1 l2 e, In e l1 -> list_permut l1 l2 -> In e l2.\nProof.\nunfold list_permut, meq; intros l1 l2 e Inel1 Pl1l2.\nelim (In_dec eq_elt_dec e l2).\nintros; trivial.\nintro notInel2; generalize (Pl1l2 e);\nrewrite (out_mult_O e l2 notInel2);\nintro M0; generalize (in_mult_S e l1 Inel1);\nrewrite M0; unfold ge;\nintro Abs; absurd (1<=0); trivial; inversion Abs.\nSave in_permut_in.\n\nAdd Morphism (In (A :=elt)) : in_morph.\nProof.\nintros; split; intros.\napply in_permut_in with x; trivial.\napply in_permut_in with y0; trivial; apply list_permut_sym; trivial.\nQed.\n\nLemma cons_permut_in :\n  forall l1 l2 e, list_permut (e :: l1) l2 -> In e l2.\nProof.\nintros l1 l2 e P; setoid_rewrite <- P; left; trivial.\nQed.\n\n(** Permutation is compatible with adding an element. *)\nLemma context_list_permut_cons :\n  forall e l1 l2, list_permut l1 l2 -> list_permut (e :: l1) (e :: l2).\nProof.\nintros e l1 l2; unfold list_permut, meq; simpl.\nintros H a; rewrite (H a); trivial.\nSave context_list_permut_cons.\n\nAdd Morphism (List.cons (A:=elt)) : add_elt_morph.\nProof.\nintros; apply context_list_permut_cons; trivial.\nQed.\n\nLemma list_permut_add_inside :\nforall a l1 l2 l3 l4, \n  list_permut (l1 ++ l2) (l3 ++ l4) ->\n  list_permut (l1 ++ a :: l2) (l3 ++ a :: l4).\nProof.\nintros a l1 l2 l3 l4; unfold list_permut, meq; simpl;\nintros H b; generalize (H b); clear H;\nrepeat rewrite multiplicity_app; simpl;\nintro H; rewrite plus_comm; rewrite <- plus_assoc; apply sym_eq;\nrewrite plus_comm; rewrite <- plus_assoc; \napply (f_equal (fun n => match eq_elt_dec a b with \n                         | left _ => 1 \n                         | right _ => 0 end + n));\nrewrite plus_comm; rewrite <- H; apply plus_comm.\nQed.\n\nLemma list_permut_add_cons_inside :\nforall a l l1 l2, \n  list_permut l (l1 ++ l2) ->\n  list_permut (a :: l) (l1 ++ a :: l2).\nProof.\nintros;\nreplace (a :: l) with (nil ++ a :: l); trivial;\napply list_permut_add_inside; trivial.\nQed.\n\n(** Permutation is compatible with append. *)\nLemma context_list_permut_app1 :\n  forall l l1 l2, list_permut l1 l2 -> list_permut (l ++ l1) (l ++ l2).\nProof.\nintros l l1 l2; unfold list_permut, meq; simpl.\nintros H a; \nrewrite (multiplicity_app l l1);\nrewrite (multiplicity_app l l2);\nrewrite (H a); \ntrivial.\nQed.\n\nLemma context_list_permut_app2 :\n  forall l l1 l2, list_permut l1 l2 -> list_permut (l1 ++ l) (l2 ++ l).\nProof.\nintros l l1 l2; unfold list_permut, meq; simpl; intros H a; \nrewrite (multiplicity_app l1 l);\nrewrite (multiplicity_app l2 l);\nrewrite (H a); \ntrivial.\nSave context_list_permut_app2.\n\nAdd Morphism (List.app (A:=elt)) : app_morph.\nProof.\nintros.\napply list_permut_trans with (x ++ y0).\napply context_list_permut_app1; trivial.\napply context_list_permut_app2; trivial.\nQed.\n\nLemma list_permut_app_app :\n forall l1 l2, list_permut (l1 ++ l2) (l2 ++ l1).\nProof.\nintros l1 l2;\nunfold list_permut, meq; \nintro a; rewrite multiplicity_app; rewrite multiplicity_app;\napply plus_comm.\nQed.\n\n(** Permutation is compatible with removal of common elements *)\nLemma remove_context_list_permut_cons :\n  forall e l1 l2, list_permut (e :: l1) (e :: l2) -> list_permut l1 l2.\nProof.\nintros e l1 l2; unfold list_permut, meq; simpl; intros H a;\ngeneralize (H a); apply plus_reg_l.\nQed.\n\nLemma remove_context_list_permut_app2 :\n  forall l l1 l2, list_permut (l1 ++ l) (l2 ++ l) -> list_permut l1 l2.\nProof.\nintros l l1 l2; unfold list_permut, meq; simpl;\nintros H a; generalize (H a);\nrewrite (multiplicity_app l1 l);\nrewrite (multiplicity_app l2 l); \nintros; apply plus_reg_l with (multiplicity (list_to_multiset l) a).\nrewrite plus_comm; rewrite H0; rewrite plus_comm.\ntrivial.\nQed.\n\nLemma list_permut_remove_hd :\n  forall l l1 l2 a,   \n  list_permut (a :: l) (l1 ++ a :: l2) -> list_permut l (l1 ++ l2).\nProof.\nintros l l1 l2 a; unfold list_permut, meq; simpl; intros H a0; generalize (H a0);\nrewrite multiplicity_app; rewrite multiplicity_app;\nsimpl; intro H1; \napply plus_reg_l with (match eq_elt_dec a a0 with left _ => 1 | right _ => 0 end);\nrewrite H1; repeat rewrite plus_assoc;\napply (f_equal (fun n => n + multiplicity (list_to_multiset l2) a0));\napply plus_comm.\nQed.\n\n(** Permutation is compatible with length. *)\nLemma list_permut_length :\n forall l1 l2, list_permut l1 l2 -> length l1 = length l2.\nProof.\ninduction l1; intros l2 H.\nrewrite (list_permut_nil (list_permut_sym H)); auto.\nelim (In_dec eq_elt_dec a l2).\nintro Inal2; generalize (split_list_app_cons eq_elt_dec a l2 Inal2);\ndestruct (split_list eq_elt_dec l2 a); intro; subst l2.\nrewrite list_app_length; simpl;\nrewrite (IHl1 _ (list_permut_remove_hd l l0 H));\nrewrite list_app_length; auto with arith.\nintro notInal2; absurd (In a l2); trivial;\napply in_permut_in with (a :: l1); trivial;\nleft; trivial.\nQed.\n\n\nAdd Morphism (length (A:=elt)) : length_morph.\nProof.\napply list_permut_length.\nQed.\n\n(** Permutation is compatible with size. *)\nLemma list_permut_size :\n  forall size l1 l2, list_permut l1 l2 -> list_size size l1 = list_size size l2.\nProof.\nintro size; induction l1.\nintros l2 P; \nrewrite (list_permut_nil (list_permut_sym P));\ntrivial.\nintros l2 P; \ngeneralize (split_list_app_cons eq_elt_dec _ _ (cons_permut_in P));\ndestruct (split_list eq_elt_dec l2 a); intro; subst l2;\nrewrite list_size_app; simpl;\nrewrite (IHl1 _ (list_permut_remove_hd _ _ P));\nrewrite list_size_app;\nrewrite plus_comm; rewrite <- plus_assoc;\napply (f_equal (fun n => list_size size l + n));\napply plus_comm.\nQed.\n\nAdd Morphism (fun size => list_size (A:=elt) size) : list_size_morph.\nProof.\nintros x y H x0. unfold Morphisms.pointwise_relation in H. induction x0.\n- intros. rewrite (list_permut_nil (list_permut_sym H0)) in *. auto.\n- intros. simpl. rewrite H. pose (in_permut_in a (in_eq _ x0) H0). apply In_split in i. destruct i as [l1 [l2 HL]]. rewrite HL in *.\n  apply list_permut_remove_hd in H0. rewrite (IHx0 _ H0). rewrite list_size_app. rewrite list_size_app. simpl.\n  rewrite (plus_comm (y a) (list_size y l2)). rewrite (plus_assoc (list_size y l1)). rewrite plus_comm. auto.\nQed.\n\n(** Permutation is compatible with map. *)\nLemma list_permut_map :\n  forall f l1 l2, list_permut l1 l2 -> list_permut (map f l1) (map f l2).\nProof.\nintros f l1; induction l1.\nintros l2 P; rewrite (list_permut_nil (list_permut_sym P)); apply list_permut_refl.\nintros l2 P;\ngeneralize (split_list_app_cons eq_elt_dec _ _ (cons_permut_in P));\ndestruct (split_list eq_elt_dec l2 a); intro; subst l2.\nrewrite map_app; simpl;\napply list_permut_add_cons_inside; rewrite <- map_app; \napply (IHl1 _ (list_permut_remove_hd l l0 P)).\nQed.\n\nAdd Morphism (fun l => fun f : elt -> elt => map f l) : map_morph.\nProof.\nintros x. induction x.\n- intros. rewrite (list_permut_nil (list_permut_sym H)) in *. auto.\n- intros. simpl. rewrite H0. pose (in_permut_in a (in_eq _ x) H). apply In_split in i. destruct i as [l1 [l2 HL]]. rewrite HL in *.\n  apply list_permut_remove_hd in H. rewrite (IHx _ H _ _ H0). rewrite map_app. rewrite map_app. simpl. apply list_permut_add_cons_inside. apply list_permut_refl.\nQed.\n\n(** ** Permutation for short lists. *)\n\nLemma list_permut_length_1:\n forall a b, list_permut (a :: nil) (b :: nil)  -> a = b.\nProof.\nintros a b; unfold list_permut, meq; intro P;\ngeneralize (P a); clear P; simpl.\nelim (eq_elt_dec a a).\nintros _; elim (eq_elt_dec b a).\nintros b_eq_a _; apply sym_eq; trivial.\nintros _ Abs; simpl in Abs; absurd (1=0); trivial; discriminate.\nintro; absurd (a=a); trivial.\nQed.\n\nLemma list_permut_length_2 :\n forall a1 b1 a2 b2, list_permut (a1 :: b1 :: nil) (a2 :: b2 :: nil) ->\n (a1=a2 /\\ b1=b2) \\/ (a1=b2 /\\ a2=b1).\nProof.\nintros a1 b1 a2 b2 P; elim (cons_permut_in P).\nintro; subst a2; left; split; trivial.\napply list_permut_length_1; apply remove_context_list_permut_cons with a1; trivial.\nintro H; elim H; clear H. \nintro; subst b2; right; split; trivial.\napply sym_eq; apply list_permut_length_1;\napply (list_permut_remove_hd (a2 :: nil) nil P).\nintro;  contradiction.\nQed.\n\n(** ** Link with AC syntactic decomposition.*)\nLemma ac_syntactic_aux :\n forall (l1 l2 l3 l4 : list elt),\n list_permut (l1 ++ l2) (l3 ++ l4) ->\n (exists u1, exists u2, exists u3, exists u4, \n list_permut l1 (u1 ++ u2) /\\\n list_permut l2 (u3 ++ u4) /\\\n list_permut l3 (u1 ++ u3) /\\\n list_permut l4 (u2 ++ u4)).\nProof.\ninduction l1.\nintros l2 l3 l4 P;\nexists (nil : list elt); exists (nil : list elt); exists l3; exists l4; \nsimpl; intuition. \n\nintros l2 l3 l4 P; rewrite <- app_comm_cons in P;\nelim (in_app_or l3 l4 a (cons_permut_in P)); intro In_a;\ngeneralize (split_list_app_cons eq_elt_dec a _ In_a).\ndestruct (split_list eq_elt_dec l3 a); intro; subst l3;\nrewrite app_ass in P; rewrite <- app_comm_cons in P;\ngeneralize (list_permut_remove_hd _ _ P); clear P; \nintro P; rewrite <- app_ass in P; \nelim (IHl1 l2 (l ++ l0) l4 P); clear IHl1 P;\nintros u1 H; elim H; clear H; \nintros u2 H; elim H; clear H;\nintros u3 H; elim H; clear H;\nintros u4 P; elim P; clear P;\nintros P1 P; elim P; clear P;\nintros P2 P; elim P; clear P;\nintros P3 P4;\nexists (a :: u1); exists u2; exists u3; exists u4; intuition; simpl; trivial.\n(* setoid_rewrite <- P1. *)\napply context_list_permut_cons; trivial.\napply list_permut_sym; apply list_permut_add_cons_inside;\napply list_permut_sym; trivial.\n\ndestruct (split_list eq_elt_dec l4 a); intro; subst l4;\nrewrite <- app_ass in P; \ngeneralize (list_permut_remove_hd _ _ P); clear P;\nintro P; rewrite app_ass in P; \nelim (IHl1 l2 l3 (l ++ l0) P); clear IHl1 P;\nintros u1 H; elim H; clear H; \nintros u2 H; elim H; clear H;\nintros u3 H; elim H; clear H;\nintros u4 P; elim P; clear P;\nintros P1 P; elim P; clear P;\nintros P2 P; elim P; clear P;\nintros P3 P4;\nexists u1; exists (a :: u2); exists u3; exists u4; intuition; simpl; trivial.\napply list_permut_add_cons_inside; trivial.\napply list_permut_sym; apply list_permut_add_cons_inside; \napply list_permut_sym; trivial.\nQed.\n\nLemma ac_syntactic :\n forall (l1 l2 l3 l4 : list elt),\n list_permut (l2 ++ l1) (l4 ++ l3) ->\n (exists u1, exists u2, exists u3, exists u4, \n list_permut l1 (u1 ++ u2) /\\\n list_permut l2 (u3 ++ u4) /\\\n list_permut l3 (u1 ++ u3) /\\\n list_permut l4 (u2 ++ u4)).\nProof.\nintros l1 l2 l3 l4 P; apply ac_syntactic_aux.\napply list_permut_trans with (l2 ++ l1).\napply list_permut_app_app.\napply list_permut_trans with (l4 ++ l3); trivial.\napply list_permut_app_app.\nQed.\n\nLemma list_permut_dec : forall l1 l2, {list_permut l1 l2}+{~list_permut l1 l2}.\nProof.\nintro l1; induction l1 as [ | e1 l1].\ndestruct l2 as [ | e2 l2].\nleft; apply list_permut_refl.\nright; intro P; assert (H := list_permut_length P); discriminate.\nintro l2; destruct (In_dec eq_elt_dec e1 l2) as [e1_in_l2 | e1_not_in_l2].\ngeneralize (split_list_app_cons eq_elt_dec _ _ e1_in_l2); clear e1_in_l2;\ndestruct (split_list eq_elt_dec l2 e1) as [l2' l2'']; intro; subst.\ndestruct (IHl1 (l2' ++ l2'')) as [P | nP].\nleft; apply list_permut_add_cons_inside; trivial.\nright; intro P; apply nP; apply list_permut_remove_hd with e1; trivial.\nright; intro P; apply e1_not_in_l2; apply in_permut_in with (e1 :: l1); trivial;\nleft; trivial.\nQed.\n\nEnd Make.\n\n(* With section instead of module, and then polymorph use \nSection LP.\nVariable elt : Set.\nParameter eq_elt_dec : forall t1 t2 : elt, {t1 = t2} + {t1 <> t2}.\n...\nEnd LP.\n\nAdd Relation list list_permut \nreflexivity proved by list_permut_refl\nsymmetry proved by list_permut_sym\ntransitivity proved by list_permut_trans as LP_poly.\n\nAdd Morphism In with signature  eq ==> list_permut ==> iff as in_morph_poly.\nProof.\nintros; split; intros.\napply in_permut_in with x1; trivial.\napply in_permut_in with x2; trivial; apply list_permut_sym; trivial.\nQed.\n\nGoal forall (a b:nat), list_permut (a::b::nil) (b::a::nil) -> \nIn a (b :: a :: nil).\nintros a b P.\nsetoid_rewrite <- P.\nleft; trivial.\nQed.\n*)\n\n(*\nExtract Constant eq_element_dec => eq.\nExtract Constant o_element_dec => le.\nExtract Constant element => int.\nExtraction split_list.\nExtraction partition.\nExtraction NoInline partition.\nExtraction quicksort.\n*)\n\n", "meta": {"author": "aarondroidbryce", "repo": "cyclic_peano", "sha": "fb0a713eb8ada20402c62a5953e1ccc800860605", "save_path": "github-repos/coq/aarondroidbryce-cyclic_peano", "path": "github-repos/coq/aarondroidbryce-cyclic_peano/cyclic_peano-fb0a713eb8ada20402c62a5953e1ccc800860605/theories/Casteran/list_permut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7379556823210308}}
{"text": "(* week_38c_mystery_functions.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\n(* Are the following specifications unique?\n   What are then the corresponding functions?\n\n   Spend the rest of your dIFP weekly time\n   to answer these questions\n   for the specifications below.\n   (* At least 7 specifications would be nice. *)\n*)\n\n(* ********** *)\nRequire Import Arith List.\nRequire Import unfold_tactic.\n\n(* Helper stuff *)\n\nLemma unfold_plus_bc :\n  forall j : nat,\n    plus 0 j = j.\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_plus_ic :\n  forall i' j : nat,\n    plus (S i') j = S (plus i' j).\nProof.\n  unfold_tactic plus.\nQed.\n\n(* Helper for later *)\nProposition plus_1_S :\n  forall n : nat,\n    S n = plus 1 n.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    rewrite -> (plus_0_r 1).\n    reflexivity.\n  \n  (* Inductive case: *)\n    rewrite -> (unfold_plus_ic 0 (S n')).\n    rewrite -> (plus_0_l (S n')).\n    reflexivity.\nQed.\n\nProposition plus_S_1 :\n  forall n : nat,\n    S n = plus n 1.\nProof.\n  intro.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n    rewrite -> (plus_0_l 1).\n    reflexivity.\n\n  (* Inductive case: *)\n    rewrite -> (unfold_plus_ic n' 1).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\nLemma unfold_mult_bc :\n  forall y : nat,\n    0 * y = 0.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic mult.\nQed.\n\nLemma unfold_mult_ic :\n  forall x' y : nat,\n    (S x') * y = y + (x' * y).\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic mult.\nQed.\n\nLemma nat_ind2 :\n  forall P : nat -> Prop,\n    P 0 ->\n    P 1 ->\n    (forall i : nat,\n      P i -> P (S i) -> P (S (S i))) ->\n    forall n : nat,\n      P n.\nProof.\n  intros P H_P0 H_P1 H_PSS n.\n  assert(consecutive :\n           forall x : nat,\n             P x /\\ P (S x)).\n    intro x.\n    induction x as [ | x' [IHx' IHSx']].\n      split.\n        exact H_P0.\n      exact H_P1.\n\n      split.\n        exact IHSx'.\n      exact (H_PSS x' IHx' IHSx').\n\n      destruct (consecutive n) as [ly _].\n\n      exact ly.\nQed.\n\n\nDefinition specification_of_the_mystery_function_0 (f : nat -> nat) :=\n  (f 0 = 1)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = f i + f j).\n\nProposition there_is_only_one_mystery_function_0 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_0 f ->\n    specification_of_the_mystery_function_0 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_0.  \n  intros [H_mys_bc1 H_mys_ic1].\n  intros [H_mys_bc2 H_mys_ic2].\n  intro n.\n  induction n as [ | n' IHn'].\n  (* Base case: *)\n    rewrite -> (H_mys_bc1).\n    rewrite -> (H_mys_bc2).\n    reflexivity.\n\n  (* Inductive case: *)\n    rewrite <- (plus_0_r n').\n    rewrite -> (H_mys_ic1 n' 0).\n    rewrite -> (H_mys_ic2 n' 0).\n    rewrite -> (H_mys_bc1).\n    rewrite -> (H_mys_bc2).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\nTheorem and_the_mystery_function_0_is_dot_dot_dot :\n  specification_of_the_mystery_function_0 S.\nProof.\n\n  unfold specification_of_the_mystery_function_0.\n  split.\n    reflexivity.\n\n    intros i j.\n    rewrite -> (plus_1_S).\n    rewrite -> (plus_S_1).\n    rewrite -> (plus_1_S).\n    rewrite -> (plus_assoc 1 i j).\n    Check(plus_1_S).\n    rewrite <- (plus_1_S i).\n    rewrite <- (plus_assoc (S i) j 1).\n    rewrite <- (plus_S_1 j).\n    reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_1 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (forall i j : nat,\n    f (i + S j) = f i + S (f j)).\n\nProposition there_is_only_one_mystery_function_1 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_1 f ->\n    specification_of_the_mystery_function_1 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_1.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n    rewrite <- (plus_0_l (S n')).\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    rewrite (IHn').\n    reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_1_is_id :\n  specification_of_the_mystery_function_1 id.\nProof.\n  unfold specification_of_the_mystery_function_1.\n  split.\n  \n    reflexivity.\n\n\n    intros i j.\n    unfold id.\n    reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_2 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = S (f i) + S (f j)).\n\nProposition there_is_only_one_mystery_function_2 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_2 f ->\n    specification_of_the_mystery_function_2 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_2.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n    Check(plus_n_Sm).\n    rewrite <- (plus_0_l (S n')).\n    rewrite <- (plus_n_Sm 0 n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\n\n\nTheorem and_the_mystery_function_2_is_mult_2 :\n  specification_of_the_mystery_function_2 (mult 2).\nProof.\n  unfold specification_of_the_mystery_function_2.\n  split.\n  \n    rewrite -> (mult_0_r 2).\n    reflexivity.\n\n    intros i j.\n    rewrite -> (plus_n_Sm i j).\n    rewrite <- (plus_0_r j).\n    rewrite -> (plus_n_Sm j 0).\n    rewrite -> (plus_assoc i j 1).\n    rewrite -> (plus_0_r j).\n    rewrite <- (plus_0_r (2*i)).\n    rewrite -> (plus_n_Sm (2*i) 0).\n    rewrite <- (plus_0_r (2*j)).\n    rewrite -> (plus_n_Sm (2*j) 0).\n    rewrite <- (plus_assoc i j 1).\n    rewrite -> (plus_comm j 1).\n    rewrite -> (plus_assoc i 1 j).\n    rewrite -> (mult_plus_distr_l 2 (i+1) j).\n    rewrite -> (mult_plus_distr_l 2 i 1).\n    rewrite -> (plus_comm (2*j) 1).\n    rewrite -> (plus_assoc (2*i+1) 1 (2*j)).\n    rewrite -> (mult_1_r 2).\n    Check(plus_assoc).\n    rewrite <- (plus_assoc (2*i) 1 1).\n    rewrite <- (plus_1_S 1).\n    reflexivity.\nQed.\n\n\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_3 (f : nat -> nat) :=\n  (f 0 = 1)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = S (f i) + S (f j)).\n\n\nProposition there_is_only_one_mystery_function_3 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_3 f ->\n    specification_of_the_mystery_function_3 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_3.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n    \n  \n  (* Inductive case: *)\n\n    rewrite <- (plus_0_l (S n')).\n    rewrite <- (plus_n_Sm 0 n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_3_is_mult_3_plus_1 :\n  specification_of_the_mystery_function_3 (fun x => (3*x +1)).\nProof.\n  unfold specification_of_the_mystery_function_3.\n  split.\n  \n    rewrite -> (mult_0_r).\n    rewrite -> (plus_0_l).\n    reflexivity.\n\n    intros i j.\n    rewrite -> (plus_S_1 (i + j)).\n    rewrite -> (mult_plus_distr_l).\n    rewrite -> (mult_plus_distr_l).\n    rewrite -> (plus_S_1 (3*i + 1)).\n    rewrite -> (plus_1_S (3*j + 1)).\n    rewrite <- (plus_assoc (3*i) 1 1).\n    rewrite <- (plus_1_S 1).\n    rewrite -> (mult_1_r 3).\n    rewrite <- (plus_assoc (3*i + 3*j) 3 1).\n    rewrite <- (plus_S_1 3).\n    rewrite -> (plus_comm (3*j) 1).\n    rewrite -> (plus_assoc 1 1 (3*j)).\n    rewrite <- (plus_S_1 1).\n    rewrite -> (plus_assoc (3*i + 2) 2 (3 * j)).\n    rewrite <- (plus_assoc (3*i) 2 2).\n    rewrite <- (plus_n_Sm 2 1).\n    rewrite <- (plus_n_Sm 2 0).\n    rewrite -> (plus_0_r 2).\n    rewrite <- (plus_assoc (3*i) 4 (3*j)).\n    rewrite -> (plus_comm 4 (3*j)).\n    rewrite -> (plus_assoc (3*i) (3*j) 4).\n    reflexivity.\nQed.\n\n\n(* ********** *)\n\n\nDefinition specification_of_the_mystery_function_4 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (forall i j : nat,\n    f (i + j) = f i + f j).\n\nProposition there_is_only_one_mystery_function_4 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_4 f ->\n    specification_of_the_mystery_function_4 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_4.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n    \n  \n  (* Inductive case: *)\n\n    rewrite -> (plus_1_S n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (plus_1_S 0).\nAbort.\n\n\nTheorem possible_mystery_function_4_is_plus_0 : \n  specification_of_the_mystery_function_4 (plus 0).\nProof.\n  unfold specification_of_the_mystery_function_4.\n  split.\n    rewrite -> (plus_0_l).\n    reflexivity.\n\n    intros i j.\n    rewrite ->3 (plus_0_l).\n    reflexivity.\nQed.\n\nTheorem another_possibility_for_mystery_function_4_is_mult_1 : \n  specification_of_the_mystery_function_4 (mult 1).\nProof.\n  unfold specification_of_the_mystery_function_4.\n  split.\n    rewrite -> (mult_0_r).\n    reflexivity.\n    \n    intros i j.\n    rewrite ->3 (mult_1_l).\n    reflexivity.\nQed.\n\nTheorem and_the_mystery_function_4_is_mult_id :\n  specification_of_the_mystery_function_4 id.\nProof.\n  unfold specification_of_the_mystery_function_4.\n  split.\n  \n    unfold id.\n    reflexivity.\n\n    intros i j.\n    unfold id.\n    reflexivity.\nQed.\n\n\n\n(* ********** *)\n\nLemma binomial_2 :\n  forall x y : nat,\n    (x + y) * (x + y) = (x * x) + 2 * x * y + (y * y).\nProof.\n  intros x y.\n\n  rewrite -> mult_plus_distr_r.\n  rewrite -> mult_plus_distr_l.\n  rewrite -> mult_plus_distr_l.\n  rewrite -> (mult_comm y x).\n  symmetry.\n\n  rewrite -> (unfold_mult_ic 1 x).\n  rewrite -> (unfold_mult_ic 0 x).\n  rewrite -> unfold_mult_bc.\n  rewrite -> plus_0_r.\n  rewrite -> mult_plus_distr_r.\n  rewrite -> plus_assoc.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed.\n\nDefinition specification_of_the_mystery_function_5 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (forall i : nat,\n    f (S i) = S (2 * i + f i)).\n\n\nProposition there_is_only_one_mystery_function_5 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_5 f ->\n    specification_of_the_mystery_function_5 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_5.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n   \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite (IHn').\n    reflexivity.\nQed.\n\nTheorem and_the_mystery_function_5_is_square :\n  specification_of_the_mystery_function_5 (fun x => x * x).\nProof.\n  unfold specification_of_the_mystery_function_5.\n  split.\n    rewrite -> (mult_0_r).\n    reflexivity.\n\n    intro i.\n    rewrite -> (plus_1_S).\n    rewrite -> (plus_1_S (2*i + i*i)).\n    rewrite -> (plus_assoc 1 (2*i) (i*i)).\n    rewrite <- (mult_1_r (2*i)).\n    rewrite <- (mult_assoc 2 i 1).\n    rewrite -> (mult_comm i 1).\n    rewrite -> (mult_assoc 2 1 i).\n    rewrite -> (binomial_2).\n    rewrite <- (mult_1_l 1) at 5.\n    reflexivity.\nQed.\n\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_6 (f : nat -> nat) :=\n  (forall i j : nat,\n    f (i + j) = f i + 2 * i * j + f j).\n\n\nProposition there_is_only_one_mystery_function_6 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_6 f ->\n    specification_of_the_mystery_function_6 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_6.\n  intros H_f H_g.\n  intro n.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n   \n    rewrite <- (plus_0_l 0).\n    rewrite -> (H_f).\n    rewrite -> (H_g).\nAbort.\n\n\n\nTheorem and_the_mystery_function_6_is_power :\n  specification_of_the_mystery_function_6 (fun x => x*x).\nProof.\n  unfold specification_of_the_mystery_function_6.\n  intros i j.\n  apply (binomial_2).\nQed.\n\nLemma rewriting_in_short_form_v1 : \n  forall a b c d : nat,\n    a + b + c + d = a + d + b + c.\nProof.                    \n  intros a b c d.\n  rewrite <- (plus_assoc a d b).\n  rewrite -> (plus_comm d b).\n  rewrite <- (plus_assoc a (b + d) c).\n  rewrite -> (plus_comm b d).\n  rewrite <- (plus_assoc d b c).\n  rewrite -> (plus_comm d (b + c)).\n  rewrite -> (plus_assoc a (b + c) d).\n  rewrite -> (plus_assoc a b c).\n  reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_6_could_also_be : \n  specification_of_the_mystery_function_6 (fun x => x*x + 2*x).\nProof.\n  unfold specification_of_the_mystery_function_6.\n  intros i j.\n  rewrite -> (binomial_2).\n  rewrite -> (mult_plus_distr_l).\n  rewrite -> (plus_comm (2*i) (2*j)).\n  rewrite <- (plus_assoc (i*i) (2*i) (2*i*j)).\n  rewrite -> (plus_comm (2*i) (2*i*j)).\n  rewrite -> (plus_assoc (i*i) (2*i*j) (2*i)).\n  rewrite ->2 (plus_assoc).\n  rewrite -> (rewriting_in_short_form_v1 (i*i + 2*i*j) (j*j) (2*j) (2*i)).\n  reflexivity.\nQed.  \n  \n(* ********** *)\n\nFixpoint exp (x n : nat)  :=\n  match n with\n      | 0 => 1\n      | S n' => mult x (exp x n')\nend.               \n\nLemma unfold_exp_bc :\n  forall x : nat,\n    exp x 0 = 1.\nProof.\n  unfold_tactic exp.\nQed.\n\nLemma unfold_exp_ic :\n  forall (x n : nat),\n    exp x (S n) = mult x (exp x n).\nProof.\n  unfold_tactic exp.\nQed.\n\n\nDefinition specification_of_the_mystery_function_7 (f : nat -> nat) :=\n  (f 0 = 1)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = 2 * f i * f j).\n\nProposition there_is_only_one_mystery_function_7 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_7 f ->\n    specification_of_the_mystery_function_7 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_7.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n   \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n\n    rewrite <- (plus_0_l (S n')).\n    rewrite <- (plus_n_Sm 0 n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (IHn').\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\nQed.\n\n\n\nLemma exp_is_distributive :\n  forall (x n m : nat),\n    mult (exp x n) (exp x m) = exp x (n+m).\nProof.\n  intros x n m.\n  induction n as [ | n' IHn'].\n  \n  (*Base case: *)\n\n    rewrite -> (unfold_exp_bc).\n    rewrite -> (plus_0_l m).\n    rewrite -> (mult_1_l).\n    reflexivity.\n\n  (* Inductive case: *)\n\n    rewrite -> (unfold_exp_ic).\n    rewrite -> (plus_1_S).\n    rewrite <- (plus_assoc 1 n' m).\n    rewrite <- (plus_1_S (n' +m)).\n    rewrite -> (unfold_exp_ic).\n    rewrite <- (IHn').\n    rewrite -> (mult_assoc x (exp x n') (exp x m)).\n    reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_7_is_power_of_2 :\n  specification_of_the_mystery_function_7 (exp 2).\nProof.\n  unfold specification_of_the_mystery_function_7.\n  split.\n  \n    rewrite -> (unfold_exp_bc).\n    reflexivity.\n\n    intros i j.\n    rewrite -> (unfold_exp_ic).\n    rewrite <- (mult_assoc 2 (exp 2 i) (exp 2 j)).\n    rewrite -> (exp_is_distributive).\n    reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_power_8 (f : nat -> nat) :=\n  (f 0 = 2)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = f i * f j).\n\n\nProposition there_is_only_one_mystery_function_power_8 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_power_8 f ->\n    specification_of_the_mystery_function_power_8 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_power_8.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n   \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n    \n    rewrite <- (plus_0_l (S n')).\n    rewrite <- (plus_n_Sm 0 n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_8_is_mult_2_power_of_2 :\n  specification_of_the_mystery_function_power_8 (fun x => mult 2 (exp 2 x)).\nProof.\n  unfold specification_of_the_mystery_function_power_8.\n  split.\n  \n    rewrite -> (unfold_exp_bc).\n    rewrite -> (mult_1_r).\n    reflexivity.\n\n\n    intros i j.\n    rewrite -> (unfold_exp_ic).\n    rewrite -> (mult_assoc 2 2 (exp 2 (i + j))).\n    rewrite <- (exp_is_distributive).\n    rewrite -> (mult_assoc).\n    rewrite -> (mult_assoc).\n    rewrite -> (mult_comm (2 * 2) (exp 2 i)).\n    rewrite -> (mult_comm 2 (exp 2 i)).\n    rewrite -> (mult_assoc).\n    reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_9 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (f 1 = 1)\n  /\\\n  (f 2 = 1)\n  /\\\n  (forall p q : nat,\n    f (S (p + q)) = f (S p) * f (S q) + f p * f q).\n\nProposition there_is_only_one_mystery_function_9 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_9 f ->\n    specification_of_the_mystery_function_9 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_9.\n  intros [H_f_bc0 [H_f_bc1 [H_f_bc2 H_f_ic]]]\n         [H_g_bc0 [H_g_bc1 [H_g_bc2 H_g_ic]]].\n  intro n.\n  induction n as [ | | n' IH_n' IH_Sn'] using nat_ind2.\n  \n  (* Base case 1: *)\n    rewrite -> H_f_bc0.\n    rewrite -> H_g_bc0.\n    reflexivity.\n\n  (* Base case 2: *)\n    rewrite -> H_f_bc1.\n    rewrite -> H_g_bc1.\n    reflexivity.\n  \n  (* Inductive case: *)\n    rewrite -> (plus_1_S n').\n    rewrite -> (H_f_ic 1 n').\n    rewrite -> (H_g_ic 1 n').\n    rewrite -> IH_n'.\n    rewrite -> (H_f_bc2).\n    rewrite -> (H_g_bc2).\n    rewrite -> IH_Sn'.\n    rewrite -> (H_f_bc1).\n    rewrite -> (H_g_bc1).\n    reflexivity.\nQed.\n\n\nFixpoint fib_ds (n : nat) : nat :=\n  match n with\n    | 0 => 0\n    | S n' => match n' with\n                | 0 => 1\n                | S n'' => fib_ds n' + fib_ds n''\n              end\n  end.\n\nLemma unfold_fib_ds_base_case_0 :\n  fib_ds 0 = 0.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma unfold_fib_ds_base_case_1 :\n  fib_ds 1 = 1.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma shorthand_rewrite_with_fib : \n  forall a b c d : nat,\n    (a + b) * c + a* d = a*(c + d) + b*c.\nProof.\n  intros a b c d .\n  rewrite -> (mult_plus_distr_r).\n  rewrite <- (plus_assoc (a*c) (b*c) (a*d)).\n  rewrite -> (plus_comm (b*c) (a*d)).\n  rewrite -> (plus_assoc (a*c) (a*d) (b*c)).\n  Check(mult_plus_distr_l).\n  rewrite <- (mult_plus_distr_l a c d).\n  reflexivity.\nQed.\n\n\nLemma unfold_fib_ds_induction_case :\n  forall n'' : nat,\n    fib_ds (S (S n'')) = fib_ds (S n'') + fib_ds n''.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nTheorem and_the_mystery_function_9_is_fib :\n  specification_of_the_mystery_function_9 (fib_ds).\nProof.\n  unfold specification_of_the_mystery_function_9.\n  split.\n  \n    rewrite -> (unfold_fib_ds_base_case_0).\n    reflexivity.\n\n    split.\n\n      rewrite -> (unfold_fib_ds_base_case_1).\n      reflexivity.\n\n      split.\n\n        rewrite -> (unfold_fib_ds_induction_case).\n        rewrite -> (unfold_fib_ds_base_case_1).\n        rewrite -> (unfold_fib_ds_base_case_0).\n        rewrite -> (plus_0_r).\n        reflexivity.\n\n        intros p q.\n        revert p. (* To strengthen my hypothesis *)\n        induction q as [ | q' IHq'].\n        \n        (* Base case *)\n          intro p.\n          rewrite -> (plus_0_r).\n          rewrite -> (unfold_fib_ds_base_case_0).\n          rewrite -> (unfold_fib_ds_base_case_1).\n          rewrite -> (mult_0_r).\n          rewrite -> (mult_1_r).\n          rewrite -> (plus_0_r).\n          reflexivity.\n\n        (* Inductive case: *)\n        \n          intro p.\n          rewrite -> (plus_1_S q') at 1.\n          rewrite -> (plus_assoc p 1 q').\n          rewrite <- (plus_S_1 p).\n          rewrite -> (IHq' (S p)).\n          rewrite ->2 (unfold_fib_ds_induction_case).\n          rewrite -> (shorthand_rewrite_with_fib (fib_ds (S p)) (fib_ds p) (fib_ds (S q')) (fib_ds q')).\n          reflexivity.\nQed.\n\n(* ********** *)\n\n\nRequire Import Bool.\n\nDefinition specification_of_the_mystery_function_power_10 (f : nat -> bool) :=\n  (f 0 = true)\n  /\\\n  (f 1 = false)\n  /\\\n  (forall i j : nat,\n     f (i + j) = eqb (f i) (f j)).\n\nProposition there_is_only_one_mystery_function_power_10 :\n  forall f g : nat -> bool,\n    specification_of_the_mystery_function_power_10 f ->\n    specification_of_the_mystery_function_power_10 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_power_10.\n  intros [H_f_bc0 [H_f_bc1 H_f_ic]].\n  intros [H_g_bc0 [H_g_bc1 H_g_ic]].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case. *)\n    rewrite -> (H_f_bc0).\n    rewrite -> (H_g_bc0).\n    reflexivity.\n\n  (* Inductive case: *)\n    rewrite -> (plus_1_S n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_f_bc1).\n    rewrite -> (IHn').\n    rewrite -> (H_g_ic).\n    rewrite -> (H_g_bc1).\n    reflexivity.\nQed.\n\n\nFixpoint evenp (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | S 0 => false\n    | S (S n'') => evenp n''\n  end.\n\n\nLemma unfold_evenp_bc0 :\n  evenp 0 = true.\nProof.\n  unfold_tactic evenp.\nQed.\n\nLemma unfold_evenp_bc1 :\n  evenp 1 = false.\nProof.\n  unfold_tactic evenp.\nQed.\n\nLemma unfold_evenp_ic :\n  forall n'' : nat,\n    evenp (S (S n'')) = evenp n''.\nProof.\n  unfold_tactic evenp.\nQed.\n\n\nLemma about_mystery_evenp_v2 :\n    forall x : nat,\n      evenp (S x) = negb (evenp x).\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n\n  rewrite -> (unfold_evenp_bc0).\n  rewrite -> (unfold_evenp_bc1).\n  unfold negb.\n  reflexivity.\n  \n  rewrite -> (unfold_evenp_ic).\n  rewrite -> (IHx').\n  rewrite -> (negb_involutive).\n  reflexivity.\nQed.\n\n\nLemma eqb_if_both_even_or_odd : \n  forall x y : nat, \n    eqb (evenp x) (evenp y) = eqb (evenp (S x)) (evenp (S y)).\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n\n  (* Base case: *)\n  \n    intros [ | y'].\n      rewrite -> (unfold_evenp_bc0).\n      rewrite -> (unfold_evenp_bc1).\n      unfold eqb.\n      reflexivity.\n\n    rewrite -> (unfold_evenp_bc1).\n    rewrite -> (unfold_evenp_bc0).\n    rewrite -> (unfold_evenp_ic).\n    rewrite -> (about_mystery_evenp_v2 y').\n    destruct (evenp y') eqn:H_y.\n      unfold negb.\n      unfold eqb.\n      reflexivity.\n\n    unfold negb.\n    unfold eqb.\n    reflexivity.\n\n  (* Inductive case: *)\n\n    rewrite -> (unfold_evenp_ic).\n    rewrite -> (about_mystery_evenp_v2).\n    intros [ | y'].\n\n      rewrite -> (unfold_evenp_bc0).\n      rewrite -> (IHx' 1).\n      rewrite -> (unfold_evenp_ic).\n      rewrite -> (unfold_evenp_bc0).\n      rewrite -> (about_mystery_evenp_v2).\n      reflexivity.\n    \n    rewrite <- (about_mystery_evenp_v2).\n    rewrite <- (IHx' y').\n    rewrite -> (unfold_evenp_ic).\n    reflexivity.\nQed.\n\n\n\n\nTheorem fun_theorem_about_evenp : \n  forall x y : nat,\n    evenp (x + y) = eqb (evenp x) (evenp y).\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n  \n  (* Base case: *)\n  \n  intro y.\n  rewrite -> (plus_0_l).\n  rewrite -> (unfold_evenp_bc0).\n  unfold eqb.\n  destruct (evenp y) eqn:H_y.\n    reflexivity.\n  reflexivity.\n  \n  intros [ | y'].\n  rewrite -> (unfold_evenp_bc0).\n  rewrite -> (plus_0_r).\n  unfold eqb.\n  destruct (evenp (S x')) eqn:H_Sx'.\n    reflexivity.\n  reflexivity.\n  rewrite -> (plus_S_1 x').\n  rewrite <- (plus_assoc x' 1 (S y')).\n  rewrite <- (plus_1_S (S y')).\n  rewrite (IHx' (S (S y'))).\n  rewrite <- (plus_S_1 x').\n  rewrite -> (unfold_evenp_ic).\n  rewrite -> (eqb_if_both_even_or_odd).\n  reflexivity.\nQed.\n\n\n\nTheorem and_the_mystery_function_10_is_is_evenp : \n  specification_of_the_mystery_function_power_10 evenp.\nProof.\n  unfold specification_of_the_mystery_function_power_10.\n  split.\n  rewrite -> (unfold_evenp_bc0).\n  reflexivity.\n  split.\n  rewrite -> (unfold_evenp_bc1).\n  reflexivity.\n  \n  apply (fun_theorem_about_evenp).\nQed.\n\n\n\n\nDefinition specification_of_the_mystery_function_11 (f : nat -> nat * nat) :=\n  (f 0 = (1, 0))\n  /\\\n  (forall n' : nat,\n    f (S n') = let (x, y) := f n'\n               in (x + y, x)).\n\nFixpoint fib_co_acc (n : nat) : nat * nat :=\n  match n with\n    | O => (1, 0)\n    | S n' => let (x, y) := fib_co_acc n'\n              in (x + y, x)\n  end.\n\nLemma unfold_fib_co_acc_base_case :\n  fib_co_acc 0 = (1, 0).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\nLemma unfold_fib_co_acc_induction_case :\n  forall n' : nat,\n    fib_co_acc (S n') = let (x, y) := fib_co_acc n'\n                        in (x + y, x).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\n\nProposition there_is_only_one_mystery_function_11 :\n  forall f g : nat -> nat * nat,\n    specification_of_the_mystery_function_11 f ->\n    specification_of_the_mystery_function_11 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_11.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n    \n  (* Inductive case: *)\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (IHn').\n    reflexivity.\nQed.    \n\nTheorem and_the_mystery_function_11_is_power_fibonacci_accumulator :\n  specification_of_the_mystery_function_11 fib_co_acc.\nProof.\n  unfold specification_of_the_mystery_function_11.\n  split.\n    rewrite -> (unfold_fib_co_acc_base_case).\n    reflexivity.\n\n    intro n'.\n    rewrite -> (unfold_fib_co_acc_induction_case).\n    reflexivity.\nQed.\n\n(* ********** *)\n\nFixpoint fac_co_acc (n : nat) : nat * nat :=\n  match n with\n    | 0 => (0, 1)\n    | S n' => let (x,y) := fac_co_acc n'\n              in (S x, y * S x)\nend.\n\nCompute fac_co_acc 3.\n\n Fixpoint split (A : Type) (ls : list A) : list A * list A :=\n    match ls with\n      | nil => (nil, nil)\n      | h :: nil => (h :: nil, nil)\n      | h1 :: h2 :: ls' =>\n        let (ls1, ls2) := split A ls' in\n          (h1 :: ls1, h2 :: ls2)\n    end.\n\nCheck split.\nCompute split nat (1 :: 2 :: 3 :: 4 :: nil).\n\nFixpoint fac (x : nat) :=\n  match x with\n    | 0 => 1\n    | S x' => mult (S x') (fac x')\n  end.\n         \n\nDefinition fac_co_help (x : nat) : nat * nat :=\n  (x, fac x).\n\n\n\nDefinition specification_of_the_mystery_function_12 (f : nat -> nat * nat) :=\n  (f 0 = (0, 1))\n  /\\\n  (forall n' : nat,\n    f (S n') = let (x, y) := f n'\n               in (S x, y * S x)).\n\nProposition there_is_only_one_mystery_function_12 :\n  forall f g : nat -> nat * nat,\n    specification_of_the_mystery_function_12 f ->\n    specification_of_the_mystery_function_12 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_12.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  \n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n  \n  (* Inductive case: *)\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\n\nLemma unfold_fac_co_acc_base_case :\n  fac_co_acc 0 = (0, 1).\nProof.\n  unfold_tactic fac_co_acc.\nQed.\n\nLemma unfold_fac_co_acc_induction_case :\n  forall n' : nat,\n    fac_co_acc (S n') = let (x, y) := fac_co_acc n'\n                        in (S x, y * S x).\nProof.\n  unfold_tactic fac_co_acc.\nQed.\n\nLemma unfold_fac_co_help_base_case :\n  fac_co_help 0 = (0,1).\nProof.\n  unfold_tactic fac_co_help.\nQed.\n\nLemma unfold_fac_co_help_induction_case : \n  forall n' : nat,\n    fac_co_help (S n') = (S n', (S n') * fac n').\nProof.\n  unfold_tactic fac_co_help.\nQed.\n\n\nTheorem and_the_mystery_function_12_is_tuple_index_and_factorial :\n  specification_of_the_mystery_function_12 fac_co_acc.\nProof.\n  unfold specification_of_the_mystery_function_12.\n  split.\n    rewrite -> (unfold_fac_co_acc_base_case).\n    reflexivity.\n\n    intro n'.\n    rewrite -> (unfold_fac_co_acc_induction_case).\n    reflexivity.\nQed.\n\nTheorem we_could_also_call_it_fac_co_help : \n  specification_of_the_mystery_function_12 fac_co_help.\nProof.\n  unfold specification_of_the_mystery_function_12.\n  split.\n    rewrite -> (unfold_fac_co_help_base_case).\n    reflexivity.\n\n    intro n'.\n    rewrite -> (unfold_fac_co_help_induction_case).\n    unfold fac_co_help.\n    rewrite -> (mult_comm).\n    reflexivity.\nQed.\n\n(* end of week_38c_mystery_functions.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/week_38c_mystery_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7379556570060147}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus y (mult (Succ y) x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj256_coqofml_mq1U9l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7378641194798568}}
{"text": "(**************************************************************************)\n(*  This is part of ATBR, it is distributed under the terms of the        *)\n(*         GNU Lesser General Public License version 3                    *)\n(*              (see file LICENSE for more details)                       *)\n(*                                                                        *)\n(*       Copyright 2009-2011: Thomas Braibant, Damien Pous.               *)\n(**************************************************************************)\n\n(** Properties of matrices over a semiring (in particular, they form a semiring)  *)\n\nRequire Import Common.\nRequire Import Classes.\nRequire Import Graph.\nRequire Import Monoid.\nRequire Import SemiLattice.\nRequire Import SemiRing.\nRequire Import MxGraph.\nRequire Import MxSemiLattice.\nRequire Import BoolView.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nTransparent equal.\n\nSection Defs.\n\n  Context `{ISR: IdemSemiRing}.\n  Variable A: T.\n  Notation MX n m := (MX_ A n m).\n  Notation mx_equal n m := (mx_equal_ A n m) (only parsing).\n\n  Definition mx_dot n m p (M: MX n m) (N: MX m p): MX n p := \n    box n p (fun i j => sum 0 m (fun k => !M i k * !N k j)).\n  Definition mx_one n: MX n n := \n    box n n (fun i j => if eq_nat_bool i j then 1 else 0).\n\n  Global Instance mx_Monoid_Ops: Monoid_Ops (mx_Graph A) := {\n    dot := mx_dot;\n    one := mx_one }.\n\n  Definition mx_bool n m (f: nat -> nat -> bool): MX n m :=\n    box n m (fun i j => xif (f i j) 1 0).\n\n  Lemma mx_dot_assoc n m p o (M: MX n m) (N: MX m p) (P: MX p o): M*(N*P) == (M*N)*P.\n  Proof.\n    intros i j Hi Hj. simpl.\n    transitivity (sum 0 m (fun k => sum 0 p (fun k' => !M i k * !N k k' * !P k' j))).\n     apply sum_compat; intros. \n     rewrite sum_distr_right; auto with algebra.\n\n     rewrite sum_inversion.\n     apply sum_compat; intros. \n     rewrite sum_distr_left; auto with algebra.\n  Qed.\n\n  Lemma mx_dot_neutral_left n m (M: MX n m): 1 * M == M.\n  Proof.\n    intros i j Hi Hj. simpl.\n    rewrite (sum_cut_nth i)  by auto with arith; simpl.\n    transitivity (0 + !M i j + 0); [|semiring_reflexivity].\n    repeat apply plus_compat; try (apply sum_zero; intros);\n      nat_analyse; semiring_reflexivity.\n  Qed.\n  \n  Lemma mx_dot_neutral_right n m (M: MX m n): M * 1 == M.\n  Proof.\n    intros i j Hi Hj. simpl. \n    rewrite (sum_cut_nth j) by auto with arith; simpl.\n    transitivity (0 + !M i j + 0); [|semiring_reflexivity].\n    repeat apply plus_compat; try (apply sum_zero; intros); \n      nat_analyse; semiring_reflexivity.\n  Qed.\n  \n  Global Program Instance mx_Monoid: Monoid (mx_Graph A) := {\n    dot_assoc := mx_dot_assoc;\n    dot_neutral_left := mx_dot_neutral_left;\n    dot_neutral_right := mx_dot_neutral_right\n  }. \n  Obligation 1. repeat intro. simpl. auto with compat. Qed.\n  \n  Global Instance mx_SemiRing: IdemSemiRing (mx_Graph A).\n  Proof.\n    constructor; repeat intro; simpl.\n    exact mx_Monoid.\n    apply mx_SemiLattice.\n    apply sum_zero; auto with algebra. \n    apply sum_zero; auto with algebra. \n    rewrite <- sum_cut_fun; auto with algebra.\n    rewrite <- sum_cut_fun; auto with algebra.\n  Qed.\n\nEnd Defs.\n\nNotation mx_dot_ A := (@dot (mx_Graph A) (mx_Monoid_Ops A)) (only parsing).\nNotation mx_one_ A := (@one (mx_Graph A) (mx_Monoid_Ops A)) (only parsing).\n\n(*begintests\nSection tac_tests.\n  Context `{ISR: IdemSemiRing}.\n  Variable A: T.\n  Notation MX n m := (MX_ A n m).\n  Variable x y z: X A A.\n  Variables n m p: nat.\n  Variables M N P : MX n m.\n  Variables Q R : MX m p.\n\n  Goal x*(z+y+z) == x*z+x*y.\n    semiring_reflexivity.\n  Qed.\n\n  Goal x*(z+y+z) <== x*z+x*y.\n    semiring_reflexivity.\n  Qed.\n\n  Goal x+y == z -> y+z+x == z.\n    intro H.\n    ac_rewrite H.\n    apply plus_idem.\n  Qed.\n\n  Goal M+(N+M*1) == N+M.\n    semiring_reflexivity.\n  Qed.\n\n  Goal M*Q+(N+M*1)*Q <== (N+M)*Q.\n    semiring_reflexivity. \n  Qed.\n\n  Goal N+M == P -> N+P+M == P.\n    intro H.\n    ac_rewrite H.\n    apply plus_idem. \n  Qed.\n\n  Goal M*0 == N*Q.\n    rewrite dot_ann_right.\n  Abort.\n\n  Goal M*0+0*N == 0+0.\n    autorewrite with simpl.\n    reflexivity.\n  Qed.\n\nEnd tac_tests.\nendtests*)\n\nSection Props1.\n\n  Context `{M: Monoid}.\n  Variable A: T.\n  Notation MX n m := (MX_ A n m).\n  Notation mx_equal n m := (mx_equal_ A n m) (only parsing).\n\n  Definition dot_scal_right n m (M: MX n m) (v: X A A): MX n m := \n    box n m (fun i j => !M i j * v).\n\n  Definition dot_scal_left n m (v: X A A) (M: MX n m): MX n m := \n    box n m (fun i j => v * !M i j).\n\n  Global Instance dot_scal_right_compat n m:\n  Proper (mx_equal n m ==> equal A A  ==> mx_equal n m) (@dot_scal_right n m).\n  Proof. repeat intro. simpl. auto with compat. Qed.\n  \n  Global Instance dot_scal_left_compat n m:\n  Proper (equal A A ==> mx_equal n m ==> mx_equal n m) (@dot_scal_left n m).\n  Proof. repeat intro. simpl. auto with compat. Qed.\n\nEnd Props1.\n\nInfix \"'*\" := dot_scal_left (at level 40): A_scope.\nInfix \"*'\" := dot_scal_right (at level 40): A_scope.\n\n\n\nGlobal Hint Extern 2 (mx_equal_ _ _ _ _ _) => apply dot_scal_left_compat: compat algebra.\nGlobal Hint Extern 2 (mx_equal_ _ _ _ _ _) => apply dot_scal_right_compat: compat algebra.\n\nSection Props2.\n\n  Context `{ISR: IdemSemiRing}.\n  Variable A: T.\n  Notation MX n m := (MX_ A n m).\n  Notation mx_equal n m := (mx_equal_ A n m) (only parsing).\n\n  Lemma mx_blocks_dot n m n' m' p p': forall\n    (a : MX n  m )\n    (b : MX n  m')\n    (c : MX n' m )\n    (d : MX n' m')\n    (a': MX m  p )\n    (b': MX m  p')\n    (c': MX m' p )\n    (d': MX m' p'),\n    mx_blocks a  b  c  d * mx_blocks a' b' c' d'\n    == mx_blocks  \n    (a * a' + b * c')  \n    (a * b' + b * d')\n    (c * a' + d * c') \n    (c * b' + d * d').\n  Proof.\n    simpl. intros. destruct_blocks.\n  \n    rewrite (plus_comm m), sum_cut. \n    apply plus_compat.\n    apply sum_compat; intros. \n    destruct_blocks. reflexivity. lia_false.\n    rewrite (plus_comm m), sum_shift. \n    apply sum_compat; intros.\n    destruct_blocks. reflexivity.\n\n    rewrite (plus_comm m), sum_cut. \n    apply plus_compat.\n    apply sum_compat; intros. \n    destruct_blocks. reflexivity. lia_false.\n    rewrite (plus_comm m), sum_shift. \n    apply sum_compat; intros.\n    destruct_blocks. reflexivity.\n\n    rewrite (plus_comm m), sum_cut. \n    apply plus_compat.\n    apply sum_compat; intros. \n    destruct_blocks. reflexivity. lia_false.\n    rewrite (plus_comm m), sum_shift. \n    apply sum_compat; intros.\n    destruct_blocks. reflexivity.\n\n    rewrite (plus_comm m), sum_cut. \n    apply plus_compat.\n    apply sum_compat; intros. \n    destruct_blocks. reflexivity. lia_false.\n    rewrite (plus_comm m), sum_shift. \n    apply sum_compat; intros.\n    destruct_blocks. reflexivity.\n  Qed.\n\n  Lemma mx_blocks_one x n : \n    1 == @mx_blocks _ A x x n n 1 0 0 1.\n  Proof.  \n    simpl. intros. destruct_blocks; nat_analyse; reflexivity.\n  Qed.\n\n  Lemma dot_scal_left_is_dot n (M: MX 1 n) x:\n    x '* M == mx_of_scal x * M.\n  Proof.\n    mx_intros i j Hi Hj.  simpl. auto with algebra. \n  Qed.\n\n  Lemma dot_scal_left_one n m (M: MX n m): 1 '* M == M.\n  Proof. \n    repeat intro; simpl. trivial with algebra. \n  Qed.\n\n  Lemma dot_scal_left_zero n m x: x '* (0: MX n m) == 0.\n    repeat intro; simpl. trivial with algebra. \n  Qed.\n\n  Lemma dot_scal_left_dot n m p (M: MX n m) (P: MX m p) x:\n    (x '* M) * P == x '* (M * P).\n  Proof.\n    repeat intro; simpl.\n    rewrite sum_distr_right. apply sum_compat. intros. auto with algebra. \n  Qed.\n\n  Lemma dot_scal_left_blocks n m p q \n    (N: MX n p) \n    (M: MX n q)\n    (P: MX m p) \n    (Q: MX m q) x:\n    x '* mx_blocks N M P Q\n    == mx_blocks (x '* N) (x '* M) (x '* P) (x '* Q).\n  Proof.\n    repeat intro; simpl. destruct_blocks; reflexivity. \n  Qed.\n\n  Lemma dot_scal_right_is_dot n x (M: MX 1 n):\n    x '* M == mx_of_scal x * M.\n  Proof.\n    mx_intros i j Hi Hj.  simpl. auto with algebra. \n  Qed.\n  \n  Lemma dot_scal_right_one n m (M: MX n m): M *' 1 == M.\n  Proof. \n    repeat intro; simpl. trivial with algebra. \n  Qed.\n\n  Lemma dot_scal_right_zero n m x: (0: MX n m) *' x == 0.\n    repeat intro; simpl. trivial with algebra. \n  Qed.\n\n  Lemma dot_scal_right_dot n m p (M: MX n m) (P: MX m p) x:\n    M * (P *' x) == (M * P) *' x.\n  Proof.\n    repeat intro; simpl.\n    rewrite sum_distr_left. apply sum_compat. intros. auto with algebra. \n  Qed.\n\n  Lemma dot_scal_right_blocks n m p q \n    (N: MX n p) \n    (M: MX n q)\n    (P: MX m p) \n    (Q: MX m q) x:\n    mx_blocks N M P Q *' x\n    == mx_blocks (N *' x) (M *' x) (P *' x) (Q *' x).\n  Proof.\n    simpl. intros. destruct_blocks; reflexivity. \n  Qed.\n\n  Lemma mx_of_scal_dot: forall a b: X A A, \n                        mx_of_scal a * mx_of_scal b == mx_of_scal (a*b).\n  Proof. \n    repeat intro; simpl. trivial with algebra. \n  Qed.\n  \n  Lemma mx_of_scal_one: 1 == mx_of_scal (one A).\n  Proof.\n    intros; mx_intros i j Hi Hj. reflexivity.\n  Qed.\n\n  Lemma mx_to_scal_dot: forall a b: MX 1 1,\n                        mx_to_scal a * mx_to_scal b == mx_to_scal (a*b).\n  Proof.\n    unfold mx_to_scal. \n    simpl. intros. auto with algebra. \n  Qed.\n  \n  Lemma mx_to_scal_one: one A == mx_to_scal 1.\n  Proof. reflexivity. Qed.\n  \n\n  Lemma mx_point_dot n m o i j k: forall a b: X A A, j < m ->\n    mx_point n m i j a * mx_point m o j k b == mx_point n o i k (a*b).\n  Proof.\n    repeat intro; simpl.\n    rewrite (sum_cut_nth j) by assumption.\n    rewrite 2sum_zero; intros.\n     nat_analyse; simpl; semiring_reflexivity.\n     nat_analyse; simpl; trivial with algebra.\n     nat_analyse; simpl; trivial with algebra.\n  Qed.\n\n  Lemma mx_point_dot_zero n m o i j j' k: forall a b: X A A, j<>j' ->\n    mx_point n m i j a * mx_point m o j' k b == 0.\n  Proof.\n    repeat intro; simpl.\n    apply sum_zero. intros.\n    nat_analyse; simpl; trivial with algebra.\n  Qed.\n\n  Lemma mx_point_one_left n m p i j: forall M: MX m p, j < m -> \n    mx_point n m i j 1 * M == box n p (fun s t =>  xif (eq_nat_bool i s) (!M j t) 0).\n  Proof.\n    intros.\n    unfold mx_point.\n    mx_intros s t Hs Ht. simpl. \n    rewrite (sum_cut_nth j) by auto.\n    rewrite 2 sum_zero; intros; nat_analyse; simpl; semiring_reflexivity.  \n  Qed.\n\n  Lemma mx_point_center n m p q i j (M: MX n m) (N: MX p q): \n    i < m -> j < p -> \n    M * mx_point m p i j 1 * N == box n q (fun s t => !M s i * !N j t).\n  Proof.\n    intros Hi Hj x y Hx Hy. simpl.\n    setoid_rewrite sum_distr_left.\n\n    rewrite (sum_cut_nth j);auto. \n    rewrite sum_zero.\n    rewrite (sum_cut_nth i). \n    \n    setoid_rewrite sum_zero; intros; simpl; nat_analyse; simpl; try semiring_reflexivity.\n    rewrite sum_zero. reflexivity.\n    intros. bool_simpl; simpl. semiring_reflexivity.\n    auto.\n    intros. rewrite sum_zero. reflexivity.\n    intros. nat_analyse; simpl; semiring_reflexivity.\n  Qed.\n    \n\nEnd Props2.\n", "meta": {"author": "coq-community", "repo": "atbr", "sha": "6f752796dd5bf2d7af1ee085ece65138c0561ab9", "save_path": "github-repos/coq/coq-community-atbr", "path": "github-repos/coq/coq-community-atbr/atbr-6f752796dd5bf2d7af1ee085ece65138c0561ab9/theories/MxSemiRing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7377732249721234}}
{"text": "Require Import HoTT.\n\n(*Strangely, I cannot find any proofs of nat being associative*)\nLocal Open Scope nat_scope.\nDefinition plus_assoc : forall j k l : nat, (j + k) + l = j + (k + l). \n  intros j k l.\n  induction j.\n  - exact idpath.\n  - exact (ap S IHj).\nDefined.\n\n\n(*Cancellation in nat*)\nOpen Scope nat_scope.\n(* Subtraction of natural numbers. *)\n  (* Is given by [m,n => -m + n] *)\n(* This is the same as the already defined [minus], but the below lemma is much easier to prove *)\nFixpoint nat_minus (m n : nat) : nat :=\n  match m with\n      |0 => n (*-0 + m := m*)\n      |m.+1 => match n with\n                  |0 => 0 (*-(m+1)+0 = 0*)\n                  |n.+1 => nat_minus m n (*- m+1 + n+1= -m + n*)\n              end\n  end.\n\n(* Just to show that this is the same as the old minus. *)\nLemma nat_minus_is_minus (m n : nat) : nat_minus m n = minus n m.\nProof.\n  revert n.\n  induction m.\n  - induction n; reflexivity.\n  - induction n.\n    + reflexivity.\n    + simpl. apply IHm.\nDefined.\n\nDefinition nat_plus_minus (m n : nat) : nat_minus m (m + n) = n.\nProof.\n  induction m. \n  - reflexivity.\n  - exact IHm.\nDefined.\n\nDefinition nat_plus_cancelL (l m n : nat) : l + m = l + n -> m = n.\nProof.\n  intro p.\n  refine ((nat_plus_minus l m)^ @ _ @ nat_plus_minus l n).\n  apply (ap (nat_minus l) p).\nDefined.\n\n(* Definition not_leq_is_gt (i j : nat) : not (i <= j) <~> i > j. *)\n(* Proof. *)\n(*   unfold not. unfold leq. unfold gt. *)\n(*   simpl. *)\n(*   induction i. simpl. *)\n\n(* Definition split_nat (i : nat) : *)\n(*   nat <~> {j : nat & j <= i} + {j : nat & j > i}. *)\n(* Proof. *)\n(*   srapply @equiv_adjointify. *)\n(*   - intro k. induction k. *)\n(*     (* k = 0 *) *)\n(*     + apply inl. *)\n(*       exists 0. *)\n(*       apply leq0n. *)\n(*     (* k+1 *) *)\n(*     +  *)\n\nClose Scope nat_scope.\n\n(* Comparing not_leq to gt *)\nSection Inequalities.\n  Local Open Scope nat.\n  (* For two natural numbers, one is either less than or equal the other, or it is greater. *)\n  Definition leq_or_gt (i j : nat) : (i <= j) + (i > j).\n  Proof.\n    revert j. induction i; intro j.\n    (* 0 <= j *)\n    - exact (inl tt).\n    - destruct j.\n      (* 0 < i+1 *)\n      + exact (inr tt).\n      (* (i < j+1) + (j.+1 < i + 1) <-> (i <= j) + (j < i) *)\n      + apply IHi.\n  Defined.\n \n\n  Definition leq_succ (n : nat) : n <= n.+1.\n  Proof.\n    induction n.\n    - reflexivity.\n    - apply IHn.\n  Defined.\n\n  (* Lemma leq_refl_code (i j : nat) : i =n j -> i <= j. *)\n  (* Proof. *)\n  (*   intro H. *)\n  (*   destruct (path_nat H). apply leq_refl. *)\n  (* Qed. *)\n  \n  Definition neq_succ (n : nat) : not (n =n n.+1).\n  Proof.\n    induction n.\n    - exact idmap.\n    - exact IHn.\n  Defined.\n\n  Definition leq0 {n : nat} : n <= 0 -> n =n 0.\n  Proof.\n    induction n; exact idmap.\n  Defined.\n\n  (* if both i<=j and j<=i, then they are equal *)\n  Definition leq_geq_to_eq (i j : nat) : (i <= j) -> (j <= i) -> i =n j.\n  Proof.\n    revert i.\n    induction j; intros i i_leq_j j_leq_i.\n    - exact (leq0 i_leq_j).\n    - destruct i.\n      + intros. destruct j_leq_i.\n      + simpl. intros.\n        apply (IHj _ i_leq_j j_leq_i).\n  Defined.\n\n  (* If i <= n, then i < n or i = n+1 *)\n  Definition lt_or_eq (i n : nat) : i <= n -> (i < n) + (i = n).\n  Proof.\n    intro i_leq_n.\n    destruct (leq_or_gt n i) as [n_leq_i | n_gt_i].\n    - apply inr. apply path_nat. exact (leq_geq_to_eq _  _ i_leq_n n_leq_i).\n    - exact (inl n_gt_i).\n  Defined.\n\n  Definition lt_or_eq_or_gt (i n : nat) :\n    (i < n) + (i = n) + (i > n).\n  Proof.\n    destruct (leq_or_gt i n) as [leq | gt].\n    - apply inl. apply (lt_or_eq i n leq).\n    - exact (inr gt).\n  Defined.\n    \n\n  (* Definition leq_to_lt_plus_eq (i j : nat) : i <= j -> (i < j) + (i = j). *)\n  (* Proof. *)\n  (*   intro i_leq_j. *)\n  (*   destruct (dec (i = j)). *)\n  (*   - exact (inr p). *)\n  (*   - apply inl. *)\n  (*     induction j. *)\n  (*     + simpl. rewrite (path_nat (leq0 i i_leq_j)) in n. apply n. reflexivity. *)\n  (*     + destruct i. exact tt. *)\n  (*       srapply (@leq_transd i.+2 j j.+1). *)\n  (*       * apply IHj. *)\n  (*         admit. *)\n           \n        \n  (*       simpl. *)\n\n        \n  (*       i. *)\n  (*     + simpl. *)\n    \n  (*   destruct j. *)\n  (*   apply inr. apply path_nat. apply (leq0  i (i_leq_j)). *)\n  (*   destruct i. *)\n  (*   - simpl. *)\n    \n  (*   apply inl. change (i < j.+1) with (i <= j). *)\n  (*   apply (leq_transd *)\n    \n    \n\n  (* Definition nlt_n0 (n : nat) : ~(n < 0) := idmap. *)\n  \n  Definition gt_to_notleq (i j : nat) : j > i -> ~(j <= i).\n  Proof.\n    intro i_lt_j.\n    intro j_leq_i.\n    apply (neq_succ i).\n    apply (leq_antisymd (leq_succ i)).\n    apply (leq_transd i_lt_j j_leq_i).\n    (* set (Si_leq_i := leq_transd i_lt_j j_leq_i). *)\n    (* set (Si_eq_i := leq_antisymd (leq_succ i) Si_leq_i). *)\n    (* apply (neq_succ i Si_eq_i). *)\n    (* induction i. *)\n    (* exact Si_eq_i. *)\n  Defined.\n\n  Definition not_i_lt_i (i : nat) : ~(i < i).\n  Proof.\n    unfold not.\n    induction i.\n    - exact idmap.\n    - exact IHi.\n  Defined.\n  \n  (* Lemma notleq_to_gt (i j : nat) : ~(j <= i) -> j > i. *)\n  (* Proof. *)\n  (*   intro j_nleq_i. *)\n  (*   induction j. *)\n  (*   - apply j_nleq_i. *)\n  (*     apply leq0n. *)\n  (*   - change (i < j.+1) with (i <= j). *)\n  (*     destruct (dec (i =n j)). *)\n  (*     (* i = j *) *)\n  (*     + destruct (path_nat t). apply leq_refl. *)\n  (*     +  *)\n\n  (*     induction i. *)\n  (*     + exact tt. *)\n  (*     +  *)\n    \n  (*   induction i, j. *)\n  (*   - apply j_nleq_i. exact tt. *)\n  (*   - exact tt. *)\n  (*   - simpl. simpl in IHi. simpl in j_nleq_i. apply IHi. exact j_nleq_i. *)\n  (*   - change (i.+1 < j.+1) with (i < j). *)\n  (*     change (j < i.+1) with (j <= i) in j_nleq_i. *)\n  (*     change (i < j.+1) with (i <= j) in IHi. *)\n      \n    \n  (*   destruct (dec (~ (j <= i))). *)\n  (*   - set (f := j_nleq_i t). destruct f. *)\n  (*   -  *)\n  \n  (* If i <= j, then j is the sum of i and some natural number *)\n  Definition leq_to_sum {i j : nat} : i <= j -> {k : nat | j = i + k}%nat.\n  Proof.\n    revert j. induction i; intro j.\n    - intro. \n      exists j. reflexivity.\n    - destruct j.\n      + intros [].\n      + simpl. change (i < j.+1) with (i <= j).\n        intro i_leq_j.\n        apply (functor_sigma (A := nat) idmap (fun _ => ap S)).\n        apply (IHi j i_leq_j).\n        (* exists (IHi j i_leq_j).1. *)\n        (* apply (ap S). *)\n      (* apply (IHi j i_leq_j).2. *)\n  Defined.\n\n  (* If j > i, then j is a successor *)\n  Definition gt_is_succ {i j : nat} : i < j -> {k : nat | j = k.+1}.\n  Proof.\n    intro i_lt_j.\n    destruct (leq_to_sum i_lt_j) as [k H].\n    exact (i+k; H)%nat.\n  Defined.\n    \nEnd Inequalities.\n\n\n", "meta": {"author": "kalfsvag", "repo": "misc_coq", "sha": "9886ed4eb3dfc077afd1d769c910a729475fa173", "save_path": "github-repos/coq/kalfsvag-misc_coq", "path": "github-repos/coq/kalfsvag-misc_coq/misc_coq-9886ed4eb3dfc077afd1d769c910a729475fa173/basics/nat_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7377198500167744}}
{"text": "From LF Require Export basics.\n\nTheorem plus_n_O : forall n : nat,\n  n = n + 0.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite <- IHn.\n    reflexivity.\nQed.\n\nTheorem minus_n_n : forall n : nat,\n  minus n n = 0.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl.\n    apply IHn.\nQed.\n\nTheorem mult_0_r : forall n : nat,\n  n * 0 = 0.\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. apply IHn.\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  - 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  induction n.\n  - reflexivity.\n  - simpl. rewrite -> IHn. reflexivity.\nQed.\n\nFixpoint double (n : nat) : 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  induction n.\n  - reflexivity.\n  - simpl. rewrite -> IHn. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  induction n.\n  - 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  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  { rewrite -> plus_comm. reflexivity. }\n  rewrite -> H. 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. rewrite -> plus_assoc.\n  assert (H: n + m = m + n).\n  { apply plus_comm. }\n  rewrite -> H. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros m n.\n  induction m.\n  - rewrite <- mult_n_O. reflexivity.\n  - rewrite <- mult_n_Sm.\n    simpl. rewrite -> IHm. \n    rewrite -> plus_comm. reflexivity.\nQed.\n\nCheck leb.\n\nTheorem leb_refl : forall n : nat,\n  true = (n <=? n).\nProof.\n  intros n.\n  induction n.\n  - reflexivity.\n  - simpl. apply IHn.\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  destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  n <=? m = true ->\n  (p + n) <=? (p + m) = true.\nProof.\n  intros.\n  induction p.\n  - simpl. apply H.\n  - simpl. apply IHp.\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,\n  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  destruct b.\n  - simpl.\n    destruct c.\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  induction p.\n  - rewrite <- mult_n_O. rewrite <- mult_n_O. \n    rewrite <- mult_n_O. reflexivity.\n  - rewrite <- mult_n_Sm. rewrite <- mult_n_Sm.\n    rewrite <- mult_n_Sm. rewrite -> IHp.\n    rewrite -> plus_swap. rewrite <- plus_assoc.\n    rewrite -> plus_swap. 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. rewrite -> IHn. \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.\n  - reflexivity.\n  - apply IHn.\nQed.\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros.\n  rewrite -> plus_assoc. rewrite -> plus_assoc.\n  replace (n + m) with (m + n). reflexivity.\n  apply plus_comm.\nQed.\n\nTheorem succ_succ : forall n : nat,\n  S n + S n = S (S (n + n)).\nProof.\n  induction n.\n  - reflexivity.\n  - rewrite -> IHn.\n    simpl. rewrite <- plus_n_Sm. \n    rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nTheorem bin_to_nat_pres_incr : forall b : bin,\n  bin_to_nat (incr b) =  S (bin_to_nat b).\nProof.\n  intros.\n  induction b.\n  - reflexivity.\n  - reflexivity.\n  - simpl. rewrite -> IHb.\n    rewrite <- plus_n_O. rewrite <- plus_n_O.\n    rewrite -> succ_succ. reflexivity.\nQed.\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  induction n.\n  - reflexivity.\n  - simpl. rewrite -> bin_to_nat_pres_incr.\n    rewrite -> IHn. reflexivity.\nQed.\n\nDefinition double_bin (b : bin) : bin :=\n  match b with\n  | Z => Z\n  | _ => B0 b\n  end.\n\nFixpoint normalize (b : bin) : bin :=\n  match b with\n  | Z => Z\n  | B0 b' => double_bin (normalize b')\n  | B1 b' => incr (double_bin (normalize b'))\n  end.\n\nLemma double_inc : forall b : bin,\n  incr (incr (double_bin b)) = double_bin (incr b).\nProof.\n  destruct b.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma nat_to_bin_double : forall n : nat,\n  nat_to_bin (double n) = double_bin (nat_to_bin n).\nProof.\n  induction n.\n  - reflexivity.\n  - simpl. rewrite -> IHn.\n    rewrite -> double_inc. reflexivity.\nQed.\n\nTheorem bin_nat_bin : forall b : bin,\n  nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n  induction b.\n  - reflexivity.\n  - simpl. rewrite <- plus_n_O.\n    rewrite <- double_plus. rewrite -> nat_to_bin_double.\n    rewrite -> IHb. reflexivity.\n  - simpl. rewrite <- plus_n_O.\n    rewrite <- double_plus. rewrite -> nat_to_bin_double.\n    rewrite -> IHb. reflexivity.\nQed.\n", "meta": {"author": "maxjanney", "repo": "Coq-Files", "sha": "9c47b1674315c48f7d2e102570af09f0dfefb59b", "save_path": "github-repos/coq/maxjanney-Coq-Files", "path": "github-repos/coq/maxjanney-Coq-Files/Coq-Files-9c47b1674315c48f7d2e102570af09f0dfefb59b/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7377198469243653}}
{"text": "Require Import SetoidClass SetoidCat.\n\nInstance natS : Setoid nat :=\n  {\n    equiv := eq\n  }\n.\n\nDefinition plusS : natS ~> natS ~~> natS := injF2 plus _.\n\nDefinition minS := injF2 min _.\n\nLemma nat_int : forall n n' , n < S n' -> ~ n' < n.\nProof.\n  double induction n n'.\n  intros. intro. inversion H0.\n  intros. intro. inversion H0. inversion H1.\n  intros. intro. inversion H0. inversion H3.\n  intros. intro. apply H0 with (n':=n0). apply le_S_n. auto. apply le_S_n. auto.\nQed.\n\nOpen Scope nat_scope.\nLemma plus_symmetry : forall a b, a+b = b+a.\nProof.\n  induction a. intros. simpl. apply plus_n_O.\n  intros. simpl. rewrite <- plus_n_Sm. f_equal. apply IHa.\nQed.\n\nDefinition ltS : natS ~> natS ~~> iff_setoid := injF2 lt _.\n\n", "meta": {"author": "xu-hao", "repo": "CertifiedQueryArrow", "sha": "8db512e0ebea8011b0468d83c9066e4a94d8d1c4", "save_path": "github-repos/coq/xu-hao-CertifiedQueryArrow", "path": "github-repos/coq/xu-hao-CertifiedQueryArrow/CertifiedQueryArrow-8db512e0ebea8011b0468d83c9066e4a94d8d1c4/Algebra/SetoidCat/NatUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7376992705920764}}
{"text": "Require Import Omega.\n\nLemma size_induction X (f : X -> nat) (p : X -> Prop) :\n  (forall x, (forall y, f y < f x -> p y) -> p x) ->\n  forall x, p x.\n\nProof.\n  intros step x. apply step.\n  assert (G: forall n y, f y < n -> p y).\n  { intros n. induction n.\n    - intros y B. exfalso. omega.\n    - intros y B. apply step. intros z C. apply IHn. omega.\n  }\n  apply G.\nQed.\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/tutorial04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7376992652154037}}
{"text": "Section Integers.\n  Inductive Int : Set :=\n  | zero : Int\n  | succ : Int -> Int\n  | opp : Int -> Int.\n  \n  Declare Scope Int_scope.\n  Bind Scope Int_scope with Int.\n  Open Scope Int_scope.\n  Notation \"- n\" := (opp n) : Int_scope.\n  \n  Axiom opp_zero : opp zero = zero.\n\n  Axiom opp_opp : forall n, - - n = n.\n  \n  Lemma equiv_implies_equiv_succ : \n    forall (n m : Int), n=m -> (succ n) = (succ m).\n  Proof.\n    intros.\n    apply f_equal with (f:= fun t => succ t) in H.\n    apply H.\n  Qed.\n  \n  Lemma equiv_succ_implies_equiv : \n    forall (n m : Int), (succ n) = (succ m) -> n = m.\n  Proof.\n    intros. inversion H. reflexivity.\n  Qed.\n  \n  Fixpoint add (n m : Int) : Int :=\n  match n with\n  | zero => m\n  | succ n' => succ (add n' m)\n  | opp n' => - (add n' (- m))\n  end.\n  \n  Infix \"+\" := add (at level 50, left associativity) : Int_scope.\n  Notation \"n - m\" := (add n (opp m)) : Int_scope.\n  \n  Lemma add_zero_l : forall (n : Int), zero + n = n.\n  Proof.\n    trivial.\n  Qed.\n\n  Lemma add_zero_r : forall (n : Int), n + zero = n.\n  Proof.\n    intros. induction n; simpl.\n    - reflexivity.\n    - rewrite IHn. reflexivity.\n    - rewrite opp_zero. rewrite IHn. reflexivity.\n  Qed.\n  \n  Lemma opp_distr : forall (n m : Int), opp (n + m) = (opp n) + (opp m).\n  Proof.\n    intros. induction n; simpl; repeat rewrite opp_opp; try reflexivity.\n  Qed.\n  \n  Lemma add_succ_l : forall n m, succ n + m = succ (n + m).\n  Proof.\n    intros. simpl. reflexivity.\n  Qed.\n\n  Lemma add_succ_r : forall n m, n + succ m = succ (n + m).\n  Proof.\n    intros. induction m; simpl.\n    - rewrite add_zero_r.\n  Qed.\n\n  Theorem add_associativity : \n    forall (i j k : Int), i + (j + k) = (i + j) + k.\n  Proof.\n    intros. induction k; simpl.\n    - repeat rewrite add_zero_r. reflexivity.\n    - simpl.  \n    \n  \n  Theorem add_associativity : \n    forall (i j k : Int), i + (j + k) = (i + j) + k.\n  Proof.\n    intros. induction i.\n    simpl. reflexivity.\n    simpl. rewrite <- IHi. reflexivity.\n    simpl. rewrite <- IHi. reflexivity.\n    induction j. induction k.\n    all: repeat rewrite add_zero; simpl; try reflexivity.\n    repeat rewrite opp_distr, opp_opp. replace (succ (j + k)) with (succ j + k).\n    apply f_equal with (f := fun t => i + i + t).\n  Qed.\n  \n  Lemma add_succ_zero : forall (n : Int), succ n = n + succ zero.\n  Proof.\n    intro. induction n. trivial.\n    symmetry. apply f_equal with (f := fun t => succ t) in IHn as IH2. \n    simpl. rewrite <- IH2. reflexivity.\n    apply f_equal with (f := fun t => pred t) in IHn as IH2.\n    simpl. rewrite <- IH2. rewrite pred_succ_equiv. apply succ_pred_equiv.\n    rewrite <- opp_pred. rewrite <- opp_opp. rewrite opp_distr. rewrite opp_opp.\n    apply f_equal with (f := fun t => opp t). rewrite opp_succ. rewrite opp_zero.\n    replace (pred n) with (pred (n + zero)).\n    apply f_equal with (f := fun t => opp t) in IHn as IH2.\n    rewrite opp_distr, opp_succ, opp_succ, opp_zero in IH2.\n    replace (n + pred zero) with (n + n -n + pred zero).\n    rewrite <- IH2.\n    \n    \n  \n  Lemma add_succ : forall (n m : Int), succ (n + m) = n + (succ m).\n  Proof.\n    intros. induction n.\n    simpl. reflexivity.\n    simpl. rewrite <- IHn. reflexivity.\n    simpl. rewrite <- IHn. \n    rewrite succ_pred_equiv. rewrite pred_succ_equiv. reflexivity.\n    induction n. induction m. repeat rewrite add_zero in IHn.\n    all: \n    \n  Theorem add_commutativity : forall (n m : Int), n + m = m + n.\n  Proof.\n    intros.\n    induction n.\n    simpl. symmetry. apply add_zero.\n    simpl. rewrite IHn. apply add_succ.\n    simpl. rewrite IHn. apply add_pred.\n  Qed.\n  \n  Theorem add_closure : forall (n m : Int), exists (x : Int), n + m = x.\n  Proof.\n    intros. now exists (n + m).\n  Qed.\n    \n  Qed.\n  \n  Lemma add_pred : forall (n m : Int), pred (n + m) = n + (pred m).\n  Proof.\n    intros. induction n.\n    simpl. reflexivity.\n    simpl. rewrite <- IHn. \n    rewrite succ_pred_equiv. rewrite pred_succ_equiv. reflexivity.\n    simpl. rewrite <- IHn. reflexivity.\n  Qed.\n  \n  \n  Lemma equiv_implies_add_equiv :\n    forall (i j k : Int), i = j -> (i + k) = (j + k).\n  Proof.\n    intros. apply f_equal with (f := fun t => t + k). apply H.\n  Qed.\n  \n  Lemma add_equiv_implies_equiv : \n    forall (i j k : Int), (i + k) = (j + k) -> i = j.\n  Proof.\n    intros. induction k.\n    rewrite add_zero in H. apply H.\n    repeat rewrite <- add_succ in H. apply equiv_succ_implies_equiv in H.\n    apply IHk. apply H.\n    apply IHk. rewrite <- add_pred in H. \n    symmetry. rewrite <- add_pred in H.\n    apply f_equal with (f := fun t => succ t) in H.\n    rewrite succ_pred_equiv in H. \n    symmetry. rewrite succ_pred_equiv in H.\n    apply H.\n  Qed.\n  \n  Lemma add_permutes : forall (i j k : Int), i + j + k = j + k + i.\n  Proof.\n    intros.\n    rewrite <- add_commutativity. rewrite add_associativity.\n    symmetry. rewrite <- add_associativity. rewrite add_commutativity.\n    reflexivity.\n  Qed.\n  \n  Fixpoint subtract (n m : Int) : Int :=\n  match n, m with\n  | _, zero => n\n  | _, succ m' => pred (subtract n m')\n  | _, pred m' => succ (subtract n m')\n  end.\n  \n  Infix \"-\" := subtract (at level 50, left associativity).\n  \n  Theorem subtract_anticommutativity : forall (n m : Int), n - m = (zero - m) + n.\n  Proof.\n    intros. induction m. simpl. reflexivity.\n    simpl. symmetry. rewrite <- IHm. reflexivity.\n    simpl. symmetry. rewrite <- IHm. reflexivity.\n  Qed.\n  \n  Theorem add_negative : forall (n m : Int), n + (zero - m) = n - m.\n  Proof.\n    intros. induction m. simpl. apply add_zero.\n    simpl. rewrite <- IHm. rewrite add_pred. reflexivity.\n    simpl. rewrite <- IHm. rewrite add_succ. reflexivity.\n  Qed.\n  \n  Theorem subtract_add : forall (i j k : Int), i - (j + k) = (i - j) - k.\n  Proof.\n    intros. induction k. simpl. rewrite add_zero. reflexivity.\n    simpl. rewrite <- add_succ. simpl.\n    apply f_equal with (f := fun t => pred t). apply IHk.\n    simpl. rewrite <- add_pred. simpl.\n    apply f_equal with (f := fun t => succ t). apply IHk.\n  Qed.\n  \n  Theorem add_subtract : forall (i j k : Int), i + (j - k) = (i + j) - k.\n  Proof.\n    intros. induction i. simpl. reflexivity.\n    simpl. rewrite IHi. apply f_equal with (f := fun t => pred t). \n    \n  \n  Fixpoint sign (n : Int) : Int :=\n  match n with\n  | zero => zero\n  | pred zero => pred zero\n  |\n  \n  Fixpoint multiply (n m : Int) : Int :=\n  match n with\n  | zero => zero\n  | succ n' => (multiply n' m) + m \n  | pred n' => (multiply n' m) - m \n  end.\n  \n  Infix \"*\" := multiply (at level 40, left associativity).\n  \n  Lemma multiply_zero : forall (n : Nat), n * zero = zero.\n  Proof.\n    intros. induction n.\n    simpl. reflexivity.\n    simpl. apply IHn.\n  Qed.\n  \n  Lemma multiply_succ : forall (n m : Nat), n * (succ m) = n + n * m.\n  Proof.\n    intros. induction n.\n    simpl. reflexivity.\n    simpl. rewrite IHn. apply equiv_implies_equiv_succ.\n    repeat rewrite add_associativity. apply equiv_implies_add_equiv.\n    apply add_commutativity.\n  Qed.\n  \n  Lemma add_multiply : forall (i j k : Nat), i * (j + k) = i*j + i*k.\n  Proof.\n    intros. induction i.\n    simpl. reflexivity.\n    simpl. rewrite IHi. repeat rewrite add_associativity.\n    apply equiv_implies_add_equiv. rewrite add_permutes.\n    symmetry. rewrite add_permutes. apply equiv_implies_add_equiv.\n    rewrite add_commutativity. reflexivity.\n  Qed.\n  \n  Theorem multiply_commutativity : forall (n m : Nat), n * m = m * n.\n  Proof.\n    intros. induction n. \n    rewrite multiply_zero. simpl. reflexivity.\n    rewrite multiply_succ. simpl.\n    rewrite add_commutativity. symmetry. rewrite add_commutativity.\n    apply equiv_implies_add_equiv. symmetry. apply IHn.\n  Qed. \n  \n  Theorem multiply_associativity :\n    forall (i j k : Nat), i * (j * k) = (i * j) * k.\n  Proof.\n    intros. induction i. simpl. reflexivity.\n    simpl. symmetry. rewrite multiply_commutativity.\n    rewrite add_multiply. rewrite multiply_commutativity.\n    rewrite add_commutativity. symmetry. rewrite add_commutativity.\n    apply equiv_implies_add_equiv. rewrite IHi.\n    symmetry. apply multiply_commutativity.\n  Qed.\n  \n  Theorem multiply_closure : forall (n m : Nat), exists x, x = n * m.\n  Proof.\n    intros. now exists (n * m).\n  Qed.\n  \n  Lemma multiply_permutes : forall (i j k : Nat), i * j * k = j * k * i.\n  Proof.\n    intros. symmetry. rewrite multiply_commutativity.\n    apply multiply_associativity.\n  Qed.\n  \n  \n    ", "meta": {"author": "felixjhb", "repo": "rhul_coq", "sha": "d80f8120ce7ed796dc324597cac3a6dbb5e8d4a6", "save_path": "github-repos/coq/felixjhb-rhul_coq", "path": "github-repos/coq/felixjhb-rhul_coq/rhul_coq-d80f8120ce7ed796dc324597cac3a6dbb5e8d4a6/integers_opp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7376992612595524}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  Rpow                                                 \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  *****************************************************************************\n  Definition of an exponential function over relative numbers *)\nRequire Export Omega.\nRequire Export Digit.\n(* We have already an exponential over natural number,\n   we prove some basic properties for this function *)\n \nTheorem pow_O : forall e : R, (e ^ 0)%R = 1%R.\nsimpl in |- *; auto with real.\nQed.\n \nTheorem pow_1 : forall e : R, (e ^ 1)%R = e.\nsimpl in |- *; auto with real.\nQed.\n \nTheorem pow_NR0 : forall (e : R) (n : nat), e <> 0%R -> (e ^ n)%R <> 0%R.\nintros e n; elim n; simpl in |- *; auto with real.\nQed.\n \nTheorem pow_add :\n forall (e : R) (n m : nat), (e ^ (n + m))%R = (e ^ n * e ^ m)%R.\nintros e n; elim n; simpl in |- *; auto with real.\nintros n0 H' m; rewrite H'; auto with real.\nQed.\nHint Resolve pow_O pow_1 pow_NR0 pow_add: real.\n \nTheorem pow_RN_plus :\n forall (e : R) (n m : nat),\n e <> 0%R -> (e ^ n)%R = (e ^ (n + m) * / e ^ m)%R.\nintros e n; elim n; simpl in |- *; auto with real.\nintros n0 H' m H'0.\nrewrite Rmult_assoc; rewrite <- H'; auto.\nQed.\n \nTheorem pow_lt : forall (e : R) (n : nat), (0 < e)%R -> (0 < e ^ n)%R.\nintros e n; elim n; simpl in |- *; auto with real.\nintros n0 H' H'0; replace 0%R with (e * 0)%R; auto with real.\nQed.\nHint Resolve pow_lt: real.\n \nTheorem Rlt_pow_R1 :\n forall (e : R) (n : nat), (1 < e)%R -> 0 < n -> (1 < e ^ n)%R.\nintros e n; elim n; simpl in |- *; auto with real.\nintros H' H'0; Contradict H'0; auto with arith.\nintros n0; case n0.\nsimpl in |- *; rewrite Rmult_1_r; auto.\nintros n1 H' H'0 H'1.\nreplace 1%R with (1 * 1)%R; auto with real.\napply Rlt_trans with (r2 := (e * 1)%R); auto with real.\napply Rmult_lt_compat_l; auto with real.\napply Rlt_trans with (r2 := 1%R); auto with real.\napply H'; auto with arith.\nQed.\nHint Resolve Rlt_pow_R1: real.\n \nTheorem Rlt_pow :\n forall (e : R) (n m : nat), (1 < e)%R -> n < m -> (e ^ n < e ^ m)%R.\nintros e n m H' H'0; replace m with (m - n + n).\nrewrite pow_add.\npattern (e ^ n)%R at 1 in |- *; replace (e ^ n)%R with (1 * e ^ n)%R;\n auto with real.\napply Rminus_lt.\nrepeat rewrite (fun x : R => Rmult_comm x (e ^ n));\n rewrite <- Rmult_minus_distr_l.\nreplace 0%R with (e ^ n * 0)%R; auto with real.\napply Rmult_lt_compat_l; auto with real.\napply pow_lt; auto with real.\napply Rlt_trans with (r2 := 1%R); auto with real.\napply Rlt_minus; auto with real.\napply Rlt_pow_R1; auto with arith.\napply plus_lt_reg_l with (p := n); auto with arith.\nrewrite le_plus_minus_r; auto with arith; rewrite <- plus_n_O; auto.\nrewrite plus_comm; auto with arith.\nQed.\nHint Resolve Rlt_pow: real.\n \nTheorem pow_R1 :\n forall (r : R) (n : nat), (r ^ n)%R = 1%R -> Rabs r = 1%R \\/ n = 0.\nintros r n H'.\ncase (Req_dec (Rabs r) 1); auto; intros H'1.\ncase (Rdichotomy _ _ H'1); intros H'2.\ngeneralize H'; case n; auto.\nintros n0 H'0.\ncut (r <> 0%R); [ intros Eq1 | idtac ].\n2: Contradict H'0; auto with arith.\n2: simpl in |- *; rewrite H'0; rewrite Rmult_0_l; auto with real.\ncut (Rabs r <> 0%R); [ intros Eq2 | apply Rabs_no_R0 ]; auto.\nabsurd (Rabs (/ r) ^ 0 < Rabs (/ r) ^ S n0)%R; auto.\nreplace (Rabs (/ r) ^ S n0)%R with 1%R.\nsimpl in |- *; apply Rlt_irrefl; auto.\nrewrite Rabs_Rinv; auto.\nrewrite <- Rinv_pow; auto.\nrewrite RPow_abs; auto.\nrewrite H'0; rewrite Rabs_right; auto with real.\napply Rlt_pow; auto with arith.\nrewrite Rabs_Rinv; auto.\napply Rmult_lt_reg_l with (r := Rabs r).\ncase (Rabs_pos r); auto.\nintros H'3; case Eq2; auto.\nrewrite Rmult_1_r; rewrite Rinv_r; auto with real.\ngeneralize H'; case n; auto.\nintros n0 H'0.\ncut (r <> 0%R); [ intros Eq1 | auto with real ].\n2: Contradict H'0; simpl in |- *; rewrite H'0; rewrite Rmult_0_l;\n    auto with real.\ncut (Rabs r <> 0%R); [ intros Eq2 | apply Rabs_no_R0 ]; auto.\nabsurd (Rabs r ^ 0 < Rabs r ^ S n0)%R; auto with real arith.\nrepeat rewrite RPow_abs; rewrite H'0; simpl in |- *; auto with real.\nQed.\n \nTheorem Zpower_NR0 :\n forall (e : Z) (n : nat), (0 <= e)%Z -> (0 <= Zpower_nat e n)%Z.\nintros e n; elim n; unfold Zpower_nat in |- *; simpl in |- *;\n auto with zarith.\nQed.\n \nTheorem Zpower_NR1 :\n forall (e : Z) (n : nat), (1 <= e)%Z -> (1 <= Zpower_nat e n)%Z.\nintros e n; elim n; unfold Zpower_nat in |- *; simpl in |- *;\n auto with zarith.\nQed.\nHint Resolve Zpower_NR0 Zpower_NR1: zarith.\n(* To define exponential over relative number, we simply do \n   a case analysis on the sign of the number *)\n \n(*Definition powerRZ :=\n   [e : R] [n : Z]  Cases n of\n                      ZERO => R1\n                     | (POS p) => (pow e (convert p))\n                     | (NEG p) => (Rinv (pow e (convert p)))\n                    end.*)\n(* we now prove some basic properties of our exponential *)\n \nTheorem powerRZ_O : forall e : R, powerRZ e 0 = 1%R.\nsimpl in |- *; auto.\nQed.\n \nTheorem powerRZ_1 : forall e : R, powerRZ e (Zsucc 0) = e.\nsimpl in |- *; auto with real.\nQed.\n \nTheorem powerRZ_NOR : forall (e : R) (z : Z), e <> 0%R -> powerRZ e z <> 0%R.\nintros e z; case z; simpl in |- *; auto with real.\nQed.\nHint Resolve powerRZ_O powerRZ_1 powerRZ_NOR: real.\n \nTheorem powerRZ_add :\n forall (e : R) (n m : Z),\n e <> 0%R -> powerRZ e (n + m) = (powerRZ e n * powerRZ e m)%R.\nintros e n m; case n; case m; simpl in |- *; auto with real.\nintros n1 m1; rewrite nat_of_P_plus_morphism; auto with real.\nintros n1 m1. rewrite Z.pos_sub_spec; unfold Pos.compare.\nCaseEq (Pcompare m1 n1 Datatypes.Eq); simpl in |- *; auto with real.\nintros H' H'0; rewrite Pcompare_Eq_eq with (1 := H'); auto with real.\nintros H' H'0; rewrite (nat_of_P_minus_morphism n1 m1); auto with real.\nrewrite (pow_RN_plus e (nat_of_P n1 - nat_of_P m1) (nat_of_P m1));\n auto with real.\nrewrite plus_comm; rewrite le_plus_minus_r; auto with real.\nrewrite Rinv_mult_distr; auto with real.\nrewrite Rinv_involutive; auto with real.\napply lt_le_weak.\napply nat_of_P_lt_Lt_compare_morphism; auto.\napply ZC2; auto.\nintros H' H'0; rewrite (nat_of_P_minus_morphism m1 n1); auto with real.\nrewrite (pow_RN_plus e (nat_of_P m1 - nat_of_P n1) (nat_of_P n1));\n auto with real.\nrewrite plus_comm; rewrite le_plus_minus_r; auto with real.\napply lt_le_weak.\nchange (nat_of_P m1 > nat_of_P n1) in |- *.\napply nat_of_P_gt_Gt_compare_morphism; auto.\nintros n1 m1. rewrite Z.pos_sub_spec; unfold Pos.compare.\nCaseEq (Pcompare n1 m1 Datatypes.Eq); simpl in |- *; auto with real.\nintros H' H'0; rewrite Pcompare_Eq_eq with (1 := H'); auto with real.\nintros H' H'0; rewrite (nat_of_P_minus_morphism m1 n1); auto with real.\nrewrite (pow_RN_plus e (nat_of_P m1 - nat_of_P n1) (nat_of_P n1));\n auto with real.\nrewrite plus_comm; rewrite le_plus_minus_r; auto with real.\nrewrite Rinv_mult_distr; auto with real.\napply lt_le_weak.\napply nat_of_P_lt_Lt_compare_morphism; auto.\napply ZC2; auto.\nintros H' H'0; rewrite (nat_of_P_minus_morphism n1 m1); auto with real.\nrewrite (pow_RN_plus e (nat_of_P n1 - nat_of_P m1) (nat_of_P m1));\n auto with real.\nrewrite plus_comm; rewrite le_plus_minus_r; auto with real.\napply lt_le_weak.\nchange (nat_of_P n1 > nat_of_P m1) in |- *.\napply nat_of_P_gt_Gt_compare_morphism; auto.\nintros n1 m1; rewrite nat_of_P_plus_morphism; auto with real.\nintros H'; rewrite pow_add; auto with real.\napply Rinv_mult_distr; auto.\napply pow_NR0; auto.\napply pow_NR0; auto.\nQed.\nHint Resolve powerRZ_O powerRZ_1 powerRZ_NOR powerRZ_add: real.\n \nTheorem powerRZ_Zopp :\n forall (e : R) (z : Z), e <> 0%R -> powerRZ e (- z) = (/ powerRZ e z)%R.\nintros e z H; case z; simpl in |- *; auto with real.\nintros p; apply sym_eq; apply Rinv_involutive.\napply pow_nonzero; auto.\nQed.\n \nTheorem powerRZ_Zs :\n forall (e : R) (n : Z),\n e <> 0%R -> powerRZ e (Zsucc n) = (e * powerRZ e n)%R.\nintros e n H'0.\nreplace (Zsucc n) with (n + Zsucc 0)%Z.\nrewrite powerRZ_add; auto.\nrewrite powerRZ_1.\nrewrite Rmult_comm; auto.\nauto with zarith.\nQed.\n(* Conversion theorem between relative numbers and reals *)\n \nTheorem Zpower_nat_Z_powerRZ :\n forall (n : Z) (m : nat),\n IZR (Zpower_nat n m) = powerRZ (IZR n) (Z_of_nat m).\nintros n m; elim m; simpl in |- *; auto with real.\nintros m1 H'; rewrite nat_of_P_o_P_of_succ_nat_eq_succ; simpl in |- *.\nreplace (Zpower_nat n (S m1)) with (n * Zpower_nat n m1)%Z.\nrewrite Rmult_IZR; auto with real.\nrewrite H'; simpl in |- *.\ncase m1; simpl in |- *; auto with real.\nintros m2; rewrite nat_of_P_o_P_of_succ_nat_eq_succ; auto.\nunfold Zpower_nat in |- *; auto.\nQed.\n \nTheorem powerRZ_lt : forall (e : R) (z : Z), (0 < e)%R -> (0 < powerRZ e z)%R.\nintros e z; case z; simpl in |- *; auto with real.\nQed.\nHint Resolve powerRZ_lt: real.\n \nTheorem powerRZ_le :\n forall (e : R) (z : Z), (0 < e)%R -> (0 <= powerRZ e z)%R.\nintros e z H'; apply Rlt_le; auto with real.\nQed.\nHint Resolve powerRZ_le: real.\n \nTheorem Rlt_powerRZ :\n forall (e : R) (n m : Z),\n (1 < e)%R -> (n < m)%Z -> (powerRZ e n < powerRZ e m)%R.\nintros e n m; case n; case m; simpl in |- *;\n try (unfold Zlt in |- *; intros; discriminate); auto with real.\nintros p p0 H' H'0; apply Rlt_pow; auto with real.\napply nat_of_P_lt_Lt_compare_morphism; auto.\nintros p H' H'0; replace 1%R with (/ 1)%R; auto with real.\nintros p p0 H' H'0; apply Rlt_trans with (r2 := 1%R).\nreplace 1%R with (/ 1)%R; auto with real.\napply Rlt_pow_R1; auto with real.\nintros p p0 H' H'0; apply Rinv_1_lt_contravar; auto with real.\napply Rlt_pow; auto with real.\napply nat_of_P_lt_Lt_compare_morphism; rewrite ZC4; auto.\nQed.\nHint Resolve Rlt_powerRZ: real.\n \nTheorem Rpow_R1 :\n forall (r : R) (z : Z),\n r <> 0%R -> powerRZ r z = 1%R -> Rabs r = 1%R \\/ z = 0%Z.\nintros r z; case z; simpl in |- *; auto; intros p H' H'1; left.\ncase (pow_R1 _ _ H'1); auto.\nintros H'0; Contradict H'0; auto with zarith; apply convert_not_O.\nrewrite Rinv_pow in H'1; auto.\ncase (pow_R1 _ _ H'1); auto.\nintros H'0.\nrewrite <- H'0.\napply Rmult_eq_reg_l with (r := 1%R); auto with real.\npattern 1%R at 1 in |- *; rewrite <- H'0; auto with real.\npattern (Rabs (/ r)) at 1 in |- *; rewrite Rabs_Rinv; try rewrite Rinv_l;\n auto with real.\nrewrite H'0; auto with real.\napply Rabs_no_R0; auto.\nintros H'0; Contradict H'0; auto with zarith; apply convert_not_O.\nQed.\n \nTheorem Rpow_eq_inv :\n forall (r : R) (p q : Z),\n r <> 0%R -> Rabs r <> 1%R -> powerRZ r p = powerRZ r q -> p = q.\nintros r p q H' H'0 H'1.\ncut (powerRZ r (p - q) = 1%R); [ intros Eq0 | idtac ].\ncase (Rpow_R1 _ _ H' Eq0); auto with zarith.\nintros H'2; case H'0; auto.\napply Rmult_eq_reg_l with (r := powerRZ r q); auto with real.\nrewrite <- powerRZ_add; auto.\nreplace (q + (p - q))%Z with p; auto with zarith.\nrewrite <- H'1; rewrite Rmult_1_r; auto with arith.\nQed.\n \nTheorem Zpower_nat_powerRZ_absolu :\n forall n m : Z,\n (0 <= m)%Z -> IZR (Zpower_nat n (Zabs_nat m)) = powerRZ (IZR n) m.\nintros n m; case m; simpl in |- *; auto with zarith.\nintros p H'; elim (nat_of_P p); simpl in |- *; auto with zarith.\nintros n0 H'0; rewrite <- H'0; simpl in |- *; auto with zarith.\nrewrite <- Rmult_IZR; auto.\nintros p H'; Contradict H'; auto with zarith.\nQed.\n \nTheorem powerRZ_R1 : forall n : Z, powerRZ 1 n = 1%R.\nintros n; case n; simpl in |- *; auto.\nintros p; elim (nat_of_P p); simpl in |- *; auto; intros n0 H'; rewrite H';\n ring.\nintros p; elim (nat_of_P p); simpl in |- *.\nexact Rinv_1.\nintros n1 H'; rewrite Rinv_mult_distr; try rewrite Rinv_1; try rewrite H';\n auto with real.\nQed.\n \nTheorem Rle_powerRZ :\n forall (e : R) (n m : Z),\n (1 <= e)%R -> (n <= m)%Z -> (powerRZ e n <= powerRZ e m)%R.\nintros e n m H' H'0.\ncase H'; intros E1.\ncase (Zle_lt_or_eq _ _ H'0); intros E2.\napply Rlt_le; auto with real.\nrewrite <- E2; auto with real.\nrepeat rewrite <- E1; repeat rewrite powerRZ_R1; auto with real.\nQed.\n \nTheorem Zlt_powerRZ :\n forall (e : R) (n m : Z),\n (1 <= e)%R -> (powerRZ e n < powerRZ e m)%R -> (n < m)%Z.\nintros e n m H' H'0.\ncase (Zle_or_lt m n); auto; intros Z1.\nContradict H'0.\napply Rle_not_lt.\napply Rle_powerRZ; auto.\nQed.\n \nTheorem Zle_powerRZ :\n forall (e : R) (n m : Z),\n (1 < e)%R -> (powerRZ e n <= powerRZ e m)%R -> (n <= m)%Z.\nintros e n m H' H'0.\ncase (Zle_or_lt n m); auto; intros Z1.\nabsurd (powerRZ e n <= powerRZ e m)%R; auto.\napply Rlt_not_le.\napply Rlt_powerRZ; auto.\nQed.\n \nTheorem Rinv_powerRZ :\n forall (e : R) (n : Z), e <> 0%R -> (/ powerRZ e n)%R = powerRZ e (- n).\nintros e n H.\napply Rmult_eq_reg_l with (powerRZ e n); auto with real zarith.\nrewrite Rinv_r; auto with real zarith.\nrewrite <- powerRZ_add; auto with real zarith.\nring_simplify (n + - n)%Z; simpl in |- *; auto.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/Rpow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7376992605167472}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2018   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Reals.Rtrigo_def.\nRequire Reals.Rpower.\nRequire Reals.R_sqrt.\nRequire BuiltIn.\nRequire real.Real.\nRequire real.Square.\nRequire real.ExpLog.\n\nImport Rpower.\n\n(* Why3 comment *)\n(* pow is replaced with (Reals.Rpower.Rpower x x1) by the coq driver *)\n\n(* Why3 goal *)\nLemma Pow_def :\nforall (x:R) (y:R),\n (0%R < x)%R ->\n ((Reals.Rpower.Rpower x y) = (Reals.Rtrigo_def.exp (y * (Reals.Rpower.ln x))%R)).\nProof.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Pow_pos :\nforall (x:R) (y:R), (0%R < x)%R -> (0%R < (Reals.Rpower.Rpower x y))%R.\nProof.\nintros x y h1.\napply Exp_prop.exp_pos.\nQed.\n\n(* Why3 goal *)\nLemma Pow_plus :\nforall (x:R) (y:R) (z:R),\n (0%R < z)%R ->\n ((Reals.Rpower.Rpower z (x + y)%R) = ((Reals.Rpower.Rpower z x) * (Reals.Rpower.Rpower z y))%R).\nProof.\nintros x y z h1.\nnow apply Rpower_plus.\nQed.\n\n(* Why3 goal *)\nLemma Pow_mult :\nforall (x:R) (y:R) (z:R),\n (0%R < x)%R ->\n ((Reals.Rpower.Rpower (Reals.Rpower.Rpower x y) z) = (Reals.Rpower.Rpower x (y * z)%R)).\nProof.\nintros x y z h1.\nnow apply Rpower_mult.\nQed.\n\n(* Why3 goal *)\nLemma Pow_x_zero :\nforall (x:R), (0%R < x)%R -> ((Reals.Rpower.Rpower x 0%R) = 1%R).\nProof.\nintros x h1.\nnow apply Rpower_O.\nQed.\n\n(* Why3 goal *)\nLemma Pow_x_one :\nforall (x:R), (0%R < x)%R -> ((Reals.Rpower.Rpower x 1%R) = x).\nProof.\nintros x h1.\nnow apply Rpower_1.\nQed.\n\n(* Why3 goal *)\nLemma Pow_one_y :\nforall (y:R), ((Reals.Rpower.Rpower 1%R y) = 1%R).\nProof.\nintros y.\nunfold Rpower.\nrewrite ln_1.\nrewrite Rmult_0_r.\nnow apply  Rtrigo_def.exp_0.\nQed.\n\n(* Why3 goal *)\nLemma Pow_x_two :\nforall (x:R),\n (0%R < x)%R -> ((Reals.Rpower.Rpower x 2%R) = (Reals.RIneq.Rsqr x)).\nProof.\nintros x h1.\nrewrite (Rpower_pow 2) by easy.\nsimpl.\nnow rewrite Rmult_1_r.\nQed.\n\n(* Why3 goal *)\nLemma Pow_half :\nforall (x:R),\n (0%R < x)%R -> ((Reals.Rpower.Rpower x (05 / 10)%R) = (Reals.R_sqrt.sqrt x)).\nProof.\nintros x h1.\nreplace (5 / 10)%R with (/ 2)%R by field.\nnow apply Rpower_sqrt.\nQed.\n\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/real/PowerReal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7376377864661162}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (z : natural) (x : natural) : natural :=\n  plus z (plus lf2 (mult z x)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj212_coqofml_oelvkh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7376377809126251}}
{"text": "Theorem plus_n_n_injective : forall n m,\n  n + n = m + m ->\n  n = m.\nProof.\n  intros n. induction n as [| n'].\n  - destruct m. \n    -- intro H. reflexivity.\n    -- simpl. intro H2. inversion H2.\n  - destruct m as [|m'].\n    -- intros H2. inversion H2.\n    -- intro H. Search (S _ = S _). apply eq_S.\n    apply IHn'. simpl in H. inversion H.\n    rewrite <- plus_n_Sm in H1. \n    rewrite <- plus_n_Sm in H1. \n    inversion H1. reflexivity.\nQed.", "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/Chapter5/plus_n_n_injective.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7376377803619772}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export Omega.\nRequire Export Zwf.\n\n\n(* taken from chapter 5 *)\n\nInductive plane : Set :=\n    point : Z->Z->plane.\n\nInductive htree (A:Type) : nat->Type :=\n  | hleaf : A -> htree A 0%nat\n  | hnode : forall n:nat, A -> htree A n -> htree A n -> htree A (S n).\n\n\nInductive south_west : plane->plane->Prop :=\n  south_west_def :\n  forall a1 a2 b1 b2:Z, (a1 <= b1)%Z -> (a2 <= b2)%Z -> \n        south_west (point a1 a2)(point b1 b2).\n\nInductive even : nat->Prop :=\n  | O_even : even 0\n  | plus_2_even : forall n:nat, even n -> even (S (S n)).\n\nInductive sorted {A:Type}(R:A->A->Prop) : list A -> Prop :=\n  | sorted0 : sorted  R nil\n  | sorted1 : forall x:A, sorted  R (x :: nil)\n  | sorted2 :\n      forall (x y:A)(l:list A),\n        R x y ->\n        sorted  R (y :: l)-> sorted  R (x  ::  y :: l).\n\n\nHint Constructors sorted :  sorted_base.\n\nRequire Export Relations.\n\n\nInductive clos_trans {A:Type}(R:relation A) : A->A->Prop :=\n  | t_step : forall x y:A, R x y -> clos_trans  R x y\n  | t_trans :\n    forall x y z:A, clos_trans  R x y -> clos_trans  R y z -> \n        clos_trans  R x z.\n\n\nTheorem sorted_nat_123 : sorted le (1::2::3::nil).\nProof.\n auto with sorted_base arith.\nQed.\n\nTheorem xy_ord :\n forall x y:nat, le x y -> sorted  le (x::y::nil).\nProof.\n auto with sorted_base.\nQed.\n\nTheorem zero_cons_ord :\n forall l:list nat, sorted le l -> sorted le (cons 0 l).\nProof.\n induction 1; auto with sorted_base arith.\nQed.\n\nTheorem sorted1_inv {A:Type}{le : relation A} { x l} (H: sorted le (x::l))  :\n  sorted le l.\nProof.\n inversion H;  auto with sorted_base.\nQed.\n\nTheorem sorted2_inv {A:Type}{le : relation A} {x y  l}\n        (H: sorted le (x::y::l)): le x y.\nProof.\n inversion H; auto with sorted_base.\nQed.\n\nTheorem not_sorted_132 :  ~ sorted le (1::3::2::nil).\nProof.\n intros H; generalize  (sorted1_inv   H); intro H0. \n generalize (sorted2_inv H0).\n omega.\nQed.\n\n(** Tests :\nCheck True_ind.\n\nCheck False_ind.\n\nCheck and_ind.\n\nCheck or_ind.\n\nCheck ex_ind.\n\nCheck eq_ind.\n*)\n\nRequire Import JMeq.\n\n(** Tests : \nCheck JMeq_eq.\n\nCheck JMeq_ind.\n\n*)\n\nInductive ahtree(A:Type) : Type :=\n  any_height : forall n:nat, htree A n -> ahtree A.\n\nArguments any_height {A} n _.\n\nTheorem any_height_inj2 {A:Type} :\n forall (n1 n2:nat)(t1:htree A n1)(t2:htree A n2),\n   any_height n1 t1 = any_height   n2 t2 -> JMeq t1 t2.\nProof.\n intros  n1 n2 t1 t2 H.\n injection H; intros H1 H2.\n dependent rewrite <- H1.\n trivial.\nQed.\n\n\nTheorem any_height_inj2' {A:Type} :\n forall (n1 n2:nat)(t1:htree A n1)(t2:htree A n2),\n   any_height n1 t1 = any_height   n2 t2 -> JMeq t1 t2.\nProof. \n intros  n1 n2 t1 t2 H.\n change (match any_height n2 t2 with\n        | any_height  n t => JMeq t1 t\n        end);\n   now rewrite <- H.\nQed.\n\nRequire Import List  Vector.\n\nSection vectors_and_lists.\n Variable A : Type. \n (** Note :\n    The type of A-vectors of length n is just (t A n)\n    or (Vector.t A n)\n\n    Since the Vector library overloads nil and cons, we use qualified names\n    for the operations on lists *)\n\n Fixpoint vector_to_list (n:nat)(v:t A n){struct v} \n  : list A :=\n  match v with\n  | nil _ => List.nil \n  | cons _ a p tl => List.cons a (vector_to_list p tl)\n  end.\n\n Fixpoint list_to_vector (l:list A) : t A (length l) :=\n   match l as x return t A (length x) with\n   | List.nil => nil A\n   | List.cons a tl => cons A a (length tl)(list_to_vector tl)\n   end.\n\n Theorem keep_length :\n  forall (n:nat)(v:t A n), length (vector_to_list n v) = n.\n Proof.\n   intros n v; induction  v; simpl; auto.\n Qed.\n\n Lemma Vconseq :\n  forall (a:A)(n m:nat),\n   n = m ->\n   forall (v:t A n)(w:t A m),\n     JMeq v w -> JMeq (cons A a n v)(cons A a m w).\n Proof.\n  intros a n m Heq; rewrite Heq.\n  intros v w HJeq.\n  rewrite HJeq; reflexivity.\nQed.\n\n Theorem vect_to_list_and_back :\n  forall n (v:t A n),\n    JMeq v (list_to_vector (vector_to_list n v)).\n Proof.\n  intros n v; induction  v as [ | h n v IHv].\n -   reflexivity.\n -    simpl;  apply Vconseq.\n   +    now rewrite  keep_length.\n   +   assumption.\n Qed.\n\nEnd vectors_and_lists.\n\nTheorem structured_intro_example1 : forall A B C:Prop, A/\\B/\\C->A.\nProof.\n intros A B C [Ha [Hb Hc]];\n assumption.\nQed.\n\nTheorem structured_intro_example2 : forall A B:Prop, A \\/ B/\\(B->A)->A.\nProof.\n intros A B [Ha | [Hb Hi]].\n - assumption.  \n - now apply Hi. \nQed.\n\nTheorem sum_even : forall n p:nat, even n -> even p -> even (n+p).\nProof.\n(** False start\n intros n; elim n.\n auto.\n intros n' Hrec p Heven_Sn' Heven_p.\nRestart.\n*)\n\n intros n p Heven_n; induction Heven_n.  \n -  trivial.\n -  intro H0; simpl;  constructor; auto. \nQed.\n\n(** \nCheck le_ind.\n\n*)\n\nTheorem lt_le : forall n p:nat, n < p -> n <= p.\nProof.\n intros n p H; induction H; repeat constructor; assumption.\nQed.\n\n\nOpen Scope Z_scope.\n\nInductive Pfact : Z->Z->Prop :=\n  Pfact0 : Pfact 0 1\n| Pfact1 : forall n v:Z, n <> 0 -> Pfact (n-1) v -> Pfact n (n*v).\n\nTheorem pfact3 : Pfact 3 6.\nProof.\n apply Pfact1 with (n := 3)(v := 2).\n discriminate.\n apply (Pfact1 2 1).\n discriminate.\n apply (Pfact1 1 1).\n discriminate.\n apply Pfact0.\nQed.\n \nTheorem fact_def_pos : forall x y:Z, Pfact x y ->  0 <= x.\nProof.\n intros x y H; induction  H.\n -  auto with zarith.\n -  omega.\nQed.\n\n\n(**\nCheck Zwf_well_founded. \n\nCheck well_founded_ind. \n*)\n\nTheorem Zle_Pfact : forall x:Z, 0 <= x -> exists y:Z, Pfact x y.\nProof.\n intros x; induction  x using (well_founded_ind (Zwf_well_founded 0)).\n intros  Hle; destruct  (Zle_lt_or_eq  _ _ Hle).\n - destruct (H (x-1)).\n   +  unfold Zwf; omega.\n   +  omega.\n   + exists (x*x0); apply Pfact1; auto with zarith.\n -  subst x; exists 1; constructor.\n\nQed.\n\nSection little_semantics.\n Variables Var aExp bExp : Set.\n Inductive inst : Set :=\n | Skip : inst\n | Assign : Var->aExp->inst\n | Sequence : inst->inst->inst\n | WhileDo : bExp->inst->inst.\n\n Variables\n  (state : Set)\n  (update : state->Var->Z -> option state)\n  (evalA : state->aExp -> option Z)\n  (evalB : state->bExp -> option bool).\n\n Inductive exec : state->inst->state->Prop :=\n | execSkip : forall s:state, exec s Skip s\n | execAssign :\n    forall (s s1:state)(v:Var)(n:Z)(a:aExp),\n     evalA s a = Some n -> update s v n = Some s1 ->\n     exec s (Assign v a) s1\n | execSequence :\n    forall (s s1 s2:state)(i1 i2:inst),\n     exec s i1 s1 -> exec s1 i2 s2 ->\n     exec s (Sequence i1 i2) s2\n | execWhileFalse :\n    forall (s:state)(i:inst)(e:bExp),\n     evalB s e = Some false -> exec s (WhileDo e i) s\n | execWhileTrue :\n    forall (s s1 s2:state)(i:inst)(e:bExp),\n     evalB s e = Some true ->\n     exec s i s1 ->\n     exec s1 (WhileDo e i) s2 ->\n     exec s (WhileDo e i) s2.\n\n Theorem HoareWhileRule :\n  forall (P:state->Prop)(b:bExp)(i:inst)(s s':state),\n    (forall s1 s2:state,\n      P s1 -> evalB s1 b = Some true -> exec s1 i s2 -> P s2)->\n    P s -> exec s (WhileDo b i) s' ->\n    P s' /\\ evalB s' b = Some false.\n Proof.\n  intros P b i s s' H Hp Hexec; elim Hexec.\n Restart.\n  intros P b i s s' H Hp Hexec; generalize H Hp; elim Hexec.\n Restart.\n  intros P b i s s' H.\n  cut\n   (forall i':inst,\n     exec s i' s' ->\n     i' = WhileDo b i -> P s -> P s' /\\ evalB s' b = Some false); \n   eauto.\n  intros i' Hexec; elim Hexec; try (intros; discriminate).\n  intros s0 i0 e Heval Heq; injection Heq; intros H1 H2.\n  match goal  with\n  | id:(e = b) |- _ => rewrite <- id; auto\n  end.\n  intros;\n   match goal with\n   | id:(_ = _) |- _ => injection id; intros H' H''\n   end.\n    subst i0 b;eauto.\n Qed.\n\nEnd little_semantics.\n\nOpen Scope nat_scope.\n\nInductive is_0_1 : nat->Prop :=\n  is_0 : is_0_1 0 | is_1 : is_0_1 1.\n\nHint Resolve is_0 is_1 .\n\nLemma sqr_01 : forall x:nat, is_0_1 x -> is_0_1 (x * x).\nProof.\n  induction 1; simpl; auto.\nQed.\n\nTheorem elim_example : forall n:nat, n <= 1 -> n*n <= 1.\nProof.\n intros n H.\n destruct (sqr_01 n); auto.\n inversion_clear H; auto.\n inversion_clear H0; auto.\nQed.\n\n\n(** bad attempt \nSection bad_proof_for_inversion.\n\n Theorem not_1_even : ~even 1.\n Proof.\n  red; intros H; elim H.\n Abort.\n\nEnd bad_proof_for_inversion.\n\n*)\n\nTheorem not_even_1 : ~even 1.\nProof.\n unfold not; intros H.\n inversion H.\nQed.\n\nTheorem plus_2_even_inv : forall n:nat, even (S (S n))-> even n.\nProof.\n intros n H; inversion H; assumption.\nQed.\n\n\n(** Same theorems, but using basic tactics only \n*)\n\nTheorem not_even_1' : ~even 1.\nProof.\n intro H.\n generalize (refl_equal 1).\n pattern 1 at -2.\n induction H.\n - discriminate.\n - discriminate.\nQed.\n\nTheorem plus_2_even_inv' : forall n:nat, even (S (S n))-> even n.\nProof.\n intros n H.\n generalize (refl_equal (S (S n))); pattern (S (S n)) at -2.\n induction  H.\n -  discriminate.\n -  intros H0 ; injection H0; intro; now subst n0.\nQed.\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/ch8_inductive_predicates/SRC/chap8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7376294931372044}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import Recdef.\nRequire Import Lia.\n\nDefinition len (p: list nat * list nat) := length (fst p) + length (snd p).\n\nFunction merge (p: list nat * list nat) {measure len p} :=\nmatch p with\n| (nil, l2) => l2\n| (l1, nil) => l1\n| ((hd1 :: tl1) as l1, (hd2 :: tl2) as l2) =>\nif hd1 <=? hd2 then hd1 :: merge (tl1, l2)\nelse hd2 :: merge (l1, tl2)\nend.\nProof.\n  - intros.\n    unfold len.\n    simpl.\n    lia.\n  - intros.\n    unfold len.\n    simpl.\n    lia.\nDefined.\n\nInductive sorted : list nat -> Prop :=\n| sorted_nil: sorted nil\n| sorted_one: forall x, sorted (x :: nil)\n| sorted_all: forall x y l, x <= y -> sorted (y :: l) -> sorted (x :: y :: l).                        \n\nTheorem merge_sorted: forall l1 l2, sorted l1 -> sorted l2 -> sorted (merge(l1,l2)).\nProof.\n  Admitted.\n", "meta": {"author": "ensino-unb", "repo": "2022-1-mergesort", "sha": "fd421e9d3d230b6f55830fb85622fc80dbb62bbf", "save_path": "github-repos/coq/ensino-unb-2022-1-mergesort", "path": "github-repos/coq/ensino-unb-2022-1-mergesort/2022-1-mergesort-fd421e9d3d230b6f55830fb85622fc80dbb62bbf/2022-1-mergesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983308, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7375932557066507}}
{"text": "Require Coq.Setoids.Setoid.\n\nModule Type Sig.\n\n  Parameter G : Type.\n  Parameter e : G.\n\n  Parameter inv : G -> G.\n  Parameter mult : G -> G -> G.\n  Infix \"*\" := mult.\n\n  Axiom left_id : forall x : G, e * x = x.\n  Axiom left_inv : forall x : G, inv x * x = e.\n  Axiom assoc : forall x y z : G, x * (y * z) = (x * y) * z.\n\n  Definition conjugate : G -> G -> G :=\n    fun x y : G => inv y * x * y.\n\n  Infix \"^\" := conjugate.\n\nEnd Sig.\n\nModule Group (G : Sig).\nImport G.\n\nTheorem left_cancel : forall x y z : G, x * y = x * z -> y = z.\nProof.\n  intros x y z.\n  intros H.\n  assert (inv x * (x * y) = inv x * (x * z)) as Hinv.\n    rewrite H.\n    reflexivity.\n  rewrite assoc in Hinv.\n  rewrite assoc in Hinv.\n  rewrite left_inv in Hinv.\n  rewrite left_id in Hinv.\n  rewrite left_id in Hinv.\n  exact Hinv.\nQed.\n\n\nTheorem right_id : forall x : G, x * e = x.\nProof.\n  intros x.\n  assert (inv x * (x * e) = inv x * x) as H.\n    rewrite assoc.\n    rewrite left_inv.\n    apply left_id.\n  apply left_cancel in H.\n  exact H.\nQed.\n\n(* Another possible proof *)\n(* Proof. *)\n(*   intros x. *)\n(*   apply left_cancel with (x := inv x). *)\n(*   rewrite assoc. *)\n(*   rewrite left_inv. *)\n(*   apply left_id. *)\n(* Qed. *)\n\n\nTheorem right_inv : forall x : G, x * inv x = e.\nProof.\n  intros x.\n  assert (inv x * (x * inv x) = inv x * e) as H.\n    rewrite assoc.\n    rewrite left_inv.\n    rewrite right_id.\n    apply left_id.\n  apply left_cancel in H.\n  exact H.\nQed.\n\n\nTheorem unique_unit : forall f : G,\n                        (forall x : G, f * x = x /\\ x * f = x) -> e = f.\nProof.\n  intros f.\n  intros H.\n  specialize (H e).\n  elim H.\n  intros Hf_is_left_unit _.\n  assert (f * e = f * e) as Hunit.\n    reflexivity.\n  rewrite right_id in Hunit at 2.\n  rewrite Hf_is_left_unit in Hunit.\n  exact Hunit.\nQed.\n\n\nTheorem right_unique_inv : forall x y : G, x * y = e -> inv x = y.\nProof.\n  intros x y H.\n  apply left_cancel with (x := x).\n  rewrite H.\n  apply right_inv.\nQed.\n\n\nTheorem inv_is_involution : forall x : G, inv (inv x) = x.\nProof.\n  intros x.\n  apply right_unique_inv.\n  apply left_inv.\nQed.\n\n\nTheorem inv_of_mult: forall x y : G, inv (x * y) = inv y * inv x.\nProof.\n  intros x y.\n  apply right_unique_inv.\n  rewrite <- assoc.\n  rewrite assoc with (y := inv y).\n  rewrite right_inv, left_id, right_inv.\n  reflexivity.\nQed.\n\n\nTheorem inv_of_conjugate: forall x y z : G,\n    x ^ z * y ^ z = (x * y) ^ z.\nProof.\n  intros x y z.\n  unfold conjugate.\n  rewrite assoc.\n  rewrite <- assoc with (y := z).\n  rewrite assoc with (x := z).\n  rewrite right_inv.\n  rewrite left_id.\n  rewrite assoc.\n  reflexivity.\nQed.\n\nTheorem conjugate_of_unit: forall y : G, e ^ y = e.\nProof.\n  intros y.\n  unfold conjugate.\n  rewrite right_id.\n  rewrite left_inv.\n  reflexivity.\nQed.\n\nEnd Group.", "meta": {"author": "Fuco1", "repo": "algebra", "sha": "a4a86f85f8c764dca557e4dc255fd3abeaecf2ad", "save_path": "github-repos/coq/Fuco1-algebra", "path": "github-repos/coq/Fuco1-algebra/algebra-a4a86f85f8c764dca557e4dc255fd3abeaecf2ad/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7375005140110404}}
{"text": "From NaturalNumbers Require Export Base Tutorial.\n\n(* Given statements in Natural Numbers Game in Lean.\n   They just write that Peano gave these.\n   If we really wanted we could have just Admitted. them *)\nFact add_zero (n : mynat) : n + 0 = n.\nProof.\n  trivial.\nQed.\n\nFact add_succ (m n : mynat) : n + (S m) = S (n + m).\nProof.\n  trivial.\nQed.\n\n(* Level 0 data *)\n(* name The `induction` tactic *)\n(* tactics induction *)\n(* theorems add_succ *)\n(* Level 0 prologue *)\n(*\nAlright, so now that we know the basics, let's get started with addition.\nJust as a reminder, these are the things we have and know:\n<ul>\n  <li>a type `mynat`</li>\n  <li>a term `0 : mynat`, the number zero</li>\n  <li>a function `S: mynat -> mynat` taking a number `n` to its successor</li>\n  <li>addition, with the usual notation `a + b`</li>\n  <li>a theorem `add_zero (n : mynat) : n + 0 = n.`</li>\n  <li>a theorem `add_succ (m n : mynat) : n + (S m) = S (n + m).`</li>\n  <li>the principle of mathematical induction, used with the `induction` tactic, see below.</li>\n</ul>\n\nOkay, so in this first level we will prove\n```\n#Lemma zero_add (n : mynat) : 0 + n = n.\n```\nStrange right, it seems so simple knowing our theorem\n```\n#Fact add_zero (n : mynat) : n + 0 = n.\n```\nbut commutativity is not a given! To prove the lemma for this level,\njust `rewrite` and `reflexivity` are not enough, we need something stronger.\nThere is a tactic called `induction`, which we can use on inductive types\nlike our type `mynat`. Suppose we have a `n : mynat` in our assumptions, then\nwe can write\n```\ninduction n s [| ? h].\n```\nto start our induction proof. When you type this, Coq will start\ntwo \"subgoals\", one for the base case (`n = 0`), and one for the \ninduction step. It is common practice to \"select\" the subgoal explicitly\nby typing a dash `-` on the next line. Doing this you will only see one goal again.\nOnce you are done proving this goal, the interpreter will tell you\n```plaintext\nThis subproof is complete, but there are some unfocused goals.\nFocus next goal with bullet -.\n\n1 subgoal\n\nsubgoal 1 is:\n...\n```\nNow you might wonder what the `[| ? h]` means. To be very precise, in\nour inductive type `mynat` we have two constructors (`0` and `S n`), so `induction`\nwill produce two paths. In the first path, we don't get any (new) hypotheses, so we \ndon't have to name any variables. In the second path, we get a number and an induction\nhypothesis. The `?` is the name for the number, indicating we don't really care\nwhat it is called, we well see it in the subgoal (it will be `n`, the same name as\nthe variable we are doing induction over). The second hypothesis is the induction\nhypothesis. I always like to call it `h`, I think by default it is `IHn`.\nThis variable will be the induction hypothesis, saying `h : 0 + n = n`.\n\nIn short, the proof will look something like this:\n```\ninduction n as [| ? h].\n- rewrite ...\n  ...\n  reflexivity.\n- rewrite ...\n  ...\n  reflexivity.\n```\nTry it out below!\n*)\nLemma zero_add (n : mynat) : 0 + n = n.\nProof.\n    induction n as [| ? H].\n    - rewrite add_zero.\n      reflexivity.\n    - rewrite add_succ.\n      rewrite H.\n      reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 1 data *)\n(* name `add_assoc` -- associativity of addition *)\n(* tactics induction *)\n(* theorems add_succ *)\n(* Level 1 prologue *)\n(*\nThe next step is to prove that addition is associative, i.e. that\n`(a + b) + c = a + (b + c)`. Note that in the goals, the left\nhand side of the equation will show up as `a + b + c` instead\nof `(a + b) + c`. This is simply because Coq knows that \naddition is left-binding.\n*)\nLemma add_assoc (a b c : mynat) : (a + b) + c = a + (b + c).\nProof.\n    induction c as [| ? H].\n    - repeat rewrite add_zero.\n      reflexivity.\n\n      (* This only works if we do induction on C, otherwise we would want succ_add *)\n    - repeat rewrite add_succ.\n      rewrite H.\n      reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 2 data *)\n(* name `succ_add` *)\n(* tactics repeat *)\n(* theorems add_succ *)\n(* Level 2 prologue *)\n(*\nIt is almost time for the boss level of this world. Before that,\nlet us first prove the counterpart to `add_succ`: `succ_add`.\nJust as a tip, instead of repeatedly writing `rewrite add_zero.`, it\nis also possible to use the `repeat` tactic, allowing you to write \n```\nrepeat rewrite add_zero.\n```\nWhen using the `rewrite` tactic, Coq guesses which parameters to use\nin the theorem. It is also possible to do this explicitly by writing\n```\nrewrite (add_zero a)\n```\nto rewrite a subterm `a + 0` into `a`.\n*)\nLemma succ_add (a b : mynat) : S a + b = S (a + b).\nProof.\n  induction b as [| ? H].\n  - repeat rewrite add_zero.\n    reflexivity.\n  - repeat rewrite add_succ.\n    rewrite H.\n    reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 3 data *)\n(* name `add_comm` (boss level) *)\n(* tactics repeat *)\n(* theorems add_succ *)\n(* Level 3 prologue *)\n(*\n<b>*boss music*</b>\n\nCheck the side menu to remember the theorems you have shown so far,\nyou should be prepared to prove this lemma.\n*)\nLemma add_comm (a b : mynat) : a + b = b + a.\nProof.\n  induction b as [| ? H].\n  - now rewrite add_zero, zero_add.\n  - rewrite add_succ, succ_add.\n    now rewrite H.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Given in natural numbers game *)\nDefinition I := S 0.\nNotation \"1\" := I.\nFact one_eq_succ_zero : 1 = S 0.\nProof.\n  trivial.\nQed.\n\n(* Level 4 data *)\n(* name `succ_eq_add_one` *)\n(* tactics repeat *)\n(* theorems one_eq_succ_zero *)\n(* Level 4 prologue *)\n(*\nI have just defined the number `1`, in the way you would \nexpect: `1 = S 0`, and added a theorem\n```\n#Fact one_eq_succ_zero : 1 = S 0.\n```\nthat witnesses this. Use it to prove the following theorem.\n*)\nLemma succ_eq_add_one (n : mynat) : S n = n + 1.\nProof.\n  rewrite one_eq_succ_zero.\n  rewrite add_succ.\n  rewrite add_zero.\n  reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 5 data *)\n(* name `add_right_comm` *)\n(* tactics repeat *)\n(* theorems one_eq_succ_zero *)\n(* Level 5 prologue *)\n(*\nAlright, time for the last level in Addition World.\nHere it might be useful to use the strategy I mentioned before:\nrewriting a specific term in the equation. Remember you can do this\nwith the `rewrite` tactic by using it like this:\n```\nrewrite (add_comm b c).\n```\n*)\nLemma add_right_comm (a b c : mynat) : a + b + c = a + c + b.\nProof.\n  rewrite add_assoc.\n  rewrite (add_comm b c).\n  (* Can just use the forward direction but whatever *)\n  rewrite <- add_assoc.\n  reflexivity.\nQed.\n(* Level epilogue *)\n(*\nWith all these statements about addition, we have shown that\n`mynat` is a commutative monoid. In Lean (the proof checker\nfrom the original Natural Numbers Game) we could tell the \nproof checker that `mynat` is indeed a commutative monoid.\nSadly such a structure does not exist, but I have come up with a\n(rather hacky) solution for this, so that we can still use some\nmore advanced tactics to make your life easier. \n\nBasically, I added a \"fake\" multiplication operation, and \nadded some `Axiom`s (basically theorems which we just assume to be \ntrue, do this at your own risk!). With these, I was able to convince\nCoq that `mynat` is a semiring with this fake multiplication. For now\nthis will suffice, and it allows us to use the powerful `ring` tactic,\nallowing us to prove simple statements about expressions in one line,\nsuch as\n```\n#Lemma test (a b c d e : mynat) : (((a+b)+c)+d)+e=(c+((b+e)+a))+d.\n#Proof.\n#    ring.\n#Qed.\n``` \n\nIt is now time to move on to Multiplication World! Though if you wish,\nyou could also go to Function World, as we know enough to get started\nthere too. You can do this by going back to the main menu and clicking \nFunction World in the graph!\n*)\n(* Level end *)\n", "meta": {"author": "DenSinH", "repo": "natural-numbers-game", "sha": "db704cdc7f0bf5f02017e94d86a6adc82ed55793", "save_path": "github-repos/coq/DenSinH-natural-numbers-game", "path": "github-repos/coq/DenSinH-natural-numbers-game/natural-numbers-game-db704cdc7f0bf5f02017e94d86a6adc82ed55793/webapp/coq/Addition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7375005138806725}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  plus x (plus y lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj184_coqofml_xiT1gf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7374604394304317}}
{"text": "Require Import Bool Coq.Strings.Ascii Coq.Lists.List.\n\nSection regexp_def.\n\n    Definition string := list ascii.\n\n    Inductive regexp : Type :=\n    | Eps : regexp\n    | Concat : regexp -> regexp -> regexp\n    | Or : regexp -> regexp -> regexp\n    | Star : regexp -> regexp\n    | Char : ascii -> regexp.\n\n    Definition Plus (A : regexp) : regexp := Concat A (Star A).\n\n    Inductive re_spec : regexp -> string -> Prop :=\n    | rs_eps : re_spec Eps nil\n    | rs_concat : forall E E' s s',\n        re_spec E s -> re_spec E' s' -> re_spec (Concat E E') (s ++ s')\n    | rs_or : forall E E' s, (re_spec E s) + (re_spec E' s) -> re_spec (Or E E') s\n    | rs_star_eps : forall E, re_spec (Star E) nil\n    | rs_star_one : forall E s, re_spec E s -> re_spec (Star E) s\n    | rs_star_many : forall E s s', \n        re_spec (Star E) s -> re_spec (Star E) s' -> re_spec (Star E) (s ++ s')\n    | rs_char : forall a, re_spec (Char a) (cons a nil).\n\n    (* re_sub E E' : Prop\n    Defines a partial ordering on regular expressions\n    via language given by E contains language given by E'\n    *)\n\n    Inductive re_sub (E E' : regexp) : Prop :=\n    | resub : (forall s, re_spec E' s -> re_spec E s) -> re_sub E E'.\n\n    Definition re_eq (E E' : regexp) : Prop := re_sub E E' /\\ re_sub E' E.\n\n    Theorem re_sub_reflexivity : forall E, re_sub E E.\n    Proof.\n        induction E; apply resub; intros; assumption.\n    Qed.\n\n    Theorem re_sub_transitivity : forall E E' E'',\n        re_sub E E' -> re_sub E' E'' -> re_sub E E''.\n    Proof.\n        intros. destruct H, H0. apply resub.\n        intros. apply H, H0, H1.\n    Qed.\n\n    Corollary re_eq_reflexivity : forall E, re_eq E E.\n    Proof.\n        intro. unfold re_eq. split; apply re_sub_reflexivity.\n    Qed.\n\n    Corollary re_eq_transitivity : forall E E' E'',\n        re_eq E E' -> re_eq E' E'' -> re_eq E E''.\n    Proof.\n        unfold re_eq. intros. destruct H, H0. split.\n        - apply (re_sub_transitivity E E' E'' H H0).\n        - apply (re_sub_transitivity E'' E' E H2 H1).\n    Qed.\n\n    Corollary re_eq_symmetry : forall E E', re_eq E' E <-> re_eq E E'.\n    Proof.\n        unfold re_eq. intros E E'. apply and_comm.\n    Qed.\n\n    (* dfa State Alphabet : Type\n    Simulates a deterministic finite state automata.\n    Record type containing an initial state,\n    a function to check if a state is final,\n    and a function to transition to the next state\n    *)\n    Record dfa {S A : Type} := DFA {\n        initial_state : S;\n        is_final : S -> bool;\n        next : S -> A -> S\n    }.\n\n    Definition run_dfa S A (M : @dfa S A) (l : list A) : bool :=\n        (is_final M) (fold_left (next M) l (initial_state M)).\n\n    Definition redfa_Eps : @dfa bool ascii :=\n        {|\n        initial_state := true;\n        is_final (s : bool) := \n            match s with\n            | true => true\n            | _ => false\n            end;\n        next (s : bool) (a : ascii) :=\n            match s, a with\n            | _, _ => false\n            end;\n        |}.\n    \n    Definition redfa_Concat S S' (M : @dfa S ascii) (M' : @dfa S' ascii) : @dfa (sum S S') ascii :=\n        {|\n        initial_state := inl (initial_state M);\n        is_final (s : sum S S') :=\n            match s with\n            | inl _ => false\n            | inr s' => (is_final M') s'\n            end;\n        next (s : sum S S') (a : ascii) :=\n            match s with\n            | inl s' =>\n                match (is_final M) s' with\n                | true => inr ((next M') (initial_state M') a)\n                | false => inl ((next M) s' a)\n                end\n            | inr s' => inr ((next M') s' a)\n            end;\n        |}.\n\n    Definition redfa_Or S S'(M : @dfa S ascii) (M' : @dfa S' ascii) : @dfa (prod S S') ascii :=\n        {|\n        initial_state := pair (initial_state M) (initial_state M');\n        is_final (sp : prod S S') :=\n            match sp with\n            | pair s s' => (is_final M s) || (is_final M' s')\n            end;\n        next (sp : prod S S') (a : ascii) :=\n            match sp with\n            | pair s s' => pair (next M s a) (next M' s' a)\n            end;\n        |}.\n    \n    Definition redfa_Star S (M : @dfa S ascii) : @dfa S ascii :=\n        {|\n        initial_state := (initial_state M);\n        is_final := (is_final M);\n        next (s : S) (a : ascii) :=\n            match (is_final M s) with\n            | true => (next M) (initial_state M) a\n            | false => (next M) s a\n            end;\n        |}.\n    \n    Definition redfa_Char (c : ascii) : @dfa bool ascii :=\n        {|\n        initial_state := false;\n        is_final (s : bool) := s;\n        next (s : bool) (a : ascii) :=\n            match s, eqb a c with\n            | false, true => true\n            | _, _ => false\n            end;\n        |}. \n\nEnd Section.", "meta": {"author": "felixjhb", "repo": "rhul_coq", "sha": "d80f8120ce7ed796dc324597cac3a6dbb5e8d4a6", "save_path": "github-repos/coq/felixjhb-rhul_coq", "path": "github-repos/coq/felixjhb-rhul_coq/rhul_coq-d80f8120ce7ed796dc324597cac3a6dbb5e8d4a6/regexp/regexp_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7374604331824803}}
{"text": "Variables A B C : Prop.\nLemma ex2 : (A -> B) -> (B -> C) -> A -> C.\nProof.\n  intro Hab.\n  intro Hbc.\n  intro Ha.\n  apply Hbc.\n  apply Hab.\n  assumption.\nQed.", "meta": {"author": "alvarofpp", "repo": "course-coq", "sha": "64dc0d9a2e6564f9fa5df508fa946a137901feee", "save_path": "github-repos/coq/alvarofpp-course-coq", "path": "github-repos/coq/alvarofpp-course-coq/course-coq-64dc0d9a2e6564f9fa5df508fa946a137901feee/logica_proposicional_e_predicados/implicacao/exercicio_02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939024825960626, "lm_q2_score": 0.7853085783754369, "lm_q1q2_score": 0.7374242511343813}}
{"text": "Require Import Logic.Axiom.Extensionality.\n\nRequire Import Logic.Rel.Initial.\nRequire Import Logic.Rel.R.\n\n(* The category of relations has a terminal object namely 0.                     *)\n\n(* Arrow needed for terminal object universal property.                          *)\nDefinition terminal (a:Type) : R a 0 := fun x y => False.\n\nArguments terminal {a}.\n\n(* Existence part of universal property                                         *)\nLemma terminal_existence : forall (a:Type), exists (r:R a 0), True.\nProof.\n    intros a. exists terminal. trivial.\nQed.\n\n(* Uniqueness part of universal property                                        *)\nLemma terminal_uniqueness : forall (a:Type) (r s:R a 0), r = s.\nProof.\n    intros a r s. apply Ext. intros x y. split; intros H1; inversion y.\nQed.\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/Logic/Rel/Terminal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7373939381557215}}
{"text": "Require Export List Relations.\n\nSection Definitions.\n  Variables (A: Type)(R: relation A).\n  Inductive sorted  : list A -> Prop :=\n  | sorted0 : sorted  nil\n  | sorted1 : forall x:A, sorted (x::nil)\n  | sorted2 :\n      forall (x y:A)(l:list A),\n        R x y ->\n        sorted  (y::l)-> sorted  (x :: y :: l).\n\n\n  Definition sorted' (l:list A) :=\n    forall (l1 l2:list A)(n1 n2:A),\n      l = l1 ++ (n1 :: n2 ::l2) -> \n      R n1 n2.\n\n  #[local] Hint Constructors sorted : core.\n\n\n  (** Let us prove that sorted' satisfies the constructors of sorted \n   *)\n\n\n  Lemma sorted'0 : sorted'   nil.\n  Proof.\n    intro l1;   case l1; simpl; intros; discriminate.\n  Qed.\n\n  Lemma sorted'1 : forall x, sorted'  (x::nil).\n  Proof.\n    intros  x l1 l2 n1 n2; case l1.\n    -  simpl; discriminate.\n    - intros a l1'; case l1'; simpl; discriminate.\n  Qed.\n\n  Lemma sorted'2 :\n    forall x y l,\n      R x y ->\n      sorted' (y :: l)-> sorted' (x :: y :: l).\n  Proof.\n    intros x y l Hr Hs l1; case l1.\n    -  intros l2 n1 n2 Heq; injection Heq; intros; subst; trivial.\n    -  simpl; intros a l1' l2 n1 n2 Heq; injection Heq.\n       intros Heq' Heqx; apply (Hs l1' l2); trivial.\n  Qed.\n\n  #[local] Hint Resolve sorted'0 sorted'1 sorted'2 : core.\n\n  Lemma sorted'_inv : forall a l, sorted' (a::l) -> sorted' l.\n  Proof.\n    intros a l H l1 l2 n1 n2 e.\n    apply (H (a::l1) l2 n1 n2); now rewrite e. \n  Qed.\n\n  Lemma sorted_imp_sorted' :\n    forall l, sorted l -> sorted'  l.\n  Proof.\n    intros l H; induction  H; auto.\n  Qed.\n\n  Lemma sorted'_imp_sorted: forall l, sorted' l -> sorted  l.\n  Proof.\n    induction l as [|a l']; auto.\n    - destruct l'; auto.\n      + intro H; constructor. \n        * apply (H nil l'); auto.\n        *  apply IHl'; apply (sorted'_inv _ _ H).\n  Qed.\n\nEnd Definitions.\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch8_inductive_predicates/SRC/non_inductive_sorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7373939313427219}}
{"text": "From mathcomp\n     Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* ***************************** *)\nSection Perm_ind.\n  Variable (T:eqType).\n\n  Lemma perm_ind (P:seq T -> seq T -> Prop) :\n    P [::] [::] ->\n    (forall u s t, P s u -> P u t -> P s t) ->\n    (forall a s t, P s t -> P (a :: s) (a :: t)) ->\n    (forall a b s, P [:: a, b & s] [:: b, a & s]) ->\n    forall s t, perm_eq s t -> P s t.\n  Proof.\n    move => Hnil Htrans Hcons Hcons2 s.\n    have [n] := ubnP (size s).\n    elim : n s =>[|n IHn][|a s]//=;\n                         [by move =>_ t; rewrite perm_sym =>/perm_nilP->|].\n    rewrite ltnS => Hs [/permP /(_ predT)|b t]// Hperm.\n    move : (perm_mem Hperm b) (Hperm).\n    rewrite !in_cons eq_refl =>/=/orP[/eqP->|Hb _].\n    - rewrite perm_cons =>/(IHn _ Hs). exact : Hcons.\n    - apply : Htrans (Htrans _ _ _ (Hcons a _ _ (IHn _ Hs _ (perm_to_rem Hb)))\n                            (Hcons2 _ _ _)) (Hcons _ _ _ (IHn _ _ _ _)).\n      + rewrite /= size_rem //. by case : s Hs Hb {Hperm}.\n      + rewrite -(perm_cons b). apply : perm_trans Hperm.\n          by rewrite -perm_rcons /= perm_cons perm_rcons perm_sym perm_to_rem.\n  Qed.\n\n  Lemma perm_eqind (S:Type) (f:seq T -> S) :\n    (forall a s t, f s = f t -> f (a :: s) = f (a :: t)) ->\n    (forall a b s, f [:: a, b & s] = f [:: b, a & s]) ->\n    forall s t, perm_eq s t -> f s = f t.\n  Proof.\n    move => Hcons Hcons2. by apply : perm_ind =>[|u s t->||].\n  Qed.\n\n  Lemma perm_Wr (P:seq T -> seq T -> Prop):\n    (forall s t, perm_eq s t -> forall u, P u s -> P u t) ->\n    forall s t, perm_eq s t -> P s t -> forall u, perm_eq s u -> P s u.\n  Proof.\n    move => HPl s t Hpst HPst u Hpsu. apply : HPl HPst.\n    apply : perm_trans Hpsu. by rewrite perm_sym.\n  Qed.\n\n  Lemma perm_Wl (P:seq T -> seq T -> Prop):\n    (forall s t, perm_eq s t -> forall u, P s u -> P t u) ->\n    forall s t, perm_eq s t -> P s t -> forall u, perm_eq u t -> P u t.\n  Proof.\n    move => HPr s t Hpst HPst u Hput. apply : HPr HPst.\n    apply : (perm_trans Hpst). by rewrite perm_sym.\n  Qed.\n\n  Lemma perm_imply_ind (P Q:seq T -> seq T -> Prop) :\n    (forall s t, perm_eq s t -> forall u, P s u -> P t u) ->\n    (forall s t, perm_eq s t -> forall u, P u s -> P u t) ->\n    (forall a s t, P (a :: s) (a :: t) -> P s t) ->\n    (P [::] [::] -> Q [::] [::]) ->\n    (forall u s t, Q s u -> Q u t -> Q s t) ->\n    (forall a s t, P (a :: s) (a :: t) -> Q s t -> Q (a :: s) (a :: t)) ->\n    (forall a b s,\n        P [:: a, b & s] [:: b, a & s] -> Q [:: a, b & s] [:: b, a & s]) ->\n    forall s t, perm_eq s t -> P s t -> Q s t.\n  Proof.\n    move => HPl HPr HPcons Hnil Htrans Hcons Hcons2 s.\n    have [n] := ubnP (size s).\n    elim : n s =>[|n IHn][|a s]//=;\n                         [by move =>_ t; rewrite perm_sym =>/perm_nilP->|].\n    rewrite ltnS => Hs [/permP/(_ predT)|b t]// Hperm.\n    move : (perm_mem Hperm b) (Hperm).\n    rewrite !in_cons eq_refl =>/=/orP[/eqP->|Hb _ HPas].\n    - rewrite perm_cons => Hpst HPst.\n      exact : Hcons HPst (IHn _ Hs _ Hpst (HPcons _ _ _ HPst)).\n    - move : (perm_Wl HPl Hperm HPas) (perm_Wr HPr Hperm HPas) (perm_to_rem Hb)\n      => HpPl HpPr Hsb.\n      have Hbas : perm_eq [:: b, a & rem b s] (b :: t)\n        by apply : perm_trans Hperm;\n        rewrite -perm_rcons /= perm_cons perm_rcons perm_sym.\n      move : (Hsb). rewrite -(perm_cons a) => Hpasr.\n      move : (HpPr _ Hpasr) => HPasr.\n      apply : (Htrans _ _ _\n                (Hcons _ _ _ HPasr (IHn _ Hs _ Hsb (HPcons _ _ _ HPasr)))).\n      apply : Htrans (Hcons2 _ _ _ _) _; [|apply : Hcons; [|apply /IHn]].\n      + apply : HPl Hpasr _ (HpPr _ _).\n          by rewrite perm_sym -perm_rcons /= perm_cons perm_rcons perm_sym.\n      + exact : HpPl.\n      + rewrite /= (size_rem Hb).\n          by case : s Hb Hs {Hperm HPas HpPr Hsb Hbas Hpasr HPasr}.\n      + by rewrite -(perm_cons b).\n      + exact : HPcons (HpPl _ _).\n  Qed.\n\n Lemma perm_imply1l_ind (P:seq T -> Prop) (Q:seq T -> seq T -> Prop) :\n    (forall s t, perm_eq s t -> P s -> P t) ->\n    (forall a s, P (a :: s) -> P s) ->\n    (P [::] -> Q [::] [::]) ->\n    (forall u s t, Q s u -> Q u t -> Q s t) ->\n    (forall a s t, P (a :: s) -> Q s t -> Q (a :: s) (a :: t)) ->\n    (forall a b s, P [:: a, b & s] -> Q [:: a, b & s] [:: b, a & s]) ->\n    forall s t, perm_eq s t -> P s -> Q s t.\n  Proof.\n    move => HP HPcons Hnil Htrans Hcons Hcons2.\n    apply : (@perm_imply_ind (fun s t => P s)) =>[s t Hst _||a s _||||]//.\n    - exact : HP.\n    - exact : HPcons.\n  Qed.\n\n  Lemma perm_imply1r_ind (P:seq T -> Prop) (Q:seq T -> seq T -> Prop) :\n    (forall s t, perm_eq s t -> P s -> P t) ->\n    (forall a s, P (a :: s) -> P s) ->\n    (P [::] -> Q [::] [::]) ->\n    (forall u s t, Q s u -> Q u t -> Q s t) ->\n    (forall a s t, P (a :: t) -> Q s t -> Q (a :: s) (a :: t)) ->\n    (forall a b s, P [:: b, a & s] -> Q [:: a, b & s] [:: b, a & s]) ->\n    forall s t, perm_eq s t -> P t -> Q s t.\n  Proof.\n    move => HP HPcons Hnil Htrans Hcons Hcons2.\n    apply : (@perm_imply_ind (fun s t => P t)) =>[|s t Hst _|a _||||]//.\n    - exact : HP.\n    - exact : HPcons.\n  Qed.\n\n(* example *)\n  Fixpoint spick (P:pred T) (s:seq T) : option T :=\n    if s is x :: s' then if P x then Some x else spick P s' else None.\n\n  Lemma perm_map_spick (S:eqType) (f:T -> S) (s1 s2:seq T):\n    perm_eq s1 s2 -> uniq [seq f x | x <- s1] ->\n    forall y, spick (eq_op^~ y \\o f) s1 = spick (eq_op^~ y \\o f) s2.\n  Proof.\n    move : s1 s2.\n    apply : perm_imply1l_ind\n    =>[s t /(perm_map f)/perm_uniq->|a s /andP[]|\n       |u s t Hsu Hut y|a s t _ H y|a b s]//=.\n    - by rewrite Hsu Hut.\n    - by rewrite H.\n    - rewrite inE negb_or eq_sym =>/and3P[/andP[Hba _] _ _] y.\n      case : ifP Hba =>[/eqP->|]//. by case : ifP.\n  Qed.\n(*\n  Variable (P Q:seq T -> seq T -> Prop).\n\n  Goal forall s t, perm_eq s t -> P s t -> Q s t.\n  Proof.\n    apply : perm_ind.\n(*  apply : (@perm_ind (fun s t => P s t -> Q s t)).*)\n*)\nEnd Perm_ind.\n", "meta": {"author": "nekonistyle", "repo": "Qiita_example", "sha": "e6b7ffdcd0bf7e7e0ad97308a8f94f182509d603", "save_path": "github-repos/coq/nekonistyle-Qiita_example", "path": "github-repos/coq/nekonistyle-Qiita_example/Qiita_example-e6b7ffdcd0bf7e7e0ad97308a8f94f182509d603/perm_ind/perm_ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7373939288491494}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire real.Real.\n\nRequire Import Rbasic_fun.\n\n(* Why3 comment *)\n(* max is replaced with (Reals.Rbasic_fun.Rmax x x1) by the coq driver *)\n\n(* Why3 goal *)\nLemma max_def : forall (x:R) (y:R), ((y <= x)%R ->\n  ((Reals.Rbasic_fun.Rmax x y) = x)) /\\ ((~ (y <= x)%R) ->\n  ((Reals.Rbasic_fun.Rmax x y) = y)).\nProof.\nintros x y.\nsplit ; intros H.\nnow apply Rmax_left.\napply Rmax_right.\nnow apply Rlt_le, Rnot_le_lt.\nQed.\n\n(* Why3 comment *)\n(* min is replaced with (Reals.Rbasic_fun.Rmin x x1) by the coq driver *)\n\n(* Why3 goal *)\nLemma min_def : forall (x:R) (y:R), ((y <= x)%R ->\n  ((Reals.Rbasic_fun.Rmin x y) = y)) /\\ ((~ (y <= x)%R) ->\n  ((Reals.Rbasic_fun.Rmin x y) = x)).\nProof.\nintros x y.\nsplit ; intros H.\nnow apply Rmin_right.\napply Rmin_left.\nnow apply Rlt_le, Rnot_le_lt.\nQed.\n\n(* Why3 goal *)\nLemma Max_r : forall (x:R) (y:R), (x <= y)%R ->\n  ((Reals.Rbasic_fun.Rmax x y) = y).\nexact Rmax_right.\nQed.\n\n(* Why3 goal *)\nLemma Min_l : forall (x:R) (y:R), (x <= y)%R ->\n  ((Reals.Rbasic_fun.Rmin x y) = x).\nexact Rmin_left.\nQed.\n\n(* Why3 goal *)\nLemma Max_comm : forall (x:R) (y:R),\n  ((Reals.Rbasic_fun.Rmax x y) = (Reals.Rbasic_fun.Rmax y x)).\nexact Rmax_comm.\nQed.\n\n(* Why3 goal *)\nLemma Min_comm : forall (x:R) (y:R),\n  ((Reals.Rbasic_fun.Rmin x y) = (Reals.Rbasic_fun.Rmin y x)).\nexact Rmin_comm.\nQed.\n\n(* Why3 goal *)\nLemma Max_assoc : forall (x:R) (y:R) (z:R),\n  ((Reals.Rbasic_fun.Rmax (Reals.Rbasic_fun.Rmax x y) z) = (Reals.Rbasic_fun.Rmax x (Reals.Rbasic_fun.Rmax y z))).\nProof.\nintros x y z.\ndestruct (Rle_or_lt x y) as [Hxy|Hxy].\nrewrite Rmax_right with (1 := Hxy).\napply eq_sym, Rmax_right.\napply Rle_trans with (1 := Hxy).\napply Rmax_l.\nrewrite (Rmax_left x y) by now apply Rlt_le.\ndestruct (Rle_or_lt x z) as [Hxz|Hxz].\nrewrite Rmax_right with (1 := Hxz).\nrewrite Rmax_right.\napply eq_sym, Rmax_right.\napply Rlt_le.\nnow apply Rlt_le_trans with x.\napply Rle_trans with (1 := Hxz).\napply Rmax_r.\nrewrite Rmax_left.\napply eq_sym, Rmax_left.\napply Rmax_case ; now apply Rlt_le.\nnow apply Rlt_le.\nQed.\n\nLemma Rmin_max_opp :\n  forall x y : R,\n  Rmin x y = Ropp (Rmax (-x) (-y)).\nProof.\nintros x y.\ndestruct (Rle_or_lt x y) as [H|H].\nrewrite Rmin_left, Rmax_left.\napply eq_sym, Ropp_involutive.\nnow apply Ropp_le_contravar.\nexact H.\nrewrite Rmin_right, Rmax_right.\napply eq_sym, Ropp_involutive.\nnow apply Ropp_le_contravar, Rlt_le.\nnow apply Rlt_le.\nQed.\n\n(* Why3 goal *)\nLemma Min_assoc : forall (x:R) (y:R) (z:R),\n  ((Reals.Rbasic_fun.Rmin (Reals.Rbasic_fun.Rmin x y) z) = (Reals.Rbasic_fun.Rmin x (Reals.Rbasic_fun.Rmin y z))).\nProof.\nintros x y z.\nrewrite !Rmin_max_opp.\napply f_equal.\nrewrite !Ropp_involutive.\napply Max_assoc.\nQed.\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/real/MinMax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7373939220509245}}
{"text": "(** This first serie of  exercises asks you to prove some derived\n    inference rule. For some of them, build a small example of its application. \n\n\nFirst, let us look at some example : *)\n\nLemma P3Q : forall P Q : Prop, (((P->Q)->Q)->Q) -> P -> Q.\nProof.\n\n intros P Q H p.\n apply H. \n intro H0;apply\n H0;assumption. \nQed.\n\nLemma triple_neg : forall P:Prop, ~~~P -> ~P.\nProof.\n intros P ;unfold not; apply P3Q.\nQed.\n\n\n\nLemma not_or_1 : forall P Q : Prop, ~(P \\/ Q) -> ~P.\nProof.\n  intros P Q H H0; apply H;left;assumption.\nQed.\n \nSection not_or_1_example.\n Variable n : nat.\n Hypothesis H : n=0 \\/ n =2 -> n <> n.\n \n Lemma L1 : ~n=0.\n Proof.\n apply not_or_1 with (n=2).\n intro H0. \n apply H;auto.\n Qed.\n\n End not_or_1_example.\n\n\n\nLemma de_morgan_1 : forall P Q: Prop, ~ (P \\/ Q) <-> ~P /\\ ~Q.\nProof.\n intros P Q;split.\n intro H ;split; intro H0;destruct H;auto.\n intros [p' q'] [p | q].\n destruct p';assumption.\n destruct q';assumption.\nQed.\n\nLemma de_morgan_2 : forall P Q: Prop, ~ P \\/ ~Q  -> ~(P /\\ Q).\nProof. \n intros P Q [p' | q'] [p q];[destruct p'|destruct q'];assumption.\nQed.\n\nLemma test : forall (A:Type) (P:A->Prop) (x:A), (forall x:A, P x) -> P x.\nProof.\nintros A P x.\nintro H.\napply H.\n\n\nLemma all_perm :\n forall (A:Type) (P:A -> A -> Prop),\n   (forall x y:A, P x y) -> \n   forall x y:A, P y x.\nProof.\n intros A P H x y;apply H.\nQed.\n\nLemma resolution :\n forall (A:Type) (P Q R S:A -> Prop),\n   (forall a:A, Q a -> R a -> S a) ->\n   (forall b:A, P b -> Q b) -> \n   forall c:A, P c -> R c -> S c.\nProof.\n intros A P Q R S H H0 c H1 H2;apply H.\n apply H0;assumption.\n assumption.\nQed.\n\n\n\nLemma not_ex_forall_not : forall (A: Type) (P: A -> Prop),\n                      ~(exists x, P x) <-> forall x, ~ P x.\nProof.\n intros A P;split.\n intros H x Hx. destruct H. exists x;assumption.\n intros H [x Hx].\n destruct (H x). assumption.\nQed.\n\nLemma ex_not_forall_not : forall (A: Type) (P: A -> Prop),\n                       (exists x, P x) -> ~ (forall x, ~ P x).\nProof.\n intros A P [x Hx] H.\n destruct (H x).\n assumption.\nQed.\n\nLemma diff_sym : forall (A:Type) (a b : A), a <> b -> b <> a.\nProof.\n intros A a b H e . destruct H.\n symmetry;assumption.\nQed.\n\n\nLemma fun_diff :  forall (A B:Type) (f : A -> B) (a b : A), \n                       f a <> f b -> a <> b.\nProof.\n intros A B f a b H e.\n destruct H. rewrite e. reflexivity.\nQed.\n\n(**  this exercise deals with five equivalent characterizations of \n     classical logic \n\n   Some  solutions may use the following patterns :\n    unfold Ident [in H].\n    destruct (H t1 ... t2)\n    generalize t.\n    exact t.\n\n   Please look at Coq's documentation before doing these exercises *)\n\nDefinition Double_neg : Prop := forall P:Prop, ~~P -> P.\n\nDefinition Exm : Prop := forall P : Prop, P \\/ ~P.\n\nDefinition Classical_impl : Prop := forall P Q:Prop, (P -> Q) -> ~P \\/ Q.\n\nDefinition Peirce : Prop := forall P Q : Prop, ((P -> Q) -> P) -> P.\n\nDefinition Not_forall_not_exists : Prop :=\n           forall (A:Type)(P:A->Prop), ~(forall x:A, ~P x) -> ex P.\n\nLemma  Exm_Double_neg : Exm -> Double_neg.\nProof.\n unfold Double_neg.\n intros H P.\n destruct (H P) as [p | p'].\n intro;assumption.\n intro H1. destruct H1. assumption.\nQed.\n\n\nLemma Double_neg_Exm :  Double_neg -> Exm.\nProof.\n intros H P.\n apply H.\n intro H0.\n assert (H1: ~P).\n intro p;destruct H0;auto.\n destruct H0;auto.\nQed.\n\n\nLemma Peirce_Double_neg : Peirce -> Double_neg.\nProof.\n intros H P H0.\n  unfold Peirce in H.\n apply H with False.\n intro H1;destruct H0;assumption.\nQed.\n\nLemma Exm_Peirce : Exm -> Peirce.\nProof.\n intros H P Q.\n intro H0;destruct (H P) as [p | p'];auto.\n apply H0;intro p;destruct p';assumption. \nQed.\n\n\nLemma Classical_impl_Exm : Classical_impl -> Exm.\nProof.\n intros H P. red in H.\n destruct (H P P) as [p | p'].\n auto.\n right;assumption.\n left;assumption.\nQed.\n\n \nLemma Exm_Classical_impl : Exm -> Classical_impl.\nProof.\n\n\n intros H P Q H0.\n unfold Exm in H.\n destruct (H P) as [p | p'].\n right;auto.\n auto.\nQed.\n \n \nLemma Not_forall_not_exists_Double_neg :  Not_forall_not_exists -> Double_neg.\nProof.\n intros H P;red in H.\n\n\n intro H0;destruct (H nat (fun n => P)) as [x Hx].\n intro H1. destruct H0.\n apply H1. exact 0.\n assumption.\nQed.\n\n\nLemma Exm_Not_forall_not_exists: Exm -> Not_forall_not_exists.\nProof.\n intros H A P H0.\n destruct (H (ex  P)).\n\nauto.\n destruct H0;intros x Hx.\n destruct H1. exists x. assumption.\nQed.\n\n\n\n(** Consider the following definitions (which could be found in the standard \n   library *)\n\nSection On_functions.\nVariables (U V W : Type).\n\nVariable g : V -> W.\nVariable f : U -> V.\n\n Definition injective : Prop := forall x y:U, f x = f y -> x = y.\n Definition surjective : Prop := forall v : V, exists u:U, f u = v.\n\nLemma injective' : injective -> forall x y:U, x <> y -> f x <> f y.\nProof.\n intros Hi x y d e.\n destruct d;apply Hi;assumption.\nQed.\n\nDefinition compose := fun u : U => g (f u).\n\nEnd On_functions.\nImplicit Arguments compose [U V W].\nImplicit Arguments injective [U V].\nImplicit Arguments surjective [U V].\n\nLemma injective_comp : forall U V W (f:U->V)(g : V -> W),\n                       injective (compose g f) -> injective f.\nProof.\n intros U V W f g Hi x y e.\n generalize (Hi x y).\n intro H;apply H.\n unfold compose;rewrite e.\n reflexivity.\nQed.\n\n\nLemma surjective_comp : forall U V W (f:U->V)(g : V -> W),\n                       surjective (compose g f) -> surjective g.\nProof.\n intros U V W f g Hs y.\n destruct (Hs y) as [x Hx].\n exists (f x);assumption.\nQed.\n\n\nLemma comp_injective : forall U V W (f:U->V)(g : V -> W),\n                       injective f -> injective g -> injective (compose g f).\nProof.\n intros U V W f g Hf Hg x y e.\n generalize (Hf x y) ;intro H1; apply H1.\n apply Hg;assumption.\nQed.\n\nFixpoint iterate (A:Type)(f:A->A)(n:nat) {struct n} : A -> A :=\n match n with 0 => (fun a => a)\n            | S p => fun a => f (iterate _ f p a) \n end.\n\n Lemma iterate_inj : forall U (f:U->U) , \n                      injective f ->\n                      forall n: nat, injective   (iterate _ f n).\nProof.\n induction n;simpl.\n intros x y e;assumption.\n intros x y e.\n apply IHn.\n apply H;assumption.\nQed.\n \n\n(** Last serie of exercises : Consider the following definitions\n   See \"impredicatve definitions\" in the book *)\n\nDefinition my_False : Prop := forall P:Prop, P.\n\nDefinition my_not (P:Prop) := P -> my_False.\n\nDefinition my_or (P Q:Prop): Prop := forall R:Prop, \n                                    (P-> R) ->(Q->R) -> R.\n\nDefinition my_and (P Q:Prop): Prop := forall R:Prop, \n                                    (P-> Q-> R) -> R.\n\nDefinition my_exists (A:Type)(P:A->Prop) : Prop :=\n  forall R: Prop, \n    (forall a: A, P a -> R) -> R.\n\nLemma my_False_ok : False <-> my_False.\nProof.\n split;intro H.\n destruct H.\n apply H.\nQed.\n\nLemma my_or_intro_l : forall P Q:Prop, P -> my_or P Q.\nProof.\n intros P Q p R H H0;apply H;assumption.\nQed.\n\nLemma my_or_ok : forall P Q:Prop, P \\/ Q <-> my_or P Q.\nProof.\n split.\n intros [p | q] R H H0;auto.\n intro H;apply H.\n left;assumption.\n right;assumption.\nQed.\n\nLemma my_and_ok :  forall P Q:Prop, P /\\ Q <-> my_and P Q.\nProof.\n split.\n intros [p q] R H;apply H;assumption.\n intro H;apply H.\n split;assumption.\nQed.\n\nLemma my_ex_ok :  forall (A:Type)(P:A->Prop),\n                   (exists x, P x) <-> (my_exists A P).\nProof.\n intros A P ; split.\n intros [x Hx] R H.\n apply H with x;assumption.\n intro H;apply H.\n intros a Ha;exists a;assumption.\nQed.\n\n\n\n\n \n\n\n\n\n \n\n \n\n                         \n  \n", "meta": {"author": "magret2canard", "repo": "master1", "sha": "a993e9cbd38ee045af2900f9486ee9438d5e3274", "save_path": "github-repos/coq/magret2canard-master1", "path": "github-repos/coq/magret2canard-master1/master1-a993e9cbd38ee045af2900f9486ee9438d5e3274/LOGIQUE/TD4/exercises_5_solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.7373921508504496}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : lst) (qreva_arg1 : lst) : lst\n           := match qreva_arg0, qreva_arg1 with\n              | Nil, x => x\n              | Cons z x, y => qreva x (Cons z y)\n              end.\n\nFixpoint revflat (revflat_arg0 : tree) : lst\n           := match revflat_arg0 with\n              | Leaf => Nil\n              | Node d l r => append (revflat l) (Cons d (revflat r))\n              end.\n\nFixpoint qrevaflat (qrevaflat_arg0 : tree) (qrevaflat_arg1 : lst) : lst\n           := match qrevaflat_arg0, qrevaflat_arg1 with\n              | Leaf, x => x\n              | Node d l r, x => qrevaflat l (Cons d (qrevaflat r x))\n              end.\n\nTheorem append_nil: forall (l: lst), append l Nil = l.\nProof.\n   induction l.\n   { simpl. f_equal. assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n   forall (l1 l2 l3: lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n   induction l1; induction l2; induction l3; try (simpl; reflexivity).\n   { simpl. rewrite <- IHl1. f_equal. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\n   { simpl. rewrite append_nil.  reflexivity. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\nQed.\n\nTheorem qrevflat_append: forall (x : tree) (y: lst), append (revflat x) y = qrevaflat x y.\nProof.\n   induction x; induction y; simpl; try reflexivity.\n   { rewrite <- IHx1.\n   rewrite <- append_assoc.\n   f_equal.\n   simpl.\n   rewrite IHx2.\n   reflexivity.\n   }\n   {\n   rewrite append_nil.\n   rewrite <- IHx1.\n   f_equal.\n   f_equal.\n   rewrite <- IHx2.\n   rewrite append_nil.\n   reflexivity.\n   }\nQed.\n\nTheorem theorem0 : forall (x : tree), eq (revflat x) (qrevaflat x Nil).\nProof.\n   intro.\n   rewrite <- qrevflat_append.\n   rewrite append_nil.\n   reflexivity.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal28.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7373921431195474}}
{"text": "(** 1.2 Function Types *)\nModule HoTT_1_2.\n\nDefinition f : nat -> nat := fun x => x + x. \n\nCompute (f 2). (** 2 + 2 = 4 *)\n\nType (fun (x : nat) => x + x). (** nat -> nat *)\n\n(* uniqueness principle for function types *)\nTheorem fun_uniq : \n  forall (A B : Type) (f : A -> B), f = (fun x => f x).\nProof. \n  intros A B f.\n  exact eq_refl. \nQed.\n\nEnd HoTT_1_2. \n\n(** 1.3 Universes and Families *)\nModule HoTT_1_3. \n\nSet Printing Universes. \n\nInductive Unit : Type := point. \n\nDefinition type_family_example : nat -> Type :=\n  fix TFEfix (x : nat) := match x with\n                     | O => Prop\n                     | S x' => sum Unit (TFEfix x') end. \n\nType type_family_example. (* nat -> Type@{Top.10} *) \n\nDefinition constant_type_family (B : Type) : forall {A : Type}, A -> Type :=\n  fun {A : Type} (x : A) => B. \n\nEnd HoTT_1_3.\n \n(** 1.4 Dependent Function Types *)\nModule HoTT_1_4.\n\n(* the dependent product type into a constant type family is equivalent to the function type *)\nLemma prod_const__fun : forall A B : Type, (forall x : A, B) = (A -> B). \nProof. \n  reflexivity.\nShow Proof.\nQed.\n\n\n(* Polymorphic functions *)\nDefinition id : forall (A : Type), A -> A := fun (A : Type) (x : A) => x. \n\nDefinition swap : forall (A B C: Type), (A -> B -> C) -> (B -> A -> C) := \n  fun (A B C : Type) (g : A -> B -> C) (b : B) (a: A) => g a b. \n\nInductive Unit := point. \n\nDefinition true_unit : True <-> Unit := conj (fun _ => point) (fun _ => I).\n\nDefinition lf : forall {A B : Prop}, A /\\ B -> A :=\n  fun {A B : Prop} (p : A /\\ B) => match p with\n                        | conj a b => a end.\n\nDefinition rt : forall {A B : Prop}, A /\\ B -> B :=\n  fun {A B : Prop} (p : A /\\ B) => match p with\n                                     | conj a b => b end.\n\nDefinition unit_contractible : forall a b : Unit, a = b :=\n  fun (a b : Unit) =>\n    match a, b with\n    | point, point => eq_refl end.\n\nDefinition true_contractible : forall a b : True, a = b :=\n  fun (a b : True) =>\n    match a, b with\n      | I, I => eq_refl end.\n\nEnd HoTT_1_4.\n\nModule HoTT_1_5.\n\nInductive prod' (A B : Type) := pair' : A -> B -> prod' A B.\n\nDefinition prod_elim : \n  forall {A B C : Type} (g : A -> B -> C), A * B -> C. \nProof.\n  intros A B C g [a b]. exact (g a b).\nShow Proof.\nDefined.\n\nType @prod_elim. (* forall A B C : Type, (A -> B -> C) -> A * B -> C) *)\n\n(* comparison with other coq-defined defs *)\nType prod_rect.\n(* forall (A B : Type) (P : A * B -> Type),\n    (forall (a : A) (b : B), P (a, b)) -> forall p : A * B, P p *)\n\nType prod_ind. (* = ind type *)\n(* forall (A B : Type) (P : A * B -> Prop), \n    (forall (a : A) (b : B), P (a, b)) -> forall p : A * B, P p *)\n          \nType prod_rec.\n(* forall (A B : Type) (P : A * B -> Set),\n    (forall (a : A) (b : B), P (a, b)) -> forall p : A * B, P p *)\n\nDefinition Unit_rec' : forall (C : Type), C -> HoTT_1_4.Unit -> C. \nProof.\n  intros C c []. exact c.\nShow Proof.\nDefined.\n\nType Unit_rec'.\n(* forall C : Type, C -> Unit -> C *)\n\nType True_rect.\n(* forall P : Type, P -> True -> P *)\n\nDefinition pr1 : \n  forall {A B : Type}, A * B -> A := fun A B => prod_elim (fun a b => a).\n\nDefinition pr2 :\n  forall {A B : Type}, A * B -> B := fun A B => prod_elim (fun a b => b).\n\nDefinition prod_uniq : forall {A B : Type} (x : A * B), (pr1(x), pr2(x)) = x.\nProof.\n  intros A B [a b]. reflexivity.\nShow Proof.\nDefined.\n\nDefinition Unit := HoTT_1_4.Unit.\nDefinition point := HoTT_1_4.point.\n\nDefinition unit_ind : \n  forall C : Unit -> Type, C(point) -> (forall x : Unit, C(x)) :=\n  fun C C_pt x => match x with point => C_pt end.\n\nType True_ind.\n(* forall P : Prop, P -> True -> P *)\n(** Notice that HoTT _ind is not the same as Coq's _ind. *)\n\nDefinition unit_uniq :\n  forall x : Unit, x = point := fun x => match x with point => eq_refl end.\nCompute unit_uniq.\n\nDefinition unit_uniq' :\n  forall x : Unit, x = point := unit_ind (fun x => x = point) eq_refl.\nCompute unit_uniq'.\n\nEnd HoTT_1_5.\n\n(* 1.6 Dependent Pair Types *)\nModule HoTT_1_6.\n\nDefinition constant_type_family := HoTT_1_3.constant_type_family.\n\nInductive sig1 {A : Type} (P : A -> Type) : Type :=\n  existP : forall x:A, P x -> sig1 P.\n\nDefinition dpt_test1 : forall A : Type, nat := fun x => 3.\nDefinition dpt_test2 : forall A : Type, A -> Type := fun x y => nat.\nDefinition dpt_test3 : forall A B: Type, nat -> Prop := fun x y z => (z = z).\nDefinition dpt_test4 : forall A B : Type, nat -> Type := fun x y z => nat. \nDefinition dpt_test5 : forall A: Type, A -> (A -> Type) := fun x y z => nat. \nDefinition dpt_test6 : forall A : Type, 3 = 3 := fun x => eq_refl. \nDefinition dpt_test7 : forall A : Type, 3 = 3 -> nat := fun x y => 3. \n\nType (existP (fun x => x)). \n\nDefinition iffT : Type -> Type -> Type := fun A B => prod (A -> B) (B -> A).  \n\n(* the dependent pair type over a constant type is equivalent to the cartesian product *)\nDefinition sum_const__prod : forall A B : Type, iffT (sigT (fun a:A => B)) (prod A B). \nProof. \n  intros A B. split.\n  - intros [a b]. exact (pair a b). \n  - intros [a b]. exact (existT (fun _ => B) a b). \nShow Proof. \nDefined.\n\nDefinition pr1 : forall {A : Type} {B : A -> Type}, (sigT (fun x:A => B x)) -> A. \nProof.\n  intros A B [a _].\n  exact a.\nShow Proof. \nDefined.\n\n Definition pr2 : forall {A : Type} {B : A -> Type} (p : sigT (fun x:A => B x)), B (pr1 p). \nProof. \n  intros A B [a b].\n  simpl. exact b. \nShow Proof. \nDefined.\n\nDefinition sum_elim : \n  forall {A : Type} {B : A -> Type} {C : (sigT (fun (x : A) => B x)) -> Type}\n                                           (a : A) (b : B a), C (existT _ a b).\nProof. Admitted. \n\nDefinition sum_elim_f : \n  forall {A : Type} {B : A -> Type} {C : (sigT (fun (x : A) => B x)) -> Type}\n         (p : sigT (fun (x : A) => B x)), C p. \nProof. \n  intros A B C [a b]. \n  exact (sum_elim a b).\nDefined.\n\n(* recursor for dependent pair types *)\nDefinition sig_rec : forall {A : Type} {B : A -> Type} {C : Type}, \n    (forall x : A, B x -> C) -> (sigT (fun x:A => B x)) -> C. \nProof. \n  intros A B C g [a b]. \n  exact (g a b).\nShow Proof. \nDefined. \n\n(* inductor for dependent pair types *)\nDefinition sig_ind : forall {A : Type} {B : A -> Type} (C : (sigT (fun x : A => B x)) -> Type),\n                            (forall (a : A) (b : B a), C (existT _ a b)) ->\n                            (forall (p : (sigT (fun x : A => B x))), C p). \nProof.\n  intros A B C g [a b]. \n  exact (g a b). \nShow Proof. \nDefined. \n\n(* The type-theoretic axiom of choice *)\nDefinition sig_ac : forall {A B : Type} {R : A -> B -> Type}, \n    (forall (x : A), sigT (fun y : B => R x y)) -> \n    (sigT (fun f : A -> B => forall x : A, R x (f x))).\nProof.\n  intros A B R g. \n  pose (fun f : A -> B => forall x : A, R x (f x)).\n  exact (existT T (fun x => pr1 (g x)) (fun x => pr2 (g x))). \nShow Proof. \nDefined. \n\n(* We may define magmas and pointed magmas in terms of dependent pair types. *)\nDefinition Magma : Type := sigT (fun A : Type => A -> A -> A). \nDefinition PointedMagma : Type := sigT (fun A : Type => prod (A -> A -> A) A). \n\nEnd HoTT_1_6.\n\n(** Coproduct types *)\nModule HoTT_1_7.\n\nInductive empty : Type :=. \n\n(* recursor for the coproduct type *)\nDefinition sum_rec : forall {A B : Type} (C : Type), (A -> C) -> (B -> C) -> (A + B -> C).\nProof.\n  intros A B C g0 g1 [a | b].\n  - exact (g0 a).\n  - exact (g1 b).\nShow Proof.\nDefined.\n\n(* recursor for the empty type *)\nDefinition empty_rec' : forall C : Type, empty -> C.\nProof.\n  intros C [].\nShow Proof.\nDefined.\n\n(* inductor for the coproduct type *)\nDefinition sum_ind : forall {A B : Type} (C : A + B -> Type),\n    (forall a : A, C (inl a)) -> (forall b : B, C (inr b)) -> \n    (forall x : A + B, C x).\nProof.\n  intros A B C g0 g1 [a | b].\n  - exact (g0 a).\n  - exact (g1 b).\nShow Proof.\nDefined.\n\n(* inductor for the empty type *)\nDefinition empty_ind' : forall (C : empty -> Type) (z : empty), C z.\nProof.\n  intros C [].\nShow Proof.\nDefined.\n\nEnd HoTT_1_7.\n\nModule HoTT_1_8.\n\nDefinition Unit := HoTT_1_4.Unit.\nDefinition point := HoTT_1_4.point.\n\nDefinition bool : Type := sum Unit Unit.\n\n(* recursor on bool type *)\nDefinition bool_rec' : forall (C : Type), C -> C -> bool -> C.\nProof.\n  intros C c0 c1 [[] | []].\n  - exact c0.\n  - exact c1.\nShow Proof.\nDefined.\n\n(* Observe that the rec proofs constructed here are not proof-independent: indeed,\n  a natural proof of bool_rec would be as follows: *)\n\nDefinition bool_rec_faulty : forall (C : Type), C -> C -> bool -> C :=\n  fun C c _ _ => c.\n\n(* While this definition type-checks, it clearly does not capture the expected\nsemantics of the type bool; using this as a recursor, in fact, would lend it the\nbehavior of the unit type. That this is possible shows bool -> unit. *)\n\nDefinition false' : bool := inl point.\nDefinition true' : bool := inr point.\n\n(* inductor on bool type *)\nDefinition bool_ind' : forall (C : bool -> Type), \n    C false' -> C true' -> forall x : bool, C x.\nProof.\n  intros C c0 c1 [[] | []].\n  - exact c0.\n  - exact c1.\nShow Proof.\nDefined.\n\n(* Note that the proof for induction, however, is in fact the most natural construction\nof the function, and we shall later show uniqueness. In this manner, the semantics\nof the bool type may be predicated purely on the type of the inductor. *)\n\nDefinition thm_1_8_1 : forall x : bool, (x = false') + (x = true').\nProof.\n  apply bool_ind'.\n  - apply (inl eq_refl).\n  - apply (inr eq_refl).\nShow Proof.\nDefined.\n\nDefinition sum' (A B : Type) := sigT (fun x : bool => bool_rec' Type A B x).\nDefinition inl' {A B: Type} (a : A) : (sum' A B) := \n  existT (fun x : bool => bool_rec' Type A B x) false' a.\nDefinition inr' {A B : Type} (b : B) : (sum' A B) :=\n  existT (fun x : bool => bool_rec' Type A B x) true' b.\n\n(* Exercise : Derive induction principle for coproducts from this. *)\n\nDefinition prod' (A B : Type) := forall x : bool, bool_rec' Type A B x.\nDefinition pair' {A B : Type} (a : A) (b : B) : prod' A B :=\n  bool_ind' (bool_rec' Type A B) a b.\nDefinition pr1' {A B : Type} (p : prod' A B) := p false'.\nDefinition pr2' {A B : Type} (p : prod' A B) := p true'.\n\nCompute pr1' (pair' 3 4). (* 3 : bool_rec' Type nat nat false' *)\nCompute (bool_rec' Type nat nat false'). (* nat : Type *)\n\n(* However this product has an extensional flavor to it. *)\n(** TODO : Exercises and proofs of equivalence *)\n\nEnd HoTT_1_8.\n\n", "meta": {"author": "stanjenie", "repo": "univalence_notes", "sha": "c9c3c5202ab69b4ab7ccc6e2745d3518ea7aa48c", "save_path": "github-repos/coq/stanjenie-univalence_notes", "path": "github-repos/coq/stanjenie-univalence_notes/univalence_notes-c9c3c5202ab69b4ab7ccc6e2745d3518ea7aa48c/univalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.7373921276160835}}
{"text": "(** 116297 - Tópicos Avançados em Computadores - 2017/2           **)\n(** Provas Formais: Uma Introdução à Teoria de Tipos - Turma B    **)\n(** Prof. Flávio L. C. de Moura                                   **)\n(** Email: contato@flaviomoura.mat.br                             **)\n(** Homepage: http://flaviomoura.mat.br                           **)\n\n(** Aluno:  Gabriel F P Araujo                                    **)\n(** Matrícula: 12/0050943                                         **)\n\n(** Formalização do algoritmo Bubble Sort. *)\n(**\nA ideia geral da formalização do algoritmo Bubble Sort foi feita em sala. Utilizando as informações dadas, faça a prova do teorema bubbleSort_correcao abaixo. Você pode adicionar os lemas (com provas completas!) que achar necessário.\n *)\n\nRequire Import Arith.\nRequire Import Recdef.\nRequire Import List.\nRequire Import Sorted.\n\nOpen Scope list_scope.\n\nFunction bubble l {measure length l} :=\n  match l with\n    | h0 :: h1 :: tl =>\n      match le_lt_dec h0 h1 with\n        | left _ => h0 :: (bubble (h1 :: tl))\n        | right _ => h1 :: (bubble (h0 :: tl))\n      end\n    | _ => l\n    end.\nProof.\n  intros. simpl. auto.\n  intros. simpl. auto.\nDefined.\n\nFixpoint bubbleSort (l: list nat) : list nat :=\n  match l with\n  | nil => l\n  | h::tl => bubble (h :: (bubbleSort tl))\n  end.\n\nInductive ordenada : list nat -> Prop :=\n  | lista_vazia : ordenada nil\n  | lista_1: forall n : nat, ordenada (cons n nil)\n  | lista_nv : forall (x y : nat) (l : list nat), ordenada (cons y l) -> x <= y -> ordenada (cons x (cons y l)).\n\nFixpoint num_oc n l := \n  match l with\n    | nil => 0\n    | cons h tl => \n      match eq_nat_dec n h with\n        | left _ => S(num_oc n tl) \n        | right _ => num_oc n tl \n      end\n  end.\n\nDefinition equiv l l' := forall n:nat, num_oc n l = num_oc n l'.\n\nLemma ordenada_n_l: forall h tl, ordenada (h :: tl) -> ((h :: tl) = bubble (h :: tl)).\nProof.\n  intros h tl.\n  induction (h :: tl).\n  - intro H.\n    reflexivity.\n  - intro H.\n    rewrite bubble_equation.\n    destruct l.\n    + reflexivity.\n    + destruct (le_lt_dec a n).\n      * rewrite <- IHl.\n        ** reflexivity.\n        ** inversion H.\n           assumption.\n      * inversion H; subst.\n        apply le_not_lt in H4.\n        contradiction.\nQed.\n\nLemma bubble_preserva_ordem : forall l n, ordenada l -> ordenada (bubble (n::l)).\nProof.\n  (* intros l n H. *)\n  induction l.\n  - intros.\n    rewrite bubble_equation.\n    apply lista_1.\n  - intros.\n    rewrite bubble_equation.\n    destruct (le_lt_dec n a).\n    + rewrite <- ordenada_n_l.\n      * apply lista_nv.\n        assumption.\n        assumption.\n      * assumption.\n    + rewrite bubble_equation.\n      destruct l.\n      * apply lista_nv.\n        ** apply lista_1.\n        ** apply Nat.lt_le_incl.\n           assumption.\n      * destruct (le_lt_dec n n0).\n        ** apply lista_nv.\n          *** assert (ordenada (bubble (n :: n0 :: l))).\n            { apply IHl. inversion H. assumption. }\n              rewrite bubble_equation in H0.\n              destruct (le_lt_dec n n0).\n              assumption.\n              apply le_not_lt in l1.\n              contradiction.\n          *** apply Nat.lt_le_incl.\n              assumption.\n        ** apply lista_nv.\n          *** assert (ordenada (bubble (n :: n0 :: l))).\n            { apply IHl. inversion H. assumption. }\n              rewrite bubble_equation in H0.\n              destruct (le_lt_dec n n0).\n              **** apply le_not_lt in l2.\n                   contradiction.\n              **** assumption.\n          *** inversion H.\n              assumption.\nQed.\n\nLemma num_oc_bubble: forall l n, num_oc n (bubble l) =  (num_oc n l).\nProof.\n  intros l n.\n  functional induction (bubble l).\n  - simpl num_oc.\n    destruct (Nat.eq_dec n h0).\n    + destruct (Nat.eq_dec n h1).\n      * rewrite IHl0.\n        simpl num_oc.\n        destruct (Nat.eq_dec n h1).\n        ** tauto.\n        ** contradiction.\n      * rewrite IHl0.\n        simpl num_oc.\n        destruct (Nat.eq_dec n h1).\n        ** contradiction.\n        ** tauto.\n    + destruct (Nat.eq_dec n h1).\n      * rewrite IHl0.\n        simpl num_oc.\n        destruct (Nat.eq_dec n h1).\n        ** tauto.\n        ** contradiction.\n      * rewrite IHl0.\n        simpl num_oc.\n        destruct (Nat.eq_dec n h1).\n        ** contradiction.\n        ** tauto.\n  - simpl num_oc.\n    destruct (Nat.eq_dec n h0).\n    + destruct (Nat.eq_dec n h1).\n      * rewrite IHl0.\n        simpl num_oc.\n        destruct (Nat.eq_dec n h0).\n        ** reflexivity.\n        ** contradiction.\n      * rewrite IHl0.\n        simpl num_oc.\n        destruct (Nat.eq_dec n h0).\n        ** reflexivity.\n        ** contradiction.\n    + destruct (Nat.eq_dec n h1).\n      * rewrite IHl0.\n        simpl num_oc.\n        destruct (Nat.eq_dec n h0).\n        ** contradiction.\n        ** reflexivity.\n      * rewrite IHl0.\n        simpl num_oc.\n        destruct (Nat.eq_dec n h0).\n        ** contradiction.\n        ** reflexivity.\n  - reflexivity.\nQed.\n\nTheorem bubbleSort_correcao: forall l, equiv (bubbleSort l) l /\\ ordenada (bubbleSort l).\nProof.\n  induction l.\n  - split.\n    + simpl.\n      unfold equiv.\n      intro n.\n      reflexivity.\n    + simpl.\n      apply lista_vazia.\n  - destruct IHl as [Hequiv Hord].\n    split.\n    + simpl.\n      unfold equiv in *.\n      intro n'.\n      assert (H:  num_oc n' (bubble (a :: (bubbleSort l))) = num_oc n' ( a :: (bubbleSort l))).\n      { apply num_oc_bubble. }\n      apply Nat.eq_trans with (num_oc n' (cons a (bubbleSort l))).\n      * assumption.\n      * simpl. destruct (Nat.eq_dec n' a).\n        ** apply eq_S.\n           apply Hequiv.\n        ** apply Hequiv.\n    + simpl.\n      assert (ordenada (bubbleSort l) -> ordenada (bubble (a :: bubbleSort l))).\n      { apply bubble_preserva_ordem. }\n      apply H.\n      assumption.\nQed.", "meta": {"author": "Gastd", "repo": "fptt", "sha": "999472e6b0df8652a299f271f1676c8c0dc78256", "save_path": "github-repos/coq/Gastd-fptt", "path": "github-repos/coq/Gastd-fptt/fptt-999472e6b0df8652a299f271f1676c8c0dc78256/bubbleSort2017_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7373873348551457}}
{"text": "Require Import List Lia.\nImport ListNotations.\n\nRequire Import Undecidability.PCP.PCP.\nRequire Import Undecidability.PCP.Util.Facts.\nImport PCPListNotation.\n\nRequire Import Undecidability.Synthetic.Definitions.\n\nSet Default Goal Selector \"!\".\n\n(* ** PCP reduces to BPCP *)\n\n(* natural numbers n to bitstrings of the form 1^n *)\n\nDefinition to_bitstring (n : nat) : string bool := Nat.iter n (cons true) [].\n\nLemma bitstring_false a : ~ false el to_bitstring a.\nProof.\n  induction a; cbn; firstorder congruence.\nQed.\n\n(* strings of natural numbers to bitstrings, [ n1, ... n2 ] |-> 1^n1 0 ... 1^n2 0 *)\nFixpoint f_s (x : string nat) : string bool :=\n  match x with\n  | nil => nil\n  | a :: x => to_bitstring a ++ [false] ++ f_s x\n  end.\n\nLemma f_s_app x y : f_s (x ++ y) = f_s x ++ f_s y.\nProof.\n  induction x; cbn. \n  - reflexivity.\n  - rewrite IHx. now rewrite <- app_assoc.\nQed.\n\n(* extension to cards and stacks *)\nDefinition f_c '(x,y) := (f_s x, f_s y).\nDefinition f (P : stack nat) : stack bool :=\n  map f_c P.\n\nLemma tau1_f A : tau1 (f A) = f_s (tau1 A).\nProof.\n  induction A as [ | (x,y) ]; cbn.\n  - reflexivity.\n  - unfold f in IHA. now rewrite IHA, f_s_app.\nQed.\n\nLemma tau2_f A : tau2 (f A) = f_s (tau2 A).\nProof.\n  induction A as [ | (x,y) ]; cbn.\n  - reflexivity.\n  - unfold f in IHA. now rewrite IHA, f_s_app.\nQed.\n\n(* interpretation of a bitstring as list of natural numbers *)\nFixpoint g_s' (x : string bool) (n : nat) : string nat :=\n  match x with\n  | nil => nil\n  | true :: x' => g_s' x' (S n)\n  | false :: x' => n :: g_s' x' 0\n  end.\n\nLemma g_s'_app n x y :\n  g_s' (f_s x ++ y) n = match x with nil => g_s' y n | m :: x => n + m :: x ++ g_s' y 0 end.\nProof.\n  revert n y. induction x as [ | m]; intros; cbn in *.\n  - reflexivity.\n  - revert n; induction m; intros; cbn in *.\n    + destruct x.\n      * do 2 f_equal. lia.\n      * rewrite IHx. f_equal. lia.\n    + rewrite IHm. f_equal. lia.\nQed.\n\nDefinition g_s x := g_s' x 0.\n\nLemma f_g_s'_inv x : g_s (f_s x) = x.\nProof.\n  unfold g_s. setoid_rewrite <- app_nil_r at 2. rewrite g_s'_app.\n  destruct x; eauto. cbn. now rewrite app_nil_r.\nQed.\n\n(* extension to cards and stacks *)\nDefinition g_c '(x,y) := (g_s x, g_s y).\nDefinition g (P : stack bool) : stack nat :=\n  map g_c P.\n\n(* Invariants *)\n\nLemma tau1_g A B : A <<= f B -> tau1 (g A) = g_s (tau1 A).\nProof.\n  induction A as [ | (x,y)]; cbn.\n  - reflexivity.\n  - unfold g in IHA. intros. rewrite !IHA.\n    { assert ( (x, y) el map f_c B) as ((x',y') & ? & ?) % in_map_iff by firstorder; inv H0.\n      rewrite g_s'_app. destruct x'.\n      + cbn. reflexivity.\n      + rewrite f_g_s'_inv. cbn. reflexivity. }\n    firstorder.\nQed.\n\nLemma tau2_g A B : A <<= f B -> tau2 (g A) = g_s (tau2 A).\nProof.\n  induction A as [ | (x,y)]; cbn.\n  - reflexivity.\n  - unfold g in IHA. intros. rewrite !IHA.\n    { assert ( (x, y) el map f_c B) as ((x',y') & ? & ?) % in_map_iff by firstorder; inv H0.\n      rewrite g_s'_app. destruct y'.\n      + cbn. reflexivity.\n      + rewrite f_g_s'_inv. cbn. reflexivity. }\n    firstorder.\nQed.\n\nLemma f_subset B A : A <<= B -> f A <<= f B.\nProof.\n  induction A in B |- *; intros H; cbn.\n  * firstorder.\n  * intros ? [| H0]; subst.\n    - unfold f. eapply in_map_iff. exists a.\n      constructor; eauto.\n      apply H; simpl; auto.\n    - eapply IHA in H0; eauto.\n      intros ? ?; apply H; simpl; auto. \nQed.\n\nLemma f_g_subset B A : A <<= f B -> g A <<= B.\nProof.\n  revert B; induction A; intros B H; cbn.\n  * firstorder.\n  * assert (a el f B) by firstorder.\n    unfold f in H0. eapply in_map_iff in H0 as ((x,y) & ? & ?). inv H0.\n    intros ? [|]; subst. { cbn. now rewrite !f_g_s'_inv. } firstorder.\nQed.\n\nTheorem reduction : PCP ⪯ PCPb.\nProof.\n  exists f. intros B. split.\n  - intros (A & HP & He & H). exists (f A). repeat split.\n    + now eapply f_subset.\n    + destruct A; cbn; congruence.\n    + unfold f, f_c, f_s. setoid_rewrite tau1_f. setoid_rewrite tau2_f. now rewrite H.\n  - intros (A & HP & He & H). exists (g A). repeat split.\n    + eapply f_g_subset; eauto.\n    + destruct A; cbn; congruence.\n    + erewrite tau1_g, tau2_g, H; eauto.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/PCP/Reductions/PCP_to_PCPb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7373873272899274}}
{"text": "Require Import List.\nRequire Import Bool.\nRequire Import ZArith.\nRequire Import Sorting.\n\n(** Aktiviramo notacijo za sezname. *)\nLocal Open Scope list_scope.\n(** Definicija vstavlanja elementov v seznam. **)\nFunction vstavi (x:Z) (l: list Z) :=\n     match l with\n      | nil => x::nil\n      | y::l' => if (x <=? y)%Z then x::y::l' else y::(vstavi x l')\nend.\n\n(** Urejanje seznama po principu insertion sort-a. **)\nFixpoint insert (l:list Z) :=\n     match l with\n      | nil => nil\n      | x::l' => let l'' := (insert l') in vstavi x l''\nend. \n\nEval compute in (insert (2 :: 5 :: 1 :: 4 :: nil)%Z).\n\n(** Dodajanje elementa ohranja urejen seznam. **)\nLemma urejen_t (a: Z) (l: list Z):\n  urejen l -> urejen (vstavi a l).\nProof.\n  intro.\n  induction l.\n  - auto.\n  - simpl.\n    case_eq (a <=? a0)%Z.\n    + destruct l.\n      * intro.\n        apply Zle_bool_imp_le in H0.\n        simpl.\n        auto.\n      * case_eq (a0 <=? z)%Z.\n        apply urejen_tail in H. firstorder.\n        apply Zle_bool_imp_le in H1; auto.\n        apply Zle_bool_imp_le in H0; auto.\n        firstorder.\n        apply Zle_bool_imp_le in H1; auto.\n   + firstorder; simpl.\n     destruct l. \n     * firstorder.\n       apply Z.leb_gt in H0.\n       apply Z.lt_le_incl in H0.\n       auto.\n     * apply Z.leb_gt in H0. simpl.\n       case_eq (a <=? z)%Z.\n       apply Z.lt_le_incl in H0.\n       split; auto.\n       apply Zle_bool_imp_le in H1. firstorder.\n       intro.\n       SearchAbout  [(_ <=? _)%Z].\n       apply Z.leb_gt in H1.\n       destruct H.\n       split. assumption.\n       replace (z :: vstavi a l) with (vstavi a (z :: l)). \n       now apply IHl.\n       simpl.\n       case_eq (a<=?z)%Z.\n       proof.\n          intro.\n          absurd ((a<=?z)%Z = true). \n          - rewrite -> not_true_iff_false.\n               now apply Z.leb_gt.\n          - assumption.\n       end proof.\n       intro.\n       reflexivity.\nQed.\n\nLemma dodaj_glavo:\n  forall (x:Z)(l:list Z), pojavi x (x :: l) = S (pojavi x l).\n\nProof.\n  intros x l.\n  simpl.\n  case_eq (x=?x)%Z.\n    - intro. auto.\n    - intro. absurd ((x=?x)%Z = false).\n      + SearchAbout (?A <> false).\n        rewrite -> not_false_iff_true.\n        apply Z.eqb_eq.\n        reflexivity.\n      + assumption.\nQed.\n\nLemma druga_glava:\n   forall (x:Z)(a:Z)(l:list Z), \n          ((x =? a)%Z = false) -> pojavi x l = pojavi x (a :: l).\n\nProof.\n  intros x a l H.\n  simpl.\n  case_eq (x=?a)%Z; intro.\n  - absurd ((x =? a)%Z = false).\n    + rewrite -> not_false_iff_true; assumption.\n    + assumption.\n  - reflexivity.\nQed.\n\nLemma ista_glava:\n   forall (x:Z)(l:list Z)(l':list Z),(pojavi x l)=(pojavi x l') -> pojavi x (x :: l) = pojavi x (x :: l').\n\nProof.\n  intros x l l' H.\n  simpl.\n  case_eq (x =? x)%Z.\n  - intro.\n    apply eq_S.\n    assumption.\n  - intro.\n    assumption.\nQed.\n\nLemma vstavi_pojavitev:\n  forall (x:Z)(l: list Z), S(pojavi x l)= pojavi x (vstavi x l).\n\nProof.\n  induction l.\n  - simpl. case_eq (x=?x)%Z.\n    + intro. auto.\n    + intro. absurd ((x=?x)%Z = false).\n      * SearchAbout (?A <> false).\n        rewrite -> not_false_iff_true.\n        apply Z.eqb_eq.\n        reflexivity.\n      * assumption.\n  - simpl.\n    case_eq (x =? a)%Z.\n    + intro.\n      apply Z.eqb_eq in H.\n      rewrite <- H. \n      case_eq (x <=? x)%Z.\n      * intro.\n        rewrite -> IHl.\n        rewrite -> dodaj_glavo.\n        apply eq_S.\n        rewrite <- IHl. \n        rewrite <- dodaj_glavo.\n        reflexivity.\n      * intro.\n        absurd ((x <=? x)%Z = false).\n        apply not_false_iff_true.\n        apply Z.leb_refl.\n        assumption.\n   + intro.\n     case_eq (x <=? a)%Z. \n     * intro.\n       rewrite <- dodaj_glavo.\n       apply ista_glava.\n       apply druga_glava.\n       assumption.\n     * intro.\n       rewrite -> IHl.\n       apply druga_glava.\n       assumption.\nQed.\n\nLemma vstavi_nepojavitev:\n  forall (x:Z)(a:Z)(l: list Z), (x<>a) -> pojavi x l= pojavi x (vstavi a l).\n \nProof.\n  intros x a l H.\n  induction l.\n  - simpl.\n    case_eq (x =? a)%Z.\n    + intro.\n      rewrite -> Z.eqb_eq in H0.\n      absurd (x=a); auto. \n    + auto.\n  - simpl.\n    case_eq (x =? a)%Z.\n    + intros.\n      absurd (x=a)%Z.\n      * auto.\n      * apply Z.eqb_eq in H0; assumption.\n    + intros.\n      case_eq (x =? a0)%Z.\n      * intros.\n        case_eq (a <=? a0)%Z.\n          intros.\n          rewrite <- druga_glava ; [idtac|assumption].\n          apply Z.eqb_eq in H1.\n          replace  a0 with x. \n          rewrite <- dodaj_glavo; auto.\n        \n          intros.\n          apply Z.eqb_eq in H1.\n          replace  a0 with x.\n          rewrite -> dodaj_glavo. \n          apply eq_S.\n          assumption.\n      * intros.\n        case_eq (a <=? a0)%Z.\n        intros. \n        rewrite <- druga_glava; [idtac | assumption].\n        rewrite <- druga_glava; [auto | assumption].\n    \n        intros.\n        rewrite <- druga_glava; [idtac | assumption].\n        apply IHl.     \nQed.\n    \n\nTheorem permutacija:\n  forall (l: list Z), (permutiran l (insert l)).\nProof.\n  intro.\n  induction l.\n  - firstorder.\n  - intro.\n    simpl.\n    case_eq (x =? a)%Z.\n    + intro.\n      apply Z.eqb_eq in H.\n      replace a with x.\n      replace (pojavi x l) with (pojavi x (insert l)). \n      apply vstavi_pojavitev.\n      apply permutiran_sym.\n      assumption.\n    + intro.  \n      apply Z.eqb_neq in H.\n      replace (pojavi x l) with (pojavi x (insert l)). \n      apply vstavi_nepojavitev; assumption.\n      apply permutiran_sym.\n      assumption.\nQed.\n\nTheorem urejenost:\n  forall (l : list Z), urejen (insert l).\nProof.\n  intro.\n  induction l; firstorder.\n  simpl.\n  apply urejen_t.\n  assumption.\nQed.\n\nTheorem vse_dela_pravilno:\n  forall (l : list Z), urejen (insert l) /\\ permutiran l (insert l).\n\nProof.\n  split; [apply urejenost | apply permutacija].\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nTheorem Mi_smo_najboljsa_skupina:\n      true=true.\nAdmitted.\n(**\"Malo zabave za profesorja. :D\" **).\n\n\n\n\n\n\n\n\n", "meta": {"author": "bezlajk", "repo": "LVR_VEK_coq", "sha": "c842d5193eae0676e08b1287973e6f3610501591", "save_path": "github-repos/coq/bezlajk-LVR_VEK_coq", "path": "github-repos/coq/bezlajk-LVR_VEK_coq/LVR_VEK_coq-c842d5193eae0676e08b1287973e6f3610501591/insurtion_sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7373873245309568}}
{"text": "Require Import Nat Arith Bool.\n\nInductive Nat : Type := zero : Nat | succ : Nat -> Nat.\n\nScheme Equality for Nat.\n\nInductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint less (less_arg0 : Nat) (less_arg1 : Nat) : bool\n           := match less_arg0, less_arg1 with\n              | x, zero => false\n              | zero, succ x => true\n              | succ x, succ y => less x y\n              end.\n\nFixpoint mem (mem_arg0 : Nat) (mem_arg1 : Lst) : bool\n           := match mem_arg0, mem_arg1 with\n              | x, nil => false\n              | x, cons y z => orb (Nat_beq x y) (mem x z)\n              end.\n\nFixpoint insort (insort_arg0 : Nat) (insort_arg1 : Lst) : Lst\n           := match insort_arg0, insort_arg1 with\n              | i, nil => cons i nil\n              | i, cons x y => if less i x then cons i (cons x y) else cons x (insort i y)\n              end.\n\nFixpoint sort (sort_arg0 : Lst) : Lst\n           := match sort_arg0 with\n              | nil => nil\n              | cons x y => insort x (sort y)\n              end.\n\nLemma Nat_beq_refl : forall (n : Nat), Nat_beq n n = true.\nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - assumption.\nQed.\n\nTheorem theorem0 : forall (x : Nat) (y : Lst), eq (mem x (insort x y)) true.\nProof.\n  intros.\n  induction y.\n  - simpl. rewrite Nat_beq_refl. reflexivity.\n  - simpl. destruct (less x n).\n    + simpl. rewrite Nat_beq_refl. reflexivity.\n    + simpl. rewrite IHy. apply orb_true_r.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal45.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7373873206728986}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_NCdistinct.\nRequire Import ProofCheckingEuclid.lemma_betweennotequal.\nRequire Import ProofCheckingEuclid.lemma_congruenceflip.\nRequire Import ProofCheckingEuclid.lemma_congruencesymmetric.\nRequire Import ProofCheckingEuclid.lemma_differenceofparts.\nRequire Import ProofCheckingEuclid.lemma_s_incirc_centre.\nRequire Import ProofCheckingEuclid.lemma_s_incirc_within_radius.\nRequire Import ProofCheckingEuclid.proposition_01.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_02 :\n\tforall A B C,\n\tneq A B -> neq B C ->\n\texists X, Cong A X B C.\nProof.\n\tintros A B C.\n\tintros neq_A_B neq_B_C.\n\tpose proof (proposition_01 _ _ neq_A_B) as (D & equilateral_ABD & Triangle_ABD).\n\tdestruct equilateral_ABD as (Cong_AB_BD & Cong_BD_DA).\n\tapply lemma_congruencesymmetric in Cong_BD_DA as Cong_DA_BD.\n\tapply lemma_congruenceflip in Cong_DA_BD as (_ & _ & Cong_DA_DB).\n\tassert (nCol_A_B_D := Triangle_ABD).\n\tunfold Triangle in nCol_A_B_D.\n\n\tpose proof (postulate_Euclid3 _ _ neq_B_C) as (J & CI_J_B_BC).\n\tapply lemma_NCdistinct in nCol_A_B_D as (\n\t\t_ & neq_B_D & neq_A_D & neq_B_A & neq_D_B & neq_D_A\n\t).\n\n\tpose proof (lemma_s_incirc_centre _ _ _ _ CI_J_B_BC) as InCirc_B_J.\n\tpose proof (\n\t\tpostulate_line_circle _ _ _ _ _ _ CI_J_B_BC InCirc_B_J neq_D_B\n\t) as (_ & G & _ & BetS_D_B_G & _ & OnCirc_G_J & _).\n\n\tpose proof(lemma_betweennotequal _ _ _ BetS_D_B_G) as (neq_B_G & _ & neq_D_G).\n\n\tpose proof (postulate_Euclid3 _ _ neq_D_G) as (R & CI_R_D_DG).\n\tpose proof(axiom_circle_center_radius _ _ _ _ _ CI_J_B_BC OnCirc_G_J) as Cong_BG_BC.\n\n\tpose proof(cn_congruencereflexive D G) as Cong_DG_DG.\n\tpose proof (\n\t\tlemma_s_incirc_within_radius _ _ _ _ _ _ _ CI_R_D_DG BetS_D_B_G Cong_DG_DG Cong_DA_DB\n\t) as InCirc_A_R.\n\n\tpose proof (\n\t\tpostulate_line_circle _ _ _ _ _ _ CI_R_D_DG InCirc_A_R neq_D_A\n\t) as (_ & L & _ & BetS_D_A_L & _ & OnCirc_L_R & _).\n\n\texists L.\n\n\tpose proof(axiom_circle_center_radius _ _ _ _ _ CI_R_D_DG OnCirc_L_R) as Cong_DL_DG.\n\n\tapply lemma_congruencesymmetric in Cong_DA_DB as Cong_DB_DA.\n\tapply lemma_congruencesymmetric in Cong_DL_DG as Cong_DG_DL.\n\tpose proof (\n\t\tlemma_differenceofparts _ _ _ _ _ _ Cong_DB_DA Cong_DG_DL BetS_D_B_G BetS_D_A_L\n\t) as Cong_BG_AL.\n\n\tpose proof (cn_congruencetransitive _ _ _ _ _ _ Cong_BG_AL Cong_BG_BC) as Cong_AL_BC.\n\n\texact Cong_AL_BC.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/proposition_02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.737387320522}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Supplementary Coq material: unification and logic programming\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/\n  * Much of the material comes from CPDT <http://adam.chlipala.net/cpdt/> by the same author. *)\n\nRequire Import Frap.\n\nSet Implicit Arguments.\n\n(** * Introducing Logic Programming *)\n\n(* Recall the definition of addition from the standard library. *)\n\nDefinition real_plus := Eval compute in plus.\nPrint real_plus.\n\n(* Recursive definition :: FP style. *)\n\n(* Inductive relations :: Logic style. *)\nInductive plusR : nat -> nat -> nat -> Prop :=\n| PlusO : forall m, plusR O m m\n| PlusS : forall n m r, plusR n m r -> plusR (S n) m (S r).\n\n(* Recall that Coq will automatically derive the induction principle for \n * inductives. For example: *)\n \nPrint list.\nCheck list_ind.\n\n(* Similarly we have a induction principle for plusR. *)\n\nCheck plusR_ind.\n\n(* Intuitively, a fact [plusR n m r] only holds when [plus n m = r].  It is not\n * hard to prove this correspondence formally. *)\n\nTheorem plus_plusR : forall n m,\n  plusR n m (n + m).\nProof.\n  induct n; simplify.\n\n  (* apply PlusO. *)\n  (* exact (PlusO m). *)\n  constructor.\n  (* [constructor] applies the corresponding constructor definition. *)\n\n  constructor.\n  apply IHn.\nQed.\n\n(* We see here another instance of the very mechanical proof pattern that came\n * up before: keep trying constructors and hypotheses.  The tactic [auto] will\n * automate searching through sequences of that kind, when we prime it with good\n * suggestions of single proof steps to try, as with this command: *)\n\nHint Constructors plusR.\n\n(* That is, every constructor of [plusR] should be considered as an atomic proof\n * step, from which we enumerate step sequences. *)\n\nTheorem plus_plusR_snazzy : forall n m,\n  plusR n m (n + m).\nProof.\n  induct n; simplify; auto.\nQed.\n\nTheorem plusR_plus : forall n m r,\n  plusR n m r\n  -> r = n + m.\nProof.\n  induct 1. \n    (* [induct 1] instructs Coq to perform induction on the first hypothesis \n     of the theorem, which is [plusR n m r]. *) \n  2: {\n    (* Choose the second subgoal to prove first *)\n    simplify; linear_arithmetic.\n  }\n  simplify; linear_arithmetic.\nQed.\n\n(* With the functional definition of [plus], simple equalities about arithmetic\n * follow by computation. *)\n\nExample four_plus_three : 4 + 3 = 7.\nProof.\n  reflexivity.\nQed.\n\nPrint four_plus_three.\n\n(* With the relational definition, the same equalities take more steps to prove,\n * but the process is completely mechanical.  \n \n * For example, consider this\n * simple-minded manual proof search strategy.  The steps prefaced by [Fail] are\n * intended to fail; they're included for explanatory value, to mimic a\n * simple-minded try-everything strategy. *)\n\nExample four_plus_three' : plusR 4 3 7.\nProof.\n  Fail apply PlusO.\n  apply PlusS.\n  Fail apply PlusO.\n  apply PlusS.\n  Fail apply PlusO.\n  apply PlusS.\n  Fail apply PlusO.\n  apply PlusS.\n  apply PlusO.\n\n  (* At this point the proof is completed.  It is no doubt clear that a simple\n   * procedure could find all proofs of this kind for us.  We are just exploring\n   * all possible proof trees, built from the two candidate steps [apply PlusO]\n   * and [apply PlusS].  Thus, [auto] is another great match! *)\nRestart.\n  debug auto.\nQed.\n\nPrint four_plus_three'.\n\n(* Let us try the same approach on a slightly more complex goal. *)\n\nExample five_plus_three : plusR 5 3 8.\nProof.\n  auto.\n\n  (* This time, [auto] is not enough to make any progress.  \n  \n   * Since even a single candidate step may lead to an infinite \n   * space of possible proof trees, [auto] is parameterized on the \n   * maximum depth of trees to consider.  \n   \n   * The default depth is 5, and it turns out that we need depth 6 to prove the\n   * goal. *)\n\n  auto 6.\n  (* Sometimes it is useful to see a description of the proof tree that [auto]\n   * finds, with the [info_auto] variant. *)\n\nRestart.\n  info_auto 6.\nRestart.\n  debug auto 6.\n  (* Also shows failed steps *)\nQed.\n\n(* The two key components of logic programming are \n\n    _backtracking_ and _unification_\n \n * To see these techniques in action, consider this further\n * silly example.  Here our candidate proof steps will be reflexivity and\n * quantifier instantiation. *)\n\nCheck ex_intro.\n\nExample seven_minus_three : exists x, x + 3 = 7.\nProof.\n  (* For explanatory purposes, let us simulate a user with minimal understanding\n   * of arithmetic.  We start by choosing an instantiation for the quantifier.\n   * It is relevant that [ex_intro] is the proof rule for existential-quantifier\n   * instantiation. *)\n\n  apply ex_intro with 0.\n  Fail reflexivity.\n\n  (* This seems to be a dead end.  Let us _backtrack_ to the point where we ran\n   * [apply] and make a better alternative choice. *)\n\nRestart.\n  apply ex_intro with 4.\n  reflexivity.\nQed.\n\n(* The above was a fairly tame example of backtracking. In general, any node in\n * an under-construction proof tree may be the destination of backtracking an\n * arbitrarily large number of times, as different candidate proof steps are\n * found not to lead to full proof trees, within the depth bound passed to [auto].\n *\n * Next we demonstrate unification, which will be easier when we switch to the\n * relational formulation of addition. *)\n\nExample seven_minus_three' : exists x, plusR x 3 7.\nProof.\n  (* We could attempt to guess the quantifier instantiation manually as before,\n   * but here there is no need.  Instead of [apply], we use [eapply], which\n   * proceeds with placeholder _unification variables_ standing in for those\n   * parameters we wish to postpone guessing. *)\n\n  eapply ex_intro.\n  (* [eapply H]: like [apply], but works when it is not obvious how to\n   * instantiate the quantifiers of theorem/hypothesis [H].  Instead,\n   * placeholders are inserted for those quantifiers, to be determined\n   * later. *)\n\n  (* Now we can finish the proof with the right applications of [plusR]'s\n   * constructors.  Note that new unification variables are being generated to\n   * stand for new unknowns. *)\n\n  apply PlusS.\n  apply PlusS. apply PlusS. apply PlusS.\n  apply PlusO.\n\n  (* The [auto] tactic will not perform these sorts of steps that introduce\n   * unification variables, but the [eauto] tactic will.  It is helpful to work\n   * with two separate tactics, because proof search in the [eauto] style can\n   * uncover many more potential proof trees and hence take much longer to\n   * run. *)\n\nRestart.\n  auto 6.\n  info_eauto 6.\nQed.\n\nPrint seven_minus_three'.\n\n(* This proof gives us our first example where logic programming simplifies\n * proof search compared to functional programming.  \n \n * In general, functional programs are only meant to be run in a single\n * direction; a function has disjoint sets of inputs and outputs.\n * In the last example, we effectively ran a logic program backwards, \n * deducing an input that gives rise to a certain output.  \n \n * The same works for deducing an unknown value of the other input. *)\n\nExample seven_minus_four' : exists x y, plusR x y 7 /\\ x <> 0 /\\ y <> 6.\nProof.\n  eauto 8.\nQed.\n\nPrint seven_minus_four'.\n\n(* _Connecting Functional Programs and Logical Proofs_\n\n * By proving the right auxiliary facts, we can reason about specific functional\n * programs in the same way as we did above for a logic program. \n \n * Recall the relational definition of [plusR] *)\n \nPrint plusR.\n\n(* Let us prove that the constructors of [plusR] have natural interpretations \n * as lemmas about [plus]. *)\n\nSearchRewrite (O + _).\n\n(* The command [Hint Immediate] asks [auto] and [eauto] to consider this lemma\n * as a candidate step for any leaf of a proof tree, meaning that all premises\n * of the rule need to match hypotheses. *)\n\nHint Immediate plus_O_n.\n\n(* Proof search will try [simple apply plus_O_n; trivial] whenever it is\n * applicable. *)\n\n(* The counterpart to [PlusS] we will prove ourselves. *)\n\nPrint PlusS.\n\nLemma plusS : forall n m r,\n  n + m = r\n  -> S n + m = S r.\nProof.\n  linear_arithmetic.\nQed.\n\n(* The command [Hint Resolve] adds a new candidate proof step, to be attempted\n * at any level of a proof tree, not just at leaves. *)\n\nHint Resolve plusS.\n\n(* Proof search will try [simple apply plusS] whenever it is applicable. *)\n\n(* Now that we have registered the proper hints, we can replicate our previous\n * examples with the normal, functional addition [plus]. *)\n\nExample seven_minus_three'' : exists x, x + 3 = 7.\nProof.\n  debug eauto 6.\nQed.\n\nExample seven_minus_four : exists x, 4 + x = 7.\nProof.\n  info_eauto 6.\nQed.\n\n(* This new _hint database_ is far from a complete decision procedure, \n * as we see in a further example that [eauto] does not finish. *)\n\nExample seven_minus_four_zero : exists x, 4 + x + 0 = 7.\nProof.\n  debug eauto 6.\nAbort.\n\n(* A further lemma will be helpful. *)\n\nLemma plusO : forall n m,\n  n = m\n  -> n + 0 = m.\nProof.\n  linear_arithmetic.\nQed.\n\nHint Resolve plusO.\n\n(* Note that, if we consider the inputs to [plus] as the inputs of a\n * corresponding logic program, the new rule [plusO] introduces an ambiguity. *)\n\nCheck plus_O_n.\nCheck plusO.\n\n(* For instance, a sum [0 + 0] would match both of [plus_O_n] and [plusO],\n * depending on which operand we focus on.  This ambiguity may increase the\n * number of potential search trees, slowing proof search, but semantically it\n * presents no problems, and in fact it leads to an automated proof of the\n * present example. *)\n\nExample seven_minus_four_zero : exists x, 4 + x + 0 = 7.\nProof.\n  info_eauto 7.\nQed.\n\n(* Just how much damage can be done by adding hints that grow the space of\n * possible proof trees?  A classic gotcha comes from unrestricted use of\n * transitivity, as embodied in this library theorem about equality: *)\n\nCheck eq_trans.\n\n(* Hints are scoped over sections, so let us enter a section to contain the\n * effects of an unfortunate hint choice. *)\n\nSection slow.\n  Hint Resolve eq_trans.\n\n  (* The following fact is false, but that does not stop [eauto] from taking a\n   * very long time to search for proofs of it.  We use the handy [Time] command\n   * to measure how long a proof step takes to run.  None of the following steps\n   * make any progress. *)\n\n  Example zero_minus_one : exists x, 1 + x = 0.\n    Time eauto 1.\n    Time eauto 2.\n    Time eauto 3.\n    Time eauto 4.\n    Time eauto. (* 5 *)\n\n    (* We see worrying exponential growth in running time, and the [debug]\n     * tactical helps us see where [eauto] is wasting its time, outputting a\n     * trace of every proof step that is attempted.  The rule [eq_trans] applies\n     * at every node of a proof tree, and [eauto] tries all such positions. *)\n\n    debug eauto 4.\n  Abort.\nEnd slow.\n\n(* Sometimes, though, transitivity is just what is needed to get a proof to go\n * through automatically with [eauto].  For those cases, we can use named\n * _hint databases_ to segregate hints into different groups that may be called\n * on as needed.  Here we put [eq_trans] into the database [slow]. *)\n\nHint Resolve eq_trans : slow.\n\nExample from_one_to_zero : exists x, 1 + x = 0.\nProof.\n  Time eauto.\n  (* This [eauto] fails to prove the goal, but at least it takes substantially\n   * less than the ~1.2 seconds required above! *)\nAbort.\n\n(* When we _do_ need transitivity, we ask for it explicitly. *)\n\nExample needs_trans : forall x y, 1 + x = y\n  -> y = 2\n  -> exists z, z + x = 3.\nProof.\n  info_eauto with slow.\nRestart.\n  intro.\nintro.\nintro.\nintro.\nsimple eapply ex_intro.\n simple apply plusS.\n  simple eapply eq_trans.\n   exact H.\n   exact H0.\nQed.\n\n(** * Searching for Underconstrained Values *)\n\n(* Recall the definition of the list length function. *)\n\nPrint Datatypes.length.\n\n(* This function is easy to reason about in the forward direction, computing\n * output from input. *)\n\nExample length_1_2 : length (1 :: 2 :: nil) = 2.\nProof.\n  info_auto.\nQed.\n\nPrint length_1_2.\n\n(* As in the last section, we will prove some lemmas to recast [length] in\n * logic-programming style, to help us compute inputs from outputs. *)\n \n(* Here is the relational definition of length *)\nInductive lengthR {A : Type} : list A -> nat -> Prop :=\n| lengthO : lengthR nil 0\n| lengthS : forall h t n, lengthR t n -> lengthR (h::t) (S n).\n\n(* As before, connect the logical version to the similar \n * functional version *)\nTheorem length_O : forall A, length (@nil A) = O.\nProof.\n  simplify; equality.\nQed.\n\nTheorem length_S : forall A (h : A) t n,\n  length t = n\n  -> length (h :: t) = S n.\nProof.\n  simplify; equality.\nQed.\n\nHint Resolve length_O length_S.\n\n(* Let us apply these hints to prove that a [list nat] of length 2 exists.\n * (Here we register [length_O] with [Hint Resolve] instead of [Hint Immediate]\n * merely as a convenience to use the same command as for [length_S]; [Resolve]\n * and [Immediate] have the same meaning for a premise-free hint.) *)\n\nExample length_is_2 : exists ls : list nat, length ls = 2.\nProof.\n  eauto.\n\n  (* Coq leaves for us two subgoals to prove... [nat]?!  We are being asked to\n   * show that natural numbers exists.  Why?  Some unification variables of that\n   * type were left undetermined, by the end of the proof.  Specifically, these\n   * variables stand for the 2 elements of the list we find.  Of course it makes\n   * sense that the list length follows without knowing the data values.  In Coq\n   * 8.6, the [Unshelve] command brings these goals to the forefront, where we\n   * can solve each one with [exact O], but usually it is better to avoid\n   * getting to such a point.\n   *\n   * To debug such situations, it can be helpful to print the current internal\n   * representation of the proof, so we can see where the unification variables\n   * show up. *)\n\n  Show Proof.\nAbort.\n\n(* Paradoxically, we can make the proof-search process easier by constraining\n * the list further, so that proof search naturally locates appropriate data\n * elements by unification.  The library predicate [Forall] will be helpful. *)\n\nCheck Forall.\n\nExample length_is_2 : exists ls : list nat, length ls = 2\n  /\\ Forall (fun n => n >= 0) ls.\nProof.\n  eauto 9.\nQed.\n\n(* We can see which list [eauto] found by printing the proof term. *)\n\nPrint length_is_2.\n\n(* The elements chosen for the list is [0] *)\n\n(* Let us try one more, fancier example.  First, we use a standard higher-order\n * function to define a function for summing all data elements of a list. *)\n\nDefinition sum := fold_right plus O.\n\n(* Another basic lemma will be helpful to guide proof search. *)\n\nCheck plusO.\n\nLemma plusO' : forall n m,\n  n = m\n  -> 0 + n = m.\nProof.\n  linear_arithmetic.\nQed.\n\nHint Resolve plusO'.\n\n(* Finally, we meet [Hint Extern], the command to register a custom hint.  That\n * is, we provide a pattern to match against goals during proof search.\n * Whenever the pattern matches, a tactic (given to the right of an arrow [=>])\n * is attempted.  Below, the number [1] gives a priority for this step.  Lower\n * priorities are tried before higher priorities, which can have a significant\n * effect on proof search time, i.e. when we manage to give lower priorities to\n * the cheaper rules. *)\n\nHint Extern 1 (sum _ = _) => simplify.\n\n(* Now we can find a length-2 list whose sum is 0. *)\n\nExample length_and_sum : exists ls : list nat, length ls = 2\n  /\\ sum ls = O.\nProof.\n  info_eauto 7.\nRestart.\nsimple eapply ex_intro.\n simple apply conj.\n  simple apply length_S.\n   simple apply length_S.\n    simple apply length_O.\n    (*external*) simplify.\n     simple apply plusO'.\n      simple apply plus_O_n ; trivial.\nQed.\n\nPrint length_and_sum.\n\n(* Printing the proof term shows the unsurprising list that is found.  Here is\n * an example where it is less obvious which list will be used.  Can you guess\n * which list [eauto] will choose? *)\n\nExample length_and_sum' : exists ls : list nat, length ls = 5\n  /\\ sum ls = 42.\nProof.\n  eauto 15.\nQed.\n\nPrint length_and_sum'.\n\n(* We will give away part of the answer and say that the above list is less\n * interesting than we would like, because it contains too many zeroes.  A\n * further constraint forces a different solution for a smaller instance of the\n * problem. *)\n\nExample length_and_sum'' : exists ls : list nat, length ls = 2\n  /\\ sum ls = 3\n  /\\ Forall (fun n => n <> 0) ls.\nProof.\n  eauto 11.\nQed.\n\nPrint length_and_sum''.\n\n(* We could continue through exercises of this kind, but even more interesting\n * than finding lists automatically is finding _programs_ automatically. *)\n\n\n(** * Synthesizing Programs *)\n\n(* Here is a simple syntax type for arithmetic expressions, similar to those we\n * have used several times before.  In this case, we allow expressions to\n * mention exactly one distinguished variable. *)\n\nInductive exp : Set :=\n| Const (n : nat)\n| Var\n| Plus (e1 e2 : exp).\n\n(* An inductive relation specifies the semantics of an expression, relating a\n * variable value and an expression to the expression value. *)\n\nInductive eval (var : nat) : exp -> nat -> Prop :=\n| EvalConst : forall n, eval var (Const n) n\n| EvalVar : eval var Var var\n| EvalPlus : forall e1 e2 n1 n2, \n       eval var e1 n1\n    -> eval var e2 n2\n    -> eval var (Plus e1 e2) (n1 + n2).\n\nHint Constructors eval.\n\n(* We can use [auto] to execute the semantics for specific expressions. *)\n\nExample eval1 : forall var, \n  eval var (Plus Var (Plus (Const 8) Var)) \n           (var + (8 + var)).\nProof.\n  info_eauto.\nRestart.\nintro.\nsimple apply EvalPlus.\n simple apply EvalVar.\n simple apply EvalPlus.\n  simple apply EvalConst.\n  simple apply EvalVar.\nQed.\n\n(* Unfortunately, just the constructors of [eval] are not enough to prove\n * theorems like the following, which depends on an arithmetic identity. *)\n\nExample eval1' : forall var, \n  eval var (Plus Var (Plus (Const 8) Var)) \n           (2 * var + 8).\nProof.\n  eauto.\nRestart.\n  intros.\n  apply EvalPlus.\n   (* cannot proceed further *)\nAbort.\n\n(* To help prove [eval1'], we prove an alternative version of [EvalPlus] that\n * inserts an extra equality premise.  This sort of staging is helpful to get\n * around limitations of [eauto]'s unification. \n \n * With the alternative version below, to prove the first\n * two premises, [eauto] is given free reign in deciding the values of [n1] and\n * [n2], while the third premise can then be proved by [reflexivity], no matter\n * how each of its sides is decomposed as a tree of additions. *)\n\nCheck EvalPlus.\n\nTheorem EvalPlus' : forall var e1 e2 n1 n2 n, \n     eval var e1 n1\n  -> eval var e2 n2\n  -> n1 + n2 = n\n  -> eval var (Plus e1 e2) n.\n  (* One way to think about this is that we're extending the\n     evaluator with more rules. *)\nProof.\n  simplify.\n  subst.\n  auto.\nQed.\n\nHint Resolve EvalPlus'.\n\n(* Further, we instruct [eauto] to apply [ring], via [Hint Extern].  We should\n * try this step for any equality goal. *)\n\nSection use_ring.\n  Hint Extern 1 (_ = _) => ring.\n\n  (* Now we can return to [eval1'] and prove it automatically. *)\n\n  Example eval1' : forall var, \n    eval var (Plus Var (Plus (Const 8) Var)) \n             (2 * var + 8).\n  Proof.\n    info_eauto.\n  Restart.\n  intro.\n  simple eapply EvalPlus'.\n   simple apply EvalVar.\n   simple apply EvalPlus.\n    simple apply EvalConst.\n    simple apply EvalVar.\n    (*external*) ring.\n  Qed.\n\n  (* Now we are ready to take advantage of logic programming's flexibility by\n   * searching for a program (arithmetic expression) that always evaluates to a\n   * particular symbolic value. *)\n\n  Example synthesize1 : exists e, forall var, eval var e (var + 7).\n  Proof.\n    eauto.\n  Qed.\n\n  Print synthesize1.\n\n  (* Here are two more examples showing off our program-synthesis abilities. *)\n\n  Example synthesize2 : exists e, forall var, \n    eval var e (2 * var + 8).\n  Proof.\n    eauto.\n  Qed.\n\n  Print synthesize2.\n\n  Example synthesize3 : exists e, forall var, \n    eval var e (3 * var + 42).\n  Proof.\n    eauto.\n  Qed.\n\n  Print synthesize3.\nEnd use_ring.", "meta": {"author": "kayceesrk", "repo": "cs6225_s21_iitm", "sha": "791faaf1a8a0981d6221be2897007fcdd4eac31c", "save_path": "github-repos/coq/kayceesrk-cs6225_s21_iitm", "path": "github-repos/coq/kayceesrk-cs6225_s21_iitm/cs6225_s21_iitm-791faaf1a8a0981d6221be2897007fcdd4eac31c/lectures/LogicProgramming_lecture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964035, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7373484785770791}}
{"text": "Require Import List. \nRequire Import Peano_dec.\n\nFixpoint upto_aux m m' n {struct n} : list nat := \n  match n with \n    | 0 => nil \n    | (S n') => \n      match eq_nat_dec n m' with\n        | left _ => nil\n        | right _ => m::(upto_aux (S m) m' n')\n      end\n  end.\n      \nDefinition upto m n := upto_aux m m n. \n\nFixpoint downto m n {struct m} : list nat := \n  match eq_nat_dec m n with \n    | left _ => nil\n    | right _ => \n      match m with \n        | 0 => nil \n        | (S m') => m::(downto m' n)\n      end      \n  end. \n\nRequire Import Ascii.\n\nInductive digit : Set := Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine.\nDefinition base10 := list digit.\n\nFixpoint base10_inc (xs : base10) := \n  match xs with \n    | nil => cons One nil\n    | cons x xs' => \n      match x with \n        | Zero => cons One xs'\n        | One => cons Two xs'\n        | Two => cons Three xs'\n        | Three => cons Four xs'\n        | Four => cons Five xs'\n        | Five => cons Six xs'\n        | Six => cons Seven xs'\n        | Seven => cons Eight xs'\n        | Eight => cons Nine xs'\n        | Nine => cons Zero (base10_inc xs')\n      end\n  end.\n\nFixpoint base10_of_nat (n:nat) := \n  match n with \n    | 0 => cons Zero nil\n    | S n' => base10_inc (base10_of_nat n')\n  end.\n\nDefinition nat_of_digit (d:digit) := \n  match d with \n    | Zero => 0\n    | One => S(0)\n    | Two => S(S(0))\n    | Three => S(S(S(0)))\n    | Four => S(S(S(S(0))))\n    | Five => S(S(S(S(S(0)))))\n    | Six => S(S(S(S(S(S(0))))))\n    | Seven => S(S(S(S(S(S(S(0)))))))\n    | Eight => S(S(S(S(S(S(S(S(0))))))))\n    | Nine => S(S(S(S(S(S(S(S(S(0)))))))))\n  end.\n  \nFixpoint nat_of_base10 (b:base10) := \n  match b with \n    | nil => 0\n    | cons d ds => (nat_of_digit d) + (10 * (nat_of_base10 ds))\n  end.\n\nRequire Import String.\nOpen Local Scope char_scope.\nDefinition string_of_digit (d : digit) := \n  match d with \n    | Zero => \"0\"\n    | One => \"1\"\n    | Two => \"2\"\n    | Three => \"3\"\n    | Four => \"4\"\n    | Five => \"5\"\n    | Six => \"6\"\n    | Seven => \"7\"\n    | Eight => \"8\"\n    | Nine => \"9\"\n  end.      \n\nOpen Local Scope string_scope.\nFixpoint string_of_base10_aux (ds : base10) := \n  match ds with \n    | nil => \"\"\n    | cons d ds' => String (string_of_digit d) (string_of_base10_aux ds') \n  end.\n\nDefinition string_of_base10 (ds : base10) := string_of_base10_aux (rev ds).\n\nDefinition string_of_nat (n:nat) := string_of_base10 (base10_of_nat n).\n\nRequire Import OptionMonad.\nOpen Scope char_scope.\n\nFixpoint base10_of_string_aux (s:string) : option base10 :=\n  match s with\n    | EmptyString => Some (A:=base10) nil\n    | String c s' => \n      match c with \n        | \"0\" => t <- (base10_of_string_aux s') ;; ret (cons Zero t)\n        | \"1\" => t <- (base10_of_string_aux s') ;; ret (cons One t) \n        | \"2\" => t <- (base10_of_string_aux s') ;; ret (cons Two t) \n        | \"3\" => t <- (base10_of_string_aux s') ;; ret (cons Three t) \n        | \"4\" => t <- (base10_of_string_aux s') ;; ret (cons Four t) \n        | \"5\" => t <- (base10_of_string_aux s') ;; ret (cons Five t) \n        | \"6\" => t <- (base10_of_string_aux s') ;; ret (cons Six t) \n        | \"7\" => t <- (base10_of_string_aux s') ;; ret (cons Seven t) \n        | \"8\" => t <- (base10_of_string_aux s') ;; ret (cons Eight t) \n        | \"9\" => t <- (base10_of_string_aux s') ;; ret (cons Nine t) \n        | _ => None (A:=base10)\n      end\n  end.\n\nDefinition base10_of_string (s:string) := l <- (base10_of_string_aux s) ;; ret (rev l).\n\nDefinition nat_of_string (s:string) := x <- (base10_of_string s) ;; ret (nat_of_base10 x).\n\nNotation \"A || B\" := (if A then true else (if B then true else false)).\nNotation \"A && B\" := (if A then (if B then true else false) else false).\nNotation \"! A\" := (if A then false else true) (at level 10).\n\nDefinition compose `A B C` (f : B -> C) (g : A -> B) :=\n  (fun (x:A) => f (g x)).\nImplicit Arguments compose [A B C]. \nInfix \"o\" := compose (at level 20).\n\nDefinition uncurry `A B C` (f : A -> B -> C) (p : A * B) : C.\nProof. \n  firstorder.\nDefined.\n\nFixpoint foldr (A B : Type) (f : A -> B -> B) (zero : B) (l : list A) : B := \n  match l with \n    | nil => zero\n    | cons h t => (f h (foldr A B f zero t))\n  end.\nImplicit Arguments foldr [A B]. \n\nFixpoint foldl (A B : Type) (f : A -> B -> B) (zero : B) (l : list A) : B := \n  match l with \n    | nil => zero\n    | cons h t => foldl A B f (f h zero) t\n  end.\nImplicit Arguments foldl [A B]. \n\nFixpoint map (A B : Type) (f : A -> B) (l : list A) : list B := \n  match l with \n    | nil => nil \n    | cons h t => cons (f h) (map A B f t)\n  end.\n\nFixpoint assoc (A B :Type) (f : A -> bool) (l : list (A*B)) : option B := \n  match l with \n    | nil => None \n    | cons h t => \n      match h with \n        | (k,v) => \n          if f k \n            then Some v\n            else assoc A B f t\n      end\n  end.\nImplicit Arguments assoc [A B]. \n\nTheorem pair_eq_dec : forall (A B:Type), \n  (forall (a a':A), {a = a'} + {a <> a'}) -> \n  (forall (b b':B), {b = b'} + {b <> b'}) -> \n  (forall (c c':A*B), {c = c'} + {c <> c'}).\nProof.\n  decide equality.\nDefined.\nImplicit Arguments pair_eq_dec [A B].\n\nFixpoint zip (A B:Type) (l:list A) (l':list B) : option (list (A*B)):= \n  match l, l' with \n    | nil, nil => Some nil\n    | cons h t, cons h' t' => \n      match zip A B t t' with\n        | None => None \n        | Some a => Some (cons (h,h') a)\n      end\n    | _,_ => None\n  end.\n\nFixpoint iter (A:Type) (f:A->A) (zero:A) (n:nat) {struct n} : A := \n  match n with \n    | 0 => zero\n    | S n' => f (iter A f zero n')\n  end.\n\n(* This gives us an `In' predicate that uses decidable equality so is useable for both Type and Set, and not just Prop *)\nDefinition Member : forall (A : Type) (eq_dec : forall (a b:A), {a = b} + {a <> b}) (a : A) (l : list A), Prop.\n  intros A eq_dec.\n  refine \n    (fix Member (a : A) (l : list A) {struct l} : Prop :=\n      match l with\n        | nil => False\n        | b :: m => match eq_dec a b with \n                      | left p => True\n                      | right p => Member a m\n                    end\n      end) ; try (right ; clear Member ; auto ; fail).\nDefined.\nImplicit Arguments Member [A].\n\nLemma member_imp_in : forall A (x:A) l eq_dec, Member eq_dec x l -> In x l. \nProof.\n  induction l. intros. inversion H. intros. simpl in H. case_eq (eq_dec x a). \n  intros. rewrite e. firstorder.\n  intros. rewrite H0 in H. simpl. right. eapply IHl. eauto.  \nDefined.\n\nLemma in_imp_member : forall A (x:A) l eq_dec, In x l -> Member eq_dec x l.\nProof.\n  induction l. intros. inversion H. intros. simpl in H. inversion H.\n  simpl. case_eq (eq_dec x a). intros. auto. intros. congruence.\n  simpl. case_eq (eq_dec x a). intros. auto. intros. \n  apply IHl. auto.\nDefined.\n \nRequire Import List.\nFixpoint Prefix `A` (l:list A) (l':list A) : Prop := \n  match l' with \n    | nil => False \n    | cons h' t' => \n      match l with \n        | nil => True \n        | cons h t => h = h' /\\ Prefix A t t'\n      end\n  end.\n\nLemma prefix_correct : forall A (a:A) (l:list A) (l':list A), Prefix l l' -> exists l'':list A, l++l''=l'.\nProof.\n  induction l. intros. exists l'. auto.\n  intros. simpl in H. destruct l'. inversion H.\n  inversion H. rewrite H0. apply IHl in H1. inversion H1.\n  exists x. rewrite <- H2. auto. \nDefined.   \n\n(* \nInductive Suffix A (l':list A) : list A -> Prop := \n| suffix_same : forall (a:A) (l:list A), l' = l -> Suffix A l' (cons a l)\n| suffix_next : forall (a:A) (l:list A), Suffix A l' l -> Suffix A l' (cons a l).\nImplicit Arguments Suffix [A]. \n*)\n\nFixpoint Suffix `A` (l:list A) (l':list A) : Prop := \n  match l' with \n    | nil => False \n    | cons h' t' => l = t' \\/ Suffix A l t'\n  end.\n\n(* Definition Suffix `A` (l:list A) (l':list A) := Prefix (rev l) (rev l'). *)\n\nLemma suffix_correct : forall A (l':list A) (l:list A), Suffix l l' -> exists l'':list A, l'' <> nil /\\ l''++l=l'.\nProof.\n  induction l'. intros. inversion H.\n  intros. simpl in H. destruct l. exists (a::l'). split. congruence. rewrite app_nil_end. auto. inversion H. rewrite H0. \n  exists (a::nil). auto. split. congruence.\n  firstorder.\n  apply IHl' in H0. inversion H0.\n  exists (a::x). simpl. split. congruence. inversion H1. subst. auto.\nDefined.\n\nLemma prefix_smaller : forall A (l:list A) (l':list A), Prefix l l' -> length l < length l'. \nProof.\n  induction l ; destruct l'; firstorder ; simpl ; auto with arith.\nDefined.\n\nLemma suffix_smaller : forall A (l:list A) (l':list A), Suffix l l' -> length l < length l'.\nProof.\n  intros A l l'. generalize dependent l. generalize dependent l'.\n  induction l' ; destruct l ; firstorder simpl in * ; subst ; auto with arith.\nDefined.\n\nLemma suffix_one : forall A (l l':list A) (a:A), Suffix (cons a l') l -> Suffix l' l.\nProof.\n  intros. induction l. inversion H.\n  simpl. inversion H. subst. right. simpl. auto.\n  right. apply IHl. auto.\nDefined. \n\nLemma suffix_nil : forall A (l:list A) (a:A), Suffix nil (cons a l).\nProof. \n  induction l. simpl. left. auto.\n  intros. simpl in *. right. apply IHl. auto.\nDefined.\n\nLemma suffix_not_nil : forall A (l l':list A), Suffix l l' -> l' <> nil.\nProof.\n  intros. destruct l'. inversion H. unfold not. intros. inversion H0.\nDefined.\n\nLemma suffix_app : forall A (l x:list A), x <> nil -> Suffix l (x ++ l). \nProof.\n  intros. induction x. congruence.  \n  simpl. destruct x. left. simpl. auto.\n  simpl. right. simpl in IHx. apply IHx. congruence.\nDefined.\n\nLemma suffix_trans : forall A (l l' l'':list A), Suffix l' l -> Suffix l'' l' -> Suffix l'' l.\nProof.\n  intros A l l' l'' H H0. cut (Suffix l' l) ; auto ; intros H1. apply suffix_not_nil in H1. \n  apply suffix_correct in H ; apply suffix_correct in H0.\n  destruct H. destruct H0. destruct H ; destruct H0. subst.\n  rewrite <- app_ass in *. apply suffix_app. \n  destruct x ; destruct x0 ; try (congruence).\n  simpl. firstorder.\nDefined.\n\nLemma Suffix_acc : forall A (l:list A), Acc Suffix l.\nProof. \n  induction l. \n  constructor. intros. inversion H.\n  constructor. intros. inversion H. subst. auto.\n  eapply Acc_inv. eauto. auto.\nDefined. \n\nTheorem Suffix_wf : forall A, well_founded (Suffix (A:=A)).\nProof.\n  intros. exact (Suffix_acc A).\nDefined.\n\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/poitin-coq/MyUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7373484724292817}}
{"text": "Require Import ssreflect ssrbool eqtype ssrnat.\n\n(**\n# 第8回\n\nhttp://qnighy.github.io/coqex2014/ex6.html\n\n## 課題37 (別解）\n\n自然数の対の商集合として整数を定義する。下の証明の空欄を埋めよ。\nomega等を使ってもよい。\n\nオリジナルの出題は SetoidClass を使用しているが、それを使わない場合。\n「Add Parametric Relation : int equiv」を使う。\n\n参考：\nhttp://d.hatena.ne.jp/m-a-o/20110112\nhttp://sssslide.com/www.slideshare.net/tmiya/coq-setoid-20110129\n*)\n\nRequire Import Setoid.                      (* !!! *)\n\nRecord int :=\n  {\n    Ifst : nat;\n    Isnd : nat\n  }.\n\nDefinition equiv (x y : int) :=             (* == *)\n  Ifst x + Isnd y = Ifst y + Isnd x.\n\nNotation \"x == z\" := (equiv x z) (at level 70).\n\n(* equivがint上の同値関係である事を証明する。 *)\t \nLemma equiv_refl : reflexive int equiv.\nProof.\n  by rewrite /reflexive.\nQed.\n\nLemma equiv_sym : symmetric int equiv.\nProof.\n  by rewrite /symmetric.\nQed.\n\nLemma addn2r p m n : (m + p = n + p) -> (m = n).\nProof.\n  move/eqP => H.\n  apply/eqP.\n  by rewrite -(eqn_add2r p).\nQed.\n\nLemma equiv_trans : transitive int equiv.\nProof.\n  rewrite /transitive.\n  rewrite /equiv.\n  move=> x y z.\n  move=> Hxy Hyz.\n  apply (addn2r (Ifst y + Isnd y)).\n  rewrite !addnA.\n  rewrite [Ifst x + Isnd z + Ifst y + Isnd y]addnC.\n  rewrite [Ifst z + Isnd x + Ifst y + Isnd y]addnC.\n  rewrite !addnA.\n  rewrite [Isnd y + Ifst x]addnC.\n  rewrite [Isnd y + Ifst z]addnC.\n  rewrite Hxy.\n  rewrite -Hyz.\n  rewrite [Ifst y + Isnd z + Isnd x + Ifst y]addnC.\n  rewrite [Ifst y + Isnd z + Isnd x]addnC.\n  rewrite [Ifst y + Isnd z]addnC.\n  rewrite !addnA.\n  by [].\nQed.\n\n(* int equiv が Setoid であることを登録す。 *)\t \nAdd Parametric Relation : int equiv\n    reflexivity  proved by equiv_refl\n    symmetry     proved by equiv_sym\n    transitivity proved by equiv_trans as ISetoid.\n\nDefinition zero : int :=\n  {|\n    Ifst := 0;\n    Isnd := 0\n  |}.\n\nDefinition int_plus (x y : int) : int :=\n  {|\n    Ifst := Ifst x + Ifst y;\n    Isnd := Isnd x + Isnd y\n  |}.\n\nDefinition int_minus (x y : int) : int :=\n  {|\n    Ifst := Ifst x + Isnd y;\n    Isnd := Isnd x + Ifst y\n  |}.\n\nAdd Parametric Morphism : int_plus with\n  signature (equiv ==> equiv ==> equiv) as int_plus_compat.\nProof.\n  move=> x y Hxy x' y' Hx'y'.\n  rewrite /int_plus /equiv /=.\n\n  have Hxy2 : (Ifst x + Isnd y = Ifst y + Isnd x) by apply Hxy.\n  have Hx'y'2 : (Ifst x' + Isnd y' = Ifst y' + Isnd x') by apply Hx'y'.\n  \n  rewrite 2!addnA.\n  rewrite -[Ifst x + Ifst x' + Isnd y]addnA.\n  rewrite [Ifst x' + Isnd y]addnC.\n  rewrite addnA.\n  rewrite Hxy2.  \n  rewrite -[(Ifst y + Isnd x) + Ifst x' + Isnd y']addnA.\n  rewrite Hx'y'2.\n  rewrite addnA.\n  rewrite -[Ifst y + Isnd x + Ifst y']addnA.\n  rewrite [Isnd x + Ifst y']addnC.\n  rewrite addnA.\n  by [].\nQed.\n\nAdd Parametric Morphism : int_minus with\n  signature (equiv ==> equiv ==> equiv) as int_minus_compat.\nProof.\n  move=> x y Hxy x' y' Hx'y'.\n  rewrite /int_minus /equiv /=.\n\n  have Hxy2 : (Ifst x + Isnd y = Ifst y + Isnd x) by apply Hxy.\n  have Hx'y'2 : (Ifst x' + Isnd y' = Ifst y' + Isnd x') by apply Hx'y'.\n  \n  rewrite 2!addnA.\n  rewrite [Ifst x + Isnd x' + Isnd y]addnC.\n  rewrite [Ifst y + Isnd y' + Isnd x]addnC.\n  rewrite 2!addnA.\n  rewrite [Isnd y + Ifst x]addnC.\n  rewrite -addnA.\n  rewrite [Isnd x' + Ifst y']addnC.\n  rewrite [Isnd x + Ifst y]addnC.\n  rewrite -Hx'y'2.\n  rewrite -Hxy2.\n  rewrite -[(Ifst x + Isnd y) + Isnd y' + Ifst x']addnA.\n  rewrite [Isnd y' + Ifst x']addnC.\n  by [].\nQed.\n\nLemma int_sub_diag : forall x, int_minus x x == zero.\nProof.\n  move=> x.\n  rewrite /equiv.\n  rewrite /int_minus.\n  by rewrite addn0 add0n addnC.\nQed.\n\n(* まず、int_minus_compatを証明せずに、下の2つの証明を実行して、どちらも失敗することを確認せよ。*)\n(* 次に、int_minus_compatを証明し、下の2つの証明を実行せよ。 *)\n\n\n(* rewrite と setoid_rewrite は SetoidClassと同様に使える。 *)\n\nGoal forall x y, int_minus x (int_minus y y) == int_minus x zero.\nProof.\n  intros x y.\n  rewrite int_sub_diag.\n  reflexivity.\nQed.\n\nGoal forall x y, int_minus x (int_minus y y) == int_minus x zero.\nProof.\n  intros x y.\n  setoid_rewrite int_sub_diag.\n  reflexivity.\nQed.\n\n(**\n\nおまけ : ISetoidの定義においてProgram InstanceをInstanceに変更し、Next Obligation. を取り除\nいてもISetoidは定義できるが、続きがうまくいかなくなる。これは何故か？\n\nヒント\n\n通常のイコール (Coq.Init.Logic.eq) 以外の同値関係を入れたい場合、Setoidを使います。Setoidに\nよる書き換えは、通常rewriteで行えます。明示的にSetoidを使う場合は、setoid_rewriteを使います。\n\nSetoidによってreplaceを行いたい場合はsetoid_replaceを使えます。通常のイコールと違い、\nSetoidの同値関係を保存しない写像が存在する可能性があります。例えば、この問題におけるIfst関\n数はSetoidの同値関係を保存しません。Setoidによる書き換えを行うためには、それぞれの関数が同\n値関係を保存することを逐一証明する必要があります。\n\nRecordは単一のコンストラクタを持ち再帰的でない型を定義するのに使えるコマンドです。メンバを\n取り出す関数(この例ではIfst, Isnd)が自動的に定義されることや、{| ... |} という構文でRecord\n型の値を記述できるという利点があります。\n*)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/ex2014/ex37_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7373484524020757}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) : natural :=\n  mult lf2 (plus x Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj196_coqofml_IcyzVT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7373097474808377}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) : natural :=\n  mult lf2 (plus y Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj53_coqofml_1w5mRV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7373097359363108}}
{"text": "(**\nHere we define the category of join semilattices using the mechanism of algebras.\n *)\nRequire Import prelude.all.\nRequire Import syntax.hit_signature.\nRequire Import syntax.hit.\nRequire Import syntax.hit_properties.\nRequire Import algebras.set_algebra.\nRequire Import existence.hit_existence.\nRequire Import displayed_algebras.displayed_algebra.\nRequire Import examples.free.\n\nOpen Scope cat.\n\nOpaque HIT_exists hit_ind hit_ind_prop hit_rec.\n\n(** We first define the signature. *)\n\n(** Operations *)\nDefinition semilattice_operations\n  : poly_code\n  := (I * I) (* join *)\n     + C unitset (* empty *).\n\n(** Labels of group axioms *)\nInductive semilattice_ax :=\n| nl : semilattice_ax\n| idem : semilattice_ax\n| com : semilattice_ax\n| assoc : semilattice_ax.\n\n(** Arguments for each label *)\nDefinition semilattice_arg\n  : semilattice_ax → poly_code\n  := fun j =>\n       match j with\n       | nl => I\n       | idem => I\n       | com => I * I\n       | assoc => I * I * I\n       end.\n\n(** Some convenient notation for the constructor terms. These represent the operations.\n    For the signature, we call the operation `join`.\n*)\nDefinition join_e\n           {P : poly_code}\n           (e₁ e₂ : endpoint semilattice_operations P I)\n  : endpoint semilattice_operations P I.\nProof.\n  refine (comp _ constr).\n  refine (comp _ (ι₁ _ _)).\n  exact (pair e₁ e₂).\nDefined.\n\nDefinition empty_e\n           {P : poly_code}\n  : endpoint semilattice_operations P I.\nProof.\n  refine (comp _ constr).\n  refine (comp _ (ι₂ _ _)).\n  apply c.\n  exact tt.\nDefined.\n\n(** The left hand side of each equation *)\nDefinition semilattice_lhs\n  : ∏ (j : semilattice_ax), endpoint semilattice_operations (semilattice_arg j) I.\nProof.\n  induction j ; cbn.\n  - refine (join_e _ _). (* nl *)\n    + exact empty_e.\n    + exact (id_e _ _).\n  - refine (join_e _ _). (* idem *)\n    + exact (id_e _ _).\n    + exact (id_e _ _).\n  - refine (join_e _ _). (* com *)\n    + exact (π₁ _ _).\n    + exact (π₂ _ _).\n  - refine (join_e (join_e _ _) _). (* assoc *)\n    + exact (comp (π₁ _ _) (π₁ _ _)).\n    + exact (comp (π₁ _ _) (π₂ _ _)).\n    + exact (π₂ _ _).\nDefined.\n\n(** The right hand side of each equation *)\nDefinition semilattice_rhs\n  : ∏ (j : semilattice_ax), endpoint semilattice_operations (semilattice_arg j) I.\nProof.\n  induction j ; cbn.\n  - exact (id_e _ _). (* nl *)\n  - exact (id_e _ _). (* idem *)\n  - refine (join_e _ _). (* com *)\n    + exact (π₂ _ _).\n    + exact (π₁ _ _).\n  - refine (join_e _ (join_e _ _)). (* assoc *)\n    + exact (comp (π₁ _ _) (π₁ _ _)).\n    + exact (comp (π₁ _ _) (π₂ _ _)).\n    + exact (π₂ _ _).\nDefined.\n\n(** The signature of ring as a HIT signature *)\nDefinition semilattice_signature\n  : hit_signature.\nProof.\n  use tpair.\n  - exact semilattice_operations.\n  - use tpair.\n    + exact semilattice_ax.\n    + use tpair.\n      * exact semilattice_arg.\n      * split.\n        ** exact semilattice_lhs.\n        ** exact semilattice_rhs.\nDefined.\n\n(** The interpretation of ring in set *)\nDefinition semilattice_cat\n  : univalent_category\n  := set_algebra semilattice_signature.\n\n(** Projections of a ring *)\nSection JoinSemiLatticeProjections.\n  Variable (S : semilattice_cat).\n\n  Definition join_semilattice_carrier : hSet\n    := pr11 S.\n\n  Definition join\n    : join_semilattice_carrier → join_semilattice_carrier → join_semilattice_carrier\n    := λ x₁ x₂, pr21 S (inl (x₁ ,, x₂)).\n\n  Local Notation \"x₁ ∪ x₂\" := (join x₁ x₂) (at level 40, left associativity).\n\n  Definition empty\n    : join_semilattice_carrier\n    := pr21 S (inr tt).\n\n  Local Notation \"'0'\" := empty.\n\n  Definition join_semilattice_nl\n    : ∏ (x : join_semilattice_carrier), 0 ∪ x = x\n    := λ x, pr2 S nl x.\n\n  Definition join_semilattice_idem\n    : ∏ (x : join_semilattice_carrier), x ∪ x = x\n    := λ x, pr2 S idem x.  \n\n  Definition join_semilattice_com\n    : ∏ (x y : join_semilattice_carrier), x ∪ y = y ∪ x\n    := λ x y, pr2 S com (x ,, y).\n\n  Definition join_semilattice_assoc\n    : ∏ (x y z : join_semilattice_carrier), (x ∪ y) ∪ z = x ∪ (y ∪ z)\n    := λ x y z, pr2 S assoc ((x ,, y) ,, z).\n\n  Definition join_semilattice_nr\n    : ∏ (x : join_semilattice_carrier), x ∪ 0 = x\n    := λ x, join_semilattice_com x 0 @ join_semilattice_nl x.\nEnd JoinSemiLatticeProjections.\n\n(** Builder for semilattices *)\nDefinition mk_semilattice\n           {S : hSet}\n           (e : S)\n           (j : S → S → S)\n           (j_nl : ∏ (x : S), j e x = x)\n           (j_idem : ∏ (x : S), j x x = x)\n           (j_com : ∏ (x y : S), j x y = j y x)\n           (j_assoc : ∏ (x y z : S), j (j x y) z = j x (j y z))\n  : semilattice_cat.\nProof.\n  simple refine ((S ,, _) ,, _).\n  - cbn.\n    intros x.\n    induction x as [x | x].\n    + exact (j (pr1 x) (pr2 x)).\n    + exact e.\n  - intros k.\n    induction k.\n    + exact j_nl.\n    + exact j_idem.\n    + exact (λ z, j_com (pr1 z) (pr2 z)).\n    + exact (λ z, j_assoc (pr11 z) (pr21 z) (pr2 z)).\nDefined.\n\n(** Kuratowski finite sets *)\nSection KFinite.\n  Variable (X : hSet).\n\n  Local Definition kuratowski_free_HIT\n    : set_algebra (free_signature semilattice_signature X)\n    := free_algebra_help semilattice_signature X.\n\n  Definition kuratowski_HIT\n    : semilattice_cat\n    := free_alg_to_alg _ kuratowski_free_HIT.\n\n  (** Constructors *)\n  Definition kuratowski\n    : hSet\n    := alg_carrier kuratowski_HIT.\n\n  Definition k_empty\n    : kuratowski\n    := alg_operation kuratowski_HIT (inr tt).\n\n  Definition k_singleton\n    : X → kuratowski\n    := free_algebra_inc semilattice_signature X.\n\n  Definition k_union\n    : kuratowski → kuratowski → kuratowski\n    := λ x y, alg_operation kuratowski_HIT (inl (x ,, y)).\n\n  Definition k_nl\n    : ∏ (x : kuratowski), k_union k_empty x = x\n    := alg_paths kuratowski_free_HIT nl.\n\n  Definition k_nr\n    : ∏ (x : kuratowski), k_union x k_empty = x\n    := join_semilattice_nr kuratowski_HIT.\n\n  Definition k_idem\n    : ∏ (x : kuratowski), k_union x x = x\n    := alg_paths kuratowski_free_HIT idem.\n\n  Definition k_com\n    : ∏ (x y : kuratowski), k_union x y = k_union y x\n    := λ x y, alg_paths kuratowski_free_HIT com (x ,, y).\n\n  Definition k_assoc\n    : ∏ (x y z : kuratowski), k_union (k_union x y) z = k_union x (k_union y z)\n    := λ x y z, alg_paths kuratowski_free_HIT assoc ((x ,, y) ,, z).\n\n  (** Induction *)\n  Section KInduction.\n    Context {Y : kuratowski → UU}.\n    Variable (Ye : Y k_empty)\n             (Ys : ∏ (x : X), Y (k_singleton x))\n             (Yu : ∏ (z₁ z₂ : kuratowski), Y z₁ → Y z₂ → Y (k_union z₁ z₂))\n             (Ynl : ∏ (x : kuratowski) (y : Y x),\n                     transportf Y (k_nl x) (Yu k_empty x Ye y)\n                     =\n                     y)\n             (Yidem : ∏ (x : kuratowski) (y : Y x),\n                      transportf Y (k_idem x) (Yu x x y y)\n                      =\n                      y)\n             (Ycom : ∏ (x₁ x₂ : kuratowski) (y₁ : Y x₁) (y₂ : Y x₂),\n                     transportf Y (k_com x₁ x₂) (Yu x₁ x₂ y₁ y₂)\n                     =\n                     Yu x₂ x₁ y₂ y₁)\n             (Yassoc : ∏ (x₁ x₂ x₃ : kuratowski)\n                         (y₁ : Y x₁) (y₂ : Y x₂) (y₃ : Y x₃),\n                       transportf Y\n                                  (k_assoc x₁ x₂ x₃)\n                                  (Yu (k_union x₁ x₂) x₃ (Yu x₁ x₂ y₁ y₂) y₃)\n                       =\n                       Yu x₁ (k_union x₂ x₃) y₁ (Yu x₂ x₃ y₂ y₃))\n             (Yset : ∏ (x : kuratowski), isaset (Y x)).\n\n    Definition K_ind_disp_algebra\n      : disp_algebra kuratowski_free_HIT.\n    Proof.\n      use make_disp_algebra.\n      - intros x.\n        use make_hSet.\n        + exact (Y x).\n        + exact (Yset x).\n      - intros x.\n        induction x as [x | x].\n        + exact (λ _, Ys x).\n        + induction x as [x | x].\n          * intros y.\n            exact (Yu (pr1 x) (pr2 x) (pr1 y) (pr2 y)).\n          * induction x.\n            exact (λ _, Ye).\n      - intros j.\n        simpl.\n        induction j.\n        + exact Ynl.\n        + exact Yidem.\n        + exact (λ x y, Ycom (pr1 x) (pr2 x) (pr1 y) (pr2 y)).\n        + exact (λ x y, Yassoc (pr11 x) (pr21 x) (pr2 x) (pr11 y) (pr21 y) (pr2 y)).\n    Defined.\n\n    Definition K_ind_help\n      : disp_algebra_map K_ind_disp_algebra\n      := pr2 (HIT_exists (free_signature semilattice_signature X)) K_ind_disp_algebra.\n    \n    Definition K_ind\n      : ∏ (x : kuratowski), Y x\n      := pr1 K_ind_help.\n\n    Definition K_ind_e\n      : K_ind k_empty = Ye.\n    Proof.\n      apply K_ind_help.\n    Qed.\n\n    Definition K_ind_s\n      : ∏ (x : X), K_ind (k_singleton x) = Ys x.\n    Proof.\n      intro x.\n      apply K_ind_help.\n    Qed.\n\n    Definition K_ind_u\n      : ∏ (x₁ x₂ : kuratowski),\n        K_ind (k_union x₁ x₂)\n        =\n        Yu x₁ x₂ (K_ind x₁) (K_ind x₂).\n    Proof.\n      intros x₁ x₂.\n      apply K_ind_help.\n    Qed.\n  End KInduction.\n\n  (** Induction on families of propositions *)\n  Section KInductionProp.\n    Context {Y : kuratowski → UU}.\n    Variable (Ye : Y k_empty)\n             (Ys : ∏ (x : X), Y (k_singleton x))\n             (Yu : ∏ (z₁ z₂ : kuratowski), Y z₁ → Y z₂ → Y (k_union z₁ z₂))\n             (Yprop : ∏ (x : kuratowski), isaprop (Y x)).\n\n    Definition K_ind_prop\n      : ∏ (x : kuratowski), Y x.\n    Proof.\n      use K_ind.\n      - exact Ye.\n      - exact Ys.\n      - exact Yu.\n      - intros ; apply Yprop.\n      - intros ; apply Yprop.\n      - intros ; apply Yprop.\n      - intros ; apply Yprop.\n      - intro x.\n        apply isasetaprop.\n        apply Yprop.\n    Defined.\n  End KInductionProp.\n\n  (** Recursion *)\n  Section KRecusion.\n    Context {A : UU}.\n    Variable (Ae : A)\n             (As : X → A)\n             (Au : A → A → A)\n             (Anl : ∏ (a : A), Au Ae a = a)\n             (Aidem : ∏ (a : A), Au a a = a)\n             (Acom : ∏ (a₁ a₂ : A), Au a₁ a₂ = Au a₂ a₁)\n             (Aassoc : ∏ (a₁ a₂ a₃ : A), Au (Au a₁ a₂) a₃ = Au a₁ (Au a₂ a₃))\n             (Aset : isaset A).\n\n    Definition K_rec_algebra\n      : set_algebra (free_signature semilattice_signature X).\n    Proof.\n      use make_algebra.\n      - use make_hSet.\n        + exact A.\n        + exact Aset.\n      - intros a ; cbn in a.\n        induction a as [x | a].\n        + exact (As x).\n        + induction a as [a | a].\n          * exact (Au (pr1 a) (pr2 a)).\n          * exact Ae.\n      - intros j.\n        induction j.\n        + exact Anl.\n        + exact Aidem.\n        + exact (λ x, Acom (pr1 x) (pr2 x)).\n        + exact (λ x, Aassoc (pr11 x) (pr21 x) (pr2 x)).\n    Defined.\n\n    Definition K_rec_help\n      : kuratowski_free_HIT --> K_rec_algebra\n      := hit_rec _ K_rec_algebra.\n\n    Definition K_rec\n      : kuratowski → A\n      := alg_map_carrier K_rec_help.\n\n    Definition K_rec_e\n      : K_rec k_empty = Ae.\n    Proof.\n      apply (eqtohomot (pr21 K_rec_help)).\n    Qed.\n\n    Definition K_rec_s\n      : ∏ (x : X), K_rec (k_singleton x) = As x.\n    Proof.\n      intro x.\n      apply (eqtohomot (pr21 K_rec_help)).\n    Qed.\n\n    Definition K_rec_u\n      : ∏ (x₁ x₂ : kuratowski), K_rec (k_union x₁ x₂) = Au (K_rec x₁) (K_rec x₂).\n    Proof.\n      intros x₁ x₂.\n      apply (eqtohomot (pr21 K_rec_help)).\n    Qed.\n  End KRecusion.\nEnd KFinite.\n", "meta": {"author": "UniMath", "repo": "SetHITs", "sha": "512f3c76926f458a130786891c2e325e66afeb21", "save_path": "github-repos/coq/UniMath-SetHITs", "path": "github-repos/coq/UniMath-SetHITs/SetHITs-512f3c76926f458a130786891c2e325e66afeb21/code/examples/join_semilattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7372707160041481}}
{"text": "\n\n(** * Additive principal ordinals *)\n\n(** Pierre Casteran, LaBRI, Universite de Bordeaux *)\n\n  \n(**\n\nIn this library, we define the exponential of basis omega, also called [phi0].\n\nIn fact,  #<math> &omega; <sup> &alpha; </sup> </math># , written  [phi0 alpha] in Coq, \n is defined as the [alpha]-th _additive principal_ ordinal. \n\n *)\n\n(* begin hide *)\nFrom Coq Require Import Arith  Logic.Epsilon  Ensembles  Lia.\nFrom hydras Require Export Countable  Schutte_basics\n     Ordering_Functions.\nImport  PartialFun  MoreEpsilonIota .\nFrom hydras Require Export Schutte.Addition  Well_Orders.\n\n\nSet Implicit Arguments.\n\n(* end hide *)\n\n(** ** Main Definitions\n\n *** Additive principal ordinals \n *)\n\n(* begin snippet APDef *)\n\nDefinition AP : Ensemble Ord :=\n  fun alpha => \n    zero < alpha /\\\n    (forall beta, beta < alpha -> beta + alpha = alpha).\n\n(* end snippet APDef *)\n\n(**  *** Exponential of basis omega\n *)\n\n(* begin snippet phi0Def *)\n\nDefinition _phi0 := ord AP.\n\nNotation phi0 := _phi0.\n\nNotation \"'omega^'\" := phi0 (only parsing) : schutte_scope.\n\n(* end snippet phi0Def *)\n\n(**  *** Omega-towers\n *)\n\n(* begin snippet omegaTower *)\n\nFixpoint omega_tower (i : nat) : Ord :=\n  match i with\n    0 =>  1\n  | S j => phi0 (omega_tower j)\n  end.\n\n(* end snippet omegaTower *)\n\n(** *** The limit ordinal [epsilon0] \n *)\n(* begin snippet epsilon0Def *)\n\nDefinition epsilon0 := omega_limit omega_tower.\n\n(* end snippet epsilon0Def *)\n\n(** ** Proofs, proofs, proofs ... *)\n\n(** ** About additive principals *)\n\n(* begin snippet APOne:: no-out *)\nLemma AP_one : In AP 1.\n(* end snippet APOne *)\nProof with auto with schutte.\n  split.\n  -  simpl (F 1) ...\n  -  simpl (F 1); intros beta H.\n     assert (H0: beta <= zero).\n     { apply lt_succ_le_2 ... }\n     rewrite (le_alpha_zero H0), zero_plus_alpha...\nQed.\n\n(* begin snippet APOne_least_AP:: no-out *)\nLemma least_AP : least_member lt AP 1.\n(* end snippet APOne_least_AP *)\nProof.\n  repeat split.\n  - simpl (F 1). auto with schutte. \n  - intros beta H;  assert (beta = zero).\n    { simpl (F 1) in H; apply le_alpha_zero,  lt_succ_le_2.\n      assumption.\n    }\n    subst beta; rewrite zero_plus_alpha; reflexivity.\n  - intros x  H0; tricho x (F 1) H3.\n    + simpl (F 1) in H3; assert (x = zero).\n    { now apply le_alpha_zero, lt_succ_le_2. }\n     subst x; destruct H0; now case (@lt_irrefl zero). \n    + subst x; now left.  \n    + right; auto.\nQed.\n\n(* begin snippet APOne_AP_omega:: no-out *)\nLemma AP_omega : In AP omega.\n(* end snippet APOne_AP_omega *)\nProof.\n  repeat split.\n  - apply lt_trans with (F 1).\n    +  simpl (F 1) ; auto with schutte.\n    + apply finite_lt_omega.\n  - intros beta H; case (@lt_omega_finite _  H).\n    intros;subst beta;apply finite_plus_infinite; auto with schutte. \nQed.\n\n\n\n#[global] Hint Resolve zero_lt_omega : schutte.\n\nLemma AP_finite_eq_one : forall n: nat, AP n -> n = 1.\nProof.\n  intro n;  case n.\n  -  inversion 1.\n     simpl in H0; case (@lt_irrefl zero);auto.\n  -  intro n0;case n0; trivial.\n     inversion_clear 1.\n     generalize (H1 (F 1)); intros;\n       absurd (F 1 + F (S (S n1)) = F (S (S n1))).\n     +  rewrite <- plus_FF;simpl; intro H2.\n        case (@lt_irrefl (succ (succ (F n1)))).\n        pattern (succ (succ (F n1))) at 2;\n          rewrite <- H2; auto with schutte.\n     + apply H, finite_mono; auto with arith.\nQed.\n\n(** Thus, omega is the second additive principal *)\n\n(* begin snippet APOne_omega_second_AP:: no-out *)\nLemma omega_second_AP :\n  least_member lt\n               (fun alpha => 1 < alpha /\\ In AP alpha)\n               omega.\n(* end snippet APOne_omega_second_AP *)\nProof with auto with schutte.\n  split.\n  - split.\n    +  apply finite_lt_omega.\n    + apply AP_omega.\n  -  intros x  H0; case (@trichotomy x omega).  \n     + intro H1; case (lt_omega_finite  H1).\n       intros; subst x.\n       destruct  H0 as [H2 H3]; generalize (AP_finite_eq_one _ H3).\n       intro;subst x0;now destruct  (@lt_irrefl (F 1)).\n     + red; intuition.\nQed.\n\n(* begin snippet APPlusClosed *)\n\nLemma AP_plus_closed (alpha beta gamma : Ord): \n  In AP alpha -> beta < alpha -> gamma < alpha ->\n  beta + gamma < alpha. (* .no-out *)\n(*| .. coq:: none |*)\nProof with auto with schutte.\n  intros  H  H0 H1; case H;  intros H2 H3.\n  generalize (@plus_mono_r  beta gamma alpha); intro H4.\n  replace alpha with (beta+alpha) ...\n  Qed.\n    \n(*||*)\n\n(* end snippet APPlusClosed *)\n\nLemma AP_mult_Sn_closed (alpha beta: Ord)  :\n  AP alpha -> beta < alpha -> forall n,  mult_Sn beta n  < alpha.\n  intros H H0; induction n.\n  - now simpl.\n  -   simpl. now  apply AP_plus_closed.\nQed.\n\n\n\nLemma AP_mult_fin_r_closed  (alpha beta: Ord)  :\n  AP alpha -> beta < alpha -> forall n,  beta * n  < alpha.\nProof.\n  destruct n.\n  - simpl; eapply le_lt_trans ; eauto with schutte.\n  - simpl; now apply AP_mult_Sn_closed.\nQed.\n\n(* begin hide *)\n\nSection AP_Unbounded.\n  Variable alpha : Ord.\n  \n  Let seq := (fix seq (n:nat)  := \n                match n with 0 => succ alpha\n                        | S p => (seq p) + (seq p)\n                end).\n  \n\n  Let beta := omega_limit seq.\n\n  Remark mono_seq : forall i, seq i < seq (S i).\n  Proof with eauto with schutte.\n    induction i.\n    - simpl;  pattern (succ alpha) at 1.\n      rewrite <- alpha_plus_zero; apply plus_mono_r ...\n    -   simpl in *.\n        pattern (seq i + seq i) at 1; rewrite <- alpha_plus_zero;\n        apply plus_mono_r ...\n  Qed.\n\n  \n  Lemma mono_seq2 : forall i j, (i < j)%nat -> seq i < seq j.\n  Proof with auto.\n    induction  1.\n    - apply mono_seq ...\n    - apply lt_trans with (seq m).\n      apply IHle.\n      apply mono_seq ...\n  Qed.\n\n  Lemma mono_seq_weak2 : forall i j, (i <= j)%nat -> seq i <= seq j.\n  Proof with eauto with schutte.\n    intros i j H; destruct (le_lt_eq_dec _ _ H).\n    - right; now apply mono_seq2.\n    - subst j;  left ...\n      \n  Qed.\n\n  #[local] Hint Resolve mono_seq mono_seq2 : schutte.\n\n\n  Remark alpha_lt_beta : alpha < beta.\n  Proof with auto with schutte.\n    apply lt_trans with (seq 0).\n    -  simpl ...\n    - unfold beta;  apply lt_omega_limit ...\n  Qed.\n\n  Remark zero_lt_beta : zero < beta.\n  Proof with eauto with schutte.\n    apply le_lt_trans with alpha ...\n    apply alpha_lt_beta.\n  Qed.\n\n  Section ksi_fixed.\n    Variable ksi: Ord.\n    Hypothesis lt_ksi : ksi < beta.\n\n    Remark lt_beta_exists : exists n, ksi < seq n.\n    Proof. \n      case (@lt_omega_limit_lt_exists_lt ksi seq mono_seq); auto.   \n      intros;exists x;auto.\n    Qed.\n\n\n    Let n := some (fun n => ksi < seq n).\n\n\n    Remark ksi_plus_seq_n : forall (m:nat), (n <= m)%nat -> ksi + seq m <= beta.\n    Proof with eauto with schutte.\n      intros m H; apply le_trans with (seq (S m)).\n      -  simpl; apply plus_mono_weak_l.\n         +  apply le_trans with (seq n).\n            *  right; unfold n, some;  \n                 pattern (epsilon InHWit (fun n0 : nat => ksi < seq n0));\n                 apply epsilon_ind.\n               apply lt_beta_exists.\n               elim H;  auto.\n            *  destruct (le_lt_eq_dec n m H).\n               right; apply mono_seq2;  auto.  \n               subst m;left; split ...\n      -  right;apply lt_omega_limit.\n         + apply seq_mono_intro ...\n    Qed.\n\n    Lemma ksi_plus_seq_n' : forall (m:nat), ksi + seq m <= beta.  \n    Proof.\n      intro m ; destruct  (Nat.le_gt_cases n m) as [H | H].\n      -  apply ksi_plus_seq_n;auto.\n      -   apply le_trans with (ksi + seq n).\n          +  apply plus_mono_r_weak;auto.\n             apply mono_seq_weak2;  auto with arith.\n          +  apply ksi_plus_seq_n;  auto with arith.\n    Qed.\n\n\n    Lemma ksi_plus_beta : ksi + beta <= beta.\n    Proof.\n      unfold beta at 1; unfold omega_limit.\n      rewrite alpha_plus_sup. \n      -  apply sup_least_upper_bound; eauto with schutte.\n         +  apply R1 with ordinal (ge ksi).\n            * apply plus_ordering; auto.\n            *  apply seq_range_countable;auto.\n            *  intro; split.\n         +  intros y [z [H1 H2]]; subst y.\n            destruct H1 as [x [_ H2]];  subst z; apply ksi_plus_seq_n'.\n      - now exists (seq 0), 0.\n      -  eauto with schutte.\n    Qed.\n\n    Lemma ksi_plus_beta_eq : ksi + beta = beta.\n    Proof.\n      apply le_antisym.\n      -  apply ksi_plus_beta.\n      -  apply le_plus_r;auto.\n    Qed.\n\n  End ksi_fixed.\n\n\n  Lemma AP_unbounded_0 : alpha < beta /\\ AP beta.\n  Proof.\n    split.\n    -  apply alpha_lt_beta. \n    -  split.\n       + apply zero_lt_beta.\n       +  intros; apply ksi_plus_beta_eq; eauto with schutte.\n  Qed.\n\nEnd AP_Unbounded.\n\n(* end hide *)\n\n(* begin snippet APUnbounded *)\n\nTheorem AP_unbounded : Unbounded AP. (* .no-out *)\nProof. (* .no-out *)\n  intro x.\n  \n  exists (omega_limit\n            (fix seq (n : nat) : Ord :=\n               match n with\n               | O => succ x\n               | S p => seq p + seq p\n               end)). (* .no-out *)\n  (* ... *)\n  (* end snippet APUnbounded *)\n  destruct (AP_unbounded_0 x); now split.\nQed.\n\n(* begin hide *)\n\nSection AP_closed.\n  Variable M : Ensemble Ord.\n  Hypothesis OM : Included M AP.\n  Hypothesis inhM : Inhabited _ M.\n  Hypothesis denM : countable M.\n  \n  Remark supM_gt0 : zero < |_| M.\n  Proof.\n    destruct inhM as [x H]; apply lt_le_trans with x.\n    -  now  destruct (OM H).\n    -  apply sup_upper_bound; auto with schutte.\n  Qed.\n  \n  Lemma AP_sup : In AP (|_| M).\n  Proof.\n    split.\n    - apply supM_gt0.\n    -  intros ksi Hksi;\n         destruct (@lt_sup_exists_lt M denM ksi Hksi)\n         as [alpha [Malpha ksialpha]].\n       apply le_antisym.\n       +  rewrite alpha_plus_sup; auto.\n          *  apply sup_mono; auto.\n             { apply R1 with ordinal (ge ksi); auto.\n               - apply plus_ordering; eauto with schutte.\n               - split.\n             }\n             { intros x H; destruct  H as [beta [Mbeta ebeta]].\n               case (@lt_or_ge beta alpha);auto with schutte.\n               - exists alpha;    split;auto.\n                 subst x; case (OM Mbeta).\n                 intros H1 H2; right.\n                 apply lt_le_trans with (ksi + alpha).\n                 + apply plus_mono_r; eauto with schutte.\n                 + left.\n                   destruct (OM Malpha) as [H3 H4]; now apply H4.\n               -  exists beta; split; auto.\n                  left; subst x.\n                  case (OM Mbeta);  intros H1 H2;  apply H2.\n                  apply lt_le_trans with alpha;auto.\n             }\n       + apply le_plus_r;eauto with schutte.\n  Qed.\n  \nEnd AP_closed.  \n\n(* end hide *)\n\n(* begin snippet APClosed *)\n\nTheorem AP_closed : Closed AP. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  split.\n  -  apply AP_sup;auto.\n  -  intros;  apply AP_sup;auto.\nQed.\n(*||*)\n\nTheorem AP_o_segment :  the_ordering_segment AP = ordinal. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intros;apply segment_unbounded.\n  eapply SA2.\n  eapply ord_ok;eauto.\n  generalize \n    (ordering_unbounded_unbounded \n       (A:=the_ordering_segment AP) \n       (B:=AP) \n       (f:=phi0)); intro H.\n  generalize (H (ord_ok  AP)); intro H0;  rewrite <- H0.\n  now  apply AP_unbounded.\nQed.\n(*||*)\n(* end snippet APClosed *)\n\n(** ** Properties of [phi0] *)\n\nTheorem normal_phi0 : normal phi0 AP.\nProof.\n  apply TH_13_6R with ordinal.\n  -  unfold _phi0; rewrite <- AP_o_segment; apply ord_ok.\n  - apply AP_closed.\n  - apply AP_unbounded.\nQed.\n\n\nLemma phi0_ordering :  ordering_function phi0 ordinal AP.\nProof.\n  intros;   unfold _phi0; rewrite <- AP_o_segment;\n    apply ord_ok.\nQed.\n\n\n(* begin snippet APPhi0 *)\n\n(*| .. coq:: no-out |*)\n\nLemma phi0_elim : forall P : (Ord->Ord)->Prop,\n    (forall f: Ord->Ord, \n        ordering_function f ordinal AP -> P f) ->\n    P phi0.\nProof.\n  intros P H; apply H, phi0_ordering.\nQed.\n\nLemma AP_phi0 (alpha : Ord) : In AP (phi0 alpha). (* .no-out *)\nProof. (* .no-out *)\n  pattern phi0; apply phi0_elim.\n  destruct 1 as [H H0 H1 H2];  apply H0;auto; split.\nQed. \n\n\nLemma phi0_zero : phi0 zero =  1. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  generalize (ordering_function_least_least  phi0_ordering),least_AP;\n    intros H H0; rewrite (least_member_unicity AX1  H H0);eauto.\nQed.\n(*||*)\n\nLemma phi0_mono (alpha beta : Ord) :\n  alpha < beta ->  phi0 alpha < phi0 beta. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intro H; pattern phi0; apply phi0_elim.\n  intros;eapply ordering_function_mono;eauto with schutte.\nQed.\n(*||*)\n\nLemma phi0_mono_weak (alpha beta : Ord) :\n  alpha <= beta ->  phi0 alpha <= phi0 beta. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  destruct 1.\n  -  subst beta; auto with schutte.\n  -  right;apply phi0_mono;auto.\nQed.\n(*||*)\n\nLemma phi0_mono_R (alpha beta : Ord) :\n  phi0 alpha < phi0 beta -> alpha < beta. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  pattern phi0; apply phi0_elim.\n  intros;eapply ordering_function_monoR; eauto.\n  all : split.\nQed.\n(*||*)\n\nLemma phi0_mono_R_weak (alpha beta: Ord): \n    phi0 alpha <= phi0 beta -> alpha <= beta. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  pattern phi0; apply phi0_elim.\n  intros f Hf; eapply ordering_function_mono_weakR;eauto.\n  all : split.\nQed.\n(*||*)\n\nLemma phi0_inj (alpha beta : Ord) :\n  phi0 alpha = phi0 beta -> alpha = beta. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intros; apply le_antisym; apply phi0_mono_R_weak;auto with schutte.\nQed.\n(*||*)\n\n\nLemma phi0_positive (alpha : Ord):  zero < phi0 alpha. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intros;  apply lt_le_trans with (phi0 zero).\n  rewrite phi0_zero; eauto with schutte arith.\n  pattern phi0 ; apply phi0_elim.\n  intros; eapply ordering_function_mono_weak; eauto with schutte.\nQed.\n(*||*)\n\n\nLemma plus_lt_phi0 (ksi alpha: Ord):\n    ksi < phi0 alpha ->  ksi + phi0 alpha = phi0 alpha. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  pattern (phi0 alpha);  apply phi0_elim;  intros f Hf;\n    assert (H: AP (f alpha)).\n  {  destruct Hf as [H0 H1 H2 H3]. \n     apply H1 ; split. }\n  destruct H;  auto. \nQed.\n(*||*)\n\nLemma phi0_alpha_phi0_beta (alpha beta: Ord) :\n  alpha < beta ->  phi0 alpha + phi0 beta = phi0 beta. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intros.\n  apply plus_lt_phi0; eauto with schutte.\n  apply phi0_mono.\n  auto.\nQed.\n(*||*)\n\n\nLemma phi0_sup : forall U: Ensemble Ord,\n    Inhabited _ U ->\n    countable U ->\n    phi0 (|_| U) = |_| (image U phi0). (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intros U H0 H1;  case normal_phi0.\n  destruct 2 as [H2 [H3 H4]]; symmetry; auto.\n  apply H4; auto;  split.\nQed.\n(*||*)\n\n\nLemma phi0_of_limit (alpha : Ord)  :\n  is_limit alpha ->\n  phi0 alpha = |_| (image (members alpha) phi0). (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intro H; pattern alpha at 1; rewrite  (is_limit_sup_members H);\n    destruct  normal_phi0 as [H0 H1].\n  destruct H1 as [H1 H2] ;symmetry;auto.\n  destruct H2 as [H2 H3]; apply H3.\n  - intro; split.\n  - exists zero; tricho zero alpha HH; auto.\n    +  subst alpha; destruct H as [H _]; now destruct H.\n    + destruct (not_lt_zero HH). \n  - apply countable_members;auto.\nQed.\n(*||*)\n\nLemma AP_to_phi0 (alpha : Ord) :\n  AP alpha -> exists beta,  alpha = phi0 beta. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intro H; pattern phi0;apply phi0_elim.\n  destruct 1 as [H0 H1 H2 H3].  \n  case (H2 _ H); intros x [_ H4]; exists x; now rewrite H4.\nQed.\n(*||*)\n\n\nLemma AP_plus_AP (alpha beta gamma : Ord) :\n  zero < beta -> \n  phi0 alpha + beta = phi0 gamma ->\n  alpha < gamma /\\  beta = phi0 gamma. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intros H H0;  tricho alpha gamma H3.\n  -  split;auto.\n     tricho beta (phi0 gamma) H4.\n     +  case (@lt_irrefl (phi0 gamma)).\n        pattern (phi0 gamma) at 1; rewrite <- H0.\n        * apply AP_plus_closed; auto.\n          apply AP_phi0;  eauto with schutte.\n          apply phi0_mono;auto.\n     + auto.\n     +  rewrite <- H0 in H4;  case (@lt_irrefl beta).\n        eapply le_lt_trans;eauto.\n        apply le_plus_r.\n  -  subst gamma;  case (@lt_irrefl (phi0 alpha)).\n     pattern (phi0 alpha) at 2;  rewrite <- H0.\n     pattern (phi0 alpha) at 1; rewrite <- alpha_plus_zero.\n     apply plus_mono_r;auto.\n  - assert(H1 :  phi0 alpha <= phi0 gamma).\n    { rewrite <- H0; apply le_plus_l. }\n    case (le_not_gt H1);  apply phi0_mono;auto.\nQed.\n(*||*)\n\n\nLemma is_limit_phi0 (alpha : Ord) :\n  zero < alpha ->  is_limit (phi0 alpha). (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intros  H; split.\n  - intro H0; case (@lt_irrefl zero).\n    apply lt_le_trans with alpha;auto.\n    rewrite <- H0;  pattern phi0; apply phi0_elim.\n    intros f H1; eapply ordering_le; [ eauto |].\n    split. \n  - intro H0; destruct H0 as [x H0].\n    generalize (@AP_phi0 alpha).\n    intro H1; destruct H1 as [H1 H2]; rewrite H0 in H2.\n    assert (H3 : x < succ x) by auto with schutte.\n    generalize (H2 _ H3);  intros H4;\n      assert (H5 :zero < x).\n    { tricho zero x H8.\n      -  auto.\n      -  subst x;  replace (succ zero) with (F 1) in H0. \n         + rewrite <- phi0_zero in H0.\n           case (@lt_irrefl (phi0 zero)).\n           pattern (phi0 zero) at 2; rewrite <- H0.\n           apply phi0_mono;auto.\n         +  simpl;auto.\n      -  case (@not_lt_zero x); auto.\n    }\n    assert (H6 : x < x + x).\n    { pattern x at 1;rewrite <- alpha_plus_zero.\n      apply plus_mono_r;auto.\n    }\n    generalize (succ_mono  H6);  rewrite <- H4.\n    intros H7; apply lt_irrefl with (succ (x+x));  auto.\n    now rewrite plus_of_succ in H7.\nQed. \n(*||*)\n\n\nLemma omega_eqn : omega = phi0 1. (* .no-out *)\n(*| .. coq:: none |*)\nProof. \n  destruct (AP_to_phi0 (AP_omega)) as [beta Hbeta]; rewrite Hbeta;\n    tricho beta (F 1) H. \n  -   destruct (finite_lt_inv 1 H ) as [i [H0 H1]].\n      inversion H0.\n      +  subst i beta; simpl in Hbeta; rewrite  phi0_zero in Hbeta.\n         specialize (finite_lt_omega 1); intro H1; rewrite Hbeta in H1.\n         destruct (lt_irrefl H1).\n      + inversion H3.\n  -  now subst.\n  -  specialize (phi0_mono H); intro H0;\n       rewrite <- Hbeta in H0.\n     specialize (lt_omega_finite H0);intros [i Hi].\n     specialize (@is_limit_phi0 (F 1));  intro H2.\n     rewrite Hi in H2;   destruct (finite_not_limit i).\n     apply H2, lt_succ.\nQed.\n(*||*)\n\nLemma le_phi0 (alpha : Ord) : alpha <= phi0 alpha. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  eapply (@ordering_le  phi0 ordinal AP).\n  apply phi0_ordering.\n  split.\nQed.\n(*||*)\n(* end snippet APPhi0 *)\n\n\n(** ** Properties of [epsilon0] *)\n\nLemma epsilon0_fxp : phi0 epsilon0 = epsilon0.\nProof.\n  unfold epsilon0, omega_limit; rewrite phi0_sup.\n  assert (D1: countable (image (seq_range omega_tower) phi0)).\n  { exists (fun alpha i =>  alpha = omega_tower i).\n    split.\n    -  red; destruct 1 as [x [H H0]].\n       destruct H as [i [_ H]];   exists (S i);\n         cbn; rewrite H; auto.\n    - red;  destruct 1;  destruct H;  split. \n    -  red; intros; congruence.\n  }\n  assert (D2: countable (seq_range omega_tower)).\n  { apply Countable.seq_range_countable. }\n  -  apply le_antisym.\n     +  apply sup_mono; trivial.\n        * destruct 1 as [x0 [[i [_ H]] H0]].\n          exists (phi0 x0); split.\n          {  exists (S i); split; auto; simpl; auto ; now f_equal. }\n          left; auto.\n     + apply sup_mono; trivial.\n       intros alpha [i H];  exists (phi0 alpha); split; auto.\n       exists alpha; split; auto.\n       * exists i; auto.\n       * apply le_phi0.\n  - exists (phi0 zero), 0; simpl; rewrite phi0_zero; split; auto. \n  - apply Countable.seq_range_countable.\nQed.\n\n\nLemma epsilon0_AP : AP epsilon0.\nProof.\n  rewrite <- epsilon0_fxp;  apply AP_phi0.\nQed.\n\n\nLemma omega_tower_mono (i : nat) : omega_tower i < omega_tower (S i).\nProof.\n  induction i;  simpl.\n  -  rewrite succ_is_plus_1, zero_plus_alpha;\n       rewrite <- omega_eqn;   apply finite_lt_omega.\n  -  simpl in IHi; now apply phi0_mono.\nQed.\n\n(* begin snippet ltPhi0 *)\n\nLemma lt_phi0 (alpha : Ord):\n  alpha < epsilon0 -> alpha < phi0 alpha. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  unfold epsilon0;  intros H.\n  specialize (@omega_limit_least_gt alpha omega_tower omega_tower_mono H);\n    intro H0.\n  destruct H0 as [i [H0 H1]].\n  destruct i as [|j].\n  -   red in H0;  simpl in H0;\n        assert (H2 : alpha = zero).\n      {\n        specialize (lt_succ_le_2  _ H0); intro H3; apply le_alpha_zero; auto.\n      }\n      subst alpha; rewrite phi0_zero; auto.\n  - assert (H2 : omega_tower j <= alpha).\n    {\n      tricho  alpha (omega_tower j) H2.\n      -   specialize (H1 _ H2);  assert False \n          by (destruct H1; abstract lia); contradiction.\n      -   left; auto.\n      -   right;auto.\n    }\n    assert (omega_tower (S j) <= phi0 alpha).\n    {   simpl.   now apply phi0_mono_weak. }\n    apply lt_le_trans with (omega_tower (S j)); auto.\nQed.\n(*||*)\n(* end snippet ltPhi0 *)\n\n(* begin snippet epsilon0Lfp *)\n\nTheorem epsilon0_lfp : least_fixpoint lt phi0 epsilon0. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  split.\n  - apply epsilon0_fxp.\n  - intros alpha H; tricho alpha epsilon0 H0.\n    + specialize (lt_phi0 H0); intro H1.\n      rewrite  H in H1; destruct (lt_irrefl H1).\n    + subst alpha; now left.\n    + now right.\nQed.\n(*||*)\n(* end snippet epsilon0Lfp *)\n\n\nLemma phi0_lt_epsilon0 (alpha : Ord) :\n  alpha < epsilon0 -> phi0 alpha < epsilon0.\nProof.\n  intro; rewrite <- epsilon0_fxp; now apply phi0_mono.\nQed.\n\n\nLemma phi0_lt_epsilon0_R (alpha : Ord):\n  phi0 alpha < epsilon0  -> alpha < epsilon0.\nProof.\n  intro H; rewrite <- epsilon0_fxp in H; now  apply phi0_mono_R.     \nQed.\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/Schutte/AP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7372707031613105}}
{"text": "(** * Peano\n\n    ペアノの公理に従った自然数についての定義を行う。 *)\n\nRequire Import Basis .\n\n(** 戦術を使う。 *)\nDeclare ML Module \"ltac_plugin\".\nSet Default Proof Mode \"Classic\".\n\n(** 記法を使う。 *)\nImport Basis.Notation .\n\n\n(** 自然数。\n\n    ペアノの公理は、最初の自然数と後者関数により自然数を定義するものである。\n    標準ライブラリはこれにより自然数を定義していて、このライブラリもこれを\n    使う。 *)\nInductive nat : Type\n  :=\n  | O : nat\n  | S : nat -> nat\n  .\n\nDefinition nat_case_nodep\n  {P : Type}\n  (case_O : P)\n  (case_S : nat -> P)\n  (x : nat) : P .\nProof.\n refine (match x with O => _ | S xp => _ end) .\n -\n  exact case_O .\n -\n  exact (case_S xp) .\nDefined.\n\nDefinition nat_case\n  {P : nat -> Type}\n  (case_O : P O)\n  (case_S : forall xp, P (S xp))\n  (x : nat) : P x .\nProof.\n refine (match x with O => _ | S xp => _ end) .\n -\n  exact case_O .\n -\n  exact (case_S xp) .\nDefined.\n\nDefinition nat_rec\n  {P : Type}\n  (case_O : P)\n  (case_S : P -> P)\n  (x : nat) : P .\nProof.\n revert x .\n refine (fix go (x : nat) {struct x} : P := _) .\n refine (nat_case_nodep _ _ x) .\n -\n  exact case_O .\n -\n  refine (fun xp => _) .\n  exact (case_S (go xp)) .\nDefined.\n\nDefinition nat_rect\n  {P : nat -> Type}\n  (case_O : P O)\n  (case_S : forall n, P n -> P (S n))\n  (x : nat) : P x .\nProof.\n revert x .\n refine (fix go (x : nat) {struct x} : P x := _) .\n refine (nat_case _ _ x) .\n -\n  exact case_O .\n -\n  refine (fun xp => _) .\n  exact (case_S xp (go xp)) .\nDefined.\n\n\n(** ** Functions *)\n\n(** 後者関数の別名。 *)\nNotation succ := S (only parsing) .\n\n(** 前者関数。 [pred O = O] 。 *)\nDefinition pred : nat -> nat .\nProof.\n refine (nat_case_nodep _ _) .\n -\n  exact O .\n -\n  exact idmap .\nDefined.\n\n(** 加法。 *)\nDefinition add : nat -> nat -> nat .\nProof.\n refine (fun x => _) .\n refine (nat_rec _ _) .\n -\n  exact x .\n -\n  exact S .\nDefined.\n\n(** 乗法。 *)\nDefinition mul : nat -> nat -> nat .\nProof.\n refine (fun x => _) .\n refine (nat_rec _ _) .\n -\n  exact O .\n -\n  exact (add x) .\nDefined.\n\n(** 減法。結果が負の値になるときは、ゼロへ丸められる。 *)\nDefinition sub : nat -> nat -> nat .\nProof.\n refine (fun x => _) .\n refine (nat_rec _ _) .\n -\n  exact x .\n -\n  exact pred .\nDefined.\n\n\n(** ** Notations\n\n    自然数の記法を定義する。 *)\n\n(** 記法の設定を閉じ込めるモジュール。 *)\nModule Notation .\n\n  (** 記法が使われる文脈を設定する。 *)\n  Delimit Scope nat_scope with nat.\n\n  (** 文脈を開く。 *)\n  Open Scope nat_scope .\n\n  (** 文脈を型と結びつける。 *)\n  Bind Scope nat_scope with nat.\n\n  (** 加法の記法。 *)\n  Notation \"x + y\" := (add x y)\n    (at level 50, left associativity)\n    : nat_scope\n    .\n\n  (** 乗法の記法。 *)\n  Notation \"x * y\" := (mul x y)\n    (at level 40, left associativity)\n    : nat_scope\n    .\n\n  (** 減法の記法。 *)\n  Notation \"x - y\" := (sub x y)\n    (at level 50, left associativity)\n    : nat_scope\n    .\n\nEnd Notation .\n\n(** 参考文献:\n\n    * https://github.com/coq/coq/blob/f4cf212efd98d01a6470ea7bfd1034d52e928906/theories/Init/Notations.v\n    * https://github.com/coq/coq/blob/f4cf212efd98d01a6470ea7bfd1034d52e928906/theories/Init/Datatypes.v\n    * https://github.com/coq/coq/blob/f4cf212efd98d01a6470ea7bfd1034d52e928906/theories/Init/Nat.v\n\n    *)\n", "meta": {"author": "Hexirp", "repo": "seityou", "sha": "ba816a97a2299dec3be1a4823e71166dfaaf5637", "save_path": "github-repos/coq/Hexirp-seityou", "path": "github-repos/coq/Hexirp-seityou/seityou-ba816a97a2299dec3be1a4823e71166dfaaf5637/theories/Peano.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7372689207891044}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  mult lf1 (plus Zero x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj249_coqofml_5Hi1Cv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.737268915567799}}
{"text": "(* definitie inductiva pentru o multime finita *)\nInductive day :=\n  |monday : day\n  |tuesday : day\n  |wednesday : day\n  |thursday : day\n  |friday : day\n  |saturday : day\n  |sunday : day.\n\nInductive bool :=\n  |true : bool\n  |false : bool.\n\n(*functii nerecursive*)\nDefinition equal (d1 d2 : day) : bool :=\n  match d1, d2 with\n    |monday, monday => true\n    |tuesday, tuesday => true\n    |wednesday, wednesday => true\n    |thursday, thursday => true\n    |friday, friday => true\n    |saturday, saturday => true\n    |sunday, sunday => true\n    | _, _ => false\n    end.\n\nDefinition not (b1 : bool) : bool :=\n  match b1 with\n    |true => false\n    |false => true\n  end.\n\nDefinition and (b1 b2 : bool) :=\n  match b1 with\n    |false => false\n    |true => b2\n  end.\n\nDefinition or (b1 b2 : bool) :=\n  match b1 with\n    |true => true\n    |false => b2\n  end.\n\nEval compute in (not true).\nEval compute in (and true false).\nEval compute in (or true false).\n\nDefinition nextDay (d:day) : day :=\n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => thursday\n  | thursday => friday\n  | friday => saturday\n  | saturday => sunday\n  | sunday => monday\n  end.\n\nEval compute in (equal monday monday).\nEval compute in (equal friday monday).\nEval compute in (nextDay friday).\n\nInductive natural :=\n  | O : natural\n  | S : natural -> natural.\n\nCheck natural.\nCheck O.\nCheck (S O).\nCheck (S (S O)).\n\n(* Functii recursive *)\nFixpoint plus (n1 n2 : natural) : natural :=\n  match n1 with\n    | O => n2\n    | S m => S (plus m n2)\n  end.\n\n\n\nFixpoint equalNaturals(n1 n2 : natural):bool:=\nmatch n1 with\n| O => match n2 with \n       | O =>true\n       | _ =>false\n       end\n\n| S x => match n2 with\n          | O => false\n          | S y => equalNaturals x y\n          end\n\nend.\n\nEval compute in (plus O (S O)).\nEval compute in (plus (S O) (S O)).\nEval compute in ( equalNaturals  O (S O)).\nEval compute in (equalNaturals O O).\nEval compute in (equalNaturals (S (S O)) (S (S O))).\n\n\nLemma a1_equal_a2:\n  forall a1 a2,a1=a2 ->equalNaturals (S a1) (S a2)=true.\nProof.\n    -induction a1.\n      simpl.\n      intros a2.\n      * induction a2.\n        trivial.\n        \n   \n    \n\n\n", "meta": {"author": "IonitaCatalin", "repo": "programming-language-principle", "sha": "e6a5b4f5284f28127707dc1b8838bad29f215c69", "save_path": "github-repos/coq/IonitaCatalin-programming-language-principle", "path": "github-repos/coq/IonitaCatalin-programming-language-principle/programming-language-principle-e6a5b4f5284f28127707dc1b8838bad29f215c69/coq_arc/laborator1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8633916134888613, "lm_q1q2_score": 0.7372611095496874}}
{"text": "(** %\\chapter{Encoding Mathematical Structures}% *)\n\nModule DepRecords.\n\nRequire Import ssreflect ssrbool ssrnat ssrfun.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Encoding partial commutative monoids *)\n\nModule PCMDef.\n\n(**\n\nWe have already seen a use of a dependent pair type, exemplified by\nthe Coq's definition of the universal quantification.\n\n*)\n\nPrint ex.\n\n(**\n[[\nInductive ex (A : Type) (P : A -> Prop) : Prop :=\n    ex_intro : forall x : A, P x -> ex P\n]]\n\n*)\n\nRecord mixin_of (T : Type) := Mixin {\n    valid_op : T -> bool;\n    join_op : T -> T -> T;\n    unit_op : T;\n    _ : commutative join_op;\n    _ : associative join_op;\n    _ : left_id unit_op join_op;\n    _ : forall x y, valid_op (join_op x y) -> valid_op x; \n    _ : valid_op unit_op \n}.\n\n(**\n[[\nmixin_of is defined\nmixin_of_rect is defined\nmixin_of_ind is defined\nmixin_of_rec is defined\nvalid_op is defined\njoin_op is defined\nunit_op is defined\n]]\n*)\n\nCheck valid_op.\n\n(**\n[[\nvalid_op\n     : forall T : Type, mixin_of T -> T -> bool\n]]\n*)\n\n\nLemma r_unit T (pcm: mixin_of T) (t: T) : (join_op pcm t (unit_op pcm)) = t.\nProof.\ncase: pcm=>_ join unit Hc _ Hlu _ _ /=.\n\n(** \n[[\n  T : Type\n  t : T\n  join : T -> T -> T\n  unit : T\n  Hc : commutative join\n  Hlu : left_id unit join\n  ============================\n   join t unit = t\n]]\n*)\n\nby rewrite Hc Hlu.\nQed.\n\n\n(** ** An alternative definition *)\n\nInductive mixin_of' (T: Type) := \n  Mixin' (valid_op: T -> bool) (join_op : T -> T -> T) (unit_op: T) of\n    commutative join_op &\n    associative join_op &\n    left_id unit_op join_op &\n    forall x y, valid_op (join_op x y) -> valid_op x &\n    valid_op unit_op.\n\n(**\n\nAlthough this definition seems more principled and is closer to what\nwe have seen in previous chapters, the record notation is more\nconvenient in this case, as it defined getters automatically as well\nas allows one to express inheritance between data structures by means\nof the coercion operator %\\texttt{:>}%\noperator%~\\cite{Garillot-al:TPHOL09}%.%\\footnote{In the next section\nwill show a different way to encode implicit inheritance, though.}%\n\n** Packaging the structure from mixins\n%\\label{sec:packaging}%\n\n*)\n\nSection Packing.\n\nStructure pack_type : Type := Pack {type : Type; _ : mixin_of type}.\n\n(** \n\nThe dependent data structure [pack_type] declares two fields: the\nfield [type] of type [Type], which described the carrier type of the\nPCM instance, and the actual PCM structure (without an explicit name\ngiven) of type [mixin_of type]. That is, in order to construct an\ninstance of [pack_type], one will have to provide _both_ arguments:\nthe carrier set and a PCM structure for it.\n\n*)\n\nLocal Coercion type : pack_type >-> Sortclass.\n\n(**\n\nNext, in the same section, we provide a number of abbreviations to\nsimplify the work with the PCM packed structure and prepare it to be\nexported by clients.\n\n*)\nVariable cT: pack_type.\n\nDefinition pcm_struct : mixin_of cT := \n    let: Pack _ c := cT return mixin_of cT in c.\n\nDefinition valid := valid_op pcm_struct.\nDefinition join := join_op pcm_struct.\nDefinition unit := unit_op pcm_struct.\n\nEnd Packing.\n\nModule Exports.\n\nNotation pcm := pack_type.\nNotation PCMMixin := Mixin.\nNotation PCM T m := (@Pack T m).\n\nNotation \"x \\+ y\" := (join x y) (at level 43, left associativity).\nNotation valid := valid.\nNotation Unit := unit.\n\n\nCoercion type : pack_type >-> Sortclass.\n\n\n(** * Properties of partial commutative monoids *)\n\nSection PCMLemmas.\nVariable U : pcm.\n\n(** \n\nFor instance, the following lemma re-establishes the commutativity of\nthe [\\+] operation:\n\n*)\n\nLemma joinC (x y : U) : x \\+ y = y \\+ x.\nProof.\ncase: U x y=> tp [v j z Cj *]; apply Cj.\nQed.\n\n\n(** \n\nNotice that in order to make the proof to go through, we had to \"push\"\nthe PCM elements [x] and [y] to be the assumption of the goal before\ncase-analysing on [U]. This is due to the fact that the structure of\n[U] affects the type of [x] and [y], therefore destructing it by means\nof [case] would change the representation of [x] and [y] as well,\ndoing some rewriting and simplifications. Therefore, when [U] is being\ndecomposed, al values, whose type depends on it (i.e., [x] and [y])\nshould be in the scope of decomposition. The naming pattern [*] helped\nus to give automatic names to all remaining assumptions, appearing\nfrom decomposition of [U]'s second component before moving it to the\ncontext before finishing the proof by applying the commutativity\n\"field\" [Cj].\n\n*)\n\nLemma joinA (x y z : U) : x \\+ (y \\+ z) = x \\+ y \\+ z.\nProof. \nby case: U x y z=>tp [v j z Cj Aj *]; apply: Aj. \nQed.\n\n(*******************************************************************)\n(**                     * Exercices 1 *                            *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [PCM Laws]\n---------------------------------------------------------------------\n\nProove the rest of the PCM laws.\n*)\n\nLemma joinAC (x y z : U) : x \\+ y \\+ z = x \\+ z \\+ y.\nProof.\nby rewrite -!joinA; rewrite (@joinC y z).\nQed.\n\nLemma joinCA (x y z : U) : x \\+ (y \\+ z) = y \\+ (x \\+ z).\nProof.\nrewrite [y \\+ (_ \\+ _)]joinC.\nrewrite (@joinC y z).\nby rewrite joinA.\nQed.\n\nLemma validL (x y : U) : valid (x \\+ y) -> valid x.\nProof.\nby case: U x y =>tp [v j z Cj Aj l i w e]; apply: i.\nQed.\n\n\nLemma validR (x y : U) : valid (x \\+ y) -> valid y.\nProof.\nrewrite joinC; apply validL.\nQed.\n\nLemma unitL (x : U) : (@Unit U) \\+ x = x.\nProof.\ncase: U x =>tp [v j z Cj Aj l i w e]; apply l.\nQed.\n\nLemma unitR (x : U) : x \\+ (@Unit U) = x.\nProof.\nrewrite joinC; apply unitL.\nQed.\n\nLemma valid_unit : valid (@Unit U).\nProof.\ncase: U => tp [a b c d e f g h]; apply h.\nQed.\n\n\n(*******************************************************************)\n(**                 * End of Exercices 1 *                         *)\n(*******************************************************************)\n\nEnd PCMLemmas.\n\nEnd Exports.\n\nEnd PCMDef.\n\nExport PCMDef.Exports.\n\n(** * Implementing inheritance hierarchies\n\nWe will now go even further and show how to build hierarchies of\nmathematical structures using the same way of encoding inheritance. We\nwill use a _cancellative PCM_ as a running example.\n\n*)\n\nModule CancelPCM.\n\nRecord mixin_of (U : pcm) := Mixin {\n  _ : forall a b c: U, valid (a \\+ b) -> a \\+ b = a \\+ c -> b = c\n}.\n\nStructure pack_type : Type := Pack {pcmT : pcm; _ : mixin_of pcmT}.\n\nModule Exports.\n\nNotation cancel_pcm := pack_type.\nNotation CancelPCMMixin := Mixin.\nNotation CancelPCM T m:= (@Pack T m).\n\nCoercion pcmT : pack_type >-> pcm.\n\nLemma cancel (U: cancel_pcm) (x y z: U): \n  valid (x \\+ y) -> x \\+ y = x \\+ z -> y = z.\nProof.\nby case: U x y z=>Up [Hc] x y z; apply: Hc.\nQed.\n\nEnd Exports.\nEnd CancelPCM. \n\nExport CancelPCM.Exports.\n\nLemma cancelC (U: cancel_pcm) (x y z : U) :\n  valid (y \\+ x \\+ z) -> y \\+ x = x \\+ z -> y = z.\nProof.\nby move/validL; rewrite ![y \\+ _]joinC; apply: cancel.\nQed.\n\n\n(**\n\n* Instantiation and canonical structures\n\nNow, as we have defined a PCM structure along with its specialized\nversion, a cancellative PCM, it is time to see how to _instantiate_\nthese abstract definitions with concrete datatypes, i.e., _prove_ the\nlater ones to be instances of a PCM.\n\n** Defining arbitrary PCM instances\n\nNatural numbers form a PCM, in particular, with addition as a join\noperation and zero as a unit element. The validity predicate is\nconstant true, because the addition of two natural numbers is again a\nvalid natural number. Therefore, we can instantiate the PCM structure\nfor [nat] as follows, first by constructing the appropriate mixin.\n\n*)\n\nDefinition natPCMMixin := \n  PCMMixin addnC addnA add0n (fun x y => @id true) (erefl _).\n\nDefinition NatPCM := PCM nat natPCMMixin.\n\n(** \n\nThis definition will indeed work, although, being somewhat\nunsatisfactory. For example, assume we want to prove the following\nlemma for natural numbers treated as elements of a PCM, which should\ntrivially follow from the PCM properties of [nat] with addition and\nzero:\n\n[[\nLemma add_perm (a b c : nat) : a \\+ (b \\+ c) = a \\+ (c \\+ b).\n]]\n\n\n[[\nThe term \"a\" has type \"nat\" while it is expected to have type \"PCMDef.type ?135\".\n]]\n\n*)\n\nCanonical natPCM := PCM nat natPCMMixin.\n\nPrint Canonical Projections.\n\n(**\n[[\n...\nnat <- PCMDef.type ( natPCM )\npred_of_mem <- topred ( memPredType )\npred_of_simpl <- topred ( simplPredType )\nsig <- sub_sort ( sig_subType )\nnumber <- sub_sort ( number_subType )\n...\n]]\n*)\n\n\nLemma cancelNat : forall a b c: nat, true -> a + b = a + c -> b = c.\nProof.\nmove=> a b c; elim: a=>// n /(_ is_true_true) Hn _ H.\nby apply: Hn; rewrite !addSn in H; move/eq_add_S: H.\nQed.\n\nDefinition cancelNatPCMMixin := CancelPCMMixin cancelNat.\n\nCanonical cancelNatPCM := CancelPCM natPCM cancelNatPCMMixin.\n\nPrint Canonical Projections.\n\n(** \n\nLet us now see the canonical instances in action, so we can prove a\nnumber of lemmas about natural numbers employing the general PCM\nmachinery.\n\n*)\n\nSection PCMExamples.\n\nVariables a b c: nat.\n\nGoal a \\+ (b \\+ c) =  c \\+ (b \\+ a).\nby rewrite joinA [c \\+ _]joinC [b \\+ _]joinC.\nQed.\n\nGoal c \\+ a = a \\+ b -> c = b.\nby rewrite [c \\+ _]joinC; apply: cancel.\nQed.\n\n(** \n\nIt might look a bit cumbersome, though, to write the PCM join\noperation [\\+] instead of the boolean addition when specifying the\nfacts about natural numbers (even though they are treated as elements\nof the appropriate PCM). Unfortunately, it is not trivial to encode\nthe mechanism, which will perform such conversion implicitly. Even\nthough Coq is capable of figuring out what PCM is necessary for a\nparticular type (if the necessary canonical instance is defined),\ne.g., when seeing [(a b : nat)] being used, it infers the [natPCM],\nalas, it's not powerful enough to infer that the by writing the\naddition function [+] on natural numbers, we mean the PCM's\njoin. However, if necessary, in most of the cases the conversion like\nthis can be done by manual rewriting using the following trivial\n\"conversion\" lemma.\n\n*)\n\nLemma addn_join (x y: nat): x + y = x \\+ y. \nProof. by []. Qed.\n\nEnd PCMExamples.\n\n(** ** Types with decidable equalities\n\nThe module [eqtype] of SSReflect's standard library provides a\ndefinition of the equality mixin and packaged class of the familiar\nshape, which, after some simplifications, boil to the following ones:\n\n[[\nModule Equality.\n\nDefinition axiom T (e : rel T) := forall x y, reflect (x = y) (e x y).\n\nStructure mixin_of T := Mixin {op : rel T; _ : axiom op}.\nStructure type := Pack {sort; _ : mixin_of sort}.\n\n...\n\nNotation EqMixin := Mixin.\nNotation EqType T m := Pack T m.\n\nEnd Equality.\n]]\n\nDEMO: check the corresponding files ssreflect-1.4/theories/eqtype.v\nand ssreflect-1.4/theories/ssrnat.v\n\n*)\n\n(*******************************************************************)\n(**                     * Exercices 2 *                            *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [Partially-ordered sets]\n---------------------------------------------------------------------\n\nA partially ordered set order is a triple (T, \\pre, \\bot), such that T\nis a carrier set, \\pre is a relation on T and \\bot is an element of T,\nsuch that\n\n- forall x in T, x \\pre x (reflexivity);\n\n- forall x, y in T, x \\pre y \\wedge y \\pre x \\implies x = y (antisymmetry);\n\n- forall x, y, z in T, x \\pre y \\wedge y \\pre z \\implies x \\pre z (transitivity).\n\nImplement a data structure for partially-ordered sets using mixins and\npacked classes. Prove the following laws:\n\nLemma poset_refl (x : T) : x <== x.\nLemma poset_asym (x y : T) : x <== y -> y <== x -> x = y.\nLemma poset_trans (y x z : T) : x <== y -> y <== z -> x <== z.\n*)\n\n(* VERSION 2. pre : A -> A -> Prop *)\n\nModule PosetDef.\n\nRecord my_mixin_of (T : Type) := MyMixin {\n    pre_op : T -> T -> Prop;\n    _ : forall x, pre_op x x;\n    _ : forall x y, pre_op x y -> pre_op y x -> x = y;\n    _ : forall x y z, pre_op x y -> pre_op y z -> pre_op x z\n}.\n\nSection MyPacking.\n\nStructure pack_type : Type := Pack {type : Type; _ : my_mixin_of type}.\n\nLocal Coercion type : pack_type >-> Sortclass.\n\nVariable cT: pack_type.\n\nDefinition poset_struct : my_mixin_of cT := \n    let: Pack _ c := cT return my_mixin_of cT in c.\n\nDefinition pre := pre_op poset_struct.\n\nEnd MyPacking.\n\nModule Exports.\n\nNotation poset := pack_type.\nNotation PosetMixin := MyMixin.\nNotation Poset T m := (@Pack T m).\n\nNotation \"x <== y\" := (pre x y) (at level 43, left associativity).\nNotation pre := pre.\n\nCoercion type : pack_type >-> Sortclass.\n\nSection PosetLemmas.\nVariable T : poset.\n\nLemma poset_refl (x : T) : x <== x.\nProof.\ncase: T x => tm [pre r e i x]; apply r.\nQed.\n\nLemma poset_asym (x y : T) : x <== y -> y <== x -> x = y.\nProof.\ncase: T x y => tm [pre r e i x y H1 H2].\nby apply e.\nQed.\n\nLemma poset_trans (y x z : T) : x <== y -> y <== z -> x <== z.\nProof.\ncase: T x y z => tm [pre r e i x y z H1 H2].\nby apply: (i x y z).\nQed.\n\nEnd PosetLemmas.\n\nEnd Exports.\n\nEnd PosetDef.\n\nExport PosetDef.Exports.\n\n\n(**\n---------------------------------------------------------------------\nExercise [Canonical instances of partially ordered sets]\n---------------------------------------------------------------------\n\nProvide canonical instances of partially ordered sets for the\nfollowing types:\n\n- [nat] and [<=];\n\n- [prod], whose components are posets;\n\n- functions [A -> B], whose codomain (range) [B] is a partially\n  ordered set.\n\nIn order to provide a canonical instance for functions, you will need\nto assume and make use of the following axiom of functional\nextensionality:\n\n*)\n\nRequire Import ssrnat eqtype.\n\nLemma leq_antisym : forall x y, x <= y -> y <= x -> x = y.\nProof.\nmove=> x y H1 H2.\nmove: (eqn_leq x y) => H.\napply/eqP.\nrewrite H.\nby apply /andP; split.\nQed.\n\nDefinition natPosetMixin := \n  PosetMixin leqnn leq_antisym (fun x y z => @leq_trans y x z).\nDefinition NatPoset := Poset nat natPosetMixin.\nCanonical natPoset := Poset nat natPosetMixin.\n\nDefinition prodPre {A B : poset} (x y : A * B): Prop :=\n  let: (xa, xb) := x in\n  let: (ya, yb) := y in\n  pre xa ya /\\ pre xb yb.\n\nLemma prodPreNN {A B : poset} (x : A * B) : prodPre x x.\nProof.\ncase x=> xa xb; rewrite /prodPre.\nsplit; apply poset_refl.\nQed. \n\nLemma prodPreAntisym {A B : poset} (x y : A * B): prodPre x y -> prodPre y x -> x = y.\nProof.\ncase x => xa xb.\ncase y => ya yb.\nrewrite /prodPre.\ncase => H1 H2.\ncase => H3 H4.\n\nmove: (@poset_asym A xa ya) => H5.\napply H5 in H1.\nFocus 2.\ndone.\n\nmove: (@poset_asym B xb yb) => H6.\napply H6 in H4.\nFocus 2.\ndone.\n\nby rewrite H1 H4.\nQed.\n\nLemma prodPreTrans {A B : poset} (x y z : A * B): prodPre x y -> prodPre y z -> prodPre x z.\nProof.\ncase x => xa xb.\ncase y => ya yb.\ncase z => za zb.\nrewrite /prodPre.\ncase => H1 H2.\ncase => H3 H4.\nsplit.\n- apply: (poset_trans H1 H3).\napply: (poset_trans H2 H4).\nQed.\n\nDefinition prodPosetMixin {A B : poset} := \n  PosetMixin prodPreNN (@prodPreAntisym A B) prodPreTrans.\n\nDefinition ProdPoset {A B : poset} := Poset (prod A B) prodPosetMixin.\nCanonical prodPoset {A B : poset} := Poset (prod A B) prodPosetMixin.\n\n(*\n- functions [A -> B], whose codomain (range) [B] is a partially\n  ordered set.\n\nIn order to provide a canonical instance for functions, you will need\nto assume and make use of the following axiom of functional\nextensionality:\n*)\n\nAxiom fext : forall A (B : A -> Type) (f1 f2 : forall x, B x), \n               (forall x, f1 x = f2 x) -> f1 = f2.\n\nDefinition funcPre {A : Type} {B : poset} (f1 f2 : A -> B): Prop :=\n  forall x, pre (f1 x) (f2 x).\n\nLemma funcPreNN {A : Type} {B : poset} (f : A -> B) : funcPre f f.\nProof.\nrewrite /funcPre.\nmove=> x.\nmove: (f x) => a.\napply: poset_refl.\nQed. \n\nLemma funcPreAntisym {A : Type} {B : poset} (x y : A -> B): funcPre x y -> funcPre y x -> x = y.\nProof.\nrewrite /funcPre.\nmove=> H1 H2.\napply fext.\nmove=> a.\nmove: (H1 a) (H2 a).\napply: poset_asym.\nQed.\n\nLemma funcPreTrans {A : Type} {B : poset}\n      (x y z : A -> B): funcPre x y -> funcPre y z -> funcPre x z.\nProof.\nrewrite /funcPre.\nmove=> H1 H2.\nmove=> a.\nmove: (H1 a) (H2 a).\napply: poset_trans.\nQed.\n\nDefinition funcPosetMixin {A : Type} {B : poset} := \n  PosetMixin funcPreNN (@funcPreAntisym A B) funcPreTrans.\n\nDefinition FuncPoset {A : Type} {B : poset} := Poset (A -> B) funcPosetMixin.\nCanonical funcPoset {A : Type} {B : poset} := Poset (A -> B) funcPosetMixin.\n\n(*******************************************************************)\n(**                 * End of Exercices 2 *                         *)\n(*******************************************************************)\n\nEnd DepRecords.\n", "meta": {"author": "anlun", "repo": "ssrLectures", "sha": "ee98c80b33ce6fab35d0cb0d8c0c45d98c5f73d8", "save_path": "github-repos/coq/anlun-ssrLectures", "path": "github-repos/coq/anlun-ssrLectures/ssrLectures-ee98c80b33ce6fab35d0cb0d8c0c45d98c5f73d8/DepRecords.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.7372611009615107}}
{"text": "From Coq Require Export List.\nImport ListNotations.\nLocal Open Scope list_scope.\nRequire Import Nat.\nRequire Import Psatz.\nRequire Import ZArith.\n\nLocal Open Scope nat_scope.\n\nLocate \">?\" .\n\nCheck ( 5 <? 5)%nat.\n\nFixpoint iter {X} (n: nat) (f:X->X) x :=\n  match n with\n  | O => x\n  | S n' => iter n' f (f x)\n  end.\n\nTheorem list_ind_length: forall (X:Type) (P: list X -> Prop),\n    P []  -> (forall (l2: list X), (forall (l1:list X),  length l1 < length l2 -> P l1) -> P l2) ->\n    forall l : list X, P l.\nProof.\n  intros.\n  apply H0.\n  induction l.\n  intros.\n  inversion H1.\n  intros.\n  apply H0.\n  intros.\n  apply IHl.\n  simpl in H1.\n  lia.\nQed.\n\nInductive binary : Type :=\n  | E1\n  | E2.\n\nDefinition bilist : Type := list binary. \n\nCheck length. \n\nCheck tl.\n\nFixpoint incr1 (b : bilist) : bilist :=\nmatch b with\n  | [] => [E1]\n  | E1 :: t => let b' := incr1 t in\n               if (length b' =? length t) then E1::b' else E2 :: (tl b')\n  | E2 :: t => let b' := incr1 t in\n               if (length b' =? length t) then E2::b' else E1::b'\nend.\n\nFixpoint decr1 (b:bilist) :=\n  match b with\n  | [] => []\n  | [E1] => []\n  | [E2] => [E1]\n  | E1::t => let b' := decr1 t in\n            if (length b' =? length t) then E1::b' else E2::b'\n  | E2::t => let b' := decr1 t in\n            if (length b' =? length t) then E2::b' else E1::E2::b'\n  end. \n\nFixpoint incr2 (b : bilist) : bilist :=\nmatch b with\n  | [] => [E2]\n  | [E1] => [E1; E1]\n  | [E2] => [E1; E2]\n  | E1 :: t => let b' := incr2 t in\n               if (length b' =? length t) then E1::b' else E2 :: (tl b')\n  | E2 :: t => let b' := incr2 t in\n               if (length b' =? length t) then E2::b' else E1::b'\nend.\n\n\nLemma neq_in: forall b : bilist,\n  incr1 b <> [].\nProof.\n  intros.\n  induction b.\n  simpl. discriminate.\n  simpl.\n  destruct a.\n  destruct (length (incr1 b) =? length b).\n  discriminate. discriminate.\n  destruct (length (incr1 b) =? length b).\n  discriminate. discriminate.\nQed.\n\nLemma neq_in_r: forall b : bilist,\n  [] <> incr1 b.\nProof.\n  intros.\n  induction b.\n  simpl. discriminate.\n  simpl.\n  destruct a.\n  destruct (length (incr1 b) =? length b).\n  discriminate. discriminate.\n  destruct (length (incr1 b) =? length b).\n  discriminate. discriminate.\nQed.\n\nLemma empty_tl: forall b : bilist,\n  [] = tl b -> length b <= 1.\nProof.\n  intros.\n  induction b.\n  auto.\n  simpl in H.\n  simpl. rewrite <- H.\n  simpl. auto. Qed.\n\nLemma neq_zero_length: forall b : bilist,\n  0 < length (incr1 b).\nProof.\n  induction b.\n  auto.\n  simpl.\n  destruct a.\n  destruct (length (incr1 b) =? length b).\n  simpl. auto.\n  simpl. lia. \n  destruct (length (incr1 b) =? length b).\n  simpl. auto.\n  simpl. lia.\nQed.\n\nLemma length_ge_zero: forall b : bilist,\n  0 < length b -> length b = S (length (tl b)).\nProof.\n  intros.\n  induction b.\n  inversion H.\n  auto.\nQed.\n\nLemma E1_head_incr: forall b: bilist, \n  (length (incr1 (E1 :: b)) =? length (E1 :: b)) = true.\nProof.\n  induction b.\n  auto.\n  simpl.\n  simpl in IHb.\n  destruct a.\n  remember (length (incr1 b) =? length b) as q.\n  destruct q.\n  simpl. rewrite <- Heqq.\n  simpl. symmetry; auto.\n  rewrite IHb.\n  auto.\n  remember (length (incr1 b) =? length b) as q.\n  destruct q.\n  simpl. rewrite <- Heqq.\n  simpl. symmetry; auto.\n  simpl. simpl in IHb.\n  rewrite <- Heqq.\n  simpl.\n  Search ((_ =? _) = true ). apply PeanoNat.Nat.eqb_eq.\n  apply PeanoNat.Nat.eqb_eq in IHb.\n  rewrite <- IHb.\n  apply length_ge_zero.\n  apply neq_zero_length.\nQed.\n\nLemma E1_head_eq: forall b, \nlength (incr1 (E1 :: b))  = length (E1 :: b).\nProof.\n    Search (_ =? _ = true).\n    intros.\n    rewrite <- PeanoNat.Nat.eqb_eq.\n    \n    apply E1_head_incr. \nQed.\n\nLemma length_neq_incr: forall b : bilist,\n  (length (incr1 b) =? length b) = false <-> length b < length (incr1 b).\nProof.\n    split.\n    intros.\n    induction b.\n    simpl. auto. \n    simpl.\n    destruct a.\n    rewrite E1_head_incr in H.\n    inversion H.\n    remember (length (incr1 b) =? length b) as q.\n    destruct q.\n    simpl.\n    Search (S _ < S _). rewrite <-PeanoNat.Nat.succ_lt_mono.\n    apply IHb.\n    simpl in H.\n    rewrite <- Heqq in H.\n    simpl in H.\n    rewrite <- Heqq in H.\n    inversion H.\n    simpl.\n    rewrite <-PeanoNat.Nat.succ_lt_mono.\n    apply IHb.\n    auto.\n    (***********)\n    induction b.\n    simpl.\n    auto.\n    intros.\n    simpl.\n    destruct a.\n    rewrite E1_head_eq in H.\n    Search (?x < ?x).\n    apply PeanoNat.Nat.lt_irrefl in H.\n    inversion H.\n    remember (length (incr1 b) =? length b) as q.\n    destruct q.\n    simpl.\n    simpl in H.\n    rewrite <- Heqq in H.\n    simpl in H.\n    rewrite <-PeanoNat.Nat.succ_lt_mono in H.\n    apply IHb in H.\n    discriminate.\n    simpl.\n    simpl in H.\n    rewrite <- Heqq in H.\n    simpl in H.\n    rewrite <-PeanoNat.Nat.succ_lt_mono in H. \n    Search (?x < ?y -> ?x <> ?y).\n    apply PeanoNat.Nat.lt_neq in H.\n    apply PeanoNat.Nat.eqb_neq. auto.\nQed.\n\nLemma eq_E1_head: forall (b b' : bilist) (h : binary),\n  b = b' -> h :: b = h ::b'.\nProof.\n  intros.\n  rewrite H.\n  auto.\nQed.\n\nLemma length_eq_head: forall (b b' : bilist) (h : binary), \n    length b = length b' -> length (h :: b) = length (h :: b').\nProof.\n    intros.\n    simpl.\n    auto.\nQed.\n\nLemma tl_greater: forall b : bilist,\n  0 < length b -> length (tl  b) =? length b = false.\nProof.\n  intros.\n  destruct b.\n  inversion H.\n  simpl.\n  induction (length b0).\n  auto.\n  auto.\nQed.\n\nLemma length_tl_incr_true: forall b,\n  (length (incr1 b) =? length b) = true -> (length (tl (incr1 b)) =? length b) = false.\nProof.\n  induction b using list_ind_length.\n  simpl.\n  auto.\n  intros.\n  apply EqNat.beq_nat_true in H0.\n  rewrite <- H0.\n  apply tl_greater.\n  apply neq_zero_length.\nQed.\n\nLemma tl_greater_eq: forall b : bilist,\n  0 < length b -> S (length (tl b)) = (length b) .\nProof.\n  intros.\n  induction b.\n  inversion H.\n  simpl. auto.\nQed.\n\nLemma length_le_S: forall b,\n  length b < length (incr1 b) -> S (length b) = length (incr1 b).\nProof.\n  induction b.\n  auto.\n  intros.\n  simpl.\n  destruct a.\n  remember (length (incr1 b) =? length b).\n  destruct b0.\n  simpl.\n  apply eq_S.\n  apply IHb.\n  simpl in H.\n  rewrite <- Heqb0 in H.\n  simpl in H.\n  apply Lt.lt_S_n in H.\n  auto.\n  simpl.\n  simpl in H.\n  rewrite <- Heqb0 in H.\n  simpl in H.\n  apply eq_S.\n  apply Lt.lt_S_n in H.\n  symmetry in Heqb0.\n  apply length_neq_incr in Heqb0.\n  apply IHb in Heqb0.\n  apply Lt.lt_n_S in H.\n  rewrite Heqb0 in H.\n  rewrite <- tl_greater_eq in H.\n  lia.\n  apply neq_zero_length.\n  remember (length (incr1 b) =? length b).\n  destruct b0.\n  simpl.\n  apply eq_S.\n  apply IHb.\n  simpl in H.\n  rewrite <- Heqb0 in H.\n  simpl in H.\n  apply Lt.lt_S_n in H.\n  auto.\n  simpl.\n  simpl in H.\n  rewrite <- Heqb0 in H.\n  simpl in H.\n  apply eq_S.\n  apply Lt.lt_S_n in H.\n  symmetry in Heqb0.\n  apply length_neq_incr in Heqb0.\n  apply IHb in Heqb0.\n  auto.\nQed.\n\nLemma tl_S: forall b,\n  S (length (tl (incr1 b))) = length (incr1 b).\nProof.\n  induction b.\n  auto.\n  destruct a.\n  simpl.\n  remember (length (incr1 b) =? length b).\n  destruct b0.\n  simpl.\n  auto.\n  simpl.\n  auto.\n  simpl.\n  remember (length (incr1 b) =? length b).\n  destruct b0.\n  simpl.\n  auto.\n  simpl.\n  auto.\nQed.\n\n\nLemma length_eq_incr_S: forall b,\n  (length (incr1 b) =? length b) = false -> length (incr1 b) = S (length b).\nProof.\n  induction b using list_ind_length.\n  auto.\n  intros.\n  destruct b.\n  auto.\n  destruct b.\n  simpl.\n  rewrite E1_head_incr in H0.\n  inversion H0.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  simpl.\n  rewrite PeanoNat.Nat.succ_inj_wd.\n  apply H.\n  auto.\n  simpl in H0.\n  rewrite <- Heqb in H0.\n  simpl in H0.\n  auto.\n  simpl.\n  rewrite PeanoNat.Nat.succ_inj_wd.\n  simpl in H0.\n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  inversion Heqb.\n  apply H.\n  auto. auto.\nQed.\n\nLemma length_incr_tl: forall b, \n  length b < length (incr1 b) -> length (tl (incr1 b)) = length b .\nProof.\n  induction b.\n  auto.\n  intros.\n  destruct a.\n  simpl.\n  remember (length (incr1 b) =? length b ).\n  destruct b0.\n  simpl.\n  rewrite E1_head_eq in H.\n  lia.\n  simpl.\n  rewrite E1_head_eq in H.\n  lia.\n  simpl.\n  remember (length (incr1 b) =? length b ).\n  destruct b0.\n  simpl.\n  symmetry in Heqb0.\n  rewrite PeanoNat.Nat.eqb_eq in Heqb0.\n  apply length_eq_head with (h := E2) in Heqb0.\n  simpl in Heqb0.\n  Search (S _ = S _).\n  apply eq_add_S in Heqb0.\n  simpl in H.\n  remember (length (incr1 b) =? length b ).\n  destruct b0.\n  simpl in H.\n  rewrite Heqb0 in H.\n  lia.\n  simpl in H.\n  lia.\n  simpl.\n  apply length_eq_incr_S.\n  auto.\nQed.\n\nLemma incr1_cons2: forall b, length b < length (incr1 b) -> \nForall (eq E2) b .\nProof.\n  induction b.\n  simpl.\n  auto.\n  intros.\n  Check Forall.\n  apply Forall_cons. \n  destruct a.\n  simpl in H.\n  remember (length (incr1 b) =? length b) as q.\n  destruct q.\n  simpl in H.\n  Search (S _ < S _ ).\n  rewrite <- PeanoNat.Nat.succ_lt_mono in H.\n  rewrite <- length_neq_incr in H.\n  rewrite <- Heqq in H.\n  inversion H.\n  simpl in H.\n  rewrite <- PeanoNat.Nat.succ_lt_mono in H.\n  symmetry in Heqq.\n  apply length_neq_incr in Heqq.\n  apply length_incr_tl in Heqq.\n  lia.\n  auto.\n  apply IHb.\n  rewrite <- length_neq_incr in H.\n  rewrite <- length_neq_incr.\n  simpl.\n  destruct a.\n  simpl in H.\n  remember (length (incr1 b) =? length b ).\n  destruct b0.\n  simpl in H.\n  rewrite H in Heqb0.\n  auto.\n  simpl in H. auto.\n  simpl in H.\n  remember (length (incr1 b) =? length b ).\n  destruct b0.\n  simpl in H.\n  rewrite H in Heqb0.\n  auto.\n  auto.\nQed.\n\nLemma incr1_cons1: forall b,\n  length b  < length (incr1 b) -> Forall (eq E1) (incr1 b).\nProof.\n  induction b using list_ind_length.\n  simpl. auto.\n  intros.\n  simpl.\n  destruct b.\n  simpl. auto.\n  destruct b.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  apply Forall_cons. auto.\n  apply H.\n  auto.\n  simpl in H0.\n  rewrite <- Heqb in H0.\n  simpl in H0.\n  Search (S _ < S _).\n  apply Lt.lt_S_n in H0.\n  apply length_le_S in H0.\n  rewrite <- H0 in Heqb.\n  lia.\n  simpl in H0.\n  rewrite <- Heqb in H0.\n  simpl in H0.  \n  apply Lt.lt_S_n in H0.\n  symmetry in Heqb.\n  apply length_neq_incr in Heqb.\n  apply length_incr_tl in Heqb.\n  lia.\n  simpl in H0.\n  simpl.  \n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  simpl in H0.\n  symmetry in Heqb.\n  apply Lt.lt_S_n in H0.\n  Search (_ =? _ = true).\n  apply PeanoNat.Nat.eqb_eq in Heqb.\n  lia.\n  apply Forall_cons.\n  auto.\n  apply H.\n  auto.\n  symmetry in Heqb.\n  apply length_neq_incr in Heqb.\n  auto.\nQed.  \n  \nLemma incr1_tl_comm_E1: forall b, 1 < (length b) -> Forall (eq E1) b ->\n  incr1 (tl b) = tl (incr1 b).\nProof.\n  induction b using list_ind_length.\n  simpl. intros. inversion H.\n  intros.\n  destruct b.\n  simpl in H0. inversion H0.\n  destruct b.\n  simpl in *.\n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  simpl.\n  auto.\n  simpl.\n  symmetry in Heqb.\n  apply length_neq_incr in Heqb.\n  apply incr1_cons2 in Heqb.\n  inversion_clear H1.\n  destruct b0.\n  simpl in H0. lia.\n  inversion_clear Heqb.\n  inversion_clear H3.\n  rewrite <- H1 in H5.\n  inversion H5.\n  inversion_clear H1.\n  inversion H2.\nQed.\n\nLemma incr1_tl_comm_E2: forall b, 0 < (length b) -> Forall (eq E2) b ->\n  incr1 (tl b) = tl (incr1 b).\nProof.\n  induction b using list_ind_length.\n  simpl. lia.\n  intros.\n  destruct b.\n  auto.\n  simpl.\n  destruct b.\n  inversion_clear H1.\n  inversion H2.\n  inversion_clear H1.\n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  simpl.\n  auto.\n  simpl.\n  auto.\nQed.\n\nFixpoint bin_to_nat (b : bilist) : nat :=\n  match b with\n  | [] => 0\n  | E1 :: t => pow 2 (length t) + bin_to_nat t\n  | E2 :: t => pow 2 (1 + length t) + bin_to_nat t\n  end.\n\nLemma bin_to_nat_incr: forall b,\n  S (bin_to_nat b) = bin_to_nat (incr1 b).\nProof.\n  intros.\n  induction b using list_ind_length.\n  simpl.\n  reflexivity.\n  destruct b.\n  simpl. auto.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  destruct b1.\n  simpl.\n  rewrite <- H.\n  symmetry in Heqb1.\n  apply EqNat.beq_nat_true in Heqb1.\n  rewrite Heqb1.\n  lia.\n  auto.\n  simpl.\n  destruct b0.\n  simpl.\n  reflexivity.\n  rewrite <- incr1_tl_comm_E2.\n  simpl tl.\n  rewrite <- H.\n  simpl length.\n  rewrite <- length_le_S.\n  destruct b.\n  simpl.\n  rewrite E1_head_incr in Heqb1.\n  inversion Heqb1.\n  simpl.\n  lia.\n  destruct b.\n  rewrite E1_head_incr in Heqb1.\n  inversion Heqb1.\n  assert (false = (length (incr1 (E2 :: b0)) =? length (E2 :: b0)) -> false = (length (incr1 (b0)) =? length (b0))).\n  induction b0.\n  simpl. auto.\n  simpl. remember (length (incr1 b0) =? length b0).\n  destruct a; simpl.\n  destruct b; simpl; try (rewrite <- Heqb).\n  simpl.\n  rewrite <- Heqb.\n  auto.\n  rewrite length_incr_tl.\n  remember (length b0 =? length b0).\n  destruct b.\n  simpl. rewrite length_incr_tl. rewrite <- Heqb0.\n  auto.\n  apply length_neq_incr. symmetry.\n  auto.\n  simpl.\n  auto.\n  apply length_neq_incr. symmetry.\n  auto.\n  destruct b.\n  simpl.\n  rewrite <- Heqb.\n  simpl.\n  rewrite <- Heqb; auto.\n  simpl.\n  rewrite <- Heqb.\n  simpl.\n  rewrite <- Heqb.\n  auto.\n  apply H0 in Heqb1.\n  apply length_neq_incr.\n  symmetry; auto.\n  simpl.\n  auto.\n  simpl. lia.\n  apply incr1_cons2.\n  apply length_neq_incr.\n  symmetry; auto.\n  destruct b1.\n  simpl.\n  symmetry in Heqb1.\n  apply EqNat.beq_nat_true in Heqb1.\n  rewrite Heqb1.\n  rewrite <- H.\n  lia.\n  auto.\n  simpl. rewrite <- H.\n  rewrite <- length_le_S.\n  simpl. lia.\n  apply length_neq_incr.\n  symmetry. auto.\n  auto.\nQed.\n\nFixpoint nat_to_bin (n : nat) : bilist :=\n  match n with\n  | 0 => []\n  | S n => incr1 (nat_to_bin n)\n  end.\n\nTheorem bin_to_nat_corr: forall b,\n bin_to_nat (nat_to_bin b) = b.\nProof.\n  intros.\n  induction b.\n  auto.\n  simpl.\n  rewrite <- bin_to_nat_incr.\n  rewrite IHb.\n  auto.\nQed.\n\n\nInductive binary_lt: bilist -> bilist -> Prop :=\n  | binary_lt_cons: forall x y b, length x <= length y -> binary_lt x (b::y)\n  | binary_lt_E: forall x y, (length x = length y) -> binary_lt (E1::x) (E2::y)\n  | binary_lt_cons2: forall x y b, binary_lt x y -> binary_lt (b::x) (b::y).\n\n\nLemma lt_incr1: forall b, binary_lt b (incr1 b).\nProof.\n  induction b using list_ind_length.\n  simpl.\n  constructor 1.\n  auto.\n  destruct b.\n  simpl. constructor. auto.\n  destruct b; simpl; remember (length (incr1 b0) =? length b0) as q; \n  destruct q. \n  apply binary_lt_cons2.\n  apply H. auto.\n  apply binary_lt_E.\n  apply eq_add_S.\n  rewrite tl_S.\n  apply length_le_S.\n  symmetry in Heqq.\n  apply  length_neq_incr.\n  assumption.\n  constructor 3.\n  apply H.\n  auto.\n  constructor 1.\n  simpl.\n  symmetry in Heqq.\n  apply length_eq_incr_S in Heqq.\n  rewrite Heqq.\n  auto.\nQed.\n\nLemma lt_less_length: forall a b,\n  length a < length b -> binary_lt a b.\nProof.\n  intros.\n  destruct b.\n  inversion H.\n  destruct b.\n  constructor.\n  simpl in H.\n  lia.\n  constructor.\n  simpl in H.\n  lia.\nQed.\n\nLemma binary_lt_leq: forall a b,\n  binary_lt a b -> length a <= length b.\nProof.\n  intros.\n  generalize dependent a.\n  induction b using list_ind_length.\n  intros.\n  inversion H.\n  destruct b.\n  simpl.\n  intros.\n  inversion H0.\n  intros.\n  simpl.\n  inversion H0.\n  lia.\n  simpl. lia.\n  simpl.\n  assert (length x <= length a).\n  rewrite <- H2.\n  simpl.\n  auto.\n  rewrite <- PeanoNat.Nat.succ_le_mono.\n  eapply H.\n  auto.\n  assumption.\nQed.\n\n\nLemma binary_lt_trans: forall a b c, \nbinary_lt a b -> \nbinary_lt b c -> \nbinary_lt a c.\nProof.\n  intros.\n  generalize dependent a.\n  generalize dependent b.\n  induction c using list_ind_length;\n  intros.\n  inversion H0.\n  destruct c.\n  inversion H0.\n  destruct a.\n  constructor .\n  simpl.\n   lia.\n  destruct b.\n  inversion H1.\n  destruct b; destruct b1; destruct b0.\n  -\n  inversion H0.\n  inversion H1.\n  apply binary_lt_cons.\n  simpl in *.\n  lia.\n  constructor.\n  apply binary_lt_leq in H0.\n  apply binary_lt_leq in H7.\n  simpl in *.\n  lia.\n  constructor 3.\n  apply H with (b := b2).\n  \n  apply binary_lt_leq in H0.\n  apply binary_lt_leq in H1.\n  simpl in *.\n  lia.\n  assumption.\n  inversion H1.\n  simpl in H8.\n  apply lt_less_length.\n  lia.\n  assumption.\n  -\n  inversion H0.\n  inversion H1.\n  constructor.\n  simpl in *.\n  lia.\n  apply binary_lt_leq in H7.\n  constructor.\n  simpl in *. lia.\n  inversion H1.\n  apply binary_lt_cons.\n  simpl in *. lia.\n  apply binary_lt_leq in H6.\n  assert (length a = length b2 \\/ length a < length b2).\n  lia.\n  inversion H9.\n  constructor 2.\n  lia.\n  constructor.\n  simpl; lia.\n  -\n  inversion H0.\n  inversion H1.\n  constructor.\n  simpl in *. lia.\n  inversion H1.\n  apply binary_lt_leq in H3.\n  constructor.\n  simpl in *.\n  lia.\n  -\n  inversion H0.\n  inversion H1.\n  constructor.\n  simpl in *.\n  lia.\n  inversion H1.\n  constructor.\n  simpl in *.\n  lia.\n  -\n  inversion H0.\n  inversion H1.\n  constructor.\n  simpl in *.\n  lia.\n  inversion H1.\n  constructor.\n  simpl in *.\n  lia.\n  constructor.\n  simpl in *.\n  lia.\n  -\n  inversion H0.\n  inversion H1.\n  constructor.\n  simpl in *. lia.\n  inversion H1.\n  constructor.\n  simpl in *. lia.\n  constructor.\n  simpl in *.\n  lia.\n  inversion H1.\n  constructor.\n  simpl in *.\n  apply binary_lt_leq in H3. lia.\n  assert (length c = length b2 \\/ length b2 < length c).\n  apply binary_lt_leq in H3. lia.\n  inversion H9.\n  constructor 2.\n  lia.\n  constructor.\n  simpl.\n  lia.\n  -\n  inversion H0.\n  inversion H1.\n  constructor.\n  simpl in *.\n  lia.\n  apply binary_lt_leq in H7.\n  assert (length a = length b2 \\/ length a < length b2).\n  lia.\n  inversion H10.\n  constructor.\n  simpl in *.\n  lia.\n  constructor.\n  simpl in *.\n  lia.\n  -\n  inversion H0.\n  inversion H1.\n  constructor.\n  simpl in *.\n  lia.\n  apply binary_lt_leq in H7.\n  constructor.\n  simpl in *.\n  lia.\n  inversion H1.\n  apply binary_lt_leq in H3.\n  constructor.\n  simpl in *. lia.\n  constructor 3.\n  apply H with (b := b2).\n  simpl; auto.\n  assumption.\n  assumption.\nQed.\n\n\nLemma incr1_length: forall b, length b <= length (incr1 b).\nProof.\n  induction b using list_ind_length.\n  simpl. lia.\n  destruct b. simpl. auto. \n  simpl.\n  destruct b.\n  -\n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  + enough (length b0 <= length (incr1 b0)).\n  simpl. lia. apply H. simpl. auto.\n  + symmetry in Heqb.\n  apply PeanoNat.Nat.eqb_neq in Heqb.\n  simpl.\n  enough (length b0 < length (incr1 b0) ).\n  destruct (incr1 b0); simpl. \n  destruct b0; simpl in H0; lia.\n  simpl in H0. lia.\n  enough (length b0 <= length (incr1 b0)).\n  lia. apply H. simpl. lia.\n  - remember (length (incr1 b0) =? length b0).\n  destruct b.\n  + enough (length b0 <= length (incr1 b0)).\n  simpl. lia. apply H. simpl. auto.\n  + symmetry in Heqb.\n  apply PeanoNat.Nat.eqb_neq in Heqb.\n  simpl.\n  enough (length b0 < length (incr1 b0) ).\n  destruct (incr1 b0); simpl. \n  destruct b0; simpl in H0; lia.\n  simpl in H0. lia.\n  enough (length b0 <= length (incr1 b0)).\n  lia. apply H. simpl. lia.\nQed.\n\n\nLemma incr1_cons2_inv: forall b, Forall (eq E2) b -> length b < length (incr1 b).\nProof.\n  intros.\n  induction b using list_ind_length.\n  simpl. lia.\n  destruct b.\n  simpl. lia.\n  inversion_clear H.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  rewrite <- H1.\n  enough (b1 = false).\n  rewrite H.\n  simpl.\n  enough ((length b0) < (length (incr1 b0))).\n  lia.\n  apply H0. simpl. auto. auto.\n  rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_neq.\n  enough (length b0 < length (incr1 b0)).\n  lia. apply H0. simpl. auto.\n  auto.\nQed.\n\nLemma incr1_cons_over: forall b b0, length (incr1 (b :: b0)) <> length (b :: b0) -> \n        length (incr1 b0) <> length b0.\nProof.\n  intros.\n  generalize dependent b.\n  induction b0 using list_ind_length; intros.\n  simpl. lia.\n  enough (length (b :: b0) < length (incr1 (b :: b0)) ).\n  apply incr1_cons2 in H1.\n  inversion_clear H1.\n  remember (incr1_cons2_inv b0).\n  apply l in H3. lia.\n  enough (length (b :: b0) <= length (incr1 (b :: b0))).\n  lia.\n  apply incr1_length.\nQed.\n\n\nLemma decr1_incr1: forall b, decr1 (incr1 b) = b.\nProof.\n  intros.\n  induction b using list_ind_length.\n  simpl. auto.\n\n  destruct b. simpl. auto.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  destruct b; destruct b1.\n  all: simpl.\n  all: try rewrite H.\n  all: auto.\n  - \n  remember (incr1 b0).\n  destruct b.\n  destruct b0. simpl in Heqb. discriminate. \n  simpl in Heqb.\n  destruct b; destruct (length (incr1 b0) =? length b0); discriminate.\n  replace (length b0 =? length (b :: b1)) with true. auto.\n  rewrite Heqb1. apply PeanoNat.Nat.eqb_sym.\n  - destruct b0. simpl. auto.\n  rewrite <- incr1_tl_comm_E2.\n  simpl tl.\n  remember (incr1 b0).\n  destruct b1.\n  destruct b0. simpl in Heqb0. discriminate.\n  simpl in Heqb0.\n  destruct b0; destruct (length (incr1 b1) =? length b1); discriminate.\n  rewrite Heqb0.\n  rewrite H.\n  replace (length b0 =? length (incr1 b0)) with false.\n  replace b with E2. auto.\n  enough (Forall (eq E2) (b::b0)).\n  inversion H0. auto.\n  apply incr1_cons2.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (length (b :: b0) <= length (incr1 (b :: b0))).\n  lia. apply incr1_length.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  apply incr1_cons_over in Heqb1.\n  symmetry.\n  apply PeanoNat.Nat.eqb_neq. lia.\n  simpl. auto.\n  simpl. lia.\n  apply incr1_cons2.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (length (b :: b0) <= length (incr1 (b :: b0))).\n  lia. apply incr1_length.\n  - remember (incr1 b0).\n  destruct b.\n  destruct b0. simpl in Heqb. discriminate.\n  simpl in Heqb.\n  destruct b; destruct (length (incr1 b0) =? length b0); discriminate.\n  replace (length b0 =? length (b :: b1)) with true.\n  auto.\n  rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_sym.\n  - destruct b0. simpl. auto.\n  remember (incr1 (b::b0)).\n  destruct b1.\n  simpl in Heqb0. \n  destruct b; destruct (length (incr1 b0) =? length b0); discriminate.\n  rewrite Heqb0. rewrite Heqb0 in Heqb1.\n  replace (length (b :: b0) =? length (incr1 (b :: b0))) with false.\n  auto. rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_sym.\nQed.  \n\nLemma incr1_decr1: forall b,\n  0 < length b -> incr1 (decr1 b) = b.\nProof.\n  intros.\n  induction b using list_ind_length.\n  simpl in H. lia.\n\n  destruct b. simpl in H. lia.\n  simpl.\n  destruct b0.\n  destruct b. auto. auto.\n  remember (length (decr1 (b0 :: b1)) =? length (b0 :: b1)).\n  remember ((b0 :: b1)).\n  destruct b; destruct b2.\n  -\n  simpl. rewrite H0.\n  replace (length l =? length (decr1 l)) with true.\n  auto.\n  rewrite Heqb2.\n  apply PeanoNat.Nat.eqb_sym. auto.\n  rewrite Heql. simpl. lia.\n  -\n  simpl. rewrite H0.\n  replace (length l =? length (decr1 l)) with false.\n  auto.\n  rewrite Heqb2.\n  apply PeanoNat.Nat.eqb_sym. auto.\n  rewrite Heql. simpl. lia.\n  - simpl. rewrite H0.\n  replace (length l =? length (decr1 l)) with true.\n  auto.\n  rewrite Heqb2.\n  apply PeanoNat.Nat.eqb_sym. auto.\n  rewrite Heql. simpl. lia.\n  - simpl. rewrite H0.\n  replace (length l =? length (decr1 l)) with false.\n  simpl.\n  replace (length l =? length (decr1 l)) with false. \n  auto.\n  rewrite Heqb2.\n  apply PeanoNat.Nat.eqb_sym. \n  rewrite Heqb2.\n  apply PeanoNat.Nat.eqb_sym.\n  auto.\n  rewrite Heql. simpl. lia.\nQed.\n\nLemma lt_decr1: forall b, \n  0 < length b ->\n  binary_lt (decr1 b) b.\nProof.\n  intros.\n  rewrite <- incr1_decr1.\n  apply lt_incr1.\n  assumption.\nQed.\n\n  \n\n\nInductive iter_relation {X} (R: X -> X -> Prop): nat -> X -> X -> Prop :=\n| iter_relation0 : forall x y, R x y -> iter_relation R 0 x y\n| iter_relationS : forall x y' y n, R y' y -> iter_relation R n x y' -> iter_relation R (S n) x y.\n\n\n\nDefinition bilist_reducible_prop (R: bilist -> bilist -> Prop) : Prop := \n    forall y, exists n, forall x, (iter_relation R n x y -> False).\n  \n  \n\nLemma incr1_length_plus: forall b, length b < length (incr1 b) ->\n                                    S (length b) =  length (incr1 b).\nProof.\n  intros.\n  induction b using list_ind_length. auto.\n  destruct b. auto.\n  simpl. simpl in H.\n  remember (length (incr1 b0) =? length b0) as q.\n  destruct b; destruct q.\n  all: symmetry in Heqq.\n  all: first [ apply PeanoNat.Nat.eqb_eq in Heqq | apply PeanoNat.Nat.eqb_neq in Heqq ].\n  all: simpl.\n  all: simpl in H.\n  - exfalso. lia.\n  - \n  exfalso. \n  remember (length b0 =? length (incr1 b0)).\n  destruct b.\n  symmetry in Heqb. apply PeanoNat.Nat.eqb_eq in Heqb.\n  congruence.\n  symmetry in Heqb. apply PeanoNat.Nat.eqb_neq in Heqb.\n  enough (length b0 < length (incr1 b0)).\n  apply H0 in H1; auto.\n  rewrite H1 in H.\n  destruct b0. simpl in H. lia.\n  remember (incr1 (b :: b0)).\n  destruct b1. \n  simpl in Heqb1.\n  destruct b; destruct (length (incr1 b0) =? length b0); discriminate.\n  simpl in H. lia.\n  enough (length b0 <= length (incr1 b0)).\n  lia. apply incr1_length.\n  - enough (length b0 < length (incr1 b0)).\n  apply H0 in H1; auto.\n  lia.\n  - enough (length b0 < length (incr1 b0)).\n  apply H0 in H1; auto.\n  lia.\nQed.\n\n\nLemma incr2_length: forall b, length b <= length (incr2 b).\nProof.\n  induction b using list_ind_length.\n  simpl. lia.\n  destruct b. simpl. auto. \n  simpl.\n  destruct b.\n  -\n  remember (length (incr2 b0) =? length b0).\n  destruct b.\n  + \n  destruct b0. simpl. auto.\n  remember (b :: b0) as b1.\n  enough (length b1 <= length (incr2 b1)).\n  simpl. lia. apply H. simpl. auto.\n  + destruct b0. simpl. auto.\n  remember (b :: b0) as b1.\n  symmetry in Heqb.\n  apply PeanoNat.Nat.eqb_neq in Heqb.\n  simpl.\n  enough (length b1 < length (incr2 b1) ).\n  destruct (incr2 b1); simpl. \n  destruct b1; simpl in H0; lia.\n  simpl in H0. lia.\n  enough (length b1 <= length (incr2 b1)).\n  lia. apply H. simpl. lia.\n  - destruct b0. simpl. auto.\n  remember (b :: b0) as b1.\n  remember (length (incr2 b1) =? length b1).\n  destruct b2.\n  + enough (length b1 <= length (incr2 b1)).\n  simpl. lia. apply H. simpl. auto.\n  + symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_neq in Heqb2.\n  simpl.\n  enough (length b1 < length (incr2 b1)).\n  destruct (incr2 b1); simpl. \n  destruct b1; simpl in H0; lia.\n  simpl in H0. lia.\n  enough (length b1 <= length (incr2 b1)).\n  lia. apply H. simpl. lia.\nQed.\n\nLemma incr2_length_plus: forall b, length b < length (incr2 b) ->\n                                    S (length b) =  length (incr2 b).\nProof.\n  intros.\n  induction b using list_ind_length. auto.\n  destruct b. auto.\n  simpl. simpl in H.\n  remember (length (incr2 b0) =? length b0) as q.\n  destruct b; destruct q.\n  all: symmetry in Heqq.\n  all: first [ apply PeanoNat.Nat.eqb_eq in Heqq | apply PeanoNat.Nat.eqb_neq in Heqq ].\n  all: simpl.\n  all: simpl in H.\n  - exfalso. destruct b0. simpl in Heqq. lia.\n  remember (b :: b0) as b1. simpl in H. lia.\n  - \n  destruct b0. simpl. auto.\n  exfalso.\n  remember (b :: b0) as b1. simpl in H. \n  remember (length b1 =? length (incr2 b1)).\n  destruct b2.\n  symmetry in Heqb2. apply PeanoNat.Nat.eqb_eq in Heqb2.\n  congruence.\n  symmetry in Heqb2. apply PeanoNat.Nat.eqb_neq in Heqb2.\n  enough (length b1 < length (incr2 b1)).\n  apply H0 in H1; auto.\n  rewrite H1 in H.\n  remember (incr2 b1).\n  destruct b2. \n  simpl in Heqb2.\n  destruct b1; simpl in H1; discriminate.\n  simpl in H. lia.\n  enough (length b1 <= length (incr2 b1)).\n  lia. apply incr2_length.\n  -\n  destruct b0. simpl. auto.\n  remember (b :: b0) as b1. \n  enough (length b1 < length (incr2 b1)).\n  apply H0 in H1; auto. simpl. congruence.\n  simpl in H. lia.\n  -\n  destruct b0. simpl. auto.\n  remember (b :: b0) as b1. \n  enough (length b1 < length (incr2 b1)).\n  apply H0 in H1; simpl; auto.\n  simpl in H. lia.\nQed.\n\nLemma incr2_incr1_length: forall b, length (incr1 b) <= length (incr2 b).\nProof.\n  induction b using list_ind_length.\n  simpl. lia.\n  destruct b. simpl. auto. \n  simpl.\n  destruct b.\n  all: destruct b0; auto.\n  simpl. lia.\n  all: remember b0 as b2. \n  all: clear Heqb2.\n  all: clear b0.\n  all: remember (b :: b2) as b0. \n  -\n  remember (length (incr1 b0) =? length b0) as p.\n  remember (length (incr2 b0) =? length b0) as q.\n  destruct p; destruct q.\n  + enough (length (incr1 b0) <= length (incr2 b0)).\n  simpl. lia. apply H. simpl. auto.\n  + symmetry in Heqp. symmetry in Heqq.\n  apply PeanoNat.Nat.eqb_eq in Heqp.\n  apply PeanoNat.Nat.eqb_neq in Heqq.\n  simpl.\n  enough (length (incr1 b0) < length (incr2 b0) ).\n  destruct (incr2 b0); simpl. \n  destruct b0; simpl in H0; lia.\n  simpl in H0. lia.\n  enough (length b0 <= length (incr2 b0)).\n  enough (length b0 <= length (incr1 b0)).\n  lia. apply incr1_length. apply incr2_length.\n  + symmetry in Heqp. symmetry in Heqq.\n  apply PeanoNat.Nat.eqb_neq in Heqp.\n  apply PeanoNat.Nat.eqb_eq in Heqq.\n  exfalso.\n  enough (length b0 <= length (incr2 b0)).\n  enough (length b0 <= length (incr1 b0)).\n  enough (length (incr1 b0) <= length (incr2 b0)).\n  lia. apply H. auto. apply incr1_length. apply incr2_length.\n  +  symmetry in Heqp. symmetry in Heqq.\n  apply PeanoNat.Nat.eqb_neq in Heqp.\n  apply PeanoNat.Nat.eqb_neq in Heqq.\n  simpl.\n  enough (length (incr1 b0) <= length (incr2 b0)).\n  destruct (incr1 b0) ; destruct (incr2 b0); try lia; auto.\n  simpl. destruct b1; simpl; lia.\n  apply H; auto.\n  - remember (length (incr1 b0) =? length b0) as p.\n  remember (length (incr2 b0) =? length b0) as q.\n  destruct p; destruct q.\n  + enough (length (incr1 b0) <= length (incr2 b0)).\n  simpl. lia. apply H. simpl. auto.\n  + symmetry in Heqp. symmetry in Heqq.\n  apply PeanoNat.Nat.eqb_eq in Heqp.\n  apply PeanoNat.Nat.eqb_neq in Heqq.\n  simpl.\n  enough (length (incr1 b0) < length (incr2 b0) ).\n  destruct (incr2 b0); simpl. \n  destruct b0; simpl in H0; lia.\n  simpl in H0. lia.\n  enough (length b0 <= length (incr2 b0)).\n  enough (length b0 <= length (incr1 b0)).\n  lia. apply incr1_length. apply incr2_length.\n  + symmetry in Heqp. symmetry in Heqq.\n  apply PeanoNat.Nat.eqb_neq in Heqp.\n  apply PeanoNat.Nat.eqb_eq in Heqq.\n  exfalso.\n  enough (length b0 <= length (incr2 b0)).\n  enough (length b0 <= length (incr1 b0)).\n  enough (length (incr1 b0) <= length (incr2 b0)).\n  lia. apply H. auto. apply incr1_length. apply incr2_length.\n  +  symmetry in Heqp. symmetry in Heqq.\n  apply PeanoNat.Nat.eqb_neq in Heqp.\n  apply PeanoNat.Nat.eqb_neq in Heqq.\n  simpl.\n  enough (length (incr1 b0) <= length (incr2 b0)).\n  destruct (incr1 b0) ; destruct (incr2 b0); try lia; auto.\n  apply H; auto.\nQed.  \n\n\nLemma incr1_E1: forall b, 0 < length b -> Forall (eq E1) b -> \n    length b = length (incr1 b).\nProof.\n    induction b using list_ind_length; intros. \n    simpl in H. lia.\n    destruct b. simpl. simpl in H0. lia.\n    inversion_clear H1.\n    simpl.\n    remember (length (incr1 b0) =? length b0) as q.\n  destruct b; destruct q.\n  all: symmetry in Heqq.\n  all: first [ apply PeanoNat.Nat.eqb_eq in Heqq | apply PeanoNat.Nat.eqb_neq in Heqq ].\n  all: simpl.\n  all: simpl in H0.\n  - lia.\n  - enough (length b0 < length (incr1 b0)).\n  apply incr1_length_plus in H1.\n  rewrite H1.\n  destruct (incr1 b0). simpl in H1.\n  lia. simpl. auto.\n  enough (length b0 <= length (incr1 b0)).\n  lia.\n  apply incr1_length.\n  - congruence.\n  - discriminate.\nQed.  \n\nLemma incr2_incr1: forall b, incr1 (incr1 b) = incr2 b.\nProof.\n  induction b using list_ind_length.\n  auto.\n  destruct b. simpl. auto. simpl.\n\n  destruct b0. simpl.\n  destruct b; auto.\n\n  all: remember b0 as b2. \n  all: clear Heqb2.\n  all: clear b0.\n  all: remember (b2 :: b1) as b0. \n\n  remember (length (incr1 b0) =? length b0) as q1.\n  remember (length (incr2 b0) =? length b0) as q2.\n\n  destruct b; destruct q1; destruct q2; simpl. \n  all: try rewrite H; auto.\n\n  all: symmetry in Heqq1. \n  all: symmetry in Heqq2. \n  all: first [ apply PeanoNat.Nat.eqb_eq in Heqq1 | apply PeanoNat.Nat.eqb_neq in Heqq1 ].\n  all: first [ apply PeanoNat.Nat.eqb_eq in Heqq2 | apply PeanoNat.Nat.eqb_neq in Heqq2 ].\n\n  - \n  replace (length (incr2 b0) =? length (incr1 b0)) with true. auto.\n  symmetry. apply PeanoNat.Nat.eqb_eq. congruence.\n\n  -\n  replace (length (incr2 b0) =? length (incr1 b0)) with false. auto. \n  symmetry. apply PeanoNat.Nat.eqb_neq. congruence.\n\n  - exfalso.\n  enough (length b0 <= length (incr1 b0)).\n  enough (length b0 <= length (incr2 b0)).\n  enough (length (incr1 b0) <= length (incr2 b0)).\n  lia.\n  apply incr2_incr1_length.\n  apply incr2_length.\n  apply incr1_length.\n  \n  - replace (length (incr1 (tl (incr1 b0))) =? length (tl (incr1 b0))) with true.\n  destruct b0. simpl. discriminate.\n  destruct b0. simpl. destruct b; auto.\n  rewrite <- H.\n  rewrite incr1_tl_comm_E1; auto.\n  enough (length (b :: b0 :: b3) <= length (incr1 (b :: b0 :: b3))).\n  simpl in H0. simpl. lia.\n  apply incr1_length.\n  apply incr1_cons1.\n  enough (length (b :: b0 :: b3) <= length (incr1 (b :: b0 :: b3))).\n  lia.  apply incr1_length.\n  simpl. lia.\n  symmetry.\n  apply PeanoNat.Nat.eqb_eq .\n  rewrite <- incr1_E1. auto.\n  rewrite Heqb0.\n  simpl.\n  destruct b2; destruct (length (incr1 b1) =? length b1); simpl; auto.\n  + destruct b1. simpl. auto. \n    simpl. destruct (length (incr1 b1) =? length b1); destruct b; simpl; try lia.\n  + rewrite Heqb0 in Heqq1.\n  enough (length (E1 :: b1) < length (incr1 (E1 :: b1)))  .\n  apply incr1_cons2 in H0.\n  inversion H0. discriminate.\n  enough (length (E1 :: b1) <= length (incr1 (E1 :: b1))).\n  lia.\n  apply incr1_length.\n  + destruct b1. auto.\n  simpl. destruct b; destruct (length (incr1 b1) =? length b1); simpl; lia.\n  + destruct b1. auto.\n  simpl. destruct b; destruct (length (incr1 b1) =? length b1); simpl; lia.\n  + \n  enough (length b0 < length (incr1 b0)).\n  apply incr1_cons1 in H0.\n  destruct (incr1 b0).\n  auto.\n  inversion H0. simpl. auto.\n  enough (length b0 <= length (incr1 b0)).\n  lia.\n  apply incr1_length.\n  - replace (length (incr2 b0) =? length (incr1 b0)) with true.\n  auto.\n  symmetry. apply PeanoNat.Nat.eqb_eq. congruence.\n  - replace (length (incr2 b0) =? length (incr1 b0)) with false.\n  auto.\n  symmetry. apply PeanoNat.Nat.eqb_neq. congruence.\n  - exfalso.\n  enough (length b0 < length (incr1 b0)).\n  enough (length (incr1 b0) <= length (incr2 b0)).\n  lia.\n  apply incr2_incr1_length.\n  enough (length b0 <= length (incr1 b0)).\n  lia.\n  apply incr1_length.\n  - replace (length (incr2 b0) =? length (incr1 b0)) with true.\n  auto.\n  symmetry. apply PeanoNat.Nat.eqb_eq.\n  rewrite <- incr1_length_plus.\n  rewrite <- incr2_length_plus.\n  auto.\n  enough (length b0 <= length (incr2 b0)).\n  lia.\n  apply incr2_length.\n  enough (length b0 <= length (incr1 b0)).\n  lia.\n  apply incr1_length.\nQed.\n\nPrint nat_ind.\n\nExample test_lt1: binary_lt [E1; E2; E1] [E2; E1; E1].\nProof.\n  apply binary_lt_E. auto.\nQed.\n\nExample test_lt2: binary_lt [E1; E2; E1] [E1; E2; E2; E2].\nProof.\n  apply binary_lt_cons. auto.\nQed.\n\nExample test_lt3: binary_lt [E1; E1] [E1; E2].\nProof.\n  apply binary_lt_cons2. apply binary_lt_E. auto.\nQed.\n\n\n\n\n\n\nLemma bilist_lt_length: forall x y, binary_lt x y -> length x <= length y.\nProof.\n  intros.\n  generalize dependent x.\n  induction y; intros.\n  inversion H.\n  inversion H.\n  simpl. lia.\n  simpl. lia.\n  simpl. apply IHy in H2. lia.\nQed.\n\n\nExample iter_relation1: iter_relation binary_lt 3 [] [E1; E2].\nProof.\n  apply iter_relationS with (y':=[E1;E1]).\n  constructor 3. constructor 2. auto. \n  apply iter_relationS with (y':=[E2]).\n  constructor 1. auto.\n  apply iter_relationS with (y':=[E1]).\n  constructor 2. auto.\n  apply iter_relation0.\n  constructor. auto.\nQed.  \n\nLemma iter_relation_S: forall n x y,  \niter_relation binary_lt (S n) x y ->\n        exists y', iter_relation binary_lt n y' y.\nProof.\n  intros.\n  generalize dependent x.\n  generalize dependent y.\n  induction n; intros.\n  inversion H.\n  exists y'. constructor. auto.\n  inversion H.\n  apply IHn in H2.\n  inversion H2.\n  exists x1.\n  apply iter_relationS with (y'0:=y'); auto. \nQed.\n\nLemma iter_relation_S2: forall n x y,  \niter_relation binary_lt (S n) x y ->\n        exists y', iter_relation binary_lt n y' y /\\ binary_lt x y'.\nProof.\n  intros.\n  generalize dependent x.\n  generalize dependent y.\n  induction n; intros.\n  inversion H.\n  exists y'. split. constructor. auto.\n  inversion H2. auto.\n\n  inversion H.\n  apply IHn in H2.\n  inversion H2. inversion_clear H5.\n  exists x1. split.\n  apply iter_relationS with (y'0:=y'); auto.\n  auto. \nQed.\n\nLemma iter_relation_plus: forall n m x y,  \niter_relation binary_lt (n + m) x y ->\n        exists y', iter_relation binary_lt m y' y.\nProof.\n  intros.\n  generalize dependent x.\n  generalize dependent y.\n  induction n; intros.\n  exists x. simpl in H. auto.\n  simpl in H.\n  inversion H.\n  apply IHn in H2.\n  destruct H2.\n  (* x1 < ... < y' < y *)\n  destruct m.\n  exists y'.\n  constructor. auto.\n  apply iter_relation_S in H2.\n  inversion H2.\n  exists x2.\n  apply iter_relationS with (y'0:=y'); auto. \nQed.\n\nLemma iter_relation_S_inv: forall n x y x',  \niter_relation binary_lt n x' y ->\nbinary_lt x x' ->\niter_relation binary_lt (S n) x y.\nProof.\n  intros.\n  generalize dependent x.\n  generalize dependent y.\n  induction n; intros.\n  apply iter_relationS with (y':=x').\n  inversion H. auto.\n  constructor. auto.\n  inversion H.\n  apply IHn  with (x:=x) in H3.\n  apply iter_relationS with (y'0:=y').\n  auto. auto. auto.\nQed.\n\n\nLemma iter_relation_trans: forall n m x y z,  \niter_relation binary_lt (n + m) x z ->\n(forall x0 : bilist, iter_relation binary_lt m x0 z -> binary_lt x0 y ) ->\niter_relation binary_lt n x y.\nProof.\n  intros.\n  generalize dependent x.\n  generalize dependent y.\n  generalize dependent z.\n  induction n; intros.\n  apply H0 in H.\n  constructor. auto.\n  simpl in H.\n  inversion H.\n  apply iter_relation_S2 in H.\n  inversion H. inversion_clear H6.\n    \n  apply IHn with (y:=y) in H7 ; auto.\n\n  apply iter_relation_S_inv with (x':=x1) .\n  auto. auto.\nQed.\n\nCheck Nat.pow.\n\nCompute pow 2 1.\n\nLemma binary_lt_length: forall a b, \nbinary_lt a b -> length a <= length b.\nProof.\n  intros.\n  generalize dependent a.\n  induction b using list_ind_length; intros.\n  inversion H.\n  destruct b.\n  inversion H0.\n  inversion H0.\n  -\n  simpl. lia.\n  - \n  simpl. lia.\n  -\n  simpl.\n  assert (length x <= length b0).\n  apply H. simpl. lia.\n  auto.\n  lia.\nQed.\n\n\n\nLemma allE2_noless: forall a b, length a = length b -> \n                  Forall (eq E2) b ->\n                  Forall (eq E2) a \\/ binary_lt a b.\nProof.\n  intros.\n  generalize dependent a.\n  induction b using list_ind_length; intros.\n  left.\n  destruct a.\n  auto.\n  simpl in H. lia.\n  destruct b.\n  left.\n  destruct a. auto.\n  simpl in H1. lia.\n  destruct a.\n  left. auto.\n  assert (Forall (eq E2) a \\/ binary_lt a b0).\n  apply H.\n  simpl. lia.\n  inversion H0. auto.\n  simpl in H1. auto.\n  inversion_clear H2.\n  destruct b1.\n  right.\n  inversion_clear H0.\n  rewrite <- H2.\n  apply binary_lt_E. simpl in H1. auto.\n  left. constructor. auto. auto.\n  inversion_clear H0.\n  rewrite <- H2.\n  right.\n  destruct b1.\n  apply binary_lt_trans with (b:=E2::a).\n  apply binary_lt_E. auto.\n  apply binary_lt_cons2. auto.\n  apply binary_lt_cons2. auto.\nQed.\n  \n\nLemma Forall_eq_length: forall X (l l': list X) x, \nlength l = length l' -> \nForall (eq x) l -> Forall (eq x) l' -> l = l'.\nProof.\n  intros.\n  generalize dependent l'.\n  induction l; intros.\n  destruct l'. auto.\n  simpl in H.\n  lia.\n  destruct l'.\n  simpl in H. lia.\n  simpl in H.\n  inversion H.\n  apply IHl in H3.\n  inversion_clear H0.\n  inversion_clear H1.\n  congruence.\n  inversion_clear H0. auto.\n  inversion_clear H1. auto.\nQed.\n\n\nLemma binary_lt_decr1: forall a b, \nbinary_lt a b -> a = decr1 b \\/ binary_lt a (decr1 b).\nProof.\n  intros.\n  generalize dependent a.\n  induction b using list_ind_length; intros.\n  inversion H.\n  destruct b.\n  inversion H0.\n  destruct b. \n  - (* E1 *)\n  destruct a.\n  destruct b0.\n  left. auto.\n  right. simpl.\n  destruct b. destruct b0.\n  simpl. constructor. simpl. auto.\n  destruct (length (decr1 (b :: b0)) =? length (b :: b0)).\n  destruct (length (E1 :: decr1 (b :: b0)) =? S (length (b :: b0))).\n  constructor. simpl. lia.\n  constructor. simpl. lia.\n  destruct (length (E2 :: decr1 (b :: b0)) =? S (length (b :: b0))).\n  constructor. simpl. lia.\n  constructor. simpl. lia.\n  destruct b0.\n  simpl. constructor. simpl. lia.\n  destruct (length (decr1 (b :: b0)) =? length (b :: b0)).\n  destruct (length (E2 :: decr1 (b :: b0)) =? S (length (b :: b0))).\n  constructor. simpl. lia.\n  constructor. simpl. lia.\n  destruct (length (E1 :: E2 :: decr1 (b :: b0)) =? S (length (b :: b0))).\n  constructor. simpl. lia.\n  constructor. simpl. lia.\n  destruct b.\n  + (*E1*)\n  inversion H0.\n  *\n  simpl.\n  destruct b0.\n  simpl in H3. lia.\n  remember ((b0 :: b1)) as b'.\n  remember (length (decr1 b') =? length b' ).\n  destruct b2.\n  **\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H. simpl. lia.\n  destruct b'.\n  simpl in H3. lia.\n  simpl in H3.\n  apply binary_lt_cons. simpl. lia.\n  inversion_clear H5.\n  left. congruence.\n  right.\n  apply binary_lt_cons2. auto.\n  **\n  right.\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H. simpl. lia.\n  destruct b'.\n  simpl in H3. lia.\n  simpl in H3.\n  apply binary_lt_cons. simpl. lia.\n  inversion_clear H5.\n  rewrite <- H6.\n  apply binary_lt_E. auto.\n  apply binary_lt_trans with (b:=E2::a).\n  apply binary_lt_E. auto.\n  apply binary_lt_cons2. auto.\n  *\n  assert (a = decr1 b0 \\/ binary_lt a (decr1 b0)).\n  apply H. simpl. lia.\n  auto.\n  simpl.\n  destruct b0.\n  inversion H2.\n  remember (b0::b1) as b'.\n  remember (length (decr1 b') =? length b').\n  destruct b2.\n  **\n  inversion_clear H5.\n  left. congruence.\n  right.\n  apply binary_lt_cons2. auto.\n  **\n  inversion_clear H5.\n  right. rewrite <- H6.\n  apply binary_lt_E. auto.\n  right.\n  apply binary_lt_trans with (b:=E2::a).\n  apply binary_lt_E. auto.\n  apply binary_lt_cons2. auto.\n  + (*E2*)\n  inversion H0.\n  simpl.\n  destruct b0. simpl in H3. lia.\n  remember (b0 :: b1) as b'.\n  remember (length (decr1 b') =? length b').\n  destruct b2.\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H.\n  simpl. lia.\n  destruct b'.\n  simpl in H3. lia.\n  simpl in H3.\n  apply binary_lt_cons. lia.\n  **\n  right.\n  inversion_clear H5.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_eq in Heqb2.\n  simpl in H3.\n  rewrite <- Heqb2 in H3.\n  rewrite <- H6 in H3. lia.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_eq in Heqb2.\n  simpl in H3.\n  rewrite <- Heqb2 in H3.\n  apply binary_lt_length in H6.\n  apply binary_lt_cons. simpl. lia.\n  **\n  simpl in H3.\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H.\n  simpl. lia.\n  destruct b'. simpl in H3.\n  lia.\n  apply binary_lt_cons. simpl in H3. lia.\n  inversion_clear H5.\n  left. congruence.\n  right.\n  apply binary_lt_cons2. auto.\n  - (* E2 *)\n  destruct a.\n  destruct b0.\n  right. simpl. constructor. simpl. lia.\n  right. simpl.\n  destruct b. destruct b0.\n  simpl. constructor. simpl. auto.\n  destruct (length (decr1 (b :: b0)) =? length (b :: b0)).\n  destruct (length (E1 :: decr1 (b :: b0)) =? S (length (b :: b0))).\n  constructor. simpl. lia.\n  constructor. simpl. lia.\n  destruct (length (E2 :: decr1 (b :: b0)) =? S (length (b :: b0))).\n  constructor. simpl. lia.\n  constructor. simpl. lia.\n  destruct b0.\n  simpl. constructor. simpl. lia.\n  destruct (length (decr1 (b :: b0)) =? length (b :: b0)).\n  destruct (length (E2 :: decr1 (b :: b0)) =? S (length (b :: b0))).\n  constructor. simpl. lia.\n  constructor. simpl. lia.\n  destruct (length (E1 :: E2 :: decr1 (b :: b0)) =? S (length (b :: b0))).\n  constructor. simpl. lia.\n  constructor. simpl. lia.\n  destruct b.\n  + (*E1*)\n  inversion H0.\n  *\n  simpl.\n  destruct b0.\n  simpl in H3. lia.\n  remember ((b0 :: b1)) as b'.\n  remember (length (decr1 b') =? length b' ).\n  destruct b2.\n  **\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H. simpl. lia.\n  destruct b'.\n  simpl in H3. lia.\n  simpl in H3.\n  apply binary_lt_cons. simpl. lia.\n  inversion_clear H5.\n  right.\n  rewrite <- H6.\n  apply binary_lt_E. auto.\n  right.\n  apply binary_lt_trans with (b:=E2::a).\n  apply binary_lt_E. auto.\n  apply binary_lt_cons2. auto.\n  **\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H. simpl. lia.\n  destruct b'.\n  simpl in H3. lia.\n  simpl in H3.\n  apply binary_lt_cons. simpl. lia.\n  inversion_clear H5.\n  right.\n  rewrite <- H6.\n  apply binary_lt_cons. simpl. lia.\n  right.\n  apply binary_lt_length in H6.\n  apply binary_lt_cons. simpl. lia.\n  *\n  simpl.\n  destruct b0.\n  destruct a. left. auto.\n  simpl in H3. lia.\n  remember ((b :: b0)) as b'.\n  remember (length (decr1 b') =? length b' ).\n  destruct b1.\n  right.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  apply binary_lt_E. congruence.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  remember (H (E2::decr1 b')).\n  clear Heqo.\n  assert (forall a,binary_lt a (E2 :: decr1 b') -> a = decr1 (E2 :: decr1 b') \\/ binary_lt a (decr1 (E2 :: decr1 b'))).\n  apply o.\n  simpl.\n  enough (length (decr1 b') < length b').\n  lia.\n  rewrite <- incr1_decr1 with (b:=b') at 2.\n  enough (length (decr1 b') <= length (incr1 (decr1 b'))).\n  enough (length (decr1 b') <> length (incr1 (decr1 b'))).\n  lia.\n  rewrite incr1_decr1. auto.\n  destruct b'. simpl in Heqb1. lia.\n  simpl. lia.\n  apply incr1_length.\n  destruct b'. simpl in Heqb1. lia.\n  simpl. lia.\n  clear o.\n  enough (Forall (eq E2) (decr1 b')).\n  remember H3. clear Heqe.\n  replace (length b') with (length (E2::decr1 b')) in e.  \n  apply allE2_noless in e.\n  inversion_clear e.\n  left.\n  apply Forall_eq_length  with (l':=E2 :: decr1 b') in H6.\n  congruence.\n  rewrite H3.\n  simpl.\n  rewrite <- incr1_decr1 with (b:=b') at 1.\n  symmetry.\n  apply incr1_length_plus.\n  enough (length (decr1 b') <= length (incr1 (decr1 b'))).\n  enough (length (decr1 b') <> length (incr1 (decr1 b'))).\n  lia.\n  rewrite incr1_decr1. auto.\n  destruct b'. simpl in Heqb1. lia.\n  simpl. lia.\n  apply incr1_length.\n  destruct b'. simpl in Heqb1. lia.\n  simpl. lia.\n  constructor. auto. auto.\n  right.\n  apply binary_lt_cons2. auto.\n  constructor.\n  auto.\n  apply incr1_cons2.\n  enough (length (decr1 b') <= length (incr1 (decr1 b'))).\n  enough (length (decr1 b') <> length (incr1 (decr1 b'))).\n  lia.\n  rewrite incr1_decr1. auto.\n  destruct b'. simpl in Heqb1. lia.\n  simpl. lia.\n  apply incr1_length.\n  simpl. \n  rewrite <- incr1_decr1 with (b:=b') at 2.\n  apply incr1_length_plus.\n  enough (length (decr1 b') <= length (incr1 (decr1 b'))).\n  enough (length (decr1 b') <> length (incr1 (decr1 b'))).\n  lia.\n  rewrite incr1_decr1. auto.\n  destruct b'. simpl in Heqb1. lia.\n  simpl. lia.\n  apply incr1_length.\n  destruct b'. simpl in Heqb1. lia.\n  simpl. lia.\n  apply incr1_cons2.\n  enough (length (decr1 b') <= length (incr1 (decr1 b'))).\n  enough (length (decr1 b') <> length (incr1 (decr1 b'))).\n  lia.\n  rewrite incr1_decr1. auto.\n  destruct b'. simpl in Heqb1. lia.\n  simpl. lia.\n  apply incr1_length.\n  +\n  inversion H0.\n  *\n  simpl.\n  destruct b0.\n  destruct a. left. auto.\n  simpl in H3. lia.\n  simpl in H3. lia.\n  remember ((b0 :: b1)) as b'.\n  remember (length (decr1 b') =? length b' ).\n  destruct b2.\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H.\n  simpl. lia.\n  destruct b'.\n  simpl in H3. lia.\n  apply binary_lt_cons. simpl in H3. lia.\n  inversion_clear H5.\n  left.\n  rewrite <- H6.\n  auto. right.\n  apply binary_lt_cons2. auto.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_neq in Heqb2.\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H.\n  simpl. lia.\n  destruct b'.\n  simpl in H3. lia.\n  simpl in H3. apply binary_lt_cons. lia.\n  inversion_clear H5.\n  right. rewrite <- H6.\n  apply binary_lt_cons. lia.\n  right.\n  apply binary_lt_length in H6.\n  apply binary_lt_cons. simpl. lia.\n  *\n  simpl.\n  destruct b0.\n  inversion H2.\n  remember (b0::b1) as b'.\n  remember (length (decr1 b') =? length b').\n  assert (a = decr1 b' \\/ binary_lt a (decr1 b')).\n  apply H.\n  simpl. lia.\n  auto.\n  destruct b2.\n  **\n  inversion_clear H5.\n  left. congruence.\n  right. apply binary_lt_cons2. auto.\n  **\n  inversion_clear H5.\n  right.\n  rewrite <- H6.\n  apply binary_lt_cons. simpl. lia. \n  right.\n  apply binary_lt_cons. \n  apply binary_lt_length in H6.\n  simpl. lia. \nQed.\n\nLemma iterS: forall X f (x:X) n, iter (S n) f x = f (iter n f x).\nProof.\n  intros.\n  generalize dependent x.\n  induction n; intros.\n  simpl. auto.\n  simpl.\n  rewrite <-IHn. simpl. auto.\n  \nQed.\n\n\nLemma decr1_lt: forall b, 0 < length b -> binary_lt (decr1 b) b.\nProof.\n  intros.\n  rewrite <- incr1_decr1.\n  apply lt_incr1.\n  auto.\nQed.\n\n\nLemma binary_lt_decr1_iter: forall a b n, \niter_relation binary_lt n a b -> \na = iter (S n) decr1 b \\/ binary_lt a (iter (S n) decr1 b).\nProof.\n  intros.\n  generalize dependent a.\n  generalize dependent b.\n  induction n; intros.\n  inversion H.\n  simpl.\n  apply binary_lt_decr1. auto.\n  apply iter_relation_S2 in H.\n  inversion_clear  H.\n  inversion_clear H0.\n  apply IHn in H.\n  inversion_clear H.\n  rewrite iterS.\n  rewrite <- H0.\n  apply binary_lt_decr1. auto.\n  rewrite iterS.\n  remember ((iter (S n) decr1 b)) as b'.\n  apply binary_lt_decr1 in H1.\n  apply binary_lt_decr1 in H0.\n  inversion_clear H1; inversion_clear H0.\n  -\n  destruct x.\n  left.\n  simpl in H. congruence.\n  right. rewrite <- H1.\n  rewrite H. \n  apply decr1_lt. simpl. lia.\n  -\n  rewrite H.\n  destruct x.\n  destruct b'.\n  inversion H1.\n  right. apply H1.\n  right.\n  apply binary_lt_trans with (b:=b0::x).\n  apply decr1_lt. simpl. lia.\n  auto.\n  -\n  rewrite H1 in H.\n  destruct (decr1 b').\n  inversion H.\n  right. apply binary_lt_trans with (b:=decr1(b0::l)).\n  auto.\n  apply decr1_lt. simpl. lia.\n  -\n  right.\n  destruct x.\n  inversion H.\n  apply binary_lt_trans with (b:=decr1 (b0 :: x)).\n  auto.\n  apply binary_lt_trans with (b:=b0 :: x).\n  apply decr1_lt. simpl. lia.\n  auto.\nQed.\n\nLemma iter_decr1_nil: forall n, iter n decr1 [] = [].\nProof.\n  intros.\n  induction n; intros.\n  simpl. auto.\n  simpl. auto.\nQed.\n\nCheck binary_lt_decr1.\n\nLemma decr1_length: forall a, length (decr1 a) <= length a.\nProof.\n  intros.\n  destruct a.\n  simpl. lia.\n  remember (b::a) as a'.\n  rewrite <- incr1_decr1 with (b:=a') at 2.\n  apply incr1_length.\n  rewrite Heqa'.\n  simpl. lia.\nQed.\n\n\nLemma binary_lt_with_decr1: forall a b,\nbinary_lt [E1] b ->\nbinary_lt a b -> \nbinary_lt (decr1 a) (decr1 b) .\nProof.\n  intros.\n  remember H0. clear Heqb0.\n  apply binary_lt_decr1 in b0.\n  inversion_clear b0.\n  rewrite H1.\n  apply decr1_lt.\n  destruct b. inversion H0.\n  simpl. \n  destruct b; destruct b0.\n  inversion H. simpl in H4. lia.\n  inversion H3.\n  destruct (length (decr1 (b :: b0)) =? length (b :: b0));simpl; lia.\n  simpl. lia.\n  destruct (length (decr1 (b :: b0)) =? length (b :: b0));simpl; lia.\n  destruct a.\n  simpl. auto.\n  apply binary_lt_trans with (b:=b0::a).\n  apply decr1_lt. simpl. lia.\n  auto.\nQed.\n\n\nLemma firstn_all_length: forall X (y: list X), firstn (length y) y = y.\nProof.\n  intros.\n  induction y.\n  simpl. auto.\n  simpl.\n  rewrite IHy. auto.\nQed.\n  \nLemma skipn_all_length: forall X (y: list X), skipn (length y) y = [].\nProof.\n  intros.\n  induction y.\n  simpl. auto.\n  simpl.\n  rewrite IHy. auto.\nQed.\n\n\nLemma iter_plus: forall X m n f (x:X), \niter (m+n) f x = iter m f (iter n f x).\nProof.\n  intros.\n  generalize dependent x.\n  induction m; intros.\n  simpl. auto.\n  simpl.\n  rewrite IHm.\n  rewrite <- iterS.\n  simpl.\n  auto.\nQed.\n\nLemma incr2_in_next: forall y b, length (incr1 y) = length y ->\nlength (incr2 (y++[b])) = length (y ++[b]).\nProof.\n  intros.\n  generalize dependent b.\n  induction y using list_ind_length; intros.\n  simpl in H.\n  lia.\n  destruct y.\n  simpl in H. lia.\n  simpl.\n  simpl in H.\n  remember (length (incr1 y) =? length y).\n  remember (length (incr2 (y ++ [b])) =? length (y ++ [b])).\n  remember (y++[b]).\n  destruct l.\n  destruct y; simpl in Heql; discriminate.\n  rewrite Heql.\n  rewrite Heql in Heqb2.\n  destruct b0; destruct b1; destruct b2.\n  - (*8*)\n  simpl in H.\n  simpl.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_eq in Heqb2.\n  lia.\n  - (*7*)\n  simpl in H.\n  simpl.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_neq in Heqb2.\n  inversion H.\n  apply H0  with (b:=b) in H2.\n  contradiction.\n  simpl. lia.\n  - (*6*)\n  simpl in H.\n  simpl.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_eq in Heqb2.\n  lia.\n  - (*5*)\n  simpl in H.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_neq in Heqb2.\n  simpl.\n  enough (length (incr2 (y ++ [b])) = S (length (y ++ [b]))).\n  destruct (incr2 (y ++ [b])).\n  simpl in H1.\n  lia.\n  simpl in H1. simpl.\n  lia.\n  rewrite incr2_length_plus.\n  auto.\n  enough (length (y ++ [b]) <= length (incr2 (y ++ [b]))).\n  lia.\n  apply incr2_length.\n  - (*4*)\n  simpl in H.\n  simpl.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_eq in Heqb2.\n  lia.\n  - (*3*)\n  simpl in H.\n  inversion H.\n  apply H0 with (b:=b) in H2 .\n  simpl. lia.\n  simpl. lia.\n  - (*2*)\n  simpl in H. simpl.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_eq in Heqb2.\n  lia.\n  - (*1*)\n  simpl in H. simpl.\n  symmetry in Heqb2.\n  apply PeanoNat.Nat.eqb_neq in Heqb2.\n  inversion H.\n  apply H0  with (b:=b) in H2.\n  contradiction.\n  simpl. lia.\nQed.\n\n\n\nLemma incr2_in_next_inv: forall y b,  \nlength (incr2 (y++[b])) = length (y ++[b]) -> \nlength (incr1 y) = length y.\nProof.\n  intros.\n  generalize dependent b.\n  induction y using list_ind_length; intros.\n  simpl. simpl in H.\n  destruct b. \n  simpl in H. lia.\n  simpl in H. lia.\n  destruct y.\n  simpl in H0. \n  destruct b; simpl in H0; lia.\n  simpl.\n  simpl in H0.\n  remember (length (incr1 y) =? length y).\n  remember (length (incr2 (y ++ [b])) =? length (y ++ [b])).\n  remember (y++[b]).\n  destruct l.\n  destruct y; simpl in Heql; discriminate.\n  rewrite Heql in H0.\n  rewrite Heql in Heqb2.\n  destruct b0; destruct b2; destruct b1.\n  - (*8*)\n  simpl in H0.\n  simpl.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  lia.\n  - (*7*)\n  simpl in H0.\n  simpl.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  inversion H0.\n  apply H with (b:=b) in H2.\n  contradiction.\n  simpl. lia.\n  - (*6*)\n  simpl in H0.\n  simpl.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  lia.\n  - (*5*)\n  simpl in H0.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  simpl.\n  enough (length (incr1 y) = S (length y)).\n  destruct (incr1 y).\n  simpl in H1.\n  lia.\n  simpl in H1. simpl.\n  lia.\n  rewrite incr1_length_plus.\n  auto.\n  enough (length y <= length (incr1 y)).\n  lia.\n  apply incr1_length.\n  - (*4*)\n  simpl in H0.\n  simpl.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  lia.\n  - (*3*)\n  simpl in H0.\n  inversion H0.\n  apply H with (b:=b) in H2 .\n  simpl. lia.\n  simpl. lia.\n  - (*2*)\n  simpl in H0. simpl.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  lia.\n  - (*1*)\n  simpl in H0. simpl.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  inversion H0.\n  apply H with (b:=b) in H2.\n  contradiction.\n  simpl. lia.\nQed.\n\n\nLemma iter_incr1_tail_helper1: forall b y, \nincr2 (y ++ [b]) = incr1 y ++ [b].\nProof.\n  intros.\n  generalize dependent b.\n  induction y using list_ind_length; intros.\n  simpl.\n  destruct b; auto.\n  destruct y.\n  destruct b; auto.\n  simpl.\n  remember (y ++ [b]).\n  destruct l.\n  destruct y; simpl in Heql; discriminate.\n  remember (length (incr2 (b1 :: l)) =? length (b1 :: l)).\n  remember (length (incr1 y) =? length y).\n  destruct b0; destruct b2; destruct b3.\n  - (*8*)\n  rewrite Heql.\n  rewrite H.\n  auto.\n  simpl. lia.\n  -(*7*)\n  rewrite Heql in Heqb2.\n  symmetry in Heqb2. symmetry in Heqb3.\n  apply PeanoNat.Nat.eqb_eq in Heqb2.\n  apply PeanoNat.Nat.eqb_neq in Heqb3.\n  apply incr2_in_next_inv in Heqb2.\n  contradiction.\n  -(*6*)\n  rewrite Heql in Heqb2.\n  symmetry in Heqb2. symmetry in Heqb3.\n  apply PeanoNat.Nat.eqb_eq in Heqb3.\n  apply PeanoNat.Nat.eqb_neq in Heqb2.\n  apply incr2_in_next with (b:=b) in Heqb3.\n  contradiction.\n  -(*5*)\n  rewrite Heql in Heqb2.\n  rewrite Heql.\n  rewrite H.\n  remember (incr1 y).\n  destruct b0.\n  simpl.\n  exfalso.\n  destruct y. simpl in Heqb0. discriminate.\n  simpl in Heqb0.\n  destruct b0; destruct (length (incr1 y) =? length y); discriminate.\n  simpl.\n  auto.\n  simpl. lia.\n  -(*4*)\n  rewrite Heql.\n  rewrite H.\n  auto.\n  simpl. lia.\n  - (*3*)\n  rewrite Heql in Heqb2.\n  symmetry in Heqb2. symmetry in Heqb3.\n  apply PeanoNat.Nat.eqb_neq in Heqb3.\n  apply PeanoNat.Nat.eqb_eq in Heqb2.\n  apply incr2_in_next_inv in Heqb2.\n  contradiction.\n  - (*2*)\n  rewrite Heql in Heqb2.\n  symmetry in Heqb2. symmetry in Heqb3.\n  apply PeanoNat.Nat.eqb_eq in Heqb3.\n  apply PeanoNat.Nat.eqb_neq in Heqb2.\n  apply incr2_in_next with (b:=b) in Heqb3.\n  contradiction.\n  -(*1*)\n  rewrite Heql in Heqb2.\n  rewrite Heql.\n  rewrite H.\n  remember (incr1 y).\n  destruct b0.\n  simpl. auto. auto.\n  simpl. lia.\nQed.  \n\nLemma iter_incr1_tail_helper2: forall b y n1, \nn1 <= length y ->\nincr2 (b :: firstn n1 y) ++ skipn n1 y = incr1 (firstn n1 (b :: y)) ++ skipn n1 (b :: y).\nProof.\n  intros.\n  remember (firstn n1 (b :: y)).\n  enough (exists x, b :: firstn n1 y = l ++ [x]).\n  destruct H0.\n  rewrite H0.\n  rewrite iter_incr1_tail_helper1.\n  rewrite app_ass.\n  enough ([x] ++ skipn n1 y =  skipn n1 (b :: y)).\n  rewrite H1. auto.\n  subst l.\n  generalize dependent y.\n  generalize dependent b.\n  generalize dependent x.\n  induction n1; intros.\n  simpl.\n  simpl in H0.\n  inversion H0. auto.\n  destruct y.\n  simpl in H. lia.\n  simpl in H0.\n  enough (b0 :: firstn n1 y = firstn n1 (b0 :: y) ++ [x]).\n  apply IHn1 in H1.\n  simpl.\n  simpl in H1. auto.\n  simpl in H. lia.\n  inversion H0. auto.\n  subst l.\n  generalize dependent y.\n  generalize dependent b.\n  induction n1; intros.\n  simpl.\n  exists b. auto.\n  destruct y.\n  simpl in H. lia.\n  simpl in H.\n  enough (n1 <=length y).\n  simpl.\n  apply IHn1 with (b:=b0) in H0.\n  destruct H0.\n  rewrite H0.\n  exists x.\n  auto.\n  lia.\nQed. \n  \n\nLemma iter_incr1_tail_helper3: forall n1 b y, n1 <= length y ->\nexists (h : binary) (t : list binary), skipn n1 (b :: y) = h :: t.\nProof.\n  intros.\n  generalize dependent b.\n  generalize dependent y.\n  induction n1; intros.\n  simpl.\n  exists b, y. auto.\n  destruct y.\n  simpl in H. lia.\n  simpl.\n  simpl in H.\n  enough (n1 <= length y).\n  apply IHn1 with (b:=b0) in H0.\n  destruct H0.\n  destruct H0.\n  rewrite H0.\n  exists x,x0. auto.\n  lia.\nQed.\n\n\nLemma iter_incr1_tail: forall y n,\nn <= length y ->\niter (pow 2 n) incr1 y = (incr1 (firstn (length y - n) y)) ++ \n                          (skipn (length y - n) y) /\\\niter (pow 2 n + pow 2 n) incr1 y = (incr2 (firstn (length y - n) y)) ++ \n                          (skipn (length y - n) y) .                       \nProof.\n    intros.\n    generalize dependent y.\n    induction n ; intros.\n    simpl.\n    replace (length y - 0) with (length y).\n    rewrite firstn_all_length.\n    rewrite skipn_all_length.\n    rewrite ?app_nil_r.\n    split.\n    auto.\n    rewrite incr2_incr1. auto.\n    lia.\n\n    destruct y.\n    simpl.\n    simpl in H.\n    lia.\n    simpl in H.\n    simpl.\n    replace ((2 ^ n + (2 ^ n + 0))) with (2 ^ n + 2 ^ n ); [| lia].\n    split.\n    - (*2*)\n    assert (iter (2 ^ n + 2 ^ n) incr1 (b::y) = incr2 (firstn (length (b::y) - n) (b::y)) ++ skipn (length (b::y) - n) (b::y)).\n    apply IHn.\n    simpl. lia.\n    rewrite H0.\n    remember (length (b :: y) - n).\n    remember (length y - n).\n    assert (S n1 = n0).\n    rewrite Heqn0. rewrite Heqn1. simpl.\n    destruct n. lia. lia.\n    rewrite <- H1.\n    Opaque incr2 incr1.\n    simpl. \n    Transparent incr2 incr1.\n    apply iter_incr1_tail_helper2.\n    lia.\n    - (*1*)\n    rewrite iter_plus.\n    assert (iter (2 ^ n + 2 ^ n) incr1 (b::y) = incr2 (firstn (length (b::y) - n) (b::y)) ++ skipn (length (b::y) - n) (b::y)).\n    apply IHn.\n    simpl. lia.\n    rewrite  H0.\n    simpl length.\n    replace (S (length y) - n) with (S (length y - n)); [|lia].\n    simpl firstn.\n    simpl skipn.\n    remember (incr2 (b :: firstn (length y - n) y) ++ skipn (length y - n) y).\n    assert (iter (2 ^ n + 2 ^ n) incr1 l = incr2 (firstn (length l - n) l) ++ skipn (length l - n) l).\n    apply IHn.\n    all: cycle 1.\n    rewrite H1.\n    rewrite iter_incr1_tail_helper2 in Heql; [| lia].\n    remember (length l - n).\n    remember (length y - n).\n    rewrite Heql.\n    simpl.\n    enough (length l > length y) as H10.\n    enough (length (skipn n1 (b :: y)) = S n).\n    enough (length (incr1 (firstn n1 (b :: y))) = length l - S n).\n    enough (exists h t, skipn n1 (b :: y) = h::t).\n    destruct H4.\n    destruct H4.\n    enough (skipn n0 (incr1 (firstn n1 (b :: y)) ++ skipn n1 (b :: y)) = x0).\n    rewrite H5.\n    enough (firstn n0 (incr1 (firstn n1 (b :: y)) ++ skipn n1 (b :: y)) = incr1 (firstn n1 (b :: y)) ++ [x] ).\n    rewrite H6.\n    rewrite H4.\n    rewrite iter_incr1_tail_helper1.\n    rewrite incr2_incr1.\n    rewrite app_ass.\n    auto.\n    remember (incr1 (firstn n1 (b :: y))).\n    enough (length b0  = n0 - 1).\n    rewrite firstn_app.\n    rewrite firstn_all2.\n    rewrite H6.\n    rewrite H4.\n    replace (n0 - (n0 - 1)) with 1.\n    simpl. auto.\n    enough (n0 >= 1).\n    lia.\n    subst n0.\n    lia.\n    lia.\n    lia.\n    rewrite H4.\n    rewrite skipn_app.\n    rewrite skipn_all2.\n    rewrite H3.\n    rewrite Heqn0.\n    replace (length l - n - (length l - S n)) with 1.\n    simpl. auto.\n    lia.\n    lia.\n    apply iter_incr1_tail_helper3.\n    lia.\n    assert (length l = length (incr1 (firstn n1 (b :: y))) + S n).\n    rewrite Heql.\n    rewrite <- H2.\n    rewrite app_length. auto.\n    lia.\n    rewrite Heqn1.\n    rewrite skipn_length.\n    simpl length.\n    lia.\n    rewrite Heql.\n    rewrite app_length.\n    enough (length (incr1 (firstn n1 (b :: y))) >= length (firstn n1 (b :: y))).\n    enough  (length ((firstn n1 (b :: y))) + length (skipn n1 (b :: y)) > length y).\n    lia.\n    rewrite <- app_length.\n    rewrite firstn_skipn. simpl. lia.\n    apply incr1_length.\n    rewrite Heql.\n    rewrite app_length.\n    enough (length (incr2 (b :: firstn (length y - n) y)) >= length ( (b :: firstn (length y - n) y))) .\n    enough (length (incr2 (b :: firstn (length y - n) y)) +\n    length (skipn (length y - n) y) >= length y).\n    lia.\n    enough (length ( (b :: firstn (length y - n) y)) +\n    length (skipn (length y - n) y) = S (length y)).\n    lia.\n    simpl length . simpl.\n    rewrite <- app_length.\n    rewrite firstn_skipn.\n    auto.\n    apply incr2_length.   \nQed.\n\n\nLemma iter_decr1_incr1: forall b n, \niter n decr1 (iter n incr1 b) = b.\nProof.\n  intros.\n  generalize dependent b.\n  induction n; intros.\n  simpl. auto.\n  rewrite iterS. simpl.\n  rewrite IHn.\n  rewrite decr1_incr1.\n  auto.\nQed.\n\nLemma iter_incr1_tail1: forall y,\niter (pow 2 (length y)) incr1 y = E1::y.\nProof.\n  intros.\n  remember (iter_incr1_tail y (length y)).\n  assert (iter (2 ^ length y) incr1 y = incr1 (firstn (length y - length y) y) ++ skipn (length y - length y) y).\n  apply a. lia.\n  rewrite H.\n  replace (length y - length y)  with 0.\n  simpl. auto.\n  lia.\nQed.\n\nLemma iter_incr1_tail2: forall y,\niter (pow 2 (length y) + pow 2 (length y)) incr1 y = E2::y.\nProof.\n  intros.\n  remember (iter_incr1_tail y (length y)).\n  assert (iter (2 ^ length y + 2 ^ length y) incr1 y =\n  incr2 (firstn (length y - length y) y) ++ skipn (length y - length y) y).\n  apply a. lia.\n  rewrite H.\n  replace (length y - length y)  with 0.\n  simpl. auto.\n  lia.\nQed.\n\nLemma remove_head1: forall b y, exists n,\n  iter n decr1 (b::y) = y. \nProof.\n  intros.\n  destruct b.\n  exists (2^(length y)).\n  rewrite <- iter_incr1_tail1.\n  rewrite iter_decr1_incr1. auto.\n  exists (2^(length y) + 2^(length y)).\n  rewrite <- iter_incr1_tail2.\n  rewrite iter_decr1_incr1. auto.\nQed.\n\nLemma iter_relation_binary_lt_lt: forall n x y,\niter_relation binary_lt n x y -> binary_lt x y.\nProof.\n  intros.\n  generalize dependent x.\n  generalize dependent y.\n  induction n; intros.\n  inversion H.\n  auto.\n  apply iter_relation_S2 in H.\n  inversion_clear H.\n  inversion H0.\n  apply IHn in H.\n  apply binary_lt_trans with (b:=x0).\n  auto. auto. \nQed.\n\n\nLemma bilist_lt_reducible_prop: bilist_reducible_prop binary_lt.\nProof.\n  unfold bilist_reducible_prop.\n  intros.\n  induction y using list_ind_length.\n  exists 0. intros.\n  inversion H.\n  inversion H0.\n  destruct y.\n  exists 0. intros.\n  inversion H0.\n  inversion H1.\n  destruct y.\n  all: cycle 1.\n  remember (b0::y) as y'.\n  enough (exists n, forall x, iter_relation binary_lt n x (b :: y') -> length x <= length y' /\\ binary_lt x y').\n  destruct H0.\n  assert (exists n : nat, forall x : bilist, iter_relation binary_lt n x y' -> False).\n  apply H. simpl. auto.\n  inversion_clear H1.\n  exists (x0+x).\n  intros.\n  (*   y < .. x .. < (b::y)  *)\n  (*   x1 < .. x + x0 .. < (b::y)  *)\n\n  apply iter_relation_trans with (y:=y') in H1.\n  apply H2 with (x:=x1).\n  auto.\n  intros. apply H0. auto.\n\n  remember (H y').\n  clear Heqe.\n  assert (exists n : nat, forall x : bilist, iter_relation binary_lt n x y' -> False).\n  apply e. simpl. lia.\n  clear e. destruct H0.\n  \n  remember (remove_head1 b y'). clear Heqe.\n  inversion_clear e.\n\n  exists (x + x0).\n  intros.\n  remember H2. clear Heqi.\n  apply iter_relation_trans with (y:=y') in i.\n  enough (binary_lt x1 y').\n  split.\n  apply binary_lt_length in H3. auto.\n  auto.\n  apply iter_relation_binary_lt_lt with (n:=x).\n  auto.\n\n  intros.\n  apply binary_lt_decr1_iter in H3.\n  inversion_clear H3.\n  rewrite iterS in H4.\n  rewrite H1 in H4.\n  rewrite H4.\n  apply decr1_lt.\n  rewrite Heqy'. simpl. lia.\n  rewrite iterS in H4.\n  rewrite H1 in H4.\n  apply binary_lt_trans with (b:=decr1 y').\n  auto.\n  apply decr1_lt.\n  rewrite Heqy'. simpl. lia.\n  destruct b.\n  exists 1.\n  intros.\n  inversion H0.\n  inversion H3.\n  inversion H2.\n  destruct y'. inversion H6.\n  simpl in H11. lia. inversion H11.\n  exists 2.\n  intros.\n  inversion_clear  H0.\n  inversion_clear H2.\n  inversion_clear H3.\n  inversion H1.\n  destruct y'. inversion H0.\n  simpl in H5. lia. \n  destruct x0. subst y'.\n  inversion H0.\n  destruct y'0.\n  inversion H2.\n  simpl in H7. lia.\n  inversion H7.\n  simpl in H5. lia.\n  inversion H5.\nQed.\n\n\n  \n\nLemma bilist_lt_ind: forall (P: bilist -> Prop), \nP [] -> (forall b, (forall b', binary_lt b' b -> P b') -> P b) -> forall b, P b .\nProof.\n  intros.\n  induction b using list_ind_length.\n  auto.\n  apply H0.\n  intros.\n  remember bilist_lt_reducible_prop as e. clear Heqe.\n  unfold bilist_reducible_prop in e.\n  remember (e b). clear Heqe0.\n  inversion_clear e0.\n  generalize dependent b'.\n  generalize dependent b.\n  induction x; intros.\n  exfalso.\n  apply H3 with (x:=b').\n  constructor. auto.\n  apply H0. intros.\n  apply IHx with (b:=b'). intros.\n  -\n  apply H1.\n  enough (length b' <= length b).\n  lia.\n  apply bilist_lt_length. auto.\n  -\n  intros.\n  apply H3 with (x0:=x0).\n  apply iter_relationS with (y':=b'). auto. auto.\n  -\n  auto.\nQed.\n\n\nLemma bilist_incr_ind: forall (P: bilist -> Prop), \nP [] -> (forall b, P b -> P (incr1 b)) -> forall b, P b .\nProof.\n  intros.\n  induction b using bilist_lt_ind.\n  auto.\n  destruct b.\n  auto.\n  enough (exists b', incr1 b' = b :: b0).\n  inversion_clear H2. rewrite <- H3.\n  apply H0. apply H1.\n  rewrite <- H3.\n  apply lt_incr1.\n  exists (decr1 (b :: b0)).\n  apply incr1_decr1.\n  simpl. lia.\nQed.\n\nFixpoint del_h (b b' : bilist) : bilist :=\n  match b' with\n  | [] => []\n  | h :: t => if (length b =? length t + 1) then h :: t else del_h b t \nend.\nCompute del_h [] [E1].\nCompute del_h [E1; E1] [E1].\nCompute del_h [E1; E2] [E1; E1; E1].\nFixpoint del_t (b b' : bilist) : bilist :=\n  match b' with\n  | [] => []\n  | h :: t => if length (del_h b b') =? length t then [h] else h :: del_t b t\nend.\n\nCompute firstn 1 [].\nCompute firstn 2 [E1;E2].\nCompute skipn 1 [].\nCompute skipn 1 [E1; E2].\nCompute skipn 2 [E1; E2].\nDefinition split (n: nat) (t : bilist) : bilist * bilist :=\n  (firstn n t, skipn n t).             \n\nCompute split 1 [E1].\n\nFixpoint plus (b b' : bilist) : bilist :=\n  match b with\n  | [] => b' \n  | h :: t => let l := plus t b' in\n              let (p, r) := split (length l - (length t)) l in\n              match h with\n              | E1 => (incr1 p) ++ r\n              | E2 => (incr2 p) ++ r\n              end\n  end.     \n\n\n  Example test_plus_1 :  plus [E1] [E1] = [E2].\n  Proof.\n    auto. Qed.\n    \n    Example test_plus_2 :  plus [E1] [E2] = [E1;E1].\n    Proof.\n      auto. Qed.\n    \n  Example test_plus_3 :  plus [E2] [E2] = [E1;E2].\n  Proof.\n    auto. Qed.\n  \n  Example test_plus_4 :  plus [E1] [E1;E1] = [E1;E2].\n  Proof.\n    auto. Qed.\n  \n  Example test_plus_5 :  plus [E1] [E2;E2] = [E1;E1;E1].\n  Proof.\n    auto. Qed.\n  \n  Example test_plus_6 :  plus [E2;E2] [E2;E2] = [E2;E1;E2].\n  Proof.\n      auto. Qed.\n  \n  \n  Example test_plus_7:  plus [E1;E1] [E1] = [E1;E2].\n  Proof.\n    auto. Qed.\n  \n  Example test_plus_8 :  plus [E2;E2] [E1] = [E1;E1;E1].\n  Proof.\n    auto. Qed.\n  \n  Example test_plus_9 :  plus [E1;E2] [E2;E2] = [E1;E2;E2].\n  Proof.\n      auto. Qed.\n  \n  Example test_plus_10 :  plus [E1; E1] [E1; E1; E1] = [E1;E2;E2].\n  Proof.\n      auto. \n  Qed.\n    \n  Example test_plus_11 :  plus [E1; E2] [E1; E2; E1] = [E2;E2;E1].\n  Proof.\n      auto. \n  Qed.\n    \n  Example test_plus_12 :  plus [E2;E2] [E1;E2] = [E1;E2;E2].\n  Proof.\n      auto. Qed.\n  \n  Example test_plus_13 :  plus [E1; E1;E1] [ E1; E1] = [E1;E2;E2].\n  Proof.\n      auto. \n  Qed.\n    \n  Example test_plus_14 :  plus [E1; E2;E1] [E1; E2] = [E2;E2;E1].\n  Proof.\n      auto. \n  Qed.\n\nLemma skipn_n: forall b : bilist,\n  skipn (length b - 0) b = [] .\nProof.\n  induction b.\n  auto.\n  simpl.\n  Search (?n - 0 = ?n).\n  Check length b.\n  rewrite PeanoNat.Nat.sub_0_r  with (length b) in IHb.\n  auto.\nQed.\n\nLemma firstn_n: forall b : bilist,\n  firstn (length b) b = b.\nProof.\n  induction b.\n  auto.\n  simpl.\n  rewrite IHb. auto.\nQed.\n\nTheorem incr_plus_r: forall b : bilist,\n  incr1 b = plus [E1] b.\nProof.\n  induction b.\n  auto.\n  simpl.\n  simpl in IHb.\n  rewrite skipn_n in IHb.\n  rewrite PeanoNat.Nat.sub_0_r  with (length b) in IHb.\n  simpl in IHb.\n  rewrite firstn_n. rewrite <- PeanoNat.Nat.sub_0_r with (length b).\n  rewrite skipn_n.\n  Search (?l ++ [] = ?l).\n  rewrite app_nil_r. auto.\nQed.\n\n\nLemma skipn_1: forall X (l: list X), 0 < length l -> tl l = skipn 1 l.\nProof.\n  intros.\n  induction l.\n  simpl in H. lia.\n  simpl. auto.\nQed.\n\nLemma forall_head: forall X (x:X) l, 0 < length l -> Forall (eq x) l -> [x] = firstn 1 l.\nProof.\n  intros.\n  induction l.\n  simpl in H. lia.\n  inversion_clear H0.\n  simpl. \n  congruence.\nQed.\n\nLemma head_tail: forall X (l:list X), 0 < length l -> (l = (firstn 1 l) ++ (tl l)).\nProof.\n  intros.\n  induction l.\n  simpl in H. lia.\n  simpl. auto.\nQed.  \n\nTheorem incr_plus_l: forall b : bilist, incr1 b = plus b [E1].\nProof.\n  induction b using list_ind_length.\n  auto.\n  destruct b. auto.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  destruct b1; destruct b.\n  -\n  rewrite <- H.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  rewrite Heqb1.\n  rewrite PeanoNat.Nat.sub_diag.\n  rewrite firstn_O.\n  rewrite skipn_O.\n  simpl. auto.\n  auto.\n  -\n  rewrite <- H.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_eq in Heqb1.\n  rewrite Heqb1.\n  rewrite PeanoNat.Nat.sub_diag.\n  rewrite firstn_O.\n  rewrite skipn_O.\n  simpl. auto.\n  auto.\n  - rewrite <- H.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (S (length b0) = length (incr1 b0)).\n  rewrite <- H0.\n  replace (S (length b0) - length b0) with 1.\n  replace ((firstn 1 (incr1 b0))) with [E1].\n  replace (skipn 1 (incr1 b0)) with (tl ((incr1 b0))).\n  simpl. auto.\n  rewrite skipn_1. auto.\n  destruct b0.\n  simpl. auto.\n  simpl. destruct b; destruct (length (incr1 b0) =? length b0); simpl; try lia; auto.\n  apply forall_head.\n  destruct b0.\n  simpl. auto.\n  simpl. destruct b; destruct (length (incr1 b0) =? length b0); simpl; try lia; auto.\n  apply incr1_cons1.\n  lia. lia.\n  apply incr1_length_plus.\n  enough (length b0 <= length (incr1 b0)). lia.\n  apply incr1_length.\n  auto.\n  - rewrite <- H.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (S (length b0) = length (incr1 b0)).\n  rewrite <- H0.\n  replace (S (length b0) - length b0) with 1.\n  replace ((firstn 1 (incr1 b0))) with [E1].\n  replace (skipn 1 (incr1 b0)) with (tl ((incr1 b0))).\n  simpl.\n  rewrite head_tail with (l:=incr1 b0) at 1.\n  replace (firstn 1 (incr1 b0)) with [E1]. auto.\n  apply forall_head.\n  lia.  apply incr1_cons1.\n  lia. lia.\n  apply skipn_1. lia.\n  apply forall_head.\n  lia. apply incr1_cons1. lia. lia.\n  apply incr1_length_plus.\n  enough (length b0 <= length (incr1 b0)). lia.\n  apply incr1_length.\n  auto.\n  \nQed.\n\n\nLemma plus_nil: forall b, plus b [] = b.\nProof.\n  induction b.\n  auto.\n  simpl.\n  destruct a.\n  rewrite ?IHb.\n  rewrite ?PeanoNat.Nat.sub_diag. \n  simpl. auto.\n  rewrite ?IHb.\n  rewrite ?PeanoNat.Nat.sub_diag.\n  simpl.\n  auto.\nQed.\n\nLemma plus_len: forall b b', \n  length b <= length (plus b b').\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using list_ind_length; intros.\n  simpl. lia.\n  destruct b.\n  simpl. lia.\n  simpl.\n  destruct b.\n  -\n  rewrite app_length.\n  rewrite skipn_length.\n  replace (length (plus b0 b') - (length (plus b0 b') - length b0)) with (length b0).\n  remember (firstn (length (plus b0 b') - length b0) (plus b0 b')).\n  destruct l.\n  simpl.  lia.\n  simpl.\n  destruct b; destruct (length (incr1 l) =? length l); simpl; lia.\n  enough (length b0 <= length (plus b0 b')).\n  lia.\n  apply H.\n  simpl. lia.\n  -\n  rewrite app_length.\n  rewrite skipn_length.\n  replace (length (plus b0 b') - (length (plus b0 b') - length b0)) with (length b0).\n  remember (firstn (length (plus b0 b') - length b0) (plus b0 b')).\n  destruct l.\n  simpl.  lia.\n  simpl.\n  destruct b; destruct (length (incr2 l) =? length l); simpl; destruct l; simpl length; lia.\n  enough (length b0 <= length (plus b0 b')).\n  lia.\n  apply H.\n  simpl. lia.\nQed.\n\nLemma incr1_lt_hom: forall b b',\nbinary_lt b b' ->\nbinary_lt (incr1 b) (incr1 b').\nProof.\n  intros.\n  generalize dependent b.\n  induction b' using bilist_lt_ind; intros.\n  inversion H.\n  enough (iter_relation binary_lt 0 b b').\n  apply binary_lt_decr1_iter in H1.\n  simpl in H1. inversion H1.\n  -\n  rewrite H2.\n  rewrite incr1_decr1.\n  apply lt_incr1.\n  destruct b'. inversion H0.\n  simpl. lia.\n  -\n  assert (binary_lt (incr1 b) (incr1 (decr1 b'))).\n  apply H; auto.\n\n  apply decr1_lt.\n  destruct b'.\n  inversion H0.\n  simpl. lia.\n  replace (incr1 (decr1 b')) with b' in H3.\n  apply binary_lt_trans with (b:=b'); auto.\n  apply lt_incr1.\n  rewrite incr1_decr1.\n  auto.\n  destruct b'.\n  inversion H0.\n  simpl. lia.\n  -\n  constructor. auto.  \nQed.\n\n\nLemma incr1_length_hom: forall b b',\nbinary_lt b b' ->\nlength (incr1 b) <= length (incr1 b').\nProof.\n  intros.\n  apply binary_lt_length.\n  apply incr1_lt_hom.\n  auto.\nQed.\n\n\nLemma binary_lt_incr1_iter_hom: forall n b b',\nbinary_lt b b' ->  \nbinary_lt (iter n incr1 b) (iter n incr1 b').\nProof.\n  intros.\n  generalize dependent b.\n  generalize dependent b'.\n  induction n; intros.\n  simpl. auto.\n  simpl.\n  apply IHn.\n  apply incr1_lt_hom.\n  auto.\nQed.\n\n\n\nLemma lt_plus: forall b b',\n0 < length b' -> \nbinary_lt b (plus b b').\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using list_ind_length; intros.\n  simpl. \n  destruct b'. inversion H.\n\n  constructor. simpl. lia.\n  destruct b.\n  simpl.\n  destruct b'. inversion H0.\n  constructor. simpl. lia.\n  simpl.\n  destruct b.\n  -\n  remember (length (plus b0 b') - length b0) as n.\n  remember (plus b0 b') as x.\n  remember (iter_incr1_tail x (length b0)).\n  assert (iter (2 ^ length b0) incr1 x = incr1 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply binary_lt_length.\n  apply H.\n  simpl. lia.\n  destruct b'. inversion H0.\n  simpl. lia.\n  rewrite <- Heqn in H1.\n  rewrite <- H1.\n  clear a Heqa.\n  assert (E1 :: b0  = iter (2 ^ length b0) incr1 b0).\n  rewrite iter_incr1_tail1.\n  auto.\n  rewrite H2.\n  apply binary_lt_incr1_iter_hom.\n  rewrite Heqx.\n  apply H.\n  simpl. lia.\n  destruct b'. inversion H0.\n  simpl. lia.\n  -\n  remember (length (plus b0 b') - length b0) as n.\n  remember (plus b0 b') as x.\n  remember (iter_incr1_tail x (length b0)).\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 x =\n  incr2 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply binary_lt_length.\n  apply H.\n  simpl. lia.\n  destruct b'. inversion H0.\n  simpl. lia.\n  rewrite <- Heqn in H1.\n  rewrite <- H1.\n  clear a Heqa.\n  assert (E2 :: b0  = iter (2 ^ length b0 + 2 ^ length b0) incr1 b0).\n  rewrite iter_incr1_tail2.\n  auto.\n  rewrite H2.\n  apply binary_lt_incr1_iter_hom.\n  rewrite Heqx.\n  apply H.\n  simpl. lia.\n  destruct b'. inversion H0.\n  simpl. lia.\nQed.\n\n\n\nLemma plus_incr1_left: forall b b', plus (incr1 b) b' = incr1 (plus b  b') .\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using bilist_lt_ind.\n  intros.\n  simpl.\n  replace (length b' - 0) with (length b').\n  rewrite firstn_all.\n  rewrite skipn_all.\n  rewrite ?app_nil_r.\n  auto.\n  lia.\n  intros.\n\n  destruct b.\n  simpl.\n  replace (length b' - 0) with (length b').\n  rewrite firstn_all.\n  rewrite skipn_all.\n  rewrite ?app_nil_r.\n  auto.\n  lia.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  remember (length (plus b0 b') - length b0).\n  remember (plus b0 b') as x.\n  destruct b; destruct b1.\n  -\n  simpl.\n  rewrite H.\n  rewrite <- Heqx.\n  remember ((length (incr1 x) - length (incr1 b0))) as m.\n  remember (iter_incr1_tail x (length b0)).\n  clear Heqa.\n  rewrite <- Heqn in a.\n  assert (iter (2 ^ length b0) incr1 x = incr1 (firstn n x) ++ skipn n x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- H0.\n  remember (iter_incr1_tail (incr1 x) (length (incr1 b0))).\n  clear Heqa0.\n  rewrite <- Heqm in a0.\n  assert (iter (2 ^ length (incr1 b0)) incr1 (incr1 x) =\n  incr1 (firstn m (incr1 x)) ++ skipn m (incr1 x)).\n  apply a0.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil. lia.\n  apply incr1_length_hom.\n  apply lt_plus.\n  simpl. lia.\n  clear a H0 a0 H1.\n  remember (iter_incr1_tail (incr1 x) (length (incr1 b0))).\n  assert (iter (2 ^ length (incr1 b0)) incr1 (incr1 x) =\n  incr1 (firstn (length (incr1 x) - length (incr1 b0)) (incr1 x)) ++\n  skipn (length (incr1 x) - length (incr1 b0)) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil. lia.\n  apply incr1_length_hom.\n  apply lt_plus. simpl. lia.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  replace (length (incr1 b0)) with (length b0).\n  rewrite <- iterS.\n  simpl. auto.\n  apply PeanoNat.Nat.eqb_eq.\n  rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_sym.\n  constructor. lia.\n- simpl.\n  remember (length (plus (tl (incr1 b0)) b') - length (tl (incr1 b0))) as m.\n  remember ((plus (tl (incr1 b0)) b')).\n  destruct b0.\n  +\n  simpl in Heqb.\n  simpl in Heqm.\n  simpl in Heqx.\n  simpl in Heqn.\n  rewrite Heqx.\n  rewrite Heqb.\n  replace m with n.\n  subst.\n  replace (length b' - 0) with (length b') by lia.\n  rewrite firstn_all2.\n  rewrite skipn_all2.\n  rewrite ?app_nil_r.\n  rewrite incr2_incr1.\n  auto.\n  lia. lia.\n  subst.\n  auto.\n  +\n  rewrite <- incr1_tl_comm_E2 in Heqb.\n  rewrite H in Heqb.\n  rewrite <- incr1_tl_comm_E2 in Heqm.\n  simpl in Heqm.\n  simpl in Heqb.\n  remember  (iter_incr1_tail b (length (incr1 b1))).\n  assert (iter (2 ^ length (incr1 b1) + 2 ^ length (incr1 b1)) incr1 b =\n  incr2 (firstn (length b - length (incr1 b1)) b) ++ skipn (length b - length (incr1 b1)) b).\n  apply a.\n  rewrite Heqb.\n  destruct b'.\n  rewrite plus_nil. lia.\n  apply incr1_length_hom.\n  apply lt_plus. simpl. lia.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  remember  (iter_incr1_tail x (length (b0 :: b1))).\n  assert (iter (2 ^ length (b0 :: b1)) incr1 x =\n  incr1 (firstn (length x - length (b0 :: b1)) x) ++ skipn (length x - length (b0 :: b1)) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  simpl.\n  simpl in Heqx.\n  replace b0 with E2 in Heqx.\n  clear a Heqa H0.\n  remember (plus b1 b') as y.\n  remember  (iter_incr1_tail y (length b1)).\n  assert (iter (2 ^ length b1 + 2 ^ length b1) incr1 y =\n  incr2 (firstn (length y - length b1) y) ++ skipn (length y - length b1) y).\n  apply a.\n  rewrite Heqy.\n  apply plus_len.\n  rewrite <- H0 in Heqx.\n  clear a Heqa H0.\n  rewrite Heqx.\n  rewrite Heqb.\n  replace (2 ^ length b1 + (2 ^ length b1 + 0)) with (2 ^ length b1 + 2 ^ length b1 ).\n  replace (length (incr1 b1)) with (S (length b1)).\n  simpl.\n  replace  (2 ^ length b1 + 0) with (2 ^ length b1 ).\n  rewrite iter_plus.\n  rewrite <- iterS.\n  simpl.\n  rewrite <- iterS.\n  simpl. auto.\n  lia.\n  apply incr1_length_plus.\n  apply incr1_cons2_inv.\n  enough (length (b0 :: b1) < length (incr1 (b0 :: b1))).\n  apply incr1_cons2 in H0.\n  inversion H0. auto.\n  enough (length (b0 :: b1) <= length (incr1 (b0 :: b1))).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia.\n  apply incr1_length.\n  lia.\n  enough (Forall (eq E2) (b0 :: b1)).\n  inversion H1. auto.\n  apply incr1_cons2.\n  enough (length (b0 :: b1) <= length (incr1 (b0 :: b1))).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia. apply incr1_length.\n  simpl. lia.\n  apply incr1_cons2.\n  enough (length (b0 :: b1) <= length (incr1 (b0 :: b1))).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia. apply incr1_length.\n  simpl.\n  constructor 1. simpl. lia.\n  simpl. lia.\n  apply incr1_cons2.\n  enough (length (b0 :: b1) <= length (incr1 (b0 :: b1))).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia. apply incr1_length.\n  -\n  simpl.\n  remember (length (plus (incr1 b0) b') - length (incr1 b0)) as m.\n  rewrite H.\n  rewrite <- Heqx.\n  remember  (iter_incr1_tail x (length b0)).\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 x =\n  incr2 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  rewrite H in Heqm.\n  rewrite <- Heqx in Heqm.\n  remember  (iter_incr1_tail (incr1 x) (length (incr1 b0))).\n  assert (iter (2 ^ length (incr1 b0) + 2 ^ length (incr1 b0)) incr1 (incr1 x) =\n  incr2 (firstn (length (incr1 x) - length (incr1 b0)) (incr1 x)) ++\n  skipn (length (incr1 x) - length (incr1 b0)) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil.\n  lia.\n  apply incr1_length_hom.\n  apply lt_plus. simpl. lia.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  rewrite <- iterS.\n  simpl.\n  replace (length (incr1 b0)) with (length b0).\n  auto.\n  apply PeanoNat.Nat.eqb_eq.\n  rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_sym.\n  constructor. lia.\n  constructor. lia.\n  -\n  simpl.\n  rewrite H.\n  rewrite <- Heqx.\n  remember (length (incr1 x) - length (incr1 b0)) as m.\n  remember  (iter_incr1_tail x (length b0)).\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 x =\n  incr2 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  remember  (iter_incr1_tail (incr1 x) (length (incr1 b0))).\n  assert (iter (2 ^ length (incr1 b0)) incr1 (incr1 x) =\n  incr1 (firstn (length (incr1 x) - length (incr1 b0)) (incr1 x)) ++\n  skipn (length (incr1 x) - length (incr1 b0)) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil.\n  lia.\n  apply incr1_length_hom.\n  apply lt_plus. simpl. lia.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  replace (length (incr1 b0)) with (S (length b0)).\n  simpl.\n  replace (2 ^ length b0 + (2 ^ length b0 + 0)) with (2 ^ length b0 + 2 ^ length b0 ).\n  rewrite <- iterS.\n  simpl. auto.\n  lia.\n  apply incr1_length_plus.\n  enough (length b0 <= length (incr1 b0)).\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  lia.\n  apply incr1_length.\n  constructor. lia.\nQed.\n\n\nLemma plus_incr1_right: forall b b', plus b (incr1 b') = incr1 (plus b b') .\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using bilist_lt_ind.\n  intros.\n  simpl. auto.\n\n  intros.\n  destruct b.\n  simpl. auto.\n  simpl.\n  rewrite H.\n  remember  (plus b0 b') as x.\n  destruct b.\n  -\n  remember ((length (incr1 x) - length b0)) as m.\n  remember (length x - length b0) as n.\n  remember (iter_incr1_tail x (length b0)).\n  clear Heqa.\n  assert (iter (2 ^ length b0) incr1 x =\n  incr1 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  clear a H0.\n  remember (iter_incr1_tail (incr1 x) (length  b0)).\n  assert (iter (2 ^ length b0) incr1 (incr1 x) =\n  incr1 (firstn (length (incr1 x) - length b0) (incr1 x)) ++\n  skipn (length (incr1 x) - length b0) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil. \n  apply incr1_length.\n  apply binary_lt_length.\n  apply binary_lt_trans with (b:=(plus b0 (b :: b'))).\n  apply lt_plus.\n  simpl. lia.\n  apply lt_incr1.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  rewrite <- iterS. simpl. auto.\n- \n  remember ((length (incr1 x) - length b0)) as m.\n  remember (length x - length b0) as n.\n  remember (iter_incr1_tail x (length b0)).\n  clear Heqa.\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 x =\n  incr2 (firstn (length x - length b0) x) ++ skipn (length x - length b0) x).\n  apply a.\n  rewrite Heqx.\n  apply plus_len.\n  rewrite <- Heqn in H0.\n  rewrite <- H0.\n  clear a H0.\n  remember (iter_incr1_tail (incr1 x) (length  b0)).\n  assert (iter (2 ^ length b0 + 2 ^ length b0) incr1 (incr1 x) =\n  incr2 (firstn (length (incr1 x) - length b0) (incr1 x)) ++\n  skipn (length (incr1 x) - length b0) (incr1 x)).\n  apply a.\n  rewrite Heqx.\n  destruct b'.\n  rewrite plus_nil. \n  apply incr1_length.\n  apply binary_lt_length.\n  apply binary_lt_trans with (b:=(plus b0 (b :: b'))).\n  apply lt_plus.\n  simpl. lia.\n  apply lt_incr1.\n  rewrite <- Heqm in H0.\n  rewrite <- H0.\n  clear a Heqa H0.\n  rewrite <- iterS. simpl. auto.\n-\n  constructor.\n  lia.\nQed.    \n\nTheorem plus_comm: forall b b' : bilist,\n  plus b b' = plus b' b.\nProof.\n  intros.\n  generalize dependent b'.\n  induction b using bilist_incr_ind.\n  intros.\n  rewrite plus_nil. simpl. auto.\n  intros.\n  enough (forall b b', plus (incr1 b) b' = incr1 (plus b b')).\n  enough (forall b b', plus b (incr1 b') = incr1 (plus b b')).\n  rewrite H.\n  rewrite IHb.\n  rewrite H0.\n  auto.\n  intros. apply plus_incr1_right.\n  intros. apply plus_incr1_left.\nQed.  \n    \n\nFixpoint minus (b b' : bilist) :  bilist := \n  match b' with\n  | [] => b\n  | E1 :: t => minus (iter (pow 2 (length t)) decr1 b) t\n  | E2 :: t => minus (iter (pow 2 (1 + length t)) decr1 b) t\n  end.\n\nExample check_min: minus [E2] [E1] = [E1].\nProof.\n  reflexivity.\nQed.\n\nExample check_min1: minus [E2;E1] [E1] = [E1;E2].\nProof.\n  reflexivity.\nQed.\n\nExample check_min2: minus [E1;E2] [E1] = [E1;E1].\nProof.\n  reflexivity.\nQed.\n\nExample check_min3: minus [E2] [E1;E1] = [].\nProof.\n  reflexivity.\nQed.\n\nLemma decr_iter_comm: forall (a : bilist) (n : nat),\n  decr1 (iter n decr1 a) = iter n decr1 (decr1 a).\nProof.\n  intros.\n  generalize dependent a.\n  induction n.\n  auto.\n  intros.\n  simpl.\n  rewrite IHn.\n  auto.\nQed.\n\nLemma minus_decr: forall a b,\n  decr1 (minus a b) = minus (decr1 a) b.\nProof.\n  intros.\n  generalize dependent a.\n  induction b using list_ind_length.\n \n  auto.\n  destruct b.\n  auto.\n  destruct b.\n  simpl.\n  intros. \n  rewrite H.\n  rewrite decr_iter_comm.\n  auto. \n  auto.\n  intros.\n  simpl.\n  rewrite H.\n  rewrite decr_iter_comm.\n  auto.\n  auto.\nQed.\n\nLemma zero_minus: forall b,\n  minus [] b = [].\nProof.\n  induction b.\n  auto.\n  simpl.\n  destruct a.\n  rewrite iter_decr1_nil.\n  assumption.\n  rewrite iter_decr1_nil.\n  assumption.\nQed.\n\nLemma minus_incr_decr_help: forall a b0,\nfalse = (length (incr1 b0) =? length b0) -> \nminus (iter (2 ^ length b0 + 2 ^ length b0) decr1 a) (tl (incr1 b0)) =\nminus (iter (2 ^ length b0) decr1 a) (incr1 b0).\nProof.\n  intros.\n  generalize dependent a.\n  induction b0 using list_ind_length.\n  simpl. auto.\n  destruct b0.\n  auto.\n  destruct b.\n  simpl.\n  remember (E1_head_incr).\n  rewrite e in H.\n  inversion H.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  destruct b.\n  simpl in H.\n  rewrite <- Heqb in H.\n  simpl in H.\n  rewrite <- H in Heqb.\n  inversion Heqb.\n  simpl.\n  rewrite Nat.add_0_r.\n   symmetry in Heqb.\n   apply length_eq_incr_S in Heqb.\n   rewrite Heqb.\n   simpl.\n   intros.\n   rewrite <- iter_plus.\n   rewrite Nat.add_0_r.\n   auto.\nQed.\n\nLemma minus_incr_decr: forall a b,\n  minus a (incr1 b) = decr1 (minus a b).\nProof.\n  intros.\n  generalize dependent a.\n  induction b using list_ind_length.\n  auto.\n  destruct b.\n  auto.\n  destruct b.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  intros.\n  destruct b.\n  simpl.\n  rewrite H.\n  symmetry in Heqb.\n  Search (_ =? _ = true).\n  apply Nat.eqb_eq in Heqb.\n  rewrite Heqb.\n  auto.\n  auto.\n  simpl.\n  rewrite <- H.\n  Search (length (tl (incr1 _)) = length _).\n  rewrite length_incr_tl.\n\n  Search (_ + 0 = _).\n  rewrite Nat.add_0_r.\n  apply minus_incr_decr_help.\n  assumption.\n  symmetry in Heqb.\n  apply length_eq_incr_S in Heqb.\n  lia.\n  auto.\n\n\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  intros.\n  destruct b.\n  simpl.\n  symmetry in Heqb.\n  apply Nat.eqb_eq in Heqb.\n  rewrite Heqb.\n  rewrite H.\n  auto.\n  auto.\n  simpl.\n  rewrite H.\n  symmetry in Heqb.\n  apply length_eq_incr_S in Heqb.\n  rewrite Heqb.\n  simpl.\n  auto.\n  auto.\nQed.\n  \n\nLemma minus_plus: forall a b : bilist,\n  minus (plus a b) b = a.\nProof.\n  induction b using bilist_incr_ind.\n  simpl.\n  rewrite plus_comm.\n  auto.\n  rewrite minus_incr_decr.\n  rewrite minus_decr.\n  Search (incr1 (plus _ _) = plus _ (incr1 _)).\n  rewrite plus_incr1_right.\n  rewrite decr1_incr1.\n  assumption.\nQed.\n\nFixpoint minusm (b b' : bilist): bilist :=\n  if length (skipn (length b - length b') b) =? length b' then\n  if length b =? length b' then \n  match b with\n  | [] => []\n  | E1 :: t => match b' with\n              | [] => b\n              | E1 :: t' => minusm t t'\n              | E2 :: t' => []\n  end\n  | E2 :: t => match b' with\n              | [] => b\n              | E1 :: t' => minusm ([E1] ++ t) t'\n              | E2 :: t' => minusm t t' \n  end\n  end\n  else \n  match b' with\n  | [] => b\n  | E1 :: t => minusm (decr1 (firstn (length b - length t)  b)\n              ++ (skipn (length b - length t) b)) t\n  | E2 :: t => minusm (decr1 (decr1 (firstn (length b - length t ) b))\n  ++ (skipn (length b - length t) b)) t\n  end\n  else [].\n\n(*\nFixpoint minusm (a b : bilist): bilist :=\n  match ltb (length a) (length b) with\n  | false => []\n  | true => if length a =? length b then \n  match a with\n  | [] => []\n  | E1 :: t => match b with\n              | [] => a\n              | E1 :: t' => minusm t t'\n              | E2 :: t' => []\n  end\n  | E2 :: t => match b with\n              | [] => b\n              | E1 :: t' => minusm (E1 :: t) t'\n              | E2 :: t' => minusm t t' \n  end\n  end\n  else  \n  if length a =? (S (length b)) then\n  match b with\n  | [] => a\n  | E1 :: t => match a with\n                | [] => []\n                | E1 :: t' => match t' with\n                              | [] => []\n                              | E1 :: t1 => (minusm (E2::t1) t)\n                              | E2 :: t1 => [E1] ++ (minusm ([E1] ++ t1) t)\n                end \n                | E2 :: t' => match t' with\n                              | [] => []\n                              | E1 :: t1 => (minusm ([E1;E2] ++ t1) t)\n                              | E2 :: t1 => E2 :: (minusm ([E1] ++ t1) t)\n                end\n  end\n  | E2 :: t => match a with\n                | [] => []\n                | E1 :: t' => match t' with\n                              | [] => []\n                              | E1 :: t1 => (minusm (E1::t1) t)\n                              | E2 :: t1 => (minusm (E2 :: t1) t)\n                end\n                | E2 :: t' => match t' with\n                              | [] => []\n                              | E1 :: t1 => (minusm ([E1;E1] ++ t1) t)\n                              | E2 :: t1 => (minusm ([E1;E2] ++ t1) t) \n                end\n  end\n  end\n  else \n  match a with\n  | [] => b\n  | h :: t => h :: (minusm t b)\n  end\nend.\n*)\nExample check_minm: minusm [E1;E2;E1] [E2; E1;E1] = [].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample check1: minusm [E1;E1;E1] [E2;E2] = [E1].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample check2: minusm [E1;E1;E2] [E2;E1] = [E1;E1].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nExample check3: minusm [E1;E2;E1] [E2;E1] = [E1;E2].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nExample check4: minusm [E1;E2;E1] [E1;E2] = [E2;E1].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample check_mi: minusm [E2;E2] [E1] = [E2;E1].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample check_mi1: minusm [E2;E2;E2] [E1] = [E2;E2;E1].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample check_mi2: minus [E1;E2;E1] [E1] = [E1;E1;E2].\nProof.\n  reflexivity.\nQed.\n\nExample check_mi3: minusm [E2] [E1;E1] = [].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample check_mi4: minusm [E2;E2] [E1;E1] = [E1;E1].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nLemma minus_aa: forall a : bilist,\n  minusm a a = [].\nProof.\n  induction a using list_ind_length.\n  auto.\n  destruct a.\n  auto.\n  destruct b.\n  simpl.\n  replace (length (skipn (length a - length a) (E1 :: a)) =? S (length a)) with true.\n  destruct (a).\n  simpl.\n  auto.\n  replace ( match length (b :: l) with\n  | 0 => S (length (b :: l))\n  | S l0 => length (b :: l) - l0\n  end) with 1.\n  simpl firstn.\n  simpl skipn.\n  simpl decr1.\n  Search ([] ++ _ = _).\n  rewrite app_nil_l.\n  rewrite Nat.eqb_refl.\n  apply H.\n  auto.\n  destruct (length (b::l)).\n  reflexivity.\n  lia.\n  replace (length a - length a) with 0.\n  simpl.\n  symmetry.\n  apply Nat.eqb_refl.\n  lia.\n  simpl.\n  replace (length (skipn (length a - length a) (E2 :: a)) =? S (length a)) with true.\n  rewrite Nat.eqb_refl.\n  apply H.\n  auto.\n  replace (length a - length a) with 0.\n  simpl.\n  symmetry.\n  apply Nat.eqb_refl.\n  lia.\nQed.\n\n\nInductive biZ := biNat : bilist -> biZ | biNeg : bilist -> biZ.\n\nFixpoint bilist2nat (b: bilist) : nat :=\n  match b with\n  | [] => 0\n  | h::t => let n := bilist2nat t in\n            match h with \n            | E1 => pow 2 (length t) + n\n            | E2 => pow 2 (1 + length t) + n\n            end\n  end.\n\nCompute bilist2nat [E2;E1;E1].\nCompute bilist2nat [E2;E2;E2].\n\n\nRequire Import ZArith.\n\nInductive diadic : Type := Diadic:  bilist -> diadic . \nDefinition diadic2Z (d: diadic) : Z := \n  let (b) := d in\n  Z.of_nat (bilist2nat b).\n\n\nFixpoint nat2bilist (n: nat) : bilist :=\n  match n with \n  | 0 => []\n  | S n => incr1 (nat2bilist n)\n  end.\n\nDefinition Z2diadic (z: Z) : diadic := Diadic (nat2bilist (Z.to_nat z)).\n\nLemma nat2bilist_plus: forall a b, nat2bilist (a + b) = plus (nat2bilist a) (nat2bilist b) .\nProof.\n  intros.\n  generalize dependent b.\n  induction a; intros.\n  simpl. auto.\n  simpl.\n  rewrite IHa.\n  rewrite plus_incr1_left. auto.\nQed.\n\n\nLemma bilist2nat_correct: forall b, nat2bilist (bilist2nat b) = b.\nProof.\n  intros.\n  induction b using list_ind_length.\n  simpl. auto.\n\n  destruct b.\n  simpl. auto.\n\n  simpl.\n  destruct b.\n\n  rewrite nat2bilist_plus.\n  rewrite H.\n  rewrite <- iter_incr1_tail1.\n  remember ((2 ^ length b0)).\n  clear H. clear Heqn.\n  generalize dependent b0.\n  induction n; intros.\n  simpl. auto.\n  simpl.\n  rewrite plus_incr1_left.\n  rewrite IHn.\n  rewrite <- iterS.\n  simpl. auto.\n  simpl. lia.\n\n  replace ((2 ^ length b0 + (2 ^ length b0 + 0) + bilist2nat b0)) with ((2 ^ length b0 + 2 ^ length b0 ) + bilist2nat b0).\n  rewrite nat2bilist_plus.\n  rewrite H.\n  rewrite <- iter_incr1_tail2.\n  remember ((2 ^ length b0 + 2 ^ length b0)).\n  clear H. clear Heqn.\n  generalize dependent b0.\n  induction n; intros.\n  simpl. auto.\n  simpl.\n  rewrite plus_incr1_left.\n  rewrite IHn.\n  rewrite <- iterS.\n  simpl. auto.\n  simpl. lia.\n  lia. \nQed.\n\nLemma nat2bilist_correct: forall n, bilist2nat (nat2bilist n) = n.\nProof.\n  intros.\n  induction n.\n  simpl. auto.\n  simpl.\n  enough (forall b, bilist2nat (incr1 b) = S (bilist2nat b)).\n  rewrite H.\n  rewrite IHn. auto.\n  clear IHn.\n  induction b using list_ind_length.\n  simpl.\n  auto.\n  simpl.\n  destruct b.\n  simpl. auto.\n  simpl.\n  remember (length (incr1 b0) =? length b0).\n  destruct b; destruct b1; simpl.\n  -\n  rewrite H.\n  replace (length (incr1 b0)) with (length b0).\n  lia.\n  apply PeanoNat.Nat.eqb_eq.\n  rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_sym.\n  simpl. lia.\n  -\n  destruct b0.\n  simpl. auto.\n  rewrite <- incr1_tl_comm_E2.\n  simpl tl.\n  rewrite H.\n  replace (length (incr1 b0)) with (S (length b0)).\n  replace b with E2.\n  simpl. lia.\n  enough (Forall (eq E2) (b :: b0)).\n  inversion H0. auto.\n  apply incr1_cons2.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (length (b :: b0) <= length (incr1 (b :: b0))).\n  lia.\n  apply incr1_length.\n  apply incr1_length_plus.\n  symmetry in Heqb1.\n  assert (Forall (eq E2) b0).\n  enough (Forall (eq E2) (b::b0)).\n  inversion H0.\n  auto.\n  apply incr1_cons2.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (length (b :: b0) <= length (incr1 (b :: b0))).\n  lia.\n  apply incr1_length.\n  apply incr1_cons2_inv. auto.\n  simpl. lia.\n  simpl. lia.\n  apply incr1_cons2.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (length (b :: b0) <= length (incr1 (b :: b0))).\n  lia.\n  apply incr1_length.\n-\n  rewrite H.\n  replace  (length (incr1 b0)) with (length b0).\n  lia.\n  apply PeanoNat.Nat.eqb_eq.\n  rewrite Heqb1.\n  apply PeanoNat.Nat.eqb_sym.\n  simpl. lia.\n-\n  rewrite H.\n  replace (length (incr1 b0)) with (S (length b0)).\n  simpl.\n  lia.\n  apply incr1_length_plus.\n  symmetry in Heqb1.\n  apply PeanoNat.Nat.eqb_neq in Heqb1.\n  enough (length b0 <= length (incr1 b0))  .\n  lia.\n  apply incr1_length.\n  simpl. lia.\nQed.  \n\n\nDeclare Scope diadic_scope.\nDelimit Scope diadic_scope with ddd.\n\n\n", "meta": {"author": "Pruvendo", "repo": "dyadic-arith", "sha": "e3f4927ff49cf46e9e3b26edead241b47a4f6951", "save_path": "github-repos/coq/Pruvendo-dyadic-arith", "path": "github-repos/coq/Pruvendo-dyadic-arith/dyadic-arith-e3f4927ff49cf46e9e3b26edead241b47a4f6951/src/Diadic/diadic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7372599431561967}}
{"text": "(**\n  Autor: Luis Felipe Benítez Lluis\n  script de proposiciones a demostrar de la \n  sección de lógica clásica  *)\nRequire Import Classical.\nFrom Tarea2VF Require Export Defs_LC .\n  \n\n\n(** Lemas *)\n\n\nProposition and_not_imply : forall A B : Prop, A /\\~ B -> ~ (A -> B).\nProof.\nintros A B H.\ndestruct H.\ntercero_ex (~ (A -> B)).\n- assumption.\n- apply NNPP in H1.\n  apply H1 in H.\n  contradiction_classic.\nQed.\n\n(* Este teorema se prueba en LM pero usa intros sobre la negación\n   por lo que se vuelve a probar en forma clásica para\n  evitar usar estas técnicas. No obstante su uso no\n  implica que nos salgamos de LM *)\n(* From Tarea2VF Require Import Props_LM . *)\n(* Check PNNP.*)\n\nLemma PNNP_classic: forall P: Prop,\n  P-> ~~P.\nProof.\n  intros.\n  tercero_ex (~P).\n  contradiction_classic.\n  assumption.\nQed.\n\n(* Este teorema puede que sea redundante y ya haya uno\n   semejante, pero se vuelve a probar para asegurar no \n   usar las técnicas prohibidas*)\n\nTheorem Contrapos_classic :forall P Q: Prop, (P -> Q) <-> (~Q -> ~P).\nProof.\n  split.\n  + intros.\n    tercero_ex (P).\n    2:{ assumption. }\n    apply H in H1.\n    contradiction_classic.\n  + intros. \n    tercero_ex Q.\n    assumption.\n    apply H in H1.\n    contradiction_classic.\nQed.\n\nLemma Univ_distr_and_classic: \n  forall T ,forall P Q: T -> Prop  , (forall x :T,\n  ( P x /\\ Q x)) <-> ((forall x:T, P x)/\\ (forall x :T, Q x)).\nProof.\n  intros.\n  split.\n  + split.\n    intros.\n    specialize H with x.\n    destruct H.\n    assumption .\n    intros.\n    specialize H with x.\n    destruct H.\n    assumption .\n  + intros.\n    destruct H.\n    split.\n    - specialize H with x.\n      assumption.\n    - specialize H0 with x.\n      assumption.\nQed.\n\n\n\n\n\n(** Propiedades del operador de cotenabilidad *)\n(* Este operador no es nada mas que un 'and' con pasos\n   extra. Todas las propiedades son las correspondientes\n   a las ya conocidas del operador de conjunción.*)\n\nLemma cotComm_ida : forall A B : Prop, A ° B -> B ° A.\nProof.\n   intros.\n   destruct_cot H. \n   apply NNPP in H0.\n   split_cot.\n   * assumption.\n   * apply PNNP_classic.\n     assumption.\nQed.\nProposition cotComm : forall A B : Prop, A ° B <-> B ° A.\nProof. \n  split.\n  * apply cotComm_ida.\n  * apply cotComm_ida.\nQed.\n\n\nProposition cotAsoc: forall A B C : Prop,\n  (A ° B) ° C <-> A ° (B ° C).\nProof.\n  split.\n  + intros.\n    destruct_cot H. \n    apply NNPP in H0.\n    apply imply_to_and in H.\n    destruct H.\n    apply NNPP in H1.\n    split_cot.\n    * assumption.\n    * apply PNNP_classic.\n      tercero_ex ((B -> ~ C)).\n      2: {assumption. }\n      apply H2 in H1.\n      contradiction_classic.\n  + intros.\n    destruct_cot H.\n    apply NNPP in H0.\n    apply  imply_to_and in H0.\n    destruct H0.\n    apply NNPP in H1.\n    split_cot. \n    * tercero_ex (A -> ~ B).\n      2: {assumption. }\n      apply H2 in H.\n      contradiction_classic.\n    * apply PNNP_classic.\n      assumption.\nQed.\n\n\n\n\nProposition cotDist: forall A B C : Prop,\n  (A ° B) \\/ (A ° C) <-> A ° (B \\/ C).\nProof.\n  intros.\n  split.\n  + intros.\n    destruct H.\n    * destruct_cot H.\n      apply NNPP in H0.\n      split_cot.\n      - assumption.\n      - apply PNNP_classic.\n        left.\n        assumption.\n    * destruct_cot H.\n      apply NNPP in H0.\n      split_cot.\n      - assumption.\n      - apply PNNP_classic.\n        right.\n        assumption.\n  + intros. \n    destruct_cot H.\n    apply NNPP in H0.\n    destruct H0.\n    * left. split_cot. assumption.\n      apply PNNP_classic. assumption.\n    * right. split_cot. assumption.\n      apply PNNP_classic. assumption.\nQed.\n\nProposition cotFusion: forall A B C : Prop,\n  (A-> B -> C)<->((A ° B)->C).\nProof.\n  intros.\n  split.\n  + intros. destruct_cot H0.\n    apply NNPP in H1.\n    apply H in H0. assumption. assumption.\n  + intros. \n    apply H.\n    split_cot.\n    assumption.\n    apply PNNP_classic.\n    assumption.\nQed.\n\nProposition cotDefImpl: forall A B : Prop,\n  (A -> B)<-> ~(A ° (~ B)).\nProof.\n  intros.\n  split.\n  + intros.\n    tercero_ex (A ° (~ B)).\n    * destruct_cot H0.\n      apply NNPP in H1.\n      apply H in H0.\n      contradiction_classic.\n    * assumption.\n  + intros.\n    tercero_ex (B).\n    assumption.\n    contradict H.\n    split_cot.\n    assumption.\n    apply PNNP_classic.\n    assumption.\nQed.\n\n  \n(** Argumentos lógicos como proposiciones.*)  \n\nProposition A: forall T,forall a:T, forall A B C: T -> Prop,\n\n  ((exists x:T, (A x /\\ B x )) -> \n        (forall x :T, (B x -> C x)))\n\n  ->                \n  \n  (B a /\\ ~C a) \n  \n  -> \n  \n    ~(forall x: T, A x).\nProof.\n  intros.\n  destruct H0.\n  apply ex_not_not_all.\n  tercero_ex (A a).\n  + assert ( forall x0 : T, B x0 -> C x0).\n    apply H; exists a; split; assumption;  assumption.\n    specialize H3 with (x0:= a).\n    apply H3 in H0.\n    contradiction_classic.\n  + exists a. assumption.\nQed.\n\n\n\nProposition B: forall T,forall m:T, forall C W: T -> Prop, forall B G: T-> T-> Prop, \n\n  (exists x:T, (~ B x m /\\ \n                           (forall y:T, (C y -> ~ G x y ))))\n  \n  ->\n  \n  (forall z :T,(~(forall y,(W y -> G z y) )-> \n                                               B z m) ) \n  \n  ->\n  \n    (forall x, (C x -> ~W x)).\nProof.\n  intros.\n  destruct H.\n  destruct H.\n  specialize H0 with (z:= x0).\n  apply Contrapos_classic in H0.\n  2: { assumption. }\n  apply NNPP in H0.\n  specialize H2 with (y := x).\n  specialize H0 with (y := x).\n  apply H2 in H1.\n  apply Contrapos_classic in H0.\n  2: { assumption. }\n  assumption. \nQed.\n\n  \n\n  \n\nProposition C: forall T, forall P H C L R: T-> Prop, forall A B: T -> T -> Prop, \n\n  ((~(forall x:T,(~P x \\/ ~H x)))\n            ->\n              (forall x:T,(C x /\\\n                                  (forall y: T ,(L y -> A x y)))))\n  ->\n  \n  ((exists x:T,(H x /\\(forall y:T,(L y -> A x y))))\n            ->\n              (forall x: T,(R x /\\ \n                                  (forall y :T, B x y) )))\n    \n  ->\n    (~forall x y:T, B x y)-> \n    (forall x :T,(~P x\\/~ H x)).\nProof.\n  do 11 intro.\n  tercero_ex ((forall x : T, ~ P x \\/ ~ H x)).\n  assumption.\n  assert(forall x : T, C x /\\ (forall y : T, L y -> A0 x y)).\n  {apply H0.  assumption. }\n  apply not_all_ex_not in H3.\n  destruct H3.\n  apply not_or_and in H3.\n  destruct H3.\n  apply NNPP in H3.\n  apply NNPP in H5.\n  specialize H4 with (x:= x).\n  destruct H4.\n  assert(forall x : T, R x /\\ (forall y : T, B0 x y)).\n  {  apply H1. exists x. split. assumption. assumption. }\n  apply Univ_distr_and_classic in H7.\n  destruct H7.\n  contradiction_classic.\nQed.\n\n", "meta": {"author": "LuisBLluis11", "repo": "Tarea2VFLuisBLluis", "sha": "ef1bfd244dc336dcf100ed923574247111ca719a", "save_path": "github-repos/coq/LuisBLluis11-Tarea2VFLuisBLluis", "path": "github-repos/coq/LuisBLluis11-Tarea2VFLuisBLluis/Tarea2VFLuisBLluis-ef1bfd244dc336dcf100ed923574247111ca719a/LogicaClasica/Props_LC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7372599419193819}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.omega.Omega.\n\nDefinition even (n: nat) := exists k, n = 2 * k.\nDefinition odd  (n: nat) := exists k, n = 2 * k + 1.\n\n\nAxiom classic : forall P:Prop, P \\/ ~ P.\n\nTheorem\teasy:\tforall\t(p\tq:\tProp),\np\t->\t((p->q)\t->\tp). (*Question 1*)\nProof.\nintro p.\nintro q.\nintro p_lhs.\nfirstorder.\nQed.\n\nTheorem\tConversion:\tforall\t(p\tq:\tProp),\n(p\t->\tq)\t->\t(~\tp\t\\/\tq). (*Question 2*)\nProof.\nintros p q.\nintros p_implies_q.\ndestruct (classic p) as [p_true | p_false].\npose (p_implies_q p_true) as l.\nright.\nexact l.\nleft.\nexact p_false.\nQed.\n\nTheorem\tNotNotAImpA\t:\tforall\tA:\tProp,\t~~A\t->\t\tA.  (*Question 3*)\nProof.\nintro A.\nintro double_neg.\ndestruct (classic A) as [p_true | p_false].\nexact p_true.\ncontradiction.\nQed.\n\nTheorem\tPeirceContra:\tforall\t(p\tq:Prop),\n~\tp\t->\t~((p\t\t->\tq)\t\t->\tp). (*Question 4*)\nProof.\nintro p.\nintro q.\nintro H.\ndestruct (classic p) as [p_true | p_false].\nintro r.\npose(H p_true)as d.\nexact d.\nintro k.\napply H.\nintuition.\nQed.\n\nTheorem\tPeirce:\tforall\t(p\tq:\tProp),\n((p\t->\tq)\t->\tp)\t->\tp. (*Question 5*)\nProof.\nintro p.\nintro q.\nintro r.\ndestruct (classic p) as [p_true | p_false].\nexact p_true.\nfirstorder.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Prateekarora1998", "repo": "Coq-and-NP-angry-bird-problem", "sha": "e2b4f44fb686347cade294830dd59d81014456b7", "save_path": "github-repos/coq/Prateekarora1998-Coq-and-NP-angry-bird-problem", "path": "github-repos/coq/Prateekarora1998-Coq-and-NP-angry-bird-problem/Coq-and-NP-angry-bird-problem-e2b4f44fb686347cade294830dd59d81014456b7/u6742441.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7372539636297923}}
{"text": "(**\nA Gentle Introduction to Type Classes and Relations in Coq\nの\nChapter 3. Lost in Manhattan\nを SSReflectで書いてみた。\n\n3.7 Deciding Route Equivalence\nのEx1'の証明ができることを目標とする。\n\n@suharahiromichi\n*)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssralg ssrint.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.                        (* !!! *)\nCheck addrA.\nCheck addrC.\nCheck add0r.\n\nCheck (1 + 1)%R.                            (* _ *)\nCheck 1 + 1.                                (* nat *)\nOpen Scope ring_scope.\nCheck 1 + 1.                                (* _ *)\n\n(**\n3.2 Data Types and Definitions\n*)\n(** Types for representing routes in the dicrete  plane *)\n\nInductive direction : Type :=\n  North | East | South | West.\nDefinition route := list direction.\n\nRecord Point : Type :=\n  {\n    Point_x : int; \n    Point_y : int\n  }.\n\nDefinition Point_O := Build_Point 0 0.\n\n(**\n3.3 Route Semantics\n *)\nDefinition translate (dx dy : int) (P : Point) :=\n  Build_Point (Point_x P + dx) (Point_y P + dy).\nCheck translate : int -> int -> Point -> Point.\nCheck translate (-1) 1 Point_O : Point.\n\n(** Equality test  between Points *)\nDefinition Point_eqb (P P': Point) : bool :=\n  (Point_x P == Point_x P') &&\n  (Point_y P == Point_y P').\n\n(*  move P r follows the route r starting from P *)\nFixpoint move (r:route) (P:Point) : Point :=\n  match r with\n    | nil => P\n    | North :: r' => move r' (translate 0 1 P)\n    | East :: r' => move r' (translate 1 0 P) \n    | South :: r' => move r' (translate 0 (-1) P)\n    | West :: r' => move r' (translate (-1) 0 P)\n  end.\n\n(* We consider that two routes are \"equivalent\" if they define\n  the same moves. For instance, the routes\n  East::North::West::South::East::nil and East::nil are equivalent *)\n\n\nLemma Point_eqb_correct' :\n  forall p p', Point_eqb p p' <-> p = p'.\nProof.\n  case=> x y.                               (* by p *)\n  case=> x' y'.                             (* by p' *)\n  split.\n  (* -> *)\n  rewrite /Point_eqb /=.\n  move/andP => [] /eqP Hxx' /eqP Hyy'.\n  by rewrite Hxx' Hyy'.\n\n  (* <- *)\n  rewrite /Point_eqb /=.\n  case=> Hxx' Hyy'.\n  by apply/andP; split; [rewrite Hxx' | rewrite Hyy'].\nQed.\n\nLemma PointEqP p p' : reflect (p = p') (Point_eqb p p').\nProof.\n  apply: (@iffP (Point_eqb p p')).\n  - by apply: idP.\n  - by rewrite (Point_eqb_correct' p p').\n  - by rewrite (Point_eqb_correct' p p').\nQed.\n\n(* Point_eqb_correct の別の証明 *)\n(* バニラCoqの andb_true_iff だが、andP を直接使えばよい。 *)\nLemma andb_true_iff :\n  forall b1 b2 : bool, b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  move=> b1 b2.\n  split => H.\n  by apply/andP.\n  by apply/andP.\nQed.\n\nLemma int_eq_boolP (a b : int) :\n  reflect (a = b) (a == b).\nProof.\n  by apply/eqP.\nQed.\n\n(* Prove the correctness of Point_eqb *)\nLemma Point_eqb_correct :\n  forall p p', Point_eqb p p' = true <-> p = p'.\nProof.\n  move=> p p'.\n  elim: p; elim: p'; split.\n  - rewrite /Point_eqb //=.\n    move/andP.\n    elim.\n    move/int_eq_boolP => H1.\n    move/int_eq_boolP => H2.\n      by rewrite H1; rewrite H2.\n  - elim.\n    rewrite /Point_eqb //=.\n    apply/andP.\n    split.\n      by apply/int_eq_boolP.\n      by apply/int_eq_boolP.\nQed.      \n\n(* *************************** *)\n\n(* Point_O が固定であることに注意。ここでは、このboolを中心に使っていく。 *)\nDefinition route_eqb r r' : bool :=\n  Point_eqb (move r Point_O) (move r' Point_O).\nInfix \"=r==\" := route_eqb (at level 70):type_scope.\n\nExample Ex1'' : East::North::West::South::East::nil =r== East::nil.\nProof.\n  apply Point_eqb_correct.\n  by [].\nQed.\n\n(* *************************** *)\n(**\n3.4 On Route Equivalence \n*)\nCheck rel route.\nCheck reflexive.\nCheck reflexive route_eqb.\nLemma route_eqb_refl : reflexive route_eqb.\nProof.\n  move=> r.\n  apply/andP; by [].\nQed.\n\nLemma route_eqb_sym : symmetric route_eqb.\nProof.\n  move=> r y.\n  rewrite /route_eqb.\n  apply/idP/idP;\n    move/PointEqP => H;\n      by apply/PointEqP.\nQed.\n\nLemma route_eqb_trans : transitive route_eqb.\nProof.\n  move=> r x z.\n  rewrite /route_eqb.\n  move/PointEqP => H1;\n  move/PointEqP => H2;\n  apply/PointEqP.\n  by rewrite H1 H2.\nQed.\n\nLemma route_eqb_Eqb : equivalence_rel route_eqb.\nProof.\n  split.\n  - apply: route_eqb_refl.\n  - move=> H1.\n    apply/idP/idP => H2.\n    Check @route_eqb_trans x y z.\n    + apply: (@route_eqb_trans x y z).\n      Check @route_eqb_sym y x.\n      * by rewrite (@route_eqb_sym y x).\n      * by apply: H2.\n    Check @route_eqb_trans y x z.\n    + apply: (@route_eqb_trans y x z).\n      * by apply: H1.\n      * by apply: H2.\nQed.\n\n(* route_eqb (=r==) を使う場合。 *)\nExample Ex2' : South::East::North::West::South::East::nil =r== South::East::nil.\nProof.\n  (* apply: route_cons. *)\n  by apply: Ex1''.\nQed.\n\nExample Ex3' : forall r, North::East::South::West::r =r== r.\nProof.\n  move=> r.\n  apply/PointEqP.\n  by rewrite //=.\nQed.\n\nExample Ex4' : forall r r', r =r== r' -> \n                North::East::South::West::r =r== r'.\nProof.\n  by [].\nQed.\n\n(* ****************** *)\n(* route_equiv と route_eqb の reflect を証明する *)\n(* ****************** *)\n\n(* これは、SSReflect の rel ではない。 *)\nDefinition route_equiv (r r' : route) :=\n  forall (P : Point), (move r P) = (move  r' P).\nCheck route_equiv : route -> route -> Prop.\nInfix \"=r=\" := route_equiv (at level 70):type_scope.\n\n(**\n3.6 Some Other instances of Proper\n*)\nLemma route_compose :\n  forall r r' P, move (r ++ r') P = move r' (move r P).\nProof.\n  induction r as [|d s IHs]; simpl;\n  [auto | destruct d; intros;rewrite IHs;auto].\nQed.\n\n\nCheck (1 - 1).\nSearch (_ - _).\nCheck subr_eq.\n\nLemma test_sub_eq (x y z : int) :           (* 使っていない *)\n  x = y + z -> x - z = y.                   (* %R *)\nProof.\n  move/eqP => H.\n  apply/eqP.\n  by rewrite subr_eq.\nQed.\n\nLemma test_sub_eq0 (x y : int) :            (* 使っていない *)\n  x = y -> x - y = 0.                       (* %R *)\nProof.\n  move/eqP => H.\n  apply/eqP.\n  by rewrite subr_eq0.\nQed.\n\nExample Ex3 : forall r, North::East::South::West::r =r= r.\nProof.\n  intros r P;\n  case: P => //=.\n  rewrite /translate => //= Px0 Py0.\n  congr (move r _).                         (* f_equal *)\n  congr (Build_Point _ _).                  (* f_equal *)\n  - do 2! rewrite addr0. apply/eqP. by rewrite subr_eq.\n  - do 2! rewrite addr0. apply/eqP. by rewrite subr_eq.\nQed.\n\nLemma translate_comm :\n  forall dx dy dx' dy' P,\n    translate dx dy (translate dx' dy' P) = translate dx' dy' (translate dx dy P).\nProof.\n  rewrite /translate //=.\n  move=> dx dy dx' dy' P.\n  apply Point_eqb_correct'.\n  rewrite /Point_eqb //=.\n  apply/andP.\n  do 4! rewrite -[_ + _ + _]addrA.                   (* %R *)\n  by split; apply/eqP; congr (_ + _); rewrite addrC. (* %R *)\nQed.\n\nLemma move_translate :\n  forall r P dx dy,\n    move r (translate dx dy P) = translate dx dy (move r P).\nProof.\n  induction r as [|a r]; simpl; [reflexivity|].  \n  destruct a;simpl; intros;rewrite <- IHr;rewrite  (translate_comm); auto.\nQed.\n\nLemma move_comm :\n  forall r r' P,\n    move r (move r' P) =  move r' (move r P).\nProof.\n  induction r as [| a r']; [reflexivity|].\n  simpl; destruct a;\n  intros; repeat rewrite move_translate; rewrite IHr'; auto.\nQed.\n\nLemma app_comm : forall r r', r++r' =r=  r'++r.\nProof.\n  intros r r' P; repeat rewrite route_compose; apply move_comm.\nQed.\n\n(** the following lemma  will be used for deciding route equivalence *)\nLemma route_equiv_Origin :\n  forall r r', r =r= r' <-> move r Point_O  = move r' Point_O .\nProof.\n  move=> r r'.\n  split; intro H.\n  rewrite H; trivial.\n  intro P; replace P with (translate (Point_x P) (Point_y P) Point_O).\n  repeat rewrite move_translate.\n  rewrite H; reflexivity.\n  destruct P; simpl; unfold translate; f_equal; simpl.\n  by rewrite add0r.\n  by rewrite add0r.\nQed.\n\n(**  ... we can now prove route_eqb's  correctness *)\nLemma route_equiv_equivb :\n  forall r r',\n    route_equiv r r' <-> route_eqb r r' = true.\nProof.\n  intros r r'; rewrite route_equiv_Origin;\n  unfold route_eqb; rewrite Point_eqb_correct; tauto.\nQed.\n\nLtac route_eq_tac := rewrite route_equiv_equivb; reflexivity.\n\n(** another proof of Ex1, using computation  *)\nExample Ex1' : East::North::West::South::East::nil =r= East::nil.\nProof.\n  route_eq_tac.\nQed.\n\nLemma route_equivP (r r' : route) :\n  reflect (route_equiv r r') (route_eqb r r').\nProof.\n  apply: (@iffP (route_eqb r r')).\n  - by apply: idP.\n  - by apply (route_equiv_equivb r r').\n  - by apply (route_equiv_equivb r r').\nQed.\n\nExample Ex1 : East::North::West::South::East::nil =r= East::nil.\nProof.\n  apply/route_equivP.\n  by [].\nQed.\n\n(* Ex5 は、=r= による rewrite を使うので、この範囲では解けない。 *)\nExample Ex5' : forall r r',  r =r= r' -> r ++ North::East::South::West::r' =r= r ++ r'.\nProof.\n  move=> r r' H.\n  (* rewrite H. *)\n  admit.                                    (* OK *)\nQed.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/gitcrc/ssr_gitcrc_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7372539620779671}}
{"text": "Require Export \"Prop\".\n\nInductive ex (X : Type) (P : X -> Type) : Prop :=\n  ex_intro: forall (witness : X), P witness -> ex X P.\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\nExample exists_example_1 : exists n, n + (n × n) = 6.\nProof.\n  apply ex_intro with (witness := 2).\n  reflexivity.\nQed.\n\nExample exists_example_1' : exists n, n + (n × n) = 6.\nProof.\n  exists 2. reflexivity.\nQed.\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n H. inversion H as [m Hm].\n  exists (2 + m). assumption.\nQed.\n\nLemma exists_example_3 : exists (n:nat), even n /\\ beautiful n.\nProof.\n  exists 8. split.\n  Case \"left\". unfold even. reflexivity.\n  Case \"right\". apply b_sum with (n := 3) (m := 5). apply b_3. apply b_5.\nQed.\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. unfold not. intros H1. inversion H1 as [x Hx].\n  apply Hx.  apply H.\nQed.\n\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  intros X P Q. split.\n  Case \"left\".\n  {\n    intros H. inversion H as [m Hm]. inversion Hm as [Hp | Hq].\n    SCase \"left\". left. exists m. assumption.\n    SCase \"rigth\". right. exists m. assumption.\n  }\n  Case \"right\".\n  {\n     intros H. inversion H as [Hp | Hq].\n     inversion Hp.\n     SCase \"left\". exists witness. left. assumption.\n     inversion Hq.\n     SCase \"rigth\". exists witness. right. assumption.\n  }\nQed.\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\nTheorem eq_nat_dec : forall n m : nat, {n = m} + {n <> m}.\nProof.\n  intros n. induction n.\n  Case \"n = O\".\n  {\n    intros m. destruct m.\n    SCase \"m = O\". apply left. reflexivity.\n    SCase \"m = S m\". apply right. intros H. inversion H.\n  }\n  Case \"n = S n\".\n  {\n    intros m. destruct m.\n    SCase \"m = O\". apply right. intros H. inversion H.\n    SCase \"m = S m\". destruct IHn with (m := m) as [Heq | Hneq].    \n    apply left. apply f_equal. assumption.\n    apply right.  intros H. inversion H. apply Hneq. assumption.\n  }\nQed.\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 -> (override' f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f H. unfold override'.\n  destruct (eq_nat_dec k1 k2). rewrite <- H. apply f_equal. assumption.\n  reflexivity.\nQed.\n\n\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  intros X x1 x2 k1 k2 f. unfold override'.\n  destruct (eq_nat_dec k1 k2). reflexivity. reflexivity.\nQed.\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n| empty : all X P []\n| cons : forall (x : X) (xs : list X),  P x -> all X P xs -> all X P (x :: xs).\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\nTheorem forallb_and_all :\n  forall (X : Type) (test : X -> bool) (l : list X),\n    forallb test l = true <-> all X (fun x => test x = true) l.\nProof.\n  intros X test l. split.\n  Case \"->\".\n  {\n    induction l.\n    SCase \"[]\". intros H. apply empty.\n    SCase \"Cons n l\". simpl. intros H. apply cons. destruct (test x).\n    reflexivity. inversion H. apply andb_prop in H. inversion H. apply IHl.\n    assumption.\n  }\n  Case \"<-\".\n  {\n    intros H. induction H.\n    SCase \"empty\". reflexivity.\n    SCase \"cons\". simpl. apply andb_true_intro. split. assumption.\n    assumption.\n  }\nQed.\n\n\nInductive merge {X : Type} : list X -> list X -> list X -> Prop :=\n| emptym : merge [] [] []\n| firstm : forall (x : X) (l m n : list X), merge l m n -> merge (x :: l) m (x :: n)\n| secondm : forall (x : X) (l m n : list X), merge l m n -> merge l (x :: m) (x :: n).\n\n\nTheorem filter_challenge : forall (X:Type) (test: X->bool) (l1 l2 l:list X),\n  merge l1 l2 l ->\n  all X (fun x => test x = true) l1 ->\n  all X (fun x => test x = false) l2 ->\n  filter test l = l1.\nProof. Abort.\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\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 intros X xs ys x H. induction xs.\n Case \"nil\". right. assumption.\n Case \"Cons n l\".\n {\n   inversion H.\n   SCase \"left\". left. apply ai_here.\n   SCase \"right\".  apply IHxs in H1. inversion H1. left. apply ai_later.\n   assumption.  right. assumption.\n }\nQed.\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  intros X xs ys x H. destruct H.\n  induction xs. inversion H. inversion H.\n  constructor. simpl. constructor. auto.\n  induction xs. assumption.\n  simpl. constructor. assumption.\nQed.\n", "meta": {"author": "tabtab777", "repo": "Coq", "sha": "4ffc37f0c970349ef1942a1519b729c6e5cba581", "save_path": "github-repos/coq/tabtab777-Coq", "path": "github-repos/coq/tabtab777-Coq/Coq-4ffc37f0c970349ef1942a1519b729c6e5cba581/software-foundation/MoreLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.8824278788223264, "lm_q1q2_score": 0.737253958207688}}
{"text": "(* \"Accept this definition without proof\" *)\nDefinition admit {T: Type} : T.  Admitted.\n\nInductive day : Type :=\n  | monday : day\n  | tuesday: day\n  | wednesday : day.\n\nDefinition next_weekday (d:day) : day :=\n  match d with\n  | monday => tuesday\n  | tuesday => wednesday\n  | wednesday => monday\n  end.\n\n(*Eval compute in (next_weekday monday).*)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday tuesday)) = monday.\nProof.\n  simpl.\n  reflexivity.\nQed.\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\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => negb b2\n  | false => true\n  end.\n\nExample test_nandb1: (nandb true false) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_nandb2: (nandb false false) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_nandb3: (nandb false true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_nandb4: (nandb true true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  (andb b1 (andb b2 b3)).\n\nExample test_andb31: (andb3 true true true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_andb32: (andb3 false true true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nExample test_andb33: (andb3 true false true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_andb34: (andb3 true true false) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n(*\nCheck true.\n\nCheck (negb true).\n\nCheck test_andb34.\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\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nExample test_oddb1: (oddb (S O)) = true.\nProof. reflexivity. Qed.\nExample test_oddb2: (oddb (S (S (S (S O))))) = false.\nProof. reflexivity. Qed.\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\nFixpoint sub (n m : nat) : nat :=\n  match n with\n    | O => O\n    | S n' =>\n      match m with\n        | O => n\n        | S m' => sub n' m'\n      end\n  end.\n\nExample plus_works: plus 2 3 = 5.\nProof. reflexivity. Qed.\n\nExample sub_works: sub 5 3 = 2.\nProof. reflexivity. Qed.\n\nExample sub_zero: sub 3 5 = 0.\nProof. reflexivity. Qed.\n\n(* Eval compute in (plus (S (S (S O))) (S (S O))). *)\n\nNotation \"x + y\" := (plus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\nNotation \"x - y\" := (sub 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(* Check ((0 + 1) + 1). *)\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. reflexivity.  Qed.\nExample test_ble_nat2:             (ble_nat 2 4) = true.\nProof. reflexivity.  Qed.\nExample test_ble_nat3:             (ble_nat 4 2) = false.\nProof. reflexivity.  Qed.\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\nDefinition blt_nat (n m : nat) : bool :=\n  andb (ble_nat n m) (negb (beq_nat n m)).\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\nProof. reflexivity.  Qed.\n\nExample test_blt_nat2:             (blt_nat 2 4) = true.\nProof. reflexivity.  Qed.\n\nExample test_blt_nat3:             (blt_nat 4 2) = false.\nProof. reflexivity.  Qed.\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 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 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n.\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_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\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 H2.\n  rewrite H1.\n  rewrite H2.\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_O_n.\n  reflexivity.  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 H.\n  rewrite H.\n  reflexivity.\nQed.\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.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros n.\n  destruct n as [| n'].\n  reflexivity.\n  reflexivity.\nQed.\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 f H b.\n  rewrite H.\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem andb_f_l : forall (x : bool), andb false x = false.\nProof.\n  intros x.\n  reflexivity.\nQed.\n\nTheorem andb_f_r : forall (x : bool), andb x false = false.\nProof.\n  intros x.\n  destruct x.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem andb_t_l : forall (x : bool), andb true x = x.\nProof.\n  intros x.\n  reflexivity.\nQed.\n\nTheorem andb_t_r : forall (x : bool), andb x true = x.\nProof.\n  intros x.\n  destruct x.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem orb_t_l : forall (x : bool), orb true x = true.\nProof.\n  intros x.\n  reflexivity.\nQed.\n\nTheorem orb_t_r : forall (x : bool), orb x true = true.\nProof.\n  intros x.\n  destruct x.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem orb_f_l : forall (x : bool), orb false x = x.\nProof.\n  intros x.\n  reflexivity.\nQed.\n\nTheorem orb_f_r : forall (x : bool), orb x false = x.\nProof.\n  intros x.\n  destruct x.\n  reflexivity.\n  reflexivity.\nQed.\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.\n  rewrite andb_t_l.\n  rewrite orb_t_l.\n  intros H.\n  rewrite H.\n  reflexivity.\n  rewrite andb_f_l.\n  rewrite orb_f_l.\n  intros H.\n  rewrite H.\n  reflexivity.\nQed.\n\nInductive bin : Type :=\n  | B0 : bin\n  | B1 : bin -> bin\n  | B2 : bin -> bin.\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n    | B0 => 0\n    | B1 b' => 2 * (bin_to_nat b')\n    | B2 b' => (2 * (bin_to_nat b')) + 1\n  end.\n\nFixpoint bin_incr (b : bin) : bin :=\n  match b with\n    | B0 => B2 B0\n    | B1 b' => B2 b'\n    | B2 b' => B1 (bin_incr b')\n  end.\n\nFixpoint nat_to_bin (n : nat) : bin :=\n  match n with\n    | 0 => B0\n    | S n => bin_incr (nat_to_bin n)\n  end.\n\nExample nbn_0: bin_to_nat (nat_to_bin 0) = 0.\nProof. reflexivity. Qed.\n\nExample nbn_1: bin_to_nat (nat_to_bin 1) = 1.\nProof. reflexivity. Qed.\n\nExample nbn_2: bin_to_nat (nat_to_bin 2) = 2.\nProof. reflexivity. Qed.\n\nExample nbn_3: bin_to_nat (nat_to_bin 3) = 3.\nProof. reflexivity. Qed.\n\nExample nbn_4: bin_to_nat (nat_to_bin 4) = 4.\nProof. reflexivity. Qed.\n\nExample nbn_5: bin_to_nat (nat_to_bin 5) = 5.\nProof. reflexivity. Qed.\n\nLemma plus_0_r : forall n : nat, n + 0 = n.\nProof.\n  intros n.\n  induction n as [| n'].\n  reflexivity.\n  simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nLemma plus_0_l : forall n : nat, 0 + n = n.\nProof.\n  intros n.\n  induction n as [| n'].\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nLemma whatever: forall n m : nat, m + S n = S (m + n).\nProof.\n  intros n m.\n  induction m as [|m'].\n  rewrite plus_0_l.\n  rewrite plus_0_l.\n  reflexivity.\n  simpl.\n  rewrite IHm'.\n  reflexivity.\nQed.\n\nLemma plus_comm : forall n m : nat, n + m = m + n.\nProof.\n  intros m n.\n  induction n as [|n'].\n  rewrite plus_0_r.\n  rewrite plus_0_l.\n  reflexivity.\n  assert (H2: n' + m = m + n').\n    symmetry.\n    assumption.\n  simpl.\n  rewrite H2.\n  simpl.\n  rewrite whatever.\n  reflexivity.\nQed.\n\nLemma plus_assoc : forall n m o : nat, n + (m + o) = (n + m) + o.\nProof.\n  intros n m o.\n  induction n as [|n'].\n  rewrite plus_0_l.\n  rewrite plus_0_l.\n  reflexivity.\n  simpl.\n  rewrite IHn'.\n  reflexivity.\nQed.\n\nLemma binary_unary_inc_commute : forall b : bin,\n  bin_to_nat (bin_incr b) = (bin_to_nat b) + 1.\nProof.\n  intros b.\n  induction b.\n  reflexivity.\n  simpl.\n  rewrite plus_0_r.\n  reflexivity.\n  simpl.\n  rewrite plus_0_r.\n  rewrite plus_0_r.\n  rewrite IHb.\n  remember (bin_to_nat b) as x.\n  rewrite plus_assoc.\n  assert (H2: x + 1 + x = x + x + 1).\n    rewrite plus_comm.\n    rewrite plus_assoc.\n    reflexivity.\n  rewrite H2.\n  reflexivity.\nQed.\n\nTheorem nat_to_bin_to_nat: forall n : nat, bin_to_nat (nat_to_bin n) = n.\nProof.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite binary_unary_inc_commute.\n  rewrite IHn.\n  rewrite plus_comm.\n  reflexivity.\nQed.\n", "meta": {"author": "ejconlon", "repo": "sfsolutions", "sha": "0bb5c48f00d10e80fe63220b0d7eeebcfb3e04d4", "save_path": "github-repos/coq/ejconlon-sfsolutions", "path": "github-repos/coq/ejconlon-sfsolutions/sfsolutions-0bb5c48f00d10e80fe63220b0d7eeebcfb3e04d4/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.8354835371034369, "lm_q1q2_score": 0.7372539473541948}}
{"text": "(* \"Human\" is a thing. *)\nAxiom Human  : Type.\n(* \"This human is mortal\" is a proposition. *)\nAxiom Mortal : Human -> Prop.\n\n(* It is given that \"all humans are mortal\" has a proof. *)\nAxiom all_humans_mortal :\n  forall h : Human, Mortal h.\n\n(* It is given that Socrates is a human *)\nAxiom socrates : Human.\n\n(* It results that Socrates is mortal *)\nTheorem socrates_mortal : Mortal socrates.\nProof.\n  exact (all_humans_mortal socrates).\nQed.", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/Geometry/socrates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7371447184247879}}
{"text": "Require Import List.\nRequire Import Omega.\n\n(******************************************************************************)\n(**************************** DM COQ 2019-2020 ********************************)\n(******************************************************************************)\n(******************************************************************************)\n(***************************# Adrien BLASSIAU #********************************)\n(***************************# Corentin JUVIGNY #*******************************)\n(******************************************************************************)\n(******************************************************************************)\n(******* PREUVES RÉUSSIES : 41 ************************************************)\n(******* PREUVES ADMISES :   7 ************************************************)\n(******************************************************************************)\n\n\n(******************************************************************************)\n(******************************************************************************)\n(********************** Exercice 1 (Listes et comptage) ***********************)\n(******************************************************************************)\n(******************************************************************************)\n(****** PREUVES RÉUSSIES : 7 **************************************************)\n(****** PREUVES ADMISE :   1 **************************************************)\n(******************************************************************************)\n\n\n(** Dans la suite on travaille avec un type A quelconque muni d’une égalité \n    décidable. Pour les tests, on utilise nat. **)\n\nVariable A : Type.\n(**Definition A := nat.**)\n\nHypothesis dec_A : forall (x y : A), ({x=y}+{~x=y}).\n(**Definition dec_A := Nat.eq_dec.**)\n\n(****************)\n(** Question 1 **)\n(****************)\n\n(** occ prend en argument un élément x de type A et une liste l de type (list A) \n    et retourne le nombre d’occurrences de x dans l. **)\nFixpoint occ (x : A) (l : list A) :=\n  match l with\n   | nil => O\n   | x' :: l' =>(\n   match dec_A x' x with\n   | left _ => S (occ x l')\n   | right _ => occ x l'\n   end)\n  end.\nCheck occ.\n(** TESTS\n  Eval compute in (occ 0 (cons 4 (cons 4 (cons 3 (cons 1 (cons 2 (cons 4 nil))))))).\n  Eval compute in (occ 4 (cons 4 (cons 4 (cons 3 (cons 1 (cons 2 (cons 4 nil))))))).\n  Eval compute in (occ 4 nil).\n**)\n\n(****************)\n(** Question 2 **)\n(****************)\n\nTheorem occ_app : forall (x : A) l1 l2,\nocc x (app l1 l2) = (occ x l1) + (occ x l2).\nProof.\n intros x l1 l2.\n induction l1.\n + simpl. reflexivity.\n + simpl. destruct (dec_A a x).\n   - simpl. rewrite IHl1. reflexivity.\n   - rewrite IHl1. reflexivity.\nQed.\n\n(****************)\n(** Question 3 **)\n(****************)\n\nTheorem occ_filter : forall (P : A -> bool) (a : A) l,\nocc a (filter P l) = if (P a) then occ a l else 0.\nProof.\n intros P a l.\n induction l.\n + case_eq (P a).\n   - intros H. simpl. reflexivity.\n   - simpl. reflexivity.\n + case_eq (P a) ;intros H2 ; rewrite H2 in IHl.\n   - case_eq (dec_A a0 a).\n     * intros H3 H4. simpl. rewrite H3. rewrite H2. rewrite H3 in H4. \n       simpl. rewrite H4. rewrite IHl. reflexivity.\n     * intros n H3. simpl. rewrite H3.\n       case_eq(P a0) ; intros H4.\n       ** simpl. rewrite H3. assumption.\n       ** assumption.\n   - simpl. case_eq (dec_A a0 a).\n     * intros H7. intros H8. rewrite H7. rewrite H2. assumption.\n     * intros H1 H3.\n       case_eq(P a0) ; intros H4.\n       ** simpl. rewrite H3. assumption.\n       ** assumption.\nQed.\n\n(****************)\n(** Question 4 **)\n(****************)\n\n(** map applique une fonction f de type A -> A sur tous les éléments d’une liste. **)\nFixpoint map (f : A -> A) (l : list A) :=\n  match l with\n   | nil => nil\n   | x' :: l' => cons (f x') (map f l')\n  end.\nCheck map.\n(** TESTS\n  Eval compute in (map (fun x => x+1) (cons 4 (cons 4 (cons 3 (cons 1 (cons 2 (cons 4 nil))))))).\n**)\n\n\n(** L'énoncé semble éronné. Si on prend deux éléments y et z distinct dans \n    l'ensemble A, on peut construire une fonction f qui rend l'énoncé faux ! **)\nTheorem occ_map : forall (y:A) (z:A), y<>z -> exists (f : A -> A) (x : A) (l : list A),\nocc (f x) (map f l) <> occ x l.\nProof.\n intros y z H.\n exists (fun x => y). exists (y). exists (cons y (cons z nil)). simpl.\n unfold not. intros H1.\n case_eq (dec_A y y).\n + intros e H2. rewrite H2 in H1.\n   case_eq(dec_A z y).\n   - intros e0 H3. pose(e':=e0). symmetry in e'. contradiction.\n   - intros n H3. rewrite H3 in H1. omega.\n + contradiction.\nQed.\n\n(****************)\n(** Question 5 **)\n(****************)\n\nInductive mem : A -> list A -> Prop :=\n| mem_cons : forall x l, mem x (cons x l)\n| mem_tail : forall x y l, mem x l -> mem x (cons y l).\n\n(** Un preuve intermédiaire ... **)\nLemma mem_diff : forall (l : list A) (x : A) (y : A), mem x (cons y l) -> x <> y -> mem x l.\nProof.\n intros l x y H1. induction l ; \n intros H.\n + inversion H1.\n   - contradiction.\n   - assumption.\n + inversion H1.\n   - apply mem_tail. rewrite <- H3. apply IHl.\n     * rewrite H3. apply mem_cons.\n     * assumption.\n   - assumption.\nQed.\n\nTheorem mem_null_1 : forall (l : list A) (x : A), occ x l = 0 -> ~(mem x l).\nProof.\n induction l ; simpl.\n + intros x H. unfold not. intros H1. inversion H1.\n + intros x.\n   case_eq (dec_A a x).\n   - intros e H1 H2. inversion H2.\n   - intros n H1 H2. unfold not. intros H3. pose (IHl2 := IHl x). unfold not in IHl2.\n     apply IHl2.\n     * rewrite H2. reflexivity.\n     * apply mem_diff with (y:=a).\n       apply H3. unfold not. intros H4. symmetry in H4. contradiction.\nQed.\n\nTheorem mem_null_2 : forall (l : list A) (x : A), ~(mem x l) -> occ x l = 0.\nProof.\n intros l x H. unfold not in H. \n induction l ; simpl.\n + reflexivity.\n + case_eq (dec_A a x).\n   - intros e H2. rewrite e in H. pose(H3:= mem_cons x l). pose(H':=H H3).\n     destruct H'.\n   - intros n H1. apply IHl. intros H2. apply mem_tail with (y:=a) in H2. apply H.\n     assumption.\nQed.\n\n(****************)\n(** Question 6 **)\n(****************)\n\nInductive nodup : list A -> Prop :=\n| nodup_nil : nodup nil\n| nodup_tail : forall x l, ~mem x l -> nodup l -> nodup (cons x l).\n\nTheorem doublon_1 : forall (l : list A) (x : A), nodup l -> occ x l <= 1.\nProof.\n intros l x H.\n induction l.\n + simpl. omega.\n + inversion H. unfold not in H2. simpl.\n   case_eq (dec_A a x).\n   * intros e H4. pose (H':=IHl H3). rewrite e in H2. apply mem_null_2 in H2.\n     rewrite H2. omega.\n   * intros n H4. apply IHl.\n     assumption.\nQed.\n\n(** Nous n'avons pas réussi à démontrer la preuve dans ce sens ... **)\nTheorem doublon_2 : forall (l : list A) (x : A), occ x l <= 1 -> nodup l.\nProof.\n intros l.\n induction l ; intros x H.\n + apply nodup_nil.\n + simpl in H.\n   case_eq (dec_A a x).\n   - intros e H1. rewrite H1 in H. \n     apply (nodup_tail).\n     * unfold not. intros H2.\n       case_eq(Nat.eq_dec (occ x l) 0).\n       ** intros e0 H3. pose(H4:=mem_null_1 l x). pose(H5:=H4 e0). \n          rewrite <- e in H5. contradiction.\n       ** intros n H3. omega.\n     * apply (IHl x). omega.\n   - intros n H1.\n     apply nodup_tail.\n     * unfold not. intros H2. rewrite H1 in H. pose(H':=IHl x). pose(H'':=H' H). \n       inversion H2.\nAdmitted.\n\n(******************************************************************************)\n(******************************************************************************)\n(*************** Exercice 2  (Implantation des multi-ensembles) ***************)\n(******************************************************************************)\n(******************************************************************************)\n(****** PREUVES RÉUSSIES : 34 *************************************************)\n(****** PREUVES ADMISES :   6 *************************************************)\n(******************************************************************************)\n\n\n(** Dans la suite on travaille avec un type T quelconque muni d’une égalité \n    décidable. Pour les tests, on utilise nat. **)\n\nVariable T : Type.\n(**Definition T := nat.**)\n\nHypothesis T_eq_dec : forall (x y : T), {x=y} + {~x=y}.\n(**Definition T_eq_dec := Nat.eq_dec.**)\n\n\n(******************************************************************************)\n(****2.1 Implantation des multi-ensembles à l’aide de listes d’association*****)\n(******************************************************************************)\n(****** PREUVES RÉUSSIES : 18 *************************************************)\n(****** PREUVES ADMISES :   6 *************************************************)\n(******************************************************************************)\n\n(****************)\n(** Question 1 **)\n(****************)\n\nDefinition multiset := list (T*nat).\n\n(** empty est le multiset vide. **)\nDefinition empty : multiset := nil.\nCheck empty.\n(** TEST\n  Eval compute in empty.\n**)\n\n\n(** singleton x crée le multi-ensemble qui ne contient que x en un seul exemplaire **)\nDefinition singleton (x:T) : multiset := cons (x,1) empty.\nCheck singleton.\n(** TEST\n  Eval compute in (singleton 2). \n**)\n\n\n(** add x n s ajoute, au multi-ensemble s, n occurrences de l’élément x dans s **)\nFixpoint add (x:T) (n:nat) (s:multiset) : multiset := if (le_lt_dec n 0) then s else\n  match s with\n  | nil => (x,n) :: empty\n  | (x',occ) :: l' => (\n    match (T_eq_dec x x') with\n    | left _ => (x',occ+n) :: l'\n    | right _ => (x',occ) :: (add x n l')\n   end)\n  end.\nCheck add.\n(** TESTS\n  Eval compute in (add 2 3 empty).\n  Eval compute in (add 2 4 (add 2 5 empty)).\n  Eval compute in (add 3 3 (singleton 2)). \n**)\n\n\n(** member x s retourne la valeur true si x a au moins une occurrence dans s, \n    false sinon. **)\nFixpoint member (x:T) (s:multiset) : bool := \n  match s with\n  | nil => false\n  | (x',occ) :: l' => (\n    match (T_eq_dec x x') with\n    | left _ => true\n    | right _ => member x l'\n   end)\n  end.\nCheck member.\n(** TESTS\n  Eval compute in (member 2 (add 2 3 empty)).\n  Eval compute in (member 3 (add 2 5 empty)).\n  Eval compute in (member 1 (singleton 2)). \n  Eval compute in (member 1 empty).\n**)\n\n\n(** union fait l’union de deux multi-ensembles. **)\nFixpoint union (s1:multiset) (s2:multiset) : multiset :=\n  match s1 with\n  | nil => s2\n  | (x',occ) :: l' => union l' (add x' occ s2)\n  end.\nCheck union.\n(** TESTS\n  Eval compute in (union (add 2 3 empty) (add 2 4 empty)).\n  Eval compute in (union (add 2 3 (add 4 5 empty)) (add 2 3 empty)).\n  Eval compute in (union (add 2 3 empty) empty).\n  Eval compute in (union empty empty).\n**)\n\n\n(** muliplicity x s retourne le nombre d’occurrences de x dans s **)\nFixpoint multiplicity (x:T) (s:multiset) : nat := \n  match s with\n  | nil => 0\n  | (x',occ) :: l' => (\n    match (T_eq_dec x x') with\n    | left _ => occ\n    | right _ => multiplicity x l'\n   end)\n  end.\nCheck multiplicity.\n(** TESTS\n  Eval compute in (multiplicity 2 (add 2 7 empty)).\n  Eval compute in (multiplicity 3 (add 2 7 empty)).\n  Eval compute in (multiplicity 3 empty).\n**)\n\n\n(** removeOne x s retourne le multi-ensemble s avec une occurrence de moins \n    pour x. Si s ne contient pas x, le multi-ensemble résultat est s. **)\nFixpoint removeOne (x:T) (s:multiset) : multiset :=\n  match s with\n  | nil => nil\n  | (x', occ) :: l' => (\n    match (T_eq_dec x x') with\n    | left _ => (\n      match (le_lt_dec occ 1) with\n      | left _ => l'\n      | right _ => (x', occ-1) :: l'\n      end)\n    | right _ => (x', occ) :: (removeOne x l')\n   end)\n  end.\nCheck removeOne.\n(** TESTS\n  Eval compute in (removeOne 2 (add 2 7 empty)).\n  Eval compute in (removeOne 2 (add 2 2 (add 3 5 empty))).\n  Eval compute in (removeOne 2 (add 6 5 (add 2 2 (add 3 5 empty)))).\n  Eval compute in (removeOne 2 (add 2 1 (add 3 5 empty))).\n  Eval compute in (removeOne 2 (add 6 5 (add 2 1 (add 3 5 empty)))).\n  Eval compute in (removeOne 3 (add 2 7 empty)).\n  Eval compute in (removeOne 3 empty).\n**)\n\n\n(** removeAll x s retourne le mult-ensemble s o`u x n’apparait plus. \n    Si s ne contient pas x, le multiensemble r´esultat est s. **)\nFixpoint removeAll (x:T) (s:multiset) : multiset :=\n  match s with\n  | nil => nil\n  | (x', occ) :: l' => (\n    match (T_eq_dec x x') with\n    | left _ => l'\n    | right _ => (x', occ) :: removeAll x l'\n   end)\n  end.\nCheck removeAll.\n(** TESTS\n  Eval compute in (removeAll 2 (add 2 7 empty)).\n  Eval compute in (removeAll 2 (add 2 2 (add 3 5 empty))).\n  Eval compute in (removeAll 2 (add 6 5 (add 2 2 (add 3 5 empty)))).\n  Eval compute in (removeAll 2 (add 2 1 (add 3 5 empty))).\n  Eval compute in (removeAll 2 (add 6 5 (add 2 1 (add 3 5 empty)))).\n  Eval compute in (removeAll 3 (add 2 7 empty)).\n  Eval compute in (removeAll 3 empty).\n**)\n\n(****************)\n(** Question 2 **)\n(****************)\n\n(********************)\n(** Question 2. a) **)\n(********************)\n\n(** Ce prédicat spécifie qu’un élément appartient à un multi-ensemble dès lors \n    qu’il en existe une occurrence **)\nInductive InMultiset (x:T) (l:multiset) : Prop := \n  | inMultiset_intro : member x l = true -> InMultiset x l.\n \n \n(********************)\n(** Question 2. b) **)\n(********************)\n\n(** Ce prédicat spécifie qu’une liste qui représente un multi-ensemble est bien \n    formée, c'est-à-dire que tout élément de T apparaît dans au plus un seul couple \n    et que tous les nombres d’occurrences sont des entiers naturels non nuls. **)\nInductive wf (l: multiset) : Prop :=\n  | wf_intro : (forall x, (InMultiset x (removeAll x l) -> False) /\\ (member x l = true -> (multiplicity x l) > 0)) -> wf l.\n\n\n(********************)\n(** Question 2. c) **)\n(********************)\n\n(** empty possède-t-elle un résultat bien formé ? **)\nTheorem empty_wf : wf empty.\nProof.\n  apply wf_intro. intro x. split; simpl ; intros H.\n  + inversion H. discriminate H0.\n  + discriminate H.\nQed. \n\n(** singleton possède-t-elle un résultat bien formé ? **)\nTheorem singleton_wf : forall (x:T), wf (singleton x).\nProof.\n  intro x. apply wf_intro. intros x0. simpl.\n  split.\n  + case_eq (T_eq_dec x0 x).\n    - intros e H H1. inversion H1. discriminate H0.\n    - intros n H1 H2. inversion H2. simpl in H.\n      case_eq (T_eq_dec x0 x).\n      * intros e. contradiction.\n      * intros H3 H4. rewrite H1 in H. discriminate H.\n  + case_eq (T_eq_dec x0 x).\n    - intros e H1 H2. omega.\n    - intros n H1 H2. discriminate H2.\nQed.\n\n(** Un preuve intermédiaire ... **)\nLemma plus_n_0 : forall n, n + O = n.\nProof.\ninduction n.\n+ simpl. reflexivity.\n+ simpl. rewrite IHn. reflexivity.\nQed.\n\n(** Un preuve intermédiaire ... **)\nLemma wf_plus_n : forall t n0 n l, wf ((t, n0) :: l) -> wf ((t, n0+n) :: l).\nProof.\nintros t n0 n l H.\ninduction n.\n+ rewrite plus_n_0. assumption.\n+ apply wf_intro. intros x. split.\n  - simpl.\n    case_eq(T_eq_dec x t).\n    * intros e H1 H2. inversion H2. rewrite e in H0. inversion IHn. pose(H4:=H3 x).\n      destruct H4. simpl in H4. rewrite H1 in H4. pose(H6:=H4 H2). destruct H6.\n    * intros n1 H1 H2. inversion H2. simpl in H0. rewrite H1 in H0. inversion H.\n      pose(H4:=H3 x). destruct H4. simpl in H4. rewrite H1 in H4.\n      apply H4. apply inMultiset_intro. simpl. rewrite H1. exact H0.\n  - intros H1. simpl in H1.\n    case_eq(T_eq_dec x t).\n    * intros e H2. simpl. rewrite H2. omega.\n    * intros n1 H2. rewrite H2 in H1. simpl. rewrite H2. inversion H. pose(H3:=H0 x).\n      destruct H3. simpl in H4. rewrite H2 in H4. rewrite H1 in H4. apply H4. reflexivity.\nQed.\n\n\n(** Nous n'avons pas réussi à démontrer que add preserve les propriétés de \n    bonne formation ... **)\nTheorem add_wf : forall (x:T) (n:nat) (l: multiset), wf l -> wf (add x n l).\nProof.\nintros x n l H. inversion H. pose(H1:=H0 x). destruct H1.\ninduction l ; simpl.\n+ case_eq(le_lt_dec n 0).\n  - intros l H3. assumption.\n  - intros l H3. apply wf_intro. intros x0. split.\n    * simpl.\n      case_eq(T_eq_dec x0 x) ; intros e H4 H5 ; inversion H5 ; simpl in H6.\n      ** discriminate H6.\n      ** rewrite H4 in H6. discriminate H6.\n    * simpl.\n      case_eq(T_eq_dec x0 x).\n      ** intros e H4. omega.\n      ** intros n0 H4 H5. discriminate H5.\n+ case_eq(le_lt_dec n 0) ;intros l0 H3.\n  - assumption.\n  - destruct a.\n    case_eq(T_eq_dec x t).\n    * intros e H4. apply wf_plus_n. assumption.\n    * intros n1 H4. apply wf_intro. intros x0. \n      split.\n      ** intros H5. inversion H5. simpl in H6. \n         case_eq(T_eq_dec x0 t).\n         *** intros e H7.\n             rewrite H7 in H6. rewrite e in H6. simpl in H2. rewrite H4 in H2. inversion H5.\nAdmitted.\n\n(** Nous n'avons pas réussi à démontrer que union preserve les propriétés de \n    bonne formation ... **)\nTheorem union_wf : forall (l: multiset) (l': multiset), wf l -> wf l' -> wf (union l l').\nProof.\nintros l l' well_formed_proof_of_l well_formed_proof_of_l'.\napply wf_intro.\nintros x.\ndestruct well_formed_proof_of_l.\npose (H1 := H x).\ndestruct H1.\ndestruct well_formed_proof_of_l'.\npose (H3 := H2 x).\ndestruct H3.\nsplit.\nAdmitted.\n\n(** Nous n'avons pas réussi à démontrer que removeOne preserve les propriétés de \n    bonne formation ... **)\nTheorem removeOne_wf: forall (x: T) (l: multiset), wf l -> wf (removeOne x l).\nProof.\nintros x l H.\ninduction l.\n+ simpl. assumption.\n+ destruct a. simpl.\n  case_eq(T_eq_dec x t).\n  - intros e H1.\n    case_eq(le_lt_dec n 1).\n    * intros l0 H2. apply wf_intro. intros x0.\n      split.\n      ** intros H3. inversion H.\nAdmitted.\n\n(** Nous n'avons pas réussi à démontrer que removeAll preserve les propriétés de \n    bonne formation ... **)\nTheorem removeAll_wf: forall (x: T) (l: multiset), wf l -> wf (removeAll x l).\nProof.\nintros x l H.\ninduction l.\n+ simpl. assumption.\n+ destruct a. simpl.\n  case_eq(T_eq_dec x t).\n  - intros e H1. inversion H.\n    pose(H':=H0 x). destruct H'. apply wf_intro. intros x0. split.\nAdmitted.\n\n\n(*****************)\n(** Question 3. **)\n(*****************)\n\nTheorem proof_1_1 : forall (x : T), ~InMultiset x empty.\nProof.\n intros x. unfold not. intros H. inversion H. discriminate H0.\nQed.\n\nTheorem proof_2_1 : forall x y , InMultiset y (singleton x) <-> x = y.\nProof.\n intros x y. unfold iff.\n split ; intros H.\n + inversion H. simpl in H0.\n   case_eq (T_eq_dec y x).\n   - intros e H2. rewrite e. reflexivity.\n   - intros n H2. rewrite H2 in H0. discriminate H0.\n + apply inMultiset_intro. simpl.\n   case_eq (T_eq_dec y x).\n   - intros e H2. reflexivity.\n   - intros n. symmetry in H. contradiction.\nQed.\n\nTheorem proof_3_1 :forall x, multiplicity x (singleton x) = 1.\nProof.\n intros x. unfold singleton. simpl.\n destruct (T_eq_dec x x).\n + reflexivity.\n + contradiction.\nQed.\n\nTheorem proof_4_1 : forall x s, wf s -> (member x s = true <-> InMultiset x s).\nProof.\nintros x s well_formed_proof_of_l. unfold iff.\nsplit ; intros H.\n+ destruct well_formed_proof_of_l. pose (H1:=H0 x). destruct H1. apply inMultiset_intro. exact H.\n+ inversion H. exact H0.\nQed.\n\nTheorem proof_5_1 : forall x n s, n > 0 -> InMultiset x (add x n s).\nProof.\n intros x n s H. apply inMultiset_intro.\n induction s.\n + simpl.\n   case_eq (le_lt_dec n 0) ; intros l H2.\n   - apply (gt_not_le n 0) in H. contradiction.\n   - simpl.\n     destruct (T_eq_dec x x).\n     * reflexivity.\n     * unfold not in n0. destruct n0. reflexivity.\n + destruct a.\n   case_eq (T_eq_dec t x).\n   - intros e H1. rewrite e. simpl.\n     case_eq (le_lt_dec n 0).\n     * intros l. apply (gt_not_le n 0) in H. contradiction.\n     * intros l H2. destruct (T_eq_dec x x) ; simpl.\n       ** destruct (T_eq_dec x x).\n          *** reflexivity.\n          *** contradiction.\n       ** destruct (T_eq_dec x x).\n          *** reflexivity.\n          *** exact IHs.\n   - intros n1 H1. simpl.\n     case_eq (le_lt_dec n 0).\n     * intros l. apply (gt_not_le n 0) in H. contradiction.\n     * intros l H2.\n       case_eq (T_eq_dec x t).\n       ** intros e. pose (f:=e). symmetry in f. contradiction.\n       ** intros n2 H3. simpl.\n          destruct (T_eq_dec x t).\n          *** reflexivity.\n          *** exact IHs.\nQed.\n\nTheorem proof_6_1 : forall x n y s, x <> y -> (InMultiset y (add x n s) <-> InMultiset y s).\nProof.\n intros x n y s H. unfold iff.\n split.\n + intros H2. inversion H2. apply inMultiset_intro.\n   induction s.\n   - simpl. simpl in H0. case_eq (le_lt_dec n 0) ; intros l H1 ; rewrite H1 in H0 ; simpl in H0.\n     * discriminate H0.\n     * case_eq (T_eq_dec y x).\n       ** intros e H3. pose(e':=e). symmetry in e'. contradiction.\n       ** intros n0 H4. rewrite H4 in H0. discriminate H0.\n   - destruct a.\n     case_eq (T_eq_dec t y).\n     * intros e H3. rewrite e. simpl.\n       case_eq (T_eq_dec y y).\n       ** reflexivity.\n       ** contradiction.\n     * intros n1 H3. simpl.\n       case_eq (T_eq_dec y t).\n       ** intros e. pose(e':=e). symmetry in e'. contradiction.\n       ** intros n2 H4. simpl in H2.\n          case_eq (le_lt_dec n 0); intros l H5 ; rewrite H5 in H2.\n          *** inversion H2. simpl in H1. rewrite H4 in H1. assumption.\n          *** case_eq (T_eq_dec x t).\n              **** intros e H6. rewrite H6 in H2. rewrite e in H0. simpl in H0. \n                   rewrite H5 in H0. \n                   case_eq (T_eq_dec t t);intros e0 H7 ;rewrite H7 in H0; simpl in H0 ;rewrite H4 in H0.\n                   ***** assumption.\n                   ***** apply IHs.\n                         ****** apply inMultiset_intro. rewrite e. exact H0.\n                         ****** rewrite e. exact H0.\n              **** intros n3 H6. rewrite H6 in H2. simpl in H0. rewrite H5 in H0.\n                   rewrite H6 in H0. simpl in H0. rewrite H4 in H0. apply IHs.\n                   ***** apply inMultiset_intro.\n                         exact H0.\n                   ***** exact H0.\n + intros H1. inversion H1. apply inMultiset_intro.\n   induction s.\n   - simpl.\n     case_eq (le_lt_dec n 0) ; intros l H2.\n     * exact H0.\n     * simpl.\n       case_eq (T_eq_dec y x).\n       ** intros e H3. reflexivity.\n       ** simpl in H0. discriminate H0.\n   - destruct a.\n     case_eq (T_eq_dec t x).\n     * intros e H2. rewrite e. simpl.\n       case_eq(le_lt_dec n 0).\n       ** intros l H3. simpl.\n          case_eq (T_eq_dec y x).\n          *** intros e0. pose(e':=e0). symmetry in e'. contradiction.\n          *** intros n1 H4. simpl in H0. case_eq (T_eq_dec y t).\n              **** intros e0 H5. rewrite e0 in H. pose(e':=e). symmetry in e'. contradiction.\n              **** intros n2 H5. rewrite H5 in H0. assumption.\n       ** intros l H3. \n          case_eq (T_eq_dec x x).\n          *** intros e0 H4. simpl.\n              case_eq(T_eq_dec y x).\n              **** intros e1 H5. reflexivity.\n              **** intros n1 H5. simpl in H0.\n                   case_eq (T_eq_dec y t) ;  intros e1 H6.\n                   ***** rewrite e1 in H. pose(e':=e). symmetry in e'. contradiction.\n                   ***** rewrite H6 in H0. assumption.\n          *** contradiction.\n     * intros n1 H2. simpl.\n       case_eq(le_lt_dec n 0) ; intros l H3.\n       ** simpl.\n          case_eq(T_eq_dec y t) ; intros e H4.\n          *** reflexivity.\n          *** simpl in H0. rewrite H4 in H0. assumption.\n       ** case_eq(T_eq_dec x t) ; intros n2 H4 ; simpl.\n          *** case_eq(T_eq_dec y t) ; intros e0 H5.\n              **** reflexivity.\n              **** simpl in H0. rewrite H5 in H0. assumption.\n          *** case_eq(T_eq_dec y t).\n              **** intros e H5. reflexivity.\n              **** intros n3 H5. apply IHs.\n                   apply inMultiset_intro.\n                   ***** simpl in H0. rewrite H5 in H0. assumption.\n                   ***** simpl in H0. rewrite H5 in H0. assumption.\nQed.\n\n(** Un preuve intermédiaire ... **)\nLemma proof_7_1_1: forall x s, multiplicity x s <> 0 -> InMultiset x s.\nProof.\nintros x s. intros H. apply inMultiset_intro.\ninduction s.\n+ simpl in H. omega.\n+ destruct a.\n  case_eq (T_eq_dec x t) ; intros e H1.\n  - rewrite e in H. simpl in H.\n    case_eq (T_eq_dec t t).\n    * intros e0 H2. rewrite e. simpl. rewrite H2. reflexivity.\n    * intros n0. unfold not in n0. intros H2. rewrite e in H1. contradiction.\n  - simpl. rewrite H1. simpl in H. rewrite H1 in H. apply IHs. assumption.\nQed.\n\nTheorem proof_7_1_2 : forall x s, wf s -> (multiplicity x s = 0 <-> ~InMultiset x s).\nProof.\nintros x s well_formed_proof_of_l. unfold iff. \nsplit.\n+ unfold not. intros H1 H2. destruct H2. destruct well_formed_proof_of_l. \n  pose (H2:= H0 x). destruct H2. apply H3 in H. rewrite H1 in H. omega.\n+ intros H2. unfold not in H2. destruct well_formed_proof_of_l. pose (H3:= H x). destruct H3.\n  case_eq (Nat.eq_dec (multiplicity x s) 0) ; intros e H3.\n  - exact e.\n  - pose (n':=e). apply proof_7_1_1 in n'. pose (H4:=H2 n'). destruct H2.\nQed.\n\n\nTheorem proof_8_1 : forall x n s, multiplicity x (add x n s) = n + (multiplicity x s).\nProof.\nintros x n s.\ninduction s.\n+ simpl.\n  case_eq(le_lt_dec n 0) ; intros l H1 ; simpl.\n  - omega.\n  - case_eq(T_eq_dec x x).\n    * intros e H2. omega.\n    * contradiction.\n+ destruct a.\n  case_eq (T_eq_dec x t) ; intros e H1.\n  - rewrite e. simpl.\n    case_eq (le_lt_dec n 0) ;intros l H2.\n    * simpl. omega.\n    * case_eq (T_eq_dec t t).\n      ** intros e0 H3. simpl. rewrite H3. omega.\n      ** contradiction.\n  - simpl.\n    case_eq (le_lt_dec n 0) ; intros l H2.\n    * simpl. omega.\n    * rewrite H1. simpl. rewrite H1. assumption.\nQed.\n\n(** Nous n'avons pas réussi à démontrer cette preuve ... **)\nTheorem proof_9_1 : forall x n y s, x <> y -> wf s ->multiplicity y (add x n s) = multiplicity y s.\nProof.\nintros x n y s H H2. inversion H2. pose(H':=H0 x). destruct H'.\ninduction s.\n+ simpl.\n  case_eq (le_lt_dec n 0) ; intros l H4 ; simpl.\n  - reflexivity.\n  - case_eq(T_eq_dec y x).\n    * intros e. pose(e':=e). symmetry in e'. contradiction.\n    * intros n0 H5. reflexivity.\n+ destruct a. simpl.\n  case_eq(le_lt_dec n 0).\n  - intros l H4. simpl. omega.\n  - intros l H4.\n    case_eq(T_eq_dec x t) ; intros e H5 ; simpl.\n    * case_eq(T_eq_dec y t).\n      ** intros e0. rewrite e0 in H. contradiction.\n      ** intros n1 H6. reflexivity.\n    * case_eq(T_eq_dec y t).\n      ** reflexivity.\n      ** intros n2 H6. apply IHs. apply wf_intro. intros x0.\n         split. simpl in H1. rewrite H5 in H1. intros H7. inversion H7.\nAdmitted.\n\n(** Nous n'avons pas réussi à démontrer cette preuve ... **)\nTheorem proof_10_1 : forall s t x, wf s -> wf t ->(InMultiset x (union s t) <-> InMultiset x s \\/ InMultiset x t).\nProof.\nintros s t x H1 H2. pose(H':=union_wf s t H1 H2). unfold iff.\nsplit.\n+ intros H3. inversion H3. inversion H1. pose (H4:=H0 x). destruct H4.\nAdmitted.\n\n\n(*****************)\n(** Question 4. **)\n(*****************)\n\nTheorem proof_11_1 : forall x, multiplicity x (removeOne x (singleton x)) = 0.\nProof.\nintros x. simpl.\ncase_eq(T_eq_dec x x ).\n+ intros e H. simpl. reflexivity.\n+ contradiction.\nQed.\n\nTheorem proof_12_1 : forall x, multiplicity x (removeAll x (singleton x)) = 0.\nProof.\nintros x. simpl.\ncase_eq(T_eq_dec x x ).\n+ intros e H. simpl. reflexivity.\n+ contradiction.\nQed.\n\nTheorem proof_13_1 : forall x l n, multiplicity x l = n -> n > 1 -> multiplicity x (removeOne x l) = n-1.\nProof.\nintros x l n H1 H2.\ninduction l.\n+ simpl. simpl in H1. omega.\n+ destruct a. simpl.\n  case_eq(T_eq_dec x t) ;intros e H3.\n  - case_eq(le_lt_dec n0 1) ; intros l0 H4.\n    * rewrite e in H1. simpl in H1.\n      case_eq (T_eq_dec t t).\n      ** intros e0 H5. rewrite H5 in H1. omega.\n      ** contradiction.\n    *  simpl. rewrite H3. rewrite e in H1. simpl in H1.\n      case_eq(T_eq_dec t t).\n      ** intros e0 H5. rewrite H5 in H1. rewrite H1. reflexivity.\n      ** contradiction.\n  - simpl. rewrite H3. apply IHl. simpl in H1. rewrite H3 in H1. assumption.\nQed.\n\nTheorem proof_14_1 : forall x l, wf l -> ~(InMultiset x (removeAll x l)).\nProof.\nintros x l H1. unfold not. intros H2. inversion H2. inversion H1.\npose(H':=H0 x). destruct H'. pose(H5:=H3 H2). destruct H5.\nQed.\n\nTheorem proof_15_1 : forall x l, multiplicity x l > 1 -> InMultiset x (removeOne x l).\nProof.\nintros x l H1. apply inMultiset_intro.\ninduction l.\n+ simpl in H1. omega.\n+ destruct a. simpl.\n  case_eq(T_eq_dec x t) ;intros e H3.\n  - case_eq(le_lt_dec n 1) ; intros l0 H4.\n    * rewrite e in H1. simpl in H1.\n      case_eq (T_eq_dec t t).\n      ** intros e0 H5. rewrite H5 in H1. omega.\n      ** contradiction.\n    * simpl. rewrite H3. reflexivity.\n  - simpl. rewrite H3. apply IHl. simpl in H1. rewrite H3 in H1. assumption.\nQed.\n\n\n(******************************************************************************)\n(**************2.2 Implantation Fonctionnelle des multi-ensembles**************)\n(******************************************************************************)\n(****** PREUVES RÉUSSIES : 16 *************************************************)\n(****** PREUVES ADMISES :   0 *************************************************)\n(******************************************************************************)\n\n(****************)\n(** Question 1 **)\n(****************)\n\nDefinition multiset_2 := T -> nat.\nPrint multiset_2.\n\n(** empty_2 est le multiset vide. **)\nDefinition empty_2 : multiset_2 := (fun a:T => 0).\nCheck empty_2.\n(** TEST\n  Eval compute in empty_2.\n**)\n\n\n(** singleton_2 x crée le multi-ensemble qui ne contient que x en un seul exemplaire **)\nDefinition singleton_2 (x:T) : multiset_2 := fun a:T => \n  match T_eq_dec a x with\n  | left _ => 1\n  | right _ => 0\n  end.\nCheck singleton_2.\n(** TEST\n  Eval compute in ((singleton_2 2) 3).\n  Eval compute in ((singleton_2 2) 2).\n**)\n\n\n(** add_2 x n s ajoute, au multi-ensemble s, n occurrences de l’élément x dans s **)\nDefinition add_2 (x:T) (n:nat) (s:multiset_2) : multiset_2 := fun a:T => \n  match T_eq_dec a x with\n  | left _ => s x + n\n  | right _ => s a\n  end.\nCheck add_2.\n(** TEST\n  Eval compute in ((add_2 3 4 (add_2 2 3 (singleton_2 1))) 3).\n  Eval compute in ((add_2 3 4 (add_2 2 3 (singleton_2 1))) 3).\n  Eval compute in ((add_2 3 4 (add_2 2 3 (singleton_2 1))) 5).\n  Eval compute in ((add_2 3 4 (add_2 2 3 (empty_2))) 1).\n**)\n\n\n(** member_2 x s retourne la valeur true si x a au moins une occurrence dans s, \n    false sinon. **)\nDefinition member_2 (x:T) (s:multiset_2) : bool := \n  match Nat.eq_dec (s x) 0 with\n  | left _ => false\n  | right _ => true\n  end.\nCheck member_2.\n(** TESTS\n  Eval compute in (member_2 2 (empty_2)).\n  Eval compute in (member_2 2 (singleton_2 2)).\n  Eval compute in (member_2 3 (singleton_2 2)).\n  Eval compute in (member_2 3 (add_2 3 0 empty_2)).\n  Eval compute in (member_2 3 (add_2 3 1 empty_2)).\n**)\n\n\n(** union_2 fait l’union de deux multi-ensembles. **)\nDefinition union_2 (s1:multiset_2) (s2:multiset_2) : multiset_2 := (fun a:T => s1 a + s2 a).\nCheck union_2.\n(** TESTS\n  Eval compute in ((union_2 (add_2 2 3 empty_2) (add_2 2 4 empty_2)) 2).\n  Eval compute in ((union_2 (add_2 2 3 (add_2 4 5 empty_2)) (add_2 2 3 empty_2)) 4).\n  Eval compute in ((union_2 (add_2 2 3 empty_2) empty_2) 2).\n  Eval compute in ((union_2 empty_2 empty_2) 1).\n**)\n\n\n(** multiplicity_2 x s retourne le nombre d’occurrences de x dans s **)\nDefinition multiplicity_2 (x:T) (s:multiset_2) : nat := s x.\nCheck multiplicity_2.\n(** TESTS\n  Eval compute in (multiplicity_2 2 (add_2 2 7 empty_2)).\n  Eval compute in (multiplicity_2 3 (add_2 2 7 empty_2)).\n  Eval compute in (multiplicity_2 3 empty_2).\n**)\n\n\n(** removeOne_2 x s retourne le multi-ensemble s avec une occurrence de moins pour x.\n    Si s ne contient pas  x, le multi-ensemble résultat est s. **)\nDefinition removeOne_2 (x:T) (s:multiset_2) : multiset_2 := fun a:T => \n  match T_eq_dec a x with\n  | left _ => if member_2 x s then s x - 1 else 0\n  | right _ => s a\n  end.\nCheck removeOne_2.\n(** TESTS\n  Eval compute in ((removeOne_2 2 (add_2 2 7 empty_2)) 2).\n  Eval compute in ((removeOne_2 2 (add_2 2 2 (add_2 3 5 empty_2))) 2).\n  Eval compute in ((removeOne_2 2 (add_2 6 5 (add_2 2 2 (add_2 3 5 empty_2)))) 2).\n  Eval compute in ((removeOne_2 2 (add_2 2 1 (add_2 3 5 empty_2))) 2).\n  Eval compute in ((removeOne_2 2 (add_2 6 5 (add_2 2 1 (add_2 3 5 empty_2)))) 2).\n  Eval compute in ((removeOne_2 3 (add_2 2 7 empty_2)) 3).\n  Eval compute in ((removeOne_2 3 empty_2) 3).\n**)\n\n\n(** removeAll_2 x s retourne le mult-ensemble s o`u x n’apparait plus. \n    Si s ne contient pas x, le multiensemble r´esultat est s. **)\nDefinition removeAll_2 (x:T) (s:multiset_2) : multiset_2 := fun a:T => \n  match T_eq_dec a x with\n  | left _ => 0\n  | right _ => s a\n  end.\nCheck removeAll_2.\n(** TESTS\n  Eval compute in ((removeAll_2 2 (add_2 2 7 empty_2)) 2).\n  Eval compute in ((removeAll_2 2 (add_2 2 2 (add_2 3 5 empty_2))) 2).\n  Eval compute in ((removeAll_2 2 (add_2 6 5 (add_2 2 2 (add_2 3 5 empty_2)))) 2).\n  Eval compute in ((removeAll_2 2 (add_2 2 1 (add_2 3 5 empty_2))) 2).\n  Eval compute in ((removeAll_2 2 (add_2 6 5 (add_2 2 1 (add_2 3 5 empty_2)))) 2).\n  Eval compute in ((removeAll_2 3 (add_2 2 7 empty_2)) 2).\n  Eval compute in ((removeAll_2 3 empty_2) 3).\n**)\n\n(****************)\n(** Question 2 **)\n(****************)\n\n(** Ce prédicat spécifie qu’un élément appartient à un multi-ensemble dès lors \n    qu’il en existe une occurrence **)\nInductive InMultiset_2 (x:T) (l:multiset_2) : Prop := \n  | inMultiset_2_intro : member_2 x l = true -> InMultiset_2 x l.\n\n\n(****************)\n(** Question 3 **)\n(****************)\n\nTheorem proof_1_2 : forall (x : T), ~InMultiset_2 x empty_2.\nProof.\n intros x. unfold not. intros H. inversion H. discriminate H0.\nQed.\n\nTheorem proof_2_2 : forall x y , InMultiset_2 y (singleton_2 x) <-> x = y.\nProof.\n intros x y. unfold iff.\n split.\n + intros H. inversion H. unfold member_2 in H0. unfold singleton_2 in H0.\n   case_eq (T_eq_dec y x) ; intros H1 H2.\n   - rewrite H1 in H0. destruct H0. symmetry. assumption.\n   - rewrite H2 in H0. simpl in H0. discriminate H0.\n + intros H0. apply inMultiset_2_intro. unfold member_2. unfold singleton_2. rewrite H0.\n   destruct (T_eq_dec y y).\n   - destruct (Nat.eq_dec 1 0). discriminate e0. reflexivity.\n   - destruct (Nat.eq_dec 0 0). contradiction. reflexivity.\nQed.\n\nTheorem proof_3_2 :forall x, multiplicity_2 x (singleton_2 x) = 1.\nProof.\n intros x. unfold multiplicity_2. unfold singleton_2.\n case_eq (T_eq_dec x x).\n + reflexivity.\n + intros n H. contradiction.\nQed.\n\nTheorem proof_4_2 : forall x s, member_2 x s = true <-> InMultiset_2 x s.\nProof.\nintros x s. unfold iff.\nsplit ; intros H.\n+ apply inMultiset_2_intro. exact H.\n+ inversion H. exact H0.\nQed.\n\nTheorem proof_5_2 : forall x n s, n > 0 -> InMultiset_2 x (add_2 x n s).\nProof.\nintros x n s H. apply inMultiset_2_intro. unfold member_2. unfold add_2.\ncase_eq (T_eq_dec x x) ; intros e H1.\n+ case_eq (Nat.eq_dec (s x + n) 0). \n  - intros e0 H2. omega.\n  - reflexivity.\n+ contradiction e. reflexivity.\nQed.\n\nTheorem proof_6_2 : forall x n y s, x <> y -> (InMultiset_2 y (add_2 x n s) <-> InMultiset_2 y s).\nProof.\n intros x n y s H. unfold iff.\n split ; intros H1 ; inversion H1.\n + apply inMultiset_2_intro.  unfold member_2. unfold member_2 in H0.\n   case_eq (Nat.eq_dec (s y) 0).\n   - intros e H3. unfold add_2 in H0.\n     case_eq (T_eq_dec y x).\n     * intros e0. pose(e0':=e0).  symmetry in e0'. contradiction.\n     * intros n0 H4. rewrite H4 in H0. rewrite e in H0. simpl in H0. discriminate H0.\n   - intros n0 H3. reflexivity.\n + unfold member_2 in H0. apply inMultiset_2_intro. unfold member_2. unfold add_2.\n     case_eq (T_eq_dec y x ) ; intros e H2.\n   - pose(e0':=e). symmetry in e0'. contradiction.\n   - exact H0.\nQed.\n\nLemma proof_7_2_1: forall x s, s x <> 0 -> InMultiset_2 x s.\nProof.\nintros x s H. apply inMultiset_2_intro. unfold member_2.\ncase_eq (Nat.eq_dec (s x) 0) ; intros e H1.\n+ contradiction.\n+ reflexivity.\nQed.\n\nTheorem proof_7_2_2 : forall x s, multiplicity_2 x s = 0 <-> ~InMultiset_2 x s.\nProof.\n intros x s. unfold iff.\n split.\n + intros H. unfold multiplicity_2 in H. unfold not. intros H2. inversion H2. \n   unfold member_2 in H0. rewrite H in H0. simpl in H0. discriminate H0.\n + unfold not. intros H. unfold multiplicity_2.\n   case_eq (Nat.eq_dec (s x) 0) ; intros e H1.\n   - exact e.\n   - pose (n':=e). apply proof_7_2_1 in n'. pose (H2:=H n'). destruct H2.\nQed.\n\n\nTheorem proof_8_2 : forall x n s, multiplicity_2 x (add_2 x n s) = n + (multiplicity_2 x s).\nProof.\nintros x n s. unfold multiplicity_2. unfold add_2.\ndestruct (T_eq_dec x x).\n+ omega.\n+ contradiction.\nQed.\n\nTheorem proof_9_2 : forall x n y s, x <> y -> multiplicity_2 y (add_2 x n s) = multiplicity_2 y s.\nProof.\nintros x n y s H. unfold multiplicity_2. unfold add_2.\ndestruct (T_eq_dec y x).\n+ pose(e0':=e). symmetry in e0'. contradiction.\n+ reflexivity.\nQed.\n\nTheorem proof_10_2 : forall s t x, (InMultiset_2 x (union_2 s t) <-> InMultiset_2 x s \\/ InMultiset_2 x t).\nProof.\n intros s t x. unfold iff.\n split.\n + intros H. inversion H. unfold member_2 in H0. unfold union_2 in H0.\n   case_eq (Nat.eq_dec (s x) 0).\n   - intros e H1. right. rewrite e in H0. simpl in H0.\n     case_eq (Nat.eq_dec (t x) 0) ;intros e0 H2.\n     * rewrite H2 in H0. discriminate H0.\n     * apply inMultiset_2_intro. unfold member_2. rewrite H2. reflexivity.\n   - case_eq (Nat.eq_dec (s x + t x) 0) ;intros e H1 ;rewrite H1 in H0.\n     * discriminate H0.\n     * intros n0 H2. left. apply inMultiset_2_intro. unfold member_2. rewrite H2. reflexivity.\n + intros H. destruct H ; inversion H ; unfold member_2 in H0 ; \n   apply inMultiset_2_intro ; unfold member_2 ; unfold union_2.\n   - case_eq (Nat.eq_dec (s x) 0) ;intros n H1.\n     * rewrite n in H0. simpl in H0.  discriminate H0.\n     * case_eq (Nat.eq_dec (s x + t x) 0).\n       ** intros e. omega. \n       ** intros n0 H2. reflexivity.\n   - case_eq (Nat.eq_dec (t x) 0) ; intros n H1.\n     * rewrite n in H0. simpl in H0. discriminate H0.\n     * case_eq (Nat.eq_dec (s x + t x) 0). \n       ** intros e. omega.\n       ** intros n0 H2. reflexivity.\nQed.\n\nTheorem proof_11_2 : forall x, multiplicity_2 x (removeOne_2 x (singleton_2 x)) = 0.\nProof.\nintros x. unfold multiplicity_2. unfold removeOne_2.\ncase_eq(T_eq_dec x x).\n+ intros H. unfold member_2.\n  case_eq(Nat.eq_dec (singleton_2 x x) 0) ; intros n H1.\n  - reflexivity.\n  - unfold singleton_2 in n. unfold singleton_2.\n    case_eq(T_eq_dec x x).\n    * intros e H2. omega.\n    * contradiction.\n+ contradiction.\nQed.\n\nTheorem proof_12_2 : forall x, multiplicity_2 x (removeAll_2 x (singleton_2 x)) = 0.\nProof.\nintros x. unfold multiplicity_2. unfold removeAll_2.\ndestruct (T_eq_dec x x).\n+ reflexivity.\n+ contradiction.\nQed.\n\nTheorem proof_13_2 : forall x l n, multiplicity_2 x l = n -> n > 1 -> multiplicity_2 x (removeOne_2 x l) = n-1.\nProof.\nintros x l n H1 H2. unfold multiplicity_2. unfold removeOne_2.\ndestruct (T_eq_dec x x).\n+ unfold member_2.\n  case_eq(Nat.eq_dec (l x) 0) ; intros e0 H3 ;unfold multiplicity_2 in H1.\n  - rewrite e0 in H1. omega.\n  - rewrite H1. reflexivity.\n+ contradiction.\nQed.\n\nTheorem proof_14_2 : forall x l, ~(InMultiset_2 x (removeAll_2 x l)).\nProof.\nintros x l. unfold not. intros H. inversion H. unfold member_2 in H0.\ncase_eq(Nat.eq_dec (removeAll_2 x l x) 0) ; intros n H1.\n+ rewrite H1 in H0. discriminate H0.\n+ unfold removeAll_2 in n.\n  case_eq(T_eq_dec x x).\n  - intros e H2. pose(n':=n). rewrite H2 in n'. contradiction.\n  - contradiction.\nQed.\n\nTheorem proof_15_2 : forall x l, multiplicity_2 x l > 1 -> InMultiset_2 x (removeOne_2 x l).\nProof.\nintros x l H. apply inMultiset_2_intro. unfold member_2. unfold removeOne_2.\ncase_eq(T_eq_dec x x).\n+ intros e H1. unfold member_2.\n  case(Nat.eq_dec (l x) 0) ; intros H2.\n  - unfold multiplicity_2 in H. rewrite H2 in H. omega.\n  - case_eq(Nat.eq_dec (l x - 1) 0) ; intros e0 H3.\n    * unfold multiplicity_2 in H. omega.\n    * reflexivity.\n+ contradiction.\nQed.\n", "meta": {"author": "AdrienBlassiau", "repo": "PROJET_COQ", "sha": "db835176af684e3fbd3182a4859776029d9c1dba", "save_path": "github-repos/coq/AdrienBlassiau-PROJET_COQ", "path": "github-repos/coq/AdrienBlassiau-PROJET_COQ/PROJET_COQ-db835176af684e3fbd3182a4859776029d9c1dba/DM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.8652240964782012, "lm_q1q2_score": 0.7371301030820894}}
{"text": "From LF Require Export Induction.\n\nModule NatList.\n\nInductive natprod : Type :=\n  | pair (n1 n2 : nat).\n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition fst (p : natprod) : nat :=\n  match p with\n  | (x, _) => x\n  end.\n\nDefinition snd (p : natprod) : nat :=\n  match p with\n  | (_, x) => x\n  end.\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x, y) => (y, x)\n  end.\n\nExample fst_test: (fst (3, 5)) = 3.\nProof. simpl. reflexivity. Qed.\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n, m) = (fst (n, m), snd (n, m)).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as [n m].\n  simpl.\n  reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\n\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(* Exercise *)\n\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(* To introduce the concept of a list, one may generalize the idea of pairs in\n * which a list is either the empty list or a pair of an element with another\n * list (which could be empty, of course).\n *)\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\n(* A list with 3 elements: *)\nDefinition my_list := cons 1 (cons 2 (cons 3 nil)).\n\n(* Lower `level`s bind tighter. *)\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => []\n  | S count' => n :: repeat n count'\n  end.\n\nFixpoint length (l : natlist) : nat :=\n  match l with\n  | [] => 0\n  | h :: t => 1 + length t\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | [] => l2\n  | h :: t => h :: app t l2\n  end.\n\nNotation \"x ++ y\" := (app x y) (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: [] ++ [4; 5] = [4; 5].\nProof. reflexivity. Qed.\nExample test_app3: [1; 2; 3] ++ [] = [1; 2; 3].\nProof. reflexivity. Qed.\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n  | [] => default\n  | h :: t => h\n  end.\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | [] => []\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\nFixpoint nonzeros (l : natlist) : natlist :=\n  match l with\n  | [] => []\n  | h :: t => match h with\n              | 0 => nonzeros t\n              | n => n :: nonzeros t\n              end\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  | [] => []\n  | h :: t => if odd h\n                then h :: oddmembers t\n                else oddmembers t\n  end.\n\nExample test_oddmembers: 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: 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\n(* Exercise *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | [], l2 => l2\n  | l1, [] => l1\n  | h1 :: t1, h2 :: t2 => h1 :: h2 :: alternate t1 t2\n  end.\n\n(******************************************************************************)\n\nDefinition bag := natlist.\n\nFixpoint count (v : nat) (s : bag) : nat :=\n  match s with\n  | [] => 0\n  | h :: t => let r := count v t in\n                if h =? v then 1 + r else r\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\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.\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 (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\nFixpoint member' (v : nat) (s : bag) : bool :=\n  match s with\n  | [] => false\n  | h :: t => if h =? v then true else member' v t\n  end.\n\nExample test_member'1: member' 1 [1; 4; 1] = true.\nProof. reflexivity. Qed.\nExample test_member'2: member' 2 [1; 4; 1] = false.\nProof. reflexivity. Qed.\n\n(******************************************************************************)\n\n(* Exercises *)\n\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with\n  | [] => []\n  | h :: t => if h =? v\n                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. reflexivity. Qed.\nExample test_remove_one2:\n  count 5 (remove_one 5 [2; 1; 4; 1]) = 0.\nProof. reflexivity. Qed.\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  | h :: t => let r := remove_all v t in\n                if h =? v then r else h :: r\n  end.\n\n\nExample test_remove_all1:\n  count 5 (remove_all 5 [2; 1; 5; 4; 1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all2:\n  count 5 (remove_all 5 [2; 1; 4; 1]) = 0.\nProof. reflexivity. Qed.\nExample test_remove_all3:\n  count 4 (remove_all 5 [2; 1; 4; 5; 1; 4]) = 2.\nProof. reflexivity. Qed.\nExample test_remove_all4:\n  count 5 (remove_all 5 [2; 1; 5; 4; 5; 1; 4; 5; 1; 4]) = 0.\nProof. reflexivity. Qed.\n\nFixpoint subset (s1 s2 : bag) : bool :=\n  match s1 with\n  | [] => true\n  | x :: s1' => member x s2 && subset s1' (remove_one x 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\n(* Exercise *)\n\nTheorem bag_add_theorem : forall (v : nat) (b : bag),\n  count v (add v b) = S (count v b).\nProof.\n  intros v b.\n  simpl.\n  rewrite eqb_refl.\n  reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Example of a proof on a list that can be solved using just simplification. *)\nTheorem nil_app : forall l : natlist,\n  [] ++ l = l.\nProof. simpl. reflexivity. Qed.\n\n(* Simplification was enough since `[]` was present in one of the app's pattern\n * match branches.\n *)\n\nTheorem tl_length_pred : forall l : natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l.\n  destruct l as [| n l'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* Most interesting proofs on lists, however, can only be solved using\n * induction, just like with natural numbers.\n *)\n\n(* Using induction to prove facts about lists is pretty much the same as that of\n * numbers.\n *\n * Inductively defined types declare a set of constructors, which are used to\n * build a value of such type. Notice that, if one applies some constructor to a\n * value of that constructor's type, one then has an inductively defined type.\n *\n * This fact raises a new way of thinking about inductively defined types. In\n * the cases where the constructor is applied to another value of such type,\n * the “inner” value can always be thought as of a “smaller” value if compared\n * to the “outer” value.\n *\n * For example, in the list `cons 1 (cons 2 nil)`, the “inner” list,\n * `cons 2 nil` is smaller than the “outer” list.\n *\n * Hence, wanting to prove some proposition `P` for all lists using induction,\n * one must:\n *\n *   - Show that `P` is valid for `nil`;\n *   - Show that `P` is valid for `cons n l'`, assuming that `P` holds for the\n *     smaller list `l'`.\n *)\n\nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3.\n  induction l1 as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nFixpoint rev (l : natlist) : natlist :=\n  match l with\n  | [] => []\n  | h :: l' => rev l' ++ [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\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros l1 l2.\n  induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l.\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl.\n    (* `rev l` is itself a list, so we are able to use the above lemma. *)\n    rewrite -> app_length.\n    simpl. rewrite -> IHl'.\n    rewrite add_comm. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercises *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l.\n  (* Since the definition of `app` pattern matches the first operator, this\n   * cannot be trivially proven using simplification. *)\n  induction l as [| n l' IHl'].\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 l1 l2.\n  (* `l1` in `app` is arbitrary, so induction is one's last resort after\n   * unsuccessful simplification or case analysis. *)\n  induction l1 as [| n l1' 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  intros l.\n  induction l as [| n l' IHl'].\n    (* The definition or `rev` for `[]` is trivial. *)\n  - reflexivity.\n  - simpl. rewrite rev_app_distr.\n    (* Step by step of `rev [n]` simplification, just to be explicit. *)\n    simpl rev. simpl app.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\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  do 2 (rewrite app_assoc). reflexivity.\nQed.\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  - reflexivity.\n  - destruct n.\n    + simpl. rewrite IHl1'. reflexivity.\n    + simpl. rewrite IHl1'. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercises *)\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | [], []             => true\n  | h1 :: t1, h2 :: t2 => (h1 =? h2) && eqblist t1 t2\n  | _, _               => false\n  end.\n\nExample test_eqblist1: (eqblist nil nil = true).\nProof. reflexivity. Qed.\nExample test_eqblist2: eqblist [1; 2; 3] [1; 2; 3] = true.\nProof. reflexivity. Qed.\nExample test_eqblist3: eqblist [1; 2; 3] [1; 2; 4] = false.\nProof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall (l : natlist),\n  true = eqblist l l.\nProof.\n  intros l.\n  (* Since `l` is arbitrary, one must use induction. *)\n  induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite <- IHl'. rewrite eqb_refl. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercises *)\n\nTheorem count_member_nonzero: forall s : bag,\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\nintros s. induction s as [|h t IHs'].\n- reflexivity.\n- simpl count. simpl leb. reflexivity.\nQed.\n\nTheorem leb_n_Sn : forall n : nat,\n  n <=? S n = true.\nProof.\n  intros n.\n  (* `n` is arbitrary, `leb` can't *)\n  induction n as [| n' IHn'].\n    (* `0 <=? 1` has a match arm, `O, n => true`. *)\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\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.\n  induction s as [| n s' IHs'].\n  - reflexivity.\n  - destruct n as [| n'].\n    + simpl. rewrite leb_n_Sn. reflexivity.\n    + simpl. rewrite IHs'. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\n\n(* Write down an interesting theorem bag_count_sum about bags involving the\n * functions count and sum, and prove it using Coq. (You may find that the\n * difficulty of the proof depends on how you defined count! Hint: If you\n * defined count using =? you may find it useful to know that destruct works on\n * arbitrary expressions, not just simple identifiers.\n *)\n\nTheorem bag_count_sum : forall (x : nat) (b1 b2 : bag),\n  count x (sum b1 b2) = count x b1 + count x b2.\nProof.\n  intros x b1 b2.\n  induction b1 as [| n b1' IHb1'].\n  - reflexivity.\n  - simpl.\n    (* Destruct `n =? x` for all constructors of `bool` (which is the type of\n     * that expression. *)\n    destruct (n =? x) eqn:E.\n    + rewrite IHb1'. reflexivity.\n    + rewrite IHb1'. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\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\n(*\n * OPTIONS\n *)\n\n(* This is bad since the caller must always provide a default value. *)\nFixpoint nth_bad (default : nat) (l : natlist) (n : nat) : nat :=\n  match l with\n  | [] => default\n  | h :: t => match n with\n              | 0 => h\n              | S n' => nth_bad default t n'\n              end\n  end.\n\n(* Another option is to use some type to encode the absence of a value. *)\nInductive natoption : Type :=\n  | None\n  | Some (n : nat).\n\nFixpoint nth_error (l : natlist) (n : nat) : natoption :=\n  match l with\n  | [] => None\n  | h :: t => match n with\n              | 0 => Some h\n              | S n' => nth_error t 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\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n => n\n  | None => d\n  end.\n\n(******************************************************************************)\n\n(* Exercise *)\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. 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\n(* Exercise *)\n\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros l d.\n  destruct l as [| h l'].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nEnd NatList.\n\n(******************************************************************************)\n\n(*\n * PARTIAL MAPS\n *)\n\nInductive id : Type :=\n  | Id (n : nat).\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\nTheorem eqb_id_refl : forall (x : id),\n  eqb_id x x = true.\nProof.\n  intros x.\n  destruct x as [n].\n  simpl.\n  rewrite eqb_refl.\n  reflexivity.\nQed.\n\nModule PartialMap.\n\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\n(* The `update` function overrides the entry for a given key by shadowing it\n * with a new one, or simply adds a new entry “at the top”. *)\nDefinition update\n  (d : partial_map) (x : id) (value : nat) : partial_map :=\n    record x value d.\n\nFixpoint find (x : id) (d : partial_map) : natoption :=\n  match d with\n  | empty => None\n  | record i v d' => if eqb_id x i\n                      then Some v\n                      else find x d'\n  end.\n\n(******************************************************************************)\n\n(* Exercise *)\n\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.\n  reflexivity.\nQed.\n\n(******************************************************************************)\n\n(* Exercise *)\n\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 H.\n  simpl.\n  rewrite H.\n  reflexivity.\nQed.\n\nEnd PartialMap.\n", "meta": {"author": "lffg", "repo": "sf", "sha": "7198c134584def60823625457b6e524f6c722492", "save_path": "github-repos/coq/lffg-sf", "path": "github-repos/coq/lffg-sf/sf-7198c134584def60823625457b6e524f6c722492/src/lf/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8652240895276223, "lm_q1q2_score": 0.7371300874035381}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Tactics.\n\nCheck 3 = 3: Prop.\n\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three : nat -> Prop.\n\nDefinition injective {A B} (f : A -> B) : Prop :=\n  forall x y : A, f x = f y -> x = y\n.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. injection H as H1. apply H1.\n  Qed\n.\n\nCheck @eq : forall A : Type, A -> A -> Prop.\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed\n.\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nExample and_exercise : forall n m : nat , n + m = 0 -> n= 0 /\\ m = 0.\nProof.\n split.\n - destruct n.\n  + reflexivity.\n  + discriminate H.\n - destruct m.\n  + reflexivity.\n  + rewrite <- plus_n_Sm in H. discriminate.\nQed\n.\n\nExample add_example2:\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nExample add_example2':\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nExample add_example3:\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  apply and_exercise in H.\n  destruct H as [Hn Hm]  .\n  rewrite Hn. \n  reflexivity.\nQed.\n\nLemma proj1: forall P Q : Prop, P /\\ Q -> P.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [HP _].\n  apply HP.\n  Qed\n.\n\nLemma proj2: forall P Q : Prop, P /\\ Q -> Q.\nProof.\n  intros P Q HPQ.\n  destruct HPQ as [_ HP].\n  apply HP.\n  Qed\n.\n\nTheorem add_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n  - apply HQ.\n  - apply HP. Qed\n.\n\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.\n  - split.\n    + apply HP.\n    + apply HQ.\n  - apply HR.\nQed\n.\n\n(* A /\\ B is a syntactic sugar for and A B. *)\nCheck and : Prop -> Prop -> Prop.\n\nLemma eq_mult_0 : forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m [Hn | Hm].\n  - rewrite Hn. reflexivity.\n  - rewrite Hm. rewrite <- mult_n_O. reflexivity.\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.\n\nLemma zero_or_succ :\nforall n : nat, n = O \\/ n = S (pred n).\nProof.\n  intros [|n'].\n  - left. reflexivity.\n  - right. reflexivity.\nQed\n.\n\nModule MyNot.\nDefinition not (P : Prop) := P -> False.\nNotation \"- x\" := (not x) : type_scope.\nCheck not : Prop -> Prop.\nEnd MyNot.\n\nTheorem ex_falso_eudlibet : forall P : Prop,\n  False -> P.\nProof.\n  intros P contra.\n  destruct contra.\nQed.\n\nFact not_implies_our_not : forall P:Prop,\n  ~P -> (forall Q:Prop, P -> Q).\nProof.\n  intros P H Q HP.\n  unfold not in H. apply H in HP. destruct HP. Qed\n.\n\nNotation \"x <> y\" := (~ (x = y)).\n\nTheorem zero_not_one : 0 <> 1.\nProof. unfold not. intros contra. discriminate contra.\nQed\n.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed\n.\n\nTheorem contradition_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP. Qed\n.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  intros P H. unfold not. intros G. apply G. apply H. Qed\n.\n\n\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~ Q -> ~ P).\nProof.\n  intros P Q HPQ.\n  unfold not. intros HQ. intros HP.\n  apply HQ. apply HPQ. apply HP.\nQed\n.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P. unfold not. intros [HP HNP]. apply HNP. apply HP.\nQed\n.\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros b H.\n  destruct b eqn: HE.\n  - unfold not in H.\n    apply ex_falso_eudlibet. (* exfalso . *)\n    apply H. reflexivity.\n  - reflexivity.\nQed\n.\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - unfold not in H.\n    exfalso.\n    apply H. reflexivity.\n  - reflexivity.\nQed\n.\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\nModule MyIff.\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\nNotation \"P <-> Q\" := (iff P Q)\n  (at level 95, no associativity) : type_scope.\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [HAB HBA].\n  split.\n  - apply HBA.\n  - apply HAB.\n  Qed\n.\n\nLemma not_true_iff_false : forall b, b <> true <-> b = false.\nProof.\n  intros b. split.\n  - apply not_true_is_false.\n  - intros H. rewrite H. intros H'. discriminate H'.\nQed.\n\nTheorem or_distribute_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. split.\n  - intros [H1|[H2 H3]].\n    + split.\n      * left. apply H1.\n      * left. apply H1.\n    + split.\n      * right. apply H2.\n      * right. apply H3.\n  - intros [[] []].\n   + left. apply H.\n   + left. apply H.\n   + left. apply H0.\n   + right. split.\n    * apply H.\n    * apply H0.\nQed.\n\nTheorem and_distribute_over_or : forall P Q R : Prop,\n  P /\\ (Q \\/ R) <-> (P /\\ Q) \\/ (P /\\ R).\nProof.\n  intros P Q R. split.\n  - intros [H1 [H2|H3]].\n    + left. split.\n      * apply H1.\n      * apply H2.\n    + right. split.\n      * apply H1.\n      * apply H3.\n  - intros [[H1 H2]|[H1 H2]].\n   + split.\n    * apply H1.\n    * left. apply H2.\n   + split.\n    * apply H1.\n    * right. apply H2.\nQed.\n\n(* Setoids and Logical Equivalence *)\nFrom Coq Require Import Setoids.Setoid. (* allows to use rewrite and reflexivity with iff statements, not just equalities. *)\n\nTheorem mult_eq_0 : forall n m , n * m = 0 -> n = 0 \\/ m = 0.\nProof. intros [] [] H.\n  - right. reflexivity.\n  - left. reflexivity.\n  - right. reflexivity.\n  - simpl in H. discriminate H.\nQed\n.\n\n\nLemma mult_0 : forall n m , n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n    split.\n    - apply mult_eq_0.\n    - apply eq_mult_0.\nQed.\n\nTheorem or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. 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 mult_0_3 : forall n m p, n * m * p = 0 <-> n = 0 \\/  m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc. reflexivity. Qed\n.\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H. Qed\n.\n\n(* Existential Quantification *)\nDefinition Even x := exists n : nat, x = double n.\n\nLemma four_is_even : Even 4.\nProof.\n  unfold Even. exists 2. reflexivity.\nQed.\n\nTheorem exists_example : forall n,\n  (exists m, n = 4 + m) -> (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].\n  exists (2 + m).\n  apply Hm.\nQed.\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. unfold not. intros [x H2]. apply H2. apply H. Qed\n.\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  intros X P Q. split.\n  - intros [x [HP|HQ]].\n    + left. exists x. apply HP.\n    + right. exists x. apply HQ.\n  - intros [[x HP]|[x HQ]].\n    + exists x. left. apply HP.\n    + exists x. right. apply HQ.\nQed\n.\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | nil => False\n  | x' :: l' => x' = x \\/ In x l'\n  end\n.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  simpl. right. right. right. left. reflexivity.\nQed.\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\nTheorem In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l -> In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [|x' l' IHl'].\n  - simpl. intros []. (* [] destructs False. *)\n  - simpl.  intros [H|H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed\n.\n\nCheck or_intro_r : forall A B : Prop, B -> A \\/ B.\n\nTheorem In_map_iff : forall A B (f : A -> B) (l : list A) (y : B),\n  In y (map f l) <-> exists x, f x = y /\\ In x l.\nProof.\n  intros A B f l y. induction l as [|x l IHl].\n  - simpl. split.\n    + intros [].\n    + intros [_ [_ []]].\n  - simpl. split.\n    + intros [H1|H2].\n      * exists x. split.\n        ** apply H1.\n        ** left. reflexivity.\n      * apply IHl in H2. destruct H2 as [x' [H1 H2]].\n        exists x'. split.\n        ** apply H1.\n        ** right. apply H2.\n    + intros [x' [H1 [H2|H2]]].\n      * left. rewrite H2. apply H1.\n      * right. rewrite IHl. exists x'. split.\n        ** apply H1.\n        ** apply H2.\nQed.\n\nTheorem In_app_iff : forall A l l' (a : A),\n  In a (l ++ l') <-> In a l \\/ In a l'.\nProof.\n  intros A l. induction l as [| a' l' IH].\n  - simpl. split.\n    + intros H. right. apply H.\n    + intros [[]|H].\n      apply H.\n  - intros l1 a. simpl. rewrite IH. apply or_assoc.\nQed\n.\n\nFixpoint All {T:Type} (P:T->Prop) (l : list T) : Prop :=\n  match l with\n  | nil => True\n  | h :: t => P h /\\ All P t end\n.\n\nTheorem All_In :\n  forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <-> All P l.\nProof.\n  intros T P l. split.\n  - intros H. induction l as [|h t IHl].\n    + reflexivity.\n    + simpl. split.\n      * apply H. simpl. left. reflexivity.\n      * apply IHl. intro H1. intro H2. apply H. simpl. right. apply H2.\n  - (* <- *)intros HA x H. generalize dependent l. induction l as [|h t IH].\n    + simpl. intros. destruct H.\n    + simpl. intros [H1 H2]. intros [H3|H4].\n      * rewrite <- H3. apply H1.\n      * apply IH.\n        ** apply H2.\n        ** apply H4.\nQed\n.\n\n(* Exercise: 2 stars, standard, optional (combine_odd_even) *)\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop\n  . Abort.\n\n  (* TODO: solve the exercise. *)\n\n\n(* Applying Theorems to Arguments *)\n\n(* Proofs are first-class objects in Coq. *)\n\nCheck add_comm : forall n m : nat, n + m = m + n.\n(* The type of the proof object is the proposition which it is a proof of. *)\n\nLemma add_comm3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z. (* x + (y + z) *)\n  rewrite add_comm. (* y + z + x *)\n  rewrite (add_comm y z). (* z + y + x. Proofs can be applied *)\n  reflexivity.\nQed.\n\nTheorem in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H. unfold not. intros Hl.\n  rewrite Hl in H. simpl in H. apply H.\nQed.\n\nLemma in_not_nil_42 :\n  forall l : list nat , In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil with (x := 42).\n  apply H.\nQed.\n\nLemma in_not_nil_42_take3 :\n  forall l : list nat , In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil in H.\n  apply H.\nQed.\n\nLemma in_not_nil_42_take4 :\n  forall l : list nat , In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil nat 42).\n  apply H.\nQed.\n\nLemma in_not_nil_42_take5 :\n  forall l : list nat , In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil _ _ _ H). (* Use theorem as a function to map H and apply the returned value (Prop). *)\nQed.\n\nCheck proj1 : forall P Q : Prop, P /\\ Q -> P.\n\nDefinition mult_n_0 := mult_n_O.\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) -> n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n    as [m [Hm _]].\n  rewrite <- mult_n_0 in Hm. rewrite <- Hm. reflexivity.\nQed.\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof.\n  reflexivity.\nQed.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n   (* Stuck *)\nAbort.\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply add_comm.\nQed.\n\n(* Prints Axioms theorems rely on. *)\nPrint Assumptions function_equality_ex2.\n\nFixpoint rev_append {X} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | x :: l1' => rev_append l1' (x :: l2) end\n.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l []\n.\n\nLemma rev_append_const : forall X (l1 l2 : list X),\n  rev_append l1 l2 = rev_append l1 [] ++ l2.\nProof.\n  intros X.\n  induction l1.\n  - intros l2. reflexivity.\n  - intros l2. simpl. rewrite IHl1. symmetry. rewrite IHl1.\n    rewrite <- app_assoc. reflexivity.\nQed.\n\nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros X.\n  apply functional_extensionality.\n  induction x as [| h x' IHx].\n  - reflexivity.\n  - simpl. rewrite <- IHx. unfold tr_rev. simpl.\n    (* rev_append x' [h] = rev_append x' [] ++ [h] *)\n    apply rev_append_const.\nQed.\n\nLemma even_double : forall k, even (double k) = true.\nProof.\n  induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\nLemma even_double_conv : forall n : nat, exists k : nat,\n n = if even n then double k else S (double k).\nProof.\n  induction n as [|n' IHn].\n  - exists 0. reflexivity.\n  - destruct (even n') eqn:E.\n    + (* n' is Even *) destruct IHn as [k IHn].\n      exists k. rewrite even_S. rewrite E. simpl. rewrite IHn. reflexivity.\n    + (* n' is odd *) destruct IHn as [k IHn].\n      exists (S k). rewrite even_S. rewrite E. simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem even_bool_prop : forall n,\n  even n = true <-> Even n.\nProof.\n  intros n. split.\n  - intros H. destruct (even_double_conv n) as[k Hk].\n    rewrite H in Hk. rewrite Hk. exists k. reflexivity.\n  - intros [k H]. rewrite H. apply even_double.\nQed.\n\nSearch eqb.\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. symmetry. rewrite eqb_refl. reflexivity.\nQed.\n\nExample not_even_1001 : even 1001 = false.\nProof.\n  reflexivity.\nQed.\n\nExample not_even_1001' : ~ (Even 1001).\nProof.\n  rewrite <- even_bool_prop.\n  unfold not.\n  simpl.\n  intros H.\n  discriminate H.\nQed.\n\nLemma plus_eqb_example: forall n m p : nat,\n  n =? m = true -> n + p =? m + p = true.\nProof.\n  intros n m p H.\n  rewrite eqb_eq in H.\n  rewrite H.\n  rewrite eqb_eq.\n  reflexivity.\nQed.\n\n(*\nNote the complementary strengths of booleans and general propositions. Being able to cross back and forth between the boolean and propositional worlds will often be conveninent.\n*)\n\nTheorem andb_true_iff : forall b1 b2: bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  split.\n  - intros H. destruct b1.\n    + split.\n      * reflexivity.\n      * destruct b2.\n        ** reflexivity.\n        ** simpl in H. apply H.\n    + split.\n      * simpl in H. apply H.\n      * simpl in H. discriminate H.\n  - intros [H1 H2]. rewrite H1. rewrite H2. reflexivity.\nQed.\n\nTheorem orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  split.\n  - intros H. destruct b1.\n    + left. reflexivity.\n    + simpl in H. right. apply H.\n  - intros [H|H].\n    + rewrite H. reflexivity.\n    + rewrite H. destruct b1.\n      * reflexivity.\n      * reflexivity.\nQed.\n\nCheck not_true_iff_false : forall b : bool, b <> true <-> b = false.\n\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  split.\n  - intros H. rewrite <- not_true_iff_false in H. unfold not in H. unfold not. intros H2. apply H. rewrite eqb_eq. apply H2.\n  - intros H. rewrite <- not_true_iff_false. unfold not in H. unfold not. intros H2. apply H. rewrite eqb_eq in H2. apply H2.\nQed.\n\nFixpoint eqb_list {A : Type} (eqb : A -> A -> bool)\n  (l1 l2 : list A) : bool :=\n  match l1, l2 with\n  | nil, nil => true\n  | nil, _ => false\n  | _, nil => false\n  | h1::l1', h2::l2' => if eqb h1 h2 then eqb_list eqb l1' l2' else false\n    end\n.\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 as [| n1 l1' IHl1].\n  - simpl. split.\n    + destruct l2.\n      * reflexivity.\n      * discriminate.\n    + intro H2. rewrite <- H2. reflexivity.\n  - split.\n    + simpl. destruct l2 as [|n2 l2'].\n      * discriminate.\n      * destruct (eqb n1 n2) eqn:E.\n        ** intros H2. apply H in E. rewrite E. rewrite IHl1 in H2. rewrite H2. reflexivity.\n        ** discriminate.\n    + intros H2. rewrite <- H2. simpl. assert (E: eqb n1 n1 = true). {\n      rewrite H. reflexivity.\n    }\n      rewrite E. rewrite IHl1. reflexivity.\nQed.\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')\nend\n.\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  induction l as [|n l' IHl].\n  - split.\n    + reflexivity.\n    + reflexivity.\n  - simpl. rewrite andb_true_iff. rewrite IHl. reflexivity.\nQed.\n\n(** Classicla vs. Constructive Logic **)\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P. (* Not provable !! *)\n\n\n(* If P is reflected to some boolean term b... *)\nTheorem restricted_excluded_middle : 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\nTheorem restricted_excluded_middle_eq : forall (n m : nat),\n  n = m \\/ n <> m.\nProof.\n  intros n m.\n  apply (restricted_excluded_middle (n=m) (n=?m)).\n  symmetry.\n  apply eqb_eq.\nQed.\n\n(* In Coq, existential conditions are constructive. i.e. For exists x, P x, it's always possible to exhibit a value of x for which we can prove P x.\nSuch logics are referred to as constructive logics.\n\nMove conventional logical systems such as ZFC, in which the excluded middle does hold for arbitrary propositions, are referred to as classical.\n*)\n\n(*\n~( P \\/ ~P ) \n( ~P \\/ ~~P )\n\n*)\nTheorem excluded_middle_irrefutable : forall (P : Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  unfold not. intros P H.\n  assert (HP: P -> False). {\n    intro H2.\n    apply H.\n    left.\n    apply H2.\n  }\n  apply H. right. apply HP.\nQed.\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  unfold not.\n  intros EM X P H x.\n  assert (HP: (P x -> False) -> False). {\n    intros H1.\n    apply H.\n    exists x. apply H1.\n  }\n  assert (EM2: P x \\/ ~ P x). {\n    apply EM.\n  }\n  unfold not in EM2.\n  destruct EM2 as [EM2|EM2].\n  - apply EM2.\n  - apply HP in EM2. destruct EM2.\nQed.\n\nDefinition peirce := forall P Q : Prop, ((P -> Q) -> P) -> P.\nDefinition double_negation_elimination := forall P : Prop, ~~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 excluded_middle_peirce : excluded_middle -> peirce.\nProof.\n  unfold excluded_middle, peirce.\n  intros EM P Q H.\n  destruct (EM P) as [HP|HP].\n  - apply HP.\n  - apply H. intros P2. exfalso. apply HP. apply P2.\nQed.\n\n\nTheorem peirce_double_negation_elimination : peirce -> double_negation_elimination.\nProof.\n  unfold peirce, double_negation_elimination, not.\n  intros HP P NNP.\n  apply (HP P False). intros H. destruct (NNP H).\nQed.\n\nTheorem double_negation_elimination_de_morgan_not_and_not : double_negation_elimination -> de_morgan_not_and_not.\nProof.\n  unfold double_negation_elimination, de_morgan_not_and_not, not.\n  intros HP P Q H. apply HP. intros HPQ. apply H. split.\n  - intros P2. apply HPQ. left. apply P2.\n  - intros Q2. apply HPQ. right. apply Q2.\nQed.\n\nTheorem de_morgan_not_and_not_implies_to_or : de_morgan_not_and_not -> implies_to_or.\nProof.\n  unfold de_morgan_not_and_not, implies_to_or, not.\n  intros HP P Q HPQ. apply HP. intros [H1 H2]. apply H1. intro P2.\n  apply H2, HPQ, P2.\nQed.\n\nLemma or_symmetry : forall A B : Prop, A \\/ B <-> B \\/ A.\nProof.\n  split.\n  - intros [HA|HB].\n    + right. apply HA.\n    + left. apply HB.\n  - intros [HB|HA].\n    + right. apply HB.\n    + left. apply HA.\nQed.\n\nTheorem implies_to_or_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or, excluded_middle, not.\n  intros HP P. rewrite or_symmetry. apply HP. intro P2. apply P2.\nQed.\n", "meta": {"author": "ogiekako", "repo": "software_foundations", "sha": "95d160edc04f12e8c85cee86a63fd791df21da1e", "save_path": "github-repos/coq/ogiekako-software_foundations", "path": "github-repos/coq/ogiekako-software_foundations/software_foundations-95d160edc04f12e8c85cee86a63fd791df21da1e/v1/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.7371300631341838}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import Lia.\nRequire Import Psatz.\n\nDefinition divides(a b:nat) := {k:nat & a * k = b}.\nDefinition isPrime(n:nat) := forall a b:nat, (divides n (a * b)) -> ((divides n a)+(divides n b)).\n\nDefinition add_comm\n     : forall n m : nat, n + m = m + n.\nintro n.\ndestruct n.\nall: intro m.\n2: generalize n; clear n.\nall: induction m.\nreflexivity.\nsimpl.\nrewrite <- IHm.\nsimpl; reflexivity.\nsimpl.\ninduction n.\nreflexivity.\nsimpl.\nrewrite IHn.\nreflexivity.\nintro n.\nsimpl.\nrewrite <- IHm.\nsimpl.\ninduction n.\nsimpl.\nreflexivity.\nrewrite IHm.\nsimpl.\nrewrite IHn.\nrewrite <- IHm.\nsimpl.\nreflexivity.\nDefined.\n\nLemma add_comm_assoc : forall a b c:nat, (a + (b + c)) = (b + (a + c)).\nintro a.\ninduction a.\nall: simpl; try reflexivity.\nintros b c.\nrewrite (add_comm b (S _)).\nsimpl.\nrewrite <- (add_comm b (_ + _)).\nrewrite IHa.\nreflexivity.\nDefined.\n\nLemma add_assoc : forall a b c:nat, (a + (b + c)) = a + b + c.\nintro a.\ninduction a.\nall: simpl; try reflexivity.\nintros b c.\nrewrite IHa.\nreflexivity.\nDefined.\n\nDefinition mul_comm\n     : forall n m : nat, n * m = m * n.\nintro n.\ndestruct n.\nall: intro m.\n2: generalize n; clear n.\nall: induction m.\nreflexivity.\nsimpl.\nrewrite <- IHm.\nsimpl; reflexivity.\nsimpl.\ninduction n.\nreflexivity.\nsimpl.\napply IHn.\nintro n.\ntransitivity ((S n * m) + (S n)).\n2: transitivity ((m * (S n)) + (S n)).\n2: rewrite IHm; reflexivity.\nall: simpl.\nall: repeat rewrite (add_comm _ (S _)).\nall: simpl.\n2:reflexivity.\ninduction n.\nall: simpl.\nreflexivity.\nrepeat rewrite (add_comm _ (S _)).\nrewrite IHn.\nrepeat rewrite (add_comm _ (S _)).\nsimpl.\nrewrite (add_comm _ m).\nrewrite add_comm_assoc.\nreflexivity.\nDefined.\n\nInductive Even : nat -> Type :=\n|EO : Even 0\n|ES : forall n:nat, Odd n -> Even (S n)\nwith Odd : nat -> Type :=\n|OS : forall n:nat, Even n -> Odd (S n).\n\n\nFixpoint twoDividesEven1(n:nat)(H:Even n) : (divides 2 n) :=\nmatch H with\n | EO => existT (fun k : nat => 2 * k = 0) 0 eq_refl\n | ES n0 o =>\n     match o with\n     | OS n1 e =>\n         let (x, e0) := twoDividesEven1 n1 e in\n         existT (fun k : nat => 2 * k = S (S n1)) (S x)\n           (eq_ind_r (fun n2 : nat => n2 = S (S n1))\n              (eq_ind_r (fun n2 : nat => S (S n2) = S (S n1))\n                 (eq_ind_r (fun n2 : nat => S (S n2) = S (S n1)) eq_refl e0) (mul_comm x 2))\n              (mul_comm 2 (S x)))\n     end\n end.\n\nFixpoint twoDividesEven2(n:nat)(H:divides 2 n) : (Even n).\ndestruct H.\ninduction e.\ninduction x.\nconstructor 1.\nsimpl.\nrepeat progress (try rewrite (add_comm _ 0); simpl;\n                 try rewrite (add_comm _ (S _)); simpl).\nconstructor 2.\nconstructor 1.\nsimpl in IHx.\nrepeat progress (try rewrite (add_comm _ 0) in IHx; simpl in IHx;\n                 try rewrite (add_comm _ (S _)) in IHx; simpl in IHx).\napply IHx.\nDefined.\n\nLemma EvenOrOddS : forall n:nat, (Even n + Odd n) -> (Even (S n) + Odd (S n)).\nintros.\ndestruct H.\nconstructor 2.\nconstructor 1.\napply e.\nconstructor 1.\nconstructor 2.\napply o.\nDefined.\n\n\nFixpoint EvenOrOdd(n:nat) : Even n + Odd n :=\nmatch n with\n | 0 => inl EO\n | S k => EvenOrOddS _ (EvenOrOdd k)\nend.\n\nLemma add_commS : forall n m:nat, S (S (n + m)) = S n + S m.\nsimpl.\nintros.\nrewrite (add_comm _ (S _)).\nsimpl.\nrewrite (add_comm n m).\nreflexivity.\nDefined.\n\n\nLemma timesS : forall a b:nat, S ((a * b) + a + b) = (S a) * (S b).\nsimpl.\nintros.\nrewrite (mul_comm _ (S _)).\nsimpl.\nrewrite (mul_comm b a).\nrewrite (add_comm _ (a * b)).\nrewrite (add_comm_assoc ).\nrewrite (add_comm b a).\nrewrite (add_assoc ).\nreflexivity.\nDefined.\n\nFixpoint OddEvenPlus{a b:nat}(Ha : Even a)(Hb : Odd b) {struct Hb}: (Odd (a + b)) := \nmatch Ha with\n |EO => @eq_rect nat b Odd Hb (0 + b) eq_refl\n |ES n o => match Hb with\n            |OS m e => \n                   eq_rect _ _ (@eq_rect nat (S (S (m + n))) Odd (OS (S (m + n)) (ES (m + n) (EvenOddPlus e o))) (S (S (n + m)))\n    (f_equal S (f_equal S (add_comm m n)))) _ (add_commS _ _)\n            end\nend\nwith EvenOddPlus{a b:nat}(Ha : Even a)(Hb : Odd b) {struct Ha}: (Odd (a + b)) := \nmatch Ha with\n |EO => @eq_rect nat b Odd Hb (0 + b) eq_refl\n |ES n o => match Hb with\n            |OS m e => \n                   eq_rect _ _ (@eq_rect nat (S (S (m + n))) Odd (OS (S (m + n)) (ES (m + n) (OddEvenPlus e o))) (S (S (n + m)))\n    (f_equal S (f_equal S (add_comm m n)))) _ (add_commS _ _)\n            end\nend.\n\nDefinition EvenTimes{a:nat}(b:nat)(Ha : Even a) : (Even (a * b)).\napply twoDividesEven2.\ndestruct (twoDividesEven1 _ Ha).\ninduction e.\nexists (x * b).\nsimpl.\nrepeat (rewrite (add_comm _ 0); simpl).\nrepeat (rewrite (mul_comm _ b); simpl).\ninduction b.\nall: simpl.\nreflexivity.\nrewrite add_comm_assoc.\nrewrite <- add_assoc.\nrewrite IHb.\nrepeat rewrite add_assoc.\nreflexivity.\nDefined.\n\nFixpoint EvenEvenPlus{a b:nat}(Ha : Even a)(Hb : Even b) {struct Ha}: (Even (a + b)) :=\nmatch Ha with\n |EO => @eq_rect nat b Even Hb (0 + b) eq_refl\n |ES n On => match Hb with\n             |EO => let p : (S n) = (S n) + 0 := eq_sym (add_comm (S n) 0) in\n                    @eq_rect nat (S n) Even (ES _ On) ((S n) + 0) p\n             |ES m Om => let p : (S (S (n + m))) = (S n + S m) := add_commS _ _ in\n                          eq_rect _ Even (ES _ (OS _ (OddOddPlus On Om))) _ p\n             end\nend\nwith\nOddOddPlus{a b:nat}(Ha : Odd a)(Hb : Odd b) {struct Ha}: (Even (a + b)) :=\nmatch Ha with\n |OS n En => match Hb with\n             |OS m Em => let p : (S (S (n + m))) = (S n + S m) := add_commS _ _ in\n                          eq_rect _ Even (ES _ (OS _ (EvenEvenPlus En Em))) _ p\n             end\nend.\n\nDefinition OddOddTimes{a b:nat}(Ha : Odd a)(Hb : Odd b) : (Odd (a * b)) := \nmatch Ha with\n|OS n En => match Hb with\n            |OS m Em => let p : S _ = _ := timesS _ _ in  \n                        eq_rect _ Odd (OS _ (EvenEvenPlus (EvenEvenPlus (EvenTimes _ En) En) Em)) _ p\n            end\nend.\n\nLemma NotBothEvenOdd : forall n:nat, Even n -> Odd n -> False.\ninduction n.\nall: intros.\ninversion H0.\ninversion H.\ninversion H0.\ninduction H3.\ninduction H1.\napply (IHn H4 H2).\nDefined.\n\nTheorem twoIsPrime : isPrime 2.\nintros a b X.\ndestruct (EvenOrOdd a).\nconstructor 1.\napply (twoDividesEven1 _ e).\nconstructor 2.\ndestruct (EvenOrOdd b).\napply (twoDividesEven1 _ e).\nassert (EX := twoDividesEven2 _ X).\nassert (OX := OddOddTimes o o0).\ndestruct (NotBothEvenOdd _ EX OX).\nDefined.\n\n(*Definition Prime := @sigT nat isPrime.*)\nDefinition Prime := {n:nat & isPrime n}.\n\nExample TwoPrime : Prime := existT isPrime 2 twoIsPrime.\n\nTheorem Grothendieck : (isPrime 51) -> False.\nunfold isPrime.\nsimpl.\nintro H.\ndestruct (H 3 17 (existT _ 1 eq_refl)) as [[k ?H]|[k ?H]].\nall: induction k.\nall: simpl in H0.\nall: try repeat rewrite (add_comm _ (S _)) in H0.\nall: inversion H0.\nDefined.\n\n\nTheorem rootPrime : forall p:nat, (forall n:nat, ((S (S (n))) * (S (S (n)))) <= p -> (divides (S (S (n))) p) -> False) -> (isPrime p).\nProof with (simpl in *; try ((constructor 1; (lia || nia || psatz nat 2)) || (constructor 2; (lia || nia || psatz nat 2)))).\nunfold isPrime, divides.\nintros.\ndestruct H0.\nall: destruct a...\nall: destruct b...\nall: destruct x...\nall: try induction a...\nall: try induction b...\nall: try induction x...\nall: rewrite (mul_comm p _) in e...\nall: induction e...\n", "meta": {"author": "bowtochris", "repo": "CoqStuff", "sha": "80ffef00b18a23b85f66fcb5b198d2730a49a362", "save_path": "github-repos/coq/bowtochris-CoqStuff", "path": "github-repos/coq/bowtochris-CoqStuff/CoqStuff-80ffef00b18a23b85f66fcb5b198d2730a49a362/Primes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.737073660144977}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (lf2 : natural) : natural :=\n  mult lf1 lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj33_coqofml_vRyPwP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7370736593374974}}
{"text": "Theorem a1 : forall (P Q : Prop), (P /\\ Q) -> ~(~P \\/ ~Q).\nProof.\n  unfold not.\n  intros.\n  case H0; intros; case H; intros.\n  apply (H1 H2).\n  apply (H1 H3).\nQed.\n\nTheorem a2 : forall (P Q : Prop), (P \\/ Q) -> ~(~P /\\ ~Q).\nProof.\n  unfold not.\n  intros.\n  case H; intros; case H0; intros.\n  apply (H2 H1).\n  apply (H3 H1).\nQed.\n\nTheorem e1 : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  unfold not.\n  intros.\n  case H0; intros.\n  apply (H1 (H x)).\nQed.\n\nTheorem e2 : forall (X:Type) (P : X -> Prop),\n  (exists x, P x) -> ~ (forall x, ~ P x).\nProof.\n  unfold not.\n  intros.\n  case H; intros.\n  apply (H0 x H1).\nQed.\n  ", "meta": {"author": "TorosFanny", "repo": "my_Coq_experiment", "sha": "6ee7ba51822bfe55a74ecc9c11221588834c99da", "save_path": "github-repos/coq/TorosFanny-my_Coq_experiment", "path": "github-repos/coq/TorosFanny-my_Coq_experiment/my_Coq_experiment-6ee7ba51822bfe55a74ecc9c11221588834c99da/or_not_and,and_not_or,forall_not_exist,exist_not_forall.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.7369973678743804}}
{"text": "(*\nD1. Zero Sum Sequences\n======================\nWe prove that given an infinite sequence α and a number n, there exists numbers\ni and k such that 0 < k and i + k ≤ n and the sequence α_{i}..α_{i+k} sums to 0\nmodulo n. The proof for this theorem is based on a \"sliding window\" over the\nfirst n elements of α.\n*)\n\nFrom graph_pebbling Require Import A_primitives.\n\nLemma unfold_mod i n :\n  n ≠ 0 -> ∃ m, i `mod` n = i - n * m ∧ n * m ≤ i.\nProof. exists (i `div` n); nia. Qed.\n\nLtac unfold_mod m :=\n  let H := fresh \"H\" in\n  edestruct unfold_mod as (m & -> & H); [done|].\n\nTheorem zero_sum_sequence (α : nat -> nat) n :\n  n ≠ 0 -> ∃ i k, 0 < k ∧ i + k ≤ n ∧ n ∣ summation (α <$> seq i k).\nProof.\nintros Hn; pose (β i := summation (α <$> seq 0 i) `mod` n).\ndestruct (nat_pigeonhole β (S n) n) as (i&j&H1&H2); unfold β in *; [lia|lia|].\nexists i, (j - i); repeat split; [lia|lia|]; revert H2.\nreplace j with (i + (j - i)) at 1 by lia.\nrewrite seq_app, fmap_app, summation_app; cbn.\nunfold_mod m_i; unfold_mod m_j; exists (m_j - m_i); nia.\nQed.\n\nLemma fmap_seq_take_drop {A} (α : nat -> A) i k l :\n  (∀ j, i ≤ j < i + k -> l !! j = Some (α j)) ->\n  α <$> seq i k = take k (drop i l).\nProof.\ninduction k; intros.\n- symmetry; apply take_0.\n- erewrite seq_S, take_S_r, fmap_app, IHk. done.\n  + intros; apply H; lia.\n  + rewrite lookup_drop; apply H; lia.\nQed.\n\nCorollary zero_sum_sublist (l : list nat) :\n  l ≠ [] -> ∃ l', l' ≠ [] ∧ l' `sublist_of` l ∧ length l ∣ summation l'.\nProof.\nintros Hl; apply non_empty_length in Hl; pose (α i := default 0 (l !! i)).\ndestruct (zero_sum_sequence α (length l)) as (i & k & H1 & H2 & H3); [done|].\neexists; split; [|split; [|done]].\n- apply non_empty_length; rewrite fmap_length, seq_length; lia.\n- erewrite fmap_seq_take_drop.\n  + etrans; [apply sublist_take|apply sublist_drop].\n  + intros; unfold α; destruct (l !! j) eqn:E; [done|exfalso].\n    apply lookup_ge_None in E; lia.\nQed.\n", "meta": {"author": "bergwerf", "repo": "pebbling", "sha": "13594dd4184033c710e35d21395929867dec038f", "save_path": "github-repos/coq/bergwerf-pebbling", "path": "github-repos/coq/bergwerf-pebbling/pebbling-13594dd4184033c710e35d21395929867dec038f/D1_zero_sum_sequence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7369554099367923}}
{"text": "(************************************************************************)\n(* Copyright 2006 Milad Niqui                                           *)\n(* This file is distributed under the terms of the                      *)\n(* GNU Lesser General Public License Version 2.1                        *)\n(* A copy of the license can be found at                                *)\n(*                  <http://www.gnu.org/licenses/lgpl-2.1.html>         *)\n(************************************************************************)\n\n\nRequire Export Qsyntax.\nRequire Export Field_Theory_Q.\nRequire Export Q_ordered_field_properties.\n\nDefinition Qabs (q:Q):Q:= \n  match q with \n  | Zero => Zero\n  | Qpos qp => Qpos qp\n  | Qneg qp => Qpos qp\n  end.\n\nLemma Qabs_eq: forall q, Zero<=q -> Qabs q = q. \nProof.\n intros [|q|q] Hq; simpl; trivial; unfold Qle in Hq; contradiction Hq; auto.\nQed.\n\nLemma Qabs_non_eq: forall q, q<=Zero -> Qabs q = (-q).\nProof.\n intros [|q|q] Hq; simpl; trivial; unfold Qle in Hq; contradiction Hq; auto.\nQed.\n\nLemma Qabs_eq_pos: forall q, Zero<q -> Qabs q = q. \nProof.\n intros [|q|q] Hq; simpl; trivial; contradiction (Zero_not_lt_Qneg q). \nQed.\n\nLemma Qabs_non_eq_neg: forall q, q<Zero -> Qabs q = (-q).\nProof.\n intros [|q|q] Hq; simpl; trivial; contradiction (Qpos_not_lt_Zero q). \nQed.\n\nLemma Qabs_Qmult: forall q1 q2, Qabs (q1*q2) = (Qabs q1) * (Qabs q2).\nProof.\n intros [|q1|q1] [|q2|q2]; simpl; trivial.  \nQed.\n\nLemma Qabs_5: forall q p, Qabs q <= p -> (- p <= q)/\\ (q<= p).\nProof.\n intros [|q|q] [|p|p]; simpl; unfold Qle; intros Hqp; split; auto;\n solve [ apply Zero_not_lt_Qneg|apply Qpos_not_lt_Qneg|apply Qle_opp; simpl; assumption].\nQed.  \n\nLemma Qabs_6: forall q p, Qabs q <= p -> q<= p.\nProof.\n intros q p H; apply (proj2 (Qabs_5 _ _ H)).\nQed.\n\nLemma Qabs_7: forall q p, Qabs q <= p -> - p <= q.\n intros q p H; apply (proj1 (Qabs_5 _ _ H)).\nQed.\n\nLemma Qabs_8: forall q p, - p <= q -> q <= p -> Qabs q <= p.\nProof.\n intros [|q|q] [|p|p]; simpl; unfold Qle; intros H1 H2; auto; apply Qle_opp; simpl; assumption.\nQed.\n\nLemma Qabs_nonneg: forall q, Zero <= Qabs q.\nProof.\n intros [|q|q]; simpl; auto. \nQed.\n\nLemma Qle_Qabs: forall q, q <= Qabs q.\nProof.\n intros [|q|q]; simpl; auto. \nQed.\n\nLemma Qle_Qabs_Qopp: forall q, -q <= Qabs q.\nProof.\n intros [|q|q]; simpl; auto. \nQed.\n\nLemma Qabs_Qle_Qopp: forall q, - (Qabs q) <= q.\nProof.\n intros [|qp|qp]; simpl; auto.\nQed.\n\nLemma Qabs_triangle: forall p q, Qabs (p + q) <= Qabs p + Qabs q.\nProof.\n intros p q. \n destruct (Q_le_lt_dec Zero p) as [Hp|Hp]; destruct (Q_le_lt_dec Zero q) as [Hq|Hq].\n  repeat rewrite Qabs_eq; auto.\n\n  assert (Hp1:=Qabs_eq _ Hp); assert (Hq1:=Qabs_non_eq_neg _ Hq); rewrite Hp1; rewrite Hq1;\n  destruct (Q_le_lt_dec Zero (p+q)) as [Hpq|Hpq].\n   rewrite Qabs_eq; trivial; apply Qle_Zero_Qminus_neg; stepl (q+q);[|ring]; auto.\n   rewrite Qabs_non_eq_neg; trivial; apply Qle_Zero_Qminus; stepr (p+p);[|ring]; auto.\n   \n  assert (Hp1:=Qabs_non_eq_neg _ Hp); assert (Hq1:=Qabs_eq _ Hq); rewrite Hp1; rewrite Hq1;\n  destruct (Q_le_lt_dec Zero (p+q)) as [Hpq|Hpq].\n   rewrite Qabs_eq; trivial; apply Qle_Zero_Qminus_neg; stepl (p+p);[|ring]; auto.\n   rewrite Qabs_non_eq_neg; trivial; apply Qle_Zero_Qminus; stepr (q+q);[|ring]; auto.\n\n  repeat rewrite Qabs_non_eq_neg; auto; (stepr (-(p+q)) by ring); trivial.\nQed.\n   \nLemma Qabs_Qopp:forall q, Qabs q = Qabs (-q).\nProof.\n intros [|qp|qp]; trivial.\nQed.\n\nLemma Qabs_Qminus_sym:forall q1 q2, Qabs (q1-q2) = Qabs (q2-q1).\nProof.\n intros q1 q2; rewrite Qabs_Qopp; apply (f_equal Qabs); ring.\nQed.\n\nLemma Qabs_nonzero_pos:forall q, q<> Zero -> Zero < Qabs q.\nProof.\n intros [|qp|qp] H; simpl; trivial; contradiction H; trivial. \nQed.\n\nLemma Qabs_Qminus_Zero_eq:forall q1 q2, Qabs (q1-q2) = Zero -> q1=q2.\nProof.\n intros q1 q2 Hq; destruct (Q_zerop (q1-q2)) as [H|H]; auto; contradiction (Qlt_irreflexive Zero);\n stepr (Qabs (q1 - q2)); trivial; apply Qabs_nonzero_pos; trivial.\nQed.\n\n\nLemma Qabs_Zero_Qminus_eq:forall q1 q2, q1=q2 -> Qabs (q1-q2) = Zero.\nProof.\n intros q1 q2 Hq; rewrite Hq; replace (q2-q2) with Zero by ring; reflexivity. \nQed.\n\nLemma Qabs_Qminus_bound:forall low up q1 q2, low <= q1 -> q1 <= up -> low <= q2 -> q2 <= up -> Qabs (q1-q2) <= up-low.  \nProof.\n intros l u q1 q2 Hq1l Hq1u Hq2l Hq2u.\n destruct (Q_le_lt_dec q2 q1) as [H|H];\n [ rewrite Qabs_eq;\n  [ \n  | apply Qle_Qminus_Zero\n  ]\n | rewrite Qabs_non_eq_neg;\n   [ stepl (q2-q1);[|ring]\n   | apply Qlt_Qminus_Zero_neg\n   ]\n ]; trivial; unfold Qminus; apply Qle_plus_plus; try apply Qopp_Qle; trivial.\nQed.\n\nLemma upper_bound_affine_base_interval_twice:forall a b c d x, -Qone<=x -> x<=Qone -> \n (a*x+b)*(c*x+d) <= Qabs (a*c) + Qabs (a*d+c*b)+b*d.\nProof.\n intros a b c d x Hxl Hxu.\n assert (Hxx0:=Qmult_mult_nonneg x).\n assert (Hxx1:=Qmult_mult_Qle_Qone_Qopp_Qone _ Hxl Hxu). \n stepl ((a*c)*(x*x)+(a*d+c*b)*x+b*d); [|ring].\n repeat apply Qle_plus_plus; trivial.\n  stepr (Qabs (a*c)*Qone); [|ring];\n  apply Qle_trans with (Qabs (a*c)*(x*x));\n  [apply Qle_reg_mult_r_strong; trivial; apply Qle_Qabs| apply Qle_reg_mult_l_strong; trivial; apply Qabs_nonneg]...\n  apply Qle_trans with (Qabs((a*d+c*b)*x)); [apply Qle_Qabs|];\n  rewrite Qabs_Qmult; stepr (Qabs(a*d+c*b)*Qone); [|ring];\n  apply Qle_reg_mult_l_strong; [apply Qabs_nonneg|];\n  apply Qabs_8; trivial...\nQed.\n\n\nLemma lower_bound_affine_base_interval_twice:forall a b c d x, -Qone<=x -> x<=Qone -> \n        -Qabs (a*c) + -Qabs (a*d+c*b)+b*d <= (a*x+b)*(c*x+d).\nProof.\n intros a b c d x Hxl Hxu.\n assert (Hxx0:=Qmult_mult_nonneg x).\n assert (Hxx1:=Qmult_mult_Qle_Qone_Qopp_Qone _ Hxl Hxu). \n stepr ((a*c)*(x*x)+(a*d+c*b)*x+b*d); [|ring].\n repeat apply Qle_plus_plus; trivial.\n  stepl (-Qabs (a*c)*Qone); [|ring];\n  apply Qle_trans with (-Qabs (a*c)*(x*x));\n  [ apply Qle_opp; \n    repeat rewrite <- Qmult_Qopp_left; apply Qle_reg_mult_l_strong; trivial; rewrite Qopp_involutive; apply Qabs_nonneg\n  | apply Qle_reg_mult_r_strong; trivial; apply Qabs_Qle_Qopp\n  ]...\n  apply Qle_trans with (-Qabs((a*d+c*b)*x)); [|apply Qabs_Qle_Qopp];\n  apply Qopp_Qle;\n  rewrite Qabs_Qmult; stepr (Qabs(a*d+c*b)*Qone); [|ring];\n  apply Qle_reg_mult_l_strong; [apply Qabs_nonneg|];\n  apply Qabs_8; trivial...\nQed.\n", "meta": {"author": "verimath", "repo": "real", "sha": "8586b22050077cc1ad095d80ca1ac2f79f781b51", "save_path": "github-repos/coq/verimath-real", "path": "github-repos/coq/verimath-real/real-8586b22050077cc1ad095d80ca1ac2f79f781b51/src/binrat/Qabs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7369554040962099}}
{"text": "(**\nThis exercise shows how to use representation predicates in Iris. We consider\nsome basic operations on linked lists. Although heap-lang is untyped, our\nrepresentation of lists intuitively corresponds to the following (rec-) type\nin an ML-style language:\n\n  list A := option (ref (A * list A))\n*)\nFrom iris.heap_lang Require Import proofmode notation.\n\n(** A function that sums all elements of a list, defined as a heap-lang value: *)\nDefinition sum_list : val :=\n  rec: \"sum_list\" \"l\" :=\n    match: \"l\" with           (* A list is either... *)\n      NONE => #0              (* ... the empty list *)\n    | SOME \"p\" =>             (* ... or [SOME p], where [p] points to a pair ... *)\n      let: \"x\" := Fst !\"p\" in (* ... whose first component is the head of the list *)\n      let: \"l\" := Snd !\"p\" in (* ... and whose second component is the rest of the list. *)\n      \"x\" + \"sum_list\" \"l\"\n    end.\n\n(** A function that increases all elements of a list in-place: *)\nDefinition inc_list : val :=\n  rec: \"inc_list\" \"n\" \"l\" :=\n    match: \"l\" with\n      NONE => #()\n    | SOME \"p\" =>\n      let: \"x\" := Fst !\"p\" in\n      let: \"l\" := Snd !\"p\" in\n      \"p\" <- (\"n\" + \"x\", \"l\");;\n      \"inc_list\" \"n\" \"l\"\n    end.\n\n(** The previous functions combined. *)\nDefinition sum_inc_list : val := λ: \"n\" \"l\",\n  inc_list \"n\" \"l\";;\n  sum_list \"l\".\n\n(** A function that maps a function over all elements of a list: *)\nDefinition map_list : val :=\n  rec: \"inc_list\" \"f\" \"l\" :=\n    match: \"l\" with\n      NONE => #()\n    | SOME \"p\" =>\n      let: \"x\" := Fst !\"p\" in\n      let: \"l\" := Snd !\"p\" in\n      \"p\" <- (\"f\" \"x\", \"l\");;\n      \"inc_list\" \"f\" \"l\"\n    end.\n\nSection proof.\nContext `{!heapG Σ}.\n\n(** Representation predicate in separation logic for a list of integers [l]: *)\nFixpoint is_list (l : list Z) (v : val) : iProp Σ :=\n  match l with\n  | [] => ⌜ v = NONEV ⌝\n  | x :: l' => ∃ (p : loc), ⌜ v = SOMEV #p ⌝ ∗\n                 ∃ v' : val, p ↦ (#x, v') ∗ is_list l' v'\n  end%I.\n\n(**\nIn order to give a specification of [sum_list] we relate its result to the\nsum defined as a pure Coq function.\n*)\nDefinition sum_list_coq (l : list Z) : Z :=\n  fold_right Z.add 0 l.\n\n(**\nThe proof of the recursive function [sum_list] requires some form of recursion.\nWe can either do the induction over the list [l], or use the Löb induction\nprinciple, given by the step-indexed nature of Iris. *)\n\n(** The proof using induction over [l]: *)\nLemma sum_list_spec_induction l v :\n  {{{ is_list l v }}} sum_list v {{{ RET #(sum_list_coq l); is_list l v }}}.\nProof.\n  iIntros (Φ) \"Hl Post\".\n  iInduction l as [|x l] \"IH\" forall (v Φ); simpl.\n  (**\n  Note that the option type is in fact encoded using sum types.\n  Hence, [NONE] is syntactic sugar for [InjL #()] (or [InjLV #()]\n  for values), and [SOME x] is syntactic sugar for [InjR x].\n  *)\n  - iDestruct \"Hl\" as %->.\n    wp_rec.\n    wp_match.\n    iApply \"Post\". iPureIntro. reflexivity.\n  - iDestruct \"Hl\" as (p) \"[-> Hl]\". iDestruct \"Hl\" as (v) \"[Hp Hl]\".\n    wp_rec.\n    wp_match.\n    wp_load. wp_proj. wp_let.\n    wp_load. wp_proj. wp_let.\n    wp_apply (\"IH\" with \"Hl\"). iIntros \"Hl\". wp_op.\n    iApply \"Post\".\n    iExists p. iSplitR; [done|].\n    iExists v. iSplitR \"Hl\"; [iApply \"Hp\"|iApply \"Hl\"].\nQed.\n\n(** The proof using Löb induction. The parts which are in common with\n[sum_list_spec_induction] are shortened using automation. *)\nLemma sum_list_spec_löb l v :\n  {{{ is_list l v }}} sum_list v {{{ RET #(sum_list_coq l); is_list l v }}}.\nProof.\n  iIntros (Φ) \"Hl Post\".\n  iLöb as \"IH\" forall (l v Φ). destruct l as [|x l]; simpl; wp_rec.\n  - iDestruct \"Hl\" as %->. wp_match. by iApply \"Post\".\n  - iDestruct \"Hl\" as (p -> v) \"[Hp Hl]\". wp_match.\n    do 2 (wp_load; wp_proj; wp_let).\n    wp_apply (\"IH\" with \"Hl\"). iIntros \"Hl\". wp_op.\n    iApply \"Post\". eauto with iFrame.\nQed.\n\n(** *Exercise*: Do the proof of [inc_list] yourself. Use ordinary induction. *)\nLemma inc_list_spec_induction n l v :\n  {{{ is_list l v }}}\n    inc_list #n v\n  {{{ RET #(); is_list (map (Z.add n) l) v }}}.\nProof.\n  iIntros (Φ) \"Hl Post\".\n  iInduction l as [|x l] \"IH\" forall (v Φ); simpl.\n  - iDestruct \"Hl\" as %->.\n    wp_rec. wp_let. wp_match.\n    by iApply \"Post\".\n  - iDestruct \"Hl\" as (p) \"[-> Hl] /=\". iDestruct \"Hl\" as (v) \"[Hp Hl]\".\n    wp_rec. wp_let.\n    wp_match.\n    wp_load. wp_proj. wp_let.\n    wp_load. wp_proj. wp_let.\n    wp_op. wp_store.\n    wp_apply (\"IH\" with \"Hl\"). iIntros \"Hl\".\n    iApply \"Post\".\n    iExists p. iSplitR; [done|].\n    iExists v. iSplitR \"Hl\"; [iApply \"Hp\"|iApply \"Hl\"].\nQed.\n\n(** *Exercise*: Now do the proof again using Löb induction. *)\nLemma inc_list_spec_löb n l v :\n  {{{ is_list l v }}}\n    inc_list #n v\n  {{{ RET #(); is_list (map (Z.add n) l) v }}}.\nProof.\n  iIntros (Φ) \"Hl Post\".\n  iLöb as \"IH\" forall (l v Φ). destruct l as [|x l]; simpl; wp_rec; wp_let.\n  - iDestruct \"Hl\" as %->. wp_match. by iApply \"Post\".\n  - iDestruct \"Hl\" as (p -> v) \"[Hp Hl] /=\". wp_match.\n    do 2 (wp_load; wp_proj; wp_let). wp_op. wp_store.\n    wp_apply (\"IH\" with \"Hl\"). iIntros \"Hl\".\n    iApply \"Post\". eauto with iFrame.\nQed.\n\n(** *Exercise*: Do the proof of [sum_inc_list] by making use of the lemmas of\n[sum_list] and [inc_list] we just proved. Make use of [wp_apply]. *)\nLemma sum_inc_list_spec n l v :\n  {{{ is_list l v }}}\n    sum_inc_list #n v\n  {{{ RET #(sum_list_coq (map (Z.add n) l)); is_list (map (Z.add n) l) v }}}.\nProof.\n  iIntros (Φ) \"Hl Post\". do 2 wp_let.\n  wp_apply (inc_list_spec_induction with \"Hl\"); iIntros \"Hl /=\"; wp_seq.\n  wp_apply (sum_list_spec_induction with \"Hl\"); auto.\nQed.\n\n(** *Optional exercise*: Prove the following spec of [map_list] which makes use\nof a nested Texan triple, This spec is rather weak, as it requires [f] to be\npure, if you like, you can try to make it more general. *)\nLemma map_list_spec_induction (f : val) (f_coq : Z → Z) l v :\n  (∀ n, {{{ True }}} f #n {{{ RET #(f_coq n); True }}}) -∗\n  {{{ is_list l v }}} map_list f v {{{ RET #(); is_list (map f_coq l) v }}}.\nProof.\n  iIntros \"#Hf\" (Φ) \"!# Hl Post\".\n  iLöb as \"IH\" forall (l v Φ). destruct l as [|x l]; simpl; wp_rec; wp_let.\n  - iDestruct \"Hl\" as %->. wp_match. by iApply \"Post\".\n  - iDestruct \"Hl\" as (p -> v) \"[Hp Hl] /=\". wp_match.\n    do 2 (wp_load; wp_proj; wp_let).\n    wp_apply (\"Hf\" with \"[//]\"); iIntros \"_ /=\".\n    wp_store.\n    wp_apply (\"IH\" with \"Hl\"). iIntros \"Hl\".\n    iApply \"Post\". eauto with iFrame.\nQed.\nEnd proof.\n", "meta": {"author": "alxest", "repo": "iris-tutorial", "sha": "abb59f9c827463e2b5dd45aa912987b2201d6744", "save_path": "github-repos/coq/alxest-iris-tutorial", "path": "github-repos/coq/alxest-iris-tutorial/iris-tutorial-abb59f9c827463e2b5dd45aa912987b2201d6744/solutions/ex_02_sumlist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.7369553949605466}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.ZArith.Znumtheory.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.Tactics.DivideExistsMul.\nRequire Import Crypto.Util.Tactics.DestructHead.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma divide_mul_div: forall a b c (a_nonzero : a <> 0) (c_nonzero : c <> 0),\n    (a | b * (a / c)) -> (c | a) -> (c | b).\n  Proof.\n    intros ? ? ? ? ? divide_a divide_c_a; do 2 Z.divide_exists_mul.\n    rewrite divide_c_a in divide_a.\n    rewrite Z.div_mul' in divide_a by auto.\n    replace (b * k) with (k * b) in divide_a by ring.\n    replace (c * k * k0) with (k * (k0 * c)) in divide_a by ring.\n    rewrite Z.mul_cancel_l in divide_a by (intuition auto with nia; rewrite H in divide_c_a; ring_simplify in divide_a; intuition).\n    eapply Zdivide_intro; eauto.\n  Qed.\n\n  Lemma divide2_even_iff : forall n, (2 | n) <-> Z.even n = true.\n  Proof.\n    intros n; split. {\n      intro divide2_n.\n      Z.divide_exists_mul; [ | pose proof (Z.mod_pos_bound n 2); lia].\n      rewrite divide2_n.\n      apply Z.even_mul.\n    } {\n      intro n_even.\n      pose proof (Zmod_even n) as H.\n      rewrite n_even in H.\n      apply Zmod_divide; lia || auto.\n    }\n  Qed.\n\n  Lemma divide_pow_le b n m : 0 <= n <= m -> (b ^ n | b ^ m).\n  Proof.\n    intros. replace m with (n + (m - n)) by ring.\n    rewrite Z.pow_add_r by lia.\n    apply Z.divide_factor_l.\n  Qed.\n\n  Lemma mod_divide_full a b : (a mod b = 0) <-> (b | a).\n  Proof.\n    destruct (Z_zerop b); auto using Z.mod_divide; subst; [].\n    rewrite Zmod_0_r; cbv [Z.divide]; intuition (destruct_head'_ex; subst; try exists 0; lia).\n  Qed.\n\n  Lemma mod_div_mod_full a m n : (n | m) -> a mod n = (a mod m) mod n.\n  Proof.\n    intros (p,Hp); rewrite (Z_div_mod_eq_full a m) at 1.\n    rewrite Hp at 1.\n    destruct (Z_zerop n); subst; try now autorewrite with zsimplify_const.\n    rewrite Z.mul_shuffle0, Z.add_comm, Z.mod_add; auto.\n  Qed.\n  #[global]\n   Hint Rewrite <- mod_div_mod_full using assumption : zsimplify push_Zmod.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/Divide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7368881502244207}}
{"text": "Require Import Ashley.Axioms.\nRequire Import Ashley.Logic.\nRequire Import Ashley.Logic.Unary.\n\n(*\nRequire Import Ashley.Set.\nRequire Import Ashley.Topology.\nRequire Import Ashley.Function.\n*)\nCheck O.\nCheck nat.\nCheck Set.\nCheck Type.\nCheck Prop.\nCheck gt.\nCheck S.\nCheck 34.\nCheck (3 > 0).\nCheck (0 = 0).\nCheck ((0 = 0) = (0 = 1)).\nCheck True.\n\nSection Test.\n\nVariables A B C : Prop.\n\nLemma abbcac: (A -> B) -> (B -> C) -> A -> C.\nintro ab.\nintro bc.\nintro a.\napply bc.\napply ab.\napply a.\nSave.\n\nLemma orc: A \\/ B -> B \\/ A.\nintro ab.\nelim ab.\nclear ab.\nright.\napply H.\nleft.\napply H.\nSave.\n\nCheck orc.\nPrint orc.\n\n\nCheck bool.\nPrint bool.\n\nEnd Test.\n\nCheck true.\n\nParameter Other : Prop.\nAxiom Tertium : ~~Other.\n\nLemma Tertium_collapse: Other.\nassume_not.\napply Tertium.\napply H.\nSave.\n\nDefinition pqr : Prop -> Prop -> Prop := fun a b => a \\/ b.\nDefinition pqr1 : nat -> nat -> nat := fun a b => a + b.\n\n\n\n\n\nRequire Import Coq.Reals.Reals.\n\nPrint R.\n\nLocal Open Scope R_scope.\n\nDefinition zz : R := 0.\n\nCheck Rmax.\nPrint Rmax.\n\nClass Fuzzy (F : Prop -> R) (very : Prop -> Prop) : Type :=\n{\n  fuzzy_lower_bound : forall a, F a >= 0;\n  fuzzy_upper_bound : forall a, F a <= 1;\n  fuzzy_false : F False = 0;\n  fuzzy_implies : forall a b : Prop, F (a -> b) = 1 + (Rmin (F b - F a) 0);\n  fuzzy_very: forall a, F (very a) = (F a) * (F a)\n}.\n\nSection Fuzzy.\nContext `{fuzzy:Fuzzy}.\n\nLemma fuzzy_true : F True = 1.\ntransitivity (F (True -> True)).\ncut ((True -> True) = True).\nintros.\nrewrite H.\ntrivial.\napply prop_ext.\nsplit.\nintros.\ntrivial.\nintros.\ntrivial.\nrewrite fuzzy_implies.\n\n????.\n\nauto.\n\nLemma fuzzy_not : forall a:Prop, F(~a) = 1 - F(a).\nintros.\nrewrite (fuzzy_implies a False).\nrewrite fuzzy_false.\nunfold Rmin.\nauto.\n\nLemma fuzzy_and : forall a b:Prop, F(a /\\ b) = Rmin (F a) (F b).\nintros.\n\n\n\nEnd Fuzzy.\n\n\n\n\nClass Modal (U : Prop -> Prop) : Type :=\n{\n  modal_N1 : U True;\n  modal_N2 : forall a b, (U a -> U b) -> U (a -> b);\n  modal_K : forall (a:Prop) (b:Prop), U (a -> b) -> U a -> U b\n}.\n\nSection Modal.\n\nContext `{M:Modal}.\n\nLemma thing: U (False -> True).\n\nLemma modal_collapse_with_prop_ext : forall a:Prop, a -> U a.\nintros.\ncut (a = True).\nintros.\nrewrite H0.\napply modal_N.\napply prop_ext.\nsplit.\ntrivial.\nintro.\napply H.\nSave.\n\n\nEnd Modal.\n", "meta": {"author": "AshleyYakeley", "repo": "maths", "sha": "42d4de811802c553d8bf0dcd69902ea01dda9a3e", "save_path": "github-repos/coq/AshleyYakeley-maths", "path": "github-repos/coq/AshleyYakeley-maths/maths-42d4de811802c553d8bf0dcd69902ea01dda9a3e/coq/scratch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7368881381837481}}
{"text": "(** * ProofsAndPrograms: The Fundamentals of the Coq Proof Assistant *)\n\n\n(** Ignore this line *)\nSet Warnings \"-notation-overridden,-parsing\".\n\n(* ################################################################# *)\n(** * Programs *)\n\n(** Let's start by defining a simple inductive datatype, corresponding\n   to a coin: *)\n\nInductive coin : Type :=\n| heads : coin\n| tails : coin.\n\n(** We can define a function [flip] that turns the coin over: *)\n\nDefinition flip (c : coin) : coin :=\n  match c with\n  | heads => tails\n  | tails => heads\n  end.\n\n(** Let's look at a few examples of coin flips. *)\n\nCompute (flip heads).\nCompute (flip tails).\n\n(** You might notice that this coin corresponds to a boolean value.\n   Conveniently, Coq makes the same observation! This allows us to\n   write an alternative definition of flip. *)\n\nDefinition flip' (c : coin) := if c then tails else heads.\n\nCompute (flip' heads).\nCompute (flip' tails).\n\n(** In general, Coq will allow us to use its conditional statement for\n   any datatype with two constructors. The first constructor will be\n   treated as [true] and the second as [false]. This [if] statement is\n   really just notation for the corresponding [match] statement. *)\n\n(** We will often want to check the types of various objects from\n   [coin] to coins to functions. For this we use the [Check]\n   command. *)\n\nCheck heads.\nCheck coin.\nCheck flip.\nCheck (flip heads).\n\n(** Let's look at a slightly more complicated datatype corresponding to\n   a play in the game Rock-Paper-Scissors: *)\n\nInductive play : Type :=\n| rock : play\n| paper : play\n| scissors : play.\n\n(** There are three possible outcomes: a win a loss and a tie. *)\nInductive outcome : Type :=\n| win : outcome\n| loss : outcome\n| tie : outcome.\n\n(** We can use these to define a game of Rock-Paper-Scissors. *)\n\nDefinition game (p1 p2 : play) : outcome :=\n  match p1, p2 with\n  | rock, scissors  => win\n  | scissors, paper => win\n  | paper, rock     => win\n  | scissors, rock  => loss\n  | paper, scissors => loss\n  | rock, paper     => loss\n  | _, _            => tie\n  end.\n\n(** That's pretty wordy, even given our use of wildcard characters to\n   capture the three remaining cases, where both players tie. It would\n   be nice if there were some way to express 'A beats B' and then use\n   that to define losses. *)\n\n(** Fortunately, Coq has the ability to define exactly that through its\n   use of propositions. *)\n\n(* ################################################################# *)\n(** * Propositions *)\n\n(** A predicate in Coq, which has the type [Prop], expresses the truth\n   of a given claim. Let's define a prop corresponding to 'A beats B'.\n   *)\n\nInductive beats : play -> play -> Prop :=\n| crushes : beats rock scissors\n| cuts    : beats scissors paper\n| covers  : beats paper rock.\n\n(** Since [beats] takes any two plays to a Prop, both of the following\n   are valid propositions. *)\n\nCheck (beats rock scissors).\nCheck (beats rock rock).\n\n(** The important difference between [beats rock scissors] and [beats\n   rock rock] is that [beats rock scissors] is _True_. For a Prop to\n   be true means that there is an element of that type. *)\n\nCheck crushes.\n\n(** It so happens that [beats rock rock] is _False_, but showing its\n   falsity is somewhat complicated. We'll return to the subject of\n   falsity later in this chapter.  *)\n\n(** It's worth noting that 'Prop' isn't special. We could replace every\n   instance of Prop in this chapter with 'Type' and nothing would\n   break. The significance of 'Prop' lies in its interpretation: We\n   treat 'beats' not as a Type that depends on two plays but as a\n   _claim_ about those two plays. *)\n\n(** We can easily define [loses] and [ties]: *)\n\nInductive loses : play -> play -> Prop :=\n| crushed  : loses scissors rock\n| cut      : loses paper scissors\n| covered  : loses rock paper.\n\nInductive ties : play -> play -> Prop :=\n| tie_rock : ties rock rock\n| tie_paper : ties paper paper\n| tie_scissors : ties scissors scissors.\n\n(** Time to start proving things!  \n   Here's a simple claim : If A beats B, then B loses to A. *)\n\nDefinition beats_backwards_loses (p1 p2 : play) (b : beats p1 p2) : loses p2 p1 :=\n  match b with\n  | crushes => crushed\n  | cuts    => cut\n  | covers  => covered\n  end.\n\n(** In fact, we could have simply defined '[loses] in terms of [beats]! *)\n\nDefinition loses' (p1 p2 : play) := beats p2 p1.\n\n(** **** Exercise: 2 stars (loses_then_loses')  *)\n(** Show that these two definitions of [loses] are equivalent. *)\n\nDefinition loses_then_loses' (p1 p2 : play) (l : loses p1 p2) : loses' p1 p2 \n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nDefinition loses'_then_loses (p1 p2 : play) (l : loses' p1 p2) : loses p1 p2 \n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** [] *)\n\n\n(** Our examples above didn't involve any computation - we haven't even\n   defined any (traditional) functions on plays. Let's try proving\n   some things about coin flipping.  *)\n\n(** First, we will introduce two predicates on pair of coins: *)\n\nInductive same : coin -> coin -> Prop :=\n| same_heads : same heads heads \n| same_tails : same tails tails.\n\nInductive inverse : coin -> coin -> Prop :=\n| heads_tails : inverse heads tails \n| tails_heads : inverse tails heads.\n\n(** Let's first show that flipping always yields an inverse. *)\nDefinition flip_inverse (c : coin) : inverse c (flip c) :=\n  match c with\n  | heads => heads_tails\n  | tails => tails_heads\n  end.\n\n(** We can also show that flipping a coin twice yields the original\n   coin. *)\n\nDefinition flip_involutive (c : coin) : same c (flip (flip c)) :=\n  match c with\n  | heads => same_heads\n  | tails => same_tails\n  end.\n\n(** Just like any coq term, we can reuse earlier proofs: *)\n\nDefinition flip_thrice (c : coin) : same (flip c) (flip (flip (flip c))) \n(* WORKED IN CLASS *) :=\n  flip_involutive (flip c).\n\n\n(* ################################################################# *)\n(** * Logic *)\n\n(** Now that we know how to prove things, it would be nice to have some\n   logical connectives, like [and] and [or] to increase the\n   expressiveness of our logic. It would also be nice to have more\n   tools for logical reasoning, which we will develop in this section.\n   *)\n\n(* ================================================================= *)\n(** ** Logic 101 *)\n\n(** Let's start off with a simple rule of logic: Modus Ponens Modus\n   Ponens says that if X -> Y and X are true, so is Y.  In our\n   context, that means that from a function of type [X -> Y] and a\n   term of type [X], we can construct a [Y]. *)\n\nDefinition modus_ponens (X Y : Prop) (P : X -> Y) (x : X) : Y := P x.\n\n(** Note that Modus Ponens is simply function application! *)\n\n(** Here's the chain rule, which corresponds to function composition: *)\nDefinition chain_rule (X Y Z : Prop) (P : X -> Y) (Q : Y -> Z) : X -> Z :=\n  fun x => Q (P x).\n\n(** We know that a [Prop] is true if it has any elements. A false\n   [Prop] would then be a Prop without any elements. While many Props\n   are true and many are false, it's worth having at least one\n   archetypal [True] and [False]. *)\n\nInductive True := t.\nInductive False := .\n\n(** [False] is actually a really exciting thing to prove. If I can\n   construct an element of [False], I can obtain whatever I want -\n   even elements of other uninhabited Props! *)\n\nDefinition ex_falso_quodlibet (X : Prop) (f : False) : X :=\n  match f with\n  end.\n\n(** **** Exercise: 2 stars (X_then_X)  *)\n(** State and prove the theorem that for any X, X implies X. *)\n\n(** What does this correspond to computationally? *)\n\n\n(** We can now use our chain rule to reverse modus ponens. *)\n\nDefinition modus_tollens (X Y : Prop) : (X -> Y) -> (Y -> False) -> (X -> False) :=\n  chain_rule X Y False.\n\n(* ================================================================= *)\n(** ** And and Or *)\n(** Let's define some standard logical connectives: *)\n\nInductive and (X Y : Prop) : Prop :=\n  conj : X -> Y -> and X Y.\n\nInductive or (X Y : Prop) : Prop :=\n | or_introl : X -> or X Y\n | or_intror : Y -> or X Y.\n\n(** The following commands just say that we don't need to provide type\n    arguments to our constructors of [and] and [or]. *) \nArguments conj {X Y}.\nArguments or_introl {X Y}.\nArguments or_intror {X Y}.\n\n(** We can also introduce some notations for these connectives: *)\nInfix \"/\\\" := and : type_scope. \nInfix \"\\/\" := or : type_scope.\n\n(** From the perspective of functional programming, [and] and [or] are\n    just product types and sum types respectively. Indeed, the Coq\n    standard library separately defines [A * B] and [A + B] over\n    [Type]s. But it's useful to have these for Props as well. *)\n\n(** What can we prove about [and] and [or]?\n   Some basic properties include symmetry and associativity. *)\n\nDefinition and_symm (X Y : Prop) : X /\\ Y -> Y /\\ X \n(* WORKED IN CLASS *) :=\n  fun xy =>\n  match xy with\n  | conj x y => conj y x\n  end.\n                                              \n(** **** Exercise: 2 stars (or_symm)  *)\n(** Prove a similar theorem for `or` *)\n\nDefinition or_symm (X Y : Prop) : X \\/ Y -> Y \\/ X \n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** [] *)\n\nDefinition and_assoc (X Y Z : Prop) : (X /\\ Y) /\\ Z -> X /\\ (Y /\\ Z)  \n(* WORKED IN CLASS *) :=\n  fun xyz =>\n  match xyz with\n  | conj (conj x y) z => conj x (conj y z)\n  end.\n\n(* ################################################################# *)\n(** * The Proof Environment *)\n\n(** Unfortunately, these proofs can get pretty heavy, especially when\n   there are a lot of cases to match on. For instance, consider the\n   following proof that [or] is associative. *)\n\nDefinition or_assoc (X Y Z : Prop) : (X \\/ Y) \\/ Z -> X \\/ (Y \\/ Z) :=\n  fun xyz =>\n    match xyz with\n    | or_introl xy => match xy with\n                     | or_introl x => or_introl x\n                     | or_intror y => or_intror (or_introl y)\n                     end\n    | or_intror z => or_intror (or_intror z)\n    end.\n\n(** And it just gets messier from here. *)\n\n(** Instead of having to write out Coq proofs as complicated programs\n    involving multiple levels of matching, function application and so\n    forth, Coq provides a convenient environment for building proofs,\n    step by step.\n\n   Here's [and_symm] again: *)\n\nLemma and_symm' (X Y : Prop) : X /\\ Y -> Y /\\ X.\nProof.\n(* WORKED IN CLASS *)\n  intros xy.             (* introduce the hypotheses *)\n  destruct xy as [x y].  (* case analysis *)\n  apply (conj y x).      (* apply a term *)\nQed.\n\n(** Since in lemmas we don't reference X and Y on the right hand side\n    of [:=], we tend to name all of our arguments on the right side of\n    the [:] We can also apply [conj] and fill in X and Y later. *)\n\nLemma and_symm'' : forall (X Y : Prop), X /\\ Y -> Y /\\ X.\nProof.\n  intros X Y xy.\n  destruct xy as [x y].\n  apply conj.\n  apply y.\n  apply x.\nQed.\n\n(** Let's return to `or_assoc` *)\n\nLemma or_assoc' : forall (X Y Z : Prop), (X \\/ Y) \\/ Z -> X \\/ (Y \\/ Z).\nProof.\n  (* WORKED IN CLASS *)\n  intros X Y Z xyz.\n  destruct xyz as [xy | z].\n  (* Two goals! We can address each separately. *)\n  - destruct xy as [x | y].\n    + apply or_introl.\n      apply x.\n    + apply or_intror.\n      apply or_introl.\n      apply y.\n  - apply or_intror.\n    apply or_intror.\n    apply z.\nQed.\n\n(** **** Exercise: 3 stars (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall X Y Z : Prop,\n  X \\/ (Y /\\ Z) -> (X \\/ Y) /\\ (X \\/ Z).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ================================================================= *)\n(** ** Constructive Logic *)\n\n(** Since Coq requires us to construct a term in order to demonstrate\n    that a type is inhabited, not all theorems of classical logic are\n    true in Coq's own logic. *)\n\nLemma excluded_middle : forall (X : Prop), X \\/ (X -> False).\nProof.\n    intros X.\n  (* Unfortunately, we can't proceed as we have no hypotheses\n     and no elements of type X or X -> False *)\n  Abort.\n\n(** The law of double negation is more interesting: *)\n\nDefinition double_negation_forwards : forall (X : Prop), X -> ((X -> False) -> False). \nProof.\n  (* WORKED IN CLASS *)\n  intros X x.\n  intros nx.\n  apply nx.\n  apply x.\nQed.\n  \nDefinition double_negation_backwards : forall (X : Prop), ((X -> False) -> False) -> X. \nProof.\n    intros X nnx.\n  (* Once again, there's no clear way to proceed. Indeed \n     ~ ~ X -> X is not a theorem of Coq's logic *)\n  Abort.\n\n(** Jumping back to our game of rock-paper-scissors, using the proof\n    system it's not hard to prove some basic theorems. *)\n\nLemma beats_same : forall (x y y' : play), beats x y -> ties y y' -> beats x y'.\nProof.\n  (* WORKED IN CLASS *)\n  intros x y y' B T.\n  destruct T.\n  - apply B.\n  - apply B.\n  - apply B.  \nQed.  \n  \n(** Here's a more succinct definition of [ties]: *)\n\nInductive ties' : play -> play -> Prop :=\n| ties_same : forall (p : play), ties' p p.\n                            \n(** Let's try proving the theorem above in our new system. *)\n\nLemma beats_same' : forall (x y y' : play), beats x y -> ties' y y' -> beats x y'.\nProof.\n  (* WORKED IN CLASS *)\n  intros x y y' B T.\n  destruct T as [t].\n  apply B.\nQed.  \n  \n(** **** Exercise: 2 stars (ties_symm)  *)\n(** Using the new definition, prove that if a ties b then b ties a *)\nTheorem ties_symm : forall (x y : play), ties' x y -> ties' y x.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n\n\n\n\n\n(* ################################################################# *)\n(** * Equality *)\n\n(** Note that we separately defined [ties] and [same] for plays and\n    coins.  Wouldn't it be nice if we could define a single proposition\n    for any type that claims two terms of that type are identical? *)\n\nInductive eq (A : Type) : A -> A -> Prop :=\n  | eq_refl : forall (a : A), eq A a a.\n\nNotation \"x == y\" := (eq _ x y) (at level 70): type_scope.\n\n(** Of course, there are other, arguably more useful ways to define\n    equality.  Here's Leibniz's definition (and, as far as we know, not\n    Newton's): *)\n\nDefinition Leq (A : Type) (a b : A) : Prop := forall (P : A -> Prop), P a -> P b.  \n\nNotation \"x =L y\" := (Leq _ x y) (at level 70): type_scope.\n\n(** That is, 'a' is equal to 'b' if everything true of 'a' is true of\n    'b'. *) \n\n(** Let's show that Leq is at least as strong as eq. *)\n\nLemma Leq_then_eq : forall (A : Type) (a b : A), a =L b -> a == b.\nProof.\n  (* WORKED IN CLASS *)\n  intros A a b L.\n  unfold Leq in L.\n  apply L.\n  apply eq_refl.\nQed.\n  \nPrint Leq_then_eq.\n\n(** Let's try going in the opposite direction. *)\n\nLemma eq_then_Leq : forall (A : Type) (a b : A), a == b -> a =L b.\nProof.\n  intros A a b H.\n  unfold Leq.\n  intros P p.\n  destruct H.\n  apply p.\nQed.\n\n(** For convenience, we can package these up into a single claim. *)\n\nDefinition iff (A B : Prop) := (A -> B) /\\ (B -> A).\nNotation \"A <-> B\" := (iff A B) (at level 95) : type_scope.\n\nDefinition eq_Leq (A : Type) (a b : A) : a == b <-> a =L b :=\n  conj (eq_then_Leq A a b) (Leq_then_eq A a b).\n\n(** What does this tell us? It says that it's okay to replace a with b\n    throughout a proposition if we know that [eq a b]. Let's try it\n    out. *)\n\nLemma inverse_of_flip : forall (x y : coin), flip x == y -> inverse x y.\nProof.\n  (* WORKED IN CLASS *)\n  intros x y H.\n  apply (eq_then_Leq coin (flip x) y).\n  apply H.\n  Search inverse.\n  apply flip_inverse.\nQed.\n  \n(** This observation forms the basis of Coq's [rewrite] rule, which\n    uses a hypotheses of the form [a = b] to replace all instances of\n    [a] with [b] in a proposition.  We'll use Coq's standard library\n    equality (which is identical to our own) to illustrate: *)\n\nLemma eq_trans : forall (A : Type) (a b c : A), a = b -> b = c -> a = c.\nProof.\n  intros A a b c H H0.\n  rewrite H.\n  apply H0.\nQed.\n\n(** **** Exercise: 1 star (eq_trans')  *)\n(** Exercise: Prove this using our version of eq, which doesn't have\n    [rewrite]. **)\n(** Remove \"[Admitted.]\" and fill in the proof. *)\n\nLemma eq_trans' : forall (A : Type) (a b c : A),  a == b -> b == c -> a == c.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (y_is_nice)  *)\n(** Exercise: Use one of the lemmas above to prove that y\n    is nice **)\n(** Remove \"[Admitted.]\" and fill in the proof. *)\nLemma y_is_nice : forall (X : Type) (x y : X) (nice : X -> Prop),\n    x == y -> nice x -> nice y.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n    \n", "meta": {"author": "jonlin1000", "repo": "coq_practice", "sha": "21e55ad57b885bc1f1afb9fb568e4a9b3cedb356", "save_path": "github-repos/coq/jonlin1000-coq_practice", "path": "github-repos/coq/jonlin1000-coq_practice/coq_practice-21e55ad57b885bc1f1afb9fb568e4a9b3cedb356/ProofsAndPrograms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.7368470570495002}}
{"text": "Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nInductive maybe (A : Set) (P : A -> Prop) : Set := \n| Unknown : maybe P\n| Found   : forall x : A, P x -> maybe P.\n\nNotation \"{{ x | P }}\" := (maybe (fun x => P)). \nNotation \"??\" := (@Unknown _ _).\nNotation \"[| x |]\" := (@Found _ _ x _).\n\nProgram Definition pred_strong7(n: nat):  {{m | n = m + 1}} :=\n match n return {{m | n = m + 1}} with\n  | 0 => ??\n  | n'.+1 => [| n' |]\n  end.\n\nNext Obligation. by rewrite addn1. Qed.\n\n\n", "meta": {"author": "ilyasergey", "repo": "coq-exercises", "sha": "97b610ca2a654b6edd329f3791cab5534ddc1cb2", "save_path": "github-repos/coq/ilyasergey-coq-exercises", "path": "github-repos/coq/ilyasergey-coq-exercises/coq-exercises-97b610ca2a654b6edd329f3791cab5534ddc1cb2/cptd-ssr/cpdt-chapter6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7367576428770711}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf2 : natural) : natural :=\n  plus lf2 (mult z y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj222_coqofml_s7INK2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7367534653001634}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (x : natural) : natural :=\n  plus lf2 (mult lf2 x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj142_coqofml_5j8SXD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7367534609784575}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus Zero (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj259_coqofml_rtjpRa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7367534598528158}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_midpoint :\n\tforall A B C,\n\tBetS A B C ->\n\tCong A B B C ->\n\tMidpoint A B C.\nProof.\n\tintros A B C.\n\tintros BetS_A_B_C.\n\tintros Cong_AB_BC.\n\n\tunfold Midpoint.\n\tsplit.\n\texact BetS_A_B_C.\n\texact Cong_AB_BC.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_midpoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7367534591626751}}
{"text": "(*** *********************** ***)\n(*** TOWERS OF HANOI - DISCS ***)\n(*** *********************** ***)\n\n(* James Power * James.Power@May.ie * http://www.cs.may.ie/~jpower/ *)\n(* Dept. of Computer Science, NUI Maynooth, Co. Kildare, Ireland.   *)\n\n(* This file is part of the Towers of Hanoi in ILL example\n * In it, we define the discs and the \"smaller\" relation\n * as well as some lemmas relating to quantification over disc-lists\n *)\n\nFrom Coq Require Import List.\nImport ListNotations.\nNotation Empty := (@nil _).\n\n(*************)\n(*** DISCS ***)\n(*************)\n\nParameter Disc : Set.\n\nParameter smaller : Disc -> Disc -> Prop.\n\nAxiom smallTrans :\n  forall (x y z:Disc), (smaller x y) -> (smaller y z) -> (smaller x z).\n\n(* Can we transfer a disc onto a pole? *)\nDefinition canTxfrTo : Disc -> list Disc -> Prop :=\n  fun (d:Disc) (ds:list Disc) =>\n  (Forall (fun d':Disc => smaller d d') ds).\n\n(* Can we move a disc-list onto a pole? *)\nDefinition canMoveTo : list Disc -> list Disc -> Prop :=\n  fun d1 d2:list Disc =>\n  (Forall (fun d':Disc => canTxfrTo d' d2) d1).\n\n(* When is a list of discs in order? *)\nInductive ordered : list Disc -> Prop :=\n  ord_nil : ordered Empty\n| ord_cons : forall (d:Disc)(ds:list Disc),\n             canTxfrTo d ds -> ordered ds -> ordered (cons d ds).\n\n\nLemma CanMoveEmpty\n  (ds:list Disc): canMoveTo ds Empty.\nProof.\ninduction ds; unfold canMoveTo.\napply Forall_nil.\nintros; unfold canTxfrTo; apply Forall_cons; [ apply Forall_nil| assumption].\nQed.\n\n\nLemma CanMoveApp\n  (ds d1 d2:list Disc):\n  canMoveTo ds d1 -> canMoveTo ds d2 -> canMoveTo ds (d1++d2).\nProof.\ninduction ds as [|a l IH].\nintros; simpl; unfold canMoveTo; apply Forall_nil.\nintros CM1 CM2.\nunfold canMoveTo in CM1; inversion CM1.\nunfold canMoveTo in CM2; inversion CM2.\nunfold canMoveTo; apply Forall_cons.\nunfold canTxfrTo; apply Forall_app; split; assumption.\napply IH; assumption.\nQed.\n\n\nLemma OrdCat\n  (d1 d2:list Disc): ordered (d1++d2) -> ordered d1.\nProof.\ninduction d1 as [|a l IH].\nintros; apply ord_nil.\nintros ORD.\nsimpl in ORD; inversion ORD; apply ord_cons.\nunfold canTxfrTo; unfold canTxfrTo in H1;\n  apply Forall_app with (l1:=l) (l2:=d2); assumption.\napply (IH H2).\nQed.\n\nLemma OrdMove\n  (d1 d2:list Disc): ordered (d1++d2) -> canMoveTo d1 d2.\nProof.\ninduction d1 as [|a l IH].\nintros; unfold canMoveTo; apply Forall_nil.\nintros ORD; simpl in ORD; inversion ORD.\nunfold canMoveTo; unfold canMoveTo in IH; apply Forall_cons.\nunfold canTxfrTo; unfold canTxfrTo in H1.\napply Forall_app with (l1:=l) (l2:=d2); assumption.\napply IH; assumption.\nQed.\n", "meta": {"author": "ComputerAidedLL", "repo": "PowerWebster_ILL", "sha": "68c5becb1eec685f70f323828bbf822b0b21f317", "save_path": "github-repos/coq/ComputerAidedLL-PowerWebster_ILL", "path": "github-repos/coq/ComputerAidedLL-PowerWebster_ILL/PowerWebster_ILL-68c5becb1eec685f70f323828bbf822b0b21f317/discs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7367370926542702}}
{"text": "Require Import List.\nRequire Import String.\nRequire Import ZArith.\n\nDefinition var := string.\n\n(* expressions *)\nInductive Expr : Type :=\n| Int : Z -> Expr\n| Var : var -> Expr\n| Add : Expr -> Expr -> Expr\n| Mul : Expr -> Expr -> Expr.\n\n(* statements *)\nInductive Stmt : Type :=\n| Skip : Stmt\n| Assign : var -> Expr -> Stmt\n| Seq : Stmt -> Stmt -> Stmt\n| Cond : Expr -> Stmt -> Stmt -> Stmt\n| While : Expr -> Stmt -> Stmt.\n\nDefinition Heap := list (var * Z).\n\nFixpoint lkup (x: var) (h: Heap) :=\n  match h with\n    | nil => 0%Z\n    | (k, v) :: h' => if string_dec x k then v else lkup x h'\n  end.\n\nInductive Eval : Heap -> Expr -> Z -> Prop :=\n| EInt : forall h z,\n  Eval h (Int z) z\n| EVar : forall h v,\n  Eval h (Var v) (lkup v h)\n| EAdd : forall h e1 e2 c1 c2 c3,\n  Eval h e1 c1 ->\n  Eval h e2 c2 ->\n  c3 = (c1 + c2)%Z ->\n  Eval h (Add e1 e2) c3\n| EMul : forall h e1 e2 c1 c2 c3,\n  Eval h e1 c1 ->\n  Eval h e2 c2 ->\n  c3 = (c1 * c2)%Z ->\n  Eval h (Mul e1 e2) c3.\n\nInductive Step : Heap -> Stmt -> Heap -> Stmt -> Prop :=\n| SAssign : forall h v e c,\n  Eval h e c ->\n  Step h (Assign v e) ((v, c) :: h) Skip\n| SSeq1 : forall h s,\n  Step h (Seq Skip s) h s\n| SSeq2 : forall h s1 h' s1' s2,\n  Step h s1 h' s1' ->\n  Step h (Seq s1 s2) h' (Seq s1' s2)\n| SCondT : forall h e c s1 s2,\n  Eval h e c ->\n  c <> 0%Z ->\n  Step h (Cond e s1 s2) h s1\n| SCondF : forall h e c s1 s2,\n  Eval h e c ->\n  c = 0%Z ->\n  Step h (Cond e s1 s2) h s2\n| SWhileT : forall h e c s,\n  Eval h e c ->\n  c <> 0%Z ->\n  Step h (While e s) h (Seq s (While e s))\n| SWhileF : forall h e c s,\n  Eval h e c ->\n  c = 0%Z ->\n  Step h (While e s) h Skip.\n\nInductive StepN : Heap -> Stmt -> nat -> Heap -> Stmt -> Prop :=\n| StepN_refl : forall h s,\n  StepN h s 0 h s\n| StepN_step : forall h s h' s' h'' s'' n,\n  Step h s h' s' ->\n  StepN h' s' n h'' s'' ->\n  StepN h s (S n) h'' s''.\n\n(** Divergance *)\n\nDefinition canStep h s :=\n  exists h', exists s', Step h s h' s'.\n\nDefinition notSkip s :=\n  match s with\n  | Skip => False\n  | _ => True\n  end.\n\nLemma notSkip_canStep:\n  forall h s, notSkip s -> canStep h s.\nAdmitted.\n\nLemma diverges_take1:\n  forall h n, exists h', exists s',\n  StepN h (While (Int 1) Skip) n h' s'.\n  (* stuck *)\nAdmitted.\n\nLemma diverges_take2:\n  forall h n, exists h', exists s',\n  StepN h (While (Int 1) Skip) n h' s' /\\ s' <> Skip.\nProof.\nAdmitted.\n\nLemma diverges_take3:\n  forall h n,\n  StepN h (While (Int 1) Skip) n h (While (Int 1) Skip).\nProof.\nAdmitted.\n\nDefinition w1 := While (Int 1) Skip.\nDefinition w2 := Cond (Int 1) (Seq Skip (While (Int 1) Skip)) Skip.\nDefinition w3 := Seq Skip (While (Int 1) Skip).\n\nLemma diverges_take4:\n  forall h n, exists s,\n  StepN h (While (Int 1) Skip) n h s /\\\n  (s = w1 \\/ s = w2 \\/ s = w3).\nProof.\nAdmitted.\n\n(** Nonneg *)\n\n\n(** Interpreters *)\n\nLocate \"+\".\n\nFixpoint eval (h: Heap) (e: Expr) : Z :=\n  match e with\n    | Int z => z\n    | Var v => lkup v h\n    | Add e1 e2 => Z.add (eval h e1) (eval h e2)\n    | Mul e1 e2 => Z.mul (eval h e1) (eval h e2)\n  end.\n\n(* notree *)\nLemma eval_Eval:\n  forall h e c,\n  eval h e = c -> Eval h e c.\nProof.\n  intro. intro. induction e.\n  { intros. simpl in *. subst. constructor. }\n  { intros. simpl in *. rewrite <- H. constructor. }\n  { intros. simpl in *. econstructor.\n    { firstorder. }\n    { firstorder. }\n    { firstorder. }\n  }\n  { intros. simpl in *. econstructor.\n    { firstorder. }\n    { firstorder. }\n    { firstorder. }\n  }\nQed.\n\n(* notree *)\nLemma Eval_eval:\n  forall h e c,\n  Eval h e c -> eval h e = c.\nProof.\n  intros. induction H.\n  { reflexivity. }\n  { reflexivity. }\n  { subst. reflexivity. }\n  { subst. reflexivity. }\nQed.\n\n(* notree *)\nLemma Eval_eval':\n  forall h e,\n  Eval h e (eval h e).\nProof.\n  intros. remember (eval h e) as c. apply eval_Eval. omega.\nQed.\n\nCheck Z.eq_dec.\n\nDefinition isSkip (s: Stmt) : bool :=\n  match s with\n    | Skip => true\n    | _ => false\n  end.\n\n(* notree *)\nLemma isSkip_t:\n  forall s, isSkip s = true -> s = Skip.\nProof.\n  intros. destruct s.\n  { reflexivity. }\n  { discriminate. }\n  { discriminate. }\n  { discriminate. }\n  { discriminate. }\nQed.\n\n(* notree *)\nLemma isSkip_f:\n  forall s, isSkip s = false -> s <> Skip.\nProof.\n  intros. destruct s.\n  { discriminate. }\n  { discriminate. }\n  { discriminate. }\n  { discriminate. }\n  { discriminate. }\nQed.\n\nFixpoint step (h: Heap) (s: Stmt) : option (Heap * Stmt) :=\n  match s with\n    | Skip => None\n    | Assign v e => Some ((v, eval h e)::h, Skip)\n    | Seq s1 s2 =>\n      if isSkip s1 then\n        Some (h, s2)\n      else\n        match step h s1 with\n          | Some (h', s1') => Some (h', Seq s1' s2)\n          | None => None\n        end\n    | Cond e s1 s2 =>\n        if Z.eq_dec (eval h e) 0%Z then\n          Some (h, s2)\n        else\n          Some (h, s1)\n    | While e s =>\n        if Z.eq_dec (eval h e) 0%Z then\n          Some (h, Skip)\n        else\n          Some (h, Seq s (While e s))\n  end.\n\n(* notree *)\nLemma step_None_Skip:\n  forall h s, step h s = None -> s = Skip.\nProof.\n  intros. induction s.\n  { reflexivity. }\n  { simpl in *. inversion H. }\n  { simpl in *. destruct (isSkip s1) eqn:?.\n    { discriminate. }\n    { destruct (step h s1) eqn:?.\n      { destruct p. discriminate. }\n      { firstorder. apply isSkip_f in Heqb. firstorder. }\n    }\n  }\n  { simpl in *. destruct (Z.eq_dec (eval h e) 0) eqn:?.\n    { discriminate. }\n    { discriminate. }\n  }\n  { simpl in *. destruct (Z.eq_dec (eval h e) 0) eqn:?.\n    { discriminate. }\n    { discriminate. }\n  }\nQed.\n\n(* notree *)\nLemma step_Step:\n  forall h s h' s',\n  step h s = Some (h', s') -> Step h s h' s'.\nProof.\n  intro. intro. induction s.\n  { discriminate. }\n  { intros. simpl in *. inversion H. constructor. apply Eval_eval'. }\n  { intros. simpl in *. destruct (isSkip s1) eqn:?.\n    { apply isSkip_t in Heqb. inversion H. subst. constructor. }\n    { apply isSkip_f in Heqb. destruct (step h s1) eqn:?.\n      { destruct p. inversion H. subst. constructor. firstorder. }\n      { discriminate. }\n    }\n  }\n  { intros. simpl in *. destruct (Z.eq_dec (eval h e) 0) eqn:?.\n    { clear Heqs. inversion H. subst. apply eval_Eval in e0.\n      econstructor.\n      { eauto. }\n      { reflexivity. }\n    }\n    { clear Heqs. inversion H. subst. remember (eval h' e).\n      symmetry in Heqz. apply eval_Eval in Heqz.\n      econstructor.\n      { eauto. }\n      { assumption. }\n    }\n  }\n  { intros. simpl in *. destruct (Z.eq_dec (eval h e) 0) eqn:?.\n    { clear Heqs0. inversion H. subst. apply eval_Eval in e0.\n      econstructor.\n      { eauto. }\n      { reflexivity. }\n    }\n    { clear Heqs0. inversion H. subst. remember (eval h' e).\n      symmetry in Heqz. apply eval_Eval in Heqz.\n      econstructor.\n      { eauto. }\n      { assumption. }\n    }\n  }\nQed.\n\n(* notree *)\nLemma Step_step:\n  forall h s h' s',\n  Step h s h' s' -> step h s = Some (h', s').\nProof.\n  intros. induction H.\n  { simpl. apply Eval_eval in H. subst. constructor. }\n  { constructor. }\n  { simpl. destruct (isSkip s1) eqn:?.\n    { apply isSkip_t in Heqb. subst. inversion H. }\n    { rewrite IHStep. reflexivity. }\n  }\n  { simpl. destruct (Z.eq_dec (eval h e) 0) eqn:?.\n    { apply Eval_eval in H. omega. }\n    { reflexivity. }\n  }\n  { simpl. destruct (Z.eq_dec (eval h e) 0) eqn:?.\n    { reflexivity. }\n    { apply Eval_eval in H. omega. }\n  }\n  { simpl. destruct (Z.eq_dec (eval h e) 0) eqn:?.\n    { apply Eval_eval in H. omega. }\n    { reflexivity. }\n  }\n  { simpl. destruct (Z.eq_dec (eval h e) 0) eqn:?.\n    { reflexivity. }\n    { apply Eval_eval in H. omega. }\n  }\nQed.\n\nFixpoint stepn (h: Heap)  (s: Stmt) (n: nat) : option (Heap * Stmt) :=\n  match n with\n    | O => Some (h, s)\n    | S m =>\n      match step h s with\n        | Some st' => stepn (fst st') (snd st') m\n        | None => None\n      end\n  end.\n\n(* notree *)\nLemma stepn_StepN:\n  forall n h s h' s',\n  stepn h s n = Some (h', s') ->\n  StepN h s n h' s'.\nProof.\n  intro. induction n.\n  { intros. simpl in *. inversion H. subst. constructor. }\n  { intros. simpl in *. destruct (step h s) eqn:?.\n    { destruct p. simpl in *. econstructor.\n      { apply step_Step. eassumption. }\n      { apply IHn. eassumption. }\n    }\n    { discriminate. }\n  }\nQed.\n\n(* notree *)\nLemma StepN_stepn:\n  forall h s n h' s',\n  StepN h s n h' s' ->\n  stepn h s n = Some (h', s').\nProof.\n  intros. induction H.\n  { simpl. reflexivity. }\n  { simpl. destruct (step h s) eqn:?.\n    { destruct p. simpl. apply Step_step in H. congruence. }\n    { apply Step_step in H. congruence. }\n  }\nQed.\n\nFixpoint run (n: nat) (h: Heap)  (s: Stmt) : Heap * Stmt :=\n  match n with\n    | O => (h, s)\n    | S m =>\n      match step h s with\n        | Some (h', s') => run m h' s'\n        | None => (h, s)\n      end\n  end.\n\nInductive StepStar : Heap -> Stmt -> Heap -> Stmt -> Prop :=\n| StepStar_refl : forall h s,\n  StepStar h s h s\n| StepStar_step : forall h s h' s' h'' s'',\n  Step h s h' s' ->\n  StepStar h' s' h'' s'' ->\n  StepStar h s h'' s''.\n\n(* notree *)\nLemma run_StepStar:\n  forall n h s h' s',\n  run n h s = (h', s') -> StepStar h s h' s'.\nProof.\n  intro. induction n.\n  { intros. simpl in *. inversion H. subst. constructor. }\n  { intros. simpl in *. destruct (step h s) eqn:?.\n    { destruct p. econstructor.\n      { apply step_Step. eassumption. }\n      { apply IHn. assumption. }\n    }\n    { inversion H. subst. constructor. }\n  }\nQed.\n\n(* notree *)\nLemma nostep_run_refl:\n  forall h s, step h s = None ->\n  forall n, run n h s = (h, s).\nProof.\n  intros. destruct n.\n  { simpl. reflexivity. }\n  { simpl. rewrite H. reflexivity. }\nQed.\n\n(* notree *)\nLemma run_combine:\n  forall m n h s h' s' h'' s'',\n  run m h s = (h', s') ->\n  run n h' s' = (h'', s'') ->\n  run (m + n) h s = (h'', s'').\nProof.\n  intro. induction m.\n  { intros. simpl in *. inversion H. subst. assumption. }\n  { intros. simpl in *. destruct (step h s) eqn:?.\n    { destruct p. eapply IHm.\n      { eauto. }\n      { eauto. }\n    }\n    { inversion H. subst. apply nostep_run_refl with (n := n) in Heqo.\n      congruence.\n    }\n  }\nQed.\n", "meta": {"author": "Ptival", "repo": "PeaCoq", "sha": "4d186879910a327455e7b7b239d58a9502145680", "save_path": "github-repos/coq/Ptival-PeaCoq", "path": "github-repos/coq/Ptival-PeaCoq/PeaCoq-4d186879910a327455e7b7b239d58a9502145680/uw-cse-505/e06/E06_Interp_NoTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7367370843090394}}
{"text": "(** * Utheory.v: Specification of [U], interval [ [0,1] ] *)\n\nRequire Export Misc.\nRequire Export Ccpo.\nSet Implicit Arguments.\nOpen Local Scope O_scope.\n\n(** ** Basic operators of U *)\n(** \n    - Constants : [0] and [1]\n    - Constructor : [ [1/1+] n ] $(\\equiv \\frac{1}{n+1})$ #(=1/(1+n))#\n    - Operations : [x+y] (=min (x+y,1)), [x*y], [ [1-] x]\n    - Relations : [x <= y], [x==y]\n*)\n\nModule Type Universe.\nParameter U : Type.\nGeneralizable All Variables.\nDeclare Instance ordU: ord U.\nDeclare Instance cpoU: cpo U.\nBind Scope U_scope with U.\nDelimit Scope U_scope with U.\n\nParameters Uplus Umult Udiv: U -> U -> U.\nParameter Uinv : U -> U.\nParameter Unth : nat -> U.\n\n\nInfix \"+\" := Uplus : U_scope.\nInfix \"*\"  := Umult  : U_scope.\nInfix \"/\"  := Udiv  : U_scope.\nNotation \"[1-]  x\" := (Uinv x)  (at level 35, right associativity) : U_scope.\n\nNotation \"[1/]1+ n\" := (Unth n) (at level 35, right associativity) : U_scope.\nOpen Local Scope U_scope.\n\nDefinition U1 : U := [1-] 0. \nNotation \"1\" := U1 : U_scope.\n\n(** ** Basic Properties *)\n\nHypothesis Udiff_0_1 : ~0 == 1.\n(*\nHypothesis Unit : forall x:U, x <= 1. \n*)\n\nHypothesis Uplus_sym : forall x y:U, x + y == y + x.\nHypothesis Uplus_assoc : forall x y z:U, x + (y + z) == x + y + z.\nHypothesis Uplus_zero_left : forall x:U, 0 + x == x.\n\nHypothesis Umult_sym : forall x y:U, x * y == y * x.\nHypothesis Umult_assoc : forall x y z:U, x * (y * z) == x * y * z.\nHypothesis Umult_one_left : forall x:U, 1 * x == x.\n\nHypothesis Uinv_one : [1-] 1 == 0. \n\n(*\nHypothesis Uinv_opp_left : forall x, [1-] x + x == 1.\n*)\n\nHypothesis Umult_div : forall x y, ~ 0 == y -> x <= y -> y * (x/y) == x.\nHypothesis Udiv_le_one : forall x y,  ~ 0 == y -> y <= x -> (x/y) == 1.\nHypothesis Udiv_by_zero : forall x y,  0 == y -> (x/y) == 0.\n\n(** - Property  : [1 - (x + y) + x = 1 - y ] holds when [x+y] does not overflow *)\nHypothesis Uinv_plus_left : forall x y, y <= [1-] x -> [1-] (x + y) + x == [1-] y.\n\n(** - Property  : [(x + y) * z  = x * z + y * z] holds when [x+y] does not overflow *)\nHypothesis Udistr_plus_right : forall x y z, x <= [1-] y -> (x + y) * z == x * z + y * z.\n\n(** - Property  : [1 - (x  y) = (1 - x) * y + (1-y) ] *)\nHypothesis Udistr_inv_right : forall x y:U,  [1-] (x * y) == ([1-] x) * y + [1-] y.\n\n(** - Totality of the order *)\nHypothesis Ule_class : forall x y : U, class (x <= y).\n\nHypothesis Ule_total : forall x y : U, orc (x <= y) (y <= x).\nImplicit Arguments Ule_total [].\n\n(** - The relation [x <=  y] is compatible with operators *)\n\nDeclare Instance Uplus_mon_right :forall x,monotonic (Uplus x).\n\n(* Instance Uplus_mon_right : forall x, monotonic (Uplus x). *)\n\nDeclare Instance Umult_mon_right : forall x, monotonic (Umult x).\n(* Instance Umult_mon_right : forall x, monotonic (Umult x). *)\n\nHypothesis Uinv_le_compat : forall x y:U, x <= y -> [1-] y <= [1-] x.\n\n(** - Properties of simplification in case there is no overflow *)\nHypothesis Uplus_le_simpl_right : forall x y z, z <= [1-] x -> x + z <= y + z -> x <= y.\n\nHypothesis Umult_le_simpl_left : forall x y z: U, ~ 0 == z -> z * x <= z * y -> x <= y .\n\n(** -  Property of [Unth]: [1 / n+1 == 1 - n  * (1/n+1)] *)\nHypothesis Unth_prop : forall n, [1/]1+n == [1-](compn Uplus 0 (fun k => [1/]1+n) n).\n\n(** - Archimedian property *)\nHypothesis archimedian : forall x, ~0 == x -> exc (fun n => [1/]1+n <= x).\n\n(** - Stability properties of lubs with respect to [+] and [*] *)\n\nHypothesis Uplus_right_continuous : forall k, continuous (mon (Uplus k)).\nHypothesis Umult_right_continuous : forall k, continuous (mon (Umult k)).\n\nEnd Universe.\n\nDeclare Module Univ:Universe.\nExport Univ.\n\nHint Resolve Udiff_0_1 Unth_prop.\nHint Resolve Uplus_sym Uplus_assoc Umult_sym Umult_assoc.\nHint Resolve Uinv_one  Uinv_plus_left Umult_div Udiv_le_one Udiv_by_zero.\nHint Resolve Uplus_zero_left Umult_one_left Udistr_plus_right Udistr_inv_right.\nHint Resolve Uplus_mon_right Umult_mon_right Uinv_le_compat.\nHint Resolve lub_le le_lub Uplus_right_continuous Umult_right_continuous. \n(* lub_eq_mult lub_eq_plus_cte_left.*)\nHint Resolve Ule_total Ule_class.\n\n", "meta": {"author": "Zhang-Xiyue", "repo": "Prob-Reo", "sha": "dc684d0c48403cc053d9e7bb3b696922a883bc80", "save_path": "github-repos/coq/Zhang-Xiyue-Prob-Reo", "path": "github-repos/coq/Zhang-Xiyue-Prob-Reo/Prob-Reo-dc684d0c48403cc053d9e7bb3b696922a883bc80/ProbReo/Utheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7367370835559741}}
{"text": "(* Examples of type classes and Setoids *)\n(* Version with operational classes *)\n(* Some comments by Matthieu *)\n\n\n\nSet Implicit Arguments.\n\nRequire Import ZArith  Div2  Recdef  Mat.\n\n\nClass monoid_binop (A:Type) := monoid_op : A -> A -> A.\n\nDelimit Scope M_scope with M.\nInfix \"*\" := monoid_op: M_scope.\nOpen Scope M_scope.\n\nClass Monoid (A:Type)(dot : monoid_binop  A)(one : A) : Prop := {\n  dot_assoc : forall x y z:A, x * (y * z)=  x * y * z;\n  one_left : forall x, one * x = x;\n  one_right : forall x,  x * one = x}.\n\n(*\none_right :\nforall (A : Type) (dot : monoid_binop A) (one : A),\nMonoid dot one -> forall x : A, x * one = x\n*)\n\n\n\nOpen Scope Z_scope.\n\n(** Tests :\n\nCompute (@monoid_op _ Zmult 5 6).\n\n*)\n\n\nInstance Zmult_op : monoid_binop Z | 17:= Zmult.\n\nInstance ZMult : Monoid   Zmult_op  1 | 22.\nProof.\n  split;intros; unfold Zmult_op, monoid_op; ring. \nDefined.\n\nRequire Import Ring.\n\nSection matrices.\n Variables (A:Type)\n           (zero one : A) \n           (plus mult minus : A -> A -> A)\n           (sym : A -> A).\n Notation \"0\" := zero.\n Notation \"1\" := one.\n Notation \"x + y\" := (plus x y).  \n Notation \"x * y \" := (mult x y).\n \n\n\n Variable rt : ring_theory  zero one plus mult minus sym (@eq A).\n\n Add  Ring Aring : rt.\n\nGlobal Instance M2_mult_op :  monoid_binop (M2 A) := (M2_mult  plus mult ) . \n\n\nGlobal Instance M2_Monoid : Monoid  M2_mult_op (Id2  0 1).\nProof.\n  split.\n  - destruct x;destruct y;destruct z;unfold monoid_op;simpl.\n    unfold M2_mult;apply M2_eq_intros;simpl;  ring.\n  - destruct x;simpl;unfold M2_mult_op, monoid_op;\n    unfold M2_mult; apply M2_eq_intros; simpl;ring.\n  - destruct x;simpl;unfold M2_mult_op, monoid_op;\n    unfold M2_mult;apply M2_eq_intros;simpl;ring. \nDefined.\n\nEnd matrices.\n\nGeneralizable Variables A dot one.\n\n\nInstance M2_Z_op : monoid_binop (M2 Z) := M2_mult Zplus Zmult . \n\nInstance M2_mono_Z : Monoid (M2_mult_op _ _)  (Id2  _ _):=  M2_Monoid Zth.\n\n(** Tests :\n\nCompute let m := Build_M2 1 1 1 0 in\n          (m  *  m)%M.\n*)\n\n\nFixpoint power `{M : @Monoid A dot one}(a:A)(n:nat) :=\n  match n with 0%nat => one\n             | S p => (a * power a p)%M\n  end.\n\n\nInfix \"**\" := power (at level 30, no associativity):M_scope.\n\n(** Tests :\nCompute  (2 ** 5) ** 2.\n\nCompute (Build_M2  1 1 1  0) **    40. \n*)\n\n\n(* A tail recursive linear function *)\n\nFixpoint power_mult `{M : Monoid }\n     (acc x:A)(n:nat) : A (*  acc * (x ** n) *) :=\n  match n with 0%nat => acc\n             | S p => power_mult (acc * x)%M x p\n  end.\n\nDefinition tail_recursive_power  `{M : Monoid}(x:A)(n:nat) :=\n     power_mult one x n.\n\nRequire Import Recdef  Div2.\n\nFunction binary_power_mult (A:Type)(dot:monoid_binop A)(one:A) \n    (M: @Monoid A dot one) (acc x:A)(n:nat){measure (fun i=>i) n} : A \n  (* acc * (x ** n) *) :=\n  match n with 0%nat => acc\n             | _ => match Even.even_odd_dec n\n                    with left H0 => binary_power_mult    _   acc (dot x x) (div2 n)\n                       | right H1 => \n                         binary_power_mult   _  (acc * x)%M ( x * x)%M (div2 n)\n                    end\n  end.\nProof. \n  - intros;apply lt_div2; auto with arith.\n  - intros;apply lt_div2; auto with arith.\nDefined.\n\n\n\nDefinition binary_power `{M: Monoid} (x:A)(n:nat)  := \n     binary_power_mult    M one  x n.\n\n(** Tests \n\nCompute binary_power  2 5.\n\nCompute  (Build_M2 1 1 1 0) ** 10.\n\nCompute binary_power (Build_M2 1 1 1 0) 20.\n*)\n\n\n\nSection About_power.\n\n  Context      `(M:Monoid  ).\n  Open Scope M_scope.\n\n  \n  Ltac monoid_rw :=\n    rewrite one_left || rewrite one_right || rewrite dot_assoc.\n\n  Ltac monoid_simpl := repeat monoid_rw.\n\n  Lemma power_x_plus : forall x n p, (x ** (n + p) = x ** n * x ** p).\n  Proof.\n   induction n;simpl. \n   - intros; monoid_simpl;trivial.\n   - intro p;rewrite (IHn p); monoid_simpl;trivial.\n  Qed.\n\n  Ltac power_simpl := repeat (monoid_rw || rewrite <- power_x_plus).\n\n  Lemma power_commute : forall x n p,  \n               x ** n * x ** p = x ** p * x ** n. \n  Proof.\n   intros x n p;power_simpl;  rewrite (plus_comm n p);trivial.\n Qed.\n\n Lemma power_commute_with_x : forall x n ,  \n        x * x ** n = x ** n * x.\n Proof.\n  induction n;simpl;power_simpl;trivial.\n  repeat rewrite <- dot_assoc; rewrite IHn; trivial.\n Qed.\n\n Lemma power_of_power : forall x n p,  (x ** n) ** p = x ** (p * n).\n Proof.\n   induction p;simpl;[| rewrite power_x_plus; rewrite IHp]; trivial.\nQed.\n\n\nLemma power_S : forall x n, x *  x ** n = x ** S n.\nProof. intros;simpl;auto. Qed.\n\nLemma sqr : forall x, x ** 2 =  x * x.\nProof.\n simpl;intros;monoid_simpl;trivial.\nQed.\n\nLtac factorize := repeat (\n                rewrite <- power_commute_with_x ||\n                rewrite  <- power_x_plus  ||\n                rewrite <- sqr ||\n                rewrite power_S ||\n                rewrite power_of_power).\n\n Lemma power_of_square : forall x n, (x * x) ** n = x ** n * x ** n.\n Proof.\n  induction n;simpl;monoid_simpl;trivial.\n  repeat rewrite dot_assoc;rewrite IHn; repeat rewrite dot_assoc.\n  factorize; simpl;trivial.\n Qed.\n\n Lemma power_mult_correct : \n    forall n x, tail_recursive_power x n = x ** n.\n  Proof.\n    intros n x;  unfold tail_recursive_power.\n    rewrite <-  (one_left  (power x n)).\n    assert (forall y:A, power_mult y x n =  y * (power x n)); auto.\n       generalize n x;intro p; induction p;simpl;intros; monoid_simpl;auto.\n  Qed.\n\nLemma binary_power_mult_ok :\n  forall n a x,  binary_power_mult  M a x n = a * x ** n.\nProof.\n  intro n; pattern n;apply lt_wf_ind.\n  clear n; intros n Hn;   destruct n.\n  -  intros;simpl; rewrite binary_power_mult_equation;monoid_simpl;\n    trivial.\n  - intros;  \n    rewrite binary_power_mult_equation; destruct (Even.even_odd_dec (S n)).\n   + rewrite Hn.\n     * rewrite power_of_square;  factorize.\n       pattern (S n) at 3;replace (S n) with (div2 (S n) + div2 (S n))%nat;auto.\n       generalize (even_double _ e);simpl;auto. \n     *  apply lt_div2;auto with arith.\n   +  rewrite Hn.\n      * rewrite power_of_square ; factorize.\n        pattern (S n) at 3;replace (S n) with (S (div2 (S n) + div2 (S n)))%nat;auto.\n        rewrite <- dot_assoc; factorize;auto.\n        generalize (odd_double _ o);intro H;auto.\n      * apply lt_div2;auto with arith.\nQed.\n\nLemma binary_power_ok : forall x n, binary_power (x:A)(n:nat) = x ** n.\nProof.\n  intros n x;unfold binary_power;rewrite binary_power_mult_ok;\n  monoid_simpl;auto.\nQed.\n\nEnd About_power.\n\n(** An efficient Fibonacci function \n*)\n\nDefinition fibonacci (n:nat) :=\n      c00  (binary_power (Build_M2 1 1 1 0) n).\n\n(** Tests:\n\nCompute fibonacci 20. \n*)\n\n(** Abelian Monoids \n*)\n\nClass Abelian_Monoid `(M:Monoid):= {\n  dot_comm : forall x y, (x * y = y * x)%M}.\n\nInstance ZMult_Abelian : Abelian_Monoid ZMult.\nProof. \n  split. \n  - exact Zmult_comm.\nDefined.\n\nSection Power_of_dot.\n Context `{M: Monoid A} {AM:Abelian_Monoid M}.\n\n Open Scope M_scope.\n \n Theorem power_of_mult :\n   forall n x y, ((x * y) ** n =  x ** n  * y ** n)%M. \nProof.\n induction n;simpl.\n -  rewrite one_left;auto.\n - intros; rewrite IHn; repeat rewrite dot_assoc.\n   rewrite <- (dot_assoc  x y (power x n)); rewrite (dot_comm y (power x n)).\n   repeat rewrite dot_assoc;trivial.\nQed.\n\nEnd Power_of_dot.\n\n\nExample Ex1:  forall (x y z :Z)(n:nat),  ((x * (y * z)) ** n  =\n                        x ** n *  (y ** n  * z ** n))%M.\nProof. \nintros; repeat (rewrite power_of_mult); trivial. \nQed.\n\n\n(*** Monoids with equivalence *)\n\nRequire Import Coq.Setoids.Setoid  Morphisms.\n\nClass Equiv A := equiv : relation A.\nInfix \"==\" := equiv (at level 70):type_scope.\n\n  Open Scope M_scope.\n\n  Class EMonoid (A:Type)(E_eq :Equiv A)(E_dot : monoid_binop A)(E_one : A):={\n  E_rel :> Equivalence equiv; \n  dot_proper :> Proper (equiv ==> equiv ==> equiv) monoid_op; \n  E_dot_assoc : forall x y z:A,\n      x * (y * z) == x * y * z;\n  E_one_left : forall x, E_one * x == x;\n  E_one_right : forall x, x * E_one == x}.\n\nGeneralizable Variables E_eq E_dot E_one.\n\n(* --- *)\n\nLemma E_trans  `(M:EMonoid A)  : transitive A  E_eq.\nProof. apply E_rel. Qed.\n\n(* The above proofs are equivalent to the overloaded reflexivity, symmetry and transitivity\n   lemmas, already avalable for every EMonoid. i.e.: *)\n\n\nLemma E_refl' `(M:EMonoid A) : reflexive A  E_eq. \nProof. intro. change (equiv x x). apply reflexivity. Qed.\n\n\n\nFixpoint Epower `{M : EMonoid }(a:A)(n:nat):A :=\n  match n with 0%nat => E_one \n             | S p =>  a * (Epower a p)\n  end.\n\nAbout Epower.\n\n\nGlobal Instance  Epower_Proper `(M: EMonoid):\n  Proper (equiv ==> Logic.eq ==> equiv) Epower.\nProof.\n  intros x y H n p e;subst p;induction n.\n  -  reflexivity.\n  -  apply dot_proper;auto. \nQed.\n\n\n\nInstance monoid_op_params : Params (@monoid_op) 2.\n\nLemma Epower_x_plus `(M: EMonoid) : \n   forall x n p,  (Epower x (n + p)) == \n                  (Epower x n) * (Epower x p).\n  Proof.\n   induction n;simpl. \n   -  intros ; rewrite E_one_left;reflexivity.\n   -  intro p;  rewrite <- E_dot_assoc;  now rewrite <- IHn.\n  Qed.\n\n\nLemma Epower_x_mult `(M: EMonoid) : \n   forall x n p,  (Epower x (n * p)) == \n                  Epower (Epower x p) n.\n  Proof.\n   induction n;simpl. \n   - reflexivity.\n   -intro p; rewrite Epower_x_plus;  now rewrite IHn.\n Qed.\n\n(*** The monoid of function composition *)\n\nSection Definitions.\n  Variable A : Type.\n\n  Definition  comp (g f : A -> A): A -> A :=\n   fun x :A => g (f x).\n\n\n  Definition fun_ext (f g: A -> A) :=\n   forall x , f x  = g x.\n\n  Lemma fun_ext_refl : reflexive (A -> A)  fun_ext.\n  Proof. intros  f x; reflexivity. Qed.\n\n  Lemma fun_ext_sym : symmetric (A -> A)  fun_ext.\n Proof. \n  intros f g H x ; rewrite H; reflexivity.\n Qed.\n\n Lemma fun_ext_trans: transitive (A -> A)  fun_ext.\n Proof. \n   intros f g h H H0 x; rewrite H;rewrite H0;reflexivity. \n Qed.\n  \n (* Global instances are not forgotten at the end of sections and keep their visibility. *)\n\n Global Instance fun_ext_equiv : Equivalence   fun_ext.\n  Proof.\n    split; [ apply fun_ext_refl| apply fun_ext_sym| apply fun_ext_trans].\n  Qed.\n\nEnd Definitions.\n\nInstance fun_ext_op A : Equiv (A->A) := @fun_ext A.\n\n(* Comp is proper for extensional equality of functions *)\nGlobal Instance comp_proper A : Proper (equiv ==> equiv ==> equiv) (@comp A).\nProof. reduce; unfold comp; rewrite H, H0; reflexivity. Qed.\n\nInstance Rels (A:Type) : EMonoid equiv (@comp  A) (@id A).\nProof.\n split.\n - apply fun_ext_equiv.  \n - apply comp_proper.\n - unfold comp;intros f g h x;reflexivity.\n - intros f x;reflexivity.\n - intros f x;reflexivity.\nDefined.\n\nDefinition fibonacci_alt (n:nat) :=\n   fst  (Epower (M:= Rels (Z*Z)) (fun p:Z*Z => let (a,b):= p in (b,a+b)) n (1,1)).\n\nCompute fibonacci_alt 40.\n\nModule SemiRing.\n\n(* Overloaded notations *)\n\nClass RingOne A := ring_one : A.\nClass RingZero A := ring_zero : A.\nClass RingPlus A := ring_plus :> monoid_binop A.\nClass RingMult A := ring_mult :> monoid_binop A.\n\nInfix \"+\" := ring_plus.\nInfix \"*\" := ring_mult.\nNotation \"0\" := ring_zero.\nNotation \"1\" := ring_one.\n\nTypeclasses Transparent RingPlus RingMult RingOne RingZero.\n\nClass Distribute `{Equiv A} (f g: A -> A -> A): Prop :=\n  { distribute_l a b c: f a (g b c) == g (f a b) (f a c)\n  ; distribute_r a b c: f (g a b) c == g (f a c) (f b c) }.\n\nClass Commutative {A B} `{Equiv B} (m: A -> A -> B): Prop := \n  commutativity x y : m x y = m y x.\n\nClass Absorb {A} `{Equiv A} (m: A -> A -> A) (x : A) : Prop := \n  { absorb_l c : m x c = x ;\n    absorb_r c : m c x = x }.\n\nClass ECommutativeMonoid `(Equiv A) (E_dot : monoid_binop A)(E_one : A):=\n  { e_commmonoid_monoid :> EMonoid equiv E_dot E_one;\n    e_commmonoid_commutative :> Commutative E_dot }.\n\nClass ESemiRing (A:Type) (E_eq :Equiv A) (E_plus : RingPlus A) (E_zero : RingZero A)\n            (E_mult : RingMult A) (E_one : RingOne A):=\n  { add_monoid :> ECommutativeMonoid equiv ring_plus ring_zero ;\n    mul_monoid :> EMonoid equiv ring_mult ring_one ;\n    ering_dist :> Distribute ring_mult ring_plus ;\n    ering_0_mult :> Absorb ring_mult 0\n  }.\n\n\nPrint Absorb.\n\nSection SemiRingTheory.\n\n  Context `{ESemiRing A}.\n\n  Definition ringtwo := 1 + 1.\n\n  Lemma ringtwomult : forall x : A, ringtwo * x == x + x.\n  Proof.\n    intros;unfold ringtwo;    rewrite distribute_r.\n    now rewrite (E_one_left x).\n  Qed.\n\nEnd SemiRingTheory.\n\nEnd SemiRing.\n\n\n\n(** Monoid of Partial Commutation *)\n\nRequire Import Coq.Lists.List  Relation_Operators  Operators_Properties.\n\nSection Partial_Com.\n\nInductive Act : Set := a | b | c.\n \n\n(** action a commutes with action b *)\n\nInductive transpose : list Act -> list Act -> Prop :=\n transpose_hd : forall w, transpose(a::b::w) (b::a::w)\n|transpose_tl : forall x w u, transpose  w u -> transpose (x::w) (x::u).\n\nDefinition commute := clos_refl_sym_trans _ transpose.\n\nInstance Commute_E : Equivalence  commute.\nProof. \nsplit.\n- constructor 2.\n- constructor 3;auto.\n- econstructor 4;eauto.\nQed.\n\nInstance CE : Equiv (list Act) := commute.\n\nExample ex1 :  (c::a::a::b::nil) == (c::b::a::a::nil).\nProof. \n constructor 4 with (c::a::b::a::nil).\n - constructor 1.\n   constructor 2.\n   constructor 2.\n   constructor 1.\n - constructor 1.\n   right;left.\nQed. \n\n\nInstance cons_transpose_Proper (x:Act): Proper (transpose ==> transpose)\n                                         (cons x).\nProof.\n intros  l l' H;constructor ;auto.\nDefined.\n\nInstance append_transpose_Proper (l:list Act): Proper (transpose ==> transpose)\n                                         (app l).\nProof.\n induction l.\n - intros z t Ht;simpl;auto.\n - intros z t Ht;simpl;constructor;auto.\nQed.\n\nInstance append_transpose_Proper_1  : Proper (transpose ==> Logic.eq  ==> transpose)\n                                         (@app Act).\nProof.\n intros x y H;induction H;intros z t e;subst t. \n -  simpl;constructor. \n -  generalize (IHtranspose z z (refl_equal z)); simpl;constructor;auto.\nQed.\n\nInstance append_commute_Proper_1 : \nProper (Logic.eq ==> commute  ==> commute)\n                                         (@app Act).\nProof.\n intros x y e;subst y;intros z t H;elim H.\n - constructor 1.\n  apply append_transpose_Proper;auto.\n -  reflexivity.\n -  constructor 3;auto.\n -  intros x0 y z0;constructor 4 with (x++y);auto.\nQed.\n\n\nInstance  append_commute_Proper_2 : \nProper (commute ==> Logic.eq   ==> commute) (@app Act).\nProof.\nintros x y H; elim H. \n-  intros x0 y0 H0  z t e; subst t; constructor 1.\n   apply append_transpose_Proper_1;auto.\n-  intros x0 z t e; subst t;constructor 2;auto.\n-   intros x0 y0 H0 H1 z t e;subst t.\n    constructor 3.\n    apply H1;auto.\n-  intros x0 y0 z0 H1 H2 H3 H4 z t e;subst t.\n   transitivity (y0 ++ z).\n   +  apply H2;reflexivity.\n   +  apply H4;reflexivity.\nQed.\n\n\n\nInstance append_Proper : Proper (commute ==> commute ==> commute) (@app Act).\nProof.\n intros x y H z t H0; transitivity (y++z).\n - now rewrite H.\n - now rewrite H0.\nQed.\n\nInstance app_op :  monoid_binop (list Act):=  @app Act.\n\nInstance PCom  : EMonoid   commute app_op nil.\nProof. \n split.\n - apply Commute_E.\n - apply append_Proper.\n - unfold monoid_op;induction x;simpl;auto.\n   + reflexivity.\n   + intros;simpl;unfold app_op; rewrite app_assoc;reflexivity.\n - unfold monoid_op;simpl;reflexivity. \n - unfold monoid_op,app_op;intro;rewrite app_nil_r;reflexivity.\nQed.\n\n\nExample ex2:  Epower  (c::a::a::b::nil) 10 == \n     Epower (Epower  (c::b::a::a::nil) 5)  2.\nProof.\n  rewrite ex1, <- Epower_x_mult.\n  reflexivity.\nQed.\n\n\n\nEnd Partial_Com.\n\n\nSection Z_additive.\n\nLocal Instance Z_plus_op :  monoid_binop Z | 2:= Zplus.\n\nRequire Import ZArithRing.\n\n\nInstance ZAdd : Monoid   Z_plus_op 0 | 2. \nProof.\n  split;intros;unfold Z_plus_op, monoid_op; simpl;ring.\nDefined.\n\nExample Ex2 : (2 * 5)%M = 7. \nProof. reflexivity. Qed.\n\n\nExample Ex3 : 2 ** 5 = 10.\nProof. reflexivity. Qed.\n\nExample Ex4 : power  (M:=ZMult) 2 5 = 32.\nProof. reflexivity. Qed.\n\n(* OK, let's remove ZAdd *)\nEnd Z_additive.\n\nExample Ex5 : (2  * 5)%M = 10. \nProof. reflexivity. Qed.\n\n(** Let us build a new instance with priority 1 *)\n\nInstance Zplus_op : monoid_binop Z | 7 := Zplus.\n\nInstance : Monoid   Zplus_op  0 | 1.\nsplit;intros;  unfold  monoid_op, Zplus_op; simpl; ring. \nDefined.\n\nExample Ex6 : (2 * 5)%M = 7.\nProof. reflexivity. Qed.\n\n(* The least priority level wins *)\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/tutorial_type_classes/SRC/Monoid_op_classes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7366916817928084}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Import BinInt.\nLocal Open Scope Z_scope.\n\n(** An alternative power function for Z *)\n\n(** This [Zpower_alt] is extensionally equal to [Z.pow],\n    but not convertible with it. The number of\n    multiplications is logarithmic instead of linear, but\n    these multiplications are bigger. Experimentally, it seems\n    that [Zpower_alt] is slightly quicker than [Z.pow] on average,\n    but can be quite slower on powers of 2.\n*)\n\nDefinition Zpower_alt n m :=\n  match m with\n    | Z0 => 1\n    | Zpos p => Pos.iter_op Z.mul p n\n    | Zneg p => 0\n  end.\n\nInfix \"^^\" := Zpower_alt (at level 30, right associativity) : Z_scope.\n\nLemma Piter_mul_acc : forall f,\n (forall x y:Z, (f x)*y = f (x*y)) ->\n forall p k, Pos.iter f k p = (Pos.iter f 1 p)*k.\nProof.\n intros f Hf.\n induction p; simpl; intros.\n - set (g := Pos.iter f 1 p) in *. now rewrite !IHp, Hf, Z.mul_assoc.\n - set (g := Pos.iter f 1 p) in *. now rewrite !IHp, Z.mul_assoc.\n - now rewrite Hf, Z.mul_1_l.\nQed.\n\nLemma Piter_op_square : forall p a,\n Pos.iter_op Z.mul p (a*a) = (Pos.iter_op Z.mul p a)*(Pos.iter_op Z.mul p a).\nProof.\n induction p; simpl; intros; trivial. now rewrite IHp, Z.mul_shuffle1.\nQed.\n\nLemma Zpower_equiv a b : a^^b = a^b.\nProof.\n destruct b as [|p|p]; trivial.\n unfold Zpower_alt, Z.pow, Z.pow_pos.\n revert a.\n induction p; simpl; intros.\n - f_equal.\n   rewrite Piter_mul_acc.\n   now rewrite Piter_op_square, IHp.\n   intros. symmetry; apply Z.mul_assoc.\n - rewrite Piter_mul_acc.\n   now rewrite Piter_op_square, IHp.\n   intros. symmetry; apply Z.mul_assoc.\n - now Z.nzsimpl.\nQed.\n\nLemma Zpower_alt_0_r n : n^^0 = 1.\nProof. reflexivity. Qed.\n\nLemma Zpower_alt_succ_r a b : 0<=b -> a^^(Z.succ b) = a * a^^b.\nProof.\n destruct b as [|b|b]; intros Hb; simpl.\n - now Z.nzsimpl.\n - now rewrite Pos.add_1_r, Pos.iter_op_succ by apply Z.mul_assoc.\n - now elim Hb.\nQed.\n\nLemma Zpower_alt_neg_r a b : b<0 -> a^^b = 0.\nProof.\n now destruct b.\nQed.\n\nLemma Zpower_alt_Ppow p q : (Zpos p)^^(Zpos q) = Zpos (p^q).\nProof.\n now rewrite Zpower_equiv, Pos2Z.inj_pow.\nQed.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/ZArith/Zpow_alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7366916792468767}}
{"text": "(** %\\chapter{Functional Programming in Coq} *)\n\nModule FunProg.\n\n(** * Enumeration datatypes *)\n\nInductive unit : Set := tt.\n\nCheck tt.\n\n(**\n[[\ntt\n     : unit\n]]\n*)\n\nCheck unit.\n\n(**\n[[\nunit\n     : Set\n]]\n*)\n\nInductive empty : Set := .\n\nRequire Import ssreflect ssrbool.\n\nPrint bool.\n(** \n[[\nInductive bool : Set :=  true : bool | false : bool\n]] \n*)\n\n(** \n\nLet us now try to define some functions that operate with the bool\ndatatype ignoring for a moment the fact that most of them, if not all,\nare already defined in the standard Coq/SSReflect library.  Our first\nfunction will simply negate the boolean value and return its opposite:\n\n*)\n\nDefinition negate b := \n  match b with \n  | true  => false\n  | false => true\n  end.\n\nCheck negate.\n(**\n[negate : bool -> bool\n]\n\n* Simple recursive datatypes and programs\n\n*)\n\nPrint nat.\n\n(**\n[Inductive nat : Set :=  O : nat | S : nat -> nat]\n\n*)\n\nRequire Import ssrnat.\n\nFixpoint my_plus n m := \n match n with \n | 0     => m   \n | n'.+1 => let: tmp := my_plus n' m in tmp.+1\n end.\n\nEval compute in my_plus 5 7. \n(** \n[  = 12 : nat] \n*)\n\nFixpoint my_plus' n m := if n is n'.+1 then (my_plus' n' m).+1 else m.\n\n(**\n[[\nFixpoint my_plus_buggy n m := \n    if n is n'.+1 then (my_plus_buggy n m).+1 else m.\n]]\n\nwe immediately get the following error out of the Coq interpreter:\n\n[[\nError: Cannot guess decreasing argument of fix.\n]]\n\n*)\n\nCheck nat_rec.\n(** \n[[\nnat_rec : forall P : nat -> Set,\n          P 0 -> (forall n : nat, P n -> P n.+1) -> forall n : nat, P n\n]]\n\nTo see how [nat_rec] is implemented, let us explore its generalized\nversion, [nat_rect]:\n\n*)\n\nPrint nat_rect.\n(** \n[[\nnat_rect = \n fun (P : nat -> Type) (f : P 0) (f0 : forall n : nat, P n -> P n.+1) =>\n fix F (n : nat) : P n :=\n   match n as n0 return (P n0) with\n   | 0 => f\n   | n0.+1 => f0 n0 (F n0)\n   end\n      : forall P : nat -> Type,\n        P 0 -> (forall n : nat, P n -> P n.+1) -> forall n : nat, P n\n]]\n\n*)\n\nDefinition my_plus1 n m := nat_rec (fun _ => nat) m (fun n' m' => m'.+1) n.\n\nEval compute in my_plus1 16 12.\n\n(** \n[    = 28 : (fun _ : nat => nat) 16]\n\n** Dependent function types and pattern matching\n\n*)\n\nCheck nat_rec.\n\nDefinition sum_no_zero n := \n let: P := (fun n => if n is 0 then unit else nat) in\n nat_rec P tt (fun n' m => \nmatch n' return P n' -> _ with\n   | 0 => fun _ => 1\n   | n1.+1 => fun m => my_plus m (n'.+1) \nend m) n.\n\n(*\nDefinition three_to_unit n := \n let: P := (fun n => if n is 3 then unit else nat) in\n nat_rec P 0 (fun n' _ => match n' return P n'.+1 with\n               | 2 => tt\n               | _ => n'.+1\n               end) n.\n\nEval compute in three_to_unit 0.\n*)\n\nEval compute in sum_no_zero 0.\n\n(** \n\n[ \n     = tt\n     : (fun n : nat => match n with\n                       | 0 => unit\n                       | _.+1 => nat\n                       end) 0\n]\n\n*)\n\nEval compute in sum_no_zero 5.\n(** \n[[\n     = 15\n     : (fun n : nat => match n with\n                       | 0 => unit\n                       | _.+1 => nat\n                       end) 5\n]]\n\nHad we omitted the [return] clauses in the pattern matching, we would\nget the following type-checking error, indicating that Coq cannot\ninfer that the type of [my_plus]' argument is always [nat], so it\ncomplains:\n\n[[\nDefinition sum_no_zero' n := \n let: P := (fun n => if n is 0 then unit else nat) in\n nat_rec P tt (fun n' m => \nmatch n' with\n   | 0 => fun _ => 1\n   | n1.+1 => fun m => my_plus m (n'.+1) \nend m) n.\n]]\n\n[[\nError:\nIn environment\nn : ?37\nP := fun n : nat => match n with\n                    | 0 => unit\n                    | _.+1 => nat\n                    end : nat -> Set\nn' : nat\nm : P n'\nThe term \"m\" has type \"P n'\" while it is expected to have type \"nat\".\n]]\n*)\n\n(** ** Recursion principle and non-inhabited types *)\n\nCheck empty_rect.\n\n(** \n[[\nempty_rect\n     : forall (P : empty -> Type) (e : empty), P e\n]]\n\n\nAssuming existence of a value, which \\emph{cannot be constructed}, we\nwill be able to construct \\emph{anything}.\n \n*)\n\nInductive strange : Set :=  cs : strange -> strange.\n\nCheck strange_rect.\n\n(** \n[[\nstrange_rect\n     : forall P : strange -> Type,\n       (forall s : strange, P s -> P (cs s)) -> forall s : strange, P s\n]]\n*)\n\nDefinition strange_to_empty (s: strange): empty :=\n  strange_rect (fun _ => empty) (fun s e => e) s.\n\n(** * More datatypes *)\n\n(* Pairs *)\n\nCheck prod.\n\n(**\n[[\nprod : Type -> Type -> Type\n\n]]\n*)\n\nPrint prod.\n\n(** \n[[\nInductive prod (A B : Type) : Type :=  pair : A -> B -> A * B\n\nFor pair: Arguments A, B are implicit and maximally inserted\nFor prod: Argument scopes are [type_scope type_scope]\nFor pair: Argument scopes are [type_scope type_scope _ _]\n]]\n*)\n\nCheck pair 1 tt.\n\n(** \n[[\n(1, tt) : nat * unit\n\n]]\n\nIf one wants to explicitly specify the type arguments of a\nconstructor, the [@]-prefixed notation can be used:\n\n*)\n\nCheck @pair nat unit 1 tt.\n\n(**\n[[\n\n(1, tt) : nat * unit\n\n]]\n\n*)\n\nCheck fst.\n(**\n[[\nfst : forall A B : Type, A * B -> A\n]]\n*)\n\nCheck snd.\n(**\n[[\nfst : forall A B : Type, A * B -> B\n]]\n\nThe notation \"[_ * _]\" is not hard-coded into Coq, but rather is\ndefined as a lightweight syntactic sugar on top of standard Coq\nsyntax. Very soon we will see how one can easily extend Coq's syntax\nby defining their own notations. We will also see how is it possible\nto find what a particular notation means.\n*)\n\nPrint sum.\n(**\n[[\nInductive sum (A B : Type) : Type :=  inl : A -> A + B | inr : B -> A + B\n]]\n*)\n\nRequire Import seq.\nPrint seq.\n\n(** \n[[\nNotation seq := list\n]]\n\n*)\n\nPrint list.\n\n(**\n[[\nInductive list (A : Type) : Type := nil : list A | cons : A -> list A -> list A\n]]\n*)\n\n(** * Searching for definitions and notations *)\n\nSearch \"filt\".\n(** \n[[\nList.filter  forall A : Type, (A -> bool) -> list A -> list A\nList.filter_In\n   forall (A : Type) (f : A -> bool) (x : A) (l : list A),\n   List.In x (List.filter f l) <-> List.In x l /\\ f x = true\n]]\n*)\n\nSearch \"filt\" (_ -> list _).\n(** \n[[\nList.filter  forall A : Type, (A -> bool) -> list A -> list A\n]]\n*)\n\nSearch _ ((?X -> ?Y) -> _ ?X -> _ ?Y).\n(**\n[[\noption_map  forall A B : Type, (A -> B) -> option A -> option B\nList.map  forall A B : Type, (A -> B) -> list A -> list B\n...\n]]\n*)\n\nSearch _ (_ * _ : nat).\n\nSearch _ (_ * _: Type).\n\n(* Locate machinery *)\n\nLocate \"_ + _\".\n\n(** \n[[\nNotation            Scope     \n\"x + y\" := sum x y   : type_scope\n                      \n\"m + n\" := addn m n  : nat_scope\n]]\n*)\n\nLocate map.\n\n(**\n[[\nConstant Coq.Lists.List.map\n  (shorter name to refer to it in current context is List.map)\nConstant Ssreflect.ssrfun.Option.map\n  (shorter name to refer to it in current context is ssrfun.Option.map)\n...\n]]\n*)\n\n(** * An alternative syntax to define inductive datatypes *)\n\nInductive my_prod (A B : Type) : Type :=  my_pair of A & B.\n\n(** \n[[\nCheck my_pair 1 tt.\n\nError: The term \"1\" has type \"nat\" while it is expected to have type \"Type\".\n]]\n*)\n\n(* Declaring implicit arguments *)\n\nImplicit Arguments my_pair [A B].\n\n(* Defining custom notation *)\n\nNotation \"X ** Y\" := (my_prod X Y) (at level 2).\nNotation \"( X ,, Y )\" := (my_pair X Y).\n\nCheck (1 ,, 3).\n\n(** \n[[\n(1,, 3)\n     : nat ** nat\n]]\n\n*)\n\nCheck nat ** unit ** nat.\n\n(** \n[[\n(nat ** unit) ** nat\n     : Set\n]]\n*)\n\n(** * Sections and modules *)\n\nSection NatUtilSection.\n\nVariable n: nat.\n\nFixpoint my_mult m := match (n, m) with\n | (0, _) => 0\n | (_, 0) => 0\n | (_, m'.+1) => my_plus (my_mult m') n\n end. \n\nEnd NatUtilSection.\n\nPrint my_mult.\n\n(** \n\n[[\nmy_mult = \nfun n : nat =>\nfix my_mult (m : nat) : nat :=\n  let (n0, y) := (n, m) in\n  match n0 with\n  | 0 => 0\n  | _.+1 => match y with\n            | 0 => 0\n            | m'.+1 => my_plus (my_mult m') n\n            end\n  end\n     : nat -> nat -> nat\n]]\n*)\n\nModule NatUtilModule.\n\nFixpoint my_fact n :=\n  if n is n'.+1 then my_mult n (my_fact n') else 1.\n\nModule Exports.\nDefinition fact := my_fact.\nEnd Exports.\n\nEnd NatUtilModule.\n\nExport NatUtilModule.Exports.\n\n(** \n[[\nCheck my_fact.\n\nError: The reference my_fact was not found in the current environment.\n]]\n*)\n\nCheck fact.\n\n(**\n[[\nfact\n     : nat -> nat\n]]\n*)\n\n(*******************************************************************)\n(**                     * Exercices *                              *)\n(*******************************************************************)\n\nRequire Import eqtype.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\n---------------------------------------------------------------------\nExercise [Power of two]\n---------------------------------------------------------------------\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\n\nFixpoint two_power n :=\n match n with\n  | 0 => 1\n  | n'.+1 =>(two_power n' ) * 2\n end.\n\nCheck two_power.\nEval compute in two_power 0.\nEval compute in two_power 5.\n\nPrint nat_rec.\n\nDefinition two_power' n:=\n nat_rec (fun _ => nat) 1 (fun n' m => m * 2) n.\nEval compute in two_power' 0.\nEval compute in two_power' 5.\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 :=\n match n with \n  | 0 => true\n  | n'.+1 => negate (evenB n')\n end.\n\nEval compute in evenB 0.\nEval compute in evenB 1.\nEval compute in evenB 2.\n\nFixpoint evenB' n := nat_rec (fun _ => _) true (fun n' m => negate m) n.\nEval compute in evenB' 0.\nEval compute in evenB' 1.\nEval compute in evenB' 2.\n\n\n(**\n---------------------------------------------------------------------\nExercise [Division by four]\n---------------------------------------------------------------------\n\nDefine the function [div4] that maps any natural number [n] to the\ninteger part of [n/4].\n\n*)\n\nFixpoint div4 n :=\n match n-3 with\n  | 0 => 0\n  | n'.+1 => (div4 n').+1\n end.\n\nEval compute in div4 0.\nEval compute in div4 3.\nEval compute in div4 4.\nEval compute in div4 5.\nEval compute in div4 11.\nEval compute in div4 12.\nEval compute in div4 13.\n\n(**\n---------------------------------------------------------------------\nExercise [Representing rational numbers]\n---------------------------------------------------------------------\n\nEvery strictly positive rational number can be obtained in a unique\nmanner by a succession of applications of functions [N] and [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\nand returns a numerator and denominator of the corresponding fraction.\n*)\n\nInductive rrn : Type :=\n | l : rrn\n | N : rrn -> rrn\n | D : rrn -> rrn.\n\nCheck N (D l).\nSearch pair.\n(* Representing rational numbers -> Fraction *)\n\nFixpoint rrn_fra (r:rrn) : prod nat nat:=\n match r with\n  | l => (1,1)\n  | N r' => ( fst (rrn_fra r') +  snd (rrn_fra r') , snd (rrn_fra r') )\n  | D r' => ( fst (rrn_fra r') , fst (rrn_fra r') +  snd (rrn_fra r') )\n end.\n\nEval compute  in rrn_fra l.\nEval compute  in rrn_fra ( N l ).\nEval compute  in rrn_fra ( D l ).\nEval compute  in rrn_fra ( N ( N l ) ).\nEval compute  in rrn_fra ( D ( N l ) ).\nEval compute  in rrn_fra ( N ( D l ) ).\nEval compute  in rrn_fra ( D ( D l ) ).\n\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\n\n(**\n---------------------------------------------------------------------\nExercise [Take n]\n---------------------------------------------------------------------\n\nWrite a function that takes a type [A], and number [n] and a list [l]\nof elements of type [A] as arguments and returns first [n] elements of\nthe list (as another list) of [l] if they exist.\n*)\n\nFixpoint take_n {A:Type} (n:nat) (l:list A) :list A:=\n match n with\n  | 0 => nil\n  | n'.+1 => \n   match l with\n    | nil => nil\n    | h :: t => cons h (take_n n' t)\n  end\n end.\n\nEval compute in take_n 0 (1::2::3::4::5::nil) .\nEval compute in take_n 2 (1::2::3::4::5::nil) .\nEval compute in take_n 5 (1::2::3::4::5::nil) .\nEval compute in take_n 8 (1::2::3::4::5::nil) .\n\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\n(*\nFixpoint gene_range n :=\n match n with\n  | 0 => nil\n  | n'.+1 => (gene_range n') :: n\n end.\n*)\n\nFixpoint gene_range n:=nat_rec (fun _ => list _ ) nil (fun n l => l ++ (n.+1 :: nil) ) n.\nEval compute in gene_range 0.\nEval compute in gene_range 1.\nEval compute in gene_range 9.\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\nHint: Use Coq's [option] type to account for the fact that the\n function of interest is partially-defined.\n*)\n\nPrint option.\n\nFixpoint list_find  {A:Type} (f:A -> bool) l :=\n match l with\n  | nil => None\n  | h::t => if f h is true then Some h else list_find f t\n end.\n\nEval compute in list_find evenB nil.\nEval compute in list_find evenB (1::3::6::8::nil).\nEval compute in list_find evenB (1::3::nil).\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\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\nSearch \"beq\".\nRequire Import EqNat.\nPrint beq_nat.\n\nFixpoint nostutter (ls:list nat) :=\n match ls with\n  | nil => nil\n  | h::t =>\n   match t with\n    | nil => ls\n    | h'::t' =>\n     if (beq_nat h h')\n      then nostutter t\n      else h :: (nostutter t)\n   end\n end.\n\nEval compute in nostutter [::].\nEval compute in nostutter [:: 0;1;2;3].\nEval compute in nostutter [:: 0;0;1;3;3].\nEval compute in nostutter [:: 1;1;1].\n\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 according to the following \"test cases\".\n\nEval compute in alternate [:: 1;2;3] [:: 4;5;6].\n[[\n     = [:: 1; 4; 2; 5; 3; 6]\n     : seq nat\n] ]\n\nEval compute in alternate [:: 1] [:: 4;5;6].\n[[\n     = [:: 1; 4; 5; 6]\n     : seq nat\n]]\nEval compute in alternate [:: 1;2;3] [:: 4].\n[[\n     = [:: 1; 4; 2; 3]\n     : seq nat\n]]\n\nHint: The reason why the \"obvious\" elegant solution might fail is\n that the argument is not strictly decreasing.\n*)\n\nFixpoint alternate (l1 l2:list nat):=\n match l1 with\n  | nil => l2\n  | h1::t1 =>\n   match l2 with\n    | nil => l1\n    | h2::t2 => h1::h2::(alternate t1 t2)\n   end\n  end.\n\nEval compute in alternate [:: 1;2;3] [:: 4;5;6].\nEval compute in alternate [:: 1] [:: 4;5;6].\nEval compute in alternate [:: 1;2;3] [:: 4].\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\nHint: Again, you might need to define a number of auxiliary\n (possibly, higher-order) functions to complete this exercise.\n*)\n\nFixpoint mod_4 n:=\nmatch n-3 with\n | 0 => n\n | n'.+1 => mod_4 n'\nend.\n\nEval compute in mod_4 0.\nEval compute in mod_4 1.\nEval compute in mod_4 4.\nEval compute in mod_4 7.\n\nCheck nat_rec.\n(*\nDefinition dep_exr n :=\nif evenB (mod_4 n) then 2*n else\nif mod_4 n is 1 then true else false.\n*)\n\nEval compute in dep_exr 0.\nEval compute in dep_exr 1.\nEval compute in dep_exr 2.\nEval compute in dep_exr 3.\nEval compute in dep_exr 4.\n\n\nEnd FunProg.\n", "meta": {"author": "YamaTomoGit", "repo": "tempCoq", "sha": "6ae73ad66ab82d118fac8ed481b24a3988ab4bfc", "save_path": "github-repos/coq/YamaTomoGit-tempCoq", "path": "github-repos/coq/YamaTomoGit-tempCoq/tempCoq-6ae73ad66ab82d118fac8ed481b24a3988ab4bfc/lectures/FunProg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.736691674155013}}
{"text": "Require Import List Lia.\nRequire Import TypeClasses Ltacs Vector.\nImport VectorNotations.\nImport ListNotations.\n(*\nFormallizing a matrix so that we can use them for operations\n*)\n\n(* \n  At its most fundamental level, a matrix is a list of lists.\n\n  We want every list within the top-level list to be the same length.\n\n  Maybe this would be better represented using vectors?\n*)\n\nInductive Matrix {A : Type} : nat -> nat -> Type :=\n| mtMatrix  : forall (rows cols : nat), rows = 0 ->\n    Matrix rows cols\n| nMatrix   : forall (rows cols : nat) {rows' : nat} \n      (curRow : (@Vector A cols)),\n    S rows' = rows ->\n    Matrix rows' cols ->\n    Matrix rows cols.\n\nDefinition mat_num_rows {A : Type} {rows cols : nat} (m : (@Matrix A rows cols)) :=\n  rows.\n\nDefinition mat_num_cols {A : Type} {rows cols : nat} (m : (@Matrix A rows cols)) :=\n  cols.\n\n(** Testing Matrix Row/Cols\n    - We want the establishment of matrices to have n = rows, m = cols\n      so that they can be specified using a row by columns idea\n*)\nDefinition tMat1 := nMatrix 2 3 (<[ 1 ; 2; 3]) eq_refl (nMatrix 1 3 (<[4;5;6]) eq_refl (mtMatrix 0 3 eq_refl)).\nExample testTmat1_rows : mat_num_rows tMat1 = 2. reflexivity. Defined.\nExample testTmat1_cols : mat_num_cols tMat1 = 3. reflexivity. Defined.\n\nFixpoint matrix_get_value_row {A : Type} {rows cols : nat} (mat : @Matrix A rows cols)\n        (rowIndex : nat) : option (@Vector A _) :=\n  match rowIndex with\n  | 0 => \n      match mat with\n      | mtMatrix _ _ _ => None\n      | nMatrix rows' cols' curVec rowProof subMat =>\n          Some curVec\n      end\n  | S ri' =>\n      match mat with\n      | mtMatrix _ _ _ => None\n      | nMatrix rows' cols' curVec rowProof subMat =>\n          matrix_get_value_row subMat ri'\n      end\n  end.\n\nDefinition matrix_get_value {A : Type} {rows cols : nat} (mat : @Matrix A rows cols)\n        (rowInd colInd : nat) : option A :=\n  match (matrix_get_value_row mat rowInd) with\n  | None => None (* row index out of bounds*)\n  | Some rowVec =>\n      rowVec <@[colInd]\n  end.\n\nLemma mgv_lt_r_c_some : forall {A : Type} {r c : nat} (m : @Matrix A r c)\n  (rowInd colInd : nat), \n  rowInd < r /\\ colInd < c ->\n  exists out, \n    matrix_get_value m rowInd colInd = Some out.\nProof.\n  induction m; smp; intros; subst; eauto.\n  - inv H. lia.\n  - destruct rowInd, colInd, H; unfold matrix_get_value in *; smp.\n    * pose proof (@vgv_lt_len_some A cols 0 curRow); eauto.\n    * pose proof (@vgv_lt_len_some A cols (S colInd) curRow); eauto.\n    * eapply IHm; lia.\n    * eapply IHm; lia.\nQed.\n\nLemma mgv_gt_r_c_none : forall {A : Type} {r c : nat} (m : @Matrix A r c)\n    (rowInd colInd : nat),\n  rowInd > r \\/ colInd > c ->\n  matrix_get_value m rowInd colInd = None.\nProof.\n  induction m; smp; intros; subst; eauto.\n  - unfold matrix_get_value; smp.\n    destruct rowInd; eauto.\n  - destruct rowInd, colInd, H; unfold matrix_get_value in *; smp; eauto;\n    try lia; \n    try (eapply vgv_gte_len_none; lia);\n    try (eapply IHm; lia).\nQed.\n\nFixpoint matrix_set_value {A : Type} {rows cols : nat} (mat : @Matrix A rows cols)\n        (rowInd colInd : nat) (newV : A) {struct mat} : (@Matrix A rows cols).\n\ndestruct rowInd eqn:RI.\n- (* rowInd = 0 *)\n  destruct mat eqn:MAT.\n  * (* mat = mtMatrix *)\n    apply mat.\n  * (* mat = nMatrix rows cols curRow e m *)\n    apply (nMatrix rows cols (curRow set<@[colInd] <- newV) e m).\n    (* updating the row since we are at it (rowInd = 0 )*)\n- (* rowInd = S n *)\n  destruct mat eqn:MAT.\n  * (* mat = mtMatrix *)\n    apply mat.\n  * (* mat = nMatrix rows cols curRow e m *)\n    apply (nMatrix rows cols curRow e (matrix_set_value _ _ _ m n colInd newV)).\n    (* recursive case, keep moving down rows *)\nDefined.\n\n(** Testing Matrix Get/Set\n    - Want intuitive get/set functions\n*)\nDefinition inVec := (<[ <[ 0 ; 1] ; <[ 2; 3] ; <[ 4; 5]]).\nDefinition tMat2 := nMatrix 3 2 (<[ 0 ; 1]) eq_refl (nMatrix 2 2 (<[ 2 ; 3]) eq_refl\n  (nMatrix 1 2 (<[ 4 ; 5]) eq_refl (mtMatrix 0 2 eq_refl))).\n(* Testing gets *)\nExample testTmat2_get1 : matrix_get_value tMat2 0 0 = Some 0. reflexivity. Defined.\nExample testTmat2_get2 : matrix_get_value tMat2 0 1 = Some 1. reflexivity. Defined.\nExample testTmat2_get3 : matrix_get_value tMat2 1 0 = Some 2. reflexivity. Defined.\nExample testTmat2_get4 : matrix_get_value tMat2 1 1 = Some 3. reflexivity. Defined.\nExample testTmat2_get5 : matrix_get_value tMat2 2 0 = Some 4. reflexivity. Defined.\nExample testTmat2_get6 : matrix_get_value tMat2 2 1 = Some 5. reflexivity. Defined.\n(* Testing sets *)\nExample testTmat2_set1 : matrix_set_value tMat2 0 0 42 = \n  nMatrix 3 2 (<[ 42 ; 1]) eq_refl (\n    nMatrix 2 2 (<[ 2 ; 3]) eq_refl (\n      nMatrix 1 2 (<[ 4 ; 5]) eq_refl (\n        mtMatrix 0 2 eq_refl\n      )\n    )\n  ). reflexivity. Defined.\nExample testTmat2_set2 : matrix_set_value tMat2 0 1 42 = \n    nMatrix 3 2 (<[ 0 ; 42]) eq_refl (\n    nMatrix 2 2 (<[ 2 ; 3]) eq_refl (\n      nMatrix 1 2 (<[ 4 ; 5]) eq_refl (\n        mtMatrix 0 2 eq_refl\n      )\n    )\n  ). reflexivity. Defined.\nExample testTmat2_set3 : matrix_set_value tMat2 1 0 42 = \n    nMatrix 3 2 (<[ 0 ; 1]) eq_refl (\n    nMatrix 2 2 (<[ 42 ; 3]) eq_refl (\n      nMatrix 1 2 (<[ 4 ; 5]) eq_refl (\n        mtMatrix 0 2 eq_refl\n      )\n    )\n    ). reflexivity. Defined.\nExample testTmat2_set4 : matrix_set_value tMat2 1 1 42 = \n    nMatrix 3 2 (<[ 0 ; 1]) eq_refl (\n    nMatrix 2 2 (<[ 2 ; 42]) eq_refl (\n      nMatrix 1 2 (<[ 4 ; 5]) eq_refl (\n        mtMatrix 0 2 eq_refl\n      )\n    )\n  ). reflexivity. Defined.\nExample testTmat2_set5 : matrix_set_value tMat2 2 0 42 = \n    nMatrix 3 2 (<[ 0 ; 1]) eq_refl (\n    nMatrix 2 2 (<[ 2 ; 3]) eq_refl (\n      nMatrix 1 2 (<[ 42 ; 5]) eq_refl (\n        mtMatrix 0 2 eq_refl\n      )\n    )\n  ). reflexivity. Defined.\nExample testTmat2_set6 : matrix_set_value tMat2 2 1 42 = \n    nMatrix 3 2 (<[ 0 ; 1]) eq_refl (\n    nMatrix 2 2 (<[ 2 ; 3]) eq_refl (\n      nMatrix 1 2 (<[ 4 ; 42]) eq_refl (\n        mtMatrix 0 2 eq_refl\n      )\n    )\n  ). reflexivity. Defined.\n  \nFixpoint default_matrix {A : Type} `{H : Defaultable A} (n : nat) (m : nat) : (@Matrix A n m).\ndestruct n.\n- (* n = 0 (rows) *)\n  apply (@mtMatrix A 0 m eq_refl).\n- (* need Matrix (S n) m *)\n  pose proof (default_matrix A H n m).\n  pose proof (defaultable_vector m) as curRow.\n  destruct curRow.\n  apply (nMatrix (S n) m defVal eq_refl X).\nDefined.\n\n#[global]\nInstance defaultable_matrix {A : Type} `{H : Defaultable A} (n : nat) (m : nat) : Defaultable (@Matrix A n m) :=\n{\n  defVal := default_matrix n m\n}.\n\nFixpoint vec_of_vecs_to_matrix {A : Type} {rows cols : nat} \n    (vVec : (@Vector (@Vector A cols) rows)) : (@Matrix A rows cols).\ndestruct vVec eqn:VEC.\n- (* vVec = <[] *)\n  apply (mtMatrix 0 cols eq_refl).\n- (* vVec = x <:: v *) \n  pose proof (vec_of_vecs_to_matrix A n cols v).\n  apply (nMatrix (S n) cols x eq_refl X).\nDefined.\n\nModule MatrixNotations.\nDeclare Scope matrix_scope.\n(* For constructing matrices from the vector vector more easily *)\nNotation \"'MAT' v\" := (vec_of_vecs_to_matrix v) (at level 50) : matrix_scope.\n(* For lookup *)\nNotation \"m @[ x ][ y ]\" := (matrix_get_value m x y) (at level 70, right associativity) : matrix_scope.\n(* For setting values *)\nNotation \"m set@[ x ][ y ] <- v\" := (matrix_set_value m x y v) (at level 75, right associativity) :\nmatrix_scope.\nOpen Scope matrix_scope.\nEnd MatrixNotations.\n\nImport MatrixNotations.\nDefinition exampleMatrix : (@Matrix nat 2 2) :=\n  (nMatrix 2 2 (<[ 1 ; 2 ]) eq_refl (nMatrix 1 2 (<[ 3; 4]) eq_refl (mtMatrix 0 2 eq_refl))).\n\nExample em1test1 : (exampleMatrix @[1][1]) = Some 4. reflexivity. Defined.\nExample em1test2 : (exampleMatrix @[0][1]) = Some 2. reflexivity. Defined.\nExample vecGetTest : ((<[ 1 ; 2 ; 3]) <@[2]) = Some 3. reflexivity. Defined.\nExample em1setTest : (exampleMatrix set@[1][1] <- 42) = (nMatrix 2 2 (<[ 1 ; 2 ]) eq_refl (nMatrix 1 2 (<[ 3; 42]) eq_refl (mtMatrix 0 2 eq_refl))). reflexivity. Defined.\nExample defMatrices : ((@defaultable_matrix nat _ 3 3).(defVal))\n  = (nMatrix 3 3 (<[ 0 ; 0 ; 0 ]) eq_refl (nMatrix 2 3 (<[ 0 ; 0 ; 0]) eq_refl (nMatrix 1 3 (<[ 0 ; 0 ;0 ]) eq_refl (mtMatrix 0 3 eq_refl)))). reflexivity. Defined.\n(** Testing Matrix Notation\n    - We want the matrix notation to make sense and be easy to use\n*)\nDefinition tMat3 := (MAT <[ <[ 1 ; 2 ; 3] ; <[ 4 ; 5 ; 6] ; <[ 7 ; 8; 9]]).\n(* Testing getters *)\nExample testTmat3_get1 : tMat3 @[0][0] = Some 1. reflexivity. Defined.\nExample testTmat3_get2 : tMat3 @[1][1] = Some 5. reflexivity. Defined.\nExample testTmat3_get3 : tMat3 @[2][2] = Some 9. reflexivity. Defined.\nExample testTmat3_get4 : tMat3 @[0][2] = Some 3. reflexivity. Defined.\nExample testTmat3_get5 : tMat3 @[2][0] = Some 7. reflexivity. Defined.\n(* Testing setters *)\nExample testTmat3_set1 : (tMat3 set@[0][0] <- 42) =\n(MAT <[ <[ 42 ; 2 ; 3] ; <[ 4 ; 5 ; 6] ; <[ 7 ; 8; 9]]). reflexivity. Defined.\nExample testTmat3_set2 : (tMat3 set@[1][1] <- 42) =\n(MAT <[ <[ 1 ; 2 ; 3] ; <[ 4 ; 42 ; 6] ; <[ 7 ; 8; 9]]). reflexivity. Defined.\nExample testTmat3_set3 : (tMat3 set@[2][2] <- 42) =\n(MAT <[ <[ 1 ; 2 ; 3] ; <[ 4 ; 5 ; 6] ; <[ 7 ; 8; 42]]). reflexivity. Defined.\nExample testTmat3_set4 : (tMat3 set@[0][2] <- 42) =\n(MAT <[ <[ 1 ; 2 ; 42] ; <[ 4 ; 5 ; 6] ; <[ 7 ; 8; 9]]). reflexivity. Defined.\nExample testTmat3_set5 : (tMat3 set@[2][0] <- 42) =\n(MAT <[ <[ 1 ; 2 ; 3] ; <[ 4 ; 5 ; 6] ; <[ 42 ; 8; 9]]). reflexivity. Defined.\n\nFixpoint eqb_matrix {A : Type} `{H : EqClass A} \n    {rows1 cols1 rows2 cols2: nat}\n    (m1 : (@Matrix A rows1 cols1)) \n    (m2 : (@Matrix A rows2 cols2)): bool :=\n  match m1, m2 with\n  | mtMatrix r1 c1 _, mtMatrix r2 c2 _ =>\n      if (andb (eqb r1 r2) (eqb c1 c2))\n      then (* if number of rows and cols eq *)\n          true\n      else false\n  | nMatrix r1 c1 curR1 pf1 subM1, nMatrix r2 c2 curR2 pf2 subM2 =>\n      if (andb (eqb r1 r2) (andb (eqb c1 c2) (eqb_vector curR1 curR2)))\n      then (* rows, cols, and current row eq *)\n          eqb_matrix subM1 subM2\n      else false\n  | _, _ => false\n  end.\n\nExample eqb_matrix_test1 :\neqb_matrix (MAT <[ <[ 1 ; 2] ; <[ 3 ; 4]]) (MAT <[ <[ 1; 2] ; <[3;4]]) = true. reflexivity. Defined.\n\nLemma eqb_matrix_refl : forall {A : Type} `{H : EqClass A} {n m : nat}\n  (mat : (@Matrix A n m)),\n  eqb_matrix mat mat = true.\nProof.\n  induction mat; simpl; repeat (rewrite gen_deceq_eqb_refl); eauto.\n  simpl. rewrite eqb_vector_refl. auto.\nQed.\n\nTheorem eqb_matrix_same_length : forall {A : Type} {rows1 rows2 cols1 cols2 : nat} \n  `{H : EqClass A}\n  (m1 : (@Matrix A rows1 cols1)) (m2 : (@Matrix A rows2 cols2)),\n    eqb_matrix m1 m2 = true ->\n    rows1 = rows2 /\\ cols1 = cols2.\nProof.\n  induction m1; destruct m2; intros; inversion H0.\n  - destruct (gen_deceq_eqb rows rows0) eqn:Req;\n    destruct (gen_deceq_eqb cols cols0) eqn:Ceq; \n    simpl in *; try congruence.\n    apply gen_eqb_impl_eqb_leibniz in Req.\n    apply gen_eqb_impl_eqb_leibniz in Ceq; eauto.\n  - destruct (gen_deceq_eqb rows rows0) eqn:Req;\n    destruct (gen_deceq_eqb cols cols0) eqn:Ceq; \n    simpl in *; try congruence.\n    apply gen_eqb_impl_eqb_leibniz in Req.\n    apply gen_eqb_impl_eqb_leibniz in Ceq; eauto.\nQed.\n\nTheorem eqb_matrix_works : forall {A : Type} `{H : EqClass A} {rows cols : nat}\n  (m1 m2 : @Matrix A rows cols),\n  eqb_matrix m1 m2 = true ->\n  (forall (i j : nat),\n    (m1 @[i][j]) = (m2 @[i][j])).\nProof.\n  induction m1; destruct m2; eauto; intros; try inversion H0.\n  unfold matrix_get_value.\n  assert (gen_deceq_eqb rows rows = true). apply gen_eqb_impl_eqb_leibniz; auto.\n  assert (gen_deceq_eqb cols cols = true). apply gen_eqb_impl_eqb_leibniz; auto.\n  rewrite H1, H3 in *. simpl in H2.\n  destruct (eqb_vector curRow curRow0) eqn:EQvec.\n  - (* eqb_matrix m1 m2 = true *)\n    assert (rows' = rows'0). lia. subst.\n    pose proof (IHm1 m2 H2).\n    unfold matrix_get_value in H4.\n    destruct i.\n    * (* i = 0 *)\n      simpl. eapply eqb_vector_works. eauto.\n    * (* i = S i *) \n      simpl. eauto.\n  - congruence.\nQed.\n\nModule MatrixTypeClass.\n\n(** UIP is needed here because the proofs embedded in each matrix\n    are unable to be proven equal without it. \n    This is a safe assumption to make here as eq_refl on nats will\n    have unique identity proofs and should be considered roughly\n    proof irrelevant\n*)\nAxiom uip : forall A (x y : A) (p q : x = y), p = q.\n\n#[global]\nInstance deceq_matrix {A : Type} `{H : EqClass A} {n m : nat} : DecEq (@Matrix A n m).\nconstructor.\ninduction x1; destruct x2; simpl in *.\n- assert (e = e0). apply uip. subst. eauto.\n- right. qcon.\n- right. qcon.\n- destruct (eqb curRow curRow0) eqn:Eqvec.\n  * (* vecs eq *)\n    rewrite eqb_leibniz in Eqvec. subst.\n    assert (rows' = rows'0). lia. subst.\n    specialize IHx1 with x2.\n    destruct IHx1.\n    ** (* rest eq *)\n      subst. left.\n      assert (eq_refl = e0). eapply uip.\n      subst. eauto.\n    ** (* rest neq *) \n      right. qcon. \n      exT H1. exT H1. congruence.\n  * (* vecs neq *)\n    rewrite neqb_leibniz in Eqvec.\n    right. qcon. exT H2.\n    congruence.\nDefined.\n\n#[global]\nInstance eq_class_matrix {A : Type} `{H : EqClass A} {n m : nat} : EqClass (@Matrix A n m) :=\n{\n  eqb := gen_deceq_eqb ;\n  eqb_leibniz := gen_eqb_impl_eqb_leibniz ;\n  neqb_leibniz := gen_eqb_impl_neqb_leibniz ;\n}.\n\nEnd MatrixTypeClass.\n\n\nFixpoint matrix_entries {A : Type} {r c : nat} (m : @Matrix A r c) : list A :=\n  match m with\n  | mtMatrix _ _ _ => nil\n  | nMatrix rows cols curRow rPrf subMat =>\n      vec_to_list curRow ++ matrix_entries subMat\n  end.\n\nExample m_ent_1 : (matrix_entries (MAT <[ <[ 1;2] ; <[3;4]])) = [1;2;3;4].\nreflexivity. Defined.\n\nExample m_ent_2 : (matrix_entries (MAT <[ <[ 41;42;40] ; <[40;41;42]])) = [41;42;40;40;41;42].\nreflexivity. Defined.\n\nLemma in_app_impl_or_in : forall {A : Type} (l1 l2 : list A) x,\n  In x (l1 ++ l2) ->\n  In x l1 \\/ In x l2.\nProof.\n  induction l1; smp; eauto; intros.\n  dest H; eauto.\n  eapply IHl1 in H. dest H; eauto.\nQed.\n(* \nLemma matrix_column_height_change_get : forall {A : Type} {r c : nat}\n  (m : @Matrix A r c) curRow ent x,\n  forall (i j : nat), (nMatrix (S r) c curRow eq_refl m @[i][j] = Some ent) ->\n    exists (i j : nat), (nMatrix (S r) (S c) (x <:: curRow) eq_refl m @[i][j] = Some ent). *)\n\nLemma in_impl_exists'' : forall {A : Type} {c : nat} (curRow : @Vector A c) ent,\n  In ent (vec_to_list curRow) ->\n  (exists (j : nat), \n    curRow <@[j] = Some ent).\nProof.\n  induction curRow; intros; smp; eauto.\n  - inv H.\n  - dest H; subst.\n    * exists 0. refl.\n    * eapply IHcurRow in H. dest H. \n      exists (S x0); eauto.\nQed. \n\nLemma in_impl_exists' : forall {A : Type} {r c : nat} (curRow : @Vector A c) (m : @Matrix A r c) ent,\n  In ent (vec_to_list curRow) ->\n  exists (i j : nat), (nMatrix (S r) c curRow eq_refl m @[i][j] = Some ent).\nProof.\n  induction curRow; intros; eauto.\n  - inv H.\n  - inv H; subst.\n    * exists 0, 0. refl.\n    * exists 0. unfold matrix_get_value. smp.\n      pose proof (@in_impl_exists'' _ _ _ _ H0).\n      dest H1. exists (S x0). eauto.\nQed.\n\nLemma in_impl_exists : forall {A : Type} {r c : nat} (m : @Matrix A r c) ent,\n  In ent (matrix_entries m) ->\n  exists (i j : nat), (m @[i][j] = Some ent).\nProof.\n  induction m; intros; smp; eauto.\n  - inv H.\n  - apply in_app_impl_or_in in H. dest H.\n    * (* in curRow *) \n      dest (curRow); smp.\n      ** inv H.\n      ** eapply in_impl_exists'. eauto.\n    * eapply IHm in H. dest H. dest H.\n      exists (S x). exists x0. \n      unfold matrix_get_value; smp. eauto.\nQed.\n\nLemma all_matrix_entries_in_matrix : forall {A : Type} {r c : nat} (m : @Matrix A r c) lm,\n  matrix_entries m = lm ->\n  (forall ent, In ent lm ->\n      exists (i j : nat), m @[i][j] = Some ent).\nProof.\n  intros. rewrite <- H in *.\n  eapply in_impl_exists. eauto.\nQed.", "meta": {"author": "Durbatuluk1701", "repo": "coq-tactics", "sha": "18500e9602d875c167cf23a2c9bf411ac2007f63", "save_path": "github-repos/coq/Durbatuluk1701-coq-tactics", "path": "github-repos/coq/Durbatuluk1701-coq-tactics/coq-tactics-18500e9602d875c167cf23a2c9bf411ac2007f63/Datastructures/Matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7366916661200127}}
{"text": "From elpi Require Import elpi.\nFrom HB Require Import structures.\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** \n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Roadmap of the second lesson \n\n  Playing with basic arithmetics\n\n  - Order\n  - Division\n  - Primality\n\n#</div>#\n----------------------------------------------------------\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Reminder  \n\n  Natural numbers\n\n#<div>#\n*)\nCheck nat.\n(* nat : Set *)\n\nPrint nat.\n(* Inductive nat : Set :=\n   O : nat | S : nat -> nat *)\n\nCheck O.\n(* 0 : nat *)\n\nCheck S O.\n(* 1 : nat *)\n\nCheck S (S O).\n(* 2 : nat *)\n\nCheck 2.+1.\n(* 3 : nat *)\n\nSet Printing All.\nCheck 4.\n(* S (S (S O)) : nat *)\n\nUnset Printing All.\nCheck 5.\n(* 5 : nat *)\n\n(**\n#</div></div>#\n----------------------------------------------------------\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Reminder  \n\n  Proof by case \n\n#<div>#\n*)\n\nGoal forall (P : pred nat), \n     P 0 -> (forall n, P n.+1) -> forall n, P n.\nProof.\nmove=> P HP0 HPS n.\ncase: n => [|n].\n  exact: HP0.\nby apply: HPS.\nQed.\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Reminder  \n\n  Proof by induction \n\n#<div>#\n*)\n\nGoal forall (P : pred nat), \n     P 0 -> (forall n, P n -> P n.+1) -> forall n, P n.\nProof.\nmove=> P HP0 HPS n.\nelim: n => [|n IH].\n  exact: HP0.\nby apply: HPS.\nQed.\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Reminder  \n\n  Eq type \n\n#<div>#\n*)\n\nCheck eqn.\n(* eqn : nat -> nat -> bool *)\n\nPrint eqn.\n(* fix eqn (m n : nat) {struct m} : bool :=\n   match m with ... end. *)\n\nCompute 1 == 1.\n(* true : bool *)\n\nCompute 2 == 3.\n(* false : bool *)\n\nGoal forall m n, m.+1 == n.+1 -> m == n.\nProof.\nmove=> m n mEn.\nexact: mEn.\nQed.\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n \n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Natural numbers  \n\n  Addition\n#<div>#\n*)\n\nCheck addn.\n(* addn : nat -> nat -> nat *)\n\nCheck addn 2 3.\n(* 2 + 3 : nat *)\n\nCompute 2 + 3.\n(* 5 : nat *)\n\nGoal forall m n, m.+1 + n = (m + n).+1.\nProof.\nmove=> m n.\nby [].\nQed.\n\nSearch (_.+1 + _ = _.+1) in ssrnat.\n(*\nadd1n: forall n : nat, 1 + n = n.+1\naddSn: forall m n : nat, m.+1 + n = (m + n).+1\nadd2n: forall m : nat, 2 + m = m.+2\nadd3n: forall m : nat, 3 + m = m.+3\nadd4n: forall m : nat, 4 + m = m.+4\n*)\n\nGoal forall m n, m + n.+1 = (m + n).+1.\nProof.\nmove=> m n.\nelim: m => [|m IH].\n  by [].\nrewrite !addSn.\nrewrite IH.\nby [].\nQed.\n\nSearch (_ + _.+1 = _.+1) in ssrnat.\n(*\naddn1: forall n : nat, n + 1 = n.+1\naddnS: forall m n : nat, m + n.+1 = (m + n).+1\naddn2: forall m : nat, m + 2 = m.+2\naddn3: forall m : nat, m + 3 = m.+3\naddn4: forall m : nat, m + 4 = m.+4\n*)\n\nSearch (_.+1 + _ = _ + _.+1) in ssrnat.\n(* addSnnS: forall m n : nat, m.+1 + n = m + n.+1*)\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Natural Numbers  \n  Subtraction \n  \n#<div>#\n*)\n\nCheck subn.\n(* subn : nat -> nat -> nat *)\n\nCheck subn 3 2.\n(* 3 - 2 : nat *)\n\nCompute 3 - 2.\n(* 1 : nat *)\n\nCompute 3 - 4.\n(* 0 : nat *)\n\nGoal forall n, 0 - n = 0.\nProof.\nmove=> n.\nby [].\nQed.\n\nSearch left_zero subn in ssrnat.\n(* sub0n: left_zero 0 subn *)\n\nGoal forall n, n - 0 = n.\nProof.\ncase => [|n].\n- by [].\nby [].\nQed.\n\nSearch (_.+1 - _.+1 = _) in ssrnat.\n(* sub0n: left_zero 0 subn *)\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Natural Numbers  \n  Order \n  \n#<div>#\n*)\n\nCheck leq.\n(* nat -> nat -> bool *)\n\nCheck 0 <= 2.\n(* 0 <= 2 : bool *)\n\nCompute (0 <= 2).\n(* true : bool *)\n\nPrint leq.\n(* leq = fun m n : nat => m - n == 0\n     : nat -> nat -> bool\n*)\n\n(**\n#</div>#\n\n  One definition several notations  \n\n#<div>#\n  \n*)\n\nGoal forall m n, m >= n -> n <= m.\nProof.\nby [].\nQed.\n\nGoal forall m n, m.+1 <= n -> m < n.\nProof.\nby [].\nQed.\n\nGoal forall n, n <= n.+1.\nProof.\nelim=> [|n IH].\n  by [].\nexact: IH.\nQed.\n\nSearch (?_1 <= ?_1.+1) in ssrnat.\n(* eqnSn: forall n : nat, n <= n.+1 *)\n\n(**\n#</div>#\n\n  Reflexivity  \n\n#<div>#\n  \n*)\n\nSearch (?_1 <= ?_1) in ssrnat.\n(*\nleqnn: forall n : nat, n <= n\nltnSn: forall n : nat, n < n.+1\n*)\n\n(**\n#</div>#\n\n  Antisymmetry\n \n#<div>#\n  \n*)\n\nSearch (~~ _) (_ <= _) in ssrnat.\n(*#\nltnNge: forall m n : nat, (m < n) = ~~ (n <= m)\nleqNgt: forall m n : nat, (m <= n) = ~~ (n < m)\nlt0n_neq0: forall [n : nat], 0 < n -> n != 0\nltnNleqif: forall [x y : nat] [C : bool], x <= y ?= iff ~~ C -> (x < y) = C\nltn_leqif: forall [a b : nat] [C : bool], a <= b ?= iff C -> (a < b) = ~~ C\nlt0n: forall n : nat, (0 < n) = (n != 0)\neqn0Ngt: forall n : nat_eqType, (n == 0) = ~~ (0 < n)\ncontraNleq: forall [b : bool] [m n : nat], (n < m -> b) -> ~~ b -> m <= n\ncontra_leqT: forall [b : bool] [m n : nat], (~~ b -> m < n) -> n <= m -> b\ncontra_ltnT: forall [b : bool] [m n : nat], (~~ b -> m <= n) -> n < m -> b\ncontraTleq: forall [b : bool] [m n : nat], (n < m -> ~~ b) -> b -> m <= n\ncontraNltn: forall [b : bool] [m n : nat], (n <= m -> b) -> ~~ b -> m < n\ncontra_ltnN: forall [b : bool] [m n : nat], (b -> m <= n) -> n < m -> ~~ b\ncontraTltn: forall [b : bool] [m n : nat], (n <= m -> ~~ b) -> b -> m < n\ncontra_leqN: forall [b : bool] [m n : nat], (b -> m < n) -> n <= m -> ~~ b\n#*)\n\nSearch (_ == _ = _) (_ <= _) in ssrnat.\n(*#\nsubn_eq0: forall m n : nat, (m - n == 0) = (m <= n)\neqn0Ngt: forall n : nat_eqType, (n == 0) = ~~ (0 < n)\neqn_leq: forall m n : nat_eqType, (m == n) = (m <= n <= m)\nltn_eqF: forall [m n : nat], m < n -> (m == n) = false\ngtn_eqF: forall [m n : nat], m < n -> (n == m) = false\nneq0_lt0n: forall [n : nat_eqType], (n == 0) = false -> 0 < n\nexpn_eq0: forall m e : nat, (m ^ e == 0) = (m == 0) && (0 < e)\neqn_pmul2l: forall [m n1 n2 : nat], 0 < m -> (m * n1 == m * n2) = (n1 == n2)\neqn_exp2r: forall (m n : nat) [e : nat], 0 < e -> (m ^ e == n ^ e) = (m == n)\neqn_pmul2r: forall [m n1 n2 : nat], 0 < m -> (n1 * m == n2 * m) = (n1 == n2)\neqn_exp2l:\n  forall [m : nat] (n1 n2 : nat), 1 < m -> (m ^ n1 == m ^ n2) = (n1 == n2)\n#*)\n\n(**\n#</div>#\n\n  Transitivity\n \n#<div>#\n  \n*)\n\nSearch nat \"trans\" in ssrnat.\n(*#\nleq_trans: forall [n m p : nat], m <= n -> n <= p -> m <= p\nleqif_trans:\n  forall [m1 m2 m3 : nat] [C12 C23 : bool],\n  m1 <= m2 ?= iff C12 -> m2 <= m3 ?= iff C23 -> m1 <= m3 ?= iff C12 && C23\nleq_ltn_trans: forall [n m p : nat], m <= n -> n < p -> m < p\nltn_trans: forall [n m p : nat], m < n -> n < p -> m < p\n#*)\n\nGoal forall m n p, m < n -> n <= p -> m < p.\nProof.\nmove=> m n p.\nhave trans := leq_trans.\nhave trans_Sm_n := leq_trans (_ : m < n) (_ : n <= p).\nby [].\nQed.\n\nGoal forall (P : pred nat), \n      P 0 ->\n      (forall m,  (forall n, n <= m -> P n) -> P m.+1) ->\n      (forall m, P m).\nProof.\nmove=> P HC IHs m.\nmove: (leqnn m).\nmove: {-2}m.\nelim: m => [|m IH].\n  by case.\ncase=> // n nLm.\napply: IHs => k kLn.\napply: IH.\napply: leq_trans kLn nLm.\nQed.\n\nGoal forall a b c,\n   a < b -> b < c -> a <= c.\nProof.\nmove=> a b c aLb bLc.\napply: leq_trans (_ : b <= _).\n  by apply: ltnW.\nby apply: ltnW.\nQed.\n\n(**\n#</div>#\n\n  Proof by case\n \n#<div>#\n  \n*)\n\nGoal forall (m : nat) (n : nat) (P : nat -> bool), \n   (n <= m -> P n) -> (m < n -> P n) -> P n.\nProof.\nmove=> m n P LP GP.\ncase: (leqP n m).\n  by apply: LP.\nby apply: GP.\nQed.\n\nGoal forall (m : nat) (n : nat) (P : nat -> bool), \n   (n < m -> P n) -> (m < n -> P n) -> (n = m -> P n) -> P n.\nProof.\nmove=> m n P LP GP EP.\ncase: (ltngtP n m).\n- by apply: LP.\n- by apply: GP.\nby apply: EP.\nQed.\n\nCheck leq_eqVlt.\n(* leq_eqVlt\n\t : forall m n : nat, (m <= n) = (m == n) || (m < n)\n*)\n\nGoal forall (P : pred nat) m n, P n ->\n    (m < n -> P m) -> m <= n -> P m.\nProof.\nmove=> P m n Pn PL.\nrewrite leq_eqVlt.\nmove=> /orP[|].\n  move/eqP->.\n  by [].\nexact: PL.\nQed.\n\nGoal forall (P : pred nat) m n, P n ->\n    (m < n -> P m) -> m <= n -> P m.\nProof.\nmove=> P m n Pn GP.\ncase: ltngtP.\n- move=> mLn _.\n  by apply: GP.\n- by [].\nmove=> -> _.\nexact: Pn.\nQed.\n\n(**\n#</div>#\n\n  Addition\n  \n#<div>#\n  \n*)\n\nSearch (_ <= _ + _) in ssrnat.\n(*#\nleq_addr: forall m n : nat, n <= n + m\nleq_addl: forall m n : nat, n <= m + n\nleq_add2r: forall p m n : nat, (m + p <= n + p) = (m <= n)\nleq_add2l: forall p m n : nat, (p + m <= p + n) = (m <= n)\nltn_addl: forall [m n : nat] (p : nat), m < n -> m < p + n\nleq_subLR: forall m n p : nat, (m - n <= p) = (m <= n + p)\nltn_addr: forall [m n : nat] (p : nat), m < n -> m < n + p\nltn_add2r: forall p m n : nat, (m + p < n + p) = (m < n)\nltn_add2l: forall p m n : nat, (p + m < p + n) = (m < n)\nleq_add:\n  forall [m1 m2 n1 n2 : nat], m1 <= n1 -> m2 <= n2 -> m1 + m2 <= n1 + n2\naddn_gt0: forall m n : nat, (0 < m + n) = (0 < m) || (0 < n)\nltn_subLR: forall [m n : nat] (p : nat), n <= m -> (m - n < p) = (m < n + p)\nltn_psubLR: forall (m n : nat) [p : nat], 0 < p -> (m - n < p) = (m < n + p)\n#*)\n\nGoal forall m n, n <= m -> n.*2 <= m + n.\nProof.\nmove=> m n nLm.\nrewrite -addnn.\nrewrite leq_add2r.\nby [].\nQed.\n\n(**\n#</div>#\n\n  Multiplication\n  \n#<div>#\n  \n*)\n\nSearch  _ (_ <= _ * _) in ssrnat.\n(*#\nleq_pmulr: forall (m : nat) [n : nat], 0 < n -> m <= m * n\nleq_pmull: forall (m : nat) [n : nat], 0 < n -> m <= n * m\nleq_mul:\n  forall [m1 m2 n1 n2 : nat], m1 <= n1 -> m2 <= n2 -> m1 * m2 <= n1 * n2\nltn_Pmull: forall [m n : nat], 1 < n -> 0 < m -> m < n * m\nltn_Pmulr: forall [m n : nat], 1 < n -> 0 < m -> m < m * n\nmuln_gt0: forall m n : nat, (0 < m * n) = (0 < m) && (0 < n)\nltn_mul: forall [m1 m2 n1 n2 : nat], m1 < n1 -> m2 < n2 -> m1 * m2 < n1 * n2\nleq_pmul2l: forall [m n1 n2 : nat], 0 < m -> (m * n1 <= m * n2) = (n1 <= n2)\nleq_pmul2r: forall [m n1 n2 : nat], 0 < m -> (n1 * m <= n2 * m) = (n1 <= n2)\nleq_mul2r: forall m n1 n2 : nat, (n1 * m <= n2 * m) = (m == 0) || (n1 <= n2)\nleq_mul2l: forall m n1 n2 : nat, (m * n1 <= m * n2) = (m == 0) || (n1 <= n2)\nltn_mul2l: forall m n1 n2 : nat, (m * n1 < m * n2) = (0 < m) && (n1 < n2)\nltn_mul2r: forall m n1 n2 : nat, (n1 * m < n2 * m) = (0 < m) && (n1 < n2)\nltn_pmul2r: forall [m n1 n2 : nat], 0 < m -> (n1 * m < n2 * m) = (n1 < n2)\nltn_pmul2l: forall [m n1 n2 : nat], 0 < m -> (m * n1 < m * n2) = (n1 < n2)\n#*)\n\nGoal forall m n, n <= m -> n ^ 2 <= m * n.\nProof.\nmove=> m n nLm.\nrewrite -mulnn.\nrewrite leq_mul2r.\nrewrite nLm.\nrewrite orbT.\nby [].\nQed.\n\n(** Conditional comparison **)\n\nSearch (_ <= _ ?= iff _) (_ && _) in ssrnat.\n(*#\neqif_trans:\n  forall [m1 m2 m3 : nat] [C12 C23 : bool],\n  m1 <= m2 ?= iff C12 -> m2 <= m3 ?= iff C23 -> m1 <= m3 ?= iff C12 && C23\nleqif_add:\n  forall [m1 n1 : nat] [C1 : bool] [m2 n2 : nat] [C2 : bool],\n  m1 <= n1 ?= iff C1 ->\n  m2 <= n2 ?= iff C2 -> m1 + m2 <= n1 + n2 ?= iff C1 && C2\nleqif_mul:\n  forall [m1 n1 : nat] [C1 : bool] [m2 n2 : nat] [C2 : bool],\n  m1 <= n1 ?= iff C1 ->\n  m2 <= n2 ?= iff C2 -> m1 * m2 <= n1 * n2 ?= iff (n1 * n2 == 0) || C1 && C2\n#*)\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Natural Numbers  \n\n  Division \n  \n#<div>#\n*)\n\nCheck (modn 21 2).\n(* 21 %% 2 : nat *)\n\nCompute 21 %% 2.\n(* 1 : nat *)\n\nCheck (divn 21 2).\n(* 21 %/ 2 : nat *)\n\nCompute 21 %/ 2.\n(* 10 : nat *)\n\nCheck (dvdn 2 21).\n\nCompute 2 %| 21.\n\nPrint dvdn.\n(*#\ndvdn = fun d m : nat => m %% d == 0\n\t : nat -> nat -> bool\n#*)\n\nSearch (_ %| _ + _) in div.\n(*# \ndvdn_add: forall [d m n : nat], d %| m -> d %| n -> d %| m + n\ndvdn_add_eq: forall [d m n : nat], d %| m + n -> (d %| m) = (d %| n)\ndvdn_addl: forall [n d : nat] (m : nat), d %| n -> (d %| m + n) = (d %| m)\ndvdn_addr: forall [m d : nat] (n : nat), d %| m -> (d %| m + n) = (d %| n)\nBezoutl:\n  forall [m : nat] (n : nat),\n  0 < m -> {a : nat | a < m & m %| gcdn m n + a * n}\nBezoutr:\n  forall (m : nat) [n : nat],\n  0 < n -> {a : nat | a < n & n %| gcdn m n + a * m}\n#*)\n\nSearch ((_ + _) %/ _) in div.\n(*#\ndivnDr:\n  forall (m : nat) [n d : nat], d %| n -> (m + n) %/ d = m %/ d + n %/ d\ndivnDl:\n  forall [m : nat] (n : nat) [d : nat],\n  d %| m -> (m + n) %/ d = m %/ d + n %/ d\nleq_divDl: forall p m n : nat, (m + n) %/ p <= m %/ p + n %/ p + 1\ndivnDMl: forall (q m : nat) [d : nat], 0 < d -> (m + q * d) %/ d = m %/ d + q\ndivnMDl: forall (q m : nat) [d : nat], 0 < d -> (q * d + m) %/ d = q + m %/ d\ndivnD:\n  forall (m n : nat) [d : nat],\n  0 < d -> (m + n) %/ d = m %/ d + n %/ d + (d <= m %% d + n %% d)\n#*)\n\nSearch (?_1 %/ ?_1) in div.\n(*# divnn: forall d : nat, d %/ d = (0 < d) #*)\n\nCompute 0 %/ 0.\n(*# 0 : nat #*)\n\nSearch (_ %| _ * _) in div.\n(*# \ndvdn_mulr: forall [d m : nat] (n : nat), d %| m -> d %| m * n\ndvdn_mull: forall [d : nat] (m : nat) [n : nat], d %| n -> d %| m * n\ndvdn_mul:\n  forall [d1 d2 m1 m2 : nat], d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2\nGauss_dvdl:\n  forall [m : nat] (n : nat) [p : nat],\n  coprime m p -> (m %| n * p) = (m %| n)\nGauss_dvdr:\n  forall [m n : nat] (p : nat), coprime m n -> (m %| n * p) = (m %| p)\ndvdn_pmul2l: forall [p d m : nat], 0 < p -> (p * d %| p * m) = (d %| m)\ndvdn_pmul2r: forall [p d m : nat], 0 < p -> (d * p %| m * p) = (d %| m)\ndvdn_divLR:\n  forall [p d : nat] (m : nat),\n  0 < p -> p %| d -> (d %/ p %| m) = (d %| m * p)\n#*)\n\nSearch ((_ * _) %/ _) in div.\n(*#\ndivnA: forall (m : nat) [n p : nat], p %| n -> m %/ (n %/ p) = (m * p) %/ n\nmuln_divA:\n  forall [d : nat] (m : nat) [n : nat], d %| n -> m * (n %/ d) = (m * n) %/ d\ndivn_mulAC: forall [d m : nat] (n : nat), d %| m -> m %/ d * n = (m * n) %/ d\nmulKn: forall (m : nat) [d : nat], 0 < d -> (d * m) %/ d = m\nmulnK: forall (m : nat) [d : nat], 0 < d -> (m * d) %/ d = m\ndivnMl: forall [p m d : nat], 0 < p -> (p * m) %/ (p * d) = m %/ d\ndivnMr: forall [p m d : nat], 0 < p -> (m * p) %/ (d * p) = m %/ d\n#*)\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Natural Numbers  \n\n  Odd \n  \n#<div>#\n*)\n\nCompute odd 4.\n(* false : bool *)\n\nCompute odd 5.\n(* true : bool *)\n\nPrint odd.\n(* \nodd = \nfix odd (n : nat) : bool :=\n  match n with\n  | 0 => false\n  | n'.+1 => ~~ odd n'\n  end\n\t : nat -> bool\n*)\n\nSearch odd (_ %% _) in div.\n(*# \nmodn2: forall m : nat, m %% 2 = odd m\nodd_mod: forall (m : nat) [d : nat], odd d = false -> odd (m %% d) = odd m\n#*)\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Natural Numbers  \n\n  Gcd and Lcm\n  \n#<div>#\n*)\n\nCompute gcdn 42 49.\n(* 7 : nat *)\n\nCompute lcmn 42 49.\n(* 294 : nat *)\n\nSearch gcdn lcmn in div.\n(* \nmuln_lcm_gcd: forall m n : nat, lcmn m n * gcdn m n = m * n\n*)\n\nSearch gcdn (_ * _) in div.\n(*# \ngcdnMr: forall n m : nat, gcdn n (n * m) = n\ngcdnMl: forall n m : nat, gcdn n (m * n) = n\nmuln_lcm_gcd: forall m n : nat, lcmn m n * gcdn m n = m * n\ngcdnMDl: forall k m n : nat, gcdn m (k * m + n) = gcdn m n\nmuln_divCA_gcd: forall n m : nat, n * (m %/ gcdn n m) = m * (n %/ gcdn n m)\nGauss_gcdl:\n  forall [p : nat] (m : nat) [n : nat],\n  coprime p n -> gcdn p (m * n) = gcdn p m\nGauss_gcdr:\n  forall [p m : nat] (n : nat), coprime p m -> gcdn p (m * n) = gcdn p n\nBezoutl:\n  forall [m : nat] (n : nat),\n  0 < m -> {a : nat | a < m & m %| gcdn m n + a * n}\nBezoutr:\n  forall (m : nat) [n : nat],\n  0 < n -> {a : nat | a < n & n %| gcdn m n + a * m}\nEgcdnSpec:\n  forall [m n km kn : nat],\n  km * m = kn * n + gcdn m n -> kn * gcdn m n < m -> egcdn_spec m n (km, kn)\n#*)\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n(**\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Natural Numbers  \n\n  Coprime & Prime \n  \n#<div>#\n*)\n\nCheck coprime.\n(* coprime : nat -> nat -> bool *)\n\nCompute coprime 3 5.\n(* true : bool *)\n\nCompute coprime 21 7.\n(* false : true *)\n\nPrint coprime.\n(* \ncoprime = fun m n : nat => gcdn m n == 1\n\t : nat -> nat -> bool\n*)\n\nSearch coprime (_ %| _) in div prime.\n(*#\ncoprime_dvdr: forall [m n p : nat], m %| n -> coprime p n -> coprime p m\ncoprime_dvdl: forall [m n p : nat], m %| n -> coprime n p -> coprime m p\nprime_coprime:\n  forall [p : nat] (m : nat), prime p -> coprime p m = ~~ (p %| m)\nGauss_dvdr:\n  forall [m n : nat] (p : nat), coprime m n -> (m %| n * p) = (m %| p)\nGauss_dvdl:\n  forall [m : nat] (n : nat) [p : nat],\n  coprime m p -> (m %| n * p) = (m %| n)\nGauss_dvd:\n  forall [m n : nat] (p : nat),\n  coprime m n -> (m * n %| p) = (m %| p) && (n %| p)\n#*)\n\nCheck prime.\n(* prime : nat -> bool *)\n\nCompute prime 21.\n(* false : bool *)\n\nCompute prime 22.\n(* false : bool *)\n\nCompute prime 23.\n(* true : bool *)\n\nPrint prime.\n(*#\nprime = \nfun p : nat =>\nmatch prime_decomp p with\n| [:: (_, 1)]  => true\n| _ => false\nend     : nat -> bool\n#*)\n\nCompute primes 21.\n(*# [:: 3, 7] : seq nat #*)\nCompute primes 22.\n(*# [:: 2; 11] : seq nat #*)\n\nCompute primes 23.\n(*# [:: 23] : seq nat #*)\n\nCheck primeP.\n(*# \nprimeP\n\t : reflect (1 < ?p /\\ (forall d : nat, d %| ?p -> (d == 1) || (d == ?p)))\n         (prime ?p)\n#*)\n\nGoal prime 2.\nProof.\napply/primeP.\nsplit.\n  by [].\nmove=> d.\ncase: d.\n  by [].\ncase.\n  by [].\nby case.\nQed.\n\nSearch prime (_ %| _) in div prime.\n(*#\nEuclid_dvd1: forall [p : nat], prime p -> (p %| 1) = false\nprime_coprime:\n  forall [p : nat] (m : nat), prime p -> coprime p m = ~~ (p %| m)\ndvdn_prime2: forall [p q : nat], prime p -> prime q -> (p %| q) = (p == q)\npdivP: forall [n : nat], 1 < n -> {p : nat | prime p & p %| n}\nEuclid_dvdM:\n  forall (m n : nat) [p : nat],\n  prime p -> (p %| m * n) = (p %| m) || (p %| n)\np'natE: forall [p : nat] (n : nat), prime p -> (p^').-nat n = ~~ (p %| n)\nEuclid_dvdX:\n  forall (m n : nat) [p : nat], prime p -> (p %| m ^ n) = (p %| m) && (0 < n)\ndvdn_pfactor:\n  forall [p : nat] (d n : nat),\n  prime p -> reflect (exists2 m : nat, m <= n & d = p ^ m) (d %| p ^ n)\nlognE:\n  forall p m : nat,\n  logn p m =\n  (if [&& prime p, 0 < m & p %| m] then (logn p (m %/ p)).+1 else 0)\npfactor_dvdn:\n  forall [p : nat] (n : nat) [m : nat],\n  prime p -> 0 < m -> (p ^ n %| m) = (n <= logn p m)\nprime_nt_dvdP:\n  forall [d : nat_eqType] [p : nat],\n  prime p -> d != 1 -> reflect (d = p) (d %| p)\npnatP:\n  forall (pi : nat_pred) [n : nat],\n  0 < n ->\n  reflect (forall p : nat, prime p -> p %| n -> p \\in pi) (pi.-nat n)\nmem_primes:\n  forall (p : nat_eqType) (n : nat),\n  (p \\in primes n) = [&& prime p, 0 < n & p %| n]\nprimePn:\n  forall {n : nat},\n  reflect (n < 2 \\/ (exists2 d : nat, 1 < d < n & d %| n)) (~~ prime n)\nlogn_count_dvd:\n  forall [p : nat] (n : nat),\n  prime p -> logn p n = \\sum_(1 <= k < n) (p ^ k %| n)\nprimePns:\n  forall {n : nat},\n  reflect (n < 2 \\/ (exists p : nat, [/\\ prime p, p ^ 2 <= n & p %| n]))\n\t(~~ prime n)\nprimeP:\n  forall {p : nat},\n  reflect (1 < p /\\ (forall d : nat, d %| p -> xpred2 1 p d)) (prime p)\nEuclid_dvd_prod:\n  forall [I : Type] (r : seq I) (P : pred I) (f : I -> nat) [p : nat],\n  prime p ->\n  (p %| \\prod_(i <- r | P i) f i) = \\big[orb/false]_(i <- r | P i) (p %| f i)\nmem_prime_decomp:\n  forall [n : nat] [p e : nat_eqType],\n  (p, e) \\in prime_decomp n -> [/\\ prime p, 0 < e & p ^ e %| n]\n#*)\n\nCheck logn.\n(* logn : nat -> nat -> nat*)\n\nCompute logn 3 8.\n(* 0 : nat *)\nCompute logn 3 9.\n(* 2 : nat *)\n\nSearch logn in prime.\n(*# \nlogn0: forall p : nat, logn p 0 = 0\nlogn1: forall p : nat, logn p 1 = 0\npfactor_dvdnn: forall p n : nat, p ^ logn p n %| n\nlogn_part: forall p m : nat, logn p m`_p = logn p m\nlogn_coprime: forall [p m : nat], coprime p m -> logn p m = 0\nlognX: forall p m n : nat, logn p (m ^ n) = n * logn p m\np_part: forall p n : nat, n`_p = p ^ logn p n\npfactorK: forall [p : nat] (n : nat), prime p -> logn p (p ^ n) = n\npfactor_gt0: forall p n : nat, 0 < p ^ logn p n\nltn_logl: forall (p : nat) [n : nat], 0 < n -> logn p n < n\nltn_log0: forall [p n : nat], n < p -> logn p n = 0\nlogn_Gauss:\n  forall [p m : nat] (n : nat), coprime p m -> logn p (m * n) = logn p n\npfactorKpdiv:\n  forall [p : nat] (n : nat), prime p -> logn (pdiv (p ^ n)) (p ^ n) = n\nlogn_prime: forall (p : nat) [q : nat], prime q -> logn p q = (p == q)\nlogn_div:\n  forall (p : nat) [m n : nat],\n  m %| n -> logn p (n %/ m) = logn p n - logn p m\ndvdn_leq_log:\n  forall (p : nat) [m n : nat], 0 < n -> m %| n -> logn p m <= logn p n\nprime_decompE:\n  forall n : nat, prime_decomp n = [seq (p, logn p n) | p <- primes n]\neqn_from_log:\n  forall [m n : nat], 0 < m -> 0 < n -> logn^~ m =1 logn^~ n -> m = n\nlogn_gt0: forall p n : nat, (0 < logn p n) = (p \\in primes n)\nlognE:\n  forall p m : nat,\n  logn p m =\n  (if [&& prime p, 0 < m & p %| m] then (logn p (m %/ p)).+1 else 0)\nlogn_lcm:\n  forall (p : nat) [m n : nat],\n  0 < m -> 0 < n -> logn p (lcmn m n) = maxn (logn p m) (logn p n)\nlognM:\n  forall (p : nat) [m n : nat],\n  0 < m -> 0 < n -> logn p (m * n) = logn p m + logn p n\nlogn_gcd:\n  forall (p : nat) [m n : nat],\n  0 < m -> 0 < n -> logn p (gcdn m n) = minn (logn p m) (logn p n)\npfactor_dvdn:\n  forall [p : nat] (n : nat) [m : nat],\n  prime p -> 0 < m -> (p ^ n %| m) = (n <= logn p m)\npfactor_coprime:\n  forall [p n : nat],\n  prime p -> 0 < n -> {m : nat | coprime p m & n = m * p ^ logn p n}\nlogn_count_dvd:\n  forall [p : nat] (n : nat),\n  prime p -> logn p n = \\sum_(1 <= k < n) (p ^ k %| n)\ntotientE:\n  forall [n : nat],\n  0 < n -> totient n = \\prod_(p <- primes n) (p.-1 * p ^ (logn p n).-1)\nwiden_partn:\n  forall [m : nat] (pi : nat_pred) [n : nat],\n  n <= m -> n`_pi = \\prod_(0 <= p < m.+1 | p \\in pi) p ^ logn p n\neq_partn_from_log:\n  forall [m n : nat] [pi : nat_pred],\n  0 < m -> 0 < n -> {in pi, logn^~ m =1 logn^~ n} -> m`_pi = n`_pi\n#*)\n\n(**\n----------------------------------------------------------\n#</div>#\n#</div>#\n*)\n\n", "meta": {"author": "gares", "repo": "math-comp-school-2022", "sha": "d7f18a5c9afd2659426be21ef54bec119451446c", "save_path": "github-repos/coq/gares-math-comp-school-2022", "path": "github-repos/coq/gares-math-comp-school-2022/math-comp-school-2022-d7f18a5c9afd2659426be21ef54bec119451446c/lesson2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.736499599960628}}
{"text": "Inductive bird : Set :=\n  | app : bird -> bird -> bird.\n\nModule thm_9_3.\n\n  Variable A : bird. (* 同調鳥を示す変数 *)\n\n  (*\n    合成鳥の存在を示すのと同値な仮定\n    (鳥の合成ルールを示す仮定)\n  *)\n  Hypothesis Hc : forall (A B x : bird), app A (app B x) = app (app A B) x.\n\n  (* 同調鳥の性質を示す仮定 *)\n  Hypothesis Ha : forall (B : bird), (exists (x' : bird), app A x' = app B x').\n  Hypothesis Ha' : forall (x : bird), (exists (x' : bird), app A x' = app (app x A) x').\n  (*\n    Coqの証明で、HaからHa'を導く手順がわからなかったため、\n    今回は手動でHa'を作成し、Ha'を使って証明。\n  *)\n\n  Theorem thm_9_3 :\n    forall (P : bird),\n      exists (x : bird), app P x = x.\n    (*\n      結論：\n      任意の P について、ある x が存在して、 P x = x となる。\n    *)\n  Proof.\n    intros P.\n    destruct Ha' with (x := P) as [x' Ha''].\n    exists (app A x').\n    rewrite Hc with (A := P) (B := A) (x := x').\n    rewrite Ha''.\n    reflexivity.\n  Qed.\n\n  From mathcomp\n  Require Import ssreflect.\n\n  Theorem thm_9_3_ssr :\n    forall (P : bird),\n      exists (x : bird), app P x = x.\n  Proof.\n    move=> P.\n    case Ha' with (x := P) => [x' Ha''].\n    exists (app A x').\n    rewrite Hc.\n    rewrite Ha''.\n    done.\n  Qed.\n\nEnd thm_9_3.\n", "meta": {"author": "wakaba2017", "repo": "To_mock_a_mockingbird", "sha": "400d7b452f9e9e8f0b4dff8e4947b731fc29a5bb", "save_path": "github-repos/coq/wakaba2017-To_mock_a_mockingbird", "path": "github-repos/coq/wakaba2017-To_mock_a_mockingbird/To_mock_a_mockingbird-400d7b452f9e9e8f0b4dff8e4947b731fc29a5bb/thm_9_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7364995972035168}}
{"text": "Set Implicit Arguments.\nUnset Printing Implicit Defensive.\nUnset Strict Implicit.\nSet Contextual Implicit.\n\nRequire Import\n        List \n        Finite.FiniteType\n        Tactics.Tactics.\n\nImport ListNotations.\n\n\n(** definition of a DFA *)\n\nSection DFA.\n  Variable sigma : finType.\n\n  Definition word := list sigma.\n  Definition epsilon : word := (@nil sigma).\n\n  Record dfa : Type\n    := DFA { \n        S :> finType      (** state set      *)\n      ; s : S             (** starting state *)\n      ; F : dec_pred S    (** final state predicate *)\n      ; d : S -> sigma -> S (** transition function *)\n      }.\n\n  Section ACCEPT.\n    Variable M : dfa.\n\n  (** extended transition function *)\n\n    Fixpoint d_star (q : M)(w : word) :=\n      match w with \n      | [] => q\n      | c :: w' => d_star (d q c) w'\n      end.\n\n    Definition accept (w : word) := F (@d_star s w).\n\n    Instance accept_dec w : dec (accept w).\n    Proof.\n      auto.\n    Defined.\n\n    Inductive reach (q : M) : M -> Prop :=\n    | Refl : reach q q\n    | Step q' c : reach (d q c) q' -> reach q q'.\n\n    Hint Constructors reach.\n\n    Definition reach_with q w q' := d_star q w = q'.\n\n    Lemma reach_is_reach_with (q q' : M) : reach q q' <-> exists w, reach_with q w q'.\n    Proof.\n      split.\n      +\n        intros H ; induction H ; crush.\n        -\n          now exists epsilon.\n        - \n          exists (c :: x) ; crush.\n      +\n        intros [w H]. revert q H ; induction w ; intros q H ; crush.\n        -\n          econstructor 2.\n          apply IHw.\n          apply H.\n    Qed.\n\n    Hint Resolve reach_is_reach_with.\n\n    Lemma reach_transitive (q : M ) q' q'': reach q q' /\\ reach q' q'' -> reach q q''.\n    Proof.\n      intros [R R']. induction R ; eauto.\n    Qed.\n\n    Lemma reach_d_star q w: reach q (d_star q w).\n    Proof.\n      apply reach_is_reach_with. now exists w.\n    Qed.\n\n    Definition step_reach (states : list M)(q : M)\n      := exists q' x, q' el states /\\ reach_with q' [x] q.\n\n    Lemma step_reach_consistent: step_consistent step_reach.\n    Proof.\n      intros B q H B' sub.\n      destruct H as [q' [x [E R]]].\n      exists* q' x. \n    Qed.    \n\n    Definition reachable_states (q : M) := finite_iter step_reach [q].\n\n    Lemma reachable_states_least_fp q\n      : least_fp_containing (finite_iter_step step_reach)\n                            (reachable_states q) [q].\n    Proof.\n      apply step_consistent_least_fp.\n      apply step_reach_consistent.\n    Qed.\n\n    Lemma reachable_states_correct1 (q : M) : inclp (reachable_states q) (reach q).\n    Proof.\n      apply finite_iter_ind.\n      -\n        intros x ; crush.\n      -\n        intros set q' H [q'' [x [E H1]]] ; eapply reach_transitive ; split.\n        +\n          apply (H _ E).\n        +\n          apply reach_is_reach_with.\n          exists* [x].\n    Qed.\n\n    Lemma reachable_states_correct2' q q' : q' el reachable_states q ->\n                                 forall q'', reach q' q'' -> q'' el reachable_states q.\n    Proof.\n      intros E q'' H ; induction H ; crush.\n      -\n        apply IHreach. apply closure_finite_iter. now exists* q0 c.\n    Qed.\n\n    Lemma reachable_states_correct2 q: forall q', reach q q' -> q' el reachable_states q.\n    Proof.\n      apply reachable_states_correct2'. apply preservation_finite_iter ; crush.\n    Qed.        \n\n    Lemma reachable_states_correct q q' : reach q q' <-> q' el (reachable_states q).\n    Proof.\n      split ; [ apply reachable_states_correct2\n              | apply reachable_states_correct1].\n    Qed.\n\n    Global Instance reach_dec q q': dec (reach q q').\n    Proof.\n      eapply dec_prop_iff.\n      -\n        symmetry. apply reachable_states_correct.\n      - auto.\n    Qed.    \n\n    Global Instance reach_with_something_dec q q' : dec (exists w, reach_with q w q').\n    Proof.\n      apply dec_prop_iff with (X := reach q q') ; eauto.\n    Qed.\n\n    Lemma reachable_states_reach_with q q'\n      : (exists w, reach_with q w q') <-> q' el reachable_states q.\n    Proof.\n      rewrite <- reach_is_reach_with.  apply reachable_states_correct.\n    Qed.\n\n    Lemma d_star_reachable_states w q : d_star q w el (reachable_states q).\n    Proof.\n      apply reachable_states_reach_with. now exists w.\n    Qed.\n\n    Notation in_lang w := (accept w) (only parsing).\n\n    (** accepting all words in sigma* *)\n\n    Lemma accepts_sigma_star_if_all_states_final\n      : (forall w, in_lang w) <-> forall q : M, q el (reachable_states s) -> F q.\n    Proof.\n      split.\n      -\n        intros H q Hel.\n        rewrite <- reachable_states_reach_with in Hel.\n        destruct Hel as [w Hw]. unfolds in Hw.\n        rewrite <- Hw. apply (H w).\n      -\n        intros H w. apply (H (d_star s w)). apply d_star_reachable_states.\n    Qed.\n\n    Global Instance accepts_sigma_star_dec : dec (forall w, in_lang w).\n    Proof.\n      decide( forall q, q el reachable_states s -> F q) as [H | H].\n      - left. now apply accepts_sigma_star_if_all_states_final.\n      - right. now rewrite accepts_sigma_star_if_all_states_final.\n    Defined.\n\n    (** rejecting all words, empty language *)\n\n    Definition empty := forall w, ~ in_lang w.\n\n    Definition negate_final_states := DecPred (fun x => ~ (@F M x)).\n\n    Definition complement := DFA s negate_final_states (@d M).\n  End ACCEPT.\n\n  Notation in_lang A w := (accept A w) (only parsing).\n\n  Section OPERATIONS.\n    Variable M : dfa.\n\n    Lemma complement_correct w : accept (complement M) w <-> ~ (accept M w).\n    Proof.\n      splits*.\n    Qed.\n\n    Global Instance empty_dec : dec (empty M).\n    Proof.\n      apply (dec_trans (@accepts_sigma_star_dec (complement M))).\n      now setoid_rewrite complement_correct.\n    Qed.\n\n    Lemma empty_reachable_states\n      : empty M <-> forall (q : M), q el (reachable_states s) -> ~ (F q).\n    Proof.\n      split.\n      - intros empt q E F . rewrite <- reachable_states_reach_with in E.\n        destruct E as [w R].\n        specialize (empt w). apply empt. unfold accept. now rewrite R.\n      - intros H w acc. specialize (H (d_star s w)). apply H.\n        + apply d_star_reachable_states.\n        + exact acc.\n    Qed.\n\n    Instance exists_accept_dec: dec (exists w, accept M w).\n    Proof.\n      decide (empty M) as [H | H].\n      - firstorder.\n      - left. unfold empty in H.  rewrite empty_reachable_states in H.\n        rewrite DM_notAll in H.\n        + destruct H as [q H]. destruct (dec_DM_impl _ _ H) as [H' acc].\n          rewrite <- reachable_states_reach_with in H'.\n          destruct H' as [w R]. exists w.  rewrite <- R in acc.\n          apply dec_DN; auto.     \n        + auto.\n    Qed.\n\n    Instance exists_not_accept_dec : dec (exists w, ~ accept M w).\n    Proof.\n      decide (forall w, accept M w) as [H | H].\n      - right. firstorder.\n      - left. rewrite accepts_sigma_star_if_all_states_final in H.\n        rewrite DM_notAll in H.\n        + destruct H as [q H].  destruct (dec_DM_impl _ _ H) as [H' acc].\n          rewrite <- reachable_states_reach_with in H'.\n          destruct H' as [w R]. exists w.  now rewrite <- R in acc.\n        + auto.\n    Qed.      \nEnd OPERATIONS.\n\n    (** DFA recognizing epsilon *)\n\nDefinition Epsilon_autom : dfa.\nProof.\n  refine (DFA (inl tt)\n              (DecPred (fun q: unit + unit => if q then True else False))\n              (fun _ _ => inr tt)).\n  intros [[]|[]]; auto.\nDefined.\n\nLemma inr_fix_epsilon w : (@d_star Epsilon_autom (inr tt) w) = inr tt.\nProof.\n  now induction w.\nQed.\n\nLemma Epsilon_autom_correct w: accept Epsilon_autom w <-> w = nil.\nProof.\n  split.\n  - cbn. destruct w.\n    + reflexivity.\n    + cbn. now rewrite inr_fix_epsilon.\n  - intros H. subst w. cbn. exact I.\nQed.\n\n(** DFA for a symbol x *)\n\nDefinition F_cons (M : dfa) (q : option M + unit) :=\n  match q with\n  | inl None => False\n  | inl (Some q) => F q\n  | inr tt => False\n  end.\n    \nDefinition d_cons x (M : dfa)\n           (q : option M + unit) y  :=\n  match q with\n  | inl None => if decision (y = x) then inl (Some s) else inr tt\n  | inl (Some q) => inl (Some (d q y))\n  | inr tt => inr tt\n  end.\n\nInstance F_cons_dec  (M : dfa) (q : option M + unit) : dec (F_cons q).\nProof.\n  destruct q.\n  - destruct o ; auto.\n  - destruct u ; auto.\nQed.\n\nDefinition cons (M : dfa) (x : sigma) :=\n  DFA (inl None) (DecPred (@F_cons M)) (@d_cons x M).\n\nLemma inr_fix M x w : (@d_star (cons M x) (inr tt) w) = inr tt.\nProof.\n  now induction w.\nQed.\n\nLemma cons_correct  (M : dfa) x w : accept M w <-> accept (cons M x) (x::w).\nProof.\n  cbn in *. deq x. unfold accept. generalize (@s M).  induction w; firstorder.\nQed.\n\n(** word automata *)\n\nFixpoint word_dfa (w : word) : dfa :=\n  match w with\n  | [] => Epsilon_autom\n  | x :: xs => cons (word_dfa xs) x\n  end.\n\nLemma word_dfa_correct : forall w, accept (word_dfa w) w.\nProof.\n  induction w ; try now auto.\n  -\n    simpl.\n    now rewrite <- cons_correct.\nQed.\n\n\nEnd DFA.", "meta": {"author": "rodrigogribeiro", "repo": "finite_types", "sha": "27582ce97686654d741bca49a0f091a68a3dc89d", "save_path": "github-repos/coq/rodrigogribeiro-finite_types", "path": "github-repos/coq/rodrigogribeiro-finite_types/finite_types-27582ce97686654d741bca49a0f091a68a3dc89d/Tests/DFA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7364995905934504}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\n  ----\n  ** Exercise 1 *)\n\n(**\nTry to define a next function over 'I_n that correspond to the\nsuccessor function over the natural plus the special case that\n\"n -1\" is mapped to zero *)\n\nDefinition onext n (x : 'I_n) : 'I_n.\nProof.\nrefine (\n(* Sub takes two arguments *)\n  Sub\n(* Write the valued in the following line *)\n(*D*)(x.+1 %% n)\n(* Leave _ for the proof, you will fill it in by tactics later *)\n_\n).\n(*D*) by case: x => [m /= ltmn]; rewrite ltn_mod (leq_trans _ ltmn).\nDefined.\n\nEval compute in val (onext (Ordinal (isT : 2 < 4))).\nEval compute in val (onext (Ordinal (isT : 3 < 4))).\n\n(**\n  ----\n  ** Exercise 2\n*)\n\n(**\n   Show that injectivity is decidable for a function f : aT -> rT\n   with  aT a finite\n*)\n\nModule MyInj.\n\nCheck injective.\n\nDefinition injectiveb (aT : finType) (rT : eqType) (f : aT -> rT) : bool :=\n(*D*) [forall x : aT, forall y : aT, (f x == f y) ==> (x == y)].\n\nLemma injectiveP (aT : finType) (rT : eqType) (f : aT -> rT) :\n  reflect (injective f) (injectiveb f).\nProof.\n(*D*)apply: (iffP forallP) => [Ibf x y Efxy|If x].\n(*D*)  by move: Ibf => /(_ x) /forallP /(_ y); rewrite Efxy eqxx => /eqP.\n(*D*)by apply/forallP=> y; apply/implyP => /eqP Efxy; apply/eqP; apply: If.\n(*A*)Qed.\n\nEnd MyInj.\n\n(**\n  ----\n  ** Exercise 3\n\n  Build a function that maps an element of an ordinal to another element\n  of the same ordinal with a p subtracted from it.\n*)\n\nLemma neg_offset_ord_proof n (i : 'I_n) (p : nat) : i - p < n.\nProof.\n(*D*)apply: leq_ltn_trans (ltn_ord i).\n(*D*)apply: leq_subr.\n(*A*)Qed.\n\nDefinition neg_offset_ord n (i : 'I_n) p := Ordinal (neg_offset_ord_proof i p).\n\nEval compute in (val (neg_offset_ord (Ordinal (isT : 7 < 9)) 4)).\n\n(**\n  ----\n  ** Exercise 4\n*)\n\n(**\n   Try to formalize the following problem\n*)\n\n(**\n  Given a parking  where the boolean indicates if the slot is occupied or not\n*)\n\nDefinition parking n := 'I_n -> 'I_n -> bool.\n\n(**\n   Number of cars at line i\n*)\n\nDefinition sumL n (p : parking n) i := \\sum_(j < n) p i j.\n\n(**\n   Number of cars at column j\n*)\n\nDefinition sumC n (p : parking n) j := \\sum_(i < n) p i j.\n\n(**\n   Show that if 0 < n there is always two lines, or two columns, or a column and a line\n   that have the same numbers of cars\n*)\n\n(* Two intermediate lemmas to use injectivity  *)\n\nLemma leq_sumL n (p : parking n) i : sumL p i < n.+1.\nProof.\n(*D*)have {2}<-: \\sum_(i < n) 1 = n by rewrite -[X in _ = X]card_ord sum1_card.\n(*D*)by apply: leq_sum => k; case: (p _ _).\n(*A*)Qed.\n\nLemma leq_sumC n (p : parking n) j : sumC p j < n.+1.\nProof.\n(*D*)have {2}<-: \\sum_(i < n) 1 = n by rewrite -[X in _ = X]card_ord sum1_card.\n(*D*)by apply: leq_sum => k; case: (p _ _).\n(*A*)Qed.\n\nLemma inl_inj {A B} : injective (@inl A B). Proof. by move=> x y []. Qed.\nLemma inr_inj {A B} : injective (@inr A B). Proof. by move=> x y []. Qed.\n\nLemma result n (p : parking n) : 0 < n ->\n  exists i, exists j,\n   [\\/  (i != j) /\\ (sumL p i = sumL p j),\n        (i != j) /\\ (sumC p i = sumC p j) | sumL p i = sumC p j].\nProof.\n(*D*)case: n p => [//|[|n]] p _ /=.\n(*D*)  exists ord0, ord0; apply: Or33.\n(*D*)  by rewrite /sumL /sumC !big_ord_recl !big_ord0.\n(*D*)pose sLC (i : 'I_n.+2 + 'I_n.+2) :=\n(*D*)  match i with\n(*D*)  | inl i => Ordinal (leq_sumL p i)\n(*D*)  | inr i => Ordinal (leq_sumC p i) end.\n(*D*)have [sC_inj | /injectivePn /=] := altP (injectiveP sLC).\n(*D*)  have := max_card (mem (codom sLC)); rewrite card_codom // card_sum !card_ord.\n(*D*)  by rewrite !addnS !addSn !ltnS -ltn_subRL subnn ltn0.\n(*D*)move=> [[i|i] [[j|j] //=]]; [| |move: i j => j i|];\n(*D*)rewrite ?(inj_eq inj_inl, inj_eq inj_inr) => neq_ij [];\n(*D*)by exists i, j; do ?[exact: Or31|exact: Or32|exact: Or33].\n(*A*)Qed.\n\n(**\n  ----\n  ** Exercise 5\n*)\n\n(**\n   Prove the following state by induction and by following Gauss proof.\n *)\n\nLemma gauss_ex_p1 : forall n, (\\sum_(i < n) i).*2 = n * n.-1.\nProof.\n(*D*)elim=> [|n IH]; first by rewrite big_ord0.\n(*D*)rewrite big_ord_recr /= doubleD {}IH.\n(*D*)case: n => [|n /=]; first by rewrite muln0.\n(*D*)by rewrite -muln2 -mulnDr addn2 mulnC.\n(*A*)Qed.\n\nLemma gauss_ex_p2 : forall n, (\\sum_(i < n) i).*2 = n * n.-1.\nProof.\n(*D*)case=> [|n/=]; first by rewrite big_ord0.\n(*D*)rewrite -addnn.\n(*D*)have Hf i : n - i < n.+1.\n(*D*)  by apply: leq_trans (leq_subr _ _) _.\n(*D*)pose f (i : 'I_n.+1) := Ordinal (Hf i).\n(*D*)have f_inj : injective f.\n(*D*)  move=> x y /val_eqP/eqP H.\n(*D*)  apply/val_eqP => /=.\n(*D*)  rewrite -(eqn_add2l (n - x)) subnK -1?ltnS  //.\n(*D*)  by rewrite [n - x]H subnK -1?ltnS.\n(*D*)rewrite {1}(reindex_inj f_inj) -big_split /=.\n(*D*)rewrite -[X in _ = X * _]card_ord -sum_nat_const.\n(*D*)by apply: eq_bigr => i _; rewrite subnK // -ltnS.\n(*A*)Qed.\n\nLemma gauss_ex_p3 : forall n, (\\sum_(i < n) i).*2 = n * n.-1.\nProof.\n(*D*)case=> [|n/=]; first by rewrite big_ord0.\n(*D*)rewrite -addnn {1}(reindex_inj rev_ord_inj) -big_split /=.\n(*D*)rewrite -[X in _ = X * _]card_ord -sum_nat_const.\n(*D*)by apply: eq_bigr => i _; rewrite subSS subnK // -ltnS.\n(*A*)Qed.\n\n(**\n  ----\n   ** Exercise 6\n*)\n\nLemma sum_odd1 : forall n, \\sum_(i < n) (2 * i + 1) = n ^ 2.\nProof.\n(*D*)case=> [|n/=]; first by rewrite big_ord0.\n(*D*)rewrite big_split -big_distrr /= mul2n gauss_ex_p3 sum_nat_const.\n(*D*)by rewrite card_ord -mulnDr addn1 mulnn.\n(*A*)Qed.\n\n(**\n  ----\n  ** Exercise 7\n*)\n\nLemma sum_exp : forall x n, x ^ n.+1 - 1 = (x - 1) * \\sum_(i < n.+1) x ^ i.\nProof.\n(*D*)move=> x n.\n(*D*)rewrite mulnBl big_distrr mul1n /=.\n(*D*)rewrite big_ord_recr [X in _ = _ - X]big_ord_recl /=.\n(*D*)rewrite [X in _ = _ - (_ + X)](eq_bigr (fun i : 'I_n =>  x * x ^ i))\n(*D*)      => [|i _]; last by rewrite -expnS.\n(*D*)rewrite [X in _ = X - _]addnC [X in _ = _ - X]addnC subnDA addnK.\n(*D*)by rewrite expnS expn0.\n(*A*)Qed.\n\n(**\n  ----\n ** Exercise 8\n*)\n\n(** Prove the following state by induction and by using a similar trick\n   as for Gauss noticing that n ^ 3 = n * (n ^ 2) *)\n\nLemma bound_square : forall n, \\sum_(i < n) i ^ 2 <= n ^ 3.\nProof.\n(*D*)move=> n.\n(*D*)rewrite expnS -[X in _ <= X * _]card_ord -sum_nat_const /=.\n(*D*)elim/big_ind2: _ => // [* |i]; first exact: leq_add.\n(*D*)by rewrite leq_exp2r // ltnW.\n(*A*)Qed.\n\n(**\n  ----\n  ** Exercise 9\n\n  Prove the following statement using only big operator theorems.\n  [big_cat_nat], [big_nat_cond], [big_mkcondl], [big1]\n*)\nLemma sum_prefix_0 (f : nat -> nat) n m : n <= m ->\n  (forall k, k < n -> f k = 0) ->\n  \\sum_(0 <= i < m) f i = \\sum_(n <= i < m) f i.\nProof.\n(*D*)pose H := big_cat_nat.\n(*D*)move => nm f0; rewrite (big_cat_nat addn_monoid _ f (leq0n n)) /=; last by [].\n(*D*)rewrite big_nat_cond big_mkcondl big1 ?add0n //.\n(*D*)move => i _; case cnd : (0 <= i < n) => //.\n(*D*)apply: f0.\n(*D*)by move/andP: cnd => [_ it].\n(*A*)Qed.\n\n(**\n  ----\n  ** Exercise 10\n*)\n\n(**\n  building a monoid law\n*)\n\nSection cex.\n\nVariable op2 : nat -> nat -> nat.\n\nHypothesis op2n0 : right_id 0 op2.\n\nHypothesis op20n : left_id 0 op2.\n\nHypothesis op2A : associative op2.\n\nHypothesis op2add : forall x y, op2 x y = x + y.\n\nCanonical Structure op2Mon : Monoid.law 0 :=\n  Monoid.Law op2A op20n op2n0.\n\nLemma ex_op2 : \\big[op2/0]_(i < 3) i = 3.\nProof.\n(*D*)by rewrite !big_ord_recr big_ord0 /= !op2add.\n(*A*)Qed.\n\nEnd cex.\n", "meta": {"author": "gares", "repo": "COQWS17", "sha": "babcf965035f24fa00bbe69497361e9c8144ae97", "save_path": "github-repos/coq/gares-COQWS17", "path": "github-repos/coq/gares-COQWS17/COQWS17-babcf965035f24fa00bbe69497361e9c8144ae97/exercise3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7364995833028571}}
{"text": "(* Exercise coq_list_06 *)\n\n(* Those are the definitions from the previous exercise: *)\n\nInductive natlist : Set :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nFixpoint append (l m : natlist) {struct l} : natlist :=\n  match l with\n  | nil => m\n  | cons x xs => cons x (append xs m)\n  end.\n\nFixpoint length (l : natlist) : nat :=\nmatch l with\n  nil => 0\n | cons a k => S(length k)\nend.\n (* copy your definition from the previous exercise here *)\n\nFixpoint reverse (l : natlist) : natlist :=\nmatch l with\n nil => nil\n | cons a k => append (reverse k) (cons a nil)\nend.\n\n (* copy your definition from the previous exercise here *)\n\n(* Now let us prove that reverse does not change the length\n   of a list *)\n\n(* For this we may need a result proven in one of the previous\n   exercises and some results about natural numbers (remember\n   the exercises concerning natural numbers?) *)\nAxiom append_length : forall l m,\n  length (append l m) = length l + length m.\nRequire Import Arith.\n\nSearch (?n + 1).\n\nLemma reverse_length : forall l,\n  length l = length (reverse l).\n\nProof.\n  intros.\n  induction l.\n  simpl; reflexivity.\n  simpl.\n  rewrite append_length.\n  simpl.\n  rewrite Nat.add_1_r.\n  rewrite IHl.\n  reflexivity.\nQed.\n", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_list_06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7364751740019653}}
{"text": "(* 1 *)\nExample a :\n  (True \\/ False) /\\ (False \\/ True).\nProof.\n  split.\n  - left. apply I.\n  - right. apply I.\nQed.\n\nExample b : forall P : Prop,\n  P -> not (not P).\nProof.\n  intros P H H0. apply H0. apply H.\nQed.\n\nExample c : forall P Q R : Prop,\n  P /\\ (Q \\/ R) -> (P /\\ Q) \\/ (P /\\ R).\nProof.\n  intros P Q R [H1 H2]. destruct H2.\n  - left. split; assumption.\n  - right. split; assumption.\nQed.\n\n(* 2 *)\nExample a : forall (T : Type) p x q f,\n  p x ->\n  (forall x : T, p x -> exists y, q x y) ->\n  (forall x y, q x y -> q y (f y)) ->\n  exists z, q z (f z).\nProof.\n  intros. apply H in X. destruct X as [y X].\n  apply H0 in X.\n  exists y. apply X.\nQed.\n", "meta": {"author": "momohatt", "repo": "cpdt", "sha": "58ab808fbd6374b230f4123e3fa6c08fe9e93664", "save_path": "github-repos/coq/momohatt-cpdt", "path": "github-repos/coq/momohatt-cpdt/cpdt-58ab808fbd6374b230f4123e3fa6c08fe9e93664/exercise/ex02_1_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7364495296972835}}
{"text": "Require Export NArith.\nRequire Import TacticEx.\nRequire Import BinPosEx.\nRequire Import Pnat.\n\nDefinition Nminus x y :=\nmatch x, y with\n| x, N0 => x\n| N0, _ => N0\n| Npos a, Npos b =>\n  match (Pcompare a b Eq) with\n  | Gt => Npos (Pminus a b)\n  | _ => N0\n  end\nend.\n\nLemma Nminus_plus: forall p q : N, (Nminus (q + p) q) = p.\nProof.\nintros [|a] [|b]; try reflexivity.\nsimpl.\nrewrite Pcompare_refl.\nreflexivity.\nsimpl.\nrewrite nat_of_P_gt_Gt_compare_complement_morphism.\nrewrite Pminus_plus.\nreflexivity.\nrewrite nat_of_P_plus_morphism.\ndestruct (ZL4 a).\nrewrite H.\nrewrite <- plus_n_Sm.\nauto with *.\nQed.\n\n", "meta": {"author": "coq-contribs", "repo": "karatsuba", "sha": "6c20ebe144d5c9a86ba47e11affecf11fa2c8881", "save_path": "github-repos/coq/coq-contribs-karatsuba", "path": "github-repos/coq/coq-contribs-karatsuba/karatsuba-6c20ebe144d5c9a86ba47e11affecf11fa2c8881/NArithEx/Nminus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.736449519419616}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Sorting.Sorted ZArith.\n\nModule Quicksort.\n\nLemma split_accto_pivot : forall {A}\n                                 (ord : A -> A -> Prop)\n                                 (total : forall a b, {ord a b} + {ord b a})\n                                 pivot list,\n                            {pre | { post |\n                             (forall x, In x pre -> ord x pivot) /\\\n                             (forall x, In x post -> ord pivot x) /\\\n                             (forall x, In x list <->\n                                        In x pre \\/ In x post) /\\\n                             (length pre + length post = length list)}}.\nProof.\n  intros ? ? ? pivot list; induction list as [|a ? IHlist];\n  [exists nil,nil;firstorder\n  |destruct IHlist as [pre [post ?]];\n   destruct (total pivot a);\n   [exists pre,(a::post)|exists (a::pre),post]; firstorder subst; auto;\n   simpl; omega].\nQed.\n\nLemma quicksort_conc_lemma : forall {A}\n                                    (ord : A -> A -> Prop)\n                                    a b c,\n                               Sorted ord a -> Sorted ord (b :: c) -> (forall x, In x a -> ord x b) -> Sorted ord (a ++ (b :: c)).\nProof.\n  intros A ord a b c H H0 H1.\n  induction a.\n  apply H0.\n  assert (tmp1 : (a :: a0) ++ b :: c = a :: (a0 ++ b :: c)).\n  reflexivity.\n  rewrite -> tmp1.\n  apply Sorted_cons.\n  apply IHa.\n  inversion H.\n  auto.\n  intros x inx.\n  apply H1.\n  apply in_cons.\n  apply inx.\n  destruct a0.\n  apply HdRel_cons.\n  apply H1.\n  apply in_eq.\n  apply HdRel_cons.\n  inversion H.\n  inversion H5.\n  auto.\nQed.\n\nTheorem quicksort : forall {A}\n                           (ord : A -> A -> Prop)\n                           (total : forall a b, {ord a b} + {ord b a})\n                           L,\n                      {L' | (forall x, In x L <-> In x L') /\\ Sorted ord L'}.\nProof.\n  intros A ord total L.\n  refine ((fix f n L (lenc : length L <= n) : {L' | (forall x, In x L <-> In x L') /\\ Sorted ord L'} :=\n             match n as m return (m = n -> _) with\n               | 0 => fun eq => _\n               | S m' => fun eq => _\n             end eq_refl) (length L) L _).\n  rewrite <- eq in lenc.\n  destruct L.\n  exists nil.\n  split.\n  intros a.\n  split.\n  trivial.\n  trivial.\n  apply Sorted_nil.\n  contradict lenc.\n  unfold length.\n  intros Q.\n  inversion Q.\n\n  destruct L.\n  exists nil.\n  split.\n  intros x.\n  split.\n  trivial.\n  trivial.\n  apply Sorted_nil.\n  assert ({pre | { post |\n                   (forall x, In x pre -> ord x a) /\\\n                   (forall x, In x post -> ord a x) /\\\n                   (forall x, In x L <->\n                              In x pre \\/ In x post) /\\\n                   (length pre + length post = length L)}}).\n  apply split_accto_pivot.\n  apply total.\n  elim X.\n  intros pre QQ.\n  elim QQ.\n  intros post QQQ.\n  elim QQQ.\n  intros B Bc1.\n  elim Bc1.\n  intros B0 Bc2.\n  elim Bc2.\n  intros B1 B2.\n  assert (X0 : {post' : list A | (forall x : A, In x post <-> In x post') /\\ Sorted ord post'}).\n  apply (f m').\n  apply Le.le_S_n.\n  apply (Le.le_trans _ (length (a :: L))).\n  replace (length (a :: L)) with (S (length L)).\n  rewrite <- B2.\n  auto.\n  assert (tmp1 : S (length pre + length post) = length pre + S (length post)).\n  auto.\n  rewrite -> tmp1.\n  apply Plus.le_plus_r.\n  auto.\n  rewrite -> eq.\n  auto.\n  elim X0.\n  intros post' X1.\n  elim X1.\n  intros X2 X3.\n  assert (Y0 : {pre' : list A | (forall x : A, In x pre <-> In x pre') /\\ Sorted ord pre'}).\n  apply (f m').\n  apply Le.le_S_n.\n  apply (Le.le_trans _ (length (a :: L))).\n  apply (Le.le_trans _ (length (a :: L))).\n  replace (length (a :: L)) with (S (length L)).\n  rewrite <- B2.\n  assert (tmp1 : S (length pre + length post) = S(length pre) + length post).\n  auto.\n  rewrite -> tmp1.\n  apply Plus.le_plus_l.\n  auto.\n  auto.\n  rewrite -> eq.\n  auto.\n  elim Y0.\n  intros pre' Y1.\n  elim Y1.\n  intros Y2 Y3.\n  exists (pre' ++ (a :: post')).\n  split.\n  split.\n  intros inxal.\n  inversion inxal.\n  apply in_or_app.\n  apply or_intror.\n  rewrite <- H.\n  apply in_eq.\n  assert (In x pre \\/ In x post).\n  apply B1.\n  apply H.\n  elim H0.\n  intros H1.\n  apply in_or_app.\n  apply or_introl.\n  apply Y2.\n  apply H1.\n  intros H1.\n  apply in_or_app.\n  apply or_intror.\n  apply in_cons.\n  apply X2.\n  apply H1.\n\n  intros inx.\n\n  assert (inx' : In x pre' \\/ In x (a :: post')).\n  apply in_app_or.\n  apply inx.\n  elim inx'.\n  intros inxpre'.\n  assert (inxpre : In x pre).\n  apply Y2.\n  apply inxpre'.\n  apply in_cons.\n  apply B1.\n  auto.\n\n  intros inxpost'.\n  inversion inxpost'.\n  rewrite <- H.\n  apply in_eq.\n  apply in_cons.\n  assert (inxpost : In x post).\n  apply X2.\n  apply H.\n  apply B1.\n  auto.\n  apply quicksort_conc_lemma.\n  apply Y3.\n  apply Sorted_cons.\n  apply X3.\n  destruct post'.\n  apply HdRel_nil.\n  apply HdRel_cons.\n  apply B0.\n  apply X2.\n  apply in_eq.\n  intros x inxpre'.\n  apply B.\n  apply Y2.\n  apply inxpre'.\n  auto.\nQed.\n\nEnd Quicksort.\n", "meta": {"author": "dasuxullebt", "repo": "quicksort.v", "sha": "0bb609a42456711d07405ead086f41876828e6c8", "save_path": "github-repos/coq/dasuxullebt-quicksort.v", "path": "github-repos/coq/dasuxullebt-quicksort.v/quicksort.v-0bb609a42456711d07405ead086f41876828e6c8/Quicksort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7364156537602025}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import ZArith.\nRequire Import Rbase.\nRequire int.Int.\n\nParameter pow2: Z -> Z.\n\nAxiom Power_0 : ((pow2 0%Z) = 1%Z).\n\nAxiom Power_s : forall (n:Z), (0%Z <= n)%Z ->\n  ((pow2 (n + 1%Z)%Z) = (2%Z * (pow2 n))%Z).\n\nAxiom Power_1 : ((pow2 1%Z) = 2%Z).\n\nOpen Scope Z_scope.\n\n(* Why3 goal *)\nTheorem Power_sum : forall (n:Z) (m:Z), ((0%Z <= n)%Z /\\ (0%Z <= m)%Z) ->\n  ((pow2 (n + m)%Z) = ((pow2 n) * (pow2 m))%Z).\n(* YOU MAY EDIT THE PROOF BELOW *)\nintros n m Hmn.\ncut (0 <= m); auto with zarith.\napply Z_lt_induction with\n  (P:= fun m => \n      0 <= m -> pow2 (n + m) = pow2 n * pow2 m);\n  auto with zarith.\nintros x Hind Hxpos.\nassert (h:(x = 0 \\/ x > 0)) by omega.\ndestruct h.\nsubst x.\nrewrite Power_0.\nreplace (n+0) with n by omega.\nreplace (pow2 n * 1) with (pow2 n)  by omega.\nauto.\nreplace (x) with ((x-1)+1) by omega.\nrewrite Power_s;auto with zarith.\nreplace (n + (x-1+1)) with (n+(x-1)+1) by omega.\nrewrite Power_s;auto with zarith.\nrewrite Hind;auto with zarith.\nrewrite Zmult_permute.\nauto with zarith.\nQed.\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/tests/bitvector1/bitvector1_Pow2int_Power_sum_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7364156517546491}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural :=\n  plus Zero (plus lf2 lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj251_coqofml_bsaKC5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7364156495266563}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural :=\n  plus Zero (plus lf1 lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj251_coqofml_VVKblj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7364156355619278}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus y (plus x lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj205_coqofml_9dcOJ3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7364156312542355}}
{"text": "Require Import ZArith.\nRequire Import Setoid.\n\nLocal Open Scope Z_scope.\n\nAdd Parametric Relation : Z Z.le\nreflexivity proved by Z.le_refl\ntransitivity proved by Z.le_trans as le.\n\nLemma eq_Zle : forall (x y : Z), x = y -> x <= y.\nProof.\nintros ; subst ; reflexivity.\nQed.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/mytheories/MyZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810496235896, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7363991583519495}}
{"text": "(* This code is copyrighted by its authors; it is distributed under  *)\n(* the terms of the LGPL license (see LICENSE and description files) *)\n\n(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*                   Solange Coupet-Grimal & Line Jakubiec                  *)\n(*                                                                          *)\n(*                                                                          *)\n(*              Laboratoire d'Informatique de Marseille                     *)\n(*               CMI-Technopole de Chateau-Gombert                          *)\n(*                   39, Rue F. Joliot Curie                                *)\n(*                   13453 MARSEILLE Cedex 13                               *)\n(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lim.univ-mrs.fr          *)\n(*                                                                          *)\n(*                                                                          *)\n(*                                Coq V5.10                                 *)\n(*                              May 30th 1996                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                                Numerals.v                                *)\n(****************************************************************************)\n\nRequire Export Dependent_lists.\nRequire Export Lib_Arith.\n\n\nDefinition Inj (A : Set) (P : A -> Prop) (e : {x : A | P x}) :=\n  let (a, _) return A := e in a.\n\nFixpoint exp (e x : nat) {struct x} : nat :=\n  match x with\n  | O => 1\n  | S p => e * exp e p\n  end.\n\nSection Numerals.\n\n  Definition BT := {b : nat | 0 < b}.\n  Variable BASE : BT.\n  Definition base := Inj nat (fun b : nat => 0 < b) BASE.\n  Definition digit := {x : nat | x < base}.\n  Definition val : digit -> nat := Inj nat (fun x : nat => x < base).\n  Definition num := list digit.\n  Definition inf (n : nat) := {x : nat | x < n}.\n  Definition val_inf (n : nat) : inf n -> nat :=\n    Inj nat (fun x : nat => x < n).\n  Let Cons := cons digit.\n  Let Nil := nil digit.\n\n  Fixpoint Val (n : nat) (X : num n) {struct X} : nat :=\n    match X with\n    | nil => 0\n    | cons p xp X' => val xp * exp base p + Val p X'\n    end.\n\n  Lemma Val_val : forall x : digit, Val 1 (Cons 0 x Nil) = val x.\n  simpl in |- *.\n  intros x.\n  rewrite (mult_1_r (val x)).\n  auto.\n  Qed.\n\n  Lemma upper_bound : forall (n : nat) (X : num n), Val n X < exp base n.\n  intros n X; elim X.\n  auto.\n  intros n0 y l H_rec.\n  simpl in |- *.\n  apply lt_le_trans with (pred base * exp_n base n0 + exp_n base n0).\n  apply le_lt_plus_mult.\n  elim y.\n  intros x H_y.\n  simpl in |- *.\n  auto. (*lt_le_pred*)\n  trivial.\n  replace (pred base) with (base - 1). (*pred_minus*)\n  rewrite mult_minus_distr_r.\n  simpl in |- *.\n  elim plus_n_O.\n  elim exp_n_plus_p1.\n  elim plus_Snm_nSm; simpl in |- *; elim plus_n_O.\n  elim plus_comm.\n  elim le_plus_minus.\n  apply le_mult_cst; auto.\n  apply le_exp_n_mult.\n  unfold base in |- *; case BASE; auto.\n  auto.\n  Qed.\n\n\n  Definition val_bound (n : nat) (X : num n) : inf (exp base n) :=\n    exist (fun p : nat => p < exp base n) (Val n X) (upper_bound n X).\n\n\n  Lemma comp_dif :\n   forall (n : nat) (x y : digit) (X Y : num n),\n   val x < val y -> Val (S n) (Cons n x X) < Val (S n) (Cons n y Y).\n  simpl in |- *; intros.\n  elim H.\n  apply same_quotient_order; auto; apply upper_bound.\n  intros; apply same_quotient_order; auto; apply upper_bound.\n  Qed.\n\n\n  Lemma comp_eq_most :\n   forall (n : nat) (x y : digit) (X Y : num n),\n   val x = val y ->\n   Val n X < Val n Y -> Val (S n) (Cons n x X) < Val (S n) (Cons n y Y).\n  intros n x y X Y e H.\n  simpl in |- *.\n  rewrite e.\n  apply plus_lt_compat_l; auto.\n  Qed.\n\n  Lemma com_eq :\n   forall (n : nat) (x y : digit) (X Y : num n),\n   val x = val y ->\n   Val n X = Val n Y -> Val (S n) (Cons n x X) = Val (S n) (Cons n y Y).\n  simpl in |- *.\n  intros n x y X Y He HE.\n  rewrite He; rewrite HE; auto.\n  Qed.\n\nEnd Numerals.", "meta": {"author": "coq-contribs", "repo": "hardware", "sha": "cc92b5cb860fd857da744cc39628c6ad1508ddf9", "save_path": "github-repos/coq/coq-contribs-hardware", "path": "github-repos/coq/coq-contribs-hardware/hardware-cc92b5cb860fd857da744cc39628c6ad1508ddf9/Factorization/Lib_Numerals/Numerals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7363947722990091}}
{"text": "Require Import List.\nImport ListNotations.\n\nInductive alpha := M | I | U.\n\nDefinition word := list alpha.\n\nInductive lang : word -> Prop :=\n| axiom : lang [M;I]\n| rule1 x : lang (x ++ [I]) -> lang (x ++ [I;U])\n| rule2 x : lang ([M] ++ x) -> lang ([M] ++ x ++ x)\n| rule3 x y : lang (x ++ [I;I;I] ++ y) -> lang (x ++ [U] ++ y)\n| rule4 x y : lang (x ++ [U;U] ++ y) -> lang (x ++ y).\n\nCheck List.hd.\nCheck List.hd_error.\n\n\nLemma startM (w:word) : lang w -> (List.hd_error w) = Some M.\nProof.\n  intro.\n  induction H; trivial.\n  unfold List.hd_error.\n  destruct x; simpl in *; trivial.\n  - destruct x; simpl in *.\n    + discriminate.\n    + apply IHlang.\n  - destruct x; simpl in *.\n    + discriminate.\n    + apply IHlang.\nQed.\n\nLemma startMexists (w:word): lang w -> exists t, w=M::t.\nProof.\n  intro.\n  apply startM in H.\n  destruct w.\n  unfold hd_error in *.\n  discriminate.\n  simpl in *.\n  injection H as ->.\n  exists w.\n  trivial.\nQed.\n\n\nInductive Z3 := Z0 | Z1 | Z2.\n\nDefinition succ (n:Z3) := \n  match n with \n  |Z0 => Z1\n  |Z1 => Z2\n  |Z2 => Z0\n  end\n.\n\n\nDefinition add (x y:Z3) :=\n  match x with \n  |Z0 => y \n  |Z1 => succ y \n  |Z2 => succ (succ y)\n  end\n.\n \nLemma add_comm (x y:Z3) : add x y = add y x.\nProof.\n  destruct x,y; simpl; trivial.\nQed.\n\nLemma add_assoc (x y z:Z3) : add x (add y z) = add (add x y) z.\nProof.\n  destruct x,y,z; simpl; trivial.\nQed.\n\nLemma add_Z0 (x:Z3) : add x Z0 = x.\nProof.\n  destruct x; simpl; trivial.\nQed.\n\n\nLemma notZ0 (z:Z3) : z<>Z0 -> add z z <> Z0.\nProof.\n  destruct z; simpl; trivial; discriminate.\nQed.\n\n\nFixpoint occurI3 (w:word) := \n  match w with \n  |[] => Z0\n  |I::t => add Z1 (occurI3 t)\n  |_::t => occurI3 t\n  end\n.\n\n\nLemma occurI3Nil : occurI3 [] = Z0.\nProof.\n  unfold occurI3.\n  trivial.\nQed.\n  \nLemma add_succ (x y:Z3) : succ (add x y) = add (succ x) y.\nProof.\n  destruct x,y; trivial.\nQed.\n\nLemma conc_occurI3 (v w:word) : occurI3 (v ++ w) = add (occurI3 v) (occurI3 w).\nProof.\n  destruct v,w; simpl; trivial;destruct a; simpl.\nQed.\n\nLemma distr_occurI3 (v w:word) : occurI3 (v ++ w) = add (occurI3 v) (occurI3 w).\nProof.\n  induction v; simpl.\n  - trivial.\n  - destruct a. \n    + apply IHv.\n    + rewrite <- add_succ. \n    rewrite occurI3Nil. rewrite add_Z0.\n  \n\n\n\n\n\n\n", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/LMFI/tp7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.736390894686322}}
{"text": "From Hammer Require Import Hammer.\n\nRequire Export Relation_Definitions.\nFrom ZornsLemma Require Import Relation_Definitions_Implicit.\nRequire Import Classical.\nRequire Import Arith.\n\nRecord DirectedSet := {\nDS_set : Type;\nDS_ord : relation DS_set;\nDS_ord_cond : preorder DS_ord;\nDS_join_cond : forall i j:DS_set, exists k:DS_set,\nDS_ord i k /\\ DS_ord j k\n}.\n\nArguments DS_ord {d}.\nArguments DS_ord_cond {d}.\nArguments DS_join_cond {d}.\n\nSection for_large.\n\nVariable I : DirectedSet.\n\nDefinition eventually (P : DS_set I -> Prop) : Prop :=\nexists i:DS_set I, forall j:DS_set I,\nDS_ord i j -> P j.\n\nLemma eventually_and: forall (P Q: DS_set I -> Prop),\neventually P -> eventually Q ->\neventually (fun i:DS_set I => P i /\\ Q i).\nProof. hammer_hook \"DirectedSets\" \"DirectedSets.eventually_and\".\nintros.\ndestruct H.\ndestruct H0.\ndestruct (DS_join_cond x x0) as [? [? ?]].\nexists x1.\nintros; split.\napply H.\napply preord_trans with x1; trivial.\napply DS_ord_cond.\napply H0.\napply preord_trans with x1; trivial.\napply DS_ord_cond.\nQed.\n\nLemma eventually_impl_base: forall (P Q: DS_set I -> Prop),\n(forall i:DS_set I, P i -> Q i) ->\neventually P -> eventually Q.\nProof. hammer_hook \"DirectedSets\" \"DirectedSets.eventually_impl_base\".\nintros.\ndestruct H0.\nexists x.\nintros.\nauto.\nQed.\n\nLemma eventually_impl: forall (P Q: DS_set I -> Prop),\neventually P -> eventually (fun i:DS_set I => P i -> Q i) ->\neventually Q.\nProof. hammer_hook \"DirectedSets\" \"DirectedSets.eventually_impl\".\nintros.\napply eventually_impl_base with (P := fun (i:DS_set I) =>\nP i /\\ (P i -> Q i)).\ntauto.\napply eventually_and; assumption.\nQed.\n\nDefinition exists_arbitrarily_large (P: DS_set I -> Prop) :=\nforall i:DS_set I, exists j:DS_set I,\nDS_ord i j /\\ P j.\n\nLemma not_eal_eventually_not: forall (P: DS_set I -> Prop),\n~ exists_arbitrarily_large P ->\neventually (fun i:DS_set I => ~ P i).\nProof. hammer_hook \"DirectedSets\" \"DirectedSets.not_eal_eventually_not\".\nintros.\napply not_all_ex_not in H.\ndestruct H as [i].\nexists i.\nintros.\nintro.\ncontradiction H.\nexists j; split; trivial.\nQed.\n\nLemma not_eventually_eal_not: forall (P: DS_set I -> Prop),\n~ eventually P ->\nexists_arbitrarily_large (fun i:DS_set I => ~ P i).\nProof. hammer_hook \"DirectedSets\" \"DirectedSets.not_eventually_eal_not\".\nintros.\nred; intros.\napply NNPP; intro.\ncontradiction H.\nexists i.\nintros.\napply NNPP; intro.\ncontradiction H0.\nexists j; split; trivial.\nQed.\n\nEnd for_large.\n\nArguments eventually {I}.\nArguments eventually_and {I}.\nArguments eventually_impl_base {I}.\nArguments eventually_impl {I}.\nArguments exists_arbitrarily_large {I}.\nArguments not_eal_eventually_not {I}.\nArguments not_eventually_eal_not {I}.\n\nNotation \"'for' 'large' i : I , p\" :=\n(eventually (fun i:I => p))\n(at level 200, i ident, right associativity).\n\nNotation \"'exists' 'arbitrarily' 'large' i : I , p\" :=\n(exists_arbitrarily_large (fun i:I => p))\n(at level 200, i ident, right associativity).\n\nSection nat_DS.\n\nDefinition nat_DS : DirectedSet.\nrefine (Build_DirectedSet nat le _ _).\nconstructor; red; intros; auto with arith.\napply le_trans with y; assumption.\nintros.\ncase (lt_eq_lt_dec i j).\nexists j.\ndestruct s; auto with arith.\ndestruct e; auto with arith.\nexists i; auto with arith.\nDefined.\n\nEnd nat_DS.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/topology/DirectedSets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7363908831250127}}
{"text": "(** Sequences of transitions. *)\n\nRequire Import Classical.\n\nSet Implicit Arguments.\n\nSection SEQUENCES.\n\nVariable A: Type.\nVariable R: A -> A -> Prop.\n\n(** Zero, one or several transitions: reflexive, transitive closure of [R]. *)\n\nInductive star: A -> A -> Prop :=\n  | star_refl: forall a,\n      star a a\n  | star_step: forall a b c,\n      R a b -> star b c -> star a c.\n\nLemma star_one:\n  forall (a b: A), R a b -> star a b.\nProof.\n  intros. econstructor; eauto. constructor.\nQed.\n\nLemma star_trans:\n  forall (a b: A), star a b -> forall c, star b c -> star a c.\nProof.\n  induction 1; intros. auto. econstructor; eauto.\nQed.\n\n(** One or several transitions: transitive closure of [R]. *)\n\nInductive plus: A -> A -> Prop :=\n  | plus_left: forall a b c,\n      R a b -> star b c -> plus a c.\n\nLemma plus_one:\n  forall a b, R a b -> plus a b.\nProof.\n  intros. apply plus_left with b. auto. apply star_refl.\nQed.\n\nLemma star_plus:\n  forall a b c, star a b -> plus b c -> plus a c.\nProof.\n  intros. inversion H0. inversion H. econstructor; eauto.\n  econstructor; eauto. eapply star_trans; eauto. econstructor; eauto. \nQed.\n\nLemma plus_right:\n  forall a b c, star a b -> R b c -> plus a c.\nProof.\n  intros. eapply star_plus; eauto. apply plus_one; auto.\nQed.\n\n(** Infinitely many transitions. *)\n\nCoInductive infseq: A -> Prop :=\n  | infseq_step: forall a b,\n      R a b -> infseq b -> infseq a.\n\n(** Coinduction principles to show the existence of infinite sequences. *)\n\nLemma infseq_coinduction_principle:\n  forall (X: A -> Prop),\n  (forall a, X a -> exists b, R a b /\\ X b) ->\n  forall a, X a -> infseq a.\nProof.\n  intros X P. cofix COINDHYP; intros.\n  destruct (P a H) as [b [U V]]. apply infseq_step with b; auto. \nQed.\n\nLemma infseq_coinduction_principle_2:\n  forall (X: A -> Prop),\n  (forall a, X a -> exists b, plus a b /\\ X b) ->\n  forall a, X a -> infseq a.\nProof.\n  intros.\n  apply infseq_coinduction_principle with\n    (X := fun a => exists b, star a b /\\ X b).\n  intros. \n  destruct H1 as [b [STAR Xb]]. inversion STAR; subst.\n  destruct (H b Xb) as [c [PLUS Xc]]. inversion PLUS; subst.\n  exists b0; split. auto. exists c; auto. \n  exists b0; split. auto. exists b; auto.\n\n  exists a; split. apply star_refl. auto.\nQed.\n\n(** An example using [infseq_coinduction_principle]. *)\n\nLemma infseq_alternate_characterization:\n  forall a,\n  (forall b, star a b -> exists c, R b c) ->\n  infseq a.\nProof.\n  apply infseq_coinduction_principle.\n  intros. destruct (H a) as [b Rb]. constructor. \n  exists b; split; auto. \n  intros. apply H. econstructor; eauto.\nQed.\n\n(** A sequence is either infinite or stops on an irreducible term. *)\n\nDefinition irred (a: A) : Prop := forall b, ~(R a b).\n\nLemma infseq_or_finseq:\n  forall a, infseq a \\/ exists b, star a b /\\ irred b.\nProof.\n  intros.\n  destruct (classic (forall b, star a b -> exists c, R b c)).\n  left. apply infseq_alternate_characterization; auto.\n  right.\n  generalize (not_all_ex_not _ _ H). intros [b P].\n  generalize (imply_to_and _ _ P). intros [U V].\n  exists b; split. auto.\n  red; intros; red; intros. elim V. exists b0; auto.\nQed.\n\n(** Additional properties for deterministic transition relations. *)\n\nHypothesis R_determ:\n  forall a b c, R a b -> R a c -> b = c.\n\n(** Uniqueness of transition sequences. *)\n\nLemma star_star_inv:\n  forall a b, star a b -> forall c, star a c -> star b c \\/ star c b.\nProof.\n  induction 1; intros.\n  auto.\n  inversion H1; subst. right. eapply star_step; eauto. \n  assert (b = b0). eapply R_determ; eauto. subst b0. \n  apply IHstar; auto.\nQed.\n\nLemma finseq_unique:\n  forall a b b',\n  star a b -> irred b ->\n  star a b' -> irred b' ->\n  b = b'.\nProof.\n  intros. destruct (star_star_inv H H1).\n  inversion H3; subst. auto. elim (H0 _ H4).\n  inversion H3; subst. auto. elim (H2 _ H4).\nQed.\n\nLemma infseq_star_inv:\n  forall a b, star a b -> infseq a -> infseq b.\nProof.\n  induction 1; intros. auto. \n  inversion H1; subst. assert (b = b0). eapply R_determ; eauto. subst b0.\n  apply IHstar. auto.\nQed.\n\nLemma infseq_finseq_excl:\n  forall a b,\n  star a b -> irred b -> infseq a -> False.\nProof.\n  intros. \n  assert (infseq b). eapply infseq_star_inv; eauto. \n  inversion H2. elim (H0 b0); auto. \nQed.\n\nEnd SEQUENCES.\n\n\n  \n\n\n", "meta": {"author": "mukeshtiwari", "repo": "DataStrucutre", "sha": "89a4916114d3681e67f963f5166468c0b1ff2276", "save_path": "github-repos/coq/mukeshtiwari-DataStrucutre", "path": "github-repos/coq/mukeshtiwari-DataStrucutre/DataStrucutre-89a4916114d3681e67f963f5166468c0b1ff2276/Sequences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7363908751682203}}
{"text": "Require Export D.\n\n\n\n(** 3 stars, advanced (beautiful__gorgeous)  *)\n\n\nLemma plus_assoc: forall a b c, \n  (a + b) + c = a + (b + c).\nProof. intros. induction a.\n  Case \"a = 0\". reflexivity.\n  Case \"a = S a\". simpl. rewrite -> IHa. reflexivity. Qed.\n\nTheorem gorgeous_sum : forall n m,\n  gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  intros n m Hn Hm. induction Hn.\n  Case \"n = 0\". simpl. apply Hm.\n  Case \"n = 3 + n0\". rewrite -> plus_assoc. apply g_plus3. apply IHHn.\n  Case \"n = 5 + n0\". rewrite -> plus_assoc. apply g_plus5. apply IHHn.  \n  Qed.\n\nTheorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.\nProof.\n  intros n Hb. induction Hb.\n  Case \"n = 0\". apply g_0.\n  Case \"n = 3\". apply g_plus3. apply g_0.\n  Case \"n = 5\". apply g_plus5. apply g_0.\n  Case \"n = n + m\". apply gorgeous_sum.  apply IHHb1. apply IHHb2.\n  Qed.\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/P06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7363504243681988}}
{"text": "Require Import Nsize.\nRequire Import Nsplit.\nRequire Import Nshift.\nRequire Import Nminus.\nRequire Import NArith.\nRequire Import Div2.\nRequire Import Max.\nRequire Import NArithRing.\nRequire Import Compare.\n\nTactic Notation \"ringreplace\" constr (a) \"with\" constr (b) :=\nreplace a with b ; [idtac | solve [ ring ]].\n\nLocal Open Scope N_scope.\n\nDefinition KaratsubaStop : nat := 40%nat.\n\nFixpoint KaratsubaMultF (i:nat) (a b:N) {struct i} : N :=\n let (a', b') := match (Ncompare a b) with\n                 | Lt => (b, a)\n                 | _ => (a, b)\n                 end in\n let n:=(div2 (Nsize a')) in \n match i, le KaratsubaStop n with\n | (S i'), true => let (a1,a2):= NsplitAt n a' in\n                   let (b1,b2) := NsplitAt n b' in\n                   let x := KaratsubaMultF i' a2 b2 in\n                   let y := KaratsubaMultF i' a1 b1 in\n                   let z := KaratsubaMultF i' (Nplus a1 a2) (Nplus b1 b2)\n                   in x + (Nshift n (Nminus z (y+x))) + (Nshift (2*n) y)\n | _, _ => (Nmult a' b')\nend.\n\nDefinition KaratsubaMult a b := KaratsubaMultF (max (Nsize a) (Nsize b)) a b.\n\nLemma KaratsubaMultCorrect1 : forall (a b c d:N),\n(Nminus ((a + b) * (c + d)) (a * c + b * d))=(b*c + a*d).\nProof.\nintros.\nringreplace ((a + b) * (c + d)) with ((a*c + b*d) + (b * c + a * d)).\napply Nminus_plus.\nQed.\n\nTheorem KaratsubaMultCorrect : forall a b, KaratsubaMult a b = a * b.\nProof.\nintros a b.\nunfold KaratsubaMult.\ngeneralize (max (Nsize a) (Nsize b)).\nintros i.\ngeneralize a b.\nclear a b.\ninduction i; intros a b.\nsimpl.\ndestruct (a ?= b); ring.\nOpaque KaratsubaStop.\nsimpl.\nset (p:=match a ?= b with\n     | Eq => (a, b)\n     | Lt => (b, a)\n     | Gt => (a, b)\n     end).\nreplace (a*b) with ((fst p)*(snd p)).\ndestruct p.\nsimpl.\nTransparent KaratsubaStop.\ndestruct (le KaratsubaStop (div2 (Nsize n))).\ntransitivity ((let (a0, b0) := NsplitAt (div2 (Nsize n)) n in\n b0 + Nshift (div2 (Nsize n)) a0) *\n(let (a0, b0) := NsplitAt (div2 (Nsize n)) n0 in\n b0 + Nshift (div2 (Nsize n)) a0)).\ndestruct (NsplitAt (div2 (Nsize n)) n).\ndestruct (NsplitAt (div2 (Nsize n)) n0).\nrepeat rewrite IHi.\nrewrite KaratsubaMultCorrect1.\nautorewrite with NshiftExpand.\nchange (Npos (Pshift.Pow2 0)) with 1.\nring.\nrewrite (NsplitAtSum (div2 (Nsize n)) n).\nrewrite (NsplitAtSum (div2 (Nsize n)) n0).\nreflexivity.\nreflexivity.\ndestruct (a?=b); try reflexivity.\napply Nmult_comm.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "karatsuba", "sha": "6c20ebe144d5c9a86ba47e11affecf11fa2c8881", "save_path": "github-repos/coq/coq-contribs-karatsuba", "path": "github-repos/coq/coq-contribs-karatsuba/karatsuba-6c20ebe144d5c9a86ba47e11affecf11fa2c8881/Karatsuba/Karatsuba.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7363504216882405}}
{"text": "(** * MoreCoq: More About Coq *)\n\nRequire Export Poly.\n\n(** This chapter introduces several more Coq tactics that,\n    together, allow us to prove many more theorems about the\n    functional programs we are writing. *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  (* At this point, we could finish with \n     \"[rewrite -> eq2. reflexivity.]\" as we have \n     done several times above. But we can achieve the\n     same effect in a single step by using the \n     [apply] tactic instead: *)\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2. \n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex) *)\n(** Complete the following proof without using [simpl]. *)\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. apply H. apply H0. Qed.\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal _exactly_ -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\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  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since \n            [apply] will do a [simpl] step first. *)  \n  apply H.  Qed.         \n\n(** **** Exercise: 3 stars (apply_exercise1) *)\n(** Hint: you can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend. *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros. rewrite -> H.\n  symmetry. apply rev_involutive. Qed.\n\n(** **** Exercise: 1 star, optional (apply_rewrite) *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  Are there situations where both can usefully be\n    applied?\n    \n*)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might\n    abstract it out as a lemma recording once and for all\n    the fact that equality is transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. \n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to\n    prove the above example.  However, to do this we need\n    a slight refinement of the [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  (* If we simply tell Coq [apply trans_eq] at this point,\n     it can tell (by matching the goal against the\n     conclusion of the lemma) that it should instantiate [X]\n     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].\n     However, the matching process doesn't determine an\n     instantiation for [m]: we have to supply one explicitly\n     by adding [with (m:=[c,d])] to the invocation of\n     [apply]. *)\n  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.\n\n(**  Actually, we usually don't have to include the name [m]\n    in the [with] clause; Coq is often smart enough to\n    figure out which instantiation we're giving. We could\n    instead write: [apply trans_eq with [c,d]]. *)\n \n(** **** Exercise: 3 stars, optional (apply_with_exercise) *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o). \nProof. \n  intros. eapply trans_eq. apply H0. apply H. Qed. \n\n(* ###################################################### *)\n(** * The [inversion] tactic *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is clear from this definition that every number has one of two\n    forms: either it is the constructor [O] or it is built by applying\n    the constructor [S] to another number.  But there is more here than\n    meets the eye: implicit in the definition (and in our informal\n    understanding of how datatype declarations work in other\n    programming languages) are two other facts:\n\n    - The constructor [S] is _injective_.  That is, the only way we can\n      have [S n = S m] is if [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor is\n    injective and [nil] is different from every non-empty list.  For\n    booleans, [true] and [false] are unequal.  (Since neither [true]\n    nor [false] take any arguments, their injectivity is not an issue.) *)\n\n(** Coq provides a tactic called [inversion] that allows us to exploit\n    these principles in proofs.\n \n    The [inversion] tactic is used like this.  Suppose [H] is a\n    hypothesis in the context (or a previously proven lemma) of the\n    form\n      c a1 a2 ... an = d b1 b2 ... bm\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] instructs Coq to \"invert\" this\n    equality to extract the information it contains about these terms:\n\n    - If [c] and [d] are the same constructor, then we know, by the\n      injectivity of this constructor, that [a1 = b1], [a2 = b2],\n      etc.; [inversion H] adds these facts to the context, and tries\n      to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory.  That is, a false assumption has crept\n      into the context, and this means that any goal whatsoever is\n      provable!  In this case, [inversion H] marks the current goal as\n      completed and pops it off the goal stack. *)\n\n(** The [inversion] tactic is probably easier to understand by\n    seeing it in action than from general descriptions like the above.\n    Below you will find example theorems that demonstrate the use of\n    [inversion] and exercises to test your understanding. *)\n\nTheorem eq_add_S : forall (n m : nat),\n     S n = S m ->\n     n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.  Qed.\n\nTheorem silly4 : forall (n m : nat),\n     [n] = [m] ->\n     n = m.\nProof.\n  intros n o eq. inversion eq. reflexivity.  Qed.\n\n(** As a convenience, the [inversion] tactic can also\n    destruct equalities between complex values, binding\n    multiple variables as it goes. *)\n\nTheorem silly5 : forall (n m o : nat),\n     [n;m] = [o;o] ->\n     [n] = [m].\nProof.\n  intros n m o eq. inversion eq. reflexivity. Qed.\n\n(** **** Exercise: 1 star (sillyex1) *) \nExample sillyex1 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof.\n  intros. inversion H0. reflexivity. Qed.\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n  intros n m contra. inversion contra.  Qed.\n\n(** **** Exercise: 1 star (sillyex2) *)\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = [] ->\n     y :: l = z :: j ->\n     x = z.\nProof.\n  intros. inversion H. Qed.\n\n(** While the injectivity of constructors allows us to reason\n    [forall (n m : nat), S n = S m -> n = m], the reverse direction of\n    the implication is an instance of a more general fact about\n    constructors and functions, which we will often find useful: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A), \n    x = y -> f x = f y. \nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed. \n\n(** Here's another illustration of [inversion].  This is a slightly\n    roundabout way of stating a fact that we have already proved\n    above.  The extra equalities force us to do a little more\n    equational reasoning and exercise some of the tactics we've seen\n    recently. *)\n \nTheorem length_snoc' : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l. induction l as [| v' l'].\n  Case \"l = []\". intros n eq. rewrite <- eq. reflexivity.\n  Case \"l = v' :: l'\". intros n eq. simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.\n\n\n(** **** Exercise: 2 stars, optional (practice) *)\n(** A couple more nontrivial but not-too-complicated proofs to work\n    together in class, or for you to work as exercises.  They may\n    involve applying lemmas from earlier lectures or homeworks. *)\n \n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros. destruct n. reflexivity. simpl in H. inversion H. Qed.\n\nTheorem beq_nat_0_r : forall n,\n   beq_nat n 0 = true -> n = 0.\nProof.\n  intros.\n  destruct n. reflexivity. inversion H. Qed.\n\n\n(* ###################################################### *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b. \nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, the tactic [apply L in H] matches some\n    conditional statement [L] (of the form [L1 -> L2], say) against a\n    hypothesis [H] in the context.  However, unlike ordinary\n    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),\n    [apply L in H] matches [H] against [L1] and, if successful,\n    replaces it with [L2].\n \n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\" -- from [L1 -> L2] and a hypothesis matching [L1], it\n    gives us a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\" -- it says that if we know [L1->L2] and we\n    are trying to prove [L2], it suffices to prove [L1].  \n\n    -->deduction theorem\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n \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  symmetry in H. apply eq in H. symmetry in H. \n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, Coq tends to favor backward reasoning, but in some\n    situations the forward style can be easier to use or to think\n    about.  *)\n\n(** **** Exercise: 3 stars (plus_n_n_injective) *)\n(** Practice using \"in\" variants in this exercise. *)\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  simpl. destruct m. intros. reflexivity.\n  intros. inversion H.\n  simpl. intros. destruct m. inversion H.\n  simpl in H. rewrite <- plus_n_Sm in H. rewrite <- plus_n_Sm in H. \n  inversion H. apply IHn' in H1. apply f_equal with (f := S) in H1. \n  apply H1.\n  Qed.\n\n(* ###################################################### *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose \n    we want to show that the [double] function is injective -- i.e., \n    that it always maps different arguments to different results:  \n    Theorem double_injective: forall n m, double n = double m -> n = m. \n    The way we _start_ this proof is a little bit delicate: if we \n    begin it with\n      intros n. induction n.\n]] \n    all is well.  But if we begin it with\n      intros n m. induction n.\n    we get stuck in the middle of the inductive case... *)\n \nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = O\". simpl. intros eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". intros eq. destruct m as [| m'].\n    SCase \"m = O\". inversion eq.\n    SCase \"m = S m'\".  apply f_equal. \n      (* Here we are stuck.  The induction hypothesis, [IHn'], does\n         not give us [n' = m'] -- there is an extra [S] in the\n         way -- so the goal is not provable. *)\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context -- \n    intuitively, we have told Coq, \"Let's consider some particular\n    [n] and [m]...\" and we now have to prove that, if [double n =\n    double m] for _this particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove that\n    the proposition\n\n      - [P n]  =  \"if [double n = double m], then [n = m]\"\n\n    holds for all [n] by showing\n\n      - [P O]              \n\n         (i.e., \"if [double O = double m] then [O = m]\")\n\n      - [P n -> P (S n)]  \n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help with proving [R]!  (If we\n    tried to prove [R] from [Q], we would say something like \"Suppose\n    [double (S n) = 10]...\" but then we'd be stuck: knowing that\n    [double (S n)] is [10] tells us nothing about whether [double n]\n    is [10], so [Q] is useless at this point.) *)\n\n(** To summarize: Trying to carry out this proof by induction on [n]\n    when [m] is already in the context doesn't work because we are\n    trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = O\". simpl. intros m eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". \n    (* Notice that both the goal and the induction\n       hypothesis have changed: the goal asks us to prove\n       something more general (i.e., to prove the\n       statement for _every_ [m]), but the IH is\n       correspondingly more flexible, allowing us to\n       choose any [m] we like when we apply the IH.  *)\n    intros m eq.\n    (* Now we choose a particular [m] and introduce the\n       assumption that [double n = double m].  Since we\n       are doing a case analysis on [n], we need a case\n       analysis on [m] to keep the two \"in sync.\" *)\n    destruct m as [| m'].\n    SCase \"m = O\". \n      (* The 0 case is trivial *)\n      inversion eq.  \n    SCase \"m = S m'\".  \n      apply f_equal. \n      (* At this point, since we are in the second\n         branch of the [destruct m], the [m'] mentioned\n         in the context at this point is actually the\n         predecessor of the one we started out talking\n         about.  Since we are also in the [S] branch of\n         the induction, this is perfect: if we\n         instantiate the generic [m] in the IH with the\n         [m'] that we are talking about right now (this\n         instantiation is performed automatically by\n         [apply]), then [IHn'] gives us exactly what we\n         need to finish the proof. *)\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What this teaches us is that we need to be careful about using\n    induction to try to prove something too specific: If we're proving\n    a property of [n] and [m] by induction on [n], we may need to\n    leave [m] generic. *)\n\n(** The proof of this theorem has to be treated similarly: *)\n\n(** **** Exercise: 2 stars (beq_nat_true) *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n. induction n as [|n'].\n  intros. destruct m. reflexivity. inversion H.\n  intros. destruct m. inversion H.\n  apply IHn' in H. rewrite -> H. reflexivity.\n  Qed.\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal) *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** The strategy of doing fewer [intros] before an [induction] doesn't\n    always work directly; sometimes a little _rearrangement_ of\n    quantified variables is needed.  Suppose, for example, that we\n    wanted to prove [double_injective] by induction on [m] instead of\n    [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  Case \"m = O\". simpl. intros eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq. \n  Case \"m = S m'\". intros eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\".  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce\n    [n] for us!)   *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    will work, but it's not nice: We don't want to have to mangle the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them -- we want to state them in the most clear and\n    natural way. *)\n\n(**  What we can do instead is to first introduce all the\n    quantified variables and then _re-generalize_ one or more of\n    them, taking them out of the context and putting them back at\n    the beginning of the goal.  The [generalize dependent] tactic\n    does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. \n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  Case \"m = O\". simpl. intros n eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq.\n  Case \"m = S m'\". intros n eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\". apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n_Theorem_: For any nats [n] and [m], if [double n = double m], then\n  [n = m].\n\n_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n  any [n], if [double n = double m] then [n = m].\n\n  - First, suppose [m = 0], and suppose [n] is a number such\n    that [double n = double m].  We must show that [n = 0].\n\n    Since [m = 0], by the definition of [double] we have [double n =\n    0].  There are two cases to consider for [n].  If [n = 0] we are\n    done, since this is what we wanted to show.  Otherwise, if [n = S\n    n'] for some [n'], we derive a contradiction: by the definition of\n    [double] we would have [double n = S (S (double n'))], but this\n    contradicts the assumption that [double n = 0].\n\n  - Otherwise, suppose [m = S m'] and that [n] is again a number such\n    that [double n = double m].  We must show that [n = S m'], with\n    the induction hypothesis that for every number [s], if [double s =\n    double m'] then [s = m'].\n \n    By the fact that [m = S m'] and the definition of [double], we\n    have [double n = S (S (double m'))].  There are two cases to\n    consider for [n].\n\n    If [n = 0], then by definition [double n = 0], a contradiction.\n    Thus, we may assume that [n = S n'] for some [n'], and again by\n    the definition of [double] we have [S (S (double n')) = S (S\n    (double m'))], which implies by inversion that [double n' = double\n    m'].\n\n    Instantiating the induction hypothesis with [n'] thus allows us to\n    conclude that [n' = m'], and it follows immediately that [S n' = S\n    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted\n    to show. [] *)\n\n(** **** Exercise: 3 stars (gen_dep_practice) *)\n\n(** Prove this by induction on [l]. *)\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     index n l = None.\nProof.\n  intros. generalize dependent n.\n  induction l as [|hd tl]. simpl. intros. reflexivity.\n  simpl. destruct n. simpl. intros. inversion H.\n  simpl. intros. inversion H. rewrite -> H1. apply IHtl in H1.\n  rewrite -> H1. reflexivity. Qed.\n\n\n(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal) *)\n(** Write an informal proof corresponding to your Coq proof\n    of [index_after_last]:\n \n     _Theorem_: For all sets [X], lists [l : list X], and numbers\n      [n], if [length l = n] then [index n l = None].\n \n     _Proof_:\n     (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (gen_dep_practice_more) *)\n(** Prove this by induction on [l]. *)\n \nTheorem length_snoc''' : forall (n : nat) (X : Type) \n                              (v : X) (l : list X),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.  \n  intros. generalize dependent n. induction l as [| h t].\n  {intros. rewrite <- H. simpl. reflexivity. }\n  {intros n eq. simpl. apply f_equal. destruct n. inversion eq.\n   apply IHt. simpl in eq. inversion eq. reflexivity. }\nQed.\n\n\n(** **** Exercise: 3 stars, optional (app_length_cons) *)\n(** Prove this by induction on [l1], without using [app_length]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X) \n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  intros X l1 l2 x. \n  induction l1 as [| hd tl]. \n  {simpl. intros. rewrite -> H. reflexivity. }\n  {simpl. destruct n. \n   {simpl. intros. inversion H. }\n   {intros. inversion H. apply f_equal. apply IHtl in H1.\n    inversion H. rewrite -> H1.  rewrite -> H2.\n    reflexivity. }\n     }\nQed.\n    \n(** **** Exercise: 4 stars, optional (app_length_twice) *)\n(** Prove this by induction on [l], without using app_length. *)\n\nLemma app_length_twice_lemma : forall (X : Type) (l1 l2 :  list X) (x : X) (n : nat),\n                                 length (l1 ++ l2) = n -> length(l1 ++ x :: l2) = S n.\nProof.\n  intros X l1.\n  induction l1 as [|hd tl].\n  {intros. simpl in *. apply f_equal. apply H. }\n  {intros. destruct n. inversion H.\n   simpl in *. apply f_equal. apply IHtl. inversion H. reflexivity. }\n  Qed.\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  intros. \n  generalize dependent n.\n  induction l as [|hd tl].\n  {intros. simpl in *. destruct n.\n   {reflexivity. }\n   {inversion H. }\n  }\n  {intros. simpl. destruct n. \n   {inversion H. }\n   {simpl in *. inversion H. apply f_equal.\n    apply IHtl in H1. apply app_length_twice_lemma with (x := hd) in H1 .\n    rewrite -> H1. rewrite <- plus_n_Sm. inversion H. reflexivity. }\n  }\n  Qed.\n\n(* ###################################################### *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where the [destruct] tactic is\n    used to perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun. \n  destruct (beq_nat n 3).\n    Case \"beq_nat n 3 = true\". reflexivity.\n    Case \"beq_nat n 3 = false\". destruct (beq_nat n 5).\n      SCase \"beq_nat n 5 = true\". reflexivity.\n      SCase \"beq_nat n 5 = false\". reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,\n    either [n] is equal to [3] or it isn't, so we use [destruct\n    (beq_nat n 3)] to let us reason about the two cases. \n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c].\n\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  intros.\n  unfold override. destruct (beq_nat k1 k2). \n  {reflexivity. }\n  {reflexivity. }\nQed.\n\n(** **** Exercise: 3 stars, optional (combine_split) *)\n(** Complete the proof below *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l. induction l as [|[h1 h2] t]. intros. simpl in *. inversion H. reflexivity.\n  intros. inversion H. simpl. apply f_equal. apply IHt. destruct (split t).\n  simpl. reflexivity. \n  Qed.\n\n(** Sometimes, doing a [destruct] on a compound expression (a\n    non-variable) will erase information we need to complete a proof. *)\n(** For example, suppose\n    we define a function [sillyfun1] like this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** And suppose that we want to convince Coq of the rather\n    obvious observation that [sillyfun1 n] yields [true] only when [n]\n    is odd.  By analogy with the proofs we did with [sillyfun] above,\n    it is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution peformed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that since, in this branch of the case\n    analysis, [beq_nat n 3 = true], it must be that [n = 3], from\n    which it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation (with whatever\n    name we choose). *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got stuck\n    above, except that the context contains an extra equality\n    assumption, which is exactly what we need to make progress. *)\n    Case \"e3 = true\". apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    Case \"e3 = false\".\n     (* When we come to the second equality test in the body of the\n       function we are reasoning about, we can use [eqn:] again in the\n       same way, allow us to finish the proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5. \n        SCase \"e5 = true\".\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        SCase \"e5 = false\". inversion eq.  Qed.\n\n\n(** **** Exercise: 2 stars (destruct_eqn_practice) *)\nTheorem bool_fn_applied_thrice : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  intros.\n  destruct (f b) eqn:eqFB.\n  {destruct (f true) eqn:eqFT.\n   {rewrite -> eqFT. reflexivity. }\n   {destruct (f false) eqn :eqFF.\n    {reflexivity. }\n    {destruct b. rewrite -> eqFB in eqFT. inversion eqFT.\n     rewrite -> eqFB in eqFF. inversion eqFF. }\n   }\n  }\n  {destruct (f false) eqn : eqFF.\n   {destruct (f true) eqn : eqFT.\n    {destruct b. rewrite -> eqFB in eqFT. inversion eqFT. \n     rewrite ->eqFB in eqFF. inversion eqFF. }\n   {destruct b. rewrite -> eqFB in eqFT. reflexivity. reflexivity. }\n   }\n  {rewrite -> eqFF. reflexivity. }\n  }\nQed. \n \n(** **** Exercise: 2 stars (override_same) *)\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.\n  unfold override. destruct (beq_nat k1 k2) eqn : H1.\n  rewrite <- H. apply f_equal. apply beq_nat_true in H1.\n  rewrite -> H1. reflexivity.\n  reflexivity.\n  Qed.\n  \n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen a bunch of Coq's fundamental tactics.  We'll\n    introduce a few more as we go along through the coming lectures,\n    and later in the course we'll introduce some more powerful\n    _automation_ tactics that make Coq do more of the low-level work\n    in many cases.  But basically we've got what we need to get work\n    done.\n\n    Here are the ones we've seen:\n\n      - [intros]: \n        move hypotheses/variables from goal to context \n\n      - [reflexivity]:\n        finish the proof (when the goal looks like [e = e])\n\n      - [apply]:\n        prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: \n        apply a hypothesis, lemma, or constructor to a hypothesis in\n        the context (forward reasoning)\n\n      - [apply... with...]:\n        explicitly specify values for variables that cannot be\n        determined by pattern matching\n\n      - [simpl]:\n        simplify computations in the goal \n\n      - [simpl in H]:\n        ... or a hypothesis \n\n      - [rewrite]:\n        use an equality hypothesis (or lemma) to rewrite the goal \n\n      - [rewrite ... in H]:\n        ... or a hypothesis \n\n      - [symmetry]:\n        changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]:\n        changes a hypothesis of the form [t=u] into [u=t]\n\n      - [unfold]:\n        replace a defined constant by its right-hand side in the goal \n\n      - [unfold... in H]:\n        ... or a hypothesis  \n\n      - [destruct... as...]:\n        case analysis on values of inductively defined types \n\n      - [destruct... eqn:...]:\n        specify the name of an equation to be added to the context,\n        recording the result of the case analysis\n\n      - [induction... as...]:\n        induction on values of inductively defined types \n\n      - [inversion]:\n        reason by injectivity and distinctness of constructors\n\n      - [assert (e) as H]:\n        introduce a \"local lemma\" [e] and call it [H] \n\n      - [generalize dependent x]:\n        move the variable [x] (and anything else that depends on it)\n        from the context back to an explicit hypothesis in the goal\n        formula \n*)\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\nTheorem XEqX : forall n, beq_nat n n = true.\nProof.\n  intros. induction n.\n  reflexivity. simpl. rewrite -> IHn.\n  reflexivity. Qed.\n\n(** **** Exercise: 3 stars (beq_nat_sym) *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  intros n.\n  induction n.\n  intros. destruct m. reflexivity. simpl. reflexivity.\n  intros. destruct m. simpl. reflexivity. simpl.\n  apply IHn. Qed.\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal) *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans) *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof. \n  intros. apply beq_nat_true in H. apply beq_nat_true in H0.\n  rewrite -> H. rewrite -> H0. apply XEqX.\n  Qed.\n\n\n(** **** Exercise: 3 stars, advanced (split_combine) *)\n(** We have just proven that for all lists of pairs, [combine] is the\n    inverse of [split].  How would you formalize the statement that\n    [split] is the inverse of [combine]?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)\n\nDefinition split_combine_statement : Prop :=\n  forall (X Y : Type) (l1 : list X) (l2 : list Y) (l : list (X * Y)), \n    length l1 = length l2 -> combine l1 l2 = l -> split l = (l1, l2).\n\nTheorem split_combine : split_combine_statement.\nProof.\n  intros X Y. induction l1.\n  simpl. intros. destruct l2.\n  rewrite <- H0.  reflexivity. inversion H.\n  Case \"l1 = cons hd tl\".\n  intros. destruct l2. inversion H.\n  inversion H. simpl in H0. destruct l. inversion H0.\n  inversion H0.  apply IHl1 with (l := l) in H2.\n  rewrite -> H4. simpl. rewrite -> H2. reflexivity.\n  apply H4.\n  Qed.\n  \n  \n(** **** Exercise: 3 stars (override_permute) *)\nTheorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),\n  beq_nat k2 k1 = false ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n  intros. unfold override.\n  rewrite -> beq_nat_sym in H. Admitted.\n\n(** **** Exercise: 3 stars, advanced (filter_exercise) *)\n(** This one is a bit challenging.  Pay attention to the form of your IH. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  intros. generalize dependent x. generalize dependent lf.\n  induction l.\n  intros. simpl in H. inversion H.\n  intros. simpl in *. destruct (test x) eqn : H1. inversion H.\n  rewrite <- H2. apply H1. apply IHl with (lf := lf). apply H.\n  Qed.\n\n(** **** Exercise: 4 stars, advanced (forall_exists_challenge) *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n  \n      forallb evenb [0;2;4;5] = false\n  \n      forallb (beq_nat 5) [] = true\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n      existsb (beq_nat 5) [0;2;3;6] = false\n \n      existsb (andb true) [true;true;false] = true\n \n      existsb oddb [1;0;0;0;0;3] = true\n \n      existsb evenb [] = false\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n \n    Prove that [existsb'] and [existsb] have the same behavior.\n*)\n\nFixpoint forallb {X : Type} (p : X -> bool) (l : list X) : bool :=\n  match l with\n      |nil => true\n      |x::xs => if p x \n                then forallb p xs\n                else false\n  end.\n\nFixpoint existsb {X : Type} (p : X -> bool) (l : list X) : bool := \n  match l with\n      |nil => false\n      |x::xs => if p x\n                then true\n                else existsb p xs\n  end.\n\nDefinition existsb' {X:Type} (p:X -> bool) (l : list X) : bool :=\n  negb (forallb (fun x => negb(p x)) l).\n\nTheorem ExistsBCorrect : forall (X : Type) (p : X -> bool) (l : list X),\n                           existsb p l = existsb' p l.\nProof.\n  intros. \n  unfold existsb'.\n  induction l. simpl. reflexivity.\n  simpl. destruct (p x) eqn : H. simpl. reflexivity.\n  simpl. apply IHl. Qed.\n  \n  \n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)\n\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/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800691997339971, "lm_q2_score": 0.919642530076595, "lm_q1q2_score": 0.7363504142458132}}
{"text": "Require Import List.\nRequire Import Arith.\n\n\n(** Not actually an exersize I was just checking out how match works*)\nFixpoint odd n :=\n  match n with\n    0 => False\n  | 1 => True\n  | S (S p) => odd p \n  end.\n\n(** Range Exersize*)\nFixpoint range (n:nat) :=\n  match n with\n    0 => nil\n  | S p => (range p) ++ (p :: nil)\n  end.\n\nCompute range 5.\n\n(** Sorting Exersize*)\nRequire Import Bool.\n\nDefinition endIsSorted (l : list nat) :=\n  (orb ((length l) <? 2) ((nth 0 l 0) <=? (nth 1 l 0))).\n  \nFixpoint isSorted (l: list nat) :=\n  match l with\n  | nil => true\n  | _ :: tail => (andb (endIsSorted l) (isSorted tail))\n  end.\n\nCompute isSorted (1::2::3::nil).\nCompute isSorted (1::4::3::nil).\n\n(*Counting occurances in list Exersize*)\n\nFixpoint countOccurances (l : list nat) (n : nat) : nat :=\n  match l with\n  | nil => 0\n  | head :: tail => if head =? n then \n      1 + (countOccurances tail n) else (countOccurances tail n)\n  end.\n\nCompute countOccurances (1::2::1::4::1::4::nil) 1.\nCompute countOccurances (1::2::1::4::1::4::nil) 4.", "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/Chapter2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576759, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7363493510428707}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(*                                                                          *)\n(*                           Group Theory in Coq                            *)\n(*                                                                          *)\n(*                                                                          *)\n(*                                Coq V5.10                                 *)\n(*\t\t\t\t\t\t\t\t\t    *)\n(*\t\t\t         Gilles Kahn \t\t\t\t    *)\n(*\t\t\t\t\t\t\t\t\t    *)\n(*                                  INRIA                                   *)\n(*                             Sophia-Antipolis                             *)\n(*\t\t\t\t\t\t\t\t\t    *)\n(*\t\t\t\t January 1996\t\t\t\t    *)\n(*                                                                          *)\n(****************************************************************************)\n\nRequire Import Ensembles.\nRequire Import Laws.\nSection group_definition.\nVariable U : Type.\n\nRecord Group : Type := group\n  {G_ : Ensemble U;\n   star_ : U -> U -> U;\n   inv_ : U -> U;\n   e_ : U;\n   G0_ : endo_operation U G_ star_;\n   G1_ : associative U star_;\n   G2a_ : In U G_ e_;\n   G2b_ : left_neutral U star_ e_;\n   G2c_ : right_neutral U star_ e_;\n   G3a_ : endo_function U G_ inv_;\n   G3b_ : right_inverse U star_ inv_ e_;\n   G3c_ : left_inverse U star_ inv_ e_}.\n\nInductive subgroup (g1 g2 : Group) : Prop :=\n    Definition_of_subgroup :\n      Included U (G_ g1) (G_ g2) -> star_ g1 = star_ g2 -> subgroup g1 g2.\n\nDefinition Setsubgroup (E : Ensemble U) (Gr : Group) : Prop :=\n  ex (fun g : Group => subgroup g Gr /\\ G_ g = E).\nEnd group_definition.\n\n", "meta": {"author": "coq-contribs", "repo": "group-theory", "sha": "ab6459ff2571529edb0d5c10c13f30b1d9379d71", "save_path": "github-repos/coq/coq-contribs-group-theory", "path": "github-repos/coq/coq-contribs-group-theory/group-theory-ab6459ff2571529edb0d5c10c13f30b1d9379d71/Group_definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7363265448522286}}
{"text": "Require Export Arith.\nRequire Export ZArithRing.\nRequire Export Omega.\n\nTheorem Frobenius_3_8 :\n  forall n:nat,\n    8 <= n -> (exists p:nat, (exists q:nat, n = 3 * p + 5 * q)).\nProof.\n intros n Hle; elim Hle.\n exists 1; exists 1; ring.\n intros n' Hle' [p' [q']].\n case q'.\n intros Heq.\n assert (H3lep': 3 <= p').\n omega.\n exists (p' - 3); exists 2.\n rewrite Heq.\n replace (3*(p'-3)+5*2) with (S (3*3+3*(p'-3))).\n rewrite <- mult_plus_distr_l.\n rewrite le_plus_minus_r; auto.\n ring.\n intros q'' Heq; exists (p'+2); exists q''; rewrite Heq.\n ring.\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/inductive-prop-chap/SRC/frobenius.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7363265371700666}}
{"text": "Require Import Setoid.\nRequire Import ZArith.\nRequire Import Setoid.\n\nDefinition Rel (A:Type) := A -> A -> Prop.\n\nInductive refltrans {A:Type} (R: Rel A) : A -> A -> Prop :=\n| refl: forall a, (refltrans R) a a\n| rtrans: forall a b c, R a b -> refltrans R b c -> refltrans R a c.\n\nDefinition Z_prop {A:Type} (R: Rel A) := exists f:A -> A, forall a b, R a b -> ((refltrans R) b (f a) /\\ (refltrans R) (f a) (f b)).\n\nDefinition f_is_Z {A:Type} (R: Rel A) (f: A -> A) := forall a b, R a b -> ((refltrans R)  b (f a) /\\ (refltrans R) (f a) (f b)).\n\nDefinition f_is_weak_Z {A} (R R': Rel A) (f: A -> A) := forall a b, R a b -> ((refltrans R') b (f a) /\\ (refltrans R') (f a) (f b)).\n\nDefinition comp {A} (f1 f2: A -> A) := fun x:A => f1 (f2 x).\nNotation \"f1 # f2\" := (comp f1 f2) (at level 40).\n\nInductive union {A} (red1 red2: Rel A) : Rel A :=\n| union_left: forall a b, red1 a b -> union red1 red2 a b\n| union_right: forall a b, red2 a b -> union red1 red2 a b.\nNotation \"R1 !_! R2\" := (union R1 R2) (at level 40).\n\nDefinition Z_comp {A:Type} (R :Rel A) := exists (R1 R2: Rel A) (f1 f2: A -> A), (forall x y, R x y <-> (R1 !_! R2) x y) /\\ f_is_Z R1 f1 /\\ (forall a b, R1 a b -> (refltrans R) ((f2 # f1) a) ((f2 # f1) b)) /\\ (forall a b, b = f1 a -> (refltrans R) b (f2 b)) /\\ (f_is_weak_Z R2 R (f2 # f1)).\n\nDefinition Z_comp_eq {A:Type} (R :Rel A) := exists (R1 R2: Rel A) (f1 f2: A -> A), (forall x y, R x y <-> (R1 !_! R2) x y) /\\ (forall a b, R1 a b -> (f1 a) = (f1 b)) /\\ (forall a, (refltrans R1) a (f1 a)) /\\ (forall b a, a = f1 b -> (refltrans R) a (f2 a)) /\\ (f_is_weak_Z R2 R (f2 # f1)).\n\nInductive trans {A} (red: Rel A) : Rel A :=\n| singl: forall a b,  red a b -> trans red a b\n| transit: forall b a c,  red a b -> trans red b c -> trans red a c.\n\nArguments transit {A} {red} _ _ _ _ _ .\n\nLemma trans_composition {A} (R: Rel A):\n  forall t u v, trans R t u -> trans R u v -> trans R t v.\nProof.\n  intros t u v H1 H2. induction H1.\n  - apply transit with b; assumption.\n  - apply transit with b.\n    + assumption.\n    + apply IHtrans; assumption.\nQed.\n\nLemma refltrans_composition {A} (R: Rel A): forall t u v, refltrans R t u -> refltrans R u v -> refltrans R t v.\nProof.\n  intros t u v.\n  intros H1 H2.\n  induction H1.\n  - assumption.\n  - apply rtrans with b.\n    + assumption.\n    + apply IHrefltrans; assumption.\nQed.\n\nLemma union_or {A}: forall (r1 r2: Rel A) (a b: A), (r1 !_! r2) a b <-> (r1 a b) \\/ (r2 a b).\nProof.\n  intros r1 r2 a b; split.\n  - intro Hunion.\n    inversion Hunion; subst.\n    + left; assumption.\n    + right; assumption.\n  - intro Hunion.\n    inversion Hunion.\n    + apply union_left; assumption.\n    + apply union_right; assumption.\nQed.\n\nLemma refltrans_union {A:Type}: forall (R R' :Rel A) (a b: A), refltrans R a b -> refltrans (R !_! R') a b.\nProof.\n  intros R R' a b Hrefl.\n  induction Hrefl.\n  - apply refl.\n  - apply rtrans with b.\n    + apply union_left. assumption.\n    + assumption.\nQed.\n\nLemma refltrans_union_equiv {A}: forall (R R1 R2 : Rel A), (forall (x y : A), (R x y <-> (R1 !_! R2) x y)) -> forall (x y: A), refltrans (R1 !_! R2) x y -> refltrans R x y.\nProof.\n  intros.\n  induction H0.\n  + apply refl.\n  + apply rtrans with b.\n    - apply H. assumption.\n    - assumption.\nQed.\n\nTheorem Z_comp_implies_Z_prop {A:Type}: forall (R :Rel A), Z_comp R -> Z_prop R.\nProof.\n  intros R H.\n  unfold Z_prop. unfold Z_comp in H. destruct H as\n  [ R1 [ R2 [f1 [f2 [Hunion [H1 [H2 [H3 H4]]]]]]]].\n  exists (f2 # f1).\n  intros a b HR.\n  apply Hunion in HR. inversion HR; subst. clear HR.\n  - split.\n    + apply refltrans_composition with (f1 a).\n      * apply H1 in H.\n        destruct H as [Hb Hf].\n        apply (refltrans_union R1 R2) in Hb.\n        apply refltrans_union_equiv with R1 R2.\n        ** apply Hunion.\n        ** apply Hb.\n      * apply H3 with a. reflexivity.\n    + apply H2. assumption. \n  - apply H4. assumption.\nQed.\n\nLemma Z_comp_eq_implies_Z_comp {A:Type}: forall (R : Rel A), Z_comp_eq R -> Z_comp R.\nProof.\n  intros R Heq. unfold Z_comp_eq in Heq.\n  destruct Heq as [R1 [R2 [f1 [f2 [Hunion [H1 [H2 [H3 H4]]]]]]]].\n  unfold Z_comp.\n  exists R1, R2, f1, f2.\n  split.\n  - assumption.\n  - split.\n    + unfold f_is_Z.\n      intros a b H; split.\n      * apply H1 in H. rewrite H. apply H2.\n      * apply H1 in H. rewrite H. apply refl.\n    + split.\n      * intros a b H.\n        unfold comp.\n        apply H1 in H.\n        rewrite H.\n        apply refl.\n      * split; assumption.\nQed.\n\nCorollary Z_comp_eq_implies_Z_prop {A:Type}: forall (R : Rel A), Z_comp_eq R -> Z_prop R.\nProof.\n  intros.\n  apply Z_comp_eq_implies_Z_comp in H.\n  apply Z_comp_implies_Z_prop.\n  assumption.\nQed.\n\n\n", "meta": {"author": "nunesgrf", "repo": "lx-confluence", "sha": "77f51c2ebf7a49510e29545d5a1dbd8e1bc471bf", "save_path": "github-repos/coq/nunesgrf-lx-confluence", "path": "github-repos/coq/nunesgrf-lx-confluence/lx-confluence-77f51c2ebf7a49510e29545d5a1dbd8e1bc471bf/src/ZProperty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7362944490014492}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) : natural :=\n  mult lf2 (plus Zero x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj196_coqofml_DfMPNT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7362944478364848}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) : natural :=\n  plus Zero (plus lf2 lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj203_coqofml_G4Eoxt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7362944454170495}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) : natural :=\n  plus Zero (plus lf2 lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj124_coqofml_mSvOgd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7362944374642044}}
{"text": "Require Import\n  Coq.Lists.List Coq.Lists.SetoidList MathClasses.implementations.list\n  MathClasses.interfaces.abstract_algebra MathClasses.interfaces.finite_sets MathClasses.interfaces.orders\n  MathClasses.theory.lattices MathClasses.orders.lattices.\n\n(*\nWe define finite sets as unordered lists. This implementation is slow,\nbut quite convenient as a reference implementation to lift properties to\narbitrary finite set instances.\n*)\nInstance listset A `{Equiv A} : SetType A | 30 := sig (NoDupA (=)).\n\nSection listset.\nContext `{Setoid A} `{∀ a₁ a₂ : A, Decision (a₁ = a₂)}.\n\nInstance listset_in_raw: Contains A (list A) := InA (=).\nInstance listset_equiv_raw: Equiv (list A) := equivlistA (=).\nInstance: Setoid (list A) := {}.\n\nInstance listset_empty_raw: Bottom (list A) := [].\nInstance listset_join_raw: Join (list A) := @app A.\nInstance: BoundedJoinSemiLattice (list A).\nProof.\n  split. split. split. split. apply _.\n       repeat intro. now apply equivlistA_app_ass.\n      apply _.\n     repeat intro. now apply equivlistA_app_nil_l.\n    repeat intro. now apply equivlistA_app_nil_r.\n   repeat intro. now apply equivlistA_app_comm.\n  repeat intro. now apply equivlistA_app_idem.\nQed.\n\nGlobal Instance listset_to_list: Cast (set_type A) (list A) := @proj1_sig _ _.\nGlobal Instance listset_in: SetContains A := λ x l, x ∈ 'l.\nGlobal Instance listset_le: SetLe A := λ l k, ∀ x, x ∈ l → x ∈ k.\nGlobal Instance listset_equiv: SetEquiv A := λ l k, ∀ x, x ∈ l ↔ x ∈ k.\n\nInstance: Setoid (set_type A).\nProof. now apply (setoids.projected_setoid listset_to_list). Qed.\n\nGlobal Instance: Setoid_Morphism listset_to_list.\nProof. firstorder. Qed.\nGlobal Instance: Injective listset_to_list.\nProof. firstorder. Qed.\n\nGlobal Instance: Proper ((=) ==> (=) ==> iff) listset_in.\nProof.\n  intros x y E1 l k E2.\n  transitivity (listset_in x k). easy.\n  unfold listset_in. now rewrite E1.\nQed.\n\nFixpoint listset_add_raw (x : A) (l : list A) : list A :=\n  match l with\n  | [] => [x]\n  | y :: l => y :: if decide_rel (=) x y then l else listset_add_raw x l\n  end.\n\nLemma listset_add_raw_cons l x :\n  x :: l = listset_add_raw x l.\nProof.\n  induction l; simpl; try reflexivity.\n  case (decide_rel _); intros E.\n   now rewrite E, equivlistA_double_head.\n  now rewrite equivlistA_permute_heads, IHl.\nQed.\n\nLemma listset_add_raw_InA (l : list A) (x y : A) :\n  y ∈ listset_add_raw x l → y = x ∨ y ∈ l.\nProof.\n  unfold contains, listset_in_raw. induction l; simpl.\n   intros E. inversion_clear E; auto.\n  case (decide_rel _); auto; intros E1 E2.\n  inversion_clear E2; intuition.\nQed.\n\nLemma listset_add_raw_NoDupA (l : list A) (x : A) :\n  NoDupA (=) l → NoDupA (=) (listset_add_raw x l).\nProof.\n  intros Pl. induction l; simpl.\n   now apply NoDupA_singleton.\n  case (decide_rel _); intros E1; auto.\n  inversion_clear Pl.\n  apply NoDupA_cons; auto.\n  intros E2. destruct (listset_add_raw_InA _ _ _ E2); intuition.\nQed.\n\nGlobal Program Instance listset_empty: EmptySet A := [].\nGlobal Program Instance listset_singleton: SetSingleton A := λ x, [x].\nNext Obligation. now apply NoDupA_singleton. Qed.\nGlobal Program Instance listset_join: SetJoin A := λ l k, fold_right listset_add_raw (`k) (`l)↾_.\nNext Obligation.\n  destruct l as [l Pl], k as [k Pk].\n  induction l; intros; simpl in *; auto.\n  apply listset_add_raw_NoDupA, IHl. now inversion Pl.\nQed.\n\nInstance: Setoid_Morphism listset_singleton.\nProof.\n  split; try apply _. intros ? ? E.\n  apply (injective listset_to_list). change ([x] = [y]). now rewrite E.\nQed.\n\nLemma listset_to_list_preserves_join l k :\n  listset_to_list (l ⊔ k) = listset_to_list l ⊔ listset_to_list k.\nProof.\n  destruct l as [l Pl], k as [k Pk].\n  unfold join, listset_join, listset_join_raw. simpl. clear Pk Pl.\n  induction l; simpl; intros; [easy|].\n  now rewrite <-IHl, listset_add_raw_cons.\nQed.\n\nInstance: BoundedJoinSemiLattice (set_type A).\nProof.\n  apply (projected_bounded_sl listset_to_list).\n   intros. now apply listset_to_list_preserves_join.\n  reflexivity.\nQed.\n\nLemma listset_in_join l k x : x ∈ l ⊔ k ↔ x ∈ l ∨ x ∈ k.\nProof.\n  unfold contains, listset_in_raw, listset_in.\n  rewrite listset_to_list_preserves_join.\n  now apply InA_app_iff.\nQed.\n\nInstance: JoinSemiLatticeOrder listset_le.\nProof.\n  apply alt_Build_JoinSemiLatticeOrder. intros l k.\n  unfold le, listset_le, equiv, listset_equiv.\n  setoid_rewrite listset_in_join. firstorder auto.\nQed.\n\nLemma listset_induction (P : set_type A → Prop) `{proper : !Proper ((=) ==> iff) P} :\n  P ∅ → (∀ x l, x ∉ l → P l → P ({{ x }} ⊔ l)) → ∀ l, P l.\nProof.\n  intros Pempty Padd.\n  intros [l Pl]. induction l as [|x l].\n   apply proper with ∅; firstorder.\n  inversion_clear Pl as [|??? Pl'].\n  apply proper with ({{ x }} ⊔ l↾Pl'); auto.\n  intros z. change (z ∈ x :: l ↔ z ∈ listset_add_raw x l).\n  now rewrite listset_add_raw_cons.\nQed.\n\nFixpoint listset_extend_raw `{Bottom B} `{Join B} (f : A → B) (l : list A) : B :=\n  match l with\n  | [] => ⊥\n  | x :: l => f x ⊔ listset_extend_raw f l\n  end.\n\nGlobal Instance list_extend: FSetExtend A := λ _ _ _ f l, listset_extend_raw f (`l).\n\nSection listset_extend.\n  Context `{BoundedJoinSemiLattice B} `{!Setoid_Morphism (f : A → B)}.\n\n  Lemma listset_extend_raw_permute (l k : list A) :\n    PermutationA (=) l k → listset_extend_raw f l = listset_extend_raw f k.\n  Proof.\n    induction 1; simpl.\n       reflexivity.\n      apply sg_op_proper. now apply sm_proper. easy.\n     now rewrite !associativity, (commutativity (f _)).\n    etransitivity; eassumption.\n  Qed.\n\n  Instance list_extend_proper: Proper (equiv ==> equiv) (fset_extend f).\n  Proof.\n    intros [??][??] ?.\n    apply listset_extend_raw_permute. now apply NoDupA_equivlistA_PermutationA.\n  Qed.\n\n  Lemma list_extend_empty:\n    fset_extend f ∅ = ⊥.\n  Proof. reflexivity. Qed.\n\n  Lemma list_extend_add x l :\n    fset_extend f ({{x}} ⊔ l) = f x ⊔ fset_extend f l.\n  Proof.\n    destruct l as [l Pl]. unfold fset_extend, list_extend. simpl. clear Pl.\n    induction l; simpl; [easy|].\n    case (decide_rel _); intros E.\n     now rewrite E, associativity, (idempotency (&) _).\n    now rewrite IHl, 2!associativity, (commutativity (f _)).\n  Qed.\n\n  Instance list_extend_mor:\n    BoundedJoinSemiLattice_Morphism (fset_extend f).\n  Proof.\n    repeat (split; try apply _).\n     intros l k. change (fset_extend f (l ⊔ k) = fset_extend f l ⊔ fset_extend f k).\n     pattern l. apply listset_induction; clear l.\n       solve_proper.\n      now rewrite list_extend_empty, 2!left_identity.\n     intros x l E1 E2.\n     now rewrite <-associativity, 2!list_extend_add, E2, associativity.\n    reflexivity.\n  Qed.\nEnd listset_extend.\n\nLocal Existing Instance list_extend_mor.\n\nGlobal Instance: FSet A.\nProof.\n  split; try apply _.\n   intros B ???? f ? x y E.\n   unfold compose, fset_extend, list_extend. simpl.\n   now rewrite E, right_identity.\n  intros B ??? f ? h ? E1 k l E2.\n  pose proof (bounded_join_slmor_b (f:=h)).\n  rewrite E2. clear k E2. pattern l.\n  apply listset_induction; clear l.\n    solve_proper.\n   now rewrite preserves_bottom.\n  intros x l E2 E3. rewrite list_extend_add, preserves_join, E3.\n  apply sg_op_proper; [|easy]. symmetry. now apply E1.\nQed.\n\nInstance: FSetContainsSpec A.\nProof.\n  split; try apply _. unfold le, listset_le.\n  intros x X; split; intros E1.\n   intros z E2. inversion_clear E2 as [?? E3|?? E3].\n    now rewrite E3.\n   now inversion E3.\n  apply E1. now rapply InA_cons_hd.\nQed.\n\nInstance listset_in_raw_dec: ∀ x (l : list A), Decision (x ∈ l) := λ x l, InA_dec (decide_rel (=)) x l.\nGlobal Instance listset_in_dec: ∀ x (l : set_type A), Decision (x ∈ l) := λ x l, InA_dec (decide_rel (=)) x ('l).\n\nInstance listset_meet_raw: Meet (list A) :=\n  fix listset_meet_raw l k :=\n    match l with\n    | [] => []\n    | x :: l => if decide_rel (∈) x k then x :: listset_meet_raw l k else listset_meet_raw l k\n    end.\n\nLemma listset_in_meet_raw l k x :\n  x ∈ l ⊓ k ↔ x ∈ l ∧ x ∈ k.\nProof.\n  unfold meet, contains, listset_in_raw. split.\n   intros E; split; revert E.\n    induction l; simpl.\n     intuition.\n    case (decide_rel _); intros ? E; intuition.\n    inversion_clear E; intuition.\n   induction l; simpl.\n    intros E1; inversion E1.\n   case (decide_rel _); intros ? E1; intuition.\n   inversion_clear E1 as [?? E2|]; auto. now rewrite E2.\n  intros [E1 E2]. induction l; simpl; [easy|].\n  case (decide_rel _); intros E3.\n   inversion_clear E1; intuition.\n  inversion_clear E1 as [?? E4|]; intuition.\n  destruct E3. now rewrite <-E4.\nQed.\n\nLemma listset_meet_raw_NoDupA (l k : list A) :\n  NoDupA (=) l → NoDupA (=) (l ⊓ k).\nProof.\n  unfold meet. intros Pl. induction l; simpl; auto.\n  inversion_clear Pl as [|? ? E1].\n  case (decide_rel _); intros; auto.\n  apply NoDupA_cons; auto.\n  intros E2. destruct E1. now apply (listset_in_meet_raw l k _).\nQed.\n\nGlobal Program Instance listset_meet: SetMeet A := λ l k, listset_meet_raw l k.\nNext Obligation. apply listset_meet_raw_NoDupA. now destruct l. Qed.\n\nInstance listset_diff_raw: Difference (list A) :=\n  fix listset_diff_raw l k :=\n    match l with\n    | [] => []\n    | x :: l => if decide_rel (∈) x k then listset_diff_raw l k else x :: listset_diff_raw l k\n    end.\n\nLemma listset_in_diff_raw l k x :\n  x ∈ l ∖ k ↔ x ∈ l ∧ x ∉ k.\nProof.\n  unfold difference, contains, listset_in_raw. split.\n   intros E; split; revert E.\n    induction l; simpl.\n     intuition.\n    case (decide_rel _); intros ? E; intuition.\n    inversion_clear E; intuition.\n   induction l; simpl.\n    intros E1; inversion E1.\n   case (decide_rel _); intros ? E1.\n    intuition.\n   inversion_clear E1 as [?? E2|]; auto. now rewrite E2.\n  intros [E1 E2]. induction l; simpl; [easy|].\n  case (decide_rel _); intros E3.\n   inversion_clear E1 as [?? E4|]; intuition.\n   destruct E2. now rewrite E4.\n  inversion_clear E1; intuition.\nQed.\n\nLemma listset_diff_raw_NoDupA (l k : list A) :\n  NoDupA (=) l → NoDupA (=) (l ∖ k).\nProof.\n  unfold difference. intros Pl. induction l; simpl; auto.\n  inversion_clear Pl as [|? ? E1].\n  case (decide_rel _); intros; auto.\n  apply NoDupA_cons; auto.\n  intros E2. destruct E1. now apply (listset_in_diff_raw l k _).\nQed.\n\nGlobal Program Instance listset_diff: SetDifference A := λ l k, listset_diff_raw l k.\nNext Obligation. apply listset_diff_raw_NoDupA. now destruct l. Qed.\n\nGlobal Instance: FullFSet A | 30.\nProof.\n  split; try apply _.\n   intros [??] [??]. now rapply listset_in_meet_raw.\n  intros [??] [??]. now rapply listset_in_diff_raw.\nQed.\nEnd listset.\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/math-classes/implementations/list_finite_set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7362501705458668}}
{"text": "Section ExerciseTwo.\n\nVariable X : Set.\nVariable P Q R : X -> Prop.\n\nLemma Ex2A : (exists x, (P x) /\\ (Q x)) -> (exists x, (P x)) /\\ (exists x, (Q x)).\nintros H.\nsplit.\n  destruct H as [x H1].\n  destruct H1 as [H2 H3].\n  exists x.\n  exact H2.\n  destruct H as [x H1].\n  destruct H1 as [H2 H3].\n  exists x.\n  exact H3.\nQed.\n\nVariable A : X -> X -> Prop.\n\nLemma Ex2B : (exists x, forall y, (A x y)) -> (forall y, exists x, (A x y)).\nintros H.\ndestruct H as [x H2].\nintro H3.\nexists x.\napply H2.\nQed.\n\nLemma Ex2C : (exists x, (P x)) -> (forall x y, (P x) -> (Q y)) -> (forall y, (Q y)).\nintros H1 H2.\nintros H3.\nelim H1.\nintros H4.\napply H2.\nQed.\n\nLemma Ex2D : (forall x, (Q x) -> (R x)) -> (exists x, (P x) /\\ (Q x)) -> (exists x, (P x) /\\ (R x)).\nintros H1 H2.\ndestruct H2 as [x H3].\nexists x.\ndestruct H3 as [H4 H5].\nsplit.\n  exact H4.\n  apply H1.\n  exact H5.\nQed.\n\nLemma Ex2E : (forall x, (P x) -> (Q x)) -> (exists x, (P x)) -> (exists y, (Q y)).\nProof.\nintros H1 H2.\ndestruct H2 as [x H3].\nexists x.\napply H1.\nexact H3.\nQed.\n\nLemma Ex2F : (exists x, (P x)) \\/ (exists x, (Q x)) <-> (exists x, (P x) \\/ (Q x)).\nProof.\nsplit.\n  (* left to right *)\n  intros H1.\n  destruct H1 as [H2 | H3].\n  destruct H2 as [x H4].\n  exists x.\n  left; exact H4.\n  destruct H3 as [x H5].\n  exists x.\n  right; exact H5.\n  (* right to left *)\n  intros H1.\n  destruct H1 as [x H2].\n  destruct H2 as [H3 | H4].\n  left.\n  exists x.\n  exact H3.\n  right.\n  exists x.\n  exact H4.\nQed.\n", "meta": {"author": "vitorenesduarte", "repo": "the_coq_proof_assistant", "sha": "6aca5e1b0bba923a6b118838b1442f0876af5009", "save_path": "github-repos/coq/vitorenesduarte-the_coq_proof_assistant", "path": "github-repos/coq/vitorenesduarte-the_coq_proof_assistant/the_coq_proof_assistant-6aca5e1b0bba923a6b118838b1442f0876af5009/p1ex2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.736250159633007}}
{"text": "Require Import Basics.\nRequire Import Types.\nRequire Import Diagrams.Graph.\nRequire Import Diagrams.Diagram.\n\n(** We define here the Graph ∫D, also denoted G·D *)\n\nDefinition integral {G : Graph} (D : Diagram G) : Graph.\nProof.\n  serapply Build_Graph.\n  + exact {i : G & D i}.\n  + intros i j.\n    exact {g : G i.1 j.1 & D _f g i.2 = j.2}.\nDefined.\n\n(** Then, a dependent diagram E over D is just a diagram over ∫D. *)\n\nDefinition DDiagram {G : Graph} (D : Diagram G)\n  := Diagram (integral D).\n\n(** Given a dependent diagram, we c.an recover a diagram over G by considering the Σ types. *)\n\n  Definition diagram_sigma {G : Graph} {D : Diagram G} (E : DDiagram D)\n    : Diagram G.\n  Proof.\n    serapply Build_Diagram.\n    - intro i.\n      exact {x : D i & E (i; x)}.\n    - intros i j g x. simpl in *.\n      exists (D _f g x.1).\n      exact (@arr _ E (i; x.1) (j; D _f g x.1) (g; idpath) x.2).\n  Defined.\n\n  (** A dependent diagram is said equifibered if all its fibers are equivalences. *)\n\n  Class Equifibered {G : Graph} {D : Diagram G} (E : DDiagram D) := {\n    isequifibered i j (g : G i j) (x : D i)\n      :> IsEquiv (@arr _ E (i; x) (j; D _f g x) (g; idpath));\n  }.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Diagrams/DDiagram.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7362390958496309}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria.                       *)\n(* You may distribute this file under the terms of the CeCILL-B license *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq div fintype tuple.\nRequire Import finfun bigop fingroup perm ssralg zmodp matrix mxalgebra.\nRequire Import poly polydiv.\n\n(******************************************************************************)\n(*   This file provides basic support for formal computation with matrices,   *)\n(* mainly results combining matrices and univariate polynomials, such as the  *)\n(* Cayley-Hamilton theorem; it also contains an extension of the first order  *)\n(* representation of algebra introduced in ssralg (GRing.term/formula).       *)\n(*      rVpoly v == the little-endian decoding of the row vector v as a       *)\n(*                  polynomial p = \\sum_i (v 0 i)%:P * 'X^i.                  *)\n(*     poly_rV p == the partial inverse to rVpoly, for polynomials of degree  *)\n(*                  less than d to 'rV_d (d is inferred from the context).    *)\n(* Sylvester_mx p q == the Sylvester matrix of p and q.                       *)\n(* resultant p q == the resultant of p and q, i.e., \\det (Sylvester_mx p q).  *)\n(*   horner_mx A == the morphism from {poly R} to 'M_n (n of the form n'.+1)  *)\n(*                  mapping a (scalar) polynomial p to the value of its       *)\n(*                  scalar matrix interpretation at A (this is an instance of *)\n(*                  the generic horner_morph construct defined in poly).      *)\n(* powers_mx A d == the d x (n ^ 2) matrix whose rows are the mxvec encodings *)\n(*                  of the first d powers of A (n of the form n'.+1). Thus,   *)\n(*                  vec_mx (v *m powers_mx A d) = horner_mx A (rVpoly v).     *)\n(*   char_poly A == the characteristic polynomial of A.                       *)\n(* char_poly_mx A == a matrix whose detereminant is char_poly A.              *)\n(*   mxminpoly A == the minimal polynomial of A, i.e., the smallest monic     *)\n(*                  polynomial that annihilates A (A must be nontrivial).     *)\n(* degree_mxminpoly A == the (positive) degree of mxminpoly A.                *)\n(* mx_inv_horner A == the inverse of horner_mx A for polynomials of degree    *)\n(*                  smaller than degree_mxminpoly A.                          *)\n(*  integralOver RtoK u <-> u is in the integral closure of the image of R    *)\n(*                  under RtoK : R -> K, i.e. u is a root of the image of a   *)\n(*                  monic polynomial in R.                                    *)\n(*  algebraicOver FtoE u <-> u : E is algebraic over E; it is a root of the   *)\n(*                  image of a nonzero polynomial under FtoE; as F must be a  *)\n(*                  fieldType, this is equivalent to integralOver FtoE u.     *)\n(*  integralRange RtoK <-> the integral closure of the image of R contains    *)\n(*                  all of K (:= forall u, integralOver RtoK u).              *)\n(* This toolkit for building formal matrix expressions is packaged in the     *)\n(* MatrixFormula submodule, and comprises the following:                      *)\n(*     eval_mx e == GRing.eval lifted to matrices (:= map_mx (GRing.eval e)). *)\n(*     mx_term A == GRing.Const lifted to matrices.                           *)\n(* mulmx_term A B == the formal product of two matrices of terms.             *)\n(* mxrank_form m A == a GRing.formula asserting that the interpretation of    *)\n(*                  the term matrix A has rank m.                             *)\n(* submx_form A B == a GRing.formula asserting that the row space of the      *)\n(*                  interpretation of the term matrix A is included in the    *)\n(*                  row space of the interpretation of B.                     *)\n(*   seq_of_rV v == the seq corresponding to a row vector.                    *)\n(*     row_env e == the flattening of a tensored environment e : seq 'rV_d.   *)\n(* row_var F d k == the term vector of width d such that for e : seq 'rV[F]_d *)\n(*                  we have eval e 'X_k = eval_mx (row_env e) (row_var d k).  *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nImport Monoid.Theory.\n\nOpen Local Scope ring_scope.\n\nImport Pdiv.Idomain.\n(* Row vector <-> bounded degree polynomial bijection *)\nSection RowPoly.\n\nVariables (R : ringType) (d : nat).\nImplicit Types u v : 'rV[R]_d.\nImplicit Types p q : {poly R}.\n\nDefinition rVpoly v := \\poly_(k < d) (if insub k is Some i then v 0 i else 0).\nDefinition poly_rV p := \\row_(i < d) p`_i.\n\nLemma coef_rVpoly v k : (rVpoly v)`_k = if insub k is Some i then v 0 i else 0.\nProof. by rewrite coef_poly; case: insubP => [i ->|]; rewrite ?if_same. Qed.\n\nLemma coef_rVpoly_ord v (i : 'I_d) : (rVpoly v)`_i = v 0 i.\nProof. by rewrite coef_rVpoly valK. Qed.\n\nLemma rVpoly_delta i : rVpoly (delta_mx 0 i) = 'X^i.\nProof.\napply/polyP=> j; rewrite coef_rVpoly coefXn.\ncase: insubP => [k _ <- | j_ge_d]; first by rewrite mxE.\nby case: eqP j_ge_d => // ->; rewrite ltn_ord.\nQed.\n\nLemma rVpolyK : cancel rVpoly poly_rV.\nProof. by move=> u; apply/rowP=> i; rewrite mxE coef_rVpoly_ord. Qed.\n\nLemma poly_rV_K p : size p <= d -> rVpoly (poly_rV p) = p.\nProof.\nmove=> le_p_d; apply/polyP=> k; rewrite coef_rVpoly.\ncase: insubP => [i _ <- | ]; first by rewrite mxE.\nby rewrite -ltnNge => le_d_l; rewrite nth_default ?(leq_trans le_p_d).\nQed.\n\nLemma poly_rV_is_linear : linear poly_rV.\nProof. by move=> a p q; apply/rowP=> i; rewrite !mxE coefD coefZ. Qed.\nCanonical poly_rV_additive := Additive poly_rV_is_linear.\nCanonical poly_rV_linear := Linear poly_rV_is_linear.\n\nLemma rVpoly_is_linear : linear rVpoly.\nProof.\nmove=> a u v; apply/polyP=> k; rewrite coefD coefZ !coef_rVpoly.\nby case: insubP => [i _ _ | _]; rewrite ?mxE // mulr0 addr0.\nQed.\nCanonical rVpoly_additive := Additive rVpoly_is_linear.\nCanonical rVpoly_linear := Linear rVpoly_is_linear.\n\nEnd RowPoly.\n\nImplicit Arguments poly_rV [R d].\nPrenex Implicits rVpoly poly_rV.\n\nSection Resultant.\n\nVariables (R : ringType) (p q : {poly R}).\n\nLet dS := ((size q).-1 + (size p).-1)%N.\nLocal Notation band r := (lin1_mx (poly_rV \\o r \\o* rVpoly)).\n\nDefinition Sylvester_mx : 'M[R]_dS := col_mx (band p) (band q).\n\nLemma Sylvester_mxE (i j : 'I_dS) :\n  let S_ r k := r`_(j - k) *+ (k <= j) in\n  Sylvester_mx i j = match split i with inl k => S_ p k | inr k => S_ q k end.\nProof.\nmove=> S_; rewrite mxE; case: {i}(split i) => i; rewrite !mxE /=;\n  by rewrite rVpoly_delta coefXnM ltnNge if_neg -mulrb.\nQed.\n\nDefinition resultant := \\det Sylvester_mx.\n\nEnd Resultant.\n\nLemma resultant_in_ideal (R : comRingType) (p q : {poly R}) :\n    size p > 1 -> size q > 1 ->\n  {uv : {poly R} * {poly R} | size uv.1 < size q /\\ size uv.2 < size p\n  & (resultant p q)%:P = uv.1 * p + uv.2 * q}.\nProof.\nmove=> p_nc q_nc; pose dp := (size p).-1; pose dq := (size q).-1.\npose S := Sylvester_mx p q; pose dS := (dq + dp)%N.\nhave dS_gt0: dS > 0 by rewrite /dS /dq -(subnKC q_nc).\npose j0 := Ordinal dS_gt0. \npose Ss0 := col_mx (p *: \\col_(i < dq) 'X^i) (q *: \\col_(i < dp) 'X^i).\npose Ss := \\matrix_(i, j) (if j == j0 then Ss0 i 0 else (S i j)%:P).\npose u ds s := \\sum_(i < ds) cofactor Ss (s i) j0 * 'X^i.\nexists (u _ (lshift dp), u _ ((rshift dq) _)).\n  suffices sz_u ds s: ds > 1 -> size (u ds.-1 s) < ds by rewrite !sz_u.\n  move/ltn_predK=> {2}<-; apply: leq_trans (size_sum _ _ _) _.\n  apply/bigmax_leqP=> i _.\n  have ->: cofactor Ss (s i) j0 = (cofactor S (s i) j0)%:P.\n    rewrite rmorphM rmorph_sign -det_map_mx; congr (_ * \\det _).\n    by apply/matrixP=> i' j'; rewrite !mxE.\n  apply: leq_trans (size_mul_leq _ _) (leq_trans _ (valP i)).\n  by rewrite size_polyC size_polyXn addnS /= -add1n leq_add2r leq_b1.\ntransitivity (\\det Ss); last first.\n  rewrite (expand_det_col Ss j0) big_split_ord !big_distrl /=.\n  by congr (_ + _); apply: eq_bigr => i _;\n    rewrite mxE eqxx (col_mxEu, col_mxEd) !mxE mulrC mulrA mulrAC.\npose S_ j1 := map_mx polyC (\\matrix_(i, j) S i (if j == j0 then j1 else j)).\npose Ss0_ i dj := \\poly_(j < dj) S i (insubd j0 j).\npose Ss_ dj := \\matrix_(i, j) (if j == j0 then Ss0_ i dj else (S i j)%:P).\nhave{Ss u} ->: Ss = Ss_ dS.\n  apply/matrixP=> i j; rewrite mxE [in X in _ = X]mxE; case: (j == j0) => {j}//.\n  apply/polyP=> k; rewrite coef_poly Sylvester_mxE mxE.\n  have [k_ge_dS | k_lt_dS] := leqP dS k.\n    case: (split i) => {i}i; rewrite !mxE coefMXn;\n    case: ifP => // /negbT; rewrite -ltnNge ltnS => hi.\n      apply: (leq_sizeP _ _ (leqnn (size p))); rewrite -(ltn_predK p_nc).\n      by rewrite ltn_subRL (leq_trans _ k_ge_dS) // ltn_add2r.\n    - apply: (leq_sizeP _ _ (leqnn (size q))); rewrite -(ltn_predK q_nc).\n      by rewrite ltn_subRL (leq_trans _ k_ge_dS) // addnC ltn_add2l.\n  by rewrite insubdK //; case: (split i) => {i}i;\n     rewrite !mxE coefMXn; case: leqP.\nelim: {-2}dS (leqnn dS) (dS_gt0) => // dj IHj dj_lt_dS _.\npose j1 := Ordinal dj_lt_dS; pose rj0T (A : 'M[{poly R}]_dS) := row j0 A^T.\nhave: rj0T (Ss_ dj.+1) = 'X^dj *: rj0T (S_ j1) + 1 *: rj0T (Ss_ dj).\n\n  apply/rowP=> i; apply/polyP=> k; rewrite scale1r !(Sylvester_mxE, mxE) eqxx.\n\n  rewrite coefD coefXnM coefC !coef_poly ltnS subn_eq0 ltn_neqAle andbC.\n  case: (leqP k dj) => [k_le_dj | k_gt_dj] /=; last by rewrite addr0.\n  rewrite Sylvester_mxE insubdK; last exact: leq_ltn_trans (dj_lt_dS).\n  by case: eqP => [-> | _]; rewrite (addr0, add0r).\nrewrite -det_tr => /determinant_multilinear->;\n  try by apply/matrixP=> i j; rewrite !mxE eq_sym (negPf (neq_lift _ _)).\nhave [dj0 | dj_gt0] := posnP dj; rewrite ?dj0 !mul1r.\n  rewrite !det_tr det_map_mx addrC (expand_det_col _ j0) big1 => [|i _].\n    rewrite add0r; congr (\\det _)%:P.\n    apply/matrixP=> i j; rewrite [in X in _ = X]mxE; case: eqP => // ->.\n    by congr (S i _); apply: val_inj.\n  by rewrite mxE /= [Ss0_ _ _]poly_def big_ord0 mul0r.\nhave /determinant_alternate->: j1 != j0 by rewrite -val_eqE -lt0n.\n  by rewrite mulr0 add0r det_tr IHj // ltnW.\nby move=> i; rewrite !mxE if_same.\nQed.\n\nLemma resultant_eq0 (R : idomainType) (p q : {poly R}) :\n  (resultant p q == 0) = (size (gcdp p q) > 1).\nProof.\nhave dvdpp := dvdpp; set r := gcdp p q.\npose dp := (size p).-1; pose dq := (size q).-1.\nhave /andP[r_p r_q]: (r %| p) && (r %| q) by rewrite -dvdp_gcd.\napply/det0P/idP=> [[uv nz_uv] | r_nonC].\n  have [p0 _ | p_nz] := eqVneq p 0.\n    have: dq + dp > 0.\n      rewrite lt0n; apply: contraNneq nz_uv => dqp0.\n      by rewrite dqp0 in uv *; rewrite [uv]thinmx0.\n    by rewrite /dp /dq /r p0 size_poly0 addn0 gcd0p -subn1 subn_gt0.\n  do [rewrite -[uv]hsubmxK -{1}row_mx0 mul_row_col !mul_rV_lin1 /=] in nz_uv *.\n  set u := rVpoly _; set v := rVpoly _; pose m := gcdp (v * p) (v * q).\n  have lt_vp: size v < size p by rewrite (polySpred p_nz) ltnS size_poly.\n  move/(congr1 rVpoly); rewrite linearD linear0 /=; move/(canRL (addKr _)).\n  rewrite !poly_rV_K ?(leq_trans (size_mul_leq _ _)) // => [vq_up||]; first 1 last.\n  - by rewrite -subn1 leq_subLR addnCA leq_add ?leqSpred ?size_poly.\n  - by rewrite -subn1 leq_subLR addnC addnA leq_add ?leqSpred ?size_poly.\n  have nz_v: v != 0.\n    apply: contraNneq nz_uv => v0; apply/eqP.\n    congr row_mx; apply: (can_inj (@rVpolyK _ _)); rewrite linear0 // -/u.\n    move/eqP: vq_up; apply: contraTeq => nz_u.\n    by rewrite v0 mul0r addr0 eq_sym oppr_eq0 mulf_neq0.\n  have r_nz: r != 0 := dvdpN0 r_p p_nz.\n  have /dvdpP [[c w] /= nz_c wv]: v %| m by rewrite dvdp_gcd !dvdp_mulr.\n  have m_wd d: m %| v * d -> w %| d.\n    case/dvdpP=> [[k f]] /= nz_k; move/(congr1 ( *:%R c)).\n    rewrite mulrC scalerA scalerAl scalerAr wv mulrA.\n    move/(mulIf nz_v)=> def_fw; apply/dvdpP.\n    by exists (c * k, f); rewrite //= mulf_neq0.\n  have w_r: w %| r by rewrite dvdp_gcd !m_wd ?dvdp_gcdl ?dvdp_gcdr.\n  have w_nz: w != 0 := dvdpN0 w_r r_nz.\n  have p_m: p %| m by rewrite dvdp_gcd vq_up addr0 -mulNr !dvdp_mull.\n  rewrite (leq_trans _ (dvdp_leq r_nz w_r)) // -(ltn_add2l (size v)).\n  rewrite addnC -ltn_subRL subn1 -size_mul // mulrC -wv size_scale //.\n  rewrite (leq_trans lt_vp) // dvdp_leq // -size_poly_eq0.\n  by rewrite -(size_scale _ nz_c) size_poly_eq0 wv mulf_neq0.\nhave [[c p'] /= nz_c p'r] := dvdpP _ _ r_p.\nhave [[k q'] /= nz_k q'r] := dvdpP _ _ r_q.\nhave def_r := subnKC r_nonC; have r_nz: r != 0 by rewrite -size_poly_eq0 -def_r.\nhave le_p'_dp: size p' <= dp.\n  have [-> | nz_p'] := eqVneq p' 0; first by rewrite size_poly0.\n  by rewrite /dp -(size_scale p nz_c) p'r size_mul // addnC -def_r leq_addl.\nhave le_q'_dq: size q' <= dq.\n  have [-> | nz_q'] := eqVneq q' 0; first by rewrite size_poly0.\n  by rewrite /dq -(size_scale q nz_k) q'r size_mul // addnC -def_r leq_addl.\nexists (row_mx (- c *: poly_rV q') (k *: poly_rV p')).\n  apply: contraNneq r_nz; rewrite -row_mx0; case/eq_row_mx=> q0 p0.\n  have{p0} p0: p = 0.\n    apply/eqP; rewrite -size_poly_eq0 -(size_scale p nz_c) p'r.\n    rewrite -(size_scale _ nz_k) scalerAl -(poly_rV_K le_p'_dp) -linearZ p0.\n    by rewrite linear0 mul0r size_poly0.\n  rewrite /r p0 gcd0p -size_poly_eq0 -(size_scale q nz_k) q'r.\n  rewrite -(size_scale _ nz_c) scalerAl -(poly_rV_K le_q'_dq) -linearZ.\n  by rewrite -[c]opprK scaleNr q0 !linear0 mul0r size_poly0.\nrewrite mul_row_col scaleNr mulNmx !mul_rV_lin1 /= !linearZ /= !poly_rV_K //.\nby rewrite !scalerCA p'r q'r mulrCA addNr.\nQed.\n\nSection HornerMx.\n\nVariables (R : comRingType) (n' : nat).\nLocal Notation n := n'.+1.\nVariable A : 'M[R]_n.\nImplicit Types p q : {poly R}.\n\nDefinition horner_mx := horner_morph (fun a => scalar_mx_comm a A).\nCanonical horner_mx_additive := [additive of horner_mx].\nCanonical horner_mx_rmorphism := [rmorphism of horner_mx].\n\nLemma horner_mx_C a : horner_mx a%:P = a%:M.\nProof. exact: horner_morphC. Qed.\n\nLemma horner_mx_X : horner_mx 'X = A. Proof. exact: horner_morphX. Qed.\n\nLemma horner_mxZ : scalable horner_mx.\nProof.\nmove=> a p /=; rewrite -mul_polyC rmorphM /=.\nby rewrite horner_mx_C [_ * _]mul_scalar_mx.\nQed.\n\nCanonical horner_mx_linear := AddLinear horner_mxZ.\nCanonical horner_mx_lrmorphism := [lrmorphism of horner_mx].\n\nDefinition powers_mx d := \\matrix_(i < d) mxvec (A ^+ i).\n\nLemma horner_rVpoly m (u : 'rV_m) :\n  horner_mx (rVpoly u) = vec_mx (u *m powers_mx m).\nProof.\nrewrite mulmx_sum_row linear_sum [rVpoly u]poly_def rmorph_sum.\napply: eq_bigr => i _.\nby rewrite valK !linearZ rmorphX /= horner_mx_X rowK /= mxvecK.\nQed.\n\nEnd HornerMx.\n\nSection CharPoly.\n\nVariables (R : ringType) (n : nat) (A : 'M[R]_n).\nImplicit Types p q : {poly R}.\n\nDefinition char_poly_mx := 'X%:M - map_mx (@polyC R) A.\nDefinition char_poly := \\det char_poly_mx.\n\nLet diagA := [seq A i i | i : 'I_n].\nLet size_diagA : size diagA = n.\nProof. by rewrite size_image card_ord. Qed.\n\nLet split_diagA :\n  exists2 q, \\prod_(x <- diagA) ('X - x%:P) + q = char_poly & size q <= n.-1.\nProof.\nrewrite [char_poly](bigD1 1%g) //=; set q := \\sum_(s | _) _; exists q.\n  congr (_ + _); rewrite odd_perm1 mul1r big_map enumT; apply: eq_bigr => i _.\n  by rewrite !mxE perm1 eqxx.\napply: leq_trans {q}(size_sum _ _ _) _; apply/bigmax_leqP=> s nt_s.\nhave{nt_s} [i nfix_i]: exists i, s i != i.\n  apply/existsP; rewrite -negb_forall; apply: contra nt_s => s_1.\n  by apply/eqP; apply/permP=> i; apply/eqP; rewrite perm1 (forallP s_1).\napply: leq_trans (_ : #|[pred j | s j == j]|.+1 <= n.-1).\n  rewrite -sum1_card (@big_mkcond nat) /= size_Msign.\n  apply: (big_ind2 (fun p m => size p <= m.+1)) => [| p mp q mq IHp IHq | j _].\n  - by rewrite size_poly1.\n  - apply: leq_trans (size_mul_leq _ _) _.\n    by rewrite -subn1 -addnS leq_subLR addnA leq_add.\n  rewrite !mxE eq_sym !inE; case: (s j == j); first by rewrite polyseqXsubC. \n  by rewrite sub0r size_opp size_polyC leq_b1.\nrewrite -{8}[n]card_ord -(cardC (pred2 (s i) i)) card2 nfix_i !ltnS.\napply: subset_leq_card; apply/subsetP=> j; move/(_ =P j)=> fix_j.\nrewrite !inE -{1}fix_j (inj_eq (@perm_inj _ s)) orbb.\nby apply: contraNneq nfix_i => <-; rewrite fix_j.\nQed.   \n\nLemma size_char_poly : size char_poly = n.+1.\nProof.\nhave [q <- lt_q_n] := split_diagA; have le_q_n := leq_trans lt_q_n (leq_pred n).\nby rewrite size_addl size_prod_XsubC size_diagA.\nQed.\n\nLemma char_poly_monic : char_poly \\is monic.\nProof.\nrewrite monicE -(monicP (monic_prod_XsubC diagA xpredT id)).\nrewrite !lead_coefE size_char_poly.\nhave [q <- lt_q_n] := split_diagA; have le_q_n := leq_trans lt_q_n (leq_pred n).\nby rewrite size_prod_XsubC size_diagA coefD (nth_default 0 le_q_n) addr0.\nQed.\n\nLemma char_poly_trace : n > 0 -> char_poly`_n.-1 = - \\tr A.\nProof.\nmove=> n_gt0; have [q <- lt_q_n] := split_diagA; set p := \\prod_(x <- _) _.\nrewrite coefD {q lt_q_n}(nth_default 0 lt_q_n) addr0.\nhave{n_gt0} ->: p`_n.-1 = ('X * p)`_n by rewrite coefXM eqn0Ngt n_gt0.\nhave ->: \\tr A = \\sum_(x <- diagA) x by rewrite big_map enumT.\nrewrite -size_diagA {}/p; elim: diagA => [|x d IHd].\n  by rewrite !big_nil mulr1 coefX oppr0.\nrewrite !big_cons coefXM mulrBl coefB IHd opprD addrC; congr (- _ + _).\nrewrite mul_polyC coefZ [size _]/= -(size_prod_XsubC _ id) -lead_coefE. \nby rewrite (monicP _) ?monic_prod_XsubC ?mulr1.\nQed.\n\nLemma char_poly_det : char_poly`_0 = (- 1) ^+ n * \\det A.\nProof.\nrewrite big_distrr coef_sum [0%N]lock /=; apply: eq_bigr => s _.\nrewrite -{1}rmorphN -rmorphX mul_polyC coefZ /=.\nrewrite mulrA -exprD addnC exprD -mulrA -lock; congr (_ * _).\ntransitivity (\\prod_(i < n) - A i (s i)); last by rewrite prodrN card_ord.\nelim: (index_enum _) => [|i e IHe]; rewrite !(big_nil, big_cons) ?coef1 //.\nby rewrite coefM big_ord1 IHe !mxE coefB coefC coefMn coefX mul0rn sub0r.\nQed.\n\nEnd CharPoly.\n\nLemma mx_poly_ring_isom (R : ringType) n' (n := n'.+1) :\n  exists phi : {rmorphism 'M[{poly R}]_n -> {poly 'M[R]_n}},\n  [/\\ bijective phi,\n      forall p, phi p%:M = map_poly scalar_mx p,\n      forall A, phi (map_mx polyC A) = A%:P\n    & forall A i j k, (phi A)`_k i j = (A i j)`_k].\nProof.\nset M_RX := 'M[{poly R}]_n; set MR_X := ({poly 'M[R]_n}).\npose Msize (A : M_RX) := \\max_i \\max_j size (A i j).\npose phi (A : M_RX) := \\poly_(k < Msize A) \\matrix_(i, j) (A i j)`_k.\nhave coef_phi A i j k: (phi A)`_k i j = (A i j)`_k.\n  rewrite coef_poly; case: (ltnP k _) => le_m_k; rewrite mxE // nth_default //.\n  apply: leq_trans (leq_trans (leq_bigmax i) le_m_k); exact: (leq_bigmax j).\nhave phi_is_rmorphism : rmorphism phi.\n  do 2?[split=> [A B|]]; apply/polyP=> k; apply/matrixP=> i j; last 1 first.\n  - rewrite coef_phi mxE coefMn !coefC.\n    by case: (k == _); rewrite ?mxE ?mul0rn.\n  - by rewrite !(coef_phi, mxE, coefD, coefN).\n  rewrite !coef_phi !mxE !coefM summxE coef_sum.\n  pose F k1 k2 := (A i k1)`_k2 * (B k1 j)`_(k - k2).\n  transitivity (\\sum_k1 \\sum_(k2 < k.+1) F k1 k2); rewrite {}/F.\n    by apply: eq_bigr=> k1 _; rewrite coefM.\n  rewrite exchange_big /=; apply: eq_bigr => k2 _.\n  by rewrite mxE; apply: eq_bigr => k1 _; rewrite !coef_phi.\nhave bij_phi: bijective phi.\n  exists (fun P : MR_X => \\matrix_(i, j) \\poly_(k < size P) P`_k i j) => [A|P].\n    apply/matrixP=> i j; rewrite mxE; apply/polyP=> k.\n    rewrite coef_poly -coef_phi.\n    by case: leqP => // P_le_k; rewrite nth_default ?mxE.\n  apply/polyP=> k; apply/matrixP=> i j; rewrite coef_phi mxE coef_poly.\n  by case: leqP => // P_le_k; rewrite nth_default ?mxE.\nexists (RMorphism phi_is_rmorphism).\nsplit=> // [p | A]; apply/polyP=> k; apply/matrixP=> i j.\n  by rewrite coef_phi coef_map !mxE coefMn.\nby rewrite coef_phi !mxE !coefC; case k; last rewrite /= mxE.\nQed.\n\nTheorem Cayley_Hamilton (R : comRingType) n' (A : 'M[R]_n'.+1) :\n  horner_mx A (char_poly A) = 0.\nProof.\nhave [phi [_ phiZ phiC _]] := mx_poly_ring_isom R n'.\napply/rootP/factor_theorem; rewrite -phiZ -mul_adj_mx rmorphM.\nby move: (phi _) => q; exists q; rewrite rmorphB phiC phiZ map_polyX.\nQed.\n\nLemma eigenvalue_root_char (F : fieldType) n (A : 'M[F]_n) a :\n  eigenvalue A a = root (char_poly A) a.\nProof.\ntransitivity (\\det (a%:M - A) == 0).\n  apply/eigenvalueP/det0P=> [[v Av_av v_nz] | [v v_nz Av_av]]; exists v => //.\n    by rewrite mulmxBr Av_av mul_mx_scalar subrr.\n  by apply/eqP; rewrite -mul_mx_scalar eq_sym -subr_eq0 -mulmxBr Av_av.\ncongr (_ == 0); rewrite horner_sum; apply: eq_bigr => s _.\nrewrite hornerM horner_exp !hornerE; congr (_ * _).\nrewrite (big_morph _ (fun p q => hornerM p q a) (hornerC 1 a)).\nby apply: eq_bigr => i _; rewrite !mxE !(hornerE, hornerMn).\nQed.\n\nSection MinPoly.\n\nVariables (F : fieldType) (n' : nat).\nLocal Notation n := n'.+1.\nVariable A : 'M[F]_n.\nImplicit Types p q : {poly F}.\n\nFact degree_mxminpoly_proof : exists d, \\rank (powers_mx A d.+1) <= d.\nProof. by exists (n ^ 2)%N; rewrite rank_leq_col. Qed.\nDefinition degree_mxminpoly := ex_minn degree_mxminpoly_proof.\nLocal Notation d := degree_mxminpoly.\nLocal Notation Ad := (powers_mx A d).\n\nLemma mxminpoly_nonconstant : d > 0.\nProof.\nrewrite /d; case: ex_minnP; case=> //; rewrite leqn0 mxrank_eq0; move/eqP.\nmove/row_matrixP; move/(_ 0); move/eqP; rewrite rowK row0 mxvec_eq0.\nby rewrite -mxrank_eq0 mxrank1.\nQed.\n\nLemma minpoly_mx1 : (1%:M \\in Ad)%MS.\nProof.\nby apply: (eq_row_sub (Ordinal mxminpoly_nonconstant)); rewrite rowK.\nQed.\n\nLemma minpoly_mx_free : row_free Ad.\nProof.\nhave:= mxminpoly_nonconstant; rewrite /d; case: ex_minnP; case=> // d' _.\nmove/(_ d'); move/implyP; rewrite ltnn implybF -ltnS ltn_neqAle.\nby rewrite rank_leq_row andbT negbK.\nQed.\n\nLemma horner_mx_mem p : (horner_mx A p \\in Ad)%MS.\nProof.\nelim/poly_ind: p => [|p a IHp]; first by rewrite rmorph0 // linear0 sub0mx.\nrewrite rmorphD rmorphM /= horner_mx_C horner_mx_X.\nrewrite addrC -scalemx1 linearP /= -(mul_vec_lin (mulmxr_linear _ A)).\ncase/submxP: IHp => u ->{p}.\nhave: (powers_mx A (1 + d) <= Ad)%MS.\n  rewrite -(geq_leqif (mxrank_leqif_sup _)).\n    by rewrite (eqnP minpoly_mx_free) /d; case: ex_minnP.\n  rewrite addnC; apply/row_subP=> i.\n  by apply: eq_row_sub (lshift 1 i) _; rewrite !rowK.\napply: submx_trans; rewrite addmx_sub ?scalemx_sub //.\n  by apply: (eq_row_sub 0); rewrite rowK.\nrewrite -mulmxA mulmx_sub {u}//; apply/row_subP=> i.\nrewrite row_mul rowK mul_vec_lin /= mulmxE -exprSr.\nby apply: (eq_row_sub (rshift 1 i)); rewrite rowK.\nQed.\n\nDefinition mx_inv_horner B := rVpoly (mxvec B *m pinvmx Ad).\n\nLemma mx_inv_horner0 :  mx_inv_horner 0 = 0.\nProof. by rewrite /mx_inv_horner !(linear0, mul0mx). Qed.\n\nLemma mx_inv_hornerK B : (B \\in Ad)%MS -> horner_mx A (mx_inv_horner B) = B.\nProof. by move=> sBAd; rewrite horner_rVpoly mulmxKpV ?mxvecK. Qed.\n\nLemma minpoly_mxM B C : (B \\in Ad -> C \\in Ad -> B * C \\in Ad)%MS.\nProof.\nmove=> AdB AdC; rewrite -(mx_inv_hornerK AdB) -(mx_inv_hornerK AdC).\nby rewrite -rmorphM ?horner_mx_mem.\nQed.\n\nLemma minpoly_mx_ring : mxring Ad.\nProof.\napply/andP; split; first by apply/mulsmx_subP; exact: minpoly_mxM.\napply/mxring_idP; exists 1%:M; split=> *; rewrite ?mulmx1 ?mul1mx //.\n  by rewrite -mxrank_eq0 mxrank1.\nexact: minpoly_mx1.\nQed.\n\nDefinition mxminpoly := 'X^d - mx_inv_horner (A ^+ d).\nLocal Notation p_A := mxminpoly.\n\nLemma size_mxminpoly : size p_A = d.+1.\nProof. by rewrite size_addl ?size_polyXn // size_opp ltnS size_poly. Qed.\n\nLemma mxminpoly_monic : p_A \\is monic.\nProof.\nrewrite monicE /lead_coef size_mxminpoly coefB coefXn eqxx /=.\nby rewrite nth_default ?size_poly // subr0.\nQed.\n\nLemma size_mod_mxminpoly p : size (p %% p_A) <= d.\nProof.\nby rewrite -ltnS -size_mxminpoly ltn_modp // -size_poly_eq0 size_mxminpoly.\nQed.\n\nLemma mx_root_minpoly : horner_mx A p_A = 0.\nProof.\nrewrite rmorphB -{3}(horner_mx_X A) -rmorphX /=.\nby rewrite mx_inv_hornerK ?subrr ?horner_mx_mem.\nQed.\n\nLemma horner_rVpolyK (u : 'rV_d) :\n  mx_inv_horner (horner_mx A (rVpoly u)) = rVpoly u.\nProof.\ncongr rVpoly; rewrite horner_rVpoly vec_mxK.\nby apply: (row_free_inj minpoly_mx_free); rewrite mulmxKpV ?submxMl.\nQed.\n\nLemma horner_mxK p : mx_inv_horner (horner_mx A p) = p %% p_A.\nProof.\nrewrite {1}(Pdiv.IdomainMonic.divp_eq mxminpoly_monic p) rmorphD rmorphM /=.\nrewrite mx_root_minpoly mulr0 add0r.\nby rewrite -(poly_rV_K (size_mod_mxminpoly _)) horner_rVpolyK.\nQed.\n\nLemma mxminpoly_min p : horner_mx A p = 0 -> p_A %| p.\nProof. by move=> pA0; rewrite /dvdp -horner_mxK pA0 mx_inv_horner0. Qed.\n\nLemma horner_rVpoly_inj : @injective 'M_n 'rV_d (horner_mx A \\o rVpoly).\nProof.\napply: can_inj (poly_rV \\o mx_inv_horner) _ => u.\nby rewrite /= horner_rVpolyK rVpolyK.\nQed.\n\nLemma mxminpoly_linear_is_scalar : (d <= 1) = is_scalar_mx A.\nProof.\nhave scalP := has_non_scalar_mxP minpoly_mx1.\nrewrite leqNgt -(eqnP minpoly_mx_free); apply/scalP/idP=> [|[[B]]].\n  case scalA: (is_scalar_mx A); [by right | left].\n  by exists A; rewrite ?scalA // -{1}(horner_mx_X A) horner_mx_mem.\nmove/mx_inv_hornerK=> <- nsB; case/is_scalar_mxP=> a defA; case/negP: nsB.\nmove: {B}(_ B); apply: poly_ind => [|p c].\n  by rewrite rmorph0 ?mx0_is_scalar.\nrewrite rmorphD ?rmorphM /= horner_mx_X defA; case/is_scalar_mxP=> b ->.\nby rewrite -rmorphM horner_mx_C -rmorphD /= scalar_mx_is_scalar.\nQed.\n\nLemma mxminpoly_dvd_char : p_A %| char_poly A.\nProof. by apply: mxminpoly_min; exact: Cayley_Hamilton. Qed.\n\nLemma eigenvalue_root_min a : eigenvalue A a = root p_A a.\nProof.\napply/idP/idP=> Aa; last first.\n  rewrite eigenvalue_root_char !root_factor_theorem in Aa *.\n  exact: dvdp_trans Aa mxminpoly_dvd_char.\nhave{Aa} [v Av_av v_nz] := eigenvalueP Aa.\napply: contraR v_nz => pa_nz; rewrite -{pa_nz}(eqmx_eq0 (eqmx_scale _ pa_nz)).\napply/eqP; rewrite -(mulmx0 _ v) -mx_root_minpoly.\nelim/poly_ind: p_A => [|p c IHp].\n  by rewrite rmorph0 horner0 scale0r mulmx0.\nrewrite !hornerE rmorphD rmorphM /= horner_mx_X horner_mx_C scalerDl.\nby rewrite -scalerA mulmxDr mul_mx_scalar mulmxA -IHp -scalemxAl Av_av.\nQed.\n\nEnd MinPoly.\n\n(* Parametricity. *)\nSection MapRingMatrix.\n\nVariables (aR rR : ringType) (f : {rmorphism aR -> rR}).\nLocal Notation \"A ^f\" := (map_mx (GRing.RMorphism.apply f) A) : ring_scope.\nLocal Notation fp := (map_poly (GRing.RMorphism.apply f)).\nVariables (d n : nat) (A : 'M[aR]_n).\n\nLemma map_rVpoly (u : 'rV_d) : fp (rVpoly u) = rVpoly u^f.\nProof.\napply/polyP=> k; rewrite coef_map !coef_rVpoly.\nby case: (insub k) => [i|]; rewrite  /=  ?rmorph0 // mxE.\nQed.\n\nLemma map_poly_rV p : (poly_rV p)^f = poly_rV (fp p) :> 'rV_d.\nProof. by apply/rowP=> j; rewrite !mxE coef_map. Qed.\n\nLemma map_char_poly_mx : map_mx fp (char_poly_mx A) = char_poly_mx A^f.\nProof.\nrewrite raddfB /= map_scalar_mx /= map_polyX; congr (_ - _).\nby apply/matrixP=> i j; rewrite !mxE map_polyC.\nQed.\n\nLemma map_char_poly : fp (char_poly A) = char_poly A^f.\nProof. by rewrite -det_map_mx map_char_poly_mx. Qed.\n\nEnd MapRingMatrix.\n\nSection MapResultant.\n\nLemma map_resultant (aR rR : ringType) (f : {rmorphism {poly aR} -> rR}) p q :\n    f (lead_coef p) != 0 -> f (lead_coef q) != 0 ->\n  f (resultant p q)= resultant (map_poly f p) (map_poly f q).\nProof.\nmove=> nz_fp nz_fq; rewrite /resultant /Sylvester_mx !size_map_poly_id0 //.\nrewrite -det_map_mx /= map_col_mx; congr (\\det (col_mx _ _));\n  by apply: map_lin1_mx => v; rewrite map_poly_rV rmorphM /= map_rVpoly.\nQed.\n\nEnd MapResultant.\n\nSection MapComRing.\n\nVariables (aR rR : comRingType) (f : {rmorphism aR -> rR}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\nLocal Notation fp := (map_poly f).\nVariables (n' : nat) (A : 'M[aR]_n'.+1).\n\nLemma map_powers_mx e : (powers_mx A e)^f = powers_mx A^f e.\nProof. by apply/row_matrixP=> i; rewrite -map_row !rowK map_mxvec rmorphX. Qed.\n\nLemma map_horner_mx p : (horner_mx A p)^f = horner_mx A^f (fp p).\nProof.\nrewrite -[p](poly_rV_K (leqnn _)) map_rVpoly.\nby rewrite !horner_rVpoly map_vec_mx map_mxM map_powers_mx.\nQed.\n\nEnd MapComRing.\n\nSection MapField.\n\nVariables (aF rF : fieldType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\nLocal Notation fp := (map_poly f).\nVariables (n' : nat) (A : 'M[aF]_n'.+1).\n\nLemma degree_mxminpoly_map : degree_mxminpoly A^f = degree_mxminpoly A.\nProof. by apply: eq_ex_minn => e; rewrite -map_powers_mx mxrank_map. Qed.\n\nLemma mxminpoly_map : mxminpoly A^f = fp (mxminpoly A).\nProof.\nrewrite rmorphB; congr (_ - _).\n  by rewrite /= map_polyXn degree_mxminpoly_map.\nrewrite degree_mxminpoly_map -rmorphX /=.\napply/polyP=> i; rewrite coef_map //= !coef_rVpoly degree_mxminpoly_map.\ncase/insub: i => [i|]; last by rewrite rmorph0.\nby rewrite -map_powers_mx -map_pinvmx // -map_mxvec -map_mxM // mxE.\nQed.\n\nLemma map_mx_inv_horner u : fp (mx_inv_horner A u) = mx_inv_horner A^f u^f.\nProof.\nrewrite map_rVpoly map_mxM map_mxvec map_pinvmx map_powers_mx.\nby rewrite /mx_inv_horner degree_mxminpoly_map.\nQed.\n\nEnd MapField.\n\nSection IntegralOverRing.\n\nDefinition integralOver (R K : ringType) (RtoK : R -> K) (z : K) :=\n  exists2 p, p \\is monic & root (map_poly RtoK p) z.\n\nDefinition integralRange R K RtoK := forall z, @integralOver R K RtoK z.\n\nVariables (B R K : ringType) (BtoR : B -> R) (RtoK : {rmorphism R -> K}).\n\nLemma integral_rmorph x :\n  integralOver BtoR x -> integralOver (RtoK \\o BtoR) (RtoK x).\nProof. by case=> p; exists p; rewrite // map_poly_comp rmorph_root. Qed.\n\nLemma integral_id x : integralOver RtoK (RtoK x).\nProof. by exists ('X - x%:P); rewrite ?monicXsubC ?rmorph_root ?root_XsubC. Qed.\n\nLemma integral_nat n : integralOver RtoK n%:R.\nProof. by rewrite -(rmorph_nat RtoK); apply: integral_id. Qed.\n\nLemma integral0 : integralOver RtoK 0. Proof. exact: (integral_nat 0). Qed.\n\nLemma integral1 : integralOver RtoK 1. Proof. exact: (integral_nat 1). Qed.\n\nLemma integral_poly (p : {poly K}) :\n  (forall i, integralOver RtoK p`_i) <-> {in p : seq K, integralRange RtoK}.\nProof.\nsplit=> intRp => [_ /(nthP 0)[i _ <-] // | i]; rewrite -[p]coefK coef_poly.\nby case: ifP => [ltip | _]; [apply/intRp/mem_nth | apply: integral0].\nQed.\n\nEnd IntegralOverRing.\n\nSection IntegralOverComRing.\n\nVariables (R K : comRingType) (RtoK : {rmorphism R -> K}).\n\nLemma integral_horner_root w (p q : {poly K}) :\n    p \\is monic -> root p w ->\n    {in p : seq K, integralRange RtoK} -> {in q : seq K, integralRange RtoK} ->\n  integralOver RtoK q.[w].\nProof.\nmove=> mon_p pw0 intRp intRq.\npose memR y := exists x, y = RtoK x.\nhave memRid x: memR (RtoK x) by exists x.\nhave memR_nat n: memR n%:R by rewrite -(rmorph_nat RtoK).\nhave [memR0 memR1]: memR 0 * memR 1 := (memR_nat 0%N, memR_nat 1%N).\nhave memRN1: memR (- 1) by exists (- 1); rewrite rmorphN1.\npose rVin (E : K -> Prop) n (a : 'rV[K]_n) := forall i, E (a 0 i).\npose pXin (E : K -> Prop) (r : {poly K}) := forall i, E r`_i.\npose memM E n (X : 'rV_n) y := exists a, rVin E n a /\\ y = (a *m X^T) 0 0.\npose finM E S := exists n, exists X, forall y, memM E n X y <-> S y.\nhave tensorM E n1 n2 X Y: finM E (memM (memM E n2 Y) n1 X).\n  exists (n1 * n2)%N, (mxvec (X^T *m Y)) => y.\n  split=> [[a [Ea Dy]] | [a1 [/fin_all_exists[a /all_and2[Ea Da1]] ->]]].\n    exists (Y *m (vec_mx a)^T); split=> [i|].\n      exists (row i (vec_mx a)); split=> [j|]; first by rewrite !mxE; apply: Ea.\n      by rewrite -row_mul -{1}[Y]trmxK -trmx_mul !mxE.\n    by rewrite -[Y]trmxK -!trmx_mul mulmxA -mxvec_dotmul trmx_mul trmxK vec_mxK.\n  exists (mxvec (\\matrix_i a i)); split.\n    by case/mxvec_indexP=> i j; rewrite mxvecE mxE; apply: Ea.\n  rewrite -[mxvec _]trmxK -trmx_mul mxvec_dotmul -mulmxA trmx_mul !mxE.\n  apply: eq_bigr => i _; rewrite Da1 !mxE; congr (_ * _).\n  by apply: eq_bigr => j _; rewrite !mxE.\nsuffices [m [X [[u [_ Du]] idealM]]]: exists m,\n  exists X, let M := memM memR m X in M 1 /\\ forall y, M y -> M (q.[w] * y).\n- do [set M := memM _ m X; move: q.[w] => z] in idealM *.\n  have MX i: M (X 0 i).\n    by exists (delta_mx 0 i); split=> [j|]; rewrite -?rowE !mxE.\n  have /fin_all_exists[a /all_and2[Fa Da1]] i := idealM _ (MX i).\n  have /fin_all_exists[r Dr] i := fin_all_exists (Fa i).\n  pose A := \\matrix_(i, j) r j i; pose B := z%:M - map_mx RtoK A.\n  have XB0: X *m B = 0.\n    apply/eqP; rewrite mulmxBr mul_mx_scalar subr_eq0; apply/eqP/rowP=> i.\n    by rewrite !mxE Da1 mxE; apply: eq_bigr=> j _; rewrite !mxE mulrC Dr.\n  exists (char_poly A); first exact: char_poly_monic.\n  have: (\\det B *: (u *m X^T)) 0 0 == 0.\n    rewrite scalemxAr -linearZ -mul_mx_scalar -mul_mx_adj mulmxA XB0 /=.\n    by rewrite mul0mx trmx0 mulmx0 mxE.\n  rewrite mxE -Du mulr1 rootE -horner_evalE -!det_map_mx; congr (\\det _ == 0).\n  rewrite !raddfB /= !map_scalar_mx /= map_polyX horner_evalE hornerX.\n  by apply/matrixP=> i j; rewrite !mxE map_polyC /horner_eval hornerC.\npose gen1 x E y := exists2 r, pXin E r & y = r.[x]; pose gen := foldr gen1 memR.\nhave gen1S (E : K -> Prop) x y: E 0 -> E y -> gen1 x E y.\n  by exists y%:P => [i|]; rewrite ?hornerC ?coefC //; case: ifP.\nhave genR S y: memR y -> gen S y.\n  by elim: S => //= x S IH in y * => /IH; apply: gen1S; apply: IH.\nhave gen0 := genR _ 0 memR0; have gen_1 := genR _ 1 memR1.\nhave{gen1S} genS S y: y \\in S -> gen S y.\n  elim: S => //= x S IH /predU1P[-> | /IH//]; last exact: gen1S.\n  by exists 'X => [i|]; rewrite ?hornerX // coefX; apply: genR.\npose propD (R : K -> Prop) := forall x y, R x -> R y -> R (x + y).\nhave memRD: propD memR.\n  by move=> _ _ [a ->] [b ->]; exists (a + b); rewrite rmorphD.\nhave genD S: propD (gen S).\n  elim: S => //= x S IH _ _ [r1 Sr1 ->] [r2 Sr2 ->]; rewrite -hornerD.\n  by exists (r1 + r2) => // i; rewrite coefD; apply: IH.\nhave gen_sum S := big_ind _ (gen0 S) (genD S).\npose propM (R : K -> Prop) := forall x y, R x -> R y -> R (x * y).\nhave memRM: propM memR.\n  by move=> _ _ [a ->] [b ->]; exists (a * b); rewrite rmorphM.\nhave genM S: propM (gen S).\n  elim: S => //= x S IH _ _ [r1 Sr1 ->] [r2 Sr2 ->]; rewrite -hornerM.\n  by exists (r1 * r2) => // i; rewrite coefM; apply: gen_sum => j _; apply: IH.\nhave gen_horner S r y: pXin (gen S) r -> gen S y -> gen S r.[y].\n  move=> Sq Sy; rewrite horner_coef; apply: gen_sum => [[i _] /= _].\n  by elim: {2}i => [|n IHn]; rewrite ?mulr1 // exprSr mulrA; apply: genM.\npose S := w :: q ++ p; suffices [m [X defX]]: finM memR (gen S).\n  exists m, X => M; split=> [|y /defX Xy]; first exact/defX.\n  apply/defX/genM => //; apply: gen_horner => // [i|]; last exact/genS/mem_head.\n  rewrite -[q]coefK coef_poly; case: ifP => // lt_i_q.\n  by apply: genS; rewrite inE mem_cat mem_nth ?orbT.\npose intR R y := exists r, [/\\ r \\is monic, root r y & pXin R r].\npose fix genI s := if s is y :: s1 then intR (gen s1) y /\\ genI s1 else True.\nhave{mon_p pw0 intRp intRq}: genI S.\n  split; set S1 := _ ++ _; first exists p.\n    split=> // i; rewrite -[p]coefK coef_poly; case: ifP => // lt_i_p.\n    by apply: genS; rewrite mem_cat orbC mem_nth.\n  have: all (mem S1) S1 by exact/allP.\n  elim: {-1}S1 => //= y S2 IH /andP[S1y S12]; split; last exact: IH.\n  have{q S S1 IH S1y S12 intRp intRq} [q mon_q qx0]: integralOver RtoK y.\n    by move: S1y; rewrite mem_cat => /orP[]; [apply: intRq | apply: intRp].\n  exists (map_poly RtoK q); split=> // [|i]; first exact: monic_map.\n  by rewrite coef_map /=; apply: genR.\nelim: {w p q}S => /= [_|x S IH [[p [mon_p px0 Sp]] /IH{IH}[m2 [X2 defS]]]].\n  exists 1%N, 1 => y; split=> [[a [Fa ->]] | Fy].\n    by rewrite tr_scalar_mx mulmx1; apply: Fa.\n  by exists y%:M; split=> [i|]; rewrite 1?ord1 ?tr_scalar_mx ?mulmx1 mxE.\npose m1 := (size p).-1; pose X1 := \\row_(i < m1) x ^+ i.\nhave [m [X defM]] := tensorM memR m1 m2 X1 X2; set M := memM _ _ _ in defM.\nexists m, X => y; rewrite -/M; split=> [/defM[a [M2a]] | [q Sq]] -> {y}.\n  exists (rVpoly a) => [i|].\n    by rewrite coef_rVpoly; case/insub: i => // i; apply/defS/M2a.\n  rewrite mxE (horner_coef_wide _ (size_poly _ _)) -/(rVpoly a).\n  by apply: eq_bigr => i _; rewrite coef_rVpoly_ord !mxE.\nhave M_0: M 0 by exists 0; split=> [i|]; rewrite ?mul0mx mxE.\nhave M_D: propD M.\n  move=> _ _ [a [Fa ->]] [b [Fb ->]]; exists (a + b).\n  by rewrite mulmxDl !mxE; split=> // i; rewrite mxE; apply: memRD.\nhave{M_0 M_D} Msum := big_ind _ M_0 M_D.\nrewrite horner_coef; apply: (Msum) => i _; case: i q`_i {Sq}(Sq i) => /=.\nelim: {q}(size q) => // n IHn i i_le_n y Sy.\nhave [i_lt_m1 | m1_le_i] := ltnP i m1.\n  apply/defM; exists (y *: delta_mx 0 (Ordinal i_lt_m1)); split=> [j|].\n    by apply/defS; rewrite !mxE /= mulr_natr; case: eqP.\n  by rewrite -scalemxAl -rowE !mxE.\nrewrite -(subnK m1_le_i) exprD -[x ^+ m1]subr0 -(rootP px0) horner_coef.\nrewrite polySpred ?monic_neq0 // -/m1 big_ord_recr /= -lead_coefE.\nrewrite opprD addrC (monicP mon_p) mul1r subrK !mulrN -mulNr !mulr_sumr.\napply: Msum => j _; rewrite mulrA mulrACA -exprD; apply: IHn.\n  by rewrite -addnS addnC addnBA // leq_subLR leq_add.\nby rewrite -mulN1r; do 2!apply: (genM) => //; apply: genR. \nQed.\n\nLemma integral_root_monic u p :\n    p \\is monic -> root p u -> {in p : seq K, integralRange RtoK} -> \n  integralOver RtoK u.\nProof.\nmove=> mon_p pu0 intRp; rewrite -[u]hornerX.\napply: integral_horner_root mon_p pu0 intRp _.\nby apply/integral_poly => i; rewrite coefX; apply: integral_nat.\nQed.\n\nHint Resolve (integral0 RtoK) (integral1 RtoK) (@monicXsubC K).\n\nLet XsubC0 (u : K) : root ('X - u%:P) u. Proof. by rewrite root_XsubC. Qed.\nLet intR_XsubC u :\n  integralOver RtoK (- u) -> {in 'X - u%:P : seq K, integralRange RtoK}.\nProof. by move=> intRu v; rewrite polyseqXsubC !inE => /pred2P[]->. Qed.\n\nLemma integral_opp u : integralOver RtoK u -> integralOver RtoK (- u).\nProof. by rewrite -{1}[u]opprK => /intR_XsubC/integral_root_monic; apply. Qed.\n\nLemma integral_horner (p : {poly K}) u :\n    {in p : seq K, integralRange RtoK} -> integralOver RtoK u -> \n  integralOver RtoK p.[u].\nProof. by move=> ? /integral_opp/intR_XsubC/integral_horner_root; apply. Qed.\n\nLemma integral_sub u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u - v).\nProof.\nmove=> intRu /integral_opp/intR_XsubC/integral_horner/(_ intRu).\nby rewrite !hornerE.\nQed.\n\nLemma integral_add u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u + v).\nProof. by rewrite -{2}[v]opprK => intRu /integral_opp; apply: integral_sub. Qed.\n\nLemma integral_mul u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u * v).\nProof.\nrewrite -{2}[v]hornerX -hornerZ => intRu; apply: integral_horner.\nby apply/integral_poly=> i; rewrite coefZ coefX mulr_natr mulrb; case: ifP.\nQed.\n\nEnd IntegralOverComRing.\n\nSection IntegralOverField.\n\nVariables (F E : fieldType) (FtoE : {rmorphism F -> E}).\n\nDefinition algebraicOver (fFtoE : F -> E) u :=\n  exists2 p, p != 0 & root (map_poly fFtoE p) u.\n\nNotation mk_mon p := ((lead_coef p)^-1 *: p).\n\nLemma integral_algebraic u : algebraicOver FtoE u <-> integralOver FtoE u.\nProof.\nsplit=> [] [p p_nz pu0]; last by exists p; rewrite ?monic_neq0.\nexists (mk_mon p); first by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0.\nby rewrite linearZ rootE hornerZ (rootP pu0) mulr0.\nQed.\n\nLemma integral_inv u : integralOver FtoE u -> integralOver FtoE u^-1.\nProof.\nhave [-> | /expf_neq0 nz_u_n] := eqVneq u 0; first by rewrite invr0.\ncase/integral_algebraic=> p nz_p pu0; apply/integral_algebraic.\nexists (Poly (rev p)).\n  apply/eqP=> /polyP/(_ 0%N); rewrite coef_Poly coef0 nth_rev ?size_poly_gt0 //.\n  by apply/eqP; rewrite subn1 lead_coef_eq0.\napply/eqP/(mulfI (nz_u_n (size p).-1)); rewrite mulr0 -(rootP pu0).\nrewrite (@horner_coef_wide _ (size p)); last first.\n  by rewrite size_map_poly -(size_rev p) size_Poly.\nrewrite horner_coef mulr_sumr size_map_poly.\nrewrite [rhs in _ = rhs](reindex_inj rev_ord_inj) /=.\napply: eq_bigr => i _; rewrite !coef_map coef_Poly nth_rev // mulrCA.\nby congr (_ * _); rewrite -{1}(subnKC (valP i)) addSn addnC exprD exprVn ?mulfK.\nQed.\n\nLemma integral_div u v :\n  integralOver FtoE u -> integralOver FtoE v -> integralOver FtoE (u / v).\nProof. by move=> algFu /integral_inv; apply: integral_mul. Qed.\n\nLemma integral_root p u :\n    p != 0 -> root p u -> {in p : seq E, integralRange FtoE} ->\n  integralOver FtoE u.\nProof.\nmove=> nz_p pu0 algFp.\nhave mon_p1: mk_mon p \\is monic.\n  by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0.\nhave p1u0: root (mk_mon p) u by rewrite rootE hornerZ (rootP pu0) mulr0.\napply: integral_root_monic mon_p1 p1u0 _ => _ /(nthP 0)[i ltip <-].\nrewrite coefZ mulrC; rewrite size_scale ?invr_eq0 ?lead_coef_eq0 // in ltip.\nby apply: integral_div; apply/algFp/mem_nth; rewrite -?polySpred.\nQed.\n\nEnd IntegralOverField.\n\n(* Lifting term, formula, envs and eval to matrices. Wlog, and for the sake  *)\n(* of simplicity, we only lift (tensor) envs to row vectors; we can always   *)\n(* use mxvec/vec_mx to store and retrieve matrices.                          *)\n(* We don't provide definitions for addition, substraction, scaling, etc,    *)\n(* because they have simple matrix expressions.                              *)\nModule MatrixFormula.\n\nSection MatrixFormula.\n\nVariable F : fieldType.\n\nLocal Notation False := GRing.False.\nLocal Notation True := GRing.True.\nLocal Notation And := GRing.And (only parsing).\nLocal Notation Add := GRing.Add (only parsing).\nLocal Notation Bool b := (GRing.Bool b%bool).\nLocal Notation term := (GRing.term F).\nLocal Notation form := (GRing.formula F).\nLocal Notation eval := GRing.eval.\nLocal Notation holds := GRing.holds.\nLocal Notation qf_form := GRing.qf_form.\nLocal Notation qf_eval := GRing.qf_eval.\n\nDefinition eval_mx (e : seq F) := map_mx (eval e).\n\nDefinition mx_term := map_mx (@GRing.Const F).\n\nLemma eval_mx_term e m n (A : 'M_(m, n)) : eval_mx e (mx_term A) = A.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nDefinition mulmx_term m n p (A : 'M[term]_(m, n)) (B : 'M_(n, p)) :=\n  \\matrix_(i, k) (\\big[Add/0]_j (A i j * B j k))%T.\n\nLemma eval_mulmx e m n p (A : 'M[term]_(m, n)) (B : 'M_(n, p)) :\n  eval_mx e (mulmx_term A B) = eval_mx e A *m eval_mx e B.\nProof.\napply/matrixP=> i k; rewrite !mxE /= ((big_morph (eval e)) 0 +%R) //=.\nby apply: eq_bigr => j _; rewrite /= !mxE.\nQed.\n\nLocal Notation morphAnd f := ((big_morph f) true andb).\n\nLet Schur m n (A : 'M[term]_(1 + m, 1 + n)) (a := A 0 0) :=\n  \\matrix_(i, j) (drsubmx A i j - a^-1 * dlsubmx A i 0%R * ursubmx A 0%R j)%T.\n\nFixpoint mxrank_form (r m n : nat) : 'M_(m, n) -> form :=\n  match m, n return 'M_(m, n) -> form with\n  | m'.+1, n'.+1 => fun A : 'M_(1 + m', 1 + n') =>\n    let nzA k := A k.1 k.2 != 0 in\n    let xSchur k := Schur (xrow k.1 0%R (xcol k.2 0%R A)) in\n    let recf k := Bool (r > 0) /\\ mxrank_form r.-1 (xSchur k) in\n    GRing.Pick nzA recf (Bool (r == 0%N))\n  | _, _ => fun _ => Bool (r == 0%N)\n  end%T.\n\nLemma mxrank_form_qf r m n (A : 'M_(m, n)) : qf_form (mxrank_form r A).\nProof.\nby elim: m r n A => [|m IHm] r [|n] A //=; rewrite GRing.Pick_form_qf /=.\nQed.\n\nLemma eval_mxrank e r m n (A : 'M_(m, n)) :\n  qf_eval e (mxrank_form r A) = (\\rank (eval_mx e A) == r).\nProof.\nelim: m r n A => [|m IHm] r [|n] A /=; try by case r.\nrewrite GRing.eval_Pick /mxrank unlock /=; set pf := fun _ => _.\nrewrite -(@eq_pick _ pf) => [|k]; rewrite {}/pf ?mxE // eq_sym.\ncase: pick => [[i j]|] //=; set B := _ - _; have:= mxrankE B.\ncase: (Gaussian_elimination B) r => [[_ _] _] [|r] //= <-; rewrite {}IHm eqSS.\nby congr (\\rank _ == r); apply/matrixP=> k l; rewrite !(mxE, big_ord1) !tpermR.\nQed.\n\nLemma eval_vec_mx e m n (u : 'rV_(m * n)) :\n  eval_mx e (vec_mx u) = vec_mx (eval_mx e u).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma eval_mxvec e m n (A : 'M_(m, n)) :\n  eval_mx e (mxvec A) = mxvec (eval_mx e A).\nProof. by rewrite -{2}[A]mxvecK eval_vec_mx vec_mxK. Qed.\n\nSection Subsetmx.\n\nVariables (m1 m2 n : nat) (A : 'M[term]_(m1, n)) (B : 'M[term]_(m2, n)).\n\nDefinition submx_form :=\n  \\big[And/True]_(r < n.+1) (mxrank_form r (col_mx A B) ==> mxrank_form r B)%T.\n\nLemma eval_col_mx e :\n  eval_mx e (col_mx A B) = col_mx (eval_mx e A) (eval_mx e B).\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma submx_form_qf : qf_form submx_form.\nProof.\nby rewrite (morphAnd (@qf_form _)) ?big1 //= => r _; rewrite !mxrank_form_qf.\nQed.\n\nLemma eval_submx e : qf_eval e submx_form = (eval_mx e A <= eval_mx e B)%MS.\nProof.\nrewrite (morphAnd (qf_eval e)) //= big_andE /=.\napply/forallP/idP=> /= [|sAB d]; last first.\n  rewrite !eval_mxrank eval_col_mx -addsmxE; apply/implyP=> /eqP <-.\n  by rewrite mxrank_leqif_sup ?addsmxSr // addsmx_sub sAB /=.\nmove/(_ (inord (\\rank (eval_mx e (col_mx A B))))).\nrewrite inordK ?ltnS ?rank_leq_col // !eval_mxrank eqxx /= eval_col_mx.\nby rewrite -addsmxE mxrank_leqif_sup ?addsmxSr // addsmx_sub; case/andP.\nQed.\n\nEnd Subsetmx.\n\nSection Env.\n\nVariable d : nat.\n\nDefinition seq_of_rV (v : 'rV_d) : seq F := fgraph [ffun i => v 0 i].\n\nLemma size_seq_of_rV v : size (seq_of_rV v) = d.\nProof. by rewrite tuple.size_tuple card_ord. Qed.\n\nLemma nth_seq_of_rV x0 v (i : 'I_d) : nth x0 (seq_of_rV v) i = v 0 i.\nProof. by rewrite nth_fgraph_ord ffunE. Qed.\n\nDefinition row_var k : 'rV[term]_d := \\row_i ('X_(k * d + i))%T.\n\nDefinition row_env (e : seq 'rV_d) := flatten (map seq_of_rV e).\n\nLemma nth_row_env e k (i : 'I_d) : (row_env e)`_(k * d + i) = e`_k 0 i.\nProof.\nelim: e k => [|v e IHe] k; first by rewrite !nth_nil mxE.\nrewrite /row_env /= nth_cat size_seq_of_rV.\ncase: k => [|k]; first by rewrite (valP i) nth_seq_of_rV.\nby rewrite mulSn -addnA -if_neg -leqNgt leq_addr addKn IHe.\nQed.\n\nLemma eval_row_var e k : eval_mx (row_env e) (row_var k) = e`_k :> 'rV_d.\nProof. by apply/rowP=> i; rewrite !mxE /= nth_row_env. Qed.\n\nDefinition Exists_row_form k (f : form) :=\n  foldr GRing.Exists f (codom (fun i : 'I_d => k * d + i)%N).\n\nLemma Exists_rowP e k f :\n  d > 0 ->\n   ((exists v : 'rV[F]_d, holds (row_env (set_nth 0 e k v)) f)\n      <-> holds (row_env e) (Exists_row_form k f)).\nProof.\nmove=> d_gt0; pose i_ j := Ordinal (ltn_pmod j d_gt0).\nhave d_eq j: (j = j %/ d * d + i_ j)%N := divn_eq j d.\nsplit=> [[v f_v] | ]; last case/GRing.foldExistsP=> e' ee' f_e'.\n  apply/GRing.foldExistsP; exists (row_env (set_nth 0 e k v)) => {f f_v}// j.\n  rewrite [j]d_eq !nth_row_env nth_set_nth /=; case: eqP => // ->.\n  by case/imageP; exists (i_ j).\nexists (\\row_i e'`_(k * d + i)); apply: eq_holds f_e' => j /=.\nmove/(_ j): ee'; rewrite [j]d_eq !nth_row_env nth_set_nth /=.\ncase: eqP => [-> | ne_j_k -> //]; first by rewrite mxE.\napply/mapP=> [[r lt_r_d]]; rewrite -d_eq => def_j; case: ne_j_k.\nby rewrite def_j divnMDl // divn_small ?addn0.\nQed.\n\nEnd Env.\n\nEnd MatrixFormula.\n\nEnd MatrixFormula.\n", "meta": {"author": "beta-ziliani", "repo": "ssreflect-1.4", "sha": "2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571", "save_path": "github-repos/coq/beta-ziliani-ssreflect-1.4", "path": "github-repos/coq/beta-ziliani-ssreflect-1.4/ssreflect-1.4-2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571/theories/mxpoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7362390933053802}}
{"text": "Definition tautology : forall P : Prop, P -> P\n  := fun (P : Prop) (H : P) => H .\n\nDefinition Modus_tollens : forall P Q : Prop, ~Q /\\ (P -> Q) -> ~P\n  :=  fun (P Q : Prop) (H0 : ~ Q /\\ (P -> Q)) (H1 : P) =>\n        match H0 with conj L R => L (R H1) end.\n\nDefinition Disjunctive_syllogism : forall P Q : Prop, (P \\/ Q) -> ~P -> Q\n  := fun (P Q : Prop) (H0 : P \\/ Q) (H1 : ~P) =>\n       match H0 with\n           | or_introl Hl => False_ind Q (H1 Hl)\n           | or_intror Hr => Hr end.\n\nDefinition tautology_on_Set : forall A : Set, A -> A\n  := fun (A : Set) (H : A) => H.\n\nDefinition Modus_tollens_on_Set : forall A B : Set, (B -> Empty_set) * (A -> B) -> (A -> Empty_set)\n  := fun (A B : Set) (S0 : (B -> Empty_set) * (A -> B)) (S1 : A) =>\n       let (L, R) := S0 in L (R S1).\n\nDefinition Disjunctive_syllogism_on_Set : forall A B : Set, (A + B) -> (A -> Empty_set) -> B\n  := fun (A B : Set) (S0 : (A + B)) (S1 : A -> Empty_set) =>\n       match S0 with\n           | inl l => Empty_set_rec (fun _ : Empty_set => B) (S1 l)\n           | inr r => r\n       end.\n", "meta": {"author": "kitayuta", "repo": "CoqEx2014", "sha": "ed9e347270aaed9872b4ebc50ab44a7c1e7ea24c", "save_path": "github-repos/coq/kitayuta-CoqEx2014", "path": "github-repos/coq/kitayuta-CoqEx2014/CoqEx2014-ed9e347270aaed9872b4ebc50ab44a7c1e7ea24c/Ex4/16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109784205502, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7361725520124857}}
{"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\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 => saturday\n  | saturday => sunday\n  | sunday => monday\n  end.\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) :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\nDefinition orb (b1 : bool) (b2 : bool) :=\n  match b1 with\n  | true => true\n  | false => b2\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\nEval simpl in (next_weekday (next_weekday saturday)).\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\nDefinition nandb (b1 : bool) (b2 : bool) : bool :=\n  match b1, b2 with\n  | true, true => false\n  | false, true => true\n  | true, false => true\n  | false, false => true\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 true).\nCheck negb.\n\nTheorem plus_0_n : forall n : nat, 0 + n = n.\nProof.\n  simpl. reflexivity. Qed.\n\nEval simpl in (forall n : nat, n + 0 = n).\nEval simpl in (forall n : nat, 0 + n = n).\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_0_n'' : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m : nat,\n    n = m ->\n    n + n = m + m.\nProof.\n  intros n m. intros H. rewrite -> H.\n  reflexivity. Qed.\n\nTheorem plus_id_exercise : forall n m o : nat,\n    n = m -> m = o -> n + m = m + o.\nProof.\n  intros m n o. intros H. intros I.\n  rewrite -> H. rewrite -> I.\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_O_n.\n  reflexivity.\nQed.\n\nTheorem plus_1_n : forall n : nat, 1 + n = S n.\nProof.\n  intros n. reflexivity.\nQed.\n\nTheorem mult_1_plus : forall n m : nat,\n    (1 + n) * m = m + (n * m).\nProof.\n  intros n m.\n  rewrite -> plus_1_n.\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  reflexivity.\n  reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n    negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n    beq_nat 0 (n + 1) = false.\nProof.\n  intros n. destruct n as [O | S n'].\n  reflexivity.\n  reflexivity.\nQed.\n\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\nTheorem andb_true_elim1 : forall b c : bool,\n    andb b c = true -> b = true.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\". rewrite <- H. reflexivity.\nQed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n    andb b c = true -> c = true.\nProof.\n  intros [] [].\n  - reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\nQed.\n\nTheorem plus_0_r : forall n : nat, 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\n\nTheorem minus_diag : forall n,\n    minus n n = 0.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n    simpl. reflexivity.\n  Case \"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 as [| n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S 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'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite -> IHn'.\n  reflexivity.\nQed.\n\nTheorem plus_0 : forall n : nat,\n    n + 0 = n.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S 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 as [ | n'].\n  Case \"n = 0\".\n  simpl.\n  rewrite -> plus_0.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite -> IHn'.\n  rewrite <- plus_n_Sm.\n  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 as [ | n'].\n  Case \"n = 0\".\n  simpl.\n  reflexivity.\n  Case \"n = S n'\".\n  simpl.\n  rewrite -> IHn'.\n  rewrite -> plus_n_Sm.\n  reflexivity.\nQed.", "meta": {"author": "3tty0n", "repo": "CoqPractice", "sha": "c059939c3c7633f96c71e6c34687ab5f8297e0ff", "save_path": "github-repos/coq/3tty0n-CoqPractice", "path": "github-repos/coq/3tty0n-CoqPractice/CoqPractice-c059939c3c7633f96c71e6c34687ab5f8297e0ff/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.736169674264749}}
{"text": "(** Type **)\nVariable X: Type.\nVariable X': forall x x': X, x = x' \\/ x <> x'.\nDefinition UpdateX (x: X) (f: X -> bool) (u: X -> X): X := if f x then u x else x.\n\n(** List **)\nInductive list: Type :=\n| nil: list\n| cons: X -> list -> list.\nFixpoint InList (l: list) (e: X): Prop :=\n    match l with \n    | nil => False\n    | cons x xs => e = x \\/ InList xs e\n    end.\nFixpoint UpdateList (l: list) (f: X -> bool) (u: X -> X): list :=\n    match l with\n    | nil => nil\n    | cons x xs => cons (if f x then u x else x) (UpdateList xs f u)\n    end.\n\n(** Set **)\nDefinition set := X -> Prop.\nDefinition InSet (s: set) (x: X): Prop := s x.\nDefinition Minus (s: set) (x: X): set := fun x0 => InSet s x0 /\\ x <> x0.\nDefinition Add (s: set) (x: X): set := fun x0 => InSet s x0 \\/ x = x0.\nDefinition UpdateSet (s: set) (f: X -> bool) (u: X -> X): set :=\n    fun x0 => exists x: X, InSet s x /\\ x0 = if f x then u x else x. \n\n(** Similarity Function **)\nDefinition Similar (l: list) (s: set): Prop := \n    forall x: X, InList l x <-> InSet s x.\n\n(** Proof **)\n\n(** Helping Lemmas **)\nLemma ClassicalOrInList: forall (l: list) (x: X), InList l x \\/ ~ InList l x.\nProof.\n    intros. induction l as [| h t].\n        right. intuition.\n        simpl. pose (X' x h). destruct o.\n            intuition.\n            destruct IHt.\n                intuition.\n                right. intuition.\nQed.\n\nLemma SimilarInclusive: forall (x: X) (xs: list) (s: set),\n    Similar (cons x xs) s -> InList xs x -> Similar xs s.\nProof.\n    unfold Similar in *. intros. pose (X' x0 x). destruct o.\n        intuition.\n            apply H. rewrite H1. simpl. left. intuition.\n            rewrite H1. intuition.\n        intuition.\n            apply H. simpl. right. intuition.\n            apply H in H2. simpl in H2. intuition.\nQed.\n\nLemma SimilarExclusive: forall (x: X) (xs: list) (s: set),\n    Similar (cons x xs) s -> ~ InList xs x -> Similar xs (Minus s x).\nProof.\n    unfold Similar in *. intros. intuition.\n        unfold InSet, Minus. split.\n            apply H. simpl. intuition.\n            intuition. rewrite H2 in H0. intuition.\n        unfold InSet, Minus in H1. intuition. apply H in H2. simpl in H2. intuition. rewrite H1 in H3.\n        intuition.\nQed.\n           \nLemma InSetMinusInvariant: forall (x x0: X) (s: set) (f: X -> bool) (u: X -> X),\n    InSet (UpdateSet (Minus s x0) f u) x -> InSet (UpdateSet s f u) x.\nProof.\n    intros. unfold InSet, UpdateSet in *. destruct H. intuition. case_eq (f x1).\n        intros. rewrite H in H1. exists x1. intuition.\n            unfold Minus in H0. destruct H0. intuition.\n            rewrite H. intuition.\n        intros. rewrite H in H1. exists x1. intuition.\n            unfold Minus in H0. destruct H0. intuition.\n            rewrite H. intuition.\nQed.\n\nLemma InSetMinusUpdatedInvariant: forall (x x0: X) (s: set) (f: X -> bool) (u: X -> X),\n    InSet (UpdateSet s f u) x0 -> x0 <> UpdateX x f u -> InSet (UpdateSet (Minus s x) f u) x0. \nProof.\n    intros. unfold Minus, UpdateSet, InSet, UpdateX in *. destruct H. destruct H. exists x1. intuition.\n    rewrite <- H2 in H1. intuition.\nQed.\n\n(** Main Theorem **)\nTheorem UpdateSimilarity: forall (l: list) (s: set) (f: X -> bool) (u: X -> X),\n    Similar l s -> Similar (UpdateList l f u) (UpdateSet s f u).\nProof.\n    unfold Similar in *. induction l as [| x xs].\n    - split.\n        simpl. intuition.\n        intros. unfold InSet, UpdateSet in H0. destruct H0. intuition. apply H in H1. intuition.\n    - split.\n        simpl. intros. intuition.\n            case_eq (f x).\n                intros. rewrite H0 in H1. rewrite H1. unfold InSet, UpdateSet. exists x. split.\n                    apply H. simpl. intuition.\n                    rewrite H0. intuition.\n                intros. rewrite H0 in H1. rewrite H1. unfold InSet, UpdateSet. exists x. split.\n                    apply H. simpl. intuition.\n                    rewrite H0. intuition.\n            pose (ClassicalOrInList xs x). destruct o.\n                apply IHxs.\n                    apply SimilarInclusive with (x:=x).\n                        intuition.\n                        intuition.\n                    assumption.\n                apply InSetMinusInvariant with (x0:=x). apply IHxs.\n                    apply SimilarExclusive.\n                        intuition.\n                        intuition.\n                    intuition.\n        intros. simpl. pose (X' x0 (if f x then u x else x)). intuition. right. pose (ClassicalOrInList xs x). destruct o.\n            apply IHxs with (s:=s).\n                apply SimilarInclusive with (x:=x).\n                    intuition.\n                    intuition.\n                intuition.\n            apply InSetMinusUpdatedInvariant with (x:=x) in H0.\n                apply IHxs with (s:=(Minus s x)).\n                    apply SimilarExclusive.\n                        intuition.\n                        intuition.\n                    intuition.\n                intuition.\nQed.\n", "meta": {"author": "sorawit", "repo": "coq-sample", "sha": "21c4cc40b2312b973d4a1aeaef6906f3e03b89d6", "save_path": "github-repos/coq/sorawit-coq-sample", "path": "github-repos/coq/sorawit-coq-sample/coq-sample-21c4cc40b2312b973d4a1aeaef6906f3e03b89d6/UpdateSetnList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.736166714702612}}
{"text": "(* Exercise 32 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_032 : (A-> (B -> C)) -> ((B /\\ ~C) -> ~A).\nProof.\nimp_i a1.\nimp_i a2.\nneg_i C a3.\ncon_e2 B.\nhyp a2.\nimp_e B.\nimp_e A.\nhyp a1.\nhyp a3.\ncon_e1 (~C).\nhyp a2.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop032.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7361667085790418}}
{"text": "Require Import Limits.Pullback Cubical.PathSquare.\nRequire Import Algebra.Groups.Group.\nRequire Import WildCat.\n\n(** Pullbacks of groups are formalized by equipping the set-pullback with the desired group structure. The universal property in the category of groups is proved by saying that the corecursion principle (grp_pullback_corec) is an equivalence. *) \n\nLocal Open Scope mc_scope.\nLocal Open Scope mc_mult_scope.\n\nSection GrpPullback.\n\n  (* Variables are named to correspond with Limits.Pullback. *)\n  Context {A B C : Group} (f : B $-> A) (g : C $-> A).\n\n  Local Instance grp_pullback_sgop : SgOp (Pullback f g).\n  Proof.\n    intros [b [c p]] [d [e q]].\n    refine (b * d; c * e; _).\n    refine (grp_homo_op f b d @ (_ @ _) @ (grp_homo_op g c e)^).\n    - exact (ap (fun y:A => f b * y) q).\n    - exact (ap (fun x:A => x * g e) p).\n  Defined.\n\n  Local Instance grp_pullback_sgop_associative\n    : Associative grp_pullback_sgop.\n  Proof.\n    intros [x1 [x2 p]] [y1 [y2 q]] [z1 [z2 u]].\n    apply equiv_path_pullback; simpl.\n    refine (associativity _ _ _; associativity _ _ _; _).\n    apply equiv_sq_path.\n    apply path_ishprop.\n  Defined.\n\n  Local Instance grp_pullback_issemigroup : IsSemiGroup (Pullback f g) := {}.\n  \n  Local Instance grp_pullback_mon_unit : MonUnit (Pullback f g)\n    := (1; 1; grp_homo_unit f @ (grp_homo_unit g)^).\n\n  Local Instance grp_pullback_leftidentity\n    : LeftIdentity grp_pullback_sgop grp_pullback_mon_unit.\n  Proof.\n    intros [b [c p]]; simpl.\n    apply equiv_path_pullback; simpl.\n    refine (left_identity _; left_identity _; _).\n    apply equiv_sq_path.\n    apply path_ishprop.\n  Defined.\n\n  Local Instance grp_pullback_rightidentity\n    : RightIdentity grp_pullback_sgop grp_pullback_mon_unit.\n  Proof.\n    intros [b [c p]]; simpl.\n    apply equiv_path_pullback; simpl.\n    refine (right_identity _; right_identity _; _).\n    apply equiv_sq_path.\n    apply path_ishprop.\n  Defined.\n\n  Local Instance ismonoid_grp_pullback : IsMonoid (Pullback f g) := {}.\n\n  Local Instance grp_pullback_negate : Negate (Pullback f g).\n  Proof.\n    intros [b [c p]].\n    refine (-b; -c; grp_homo_inv f b @ _ @ (grp_homo_inv g c)^).\n    exact (ap (fun a => -a) p).\n  Defined.\n\n  Local Instance grp_pullback_leftinverse\n    : LeftInverse grp_pullback_sgop grp_pullback_negate grp_pullback_mon_unit.\n  Proof.\n    unfold LeftInverse.\n    intros [b [c p]].\n    unfold grp_pullback_sgop; simpl.\n    apply equiv_path_pullback; simpl.\n    refine (left_inverse _; left_inverse _; _).\n    apply equiv_sq_path.\n    apply path_ishprop.\n  Defined.\n\n  Local Instance grp_pullback_rightinverse\n    : RightInverse grp_pullback_sgop grp_pullback_negate grp_pullback_mon_unit.\n  Proof.\n    intros [b [c p]].\n    unfold grp_pullback_sgop; simpl.\n    apply equiv_path_pullback; simpl.\n    refine (right_inverse _; right_inverse _; _).\n    apply equiv_sq_path.\n    apply path_ishprop.\n  Defined.\n\n  Global Instance isgroup_grp_pullback : IsGroup (Pullback f g) := {}.\n\n  Definition grp_pullback : Group\n    := Build_Group (Pullback f g) _ _ _ _.\n\n  Definition grp_pullback_pr1 : grp_pullback $-> B.\n  Proof.\n    snrapply Build_GroupHomomorphism.\n    - apply pullback_pr1.\n    - intros x y. reflexivity.\n  Defined.\n\n  Definition grp_pullback_pr2 : grp_pullback $-> C.\n  Proof.\n    snrapply Build_GroupHomomorphism.\n    - apply pullback_pr2.\n    - intros x y. reflexivity.\n  Defined.\n\n  Proposition grp_pullback_corec {X : Group}\n              (b : X $-> B) (c : X $-> C)\n              (p : f o b == g o c)\n    : X $-> grp_pullback.\n  Proof.\n    snrapply Build_GroupHomomorphism.\n    - exact (fun x => (b x; c x; p x)).\n    - intros x y.\n      srapply path_sigma.\n      + simpl.\n        apply (grp_homo_op b).\n      + unfold pr2.\n        refine (transport_sigma' _ _ @ _). unfold pr1.\n        apply path_sigma_hprop.\n        simpl.\n        apply (grp_homo_op c).\n  Defined.\n\n  Corollary grp_pullback_corec' (X : Group)\n    : {b : X $-> B & { c : X $-> C & f o b == g o c}}\n      -> (X $-> grp_pullback).\n  Proof.\n    intros [b [c p]]; exact (grp_pullback_corec b c p).\n  Defined.\n\nEnd GrpPullback.\n\nDefinition functor_grp_pullback {A A' B B' C C' : Group}\n           (f : B $-> A) (f' : B' $-> A')\n           (g : C $-> A) (g' : C' $-> A')\n           (alpha : A $-> A') (beta : B $-> B') (gamma : C $-> C')\n           (h : f' o beta == alpha o f)\n           (k : alpha o g == g' o gamma)\n  : grp_pullback f g $-> grp_pullback f' g'.\nProof.\n  srapply grp_pullback_corec.\n  - exact (beta $o grp_pullback_pr1 f g).\n  - exact (gamma $o grp_pullback_pr2 f g).\n  - intro x; cbn.\n    refine (h _ @ ap alpha _ @ k _).\n    apply pullback_commsq.\nDefined.\n\nDefinition equiv_functor_grp_pullback {A A' B B' C C' : Group}\n           (f : B $-> A) (f' : B' $-> A')\n           (g : C $-> A) (g' : C' $-> A')\n           (alpha : GroupIsomorphism A A')\n           (beta : GroupIsomorphism B B')\n           (gamma : GroupIsomorphism C C')\n           (h : f' o beta == alpha o f)\n           (k : alpha o g == g' o gamma)\n  : GroupIsomorphism (grp_pullback f g) (grp_pullback f' g').\nProof.\n  srapply Build_GroupIsomorphism.\n  1: exact (functor_grp_pullback f f' g g' _ _ _ h k).\n  srapply isequiv_adjointify.\n  { srapply (functor_grp_pullback f' f g' g).\n    1-3: rapply grp_iso_inverse; assumption.\n    + rapply (equiv_ind beta); intro b.\n      refine (ap f (eissect _ _) @ _).\n      apply (equiv_ap' alpha _ _)^-1.\n      exact ((h b)^ @ (eisretr _ _)^).\n    + rapply (equiv_ind gamma); intro c.\n      refine (_ @ ap g (eissect _ _)^).\n      apply (equiv_ap' alpha _ _)^-1.\n      exact (eisretr _ _ @ (k c)^). }\n  all: intro x;\n    apply equiv_path_pullback_hset; split; cbn.\n  1-2: apply eisretr.\n  1-2: apply eissect.\nDefined.\n\n(** Pulling back along some [g : Y $-> Z] and then [g' : Y' $-> Y] is the same as pulling back along [g $o g']. *)\nDefinition equiv_grp_pullback_compose_r {X Z Y Y' : Group} (f : X $-> Z) (g' : Y' $-> Y) (g : Y $-> Z)\n  : GroupIsomorphism (grp_pullback (grp_pullback_pr2 f g) g') (grp_pullback f (g $o g')).\nProof.\n  srapply Build_GroupIsomorphism.\n  - srapply grp_pullback_corec.\n    + exact (grp_pullback_pr1 _ _ $o grp_pullback_pr1 _ _).\n    + apply grp_pullback_pr2.\n    + intro x; cbn.\n      exact (pullback_commsq _ _ _ @ ap g (pullback_commsq _ _ _)).\n  - srapply isequiv_adjointify.\n    + srapply grp_pullback_corec.\n      * srapply functor_grp_pullback.\n        1,2: exact grp_homo_id.\n        1: exact g'.\n        all: reflexivity.\n      * apply grp_pullback_pr2.\n      * reflexivity.\n    + intro x; cbn.\n      by srapply equiv_path_pullback_hset.\n    + intros [[x [y z0]] [y' z1]]; srapply equiv_path_pullback_hset; split; cbn.\n      2: reflexivity.\n      srapply equiv_path_pullback_hset; split; cbn.\n      1: reflexivity.\n      exact z1^.\nDefined.\n\nSection IsEquivGrpPullbackCorec.\n\n  (* New section with Funext at the start of the Context. *)\n  Context `{Funext} {A B C : Group} (f : B $-> A) (g : C $-> A).\n\n  Lemma grp_pullback_corec_pr1 {X : Group}\n        (b : X $-> B) (c : X $-> C)\n        (p : f o b == g o c)\n    : grp_pullback_pr1 f g $o grp_pullback_corec f g b c p = b.\n  Proof.\n    apply equiv_path_grouphomomorphism; reflexivity.\n  Defined.\n\n  Lemma grp_pullback_corec_pr2 {X : Group}\n        (b : X $-> B) (c : X $-> C)\n        (p : f o b == g o c)\n    : grp_pullback_pr2 f g $o grp_pullback_corec f g b c p = c.\n  Proof.\n    apply equiv_path_grouphomomorphism; reflexivity.\n  Defined.\n\n  Theorem isequiv_grp_pullback_corec (X : Group)\n    : IsEquiv (grp_pullback_corec' f g X).\n  Proof.\n    snrapply isequiv_adjointify.\n    - intro phi.\n      refine (grp_pullback_pr1 f g $o phi; grp_pullback_pr2 f g $o phi; _).\n      intro x; exact (pullback_commsq f g (phi x)).\n    - intro phi.\n      apply equiv_path_grouphomomorphism; reflexivity.\n    - intro bcp; simpl.\n      srapply path_sigma.\n      + simpl. apply grp_pullback_corec_pr1.\n      + refine (transport_sigma' _ _ @ _).\n        apply path_sigma_hprop; simpl pr1.\n        simpl. apply grp_pullback_corec_pr2.\n  Defined.\n\nEnd IsEquivGrpPullbackCorec.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Algebra/Groups/GrpPullback.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7361667071016952}}
{"text": "(** A library of relation operators defining sequences of transitions\n  and useful properties about them. *)\n\nSet Implicit Arguments.\n\nSection SEQUENCES.\n\nVariable A: Type.                 (**r the type of states *)\nVariable R: A -> A -> Prop.       (**r the transition relation, from one state to the next *)\n\n(** ** Finite sequences of transitions *)\n\n(** Zero, one or several transitions: reflexive, transitive closure of [R]. *)\n\nInductive star: A -> A -> Prop :=\n  | star_refl: forall a,\n      star a a\n  | star_step: forall a b c,\n      R a b -> star b c -> star a c.\n\nLemma star_one:\n  forall (a b: A), R a b -> star a b.\nProof.\n  eauto using star.\nQed.\n\nLemma star_trans:\n  forall (a b: A), star a b -> forall c, star b c -> star a c.\nProof.\n  induction 1; eauto using star.\nQed.\n\n(** One or several transitions: transitive closure of [R]. *)\n\nInductive plus: A -> A -> Prop :=\n  | plus_left: forall a b c,\n      R a b -> star b c -> plus a c.\n\nLemma plus_one:\n  forall a b, R a b -> plus a b.\nProof.\n  eauto using star, plus.\nQed.\n\nLemma plus_star:\n  forall a b,\n  plus a b -> star a b.\nProof.\n  intros. inversion H. eauto using star.\nQed.\n\nLemma plus_star_trans:\n  forall a b c, plus a b -> star b c -> plus a c.\nProof.\n  intros. inversion H. eauto using plus, star_trans.\nQed.\n\nLemma star_plus_trans:\n  forall a b c, star a b -> plus b c -> plus a c.\nProof.\n  intros. inversion H0. inversion H; eauto using plus, star, star_trans.\nQed.\n\nLemma plus_right:\n  forall a b c, star a b -> R b c -> plus a c.\nProof.\n  eauto using star_plus_trans, plus_one.\nQed.\n\n(** No transitions from a state. *)\n\nDefinition irred (a: A) : Prop := forall b, ~(R a b).\n\n(** ** Infinite sequences of transitions *)\n\n(** It is easy to characterize the fact that all transition sequences starting\n  from a state [a] are infinite: it suffices to say that any finite sequence\n  starting from [a] can always be extended by one more transition. *)\n\nDefinition all_seq_inf (a: A) : Prop :=\n  forall b, star a b -> exists c, R b c.\n\n(** However, this is not the notion we are trying to characterize: that, starting\n  from [a], there exists one infinite sequence of transitions\n  [a --> a1 --> a2 --> ... -> aN -> ...].\n\n  Indeed, consider [A = nat] and [R] such that [R 0 0] and [R 0 1].\n  [all_seq_inf 0] does not hold, because a sequence [0 -->* 1] cannot be extended.\n  Yet, [R] admits an infinite sequence, namely [0 --> 0 --> ...].\n\n  Another attempt would be to represent the sequence of states\n  [a0 --> a1 --> a2 --> ... -> aN -> ...] explicitly, as a function\n  [f: nat -> A] such that [f i] is the [i]-th state [ai] of the sequence. *)\n\nDefinition infseq_with_function (a: A) : Prop :=\n  exists f: nat -> A, f 0 = a /\\ forall i, R (f i) (f (1 + i)).\n\n(** This is a correct characterization of the existence of an infinite sequence\n  of reductions.  However, it is very inconvenient to work with this definition\n  in Coq's constructive logic: in most use cases, the function [f] is not\n  computable and therefore cannot be defined in Coq.  *)\n\n(** To obtain a practical definition of infinite sequences, we use the following\n  coinductive definition of the predicate [infseq a]. *)\n\nCoInductive infseq: A -> Prop :=\n  | infseq_step: forall a b,\n      R a b -> infseq b -> infseq a.\n\n(** An inductive predicate such as [star a b] holds iff there exists a finite\n  derivation of the conclusion [star a b] that uses the constructors\n  [star_refl] and [star_step] a finite number of times.\n\n  A coinductive predicate is similar, but holds iff there exists a finite\n  OR INFINITE derivation of the conclusion that uses the constructors\n  of the predicate a finite OR INFINITE number of times.\n\n  In other words, an inductive predicate is a smallest fixpoint: the smallest predicate\n  that satisfies its constructors; a coinductive predicate is a greatest fixpoint:\n  the largest predicate that satisfies its constructors.\n\n  The [infseq] predicate above must be defined coinductively.  Indeed, if\n  we define it inductively, the predicate would be empty (always false),\n  since there are no base cases!\n\n  Coq provides some primitive support for constructing infinite derivations\n  of facts such as [infseq a].  Such constructions are proofs by coinduction.\n  For example, we can prove the following: *)\n\nRemark cycle_infseq:\n  forall a, R a a -> infseq a.\nProof.\n  intros. cofix COINDHYP. apply infseq_step with a. auto. apply COINDHYP.\nQed.\n\n(** This style of proof by coinduction, using the [cofix] tactic, is effective\n  but can run into limitations of Coq's proof engine (the so-called\n  \"guard condition\").  However, we can derive more conventional\n  coinduction principles that are often easier to use. *)\n\n(** Consider a set [X] of states [A], that is, a predicate [X: A -> Prop].\n  Assume that for every [a] in [X], we can make one [R] transition to a [b]\n  that is still in [X].  Then, starting from [a] in [X], we can transition\n  to some [a1] in [X], then to some [a2] still in [X], then... It is clear\n  that we are just building an infinite sequence of transitions starting from\n  [a]. Therefore [infseq a] should hold.  Let's prove this! *)\n\nLemma infseq_coinduction_principle:\n  forall (X: A -> Prop),\n  (forall a, X a -> exists b, R a b /\\ X b) ->\n  forall a, X a -> infseq a.\nProof.\n  intros X P. cofix COINDHYP; intros.\n  destruct (P a H) as [b [U V]]. apply infseq_step with b; auto.\nQed.\n\n(** An even more useful variant of this coinduction principle considers a\n  set [X] where for every [a] in [X], we can make one *or several* transitions\n  to reach a [b] in [X].  *)\n\nLemma infseq_coinduction_principle_2:\n  forall (X: A -> Prop),\n  (forall a, X a -> exists b, plus a b /\\ X b) ->\n  forall a, X a -> infseq a.\nProof.\n  intros.\n  apply infseq_coinduction_principle with\n    (X := fun a => exists b, star a b /\\ X b).\n- intros.\n  destruct H1 as [b [STAR Xb]]. inversion STAR; subst.\n+ destruct (H b Xb) as [c [PLUS Xc]]. inversion PLUS; subst.\n  exists b0; split. auto. exists c; auto.\n+ exists b0; split. auto. exists b; auto.\n- exists a; split. apply star_refl. auto.\nQed.\n\n(** Here is an example of use of [infseq_coinduction_principle]:\n  if all finite transition sequences starting at [a] can be extended,\n  [infseq a] holds. *)\n\nLemma infseq_if_all_seq_inf:\n  forall a, all_seq_inf a -> infseq a.\nProof.\n  apply infseq_coinduction_principle.\n  intros. destruct (H a) as [b Rb]. constructor.\n  exists b; split; auto.\n  unfold all_seq_inf; intros. apply H. apply star_step with b; auto.\nQed.\n\n(** Likewise, the function-based characterization [infseq_with_function]\n  implies [infseq]. *)\n\nLemma infseq_from_function:\n  forall a, infseq_with_function a -> infseq a.\nProof.\n  apply infseq_coinduction_principle.\n  intros. destruct H as [f [P Q]].\n  exists (f 1); split.\n  subst a. apply Q.\n  exists (fun n => f (1 + n)); split. auto. intros. apply Q.\nQed.\n\n(** ** Determinism properties for functional transition relations. *)\n\n(** A transition relation is functional if every state can transition to at most\n  one other state. *)\n\nHypothesis R_functional:\n  forall a b c, R a b -> R a c -> b = c.\n\n(** Uniqueness of finite transition sequences. *)\n\nLemma star_star_inv:\n  forall a b, star a b -> forall c, star a c -> star b c \\/ star c b.\nProof.\n  induction 1; intros.\n- auto.\n- inversion H1; subst.\n+ right. eauto using star.\n+ assert (b = b0) by (eapply R_functional; eauto). subst b0.\n  apply IHstar; auto.\nQed.\n\nLemma finseq_unique:\n  forall a b b',\n  star a b -> irred b ->\n  star a b' -> irred b' ->\n  b = b'.\nProof.\n  intros. destruct (star_star_inv H H1).\n- inversion H3; subst. auto. elim (H0 _ H4).\n- inversion H3; subst. auto. elim (H2 _ H4).\nQed.\n\n(** A state cannot both diverge and terminate on an irreducible state. *)\n\nLemma infseq_star_inv:\n  forall a b, star a b -> infseq a -> infseq b.\nProof.\n  induction 1; intros.\n- auto.\n- inversion H1; subst.\n  assert (b = b0) by (eapply R_functional; eauto). subst b0.\n  apply IHstar; auto.\nQed.\n\nLemma infseq_finseq_excl:\n  forall a b,\n  star a b -> irred b -> infseq a -> False.\nProof.\n  intros.\n  assert (infseq b) by (eapply infseq_star_inv; eauto).\n  inversion H2. elim (H0 b0); auto.\nQed.\n\n(** If there exists an infinite sequence of transitions from [a],\n  all sequences of transitions arising from [a] are infinite. *)\n\nLemma infseq_all_seq_inf:\n  forall a, infseq a -> all_seq_inf a.\nProof.\n  intros. unfold all_seq_inf. intros.\n  assert (infseq b) by (eapply infseq_star_inv; eauto).\n  inversion H1. subst. exists b0; auto.\nQed.\n\nEnd SEQUENCES.\n\n\n\n\n\n", "meta": {"author": "Hoblovski", "repo": "compilerverif", "sha": "7f2fefb761afbcd610ef2ebe04c9a9e5e36f31de", "save_path": "github-repos/coq/Hoblovski-compilerverif", "path": "github-repos/coq/Hoblovski-compilerverif/compilerverif-7f2fefb761afbcd610ef2ebe04c9a9e5e36f31de/Sequences.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7361667058993722}}
{"text": "From HB Require Import structures.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype choice order.\nFrom mathcomp Require Import fintype ssrnat bigop.\nRequire Import mathcomp.analysis.boolp.\nRequire Import mathcomp.analysis.classical_sets.\nRequire Import HB_wrappers dioid complete_lattice.\n\n(******************************************************************************)\n(* The algebraic structure of complete dioids, as described in:               *)\n(*   Michel Minoux, Michel Gondran.                                           *)\n(*   'Graphs, Dioids and Semirings. New Models and Algorithms.'               *)\n(*   Springer, 2008                                                           *)\n(*                                                                            *)\n(* This file defines for each structure its type, its packers and its         *)\n(* canonical properties:                                                      *)\n(*                                                                            *)\n(*   * CompleteDioid (dioid with infinte distributivity):                     *)\n(*                   (From GONDRAN-MINOUX définition 6.1.8)                   *)\n(*    CompleteDioid.yype == interface type for complete Dioid structure       *)\n(* CompleteDioid_of_Dioid_and_CompleteLattice.Build D mulDl mulDr             *)\n(*                       == packs a CompleteDioid; the carrier type D must    *)\n(*                          have both a Dioid and a CompleteLattice canonical *)\n(*                          structure (see complete_lattice.v).               *)\n(*                   a^i == the power i of a                                  *)\n(*                   a^* == the kleene star operator                          *)\n(*                          (infinite sum of a^i, i >= 0)                     *)\n(*                   a^+ == the 'plus' operator (infinite sum of a^i, i > 0)  *)\n(*                 a / b == the residuation operator:                         *)\n(*                          x * b <= a <-> x <= a / b                         *)\n(* [CompleteDioid of U by <:] == CompleteDioid mixin for a subType whose base *)\n(*                          type is both a Dioid and a CompleteLattice.       *)\n(*                                                                            *)\n(*   * ComCompleteDioid:                                                      *)\n(* ComCompleteDioid.type == interface type for complete commutative dioid     *)\n(*                          structure                                         *)\n(* ComCompleteDioid_of_CompleteDioid.Build D mulC                             *)\n(*                       == packs mulC into a ComCompleteDioid; the carrier   *)\n(*                          type D must have a CompleteDioid canonical        *)\n(*                          structure.                                        *)\n(* ComCompleteDioid_of_ComDioid_and_CompleteLattice.Build D mulDl             *)\n(*                       == packs mulDl into a ComCompleteDioid; the carrier  *)\n(*                          type D must have both a ComDioid and a            *)\n(*                          CompleteLattice canonical structure.              *)\n(* ComCompleteDioid_of_CompleteLattice.Build D addA addC add0l mulA mulC      *)\n(*   mul1l mulDl mul0l le_def set_mulDl                                       *)\n(*                       == build a ComCompleteDioid structure from the       *)\n(*                          algebraic properties of its operations.           *)\n(*                          The carrier type T must have a CompleteLattice    *)\n(*                          canonical structure (see complete_lattice.v).     *)\n(*                                                                            *)\n(* Interesting lemmas:                                                        *)\n(* * forall a and b in a complete dioid, a^* * b is the least solution of     *)\n(*   x = a * x + b                                                            *)\n(* * forall a and b in a complete commutative dioid, (a + b)^* = a^* * b ^*   *)\n(*                                                                            *)\n(*   Notations are defined in scope dioid_scope (delimiter %D).               *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nReserved Notation \"x ^+\" (at level 2, format \"x ^+\").\nReserved Notation \"x ^*\" (at level 2, format \"x ^*\").\n\nLocal Open Scope classical_set_scope.\nLocal Open Scope order_scope.\nLocal Open Scope dioid_scope.\n\nImport Order.Theory.\n\nHB.mixin Record CompleteDioid_of_Dioid_and_CompleteLattice D\n         of Dioid D & CompleteLattice D := {\n  set_mulDl : forall (a : D) (B : set D),\n      a * set_join B = set_join [set a * x | x in B];\n  set_mulDr : forall (a : D) (B : set D),\n      set_join B * a = set_join [set x * a | x in B];\n}.\n\nHB.structure Definition CompleteDioid :=\n  { D of Dioid D & CompleteLattice D\n    & CompleteDioid_of_Dioid_and_CompleteLattice D }.\n\nCoercion CompleteDioid_to_Equality (T : CompleteDioid.type) :=\n  Eval hnf in [eqType of T for T].\nCanonical CompleteDioid_to_Equality.\nCoercion CompleteDioid_to_Choice (T : CompleteDioid.type) :=\n  Eval hnf in [choiceType of T for T].\nCanonical CompleteDioid_to_Choice.\nCoercion CompleteDioid_to_POrder (T : CompleteDioid.type) :=\n  Eval hnf in [porderType of T for T].\nCanonical CompleteDioid_to_POrder.\nCoercion CompleteDioid_to_Lattice (T : CompleteDioid.type) :=\n  Eval hnf in [latticeType of T for T].\nCanonical CompleteDioid_to_Lattice.\n\nSection CompleteDioidTheory.\n\nVariables D : CompleteDioid.type.\n\nImplicit Types a b c : D.\nImplicit Types B : set D.\n\nDefinition set_add : set D -> D := set_join.\n\nLemma bottom_zero : bottom D = 0.\nProof. by apply/le_anti; rewrite bottom_minimum /= le0d. Qed.\n\nLemma set_addDl a B : set_add (a |` B) = a + set_add B.\nProof.\napply/le_anti/andP; split.\n- apply: set_join_le_ub; rewrite -ubP => x [-> | Hx]; [exact: led_addr|].\n  refine (le_trans _ (led_addl _ _)); exact: set_join_ub.\n- rewrite led_add_eqv set_joinU_ge_r andbC /=.\n  by rewrite -[in X in X <= _](set_join_set1 a) set_joinU_ge_l.\nQed.\n\nLemma add_def a b : a + b = a `|` b.\nProof.\nrewrite -[in LHS](set_join_set1 b) -set_addDl.\nby rewrite /set_add set_joinU !set_join_set1.\nQed.\n\nLemma set_addU A B : set_add (A `|` B) = set_add A + set_add B.\nProof. by rewrite /set_add set_joinU add_def. Qed.\n\nLemma add_dtop : right_zero (top D) add.\nProof. by move=> x; rewrite -set_addDl setUT. Qed.\n\nLemma add_topd : left_zero (top D) add.\nProof. by move=> x; rewrite adddC add_dtop. Qed.\n\nLemma set_add_0 (F : nat -> D) : set_add [set F i | i in [set x | 'I_0 x]] = 0.\nProof. by rewrite -bottom_zero; apply: f_equal; rewrite -subset0 => x [[]]. Qed.\n\nLemma set_add_1 (F : nat -> D) : set_add [set F i | i in [set x | 'I_1 x]] = F O.\nProof.\nrewrite -(addd0 (F O)) -bottom_zero -set_addDl setU0; apply: f_equal.\nby rewrite predeqP => x; split=> [[y] | ->]; [rewrite ord1|exists ord0].\nQed.\n\nLemma set_add_S (F : nat -> D) k :\n  set_add [set F i | i in [set x | 'I_k.+1 x]]\n  = set_add [set F i | i in [set x | 'I_k x]] + F k.\nProof.\nrewrite adddC -set_addDl; apply: f_equal; rewrite predeqP => x; split.\n- move=> -[i Hi] <-.\n  move: (leq_ord i); rewrite leq_eqVlt => /orP[/eqP -> | {}Hi]; [by left|].\n  by right; exists (Ordinal Hi).\n- move=> [-> | [i _ <-]]; [by exists ord_max|].\n  by exists (inord i); rewrite ?inordK // ltnS ltnW.\nQed.\n\nLemma set_add_led (F : nat -> D) k :\n  set_add [set F i | i in [set x | 'I_k x]] <= set_add [set of F].\nProof.\nelim: k => [|k IHk].\n- set S := image _ _.\n  have ->: S = set0 by rewrite -subset0 => x [[]].\n  exact: bottom_minimum.\n- rewrite set_add_S led_add_eqv IHk /=.\n  by apply: set_join_ub; exists k.\nQed.\n\nLemma set_add_lim_nat (F : nat -> D) l :\n  (forall k, set_add [set F i | i in [set x | 'I_k x]] <= l) ->\n  set_add [set of F] <= l.\nProof.\nmove=> H; apply: set_join_le_ub => _ [i _ <-].\nby move: (H i.+1); apply/le_trans/set_join_ub; exists ord_max.\nQed.\n\nLemma set_add_led_set (F F' : nat -> D) :\n  (forall k, set_add [set F i | i in [set x | 'I_k x]]\n             <= set_add [set F' i | i in [set x | 'I_k x]]) ->\n  set_add [set of F] <= set_add [set of F'].\nProof.\nmove=> H; apply: set_add_lim_nat => k.\nexact/(le_trans (H k))/set_add_led.\nQed.\n\nSection KleeneOperatorsDefinitions.\n\nDefinition exp a n := iterop n *%D a 1.\nDefinition op_kleene a := set_add [set of exp a].\nDefinition op_plus a := set_add [set of fun i => exp a i.+1].\nDefinition div a b := set_add [set c | c * b <= a].\n\nEnd KleeneOperatorsDefinitions.\n\nLocal Notation \"a ^ i\" := (exp a i) : dioid_scope.\nLocal Notation \"a ^*\" := (op_kleene a) : dioid_scope.\nLocal Notation \"a ^+\" := (op_plus a) : dioid_scope.\nLocal Notation \"a / b\" := (div a b) : dioid_scope.\n\nSection KleeneStar.\n\nLemma exp0 a : a ^ 0 = 1.\nProof. by []. Qed.\n\nLemma expS i a : a ^ (i.+1) = a * (a ^ i).\nProof. by case: i => //; rewrite exp0 muld1. Qed.\n\nLemma expSr i a : a ^ i.+1 = a ^ i * a.\nProof.\nelim: i => [ | i Hi]; first by rewrite exp0 mul1d.\nby rewrite expS {1}Hi expS muldA.\nQed.\n\nLemma kleeneSr a : a^* = 1 + a^+.\nProof.\nrewrite -(exp0 a) -set_addDl /op_kleene.\napply: f_equal; rewrite predeqP => b; split.\n- by move=> [[| i] _ <-]; [left|right; exists i].\n- by move=> [-> | [i _ <-]]; [exists O|exists i.+1].\nQed.\n\nLemma plusSr a : a ^+ = a * a ^*.\nProof.\nrewrite set_mulDl /op_plus /op_kleene.\napply: f_equal; rewrite predeqP => b; split.\n- by move=> [i _ <-]; rewrite expS; exists (a ^ i); [exists i|].\n- by move=> [c [i _ <-] <-]; rewrite -expS; exists i.\nQed.\n\nLemma plus_le_kleene a : a^+ <= a^*.\nProof. by rewrite le_def kleeneSr adddCA adddd. Qed.\n\nLemma le_plus a : a <= a ^+.\nProof. by rewrite le_def plusSr kleeneSr muldDr muld1 adddA adddd. Qed.\n\nLemma le_kleene a : a <= a^*.\nProof. exact/(le_trans (le_plus a))/plus_le_kleene. Qed.\n\nLemma kleene_mul_expl a n : a ^ n * a ^* <= a^*.\nProof.\nelim: n => [|n IHn]; [by rewrite mul1d|].\nrewrite expSr -muldA.\nmove: IHn; apply/le_trans/led_mul2l.\nrewrite -plusSr; apply: plus_le_kleene.\nQed.\n\nLemma kleene_monotony a b : a <= b -> a ^* <= b ^*.\nProof.\nmove=> Hab.\napply: set_add_led_set => k.\nhave Hyp : forall i, a ^ i <= b ^ i.\n  elim=> [|i IHi].\n  - by rewrite exp0.\n  - by rewrite !expS; apply: led_mul.\nelim: k => [|k IHk].\n- by rewrite set_add_0 le0d.\n- rewrite !set_add_S; exact: led_add.\nQed.\n\nLemma kleene_1r a : (a + 1) ^* = a ^*.\nProof.\napply/le_anti/andP; split; [|exact/kleene_monotony/led_addr].\nsuff Hyp : forall i, (a + 1) ^ i = set_add [set a ^ j | j in [set x | 'I_i.+1 x]].\n{ apply: set_add_led_set => k.\n  elim: k => [ | k IHk]; [by rewrite set_add_0 le0d|].\n  rewrite !set_add_S Hyp.\n  rewrite -[in X in _ <= X](adddd (set_add _)) -adddA.\n  apply: (led_add IHk).\n  by rewrite set_add_S. }\nelim=> [ | i IHi]; [by rewrite set_add_1 !exp0|].\nrewrite expS muldDl mul1d IHi set_mulDl.\nset B' := [set a ^ j | j in [set j | (1 <= j <= i)%nat]].\nrewrite [X in set_join X](_ : _ = a ^ i.+1 |` B'); last first.\n{ rewrite predeqP => x; split.\n  - move=> -[y [[j Hj] _ <-] <-].\n    rewrite expS /= -!expS.\n    move: Hj; rewrite leq_eqVlt ltnS => /orP[/eqP [->] | Hj]; [by left|].\n    by right; exists j.+1.\n  - move=> [->|]; [by rewrite expS; exists (a ^ i) => //; exists ord_max|].\n    move=> -[[//|j] /andP [Hj Hji] <-]; rewrite expS; exists (a ^ j) => //.\n    by move: Hji => /ltnW; rewrite -ltnS => Hji; exists (Ordinal Hji). }\nrewrite -[set_join]/set_add set_addDl.\nrewrite (_ : image _ _ = (1 |` B')); last first.\n{ rewrite predeqP => x; split.\n  { move=> -[[[|j] Hj] _ <-]; [by left; rewrite exp0|].\n    by right; exists (Ordinal Hj). }\n  move=> [-> | [j /= Hj <-]]; [by rewrite -(exp0 a); exists ord0|].\n  by move: Hj => /andP[_]; rewrite -ltnS => Hj; exists (Ordinal Hj). }\nrewrite set_addDl.\nrewrite (adddC (a ^ 0)) adddA -(adddA (a ^ i.+1)) adddd adddC -!set_addDl.\napply: f_equal; rewrite predeqP => x; split.\n- move=> [-> | [-> | [j /= Hj <-]]].\n  + by exists ord0.\n  + by exists ord_max.\n  + move: Hj => /andP[_]; rewrite -ltnS; move=> /ltnW; rewrite -ltnS => Hj.\n    by exists (Ordinal Hj).\n- move=> -[[[|j] Hj] _ <-]; [by left|right].\n  move: Hj; rewrite /nat_of_ord !ltnS leq_eqVlt => /orP[/eqP -> | ]; [by left|].\n  by rewrite -ltnS => Hj; right; exists (Ordinal Hj).\nQed.\n\nLemma kleene_sqr a : a^* * a^* = a^*.\nProof.\nrewrite {1}/op_kleene set_mulDr.\nset B' := (a ^* |` [set of fun i => a ^ i.+1 * a ^*]).\nrewrite (_ : image _ _ = B'); last first.\n{ rewrite predeqP => x; split.\n  - by move=> -[_ [[|i] _ <-] <-]; [left; rewrite exp0 mul1d|right; exists i].\n  - move=> [-> | [i _ <-]]; [by exists 1; [exists O|rewrite mul1d]|].\n    by exists (a ^ i.+1); [exists i.+1|]. }\nrewrite -[set_join]/set_add set_addDl.\napply/eqP; rewrite adddC -le_def; apply: set_add_lim_nat.\nelim=> [|k].\n- by rewrite (set_add_0 (fun i => a ^ i.+1 * _)) le0d.\n- rewrite (set_add_S (fun i => a ^ i.+1 * _)).\n  rewrite !le_def => /eqP IHk.\n  rewrite adddAC IHk adddC -le_def.\n  exact: kleene_mul_expl.\nQed.\n\nLemma kleene_exp a i : (1 <= i)%nat -> (a ^*) ^ i = a ^*.\nProof.\ncase: i => [// | ] i _; elim: i => [// | i IHi].\nby rewrite expS IHi kleene_sqr.\nQed.\n\nLemma kleene_kleene a : (a ^*) ^* = a ^*.\nProof.\nrewrite kleeneSr /op_plus.\nrewrite (_ : image _ _ = a ^* |` set0).\n  by rewrite setU0 /set_add set_join_set1 kleeneSr adddA adddd.\nrewrite predeqP => x; split.\n- move=> [i _ <-]; left; exact: kleene_exp.\n- by move=> [-> | //]; exists O.\nQed.\n\nTheorem kleene_star_eq a b : a ^* * b = a * (a ^* * b) + b.\nProof. by rewrite muldA -plusSr -{3}(mul1d b) -muldDl kleeneSr adddC. Qed.\n\nTheorem kleene_star_least a b : forall x, (x = a * x + b) -> a ^* * b <= x.\nProof.\nmove=> x Hx.\nrewrite set_mulDr.\nrewrite [X in set_join X](_ : _ = [set (a ^ i) * b | i in setT]); last first.\n  rewrite predeqP => y; split.\n  - by move=> [_ [i _ <-] <-]; exists i.\n  - by move=> [i _ <-]; exists (a ^ i); [exists i|].\napply: set_add_lim_nat; elim=> [ | k IHk].\n  by rewrite le_def (set_add_0 (fun i => a ^ i * b)) add0d.\nrewrite (set_add_S (fun i => a ^ i * b)) led_add_eqv IHk /=.\nelim: k {IHk} => [ | k IHk]; [by rewrite mul1d Hx led_addl|].\nrewrite expS.\nhave Ha : a * x <= x; [by rewrite {2}Hx led_addr|].\nby apply: (le_trans _ Ha); rewrite -muldA led_mul2l.\nQed.\n\nEnd KleeneStar.\n\nSection ResiduationTheory.\n\nLemma div_mul_le a b : (a / b) * b <= a.\nProof. by rewrite set_mulDr; apply: set_join_le_ub => y [z + <-]. Qed.\n\nLemma mul_div_le a b : a <= (a * b) / b.\nProof. exact/set_join_ub/lexx. Qed.\n\nLemma mul_div_equiv a b x : (x * a <= b) = (x <= b / a).\nProof.\napply/idP/idP.\n- move=> H; exact: set_join_ub.\n- move=> H.\n  move: (div_mul_le b a); apply: le_trans.\n  exact: led_mul2r.\nQed.\n\nLemma div_top x : top D / x = top D.\nProof.\napply/le_anti /andP; split; [|rewrite -mul_div_equiv]; exact: top_maximum.\nQed.\n\nLemma led_divl a b c : a <= b -> a / c <= b / c.\nProof. rewrite -mul_div_equiv; exact/le_trans/div_mul_le. Qed.\n\nLemma led_divr a b c : a <= b -> c / b <= c / a.\nProof.\nmove=> Hab; rewrite -mul_div_equiv.\nexact/(le_trans (led_mul2l  _ Hab))/div_mul_le.\nQed.\n\nLemma led_div a b c d : a <= b -> d <= c -> a / c <= b / d.\nProof.\nmove=> Hab Hcd; rewrite -mul_div_equiv.\napply/(le_trans _ Hab); rewrite mul_div_equiv.\nexact: led_divr.\nQed.\n\nLemma addd_div_le (a b c : D) : a / c + b / c <= (a + b) / c.\nProof.\nrewrite led_add_eqv.\napply/andP; split; apply: led_divl; [exact: led_addr|exact: led_addl].\nQed.\n\nLemma div_mul a b c : a / (b * c) = a / c / b.\nProof.\napply/le_anti/andP; split.\n- by rewrite -!mul_div_equiv -muldA; apply: div_mul_le.\n- by rewrite -mul_div_equiv muldA !mul_div_equiv; exact: lexx.\nQed.\n\nLemma mul_divA a b c : a * (b / c) <= (a * b) / c.\nProof. rewrite -mul_div_equiv -muldA; exact/led_mul2l/div_mul_le. Qed.\n\nLemma kleene_div_equiv a : (a == a ^*) = (a == a / a).\nProof.\napply/idP/idP => /eqP.\n- move=> ->.\n  apply/eqP/le_anti/andP; split.\n  + apply: set_join_le_ub => _ [i _ <-].\n    rewrite -mul_div_equiv.\n    exact: kleene_mul_expl.\n  + apply: set_join_le_ub => x /=.\n    rewrite {1}kleeneSr muldDr muld1.\n    by rewrite led_add_eqv => /andP[].\n- move=> Ha; apply/eqP/le_anti/andP; split; [exact: le_kleene|].\n  apply: set_join_le_ub => _ [i _ <-].\n  elim: i => [ | i IHi]; [by rewrite exp0 Ha -mul_div_equiv mul1d|].\n  by rewrite expSr mul_div_equiv -Ha.\nQed.\n\nLemma mul_kleene a b : a * b ^* = (a * b ^*) / b ^*.\nProof.\napply/le_anti/andP; split.\n- by rewrite -mul_div_equiv -muldA kleene_sqr.\n- apply: set_join_le_ub => x.\n  apply: le_trans.\n  by rewrite kleeneSr muldDr muld1 led_addr.\nQed.\n\nLemma div_kleene a b : a / b ^* = (a / b ^*) * b ^*.\nProof.\napply/le_anti/andP; split; last first.\n- by rewrite -mul_div_equiv -muldA kleene_sqr div_mul_le.\n- apply: set_join_le_ub => x /=.\n  rewrite mul_div_equiv => Hx.\n  apply: (le_trans Hx).\n  by rewrite kleeneSr muldDr muld1 led_addr.\nQed.\n\nEnd ResiduationTheory.\n\nEnd CompleteDioidTheory.\n\nHB.structure Definition ComCompleteDioid :=\n  { D of ComSemiRing D & CompleteDioid D }.\n\nHB.factory Record ComCompleteDioid_of_ComDioid_and_CompleteLattice D\n           of ComDioid D & CompleteLattice D := {\n  set_mulDl : forall (a : D) (B : set D),\n      a * set_join B = set_join [set a * x | x in B];\n}.\n\nHB.builders Context D (f : ComCompleteDioid_of_ComDioid_and_CompleteLattice D).\n\n  Lemma set_mulDr a (B : set D) :\n    set_join B * a = set_join [set x * a | x in B].\n  Proof.\n  by rewrite muldC set_mulDl; apply: f_equal; rewrite predeqP => x; split;\n    (move=> -[y Hy <-]; exists y; [|rewrite muldC]).\n  Qed.\n\n  HB.instance Definition to_CompleteDioid_of_Dioid_and_CompleteLattice :=\n    CompleteDioid_of_Dioid_and_CompleteLattice.Build D set_mulDl set_mulDr.\n\nHB.end.\n\nHB.factory Record ComCompleteDioid_of_CompleteLattice D\n           of CompleteLattice D := {\n  zero : D;\n  one : D;\n  add : D -> D -> D;\n  mul : D -> D -> D;\n  adddA : associative add;\n  adddC : commutative add;\n  add0d : left_id zero add;\n  adddd : idempotent add;\n  muldA : associative mul;\n  muldC : commutative mul;\n  mul1d : left_id one mul;\n  muldDl : left_distributive mul add;\n  mul0d : left_zero zero mul;\n  le_def : forall (a b : D),\n      (Order.POrder.le wrap_porderMixin a b)\n      = (Equality.op wrap_eqMixin (add a b) b);\n  set_mulDl : forall (a : D) (B : set D),\n      mul a (set_join B) = set_join [set mul a x | x in B];\n}.\n\nHB.builders Context D (f : ComCompleteDioid_of_CompleteLattice D).\n\n  HB.instance Definition to_ComDioid_of_WrapPOrder :=\n    ComDioid_of_WrapPOrder.Build\n      D adddA adddC add0d adddd\n      muldA muldC mul1d muldDl mul0d le_def.\n\n  HB.instance Definition to_ComCompleteDioid_of_ComDioid_and_CompleteLattice :=\n    ComCompleteDioid_of_ComDioid_and_CompleteLattice.Build\n      D set_mulDl.\n\nHB.end.\n\nSection ComCompleteDioidTheory.\n\nVariables D : ComCompleteDioid.type.\n\nImplicit Types a b : D.\n\nLocal Notation \"a ^ i\" := (@exp _ a i) : dioid_scope.\nLocal Notation \"a ^*\" := (@op_kleene _ a) : dioid_scope.\nLocal Notation \"a ^+\" := (@op_plus _ a) : dioid_scope.\nLocal Notation \"a / b\" := (div a b) : dioid_scope.\n\nSection ComResiduationTheory.\n\nLemma divAC : right_commutative (@div D).\nProof.\nmove=> a b c; apply/le_anti/andP; split; rewrite -!mul_div_equiv.\n- by rewrite -muldA (muldC b) muldA !mul_div_equiv.\n- by rewrite -muldA (muldC c) muldA !mul_div_equiv.\nQed.\n\nLemma kleene_add_mul a b : (a + b) ^* = a ^* * b ^*.\nProof.\napply/le_anti/andP; split.\n- apply: set_join_le_ub => _ [i _ <-].\n  elim: i => [ | i IHi].\n  + rewrite exp0 -(muld1 1).\n    apply: led_mul.\n    * rewrite kleeneSr -{1}(addd0 1).\n      exact/led_add2l/le0d.\n    * rewrite kleeneSr -{1}(addd0 1).\n      exact/led_add2l/le0d.\n  + rewrite expS.\n    apply: (le_trans (led_mul2l _ IHi)).\n    rewrite muldDl muldA -plusSr (muldC b) -muldA -(muldC b) -plusSr.\n    rewrite !kleeneSr !muldDl !muldDr !muld1 !mul1d.\n    rewrite !adddA (adddC (a^+)) adddC !adddA adddd.\n    rewrite [X in _ <= X]adddC -!adddA (adddC 1) (adddC (a^+)) !adddA.\n    exact: led_addr.\n- rewrite {2}/op_kleene /set_add set_mulDl.\n  apply: set_join_le_ub => _ [_ [i _ <-] <-].\n  rewrite {1}/op_kleene /set_add set_mulDr.\n  apply: set_join_le_ub => _ [_ [j _ <-] <-].\n  elim: i => [ | i HIi].\n  + rewrite exp0 muld1.\n    elim: j => [ | j HIj]; [by rewrite exp0 kleeneSr led_addr|].\n    rewrite expS kleeneSr plusSr -(add0d (_ * _)).\n    apply: led_add; [exact: le0d|].\n    apply: led_mul => [ | //].\n    exact: led_addr.\n  + rewrite expS (muldC b) muldA.\n    apply: (le_trans (led_mul2r _ HIi)).\n    rewrite muldC {2}kleeneSr plusSr -(add0d (_ * _)).\n    apply: led_add; [exact: le0d|].\n    exact/led_mul2r/led_addl.\nQed.\n\nEnd ComResiduationTheory.\n\nEnd ComCompleteDioidTheory.\n\nModule SubType.\n\nSection CompleteDioid.\n\nVariables (V : CompleteDioid.type) (S : pred V).\nVariable (U : subType S).\n\nVariable D : Dioid.type.\nVariable cD : Dioid.axioms U.\nHypothesis uUD : unify Type Type U D None.\nHypothesis uUD' :\n  unify Dioid.type Dioid.type D (Dioid.Pack cD) None.\nLet U' := @Dioid.phant_clone U D cD uUD uUD'.\n\nVariable L : CompleteLattice.type.\nVariable cL : CompleteLattice.axioms U'.\nHypothesis uU'L : unify Type Type U' L None.\nHypothesis uU'L' :\n  unify CompleteLattice.type CompleteLattice.type L (CompleteLattice.Pack cL) None.\nLet U'' := @CompleteLattice.phant_clone U' L cL uU'L uU'L'.\n\nHypothesis valM : forall x y : U'', val (x * y) = val x * val y.\nHypothesis valSJ : forall B : set U'', val (set_join B) = set_join (val @` B).\n\nLemma set_mulDl (a : U'') (B : set U'') :\n  a * set_join B = set_join [set (a * x : U'') | x in B].\nProof.\napply/val_inj; rewrite valM !valSJ set_mulDl.\napply: f_equal; rewrite predeqP => x; split.\n- move=> -[_ [y Hy <-] <-].\n  by exists (a * y) => //; exists y.\n- move=> -[_ [y Hy <-] <-].\n  by exists (val y) => //; exists y.\nQed.\n\nLemma set_mulDr (a : U'') (B : set U'') :\n  set_join B * a = set_join [set (x * a : U'') | x in B].\nProof.\napply/val_inj; rewrite valM !valSJ set_mulDr.\napply: f_equal; rewrite predeqP => x; split.\n- move=> -[_ [y Hy <-] <-].\n  by exists ((y : U'') * a) => //; exists y.\n- move=> -[_ [y Hy <-] <-].\n  by exists (val y) => //; exists y.\nQed.\n\nEnd CompleteDioid.\n\nModule Exports.\n\nNotation \"[ 'CompleteDioid' 'of' R 'by' <: ]\" :=\n  (CompleteDioid_of_Dioid_and_CompleteLattice.Build\n     R\n     (@SubType.set_mulDl\n        _ _ _ (Dioid.clone R _) _ id_phant id_phant\n        (CompleteLattice.clone R _) _ id_phant id_phant (rrefl _) (frefl _))\n     (@SubType.set_mulDr\n        _ _ _ (Dioid.clone R _) _ id_phant id_phant\n        (CompleteLattice.clone R _) _ id_phant id_phant (rrefl _) (frefl _)))\n  (at level 0, format \"[ 'CompleteDioid' 'of' R 'by' <: ]\") : form_scope.\n\nEnd Exports.\n\nEnd SubType.\n\nExport SubType.Exports.\n\nNotation \"a ^ i\" := (@exp _ a i) : dioid_scope.\nNotation \"a ^*\" := (@op_kleene _ a) : dioid_scope.\nNotation \"a ^+\" := (@op_plus _ a) : dioid_scope.\nNotation \"a / b\" := (div a b) : dioid_scope.\n", "meta": {"author": "math-comp", "repo": "dioid", "sha": "ec66c1c3990e433ebcb3d9a1989ed0532413ed36", "save_path": "github-repos/coq/math-comp-dioid", "path": "github-repos/coq/math-comp-dioid/dioid-ec66c1c3990e433ebcb3d9a1989ed0532413ed36/complete_dioid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7361667014162174}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Pow2.\nRequire Import Crypto.Util.ZUtil.Log2.\nRequire Import Crypto.Util.ZUtil.Lnot.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Hints.ZArith.\nRequire Import Crypto.Util.ZUtil.ZSimplify.Simple.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Tactics.ZeroBounds.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.UniquePose.\nLocal Open Scope bool_scope. Local Open Scope Z_scope.\n\nModule Z.\n  Lemma ones_le x y : x <= y -> Z.ones x <= Z.ones y.\n  Proof using Type.\n    rewrite !Z.ones_equiv; auto with zarith.\n  Qed.\n#[global]\n  Hint Resolve ones_le : zarith.\n\n  Lemma ones_lt_pow2 x y : 0 <= x <= y -> Z.ones x < 2^y.\n  Proof using Type.\n    rewrite Z.ones_equiv, Z.lt_pred_le.\n    auto with zarith.\n  Qed.\n#[global]\n  Hint Resolve ones_lt_pow2 : zarith.\n\n  Lemma log2_ones_full x : Z.log2 (Z.ones x) = Z.max 0 (Z.pred x).\n  Proof using Type.\n    rewrite Z.ones_equiv, Z.log2_pred_pow2_full; reflexivity.\n  Qed.\n#[global]\n  Hint Rewrite log2_ones_full : zsimplify.\n\n  Lemma log2_ones_lt x y : 0 < x <= y -> Z.log2 (Z.ones x) < y.\n  Proof using Type.\n    rewrite log2_ones_full; apply Z.max_case_strong; lia.\n  Qed.\n#[global]\n  Hint Resolve log2_ones_lt : zarith.\n\n  Lemma log2_ones_le x y : 0 <= x <= y -> Z.log2 (Z.ones x) <= y.\n  Proof using Type.\n    rewrite log2_ones_full; apply Z.max_case_strong; lia.\n  Qed.\n#[global]\n  Hint Resolve log2_ones_le : zarith.\n\n  Lemma log2_ones_lt_nonneg x y : 0 < y -> x <= y -> Z.log2 (Z.ones x) < y.\n  Proof using Type.\n    rewrite log2_ones_full; apply Z.max_case_strong; lia.\n  Qed.\n#[global]\n  Hint Resolve log2_ones_lt_nonneg : zarith.\n\n  Lemma ones_pred : forall i, 0 < i -> Z.ones (Z.pred i) = Z.shiftr (Z.ones i) 1.\n  Proof using Type.\n    induction i as [|p|p]; [ | | pose proof (Pos2Z.neg_is_neg p) ]; try lia.\n    intros.\n    unfold Z.ones.\n    rewrite !Z.shiftl_1_l, Z.shiftr_div_pow2, <-!Z.sub_1_r, Z.pow_1_r, <-!Z.add_opp_r by lia.\n    replace (2 ^ (Z.pos p)) with (2 ^ (Z.pos p - 1)* 2).\n    rewrite Z.div_add_l by lia.\n    reflexivity.\n    change 2 with (2 ^ 1) at 2.\n    rewrite <-Z.pow_add_r by (pose proof (Pos2Z.is_pos p); lia).\n    f_equal. lia.\n  Qed.\n#[global]\n  Hint Rewrite <- ones_pred using zutil_arith : push_Zshift.\n\n  Lemma ones_succ : forall x, (0 <= x) ->\n    Z.ones (Z.succ x) = 2 ^ x + Z.ones x.\n  Proof using Type.\n    unfold Z.ones; intros.\n    rewrite !Z.shiftl_1_l.\n    rewrite Z.add_pred_r.\n    apply Z.succ_inj.\n    rewrite !Z.succ_pred.\n    rewrite Z.pow_succ_r; lia.\n  Qed.\n\n  Lemma ones_nonneg : forall i, (0 <= i) -> 0 <= Z.ones i.\n  Proof using Type.\n    apply natlike_ind.\n    + unfold Z.ones. simpl; lia.\n    + intros.\n      rewrite Z.ones_succ by assumption.\n      Z.zero_bounds.\n  Qed.\n#[global]\n  Hint Resolve ones_nonneg : zarith.\n\n  Lemma ones_bound m (Hm : 0 <= m) :\n    0 <= Z.ones m < 2 ^ m.\n  Proof using Type. split. apply ones_nonneg; lia. rewrite Z.ones_equiv; lia. Qed.\n\n  Lemma ones_pos_pos : forall i, (0 < i) -> 0 < Z.ones i.\n  Proof using Type.\n    intros.\n    unfold Z.ones.\n    rewrite Z.shiftl_1_l.\n    apply Z.lt_succ_lt_pred.\n    apply Z.pow_gt_1; lia.\n  Qed.\n#[global]\n  Hint Resolve ones_pos_pos : zarith.\n\n  Lemma lnot_ones_equiv n : Z.lnot (Z.ones n) = -2^n.\n  Proof using Type. rewrite Z.ones_equiv, Z.lnot_equiv, <- ?Z.sub_1_r; lia. Qed.\n\n  Lemma land_ones_ones n m\n    : Z.land (Z.ones n) (Z.ones m)\n      = Z.ones (if ((n <? 0) || (m <? 0))\n                then Z.max n m\n                else Z.min n m).\n  Proof using Type.\n    repeat first [ reflexivity\n                 | break_innermost_match_step\n                 | progress rewrite ?Bool.orb_true_iff in *\n                 | progress rewrite ?Bool.orb_false_iff in *\n                 | progress rewrite ?Z.ltb_lt, ?Z.ltb_ge in *\n                 | progress destruct_head'_and\n                 | apply Z.min_case_strong\n                 | apply Z.max_case_strong\n                 | progress intros\n                 | progress destruct_head'_or\n                 | rewrite !Z.pow_r_Zneg\n                 | rewrite !Z.land_m1_l\n                 | rewrite !Z.land_m1_r\n                 | progress change (Z.pred 0) with (-1)\n                 | rewrite Z.mod_small by lia\n                 | match goal with\n                   | [ H : ?x < 0 |- _ ] => is_var x; destruct x; try lia\n                   | [ H : ?x <= Z.neg _ |- _ ] => is_var x; destruct x; try lia\n                   | [ |- context[Z.ones (Z.neg ?x)] ] => rewrite (Z.ones_equiv (Z.neg x))\n                   | [ H : ?n <= ?m |- Z.land (Z.ones ?m) (Z.ones ?n) = _ ]\n                     => rewrite (Z.land_comm (Z.ones m) (Z.ones n))\n                   | [ H : ?n <= ?m |- Z.land (Z.ones ?n) (Z.ones ?m) = _ ]\n                     => progress rewrite ?Z.land_ones, ?Z.ones_equiv, <- ?Z.sub_1_r by auto\n                   | [ H : ?n <= ?m |- _ ]\n                     => is_var n; is_var m; unique pose proof (Z.pow_le_mono_r 2 n m ltac:(lia) H)\n                   | [ |- context[2^?x] ] => unique pose proof (Z.pow2_gt_0 x ltac:(lia))\n                   end ].\n  Qed.\n#[global]\n  Hint Rewrite land_ones_ones : zsimplify.\n\n  Lemma lor_ones_ones n m\n    : Z.lor (Z.ones n) (Z.ones m)\n      = Z.ones (if ((n <? 0) || (m <? 0))\n                then Z.min n m\n                else Z.max n m).\n  Proof using Type.\n    destruct (Z_zerop n), (Z_zerop m); subst;\n      repeat first [ reflexivity\n                   | break_innermost_match_step\n                   | progress rewrite ?Bool.orb_true_iff in *\n                   | progress rewrite ?Bool.orb_false_iff in *\n                   | progress rewrite ?Z.ltb_lt, ?Z.ltb_ge in *\n                   | progress destruct_head'_and\n                   | apply Z.min_case_strong\n                   | apply Z.max_case_strong\n                   | progress intros\n                   | progress destruct_head'_or\n                   | rewrite !Z.pow_r_Zneg\n                   | rewrite !Z.lor_m1_l\n                   | rewrite !Z.lor_m1_r\n                   | progress change (Z.pred 0) with (-1)\n                   | rewrite Z.mod_small by lia\n                   | lia\n                   | match goal with\n                     | [ H : ?x < 0 |- _ ] => is_var x; destruct x; try lia\n                     | [ H : ?x <= Z.neg _ |- _ ] => is_var x; destruct x; try lia\n                     | [ |- context[Z.ones (Z.neg ?x)] ] => rewrite (Z.ones_equiv (Z.neg x))\n                     | [ H : ?n <= ?m |- Z.lor (Z.ones ?m) (Z.ones ?n) = _ ]\n                       => rewrite (Z.lor_comm (Z.ones m) (Z.ones n))\n                     | [ H : ?n <= ?m |- Z.lor (Z.ones ?n) (Z.ones ?m) = _ ]\n                       => progress rewrite ?Z.lor_ones_low; try apply Z.log2_ones_lt_nonneg; rewrite ?Z.ones_equiv, <- ?Z.sub_1_r\n                     | [ H : ?n <= ?m |- _ ]\n                       => is_var n; is_var m; unique pose proof (Z.pow_le_mono_r 2 n m ltac:(lia) H)\n                     | [ |- context[2^?x] ] => unique pose proof (Z.pow2_gt_0 x ltac:(lia))\n                     end ].\n  Qed.\n#[global]\n  Hint Rewrite lor_ones_ones : zsimplify.\n\n  Lemma lor_pow2_mod_pow2_r x e (He : 0 <= e) : Z.lor x (2^e-1) mod (2^e) = 2^e-1.\n  Proof using Type.\n    destruct (Z_zerop e).\n    { subst; autorewrite with zsimplify_const; reflexivity. }\n    assert (0 <= x mod 2^e < 2^e) by auto with zarith.\n    assert (0 <= x mod 2^e <= 2^e-1) by lia.\n    assert (Z.log2 (x mod 2^e) <= Z.log2 (2^e-1)) by (apply Z.log2_le_mono; lia).\n    assert (Z.log2 (x mod 2^e) < e) by (rewrite Z.sub_1_r, Z.log2_pred_pow2 in * by lia; lia).\n    rewrite <- Z.land_ones, Z.land_lor_distr_l by assumption.\n    rewrite !Z.sub_1_r, <- !Z.ones_equiv, !Z.land_ones_ones, Z.min_id, Z.max_id, Bool.if_const.\n    rewrite Z.land_ones by assumption.\n    rewrite Z.lor_ones_low; auto with zarith.\n  Qed.\n#[global]\n  Hint Rewrite lor_pow2_mod_pow2_r using zutil_arith : zsimplify.\n#[global]\n  Hint Rewrite lor_pow2_mod_pow2_r using assumption : zsimplify_fast.\n\n  Lemma lor_pow2_mod_pow2_l x e (He : 0 <= e) : Z.lor (2^e-1) x mod (2^e) = 2^e-1.\n  Proof using Type. rewrite Z.lor_comm; apply lor_pow2_mod_pow2_r; assumption. Qed.\n#[global]\n  Hint Rewrite lor_pow2_mod_pow2_l using zutil_arith : zsimplify.\n#[global]\n  Hint Rewrite lor_pow2_mod_pow2_l using assumption : zsimplify_fast.\n\n  Lemma lor_pow2_div_pow2_r x e (He : 0 <= e) : (Z.lor x (2^e-1)) / (2^e) = x / 2^e.\n  Proof using Type.\n    destruct (Z_zerop e).\n    { subst; autorewrite with zsimplify_const; reflexivity. }\n    assert (0 < 2^e) by auto with zarith.\n    rewrite <- Z.shiftr_div_pow2, Z.shiftr_lor, !Z.shiftr_div_pow2 by lia.\n    rewrite (Z.div_small (_-1) _), Z.lor_0_r by lia.\n    reflexivity.\n  Qed.\n#[global]\n  Hint Rewrite lor_pow2_div_pow2_r using zutil_arith : zsimplify.\n#[global]\n  Hint Rewrite lor_pow2_div_pow2_r using assumption : zsimplify_fast.\n\n  Lemma lor_pow2_div_pow2_l x e (He : 0 <= e) : (Z.lor (2^e-1) x) / (2^e) = x / 2^e.\n  Proof using Type. rewrite Z.lor_comm; apply lor_pow2_div_pow2_r; assumption. Qed.\n#[global]\n  Hint Rewrite lor_pow2_div_pow2_l using zutil_arith : zsimplify.\n#[global]\n  Hint Rewrite lor_pow2_div_pow2_l using assumption : zsimplify_fast.\n\n  Lemma land_ones_low_alt a n : 0 <= a < 2^n -> Z.land a (Z.ones n) = a.\n  Proof using Type.\n    destruct (Z_zerop a); subst; [ intros; now rewrite Z.land_0_l | ].\n    intros; apply Z.land_ones_low; try lia; apply Z.log2_lt_pow2; try lia.\n  Qed.\n#[global]\n  Hint Rewrite land_ones_low_alt using zutil_arith : zsimplify.\n#[global]\n  Hint Rewrite land_ones_low_alt using (idtac + split); assumption : zsimplify_fast.\n\n  Lemma land_ones_low_alt_ones a n : 0 <= a <= Z.ones n -> Z.land a (Z.ones n) = a.\n  Proof using Type. rewrite Z.ones_equiv at 1; intro H; rewrite land_ones_low_alt; lia. Qed.\n#[global]\n  Hint Rewrite land_ones_low_alt_ones using zutil_arith : zsimplify.\n#[global]\n  Hint Rewrite land_ones_low_alt_ones using (idtac + split); assumption : zsimplify_fast.\n\n  Lemma shiftr_ones_sub n m : 0 <= m <= n -> Z.shiftr (Z.ones n) m = Z.ones (n - m).\n  Proof using Type. intro; now rewrite Z.shiftr_div_pow2, Z.ones_div_pow2 by lia. Qed.\n#[global]\n  Hint Rewrite shiftr_ones_sub using zutil_arith : zsimplify.\n#[global]\n  Hint Rewrite shiftr_ones_sub using (idtac + split); assumption : zsimplify_fast.\n\n  Lemma shiftr_ones_same n : 0 <= n -> Z.shiftr (Z.ones n) n = 0.\n  Proof using Type. intro; rewrite shiftr_ones_sub, Z.sub_diag by lia; reflexivity. Qed.\n#[global]\n  Hint Rewrite shiftr_ones_same using zutil_arith : zsimplify.\n#[global]\n  Hint Rewrite shiftr_ones_same using assumption : zsimplify_fast.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/Ones.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7360872230214018}}
{"text": "Require Import Coq.omega.Omega.\n\n(** 1. Simple things *)\nLemma N_S_bij: forall a b: nat, a = b <-> S a = S b.\nProof. split; omega. Defined.\nLemma N_nonzero__pos: forall a: nat, a <> 0 <-> a > 0.\nProof. split; omega. Defined.\nLemma N_lt__gt: forall a b: nat, a < b <-> b > a.\nProof. split; omega. Defined.\nLemma N_le__ge: forall a b: nat, a <= b <-> b >= a.\nProof. split; omega. Defined.\nLemma N_minus_zero: forall a: nat, a - 0 = a.\nProof. intros; omega. Defined.\nLemma N_minus_itself: forall a: nat, a - a = 0.\nProof. intros; omega. Defined.\nLemma N_gt_max: forall n a b: nat, n > Init.Nat.max a b -> n > a /\\ n > b.\n  induction n. intros. inversion H.\n  destruct a; destruct b; try (intros; simpl; omega); simpl; try omega.\n  assert (forall p q: nat, S p > S q <-> p > q) by (intros; omega).\n  repeat rewrite H. apply IHn.\nDefined.\n\n(** 2. Trichotomy-like *)\nLemma N_eq_dec: forall a b: nat, a = b \\/ a <> b.\nProof. intros; omega. Defined.\nLemma N_trichotomy_ne: forall a b: nat, a <> b <-> a < b \\/ a > b.\nProof. intros; omega. Defined.\nLemma N_trichotomy: forall a b: nat, a < b \\/ a = b \\/ a > b.\nProof. intros; omega. Defined.\nLemma N_le__lt_eq: forall a b: nat, a <= b <-> a < b \\/ a = b.\nProof. intros; omega. Defined.\nLemma N_lt__le_ne: forall a b: nat, a < b <-> a <= b /\\ a <> b.\nProof. intros; omega. Defined.\nLemma N_nle__gt: forall a b: nat, ~ a <= b <-> a > b.\nProof. intros; omega. Defined.\nLemma N_nlt__ge: forall a b: nat, ~ a < b <-> a >= b.\nProof. intros; omega. Defined.\nLemma N_eq__le_ge: forall a b: nat, a = b <-> a <= b /\\ a >= b.\nProof. intros; omega. Defined.\n\n(** 3. Iff-conditions of inequalities *)\nLemma N_leb_true__le: forall a b: nat, (a <=? b) = true <-> a <= b.\nProof. apply Nat.leb_le. Defined.\nLemma N_ltb_true__lt: forall a b: nat, (a <? b) = true <-> a < b.\nProof. apply Nat.ltb_lt. Defined.\nLemma N_eqb_true__eq: forall a b: nat, (a =? b) = true <-> a = b.\nProof. apply Nat.eqb_eq. Defined.\nLemma N_leb_false__gt: forall a b: nat, (a <=? b) = false <-> a > b.\nProof.\n  induction a; intro b; destruct b; simpl;\n  split; intro; try easy; try omega.\n  apply IHa in H; omega.\n  rewrite IHa. omega.\nDefined.\nLemma N_ltb_false__ge: forall a b: nat, (a <? b) = false <-> a >= b.\nProof.\n  induction a; intro b; destruct b; simpl;\n  split; intro; try easy; try omega.\n  apply IHa in H; omega.\n  unfold Nat.ltb; rewrite N_leb_false__gt; unfold gt, lt; omega.\nDefined.\nLemma N_eqb_false__ne: forall a b: nat, (a =? b) = false <-> a <> b.\nProof. apply beq_nat_false_iff. Defined.\nLemma N_gt__pos_minus: forall a b: nat, a > b <-> a - b > 0.\nProof. intros; omega. Defined.\nLemma N_le__zero_minus: forall a b: nat, a <= b <-> a - b = 0.\nProof. intros; omega. Defined.\n\nLtac zero := simpl; repeat rewrite <- mult_n_O; repeat rewrite <- plus_n_O; repeat rewrite N_minus_zero; repeat rewrite N_minus_itself; try reflexivity.\nLtac zero_in H := simpl in H; repeat rewrite <- mult_n_O in H; repeat rewrite <- plus_n_O in H; repeat rewrite N_minus_zero in H; repeat rewrite N_minus_itself in H; try reflexivity.\n\nLtac one:= repeat rewrite mult_1_r.\nLtac one_in H:= repeat rewrite mult_1_r in H.\n\n(** 4. Consistencies of inequalities *)\n(* Use left operations *)\nLemma N_plus_minus: forall a b: nat, a + b - b = a.\nProof. intros; omega. Defined.\nLemma N_minus_plus: forall a b: nat, a >= b -> a - b + b = a.\nProof. intros; omega. Defined.\nLemma N_minus_distr: forall a b c: nat, a - b - c = a - (b + c).\nProof. intros; omega. Defined.\nLemma N_plus_minus_diff: forall a b c: nat, b >= c -> a + b - c = a + (b - c).\nProof. intros; omega. Defined.\nLemma N_minus_plus_distr: forall a b c: nat, a >= b -> b >= c -> a - b + c = a - (b - c).\nProof. intros. omega. Defined.\nLemma N_plus_minus_distr: forall a b c: nat, a + c >= b -> b >= c -> a + c - b = a - (b - c).\nProof. intros; omega. Defined.\nLemma N_cons_eq_plus: forall a b c: nat, b = c <-> a + b = a + c.\nProof. intros; omega. Defined.\nLemma N_cons_lt_plus: forall a b c: nat, b < c <-> a + b < a + c.\nProof. intros; omega. Defined.\nLemma N_cons_le_plus: forall a b c: nat, b <= c <-> a + b <= a + c.\nProof. intros; omega. Defined.\nLemma N_cons_eq_mult_pos: forall a b c: nat, a > 0 -> b = c <-> a * b = a * c.\nProof.\n  destruct a. intros; easy. intros b c H. clear H.\n  generalize dependent c. generalize dependent b. induction a.\n  - intros. omega.\n  - induction b. simpl. destruct c.\n    + zero.\n    + split; zero; intros; inversion H.\n    + split. intros; rewrite H; reflexivity.\n      destruct c. intros. rewrite <- mult_n_O in H. inversion H.\n      assert (forall n: nat, S n = 1 + n) by reflexivity.\n      rewrite (H b), (H c). repeat rewrite mult_plus_distr_l.\n      repeat rewrite <- N_cons_eq_plus. apply IHb.\nDefined.\nLemma N_cons_lt_mult_pos: forall a b c: nat, a > 0 -> b < c <-> a * b < a * c.\nProof.\n  destruct a. intros; easy. intros b c H. clear H.\n  generalize dependent c. generalize dependent b. induction a.\n  - intros. omega.\n  - induction b. simpl. destruct c.\n    + zero.\n    + split; zero; intros; apply gt_Sn_O.\n    + split. intros. pose proof H as N.\n      rewrite N_lt__le_ne in H. destruct H. clear H0.\n      pose proof ((N_minus_plus c (S b)) H) as F. rewrite <- F.\n      rewrite mult_plus_distr_l, plus_comm.\n      remember (S (S a) * S b + S (S a) * (c - S b)) as f.\n      assert (S (S a) * S b = S (S a) * S b + 0) by omega.\n      rewrite H0; clear H0. rewrite Heqf; clear Heqf.\n      rewrite <- N_cons_lt_plus. rewrite N_lt__gt, N_gt__pos_minus in N.\n      remember (c - S b) as g. destruct g. easy. apply gt_Sn_O.\n      destruct c. zero. intros. inversion H.\n      assert (forall n: nat, S n = 1 + n) by reflexivity.\n      rewrite (H b), (H c). repeat rewrite mult_plus_distr_l.\n      repeat rewrite <- N_cons_lt_plus. apply IHb.\nDefined.\nLemma N_cons_le_mult_pos: forall a b c: nat, a > 0 -> b <= c <-> a * b <= a * c.\nProof.\n  destruct a. intros; easy. intros b c H.\n  repeat rewrite N_le__lt_eq.\n  rewrite (N_cons_lt_mult_pos (S a) b c).\n  rewrite (N_cons_eq_mult_pos (S a) b c).\n  reflexivity. apply H. apply H.\nDefined.\nLemma N_rearrange: forall a b c d: nat, a < b -> c < d -> a * d + b * c < a * c + b * d.\nProof.\n  induction b.\n  - intros. inversion H.\n  - simpl in IHb. simpl. intros. simpl.\n    destruct b. inversion H. omega. inversion H2.\n    assert (S (S b) - a > 0). { omega. }\n    repeat rewrite (mult_comm (S b)).\n    assert ((S (S b) - a) + a = S (S b)) by (apply N_minus_plus; omega).\n    assert (forall n: nat, n + n * (S b) = n * S (S b)).\n    { intros. assert (S (S b) = 1 + S b) by reflexivity. rewrite H3, mult_plus_distr_l. omega. }\n    repeat rewrite H3. rewrite <- H2. repeat rewrite mult_plus_distr_l.\n    rewrite (plus_comm _ (c * a)), (plus_comm _ (d * a)).\n    repeat rewrite plus_assoc. rewrite (mult_comm d a), (mult_comm a c), (plus_comm (a * d) (c * a)),\n    <- N_cons_lt_plus. repeat rewrite (mult_comm _ (S (S b) - a)). apply N_cons_lt_mult_pos.\n    apply H1. apply H0.\nDefined.\n", "meta": {"author": "TaeK0717", "repo": "number-construction", "sha": "7ca0a81ae3282e6d43e4fba99727144ce5add39f", "save_path": "github-repos/coq/TaeK0717-number-construction", "path": "github-repos/coq/TaeK0717-number-construction/number-construction-7ca0a81ae3282e6d43e4fba99727144ce5add39f/Z_setoid/natural.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7360872201870127}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nLemma lem : forall (x : Lst) (y : Nat), eq (rev (append x (cons y nil))) (cons y (rev x)).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. reflexivity.\n- intros. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Lst) (y : Lst) (z : Nat), eq (rev (append x (append y (cons z nil)))) (cons z (rev (append x y))).\nProof.\ninduction x.\n- intros. simpl. rewrite IHx. reflexivity.\n- intros. simpl. apply lem.\nQed.\n\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal59.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7360872182933251}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\nRequire Import ZAxioms ZMulOrder ZSgnAbs NZDiv.\n\n(** * Euclidean Division for integers (Floor convention)\n\n    We use here the convention known as Floor, or Round-Toward-Bottom,\n    where [a/b] is the closest integer below the exact fraction.\n    It can be summarized by:\n\n    [a = bq+r /\\ 0 <= |r| < |b| /\\ Sign(r) = Sign(b)]\n\n    This is the convention followed historically by [Zdiv] in Coq, and\n    corresponds to convention \"F\" in the following paper:\n\n    R. Boute, \"The Euclidean definition of the functions div and mod\",\n    ACM Transactions on Programming Languages and Systems,\n    Vol. 14, No.2, pp. 127-144, April 1992.\n\n    See files [ZDivTrunc] and [ZDivEucl] for others conventions.\n*)\n\nModule Type ZDivProp\n (Import A : ZAxiomsSig')\n (Import B : ZMulOrderProp A)\n (Import C : ZSgnAbsProp A B).\n\n(** We benefit from what already exists for NZ *)\nModule Import NZDivP := Nop <+ NZDivProp A A B.\n\n(** Another formulation of the main equation *)\n\nLemma mod_eq :\n forall a b, b~=0 -> a mod b == a - b*(a/b).\nProof.\nintros.\nrewrite <- add_move_l.\nsymmetry. now apply div_mod.\nQed.\n\n(** We have a general bound for absolute values *)\n\nLemma mod_bound_abs :\n forall a b, b~=0 -> abs (a mod b) < abs b.\nProof.\nintros.\ndestruct (abs_spec b) as [(LE,EQ)|(LE,EQ)]; rewrite EQ.\ndestruct (mod_pos_bound a b). order. now rewrite abs_eq.\ndestruct (mod_neg_bound a b). order. rewrite abs_neq; trivial.\nnow rewrite <- opp_lt_mono.\nQed.\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique : forall b q1 q2 r1 r2 : t,\n  (0<=r1<b \\/ b<r1<=0) -> (0<=r2<b \\/ b<r2<=0) ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof.\nintros b q1 q2 r1 r2 Hr1 Hr2 EQ.\ndestruct Hr1; destruct Hr2; try (intuition; order).\napply div_mod_unique with b; trivial.\nrewrite <- (opp_inj_wd r1 r2).\napply div_mod_unique with (-b); trivial.\nrewrite <- opp_lt_mono, opp_nonneg_nonpos; tauto.\nrewrite <- opp_lt_mono, opp_nonneg_nonpos; tauto.\nnow rewrite 2 mul_opp_l, <- 2 opp_add_distr, opp_inj_wd.\nQed.\n\nTheorem div_unique:\n forall a b q r, (0<=r<b \\/ b<r<=0) -> a == b*q + r -> q == a/b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0) by (destruct Hr; intuition; order).\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\ndestruct Hr; [left; apply mod_pos_bound|right; apply mod_neg_bound];\n intuition order.\nnow rewrite <- div_mod.\nQed.\n\nTheorem div_unique_pos:\n forall a b q r, 0<=r<b -> a == b*q + r -> q == a/b.\nProof. intros; apply div_unique with r; auto. Qed.\n\nTheorem div_unique_neg:\n forall a b q r, 0<=r<b -> a == b*q + r -> q == a/b.\nProof. intros; apply div_unique with r; auto. Qed.\n\nTheorem mod_unique:\n forall a b q r, (0<=r<b \\/ b<r<=0) -> a == b*q + r -> r == a mod b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0) by (destruct Hr; intuition; order).\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\ndestruct Hr; [left; apply mod_pos_bound|right; apply mod_neg_bound];\n intuition order.\nnow rewrite <- div_mod.\nQed.\n\nTheorem mod_unique_pos:\n forall a b q r, 0<=r<b -> a == b*q + r -> r == a mod b.\nProof. intros; apply mod_unique with q; auto. Qed.\n\nTheorem mod_unique_neg:\n forall a b q r, b<r<=0 -> a == b*q + r -> r == a mod b.\nProof. intros; apply mod_unique with q; auto. Qed.\n\n(** Sign rules *)\n\nLtac pos_or_neg a :=\n let LT := fresh \"LT\" in\n let LE := fresh \"LE\" in\n destruct (le_gt_cases 0 a) as [LE|LT]; [|rewrite <- opp_pos_neg in LT].\n\nFact mod_bound_or : forall a b, b~=0 -> 0<=a mod b<b \\/ b<a mod b<=0.\nProof.\nintros.\ndestruct (lt_ge_cases 0 b); [left|right].\n apply mod_pos_bound; trivial. apply mod_neg_bound; order.\nQed.\n\nFact opp_mod_bound_or : forall a b, b~=0 ->\n 0 <= -(a mod b) < -b \\/ -b < -(a mod b) <= 0.\nProof.\nintros.\ndestruct (lt_ge_cases 0 b); [right|left].\nrewrite <- opp_lt_mono, opp_nonpos_nonneg.\n destruct (mod_pos_bound a b); intuition; order.\nrewrite <- opp_lt_mono, opp_nonneg_nonpos.\n destruct (mod_neg_bound a b); intuition; order.\nQed.\n\nLemma div_opp_opp : forall a b, b~=0 -> -a/-b == a/b.\nProof.\nintros. symmetry. apply div_unique with (- (a mod b)).\nnow apply opp_mod_bound_or.\nrewrite mul_opp_l, <- opp_add_distr, <- div_mod; order.\nQed.\n\nLemma mod_opp_opp : forall a b, b~=0 -> (-a) mod (-b) == - (a mod b).\nProof.\nintros. symmetry. apply mod_unique with (a/b).\nnow apply opp_mod_bound_or.\nrewrite mul_opp_l, <- opp_add_distr, <- div_mod; order.\nQed.\n\n(** With the current conventions, the other sign rules are rather complex. *)\n\nLemma div_opp_l_z :\n forall a b, b~=0 -> a mod b == 0 -> (-a)/b == -(a/b).\nProof.\nintros a b Hb H. symmetry. apply div_unique with 0.\ndestruct (lt_ge_cases 0 b); [left|right]; intuition; order.\nrewrite <- opp_0, <- H.\nrewrite mul_opp_r, <- opp_add_distr, <- div_mod; order.\nQed.\n\nLemma div_opp_l_nz :\n forall a b, b~=0 -> a mod b ~= 0 -> (-a)/b == -(a/b)-1.\nProof.\nintros a b Hb H. symmetry. apply div_unique with (b - a mod b).\ndestruct (lt_ge_cases 0 b); [left|right].\nrewrite le_0_sub. rewrite <- (sub_0_r b) at 5. rewrite <- sub_lt_mono_l.\ndestruct (mod_pos_bound a b); intuition; order.\nrewrite le_sub_0. rewrite <- (sub_0_r b) at 1. rewrite <- sub_lt_mono_l.\ndestruct (mod_neg_bound a b); intuition; order.\nrewrite <- (add_opp_r b), mul_sub_distr_l, mul_1_r, sub_add_simpl_r_l.\nrewrite mul_opp_r, <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma mod_opp_l_z :\n forall a b, b~=0 -> a mod b == 0 -> (-a) mod b == 0.\nProof.\nintros a b Hb H. symmetry. apply mod_unique with (-(a/b)).\ndestruct (lt_ge_cases 0 b); [left|right]; intuition; order.\nrewrite <- opp_0, <- H.\nrewrite mul_opp_r, <- opp_add_distr, <- div_mod; order.\nQed.\n\nLemma mod_opp_l_nz :\n forall a b, b~=0 -> a mod b ~= 0 -> (-a) mod b == b - a mod b.\nProof.\nintros a b Hb H. symmetry. apply mod_unique with (-(a/b)-1).\ndestruct (lt_ge_cases 0 b); [left|right].\nrewrite le_0_sub. rewrite <- (sub_0_r b) at 5. rewrite <- sub_lt_mono_l.\ndestruct (mod_pos_bound a b); intuition; order.\nrewrite le_sub_0. rewrite <- (sub_0_r b) at 1. rewrite <- sub_lt_mono_l.\ndestruct (mod_neg_bound a b); intuition; order.\nrewrite <- (add_opp_r b), mul_sub_distr_l, mul_1_r, sub_add_simpl_r_l.\nrewrite mul_opp_r, <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma div_opp_r_z :\n forall a b, b~=0 -> a mod b == 0 -> a/(-b) == -(a/b).\nProof.\nintros. rewrite <- (opp_involutive a) at 1.\nrewrite div_opp_opp; auto using div_opp_l_z.\nQed.\n\nLemma div_opp_r_nz :\n forall a b, b~=0 -> a mod b ~= 0 -> a/(-b) == -(a/b)-1.\nProof.\nintros. rewrite <- (opp_involutive a) at 1.\nrewrite div_opp_opp; auto using div_opp_l_nz.\nQed.\n\nLemma mod_opp_r_z :\n forall a b, b~=0 -> a mod b == 0 -> a mod (-b) == 0.\nProof.\nintros. rewrite <- (opp_involutive a) at 1.\nnow rewrite mod_opp_opp, mod_opp_l_z, opp_0.\nQed.\n\nLemma mod_opp_r_nz :\n forall a b, b~=0 -> a mod b ~= 0 -> a mod (-b) == (a mod b) - b.\nProof.\nintros. rewrite <- (opp_involutive a) at 1.\nrewrite mod_opp_opp, mod_opp_l_nz by trivial.\nnow rewrite opp_sub_distr, add_comm, add_opp_r.\nQed.\n\n(** The sign of [a mod b] is the one of [b] (when it isn't null) *)\n\nLemma mod_sign_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n sgn (a mod b) == sgn b.\nProof.\nintros a b Hb H. destruct (lt_ge_cases 0 b) as [Hb'|Hb'].\ndestruct (mod_pos_bound a b Hb'). rewrite 2 sgn_pos; order.\ndestruct (mod_neg_bound a b). order. rewrite 2 sgn_neg; order.\nQed.\n\nLemma mod_sign : forall a b, b~=0 -> sgn (a mod b) ~= -sgn b.\nProof.\nintros a b Hb H.\ndestruct (eq_decidable (a mod b) 0) as [EQ|NEQ].\napply Hb, sgn_null_iff, opp_inj. now rewrite <- H, opp_0, EQ, sgn_0.\napply Hb, sgn_null_iff. apply eq_mul_0_l with 2; try order'. nzsimpl'.\napply add_move_0_l. rewrite <- H. symmetry. now apply mod_sign_nz.\nQed.\n\nLemma mod_sign_mul : forall a b, b~=0 -> 0 <= (a mod b) * b.\nProof.\nintros. destruct (lt_ge_cases 0 b).\napply mul_nonneg_nonneg; destruct (mod_pos_bound a b); order.\napply mul_nonpos_nonpos; destruct (mod_neg_bound a b); order.\nQed.\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, a~=0 -> a/a == 1.\nProof.\nintros. pos_or_neg a. apply div_same; order.\nrewrite <- div_opp_opp by trivial. now apply div_same.\nQed.\n\nLemma mod_same : forall a, a~=0 -> a mod a == 0.\nProof.\nintros. rewrite mod_eq, div_same by trivial. nzsimpl. apply sub_diag.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, 0<=a<b -> a/b == 0.\nProof. exact div_small. Qed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, 0<=a<b -> a mod b == a.\nProof. exact mod_small. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, a~=0 -> 0/a == 0.\nProof.\nintros. pos_or_neg a. apply div_0_l; order.\nrewrite <- div_opp_opp, opp_0 by trivial. now apply div_0_l.\nQed.\n\nLemma mod_0_l: forall a, a~=0 -> 0 mod a == 0.\nProof.\nintros; rewrite mod_eq, div_0_l; now nzsimpl.\nQed.\n\nLemma div_1_r: forall a, a/1 == a.\nProof.\nintros. symmetry. apply div_unique with 0. left. split; order || apply lt_0_1.\nnow nzsimpl.\nQed.\n\nLemma mod_1_r: forall a, a mod 1 == 0.\nProof.\nintros. rewrite mod_eq, div_1_r; nzsimpl; auto using sub_diag.\nintro EQ; symmetry in EQ; revert EQ; apply lt_neq; apply lt_0_1.\nQed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof. exact div_1_l. Qed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof. exact mod_1_l. Qed.\n\nLemma div_mul : forall a b, b~=0 -> (a*b)/b == a.\nProof.\nintros. symmetry. apply div_unique with 0.\ndestruct (lt_ge_cases 0 b); [left|right]; split; order.\nnzsimpl; apply mul_comm.\nQed.\n\nLemma mod_mul : forall a b, b~=0 -> (a*b) mod b == 0.\nProof.\nintros. rewrite mod_eq, div_mul by trivial. rewrite mul_comm; apply sub_diag.\nQed.\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, 0<=a -> 0<b -> a mod b <= a.\nProof. exact mod_le. Qed.\n\nTheorem div_pos : forall a b, 0<=a -> 0<b -> 0<= a/b.\nProof. exact div_pos. Qed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof. exact div_str_pos. Qed.\n\nLemma div_small_iff : forall a b, b~=0 -> (a/b==0 <-> 0<=a<b \\/ b<a<=0).\nProof.\nintros a b Hb.\nsplit.\nintros EQ.\nrewrite (div_mod a b Hb), EQ; nzsimpl.\nnow apply mod_bound_or.\ndestruct 1. now apply div_small.\nrewrite <- div_opp_opp by trivial. apply div_small; trivial.\nrewrite <- opp_lt_mono, opp_nonneg_nonpos; tauto.\nQed.\n\nLemma mod_small_iff : forall a b, b~=0 -> (a mod b == a <-> 0<=a<b \\/ b<a<=0).\nProof.\nintros.\nrewrite <- div_small_iff, mod_eq by trivial.\nrewrite sub_move_r, <- (add_0_r a) at 1. rewrite add_cancel_l.\nrewrite eq_sym_iff, eq_mul_0. tauto.\nQed.\n\n(** As soon as the divisor is strictly greater than 1,\n    the division is strictly decreasing. *)\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof. exact div_lt. Qed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, 0<c -> a<=b -> a/c <= b/c.\nProof.\nintros a b c Hc Hab.\nrewrite lt_eq_cases in Hab. destruct Hab as [LT|EQ];\n [|rewrite EQ; order].\nrewrite <- lt_succ_r.\nrewrite (mul_lt_mono_pos_l c) by order.\nnzsimpl.\nrewrite (add_lt_mono_r _ _ (a mod c)).\nrewrite <- div_mod by order.\napply lt_le_trans with b; trivial.\nrewrite (div_mod b c) at 1 by order.\nrewrite <- add_assoc, <- add_le_mono_l.\napply le_trans with (c+0).\nnzsimpl; destruct (mod_pos_bound b c); order.\nrewrite <- add_le_mono_l. destruct (mod_pos_bound a c); order.\nQed.\n\n(** In this convention, [div] performs Rounding-Toward-Bottom.\n\n    Since we cannot speak of rational values here, we express this\n    fact by multiplying back by [b], and this leads to separates\n    statements according to the sign of [b].\n\n    First, [a/b] is below the exact fraction ...\n*)\n\nLemma mul_div_le : forall a b, 0<b -> b*(a/b) <= a.\nProof.\nintros.\nrewrite (div_mod a b) at 2; try order.\nrewrite <- (add_0_r (b*(a/b))) at 1.\nrewrite <- add_le_mono_l.\nnow destruct (mod_pos_bound a b).\nQed.\n\nLemma mul_div_ge : forall a b, b<0 -> a <= b*(a/b).\nProof.\nintros. rewrite <- div_opp_opp, opp_le_mono, <-mul_opp_l by order.\napply mul_div_le. now rewrite opp_pos_neg.\nQed.\n\n(** ... and moreover it is the larger such integer, since [S(a/b)]\n    is strictly above the exact fraction.\n*)\n\nLemma mul_succ_div_gt: forall a b, 0<b -> a < b*(S (a/b)).\nProof.\nintros.\nnzsimpl.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_pos_bound a b); order.\nQed.\n\nLemma mul_succ_div_lt: forall a b, b<0 -> b*(S (a/b)) < a.\nProof.\nintros. rewrite <- div_opp_opp, opp_lt_mono, <-mul_opp_l by order.\napply mul_succ_div_gt. now rewrite opp_pos_neg.\nQed.\n\n(** NB: The four previous properties could be used as\n    specifications for [div]. *)\n\n(** Inequality [mul_div_le] is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, b~=0 -> (a == b*(a/b) <-> a mod b == 0).\nProof.\nintros.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- (add_0_r (b*(a/b))) at 2.\napply add_cancel_l.\nQed.\n\n(** Some additionnal inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, 0<b -> a < b*q -> a/b < q.\nProof.\nintros.\nrewrite (mul_lt_mono_pos_l b) by trivial.\napply le_lt_trans with a; trivial.\nnow apply mul_div_le.\nQed.\n\nTheorem div_le_upper_bound:\n  forall a b q, 0<b -> a <= b*q -> a/b <= q.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\nTheorem div_le_lower_bound:\n  forall a b q, 0<b -> b*q <= a -> q <= a/b.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<=p -> 0<q<=r -> p/r <= p/q.\nProof. exact div_le_compat_l. Qed.\n\n(** * Relations between usual operations and mod and div *)\n\nLemma mod_add : forall a b c, c~=0 ->\n (a + b * c) mod c == a mod c.\nProof.\nintros.\nsymmetry.\napply mod_unique with (a/c+b); trivial.\nnow apply mod_bound_or.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add : forall a b c, c~=0 ->\n (a + b * c) / c == a / c + b.\nProof.\nintros.\napply (mul_cancel_l _ _ c); try order.\napply (add_cancel_r _ _ ((a+b*c) mod c)).\nrewrite <- div_mod, mod_add by order.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add_l: forall a b c, b~=0 ->\n (a * b + c) / b == a + c / b.\nProof.\n intros a b c. rewrite (add_comm _ c), (add_comm a).\n now apply div_add.\nQed.\n\n(** Cancellations. *)\n\nLemma div_mul_cancel_r : forall a b c, b~=0 -> c~=0 ->\n (a*c)/(b*c) == a/b.\nProof.\nintros.\nsymmetry.\napply div_unique with ((a mod b)*c).\n(* ineqs *)\ndestruct (lt_ge_cases 0 c).\nrewrite <-(mul_0_l c), <-2mul_lt_mono_pos_r, <-2mul_le_mono_pos_r by trivial.\nnow apply mod_bound_or.\nrewrite <-(mul_0_l c), <-2mul_lt_mono_neg_r, <-2mul_le_mono_neg_r by order.\ndestruct (mod_bound_or a b); tauto.\n(* equation *)\nrewrite (div_mod a b) at 1 by order.\nrewrite mul_add_distr_r.\nrewrite add_cancel_r.\nrewrite <- 2 mul_assoc. now rewrite (mul_comm c).\nQed.\n\nLemma div_mul_cancel_l : forall a b c, b~=0 -> c~=0 ->\n (c*a)/(c*b) == a/b.\nProof.\nintros. rewrite !(mul_comm c); now apply div_mul_cancel_r.\nQed.\n\nLemma mul_mod_distr_l: forall a b c, b~=0 -> c~=0 ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof.\nintros.\nrewrite <- (add_cancel_l _ _ ((c*b)* ((c*a)/(c*b)))).\nrewrite <- div_mod.\nrewrite div_mul_cancel_l by trivial.\nrewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\napply div_mod; order.\nrewrite <- neq_mul_0; auto.\nQed.\n\nLemma mul_mod_distr_r: forall a b c, b~=0 -> c~=0 ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof.\n intros. rewrite !(mul_comm _ c); now rewrite mul_mod_distr_l.\nQed.\n\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, n~=0 ->\n (a mod n) mod n == a mod n.\nProof.\nintros. rewrite mod_small_iff by trivial.\nnow apply mod_bound_or.\nQed.\n\nLemma mul_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite add_comm, (mul_comm n), (mul_comm _ b).\n rewrite mul_add_distr_l, mul_assoc.\n intros. rewrite mod_add by trivial.\n now rewrite mul_comm.\nQed.\n\nLemma mul_mod_idemp_r : forall a b n, n~=0 ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof.\n intros. rewrite !(mul_comm a). now apply mul_mod_idemp_l.\nQed.\n\nTheorem mul_mod: forall a b n, n~=0 ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof.\n intros. now rewrite mul_mod_idemp_l, mul_mod_idemp_r.\nQed.\n\nLemma add_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite <- add_assoc, add_comm, mul_comm.\n intros. now rewrite mod_add.\nQed.\n\nLemma add_mod_idemp_r : forall a b n, n~=0 ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof.\n intros. rewrite !(add_comm a). now apply add_mod_idemp_l.\nQed.\n\nTheorem add_mod: forall a b n, n~=0 ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof.\n intros. now rewrite add_mod_idemp_l, add_mod_idemp_r.\nQed.\n\n(** With the current convention, the following result isn't always\n    true with a negative last divisor. For instance\n    [ 3/(-2)/(-2) = 1 <> 0 = 3 / (-2*-2) ], or\n    [ 5/2/(-2) = -1 <> -2 = 5 / (2*-2) ]. *)\n\nLemma div_div : forall a b c, b~=0 -> 0<c ->\n (a/b)/c == a/(b*c).\nProof.\n intros a b c Hb Hc.\n apply div_unique with (b*((a/b) mod c) + a mod b).\n (* begin 0<= ... <b*c \\/ ... *)\n apply neg_pos_cases in Hb. destruct Hb as [Hb|Hb].\n right.\n destruct (mod_pos_bound (a/b) c), (mod_neg_bound a b); trivial.\n split.\n apply le_lt_trans with (b*((a/b) mod c) + b).\n now rewrite <- mul_succ_r, <- mul_le_mono_neg_l, le_succ_l.\n now rewrite <- add_lt_mono_l.\n apply add_nonpos_nonpos; trivial.\n apply mul_nonpos_nonneg; order.\n left.\n destruct (mod_pos_bound (a/b) c), (mod_pos_bound a b); trivial.\n split.\n apply add_nonneg_nonneg; trivial.\n apply mul_nonneg_nonneg; order.\n apply lt_le_trans with (b*((a/b) mod c) + b).\n now rewrite <- add_lt_mono_l.\n now rewrite <- mul_succ_r, <- mul_le_mono_pos_l, le_succ_l.\n (* end 0<= ... < b*c \\/ ... *)\n rewrite (div_mod a b) at 1 by order.\n rewrite add_assoc, add_cancel_r.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\nQed.\n\n(** Similarly, the following result doesn't always hold when [c<0].\n    For instance [3 mod (-2*-2)) = 3] while\n    [3 mod (-2) + (-2)*((3/-2) mod -2) = -1].\n*)\n\nLemma rem_mul_r : forall a b c, b~=0 -> 0<c ->\n a mod (b*c) == a mod b + b*((a/b) mod c).\nProof.\n intros a b c Hb Hc.\n apply add_cancel_l with (b*c*(a/(b*c))).\n rewrite <- div_mod by (apply neq_mul_0; split; order).\n rewrite <- div_div by trivial.\n rewrite add_assoc, add_shuffle0, <- mul_assoc, <- mul_add_distr_l.\n rewrite <- div_mod by order.\n apply div_mod; order.\nQed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a/b) <= (c*a)/b.\nProof. exact div_mul_le. Qed.\n\nEnd ZDivProp.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/Integer/Abstract/ZDivFloor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7360864506120349}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path.\nFrom mathcomp Require Import div fintype tuple finfun bigop.\nRequire Import Reals Fourier.\nRequire Import ssrR Reals_ext Ranalysis_ext logb.\n\n(** * The \"natural entropy function\" *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** We first find the maximum of the \"natural entropy function\"\n    (the same the binary entropy function except that we replace\n    the logarithm in base 2 by its natural version). *)\n\nDefinition H2ln := fun p => - p * ln p - (1 - p) * ln (1 - p).\n\nLemma derivable_pt_ln_Rminus x : x < 1 -> derivable_pt ln (1 - x).\nProof.\nmove=> Hx.\nexists (/ (1 - x)).\napply derivable_pt_lim_ln, subR_gt0.\nassumption.\nDefined.\n\nLemma pderivable_H2ln : pderivable H2ln (fun x => 0 < x <= 1/2).\nProof.\nmove=> x /= [Hx0 Hx1].\napply derivable_pt_minus.\napply derivable_pt_mult.\napply derivable_pt_Ropp.\napply derivable_pt_ln.\nassumption.\napply derivable_pt_mult.\napply derivable_pt_Rminus.\napply derivable_pt_comp.\napply derivable_pt_Rminus.\napply derivable_pt_ln_Rminus.\nfourier.\nDefined.\n\n(* NB: on peut pas utiliser derivable_pt_Ropp2? *)\nLemma pderivable_Ropp_H2ln : pderivable (fun x => - H2ln x) (fun x => 1/2 <= x < 1).\nProof.\nrewrite /H2ln /pderivable => x [Hx0 Hx1].\napply derivable_pt_comp.\napply derivable_pt_minus.\napply derivable_pt_mult.\napply derivable_pt_Ropp.\napply derivable_pt_ln.\nfourier.\napply derivable_pt_mult.\napply derivable_pt_Rminus.\napply derivable_pt_comp.\napply derivable_pt_Rminus.\napply derivable_pt_ln_Rminus.\nassumption.\napply derivable_pt_Ropp.\nDefined.\n\nLemma increasing_on_0_to_half : forall x y,\n  0 < x <= 1/2 -> 0 < y <= 1/2 -> x <= y -> H2ln x <= H2ln y.\nProof.\napply derive_increasing_interv_left with (pr := pderivable_H2ln); first by fourier.\nmove=> t [Ht1 Ht2].\nrewrite /H2ln /pderivable_H2ln derive_pt_minus 2!derive_pt_mult /=.\ndestruct (Rlt_le_dec 0 t) => /=; last first.\n  suff : False by done.\n  fourier.\nrewrite derive_pt_comp /= mulRA.\napply (@leR_trans (- ln t + ln (1 - t))); last first.\n  apply Req_le; field.\n  split=> ?; fourier.\nrewrite -ln_Rinv // -ln_mult; last 2 first.\n  exact/invR_gt0.\n  fourier.\nrewrite -ln_1.\napply ln_increasing_le.\nfourier.\napply (@leR_pmul2l t) => //.\nrewrite mulRA mulRV; last exact/eqP/gtR_eqF.\nrewrite mulR1 mul1R; fourier.\nQed.\n\nLemma decreasing_on_half_to_1 : forall x y : R,\n  1/2 <= x < 1 -> 1/2 <= y < 1 -> x <= y -> H2ln y <= H2ln x.\nProof.\nmove=> x y Hx Hy xy.\nrewrite -[X in _ <= X]oppRK leR_oppr.\nmove: x y Hx Hy xy.\napply derive_increasing_interv_right with (pr := pderivable_Ropp_H2ln); first by fourier.\nmove=> t [Ht1 Ht2].\nrewrite /H2ln /pderivable_Ropp_H2ln derive_pt_comp derive_pt_minus 2!derive_pt_mult /=.\ndestruct (Rlt_le_dec 0 t) => /=; last first.\n  suff : False by done.\n  fourier.\nrewrite derive_pt_comp /= mulRA.\napply (@leR_trans (ln t - ln (1 - t))); last first.\n  apply Req_le; field.\n  split => abs; fourier.\nsuff : ln ( 1 - t) <= ln t.\n  move=> ?; fourier.\napply ln_increasing_le; fourier.\nQed.\n\nLemma H2ln_max (q : R) : 0 < q < 1 -> - q * ln q - (1 - q) * ln (1 - q) <= ln 2.\nProof.\nmove=> [Hq0 Hq1].\napply (@leR_trans (H2ln (1/2))); last first.\n  apply Req_le.\n  rewrite /H2ln (_ : 1 - 1/2 = 1/2); last by field.\n  rewrite -mulRBl (_ : - _ - _ = - 1); last by field.\n  rewrite div1R ln_Rinv; [by field | by fourier].\nrewrite -/(H2ln q).\ncase: (Rlt_le_dec q (1/2)) => H1.\n- apply increasing_on_0_to_half => //.\n  split; fourier.\n  split; fourier.\n  fourier.\n- case/Rle_lt_or_eq_dec : H1 => H1.\n  + apply decreasing_on_half_to_1 => //.\n    split; fourier.\n    split; fourier.\n    fourier.\n  + rewrite -H1; by apply Req_le.\nQed.\n\n(** * The Binary Entropy Function *)\n\nDefinition H2 p := - (p * log p) + - ((1 - p) * log (1 - p)).\n\nLemma bin_ent_0eq0 : H2 0 = 0.\nProof.\nrewrite /H2 /log.\nby rewrite !(Log_1, mulR0, mul0R, oppR0, mul1R, mulR1,\n                       add0R, addR0, subR0).\nQed.\n\nLemma bin_ent_1eq0 : H2 1 = 0.\nProof.\nrewrite /H2 /log.\nby rewrite !(Log_1, mulR0, mul0R, oppR0, mul1R, mulR1,\n                       add0R, addR0, subR0, subRR).\nQed.\n\n(** The binary entropy function is bounded by 1: *)\n\nLemma H2_max : forall p, 0 < p < 1 -> H2 p <= 1.\nProof.\nmove=> p [Hp0 Hp1].\nrewrite /H2.\napply (@leR_pmul2l (ln 2)) => //.\nrewrite mulR1 mulRDr /log -!mulNR !(mulRC (ln 2)) -!mulRA.\nrewrite (mulVR _ ln2_neq0) !mulR1 (mulNR (1 - p)); exact/H2ln_max.\nQed.\n\nLemma H2_max' (x : R): 0 <= x <= 1 -> H2 x <= 1.\nProof.\nmove=> [x_0 x_1].\ncase: x_0 => [?|<-]; last by rewrite bin_ent_0eq0.\ncase: x_1 => [?|->]; last by rewrite bin_ent_1eq0.\nexact: H2_max.\nQed.\n", "meta": {"author": "erikmd", "repo": "coq-bool-games", "sha": "659e9ac9c7f40d07ed651dde31d575f4ef0bce19", "save_path": "github-repos/coq/erikmd-coq-bool-games", "path": "github-repos/coq/erikmd-coq-bool-games/coq-bool-games-659e9ac9c7f40d07ed651dde31d575f4ef0bce19/external/infotheo/binary_entropy_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7360167484542314}}
{"text": "Fixpoint ltb (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' =>\n      match m with\n      | O => false\n      | S m' => ltb n' m'\n      end\n  end.\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1: (ltb 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_ltb2: (ltb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ltb3: (ltb 4 2) = false.\nProof. simpl. reflexivity. Qed.", "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/Chapter1/ltb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7360167389515356}}
{"text": "Require Import List  Arith Omega.\n\nSection mirror.\n\n Variable A : Type.\n\n Inductive remove_last (a:A) : list A -> list A -> Prop :=\n   | remove_last_hd : remove_last a (a :: nil) nil\n   | remove_last_tl :\n       forall (b:A) (l m:list A),\n         remove_last a l m -> remove_last a (b :: l) (b :: m). \n\n Inductive palindrome : list A -> Prop :=\n   | empty_pal : palindrome nil\n   | single_pal : forall a:A, palindrome (a :: nil)\n   | cons_pal :\n       forall (a:A) (l m:list A),\n         palindrome l -> remove_last a m l -> palindrome (a :: m).\n \n #[local] Hint Constructors remove_last palindrome : core.\n\n\n Lemma ababa : forall a b:A, palindrome (a :: b :: a :: b :: a :: nil).\n Proof.\n  eauto 7.\n Qed.\n\n\n(* more about palindromes *)\n\nLemma remove_last_inv :\n forall (a:A) (l m:list A), remove_last a m l -> m = l ++ a :: nil.\nProof.\n intros a l m H; elim H; simpl; auto with datatypes.\n intros b l0 m0 H0 e; rewrite e; trivial.\nQed.\n\nLemma rev_app : forall l m:list A, rev (l ++ m) = rev m ++ rev l.\nProof.\n intros l m; elim l; simpl; auto with datatypes.\n intros a l0 H0; rewrite ass_app; rewrite H0; auto.\nQed.\n\nLemma palindrome_rev : forall l:list A, palindrome l -> rev l = l.\nProof.\n intros l H; elim H; simpl; auto with datatypes.\n intros a l0 m H0 H1 H2; generalize H1; inversion_clear H2.\n -  simpl; auto.\n -  rewrite (remove_last_inv _ _  _ H3); simpl; repeat (rewrite rev_app; simpl).\n    intro eg; rewrite eg;  simpl; auto.\nQed.\n\n(* A new induction principle for lists *)\n\n(* preliminaries *)\n\nLemma length_app :\n forall l l':list A, length (l ++ l') = length l + length l'.\nProof.\n  intro l; elim l; simpl; auto.\nQed.\n\nLemma fib_ind :\n forall P:nat -> Prop,\n   P 0 ->\n   P 1 -> \n  (forall n:nat, P n -> P (S n) -> P (S (S n))) -> \n  forall n:nat, P n.\nProof.\n intros P H0 H1 HSSn n.\n assert (H2 : P n /\\ P (S n)).\n - induction n ;[tauto | ].\n   destruct IHn;split;auto.\n -  destruct H2; auto.\nQed.\n\nSection Proof_of_list_new_ind.\nVariables (P : list A -> Prop).\n\nHypotheses (H0 : P nil)\n           (H1 : forall a: A, P (a::nil))\n           (H2 : forall (a b:A) (l:list A), P l -> P (a :: l ++ b :: nil)).  \n   \nLemma list_cut : \nforall (l:list A) (x:A),\n            exists b : A, exists l' : list A, x :: l = l' ++ b :: nil.\nProof.\nintro l; elim l; simpl.\n intro x; exists x; exists (nil (A:=A)); auto.\n intros a1 l3 H x.\n case (H a1).\n intros x0 H7.\n case H7; intros b Hb.\n rewrite Hb.\n exists x0.\n exists (x :: b); auto.\nQed.\n\n\n\nLemma list_new_ind_length :\nforall (n:nat) (l:list A), length l = n -> P l.\nProof.\nintro n; pattern n; apply fib_ind.\n  -  intro l; case l; [simpl; auto with datatypes |  discriminate].\n  -  intro l; case l; simpl; [ discriminate | ].\n     +  intros a l0; case l0; simpl; [auto | discriminate].\n  -  intros n0 H3 H4 l; case l; simpl;[discriminate |].\n     +  intros a l0 H5; generalize H5; case l0. \n       *   simpl; discriminate 1.\n       *   intros a0 l1 H6; destruct (list_cut l1 a0) as [x [l' Hx]];\n           rewrite Hx; apply H2.\n           apply H3.\n           rewrite Hx in H6.\n           rewrite length_app in H6.\n           simpl in H6; omega.\nQed.\n\n\nLemma list_new_ind :\n   forall l:list A, P l.\nProof.\n intro l; now apply list_new_ind_length with (length l).\nQed. \n\n\nEnd Proof_of_list_new_ind.\n\n\n\nLemma app_left_reg : forall l l1 l2:list A, l ++ l1 = l ++ l2 -> l1 = l2.\nProof.\n intro l; elim l; simpl; auto.\n intros a l0 H0 l1 l2 H; injection H; auto.\nQed.\n\nLemma app_right_reg : forall l l1 l2:list A, l1 ++ l = l2 ++ l -> l1 = l2.\nProof.\n intros l l1 l2 e.\n assert (H: rev (l1 ++ l) = rev (l2 ++ l)).\n - now rewrite e.\n -  repeat rewrite rev_app in H.\n    generalize (app_left_reg _ _ _ H).\n    intro H1;  rewrite <- (rev_involutive  l1) ; \n    rewrite <- (rev_involutive l2);\n    rewrite H1; auto.\n    Qed.\n\nTheorem rev_pal : forall l:list A, rev l = l -> palindrome  l. \nProof.\n intro l; elim l using list_new_ind; auto.\n -  intros a b l0 H H0.\n    apply cons_pal with l0.\n   +  apply H;  simpl in H0;  rewrite rev_app in H0.\n      simpl in H0; injection H0.\n      intros H1 e; generalize H1; rewrite e.\n      intro H2; generalize (app_right_reg _ _ _ H2); auto.\n   +  simpl in H0; rewrite rev_app in H0; simpl in H0.\n      injection H0; intros H1 H2; rewrite <- H2.\n      generalize l0; intro l1; induction l1; simpl; auto.\nQed.\n\n\nEnd mirror.\n", "meta": {"author": "baberrehman", "repo": "interactive-theorem-proving", "sha": "e8e9de4bc664f4dd1b0fd72d6edf84f736da8874", "save_path": "github-repos/coq/baberrehman-interactive-theorem-proving", "path": "github-repos/coq/baberrehman-interactive-theorem-proving/interactive-theorem-proving-e8e9de4bc664f4dd1b0fd72d6edf84f736da8874/coq-art-8.13.0/ch8_inductive_predicates/SRC/palindrome.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7360167354105304}}
{"text": "Check 0.\nCheck nat.\nCheck Set.\nCheck Type.\nCheck forall T : Set, T.\nCheck forall T : Type, T.\n\nDefinition id (T : Type) (x : T) : T := x.\n\nSet Printing Universes.\n\nInductive exp : Type -> Type :=\n| Const : forall T, T -> exp T\n| Pair : forall T1 T2, exp T1 -> exp T2 -> exp (T1 * T2)\n| Eq : forall T, exp T -> exp T -> exp bool.\n\nPrint exp.\n\nCheck (nat, (Type, Set)).\n\nInductive prod' : Type -> Type -> Type :=\n| pair' : forall A B : Type, A -> B -> prod' A B.\n\nInductive foo (A : Type) : Type :=\n  | Foo : A -> foo A.\n\nCheck foo nat.\nCheck foo Set.\nCheck foo Type.\nCheck foo True.\n\nInductive bar : Type := Bar : bar.\n\nCheck Bar.\nCheck bar.\n\nPrint sig.\nPrint ex.\n\n\nDefinition projS A (P : A -> Prop) (x : sig P) : A :=\n  match x with\n    | exist _ v _ => v\n  end.\n\n\nDefinition churchnat := forall X : Prop, (X -> X) -> X -> X.\n\nDefinition two : churchnat :=\n  fun (X : Prop) (f : X -> X) (x : X) => f (f x).\nDefinition three : churchnat :=\n  fun (X : Prop) (f : X -> X) (x : X) => f (f (f x)).\n\nDefinition succ (n : churchnat) : churchnat :=\n   fun (X : Prop) (f : X -> X) (x : X) => f (n X f x).\n \n \nExample succ_2 : succ two = three.\nProof.\n  reflexivity.\nQed.\n\nDefinition plus (n m : churchnat) : churchnat := n _ succ m.\n\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\n\n\nDefinition projE A (P : A -> Prop) (x : ex P) : A :=\n  match x with\n    | ex_intro _ v _ => v\n  end.\n", "meta": {"author": "ankitku", "repo": "awotap", "sha": "1354a1f0e2f77c0157398553e666b6ff0be6d1ee", "save_path": "github-repos/coq/ankitku-awotap", "path": "github-repos/coq/ankitku-awotap/awotap-1354a1f0e2f77c0157398553e666b6ff0be6d1ee/DepTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7360143941431779}}
{"text": "(* author: Jean-Christophe Filliâtre *)\n\n(**\n  Correctness proof of Floyd's cycle-finding algorithm, also known as     \n  the \"tortoise and the hare\"-algorithm\n  (see http://en.wikipedia.org/wiki/Floyd's_cycle-finding_algorithm)\n\n  If $f:A\\rightarrow A$ is a function over a finite set $A$, \n  then the iterations of $f$ from $x_0\\in A$ will ultimately cycle. \n  The following code finds out an integer $m$ such that \n  $f^m(x_0)=f^{2m}(x_0)$ :\n<<\nlet rec race m x y = if x = y then m else race (m+1) (f x) (f (f y))\nin race 1 (f x0) (f (f x0))\n>>\n  The difficulty is to prove $f$'s termination.\n*)\n\nRequire Export Arith.\nRequire Export Omega.\nOpen Scope nat_scope.\n\n(** Let [f] be a function over a set [A] *)\n\nParameter A : Set.\nParameter eq_A_dec : forall (x y:A), {x=y}+{~x=y}.\nParameter f : A -> A.\nParameter x0 : A.\n\n(** We consider the sequence $x_i = f^i(x_0)$ *)\n\nFixpoint x (i:nat) { struct i } : A := match i with\n  | O => x0\n  | S j => f (x j)\n  end.\n\n(** We assume this sequence cycles after [lambda+mu] iterations, [mu]\n    being the length of the cycle (we actually don't require [lambda] and\n    [mu] to be minimal, because it is not needed for the remaining of the \n    proof *)\n\nParameter lambda : nat.\nParameter mu : nat.\nAxiom mu_positive : mu > 0.\nAxiom lambda_mu : forall i j, x (lambda+i) = x (lambda+i+j*mu).\n\n(** Hilbert's epsilon operator. *)\n\nParameter epsilon : (nat -> Prop) -> nat.\nAxiom epsilon_spec : forall P, ex P -> P (epsilon P).\n\n(** The distance between [x (2m)] and [x m] defined using [epsilon] *)\n\nDefinition sep_x2m_xm m i := x (2*m+i) = x m.\n\nDefinition min P i := P i /\\ forall j, P j -> i <= j.\n\nDefinition dist_x2m_xm m := epsilon (min (sep_x2m_xm m)).\n\n(** Existence of this distance whenever [lambda <= m] *)\n\nAxiom ex_min_P : forall P, (forall x, {P x}+{~(P x)}) -> ex P -> ex (min P).\n\nAxiom div : forall a, a > 0 -> forall b, exists k, k*a >= b.\n\nLemma ex_dist_x2m_xm : forall m, lambda <= m -> ex (min (sep_x2m_xm m)).\nProof.\n  intros m hm; apply ex_min_P.\n  intro i; unfold sep_x2m_xm.\n  case (eq_A_dec (x (2 * m + i))  (x m)); auto.\n  generalize (div mu mu_positive m); intros (k,hk).\n  exists (k*mu - m); unfold sep_x2m_xm.\n  replace (2 * m + (k * mu - m)) with (lambda + (m-lambda)+k*mu) by omega.\n  rewrite <- lambda_mu.\n  replace (lambda+(m-lambda)) with m by omega; auto.\nQed.\n\n(** Variant to prove the termination of Floyd's algorithm:\n    - either [x m] has not entered the loop yet and [lambda-m] is decreasing\n    - or bot [x m] and [x (2m)] are inside the loop and the distance between\n      [x (2m)] and [x m] is decreasing\n    Thus we use a lexicographic order. *)\n\nDefinition variant m := (lambda - m, dist_x2m_xm m).\n\nDefinition lex x y := fst x < fst y \\/ (fst x = fst y /\\ snd x < snd y).\n\n(** Correctness proof *)\n\nTheorem rec_call_is_wf : \n  forall m, x m <> x (2*m) -> lex (variant (S m)) (variant m).\nProof.\n  unfold lex,variant; simpl.  \n  intros.\n  assert (h: m < lambda \\/ m >= lambda) by omega.\n  destruct h.\n  left; omega.\n  right.\n  split; auto with *.\n  unfold dist_x2m_xm.\n  assert (exd1: ex (min (sep_x2m_xm (S m)))).\n  apply ex_dist_x2m_xm; auto with *.\n  generalize (epsilon_spec (min (sep_x2m_xm (S m))) exd1).\n  assert (exd0: ex (min (sep_x2m_xm m))).\n  apply ex_dist_x2m_xm; auto with *.\n  generalize (epsilon_spec (min (sep_x2m_xm m)) exd0).\n  generalize (epsilon (min (sep_x2m_xm m))).\n  generalize (epsilon (min (sep_x2m_xm (S m)))).\n  intros d1 d0.\n  unfold min,sep_x2m_xm.\n  intros (h1,h2) (h3,h4).\n  assert (x (S(2*m+d0)) = x (S m)).\n  simpl; simpl in h1; congruence. \n  assert (d0 > 0).\n  assert (h: d0=0 \\/ d0>0) by omega. destruct h; auto.\n  subst d0; absurd (x (2*m)=x m); auto.\n  replace (2*m+0) with (2*m) in h1; auto.\n  assert (d1 <= d0-1).\n  apply h4.\n  replace (2 * (S m) + (d0 - 1)) with (S (2 * m + d0)) by omega.\n  auto.\n  omega.\nQed.\n\nDefinition R x y := lex (variant x) (variant y).\nAxiom R_wf : well_founded R.\n\nDefinition find_cycle_rec :\n  forall (m:nat) (xm x2m:A), m > 0 -> xm=x m -> x2m=x (2*m) -> \n  { m:nat | m > 0 /\\ x m = x (2*m) }.\nProof.\n  induction m using (well_founded_induction R_wf).\n  intros xm x2m h hm h2m.\n  destruct (eq_A_dec xm x2m).\n  exists m; subst xm x2m; auto.\n  apply (H (S m)) with (f xm) (f (f x2m)); subst xm x2m; auto with *.\n  unfold R; apply rec_call_is_wf; auto.\n  replace (2*(S m)) with (S (S (2*m))) by omega; auto.\nDefined.\n\nDefinition find_cycle : { m:nat | m > 0 /\\ x m = x (2*m) }.\nProof.\n  apply (find_cycle_rec (S O) (f x0) (f (f x0))); auto with *.\nDefined.\n\n(*\nRecursive Extraction find_cycle.\n*)\n\n", "meta": {"author": "coq-contribs", "repo": "tortoise-hare-algorithm", "sha": "700280680be9dce3a339c75f020ed9c281efb687", "save_path": "github-repos/coq/coq-contribs-tortoise-hare-algorithm", "path": "github-repos/coq/coq-contribs-tortoise-hare-algorithm/tortoise-hare-algorithm-700280680be9dce3a339c75f020ed9c281efb687/TortoiseHareAlgorithm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7360143851669881}}
{"text": "Require Import Arith.\nRequire Import Arith.Max.\n\nRequire Import set.\nRequire Import order.\n\n(******************************************************************************)\n(*                       subset : set -> set -> Prop                          *)\n(******************************************************************************)\n(*\n  We have defined a type 'set' which is meant to represent a subclass of the \n  set theoretic class of finite sets. However, we know that equality on 'set'\n  is of no value and an appropriate equivalence relation needs to be defined.\n  One key step on the path to defining equivalence between sets is to define\n  the inclusion relation <= on sets. Set membership is another important \n  relation on sets, but we shall find it more convenient to focus first on \n  the inclusion relation as a primitive, and define 'x in y' as {x} <= y. \n    \n  The inclusion relation <= should satisfy the following properties:\n\n  (i)   0 <= x                                , forall x\n  (ii)  ¬({x} <= 0)                           , forall x\n  (iii) {x} <= {y}  <-> (x <= y) /\\ (y <= x)  , forall x,y\n  (iv)  {x} <= yUz  <-> {x] <= y \\/ {x} <= z  , forall x,y,z\n  (v)   xUy <= z    <->  x <= z  /\\  y <= z   , forall x,y,z\n\n  Property (i) states that the empty set is a subset of all sets. \n  Property (ii) states that no singleton set {x} is ever a subset of the \n  empty set. Property (iii) states that a singleton set {x} is a subset\n  of another singleton {y} if and only if x and y are 'equal' (we do not\n  mean 'equal' as elements of 'set' of course), that is 'equivalent' (as \n  we shall later define it) which means that x and y are both subsets of \n  each other. Property (iv) states that a singleton set {x} is a subset of\n  a union yUz if and only if x is an element of y or x is an element of z, \n  which in turn means that {x} is a subset of y or {x} is a subset of z.\n  Property (v) states that a union xUy is a subset of z, if and only if\n  both x and y are subsets of z. \n\n  All these properties are pretty natural, and we expect them to hold for \n  a binary relation <=, if it is to be viewed as a suitable candidate for \n  modelling the inclusion relation on 'set'. However, because properties \n  (i)-(v) appear to be very similar to a definition by recursion of <= \n  (viewed as a curried operator with boolean values <= : set -> set -> bool), \n  it is tempting to believe that these are actually defining properties. \n  In other words, it is tempting to believe that not only does there exists\n  a relation on set which satisfies properties (i)-(v), but such relation\n  is in fact unique. Proving existence and uniqueness of this relation is \n  the purpose of what follows. \n  \n  Defining the Haskell type: \n  \n    data Set = O | S Set | U Set Set\n  \n  the relation <= can be viewed as a map: subset :: Set -> Set -> Bool \n  which (following properties (i)-(v)) could be defined as follows:\n\n  subset O _            = True                                  -- prop (i)\n  subset (S x) O        = False                                 -- prop (ii)\n  subset (S x) (S y)    = (subset x y) && (subset y x)          -- prop (iii)\n  subset (S x) (U y z)  = (subset (S x) y) || (subset (S x) z)  -- prop (iv)\n  subset (U x y) z      = (subset x z) && (subset y z)          -- prop (v)\n\n  This looks like a recursive definition: first 'subset 0' is defined.\n  Then 'subset (S x)' is defined and lastly 'subset (U x y)'. The definition \n  of 'subset (U x y)' involves 'subset x' and 'subset y' which is legtimate \n  for a structural recursion. Now the definition of 'subset (S x)' itself \n  looks like a structural recursion: it is first defined on O, then on (S y) \n  and finally on (U y z). The definition on (U y z) only involves evaluations\n  of subset (S x) on y and z which is also very nice. However, something is\n  not quite right when defining subset (S x) on (S y). A normal recursive\n  definition of subset (S x) on (S y) should involve subset (S x) evaluated\n  at y. Unfortunately, this is not what we have: our definition of subset (S x)\n  on (S y) involves subset x y and subset y x. \n\n  Hence we cannot claim that the above Haskell definition constitutes a\n  mathematically acceptable recursive definition. We may have valid \n  Haskell syntax and possibly prove that function evaluations would \n  always terminate, but we cannot claim to have 'mathematically' proved\n  the existence of a binary relation <= on set, which satisfies (i)-(v).\n\n  In fact, attempting to replicate this definition in Coq will not yield\n  valid code: \"Error: Recursive definition of subset is ill-formed.\"\n\n  Fixpoint subset (a:set): set -> Prop :=\n    match a with\n      | Empty       => (fun b => True)\n      | Singleton x => (fun b =>\n        match b with\n          | Empty             => False\n          | Singleton y       => subset x y /\\ subset y x   (* problem here *) \n          | Union y z         => subset a y \\/ subset a z \n        end)\n      | Union x y   => (fun b => subset x b /\\ subset y b) \n    end.\n\n  Rather than attempting to define a map subset : set -> set -> Prop directly,\n  we shall define a sequence of maps Rn : set -> set -> Prop indexed by the \n  natural numbers. This sequence will be defined by a standard recursion on N, \n  making sure the map Rn for (n >= 1) is solely defined in terms of R(n-1).\n  While we consider Rn to have values in 'Prop' when working with Coq, when\n  translating the argument into standard ZF-based mathematics, we shall \n  regard Rn: set -> set -> 2 = {0,1}. Defining R0 x y = 1, for n >=1 we set: \n\n    Rn 0 _      = 1\n    Rn {x} 0    = 0\n    Rn {x} {y}  = R(n-1) x y /\\ R(n-1) y x   \n    Rn {x} yUz  = R(n-1) {x} y \\/ R(n-1) {x} z\n    Rn xUy z    = R(n-1) x z /\\ R(n-1) y z\n\n*)\n\nFixpoint subset_n (n:nat) : set -> set -> Prop :=\n  match n with \n    | 0   => (fun _ _     => True)\n    | S p => (fun a b     =>\n      match a with\n        | Empty           => True\n        | Singleton x     => \n          match b with\n            | Empty       => False\n            | Singleton y => subset_n p x y /\\ subset_n p y x\n            | Union y z   => subset_n p (Singleton x) y \\/\n                             subset_n p (Singleton x) z \n          end\n        | Union x y       => subset_n p x b /\\ subset_n p y b\n      end)\n  end.\n\n(* \n\nOnce we have defined the sequence of mappings Rn: set -> set -> 2,\nthe key is to realize that given a b:set, the boolean sequence\n(Rn a b) is eventually constant. Specifically, we have:\n\n  order(a) + order(b) <= n -> Rn a b = R(n+1) a b\n\n*)\n\nLemma subset_n_Sn : forall (n:nat) (a b:set),\n  order a + order b <= n -> (subset_n n a b <-> subset_n (S n) a b).\nProof. \n  (* induction on n *)\n  intro n. elim n.\n  (* n = 0 *)\n  intros a b. intro H. cut(a = Empty). intro H'. rewrite H'. simpl. tauto.\n  apply order_sum_eq_0_l with (b:=b). symmetry. apply le_n_0_eq. exact H.\n  (* n -> n+1 *)(* induction on a *)\n  clear n. intros n IH. intro a. elim a.\n  (* a = Empty *)\n  intro b. simpl. tauto.\n  (* a = Singleton x *)(* induction on b *)\n  clear a. intros x Hx. intro b. elim b.\n  (* b = Empty *)\n  intro H. simpl. tauto.\n  (* b = Singleton y *)\n  clear b. intros y Hy H.\n  unfold subset_n at 1. fold subset_n.\n  cut(subset_n (S (S n)) (Singleton x) (Singleton y) <-> \n     (subset_n (S n) x y)/\\(subset_n (S n) y x)). \n  intro H'. rewrite H'. rewrite <- IH, <- IH. tauto.\n  apply order_sum_singleton. rewrite plus_comm. exact H.\n  apply order_sum_singleton. exact H.\n  simpl. reflexivity.\n  (* b = Union y z *)\n  clear b. intros y Hy z Hz H.\n  unfold subset_n at 1. fold subset_n.\n  cut(subset_n (S (S n)) (Singleton x) (Union y z) <->\n     (subset_n (S n) (Singleton x) y)\\/(subset_n (S n) (Singleton x) z)).\n  intro H'. rewrite H'. rewrite <- IH, <- IH. tauto.\n  apply order_sum_union_Rr with (y:=y). exact H.\n  apply order_sum_union_Rl with (z:=z). exact H. \n  simpl. reflexivity.\n  (* a = Union x y *)\n  clear a. intros x Hx y Hy b H.\n  unfold subset_n at 1. fold subset_n.\n  cut(subset_n (S (S n)) (Union x y) b <-> \n     (subset_n (S n) x b)/\\(subset_n (S n) y b)).\n  intro H'. rewrite H'. rewrite <- IH, <- IH. tauto.\n  apply order_sum_union_Lr with (x:=x). exact H.\n  apply order_sum_union_Ll with (y:=y). exact H.\n  simpl. reflexivity.\n  Qed.\n\n(* This allows us to define R: set -> set -> 2 as by setting\nR a b = Rn a b for n large enough, specifically n = order a + order b\n*)\nDefinition subset (a b:set) : Prop :=\n  let n:= order a + order b in subset_n n a b.\n\n\n(*\nWe now check the obvious, namely that R a b = Rn a b for n large enough\n*)\n\nLemma subset_subset_n : forall (n:nat) (a b:set),\n  order a + order b <= n -> (subset a b <-> subset_n n a b).\nProof.\n  (* induction on n *)\n  intros n. elim n.\n  (* n = 0 *)\n  intros a b H. cut (a = Empty). cut (b = Empty). intros Hb Ha. rewrite Ha, Hb.\n  unfold subset. simpl. tauto.\n  apply order_sum_eq_0_r with (a:=a). symmetry. apply le_n_0_eq. exact H.\n  apply order_sum_eq_0_l with (b:=b). symmetry. apply le_n_0_eq. exact H.\n  (* n -> n+1 *)\n  clear n. intros n IH a b H.\n  (* either order a + order b < S n or = S n *)\n  cut((order a + order b < S n)\\/(order a + order b = S n)). intro H0. elim H0.\n  (* order a + order b < S n *)\n  intro H1. rewrite IH. apply subset_n_Sn. \n  apply le_S_n. exact H1. apply le_S_n. exact H1. \n  (* order a + order b = S n *)\n  intro H1. unfold subset. rewrite H1. tauto.\n  (* finally *)\n  apply le_lt_or_eq. exact H.\nQed.\n\n(* \nAt this stage we have defined a relation R: set -> set -> 2.\nIt remains to prove that R satisfies properties (i)-(v).\n\n  (i)   0 <= x                                , forall x\n  (ii)  ¬({x} <= 0)                           , forall x\n  (iii) {x} <= {y}  <-> (x <= y) /\\ (y <= x)  , forall x,y\n  (iv)  {x} <= yUz  <-> {x] <= y \\/ {x} <= z  , forall x,y,z\n  (v)   xUy <= z    <->  x <= z  /\\  y <= z   , forall x,y,z\n\n  We start with (i)\n*)\nProposition subset_0_all : forall (b:set), subset Empty b.\nProof.\n  (* induction on b *)\n  intro b. elim b.\n  (* b = Empty *)\n  unfold subset. simpl. apply I.\n  (* b = Singleton x *)\n  clear b. intros x H. unfold subset. simpl. apply I.\n  (* b = Union x y *)\n  clear b. intros x Hx y Hy. unfold subset. simpl. apply I.\nQed.\n\n(*\nproperty (ii)\n*)\n\nProposition subset_single_0 : forall (x:set), ~subset (Singleton x) Empty.\nProof.\n  (* not structural induction necessary *)\n  intro x. unfold subset. simpl. tauto.\nQed.\n\n(*\nproperty (iii)\n*)\n\nProposition subset_single_single : forall (x y:set),\n  subset (Singleton x) (Singleton y) <-> (subset x y)/\\(subset y x).\nProof.\n  intros x y. unfold subset at 1. simpl. \n  rewrite <- subset_subset_n, <- subset_subset_n. tauto.\n  rewrite plus_comm. apply plus_le_compat_l. apply le_S. apply le_n.\n  apply plus_le_compat_l. apply le_S. apply le_n.\nQed.\n\n(*\nproperty (iv)\n*)\n\nProposition subset_single_union: forall (x y z:set),\n  subset (Singleton x) (Union y z) <-> \n  (subset (Singleton x) y)\\/(subset (Singleton x) z).\nProof.\n  intros x y z. unfold subset at 1. simpl.\n  rewrite <- subset_subset_n, <- subset_subset_n. tauto. \n  simpl. rewrite <- plus_n_Sm. apply le_n_S. \n  apply plus_le_compat_l. apply le_max_r.\n  simpl. rewrite <- plus_n_Sm. apply le_n_S. \n  apply plus_le_compat_l. apply le_max_l.\nQed.\n\n(*\nproperty (v)\n*)\n\nProposition subset_union_all : forall (x y b:set),\n  subset (Union x y) b <-> (subset x b)/\\(subset y b).\nProof.\n  intros x y b. unfold subset at 1. simpl.\n  rewrite <- subset_subset_n, <- subset_subset_n. tauto.\n  apply plus_le_compat_r. apply le_max_r. apply plus_le_compat_r. apply le_max_l.\nQed.\n\n(*\nWrapping things up for the existence result: defining a few predicates\non relations of type set -> set -> 2. Each predicate refers to one\nof the properties (i)-(v) which we have proved our inclusion \nrelation satisfies\n*)\n\nDefinition subset_prop_1 (relation: set -> set -> Prop) : Prop :=\n  forall (b:set), relation Empty b.\n\nDefinition subset_prop_2 (relation: set -> set -> Prop) : Prop :=\n  forall (x:set), ~relation (Singleton x) Empty.\n\nDefinition subset_prop_3 (relation: set-> set -> Prop) : Prop :=\n  forall (x y:set),\n  relation (Singleton x) (Singleton y) <-> relation x y /\\ relation y x.\n\nDefinition subset_prop_4 (relation: set -> set -> Prop) : Prop :=\n  forall (x y z:set),\n  relation (Singleton x) (Union y z) <->\n  relation (Singleton x) y \\/ relation (Singleton x) z.\n\nDefinition subset_prop_5 (relation: set -> set -> Prop) : Prop :=\n  forall (x y b:set),\n  relation (Union x y) b <-> relation x b /\\ relation y b.\n\n(*\nThere exists a binary relation on set which satisfies (i)-(v)\n  (i)   0 <= x                                , forall x\n  (ii)  ¬({x} <= 0)                           , forall x\n  (iii) {x} <= {y}  <-> (x <= y) /\\ (y <= x)  , forall x,y\n  (iv)  {x} <= yUz  <-> {x] <= y \\/ {x} <= z  , forall x,y,z\n  (v)   xUy <= z    <->  x <= z  /\\  y <= z   , forall x,y,z\n*)\n\nLemma subset_exist :\n  subset_prop_1 subset /\\\n  subset_prop_2 subset /\\\n  subset_prop_3 subset /\\\n  subset_prop_4 subset /\\\n  subset_prop_5 subset.\nProof.\n  split. unfold subset_prop_1. apply subset_0_all.\n  split. unfold subset_prop_2. apply subset_single_0.\n  split. unfold subset_prop_3. apply subset_single_single.\n  split. unfold subset_prop_4. apply subset_single_union.\n  unfold subset_prop_5. apply subset_union_all.\nQed.\n\n(*\nSuch relation is in fact unique.\n*)\n\nLemma subset_unique : forall (relation : set -> set -> Prop),\n  subset_prop_1 relation ->\n  subset_prop_2 relation ->\n  subset_prop_3 relation ->\n  subset_prop_4 relation ->\n  subset_prop_5 relation ->\n  forall (a b:set), relation a b <-> subset a b.\nProof.\n  intros relation H1 H2 H3 H4 H5 a b.\n  (* proof by induction on order a + order b <= n *)\n  cut(forall n:nat, order a + order b <= n -> (relation a b <-> subset a b)).\n  intro H. apply H with (n:= order a + order b). apply le_n.\n  intro n. generalize a b. clear a b. elim n.\n  (* order a + order b <= 0 *) \n  intros a b H. cut (a = Empty). intro H'. rewrite H'.\n  split. intros. apply subset_0_all. intros. apply H1.\n  apply order_sum_eq_0_l with (b:=b). symmetry. apply le_n_0_eq. exact H.\n  (* true for <= n -> true for <= n+1 *)\n  (* induction on a *)  \n  clear n. intros n IH a. elim a.\n  (* a = Empty *)\n  intros b H. split. intros. apply subset_0_all. intros. apply H1.\n  (* a = Singleton x *)(* induction on b *)\n  clear a. intros x H b. elim b.\n  (* b = Empty *)\n  intros. split. \n  intros. apply False_ind. apply H2 with (x:=x). exact H6.\n  intros. apply False_ind. apply subset_single_0 with (x:=x). exact H6. \n  (* b = Singleton y *)\n  clear b. intros y H' H''. unfold subset_prop_3 in H3. \n  rewrite H3, subset_single_single, IH, IH. tauto.\n  rewrite plus_comm. apply order_sum_singleton. exact H''.\n  apply order_sum_singleton. exact H''.\n  (* b = Union y z *)\n  clear b. intros y Hy z Hz H'. unfold subset_prop_4 in H4.\n  rewrite H4, subset_single_union, IH, IH. tauto.\n  apply order_sum_union_Rr with (y:=y). exact H'.\n  apply order_sum_union_Rl with (z:=z). exact H'.\n  (* a = Union x y *)\n  clear a. intros x Hx y Hy b H. unfold subset_prop_5 in H5.\n  rewrite H5, subset_union_all, IH, IH. tauto.\n  apply order_sum_union_Lr with (x:=x). exact H.\n  apply order_sum_union_Ll with (y:=y). exact H.\nQed.\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/set2/subset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7358914688199601}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Ralph Matthes [+]                              *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [+] Affiliation IRIT -- CNRS   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega Extraction.\nRequire Import list_utils bt sorted.\n\nSet Implicit Arguments.\n\n(** The very standard Depth First Search algorithm on a binary\n    tree with a specification: it returns the values on nodes where\n    nodes are sorted in lexicographic order of their corresponding\n    branches. *)\n\nSection dft_std.\n\n  Variable X : Type.\n\n  Implicit Types (l : list bool) (ll: list (list bool)) (t : bt X).\n\n  (* Depth first traversal, VERY standard algo *)\n\n  Fixpoint dft_std t : list X :=\n    match t with \n      | leaf x => x::nil\n      | node u x v => x::dft_std u++dft_std v\n    end.\n\n  Fact dft_std_length t : length (dft_std t) = m_bt t.\n  Proof. induction t; simpl; repeat rewrite app_length; omega. Qed.\n\n  (* The tree branches by Depth First Traversal *)\n\n  Fixpoint dft_br t : list (list bool) :=\n    nil::match t with \n           | leaf _     => nil\n           | node u _ v => map (cons false) (dft_br u) ++ map (cons true) (dft_br v)\n         end.\n\n  (* dft_br corresponds to dft_std *)\n\n  Theorem dft_br_std t : Forall2 (bt_path_node t) (dft_br t) (dft_std t).\n  Proof.\n    induction t as [ | ? Hu ? ? Hv ]; simpl; repeat constructor.\n    apply Forall2_app; apply Forall2_map_left; [ revert Hu | revert Hv ];\n      apply Forall2_mono; constructor; auto.\n  Qed.\n\n  (* number of branches equals size of tree *)\n\n  Fact dft_br_length t : length (dft_br t) = m_bt t.\n  Proof. rewrite (Forall2_length (dft_br_std t)), dft_std_length; trivial. Qed.\n\n  (* dft_br lists the branches of t *)\n\n  Fact dft_br_spec l t : In l (dft_br t) <-> btb t l.\n  Proof.\n    split.\n    + intros Hl; rewrite btb_spec.\n      destruct Forall2_In_inv_left with (1 := dft_br_std t) (2 := Hl) as (x & ? & ?).\n      exists x; auto.\n    + induction 1 as [ [] | | ]; simpl; auto; right; apply in_or_app;\n        [ left | right ]; apply in_map; auto.\n   Qed.\n\n  Corollary dft_br_spec_1 t : Forall (btb t) (dft_br t).\n  Proof. rewrite Forall_forall; intro; apply dft_br_spec. Qed.\n\n  (* the branches of t in dft_br t are sorted according to lb_lex *)\n\n  Fact dft_br_sorted t : sorted lb_lex (dft_br t).\n  Proof.\n    induction t; simpl.\n    + do 2 constructor.\n    + constructor.\n      * apply Forall_app; rewrite Forall_forall; intro; \n          rewrite in_map_iff; intros (? & ? & ?); subst; constructor.\n      * apply sorted_app.\n        - intros ? ?; do 2 rewrite in_map_iff.\n          intros (? & ? & ?) (? & ? & ?); subst; constructor.\n        - apply sorted_map; auto; constructor; auto.\n        - apply sorted_map; auto; constructor; auto.\n  Qed.\n\nEnd dft_std.\n\n(*\nRecursive Extraction dft_std.\n\nCheck dft_br_spec.\nCheck dft_br_sorted.\nCheck dft_br_std.\n*)\n", "meta": {"author": "DmxLarchey", "repo": "BFE", "sha": "0bf8376a80ca4378be1630689f6561744d43474e", "save_path": "github-repos/coq/DmxLarchey-BFE", "path": "github-repos/coq/DmxLarchey-BFE/BFE-0bf8376a80ca4378be1630689f6561744d43474e/coq/dft_std.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7358914670159324}}
{"text": "(** TP5 : Lemme du diamant, pour prouver la confluence du lambda-calcul *)\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(* 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 := fun x y => True.\nDefinition rel_empty A : relation A := fun x y => False.\nDefinition rel_id A : relation A := fun x y => x = y.\n\n(* Étant donnée une relation, définissez la relation réciproque. *)\nDefinition converse A (R : relation A) := 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 := forall n, R n n.\nDefinition symmetric A (R : relation A) : Prop := forall x y, R x y -> R y x.\n\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\nLemma R_star : incl A R star.\nProof.\n  intros x y Rxy.\n  apply (star_R x y y).\n    assumption.\n    constructor.\nQed.\n\nLemma star_trans : transitive A star.\nProof.\n  intros x y z p. induction p.\n    intros q. assumption.\n    intros q. apply star_R with b.\n      assumption.\n      apply IHp. assumption.\nQed.\n\nDefinition plus x y := exists z, R x z /\\ star z y.\n\nLemma R_plus : forall x y, R x y -> plus x y.\nProof.\n  intros x y p. exists y. split.\n    assumption.\n    constructor.\nQed.\n\nLemma plus_trans :transitive A plus.\nProof.\n  intros x y z p q.\n  destruct p as [s [p1 p2]].\n  destruct q as [t [q1 q2]].\n  exists s. split.\n    assumption.\n    apply star_trans with t.\n      apply star_trans with y.\n        assumption.\n        apply R_star. assumption.\n      assumption.\nQed.\n\nCheck star_trans.  \nEnd Star.\nCheck star_trans.\n\n\n\n\n(** Définition de la confluence **)\n\n\nVariable A : Type.\nVariable R : relation A.\n\nNotation \"a => b\" := (R a b) (at level 42).\nNotation \"a =>* b\" := (star _ R a b) (at level 42).\nNotation \"a =>+ b\" := (plus _ R a b) (at level 42).\n\n\nDefinition confl_wrt (x : A) :=\n  forall n1 n2:A, (x =>* n1 /\\ x =>* n2) -> exists p:A, n1 =>* p /\\ n2=>* p.\n\nDefinition confl := forall x, confl_wrt x.\n\n\n\n(** Propriété et lemme du diamant *)\n\n\nDefinition dia_wrt (x : A) := ...\n\nDefinition dia := forall x, dia_wrt x.\n\nLemma dia_one_square: dia -> forall x y, x =>* y -> forall z, x => z ->\n  exists k, z =>* k /\\ y => k.\nProof.\n...\nQed.\n\n\nLemma diaconfl : dia -> confl.\nProof.\n...\nQed.\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/tp5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7358914539445722}}
{"text": "Require Export Induction.\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\nDefinition fst (p:natprod) := match p with\n| pair x y => x\nend.\n\nDefinition snd (p:natprod) := match p with\n| pair x y => y\nend.\n\nTheorem surjective_pairing_n_m : forall n m : nat, pair n m = pair (fst (pair n m)) (snd (pair n m)).\nreflexivity.\nShow Proof.\nQed.\n\nTheorem surjective_pairing : forall p : natprod, p = pair (fst p) (snd p).\ndestruct p.\nreflexivity.\nShow Proof.\nQed.\n\nInductive natlist : Type :=\n| nil : natlist\n| cons : nat->natlist->natlist\n.\n\nFixpoint repeat (n count : nat) : natlist :=\nmatch count with\n| O => nil\n| S c' => cons n (repeat n c')\nend.\n\nFixpoint length (l : natlist) : nat :=\nmatch l with\n| nil => O\n| cons n rest => S (length rest)\nend.\n\nFixpoint append (l1 l2 : natlist) : natlist := match l1 with\n| nil => l2\n| cons n1 rest1 => cons n1 (append rest1 l2)\nend.\n\nDefinition head (l:natlist) (d:nat) : nat := match l with\n| nil => d\n| cons n _ => n\nend.\n\nDefinition tail (l:natlist) : natlist := match l with\n| nil => nil\n| cons _ t => t\nend.\n\nTheorem nil_app : forall l:natlist, (append nil l) = l.\nreflexivity.\nQed.\n\nTheorem tl_length_pred : forall l:natlist, pred (length l) = length (tail l).\ndestruct l;reflexivity.\nShow Proof.\nQed.\n\nTheorem append_associative : forall (l m n : natlist), (append (append l m) n) = (append l (append m n)).\ninduction l.\nreflexivity.\nsimpl.\nintros m n0.\nrewrite (IHl m n0).\nreflexivity.\nShow Proof.\nQed.\n\nFixpoint rev (l:natlist) : natlist :=\nmatch l with\n| nil => nil\n| cons n rest => (append rest (cons n nil))\nend.\n\nTheorem app_length : forall l1 l2 : natlist, length (append l1 l2) = (plus (length l1) (length l2)).\nintro l.\ninduction l.\nreflexivity.\nsimpl.\nintro l2.\nrewrite(IHl l2).\nreflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist, length (rev l) = length l.\ninduction l.\nreflexivity.\nsimpl.\nrewrite -> app_length.\nrewrite -> plus_commute.\nreflexivity.\nQed.\n\nInductive natoption : Type :=\n| Some : nat -> natoption\n| None : natoption\n.\n\nFixpoint nth (l:natlist) (n:nat) : natoption := match l with\n| nil => None\n| cons e rest => if beq_nat n O then Some e else nth rest (pred n)\nend.\n\nDefinition elim (o:natoption) (d:nat) := match o with\n| None => d\n| Some n => n\nend.\n\nInductive id : Type :=\n| Id : nat -> id.\n\nDefinition beq_id (i j : id) :=\nmatch i, j with\n| Id ni, Id nj => beq_nat ni nj\nend.\n\nInductive partial_map : Type :=\n| empty : partial_map\n| record : id -> nat -> partial_map -> partial_map.\n\nDefinition update (d:partial_map) (x:id) (value:nat) : partial_map := record x value d.\n\nFixpoint find (x:id) (d:partial_map) : natoption := match d with \n| empty => None\n| record y v d' => if beq_id x y then Some v else find x d'\nend.\n\n\n\n", "meta": {"author": "xavierdpt", "repo": "adventures", "sha": "038a17cf71d8f9690ad168b2592b12e61d2e6c32", "save_path": "github-repos/coq/xavierdpt-adventures", "path": "github-repos/coq/xavierdpt-adventures/adventures-038a17cf71d8f9690ad168b2592b12e61d2e6c32/trove/SF/V1/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7358914531343278}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  mult lf1 (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj292_coqofml_4wJa0p.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7358658091280016}}
{"text": "Require Export Reals.\nRequire Export QArith.\nRequire Export Qreals.\n\nOpen Scope R_scope.\nLemma inverses_of_nats_approach_0:\n  forall eps:R, eps > 0 -> exists n:nat, (n > 0)%nat /\\\n                                         / (INR n) < eps.\nProof.\nintros.\nassert (exists n:Z, (n>0)%Z /\\ / (IZR n) < eps).\nexists (up (/ eps)); split.\nassert (IZR (up (/ eps)) > 0).\napply Rgt_trans with (/ eps).\napply archimed.\nauto with *.\nassert ((0 < up (/ eps))%Z).\napply lt_IZR.\nsimpl.\nassumption.\nauto with *.\npattern eps at 2.\nrewrite <- Rinv_involutive.\napply Rinv_lt_contravar.\napply Rmult_lt_0_compat; auto with *.\napply Rlt_trans with (/ eps); auto with *.\napply archimed.\napply archimed.\nauto with *.\n\ndestruct H0 as [[ | p | p]].\ndestruct H0.\ncontradict H0; auto with *.\n\ndestruct H0.\nexists (nat_of_P p).\nsplit; auto with *.\n\ndestruct H0.\ncontradict H0.\nred; intro.\ninversion H0.\nQed.\n\nLemma Z_interpolation: forall x y:R, y > x+1 ->\n  exists n:Z, x < IZR n < y.\nProof.\nintros.\nexists (up x).\nsplit.\napply archimed.\napply Rle_lt_trans with (x+1).\npose proof (archimed x).\ndestruct H0.\nassert (x + (IZR (up x) - x) <= x + 1).\nauto with real.\nring_simplify in H2.\nassumption.\nassumption.\nQed.\n\nLemma rational_interpolation: forall (x y:R) (n:positive),\n  x<y -> IZR (' n) > 1/(y-x) ->\n  exists m:Z, x < Q2R (m # n) < y.\nProof.\nintros.\nassert (0 < / IZR (' n)).\ncut (0 < IZR (' n)); auto with real.\nreplace 0 with (IZR 0) by trivial.\ncut ((0 < ' n)%Z); auto with *.\napply IZR_lt.\nunfold Zlt.\ntrivial.\n\ndestruct (Z_interpolation (IZR (' n) * x)\n  (IZR (' n) * y)) as [m].\napply Rgt_minus in H.\nassert (IZR (' n) * (y - x) > 1).\nreplace 1 with ((1 / (y-x)) * (y-x)); try field.\napply Rmult_gt_compat_r; trivial.\nauto with real.\napply Rgt_minus in H2.\napply Rminus_gt.\nmatch goal with H2: ?a > 0 |- ?b > 0 => replace b with a end.\ntrivial.\nring.\n\nexists m.\nunfold Q2R.\nsimpl.\nreplace (INR (nat_of_P n)) with (IZR (' n)) by auto with real.\nreplace x with ((IZR (' n) * x) / IZR (' n)).\nreplace y with ((IZR (' n) * y) / IZR (' n)).\n\ndestruct H2.\nsplit.\napply Rmult_lt_compat_r; trivial.\napply Rmult_lt_compat_r; trivial.\nfield.\nauto with *.\nfield.\nauto with *.\nQed.\n\nLemma rationals_dense_in_reals: forall x y:R, x<y ->\n  exists q:Q, x < Q2R q < y.\nProof.\nintros.\npose (d := up (/ (y - x))).\nassert ((0 < d)%Z).\napply lt_IZR.\nsimpl.\napply Rlt_trans with (/ (y - x)).\napply Rgt_minus in H.\nauto with *.\napply archimed.\nassert (/ (y - x) < IZR d) by apply archimed.\ndestruct d as [|d|]; try discriminate H0.\n\ndestruct (rational_interpolation x y d) as [n]; trivial.\nreplace (1 / (y-x)) with (/(y-x)).\ntrivial.\nfield.\napply Rgt_minus in H.\nauto with real.\n\nexists (n # d); trivial.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/RationalsInReals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7357952390206309}}
{"text": "Section Negation.\n  Variables P Q R S T: Prop.\n\n  (* unfold not: expansion de la négation dans le but *)\n  (* unfold not in X: expansion de la négation dans l'hypothèse X *)\n  (* exfalso: transforme le but courant en False; c'est l'équivalent\n     de la règle d'élimination de la contradiction *)\n  (*unfold -> transformer ~p en p -> bottom*)\n  (*exfalso -> transforme une lettre en bottom*)\n  (* Executez cette preuve en essayant de comprendre le sens de chacune des nouvelles tactiques utilisées. *)\n  Lemma absurde_exemple: P -> ~P -> S.\n  Proof.\n    intros p np.\n    unfold not in np.\n    exfalso.\n    apply np.\n    assumption.\n  Qed.\n  \n  Lemma triple_neg_e : ~~~P -> ~P.\n  Proof.\n     intro H. \n     intro H0.\n     apply H.\n     intro H1.\n     apply H1; assumption.\n   Restart.  (* Annule la preuve en cours, et en commence un autre *)\n   unfold not.\n   auto.\n   (* auto est une tactique qui est capable de beaucoup, mais qu'on\n      s'interdira d'utiliser dans nos preuves *)\n   Qed.\n\n  (* Début des exercices *)\n\n  (* QUESTION: Remplacer les Admitted par des scripts de preuve *)\n  Lemma absurde: (P -> Q) -> (P -> ~Q) -> (P -> S).\n  Proof.\n    intros.\n    exfalso.\n    unfold not in H0.\n    apply H0.\n    assumption.\n    apply H.\n    assumption.\n  Qed.\n\n  Lemma triple_abs: ~P -> ~~~P.\n  Proof.\n    intro.\n    unfold not.\n    intros.\n    apply H0.\n    intro.\n    apply H.\n    assumption.\n  Qed.\n  \n  Lemma absurd' : (~P -> P) -> ~~P.\n  Proof.\n    intros.\n    unfold not.\n    intros.\n    apply H0.\n    apply H.\n    unfold not.\n    apply H0.\n  Qed.\n\n  Definition Peirce  := ((P -> Q) -> P) -> P.\n\n  (* On va prouver non-non-Peirce *)\n  Lemma Peirce_2 : ~~ Peirce.\n  unfold not.\n  intro.\n  apply H.\n  unfold Peirce in H.\n  unfold Peirce.\n  intro.\n  apply H0.\n  intro.\n  exfalso.\n  apply H.\n  intro.\n  assumption.\n  Qed.\n\n  (* Une série de séquents à prouver; à chaque fois, il faut\n  l'énoncer, en introduisant les hypothèses au moyen d'une\n  sous-section. *)\n\n  (* P->Q, R->~Q, P->R |- P->S *)\n\n  (* ~P->~Q |- ~~Q->~~P *)\n\n  (* P->~P |- ~P *)\n\n  (* ~~P |- ~P->~Q *)\n\n  (* P->~Q, R->Q |- P->~R *)\n\n  (* ~(P->Q) |- ~Q *)\n  \n\n  (* Séquents proposés en test par le passé *)\n\n  Section Test01.\n    \n    Hypothesis H: P->Q.\n\n    Lemma Ex01: ~(~Q->~P) -> R.\n    intro.\n    exfalso.\n    unfold not in H0.\n    apply H0.\n    intros.\n    apply H1.\n    apply H.\n    assumption.\n    Qed.\n  End Test01.\n\n  Section Test02.\n    Hypothesis H: ~(P->R).\n\n    Lemma Ex02: Q->(P->Q->R)->P.\n    intros.\n    unfold not in H.\n    exfalso.\n    apply H.\n    intro.\n    apply H1.\n    assumption.\n    assumption. \n    Qed.\n  End Test02.\n\n  Section Test03.\n    Hypothesis H: ~(Q->R).\n\n    Lemma Ex03: (P->Q->R)->(P->Q).\n    intros.\n    unfold not in H.\n    exfalso.\n    apply H.\n    intro.\n    apply H0.\n    assumption.\n    assumption.\n    Qed.\n  End Test03.\n\n  Section Test04.\n    Hypothesis H: ~~P.\n\n    Lemma Ex04: Q->(P->Q->False)->P.\n    unfold not in H.\n    intros.\n    exfalso.\n    apply H.\n    intro.\n    apply H1.\n    assumption.\n    assumption. \n    Qed.\n  End Test04.\n    \nEnd Negation.\n\n\n", "meta": {"author": "Anatgnr", "repo": "Logique-et-Preuve", "sha": "4fba761060910acb10f84dd5dda8e00eb82921db", "save_path": "github-repos/coq/Anatgnr-Logique-et-Preuve", "path": "github-repos/coq/Anatgnr-Logique-et-Preuve/Logique-et-Preuve-4fba761060910acb10f84dd5dda8e00eb82921db/negation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7357661172601204}}
{"text": "Require Export Poly.\n\nCheck (2 + 2 = 4).\n\nCheck (ble_nat 3 2 = false).\n\nCheck (2 + 2 = 5).\n\nTheorem plus_2_2_is_4:\n  2 + 2 = 4.\nProof. reflexivity. Qed.\n\nDefinition plus_fact :\n  Prop := 2 + 2 = 4.\nCheck plus_fact.\n\nTheorem plus_fact_is_true:\n  plus_fact.\nProof. reflexivity. Qed.\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\nCheck even.\nCheck (even 4).\nCheck (even 3).\n\nDefinition even_n__even_SSn (n:nat) : Prop :=\n  (even n) -> (even (S (S n))).\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\nDefinition teen : nat -> Prop := between 13 19.\nCheck teen.\n\nDefinition true_for_zero (P:nat -> Prop) : Prop := P 0.\n\nDefinition true_for_n__true_for_Sn (P:nat -> Prop) (n:nat) : Prop :=\n  P n -> P (S n).\n\nDefinition preserved_by_S (P:nat -> Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\nDefinition true_for_all_numbers (P:nat -> Prop) : Prop :=\n  forall n, P n.\n\nDefinition our_nat_induction (P:nat -> Prop) : Prop :=\n  (true_for_zero P) ->\n  (preserved_by_S P) ->\n  (true_for_all_numbers P).\n\nCheck our_nat_induction.\n\nInductive good_day: day -> Prop :=\n| gd_sat : good_day saturday\n| gd_sun : good_day sunday.\n\nTheorem gds : good_day sunday.\nProof.\n  apply gd_sun.\nQed.\n\nInductive day_before: day -> day -> Prop :=\n| db_tue : day_before tuesday monday\n| db_wed : day_before wednesday tuesday\n| db_thu : day_before thursday wednesday\n| db_fri : day_before friday thursday\n| db_sat : day_before saturday friday\n| db_sun : day_before sunday saturday\n| db_mon : day_before monday sunday.\n\nInductive fine_day_for_singing : day -> Prop :=\n| fdfs_any : forall d:day, fine_day_for_singing d.\n\nTheorem fdfs_wed : fine_day_for_singing wednesday.\nProof.\n  apply fdfs_any.\nQed.\n\nInductive ok_day: day -> Prop :=\n|okd_gd :\n   forall d,\n     good_day d -> ok_day d\n|okd_before:\n   forall d1 d2,\n     ok_day d2 -> day_before d2 d1 -> ok_day d1.\n\nDefinition okdw : ok_day wednesday :=\n  okd_before wednesday thursday\n             (okd_before thursday friday\n                         (okd_before friday saturday\n                                     (okd_gd saturday gd_sat)\n                                     db_sat)\n                         db_fri)\n             db_thu.\n\nTheorem okdw': ok_day wednesday.\nProof.\n  apply okd_before with (d2:=thursday).\n  apply okd_before with (d2:=friday).\n  apply okd_before with (d2:=saturday).\n  apply okd_gd. apply gd_sat.\n  apply db_sat.\n  apply db_fri.\n  apply db_thu.\nQed.\n\nDefinition okd_before2 := forall d1 d2 d3,\n  ok_day d3 ->\n  day_before d2 d1 ->\n  day_before d3 d2 ->\n  ok_day d1.\n\nTheorem okd_before2_vaild : okd_before2.\nProof.\n  unfold okd_before2.\n  intros.\n  generalize dependent H0.\n  apply okd_before.\n  generalize dependent H1.\n  apply okd_before.\n  apply H.\nQed.\n\nDefinition okd_before2_valid' : okd_before2 :=\n  fun (d1 d2 d3 : day) =>\n  fun (H : ok_day d3) =>\n  fun (H0 : day_before d2 d1) =>\n  fun (H1 : day_before d3 d2) =>\n  okd_before d1 d2 (okd_before d2 d3 H H1) H0.\n\nPrint okd_before2_vaild.\n\nCheck nat_ind.\n\nTheorem mult_0_r':\n  forall n:nat, n * 0 = 0.\nProof.\n  apply nat_ind.\n  Case \"0\". reflexivity.\n  Case \"S\". simpl. intros n IHn. apply IHn.\nQed.\n\nTheorem plus_one_r':\n  forall n:nat, n + 1 = S n.\nProof.\n  apply nat_ind.\n  Case \"0\".\n  simpl. reflexivity.\n  Case \"S\".\n  simpl. intros n IHn. apply eq_remove_S. apply IHn.\nQed.\n\nInductive yesno: Type :=\n| yes: yesno\n| no: yesno.\n\nCheck yesno_ind.\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\nCheck rgb_ind.\n\nInductive natlist: Type :=\n| nnil : natlist\n| ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n\nInductive natlist1 : Type :=\n| nnil1 : natlist1\n| ncons1 : natlist1 -> nat -> natlist1.\n\nCheck natlist1_ind.\n\nInductive ExSet : Type :=\n| con1 : forall b:bool, ExSet\n| con2 : nat -> ExSet -> ExSet.\n\nCheck ExSet_ind.\n\nInductive tree (X:Type) : Type :=\n| leaf : X -> tree X\n| node : tree X -> tree X -> tree X.\n\nCheck tree_ind.\n\nInductive mytype (X:Type) : Type :=\n| constr1: X -> mytype X\n| constr2: nat -> mytype X\n| constr3: mytype X -> nat -> mytype X.\n\nCheck mytype_ind.\n\nInductive foo (X Y:Type) : Type :=\n| bar: X -> foo X Y\n| baz: Y -> foo X Y\n| quux: (nat -> foo X Y) -> foo X Y.\n\nCheck foo_ind.\n\nInductive foo' (X:Type) : Type :=\n| C1 : list X -> foo' X -> foo' X\n| C2 : foo' X.\n\nCheck foo'_ind.\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\n\nDefinition P_m0r': nat -> Prop :=\n  fun n => n * 0 = 0.\n\nTheorem mult_0_r'' :\n  forall n:nat, P_m0r n.\nProof.\n  apply nat_ind.\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n\".\n  unfold P_m0r. simpl. intros n' IHn'.\n  apply IHn'.\nQed.\n\nInductive ev : nat -> Prop :=\n| ev_0: ev 0\n| ev_SS: forall n:nat, ev n -> ev (S (S n)).\n\nTheorem four_ev':\n  ev 4.\nProof.\n  apply ev_SS.\n  apply ev_SS.\n  apply ev_0.\nQed.\n\nPrint four_ev'.\n\nDefinition four_ev: ev 4 := ev_SS 2 (ev_SS 0 ev_0).\n\nTheorem ev_plus4':\n  forall n, ev n -> ev (4 + n).\nProof.\n  apply ev_ind.\n (* Case \"n=0\". *)\n  simpl. apply four_ev.\n  (* Case \"n = S n\". *)\n  simpl.\n  intros.\n  apply ev_SS.\n  apply H0.\nQed.\n\nPrint ev_plus4'.\n\nDefinition ev_plus4 : forall n, ev n -> ev (4 + n) :=\n  ev_ind (fun n : nat => ev (4 + n)) four_ev\n         (fun (n : nat) (_ : ev n) (H0 : ev (S (S (S (S n))))) =>\n            ev_SS (S (S (S (S n)))) H0).\n\nTheorem double_even: forall n, ev (double n).\nProof.\n  intros.\n  induction n.\n  simpl. apply ev_0.\n  simpl. apply ev_SS. apply IHn.\nQed.\n\nPrint double_even.\n\nTheorem ev_minus2:\n  forall n, ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct 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\nTheorem ev_minus2_n:\n  forall n, ev n -> ev (pred (pred n)).\n  intros n E.\n  destruct n as [| n'].\n  Case \"E = n\". simpl. apply E.\n  Case \"E = S n\". simpl.\n  Restart.\n  intros n E.\n  destruct 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\nTheorem ev_even:\n  forall 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\nTheorem ev_even_n:\n  forall n, ev n -> even n.\nProof.\n  intros n E. induction n as [| n' ].\n  unfold even. simpl. reflexivity.\n  unfold even.\nAdmitted.\n\nTheorem ev_sum:\n  forall n m, ev n -> ev m -> ev (n+m).\n  intros n m En Em.\n  induction En as [|n' En'].\n  simpl. apply Em.\n  simpl. apply ev_SS. apply IHEn'.\nQed.\n\nTheorem SSev_ev_firsttry:\n  forall n, ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  destruct E as [| n' E'].\nAdmitted.\n\nTheorem SSev_even:\n  forall n, ev (S (S n)) -> ev n.\n  intros n E.\n  inversion E as [| n' E'].\n  apply E'.\nQed.\n\nTheorem SSSSev_even:\n  forall n, ev (S (S (S (S n)))) -> ev n.\n  intros n E.\n  inversion E as [| n' E'].\n  apply SSev_even.\n  apply E'.\nQed.\n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros.\n  inversion H as [| n' H'].\n  inversion H'.\n  inversion H2.\nQed.\n\nTheorem ev_minus2':\n  forall n, ev n -> ev (pred (pred n)).\nProof.\n  intros n E. inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'.\nQed.\n\nTheorem ev_ev_even:\n  forall n m, ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m Hn Hm.\n  induction Hm.\n  apply Hn.\n  apply IHHm.\n  apply SSev_even.\n  apply Hn.\nQed.\n\nTheorem ev_plus_plus:\n  forall n m p, ev (n + m) -> ev (n + p) -> ev (m + p).\nProof.\n  intros n m p H.\n  apply ev_ev_even.\n  rewrite plus_swap. rewrite <- plus_assoc.\n  rewrite plus_swap. rewrite plus_assoc.\n  apply ev_sum. apply H.\n  SearchAbout (_ + _).\n  rewrite <- double_plus. apply double_even.\nQed.\n\nInductive MyProp : nat -> Prop :=\n| MyProp1: MyProp 4\n| MyProp2: forall n:nat, MyProp n -> MyProp (4 + n)\n| MyProp3: forall n:nat, MyProp (2 + n) -> MyProp n.\n\nTheorem MyProp_ten : MyProp 10.\nProof.\n  apply MyProp3.\n  simpl. assert(12=4+8) as H12.\n  Case \"Proof of assertion.\". reflexivity.\n  rewrite H12.\n  apply MyProp2.\n  assert(8=4+4) as H8.\n  Case \"Proof of assertion.\". reflexivity.\n  rewrite H8.\n  apply MyProp2.\n  apply MyProp1.\nQed.\n\nTheorem MyProp_0: MyProp 0.\nProof.\n  apply MyProp3. simpl.\n  apply MyProp3. simpl.\n  apply MyProp1.\nQed.\n\nTheorem MyProp_plustwo :\n  forall n:nat, MyProp n -> MyProp (S (S n)).\nProof.\n  intros.\n  rewrite <- plus_one_r'.\n  rewrite <- plus_one_r'.\n  rewrite <- plus_assoc.\n  simpl.\n  rewrite <- plus_comm.\n  apply MyProp3.\n  rewrite plus_assoc.\n  rewrite <- plus_comm.\n  simpl.\n  rewrite <- plus_comm.\n  apply MyProp2.\n  apply H.\nQed.\n\nTheorem MyProp_ev :\n  forall n:nat, ev n -> MyProp n.\nProof.\n  intros n E.\n  induction E as [|n' E'].\n  Case \"E = ev_0\".\n  apply MyProp_0.\n  Case \"E = ev_SS n' E'\".\n  apply MyProp_plustwo.\n  apply IHE'.\nQed.\n\n(*\n非形式的な証明.\n定理: 任意の自然数nにおいて,ev nならばMyProp nが成り立つ\n証明:\n   n = 0のとき,MyProp 0は補題MyProp_0で成立\n   n = S (S n')のとき,MyProp n'が成立すると仮定すると,\n   MyProp  S (S n')は,MyProp_plustwoが成立するので,帰納法により定理は成立する.\n *)\n\nTheorem ev_MyProp:\n  forall n:nat, MyProp n -> ev n.\nProof.\n  intros n P.\n  induction P.\n  Case \"n = 4\".\n  apply four_ev.\n  Case \"n = 4 + n'\".\n  apply ev_plus4.\n  apply IHP.\n  Case \"n = 2 + n'\".\n  simpl in IHP.\n  apply SSev_even.\n  apply IHP.\nQed.\n\nTheorem plus_assoc' :\n  forall n m p: nat, n+(m+p)=(n+m)+p.\nProof.\n  intros n m p.\n  induction n as [|n'].\n  Case \"n=0\".\n  simpl. reflexivity.\n  Case \"n=S n'\".\n  simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem plus_comm' :\n  forall n m : nat, n + m = m + n.\nProof.\n  induction n as [|n'].\n  Case \"n=0\".\n  intro m. rewrite plus_0_r. simpl. reflexivity.\n  Case \"n=S n'\".\n  intro m. simpl.\n  rewrite -> IHn'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_comm'' :\n  forall n m: nat, n + m = m + n.\n  induction m as [| m'].\n  Case \"m = 0\".\n  simpl. rewrite -> plus_0_r. reflexivity.\n  Case \"m = S m\".\n  simpl. rewrite <- IHm'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\nCheck ev_ind.\n\nTheorem ev_even':\n  forall n:nat,ev n -> even n.\nProof.\n  apply ev_ind.\n  Case \"ev_0\". unfold even. reflexivity.\n  Case \"ev_SS\". intros n' E' IHE'. unfold even. apply IHE'.\nQed.\n\nCheck list_ind.\nCheck MyProp_ind.\n\nTheorem ev_MyProp':\n  forall n:nat, MyProp n -> ev n.\nProof.\n  apply MyProp_ind.\n  Case \"n = 4\".\n  apply four_ev.\n  Case \"n = 4 + n'\".\n  intros.\n  apply ev_plus4.\n  apply H0.\n  Case \"n = 2 + n\".\n  intros.\n  simpl in H0.\n  apply SSev_even.\n  apply H0.\nQed.\n\nPrint ev_plus4'.\n\nPrint MyProp_ev.\n\nDefinition MyProp_ev' :\n  forall n:nat, ev n -> MyProp n :=\n  fun (n : nat) (E : ev n) =>\n    ev_ind (fun n : nat => MyProp n) MyProp_0\n           (fun (n' : nat) (_ : ev n') (H : MyProp n') => MyProp_plustwo n' H) n E.\n\nPrint ev_MyProp.\nPrint MyProp_ind.\n\nDefinition ev_MyProp'' :\n  forall n : nat, MyProp n -> ev n :=\n  fun (n : nat) (P : MyProp n) =>\n    MyProp_ind (fun m : nat => ev m) four_ev\n               (fun (m : nat) (_ : MyProp m) (H : ev m) => ev_plus4 m H)\n               (fun (m : nat) (_ : MyProp (2 + m)) (H : ev (2 + m)) => SSev_even m H) n P.\n\nModule Test.\nInductive foo (X : Set) (Y : Set) : Set :=\n     | foo1 : X -> foo X Y\n     | foo2 : Y -> foo X Y\n     | foo3 : foo X Y -> foo X Y.\nCheck foo_ind.\nEnd Test.\n\n\nInductive pal {X :Type}: list X -> Prop :=\n| c0 : pal []\n| c1 : forall n:X, pal [n]\n| c2 : forall (n:X) (l:list X), pal l -> pal (n :: (snoc l n)).\n\nTheorem pal_ref :\n  forall {X:Type} (l:list X), pal (l ++ rev l).\n  intros.\n  induction l.\n  Case \"l = []\".\n  simpl.\n  apply c0.\n  Case \"l = x::l'\".\n  simpl.\n  rewrite <- snoc_with_append.\n  apply c2.\n  apply IHl.\nQed.\n\nLemma rev_involutive:\n  forall {X:Type} (l:list X), rev (rev l) = l.\nProof.\n  intros.\n  induction l as [| n l'].\n  Case \"l=[]\".\n  simpl.\n  reflexivity.\n  Case \"l=[n::l]\".\n  assert (H1:forall {X:Type} (n: X) (l:list X), rev (snoc l n) = n::rev l).\n  intros.\n  induction l as [|n0' l0'].\n  SCase \"l0=[]\".\n  simpl.\n  reflexivity.\n  SCase \"l0=n0::l0'\".\n  simpl.\n  rewrite -> IHl0'.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite->H1.\n  rewrite->IHl'.\n  reflexivity.\nQed.\n\nTheorem pal_id_rev:\n  forall {X:Type} (l:list X), pal l -> l = rev l.\nProof.\n  intros.\n  induction H.\n  Case \"l = []\".\n  simpl.\n  reflexivity.\n  Case \"l = [n]\".\n  simpl.\n  reflexivity.\n  Case \"l = [n::l::n]\".\n  rewrite IHpal.\n  simpl.\n  rewrite rev_snoc.\n  simpl.\n  rewrite -> rev_involutive.\n  rewrite <- IHpal.\n  reflexivity.\nQed.\n\nInductive subseq : list nat -> list nat -> Prop :=\n| subseq_c1 : forall l, subseq [] l\n| subseq_c2 : forall sl l n m, subseq (n::sl) l -> subseq (n::sl) (m::l)\n| subseq_c3 : forall sl l n, subseq sl l -> subseq (n::sl) (n::l).\n\nCheck subseq.\nCheck (subseq [1,2,3] [1,2,3]).\nCheck subseq_c3.\n\nExample subseq_ex1:\n  subseq [] [1,2,3].\nProof.\n  apply subseq_c1.\nQed.\n\nExample subseq_ex2:\n  subseq [1] [1,2,3].\nProof.\n  apply subseq_c3.\n  apply subseq_c1.\nQed.\n\nExample subseq_ex3:\n  subseq [1,2,3] [1,2,3].\nProof.\n  apply subseq_c3.\n  apply subseq_c3.\n  apply subseq_c3.\n  apply subseq_c1.\nQed.\n\nExample subseq_ex4:\n  subseq [1,2,3] [1,2,7,3].\nProof.\n  apply subseq_c3.\n  apply subseq_c3.\n  apply subseq_c2.\n  apply subseq_c3.\n  apply subseq_c1.\nQed.\n\nExample subseq_ex5:\n  subseq [1,2,3] [5,6,1,9,9,2,7,3,8].\nProof.\n  apply subseq_c2.\n  apply subseq_c2.\n  apply subseq_c3.\n  apply subseq_c2.\n  apply subseq_c2.\n  apply subseq_c3.\n  apply subseq_c2.\n  apply subseq_c3.\n  apply subseq_c1.\nQed.\n\nTheorem subseq_involutive:\n  forall s1 s2:list nat,  s1 s2 -> subseq s1 s2.\nProof.\n  \n  \nModule Foo_Ind_principle.\n  Inductive foo (X: Set) (Y: Set) : Set :=\n  | foo1 : X -> foo X Y\n  | foo2 : Y -> foo X Y\n  | foo3 : foo X Y -> foo X Y.\n  Check foo_ind.\nEnd Foo_Ind_principle.\n\nModule R.\n\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\n  Check R.\n  Check (R 1 [1,2,1,0]).\n  Check (R 2 [1,0]).\n  Check (R 6 [3,2,1,0]).\n\n  Theorem r_1_list_1_2_1_0:\n    R 1 [1,2,1,0].\n  Proof.\n    apply c3.\n    apply c2.\n    apply c3.\n    apply c3.\n    apply c2.\n    apply c2.\n    apply c2.\n    apply c1.\n  Qed.\n\n  Theorem r_2_list_1_0:\n    R 2 [1,0].\n  Proof.\n    apply c2.\n    apply c2.\n    apply c1.\n  Qed.\nEnd R.", "meta": {"author": "seisyuu-hantatsushi", "repo": "coq-sf", "sha": "9f5088870d6734cebbbe9937f40b89b04ebd206b", "save_path": "github-repos/coq/seisyuu-hantatsushi-coq-sf", "path": "github-repos/coq/seisyuu-hantatsushi-coq-sf/coq-sf-9f5088870d6734cebbbe9937f40b89b04ebd206b/old/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7357442193558329}}
{"text": "(*\n   CPS その1、リストの長さ (len_cps)\n   2010_10_29\n   *)\n\n\nRequire Export List.\nRequire Export Arith.\n\n\n(**************)\n(* Len        *)\n(**************)\n\n\n(* 再帰関数 *)\nFixpoint len (lst : list nat) :=\n   match lst with \n     | nil => 0\n     | hd :: tl => S (len tl)\n   end.\nEval cbv in len (1::2::3::4::nil).\n\n\n(* CPS版 *)\nFixpoint len_cps (lst : list nat) (cont : nat -> nat) :=\n   match lst with \n     | nil => cont 0\n     | hd :: tl => len_cps tl (fun x => cont (S x))\n   end.\nEval cbv in len_cps (1::2::3::4::nil) (fun n:nat => n).\n\n\nLemma len_Sn :\n  forall n l, len (n::l) = S (len l).\nProof.\n  reflexivity.\nQed.\n\n\nEval cbv in len_cps (1::2::3::4::nil) (fun (r:nat) => r).  (* 4 *)\nEval cbv in len_cps (2::3::4::nil) (fun (r:nat) => S r).   (* 4 *)\n\n\nLemma len_cps_Sn :\n  forall n l f,\n    len_cps (n::l) f =\n    len_cps l (fun (r:nat) => f (S r)).\nProof.\n  intros.\n  simpl.\n  (* ここでGoalの左辺が右辺とおなじになるように、定理を用意するのだ。*)\n  reflexivity.\nQed.\n\n\nLemma eq_len_len_cps_aux :\n  forall (l : list nat) (a : nat),\n    (forall f, f (len l) = (len_cps l f)) /\\\n    (forall g, g (len (a::l)) = len_cps (a::l) g).\nProof.\n  intros.\n  induction l.\n  auto.\n\n\n  destruct IHl.\n  split.\n  apply H0.\n  \n  intros.\n  rewrite len_cps_Sn.\n  rewrite len_Sn.\n  simpl.\n  rewrite <- H.\n  reflexivity.\nQed.\nCheck eq_len_len_cps_aux.\n\n\nTheorem eq_len_len_cps :\n  forall (l : list nat) (n : nat) (f : nat -> nat), f (len l) = (len_cps l f).\nProof.\n  intros.\n  destruct (eq_len_len_cps_aux l n).\n  apply H.\nQed.\n\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/coq_cps_len.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7357442178172644}}
{"text": "(* exercise 8.5 *)\n(****************)\n\nRequire Export List.\nRequire Export Arith.\n(* In our exercises we consider strings with only opening and closing\n  parentheses. *)\n \nInductive par : Set :=\n  | open : par\n  | close : par.\n(* This is the definition of well-parenthesized expressions that is\n  probably the easiest to agree on. solution to \\ref{exo-wp-1} *)\n \nInductive wp : list par -> Prop :=\n  | wp_nil : wp nil\n  | wp_concat : forall l1 l2:list par, wp l1 -> wp l2 -> wp (l1 ++ l2)\n  | wp_encapsulate :\n      forall l:list par, wp l -> wp (open :: l ++ close :: nil).\n \nTheorem wp_oc : wp (open :: close :: nil).\nProof.\n change (wp (open :: nil ++ close :: nil)) in |- *.\n apply wp_encapsulate.\n apply wp_nil.\nQed.\n \nTheorem wp_o_head_c :\n forall l1 l2:list par, wp l1 -> wp l2 -> wp (open :: l1 ++ close :: l2).\nProof.\n intros l1 l2 H1 H2.\n replace (open :: l1 ++ close :: l2) with ((open :: l1 ++ close :: nil) ++ l2).\n -  apply wp_concat.\n    apply wp_encapsulate; trivial.\n    trivial.\n -  repeat (simpl in |- *; rewrite app_ass); simpl in |- *.\n    trivial.\nQed.\n \nTheorem wp_o_tail_c :\n forall l1 l2:list par,\n   wp l1 -> wp l2 -> wp (l1 ++ open :: l2 ++ close :: nil).\nProof. \n intros l1 l2 H1 H2;  apply wp_concat.\n -  trivial.\n - now  apply wp_encapsulate.\nQed.\n\n(* exercice 8.6 *)\n(****************)\n\n(* The structure of well-parenthesized expressions can actually be\n  represented by binary trees.*)\n \nInductive bin : Set :=\n  | L : bin\n  | N : bin -> bin -> bin.\n \nFixpoint bin_to_string (t:bin) : list par :=\n  match t with\n  | L => nil (A:=par)\n  | N u v => open :: bin_to_string u ++ close :: bin_to_string v\n  end.\n\n(**  Tests\n\nCompute bin_to_string (N (N L L) L).\n\nCompute bin_to_string (N (N L L) (N L L)).\n\n*)\n\nTheorem bin_to_string_wp : forall t:bin, wp (bin_to_string t).\nProof.\n simple induction t.\n -  simpl ; apply wp_nil.\n -  simpl ; intros t1 H1 t2 H2; apply wp_o_head_c; trivial.\nQed.\n\nHint Resolve wp_nil wp_concat wp_encapsulate wp_o_head_c wp_o_tail_c wp_oc.\n\nFixpoint bin_to_string' (t:bin) : list par :=\n  match t with\n  | L => nil (A:=par)\n  | N u v =>\n      bin_to_string' u ++ open :: bin_to_string' v ++ close :: nil\n  end.\n\n(* This is the correction for exercise 8.7 *)\n \nTheorem bin_to_string'_wp : forall t:bin, wp (bin_to_string' t).\nProof.\n simple induction t; simpl ; auto.\nQed.\n \n(*  This is the correction for exercise 8.24 *)\n\nInductive parse_rel : list par -> list par -> bin -> Prop :=\n  | parse_node :\n      forall (l1 l2 l3:list par) (t1 t2:bin),\n        parse_rel l1 (close :: l2) t1 ->\n        parse_rel l2 l3 t2 -> parse_rel (open :: l1) l3 (N t1 t2)\n  | parse_leaf_nil : parse_rel nil nil L\n  | parse_leaf_close :\n      forall l:list par, parse_rel (close :: l) (close :: l) L.\n\n \nTheorem parse_rel_sound_aux :\n forall (l1 l2:list par) (t:bin),\n   parse_rel l1 l2 t -> l1 = bin_to_string t ++ l2.\nProof.\n intros l1 l2 t H; elim H; clear H l1 l2 t.\n -  intros l1 l2 l3 t1 t2 Hp Hr1 Hp2 Hr2; simpl.\n     rewrite app_ass, Hr1; simpl.\n     now      rewrite Hr2.\n -  reflexivity.\n -  reflexivity.\nQed.\n \n\nTheorem parse_rel_sound :\n forall l:list par, (exists t : bin, parse_rel l nil t) -> wp l.\nProof.\n intros l [t H]; replace l with (bin_to_string t).\n -  apply bin_to_string_wp.\n -  symmetry;\n   replace (bin_to_string t) with (bin_to_string t ++ nil).\n   +  apply parse_rel_sound_aux; auto.\n   +  rewrite app_nil_end; auto.\nQed.\n\n(* correction to exercise 8.19 *)\n\n(* This is another possible definition of well-parenthesized expressions,\n  actually better adapted to showing that a given parser is correct. *)\n \nInductive wp' : list par -> Prop :=\n  | wp'_nil : wp' nil\n  | wp'_cons :\n      forall l1 l2:list par,\n        wp' l1 -> wp' l2 -> wp' (open :: l1 ++ close :: l2).\n\n(* To prove that the two definitions of well-parenthesized expressions are\n  equivalent, we need to prove that each predicate satisfies the constructors\n  of the other. *)\n \nTheorem wp'_concat :\n forall l1 l2:list par, wp' l1 -> wp' l2 -> wp' (l1 ++ l2).\nProof.\n intros l1 l2 H; generalize l2; clear l2.\n elim H.\n -  simpl; auto.\n -  intros l1' l2' Hb1' Hr1 Hb2' Hr2 l2 Hb2; simpl; rewrite app_ass.\n    simpl; apply wp'_cons; auto.\nQed.\n\nHint Resolve wp'_nil wp'_cons wp'_concat.\n\n(* This is the other constructor of wp, also satisfied by wp'. *)\n \nTheorem wp'_encapsulate :\n forall l:list par, wp' l -> wp' (open :: l ++ close :: nil).\nProof.\n intros l H; elim H; auto.\nQed.\n\n(* One interpretation of inductive definitions of predicates is that\n  the defined predicate is the least (with respect to implication) to\n  satisfy the constructors.  Thus, having proved that one of the predicates\n  satisfies the constructors of the other gives a simple way to prove\n  that one predicate implies the other.  The proof is done by induction\n  on the predicate. solution to \\ref{exo-wp-2}*)\n \nTheorem wp_imp_wp' : forall l:list par, wp l -> wp' l.\nProof.\n intros l H; elim H.\n -  apply wp'_nil.\n -  intros; apply wp'_concat; trivial.\n -  intros; apply wp'_encapsulate; trivial.\nQed.\n \nTheorem wp'_imp_wp : forall l:list par, wp' l -> wp l.\nProof.\n intros l H; elim H; auto.\nQed.\n\n(* correction of exercise 8.20 *)\n\n(* Here is an alternative definition, the same as before, but with the\n  second constructor that privileges parentheses on the right. *)\n \nInductive wp'' : list par -> Prop :=\n  | wp''_nil : wp'' nil\n  | wp''_cons :\n      forall l1 l2:list par,\n        wp'' l1 -> wp'' l2 -> wp'' (l1 ++ open :: l2 ++ close :: nil).\n\nHint Resolve wp''_nil wp''_cons.\n\n(* Obviously this one also satisfies the concatenation property. *)\n \nLemma wp''_concat :\n forall l1 l2:list par, wp'' l1 -> wp'' l2 -> wp'' (l1 ++ l2).\nProof.\n (* Only a proof by induction on the fact that the second list is \n    well-parenthesized   is needed. *)\n intros l1 l2 H1 H2; generalize l1 H1; clear H1 l1; elim H2.\n -  intros; rewrite <- app_nil_end; trivial.\n -  intros; rewrite ass_app; auto.\nQed.\n \n\nTheorem wp''_encapsulate :\n forall l:list par, wp'' l -> wp'' (open :: l ++ close :: nil).\nProof.\n intros l H; change (wp'' (nil ++ open :: l ++ close :: nil));\n auto.\nQed.\nHint Resolve wp''_concat wp''_encapsulate.\n\n(* solution to exercise \\ref{exo-wp-4} *)\n \nTheorem wp_imp_wp'' : forall l:list par, wp l -> wp'' l.\nProof.\n simple induction 1; auto.\nQed.\n \n\nTheorem wp''_imp_wp : forall l:list par, wp'' l -> wp l.\nProof.\n simple induction 1; auto.\nQed.\n\nFixpoint recognize (n:nat) (l:list par) {struct l} : bool :=\n  match l with\n  | nil => match n with\n           | O => true\n           | _ => false\n           end\n  | open :: l' => recognize (S n) l'\n  | close :: l' => match n with\n                   | O => false\n                   | S n' => recognize n' l'\n                   end\n  end.\n\n(* solution to exercise 8.21 *)\n \nTheorem recognize_complete_aux :\n forall l:list par,\n   wp l ->\n   forall (n:nat) (l':list par), recognize n (l ++ l') = recognize n l'.\nProof.\n intros l H; elim H.\n -  simpl; auto.\n -  intros l1 l2 H1 Hrec1 H2 Hrec2 n l'.\n    rewrite app_ass; transitivity (recognize n (l2 ++ l')); auto.\n -  intros l1 H1 Hrec n l'; simpl ; rewrite app_ass; rewrite Hrec;\n    simpl ; auto.\nQed.\n \nTheorem recognize_complete : forall l:list par, wp l -> recognize 0 l = true.\nProof.\n intros l H; rewrite (app_nil_end l),  recognize_complete_aux; auto.\nQed.\n\n(* solution of exercise 8.22 *)\n\nTheorem app_decompose :\n forall (A:Type) (l1 l2 l3 l4:list A),\n   l1 ++ l2 = l3 ++ l4 ->\n   (exists l1' : list A, l1 = l3 ++ l1' /\\ l4 = l1' ++ l2) \\/\n   (exists a : A,\n      exists l2' : list A, l3 = l1 ++ a :: l2' /\\ l2 = (a :: l2') ++ l4).\nProof.\n simple induction l1.\n -  intros l2 l3; case l3.\n   +  intros l4 H; left; exists (nil (A:=A)); auto.\n   +  intros a l3' Heq; right; exists a; exists l3'; auto.\n -  clear l1; intros a l1 Hrec l2 l3; case l3.\n   +  intros l4 H; left; exists (a :: l1); auto.\n   +  simpl ; intros a' l3' l4 Heq; injection Heq; intros Heq' Heq''.\n       elim Hrec with (1 := Heq').\n       intros [l1' [Heq3 Heq4]]; left; exists l1'; split; auto.\n       rewrite Heq''; rewrite Heq3; auto.\n       intros [a'' [l2' [Heq3 Heq4]]]; right; exists a'', l2'; split; auto.\n       rewrite Heq''; rewrite Heq3; auto.\nQed.\n\n\n(* length of lists is actually an abstract view of lists.  There is\n  a morphism between appending and addition.  This is already visible\n  in the structure of the two functions app and plus and the proof of\n  this theorem follows in a simple way the structure of app (and plus by\n  the same occasion). *)\n \nTheorem length_app :\n forall {A:Type} (l1 l2:list A), length (l1 ++ l2) = length l1 + length l2.\nProof.\n simple induction l1; simpl in |- *; auto.\nQed.\n \nTheorem length_rev : forall {A:Type} (l:list A), length l = length (rev l).\nProof.\n simple induction l; auto.\n -  intros a l' H; simpl in |- *.\n    rewrite length_app.\n    simpl in |- *; rewrite <- plus_n_Sm; rewrite H; auto with arith.\nQed.\n\n \nTheorem cons_to_app_end :\n forall {A:Type} (l:list A) (a:A),\n    exists b : A, exists l' : list A, a :: l = l' ++ b :: nil.\nProof.\n intros A l a.\n rewrite <- (rev_involutive (a :: l)).\n (* We want to use the first element of (rev (a :: l)) but we\n  need to say that this list has at least one element. *)\n assert (H : 0 < length (rev (a :: l)))\n  by  (rewrite <- length_rev; simpl ; auto with arith).\n \n destruct (rev (a :: l)) as [ | a0 l0].\n -  (* If (rev (cons a l)) was nil, then there would be a contradiction. *)\n   simpl ; elim (lt_n_O 0); auto.\n -  exists a0,  (rev l0); simpl ; auto.\nQed.\n \n\nTheorem last_same :\n forall {A:Type} (a b:A) (l1 l2:list A),\n   l1 ++ a :: nil = l2 ++ b :: nil -> l1 = l2 /\\ a = b.\nProof.\n intros A a b l1 l2 H.\n assert (e: a :: rev l1 = b :: rev l2).\n -  repeat rewrite <- rev_unit; now rewrite H.\n -  injection e; intros H1 H2; split; auto.\n    rewrite <- (rev_involutive l1), H1; apply rev_involutive.\nQed.\n \nTheorem wp_remove_oc_aux :\n forall l:list par,\n   wp l ->\n   forall l1 l2:list par, l1 ++ l2 = l -> wp (l1 ++ open :: close :: l2).\nProof.\n intros l H; elim H.\n -\n (* In the first case l is the empty list, there is only one way to insert\n  an open-string pair.  We use the theorem app_eq_nil to determine\n  l1 and l2.  This theorem has implicit arguments. *)\n \n intros l1 l2 H1; elim (app_eq_nil _ _ H1); auto.\n simpl in |- *; intros Heq1 Heq2; rewrite Heq1; rewrite Heq2; apply wp_oc.\n\n -  (* In the second case l is already a concatenation of two well-parenthesized\n    expressions l1 and l2.  We need to now whether the open-close pair is\n   inserted in l1' or in l2', the theorem app_decompose helps here. *)\n   intros l1 l2 Hp1 Hr1 Hp2 Hr2 l3 l4 Heq.\n   elim app_decompose with (1 := Heq).\n   intros [l1' [Heq1 Heq2]]; rewrite Heq1, app_ass;\n   apply wp_concat; auto.\n   intros [a' [l2' [Heq1 Heq2]]].\n   rewrite Heq2.\n   repeat rewrite app_comm_cons.\n   rewrite ass_app.\n  apply wp_concat; auto.\n\n- (* In the third case, we have to check three possibilities: either\n   the open-close pair has been inserted before the existing open character,\n  or between the two parentheses, or after. *)\n idtac.\n intros l' Hp'' Hrec l1; case l1.\n simpl ; intros l2 Heq; rewrite Heq.\n change (wp (open :: nil ++ close :: open :: l' ++ close :: nil));\n auto.\n simpl; intros c l1' l2; case l2.\n(* If l2 is nil, then the open-close pair was introduced after the\n  closing parenthesis. *)\n +  intros Heq; injection Heq; intros Heq1 Heq2.\n    rewrite <- app_nil_end in Heq1; rewrite Heq1; rewrite Heq2.\n    rewrite app_comm_cons.\n    apply wp_concat; auto.\n + (* if l2 is non nil then the open-close pair was introduced between the\n   parentheses *)\n intros c' l2'; elim (cons_to_app_end  l2' c').\n intros c'' [l2'' Heq]; rewrite Heq.\n rewrite ass_app; intros Heq1.\n injection Heq1; intros Heq2 Heq3; elim last_same with (1 := Heq2).\n intros Heq4 Heq5; rewrite Heq5; rewrite Heq3.\n change (wp (open :: l1' ++ (open :: close :: l2'') ++ close :: nil)) .\n rewrite ass_app; auto.\nQed.\n \nTheorem wp_remove_oc :\n forall l1 l2:list par, wp (l1 ++ l2) -> wp (l1 ++ open :: close :: l2).\nProof.\n intros; apply wp_remove_oc_aux with (l := l1 ++ l2); auto.\nQed.\n \nFixpoint make_list (A:Type) (a:A) (n:nat) {struct n} : \n list A := match n with\n           | O => nil (A:=A)\n           | S n' => a :: make_list A a n'\n           end.\n \nTheorem make_list_end :\n forall (A:Type) (a:A) (n:nat) (l:list A),\n   make_list A a (S n) ++ l = make_list A a n ++ a :: l.\nProof.\n simple induction n; simpl.\n -  trivial.\n-  intros n' H l; rewrite H; trivial.\nQed.\n\n(* Now we want to express that only well-parenthesized expressions are accepted.  Again,\n  we prove a more general statement, where n is understood as the number of\n  unmatched opening parentheses recognized so far. *)\n \nTheorem recognize_sound_aux :\n forall (l:list par) (n:nat),\n   recognize n l = true -> wp (make_list _ open n ++ l).\nProof.\n simple induction l; simpl.\n-  intros n; case n.\n   simpl ; intros; apply wp_nil.\n   intros n' H; discriminate H.\n-  intros a; case a; simpl ; clear a.\n   + intros l' H n H0.\n     rewrite <- make_list_end; auto.\n   +  intros l' H n; case n; clear n.\n      intros H'; discriminate H'.\n      intros n H0; rewrite make_list_end; apply wp_remove_oc;auto.\nQed.\n\n(* The soundness statement is the general statement specialized to value 0.\n *)\n \nTheorem recognize_sound : forall l:list par, recognize 0 l = true -> wp l.\nProof.\n intros l H; generalize (recognize_sound_aux _ _ H); simpl; auto.\nQed.\n\n(* Now we want to write a real parser, that is, a function that constructs \n  a term representing the structure of the string.\n  The parsing function is a tail-recursive representation of a stack automaton.\n   The argument s is the stack, the argument t is the tree representing the\n  the last well-formed expression that was recognized.  The return value is\n  None if the string is rejected and (Some t) if the string is accepted.  In\n  this case one should be able to reconstruct the recognized string from t,\n  but this is done later as another exercise. *)\n \n\n(* exercise 8.23 *)\nFixpoint parse (s:list bin) (t:bin) (l:list par) {struct l} : \n option bin :=\n  match l with\n  | nil => match s with\n           | nil => Some t\n           | _ => None (A:=bin)\n           end\n  | open :: l' => parse (t :: s) L l'\n  | close :: l' =>\n      match s with\n      | t' :: s' => parse s' (N t' t) l'\n      | _ => None (A:=bin)\n      end\n  end.\n\n(* The length of the stack plays the same role as argument n in the\n  function recognize. *)\n \nTheorem parse_reject_indep_t :\n forall (l:list par) (s:list bin) (t:bin),\n   parse s t l = None ->\n   forall (s':list bin) (t':bin),\n     length s' = length s -> parse s' t' l = None.\nProof.\n simple induction l.\n-  intros s; case s.\n   +  simpl; intros t H; discriminate H.\n   + intros t0 s0 t H s'; case s'.\n     *  simpl; intros t' Hle; discriminate Hle.\n     *  simpl; auto.\n-  intros a; case a; simpl; clear a; intros l' Hrec s.\n   + intros t H s' t' Hle.\n     apply Hrec with (1 := H).\n     simpl; auto with arith.\n   +  case s.\n      *  intros t H s'; case s'; simpl; auto.\n         intros t0 s0 t' Hle; discriminate Hle.\n      *  intros t0 s0 t H s'; case s'; simpl.\n         intros t' H0; discriminate H0.\n         intros t'0 s'0 t' Hle; apply Hrec with (1 := H).\n         simpl in Hle; auto with arith.\nQed.\n\n(* Rejected strings are those for which the return value is None. \n  In the completeness theorem we actually talk about the rejected strings.\n  Here it is more convenient to use wp' as the definition of well-parenthesized\n  expressions to organize the proof.*)\n \nTheorem parse_complete_aux :\n forall l:list par,\n   wp' l ->\n   forall (s:list bin) (t:bin) (l':list par),\n     parse s t (l ++ l') = None ->\n     forall (s':list bin) (t':bin),\n       length s' = length s -> parse s' t' l' = None.\nProof.\n simple induction 1.\n -  simpl; intros; eapply parse_reject_indep_t; eauto.\n -  intros l1 l2 Hp1 Hr1 Hp2 Hr2 s t l' Hrej s' t' Hle.\n    apply Hr2 with (s := s') (t := N t L).\n    change (parse (t :: s') L (close :: l2 ++ l') = None) in |- *.\n    simpl in Hrej.\n    rewrite app_ass in Hrej.\n    apply Hr1 with (1 := Hrej).\n    simpl; auto with arith.\n   auto.\nQed.\n \n\nTheorem parse_complete : forall l:list par, wp l -> parse nil L l <> None.\nProof.\n intros l H; replace l with (l ++ nil).\n red in |- *; intros H'.\n assert (e : parse nil L nil = None).\n -   apply parse_complete_aux with (2 := H'); auto.\n     apply wp_imp_wp'; auto.\n - discriminate.\n - rewrite <- app_nil_end; auto.\nQed.\n\n(* We will use bin_to_string' to map binary trees to strings of characters.\n  Stacks also represent strings. *)\n \nFixpoint unparse_stack (s:list bin) : list par :=\n  match s with\n  | nil => nil (A:=par)\n  | t :: s' => unparse_stack s' ++ bin_to_string' t ++ open :: nil\n  end.\n \nTheorem parse_invert_aux :\n forall (l:list par) (s:list bin) (t t':bin),\n   parse s t l = Some t' ->\n   bin_to_string' t' = unparse_stack s ++ bin_to_string' t ++ l.\nProof.\n simple induction l.\n-  intros s; case s.\n + simpl.\n   intros t t' H; injection H; intros Heq.\n   rewrite Heq; apply app_nil_end.\n +  simpl ; intros t0 s0 t t' H; discriminate H.\n-  intros a; case a; simpl; clear a; intros l' Hrec s.\n  +  intros t t' H; rewrite Hrec with (1 := H).\n     simpl; repeat (rewrite app_ass; simpl); auto.\n  + case s.\n   *  intros t t' H; discriminate H.\n   *  intros t0 s0 t t' Hp; rewrite Hrec with (1 := Hp);\n      simpl; repeat (rewrite app_ass; simpl); auto.\nQed.\n \nTheorem parse_invert :\n forall (l:list par) (t:bin), parse nil L l = Some t -> bin_to_string' t = l.\nProof.\n intros; replace l with (unparse_stack nil ++ bin_to_string' L ++ l); auto.\n apply parse_invert_aux; auto.\nQed.\n\n(* With this last theorem, we know that our parser is correct, that is\n  sound and complete. *)\n \nTheorem parse_sound :\n forall (l:list par) (t:bin), parse nil L l = Some t -> wp l.\nProof.\n intros l t H; rewrite <- parse_invert with (1 := H).\n apply bin_to_string'_wp.\nQed.\n\n(* Now, an exercise for which we do not give the solution is the exercise\n          where strings can also contain other characters that play no role\n          with  respect to parentheses, but should not be forgotten by the\n parser.*)\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/ch8_inductive_predicates/SRC/parsing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7357442068800882}}
{"text": "(**\nDeux objectifs dans ce TD :\n- deux structures linéaires qui serviront constamment,\n  les listes et les entiers naturels,\n  et les pricipes de récurrence associés\n- extensions des expressions arithmétiques\n*)\n\n(** * Listes et entiers naturels *)\n\n(** ** Listes *)\n\n(**\nOn oublie pour l'instant les entiers prédéfinis en Coq,\ncar on les refera à partir de zéro (c'est le cas de le dire).\n\nPour avoir des listes de quelque chose, on reprend donc le type\ndes couleurs vu auparavant.\nOn verra plus tard que, comme en OCaml, Coq permet de\ntravailler sur des listes d'éléments dont le type n'est pas fixé\na priori.\n *)\n\nInductive coulfeu : Set :=\n  | Vert : coulfeu\n  | Orange : coulfeu\n  | Rouge : coulfeu\n.\n\nInductive listc : Set  :=\n  | Nilc  : listc\n  | Consc : coulfeu -> listc -> listc\n.\n\nExample l1 := Consc Vert (Consc Rouge Nilc).\nExample l2 := Consc Orange (Consc Orange Nilc).\n\n(** La fonction la plus importante sur les listes est la concaténation,\n    vue en PF sous le nom append.\n    Elle se définit récursivement par analyse (ou filtrage) du *premier* argument\n *)\n\nFixpoint app u v : listc :=\n  match u with\n  | Nilc       => v\n  | Consc x u' => Consc x (app u' v)\n  end.\n\nCompute (app l1 l2).\n\n(** Exercice à faire à la maison :\n    tenter de définir app par filtrage du second argument *)\n\nFixpoint app' u v : listc :=\n    match v with\n    | Nilc => u\n    | Consc x v' => app' u v' (* FAUX *)\n    end.\n(* La structure du type listc rend cette façon de\n * définir app impossible *)\n\n(** Remarque : pour une définition récursive on écrit\n    [Fixpoint app u v := ]\n    plutôt que\n    [Definition app := fun u v => ].\n *)\n\n(** On commence par deux lemmes dont l'énoncé est semblable\n    ([Nilc] est neutre à gauche et à droite de [app])\n    mais dont les démonstrations sont très différentes *)\n\nTheorem app_Nilc_l : forall l, app Nilc l = l.\nProof.\n  intro l. cbn [app]. reflexivity.\nQed.\n\n(** Exprimer cette preuve en français *)\n\n(*\n  Soit l une liste (listc).\n  Si on applique `app` à `Nilc` et à `l` on obtient `l`\n  (on entre dans la première branche du match comme `u = Nilc`\n  donc `app` renvoie `v = l`).\n  Or `l = l`.\n  Donc `app Nilc l = l` quel que soit `l`.\n*)\n\nTheorem app_Nilc_r : forall l, app l Nilc = l.\nProof.\n  intro l. cbn [app]. (* aucun effet : pourquoi ? *)\n  (* Ce cbn  n'a aucun effet car on ne peut pas\n     déterminer quelle branche du match sera exécutée,\n     étant donné qu'on ne sait rien sur `l`. *)\n  (** terminer au moyen d'une preuve par récurrence *)\n  induction l.\n  - cbn [app]. reflexivity.\n  - cbn [app]. rewrite IHl. reflexivity.\nQed.\n\n(** Lemme fondamental : app est associative *)\n\nTheorem app_assoc : forall u v w, app u (app v w) = app (app u v) w.\nProof.\n  intros u v w. (** équivalent à intro u. intro v. intro w. *)\n  (** Comme app analyse son premier argument on tente une récurrence sur u *)\n  induction u as [ | x u' Hrecu'].\n  - cbn [app]. reflexivity.\n  - cbn [app]. rewrite Hrecu'. reflexivity.\nQed.\n\n(* ----------------------------------------------------------------------- *)\n(** DEBUT QUESTIONS FACULTATIVES (1) *)\n\nFixpoint renv u : listc :=\n  match u with\n  | Nilc       => Nilc\n  | Consc x u' => app (renv u') (Consc x Nilc)\n  end.\n\n(* Penser à utiliser les théorèmes précédents *)\nLemma app_renv : forall u v, renv (app u v) = app (renv v) (renv u).\nProof.\n  intros.\n  induction u.\n  - cbn [app renv]. rewrite app_Nilc_r. reflexivity.\n  - cbn [app renv]. rewrite IHu. rewrite app_assoc. reflexivity.\nQed.\n\nLemma renv_renv : forall u, renv (renv u) = u.\nProof.\n  intros.\n  induction u.\n  - cbn [renv]. reflexivity.\n  - cbn [renv].\n    rewrite app_renv.\n    rewrite IHu.\n    cbn [renv].\n    cbn [app].\n    reflexivity.\nQed.\n\n(** FIN QUESTIONS FACULTATIVES (1) *)\n(* ----------------------------------------------------------------------- *)\n\n(** ** Entiers naturels *)\n\n(** En mathématiques, les entiers ne sont plus une notion primitive depuis\n    les travaux de Dedekind et Peano au 19e siècle : ils sont obtenus\n    à partir de deux constructions élémentaires :\n    - l'entier nul, que l'on notera O ;\n    - le successeur d'un entier [n] déjà construit, que l'on notera [S n].\n    C'est exactement ce que l'on obtient avec le type inductif suivant.\n*)\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat\n.\n\nCheck (S (S O)). (** représente l'entier noté usuellement 2 *)\n\n(** En comparant les définitions de [nat] et de [listc], on voit\n    que les entiers naturels sont analogues à des listes décolorées.\n    Scoop : la récurrence structurelle sur nat correspond exactement à\n    la récurrence usuelle sur les entiers !\n    L'opération qui correspond à [app], mais sur [nat], est tout\n    simplement l'addition.\n    Les exercices suivants peuvent être résolus en procédant de manière\n    analogue à ce qui a été fait sur les listes.\n *)\n\nFixpoint plus (n m : nat) : nat :=\n    match n with\n    | O => m\n    | S n' => S (plus n' m)\n    end.\n(** remplacer \". Admitted\" par \" := bonne_définition .\" *)\n\nTheorem plus_0_l : forall n, plus O n = n.\n  intros.\n  cbn [plus]. reflexivity.\nQed.\n\nTheorem plus_0_r : forall n, plus n O = n.\n  intros.\n  induction n.\n  - cbn [plus]. reflexivity.\n  - cbn [plus]. rewrite IHn. reflexivity.\nQed.\n\n\n(** Pour les exercices suivants une récurrence structurelle simple suffit,\n    il faut bien choisir la variable qur laquelle elle porte *)\n\nTheorem plus_assoc : forall n m p, plus n (plus m p) = plus (plus n m) p.\n  intros.\n  induction n.\n  - cbn [plus]. reflexivity.\n  - cbn [plus]. rewrite IHn. reflexivity.\nQed.\n\n(* ----------------------------------------------------------------------- *)\n(** DEBUT QUESTIONS FACULTATIVES (2) *)\n\nTheorem plus_Sm_r : forall n m, plus n (S m) = S (plus n m).\n  intros.\n  induction n.\n  - cbn [plus]. reflexivity.\n  - cbn [plus]. rewrite IHn. reflexivity.\nQed.\n\n(* Penser à utliser les théorèmes précédents *)\nTheorem plus_com : forall n m, plus n m = plus m n.\n  intros.\n  induction n.\n  - cbn [plus]. rewrite plus_0_r. reflexivity.\n  - cbn [plus]. rewrite IHn. rewrite plus_Sm_r. reflexivity.\nQed.\n\n(** Longueur d'une liste :\n    il est plus simple de la définir avec [S] plutôt qu'avec [plus]\n*)\nFixpoint long (l : listc) : nat :=\n    match l with\n    | Nilc => O\n    | Consc x xs => S (long xs)\n    end.\n\nTheorem long_app : forall u v, long (app u v) = plus (long u) (long v).\n  intros.\n  induction u.\n  - cbn [long app plus]. reflexivity.\n  - cbn [long app plus]. rewrite IHu. reflexivity.\nQed.\n(** FIN QUESTIONS FACULTATIVES (2) *)\n(* ----------------------------------------------------------------------- *)\n\n(** Les entiers naturels de Coq sont définis exactement comme ci-dessus *)\n\n(** On annule ce qui a été fait depuis notre définition de nat,\n    pou retrouver la situation fournie par Coq. *)\nReset nat.\nPrint nat.\n\n(** Mais on a dispose alors facilités de notation, par exemple,\n    [S (S O)] s'écrit [2] *)\n\nFact deux : 2 = S (S O).\nProof. (** regarder le but écrit par Coq *) reflexivity. Qed.\n\n(** * Quelques commandes de recherche d'information *)\n\n(** Quelle est la fonction qui est derrière le symbole \"+\" ? *)\nLocate \"+\".\n(**  Print est connu *)\nPrint Nat.add.\n(** Intégration de l'espace de nommage Nat *)\nImport Nat.\nLocate \"+\".\n(* Quelles fonctions de type [nat -> nat -> nat] sot disponibles ? *)\nSearch (nat -> nat -> nat).\n\n\n(** * AST d'expressions arithmétiques, le retour *)\n\n(** On considère des expressions arithmétiques comprenant\n    non seulement des opération et des constantes, mais aussi des noms\n    de variables.\n    Pour simplifier on considère que ces variables s'écriraient \"x0\", \"x1\",\n    \"x2\", etc., ce qui permet de les représenter par un simple entier naturel.\n    Noter que les constructeurs [Ana] et [Ava] permettent de distinguer\n    la constante 2 de la variable x2.\n*)\n\nInductive aexp :=\n| Aco : nat -> aexp (* constantes *)\n| Ava : nat -> aexp (* variables *)\n| Apl : aexp -> aexp -> aexp\n| Amu : aexp -> aexp -> aexp\n| Amo : aexp -> aexp -> aexp\n.\n\n(* Définir les expressions aexp correspondant à\n  (1 + x2) * 3 et  (x1 * 2) + x3\n *)\n\n Example expr1 := Amu (Apl (Aco 1) (Ava 2)) (Aco 3).\n Example expr2 := Apl (Amu (Ava 1) (Aco 2)) (Ava 3).\n\n\n(** Pour évaluer une expression représentée par un tel AST,\n    on considère un *état*, c'est à dire une association entre\n    chaque nom de variable et un valeur dans [nat].\n    On choisit de représenter un tel état par une liste d'entiers,\n    avec comme convention :\n    - le premier élément de cette liste est la valeur associée à x0\n    - le second élément de cette liste est la valeur associée à x1\n    - et ainsi de suite ;\n    - pour les noms restants, la valeur associée est 0.\n    Par exemple, dans l'état Cons 3 (Cons 0 (Cons 8 Nil)),\n    la valeur associée à x0 est 3, la valeur associée à x1 est 0,\n    la valeur associée à x2 est 8, et la valeur associée à x3, x4, etc.\n    est 0.\n *)\n\nInductive state :=\n  | Nil : state\n  | Cons : nat -> state -> state\n.\n\n(* ----------------------------------------------------------------------- *)\n(** DEBUT QUESTIONS FACULTATIVES (3) *)\n\n(** Définir une fonction [get] qui rend la valeur associée à xi dans l'état s *)\n\nFixpoint get (i: nat) (s: state) : nat :=\n    match (i, s) with\n    | (0, Cons x s') => x\n    | (n, Cons x s') => get (n - 1) s'\n    | _ => 0\n    end.\n\n(** FIN QUESTIONS FACULTATIVES (3) *)\n(* ----------------------------------------------------------------------- *)\n\n(** Définir une fonction [eval] qui rend la valeur d'une aexp dans l'état s *)\n\n(** Même si la fonction get ci-dessus a été laissée 'Admitted', elle est \n    utilisable dans les questions suivantes.  *)\n\nFixpoint eval (a: aexp) (s: state) : nat :=\n    match a with\n    | Aco c => c\n    | Ava x => get x s\n    | Apl x y => (eval x s) + (eval y s)\n    | Amu x y => (eval x s) * (eval y s)\n    | Amo x y => (eval x s) - (eval y s)\n    end.\n\n(* ----------------------------------------------------------------------- *)\n(** DEBUT QUESTIONS FACULTATIVES (4) *)\n\n(** Définir une fonction [renomme] qui prend une aexp [a] et rend [a] où\n    les variables correspondant à x0, x1, x2... ont été respectivement\n    renommées en x1, x2, x3...  *)\n\nFixpoint renomme (a: aexp) : aexp :=\n    match a with\n    | Aco c => Aco c\n    | Ava x => Ava (1 + x)\n    | Apl x y => Apl (renomme x) (renomme y)\n    | Amu x y => Amu (renomme x) (renomme y)\n    | Amo x y => Amo (renomme x) (renomme y)\n    end.\n\n(** Définir une fonction [decale] qui prend un état [s] et rend\n    l'état dans lequel la valeur de x0 est 0, \n    la valeur de x1 est la valeur de x0 dans [s],\n    la valeur de x2 est la valeur de x1 dans [s], \n    la valeur de x3 est la valeur de x2 dans [s], etc. \n    Indication : ce n'est PAS un Fixpoint *)\n\nDefinition decale (s : state) : state := Cons 0 s.\n\n(** Démontrer qu'évaluer une expression renommée dans un environnement\n    décalé rend la même chose qu'avant *)\n\nRequire Import Arith. Import Nat.\n\nLemma eval_renomme_decale : forall a s, eval a s = eval (renomme a) (decale s).\nProof.\n    intros.\n    induction a.\n    - cbn [renomme eval]. reflexivity.\n    - unfold decale. cbn [eval renomme get].\n      simpl. rewrite Nat.sub_0_r. reflexivity.\n    - cbn [eval renomme]. rewrite IHa1, IHa2. reflexivity.\n    - cbn [eval renomme]. rewrite IHa1, IHa2. reflexivity.\n    - cbn [eval renomme]. rewrite IHa1, IHa2. reflexivity.\nQed.\n\n(** FIN QUESTIONS FACULTATIVES (4) *)\n(* ----------------------------------------------------------------------- *)\n\n\n(* ----------------------------------------------------------------------- *)\n(** DEBUT QUESTIONS FACULTATIVES (5) *)\n\n(** ** Expressions booléennes *)\n\n(** Définir un type d'AST nommé bexp pour des expressions booléennes\n    comprenant :\n    - les constantes booléennes Btrue et Bfalse\n    - un opérateur booléen unaire Bnot\n    - des opérateurs booléens binaires Band et Bor\n    - un opérateur de comparaison représentant le test d'égalité\n      entre deux expressions arithmétiques\n*)\n\n(** L'environnenent initial de Coq comprend, en plus de [nat],\n    un type énuméré nommé [bool à deux valeurs nommées [true] et [false] \n    ainsi que des fonctions telles que la disjonction entre deux valeurs\n    de type [bool].\n    Vous pouvez découvrir tout cela au moyen de la commande \"Print bool\"\n    et de la commande Search indiquée ci-dessus, mais on vous demande de \n    reprogrammer les fonctions booléennes par vous-même en utilisant, comme \n    pour [coulfeu], match with suivant le schéma :\n\n      match blabla_booléen with\n      | true => ...\n      | false => ...\n      end\n\n    L'opération de comparaison entre deux entiers devra aussi être programmée.\n\n    Définir une fonction d'évaluation sur bexp en s'appuyant sur ces fonctions.\n*)\n\nInductive bexp :=\n  | Btrue : bexp\n  | Bfalse : bexp\n  | Bnot : bexp -> bexp\n  | Band : bexp -> bexp -> bexp\n  | Bor : bexp -> bexp -> bexp\n  | Beq : aexp -> aexp -> bexp\n  .\n\nFixpoint beval b s := match b with\n  | Btrue => true\n  | Bfalse => false\n  | Bnot x => negb (beval x s)\n  | Band x y => andb (beval x s) (beval y s)\n  | Bor x y => orb (beval x s) (beval y s)\n  | Beq x y => Nat.eqb (eval x s) (eval y s)\n  end.\n\n(** FIN QUESTIONS FACULTATIVES (5) *)\n(* ----------------------------------------------------------------------- *)\n", "meta": {"author": "elegaanz", "repo": "info4-ltpf", "sha": "1c2802dc05157ac781e07147763d35491f7995a6", "save_path": "github-repos/coq/elegaanz-info4-ltpf", "path": "github-repos/coq/elegaanz-info4-ltpf/info4-ltpf-1c2802dc05157ac781e07147763d35491f7995a6/TD03_nat_Exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.8947894569842487, "lm_q1q2_score": 0.7356861734351496}}
{"text": "Require Import MyTactics.\nRequire Import PreLattice.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import Classical.\n\nInstance NatJoinPreLattice : JoinPreLattice nat le :=\n{ join := max }.\nProof.\n* auto with arith.\n* auto with arith.\n* auto using Max.max_lub.\nDefined.\n\nInstance NatMeetPreLattice : MeetPreLattice nat le :=\n{ meet := min }.\nProof.\n* auto with arith.\n* auto with arith.\n* auto using Min.min_glb.\nQed.\n\nInstance NatHasBottom : HasBottom nat le :=\n{ bottom := 0 }.\nProof.\nintro t. auto with arith.\nQed.\n\nLemma not_empty_is_sup_in :\n  forall (P: nat -> Prop) (sup: nat),\n    (exists n, P n) ->\n    is_sup P sup ->\n    P sup.\nProof.\nintros P sup [n0 Hn0] H.\ngeneralize dependent P. revert n0. induction sup; intros n0 P Hn0 Hsup.\n* destruct Hsup. specialize (H n0 Hn0).\n  compute in H. destruct n0; trivial.\n  exfalso. omega.\n* destruct (eq_nat_dec n0 (S sup)).\n  + congruence.\n  + assert (n0 <= sup).\n    { destruct Hsup. specialize (H n0 Hn0). compute in H. omega. }\n    pose (P' n := P (S n)).\n    assert (exists n1, P' n1) as [n1 Hn1].\n    { apply NNPP. intro Hempty.\n      assert (forall n, ~ P' n) as HP' by firstorder. clear Hempty.\n      { unfold P' in HP'.\n        assert (is_upper_bound P 0) as H0.\n        { intros m Hm. destruct m.\n          - reflexivity.\n          - exfalso. apply (HP' _ Hm).\n        }\n        destruct Hsup as [_ HLUB].\n        specialize (HLUB _ H0). omega.\n      }\n    }\n    destruct Hsup as [HUB HLUB].\n    assert (is_sup P' sup) as Hsup'.\n    { unfold P'. split.\n      - intros m Hm. specialize (HUB _ Hm). omega.\n      - intros m Hm.\n        assert (S sup <= S m) as HSm.\n        { apply HLUB. intros k Hk.\n          destruct k. auto with arith.\n          assert (k <= m). { apply Hm. eauto. }\n          auto with arith.\n        }\n        auto with arith.\n    }\n    specialize (IHsup _ P' Hn1 Hsup').\n    assumption.\nQed.\n\n(** The set of all natural numbers. *)\nDefinition Naturals : nat -> Prop := fun _ => True.\n\nLemma Naturals_sup_directed : sup_directed Naturals.\nProof.\nsplit.\n* exists 0. compute. trivial.\n* intros m n Hm Hn. exists (max m n). splits.\n  - compute. trivial.\n  - auto with arith.\n  - auto with arith.\nQed.\n", "meta": {"author": "esope", "repo": "robustness_coq", "sha": "149b3b60f5f018237ad5371212cdb1e9e4603fdf", "save_path": "github-repos/coq/esope-robustness_coq", "path": "github-repos/coq/esope-robustness_coq/robustness_coq-149b3b60f5f018237ad5371212cdb1e9e4603fdf/NatLattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7356861678065504}}
{"text": "From Coq Require Import Arith.\nFrom Coq Require Import Relations.\nFrom KBase Require Import Tactics.\nFrom KBase Require Import Relations.\n\n(** Definition of the terms *)\nInductive tm : Set :=\n  | I : nat -> tm (* de Bruijn indices *)\n  | Abs : tm -> tm\n  | App : tm -> tm -> tm.\n\n(** Shifting de Bruijn indices in terms *)\n\n(* The function shift adds n to all indices greater or equal to k in the term t.\nThe index k takes into account the number of lambda abstraction *)\nFixpoint shift (t : tm) (n k : nat) : tm :=\n  match t with\n  | I i => if lt_dec i k then I i else I (i + n)\n  | Abs t => Abs (shift t n (k + 1))\n  | App t1 t2 => App (shift t1 n k) (shift t2 n k)\n  end.\n\n(* Let us prove some usefull theorems about shift. *)\n\nTheorem shift_0 : forall t k,\n  shift t 0 k = t.\nProof.\n  induction t; crush; autodestruct; crush.\nQed.\n#[export] Hint Resolve shift_0 : KBaseHints.\n#[export] Hint Rewrite shift_0 : KBaseHints.\n\nTheorem shift_merge : forall t n1 k1 n2 k2,\n  k1 <= k2 ->\n  k2 <= k1 + n1 ->\n  shift (shift t n1 k1) n2 k2 = shift t (n1 + n2) k1.\nProof.\n  induction t; crush; repeat (autodestruct; crush).\nQed.\n#[export] Hint Resolve shift_merge : KBaseHints.\n#[export] Hint Rewrite shift_merge : KBaseHints.\n\nTheorem shift_swap_le : forall t n1 k1 n2 k2,\n  k2 <= k1 ->\n  shift (shift t n1 k1) n2 k2 = shift (shift t n2 k2) n1 (k1 + n2).\nProof.\n  induction t; crush; repeat (autodestruct; crush).\nQed.\n#[export] Hint Rewrite shift_swap_le : KBaseHints.\n\n(* This theorem is the reverse of the preceding one *)\nTheorem shift_swap_ge : forall t n1 k1 n2 k2,\n  k2 >= k1 + n1 ->\n  shift (shift t n1 k1) n2 k2 = shift (shift t n2 (k2 - n1)) n1 k1.\nProof.\n  induction t; crush; repeat (autodestruct; crush).\nQed.\n#[export] Hint Rewrite shift_swap_ge : KBaseHints.\n\n(** Let us now define the substitution *)\nFixpoint subst (t u : tm) (k : nat) : tm :=\n  match t with\n  | I i => match lt_eq_lt_dec i k with\n            | inleft (left _) => I i\n            | inleft (right _) => shift u k 0\n            | inright _ => I (i - 1)\n           end\n  | Abs t => Abs (subst t u (k + 1))\n  | App t1 t2 => App (subst t1 u k) (subst t2 u k)\n  end.\n\n(** Theorems about the substitution function *)\nTheorem subst_shift_swap : forall t u k1 n2 k2,\n  k2 <= k1 ->\n  shift (subst t u k1) n2 k2 = subst (shift t n2 k2) u (k1 + n2).\nProof.\n  induction t; crush; repeat (autodestruct; crush).\nQed.\n#[export] Hint Resolve subst_shift_swap : KBaseHints.\n\nTheorem subst_shift_merge : forall t u k1 n2 k2,\n  k2 <= k1 ->\n  k1 < k2 + n2 ->\n  subst (shift t n2 k2) u k1 = shift t (n2 - 1) k2.\nProof.\n  induction t; crush; repeat (autodestruct; crush).\nQed.\n#[export] Hint Resolve subst_shift_merge : KBaseHints.\n\nTheorem subst_shift_shift : forall t u k1 n2 k2 n3 k3,\n  k1 + k3 < k2 ->\n  k2 <= k1 + k3 + 1 + (n3 - n2) ->\n  n2 <= n3 ->\n  subst (shift t n2 k2) (shift u n3 k3) k1 = \n  shift (subst t (shift u (n3 - n2) k3) k1) n2 (k2 - 1).\nProof.\n  induction t; crush; repeat (autodestruct; crush).\n  repeat match goal with\n  | [ |- context [shift (shift ?x ?n1 ?k1) ?k2 0]] => \n      rewrite (shift_swap_le x n1 k1 k2 0) by crush\n  | [ |- shift ?x ?n1 ?k1 = shift (shift ?x (?n1 - ?n2) ?k1) ?n2 ?k2 ] => \n      rewrite (shift_merge x (n1 - n2) k1 n2 k2) by crush\n  | [ |- context [?x - ?y + ?y]] => assert (x - y + y = x) by crush; auto\n  end.\nQed.\n#[export] Hint Resolve subst_shift_shift : KBaseHints.\n#[export] Hint Rewrite subst_shift_shift : KBaseHints.\n\n\n(** Also known as the substitution lemma *)\nTheorem subst_swap : forall t u1 k1 u2 k2,\n  k1 <= k2 ->\n  subst (subst t u1 k1) u2 k2 = subst (subst t u2 (S k2)) (subst u1 u2 (k2 - k1)) k1.\nProof.\n  induction t; crush; repeat (autodestruct; crush);\n  (* We are left with to cases where we need to massage the hypothesis\n     a little bit to apply subst_shift_swap and subst_shift_merge *)\n  match goal with\n  | [ |- subst (shift ?u1 ?k1 0) ?u2 ?k2 = shift (subst ?u1 ?u2 (?k2 - ?k1)) ?k1 0] =>\n        let H1 := fresh \"H1\" in\n        let H2 := fresh \"H2\" in\n        let H3 := fresh \"H3\" in\n        assert (H1 : 0 <= k2 - k1) by lia';\n        pose proof (subst_shift_swap u1 u2 (k2 - k1) k1 0 H1) as H2;\n        assert (H3 : k2 - k1 + k1 = k2) by lia';\n        rewrite H3 in H2;\n        auto\n  | [ |- shift ?u2 ?n2 0 = subst (shift ?u (S ?n2) 0) ?u1 ?k1] =>\n      let H1 := fresh \"H1\" in\n      let H2 := fresh \"H2\" in\n      assert (H1 : 0 <= k1) by lia';\n      assert (H2 : k1 < S n2) by lia';\n      pose proof (subst_shift_merge u2 u1 k1 (S n2) 0 H1 H2);\n      crush\n  end.\nQed.\n#[export] Hint Resolve subst_swap : KBaseHints.\n#[export] Hint Rewrite <- subst_swap : KBaseHints.\n\n(** Small steps *)\nInductive ss : tm -> tm -> Prop :=\n  | ss_left : forall t1 t1' t2, ss t1 t1' -> ss (App t1 t2) (App t1' t2)\n  | ss_right : forall t1 t2 t2', ss t2 t2' -> ss (App t1 t2) (App t1 t2')\n  | ss_abs : forall t t', ss t t' -> ss (Abs t) (Abs t') \n  | ss_beta : forall t u, ss (App (Abs t) u) (subst t u 0).\n\n#[export] Hint Constructors ss : KBaseHints.\n\nNotation \"ss*\" := (clos_refl_trans_1n tm ss).\n\nLemma ss_shift : forall t t' n k,\n  ss t t' ->\n  ss (shift t n k) (shift t' n k).\nProof.\n  intros t t' n k t_t'; \n  generalize dependent k;\n  induction t_t'; intro k; crush.\n  - pose proof (ss_beta (shift t n (k + 1)) (shift u n k));\n    rewrite (subst_shift_shift t u 0 n (k + 1) n k) in H by crush;\n    assert (H2 : k + 1 - 1 = k) by crush;\n    rewrite H2 in H;\n    assert (H3 : n - n = 0) by crush;\n    rewrite H3 in H;\n    rewrite (shift_0 u k) in H;\n    auto.\nQed.\n#[global] Hint Resolve ss_shift : KBaseHints.\n\nLemma ss_subst_left : forall t t' u k,\n  ss t t' ->\n  ss (subst t u k) (subst t' u k).\nProof.\n  intros t t' u k t_t';\n  generalize dependent k;\n  induction t_t'; crush; repeat (autodestruct; crush).\n  - pose proof (ss_beta (subst t u (k + 1)) (subst u0 u k)).\n    assert (H3 : 0 <= k) by crush.\n    pose proof (subst_swap t u0 0 u k H3) as H4.\n    assert (S k = k + 1) by crush.\n    assert (k - 0 = k) by crush.\n    crush.\nQed.\n#[global] Hint Resolve ss_subst_left : KBaseHints.\n\n(** We want to prove the confluence of the small steps relation. We will first\n        show that ss and pss defined below have the same reflexive transitive\n        closure. Then prove that pss is confluent, thus proving ss confluent.*)\n\n(** Parallel small steps *)\nInductive pss : tm -> tm -> Prop :=\n| pss_i : forall i, pss (I i) (I i)\n| pss_para : forall t1 t1' t2 t2', \n    pss t1 t1' -> \n    pss t2 t2' -> \n    pss (App t1 t2) (App t1' t2')\n| pss_abs : forall t t', \n    pss t t' -> \n    pss (Abs t) (Abs t') \n| pss_beta : forall t t' u u', \n    pss t t' -> \n    pss u u' -> \n  pss (App (Abs t) u) (subst t' u' 0).\n\n#[local] Hint Constructors pss : KBaseHints.\n\nNotation \"pss*\" := (clos_refl_trans_1n tm pss).\n\nLemma pss_refl : reflexive tm pss.\nProof.\n  intro t1;\n  induction t1; crush.\nQed.\n#[local] Hint Resolve pss_refl : KBaseHints.\n\nLemma inclusion_ss_pss : inclusion tm ss pss.\nProof.\n  intros x y x_y; induction x_y; crush.\nQed.\n#[local] Hint Resolve inclusion_ss_pss : KBaseHints.\n\nLemma inclusion_pss_ss_rt : inclusion tm pss ss*.\nProof.\n  intros x y x_y; induction x_y; crush.\n  - assert (H : ss* (App (Abs t) u) (App (Abs t') u')) by crush.\n    pose proof (ss_beta t' u').\n    crush.\nQed.\n#[local] Hint Resolve inclusion_pss_ss_rt : KBaseHints.\n\nLemma pss_shift : forall t t' n k,\n  pss t t' ->\n  pss (shift t n k) (shift t' n k).\nProof.\n  intros t t' n k t_t';\n  generalize dependent k; \n  induction t_t'; crush.\n  - specialize (IHt_t'1 (k + 1)).\n    specialize (IHt_t'2 k).\n    pose proof (pss_beta _ _ _ _ IHt_t'1  IHt_t'2) as H.\n    rewrite (subst_shift_shift t' u' 0 n (k + 1) n k) in H by crush.\n    assert (H2 : k + 1 - 1 = k) by crush.\n    rewrite H2 in H.\n    assert (H3 : n - n = 0) by crush.\n    rewrite H3 in H.\n    rewrite (shift_0 u' k) in H.\n    crush. \nQed.\n#[local] Hint Resolve pss_shift : KBaseHints.\n\nLemma pss_subst : forall t t' u u' k,\n  pss t t' ->\n  pss u u' ->\n  pss (subst t u k) (subst t' u' k).\nProof.\n  intros t t' u u' k t_t';\n  generalize dependent k;\n  induction t_t'; crush; repeat (autodestruct; crush).\n  - specialize (IHt_t'1 (k + 1) H).\n    specialize (IHt_t'2 k H).\n    pose proof (pss_beta _ _ _ _ IHt_t'1  IHt_t'2) as H2.\n    assert (H3 : 0 <= k) by crush.\n    pose proof (subst_swap t' u'0 0 u' k H3) as H4.\n    assert (S k = k + 1) by crush.\n    assert (k - 0 = k) by crush.\n    crush.\nQed.\n#[local] Hint Resolve pss_subst : KBaseHints.\n\n(* Now we can easily prove ss_subst_right *)\n(* Crush will use the fact that pss is sandwich between\n   ss and ss*. *)\nLemma ss_subst_right : forall t u u' k,\n  ss u u' ->\n  ss* (subst t u k) (subst t u' k).\nProof.\n  crush.\nQed.\n#[global] Hint Resolve ss_subst_right : KBaseHints.\n\nLemma ss_subst_para : forall t t' u u' k,\n  ss* t t' ->\n  ss* u u' ->\n  ss* (subst t' u' k) (subst t' u' k).\nProof.\n  crush.\nQed.\n#[global] Hint Resolve ss_subst_para : KBaseHints.\n\nFixpoint pss_normalizer (x : tm) : tm :=\n  match x with\n  | I i => I i\n  | Abs t => Abs (pss_normalizer t)\n  | App (Abs t) u => subst (pss_normalizer t) (pss_normalizer u) 0\n  | App t1 t2 => App (pss_normalizer t1) (pss_normalizer t2)\n  end.\n\nLemma Triangle_pss_normalizer : triangle_op pss pss_normalizer.\nProof.\n  intros x y x_y; induction x_y; crush; autodestruct; crush.\n  - inversion x_y1; subst.\n    inversion IHx_y1; subst.\n    crush.\nQed.\n#[local] Hint Resolve Triangle_pss_normalizer : KBaseHints.\n\nLemma pss_diamond : diamond pss.\nProof.\n  exact (triangle_diamond pss pss_normalizer Triangle_pss_normalizer).\nQed.\n#[local] Hint Resolve pss_diamond : KBaseHints.\n\nLemma ss_confluent : confluent ss.\nProof.\n  apply (triangle_confluent ss pss pss_normalizer); crush.\nQed.  \n#[global] Hint Resolve ss_confluent : KBaseHints.", "meta": {"author": "archambaultv", "repo": "KBase", "sha": "9e555c908979cb46838265278ac601c7ffcbf40d", "save_path": "github-repos/coq/archambaultv-KBase", "path": "github-repos/coq/archambaultv-KBase/KBase-9e555c908979cb46838265278ac601c7ffcbf40d/coq/LambdaCalculus/Terms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7356784689091721}}
{"text": "(** Can you write down three \"different\" proofs of transitivity (they should all be judgmentally different; [refl] should not prove any two of them the same. *)\n\nDefinition trans1\n: forall A (x y z : A),\n    x = y -> y = z -> x = z.\nintros. rewrite <- H in H0. apply H0. Defined.\nDefinition trans2\n: forall A (x y z : A),\n    x = y -> y = z -> x = z.\nintros. transitivity y. auto. auto. Defined.\nDefinition trans3\n: forall A (x y z : A),\n    x = y -> y = z -> x = z.\nintros. rewrite H. rewrite H0. auto. Defined.\n(** Now we have Coq check that they are not the same; these lines should compile unmodified. *)\n\nFail Check eq_refl : trans1 = trans2.\n\nFail Check eq_refl : trans2 = trans3.\n\nFail Check eq_refl : trans1 = trans3.\n\n\n(** Now prove that these are all equal (propositionally, but not judgmentally. *)\n\nDefinition trans_12\n: forall A (x y z : A) (H0 : x = y) (H1 : y = z),\n    trans1 A x y z H0 H1 = trans2 A x y z H0 H1.\nProof.\n  unfold trans1. unfold trans2. intros.\n  subst. auto.\nQed.\nDefinition trans_23\n: forall A (x y z : A) (H0 : x = y) (H1 : y = z),\n    trans2 A x y z H0 H1 = trans3 A x y z H0 H1.\nProof.\n  unfold trans2. unfold trans3. intros.\n  subst. auto.\nQed.\n\n(** We can also prove associativity. *)\n\nDefinition trans_assoc\n: forall A (x y z w : A) (H0 : x = y) (H1 : y = z) (H2 : z = w),\n    eq_trans H0 (eq_trans H1 H2) = eq_trans (eq_trans H0 H1) H2.\nProof. intros. subst. auto. Qed.\n\nDefinition trans_Vp\n: forall A (x y : A) (H : x = y),\n    eq_trans (eq_sym H) H = eq_refl.\nProof. intros. subst. auto. Qed.\n  \nDefinition trans_pV\n: forall A (x y : A) (H : x = y),\n    eq_trans H (eq_sym H) = eq_refl.\nProof. intros. subst. auto. Qed.\n  \nDefinition trans_1p\n: forall A (x y : A) (H : x = y),\n    eq_trans eq_refl H = H.\nProof. intros. subst. auto. Qed.\n\nDefinition trans_p1\n: forall A (x y : A) (H : x = y),\n    eq_trans H eq_refl = H.\nProof. intros. subst. auto. Qed.\n\nDefinition trans_sym\n: forall A (x y z : A) (H0 : x = y) (H1 : y = z),\n    eq_sym (eq_trans H0 H1) = eq_trans (eq_sym H1) (eq_sym H0).\nProof. intros. subst. auto. Qed.\n", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/Equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7355689091759368}}
{"text": "(* week-04_equational-reasoning.v *)\n(* FPP 2020 - YSC3236 2020-2021, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 06 Sep 2020, with the mirror function *)\n(* was: *)\n(* Version of 05 Sep 2020, with the fold-unfold lemmas for the power function *)\n(* was: *)\n(* Version of 05 Sep 2020 *)\n\n(* ********** *)\n\n(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name := intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith.\n\n(* ********** *)\n\nDefinition recursive_specification_of_addition (add : nat -> nat -> nat) :=\n  (forall y : nat,\n      add O y = y)\n  /\\\n  (forall x' y : nat,\n      add (S x') y = S (add x' y)).\n\nFixpoint add_v1 (i j : nat) : nat :=\n  match i with\n  | O =>\n    j\n  | S i' =>\n    S (add_v1 i' j)\n  end.\n\nLemma fold_unfold_add_v1_O :\n  forall j : nat,\n    add_v1 O j =\n    j.\nProof.\n  fold_unfold_tactic add_v1.\nQed.\n\nLemma fold_unfold_add_v1_S :\n  forall i' j : nat,\n    add_v1 (S i') j =\n    S (add_v1 i' j).\nProof.\n  fold_unfold_tactic add_v1.\nQed.\n\nTheorem add_v1_satisfies_the_recursive_specification_of_addition :\n  recursive_specification_of_addition add_v1.\nProof.\n  unfold recursive_specification_of_addition.\n  split.\n  \n  - exact fold_unfold_add_v1_O.\n\n  - exact fold_unfold_add_v1_S.\nQed.\n\n(* ********** *)\n\nFixpoint power (x n : nat) : nat :=\n  match n with\n  | O =>\n    1\n  | S n' =>\n    x * power x n'\n  end.\n\nLemma fold_unfold_power_O :\n  forall x : nat,\n    power x O =\n    1.\nProof.\n  fold_unfold_tactic power.\nQed.\n\nLemma fold_unfold_power_S :\n  forall x n' : nat,\n    power x (S n') =\n    x * power x n'.\nProof.\n  fold_unfold_tactic power.\nQed.\n\n(* ********** *)\n\nFixpoint fib_v1 (n : nat) : nat :=\n  match n with\n  | 0 =>\n    0\n  | S n' =>\n    match n' with\n    | 0 => 1\n    | S n'' => fib_v1 n' + fib_v1 n''\n    end\n  end.\n\nLemma fold_unfold_fib_v1_O :\n  fib_v1 O =\n  0.\nProof.\n  fold_unfold_tactic fib_v1.\nQed.\n\nLemma fold_unfold_fib_v1_S :\n  forall n' : nat,\n    fib_v1 (S n') =\n    match n' with\n    | 0 => 1\n    | S n'' => fib_v1 n' + fib_v1 n''\n    end.\nProof.\n  fold_unfold_tactic fib_v1.\nQed.\n\nCorollary fold_unfold_fib_v1_1 :\n  fib_v1 1 =\n  1.\nProof.\n  rewrite -> (fold_unfold_fib_v1_S 0).\n  reflexivity.\nQed.\n\nCorollary fold_unfold_fib_v1_SS :\n  forall n'' : nat,\n    fib_v1 (S (S n'')) =\n    fib_v1 (S n'') + fib_v1 n''.\nProof.\n  intro n''.\n  rewrite -> (fold_unfold_fib_v1_S (S n'')).\n  reflexivity.\nQed.\n\n(* ********** *)\n\nInductive binary_tree (V : Type) : Type :=\n| Leaf : V -> binary_tree V\n| Node : binary_tree V -> binary_tree V -> binary_tree V.\n\n(* ***** *)\n\nDefinition specification_of_mirror (mirror : forall V : Type, binary_tree V -> binary_tree V) : Prop :=\n  (forall (V : Type)\n          (v : V),\n      mirror V (Leaf V v) =\n      Leaf V v)\n  /\\\n  (forall (V : Type)\n          (t1 t2 : binary_tree V),\n      mirror V (Node V t1 t2) =\n      Node V (mirror V t2) (mirror V t1)).\n\n(* ***** *)\n\nFixpoint mirror (V : Type) (t : binary_tree V) : binary_tree V :=\n  match t with\n  | Leaf _ v =>\n    Leaf V v\n  | Node _ t1 t2 =>\n    Node V (mirror V t2) (mirror V t1)\n  end.\n\nLemma fold_unfold_mirror_Leaf :\n  forall (V : Type)\n         (v : V),\n    mirror V (Leaf V v) =\n    Leaf V v.\nProof.\n  fold_unfold_tactic mirror.\nQed.\n\nLemma fold_unfold_mirror_Node :\n  forall (V : Type)\n         (t1 t2 : binary_tree V),\n    mirror V (Node V t1 t2) =\n    Node V (mirror V t2) (mirror V t1).\nProof.\n  fold_unfold_tactic mirror.\nQed.\n\n(* ***** *)\n\nProposition there_is_at_least_one_mirror_function :\n  specification_of_mirror mirror.\nProof.\n  unfold specification_of_mirror.\n  split.\n  - exact fold_unfold_mirror_Leaf.\n  - exact fold_unfold_mirror_Node.\nQed.\n\n(* ***** *)\n\nTheorem mirror_is_involutory :\n  forall (V : Type)\n         (t : binary_tree V),\n    mirror V (mirror V t) = t.\nProof.\n  intros V t.\n  induction t as [v | t1 IHt1 t2 IHt2].\n  - rewrite -> (fold_unfold_mirror_Leaf V v).\n    exact (fold_unfold_mirror_Leaf V v).\n  - rewrite -> (fold_unfold_mirror_Node V t1 t2).\n    rewrite -> (fold_unfold_mirror_Node V (mirror V t2) (mirror V t1)).\n    rewrite -> IHt1.\n    rewrite -> IHt2.\n    reflexivity.\nQed.\n\n(* ********** *)\n\n(* end of week-04_equational-reasoning.v *)\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w04/week-04_equational-reasoning.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.73556890655739}}
{"text": "Require Import \n  Algebra.SetsC\n  Algebra.OrderC\n  Algebra.PreOrder\n  Types.List\n  Coq.Lists.List.\n\nImport ListNotations.\n\nLocal Open Scope FT.\n\nModule ML.\nSection FreeMeetLattice.\n\nContext {X : PreOrder}\n        {POX : PreO.t (le X)}.\n\nDefinition FreeML : PreOrder :=\n  {| PO_car := list X\n  ; le := fun a b => Each (fun ub => LSome (fun ua => ua <=[X] ub) a) b \n  |}.\n\nGlobal Instance PO : PreO.t (le FreeML).\nProof.\nconstructor; simpl; intros. \n- intros x' mem. econstructor. eassumption.\n  reflexivity.\n- unfold Each. intros. \n  specialize (X1 x0 X2). simpl in X1.\n  induction X1.\n  specialize (X0 _ S_member). simpl in X0.\n  induction X0.\n  econstructor. eassumption.\n  etransitivity; eassumption.\nQed.\n\nLemma FSubset_le (xs ys : FreeML) : (ys ⊆ xs)%list -> xs <= ys.\nProof.\nsimpl. unfold FSubset, Each.\nintros H x mem.\neexists x. apply H. assumption.\nreflexivity.\nQed.\n\nLocal Open Scope Subset.\n\nDefinition bmeet (xs ys : FreeML) : FreeML := xs ++ ys.\n\nLocal Infix \"++\" := bmeet.\n\nLemma bmeet_le_r (l r : FreeML)\n  : l ++ r <= r.\nProof.\nunfold bmeet. apply FSubset_le. apply FSubset_app_r.\nQed.\n\nLemma bmeet_le_l (l r : FreeML)\n  : l ++ r <= l.\nProof.\nunfold bmeet. apply FSubset_le. apply FSubset_app_l.\nQed.\n\nLemma app_le (xs ys : FreeML) : \n  xs <= ys -> xs <= (xs ++ ys).\nProof.\nsimpl. unfold bmeet, Each. intros H x mem.\napply member_app in mem. induction mem.\n- econstructor. eassumption. reflexivity.\n- apply H. assumption.\nQed.\n\nLemma le_app_r (xs xs' ys : FreeML)\n  : xs <= xs' -> (xs ++ ys) <= (xs' ++ ys).\nProof.\nsimpl. unfold Each, bmeet. intros H x mem.\napply member_app in mem. apply LSome_app.\ninduction mem.\n- left. apply H. assumption.\n- right. econstructor. eassumption. reflexivity. \nQed.\n\nDefinition inj (a : X) : FreeML := [a].\n\nLemma le_singleton (a b : X)\n  : a <= b -> inj a <= inj b.\nProof.\nsimpl; unfold Each, inj; intros H x mem.\napply member_singleton in mem.\nsubst. econstructor. econstructor. eassumption.\nQed.\n\nLemma le_singleton_opp (a b : X)\n  : inj a <= inj b -> a <= b.\nProof.\nsimpl; unfold Each, inj; intros H.\nspecialize (H _ here). induction H.\napply member_singleton in S_member.\nsubst. assumption.\nQed.\n\nLemma bmeet_comm (xs ys : FreeML)\n  : (xs ++ ys) <= (ys ++ xs).\nProof.\nsimpl. unfold Each, bmeet. intros x mem.\napply member_app in mem. apply LSome_app.\ninduction mem; [right | left]; \n  (econstructor; [eassumption | reflexivity]).\nQed.\n\nLemma le_app_l (ys ys' xs : FreeML)\n  : ys <= ys' -> (ys ++ xs) <= (ys' ++ xs).\nProof.\nintros H.\nrewrite (bmeet_comm ys).\netransitivity.\nFocus 2. eapply le_app_r. eassumption.\napply bmeet_comm.\nQed.\n\nLemma le_app_distr {xs xs' ys ys' : FreeML}\n  : xs <= xs' -> ys <= ys' -> (xs ++ ys) <= (xs' ++ ys').\nProof.\nsimpl. unfold Each, bmeet.\nintros Hx Hy x mem.\napply member_app in mem. apply LSome_app.\ninduction mem.\n- left. apply Hx. assumption.\n- right. apply Hy. assumption.\nQed.\n\nLemma le_cons (a b : X) (xs ys : FreeML)\n  : a <= b -> xs <= ys -> (inj a ++ xs) <=[FreeML] (inj b ++ ys).\nProof.\nintros H H'.\napply (@le_app_distr [a] [b] xs ys).\napply le_singleton. assumption. assumption.\nQed.\n\nLemma le_cons_r {xs ys : FreeML} {a : X}\n  (Ha : xs <= inj a) (Hys : xs <= ys)\n  : xs <=[FreeML] (inj a ++ ys).\nProof.\nsimpl. unfold Each.\nintros x mem. inv mem.\n- apply Ha. constructor.\n- apply Hys. assumption.\nQed.\n\nLemma le_app_each (l x y : FreeML)\n  (lx : l <= x) (ly : l <= y)\n  : l <= (x ++ y).\nProof.\nsimpl. unfold Each, bmeet. intros u mem.\napply member_app in mem. destruct mem.\n- apply lx. assumption.\n- apply ly. assumption.\nQed.\n\nLemma down_app (b c : FreeML) : (eq b ↓ eq c) === ⇓ (eq (b ++ c) : FreeML -> Prop).\nProof.\napply Same_set_iff.\nintros bc. split; intros.\n- destruct X0. le_downH d. le_downH d0.\n  le_down.\n  apply le_app_each; assumption.\n- le_downH X0. split; le_down.\n  etransitivity. eassumption. apply FSubset_le.\n  apply FSubset_app_l.\n  etransitivity. eassumption. apply FSubset_le. \n  apply FSubset_app_r.\nQed.\n\nLemma Each_monotone (P : X -> Type)\n  (Pmono : forall x y, x <= y -> P x -> P y)\n  (xs ys : FreeML)\n  (H : xs <= ys) : Each P xs -> Each P ys.\nProof.\nintros E x mem. specialize (H x mem).\nsimpl in H. induction H.\neapply Pmono. eassumption. apply E. assumption.\nQed.\n\nEnd FreeMeetLattice.\nEnd ML.\n\n\nArguments ML.FreeML : clear implicits.\n\nDelimit Scope FreeML_scope with FreeML.\nInfix \"∧\" := ML.bmeet (at level 60) : FreeML_scope.\n", "meta": {"author": "bmsherman", "repo": "topology", "sha": "c7bccdefb9e85978a362d17aa4c3ac4bf5855396", "save_path": "github-repos/coq/bmsherman-topology", "path": "github-repos/coq/bmsherman-topology/topology-c7bccdefb9e85978a362d17aa4c3ac4bf5855396/src/Algebra/FreeLattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7354383118340566}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq path order.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nAxiom replace_with_your_solution_here : forall {A : Type}, A.\n\nSection InsertionSort.\n\nVariable T : eqType.\nVariable leT : rel T.\nImplicit Types x y z : T.\n\n(** Insert an element [e] into a sorted list [s] *)\nFixpoint insert e s : seq T :=\n  if s is x :: s' then\n    if leT e x then e :: s\n    else x :: (insert e s')\n  else [:: e].\n\n(** Sort input list [s] *)\nFixpoint sort s : seq T :=\n  if s is x :: s' then insert x (sort s')\n  else [::].\n\nHypothesis leT_total : total leT.\nHypothesis leT_tr : transitive leT.\n\nLemma insert_path z e s :\n  leT z e ->\n  path leT z s ->\n  path leT z (insert e s).\nProof.\nmove: z.\nelim: s=> [/=| x1 s IHs] z.\n- by move => ->.\nmove=> z_le_e.\nmove=> /=.\ncase/andP=> z_le_x1 path_x1_s.\ncase: ifP.\n- by rewrite /= z_le_e path_x1_s => ->.\nmove=> /= e_gt_x1.\nrewrite z_le_x1.\nhave:= leT_total e x1.\nrewrite {}e_gt_x1 /= => x1_le_e.\nexact: IHs.\nQed.\n\nLemma insert_sorted e s :        \n  sorted leT s ->\n  sorted leT (insert e s).\nProof.\nrewrite /sorted.\ncase: s=> // x s.\nmove=> /=.\ncase: ifP; first by move=> /= ->->.\nmove=> e_gt_x.\napply: insert_path.\nhave:= leT_total e x.\nby rewrite e_gt_x /= => ->.\nQed.\n\nLemma sort_sorted s : sorted leT (sort s).\nProof.\n  rewrite /sorted.\n  elim : s.\n  - by rewrite //.\n  - move => a l IH.\n    move => //=.\n    move : (@insert_sorted a (sort l) IH).\n    rewrite /sorted.\n    done.\nQed.\n\n(** * Exercise *)\n\nLemma path_let e x l : leT e x -> path leT x l -> path leT e l.\nProof.\n  elim : l.\n  - by move => /=.\n  - move => a l ih /= le_e_x.\n    case/andP.\n    move => le_x_a.\n    move : (leT_tr le_e_x le_x_a).\n    move => h1 h2.\n    rewrite h1 h2.\n    done.\nQed.\n    \n\nLemma filter_keeps_sorted : forall l p x,\n    sorted leT (x :: l) ->\n    sorted leT (x :: filter p l).\nProof.\n  elim.\n  - by rewrite /=.\n  - move => e l IH p x /=.\n    case : ifP.\n    set ih := (IH p e).\n    move => h1.\n    case/andP.\n    move => le_x_e h2.\n    have h3 : sorted leT (e :: l).\n      by rewrite /sorted.\n      move : (ih h3).\n      rewrite /sorted /= le_x_e.\n        by done.\n  - move => h1.\n    case/andP.\n    move => le_x_e h2.\n    set ih := IH p x.\n    have h3 : sorted leT (x :: l).\n    rewrite /=.\n      by exact (path_let le_x_e h2).\n      move : (ih h3) => /=.\n      done.\nQed.\n\nLemma path_sorted a l : path leT a l -> sorted leT l.\nProof.\n  elim : l.\n  - by rewrite /=.\n  - move => e l ih /=; case/andP; by done.\nQed.\n\nLemma insert_in_sorted e l :\n  sorted leT (e :: l) -> insert e l = e :: l.\nProof.\n  case : l.\n  - by rewrite /=.\n  - move => a l.\n    rewrite /sorted /=.\n    case/andP => h1 h2.\n    rewrite h1.\n    by done.\nQed.    \n\nLemma sort_of_sorted l : sorted leT l -> (sort l) = l.\nProof.\n  elim : l.\n  - by rewrite /=.\n  - move => a l ih.\n    rewrite /=.\n    move => h1.\n    set h2 := path_sorted h1.\n    rewrite (ih h2).\n    have h3 : sorted leT (a :: l).\n    by rewrite /sorted.\n    by exact (insert_in_sorted h3).\nQed.\n\nLemma path_le a e l : leT e a -> path leT a l -> path leT e l.\nProof.\n  case l.\n  - by rewrite /=.\n  - move => x xs /= le_e_a.\n    case/andP => le_a_x.\n    move : (leT_tr le_e_a le_a_x) => le_e_x p_a_x.\n    by rewrite le_e_x p_a_x.\nQed.\n\nLemma insert_filtered_path (p : T -> bool) e l :\n  p e ->\n  path leT e l ->\n  insert e (filter p l) = e :: (filter p l).\nProof.\n  move : e.\n  elim : l.\n  - by rewrite /=.\n  - move => a l ih e pe /=.\n    case/andP => le_e_a p_a_l.\n  - case : ifP => pa.\n    by rewrite /= le_e_a.\n  - set p_e_l := path_le le_e_a p_a_l.\n    by rewrite (ih e pe p_e_l).\nQed.\n\nLemma filter_path p e l:\n  path leT e l -> path leT e (filter p l).\nProof.\n  move : e.\n  elim : l.\n  - by rewrite /=.\n  - move => a l ih e.\n    rewrite /=.\n    case/andP => le_e_a p_a_l.\n    set p_e_l := path_le le_e_a p_a_l.\n    case : ifP => pa.\n  - rewrite /=.\n    set h1 := (ih a p_a_l).\n    by rewrite le_e_a h1.\n  - by exact (ih e (path_le le_e_a p_a_l)).\nQed.\n    \nLemma insert_filtered (p : T -> bool) a l :      \n  p a\n  -> (sorted leT l)\n  -> insert a (filter p l) = filter p (insert a l).\nProof.\n  move : a.\n  elim : l => a.\n  - move => pa /=. by rewrite pa.\n  - move => l ih e pe.\n    rewrite /=.\n    move => path_al.\n    case : ifP => pa /=.\n  - case : ifP => le_e_a.\n  - by rewrite /= pe pa.\n  - rewrite {2}/filter pa.\n    by rewrite (ih e pe (path_sorted path_al)).\n  - case : ifP => le_e_a.\n  - set h1 := (path_le le_e_a path_al).\n    set h2 := (@filter_path p e l h1).\n    set h3 := (@insert_filtered_path p e l pe h1).\n    by rewrite h3 /= pe pa.\n  - rewrite /= pa.\n    set h1 := (@path_sorted a l path_al).\n    by rewrite (ih e pe h1).\nQed.\n\nLemma mis_insert_filtered (p : T -> bool) a l:\n  p a = false\n  -> sorted leT l\n  -> filter p (insert a l) = filter p l.\nProof.\n  move : a.\n  elim : l => e.\n  - move => npe.\n      by rewrite /= npe.\n  - move => l ih a npa.\n    rewrite /sorted /= => p_e_l.\n    case : ifP => le_a_e.\n  - by rewrite /= npa.\n  - rewrite /=.\n    case : ifP => pe.\n    by rewrite (ih a npa (path_sorted p_e_l)).\n  - by rewrite (ih a npa (path_sorted p_e_l)).\nQed.\n    \nLemma filter_sort p l :\n  filter p (sort l) = sort (filter p l).\nProof.\n  Show.\n  elim : l.\n  - by done.\n  - move => a l ih /=.\n    case : ifP.\n    rewrite /= => pa.\n    set h0 := sort_sorted l.\n    set h1 := @insert_filtered p a (sort l) pa h0.\n    by rewrite -h1 ih.\n  - move => npa.\n    set h1 := @mis_insert_filtered p a (sort l) npa (sort_sorted l).\n    by rewrite h1 ih.\nQed.\n    \n(** Hint: you will probably need to introduce a number of helper lemmas *)\n\nEnd InsertionSort.\n\nSection AccPredicate.\n\n(* To help you understand the meaning of the `Acc` predicate, here is how\n it can be used to write recursive functions without explicitly using recursion: *)\n\n\n(** * Exercise:  understand how `addn_f` works *)\nSection AdditionViaFix_F.\n\n(* First, let's redefine the addition on natural numbers\n   using the `Fix_F` combinator: *)\nAbout Fix_F.\n  \nPrint Fix_F.\n\n(* notice we do recursion on the `a : Acc R x` argument *)\n\n(* To define addition, we first need to choose the relation `R`\n   which \"connects\" successive value.\n   In the case of addition `R x y` can simply mean `y = x.+1` *)\n\nDefinition R m n := n = m.+1.\n\n(* This definition has to be transparent, otherwise\n   evaluation will get stuck *)\n\nDefinition esucc_inj : injective succn. by move=> n m []. Defined.\n\n(* Every natural number is accessible w.r.t. R defined above *)\nFixpoint acc (n : nat) : Acc R n :=\n  if n is n'.+1 then\n      Acc_intro n'.+1 (fun y (pf : n'.+1 = y.+1) =>\n                         eq_ind n' _ (acc n') y (esucc_inj pf))\n  else Acc_intro 0 (fun y contra => False_ind _ (O_S y contra)).\n\nCheck acc.\n(*\nBy the way, `forall n : nat, Acc R n` means that `R` is a well-founded\nrelation: https://en.wikipedia.org/wiki/Well-founded_relation.\n*)\nPrint well_founded.\n\nAbout Fix_F.\n\n(* Addition via `Fix_F` *)\nDefinition addn_f : nat -> nat -> nat :=\n  fun m =>\n    @Fix_F nat\n           R\n           (fun=> nat -> nat)\n           (fun m rec =>\n              match m return (_ = m -> nat -> nat) with\n              | m'.+1 => fun (eq : m = m'.+1) => succn \\o rec m' eq\n              | 0 => fun=> id\n              end erefl)\n           m\n           (acc m).\n\nCompute addn_f 4.\n\n(* This would get stuck if esucc *)\nCheck erefl : addn_f 2 4 = 6.\n\nLemma addn_equiv_addn_f :\n  addn =2 addn_f.\nProof. by elim=> // m IHm n; rewrite addSn IHm. Qed.\n\nEnd AdditionViaFix_F.\n\n(** Exercise: implement multiplication on natural numbers using `Fix_F`:\n    no explicit recursion, Program Fixpoint or things like that! *)\n\nSection MultiplicationViaFix_F.\n\nDefinition muln_f : nat -> nat -> nat :=\n  fun m n =>\n    @Fix_F nat\n           R\n           (fun => nat)\n           (fun k rec =>\n              match k return (_ = k -> nat) with\n              | (S k') =>\n                fun (eq : k = (S k')) => addn n (rec k' eq)\n              | O => fun => 0\n              end erefl)\n           m\n           (acc m).\n\nCompute muln_f 11.\n\n(* this should not fail *)\nCheck erefl : muln_f 21 2 = 42.\n\nLemma muln_equiv_muln_f :\n  muln =2 muln_f.\nProof.\n  elim => // m ih n.\n  rewrite mulSn (ih n) /muln_f /=.\n  done.\nQed.\n\nEnd MultiplicationViaFix_F.\n\n\n\nEnd AccPredicate.\n", "meta": {"author": "mbakhterev", "repo": "csclub-coq-21", "sha": "9634684301b000748479cf4427db5c5ff79d6a14", "save_path": "github-repos/coq/mbakhterev-csclub-coq-21", "path": "github-repos/coq/mbakhterev-csclub-coq-21/csclub-coq-21-9634684301b000748479cf4427db5c5ff79d6a14/hw09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7354280806775866}}
{"text": "Record iso (A B : Set) : Set :=\n  bijection {\n    A_to_B : A -> B;\n    B_to_A : B -> A;\n    A_B_A  : forall a : A, B_to_A (A_to_B a) = a;\n    B_A_B  : forall b : B, A_to_B (B_to_A b) = b\n  }.\n\nRequire Import Arith.\nRequire Import PeanoNat.\nRequire Import Omega.\n\nTheorem iso_refl : forall A : Set, iso A A.\nProof.\n  intros. apply (bijection _ _ (fun x => x) (fun x => x)).\n  auto. auto.\nQed.\n\nTheorem iso_sym : forall A B : Set, iso A B -> iso B A.\nProof.\n  intros. inversion H.\n  apply (bijection B A B_to_A0 A_to_B0).\n  auto. auto.\nQed.\n\nTheorem iso_trans : forall A B C : Set, iso A B -> iso B C -> iso A C.\nProof.\n  intros. inversion H. inversion H0.\n  apply (bijection A C (fun x => A_to_B1 (A_to_B0 x)) (fun x => (B_to_A0 (B_to_A1 x)))).\n  intros. specialize (A_B_A1 (A_to_B0 a)). rewrite A_B_A1. auto.\n  intros. specialize (B_A_B0 (B_to_A1 b)). rewrite B_A_B0. auto.\nQed.\n\nTheorem bijection_alt : forall (A B : Set) (A2B : A -> B) (B2A : B -> A),\n  (forall a, B2A (A2B a) = a) -> (forall b1 b2, B2A b1 = B2A b2 -> b1 = b2) -> iso A B.\nProof.\n  intros. assert(H' : forall b : B, A2B (B2A b) = b).\n  intros. specialize (H0 (A2B (B2A b)) b). specialize (H (B2A b)).\n  apply H0 in H. auto.\n  apply (bijection _ _ A2B B2A H H').\nQed.\n\nInductive nat_plus_1 : Set := null | is_nat (n : nat).\n\nDefinition nat_to_nat_plus_1 (n : nat) : nat_plus_1 :=\n  match n with\n  | 0 => null\n  | S n => is_nat n\n  end.\n\nDefinition nat_plus_1_to_nat (n : nat_plus_1) : nat :=\n  match n with\n  | null => 0\n  | is_nat n => S n\n  end.\n\nTheorem nat_iso_natp1 : iso nat nat_plus_1.\nProof.\n  apply (bijection _ _ nat_to_nat_plus_1 nat_plus_1_to_nat).\n  intros. destruct a. auto. auto.\n  intros. destruct b. auto. auto.\nQed.\n\nInductive nat_plus_nat : Set := left (n : nat) | right (n : nat).\n\nFixpoint nat_to_nat_plus_nat (n : nat) :=\n  match n with\n  | O => left O\n  | S n => match nat_to_nat_plus_nat n with\n           | left n => right n\n           | right n => left (S n)\n           end\n  end.\n\nDefinition nat_plus_nat_to_nat (a : nat_plus_nat) : nat :=\n  match a with\n  | left n' => n' * 2\n  | right n' => S (n' * 2)\n  end.\n\nTheorem nat_iso_natpnat : iso nat nat_plus_nat.\nProof.\n  apply (bijection _ _ nat_to_nat_plus_nat nat_plus_nat_to_nat);intros.\n  - induction a;simpl;auto;destruct (nat_to_nat_plus_nat);subst;simpl;omega.\n  - destruct b;simpl;induction n;auto;simpl in *;rewrite IHn;auto.\nQed.", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/Isomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7354197876583214}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (z : natural) : natural :=\n  plus (mult y x) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj157_coqofml_53ioJa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.735419785871635}}
{"text": "From NAT Require Import Peanos_axioms.\nFrom NAT Require Import Tutorial_World.\nFrom NAT Require Import Addition_World.\n\n\n\nSection Multiplication_World.\n(*Well, here we go again. One of Peanos axioms states that m * 0 = 0. However, the reverse has not been shown, so let us do it now.*)\nProposition zero_mul (m : nat) : 0 * m = 0.\nProof.\n    induction m.\n    rewrite mul_zero. \n    (*This base case is very interesting, since in some sense we are on the verge of derivining the fact that like terms commute. After all, you cannot tell the difference between 1*1 and 1*1, even though I swapped the order of the ones.(You cannot prove I did not)*)\n    reflexivity.\n    (*Now again we can use another axiom, and then easily simplify.*)\n    rewrite succ_dist. rewrite add_zero. exact IHm.\nQed.\n\nProposition mul_one (m : nat) : m*1 = m. \nProof.\n    induction m.\n    rewrite zero_mul. reflexivity.\n    rewrite succ_dist.\n    rewrite mul_zero. rewrite zero_add. reflexivity.\nQed.\n\nProposition one_mul (m : nat) : 1*m = m.\nProof.\n    induction m.\n    rewrite mul_zero. reflexivity.\n    rewrite succ_dist.\n    rewrite IHm.\n    rewrite succ_add. rewrite add_zero. reflexivity.\nQed.\n(*Now we will derive one of the most important propositions in this section. That is, leftward distribtivity. The best thing to do here is to try and see which inductive variable suits you the best. It is most likely possible using any of them, but not without tears.*)\nProposition mul_add ( t a b : nat) : t*(a + b) = (t * a) + (t * b).\nProof.\n    induction a. rewrite zero_add. rewrite mul_zero. rewrite zero_add. \n    reflexivity.\n    rewrite succ_dist. rewrite (commute (t *a)(t)).\n    symmetry. rewrite add_assoc. rewrite <- IHa.\n    rewrite commute. rewrite <- succ_dist. reflexivity.\nQed.\n(*This is another important result, we are now going to show that multiplicaiton is associative. If you are an algebrist proving this now seems out of order, since to prove a ring structure you usually show this first. Indeed, if this angers you feel free to contact Dr. Steven Clonz at sclontz@southalabama.edu. On the other hand if you are enjoying this expierence, and wish to find an outlet for your praise, then by all means try brandon.sisler1118@gmail.com. *)\nProposition mul_assoc (a b c : nat) : (a * b) * c = a * (b * c).\nProof.\n    induction c.\n    rewrite mul_zero. rewrite mul_zero. rewrite mul_zero. reflexivity.\n    rewrite succ_dist. rewrite succ_dist.\n    rewrite mul_add. rewrite IHc. reflexivity.\nQed.\n(*Now, in secret, we are going to use the next result to obtain a commutative ring. But in any case, this uses the same techniques you have been using the whole time.*)\nProposition succ_mul (a b : nat) : S (a) * b = a * b + b.\nProof.\n    induction b.\n    rewrite mul_zero. rewrite mul_zero. rewrite add_zero. reflexivity.\n    rewrite succ_dist. rewrite IHb. rewrite add_one. symmetry.\n    rewrite add_one. rewrite mul_add. rewrite mul_one. rewrite add_assoc.\n    rewrite add_assoc. rewrite <- (add_assoc (a)(b)(1)).\n    rewrite (commute (a)(b)). rewrite add_assoc. reflexivity.\nQed.\n(*Now, let us show rightward associativity.*)\nProposition add_mul (a b t : nat) : (a + b)*t = (a * t) + (b * t).\nProof.\n    induction t. rewrite mul_zero. rewrite mul_zero. rewrite mul_zero. \n    rewrite add_zero. reflexivity.\n\n    rewrite succ_dist. rewrite IHt. rewrite add_one.\n    rewrite mul_add. rewrite mul_add. rewrite mul_one. rewrite mul_one.\n    rewrite add_assoc. rewrite <-(add_assoc (b * t)(a)(b)). \n    rewrite (commute (b*t)(a)). rewrite (add_assoc (a)(b*t)(b)). \n    rewrite add_assoc. reflexivity.\nQed.\n(*Great, now that we have all these results we can get to the one that would have helped you all along, and hilariously relies on none of the previous parts. On the other hand, it was good to have not used this result quite yet, since now we have a good appreciation for how things can be proven when commutivity is not neccesarily true.*)\nProposition mul_comm (m n : nat) : m * n = n * m.\nProof.\n    induction n. rewrite mul_zero. rewrite zero_mul. reflexivity.\n\n    rewrite succ_dist. rewrite succ_mul. rewrite IHn. reflexivity.\nQed.\n(*To end, we will prove what could be considered a theorem that will be helpful for computation.\nConsider, after all, when your instructors wave their hands and just write a * (b * c) = b * (a * c) without appealing to the axioms. This will not work here, and yet, it surely is our dream to have the computer learn to waive its hands as well. The compromise is struck by showing this computational trick is justifable. Let us do so now. *)\nProposition mul_left_comm (a b c : nat) : a * (b * c) = b * (a * c).\nProof.\n    induction a. rewrite zero_mul. rewrite zero_mul. rewrite mul_zero.\n    reflexivity. \n\n    rewrite succ_mul. rewrite add_one. rewrite IHa. rewrite add_mul.\n    rewrite one_mul. rewrite mul_add. reflexivity.\nQed.\n\nEnd Multiplication_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/Multiplication_World.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7354197836874968}}
{"text": "Require Export Reals.\nOpen Scope R_scope.\n\n(* 定义：实数构成的集合 *)\n\nDefinition R_Ensemble := R -> Prop.\n\n(* 定义：实数x属于集合A *)\n\nDefinition In (x:R)(A:R_Ensemble) :Prop := A x.\n\nNotation \"x ∈ A\" := (In x A) (at level 10).\n\n(* 定义：区间 *)\n(* 开区间 *)\nDefinition oo (a b:R) := fun x:R => a<b/\\a<x<b.\nNotation \"( a , b )\" := (oo a b).\n\n(* 闭区间 *)\nDefinition cc (a b:R) := fun x:R => a<b/\\a<=x<=b.\nNotation \"[ a , b ]\" := (cc a b).\n\n(* 半开半闭区间-左开右闭 *)\nDefinition oc (a b:R) := fun x:R => a<b/\\a<x<=b.\nNotation \"( a , b ]\" := (oc a b).\n\n(* 半开半闭区间-左闭右开 *)\nDefinition co (a b:R) := fun x:R => a<b/\\a<=x<b.\nNotation \"[ a , b )\" := (co a b).\n\n(* 函数在区间上一些基本性质的形式化描述 *)\n(* 函数f在区间q上单调增 *)\nDefinition mon_increasing f (q:R_Ensemble) :=\n  forall x y:R, x ∈ q /\\ y ∈ q /\\ y-x>0 -> f x <= f y.\n\n(* 函数f在区间q上严格单调增 *)\nDefinition strict_mon_increasing f (q:R_Ensemble) :=\n  forall x y:R, x ∈ q /\\ y ∈ q /\\ y-x>0 -> f x < f y.\n\n(* 函数f在区间q上单调减 *)\nDefinition mon_decreasing f (q:R_Ensemble) :=\n  forall x y:R, x ∈ q /\\ y ∈ q /\\ y-x>0 -> f x >= f y.\n\n(* 函数f在区间q上严格单调减 *)\nDefinition strict_mon_decreasing f (q:R_Ensemble) :=\n  forall x y:R, x ∈ q /\\ y ∈ q /\\ y-x>0 -> f x > f y.\n\n(* 函数f在区间q上倒数无界 *)\nDefinition bounded_rec_f f (q:R_Ensemble) :=\n  forall M:R, exists z:R, z ∈ q /\\ M < Rabs(1/(f z)).\n\n(* 函数f在区间q上正值单调不减 *)\nDefinition pos_inc f (q:R_Ensemble) := \n  (forall z:R, z ∈ q -> f z > 0) /\\\n  (forall z1 z2:R, z1 ∈ q -> z2 ∈ q -> z1<z2 -> f z1 <= f z2).\n\n(* 函数f在区间q上正值单调不增 *)\nDefinition pos_dec f (q:R_Ensemble) :=\n  (forall z:R, z ∈ q -> f z > 0) /\\\n  (forall z1 z2:R, z1 ∈ q -> z2 ∈ q -> z1<z2 -> f z2 >= f z1).\n\n(* 一些组合函数、复合函数的形式化描述 *)\n\n(* 设有函数f(x)，下面给出函数cf(x)的形式化描述 *)\nDefinition mult_real_f (c:R) f := fun x:R => (c * (f x)).\n\n(* 设有函数f1(x)、f2(x)，下面给出函数f1(x)+f2(x)的形式化描述 *)\nDefinition plus_Fu f1 f2   := fun x:R => f1 x + f2 x.\n\n(* 设有函数f(x)，实数c，下面给出函数f(cx)的形式化描述 *)\nDefinition Com_F_c (f:R->R) c x := f (c * x). \n\n(* 设有函数f(x)，实数c、d，下面给出函数f(cx+d)的形式化描述 *)\nDefinition Com_F (f:R->R) (c d x:R) := f (c*x+d).\n\n(* 排中律 *)\nAxiom classic : forall P : Prop, P \\/ ~P.\n\nTheorem not_and_or : forall P Q : Prop, ~ (P /\\ Q) -> ~ P \\/ ~ Q.\nProof.\n  intros.\n  generalize(classic P); intro.\n  generalize(classic Q); intro.\n  destruct H0. destruct H1.\n  assert(P/\\Q). { split; auto. }\n  contradiction.\n  right; auto. left; auto.\nQed.", "meta": {"author": "LittleGavin", "repo": "calculus_3rd", "sha": "6d0fd26bcf9f00252a2fffaee85b299c589d844c", "save_path": "github-repos/coq/LittleGavin-calculus_3rd", "path": "github-repos/coq/LittleGavin-calculus_3rd/calculus_3rd-6d0fd26bcf9f00252a2fffaee85b299c589d844c/Calculus_3rd/Basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7354197811059062}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq path order.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nModule Insertion.\nSection InsertionSort.\n\nVariable T : eqType.\nVariable leT : rel T.\nImplicit Types x y z : T.\nImplicit Types s t u : seq T.\n\n(*| Insert an element `e` into a sorted list `s` |*)\nFixpoint insert e s : seq T :=\n  if s is x :: s' then\n    if leT e x then\n      e :: s\n    else\n      x :: (insert e s')\n  else [:: e].\n\n(*| Sort input list `s` |*)\nFixpoint sort s : seq T :=\n  if s is x :: s' then\n    insert x (sort s')\n  else\n    [::].\n\n(** * Exercise *)\nLemma sorted_cons x s :\n  sorted leT (x :: s) -> sorted leT s.\nProof.\nby move=> //= ; case: s=> //= e y /andP[].\nQed.\n\n\nHypothesis leT_total : total leT.\nLemma insert_sorted x s :\n    sorted leT s ->\n    sorted leT (insert x s).\nProof.\nelim: s=> //= e s IHs.\ncase: ifP=> /= [->-> // | ].\nmove=> le_x_e_false path_e_s.\nhave:= leT_total x e.\nrewrite le_x_e_false /=.\nmove=> le_e_x.\nmove: path_e_s=> {}/path_sorted/IHs.\ncase: s=> //= ; first by rewrite le_e_x.\nAdmitted.\n\n(** * Exercise *)\nLemma sort_sorted s :\n  sorted leT (sort s).\nProof.\nelim: s=> //= x s IHs.\nby rewrite insert_sorted.\nQed.\n\nEnd InsertionSort.\nEnd Insertion.\n\n\n\n(** * Exercise: implement guarded interleave function *)\n\n(* here is its unguarded version *)\nUnset Guard Checking.\nFixpoint interleave_ns {T} (xs ys : seq T)\n           {struct xs} : seq T :=\n  if xs is (x :: xs')\n  then x :: interleave_ns ys xs'\n  else ys.\nSet Guard Checking.\n\n(** A simple unit test. *)\nCheck erefl : interleave_ns [:: 1; 3] [:: 2; 4] = [:: 1; 2; 3; 4].\n\nFixpoint interleave {T} (xs ys : seq T) : seq T :=\n    match xs, ys with\n    | [::], _ => ys\n    | _, [::] => xs\n    | x::xs', y::ys' => x :: y :: interleave xs' ys'\n    end.\nCheck erefl : interleave [:: 1; 3] [:: 2; 4] = [:: 1; 2; 3; 4].\n\nLemma interleave_ns_eq_interleave {T} :\n  (@interleave_ns T) =2 (@interleave T).\nProof. by elim=> // x xs IHs [] // y ys /= ; rewrite IHs.\nQed.\n\n\n(** * Exercise: implement Ackermann's function\n\nIt's defined via the following expressions:\n\n  A(0,   n)   = n + 1\n  A(m+1, 0)   = A(m, 1)\n  A(m+1, n+1) = A(m, A(m+1, n))\n*)\nFixpoint acker m n :=\n    let fix acker_m n :=\n    match m, n with\n    | O, _ => n + 1\n    | S m', O => acker m' 1\n    | S m', S n' => acker m' (acker_m n')\n    end\n    in acker_m n.\nCheck erefl : acker 0 0 = 1.\nCheck erefl : acker 0 1 = 2.\nCheck erefl : acker 1 0 = 2.\nCheck erefl : acker 1 1 = 3.\nCheck erefl : acker 3 2 = 29.\nCheck erefl : acker 4 0 = 13.\n\n\n\n(** * Exercise: implement merge function via Program plugin *)\nFrom Coq Require Import Program.\nProgram Fixpoint merge2 s t {measure (size s + size t)} : seq nat :=\n    match s, t with\n    | [::], _ => t\n    | _, [::] => s\n    | x :: s', y :: t' =>\n        if (x <= y)%O\n        then x :: merge2 s' t\n        else y :: merge2 s t'\n    end.\nNext Obligation.\napply/ltP ; move=> //=; by rewrite ltn_add2l ltnSn.\nQed.\nCompute merge2 [::] [::].\nCompute merge2 [:: 1; 2; 3] [::].\nCompute merge2 [:: 1; 2; 3] [:: 1; 2; 3].\nCompute merge2 [::] [:: 1; 2; 3].\nCompute merge2 [:: 1; 4; 6] [:: 1; 2; 3].", "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/seminar08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7353608644177677}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to strengthen an induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can achieve the same effect in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, standard, optional (silly_ex)  \n\n    Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     oddb 3 = true ->\n     evenb 4 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = (n =? 5)  ->\n     (S (S n)) =? 7 = true.\nProof.\n  intros n H.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (** (This [simpl] is optional, since [apply] will perform\n             simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars, standard (apply_exercise1)  \n\n    (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [Search] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (apply_rewrite)  \n\n    Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied? *)\n\n(* FILL IN HERE \n\n    [] *)\n\n(* ################################################################# *)\n(** * The [apply with] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a;b]] to [[e;f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, standard, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [injection] and [discriminate] Tactics *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n].\n\n    Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not\n    interesting.)  And so on. *)\n\n(** For example, we can prove the injectivity of [S] by using the\n    [pred] function defined in [Basics.v]. *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H1.\n  assert (H2: n = pred (S n)). { reflexivity. }\n  rewrite H2. rewrite H1. reflexivity.\nQed.\n\n(** This technique can be generalized to any constructor by\n    writing the equivalent of [pred] for that constructor -- i.e.,\n    writing a function that \"undoes\" one application of the\n    constructor. As a more convenient alternative, Coq provides a\n    tactic called [injection] that allows us to exploit the\n    injectivity of any constructor.  Here is an alternate proof of the\n    above theorem using [injection]: *)\n\nTheorem S_injective' : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [injection H] at this point, we are asking Coq to\n    generate all equations that it can infer from [H] using the\n    injectivity of constructors. Each such equation is added as a\n    premise to the goal. In the present example, adds the premise\n    [n = m]. *)\n\n  injection H. intros Hnm. apply Hnm.\nQed.\n\n(** Here's a more interesting example that shows how [injection] can\n    derive multiple equations at once. *)\n\nTheorem injection_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H.\n  injection H. intros H1 H2.\n  rewrite H1. rewrite H2. reflexivity.\nQed.\n\n(** The \"[as]\" variant of [injection] permits us to choose names for\n    the introduced equations rather than letting Coq do it. *)\n\nTheorem injection_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H.\n  injection H as Hnm. rewrite Hnm.\n  reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard (injection_ex3)  *)\nExample injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** So much for injectivity of constructors.  What about disjointness?\n\n    The principle of disjointness says that two terms beginning with\n    different constructors (like [O] and [S], or [true] and [false])\n    can never be equal.  This means that, any time we find ourselves\n    working in a context where we've _assumed_ that two such terms are\n    equal, we are justified in concluding anything we want to (because\n    the assumption is nonsensical).\n\n    The [discriminate] tactic embodies this principle: It is used on a\n    hypothesis involving an equality between different\n    constructors (e.g., [S n = O]), and it solves the current goal\n    immediately.  For example: *)\n\nTheorem eqb_0_l : forall n,\n   0 =? n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'] eqn:E.\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming [0\n    =? (S n') = true], we must show [S n' = 0]!  The way forward is to\n    observe that the assumption itself is nonsensical: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [discriminate] on this hypothesis, Coq confirms\n    that the subgoal we are working on is impossible and removes it\n    from further consideration. *)\n\n    intros H. discriminate H.\nQed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything, even false things! *)\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra. Qed.\n\nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. discriminate contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are _not_ showing that the conclusion of the\n    statement holds.  Rather, they are showing that, if the\n    nonsensical situation described by the premise did somehow arise,\n    then the nonsensical conclusion would follow.  We'll explore the\n    principle of explosion of more detail in the next chapter. *)\n\n(** **** Exercise: 1 star, standard (discriminate_ex3)  *)\nExample discriminate_ex3 :\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] ->\n    x = z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find convenient in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     (S n) =? (S m) = b  ->\n     n =? m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [X -> Y], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [Y] into a subgoal [X]), [apply L in H] matches [H]\n    against [X] and, if successful, replaces it with [Y].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [X -> Y] and a hypothesis matching [X], it\n    produces a hypothesis matching [X].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [X -> Y] and we\n    are trying to prove [Y], it suffices to prove [X].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (n =? 5 = true -> (S (S n)) =? 7 = true) ->\n  true = (n =? 5)  ->\n  true = ((S (S n)) =? 7).\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, standard, recommended (plus_n_n_injective)  \n\n    Practice using \"in\" variants in this proof.  (Hint: use\n    [plus_n_Sm].) *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that [double] is injective -- i.e., that it maps\n    different arguments to different results:\n\n       Theorem double_injective: forall n m,\n         double n = double m -> n = m.\n\n    The way we _start_ this proof is a bit delicate: if we begin with\n\n       intros n. induction n.\n\n    all is well.  But if we begin it with\n\n       intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'] eqn:E.\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) discriminate eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'] eqn:E.\n    + (* m = O *) discriminate eq.\n    + (* m = S m' *) apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a statement involving _every_ [n] but just a _single_ [m]. *)\n\n(** The successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) discriminate eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'] eqn:E.\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      discriminate eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. injection eq as goal. apply goal. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful, when using induction, that we are not trying to prove\n    something too specific: To prove a property of [n] and [m] by\n    induction on [n], it is sometimes important to leave [m]\n    generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars, standard (eqb_true)  *)\nTheorem eqb_true : forall n m,\n    n =? m = true -> n = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (eqb_true_informal)  \n\n    Give a careful informal proof of [eqb_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. injection eq as goal. apply goal. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by injectivity that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises,\n    let's digress briefly and use [eqb_true] to prove a similar\n    property of identifiers that we'll need in later chapters: *)\n\nTheorem eqb_id_true : forall x y,\n  eqb_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply eqb_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, standard, recommended (gen_dep_practice)  \n\n    Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a name that\n    has been introduced by a [Definition] so that we can manipulate\n    its right-hand side.  For example, if we define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we appear to be stuck: [simpl] doesn't simplify anything at\n    this point, and since we haven't proved any other facts about\n    [square], there is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these it is not hard\n    to finish the proof. *)\n\n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n    { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, some discussion of unfolding and simplification is\n    in order.\n\n    You may already have observed that tactics like [simpl],\n    [reflexivity], and [apply] will often unfold the definitions of\n    functions automatically when this allows them to make progress.\n    For example, if we define [foo m] to be the constant [5]... *)\n\nDefinition foo (x: nat) := 5.\n\n(** .... then the [simpl] in the following proof (or the\n    [reflexivity], if we omit the [simpl]) will unfold [foo m] to\n    [(fun x => 5) m] and then further simplify this expression to just\n    [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is somewhat conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  It is not smart enough to notice that the\n    two branches of the [match] are identical, so it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that cannot itself be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone. *)\n\n(** At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m eqn:E.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress. *)\n\n(** A more straightforward way to make progress is to explicitly tell\n    Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m eqn:E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if n =? 3 then false\n  else if n =? 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (n =? 3) eqn:E1.\n    - (* n =? 3 = true *) reflexivity.\n    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.\n      + (* n =? 5 = true *) reflexivity.\n      + (* n =? 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (n =? 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (eqb\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, standard, optional (combine_split)  \n\n    Here is an implementation of the [split] function mentioned in\n    chapter [Poly]: *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x, y) :: t =>\n      match split t with\n      | (lx, ly) => (x :: lx, y :: ly)\n      end\n  end.\n\n(** Prove that [split] and [combine] are inverses in the following\n    sense: *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The [eqn:] part of the [destruct] tactic is optional: We've chosen\n    to include it most of the time, just for the sake of\n    documentation, but many Coq proofs omit it.\n\n    When [destruct]ing compound expressions, however, the information\n    recorded by the [eqn:] can actually be critical: if we leave it\n    out, then [destruct] can sometimes erase information we need to\n    complete a proof. \n\n    For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? 3 then true\n  else if n =? 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  If we start the proof like this (with no [eqn:] on the\n    destruct)... *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3).\n  (* stuck... *)\nAbort.\n\n(** ... then we are stuck at this point because the context does\n    not contain enough information to prove the goal!  The problem is\n    that the substitution performed by [destruct] is quite brutal --\n    in this case, it thows away every occurrence of [n =? 3], but we\n    need to keep some memory of this expression and how it was\n    destructed, because we need to be able to reason that, since [n =?\n    3 = true] in this branch of the case analysis, it must be that [n\n    = 3], from which it follows that [n] is odd.\n\n    What we want here is to substitute away all existing occurences of\n    [n =? 3], but at the same time add an equation to the context that\n    records which case we are in.  This is precisely what the [eqn:]\n    qualifier does. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply eqb_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allowing us to finish the\n        proof. *)\n      destruct (n =? 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply eqb_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) discriminate eq.  Qed.\n\n(** **** Exercise: 2 stars, standard (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [injection]: reason by injectivity on equalities\n        between values of inductively defined types\n\n      - [discriminate]: reason by disjointness of constructors on\n        equalities between values of inductively defined types\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars, standard (eqb_sym)  *)\nTheorem eqb_sym : forall (n m : nat),\n  (n =? m) = (m =? n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (eqb_sym_informal)  \n\n    Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [(n =? m) = (m =? n)].\n\n   Proof: *)\n   (* FILL IN HERE \n\n    [] *)\n\n(** **** Exercise: 3 stars, standard, optional (eqb_trans)  *)\nTheorem eqb_trans : forall n m p,\n  n =? m = true ->\n  m =? p = true ->\n  n =? p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  \n\n    We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split (combine l1 l2) = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop\n  (* (\"[: Prop]\" means that we are giving a name to a\n     logical proposition here.) *)\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_split_combine : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  \n\n    This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  \n\n    Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (eqb 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (eqb 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_forallb_1 : forallb oddb [1;3;5;7;9] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_forallb_2 : forallb negb [false;false] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_forallb_3 : forallb evenb [0;2;4;5] = false.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_forallb_4 : forallb (eqb 5) [] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_existsb_2 : existsb (andb true) [true;true;false] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.\nProof. (* FILL IN HERE *) Admitted.\n\nExample test_existsb_4 : existsb evenb [] = false.\nProof. (* FILL IN HERE *) Admitted.\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),\n  existsb test l = existsb' test l.\nProof. (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n\n\n(* Wed Jan 9 12:02:44 EST 2019 *)\n", "meta": {"author": "carliros", "repo": "software-foundations-book", "sha": "fea3e774d18d2434c7296cedbf52756c5ab8dbdd", "save_path": "github-repos/coq/carliros-software-foundations-book", "path": "github-repos/coq/carliros-software-foundations-book/software-foundations-book-fea3e774d18d2434c7296cedbf52756c5ab8dbdd/logical-foundations-2019/dotv/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.9046505331728751, "lm_q1q2_score": 0.7353608483794667}}
{"text": "From Coq Require Import Logic.FunctionalExtensionality.\n\nDefinition Object: Type := Type.\n\n(* ‘singleton’ set, a set with exactly one element. *)\nDefinition Singleton: Object := True.\n\nDefinition Morphism (domain: Object) (codomain: Object): Type:= domain -> codomain.\n\n(* All Objects has an identity morphism *)\nDefinition identity (x: Object): (Morphism x x) :=\n  fun x => x.\n\n(* Composition of 2 morphisms *)\nDefinition compose {domain: Object} {mid: Object} {codomain: Object} \n  (f: Morphism domain mid) (g: Morphism mid codomain): (Morphism domain codomain)\n  := fun x => g (f x).\n\n(** The identity function is a unit in the composition *)\nTheorem composition_id: forall (A B: Object) (f: Morphism A B),\n  compose (identity A) f = f /\\ compose f (identity B) = f.\nProof.\n  unfold compose. unfold identity. intros.\n  split; apply functional_extensionality; intros;\n  reflexivity.\nQed.\n\n(* Split composition_id, for easily using *)\nTheorem composition_id_left: forall (A B: Object) (f: Morphism A B),\n  compose (identity A) f = f.\nProof. auto. Qed.\n\nTheorem composition_id_right: forall (A B: Object) (f: Morphism A B),\n  compose f (identity B) = f.\nProof. auto. Qed.\n\n(** h o (g o f) = (h o g) o f *)\nTheorem composition_assoc: forall (A B C D: Object) (f: Morphism A B) (g: Morphism B C) (h: Morphism C D),\n  compose (compose f g) h = compose f (compose g h).\nProof.\n  intros. unfold compose. reflexivity.\nQed.", "meta": {"author": "HaoYang670", "repo": "conceptual_mathematics", "sha": "465ee186e711076cf7d010c6325868944db927e6", "save_path": "github-repos/coq/HaoYang670-conceptual_mathematics", "path": "github-repos/coq/HaoYang670-conceptual_mathematics/conceptual_mathematics-465ee186e711076cf7d010c6325868944db927e6/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7353574209774649}}
{"text": "(* -*- mode: coq; mode: visual-line -*- *)\n\nRequire Import HoTT.Basics HoTT.Types.\n\nLocal Open Scope path_scope.\nGeneralizable Variables A B f.\n\n(** * Bi-invertible maps *)\n\n(** A map is \"bi-invertible\" if it has both a section and a retraction, not necessarily the same.  This definition of equivalence was proposed by Andre Joyal. *)\n\nDefinition BiInv `(f : A -> B) : Type\n  := {g : B -> A & g o f == idmap} * {h : B -> A & f o h == idmap}.\n\n(** It seems that the easiest way to show that bi-invertibility is equivalent to being an equivalence is also to show that both are h-props and that they are logically equivalent. *)\n\nDefinition isequiv_biinv `(f : A -> B)\n  : BiInv f -> IsEquiv f.\nProof.\n  intros [[g s] [h r]].\n  exact (isequiv_adjointify f g\n    (fun x => ap f (ap g (r x)^ @ s (h x))  @ r x)\n    s).\nDefined.\n\nGlobal Instance isprop_biinv `{Funext} `(f : A -> B) : IsHProp (BiInv f) | 0.\nProof.\n  apply hprop_inhabited_contr.\n  intros bif; pose (fe := isequiv_biinv f bif).\n  apply @contr_prod.\n  (* For this, we've done all the work already. *)\n  - by apply contr_retr_equiv.\n  - by apply contr_sect_equiv.\nDefined.\n\nDefinition equiv_biinv_isequiv `{Funext} `(f : A -> B)\n  : BiInv f <~> IsEquiv f.\nProof.\n  apply equiv_iff_hprop.\n  - by apply isequiv_biinv.\n  - intros ?.  split.\n    + by exists (f^-1); apply eissect.\n    + by exists (f^-1); apply eisretr.\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Equiv/BiInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7353574149290326}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (z : natural) (x : natural) : natural :=\n  plus lf1 (mult z (plus Zero x)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj231_coqofml_zpuGZC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7353009257589247}}
{"text": "Theorem modus_ponens\n  : forall (P Q : Prop)\n  , (P -> Q) -> P -> Q.\nProof.\n  intros.\n  apply H. exact H0.\nQed.\n\nTheorem modus_tollens\n  : forall (P Q : Prop)\n  , (P -> Q) -> ~ Q -> ~ P.\nProof.\n  unfold not.\n  intros.\n  pose (H2 := H0 (H H1)).\n  exact H2.\nQed.", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/SoftwareFoundations/Basics/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7352750529952164}}
{"text": "Theorem ex54_10: forall a b c : Prop,\n                 (a -> c) -> (b -> c) -> (a \\/ b) -> c.\nProof.\n  intros. elim H1. assumption. assumption.\nQed.\n\nTheorem ex54_11: forall a1 a2 b : Prop,\n                 (a1 -> b) -> (a2 -> b) -> ((a1 /\\ ~a2)\n                 \\/ (~a1 /\\ a2)) -> b.\nProof.\n  intros. elim H1. intro. elim H2. intros.\n  apply (H H3). intro. elim H2. intros.\n  apply (H0 H4).\nQed.\n\nTheorem ex54_12: forall a b c d : Prop,\n                 (a -> c) -> (b -> d) -> (a \\/ b) \n                 -> (c \\/ d).\nProof.\n  intros. elim H1. intro. left. apply (H H2).\n  intro. right. apply (H0 H2).\nQed.\n\nTheorem ex54_13: forall a b c : Prop,\n                 (c -> a) -> (c -> b) -> (~a \\/ ~b) \n                 -> ~c.\nProof.\n  intros. intro. elim H1. intro. apply H3.\n  apply H. assumption. intro. apply H3.\n  apply H0. assumption.\nQed.\n\nTheorem ex54_14: forall a b1 b2 : Prop,\n                 (a -> b1) -> (a -> b2) -> (~b1 \\/ ~b2) \n                 -> ~a.\nProof.\n  intros. intro. elim H1. intro. apply H3.\n  apply H. assumption. intro. apply H3.\n  apply H0. assumption.\nQed.\n\nTheorem ex54_15: forall a b c d : Prop,\n                 (c -> a) -> (d -> b) -> (~a \\/ ~b) -> \n                 (~c \\/ ~d).\nProof.\n  intros. elim H1. intro. left. intro.\n  apply H2. apply H. assumption.\n  intro. right. intro. apply H2. apply H0.\n  assumption.\nQed.", "meta": {"author": "limitedeternity", "repo": "PrPr-Labs", "sha": "0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62", "save_path": "github-repos/coq/limitedeternity-PrPr-Labs", "path": "github-repos/coq/limitedeternity-PrPr-Labs/PrPr-Labs-0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62/PrPr-01/ConstDestDilemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7352750467972212}}
{"text": "Require Export Basics.\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n    for [+] on the left using an easy argument based on\n    simplification.  The fact that it is also a neutral element on the\n    _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\n\n(** ... cannot be proved in the same simple way.  Just applying\n  [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n  unknown number, so the [match] in the definition of [+] can't be\n  simplified.  *)\n\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n   further: the branch of the case analysis where we assume [n = 0]\n   goes through fine, but in the branch where [n = S n'] for some [n'] we\n   get stuck in exactly the same way.  We could use [destruct n'] to\n   get one step further, but, since [n] can be arbitrarily large, if we\n   try to keep on like this we'll never be done. *)\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(** To prove interesting facts about numbers, lists, and other\n    inductively defined sets, we usually need a more powerful\n    reasoning principle: _induction_.\n\n    Recall (from high school, a discrete math course, etc.) the\n    principle of induction over natural numbers: If [P(n)] is some\n    proposition involving a natural number [n] and we want to show\n    that [P] holds for _all_ numbers [n], we can reason like this:\n         - show that [P(O)] holds;\n         - show that, for any [n'], if [P(n')] holds, then so does\n           [P(S n')];\n         - conclude that [P(n)] holds for all [n].\n\n    In Coq, the steps are the same but the order is backwards: we\n    begin with the goal of proving [P(n)] for all [n] and break it\n    down (by applying the [induction] tactic) into two separate\n    subgoals: first showing [P(O)] and then showing [P(n') -> P(S\n    n')].  Here's how this works for the theorem at hand: *)\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\n(** Like [destruct], the [induction] tactic takes an [as...]\n    clause that specifies the names of the variables to be introduced\n    in the subgoals.  In the first branch, [n] is replaced by [0] and\n    the goal becomes [0 + 0 = 0], which follows by simplification.  In\n    the second, [n] is replaced by [S n'] and the assumption [n' + 0 =\n    n'] is added to the context (with the name [IHn'], i.e., the\n    Induction Hypothesis for [n'] -- notice that this name is\n    explicitly chosen in the [as...] clause of the call to [induction]\n    rather than letting Coq choose one arbitrarily). The goal in this\n    case becomes [(S n') + 0 = S n'], which simplifies to [S (n' + 0)\n    = S n'], which in turn follows from [IHn']. *)\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(** (The use of the [intros] tactic in these proofs is actually\n    redundant.  When applied to a goal that contains quantified\n    variables, the [induction] tactic will automatically move them\n    into the context as needed.) *)\n\n(** **** Exercise: 2 stars, recommended (basic_induction)  *)\n(** Prove the following using induction. You might need previously\n    proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n.\n  induction 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. induction m. simpl. reflexivity.\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 as [|n'].\n    simpl. rewrite <- plus_n_O. reflexivity.\n    simpl. rewrite <- plus_n_Sm. rewrite -> IHn'. 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 as [| n' IHn']. simpl. reflexivity.\n  simpl. rewrite -> IHn'. reflexivity.\nQed. \n(** [] *)\n\n(** **** Exercise: 2 stars (double_plus)  *)\n(** Consider the following function, which doubles its argument: *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (evenb_S)  *)\n(** One inconveninent aspect of our definition of [evenb n] is that it\n    may need to perform a recursive call on [n - 2]. This makes proofs\n    about [evenb n] harder when done by induction on [n], since we may\n    need an induction hypothesis about [n - 2]. The following lemma\n    gives a better characterization of [evenb (S n)]: *)\n\n(**Theorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  (* FILL IN HERE *) Admitted.*)\n(** [] *)\n\n(** **** Exercise: 1 star (destruct_induction)  *)\n(** Briefly explain the difference between the tactics [destruct] \n    and [induction].\n\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\n(** In Coq, as in informal mathematics, large proofs are often\n    broken into a sequence of theorems, with later proofs referring to\n    earlier theorems.  But sometimes a proof will require some\n    miscellaneous fact that is too trivial and of too little general\n    interest to bother giving it its own top-level name.  In such\n    cases, it is convenient to be able to simply state and prove the\n    needed \"sub-theorem\" right at the point where it is used.  The\n    [assert] tactic allows us to do this.  For example, our earlier\n    proof of the [mult_0_plus] theorem referred to a previous theorem\n    named [plus_O_n].  We could instead use [assert] to state and\n    prove [plus_O_n] in-line: *)\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.  Qed.\n\n(** The [assert] tactic introduces two sub-goals.  The first is\n    the assertion itself; by prefixing it with [H:] we name the\n    assertion [H].  (We can also name the assertion with [as] just as\n    we did above with [destruct] and [induction], i.e., [assert (0 + n\n    = n) as H].)  Note that we surround the proof of this assertion\n    with curly braces [{ ... }], both for readability and so that,\n    when using Coq interactively, we can see more easily when we have\n    finished this sub-proof.  The second goal is the same as the one\n    at the point where we invoke [assert] except that, in the context,\n    we now have the assumption [H] that [0 + n = n].  That is,\n    [assert] generates one subgoal where we must prove the asserted\n    fact and a second subgoal where we can use the asserted fact to\n    make progress on whatever we were trying to prove in the first\n    place. *)\n\n(** The [assert] tactic is handy in many sorts of situations.  For\n    example, suppose we want to prove that [(n + m) + (p + q) = (m +\n    n) + (p + q)]. The only difference between the two sides of the\n    [=] is that the arguments [m] and [n] to the first inner [+] are\n    swapped, so it seems we should be able to use the commutativity of\n    addition ([plus_comm]) to rewrite one into the other.  However,\n    the [rewrite] tactic is a little stupid about _where_ it applies\n    the rewrite.  There are three uses of [+] here, and it turns out\n    that doing [rewrite -> plus_comm] will affect only the _outer_\n    one... *)\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)...\n     it seems like plus_comm should do the trick! *)\n  rewrite -> plus_comm.\n  (* Doesn't work...Coq rewrote the wrong plus! *)\nAbort.\n\n(** To get [plus_comm] to apply at the point where we want it to, we\n    can introduce a local lemma stating that [n + m = m + n] (for the\n    particular [m] and [n] that we are talking about here), prove this\n    lemma using [plus_comm], and then use it to do the desired\n    rewrite. *)\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\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, recommended (mult_comm)  *)\n(** Use [assert] to help prove this theorem.  You shouldn't need to\n    use induction on [plus_swap]. *)\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. rewrite <- plus_assoc. (*m + (p + n) = m + (n + p)*)\n  assert (H: (p + n) =(n + p )).\n  rewrite -> plus_comm. reflexivity.\n  rewrite -> H. reflexivity.\n Qed.\n\n(** Now 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 mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (more_exercises)  *)\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\nTheorem leb_refl : forall n:nat,\n  true = leb n n.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  leb n m = true -> leb (p + n) (p + m) = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem S_nbeq_0 : forall n:nat,\n  beq_nat (S n) 0 = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl)  *)\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.) *)\n\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap')  *)\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)]. *)\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (binary_commute)  *)\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               bin --------- incr -------> bin\n                |                           |\n            bin_to_nat                  bin_to_nat\n                |                           |\n                v                           v\n               nat ---------- S ---------> nat\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, please copy the\n    definitions from your solution to the [binary] exercise here so\n    that this file can be graded on its own.  If you find yourself\n    wanting to change your original definitions to make the property\n    easier to prove, feel free to do so! *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse)  *)\n(** This exercise is a continuation of the previous exercise about\n    binary numbers.  You will need your definitions and theorems from\n    there to complete this one.\n\n    (a) First, write a function to convert natural numbers to binary\n        numbers.  Then prove that starting with any natural number,\n        converting to binary, then converting back yields the same\n        natural number you started with.\n\n    (b) You might naturally think 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 yields the\n        same number we started with.  However, this is not true!\n        Explain what the problem is.\n\n    (c) Define a \"direct\" normalization function -- i.e., a function\n        [normalize] from binary numbers to binary numbers such that,\n        for any binary number b, converting to a natural and then back\n        to binary yields [(normalize b)].  Prove it.  (Warning: This\n        part is tricky!)\n\n    Again, feel free to change your earlier definitions if this helps\n    here. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proof (Optional) *)\n\n(** \"_Informal proofs are algorithms; formal proofs are code_.\" *)\n\n(** The question of what constitutes a proof of a mathematical\n    claim has challenged philosophers for millennia, but a rough and\n    ready definition could be this: A proof of a mathematical\n    proposition [P] is a written (or spoken) text that instills in the\n    reader or hearer the certainty that [P] is true.  That is, a proof\n    is an act of communication.\n\n    Acts of communication may involve different sorts of readers.  On\n    one hand, the \"reader\" can be a program like Coq, in which case\n    the \"belief\" that is instilled is that [P] can be mechanically\n    derived from a certain set of formal logical rules, and the proof\n    is a recipe that guides the program in checking this fact.  Such\n    recipes are _formal_ proofs.\n\n    Alternatively, the reader can be a human being, in which case the\n    proof will be written in English or some other natural language,\n    and will thus necessarily be _informal_.  Here, the criteria for\n    success are less clearly specified.  A \"valid\" proof is one that\n    makes the reader believe [P].  But the same proof may be read by\n    many different readers, some of whom may be convinced by a\n    particular way of phrasing the argument, while others may not be.\n    Some readers may be particularly pedantic, inexperienced, or just\n    plain thick-headed; the only way to convince them will be to make\n    the argument in painstaking detail.  But other readers, more\n    familiar in the area, may find all this detail so overwhelming\n    that they lose the overall thread; all they want is to be told the\n    main ideas, since it is easier for them to fill in the details for\n    themselves than to wade through a written presentation of them.\n    Ultimately, there is no universal standard, because there is no\n    single way of writing an informal proof that is guaranteed to\n    convince every conceivable reader.\n\n    In practice, however, mathematicians have developed a rich set of\n    conventions and idioms for writing about complex mathematical\n    objects that -- at least within a certain community -- make\n    communication fairly reliable.  The conventions of this stylized\n    form of communication give a fairly clear standard for judging\n    proofs good or bad.\n\n    Because we are using Coq in this course, we will be working\n    heavily with formal proofs.  But this doesn't mean we can\n    completely forget about informal ones!  Formal proofs are useful\n    in many ways, but they are _not_ very efficient ways of\n    communicating ideas between human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\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\n(** Coq is perfectly happy with this.  For a human, however, it\n    is difficult to make much sense of it.  We can use comments and\n    bullets to show the structure a little more clearly... *)\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(** ... and if you're used to Coq you may be able to step\n    through the tactics one after the other in your mind and imagine\n    the state of the context and goal stack at each point, but if the\n    proof were even a little bit more complicated this would be next\n    to impossible.\n\n    A (pedantic) mathematician might write the proof something like\n    this: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n      n + (m + p) = (n + m) + p.\n\n    _Proof_: By induction on [n].\n\n    - First, suppose [n = 0].  We must show\n\n        0 + (m + p) = (0 + m) + p.\n\n      This follows directly from the definition of [+].\n\n    - Next, suppose [n = S n'], where\n\n        n' + (m + p) = (n' + m) + p.\n\n      We must show\n\n        (S n') + (m + p) = ((S n') + m) + p.\n\n      By the definition of [+], this follows from\n\n        S (n' + (m + p)) = S ((n' + m) + p),\n\n      which is immediate from the induction hypothesis.  _Qed_. *)\n\n\n(** The overall form of the proof is basically similar, and of\n    course this is no accident: Coq has been designed so that its\n    [induction] tactic generates the same sub-goals, in the same\n    order, as the bullet points that a mathematician would write.  But\n    there are significant differences of detail: the formal proof is\n    much more explicit in some ways (e.g., the use of [reflexivity])\n    but much less explicit in others (in particular, the \"proof state\"\n    at any given point in the Coq proof is completely implicit,\n    whereas the informal proof reminds the reader several times where\n    things stand). *)\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal)  *)\n(** Translate your solution for [plus_comm] into an informal proof:\n\n    Theorem: Addition is commutative.\n\n    Proof: (* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal)  *)\n(** Write an informal proof of the following theorem, using the\n    informal proof of [plus_assoc] as a model.  Don't just\n    paraphrase the Coq tactics into English!\n\n    Theorem: [true = beq_nat n n] for any [n].\n\n    Proof: (* FILL IN HERE *)\n[] *)\n\n(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)", "meta": {"author": "Rijndael9", "repo": "COQ", "sha": "4a206aa095995c11877d7e8e07c47589adbac212", "save_path": "github-repos/coq/Rijndael9-COQ", "path": "github-repos/coq/Rijndael9-COQ/COQ-4a206aa095995c11877d7e8e07c47589adbac212/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629215, "lm_q2_score": 0.9019206659843132, "lm_q1q2_score": 0.7352750256796128}}
{"text": "Require Import Coq.Relations.Relations.\nFrom Coq.Classes Require Import RelationClasses Morphisms.\nRequire Import Setoid.\n\nSection Semigroups.\nContext {Carrier: Type}.\nContext (equiv: relation Carrier).\nContext {equiv_equiv: Equivalence equiv}.\nContext (op: Carrier -> Carrier -> Carrier).\nContext {op_proper: Proper (equiv ==> equiv ==> equiv) op}.\n\nInfix \"==\" := equiv (at level 60, no associativity).\nInfix \"<o>\" := op (at level 40, left associativity).\n\nClass Semigroup := {\n  semigroup_assoc:\n    forall (a b c: Carrier),\n      a <o> b <o> c == a <o> (b <o> c);\n}.\n\nContext {semigroup: Semigroup}.\n\nLemma semigroup_op_l (a b: Carrier):\n  a == b -> forall (c: Carrier), c <o> a == c <o> b.\nProof.\n  intros Hab c.\n  setoid_rewrite Hab.\n  reflexivity.\nQed.\n\nLemma semigroup_op_r (a b: Carrier):\n  a == b -> forall (c: Carrier), a <o> c == b <o> c.\nProof.\n  intros Hab c.\n  setoid_rewrite Hab.\n  reflexivity.\nQed.\n\nClass Commutative := {\n    commutative:\n      forall (a b: Carrier),\n        a <o> b == b <o> a;\n}.\nEnd Semigroups.\n", "meta": {"author": "ku-sldg", "repo": "algebra", "sha": "026fb7daeef2dcd88c7d6723929e90f261caf109", "save_path": "github-repos/coq/ku-sldg-algebra", "path": "github-repos/coq/ku-sldg-algebra/algebra-026fb7daeef2dcd88c7d6723929e90f261caf109/theories/Semigroups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7352660108072}}
{"text": "Require Import Problem List PeanoNat.\nImport ListNotations.\n\nLemma lemma : forall xs a n, count_occ Nat.eq_dec (xs ++ [a]) n = count_occ Nat.eq_dec (a :: xs) n.\nProof.\n  intros.\n  induction xs; [auto|].\n  rewrite <- app_comm_cons.\n  simpl.\n  rewrite IHxs; clear IHxs.\n  destruct (Nat.eq_dec a0 n); [subst a0|]; simpl.\n  all: destruct (Nat.eq_dec a n); auto.\nQed.\n\nTheorem solution: task.\nProof.\n  unfold task.\n  intros.\n  induction l; [auto|].\n  replace (rev (a :: l)) with (rev l ++ [a]) by auto.\n  rewrite lemma.\n  simpl.\n  rewrite IHl.\n  auto.\nQed.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/017/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7352642449261071}}
{"text": "Require Import FunctionalExtensionality.\nRequire Import ProofIrrelevance.\n\n(*Require Import Compare_dec.\nRequire Import Coq.Arith.Lt.*)\n(*Require Import Lia.*)\n\n(*Print Coq.Init.Peano.*)\n\nSection Numbers.\n(* Arithmetic facts *)\n\n(* Tactics:\ncase -- the weakest one\ndestruct -- sufficient for most tasks\nelim -- recursive destruct\ninduction -- destruct with induction\n\ninverse\n\nFor = and <>:\ndiscriminate.\ncontradiction.\n*)\n\nFact le_n_0_imp_eq_n_0 (n:nat) : n <= 0 -> n = 0.\nintro.\ninversion H.\nreflexivity.\nQed.\n\nFact le_0_n (n:nat) : 0 <= n.\nelim n.\n- apply le_n.\n- intros. apply le_S. assumption.\nQed.\n\nFact le_S_relax_left (n m:nat) : S n <= m -> n <= m.\nintro.\nelim H; intros.\n- apply le_S. apply le_n.\n- apply le_S. exact H1.\nQed.\n\nFact le_S_relax_right (n m:nat) : n <= m -> n <= S m.\napply le_S.\nQed.\n\nFact le_S_S (n m:nat) : n <= m <-> S n <= S m.\nsplit; intros.\n- elim H; intros.\n* apply le_n.\n* apply le_S. exact H1.\n- inversion H.\n* apply le_n.\n* apply le_S_relax_left. exact H1.\nQed.\n\nFact nle_0 (n:nat) : ~ S n <= 0.\nintro. inversion H.\nQed.\n\nFact nle_0' (n:nat) : ~ S n <= 0.\nexact (fun H =>\n    match H with\n    end).\nQed.\n\nFact nle_1_0 : ~ 1 <= 0.\napply nle_0.\nQed.\n\nDefinition nle_0_term (n:nat) : ~ S n <= 0 :=\nfun e:S n <= 0 =>\nlet f1 : S n = 0 -> False := fun (e:S n = 0) =>\n  eq_ind (S n) (fun e : nat => match e with\n                           | 0 => False\n                           | S _ => True\n                           end) I 0 e\nin\nlet f2 : forall m:nat, S m = 0 -> False := fun (m:nat) (e:S m = 0) =>\n  eq_ind (S m) (fun e : nat => match e with\n                           | 0 => False\n                           | S _ => True\n                           end) I 0 e\nin\nmatch e in le _ b return (b = 0 -> False) with\n  | le_n _ => f1\n  | le_S _ m x => f2 m\nend eq_refl.\n\nFact neq_Sn_n (n:nat) : S n <> n.\ninduction n.\n- discriminate.\n- injection.\nexact IHn.\nQed.\n\nFact nle_Sn_n (n:nat) : ~ S n <= n.\ninduction n.\n- apply nle_0.\n- intro.\napply IHn.\napply le_S_S.\nexact H.\nQed.\n\nPrint le_ind.\n\n(*Require Import Coq.Program.Equality.*)\n\nFact le_trans (n m k:nat) : n <= m -> m <= k -> n <= k.\nintros.\ninduction H.\n- assumption.\n- apply IHle. apply le_S_relax_left in H0. exact H0.\nQed.\n\nFact le_antisymmetry (n m:nat) : n <= m -> m <= n -> n = m.\nintros.\ninduction H.\n- reflexivity.\n- apply (le_trans (S m) n m) in H0.\n* apply nle_Sn_n in H0. contradiction.\n* assumption.\nQed.\n\nFact le_S4 (n m:nat) : n <= m -> n <> m -> S n <= m.\nintros.\ninduction H.\n- contradiction H0. reflexivity.\n- apply (proj1 (le_S_S n m)). exact H.\nQed.\n\nFact lt_irrefl (n:nat) : ~ n < n.\napply nle_Sn_n.\nQed.\n\nFact lt_assym (n m:nat) : n < m -> ~ m < n.\nintro. intro. unfold lt in *.\ninduction H.\n- apply le_S_relax_left in H0. eapply nle_Sn_n. exact H0.\n- apply IHle. apply le_S_relax_left. exact H0.\nQed.\n\nFact nlt_0 (n:nat) : ~ n < 0.\napply nle_0.\nQed.\n\nFact lt_S_relax_right (n m:nat) : n < m -> n < S m.\napply le_S.\nQed.\n\nFact exists_Sx (n:nat) : n <> 0 -> (~ forall x:nat, ~ n = S x).\nintro.\ndestruct n.\n- contradiction H. reflexivity.\n- intro. eapply H0. reflexivity.\nQed.\n\nFact exists_Sx2 (n:nat) : n <> 0 -> (exists x:nat, n = S x).\nintro.\ndestruct n.\n- contradiction H. reflexivity.\n- eapply ex_intro. reflexivity.\nQed.\n\nDefinition exists_Sx_term (n:nat) : n <> 0 -> (~ forall x:nat, ~ n = S x) :=\nfun H : n <> 0 =>\nfun H2 : forall x:nat, ~ n = S x =>\nmatch n as n1 return ~ n = n1 with\n| O => H\n| S n0 => H2 n0\nend eq_refl.\n\nDefinition exists_Sx2_term (n:nat) : n <> 0 -> (exists x:nat, n = S x) :=\n(match n as n0 return (n0 <> 0 -> exists x:nat, n0 = S x) with\n| O => fun H : 0 <> 0 =>\n  False_ind _ (H eq_refl)\n| S x0 => fun _ : S x0 <> 0 =>\n  ex_intro (fun x => S x0 = S x) x0 eq_refl\nend).\n\n(*Fact lt_discrim : forall (n m:nat), n < m -> S n <> m -> S n < m.\nintros.\ndestruct H as [|a].\n- contradiction.\n- unfold lt.\napply le_n_S. exact H.\nQed.\n\nFact lt_discrim2 : forall (n m:nat), n < S m -> n <> m -> n < m.\nintros.\napply le_S_S.\napply lt_discrim.\n- exact H.\n- injection. exact H0.\nQed.*)\n\n(*- induction (zerop n).\napply le_n_S. exact H.*)\nEnd Numbers.\n\n\n\n(** Ugly fact about default implementation of [sub] *)\nTheorem sub_non_distrib : exists (x y z : nat), x + (y - z) <> (x + y) - z.\napply (ex_intro _ 1).\napply (ex_intro _ 0).\napply (ex_intro _ 1).\ndiscriminate.\nQed.\n\nDefinition option_bind {A B:Type} (o:option A) (k:A -> option B) : option B :=\n  match o with\n    | None => None\n    | Some x => k x\n  end.\n\nDefinition option_join {A:Type} (o:option (option A)) : option A := \n  option_bind o (fun x => x).\n\nDefinition option_join' {A:Type} (o:option (option A)) : option A := match o with\n  | None => None\n  | Some None => None\n  | Some (Some x) => Some x\nend.\n\nDefinition option_bind' {A B:Type} (o:option A) (k:A -> option B) : option B :=\n  option_join' (option_map k o).\n\nInfix \">>=\" := option_bind (at level 65).\n\nNotation \"x |> f\" := (f x)\n  (at level 90, left associativity, only parsing).\nNotation \"f <| x\" := (f x)\n  (at level 90, left associativity, only parsing).\n\n(* Safe predecessor function *)\nDefinition s_pred (n:nat) : n <> 0 -> nat.\nintro.\ndestruct n.\n* contradiction.\n* exact n.\nDefined.\n\nPrint s_pred.\n\n\n\nFixpoint m4 (n m:nat) (H:m <= n) : nat.\ndestruct (n) as [|x]; destruct m as [|y].\n- exact O.\n- apply nle_0 in H. contradiction.\n- exact n.\n- apply le_S_S in H.\nexact (m4 x y H).\nDefined.\n\nNotation \"n -( H )- m\" := (m4 n m H) (at level 50).\n(* Notation \"n -- m\" := (m4 n m _) (at level 50, only printing).\n *)\n(** Proof is irrelevant *)\nFact m4_irrelevant (n m:nat) (H1 H2:m <= n) : n -(H1)- m = n -(H2)- m.\nrewrite (proof_irrelevance <| m <= n <| H1 <| H2).\nreflexivity.\nQed.\n\nFact m4_n_0 (n:nat) : n -(le_0_n n)- 0 = n.\ncase n; reflexivity.\nQed.\n\nFact m3_S2 (n m:nat) (H:m <= n) :\n  let H2:(S m <= S n) := (le_S_S m n |> @proj1 _ _) H in\n  S n -(H2)- S m = n -(H)- m.\nintro.\nunfold m4.\nfold m4.\napply m4_irrelevant.\nQed.\n\nLemma S_inj (x y:nat) : S x = S y -> x = y.\nintro.\ninjection H.\ntrivial.\nQed.\n\nFact m3_S_n (n m:nat) (H1:m <= n) :\n  exists H2,\n  S n -(H2)- m = S (n -(H1)- m).\napply (ex_intro _ (le_S_relax_right _ _ H1)).\n\ninduction m as [|m1].\n- shelve.\n- apply S_inj.\nsimpl. (*applies le_S_S*)\nset (HSS := match le_S_S m1 n with\n   | conj _ H0 => H0\n   end (le_S_relax_right (S m1) n H1)).\nrewrite <- IHm1.\n\nLemma doge (n m:nat) (H1:S m <= n) :\n  exists H2,\n  n -(H2)- m <> 0.\nset (H2 := le_S_relax_left _ _ H1).\napply (ex_intro _ H2).\ninduction n.\n- shelve.\n- \n(* destruct H1 as [| x].\n- shelve.\n- *) \n\n\nFact m3_n_S (n m:nat) (H1:S m <= n) :\n  exists H2 H3,\n  n -(H1)- S m = s_pred (n -(H2)- m) H3.\nset (H2 := le_S_relax_left _ _ H1).\napply (ex_intro _ H2).\nassert (H3 : n -(H2)- m <> 0).\n\n(*\nFixpoint m3 (n m:nat) : option nat := \nmatch n with\n| O => match m with\n  | O => Some O\n  | S _ => None\n  end\n| S n' => match m with\n  | O => Some n\n  | S m' => m3 n' m'\n  end\nend.\n*)\n\nFixpoint m3 (n m:nat) : option nat := match (n, m) with\n  | (O, O) => Some O\n  | (O, S _) => None\n  | (S _, O) => Some n\n  | (S n', S m') => m3 n' m'\nend.\n\nNotation \"n -- m\" := (m3 n m) (at level 50).\n\nFact m3_n_0 (n:nat) : n -- 0 = Some n.\ncase n; reflexivity.\nQed.\n\nFact m3_S2 (n m:nat) : n -- m = S n -- S m.\nreflexivity.\nQed.\n\nFact m3_n_n (n:nat) : n -- n = Some 0.\ninduction n.\n- reflexivity.\n- rewrite <- m3_S2. assumption.\nQed.\n\nFact m3_0_n (n:nat) : 0 -- n <> None -> n = 0.\nintro.\ndestruct n.\n- reflexivity.\n- contradiction H. reflexivity.\nQed.\n\n(* experiments *)\n\nDefinition fail_if_0 (n:nat) : option nat :=\n  match n with\n    | O => None\n    | x => Some x\n  end.\n\nDefinition f2 (on:option nat) : option nat :=\n  match on with\n    | None\n    | Some O => None\n    | Some x => Some (S x)\n  end.\n\nDefinition f2' (on:option nat) : option nat :=\n  option_map S (on >>= fail_if_0).\n\nFact eq_sub (A B:Type) (f:A -> B) (x y:A) : x = y -> f x = f y.\nintro.\napply f_equal.\nassumption.\nQed.\n\nFact f2_eq : f2 = f2'.\napply functional_extensionality.\nintro.\ndestruct x; try (destruct n); reflexivity.\nQed.\n\nDefinition maybeS : option nat -> option nat := option_map S.\n\nLemma maybeS_inj (x y: option nat) : maybeS x = maybeS y -> x = y.\nintro.\ndestruct x.\n- destruct y.\n* compute in H.\nf_equal.\ninjection H.\ntrivial.\n* compute in H. discriminate.\n- destruct y.\n* compute in H. discriminate.\n* reflexivity.\nQed.\n\nDefinition safe_unwrap (A:Set) (o:option A) : o <> None -> A :=\n  option_rec (fun o0 : option A => o0 <> None -> A)\n  (fun (a : A) (_ : Some a <> None) => a)\n  (fun H : None <> None => False_rec A (H eq_refl)) o.\n\nDefinition safe_unwrap_tactics (A:Set) (o:option A) : o <> None -> A.\nelim o; intro.\n- intro. exact a.\n- contradiction H.\nreflexivity.\nDefined.\n\nGoal safe_unwrap = safe_unwrap_tactics.\nreflexivity.\nQed.\n\n(* Fallible predecessor function *)\nDefinition maybe_pred_f (n:nat) : option nat :=\n  match n with\n    | O => None\n    | S x => Some x\n  end.\n\nNotation \"'maybe_pred' o\" := (option_bind o maybe_pred_f) (at level 0).\n\n(* Safe predecessor function *)\nDefinition s_pred (n:nat) : n <> 0 -> nat.\nintro.\ndestruct n.\n* contradiction.\n* exact n.\nDefined.\n\n(* idk if i actually need this lemma *)\nLemma maybe_pred_inj (x y: option nat) :\n  x <> Some 0 -> y <> Some 0 -> maybe_pred x = maybe_pred y -> x = y.\nintros H1 H2 H3.\ndestruct x.\n- destruct y.\n* f_equal.\ndestruct n.\n+ contradiction.\n+ destruct n0.\n++ contradiction.\n++ f_equal. injection H3. trivial.\n* destruct n.\n+ contradiction. \n+ discriminate.\n- destruct y.\n* destruct n.\n+ contradiction.\n+ discriminate.\n* reflexivity.\nQed.\n\nLemma doge (x y:option nat) : y <> (Some 0) -> x = maybe_pred y -> maybeS x = y.\nintros H1 H2.\ndestruct y; rewrite H2.\n- destruct n.\n* contradiction H1. reflexivity.\n* reflexivity.\n- reflexivity.\nQed.\n\n(* Lemma doge2 (n m:nat) : n <> m -> n -- m <> Some 0.\nintro.\ninduction n.\n- shelve.\n- *)\n\nFact m3_lemma_1_test2 (n m:nat) : (S m) <= n -> n -- S m = maybe_pred (n -- m).\nintro.\ninduction n.\n- compute.\ndestruct m; reflexivity.\n- rewrite <- m3_S2.\napply doge in IHn.\nshelve.\n\n\nrewrite <- IHn.\n+\ndestruct m.\n* apply nle_0 in H. contradiction.\n* rewrite <- m3_S2.\napply le_S in H.\nshelve.\n+ apply le_S_relax_left. assumption.\nUnshelve.\nAbort.\n\n(* It's false lol *)\nFact m3_lemma_1_test (n m:nat) : n < m -> n -- S m = maybeS (n -- m).\nunfold lt.\nintro.\ninduction n.\n- compute.\ndestruct m.\n* apply nle_0 in H. contradiction.\n* reflexivity.\n- rewrite <- m3_S2.\nrewrite (maybeS_inj _ (maybeS (S n -- m))). reflexivity.\nrewrite <- IHn.\n+\ndestruct m.\n* apply nle_0 in H. contradiction.\n* rewrite <- m3_S2.\napply le_S in H.\nshelve.\n+ apply le_S_relax_left. assumption.\nUnshelve.\nAbort.\n\n\nFact m3_lemma_1_test (n m:nat) : n -- S m = f2 (n -- m).\ninduction n.\n- compute.\ncase m; reflexivity.\n- apply (f_equal f2) in IHn.\nall: swap 1 2.\nunfold m3 in *.\nfold m3 in *.\n\n\nFact m3_lemma_1 (n m:nat) : n -- S m <> None -> n -- m <> None.\nintro.\ninduction n.\nall: swap 1 2.\nunfold m3 in *.\nfold m3 in *.\n\n\nFact m3_lemma_2 (n m:nat) : n -- m <> None -> m <= n.\nintro.\ninduction m.\nall:swap 1 2.\napply le_S4.\napply IHm.\n\nFact m3_lemma'_1 (n m:nat) : m <= n -> n -- m <> None.\nintro.\ninduction H.\nall: swap 1 2.\n\n\n(*\nFact ok (n m:nat) : n -- m <> None -> S n -- m <> None.\nintro.\ninduction n.\n- apply m3_0_n in H.\nrewrite H.\ndiscriminate.\n- apply IHn.\n*)\n\n(*\nFact ok (n m:nat) : n -- m <> None -> S n -- m <> None.\nintro.\nunfold m3 in *.\nfold m3 in *.\nset (f2 := match m with\n| 0 => Some (S n)\n| S m' => n -- m'\nend).\nrefine (fun e => match e in _ = x return False with\n  | eq_refl _ => _\nend).\n(*match m with\n  | O => 1\n  | S x => 2\nend*)\n(*match e with\n  | eq_refl _ => 1\nend*)\nelim m.\n* discriminate.\n* intros.\n*)\n\nFact m3nz (n m:nat) : m <= n -> n -- m <> None.\nintro.\ninduction H.\n- rewrite (m3_n_n m). discriminate.\n-\n\n(*\nFact m3nz (n m:nat) : m <= n -> n -- m <> None.\nintro.\ninduction m.\n- rewrite (m3_n_0 n). discriminate.\n- elim H.\n* rewrite m3_n_n. discriminate.\n* intros.\nset (k := m0) in *.\nunfold m3.\napply le_S_relax_left in H.\napply IHm in H.\n\nFact m3nz (n m:nat) : m <= n -> n -- m <> None.\nintro.\ninduction n.\n- apply le_n_0_iff_eq_n_0 in H. rewrite H. discriminate.\n- induction m.\n* rewrite (m3_n_0 (S n)). discriminate.\n* \n*)\n\nTheorem sub3_distrib : ~ exists (x y z : nat), x + (y - z) <> (x + y) - z.\n\n(*\nzerop\nlt_asym\nlt_discrim\napply (lt_irrefl 0 H).\napply lt_S_n in H.\n*)", "meta": {"author": "serid", "repo": "coq-theories", "sha": "8401361ad241f3188f4c1a61060114c646f935e4", "save_path": "github-repos/coq/serid-coq-theories", "path": "github-repos/coq/serid-coq-theories/coq-theories-8401361ad241f3188f4c1a61060114c646f935e4/Minus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8670357546485408, "lm_q1q2_score": 0.7352183686339606}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Preliminaries for Provability in Hilbert-style calculi\n*)\n\nRequire Import List.\n\n(* propositional formulae s, t ::= a | s → t *)\nInductive formula : Set :=\n  | var : nat -> formula\n  | arr : formula -> formula -> formula.\n\n(* substitute ζ t replaces each variable n in t by ζ n *)\nFixpoint substitute (ζ: nat -> formula) (t: formula) : formula :=\n  match t with\n  | var n => ζ n\n  | arr s t => arr (substitute ζ s) (substitute ζ t)\n  end.\n\n(* Hilbert-style calculus *)\nInductive hsc (Gamma: list formula) : formula -> Prop :=\n  | hsc_var : forall (ζ: nat -> formula) (t: formula), In t Gamma -> hsc Gamma (substitute ζ t)\n  | hsc_arr : forall (s t : formula), hsc Gamma (arr s t) -> hsc Gamma s -> hsc Gamma t.\n", "meta": {"author": "uds-psl", "repo": "2020-types-propositional-calculi", "sha": "87d61951f216881ccb45984349031915b2f842ee", "save_path": "github-repos/coq/uds-psl-2020-types-propositional-calculi", "path": "github-repos/coq/uds-psl-2020-types-propositional-calculi/2020-types-propositional-calculi-87d61951f216881ccb45984349031915b2f842ee/HSC/HSC_prelim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067228145365, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7351485570572689}}
{"text": "(* Exercise 56 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_056 : (forall x, P x -> forall y, R y x) -> ~(exists x, P x /\\ ~ R x x).\nProof.\nimp_i a1.\nneg_i (1=1) a2.\nexi_e (exists x:D, P x /\\ ~R x x) a a3.\nhyp a2.\nneg_e (R a a).\ncon_e2 (P a).\nhyp a3.\nall_e (forall y:D, R y a) a.\nimp_e (P a).\nall_e (forall x:D, P x -> forall y:D, R y x) a.\nhyp a1.\ncon_e1 (~R a a).\nhyp a3.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred056.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067244294587, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7351485486765666}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import PL.RTClosure.\nImport ListNotations.\nLocal Open Scope Z.\nRequire Import PL.Imp.\nRequire Import FunctionalExtensionality.\n\n(** Splay tree is a kind of self-balanced binary search tree. You may learn this\n    data structure from online resources like:\n\n    <<\n       https://people.eecs.berkeley.edu/~jrs/61b/lec/36\n    >>\n\n    In this task, you should prove the functional correctness of the splay\n    operation, the key operation of splay trees. We provide a step-wise\n    description of splay. *)\n\nDefinition Key: Type := Z.\nDefinition Value: Type := Z.\n\nRecord Node  := {\n   key_of_node : Key;\n   value_of_node : Value\n}.\n\nInductive tree : Type :=\n| E : tree\n| T : tree -> Node -> tree -> tree.\n\nDefinition optionZ_lt (ok1 ok2: option Key): Prop :=\n  match ok1, ok2 with\n  | Some k1, Some k2 => k1 < k2\n  | _, _ => True\n  end.\n  \nDefinition optionZ_le (ok1 ok2: option Key): Prop :=\n  match ok1, ok2 with\n  | Some k1, Some k2 => k1 <= k2\n  | _, _ => True\n  end.\n\nInductive SearchTree : option Key -> tree -> option Key -> Prop :=\n| ST_E : forall lo hi, optionZ_lt lo hi -> SearchTree lo E hi\n| ST_T: forall lo l n r hi,\n    SearchTree lo l (Some (key_of_node n)) ->\n    SearchTree (Some (key_of_node n)) r hi ->\n    SearchTree lo (T l n r) hi.\n\nDefinition relate_map := Key -> option Value .\n\nDefinition relate_default: relate_map := fun x => None.\n\nDefinition relate_single (k: Key) (v: Value): relate_map :=\n  fun x =>\n    if Z.eq_dec x k then Some v else None.\n\nDefinition combine (m1 m2: relate_map): relate_map :=\n  fun x =>\n    match m1 x, m2 x with \n    | None, Some v => Some v\n    | Some v, None => Some v\n    | _ ,_ => None\n    end.\n\nInductive Abs : tree -> relate_map -> Prop :=\n| Abs_E :  Abs E relate_default\n| Abs_T: forall l n r lm rm,\n    Abs l lm ->\n    Abs r rm ->\n    Abs\n      (T l n r)\n      (combine lm\n         (combine (relate_single (key_of_node n) (value_of_node n)) rm)).\n\nInductive LeftOrRight :=\n| L: LeftOrRight\n| R: LeftOrRight.\n\nDefinition half_tree: Type := (LeftOrRight * Node * tree)%type.\n\nDefinition partial_tree: Type := list half_tree.\n\nInductive SearchTree_half_in: (*inner border of partial tree*)\n  option Key -> partial_tree -> option Key -> Prop :=\n| ST_in_nil:\n    forall lo hi, optionZ_lt lo hi -> SearchTree_half_in lo nil hi\n| ST_in_cons_L:\n    forall lo hi h l n,\n      SearchTree_half_in lo h hi ->\n      SearchTree lo l (Some (key_of_node n)) ->\n      SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) hi\n| ST_in_cons_R:\n    forall lo hi h r n,\n      SearchTree_half_in lo h hi ->\n      SearchTree (Some (key_of_node n)) r hi ->\n      SearchTree_half_in lo ((R, n, r) :: h) (Some (key_of_node n)).\n\nFact example:\n  forall n1 n2,\n  key_of_node n1 = 11 ->\n  value_of_node n1 = 11 ->\n  key_of_node n2 = 9 ->\n  value_of_node n2 = 9 ->\n  SearchTree_half_in (Some (key_of_node n1)) [(L, n1,(T E n2 E))] (Some 10).\nProof.\n  intros.\n  assert (SearchTree_half_in (Some 8) [] (Some 10)).\n  { constructor. simpl. lia. }\n  assert (SearchTree (Some 8) (T E n2 E) (Some (key_of_node n1))).\n  { constructor. constructor. rewrite H1. constructor.\n    constructor. rewrite H, H1. constructor. }\n  pose proof ST_in_cons_L _ _ _ _ _ H3 H4.\n  exact H5.\nQed.\n\nInductive Abs_half : partial_tree -> relate_map -> Prop :=\n| Abs_half_nil : Abs_half nil relate_default\n| Abs_half_cons: forall LR n t h m1 m2,\n    Abs t m1 ->\n    Abs_half h m2 ->\n    Abs_half\n      ((LR, n, t) :: h)\n      (combine m1\n         (combine (relate_single (key_of_node n) (value_of_node n)) m2)).\n\nInductive SearchTree_half_out: (*outer border of partial tree*)\n  option Key -> partial_tree -> option Key ->  Prop :=\n| ST_out_nil:\n    forall lo hi, optionZ_lt lo hi -> SearchTree_half_out lo nil hi \n| ST_out_cons_L:\n    forall lo hi h l n,\n      SearchTree_half_out lo h hi ->\n      SearchTree lo l (Some (key_of_node n)) ->\n      optionZ_lt (Some (key_of_node n)) hi ->\n      SearchTree_half_out lo ((L, n, l) :: h) hi\n| ST_out_cons_R:\n    forall lo hi h r n,\n      SearchTree_half_out lo h hi ->\n      SearchTree (Some (key_of_node n)) r hi ->\n      optionZ_lt lo (Some (key_of_node n)) ->\n      SearchTree_half_out lo ((R, n, r) :: h) hi.\n\nInductive splay_step: partial_tree * tree -> partial_tree * tree -> Prop :=\n| Splay_LL: forall h a b c d n1 n2 n3,\n    splay_step\n      ((R, n2, c) :: (R, n3, d) :: h, T a n1 b)\n      (h, T a n1 (T b n2 (T c n3 d)))\n| Splay_RR: forall h a b c d n1 n2 n3,\n    splay_step\n      ((L, n2, b) :: (L, n1, a) :: h, T c n3 d)\n      (h, T (T (T a n1 b) n2 c) n3 d)\n| Splay_RL: forall h a b c d n1 n2 n3, (* right child of left child *)\n    splay_step\n      ((L, n1, a) :: (R, n3, d) :: h, T b n2 c)\n      (h, T (T a n1 b) n2 (T c n3 d))\n| Splay_LR: forall h a b c d n1 n2 n3, (* left child of right child *)\n    splay_step\n      ((R, n3, d) :: (L, n1, a) :: h, T b n2 c)\n      (h, T (T a n1 b) n2 (T c n3 d))\n| Splay_L: forall x y z n1 n2,\n    splay_step ((R, n2, z) :: nil, T x n1 y) (nil, T x n1 (T y n2 z))\n| Splay_R: forall x y z n1 n2,\n    splay_step ((L, n1, x) :: nil, T y n2 z) (nil, T (T x n1 y) n2 z)\n.\n\nDefinition splay (h: partial_tree) (t t': tree): Prop :=\n  clos_refl_trans splay_step (h, t) (nil, t').\n\nDefinition preserves: Prop :=\n  forall HI LO hi lo h t t',\n    optionZ_lt (Some LO) (Some lo) ->\n    optionZ_lt (Some hi) (Some HI) ->\n    SearchTree_half_in (Some lo) h (Some hi) ->\n    SearchTree_half_out (Some LO) h (Some HI) ->\n    SearchTree (Some lo) t (Some hi)->\n    splay h t t' ->\n    SearchTree (Some LO) t' (Some HI).\n\nDefinition correct: Prop :=\n  forall h t t' m1 m2 lo hi LO HI,\n    Abs_half h m1 ->\n    Abs t m2 ->\n    splay h t t' ->\n    SearchTree (Some lo) t (Some hi)->(* new *)\n    SearchTree_half_in (Some lo) h (Some hi)->(* new *)\n    SearchTree_half_out (Some LO) h (Some HI)->(* new *)\n    optionZ_lt (Some LO) (Some lo) ->\n    optionZ_lt (Some hi) (Some HI) ->\n    Abs t' (combine m1 m2).\n\nDefinition splay' :partial_tree * tree -> partial_tree * tree -> Prop :=\n  clos_refl_trans splay_step .\n\nLemma splay'_splay :\n  forall h t t',\n  splay' (h,t) (nil,t') -> splay h t t'.\nProof.\n  intros.\n  unfold splay.\n  unfold splay' in H.\n  exact H.\nQed.\n\nLemma splay_splay':\n  forall h t t',\n  splay h t t' -> splay' (h,t) (nil,t').\nProof.\n  intros. unfold splay'. unfold splay in H. exact H.\nQed.\n\n(* =============================================================*)\n(* =====================Proof of preserves =====================*)\n(* =============================================================*)\n\nLemma lt_le:\n  forall a b,\n  optionZ_lt a b -> optionZ_le a b.\nProof.\n  intros. destruct a;destruct b;simpl in *;try tauto. lia.\nQed.\n\nLemma lt_le':\n  forall a b,\n  optionZ_lt (Some a) (Some b) -> optionZ_le (Some a) (Some (b-1)).\nProof.\n  intros. simpl in *. lia.\nQed.\n\nLemma lt_le'':\n  forall a b,\n  optionZ_lt (Some a) (Some b) -> optionZ_le (Some (a+1)) (Some b).\nProof.\n  intros.\n  simpl in *.\n  lia.\nQed.\n\nLemma lt_le''':\n  forall a b,\n  optionZ_lt (Some a) (Some (b+1)) -> optionZ_le (Some a) (Some b).\nProof.\n  intros. simpl in *. lia.\nQed.\n\nLemma optionZ_lt_cong: forall n lo hi,\noptionZ_lt (Some (n)) hi->\noptionZ_lt lo (Some (n))->\noptionZ_lt lo hi.\nProof.\nintros. induction hi; simpl in H;simpl; induction lo; simpl in H0; simpl; try exact I; unfold Key in *. lia. Qed. \n\nLemma optionZ_le_cong: forall n lo hi,\noptionZ_le (Some (n)) hi->\noptionZ_le lo (Some (n))->\noptionZ_le lo hi.\nProof.\nintros. induction hi; simpl in H;simpl; induction lo; simpl in H0; simpl; try exact I; unfold Key in *. lia. Qed.\n\nLemma optionZ_let_cong: forall n lo hi,\noptionZ_le (Some (n)) hi->\noptionZ_lt lo (Some (n))->\noptionZ_lt lo hi.\nProof.\nintros. induction hi; simpl in H;simpl; induction lo; simpl in H0; simpl; try exact I; unfold Key in *. lia. Qed.\n\nLemma optionZ_lte_cong: forall n lo hi,\noptionZ_lt (Some (n)) hi->\noptionZ_le lo (Some (n))->\noptionZ_lt lo hi.\nProof.\nintros. induction hi; simpl in H;simpl; induction lo; simpl in H0; simpl; try exact I; unfold Key in *. lia. Qed.\n\nLemma optionZ_lt_SearchTree: forall l lo hi,\nSearchTree lo l hi\n-> optionZ_lt lo hi.\nProof.\nintros. induction H. tauto. pose proof optionZ_lt_cong _ _ _ IHSearchTree2 IHSearchTree1. tauto. \nQed.\n\nLemma looser_SearchTree_l: \n  forall lo' lo hi t,\n    optionZ_lt lo (Some lo') -> \n    SearchTree (Some lo') t (Some hi) ->\n    SearchTree lo t (Some hi).\nProof.\n  intros. revert H. revert lo. revert H0. revert lo'. revert hi.\n  induction t;subst.  \n  2:{ intros. inversion H0; subst. constructor. \n      specialize (IHt1 (key_of_node n) lo' H6 lo H). \n      exact IHt1. exact H7. }\n  intros. constructor. \n  pose proof optionZ_lt_SearchTree _ _ _ H0. \n  pose proof optionZ_lt_cong _ _ _ H1 H. \n  tauto. \nQed.\n\nLemma looser_SearchTree_r: \n  forall hi' lo hi t,\n    optionZ_lt (Some hi') hi -> \n    SearchTree (Some lo) t (Some hi') ->\n    SearchTree (Some lo) t hi.\nProof.\n  intros. revert H. revert hi. revert H0. revert lo. revert hi'. \n  induction t;subst.  \n  2:{ intros. inversion H0; subst. \n      constructor. exact H6. \n      specialize (IHt2 hi' (key_of_node n) H7 hi H). \n      exact IHt2. }\n  intros. constructor. \n  pose proof optionZ_lt_SearchTree _ _ _ H0. \n  pose proof optionZ_lt_cong _ _ _ H H1. \n  tauto. \nQed.\n\nLemma looser_SearchTree: \n  forall lo' hi' lo hi t,\n    optionZ_lt lo (Some lo') -> \n    optionZ_lt (Some hi') hi ->\n    SearchTree (Some lo') t (Some hi') ->\n    SearchTree lo t hi.\nProof.\nintros. \ninversion H1. subst. constructor. pose proof optionZ_lt_cong _ _ _ H0 H2. pose proof optionZ_lt_cong _ _ _ H3 H. exact H4.  \nsubst. constructor. pose proof looser_SearchTree_l _ _ _ _ H H2. tauto. pose proof looser_SearchTree_r _ _ _ _ H0 H3. tauto. Qed.\n\nLemma looser_SearchTree_l_e: \n  forall lo' lo hi t,\n    optionZ_le lo (Some lo') -> \n    SearchTree (Some lo') t (Some hi) ->\n    SearchTree lo t (Some hi).\nProof.\n  intros. revert H. revert lo. revert H0. revert lo'. revert hi.\n  induction t;subst.  \n  2:{ intros. inversion H0; subst. constructor. \n      specialize (IHt1 (key_of_node n) lo' H6 lo H). \n      exact IHt1. exact H7. }\n  intros. constructor. \n  pose proof optionZ_lt_SearchTree _ _ _ H0. \n  pose proof optionZ_lte_cong _ _ _ H1 H. \n  tauto. \nQed.\n\nLemma looser_SearchTree_r_e: \n  forall hi' lo hi t,\n    optionZ_le (Some hi') hi -> \n    SearchTree (Some lo) t (Some hi') ->\n    SearchTree (Some lo) t hi.\nProof.\n  intros. revert H. revert hi. revert H0. revert lo. revert hi'. \n  induction t;subst.  \n  2:{ intros. inversion H0; subst. \n      constructor. exact H6. \n      specialize (IHt2 hi' (key_of_node n) H7 hi H). \n      exact IHt2. }\n  intros. constructor. \n  pose proof optionZ_lt_SearchTree _ _ _ H0. \n  pose proof optionZ_let_cong _ _ _ H H1. \n  tauto. \nQed.\n\nLemma looser_SearchTree_le:\n  forall lo' hi' lo hi t,\n    optionZ_le lo (Some lo') -> \n    optionZ_le (Some hi') hi ->\n    SearchTree (Some lo') t (Some hi') ->\n    SearchTree lo t hi.\nProof.\nintros. \ninversion H1; subst. constructor. pose proof optionZ_let_cong _ _ _ H0 H2. pose proof optionZ_lte_cong _ _ _ H3 H. exact H4.  \nsubst. constructor. pose proof looser_SearchTree_l_e _ _ _ _ H H2. tauto. pose proof looser_SearchTree_r_e _ _ _ _ H0 H3. tauto. Qed.\n\n\nFixpoint supremum (t: tree): option Key:= \n  match t with \n  | E => None\n  | T _ n E => Some (key_of_node n)\n  | T l n r => supremum r\n  end.\n\nLemma sup_fact':\n  forall t,\n    t <> E ->\n    exists v, supremum t = Some v.\nProof.\n  intros.\n  induction t.\n  + tauto.\n  + destruct t2.\n    { exists (key_of_node n). simpl. reflexivity. }\n    assert (T t2_1 n0 t2_2 <> E).\n    { pose proof classic (T t2_1 n0 t2_2 = E).\n      destruct H0;[inversion H0|tauto]. }\n    specialize (IHt2 H0).\n    destruct IHt2.\n    exists x.\n    simpl in *.\n    exact H1.\nQed.\n\nLemma sup_fact :\n  forall l n r, exists v, supremum (T l n r) = Some v.\nProof.\n  intros.\n  assert ((T l n r) <> E).\n  { pose proof classic ((T l n r) = E). destruct H;[inversion H|tauto]. }\n  apply sup_fact' in H. tauto.\nQed.\n\nLemma sup_property:\n  forall lo hi t sup,\n    SearchTree lo t hi ->\n    supremum t = sup ->\n    optionZ_lt sup hi.\nProof.\n  intros.\n  revert sup lo hi H H0.\n  induction t;intros.\n  + subst. simpl. tauto.\n  + destruct t2.\n    { simpl in H0. subst.\n      inversion H;subst.\n      inversion H6;subst.\n      exact H0.\n    }\n    inversion H. subst lo0 l n1 r hi0.\n    specialize (IHt2 sup _ _ H7).\n    simpl in *.\n    specialize (IHt2 H0).\n    exact IHt2.\nQed.\n\nLemma SearchTree_sup:\n  forall lo t hi sup,\n    SearchTree lo t hi ->\n    supremum t = (Some sup) ->\n    SearchTree lo t (Some (sup+1)).\nProof.\n  intros.\n  revert lo hi sup H H0 .\n  induction t;intros.\n  + discriminate H0.\n  + inversion H. subst lo0 l n0 r hi0.\n    constructor;[tauto|].\n    destruct t2.\n    { simpl in H0. injection H0. intros. rewrite H1.\n      constructor. simpl. lia. }\n    specialize (IHt2 _ _ sup H7).\n    simpl in *.\n    specialize (IHt2 H0).\n    exact IHt2.\nQed.\n\nFixpoint infimum (t: tree): option Key:= \n  match t with \n  | E => None\n  | T E n _ => Some (key_of_node n)\n  | T l n r => infimum l\n  end.\n\n\nLemma inf_fact':\n  forall t,\n    t <> E ->\n    exists v, infimum t = Some v.\nProof.\n  intros.\n  induction t.\n  + tauto.\n  + destruct t1.\n    { exists (key_of_node n). simpl. reflexivity. }\n    assert (T t1_1 n0 t1_2 <> E).\n    { pose proof classic (T t1_1 n0 t1_2 = E).\n      destruct H0;[inversion H0|tauto]. }\n    specialize (IHt1 H0).\n    destruct IHt1.\n    exists x.\n    simpl in *.\n    exact H1.\nQed.\n\nLemma inf_fact :\n  forall l n r, exists v, infimum (T l n r) = Some v.\nProof.\n  intros.\n  assert ((T l n r) <> E).\n  { pose proof classic ((T l n r) = E). destruct H;[inversion H|tauto]. }\n  apply inf_fact' in H. tauto.\nQed.\n\nLemma inf_property:\n  forall lo hi t inf,\n    SearchTree lo t hi ->\n    infimum t = inf ->\n    optionZ_lt lo inf.\nProof.\n  intros.\n  revert inf lo hi H H0.\n  induction t;intros.\n  + subst. destruct lo;simpl;tauto.\n  + destruct t1.\n    { simpl in H0. subst.\n      inversion H;subst.\n      inversion H5;subst.\n      exact H0.\n    }\n    inversion H. subst lo0 l n1 r hi0.\n    specialize (IHt1 inf _ _ H6).\n    simpl in *.\n    specialize (IHt1 H0).\n    exact IHt1.\nQed.\n\nLemma SearchTree_inf:\n  forall lo t hi inf,\n    SearchTree lo t hi ->\n    infimum t = (Some inf) ->\n    SearchTree (Some (inf-1)) t hi.\nProof.\n  intros.\n  revert lo hi inf H H0 .\n  induction t;intros.\n  + discriminate H0.\n  + inversion H. subst lo0 l n0 r hi0.\n    constructor;[|tauto].\n    destruct t1.\n    { simpl in H0. injection H0. intros. rewrite H1.\n      constructor. simpl. lia. }\n    specialize (IHt1 _ _ inf H6).\n    simpl in *.\n    specialize (IHt1 H0).\n    exact IHt1.\nQed.\n\n\nInductive R_in: partial_tree -> half_tree -> Prop :=\n  | R_in_base: forall n r h, R_in ((R, n, r)::h) (R, n, r)\n  | R_in_forward: forall n n' l r h, R_in h (R, n, r) -> R_in ((L, n', l)::h) (R, n, r).\n\nInductive all_L: partial_tree ->Prop :=\n  | AL_nil: all_L nil\n  | AL_forward: forall h n l, all_L h -> all_L ((L, n, l)::h).\n\nInductive L_in: partial_tree -> half_tree -> Prop :=\n  | L_in_base: forall n l h, L_in ((L, n, l)::h) (L, n, l)\n  | L_in_forward: forall n n' l r h, L_in h (L, n, l) -> L_in ((R, n', r)::h) (L, n, l).\n\nInductive all_R: partial_tree ->Prop :=\n  | AR_nil: all_R nil\n  | AR_forward: forall h n r, all_R h -> all_R ((R, n, r)::h).\n\nLemma all_L_or_R_in: forall h, \n  all_L h \\/ exists n r, R_in h (R, n, r).\nProof.\n  intros.\n  induction h.\n  + left. constructor.\n  + destruct IHh.\n    - destruct a. destruct p. destruct l.\n      -- left. constructor. tauto.\n      -- right. exists n,t. constructor.\n    - right.\n      destruct H as [n [r ?]].\n      destruct a. destruct p. destruct l.\n      -- exists n, r. constructor; tauto.\n      -- exists n0, t. constructor.\nQed.\n\nLemma not_all_L_R_in: forall h,\n  ~ all_L h <-> exists n r, R_in h (R, n, r) .\nProof.\n  intros.\n  unfold iff;split;intros.\n  + pose proof all_L_or_R_in h.\n    destruct H0;tauto.\n  + pose proof classic (all_L h).\n    destruct H0;[|tauto].\n    destruct H as [n [r ?]].\n    induction H;intros. \n    - inversion H0.\n    - inversion H0;subst. tauto.\nQed.\n\nLemma all_R_or_L_in: forall h, \n  all_R h \\/ exists n l, L_in h (L, n, l).\nProof.\n  intros.\n  induction h.\n  + left. constructor.\n  + destruct IHh.\n    - destruct a. destruct p. destruct l.\n      -- right. exists n,t. constructor.\n      -- left. constructor. tauto.\n    - right.\n      destruct H as [n [l ?]].\n      destruct a. destruct p. destruct l0.\n      -- exists n0, t. constructor.\n      -- exists n, l. constructor; tauto.\nQed.\n\nLemma not_all_R_L_in: forall h,\n  ~ all_R h <-> exists n l, L_in h (L, n, l) .\nProof.\n  intros.\n  unfold iff;split;intros.\n  + pose proof all_R_or_L_in h.\n    destruct H0;tauto.\n  + pose proof classic (all_R h).\n    destruct H0;[|tauto].\n    destruct H as [n [l ?]].\n    induction H;intros. \n    - inversion H0.\n    - inversion H0;subst. tauto.\nQed.\n\n\nLemma r_none_all_L: \n  forall n l h,\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) None ->\n    all_L ((L, n, l) :: h).\nProof.\n  intros.\n  pose proof classic (all_L ((L, n, l) :: h)).\n  pose proof not_all_L_R_in ((L, n, l) :: h).\n  destruct H0;[tauto|].\n  assert (exists (n0 : Node) (r : tree), R_in ((L, n, l) :: h) (R, n0, r)) by tauto.\n  clear H0 H1.\n  destruct H2 as [n0 [r ?]].\n  inversion H0;subst.\n  remember None as hi.\n  remember (R, n0, r) as ht.\n  revert n l H H0.\n  induction H2;intros;subst.\n  + inversion H;subst.\n    inversion H6;subst.\n  + inversion H;subst.\n    inversion H0;subst.\n    inversion H7;subst.\n    specialize (IHR_in Heqht _ _ H7 H4).\n    constructor. exact IHR_in.\nQed.\n\nLemma r_none_tighter: \n  forall n l h hi,\n    optionZ_le (Some (key_of_node n)) hi ->\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) None ->\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) hi.\nProof.\n  intros.\n  pose proof r_none_all_L _ _ _ H0.\n  inversion H1;subst.\n  revert n l H H0 H1.\n  induction H3;intros.\n  + inversion H0;subst.\n    clear H2.\n    assert (SearchTree_half_in lo [] hi).\n    { constructor. apply optionZ_lt_SearchTree in H8.\n      pose proof optionZ_let_cong _ _ _ H H8. exact H2. }\n    Print SearchTree_half_in.\n    pose proof ST_in_cons_L _ _ _ _ _ H2 H8.\n    exact H3.\n  + inversion H0;subst.\n    inversion H8;subst.\n    inversion H1;subst.\n    pose proof optionZ_lt_SearchTree _ _ _ H9.\n    pose proof optionZ_let_cong _ _ _ H H4.\n    apply lt_le in H6.\n    specialize (IHall_L _ _ H6 H8 H5).\n    Print SearchTree_half_in.\n    pose proof ST_in_cons_L _ _ _ _ _ IHall_L H9.\n    exact H7.\nQed.\n\nLemma l_none_all_R: \n  forall n r h,\n    SearchTree_half_in None ((R, n, r) :: h) (Some (key_of_node n)) ->\n    all_R ((R, n, r) :: h).\nProof.\n  intros.\n  pose proof classic (all_R ((R, n, r) :: h)).\n  pose proof not_all_R_L_in ((R, n, r) :: h).\n  destruct H0;[tauto|].\n  assert (exists (n0 : Node) (l : tree), L_in ((R, n, r) :: h) (L, n0, l)) by tauto.\n  clear H0 H1.\n  destruct H2 as [n0 [l ?]].\n  inversion H0;subst.\n  remember None as lo.\n  remember (L, n0, l) as ht.\n  revert n r H H0.\n  induction H2;intros;subst.\n  + inversion H;subst.\n    inversion H4;subst.\n  + inversion H;subst.\n    inversion H0;subst.\n    inversion H5;subst.\n    specialize (IHL_in Heqht _ _ H5 H3).\n    constructor. exact IHL_in.\nQed.\n\nLemma l_none_tighter: \n  forall n r h lo,\n    optionZ_le lo (Some (key_of_node n)) ->\n    SearchTree_half_in None ((R, n, r) :: h) (Some (key_of_node n)) ->\n    SearchTree_half_in lo ((R, n, r) :: h) (Some (key_of_node n)).\nProof.\n  intros.\n  pose proof l_none_all_R _ _ _ H0.\n  inversion H1;subst.\n  revert n r H H0 H1.\n  induction H3;intros.\n  + inversion H0;subst.\n    assert (SearchTree_half_in lo [] hi).\n    { constructor. apply optionZ_lt_SearchTree in H7.\n      pose proof optionZ_lte_cong _ _ _ H7 H. exact H2. }\n    Print SearchTree_half_in.\n    pose proof ST_in_cons_R _ _ _ _ _ H2 H7.\n    exact H3.\n  + inversion H0;subst.\n    inversion H6;subst.\n    inversion H1;subst.\n    pose proof optionZ_lt_SearchTree _ _ _ H8.\n    pose proof optionZ_lte_cong _ _ _ H2 H.\n    apply lt_le in H5.\n    specialize (IHall_R _ _ H5 H6 H4).\n    Print SearchTree_half_in.\n    pose proof ST_in_cons_R _ _ _ _ _ IHall_R H8.\n    exact H7.\nQed.\n\nLemma all_L_r_some_tighter:\n  forall n l h hi k,\n    all_L ((L, n, l) :: h) ->\n    optionZ_le (Some (key_of_node n)) hi ->\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) (Some k) ->\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) hi.\nProof.\n  intros.\n  inversion H;subst.\n  revert n l H0 H1 H.\n  induction H3;intros.\n  + inversion H1;subst.\n    assert (SearchTree_half_in lo [] hi).\n    { constructor. apply optionZ_lt_SearchTree in H8.\n      pose proof optionZ_let_cong _ _ _ H0 H8. exact H3. }\n    Print SearchTree_half_in.\n    pose proof ST_in_cons_L _ _ _ _ _ H3 H8.\n    exact H4.\n  + inversion H1;subst.\n    inversion H8;subst.\n    inversion H;subst.\n    pose proof optionZ_lt_SearchTree _ _ _ H9.\n    pose proof optionZ_let_cong _ _ _ H0 H4.\n    apply lt_le in H6.\n    specialize (IHall_L _ _ H6 H8 H5).\n    Print SearchTree_half_in.\n    pose proof ST_in_cons_L _ _ _ _ _ IHall_L H9.\n    exact H7.\nQed.\n\nLemma all_R_l_some_tighter:\n  forall n r h lo k,\n    all_R ((R, n, r) :: h) ->\n    optionZ_le lo (Some (key_of_node n)) ->\n    SearchTree_half_in (Some k) ((R, n, r) :: h) (Some (key_of_node n)) ->\n    SearchTree_half_in lo ((R, n, r) :: h) (Some (key_of_node n)).\nProof.\n  intros.\n  inversion H;subst.\n  revert n r H0 H1 H.\n  induction H3;intros.\n  + inversion H1;subst.\n    assert (SearchTree_half_in lo [] hi).\n    { constructor. apply optionZ_lt_SearchTree in H7.\n      pose proof optionZ_lte_cong _ _ _ H7 H0. exact H2. }\n    Print SearchTree_half_in.\n    pose proof ST_in_cons_R _ _ _ _ _ H2 H7.\n    exact H3.\n  + inversion H1;subst.\n    inversion H6;subst.\n    inversion H;subst.\n    pose proof optionZ_lt_SearchTree _ _ _ H8.\n    pose proof optionZ_lte_cong _ _ _ H2 H0.\n    apply lt_le in H5.\n    specialize (IHall_R _ _ H5 H6 H4).\n    Print SearchTree_half_in.\n    pose proof ST_in_cons_R _ _ _ _ _ IHall_R H8.\n    exact H7.\nQed.\n\nLemma R_in_r_bound: \n  forall n l n0 r0 h LO HI hi,\n    R_in ((L, n, l)::h) (R, n0, r0) ->\n    SearchTree_half_out (Some LO) ((L, n, l) :: h) (Some HI) ->\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) hi ->\n    hi = (Some (key_of_node n0)) /\\ optionZ_le hi (Some HI).\nProof.\n  intros.\n  inversion H;subst.\n  clear H.\n  remember (R, n0, r0) as h_t.\n  revert n l H0 H1.\n  induction H3;intros.\n  + inversion H1;subst.\n    inversion H6;subst.\n    injection Heqh_t.\n    intros;subst.\n    inversion H0;subst.\n    inversion H8;subst.\n    apply optionZ_lt_SearchTree, lt_le in H15.\n    split;[reflexivity|exact H15].\n  + inversion H0;subst.\n    inversion H1;subst.\n    inversion H10;subst.\n    specialize (IHR_in Heqh_t _ _ H6 H10).\n    exact IHR_in.\nQed.\n\nLemma L_in_l_bound: \n  forall n r n0 l0 h LO HI lo,\n    L_in ((R, n, r)::h) (L, n0, l0) ->\n    SearchTree_half_out (Some LO) ((R, n, r) :: h) (Some HI) ->\n    SearchTree_half_in lo ((R, n, r) :: h) (Some (key_of_node n)) ->\n    lo = (Some (key_of_node n0)) /\\ optionZ_le (Some LO) lo.\nProof.\n  intros.\n  inversion H;subst.\n  clear H.\n  remember (L, n0, l0) as h_t.\n  revert n r H0 H1.\n  induction H3;intros.\n  + inversion H1;subst.\n    inversion H4;subst.\n    injection Heqh_t.\n    intros;subst.\n    inversion H0;subst.\n    inversion H7;subst.\n    apply optionZ_lt_SearchTree, lt_le in H14.\n    split;[reflexivity|exact H14].\n  + inversion H0;subst.\n    inversion H1;subst.\n    inversion H5;subst.\n    specialize (IHL_in Heqh_t _ _ H6 H5).\n    exact IHL_in.\nQed.\n\nLemma all_L_r_bound:\n  forall lt nt rt LO HI n l h k,\n    all_L ((L, n, l) :: h) ->\n    SearchTree (Some (key_of_node n)) (T lt nt rt) (Some HI) ->\n    SearchTree_half_out (Some LO) ((L, n, l) :: h) (Some HI) ->\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) (Some k) ->\n    exists hi',\n      SearchTree (Some (key_of_node n)) (T lt nt rt) (Some hi') /\\\n      SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) (Some hi') /\\\n      optionZ_le (Some hi') (Some HI).\nProof.\n  intros.\n  pose proof sup_fact lt nt rt. destruct H3 as [sup ?].\n  exists (sup +1).\n  pose proof SearchTree_sup _ _ _ _ H0 H3.\n  split;[exact H4|split].\n  { inversion H4;subst.\n    apply optionZ_lt_SearchTree in H10. apply optionZ_lt_SearchTree in H11.\n    pose proof optionZ_lt_cong _ _ _ H11 H10. apply lt_le in H5.\n    pose proof all_L_r_some_tighter _ _ _ _ _ H H5 H2. exact H6. }\n  pose proof sup_property _ _ _ _ H0 H3.\n  apply lt_le'' in H5. exact H5.\nQed.\n\nLemma all_R_l_bound:\n  forall lt nt rt LO HI n r h k,\n    all_R ((R, n, r) :: h) ->\n    SearchTree (Some LO) (T lt nt rt) (Some (key_of_node n)) ->\n    SearchTree_half_out (Some LO) ((R, n, r) :: h) (Some HI) ->\n    SearchTree_half_in (Some k) ((R, n, r) :: h) (Some (key_of_node n)) ->\n    exists lo',\n      SearchTree (Some lo') (T lt nt rt) (Some (key_of_node n)) /\\\n      SearchTree_half_in (Some lo') ((R, n, r) :: h) (Some (key_of_node n)) /\\\n      optionZ_le (Some LO) (Some lo').\nProof.\n  intros.\n  pose proof inf_fact lt nt rt. destruct H3 as [inf ?].\n  exists (inf - 1).\n  pose proof SearchTree_inf _ _ _ _ H0 H3.\n  split;[exact H4|split].\n  { inversion H4;subst.\n    apply optionZ_lt_SearchTree in H10. apply optionZ_lt_SearchTree in H11.\n    pose proof optionZ_lt_cong _ _ _ H11 H10. apply lt_le in H5.\n    pose proof all_R_l_some_tighter _ _ _ _ _ H H5 H2. exact H6. }\n  pose proof inf_property _ _ _ _ H0 H3.\n  apply lt_le' in H5. exact H5.\nQed.\n\nLemma r_bound_None:\n  forall lt nt rt LO HI n l h,\n    SearchTree (Some (key_of_node n)) (T lt nt rt) (Some HI) ->\n    SearchTree_half_out (Some LO) ((L, n, l) :: h) (Some HI) ->\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) None ->\n    exists hi',\n      SearchTree (Some (key_of_node n)) (T lt nt rt) (Some hi') /\\\n      SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) (Some hi') /\\\n      optionZ_le (Some hi') (Some HI).\nProof.\n  intros.\n  pose proof sup_fact lt nt rt. destruct H2 as [sup ?].\n  exists (sup + 1).\n  pose proof SearchTree_sup _ _ _ _ H H2.\n  split;[exact H3|split].\n  { inversion H3;subst.\n    apply optionZ_lt_SearchTree in H9.\n    apply optionZ_lt_SearchTree in H10.\n    pose proof optionZ_lt_cong _ _ _ H10 H9.\n    apply lt_le in H4. pose proof r_none_tighter _ _ _ _ H4 H1. exact H5. }\n  Check sup_property.\n  pose proof sup_property _ _ _ _ H H2.\n  apply lt_le'' in H4. exact H4.\nQed.\n\nLemma l_bound_None:\n  forall lt nt rt LO HI n r h,\n    SearchTree (Some LO) (T lt nt rt) (Some (key_of_node n)) ->\n    SearchTree_half_out (Some LO) ((R, n, r) :: h) (Some HI) ->\n    SearchTree_half_in None ((R, n, r) :: h) (Some (key_of_node n)) ->\n    exists lo',\n      SearchTree (Some lo') (T lt nt rt) (Some (key_of_node n)) /\\\n      SearchTree_half_in (Some lo') ((R, n, r) :: h) (Some (key_of_node n)) /\\\n      optionZ_le (Some LO) (Some lo').\nProof.\n  intros.\n  pose proof inf_fact lt nt rt. destruct H2 as [inf ?].\n  exists (inf - 1).\n  pose proof SearchTree_inf _ _ _ _ H H2.\n  split;[exact H3|split].\n  { inversion H3;subst.\n    apply optionZ_lt_SearchTree in H9.\n    apply optionZ_lt_SearchTree in H10.\n    pose proof optionZ_lt_cong _ _ _ H10 H9.\n    apply lt_le in H4. pose proof l_none_tighter _ _ _ _ H4 H1. exact H5. }\n  Check inf_property.\n  pose proof inf_property _ _ _ _ H H2.\n  apply lt_le' in H4. exact H4.\nQed. \n\n\nLemma inner_border_tighter_L:\n  forall n l h hi LO HI lt nt rt,\n    SearchTree (Some (key_of_node n)) (T lt nt rt) hi ->\n    SearchTree (Some (key_of_node n)) (T lt nt rt) (Some HI) ->\n    SearchTree_half_out (Some LO) ((L, n, l) :: h) (Some HI) ->\n    SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) hi ->\n    exists hi',\n      SearchTree (Some (key_of_node n)) (T lt nt rt) (Some hi') /\\\n      SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) (Some hi') /\\\n      optionZ_le (Some hi') (Some HI).\nProof.\n  intros.\n  destruct hi.\n  2:{ pose proof r_bound_None _ _ _ _ _ _ _ _ H0 H1 H2. exact H3. }\n  pose proof all_L_or_R_in ((L, n, l)::h).\n  destruct H3;[|destruct H3 as [n0 [r ?]]].\n  2:{ pose proof R_in_r_bound _ _ _ _ _ _ _ _ H3 H1 H2.\n      destruct H4;injection H4;intros;subst.\n      exists (key_of_node n0). tauto. }\n  pose proof all_L_r_bound _ _ _ _ _ _ _ _ _ H3 H0 H1 H2. exact H4.\nQed.\n\nLemma inner_border_tighter_R:\n  forall n r h lo LO HI lt nt rt,\n    SearchTree lo (T lt nt rt) (Some (key_of_node n)) ->\n    SearchTree (Some LO) (T lt nt rt) (Some (key_of_node n)) ->\n    SearchTree_half_out (Some LO) ((R, n, r) :: h) (Some HI) ->\n    SearchTree_half_in lo ((R, n, r) :: h) (Some (key_of_node n)) ->\n    exists lo',\n      SearchTree (Some lo') (T lt nt rt) (Some (key_of_node n)) /\\\n      SearchTree_half_in (Some lo') ((R, n, r) :: h) (Some (key_of_node n)) /\\\n      optionZ_le (Some LO) (Some lo').\nProof.\n  intros.\n  destruct lo.\n  2:{ pose proof l_bound_None _ _ _ _ _ _ _ _ H0 H1 H2. exact H3. }\n  pose proof all_R_or_L_in ((R, n, r)::h).\n  destruct H3;[|destruct H3 as [n0 [l ?]]].\n  2:{ pose proof L_in_l_bound _ _ _ _ _ _ _ _ H3 H1 H2.\n      destruct H4;injection H4;intros;subst.\n      exists (key_of_node n0). tauto. }\n  pose proof all_R_l_bound _ _ _ _ _ _ _ _ _ H3 H0 H1 H2. exact H4.\nQed.\n\nLemma step_preserves: \n  forall h h' t t' lo hi LO HI,\n    optionZ_le (Some LO) (Some lo) ->\n    optionZ_le (Some hi) (Some HI) ->\n    SearchTree_half_in (Some lo) h (Some hi) ->\n    SearchTree_half_out (Some LO) h (Some HI) ->\n    SearchTree (Some lo) t (Some hi) ->\n    splay_step (h,t) (h',t') ->\n    exists lo' hi',\n      (optionZ_le (Some LO) (Some lo')) /\\\n      (optionZ_le (Some hi') (Some HI)) /\\\n      (SearchTree (Some lo') t' (Some hi')) /\\ \n      (SearchTree_half_in (Some lo') h' (Some hi')) /\\ \n      (SearchTree_half_out (Some LO) h' (Some HI)).\nProof.\n  intros.\n  inversion H4;subst.\n  + inversion H1;subst.\n    inversion H8;subst.\n    rename H3 into H_Tn1, H11 into H_c, H13 into H_d.\n    rename H12 into H_h'.\n    inversion H2;subst.\n    inversion H9;subst.\n    exists lo.  \n    inversion H_h';subst.\n    3:{ exists (key_of_node n).\n        inversion H10;subst.\n        apply optionZ_lt_SearchTree , lt_le in H19.\n        split;[exact H|split;[exact H19|split]].\n        { inversion H_Tn1;subst.\n        constructor;try tauto;constructor;try tauto;constructor;try tauto. }\n        split;tauto. }\n    - exists HI.\n      split;[tauto|split;[simpl;lia|]].\n      split;[|split;[|exact H10]].\n      { inversion H_Tn1;subst.\n        constructor;try tauto;constructor;try tauto;constructor;try tauto. }\n      constructor.\n      apply optionZ_lt_SearchTree in H_Tn1.\n      apply optionZ_lt_SearchTree in H11.\n      pose proof optionZ_lt_cong _ _ _ H11 H_Tn1.\n      exact H5.\n    - inversion H_Tn1;subst.\n      assert (SearchTree (Some (key_of_node n)) (T a n1 (T b n2 (T c n3 d))) hi).\n      { constructor;try tauto;constructor;try tauto;constructor;try tauto. }\n      assert (SearchTree (Some (key_of_node n)) (T a n1 (T b n2 (T c n3 d))) (Some HI)).\n      { constructor;try tauto;constructor;try tauto;constructor;try tauto. }\n      pose proof inner_border_tighter_L _ _ _ _ _ _ _ _ _ H3 H7 H10 H_h'.\n      destruct H13 as [hi' ?].\n      exists hi'. tauto. \n  +  inversion H1;subst. inversion H10;subst.\n     inversion H2;subst. inversion H9;subst.\n     inversion H3;subst.\n     inversion H12;subst.\n     2:{ exists (key_of_node n), hi.\n         inversion H14;subst. apply optionZ_lt_SearchTree, lt_le in H25.\n         assert (SearchTree (Some (key_of_node n)) (T (T (T a n1 b) n2 c) n3 d) (Some hi)).\n         { constructor;[constructor;[constructor;tauto|tauto]|tauto]. }\n         tauto. }\n     - exists LO, hi.\n       assert (optionZ_le (Some LO) (Some LO)) by (simpl;lia).\n       assert (SearchTree (Some LO) (T (T (T a n1 b) n2 c) n3 d) (Some hi)).\n         { constructor;[constructor;[constructor;tauto|tauto]|tauto]. }\n       apply optionZ_lt_SearchTree in H21. apply optionZ_lt_SearchTree in H20.\n       apply optionZ_lt_SearchTree in H15.\n       pose proof optionZ_lt_cong _ _ _ H21 H20.\n       pose proof optionZ_lt_cong _ _ _ H8 H15.\n       pose proof ST_in_nil _ _ H17.\n       tauto.\n    - assert (SearchTree lo (T (T (T a n1 b) n2 c) n3 d) (Some (key_of_node n))).\n      { constructor;[constructor;[constructor;tauto|tauto]|tauto]. }\n      assert (SearchTree (Some LO) (T (T (T a n1 b) n2 c) n3 d) (Some (key_of_node n))).\n      { constructor;[constructor;[constructor;tauto|tauto]|tauto]. }\n      pose proof inner_border_tighter_R _ _ _ _ _ _ _ _ _ H5 H7 H14 H12.\n      destruct H8 as [lo' ?].\n      exists lo' ,(key_of_node n). tauto. \n  + inversion H1;subst. inversion H10;subst.\n    inversion H2;subst. inversion H12;subst.\n    inversion H8;subst.\n    - exists LO, HI.\n      inversion H3;subst.\n      assert (optionZ_le (Some LO) (Some LO)) by (simpl;lia).\n      assert (optionZ_le (Some HI) (Some HI)) by (simpl;lia).\n      assert (SearchTree (Some LO) (T (T a n1 b) n2 (T c n3 d)) (Some HI)).\n      { constructor;constructor;tauto. }\n      inversion H14;subst.\n      assert (SearchTree_half_in (Some LO) [] (Some HI)) by (constructor;simpl;exact H17).\n      tauto.\n    - exists (key_of_node n).\n      inversion H14;subst.\n      apply optionZ_lt_SearchTree, lt_le in H23.\n      inversion H3;subst.\n      assert (SearchTree (Some (key_of_node n)) (T (T a n1 b) n2 (T c n3 d)) hi0).\n      { constructor;constructor;tauto. }\n      assert (SearchTree (Some (key_of_node n)) (T (T a n1 b) n2 (T c n3 d)) (Some HI)).\n      { constructor;constructor;tauto. }\n      pose proof inner_border_tighter_L _ _ _ _ _ _ _ _ _ H7 H9 H14 H8.\n      destruct H17 as [hi' ?].\n      exists hi'. tauto.\n    - inversion H14;subst.\n      apply optionZ_lt_SearchTree, lt_le in H23.\n      inversion H3;subst.\n      assert (SearchTree lo0 (T (T a n1 b) n2 (T c n3 d)) (Some (key_of_node n))).\n      { constructor;constructor;tauto. }\n      assert (SearchTree (Some LO) (T (T a n1 b) n2 (T c n3 d)) (Some (key_of_node n))).\n      { constructor;constructor;tauto. }\n      pose proof inner_border_tighter_R _ _ _ _ _ _ _ _ _ H7 H9 H14 H8.\n      destruct H17 as [lo' ?].\n      exists lo', (key_of_node n). tauto.\n  + inversion H1;subst. inversion H8;subst.\n    inversion H2;subst. inversion H10;subst.\n    inversion H12;subst.\n    - exists LO, HI.\n      inversion H3;subst.\n      assert (optionZ_le (Some LO) (Some LO)) by (simpl;lia).\n      assert (optionZ_le (Some HI) (Some HI)) by (simpl;lia).\n      assert (SearchTree (Some LO) (T (T a n1 b) n2 (T c n3 d)) (Some HI)).\n      { constructor;constructor;tauto. }\n      inversion H14;subst.\n      assert (SearchTree_half_in (Some LO) [] (Some HI)) by (constructor;simpl;exact H17).\n      tauto.\n    - exists (key_of_node n).\n      inversion H14;subst.\n      apply optionZ_lt_SearchTree, lt_le in H23.\n      inversion H3;subst.\n      assert (SearchTree (Some (key_of_node n)) (T (T a n1 b) n2 (T c n3 d)) hi0).\n      { constructor;constructor;tauto. }\n      assert (SearchTree (Some (key_of_node n)) (T (T a n1 b) n2 (T c n3 d)) (Some HI)).\n      { constructor;constructor;tauto. }\n      pose proof inner_border_tighter_L _ _ _ _ _ _ _ _ _ H7 H9 H14 H12.\n      destruct H17 as [hi' ?].\n      exists hi'. tauto.\n    - inversion H14;subst.\n      apply optionZ_lt_SearchTree, lt_le in H23.\n      inversion H3;subst.\n      assert (SearchTree lo0 (T (T a n1 b) n2 (T c n3 d)) (Some (key_of_node n))).\n      { constructor;constructor;tauto. }\n      assert (SearchTree (Some LO) (T (T a n1 b) n2 (T c n3 d)) (Some (key_of_node n))).\n      { constructor;constructor;tauto. }\n      pose proof inner_border_tighter_R _ _ _ _ _ _ _ _ _ H7 H9 H14 H12.\n      destruct H17 as [lo' ?].\n      exists lo', (key_of_node n). tauto.\n  +  inversion H1;subst.\n     inversion H2;subst.\n     inversion H3;subst.\n     exists lo, HI.\n     assert (optionZ_le (Some HI) (Some HI)) by (simpl;lia).\n     assert (SearchTree (Some lo) (T x n1 (T y n2 z)) (Some HI)).\n     { constructor;[tauto|constructor;tauto]. }\n     pose proof optionZ_lt_SearchTree _ _ _ H6.\n     assert (SearchTree_half_in (Some lo) [] (Some HI)) by (constructor;exact H7).\n     tauto.\n  +  inversion H1;subst.\n     inversion H2;subst.\n     inversion H3;subst.\n     exists LO, hi.\n     assert (optionZ_le (Some LO) (Some LO)) by (simpl;lia).\n     assert (SearchTree (Some LO) (T (T x n1 y) n2 z) (Some hi)).\n     { constructor;[constructor;tauto|tauto]. }\n     pose proof optionZ_lt_SearchTree _ _ _ H6.\n     assert (SearchTree_half_in (Some LO) [] (Some hi)) by (constructor;exact H7).\n     tauto.\nQed.\n\nLemma preserves_le: \n  forall HI LO hi lo h t t',\n    optionZ_le (Some LO) (Some lo) ->\n    optionZ_le (Some hi) (Some HI) ->\n    SearchTree_half_in (Some lo) h (Some hi) ->\n    SearchTree_half_out (Some LO) h (Some HI) ->\n    SearchTree (Some lo) t (Some hi)->\n    splay h t t' ->\n    SearchTree (Some LO) t' (Some HI).\nProof.\n  intros.\n  apply splay_splay' in H4.\n  revert H H0 H1 H2 H3.\n  revert lo hi LO HI.\n  induction_1n H4; intros.\n  2:{ rename p into h'.\n      pose proof step_preserves _ _ _ _ _ _ _ _ H1 H2 H3 H4 H5 H.\n      clear H1 H2 H3 H4 H5 H.\n      destruct H6 as [lo' [hi' [? [? [? [? ?]]]]]].\n      specialize (IHrt _ _ _ _ H H1 H3 H4 H2).\n      exact IHrt.\n    }\n  inversion H1. inversion H2. subst. clear H1 H2. \n  Check looser_SearchTree.\n  pose proof looser_SearchTree_le _ _ _ _ _ H H0 H3. tauto. \nQed.\n\nTheorem preserve: preserves.\nProof.\n  unfold preserves;intros.\n  apply lt_le in H.\n  apply lt_le in H0.\n  pose proof preserves_le _ _ _ _ _ _ _ H H0 H1 H2 H3 H4.\n  exact H5.\nQed.\n\n\n(* ============================================================*)\n(* ===================== Proof of correct =====================*)\n(* ============================================================*)\n\nLemma map_eq: forall lm rm: relate_map,\n(forall k , lm k = rm k)->\nlm=rm.\nProof.\nintros.\nextensionality k. apply H. \nQed.\n\nLemma combine_com: \n  forall m1 m2,\n    forall k, combine m1 m2 k = combine m2 m1 k.\nProof.\n  intros.\n  unfold combine.\n  destruct (m1 k);destruct (m2 k);reflexivity.\nQed.\n\n\nLemma Abs_in:\nforall t lo hi m,\nAbs t m->\nSearchTree lo t hi->\nforall k, (m k= None/\\ optionZ_lt lo hi) \\/ (exists v, m k =Some v /\\  optionZ_lt lo (Some k) /\\ optionZ_lt (Some k) hi).\nProof.\nintros. revert H k. revert m. induction H0;subst.\nintros.\ninversion H0;subst. left. tauto. \nintros. inversion H;subst. specialize (IHSearchTree1 lm H4 k). specialize (IHSearchTree2 rm H5 k). destruct IHSearchTree1; destruct IHSearchTree2; pose proof combine_com (relate_single (key_of_node n) (value_of_node n)) rm;\npose proof map_eq _ _ H2; rewrite H3; unfold combine .\n+ destruct H0;rewrite H0;destruct H1; rewrite H1;  unfold relate_single. destruct (Z.eq_dec k (key_of_node n)). right.  pose proof optionZ_lt_SearchTree _ _ _ H0_. pose proof optionZ_lt_SearchTree _ _ _ H0_0. pose proof lt_le _ _ H8. pose proof lt_le _ _ H9. rewrite e. exists (value_of_node n).  split;tauto. left. split. tauto. pose proof optionZ_lt_cong _ _ _ H7 H6. tauto.   \n+ destruct H0; rewrite H0. destruct H1 as[v[?[? ?]]]. rewrite H1. assert ((key_of_node n)<> k). simpl in H7. lia.   unfold relate_single. destruct (Z.eq_dec k (key_of_node n)). rewrite e in H9. tauto.  right. exists v. split;[reflexivity| ]. split. pose proof optionZ_lt_SearchTree _ _ _ H0_. pose proof optionZ_lt_cong _ _ _ H7 H10. tauto. tauto.\n+ destruct H0 as[v[?[? ?]]]. destruct H1. rewrite H0. rewrite H1. assert ((key_of_node n)<> k). simpl in H7. lia.   unfold relate_single. destruct (Z.eq_dec k (key_of_node n)). rewrite e in H9. tauto. right. exists v. split;[reflexivity| ]. split. tauto. pose proof optionZ_lt_SearchTree _ _ _ H0_0. pose proof optionZ_lt_cong _ _ _ H10 H7.  tauto.\n+ destruct H0 as[vl[?[? ?]]]. destruct H1 as[vr[?[? ?]]]. simpl in H7. simpl in H8. lia.\n  Qed.\n\nLemma l_none_le:\n  forall n r h m k v,\n  SearchTree_half_in None ((R, n, r) :: h) (Some (key_of_node n)) ->\n  Abs_half ((R, n, r) :: h) m ->\n  m k = Some v ->\n  optionZ_le (Some (key_of_node n)) (Some k).\nProof.\n  intros.\n  pose proof l_none_all_R _ _ _ H.\n  inversion H2;subst. clear H2.\n  revert n r m v H H0 H1.\n  induction H4;subst;intros.\n  + inversion H0;subst.\n    inversion H8;subst. clear H8.\n    inversion H;subst. clear H5.\n    inversion H8;subst.\n    { inversion H7;subst. assert( relate_default k = None ) by (unfold relate_default;reflexivity). assert((relate_single (key_of_node n) (value_of_node n) k) = Some v). { destruct (relate_single (key_of_node n) (value_of_node n) k) eqn:?H. { unfold combine in H1;rewrite H3 in H1;rewrite H4 in H1. exact H1. } unfold combine in H1;rewrite H3 in H1;rewrite H4 in H1. discriminate H1. } unfold relate_single in H4. assert(k=(key_of_node n)).  { destruct(Z.eq_dec k (key_of_node n)). tauto. discriminate H4. } rewrite H5. simpl. simpl. lia. }\n    pose proof Abs_in _ _ _ _ H7 H8. specialize (H4 k).\n    destruct H4.\n    { destruct H4.\n      assert( relate_default k = None ) by (unfold relate_default;reflexivity). assert((relate_single (key_of_node n) (value_of_node n) k) = Some v). { destruct (relate_single (key_of_node n) (value_of_node n) k) eqn:?H. { unfold combine in H1;rewrite H4 in H1;rewrite H9 in H1;rewrite H6 in H1. exact H1. } unfold combine in H1;rewrite H4 in H1;rewrite H9 in H1;rewrite H6 in H1. discriminate H1. } unfold relate_single in H9. assert(k=(key_of_node n)).  { destruct(Z.eq_dec k (key_of_node n)). tauto. discriminate H9. } rewrite H10. simpl. simpl. lia. }\n    destruct H4 as [? [? [? ?]]]. apply lt_le in H5. exact H5.\n  \n  + inversion H;subst. \n    inversion H0;subst.\n    specialize (IHall_R n r m2).\n    pose proof Abs_in _ _ _ _ H10 H8.\n    specialize (H2 k). \n    destruct H2.\n    2:{ destruct H2 as [? [? [? ?]]]. apply lt_le in H3. exact H3. }\n    destruct H2.\n    destruct ((relate_single (key_of_node n0) (value_of_node n0)) k) eqn:?H. \n    { unfold relate_single in H5. assert (k=(key_of_node n0)). { destruct (Z.eq_dec k (key_of_node n0)). tauto. discriminate H5. } rewrite H7. simpl. simpl. lia. }\n    assert (m2 k = Some v). { unfold combine in H1; rewrite H2 in H1; rewrite H5 in H1. destruct (m2 k);[ exact H1| discriminate H1]. }\n    clear H1.\n    inversion H6;subst.\n    specialize (IHall_R v H6 H11 H7).\n    pose proof optionZ_let_cong _ _ _ IHall_R H3.\n    apply lt_le in H1; exact H1.\nQed.\n\nLemma r_none_le:\n  forall n l h m k v,\n  SearchTree_half_in (Some (key_of_node n)) ((L, n, l) :: h) None ->\n  Abs_half ((L, n, l) :: h) m ->\n  m k = Some v ->\n  optionZ_le (Some k) (Some (key_of_node n)).\nProof.\n  intros.\n  pose proof r_none_all_L _ _ _ H.\n  inversion H2;subst. clear H2.\n  revert n l m v H H0 H1.\n  induction H4;subst;intros.\n  + inversion H0;subst.\n    inversion H8;subst. clear H8.\n    inversion H;subst. clear H2. clear H8.\n    inversion H9;subst.\n    { inversion H7;subst. assert( relate_default k = None ) by (unfold relate_default;reflexivity). assert((relate_single (key_of_node n) (value_of_node n) k) = Some v). { destruct (relate_single (key_of_node n) (value_of_node n) k) eqn:?H. { unfold combine in H1;rewrite H3 in H1;rewrite H4 in H1. exact H1. } unfold combine in H1;rewrite H3 in H1;rewrite H4 in H1. discriminate H1. } unfold relate_single in H4. assert(k=(key_of_node n)).  { destruct(Z.eq_dec k (key_of_node n)). tauto. discriminate H4. } rewrite H5. simpl. simpl. lia. }\n    pose proof Abs_in _ _ _ _ H7 H9. specialize (H4 k).\n    destruct H4.\n    { destruct H4.\n      assert( relate_default k = None ) by (unfold relate_default;reflexivity). assert((relate_single (key_of_node n) (value_of_node n) k) = Some v). { destruct (relate_single (key_of_node n) (value_of_node n) k) eqn:?H. { unfold combine in H1;rewrite H4 in H1;rewrite H8 in H1;rewrite H6 in H1. exact H1. } unfold combine in H1;rewrite H4 in H1;rewrite H8 in H1;rewrite H6 in H1. discriminate H1. } unfold relate_single in H8. assert(k=(key_of_node n)).  { destruct(Z.eq_dec k (key_of_node n)). tauto. discriminate H8. } rewrite H10. simpl. simpl. lia. }\n    destruct H4 as [? [? [? ?]]]. apply lt_le in H6. exact H6.\n  \n  + inversion H;subst. clear H2. \n    inversion H0;subst.\n    specialize (IHall_L n l m2).\n    pose proof Abs_in _ _ _ _ H10 H9.\n    specialize (H2 k). \n    destruct H2.\n    2:{ destruct H2 as [? [? [? ?]]]. apply lt_le in H5. exact H5. }\n    destruct H2.\n    destruct ((relate_single (key_of_node n0) (value_of_node n0)) k) eqn:?H. \n    { unfold relate_single in H5. assert (k=(key_of_node n0)). { destruct (Z.eq_dec k (key_of_node n0)). tauto. discriminate H5. } rewrite H6. simpl. simpl. lia. }\n    assert (m2 k = Some v). { unfold combine in H1; rewrite H2 in H1; rewrite H5 in H1. destruct (m2 k);[ exact H1| discriminate H1]. }\n    clear H1.\n    inversion H8;subst.\n    specialize (IHall_L v H8 H11 H6).\n    pose proof optionZ_lte_cong _ _ _ H3 IHall_L.\n    apply lt_le in H1; exact H1.\nQed.\n\nLemma Abs_in_half:\nforall t lo hi m ,\nAbs_half t m->\nSearchTree_half_in (Some lo) t (Some hi)->\n(* SearchTree_half_out LO t HI-> *)\nforall k, m k= None \\/ (exists v, m k =Some v /\\  (optionZ_le (Some k) (Some lo) \\/ optionZ_le (Some hi) (Some k))).\nProof.\n  intros. revert H k. revert m. induction H0;subst;intros. \n  + inversion H0;subst.  left. tauto.\n  + inversion H1;subst.\n    specialize (IHSearchTree_half_in m2 H8 k).\n    destruct IHSearchTree_half_in.\n    { pose proof Abs_in _ _ _ _ H7 H.\n      specialize (H3 k). \n      destruct H3.\n      { destruct H3. destruct ((relate_single (key_of_node n) (value_of_node n)) k) eqn: ?H. \n        { right. exists v. split;[unfold combine;rewrite H2;rewrite H3;rewrite H5;reflexivity|]. unfold relate_single in H5. assert(k=(key_of_node n)). { destruct(Z.eq_dec k (key_of_node n)). tauto. discriminate H5. } rewrite H6 in *. left. simpl. lia. }\n        left. unfold combine;rewrite H2;rewrite H3;rewrite H5;reflexivity. }\n      destruct H3 as [v [? [? ?]]].\n      destruct ((relate_single (key_of_node n) (value_of_node n)) k) eqn: ?H.\n      { left. unfold combine;rewrite H2;rewrite H3;rewrite H6;reflexivity. }\n      right. exists v. split;[unfold combine; rewrite H2;rewrite H3;rewrite H6;reflexivity|]. left. apply lt_le in H5;exact H5. }\n    destruct H2 as [v [? ?]].\n    destruct (m1 k) eqn: ?H;destruct ((relate_single (key_of_node n) (value_of_node n)) k) eqn: ?H.\n    { left. assert(k=(key_of_node n)). {unfold relate_single in H5 . destruct(Z.eq_dec k (key_of_node n)). tauto. discriminate H5. } rewrite H6 in *. pose proof Abs_in _ _ _ _ H7 H. specialize (H9 (key_of_node n)). destruct H9. { destruct H9. rewrite H4 in H9. discriminate H9. } destruct H9 as [? [? [? ?]]]. simpl in H11. lia. }\n    { left. unfold combine; rewrite H2;rewrite H4;rewrite H5;reflexivity. }\n    { left. unfold combine; rewrite H2;rewrite H4;rewrite H5;reflexivity. }\n    { right. exists v. split;[unfold combine; rewrite H2;rewrite H4;rewrite H5;reflexivity|]. \n      destruct H3;[|right;exact H3].\n      destruct lo0 ;[rename k0 into lo0|].\n      { left. apply optionZ_lt_SearchTree in H. pose proof optionZ_lte_cong _ _ _ H H3. apply lt_le in H6;exact H6. }\n      inversion H0;subst.\n      { inversion H8. rewrite <- H10 in H2. unfold relate_default in H2. discriminate H2. }\n      pose proof l_none_le _ _ _ _ _ _ H0 H8 H2.\n      right. exact H10. }\n  + inversion H1;subst.\n    specialize (IHSearchTree_half_in m2 H8 k).\n    destruct IHSearchTree_half_in.\n    { pose proof Abs_in _ _ _ _ H7 H.\n      specialize (H3 k). \n      destruct H3.\n      { destruct H3. destruct ((relate_single (key_of_node n) (value_of_node n)) k) eqn: ?H. \n        { right. exists v. split;[unfold combine;rewrite H2;rewrite H3;rewrite H5;reflexivity|]. unfold relate_single in H5. assert(k=(key_of_node n)). { destruct(Z.eq_dec k (key_of_node n)). tauto. discriminate H5. } rewrite H6 in *. right. simpl. lia. }\n        left. unfold combine;rewrite H2;rewrite H3;rewrite H5;reflexivity. }\n      destruct H3 as [v [? [? ?]]].\n      destruct ((relate_single (key_of_node n) (value_of_node n)) k) eqn: ?H.\n      { left. unfold combine;rewrite H2;rewrite H3;rewrite H6;reflexivity. }\n      right. exists v. split;[unfold combine; rewrite H2;rewrite H3;rewrite H6;reflexivity|]. right. apply lt_le in H4;exact H4. }\n    destruct H2 as [v [? ?]].\n    destruct (m1 k) eqn: ?H;destruct ((relate_single (key_of_node n) (value_of_node n)) k) eqn: ?H.\n    { left. assert(k=(key_of_node n)). {unfold relate_single in H5 . destruct(Z.eq_dec k (key_of_node n)). tauto. discriminate H5. } rewrite H6 in *. pose proof Abs_in _ _ _ _ H7 H. specialize (H9 (key_of_node n)). destruct H9. { destruct H9. rewrite H4 in H9. discriminate H9. } destruct H9 as [? [? [? ?]]]. simpl in H10. lia. }\n    { left. unfold combine; rewrite H2;rewrite H4;rewrite H5;reflexivity. }\n    { left. unfold combine; rewrite H2;rewrite H4;rewrite H5;reflexivity. }\n    { right. exists v. split;[unfold combine; rewrite H2;rewrite H4;rewrite H5;reflexivity|]. \n      destruct H3;[left;exact H3|].\n      destruct hi0 ;[rename k0 into hi0|].\n      { right. apply optionZ_lt_SearchTree in H. pose proof optionZ_let_cong _ _ _ H3 H. apply lt_le in H6;exact H6. }\n      inversion H0;subst.\n      { inversion H8. rewrite <- H10 in H2. unfold relate_default in H2. discriminate H2. }\n      pose proof r_none_le _ _ _ _ _ _ H0 H8 H2.\n      left. exact H10. }\nQed.\n\nLemma step_correct_le: \n  forall h t h' t' m1 m2 lo hi LO HI,\n    splay_step (h,t) (h',t') ->\n    Abs_half h m1 ->\n    Abs t m2 ->\n    SearchTree (Some lo) t (Some hi)->\n    (SearchTree_half_in (Some lo) h (Some hi))->\n    (SearchTree_half_out (Some LO) h (Some HI))->\n    optionZ_le (Some LO) (Some lo)->\n    optionZ_le (Some hi) (Some HI)->\n    (exists  lo' hi' LO' HI' m1' m2',\n      (SearchTree (Some lo') t' (Some hi') )/\\\n      (SearchTree_half_in (Some lo') h' (Some hi')) /\\ (SearchTree_half_out (Some LO') h' (Some HI')) /\\  optionZ_le (Some LO') (Some lo') /\\\n    optionZ_le (Some hi') (Some HI') /\\ (Abs_half h' m1') /\\ (Abs t' m2') /\\ \n      (forall k, combine m1' m2' k = combine m1 m2 k)).\nProof.\n  intros.\n  pose proof step_preserves _ _ _ _ _ _ _ _ H5 H6 H3 H4 H2 H.\n  destruct H7 as [lo' [hi' [? [? [? [? ?]]]]]].\n  exists lo',hi', LO ,HI. \n  inversion H;subst.\n  + inversion H0;subst. inversion H1;subst. inversion H18;subst. exists m2.  exists (combine lm (combine (relate_single (key_of_node n1) (value_of_node n1)) \n     (combine rm (combine (relate_single (key_of_node n2) (value_of_node n2)) \n     (combine m0 (combine (relate_single (key_of_node n3) (value_of_node n3))\n      m1)))))). split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split. constructor;try tauto. constructor;try tauto.  constructor;try tauto. intros.  clear H7 H8 H11 H5 H6 H3 H4 H H0 H18 H1. inversion H9;subst;clear H9. inversion H6;subst;clear H6. inversion H8;subst;clear H8. pose proof Abs_in _ _ _ _ H16 H5 k; pose proof optionZ_lt_SearchTree _ _ _ H5; clear H16 H5. pose proof Abs_in _ _ _ _ H19 H7 k; pose proof optionZ_lt_SearchTree _ _ _ H7; clear H19 H7. pose proof Abs_in _ _ _ _ H17 H6 k; pose proof optionZ_lt_SearchTree _ _ _ H6; clear H17 H6. clear H2. pose proof Abs_in _ _ _ _ H21 H9 k. clear H21 H9.\npose proof Abs_in_half _ _ _ _ H22 H10 k; clear H22 H10. destruct H. \n2:{ destruct H1.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H1 as [v1[?[? ? ]]]. simpl in H9. simpl in H8. \nlia. }\n    destruct H4.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H2.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H6; destruct H1;destruct H4;destruct H2.  \n    2:{ destruct H as [v[?[? ? ]]]. destruct H6 as [v1[? ?]]. simpl in *. lia. }\n    destruct H as[v[?[? ?]]]. unfold combine.  rewrite H1, H4,H2,H6,H. clear H1 H2 H4 H6 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n          destruct H. clear H7. \n      destruct H1.\n  2:{ destruct H1 as [v[?[? ? ]]]. destruct H4.\n    2:{ destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H2.\n    2:{destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H6.\n    2:{ destruct H6 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H4;destruct H2. unfold combine. rewrite H1, H4,H2,H6,H. clear H1 H2 H4 H6 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H1. \n      destruct H4.\n    2:{ destruct H4 as [v[?[? ? ]]].  destruct H2.\n    2:{destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H6.\n    2:{ destruct H6 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H2. unfold combine. rewrite H1,H2,H6, H4,H. clear H1 H2 H6 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H2.   \n      2:{destruct H2 as [v[?[? ?] ]]. destruct H6.\n    2:{ destruct H6 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H4. unfold combine. rewrite H1,H2,H6, H4,H. clear H1 H2 H6 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H6;destruct H4;destruct H2.\n      1:{unfold combine. rewrite H1,H2,H6, H4,H. clear H1 H2 H6 H4 H. simpl in *. unfold relate_single. destruct (Z.eq_dec k (key_of_node n1)).\n      1:{ destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto. }\n    destruct (Z.eq_dec k (key_of_node n2)). 1:{ destruct (Z.eq_dec k (key_of_node n3));try lia. tauto. } destruct (Z.eq_dec k (key_of_node n3));try tauto. }\n    destruct H6 as [v[? ?]]. destruct H10;simpl in *;\n   unfold combine; rewrite H1,H2,H6, H4,H; clear H1 H2 H6 H4 H; simpl in *; unfold relate_single;  destruct (Z.eq_dec k (key_of_node n1));try lia; destruct (Z.eq_dec k (key_of_node n2));try lia; destruct (Z.eq_dec k (key_of_node n3));try lia; tauto. \n + inversion H0;subst. inversion H1;subst. inversion H18;subst. exists m2.  exists (combine(combine(combine m1(combine (relate_single(key_of_node n1)(value_of_node n1)) m0))(combine(relate_single(key_of_node n2)(value_of_node n2)) lm)) (combine (relate_single(key_of_node n3)(value_of_node n3)) rm)).  split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split. constructor;try tauto. constructor;try tauto.  constructor;try tauto. intros.  clear H7 H8 H11 H5 H6 H3 H4 H H0 H18 H1. inversion H9;subst;clear H9. inversion H5;subst;clear H5. inversion H7;subst;clear H7. pose proof Abs_in _ _ _ _ H21 H5 k; pose proof optionZ_lt_SearchTree _ _ _ H5; clear H21 H5.  pose proof Abs_in _ _ _ _ H17 H9 k; pose proof optionZ_lt_SearchTree _ _ _ H9; clear H17 H9. pose proof Abs_in _ _ _ _ H16 H8 k; pose proof optionZ_lt_SearchTree _ _ _ H8; clear H16 H8. clear H2. pose proof Abs_in _ _ _ _ H19 H6 k; clear H19 H6.\npose proof Abs_in_half _ _ _ _ H22 H10 k; clear H22 H10.  destruct H. \n2:{ destruct H1. \n    2:{ destruct H as [v[?[? ? ]]]. destruct H1 as [v1[?[? ? ]]]. simpl in H9. simpl in H8. \nlia. }\n    destruct H4.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H2.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H6; destruct H1;destruct H4;destruct H2.  \n    2:{ destruct H as [v[?[? ? ]]]. destruct H6 as [v1[? ?]]. simpl in *. lia. }\n    destruct H as[v[?[? ?]]]. unfold combine.  rewrite H1, H4,H2,H6,H. clear H1 H2 H4 H6 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n          destruct H. clear H7. \n      destruct H1.\n  2:{ destruct H1 as [v[?[? ? ]]]. destruct H4.\n    2:{ destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H2.\n    2:{destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H6.\n    2:{ destruct H6 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H4;destruct H2. unfold combine. rewrite H1, H4,H2,H6,H. clear H1 H2 H4 H6 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H1. \n      destruct H4.\n    2:{ destruct H4 as [v[?[? ? ]]].  destruct H2.\n    2:{destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H6.\n    2:{ destruct H6 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H2. unfold combine. rewrite H1,H2,H6, H4,H. clear H1 H2 H6 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H2.  \n      2:{destruct H2 as [v[?[? ?] ]]. destruct H6.\n    2:{ destruct H6 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H4. unfold combine. rewrite H1,H2,H6, H4,H. clear H1 H2 H6 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H6;destruct H4;destruct H2.\n      1:{unfold combine. rewrite H1,H2,H6, H4,H. clear H1 H2 H6 H4 H. simpl in *. unfold relate_single. destruct (Z.eq_dec k (key_of_node n1)).\n      1:{ destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto. }\n    destruct (Z.eq_dec k (key_of_node n2)). 1:{ destruct (Z.eq_dec k (key_of_node n3));try lia. tauto. } destruct (Z.eq_dec k (key_of_node n3));try tauto. }\n    destruct H6 as [v[? ?]]. destruct H10;simpl in *;\n   unfold combine; rewrite H1,H2,H6, H4,H; clear H1 H2 H6 H4 H; simpl in *; unfold relate_single;  destruct (Z.eq_dec k (key_of_node n1));try lia; destruct (Z.eq_dec k (key_of_node n2));try lia; destruct (Z.eq_dec k (key_of_node n3));try lia; tauto. \n+  inversion H0;subst. inversion H1;subst. inversion H18;subst. exists m2.  exists (combine(combine m0 (combine (relate_single(key_of_node n1)(value_of_node n1)) lm))(combine(relate_single(key_of_node n2)(value_of_node n2))(combine rm (combine(relate_single(key_of_node n3)(value_of_node n3)) m1)))). split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split. constructor;try tauto. constructor;try tauto.  constructor;try tauto. intros.  clear H7 H8 H11 H5 H6 H3 H4 H H0 H18 H1. inversion H9;subst;clear H9. inversion H5;subst;clear H5. inversion H6;subst;clear H6. pose proof Abs_in _ _ _ _ H21 H9 k; pose proof optionZ_lt_SearchTree _ _ _ H9; clear H21 H9.  pose proof Abs_in _ _ _ _ H17 H7 k; pose proof optionZ_lt_SearchTree _ _ _ H7; clear H17 H7. pose proof Abs_in _ _ _ _ H16 H8 k; pose proof optionZ_lt_SearchTree _ _ _ H8; clear H16 H8. clear H2. pose proof Abs_in _ _ _ _ H19 H5 k; pose proof optionZ_lt_SearchTree _ _ _ H5; clear H19 H5.\npose proof Abs_in_half _ _ _ _ H22 H10 k; clear H22 H10.  destruct H. \n2:{ destruct H1. \n    2:{ destruct H as [v[?[? ? ]]]. destruct H1 as [v1[?[? ? ]]]. simpl in *. lia. }\n    destruct H4.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H2.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H5; destruct H1;destruct H4;destruct H2.  \n    2:{ destruct H as [v[?[? ? ]]]. destruct H5 as [v1[? ?]]. simpl in *. lia. }\n    destruct H as[v[?[? ?]]]. unfold combine.  rewrite H1, H4,H2,H5,H. clear H1 H2 H4 H5 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n          destruct H. clear H8. \n      destruct H1.\n  2:{ destruct H1 as [v[?[? ? ]]]. destruct H4.\n    2:{ destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H2.\n    2:{destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H5.\n    2:{ destruct H5 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H4;destruct H2. unfold combine. rewrite H1, H4,H2,H5,H. clear H1 H2 H4 H5 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H1. \n      destruct H4.\n    2:{ destruct H4 as [v[?[? ? ]]].  destruct H2.\n    2:{destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H5.\n    2:{ destruct H5 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H2. unfold combine. rewrite H1,H2,H5, H4,H. clear H1 H2 H5 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H2.  \n      2:{destruct H2 as [v[?[? ?] ]]. destruct H5.\n    2:{ destruct H5 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H4. unfold combine. rewrite H1,H2,H5, H4,H. clear H1 H2 H5 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H5;destruct H4;destruct H2.\n      1:{unfold combine. rewrite H1,H2,H5, H4,H. clear H1 H2 H5 H4 H. simpl in *. unfold relate_single. destruct (Z.eq_dec k (key_of_node n1)).\n      1:{ destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto. }\n    destruct (Z.eq_dec k (key_of_node n2)). 1:{ destruct (Z.eq_dec k (key_of_node n3));try lia. tauto. } destruct (Z.eq_dec k (key_of_node n3));try tauto. }\n    destruct H5 as [v[? ?]]. destruct H10;simpl in *;\n   unfold combine; rewrite H1,H2,H5, H4,H; clear H1 H2 H5 H4 H; simpl in *; unfold relate_single;  destruct (Z.eq_dec k (key_of_node n1));try lia; destruct (Z.eq_dec k (key_of_node n2));try lia; destruct (Z.eq_dec k (key_of_node n3));try lia; tauto. \n+ inversion H0;subst. inversion H1;subst. inversion H18;subst. exists m2.  exists (combine (combine m1 (combine(relate_single(key_of_node n1)(value_of_node n1)) lm))(combine (relate_single(key_of_node n2)(value_of_node n2))(combine rm (combine(relate_single(key_of_node n3)(value_of_node n3)) m0)))). split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split. constructor;try tauto. constructor;try tauto.  constructor;try tauto. intros.  clear H7 H8 H11 H5 H6 H3 H4 H H0 H18 H1. inversion H9;subst;clear H9. inversion H5;subst;clear H5. inversion H6;subst;clear H6. pose proof Abs_in _ _ _ _ H17 H9 k; pose proof optionZ_lt_SearchTree _ _ _ H9; clear H17 H9.  pose proof Abs_in _ _ _ _ H21 H7 k; pose proof optionZ_lt_SearchTree _ _ _ H7; clear H21 H7. pose proof Abs_in _ _ _ _ H16 H8 k; pose proof optionZ_lt_SearchTree _ _ _ H8; clear H16 H8. clear H2. pose proof Abs_in _ _ _ _ H19 H5 k; pose proof optionZ_lt_SearchTree _ _ _ H5; clear H19 H5.\npose proof Abs_in_half _ _ _ _ H22 H10 k; clear H22 H10.  destruct H. \n2:{ destruct H1. \n    2:{ destruct H as [v[?[? ? ]]]. destruct H1 as [v1[?[? ? ]]]. simpl in *. lia. }\n    destruct H4.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H2.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H5; destruct H1;destruct H4;destruct H2.  \n    2:{ destruct H as [v[?[? ? ]]]. destruct H5 as [v1[? ?]]. simpl in *. lia. }\n    destruct H as[v[?[? ?]]]. unfold combine.  rewrite H1, H4,H2,H5,H. clear H1 H2 H4 H5 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n          destruct H. clear H8. \n      destruct H1.\n  2:{ destruct H1 as [v[?[? ? ]]]. destruct H4.\n    2:{ destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H2.\n    2:{destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H5.\n    2:{ destruct H5 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H4;destruct H2. unfold combine. rewrite H1, H4,H2,H5,H. clear H1 H2 H4 H5 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H1. \n      destruct H4.\n    2:{ destruct H4 as [v[?[? ? ]]].  destruct H2.\n    2:{destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H5.\n    2:{ destruct H5 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H2. unfold combine. rewrite H1,H2,H5, H4,H. clear H1 H2 H5 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H2.  \n      2:{destruct H2 as [v[?[? ?] ]]. destruct H5.\n    2:{ destruct H5 as [v1[? ? ]]. simpl in *. lia. }\n      destruct H4. unfold combine. rewrite H1,H2,H5, H4,H. clear H1 H2 H5 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto.  }\n      destruct H5;destruct H4;destruct H2.\n      1:{unfold combine. rewrite H1,H2,H5, H4,H. clear H1 H2 H5 H4 H. simpl in *. unfold relate_single. destruct (Z.eq_dec k (key_of_node n1)).\n      1:{ destruct (Z.eq_dec k (key_of_node n2));try lia. destruct (Z.eq_dec k (key_of_node n3));try lia. tauto. }\n    destruct (Z.eq_dec k (key_of_node n2)). 1:{ destruct (Z.eq_dec k (key_of_node n3));try lia. tauto. } destruct (Z.eq_dec k (key_of_node n3));try tauto. }\n    destruct H5 as [v[? ?]]. destruct H10;simpl in *;\n   unfold combine; rewrite H1,H2,H5, H4,H; clear H1 H2 H5 H4 H; simpl in *; unfold relate_single;  destruct (Z.eq_dec k (key_of_node n1));try lia; destruct (Z.eq_dec k (key_of_node n2));try lia; destruct (Z.eq_dec k (key_of_node n3));try lia; tauto. \n+ inversion H1;subst;clear H1. inversion H0;subst;clear H0. inversion H19;subst;clear H19. exists relate_default. exists (combine lm (combine (relate_single (key_of_node n1)(value_of_node n1)) (combine rm (combine (relate_single(key_of_node n2)(value_of_node n2)) m0)))).  split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. constructor. split. constructor;try tauto. constructor;try tauto. inversion H9;subst;clear H9. inversion H19;subst;clear H19. intros. clear H H4 H3 H5 H6 H7 H8 H11 H10. pose proof Abs_in _ _ _ _ H16 H15 k; pose proof optionZ_lt_SearchTree _ _ _ H15; clear H16 H15.  pose proof Abs_in _ _ _ _ H17 H14 k; pose proof optionZ_lt_SearchTree _ _ _ H14; clear H17 H14. pose proof Abs_in _ _ _ _ H18 H20 k; pose proof optionZ_lt_SearchTree _ _ _ H20; clear H18 H20. clear H2. destruct H. \n2:{ destruct H1. \n    2:{ destruct H as [v[?[? ? ]]]. destruct H1 as [v1[?[? ? ]]]. simpl in *. lia. }\n    destruct H4.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H as[v[?[? ?]]]. unfold combine. destruct H1;destruct H2;clear H8.  rewrite H1, H2,H. clear H1 H2 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia.  tauto.  }\n          destruct H. clear H2. \n      destruct H1.\n  2:{ destruct H1 as [v[?[? ? ]]]. destruct H4.\n    2:{ destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }     \n      destruct H4. unfold combine. clear H7. rewrite H1, H4,H. clear H1 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. tauto.  }\n      destruct H1. \n      destruct H4.\n    2:{ destruct H4 as [v[?[? ? ]]]. unfold combine,relate_single.  rewrite H1,H4,H. clear H1 H4 H.  simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia.  tauto.  }\n      destruct H4. unfold combine. clear H6. rewrite H1, H4,H. clear H1 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1)). \n      1:{  destruct (Z.eq_dec k (key_of_node n2));try lia. tauto.  }\n      destruct (Z.eq_dec k (key_of_node n2));try tauto. \n+ inversion H1;subst;clear H1. inversion H0;subst;clear H0. inversion H19;subst;clear H19. exists relate_default. exists (combine (combine m0 (combine (relate_single(key_of_node n1)(value_of_node n1)) lm))(combine(relate_single (key_of_node n2)(value_of_node n2)) rm)).  split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. split ;try tauto. constructor. split. constructor;try tauto. constructor;try tauto. inversion H9;subst;clear H9. inversion H15;subst;clear H15. intros. clear H H4 H3 H5 H6 H7 H8 H11 H10. pose proof Abs_in _ _ _ _ H16 H20 k; pose proof optionZ_lt_SearchTree _ _ _ H20; clear H16 H20.  pose proof Abs_in _ _ _ _ H17 H19 k; pose proof optionZ_lt_SearchTree _ _ _ H19; clear H17 H19. pose proof Abs_in _ _ _ _ H18 H14 k; pose proof optionZ_lt_SearchTree _ _ _ H14; clear H18 H14. clear H2. destruct H. \n2:{ destruct H1. \n    2:{ destruct H as [v[?[? ? ]]]. destruct H1 as [v1[?[? ? ]]]. simpl in *. lia. }\n    destruct H4.\n    2:{ destruct H as [v[?[? ? ]]]. destruct H2 as [v1[?[? ? ]]]. simpl in *.  lia. }\n    destruct H as[v[?[? ?]]]. unfold combine. destruct H1;destruct H2;clear H8.  rewrite H1, H2,H. clear H1 H2 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia.  tauto.  }\n          destruct H. clear H2. \n      destruct H1.\n  2:{ destruct H1 as [v[?[? ? ]]]. destruct H4.\n    2:{ destruct H4 as [v1[?[? ? ]]]. simpl in *.  lia. }     \n      destruct H4. unfold combine. clear H7. rewrite H1, H4,H. clear H1 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia. tauto.  }\n      destruct H1. \n      destruct H4.\n    2:{ destruct H4 as [v[?[? ? ]]]. unfold combine,relate_single.  rewrite H1,H4,H. clear H1 H4 H.  simpl in *. destruct (Z.eq_dec k (key_of_node n1));try lia. destruct (Z.eq_dec k (key_of_node n2));try lia.  tauto.  }\n      destruct H4. unfold combine. clear H6. rewrite H1, H4,H. clear H1 H4 H. unfold relate_single. simpl in *. destruct (Z.eq_dec k (key_of_node n1)). \n      1:{  destruct (Z.eq_dec k (key_of_node n2));try lia. tauto.  }\n      destruct (Z.eq_dec k (key_of_node n2));try tauto. \n      Qed.\n\n \nLemma combine_default:\n  forall m ,\n  forall k, m k= combine relate_default m k.\nProof.\nintros. unfold combine, relate_default. induction m;tauto. \nQed.\n\nLemma correct_le:\n   forall h t t' m1 m2 lo hi LO HI,\n    Abs_half h m1 ->\n    Abs t m2 ->\n    splay h t t' ->\n    SearchTree (Some lo) t (Some hi)->(* new *)\n    SearchTree_half_in (Some lo) h (Some hi)->(* new *)\n    SearchTree_half_out (Some LO) h (Some HI)->(* new *)\n    optionZ_le (Some LO) (Some lo) ->\n    optionZ_le (Some hi) (Some HI) ->\n    Abs t' (combine m1 m2).\nProof.\n  intros.\n  apply splay_splay' in H1.\n  revert H H0 H2 H3 H4 H5 H6 .\n  revert m1 m2 lo hi LO HI.\n  induction_1n H1;intros.\n  + inversion H;subst.\n    pose proof combine_default m2 . pose proof map_eq _ _ H1. rewrite <-H7. tauto.\n  + \n  pose proof step_correct_le _ _ _ _ _ _ _ _ _ _ H H1 H2 H3 H4 H5 H6 H7.\n  destruct H8 as [lo' [hi'[LO'[HI'[m1'[m2'[?[?[?[?[?[?[? ?]]]]]]]]]]]]].\n  specialize (IHrt _ _ _ _ _ _  H13 H14 H8 H9 H10 H11 H12). pose proof map_eq _ _ H15. rewrite<- H16 . tauto.\n   Qed.\n   \nTheorem correctness: correct.\nProof.\nunfold correct;intros.\npose proof lt_le _ _ H6. pose proof lt_le _ _ H5.\npose proof correct_le _ _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H8 H7. tauto. \nQed.\n\n(* Long may the sun shine! *)\n(* 2021-06-08 22:13 *)\n", "meta": {"author": "Youmu-Niwashi", "repo": "splay-correct", "sha": "54355d28b3c7d11e46045f61e8e825597c4027fc", "save_path": "github-repos/coq/Youmu-Niwashi-splay-correct", "path": "github-repos/coq/Youmu-Niwashi-splay-correct/splay-correct-54355d28b3c7d11e46045f61e8e825597c4027fc/F0504_Splay.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7350986976842785}}
{"text": "Require Export Arith.\nRequire Export XR_S_INR.\nRequire Export XR_Rlt_trans.\nRequire Export XR_Rlt_plus_1.\n\nLocal Open Scope R_scope.\n\nLemma lt_0_INR : forall n:nat,\n  (0 < n)%nat ->\n  R0 < INR n.\nProof.\n  intros n hn.\n  induction n as [ | n hin ].\n  { inversion hn. }\n  {\n    unfold lt in hn.\n    inversion hn as [ eq | n' hn' ].\n    {\n      subst n.\n      simpl.\n      exact Rlt_0_1.\n    }\n    {\n      subst n'.\n      rewrite S_INR.\n      apply Rlt_trans with (INR n).\n      {\n        apply hin.\n        apply lt_le_trans with 1%nat.\n        {\n          unfold lt.\n          apply le_n.\n        }\n        { exact hn'. }\n      }\n      { apply Rlt_plus_1. }\n    }\n  }\nQed.\n\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_lt_0_INR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8175744673038221, "lm_q1q2_score": 0.7350986766429262}}
{"text": "\n\nModule boolean.\nInductive bool: Type :=\n  |true\n  |false.\n  \n(*punto 1*)\nDefinition bnand (b1:bool)(b2:bool) : bool :=\n  match b1,b2 with\n  | true, true => false\n  | _, _ => true\n  end.\n\n\n(*Ejemplos (00, 01, 10, 11)*)\n\n(*00*)\nExample testbnand00: (bnand false false) = true.\nProof. simpl. reflexivity. Qed.\n\n(*01*)\nExample testbnand01: (bnand false true) = true.\nProof. simpl. reflexivity. Qed.\n\n(*10*)\nExample testbnand10: (bnand true false) = true.\nProof. simpl. reflexivity. Qed.\n\n(*11*)\nExample testbnand11: (bnand true true) = false.\nProof. simpl. reflexivity. Qed.\n\n\n(*punto 2*)\n\n(*negacion*)\nDefinition neg (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\n(*conjuncion*)\nDefinition and (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\n\n(*neg y and*)\nDefinition Bnand (b1:bool)(b2:bool) : bool :=\n  match (and b1 b2) with\n  | true => false\n  | false => true\n  end.\n\n\nCompute bnand true true.\nCompute Bnand true true.\n\nExample testBnand01: (Bnand true true) = false.\nProof. simpl. reflexivity. Qed.\nEnd boolean.\n\n(*punto3*)\nModule Direct.\nInductive direccion : Type :=\n  |O.\n\n(*punto 4*)\nModule Natural.\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\nDefinition pred(n :nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\n  \nEnd Natural.\n\n\n\n\n(*Punto 5*)\n\nDefinition subtwo (n: nat) : nat := \n  match n with\n  |0 => 0\n  |1 => 0\n  |_ => (pred(n)-1)\n  end.\n\nCompute subtwo 0.\n\n(* Definir una funci´on que reciba dos funciones y retorne la composici´on de\nambas. (Tener en cuenta que el valor de retorno es una funci´on)*)\n\n(*punto 6*)\nDefinition returnDosFunciones (f: nat -> nat ) ( g: nat -> nat ) : nat -> nat  :=\nfun(x: nat) => f(g(x)).\n\n(*punto 7*)\nDefinition suma (a:nat)(b:nat) : nat := (a+b).\n\n(*punto 8*)\nDefinition sumprod (a:nat)(b:nat) : (nat*nat) := ((a+b),(a*b)).\nCompute sumprod 5 2.\n\nCompute Nat.leb (100)(1).\n\n\n(*punto 9*)\nDefinition pares (g: nat->nat)(f:(nat->nat)->nat)(a: nat)(b:nat) : (g(b)*f(b*a)) :=\n\n(*punto10*)\nDefinition par (n: nat): bool :=\n  match n with\n    |1 => true\n    |_ => 1*+par(n-2) \n  end.\n\n\n \n \n (*punto12 *)\nDefinition parejafunc (a: nat)( b: nat)(f: nat -> nat): nat->nat := \n  if (Nat.leb a b) then fun (x: nat) => f(a-b) \n  else fun (x: nat) => f(b+1).\n  \n  \n \n", "meta": {"author": "Epshilon", "repo": "Computer-Science-Logic", "sha": "033b98a86912bdbc32806295a5aea087730d2f0c", "save_path": "github-repos/coq/Epshilon-Computer-Science-Logic", "path": "github-repos/coq/Epshilon-Computer-Science-Logic/Computer-Science-Logic-033b98a86912bdbc32806295a5aea087730d2f0c/Taller_1_Portilla_Montaña_Edgar_Esteban.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.735087935094321}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) : natural :=\n  mult lf2 (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj52_coqofml_gPXfvT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7350879293394517}}
{"text": "(************************************************************************)\n(* Copyright (c) 2010, Martijn Vermaat <martijn@vermaat.name>           *)\n(*                                                                      *)\n(* Licensed under the MIT license, see the LICENSE file or              *)\n(* http://en.wikipedia.org/wiki/Mit_license                             *)\n(************************************************************************)\n\n\n(** This library proofs that uniqueness of normal forms (UN) is not implied\n   by weak orthogonality (WO) by counterexample. *)\n\n\nRequire Import Rewriting.\nRequire Import Equality.\n\nSet Implicit Arguments.\n\n\n(** We construct the weakly orthogonal TRS with rules\n    - PS : P(S(x)) -> x\n    - SP : S(P(x)) -> x\n    and show it is a counterexample to UN-inf.\n\n\n    J. Endrullis, C. Grabmayer, D. Hendriks, J.W. Klop and V. van Oostrom.\n    Unique Normal Forms in Infinitary Weakly Orthogonal Rewriting.\n    Rewriting Techniques and Applications, 2010.\n\n    Because we have [S] as constructor for [nat], we rename the function\n    symbols to D and U ('up' and 'down').\n\n    Let psi = U D D U U U D D D D... We show that\n    - this TRS is weakly orthogonal\n    - psi rewrites to DDD...\n    - psi rewrites to UUU...\n    - DDD... is a normal form\n    - UUU... is a normal form\n    - DDD... and UUU... are not bisimilar\n\n    Together this gives a counterexample to (WO => UN). *)\n\n\n(** * Signature\n\n   We have two unary function symbols [D] and [U]. *)\n\nInductive symbol : Set := D | U.\n\nDefinition beq_symb (f g : symbol) : bool :=\n  match f, g with\n  | D, D => true\n  | U, U => true\n  | _, _ => false\nend.\n\nLemma beq_symb_ok : forall f g, beq_symb f g = true <-> f = g.\nProof.\n(* This should work for any finite inductive symbol type *)\nintros f g.\nsplit; intro H.\n(* beq_symb f g = true -> f = g *)\n  destruct f; destruct g; simpl; (reflexivity || discriminate).\n(* f = g ->  beq_symb f g = true *)\n  subst g; destruct f; simpl; reflexivity.\nQed.\n\nDefinition arity (f : symbol) : nat :=\n  match f with\n  | D => 1\n  | U => 1\n  end.\n\n(** * Variables\n\n   We only need one variable that is used in both rewrite rules. *)\n\nDefinition variable : Set := unit.\n\nFixpoint beq_var (x y : variable) : bool := true.\n\nLemma beq_var_ok : forall x y, beq_var x y = true <-> x = y.\nProof.\nintros [] []; split; reflexivity.\nQed.\n\n(** * Terms\n\n   Terms over the given signature and variable. *)\n\nDefinition F : signature := Signature arity beq_symb_ok.\nDefinition X : variables := Variables beq_var_ok.\n\nNotation term := (term F X).\nNotation fterm := (finite_term F X).\nNotation terms := (vector term).\n\n(** We define notational shortcuts for constructing terms:\n   - variable [x] by [x!]\n   - function application of [f] to [a] by [f @ a]\n   - function application of [f] to [a] by [f @@ a] for finite terms *)\n\nNotation \"x !\" := (@FVar F X x) (at level 75).\n\nNotation \"f @ a\" := (@Fun F X f (vcons a (vnil term))) (right associativity, at level 75).\nNotation \"f @@ a\" := (@FFun F X f (vcons a (vnil fterm))) (right associativity, at level 75).\n\n(** UUU... *)\nCoFixpoint repeat_U : term :=\n  U @ repeat_U.\n\n(** DDD... *)\nCoFixpoint repeat_D : term :=\n  D @ repeat_D.\n\n(** U^n t *)\nFixpoint Unt (n : nat) t :=\n  match n with\n  | O   => t\n  | S n => U @ (Unt n t)\n  end.\n\n(** D^n t *)\nFixpoint Dnt (n : nat) t :=\n  match n with\n  | O   => t\n  | S n => D @ (Dnt n t)\n  end.\n\n(** U^2n t *)\nFixpoint U2nt (n : nat) t :=\n  match n with\n  | O   => t\n  | S n => U @ U @ (U2nt n t)\n  end.\n\n(** D^2n t *)\nFixpoint D2nt (n : nat) t :=\n  match n with\n  | O   => t\n  | S n => D @ D @ (D2nt n t)\n  end.\n\n(** D^n U^n t *)\nDefinition DnUnt n t : term :=\n  Dnt n (Unt n t).\n\n(** U^n D^n t *)\nDefinition UnDnt n t : term :=\n  Unt n (Dnt n t).\n\n(** D^2n U^2n t *)\nDefinition D2nU2nt n t : term :=\n  D2nt n (U2nt n t).\n\n(** U^2n D^2n t *)\nDefinition U2nD2nt n t : term :=\n  U2nt n (D2nt n t).\n\n(** We now define the term\n\n     [psi] = D U^2 D^3 U^4 ...\n\n   via an auxiliary parameterised term [psi'].\n\n   We would like to define psi' like this\n[[\n     CoFixpoint psi' n : term :=\n       Unt n (Dnt (S n) (psi' (S (S n)))).\n]]\n   but unfortunately this is not in guarded form. We therefore turn to a\n   more complex definition with anonymous cofixpoints. *)\n\n(** [psi' n] = D^n U^Sn D^SSn U^SSSn ... *)\nCoFixpoint psi' n : term :=\n  (cofix D2nDt (d : nat) :=\n    match d with\n    | O   => D @ (cofix U2nt (u : nat) :=\n               match u with\n               | O   => psi' (S n)\n               | S u => U @ U @ (U2nt u)\n               end) (S n)\n    | S d => D @ D @ (D2nDt d)\n    end) n.\n\n(* [psi] = D U^2 D^3 U^4 ... *)\nDefinition psi := psi' 0.\n\n(** Some useful lemmas on bisimilarity and equality of common terms follow. *)\n\nLemma term_bis_U :\n  forall t s,\n    t [~] s -> (U @ t) [~] (U @ s).\nProof.\nintros t s H.\nconstructor.\nintro i; dependent destruction i; [idtac | inversion i].\nassumption.\nQed.\n\nLemma term_bis_D :\n  forall t s,\n    t [~] s -> (D @ t) [~] (D @ s).\nProof.\nintros t s H.\nconstructor.\nintro i; dependent destruction i; [idtac | inversion i].\nassumption.\nQed.\n\nLemma term_eq_up_to_n_Unt_repeat_U :\n  forall n t,\n    term_eq_up_to n (Unt n t) repeat_U.\nProof.\ninduction n as [| n IH]; simpl; intro t.\nconstructor.\nrewrite (peek_eq repeat_U); simpl.\nconstructor.\nintro i.\ndependent destruction i.\napply IH.\ndependent destruction i.\nQed.\n\nLemma term_eq_up_to_n_Dnt_repeat_D :\n  forall n t,\n    term_eq_up_to n (Dnt n t) repeat_D.\nProof.\ninduction n as [| n IH]; simpl; intro t.\nconstructor.\nrewrite (peek_eq repeat_D); simpl.\nconstructor.\nintro i.\ndependent destruction i.\napply IH.\ndependent destruction i.\nQed.\n\nLemma term_bis_Unt :\n  forall n t s,\n    t [~] s -> Unt n t [~] Unt n s.\nProof.\ninduction n; intros t s H; simpl.\nassumption.\napply term_bis_U.\napply IHn.\nassumption.\nQed.\n\nLemma term_bis_Dnt :\n  forall n t s,\n    t [~] s -> Dnt n t [~] Dnt n s.\nProof.\ninduction n; intros t s H; simpl.\nassumption.\napply term_bis_D.\napply IHn.\nassumption.\nQed.\n\nLemma UUnt_eq_UnUt :\n  forall n t,\n    (U @ Unt n t) = Unt n (U @ t).\ninduction n; intro t.\nreflexivity.\nsimpl.\nrewrite <- IHn.\nreflexivity.\nQed.\n\nLemma DDnt_eq_DnDt :\n  forall n t,\n    (D @ Dnt n t) = Dnt n (D @ t).\ninduction n; intro t.\nreflexivity.\nsimpl.\nrewrite <- IHn.\nreflexivity.\nQed.\n\nLemma UU2nt_eq_U2nUt :\n  forall n t,\n    (U @ U2nt n t) = U2nt n (U @ t).\ninduction n; intro t.\nreflexivity.\nsimpl.\nrewrite <- IHn.\nreflexivity.\nQed.\n\nLemma DD2nt_eq_D2nDt :\n  forall n t,\n    (D @ D2nt n t) = D2nt n (D @ t).\ninduction n; intro t.\nreflexivity.\nsimpl.\nrewrite <- IHn.\nreflexivity.\nQed.\n\nLemma DSnUSnt_eq_DDnUnUt :\n  forall n t,\n    DnUnt (S n) t = (D @ (DnUnt n (U @ t))).\nProof.\nintros n t.\nunfold DnUnt.\nsimpl.\nrewrite UUnt_eq_UnUt.\nreflexivity.\nQed.\n\nLemma USnDSnt_eq_UUnDnDt :\n  forall n t,\n    UnDnt (S n) t = (U @ (UnDnt n (D @ t))).\nProof.\nintros n t.\nunfold UnDnt.\nsimpl.\nrewrite DDnt_eq_DnDt.\nreflexivity.\nQed.\n\nLemma D2SnU2Snt_eq_DDD2nU2nUUt :\n  forall n t,\n    D2nU2nt (S n) t = (D @ D @ (D2nU2nt n (U @ U @ t))).\nProof.\nintros n t.\nunfold D2nU2nt.\nsimpl.\nrewrite UU2nt_eq_U2nUt.\nrewrite UU2nt_eq_U2nUt.\nreflexivity.\nQed.\n\nLemma U2SnD2Snt_eq_UUU2nD2nDDt :\n  forall n t,\n    U2nD2nt (S n) t = (U @ U @ (U2nD2nt n (D @ D @ t))).\nProof.\nintros n t.\nunfold U2nD2nt.\nsimpl.\nrewrite DD2nt_eq_D2nDt.\nrewrite DD2nt_eq_D2nDt.\nreflexivity.\nQed.\n\nLemma D2nU2nt_eq_D2nU2nt :\n  forall n t,\n    D2nU2nt n t = DnUnt (2 * n) t.\nProof.\ninduction n; intro t; simpl.\nunfold D2nU2nt, D2nt, U2nt, DnUnt, Dnt, Unt.\nreflexivity.\nrewrite D2SnU2Snt_eq_DDD2nU2nUUt.\nrewrite DSnUSnt_eq_DDnUnUt.\nrewrite IHn with (U @ U @ t).\nsimpl.\nrewrite (eq_sym (plus_n_Sm n (n + 0))).\nrewrite DSnUSnt_eq_DDnUnUt.\nreflexivity.\nQed.\n\n(** Some useful (but ugly) lemmas on bisimilarity and equality of psi and\n   (partial) unfoldings follow. *)\n\nLemma UU2nt_eq_U2nUt_unfolded :\n  forall n t,\n    (U @ (cofix U2nt (u : nat) : term :=\n            match u with\n            | 0 => t\n            | S u0 => U @ U @ U2nt u0\n            end) n)\n    =\n    (cofix U2nt (u : nat) : term :=\n       match u with\n       | 0 => U @ t\n       | S u0 => U @ U @ U2nt u0\n       end) n.\nProof.\ninduction n; intro t.\nrewrite (peek_eq ((cofix U2nt (u : nat) : term :=\n        match u with\n        | 0 => t\n        | S u0 => U @ U @ U2nt u0\n        end) 0)).\nrewrite (peek_eq ((cofix U2nt (u : nat) : term :=\n      match u with\n      | 0 => U @ t\n      | S u0 => U @ U @ U2nt u0\n      end) 0)).\nsimpl.\ndestruct t; reflexivity.\nrewrite (peek_eq ((cofix U2nt (u : nat) : term :=\n       match u with\n       | 0 => t\n       | S u0 => U @ U @ U2nt u0\n       end) (S n))).\nrewrite (peek_eq ((cofix U2nt (u : nat) : term :=\n      match u with\n      | 0 => U @ t\n      | S u0 => U @ U @ U2nt u0\n      end) (S n))).\nsimpl.\nrewrite IHn with t.\nreflexivity.\nQed.\n\nLemma psin_eq_DD2nU2nUUpsiSn :\n  forall n,\n    psi' n = (D @ (D2nU2nt n (U @ U @ (psi' (S n))))).\nProof.\nintro n.\nrewrite (peek_eq (psi' n)).\nsimpl.\ngeneralize (psi' (S n)).\ninduction n; intro t.\nrewrite (peek_eq ((cofix U2nt (u : nat) : term :=\n       match u with\n       | 0 => t\n       | S u0 => U @ U @ U2nt u0\n       end) 1)).\nunfold D2nU2nt.\nsimpl.\nrewrite (peek_eq ((cofix U2nt (u : nat) : term :=\n       match u with\n       | 0 => t\n       | S u0 => U @ U @ U2nt u0\n       end) 0)).\nsimpl.\ndestruct t; reflexivity.\nrewrite (peek_eq ((cofix U2nt (u : nat) : term :=\n                 match u with\n                 | 0 => t\n                 | S u0 => U @ U @ U2nt u0\n                 end) (S (S n)))).\nrewrite D2SnU2Snt_eq_DDD2nU2nUUt.\nsimpl.\nrewrite UU2nt_eq_U2nUt_unfolded with (S n) t.\nrewrite UU2nt_eq_U2nUt_unfolded with (S n) (U @ t).\nrewrite (peek_eq ((cofix D2nDt (d : nat) : term :=\n       match d with\n       | 0 =>\n           D @\n           (cofix U2nt (u : nat) : term :=\n              match u with\n              | 0 => U @ U @ t\n              | S u0 => U @ U @ U2nt u0\n              end) (S n)\n       | S d0 => D @ D @ D2nDt d0\n       end) n)).\nsimpl.\nrewrite IHn with (U @ U @ t).\nreflexivity.\nQed.\n\nLemma psin_eq_DS2nUS2nUpsiSn :\n  forall n,\n    psi' n = DnUnt (S (2 * n)) (U @ (psi' (S n))).\nProof.\nintro n.\nrewrite psin_eq_DD2nU2nUUpsiSn.\nrewrite D2nU2nt_eq_D2nU2nt.\nrewrite DSnUSnt_eq_DDnUnUt.\nreflexivity.\nQed.\n\n(** * Contexts\n\n   Contexts over the given signature and variable. *)\n\nNotation context := (context F X).\n\n(** Notational shortcut for function application in contexts. *)\nNotation \"f @@@ a\" := (@CFun F X f 0 0 (@refl_equal nat (arity f)) (vnil term) a (vnil term)) (right associativity, at level 75).\n\n(** D^n c *)\nFixpoint Dnc n c : context :=\n  match n with\n  | O   => c\n  | S n => D @@@ (Dnc n c)\n  end.\n\n(** U^n c *)\nFixpoint Unc n c : context :=\n  match n with\n  | O   => c\n  | S n => U @@@ (Unc n c)\n  end.\n\n(** We prove some lemmas about filling contexts. *)\n\nLemma fill_Dnc_t :\n  forall n c t,\n    fill (Dnc n c) t = Dnt n (fill c t).\nProof.\ninduction n.\nreflexivity.\nintros c t.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\nLemma fill_Unc_t :\n  forall n c t,\n    fill (Unc n c) t = Unt n (fill c t).\nProof.\ninduction n.\nreflexivity.\nintros c t.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\nLemma fill_DnHole_t :\n  forall n t,\n    fill (Dnc n Hole) t = Dnt n t.\nProof.\nintros n t.\napply fill_Dnc_t.\nQed.\n\nLemma fill_UnHole_t :\n  forall n t,\n    fill (Unc n Hole) t = Unt n t.\nProof.\nintros n t.\napply fill_Unc_t.\nQed.\n\nLemma fill_DmUnc_t :\n  forall m n c t,\n    fill (Dnc m (Unc n c)) t = Dnt m (Unt n (fill c t)).\nProof.\nintros m n c t.\nrewrite fill_Dnc_t.\nrewrite fill_Unc_t.\nreflexivity.\nQed.\n\nLemma fill_UmDnc_t :\n  forall m n c t,\n    fill (Unc m (Dnc n c)) t = Unt m (Dnt n (fill c t)).\nProof.\nintros m n c t.\nrewrite fill_Unc_t.\nrewrite fill_Dnc_t.\nreflexivity.\nQed.\n\nLemma fill_DmUnHole_t :\n  forall m n t,\n    fill (Dnc m (Unc n Hole)) t = Dnt m (Unt n t).\nProof.\nintros m n t.\napply fill_DmUnc_t.\nQed.\n\nLemma fill_UmDnHole_t :\n  forall m n t,\n    fill (Unc m (Dnc n Hole)) t = Unt m (Dnt n t).\nProof.\nintros m n t.\napply fill_UmDnc_t.\nQed.\n\n(** * Rewriting\n\n   We construct the rewrite rules for the TRS and show it is weakly\n   orthogonal. We also show that UUU... and DDD... are normal forms. *)\n\nNotation trs := (trs F X).\n\n(** We use this variable in the rewrite rules *)\nDefinition varx : X := tt.\n\n(** Rule [DU] : DUx -> x *)\n\nDefinition DU_l : fterm := D @@ U @@ varx!.\nDefinition DU_r : fterm := varx!.\n\nLemma wf_DU :\n  is_var DU_l = false /\\\n  incl (vars DU_r) (vars DU_l).\nProof.\nsplit; simpl.\nreflexivity.\nintros a H.\nassumption.\nQed.\n\nDefinition DU : rule := Rule DU_l DU_r wf_DU.\n\n(** Rule [UD] : UDx -> x *)\n\nDefinition UD_l : fterm := U @@ D @@ varx!.\nDefinition UD_r : fterm := varx!.\n\nLemma wf_UD :\n  is_var UD_l = false /\\\n  incl (vars UD_r) (vars UD_l).\nProof.\nsplit; simpl.\nreflexivity.\nintros a H.\nassumption.\nQed.\n\nDefinition UD : rule := Rule UD_l UD_r wf_UD.\n\n(** The TRS [UD_trs] as a list of its rules. *)\n\nDefinition UD_trs : trs := DU :: UD :: nil.\n\n(** [UD_trs] is trivialy left-linear. *)\nLemma left_linear_UD :\n  trs_left_linear UD_trs.\nProof.\nconstructor; [| constructor];\n  unfold left_linear; unfold linear; simpl;\n    constructor.\nintro; assumption.\nconstructor.\nintro; assumption.\nconstructor.\nQed.\n\n(** All critical pairs in [UD_trs] are trivial. *)\nLemma critical_pairs_trivial_UD :\n  forall t1 t2,\n    critical_pair UD_trs t1 t2 ->\n    t1 [~] t2.\nProof.\nintros t1 t2 H.\nunfold critical_pair in H.\ndestruct H as [r1 [r2 [[| [| a] [| [| b] [| c p]]] [sigma [tau [[Hr1 | [Hr1 | []]] [[Hr2 | [Hr2 | []]] [T H]]]]]]]];\nrewrite <- Hr1 in * |-;\nrewrite <- Hr2 in * |-;\nclear r1 r2 Hr1 Hr2;\ntry (contradict T; auto; fail);\nclear T;\ntry (contradict H; fail); simpl in H;\ndestruct H as [V [H [H1 H2]]];\ntry (contradict V; fail);\napply (term_bis_trans H1); apply term_bis_symm; apply (term_bis_trans H2);\nclear H1 H2;\ndependent destruction H; specialize H with (First (n := 0)); unfold vmap in H; simpl in H;\ndependent destruction H; specialize H with (First (n := 0)); unfold vmap in H; simpl in H;\nclear V.\n\nrewrite <- x.\nconstructor.\nintro i.\ndependent destruction i.\nunfold vcast.\ngeneralize (lt_plus_minus_r (Gt.gt_le_S 0 1 (Lt.lt_0_Sn 0))).\nintro e.\ndependent destruction e.\ngeneralize (lt_plus_minus_r (Lt.lt_le_S 0 1 (Lt.lt_0_Sn 0))).\nintro e.\ndependent destruction e.\nassumption.\ninversion i.\n\nrewrite <- x.\nconstructor.\nintro i.\ndependent destruction i.\nunfold vcast.\ngeneralize (lt_plus_minus_r (Gt.gt_le_S 0 1 (Lt.lt_0_Sn 0))).\nintro e.\ndependent destruction e.\ngeneralize (lt_plus_minus_r (Lt.lt_le_S 0 1 (Lt.lt_0_Sn 0))).\nintro e.\ndependent destruction e.\nassumption.\ninversion i.\nQed.\n\nLemma weakly_orthogonal_UD :\n  weakly_orthogonal UD_trs.\nProof.\nsplit.\nexact left_linear_UD.\nexact critical_pairs_trivial_UD.\nQed.\n\n(** DDD... is a normal form. *)\nLemma normal_form_repeat_D :\n  normal_form UD_trs repeat_D.\nProof.\n(** TODO: a lot of this proof is a mess, cleanup.\n   Also, I expect that this could be generalized and shortened quite a bit\n   by using pos_eq. *)\nintros [c [r [u [H1 H2]]]].\ndestruct H1 as [H1 | [H1 | []]].\nrewrite <- H1 in *|-.\nclear H1.\nassert (H := (term_bis_implies_term_eq H2) (S (S (hole_depth c)))).\nrewrite (peek_eq repeat_D) in H.\ndependent destruction H.\nassert (H' := H First).\nrewrite (peek_eq repeat_D) in H'.\ndependent destruction H'.\nassert (H' := H0 First).\nsimpl in H'.\n\n(* idea, make [=]1 from x0 *)\nassert (y0 : term_eq_up_to 1 (@Fun F X D v) (fill c (@Fun F X D (vmap (substitute u) (vcons (U @@ varx!) (vnil fterm)))))).\n(*assert (y0 : @Fun F X D v [=] fill c (@Fun F X D (vmap (substitute u) (vcons (U @@ 1 !) (vnil fterm))))).*)\nrewrite x0.\napply term_eq_up_to_refl.\nclear x0.\n\ninduction c.\n\nassert (H3 := (term_bis_implies_term_eq H2) 2).\nrewrite (peek_eq repeat_D) in H3.\ndependent destruction H3.\nassert (H3 := H1 First).\nrewrite (peek_eq repeat_D) in H3.\ndependent destruction H3.\n\nrewrite (peek_eq repeat_D) in H2.\n(*intro x0.*)\nassert (d : f = D).\n(*assert (y1 := y0 1).*)\ninversion_clear y0.\nreflexivity.\n\n(*injection x0.\nintros _ d.*)\nrevert e H2 H y0 H0 H'.\ndependent rewrite d.\nintro e.\nassert (ij : i = 0 /\\ j = 0).\ndestruct i as [| [| i]]; auto; discriminate e.\nrevert e v1 v2.\nrewrite (proj1 ij).\nrewrite (proj2 ij).\nintros e v1 v2 H2 H y0 H0 H'.\nclear f i j d ij.\napply IHc; clear IHc.\n\n(* this part is quite ugly *)\napply term_eq_implies_term_bis.\nintro n.\nassert (H2' : term_eq_up_to (S n) (@Fun F X D (vcons (fill c (substitute u (lhs DU))) v2)) (D @ repeat_D)).\nassert (jaja : fill (@CFun F X D 0 0 e v1 c v2) (substitute u (lhs DU)) = @Fun F X D (vcons (fill c (substitute u (lhs DU))) v2)).\ndependent destruction e.\nreflexivity.\nrewrite jaja in H2.\nexact ((term_bis_implies_term_eq H2) (S n)).\napply (@teut_fun_inv F X n D (vcons (fill c (substitute u (lhs DU))) v2) (vcons repeat_D (vnil term)) H2' First).\nintro i.\napply term_eq_up_to_weaken.\napply H.\nintro i.\ndependent destruction i.\napply term_eq_up_to_weaken.\nassumption.\ndependent destruction i.\napply term_eq_up_to_weaken.\nassumption.\n\nclear v0 x H y0 H0 H'.\ndestruct c.\nconstructor.\nconstructor.\nsimpl.\nsimpl in H2.\ndependent destruction H2.\nassert (H3 := H First).\nsimpl in H3.\nclear H.\nrewrite (peek_eq repeat_D) in H3.\ndependent destruction H3.\nrevert x.\ndependent destruction e.\nintro y.\nsimpl in y.\ninjection y.\nintros _ d.\nclear y x H v1 v2 v4.\nrevert e0.\nrewrite <- d.\nintro e.\nconstructor.\nconstructor.\n\n(** Almost the same argument follows for [r=UD] instead of [r=DU]. *)\n\nrewrite <- H1 in *|-.\nclear H1.\nassert (H := (term_bis_implies_term_eq H2) (S (hole_depth c))).\nrewrite (peek_eq repeat_D) in H.\ndependent destruction H.\nassert (H' := H First).\nsimpl in H'.\nclear x.\n\ninduction c.\n\nrewrite (peek_eq repeat_D) in H2.\ninversion_clear H2.\n\nrewrite (peek_eq repeat_D) in H2.\n(*intro x0.*)\nassert (d : f = D).\ninversion_clear H2.\nreflexivity.\n\nrevert e H2 H H'.\ndependent rewrite d.\nintro e.\nassert (ij : i = 0 /\\ j = 0).\ndestruct i as [| [| i]]; auto; discriminate e.\nrevert e v0 v1.\nrewrite (proj1 ij).\nrewrite (proj2 ij).\nintros e v1 v2 H2 H H'.\nclear f i j d ij.\napply IHc; clear IHc.\n\n(* this part is quite ugly *)\napply term_eq_implies_term_bis.\nintro n.\nassert (H2' : term_eq_up_to (S n) (@Fun F X D (vcons (fill c (substitute u (lhs UD))) v2)) (D @ repeat_D)).\nassert (jaja : fill (@CFun F X D 0 0 e v1 c v2) (substitute u (lhs UD)) = @Fun F X D (vcons (fill c (substitute u (lhs UD))) v2)).\ndependent destruction e.\nreflexivity.\nrewrite jaja in H2.\nexact ((term_bis_implies_term_eq H2) (S n)).\napply (@teut_fun_inv F X n D (vcons (fill c (substitute u (lhs UD))) v2) (vcons repeat_D (vnil term)) H2' First).\nintro i.\napply term_eq_up_to_weaken.\napply H.\napply term_eq_up_to_weaken.\nassumption.\nQed.\n\n(** UUU... is a normal form. *)\nLemma normal_form_repeat_U :\n  normal_form UD_trs repeat_U.\nProof.\n(** This proof is just a copy of the DDD... proof. *)\nintros [c [r [u [H1 H2]]]].\ndestruct H1 as [H1 | [H1 | []]].\n\nrewrite <- H1 in *|-.\nclear H1.\nassert (H := (term_bis_implies_term_eq H2) (S (hole_depth c))).\nrewrite (peek_eq repeat_U) in H.\ndependent destruction H.\nassert (H' := H First).\nsimpl in H'.\nclear x.\n\ninduction c.\n\nrewrite (peek_eq repeat_U) in H2.\ninversion_clear H2.\n\nrewrite (peek_eq repeat_U) in H2.\n(*intro x0.*)\nassert (d : f = U).\ninversion_clear H2.\nreflexivity.\n\nrevert e H2 H H'.\ndependent rewrite d.\nintro e.\nassert (ij : i = 0 /\\ j = 0).\ndestruct i as [| [| i]]; auto; discriminate e.\nrevert e v0 v1.\nrewrite (proj1 ij).\nrewrite (proj2 ij).\nintros e v1 v2 H2 H H'.\nclear f i j d ij.\napply IHc; clear IHc.\n\n(* this part is quite ugly *)\napply term_eq_implies_term_bis.\nintro n.\nassert (H2' : term_eq_up_to (S n) (@Fun F X U (vcons (fill c (substitute u (lhs DU))) v2)) (U @ repeat_U)).\nassert (jaja : fill (@CFun F X U 0 0 e v1 c v2) (substitute u (lhs DU)) = @Fun F X U (vcons (fill c (substitute u (lhs DU))) v2)).\ndependent destruction e.\nreflexivity.\nrewrite jaja in H2.\nexact ((term_bis_implies_term_eq H2) (S n)).\napply (@teut_fun_inv F X n U (vcons (fill c (substitute u (lhs DU))) v2) (vcons repeat_U (vnil term)) H2' First).\nintro i.\napply term_eq_up_to_weaken.\napply H.\napply term_eq_up_to_weaken.\nassumption.\n\n(** Almost the same argument follows for [r=UD] instead of [r=DU]. *)\n\nrewrite <- H1 in *|-.\nclear H1.\nassert (H := (term_bis_implies_term_eq H2) (S (S (hole_depth c)))).\nrewrite (peek_eq repeat_U) in H.\ndependent destruction H.\nassert (H' := H First).\nrewrite (peek_eq repeat_U) in H'.\ndependent destruction H'.\nassert (H' := H0 First).\nsimpl in H'.\n\n(* idea, make [=]1 from x0 *)\nassert (y0 : term_eq_up_to 1 (@Fun F X U v) (fill c (@Fun F X U (vmap (substitute u) (vcons (D @@ varx!) (vnil fterm)))))).\n(*assert (y0 : @Fun F X D v [=] fill c (@Fun F X D (vmap (substitute u) (vcons (U @@ 1 !) (vnil fterm))))).*)\nrewrite x0.\napply term_eq_up_to_refl.\nclear x0.\n\ninduction c.\n\nassert (H3 := (term_bis_implies_term_eq H2) 2).\nrewrite (peek_eq repeat_U) in H3.\ndependent destruction H3.\nassert (H3 := H1 First).\nrewrite (peek_eq repeat_U) in H3.\ndependent destruction H3.\n\nrewrite (peek_eq repeat_U) in H2.\n(*intro x0.*)\nassert (d : f = U).\n(*assert (y1 := y0 1).*)\ninversion_clear y0.\nreflexivity.\n\n(*injection x0.\nintros _ d.*)\nrevert e H2 H y0 H0 H'.\ndependent rewrite d.\nintro e.\nassert (ij : i = 0 /\\ j = 0).\ndestruct i as [| [| i]]; auto; discriminate e.\nrevert e v1 v2.\nrewrite (proj1 ij).\nrewrite (proj2 ij).\nintros e v1 v2 H2 H y0 H0 H'.\nclear f i j d ij.\napply IHc; clear IHc.\n\n(* this part is quite ugly *)\napply term_eq_implies_term_bis.\nintro n.\nassert (H2' : term_eq_up_to (S n) (@Fun F X U (vcons (fill c (substitute u (lhs UD))) v2)) (U @ repeat_U)).\nassert (jaja : fill (@CFun F X U 0 0 e v1 c v2) (substitute u (lhs UD)) = @Fun F X U (vcons (fill c (substitute u (lhs UD))) v2)).\ndependent destruction e.\nreflexivity.\nrewrite jaja in H2.\nexact ((term_bis_implies_term_eq H2) (S n)).\napply (@teut_fun_inv F X n U (vcons (fill c (substitute u (lhs UD))) v2) (vcons repeat_U (vnil term)) H2' First).\nintro i.\napply term_eq_up_to_weaken.\napply H.\nintro i.\ndependent destruction i.\napply term_eq_up_to_weaken.\nassumption.\ndependent destruction i.\napply term_eq_up_to_weaken.\nassumption.\n\nclear v0 x H y0 H0 H'.\ndestruct c.\nconstructor.\nconstructor.\nsimpl.\nsimpl in H2.\ndependent destruction H2.\nassert (H3 := H First).\nsimpl in H3.\nclear H.\nrewrite (peek_eq repeat_U) in H3.\ndependent destruction H3.\nrevert x.\ndependent destruction e.\nintro y.\nsimpl in y.\ninjection y.\nintros _ d.\nclear y x H v1 v2 v4.\nrevert e0.\nrewrite <- d.\nintro e.\nconstructor.\nconstructor.\nQed.\n\n(** DDD... and UUU... are different. *)\nLemma neq_repeat_D_repeat_U :\n  ~ repeat_D [~] repeat_U.\nProof.\nintro H.\nrewrite (peek_eq repeat_D), (peek_eq repeat_U) in H.\ninversion H.\nQed.\n\n(** * Rewrite sequences\n\n   We now build our infinite rewrite sequences. *)\n\nNotation Step := (Step UD_trs).\nNotation Nil' := (Nil UD_trs).\n\nNotation \"s [>] t\" := (step UD_trs s t) (at level 40).\nNotation \"s ->> t\" := (sequence UD_trs s t) (at level 40).\n\nNotation \"r [ i ]\" := (pred r i) (at level 60).\nNotation \"r [1 i ]\" := (fst (projT1 (pred r i))) (at level 60).\nNotation \"r [2 i ]\" := (snd (projT1 (pred r i))) (at level 60).\nNotation \"r [seq i ]\" := (fst (projT2 (pred r i))) (at level 60).\nNotation \"r [stp i ]\" := (snd (projT2 (pred r i))) (at level 60).\n\nLemma DU_in :\n  In DU UD_trs.\nProof.\nleft; reflexivity.\nQed.\n\nLemma UD_in :\n  In UD UD_trs.\nProof.\nright; left; reflexivity.\nQed.\n\nDefinition sub_t t (x : X) : term := t.\n\n(** ** psi ->> UUU... *)\n\nLemma fact_term_bis_UmDSnUSnt :\n  forall (m n : nat) (t : term),\n    fill (Unc m (Dnc n Hole)) (substitute (sub_t (Unt n t)) (lhs DU))\n    [~]\n    Unt m (DnUnt (S n) t).\nProof.\nintros m n t.\nrewrite fill_UmDnHole_t.\nunfold DnUnt.\nsimpl.\nrewrite DDnt_eq_DnDt.\napply term_bis_Unt.\napply term_bis_Dnt.\nconstructor.\nintro i; dependent destruction i; [idtac | inversion i].\nunfold vmap.\nsimpl.\nconstructor.\nintro i; dependent destruction i; [idtac | inversion i].\nunfold vmap.\nsimpl.\napply term_bis_refl.\nQed.\n\nLemma fact_term_eq_UmDnUnt :\n  forall (m n : nat) (t : term),\n    fill (Unc m (Dnc n Hole)) (substitute (sub_t (Unt n t)) (rhs DU))\n    =\n    Unt m (DnUnt n t).\nProof.\nintros m n t.\nrewrite fill_Unc_t.\nrewrite fill_Dnc_t.\nsimpl.\nreflexivity.\nQed.\n\nLemma fact_term_bis_UmDnUnt :\n  forall (m n : nat) (t : term),\n    fill (Unc m (Dnc n Hole)) (substitute (sub_t (Unt n t)) (rhs DU))\n    [~]\n    Unt m (DnUnt n t).\nProof.\nintros m n t.\nrewrite fact_term_eq_UmDnUnt.\napply term_bis_refl.\nQed.\n\n(** Step from U^m D^Sn U^Sn to U^m D^n U^n t. *)\nDefinition p_UmDSnUSnt_UmDnUnt m n t : Unt m (DnUnt (S n) t) [>] Unt m (DnUnt n t) :=\n  Step DU (Unc m (Dnc n Hole)) (sub_t (Unt n t)) DU_in (fact_term_bis_UmDSnUSnt m n t) (fact_term_bis_UmDnUnt m n t).\n\n(** n-step rewrite sequence from U^m D^n U^n t to U^m t. *)\nFixpoint s_UmDnUnt_Umt m n t : Unt m (DnUnt n t) ->> Unt m t :=\n  match n return Unt m (DnUnt n t) ->> Unt m t with\n  | O   => Nil' (Unt m t)\n  | S n => snoc (p_UmDSnUSnt_UmDnUnt m n t) (s_UmDnUnt_Umt m n t)\n  end.\n\n(** 2n+1-step rewrite sequence from U^n [psi' n] to U^Sn [psi' Sn]. *)\nDefinition s_Unpsin_USnpsiSn n : Unt n (psi' n) ->> Unt (S n) (psi' (S n)).\n(** Coq 8.3-rc1 does the 'intro n' automatically, but 8.3-beta0-1 needs it. *)\nintros.\nassert (H : Unt n (DnUnt (S (2 * n)) (U @ psi' (S n))) ->> Unt n (U @ psi' (S n))).\nrefine (s_UmDnUnt_Umt n (S (2 * n)) (U @ psi' (S n))).\nunfold DnUnt in H.\nrewrite psin_eq_DS2nUS2nUpsiSn.\nsimpl.\nsimpl in H.\nunfold DnUnt.\nsimpl.\nrewrite UUnt_eq_UnUt with n (psi' (S n)).\nexact H.\nDefined.\n\n(** We would have liked to define the above by the following definition\n   using [Program], but unfortunately it is not accepted by Coq. Is this\n   a bug in [Program]?\n\n[[\nProgram Definition s_Unpsin_USnpsiSn n : Unt n (psi' n) ->> Unt (S n) (psi' (S n)) :=\n  s_UmDnUnt_Umt n (S (2 * n)) (U @ psi' (S n)).\nNext Obligation.\nsymmetry.\nunfold DnUnt.\nrewrite psin_eq_DS2nUS2nUpsiSn.\nreflexivity.\nDefined.\nNext Obligation.\nrewrite UUnt_eq_UnUt.\nreflexivity.\nDefined.\n]]\n*)\n\n(** Rewrite sequence from [psi] to U^n [psi' n]. *)\nFixpoint s_psi_Unpsin n : psi ->> Unt n (psi' n) :=\n  match n return psi ->> Unt n (psi' n) with\n  | O   => Nil' psi\n  | S n => append (s_psi_Unpsin n) (s_Unpsin_USnpsiSn n)\n  end.\n\nLemma converges_Unpsin : converges (fun n => Unt n (psi' n)) repeat_U.\nProof.\nintro d.\nexists d.\nintros m H.\nsimpl.\napply term_eq_up_to_weaken_generalized with m.\nassumption.\napply term_eq_up_to_n_Unt_repeat_U.\nQed.\n\n(** Omega-step rewrite sequence from [psi] to UUU... *)\nDefinition s_psi_repeat_U : psi ->> repeat_U :=\n  Lim s_psi_Unpsin converges_Unpsin.\n\n(** ** psi ->> DDD... *)\n\nLemma fact_term_bis_DmUSnDSnt :\n  forall (m n : nat) (t : term),\n    fill (Dnc m (Unc n Hole)) (substitute (sub_t (Dnt n t)) (lhs UD))\n    [~]\n    Dnt m (UnDnt (S n) t).\nProof.\nintros m n t.\nrewrite fill_DmUnHole_t.\nunfold UnDnt.\nsimpl.\nrewrite UUnt_eq_UnUt.\napply term_bis_Dnt.\napply term_bis_Unt.\nconstructor.\nintro i; dependent destruction i; [idtac | inversion i].\nunfold vmap.\nsimpl.\nconstructor.\nintro i; dependent destruction i; [idtac | inversion i].\nunfold vmap.\nsimpl.\napply term_bis_refl.\nQed.\n\nLemma fact_term_eq_DmUnDnt :\n  forall (m n : nat) (t : term),\n    fill (Dnc m (Unc n Hole)) (substitute (sub_t (Dnt n t)) (rhs UD))\n    =\n    Dnt m (UnDnt n t).\nProof.\nintros m n t.\nrewrite fill_Dnc_t.\nrewrite fill_Unc_t.\nsimpl.\nreflexivity.\nQed.\n\nLemma fact_term_bis_DmUnDnt :\n  forall (m n : nat) (t : term),\n    fill (Dnc m (Unc n Hole)) (substitute (sub_t (Dnt n t)) (rhs UD))\n    [~]\n    Dnt m (UnDnt n t).\nProof.\nintros m n t.\nrewrite fact_term_eq_DmUnDnt.\napply term_bis_refl.\nQed.\n\n(* Step from D^m U^Sn D^Sn t to D^m U^n D^n t. *)\nDefinition p_DmUSnDSnt_DmUnDnt m n t : Dnt m (UnDnt (S n) t) [>] Dnt m (UnDnt n t) :=\n  Step UD (Dnc m (Unc n Hole)) (sub_t (Dnt n t)) UD_in (fact_term_bis_DmUSnDSnt m n t) (fact_term_bis_DmUnDnt m n t).\n\n(* n-step rewrite sequence from D^m U^n D^n t to D^m t. *)\nFixpoint s_DmUnDnt_Dmt m n t : Dnt m (UnDnt n t) ->> Dnt m t :=\n  match n return Dnt m (UnDnt n t) ->> Dnt m t with\n  | O   => Nil' (Dnt m t)\n  | S n => snoc (p_DmUSnDSnt_DmUnDnt m n t) (s_DmUnDnt_Dmt m n t)\n  end.\n\n(** 2n-step rewrite sequence from D^n U^2n [psi' n] to D^Sn U2Sn [psi' Sn]. *)\nDefinition s_DnU2npsin_DSnU2SnpsiSn n : Dnt n (Unt (2 * n) (psi' n)) ->> Dnt (S n) (Unt (2 * (S n)) (psi' (S n))).\n(** Coq 8.3-rc1 does the 'intro n' automatically, but 8.3-beta0-1 needs it. *)\nintros.\nassert (H : Dnt n (UnDnt (2 * n) (D @ Unt (2 * (S n)) (psi' (S n)))) ->> Dnt n (D @ (Unt (2 * S n)) (psi' (S n)))).\nrefine (s_DmUnDnt_Dmt n (2 * n) (D @ (Unt (2 * (S n)) (psi' (S n))))).\nunfold UnDnt in H.\nrewrite psin_eq_DS2nUS2nUpsiSn.\nunfold DnUnt.\nsimpl.\nrewrite DDnt_eq_DnDt.\nsimpl in H.\nrewrite <- plus_n_Sm in H.\nrewrite <- plus_n_Sm.\nsimpl in H.\nsimpl.\nrewrite <- UUnt_eq_UnUt.\nrewrite DDnt_eq_DnDt.\nexact H.\nDefined.\n\n(** We would have liked to define the above by the following definition\n   using [Program], but unfortunately it is not accepted by Coq. Is this\n   a bug in [Program]?\n\n[[\nProgram Definition s_DnU2npsin_DSnU2SnpsiSn n : Dnt n (Unt (2 * n) (psi' n)) ->> Dnt (S n) (Unt (2 * (S n)) (psi' (S n))) :=\n  s_DmUnDnt_Dmt n (2 * n) (D @ (Unt (2 * (S n)) (psi' (S n)))).\nNext Obligation.\nsymmetry.\nunfold UnDnt.\nrewrite psin_eq_DS2nUS2nUpsiSn.\nunfold DnUnt.\nsimpl.\nrewrite DDnt_eq_DnDt.\nrewrite <- plus_n_Sm.\nrewrite <- UUnt_eq_UnUt.\nreflexivity.\nDefined.\nNext Obligation.\nrewrite DDnt_eq_DnDt.\nreflexivity.\nDefined.\n]]\n*)\n\n(** Rewrite sequence from [psi] to D^Sn U^2Sn [psi' Sn]. *)\nFixpoint s_psi_DSnU2SnpsiSn n : psi ->> Dnt (S n) (Unt (2 * (S n)) (psi' (S n))) :=\n  match n return psi ->> Dnt (S n) (Unt (2 * (S n)) (psi' (S n))) with\n  | O   => s_DnU2npsin_DSnU2SnpsiSn 0\n  | S n => append (s_psi_DSnU2SnpsiSn n) (s_DnU2npsin_DSnU2SnpsiSn (S n))\n  end.\n\nLemma converges_DSnU2SnpsiSn : converges (fun n => Dnt (S n) (Unt (2 * (S n)) (psi' (S n)))) repeat_D.\nProof.\nintro d.\nexists d.\nintros m H.\nsimpl.\napply term_eq_up_to_weaken_generalized with m.\nassumption.\nrewrite DDnt_eq_DnDt.\napply term_eq_up_to_n_Dnt_repeat_D.\nQed.\n\n(* Omega-step reduction from [psi] to DDD... *)\nDefinition s_psi_repeat_D : psi ->> repeat_D :=\n  Lim s_psi_DSnU2SnpsiSn converges_DSnU2SnpsiSn.\n\n(** * Well-formedness of the rewrite sequences\n\n   It should be noted that at this point, nothing has been said yet about\n   well-formedness of the two rewrite sequences. Furthermore, they might\n   not be convergent.\n\n   So we proceed by proving the [wf] property for the rewrite sequences.\n   Convergence seems our of our reach at this point unfortunately. *)\n\n(** ** Well-formedness of psi ->> UUU...\n\n   We first prove all finite prefixes are indeed finite. Then we prove that\n   every branch of the [Lim] constructor is embedded in the next branch. *)\n\nLemma finite_s_UmDnUnt_Umt :\n  forall m n t, finite (s_UmDnUnt_Umt m n t).\nProof.\ninduction n as [| n IH]; intro t; simpl.\nexact I.\napply snoc_finite.\napply IH.\nQed.\n\nLemma finite_s_Unpsin_USnpsiSn :\n  forall n, finite (s_Unpsin_USnpsiSn n).\nProof.\nintro n.\nunfold s_Unpsin_USnpsiSn; simpl.\nunfold eq_rect_r; repeat (elim_eq_rect ; simpl).\napply finite_s_UmDnUnt_Umt.\nQed.\n\nLemma finite_s_psi_Unpsin :\n  forall n : nat, finite (s_psi_Unpsin n).\nProof.\ninduction n as [| n IH]; simpl.\nexact I.\napply append_finite.\nexact IH.\napply finite_s_Unpsin_USnpsiSn.\nQed.\n\n(** The following lemmas help establish [wf]. They are not pretty. *)\n\nLemma s_UmDnUnt_Umt_is_cons :\n  forall m n t,\n    exists s, exists r : _ ->> s, exists p : s [>] _,\n      s_UmDnUnt_Umt m (S n) t = Cons r p.\nProof.\ninduction n; intro t; simpl.\nexists (Unt m (DnUnt 1 t)).\nexists (Nil' (Unt m (DnUnt 1 t))).\nexists (p_UmDSnUSnt_UmDnUnt m 0 t).\nreflexivity.\nsimpl in IHn.\nspecialize IHn with t.\ndestruct IHn as [s [r [p IH]]].\nrewrite IH.\nsimpl.\nexists s.\nexists (snoc (p_UmDSnUSnt_UmDnUnt m (S n) t) r).\nexists p.\nreflexivity.\nQed.\n\nLemma embed_strict_append_Unpsin_USnpsiSn :\n  forall t n (r : t ->> Unt n (psi' n)),\n    embed_strict r (append r (s_Unpsin_USnpsiSn n)).\nProof.\nintro t.\ndestruct n as [| n]; simpl;\nunfold s_Unpsin_USnpsiSn; simpl; unfold eq_rect_r; repeat (elim_eq_rect ; simpl); intro r.\nexists (inl _ tt).\napply embed_refl.\nrevert r.\nrewrite <- (plus_n_Sm n).\nrewrite <- plus_n_O.\nintro r.\ndestruct (s_UmDnUnt_Umt_is_cons (S n) (n + n) (U @ psi' (S (S n)))) as [s [q [p H]]].\nrewrite H.\nexists (inl _ tt).\nsimpl.\napply embed_append_right.\nQed.\n\nLemma wf_s_psi_Unpsin :\n  forall n : nat, wf (s_psi_Unpsin n).\nProof.\nintro n.\napply wf_finite.\napply finite_s_psi_Unpsin.\nQed.\n\nLemma wf_s_psi_repeat_U :\n  wf s_psi_repeat_U.\nProof.\nsplit.\napply wf_s_psi_Unpsin.\nintros n m H.\ninduction H; simpl.\napply embed_strict_append_Unpsin_USnpsiSn.\napply embed_strict_trans with psi (Unt m (psi' m)) (s_psi_Unpsin m).\napply IHle.\napply embed_strict_append_Unpsin_USnpsiSn.\nQed.\n\n(** ** Well-formedness of psi ->> DDD...\n\n   We first prove all finite prefixes are indeed finite. Then we prove that\n   every branch of the [Lim] constructor is embedded in the next branch. *)\n\nLemma finite_s_DmUnDnt_Dmt :\n  forall m n t, finite (s_DmUnDnt_Dmt m n t).\nProof.\ninduction n as [| n IH]; intro t; simpl.\nexact I.\napply snoc_finite.\napply IH.\nQed.\n\n(** It is very unclear to me why we have to take this statement apart. *)\nLemma finite_s_DnU2npsin_DSnU2SnpsiSn_helper :\n  forall n,\n       finite\n     (eq_rect\n        (Dnt (n + (n + 0)) (D @ U @ Unt (n + (n + 0)) (U @ psi' (S n))))\n        (fun y : term =>\n         Dnt n (Unt (n + (n + 0)) y) ->>\n         Dnt n (D @ U @ U @ Unt (n + (n + 0)) (psi' (S n))))\n        (eq_rect (U @ Unt (n + (n + 0)) (psi' (S n)))\n           (fun t : term =>\n            Dnt n (Unt (n + (n + 0)) (Dnt (n + (n + 0)) (D @ U @ t))) ->>\n            Dnt n (D @ U @ U @ Unt (n + (n + 0)) (psi' (S n))))\n           (s_DmUnDnt_Dmt n (n + (n + 0))\n              (D @ U @ U @ Unt (n + (n + 0)) (psi' (S n))))\n           (Unt (n + (n + 0)) (U @ psi' (S n)))\n           (UUnt_eq_UnUt (n + (n + 0)) (psi' (S n))))\n        (D @ Dnt (n + (n + 0)) (U @ Unt (n + (n + 0)) (U @ psi' (S n))))\n        (eq_sym\n           (DDnt_eq_DnDt (n + (n + 0))\n              (U @ Unt (n + (n + 0)) (U @ psi' (S n)))))).\nProof.\nintro n.\nrepeat (elim_eq_rect ; simpl).\napply finite_s_DmUnDnt_Dmt.\nQed.\n\nLemma finite_s_DnU2npsin_DSnU2SnpsiSn :\n  forall n, finite (s_DnU2npsin_DSnU2SnpsiSn n).\nProof.\nintro n.\nunfold s_DnU2npsin_DSnU2SnpsiSn; simpl.\nunfold eq_rect_r; repeat (elim_eq_rect ; simpl).\napply finite_s_DnU2npsin_DSnU2SnpsiSn_helper.\nQed.\n\n(** It is very unclear to me why we have to take this statement apart. *)\nLemma finite_s_psi_DSnU2SnpsiSn_helper :\n   finite\n     (eq_rect (DnUnt 1 (U @ psi' 1))\n        (fun y : term => y ->> (D @ U @ U @ psi' 1))\n        (Nil' (D @ U @ U @ psi' 1)) (psi' 0) (eq_sym (psin_eq_DS2nUS2nUpsiSn 0))).\nProof.\nelim_eq_rect; simpl.\nexact I.\nQed.\n\nLemma finite_s_psi_DSnU2SnpsiSn :\n  forall n : nat, finite (s_psi_DSnU2SnpsiSn n).\nProof.\ninduction n as [| n IH]; simpl.\nunfold s_DnU2npsin_DSnU2SnpsiSn; simpl.\nunfold eq_rect_r; repeat (elim_eq_rect; simpl).\napply finite_s_psi_DSnU2SnpsiSn_helper.\napply append_finite.\nexact IH.\nexact (finite_s_DnU2npsin_DSnU2SnpsiSn (S n)).\nQed.\n\n(** We use this predicate and the following lemmas to prove well-formedness.\n   Yes, this is ugly and a bit of a hack. *)\nFixpoint is_cons s t (r : s ->> t) : Prop :=\n  match r with\n  | Nil _          => False\n  | Cons _ _ q _ _ => True\n  | Lim _ _ f t c  => False\n  end.\n\nLemma is_cons_snoc :\n  forall s t u (p : s [>] t) (r : t ->> u),\n    is_cons r ->\n    is_cons (snoc p r).\nProof.\nintros.\ndestruct r; simpl.\nexact I.\nexact I.\ninversion H.\nQed.\n\nLemma append_is_cons :\n  forall s t u (r : s ->> t) (q : t ->> u),\n    is_cons q ->\n    embed_strict r (append r q).\nProof.\nintros.\ndestruct q.\nelim H.\nsimpl.\nexists (inl _ tt).\nsimpl.\napply embed_append_right.\nelim H.\nQed.\n\nLemma is_cons_s_DmUnDnt_Dmt :\n  forall m n t, is_cons (s_DmUnDnt_Dmt m (S n) t).\nProof.\ninduction n as [| n IH]; intro t; simpl.\nexact I.\napply is_cons_snoc.\napply IH.\nQed.\n\n(** It is very unclear to me why we have to take this statement apart. *)\nLemma is_cons_s_DnU2npsin_DSnU2SnpsiSn_helper :\n  forall n,\n   is_cons\n     (eq_rect\n        (Dnt (S n + (S n + 0))\n           (D @ U @ Unt (S n + (S n + 0)) (U @ psi' (S (S n)))))\n        (fun y : term =>\n         Dnt (S n) (Unt (S n + (S n + 0)) y) ->>\n         Dnt (S n) (D @ U @ U @ Unt (S n + (S n + 0)) (psi' (S (S n)))))\n        (eq_rect (U @ Unt (S n + (S n + 0)) (psi' (S (S n))))\n           (fun t : term =>\n            Dnt (S n)\n              (Unt (S n + (S n + 0)) (Dnt (S n + (S n + 0)) (D @ U @ t))) ->>\n            Dnt (S n) (D @ U @ U @ Unt (S n + (S n + 0)) (psi' (S (S n)))))\n           (s_DmUnDnt_Dmt (S n) (S n + (S n + 0))\n              (D @ U @ U @ Unt (S n + (S n + 0)) (psi' (S (S n)))))\n           (Unt (S n + (S n + 0)) (U @ psi' (S (S n))))\n           (UUnt_eq_UnUt (S n + (S n + 0)) (psi' (S (S n)))))\n        (D @\n         Dnt (S n + (S n + 0))\n           (U @ Unt (S n + (S n + 0)) (U @ psi' (S (S n)))))\n        (eq_sym\n           (DDnt_eq_DnDt (S n + (S n + 0))\n              (U @ Unt (S n + (S n + 0)) (U @ psi' (S (S n))))))).\nProof.\nintro n.\nsimpl.\nrepeat (elim_eq_rect ; simpl).\napply is_cons_snoc.\nrewrite <- plus_n_Sm.\nexact (is_cons_s_DmUnDnt_Dmt (S n) (n + (n + 0)) (D @ U @ U @ U @ Unt (S (n + (n + 0))) (psi' (S (S n))))).\nQed.\n\nLemma is_cons_s_DnU2npsin_DSnU2SnpsiSn :\n  forall n, 0 < n -> is_cons (s_DnU2npsin_DSnU2SnpsiSn n).\nProof.\nintros n H.\nunfold s_DnU2npsin_DSnU2SnpsiSn; simpl.\nunfold eq_rect_r; repeat (elim_eq_rect ; simpl).\ndestruct n.\ninversion H.\napply is_cons_s_DnU2npsin_DSnU2SnpsiSn_helper.\nQed.\n\nLemma embed_strict_append_DnU2npsin_DSnU2SnpsiSn :\n  forall t n (r : t ->> Dnt (S n) (Unt (2 * (S n)) (psi' (S n)))),\n    embed_strict r (append r (s_DnU2npsin_DSnU2SnpsiSn (S n))).\nProof.\nintros.\napply append_is_cons.\napply is_cons_s_DnU2npsin_DSnU2SnpsiSn.\nintuition.\nQed.\n\nLemma wf_s_psi_DSnU2SnpsiSn :\n  forall n : nat, wf (s_psi_DSnU2SnpsiSn n).\nProof.\nintro n.\napply wf_finite.\napply finite_s_psi_DSnU2SnpsiSn.\nQed.\n\nLemma wf_s_psi_repeat_D :\n  wf s_psi_repeat_D.\nProof.\nsplit.\napply wf_s_psi_DSnU2SnpsiSn.\nintros n m H.\ninduction H; simpl.\napply embed_strict_append_DnU2npsin_DSnU2SnpsiSn.\napply (embed_strict_trans (q := s_psi_DSnU2SnpsiSn m)).\napply IHle.\napply embed_strict_append_DnU2npsin_DSnU2SnpsiSn.\nQed.\n\n(** * Conclusions\n\n   We conclude by taking our results together, showing this TRS does not\n   have the unique normal forms property. We then generalise this to\n   show that weak orthogonality does not imply unique normal forms. *)\n\nLemma no_unique_normal_forms_UD :\n  ~ unique_normal_forms UD_trs.\nProof.\nintro H.\napply neq_repeat_D_repeat_U.\napply H with psi s_psi_repeat_D s_psi_repeat_U.\nexact wf_s_psi_repeat_D.\nexact wf_s_psi_repeat_U.\nexact normal_form_repeat_D.\nexact normal_form_repeat_U.\nQed.\n\nLemma no_unique_normal_forms_wo :\n  ~ forall F X trs, weakly_orthogonal (F := F) (X := X) trs -> unique_normal_forms trs.\nProof.\nintro H.\napply no_unique_normal_forms_UD.\napply H.\napply weakly_orthogonal_UD.\nQed.\n", "meta": {"author": "martijnvermaat", "repo": "infinitary-rewriting-coq", "sha": "0af6403a39c630de96ab2616ee7f3e01cd67a2f5", "save_path": "github-repos/coq/martijnvermaat-infinitary-rewriting-coq", "path": "github-repos/coq/martijnvermaat-infinitary-rewriting-coq/infinitary-rewriting-coq-0af6403a39c630de96ab2616ee7f3e01cd67a2f5/NoUniqueNormalFormsWO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7349920781132007}}
{"text": "Require Export Paths Fibrations.\n\n(** For compatibility with Coq 8.2. *)\nUnset Automatic Introduction.\n\n(** A space [A] is contractible if there is a point [x : A] and a\n   (pointwise) homotopy connecting the identity on [A] to the constant\n   map at [x].  Thus an element of [is_contr A] is a pair whose\n   first component is a point [x] and the second component is a\n   pointwise retraction of [A] to [x]. *)\n\nDefinition is_contr A := {x : A & forall y : A, y == x}.\n\n(** If a space is contractible, then any two points in it are\n   connected by a path in a canonical way. *)\n\nLemma contr_path {A} (x y : A) : (is_contr A) -> (x == y).\nProof.\n  intros A x y.\n  intro H.\n  destruct H as (z,p).\n  path_via z.\nDefined.\n\n(** Similarly, any two parallel paths in a contractible space are homotopic.  *)\n\nLemma contr_path2 {A} {x y : A} (p q : x == y) : (is_contr A) -> (p == q).\nProof.\n  intros X x y p q.\n  intro ctr.\n  destruct ctr as (c, ret).\n  path_via (ret x @ !ret y).\n  moveleft_onright.\n  moveright_onleft.\n  apply opposite.\n  exact (! trans_is_concat_opp p (ret x)  @  map_dep ret p ).\n  moveright_onright.\n  moveleft_onleft.\n  exact (! trans_is_concat_opp q (ret x)  @  map_dep ret q).\nDefined.\n\n(** It follows that any space of paths in a contractible space is contractible. *)\n\nLemma contr_pathcontr {A} (x y : A) : is_contr A -> is_contr (x == y).\nProof.\n  intros A x y.\n  intro ctr.\n  exists (contr_path x y ctr).\n  intro p.\n  apply contr_path2.\n  assumption.\nDefined.\n\n(** The total space of any based path space is contractible. *)\n\nLemma pathspace_contr {X} (x:X) : is_contr (sigT (paths x)).\nProof.\n  intros X x.\n  exists (x ; idpath x).\n  intros [y p].\n  path_induction.\nDefined.\n\nLemma pathspace_contr' {X} (x:X) : is_contr { y:X  &  x == y }.\nProof.\n  intros X x.\n  exists (existT (fun y => x == y) x (idpath x)).\n  intros [y p].\n  path_induction.\nDefined.\n\nLemma pathspace_contr_opp {X} (x:X) : is_contr { y:X & y == x }.\nProof.\n  intros X x.\n  exists (existT (fun y => y == x) x (idpath x)).\n  intros [y p].\n  path_induction.\nDefined.\n\n(** The unit type is contractible. *)\n\nLemma unit_contr : is_contr unit.\nProof.\n  exists tt.\n  intro y.\n  induction y.\n  auto.\nDefined.\n\nHint Resolve unit_contr.\n", "meta": {"author": "jcmckeown", "repo": "HoTT-local", "sha": "6f6aec6dc86148181fd30f58f671e3007e1212b0", "save_path": "github-repos/coq/jcmckeown-HoTT-local", "path": "github-repos/coq/jcmckeown-HoTT-local/HoTT-local-6f6aec6dc86148181fd30f58f671e3007e1212b0/Coq/Contractible.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7349920692210786}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  plus lf2 (mult y lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj282_coqofml_CghL9c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7349621448505543}}
{"text": "Require Import RelationClasses.\nRequire Import OrderedType.\n\nModule OT_Equiv (O: OrderedType).\n\n  Theorem Equiv: Equivalence O.eq.\n  Proof.\n    intros.\n    eapply Build_Equivalence.\n    unfold Reflexive; apply O.eq_refl; auto.\n    unfold Symmetric; apply O.eq_sym; auto.\n    unfold Transitive; apply O.eq_trans; auto.\n  Qed.\n\n  Theorem Leibniz_eq: forall {x} {x'},\n    Logic.eq x x' -> O.eq x x'.\n  Proof.\n    intros; rewrite H in *; try apply O.eq_refl.\n  Qed.\n\nEnd OT_Equiv.", "meta": {"author": "doerrie", "repo": "confinement-proof", "sha": "db7bfb3522990d0820de64f13baa97b67e694c44", "save_path": "github-repos/coq/doerrie-confinement-proof", "path": "github-repos/coq/doerrie-confinement-proof/confinement-proof-db7bfb3522990d0820de64f13baa97b67e694c44/OrderedTypeEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7349621382199065}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) : natural := mult (Succ x) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj241_coqofml_5BOyqR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7348244819330475}}
{"text": "(******************************************************************************)\n(* Dr Daniel Kirk (c) 2021                                                    *)\n(******************************************************************************)\n(*         M1 \\oplus M2 == the lmodType given by pair_lmodType in ssralg.v    *)\n(*                         This is an implementation of the direct sum of two *)\n(*                         lmodTypes of the same ring.                        *)\n(* \\bigoplus_(f in L) I == the lmodType built up iteratively, where L : seq S *)\n(*                         for S : eqType and I : S -> lmodType R             *)\n(*                         \\bigoplus_(f in nil) I is lmodNull R whilst        *)\n(*                         \\bigoplus_(f in a::L) I is                         *)\n(*                               (I a) \\oplus (\\bigoplus_(f in L) I)          *)\n(*                         This is an implementation of the direct sum of an  *)\n(*                         arbitrary number of lmodTypes. Note that L is not  *)\n(*                         a list of lmodTypes but of some eqType S, which    *)\n(*                         are 'converted' to lmodTypes by                    *)\n(*                           I : S -> lmodType R.                             *)\n(*  \\bigoplus_(f : F) I == the lmodType equal to \\bigoplus_(f in (enum F)) I  *)\n(*        \\bigoplus_F I == equivalent to \\bigoplus_(f : F) I                  *)\n(*          \\bigoplus I == equivalent to \\bigoplus_(f : F) I                  *)\n(*                         where I : F -> lmodType R                          *)\n(******************************************************************************)\n(* The following constructions and lemmas relate to M \\oplus N,               *)\n(* the direct sum of the pair of lmodTypes M and N                            *)\n(******************************************************************************)\n(*  \\proj1^(M,N)   == the linear projection from M \\oplus N to M              *)\n(*  \\proj2^(M,N)   == the linear projection from M \\oplus N to N              *)\n(*  \\incl1^(M,N)   == the linear inclusion from M to M \\oplus N               *)\n(*  \\incl2^(M,N)   == the linear inclusion from N to M \\oplus N               *)\n(*  incl1_injective  == a proof that \\incl1^(M,N) is injective                *)\n(*  incl2_injective  == a proof that \\incl2^(M,N) is injective                *)\n(*  proj1_incl1K     == a proof of \\proj1^(M,N) (\\incl1^(M,N) x) = x          *)\n(*  proj2_incl2K     == a proof of \\proj2^(M,N) (\\incl2^(M,N) x) = x          *)\n(*  proj1_incl20     == a proof of \\proj1^(M,N) (\\incl2^(M,N) x) = 0          *)\n(*  proj2_incl10     == a proof of \\proj2^(M,N) (\\incl1^(M,N) x) = 0          *)\n(*  incl_proj12_sum  == a proof that any x : M \\oplus N can be written        *)\n(*                         x = \\incl1^(M,N) (\\proj1^(M,N) x)                  *)\n(*                              + \\incl2^(M,N) (\\proj2^(M,N) x)               *)\n(*  incl_proj12_idem == a proof that rewriting with incl_proj12_sum is        *)\n(*                         idempotent                                         *)\n(******************************************************************************)\n(* Let M N M1 M2 N1 N2 : lmodType R.                                          *)\n(* We define construction for combining linear maps so to be compatible       *)\n(* with direct sums                                                           *)\n(******************************************************************************)\n(* Let f1 : {linear M1 -> N1} and f2 : {linear M2 -> N2}                      *)\n(* \\diagmap(f,g) == the linear map : M1 \\oplus M2 -> N1 \\oplus N2             *)\n(*                         given by \\diagmap(f,g) (x,y) = (f x, g y)          *)\n(******************************************************************************)\n(* Let f1 : {linear M1 -> N} and f2 : {linear M2 -> N}                        *)\n(* \\rowmap(f,g) == the linear map : M1 \\oplus M2 -> N                         *)\n(*                         given by \\rowmap(f,g) (x,y) = f x + g y            *)\n(******************************************************************************)\n(* Let f1 : {linear M -> N1} and f2 : {linear M -> N2}                        *)\n(* \\colmap(f,g) == the linear map : M -> N1 \\oplus N2                         *)\n(*                         given by \\colmap(f,g) x = (f x, g x)               *)\n(******************************************************************************)\n(* The following constructions and lemmas relate to \\bigoplus_(f : F) I,      *)\n(* the direct sum of the lmodTypes given by (I : F -> lmodType R), and F is a *)\n(* finite index set (i.e. a finType)                                          *)\n(******************************************************************************)\n(*  \\proj_f^(I)    == the linear projection from \\bigoplus I to (I f),        *)\n(*                 for f : F. This function is surjective                     *)\n(*  \\incl_f^(I)    == the linear inclusion from (I f) to \\bigoplus I,         *)\n(*                 for f : F. This function is injective                      *)\n(*  incl_injective == a proof that \\incl_f^(I) is injective for f : F         *)\n(*  proj_inclK     == a proof that \\incl_f^(I) and \\proj_f^(I) cancel         *)\n(*  proj_incl0     == a proof that \\incl_f^(I) and \\proj_(f')^(I) equals zero *)\n(*                    if f != f'                                              *)\n(*  incl_proj_sum  == rewrites element x : \\bigoplus I as                     *)\n(*                        \\sum_(f : F)\\incl_f^(I) (\\proj_f^(I) x)             *)\n(*  incl_proj_idem       ==  a proof that rewriting with incl_proj_sum is     *)\n(*                         idempotent                                         *)\n(******************************************************************************)\n(* The following constructions are used to split and unsplit the direct sum   *)\n(* of two direct sums, that is (\\bigoplus J) \\oplus (\\bigoplus K).            *)\n(* Doing this involves:                                                       *)\n(*  1) three index sets F, G and H,                                           *)\n(*  2) a function GH_F : G + H -> F, connecting the sum of G and H to F       *)\n(*  3) a proof enumB : enum F = map F_GH (enum sum_finType G H) which         *)\n(* establishes that GH_F is an 'isomorphism' of G + H and F as finTypes,      *)\n(* and the notations J = I \\o GH_F \\o inl and K = I \\o GH_F \\o inr.           *)\n(******************************************************************************)\n(*     split == a linear function from \\bigoplus I to                         *)\n(*                    (\\bigoplus J) \\oplus (\\bigoplus K)                      *)\n(*   unsplit == a linear function from (\\bigoplus J) \\oplus (\\bigoplus K)     *)\n(*                    to \\bigoplus I                                          *)\n(*  splitK   == a proof that split and unsplit cancel                         *)\n(*  unsplitK == a proof that unsplit and split cancel                         *)\n(******************************************************************************)\n(* DirectSum_UniversalProperty == *)\n(******************************************************************************)\n\nFrom Coq.Init Require Import Notations Datatypes.\nRequire Import Coq.Program.Tactics.\nFrom Coq.Logic Require Import FunctionalExtensionality.\nFrom mathcomp Require Import ssreflect ssrfun seq.\nFrom mathcomp Require Import eqtype choice fintype bigop generic_quotient tuple finfun.\n\nSet Warnings \"-parsing\". (* Some weird bug in ssrbool throws out parsing warnings*)\n  From mathcomp Require Import ssrbool ssrnat.\nSet Warnings \"parsing\".\n\nSet Warnings \"-ambiguous-paths\". (* Some weird bug in ssralg throws out coercion warnings*)\n    From mathcomp Require Import ssralg.\nSet Warnings \"ambiguous-paths\".\n\nRequire Import Modules Linears.\nOpen Scope ring_scope.\nSet Implicit Arguments.\nUnset Strict Implicit.\nInclude GRing.\n\nOpen Scope  lmod_scope.\n\nSection Helpers.\n  Variable (R : ringType) (S : finType) (X : lmodType R) (f : S*S -> X).\n  Lemma big_pair_diag_eq :\n    \\sum_(i : S*S | i.2 == i.1)f i\n      = \\sum_(i : S) f (i, i).\n  Proof.\n    have : forall (i : S) (_ : true), f (i, i) = \\sum_(j : S) if (j == i) then f (i, j) else 0\n    by move=>i _;\n    rewrite -big_mkcond (big_pred1 i).\n    move=> H; rewrite (eq_bigr _ H); clear H.\n    by rewrite pair_bigA -big_mkcond\n    (eq_bigr (fun i => f (i.1,i.2)) _)=>/=;\n      [|move=>i _; destruct i=>/=].\n  Qed.\nEnd Helpers.\n\nReserved Notation \"\\bigoplus_ i F\"\n(at level 36, F at level 36, i at level 50,\n  right associativity,\n        format \"'[' \\bigoplus_ i '/ ' F ']'\").\n\nReserved Notation \"\\bigoplus F\"\n(at level 36, F at level 36,\n  right associativity,\n        format \"'[' \\bigoplus F ']'\").\n\nReserved Notation \"\\bigoplus_ ( i : t ) F\"\n(at level 36, F at level 36, i at level 50,\n        format \"'[' \\bigoplus_ ( i : t ) '/ ' F ']'\").\n\nReserved Notation \"\\bigoplus_ ( i < n ) F\"\n(at level 36, F at level 36, i, n at level 50,\n        format \"'[' \\bigoplus_ ( i < n ) F ']'\").\n\nReserved Notation \"\\bigoplus_ ( i 'in' A ) F\"\n(at level 36, F at level 36, i, A at level 50,\n        format \"'[' \\bigoplus_ ( i 'in' A ) '/ ' F ']'\").\n\nReserved Notation \"\\proj^( I )_ f \"\n(at level 36, f at level 36, I at level 36,\n  format \"'[' \\proj^( I )_ f ']'\").\n\nReserved Notation \"\\incl^( I )_ f \"\n(at level 36, f at level 36, I at level 36,\n  format \"'[' \\incl^( I )_ f ']'\").\n\nReserved Notation \"\\proj_ f ^( I ) \"\n(at level 36, f at level 36, I at level 36,\n  format \"'[' \\proj_ f '^(' I ) ']'\").\n\nReserved Notation \"\\incl_ f ^( I )\"\n(at level 36, f at level 36, I at level 36,\n  format \"'[' \\incl_ f '^(' I ) ']'\").\n\nModule dsLmod.\n  Module Pair.\n    Section Def.\n      Variable (R : ringType) (m1 m2 : lmodType R).\n\n      Section Injection.\n        Definition incl1_raw := fun x : m1 => (x,zero m2) : pair_lmodType m1 m2.\n        Definition incl2_raw := fun x : m2 => (zero m1, x) : pair_lmodType m1 m2.\n\n        Lemma incl1_lin : linear incl1_raw.\n        Proof. rewrite /(additive (pair^~0%R))/morphism_2=>r x y.\n          rewrite /scale/add=>/=.\n          by rewrite /add_pair/scale_pair scaler0 addr0. Qed.\n        Lemma incl2_lin : linear incl2_raw.\n        Proof. rewrite /(additive (pair^~0%R))/morphism_2=>r x y.\n          rewrite /scale/add=>/=.\n          by rewrite /add_pair/scale_pair scaler0 addr0. Qed.\n\n        Lemma incl1_injective : injective incl1_raw.\n        Proof. by move=>x y H; inversion H. Qed.\n        Lemma incl2_injective : injective incl2_raw.\n        Proof. by move=>x y H; inversion H. Qed.\n\n        Definition incl1 := Linear incl1_lin.\n        Definition incl2 := Linear incl2_lin.\n      End Injection.\n\n      Section Projection.\n        Definition proj1_raw := fun x : pair_lmodType m1 m2 => x.1.\n        Definition proj2_raw := fun x : pair_lmodType m1 m2 => x.2.\n\n        Lemma proj1_lin : linear proj1_raw.\n        Proof. by rewrite /morphism_2. Qed.\n        Lemma proj2_lin : linear proj2_raw.\n        Proof. by rewrite /morphism_2. Qed.\n\n        Definition proj1 := Linear proj1_lin.\n        Definition proj2 := Linear proj2_lin.\n\n        Lemma proj1_incl1K x : proj1 (incl1 x) = x. Proof. by []. Qed.\n        Lemma proj2_incl2K x : proj2 (incl2 x) = x. Proof. by []. Qed.\n        Lemma proj1_incl20 x : proj1 (incl2 x) = 0. Proof. by []. Qed.\n        Lemma proj2_incl10 x : proj2 (incl1 x) = 0. Proof. by []. Qed.\n      End Projection.\n\n      Lemma incl_proj_sum x : x = incl1 (proj1 x) + incl2 (proj2 x).\n      Proof. rewrite /(add _)/=/add_pair addr0 add0r;\n        by destruct x.\n      Qed.\n    End Def.\n\n    Section Morphisms.\n      Section MorphismsToDS.\n        Variable (R : ringType) (M N1 N2 : lmodType R)\n          (f1 : {linear M -> N1}) (f2 : {linear M -> N2}).\n\n        Definition to_ds_raw : M -> (pair_lmodType N1 N2)\n          := fun x => (incl1 _ _ (f1 x)) + (incl2  _ _ (f2 x)).\n\n        Lemma to_ds_lin : linear to_ds_raw.\n        Proof. rewrite/to_ds_raw=>r x y.\n        by rewrite !linearP addrACA scalerDr. Qed.\n        Definition to_ds : {linear M -> (pair_lmodType N1 N2)}\n          := Linear to_ds_lin.\n\n      End MorphismsToDS.\n\n      Section MorphismsFromDS.\n        Variable (R : ringType) (M1 M2 N : lmodType R)\n          (f1 : {linear M1 -> N}) (f2 : {linear M2 -> N}).\n\n        Definition from_ds_raw : (pair_lmodType M1 M2) -> N\n          := fun x => (f1 (proj1 _ _ x)) + (f2 (proj2  _ _ x)).\n\n        Lemma from_ds_lin : linear from_ds_raw.\n        Proof. rewrite/from_ds_raw=>r x y.\n        by rewrite !linearP addrACA scalerDr. Qed.\n\n        Definition from_ds : {linear (pair_lmodType M1 M2) -> N}\n          := Linear from_ds_lin.\n\n      End MorphismsFromDS.\n\n      Section MorphismsDiag.\n        Variable (R : ringType) (M1 M2 N1 N2 : lmodType R)\n          (f1 : {linear M1 -> N1}) (f2 : {linear M2 -> N2}).\n\n        Definition diag_raw : (pair_lmodType M1 M2) -> (pair_lmodType N1 N2)\n          := fun x => (incl1 _ _ (f1 (proj1 _ _ x))) + (incl2 _ _ (f2 (proj2  _ _ x))).\n\n        Lemma diag_lin : linear diag_raw.\n        Proof. rewrite/diag_raw=>r x y.\n        by rewrite !linearP addrACA scalerDr. Qed.\n\n        Definition diag : {linear (pair_lmodType M1 M2) -> (pair_lmodType N1 N2)}\n          := Linear diag_lin.\n      End MorphismsDiag.\n\n      Section MorphismsDiagCompositions.\n        Variable (R : ringType) (M1 M2 N1 N2 O1 O2 : lmodType R)\n          (f1 : {linear M1 -> N1}) (f2 : {linear M2 -> N2})\n          (g1 : {linear N1 -> O1}) (g2 : {linear N2 -> O2}).\n\n        Lemma diag_id : diag (\\id_M1) (\\id_M2) = \\id_(pair_lmodType M1 M2).\n        Proof.\n          rewrite linear_eq.\n          apply functional_extensionality=>x/=.\n          by rewrite /diag_raw /linID.map -!(lock) -(incl_proj_sum x).\n        Qed.\n\n        Lemma diag_comp : (diag g1 g2) \\oLin (diag f1 f2) = diag (g1 \\oLin f1) (g2 \\oLin f2).\n        Proof.\n          rewrite linear_eq.\n          apply functional_extensionality=>x.\n          rewrite -!linCompChain=>/=.\n          rewrite /diag_raw -!linCompChain=>/=.\n          by rewrite addr0 add0r.\n        Qed.\n      End MorphismsDiagCompositions.\n    End Morphisms.\n\n    Module Exports.\n\n      Notation lmodDSPairType := pair_lmodType.\n      Infix \"\\oplus\" := (pair_lmodType) (at level 35).\n      Notation \"\\diagmap( f , g )\" := (diag f g) (at level 35).\n      Notation \"\\rowmap( f , g )\" := (from_ds f g) (at level 35).\n      Notation \"\\colmap( f , g )\" := (to_ds f g) (at level 35).\n    End Exports.\n  End Pair.\n  Export Pair.Exports.\n\n\n\n  Module Seq.\n    Section Ring.\n      Variable (R : ringType).\n      Section Environment.\n        Variable (T : eqType) (I : T -> lmodType R).\n\n        Section Def.\n          Definition Nth := (fun L n => match (seq.nth None (map Some L) n) with\n          |Some t => I t\n          |None => lmodZero.type R\n          end).\n\n          Fixpoint DS (L : seq T) : lmodType R := match L with\n            |nil => lmodZero.type R\n            |a'::L' => (I a') \\oplus (DS L')\n          end.\n        End Def.\n\n        Section Injection.\n        Fixpoint incl_raw (L : seq T) (n : nat) {struct n} :\n          Nth L n -> DS L\n        := match L as LL return Nth LL n -> DS LL with\n          |nil => fun _ => tt\n          |a::L' => match n as nn return Nth (a::L') nn -> DS (a::L') with\n            |0    => fun x => @Pair.incl1 R (I a) (DS L') x\n            |S n' => fun x => @Pair.incl2 R (I a) (DS L') ((@incl_raw L' n') x)\n            end\n          end.\n\n          Lemma incl_lin (L : seq T) (n : nat) : linear (@incl_raw L n).\n          Proof. move: n; induction L=>//=. {\n            induction n=>//=. }\n            move : L IHL; induction n=>//= r x y.\n            apply (linearP (@Pair.incl1 _ (I a) (DS L))).\n            by rewrite -(linearP (@Pair.incl2 _ (I a) (DS L))) (IHL n).\n          Qed.\n\n          Lemma incl_injective\n            (L : seq T) (n : nat) : injective (@incl_raw L n).\n          Proof. move: n; induction L=>//=.\n          { induction n; by move=> x y; destruct x, y. }\n            move: L IHL.\n            induction n=>/= x y H.\n            apply (@Pair.incl1_injective R _ _ x y H).\n            apply (IHL n x y (@Pair.incl2_injective R _ _ (@incl_raw L n x) (@incl_raw L n y) H)).\n          Qed.\n        End Injection.\n        Definition incl (L : seq T) (n : nat)\n          := Linear (@incl_lin L n).\n\n        Section Projection.\n          Fixpoint proj_raw (L : seq T) (n : nat) {struct n} :\n          DS L -> Nth L n\n        := match L as LL return DS LL -> Nth LL n with\n          |nil => match n as nn return lmodZero.type R -> Nth nil nn with\n            |0    => fun _ => tt\n            |S n' => fun _ => tt\n            end\n          |a::L' => match n as nn return DS (a::L') -> Nth (a::L') nn with\n            |0    => fun x => @Pair.proj1 R (I a) (DS L') x\n            |S n' => fun x => (@proj_raw L' n') (@Pair.proj2 R (I a) (DS L') x)\n            end\n          end.\n          \n          Lemma proj_lin (L : seq T) (n : nat) : linear (@proj_raw L n).\n          Proof. move: n; induction L=>//. { induction n=>//=. }\n            move: L IHL; induction n=>//; move=> r x y.\n            by rewrite -(IHL n).\n          Qed.\n        End Projection.\n        Definition proj (L : seq T) (n : nat)\n          := Linear (@proj_lin L n).\n\n        Section Results.\n          Section Lemmas.\n            Variable (L : seq T).    \n            Lemma nth_cons {a d} {n : nat} : seq.nth d (a::L) (S n) = seq.nth d L n.\n            Proof. by induction n. Qed.\n        \n            Lemma incl_cons n a x : @incl (a::L) (S n) x = Pair.incl2 (I a) _ (@incl L n x).\n            Proof. by []. Qed.\n        \n            Lemma proj_cons n a x : @proj (a::L) (S n) (Pair.incl2 (I a) _ x) = @proj L n x.\n            Proof. by []. Qed.\n\n            Lemma proj_incl_cons (n n' : nat) a x\n            : @proj (a::L) (n.+1) (@incl (a::L) (n'.+1) x) = @proj L n (@incl L n' x).\n            Proof. by []. Qed.\n          End Lemmas.\n          Variable (L : seq T).\n\n          (* The following two lemmas are used for cancellation *)\n          Lemma proj_inclK_ofsize (n : 'I_(size L)) x : @proj L (nat_of_ord n) (@incl L (nat_of_ord n) x) = x.\n          Proof.\n            induction L; destruct n as [n N]=>//.\n            induction n=>//; move:x; simpl (Ordinal N : nat)=>x.\n            rewrite -ltn_predRL in N.\n            by rewrite proj_incl_cons (IHl (Ordinal N)).\n          Qed.\n\n          Lemma proj_incl0_ofsize (n n' : 'I_(size L)) x : (nat_of_ord n) != n' -> @proj L n (@incl L n' x) = 0.\n          Proof.\n            induction L; destruct n as [n N], n' as [n' N']=>//.\n            simpl in x, IHl, N, N'=>H.\n            induction n; induction n'=>//.\n              by (have: proj l n 0 = 0 by rewrite linear0).\n            simpl; clear IHn' IHn; move: N' N H;\n            rewrite /=eqSS !ltnS=>N' N H.\n            by apply (IHl (Ordinal N) (Ordinal N') x H).\n          Qed.\n          \n          (* The following two lemmas are the same as above but more versitile,\n          in that they don't require the index to be an ordinal of size L, simply\n          that they are naturals less than size L *)\n          Lemma proj_inclK (n : nat) x (M : n < size L) : @proj L n (@incl L n x) = x.\n          Proof. apply (@proj_inclK_ofsize (Ordinal M)). Qed.\n      \n          Lemma proj_incl0 m1 m2 (n : 'I_m1) (n' : 'I_m2) x (M1 : m1 <= (size L)) (M2 : m2 <= (size L))\n            : (nat_of_ord n) != n' -> @proj L n (@incl L n' x) = 0.\n          Proof. apply (@proj_incl0_ofsize (widen_ord M1 n) (widen_ord M2 n')). Qed.\n\n          (* this lemma expresses any element as a sum of projections *)\n          Lemma incl_proj_sum x : x = \\sum_(n < size L) incl L (nat_of_ord n) (@proj L (nat_of_ord n) x).\n          Proof.\n            induction L.\n            by rewrite /size big_ord0; case x.\n            destruct x as [Ia DSl].\n            by rewrite big_ord_recl {1}(IHl DSl)\n            (Pair.incl_proj_sum (Ia, _)) linear_sum.\n          Qed.\n        End Results.\n\n        (* Given a direct sum indexed by a seq, we define a function to reform\n        the direct sum into the direct sum of two smaller direct sums. *)\n        Section Operations.\n          Variable (L1 L2 : seq T).\n          (*Tr = truncate, Ap = Append, R = right, L = left*)\n          Section L1.\n            Variable (n : 'I_(size L1)).\n            Lemma catTrR_eq : (Nth (L1 ++ L2) n) = (Nth L1 n).\n            Proof. destruct n as [n' H].\n            by rewrite/Nth map_cat nth_cat size_map H. Qed.\n\n            Definition catTrR : (Nth (L1 ++ L2) n) -> (Nth L1 n).\n            Proof. by rewrite catTrR_eq. Defined.\n\n            Definition catApR : (Nth L1 n) -> (Nth (L1 ++ L2) n).\n            Proof. by rewrite catTrR_eq. Defined.\n\n            Lemma catTrApR_lin : linear catTrR /\\ linear catApR.\n            Proof. split; rewrite/catTrR/catApR=>r x y; by destruct(catTrR_eq). Qed.\n\n            Lemma catApTrRK : cancel catTrR catApR /\\ cancel catApR catTrR.\n            Proof. split; rewrite/catApR/catTrR=>x; by destruct(catTrR_eq). Qed.\n\n            Definition catifyL1 : linIsomType (Nth (L1 ++ L2) n) (Nth L1 n)\n            := linIsomBuildPack catTrApR_lin catApTrRK.\n          End L1.\n          Section L2.\n            Variable (n : 'I_(size L2)).\n        \n            Lemma catTrL_eq : (Nth (L1 ++ L2) (rshift (size L1) n)) = (Nth L2 n).\n            Proof. by simpl; rewrite/Nth map_cat nth_cat size_map\n            -{2}(addn0 (size L1)) ltn_add2l addnC addnK. Qed.\n\n            Definition catTrL : (Nth (L1 ++ L2) (rshift (size L1) n)) -> (Nth L2 n).\n            Proof.  by rewrite catTrL_eq. Defined.\n\n            Definition catApL : (Nth L2 n) -> (Nth (L1 ++ L2) (rshift (size L1) n)).\n            Proof. by rewrite catTrL_eq. Defined.\n\n            Lemma catTrApL_lin : linear catTrL /\\ linear catApL.\n            Proof. split; rewrite/catTrL/catApL=>r x y;by destruct (catTrL_eq). Qed.\n            \n            Lemma catApTrLK : cancel catTrL catApL /\\ cancel catApL catTrL.\n            Proof. split; rewrite/catApL/catTrL=>x; by destruct(catTrL_eq). Qed.\n\n            Definition catifyL2 : linIsomType (Nth (L1 ++ L2) (rshift (size L1) n)) (Nth L2 n)\n            := linIsomBuildPack catTrApL_lin catApTrLK.\n          End L2.\n\n          Definition split_raw : DS (L1 ++ L2) -> DS L1 \\oplus DS L2\n            := fun x =>\n            (\\sum_(n < size L1)(incl L1 n \\oLin catifyL1 n \\oLin proj (L1 ++ L2) n ) x,\n            \\sum_(n < size L2)(incl L2 n \\oLin catifyL2 n \\oLin proj (L1 ++ L2) (rshift (size L1) n)) x).\n\n          Definition unsplit_raw : DS L1 \\oplus DS L2 -> DS (L1 ++ L2)\n          := fun x =>\n            \\sum_(n < size L1)((incl (L1 ++ L2) n                     \\oLin inv(catifyL1 n) \\oLin proj L1 n) x.1) +\n            \\sum_(n < size L2)((incl (L1 ++ L2) (rshift (size L1) n)  \\oLin inv(catifyL2 n) \\oLin proj L2 n) x.2).\n\n          Lemma split_lin : linear split_raw.\n          Proof. rewrite/split_raw=>r x y/=.\n            by rewrite (rwP eqP)/eq_op -(rwP andP) -!(rwP eqP)=>/=;\n            rewrite !scaler_sumr -!big_split !(eq_bigr _ (fun i _ => linearP _ _ _ _)).\n          Qed.\n\n          Lemma unsplit_lin : linear unsplit_raw.\n          Proof. rewrite/unsplit_raw=>r x y/=.\n            by rewrite !(eq_bigr _ (fun i _ => linearP _ _ _ _)) !big_split=>/=;\n            rewrite -!scaler_sumr scalerDr !addrA (addrC _ (r *: _)) !addrA (addrC (r *: _) (r *: _)).\n          Qed.\n\n          Definition split := Linear split_lin.\n          Definition unsplit := Linear unsplit_lin.\n\n          Lemma unsplitK : cancel split unsplit.\n          Proof. simpl; rewrite /unsplit_raw/split_raw=>x.\n            under eq_bigr do rewrite linear_sum.\n            under eq_bigr do under eq_bigr do rewrite -!linCompChain.\n            under[\\sum_(_ < size L2) _] eq_bigr do rewrite linear_sum.\n            under[\\sum_(_ < size L2) _] eq_bigr do under eq_bigr do rewrite -!linCompChain.\n            rewrite!pair_bigA.\n            rewrite (eq_bigr (fun p : 'I_(size L1)*'I_(size L1)\n            => if p.2 == p.1\n              then incl _ p.1 (proj _ p.1 x)\n              else 0 ) _).\n            rewrite (eq_bigr (fun p : 'I_(size L2)*'I_(size L2)\n              => if p.2 == p.1\n              then incl _ (rshift (size L1) p.2) (proj _ (rshift (size L1) p.2) x)\n              else 0 ) _).\n            by rewrite -!big_mkcond !big_pair_diag_eq {3}(@incl_proj_sum _ x)\n            size_cat (@big_split_ord _ _ _ (size L1) (size L2)).\n            by move=>p _; case (p.2 == p.1) as []eqn:E;\n            [move/eqP in E; rewrite E proj_inclK_ofsize (isomlK (catifyL2 p.1)) |\n            rewrite proj_incl0_ofsize; [rewrite !linear0|\n              rewrite eq_sym/eq_op in E; simpl in E; rewrite E]].\n            by move=>p _; case (p.2 == p.1) as []eqn:E;\n            [move/eqP in E; rewrite E proj_inclK_ofsize (isomlK (catifyL1 p.1))|\n            rewrite proj_incl0_ofsize; [rewrite !linear0|\n              rewrite eq_sym/eq_op in E; simpl in E; rewrite E]].\n          Qed.\n\n          Lemma splitK : cancel unsplit split.\n          Proof. simpl; rewrite /unsplit_raw/split_raw=>x.\n          under eq_bigr do rewrite !raddfD.\n          under[\\sum_(n < _) ((_ \\oLin _ \\oLin proj _ (rshift _ n)) _)]\n            eq_bigr do rewrite !raddfD.\n\n          rewrite !big_split !(eq_bigr _ (fun i _ => linear_sum _ _ _ _)) !pair_bigA.\n          rewrite (eq_bigr (fun p : 'I_(size L1)*'I_(size L1)\n          => if(p.2 == p.1)\n            then incl L1 p.1 (proj L1 p.1 x.1)\n            else 0) _).\n          rewrite (eq_bigr (fun p : 'I_(size L2)*'I_(size L2)\n          => if(p.2 == p.1)\n            then incl L2 p.2 (proj L2 p.2 x.2)\n            else 0) _).\n          {\n            destruct x as [x1 x2];\n            rewrite -!big_mkcond !big_pair_diag_eq\n            (eq_bigr (fun p : 'I_(size L1) => incl _ p (proj _ p x1)) _);[|by move].\n            rewrite (eq_bigr (fun p : 'I_(size L2) => incl _ p (proj _ p x2)) _); [| by []].\n            rewrite {4}(incl_proj_sum x1) {4}(incl_proj_sum x2) (rwP eqP) /eq_op -(rwP andP).\n            split; rewrite -subr_eq0.\n\n            rewrite {1}addrC addrA addNr add0r (eq_bigr (fun _ => 0) _).\n            rewrite big_const cardE /iter enumT;\n            induction(Finite.enum _)=>//=; by rewrite add0r.\n\n            move =>[[p1 H1] [p2 H2]] _;\n            rewrite -!linCompChain proj_incl0;[by rewrite !linear0 |by rewrite size_cat leq_addr|by rewrite size_cat|];\n            rewrite -(rwP negP)/not -(rwP eqP)=>/=N;\n            by rewrite N -{2}(addn0 (size L1)) ltn_add2l in H1.\n\n            rewrite -addrA addrN addr0 (eq_bigr (fun _ => 0) _).\n            rewrite big_const cardE /iter enumT;\n            induction(Finite.enum _)=>//=; by rewrite add0r.\n\n            move =>[[p1 H1] [p2 H2]] _;\n            rewrite -!linCompChain proj_incl0;[by rewrite !linear0 |by rewrite size_cat|by rewrite size_cat leq_addr|];\n            rewrite -(rwP negP)/not -(rwP eqP)=>/=N.\n            by rewrite -N -{2}(addn0 (size L1)) ltn_add2l in H2.\n          }\n          move=>p _; case(p.2 == p.1) as []eqn:E.\n          move/eqP in E; rewrite E -!linCompChain.\n          rewrite proj_inclK; [by rewrite isomKl|].\n          destruct p as [[p1 H1] [p2 H2]].\n          by rewrite size_cat ltn_add2l.\n          rewrite -!linCompChain proj_incl0; [by rewrite !linear0|by rewrite size_cat|by rewrite size_cat|].\n          rewrite /eq_op in E; simpl in E.\n          by rewrite /rshift eqn_add2l eq_sym E.\n\n          move=>p _; case(p.2 == p.1) as []eqn:E.\n          move/eqP in E; rewrite -E -!linCompChain.\n          rewrite proj_inclK; [by rewrite isomKl|].\n          destruct p as [[p1 H1] [p2 H2]]=>/=.\n          by rewrite size_cat addnC (ltn_addl _ H2).\n          rewrite -!linCompChain proj_incl0; [by rewrite !linear0|by rewrite size_cat leq_addr|by rewrite size_cat leq_addr|].\n          rewrite /eq_op in E; simpl in E.\n          by rewrite eq_sym E.\n          Qed.\n        End Operations.\n      End Environment.\n      \n      Section Hom.\n        Variable (S T : eqType) (I : T -> lmodType R) (T_S : S -> T).\n\n        Fixpoint homify_raw (L : seq S) : DS (I \\o T_S) L -> DS I (map T_S L)\n          := match L with\n          |nil => id\n          |a::l => fun x => (x.1 , homify_raw x.2)\n          end.\n        Fixpoint unhomify_raw (L : seq S) : DS I (map T_S L) -> DS (I \\o T_S) L\n          := match L with\n          |nil => id\n          |a::l => fun x => (x.1 , unhomify_raw x.2)\n          end.\n        \n        Variable (L : seq S).\n        Lemma homify_lin : linear (@homify_raw L) /\\ linear (@unhomify_raw L).\n        Proof. split; induction L=>//=r x y;\n          by rewrite IHl/homify_raw/unhomify_raw.\n        Qed.\n        Lemma homifyK : cancel (@homify_raw L) (@unhomify_raw L) /\\ cancel (@unhomify_raw L) (@homify_raw L).\n        Proof. split; induction L=>//=x; destruct x;\n          by rewrite IHl.\n        Qed.\n        Definition homify := linIsomBuildPack homify_lin homifyK.\n      End Hom.\n\n      Section Bijection.\n        Variable (S T : eqType) (I : T -> lmodType R)\n            (T_S : S -> T) (S_T : T -> S) (Inj : cancel S_T T_S).\n\n        Variable (L : seq T).\n        Definition mapify_raw : DS I (map T_S (map S_T L)) -> DS I L.\n        by rewrite mapK. Defined.      \n        Definition unmapify_raw : DS I L -> DS I (map T_S (map S_T L)).\n        by rewrite mapK. Defined.\n        Lemma mapify_lin : linear mapify_raw /\\ linear unmapify_raw.\n        Proof. split; by rewrite/mapify_raw/unmapify_raw; destruct mapK. Qed.\n        Lemma mapifyK : cancel mapify_raw unmapify_raw /\\ cancel unmapify_raw mapify_raw.\n        Proof. split; by rewrite/mapify_raw/unmapify_raw; destruct mapK. Qed.\n        Definition mapify := linIsomBuildPack mapify_lin mapifyK.\n\n        Definition bijectify := linIsomConcat (homify I T_S (map S_T L)) mapify.\n      End Bijection.\n    End Ring.\n  End Seq.\n\n\n\n\n\n\n\n\n\n  Section General.\n    Variable (R : ringType).\n    Section Def.\n      Variable (F : finType) (I : F -> lmodType R).\n\n      Definition DS : lmodType R := Seq.DS I (enum F).\n\n      Section Components.\n        Variable (f : F).\n\n        Lemma cardElt : nat_of_ord (enum_rank f) < size (enum F).\n        Proof. rewrite -cardE; apply ltn_ord. Qed.\n\n        Definition Ord := Ordinal cardElt.\n        Definition Nth := Seq.Nth I (enum F) Ord.\n\n        Section TypeConversion.\n          Lemma Nth_If_eq : Nth = I f.\n          Proof. by rewrite /Nth/Seq.Nth -codomE nth_codom enum_rankK. Qed.\n          Lemma If_Nth_eq : I f = Nth.\n          Proof. by rewrite Nth_If_eq. Qed.\n\n          Definition finify_raw : Nth -> I f := (fun fn : Nth\n            -> Nth => eq_rect_r (fun M : lmodType R => Nth -> M)\n              fn If_Nth_eq) id.\n          Definition unfinify_raw : I f -> Nth := (fun fn : Nth\n            -> Nth => eq_rect_r (fun M : lmodType R => M -> Nth)\n              fn If_Nth_eq) id.\n          Lemma finify_lin : linear finify_raw /\\ linear unfinify_raw.\n          Proof. split; by rewrite /finify_raw/unfinify_raw=>r x y; destruct If_Nth_eq. Qed.\n          Lemma finifyK : cancel finify_raw unfinify_raw /\\ cancel unfinify_raw finify_raw.\n          Proof. split; by rewrite/finify_raw/unfinify_raw; destruct If_Nth_eq. Qed.\n\n          Definition finify := linIsomBuildPack finify_lin finifyK.\n\n        End TypeConversion.\n      \n        Section Projection.\n          Definition proj_raw : DS -> I f\n          := finify \\oLin (@Seq.proj R F I (enum F) Ord).\n          \n          Lemma proj_lin : linear proj_raw.\n          Proof. rewrite/proj_raw=> r x y; by rewrite !linearPZ. Qed.\n\n          Definition proj : {linear DS -> I f} := Linear proj_lin.\n        End Projection.\n        \n        Section Injection.\n          Definition incl_raw : I f -> DS\n          := (@Seq.incl R F I (enum F) Ord) \\oLin inv(finify).\n\n          Lemma incl_lin : linear incl_raw.\n          Proof. rewrite/incl_raw=> r x y; by rewrite !linearPZ. Qed.\n\n          Lemma incl_injective : injective incl_raw.\n          Proof. rewrite/incl_raw=>x y; rewrite -!linCompChain=>H.\n            apply Seq.incl_injective in H.\n            apply (congr1 finify) in H.\n            by rewrite !isomKl in H.\n          Qed.\n\n          Definition incl : {linear I f -> DS} := Linear incl_lin.\n        End Injection.\n      End Components.\n\n      Section Results.\n        Lemma proj_inclK (f : F) x : proj f (incl f x) = x.\n        Proof. by rewrite /proj_raw/incl_raw -!linCompChain\n          Seq.proj_inclK; [rewrite -{2}(isomKf (finify f) x) | apply cardElt].\n        Qed.\n\n        Lemma proj_incl0 (f f' : F) x : f != f' -> @proj f (@incl f' x) = 0.\n        Proof.\n          rewrite/proj_raw/incl_raw-!linCompChain.\n          case(enum_rank f != enum_rank f') as []eqn:E.\n          by rewrite (@Seq.proj_incl0_ofsize _ _ _ _ (Ord f) (Ord f') _ E) linear0.\n          move/negbFE/eqP/enum_rank_inj/eqP in E.\n          by rewrite E.\n        Qed.\n\n        Lemma incl_proj_sum x : x = \\sum_(f : F) incl f (proj f x).\n        Proof.\n          rewrite big_enum_val {1}(Seq.incl_proj_sum x) -!big_enum -cardT.\n          refine (eq_bigr _ _).\n          move=> i _; rewrite /incl_raw/proj_raw/Seq.incl/Seq.proj\n          -!linCompChain (isomlK (finify _))/Ord=>/=.\n          by rewrite enum_valK.\n        Qed.\n\n        Lemma inj_proj_idem x : \\sum_(f : F) incl f (proj f (\\sum_(f : F) incl f (proj f x))) = \\sum_(f : F) incl f (proj f x).\n        Proof. by rewrite -incl_proj_sum. Qed.\n      End Results.\n    End Def.\n\n    Section Operations.\n      Variable (F G : finType) (I : F + G -> lmodType R).\n      Definition J : F -> lmodType R := I \\o inl.\n      Definition K : G -> lmodType R := I \\o inr.\n\n      Lemma sumify_eq : (enum (sum_finType F G)) = ((map inl (enum F)) ++ (map inr (enum G))).\n      Proof. by rewrite/DS enumT(unlock _)/=/sum_enum -!enumT. Qed.\n\n      Definition sumify_raw : DS I -> Seq.DS I ((map inl (enum F)) ++ (map inr (enum G))).\n      by rewrite /DS sumify_eq. Defined.\n      Definition unsumify_raw : Seq.DS I ((map inl (enum F)) ++ (map inr (enum G))) -> DS I.\n      by rewrite /DS sumify_eq. Defined.\n      \n      Lemma sumify_lin : linear sumify_raw /\\ linear unsumify_raw.\n        Proof. split; rewrite/sumify_raw/unsumify_raw=>r x y;\n        by destruct sumify_eq. Qed.\n      Lemma sumifyK : cancel sumify_raw unsumify_raw /\\ cancel unsumify_raw sumify_raw.\n        Proof. split; rewrite/sumify_raw/unsumify_raw=>x;\n        by destruct sumify_eq. Qed.\n\t    Definition sumify := linIsomBuildPack sumify_lin sumifyK.\n      \n      Definition split : DS I -> DS J \\oplus DS K\n       := \\diagmap(inv(Seq.homify _ inl _), inv(Seq.homify _ inr _))\n\t\t\t      \\oLin (Seq.split I _ _) \\oLin sumify.\n\n      Definition unsplit : {linear DS J \\oplus DS K -> DS I}\n      := inv(sumify) \\oLin (Seq.unsplit I _ _) \\oLin\n          \\diagmap(Seq.homify _ inl _, Seq.homify _ inr _).\n\n      Lemma unsplitK : cancel split unsplit.\n      Proof. rewrite /unsplit/split=>x.\n        by rewrite -!linCompChain (linCompChain (\\diagmap(_,_)) (\\diagmap(_,_)))\n        Pair.diag_comp !linIsom.concatKl Pair.diag_id -linIDChain\n        Seq.unsplitK (isomlK sumify).\n      Qed.\n\n      Lemma splitK : cancel unsplit split.\n      Proof. rewrite /unsplit/split=>x.\n        by rewrite -!linCompChain isomKl Seq.splitK\n        (linCompChain (\\diagmap(_,_)) (\\diagmap(_,_)))\n        Pair.diag_comp !linIsom.concatlK Pair.diag_id -linIDChain.\n      Qed.\n\n    End Operations.\n\n  End General.\n  Section Results.\n    Variable (R : ringType) (M N : lmodType R) (m : M) (n : N).\n    Lemma pair_eq_seq (F G : eqType) (f : F -> M) (g : G -> N)\n      (L1 : seq F) (L2 : seq G) :\n      \\sum_(i <- L1) (f i, 0)%R + \\sum_(i <- L2) (0, g i) == (m,n)\n      <-> (\\sum_(i <- L1) f i == m /\\ \\sum_(i <- L2) g i == n).\n    Proof. split; [move=> H|move=> [H1 H2]]. {\n        have:(\\sum_(i <- L1) (dsLmod.Pair.incl1 M N (f i)) + \\sum_(i <- L2) (dsLmod.Pair.incl2 M N (g i)) == (m, n))\n          by apply H .\n        rewrite -!raddf_sum/Pair.incl1/Pair.incl2/(@add _)/=\n        /add_pair add0r addr0 -(rwP eqP)=>H0;\n        by inversion H0.\n      }\n      move: H1 H2; rewrite -!(rwP eqP)=>H1 H2.\n      have:(\\sum_(i <- L1) (Pair.incl1 _ _  (f i)) == (m, @zero N))\n        by rewrite -raddf_sum/Pair.incl1 H1.\n      have:(\\sum_(i <- L2) (Pair.incl2 _ _ (g i)) == (@zero M, n))\n        by rewrite -raddf_sum/Pair.incl2 H2=>/=.\n      rewrite -!(rwP eqP)=>H H0.\n      have:(\\sum_(i <- L1) (dsLmod.Pair.incl1 _ _ (f i)) + \\sum_(i <- L2) (dsLmod.Pair.incl2 _ _ (g i)) == (m, n))\n        by rewrite H H0 {1}/(@add (pair_lmodType M N))/=\n        /add_pair add0r addr0.\n      by rewrite /Pair.incl1/Pair.incl2 -(rwP eqP).\n    Qed.\n\n    Lemma pair_eq (F G : finType) (f : F -> M) (g : G -> N) :\n      \\sum_i (f i, 0)%R + \\sum_i (0, g i) == (m,n)\n      <-> (\\sum_i f i == m /\\ \\sum_i g i == n).\n    Proof. by rewrite -big_enum/=pair_eq_seq big_enum/=. Qed.\n  End Results.\nEnd dsLmod.\n\n\n\n\nExport dsLmod.Pair.Exports.\nNotation \"\\bigoplus_ i F\" := (dsLmod.DS (fun i => F i)) : lmod_scope.\nNotation \"\\bigoplus F\" := (dsLmod.DS F) : lmod_scope.\nNotation \"\\bigoplus_ ( i : t ) F\" := (dsLmod.DS (fun i : t => F i)) : lmod_scope.\nNotation \"\\bigoplus_ ( i 'in' A ) F\" := (dsLmod.Seq.DS (filter F (fun i => i \\in A))) : lmod_scope.\nNotation \"\\proj^( I )_ f \" := (dsLmod.proj I f ) : lmod_scope.\nNotation \"\\incl^( I )_ f \" := (dsLmod.incl I f ) : lmod_scope.\nNotation \"\\proj_ f ^( I )\" := (dsLmod.proj I f ) : lmod_scope.\nNotation \"\\incl_ f ^( I )\" := (dsLmod.incl I f ) : lmod_scope.\n\nTheorem DirectSum_UniversalProperty (R : ringType) (F : finType)\n  (I : F -> (lmodType R))\n    : forall (f : forall i : F, {linear \\bigoplus I -> (I i)}), \n      exists (g : forall i : F, {linear (I i) -> (I i)}),\n        forall i : F, f i \\oLin \\incl_i^(I) = g i.\nProof. move=> f.\n  by refine(ex_intro _ (fun i => f i \\oLin \\incl_i^(I)) _ ).\nQed.\n\nClose Scope  lmod_scope.\nClose Scope  ring_scope.", "meta": {"author": "Modularius", "repo": "MathcompFreeModules", "sha": "5731747c5bcbafe914687d44e74f112632f07ec7", "save_path": "github-repos/coq/Modularius-MathcompFreeModules", "path": "github-repos/coq/Modularius-MathcompFreeModules/MathcompFreeModules-5731747c5bcbafe914687d44e74f112632f07ec7/theories/Modules/DirectSum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7348244736038371}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import bedrock2.Semantics.\nRequire Import coqutil.Word.Interface.\nRequire Import Crypto.Bedrock.Field.Common.Types.\nRequire Import Crypto.Arithmetic.WordByWordMontgomery.\nRequire Import Coq.Lists.List.\nRequire Import Implementations.SOS.SOSReduction.\n\nSection word.\n\nContext {p : Types.parameters}\n        {ok : Types.ok}.\n        Existing Instance semantics_ok.\n\nLocal Notation ws := word_size_in_bytes.\n\nNotation N aw := (word.add (word.of_Z ws) aw).\nLocal Coercion Z.of_nat : nat >-> Z.\n\nAdd Ring Wring : Word.Properties.word.ring_theory.\n\nLemma word_add_0' : forall (a : Semantics.word), word.add a (word.of_Z (0)) = a.\nProof. \n  intros. ring.\nQed.\n\nLemma word_add_0 : forall (a : Semantics.word), word.add a (word.of_Z (0 * ws)) = a.\nProof.\n  intros. assert (0 = 0 * ws) by auto. rewrite <- H. ring.\nQed.\n\nLemma word_add_assoc (a : Semantics.word) b c : word.add a (word.add b c) = word.add (word.add a b) c.\nProof.\n    ring.\nQed.\n\nLemma word_add_comm (a b : Semantics.word) : word.add a b = word.add b a.\nProof.\n    ring.\nQed.\n\nLemma next_word' (a : Semantics.word) n : word.add a (word.of_Z (n)) = N (word.add a (word.of_Z (n - ws))).\nProof.\n    ring_simplify.\n    rewrite <- word_add_assoc.\n    rewrite <- Properties.word.ring_morph_add. assert (ws + (n - ws)= n) by auto with zarith.\n    rewrite H. auto.\nQed.\n\nEnd word.\n\n", "meta": {"author": "AU-COBRA", "repo": "AUCurves", "sha": "ea864da1b1e78a86fda16818a9366a96da83cb63", "save_path": "github-repos/coq/AU-COBRA-AUCurves", "path": "github-repos/coq/AU-COBRA-AUCurves/AUCurves-ea864da1b1e78a86fda16818a9366a96da83cb63/src/Bedrock/Util/Word.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8031737916455819, "lm_q1q2_score": 0.7348244727291243}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Import ZAxioms ZMulOrder ZSgnAbs NZDiv.\n\n(** * Euclidean Division for integers, Euclid convention\n\n    We use here the \"usual\" formulation of the Euclid Theorem\n    [forall a b, b<>0 -> exists r q, a = b*q+r /\\ 0 <= r < |b| ]\n\n    The outcome of the modulo function is hence always positive.\n    This corresponds to convention \"E\" in the following paper:\n\n    R. Boute, \"The Euclidean definition of the functions div and mod\",\n    ACM Transactions on Programming Languages and Systems,\n    Vol. 14, No.2, pp. 127-144, April 1992.\n\n    See files [ZDivTrunc] and [ZDivFloor] for others conventions.\n\n    We simply extend NZDiv with a bound for modulo that holds\n    regardless of the sign of a and b. This new specification\n    subsume mod_bound_pos, which nonetheless stays there for\n    subtyping. Note also that ZAxiomSig now already contain\n    a div and a modulo (that follow the Floor convention).\n    We just ignore them here.\n*)\n\nModule Type EuclidSpec (Import A : ZAxiomsSig')(Import B : DivMod A).\n Axiom mod_always_pos : forall a b, b ~= 0 -> 0 <= B.modulo a b < abs b.\nEnd EuclidSpec.\n\nModule Type ZEuclid (Z:ZAxiomsSig) := NZDiv.NZDiv Z <+ EuclidSpec Z.\n\nModule ZEuclidProp\n (Import A : ZAxiomsSig')\n (Import B : ZMulOrderProp A)\n (Import C : ZSgnAbsProp A B)\n (Import D : ZEuclid A).\n\n (** We put notations in a scope, to avoid warnings about\n     redefinitions of notations *)\n Infix \"/\" := D.div : euclid.\n Infix \"mod\" := D.modulo : euclid.\n Local Open Scope euclid.\n\n Module Import Private_NZDiv := Nop <+ NZDivProp A D B.\n\n(** Another formulation of the main equation *)\n\nLemma mod_eq :\n forall a b, b~=0 -> a mod b == a - b*(a/b).\nProof.\nintros.\nrewrite <- add_move_l.\nsymmetry. now apply div_mod.\nQed.\n\nLtac pos_or_neg a :=\n let LT := fresh \"LT\" in\n let LE := fresh \"LE\" in\n destruct (le_gt_cases 0 a) as [LE|LT]; [|rewrite <- opp_pos_neg in LT].\n\n(** Uniqueness theorems *)\n\nTheorem div_mod_unique : forall b q1 q2 r1 r2 : t,\n  0<=r1<abs b -> 0<=r2<abs b ->\n  b*q1+r1 == b*q2+r2 -> q1 == q2 /\\ r1 == r2.\nProof.\nintros b q1 q2 r1 r2 Hr1 Hr2 EQ.\npos_or_neg b.\nrewrite abs_eq in * by trivial.\napply div_mod_unique with b; trivial.\nrewrite abs_neq' in * by auto using lt_le_incl.\nrewrite eq_sym_iff. apply div_mod_unique with (-b); trivial.\nrewrite 2 mul_opp_l.\nrewrite add_move_l, sub_opp_r.\nrewrite <-add_assoc.\nsymmetry. rewrite add_move_l, sub_opp_r.\nnow rewrite (add_comm r2), (add_comm r1).\nQed.\n\nTheorem div_unique:\n forall a b q r, 0<=r<abs b -> a == b*q + r -> q == a/b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0).\n pos_or_neg b.\n rewrite abs_eq in Hr; intuition; order.\n rewrite <- opp_0, eq_opp_r. rewrite abs_neq' in Hr; intuition; order.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\nnow apply mod_always_pos.\nnow rewrite <- div_mod.\nQed.\n\nTheorem mod_unique:\n forall a b q r, 0<=r<abs b -> a == b*q + r -> r == a mod b.\nProof.\nintros a b q r Hr EQ.\nassert (Hb : b~=0).\n pos_or_neg b.\n rewrite abs_eq in Hr; intuition; order.\n rewrite <- opp_0, eq_opp_r. rewrite abs_neq' in Hr; intuition; order.\ndestruct (div_mod_unique b q (a/b) r (a mod b)); trivial.\nnow apply mod_always_pos.\nnow rewrite <- div_mod.\nQed.\n\n(** Sign rules *)\n\nLemma div_opp_r : forall a b, b~=0 -> a/(-b) == -(a/b).\nProof.\nintros. symmetry.\napply div_unique with (a mod b).\nrewrite abs_opp; now apply mod_always_pos.\nrewrite mul_opp_opp; now apply div_mod.\nQed.\n\nLemma mod_opp_r : forall a b, b~=0 -> a mod (-b) == a mod b.\nProof.\nintros. symmetry.\napply mod_unique with (-(a/b)).\nrewrite abs_opp; now apply mod_always_pos.\nrewrite mul_opp_opp; now apply div_mod.\nQed.\n\nLemma div_opp_l_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a)/b == -(a/b).\nProof.\nintros a b Hb Hab. symmetry.\napply div_unique with (-(a mod b)).\nrewrite Hab, opp_0. split; [order|].\npos_or_neg b; [rewrite abs_eq | rewrite abs_neq']; order.\nnow rewrite mul_opp_r, <-opp_add_distr, <-div_mod.\nQed.\n\nLemma div_opp_l_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a)/b == -(a/b)-sgn b.\nProof.\nintros a b Hb Hab. symmetry.\napply div_unique with (abs b -(a mod b)).\nrewrite lt_sub_lt_add_l.\nrewrite <- le_add_le_sub_l. nzsimpl.\nrewrite <- (add_0_l (abs b)) at 2.\nrewrite <- add_lt_mono_r.\ndestruct (mod_always_pos a b); intuition order.\nrewrite <- 2 add_opp_r, mul_add_distr_l, 2 mul_opp_r.\nrewrite sgn_abs.\nrewrite add_shuffle2, add_opp_diag_l; nzsimpl.\nrewrite <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma mod_opp_l_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a) mod b == 0.\nProof.\nintros a b Hb Hab. symmetry.\napply mod_unique with (-(a/b)).\nsplit; [order|now rewrite abs_pos].\nnow rewrite <-opp_0, <-Hab, mul_opp_r, <-opp_add_distr, <-div_mod.\nQed.\n\nLemma mod_opp_l_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a) mod b == abs b - (a mod b).\nProof.\nintros a b Hb Hab. symmetry.\napply mod_unique with (-(a/b)-sgn b).\nrewrite lt_sub_lt_add_l.\nrewrite <- le_add_le_sub_l. nzsimpl.\nrewrite <- (add_0_l (abs b)) at 2.\nrewrite <- add_lt_mono_r.\ndestruct (mod_always_pos a b); intuition order.\nrewrite <- 2 add_opp_r, mul_add_distr_l, 2 mul_opp_r.\nrewrite sgn_abs.\nrewrite add_shuffle2, add_opp_diag_l; nzsimpl.\nrewrite <-opp_add_distr, <-div_mod; order.\nQed.\n\nLemma div_opp_opp_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a)/(-b) == a/b.\nProof.\nintros. now rewrite div_opp_r, div_opp_l_z, opp_involutive.\nQed.\n\nLemma div_opp_opp_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a)/(-b) == a/b + sgn(b).\nProof.\nintros. rewrite div_opp_r, div_opp_l_nz by trivial.\nnow rewrite opp_sub_distr, opp_involutive.\nQed.\n\nLemma mod_opp_opp_z : forall a b, b~=0 -> a mod b == 0 ->\n (-a) mod (-b) == 0.\nProof.\nintros. now rewrite mod_opp_r, mod_opp_l_z.\nQed.\n\nLemma mod_opp_opp_nz : forall a b, b~=0 -> a mod b ~= 0 ->\n (-a) mod (-b) == abs b - a mod b.\nProof.\nintros. now rewrite mod_opp_r, mod_opp_l_nz.\nQed.\n\n(** A division by itself returns 1 *)\n\nLemma div_same : forall a, a~=0 -> a/a == 1.\nProof.\nintros. symmetry. apply div_unique with 0.\nsplit; [order|now rewrite abs_pos].\nnow nzsimpl.\nQed.\n\nLemma mod_same : forall a, a~=0 -> a mod a == 0.\nProof.\nintros.\nrewrite mod_eq, div_same by trivial. nzsimpl. apply sub_diag.\nQed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem div_small: forall a b, 0<=a<b -> a/b == 0.\nProof. exact div_small. Qed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem mod_small: forall a b, 0<=a<b -> a mod b == a.\nProof. exact mod_small. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma div_0_l: forall a, a~=0 -> 0/a == 0.\nProof.\nintros. pos_or_neg a. apply div_0_l; order.\napply opp_inj. rewrite <- div_opp_r, opp_0 by trivial. now apply div_0_l.\nQed.\n\nLemma mod_0_l: forall a, a~=0 -> 0 mod a == 0.\nProof.\nintros; rewrite mod_eq, div_0_l; now nzsimpl.\nQed.\n\nLemma div_1_r: forall a, a/1 == a.\nProof.\nintros. symmetry. apply div_unique with 0.\nassert (H:=lt_0_1); rewrite abs_pos; intuition; order.\nnow nzsimpl.\nQed.\n\nLemma mod_1_r: forall a, a mod 1 == 0.\nProof.\nintros. rewrite mod_eq, div_1_r; nzsimpl; auto using sub_diag.\napply neq_sym, lt_neq; apply lt_0_1.\nQed.\n\nLemma div_1_l: forall a, 1<a -> 1/a == 0.\nProof. exact div_1_l. Qed.\n\nLemma mod_1_l: forall a, 1<a -> 1 mod a == 1.\nProof. exact mod_1_l. Qed.\n\nLemma div_mul : forall a b, b~=0 -> (a*b)/b == a.\nProof.\nintros. symmetry. apply div_unique with 0.\nsplit; [order|now rewrite abs_pos].\nnzsimpl; apply mul_comm.\nQed.\n\nLemma mod_mul : forall a b, b~=0 -> (a*b) mod b == 0.\nProof.\nintros. rewrite mod_eq, div_mul by trivial. rewrite mul_comm; apply sub_diag.\nQed.\n\nTheorem div_unique_exact a b q: b~=0 -> a == b*q -> q == a/b.\nProof.\n intros Hb H. rewrite H, mul_comm. symmetry. now apply div_mul.\nQed.\n\n(** * Order results about mod and div *)\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem mod_le: forall a b, 0<=a -> b~=0 -> a mod b <= a.\nProof.\nintros. pos_or_neg b. apply mod_le; order.\nrewrite <- mod_opp_r by trivial. apply mod_le; order.\nQed.\n\nTheorem div_pos : forall a b, 0<=a -> 0<b -> 0<= a/b.\nProof. exact div_pos. Qed.\n\nLemma div_str_pos : forall a b, 0<b<=a -> 0 < a/b.\nProof. exact div_str_pos. Qed.\n\nLemma div_small_iff : forall a b, b~=0 -> (a/b==0 <-> 0<=a<abs b).\nProof.\nintros a b Hb.\nsplit.\nintros EQ.\nrewrite (div_mod a b Hb), EQ; nzsimpl.\nnow apply mod_always_pos.\nintros. pos_or_neg b.\napply div_small.\nnow rewrite <- (abs_eq b).\napply opp_inj; rewrite opp_0, <- div_opp_r by trivial.\napply div_small.\nrewrite <- (abs_neq' b) by order. trivial.\nQed.\n\nLemma mod_small_iff : forall a b, b~=0 -> (a mod b == a <-> 0<=a<abs b).\nProof.\nintros.\nrewrite <- div_small_iff, mod_eq by trivial.\nrewrite sub_move_r, <- (add_0_r a) at 1. rewrite add_cancel_l.\nrewrite eq_sym_iff, eq_mul_0. tauto.\nQed.\n\n(** As soon as the divisor is strictly greater than 1,\n    the division is strictly decreasing. *)\n\nLemma div_lt : forall a b, 0<a -> 1<b -> a/b < a.\nProof. exact div_lt. Qed.\n\n(** [le] is compatible with a positive division. *)\n\nLemma div_le_mono : forall a b c, 0<c -> a<=b -> a/c <= b/c.\nProof.\nintros a b c Hc Hab.\nrewrite lt_eq_cases in Hab. destruct Hab as [LT|EQ];\n [|rewrite EQ; order].\nrewrite <- lt_succ_r.\nrewrite (mul_lt_mono_pos_l c) by order.\nnzsimpl.\nrewrite (add_lt_mono_r _ _ (a mod c)).\nrewrite <- div_mod by order.\napply lt_le_trans with b; trivial.\nrewrite (div_mod b c) at 1 by order.\nrewrite <- add_assoc, <- add_le_mono_l.\napply le_trans with (c+0).\nnzsimpl; destruct (mod_always_pos b c); try order.\nrewrite abs_eq in *; order.\nrewrite <- add_le_mono_l. destruct (mod_always_pos a c); order.\nQed.\n\n(** In this convention, [div] performs Rounding-Toward-Bottom\n    when divisor is positive, and Rounding-Toward-Top otherwise.\n\n    Since we cannot speak of rational values here, we express this\n    fact by multiplying back by [b], and this leads to a nice\n    unique statement.\n*)\n\nLemma mul_div_le : forall a b, b~=0 -> b*(a/b) <= a.\nProof.\nintros.\nrewrite (div_mod a b) at 2; trivial.\nrewrite <- (add_0_r (b*(a/b))) at 1.\nrewrite <- add_le_mono_l.\nnow destruct (mod_always_pos a b).\nQed.\n\n(** Giving a reversed bound is slightly more complex *)\n\nLemma mul_succ_div_gt: forall a b, 0<b -> a < b*(S (a/b)).\nProof.\nintros.\nnzsimpl.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_always_pos a b). order.\nrewrite abs_eq in *; order.\nQed.\n\nLemma mul_pred_div_gt: forall a b, b<0 -> a < b*(P (a/b)).\nProof.\nintros a b Hb.\nrewrite mul_pred_r, <- add_opp_r.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- add_lt_mono_l.\ndestruct (mod_always_pos a b). order.\nrewrite <- opp_pos_neg in Hb. rewrite abs_neq' in *; order.\nQed.\n\n(** NB: The three previous properties could be used as\n    specifications for [div]. *)\n\n(** Inequality [mul_div_le] is exact iff the modulo is zero. *)\n\nLemma div_exact : forall a b, b~=0 -> (a == b*(a/b) <-> a mod b == 0).\nProof.\nintros.\nrewrite (div_mod a b) at 1; try order.\nrewrite <- (add_0_r (b*(a/b))) at 2.\napply add_cancel_l.\nQed.\n\n(** Some additional inequalities about div. *)\n\nTheorem div_lt_upper_bound:\n  forall a b q, 0<b -> a < b*q -> a/b < q.\nProof.\nintros.\nrewrite (mul_lt_mono_pos_l b) by trivial.\napply le_lt_trans with a; trivial.\napply mul_div_le; order.\nQed.\n\nTheorem div_le_upper_bound:\n  forall a b q, 0<b -> a <= b*q -> a/b <= q.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\nTheorem div_le_lower_bound:\n  forall a b q, 0<b -> b*q <= a -> q <= a/b.\nProof.\nintros.\nrewrite <- (div_mul q b) by order.\napply div_le_mono; trivial. now rewrite mul_comm.\nQed.\n\n(** A division respects opposite monotonicity for the divisor *)\n\nLemma div_le_compat_l: forall p q r, 0<=p -> 0<q<=r -> p/r <= p/q.\nProof. exact div_le_compat_l. Qed.\n\n(** * Relations between usual operations and mod and div *)\n\nLemma mod_add : forall a b c, c~=0 ->\n (a + b * c) mod c == a mod c.\nProof.\nintros.\nsymmetry.\napply mod_unique with (a/c+b); trivial.\nnow apply mod_always_pos.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add : forall a b c, c~=0 ->\n (a + b * c) / c == a / c + b.\nProof.\nintros.\napply (mul_cancel_l _ _ c); try order.\napply (add_cancel_r _ _ ((a+b*c) mod c)).\nrewrite <- div_mod, mod_add by order.\nrewrite mul_add_distr_l, add_shuffle0, <- div_mod by order.\nnow rewrite mul_comm.\nQed.\n\nLemma div_add_l: forall a b c, b~=0 ->\n (a * b + c) / b == a + c / b.\nProof.\n intros a b c. rewrite (add_comm _ c), (add_comm a).\n now apply div_add.\nQed.\n\n(** Cancellations. *)\n\n(** With the current convention, the following isn't always true\n    when [c<0]: [-3*-1 / -2*-1 = 3/2 = 1] while [-3/-2 = 2] *)\n\nLemma div_mul_cancel_r : forall a b c, b~=0 -> 0<c ->\n (a*c)/(b*c) == a/b.\nProof.\nintros.\nsymmetry.\napply div_unique with ((a mod b)*c).\n(* ineqs *)\nrewrite abs_mul, (abs_eq c) by order.\nrewrite <-(mul_0_l c), <-mul_lt_mono_pos_r, <-mul_le_mono_pos_r by trivial.\nnow apply mod_always_pos.\n(* equation *)\nrewrite (div_mod a b) at 1 by order.\nrewrite mul_add_distr_r.\nrewrite add_cancel_r.\nrewrite <- 2 mul_assoc. now rewrite (mul_comm c).\nQed.\n\nLemma div_mul_cancel_l : forall a b c, b~=0 -> 0<c ->\n (c*a)/(c*b) == a/b.\nProof.\nintros. rewrite !(mul_comm c); now apply div_mul_cancel_r.\nQed.\n\nLemma mul_mod_distr_l: forall a b c, b~=0 -> 0<c ->\n  (c*a) mod (c*b) == c * (a mod b).\nProof.\nintros.\nrewrite <- (add_cancel_l _ _ ((c*b)* ((c*a)/(c*b)))).\nrewrite <- div_mod.\nrewrite div_mul_cancel_l by trivial.\nrewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\napply div_mod; order.\nrewrite <- neq_mul_0; intuition; order.\nQed.\n\nLemma mul_mod_distr_r: forall a b c, b~=0 -> 0<c ->\n  (a*c) mod (b*c) == (a mod b) * c.\nProof.\n intros. rewrite !(mul_comm _ c); now rewrite mul_mod_distr_l.\nQed.\n\n\n(** Operations modulo. *)\n\nTheorem mod_mod: forall a n, n~=0 ->\n (a mod n) mod n == a mod n.\nProof.\nintros. rewrite mod_small_iff by trivial.\nnow apply mod_always_pos.\nQed.\n\nLemma mul_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)*b) mod n == (a*b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite add_comm, (mul_comm n), (mul_comm _ b).\n rewrite mul_add_distr_l, mul_assoc.\n rewrite mod_add by trivial.\n now rewrite mul_comm.\nQed.\n\nLemma mul_mod_idemp_r : forall a b n, n~=0 ->\n (a*(b mod n)) mod n == (a*b) mod n.\nProof.\n intros. rewrite !(mul_comm a). now apply mul_mod_idemp_l.\nQed.\n\nTheorem mul_mod: forall a b n, n~=0 ->\n (a * b) mod n == ((a mod n) * (b mod n)) mod n.\nProof.\n intros. now rewrite mul_mod_idemp_l, mul_mod_idemp_r.\nQed.\n\nLemma add_mod_idemp_l : forall a b n, n~=0 ->\n ((a mod n)+b) mod n == (a+b) mod n.\nProof.\n intros a b n Hn. symmetry.\n rewrite (div_mod a n) at 1 by order.\n rewrite <- add_assoc, add_comm, mul_comm.\n now rewrite mod_add.\nQed.\n\nLemma add_mod_idemp_r : forall a b n, n~=0 ->\n (a+(b mod n)) mod n == (a+b) mod n.\nProof.\n intros. rewrite !(add_comm a). now apply add_mod_idemp_l.\nQed.\n\nTheorem add_mod: forall a b n, n~=0 ->\n (a+b) mod n == (a mod n + b mod n) mod n.\nProof.\n intros. now rewrite add_mod_idemp_l, add_mod_idemp_r.\nQed.\n\n(** With the current convention, the following result isn't always\n    true with a negative intermediate divisor. For instance\n    [ 3/(-2)/(-2) = 1 <> 0 = 3 / (-2*-2) ] and\n    [ 3/(-2)/2 = -1 <> 0 = 3 / (-2*2) ]. *)\n\nLemma div_div : forall a b c, 0<b -> c~=0 ->\n (a/b)/c == a/(b*c).\nProof.\n intros a b c Hb Hc.\n apply div_unique with (b*((a/b) mod c) + a mod b).\n (* begin 0<= ... <abs(b*c) *)\n rewrite abs_mul.\n destruct (mod_always_pos (a/b) c), (mod_always_pos a b); try order.\n split.\n apply add_nonneg_nonneg; trivial.\n apply mul_nonneg_nonneg; order.\n apply lt_le_trans with (b*((a/b) mod c) + abs b).\n now rewrite <- add_lt_mono_l.\n rewrite (abs_eq b) by order.\n now rewrite <- mul_succ_r, <- mul_le_mono_pos_l, le_succ_l.\n (* end 0<= ... < abs(b*c) *)\n rewrite (div_mod a b) at 1 by order.\n rewrite add_assoc, add_cancel_r.\n rewrite <- mul_assoc, <- mul_add_distr_l, mul_cancel_l by order.\n apply div_mod; order.\nQed.\n\n(** Similarly, the following result doesn't always hold when [b<0].\n    For instance [3 mod (-2*-2)) = 3] while\n    [3 mod (-2) + (-2)*((3/-2) mod -2) = -1]. *)\n\nLemma mod_mul_r : forall a b c, 0<b -> c~=0 ->\n a mod (b*c) == a mod b + b*((a/b) mod c).\nProof.\n intros a b c Hb Hc.\n apply add_cancel_l with (b*c*(a/(b*c))).\n rewrite <- div_mod by (apply neq_mul_0; split; order).\n rewrite <- div_div by trivial.\n rewrite add_assoc, add_shuffle0, <- mul_assoc, <- mul_add_distr_l.\n rewrite <- div_mod by order.\n apply div_mod; order.\nQed.\n\nLemma mod_div: forall a b, b~=0 ->\n a mod b / b == 0.\nProof.\n intros a b Hb.\n rewrite div_small_iff by assumption.\n auto using mod_always_pos.\nQed.\n\n(** A last inequality: *)\n\nTheorem div_mul_le:\n forall a b c, 0<=a -> 0<b -> 0<=c -> c*(a/b) <= (c*a)/b.\nProof. exact div_mul_le. Qed.\n\n(** mod is related to divisibility *)\n\nLemma mod_divides : forall a b, b~=0 ->\n (a mod b == 0 <-> (b|a)).\nProof.\nintros a b Hb. split.\nintros Hab. exists (a/b). rewrite mul_comm.\n rewrite (div_mod a b Hb) at 1. rewrite Hab; now nzsimpl.\nintros (c,Hc). rewrite Hc. now apply mod_mul.\nQed.\n\nEnd ZEuclidProp.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/theories/Numbers/Integer/Abstract/ZDivEucl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7347631099841939}}
{"text": "Require Import Reals.\nRequire Import Rsequence_def.\nRequire Import Rpser_def Rpser_def_simpl Rpser_base_facts Rpser_sums Rpser_cv_facts.\nRequire Import Rinterval Ranalysis_def Rfunction_facts.\nRequire Import Ass_handling.\n\n(** * Extensionality of the common properties of functions. *)\n\n(** Usual properties. *)\n\nSection Functions_extensionality.\n\nVariables f g : R -> R.\nHypothesis fg_ext : f == g.\n\nLemma continuity_ext : continuity f -> continuity g.\nProof.\nintros f_cont x eps eps_pos.\n destruct (f_cont x _ eps_pos) as [delta [delta_pos Hdelta]].\n exists delta ; split ; [assumption |].\n intros ; do 2 rewrite <- fg_ext ; auto.\nQed.\n\nLemma derivable_pt_lim_ext : forall x l, derivable_pt_lim f x l ->\n  derivable_pt_lim g x l.\nProof.\nintros x l Hl eps eps_pos ; destruct (Hl _ eps_pos) as [delta Hdelta] ;\n exists delta ; intros ; do 2 rewrite <- fg_ext ; auto.\nQed.\n\nLemma derivable_pt_ext : forall x, derivable_pt f x ->\n  derivable_pt g x.\nProof.\nintros x [df Hdf] ; exists df ; apply derivable_pt_lim_ext ; trivial.\nQed.\n\nLemma derivable_ext : derivable f -> derivable g.\nProof.\nintros f_deriv x ; apply derivable_pt_ext ; auto.\nQed.\n\nLemma derive_pt_ext (x : R) (prf : derivable_pt f x) (prg : derivable_pt g x) :\n  derive_pt f x prf = derive_pt g x prg.\nProof.\napply pr_nu_var2 ; assumption.\nQed.\n\nLemma derive_ext (prf : derivable f) (prg : derivable g) :\n  derive f prf == derive g prg.\nProof.\nintro x ; unfold derive ; apply derive_pt_ext.\nQed.\n\nEnd Functions_extensionality.\n\n(** * Extensionality of power serie related concepts. *)\n\nSection Rpser_extensionality.\n\nVariables An Bn : Rseq.\nHypothesis AnBn_ext : (An == Bn)%Rseq.\n\nLemma sum_f_R0_ext : (sum_f_R0 An == sum_f_R0 Bn)%Rseq.\nProof.\nintro n ; induction n ; simpl ; rewrite AnBn_ext ;\n [| rewrite IHn] ; reflexivity.\nQed.\n\nLemma Pser_ext : forall x l, Pser An x l <-> Pser Bn x l.\nProof.\nintros x l ; split ; intros HP eps eps_pos ; destruct (HP _ eps_pos) as [N HN] ;\n exists N ; intros n n_lb ;\n [rewrite (sum_eq _ (fun n => An n * x ^ n)%R) |\n rewrite (sum_eq _ (fun n => Bn n * x ^ n)%R)] ;\n ((apply HN ; assumption) || (intros ; rewrite AnBn_ext ; reflexivity)).\nQed.\n\nLemma weaksum_r_ext : forall (r : R) (rAn : Cv_radius_weak An r)\n (rBn : Cv_radius_weak Bn r),\n weaksum_r An r rAn == weaksum_r Bn r rBn.\nProof.\nintros r rAn rBn x.\n unfold weaksum_r ; destruct (Rlt_le_dec (Rabs x) r) ; trivial.\n destruct (Rpser_abel _ _ rAn x r0) as [l1 Hl1] ; copy Hl1 ;\n  rewrite Pser_ext in Hl0.\n destruct (Rpser_abel _ _ rBn x r0) as [l2 Hl2].\n simpl ; eapply Rpser_unique ; eassumption.\nQed.\n\nLemma sum_r_ext : forall (r : R) (rAn : finite_cv_radius An r)\n (rBn : finite_cv_radius Bn r),\n sum_r An r rAn == sum_r Bn r rBn.\nProof.\nintros r rAn rBn x.\n unfold sum_r ; destruct (Rlt_le_dec (Rabs x) r) ; trivial ;\n  apply weaksum_r_ext.\nQed.\n\nLemma sum_ext : forall (rAn : infinite_cv_radius An)\n  (rBn : infinite_cv_radius Bn),\n  sum An rAn == sum Bn rBn.\nintros rAn rBn x ; unfold sum ; apply weaksum_r_ext.\nQed.\n\nEnd Rpser_extensionality.\n\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/Rextensionality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.734763106286624}}
{"text": "From mathcomp Require Import ssreflect seq ssrfun ssrbool ssrnat.\nFrom mf Require Import all_mf.\nRequire Import pointwise reals.\nRequire Import Reals Psatz Morphisms ChoiceFacts Classical.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDelimit Scope pseudometric_scope with pmetric.\nLocal Open Scope pseudometric_scope.\nLocal Open Scope R_scope.\nSection pseudometrics.\n  Class is_pseudometric `{M: Type} (d: M * M -> R) :=\n    {\n      positive: forall x y, 0 <= d(x,y);\n      symmetric: forall x y, d(x,y) = d(y,x);\n      reflexive: forall x, d(x,x) = 0;\n      triangle_inequality: forall x y z, d(x,y) <= d(x,z) + d(z,y);\n    }.\n  Local Notation \"p /is_pseudometric\":= (is_pseudometric p) (at level 30).\n  \n  Context `{is_pseudometric}.\n  Implicit Types (x y z: M).\n\n  Lemma dst_pos x y: 0 <= d(x,y).\n  Proof. by apply positive. Qed.\n\n  Lemma dst_sym x y: d(x,y) = d(y,x).\n  Proof. by apply symmetric. Qed.\n\n  Lemma dstxx x: d(x,x) = 0.\n  Proof. by apply reflexive. Qed.\n\n  Lemma dst_trngl z x y: d(x,y) <= d(x,z) + d(z,y).\n  Proof. by apply triangle_inequality. Qed.\n  \n  Lemma dst_le x y z r r' q: d(x,z) <= r -> d(z,y) <= r' -> r + r' <= q -> d(x,y) <= q.\n  Proof.\n    move => ineq ienq' add.\n    by apply/Rle_trans/add/Rle_trans/Rplus_le_compat; first exact/dst_trngl.\n  Qed.\n\n  Lemma le_dst x y z r r' q: r + r' <= q -> d(x,z) <= r -> d(z,y) <= r' -> d(x,y) <= q.\n  Proof. by move => ineq dst dst'; apply/dst_le/ineq/dst'/dst. Qed.\n\n  Lemma dst_lt x y z r r' q: d(x,z) <= r -> d(z,y) <= r' -> r + r' < q -> d(x,y) < q.\n  Proof.\n    move => ineq ienq' add.\n    by apply/Rle_lt_trans/add/Rle_trans/Rplus_le_compat; first exact/dst_trngl.\n  Qed.\nEnd pseudometrics.\nNotation \"d \\is_pseudometric_on M\" := (@is_pseudometric M d) (at level 36): pseudometric_scope.\nNotation \"d \\is_pseudometric\" := (is_pseudometric d) (at level 36): pseudometric_scope.\n\nDelimit Scope metric_scope with metric.\nLocal Open Scope metric_scope.\nSection limits.\n  Context `{is_pseudometric}.\n  Definition limit M (d: M * M -> R) := make_mf (fun xn x =>\n    forall eps, 0 < eps -> exists N, forall m,\n          (N <= m)%nat -> d (x,xn m) <= eps).\n\n  Local Notation \"x \\limits xn \\wrt d\" := (limit d xn x) (at level 4).\n  Local Notation \"x \\is_limit_of xn \\wrt d\" := (limit d xn x) (at level 4).\n  \n  Global Instance lim_prpr M d: Proper (@eqfun M nat ==> @set_equiv M) (limit d).\n  Proof.\n    move => xn yn eq x.\n    split => lim eps eg0; have [N prp]:= lim eps eg0; exists N => m.\n    - by rewrite -(eq m); apply/prp.\n    by rewrite (eq m); apply/prp.\n  Qed.\n\n  Implicit Types (x y z: M).\n\n  Lemma lim_dst xn x y: x \\limits xn \\wrt d -> y \\limits xn \\wrt d -> d(x,y) = 0.\n  Proof.\n    move => limxnx limxnx'.\n    apply/cond_eq => eps epsg0.\n    rewrite Rminus_0_r Rabs_pos_eq; last by apply dst_pos.\n    have [ | N Nprp]:= limxnx (eps/3); try lra.\n    have [ | N' N'prp]:= limxnx' (eps/3); try lra.\n    pose k:= maxn N N'.\n    apply/(@dst_lt _ _ H); first by apply/Nprp/leq_maxl/N'.\n    - rewrite dst_sym; apply/N'prp/leq_maxr.\n    lra.\n  Qed.\n\n  Lemma lim_cnst x: x \\limits (cnst x) \\wrt d.\n  Proof. by exists 0%nat; rewrite/cnst dstxx; intros; lra. Qed.\n  \n  Lemma lim_tpmn xn x: x \\limits xn \\wrt d <->\n    (forall n, exists N, forall m, (N <= m)%nat -> d(x,xn m) <= /2 ^ n).\n  Proof.\n    split => [lim n | lim eps eg0].\n    - case: (lim (/2 ^ n)) => [ | N]; last by exists N.\n      by apply/Rinv_0_lt_compat/pow_lt; lra.\n    have [n [? ineq]]:= accf_tpmn eg0.\n    have [N prp]:= lim n; exists N => ? ?.\n    exact/Rlt_le/Rle_lt_trans/ineq/prp.\n  Qed.\n  \n  Lemma dst0_tpmn x y: d(x,y) = 0 <-> forall n, d(x,y) <= / 2 ^ n.\n  Proof.\n    split => [-> | ?]; first exact/tpmn_pos.\n    apply/cond_eq_f; first exact/accf_tpmn.\n    rewrite /R_dist Rminus_0_r Rabs_pos_eq //.\n    by apply dst_pos.\n  Qed.\n\n  Lemma lim_lim_choice xnk xn x:\n    FunctionalCountableChoice_on nat ->\n    (forall n, (xn n) \\limits (xnk n) \\wrt d) -> x \\limits xn \\wrt d ->\n    exists mu, x \\limits (fun n => xnk n (mu n)) \\wrt d.\n  Proof.\n    move => choice lmtlmt /lim_tpmn lmt.\n    have /choice [mu muprp]:\n      forall n, exists m, forall k, (m <= k)%nat -> d (xn n, xnk n k) <= /2 ^ n.\n    - by move => n; apply/(lmtlmt n (/2^n))/Rinv_0_lt_compat/pow_lt; lra.\n    exists mu.\n    apply/lim_tpmn => n.\n    have [N prp]:= lmt (n.+1).\n    exists (maxn n.+1 N) => k ineq.\n    apply/(le_dst _)/muprp => //; last exact/prp/leq_trans/ineq/leq_maxr.\n    rewrite [X in _ <= X]tpmn_half.\n    apply/Rplus_le_compat/Rinv_le_contravar/Rle_pow/leP/leq_trans/ineq/leq_maxl; try lra.\n    by apply/pow_lt; lra.\n  Qed.    \nEnd limits.\nNotation \"xn \\converges_to x \\wrt d\" := (limit d xn x) (at level 23): pseudometric_scope.\n\nSection density.\n  Context `{pm: is_pseudometric}.\n\n  Definition dense_subset (A: subset M):=\n    forall x eps, eps > 0 -> exists y, y \\from A /\\ d(x,y) <= eps.\n\n  Global Instance dns_prpr: Proper (@set_equiv M ==> iff) dense_subset.\n  Proof.\n    move => A B eq; split => dns x eps eg0; have [y []]:= dns x eps eg0; exists y.\n    - by rewrite <-eq.\n    by rewrite ->eq.\n  Qed.\n    \n  Lemma dns_tpmn (A: subset M):\n    dense_subset A <-> forall x n, exists y, y \\from A /\\ d(x,y) <= /2^n.\n  Proof.\n    split => [dns x n | dns x eps eg0]; first by apply/dns/Rlt_gt/Rinv_0_lt_compat/pow_lt; lra.\n    have [n ineq]:= accf_tpmn eg0.\n    have [y []]:= dns x n.\n    exists y; split => //.\n    exact/Rlt_le/Rle_lt_trans/ineq.2.\n  Qed.\n\n  Local Notation sequence := (nat -> M).\n  \n  Definition dense_sequence (r: sequence) :=\n    forall x eps, 0 < eps -> exists n, d(x,r n) <= eps.\n\n  Lemma dseq_dns (r: sequence):\n    dense_sequence r <-> dense_subset (codom (F2MF r)). \n  Proof.\n    split => dns x eps eg0; have []:= dns x eps eg0.\n    - by move => n ineq; exists (r n); split => //; exists n.\n    by move => y [[n <-] ineq]; exists n.\n  Qed.\n\n  Lemma dseq_tpmn (r: sequence):\n    dense_sequence r <-> forall x n, exists m, d(x,r m) <= /2^n.\n  Proof.\n    split => [dns x n| dns x eps eg0]; first apply/dns.\n    - by apply/Rinv_0_lt_compat/pow_lt; lra.\n    have [n [_ ineq]]:= accf_tpmn eg0.\n    have [m prp]:= dns x n.\n    exists m.\n    exact/Rlt_le/Rle_lt_trans/ineq/prp.\n  Qed.\n\n  Definition closure A := make_subset (fun (x: M) =>\n    forall eps, 0 < eps -> exists y, y \\from A /\\ d(x,y) <= eps).\n\n  Lemma subs_clos A: A \\is_subset_of closure A.\n  Proof. by move => x Ax eps epsg0; exists x; split; last rewrite dstxx; try lra. Qed.\n\n  Lemma dns_clos A: dense_subset A <-> closure A === All.\n  Proof.\n    split => [dns x | eq x]; first by split => // _; apply/dns.\n    by have [_ prp]:= eq x; apply/prp.\n  Qed.\n\n  Lemma clos_spec_choice A x:\n    FunctionalCountableChoice_on M ->\n    x \\from closure A <->\n                     exists (xn: sequence), (forall n, xn n \\from A) /\\ xn \\converges_to x \\wrt d.\n  Proof.\n    move => choice; split => [clos | [xn [prp lmt]] eps eg0].\n    - have /choice [xn prp]: forall n, exists y, d(y, x) <= /2^n /\\ A y.\n      + move => n.\n        have [ | y []]:= clos (/2^n); first by apply/Rinv_0_lt_compat/pow_lt; lra.\n        by exists y; rewrite dst_sym.\n      exists xn; split => [n | ]; first by have []:= prp n.\n      apply/lim_tpmn => n; exists n => k ineq.\n      rewrite dst_sym; apply/Rle_trans; first exact/(prp k).1.\n      apply/Rinv_le_contravar/Rle_pow/leP => //; try lra.\n      by apply/pow_lt; lra.\n    have [n cnd]:= lmt eps eg0.\n    by exists (xn n); split; [apply/prp | apply/(cnd n)].\n  Qed.\nEnd density.\nNotation sequence_in M := (nat -> M).\nArguments dense_subset: clear implicits.\nArguments dense_subset {M} (d).\nNotation \"A \\dense_subset_wrt d\" := (dense_subset d A) (at level 35): pseudometric_scope.\nArguments dense_sequence: clear implicits.\nArguments dense_sequence {M} (d).\nNotation \"xn \\dense_wrt d\":= (dense_sequence d xn) (at level 35): pseudometric_scope.\nNotation \"xn \\dense_sequence_wrt d\":= (dense_sequence d xn) (at level 35): pseudometric_scope.\nArguments closure: clear implicits.\nArguments closure {M} (d).\nNotation \"A \\closed_wrt d\":= (closure d A) (at level 35): pseudometric_scope.\n\nSection Cauchy_sequences.\n  Context `{is_pseudometric}.\n  Implicit Types (x y z: M) (xn yn: sequence_in M).\n  Notation limit := (limit d).\n\n  Definition Cauchy_sequences := make_subset (fun xn =>\n    forall eps, 0 < eps -> exists N, forall n m, (N <= n)%nat -> (N <= m)%nat -> d(xn n, xn m) <= eps).\n  \n  Lemma lim_cchy: dom limit \\is_subset_of Cauchy_sequences.\n  Proof.\n    move => xn [x lim] eps eg0.\n    have [ | N prp]:= lim (eps/2); first by lra.\n    exists N => n m ineq ineq'.\n    apply/(@dst_le _ _ H); try exact/prp; first by rewrite dst_sym; apply/prp.\n    lra.\n  Qed.\n  \n  Definition complete := Cauchy_sequences \\is_subset_of dom limit.\n      \n  Lemma cchy_tpmn xn: xn \\from Cauchy_sequences <->\n    forall k, exists N, forall n m, (N <= n <= m)%nat -> d (xn n, xn m) <= /2^k.\n  Proof.\n    split => [cchy k | ass eps /dns0_tpmn [N /Rlt_le ineq]].\n    - have [ | N prp]:= cchy (/2 ^ k); first exact/tpmn_lt.\n      by exists N => n m /andP [? ineq]; apply/prp/leq_trans/ineq.\n    have [N' N'prp]:= ass N; exists N' => n m ? ?.\n    case/orP: (leq_total n m) => ineq'.\n    - by apply/Rle_trans; first exact/N'prp/andP.\n    by rewrite dst_sym; apply/Rle_trans; first apply/N'prp/andP.\n  Qed.\n\n  Definition Cauchy_sequences_with_modulus mu := make_subset (fun xn =>\n    forall k n m, (mu k <= n <= m)%nat -> d (xn n, xn m) <= /2^k).\n\n  Lemma chym_subs mu: Cauchy_sequences_with_modulus mu \\is_subset_of Cauchy_sequences.\n  Proof. by move => xn chy; apply/cchy_tpmn => k; exists (mu k); apply/chy. Qed.\n    \n  Lemma cchy_mod_exists_choice xn:\n    FunctionalCountableChoice_on nat ->\n    xn \\from Cauchy_sequences <-> exists mu, xn \\from Cauchy_sequences_with_modulus mu.\n  Proof. by move => choice; split => [/cchy_tpmn /choice | [mu]]//; apply/chym_subs. Qed.\n\n  Definition eventually_big mu:= forall (n: nat), exists N, forall m, (N <= m)%nat -> (n <= mu m)%nat.\n\n  Lemma lim_evb xn mu (x: M): limit xn x -> eventually_big mu -> limit (xn \\o_f mu) x.\n  Proof.\n    move => lim evb eps eg0.\n    have [N prp]:= lim eps eg0.\n    have [N' ineq]:= evb N.\n    exists N' => m ineq'.\n    exact/prp/ineq/ineq'. \n  Qed.\n  \n  Lemma cchy_evb xn mu:\n    xn \\from Cauchy_sequences -> eventually_big mu -> (xn \\o_f mu) \\from Cauchy_sequences.\n  Proof.\n    move => cchy evb eps /cchy [N prp].\n    have [N' le]:= evb N.\n    exists N' => n m ineq ineq'; apply/prp/le/ineq'.\n    exact/le/ineq.\n  Qed.\nEnd Cauchy_sequences.\nArguments Cauchy_sequences: clear implicits.\nArguments Cauchy_sequences {M} (d).\nNotation \"xn \\Cauchy_wrt d\" := (xn \\from Cauchy_sequences d) (at level 45): pseudometric_scope.\nNotation \"xn \\Cauchy_sequence_wrt d\" := (xn \\from Cauchy_sequences d) (at level 45): pseudometric_scope.\nNotation \"xn \\is_Cauchy_wrt d\" := (xn \\from Cauchy_sequences d) (at level 45): pseudometric_scope.\nNotation \"xn \\is_Cauchy_sequence_wrt d\" :=\n  (xn \\from Cauchy_sequences d) (at level 45): pseudometric_scope.\nArguments complete: clear implicits.\nArguments complete {M} (d).\nNotation \"d \\is_complete\" := (complete d) (at level 45): pseudometric_scope.\nNotation \"d \\is_complete_metric\" := (complete d) (at level 45): pseudometric_scope.\n\nSection efficient_convergence.\n  Context `{pm: is_pseudometric}.\n  Local Notation limit := (limit d).\n  Local Notation Cauchy_sequences:= (Cauchy_sequences d).\n  Local Notation complete := (complete d).\n\n  Definition fast_Cauchy_sequence xn :=\n    forall n m, d (xn n,xn m) <= /2^n + /2^m.\n\n  Definition fast_Cauchy_sequences := make_subset fast_Cauchy_sequence.\n  \n  Lemma fchy_cchy: fast_Cauchy_sequences \\is_subset_of Cauchy_sequences.\n  Proof.\n    move => xn cchy eps epsg0.\n    have [N [_ ineq]]:= accf_tpmn epsg0.\n    exists N.+1 => n m nineq mineq.\n    apply/Rlt_le/Rle_lt_trans; last exact/ineq.\n    apply /Rle_trans; [exact/cchy | rewrite (tpmn_half N)].\n    by apply/Rplus_le_compat; apply/Rinv_le_contravar;\n      try apply/pow_lt; try apply/Rle_pow/leP => //; try lra.\n  Qed.\n\n  Definition efficient_limit := make_mf (fun xn (x: M) =>\n    forall n, d(x, xn n) <= /2^n).\n  \n  Lemma lim_eff_spec: efficient_limit =~= limit|_(fast_Cauchy_sequences).\n  Proof.\n    move => xn x; split => [lim | [fchy lim] n].\n    - split => [n m | eps epsg0].\n      apply/(@dst_le _ _ pm)/Rle_refl/lim; first by rewrite dst_sym; apply/lim.\n      have [n ineq]:= accf_tpmn epsg0.\n      exists n => m nlm.\n      apply/Rlt_le/Rle_lt_trans/ineq.2/Rle_trans; first exact/lim.\n      apply/Rinv_le_contravar; first by apply/pow_lt; lra.\n      by apply/Rle_pow/leP => //; lra.\n    suff all: forall m, d(x, xn n) <= / 2 ^ n + / 2 ^ m.\n    - suff: d(x, xn n) - / 2 ^ n <= 0 by lra.\n      apply/Rnot_lt_le => ineq.\n      have [m ineq']:= accf_tpmn ineq.\n      by have := all m; lra.\n    move => m.  \n    have [ | N prp]:= lim (/2 ^ m.+1); first by apply/Rinv_0_lt_compat/pow_lt; lra.\n    rewrite (tpmn_half m) -Rplus_assoc Rplus_comm.\n    apply/Rle_trans/Rplus_le_compat.\n    - by apply (dst_trngl (xn (maxn m.+1 N))).\n    - exact/prp/leq_maxr.\n    rewrite dst_sym; apply/Rle_trans; first exact/fchy.\n    apply/Rplus_le_compat_l/Rinv_le_contravar/Rle_pow/leP/leq_maxl; try lra.\n    by apply/pow_lt; lra.\n  Qed.\n    \n  Lemma lim_eff_lim : limit \\extends efficient_limit.\n  Proof.\n    rewrite ->lim_eff_spec.\n    rewrite {2}[limit]restr_all.\n    exact/exte_restr/subs_all.\n  Qed.\n\n  Lemma fchy_lim_eff: complete -> fast_Cauchy_sequences === dom efficient_limit.\n  Proof.\n    move => cmplt xn; split => [cchy | [x /lim_eff_spec []]]//.\n    rewrite ->lim_eff_spec; rewrite ->dom_restr_spec; split => //.\n    exact/cmplt/fchy_cchy.\n  Qed.  \n\n  Lemma cchy_fchy_choice xn: FunctionalCountableChoice_on nat ->\n    xn \\Cauchy_wrt d -> exists mu, (xn \\o_f mu) \\from fast_Cauchy_sequences.\n  Proof.\n    move => choice /cchy_tpmn /choice [mu prp].    \n    exists mu => n k /=.\n    case/orP: (leq_total (mu n) (mu k)) => ineq.\n    - apply/Rle_trans; first by apply/prp/andP.\n      rewrite -[X in X <= _]Rplus_0_r; apply/Rplus_le_compat_l.\n      by apply/Rlt_le/Rinv_0_lt_compat/pow_lt; lra.\n    rewrite dst_sym; apply/Rle_trans; first by apply/prp/andP.\n    rewrite -[X in X <= _]Rplus_0_l; apply/Rplus_le_compat_r.\n    by apply/Rlt_le/Rinv_0_lt_compat/pow_lt; lra.\n  Qed.\n\n  Lemma lim_eff_dst xn x y: efficient_limit xn x -> efficient_limit xn y -> d(x, y) = 0.\n  Proof. by move => lim lim'; apply/(@lim_dst _ _ pm)/lim_eff_lim/lim'/lim_eff_lim/lim. Qed.\n\n  Lemma lim_tight_lim_eff: limit \\tightens efficient_limit.\n  Proof.\n    move => xn [x lim]; split => [ | y lim' n]; first by exists x; apply/lim_eff_lim.\n    apply/Rle_trans; first by apply (dst_trngl x).\n    have ->: d(y, x) = 0 by apply/(@lim_dst _ _ pm)/lim_eff_lim/lim.\n    by rewrite Rplus_0_l; apply/lim.\n  Qed.\n\n  Lemma cchy_eff_suff xn:\n    (forall n m, (n <= m)%nat -> d (xn n, xn m) <= /2^n + /2^m) ->\n    fast_Cauchy_sequence xn.\n  Proof.\n    move => ass n m.\n    case /orP: (leq_total n m) => ineq; first by apply ass.\n    by rewrite dst_sym Rplus_comm; apply ass.\n  Qed.\nEnd efficient_convergence.\nArguments fast_Cauchy_sequence: clear implicits.\nArguments fast_Cauchy_sequence {M} (d).\nArguments fast_Cauchy_sequences: clear implicits.\nArguments fast_Cauchy_sequences {M} (d).\nNotation \"xn \\fast_Cauchy_wrt d\" :=\n  (xn \\from fast_Cauchy_sequences d) (at level 45): pseudometric_scope.\nNotation \"xn \\fast_Cauchy_sequence_wrt d\" :=\n  (xn \\from fast_Cauchy_sequences d) (at level 45): pseudometric_scope.\nNotation \"xn \\is_fast_Cauchy_sequence_wrt d\" :=\n  (xn \\from fast_Cauchy_sequences d) (at level 45): pseudometric_scope.\nArguments efficient_limit: clear implicits.\nArguments efficient_limit {M} (d).\nNotation \"x \\efficient_limit_of xn \\wrt d\" := (efficient_limit d xn x) (at level 45): pseudometric_scope.\n\nSection continuity.\n  Context `{pm: is_pseudometric}.\n  Context `{pm0: is_pseudometric}.\n  Context (f: M -> M0).\n  Implicit Types (x y: M) (xn yn: sequence_in M).\n  \n  Definition continuity_point x :=\n    forall eps, 0 < eps -> exists delta, 0 < delta /\\ forall y, d(x,y) <= delta -> d0(f x, f y) <= eps.\n\n  Lemma cntp_tpmn x:\n    continuity_point x <-> forall n, exists m, forall x', d (x, x') <= /2^m -> d0 (f x, f x') <= /2^n.\n  Proof.\n    split => [cont n | cont eps /dns0_tpmn [n ineq]].\n    - have [delta [/dns0_tpmn [m ineq] prp]]:= cont (/2^n) (tpmn_lt n).\n      by exists m => x' dst; apply/prp/Rlt_le/Rle_lt_trans/ineq.\n    have [m prp]:= cont n.\n    exists (/2^m); split => [ | y dst]; first exact/tpmn_lt.\n    exact/Rlt_le/Rle_lt_trans/ineq/prp.\n  Qed.\n\n  Definition continuity_points := make_subset continuity_point.\n\n  Definition continuous:= forall x, continuity_point x.\n\n  Lemma cont_tpmn:\n    continuous <-> forall x n, exists m, forall x', d (x, x') <= /2^m -> d0 (f x, f x') <= /2^n.\n  Proof. by split => cont x; apply/cntp_tpmn. Qed.\n\n  Lemma cntp_all: continuous <-> continuity_points === All.\n  Proof.\n    split => [cont x | eq x]; last exact/eq.\n    by split => // _; apply/cont.\n  Qed.\n  \n  Definition sequential_continuity_point x:=\n    forall xn, xn \\converges_to x \\wrt d -> (ptw f xn) \\converges_to (f x) \\wrt d0.\n\n  Definition sequential_continuity_points := make_subset sequential_continuity_point.\n\n  Definition sequentially_continuous:=\n    forall x, sequential_continuity_point x.\n\n  Lemma scntp_all: sequentially_continuous <-> sequential_continuity_points === All.\n  Proof.\n    split => [cont x | eq x]; last exact/eq.\n    by split => // _; apply/cont.\n  Qed.\n\n  Lemma cntp_scntp x: continuity_point x -> sequential_continuity_point x.\n  Proof.\n    move => cont xn lmt eps eg0.\n    have [delta [dg0 prp]]:= cont eps eg0.\n    have [N' cnd]:= lmt delta dg0.\n    exists N' => m ineq.\n    exact/prp/cnd.\n  Qed.\n\n  Lemma cont_scnt: continuous -> sequentially_continuous.\n  Proof. by move => cont x; apply/cntp_scntp. Qed.\n\n  Lemma scnt_cont_choice:\n    FunctionalCountableChoice_on M -> sequentially_continuous -> continuous.\n  Proof.    \n    move => choice scnt x eps eg0.\n    apply/not_all_not_ex => prp.\n    have /choice [xn xnprp]: forall n, exists y, d(x, y) <= /2^n /\\ eps < d0(f x, f y).\n    - move => n; have /not_and_or [ | cnd]:= (prp (/2 ^ n)).\n      + by have : 0 < /2^n by apply/Rinv_0_lt_compat/pow_lt; lra.\n      apply/not_all_not_ex => asd.\n      apply/cnd => y dst.\n      have /not_and_or [ineq | ineq]:= asd y; last exact/Rnot_lt_le.\n      lra.\n    have lmt: xn \\converges_to x \\wrt d.\n    - rewrite ->lim_tpmn => n.\n      exists n => k ineq; have [le _]:= xnprp k.\n      apply/Rle_trans; first exact/le.\n      apply/Rinv_le_contravar/Rle_pow; try lra; first by apply/pow_lt; lra.\n      exact/leP.\n    have [K cnd]:= scnt x xn lmt eps eg0.\n    have []:= xnprp K.\n    suff: d0 (f x, f (xn K)) <= eps by lra.\n    exact/cnd.\n  Qed.\nEnd continuity.\nArguments continuity_point: clear implicits.\nArguments continuity_point {M} (d) {M0} (d0).\nArguments continuity_points: clear implicits.\nArguments continuity_points {M} (d) {M0} (d0).\nNotation \"f \\continuous_wrt d \\and d0 \\in x\" :=\n  (continuity_point d d0 f x) (at level 35): pseudometric_scope.\nNotation continuous_wrt d d0 := (@continuous _ d _ d0).\nNotation \"f \\continuous_wrt d \\and d0\" :=\n  (continuous_wrt d d0 f) (at level 30): pseudometric_scope.\nNotation \"f \\is_continuous_wrt d \\and d0\" :=\n  (continuous_wrt d d0 f) (at level 30): pseudometric_scope.\nArguments sequential_continuity_points: clear implicits.\nArguments sequential_continuity_points {M} (d) {M0} (d0).\nArguments sequential_continuity_point: clear implicits.\nArguments sequential_continuity_point {M} (d) {M0} (d0).\nArguments sequentially_continuous: clear implicits.\nArguments sequentially_continuous {M} (d) {M0} (d0).\nNotation \"f \\sequentially_continuous_wrt d \\and d0 \\in x\" :=\n  (sequential_continuity_point d d0 f x) (at level 40): pseudometric_scope.\nNotation \"f \\sequentially_continuous_wrt d \\and d0\" :=\n  (sequentially_continuous d d0 f) (at level 40): pseudometric_scope.\nNotation \"f \\is_sequentially_continuous_wrt d \\and d0\" :=\n  (sequentially_continuous d d0 f) (at level 40): pseudometric_scope.\n\nSection subpseudometric.\n  Context `{pm: is_pseudometric}.\n  Global Instance sub_pseudo_metric (A: subset M):\n    (fun xy => d (sval xy.1, sval xy.2)) \\is_pseudometric_on {x | x \\from A}.\n    split; first by move => x y; apply dst_pos.\n    - by move => x y; apply dst_sym.\n    - by move => x; apply dstxx.\n    by move => x y z; apply dst_trngl.\n  Defined.\nEnd subpseudometric.\n", "meta": {"author": "FlorianSteinberg", "repo": "metric", "sha": "b34f29091173ffe079b4d4b6eab21061b81a930c", "save_path": "github-repos/coq/FlorianSteinberg-metric", "path": "github-repos/coq/FlorianSteinberg-metric/metric-b34f29091173ffe079b4d4b6eab21061b81a930c/pseudo_metrics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7347630905832017}}
{"text": "(* partly inspired by \"Coq in a Hurry\" *)\n\nCheck False.\nCheck (3,3).\nCompute let f := fun x => (x * 3, x) in f 3.\nDefinition example1 := fun x : nat => x*x + 2*x + 1.\nCompute example1 5.\n\nRequire Import Bool.\nRequire Import Arith.\n\nPrint bool.\nPrint pred.\nPrint Init.Nat.pred.\n\nLocate \"_ <= _\".\nLocate \"_ -> _\".\n\nSearchPattern (nat -> bool).\nSearchPattern (_ + _ <= _ + _).\nSearchRewrite (_ + (_ + _)).\n\nFixpoint sum_n n :=\n  match n with\n    0 => 0\n  | S p => p + sum_n p\n  end.\n\nTheorem sum_n_eq:\n  forall n, 2 * sum_n n = n * (n - 1).\nProof.\n  intro n; induction n.\n  - auto.\n  - pose (s := sum_n (S n)); fold s; simpl in s; unfold s; clear s. (* eww, but direct 'simpl' goes too far *)\n    rewrite Nat.mul_add_distr_l. rewrite IHn.\n    case n.\n    + reflexivity.\n    + intro n'.\n      repeat (rewrite Nat.mul_succ_l || rewrite Nat.add_succ_l || rewrite Nat.mul_succ_r ||\n        rewrite Nat.add_succ_r || rewrite Nat.add_0_r || rewrite Nat.add_0_l || rewrite Nat.sub_succ ||\n        rewrite Nat.sub_0_r).\n      ring.\nQed.\n\n(* discriminate / injection *)\n(* Open Scope Z_scope. *)\nRequire Import ZArith.\nAbout Z.iter.\n", "meta": {"author": "int-e", "repo": "coq-playground", "sha": "db187eb6685a3f052d93c9490443be4e738c5dc8", "save_path": "github-repos/coq/int-e-coq-playground", "path": "github-repos/coq/int-e-coq-playground/coq-playground-db187eb6685a3f052d93c9490443be4e738c5dc8/Scratch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7346927836098719}}
{"text": "Add LoadPath \"C:\\Projects\\Coq\".\n\nRequire Export Basic.\nRequire Export Case.\n\nTheorem andb_true_elim1:\n  forall b c, andb b c = true -> b = true.\nProof.\n  intros b c.\n  intro H.\n  destruct b.\n  Case \"b = true\".\n    reflexivity.\n  Case \"b = false\".\n    rewrite <- H.\n    reflexivity.\nQed.\n\nTheorem andb_true_elim2:\n  forall b c, andb b c = true -> c = true.\nProof.\n  intros b c.\n  intro H.\n  destruct c.\n  Case \"c = true\".\n    reflexivity.\n  Case \"c = false\".\n    rewrite <- H.\n    destruct b.\n    SCase \"b = false\".\n      reflexivity.\n    SCase \"b = true\".\n      reflexivity.\nQed.\n\nTheorem plus_0_r_firsttry:\n  forall n, n + 0 = n.\nProof.\n  intros n.\n  destruct n as [|n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n  simpl.\nAbort.\n\nTheorem plus_0_r:\n  forall n, n + 0 = n.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem minus_diag:\n  forall n, minus n n = 0.\nProof.\n  intro n.\n  induction n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem mult_0_r:\n  forall n, n * 0 = 0.\nProof.\n  intro n.\n  induction n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_n_Sm:\n  forall n m, S (n + m) = n + S m.\nProof.\n  intros n m.\n  induction n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem plus_comm:\n  forall n m, n + m = m + n.\nProof.\n  intros n m.\n  induction n as [|n'].\n  Case \"n = 0\".\n    rewrite -> plus_0_r.\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'.\n    rewrite plus_n_Sm. reflexivity.\nQed.\n\nTheorem plus_assoc:\n  forall n m p, n + (m + p) = n + m + p.\nProof.\n  intros n m p.\n  induction n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'.\n    reflexivity.\nQed.\n\nFixpoint double n :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\nLemma double_plus:\n  forall n, double n = n + n.\nProof.\n  intro n.\n  induction n as [|n'].\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite -> IHn'.\n    rewrite -> plus_n_Sm.\n    reflexivity.\nQed.\n\n(*\nDestructs attempts to demonstrate the property by solving cases\nof the inductively defined type separately.\nInduction attempts to demonstrate the property by showing how\nthe truth value for a value of the inductively defined set implies\nthe truth of the subsequent value.\n*)\n\nTheorem plus_0_plus':\n  forall n m, (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (0 + n = n) as H.\n  Case \"Proof of assertion\". reflexivity.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_rearrange_firsttry:\n  forall n m p q, n + m + (p + q) = m + n + (p + q).\nProof.\n  intros n m p q.\n  rewrite -> plus_comm.\nAbort.\n\nTheorem plus_rearrange:\n  forall n m p q, n + m + (p + q) = m + n + (p + q).\nProof.\n  intros n m p q.\n  assert (n + m = m + n) as H.\n  Case \"proof of assertion\".\n    rewrite -> plus_comm. reflexivity.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem plus_swap:\n  forall n m p, n + (m + p) = m + (n + p).\nProof.\n  intros.\n  rewrite -> plus_assoc.\n  assert (n + m = m + n) as H.\n    Case \"proof of assertion\".\n    rewrite -> plus_comm. reflexivity.\n  rewrite -> H.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed.\n\nTheorem times_n_succm:\n  forall n m, n * S m = n + n * m.\nProof.\n  intros n m.\n  induction n as [|n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> plus_swap.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem mult_comm:\n  forall n m, n * m = m * n.\nProof.\n  intros.\n  induction n as [|n'].\n  Case \"n = 0\".\n    rewrite -> mult_0_r. reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'.\n    rewrite -> times_n_succm.\n    reflexivity.\nQed.\n\nTheorem evenb_n__oddb_Sn:\n  forall n, evenb n = negb (evenb (S n)).\nProof.\n  intro n.\n  induction n.\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    assert (evenb (S (S n)) = evenb n).\n      SCase \"Proof of assertion\".\n      reflexivity.\n    rewrite -> H.\n    rewrite -> IHn.\n    rewrite -> negb_involutive.\n    reflexivity.\nQed.\n\nTheorem ble_nat_refl:\n  forall n, true = ble_nat n n.\nProof.\n  intro.\n  induction n.\n  reflexivity.\n  rewrite -> IHn.\n  reflexivity.\nQed.\n\nTheorem zero_nbeq_S:\n  forall n, beq_nat 0 (S n) = false.\nProof.\n  intro.\n  reflexivity.\nQed.\n\nTheorem andb_false_r:\n  forall b, andb b false = false.\nProof.\n  intro.\n  destruct b.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem plus_ble_compat_l:\n  forall n m p, ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n  intros.\n  induction p as [|p'].\n  Case \"p = 0\".\n    simpl. rewrite -> H. reflexivity.\n  Case \"p = S p'\".\n    simpl.\n    rewrite -> IHp'.\n    reflexivity.\nQed.\n\nTheorem S_nbeq_0:\n  forall n, beq_nat (S n) 0 = false.\nProof.\n  intro. reflexivity.\nQed.\n\nTheorem mult_1_l:\n  forall n, 1 * n = n.\nProof.\n  intro. simpl.\n  rewrite -> plus_0_r.\n  reflexivity.\nQed.\n\nTheorem all3_spec:\n  forall b c,\n    orb\n      (andb b c)\n      (orb\n        (negb b)\n        (negb c))\n        = true.\nProof.\n  intros.\n  destruct b.\n  destruct c.\n  reflexivity.\n  reflexivity.\n  reflexivity.\nQed.\n\nTheorem mult_plus_distr_r:\n  forall n m p, (n + m) * p = n * p + m * p.\nProof.\n  intros.\n  induction n.\n  induction m.\n  reflexivity.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed.\n\nTheorem mult_assoc:\n  forall n m p, n * (m * p) = n * m * p.\nProof.\n  intros.\n  induction n.\n  induction m.\n  reflexivity.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  rewrite -> mult_plus_distr_r.\n  reflexivity.\nQed.\n\nTheorem beq_nat_refl:\n  forall n, true = beq_nat n n.\nProof.\n  intro n.\n  induction n.\n  reflexivity.\n  rewrite -> IHn.\n  reflexivity.\nQed.\n\nTheorem plus_swap':\n  forall n m p, n + (m + p) = m + (n + p).\nProof.\n  intros.\n  rewrite -> plus_assoc.\n  replace (n + m) with (m + n).\n  rewrite -> plus_assoc.\n  reflexivity.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\n\nInductive bin :=\n  | Z\n  | T: bin -> bin\n  | TPlus: bin -> bin.\n\nFixpoint incr n :=\n  match n with\n  | Z => TPlus Z\n  | T n' => TPlus n'\n  | TPlus n' => T (incr n')\n  end.\n\nFixpoint toNat n :=\n  match n with\n  | Z => O\n  | T n' => mult 2 (toNat n')\n  | TPlus n' => S (mult 2 (toNat n'))\n  end.\n\nTheorem incr_toNat_comm:\n  forall b, toNat (incr b) = S (toNat b).\nProof.\n  intro.\n  induction b as [|b'| b''].\n  Case \"b = Z\".\n    reflexivity.\n  Case \"b = T b'\".\n    simpl.\n    rewrite -> plus_0_r.\n    reflexivity.\n  Case \"b = TPlus b''\".\n    simpl.\n    rewrite -> plus_0_r.\n    rewrite -> plus_0_r.\n    rewrite -> IHb''.\n    simpl.\n    rewrite -> plus_comm.\n    reflexivity.\nQed.\n\nFixpoint toBin n :=\n  match n with\n  | O => Z\n  | S n' => incr (toBin n')\n  end.\n\nTheorem toBin_toNat:\n  forall n, toNat (toBin n) = n.\nProof.\n  intro n.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite -> incr_toNat_comm.\n  rewrite -> IHn.\n  reflexivity.\nQed.\n(*\n\nEval simpl in toBin 3.\nEval simpl in toBin 4.\nEval simpl in toBin 5.\nEval simpl in toBin 6.\nEval simpl in toBin 7.\nEval simpl in toBin 8.\nEval simpl in toBin 9.\nEval simpl in toBin 10.\nEval simpl in toBin 11.\n\nFixpoint normalize b:\n  match b with\n  | Z => Z\n  | T b' => \n\nTheorem toNat_toBin:\n  forall b, toBin (toNat b) = b.\nProof.\n  intro b.\n  induction b as [|b'|b''].\n  Case \"b = Z\".\n    reflexivity.\n  Case \"b = T b'\".\n    simpl.\n    rewrite -> plus_0_r.\n\n*)", "meta": {"author": "davidgrenier", "repo": "SoftwareFoundation", "sha": "4e34d1ac87c4136ea2468048dee306ba5180eb82", "save_path": "github-repos/coq/davidgrenier-SoftwareFoundation", "path": "github-repos/coq/davidgrenier-SoftwareFoundation/SoftwareFoundation-4e34d1ac87c4136ea2468048dee306ba5180eb82/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7345126580435606}}
{"text": "\nRequire Import Arith.\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint less (less_arg0 : natural) (less_arg1 : natural) : bool\n           := match less_arg0, less_arg1 with\n              | x, Zero => false\n              | Zero, Succ x => true\n              | Succ x, Succ y => less x y\n              end.\n\nFixpoint eqb (n m: natural) : bool :=\n  match n, m with\n    | Zero, Zero => true\n    | Zero, Succ _ => false\n    | Succ _, Zero => false\n    | Succ n', Succ m' => eqb n' m'\n  end.\n\n\nFixpoint count  (count_arg1 : lst) (count_arg0 : natural): natural\n           := match  count_arg1,count_arg0 with\n              | Nil, x => Zero\n              | Cons y z, x => if eqb x y then Succ (count z x) else count z x\n              end.\n\n              Fixpoint insort  (insort_arg1 : lst) (insort_arg0 : natural) : lst\n              := match insort_arg1, insort_arg0 with\n                 |  Nil, i => Cons i Nil\n                 | Cons x y, i => if less i x then Cons i (Cons x y) else Cons x (insort y i)\n                 end.\n\n                 Fixpoint sort (sort_arg0 : lst) : lst\n                 := match sort_arg0 with\n                    | Nil => Nil\n                    | Cons x y => insort (sort y) x\n                    end.\n\nTheorem eqb_refl: forall n, eqb n n = true.\nProof.\n   induction n; simpl.\n   { assumption. }\n   { reflexivity. }\nQed.\n\nTheorem eqb_diff: forall (x y: natural), x <> y -> eqb x y = false.\nProof.\n   induction x; induction y; simpl.\n   {\n   intros.\n   apply IHx.\n   intro.\n   subst.\n   assert (Succ y = Succ y). reflexivity.\n   apply H in H0.\n   destruct H0.\n   }\n   {\n   intros. reflexivity.\n   }\n   {\n   intros. reflexivity.\n   }\n   {\n   intros.\n   assert (Zero = Zero). reflexivity.\n   apply H in H0.\n   destruct H0.\n   }\nQed.\n\nTheorem eqb_elim: forall (x y: natural), Bool.Is_true (eqb x y) -> x = y.\nProof.\n   induction x; induction y; simpl in *.\n   intros.\n   {\n   apply IHx in H.\n   subst.\n   reflexivity.\n   }\n   {\n   intros.\n   destruct H.\n   }\n   { intros; destruct H. }\n   {\n   intros. reflexivity.\n   }\nQed.\n\nTheorem count_cons: forall (x: natural) (l: lst), count (Cons x l) x = Succ (count l x).\nProof.\n   intros.\n   simpl.\n   rewrite eqb_refl.\n   reflexivity.\nQed.\n\nTheorem count_insort: forall (x: natural) (l: lst), count (insort l x) x= Succ (count l x).\nProof.\n   intros.\n   induction l.\n   {\n   simpl in *.\n   destruct (less x n).\n   {\n      rewrite count_cons.\n      f_equal.\n   }\n   {\n      destruct (eqb x n) eqn:E.\n      {\n         apply Bool.Is_true_eq_left in E.\n         apply eqb_elim in E.\n         rewrite E in *.\n         rewrite count_cons.\n         rewrite IHl.\n         reflexivity.\n      }\n      {\n         simpl.\n         rewrite E.\n         assumption.\n      }\n   }\n   }\n   {\n   simpl.\n   rewrite eqb_refl.\n   reflexivity.\n   }\nQed.\n\nTheorem count_cons_diff: forall (x y: natural) (l: lst), x <> y -> count (Cons y l) x= count l x.\nProof.\n   intros. simpl.\n   apply eqb_diff in H.\n   rewrite H.\n   reflexivity.\nQed.\n\nTheorem count_insort_diff: forall (x y: natural) (l: lst), x <> y -> count (insort l y) x= count l x.\nProof.\n   intros.\n   induction l.\n   {\n   simpl.\n   destruct (less y n) eqn:El; destruct (eqb x n) eqn:Ee.\n   {\n      simpl.\n      apply eqb_diff in H. rewrite H.\n      rewrite Ee.\n      reflexivity.\n   }\n   {\n      rewrite count_cons_diff.\n      { simpl. rewrite Ee. reflexivity. }\n      { assumption. }\n   }\n   {\n      simpl. rewrite Ee. f_equal.\n      assumption.\n   }\n   {\n      simpl. rewrite Ee. assumption.\n   }\n   }\n   {\n   simpl.\n   apply eqb_diff in H.\n   rewrite H.\n   reflexivity.\n   }\nQed.\n\nTheorem theorem0 : forall (x : natural) (y : lst), eq (count (sort y) x) (count y x).\nProof.\n   intros.\n   induction y.\n   {\n   simpl.\n   destruct (eqb x n) eqn:E.\n   {\n      apply Bool.Is_true_eq_left in E.\n      apply eqb_elim in E.\n      subst.\n      rewrite count_insort.\n      f_equal. assumption.\n   }\n   {\n      simpl.\n      rewrite count_insort_diff.\n      assumption.\n      intro.\n      rewrite H in E.\n      rewrite eqb_refl in E.\n      inversion E.\n   }\n   }\n   {\n   simpl.\n   reflexivity.\n   }\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal50.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7344768964876197}}
{"text": "Require Import Basics PeanoNat Bool.\nRequire Import Lia ZifyBool.\n\nInductive List : Set :=\n  | nil : List\n  | cons (n : nat) (tail : List) : List.\n\nDefinition Empty (l : List) : Prop := match l with\n  | nil => True\n  | cons _ _ => False\n  end.\n\nFixpoint length (l : List) : nat := match l with\n  | nil => 0\n  | cons _ rest => 1 + length rest\n  end.\n\nInductive Sorted (R : nat -> nat -> Prop): List -> Prop :=\n  | Sorted_empty : Sorted R nil\n    (* prázdný List je vždy seřazen *)\n  | Sorted_one (n : nat) : Sorted R (cons n nil)\n    (* List s jedním prvkem je také vždy seřazen *)\n  | Sorted_cons (n : nat) (m : nat) (rest : List)\n    (* List s více prvky [n, m, ...rest] je seřazen, když:*)\n      (* 1. n a m jsou správně seřazeny: *)\n        (first_pair_sorted : R n m)\n      (* 2. zbytek [m, ...rest] je seřazen: *)\n        (rest_sorted : Sorted R (cons m rest))\n      : Sorted R (cons n (cons m rest)).\n\nFixpoint elem (n:nat) (l:List) : bool := match l with\n  | nil => false\n  | cons m r => (if n =? m then true else elem n r)\nend.\n\nInductive Elem (n: nat) : List -> Prop :=\n  | Elem_triv : forall l, Elem n (cons n l)\n  | Elem_cons : forall l u, Elem n l -> Elem n (cons u l).\n\nTheorem Elem_tail {l n u}: Elem n (cons u l) -> n <> u -> Elem n l.\nProof.\n  intros.\n  inversion H.\n  - contradiction.\n  - assumption.\nQed.\n\nTheorem Elem_el0 {l n u} : Elem n (cons u l) <-> n = u \\/ (Elem n l /\\ n <> u).\nProof.\n  intros.\n  split.\n  - destruct (Nat.eq_decidable n u).\n    left. exact H.\n    right.\n    split.\n    + apply (Elem_tail H0 H).\n    + assumption.\n  - intros.\n    destruct H as [-> | E].\n    + apply Elem_triv.\n    + apply Elem_cons.\n      destruct E.\n      exact H.\n      Show Proof.\nQed.\n\n\nTheorem Elem_el {l n u} : Elem n (cons u l) <-> n = u \\/ Elem n l.\nProof.\n  intros.\n  split.\n  - destruct (Nat.eq_decidable n u).\n    left. exact H.\n    right.\n    apply (Elem_tail H0 H).\n  - intros.\n    destruct H as [-> | E].\n    + apply Elem_triv.\n    + apply Elem_cons.\n      exact E.\nQed.\n\nTheorem elem_spec n l: Elem n l <-> elem n l = true.\nProof.\n  split.\n  - intro E.\n    induction l.\n    + inversion E.\n    + simpl.\n      destruct (Nat.eqb_spec n n0); [reflexivity| ].\n      apply IHl.\n      apply Elem_el in E.\n      destruct E; [contradiction | ].\n      exact H.\n  - intro E.\n    induction l.\n    + simpl in E.\n      discriminate E.\n    + simpl in E.\n      destruct (Nat.eqb_spec n n0) as [-> | D].\n      * apply Elem_triv.\n      * apply Elem_cons.\n        exact (IHl E).\nQed.\n\nDefinition elem_reflect n l: reflect (Elem n l) (elem n l) := iff_reflect _ _ (elem_spec n l).\n\nTheorem elem_not_nil : forall l n, Elem n l -> l <> nil.\nProof.\n  intros.\n  destruct l.\n  - inversion H.\n  - discriminate.\nQed.\n\nFixpoint push (a : nat) (l : List) : List :=\n  match l with\n    | nil => cons a nil\n    | cons h rest => cons h (push a rest)\n  end.\n\nFixpoint reverse (a : List) : List :=\n  match a with\n    | nil => nil\n    | cons a rest => push a (reverse rest)\n  end.\n\nFixpoint append (a b : List) : List :=\n  match a with\n    | nil => b\n    | cons ah ar => cons ah (append ar b)\n  end.\n\nFixpoint lastd (n : nat) (l : List) : nat :=\n  match l with\n  | nil => n\n  | cons m r => lastd m r\n  end.\n\nDefinition last (l : List) : if l then unit else nat :=\n  match l with\n  | nil => tt\n  | cons m r => lastd m r\n  end.\n\nDefinition head (l : List) : if l then unit else nat :=\n  match l with\n  | nil => tt\n  | cons m r => m\n  end.\n\nDeclare Scope List_scope.\nDelimit Scope List_scope with List.\nOpen Scope List_scope.\n\nNotation \"a +> b\" := (cons a b) (right associativity, at level 100) : List_scope.\nNotation \"[ ]\" := nil : List_scope.\nNotation \"[ a ; .. ; e ]\" := ( cons a .. (cons e nil) ..) : List_scope.\nNotation \"a ++ b\" := (append a b) : List_scope.\nNotation \"a <+ b\" := (push b a) (left associativity, at level 101) : List_scope.\n\n\nTheorem append_nil {a}: append a nil = a.\nProof.\n  induction a.\n  - reflexivity.\n  - simpl.\n    rewrite IHa.\n    reflexivity.\nQed.\n\nTheorem append_comm {a b c}: append a (append b c) = append (append a b) c.\nProof.\n  induction a.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHa.\n    reflexivity.\nQed.\n\nTheorem append_length a b: length (append a b) = length a + length b.\nProof.\n  induction a.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHa.\n    reflexivity.\nQed.\n\nTheorem Elem_push l n: Elem n (push n l).\nProof.\n  induction l.\n  - constructor.\n  - simpl.\n    constructor.\n    exact IHl.\nQed.\n\nTheorem append_push l a: append l (cons a nil) = push a l.\nProof.\n  induction l.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nTheorem cons_push_comm l a b: cons a (push b l) = push b (cons a l).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nTheorem reverse_cons l a: reverse (cons a l) = push a (reverse l).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem reverse_push l a: reverse (push a l) = cons a (reverse l).\nProof.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite IHl.\n    simpl.\n    reflexivity.\nQed.\n\nTheorem reverse_reverse l: reverse (reverse l) = l.\nProof.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite reverse_push.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nTheorem reverse_exists l: exists rl, l = reverse rl.\nProof.\n  induction l.\n  - exists nil.\n    reflexivity.\n  - destruct IHl.\n    rewrite H.\n    exists (push n x).\n    rewrite reverse_push.\n    reflexivity.\nQed.\n\nTheorem List_push_ind: forall (P: List -> Prop), P nil -> (forall n tail, P tail -> P (push n tail)) -> forall l, P l.\nProof.\n  intros.\n  destruct (reverse_exists l).\n  rewrite H1.\n  clear H1 l.\n  induction x.\n  - simpl.\n    exact H.\n  - simpl.\n    apply H0.\n    exact IHx.\nQed.\n\nTheorem List_push_case l: l = nil \\/ exists n r, l = push n r.\nProof.\n  intros.\n  induction l using List_push_ind.\n  - left. reflexivity.\n  - right.\n    exists  n.\n    exists l.\n    reflexivity.\nQed.\n\nTheorem push_length l a: length (push a l) = S (length l).\nProof.\n  induction l.\n  - reflexivity.\n  - simpl.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nTheorem push_nnil l a: nil <> push a l.\nProof.\n  induction l; discriminate.\nQed.\n\nTheorem Sorted_tail {l a R}: Sorted R (cons a l) -> Sorted R l.\nProof.\n  intros.\n  inversion H.\n  - constructor.\n  - apply rest_sorted.\nQed.\n\nTheorem Sorted_pop {l a R}: Sorted R (push a l) -> Sorted R l.\nProof.\n  intros.\n  destruct l.\n    apply Sorted_empty.\n  generalize dependent a.\n  generalize dependent n.\n  induction l; intros.\n    apply Sorted_one.\n  simpl in H.\n  inversion H; subst.\n  simpl in rest_sorted.\n  apply IHl in rest_sorted.\n  apply Sorted_cons.\n  - exact first_pair_sorted.\n  - exact rest_sorted.\nQed.\n\nTheorem Sorted_app1 {a b R}:\n  Sorted R (append a b)\n  -> Sorted R a.\nProof.\n  intros.\n  destruct a.\n    constructor.\n  generalize dependent n.\n  induction a; intros.\n    constructor.\n  simpl in *.\n  inversion H.\n  subst.\n  constructor.\n  assumption.\n  exact (IHa n rest_sorted).\nQed.\n\nTheorem Sorted_app2 {a b R}:\n  Sorted R (append a b)\n  -> Sorted R b.\nProof.\n  intros.\n  destruct a.\n    destruct b.\n    constructor.\n    simpl in H.\n    assumption.\n  generalize dependent n.\n  induction a; intros.\n    destruct b.\n    constructor.\n    simpl in H.\n    exact (Sorted_tail H).\n  simpl in *.\n  exact (IHa n (Sorted_tail H)).\nQed.\n\n\nTheorem Sorted_push {l a b R}:\n  Sorted R (push a l) ->\n  R a b\n  -> Sorted R (push b (push a l)).\nProof.\n  intros.\n  induction l.\n  - simpl in *.\n    apply Sorted_cons.\n    exact H0.\n    apply Sorted_one.\n  - simpl in *.\n    pose proof (Sorted_tail H).\n    apply IHl in H1.\n    destruct l.\n      simpl in *.\n      inversion H; subst.\n      auto using Sorted.\n    simpl in *.\n    inversion H; subst.\n    constructor.\n    exact first_pair_sorted.\n    exact H1.\nQed.\n\nTheorem Sorted_reverse l R: Sorted R l -> Sorted (flip R) (reverse l).\nProof.\n  intros S.\n  destruct l.\n    constructor.\n  generalize dependent n.\n  induction l; intros.\n    constructor.\n  simpl in *.\n  apply Sorted_push.\n  apply Sorted_tail in S.\n  apply IHl.\n  exact S.\n  unfold flip.\n  inversion S; subst.\n  exact first_pair_sorted.\nQed.\n\nTheorem Sorted_unreverse l R: Sorted R (reverse l) -> Sorted (flip R) l.\nProof.\n  intros S.\n  destruct (reverse_exists l).\n  subst.\n  rewrite reverse_reverse in S.\n  apply Sorted_reverse.\n  exact S.\nQed.\n\nTheorem Sorted_append {R l1 n l2 m} :\n  Sorted R (push n l1) ->\n  Sorted R (cons m l2) ->\n  R n m\n  -> Sorted R (append (push n l1) (cons m l2)).\nProof.\n  generalize dependent l2.\n  generalize dependent m.\n  generalize dependent n.\n  induction l1; intros.\n  - simpl.\n    constructor.\n    exact H1.\n    exact H0.\n  - simpl in *.\n    pose proof (Sorted_tail H).\n    pose proof (IHl1 _ _ _ H2 H0 H1).\n    destruct l1.\n    + simpl in *.\n      inversion H. subst.\n      repeat assumption || constructor.\n    + simpl in *.\n      inversion H; subst.\n      constructor.\n      exact first_pair_sorted.\n      exact H3.\nQed.\n\nFixpoint min (n: nat) (l: List): nat :=\n  match l with\n    | nil => n\n    | cons m t => if m <? n then min m t else min n t\n  end.\n\nTheorem min_elem {n l}: Elem (min n l) (cons n l).\nProof.\n  generalize dependent n.\n  induction l; intros.\n  - simpl.\n    constructor.\n  - simpl in *.\n    destruct (Nat.ltb_spec n n0).\n    constructor.\n    apply IHl.\n    specialize (IHl n0).\n    rewrite Elem_el in IHl.\n    rewrite Elem_el.\n    destruct IHl.\n    rewrite H0.\n    left. reflexivity.\n    right.\n    constructor.\n    exact H0.\nQed.\n\nTheorem min_refl n l: min n l <= n.\nProof.\n  generalize dependent n.\n  induction l; intros.\n  - simpl. lia.\n  - simpl.\n    destruct (Nat.ltb_spec n n0).\n    + specialize (IHl n).\n      lia.\n    + apply IHl.\nQed.\n\nTheorem min_inj n m l: n <= m -> min n l <= min m l.\nProof.\n  intros.\n  generalize dependent m.\n  generalize dependent n.\n  induction l; intros.\n  - simpl.\n    lia.\n  - simpl.\n    destruct (Nat.ltb_spec n n0), (Nat.ltb_spec n m).\n    + lia.\n    + lia.\n    + specialize (IHl n0 n H0).\n      lia.\n    + specialize (IHl n0 m H).\n      lia.\nQed.\n\nTheorem min_lt_elem {n l x}: Elem x l ->  min n l <= x.\nProof.\n  intros.\n  induction l.\n  - inversion H.\n  - apply Elem_el in H.\n    destruct H.\n    subst.\n    simpl.\n    destruct (Nat.ltb_spec n0 n).\n    apply min_refl.\n    pose proof (min_refl n l).\n    lia.\n    specialize (IHl H).\n    simpl.\n    destruct (Nat.ltb_spec n0 n).\n    assert (n0 <= n) by lia.\n    pose proof (min_inj n0 n l H1).\n    lia.\n    lia.\nQed.\n\nNotation LeSorted := (Sorted le).\n\nTheorem LeSorted_min {l} n : LeSorted l -> LeSorted (cons (min n l) l).\nProof.\n  intros.\n  generalize dependent n.\n  induction l; intros.\n    simpl.\n    constructor.\n  simpl.\n  destruct (Nat.ltb_spec n n0).\n  - constructor.\n    + apply min_refl.\n    + exact H.\n  - constructor.\n    + pose proof (min_refl n0 l).\n      lia.\n    + exact H.\nQed.\n\nFixpoint remove_elem n l: List :=\n  match l with\n    | nil => nil\n    | cons m l' => if m =? n then remove_elem n l' else cons m (remove_elem n l')\n  end.\n\nTheorem List_strong_ind:\n  forall P : (List -> Prop),\n  P nil ->\n  (forall l, (forall r, length r < length l -> P r) -> P l)\n  -> forall l, P l.\nProof.\n  intros.\n  assert (exists r, length l < length r).\n    exists (cons 8 l).\n    simpl.\n    lia.\n  destruct H1.\n  generalize dependent l.\n  induction x; intros.\n  - simpl in H1.\n    lia.\n  - simpl in H1.\n    assert (length l <= length x) by lia.\n    Nat.le_elim H2.\n    + apply IHx.\n      exact H2.\n    + apply H0.\n      intros.\n      apply IHx.\n      lia.\nQed.\n\nTheorem List_strong_ind0:\n  forall P : (List -> Prop),\n  P nil ->\n  (forall l, (forall r, length r <= length l -> P r) -> forall n, P (cons n l) )\n  -> forall l, P l.\nProof.\n  intros.\n  destruct l.\n  exact H.\n  assert (exists r, length (cons n l) <= length r).\n    exists (cons 9 l).\n    simpl.\n    lia.\n  destruct H1.\n  generalize dependent l.\n  generalize dependent n.\n  induction x; intros.\n  - simpl in H1.\n    lia.\n  - simpl in H1.\n    assert (length l <= length x) by lia.\n    Nat.le_elim H2.\n    + apply IHx.\n      exact H2.\n    + apply H0.\n      intros.\n      destruct r.\n      exact H.\n      apply IHx.\n      lia.\nQed.\n\nTheorem Sorted_over {n m l}: LeSorted (cons n (cons m l)) -> LeSorted (cons n l).\nProof.\n  intros.\n  destruct l.\n  constructor.\n  inversion H. subst.\n  inversion rest_sorted. subst.\n  constructor.\n  lia.\n  assumption.\nQed.\n\nTheorem Sorted_remove_elem {l} n: LeSorted l -> LeSorted (remove_elem n l).\nProof.\n  intros.\n  destruct l.\n    simpl.\n    constructor.\n  generalize dependent n0.\n  generalize dependent n.\n  induction l; intros.\n  - simpl.\n    destruct (n0 =? n); constructor.\n  - simpl.\n    destruct (Nat.eqb_spec n1 n0);\n    destruct (Nat.eqb_spec n n0); subst.\n    + apply Sorted_tail in H.\n      specialize (IHl n0 0).\n      assert (LeSorted (cons 0 l)). {\n        destruct l.\n        * constructor.\n        * apply Sorted_cons.\n          lia.\n          exact (Sorted_tail H).\n      }\n      specialize (IHl H0).\n      simpl in IHl.\n      destruct n0.\n      * exact IHl.\n      * exact (Sorted_tail IHl).\n    + simpl in *.\n      assert (n =? n0 = false) by lia.\n      specialize (IHl n0 n (Sorted_tail H)).\n      rewrite H0 in IHl.\n      exact IHl.\n    + simpl in *.\n      assert (n1 =? n0 = false) by lia.\n      specialize (IHl n0 n1 (Sorted_over H)).\n      rewrite H0 in IHl.\n      exact IHl.\n    + simpl in *.\n      assert (n =? n0 = false) by lia.\n      specialize (IHl n0 n (Sorted_tail H)).\n      rewrite H0 in IHl.\n      inversion H. subst.\n      constructor.\n      * exact first_pair_sorted.\n      * exact IHl.\nQed.\n\nFixpoint count (n : nat) (l : List) : nat :=\n  match l with\n    | nil => 0\n    | cons m lr => (if m =? n then 1 else 0) + count n lr\n  end.\n\nTheorem count_elem n l: count n l >= 1 <-> Elem n l.\n  split.\n  - intros.\n    induction l.\n    + simpl in H.\n      lia.\n    + simpl in *.\n      destruct (Nat.eqb_spec n0 n).\n      * subst.\n        constructor.\n      * simpl in H.\n        specialize (IHl H).\n        constructor.\n        exact IHl.\n  - intros.\n    induction l.\n    + inversion H.\n    + simpl in *.\n      rewrite Elem_el0 in H.\n      destruct H.\n      * subst.\n        rewrite Nat.eqb_refl.\n        lia.\n      * simpl.\n        destruct H.\n        assert (n0 =? n = false) by lia.\n        rewrite H1.\n        simpl.\n        apply (IHl H).\nQed.\n\nDefinition Permutation a b : Prop := forall n, count n a = count n b.\n\nGoal Permutation (cons 4 (cons 6 nil)) (cons 6 (cons 4 nil)).\nProof.\n  unfold Permutation.\n  intros.\n  do 6 try destruct n.\n  all: simpl.\n  all: reflexivity.\nQed.\n\nTheorem Permutation_refl l : Permutation l l.\nProof.\n  intro.\n  reflexivity.\nQed.\n\nTheorem Permutation_symm {a b} : Permutation a b -> Permutation b a.\nProof.\n  intros H n.\n  specialize (H n).\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem Permutation_trans {a b c} : Permutation a b -> Permutation b c -> Permutation a c.\nProof.\n  unfold Permutation.\n  intros AB BC n.\n  rewrite AB.\n  apply BC.\nQed.\n\nTheorem count_append a b : forall n, count n (append a b) = count n a + count n b.\nProof.\n  generalize dependent b.\n  induction a; intros.\n  - simpl.\n    reflexivity.\n  - simpl.\n    destruct (Nat.eqb_spec n n0).\n    + subst.\n      simpl.\n      f_equal.\n      apply IHa.\n    + simpl.\n      apply IHa.\nQed.\n\n\nTheorem count_push a m: forall n, count n (push m a) = count n (cons m a).\nProof.\n  intro.\n  rewrite <- append_push.\n  rewrite count_append.\n  simpl.\n  lia.\nQed.\n\nTheorem Permutation_reverse l: Permutation l (reverse l).\nProof.\n  intro.\n  induction l.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite count_push.\n    simpl.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nFixpoint filter (f: nat -> bool) (l: List): List :=\n  match l with\n  | nil => nil\n  | cons n r => if f n then cons n (filter f r)\n                      else filter f r\n  end.\n\nTheorem filter_forall l f: forall n, Elem n (filter f l) -> Elem n l /\\ f n = true.\nProof.\n  intros.\n  split. {\n    generalize dependent n.\n    induction l.\n    - intros.\n      simpl in H.\n      inversion H.\n    - intros.\n      simpl in H.\n      destruct (f n).\n      + rewrite Elem_el0 in H.\n        destruct H as [].\n        * subst.\n          constructor.\n        * constructor.\n          apply IHl.\n          apply H.\n      + constructor.\n        apply IHl.\n        exact H.\n  } {\n    generalize dependent n.\n    induction l.\n    - intros.\n      simpl in H.\n      inversion H.\n    - intros.\n      simpl in H.\n      destruct (f n) eqn:E.\n      + destruct (Nat.eqb_spec n0 n).\n        * subst.\n          exact E.\n        * apply IHl.\n          apply Elem_tail in H.\n          exact H. exact n1.\n      + apply IHl.\n        exact H.\n  }\nQed.\n\nTheorem filter_length f l: length (filter f l) <= length l.\n  induction l.\n  - simpl.\n    lia.\n  - simpl.\n    destruct (f n).\n    + simpl.\n      lia.\n    + lia.\nQed.\n\nTheorem filter_comp f g l: filter f (filter g l) = filter (fun x => f x && g x) l.\n  induction l.\n  - simpl.\n    reflexivity.\n  - simpl.\n    all: destruct (g n).\n    all: simpl.\n    all: destruct (f n).\n    all: simpl.\n    all: rewrite IHl.\n    all: reflexivity.\nQed.\n\nEval compute in filter (fun a => a <? 8) (cons 2 (cons 6 (cons 8 (cons 11 (cons 3 nil))))).\n\nFixpoint qs (u : nat) (l : List) : List :=\n  match l, u with\n  | cons p r, S v => append (qs v (filter (fun a => a <? p) r))\n              (cons p (qs v (filter (fun a => p <=? a) r)))\n  | _, _ => nil\n  end.\n\nDefinition quicksort (l: List) : List := qs (length l) l.\n\nEval compute in quicksort (cons 2 (cons 6 (cons 8 (cons 11 (cons 3 nil))))).\nEval compute in quicksort nil.\n\nTheorem le_to_add {n m}: n <= m -> exists x, x + n = m.\nProof .\n  intros.\n  induction n.\n  - exists m.\n    lia.\n  - destruct m.\n    + lia.\n    + assert (n <= S m) by lia.\n      specialize (IHn H0).\n      destruct IHn.\n      destruct x; simpl in *.\n      * lia.\n      * exists x.\n        lia.\nQed.\n\nTheorem qs_u_irrelevant0 {l} u: qs (length l) l = qs (u + length l) l.\nProof.\n  replace (length l) with (0 + length l) by lia.\n  generalize 0 as v.\n  revert u.\n  induction l using List_strong_ind0; intros.\n  - simpl.\n    destruct u.\n    + simpl. reflexivity.\n    + simpl. destruct v; reflexivity.\n  - simpl.\n    replace (v + S (length l)) with (S (v + length l)) by lia.\n    replace (u + S (v + length l)) with (S (u + v + length l)) by lia.\n    simpl.\n    f_equal.\n    + remember (fun a => a <? n) as less.\n      pose proof (filter_length less l).\n      remember (filter less l) as before.\n      pose proof (H _ H0).\n      destruct (le_to_add H0).\n      specialize (H1 u (v + x)).\n      rewrite <- H2.\n      repeat rewrite Nat.add_assoc in *.\n      exact H1.\n    + remember (fun a => n <=? a) as more.\n      pose proof (filter_length more l).\n      remember (filter more l) as after.\n      f_equal.\n      pose proof (H _ H0).\n      destruct (le_to_add H0).\n      specialize (H1 u (v + x)).\n      rewrite <- H2.\n      repeat rewrite Nat.add_assoc in *.\n      exact H1.\nQed.\n\nTheorem qs_u_irrelevant {l u}: length l <= u -> qs (length l) l = qs u l.\nProof.\n  intros.\n  destruct (le_to_add H) as [? <-].\n  apply qs_u_irrelevant0.\nQed.\n\nTheorem Elem_case l: l = nil \\/ exists n, Elem n l.\nProof.\n  destruct l.\n  - left.\n    reflexivity.\n  - right.\n    exists n.\n    constructor.\nQed.\n\nTheorem Permutation_Elem {l l'}: Permutation l l' -> forall n, Elem n l -> Elem n l'.\nProof.\n  intros.\n  unfold Permutation in H.\n  rewrite <- count_elem in *.\n  specialize (H n).\n  rewrite <- H.\n  exact H0.\nQed.\n\nTheorem quicksort_permutation l: Permutation l (quicksort l).\nProof.\n  unfold quicksort.\n  induction l as [| l IH p] using List_strong_ind0 .\n  - simpl.\n    intros n.\n    simpl.\n    reflexivity.\n  - intros n.\n    simpl.\n    rewrite count_append.\n    simpl.\n\n    remember (fun a => a <? p) as less.\n    pose proof (filter_length less l).\n    remember (filter less l) as before.\n    pose proof (IH _ H).\n    rewrite (qs_u_irrelevant H) in H0.\n    specialize (H0 n).\n    rewrite <- H0.\n    clear H0 H.\n\n    remember (fun a => p <=? a) as more.\n    pose proof (filter_length more l).\n    remember (filter more l) as after.\n    pose proof (IH _ H).\n    rewrite (qs_u_irrelevant H) in H0.\n    specialize (H0 n).\n    rewrite <- H0.\n    clear H0 H.\n\n    enough (count n l = count n before + count n after) by lia.\n    clear IH.\n    subst.\n    induction l.\n    + subst.\n      simpl.\n      reflexivity.\n    + simpl.\n      destruct (Nat.ltb_spec n0 p).\n      * replace (p <=? n0) with false by lia.\n        simpl.\n        lia.\n      * replace (p <=? n0) with true by lia.\n        simpl.\n        lia.\nQed.\n\nTheorem quicksort_sorted l: LeSorted (quicksort l).\nProof.\n  unfold quicksort.\n  induction l as [| l IH p] using List_strong_ind0 .\n  - compute.\n    constructor.\n  - simpl.\n    remember (fun a => a <? p) as less.\n    pose proof (filter_length less l).\n    remember (filter less l) as before.\n    remember (fun a => p <=? a) as more.\n    pose proof (filter_length more l).\n    remember (filter more l) as after.\n    pose proof (IH _ H).\n    rewrite (qs_u_irrelevant H) in H1.\n    pose proof (IH _ H0).\n    rewrite (qs_u_irrelevant H0) in H2.\n    assert (LeSorted (cons p (qs (length l) after))). {\n      clear IH H H1 Heqless Heqbefore less before.\n      pose proof (quicksort_permutation after).\n      unfold quicksort in *.\n      rewrite (qs_u_irrelevant H0) in H.\n      pose proof (filter_forall l more).\n      rewrite <- Heqafter in H1.\n      remember (qs (length l) after) as qafter.\n      destruct qafter.\n      constructor.\n      specialize (H1 n).\n      pose proof (Permutation_Elem (Permutation_symm H) n).\n      assert (Elem n (cons n qafter)) by constructor.\n      specialize (H3 H4).\n      destruct (H1 H3).\n      subst more.\n      constructor.\n      lia.\n      exact H2.\n    }\n    destruct (List_push_case (qs (length l) before)).\n    + rewrite H4.\n      simpl.\n      exact H3.\n    + destruct H4 as (n & r & H4).\n      rewrite H4.\n      apply Sorted_append.\n      rewrite <- H4.\n      exact H1.\n      exact H3.\n      clear IH H1 H2 H3 H0 Heqmore more Heqafter after.\n      pose proof (quicksort_permutation before).\n      unfold quicksort in *.\n      rewrite (qs_u_irrelevant H) in H0.\n      pose proof (Elem_push r n).\n      rewrite <- H4 in H1.\n      pose proof (filter_forall l less).\n      rewrite <- Heqbefore in H2.\n      pose proof (Permutation_Elem (Permutation_symm H0) n).\n      specialize (H3 H1).\n      destruct (H2 n H3).\n      subst less.\n      lia.\nQed.\n\nRequire Import FunInd Recdef.\n\nFunction fquicksort (l : List) {measure length l} : List :=\n  match l with\n  | nil => nil\n  | cons p r => append (fquicksort (filter (fun a => a <? p) r))\n              (cons p (fquicksort (filter (fun a => p <=? a) r)))\n  end.\nProof.\n  all: intros.\n\n  remember (fun a => p <=? a) as more.\n  pose proof (filter_length more r).\n  simpl. lia.\n\n  remember (fun a => a <? p) as less.\n  pose proof (filter_length less r).\n  simpl. lia.\nDefined.\n\nSearch \"fquicksort\".\n\nPrint fquicksort.\nPrint fquicksort_terminate.\n\nEval vm_compute in fquicksort (cons 2 (cons 6 (cons 8 (cons 11 (cons 3 nil))))).\n\nEval vm_compute in (6 +> 5 +> []).\n\nEval vm_compute in fquicksort  (6 +> 7 +> 1 +> 0 +> 100 +> 2 +> 20 +> 120 +> 130 +> 140 +> 151 +> 156 +> nil).\n\nEval vm_compute in fquicksort [6; 7; 1; 0; 100; 2; 20; 120; 130; 140; 151; 156].\n\nEval vm_compute in (5 +> 1 +> nil <+ 6 <+ 19).\n\nEval vm_compute in fquicksort [6; 5; 4; 3; 7; 5; 7; 2; 7; 1; 7; 8; 2; 5; 7; 3; 9].\n\nEval vm_compute in filter (fun a => 0 <? a) [ 6 ; 7 ; 1 ; 0 ; 100 ; 2 ; 20 ; 120 ; 130 ; 140 ; 151 ; 156].\n\nTheorem fquicksort_permutation l: Permutation l (fquicksort l).\nProof.\n  intros n.\n  functional induction (fquicksort l) as [ | ? p r ? IHbefore IHafter].\n  - simpl. reflexivity.\n  - set (less := fun a => a <? p) in *.\n    set (before := filter less r) in *.\n    set (more := fun a => p <=? a) in *.\n    set (after := filter more r) in *.\n    simpl.\n    rewrite count_append.\n    simpl.\n    enough (count n r = count n (fquicksort before) + count n (fquicksort after))\n      by (simpl;lia).\n    destruct IHbefore, IHafter.\n    induction r.\n    + simpl. reflexivity.\n    + subst less more before after.\n      simpl in *.\n      destruct (n0 <? p) eqn:E.\n      * replace (p <=? n0) with false by lia.\n        simpl. lia.\n      * replace (p <=? n0) with true by lia.\n        simpl. lia.\nQed.\n\n\nTheorem fquicksort_sorted l: LeSorted (fquicksort l).\nProof.\n  functional induction (fquicksort l) as [ | ? p l ? IHbefore IHafter].\n  - constructor.\n  - set (less := fun a => a <? p) in *.\n    set (before := filter less l) in *.\n    set (more := fun a => p <=? a) in *.\n    set (after := filter more l) in *.\n\n    assert ( LeSorted (cons p (fquicksort after))) as p_after_sorted. {\n      clear IHbefore less before.\n      remember (fquicksort after) as qafter.\n      destruct qafter.\n      + constructor.\n      + constructor.\n        rewrite Heqqafter in *.\n        pose proof (fquicksort_permutation after).\n        apply Permutation_symm in H.\n        pose proof (Permutation_Elem H n).\n        assert (Elem n (n +> qafter)) by constructor.\n        rewrite Heqqafter in H1.\n        apply H0 in H1.\n        clear H0 H qafter Heqqafter.\n        subst more after.\n        apply filter_forall in H1.\n        destruct H1.\n        lia.\n        exact IHafter.\n    }\n\n\n    destruct (List_push_case (fquicksort before)) as [-> | H].\n    + simpl.\n      exact p_after_sorted.\n    + destruct H as (n & r & push_eq).\n      rewrite push_eq.\n      apply Sorted_append.\n      * rewrite <- push_eq.\n        exact IHbefore.\n      * exact p_after_sorted.\n      * clear p_after_sorted more after IHafter.\n        pose proof (fquicksort_permutation before).\n        apply Permutation_symm in H.\n        pose proof (Permutation_Elem H n).\n        pose proof (Elem_push r n).\n        rewrite <- push_eq in H1.\n        apply H0 in H1.\n        clear push_eq H0 H r.\n        subst before less.\n        apply filter_forall in H1.\n        destruct H1.\n        lia.\nQed.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/laz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.7344692947490035}}
{"text": "(*From LF Require Export Logic.*)\nFrom Coq Require Import Lia.\nRequire Import Coq.Strings.Ascii.\nRequire Import List.\n\nModule IndPropRegexp.\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).\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\n\n(*\n    The expression EmptySet does not match any string.\n    The expression EmptyStr matches the empty string [].\n    The expression Char x matches the one-character string [x].\n    If re1 matches s1, and re2 matches s2, then App re1 re2 matches s1 ++ s2.\n    If at least one of re1 and re2 matches s, then Union re1 re2 matches s.\n    Finally, if we can write some string s as the concatenation of a sequence of \n      strings s = s_1 ++ ... ++ s_k, and the expression re matches each one of the \n      strings s_i, then Star re matches s.\n    In particular, the sequence of strings may be empty, so Star re always matches \n      the empty string [] no matter what re is.\n*)\n\nSearch nil.\n\nInductive exp_match {T} : list T -> reg_exp T -> Prop :=\n  | MEmpty : nil =~ EmptyStr\n  | MChar x : cons x nil =~ (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 : nil =~ (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\n\nSearch list.\nDefinition string := list ascii.\n\n\nModule HelperLemmas.\n  Lemma provable_equiv_true : forall (P : Prop), P -> (P <-> True).\n  Proof.\n    intros.\n    split.\n    - intros. constructor.\n    - intros _. apply H.\n  Qed.\n\n  Lemma not_equiv_false : forall (P : Prop), ~P -> (P <-> False).\n  Proof.\n    intros.\n    split.\n    - apply H.\n    - intros. destruct H0.\n  Qed.\n\n  Lemma null_matches_none : forall (s : string), (s =~ EmptySet) <-> False.\n  Proof.\n    intros.\n    apply not_equiv_false.\n    unfold not. intros. inversion H.\n  Qed.\n\n  Lemma empty_matches_eps : forall (s : string), s =~ EmptyStr <-> s = nil.\n  Proof.\n    split.\n    - intros. inversion H. reflexivity.\n    - intros. rewrite H. apply MEmpty.\n  Qed.\n\n  Lemma empty_nomatch_ne : forall (a : ascii) s, (a :: s =~ EmptyStr) <-> False.\n  Proof.\n    intros.\n    apply not_equiv_false.\n    unfold not. intros. inversion H.\n  Qed.\n\n  Lemma char_nomatch_char :\n    forall (a b : ascii) s, b <> a -> (b :: s =~ Char a <-> False).\n  Proof.\n    intros.\n    apply not_equiv_false.\n    unfold not.\n    intros.\n    apply H.\n    inversion H0.\n    reflexivity.\n  Qed.\n\n  Lemma char_eps_suffix : forall (a : ascii) s, a :: s =~ Char a <-> s = nil.\n  Proof.\n    split.\n    - intros. inversion H. reflexivity.\n    - intros. rewrite H. apply MChar.\n  Qed.\n\n  Lemma app_exists : forall (s : string) re0 re1,\n    s =~ App re0 re1 <->\n    exists s0 s1, s = s0 ++ s1 /\\ s0 =~ re0 /\\ s1 =~ re1.\n  Proof.\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).\n  Qed.\n\n  Lemma app_ne : forall (a : ascii) s re0 re1,\n    a :: s =~ (App re0 re1) <->\n    (nil =~ re0 /\\ a :: s =~ re1) \\/\n    exists s0 s1, s = s0 ++ s1 /\\ a :: s0 =~ re0 /\\ s1 =~ re1.\n  Proof.\n    intros. split.\n    - intros Hmat.\n      (* MApp s1 re1 s2 re2\n             (H1 : s1 =~ re1)\n             (H2 : s2 =~ re2) *)\n      inversion Hmat.\n      destruct s1 as [| s1h s1t].\n      + left.\n        split. apply H1.\n        simpl. apply H3.\n      + right.\n        simpl in H0.\n        injection H0 as H0h H0.\n        exists s1t, s2.\n        split.\n        * symmetry. apply H0.\n        * split.\n          ** rewrite -> H0h in H1. apply H1.\n          ** apply H3.\n    - intros [ [ Hnil Hasre1] | [ s0 [ s1 [ Es [ Has0re0 Hs1re1 ] ] ] ] ].\n      + (*MApp s1 re1 s2 re2 (H1 : s1 =~ re1) (H2 : s2 =~ re2): (s1 ++ s2) *)\n        apply (MApp nil re0 (a :: s) re1 Hnil Hasre1).\n      + assert(G: a :: s = (a :: s0) ++ s1). {\n          rewrite -> Es. simpl. reflexivity.\n        }\n        rewrite -> G.\n        apply (MApp (a :: s0) re0 s1 re1 Has0re0 Hs1re1).\n  Qed.\n\n  Lemma union_disj : forall (s : string) re0 re1,\n    s =~ Union re0 re1 <-> (s =~ re0 \\/ s =~ re1).\n  Proof.\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.\n  Qed.\n\n  Lemma star_empty_empty: forall (s: string), \n    s =~ Star EmptyStr -> s = nil.\n  Proof.\n    intros.\n    remember (Star EmptyStr) as k eqn:Ek.\n    induction H as [| c \n                    | s1 re1 s2 re2 H1 IH1 H2 IH2\n                    | s1 re1 re2 H1 IH\n                    | re1 s2 re2 H2 IH\n                    | re\n                    | s1 s2 re H1 IH1 H2 IH2 ].\n    - (* MEmpty  *) discriminate Ek.\n    - (* MChar *) discriminate Ek.\n    - (* MApp *) discriminate Ek.\n    - (* MUnionL *) discriminate Ek.\n    - (* MUnionR *) discriminate Ek.\n    - (* MStar0 *) reflexivity.\n    - (* MStarApp *) injection Ek as Ek'.\n      rewrite -> Ek' in H2.\n      rewrite -> Ek' in H1.\n      assert(G: s1 = nil). {\n        apply empty_matches_eps.\n        apply H1.\n      }\n      rewrite -> G. simpl. \n      apply IH2.\n      rewrite -> Ek'.\n      reflexivity.\n  Qed.\n\n  Search (?l ++ nil = ?l).\n  Lemma 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.\n  Proof.\n    intros.\n    split.\n    + intros H.\n      remember (Star re) as k eqn:Ek.\n      remember (a :: s) as acs eqn:Eacs.\n      induction H as [| c \n                      | s1 re1 s2 re2 H1 IH1 H2 IH2\n                      | s1 re1 re2 H1 IH\n                      | re1 s2 re2 H2 IH\n                      | re'\n                      | s1 s2 re' H1 IH1 H2 IH2 ].\n      - (* MEmpty  *) discriminate Ek.\n      - (* MChar *) discriminate Ek.\n      - (* MApp *) discriminate Ek.\n      - (* MUnionL *) discriminate Ek.\n      - (* MUnionR *) discriminate Ek.\n      - (* MStar0 *) discriminate Eacs.\n      - (* MStarApp *) \n        destruct s1 as [| s1h s1t] eqn:Es1.\n        * simpl in Eacs.\n          apply (IH2 Ek Eacs).\n        * simpl in Eacs.\n          injection Eacs as Eacs'h Eacs't.\n          exists s1t, s2.\n          split.\n          ** symmetry. apply Eacs't.\n          ** split.\n             *** rewrite -> Eacs'h in H1. injection Ek as Ek. rewrite -> Ek in H1. apply H1.\n             *** apply H2.\n    + intros [ s0 [ s1 [ Es [Has0 Hs1 ] ] ] ].\n      rewrite -> Es.\n      assert (G: a :: s0 ++ s1 = (a :: s0) ++ s1). { reflexivity. }\n      rewrite -> G.\n      (* MStarApp s1 s2 re (H1 : s1 =~ re) (H2 : s2 =~ (Star re))   : (s1 ++ s2) =~ (Star re) *)\n      apply (MStarApp (a :: s0) s1 _ Has0 Hs1).\n  Qed.\n\n\n  Inductive reflect (P : Prop) : bool -> Prop :=\n  | ReflectT (H : P) : reflect P true\n  | ReflectF (H : ~ P) : reflect P false.\n\nEnd HelperLemmas.\n\n\nImport HelperLemmas.\n\nDefinition refl_matches_eps m := forall re : reg_exp ascii, reflect (nil =~ re) (m re).\n\nFixpoint match_eps (re: reg_exp ascii) : bool :=\n  match re with \n  | EmptyStr => true\n  | EmptySet => false\n  | Char _ => false\n  | App r1 r2 => match_eps r1 && match_eps r2\n  | Union r1 r2 => match_eps r1 || match_eps r2\n  | Star _ => true\n  end.\n\n  Search (?l1 ++ ?l2 = nil).\n\nLemma match_eps_refl : refl_matches_eps match_eps.\nProof.\n  unfold refl_matches_eps.\n  intros re.\n  induction re as [ | | c | r1 IHl r2 IHr | r1 IHl r2 IHr | r IH].\n  - simpl. apply ReflectF. unfold not. intros H. inversion H.\n  - simpl. apply ReflectT. apply MEmpty.\n  - simpl. apply ReflectF. unfold not. intros H. inversion H.\n  - simpl. \n    destruct (match_eps r1).\n    + destruct (match_eps r2).\n      ++ simpl. inversion IHl as [IHl' | _]. inversion IHr as [IHr' | _]. apply ReflectT. \n         apply (MApp nil r1 nil r2 IHl' IHr').\n      ++ simpl. apply ReflectF. unfold not. intros H. inversion H. inversion IHr.\n         apply H5.\n         assert (G: s2 = nil). { destruct (app_eq_nil s1 s2 H1). apply H7. }\n         rewrite -> G in H4. apply H4.\n    + simpl. apply ReflectF. unfold not. intros H. inversion H. inversion IHl.\n      apply H5.\n      assert (G: s1 = nil). { destruct (app_eq_nil s1 s2 H1). apply H6. }\n      rewrite -> G in H3. apply H3.\n  - simpl. \n    destruct (match_eps r1).\n    + simpl. apply ReflectT. \n      assert (G: nil =~ r1). {inversion IHl. apply H. }\n      apply (MUnionL nil r1 r2 G).\n    + destruct (match_eps r2).\n      ++ simpl. apply ReflectT. \n         assert (G: nil =~ r2). {inversion IHr. apply H. }\n         apply (MUnionR r1 nil r2 G).\n      ++ simpl. apply ReflectF. unfold not. intros H. inversion IHl.\n         apply H0. inversion H. apply H3. \n         inversion IHr. exfalso. apply H5. apply H3.\n  - simpl. apply ReflectT. 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\nFixpoint derive (a : ascii) (re : reg_exp ascii) : reg_exp ascii :=\n  match re with\n  | EmptySet => EmptySet\n  | EmptyStr => EmptySet\n  | Char t => if eqb t a then EmptyStr else EmptySet\n  | App r1 r2 =>  (* TODO *)\n    if match_eps r1 \n    then \n      match derive a r1 with\n      | EmptySet => derive a r2\n      | o => App o r2\n      end\n    else App (derive a r1) r2\n  | Union r1 r2 => \n    match derive a r1 with\n    | EmptySet => derive a r2\n    | o => o\n    end\n  | Star r =>  \n    let d := derive a r in\n    if match_eps d then Star r else App d (Star r)\n  end.\n\nModule DeriveTests.\n  Example c := ascii_of_nat 99.\n  Example d := ascii_of_nat 100.\n\n  (* \"c\" =~ EmptySet: *)\n  Example test_der0 : match_eps (derive c (EmptySet)) = false.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"c\" =~ Char c:  *)\n  Example test_der1 : match_eps (derive c (Char c)) = true.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"c\" =~ Char d: *)\n  Example test_der2 : match_eps (derive c (Char d)) = false.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"c\" =~ App (Char c) EmptyStr: *)\n  Example test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"c\" =~ App EmptyStr (Char c): *)\n  Example test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"c\" =~ App (Star d) (Char c): *)\n  Example test_der41 : match_eps (derive c (App (Star (Char d)) (Char c))) = true.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"dc\" =~ App (Star d) (Char c): *)\n  Example test_der42 : match_eps (derive c (derive d (App (Star (Char d)) (Char c)))) = true.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"c\" =~ Star c: *)\n  Example test_der5 : match_eps (derive c (Star (Char c))) = true.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"cd\" =~ App (Char c) (Char d): *)\n  Example test_der6 :\n    match_eps (derive d (derive c (App (Char c) (Char d)))) = true.\n  Proof. simpl. reflexivity. Qed.\n\n  (* \"cd\" =~ App (Char d) (Char c): *)\n  Example test_der7 :\n    match_eps (derive d (derive c (App (Char d) (Char c)))) = false.\n  Proof. simpl. reflexivity. Qed.\n\nEnd DeriveTests.\n\nSearch (?s = nil ++ ?s).\n\nLemma derive_corr : derives derive.\nProof.\n  unfold derives, is_der.\n  intros a re.\n  generalize dependent a.\n  induction re as [ | | c | r1 IHl r2 IHr | r1 IHl r2 IHr | r IH].\n  - simpl. intros. split.\n    + intros H. inversion H.\n    + intros H. inversion H.\n  - simpl. intros. split.\n    + intros H. inversion H.\n    + intros H. inversion H.\n  - simpl. intros. split.\n    + intros H. inversion H. \n      destruct (eqb_spec c c).\n      * apply MEmpty.\n      * exfalso. apply n. reflexivity.\n    + intros H.\n      destruct (eqb_spec c a) as [Eca | Eca].\n      * rewrite <- Eca. \n        inversion H.\n        apply (MChar c).\n      * inversion H.\n  - simpl. intros. split.\nAdmitted.\n\n\nDefinition matches_regex m : Prop :=\n  forall (s : string) re, reflect (s =~ re) (m s re).\n\nFixpoint regex_match (s : string) (re : reg_exp ascii) : bool. Admitted.\n\nTheorem regex_refl : matches_regex regex_match.\nProof. Admitted.\n\nModule End.", "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/IndPropRegexp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.734469285408094}}
{"text": "Inductive bTree : Set :=\n  | bleaf : bool -> bTree\n  | bnode : (bool -> bool -> bool) -> bTree -> bTree -> bTree.\n\nCheck bleaf true.\nCheck bnode orb (bleaf true) (bnode andb (bleaf false) (bleaf true)).\n\n(* a *)\n\nFixpoint height (t:bTree) : nat :=\n  match t with\n    | bleaf b => 1\n    | bnode o bl br => 1 + max (height bl) (height br)\n  end.\n\nDefinition t1 := bnode orb (bleaf true) (bnode andb (bleaf false) (bleaf true)).\nDefinition t2 := bnode orb (bnode andb (bleaf true) (bleaf false)) (bleaf true).\n\nEval compute in height t1.\nEval compute in height t2.\n\n(* b *)\n\nFixpoint mirror (t:bTree) : bTree :=\n  match t with\n    | bleaf b => bleaf b\n    | bnode o bl br => bnode o (mirror br) (mirror bl)\n  end.\n\nEval simpl in mirror t1.\nEval simpl in mirror t2.\n\nPrint t1.\nPrint t2.\n\n(* c *)\n\nInductive hbTree : nat -> Set :=\n  | hleaf : bool -> hbTree 0\n  | hnode : forall n:nat, (bool->bool->bool) -> hbTree n -> hbTree n -> hbTree (S n).\n\nCheck hleaf true.\nCheck hnode 0 andb (hleaf true) (hleaf true).\nCheck hnode 1 andb (hnode 0 andb (hleaf true) (hleaf true)) (hnode 0 andb (hleaf true) (hleaf true)).\n\nFixpoint forgetful (n:nat) (t: hbTree n) : bTree :=\n  match t with\n    | hleaf b => bleaf b\n    | hnode m o bl br => bnode o (forgetful m bl) (forgetful m br)\n  end.\n\nEval compute in forgetful 0 (hleaf true).\nEval compute in forgetful 1 (hnode 0 andb (hleaf true) (hleaf true)).\nEval compute in forgetful 2 (hnode 1 andb (hnode 0 andb (hleaf true) (hleaf true)) (hnode 0 andb (hleaf true) (hleaf true))).\n", "meta": {"author": "mozow01", "repo": "bizcoq2021", "sha": "f98f22ba3ce80899bc88605ce3193d8972102c92", "save_path": "github-repos/coq/mozow01-bizcoq2021", "path": "github-repos/coq/mozow01-bizcoq2021/bizcoq2021-f98f22ba3ce80899bc88605ce3193d8972102c92/hallgatoi/gabormarton/bizcoq_3_hf_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7344692768448886}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_congruenceflip.\nRequire Import ProofCheckingEuclid.lemma_congruencesymmetric.\nRequire Import ProofCheckingEuclid.lemma_congruencetransitive.\nRequire Import ProofCheckingEuclid.lemma_extensionunique.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_rightreverse :\n\tforall A B C D,\n\tRightTriangle A B C ->\n\tBetS A B D ->\n\tCong A B B D ->\n\tCong A C D C.\nProof.\n\tintros A B C D.\n\tintros RightTriangle_ABC.\n\tintros BetS_A_B_D.\n\tintros Cong_AB_BD.\n\n\tdestruct RightTriangle_ABC as (E & BetS_A_B_E & Cong_AB_EB & Cong_AC_EC & _).\n\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_AB_BD) as Cong_BD_AB.\n\tpose proof (lemma_congruencetransitive _ _ _ _ _ _ Cong_BD_AB Cong_AB_EB) as Cong_BD_EB.\n\tpose proof (lemma_congruenceflip _ _ _ _ Cong_BD_EB) as (_ & _ & Cong_BD_BE).\n\tpose proof (lemma_extensionunique _ _ _ _ BetS_A_B_D BetS_A_B_E Cong_BD_BE) as eq_D_E.\n\tassert (Cong A C D C) as Cong_AC_DC by (rewrite eq_D_E; exact Cong_AC_EC).\n\n\texact Cong_AC_DC.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_rightreverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7344692756774424}}
{"text": "(** Proof that the square root of 2 is irrational *)\n\nRequire Import Coq.ZArith.Znumtheory.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Reals.Reals.\n\nOpen Scope Z_scope.\n\nLemma even_sqr_even :\n  forall n:Z, Zeven (n * n) -> Zeven n.\nProof.\n  intros.\n  apply Zeven_bool_iff in H.\n  apply Zeven_bool_iff.\n  rewrite Z.even_mul in H.\n  rewrite Bool.orb_diag in H.\n  apply H.\nQed.\n\nLemma even_not_rel_prime :\n  forall a b:Z, Zeven a /\\ Zeven b -> ~ rel_prime a b.\nProof.\n  intros.\n  destruct H as [ H_even_a H_even_b ].\n  assert (H_b_half_exists : exists b_half : Z, b = 2 * b_half).\n  apply Zeven_ex_iff.\n  apply H_even_b.\n  destruct H_b_half_exists as [ b_half H_b_half_b_eqn ].\n  assert (H_a_half_exists : exists a_half : Z, a = 2 * a_half).\n  apply Zeven_ex_iff.\n  apply H_even_a.\n  destruct H_a_half_exists as [ a_half H_a_half_a_eqn ].\n  rewrite H_b_half_b_eqn, H_a_half_a_eqn.\n  unfold rel_prime.\n  intro H_rel_prime.\n  remember (Z.gcd a_half b_half) as g.\n  assert (H_rel_prime' : Zis_gcd a_half b_half g).\n  rewrite Heqg.\n  apply Zgcd_is_gcd.\n  apply (Zis_gcd_mult _ _ 2 _) in H_rel_prime'.\n  apply Zis_gcd_gcd in H_rel_prime.\n  apply Zis_gcd_gcd in H_rel_prime'.\n  assert (H_1_eq_2_g : 1 = 2 * g).\n  congruence.\n  assert (H_1_neq_2_g : 1 <> 2 * g).\n  omega.\n  contradiction.\n  assert (H_g_nonneg : 0 <= g).\n  rewrite Heqg.\n  apply Z.gcd_nonneg.\n  omega.\n  discriminate.\nQed.\n\nTheorem sqrt_2_irrat :\n  (*\n    sqrt(2) = b / a\n    2 = (b * b) / (a * a)\n    b * b = 2 * a * a\n  *)\n  forall a b:Z, a <> 0 -> b * b = 2 * a * a /\\ rel_prime a b -> False.\nProof.\n  intros a b H_a_nonzero H.\n  destruct H as [ H_b_a_eqn H_rel_prime ].\n  assert (H_2_a_sqr_even : Zeven (2 * a * a)).\n  rewrite <- Z.mul_assoc.\n  apply Zeven_2p.\n  assert (H_b_sqr_even : Zeven (b * b)).\n  rewrite H_b_a_eqn.\n  apply H_2_a_sqr_even.\n  clear H_2_a_sqr_even.\n  assert (H_b_even : Zeven b).\n  apply even_sqr_even.\n  apply H_b_sqr_even.\n  clear H_b_sqr_even.\n  assert (H_c_exists : exists c : Z, b = 2 * c).\n  apply Zeven_ex_iff.\n  apply H_b_even.\n  destruct H_c_exists as [ c H_b_c_eqn ].\n  assert (H_c_a_eqn : 2 * c * c = a * a).\n  rewrite <- (Z.mul_cancel_l _ _ 2).\n  rewrite Z.mul_comm.\n  rewrite <- H_b_c_eqn.\n  replace (b * c * 2) with (b * (2 * c)) by ring.\n  rewrite <- H_b_c_eqn.\n  rewrite Z.mul_assoc.\n  apply H_b_a_eqn.\n  discriminate.\n  clear H_b_c_eqn.\n  assert (H_2_c_sqr_even : Zeven (2 * c * c)).\n  rewrite <- Z.mul_assoc.\n  apply Zeven_2p.\n  assert (H_a_sqr_even : Zeven (a * a)).\n  rewrite <- H_c_a_eqn.\n  apply H_2_c_sqr_even.\n  clear dependent c.\n  assert (H_a_even : Zeven a).\n  apply even_sqr_even.\n  apply H_a_sqr_even.\n  clear H_a_sqr_even.\n  assert (H_not_rel_prime : ~ rel_prime a b).\n  apply even_not_rel_prime.\n  auto.\n  contradiction.\nQed.\n", "meta": {"author": "io12", "repo": "coq-proofs", "sha": "62e0612980f25a3f31c2dedf2c7690757d797f31", "save_path": "github-repos/coq/io12-coq-proofs", "path": "github-repos/coq/io12-coq-proofs/coq-proofs-62e0612980f25a3f31c2dedf2c7690757d797f31/sqrt_2_irrat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210673, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7344235872021945}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export IndProp.\n\n(* a playground module that helps me to recall the refined reflection *)\nModule Silly.\n  Inductive reflect (P : Prop) : bool -> Set :=\n  | ReflectT : P -> reflect P true\n  | ReflectF : ~ P -> reflect P false.\n\n  Theorem eqb_natP : forall a b : nat, reflect (a = b) (a =? b).\n  Proof.\n    intros a b. destruct (a =? b) eqn:E.\n    - apply ReflectT. apply eqb_true. apply E.\n    - apply ReflectF. intro contra. rewrite contra in E.\n      rewrite eqb_refl in E. discriminate E. Qed.\n\n  Theorem silly_refl : forall n : nat, n =? n = true.\n  Proof.\n    intros n. Show Proof. destruct (eqb_natP n n). Show Proof.\n    - reflexivity. Show Proof.\n    - exfalso. Show Proof.\n      apply n0. Show Proof. reflexivity. Show Proof. Qed.\nEnd Silly.\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof. apply ev_SS.\n  Show Proof. apply ev_SS.\n  Show Proof. apply ev_0.\n  Show Proof. Qed.\n\nTheorem ev_8 : ev 8.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_SS. apply ev_SS. apply ev_0.\nQed.\n\nDefinition ev_8' : ev 8 := (ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0)))).\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. apply ev_SS. apply ev_SS.\n  apply H. Show Proof. Qed.\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) (H : ev n) => (ev_SS (S (S n)) (ev_SS n H)).\n\nDefinition add1 : nat -> nat.\n  intro n. Show Proof.\n  apply S. Show Proof.\n  apply n. Show Proof.\nDefined.\n\nPrint add1.\n\nModule Props.\n  Module And.\n    Inductive and (P Q : Prop) : Prop :=\n    | conj : P -> Q -> and P Q.\n\n    Arguments conj [P] [Q].\n    Notation \"P /\\ Q\" := (and P Q) : type_scope.\n\n    Theorem proj1' : forall P Q, P /\\ Q -> P.\n    Proof.\n      intros P Q H. destruct H as [HP HQ]. apply HP.\n      Show Proof. Qed.\n\n    Lemma and_comm : forall P Q, P /\\ Q <-> Q /\\ P.\n    Proof.\n      intros P Q. Show Proof. split. Show Proof.\n      - intro H. Show Proof. destruct H as [HP HQ]. Show Proof.\n        split. Show Proof.\n        + apply HQ. Show Proof.\n        + apply HP. Show Proof.\n      - intros [HQ HP]. split.\n        + apply HP.\n        + apply HQ. Show Proof. Qed.\n  End And.\n\n  Definition and_comm'_aux (P Q : Prop) (H : P /\\ Q) : Q /\\ P :=\n    match H with\n    | conj HP HQ => conj HQ HP\n    end.\n\n  Check and_comm'_aux.\n\n  Definition and_comm' : forall (P Q : Prop), P /\\ Q <-> Q /\\ P.\n    split.\n    - intro H. apply (and_comm'_aux P Q). apply H.\n    - intro H. apply (and_comm'_aux Q P). apply H. Defined.\n\n  Definition and_comm'' : forall (P Q : Prop), P /\\ Q <-> Q /\\ P :=\n    fun (P Q : Prop) => conj (fun H : P /\\ Q => and_comm'_aux P Q H)\n                        (fun H : Q /\\ P => and_comm'_aux Q P H).\n\n  (* Currying is brilliant! *)\n  Definition and_comm''' (P Q : Prop) : P /\\ Q <-> Q /\\ P :=\n    conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n  Definition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n    fun P Q R => (fun HPQ : P /\\ Q =>\n                 match HPQ with\n                 | conj HP _ =>\n                   (fun HQR : Q /\\ R =>\n                      match HQR with\n                      | conj _ HR => conj HP HR\n                      end)\n                 end).\n\n  Module Or.\n    Inductive or (P Q : Prop) : Prop :=\n    | or_introl : P -> or P Q\n    | or_intror : Q -> or P Q.\n\n    Arguments or_introl [P] [Q].\n    Arguments or_intror [P] [Q].\n    Notation \"P \\/ Q\" := (or P Q) : type_scope.\n\n    Definition inj_l : forall P Q : Prop, P -> P \\/ Q :=\n      fun P Q : Prop => fun HP : P => or_introl HP.\n\n    Theorem inj_j' : forall P Q : Prop, P -> P \\/ Q.\n    Proof.\n      intros P Q HP. Show Proof. left. (* selects the `or_introl` constructor *)\n      Show Proof. apply HP. Qed.\n\n    Definition or_elim : forall (P Q R : Prop), P \\/ Q -> (P -> R) -> (Q -> R) -> R :=\n      fun P Q R (H : P \\/ Q) (HPR : P -> R) (HQR : Q -> R) =>\n        match H with\n        | or_introl HP => HPR HP\n        | or_intror HQ => HQR HQ\n        end.\n  End Or.\n\n  Definition or_commut' : forall P Q, P \\/ Q -> Q \\/ P :=\n    fun P Q (H : P \\/ Q) =>\n      match H with\n      | or_introl HP => (@or_intror Q P) HP\n      | or_intror HQ => (@or_introl Q P) HQ\n      end.\n\n  Module Ex.\n    (* ex: \"Show me a witness of the Prop, and I'll know there\n            exists something that witnesses the Prop...\" *)\n    Inductive ex {A : Type} (P : A -> Prop) : Prop :=\n    | ex_intro (x : A) : P x -> ex P.\n\n    Notation \"'exists' x , p\" :=\n      (ex (fun x => p)) (at level 200, right associativity) : type_scope.\n  End Ex.\n\n  Check @ex.\n  Check @ex_intro.\n\n  Check ex (fun n => ev n) : Prop.\n  Definition some_nat_is_even : exists n, ev n :=\n    ex_intro ev 0 ev_0.\n\n  Definition ex_ev_Sn : ex (fun n => ev (S n)) :=\n    ex_intro (fun n => ev (S n)) 1 (ev_SS 0 ev_0).\n\n  Inductive True : Prop :=\n  | I : True.\n\n  Definition p_implies_true : forall P : Prop, P -> True :=\n    fun P (_ : P) => I.\n\n  Inductive False : Prop :=.\n\n  Definition ex_falso_quodlibet' : forall P, False -> P :=\n    fun P (contra : False) =>\n      match contra with end.\nEnd Props.\n\nModule MyEquality.\n  Inductive eq {X : Type} : X -> X -> Prop :=\n  | eq_refl : forall (x : X), eq x x.\n\n  Notation \"x == y\" := (eq x y) (at level 70, no associativity).\n\n  Definition singleton : forall (X : Type) (x : X), [] ++ [x] == x :: [] :=\n    fun X x => eq_refl [x].\n\n  Lemma equality__leibniz_equality : forall (X : Type) (x y : X),\n      x == y -> forall (P : X -> Prop), P x -> P y.\n  Proof.\n    intros X x y [x_y] P HPx. apply HPx. Qed.\n\n  Lemma leibniz_equality__equality : forall (X : Type) (x y : X),\n      (forall P : X -> Prop, P x -> P y) -> x == y.\n  Proof.\n    intros X x y Leib. apply (Leib (eq x)).\n    apply (eq_refl x). Qed.\n\n  Theorem try_leibniz_refl : forall (X : Type) (x y : X),\n      (forall P : X -> Prop, P x -> P y) -> (forall P : X -> Prop, P y -> P x).\n  Proof.\n    intros X x y Hxy P.\n    apply (Hxy (fun t : X => P t -> P x)).\n    intro H. apply H.\n  Qed.\nEnd MyEquality.\n", "meta": {"author": "duinomaker", "repo": "LearningStuff", "sha": "73410047a0d9ee36e54580ee9d22460037b7459c", "save_path": "github-repos/coq/duinomaker-LearningStuff", "path": "github-repos/coq/duinomaker-LearningStuff/LearningStuff-73410047a0d9ee36e54580ee9d22460037b7459c/LogicalFoundations/ch9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7343644086215487}}
{"text": "(*This file contains two theorems: forward and backward error bounds for \n  the sum of two floating point lists; the functional model for\n  the summation is defined in sum_model.v.*)\n\nRequire Import vcfloat.VCFloat.\nRequire Import List.\nImport ListNotations.\nRequire Import common sum_model float_acc_lems op_defs list_lemmas.\n\nRequire Import Reals.\nOpen Scope R.\n\n\nSection NAN.\nVariable NAN: Nans.\n\nLemma sum_forward_error :\n  forall (t: type) (l: list (ftype t))\n  (Hlen: (1 <= length l)%nat)\n  (fs : ftype t) (rs rs_abs : R)\n  (Hfs: sum_rel_Ft t l fs)\n  (Hrs: sum_rel_R (map FT2R l) rs)\n  (Hra: sum_rel_R (map Rabs (map FT2R l)) rs_abs)\n  (Hin: forall a, In a l ->  Binary.is_finite _ _ a = true)\n  (Hfin: Binary.is_finite (fprec t) (femax t) fs = true),\n  Rabs (rs - FT2R fs) <= g t (length l -1) * rs_abs.\nProof.\ninduction l.\n{ simpl; intros; pose proof (Nat.nle_succ_0 0); try contradiction. } \n(* case a::l *)\nintros.\nassert (Hl: l = [] \\/ l <> []).\ndestruct l; auto.\nright.\neapply hd_error_some_nil; simpl; auto.\ndestruct Hl.\n(* case empty l *)\n{ assert (HFINa: \n  Binary.is_finite (fprec t) (femax t) a = true) by (apply Hin; simpl; auto).\n  assert (HFINfs: \n  Binary.is_finite (fprec t) (femax t) fs = true).\n  { subst. inversion Hfs. fold (@sum_rel_Ft NAN t) in H2. inversion H2. subst.\n  destruct a; simpl; try discriminate; auto. } \n  subst; simpl; pose proof (sum_rel_Ft_single t fs a HFINfs Hfs); subst.\n  rewrite (sum_rel_R_single (FT2R a) rs Hrs); subst.\n  unfold g; simpl; field_simplify_Rabs;\n  rewrite Rabs_R0; nra. }\n(* case non-empty l *)\ninversion Hfs; fold (@sum_rel_Ft NAN t) in H3. \ninversion Hrs; fold sum_rel_R in H7.\ninversion Hra; fold sum_rel_R in H11.\nsubst; unfold sum in *.\nassert (HFINa: \n  Binary.is_finite (fprec t) (femax t) a = true) by (apply Hin; simpl; auto).\n(* IHl *)\npose proof (length_not_empty_nat l H) as Hlen1.\nassert (Hinl: forall a : ftype t,\n       In a l -> Binary.is_finite (fprec t) (femax t) a = true).\n{ intros; apply Hin; simpl; auto. }\nassert (Hfins: Binary.is_finite (fprec t) (femax t) s = true).\n{ destruct a, s; simpl in *; try discriminate; auto. }\nspecialize (IHl Hlen1 s s0 s1 H3 H7 H11 Hinl Hfins).\n(* accuracy rewrites *)\nassert (Hov: Bplus_no_overflow t (FT2R a) (FT2R s)).\n{ unfold Bplus_no_overflow. pose proof is_finite_sum_no_overflow t.\n  simpl in H0; unfold rounded in H0; eapply H0; auto. }\npose proof (BPLUS_accurate t a HFINa s Hfins Hov) as Hplus.\ndestruct Hplus as (d' & Hd'& Hplus); rewrite Hplus; \n  clear Hplus Hov.\n(* algebra *)\nfield_simplify_Rabs.\nreplace (- FT2R a * d' + s0 - FT2R s * d' - FT2R s) with\n  ((s0 - FT2R s) - d' * (FT2R s + FT2R a)) by nra.\neapply Rle_trans; \n  [ apply Rabs_triang | eapply Rle_trans; [ apply Rplus_le_compat_r\n    | rewrite !Rabs_Ropp] ].\napply IHl.\neapply Rle_trans; \n  [apply Rplus_le_compat_l | ].\n  rewrite Rabs_mult. apply Rmult_le_compat; try apply Rabs_pos.\n  apply Hd'.\n  eapply Rle_trans; [apply Rabs_triang | apply Rplus_le_compat_r].\n  rewrite Rabs_minus_sym in IHl; apply Rabs_le_minus in IHl. apply IHl.\nrewrite !Rmult_plus_distr_l; rewrite <- !Rplus_assoc.\nreplace (g t (length l - 1) * s1 + default_rel t * (g t (length l - 1) * s1)) with\n  ((1+ default_rel t) * g t (length l - 1) * s1) by nra.\neapply Rle_trans; [apply Rplus_le_compat_r; \n  apply Rplus_le_compat_l; apply Rmult_le_compat_l; try apply Rabs_pos|].\napply default_rel_ge_0.\napply (sum_rel_R_Rabs (map FT2R l)); auto; apply H11.\nrewrite (sum_rel_R_Rabs_eq (map FT2R l)); auto.\nrewrite one_plus_d_mul_g. simpl.\nrewrite Rplus_comm.\napply Rplus_le_compat.\napply Rmult_le_compat; try apply Rabs_pos; \n  try apply default_rel_ge_0; try nra.\napply d_le_g_1; try lia.\napply Req_le; f_equal. f_equal; lia.\nQed.\n\nLemma sum_backward_error :\n  forall (t: type) (l: list (ftype t))\n  (Hlen: (1 <= length l)%nat)\n  (fs : ftype t) (rs : R)\n  (Hfs: sum_rel_Ft t l fs)\n  (Hrs: sum_rel_R (map FT2R l) rs)\n  (Hin: forall a, In a l ->  Binary.is_finite _ _ a = true)\n  (Hfin: Binary.is_finite (fprec t) (femax t) fs = true),\n    exists (l': list R), \n    length l' = length l /\\\n    sum_rel_R l' (FT2R fs) /\\\n    (forall n, (n <= length l')%nat -> exists delta, \n        nth n l' 0 = FT2R (nth n l neg_zero) * (1 + delta) /\\ Rabs delta <= g t (length l' - 1)).\nProof.\nintros ? ?. induction l.\n{ simpl; intros; pose proof (Nat.nle_succ_0 0); try contradiction. } \n(* case a::l *)\nintros.\nassert (Hl: l = [] \\/ l <> []).\ndestruct l; auto.\nright.\neapply hd_error_some_nil; simpl; auto.\ndestruct Hl.\n(* case empty l *)\n{ assert (HFINa: \n  Binary.is_finite (fprec t) (femax t) a = true) by (apply Hin; simpl; auto).\n  assert (HFINfs: \n  Binary.is_finite (fprec t) (femax t) fs = true).\n  { subst. inversion Hfs. fold (@sum_rel_Ft NAN t) in H2. inversion H2. subst.\n  destruct a; simpl; try discriminate; auto. } \n  inversion Hfs. inversion Hrs; subst. inversion H3. subst. inversion H7; subst.\n  unfold sum in Hrs; simpl in Hrs; rewrite Rplus_0_r in Hrs.\n  exists [FT2R a]; repeat split.\n  simpl; auto. unfold sum. rewrite BPLUS_neg_zero; auto.\n  intros. exists 0; split; auto. rewrite Rplus_0_r. rewrite Rmult_1_r.\n  replace [FT2R a] with (map FT2R [a]) by (simpl; auto).\n  replace 0 with (@FT2R t neg_zero) by (unfold neg_zero; simpl; auto).\n  rewrite map_nth; auto.\n  unfold g. simpl. rewrite Rabs_R0; nra.\n}\n(* case non-empty l *)\ninversion Hfs; fold (@sum_rel_Ft NAN t) in H3. \ninversion Hrs; fold sum_rel_R in H7.\nsubst; unfold sum in *.\nassert (HFINa: \n  Binary.is_finite (fprec t) (femax t) a = true) by (apply Hin; simpl; auto).\n(* IHl *)\npose proof (length_not_empty_nat l H) as Hlen1.\nassert (Hinl: forall a : ftype t,\n       In a l -> Binary.is_finite (fprec t) (femax t) a = true).\n{ intros; apply Hin; simpl; auto. }\nassert (Hfins: Binary.is_finite (fprec t) (femax t) s = true).\n{ destruct a, s; simpl in *; try discriminate; auto. }\nspecialize (IHl Hlen1 s s0 H3 H7 Hinl Hfins).\ndestruct IHl as (l' & Hlen' & Hsum & Hdel).\n(* construct l'0 *)\nassert (Hov: Bplus_no_overflow t (FT2R a) (FT2R s)).\n{ unfold Bplus_no_overflow. pose proof is_finite_sum_no_overflow t.\n  simpl in H0; unfold rounded in H0; eapply H0; auto. }\npose proof (BPLUS_accurate t a HFINa s Hfins Hov) as Hplus.\ndestruct Hplus as (d' & Hd'& Hplus).\nexists (FT2R a * (1+d') :: map (Rmult (1+d')) l'); repeat split.\n{ simpl; auto. rewrite map_length; auto. }\n{ rewrite Hplus. unfold sum_rel_R. \n  rewrite Rmult_plus_distr_r. apply sum_rel_cons. rewrite Rmult_comm; apply sum_map_Rmult; auto. }\nintros. destruct n. \n{ simpl. exists d'; split; auto.\n  eapply Rle_trans; [apply Hd'| ]. apply d_le_g_1. rewrite map_length; auto.\n  rewrite Hlen'. lia. }\nsimpl in H0; rewrite map_length in H0; rewrite Hlen' in H0.\nassert (Hlen2: (n <= length l')%nat) by lia.\nspecialize (Hdel n Hlen2).\ndestruct Hdel as (d & Hd1 & Hd2).\nexists ( (1+d') * (1+d) -1). simpl; split.\n{ replace 0 with (Rmult (1 + d') 0) by nra. rewrite map_nth; rewrite Hd1; nra. }\nrewrite map_length. field_simplify_Rabs. \n  eapply Rle_trans; [apply Rabs_triang | eapply Rle_trans; [apply Rplus_le_compat_r; apply Rabs_triang | ]  ].\nrewrite Rabs_mult.\nreplace (Rabs d' * Rabs d + Rabs d' + Rabs d ) with\n  ((1 + Rabs d') * Rabs d + Rabs d' ) by nra.\neapply Rle_trans; [apply Rplus_le_compat | ].\napply Rmult_le_compat; try apply Rabs_pos.\napply Fourier_util.Rle_zero_pos_plus1; try apply Rabs_pos.\napply Rplus_le_compat_l; apply Hd'.\napply Hd2. apply Hd'.\nreplace ((1 + default_rel t) * g t (length l' - 1) + default_rel t) with\n((1 + default_rel t) * g t (length l' - 1) * 1 + default_rel t * 1) by nra.\nrewrite one_plus_d_mul_g; apply Req_le; rewrite Rmult_1_r. f_equal; lia.\nQed.\n\n\nEnd NAN.", "meta": {"author": "VeriNum", "repo": "iterative_methods", "sha": "7507d713cceaf91d9493dab620d3583438b8bc8a", "save_path": "github-repos/coq/VeriNum-iterative_methods", "path": "github-repos/coq/VeriNum-iterative_methods/iterative_methods-7507d713cceaf91d9493dab620d3583438b8bc8a/StationaryMethods/sum_acc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7343643961104652}}
{"text": "Require Import EqNat.\n\n(** * Hypermaps in Coq *)\n(** ** Dimensions\n  We define dimensions inductively. As there are only two dimensions to be considered, we just define two branches: 0 and 1.\n*)\nInductive dimension: Set :=\n| zero: dimension\n| one: dimension.\n\n(** We then prove that equality of dimensions is decidable i.e. either two dimensions\n    are equal or they are not equal. Logic in Coq is constructive, we need to prove\n    seperately, even though it may seem trivial\n*)\nTheorem eq_dimension_decide: forall p q: dimension,\n  {p = q} + {p <> q}.\nProof.\n  intros.\n  destruct p, q;\n  try(left; reflexivity);\n  right; intro; discriminate.\nQed.\n\n(** ** Darts\n  Darts we simply encode as natural numbers.\n*)\n\nDefinition dart := nat.\nDefinition eq_dart_decide := eq_nat_decide.\nDefinition nil := 0.\n\n(** We set aside 0 for the [nil] dart. We use the [nil] dart for exceptions later on. *)\n\n(** ** Free Maps\n  Before going into hypermaps we first define a collection of darts we call a free map.\n  We will use this definition of free maps, and some propositions to define hyper maps.\n  A Free Map we define inductively as either a empty free map, or a free map with a dart\n  inserted into it, or a free map with two darts joined in a specified dimension.\n  *)\n\nInductive free_map: Set :=\n(* void(empty) free map *)\n| V: free_map\n(* inserting dart d into free map f *)\n| I(f: free_map)(d: dart): free_map\n(* linking darts d1 and d2, of free map f, in dimension d *)\n| L(f: free_map)(dim: dimension)(d1 d2: dart): free_map.\n\n(** Then we define [dart_exists] which checks if a dart is in a map *)\n\nFixpoint dart_exists (d: dart) (f: free_map): Prop :=\n  match f with\n  | V => False\n  | I f' d' => d = d' \\/ dart_exists d f'\n  | L f' _ _ _ => dart_exists d f'\n  end.\n\n(** We then prove decidability of [dart_exists]: either a dart exists in a map,\n  or it doesn't\n*)\n\nTheorem dart_exists_is_decidable: forall d m,\n  {dart_exists d m} + {~dart_exists d m}.\nProof.\n  intros.\n  induction m; simpl.\n  - right. intro. assumption.\n  - destruct IHm.\n    + left. right. assumption.\n    + destruct (eq_dart_decide d d0) as [H1 | H1].\n      * apply (eq_nat_eq d d0) in H1.\n        left. left. assumption.\n      * unfold not in H1.\n        right.\n        intro.\n        destruct H.\n        -- apply H1. apply eq_eq_nat. assumption.\n        -- apply n. assumption.\n  - assumption.\nQed.\n\nFixpoint A (f: free_map)(k: dimension)(d: dart) :=\n  match f with\n  | V => nil\n  | I f' _ => A f' k d\n  | L f' k' d1 d2 =>\n      if (eq_dimension_decide k k') then\n        if (eq_dart_decide d d1) then\n          d2\n        else\n          A f' k d\n      else\n        A f' k d\n  end.\n\nFixpoint A_inv (f: free_map)(k: dimension)(d: dart) :=\n  match f with\n  | V => nil\n  | I f' _ => A_inv f' k d\n  | L f' k' d1 d2 =>\n      if (eq_dimension_decide k k') then\n        if (eq_dart_decide d d2) then\n          d1\n        else\n          A_inv f' k d\n      else\n        A_inv f' k d\n  end.\n\n", "meta": {"author": "wags-1314", "repo": "coq-hypermaps", "sha": "eca9672061f91ce05869436ba4eb2eb5b5f99a60", "save_path": "github-repos/coq/wags-1314-coq-hypermaps", "path": "github-repos/coq/wags-1314-coq-hypermaps/coq-hypermaps-eca9672061f91ce05869436ba4eb2eb5b5f99a60/hypermap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7342856553573119}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_parallelsymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_parallelflip.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral}.\n\nLemma lemma_PGrotate : \n   forall A B C D, \n   PG A B C D ->\n   PG B C D A.\nProof.\nintros.\nassert ((Par A B C D /\\ Par A D B C)) by (conclude_def PG ).\nassert (Par B C A D) by (conclude lemma_parallelsymmetric).\nassert (Par B C D A) by (forward_using lemma_parallelflip).\nassert (Par B A C D) by (forward_using lemma_parallelflip).\nassert (PG B C D A) by (conclude_def PG ).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_PGrotate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7342583451640257}}
{"text": "Require Export Untyped.\nRequire Import Omega.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Plus.\nRequire Import Coq.Arith.Lt.\n\n(** (l)ift (t)erms by some (l)evel if greater or equal the (b)ound **)\n\nFixpoint lift (l: nat) (b: nat) (t: lterm) : lterm :=\n  match t with\n      | Var i as v =>  if (lt_dec i b) then v else Var (i+l)\n      | App m n => App (lift l b m) (lift l b n)\n      | Lam t => Lam (lift l (b+1) t)\n  end.\n\nDefinition shift (b: nat) (t: lterm) : lterm :=\n  lift 1 b t.\n\n(** Substitute the variable with index [v] by [r] in the term [t] **)\n\nFixpoint subst (v: nat) (r: lterm) (t: lterm) : lterm :=\n  match t with\n      | Var i =>  match (nat_compare i v) with\n                           | Lt => Var i\n                           | Eq => lift v 0 r\n                           | Gt => Var (i - 1)\n                  end\n      | App m n => App (subst v r m) (subst v r n)\n      | Lam m => Lam (subst (v+1) r m)\n  end.\n\nLemma lift_0_ident:\n  forall M, forall b,\n    lift 0 b M = M.\nProof.\n  induction M.\n  intros. simpl. replace (n + 0) with n. case (lt_dec n b).\n     reflexivity. reflexivity.\n     auto.\n  simpl. intros. rewrite IHM. reflexivity.\n  simpl. intros. rewrite IHM1. rewrite IHM2. reflexivity.\nQed.\n\n\n(** The following lemmas are described in Berghofer and Urban, who\n    seem to trace down these due to Huet\n*)\n\nLemma lift_fuse:\n  forall (N: lterm) (i j n m: nat),\n    i <= j <= i + m -> lift n j (lift m i N) = lift (n+m) i N.\nProof.\n  induction N as [k | N1 N2 | N1].\n    (* N := Var k *)\n    intros. simpl. case_eq (lt_dec k i).\n      (* k < i *)\n      intros. simpl. assert (k < j).\n          apply lt_le_trans with i. assumption. apply H.\n          destruct (lt_dec k j). reflexivity. contradict H1. auto.\n      (* k >= i *)\n      intros. simpl.\n          destruct (lt_dec (k+m) j). contradict l. omega. apply f_equal.\n          omega.\n    (* N := Lam .. *)\n    intros. simpl. apply f_equal. rewrite N2. reflexivity. omega.\n    (* N := App .. .. *)\n    intros. simpl. rewrite IHN1. rewrite IHN2. auto. auto. auto.\nQed.\n\nLemma lift_lem2:\n  forall (N L: lterm) (i j k: nat),\n  k <= j -> lift i k (subst j L N) = subst (j+i) L (lift i k N).\nProof.\n  induction N as [v | N' | N1 ].\n    (* N := Var v *)\n    intros. simpl. case_eq (nat_compare v j).\n      (* v Eq j *)\n      intros. apply nat_compare_eq in H0. rewrite lift_fuse.\n      destruct (lt_dec v k).\n        (* v < k *)\n        simpl. case_eq (nat_compare v (j + i)).\n          (* Eq *)\n          rewrite plus_comm. reflexivity.\n          (* Lt *)\n          contradict l. omega.\n          (* Gt *)\n          intros. apply nat_compare_gt in H1. contradict H1. omega.\n        (* ~ v < k *)\n        simpl. case_eq (nat_compare (v+i) (j+i)).\n          (* Eq *)\n          intros. rewrite plus_comm. reflexivity.\n          (* Lt *)\n          intros. apply nat_compare_lt in H1. contradict H1. omega.\n          (* Gt *)\n          intros. apply nat_compare_gt in H1. contradict H1. omega.\n        split. omega. omega.\n      (* v Lt j *)\n      intros. apply nat_compare_lt in H0. destruct (lt_dec v k).\n        (* v < k *)\n        simpl. destruct (lt_dec v k).\n          (* v < k *)\n          case_eq (nat_compare v (j + i)).\n            (* Eq *)\n            intros. apply nat_compare_eq in H1. contradict H0. omega.\n            (* Lt *)\n            intros. reflexivity.\n            (* Gt *)\n            intros. apply nat_compare_gt in H1. contradict H1. omega.\n          (* ~ v < k *)\n          contradiction.\n        (* ~ v < k *)\n        simpl. destruct (lt_dec v k).\n          (* v < k *)\n          contradiction.\n          (* ~ v < k *)\n          case_eq (nat_compare (v+i) (j+i)).\n            (* Eq *)\n            intros. apply nat_compare_eq in H1. contradict H0. omega.\n            (* Lt *)\n            intros. reflexivity.\n            (* Gt *)\n            intros. apply nat_compare_gt in H1. contradict H0. omega.\n      (* v Gt j *)\n      intros. apply nat_compare_gt in H0. simpl. destruct (lt_dec (v - 1) k).\n        (* v - 1 < k *)\n        contradict l. omega.\n        (* ~ v - 1 < k *)\n        destruct (lt_dec v k).\n          (* v < k *)\n          contradict l. omega.\n          (* ~ v < k *)\n          simpl. case_eq (nat_compare (v + i) (j + i)).\n            (* Eq *)\n            intros. apply nat_compare_eq in H1. contradict H0. omega.\n            (* Lt *)\n            intros. apply nat_compare_lt in H1. contradict H0. omega.\n            (* Gt *)\n            intros. apply nat_compare_gt in H1. f_equal. omega.\n    (* N := Lam N' *)\n    intros. simpl. f_equal.\n    assert (U: j + 1 + i = j + i + 1). omega. rewrite <- U.\n    apply (IHN' L i (j+1) (k+1)). omega.\n    (* N := App N1 N2 *)\n    intros. simpl. f_equal.\n    apply IHN1. assumption.\n    apply IHN2. assumption.\nQed.\n\nLemma lift_lem3:\n  forall (L P: lterm) (i j k: nat),\n  k <= i < k + (j + 1) -> subst i P (lift (j+1) k L) = lift j k L.\nProof.\n  intro L. induction L.\n  intros. simpl. destruct (lt_dec n k).\n    intros. simpl. assert (n < i). apply lt_le_trans with k. assumption. apply H.\n    apply nat_compare_lt in H0. rewrite H0. reflexivity.\n\n    simpl. apply not_lt in n0. assert (i < n + (j + 1)). omega.\n     apply nat_compare_gt in H0. rewrite H0. apply f_equal. omega.\n\n  intros. simpl. apply f_equal. apply IHL. omega.\n  intros. simpl. rewrite IHL1. rewrite IHL2. reflexivity.\n  auto. auto.\nQed.\n\n(** We now proceed to prove the substitution lemma **)\n\n(* variable case of the substitution lemma *)\nLemma var_subst_lemma: forall (i j n: nat), forall (N L: lterm),\n   (i <= j) ->\n       subst j L (subst i N (Var n)) =\n                 subst i (subst (j-i) L N) (subst (j+1) L (Var n)).\nProof.\n  intros. simpl. case_eq (nat_compare n i).\n  (* n = i *)\n    intros. simpl. apply nat_compare_eq in H0. rewrite H0. simpl.\n    assert (i < j + 1). omega. apply nat_compare_lt in H1. rewrite H1.\n    simpl. assert (i = i). reflexivity. apply nat_compare_eq_iff in H2.\n    rewrite H2. clear H1 H2. rewrite lift_lem2.\n    assert (Jeq: j - i + i = j). omega. rewrite Jeq. reflexivity. omega.\n  (* n < i *)\n    simpl. intros. apply nat_compare_lt in H0.\n    assert (n < j). omega. assert (n < j + 1). omega.\n    apply nat_compare_lt in H0.\n    apply nat_compare_lt in H1.\n    apply nat_compare_lt in H2.\n    rewrite  H1, H2. simpl. rewrite H0. reflexivity.\n  (* n > i *)\n    intros.\n    apply nat_compare_gt in H0.\n    case_eq (nat_compare n (j + 1)).\n      (* n = j + 1 *)\n      intros. apply nat_compare_eq in H1. rewrite H1.\n      assert (Jeq: j + 1 - 1 = j). omega. rewrite Jeq. simpl.\n      assert (HH: nat_compare j j = Eq). assert (JJ: j = j). reflexivity.\n          apply nat_compare_eq_iff in JJ. assumption.\n      rewrite HH. rewrite lift_lem3. reflexivity. omega.\n      (* n < j + 1 *)\n      intros. apply nat_compare_lt in H1. simpl.\n      assert (HLt: nat_compare (n-1) j = Lt).\n        assert (n - 1 < j). omega. apply nat_compare_lt in H2. assumption.\n        rewrite HLt.\n      assert (Hgt: nat_compare n i = Gt).\n        apply nat_compare_gt in H0. assumption.\n        rewrite Hgt.\n      reflexivity.\n      (* n > j + 1 *)\n      intros. apply nat_compare_gt in H1. simpl.\n      assert (Ineq1: nat_compare (n - 1) j = Gt).\n        assert (F: n - 1 > j). omega.\n        apply nat_compare_gt in F. assumption. rewrite Ineq1.\n      assert (Ineq2: nat_compare (n - 1) i = Gt).\n        assert (n - 1 > i). omega. apply nat_compare_gt in H2. assumption.\n        rewrite Ineq2.\n      reflexivity.\nQed.\n\n\n(** The substitution lemma.\n    The named version looks like this:\n\n       [x =/= y] and [x] not free in [L] implies:\n           [M[x/N][y/L] = M[y/L][x/(N[y/L])]\n**)\n\nLemma subst_lemma: forall (M N L: lterm), forall (i j: nat),\n   (i <= j) ->\n       subst j L (subst i N M) = subst i (subst (j-i) L N) (subst (j+1) L M).\nProof.\n  induction M.\n  intros. intros. apply var_subst_lemma. assumption.\n  intros. simpl. apply f_equal. rewrite IHM.\n  assert (AllGood: j + 1 - (i + 1) = j - i). omega.\n  rewrite AllGood. reflexivity. omega.\n  intros. simpl. rewrite IHM1. rewrite IHM2. reflexivity.\n  auto. auto.\nQed.\n\n(** A few other useful lemmas about [lift] and [subst]. **)\n\n(** Attempting to substitute a variable with index [k] in a term which is\n    already shifted by [k] simply un-shifts the term: **)\n\nLemma subst_shift_ident:\n    forall t, forall k v,\n    subst k v (shift k t) =  t.\nProof.\n  induction t.\n  unfold shift. intros.\n  simpl.\n  case_eq (lt_dec n k).\n  intros. simpl. clear H. rewrite nat_compare_lt in l. rewrite l.\n  reflexivity.\n  intros. simpl.\n  case_eq (nat_compare (n+1) k). intros. apply nat_compare_eq_iff in H0. omega.\n  intros. apply nat_compare_lt in H0. omega.\n  intros. f_equal. omega.\n\n  intros. simpl. f_equal.\n  apply IHt.\n\n  intros. simpl. f_equal. apply IHt1. apply IHt2.\nQed.\n\n(** Similarly, if the variable we're substituting in is [Var 0], then\n    it gets unshifted even more: **)\n\nLemma subst_k_shift_S_k:\n    forall t, forall k,\n    subst k (Var 0) (shift (S k) t) = t.\nProof.\n  induction t.\n  unfold shift. simpl.\n  case_eq (lt_dec n 1).\n  intros. simpl. assert (HH: n = 0). omega.\n  rewrite HH. simpl.\n  case_eq (lt_dec k 1).\n  intros. simpl. assert (HHH: k = 0). omega.\n  rewrite HHH. reflexivity.\n  intros.\n  case_eq (lt_dec 0 k).\n  intros. simpl. destruct k.\n  reflexivity. reflexivity.\n  intros. omega.\n\n  intros.\n  case_eq (lt_dec n k).\n  intros. simpl.\n  case_eq (nat_compare n k).\n  intros. apply nat_compare_eq_iff in H1. f_equal. auto.\n  rewrite H1.\n  case_eq (lt_dec k (S k)).\n  intros. simpl. replace (nat_compare k k) with Eq. reflexivity.\n  symmetry. apply nat_compare_eq_iff. reflexivity.\n  intros. omega. intros. apply nat_compare_lt in H1.\n  case_eq (lt_dec n (S k)).\n  intros. simpl.\n  replace (nat_compare n k) with Lt. reflexivity.\n  symmetry. apply nat_compare_lt. assumption.\n  intros. omega. intros. apply nat_compare_gt in H1. omega.\n  intros.\n  case_eq (lt_dec n (S k)).\n  intros. assert (n = k). omega. rewrite H2.\n  simpl. replace (nat_compare k k) with Eq.\n  reflexivity. symmetry. apply nat_compare_eq_iff. reflexivity.\n  intros. simpl.\n  replace (nat_compare (n+1) k) with Gt. f_equal. omega.\n  symmetry. apply nat_compare_gt. omega.\n\n\n  intros. simpl. f_equal. apply IHt.\n\n  intros. simpl. f_equal. apply IHt1. apply IHt2.\nQed.\n\n(** Given compatible bounds, a sequence of [lift]s commutes in a very specific\n    way: **)\n\nLemma lift_lift:\n    forall M, forall b1 b2 k1 k2,\n      b1 <= b2 ->\n      lift k1 b1 (lift k2 b2 M) = lift k2 (k1 + b2) (lift k1 b1 M).\nProof.\n  induction M.\n  intros.\n  simpl.\n  case_eq (lt_dec n b1).\n  intros.\n  case_eq (lt_dec n b2).\n  intros.\n  simpl. rewrite H0.\n  case_eq (lt_dec n (k1 + b2)).\n  intros. reflexivity.\n  intros. omega.\n  intros. omega.\n\n  intros.\n  case_eq (lt_dec n b2).\n  intros. simpl.\n  rewrite H0.\n  case_eq (lt_dec (n+k1) (k1+b2)).\n  intros. reflexivity.\n  intros. omega.\n  intros. simpl.\n  case_eq (lt_dec (n+k2) b1).\n  intros. omega. intros.\n  case_eq (lt_dec (n+k1) (k1+b2)).\n  intros. omega.\n  intros. f_equal. omega.\n\n  intros.\n  simpl.\n  f_equal. rewrite IHM.\n  f_equal. omega. omega.\n\n  intros.\n  simpl. f_equal. apply IHM1. omega.\n  apply IHM2. omega.\nQed.\n\n(** This is a reverse statement of [lift_lift]: **)\n\nLemma lift_lift_rev:\n  forall wk k ws s t,\n  k >= s + ws ->\n  lift wk k (lift ws s t) = lift ws s (lift wk (k - ws) t).\nProof.\n  intros.\n  replace k with (ws + (k - ws)) by omega.\n  rewrite <- lift_lift by omega.\n  replace (ws + (k - ws) - ws) with (k - ws) by omega.\n  reflexivity.\nQed.\n\n(** [lift] distributes over [subst], also in a specific way: **)\n\nLemma lift_distr_subst:\n  forall M N, forall v, forall i b,\n    v <= b ->\n    lift i b (subst v N M) = subst v (lift i (b-v) N) (lift i (b+1) M).\nProof.\n  induction M. intros N v.\n  generalize dependent N.\n  generalize dependent n.\n  induction v.\n  intros ? ? ? ? HH. simpl. case_eq (nat_compare n 0).\n  intros H. apply nat_compare_eq_iff in H. rewrite H. simpl.\n  replace (b + 1) with (S b) by omega. simpl.\n  rewrite lift_0_ident. rewrite lift_0_ident.\n  replace (b - 0) with b by omega. reflexivity.\n\n  intros. simpl. apply nat_compare_lt in H. omega.\n  intros. simpl. apply nat_compare_gt in H.\n\n  assert (H1: exists n', n = (S n')).\n  inversion H. exists 0. reflexivity.\n  exists m. reflexivity.\n\n  destruct H1. rewrite H0. replace (S x - 1) with x by omega.\n  simpl.  replace (b +1) with (S b) by omega.\n  case_eq (lt_dec x b).\n  simpl.\n  intros. case_eq (lt_dec (S x) (S b)).\n  intros. simpl. f_equal. omega.\n  intros. omega. intros.\n  case_eq (lt_dec (S x) (S b)). intros. simpl. omega.\n  intros. simpl. f_equal. omega.\n\n  intros ? ? ? ? HH. simpl.\n  case_eq (nat_compare n (S v)).\n  intros H. apply nat_compare_eq_iff in H.\n  rewrite H. simpl.\n  case_eq (lt_dec (S v) (b + 1)).\n  intros.\n  simpl. replace (nat_compare v v) with Eq.\n  replace b with (((b - S v) + (S v))) by omega.\n  rewrite lift_lift_rev. reflexivity.\n  omega. symmetry. apply nat_compare_eq_iff. reflexivity.\n  intros. simpl.\n  case_eq (nat_compare (v+i) v).\n  intros. apply nat_compare_eq_iff in H1.\n  assert (HHH: i = 0). omega.\n  rewrite HHH. rewrite lift_0_ident.\n  f_equal. rewrite lift_0_ident. reflexivity.\n  intros. apply nat_compare_lt in H1.\n  omega. intros. apply nat_compare_gt in H1.\n  omega.\n  intros.\n  apply nat_compare_lt in H.\n  simpl.\n  case_eq (lt_dec n b).\n  intros.\n  case_eq (lt_dec n (b+1)).\n  simpl. intros.\n  replace (nat_compare n (S v)) with Lt.\n  reflexivity. symmetry. apply nat_compare_lt. assumption.\n  intros. omega.\n  intros. omega.\n  intros. apply nat_compare_gt in H.\n  simpl. case_eq (lt_dec (n - 1) b).\n  intros. case_eq (lt_dec n (b+1)).\n  intros. simpl. replace (nat_compare n (S v)) with Gt.\n  reflexivity. symmetry. apply nat_compare_gt. assumption.\n  intros. omega.\n  intros. case_eq (lt_dec n (b+1)). intros.\n  omega. intros. simpl.\n  case_eq (nat_compare (n+i) (S v)).\n  intros. apply nat_compare_eq_iff in H2.\n  omega.\n  intros. apply nat_compare_lt in H2.\n  omega.\n  intros. f_equal. omega.\n\n  intros.\n  simpl. f_equal.\n  rewrite IHM. f_equal. f_equal. omega. omega.\n\n  intros. simpl. f_equal. apply IHM1. omega.\n  apply IHM2. omega.\nQed.\n\n(** Finally, some trivialities for convenient rewriting. **)\n\nLemma subst_app : forall t1 t2 t3, forall n,\n  subst n t3 (App t1 t2) = App (subst n t3 t1) (subst n t3 t2).\nProof. intros. reflexivity. Qed.\n\nLemma subst_lam : forall t t', forall n,\n  subst n t' (Lam t) = Lam (subst (n+1) t' t).\nProof.  intros. reflexivity. Qed.\n\nLemma lift_app : forall t t' n k,\n  lift n k (App t t') = App (lift n k t) (lift n k t').\nProof. intros. reflexivity. Qed.\n\nLemma lift_lam : forall t n k,\n  lift n k (Lam t) = Lam (lift n (k+1) t).\nProof. intros. reflexivity. Qed.\n\n", "meta": {"author": "knuton", "repo": "la-girafe-sportive", "sha": "3aaead03aa1cd62acb064d5b7115c25e706bbb47", "save_path": "github-repos/coq/knuton-la-girafe-sportive", "path": "github-repos/coq/knuton-la-girafe-sportive/la-girafe-sportive-3aaead03aa1cd62acb064d5b7115c25e706bbb47/src/Subst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.734258332741776}}
{"text": "From Enderton Require Export NaturalNumbers.\n\n(** In this chapter, Enderton embeds the real numbers into the axiomatic set\n    theory. He begins by constructing the integers as equivalence classes of\n    ordered pairs of natural numbers. *)\n\nDefinition NatPair_Equivalence (r : set) : Prop :=\n  forall x, In x r <-> exists m n mn p q pq mq pn,\n      NaturalNumber m /\\ NaturalNumber n /\\ OrdPair m n mn /\\\n      NaturalNumber p /\\ NaturalNumber q /\\ OrdPair p q pq /\\\n      Sum_w m q mq /\\ Sum_w p n pn /\\ mq = pn /\\ OrdPair mn pq x.\n\nTheorem NatPair_Equivalence_Exists : exists x, NatPair_Equivalence x.\nProof.\n  omga. prod omga omga. rename x into wxw. rename H into Hwxw.\n  prod wxw wxw. rename x into wxwxwxw. rename H into Hwxwxwxw.\n  build_set unit\n    (fun (_ : unit) (wxwxwxw ab : set) => exists m n mn p q pq mq pn, \n      NaturalNumber m /\\ NaturalNumber n /\\ OrdPair m n mn /\\\n      NaturalNumber p /\\ NaturalNumber q /\\ OrdPair p q pq /\\\n      Sum_w m q mq /\\ Sum_w p n pn /\\ mq = pn /\\ OrdPair mn pq ab)\n    tt wxwxwxw.\n  rename x into eq. rename H into Heq. exists eq. intros x. split; intros H.\n  - apply Heq. assumption.\n  - apply Heq. split; try assumption.\n    apply Hwxwxwxw. destruct H as [m [n [mn [p [ q [pq [mq [pn H]]]]]]]].\n    destruct H as [Hm [Hn [Hmn [Hp [Hq [Hpq [_ [_ [_ H]]]]]]]]].\n    exists mn. exists pq. split; try (split; try assumption).\n    + apply Hwxw. exists m. exists n. split; try apply Homga; try assumption.\n      split; try apply Homga; try assumption.\n    + apply Hwxw. exists p. exists q. split; try split; try apply Homga; try assumption.\nQed.\n\nTheorem NatPair_Equivalence_Unique : forall x y, NatPair_Equivalence x ->\n                                            NatPair_Equivalence y -> x = y.\nProof.\n  intros A B HA HB. apply Extensionality_Axiom. intros x. split; intros H.\n  - apply HB. apply HA. assumption.\n  - apply HA; apply HB; assumption.\nQed.\n\nLtac natpair_eq := destruct NatPair_Equivalence_Exists.\n\nLemma NatPair_Equivalence_On_NatPairs : forall eq w wxw,\n    NatPair_Equivalence eq -> Nats w -> Prod w w wxw -> RelationOn eq wxw.\nProof.\n  intros eq w wxw Heq Hw Hwxw ab H. apply Heq in H.\n  destruct H as [m [n [mn [p [q [pq [_ [_ [Hm [Hn [Hmn [Hp [Hq [Hpq [_ [_ [_ H]]]]]]]]]]]]]]]]].\n  exists mn, pq. split; try assumption. split.\n    + apply Hwxw. exists m, n. repeat (split; try assumption; try apply Hw; try assumption).\n    + apply Hwxw. exists p, q. repeat (split; try assumption; try apply Hw; try assumption).\nQed.  \n\nTheorem Enderton5ZA : forall x w wxw, NatPair_Equivalence x -> Nats w ->\n                                 Prod w w wxw -> EquivalenceRelation x wxw.\nProof.\n  intros eq w wxw Heq Hw Hwxw. repeat (try split).\n  - apply (NatPair_Equivalence_On_NatPairs eq w wxw); try assumption.\n  - intros a aa Haa H. apply Heq. apply Hwxw in H. destruct H as [x [y [Hx [Hy Ha]]]].\n    apply Hw in Hx, Hy. exists x, y, a, x, y, a.\n    sum_w x y Hx Hy. rename x0 into xy. rename H into Hxy. exists xy, xy.\n    repeat (split; try assumption).\n  - intros x y xy yx Hxy Hyx H. apply Heq in H. apply Heq.\n    destruct H as [m [n [mn [p [q [pq [mq [pn H]]]]]]]].\n    destruct H as [Hm [Hn [Hmn [Hp [Hq [Hpq [Hmq [Hpn [H Hxy']]]]]]]]].\n    exists p, q, pq, m, n, mn, pn, mq.\n    assert (P : mn = x /\\ pq = y). {\n      apply (Enderton3A mn pq x y xy xy Hxy' Hxy). reflexivity. }\n    destruct P as [P1 P2]. replace y with pq in Hyx. replace x with mn in Hyx.\n    repeat (split; try assumption). symmetry. assumption.\n  - intros x y z xy yz xz Hxy Hyz Hxz H1 H2.\n    apply Heq. apply Heq in H1, H2.\n    destruct H1 as [m [n [mn [p [q [pq [mq [pn H1]]]]]]]].\n    destruct H1 as [Hm [Hn [Hmn [Hp [Hq [Hpq [Hmq [Hpn [H1 Hxy']]]]]]]]].\n    destruct H2 as [p' [q' [pq' [r [s [rs [ps [rq H2]]]]]]]].\n    destruct H2 as [Hp' [Hq' [Hpq' [Hr [Hs [Hrs [Hps [Hrq [H2 Hyz']]]]]]]]].\n    replace p' with p in *. replace q' with q in *. replace pq' with pq in *.\n    sum_w m s Hm Hs. rename x0 into ms. rename H into Hms.\n    sum_w r n Hr Hn. rename x0 into rn. rename H into Hrn.\n    exists m, n, mn, r, s, rs, ms, rn.\n    replace x with mn in Hxz. replace z with rs in Hxz. repeat (split; try assumption).\n    sum_w ms p (Sum_NaturalNumber m s ms Hm Hs Hms) Hp.\n    rename x0 into msp. rename H into Hmsp.\n    sum_w rn p (Sum_NaturalNumber r n rn Hr Hn Hrn) Hp.\n    rename x0 into rnp. rename H into Hrnp.\n    apply (Enderton4P ms rn p msp rnp).\n    { apply (Sum_NaturalNumber m s ms Hm Hs Hms). }\n    { apply (Sum_NaturalNumber r n rn Hr Hn Hrn). }\n    apply Hp. apply Hmsp.  apply Hrnp.\n    sum_w n p Hn Hp. rename x0 into np. rename H into Hnp.\n    sum_w r np Hr (Sum_NaturalNumber n p np Hn Hp Hnp). rename x0 into rnp'. rename H into Hrnp'.\n    transitivity rnp'. sum_w s p Hs Hp. rename x0 into sp. rename H into Hsp.\n    sum_w m sp Hm (Sum_NaturalNumber s p sp Hs Hp Hsp). rename x0 into msp'. rename H into Hmsp'.\n    transitivity msp'. symmetry. Print Enderton4K1.\n    apply (Enderton4K1 m s p sp ms msp' msp Hm Hs Hp Hsp Hms Hmsp' Hmsp).\n    sum_w r pn Hr (Sum_NaturalNumber p n pn Hp Hn Hpn). rename x0 into rpn. rename H into Hrpn.\n    transitivity rpn.\n    sum_w m ps Hm (Sum_NaturalNumber p s ps Hp Hs Hps). rename x0 into mps. rename H into Hmps.\n    transitivity mps.\n    apply (Sum_w_Unique m ps msp' mps Hm (Sum_NaturalNumber p s ps Hp Hs Hps)); try assumption.\n    replace ps with sp. assumption. apply (Enderton4K2 s p sp ps Hs Hp Hsp Hps).\n    sum_w r mq Hr (Sum_NaturalNumber m q mq Hm Hq Hmq). rename x0 into rmq. rename H into Hrmq.\n    transitivity rmq. sum_w q m Hq Hm. rename x0 into qm. rename H into Hqm.\n    sum_w r qm Hr (Sum_NaturalNumber q m qm Hq Hm Hqm). rename x0 into rqm. rename H into Hrqm.\n    transitivity rqm.\n    sum_w rq m (Sum_NaturalNumber r q rq Hr Hq Hrq) Hm. rename x0 into rqm'. rename H into Hrqm'.\n    transitivity rqm'.\n    sum_w m rq Hm (Sum_NaturalNumber r q rq Hr Hq Hrq). rename x0 into mrq. rename H into Hmrq.\n    transitivity mrq. apply (Sum_w_Unique m ps mps mrq); try assumption.\n    apply (Sum_NaturalNumber p s ps Hp Hs Hps). replace ps with rq; try assumption.\n    apply (Enderton4K2 m rq mrq rqm'); try assumption.\n    apply (Sum_NaturalNumber r q rq); try assumption.\n    symmetry. apply (Enderton4K1 r q m qm rq); try assumption.\n    apply (Sum_w_Unique r qm rqm rmq); try assumption.\n    apply (Sum_NaturalNumber q m qm); try assumption.\n    replace qm with mq; try assumption.\n    apply (Enderton4K2 m q mq qm); try assumption.\n    apply (Sum_w_Unique r mq rmq rpn); try assumption.\n    apply (Sum_NaturalNumber m q mq); try assumption.\n    replace mq with pn; try assumption.\n    apply (Sum_w_Unique r pn rpn rnp'); try assumption.\n    apply (Sum_NaturalNumber p n pn); try assumption.\n    replace pn with np; try assumption.\n    apply (Enderton4K2 n p np pn); try assumption.\n    apply (Enderton4K1 r n p np rn); try assumption.\n    assert (P : pq = y /\\ rs = z). {\n      apply (Enderton3A pq rs y z yz yz); try assumption. trivial. }\n    apply P.\n    assert (P : mn = x /\\ pq = y). {\n      apply (Enderton3A mn pq x y xy xy); try assumption. trivial. }\n    apply P.\n    transitivity y.\n    assert (P : mn = x /\\ pq = y). {\n      apply (Enderton3A mn pq x y xy xy); try assumption. trivial. }\n    apply P.\n    assert (P : pq' = y /\\ rs = z). {\n      apply (Enderton3A pq' rs y z yz yz); try assumption. trivial. }\n    symmetry. apply P.\n    assert (P : pq' = y /\\ rs = z). {\n      apply (Enderton3A pq' rs y z yz yz); try assumption. trivial. }\n    assert (Q : mn = x /\\ pq = y). {\n      apply (Enderton3A mn pq x y xy xy); try assumption. trivial. }\n    assert (R : pq = pq'). {\n      transitivity y; try apply Q; try (symmetry; apply P). }\n    assert (S : p = p /\\ q = q'). {\n      apply (Enderton3A p q p q' pq pq'); try assumption. }\n    apply S.\n    assert (P : pq' = y /\\ rs = z). {\n      apply (Enderton3A pq' rs y z yz yz); try assumption. trivial. }\n    assert (Q : mn = x /\\ pq = y). {\n      apply (Enderton3A mn pq x y xy xy); try assumption. trivial. }\n    assert (R : pq = pq'). {\n      transitivity y; try apply Q; try (symmetry; apply P). }\n    assert (S : p = p' /\\ q = q'). {\n      apply (Enderton3A p q p' q' pq pq'); try assumption. }\n    apply S.\nQed.\n\nDefinition Ints (Z : set) : Prop :=\n  forall w wxw natpair_eq, Nats w -> Prod w w wxw -> NatPair_Equivalence natpair_eq ->\n                      Quotient wxw natpair_eq Z.\n\nTheorem Ints_Exists : exists Z, Ints Z.\nProof.\n  natpair_eq. rename x into eq. rename H into Heq.\n  omga. prod omga omga. rename x into wxw. rename H into Hwxw.\n  assert (P : RelationOn eq wxw). {\n    destruct (Enderton5ZA eq omga wxw Heq Homga Hwxw). assumption. }\n  quotient P wxw eq. exists x. intros w wxw' eq' Hw Hwxw' Heq'.\n  replace wxw' with wxw; replace eq' with eq; try assumption;\n    try (apply NatPair_Equivalence_Unique; assumption).\n  - apply (Prod_Unique omga omga); try assumption.\n    replace omga with w; try assumption.\n    apply (Nats_Unique); assumption.\nQed.  \n\nTheorem Ints_Unique : forall Z Z', Ints Z -> Ints Z' -> Z = Z'.\nProof.\n  intros Z Z' HZ HZ'. omga.\n  prod omga omga. rename x into wxw. rename H into Hwxw.\n  natpair_eq. rename x into eq. rename H into Heq.\n  apply (Quotient_Unique wxw eq);\n    try apply (NatPair_Equivalence_On_NatPairs eq omga wxw); try assumption.\n  - apply (HZ omga wxw eq); try assumption.\n  - apply (HZ' omga wxw eq); try assumption.\nQed.\n\nLtac Z := destruct (Ints_Exists) as [Z HZ].\n\nDefinition Int (a : set) : Prop :=\n  forall Z, Ints Z -> In a Z.\n\nDefinition Addition_Z (add : set) : Prop :=\n  forall abc, In abc add <-> exists ab c a b m n p q mn pq mp nq mpnq eq,\n      OrdPair ab c abc /\\ OrdPair a b ab /\\ Int a /\\ Int b /\\\n      NaturalNumber m /\\ NaturalNumber n /\\ NaturalNumber p /\\ NaturalNumber q /\\\n      OrdPair m n mn /\\ OrdPair p q pq /\\ Sum_w m p mp /\\ Sum_w n q nq /\\\n      OrdPair mp nq mpnq /\\ NatPair_Equivalence eq /\\ EquivalenceClass mn eq a /\\\n      EquivalenceClass pq eq b /\\ EquivalenceClass mpnq eq c.\n\nTheorem Addition_Z_Exists : exists add_Z, Addition_Z add_Z.\nProof.\n  Z. prod Z Z. rename x into ZxZ. rename H into HZxZ.\n  prod ZxZ Z. rename x into ZxZxZ. rename H into HZxZxZ.\n  build_set unit\n    (fun (_ : unit) (ZxZxZ abc : set) => exists ab c a b m n p q mn pq mp nq mpnq eq,\n      OrdPair ab c abc /\\ OrdPair a b ab /\\ Int a /\\ Int b /\\\n      NaturalNumber m /\\ NaturalNumber n /\\ NaturalNumber p /\\ NaturalNumber q /\\\n      OrdPair m n mn /\\ OrdPair p q pq /\\ Sum_w m p mp /\\ Sum_w n q nq /\\\n      OrdPair mp nq mpnq /\\ NatPair_Equivalence eq /\\ EquivalenceClass mn eq a /\\\n      EquivalenceClass pq eq b /\\ EquivalenceClass mpnq eq c)\n    tt ZxZxZ.\n  rename x into add. rename H into Hadd. exists add. intros abc. split; intros H.\n  - apply Hadd. assumption.\n  - apply Hadd. split; try assumption.\n    destruct H as [ab [c [a [b [m [n [p [q [mn [pq [mp [nq [mpnq [eq H]]]]]]]]]]]]]].\n    destruct H as [Habc [Hab [Ha [Hb [Hm [Hn [Hp [Hq [Hmn [Hpq [Hmp [Hnq [Hmpnq [Heq [HCa [HCb HCc]]]]]]]]]]]]]]]].\n    apply HZxZxZ. exists ab, c. split; try (split; try assumption).\n    apply HZxZ. exists a, b. repeat (split; try assumption).\n    + apply Ha; try assumption.\n    + apply Hb; try assumption.\n    + omga. prod omga omga. rename x into wxw. rename H into Hwxw.\n      apply (HZ omga wxw eq Homga Hwxw Heq\n                (NatPair_Equivalence_On_NatPairs eq omga wxw Heq Homga Hwxw)).\n      exists mpnq. split; try assumption. apply Hwxw.\n      exists mp, nq. split; try split; try assumption. Check Sum_NaturalNumber.\n      * apply Homga. apply (Sum_NaturalNumber m p mp Hm Hp Hmp).\n      * apply Homga. apply (Sum_NaturalNumber n q nq Hn Hq Hnq).\nQed.\n\nTheorem Addition_Z_Unique : forall add_Z add_Z', Addition_Z add_Z -> Addition_Z add_Z' ->\n                                            add_Z = add_Z'.\nProof.\n  intros Z Z' HZ HZ'. apply Extensionality_Axiom. intros abc. split; intros H.\n  - apply HZ'. apply HZ in H. apply H.\n  - apply HZ. apply HZ' in H. apply H.\nQed.  \n\nTheorem Addition_Z_BinaryOperation : forall Z add_Z, Ints Z -> Addition_Z add_Z ->\n                                                BinaryOperator add_Z Z.\nProof.\n  intros Z add_Z HZ Hadd_Z. prod Z Z. rename x into ZxZ. rename H into HZxZ.\n  exists ZxZ. split; try assumption. split; try split.\n  - intros abc Habc. apply Hadd_Z in Habc.\n    destruct Habc as [ab [c [a [b [m [n [p [q [mn [pq [mp [nq [mpnq [eq Habc]]]]]]]]]]]]]].\n    destruct Habc as [Habc _]. exists ab, c. assumption.\n  - intros ab c d abc abd Habc Habd H1 H2.\n    apply Hadd_Z in H1, H2.\nAdmitted.\n\nLtac add_Z := destruct Addition_Z_Exists as [addZ HaddZ].\n\nDefinition Sum_Z (a b c : set) : Prop :=\n  exists add ab abc, Addition_Z add /\\ OrdPair a b ab /\\ OrdPair ab c abc /\\\n                In abc add.\n\nTheorem Sum_Z_Exists : forall a b, Int a -> Int b -> exists c, Sum_Z a b c.\nProof.\nAdmitted.\n\nLemma Enderton5ZB : forall m n m' n' p q p' q' mp nq m'p' n'q' mn m'n' pq p'q' mpnq,\n  forall m'p'n'q' A B C eq,\n  NaturalNumber m -> NaturalNumber n -> NaturalNumber m' -> NaturalNumber n' ->\n  NaturalNumber p -> NaturalNumber q -> NaturalNumber p' -> NaturalNumber q' ->\n  Sum_w m p mp -> Sum_w n q nq -> Sum_w m' p' m'p' -> Sum_w n' q' n'q' ->\n  OrdPair m n mn -> OrdPair m' n' m'n' -> OrdPair p q pq -> OrdPair p' q' p'q' ->\n  OrdPair mp nq mpnq -> OrdPair m'p' n'q' m'p'n'q' ->\n  OrdPair mn m'n' A -> OrdPair pq p'q' B -> OrdPair mpnq m'p'n'q' C ->\n  NatPair_Equivalence eq ->\n  In A eq -> In B eq -> In C eq.\nProof.\nAdmitted.\n\n(* should follow from Enderton3Q and previous lemma *)\nTheorem Sum_Z_Unique : forall a b c c', Int a -> Int b -> Sum_Z a b c ->\n                                   Sum_Z a b c' -> c = c'.\nProof.\nAdmitted.\n\nLtac sum_w a b Ha Hb := destruct (Sum_Z_Exists a b Ha Hb).\n\nDefinition Add_Z_Associative : Prop := forall a b c ab bc r l,\n  Int a -> Int b -> Int c -> Sum_Z a b ab -> Sum_Z b c bc ->\n  Sum_Z a bc r -> Sum_Z ab c l -> r = l.\n\nDefinition Add_Z_Commutative : Prop := forall a b ab ba,\n  Int a -> Int b -> Sum_Z a b ab -> Sum_Z b a ba -> ab = ba.\n\nTheorem Enderrton5ZC1 : Add_Z_Associative.\nProof.\nAdmitted.\n\nTheorem Enderton5ZC2 : Add_Z_Commutative.\nProof.\nAdmitted.\n\nDefinition Zero_Z (z : set) : Prop :=\n  forall o oo eq, Empty o -> OrdPair o o oo -> NatPair_Equivalence eq -> EquivalenceClass oo eq z.\n\nTheorem Zero_Z_Exists : exists z, Zero_Z z.\nProof.\nAdmitted.\n\nTheorem Zero_Z_Unique : forall z z', Zero_Z z -> Zero_Z z' -> z = z'.\nProof.\nAdmitted.\n\nLtac zero_z := destruct Zero_Z_Exists.\n\nTheorem Enderton5ZDa : forall a o, Int a -> Zero_Z o -> Sum_Z a o a.\nProof.\nAdmitted.\n\nTheorem Enderton5ZDb : forall a o, Int a -> Zero_Z o -> exists b, Sum_Z a b o.\nProof.\nAdmitted.\n\nTheorem Add_Z_Inverse_Unique : forall a b b' o,\n  Int a -> Int b -> Int b' -> Zero_Z o -> Sum_Z a b o -> Sum_Z a b' o -> b = b'.\nProof.\nAdmitted.\n\n", "meta": {"author": "stp59", "repo": "math-texts", "sha": "dcf36696cbd7526a35020aa32809e6e7d790d0da", "save_path": "github-repos/coq/stp59-math-texts", "path": "github-repos/coq/stp59-math-texts/math-texts-dcf36696cbd7526a35020aa32809e6e7d790d0da/enderton/RealNumbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7342583307630001}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf1 : natural) : natural :=\n  plus Zero (plus lf1 lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj144_coqofml_JiYHwU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7342243340579566}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus y (plus x lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj206_coqofml_hAaUXO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7342243301590969}}
{"text": "Require Import Coq.Program.Tactics.\nRequire Import Coq.Sets.Ensembles.\nRequire Export Essentials.Notations Essentials.Definitions.\n\nLocal Open Scope order_scope.\n\n(** Basic Definition of a preorder relation. *)\nRecord PartialOrder : Type :=\n  {\n    PO_Carrier :> Type;\n    PO_LE : PO_Carrier → PO_Carrier → Prop where \"x ⊑ y\" := (PO_LE x y);\n    PO_Refl : ∀ x, x ⊑ x;\n    PO_ASym : ∀ x y, x ⊑ y → y ⊑ x → x = y;\n    PO_Trans : ∀ x y z, x ⊑ y → y ⊑ z → x ⊑ z\n  }\n.\n\nArguments PO_Carrier _ : assert.\nArguments PO_LE {_} _ _, _ _ _.\nArguments PO_Refl {_} _.\nArguments PO_ASym {_} _ _ _ _.\nArguments PO_Trans {_} _ _ _ _ _.\n\nNotation \"x ⊑ y\" := (PO_LE x y) : order_scope.\n\nDefinition PO_LT {p : PartialOrder} (x y : p) := (x ⊑ y)%order ∧ x ≠ y.\n\nNotation \"x ⊏ y\" := (PO_LT x y) : order_scope.\n  \n(** A monotone function is order preserving. *)\nRecord Monotone (A B : PartialOrder) : Type :=\n  {\n    MNT_fun :> A → B;\n    MNT_monotone : ∀ x y, x ⊑ y → MNT_fun x ⊑ MNT_fun y\n  }.\n\nLocal Hint Resolve MNT_monotone.\n\nProgram Definition Monotone_comp\n           {A B C : PartialOrder}\n           (f : Monotone A B)\n           (g : Monotone B C)\n  :\n    Monotone A C :=\n  {|\n    MNT_fun := fun x => g (f x)\n  |}.\n\nProgram Definition iterate_Monotone\n        {A : PartialOrder}\n        (f : Monotone A A)\n        (n : nat)\n  :\n    Monotone A A :=\n  {|\n    MNT_fun := fun x => iterate f x n\n  |}.\n\nNext Obligation.\nProof.\n  induction n; cbn; auto.\nQed.\n\n(** Greatest lower bound and least upper bound in a preorder. *)\nSection LUB_GLB.\n  Context {A : PartialOrder}.\n\n  Section Generalized.\n    Context {X : Type} (f : X → A).\n    \n    Record LUB :=\n      {\n        lub :> A;\n        lub_ub : ∀ (x : X), (f x) ⊑ lub;\n        lub_lst : ∀ (ub : A), (∀ (x : X), (f x) ⊑ ub) → lub ⊑ ub\n      }\n    .\n\n    Record GLB :=\n      {\n        glb :> A;\n        glb_lb : ∀ (x : X), glb ⊑ (f x);\n        glb_grst : ∀ (lb : A), (∀ (x : X), lb ⊑ (f x)) → lb ⊑ glb\n      }\n    .\n\n  End Generalized.\n\n  Notation \"⊔ᵍ Q\" := (LUB Q) : order_scope.\n  \n  Notation \"⊓ᵍ Q\" := (GLB Q) : order_scope.\n\n  Definition LUB_Pair (x y : A) :=\n    (⊔ᵍ (fun u : bool => match u with | true => x | false => y end)).\n\n  Definition GLB_Pair (x y : A) :=\n    (⊓ᵍ (fun u : bool => match u with | true => x | false => y end)).\n\nEnd LUB_GLB.\n\nArguments lub {_ _ _} _.\nArguments glb {_ _ _} _.\n\nNotation \"⊔ᵍ Q\" := (LUB Q) : order_scope.\n\nNotation \"⊓ᵍ Q\" := (GLB Q) : order_scope.\n\nNotation \"x ⊔ y\" := (LUB_Pair x y) : order_scope.\n  \nNotation \"x ⊓ y\" := (GLB_Pair x y) : order_scope.\n\nHint Resolve PO_Refl PO_ASym PO_Trans.\n\nTheorem LE_LT_Trans {A : PartialOrder} : ∀ (x y z : A), x ⊑ y → y ⊏ z → x ⊏ z.\nProof.\n  intros x y z H1 [H21 H22]; split; eauto.\n  intros eq.\n  rewrite eq in H1; auto.\nQed.\n\nTheorem LT_LE_Trans {A : PartialOrder} : ∀ (x y z : A), x ⊏ y → y ⊑ z → x ⊏ z.\nProof.\n  intros x y z [H11 H12] H2; split; eauto.\n  intros eq.\n  rewrite <- eq in H2; auto.\nQed.", "meta": {"author": "amintimany", "repo": "CTDT", "sha": "91e390152e09c554126b13fd953c905d16bfed5f", "save_path": "github-repos/coq/amintimany-CTDT", "path": "github-repos/coq/amintimany-CTDT/CTDT-91e390152e09c554126b13fd953c905d16bfed5f/Lattice/PartialOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.734141137406285}}
{"text": "Inductive Var := n | i | sum.\nDefinition var_eq (v1 v2 : Var) : bool :=\n  match v1, v2 with\n  |n ,n => true\n  |i, i => true\n  |sum, sum => true\n  |_,_ => false\n  end.\n\nCompute (var_eq n n).\n\n(*Eviroment*)\nDefinition Env := Var -> nat.\nDefinition env1 : Env :=\n  fun x =>\n    if (var_eq x n)\n    then 10\n    else 0.\n\nCheck env1.\nCompute (env1 n).\nCompute (env1 sum).\n\nDefinition update (env : Env) (x: Var) (v : nat) : Env :=\n  fun y =>\n    if(var_eq y x)\n    then v\n    else (env y).\nCheck update.\n\nDefinition env2 := (update env1 n 1045).\nCompute (env2 n).\nCompute ((update env1 n 1045) n).\n\nInductive AExp :=\n  |avar : Var -> AExp\n  |anum : nat -> AExp\n  |aplus : AExp -> AExp -> AExp\n  |amul : AExp -> AExp -> AExp.\n\nNotation \"A +' B\" := (aplus A B) (at level 48).\nNotation \"A *' B\" := (amul A B) (at level 46).\nCoercion anum : nat >-> AExp.\nCoercion avar : Var >-> AExp.\n\nCheck (2 +' 3 *' 5).\n\nFixpoint aeval (a : AExp) (env : Env) : nat :=\n  match a with\n  | avar x => env x\n  | anum v => v\n  | aplus a1 a2 => (aeval a1 env) + (aeval a2 env)\n  | amul a1 a2 => (aeval a1 env) * (aeval a2 env)\nend.\n\nCompute aeval (2 +' 3 *' 5) env1.\nCompute aeval (2 +' 3 *' n) env1.\n\nInductive BExp :=\n| btrue : BExp\n| bfalse : BExp\n| blessthan : AExp -> AExp -> BExp\n| bnot : BExp -> BExp.\n\nFixpoint beval (b : BExp) (env : Env) : bool :=\n  match b with\n  | btrue => true\n  | bfalse => false\n  | blessthan a1 a2 =>Nat.leb (aeval a1 env) (aeval a2 env)\n  | bnot b' => negb (beval b' env)\nend.\n\nNotation \"A <<= B\" := (blessthan A B) (at level 58).\nCompute beval (bnot (n<<= (2 +' 3 *' n))) env1.\n\nInductive Stmt :=\n| assignment : Var -> AExp -> Stmt\n| sequence : Stmt -> Stmt -> Stmt\n| while : BExp -> Stmt -> Stmt.\n\nNotation \"X ::= N\" := (assignment X N) (at level 60).\nNotation \"S ;; S'\" := (sequence S S') (at level 63, right associativity).\n\nCheck (n ::= n +' 10).\nCheck (n ::= 0 ;; i ::=7 ;; sum ::= 0).\n\nFixpoint eval (s : Stmt) (env : Env) (gas : nat) : Env :=\n  match gas with\n  |0 => env\n  |S gas' => match s with\n              | x ::= a => update env x (aeval a env)\n              | sequence s1 s2 => eval s2 (eval s1 env gas') gas'\n              |while b s => if (beval b env)\n                            then (eval (sequence s (while b s)) env gas')\n                            else env\n  end\nend.\n\nDefinition pgm := (n ::= 7).\nDefinition env_after_assign := eval pgm env1.\n\n\n\nDefinition pgm2 := n ::= 243 ;; i ::= 7 ;; sum ::= 10.\n\nCompute (eval pgm2 env1 100) n.\nCompute (eval pgm2 env1 100) i.\nCompute (eval pgm2 env1 100) sum.\n\nDefinition sumpgm :=\n  n::=10;;\n  i::=1;;\n  sum::=0;;\n    while (i<<=n)\n      (sum ::= sum +' i ;; i::=i+'1).\n\nCheck sumpgm.\nCompute (eval sumpgm env1 100) sum.\n\n\n\n\n", "meta": {"author": "IonitaCatalin", "repo": "programming-language-principle", "sha": "e6a5b4f5284f28127707dc1b8838bad29f215c69", "save_path": "github-repos/coq/IonitaCatalin-programming-language-principle", "path": "github-repos/coq/IonitaCatalin-programming-language-principle/programming-language-principle-e6a5b4f5284f28127707dc1b8838bad29f215c69/plp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7341218086871788}}
{"text": "(* These exercises come from Lab Session 6 of the MAP Spring School *)\n(* on formalization of mathematics. *)\n\nFrom mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition onext_id n (x: 'I_n): 'I_n.\npose v := nat_of_ord x.\npose H := ltn_ord x.\npose H1 := leq_trans H (leqnn n).\nexact: Ordinal H1.\nDefined.\n\n(* {x | x < 0} is an empty type *)\nLemma empty_i0 (x: 'I_0): false.\nProof.\n  case x. by [].\nQed.\n\n(* Toy structure from examples *)\nStructure semiGroup := SemiGroup {\n  toy_dom : Type;\n  binop : toy_dom -> toy_dom -> toy_dom;\n  binopA : forall x y z : toy_dom,\n    binop x (binop y z) = binop (binop x y) z\n}.\n\n(* Canonical semigroup: register a semigroup to be available for type\n   inference - see next Lemma *)\nCanonical nat_semiGroup : semiGroup := @SemiGroup nat addn addnA.\n\nLemma semigroup_canonical (x y z : nat) : x + (y + z) = x + y + z.\nProof.\n  apply: binopA.\nQed.\n\n\n(* We define here an interface for types equipped with a binary boolean *)\n(* relation and a unary operation monotonic wrt the previous relation*)\n(* Specification projections are unnamed to avoid introducing *)\n(* projections that do not play a role for the inference of canonical *)\n(* instances *)\nStructure rel_s := Rel_s {\n   dom : Type;\n   cmp : rel dom;\n   f : dom -> dom;\n   _ : transitive cmp;\n   _ : forall x, cmp x (f x)\n}.\n\n(* Now we prove that the relation associated with an instance of rel_s *)\n(* is transitive.*)\nLemma cmp_trans (s : rel_s) : transitive (@cmp s).\nProof.\n  by case: s.\nQed.\n\n(* Ex1 - Prove the following lemma *)\nLemma cmp_f (s : rel_s) : forall x : dom s, cmp x (f x).\nProof.\n  by case: s.\nQed.\n\nSection thms.\n\n(* We a assume a parameter type and all the material needed in order *)\n(* to build an instance of rel_s*)\nVariables (T : Type) (cmpT : rel T) (fT : T -> T).\n\nHypothesis cmp_trans : transitive cmpT.\n\nHypothesis f_mon : forall x, cmpT x (fT x).\n\n(* Define a canonical instance of rel_s for cmpT and fT *)\n(* Warning: the effect of canonical declarations do not survive *)\n(* to the end of sections *)\nCanonical res_st : rel_s := Rel_s cmp_trans f_mon.\n\n(* This is a notation local to the section thms for the relation *)\n(* associated with the instance s *)\n\nEnd thms.\n\n(* Prove the following theorem *)\nLemma f3 : forall (s : rel_s) (n : dom s), cmp n (f (f (f n))).\nProof.\n  move => s n.\n  apply (@cmp_trans _ (f (f n))).\n    - apply (@cmp_trans _ (f n)); by rewrite cmp_f.\n    - by rewrite cmp_f.\nQed.\n\n(* Define a canonical instance of rel_s on type nat equipped with the *)\n(* relation leq and the successor operation *)\nCanonical res_snat : rel_s := Rel_s leq_trans leqnSn.\n\n(* This result comes for free using the more generic f3 *)\nLemma fnat3 n : n <= n.+3.\nProof.\n  apply f3.\nQed.\n\nSection pairs.\n\n(* We assume two parameter types, and two binary boolean relations *)\n(* respectively on these types, and two unary functions *)\n\nVariables (T1 T2 : Type)(r1 : rel T1)(r2 : rel T2).\nVariables (f1 : T1 -> T1)(f2 : T2 -> T2).\n\nHypothesis r1_trans : transitive r1.\nHypothesis r2_trans : transitive r2.\n\nHypothesis f1_mon : forall x, r1 x (f1 x).\nHypothesis f2_mon : forall x, r2 x (f2 x).\n\nDefinition pair_rel (u v : T1 * T2) := (r1 u.1 v.1) && (r2 u.2 v.2).\n\n(* Complete the following definition to define a function on pairs *)\n(* which associates (x, y) with the pair (f1 x, f2 y) *)\nDefinition pair_fun (u : T1 * T2) := (*D *) (f1 u.1, f2 u.2).\n\n(* State and prove that pair_rel is transitive *)\nLemma pair_rel_trans : transitive pair_rel.\nProof.\n  case => x1 x2 [y1 y2] [z1 z2].\n  move => /andP. rewrite /=. move => [Hxy1 Hxy2].\n  move => /andP /= [Hxz1 Hxz2].\n  (* Unfold pair_rel definition *)\n  rewrite/pair_rel. apply /andP. rewrite /=.\n  rewrite (r1_trans Hxy1).\n    + by rewrite (r2_trans Hxy2).\n    + by apply Hxz1.\nQed.\n\n(* State and prove that pair_fun is monotonic wrt pair_rel *)\nLemma pair_fun_mon : forall x, pair_rel x (pair_fun x).\nProof.\n  case => x1 x2.\n  rewrite /pair_rel /=. apply /andP.\n  by rewrite f1_mon f2_mon.\nQed.\n\nEnd pairs.\n\nSection instances.\n(* Write a canonical declaration which builds a new instance of rel_s *)\n(* from two existing ones using the lemmas prouved in section Pairs. *)\n\nDefinition test_fun := pair_fun S S.\nDefinition test_comp := pair_rel leq leq.\n\n(* An instance of rel_s which satisfies the Rel_s definition for pairs *)\nCanonical rel_s_pair (s1 s2: rel_s) :=\n  Rel_s (pair_rel_trans (@cmp_trans s1) (@cmp_trans s2))\n  (pair_fun_mon (@cmp_f s1) (@cmp_f s2)).\n\n(* Find the shortest possible proof for this test lemma *)\nLemma test_rels_pair : forall u : nat * nat, test_comp u (test_fun u).\nProof.\n  apply cmp_f.\nQed.\n\n(* Now instanciate rel_s for divisibility and doubling on nat and test *)\n(* your approach *)\n\nLemma doubling_mon_dvdn : forall x, dvdn x (x.*2).\nProof.\n  move => x.\n  apply /dvdnP.\n  by exists 2; rewrite mulnC muln2.\nQed.\n\nCanonical rel_s_div : rel_s := Rel_s dvdn_trans doubling_mon_dvdn.\n\n(* Test the benchmark to see if our approach was correct *)\nLemma dvdn_times_8 : forall x, dvdn x (x.*2.*2.*2).\nProof.\n  move => x. apply f3.\nQed.\n\nEnd instances.\n", "meta": {"author": "VHarisop", "repo": "coq_exercises", "sha": "3dd12f8b15704d786b9f53ce755290a6d0b5d8f6", "save_path": "github-repos/coq/VHarisop-coq_exercises", "path": "github-repos/coq/VHarisop-coq_exercises/coq_exercises-3dd12f8b15704d786b9f53ce755290a6d0b5d8f6/canonical_structs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7340778383385342}}
{"text": "Require Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Hints.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.ZUtil.Lnot.\nRequire Import Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Hints.Ztestbit.\nRequire Import Crypto.Util.ZUtil.Tactics.ZeroBounds.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.ZUtil.Log2.\nRequire Import Crypto.Util.ZUtil.Pow.\nRequire Import Crypto.Util.Bool.LeCompat.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma ones_spec : forall n m, 0 <= n -> 0 <= m -> Z.testbit (Z.ones n) m = if Z_lt_dec m n then true else false.\n  Proof using Type.\n    intros.\n    break_match.\n    + apply Z.ones_spec_low. lia.\n    + apply Z.ones_spec_high. lia.\n  Qed.\n#[global]\n  Hint Rewrite ones_spec using zutil_arith : Ztestbit.\n\n  Lemma ones_spec' n m (Hn : 0 <= n) (Hm : 0 <= m) :\n    Z.testbit (Z.ones n) m = if (m <? n) then true else false.\n  Proof using Type. rewrite ones_spec by assumption.\n         destruct (Z_lt_dec m n) as [lt|lt];\n           [apply Z.ltb_lt in lt|apply Z.ltb_nlt in lt];\n           rewrite lt; reflexivity. Qed.\n\n  Lemma ones_spec_full : forall n m, Z.testbit (Z.ones n) m\n                                     = if Z_lt_dec m 0\n                                       then false\n                                       else if Z_lt_dec n 0\n                                            then true\n                                            else if Z_lt_dec m n then true else false.\n  Proof using Type.\n    intros n m.\n    repeat (break_match || autorewrite with Ztestbit); try reflexivity; try lia.\n    unfold Z.ones.\n    rewrite <- Z.shiftr_opp_r, Z.shiftr_eq_0 by (simpl; lia); simpl.\n    destruct m; simpl in *; try reflexivity.\n    exfalso; auto using Zlt_neg_0.\n  Qed.\n#[global]\n  Hint Rewrite ones_spec_full : Ztestbit_full.\n\n  Lemma testbit_pow2_mod : forall a n i, 0 <= n ->\n  Z.testbit (Z.pow2_mod a n) i = if Z_lt_dec i n then Z.testbit a i else false.\n  Proof using Type.\n    cbv [Z.pow2_mod]; intros a n i H; destruct (Z_le_dec 0 i);\n      repeat match goal with\n          | |- _ => rewrite Z.testbit_neg_r by lia\n          | |- _ => break_innermost_match_step\n          | |- _ => lia\n          | |- _ => reflexivity\n          | |- _ => progress autorewrite with Ztestbit\n          end.\n  Qed.\n#[global]\n  Hint Rewrite testbit_pow2_mod using zutil_arith : Ztestbit.\n\n  Lemma testbit_pow2_mod_full : forall a n i,\n      Z.testbit (Z.pow2_mod a n) i = if Z_lt_dec n 0\n                                     then if Z_lt_dec i 0 then false else Z.testbit a i\n                                     else if Z_lt_dec i n then Z.testbit a i else false.\n  Proof using Type.\n    intros a n i; destruct (Z_lt_dec n 0); [ | apply testbit_pow2_mod; lia ].\n    unfold Z.pow2_mod.\n    autorewrite with Ztestbit_full;\n      repeat break_match;\n      autorewrite with Ztestbit;\n      reflexivity.\n  Qed.\n#[global]\n  Hint Rewrite testbit_pow2_mod_full : Ztestbit_full.\n\n  Lemma bits_above_pow2 a n : 0 <= a < 2^n -> Z.testbit a n = false.\n  Proof using Type.\n    intros.\n    destruct (Z_zerop a); subst; autorewrite with Ztestbit; trivial.\n    apply Z.bits_above_log2; auto with zarith concl_log2.\n  Qed.\n#[global]\n  Hint Rewrite bits_above_pow2 using zutil_arith : Ztestbit.\n\n  Lemma testbit_low : forall n x i, (0 <= i < n) ->\n    Z.testbit x i = Z.testbit (Z.land x (Z.ones n)) i.\n  Proof using Type.\n    intros.\n    rewrite Z.land_ones by lia.\n    symmetry.\n    apply Z.mod_pow2_bits_low.\n    lia.\n  Qed.\n\n  Lemma testbit_add_shiftl_low : forall i, (0 <= i) -> forall a b n, (i < n) ->\n    Z.testbit (a + Z.shiftl b n) i = Z.testbit a i.\n  Proof using Type.\n    intros i H a b n H0.\n    erewrite Z.testbit_low; eauto.\n    rewrite Z.land_ones, Z.shiftl_mul_pow2 by lia.\n    rewrite Z.mod_add by (pose proof (Z.pow_pos_nonneg 2 n); lia).\n    auto using Z.mod_pow2_bits_low.\n  Qed.\n#[global]\n  Hint Rewrite testbit_add_shiftl_low using zutil_arith : Ztestbit.\n\n  Lemma testbit_sub_pow2 n i x (i_range:0 <= i < n) (x_range:0 < x < 2 ^ n) :\n    Z.testbit (2 ^ n - x) i = negb (Z.testbit (x - 1)  i).\n  Proof using Type.\n    rewrite <-Z.lnot_spec, Z.lnot_sub1 by lia.\n    rewrite <-(Z.mod_pow2_bits_low (-x) _ _ (proj2 i_range)).\n    f_equal.\n    rewrite Z.mod_opp_l_nz; autorewrite with zsimplify; lia.\n  Qed.\n\n  Lemma testbit_false_bound : forall a x, 0 <= x ->\n    (forall n, ~ (n < x) -> Z.testbit a n = false) ->\n    a < 2 ^ x.\n  Proof using Type.\n    intros a x H H0.\n    assert (H1 : a = Z.pow2_mod a x). {\n     apply Z.bits_inj'; intros.\n     rewrite Z.testbit_pow2_mod by lia; break_match; auto.\n    }\n    rewrite H1.\n    cbv [Z.pow2_mod]; rewrite Z.land_ones by auto.\n    try apply Z.mod_pos_bound; Z.zero_bounds.\n  Qed.\n\n  Lemma testbit_neg_eq_if x n :\n    0 <= n ->\n    - (2 ^ n) <= x  < 2 ^ n ->\n    Z.b2z (if x <? 0 then true else Z.testbit x n) = - (x / 2 ^ n) mod 2.\n  Proof using Type.\n    intros. break_match; Z.ltb_to_lt.\n    { autorewrite with zsimplify. reflexivity. }\n    { autorewrite with zsimplify.\n      rewrite Z.bits_above_pow2 by lia.\n      reflexivity. }\n  Qed.\n\n  Lemma shiftl_spec_full a n m : Z.testbit (a << n) m = if (0 <=? m) then Z.testbit a (m - n) else false.\n  Proof using Type.\n    break_innermost_match; Z.ltb_to_lt; now autorewrite with Ztestbit.\n  Qed.\n#[global]\n  Hint Rewrite shiftl_spec_full : Ztestbit_full.\n\n  Lemma shiftr_spec_full a n m : Z.testbit (a >> n) m = if (0 <=? m) then Z.testbit a (m + n) else false.\n  Proof using Type.\n    break_innermost_match; Z.ltb_to_lt; now autorewrite with Ztestbit.\n  Qed.\n#[global]\n  Hint Rewrite shiftr_spec_full : Ztestbit_full.\n\n  Lemma mod_pow2_ones a m :\n    a mod 2 ^ m = if (Z_lt_dec m 0) then ltac:(match eval hnf in (1 mod 0) with | 0 => exact 0 | _ => exact a end) else a &' Z.ones m.\n  Proof using Type. destruct (Z_lt_dec m 0). rewrite Z.pow_neg_r, Zmod_0_r; lia.\n         symmetry; apply Z.land_ones; lia. Qed.\n\n  Lemma bits_1 m :\n    Z.testbit 1 m = if Z.eq_dec m 0 then true else false.\n  Proof using Type.\n    destruct (Z.eq_dec m 0); subst. reflexivity.\n    destruct (Z_lt_dec m 0). rewrite Z.testbit_neg_r by lia. reflexivity.\n    rewrite Z.bits_above_log2; simpl; try reflexivity; lia. Qed.\n\n  Lemma bits_opp_full a i :\n    Z.testbit (- a) i = if (Z_lt_dec i 0) then false else negb (Z.testbit (Z.pred a) i).\n  Proof using Type.\n    destruct (Z_lt_dec i 0). rewrite Z.testbit_neg_r by lia. reflexivity.\n    apply Z.bits_opp; lia. Qed.\n\n  Lemma pow2_bits_full m i :\n    Z.testbit (2 ^ m) i =\n    if (Z_lt_dec m 0) then false else if (Z.eq_dec i m) then true else false.\n  Proof using Type.\n    destruct (Z_lt_dec m 0); [now rewrite Z.pow_neg_r, Z.bits_0|].\n    destruct (Z.eq_dec i m); subst.\n    - apply Z.pow2_bits_true; lia.\n    - apply Z.pow2_bits_false; lia. Qed.\n\n\n  Definition bit_compare (b1 b2 : bool) : comparison\n    := match b1, b2 with\n       | true, true => Eq\n       | true, false => Lt\n       | false, false => Eq\n       | false, true => Gt\n       end.\n\n  Lemma bit_compare_refl (b  : bool) : bit_compare b b = Eq.\n  Proof using Type. now destruct b. Qed.\n#[global]\n  Hint Rewrite bit_compare_refl : Ztestbit.\n\n  Lemma bit_compare_eq_iff (b1 b2 : bool)\n    : bit_compare b1 b2 = Eq <-> b1 = b2.\n  Proof using Type. now destruct b1, b2. Qed.\n\n  Lemma bit_compare_gt_iff (b1 b2 : bool)\n    : bit_compare b1 b2 = Gt <-> (b1 = false /\\ b2 = true).\n  Proof using Type. now destruct b1, b2. Qed.\n\n  Lemma bit_compare_lt_iff (b1 b2 : bool)\n    : bit_compare b1 b2 = Lt <-> (b1 = true /\\ b2 = false).\n  Proof using Type. now destruct b1, b2. Qed.\n\n  Lemma bits_const_iff z b\n    : (forall n, 0 <= n -> Z.testbit z n = b)\n      <-> z = if b then -1 else 0.\n  Proof using Type.\n    destruct b; [ rewrite <- (Z.bits_inj_iff z (-(1))) | rewrite <- (Z.bits_inj_iff z 0) ];\n      cbv [Z.eqf];\n      split; intros H n; specialize (H n); intros; destruct (Z_le_gt_dec 0 n);\n        try specialize (H ltac:(assumption)); try lia;\n        revert H;\n        rewrite ?Z.bits_0, ?Z.bits_m1, ?Z.testbit_neg_r by lia; trivial.\n  Qed.\n\n  Lemma compare_by_bits_impl z1 z2 c\n    : (forall n, 0 <= n -> bit_compare (Z.testbit z1 n) (Z.testbit z2 n) = c)\n      -> Z.compare z1 z2 = c.\n  Proof using Type.\n    destruct (Z.compare_spec z1 z2), c; subst.\n    all: repeat first [ progress setoid_rewrite bit_compare_refl\n                      | progress setoid_rewrite bit_compare_eq_iff\n                      | progress setoid_rewrite bit_compare_gt_iff\n                      | progress setoid_rewrite bit_compare_lt_iff\n                      | reflexivity\n                      | assumption\n                      | congruence\n                      | lia\n                      | progress subst\n                      | progress intros\n                      | progress split_and\n                      | match goal with\n                        | [ H : forall n, 0 <= n -> ?T |- _ ] => assert T by (eapply H; reflexivity); clear H\n                        | [ H : forall n, 0 <= n -> Z.testbit _ _ = Z.testbit _ _ |- _ ]\n                          => apply Z.bits_inj' in H\n                        | [ H : forall n, 0 <= n -> Z.testbit _ n = ?b |- _ ]\n                          => apply bits_const_iff in H\n                        end ].\n  Qed.\n\n  Lemma testbit_small_neg a b\n        (Ha : - 2^b <= a < 0)\n        (Hb : 0 < b) :\n    Z.testbit a b = true.\n  Proof using Type.\n    destruct Ha; apply Z_le_lt_eq_dec in H; destruct H.\n    - apply Z.bits_iff_neg with (n:=b) in H0; [assumption|].\n      apply Log2.Z.log2_lt_pow2_alt; try lia.\n    - subst; replace (- 2 ^ b) with ((-1) * 2 ^ b) by ring.\n      rewrite Z.mul_pow2_bits, Z.sub_diag, Z.bit0_odd by lia; reflexivity. Qed.\n\n  Lemma testbit_large a b\n        (Ha : 2 ^ (b - 1) <= a < 2 ^ b)\n        (Hb : 0 < b) :\n    Z.testbit a (b - 1) = true.\n  Proof using Type.\n    destruct (Z.testbit a (b - 1)) eqn:E; try reflexivity.\n    rewrite Z.testbit_false in * by lia.\n    apply Z.div_exact in E; [|lia].\n    rewrite Div.Z.div_between_1 in E; auto with zarith.\n    rewrite Pow.Z.pow_mul_base, Z.sub_simpl_r; lia. Qed.\n\n   Lemma testbit_b2z a m :\n     Z.testbit a m = negb (Z.b2z (Z.testbit a m) =? 0).\n   Proof using Type. destruct (Z.testbit a m); reflexivity. Qed.\n\n   Lemma pos_le_bitwise a b (H : forall i, Bool.le (Pos.testbit a i) (Pos.testbit b i))\n     : Pos.le a b.\n   Proof using Type.\n     revert dependent a; induction b as [b IHb|b IHb|], a as [a|a|]; intros; try lia;\n       try solve [ change (a <= b)%positive;\n                   apply IHb;\n                   intro i; specialize (H (N.succ i)); destruct i; cbn in H; rewrite ?Pos.pred_N_succ in H; try assumption ].\n     all: first [ cbv [Pos.le]; cbn; rewrite Pos.compare_cont_Lt_not_Gt\n                | cbv [Pos.le]; cbn; rewrite Pos.compare_cont_Gt_not_Gt\n                | idtac ].\n     all: try solve [ apply IHb;\n                      intro i; specialize (H (N.succ i)); destruct i; cbn in H; rewrite ?Pos.pred_N_succ in H; try assumption\n                    | specialize (H 0%N); cbn in H; congruence ].\n     all: specialize (fun i => H (Npos i)).\n     all: lazymatch type of H with\n          | forall i, Bool.le (Pos.testbit ?a _) (Pos.testbit ?b _)\n            => change (forall i, Bool.le (Z.testbit (Zpos a) (Zpos i)) (Z.testbit (Zpos b) (Zpos i))) in H;\n                 specialize (H (Z.to_pos (Z.log2 (Zpos a))))\n          end.\n     all: rewrite Z2Pos.id in H by (apply Z.log2_pos; lia).\n     all: rewrite Z.bit_log2 in H by lia.\n     all: rewrite Z.bits_above_log2 in H; try apply Z.log2_pos; try lia.\n     all: cbn in H; try congruence.\n   Qed.\n\n   Lemma le_bitwise a b (Ha : 0 <= a) (Hb : 0 <= b)  (H : forall i, 0 <= i -> Bool.le (Z.testbit a i) (Z.testbit b i))\n     : Z.le a b.\n   Proof using Type.\n     destruct a as [|a|a], b as [|b|b]; try lia.\n     { specialize (H (Z.log2 (Zpos a)) (Z.log2_nonneg (Zpos a))).\n       rewrite Z.testbit_0_l, Z.bit_log2 in H by lia.\n       cbn in H; congruence. }\n     { apply pos_le_bitwise.\n       intro i; destruct i.\n       { specialize (H 0 ltac:(lia)); cbn in H.\n         destruct a, b; cbn in *; try reflexivity; try congruence. }\n       { refine (H (Zpos _) _); lia. } }\n   Qed.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/Testbit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7340465042181868}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  mult x (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj249_coqofml_F4k4qv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7340465037686478}}
{"text": "(*  This showcases a version of Higg's involution theorem.\n    The proof outline was taken from \n      \"On Some non-classical extensions of second-order \n       intuitionistic propositional calculus\"\n    by Andrej Scedrov.\n*)\nSection Higgs.\n\nImplicit Type p q P : Prop.\nVariable f : Prop -> Prop.\nHypothesis f_lc : (forall p q, (f p <-> f q) -> (p <-> q)).\nHypothesis f_eq : (forall p q,  (p <-> q) -> (f p <-> f q)).\n\nFact L1 P :\n  f P -> (f True <-> P).\nProof.\n  intros fp. split.\n  - intros fT. apply f_lc with True.\n    all: tauto.\n  - intros p. apply f_eq with P.\n    all: tauto.\nQed.\n\nFact L2 P :\n  f (f P) -> P.\nProof.\n  intros H%L1. apply (f_lc True P) in H; tauto.\nQed.\n\nFact L3 P :\n  f P -> f (f (f P)).\nProof.\n  intros fp.\n  apply L1 in fp as H.\n  specialize (f_eq (f P) True ltac:(tauto)) as E.\n  eapply f_eq with P.\n  all: tauto.\nQed.\n\nTheorem Involutive P :\n  f (f P) <-> P.\nProof.\n  apply f_lc. split.\n  - apply L2.\n  - apply L3.\nQed.\nEnd Higgs.\n\n\nDefinition PE := forall A B, (A <-> B) -> A = B.\n\nLemma PE_Involutive (f : Prop -> Prop) :\n  PE ->\n  (forall p q, (f p <-> f q) -> (p <-> q)) <->\n  forall P, f (f P) = P.\nProof.\n  intros pe. split.\n  - intros f_lc P.\n    apply pe, Involutive. try assumption.\n    intros A B. now intros ->%pe.\n  - intros inv. intros p q H%pe.\n    rewrite <-(inv p), <-(inv q).\n    now rewrite !H.\nQed.", "meta": {"author": "HermesMarc", "repo": "Coq_files", "sha": "1eea4f8c843f6ed43fca1c793c78b52ab9a45986", "save_path": "github-repos/coq/HermesMarc-Coq_files", "path": "github-repos/coq/HermesMarc-Coq_files/Coq_files-1eea4f8c843f6ed43fca1c793c78b52ab9a45986/Higgs_involution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.734046500252801}}
{"text": "(* I have not worked with any partners. *)\n(** * Basics: Functional Programming in Coq *)\n\n(* REMINDER:\n\n          #####################################################\n          ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n          #####################################################\n\n   (See the [Preface] for why.)\n\n*)\n\n(* ################################################################# *)\n(** * Introduction *)\n\n(** The functional programming style is founded on simple, everyday\n    mathematical intuition: If a procedure or method has no side\n    effects, then (ignoring efficiency) all we need to understand\n    about it is how it maps inputs to outputs -- that is, we can think\n    of it as just a concrete method for computing a mathematical\n    function.  This is one sense of the word \"functional\" in\n    \"functional programming.\"  The direct connection between programs\n    and simple mathematical objects supports both formal correctness\n    proofs and sound informal reasoning about program behavior.\n\n    The other sense in which functional programming is \"functional\" is\n    that it emphasizes the use of functions (or methods) as\n    _first-class_ values -- i.e., values that can be passed as\n    arguments to other functions, returned as results, included in\n    data structures, etc.  The recognition that functions can be\n    treated as data gives rise to a host of useful and powerful\n    programming idioms.\n\n    Other common features of functional languages include _algebraic\n    data types_ and _pattern matching_, which make it easy to\n    construct and manipulate rich data structures, and sophisticated\n    _polymorphic type systems_ supporting abstraction and code reuse.\n    Coq offers all of these features.\n\n    The first half of this chapter introduces the most essential\n    elements of Coq's functional programming language, called\n    _Gallina_.  The second half introduces some basic _tactics_ that\n    can be used to prove properties of Coq programs. *)\n\n(* ################################################################# *)\n(** * Enumerated Types *)\n\n(** One notable aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers a powerful mechanism for defining new\n    data types from scratch, with all these familiar types as\n    instances.\n\n    Naturally, the Coq distribution comes preloaded with an extensive\n    standard library providing definitions of booleans, numbers, and\n    many common data structures like lists and hash tables.  But there\n    is nothing magic or primitive about these library definitions.  To\n    illustrate this, we will explicitly recapitulate all the\n    definitions we need in this course, rather than just getting them\n    implicitly from the library. *)\n\n(* ================================================================= *)\n(** ** Days of the Week *)\n\n(** To see how this definition mechanism works, let's start with\n    a very simple example.  The following declaration tells Coq that\n    we are defining a new set of data values -- a _type_. *)\n\nInductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\n(** The type is called [day], and its members are [monday],\n    [tuesday], etc.  The second and following lines of the definition\n    can be read \"[monday] is a [day], [tuesday] is a [day], etc.\"\n\n    Having defined [day], we can write functions that operate on\n    days. *)\n\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\n(** One thing to note is that the argument and return types of\n    this function are explicitly declared.  Like most functional\n    programming languages, Coq can often figure out these types for\n    itself when they are not given explicitly -- i.e., it can do _type\n    inference_ -- but we'll generally include them to make reading\n    easier. *)\n\n(** Having defined a function, we should check that it works on\n    some examples.  There are actually three different ways to do this\n    in Coq.  First, we can use the command [Compute] to evaluate a\n    compound expression involving [next_weekday]. *)\n\nCompute (next_weekday friday).\n(* ==> monday : day *)\n\nCompute (next_weekday (next_weekday saturday)).\n(* ==> tuesday : day *)\n\n(** (We show Coq's responses in comments, but, if you have a\n    computer handy, this would be an excellent moment to fire up the\n    Coq interpreter under your favorite IDE -- either CoqIde or Proof\n    General -- and try this for yourself.  Load this file, [Basics.v],\n    from the book's Coq sources, find the above example, submit it to\n    Coq, and observe the result.)\n\n    Second, we can record what we _expect_ the result to be in the\n    form of a Coq example: *)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n(** This declaration does two things: it makes an\n    assertion (that the second weekday after [saturday] is [tuesday]),\n    and it gives the assertion a name that can be used to refer to it\n    later.  Having made the assertion, we can also ask Coq to verify\n    it, like this: *)\n\nProof. simpl. reflexivity.  Qed.\n\n(** The details are not important for now (we'll come back to\n    them in a bit), but essentially this can be read as \"The assertion\n    we've just made can be proved by observing that both sides of the\n    equality evaluate to the same thing, after some simplification.\"\n\n    Third, we can ask Coq to _extract_, from our [Definition], a\n    program in some other, more conventional, programming\n    language (OCaml, Scheme, or Haskell) with a high-performance\n    compiler.  This facility is very interesting, since it gives us a\n    way to go from proved-correct algorithms written in Gallina to\n    efficient machine code.  (Of course, we are trusting the\n    correctness of the OCaml/Haskell/Scheme compiler, and of Coq's\n    extraction facility itself, but this is still a big step forward\n    from the way most software is developed today.) Indeed, this is\n    one of the main uses for which Coq was developed.  We'll come back\n    to this topic in later chapters. *)\n\n(* ================================================================= *)\n(** ** Homework Submission Guidelines *)\n\n(** If you are using Software Foundations in a course, your instructor\n    may use automatic scripts to help grade your homework assignments.\n    In order for these scripts to work correctly (so that you get full\n    credit for your work!), please be careful to follow these rules:\n      - The grading scripts work by extracting marked regions of the\n        .v files that you submit.  It is therefore important that you\n        do not alter the \"markup\" that delimits exercises: the\n        Exercise header, the name of the exercise, the \"empty square\n        bracket\" marker at the end, etc.  Please leave this markup\n        exactly as you find it.\n      - Do not delete exercises.  If you skip an exercise (e.g.,\n        because it is marked Optional, or because you can't solve it),\n        it is OK to leave a partial proof in your .v file, but in this\n        case please make sure it ends with [Admitted] (not, for\n        example [Abort]). *)\n\n(* ================================================================= *)\n(** ** Booleans *)\n\n(** In a similar way, we can define the standard type [bool] of\n    booleans, with members [true] and [false]. *)\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\n(** Although we are rolling our own booleans here for the sake\n    of building up everything from scratch, Coq does, of course,\n    provide a default implementation of the booleans, together with a\n    multitude of useful functions and lemmas.  (Take a look at\n    [Coq.Init.Datatypes] in the Coq library documentation if you're\n    interested.)  Whenever possible, we'll name our own definitions\n    and theorems so that they exactly coincide with the ones in the\n    standard library.\n\n    Functions over booleans can be defined in the same way as\n    above: *)\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(** The last two of these illustrate Coq's syntax for\n    multi-argument function definitions.  The corresponding\n    multi-argument application syntax is illustrated by the following\n    \"unit tests,\" which constitute a complete specification -- a truth\n    table -- for the [orb] function: *)\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(** We can also introduce some familiar syntax for the boolean\n    operations we have just defined. The [Infix] command defines a new\n    symbolic notation for an existing definition. *)\n\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nExample test_orb5:  false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(** _A note on notation_: In [.v] files, we use square brackets\n    to delimit fragments of Coq code within comments; this convention,\n    also used by the [coqdoc] documentation tool, keeps them visually\n    separate from the surrounding text.  In the html version of the\n    files, these pieces of text appear in a [different font].\n\n    The command [Admitted] can be used as a placeholder for an\n    incomplete proof.  We'll use it in exercises, to indicate the\n    parts that we're leaving for you -- i.e., your job is to replace\n    [Admitted]s with real proofs. *)\n\n(** **** Exercise: 1 star (nandb)  *)\n(** Remove \"[Admitted.]\" and complete the definition of the following\n    function; then make sure that the [Example] assertions below can\n    each be verified by Coq.  (Remove \"[Admitted.]\" and fill in each\n    proof, following the model of the [orb] tests above.) The function\n    should return [true] if either or both of its inputs are\n    [false]. *)\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  (negb (andb b1 b2)).\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(** [] *)\n\n(** **** Exercise: 1 star (andb3)  *)\n(** Do the same for the [andb3] function below. This function should\n    return [true] when all of its inputs are [true], and [false]\n    otherwise. *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with\n    | true => (andb b2 b3)\n    | false => false\n  end.\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  (** [] *)\n\n(* ================================================================= *)\n(** ** Function Types *)\n\n(** Every expression in Coq has a type, describing what sort of\n    thing it computes. The [Check] command asks Coq to print the type\n    of an expression. *)\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\n\n(** Functions like [negb] itself are also data values, just like\n    [true] and [false].  Their types are called _function types_, and\n    they are written with arrows. *)\n\nCheck negb.\n(* ===> negb : bool -> bool *)\n\n(** The type of [negb], written [bool -> bool] and pronounced\n    \"[bool] arrow [bool],\" can be read, \"Given an input of type\n    [bool], this function produces an output of type [bool].\"\n    Similarly, the type of [andb], written [bool -> bool -> bool], can\n    be read, \"Given two inputs, both of type [bool], this function\n    produces an output of type [bool].\" *)\n\n(* ================================================================= *)\n(** ** Modules *)\n\n(** Coq provides a _module system_, to aid in organizing large\n    developments.  In this course we won't need most of its features,\n    but one is useful: If we enclose a collection of declarations\n    between [Module X] and [End X] markers, then, in the remainder of\n    the file after the [End], these definitions are referred to by\n    names like [X.foo] instead of just [foo].  We will use this\n    feature to introduce the definition of the type [nat] in an inner\n    module so that it does not interfere with the one from the\n    standard library (which we want to use in the rest because it\n    comes with a tiny bit of convenient special notation).  *)\n\nModule NatPlayground.\n\n(* ================================================================= *)\n(** ** Numbers *)\n\n(** The types we have defined so far are examples of \"enumerated\n    types\": their definitions explicitly enumerate a finite set of\n    elements.  A more interesting way of defining a type is to give a\n    collection of _inductive rules_ describing its elements.  For\n    example, we can define (a unary representation of) the natural\n    numbers as follows: *)\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(** The clauses of this definition can be read:\n      - [O] is a natural number (note that this is the letter \"[O],\"\n        not the numeral \"[0]\").\n      - [S] can be put in front of a natural number to yield another\n        one -- if [n] is a natural number, then [S n] is too. *)\n\n(** Let's look at this in a little more detail.\n\n    Every inductively defined set ([day], [nat], [bool], etc.) is\n    actually a set of _expressions_ built from _constructors_\n    like [O], [S], [true], [false], [monday], etc.  The definition of\n    [nat] says how expressions in the set [nat] can be built:\n\n    - [O] and [S] are constructors;\n    - the expression [O] belongs to the set [nat];\n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat]. *)\n\n(** The same rules apply for our definitions of [day] and\n    [bool]. (The annotations we used for their constructors are\n    analogous to the one for the [O] constructor, indicating that they\n    don't take any arguments.)\n\n    The above conditions are the precise force of the [Inductive]\n    declaration.  They imply that the expression [O], the expression\n    [S O], the expression [S (S O)], the expression [S (S (S O))], and\n    so on all belong to the set [nat], while other expressions built\n    from data constructors, like [true], [andb true false], [S (S\n    false)], and [O (O (O S))] do not.\n\n    A critical point here is that what we've done so far is just to\n    define a _representation_ of numbers: a way of writing them down.\n    The names [O] and [S] are arbitrary, and at this point they have\n    no special meaning -- they are just two different marks that we\n    can use to write down numbers (together with a rule that says any\n    [nat] will be written as some string of [S] marks followed by an\n    [O]).  If we like, we can write essentially the same definition\n    this way: *)\n\nInductive nat' : Type :=\n  | stop : nat'\n  | tick : nat' -> nat'.\n\n(** The _interpretation_ of these marks comes from how we use them to\n    compute. *)\n\n(** We can do this by writing functions that pattern match on\n    representations of natural numbers just as we did above with\n    booleans and days -- for example, here is the predecessor\n    function: *)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\n(** The second branch can be read: \"if [n] has the form [S n']\n    for some [n'], then return [n'].\"  *)\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\n(** Because natural numbers are such a pervasive form of data,\n    Coq provides a tiny bit of built-in magic for parsing and printing\n    them: ordinary arabic numerals can be used as an alternative to\n    the \"unary\" notation defined by the constructors [S] and [O].  Coq\n    prints numbers in arabic form by default: *)\n\nCheck (S (S (S (S O)))).\n  (* ===> 4 : nat *)\nCompute (minustwo 4).\n  (* ===> 2 : nat *)\n\n(** The constructor [S] has the type [nat -> nat], just like the\n    functions [minustwo] and [pred]: *)\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\n(** These are all things that can be applied to a number to yield a\n    number.  However, there is a fundamental difference between the\n    first one and the other two: functions like [pred] and [minustwo]\n    come with _computation rules_ -- e.g., the definition of [pred]\n    says that [pred 2] can be simplified to [1] -- while the\n    definition of [S] has no such behavior attached.  Although it is\n    like a function in the sense that it can be applied to an\n    argument, it does not _do_ anything at all!  It is just a way of\n    writing down numbers.  (Think about standard arabic numerals: the\n    numeral [1] is not a computation; it's a piece of data.  When we\n    write [111] to mean the number one hundred and eleven, we are\n    using [1], three times, to write down a concrete representation of\n    a number.)\n\n    For most function definitions over numbers, just pattern matching\n    is not enough: we also need recursion.  For example, to check that\n    a number [n] is even, we may need to recursively check whether\n    [n-2] is even.  To write such functions, we use the keyword\n    [Fixpoint]. *)\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(** We can define [oddb] by a similar [Fixpoint] declaration, but here\n    is a simpler definition: *)\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(** (You will notice if you step through these proofs that\n    [simpl] actually has no effect on the goal -- all of the work is\n    done by [reflexivity].  We'll see more about why that is shortly.)\n\n    Naturally, we can also define multi-argument functions by\n    recursion.  *)\n\nModule NatPlayground2.\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\n(** Adding three to two now gives us five, as we'd expect. *)\n\nCompute (plus 3 2).\n\n(** The simplification that Coq performs to reach this conclusion can\n    be visualized as follows: *)\n\n(*  [plus (S (S (S O))) (S (S O))]\n==> [S (plus (S (S O)) (S (S O)))]\n      by the second clause of the [match]\n==> [S (S (plus (S O) (S (S O))))]\n      by the second clause of the [match]\n==> [S (S (S (plus O (S (S O)))))]\n      by the second clause of the [match]\n==> [S (S (S (S (S O))))]\n      by the first clause of the [match]\n*)\n\n(** As a notational convenience, if two or more arguments have\n    the same type, they can be written together.  In the following\n    definition, [(n m : nat)] means just the same as if we had written\n    [(n : nat) (m : nat)]. *)\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(** You can match two expressions at once by putting a comma\n    between them: *)\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\n(** The _ in the first line is a _wildcard pattern_.  Writing _ in a\n    pattern is the same as writing some variable that doesn't get used\n    on the right-hand side.  This avoids the need to invent a variable\n    name. *)\n\nEnd NatPlayground2.\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\n(** **** Exercise: 1 star (factorial)  *)\n(** Recall the standard mathematical factorial function:\n\n       factorial(0)  =  1\n       factorial(n)  =  n * factorial(n-1)     (if n>0)\n\n    Translate this into Coq. *)\n\nFixpoint factorial (n:nat) : nat :=\n  match n with\n    | O => S O\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  (** [] *)\n\n(** We can make numerical expressions a little easier to read and\n    write by introducing _notations_ for addition, multiplication, and\n    subtraction. *)\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\n(** (The [level], [associativity], and [nat_scope] annotations\n    control how these notations are treated by Coq's parser.  The\n    details are not important for our purposes, but interested readers\n    can refer to the optional \"More on Notation\" section at the end of\n    this chapter.)\n\n    Note that these do not change the definitions we've already made:\n    they are simply instructions to the Coq parser to accept [x + y]\n    in place of [plus x y] and, conversely, to the Coq pretty-printer\n    to display [plus x y] as [x + y]. *)\n\n(** When we say that Coq comes with almost nothing built-in, we really\n    mean it: even equality testing for numbers is a user-defined\n    operation!  We now define a function [beq_nat], which tests\n    [nat]ural numbers for [eq]uality, yielding a [b]oolean.  Note the\n    use of nested [match]es (we could also have used a simultaneous\n    match, as we did in [minus].) *)\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\n(** The [leb] function tests whether its first argument is less than or\n  equal to its second argument, yielding a boolean. *)\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\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)  *)\n(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,\n    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for\n    this one, define it in terms of a previously defined function. *)\n\nDefinition blt_nat (n m : nat) : bool :=\n  match (leb n m) with\n    | true => match (beq_nat n m) with\n      | true => false\n      | false => true\n      end\n    | false => false\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\n(* ################################################################# *)\n(** * Proof by Simplification *)\n\n(** Now that we've defined a few datatypes and functions, let's\n    turn to stating and proving properties of their behavior.\n    Actually, we've already started doing this: each [Example] in the\n    previous sections makes a precise claim about the behavior of some\n    function on some particular inputs.  The proofs of these claims\n    were always the same: use [simpl] to simplify both sides of the\n    equation, then use [reflexivity] to check that both sides contain\n    identical values.\n\n    The same sort of \"proof by simplification\" can be used to prove\n    more interesting properties as well.  For example, the fact that\n    [0] is a \"neutral element\" for [+] on the left can be proved just\n    by observing that [0 + n] reduces to [n] no matter what [n] is, a\n    fact that can be read directly off the definition of [plus].*)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity.  Qed.\n\n(** (You may notice that the above statement looks different in\n    the [.v] file in your IDE than it does in the HTML rendition in\n    your browser, if you are viewing both. In [.v] files, we write the\n    [forall] universal quantifier using the reserved identifier\n    \"forall.\"  When the [.v] files are converted to HTML, this gets\n    transformed into an upside-down-A symbol.)\n\n    This is a good place to mention that [reflexivity] is a bit\n    more powerful than we have admitted. In the examples we have seen,\n    the calls to [simpl] were actually not needed, because\n    [reflexivity] can perform some simplification automatically when\n    checking that two sides are equal; [simpl] was just added so that\n    we could see the intermediate state -- after simplification but\n    before finishing the proof.  Here is a shorter proof of the\n    theorem: *)\n\nTheorem plus_O_n' : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\n(** Moreover, it will be useful later to know that [reflexivity]\n    does somewhat _more_ simplification than [simpl] does -- for\n    example, it tries \"unfolding\" defined terms, replacing them with\n    their right-hand sides.  The reason for this difference is that,\n    if reflexivity succeeds, the whole goal is finished and we don't\n    need to look at whatever expanded expressions [reflexivity] has\n    created by all this simplification and unfolding; by contrast,\n    [simpl] is used in situations where we may have to read and\n    understand the new goal that it creates, so we would not want it\n    blindly expanding definitions and leaving the goal in a messy\n    state.\n\n    The form of the theorem we just stated and its proof are almost\n    exactly the same as the simpler examples we saw earlier; there are\n    just a few differences.\n\n    First, we've used the keyword [Theorem] instead of [Example].\n    This difference is mostly a matter of style; the keywords\n    [Example] and [Theorem] (and a few others, including [Lemma],\n    [Fact], and [Remark]) mean pretty much the same thing to Coq.\n\n    Second, we've added the quantifier [forall n:nat], so that our\n    theorem talks about _all_ natural numbers [n].  Informally, to\n    prove theorems of this form, we generally start by saying \"Suppose\n    [n] is some number...\"  Formally, this is achieved in the proof by\n    [intros n], which moves [n] from the quantifier in the goal to a\n    _context_ of current assumptions.\n\n    The keywords [intros], [simpl], and [reflexivity] are examples of\n    _tactics_.  A tactic is a command that is used between [Proof] and\n    [Qed] to guide the process of checking some claim we are making.\n    We will see several more tactics in the rest of this chapter and\n    yet more in future chapters.\n\n    Other similar theorems can be proved with the same pattern. *)\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(** The [_l] suffix in the names of these theorems is\n    pronounced \"on the left.\" *)\n\n(** It is worth stepping through these proofs to observe how the\n    context and the goal change.  You may want to add calls to [simpl]\n    before [reflexivity] to see the simplifications that Coq performs\n    on the terms before checking that they are equal.\n\n    Although simplification is powerful enough to prove some fairly\n    general facts, there are many statements that cannot be handled by\n    simplification alone.  For instance, we cannot use it to prove\n    that [0] is also a neutral element for [+] _on the right_. *)\n\nTheorem plus_n_O : forall n, n = n + 0.\nProof.\n  intros n. simpl. (* Doesn't do anything! *)\n(** (Can you explain why this happens?  Step through both proofs\n    with Coq and notice how the goal and context change.)\n\n    When stuck in the middle of a proof, we can use the [Abort]\n    command to give up on it for the moment. *)\n\nAbort.\n\n(** The next chapter will introduce _induction_, a powerful\n    technique that can be used for proving this goal.  For the moment,\n    though, let's look at a few more simple tactics. *)\n\n(* ################################################################# *)\n(** * Proof by Rewriting *)\n\n(** This theorem is a bit more interesting than the others we've\n    seen: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\n(** Instead of making a universal claim about all numbers [n] and [m],\n    it talks about a more specialized property that only holds when [n\n    = m].  The arrow symbol is pronounced \"implies.\"\n\n    As before, we need to be able to reason by assuming we are given such\n    numbers [n] and [m].  We also need to assume the hypothesis\n    [n = m]. The [intros] tactic will serve to move all three of these\n    from the goal into assumptions in the current context.\n\n    Since [n] and [m] are arbitrary numbers, we can't just use\n    simplification to prove this theorem.  Instead, we prove it by\n    observing that, if we are assuming [n = m], then we can replace\n    [n] with [m] in the goal statement and obtain an equality with the\n    same expression on both sides.  The tactic that tells Coq to\n    perform this replacement is called [rewrite]. *)\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 using the hypothesis: *)\n  rewrite -> H.\n  reflexivity.  Qed.\n\n(** The first line of the proof moves the universally quantified\n    variables [n] and [m] into the context.  The second moves the\n    hypothesis [n = m] into the context and gives it the name [H].\n    The third tells Coq to rewrite the current goal ([n + n = m + m])\n    by replacing the left side of the equality hypothesis [H] with the\n    right side.\n\n    (The arrow symbol in the [rewrite] has nothing to do with\n    implication: it tells Coq to apply the rewrite from left to right.\n    To rewrite from right to left, you can use [rewrite <-].  Try\n    making this change in the above proof and see what difference it\n    makes.) *)\n\n(** **** Exercise: 1 star (plus_id_exercise)  *)\n(** Remove \"[Admitted.]\" and fill in the proof. *)\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 H.\n  rewrite <- H.\n  intros H'.\n  rewrite -> H'.\n  reflexivity.\nQed.\n\n(** The [Admitted] command tells Coq that we want to skip trying\n    to prove this theorem and just accept it as a given.  This can be\n    useful for developing longer proofs, since we can state subsidiary\n    lemmas that we believe will be useful for making some larger\n    argument, use [Admitted] to accept them on faith for the moment,\n    and continue working on the main argument until we are sure it\n    makes sense; then we can go back and fill in the proofs we\n    skipped.  Be careful, though: every time you say [Admitted] you\n    are leaving a door open for total nonsense to enter Coq's nice,\n    rigorous, formally checked world! *)\n\n(** We can also use the [rewrite] tactic with a previously proved\n    theorem instead of a hypothesis from the context. If the statement\n    of the previously proved theorem involves quantified variables,\n    as in the example below, Coq tries to instantiate them\n    by matching with the current goal. *)\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\n(** **** Exercise: 2 stars (mult_S_1)  *)\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 -> plus_1_l.\n  rewrite <- H.\n  reflexivity. Qed.\n\n  (* (N.b. This proof can actually be completed without using [rewrite],\n     but please do use [rewrite] for the sake of the exercise.) *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Case Analysis *)\n\n(** Of course, not everything can be proved by simple\n    calculation and rewriting: In general, unknown, hypothetical\n    values (arbitrary numbers, booleans, lists, etc.) can block\n    simplification.  For example, if we try to prove the following\n    fact using the [simpl] tactic as above, we get stuck. *)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n.\n  simpl.  (* does nothing! *)\nAbort.\n\n(** The reason for this is that the definitions of both\n    [beq_nat] and [+] begin by performing a [match] on their first\n    argument.  But here, the first argument to [+] is the unknown\n    number [n] and the argument to [beq_nat] is the compound\n    expression [n + 1]; neither can be simplified.\n\n    To make progress, we need to consider the possible forms of [n]\n    separately.  If [n] is [O], then we can calculate the final result\n    of [beq_nat (n + 1) 0] and check that it is, indeed, [false].  And\n    if [n = S n'] for some [n'], then, although we don't know exactly\n    what number [n + 1] yields, we can calculate that, at least, it\n    will begin with one [S], and this is enough to calculate that,\n    again, [beq_nat (n + 1) 0] will yield [false].\n\n    The tactic that tells Coq to consider, separately, the cases where\n    [n = O] and where [n = S n'] is called [destruct]. *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n  - reflexivity.\n  - reflexivity.   Qed.\n\n(** The [destruct] generates _two_ subgoals, which we must then\n    prove, separately, in order to get Coq to accept the theorem. The\n    annotation \"[as [| n']]\" is called an _intro pattern_.  It tells\n    Coq what variable names to introduce in each subgoal.  In general,\n    what goes between the square brackets is a _list of lists_ of\n    names, separated by [|].  In this case, the first component is\n    empty, since the [O] constructor is nullary (it doesn't have any\n    arguments).  The second component gives a single name, [n'], since\n    [S] is a unary constructor.\n\n    The [-] signs on the second and third lines are called _bullets_,\n    and they mark the parts of the proof that correspond to each\n    generated subgoal.  The proof script that comes after a bullet is\n    the entire proof for a subgoal.  In this example, each of the\n    subgoals is easily proved by a single use of [reflexivity], which\n    itself performs some simplification -- e.g., the first one\n    simplifies [beq_nat (S n' + 1) 0] to [false] by first rewriting\n    [(S n' + 1)] to [S (n' + 1)], then unfolding [beq_nat], and then\n    simplifying the [match].\n\n    Marking cases with bullets is entirely optional: if bullets are\n    not present, Coq simply asks you to prove each subgoal in\n    sequence, one at a time. But it is a good idea to use bullets.\n    For one thing, they make the structure of a proof apparent, making\n    it more readable. Also, bullets instruct Coq to ensure that a\n    subgoal is complete before trying to verify the next one,\n    preventing proofs for different subgoals from getting mixed\n    up. These issues become especially important in large\n    developments, where fragile proofs lead to long debugging\n    sessions.\n\n    There are no hard and fast rules for how proofs should be\n    formatted in Coq -- in particular, where lines should be broken\n    and how sections of the proof should be indented to indicate their\n    nested structure.  However, if the places where multiple subgoals\n    are generated are marked with explicit bullets at the beginning of\n    lines, then the proof will be readable almost no matter what\n    choices are made about other aspects of layout.\n\n    This is also a good place to mention one other piece of somewhat\n    obvious advice about line lengths.  Beginning Coq users sometimes\n    tend to the extremes, either writing each tactic on its own line\n    or writing entire proofs on one line.  Good style lies somewhere\n    in the middle.  One reasonable convention is to limit yourself to\n    80-character lines.\n\n    The [destruct] tactic can be used with any inductively defined\n    datatype.  For example, we use it next to prove that boolean\n    negation is involutive -- i.e., that negation is its own\n    inverse. *)\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** Note that the [destruct] here has no [as] clause because\n    none of the subcases of the [destruct] need to bind any variables,\n    so there is no need to specify any names.  (We could also have\n    written [as [|]], or [as []].)  In fact, we can omit the [as]\n    clause from _any_ [destruct] and Coq will fill in variable names\n    automatically.  This is generally considered bad style, since Coq\n    often makes confusing choices of names when left to its own\n    devices.\n\n    It is sometimes useful to invoke [destruct] inside a subgoal,\n    generating yet more proof obligations. In this case, we use\n    different kinds of bullets to mark goals on different \"levels.\"\n    For example: *)\n\nTheorem andb_commutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n\n(** Each pair of calls to [reflexivity] corresponds to the\n    subgoals that were generated after the execution of the [destruct c]\n    line right above it. *)\n\n(** Besides [-] and [+], we can use [*] (asterisk) as a third kind of\n    bullet.  We can also enclose sub-proofs in curly braces, which is\n    useful in case we ever encounter a proof that generates more than\n    three levels of subgoals: *)\n\nTheorem andb_commutative' : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  { destruct c.\n    { reflexivity. }\n    { reflexivity. } }\n  { destruct c.\n    { reflexivity. }\n    { reflexivity. } }\nQed.\n\n(** Since curly braces mark both the beginning and the end of a\n    proof, they can be used for multiple subgoal levels, as this\n    example shows. Furthermore, curly braces allow us to reuse the\n    same bullet shapes at multiple levels in a proof: *)\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.\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(** Before closing the chapter, let's mention one final\n    convenience.  As you may have noticed, many proofs perform case\n    analysis on a variable right after introducing it:\n\n       intros x y. destruct y as [|y].\n\n    This pattern is so common that Coq provides a shorthand for it: we\n    can perform case analysis on a variable when introducing it by\n    using an intro pattern instead of a variable name. For instance,\n    here is a shorter proof of the [plus_1_neq_0] theorem above. *)\n\nTheorem plus_1_neq_0' : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** If there are no arguments to name, we can just write [[]]. *)\n\nTheorem andb_commutative'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (andb_true_elim2)  *)\n(** Prove the following claim, marking cases (and subcases) with\n    bullets when you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros [] [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(** **** Exercise: 1 star (zero_nbeq_plus_1)  *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** More on Notation (Optional) *)\n\n(** (In general, sections marked Optional are not needed to follow the\n    rest of the book, except possibly other Optional sections.  On a\n    first reading, you might want to skim these sections so that you\n    know what's there for future reference.)\n\n    Recall the notation definitions for infix plus and times: *)\n\nNotation \"x + y\" := (plus 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(** For each notation symbol in Coq, we can specify its _precedence\n    level_ and its _associativity_.  The precedence level [n] is\n    specified by writing [at level n]; this helps Coq parse compound\n    expressions.  The associativity setting helps to disambiguate\n    expressions containing multiple occurrences of the same\n    symbol. For example, the parameters specified above for [+] and\n    [*] say that the expression [1+2*3*4] is shorthand for\n    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and\n    _left_, _right_, or _no_ associativity.  We will see more examples\n    of this later, e.g., in the [Lists]\n    chapter.\n\n    Each notation symbol is also associated with a _notation scope_.\n    Coq tries to guess what scope is meant from context, so when it\n    sees [S(O*O)] it guesses [nat_scope], but when it sees the\n    cartesian product (tuple) type [bool*bool] (which we'll see in\n    later chapters) it guesses [type_scope].  Occasionally, it is\n    necessary to help it out with percent-notation by writing\n    [(x*y)%nat], and sometimes in what Coq prints it will use [%nat]\n    to indicate what scope a notation is in.\n\n    Notation scopes also apply to numeral notation ([3], [4], [5],\n    etc.), so you may sometimes see [0%nat], which means [O] (the\n    natural number [0] that we're using in this chapter), or [0%Z],\n    which means the Integer zero (which comes from a different part of\n    the standard library).\n\n    Pro tip: Coq's notation mechanism is not especially powerful.\n    Don't expect too much from it! *)\n\n(* ================================================================= *)\n(** ** Fixpoints and Structural Recursion (Optional) *)\n\n(** Here is a copy of the definition of addition: *)\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\n(** When Coq checks this definition, it notes that [plus'] is\n    \"decreasing on 1st argument.\"  What this means is that we are\n    performing a _structural recursion_ over the argument [n] -- i.e.,\n    that we make recursive calls only on strictly smaller values of\n    [n].  This implies that all calls to [plus'] will eventually\n    terminate.  Coq demands that some argument of _every_ [Fixpoint]\n    definition is \"decreasing.\"\n\n    This requirement is a fundamental feature of Coq's design: In\n    particular, it guarantees that every function that can be defined\n    in Coq will terminate on all inputs.  However, because Coq's\n    \"decreasing analysis\" is not very sophisticated, it is sometimes\n    necessary to write functions in slightly unnatural ways. *)\n\n(** **** Exercise: 2 stars, optional (decreasing)  *)\n(** To get a concrete sense of this, find a way to write a sensible\n    [Fixpoint] definition (of a simple function on numbers, say) that\n    _does_ terminate on all inputs, but that Coq will reject because\n    of this restriction. *)\n\n(** Fixpoint sensible (n : nat) (m : nat) : nat :=\n  match n with\n  | O => m\n  | (S n') => match m with\n    | (S m') => (sensible n' m')\n    | O => (sensible m n)\n    end\n  end. *)\n(** [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 2 stars (boolean_functions)  *)\n(** Use the tactics you have learned so far to prove the following\n    theorem about boolean functions. *)\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 f. intros l. intros []. \n  - rewrite l. rewrite l. reflexivity.\n  - rewrite l. rewrite l. reflexivity.\nQed.\n\n(** Now state and prove a theorem [negation_fn_applied_twice] similar\n    to the previous one but where the second hypothesis says that the\n    function [f] has the property that [f x = negb x].*)\n\nTheorem negation_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 f. intros l. intros []. \n  - rewrite l. rewrite l. reflexivity.\n  - rewrite l. rewrite l. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, optional (andb_eq_orb)  *)\n(** Prove the following theorem.  (Hint: This one can be a bit tricky,\n    depending on how you approach it.  You will probably need both\n    [destruct] and [rewrite], but destructing everything in sight is\n    not the best way.) *)\n\nLemma andb_negb : forall (b : bool), (andb b (negb b)) = false.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma orb_negb : forall (b : bool), (orb b (negb b)) = true.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros [] [].\n  - reflexivity.\n  - rewrite andb_negb. rewrite orb_negb. intros h. rewrite<-h. reflexivity.\n  - rewrite andb_negb. rewrite orb_negb. intros h. rewrite<-h. reflexivity.\n  - reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (binary)  *)\n(** Consider a different, more efficient representation of natural\n    numbers using a binary rather than unary system.  That is, instead\n    of saying that each natural number is either zero or the successor\n    of a natural number, we can say that each binary number is either\n\n      - zero,\n      - twice a binary number, or\n      - one more than twice a binary number.\n\n    (a) First, write an inductive definition of the type [bin]\n        corresponding to this description of binary numbers.\n\n    (Hint: Recall that the definition of [nat] above,\n\n         Inductive nat : Type := | O : nat | S : nat -> nat.\n\n    says nothing about what [O] and [S] \"mean.\"  It just says \"[O] is\n    in the set called [nat], and if [n] is in the set then so is [S\n    n].\"  The interpretation of [O] as zero and [S] as successor/plus\n    one comes from the way that we _use_ [nat] values, by writing\n    functions to do things with them, proving things about them, and\n    so on.  Your definition of [bin] should be correspondingly simple;\n    it is the functions you will write next that will give it\n    mathematical meaning.)\n\n    (b) Next, write an increment function [incr] for binary numbers,\n        and a function [bin_to_nat] to convert binary numbers to unary\n        numbers.\n\n    (c) Write five unit tests [test_bin_incr1], [test_bin_incr2], etc.\n        for your increment and binary-to-unary functions.  (A \"unit\n        test\" in Coq is a specific [Example] that can be proved with\n        just [reflexivity], as we've done for several of our\n        definitions.)  Notice that incrementing a binary number and\n        then converting it to unary should yield the same result as\n        first converting it to unary and then incrementing. *)\n\nInductive bin : Type :=\n  | B : bin\n  | T : bin -> bin\n  | P : bin -> bin.\n\nFixpoint incr (b : bin) : bin := \n  match b with\n    | B => P B\n    | T b' => P b'\n    | P b' => T (incr b')\n  end.\n\nFixpoint bin_to_nat (b : bin) : nat :=\n  match b with\n    | B => 0\n    | T b' => mult (bin_to_nat b') 2\n    | P b' => S (mult (bin_to_nat b') 2)\n  end.\n\nExample test_bin_nat_convert1:  bin_to_nat B = 0.\nProof. simpl. reflexivity.  Qed.\nExample test_bin_nat_convert2:  bin_to_nat (P (T (P B))) = 5.\nProof. simpl. reflexivity.  Qed.\nExample test_bin_nat_convert3:  bin_to_nat (T (T (T (P B)))) = 8.\nProof. simpl. reflexivity.  Qed.\nExample test_bin_incr1:         bin_to_nat (P (incr (P B))) = 5.\nProof. simpl. reflexivity.  Qed.\nExample test_bin_incr2:         bin_to_nat (incr (P (incr (P B)))) = \n  2 * ((bin_to_nat (P B)) + 1) + 1 + 1.\nProof. simpl. reflexivity.  Qed.\nExample test_bin_incr3:         bin_to_nat (T (P (incr (P B)))) = \n  bin_to_nat (T (incr (incr (incr (incr (incr (T B))))))).\nProof. simpl. reflexivity.  Qed.\n(** [] *)\n\n(** $Date: 2017-08-24 17:13:02 -0400 (Thu, 24 Aug 2017) $ *)\n\n", "meta": {"author": "qq456cvb", "repo": "lf", "sha": "1a0b565880df5f4d891aa88c9674afeff8991cc8", "save_path": "github-repos/coq/qq456cvb-lf", "path": "github-repos/coq/qq456cvb-lf/lf-1a0b565880df5f4d891aa88c9674afeff8991cc8/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7340136850310887}}
{"text": "(** * Prop: Propositions and Evidence *)\n\nRequire Import Coq.Arith.Plus.\nRequire Import Cases.\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    In this chapter we take a deeper look at the way propositions are\n    expressed in Coq and at the structure of the logical evidence that\n    we construct when we carry out proofs.  \n\n    Some of the concepts in this chapter may seem a bit abstract on a\n    first encounter.  We've included a _lot_ of exercises, most of\n    which should be quite approachable even if you're still working on\n    understanding the details of the text.  Try to work as many of\n    them as you can, especially the one-starred exercises. \n\n*)\n(* ##################################################### *)\n(** * Inductively Defined Propositions *)\n\n(** This chapter will take us on a first tour of the\n    propositional (logical) side of Coq.  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.  The rules with no premises above the line are\n    called _axioms_.\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(* FILL IN HERE *)\n(* two \"minimal\" proofs and infinite proofs. 3+5, 5+3, 3+5+0, ... *)\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(** 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    We can use Coq's tactic scripting facility to assemble proofs that\n    particular numbers are [beautiful].  *)\n\nTheorem three_is_beautiful: beautiful 3.\nProof.\n   (* This simply follows from the axiom [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   (* appply (b_sum 3 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 axioms for both. *)\n   apply b_3.\n   apply b_5.\nQed.\n\n(* ##################################################### *)\n(** * Proof Objects *)\n\n(** Look again at the formal definition of the [beautiful]\n    property.  The opening keyword, [Inductive], has been used up to\n    this point to declare new types of _data_, such as numbers and\n    lists.  Does this interpretation also make sense for the Inductive\n    definition of [beautiful]?  That is, can we view evidence of\n    beauty as some kind of data structure? Yes, we can!\n\n    The trick is to introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can also say \"is a proof of.\"  For\n    example, the second line in the definition of [beautiful] declares\n    that [b_0 : beautiful 0].  Instead of \"[b_0] has type \n    [beautiful 0],\" we can say that \"[b_0] is a proof of [beautiful 0].\"\n    Similarly for [b_3] and [b_5]. *)\n\n(** This pun between types and propositions (between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\") is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation.\n<<\n                 propositions  ~  types\n                 proofs        ~  data values\n>>\n    Many useful insights follow from this connection.  To begin with, it\n    gives us a natural interpretation of the type of [b_sum] constructor: *)\n\nCheck b_sum.\n(* ===> b_sum : forall n m, \n                  beautiful n -> \n                  beautiful m -> \n                  beautiful (n+m) *)\n\n(** This can be read \"[b_sum] is a constructor that takes four\n    arguments -- two numbers, [n] and [m], and two values, of types\n    [beautiful n] and [beautiful m] -- and yields evidence for the\n    proposition [beautiful (n+m)].\" *)\n\n(** In view of this, we might wonder whether we can write an\n    expression of type [beautiful 8] by applying [b_sum] to\n    appropriate arguments.  Indeed, we can: *)\n\nCheck (b_sum 3 5 b_3 b_5).\nCheck (b_sum 3 5).  \n(* ===> beautiful (3 + 5) *)\n\n(** The expression [b_sum 3 5 b_3 b_5] can be thought of as\n    instantiating the parameterized constructor [b_sum] with the\n    specific arguments [3] [5] and the corresponding proof objects for\n    its premises [beautiful 3] and [beautiful 5] (Coq is smart enough\n    to figure out that 3+5=8).  Alternatively, we can think of [b_sum]\n    as a primitive \"evidence constructor\" that, when applied to two\n    particular numbers, wants to be further applied to evidence that\n    those two numbers are beautiful; its type, \n[[  \n    forall n m, beautiful n -> beautiful m -> beautiful (n+m),\n    expresses this functionality, in the same way that the polymorphic\n    type [forall X, list X] in the previous chapter expressed the fact\n    that the constructor [nil] can be thought of as a function from\n    types to empty lists with elements of that type. *)\n\n(** This gives us an alternative way to write the proof that [8] is\n    beautiful: *)\n\nTheorem eight_is_beautiful': beautiful 8.\nProof.\n   exact (b_sum 3 5 b_3 b_5).\nQed.\n\n\n\n(** Notice that we're using [apply] here in a new way: instead of just\n    supplying the _name_ of a hypothesis or previously proved theorem\n    whose type matches the current goal, we are supplying an\n    _expression_ that directly builds evidence with the required\n    type. *)\n\n(* ##################################################### *)\n(** ** Proof Scripts and Proof Objects *)\n\n(** These proof objects lie at the core of how Coq operates. \n\n    When Coq is following a proof script, what is happening internally\n    is that it is gradually constructing a proof object -- a term\n    whose type is the proposition being proved.  The tactics between\n    the [Proof] command and the [Qed] instruct Coq how to build up a\n    term of the required type.  To see this process in action, let's\n    use the [Show Proof] command to display the current state of the\n    proof tree at various points in the following tactic proof. *)\n\nTheorem eight_is_beautiful'': beautiful 8.\nProof.\n   Show Proof.\n   apply b_sum with (n:=3) (m:=5).\n   Show Proof.\n   apply b_3.\n   Show Proof.\n   apply b_5.\n\n   Show Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with some\n    \"holes\" (indicated by [?1], [?2], and so on), and it knows what\n    type of evidence is needed at each hole.  In the [Show Proof]\n    output, lines of the form [?1 -> beautiful n] record these\n    requirements.  (The [->] here has nothing to do with either\n    implication or function types -- it is just an unfortunate choice\n    of concrete syntax for the output!)  \n\n    Each of the holes corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    [Theorem] command gives a name to the evidence we've built and\n    stores it in the global context. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand.  Indeed, we don't even need the [Theorem]\n    command: we can instead use [Definition] to directly give a global\n    name to a piece of evidence. *)\n\nDefinition eight_is_beautiful''' : beautiful 8 :=\n  b_sum 3 5 b_3 b_5.\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint eight_is_beautiful.\n(* ===> eight_is_beautiful    = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful'.\n(* ===> eight_is_beautiful'   = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful''.\n(* ===> eight_is_beautiful''  = b_sum 3 5 b_3 b_5 : beautiful 8 *)\nPrint eight_is_beautiful'''.\n(* ===> eight_is_beautiful''' = b_sum 3 5 b_3 b_5 : beautiful 8 *)\n\n(** **** Exercise: 1 star (six_is_beautiful) *)\n(** Give a tactic proof and a proof object showing that [6] is [beautiful]. *)\n\nTheorem six_is_beautiful :\n  beautiful 6.\nProof.\n  apply b_sum with (n:=3) (m:=3); apply b_3.\nQed.\n\nDefinition six_is_beautiful' : beautiful 6 := (b_sum 3 3 b_3 b_3).\n\n(* Digression: In the spirit of \"everything is a proof object\", consider how we \n   defined the value \"admit\".  It has type T, for every single type T!\n   That's impossible.  So we use Coq's Admitted tactic, which says,\n   \"I give up for now; just assume this can be proven.\" For instance,\n   we can use Admitted to prove things that are blatantly False: *)\nTheorem foo: False. Admitted.\n(* We do the same thing for admit: *)\nDefinition admit {T: Type} : T.  Admitted.\n(* If we then ask \"what is the proof object for admit?\", Coq responds *)\nPrint admit.\n(* [*** [ admit : forall T : Type, T ]]\n   which is its way of saying, \"I don't know, but whatever it is,\n   it has type forall T:Type, T.\"  In fact, Coq will say something \n   similar for foo: *)\nPrint foo.\n(* [*** foo : False ], or in other words \"I don't know what this \n   value is, but it has type False *)\n\n(** [] *)\n\n(** **** Exercise: 1 star (nine_is_beautiful) *)\n(** Give a tactic proof and a proof object showing that [9] is [beautiful]. *)\n\nTheorem nine_is_beautiful :\n  beautiful 9.\nProof.\n  (* FILL IN HERE *)\napply (b_sum 3 6 b_3 six_is_beautiful).\nQed.\n\nDefinition nine_is_beautiful' : beautiful 9 := (b_sum 3 6 b_3 six_is_beautiful).\n  (* FILL IN HERE *)\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Implications and Functions *)\n\n(** In Coq's computational universe (where we've mostly been living\n    until this chapter), there are two sorts of values with arrows in\n    their types: _constructors_ introduced by [Inductive]-ly defined\n    data types, and _functions_.\n\n    Similarly, in Coq's logical universe, there are two ways of giving\n    evidence for an implication: constructors introduced by\n    [Inductive]-ly defined propositions, and... functions!\n\n    For example, consider this statement: *)\n\nTheorem b_plus3: forall (n:nat) (bn:beautiful n), beautiful (3+n).\nProof.\n  intros.\n  apply b_sum with (n:=3) (m:=n). exact b_3. exact bn.\n  Show Proof.\n\n(* fun (n : nat) (bn : beautiful n) => b_sum 3 n b_3 bn *)\nQed.\n\n(** What is the proof object corresponding to [b_plus3]? \n\n    We're looking for an expression whose _type_ is [forall n,\n    beautiful n -> beautiful (3+n)] -- that is, a _function_ that\n    takes two arguments (one number and a piece of evidence) and\n    returns a piece of evidence!  Here it is: *)\n\nDefinition b_plus3' : forall n, beautiful n -> beautiful (3+n) := \n  fun n => fun H : beautiful n =>\n    b_sum 3 n b_3 H.\n\nCheck b_plus3'.\n(* ===> b_plus3' : forall n, beautiful n -> beautiful (3+n) *)\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah].\"  Another equivalent way to write this definition is: *)\n\nDefinition b_plus3'' (n : nat) (H : beautiful n) : beautiful (3+n) := \n  b_sum 3 n b_3 H.\n\nCheck b_plus3''.\n(* ===> b_plus3'' : forall n, beautiful n -> beautiful (3+n) *)\n\n(** **** Exercise: 2 stars (b_times2) *)\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros. simpl. apply b_sum. exact H. rewrite plus_0_r. exact H.\nQed.\n\nTheorem b_times2': forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros. simpl. apply b_sum. exact H. apply b_sum. exact H. exact b_0.\nQed.\n\nPrint b_times2.\nPrint b_times2'.\n\n(** **** Exercise: 3 stars, optional (b_times2') *)\n(** Write a proof object corresponding to [b_times2] above *)\n\nDefinition b_times2'': forall n, beautiful n -> beautiful (2*n) :=\n  (* FILL IN HERE *)\n  fun (n:nat) (b_n : beautiful n) => b_sum n (n+0) b_n (b_sum n 0 b_n b_0).\n\n(** **** Exercise: 2 stars (b_timesm) *)\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m*n).\nProof.\n   (* FILL IN HERE *)\n\n(* 3*n = 2*n + 1*n  <-  b_2_mult and b_sum.\n 2+z * n = 2*n + z*n  <-  b_times2'' and H. *)\nintros x y H. induction H.\n Case \"x=0\". rewrite Mult.mult_0_r. apply b_0.\n Case \"x=3\". (* 3*y = sum of 3s *) induction y as [|y].\n  apply b_0.\n  simpl. apply (b_sum 3 (y*3) b_3 IHy).\n Case \"x=5\". induction y as [|y].\n  apply b_0.\n  simpl. apply (b_sum 5 (y*5) b_5 IHy).\n Case \"x=n+m\". \n  rewrite Mult.mult_plus_distr_l.\n  apply (b_sum (y*n) (y*m) IHbeautiful1 IHbeautiful2).\nQed.\n\n(** [] *)\n\n(* ####################################################### *)\n(** ** Induction Over Proof Objects *)\n\n(** Since we use the keyword [Induction] to define primitive\n    propositions together with their evidence, we might wonder whether\n    there are some sort of induction principles associated with these\n    definitions.  Indeed there are, and in this section we'll take a\n    look at how they can be used.  *)\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 us 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 gives rise to an _induction principle_ for proofs -- i.e., we\n    can use the [induction] tactic that we have already seen for\n    reasoning about inductively defined _data_ to reason about\n    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----------\ngorgeous 0\n\ngorgeous n\n----------\ngorgeous (3+n)\n\ngorgeous n\n----------\ngorgeous (5+n)\n\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(* Exercise: 2 stars (recommended)\n   Prove the reverse direction. *)\nTheorem gorgeous_sum: forall n m, gorgeous n -> gorgeous m -> gorgeous (n + m).\nProof.\n  (* FILL IN HERE *)\nintros n m N. induction N as [|n|n].\n   Case \"0\". intro H. apply H.\n   Case \"+ 3\". intro H. apply (g_plus3 (n+m) (IHN H)). (* modus ponens *)\n   Case \"+ 5\". intro H. apply (g_plus5 (n+m) (IHN H)).\nQed.\n\nTheorem beautiful__gorgeous : forall n, \n  beautiful n -> gorgeous n.\nProof.\n  (* FILL IN HERE *)\nintros n H. induction H.\n Case \"0\". apply g_0.\n Case \"3\". apply (g_plus3 0 g_0).\n Case \"5\". apply (g_plus5 0 g_0).\n Case \"n+m\". apply (gorgeous_sum n m IHbeautiful1 IHbeautiful2).\nQed.\n\n", "meta": {"author": "sboosali", "repo": "coq", "sha": "c09f90a114ed7948f8cdf75828832e7d01093a84", "save_path": "github-repos/coq/sboosali-coq", "path": "github-repos/coq/sboosali-coq/coq-c09f90a114ed7948f8cdf75828832e7d01093a84/Prop-part1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.8902942239389252, "lm_q1q2_score": 0.7340136832307197}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria.                       *)\n(* You may distribute this file under the terms of the CeCILL-B license *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(******************************************************************************)\n(*    The basic theory of paths over an eqType; this file is essentially a    *)\n(* complement to seq.v. Paths are non-empty sequences that obey a progression *)\n(* relation. They are passed around in three parts: the head and tail of the  *)\n(* sequence, and a proof of (boolean) predicate asserting the progression.    *)\n(* This \"exploded\" view is rarely embarrassing, as the first two parameters   *)\n(* are usually inferred from the type of the third; on the contrary, it saves *)\n(* the hassle of constantly constructing and destructing a dependent record.  *)\n(*    We define similarly cycles, for which we allow the empty sequence,      *)\n(* which represents a non-rooted empty cycle; by contrast, the \"empty\" path   *)\n(* from a point x is the one-item sequence containing only x.                 *)\n(*   We allow duplicates; uniqueness, if desired (as is the case for several  *)\n(* geometric constructions), must be asserted separately. We do provide       *)\n(* shorthand, but only for cycles, because the equational properties of       *)\n(* \"path\" and \"uniq\" are unfortunately  incompatible (esp. wrt \"cat\").        *)\n(*    We define notations for the common cases of function paths, where the   *)\n(* progress relation is actually a function. In detail:                       *)\n(*   path e x p == x :: p is an e-path [:: x_0; x_1; ... ; x_n], i.e., we     *)\n(*                 e x_i x_{i+1} for all i < n. The path x :: p starts at x   *)\n(*                 and ends at last x p.                                      *)\n(*  fpath f x p == x :: p is an f-path, where f is a function, i.e., p is of  *)\n(*                 the form [:: f x; f (f x); ...]. This is just a notation   *)\n(*                 for path (frel f) x p.                                     *)\n(*   sorted e s == s is an e-sorted sequence: either s = [::], or s = x :: p  *)\n(*                 is an e-path (this is oten used with e = leq or ltn).      *)\n(*    cycle e c == c is an e-cycle: either c = [::], or c = x :: p with       *)\n(*                 x :: (rcons p x) an e-path.                                *)\n(*   fcycle f c == c is an f-cycle, for a function f.                         *)\n(* traject f x n == the f-path of size n starting at x                        *)\n(*              := [:: x; f x; ...; iter n.-1 f x]                            *)\n(* looping f x n == the f-paths of size greater than n starting at x loop     *)\n(*                 back, or, equivalently, traject f x n contains all         *)\n(*                 iterates of f at x.                                        *)\n(* merge e s1 s2 == the e-sorted merge of sequences s1 and s2: this is always *)\n(*                 a permutation of s1 ++ s2, and is e-sorted when s1 and s2  *)\n(*                 are and e is total.                                        *)\n(*     sort e s == a permutation of the sequence s, that is e-sorted when e   *)\n(*                 is total (computed by a merge sort with the merge function *)\n(*                 above).                                                    *)\n(*   mem2 s x y == x, then y occur in the sequence (path) s; this is          *)\n(*                 non-strict: mem2 s x x = (x \\in s).                        *)\n(*     next c x == the successor of the first occurrence of x in the sequence *)\n(*                 c (viewed as a cycle), or x if x \\notin c.                 *)\n(*     prev c x == the predecessor of the first occurrence of x in the        *)\n(*                 sequence c (viewed as a cycle), or x if x \\notin c.        *)\n(*    arc c x y == the sub-arc of the sequece c (viewed as a cycle) starting  *)\n(*                 at the first occurrence of x in c, and ending just before  *)\n(*                 the next ocurrence of y (in cycle order); arc c x y        *)\n(*                 returns an unspecified sub-arc of c if x and y do not both *)\n(*                 occur in c.                                                *)\n(*  ucycle e c <-> ucycleb e c (ucycle e c is a Coercion target of type Prop) *)\n(* ufcycle f c <-> c is a simple f-cycle, for a function f.                   *)\n(*  shorten x p == the tail a duplicate-free subpath of x :: p with the same  *)\n(*                 endpoints (x and last x p), obtained by removing all loops *)\n(*                 from x :: p.                                               *)\n(* rel_base e e' h b <-> the function h is a functor from relation e to       *)\n(*                 relation e', EXCEPT at points whose image under h satisfy  *)\n(*                 the \"base\" predicate b:                                    *)\n(*                    e' (h x) (h y) = e x y UNLESS b (h x) holds             *)\n(*                 This is the statement of the side condition of the path    *)\n(*                 functorial mapping lemma map_path.                         *)\n(* fun_base f f' h b <-> the function h is a functor from function f to f',   *)\n(*                 except at the preimage of predicate b under h.             *)\n(* We also provide three segmenting dependently-typed lemmas (splitP, splitPl *)\n(* and splitPr) whose elimination split a path x0 :: p at an internal point x *)\n(* as follows:                                                                *)\n(*  - splitP applies when x \\in p; it replaces p with (rcons p1 x ++ p2), so  *)\n(*    that x appears explicitly at the end of the left part. The elimination  *)\n(*    of splitP will also simultaneously replace take (index x p) with p1 and *)\n(*    drop (index x p).+1 p with p2.                                          *)\n(*  - splitPl applies when x \\in x0 :: p; it replaces p with p1 ++ p2 and     *)\n(*    simulaneously generates an equation x = last x0 p.                      *)\n(*  - splitPr applies when x \\in p; it replaces p with (p1 ++ x :: p2), so x  *)\n(*    appears explicitly at the start of the right part.                      *)\n(* The parts p1 and p2 are computed using index/take/drop in all cases, but   *)\n(* only splitP attemps to subsitute the explicit values. The substitution of  *)\n(* p can be deferred using the dependent equation generation feature of       *)\n(* ssreflect, e.g.: case/splitPr def_p: {1}p / x_in_p => [p1 p2] generates    *)\n(* the equation p = p1 ++ p2 instead of performing the substitution outright. *)\n(*   Similarly, eliminating the loop removal lemma shortenP simultaneously    *)\n(* replaces shorten e x p with a fresh constant p', and last x p with         *)\n(* last x p'.                                                                 *)\n(*   Note that although all \"path\" functions actually operate on the          *)\n(* underlying sequence, we provide a series of lemmas that define their       *)\n(* interaction with thepath and cycle predicates, e.g., the cat_path equation *)\n(* can be used to split the path predicate after splitting the underlying     *)\n(* sequence.                                                                  *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Paths.\n\nVariables (n0 : nat) (T : Type).\n\nSection Path.\n\nVariables (x0_cycle : T) (e : rel T).\n\nFixpoint path x (p : seq T) :=\n  if p is y :: p' then e x y && path y p' else true.\n\nLemma cat_path x p1 p2 : path x (p1 ++ p2) = path x p1 && path (last x p1) p2.\nProof. by elim: p1 x => [|y p1 Hrec] x //=; rewrite Hrec -!andbA. Qed.\n\nLemma rcons_path x p y : path x (rcons p y) = path x p && e (last x p) y.\nProof. by rewrite -cats1 cat_path /= andbT. Qed.\n\nLemma pathP x p x0 :\n  reflect (forall i, i < size p -> e (nth x0 (x :: p) i) (nth x0 p i))\n          (path x p).\nProof.\nelim: p x => [|y p IHp] x /=; first by left.\napply: (iffP andP) => [[e_xy /IHp e_p [] //] | e_p].\nby split; [exact: (e_p 0) | apply/(IHp y) => i; exact: e_p i.+1].\nQed.\n\nDefinition cycle p := if p is x :: p' then path x (rcons p' x) else true.\n\nLemma cycle_path p : cycle p = path (last x0_cycle p) p.\nProof. by case: p => //= x p; rewrite rcons_path andbC. Qed.\n\nLemma rot_cycle p : cycle (rot n0 p) = cycle p.\nProof.\ncase: n0 p => [|n] [|y0 p] //=; first by rewrite /rot /= cats0.\nrewrite /rot /= -{3}(cat_take_drop n p) -cats1 -catA cat_path.\ncase: (drop n p) => [|z0 q]; rewrite /= -cats1 !cat_path /= !andbT andbC //.\nby rewrite last_cat; repeat bool_congr.\nQed.\n\nLemma rotr_cycle p : cycle (rotr n0 p) = cycle p.\nProof. by rewrite -rot_cycle rotrK. Qed.\n\nEnd Path.\n\nLemma eq_path e e' : e =2 e' -> path e =2 path e'.\nProof. by move=> ee' x p; elim: p x => //= y p IHp x; rewrite ee' IHp. Qed.\n\nLemma eq_cycle e e' : e =2 e' -> cycle e =1 cycle e'.\nProof. by move=> ee' [|x p] //=; exact: eq_path. Qed.\n\nLemma sub_path e e' : subrel e e' -> forall x p, path e x p -> path e' x p.\nProof. by move=> ee' x p; elim: p x => //= y p IHp x /andP[/ee'-> /IHp]. Qed.\n\nLemma rev_path e x p :\n  path e (last x p) (rev (belast x p)) = path (fun z => e^~ z) x p.\nProof.\nelim: p x => //= y p IHp x; rewrite rev_cons rcons_path -{}IHp andbC.\nby rewrite -(last_cons x) -rev_rcons -lastI rev_cons last_rcons.\nQed.\n\nEnd Paths.\n\nImplicit Arguments pathP [T e x p].\nPrenex Implicits pathP.\n\nSection EqPath.\n\nVariables (n0 : nat) (T : eqType) (x0_cycle : T) (e : rel T).\nImplicit Type p : seq T.\n\nCoInductive split x : seq T -> seq T -> seq T -> Type :=\n  Split p1 p2 : split x (rcons p1 x ++ p2) p1 p2.\n\nLemma splitP p x (i := index x p) :\n  x \\in p -> split x p (take i p) (drop i.+1 p).\nProof.\nmove=> p_x; have lt_ip: i < size p by rewrite index_mem.\nby rewrite -{1}(cat_take_drop i p) (drop_nth x lt_ip) -cat_rcons nth_index.\nQed.\n\nCoInductive splitl x1 x : seq T -> Type :=\n  Splitl p1 p2 of last x1 p1 = x : splitl x1 x (p1 ++ p2).\n\nLemma splitPl x1 p x : x \\in x1 :: p -> splitl x1 x p.\nProof.\nrewrite inE; case: eqP => [->| _ /splitP[]]; first by rewrite -(cat0s p).\nby split; exact: last_rcons.\nQed.\n\nCoInductive splitr x : seq T -> Type :=\n  Splitr p1 p2 : splitr x (p1 ++ x :: p2).\n\nLemma splitPr p x : x \\in p -> splitr x p.\nProof. by case/splitP=> p1 p2; rewrite cat_rcons. Qed.\n\nFixpoint next_at x y0 y p :=\n  match p with\n  | [::] => if x == y then y0 else x\n  | y' :: p' => if x == y then y' else next_at x y0 y' p'\n  end.\n\nDefinition next p x := if p is y :: p' then next_at x y y p' else x.\n\nFixpoint prev_at x y0 y p :=\n  match p with\n  | [::]     => if x == y0 then y else x\n  | y' :: p' => if x == y' then y else prev_at x y0 y' p'\n  end.\n\nDefinition prev p x := if p is y :: p' then prev_at x y y p' else x.\n\nLemma next_nth p x :\n  next p x = if x \\in p then\n               if p is y :: p' then nth y p' (index x p) else x\n             else x.\nProof.\ncase: p => //= y0 p. \nelim: p {2 3 5}y0 => [|y' p IHp] y /=; rewrite (eq_sym y) inE;\n  by case: ifP => // _; exact: IHp.\nQed.\n\nLemma prev_nth p x :\n  prev p x = if x \\in p then\n               if p is y :: p' then nth y p (index x p') else x\n             else x.\nProof.\ncase: p => //= y0 p; rewrite inE orbC.\nelim: p {2 5}y0 => [|y' p IHp] y; rewrite /= ?inE // (eq_sym y').\nby case: ifP => // _; exact: IHp.\nQed.\n\nLemma mem_next p x : (next p x \\in p) = (x \\in p).\nProof.\nrewrite next_nth; case p_x: (x \\in p) => //.\ncase: p (index x p) p_x => [|y0 p'] //= i _; rewrite inE.\nhave [lt_ip | ge_ip] := ltnP i (size p'); first by rewrite orbC mem_nth.\nby rewrite nth_default ?eqxx.\nQed.\n\nLemma mem_prev p x : (prev p x \\in p) = (x \\in p).\nProof.\nrewrite prev_nth; case p_x: (x \\in p) => //; case: p => [|y0 p] // in p_x *.\nby apply mem_nth; rewrite /= ltnS index_size.\nQed.\n\n(* ucycleb is the boolean predicate, but ucycle is defined as a Prop *)\n(* so that it can be used as a coercion target. *)\nDefinition ucycleb p := cycle e p && uniq p.\nDefinition ucycle p : Prop := cycle e p && uniq p.\n\n(* Projections, used for creating local lemmas. *)\nLemma ucycle_cycle p : ucycle p -> cycle e p.\nProof. by case/andP. Qed.\n\nLemma ucycle_uniq p : ucycle p -> uniq p.\nProof. by case/andP. Qed.\n\nLemma next_cycle p x : cycle e p -> x \\in p -> e x (next p x).\nProof.\ncase: p => //= y0 p; elim: p {1 3 5}y0 => [|z p IHp] y /=; rewrite inE.\n  by rewrite andbT; case: (x =P y) => // ->.\nby case/andP=> eyz /IHp; case: (x =P y) => // ->.\nQed.\n\nLemma prev_cycle p x : cycle e p -> x \\in p -> e (prev p x) x.\nProof.\ncase: p => //= y0 p; rewrite inE orbC.\nelim: p {1 5}y0 => [|z p IHp] y /=; rewrite ?inE.\n  by rewrite andbT; case: (x =P y0) => // ->.\nby case/andP=> eyz /IHp; case: (x =P z) => // ->.\nQed.\n\nLemma rot_ucycle p : ucycle (rot n0 p) = ucycle p.\nProof. by rewrite /ucycle rot_uniq rot_cycle. Qed.\n\nLemma rotr_ucycle p : ucycle (rotr n0 p) = ucycle p.\nProof. by rewrite /ucycle rotr_uniq rotr_cycle. Qed.\n\n(* The \"appears no later\" partial preorder defined by a path. *)\n\nDefinition mem2 p x y := y \\in drop (index x p) p.\n\nLemma mem2l p x y : mem2 p x y -> x \\in p.\nProof.\nby rewrite /mem2 -!index_mem size_drop => /ltn_predK; rewrite -subn_gt0 => <-.\nQed.\n\nLemma mem2lf {p x y} : x \\notin p -> mem2 p x y = false.\nProof. by apply: contraNF; exact: mem2l. Qed.\n\nLemma mem2r p x y : mem2 p x y -> y \\in p.\nProof.\nrewrite /mem2 => pxy.\nby rewrite -(cat_take_drop (index x p) p) mem_cat pxy orbT.\nQed.\n\nLemma mem2rf {p x y} : y \\notin p -> mem2 p x y = false.\nProof. by apply: contraNF; exact: mem2r. Qed.\n\nLemma mem2_cat p1 p2 x y :\n  mem2 (p1 ++ p2) x y = mem2 p1 x y || mem2 p2 x y || (x \\in p1) && (y \\in p2).\nProof.\nrewrite {1}/mem2 index_cat drop_cat; have [p1x | p1'x] := boolP (x \\in p1).\n  rewrite index_mem p1x mem_cat /= -orbA.\n  by have [|p2'y] := boolP (y \\in p2); [rewrite !orbT | rewrite (mem2rf p2'y)].\nby rewrite ltnNge leq_addr /= orbF addKn (mem2lf p1'x).\nQed.\n\nLemma mem2_splice p1 p3 x y p2 :\n   mem2 (p1 ++ p3) x y -> mem2 (p1 ++ p2 ++ p3) x y.\nProof.\nmove=> p13xy; move: p13xy; rewrite !mem2_cat mem_cat -orbA.\nby case/or3P=> [-> | -> | /andP[-> ->]]; rewrite ?orbT.\nQed.\n\nLemma mem2_splice1 p1 p3 x y z :\n  mem2 (p1 ++ p3) x y -> mem2 (p1 ++ z :: p3) x y.\nProof. exact: (mem2_splice [::z]). Qed.\n\nLemma mem2_cons x p y :\n  mem2 (x :: p) y =1 (if x == y then mem (x :: p) : pred T else mem2 p y).\nProof. by move=> z; rewrite {1}/mem2 /=; case (x == y). Qed.\n\nLemma mem2_last y0 p x : mem2 (y0 :: p) x (last y0 p) = (x \\in y0 :: p).\nProof.\napply/idP/idP; first exact: mem2l.\nrewrite -index_mem /mem2; move: (index x _) => i le_ip.\nby rewrite lastI drop_rcons ?size_belast // mem_rcons mem_head.\nQed.\n\nLemma mem2l_cat {p1 p2 x} : x \\notin p1 -> mem2 (p1 ++ p2) x =1 mem2 p2 x.\nProof. by move=> p1'x y; rewrite mem2_cat (negPf p1'x) mem2lf ?orbF. Qed.\n\nLemma mem2r_cat {p1 p2 x y} : y \\notin p2 -> mem2 (p1 ++ p2) x y = mem2 p1 x y.\nProof.\nby move=> p2'y; rewrite mem2_cat (negPf p2'y) -orbA orbC andbF mem2rf.\nQed.\n\nLemma mem2lr_splice {p1 p2 p3 x y} :\n  x \\notin p2 -> y \\notin p2 -> mem2 (p1 ++ p2 ++ p3) x y = mem2 (p1 ++ p3) x y.\nProof.\nmove=> p2'x p2'y; rewrite catA !mem2_cat !mem_cat.\nby rewrite (negPf p2'x) (negPf p2'y) (mem2lf p2'x) andbF !orbF.\nQed.\n\nCoInductive split2r x y : seq T -> Type :=\n  Split2r p1 p2 of y \\in x :: p2 : split2r x y (p1 ++ x :: p2).\n\nLemma splitP2r p x y : mem2 p x y -> split2r x y p.\nProof.\nmove=> pxy; have px := mem2l pxy.\nhave:= pxy; rewrite /mem2 (drop_nth x) ?index_mem ?nth_index //.\nby case/splitP: px => p1 p2; rewrite cat_rcons.\nQed.\n\nFixpoint shorten x p :=\n  if p is y :: p' then\n    if x \\in p then shorten x p' else y :: shorten y p'\n  else [::].\n\nCoInductive shorten_spec x p : T -> seq T -> Type :=\n   ShortenSpec p' of path e x p' & uniq (x :: p') & subpred (mem p') (mem p) :\n     shorten_spec x p (last x p') p'.\n\nLemma shortenP x p : path e x p -> shorten_spec x p (last x p) (shorten x p).\nProof.\nmove=> e_p; have: x \\in x :: p by exact: mem_head.\nelim: p x {1 3 5}x e_p => [|y2 p IHp] x y1.\n  by rewrite mem_seq1 => _ /eqP->.\nrewrite inE orbC /= => /andP[ey12 /IHp {IHp}IHp].\ncase: ifPn => [y2p_x _ | not_y2p_x /eqP def_x].\n  have [p' e_p' Up' p'p] := IHp _ y2p_x.\n  by split=> // y /p'p; exact: predU1r.\nhave [p' e_p' Up' p'p] := IHp y2 (mem_head y2 p).\nhave{p'p} p'p z: z \\in y2 :: p' -> z \\in y2 :: p.\n  by rewrite !inE; case: (z == y2) => // /p'p.\nrewrite -(last_cons y1) def_x; split=> //=; first by rewrite ey12.\nby rewrite (contra (p'p y1)) -?def_x.\nQed.\n\nEnd EqPath.\n\n\n(* Ordered paths and sorting. *)\n\nSection SortSeq.\n\nVariable T : eqType.\nVariable leT : rel T.\n\nDefinition sorted s := if s is x :: s' then path leT x s' else true.\n\nLemma path_sorted x s : path leT x s -> sorted s.\nProof. by case: s => //= y s /andP[]. Qed.\n\nLemma path_min_sorted x s :\n  {in s, forall y, leT x y} -> path leT x s = sorted s.\nProof. by case: s => //= y s -> //; exact: mem_head. Qed.\n\nSection Transitive.\n\nHypothesis leT_tr : transitive leT.\n\nLemma subseq_order_path x s1 s2 :\n  subseq s1 s2 -> path leT x s2 -> path leT x s1.\nProof.\nelim: s2 x s1 => [|y s2 IHs] x [|z s1] //= {IHs}/(IHs y).\ncase: eqP => [-> | _] IHs /andP[] => [-> // | leTxy /IHs /=].\nby case/andP=> /(leT_tr leTxy)->.\nQed.\n\nLemma order_path_min x s : path leT x s -> all (leT x) s.\nProof.\nmove/subseq_order_path=> le_x_s; apply/allP=> y.\nby rewrite -sub1seq => /le_x_s/andP[].\nQed.\n\nLemma subseq_sorted s1 s2 : subseq s1 s2 -> sorted s2 -> sorted s1.\nProof.\ncase: s1 s2 => [|x1 s1] [|x2 s2] //= sub_s12 /(subseq_order_path sub_s12).\nby case: eqP => [-> | _ /andP[]].\nQed.\n\nLemma sorted_filter a s : sorted s -> sorted (filter a s).\nProof. exact: subseq_sorted (filter_subseq a s). Qed.\n\nLemma sorted_uniq : irreflexive leT -> forall s, sorted s -> uniq s.\nProof.\nmove=> leT_irr; elim=> //= x s IHs s_ord.\nrewrite (IHs (path_sorted s_ord)) andbT; apply/negP=> s_x.\nby case/allPn: (order_path_min s_ord); exists x; rewrite // leT_irr.\nQed.\n\nLemma eq_sorted : antisymmetric leT ->\n  forall s1 s2, sorted s1 -> sorted s2 -> perm_eq s1 s2 -> s1 = s2.\nProof.\nmove=> leT_asym; elim=> [|x1 s1 IHs1] s2 //= ord_s1 ord_s2 eq_s12.\n  by case: {+}s2 (perm_eq_size eq_s12).\nhave s2_x1: x1 \\in s2 by rewrite -(perm_eq_mem eq_s12) mem_head.\ncase: s2 s2_x1 eq_s12 ord_s2 => //= x2 s2; rewrite in_cons.\ncase: eqP => [<- _| ne_x12 /= s2_x1] eq_s12 ord_s2.\n  by rewrite {IHs1}(IHs1 s2) ?(@path_sorted x1) // -(perm_cons x1).\ncase: (ne_x12); apply: leT_asym; rewrite (allP (order_path_min ord_s2)) //.\nhave: x2 \\in x1 :: s1 by rewrite (perm_eq_mem eq_s12) mem_head.\ncase/predU1P=> [eq_x12 | s1_x2]; first by case ne_x12.\nby rewrite (allP (order_path_min ord_s1)).\nQed.\n\nLemma eq_sorted_irr : irreflexive leT ->\n  forall s1 s2, sorted s1 -> sorted s2 -> s1 =i s2 -> s1 = s2.\nProof.\nmove=> leT_irr s1 s2 s1_sort s2_sort eq_s12.\nhave: antisymmetric leT.\n  by move=> m n /andP[? ltnm]; case/idP: (leT_irr m); exact: leT_tr ltnm.\nby move/eq_sorted; apply=> //; apply: uniq_perm_eq => //; exact: sorted_uniq.\nQed.\n\nEnd Transitive.\n\nHypothesis leT_total : total leT.\n\nFixpoint merge s1 :=\n  if s1 is x1 :: s1' then\n    let fix merge_s1 s2 :=\n      if s2 is x2 :: s2' then\n        if leT x2 x1 then x2 :: merge_s1 s2' else x1 :: merge s1' s2\n      else s1 in\n    merge_s1\n  else id.\n\nLemma merge_path x s1 s2 :\n  path leT x s1 -> path leT x s2 -> path leT x (merge s1 s2).\nProof.\nelim: s1 s2 x => //= x1 s1 IHs1.\nelim=> //= x2 s2 IHs2 x /andP[le_x_x1 ord_s1] /andP[le_x_x2 ord_s2].\ncase: ifP => le_x21 /=; first by rewrite le_x_x2 {}IHs2 // le_x21.\nby rewrite le_x_x1 IHs1 //=; have:= leT_total x2 x1; rewrite le_x21 /= => ->.\nQed.\n\nLemma merge_sorted s1 s2 : sorted s1 -> sorted s2 -> sorted (merge s1 s2).\nProof.\ncase: s1 s2 => [|x1 s1] [|x2 s2] //= ord_s1 ord_s2.\ncase: ifP => le_x21 /=.\n  by apply: (@merge_path x2 (x1 :: s1)) => //=; rewrite le_x21.\nby apply: merge_path => //=; have:= leT_total x2 x1; rewrite le_x21 /= => ->.\nQed.\n\nLemma perm_merge s1 s2 : perm_eql (merge s1 s2) (s1 ++ s2).\nProof.\napply/perm_eqlP; rewrite perm_eq_sym; elim: s1 s2 => //= x1 s1 IHs1.\nelim=> [|x2 s2 IHs2]; rewrite /= ?cats0 //.\ncase: ifP => _ /=; last by rewrite perm_cons.\nby rewrite (perm_catCA (_ :: _) [::x2]) perm_cons.\nQed.\n\nLemma mem_merge s1 s2 : merge s1 s2 =i s1 ++ s2.\nProof. by apply: perm_eq_mem; rewrite perm_merge. Qed.\n\nLemma size_merge s1 s2 : size (merge s1 s2) = size (s1 ++ s2).\nProof. by apply: perm_eq_size; rewrite perm_merge. Qed.\n\nLemma merge_uniq s1 s2 : uniq (merge s1 s2) = uniq (s1 ++ s2).\nProof. by apply: perm_eq_uniq; rewrite perm_merge. Qed.\n\nFixpoint merge_sort_push s1 ss :=\n  match ss with\n  | [::] :: ss' | [::] as ss' => s1 :: ss'\n  | s2 :: ss' => [::] :: merge_sort_push (merge s1 s2) ss'\n  end.\n\nFixpoint merge_sort_pop s1 ss :=\n  if ss is s2 :: ss' then merge_sort_pop (merge s1 s2) ss' else s1.\n\nFixpoint merge_sort_rec ss s :=\n  if s is [:: x1, x2 & s'] then\n    let s1 := if leT x1 x2 then [:: x1; x2] else [:: x2; x1] in\n    merge_sort_rec (merge_sort_push s1 ss) s'\n  else merge_sort_pop s ss.\n\nDefinition sort := merge_sort_rec [::].\n\nLemma sort_sorted s : sorted (sort s).\nProof.\nrewrite /sort; have allss: all sorted [::] by [].\nelim: {s}_.+1 {-2}s [::] allss (ltnSn (size s)) => // n IHn s ss allss.\nhave: sorted s -> sorted (merge_sort_pop s ss).\n  elim: ss allss s => //= s2 ss IHss /andP[ord_s2 ord_ss] s ord_s.\n  exact: IHss ord_ss _ (merge_sorted ord_s ord_s2).\ncase: s => [|x1 [|x2 s _]]; try by auto.\nmove/ltnW/IHn; apply=> {n IHn s}; set s1 := if _ then _ else _.\nhave: sorted s1 by exact: (@merge_sorted [::x2] [::x1]).\nelim: ss {x1 x2}s1 allss => /= [|s2 ss IHss] s1; first by rewrite andbT.\ncase/andP=> ord_s2 ord_ss ord_s1.\nby case: {1}s2=> /= [|_ _]; [rewrite ord_s1 | exact: IHss (merge_sorted _ _)].\nQed.\n\nLemma perm_sort s : perm_eql (sort s) s.\nProof.\nrewrite /sort; apply/perm_eqlP; pose catss := foldr (@cat T) [::].\nrewrite perm_eq_sym -{1}[s]/(catss [::] ++ s).\nelim: {s}_.+1 {-2}s [::] (ltnSn (size s)) => // n IHn s ss.\nhave: perm_eq (catss ss ++ s) (merge_sort_pop s ss).\n  elim: ss s => //= s2 ss IHss s1; rewrite -{IHss}(perm_eqrP (IHss _)).\n  by rewrite perm_catC catA perm_catC perm_cat2l -perm_merge.\ncase: s => // x1 [//|x2 s _]; move/ltnW; move/IHn=> {n IHn}IHs.\nrewrite -{IHs}(perm_eqrP (IHs _)) ifE; set s1 := if_expr _ _ _.\nrewrite (catA _ [::_;_] s) {s}perm_cat2r.\napply: (@perm_eq_trans _ (catss ss ++ s1)).\n  by rewrite perm_cat2l /s1 -ifE; case: ifP; rewrite // (perm_catC [::_]).\nelim: ss {x1 x2}s1 => /= [|s2 ss IHss] s1; first by rewrite cats0.\nrewrite perm_catC; case def_s2: {2}s2=> /= [|y s2']; first by rewrite def_s2.\nby rewrite catA -{IHss}(perm_eqrP (IHss _)) perm_catC perm_cat2l -perm_merge.\nQed.\n\nLemma mem_sort s : sort s =i s.\nProof. by apply: perm_eq_mem; rewrite perm_sort. Qed.\n\nLemma size_sort s : size (sort s) = size s.\nProof. by apply: perm_eq_size; rewrite perm_sort. Qed.\n\nLemma sort_uniq s : uniq (sort s) = uniq s.\nProof. by apply: perm_eq_uniq; rewrite perm_sort. Qed.\n\nLemma perm_sortP : transitive leT -> antisymmetric leT ->\n  forall s1 s2, reflect (sort s1 = sort s2) (perm_eq s1 s2).\nProof.\nmove=> leT_tr leT_asym s1 s2.\napply: (iffP idP) => eq12; last by rewrite -perm_sort eq12 perm_sort.\napply: eq_sorted; rewrite ?sort_sorted //.\nby rewrite perm_sort (perm_eqlP eq12) -perm_sort.\nQed.\n\nEnd SortSeq.\n\nLemma rev_sorted (T : eqType) (leT : rel T) s :\n  sorted leT (rev s) = sorted (fun y x => leT x y) s.\nProof. by case: s => //= x p; rewrite -rev_path lastI rev_rcons. Qed.\n\nLemma ltn_sorted_uniq_leq s : sorted ltn s = uniq s && sorted leq s.\nProof.\ncase: s => //= n s; elim: s n => //= m s IHs n.\nrewrite inE ltn_neqAle negb_or IHs -!andbA.\ncase sn: (n \\in s); last do !bool_congr.\nrewrite andbF; apply/and5P=> [[ne_nm lenm _ _ le_ms]]; case/negP: ne_nm.\nrewrite eqn_leq lenm; exact: (allP (order_path_min leq_trans le_ms)).\nQed.\n\nLemma iota_sorted i n : sorted leq (iota i n).\nProof. by elim: n i => // [[|n] //= IHn] i; rewrite IHn leqW. Qed.\n\nLemma iota_ltn_sorted i n : sorted ltn (iota i n).\nProof. by rewrite ltn_sorted_uniq_leq iota_sorted iota_uniq. Qed.\n\n(* Function trajectories. *)\n\nNotation fpath f := (path (coerced_frel f)).\nNotation fcycle f := (cycle (coerced_frel f)).\nNotation ufcycle f := (ucycle (coerced_frel f)).\n\nPrenex Implicits path next prev cycle ucycle mem2.\n\nSection Trajectory.\n\nVariables (T : Type) (f : T -> T).\n\nFixpoint traject x n := if n is n'.+1 then x :: traject (f x) n' else [::].\n\nLemma trajectS x n : traject x n.+1 = x :: traject (f x) n.\nProof. by []. Qed.\n\nLemma trajectSr x n : traject x n.+1 = rcons (traject x n) (iter n f x).\nProof. by elim: n x => //= n IHn x; rewrite IHn -iterSr. Qed.\n\nLemma last_traject x n : last x (traject (f x) n) = iter n f x.\nProof. by case: n => // n; rewrite iterSr trajectSr last_rcons. Qed.\n\nLemma traject_iteri x n :\n  traject x n = iteri n (fun i => rcons^~ (iter i f x)) [::].\nProof. by elim: n => //= n <-; rewrite -trajectSr. Qed.\n\nLemma size_traject x n : size (traject x n) = n.\nProof. by elim: n x => //= n IHn x //=; rewrite IHn. Qed.\n\nLemma nth_traject i n : i < n -> forall x, nth x (traject x n) i = iter i f x.\nProof.\nelim: n => // n IHn; rewrite ltnS leq_eqVlt => le_i_n x.\nrewrite trajectSr nth_rcons size_traject.\ncase: ltngtP le_i_n => [? _||->] //; exact: IHn.\nQed.\n\nEnd Trajectory.\n\nSection EqTrajectory.\n\nVariables (T : eqType) (f : T -> T).\n\nLemma eq_fpath f' : f =1 f' -> fpath f =2 fpath f'.\nProof. by move/eq_frel/eq_path. Qed.\n\nLemma eq_fcycle f' : f =1 f' -> fcycle f =1 fcycle f'.\nProof. by move/eq_frel/eq_cycle. Qed.\n\nLemma fpathP x p : reflect (exists n, p = traject f (f x) n) (fpath f x p).\nProof.\nelim: p x => [|y p IHp] x; first by left; exists 0.\nrewrite /= andbC; case: IHp => [fn_p | not_fn_p]; last first.\n  by right=> [] [[//|n]] [<- fn_p]; case: not_fn_p; exists n.\napply: (iffP eqP) => [-> | [[] // _ []//]].\nby have [n ->] := fn_p; exists n.+1.\nQed.\n\nLemma fpath_traject x n : fpath f x (traject f (f x) n).\nProof. by apply/(fpathP x); exists n. Qed.\n\nDefinition looping x n := iter n f x \\in traject f x n.\n\nLemma loopingP x n :\n  reflect (forall m, iter m f x \\in traject f x n) (looping x n).\nProof.\napply: (iffP idP) => loop_n; last exact: loop_n.\ncase: n => // n in loop_n *; elim=> [|m /= IHm]; first exact: mem_head.\nmove: (fpath_traject x n) loop_n; rewrite /looping !iterS -last_traject /=.\nmove: (iter m f x) IHm => y /splitPl[p1 p2 def_y].\nrewrite cat_path last_cat def_y; case: p2 => // z p2 /and3P[_ /eqP-> _] _.\nby rewrite inE mem_cat mem_head !orbT.\nQed.\n\nLemma trajectP x n y :\n  reflect (exists2 i, i < n & y = iter i f x) (y \\in traject f x n).\nProof.\nelim: n x => [|n IHn] x /=; first by right; case.\nrewrite inE; have [-> | /= neq_xy] := eqP; first by left; exists 0.\napply: {IHn}(iffP (IHn _)) => [[i] | [[|i]]] // lt_i_n ->.\n  by exists i.+1; rewrite ?iterSr.\nby exists i; rewrite ?iterSr.\nQed.\n\nLemma looping_uniq x n : uniq (traject f x n.+1) = ~~ looping x n.\nProof.\nrewrite /looping; elim: n x => [|n IHn] x //.\nrewrite {-3}[n.+1]lock /= -lock {}IHn -iterSr -negb_or inE; congr (~~ _).\napply: orb_id2r => /trajectP no_loop.\napply/idP/eqP => [/trajectP[m le_m_n def_x] | {1}<-]; last first.\n  by rewrite iterSr -last_traject mem_last.\nhave loop_m: looping x m.+1 by rewrite /looping iterSr -def_x mem_head.\nhave/trajectP[[|i] // le_i_m def_fn1x] := loopingP _ _ loop_m n.+1.\nby case: no_loop; exists i; rewrite -?iterSr // -ltnS (leq_trans le_i_m).\nQed.\n\nEnd EqTrajectory.\n\nImplicit Arguments fpathP [T f x p].\nImplicit Arguments loopingP [T f x n].\nImplicit Arguments trajectP [T f x n y].\nPrenex Implicits traject fpathP loopingP trajectP.\n\nSection UniqCycle.\n\nVariables (n0 : nat) (T : eqType) (e : rel T) (p : seq T).\n\nHypothesis Up : uniq p.\n\nLemma prev_next : cancel (next p) (prev p).\nProof.\nmove=> x; rewrite prev_nth mem_next next_nth; case p_x: (x \\in p) => //.\ncase def_p: p Up p_x => // [y q]; rewrite -{-1}def_p => /= /andP[not_qy Uq] p_x.\nrewrite -{2}(nth_index y p_x); congr (nth y _ _); set i := index x p.\nhave: ~~ (size q < i) by rewrite -index_mem -/i def_p leqNgt in p_x.\ncase: ltngtP => // [lt_i_q | ->] _; first by rewrite index_uniq.\nby apply/eqP; rewrite nth_default // eqn_leq index_size leqNgt index_mem.\nQed.\n\nLemma next_prev : cancel (prev p) (next p).\nProof.\nmove=> x; rewrite next_nth mem_prev prev_nth; case p_x: (x \\in p) => //.\ncase def_p: p p_x => // [y q]; rewrite -def_p => p_x.\nrewrite index_uniq //; last by rewrite def_p ltnS index_size.\ncase q_x: (x \\in q); first exact: nth_index.\nrewrite nth_default; last by rewrite leqNgt index_mem q_x.\nby apply/eqP; rewrite def_p inE q_x orbF eq_sym in p_x.\nQed.\n\nLemma cycle_next : fcycle (next p) p.\nProof.\ncase def_p: {-2}p Up => [|x q] Uq //.\napply/(pathP x)=> i; rewrite size_rcons => le_i_q.\nrewrite -cats1 -cat_cons nth_cat le_i_q /= next_nth {}def_p mem_nth //.\nrewrite index_uniq // nth_cat /= ltn_neqAle andbC -ltnS le_i_q.\nby case: (i =P _) => //= ->; rewrite subnn nth_default.\nQed.\n\nLemma cycle_prev : cycle (fun x y => x == prev p y) p.\nProof.\napply: etrans cycle_next; symmetry; case def_p: p => [|x q] //.\napply: eq_path; rewrite -def_p; exact (can2_eq prev_next next_prev).\nQed.\n\nLemma cycle_from_next : (forall x, x \\in p -> e x (next p x)) -> cycle e p.\nProof.\ncase: p (next p) cycle_next => //= [x q] n; rewrite -(belast_rcons x q x).\nmove: {q}(rcons q x) => q n_q; move/allP.\nby elim: q x n_q => //= _ q IHq x /andP[/eqP <- n_q] /andP[-> /IHq->].\nQed.\n\nLemma cycle_from_prev : (forall x, x \\in p -> e (prev p x) x) -> cycle e p.\nProof.\nmove=> e_p; apply: cycle_from_next => x p_x.\nby rewrite -{1}[x]prev_next e_p ?mem_next.\nQed.\n\nLemma next_rot : next (rot n0 p) =1 next p.\nProof.\nmove=> x; have n_p := cycle_next; rewrite -(rot_cycle n0) in n_p.\ncase p_x: (x \\in p); last by rewrite !next_nth mem_rot p_x.\nby rewrite (eqP (next_cycle n_p _)) ?mem_rot.\nQed.\n\nLemma prev_rot : prev (rot n0 p) =1 prev p.\nProof.\nmove=> x; have p_p := cycle_prev; rewrite -(rot_cycle n0) in p_p.\ncase p_x: (x \\in p); last by rewrite !prev_nth mem_rot p_x.\nby rewrite (eqP (prev_cycle p_p _)) ?mem_rot.\nQed.\n\nEnd UniqCycle.\n\nSection UniqRotrCycle.\n\nVariables (n0 : nat) (T : eqType) (p : seq T).\n\nHypothesis Up : uniq p.\n\nLemma next_rotr : next (rotr n0 p) =1 next p. Proof. exact: next_rot. Qed.\n\nLemma prev_rotr : prev (rotr n0 p) =1 prev p. Proof. exact: prev_rot. Qed.\n\nEnd UniqRotrCycle.\n\nSection UniqCycleRev.\n\nVariable T : eqType.\nImplicit Type p : seq T.\n\nLemma prev_rev p : uniq p -> prev (rev p) =1 next p.\nProof.\nmove=> Up x; case p_x: (x \\in p); last first.\n  by rewrite next_nth prev_nth mem_rev p_x.\ncase/rot_to: p_x (Up) => [i q def_p] Urp; rewrite -rev_uniq in Urp.\nrewrite -(prev_rotr i Urp); do 2 rewrite -(prev_rotr 1) ?rotr_uniq //.\nrewrite -rev_rot -(next_rot i Up) {i p Up Urp}def_p.\nby case: q => // y q; rewrite !rev_cons !(=^~ rcons_cons, rotr1_rcons) /= eqxx.\nQed.\n\nLemma next_rev p : uniq p -> next (rev p) =1 prev p.\nProof. by move=> Up x; rewrite -{2}[p]revK prev_rev // rev_uniq. Qed.\n\nEnd UniqCycleRev.\n\nSection MapPath.\n\nVariables (T T' : Type) (h : T' -> T) (e : rel T) (e' : rel T').\n\nDefinition rel_base (b : pred T) :=\n  forall x' y', ~~ b (h x') -> e (h x') (h y') = e' x' y'.\n\nLemma map_path b x' p' (Bb : rel_base b) :\n    ~~ has (preim h b) (belast x' p') ->\n  path e (h x') (map h p') = path e' x' p'.\nProof. by elim: p' x' => [|y' p' IHp'] x' //= /norP[/Bb-> /IHp'->]. Qed.\n\nEnd MapPath.\n\nSection MapEqPath.\n\nVariables (T T' : eqType) (h : T' -> T) (e : rel T) (e' : rel T').\n\nHypothesis Ih : injective h.\n\nLemma mem2_map x' y' p' : mem2 (map h p') (h x') (h y') = mem2 p' x' y'.\nProof. by rewrite {1}/mem2 (index_map Ih) -map_drop mem_map. Qed.\n\nLemma next_map p : uniq p -> forall x, next (map h p) (h x) = h (next p x).\nProof.\nmove=> Up x; case p_x: (x \\in p); last by rewrite !next_nth (mem_map Ih) p_x.\ncase/rot_to: p_x => i p' def_p.\nrewrite -(next_rot i Up); rewrite -(map_inj_uniq Ih) in Up.\nrewrite -(next_rot i Up) -map_rot {i p Up}def_p /=.\nby case: p' => [|y p''] //=; rewrite !eqxx.\nQed.\n\nLemma prev_map p : uniq p -> forall x, prev (map h p) (h x) = h (prev p x).\nProof.\nmove=> Up x; rewrite -{1}[x](next_prev Up) -(next_map Up).\nby rewrite prev_next ?map_inj_uniq.\nQed.\n\nEnd MapEqPath.\n\nDefinition fun_base (T T' : eqType) (h : T' -> T) f f' :=\n  rel_base h (frel f) (frel f').\n\nSection CycleArc.\n\nVariable T : eqType.\nImplicit Type p : seq T.\n\nDefinition arc p x y := let px := rot (index x p) p in take (index y px) px.\n\nLemma arc_rot i p : uniq p -> {in p, arc (rot i p) =2 arc p}.\nProof.\nmove=> Up x p_x y; congr (fun q => take (index y q) q); move: Up p_x {y}.\nrewrite -{1 2 5 6}(cat_take_drop i p) /rot cat_uniq => /and3P[_ Up12 _].\nrewrite !drop_cat !take_cat !index_cat mem_cat orbC.\ncase p2x: (x \\in drop i p) => /= => [_ | p1x].\n  rewrite index_mem p2x [x \\in _](negbTE (hasPn Up12 _ p2x)) /= addKn.\n  by rewrite ltnNge leq_addr catA.\nby rewrite p1x index_mem p1x addKn ltnNge leq_addr /= catA.\nQed.\n\nLemma left_arc x y p1 p2 (p := x :: p1 ++ y :: p2) :\n  uniq p -> arc p x y = x :: p1.\nProof.\nrewrite /arc /p [index x _]/= eqxx rot0 -cat_cons cat_uniq index_cat.\nmove: (x :: p1) => xp1 /and3P[_ /norP[/= /negbTE-> _] _].\nby rewrite eqxx addn0 take_size_cat.\nQed.\n\nLemma right_arc x y p1 p2 (p := x :: p1 ++ y :: p2) :\n  uniq p -> arc p y x = y :: p2.\nProof.\nrewrite -[p]cat_cons -rot_size_cat rot_uniq => Up.\nby rewrite arc_rot ?left_arc ?mem_head.\nQed.\n\nCoInductive rot_to_arc_spec p x y :=\n    RotToArcSpec i p1 p2 of x :: p1 = arc p x y\n                          & y :: p2 = arc p y x\n                          & rot i p = x :: p1 ++ y :: p2 :\n    rot_to_arc_spec p x y.\n\nLemma rot_to_arc p x y :\n  uniq p -> x \\in p -> y \\in p -> x != y -> rot_to_arc_spec p x y.\nProof.\nmove=> Up p_x p_y ne_xy; case: (rot_to p_x) (p_y) (Up) => [i q def_p] q_y.\nrewrite -(mem_rot i) def_p inE eq_sym (negbTE ne_xy) in q_y.\nrewrite -(rot_uniq i) def_p.\ncase/splitPr: q / q_y def_p => q1 q2 def_p Uq12; exists i q1 q2 => //.\n  by rewrite -(arc_rot i Up p_x) def_p left_arc.\nby rewrite -(arc_rot i Up p_y) def_p right_arc.\nQed.\n\nEnd CycleArc.\n\nPrenex Implicits arc.\n\n", "meta": {"author": "beta-ziliani", "repo": "ssreflect-1.4", "sha": "2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571", "save_path": "github-repos/coq/beta-ziliani-ssreflect-1.4", "path": "github-repos/coq/beta-ziliani-ssreflect-1.4/ssreflect-1.4-2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571/theories/path.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7339898903276488}}
{"text": "(* ================================================================== *)\nSection EX.\n\nVariables (A:Set) (P : A->Prop).\nVariable Q:Prop.\n\n(* Check the type of an expression. *)\nCheck P.  \n\nLemma trivial : forall x:A, P x -> P x.\nProof.\nintros x H.\nexact H.\nQed.\n\n\n(* Prints the definition of an identifier. *)\nPrint trivial.\n\n\nLemma example : forall x:A, (Q -> Q -> P x) -> Q -> P x.\nProof.\nintros x H1 H2.\napply H1.\nexact H2.\nexact H2.\nQed.\n\nPrint example.\n\nEnd EX.\n\nPrint trivial.\nPrint example.\n(* ================================================================== *)\n\n\n\n\n(* ================================================================== *)\n(* ====================== Propositional Logic ======================= *)\n(* ================================================================== *)\n\nSection ExamplesPL.\n\nVariables Q P :Prop.\n\nLemma ex1 : (P -> Q) -> ~Q -> ~P.\nProof.\nintros H1 H2.\nintro H3.\napply H2.\napply H1.\nexact H3.\nQed.\n\nPrint ex1.\n\nLemma ex1' : (P -> Q) -> ~Q -> ~P.\nProof.\nintros H1 H2.\nintro H3.\napply H2.\napply H1.\nexact H3.\nQed.\n\nPrint ex1'.\n\n\nLemma ex2 : P /\\ Q -> Q /\\ P.\nProof.\nintro H1.\ndestruct H1 as [H2 H3].\nsplit.\nexact H3.\nexact H2.\nQed.\n\n\nLemma ex3 : P \\/ Q -> Q \\/ P.\nProof.\nintro H.\ndestruct H as [H1 | H2].\nright; assumption.\nleft; assumption.\nQed.\n\n\n\nTheorem ex4 : forall A:Prop, A -> ~~A.\nProof.\nintro A.\nintro H1.\nintro H2.\napply H2.\nexact H1.\nQed.\n\nLemma ex4' : forall A:Prop, A -> ~~A.\nProof.\nintros A H1.\nred.\nintro H2.\nunfold not in H2.\napply H2.\nexact H1.\nSave.\n\n\n\n\nAxiom double_neg_law : forall A:Prop, ~~A -> A.  (* classical *)\n\n(* CAUTION: Axiom is a global declaration. \n   Even after the section is closed double_neg_law is assume in the enviroment, and can be used. \n   If we want to avoid this we should decalre double_neg_law using the command Hypothesis. \n*)  \n\n\nLemma ex5 : (~Q -> ~P) -> P -> Q.   (* this result is only valid classically *)\nProof.\nintros H1 H2.\napply double_neg_law.\nintro H3.\napply H1.\nexact H3.\nexact H2.\nQed.\n\n\nLemma ex6 : (P\\/Q)/\\~P -> Q.   \nProof.\nintro H1.\ndestruct H1 as [H2 H3].\napply double_neg_law.\nintro H4.\ndestruct H2 as [H5 | H6].\napply H3.\nexact H5.\napply H4.\nexact H6.\nQed.\n\n\nLemma ex6' : (P\\/Q)/\\~P -> Q.   \nProof.\nintros H1.\ndestruct H1 as [H2 H3].\ndestruct H2 as [H4 | H5].\ncontradiction.\nexact H5.\nQed.\n\nLemma ex7 : ~(P \\/ Q) <-> ~P /\\ ~Q.   \nProof.\nsplit.\n  (* left to right *)\n  intro H.\n  split.\n    unfold not in H.\n    intro H1.\n    apply H.\n    left; assumption.\n    intro H2.\n    apply H.\n    right; assumption.\n  (* right to left *)\n  intro H.\n  intro H1.\n  destruct H as [H2 H3].\n  destruct H1 as [H4 | H5].\n  apply H2.\n  exact H4.\n  apply H3.\n  exact H5.\nQed.\n\n\nLemma ex7' : ~(P \\/ Q) <-> ~P /\\ ~Q.\nProof.\ntauto.\nQed.\n\n\n\nVariable B :Prop.\nVariable C :Prop.\n\n\n(* exercise *)\nLemma ex8 : (P->Q) /\\ (B->C) /\\ P /\\ B -> Q/\\C. \nProof.\nintro H.\ndestruct H as [H1 H2].\ndestruct H2 as [H3 H4].\ndestruct H4 as [H5 H6].\nsplit.\n  apply H1.\n  exact H5.\n  apply H3.\n  exact H6.\nQed.\n \n(* exercise *)\nLemma ex9 : ~ (P /\\ ~P).   \nProof.\nintro H.\ndestruct H as [H1 H2].\napply H2.\nexact H1.\nQed.\n\nEnd ExamplesPL.\n\n(* ================================================================== *)\n(* =======================  First-Order Logic ======================= *)\n(* ================================================================== *)\n\nSection ExamplesFOL.\n\nVariable X :Set.\nVariable t :X. \nVariables R W : X -> Prop.\n\nLemma ex10 : R(t) -> (forall x, R(x)->~W(x)) -> ~W(t).\nProof.\nintros H1.\nintros H2.\napply H2.\nexact H1.\nQed.\n\n\nLemma ex11 : forall x, R x -> exists x, R x.\nProof.\nintro x.\nintro H1.\nexists x.\nexact H1.\nQed.\n\n\nLemma ex11' : forall x, R x -> exists x, R x.\nProof.\nfirstorder.\nQed.\n\n\nLemma ex12 : (exists x, ~(R x)) -> ~ (forall x, R x).\nProof.\nintro H.\nintro H1.\ndestruct H as [x H2].\napply H2.\napply H1.\nQed.\n\n(* Exercise *)\nLemma ex13 : (forall x, R x) \\/ (forall x, W x) -> forall x, (R x) \\/ (W x).\nProof.\nintro H.\nintro x.\ndestruct H as [H1 | H2].\nleft.\napply H1.\nright.\napply H2.\nQed.\n\nVariable G : X->X->Prop.\n\n(* Exercise *)\nLemma ex14 : (exists x, exists y, (G x y)) -> exists y, exists x, (G x y).\nProof.\nintro H.\ndestruct H as [x H1].\ndestruct H1 as [y H2].\nexists y.\nexists x.\nexact H2.\nQed.\n\n(* Exercise *)\nProposition ex15: (forall x, W x)/\\(forall x, R x) -> (forall x, W x /\\ R x).\nProof.\nintro H.\nintro x.\ndestruct H as [H1 H2].\nsplit.\napply H1.\napply H2.\nQed.\n\n\n(* ------- Note that we can have nested sections ----------- *)\nSection Relations.       \n\nVariable D : Set.\nVariable Rel : D->D->Prop.\n\nHypothesis R_symmetric : forall x y:D, Rel x y -> Rel y x.\nHypothesis R_transitive : forall x y z:D, Rel x y -> Rel y z -> Rel x z.\n\n\nLemma refl_if : forall x:D, (exists y, Rel x y) -> Rel x x.\nProof.\nintro H.\nintro H1.\ndestruct H1 as [y H2].\napply R_transitive with y.\nexact H2.\napply R_symmetric.\nexact H2.\nQed.\n\nCheck refl_if.\n\nEnd Relations.\n\nCheck refl_if. (* Note the difference after the end of the section Relations. *)\n\n\n\n(* ====== OTHER USES OF AXIOMS ====== *)\n\n(* --- A stack abstract data type --- *)\nSection Stack.\n\nVariable U:Type.\n\nParameter stack : Type -> Type.\nParameter emptyS : stack U. \nParameter push : U -> stack U -> stack U.\nParameter pop : stack U -> stack U.\nParameter top : stack U -> U.\nParameter isEmpty : stack U -> Prop.\n\nAxiom emptyS_isEmpty : isEmpty emptyS.\nAxiom push_notEmpty : forall x s, ~isEmpty (push x s).\nAxiom pop_push : forall x s, pop (push x s) = s.\nAxiom top_push : forall x s, top (push x s) = x.\n\nEnd Stack.\n\nCheck pop_push.\n\n(* Now we can make use of stacks in our formalisation!!! *)\n\n(* A NOTE OF CAUTION!!! *)\n(* The capability to extend the underlying theory with arbitary axiom \n   is a powerful but dangerous mechanism. We must avoid inconsistency. \n*)\nSection Caution.\n\nCheck False_ind.\n\nHypothesis ABSURD : False.\n\nTheorem oops : forall (P:Prop), P /\\ ~P.\nelim ABSURD.\nQed.\n\nEnd Caution. (* We have declared ABSURD as an hypothesis to avoid its use outside this section. *)\n\n\n\n", "meta": {"author": "vitorenesduarte", "repo": "the_coq_proof_assistant", "sha": "6aca5e1b0bba923a6b118838b1442f0876af5009", "save_path": "github-repos/coq/vitorenesduarte-the_coq_proof_assistant", "path": "github-repos/coq/vitorenesduarte-the_coq_proof_assistant/the_coq_proof_assistant-6aca5e1b0bba923a6b118838b1442f0876af5009/lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7339898895937793}}
{"text": "Set Implicit Arguments.\nRequire Import  List.\nRequire Import Eqdep.\nRequire Import Eqdep_dec.\nRequire Import Omega.\n\n\n(* Coq assignment - ZPF 2019 - due to 14.05.2019\n\nFill the definitions and prove the lemmas given below (replace \nAdmitted with Qed).\n\nIt is not allowed to: \n1. change/erase given definitions and lemma statements,\n   section header/footer, variable declaration, etc.,\n2. introduce your own axioms, parameters, variables, hypotheses etc.,   \n3. import other modules,\n4. define Ltac tactics.\n\nIt is allowed to:\n1. introduce your own definitions and auxiliary lemmas,\n2. change the order of the lemmas to prove,\n3. add comments. \n\nSubmit your solution via email before 23:59 on 14.05.2019. \nYou should submit one file named zal.v containing your proofs.\n\nThe author of the assignment and the grader is Daria Walukiewicz-Chrząszcz.\n\n*)\n\nSection filterL.\n(*------------------------------------------------------------------\nNondependent case : filter on lists\n--------------------------------------------------------------------\n*)\n\nPrint list.\n\nVariable A : Type.\nVariable P : A -> Prop.\n\nVariable P_dec : forall x, {P x}+{~P x}.\n\nFixpoint filterL (l:list A) : list A :=\nmatch l with\n| nil => nil\n| cons a l' => if P_dec a then cons a (filterL l') else filterL l'\nend.\n\nFixpoint countPL (l : list A) := \nmatch l with \n| nil => O\n| cons x l' => if P_dec x then S (countPL l') else countPL l'\nend.\n\n\n(* Prove lemmas cPL1 and cPL2 *)\n\nPrint Forall.\n\nLemma cPL1: forall (l:list A), countPL l = 0 -> \n           Forall (fun x => ~P x) l.\nProof.\nAdmitted.\n\n\nLemma cPL2: forall (l:list A), countPL l = length l -> Forall P l.\nProof.\nAdmitted.\n\n\n(* in case of troubles: think about the lengths of the lists *)\n\nEnd filterL.\n\n\nSection filterV.\n(*------------------------------------------------------------------\nDependent case: filter on vectors\n--------------------------------------------------------------------\n*)\n\n\nVariable A : Type.\nVariable P : A -> Prop.\n\nVariable P_dec : forall x, {P x}+{~P x}.\n\n\nInductive vector : nat -> Type :=\n  | Vnil : vector 0\n  | Vcons : forall {n}, A -> vector n -> vector (S n).\n\n  Arguments Vcons {_} _ _.\n\n(*\nWrite the definition of countPV on vectors; it should correspond to countPL \nUse keyword Fixpoint\n*)\n\n(*\nWrite the definition of filterV on vectors; it should correspond to filterL.\nUse keyword Fixpoint\n*)\n\n(*\nForallV is Forall on vectors\n*)\n\nPrint Forall.\n\nInductive ForallV (P:A-> Prop): forall {n:nat}, vector n -> Prop :=\n    Forall_Vnil : ForallV P Vnil\n  | Forall_Vcons : forall (x : A) (n:nat) (v : vector n),\n                  P x -> ForallV P v -> ForallV P (Vcons x v).\n\n\n\n(* \nWrite the definition of the last element of a nonempty vector. \nDo it twice:\n- using tactics in proof-mode\n- using Fixpoint and match\n\nFill:\n\nDefinition lastOfNonemptyByProof {n:nat} (v:vector (S n)): A := \nDefinition lastOfNonemptyByHand {n:nat} (v:vector (S n)) : A := \n*)\n\nVariable e1 e2 e3:A.\n\n(*\nand test it:\n\nEval compute in (lastOfNonemptyByProof (Vcons e1 (Vcons e2 (Vcons e3 Vnil)))). \nEval compute in (lastOfNonemptyByHand (Vcons e1 (Vcons e2 (Vcons e3 Vnil)))). \n*)\n\n\n(* \nProve lemmas cPV1 and cPV2\n*)\n\nLemma cPV1: forall (n:nat)(v:vector n), countPV v = 0 -> \n           ForallV (fun x => ~P x) v.\nProof.\nAdmitted.\n\n\nLemma cPV2: forall (n:nat) (v:vector n), countPV v = n -> ForallV P v.\nProof.\nAdmitted.\n\n(* Recall that UIP_refl nat is provable in Coq *)\n\nCheck (UIP_refl nat).\n\n\n(*\nProve the following inversion lemma \n*)\n\n\nLemma cPVInversion: forall (n:nat) (a:A) (v:vector n), \n      S n = countPV (Vcons a v) -> (P a /\\ n = countPV v).\nProof.\nAdmitted.\n\n(*\nProve cPVfilterVIdentity\n*)\n\n\nLemma cPVfilterVIdentity: forall (n:nat) (v:vector n) (d: n = countPV v),\nfilterV v = match d in _= m return vector m with\n                            | eq_refl => v\n                            end.\nProof.\nAdmitted.\n\n\n(* \ncPVtc is a type-cast needed to formulate the lemma given below\n*)\n\nLemma cPVtc : forall {n:nat} (v:vector n),  countPV v = countPV (filterV v).\nProof.\nAdmitted.\n\n(* \nUse the lemmas proved above to show that filterV is idempotent\n*)\n \n\nLemma filterV_idem: forall {n:nat} (v:vector n),\n      filterV (filterV v) = match cPVtc v in _= m return vector m with\n                            | eq_refl => filterV v\n                            end.\nProof.\nAdmitted.\n\nEnd filterV.\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/zal19_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.8807970873650401, "lm_q1q2_score": 0.7339898727345227}}
{"text": "Require Export Pairs.\nRequire Export Families.\n\nDefinition CProd (A B : set) : set :=\n  FamUnion A (fun a => Repl (fun b => ⟨a,b⟩) B).\n\nNotation \"A × B\" := (CProd A B) (at level 69).\n\nLemma CProd_I : ∀ a A b B, a ∈ A → b ∈ B → ⟨a, b⟩ ∈ CProd A B.\nProof.\n  intros. unfold CProd.\n  apply FamUnion_I with (x := a).\n    auto.\n    apply Repl_I. auto.\nQed.\n\nHint Resolve CProd_I.\n\nLemma CProd_E1 : ∀ p A B, p ∈ CProd A B → π1 p ∈ A ∧ π2 p ∈ B.\nProof.\n  intros. unfold CProd in H.\n  split;\n  apply FamUnion_E in H; destruct H; inv H;\n  apply Repl_E in H1; destruct H1; inv H.\n   rewrite Pair_E1. auto.\n   rewrite Pair_E2. auto.\nQed.\n\nHint Resolve CProd_E1.\n\nLemma CProd_E2 : ∀ p A B, p ∈ CProd A B → is_pair p.\nProof.\n  intros. unfold CProd in H. unfold is_pair.\n  apply FamUnion_E in H. destruct H. inv H.\n  apply Repl_E in H1. destruct H1. inv H.\n  exists x. exists x0. reflexivity.\nQed.\n\nHint Resolve CProd_E2.\n\nLemma empty_cross : ∀ B, ∅ × B = ∅.\nProof.\n  intros.\n  rewrite <- (Pair_E1 ∅ B).\n  extension.\n    apply FamUnion_E in H. destruct H. inv H.\n    apply Repl_E in H1. destruct H1. inv H.\n    rewrite Pair_E1 in H0.\n    contradiction (Empty_E x0).\n  apply FamUnion_I with (x := x). auto.\n  rewrite Pair_E1 in H.\n  contradiction (Empty_E x).\nQed.\n\nHint Resolve empty_cross.\n\nLemma cross_empty : ∀ A, A × ∅ = ∅.\nProof.\n  intros.\n  rewrite <- (Pair_E2 A ∅).\n  extension.\n    apply FamUnion_E in H. destruct H. inv H.\n    apply Repl_E in H1. destruct H1. inv H.\n    rewrite Pair_E2 in H1.\n    contradiction (Empty_E x1).\n  apply FamUnion_I with (x := x).\n    rewrite Pair_E2 in H.\n    contradiction (Empty_E x).\n  rewrite Pair_E2 in H.\n  contradiction (Empty_E x).\nQed.\n\nHint Resolve cross_empty.\n", "meta": {"author": "jwiegley", "repo": "set-theory", "sha": "ae9714a5b7355fb23b7383a0bc4c90dc00c50264", "save_path": "github-repos/coq/jwiegley-set-theory", "path": "github-repos/coq/jwiegley-set-theory/set-theory-ae9714a5b7355fb23b7383a0bc4c90dc00c50264/Products.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7339898581278649}}
{"text": "Require Import Omega.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Program.Basics.\nImport ListNotations.\n\nFrom q3_2001 Require Export misc.\nFrom q3_2001 Require Export nat_list_max.\nFrom q3_2001 Require Export ceil.\nFrom q3_2001 Require Export inequalities.\nFrom q3_2001 Require Export list_extra.\nFrom q3_2001 Require Export matrices.\n\nSection Question.\n\n  Variables (r : nat) (M : matrix nat r).\n\n  Definition c := col_count M.\n  Definition m := nat_list_max (map nunique (columns M)).\n  Definition n := nat_list_max (map nunique (rows M)).\n  Definition k := k' r c m n.\n\n  Definition is_good (v : list nat) (x : nat) := k <=? count_occ Nat.eq_dec v x.\n  Definition is_bad (v : list nat) (x : nat) := negb (is_good v x).\n  Definition is_both_good (vwx : list nat * list nat * nat) :=\n    match vwx with | (v, w, x) => is_good v x && is_good w x end.\n  Definition is_either_bad (vwx : list nat * list nat * nat) :=\n    match vwx with | (v, w, x) => is_bad v x || is_bad w x end.\n\n  Lemma is_bad_spec : forall (v : list nat),\n    let f := fun x => count_occ Nat.eq_dec v x <? k in\n      forall x, f x = is_bad v x.\n  Proof.\n    intros v f x. unfold f. unfold is_bad. unfold is_good.\n    destruct (Nat.leb_spec0 k (count_occ Nat.eq_dec v x)) as [Hx | Hx]; simpl.\n    - rewrite Nat.ltb_ge. assumption.\n    - rewrite Nat.ltb_lt. omega.\n  Qed.\n\n  Lemma m_spec : forall v, In v (columns M) -> nunique v <= m.\n  Proof. intros v Hv. unfold m. apply nat_list_max_spec_3. apply in_map. assumption. Qed.\n\n  Lemma n_spec : forall v, In v (rows M) -> nunique v <= n.\n  Proof. intros v Hv. unfold n. apply nat_list_max_spec_3. apply in_map. assumption. Qed.\n\n  Lemma is_either_bad_spec : forall (x : nat) (v w : list nat),\n    is_either_bad (v, w, x) = false <-> is_both_good (v, w, x) = true.\n  Proof.\n    intros x v w.\n    unfold is_either_bad. unfold is_both_good. unfold is_bad.\n    rewrite -> Bool.orb_false_iff. repeat (rewrite -> Bool.negb_false_iff). rewrite Bool.andb_true_iff.\n    reflexivity.\n  Qed.\n\n  Lemma mn_non_zero : r <> 0 -> c <> 0 -> m <> 0 /\\ n <> 0.\n  Proof.\n    intros Hr Hc.\n    unfold m. unfold n.\n    split; intros contra; rewrite nat_list_max_spec_4 in contra.\n    - assert (H : forall v, ~In v (columns M)). {\n        intros v Hv.\n        specialize (contra (nunique v) (in_map nunique (columns M) v Hv)).\n        apply nunique_spec_5 in contra.\n        apply columns_spec_0 in Hv.\n        rewrite contra in Hv. simpl in Hv. symmetry in Hv. contradiction.\n      }\n      apply list_in_nil in H.\n      unfold c in Hc. unfold col_count in Hc. rewrite H in Hc. simpl in Hc. contradiction.\n    - assert (H : forall v, ~In v (rows M)). {\n        intros v Hv.\n        specialize (contra (nunique v) (in_map nunique (rows M) v Hv)).\n        apply nunique_spec_5 in contra.\n        apply columns_spec_0 in Hv.\n        rewrite contra in Hv. simpl in Hv. symmetry in Hv. contradiction.\n      }\n      apply list_in_nil in H.\n      rewrite <- (rows_spec_1 M) in Hr. rewrite H in Hr. simpl in Hr. contradiction.\n  Qed.\n\n  Lemma single_col_bad_count : r <> 0 -> c <> 0 -> forall v, In v (columns M) ->\n    length (filter (is_bad v) v) <= (m-1) * (k-1).\n  Proof.\n    intros Hr Hc v Hv. destruct v as [| x v]; [apply Nat.le_0_l|].\n    rewrite <- (filter_ext _ _ _ (is_bad_spec (x::v))). apply list_length_nunique_php.\n    - discriminate.\n    - apply m_spec. assumption.\n    - rewrite -> (columns_spec_0 M (x::v) Hv).\n      apply k_spec_2; try (apply mn_non_zero); assumption.\n  Qed.\n\n  Lemma single_row_bad_count : r <> 0 -> c <> 0 -> forall v, In v (rows M) ->\n    length (filter (is_bad v) v) <= (n-1) * (k-1).\n  Proof.\n    intros Hr Hc v Hv. destruct v as [| x v]; [apply Nat.le_0_l|].\n    rewrite <- (filter_ext _ _ _ (is_bad_spec (x::v))). apply list_length_nunique_php.\n    - discriminate.\n    - apply n_spec. assumption.\n    - rewrite -> (rows_spec_0 M (x::v) Hv).\n      apply k_spec_3; try (apply mn_non_zero); assumption.\n  Qed.\n\n  Lemma col_bad_count : r <> 0 -> c <> 0 ->\n    let is_col_bad := fun (vwx : list nat * list nat * nat) => match vwx with | (v, w, x) => is_bad w x end in\n      length (filter_columnwise is_col_bad (matrix_by_row_and_column M)) <= c * ((m-1) * (k-1)).\n  Proof.\n    intros Hr Hc is_col_bad.\n    unfold c. rewrite <- matrix_by_row_and_column_spec_0.\n    apply filter_columnwise_bounded_length.\n    intros u Hu.\n    pose (w' := (map snd u)).\n    rewrite <- map_length with (f:=snd) (l:=(filter is_col_bad u)).\n    rewrite <- filter_map_commute with (fB:=(is_bad w')).\n    - apply matrix_by_row_and_column_spec_4 in Hu. fold w' in Hu. fold w'. apply single_col_bad_count; assumption.\n    - intros [[v w] x] Hvwx. simpl. apply (matrix_by_row_and_column_spec_2 M u) in Hvwx.\n      + subst. fold w'. reflexivity.\n      + assumption.\n  Qed.\n\n  Lemma row_bad_count : r <> 0 -> c <> 0 ->\n    let is_row_bad := fun (vwx : list nat * list nat * nat) => match vwx with | (v, w, x) => is_bad v x end in\n      length (filter_rowwise is_row_bad (matrix_by_row_and_column M)) <= r * ((n-1) * (k-1)).\n  Proof.\n    intros Hr Hc is_row_bad.\n    apply filter_rowwise_bounded_length.\n    intros u Hu.\n    pose (v' := (map snd u)).\n    rewrite <- map_length with (f:=snd) (l:=(filter is_row_bad u)).\n    rewrite <- filter_map_commute with (fB:=(is_bad v')).\n    - apply matrix_by_row_and_column_spec_5 in Hu. fold v'. apply single_row_bad_count; assumption.\n    - intros [[v w] x] Hvwx. simpl. apply (matrix_by_row_and_column_spec_3 M u) in Hvwx.\n      + subst. fold v'. reflexivity.\n      + assumption.\n  Qed.\n\n  Lemma either_bad_count : r <> 0 -> c <> 0 ->\n    length (filter_columnwise is_either_bad (matrix_by_row_and_column M)) < r*c.\n  Proof.\n    intros Hr Hc.\n    destruct (mn_non_zero Hr Hc) as [Hm Hn].\n    pose (is_row_bad := (fun (vwx : list nat * list nat * nat) => match vwx with | (v, w, x) => is_bad v x end)).\n    pose (is_col_bad := (fun (vwx : list nat * list nat * nat) => match vwx with | (v, w, x) => is_bad w x end)).\n    assert (H : forall vwx, is_either_bad vwx = (orf is_row_bad is_col_bad) vwx). { intros [[v w] x]. reflexivity. }\n    apply filter_ext with (l := (flatten_columnwise (matrix_by_row_and_column M))) in H.\n    unfold filter_columnwise. rewrite -> H.\n    assert (Hr' : length (filter_columnwise is_row_bad (matrix_by_row_and_column M)) <= r * ((n - 1) * (k - 1))). {\n      rewrite <- filter_columnwise_rowwise_same_length. apply row_bad_count; assumption. }\n    assert (Hc' : length (filter_columnwise is_col_bad (matrix_by_row_and_column M)) <= c * ((m - 1) * (k - 1))). {\n      apply col_bad_count; assumption. }\n    assert (Hrc : length (filter (orf is_row_bad is_col_bad) (flatten_columnwise (matrix_by_row_and_column M))) <=\n                  length (filter_columnwise is_row_bad (matrix_by_row_and_column M)) +\n                  length (filter_columnwise is_col_bad (matrix_by_row_and_column M))). {\n      apply list_filter_disjunction_length.\n    }\n    pose (Hk := (k_spec_5 _ _ _ _ Hr Hc Hm Hn)). fold k in Hk. omega.\n  Qed.\n\n  Theorem php_2d : r <> 0 -> c <> 0 -> exists x v w i j,\n    nth_error (rows M) i = Some v /\\\n    nth_error (columns M) j = Some w /\\\n    nth_error w i = Some x /\\\n    nth_error v j = Some x /\\\n    k <= count_occ Nat.eq_dec v x /\\\n    k <= count_occ Nat.eq_dec w x.\n  Proof.\n    intros Hr Hc.\n    apply either_bad_count in Hr; [| assumption].\n    unfold c in Hr. apply matrix_filter_by_row_and_column_spec_0 in Hr.\n    destruct Hr as [x [v [w [j [Hv [Hj [Hj' Hvwx]]]]]]].\n    apply In_nth_error in Hv. destruct Hv as [i Hi].\n    assert (Hij : nth_error w i = Some x). { rewrite (matrix_indexing_commutes M i j Hj Hi) in Hj'. assumption. }\n    exists x. exists v. exists w. exists i. exists j.\n    repeat (rewrite <- Nat.leb_le).\n    fold (is_good v x). fold (is_good w x).\n    rewrite <- Bool.andb_true_iff.\n    fold (is_both_good (v, w, x)).\n    rewrite <- is_either_bad_spec. tauto.\n  Qed.\n\nEnd Question.\n", "meta": {"author": "ocfnash", "repo": "imo-coq", "sha": "f6d2e8337fadf00583fd09f86faf9cba62a25677", "save_path": "github-repos/coq/ocfnash-imo-coq", "path": "github-repos/coq/ocfnash-imo-coq/imo-coq-f6d2e8337fadf00583fd09f86faf9cba62a25677/q3_2001/question.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7339327666917408}}
{"text": "\nInductive entier : Type :=\n| O : entier\n| S : entier -> entier.\n\n(* Addition *)\n\nFixpoint plus (n m : entier) : entier :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\n\n(* Question 1 *)\n\nTheorem associativite (n m p : entier) : plus n (plus m p) = plus (plus n m) p.\nProof.\ninduction n.\nreflexivity.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\n\n(* Symétrie *)\n\n(* Question 2 *)\n\nLemma plus0 (n : entier) : plus n O = n.\nProof.\ninduction n.\nreflexivity.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\n(* Question 3 *)\n\nLemma plusS (n p : entier) : plus n (S p) = S (plus n p).\nProof.\ninduction n.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\n(* Question 4 *)\n\nTheorem symetrie (n m : entier) : plus n m = plus m n.\nProof.\ninduction n.\nrewrite plus0.\nsimpl.\nreflexivity.\nrewrite plusS.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\n(* Simplification *)\n\n(* Question 5 *)\n\nLemma egalS (n m : entier) : n = m <-> S n = S m.\nProof.\nsplit.\n- intro nm.\n  rewrite nm.\n  reflexivity.\n- intro snsm.\n  inversion snsm.\n  reflexivity.\nQed.\n\n(* Question 6 *)\n\nTheorem simplification (a n m : entier) : plus a n = plus a m <-> n = m.\nProof.\nsplit.\ninduction a.\n-intro x.\n apply x.\n-simpl.\n intro y.\n rewrite IHa.\n reflexivity.\n apply egalS.\n apply y.\n-intro i.\n rewrite i.\n reflexivity.\nQed.\n\n\n\n(* Multiplication *)\nFixpoint mult (n m : entier) : entier :=\n  match n with\n    | O => O\n    | S n' => plus m (mult n' m)\n  end.\n\n(* Symétrie *)\n\n(* Question 7 *)\n\nLemma multO (n : entier) : mult n O = O.\nProof.\ninduction n.\nreflexivity.\nsimpl.\nassumption.\nQed.\n\n(* Question 8 *)\n\nLemma assoc2 (n m p : entier) : plus n (plus m p) = plus m (plus n p).\nProof.\ninduction n.\nreflexivity.\nsimpl.\nrewrite IHn.\nrewrite plusS.\nreflexivity.\nQed.\n\n(* Question 9 *)\n\nLemma multsn (n m : entier) : mult n (S m) = plus n (mult n m).\nProof.\ninduction n.\nreflexivity.\nsimpl.\nrewrite IHn.\nrewrite assoc2.\nreflexivity.\nQed.\n\n(* Question 10 *)\n\nTheorem symetriemult (n m : entier) : mult n m = mult m n.\nProof.\ninduction n.\nrewrite multO.\nreflexivity.\nrewrite multsn.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\n(* Distributivité *)\n\n(* Question 11 *)\n\nTheorem distributivite (n m p : entier) : mult (plus n m) p = plus (mult n p) (mult m p).\nProof.\ninduction n.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHn.\nrewrite associativite.\nreflexivity.\nQed.\n\n(* Associativité *)\n\n(* Question 12 *)\n\nTheorem associativitemult (n m p : entier) : mult n (mult m p) = mult (mult n m) p.\nProof.\ninduction n.\nreflexivity.\nsimpl.\nrewrite IHn.\nrewrite distributivite.\nreflexivity.\nQed.\n", "meta": {"author": "RadiLina", "repo": "Logique_L3_Lille1", "sha": "20969b187a414f417fae7aed7dd1980be5366536", "save_path": "github-repos/coq/RadiLina-Logique_L3_Lille1", "path": "github-repos/coq/RadiLina-Logique_L3_Lille1/Logique_L3_Lille1-20969b187a414f417fae7aed7dd1980be5366536/logique-tp4/entiers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7339327535081495}}
{"text": "(** * IndProp: Inductively Defined Propositions *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Logic.\nRequire Coq.omega.Omega.\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: _inductive definitions_. *)\n\n(** In past chapters, we have seen two ways of stating that a number\n    [n] is even: We can say\n\n      (1) [evenb n = true], or\n\n      (2) [exists k, n = double k].\n\n    Yet another possibility is to say that [n] is even if we can\n    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: \n\n                              ------------             (ev_0)\n                                 even 0\n\n                                 even n\n                            ----------------          (ev_SS)\n                             even (S (S 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 [ev_SS] says that, if [n]\n    satisfies [even], then [S (S n)] also does.  If a rule has no\n    premises above the line, then its conclusion holds\n    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                              even 0\n                             -------- (ev_SS)\n                              even 2\n                             -------- (ev_SS)\n                              even 4\n*)\n\n(** (Why call this a \"tree\" (rather than a \"stack\", for example)?\n    Because, in general, inference rules can have multiple premises.\n    We will see examples of this shortly. *)\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 even : nat -> Prop :=\n| ev_0 : even 0\n| ev_SS (n : nat) (H : even n) : even (S (S n)).\n\n(** This definition is different in one crucial respect from previous\n    uses of [Inductive]: the thing we are defining is not a [Type],\n    but rather a function from [nat] to [Prop] -- that is, a property\n    of numbers.  We've already seen other inductive definitions that\n    result in functions -- for example, [list], whose type is [Type ->\n    Type].  What is really new here is that, because the [nat]\n    argument of [even] appears to the _right_ of the colon, it is\n    allowed to take different values in the types of different\n    constructors: [0] in the type of [ev_0] and [S (S n)] in the type\n    of [ev_SS].\n\n    In contrast, the definition of [list] names the [X] parameter\n    _globally_, to the _left_ of the colon, forcing the result of\n    [nil] and [cons] to be the same ([list X]).  Had we tried to bring\n    [nat] to the left in defining [even], we would have seen an\n    error: *)\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS : wrong_ev n -> wrong_ev (S (S n)).\n(* ===> Error: Last occurrence of \"[wrong_ev]\" must have \"[n]\"\n        as 1st argument in \"[wrong_ev 0]\". *)\n\n(** In an [Inductive] definition, an argument to the type\n    constructor on the left of the colon is called a \"parameter\",\n    whereas an argument on the right is called an \"index\".\n\n    For example, in [Inductive list (X : Type) := ...], [X] is a\n    parameter; in [Inductive even : nat -> Prop := ...], the\n    unnamed [nat] argument is an index. *)\n\n(** We can think of the definition of [even] as defining a Coq\n    property [even : nat -> Prop], together with primitive theorems\n    [ev_0 : even 0] and [ev_SS : forall n, even n -> even (S (S n))]. *)\n\n(** That definition can also be written as follows...\n\n  Inductive even : nat -> Prop :=\n  | ev_0 : even 0\n  | ev_SS : forall n, even n -> even (S (S n)).\n*)\n\n(** ... making explicit the type of the rule [ev_SS]. *)\n\n(** Such \"constructor theorems\" have the same status as proven\n    theorems.  In particular, we can use Coq's [apply] tactic with the\n    rule names to prove [even] for particular numbers... *)\n\nTheorem ev_4 : even 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** ... or we can use function application syntax: *)\n\nTheorem ev_4' : even 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\n(** We can also prove theorems that have hypotheses involving [even]. *)\n\nTheorem ev_plus4 : forall n, even n -> even (4 + n).\nProof.\n  intros n. simpl. intros Hn.\n  apply ev_SS. apply ev_SS. apply Hn.\nQed.\n\n(** **** Exercise: 1 star, standard (ev_double)  *)\nTheorem ev_double : forall n,\n  even (double n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Using Evidence in Proofs *)\n\n(** Besides _constructing_ evidence that numbers are even, we can also\n    _reason about_ such evidence.\n\n    Introducing [even] 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 even, but also that these two\n    constructors are the _only_ ways to build evidence that numbers\n    are even (in the sense of [even]). *)\n\n(** In other words, if someone gives us evidence [E] for the assertion\n    [even n], then we know that [E] must have one of two shapes:\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 [even n']). *)\n\n(** This suggests that it should be possible to analyze a\n    hypothesis of the form [even 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 [even 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 that [even n] _directly_. As\n    a tool, we can prove our characterization of evidence for\n    [even n], using [destruct]. *)\n\nTheorem ev_inversion :\n  forall (n : nat), even n ->\n    (n = 0) \\/ (exists n', n = S (S n') /\\ even n').\nProof.\n  intros n E.\n  destruct E as [ | n' E'].\n  - (* E = ev_0 : even 0 *)\n    left. reflexivity.\n  - (* E = ev_SS n' E' : even (S (S n')) *)\n    right. exists n'. split. reflexivity. apply E'.\nQed.\n\n(** The following theorem can easily be proved using [destruct] on\n    evidence. *)\n\nTheorem ev_minus2 : forall n,\n  even n -> even (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.\nQed.\n\n(** However, this variation cannot easily be handled with [destruct]. *)\n\nTheorem evSS_ev : forall n,\n  even (S (S n)) -> even 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  destruct E as [| n' E'].\n  - (* E = ev_0. *)\n    (* We must prove that [n] is even from no assumptions! *)\nAbort.\n\n(** What happened, exactly?  Calling [destruct] has the effect of\n    replacing all occurrences of the property argument by the values\n    that correspond to each constructor.  This is enough in the case\n    of [ev_minus2] because that argument [n] is mentioned directly\n    in the final goal. However, it doesn't help in the case of\n    [evSS_ev] since the term that gets replaced ([S (S n)]) is not\n    mentioned anywhere. *)\n\n(** We could patch this proof by replacing the goal [even n],\n    which does not mention the replaced term [S (S n)], by the\n    equivalent goal [even (pred (pred (S (S n))))], which does mention\n    this term, after which [destruct] can make progress. But it is\n    more straightforward to use our inversion lemma. *)\n\nTheorem evSS_ev : forall n, even (S (S n)) -> even n.\nProof. intros n H. apply ev_inversion in H. destruct H.\n - discriminate H.\n - destruct H as [n' [Hnm Hev]]. injection Hnm.\n   intro Heq. rewrite Heq. apply Hev.\nQed.\n\n(** Coq provides a tactic called [inversion], which does the work of\n    our inversion lemma and more besides. *)\n\n(** The [inversion] tactic can detect (1) that the first case\n    ([n = 0]) does not apply and (2) that the [n'] that appears in the\n    [ev_SS] case must be the same as [n].  It has an \"[as]\" variant\n    similar to [destruct], allowing us to assign names rather than\n    have Coq choose them. *)\n\nTheorem evSS_ev' : forall n,\n  even (S (S n)) -> even n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  (* We are in the [E = ev_SS n' E'] case now. *)\n  apply E'.\nQed.\n\n(** The [inversion] tactic can apply the principle of explosion to\n    \"obviously contradictory\" hypotheses involving inductive\n    properties, something that takes a bit more work using our\n    inversion lemma. For example: *)\nTheorem one_not_even : ~ even 1.\nProof.\n  intros H. apply ev_inversion in H.\n  destruct H as [ | [m [Hm _]]].\n  - discriminate H.\n  - discriminate Hm.\nQed.\n\nTheorem one_not_even' : ~ even 1.\n  intros H. inversion H. Qed.\n\n(** **** Exercise: 1 star, standard (inversion_practice)  \n\n    Prove the following result using [inversion].  For extra practice,\n    prove it using the inversion lemma. *)\n\nTheorem SSSSev__even : forall n,\n  even (S (S (S (S n)))) -> even n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (even5_nonsense)  \n\n    Prove the following result using [inversion]. *)\n\nTheorem even5_nonsense :\n  even 5 -> 2 + 2 = 9.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The [inversion] tactic does quite a bit of work. When\n    applied to equalities, as a special case, it does the work of both\n    [discriminate] and [injection]. In addition, it carries out the\n    [intros] and [rewrite]s that are typically necessary in the case\n    of [injection]. It can also be applied, more generally, to analyze\n    evidence for inductively defined propositions.  As examples, we'll\n    use it to reprove some theorems from [Tactics.v]. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\n(** Here's how [inversion] works in general.  Suppose the name\n    [H] refers to an assumption [P] in the current context, where [P]\n    has been defined by an [Inductive] declaration.  Then, for each of\n    the constructors of [P], [inversion H] generates a subgoal in which\n    [H] has been replaced by the exact, specific conditions under\n    which this constructor could have been used to prove [P].  Some of\n    these subgoals will be self-contradictory; [inversion] throws\n    these away.  The ones that are left represent the cases that must\n    be proved to establish the original goal.  For those, [inversion]\n    adds all equations into the proof context that must hold of the\n    arguments given to [P] (e.g., [S (S n') = n] in the proof of\n    [evSS_ev]). *)\n\n(** The [ev_double] exercise above shows that our new notion of\n    evenness is implied by the two earlier ones (since, by\n    [even_bool_prop] in chapter [Logic], we already know that\n    those are equivalent to each other). To show that all three\n    coincide, we just need the following lemma. *)\n\nLemma ev_even_firsttry : forall n,\n  even n -> exists k, n = double k.\nProof.\n(* WORKED IN CLASS *)\n\n(** We could try to proceed by case analysis or induction on [n].  But\n    since [even] is mentioned in a premise, this strategy would\n    probably lead to a dead end, as in the previous section.  Thus, it\n    seems better to first try [inversion] on the evidence for [even].\n    Indeed, the first case can be solved trivially. *)\n\n  intros n E. inversion E as [| n' E'].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E' *) simpl.\n\n(** Unfortunately, the second case is harder.  We need to show [exists\n    k, S (S n') = double k], but the only available assumption is\n    [E'], which states that [even n'] holds.  Since this isn't\n    directly useful, it seems that we are stuck and that performing\n    case analysis on [E] was a waste of time.\n\n    If we look more closely at our second goal, however, we can see\n    that something interesting happened: By performing case analysis\n    on [E], we were able to reduce the original result to a similar\n    one that involves a _different_ piece of evidence for [even]:\n    namely [E'].  More formally, we can finish our proof by showing\n    that\n\n        exists k', n' = double k',\n\n    which is the same as the original statement, but with [n'] instead\n    of [n].  Indeed, it is not difficult to convince Coq that this\n    intermediate result suffices. *)\n\n    assert (I : (exists k', n' = double k') ->\n                (exists k, S (S n') = double k)).\n    { intros [k' Hk']. rewrite Hk'. exists (S k'). reflexivity. }\n    apply I. (* reduce the original goal to the new one *)\n\nAbort.\n\n(* ================================================================= *)\n(** ** Induction on Evidence *)\n\n(** If this looks familiar, it is no coincidence: We've\n    encountered similar problems in the [Induction] chapter, when\n    trying to use case analysis to prove results that required\n    induction.  And once again the solution is... induction!\n\n    The behavior of [induction] on evidence is the same as its\n    behavior on data: It causes Coq to generate one subgoal for each\n    constructor that could have used to build that evidence, while\n    providing an induction hypotheses for each recursive occurrence of\n    the property in question.\n\n    To prove a property of [n] holds for all numbers for which [even\n    n] holds, we can use induction on [even n]. This requires us to\n    prove two things, corresponding to the two ways in which [even n]\n    could have been constructed. If it was constructed by [ev_0], then\n    [n=0], and the property must hold of [0]. If it was constructed by\n    [ev_SS], then the evidence of [even n] is of the form [ev_SS n'\n    E'], where [n = S (S n')] and [E'] is evidence for [even n']. In\n    this case, the inductive hypothesis says that the property we are\n    trying to prove holds for [n']. *)\n\n(** Let's try our current lemma again: *)\n\nLemma ev_even : forall n,\n  even n -> exists k, n = double k.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       with IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). reflexivity.\nQed.\n\n(** Here, we can see that Coq produced an [IH] that corresponds\n    to [E'], the single recursive occurrence of [even] in its own\n    definition.  Since [E'] mentions [n'], the induction hypothesis\n    talks about [n'], as opposed to [n] or some other number. *)\n\n(** The equivalence between the second and third definitions of\n    evenness now follows. *)\n\nTheorem ev_even_iff : forall n,\n  even n <-> exists k, n = double k.\nProof.\n  intros n. split.\n  - (* -> *) apply ev_even.\n  - (* <- *) intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\n(** As we will see in later chapters, induction on evidence is a\n    recurring technique across many areas, and in particular when\n    formalizing the semantics of programming languages, where many\n    properties of interest are defined inductively. *)\n\n(** The following exercises provide simple examples of this\n    technique, to help you familiarize yourself with it. *)\n\n(** **** Exercise: 2 stars, standard (ev_sum)  *)\nTheorem ev_sum : forall n m, even n -> even m -> even (n + m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, optional (even'_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 [even]: *)\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\n(** Prove that this definition is logically equivalent to the old\n    one.  (You may want to look at the previous theorem when you get\n    to the induction step.) *)\n\nTheorem even'_ev : forall n, even' n <-> even n.\nProof.\n (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, recommended (ev_ev__ev)  \n\n    Finding the appropriate thing to do induction on is a\n    bit tricky here: *)\n\nTheorem ev_ev__ev : forall n m,\n  even (n+m) -> even n -> even m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\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  even (n+m) -> even (n+p) -> even (m+p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Inductive Relations *)\n\n(** A proposition parameterized by a number (such as [even])\n    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 Playground.\n\n(** One useful example is the \"less than or equal to\" relation on\n    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 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\n(** Proofs of facts about [<=] using the constructors [le_n] and\n    [le_S] follow the same patterns as proofs about properties, like\n    [even] above. 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) ->\n    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 Playground.\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_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: 2 stars, standard, optional (total_relation)  \n\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\n(** **** Exercise: 2 stars, standard, optional (empty_relation)  \n\n    Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\n\n(* FILL IN HERE \n\n    [] *)\n\n(** From the definition of [le], we can sketch the behaviors of\n    [destruct], [inversion], and [induction] on a hypothesis [H]\n    providing evidence of the form [le e1 e2].  Doing [destruct H]\n    will generate two cases. In the first case, [e1 = e2], and it\n    will replace instances of [e2] with [e1] in the goal and context.\n    In the second case, [e2 = S n'] for some [n'] for which [le e1 n']\n    holds, and it will replace instances of [e2] with [S n']. \n    Doing [inversion H] will remove impossible cases and add generated\n    equalities to the context for further use. Doing [induction H]\n    will, in the second case, add the induction hypothesis that the\n    goal holds when [e2] is replaced with [n']. *)\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  (* 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\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\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 leb_complete : forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\n\n(** Hint: This 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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\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(* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_R_provability : option (nat*string) := None.\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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nEnd R.\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(* FILL IN HERE *)\n.\n\nTheorem subseq_refl : forall (l : list nat), subseq l l.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem subseq_app : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l1 (l2 ++ l3).\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem subseq_trans : forall (l1 l2 l3 : list nat),\n  subseq l1 l2 ->\n  subseq l2 l3 ->\n  subseq l1 l3.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\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 : forall n l, R n l -> R (S n) (n :: l)\n      | c3 : forall n l, 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(** * Case Study: Regular Expressions *)\n\n(** The [even] property provides a simple example for\n    illustrating inductive definitions and the basic techniques for\n    reasoning about them, but it is not terribly exciting -- after\n    all, it is equivalent to the two non-inductive definitions of\n    evenness that we had already seen, and does not seem to offer any\n    concrete benefit over them.\n\n    To give a better sense of the power of inductive definitions, we\n    now show how to use them to model a classic concept in computer\n    science: _regular expressions_. *)\n\n(** Regular expressions are a simple language for describing sets of\n    strings.  Their syntax is defined as follows: *)\n\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\n(** Note that this definition is _polymorphic_: Regular\n    expressions in [reg_exp T] describe strings with characters drawn\n    from [T] -- that is, lists of elements of [T].\n\n    (We depart slightly from standard practice in that we do not\n    require the type [T] to be finite.  This results in a somewhat\n    different theory of regular expressions, but the difference is not\n    significant for our purposes.) *)\n\n(** We connect regular expressions and strings via the following\n    rules, which define when a regular expression _matches_ some\n    string:\n\n      - The expression [EmptySet] does not match any string.\n\n      - The expression [EmptyStr] matches the empty string [[]].\n\n      - The expression [Char x] matches the one-character string [[x]].\n\n      - If [re1] matches [s1], and [re2] matches [s2],\n        then [App re1 re2] matches [s1 ++ s2].\n\n      - If at least one of [re1] and [re2] matches [s],\n        then [Union re1 re2] matches [s].\n\n      - Finally, if we can write some string [s] as the concatenation\n        of a sequence of strings [s = s_1 ++ ... ++ s_k], and the\n        expression [re] matches each one of the strings [s_i],\n        then [Star re] matches [s].\n\n        As a special case, the sequence of strings may be empty, so\n        [Star re] always matches the empty string [[]] no matter what\n        [re] is. *)\n\n(** We can easily translate this informal definition into an\n    [Inductive] one as follows: *)\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\n             (H1 : exp_match s1 re1)\n             (H2 : exp_match s2 re2) :\n             exp_match (s1 ++ s2) (App re1 re2)\n  | MUnionL s1 re1 re2\n                (H1 : exp_match s1 re1) :\n                exp_match s1 (Union re1 re2)\n  | MUnionR re1 s2 re2\n                (H2 : exp_match s2 re2) :\n                exp_match s2 (Union re1 re2)\n  | MStar0 re : exp_match [] (Star re)\n  | MStarApp s1 s2 re\n                 (H1 : exp_match s1 re)\n                 (H2 : exp_match s2 (Star re)) :\n                 exp_match (s1 ++ s2) (Star re).\n\n(** Again, for readability, we can also display this definition using\n    inference-rule notation.  At the same time, let's introduce a more\n    readable infix notation. *)\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\n(**\n\n                          ----------------                    (MEmpty)\n                           [] =~ EmptyStr\n\n                          ---------------                      (MChar)\n                           [x] =~ Char x\n\n                       s1 =~ re1    s2 =~ re2\n                      -------------------------                 (MApp)\n                       s1 ++ s2 =~ App re1 re2\n\n                              s1 =~ re1\n                        ---------------------                (MUnionL)\n                         s1 =~ Union re1 re2\n\n                              s2 =~ re2\n                        ---------------------                (MUnionR)\n                         s2 =~ Union re1 re2\n\n                          ---------------                     (MStar0)\n                           [] =~ Star re\n\n                      s1 =~ re    s2 =~ Star re\n                     ---------------------------            (MStarApp)\n                        s1 ++ s2 =~ Star re\n*)\n\n(** Notice that these rules are not _quite_ the same as the\n    informal ones that we gave at the beginning of the section.\n    First, we don't need to include a rule explicitly stating that no\n    string matches [EmptySet]; we just don't happen to include any\n    rule that would have the effect of some string matching\n    [EmptySet].  (Indeed, the syntax of inductive definitions doesn't\n    even _allow_ us to give such a \"negative rule.\")\n\n    Second, the informal rules for [Union] and [Star] correspond\n    to two constructors each: [MUnionL] / [MUnionR], and [MStar0] /\n    [MStarApp].  The result is logically equivalent to the original\n    rules but more convenient to use in Coq, since the recursive\n    occurrences of [exp_match] are given as direct arguments to the\n    constructors, making it easier to perform induction on evidence.\n    (The [exp_match_ex1] and [exp_match_ex2] exercises below ask you\n    to prove that the constructors given in the inductive declaration\n    and the ones that would arise from a more literal transcription of\n    the informal rules are indeed equivalent.)\n\n    Let's illustrate these rules with a few examples. *)\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2]).\n  - apply MChar.\n  - apply MChar.\nQed.\n\n(** (Notice how the last example applies [MApp] to the strings\n    [[1]] and [[2]] directly.  Since the goal mentions [[1; 2]]\n    instead of [[1] ++ [2]], Coq wouldn't be able to figure out how to\n    split the string on its own.)\n\n    Using [inversion], we can also show that certain strings do _not_\n    match a regular expression: *)\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. inversion H.\nQed.\n\n(** We can define helper functions for writing down regular\n    expressions. The [reg_exp_of_list] function constructs a regular\n    expression that matches exactly the list that it receives as an\n    argument: *)\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.\nQed.\n\n(** We can also prove general facts about [exp_match].  For instance,\n    the following lemma shows that every string [s] that matches [re]\n    also matches [Star re]. *)\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(** (Note the use of [app_nil_r] to change the goal of the theorem to\n    exactly the same shape expected by [MStarApp].) *)\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *) Admitted.\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),\n  (forall s, In s ss -> s =~ re) ->\n  fold app ss [] =~ Star re.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\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: *)\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Since the definition of [exp_match] has a recursive\n    structure, we might expect that proofs involving regular\n    expressions will often require induction on evidence. *)\n\n(** For example, suppose that we wanted to prove the following\n    intuitive result: If a regular expression [re] matches some string\n    [s], then all elements of [s] must occur as character literals\n    somewhere in [re].\n\n    To state this theorem, we first define a function [re_chars] that\n    lists all characters that occur in a regular expression: *)\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\n(** We can then phrase our theorem as follows: *)\n\nTheorem in_re_match : forall T (s : list T) (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 [| 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  (* WORKED IN CLASS *)\n  - (* MEmpty *)\n    apply Hin.\n  - (* MChar *)\n    apply Hin.\n  - simpl. 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\n(** Something interesting happens in the [MStarApp] case.  We obtain\n    _two_ induction hypotheses: One that applies when [x] occurs in\n    [s1] (which matches [re]), and a second one that applies when [x]\n    occurs in [s2] (which matches [Star re]).  This is a good\n    illustration of why we need induction on evidence for [exp_match],\n    rather than induction on the regular expression [re]: The latter\n    would only provide an induction hypothesis for strings that match\n    [re], which would not allow us to reason about the case [In x\n    s2]. *)\n\n  - (* MStarApp *)\n    simpl. 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(** **** 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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nLemma re_not_empty_correct : forall T (re : @reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** The [remember] Tactic *)\n\n(** One potentially confusing feature of the [induction] tactic is\n    that it will let you try to perform an induction over a term that\n    isn't sufficiently general.  The effect of this is to lose\n    information (much as [destruct] without an [eqn:] clause can do),\n    and leave you unable to complete the proof.  Here's an example: *)\n\nLemma star_app: 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\n(** Just doing an [inversion] on [H1] won't get us very far in\n    the recursive cases. (Try it!). So we need induction (on\n    evidence!). Here is a naive first attempt: *)\n\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\n(** But now, although we get seven cases (as we would expect from the\n    definition of [exp_match]), we have lost a very important bit of\n    information from [H1]: the fact that [s1] matched something of the\n    form [Star re].  This means that we have to give proofs for _all_\n    seven constructors of this definition, even though all but two of\n    them ([MStar0] and [MStarApp]) are contradictory.  We can still\n    get the proof to go through for a few constructors, such as\n    [MEmpty]... *)\n\n  - (* MEmpty *)\n    simpl. intros H. apply H.\n\n(** ... but most cases get stuck.  For [MChar], for instance, we\n    must show that\n\n    s2 =~ Char x' -> x' :: s2 =~ Char x',\n\n    which is clearly impossible. *)\n\n  - (* MChar. Stuck... *)\nAbort.\n\n(** The problem is that [induction] over a Prop hypothesis only works\n    properly with hypotheses that are completely general, i.e., ones\n    in which all the arguments are variables, as opposed to more\n    complex expressions, such as [Star re].\n\n    (In this respect, [induction] on evidence behaves more like\n    [destruct]-without-[eqn:] than like [inversion].)\n\n    An awkward way to solve this problem is \"manually generalizing\" \n    over the problematic expressions by adding explicit equality \n    hypotheses to the lemma: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp),\n  re' = Star re ->\n  s1 =~ re' ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\n\n(** We can now proceed by performing induction over evidence directly,\n    because the argument to the first hypothesis is sufficiently\n    general, which means that we can discharge most cases by inverting\n    the [re' = Star re] equality in the context.\n\n    This idiom is so common that Coq provides a tactic to\n    automatically generate such equations for us, avoiding thus the\n    need for changing the statements of our theorems. *)\n\nAbort.\n\n(** The tactic [remember e as x] causes Coq to (1) replace all\n    occurrences of the expression [e] by the variable [x], and (2) add\n    an equation [x = e] to the context.  Here's how we can use it to\n    show the above result: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re : reg_exp),\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\n(** We now have [Heqre' : re' = Star re]. *)\n\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\n(** The [Heqre'] is contradictory in most cases, allowing us to\n    conclude immediately. *)\n\n  - (* MEmpty *)  discriminate.\n  - (* MChar *)   discriminate.\n  - (* MApp *)    discriminate.\n  - (* MUnionL *) discriminate.\n  - (* MUnionR *) discriminate.\n\n(** The interesting cases are those that correspond to [Star].  Note\n    that the induction hypothesis [IH2] on the [MStarApp] case\n    mentions an additional premise [Star re'' = Star re'], which\n    results from the equality generated by [remember]. *)\n\n  - (* MStar0 *)\n    injection Heqre'. intros Heqre'' s H. apply H.\n\n  - (* MStarApp *)\n    injection Heqre'. intros H0.\n    intros s2 H1. rewrite <- app_assoc.\n    apply MStarApp.\n    + apply Hmatch1.\n    + apply IH2.\n      * rewrite H0. reflexivity.\n      * apply H1.\nQed.\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),\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (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].\n\n    To begin, we need to define \"sufficiently long.\"  Since we are\n    working in a constructive logic, we actually need to be able to\n    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 => 0\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 _ => 1\n  end.\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\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\n(** Now, the 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 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(** To streamline the proof (which you are to fill in), the [omega]\n    tactic, which is enabled by the following [Require], is helpful in\n    several places for automatically completing tedious low-level\n    arguments involving equalities or inequalities over natural\n    numbers.  We'll return to [omega] in a later chapter, but feel\n    free to experiment with it now if you like.  The first case of the\n    induction gives an example of how it is used. *)\n\nImport Coq.omega.Omega.\n\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. omega.\n  (* FILL IN HERE *) Admitted.\n\nEnd Pumping.\n(** [] *)\n\n(* ################################################################# *)\n(** * Case Study: Improving Reflection *)\n\n(** We've seen in the [Logic] chapter that we often need to\n    relate boolean computations to statements in [Prop].  But\n    performing this conversion as we did it there can result in\n    tedious proof scripts.  Consider the proof of the following\n    theorem: *)\n\nTheorem filter_not_empty_In : forall n l,\n  filter (fun x => n =? x) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (n =? m) eqn:H.\n    + (* n =? m = true *)\n      intros _. rewrite eqb_eq in H. rewrite H.\n      left. reflexivity.\n    + (* n =? m = false *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** In the first branch after [destruct], we explicitly apply\n    the [eqb_eq] lemma to the equation generated by\n    destructing [n =? m], to convert the assumption [n =? m\n    = true] into the assumption [n = m]; then we had to [rewrite]\n    using this assumption to complete the case. *)\n\n(** We can streamline this by defining an inductive proposition that\n    yields a better case-analysis principle for [n =? m].\n    Instead of generating an equation such as [(n =? m) = true],\n    which is generally not directly useful, this principle gives us\n    right away the assumption we really need: [n = m]. *)\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT (H :   P) : reflect P true\n| ReflectF (H : ~ P) : reflect P false.\n\n(** The [reflect] property takes two arguments: a proposition\n    [P] and a boolean [b].  Intuitively, it states that the property\n    [P] is _reflected_ in (i.e., equivalent to) the boolean [b]: that\n    is, [P] holds if and only if [b = true].  To see this, notice\n    that, by definition, the only way we can produce evidence for\n    [reflect P true] is by showing [P] and then using the [ReflectT]\n    constructor.  If we invert this statement, this means that it\n    should be possible to extract evidence for [P] from a proof of\n    [reflect P true].  Similarly, the only way to show [reflect P\n    false] is by combining evidence for [~ P] with the [ReflectF]\n    constructor.\n\n    It is easy to formalize this intuition and show that the\n    statements [P <-> b = true] and [reflect P b] are indeed\n    equivalent.  First, the left-to-right implication: *)\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  (* WORKED IN CLASS *)\n  intros P b H. destruct b.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. intros H'. discriminate.\nQed.\n\n(** Now you prove the right-to-left implication: *)\n\n(** **** Exercise: 2 stars, standard, recommended (reflect_iff)  *)\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The advantage of [reflect] over the normal \"if and only if\"\n    connective is that, by destructing a hypothesis or lemma of the\n    form [reflect P b], we can perform case analysis on [b] while at\n    the same time generating appropriate hypothesis in the two\n    branches ([P] in the first subgoal and [~ P] in the second). *)\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(** A smoother proof of [filter_not_empty_In] now goes as follows.\n    Notice how the calls to [destruct] and [apply] are combined into a\n    single call to [destruct]. *)\n\n(** (To see this clearly, look at the two proofs of\n    [filter_not_empty_In] with Coq and observe the differences in\n    proof state at the beginning of the first case of the\n    [destruct].) *)\n\nTheorem filter_not_empty_In' : forall n l,\n  filter (fun x => n =? x) l <> [] ->\n  In n l.\nProof.\n  intros n l. induction l as [|m l' IHl'].\n  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (eqbP n m) as [H | H].\n    + (* n = m *)\n      intros _. rewrite H. left. reflexivity.\n    + (* n <> m *)\n      intros H'. right. apply IHl'. apply H'.\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** This small example shows how reflection gives us a small gain in\n    convenience; in larger developments, using [reflect] consistently\n    can often lead to noticeably shorter and clearer proof scripts.\n    We'll see many more examples in later chapters and in _Programming\n    Language Foundations_.\n\n    The use of the [reflect] property has been popularized by\n    _SSReflect_, a Coq library that has been used to formalize\n    important results in mathematics, including as the 4-color theorem\n    and the Feit-Thompson theorem.  The name SSReflect stands for\n    _small-scale reflection_, i.e., the pervasive use of reflection to\n    simplify small proof steps with boolean computations. *)\n\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 (* FILL IN HERE *)\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(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply eqb_neq; auto.\n  Qed.\n*)\n\nExample test_nostutter_2:  nostutter (@nil nat).\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply eqb_neq; auto.\n  Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply eqb_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 Hneq0; auto. Qed.\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_nostutter : option (nat*string) := None.\n(** [] *)\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(* Do not modify the following line: *)\nDefinition manual_grade_for_filter_challenge : option (nat*string) := None.\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    [] *)\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(* Do not modify the following line: *)\nDefinition manual_grade_for_pal_pal_app_rev_pal_rev : option (nat*string) := None.\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(* Do not modify the following line: *)\nDefinition manual_grade_for_NoDup_disjoint_etc : option (nat*string) := None.\n(** [] *)\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  (* FILL IN HERE *) Admitted.\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  (* FILL IN HERE *)\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  (* FILL IN HERE *) Admitted.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_check_repeats : option (nat*string) := None.\n(** [] *)\n\n(* ================================================================= *)\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 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: *)\nRequire Export Coq.Strings.Ascii.\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(* Wed Jan 9 12:02:45 EST 2019 *)\n", "meta": {"author": "carliros", "repo": "software-foundations-book", "sha": "fea3e774d18d2434c7296cedbf52756c5ab8dbdd", "save_path": "github-repos/coq/carliros-software-foundations-book", "path": "github-repos/coq/carliros-software-foundations-book/software-foundations-book-fea3e774d18d2434c7296cedbf52756c5ab8dbdd/logical-foundations-2019/dotv/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.7338579896918647}}
{"text": "(** Logique propositionnelle *)\n\n(* indiquer toutes les etapes de la preuve du theoreme ci-dessous *)\n\n\n\nLemma L1: forall P Q, ~(P /\\ Q)-> P -> ~Q.\n\n\n\n(** Logique du premier ordre *)\n(* indiquer les etapes principlaes de la preuve du theoreme ci-dessous \n   (utilisation d'apply, de destruct ou d'exists) *)\n\n\nLemma L2 : forall (A:Type) (P : A->Prop) (Q : Prop),\n  (forall x:A, P x -> Q) <-> ((exists y:A, P y) -> Q).\n\n\n(** Arithmetique *)\n\n\n(* On definit les fonctions suivantes *)\n\n\nFixpoint Le (n p:nat) : bool :=\n match n, p with 0, _ => true\n               | S q, S r => Le q r\n               | _, _ => false\n end.\n\nFixpoint Lt (n p:nat) : bool :=\n match n, p with 0, S _ => true\n               | S q, S r => Lt q r\n               | _, _ => false\n end.\n\n(*   Comment terminer les preuves suivantes *)\n\nLemma Lt_irr : forall n, Lt n n = false.\nProof.\n induction n; simpl.\nAdmitted.\n\n\nLemma Le_eq_or_Lt : forall n p, Le n p = true -> n = p \\/ Lt n p = true.\nProof.\n induction n; simpl; auto.\n  destruct p;simpl;auto.\n \n destruct p;simpl;auto.\n(*\n\n1 subgoal\n  \n  n : nat\n  IHn : forall p : nat, Le n p = true -> n = p \\/ Lt n p = true\n  p : nat\n  ============================\n   Le n p = true -> S n = S p \\/ Lt n p = true\n*)\nAdmitted.\n\n\n(* On definit le predicat suivant *)\n\nDefinition multiple_de_3 (n : nat) := exists p:nat, n = 3 * p.\n\n\n\n(* On admet le resultat suivant (demonstration non demandée) : *)\nLemma mult3_inv : forall n, multiple_de_3 n ->\n                            n = 0 \\/ \n                            exists p, n = 3 + p /\\ multiple_de_3 p.\nAdmitted.\n\n(* Prouver le lemme ci-dessous (on utilisera mult3_inv) *)\n\n\nLemma One_not_mult3 : ~multiple_de_3 1.\nAdmitted.\n\n(* Note : on rappelle que \"discriminate H\" permet de resoudre tout\nbut contenant une hypothese H : n = p, ou n et p seont deux entiers\ndifferents.\n\nPar exemple :\n\nGoal  forall n, 2 <> 4+ n.\nintros n H;discriminate H.\nQed.\n\n*)\n", "meta": {"author": "magret2canard", "repo": "master1", "sha": "a993e9cbd38ee045af2900f9486ee9438d5e3274", "save_path": "github-repos/coq/magret2canard-master1", "path": "github-repos/coq/magret2canard-master1/master1-a993e9cbd38ee045af2900f9486ee9438d5e3274/LOGIQUE/Exam/preparation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.7338579763938932}}
{"text": "\n(*\n\n2. Basic Proofs\n\nTry to be brief.\n\n\nCurry-Howard\nTuple = And\nEither = Or\nVoid = False\nIntuitionistic. No double negation\n\n\nEven more vitally than for programming, you need interactive help from the ocmpiler for theorem proving.\n\n\nProof is actually a no-op.\n\nYou can use tactics for defining regular functions\nhttps://stackoverflow.com/questions/41837820/agda-like-programming-in-coq-proof-general\nJust need to use a period after the type declaration rather than :=\nTheorem ~ Fixpoint\n\nDefinition three : nat.\nexact 3. Defined.\n\nProgram automates parts of refinement typing.\n\n\n*)\n\n(*\nIt's important to learn the techniques and tactics for proofs,\n But the ultimate goal is to make proofs as simple and automatic as possible. There are some automatic tactics.\n\n*)\n\n\n(* The Theorems aren't really a seperate part of the language from the programs. It is very interesting. \nWhat makes the vernacular keywords Theorem and Proof special is how they put coq into proof mode where you can use tactics to write programs\n\nThe word \"exact\" is a tactic that takes a Gallina expression that fulfils the type signature\n*)\n\nTheorem double : nat -> nat.\nProof. exact (fun x => 2 * x). Qed.\n\nCompute double 3. (* This didn't work *)\n\n(* It is certainly a stretch to call double a theorem, but we'll see things later that really are more thoerem like. In this case, what we've proven is that it is possible to construct a function with the type nat -> nat. This is not at all unique *)\n\nTheorem weird_double : nat -> nat.\nProof. exact (fun x => 340). Qed.\n\n(* You can also write terms with holes. In languages like Agda and Idris, this is the main way programming and proofs are done, but it seems to be rather unidiomatic coq.\n\nThe refine tactic lets you have holes in your expression. Each hole becomes a goal in the proof state that you're going to need to supply later.\n*)\n\nTheorem double' : nat -> nat.\nProof. refine (fun x => _). exact (2 * x). Qed.\n\n(* There is a different tactic that introduces variables call intros. This is more idiomatic *)\n\nTheorem double'' : nat -> nat.\nProof. intros x. exact (2 * x). Qed.\n\n\nTheorem idtheorem: forall (A: Type), A -> A.\nProof. intros. exact X. Qed.\n\nTheorem idtheorem': forall (A: Type), A -> A.\nProof. exact (fun (A:Type) (x:A) => x). Qed.\n\n\n  (* What is refelxivity?  *)\n\n  (* The exact manner a function is defined vastly changes how similar seeming facts are proved\n  For example, depending of whether zero is being added from the left or right is different.\n  *)\n\n(* \nA very important thing imported by default is the Equality type. The type has the notation a = b.\nEquality is a proposition with a single constructor eq_refl. I recall finding this very puzzling, and I'm sure I still would if I was probed about it or contemplated hard. Equality is a fundamental, but subtle thing. I find that a rough picture of how typechecking works helps me to understand what is going on. \n\nx = y is a Prop, which is similar to a Type. Prop are intended to be used for non computational purposes, proofs only.\nThere may be a way to construct a value of this type or not (depending whether you can actually prove the equality or not).\n\n\nSome basic combinators for equality\nVariables A B : Type.\nVariable f : A -> B.\nVariables x y z : A.\n\nTheorem eq_sym : x = y -> y = x.\nTheorem eq_trans : x = y -> y = z -> x = z.\nTheorem f_equal : x = y -> f x = f y.\nTheorem not_eq_sym : x <> y -> y <> x.\n\nso to rewrite the positions in an equality, you need to hand it a lambda that shows exactly which positions you want to change.\n\n*)\n\nDefinition eq_3 : (3 = 3) := eq_refl.\n\nDefinition eq_22 : (2 + 2 = 4) := eq_refl.\n\nTheorem eq_3: 3 = 3.\nProof. exact eq_refl. Qed. \n\nTheorem eq_3': 3 = 3.\nProof. reflexivity. Qed. \n\nDefinition eq_3'' : 3 = 3 := eq_refl.\n\nTheorem andb1 : andb true true = true.\nProof. exact eq_refl. Qed.\n\nTheorem andb1' : andb true true = true.\nProof. reflexivity. Qed.\n\n\n(*  Reflexivity is a tactic that deals with equality. It also does some simplification and works for equality other than eq *)\n\nTheorem nat_eq: forall (n:nat), n = n.\nProof. intros n. reflexivity. Qed.\n\nTheorem zero_id: forall n, 0 + n = n.\nProof. intros n. reflexivity. Qed.\n\n(* Many proofs are by induction. *)\n\nTheorem zero_id': forall n, n + 0 = n.\nProof. intros n. induction n. reflexivity. simpl. rewrite IHn. reflexivity. Qed.\n\nTheorem zero_id'': forall n, n + 0 = n.\nProof. auto. Qed.\n\n(* We can actually see the proof derived using Print *)\nPrint zero_id''.\n\n(* the theorem eq_sym and plus_n_0 were used. These we in the hint data base *)\n\n(*\n\nauto can also take a search depth parameter\n\n*)\n\nSearch nat.\nTheorem double_plus_ungood: forall n, 2 * n = n + n.\nProof. intros. simpl. rewrite zero_id'. reflexivity. Qed. \n\nTheorem double_plus_ungood': forall n, 2 * n = n + n.\nProof. auto. Qed.\n\nPrint double_plus_ungood'.\n\nTheorem plus_comm: forall n m,  m + n = n + m.\nProof. auto. intros n m. induction m. auto. simpl. rewrite IHm. auto. Qed. \n\nSearchRewrite (_ + S _).\n\n\nSearch True.\n\n\n(* True is a Prop with a single contstructor I. It is similar to unit. *)\n\nGoal True. \nProof. apply I. Qed.\n\nGoal forall {A B : Prop}, A /\\ B -> A.\nProof. exact proj1. Qed.\n\n\nGoal forall {A B : Prop}, A -> B -> A /\\ B.\nProof. intros A B HA HB. split. apply HA. apply HB.  Qed.\n\n  (*  tt : unit *) \nSearch unit.\n\n\n(* existentails\n\neauto - is auto plus a little more. \n*)\n\nTheorem exists_3 : exists (n : nat), n = 3.\nProof. exists 3. reflexivity. Qed.\n\nTheorem exists_3' : exists (n : nat), n = 3. \nProof. eauto. Qed. \n\n\n\n\n\n  (*  Tacticals are higher order tactics. They allow chaining of tactics. \n  \n  ; sequences tactics. Each subsequent tactic is applied to the goal tree in parallel\n\n  try - tries a tactic, which may fail\n\n  repeat - does the tactic until it stops applying\n\n\n\n  + is backtracking it will try the left branch and then go downward until a tactic fails to apply. Then it will back track to this point\n\n  || tries the left tactic and if it doesn't work in all the goals, it will just use the right tactic\n  *)\n\n\n\n  (*\n     LTAC is the Coq tactic scripting language\n\n     idtac\n     fail\n     fresh\n\n\n\n\n  *)\n(*\n\nRaw Dog without tactics \n\n\nTactics.\nTheorem\nLemma\n\n\nEquality.\n\n\nLTAC?\n\n\n\n\nGoal\n\n*)\n(*\nhttps://stackoverflow.com/questions/32682544/is-there-a-minimal-complete-set-of-tactics-in-coq\n\nhttps://pjreddie.com/coq-tactics/\nhttp://adam.chlipala.net/itp/tactic-reference.html\nhttps://www.cs.cornell.edu/courses/cs3110/2018sp/a5/coq-tactics-cheatsheet.html\n\n\n\n\nAutomation\n\nauto - automatic proof search\nring - solves polynomials / numbers stuff.\nomega - automatic solves simple problems for integers\n\n\nThe tactic auto is able to solve a goal that can be proved using a sequence of intros, apply, assumption, and reflexivity\n\n\n\nexact - give exactly the term that fulfills the proof obligations\nrefine - give proof with holes\n\nintro{s} intro introduces variables. \n\nreflexivity - When the goal is an obvious equality\n\nsimpl - does computational simplification\n\n\nexists, , symmetry, \napply, rewrite, revert, destruct and induction. inversion\n\n\n\nTacticals\n\nrepeat\ntry \n;\n\n\n*)\n\n\n(*\nInduction principles made by data type definitions.\n\n*)\n\n\n(* Case matching on impossible things *)\n(* Proving anything from False *)\n(*   *)\n\n(* https://stackoverflow.com/questions/40695030/how-to-prove-the-arithmetic-equality-3-s-i-j-1-s-3-i-1-s-3\n*)\n\n(* Goal vecrnacular. don't have to give it a name*)\nRequire Import Arith.\nTheorem doub (a : nat) : 2 * a = a + a. \n  ring. Qed.\n\nRequire Import Omega.\nTheorem doub2 (a : nat) : 2 * a = a + a. \n  omega. Qed.\n\n\nTheorem simp : exists e, e + 1 = 2.\nProof.\n exists 1. simpl. reflexivity. Qed.\n\n\nAbout prod.\n\nTheorem myfst (a b : Type): (prod a b) ->  a.\nProof.\n  exact fst.\nQed.\n\n\nSearch and.\nSearch exist.\nTheorem twoexists : exists x : nat, 2 = x.\nProof.\n  exists 2. reflexivity.\nQed.\n\nTheorem twoexists' : exists x : nat, 2 = x.\nProof.\n  eauto. \nQed.\n\nSearch nat.\n\nTheorem twoeven : Nat.even 2 = true.\nProof.\n  reflexivity.\nQed.\n\nDefinition square (x : nat) : nat := x * x.\nCompute square 4.\n\nSearch nat.\n\n\n\n(*\nTheorem squareven : forall x : nat, Nat.even (square x) = true.\nProof.\n  intro x. induction x. simpl. reflexivity.\n  unfold square. \n *)\n(*\nTheorem eveneven : forall x y: nat, Nat.even x = true ->  Nat.even y = true -> Nat.even (x + y) = true.\nProof.\n  intros x y Hx Hy. induction x. simpl. apply Hy. \n *)\n(*\nTheorem eveneven : forall x: nat, Nat.even (x + x) = true.\nProof.\n  intros x. induction x. simpl. reflexivity.  simpl.\n *)\nTheorem eveneven : forall x: nat, Nat.even x = true -> Nat.even (S x) = false.\nProof.\n  intros x. ", "meta": {"author": "philzook58", "repo": "nand2coq", "sha": "c62c6e093cff428a86ce071e4d352c60a1dba471", "save_path": "github-repos/coq/philzook58-nand2coq", "path": "github-repos/coq/philzook58-nand2coq/nand2coq-c62c6e093cff428a86ce071e4d352c60a1dba471/coq/02_Basic_Proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7338579692444034}}
{"text": "Require Import ssreflect.\nFrom Coq.Relations Require Import Relations Relation_Operators.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* A stupid property of the transitive closure. *)\n\n(* We have two sub-relations A and B of V, which we now is a strict\n  partial order: then we want to show that if V is a strict partial\n  order, then thw tranisitive closure of A union B cannot have cycles\n  *)\n\n(* e.g. A is PO, B is RF, AUBT is CO/HB and V = is visibility *)\n  \nSection RelFacts.\n\nVariable X : Type.\nVariables (A B V: relation X).\n\nDefinition irreflexive (f : relation X) := forall x, f x x -> False.\n\nHypothesis AinV: inclusion X A V.\nHypothesis BinV: inclusion X B V.\n\nHypothesis transV: transitive X V.\nHypothesis irrV: irreflexive V.\n\nHypothesis transA: transitive X A.\nHypothesis irrA: irreflexive A.\n\nDefinition AUBT : relation X := clos_trans _ (union _ A B).\n\n(* Transitive + IRR => Anti *) \n\nLemma antiV: antisymmetric _ V.\nProof. move=>x y /transV H1 /H1 /irrV //. Qed.\n\nLemma AUBTinV : inclusion _ AUBT V.\nProof.  \nmove=> x y /= H; elim:H=>{x y}x0 y0; first by case; [move/AinV|move/BinV].\nby move=>z _ /transV H1 _ /H1.\nQed.\n\n(* AUBT cannot have cycles, because V does not have them *)\n\nLemma irrAUBT : irreflexive AUBT.\nProof. by move=>x /= /AUBTinV /irrV. Qed.\n\n(* AUBT trans: this should be trivial *)\n\nLemma transAUBT : transitive _ AUBT.\nProof. by exact:t_trans. Qed.\n\n(* AUBT anti: this is trivial as it is irreflexive and transitive*)\n\nLemma antiAUBT : antisymmetric _ AUBT.\nProof. move=>x y /transAUBT H2 /H2 /irrAUBT //. Qed. \n\nDefinition close {X} (r:relation X) (o:X) :=\n  fun x y =>  r x o /\\ r y o /\\ r x y.  \n\nEnd RelFacts.\n\n\n\n\n ", "meta": {"author": "germanD", "repo": "misc", "sha": "5702ba76b5ae6c1c70e5e8033ca2b28044d3876c", "save_path": "github-repos/coq/germanD-misc", "path": "github-repos/coq/germanD-misc/misc-5702ba76b5ae6c1c70e5e8033ca2b28044d3876c/sub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7338053968758592}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  plus lf2 (Succ (mult y x)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj232_coqofml_YnP29E.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7338053790237749}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (x : natural) : natural :=\n  plus y (mult (Succ y) x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj156_coqofml_CPMmiY.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.733805371856019}}
{"text": "From LF Require Export Induction.\nModule NatList.\n  Inductive natprod : Type :=\n  | pair (n1 n2 : nat).\n\n  Definition fst (p : natprod) : nat :=\n    match p with\n    | pair n1 n2 => n1\n    end.\n\n  Definition snd (p : natprod) : nat :=\n    match p with\n    | pair _ n2 => n2\n    end.\n\n  Notation \"( x , y )\" := (pair x y).\n\n  Definition swap_pair (p : natprod) : natprod :=\n    match p with\n    | pair x y => pair y x\n    end.\n\n  Theorem surjective_pairing : forall (p : natprod),\n      p = (fst p, snd p).\n  Proof.\n    intro p. destruct p as [n m]. simpl. reflexivity.\n  Qed.\n\n  Theorem snd_fst_is_swap : forall (p : natprod),\n      (snd p, fst p) = swap_pair p.\n  Proof.\n    intro p. destruct p as [n m]. simpl. reflexivity.\n  Qed.\n\n  Theorem fst_swap_is_snd : forall (p : natprod),\n      fst (swap_pair p) = snd p.\n  Proof.\n    intro p. destruct p as [n m]. simpl. reflexivity.\n  Qed.\n\n  Inductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\n  Notation \"x :: l\" := (cons x l) (at level 60, right associativity).\n  Notation \"[ ]\" := nil.\n  Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n  Fixpoint repeat (n count : nat) : natlist :=\n    match count with\n    | O => []\n    | S count' => n :: (repeat n count')\n    end.\n\n  Fixpoint length (l : natlist) : nat :=\n    match l with\n    | [] => O\n    | h :: t => 1 + (length t)\n    end.\n\n  Fixpoint app (l1 l2 : natlist) : natlist :=\n    match l1 with\n    | [] => l2\n    | h :: t => h :: (app t l2)\n    end.\n\n  Notation \"x ++ y\" := (app x y) (at level 60, right associativity).\n\n  Example test_app1 : [1;2;3] ++ [4;5] = [1;2;3;4;5].\n  Proof. reflexivity. Qed.\n  Example test_app2 : [] ++ [4;5] = [4;5].\n  Proof. reflexivity. Qed.\n  Example test_app3 : [1;2;3] ++ [] = [1;2;3].\n  Proof. reflexivity. Qed.\n\n  Definition hd (default : nat) (l : natlist) : nat :=\n    match l with\n    | [] => default\n    | h :: t => h\n    end.\n\n  Definition tl (l : natlist) : natlist :=\n    match l with\n    | [] => []\n    | h :: t => t\n    end.\n\n  Fixpoint nonzeros (l : natlist) : natlist :=\n    match l with\n    | [] => []\n    | O :: t => nonzeros t\n    | h :: t => h :: (nonzeros t)\n    end.\n\n  Fixpoint nonzeros' (l : natlist) (acc : natlist) : natlist :=\n    match l with\n    | [] => acc\n    | h :: t => if eqb h 0 then nonzeros' t acc else nonzeros' t acc++[h]\n    end.\n\n  Fixpoint oddmembers (l : natlist) : natlist :=\n    match l with\n    | [] => l\n    | h :: t => if oddb h then h :: (oddmembers t) else oddmembers t\n    end.\n\n  Fixpoint countoddmembers (l : natlist) : nat :=\n    match l with\n    | [] => O\n    | h :: t => if oddb h then S (countoddmembers t)\n                else countoddmembers t\n    end.\n\n  Example test_countoddmembers1 :\n    countoddmembers [1;0;3;1;4;5] = 4.\n  Proof. reflexivity. Qed.\n\n  Fixpoint alternate (l1 l2 : natlist) : natlist :=\n    match l1, l2 with\n    | [], _ => l2\n    | _, [] => l1\n    | h1 :: t1, h2 :: t2 => h1 :: h2 :: (alternate t1 t2)\n    end.\n  \n  Example test_alternate1:\n    alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  Proof. reflexivity. Qed.\n  Example test_alternate2:\n    alternate [1] [4;5;6] = [1;4;5;6].\n  Proof. reflexivity. Qed.\n  Example test_alternate3:\n    alternate [1;2;3] [4] = [1;4;2;3].\n  Proof. reflexivity. Qed.\n  Example test_alternate4:\n    alternate [] [20;30] = [20;30].\n  Proof. reflexivity. Qed.\n  \n  Definition bag := natlist.\n  \n  Fixpoint count (v : nat) (s : bag) : nat :=\n    match s with\n    | [] => O\n    | h :: s' => if eqb h v then S(count v s')\n                 else count v s'\n    end.\n  \n  Example test_count1: count 1 [1;2;3;1;4;1] = 3.\n  Proof. reflexivity. Qed.\n  Example test_count2: count 6 [1;2;3;1;4;1] = 0.\n  Proof. reflexivity. Qed.\n  \n  Definition sum : bag -> bag -> bag := app.\n  \n  Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n  Proof. reflexivity. Qed.\n  \n  Definition add (v:nat) (s:bag) : bag := v :: s.\n  \n  Example test_add1: count 1 (add 1 [1;4;1]) = 3.\n  Proof. reflexivity. Qed.\n  Example test_add2: count 5 (add 1 [1;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  \n  Fixpoint member (v:nat) (s:bag) : bool :=\n    match s with\n    | [] => false\n    | h :: t => if eqb v h then true\n                else member v t\n    end.\n  \n  Example test_member1: member 1 [1;4;1] = true.\n  Proof. reflexivity. Qed.\n  Example test_member2: member 2 [1;4;1] = false.\n  Proof. reflexivity. Qed.\n  \n  Fixpoint remove_one (v:nat) (s:bag) : bag :=\n    match s with\n    | [] => s\n    | h :: s' => if eqb v h then s'\n                 else h :: (remove_one v s')\n    end.\n  \n  Example test_remove_one1:\n    count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_one2:\n    count 5 (remove_one 5 [2;1;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_one3:\n    count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  Proof. reflexivity. Qed.\n  Example test_remove_one4:\n    count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  Proof. reflexivity. Qed.\n  \n  Fixpoint remove_all (v:nat) (s:bag) : bag :=\n    match s with\n    | [] => []\n    | h :: s' => if eqb v h then remove_all v s'\n                 else h :: (remove_all v s')\n    end.\n  \n  Example test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n  Proof. reflexivity. Qed.\n  Example test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n  Proof. reflexivity. Qed.\n\n  Fixpoint subset (s1:bag) (s2:bag) : bool :=\n    match s1 with\n    | [] => true\n    | h :: t => if member h s2 then subset t (remove_one h s2)\n                else false\n    end.\n\n  Example test_subset1: subset [1;2] [2;1;4;1] = true.\n  Proof. reflexivity. Qed.\n  Example test_subset2: subset [1;2;2] [2;1;4;1] = false.\n  Proof. reflexivity. Qed.\n\n  Theorem nil_app : forall l : natlist, [] ++ l = l.\n  Proof. intro l. simpl. reflexivity. Qed.\n\n  Theorem tl_length_pred : forall l : natlist,\n      pred (length l) = length (tl l).\n  Proof.\n    intro l. destruct l.\n    - reflexivity.\n    - simpl. reflexivity.\n  Qed.\n\n  Theorem app_assoc : forall l1 l2 l3 : natlist,\n      (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n  Proof.\n    intros. induction l1 as [| n l1' IHl1'].\n    - simpl. reflexivity.\n    - simpl. rewrite IHl1'. reflexivity.\n  Qed.\n\n  Fixpoint rev (l : natlist) : natlist :=\n    match l with\n    | nil => nil\n    | h :: t => (rev t) ++ [h]\n    end.\n\n  Example test_rev1: rev [1;2;3] = [3;2;1].\n  Proof. reflexivity. Qed.\n  Example test_rev2: rev nil = nil.\n  Proof. reflexivity. Qed.\n\n  Lemma app_length : forall l1 l2 : natlist,\n      length (l1 ++ l2) = (length l1) + (length l2).\n  Proof.\n    intros l1 l2. induction l1.\n    - simpl. reflexivity.\n    - simpl. rewrite IHl1. reflexivity.\n  Qed.\n  \n  Theorem rev_length : forall l : natlist,\n      length (rev l) = length l.\n  Proof.\n    intro l. induction l as [| n l' IHl'].\n    - reflexivity.\n    - simpl. rewrite app_length. rewrite IHl'. simpl.\n      rewrite plus_comm. simpl. reflexivity.\n  Qed.\n\n  Theorem app_nil_r : forall l : natlist, l ++ [] = l.\n  Proof.\n    intro l. induction l.\n    - reflexivity.\n    - simpl. rewrite -> IHl. reflexivity.\n  Qed.\n\n  Theorem rev_app_distr : forall l1 l2 : natlist,\n      rev (l1 ++ l2) = rev l2 ++ rev l1.\n  Proof.\n    intros. induction l1.\n    - simpl. rewrite app_nil_r. reflexivity.\n    - simpl. rewrite IHl1. rewrite app_assoc. reflexivity.\n  Qed.\n\n  Theorem rev_involutive : forall l : natlist,\n      rev (rev l) = l.\n  Proof.\n    intro l; induction l.\n    - reflexivity.\n    - simpl. rewrite rev_app_distr. rewrite IHl.\n      simpl. reflexivity.\n  Qed.\n\n  Theorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n      l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\n  Proof.\n    intros. induction l1.\n    - simpl. rewrite app_assoc. reflexivity.\n    - simpl. rewrite IHl1. reflexivity.\n  Qed.\n\n  Lemma nonzeros_app : forall l1 l2 : natlist,\n      nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\n  Proof.\n    intros. induction l1.\n    - simpl. reflexivity.\n    - simpl. destruct n as [| n'] eqn:E.\n      + apply IHl1.\n      + rewrite IHl1. simpl. reflexivity.\n  Qed.\n\n  Fixpoint eqblist (l1 l2 : natlist) : bool :=\n    match l1, l2 with\n    | nil, nil => true\n    | h1 :: t1, h2 :: t2 => if eqb h1 h2 then eqblist t1 t2 else false\n    | _, _ => false\n    end.\n\n  Example test_eqblist1 : (eqblist nil nil = true).\n  Proof. reflexivity. Qed.\n  Example test_eqblist2 : eqblist [1;2;3] [1;2;3] = true.\n  Proof. reflexivity. Qed.\n  Example test_eqblist3 : eqblist [1;2;3] [1;2;4] = false.\n  Proof. reflexivity. Qed.\n\n  Theorem eqb_refl : forall n : nat, true = eqb n n.\n  Proof.\n    intro n. induction n.\n    - reflexivity.\n    - simpl. apply IHn.\n  Qed.\n\n  Theorem eqblist_refl : forall l : natlist, true = eqblist l l.\n  Proof.\n    intro l. induction l.\n    - reflexivity.\n    - simpl. rewrite <- IHl. rewrite <- eqb_refl. reflexivity.\n  Qed.\n\n  Theorem count_member_nonzero : forall s : bag,\n      1 <=? (count 1 (1 :: s)) = true.\n  Proof.\n    intro s. simpl. reflexivity. Qed.\n\n  Theorem leb_n_Sn : forall n : nat, n <=? (S n) = true.\n  Proof.\n    intro n. induction n.\n    - reflexivity.\n    - simpl. apply IHn.\n  Qed.\n\n  Theorem remove_does_not_increase_count : forall s : bag,\n      (count 0 (remove_one 0 s)) <=? (count 0 s) = true.\n  Proof.\n    intro s. induction s.\n    - reflexivity.\n    - simpl. destruct n.\n      + simpl. rewrite leb_n_Sn. reflexivity.\n      + simpl. apply IHs.\n  Qed.\n\n  Theorem rev_injective : forall l1 l2 : natlist,\n      rev l1 = rev l2 -> l1 = l2.\n  Proof.\n    intros. rewrite <- rev_involutive. rewrite <- H.\n    rewrite rev_involutive. reflexivity.\n  Qed.\n\n  Inductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\n  Fixpoint nth_error (l : natlist) (n : nat) : natoption :=\n    match l with\n    | [] => None\n    | h :: t => if n =? 0 then Some h else nth_error t (n - 1)\n    end.\n\n  Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\n  Proof. reflexivity. Qed.\n  Example test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\n  Proof. reflexivity. Qed.\n  Example test_nth_error3 : nth_error [4;5;6;7] 9 = None.\n  Proof. reflexivity. Qed.\n\n  Definition option_elim (d : nat) (o : natoption) : nat :=\n    match o with\n    | Some n' => n'\n    | None => d\n    end.\n\n  Definition hd_error (l : natlist) : natoption :=\n    match l with\n    | nil => None\n    | h :: t => Some h\n    end.\n\n  Theorem option_elim_hd : forall (l : natlist) (default : nat),\n      hd default l = option_elim default (hd_error l).\n  Proof.\n    intros. destruct l as [| n l'].\n    - reflexivity.\n    - simpl. reflexivity.\n  Qed.\n\nEnd NatList.\n\nInductive id : Type :=\n| Id (n : nat).\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\nTheorem eqb_id_refl : forall x, true = eqb_id x x.\nProof.\n  intro x. destruct x as [n].\n  simpl. Search eqb. rewrite <- NatList.eqb_refl.\n  reflexivity.\nQed.\n\nModule PartialMap.\n  Export NatList.\n\n  Inductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\n  Definition update (d : partial_map) (x : id) (value : nat)\n    : partial_map :=\n    record x value d.\n\n  Fixpoint find (x : id) (d : partial_map) : natoption :=\n    match d with\n    | empty => None\n    | record k v d' => if eqb_id x k then Some v\n                       else find x d'\n    end.\n\n  Theorem update_eq :\n    forall (d : partial_map) (x : id) (v : nat),\n      find x (update d x v) = Some v.\n  Proof.\n    intros. simpl. rewrite <- eqb_id_refl. reflexivity.\n  Qed.\n\n  Theorem 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.\n  Proof. intros. simpl. rewrite H. reflexivity. Qed.\n\nEnd PartialMap.", "meta": {"author": "kailiangji", "repo": "software-foundation-exercise", "sha": "1538f43bcf240d3f9f2502aa4164cecf821da61b", "save_path": "github-repos/coq/kailiangji-software-foundation-exercise", "path": "github-repos/coq/kailiangji-software-foundation-exercise/software-foundation-exercise-1538f43bcf240d3f9f2502aa4164cecf821da61b/logic_foundation/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.7336821154830981}}
{"text": "(* Generalizing the definition of pairs, we can describe the type of lists of numbers like this: \"A list is either the empty 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 familiar programming notation. The following declarations allow us to use :: as an infix cons operator and square 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(* all equivalent *)\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n\n(* Next let's look at several functions for constructing and manipulating lists. First, the repeat function takes a number n and a count and returns a list of length count in which 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(* The length function calculates the length of a list. *)\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\n(* The app function concatenates (appends) two lists. *)\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 to have an infix operator for it. *)\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n                    \n(* Here are two smaller examples of programming with lists. The hd function returns the first element (the \"head\") of the list, while tl returns everything but the first element (the \"tail\"). Since the empty list has no first element, we 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.", "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/lists/lessons/lists_of_numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.733682115447297}}
{"text": "Require Export ZArith.\nRequire Export FunInd.\nRequire Export Omega.\nOpen Scope Z_scope.\n\nInductive AB : Set :=\n  | Node : Z -> AB -> AB -> AB\n  | Empty : AB.\n\n(*is_ABR node lower upper\nequal goes left*)\nInductive is_ABR : AB -> (option Z) -> (option Z) -> Prop :=\n  | Empty_N : is_ABR Empty None None\n  | Empty_L : forall (vL : Z), is_ABR Empty (Some vL) None\n  | Empty_U : forall (vR : Z), is_ABR Empty None (Some vR)\n  | Empty_B : forall (vL vR : Z), vL <= vR -> is_ABR Empty (Some vL) (Some vR)\n  | No_Limits : forall (v : Z) (aL aR : AB), is_ABR aL None (Some v) -> is_ABR aR (Some v) None -> \n    is_ABR (Node v aL aR) None None\n  | Lower : forall (v vL : Z) (aL aR : AB), v > vL -> is_ABR aL (Some vL) (Some v) ->\n    is_ABR aR (Some v) None -> is_ABR (Node v aL aR) (Some vL) None\n  | Upper : forall (v vR : Z) (aL aR : AB), v <= vR -> is_ABR aL None (Some v) ->\n    is_ABR aR (Some v) (Some vR) -> is_ABR (Node v aL aR) None (Some vR)\n  | Both : forall (v vL vR : Z) (aL aR : AB), v > vL -> v <= vR -> is_ABR aL (Some vL) (Some v) ->\n    is_ABR aR (Some v) (Some vR) -> is_ABR (Node v aL aR) (Some vL) (Some vR).\n\nDefinition benchmark_01 := (Node 3 (Node 1 (Node 0 Empty Empty) (Node 3 Empty Empty)) (Node 5 Empty Empty)).\nDefinition benchmark_02 := (Node 5 (Node 3 (Node 2 Empty Empty) (Node 4 Empty Empty)) (Node 7 (Node 7 Empty Empty) (Node 8 Empty Empty))).\nDefinition benchmark_03 := (Node 15 (Node 12 (Node 11 (Node 5 Empty Empty) Empty) (Node 14 (Node 13 Empty (Node 14 Empty Empty)) (Node 15 Empty Empty))) (Node 18 (Node 17 Empty Empty) (Node 19 Empty (Node 20 Empty Empty)))).\n\nLemma p1 : is_ABR benchmark_01 None None.\napply No_Limits.\napply Upper.\nomega.\napply Upper.\nomega.\napply Empty_U.\napply Empty_B.\nomega.\napply Both.\nomega.\nomega.\napply Empty_B.\nomega.\napply Empty_B.\nomega.\napply Lower.\nomega.\napply Empty_B.\nomega.\napply Empty_L.\n\nLtac apply_is_ABR :=\n  repeat\n  apply Empty_N || apply Empty_L || apply Empty_U || apply Empty_B || \n  apply No_Limits || apply Lower || apply Upper || apply Both || auto || omega.\n\nLemma p2 : is_ABR benchmark_02 None None.\napply_is_ABR.\nQed.\n\n\nLemma p3 : is_ABR benchmark_03 None None.\napply_is_ABR.\nQed.\n\nInductive value_exists : AB -> Z -> Prop :=\n  | Curr : forall (v : Z) (aL aR : AB), value_exists (Node v aL aR) v\n  | Left : forall (v vL : Z) (aL aR : AB), value_exists aL vL ->\n    value_exists (Node v aL aR) vL\n  | Right : forall (v vR : Z) (aL aR : AB), value_exists aR vR ->\n    value_exists (Node v aL aR) vR.\n\nLemma p5 : value_exists benchmark_01 3.\neapply Curr.\nQed.\n\nLemma p6 : value_exists benchmark_03 17.\neapply Right.\neapply Left.\neapply Curr.\nQed.\n\nFixpoint search (arbre : AB) (v : Z) : bool :=\n  match arbre with\n  | Empty => false\n  | Node w aL aR =>\n    if Z.eq_dec v w then true\n    else if Z_le_dec v w then search aL v\n    else search aR v\nend.\n\nFunctional Scheme search_ind := Induction for search Sort Prop.\n\nLemma both_upper : forall (arbre : AB) (vL vR : Z), is_ABR arbre (Some vL) (Some vR) -> \n    is_ABR arbre None (Some vR).\nintros.\ninduction H; apply_is_ABR.\nQed.\n\nLemma both_lower : forall (arbre : AB) (vL vR : Z), is_ABR arbre (Some vL) (Some vR) -> \n    is_ABR arbre (Some vL) None.\nintros.\ninduction H; apply_is_ABR.\nQed.\n\nLemma both_option_reduce : forall (arbre : AB) (vL vR : option Z), is_ABR arbre vL vR ->\n    is_ABR arbre None None.\nintros.\ninduction H; apply_is_ABR.\neapply both_upper.\napply H0.\neapply both_lower.\napply H1.\neapply both_upper.\napply H1.\neapply both_lower.\napply H2.\nQed.\n\nTheorem search_sound : \n  forall (arbre : AB) (v : Z), is_ABR arbre None None -> search arbre v = true -> value_exists arbre v.\n\nProof.\nintro.\nintro.\nintro.\nfunctional induction (search arbre v) using search_ind; intros.\neapply Curr.\neapply Left.\napply IHb.\ninversion H.\neapply both_option_reduce.\napply H3.\nassumption.\napply Right.\napply IHb.\ninversion H.\neapply both_option_reduce.\napply H5.\nassumption.\ncontradict H0.\nauto.\nQed.\n\nLemma limits : forall (arbre : AB) (vL vR : Z), is_ABR arbre (Some vL) (Some vR) -> vL <= vR.\nintros.\ninversion H.\nassumption.\nomega.\nQed.\n\nLemma combine_limits_R : forall (arbre : AB) (vL vR1 vR2 : Z), is_ABR arbre (Some vL) (Some vR1) ->\n    is_ABR arbre None (Some vR2) -> vR1 <= vR2 ->  is_ABR arbre (Some vL) (Some vR2).\nintros.\ninduction arbre.\napply_is_ABR.\ninversion H.\nomega.\ninversion H0.\nomega.\ninversion H.\nassumption.\ninversion H0.\nassumption.\napply_is_ABR.\ninversion H.\nomega.\nQed.\n\nLemma right_loosen : forall (arbre : AB) (vR1 vR2 : Z), is_ABR arbre None (Some vR1) ->\n    vR1 <= vR2 -> is_ABR arbre None (Some vR2).\nintros.\ninduction arbre.\napply_is_ABR.\ninversion H.\nomega.\ninversion H.\nassumption.\ninversion H.\neapply combine_limits_R.\napply H7.\napply IHarbre2.\neapply both_upper.\napply H7.\nomega.\napply_is_ABR.\nQed.\n\nLemma left_less : forall (aL aR : AB) (v vL : Z), is_ABR (Node v aL aR) None None -> \n    value_exists aL vL -> vL <= v.\nintros.\ninduction H0.\ninversion H.\ninversion H2.\nomega.\napply IHvalue_exists.\ninversion H.\napply_is_ABR.\ninversion H3.\neapply right_loosen.\napply H11.\nomega.\napply IHvalue_exists.\ninversion H.\napply_is_ABR.\ninversion H3.\neapply both_upper.\napply H12.\nQed.\n\nLemma combine_limits_L : forall (arbre : AB) (vL1 vL2 vR : Z), is_ABR arbre (Some vL1) (Some vR) ->\n    is_ABR arbre (Some vL2) None -> vL2 <= vL1 ->  is_ABR arbre (Some vL2) (Some vR).\nintros.\ninduction arbre.\napply_is_ABR.\ninversion H.\nomega.\ninversion H.\nomega.\ninversion H0.\nassumption.\ninversion H.\nassumption.\napply_is_ABR.\ninversion H.\nomega.\nQed.\n\nLemma left_loosen : forall (arbre : AB) (vL1 vL2 : Z), is_ABR arbre (Some vL1) None ->\n    vL2 <= vL1 -> is_ABR arbre (Some vL2) None.\nintros.\ninduction arbre.\napply_is_ABR.\ninversion H.\nomega.\ninversion H.\neapply combine_limits_L.\napply H6.\napply IHarbre1.\neapply both_lower.\napply H6.\nassumption.\ninversion H.\nassumption.\napply_is_ABR.\nQed.\n\nLemma right_more : forall (aL aR : AB) (v vR : Z), is_ABR (Node v aL aR) None None -> \n    value_exists aR vR -> vR > v.\nintros.\ninduction H0.\ninversion H.\ninversion H4.\nomega.\napply IHvalue_exists.\ninversion H.\napply_is_ABR.\ninversion H5.\neapply both_lower.\napply H11.\napply IHvalue_exists.\ninversion H.\napply_is_ABR.\ninversion H5.\neapply left_loosen.\napply H12.\nomega.\nQed.\n\nTheorem search_complete : forall (arbre : AB) (v : Z), is_ABR arbre None None ->\n    value_exists arbre v -> search arbre v = true.\nintro.\nintro.\nintro.\nintro.\ninduction H0.\nsimpl.\nelim (Z.eq_dec v v); intro; auto.\nsimpl.\nelim (Z.eq_dec vL v); intro; auto.\nelim (Z_le_dec vL v); intro; auto.\napply IHvalue_exists.\ninversion H.\neapply both_option_reduce.\napply H3.\ncontradict b0.\neapply left_less.\napply H.\napply H0.\nsimpl.\nelim (Z.eq_dec vR v); intro; auto.\nelim (Z_le_dec vR v); intro; auto.\ndestruct a.\neapply right_more.\napply H.\napply H0.\napply IHvalue_exists.\ninversion H.\neapply both_option_reduce.\napply H5.\nQed.\n\n\nFixpoint insert (arbre : AB) (v : Z) : AB :=\n  match arbre with\n  | Empty => (Node v Empty Empty)\n  | Node w aL aR =>\n    if Z.eq_dec v w then arbre\n    else if Z_le_dec v w then (Node w (insert aL v) aR)\n    else (Node w aL (insert aR v))\nend.\n\nFunctional Scheme insert_ind := Induction for insert Sort Prop.\n\nLemma combine : forall (vL vR : Z) (arbre : AB), is_ABR arbre None (Some vR) ->\n    is_ABR arbre (Some vL) None -> vL <= vR -> is_ABR arbre (Some vL) (Some vR).\nintros.\ninduction arbre.\napply_is_ABR.\ninversion H0.\nomega.\ninversion H.\nomega.\ninversion H0.\nassumption.\ninversion H.\nassumption.\napply_is_ABR.\nQed.\n\nLemma insert_right : forall (v vR : Z) (arbre : AB), is_ABR arbre None (Some vR) ->\n    is_ABR (insert arbre v) None None -> v <= vR -> is_ABR (insert arbre v) None (Some vR).\nintros.\nfunctional induction (insert arbre v) using insert_ind; intros.\nassumption.\napply_is_ABR.\ninversion H.\nomega.\ninversion H0.\nassumption.\ninversion H.\nassumption.\napply_is_ABR.\ninversion H.\ninversion H.\nassumption.\ninversion H0.\napply combine.\napply IHa.\neapply both_upper.\ninversion H.\napply H13.\neapply both_option_reduce.\napply H6.\nassumption.\nassumption.\nomega.\napply_is_ABR.\nQed.\n\nLemma insert_left : forall (v vL : Z) (arbre : AB), is_ABR arbre (Some vL) None ->\n    is_ABR (insert arbre v) None None -> v > vL -> is_ABR (insert arbre v) (Some vL) None.\nintros.\nfunctional induction (insert arbre v) using insert_ind; intros.\nassumption.\napply_is_ABR.\napply combine.\ninversion H0.\nassumption.\napply IHa.\ninversion H.\neapply both_lower.\napply H7.\ninversion H0.\neapply both_option_reduce.\napply H4.\nomega.\nomega.\ninversion H.\nassumption.\napply_is_ABR.\ninversion H.\nomega.\ninversion H.\nassumption.\ninversion H0.\nassumption.\napply_is_ABR.\nQed.\n\nLemma insert_is_ABR : forall (v : Z) (a_in : AB), is_ABR a_in None None ->\n    is_ABR (insert a_in v) None None.\nintro.\nintro.\nintro.\nfunctional induction (insert a_in v) using insert_ind; intros.\napply_is_ABR.\ninversion H.\nassumption.\ninversion H.\nassumption.\napply_is_ABR.\ninversion H.\neapply insert_right; auto.\napply IHa.\neapply both_option_reduce.\napply H2.\ninversion H.\nassumption.\ninversion H.\napply_is_ABR.\napply insert_left; auto.\napply IHa.\neapply both_option_reduce.\napply H4.\nomega.\napply_is_ABR.\nQed.\n\nLemma insert_new_value : forall (v : Z) (a_in : AB), is_ABR a_in None None ->\n    value_exists (insert a_in v) v.\nintros.\nfunctional induction (insert a_in v) using insert_ind; intros.\napply Curr.\napply Left.\napply IHa.\ninversion H.\neapply both_option_reduce.\napply H2.\napply Right.\napply IHa.\ninversion H.\neapply both_option_reduce.\napply H4.\napply Curr.\nQed.\n\nLemma insert_no_loss : forall (v : Z) (a_in : AB), is_ABR a_in None None ->\n    (forall (w : Z), value_exists a_in w -> value_exists (insert a_in v) w).\nintros.\nfunctional induction (insert a_in v) using insert_ind; intros.\nassumption.\ninversion H0.\napply Curr.\napply Left.\napply IHa.\ninversion H.\neapply both_option_reduce.\napply H8.\nassumption.\napply Right.\nassumption.\ninversion H0.\napply Curr.\napply Left.\nassumption.\napply Right.\napply IHa.\ninversion H.\neapply both_option_reduce.\napply H10.\nassumption.\ninversion H0.\nQed.\n\nTheorem insert_sound : forall (v : Z) (a_in a_out : AB), is_ABR a_in None None -> a_out = (insert a_in v) ->\n    is_ABR a_out None None /\\ value_exists a_out v /\\ (forall (w : Z), value_exists a_in w -> value_exists a_out w).\nintros.\nrewrite H0.\nsplit.\napply insert_is_ABR.\nassumption.\nsplit.\napply insert_new_value.\nassumption.\napply insert_no_loss.\nassumption.\nQed.\n\nFixpoint find_max (arbre : AB) : option Z :=\n  match arbre with\n  | Empty => None\n  | (Node x _ Empty) => (Some x)\n  | (Node x _ aR) => find_max aR\nend.\n\nFixpoint delete (arbre : AB) (v : Z) : AB :=\n  match arbre with\n  | Empty => Empty\n  | (Node w aL aR) =>\n    if Z.eq_dec w v then \n    match aL, aR with\n    | Empty, aR => aR\n    | aL, Empty => aL\n    | aL, aR => let max := find_max aL in\n      match max with\n      | None => aR\n      | Some x => (Node x (delete aL x) aR)\n    end\n   end\n    else if Z_lt_dec v w then (Node w (delete aL v) aR)\n    else (Node w aL (delete aR v))\nend.\n\nFunctional Scheme find_max_ind := Induction for find_max Sort Prop.\nFunctional Scheme delete_ind := Induction for delete Sort Prop.\n\nLemma max_geq : forall (arbre : AB) (x vR : Z) (L : option Z), is_ABR arbre L (Some vR) ->\n    (find_max arbre) = (Some x) -> x <= vR.\nintros.\nfunctional induction (find_max arbre) using find_max_ind.\napply IHo.\ninversion H.\neapply both_upper.\napply H8.\napply combine.\neapply both_upper.\napply H9.\neapply left_loosen.\neapply both_lower.\napply H9.\neapply limits.\napply H8.\ninversion H9.\ncut (vL <= x0).\nomega.\neapply limits.\napply H8.\napply H0.\ninversion H0.\nrewrite <- H2.\ninversion H; omega.\ninversion H0.\nQed.\n\nLemma min_less : forall (arbre : AB) (x vL : Z) (R : option Z), is_ABR arbre (Some vL) R ->\n    find_max arbre = (Some x) -> x > vL.\nintros.\nfunctional induction (find_max arbre) using find_max_ind.\napply IHo.\ninversion H.\neapply left_loosen.\napply H8.\neapply limits.\napply H7.\napply combine.\neapply both_upper.\napply H9.\neapply left_loosen.\neapply both_lower.\napply H9.\neapply limits.\napply H8.\ncut (vL <= x0).\nomega.\neapply limits.\napply H8.\nauto.\ninversion H0.\nrewrite <- H2.\ninversion H; omega.\ninversion H0.\nQed.\n\n\n\nLemma max_limit : forall (arbre : AB) (x : Z), is_ABR arbre None None -> \n    (find_max arbre) = (Some x) -> is_ABR arbre None (Some x).\nintros.\nfunctional induction (find_max arbre) using find_max_ind.\napply_is_ABR.\ncut (is_ABR (Node _x0 _x1 _x2) None (Some x)).\nintros.\ninversion H1.\ninversion H.\ninversion H13.\nomega.\napply IHo.\ninversion H.\neapply both_option_reduce.\napply H5.\nauto.\ninversion H.\nauto.\ninversion H.\ninversion H5.\nomega.\ncut (is_ABR (Node _x0 _x1 _x2) None (Some x)).\nintros.\ninversion H1.\neapply limits.\napply H8.\napply IHo.\ninversion H.\neapply both_option_reduce.\napply H5.\nauto.\ninversion H.\ninversion H5.\nauto.\ninversion H.\ninversion H5.\napply combine.\ncut (is_ABR (Node _x0 _x1 _x2) None (Some x)).\nintros.\ninversion H13.\neapply both_upper.\napply H20.\napply IHo.\ninversion H.\neapply both_option_reduce.\napply H5.\nauto.\napply H12.\ncut (is_ABR (Node _x0 _x1 _x2) None (Some x)).\nintros.\ninversion H13.\nomega.\napply IHo.\ninversion H.\neapply both_option_reduce.\napply H5.\nauto.\ninversion H.\ninversion H0.\napply_is_ABR.\nrewrite <- H7.\nauto.\ninversion H0.\nQed.\n\nLemma delete_right : forall (arbre : AB) (v vR : Z), is_ABR arbre None (Some vR) ->\n    is_ABR (delete arbre v) None None -> is_ABR (delete arbre v) None (Some vR).\nintros.\nfunctional induction (delete arbre v) using delete_ind; apply_is_ABR.\neapply max_geq.\ninversion H.\neapply right_loosen.\napply H6.\nomega.\napply e3.\ninversion H0.\nsimpl.\nauto.\ninversion H0.\ninversion H5.\nomega.\ninversion H.\ninversion H7.\nomega.\ninversion H.\ninversion H7.\napply combine.\neapply both_upper.\napply H15.\neapply left_loosen.\neapply both_lower.\napply H15.\neapply max_geq.\napply H6.\nauto.\ninversion H0.\ninversion H21.\nomega.\ninversion H.\ninversion H7.\napply H16.\ninversion H.\ninversion H7.\nomega.\ninversion H0.\nauto.\ninversion H.\ninversion H7.\nauto.\ninversion H.\ninversion H6.\ncut (w <= vR).\nomega.\neapply limits.\napply H7.\ninversion H.\ninversion H6.\nauto.\ninversion H.\ninversion H6.\napply combine.\neapply right_loosen.\neapply both_upper.\napply H14.\neapply limits.\napply H7.\neapply both_lower.\napply H14.\ncut (w <= vR).\nomega.\neapply limits.\napply H7.\ninversion H.\neapply both_upper.\napply H7.\ninversion H.\nomega.\ninversion H0.\napply H3.\ninversion H.\nauto.\ninversion H.\nauto.\ninversion H.\nauto.\ninversion H0.\ninversion H.\napply combine.\napply IHa.\neapply both_upper.\napply H12.\neapply both_option_reduce.\napply H5.\nauto.\neapply limits.\napply H12.\nQed.\n\nLemma delete_left : forall (arbre : AB) (v vL : Z), is_ABR arbre (Some vL) None ->\n    is_ABR (delete arbre v) None None -> is_ABR (delete arbre v) (Some vL) None.\nintros.\nfunctional induction (delete arbre v) using delete_ind; apply_is_ABR.\neapply min_less.\ninversion H.\napply H6.\nauto.\napply combine.\ninversion H0.\nsimpl.\nauto.\napply IHa.\ninversion H.\neapply both_lower.\napply H6.\neapply both_option_reduce.\nsimpl.\ninversion H0.\napply H3.\ncut (x > vL).\nomega.\neapply min_less.\ninversion H.\napply H6.\nauto.\ncut (x <= w).\nintro.\ninversion H.\ninversion H8.\nomega.\neapply max_geq.\ninversion H.\napply H6.\nauto.\ninversion H.\ninversion H7.\napply combine.\neapply both_upper.\napply H13.\neapply left_loosen.\neapply both_lower.\napply H13.\neapply max_geq.\napply H6.\nauto.\ncut (x <= w).\nomega.\neapply max_geq.\napply H6.\nauto.\ninversion H.\ninversion H7.\nauto.\ninversion H.\ninversion H7.\nauto.\ncut (vL <= w).\nomega.\neapply limits.\napply H6.\ninversion H.\ninversion H7.\napply combine.\neapply both_upper.\napply H13.\neapply left_loosen.\neapply both_lower.\napply H13.\neapply limits.\napply H6.\ncut (vL <= w).\nomega.\neapply limits.\napply H6.\ninversion H.\ninversion H7.\nauto.\ninversion H.\ninversion H6.\nomega.\ninversion H.\ninversion H6.\nauto.\ninversion H.\ninversion H6.\neapply both_lower.\napply H16.\ninversion H.\neapply left_loosen.\napply H7.\neapply limits.\napply H6.\ninversion H.\nomega.\napply combine.\ninversion H0.\nauto.\napply IHa.\ninversion H.\neapply both_lower.\napply H6.\ninversion H0.\neapply both_option_reduce.\napply H3.\ninversion H.\nomega.\ninversion H.\nauto.\ninversion H.\nomega.\ninversion H.\nauto.\ninversion H0.\nauto.\nQed.\n\n\n\nLemma delete_is_ABR : forall (arbre : AB) (v : Z), is_ABR arbre None None ->\n    is_ABR (delete arbre v) None None.\nintros.\nfunctional induction (delete arbre v) using delete_ind; apply_is_ABR.\neapply delete_right.\napply_is_ABR.\ncut (is_ABR (Node _x0 _x1 _x2) None (Some x)).\nintros.\ninversion H0.\neapply limits.\napply H7.\neapply max_limit.\ninversion H.\neapply both_option_reduce.\napply H2.\napply e3.\ninversion H.\ninversion H2.\napply H10.\ninversion H.\ninversion H2.\napply combine.\ncut (is_ABR (Node _x0 _x1 _x2) None (Some x)).\nintros.\ninversion H12.\neapply both_upper.\napply H19.\neapply max_limit.\neapply both_option_reduce.\napply H2.\nauto.\neapply both_lower.\napply H11.\ncut (is_ABR (Node _x0 _x1 _x2) None (Some x)).\nintros.\ninversion H12.\nomega.\neapply max_limit.\ninversion H.\neapply both_option_reduce.\napply H14.\nauto.\napply IHa.\ninversion H.\neapply both_option_reduce.\napply H2.\ninversion H.\ninversion H4.\ncut (x <= w).\nomega.\neapply max_geq.\napply H2.\nauto.\ninversion H.\ninversion H4.\napply combine.\neapply both_upper.\napply H10.\neapply left_loosen.\neapply both_lower.\napply H10.\neapply max_geq.\napply H2.\nauto.\ncut (x <= w).\nomega.\neapply max_geq.\napply H2.\nauto.\ninversion H.\ninversion H4.\napply H11.\ninversion H.\ninversion H4.\neapply both_upper.\napply H10.\ninversion H.\ninversion H4.\napply H11.\ninversion H.\ninversion H2.\napply H10.\ninversion H.\ninversion H2.\neapply both_lower.\napply H11.\ninversion H.\neapply both_option_reduce.\napply H4.\neapply delete_right.\ninversion H.\napply H2.\napply IHa.\ninversion H.\neapply both_option_reduce.\napply H2.\ninversion H.\nauto.\ninversion H.\nauto.\neapply delete_left.\ninversion H.\nauto.\napply IHa.\ninversion H.\neapply both_option_reduce.\napply H4.\nQed.\n\nFixpoint delete_all (arbre : AB) (v : Z) {struct arbre} : AB :=\n  let del_one := (delete arbre v) in\n  if (search del_one v) then \n  match del_one with\n  | Empty => Empty\n  | (Node x aL aR) => (delete_all del_one v) \nend\n  else del_one.\n\nFixpoint leftmost_value (v : Z) (aL : AB) : Z :=\n  match aL with\n  | Empty => v\n  | (Node vL aLL aLR) => leftmost_value vL aLL\nend.\n\nFixpoint delete_leftmost (arbre : AB) : AB :=\n  match arbre with\n  | Empty => Empty\n  | (Node v aL aR) =>\n    match aL with\n    | Empty => aR\n    | (Node vL aLL aLR) => (Node v (delete_leftmost aL) aR)\n  end\nend.\n\nFixpoint \ndelete (arbre : AB) (v : Z) : AB :=\n  match arbre with\n  | Empty => Empty\n  | (Node w aL aR) =>\n    let del_1 := match aL with\n    | Empty =>\n      match aR with\n      | Empty =>\n        if Z.eq_dec w v then Empty\n        else arbre\n      | (Node vR aRL aRR) =>\n        if Z.eq_dec w v then aR\n        else (Node w Empty (delete aR v))\n    end\n    | (Node vL aLL aLR) =>\n      match aR with\n      | Empty =>\n        if Z.eq_dec w v then aL\n        else (Node w (delete aL v) Empty)\n      | (Node vR aRL aRR) =>\n        if Z.eq_dec w v then (Node (leftmost_value vR aRL) aL (delete_leftmost aR) )\n        else if Z_le_dec w v then (Node w (delete aL v) aR)\n        else (Node w aL (delete aR v))\n    end\n  end\n    in if (search del_1 v) then (delete del_1 v) else del_1\nend.\nFunctional Scheme lval_ind := Induction for leftmost_value Sort Prop.\nFunctional Scheme ldel_ind := Induction for delete_leftmost Sort Prop.\nFunctional Scheme delete_ind := Induction for delete Sort Prop.\n\nLemma limit_inherit_left : forall (v : Z) (aL aR : AB) (L R : option Z), is_ABR (Node v aL aR) L R ->\n    is_ABR aL L (Some v).\nintros.\ninversion H; assumption.\nQed.\n\nLemma delete_left : forall (vR : Z) (arbre : AB) (L R : option Z), is_ABR arbre L (Some vR) ->\n    is_ABR (delete_leftmost arbre) L R -> is_ABR (delete_leftmost arbre) L (Some vR).\nintros.\nfunctional induction (delete_leftmost arbre) using ldel_ind; intros; apply_is_ABR.\ninversion H; apply_is_ABR.\neapply limit_inherit_left.\nrewrite H5.\napply H0.\nrewrite H6.\neapply limit_inherit_left.\napply H0.\ninversion H.\neapply both_upper.\napply H8.\neapply combine.\neapply both_upper.\napply H9.\neapply left_loosen.\neapply both_lower.\napply H9.\nomega.\nomega.\nQed.\n\nLemma left_delete_is_ABR : forall (arbre : AB) (L R : option Z), is_ABR arbre L R ->\n    is_ABR (delete_leftmost arbre) L R.\nintros.\nfunctional induction (delete_leftmost arbre) using ldel_ind; intros; apply_is_ABR.\ninversion H; apply_is_ABR.\neapply delete_left.\napply H5.\nrewrite H2.\napply IHa.\nrewrite <- H2.\nrewrite <- H4.\neapply both_option_reduce.\napply H5.\neapply delete_left.\nassumption.\nrewrite H4.\napply IHa.\nrewrite <- H4.\nrewrite <- H5.\neapply both_lower.\napply H6.\neapply delete_left.\nassumption.\nrewrite H4.\napply IHa.\nrewrite <- H4.\nrewrite <- H5.\neapply right_loosen.\napply H6.\nassumption.\neapply delete_left.\nassumption.\nrewrite H5.\napply IHa.\nrewrite <- H5.\nrewrite <- H6.\napply combine.\neapply right_loosen.\neapply both_upper.\napply H7.\nassumption.\neapply both_lower.\napply H7.\nomega.\ninversion H.\neapply both_option_reduce.\napply H6.\neapply left_loosen.\napply H7.\nomega.\neapply both_upper.\napply H7.\napply combine.\neapply both_upper.\napply H8.\neapply left_loosen.\neapply both_lower.\napply H8.\nomega.\nomega.\nQed.\n\nLemma leftmost_within_left : forall (v vL: Z) (aL aR : AB) (R : option Z), is_ABR (Node v aL aR) (Some vL) R ->\n    vL < leftmost_value v aL .\nintros.\nfunctional induction (leftmost_value v aL) using lval_ind; intros.\napply IHz.\ninversion H.\napply_is_ABR.\ninversion H6.\nassumption.\ninversion H6.\nassumption.\neapply left_loosen.\napply H7.\ninversion H6.\nassumption.\napply_is_ABR.\ninversion H7.\nassumption.\ninversion H7.\nomega.\ninversion H7.\nassumption.\napply combine.\neapply both_upper.\napply H8.\neapply left_loosen.\neapply both_lower.\napply H8.\ninversion H7.\nassumption.\ninversion H7.\nomega.\ninversion H.\ninversion H6.\nomega.\ninversion H7.\nomega.\nQed.\n\nLemma limits_inequality : forall (v vL vR : Z) (aL aR : AB), is_ABR (Node v aL aR) (Some vL) (Some vR) -> vR > vL.\nintros.\ninversion H.\ninversion H7.\ninversion H8.\nomega.\nomega.\nomega.\nQed.\n\nLemma leftmost_within_right : forall (v vR: Z) (aL aR : AB) (L : option Z), is_ABR (Node v aL aR) L (Some vR) ->\n    vR >= leftmost_value v aL .\nintros.\nfunctional induction (leftmost_value v aL) using lval_ind; intros.\napply IHz.\ninversion H.\ninversion H6.\napply_is_ABR.\napply combine.\neapply both_upper.\napply H7.\neapply left_loosen.\neapply both_lower.\napply H7.\nomega.\nomega.\ninversion H7.\napply_is_ABR.\napply combine.\neapply both_upper.\napply H8.\neapply left_loosen.\neapply both_lower.\napply H8.\nomega.\nomega.\ninversion H.\nomega.\nomega.\nQed.\n\nLemma delete_is_ABR : forall (arbre : AB) (v : Z), is_ABR arbre None None ->\n    is_ABR (delete arbre v) None None.\nintros.\nfunctional induction (delete arbre v) using delete_ind; intros; apply_is_ABR.\napply Z.lt_le_incl.\neapply leftmost_within_left.\ninversion H.\ninversion H2.\neapply left_loosen.\napply H4.\nomega.\ninversion H.\ninversion H2.\nauto.\ninversion H.\ninversion H2.\napply combine.\neapply right_loosen.\neapply both_upper.\napply H11.\napply Z.lt_le_incl.\neapply leftmost_within_left.\napply H4.\neapply both_lower.\napply H11.\napply Z.lt_le_incl.\neapply leftmost_within_left.\neapply left_loosen.\napply H4.\nomega.\ninversion H.\neapply left_delete_is_ABR.\napply_is_ABR.\n\nLemma delete_left_is_ABR : \n\n\nHypotheses:\nH : is_ABR (Node w (Node _x _x0 _x1) (Node vR aRL _x2)) None None\ne2 : Z.eq_dec w w = left eq_refl\nv : Z\naL, aR : AB\nH2 : is_ABR (Node _x _x0 _x1) None (Some w)\nH4 : is_ABR (Node vR aRL _x2) (Some w) None\nH0 : v = w\nH1 : aL = Node _x _x0 _x1\nH3 : aR = Node vR aRL _x2\n\n\nGoal:\nis_ABR (delete_leftmost (Node vR aRL _x2)) (Some (leftmost_value vR aRL)) None\n\n\nLemma left_swap : forall (v v1 v2 : Z) (arbre : AB) (L R : option Z), is_ABR arbre L R ->\n    v2 < (leftmost_value v1 arbre) -> v2 < v1 -> v < v1 -> v < (leftmost_value v2 arbre).\nintros.\nfunctional induction (leftmost_value v2 arbre) using lval_ind; intros.\napply IHz.\ninversion H.\neapply both_option_reduce.\napply H8.\neapply both_lower.\napply H9.\neapply right_loosen.\napply H9.\nassumption.\neapply combine.\neapply right_loosen.\neapply both_upper.\napply H10.\nassumption.\neapply both_lower.\napply H10.\nomega.\n\n\n\n\n\n\n\n", "meta": {"author": "thomasbernardi", "repo": "Formal-Methods-2018", "sha": "ea79b0012012b5e1eff32e6a548e67da26cb3b50", "save_path": "github-repos/coq/thomasbernardi-Formal-Methods-2018", "path": "github-repos/coq/thomasbernardi-Formal-Methods-2018/Formal-Methods-2018-ea79b0012012b5e1eff32e6a548e67da26cb3b50/projet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7336319242409457}}
{"text": "(** * IndPrinciples: Induction Principles *)\n\n(** With the Curry-Howard correspondence and its realization in Coq in\n    mind, we can now take a deeper look at induction principles. *)\n\nRequire Export ProofObjects.\n\n(* ################################################################# *)\n(** * Basics *)\n\n(** Every time we declare a new [Inductive] datatype, Coq\n    automatically generates an _induction principle_ for this type.\n    This induction principle is a theorem like any other: If [t] is\n    defined inductively, the corresponding induction principle is\n    called [t_ind].  Here is the one for natural numbers: *)\n\nCheck nat_ind.\n(*  ===> nat_ind :\n           forall P : nat -> Prop,\n              P 0  ->\n              (forall n : nat, P n -> P (S n))  ->\n              forall n : nat, P n  *)\n\n(** The [induction] tactic is a straightforward wrapper that, at its\n    core, simply performs [apply t_ind].  To see this more clearly,\n    let's experiment with directly using [apply nat_ind], instead of\n    the [induction] tactic, to carry out some proofs.  Here, for\n    example, is an alternate proof of a theorem that we saw in the\n    [Basics] chapter. *)\n\nTheorem mult_0_r' : forall n:nat,\n  n * 0 = 0.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *) simpl. intros n' IHn'. rewrite -> IHn'.\n    reflexivity.  Qed.\n\n(** This proof is basically the same as the earlier one, but a\n    few minor differences are worth noting.\n\n    First, in the induction step of the proof (the [\"S\"] case), we\n    have to do a little bookkeeping manually (the [intros]) that\n    [induction] does automatically.\n\n    Second, we do not introduce [n] into the context before applying\n    [nat_ind] -- the conclusion of [nat_ind] is a quantified formula,\n    and [apply] needs this conclusion to exactly match the shape of\n    the goal state, including the quantifier.  By contrast, the\n    [induction] tactic works either with a variable in the context or\n    a quantified variable in the goal.\n\n    These conveniences make [induction] nicer to use in practice than\n    applying induction principles like [nat_ind] directly.  But it is\n    important to realize that, modulo these bits of bookkeeping,\n    applying [nat_ind] is what we are really doing. *)\n\n(** **** Exercise: 2 stars, optional (plus_one_r')  *)\n(** Complete this proof without using the [induction] tactic. *)\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Coq generates induction principles for every datatype defined with\n    [Inductive], including those that aren't recursive.  Although of\n    course we don't need induction to prove properties of\n    non-recursive datatypes, the idea of an induction principle still\n    makes sense for them: it gives a way to prove that a property\n    holds for all values of the type.\n\n    These generated principles follow a similar pattern. If we define\n    a type [t] with constructors [c1] ... [cn], Coq generates a\n    theorem with this shape:\n\n    t_ind : forall P : t -> Prop,\n              ... case for c1 ... ->\n              ... case for c2 ... -> ...\n              ... case for cn ... ->\n              forall n : t, P n\n\n    The specific shape of each case depends on the arguments to the\n    corresponding constructor.  Before trying to write down a general\n    rule, let's look at some more examples. First, an example where\n    the constructors take no arguments: *)\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind.\n(* ===> yesno_ind : forall P : yesno -> Prop,\n                      P yes  ->\n                      P no  ->\n                      forall y : yesno, P y *)\n\n(** **** Exercise: 1 star, optional (rgb)  *)\n(** Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\nCheck rgb_ind.\n(** [] *)\n\n(** Here's another example, this time with one of the constructors\n    taking some arguments. *)\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n(* ===> (modulo a little variable renaming)\n   natlist_ind :\n      forall P : natlist -> Prop,\n         P nnil  ->\n         (forall (n : nat) (l : natlist),\n            P l -> P (ncons n l)) ->\n         forall n : natlist, P n *)\n\n(** **** Exercise: 1 star, optional (natlist1)  *)\n(** Suppose we had written the above definition a little\n   differently: *)\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\n\n(** Now what will the induction principle look like? *)\n(** [] *)\n\n(** From these examples, we can extract this general rule:\n\n    - The type declaration gives several constructors; each\n      corresponds to one clause of the induction principle.\n    - Each constructor [c] takes argument types [a1] ... [an].\n    - Each [ai] can be either [t] (the datatype we are defining) or\n      some other type [s].\n    - The corresponding case of the induction principle says:\n\n        - \"For all values [x1]...[xn] of types [a1]...[an], if [P]\n          holds for each of the inductive arguments (each [xi] of type\n          [t]), then [P] holds for [c x1 ... xn]\".\n*)\n\n(** **** Exercise: 1 star, optional (byntree_ind)  *)\n(** Write out the induction principle that Coq will generate for the\n    following datatype.  (Again, write down your answer on paper or\n    type it into a comment, and then compare it with what Coq\n    prints.) *)\n\nInductive byntree : Type :=\n | bempty : byntree\n | bleaf  : yesno -> byntree\n | nbranch : yesno -> byntree -> byntree -> byntree.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (ex_set)  *)\n(** Here is an induction principle for an inductively defined\n    set.\n\n      ExSet_ind :\n         forall P : ExSet -> Prop,\n             (forall b : bool, P (con1 b)) ->\n             (forall (n : nat) (e : ExSet), P e -> P (con2 n e)) ->\n             forall e : ExSet, P e\n\n    Give an [Inductive] definition of [ExSet]: *)\n\nInductive ExSet : Type :=\n  (* FILL IN HERE *)\n.\n(** [] *)\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** Next, what about polymorphic datatypes?\n\n    The inductive definition of polymorphic lists\n\n      Inductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\n\n    is very similar to that of [natlist].  The main difference is\n    that, here, the whole definition is _parameterized_ on a set [X]:\n    that is, we are defining a _family_ of inductive types [list X],\n    one for each [X].  (Note that, wherever [list] appears in the body\n    of the declaration, it is always applied to the parameter [X].)\n    The induction principle is likewise parameterized on [X]:\n\n      list_ind :\n        forall (X : Type) (P : list X -> Prop),\n           P [] ->\n           (forall (x : X) (l : list X), P l -> P (x :: l)) ->\n           forall l : list X, P l\n\n    Note that the _whole_ induction principle is parameterized on\n    [X].  That is, [list_ind] can be thought of as a polymorphic\n    function that, when applied to a type [X], gives us back an\n    induction principle specialized to the type [list X]. *)\n\n(** **** Exercise: 1 star, optional (tree)  *)\n(** Write out the induction principle that Coq will generate for\n   the following datatype.  Compare your answer with what Coq\n   prints. *)\n\nInductive tree (X:Type) : Type :=\n  | leaf : X -> tree X\n  | node : tree X -> tree X -> tree X.\nCheck tree_ind.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (mytype)  *)\n(** Find an inductive definition that gives rise to the\n    following induction principle:\n\n      mytype_ind :\n        forall (X : Type) (P : mytype X -> Prop),\n            (forall x : X, P (constr1 X x)) ->\n            (forall n : nat, P (constr2 X n)) ->\n            (forall m : mytype X, P m ->\n               forall n : nat, P (constr3 X m n)) ->\n            forall m : mytype X, P m\n*) \n(** [] *)\n\n(** **** Exercise: 1 star, optional (foo)  *)\n(** Find an inductive definition that gives rise to the\n    following induction principle:\n\n      foo_ind :\n        forall (X Y : Type) (P : foo X Y -> Prop),\n             (forall x : X, P (bar X Y x)) ->\n             (forall y : Y, P (baz X Y y)) ->\n             (forall f1 : nat -> foo X Y,\n               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n             forall f2 : foo X Y, P f2\n*) \n(** [] *)\n\n(** **** Exercise: 1 star, optional (foo')  *)\n(** Consider the following inductive definition: *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 : list X -> foo' X -> foo' X\n  | C2 : foo' X.\n\n(** What induction principle will Coq generate for [foo']?  Fill\n   in the blanks, then check your answer with Coq.)\n\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    _______________________ ->\n                    _______________________   ) ->\n             ___________________________________________ ->\n             forall f : foo' X, ________________________\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?\n\n    The induction principle for numbers\n\n       forall P : nat -> Prop,\n            P 0  ->\n            (forall n : nat, P n -> P (S n))  ->\n            forall n : nat, P n\n\n   is a generic statement that holds for all propositions\n   [P] (or rather, strictly speaking, for all families of\n   propositions [P] indexed by a number [n]).  Each time we\n   use this principle, we are choosing [P] to be a particular\n   expression of type [nat->Prop].\n\n   We can make proofs by induction more explicit by giving\n   this expression a name.  For example, instead of stating\n   the theorem [mult_0_r] as \"[forall n, n * 0 = 0],\" we can\n   write it as \"[forall n, P_m0r n]\", where [P_m0r] is defined\n   as... *)\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\n\n(** ... or equivalently: *)\n\nDefinition P_m0r' : nat->Prop :=\n  fun n => n * 0 = 0.\n\n(** Now it is easier to see where [P_m0r] appears in the proof. *)\n\nTheorem mult_0_r'' : forall n:nat,\n  P_m0r n.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    (* Note the proof state at this point! *)\n    intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n(** This extra naming step isn't something that we do in\n    normal proofs, but it is useful to do it explicitly for an example\n    or two, because it allows us to see exactly what the induction\n    hypothesis is.  If we prove [forall n, P_m0r n] by induction on\n    [n] (using either [induction] or [apply nat_ind]), we see that the\n    first subgoal requires us to prove [P_m0r 0] (\"[P] holds for\n    zero\"), while the second subgoal requires us to prove [forall n',\n    P_m0r n' -> P_m0r n' (S n')] (that is \"[P] holds of [S n'] if it\n    holds of [n']\" or, more elegantly, \"[P] is preserved by [S]\").\n    The _induction hypothesis_ is the premise of this latter\n    implication -- the assumption that [P] holds of [n'], which we are\n    allowed to use in proving that [P] holds for [S n']. *)\n\n(* ################################################################# *)\n(** * More on the [induction] Tactic *)\n\n(** The [induction] tactic actually does even more low-level\n    bookkeeping for us than we discussed above.\n\n    Recall the informal statement of the induction principle for\n    natural numbers:\n      - If [P n] is some proposition involving a natural number n, and\n        we want to show that P holds for _all_ numbers n, we can\n        reason like this:\n          - show that [P O] holds\n          - show that, if [P n'] holds, then so does [P (S n')]\n          - conclude that [P n] holds for all n.\n    So, when we begin a proof with [intros n] and then [induction n],\n    we are first telling Coq to consider a _particular_ [n] (by\n    introducing it into the context) and then telling it to prove\n    something about _all_ numbers (by using induction).\n\n    What Coq actually does in this situation, internally, is to\n    \"re-generalize\" the variable we perform induction on.  For\n    example, in our original proof that [plus] is associative... *)\n\nTheorem plus_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  (* ...we first introduce all 3 variables into the context,\n     which amounts to saying \"Consider an arbitrary [n], [m], and\n     [p]...\" *)\n  intros n m p.\n  (* ...We now use the [induction] tactic to prove [P n] (that\n     is, [n + (m + p) = (n + m) + p]) for _all_ [n],\n     and hence also for the particular [n] that is in the context\n     at the moment. *)\n  induction n as [| n'].\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    (* In the second subgoal generated by [induction] -- the\n       \"inductive step\" -- we must prove that [P n'] implies\n       [P (S n')] for all [n'].  The [induction] tactic\n       automatically introduces [n'] and [P n'] into the context\n       for us, leaving just [P (S n')] as the goal. *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** It also works to apply [induction] to a variable that is\n    quantified in the goal. *)\n\nTheorem plus_comm' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [| n'].\n  - (* n = O *) intros m. rewrite <- plus_n_O. reflexivity.\n  - (* n = S n' *) intros m. simpl. rewrite -> IHn'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** Note that [induction n] leaves [m] still bound in the goal --\n    i.e., what we are proving inductively is a statement beginning\n    with [forall m].\n\n    If we do [induction] on a variable that is quantified in the goal\n    _after_ some other quantifiers, the [induction] tactic will\n    automatically introduce the variables bound by these quantifiers\n    into the context. *)\n\nTheorem plus_comm'' : forall n m : nat,\n  n + m = m + n.\nProof.\n  (* Let's do induction on [m] this time, instead of [n]... *)\n  induction m as [| m'].\n  - (* m = O *) simpl. rewrite <- plus_n_O. reflexivity.\n  - (* m = S m' *) simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, optional (plus_explicit_prop)  *)\n(** Rewrite both [plus_assoc'] and [plus_comm'] and their proofs in\n    the same style as [mult_0_r''] above -- that is, for each theorem,\n    give an explicit [Definition] of the proposition being proved by\n    induction, and state the theorem and proof in terms of this\n    defined proposition.  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Induction Principles in [Prop] *)\n\n(** Earlier, we looked in detail at the induction principles that Coq\n    generates for inductively defined _sets_.  The induction\n    principles for inductively defined _propositions_ like [ev] are a\n    tiny bit more complicated.  As with all induction principles, we\n    want to use the induction principle on [ev] to prove things by\n    inductively considering the possible shapes that something in [ev]\n    can have.  Intuitively speaking, however, what we want to prove\n    are not statements about _evidence_ but statements about\n    _numbers_: accordingly, we want an induction principle that lets\n    us prove properties of numbers by induction on evidence.\n\n    For example, from what we've said so far, you might expect the\n    inductive definition of [ev]...\n\n      Inductive ev : nat -> Prop :=\n      | ev_0 : ev 0\n      | ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\n    ...to give rise to an induction principle that looks like this...\n\n    ev_ind_max : forall P : (forall n : nat, ev n -> Prop),\n         P O ev_0 ->\n         (forall (m : nat) (E : ev m),\n            P m E ->\n            P (S (S m)) (ev_SS m E)) ->\n         forall (n : nat) (E : ev n),\n         P n E\n\n     ... because:\n\n     - Since [ev] is indexed by a number [n] (every [ev] object [E] is\n       a piece of evidence that some particular number [n] is even),\n       the proposition [P] is parameterized by both [n] and [E] --\n       that is, the induction principle can be used to prove\n       assertions involving both an even number and the evidence that\n       it is even.\n\n     - Since there are two ways of giving evidence of evenness ([ev]\n       has two constructors), applying the induction principle\n       generates two subgoals:\n\n         - We must prove that [P] holds for [O] and [ev_0].\n\n         - We must prove that, whenever [n] is an even number and [E]\n           is an evidence of its evenness, if [P] holds of [n] and\n           [E], then it also holds of [S (S n)] and [ev_SS n E].\n\n     - If these subgoals can be proved, then the induction principle\n       tells us that [P] is true for _all_ even numbers [n] and\n       evidence [E] of their evenness.\n\n    This is more flexibility than we normally need or want: it is\n    giving us a way to prove logical assertions where the assertion\n    involves properties of some piece of _evidence_ of evenness, while\n    all we really care about is proving properties of _numbers_ that\n    are even -- we are interested in assertions about numbers, not\n    about evidence.  It would therefore be more convenient to have an\n    induction principle for proving propositions [P] that are\n    parameterized just by [n] and whose conclusion establishes [P] for\n    all even numbers [n]:\n\n       forall P : nat -> Prop,\n       ... ->\n       forall n : nat,\n       even n -> P n\n\n    For this reason, Coq actually generates the following simplified\n    induction principle for [ev]: *)\n\nCheck ev_ind.\n(* ===> ev_ind\n        : forall P : nat -> Prop,\n          P 0 ->\n          (forall n : nat, ev n -> P n -> P (S (S n))) ->\n          forall n : nat,\n          ev n -> P n *)\n\n(** In particular, Coq has dropped the evidence term [E] as a\n    parameter of the the proposition [P]. *)\n\n(** In English, [ev_ind] says:\n\n    - Suppose, [P] is a property of natural numbers (that is, [P n] is\n      a [Prop] for every [n]).  To show that [P n] holds whenever [n]\n      is even, it suffices to show:\n\n      - [P] holds for [0],\n\n      - for any [n], if [n] is even and [P] holds for [n], then [P]\n        holds for [S (S n)]. *)\n\n(** As expected, we can apply [ev_ind] directly instead of using\n    [induction]. *)\n\nTheorem ev_ev' : forall n, ev n -> ev' n.\nProof.\n  apply ev_ind.\n  - (* ev_0 *)\n    apply ev'_0.\n  - (* ev_SS *)\n    intros m Hm IH.\n    apply (ev'_sum 2 m).\n    + apply ev'_2.\n    + apply IH.\nQed.\n\n(** The precise form of an [Inductive] definition can affect the\n    induction principle Coq generates.\n\n    For example, in chapter [IndProp], we defined [<=] as: *)\n\n(* Inductive 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\n(** This definition can be streamlined a little by observing that the\n    left-hand argument [n] is the same everywhere in the definition,\n    so we can actually make it a \"general parameter\" to the whole\n    definition, rather than an argument to each constructor. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proofs by Induction *)\n\n(** Question: What is the relation between a formal proof of a\n    proposition [P] and an informal proof of the same proposition [P]?\n\n    Answer: The latter should _teach_ the reader how to produce the\n    former.\n\n    Question: How much detail is needed??\n\n    Unfortunately, there is no single right answer; rather, there is a\n    range of choices.\n\n    At one end of the spectrum, we can essentially give the reader the\n    whole formal proof (i.e., the \"informal\" proof will amount to just\n    transcribing the formal one into words).  This may give the reader\n    the ability to reproduce the formal one for themselves, but it\n    probably doesn't _teach_ them anything much.\n\n   At the other end of the spectrum, we can say \"The theorem is true\n   and you can figure out why for yourself if you think about it hard\n   enough.\"  This is also not a good teaching strategy, because often\n   writing the proof requires one or more significant insights into\n   the thing we're proving, and most readers will give up before they\n   rediscover all the same insights as we did.\n\n   In the middle is the golden mean -- a proof that includes all of\n   the essential insights (saving the reader the hard work that we\n   went through to find the proof in the first place) plus high-level\n   suggestions for the more routine parts to save the reader from\n   spending too much time reconstructing these (e.g., what the IH says\n   and what must be shown in each case of an inductive proof), but not\n   so much detail that the main ideas are obscured.\n\n   Since we've spent much of this chapter looking \"under the hood\" at\n   formal proofs by induction, now is a good moment to talk a little\n   about _informal_ proofs by induction.\n\n   In the real world of mathematical communication, written proofs\n   range from extremely longwinded and pedantic to extremely brief and\n   telegraphic.  Although the ideal is somewhere in between, while one\n   is getting used to the style it is better to start out at the\n   pedantic end.  Also, during the learning phase, it is probably\n   helpful to have a clear standard to compare against.  With this in\n   mind, we offer two templates -- one for proofs by induction over\n   _data_ (i.e., where the thing we're doing induction on lives in\n   [Type]) and one for proofs by induction over _evidence_ (i.e.,\n   where the inductively defined thing lives in [Prop]). *)\n\n(* ================================================================= *)\n(** ** Induction Over an Inductively Defined Set *)\n\n(** _Template_:\n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_:\n\n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if [length [] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of [index].\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n\n            length l = length (x::l') = S (length l'),\n\n          it suffices to show that\n\n            index (S (length l')) l' = None.\n\n          But this follows directly from the induction hypothesis,\n          picking [n'] to be [length l'].  [] *)\n\n(* ================================================================= *)\n(** ** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_.\n\n    _Template_:\n\n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n\n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n(** $Date: 2016-07-14 17:02:35 -0400 (Thu, 14 Jul 2016) $ *)\n", "meta": {"author": "coqoon", "repo": "Software-Foundations", "sha": "a327b63aa8ff8543ae2cedee7a5960da05bbfaa7", "save_path": "github-repos/coq/coqoon-Software-Foundations", "path": "github-repos/coq/coqoon-Software-Foundations/Software-Foundations-a327b63aa8ff8543ae2cedee7a5960da05bbfaa7/Software Foundations/src/SF/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.8947894632969137, "lm_q1q2_score": 0.7336319101271083}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import Lia.\n\nFixpoint x(n:nat) : nat :=\n match n with\n |0 => 0\n |S k => match k with\n         |0 => 1 (*n = 1*)\n         |1 => 1 (*n = 2*)\n         |S j => (x k) + 2 * (x j)\n         end\n end.\n\nLemma ch3div3_caseSS : forall j:nat, x (S (S (S j))) = (x (S (S j))) + (x (S j)) + (x (S j)).\nintros.\nunfold x.\nprogress fold x.\nunfold \"*\".\nremember (match j with\n| 0 => 1\n| S _ =>\n    match j with\n    | S (S _ as j0) => x j + (x j0 + (x j0 + 0))\n    | _ => 1\n    end + (x j + (x j + 0))\nend ) as a.\nremember (match j with\n | S (S _ as j0) => x j + (x j0 + (x j0 + 0))\n | _ => 1\n end) as b.\nrewrite Nat.add_0_r.\nrewrite Nat.add_assoc.\neasy.\nDefined.\n\nLemma ch3div3_lemma : forall n:nat, {a : nat & 3 * a = (x (3 * n))}.\nintros.\ndestruct n.\nexists 0; easy.\ndestruct n.\nexists 1; easy.\ninduction n.\nexists 7; easy.\ndestruct IHn as [a e].\nsimpl in *.\nSearch Nat.add.\nrepeat (try rewrite Nat.add_0_r in *;\n        try rewrite plus_Sn_m in *;\n        try rewrite <- plus_n_Sm in *).\nrepeat rewrite Nat.add_assoc in *.\nremember (S (n + n + n)) as j.\nprogress repeat rewrite (ch3div3_caseSS) in *.\nremember (x (S j)) as C.\nremember (x (S (S j))) as D.\nexists (10 * C + 11 * D + 2 * a).\nsimpl.\nrepeat rewrite Nat.add_assoc in *.\nrepeat (try rewrite Nat.add_0_r).\nrepeat rewrite (Nat.add_comm _ a).\nprogress repeat rewrite (Nat.add_assoc).\nprogress rewrite e.\nprogress repeat rewrite <- (Nat.add_assoc).\nprogress repeat apply Nat.add_cancel_l.\nprogress repeat rewrite (Nat.add_assoc).\nprogress rewrite e.\nprogress repeat rewrite <- (Nat.add_assoc).\nprogress repeat apply Nat.add_cancel_l.\nprogress repeat rewrite (Nat.add_assoc).\nprogress repeat apply Nat.add_cancel_r.\nprogress repeat rewrite <- (Nat.add_assoc).\nprogress repeat rewrite (Nat.add_comm C).\nprogress repeat rewrite <- (Nat.add_assoc).\nprogress repeat apply Nat.add_cancel_l.\ntrivial.\nDefined.\n\nTheorem ch3div3_1 : forall n:nat, {a : nat & 3 * a = n} -> {a : nat & 3 * a = (x n)}.\nintros.\ndestruct H as [a ?e].\nrewrite <- e.\ndestruct (ch3div3_lemma a) as [b ?e].\nexists b.\napply e0.\nDefined.\n\nTheorem ch3div3_2 : forall n:nat, {a : nat & 3 * a = (x n)} -> {a : nat & 3 * a = n}.\n\n", "meta": {"author": "bowtochris", "repo": "CoqStuff", "sha": "80ffef00b18a23b85f66fcb5b198d2730a49a362", "save_path": "github-repos/coq/bowtochris-CoqStuff", "path": "github-repos/coq/bowtochris-CoqStuff/CoqStuff-80ffef00b18a23b85f66fcb5b198d2730a49a362/divby3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7336319101271082}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type :=   Zero : natural | Succ : natural -> natural .\n\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint qmult (qmult_arg0 : natural) (qmult_arg1 : natural) (qmult_arg2 : natural) : natural\n           := match qmult_arg0, qmult_arg1, qmult_arg2 with\n              | Zero, n, m => m\n              | Succ n, m, p => qmult n m (plus p m)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\n   intros.\n   induction x.\n   - rewrite plus_zero. reflexivity.\n   - simpl. rewrite plus_succ. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_qmult : forall (x y z a : natural), plus (qmult x y z) a = qmult x y (plus z a).\nProof.\n   intro.\n   induction x.\n   - reflexivity.\n   - intros. simpl. rewrite IHx. rewrite plus_assoc. rewrite (plus_commut y a). \nlfind.  reflexivity. \nAdmitted.\n\nTheorem mult_eq_qmult : forall (x : natural) (y : natural), eq (mult x y) (qmult x y Zero).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. rewrite plus_qmult. reflexivity.\nQed.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal34_plus_qmult_67_plus_assoc/goal34.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.733631910127108}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) (lf2 : natural)\n  : natural := mult (Succ y) (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj164_coqofml_BQxJWb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.733534586168625}}
{"text": "Set Printing Universes.\nSet Universe Polymorphism.\n\n(*The inductive type of formulae. Note that if All or Ex quantifies over a type in a universe, then the resulting form is in a strictly higher universe. Note also that the definition is universe-polymorphic, thus the All and Ex constructors of a form at a higher level can quantify over a form at a lower level*)\nInductive form :=\n| Tr : form (*true/⊤*)\n| Fa : form (*absurd*)\n| And : form -> form -> form (*conjunction*)\n| Or : form -> form -> form (*disjunction*)\n| Impl : form -> form -> form (*implication*)\n| All : forall {A : Type}, (A -> form) -> form (*Universal quantifier*)\n| Ex : forall {A : Type}, (A -> form) -> form (*Existential quantifier*)\n| Atom : Prop -> form. (*Atomic propositions*)\n\nNotation \"f ⇒ g\" := (Impl f g)\n                     (at level 99, right associativity).\n\n\n(*---------------------------------*)\n(*Contexts --- are represented by terms L:form → Prop*)\n\n\n(*Empty context*)\nDefinition Ø (f:form) := False.\n\n\n(*Context extension*)\nDefinition L_ext : (form -> Prop) -> form -> form -> Prop :=\n  fun L f g => (L g) \\/ (g = f).\nNotation \"L ⋯ f\" := (L_ext L f) (at level 99).\n\n\n(*One might be tempted instead to make the following definition of \"removing a hypothesis from a context\". However, since contexts are not interpreted as lists but as (sub)sets/classes of formulae specified/separated by a predicate, and not as lists or multisets, the only sense to removing a formulae from a context is that of discarding *all* occurrences of the formula from the context. This is unwise --- for instance, it seems to me as though defining inference rules so that weakening is admissible becomes tricky, especially in the case of the introduction of the implication.\n\nDefinition L_rm : (form -> Prop) -> form -> form -> Prop :=\n  fun L A B => (L B) /\\ (~ B = A).*)\n\n\n\n\n(*--------------------------------*)\n(*Derivations/Judgements*)\n\n(*Question 1.1.1*)\n(*The inductive family of derivations, indexed over contexts and formulae, and valued in Prop. We choose to place ourselves in Natural Deduction.*)\nInductive deriv : (form -> Prop) -> form -> Prop :=\n| ax     : forall (L:_ -> Prop) f,\n             L f -> deriv L f\n| Tr_i   : forall L, deriv L Tr\n| Fa_e   : forall L f, deriv L Fa -> deriv L f\n| imp_i  : forall L f g,\n             deriv (L⋯f) g -> deriv L (Impl f g)\n| imp_e  : forall L f g,\n             deriv L (Impl f g) -> deriv L f -> deriv L g\n| and_i  : forall L f g,\n             deriv L f -> deriv L g -> deriv L (And f g)\n| and_e1 : forall L f g,\n             deriv L (And f g) -> deriv L f\n| and_e2 : forall L f g,\n             deriv L (And f g) -> deriv L g\n| or_i1  : forall L f g,\n             deriv L f -> deriv L (Or f g)\n| or_i2  : forall L f g,\n             deriv L g -> deriv L (Or f g)\n| or_e   : forall L f g h,\n             deriv L (Or f g) -> deriv (L⋯f) h -> deriv (L⋯g) h -> deriv L h\n| ex_i   : forall L {A:Type} (P:A -> form) t,\n             deriv L (P t) -> deriv L (Ex P)\n| ex_e   : forall L {A:Type} (P:A -> form) f,\n             (forall t, deriv (L⋯P t) f) -> (deriv L (Ex P)) -> deriv L f\n(*Note the side condition that the standard formulaion of the rule above requires, namely that neither L nor f contain t as a free variable. This is guaranteed by explicitly binding L and f — the forall in the Coq lambda-term/the meta-term — above the binder for t, thus t is neither free in nor can be captured by any substitution for L or f. Note also that this meta-binding inside the scope of L and f is *precisely* what we mean when we say that the term-variable in the auxiliary premiss of the ∃-elim rule is free neither in the rest of the context nor in the conclusion.*)\n\n| all_i  : forall L {A:Type} (P:A -> form),\n             (forall t, deriv L (P t)) -> deriv L (All P)\n(*same remark for the side condition in the rule above*)\n                                                \n| all_e  : forall L {A:Type} (P:A -> form),\n             deriv L (All P) -> forall t, deriv L (P t).\nNotation \"L ⊢ f\" := (deriv L f) (at level 99).\n\n\n\n(* ---------------------------------------------  *)\n(*The admissible inference rules*)\n\n\n(*Weakening*)\nLemma deriv_weakening_strong (L : form -> Prop) f {H:L ⊢ f} :\n  forall L':_-> Prop,\n    (forall f, L f -> L' f) ->\n    L' ⊢ f.\nProof.\n  induction H; intros.\n  - apply ax, H0, H.\n  - apply Tr_i.\n  - apply Fa_e, IHderiv, H0. \n  - apply imp_i, IHderiv. intros.\n    case H1.\n    + intro; left; apply H0. assumption.\n    + intro; right; assumption.\n  - apply (imp_e _ f g). apply IHderiv1, H1.\n    apply IHderiv2, H1.\n  - apply and_i.\n    + apply IHderiv1, H1.\n    + apply IHderiv2, H1.\n  - apply (and_e1 _ _ g), IHderiv, H0.\n  - apply (and_e2 _ f _), IHderiv, H0.\n  - apply or_i1, IHderiv, H0.\n  - apply or_i2, IHderiv, H0.\n  - apply (or_e _ f g).\n    + apply IHderiv1, H2.\n    + apply IHderiv2. intros. case H3.\n      * intro; left; apply H2; assumption.\n      * intro; right; assumption.\n    + apply IHderiv3; intros; case H3.\n      * intro; left; apply H2; assumption.\n      * intro; right; assumption.\n  - apply (ex_i _ _ t), IHderiv, H0.\n  - apply (ex_e _ P f). intro t1. apply (H0 t1).\n    intros. case H3.\n    + intro; left; apply H2; assumption.\n    + intro; right; assumption.\n    + apply IHderiv. assumption.\n  - apply all_i. intro; apply H0, H1.\n  - apply all_e, IHderiv, H0.\nDefined.\n\n\n(*Question 1.2.1*)\n(*A logically equivalent statement, but where the induction tactic does not \nproduce strong enough hypotheses for the proof to go through*)\nLemma deriv_weakening (L L' : form -> Prop) f :\n  L ⊢ f ->\n  (forall f, L f -> L' f) ->\n  L' ⊢ f.\nProof.\n  intros; apply (deriv_weakening_strong L); assumption.\nDefined.\n\n(*The usual form of the weakening rule*)\nLemma wkn (L : form -> Prop) g f :\n  L ⊢ f -> (L⋯g) ⊢ f.\nProof.\n  intro; apply (deriv_weakening L (L⋯_)).\n  - assumption.\n  - intros; left; assumption.\nDefined.\n\n\n\n\n(*Substitution/Cut/Context morphisms*)\n\n(*A statement phrased in a way to let Coq's induction tactic go through*)\nLemma deriv_substitution_strong (L : form -> Prop) f :\n  deriv L f ->\n  forall L', (forall f, L f -> deriv L' f) ->\n        deriv L' f.\nProof.\n  intros H; induction H; intros.\n  - apply H0, H.\n  - apply Tr_i.\n  - apply Fa_e, IHderiv, H0. \n  - apply imp_i, IHderiv.\n    intros. case H1.\n    + intro; apply wkn.\n      apply H0, H2. \n    + intro; apply ax; right; assumption.\n  - apply (imp_e _ f g). apply IHderiv1, H1.\n    apply IHderiv2, H1.\n  - apply and_i.\n    + apply IHderiv1, H1.\n    + apply IHderiv2, H1.\n  - apply (and_e1 _ _ g), IHderiv, H0.\n  - apply (and_e2 _ f _), IHderiv, H0.\n  - apply or_i1, IHderiv, H0.\n  - apply or_i2, IHderiv, H0.\n  - apply (or_e _ f g).\n    + apply IHderiv1, H2.\n    + apply IHderiv2; intros; case H3.\n      * intro; apply wkn, H2, H4.\n      * intro; apply ax; right; assumption.\n    + apply IHderiv3. intros; case H3.\n      * intro; apply wkn, H2, H4. \n      * intro; apply ax; right; assumption.\n  - apply (ex_i _ _ t), IHderiv, H0.\n  - apply (ex_e _ P f). intro t1; apply (H0 t1).\n    intros; case H3.\n    + intro; apply wkn, H2; assumption.\n    + intro. apply ax; right; assumption.\n    + apply IHderiv. assumption.\n  - apply all_i. intro; apply H0, H1.\n  - apply all_e, IHderiv, H0.\nDefined.\n\n\n(*Question 1.2.2*)\n(*A statement equivalent to the one above*)\nLemma deriv_substitution (L L' : form -> Prop) f :\n  deriv L f ->\n  (forall f, L f -> deriv L' f) ->\n  deriv L' f.\nProof.\n  intros.\n  apply (deriv_substitution_strong L); assumption.\nDefined.\n\n(*Fin*)\n\n\n", "meta": {"author": "huevosybacon", "repo": "mpri-272-exo1", "sha": "439b3065e6b7190836f24ed506c63c3c29c6483b", "save_path": "github-repos/coq/huevosybacon-mpri-272-exo1", "path": "github-repos/coq/huevosybacon-mpri-272-exo1/mpri-272-exo1-439b3065e6b7190836f24ed506c63c3c29c6483b/FormalSystem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.733534575000812}}
{"text": "\nRequire Import Arith.\nSection strong_induction.\n\nTheorem induction1:\n forall P : nat -> Prop,\n (forall n : nat, \n    (forall k : nat, (k < n -> P k)) -> (forall k : nat, (k <= n -> P k)))\n -> (forall n : nat, (forall k : nat, (k <= n -> P k))).\n\nProof.\n\ninduction n.\nintro.\napply H.\nintro.\nintro.\n\nunfold lt in H0.\ninversion H0.\n\napply H.\nintro.\nintro.\napply IHn.\n\nunfold lt in H0.\napply le_S_n in H0.\nassumption.\n\nQed.\n\n\nTheorem strong_induction:\n forall P : nat -> Prop,\n (forall n : nat, \n   (forall k : nat, (k < n -> P k)) -> P n)\n -> (forall n : nat, P n).\n\nProof.\n\nintro.\nintro.\n\nassert ( forall n:nat, (forall k:nat, k < n -> P k) -> \n                       (forall k:nat, k <= n -> P k) ).\nintro.\nintro.\nintro.\nintro.\n\ninversion H1.\napply H.\nassumption.\n\napply H0.\nrewrite <- H3.\nunfold lt.\napply le_n_S.\nassumption.\n\n\nassert( forall n : nat, (forall k : nat, (k <= n -> P k)) ).\n\napply induction1.\nassumption.\n\nintro.\n\nassert (forall k:nat, k <= n -> P k).\napply H1.\n\napply H2.\n\nconstructor.\n\n\nQed.\n\n\n\n\n", "meta": {"author": "Toskah", "repo": "Coq", "sha": "956df87bfc60f2ae32b80851978d211f60768de0", "save_path": "github-repos/coq/Toskah-Coq", "path": "github-repos/coq/Toskah-Coq/Coq-956df87bfc60f2ae32b80851978d211f60768de0/lab9/lab9strongInduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098192, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7335345715870732}}
{"text": "(**************************************************************************)\n(*           *                                                            *)\n(*     _     *   The Coccinelle Library / Evelyne Contejean               *)\n(*    <o>    *          CNRS-LRI-Universite Paris Sud                     *)\n(*  -/@|@\\-  *                   A3PAT Project                            *)\n(*  -@ | @-  *                                                            *)\n(*  -\\@|@/-  *      This file is distributed under the terms of the       *)\n(*    -v-    *      CeCILL-C licence                                      *)\n(*           *                                                            *)\n(**************************************************************************)\n\nSet Implicit Arguments. \n\nRequire Import Setoid.\nRequire Import Relations.\nRequire Import List.\nRequire Import Wellfounded.\nRequire Export TransClosure.\n\nLemma acc_trans :\n forall A (R : relation A) a, Acc R a -> Acc (trans_clos R) a.\nProof.\nintros A R a Acc_R_a.\ninduction Acc_R_a as [a Acc_R_a IH].\napply Acc_intro.\nintros b b_Rp_a; induction b_Rp_a.\napply IH; trivial.\napply Acc_inv with y.\napply IHb_Rp_a; trivial.\napply t_step; trivial.\nDefined.\n\nLemma wf_trans :\n  forall A (R : relation A) , well_founded R -> well_founded (trans_clos R).\nProof.\nunfold well_founded; intros A R WR.\nintro; apply acc_trans; apply WR; trivial.\nDefined.\n\n\nLemma trans_incl :\n  forall A (R1 R2 : relation A), inclusion _ R1 R2 -> inclusion _ (trans_clos R1) (trans_clos R2).\nProof.\nintros A R1 R2 R1_in_R2 a b H; induction H as [a' b' H | a' b' c' H1 H2].\napply t_step; apply R1_in_R2; trivial.\napply t_trans with b'; trivial.\napply R1_in_R2; trivial.\nQed.\n\nLemma refl_trans_incl :\n  forall A (R1 R2 : relation A), inclusion _ R1 R2 -> inclusion _ (refl_trans_clos R1) (refl_trans_clos R2).\nProof.\nintros A R1 R2 R1_in_R2 a b [a' | a' b' H].\nleft.\napply t_clos; apply trans_incl with R1; assumption.\nQed.\n\nLemma trans_incl2 :\n  forall A B (f : A -> B) (R1 : relation A) (R2 : relation B), \n  (forall a1 a2, R1 a1 a2 -> R2 (f a1) (f a2)) -> \n\tforall a1 a2, trans_clos R1 a1 a2 ->  trans_clos R2 (f a1) (f a2).\nProof.\nintros A B f R1 R2 R1_in_R2 a b H; induction H as [a' b' H | a' b' c' H1 H2].\napply t_step; apply R1_in_R2; trivial.\napply t_trans with (f b'); trivial.\napply R1_in_R2; trivial.\nQed.\n\nLemma trans_with_eq : \n  forall A (R : relation A) a1 a2, \n  trans_clos (union A (@eq _) R) a1 a2 <-> refl_trans_clos R a1 a2.\nProof.\nintros A R a1 a2; split.\nintro H; induction H as [b1 b2 H | b1 b2 b3 H1 H2]. \ndestruct H as [H | H].\nsubst b2; apply r_step; assumption.\napply t_clos; apply t_step; assumption.\ndestruct H1 as [H1 | H1].\nsubst b2; assumption.\ndestruct IHH2 as [b2 H3 | b2 b3 H3].\napply t_clos; apply t_step; assumption.\napply t_clos; apply t_trans with b2; assumption.\n\nintro H; destruct H as [a1 H | a1 a2 H].\napply t_step; left; apply refl_equal.\napply (@trans_incl _ R); trivial.\nright; assumption.\nQed.\n\nLemma acc_star : \n   forall A (R : relation A) a, Acc R a -> forall b,  refl_trans_clos  R b a -> Acc R b.\nProof.\nintros A R a Acc_a b H; destruct H as [a1 H | a1 a2 H].\nassumption.\napply Acc_incl with (trans_clos R).\nintros b1 b2 H'; apply t_step; assumption.\napply Acc_inv with a2; trivial.\napply acc_trans; trivial.\nQed.\n\nInductive compose_rel A (R1 R2 : relation A) : relation A :=\n  Comp : forall a1 a2 a3, R1 a1 a2 -> R2 a2 a3 -> compose_rel R1 R2 a1 a3.\n\nSection Compose.\nVariable A : Type.\nVariable R1 : relation A.\nVariable R2 : relation A.\n\nLemma trans_union :\n  forall a b,\n  trans_clos (union _ R1 R2) a b <-> \n  union _ (trans_clos R1) \n            (compose_rel (refl_trans_clos R1) (trans_clos (compose_rel R2 (refl_trans_clos R1)))) a b.\nProof.\nintros a b; split.\n(* 1/2 -> *)\nintro H; induction H as [x y H1 | x y z H1 Hn].\ndestruct H1 as [H1 | H1].\nleft; apply t_step; assumption.\nright; apply Comp with x.\napply r_step.\napply t_step.\napply Comp with y; trivial.\napply r_step.\ndestruct H1 as [H1 | H2]; destruct IHHn as [IHHn | IHHn].\nleft; apply t_trans with y; trivial.\nright; inversion IHHn as [x' y' z' K1 K2]; subst x' z'; clear IHHn.\napply Comp with y'.\ninversion K1 as [y1 | y1 y2 K1']; clear K1.\nsubst y1 y'; apply t_clos; apply t_step; trivial.\nsubst y1 y2; apply t_clos; apply t_trans with y; trivial.\ntrivial.\nright.\napply Comp with x.\napply r_step.\napply t_step; apply Comp with y; trivial.\napply t_clos; trivial.\nright; inversion IHHn as [x' y' z' K1 K2]; subst x' z'; clear IHHn.\napply Comp with x.\napply r_step.\napply t_trans with y'; trivial.\napply Comp with y; trivial.\n(* 1/1 <- *)\nintros [H | H].\napply trans_incl with R1; trivial.\nintros; left; trivial.\ninversion H as [x' y' z' K1 K2]; clear H; subst x' z'.\ninversion K1 as [y1 | y1 y2 K1']; clear K1.\nsubst y1 y'.\napply trans_clos_is_clos.\napply trans_incl with (compose_rel R2 (refl_trans_clos R1)); trivial.\nclear a b K2; intros a b K2.\ninversion K2 as [x' y' z' K1 K2']; clear K2; subst x' z'.\ninversion K2' as [y1 | y1 y2 K2'']; clear K2'.\nsubst y1 y'; apply t_step; right; trivial.\nsubst y1 y2.\napply t_trans with y'.\nright; trivial.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nsubst y1 y2.\napply trans_clos_is_trans with y'.\napply trans_incl with R1; trivial.\nintros; left; trivial.\napply trans_clos_is_clos.\napply trans_incl with (compose_rel R2 (refl_trans_clos R1)); trivial.\nclear a b y' K1' K2; intros a b K2.\ninversion K2 as [x' y' z' K1 K2']; clear K2; subst x' z'.\ninversion K2' as [y1 | y1 y2 K2'']; clear K2'.\nsubst y' y1.\nleft; right; trivial.\nsubst y1 y2.\nright with y'.\nright; trivial.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nQed.\n\nLemma trans_union_alt :\n  forall a b,\n  trans_clos (union _ R1 R2) a b <-> \n  union _ (trans_clos R1) \n             (compose_rel (trans_clos (compose_rel (refl_trans_clos R1) R2)) \n                                  (refl_trans_clos R1)) a b.\nProof.\nintros a b; split.\n(* 1/2 -> *)\nrewrite trans_clos_trans_clos_alt in *; intro H; induction H as [x y H1 | x y z H1 IHH1 Hn].\n(* 1/3 one step *)\ndestruct H1 as [H1 | H1].\nleft; left; assumption.\nright; apply Comp with y.\nleft; apply Comp with x; trivial.\nleft.\nleft.\n(* 1/2 several steps *)\ndestruct IHH1 as [IHH1 | IHH1]; destruct Hn as [Hn | Hn].\n(* 1/5 *)\nleft; rewrite trans_clos_trans_clos_alt in *; right with y; trivial.\n(* 1/4 *)\nright; apply Comp with z.\nleft; apply Comp with y; trivial.\nright; trivial.\nleft.\n(* 1/3 *)\ninversion IHH1 as [x' y' z' K1 K2]; subst x' z'; clear IHH1.\nright; apply Comp with y'; trivial.\ninversion K2 as [y'' | a a' K2' K2''].\nsubst y' y''.\nright; left; trivial.\nsubst a a'; right; apply trans_clos_is_trans with y; trivial.\nleft; trivial.\n(* 1/2 *)\ninversion IHH1 as [x' y' z' K1 K2]; subst x' z'; clear IHH1.\nright.\napply Comp with z.\napply trans_clos_is_trans with y'; trivial.\nleft; apply Comp with y; trivial.\nleft.\n(* 1/1 <- *)\nintros [H | H].\napply trans_incl with R1; trivial.\nintros; left; trivial.\ninversion H as [x' y' z' K1 K2]; clear H; subst x' z'.\ninversion K2 as [y1 | y1 y2 K2']; clear K2.\nsubst y1 y'.\napply trans_clos_is_clos.\napply trans_incl with (compose_rel (refl_trans_clos R1) R2); trivial.\nclear a b K1; intros a b H.\ninversion H as [x' y' z' K1 K2]; subst x' z'; clear H.\ninversion K1 as [y1 | y1 y2 K1']; clear K1.\nsubst y1 y'; apply t_step; right; trivial.\nsubst y1 y2.\napply trans_clos_is_trans with y'.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nleft; right; trivial.\nsubst y1 y2.\napply trans_clos_is_trans with y'.\napply trans_clos_is_clos.\napply trans_incl with (compose_rel (refl_trans_clos R1) R2); trivial.\nclear a b y' K1 K2'; intros a b H.\ninversion H as [x' y' z' K1 K2]; subst x' z'; clear H.\ninversion K1 as [y1 | y1 y2 K1']; clear K1.\nsubst y1 y'; apply t_step; right; trivial.\nsubst y1 y2.\napply trans_clos_is_trans with y'.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nleft; right; trivial.\napply trans_incl with R1; trivial.\nintros; left; trivial.\nQed.\n\nLemma acc_union :\n  well_founded R1 ->\n  forall a, Acc (compose_rel R2 (refl_trans_clos R1)) a <-> Acc (union _ R1 R2) a.\nProof.\nintros W1'.\nassert (W1 := wf_trans W1'); clear W1'.\nintros a; split.\nintro Acc_a; induction Acc_a as [a Acc_a' IH2].\nassert (Acc_a : Acc (compose_rel R2 (refl_trans_clos R1)) a).\napply Acc_intro; trivial.\nclear Acc_a'.\nrevert IH2 Acc_a.\npattern a; apply (well_founded_ind W1); clear a.\nintros a IH1 IH2 Acc_a.\napply Acc_intro.\nintros b [H1 | H2].\napply IH1.\napply t_step; trivial.\nintros c H2; apply IH2.\ninversion H2 as [c' d' b' H H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\napply Acc_intro; intros c H2.\napply Acc_inv with a; trivial.\ninversion H2 as [c' d' b' H H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\napply IH2.\napply Comp with a; trivial.\napply r_step.\n\nintro Acc_a; apply Acc_incl with (trans_clos (union _ R1 R2)).\nintros a1 a3 H; inversion H as [b1 b2 b3 H1 H2]; clear H; subst a1 a3.\ninversion H2 as [b | a2 a3 K2]; clear H2; subst.\nleft; right; assumption.\napply t_trans with b2.\nright; assumption.\napply trans_incl with R1; trivial.\nintros x y H; left; assumption.\napply acc_trans; assumption.\nQed.\n\nLemma acc_union_weak :\n  forall a, Acc (compose_rel R2 (refl_trans_clos R1)) a -> \n              (forall b, refl_trans_clos (compose_rel R2 (refl_trans_clos R1)) b a -> Acc R1 b) -> \n              Acc (union _ R1 R2) a.\nProof.\nintros a Acc_a H; \ninduction Acc_a as [a Acc_a' IH2].\nassert (Acc_a : Acc (compose_rel R2 (refl_trans_clos R1)) a).\napply Acc_intro; trivial.\nclear Acc_a'.\nassert (Acc1_a : Acc R1 a).\napply H; left.\nrevert IH2 H Acc_a.\ninduction Acc1_a as [a Acc1_a IH1].\nintros IH2 H Acc_a.\napply Acc_intro.\nintros b [H1 | H2].\napply IH1; trivial.\nintros c H2; apply IH2.\ninversion H2 as [c' d' b' h H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\nintros c K; inversion K; clear K; subst.\napply Acc1_a; assumption.\napply H.\nrewrite trans_clos_trans_clos_alt in H0.\ninversion H0; clear H0; subst.\nright; left.\ninversion H2; clear H2; subst.\napply Comp with a2; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; exact H1.\ninversion H3; clear H3; subst.\napply refl_trans_clos_is_trans with y; trivial.\nright; rewrite trans_clos_trans_clos_alt; assumption.\nright; left.\napply Comp with a2; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; exact H1.\napply Acc_intro; intros c K.\napply Acc_inv with a; trivial.\ninversion K; clear K; subst.\napply Comp with a2; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; exact H1.\n\napply IH2.\napply Comp with a; [assumption | left].\nintros c K; apply H.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; apply Comp with a; [assumption | left].\nQed.\n\nLemma acc_union_alt :\n  well_founded R1 ->\n  forall a, (forall b, refl_trans_clos R1 b a -> Acc (compose_rel (refl_trans_clos R1) R2) b) <-> Acc (union _ R1 R2) a.\nProof.\nintros W1'; split.\nintro Ha; apply acc_union_weak; trivial.\napply Acc_intro; intros b4 H.\ninversion H as [a4 b2 a1 H' H21]; clear H; subst.\nassert (Acc_b2 := Ha b2 H21).\nrevert a Ha b4 H' H21; induction Acc_b2 as [b2 Acc_b2 IH].\nintros a Ha b4 H' H21.\napply Acc_intro.\nintros b6 H.\ninversion H as [a6 b5 a4 H65 H54]; clear H; subst.\napply IH with b5 b4; trivial.\napply Comp with b4; trivial.\nintros b7 H7.\napply Acc_b2.\napply Comp with b4; trivial.\n\nintros Acc_a b H; apply Acc_incl with (trans_clos (union _ R1 R2)).\nclear b H; intros a1 a3 H; inversion H as [b1 b2 b3 H1 H2]; clear H; subst a1 a3.\ninversion H1 as [b | a2 a3 K1]; clear H1; subst.\nleft; right; assumption.\napply trans_clos_is_trans with b2.\napply trans_incl with R1; trivial.\nintros x y H; left; assumption.\nleft; right; assumption.\ninversion H as [a' | b' a' K]; clear H.\napply acc_trans; assumption.\nsubst; apply Acc_inv with a.\napply acc_trans; assumption.\napply trans_incl with R1; trivial.\nintros x y H; left; assumption.\nQed.\n\nLemma acc_union_alt_weak :\n  forall a, (forall b, refl_trans_clos (compose_rel R2 (refl_trans_clos R1)) b a -> Acc R1 b) ->\n               (forall b, refl_trans_clos R1 b a -> Acc (compose_rel (refl_trans_clos R1) R2) b) -> \n              Acc (union _ R1 R2) a.\nProof.\nintros a H1a H2a.\napply acc_union_weak; trivial.\nclear H1a.\napply Acc_intro; intros b4 H.\ninversion H as [a4 b2 a1 H' H21]; clear H; subst.\nassert (Acc_b2 := H2a b2 H21).\nrevert a H2a b4 H' H21; induction Acc_b2 as [b2 Acc_b2 IH].\nintros a Ha b4 H' H21.\napply Acc_intro.\nintros b6 H.\ninversion H as [a6 b5 a4 H65 H54]; clear H; subst.\napply IH with b5 b4; trivial.\napply Comp with b4; trivial.\nintros b7 H7.\napply Acc_b2.\napply Comp with b4; trivial.\nQed.\n\nLemma wf_union_alt :\n  well_founded R1 ->\n  (well_founded (compose_rel (refl_trans_clos R1) R2) <-> well_founded (union _ R1 R2)).\nProof.\nintros W1'; split.\nintro W; intro a; rewrite <- acc_union; trivial.\nassert (W1 := wf_trans W1'); clear W1'.\napply Acc_intro.\nintros b4 H.\ninversion H as [a4 b2 a1 H' H21]; clear H; subst.\nclear a H21.\nrevert b4 H'.\npattern b2; apply (well_founded_ind (wf_trans W)); clear b2.\nintros a IH b H.\napply Acc_intro; intros c K.\ninversion K as [d' c' b' H1 H2];clear K; subst.\napply IH with c'; trivial.\nleft; apply Comp with b; trivial.\n\nintros W a; apply Acc_incl with (trans_clos (union _ R1 R2)).\nintros a1 a3 H; inversion H as [b1 b2 b3 H1 H2]; clear H; subst a1 a3.\ninversion H1 as [b | a2 a3 K1]; clear H1; subst.\nleft; right; assumption.\napply trans_clos_is_trans with b2.\napply trans_incl with R1; trivial.\nintros x y H; left; assumption.\nleft; right; assumption.\napply acc_trans; apply W.\nQed.\n\nLemma acc_comp_incl :\n  forall R, (forall a, Acc R a -> Acc (union _ R1 R2) a) -> \n  forall a, Acc R a -> Acc (compose_rel (refl_trans_clos R1) R2) a.\nProof.\nintros R H a Acc_a.\napply Acc_incl with (trans_clos (union _ R1 R2)).\nclear; intros a b H.\ninversion H as [c1 c2 c3 K1 K2]; clear H; subst.\ninversion K1 as [c | b1 b2 K3 K4]; clear K1; subst.\nleft; right; assumption.\napply trans_clos_is_trans with c2.\napply trans_incl with R1; trivial.\nclear; intros a b H; left; assumption.\nleft; right; assumption.\napply acc_trans.\napply H; assumption.\nQed.\n\nEnd Compose.\n\nDefinition rest A P R := fun (a b : A) => R a b /\\ P a /\\ P b.\n\nLemma rest_union : forall A P (R1 R2 : relation A) a b, rest P (union _ R1 R2) a b <-> union _ (rest P R1) (rest P R2) a b.\nintros A P R1 R2 a b; split.\nintros [[H1 | H2] [Pa Pb]]; [left | right]; repeat split; assumption.\nintros [[H1 [Pa Pb]] | [H2 [Pa Pb]]]; repeat split; trivial.\nleft; assumption.\nright; assumption.\nQed.\n\nLemma rest_trans : \n   forall A (P : A -> Prop) (R : relation A), (forall a b, P a -> R b a -> P b) -> \n\tforall a, P a -> forall b, trans_clos (rest P R) b a <-> trans_clos R b a.\nProof.\nintros A P R Inv a Pa b; split.\napply trans_incl; intros x y [H _]; assumption.\nintro H; rewrite trans_clos_trans_clos_alt in H; rewrite trans_clos_trans_clos_alt.\ninduction H as [x y K | x y z K1 K2].\nleft; repeat split; trivial.\napply Inv with y; assumption.\nassert (Py := Inv _ _ Pa H).\nright with y.\nexact (K2 Py).\nrepeat split; assumption.\nQed.\n\nLemma acc_rest : \n  forall A (R : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R b a -> P b) -> \n  (forall a, (P a -> Acc R a) <-> Acc (rest P R) a).\nProof.\nintros A R P Inv a; split.\nintro K; apply Acc_intro; intros b [H [Wb Wa]].\napply Acc_inv with a; trivial.\napply Acc_incl with R.\nclear; intros a b [H _]; assumption.\napply K; assumption.\nrepeat split; assumption.\nintro Acc_a; induction Acc_a as [a Acc_a IH].\nintro Pa; apply Acc_intro; intros b H.\napply IH.\nrepeat split; trivial.\napply Inv with a; assumption.\napply Inv with a; assumption.\nQed.\n\nLemma wf_rest : \n  forall A (R : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R b a -> P b) -> \n  ((forall a, P a -> Acc R a) <->  well_founded (rest P R)).\nProof.\nintros A R P Inv; split.\nintros W a; rewrite <- acc_rest; trivial.\napply W.\nintros W a; rewrite acc_rest; trivial.\nQed.\n\nLemma acc_union_rest :\n  forall A (R1 R2 : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R1 b a -> P b) -> \n  (forall (a b : A), P a -> R2 b a -> P b) -> \n  (forall a, P a -> Acc R1 a) ->\n  forall a, P a -> Acc (compose_rel R2 (refl_trans_clos R1)) a -> Acc (union _ R1 R2) a.\nProof.\nintros A R1 R2 P Inv1 Inv2 W1' a Wa Acc_a.\nrewrite wf_rest in W1'.\nset (R1' := fun a b => R1 a b /\\ P a /\\ P b) in *.\nassert (W1 := wf_trans W1'); clear W1'.\nrevert Wa; induction Acc_a as [a Acc_a' IH2].\nassert (Acc_a : Acc (compose_rel R2 (refl_trans_clos R1)) a).\napply Acc_intro; trivial.\nclear Acc_a'.\nrevert IH2 Acc_a.\npattern a; apply (well_founded_ind W1); clear a.\nintros a IH1 IH2 Acc_a Wa.\napply Acc_intro.\nintros b [H1 | H2].\napply IH1.\napply t_step; repeat split; trivial.\napply Inv1 with a; trivial.\nintros c H2; apply IH2.\ninversion H2 as [c' d' b' H H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\napply Acc_intro; intros c H2.\napply Acc_inv with a; trivial.\ninversion H2 as [c' d' b' H H']; subst.\napply Comp with d'; trivial.\napply refl_trans_clos_is_trans with b; trivial.\nright; left; trivial.\napply Inv1 with a; trivial.\napply IH2.\napply Comp with a; trivial.\napply r_step.\napply Inv2 with a; trivial.\ntrivial.\nQed.\n\nLemma acc_union_rest_alt :\n  forall A (R1 R2 : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R1 b a -> P b) -> \n  (forall (a b : A), P a -> R2 b a -> P b) -> \n  (forall a, P a -> Acc R1 a) ->\n  (forall a, (forall b, refl_trans_clos R1 b a -> Acc (compose_rel (refl_trans_clos R1) R2) b) -> P a -> Acc (union _ R1 R2) a).\nProof.\nintros A R1 R2 P Inv1 Inv2 W1' a W Pa.\nassert (H : Acc (union _ (rest P R1) (rest P R2)) a).\nrewrite <- acc_union_alt.\nintros b H; apply Acc_incl with (compose_rel (refl_trans_clos R1) R2).\nclear; intros a1 a2 H; inversion H as [c1 a c2 H1 [H2 _]]; subst.\napply Comp with a; [idtac | assumption].\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\napply W.\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\nrewrite wf_rest in W1'; assumption.\nclear W; revert Pa; induction H as [a Acc_a IH].\nintro Pa; apply Acc_intro; intros a1 [H1 | H2]; apply IH.\nleft; repeat split; trivial.\napply Inv1 with a; assumption.\napply Inv1 with a; assumption.\nright; repeat split; trivial.\napply Inv2 with a; assumption.\napply Inv2 with a; assumption.\nQed.\n\nLemma acc_union_rest_alt_weak :\n  forall A (R1 R2 : relation A) (P : A -> Prop),\n  (forall (a b : A), P a -> R1 b a -> P b) -> \n  (forall (a b : A), P a -> R2 b a -> P b) -> \n  forall a, (forall b, refl_trans_clos (compose_rel R2 (refl_trans_clos R1)) b a -> Acc R1 b) ->\n               (forall b, refl_trans_clos R1 b a -> Acc (compose_rel (refl_trans_clos R1) R2) b) -> \n               P a -> Acc (union _ R1 R2) a.\nProof.\nintros A R1 R2 P Inv1 Inv2 a H1a H2a Pa.\nassert (H : Acc (union _ (rest P R1) (rest P R2)) a).\napply acc_union_alt_weak.\nintros b H; apply Acc_incl with R1.\nclear; intros a1 a2 [H _]; assumption.\napply H1a.\napply refl_trans_incl with (compose_rel (rest P R2) (refl_trans_clos (rest P R1))); trivial.\nclear; intros a1 a2 H; inversion H as [c1 a c2 H1 H2]; subst.\napply Comp with a.\ninversion H1; trivial.\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\n\nintros b H; apply Acc_incl with (compose_rel (refl_trans_clos R1) R2).\nclear; intros a1 a2 H; inversion H as [c1 a c2 H1 [H2 _]]; subst.\napply Comp with a; [idtac | assumption].\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\napply H2a.\napply refl_trans_incl with (rest P R1); [idtac | assumption].\nclear; intros a1 a2 [H _]; assumption.\nclear H1a H2a; revert Pa; induction H as [a Acc_a IH].\nintro Pa; apply Acc_intro; intros a1 [H1 | H2]; apply IH.\nleft; repeat split; trivial.\napply Inv1 with a; assumption.\napply Inv1 with a; assumption.\nright; repeat split; trivial.\napply Inv2 with a; assumption.\napply Inv2 with a; assumption.\nQed.\n\nLemma accR2 : forall A (R : relation A) a, Acc R a <-> Acc (compose_rel R R) a.\nProof.\nintros A R a; split.\nintro Acc_a; apply Acc_incl with (trans_clos R).\nintros x z H; inversion H as [x' y z' H1 H2]; clear H; subst; apply t_trans with y; trivial.\napply t_step; trivial.\napply acc_trans; trivial.\nintros Acc_a; induction Acc_a as [a Acc_a IH].\napply Acc_intro; intros b H; apply Acc_intro; intros c H'.\napply IH; apply Comp with b; trivial.\nQed.\n\nLemma acc_inv_im : \n\tforall A B (R1 : relation A) (R2 : relation B) (f : A -> B),\n\t(forall a1 a2, R1 a1 a2 -> R2 (f a1) (f a2)) ->\n\tforall a, Acc R2 (f a) -> Acc R1 a.\nProof.\nintros A B R1 R2 f H a.\nset (b := f a) in *.\nassert (b_eq_fa := refl_equal b).\nunfold b at 2 in b_eq_fa; clearbody b.\nintro Acc_b; revert a b_eq_fa; induction Acc_b as [b Acc_b IH].\nintros a b_eq_fa; apply Acc_intro; intros a' H'.\napply IH with (f a'); trivial.\nsubst b; apply H; trivial.\nQed.\n\nLemma acc_inv_im2 :\n   forall A B (R1 : relation A) (R2 : relation B) (f : A -> B),\n  forall a, (forall a1 a2 a3, R1 a3 a2 -> R1 a2 a1 -> refl_trans_clos R1 a1 a -> R2 (f a2) (f a1)) ->\n  Acc R2 (f a) -> Acc R1 a.\nProof.\nintros A B R1 R2 f a Hinv Acc_b.\nset (b := f a) in *.\nassert (b_eq_fa := refl_equal b).\nunfold b at 2 in b_eq_fa; clearbody b.\nrevert a b_eq_fa Hinv; induction Acc_b as [b Acc_b IH].\nintros a b_eq_fa Hinv.\napply Acc_intro; intros a2 H2.\napply Acc_intro; intros a3 H3.\napply Acc_inv with a2; trivial.\napply IH with (f a2); trivial.\nsubst b; apply Hinv with a3; trivial.\nleft.\nrevert Hinv H2; clear; intros Hinv H2.\nintros b1 b2 b3 K3 K2 K1.\napply Hinv with b3; trivial.\ninversion K1 as [b | b' a' K1'].\nright; left; assumption.\nright; apply trans_clos_is_trans with a2; trivial.\nleft; assumption.\nQed.\n\nLemma acc_inv_im3 :\n   forall A B (R1 : relation A) (R2 : relation B) (f : A -> B),\n  forall a, (forall a1 a2, R1 a2 a1 -> refl_trans_clos R1 a1 a -> R2 (f a2) (f a1)) ->\n  Acc R2 (f a) -> Acc R1 a.\nProof.\nintros A B R1 R2 f a Hinv Acc_b.\nset (b := f a) in *.\nassert (b_eq_fa := refl_equal b).\nunfold b at 2 in b_eq_fa; clearbody b.\nrevert a b_eq_fa Hinv; induction Acc_b as [b Acc_b IH].\nintros a b_eq_fa Hinv.\napply Acc_intro; intros a2 H2.\napply IH with (f a2); trivial.\nsubst b; apply Hinv; trivial.\nleft.\nrevert Hinv H2; clear; intros Hinv H2.\nintros b1 b2 K2 K1.\napply Hinv; trivial.\ninversion K1 as [b | b' a' K1'].\nright; left; assumption.\nright; apply trans_clos_is_trans with a2; trivial.\nleft; assumption.\nQed.\n\nLemma union_equiv : \nforall A R1 R2 R3 R4 (R1_equiv_R3: forall x y, R1 x y <-> R3 x y)\n(R2_equiv_R4: forall x y, R2 x y <-> R4 x y) x y,\n(union A R1 R2 x y <-> union _ R3 R4 x y).\nProof.\n  intros A R1 R2 R3 R4 R1_equiv_R3 R2_equiv_R4 x y.\n  split;intro H;case H.\n  rewrite R1_equiv_R3;intro H';left;exact H'.\n  rewrite R2_equiv_R4;intro H';right;exact H'.\n  rewrite <- R1_equiv_R3;intro H';left;exact H'.\n  rewrite <- R2_equiv_R4;intro H';right;exact H'.\nQed.\n\nLemma union_sym : forall A R1 R2 x y, union A R1 R2 x y <-> union A R2 R1 x y.\nProof. \n  intros A R1 R2 x y.\n  split;  (inversion_clear 1;[right|left];assumption).\nQed.\n\nLemma union_assoc : \n  forall A R1 R2 R3 x y, union A (union A R1 R2) R3 x y <-> union A R1 (union A R2 R3) x y.\nProof.\n  intros A R1 R2 R3 x y.\n  split.\n  intro H.\n  case H;clear H;intro H.\n  case H;clear H;intro H.\n  left;assumption.\n  right;left;assumption.\n  right;right;assumption.\n  intro H.\n  case H;clear H;intro H.\n  left;left;assumption.\n  case H;clear H;intro H.\n  left;right;assumption.\n  right;assumption.\nQed.\n\nLemma union_idem : forall A R x y, union A R R x y <-> R x y.\nProof.\n  intros A R x y.\n  split.\n  inversion_clear 1;assumption.\n  intro H;left;assumption.\nQed.\n\nLemma union_idem_strong : forall A (R R': A -> A -> Prop) (H:forall x y, R x y -> R' x y) x y, (union A R R' x y <-> R' x y).\nProof.\n  intros A R R' H x y.\n  split.\n  inversion_clear 1. apply H;assumption.\n  assumption.\n  intro H';right;assumption.\nQed.\n\n\nSection star.\nUnset Implicit Arguments.\nVariable A:Type.\nVariable R : A -> A -> Prop.\nInductive star (x:A) : A -> Prop := \n| star_refl : star x x\n| star_step : forall y, star x y -> forall z, R y z -> star x z\n.\n\n\nLemma star_trans: forall x y z, star x y -> star y z -> star x z.\nProof. \nintros x y z H H1;revert x H; \ninduction H1.\n\ntauto.\nintros.\neconstructor 2 with y0;auto.\nQed.\n\nLemma star_R : forall x y, R x y -> star x y.\nProof.\nintros x y H;constructor 2 with x;[constructor|assumption].\nQed.\n\nLemma star_ind2 : forall  x (P:A -> Prop),\n  (P x) -> \n  (forall y, P y -> forall z, R y z -> P z) ->\n  forall a, star x a -> P a.\nProof.\n  intros x P H H0 a H1.\n  induction H1.\n  exact H.\n  apply H0 with (y:=y);assumption.\nQed.\n\nEnd star.\n\nLemma star_equiv :  forall A (R1 R2: A -> A -> Prop), (forall l r, R1 r l <-> R2 r l) -> \n  forall l r, star _ R1 r l <-> star _ R2 r l.\nProof.\n  intros A R1 R2 H l r.\n  split;induction 1;try constructor.\n  constructor 2 with y;auto.\n  rewrite H in H1;assumption.\n  constructor 2 with y;auto.\n  rewrite H;assumption.\nQed.\nSet Implicit Arguments.\nInductive product_o A B (R1 : relation A) (R2 : relation B) : relation (A*B)%type :=\n\t| CaseA : forall a a' b, R1 a a' -> product_o R1 R2 (a,b) (a',b)\n\t| CaseB : forall a b b', R2 b b' -> product_o R1 R2 (a,b) (a,b').\n\nLemma acc_and :\n   forall A B (R1 : relation A) (R2 : relation B),\n   forall a b, Acc R1 a -> Acc R2 b -> Acc (product_o R1 R2) (a,b). \nProof. \nintros A B R1 R2 a b Acc_a; generalize b; clear b;\ninduction Acc_a as [a Acc_a IHa].\nintros b Acc_b; generalize a Acc_a IHa; clear a Acc_a IHa;\ninduction Acc_b as [b Acc_b IHb]; intros a Acc_a IHa;\napply Acc_intro; intros [a' b'] H; inversion H; clear H; subst.\napply IHa; trivial.\napply Acc_intro; trivial.\napply IHb; trivial.\nDefined.\n\nDefinition nf A (R : relation A) t := forall s, R s t -> False.\n\nLemma acc_nf : forall A (R : relation A) FB, (forall t s, In s (FB t) <-> R s t) ->\n                          forall t, Acc R t -> { s : A | nf R s /\\ (s = t \\/ trans_clos R s t)}.\nProof.\nintros A R FB red_dec t Acc_t; induction Acc_t as [t Acc_t IH].\ncase_eq (FB t).\nintro H; exists t; split.\nintros s H'; rewrite <- red_dec in H';  rewrite H in H'; trivial.\nleft; trivial.\nintros a l H; destruct (IH a) as [a' [nf_a'  H']].\nrewrite <- red_dec; rewrite H; left; trivial.\nexists a'; split; trivial.\ndestruct H' as [a'_eq_a | H'].\nsubst; right; apply t_step; rewrite <- red_dec; rewrite H; left; trivial.\nright; apply trans_clos_is_trans with a; trivial.\napply t_step; rewrite <- red_dec; rewrite H; left; trivial.\nDefined.\n\nLemma dec_nf : forall A (R : relation A) FB, (forall t s, In s (FB t) <-> R s t) ->\n                          forall t, {nf R t}+{~nf R t}.\nProof.\nintros A R FB red_dec t.\ncase_eq (FB t).\nintro H; left; unfold nf; intros s H'; rewrite <- red_dec in H'; rewrite H in H'; contradiction.\nintros a l H.\nright; intro H'; apply H' with a.\nrewrite <- red_dec; rewrite H; left; trivial.\nDefined.\n\nLemma cycle_not_acc : forall A (R : relation A) (a : A), R a a -> ~Acc R a.\nProof.\nintros A R a H Acc_a; generalize H; clear H; \ninduction Acc_a as [a Acc_a IH].\nintro H; apply (IH a); trivial.\nQed.\n\n", "meta": {"author": "sorinica", "repo": "spike-prover", "sha": "f2d6dd0bcebb647e09dd23048753075551da27eb", "save_path": "github-repos/coq/sorinica-spike-prover", "path": "github-repos/coq/sorinica-spike-prover/spike-prover-f2d6dd0bcebb647e09dd23048753075551da27eb/Coccinelle/Coq8.15/closure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7335345654130785}}
{"text": "Require Import Coq.Sets.Constructive_sets.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Arith.PeanoNat.\n\nDefinition group_closure {X : Type} (A : Ensemble X) (op : X -> X -> X) := \n    forall x y: X, A x /\\ A y -> A (op x y).\n\nDefinition group_associativity {X : Type} (A : Ensemble X) (op : X -> X -> X) := \n    forall x y z : X, A x /\\ A y /\\ A z -> op (op x y) z = op x (op y z).\n\nDefinition group_identity {X : Type} (e : X) (A : Ensemble X) (op : X -> X -> X) := \n    forall x : X, A x -> op x e = op e x /\\ op x e = x /\\ op e x = x.\n\nDefinition group_inverse {X : Type} (e : X) (A : Ensemble X) (op : X -> X -> X) := \n    forall x : X, A x -> exists x_inv, op x x_inv = e /\\ op x_inv x = e.\n\nDefinition EmptyBoolSet : Ensemble bool := \n    Empty_set bool.\n\nDefinition BoolSet : Ensemble bool := Full_set bool.\n\nTheorem All_in_BoolSet : forall x : bool, In bool BoolSet x.\nProof.\n    unfold In.\n    unfold BoolSet.\n    apply Full_intro.\nQed.\n\nTheorem Bool_closed : group_closure BoolSet xorb.\nProof.\n    unfold group_closure.\n    intros x y H.\n    apply All_in_BoolSet.\nQed.\n\nTheorem Bool_associative : group_associativity BoolSet xorb.\nProof.\n    unfold group_associativity.\n    intros x y z H.\n    apply xorb_assoc_reverse.\nQed.\n\nTheorem Bool_identity : group_identity false BoolSet xorb.\nProof.\n    unfold group_identity.\n    intros x H.\n    rewrite xorb_false_r.\n    rewrite xorb_false_l.\n    split; try split; reflexivity.\nQed.\n\nTheorem Bool_inverse : group_inverse false BoolSet xorb.\nProof.\n    unfold group_inverse.\n    intros x H.\n    destruct x.\n    - exists true. split; reflexivity.\n    - exists false. split; reflexivity.\nQed.\n\nDefinition Group {X : Type} (S : Ensemble X) (op : X -> X -> X) (e : X) :=\ngroup_closure S op /\\ group_associativity S op /\\ group_identity e S op /\\ group_inverse e S op.\n\nTheorem BooleanGroup : Group BoolSet xorb false.\nProof.\n    unfold Group.\n    split. \n    apply Bool_closed.\n    split.\n    apply Bool_associative.\n    split.\n    apply Bool_identity.\n    apply Bool_inverse.\nQed.\n\nDefinition plus_mod_n (n x y : nat) := (plus x y) mod n.\n\nFixpoint Numbers0Ton (n : nat) (S : Ensemble nat) :=\nmatch n with\n| 0 => Add nat S 0\n| S n' => Add nat (Numbers0Ton n' S) n\nend.\n\nDefinition Zn (n : nat) := \nmatch n with\n| 0 => Empty_set nat\n| S n' => Numbers0Ton n' (Empty_set nat)\nend.\n\nTheorem m_lt_n_in_Zn : forall n m, m < n -> In nat (Zn n) m.\nProof.\n  intros.\n  induction n.\n  - lia.\n  - assert(H' : m < n \\/ m = n). { lia. }\n    destruct H'.\n    + apply IHn in H0.\n      destruct n.\n      simpl in H0.\n      contradiction.\n      simpl.\n      apply Union_introl.\n      apply H0.\n    + destruct n; \n      apply Union_intror; \n      rewrite H0;\n      apply In_singleton.\nQed.\n\nTheorem Zn_set_equivalence : forall n : nat, Zn (S n) = Add nat (Zn n) n.\nProof.\n  intros.\n  apply Extensionality_Ensembles.\n  induction n.\n  {\n    split.\n    - unfold Included.\n      intros.\n      simpl.\n      simpl in H.\n      apply H.\n    - unfold Included.\n      intros.\n      simpl.\n      simpl in H.\n      apply H.\n  }\n  {\n    apply Extensionality_Ensembles in IHn.\n    split.\n    - intros x H.\n      simpl.\n      simpl in H.\n      apply H.\n    - intros x H.\n      apply H.\n  }\nQed.\n\n\nTheorem m_in_Zn_m_lt_n : forall n m, In nat (Zn n) m -> m < n.\nProof.\n  intros.\n  induction n.\n  - simpl in H. apply Noone_in_empty in H. contradiction.\n  - assert(H0: Zn (S n) = Add nat (Zn n) n). { apply Zn_set_equivalence. }\n    assert(H1 : In nat (Zn n) m \\/ m = n). \n    {\n      rewrite H0 in H.\n      induction H.\n      - left. apply H.\n      - right. \n        apply Singleton_inv in H.\n        lia.\n    }\n    destruct H1.\n    + apply IHn in H1. lia.\n    + lia. \nQed.\n\nDefinition group_homomorphism {X Y : Type} (G1 : Ensemble X) (op1 : X -> X -> X) (e1 : X)\n(G2 : Ensemble Y) (op2 : Y -> Y -> Y) (e2 : Y) (f : X -> Y) : Prop :=\nGroup G1 op1 e1 /\\ Group G2 op2 e2 -> forall (x y : X), G1 x /\\ G1 y -> f (op1 x y) = op2 (f x) (f y) /\\ G2 (f x) /\\ G2 (f y).\n\nTheorem mod_lt_n : forall x n, x < S n -> x mod (S n) = x.\nProof.\nAdmitted.\n      \nTheorem mod_plus : forall n x y, x mod S n + y mod (S n) = (x + y) mod S n.\nProof.\n  intros.\nAdmitted.\n\nTheorem mod_mod : forall n x, (x mod S n) mod S n = x mod S n.\nAdmitted.\n\nTheorem In_Zn_iff_lt_n : forall n x, x < n <-> Zn n x.\nAdmitted. \n\nTheorem n_mod_n : forall n, n <> 0 -> n mod n = 0.\nProof.\nAdmitted.\n\nTheorem plus_mod_n_3 : forall n x y z, \nplus_mod_n (S n) (plus_mod_n (S n) x y) z = (x + y + z) mod (S n).\nProof.\n  intros.\n  unfold plus_mod_n.\n  remember (x + y) as w.\n  rewrite <- mod_plus.\n  rewrite mod_mod.\n  rewrite mod_plus.\n  reflexivity.\nQed.    \n\nTheorem ZnGroup : forall n, n <> 0 -> Group (Zn n) (plus_mod_n n) 0.\nProof.\n    unfold Group.\n    intros.\n    destruct n.\n    - contradiction.\n    - split.\n      unfold group_closure.\n      intros.\n      simpl.\n      induction n.\n      simpl.\n      apply Add_intro2.\n      assert(S n <> 0). {\n        lia.\n      }\n      induction (x+y); simpl.\n      assert(H' : n - n = 0). { lia. }\n      rewrite H'.\n      assert(H'' : Add nat (Numbers0Ton n (Empty_set nat)) (S n) = Zn (S (S n))).\n      {\n        reflexivity.\n      }\n      rewrite H''.\n      assert(H''' : 0 < S (S n)).\n      {\n        lia.\n      }\n      apply m_lt_n_in_Zn in H'''.\n      apply H'''.\n      destruct (snd (Init.Nat.divmod n0 (S n) 0 n)).\n      apply Add_intro2.\n      assert(H'' : Add nat (Numbers0Ton n (Empty_set nat)) (S n) = Zn (S (S n))).\n      {\n        reflexivity.\n      }\n      rewrite H''.\n      apply m_lt_n_in_Zn.\n      lia.\n      split.\n      simpl.\n      unfold group_associativity.\n      intros.\n      destruct H0.\n      destruct H1.\n      rewrite plus_mod_n_3.\n      unfold plus_mod_n.\n      replace ((x + y + z)) with ((x + (y + z))).\n      remember (y + z) as w.\n      rewrite <- mod_plus.\n      replace (x + w mod S n) with (w mod S n + x).\n      rewrite <- mod_plus.\n      rewrite mod_mod.\n      replace (x mod S n + w mod S n) with (w mod S n + x mod S n).\n      reflexivity.\n      lia.\n      lia.\n      lia.\n      split.\n      unfold group_identity.\n      intros.\n      split.\n      unfold plus_mod_n.\n      replace (x + 0) with x.\n      replace (0 + x) with x.\n      reflexivity.\n      lia.\n      lia.\n      split.\n      unfold plus_mod_n.\n      replace (x + 0) with x.\n      apply mod_lt_n.\n      simpl.\n      apply In_Zn_iff_lt_n.\n      apply H0.\n      lia.\n      unfold plus_mod_n.\n      replace (0 + x) with x.\n      apply mod_lt_n.\n      apply In_Zn_iff_lt_n.\n      apply H0.\n      lia.\n      unfold group_inverse.\n      intros.\n      exists (S n - x).\n      split.\n      unfold plus_mod_n.\n      assert(H' : x < S n).\n      {\n        apply In_Zn_iff_lt_n in H0.\n        apply H0.\n      }\n      assert(x + (S n - x) = S n). { lia. }\n      rewrite H1.\n      apply n_mod_n.\n      apply H.\n      unfold plus_mod_n.\n      assert(H' : x < S n).\n      {\n        apply In_Zn_iff_lt_n in H0.\n        apply H0.\n      }\n      assert(S n - x + x = S n). { lia. }\n      rewrite H1.\n      apply n_mod_n.\n      lia.\nQed.\n\nTheorem Z2_Group : Group (Zn 2) (plus_mod_n 2) 0.\nProof.\n apply ZnGroup.\n lia.\nQed.\n\nDefinition Bool_Z2_Map (x : bool) : nat :=\nmatch x with\n| false => 0\n| true => 1\nend.\n\n\nTheorem Bool_Z2_Homomorphism : group_homomorphism \nBoolSet xorb false \n(Zn 2) (plus_mod_n 2) 0\nBool_Z2_Map.\nProof.\n  unfold group_homomorphism.\n  intros.\n  unfold plus_mod_n.\n  destruct x; destruct y; try simpl; repeat (try split; try reflexivity; try apply Add_intro2; try apply Add_intro1).\nQed.      \n    \n", "meta": {"author": "depaulmillz", "repo": "FormalizedMathematics", "sha": "77e680e406ee8fa26fd414b27dd19ee4590091d2", "save_path": "github-repos/coq/depaulmillz-FormalizedMathematics", "path": "github-repos/coq/depaulmillz-FormalizedMathematics/FormalizedMathematics-77e680e406ee8fa26fd414b27dd19ee4590091d2/theories/Groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7335216526814614}}
{"text": "Require Export TopologicalSpaces.\nRequire Export OrderTopology.\nRequire Export Reals.\n\nDefinition RTop := OrderTopology Rle.\n\nRequire Export MetricSpaces.\n\nDefinition R_metric (x y:R) : R := Rabs (y-x).\n\nLemma R_metric_is_metric: metric R_metric.\nProof.\nconstructor.\nintros.\nunfold R_metric.\npose proof (Rabs_pos (y-x)).\nauto with *.\n\nintros.\nunfold R_metric.\nreplace (y-x) with (-(x-y)); try ring.\napply Rabs_Ropp.\n\nintros.\nunfold R_metric.\nreplace (z-x) with ((y-x) + (z-y)); try ring.\napply Rabs_triang.\n\nintros.\nunfold R_metric.\nreplace (x-x) with 0; try ring.\nexact Rabs_R0.\n\nintros.\nassert (y-x=0).\napply NNPP.\ncontradict H.\napply Rabs_no_R0; assumption.\nauto with *.\nQed.\n\nLemma Rmetric_bound: forall x y z:R, R_metric x z < y - x ->\n  z < y.\nProof.\nintros.\nreplace z with (x + (z-x)); try ring.\napply Rle_lt_trans with (x + R_metric x z).\nassert (z - x <= R_metric x z).\napply Rle_abs.\nauto with real.\nreplace y with (x + (y-x)); try ring.\nauto with real.\nQed.\n\nLemma Rmetric_bound2: forall x y z:R, R_metric y z < y - x ->\n  x < z.\nProof.\nintros.\nreplace z with (y + (z-y)); try ring.\napply Rlt_le_trans with (y - R_metric y z).\napply Rlt_minus in H.\napply Rminus_lt.\nreplace (x - (y - R_metric y z)) with\n  (R_metric y z - (y - x)); try ring.\ntrivial.\nassert (y - z <= R_metric y z).\nrewrite (metric_sym _ _ R_metric_is_metric y z).\napply Rle_abs.\napply Rle_minus in H0.\napply Rminus_le.\nreplace (y - R_metric y z - (y + (z - y))) with\n  (y - z - R_metric y z); trivial; ring.\nQed.\n\nLemma RTop_metrization: metrizes RTop R_metric.\nProof.\nrefine (let Hsubbasis := Build_TopologicalSpace_from_subbasis_subbasis\n  _ (order_topology_subbasis _ Rle) in _).\nclearbody Hsubbasis.\nred; intros.\nconstructor.\nintros.\ndestruct H.\nassert (open_ball (point_set RTop) R_metric x r = Intersection\n  [ y:R | x-r <= y /\\ y <> x-r ]\n  [ y:R | y <= x+r /\\ y <> x+r ]).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H0.\nassert (x - r < x0).\napply Rmetric_bound2 with x.\nring_simplify; trivial.\nassert (x + r > x0).\napply Rmetric_bound with x.\nring_simplify; trivial.\nrepeat split; auto with real.\nconstructor.\ndestruct H0.\ndestruct H0.\ndestruct H0.\ndestruct H1.\ndestruct H1.\napply Rabs_def1.\nassert (x0-x <= r).\napply Rminus_le.\napply Rle_minus in H1.\nreplace (x0 - x - r) with (x0 - (x + r)); trivial; ring.\nassert (x0 - x <> r).\nintro.\ncontradiction H3.\nrewrite <- H5.\nring.\ndestruct (total_order_T (x0 - x) r) as [[|]|]; try tauto.\nassert (r < r).\napply Rlt_le_trans with (x0 - x); trivial.\ncontradict H6.\napply Rlt_irrefl.\nassert (-r <= x0 - x).\napply Rle_minus in H0.\napply Rminus_le.\nreplace (-r - (x0 - x)) with (x - r - x0); try ring; trivial.\nassert (-r <> x0 - x).\nintro.\ncontradiction H2.\nreplace r with (- -r); try ring.\nrewrite H5; ring.\ndestruct (total_order_T (-r) (x0 - x)) as [[|]|]; try tauto.\nassert (-r < -r).\napply Rle_lt_trans with (x0 - x); trivial.\ncontradict H6.\napply Rlt_irrefl.\n\nrewrite H0.\nconstructor.\napply (@open_intersection2 RTop).\napply Hsubbasis; constructor.\napply Hsubbasis; constructor.\nassert (x-r < x).\napply Rminus_lt.\nring_simplify.\nauto with real.\nassert (x+r > x).\napply Rminus_gt.\nring_simplify; trivial.\nrepeat split; auto with real.\n\nintros.\ndestruct H.\ndestruct H.\ndestruct H0.\npose proof (H _ H0).\nassert (exists eps:R, eps > 0 /\\ Included (open_ball _ R_metric x eps) S).\nclear H0.\ninduction H2.\nexists 1.\nsplit.\nred.\nauto with real.\nintro; constructor.\ndestruct H0.\ndestruct H1.\ndestruct H0.\nexists (x0-x).\nsplit.\ndestruct (total_order_T x0 x) as [[]|].\nassert (x < x).\napply Rle_lt_trans with x0; trivial.\ncontradict H2.\napply Rlt_irrefl.\ncongruence.\napply Rgt_minus; trivial.\nred; intros y ?.\ndestruct H2.\nconstructor.\nassert (y < x0).\napply Rmetric_bound with x; trivial.\nsplit; auto with real.\n\ndestruct H1.\ndestruct H0.\nexists (x - x0).\nsplit.\ndestruct (total_order_T x0 x) as [[]|].\napply Rgt_minus; trivial.\ncongruence.\nassert (x < x).\napply Rlt_le_trans with x0; trivial.\ncontradict H2.\napply Rlt_irrefl.\nintros y ?.\ndestruct H2.\nconstructor.\nassert (x0 < y).\napply Rmetric_bound2 with x; trivial.\nsplit; auto with real.\ndestruct H1.\napply IHfinite_intersections in H1.\napply IHfinite_intersections0 in H3.\ndestruct H1 as [eps1 []].\ndestruct H3 as [eps2 []].\nexists (Rmin eps1 eps2).\nsplit.\nunfold Rmin.\ndestruct Rle_dec; trivial.\nred; intros y ?.\ndestruct H6.\nconstructor.\napply H4.\nconstructor.\napply Rlt_le_trans with (Rmin eps1 eps2); trivial.\nunfold Rmin; destruct Rle_dec; auto with real.\napply H5.\nconstructor.\napply Rlt_le_trans with (Rmin eps1 eps2); trivial.\nunfold Rmin; destruct Rle_dec; auto with real.\n\ndestruct H3 as [eps []].\nexists (open_ball R R_metric x eps).\nsplit.\nconstructor.\ntrivial.\nassert (Included S (FamilyUnion F)).\nintros y ?.\nexists S; trivial.\nauto with sets.\nQed.\n\nCorollary RTop_metrizable: metrizable RTop.\nProof.\nexists R_metric.\nexact R_metric_is_metric.\nexact RTop_metrization.\nQed.\n\nLemma RTop_separable: separable RTop.\nProof.\nRequire Import RationalsInReals.\nexists (Im Full_set Q2R).\napply countable_img.\napply countable_type_ensemble.\nexact Q_countable.\n\napply meets_every_nonempty_open_impl_dense.\nintros.\ndestruct H0 as [x].\ndestruct (RTop_metrization x).\ndestruct (open_neighborhood_basis_cond U) as [V []].\nsplit; trivial.\ndestruct H1.\ndestruct (rationals_dense_in_reals (x-r) (x+r)) as [q].\napply Rminus_gt.\nreplace (x+r-(x-r)) with (r+r); try ring.\napply Rgt_trans with r; auto with real.\npattern r at 3.\nreplace r with (r+0); try ring.\nauto with real.\n\nexists (Q2R q).\nconstructor.\nexists q; trivial.\nconstructor.\napply H2.\nconstructor.\ndestruct H3.\napply Rabs_def1.\napply Rminus_lt.\napply Rlt_minus in H4.\nreplace (Q2R q - x - r) with (Q2R q - (x + r)); trivial; ring.\napply Rminus_lt.\napply Rlt_minus in H3.\nreplace (-r - (Q2R q - x)) with (x - r - Q2R q); trivial; ring.\nQed.\n\nRequire Export Compactness.\n\nLemma bounded_real_net_has_cluster_point: forall (I:DirectedSet)\n  (x:Net I RTop) (a b:R), (forall i:DS_set I, a <= x i <= b) ->\n  exists x0:point_set RTop, net_cluster_point x x0.\nProof.\n(* idea: the liminf is a cluster point *)\nintros.\ndestruct (classic (inhabited (DS_set I))) as [Hinh|Hempty].\nassert (forall i:DS_set I, { y:R | is_glb\n                             (Im [ j:DS_set I | DS_ord i j ] x) y }).\nintro.\napply inf.\nexists a.\nred; intros.\ndestruct H0.\ndestruct (H x0).\nrewrite H1.\nauto with real.\nexists (x i).\nexists i; trivial.\nconstructor.\napply preord_refl.\napply DS_ord_cond.\n\nassert ({ x0:R | is_lub (Im Full_set (fun i:DS_set I => proj1_sig (X i)))\n                        x0 }).\napply sup.\nexists b.\nred; intros.\ndestruct H0 as [i].\ndestruct (X i).\nsimpl in H1.\nrewrite H1.\ndestruct i0.\ncut (b >= x0).\nauto with real.\napply Rge_trans with (x i).\ndestruct (H i).\nauto with real.\napply H2.\nexists i; trivial.\nconstructor.\napply preord_refl.\napply DS_ord_cond.\n\ndestruct Hinh as [i0].\nexists (proj1_sig (X i0)).\nexists i0; trivial.\nconstructor.\n\ndestruct H0 as [x0].\nexists x0.\nassert (forall i j:DS_set I, DS_ord i j ->\n  proj1_sig (X i) <= proj1_sig (X j)).\nintros.\ndestruct (X i0).\ndestruct (X j).\nsimpl.\ndestruct i1.\ndestruct i2.\napply H4.\nred; intros.\ndestruct H5.\ndestruct H5.\napply H1.\nexists x3; trivial.\nconstructor.\napply preord_trans with j; trivial.\napply DS_ord_cond.\n\nred; intros.\ndestruct (RTop_metrization x0).\ndestruct (open_neighborhood_basis_cond U).\nsplit; trivial.\ndestruct H3.\ndestruct H3.\ndestruct (lub_approx _ _ r i).\ntrivial.\ndestruct H5.\ndestruct H5.\ndestruct H6.\nred; intros.\ndestruct (DS_join_cond x1 i0).\ndestruct H9.\nremember (X x2) as y2.\ndestruct y2.\ndestruct (glb_approx _ _ r i1).\ntrivial.\ndestruct H11.\ndestruct H11.\ndestruct H11.\ndestruct H12.\nexists x4.\nsplit.\napply preord_trans with x2; trivial.\napply DS_ord_cond.\napply H4.\nconstructor.\nassert (y <= proj1_sig (X x2)).\nrewrite H7.\napply H0; trivial.\nrewrite <- Heqy2 in H15.\nsimpl in H15.\nassert (proj1_sig (X x2) <= x0).\napply i.\nexists x2; trivial.\nconstructor.\nrewrite <- Heqy2 in H16.\nsimpl in H16.\nrewrite <- H13.\napply Rabs_def1.\n\ncut (y0 < x0 + r).\nintro.\napply Rlt_minus in H17.\napply Rminus_lt.\nreplace (y0 - x0 - r) with (y0-(x0+r)); trivial; ring.\napply Rlt_le_trans with (x3 + r).\ntrivial.\nauto with real.\n\ncut (y0 > x0 - r).\nintro.\napply Rlt_minus in H17.\napply Rminus_lt.\nreplace (-r - (y0-x0)) with (x0-r-y0); trivial; ring.\napply Rge_gt_trans with y.\napply Rge_trans with x3; auto with real.\ntrivial.\n\nexists a.\nred; intros.\nred; intros.\ncontradiction Hempty.\nexists; exact i.\nQed.\n\nLemma R_closed_interval_compact: forall a b:R, a <= b ->\n  compact (SubspaceTopology ([x:point_set RTop | a <= x <= b])).\nProof.\nintros a b Hbound.\napply net_cluster_point_impl_compact.\nintros.\npose (y := fun i:DS_set I => proj1_sig (x i)).\ndestruct (bounded_real_net_has_cluster_point _ y a b).\nintros.\nunfold y.\ndestruct (x i).\ndestruct i0.\nsimpl.\ntrivial.\n\nassert (closed [x:point_set RTop | a <= x <= b]).\nassert ([x:point_set RTop | a <= x <= b] = Intersection\n                [ x:point_set RTop | a <= x ]\n                [ x:point_set RTop | x <= b ]).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\ndestruct H1.\nconstructor; constructor; trivial.\ndestruct H1.\ndestruct H1.\ndestruct H2.\nconstructor.\nauto.\nrewrite H1.\napply closed_intersection2.\napply upper_closed_interval_closed.\nconstructor; red; intros; auto with real.\napply Rle_trans with y0; trivial.\nintros.\ndestruct (total_order_T x1 y0) as [[|]|]; auto with real.\napply lower_closed_interval_closed.\nconstructor; red; intros; auto with real.\napply Rle_trans with y0; trivial.\nintros.\ndestruct (total_order_T x1 y0) as [[|]|]; auto with real.\n\nassert (Ensembles.In [x:point_set RTop | a <= x <= b] x0).\nrewrite <- (closure_fixes_closed _ H1).\napply net_cluster_point_in_closure with y.\ndestruct H as [i0].\nexists i0.\nintros.\nconstructor.\nunfold y.\ndestruct (x j).\nsimpl.\ndestruct i.\ntrivial.\ntrivial.\n\nexists (exist _ x0 H2).\nred; intros.\ndestruct (subspace_topology_topology _ _ _ H3) as [V].\ndestruct H5.\nred; intros.\nassert (Ensembles.In V x0).\nrewrite H6 in H4.\ndestruct H4.\nsimpl in H4.\ntrivial.\n\ndestruct (H0 V H5 H7 i) as [j []].\nexists j.\nsplit; trivial.\nrewrite H6.\nconstructor.\nsimpl.\nexact H9.\nQed.\n\nLemma R_compact_subset_bounded: forall A:Ensemble (point_set RTop),\n  compact (SubspaceTopology A) -> bound A.\nProof.\nintros.\ndestruct (H (Im Full_set (fun y:R => inverse_image (subspace_inc _)\n                   [ x:point_set RTop | y - 1 < x < y + 1 ]))).\nintros.\ndestruct H0.\nrewrite H1.\napply subspace_inc_continuous.\nreplace [x0:point_set RTop | x-1 < x0 < x+1] with\n  (Intersection [x0:point_set RTop | x-1 <= x0 /\\ x0 <> x-1]\n                [x0:point_set RTop | x0 <= x+1 /\\ x0 <> x+1]).\npose proof (Build_TopologicalSpace_from_subbasis_subbasis\n  _ (order_topology_subbasis _ Rle)).\napply open_intersection2.\napply H2.\nconstructor.\napply H2.\nconstructor.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H2.\ndestruct H2.\ndestruct H2.\ndestruct H3.\ndestruct H3.\nconstructor.\nsplit.\ndestruct (total_order_T (x-1) x0) as [[|]|]; auto with real.\ncontradiction H4; symmetry; trivial.\nassert (x0 < x0).\napply Rlt_le_trans with (x-1); auto with real.\ncontradict H6; apply Rlt_irrefl.\ndestruct (total_order_T x0 (x+1)) as [[|]|]; auto with real.\ncontradiction H5.\nassert (x0 < x0).\napply Rle_lt_trans with (x+1); auto with real.\ncontradict H6; apply Rlt_irrefl.\ndestruct H2.\ndestruct H2.\nconstructor; constructor; split; auto with real.\n\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\neexists.\nexists (proj1_sig x).\nconstructor.\nreflexivity.\nconstructor.\nconstructor.\ndestruct x.\nsimpl.\nsplit; apply Rminus_lt; auto with real.\nreplace (x-1-x) with (-1); try ring.\napply Ropp_lt_gt_0_contravar.\nexact Rlt_0_1.\n\ndestruct H0.\ndestruct H1.\nassert (exists a:R, forall S:Ensemble (point_set (SubspaceTopology A)),\n  forall b:point_set (SubspaceTopology A),\n  Ensembles.In x S -> Ensembles.In S b -> proj1_sig b < a).\nclear H2.\ninduction H0.\nexists 0.\nintros.\ndestruct H0.\ndestruct IHFinite.\ncut (Included A0 (Add A0 x)); auto with sets.\nassert (Ensembles.In (Add A0 x) x).\nright.\nconstructor.\napply H1 in H4.\ndestruct H4.\nexists (Rmax x0 (x+1)).\nintros.\ndestruct H6.\napply Rlt_le_trans with x0.\napply H3 with x1; trivial.\nunfold Rmax.\ndestruct Rle_dec; auto with real.\ndestruct H6.\nrewrite H5 in H7.\ndestruct H7.\ndestruct H6.\napply Rlt_le_trans with (x+1).\napply H6.\nunfold Rmax; destruct Rle_dec; auto with real.\n\ndestruct H3 as [a].\nexists a.\nred; intros.\nassert (Ensembles.In (FamilyUnion x)\n  (exist (fun x:R => Ensembles.In A x) x0 H4)).\nrewrite H2; constructor.\ninversion H5.\npose proof (H3 _ _ H6 H7).\nsimpl in H9.\nauto with real.\nQed.\n\nLemma Ropp_continuous: continuous Ropp (X:=RTop) (Y:=RTop).\nProof.\napply pointwise_continuity.\nintro.\napply metric_space_fun_continuity with R_metric R_metric;\n  try apply RTop_metrization.\nintros.\nexists eps.\nsplit; trivial.\nintros.\nunfold R_metric.\nreplace (-x' - -x) with (x-x'); try ring.\nrewrite Rabs_minus_sym; trivial.\nQed.\n\nRequire Export Connectedness.\n\nLemma R_connected: connected RTop.\nProof.\ncut (forall S:Ensemble (point_set RTop),\n  clopen S -> Ensembles.In S 0 -> S = Full_set).\nintro.\nred; intros.\ndestruct (classic (Ensembles.In S 0)).\nright.\napply H; trivial.\nleft.\nassert (Complement S = Full_set).\napply H; trivial.\ndestruct H0; split; trivial.\nred; rewrite Complement_Complement; trivial.\napply Extensionality_Ensembles; split; red; intros.\nassert (Ensembles.In (Complement S) x).\nrewrite H2; constructor.\ncontradiction H4.\ndestruct H3.\n\ncut (forall S:Ensemble (point_set RTop),\n  clopen S -> Ensembles.In S 0 -> forall x:R, x > 0 ->\n                                  Ensembles.In S x).\nintro.\nassert (forall S:Ensemble (point_set RTop),\n  clopen S -> Ensembles.In S 0 -> forall x:R, x < 0 ->\n                                  Ensembles.In S x).\nintros.\npose (T := inverse_image Ropp S).\n\nassert (Ensembles.In T (-x)).\napply H.\ndestruct H0; split.\napply Ropp_continuous; trivial.\nred.\nsubst T.\nrewrite <- inverse_image_complement.\napply Ropp_continuous; trivial.\nconstructor.\nreplace (-0) with 0; trivial; ring.\ncut (0 < -x); auto with real.\ndestruct H3.\nrewrite Ropp_involutive in H3; trivial.\n\nintros.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\ndestruct (total_order_T x 0) as [[|]|].\napply H0; trivial.\ncongruence.\napply H; trivial.\n\nintros.\napply NNPP; intro.\npose (T := [ y:R | forall z:R, 0 <= z <= y -> Ensembles.In S z ]).\nassert (Ensembles.In T 0).\nconstructor.\nintros.\nassert (z = 0).\ndestruct H3; auto with real.\nrewrite H4; trivial.\n\ndestruct (sup T).\nexists x.\nred; intros.\ncut (~ x0>x).\napply Rnot_lt_le; auto with real.\nintro.\ndestruct H4.\napply H2.\napply H4.\nsplit; auto with real.\nexists 0.\nexact H3.\n\nassert (0 <= x0).\napply i.\nexact H3.\n\ndestruct (RTop_metrization x0).\nassert (Ensembles.In S x0).\nrewrite <- (closure_fixes_closed S); try apply H.\napply meets_every_open_neighborhood_impl_closure.\nintros.\ndestruct (open_neighborhood_basis_cond U).\nsplit; trivial.\ndestruct H7.\ndestruct H7.\ndestruct (lub_approx _ _ r i).\ntrivial.\ndestruct H9.\nexists (Rmax x1 0).\nconstructor.\nunfold Rmax.\ndestruct Rle_dec.\ntrivial.\napply H9.\nauto with real.\n\napply H8.\nconstructor.\nunfold Rmax.\ndestruct Rle_dec.\nunfold R_metric.\nrewrite Rabs_minus_sym.\nreplace (x0-0) with x0; try ring.\napply Rabs_def1.\napply Rminus_lt.\ndestruct H10.\napply Rlt_le_trans with x1; trivial.\napply Rlt_le_trans with 0; auto with real.\n\napply Rabs_def1.\napply Rle_lt_trans with 0; auto with real.\ndestruct H10.\napply Rle_minus; trivial.\ndestruct H10.\napply Rminus_lt.\napply Rlt_minus in H10.\nreplace (-r - (x1-x0)) with (x0-r-x1); trivial; ring.\n\ndestruct (open_neighborhood_basis_cond S).\nsplit; trivial.\napply H.\ndestruct H6.\ndestruct H6.\n\ndestruct (lub_approx _ _ r i).\ntrivial.\ndestruct H8.\n\nassert (Ensembles.In T (x0+r/2)).\nconstructor.\nintros.\ndestruct H10.\ndestruct (total_order_T z x1) as [[|]|].\napply H8.\nsplit; auto with real.\napply H8.\nsplit; auto with real.\napply H7.\nconstructor.\napply Rabs_def1.\napply Rle_lt_trans with (r/2).\napply Rminus_le.\napply Rle_minus in H11.\nreplace (z-x0-r/2) with (z-(x0+r/2)); trivial; ring.\napply Rminus_gt.\nreplace (r-r/2) with (r/2); try field.\napply Rmult_gt_0_compat; auto with real.\nauto with *.\napply Rlt_trans with (x1 - x0).\ndestruct H9.\napply Rlt_minus in H9.\napply Rminus_lt.\nreplace (-r - (x1-x0)) with (x0-r-x1); trivial; ring.\ncut (x1<z); trivial.\nintro.\nunfold Rminus.\nauto with real.\n\nassert (x0 + r/2 <= x0).\napply i.\nexact H10.\n\nabsurd (x0 + r/2 > x0).\napply Rge_not_gt; auto with real.\napply Rminus_gt.\nring_simplify.\napply Rmult_gt_0_compat; auto with real.\napply Rinv_0_lt_compat.\nauto with real.\nQed.\n\nRequire Export Completeness.\n\nLemma R_cauchy_sequence_bounded: forall x:nat->R,\n  cauchy R_metric x -> bound (Im Full_set x).\nProof.\nintros.\ndestruct (H 1) as [N].\nred; auto with real.\nassert (exists y:R, forall n:nat, (n<N)%nat -> x n <= y).\nclear H0; induction N.\nexists 0.\nintros.\ncontradict H0.\nauto with arith.\ndestruct IHN as [y].\nexists (Rmax y (x N)).\nintros.\napply lt_n_Sm_le in H1.\ndestruct (le_lt_or_eq _ _ H1).\napply Rle_trans with y.\napply H0; trivial.\napply Rmax_l.\nrewrite H2.\napply Rmax_r.\n\ndestruct H1 as [y].\nexists (Rmax y (x N + 1)).\nred; intros.\ndestruct H2 as [n].\nrewrite H3; clear y0 H3.\ndestruct (le_or_lt N n).\napply Rle_trans with (x N + 1).\nassert (R_metric (x n) (x N) < 1).\napply H0; auto with arith.\napply Rabs_def2 in H4.\ndestruct H4.\nRequire Import Fourier.\nfourier.\napply Rmax_r.\napply Rle_trans with y; auto.\napply Rmax_l.\nQed.\n\nLemma R_cauchy_sequence_lower_bound: forall x:nat->R,\n  cauchy R_metric x -> lower_bound (Im Full_set x).\nProof.\nintros.\nassert (cauchy R_metric (fun n:nat => - x n)).\nred; intros.\ndestruct (H eps H0) as [N].\nexists N.\nintros.\nreplace (R_metric (- x m) (- x n)) with (R_metric (x m) (x n)).\napply H1; trivial.\nunfold R_metric.\nreplace (x n - x m) with (- (- x n - - x m)) by ring.\napply Rabs_Ropp.\ndestruct (R_cauchy_sequence_bounded _ H0) as [m].\nexists (-m).\nred; intros.\ncut (-x0 <= m).\nintros; fourier.\napply H1.\ndestruct H2 as [n].\nexists n; trivial.\nf_equal; trivial.\nQed.\n\nLemma R_metric_complete: complete R_metric R_metric_is_metric.\nProof.\nred; intros.\ndestruct (R_cauchy_sequence_bounded _ H) as [b].\ndestruct (R_cauchy_sequence_lower_bound _ H) as [a].\ndestruct (bounded_real_net_has_cluster_point nat_DS x a b) as [x0].\nintros; split; [ cut (x i >= a); auto with real; apply H1 | apply H0 ];\n  exists i; trivial; constructor.\nexists x0.\napply cauchy_sequence_with_cluster_point_converges; trivial.\napply metric_space_net_cluster_point with R_metric;\n  try apply MetricTopology_metrizable.\nintros.\napply metric_space_net_cluster_point_converse with RTop; trivial.\napply RTop_metrization.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/RTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990283, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7335216453458685}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Arith.Wf_nat.\nRequire Import Recdef.\n\nOpen Scope nat_scope.\n\n\nDefinition max (a b : nat) :=\n    match nat_compare a b with\n    | Lt => b\n    | _  => a\n    end.\n\nInductive tree :=\n    | Tip : tree\n    | Bin : nat -> tree -> tree -> tree.\n\nDefinition ht (t : tree) :=\n    match t with\n    | Tip       => 0\n    | Bin n _ _ => n\n    end.\n\n\nDefinition join (x y : tree) : tree := Bin (max (ht x) (ht y) + 1) x y.\n\nFixpoint step (t : tree) (xs : list tree) : list tree :=\n    match xs with\n    | nil      => t :: nil\n    | u :: nil =>\n        match nat_compare (ht t) (ht u) with\n        | Lt => t :: u :: nil\n        | _  => (join t u) :: nil\n        end\n    | u :: v :: ts =>\n        match nat_compare (ht t) (ht u) with\n        | Lt => t :: u :: v :: ts\n        | _  =>\n            match nat_compare (ht t) (ht v) with\n            | Lt => step (join t u) (v :: ts)\n            | _  => step t (step (join u v) ts)\n            end\n        end\n    end.\n\n(* TODO: problem: there is no fold1 in Coq (partial) *)\nDefinition build (xs : list tree) := fold_left join (fold_right step nil xs).\n\n", "meta": {"author": "ltbinsbe", "repo": "INFODTP", "sha": "2995a6503d4b8028f83a0907e83bcd85dd417d48", "save_path": "github-repos/coq/ltbinsbe-INFODTP", "path": "github-repos/coq/ltbinsbe-INFODTP/INFODTP-2995a6503d4b8028f83a0907e83bcd85dd417d48/coq/abandonware/Default.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.733519713804531}}
{"text": "Require Import Ring.\nRequire Import Field.\nRequire Import Setoid.\nRequire Import Classes.RelationClasses.\nRequire Import Classes.Morphisms.\nRequire Import Ensembles.\nRequire Import Vector.\n\nSection VS.\n\n(*Variable (A : Type).*)\n\nClass Ring A :=\n  {\n  r0 : A;\n  r1 : A;\n  radd : A -> A -> A;\n  rmult : A -> A -> A;\n  rainv : A -> A;\n  rminus : A -> A -> A;\n  isring : ring_theory r0 r1 radd rmult rminus rainv eq;\n  }.\n(*\nContext `{Ring A}.\n*)\nClass Field A `{Ring A} :=\n  {\n  fdiv : A -> A -> A;\n  finv : A -> A;\n  isfield : field_theory r0 r1 radd rmult rminus rainv fdiv finv eq;\n  }.\n\nDeclare Scope field_scope.\nDelimit Scope field_scope with fieldsc.\nOpen Scope field_scope.\nBind Scope field_scope with Field.\nInfix \"+\" := radd : field_scope.\nInfix \"*\" := rmult : field_scope.\nNotation \"- k\" := rainv : field_scope.\nNotation \"/ k\" := finv : field_scope.\nInfix \"/\" := fdiv : field_scope.\n\n\nVariable (F V : Type).\nContext `{Field F}.\nVariable vadd : V -> V -> V.\nVariable vsmult : F -> V -> V.\nVariable v0 : V.\nVariable veq : V -> V -> Prop.\n\nInfix \"⨥\" := vadd (at level 50).\nInfix \"*\" := vsmult.\nNotation \"0\" := v0.\nInfix \"==\" := veq (at level 90).\n\n(*1.19*)\nRecord vectorspace_theory\n       (*(vadd : V -> V -> V) (vsmult : F -> V -> V) (v0 : V) (veq : V -> V -> Prop)*)\n  : Prop\n  := mk_vst\n       {\n         vadd_comm : forall (x y : V), x ⨥ y == y ⨥ x;\n         vadd_assoc : forall (x y z : V), (x ⨥ y) ⨥ z == x ⨥ (y ⨥ z);\n         vadd_ident : forall (x : V), x ⨥ 0 == x;\n         vadd_inv : forall (x : V), exists (w : V), x ⨥ w == 0;\n         vsmult_ident : forall (x : V), r1 * x == x;\n         vdistr1 : forall (a : F) (x y : V), a * (x ⨥ y) == (a * x) ⨥ (a * y);\n         vdistr2 : forall (a b : F) (x : V), (a + b) * x == (a * x) ⨥ (b * x);\n       }.\n\n(*vector equality is extensional*)\nRecord vec_eq_ext : Prop\n  :=\n    mk_veqe {\n        vadd_ext : Proper (veq ==> veq ==> veq) vadd;\n        vsmult_ext : Proper (eq ==> veq ==> veq) vsmult;\n      }.\n\n(*1.18*)\nClass VectorSpace F `{Field F} V :=\n  {\n  vaddition : V -> V -> V;\n  vscalar_mult : F -> V -> V;\n  v0 : V;\n  veq : relation V;\n  isvectorspace : vectorspace_theory vaddition vscalar_mult v0 veq;\n  }.\n\nDeclare Scope vectorspace_scope.\nDelimit Scope vectorspace_scope with vecsc.\nOpen Scope vectorspace_scope.\nBind Scope vectorspace_scope with VectorSpace.\n\nContext `{VectorSpace F V}.\n\nDefinition vainv (v : V) :=\n  vscalar_mult (rainv r1) v.\n\nDefinition vminus (u v : V) :=\n  vaddition u (vainv v).\n\nInfix \"⨥\" := vaddition (at level 50) : vectorspace_scope.\nInfix \"*\" := vscalar_mult : vectorspace_scope.\nNotation \"⨪\" := vainv : vectorspace_scope.\nInfix \"⨪\" := vminus (at level 50) : vectorspace_scope.\nInfix \"==\" := veq (at level 90) : vectorspace_scope.\n\nRecord vectorspace_eq_ext : Prop\n  :=\n    mk_vseqe\n      {\n        vadd_ext : Proper ((fun u => fun v => u == v) ==> (fun u => fun v => u == v) ==> (fun u => fun v => u == v))\n                          (fun u => fun v => u ⨥ v);\n        vsmult_ext : Proper ((fun x => fun y => x = y) ==> (fun u => fun v => u == v) ==> (fun u => fun v => u == v))\n                            (fun (a : F) => fun (v : V) => a * v);\n        v0_ext : Proper (fun u => fun v => u == v) v0;\n}.\nCompute relation V.\nInstance vadd_Proper (u v : V) :\n  Proper (veq ==> veq ==> veq) vaddition.\nProof.\n  unfold Proper.\n\n\nTheorem veq_equiv_refl : forall (v : V), v == v.\n  Admitted.\n\nTheorem veq_equiv_symm : forall (u v : V), u == v -> v == u.\n  Admitted.\n\nTheorem veq_equiv_trans : forall (u v w : V), u == v -> v == w -> u == w.\n  Admitted.\n\nInstance VEqReflexive : Reflexive veq :=\n  {\n  reflexivity := veq_equiv_refl;\n  }.\n\nInstance VEqSymmetric : Symmetric veq :=\n  {\n  symmetry := veq_equiv_symm;\n  }.\n\nInstance VEqTransitive : Transitive veq :=\n  {\n  transitivity := veq_equiv_trans\n  }.\n\nInstance VEqEquiv : Equivalence veq :=\n  {\n  Equivalence_Reflexive := VEqReflexive;\n  Equivalence_Symmetric := VEqSymmetric;\n  Equivalence_Transitive := VEqTransitive;\n  }.\n\nTheorem veq_refl : forall (v : V), v == v.\nProof.\n  intros.\n  reflexivity.\nQed.\n\nTheorem veq_symm : forall (u v : V), u == v -> v == u.\nProof.\n  intros u v H2.\n  rewrite H2.\n  reflexivity.\nQed.\n\nTheorem veq_trans : forall (u v w : V), u == v -> v == w -> u == w.\nProof.\n  intros u v w H2 H3.\n  rewrite H2.\n  rewrite <- H3.\n  reflexivity.\nQed.\n\n\nAdd Parametric Relation : V veq\n  reflexivity proved by veq_refl\n  symmetry proved by veq_symm\n  transitivity proved by veq_trans\n    as veq_equiv_rel.\n\n\nAdd Morphism vaddition with signature (veq ==> veq ==> veq) as vadd_ext1.\n  intros.\n  Admitted.\n\nAdd Morphism vscalar_mult with signature (eq ==> veq ==> veq) as vsmult_ext1.\n  intros.\n  Admitted.\n\n\nLtac unpack_vectorspace H :=\n  destruct H;\n  inversion isvectorspace0.\n\nLtac unpack_ring H :=\n  destruct H; inversion isring0.\n\nLtac unpack_field H :=\n  destruct H; inversion isfield0.\n\nLtac vby_definition H :=\n  destruct H;\n  inversion isvectorspace0;\n  simpl;\n  easy.\n\nLemma vaddition_assoc (u v w : V) : (u ⨥ v) ⨥ w == u ⨥ (v ⨥ w).\nProof.\n  vby_definition H1.\nQed.\n\nLemma vaddition_commu (u v : V) : u ⨥ v == v ⨥ u.\nProof.\n  vby_definition H1.\nQed.\n\nLemma vaddition_ident (v : V) : v ⨥ v0 == v.\nProof.\n  vby_definition H1.\nQed.\n\nLemma vaddition_inverse (v : V) : exists (w : V), v ⨥ w == v0.\nProof.\n  unpack_vectorspace H1.\n  specialize (vadd_inv0 v).\n  destruct vadd_inv0 as [w vadd_inv0].\n  exists w.\n  apply vadd_inv0.\nQed.\n\nLemma vmultiplicative_identity (v : V) : r1 * v == v.\nProof.\n  vby_definition H1.\nQed.\n\nLemma vdistributive1 (a : F) (u v : V) : a * (u ⨥ v) == a * u ⨥ a * v.\nProof.\n  vby_definition H1.\nQed.\n\nLemma vdistributive2 (a b : F) (v : V) : (a + b) * v == a * v ⨥ b * v.\nProof.\n  vby_definition H1.\nQed.\n\nLemma radd_inv_zero (x : F) : x + rainv x = r0.\nProof.\n  unpack_ring H.\n  simpl.\n  rewrite (Ropp_def x).\n  reflexivity.\nQed.\n\n(*1.29*)\nTheorem zero_times_vector (v : V) :\n  r0 * v == v0.\nProof.\n  unpack_field H0.\n  inversion F_R.\n  rewrite <- (Radd_0_l r0).\n  destruct H1; inversion isvectorspace0.\nAdmitted.\n\nLemma vadd_inverse_zero (v : V) : v ⨥ ⨪ v == v0.\nProof.\n  unfold vainv.\n  rewrite <- vmultiplicative_identity at 1.\n  rewrite vdistributive1.\n  rewrite (vmultiplicative_identity (rainv r1 * v)).\n  rewrite <- vdistributive2.\n  rewrite radd_inv_zero.\n  apply zero_times_vector.\nQed.\n\nLemma cancel_vadditive1 (u v : V) : u == v -> u ⨥ (⨪ u) == v ⨥ (⨪ u).\nProof.\n  intros H2.\n  rewrite vadd_inverse_zero.\nAdmitted.\n\nLemma add_to_both_sides1 (u v : V) : forall w, u == v -> w ⨥ u == w ⨥ v.\nProof.\n  intros.\n  rewrite H2.\n  reflexivity.\nQed.\n\nLemma add_to_both_sides2 (u v : V) : forall w, w ⨥ u == w ⨥ v -> u == v.\nProof.\n  intros.\n  apply add_to_both_sides1 with (w:= ⨪ w) in H2.\n  rewrite <- vaddition_assoc in H2; rewrite <- vaddition_assoc in H2 at 1.\n  rewrite vaddition_commu with (u:=⨪ w) in H2.\n  rewrite vadd_inverse_zero in H2.\n  rewrite vaddition_commu in H2; rewrite vaddition_ident in H2.\n  rewrite vaddition_commu in H2; rewrite vaddition_ident in H2.\n  apply H2.\nQed.\n\nLemma add_to_both_sides (u v : V) : forall w, u == v <-> w ⨥ u == w ⨥ v.\nProof.\n  split.\n  - apply add_to_both_sides1.\n  - apply add_to_both_sides2.\nQed.\n\nLemma vaddition_injective (v : V) : forall u w : V, v ⨥ u == v ⨥ w -> u == w.\nProof.\n  intros u w H2.\n  rewrite (add_to_both_sides2 u w v); easy.\nQed.\n\n(*1.25*)\nTheorem unique_vadditive_identity (v v0' : V) (H2 : forall u, u ⨥ v0' == u) : v0' == v0.\nProof.\n  specialize (H2 v0).\n  rewrite <- H2.\n  rewrite vaddition_commu.\n  rewrite vaddition_ident.\n  reflexivity.\nQed.\n\nLemma unique_vadditive_identity' (v v0' : V) : v ⨥ (⨪ v) == v0' -> v0' == v0.\nProof.\n  intros H2.\n  subst.\n  rewrite vadd_inverse_zero in H2.\n  symmetry.\n  apply H2.\nQed.\n\n(*1.26*)\nTheorem unique_vadditive_inverse\n        (*        (v z' : V) : v ⨥ ((- r1) * v) = z' -> v0 = z'. *)\n        (v : V) : forall (w w' : V) (H__w : v ⨥ w == v0) (H__w' : v ⨥ w' == v0),\n    w == w'.\nProof.\n  intros.\n  rewrite <- H__w' in H__w.\n  apply vaddition_injective in H__w.\n  apply H__w.\nQed.\n\n(*1.30*)\nTheorem number_times_zero (a : F) :\n  a * v0 == v0.\nProof.\n  unpack_vectorspace H1.\n  simpl.\n\nAdmitted.\n\n(*1.31*)\nTheorem minusone_times_vector (v : V) :\n  (rainv r1) * v = ⨪ v.\nProof.\n  unfold vainv.\n  reflexivity.\nQed.\n\n(*exercise 1.B.1*)\nTheorem vainv_involutive (v : V) :\n  ⨪ (⨪ v) = v.\nProof.\n  unfold vainv.\n  simpl.\n\nAdmitted.\n\n(*exercise 1.B.2*)\nTheorem zero_or (a : F) (u : V) :\n  a * u = v0 -> a = r0 \\/ u = v0.\nProof.\nAdmitted.\n\n(*End VS.\n\nSection Subspaces.\n*)\nRecord Subspace :=\n  {\n    set__subspace : Ensemble V;\n    additive_ident__subspace : set__subspace v0;\n    closed_addition__subspace :\n      forall (u w : V), set__subspace u -> set__subspace w -> set__subspace (u ⨥ w);\n    closed_smult__subspace :\n      forall (a : F) (u : V), set__subspace u -> set__subspace (a * u);\n  }.\n\nDefinition biplus__subset (U W : Ensemble V) : Ensemble V :=\n  fun v => exists (u w : V), U u -> W w -> v == u ⨥ w.\n\nDefinition empty_set : Ensemble V :=\n  fun u => False.\n\nDefinition plus__subset {n : nat} (Un : t (Ensemble V) n) : Ensemble V :=\n  fold_left biplus__subset empty_set Un.\n\nContext (U W : Subspace).\n\n\n\nInfix \"∔\" := (fun U1 => fun U2 => biplus__subset (set__subspace U1) (set__subspace U2)) (at level 50).\n\n\n\nDefinition bi_smallest_containing_subspace (U W : Subspace) : Prop :=\n  Included V (set__subspace U) (U ∔ W) /\\\n  Included V (set__subspace W) (U ∔ W) /\\\n  (forall (X : Subspace),\n      Included V (set__subspace U) (set__subspace X) ->\n      Included V (set__subspace W) (set__subspace X) ->\n      Included V (U ∔ W) (set__subspace X)).\n\nTheorem smallest_containing_subspace2 : bi_smallest_containing_subspace U W.\nProof.\n  unfold bi_smallest_containing_subspace, Included, Ensembles.In in *;\n    intros;\n    split;\n    try split;\n    intros.\n  - unfold biplus__subset.\n    exists x. exists v0.\n    intros.\n    rewrite vaddition_ident.\n    reflexivity.\n  - unfold biplus__subset.\n    exists v0. exists x.\n    intros.\n    rewrite vaddition_commu.\n    rewrite vaddition_ident.\n    reflexivity.\n  - unfold biplus__subset in H4; destruct H4 as [u [w H4]].\n    inversion X as [X' zero_in_X X_closed_addition _].\n    simpl.\nAdmitted.\n\nTheorem singleton_zero_closed_addition (u w : V) : u == v0 -> w == v0 -> u ⨥ w == v0.\nProof.\n  intros.\n  rewrite H2.\n  rewrite H3.\n  rewrite vaddition_ident.\n  reflexivity.\nQed.\n\nTheorem singleton_zero_closed_smult (a : F) (u : V) : u == v0 -> a * u == v0.\nProof.\n  intros.\nAdmitted.\n\nDefinition singleton_zero : Subspace :=\n  {|\n  set__subspace := fun v => v == v0 ;\n  additive_ident__subspace := (veq_refl v0) ;\n  closed_addition__subspace := singleton_zero_closed_addition ;\n  closed_smult__subspace := singleton_zero_closed_smult\n  |}.\n\nDefinition Directsum2'\n           (U1 U2 : Subspace)\n           (H : (forall (u1 u2 : V), set__subspace U1 u1 -> set__subspace U2 u2 ->\n                                u1 ⨥ u2 = v0 -> (u1 == v0) /\\ (u2 == v0)))\n  : Subspace\n  :=\n\n    (*\n      function subspace -> subspace -> subspace\n      Proposition: subspace -> subspaces -> (a belief that zero can be written uniquely)\n     *)\n\nRecord Directsum2 :=\n  {\n  U1 : Subspace;\n  U2 : Subspace;\n  zero_unique2 :\n    forall (u1 u2 : V), set__subspace U1 u1 -> set__subspace U2 u2 ->\n                   u1 ⨥ u2 = v0 -> (u1 == v0) /\\ (u2 == v0)\n  }.\n\n(*1.45*)\n\nTheorem direct_sum_of_two_subspaces (U W : Subspace) :\n  Build_Directsum2 U W <-> Intersection V (set__subspace U) (set__subspace W) = singleton_zero.\n\nInductive even (n : nat) : Prop :=\n| ev0 : even 0\n| ev__SS (n : nat) : even n.\n\n\nRecord Directsum :=\n  {\n  n : nat;\n  Un : t Subspace n;\n  vn : t V n;\n  zero_unique :\n\n  }\n\n\n\n    End VS.\n", "meta": {"author": "quinn-dougherty", "repo": "ladr", "sha": "a3137394831791ad29c5bbfe6241d1fb233d67cb", "save_path": "github-repos/coq/quinn-dougherty-ladr", "path": "github-repos/coq/quinn-dougherty-ladr/ladr-a3137394831791ad29c5bbfe6241d1fb233d67cb/src/classes/Classes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7334625082047195}}
{"text": "From Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nRequire Export Coq.Strings.String.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\n\n(** Documentation for the standard library can be found at\n    http://coq.inria.fr/library/.\n\n    The [Search] command is a good way to look for theorems involving\n    objects of specific types.  Take a minute now to experiment with it. *)\n\n(* ################################################################# *)\n(** * Identifiers *)\nDefinition eqb_string (x y : string) : bool :=\n  if string_dec x y then true else false.\n\n(** (The function [string_dec] comes from Coq's string library.\n    If you check the result type of [string_dec], you'll see that it\n    does not actually return a [bool], but rather a type that looks\n    like [{x = y} + {x <> y}], called a [sumbool], which can be\n    thought of as an \"evidence-carrying boolean.\"  Formally, an\n    element of [sumbool] is either a proof that two things are equal\n    or a proof that they are unequal, together with a tag indicating\n    which.  But for present purposes you can think of it as just a\n    fancy [bool].) *)\n\n(** Now we need a few basic properties of string equality... *)\nTheorem eqb_string_refl : forall s : string, true = eqb_string s s.\nProof. intros s. unfold eqb_string. destruct (string_dec s s) as [|Hs].\n  - reflexivity.\n  - destruct Hs. reflexivity.\nQed.\n\nTheorem eqb_string_true_iff : forall x y : string,\n    eqb_string x y = true <-> x = y.\nProof.\n   intros x y.\n   unfold eqb_string.\n   destruct (string_dec x y) as [|Hs].\n   - subst. split. reflexivity. reflexivity.\n   - split.\n     + intros contra. discriminate contra.\n     + intros H. rewrite H in Hs. destruct Hs. reflexivity.\nQed.\n\nTheorem eqb_string_false_iff : forall x y : string,\n    eqb_string x y = false <-> x <> y.\nProof.\n  intros x y. rewrite <- eqb_string_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This handy variant follows just by rewriting: *)\n\nTheorem false_eqb_string : forall x y : string,\n   x <> y -> eqb_string x y = false.\nProof.\n  intros x y. rewrite eqb_string_false_iff.\n  intros H. apply H. Qed.\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about its behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the very same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps. *)\n\n(** We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A : Type) := string -> A.\n\n(** Intuitively, a total map over an element type [A] is just a\n    function that can be used to look up [string]s, yielding [A]s. *)\n\n(** The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any string. *)\n\nDefinition t_empty {A : Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A : Type} (m : total_map A)\n                    (x : string) (v : A) :=\n  fun x' => if eqb_string x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming:\n    [t_update] takes a _function_ [m] and yields a new function\n    [fun x' => ...] that behaves like the desired map. *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) \"foo\" true)\n           \"bar\" true.\n\n(*Notation*)\n\nNotation \"'_' '!->' v\" := (t_empty v)\n  (at level 100, right associativity).\n\nExample example_empty := (_ !-> false).\n\n(** We then introduce a convenient notation for extending an existing\n    map with some bindings. *)\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n                                (at level 100, v at next level, right associativity).\n\nDefinition examplemap' :=\n  ( \"bar\" !-> true;\n    \"foo\" !-> true;\n    _     !-> false\n  ).\n\nExample update_example1 : examplemap' \"baz\" = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap' \"foo\" = true.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap' \"quux\" = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap' \"bar\" = true.\nProof. reflexivity. Qed.\n\n\nLemma t_apply_empty : forall (A : Type) (x : string) (v : A),\n    (_ !-> v) x = v.\nProof.\n  intros. unfold t_empty . reflexivity. Qed. \n(** [] *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id id1 id2 :=\n  match id1,id2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n  end.\nCheck @eqb_string_refl. \n\nLemma t_update_eq : forall (A : Type) (m : total_map A) x v,\n    (x !-> v ; m) x = v.\nProof.\n  intros. unfold t_update. rewrite <- eqb_string_refl. reflexivity. Qed. \n\n  (** Vr2_ unfold eqb_string. destruct (string_dec x x) as [|Hx] .\n  -reflexivity.\n   -rewrite beq_id_refl  *)\n\nTheorem t_update_neq : forall (A : Type) (m : total_map A) x1 x2 v,\n    x1 <> x2 ->\n    (x1 !-> v ; m) x2 = m x2.\nProof.\n  intros.  unfold t_update. rewrite false_eqb_string .\n  - reflexivity.\n    - apply H. Qed. \n\n\nLemma t_update_shadow : forall (A : Type) (m : total_map A) x v1 v2,\n    (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\n  intros. unfold t_update. extensionality i . remember (eqb_string x i) as e; induction e.\n  -reflexivity. \n   -reflexivity. Qed. \n\nLemma eqb_stringP : forall x y : string,\n    reflect (x = y) (eqb_string x y).\nProof.\n  intros. apply iff_reflect. rewrite eqb_string_true_iff. reflexivity. Qed. \n \n\n\nTheorem t_update_same : forall (A : Type) (m : total_map A) x,\n    (x !-> m x ; m) = m.\nProof.\n (* intros. unfold t_update. extensionality i. remember (eqb_string x i) as e; induction e. trivial.\n  -simpl. symmetry in Heqe. apply eqb_string_true_iff in Heqe. rewrite Heqe. reflexivity.\n   -simpl.reflexivity.*)\nAdmitted. \n   (** [] *)\n\n\nTheorem t_update_permute : forall (A : Type) (m : total_map A)\n                                  v1 v2 x1 x2,\n    x2 <> x1 ->\n    (x1 !-> v1 ; x2 !-> v2 ; m)\n    =\n    (x2 !-> v2 ; x1 !-> v1 ; m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A : Type) := total_map (option A).\n\nDefinition empty {A : Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A : Type} (m : partial_map A)\n           (x : string) (v : A) :=\n  (x !-> Some v ; m).\n\n(** We introduce a similar notation for partial maps: *)\nNotation \"x '|->' v ';' m\" := (update m x v)\n  (at level 100, v at next level, right associativity).\n\n(** We can also hide the last case when it is empty. *)\nNotation \"x '|->' v\" := (update empty x v)\n  (at level 100).\n\nExample examplepmap :=\n  (\"Church\" |-> true ; \"Turing\" |-> false).\n\n(** We now straightforwardly lift all of the basic lemmas about total\n    maps to partial maps.  *)\n\nLemma apply_empty : forall (A : Type) (x : string),\n    @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall (A : Type) (m : partial_map A) x v,\n    (x |-> v ; m) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (A : Type) (m : partial_map A) x1 x2 v,\n    x2 <> x1 ->\n    (x2 |-> v ; m) x1 = m x1.\nProof.\n  intros A m x1 x2 v H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall (A : Type) (m : partial_map A) x v1 v2,\n    (x |-> v2 ; x |-> v1 ; m) = (x |-> v2 ; m).\nProof.\n  intros A m x v1 v2. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall (A : Type) (m : partial_map A) x v,\n    m x = Some v ->\n    (x |-> v ; m) = m.\nProof.\n  intros A m x v H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (A : Type) (m : partial_map A)\n                                x1 x2 v1 v2,\n    x2 <> x1 ->\n    (x1 |-> v1 ; x2 |-> v2 ; m) = (x2 |-> v2 ; x1 |-> v1 ; m).\nProof.\n  intros A m x1 x2 v1 v2. unfold update.\n  apply t_update_permute.\nQed.\n", "meta": {"author": "taniaadb", "repo": "sympath-coq", "sha": "affded6de6aba7eada68d0a9cae33ac7290d01ab", "save_path": "github-repos/coq/taniaadb-sympath-coq", "path": "github-repos/coq/taniaadb-sympath-coq/sympath-coq-affded6de6aba7eada68d0a9cae33ac7290d01ab/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.733462503094527}}
{"text": "From Undecidability.Shared.Libs.PSL Require Import Base. \nFrom Undecidability.Shared.Libs.PSL Require Import FiniteTypes. \nFrom Complexity.Libs Require Import MorePrelim.\nRequire Import Lia.\n\n(** * 3-Covering Cards *)\n(** We define a variant of Covering Cards where the width is fixed to 3 and the offset is fixed to 1. \n  The resulting specialised definitions make the reduction from Turing machines easier to construct.\n\nMoreover, we generalise the definition of CC-steps (here called \"valid\") to arbitrary coversHead predicates. \nThis allows us to define the reduction from Turing machines using inductive predicates. \nThe list-based version (with a set of cards given as a list) is obtained as a special case.\n\nTo that end, we define two variants of 3-CC in this file:\n- the usual variant (TCC) which is based on lists of cards\n- the propositional variant PTCC over an abstract coversHead predicate \n*)\n\nSection abstractDefs.\n  Variable (X : Type). \n  Notation string := (list X). \n\n  (** We first define some general notions for an arbitrary coversHead predicate *)\n  Definition coversHeadAbstract := string -> string -> Prop. \n\n  Section fixCoversHead.\n    Variable (p : coversHeadAbstract). \n\n    (** coverings inside a string *)\n    Definition coversAt (i : nat) a b := p (skipn i a) (skipn i b).\n    Lemma coversAt_head a b : p a b <-> coversAt 0 a b. \n    Proof. \n      unfold coversAt.\n      rewrite <- firstn_skipn with (n:= 0) (l:= a) at 1.\n      rewrite <- firstn_skipn with (n:= 0) (l:= b) at 1.\n      repeat rewrite firstn_O; now cbn. \n    Qed. \n\n    Lemma coversAt_step a b x y (i:nat) : coversAt i a b <-> coversAt (S i) (x :: a) (y:: b). \n    Proof. intros. unfold coversAt. now cbn. Qed. \n\n    (** validity of a covering *)\n    Inductive valid : string -> string -> Prop :=\n    | validB: valid [] [] \n    | validSA a b x y: valid a b -> length a < 2 -> valid (x:: a) (y:: b)\n    | validS a b x y : valid a b -> p (x::a) (y::b) -> valid (x::a) (y::b). \n\n    Hint Constructors valid : core. \n\n    Lemma valid_vacuous a b : |a| <= 2 -> |a| = |b| -> valid a b. \n    Proof. \n      intros. \n      destruct a as [ | a1 a]; [ | destruct a as [ | a2 a]; [ | destruct a; cbn in *; [ | lia]]];\n      (destruct b as [ | b1 b]; [ | destruct b as [ | b2 b]; [ | destruct b; cbn in *; [ | lia]]]); \n          cbn in *; try congruence; eauto. \n    Qed. \n\n    Lemma valid_length_inv a b : valid a b -> length a = length b. \n    Proof. induction 1; cbn; lia. Qed. \n\n    Lemma relpower_valid_length_inv n a b : relpower valid n a b -> length a = length b. \n    Proof.  induction 1; [solve [eauto] | ]. apply valid_length_inv in H. congruence. Qed. \n\n    Lemma valid_base (a b c d e f : X) : valid [a; b ; c] [d; e; f] <-> p [a; b; c] [d; e; f]. \n    Proof. \n      split.\n      - intros; inv H. cbn in H5; lia. apply H5.  \n      - constructor 3. 2: apply H. repeat constructor.\n    Qed. \n\n    (** a different characterisation not allocardg vacuous coverings *)\n    (** this is conceptually nicer, but it has the problem that p is used in two cases, which makes some proofs harder *)\n    Inductive validDirect : string -> string -> Prop :=\n    | validDirectB a b : |a| = 3 -> |b| = 3 -> p a b -> validDirect a b \n    | validDirectS a b x y : validDirect a b -> p (x::a) (y::b) -> validDirect (x::a) (y::b). \n\n    Lemma validDirect_valid a b : validDirect a b <-> valid a b /\\ |a| >= 3. \n    Proof. \n      split. \n      - induction 1 as [a b H0 H1 H2 | a b x y H0 IH H1]. \n        + split; [ | lia]. list_length_inv. eauto 10.\n        + destruct IH as [IH H2]. split; [ | cbn; lia]. eauto 10.\n      - intros (H1 & H2). induction H1 as [ | a b x y H0 IH H1 | a b x y H0 IH H1]; cbn in H2; [easy | easy | ]. \n        list_length_inv. destruct a. \n        + clear IH. apply valid_length_inv in H0. cbn in H0. constructor; cbn; easy. \n        + constructor 2; [ | apply H1]. apply IH. now cbn. \n    Qed. \n\n    (** the explicit characterisation using bounded quantification *)\n    Definition validExplicit a b := \n      length a = length b \n      /\\ forall i, 0 <= i < length a - 2  -> coversAt i a b.\n\n    Lemma valid_iff a b :\n      valid a b <-> validExplicit a b.\n    Proof.\n      unfold validExplicit. split.\n      - induction 1. \n        + cbn; split; [reflexivity | ]. \n          intros; lia. \n        + destruct IHvalid as (IH1 & IH2). split; [cbn; congruence | ]. \n          cbn [length]; intros. lia. \n        + destruct IHvalid as (IH1 & IH2); split; [cbn; congruence | ].\n          cbn [length]; intros.\n          destruct i. \n          * eauto. \n          * assert (0 <= i < (|a|) - 2) by lia. eauto. \n      - revert b. induction a; intros b (H1 & H2). \n        + inv_list. constructor. \n        + inv_list. destruct (le_lt_dec 2 (length a0)). \n          * cbn [length] in H2.\n            assert (0 <= 0 < S (|a0|) - 2) by lia. specialize (H2 0 H) as H3. \n            eapply (@validS a0 b a x). 2: assumption. \n            apply IHa. split; [congruence | ]. \n            intros. assert (0 <= S i < S (|a0|) - 2) by lia. \n            specialize (H2 (S i) H4). eauto. \n          * constructor. \n            2: assumption. \n            apply IHa. split; [congruence | intros ]. \n            cbn [length] in H2. assert (0 <= S i < S(|a0|) - 2) by lia. \n            specialize (H2 (S i) H0); eauto. \n    Qed. \n  End fixCoversHead.\n\n  Hint Constructors valid : core. \n\n  (** valid is congruent with regards to coversHead predicates*)\n  Lemma valid_monotonous (p1 p2 : coversHeadAbstract) : (forall x y, p1 x y -> p2 x y) -> forall x y, valid p1 x y -> valid p2 x y.\n  Proof. \n    intros H x y. induction 1.  \n    - eauto. \n    - constructor 2; eauto. \n    - apply H in H1. eauto. \n  Qed. \n\n  Corollary valid_congruent p1 p2 : \n    (forall u v, p1 u v <-> p2 u v) \n    -> forall a b, valid p1 a b <-> valid p2 a b.\n  Proof.\n    intros; split; [apply valid_monotonous; intros; now apply H | ].\n    assert (forall u v, p2 u v <-> p1 u v) by (intros; now rewrite H).\n    apply valid_monotonous. intros; now apply H. \n  Qed.\n\nEnd abstractDefs. \n\nArguments valid {X}. \n#[export]\nHint Constructors valid : core. \n\nLtac inv_valid := match goal with\n                    | [ H : valid _ _ _ |- _] => inv H\n                  end;\n                  try match goal with\n                  | [ H : | _ | < 2 |- _] => solve [exfalso;cbn in H;nia]\n                  end.\n\n\n(** ** 3-CC using list-based cards *)\n\n(** use an explicit representation instead of vectors of size 3 since this will make the problem closer to the flattened extractable problem *)\nInductive TCCCardP (Sigma : Type) := {\n         cardEl1 : Sigma;\n         cardEl2 : Sigma;\n         cardEl3 : Sigma\n       }.\n\nInductive TCCCard (Sigma : Type) := {\n          prem : TCCCardP Sigma;\n          conc : TCCCardP Sigma\n        }.\n\nDefinition TCCCardP_to_list (sig : Type) (a : TCCCardP sig) := match a with Build_TCCCardP a b c => [a; b; c] end. \nCoercion TCCCardP_to_list : TCCCardP >-> list. \n\nDeclare Scope cc_scope. \nLocal Open Scope cc_scope.\nNotation \"'{' a ',' b ',' c '}'\" := (Build_TCCCardP a b c) (format \"'{' a ',' b ',' c '}'\") : cc_scope. \nNotation \"a / b\" := ({|prem := a; conc := b|}) : cc_scope. \n\nRecord TCC := {\n               Sigma : finType;\n               init : list Sigma;  (* length is encoded implicitly as the length of init*) \n               cards : list (TCCCard Sigma);\n               final : list (list Sigma);\n               steps : nat\n             }.\n\nDefinition TCC_wellformed C := length (init C) >= 3. \n\nImplicit Type (C : TCC).\n\n(** the final constraint*)\nDefinition satFinal (X : Type) final (s : list X) := \n  exists subs, subs el final /\\ substring subs s.\n\n(** specific definitions and results for list-based cards*)\nSection fixInstance.\n  Variable (Sigma : Type).\n  Variable (init : list Sigma).\n  Variable (cards : list (TCCCard Sigma)).\n  Variable (final : list (list Sigma)).\n  Variable (steps : nat). \n\n  Notation string := (list Sigma). \n  Notation card := (TCCCard Sigma).\n\n  Implicit Type (s a b: string). \n  Implicit Type (w card : card).\n  Implicit Type (x y : Sigma).\n\n  Definition isCard w := w el cards.\n  Lemma isRule_length w : length (prem w) = 3 /\\ length (conc w) = 3.\n  Proof. \n    intros. destruct w. \n    cbn. destruct prem0, conc0. now cbn. \n  Qed. \n\n  (** we now define a concrete covering predicate based on a set of cards *)\n  Definition coversHead card a b := prefix (prem card) a /\\ prefix (conc card) b.\n\n  Lemma coversHead_length_inv card a b : coversHead card a b -> isCard card -> length a >= 3 /\\ length b >= 3. \n  Proof. \n    intros. unfold coversHead, prefix in *. firstorder.\n    - rewrite H. rewrite app_length, (proj1 (isRule_length card)). lia.  \n    - rewrite H1. rewrite app_length, (proj2 (isRule_length card)). lia. \n  Qed. \n\n  Definition coversHeadList cards a b := exists card, card el cards /\\ coversHead card a b. \n\n  Lemma coversHeadList_subset cards1 cards2 a b :\n    cards1 <<= cards2 -> coversHeadList cards1 a b -> coversHeadList cards2 a b.\n  Proof. intros H (r & H1 & H2). exists r. split; [ apply H, H1 | apply H2]. Qed. \n\n  Lemma coversHead_card_inv r a b (σ1 σ2 σ3 σ4 σ5 σ6 : Sigma) : coversHead r (σ1 :: σ2 :: σ3 :: a) (σ4 :: σ5 :: σ6 :: b) -> r = {σ1, σ2 , σ3} / {σ4 , σ5, σ6}. \n  Proof. \n    unfold coversHead. unfold prefix. intros [(b' & H1) (b'' & H2)]. destruct r. destruct prem0, conc0. cbn in H1, H2. congruence. \n  Qed. \n\n  Lemma coversAt_HeadList_add_at_end i (a b c d : string) : \n    coversAt (coversHeadList cards) i a b -> coversAt (coversHeadList cards) i (a ++ c) (b ++ d). \n  Proof. \n    intros. unfold coversAt, coversHeadList in *.\n    destruct H as (card & H0 & H). exists card; split; [assumption | ]. \n    unfold prefix in *. destruct H as ((b1 & H1) & (b2 & H2)). \n    split.\n    - exists (b1 ++ c). rewrite app_assoc. apply skipn_app2 with (c := prem card ++ b1); [ | assumption]. \n      destruct card, prem. now cbn.  \n    - exists (b2 ++ d). rewrite app_assoc. apply skipn_app2 with (c := conc card ++ b2); [ | assumption]. \n      destruct card, conc. now cbn. \n   Qed. \nEnd fixInstance. \n\n\n(** we define it using the coversHead_pred rewrite predicate *)\nDefinition TCCLang (C : TCC) := \n  TCC_wellformed C \n  /\\ exists (sf : list (Sigma C)), relpower (valid (coversHeadList (cards C))) (steps C) (init C) sf \n    /\\ satFinal (final C) sf. \n\n(** ** variant P-3-CC using propositional rules (defined via inductive predicates) *)\n\nRecord PTCC := {\n             PSigma : finType;\n             Pinit : list PSigma;  (* length is encoded implicitly as the length of init*) \n             Pcards : PSigma -> PSigma -> PSigma -> PSigma -> PSigma -> PSigma -> Prop;\n             Pfinal : list (list PSigma);\n             Psteps : nat\n           }.\n\nDefinition PTCC_wellformed D := length (Pinit D) >= 3. \n\nSection fixRulePred.\n  (** We define the equivalent of coversHeadList for predicate-based rules  *)\n\n  Variable (X : Type).\n  Definition cardPred := X -> X -> X -> X -> X -> X -> Prop.\n  Variable (p : cardPred). \n\n  Inductive coversHeadInd: list X -> list X -> Prop :=\n    | coversHead_indC (x1 x2 x3 x4 x5 x6 : X) s1 s2 : \n        p x1 x2 x3 x4 x5 x6 -> coversHeadInd (x1 :: x2 :: x3 :: s1) (x4 :: x5 :: x6 :: s2). \n\n  Hint Constructors coversHeadInd : core. \n\n  (** a few facts which will be useful *)\n  Lemma coversHeadInd_tail_invariant (γ1 γ2 γ3 γ4 γ5 γ6 : X) s1 s2 s1' s2' :\n    coversHeadInd (γ1 :: γ2 :: γ3 :: s1) (γ4 :: γ5 :: γ6 :: s2) <-> coversHeadInd (γ1 :: γ2 :: γ3 :: s1') (γ4 :: γ5 :: γ6 :: s2').\n  Proof. split; intros; inv H; eauto. Qed. \n\n  Corollary coversHeadInd_rem_tail (γ1 γ2 γ3 γ4 γ5 γ6 : X) h1 h2 :\n    coversHeadInd [γ1; γ2; γ3] [γ4; γ5; γ6] <-> coversHeadInd (γ1 :: γ2 :: γ3 :: h1) (γ4 :: γ5 :: γ6 :: h2).\n  Proof. now apply coversHeadInd_tail_invariant. Qed. \n\n  Lemma coversHeadInd_append_invariant (γ1 γ2 γ3 γ4 γ5 γ6 : X) s1 s2 s1' s2' :\n    coversHeadInd (γ1 :: γ2 :: γ3 :: s1) (γ4 :: γ5 :: γ6 :: s2) <-> coversHeadInd (γ1 :: γ2 :: γ3 :: s1 ++ s1') (γ4 :: γ5 :: γ6 :: s2 ++ s2').\n  Proof. now apply coversHeadInd_tail_invariant. Qed.\n\n  Lemma coversAt_coversHeadInd_add_at_end i a b h1 h2 :\n    coversAt coversHeadInd i a b -> coversAt coversHeadInd i (a ++ h1) (b ++ h2).\n  Proof. \n    intros. unfold coversAt in *. inv H; symmetry in H0; symmetry in H1; repeat erewrite skipn_app2; eauto; try congruence; cbn; eauto. \n  Qed.\n\n  Lemma coversAt_coversHeadInd_rem_at_end i a b h1 h2 :\n    coversAt coversHeadInd i (a ++ h1) (b ++ h2) -> i < |a| - 2 -> i < |b| - 2 -> coversAt coversHeadInd i a b.\n  Proof. \n    intros. unfold coversAt in *.\n    assert (i <= |a|) by lia. destruct (skipn_app3 h1 H2) as (a' & H3 & H4). rewrite H3 in H. \n    assert (i <= |b|) by lia. destruct (skipn_app3 h2 H5) as (b' & H6 & H7). rewrite H6 in H. \n    clear H2 H5.\n    rewrite <- firstn_skipn with (l := a) (n := i) in H4 at 1. apply app_inv_head in H4 as <-. \n    rewrite <- firstn_skipn with (l := b) (n := i) in H7 at 1. apply app_inv_head in H7 as <-. \n    specialize (skipn_length i a) as H7. specialize (skipn_length i b) as H8. \n    remember (skipn i a) as l. do 3 (destruct l as [ | ? l] ; [cbn in H7; lia | ]). \n    remember (skipn i b) as l'. do 3 (destruct l' as [ | ? l']; [cbn in H8; lia | ]). \n    cbn in H. rewrite coversHeadInd_tail_invariant in H. apply H. \n  Qed. \n \nEnd fixRulePred. \n\n#[export]\nHint Constructors coversHeadInd : core. \n\nDefinition cardPred_subs (X : Type) (p1 p2 : cardPred X) := forall x1 x2 x3 x4 x5 x6, p1 x1 x2 x3 x4 x5 x6 -> p2 x1 x2 x3 x4 x5 x6.\n\nLemma coversHeadInd_monotonous (X : Type) (p1 p2 : cardPred X) : cardPred_subs p1 p2 -> forall x y, coversHeadInd p1 x y -> coversHeadInd p2 x y.\nProof. \n  intros H x y H1. inv H1. apply H in H0. eauto.  \nQed. \n\nLemma coversHeadInd_congruent (X : Type) (p1 p2 : cardPred X) : (forall x1 x2 x3 x4 x5 x6, p1 x1 x2 x3 x4 x5 x6 <-> p2 x1 x2 x3 x4 x5 x6) -> forall x y, coversHeadInd p1 x y <-> coversHeadInd p2 x y.\nProof.  intros H; intros. split; apply coversHeadInd_monotonous; unfold cardPred_subs; apply H. Qed. \n\n#[export]\nHint Constructors coversHeadInd : core.\n\nDefinition PTCCLang (C : PTCC) := \n  PTCC_wellformed C \n  /\\ exists (sf : list (PSigma C)), relpower (valid (coversHeadInd (@Pcards C))) (Psteps C) (Pinit C) sf \n    /\\ satFinal (Pfinal C) sf. \n\n(** ** results for agreement of P-3-CC and 3-CC *)\nDefinition cards_list_ind_agree {X : Type} (p : X -> X -> X -> X -> X -> X -> Prop) (l : list (TCCCard X)) :=\n  forall x1 x2 x3 x4 x5 x6, p x1 x2 x3 x4 x5 x6 <-> {x1, x2, x3} / {x4, x5, x6} el l. \n\nLemma cards_list_ind_coversHead_agree {X : Type} (p : X -> X -> X -> X -> X -> X -> Prop) (l : list (TCCCard X)) :\n  cards_list_ind_agree p l -> forall s1 s2, (coversHeadInd p s1 s2 <-> coversHeadList l s1 s2). \nProof. \n  intros; split; intros. \n  + inv H0. exists ({x1, x2, x3} / {x4, x5, x6}). split.\n    * apply H, H1. \n    * split; unfold prefix; cbn; eauto. \n  + destruct H0 as (r & H1 & ((b & ->) & (b' & ->))). \n    destruct r as [prem0 conc0], prem0, conc0. cbn. constructor. apply H, H1.  \nQed.\n\nLemma tpr_ptpr_agree (X : finType) s final steps indcards (listcards : list (TCCCard X)): \n  cards_list_ind_agree indcards listcards \n  -> (TCCLang (Build_TCC s listcards final steps) <-> PTCCLang (Build_PTCC s indcards final steps)).\nProof. \n  intros; split; intros (H0 & sf & H1 & H2); cbn in *. \n  - split; [apply H0 | ]. \n    exists sf; cbn. split; [ | apply H2]. \n    eapply relpower_congruent; [ apply valid_congruent, cards_list_ind_coversHead_agree, H | apply H1].  \n  - split; [apply H0 | ].  \n    exists sf; cbn. split; [ | apply H2]. \n    eapply relpower_congruent; [ apply valid_congruent; symmetry; apply cards_list_ind_coversHead_agree, H | apply H1]. \nQed. \n\n", "meta": {"author": "uds-psl", "repo": "coq-library-complexity", "sha": "5a996877f16fd6fe16dc5f0c3b933486957869df", "save_path": "github-repos/coq/uds-psl-coq-library-complexity", "path": "github-repos/coq/uds-psl-coq-library-complexity/coq-library-complexity-5a996877f16fd6fe16dc5f0c3b933486957869df/theories/NP/SAT/CookLevin/Subproblems/TCC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7334624934112277}}
{"text": "Theorem plus_O_n: forall n : nat , (plus O n) = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_O_n': forall n : nat , (O + n) = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_O_n'': forall n : nat, (plus O n) = n.\nProof.\n  intros n. reflexivity. Qed.\n\n\nTheorem plus_1_1 : forall n : nat, ((S O) + n) = (S n).\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem mult_0_1: forall n:nat, (O * n) = O.\nProof.\n  intros n. reflexivity. Qed.\n\n\nTheorem mult_0_11: forall n:nat, (mult O n) = O.\nProof.\n  intros n. reflexivity. Qed.\n\n\nTheorem plus_n_0: forall n:nat, n = (n + O).\nProof.\nintros n. \nAdmitted.\n\nTheorem plus_id_example: forall n m :nat,\nn = m ->\nn + n = m + m.\nProof.\nAdmitted.\n\n\nTheorem plus_id_exercise: forall n m o : nat,\nn = m -> m = o -> n + m = m + o.\nProof.\nintros n m o.\nintros H.\nintros J.\nrewrite H.\nrewrite J.\nreflexivity.\nQed.\n\n\nTheorem mult_0_plus : forall n m: nat,\n(O + n) * m = n * m.\nProof.\nintros n m.\nsimpl.\nreflexivity.\nQed.\n\nTheorem mult_0_plus' : forall n m: nat,\n(O + n) * m = n * m.\nProof.\nintros n m.\nrewrite mult_0_plus.\nreflexivity.\nQed.\n\n\nTheorem mult_0_plus'' : forall n m: nat,\n(O + n) * m = n * m.\nProof.\nintros n m.\nrewrite plus_O_n'.\nreflexivity.\nQed.\n\n\n\nTheorem mult_S_1 : forall n m : nat,\nm = S n ->\nm * ((S O) + n) = m * m.\nProof.\nintros n m.\nintros H.\nrewrite plus_1_1.\nrewrite <- H.\nreflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\nbeq_nat (n + (S O)) O = false.\nProof.\nintros n.\ndestruct n as [| n'].\nreflexivity.\nreflexivity.\nQed.\n\nTheorem plus_1_neq_0_firsttry' : forall n : nat,\nbeq_nat (n + (S O)) O = false.\nProof.\nintros n.\ndestruct n as [| n'].\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n(negb (negb b)) = b.\nProof.\nintro b.\nsimpl.\ndestruct b.\n- simpl.\nreflexivity.\n- simpl.\nreflexivity.\nQed.\n\nTheorem andb_commutative : forall b c: bool, \nandb b c = andb c b.\nProof.\nintros b c.\ndestruct b.\ndestruct c.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\ndestruct c.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\nTheorem andb_commutative_with_braces : forall b c:bool,\nandb b c = andb c b.\nProof.\nintros b c.\ndestruct b.\n{ destruct c.\n{ simpl. reflexivity. }\n{ simpl. reflexivity. } }\n{ destruct c.\n  { simpl. reflexivity. }\n{ simpl. reflexivity. } }\nQed.\n\nTheorem andb3_exchange: forall b c d,\nandb (andb b c) d = andb (andb b d) c.\nintros b c d.\n{ destruct b.\n{ destruct c.\n{ destruct d.\n{ simpl.\nreflexivity. }\n{ simpl.\nreflexivity. } }\n{ destruct d. \n{ simpl.\nreflexivity. }\n{ simpl.\nreflexivity. } }\n{ destruct c.\n{ destruct d.\n{ simpl.\nreflexivity. } \n{ simpl.\nreflexivity. } }\n{ destruct d.\n{ simpl.\nreflexivity. }\n{ simpl.\nreflexivity. } } } } } \nQed.\n\nTheorem plus_1_neq_0''' : forall n : nat,\nbeq_nat (n + (S O)) O = false.\nProof.\nintros [|n].\nreflexivity.\nreflexivity.\nQed.\n\nTheorem andb_true_elim2: forall b c: bool,\nandb b c = true -> c = true.\nProof.\nintros b c.\n{ destruct b.\n{ destruct c.\n{ simpl.\nintros H1.\nreflexivity. }\n\n{ simpl.\nintros H2.\nrewrite H2.\nreflexivity. } }\n\n{ destruct c.\n{ simpl.\nintros H3.\nreflexivity. }\n\n{ simpl.\nintros H4.\nrewrite H4.\nreflexivity. } } }\n\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n: nat,\nbeq_nat O (S n) = false.\nProof.\nintros n.\n{ simpl.\nreflexivity. }\nQed.\n\nTheorem identity_fn_applied_twice : forall (f : bool -> bool), \n(forall (x : bool), f x = x) -> \nforall (b : bool),\nf (f b) = b.\nProof.\nintros f.\nintros H.\nintros b0.\nrewrite H.\nrewrite H.\nreflexivity.\nQed.\n\nTheorem andb_eq_orb: \nforall (b c : bool),\n(andb b c) = (orb b c) -> \nb=c.\nProof.\nintros b0.\nintros c.\ndestruct b0.\ndestruct c.\nsimpl.\nintros H.\nreflexivity.\n\nsimpl.\nintros H1.\nrewrite H1.\nreflexivity.\n\ndestruct c.\nsimpl.\nintros H2.\nrewrite H2.\nreflexivity.\n\nsimpl.\nintros H3.\nreflexivity.\n\nQed.\n\n\n", "meta": {"author": "soumyadsanyal", "repo": "sf", "sha": "6103ef0efb46d1e9d4f34f5f8269cdc1a554afc7", "save_path": "github-repos/coq/soumyadsanyal-sf", "path": "github-repos/coq/soumyadsanyal-sf/sf-6103ef0efb46d1e9d4f34f5f8269cdc1a554afc7/proofs1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.733462339751552}}
{"text": "(* Software Foundations Chapter 3 : Lists *)\nAdd LoadPath \"./bin\".\nRequire Import lesson1_Basics.\nRequire Import lesson2_Induction.\n\nModule NatList.\n\n\n\n(**************************************************\n  Exercise: 1 star (snd_fst_is_swap)\n **************************************************)\n\nInductive natprod : Type :=\n  pair : nat -> nat -> natprod.\n\nNotation \"( x , y )\" := (pair x y).\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n    | (x,y) => (y,x)\n  end.\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\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  reflexivity.\nQed.\n\n\n\n(**************************************************\n  Exercise: 1 star, optional (fst_swap_is_snd)\n **************************************************)\n\nTheorem fst_swap_is_snd : forall (p : natprod),\n                            fst (swap_pair p) = snd p.\nProof.\n  intros p.\n  destruct p as (m,n).\n  reflexivity.\nQed.\n\n\n\n(**************************************************\n  Exercise: 2 stars (list_funs)\n  Complete the definitions of nonzeros, oddmembers and countoddmembers below. Have a look at the tests to understand what these functions should do.\n **************************************************)\n\nInductive natlist : Type :=\n| nil : natlist\n| cons : nat -> natlist -> natlist.\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\nNotation \"x + y\" := (plus x y) (at level 50, left associativity).\n\nFixpoint nonzeros (l : natlist) : natlist :=\n  match l with\n    | nil => nil\n    | O :: 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 :=\nmatch l with\n| nil => nil\n| h :: t => match evenb h with\n            | true => oddmembers t\n            | false => h :: oddmembers t\n            end\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 => match evenb h with\n            | true => countoddmembers t\n            | false => S (countoddmembers t)\n            end\nend.\n\nExample test_countoddmembers1: countoddmembers [1,0,3,1,4,5] = 4.\nProof. simpl. 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\n(**************************************************\n  Exercise: 3 stars, advanced (alternate)\n  Complete the definition of alternate, which \"zips up\" two lists into one, alternating between elements taken from the first list and elements from the second. See the tests below for more specific examples.\n\n  Note: one natural and elegant way of writing alternate will fail to satisfy Coq's requirement that all Fixpoint definitions be \"obviously terminating.\" If you find yourself in this rut, look for a slightly more verbose solution that considers elements of both lists at the same time. (One possible solution requires defining a new kind of pairs, but this is not the only way.)\n **************************************************)\n\nInductive natlistprod : Type :=\n  lpair : natlist -> natlist -> natlistprod.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match lpair l1 l2 with\n    | lpair nil nil => nil\n    | lpair nil l => l\n    | lpair l nil => l\n    | lpair (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].\nProof. simpl. 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. simpl. reflexivity. Qed. \nExample test_alternate4: alternate [] [20,30] = [20,30].\nProof. reflexivity. Qed. \n\n\n\n(**************************************************\n  Exercise: 3 stars (bag_functions)\n  Complete the following definitions for the functions count, sum, add, and member for bags.\n **************************************************)\n\nDefinition bag := natlist.\n\nFixpoint count (v : nat) (s : bag) : nat :=\nmatch s with \n| nil => 0\n| h :: t => match beq_nat v h with\n            | true => S (count v t)\n            | false => count v t\n            end\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 all the elements of a and of b. (Mathematicians usually define union on multisets a little bit differently, which is why we don't use that name for this operation.) For sum we're giving you a header that does not give explicit names to the arguments. Moreover, it uses the keyword Definition instead of Fixpoint, so even if you had names for the arguments, you wouldn't be able to process them recursively. The point of stating the question this way is to encourage you to think about whether sum can be implemented in another way — perhaps by using functions that have already been defined. *)\n\nFixpoint app (l1 l2 : natlist) : natlist := \n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y) \n                       (right associativity, at level 60).\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.\nProof. reflexivity. Qed.\n\nExample test_add2: count 5 (add 1 [1,4,1]) = 0.\nProof. reflexivity. Qed. \n\nFixpoint bgteq_nat (n : nat) (m : nat) :=\n  match (n, m) with\n    | (_ , O) => true\n    | (O , _) => false\n    | (S nn, S mm) => bgteq_nat nn mm\n  end.\n\nDefinition member (v:nat) (s:bag) : bool := \n  bgteq_nat (count v s) 1.\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\n(**************************************************\n  Exercise: 3 stars, optional (bag_more_functions)\n  Here are some more bag functions for you to practice with.\n**************************************************)\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\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. Proof. reflexivity. Qed. \nExample test_remove_one3: count 4 (remove_one 5 [2,1,4,5,1,4]) = 2. Proof. reflexivity. Qed. \nExample test_remove_one4: count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1. 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\n  end.\n\nExample test_remove_all1: count 5 (remove_all 5 [2,1,5,4,1]) = 0. Proof. reflexivity. Qed. \nExample test_remove_all2: count 5 (remove_all 5 [2,1,4,1]) = 0. Proof. reflexivity. Qed.\nExample test_remove_all3: count 4 (remove_all 5 [2,1,4,5,1,4]) = 2. Proof. reflexivity. Qed. \nExample test_remove_all4: count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0. Proof. reflexivity. Qed. \n\n\nFixpoint subset (s1:bag) (s2:bag) : bool :=\nmatch s1 with \n| nil => true\n| h :: t => andb (member h s2) (subset t (remove_one h s2))\nend.\n\nExample test_subset1: subset [1,2] [2,1,4,1] = true. Proof. reflexivity. Qed. \nExample test_subset2: subset [1,2,2] [2,1,4,1] = false. Proof. simpl. reflexivity. Qed. \n\n\n\n(**************************************************\n  Exercise: 3 stars (bag_theorem)\n  Write down an interesting theorem about bags involving the functions count and add, and prove it. Note that, since this problem is somewhat open-ended, it's possible that you may come up with a theorem which is true, but whose proof requires techniques you haven't learned yet. Feel free to ask for help if you get stuck!\n **************************************************)\n\nTheorem beq_n_n : forall (n : nat),\n                    beq_nat n n = true.\nProof.\n  intros n. induction n as [|nn].\n  simpl. reflexivity.\n  simpl. rewrite -> IHnn. reflexivity.\nQed.\n\nTheorem inc_count_by_one : forall (v1 v2 : nat) (s : bag),\n                             v1 = v2 -> count v1 (add v2 s) = 1 + count v1 s.\nProof.\n  intros v1 v2 s H.\n  unfold add.\n  rewrite <- H.\n  assert (Thm1 : forall (v : nat) (b : bag),\n                  count v (v::[]) = 1).\n   intros v E. simpl. rewrite -> beq_n_n. reflexivity.\n  simpl. rewrite -> beq_n_n. reflexivity.\nQed.  \n\n\n\n(**************************************************\n  Exercise: 3 stars (list_exercises)\n  More practice with lists.\n **************************************************)\n\nTheorem app_nil_end : forall l : natlist,\n                        l ++ [] = l.\nProof. \n  intro l. induction l as [| h t].\n  reflexivity. \n  simpl. rewrite -> IHt. reflexivity. \nQed.\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\nFixpoint rev (l:natlist) : natlist := \n  match l with\n  | nil => nil\n  | h :: t => snoc (rev t) h\n  end.\n\nTheorem cibele : forall (l : natlist) (n : nat),\n                   rev (snoc l n) = n :: (rev l).\nProof.\n intros l n. induction l as [| h t].\n simpl. reflexivity. \n simpl. rewrite -> IHt. simpl. reflexivity. \nQed. \n\nTheorem rev_involutive :  forall l : natlist,\n                            rev (rev l) = l.\nProof.\n intro l. induction l as [| h t].\n reflexivity. \n simpl. rewrite -> cibele. rewrite -> IHt. reflexivity. \nQed. \n \n(* There is a short solution to the next exercise. If you find yourself getting tangled up, step back and try to look for a simpler way. *)\n\nTheorem app_right : forall l1 l2 l3 : natlist,\n                      l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n  intros m1 m2 m3. induction m1 as [|h1 t1]. \n  reflexivity. \n  simpl. rewrite -> IHt1. reflexivity.\nQed.\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_right. \n  rewrite app_right. \n  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 [| nn ll]. reflexivity. \n simpl. rewrite <- IHll. reflexivity. \nQed. \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 [| h1 t1].\n  Case \"l1 is nil\".\n  simpl. rewrite -> app_nil_end. reflexivity. \n  Case \"l1 is some h::t\".\n  simpl. \n  rewrite -> snoc_append. \n  rewrite -> IHt1. \n  rewrite -> snoc_append. \n  rewrite -> app_right. \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. induction l1 as [|h1 t1].\n  Case \"l1 is an empty list\".\n  simpl. reflexivity.\n  Case \"l2 is not an empty list.\".\n  destruct h1 as [|n].\n  SCase \"the head of l1 is zero\".\n  simpl. intros l2.\n  rewrite -> IHt1.\n  reflexivity.\n  SCase \"the head of l1 is not zero\".\n  simpl. intros l2.\n  rewrite -> IHt1.\n  reflexivity.\nQed.\n\n\n\n(**************************************************\n  Exercise: 2 stars (list_design)\n  Design exercise:\n  Write down a non-trivial theorem involving cons (::), snoc, and app (++).\n  Prove it.\n **************************************************)\n\nTheorem tack : forall (n : nat) (l : natlist),\n                 snoc (n::l) n = n :: (snoc l n).\nProof.\n  intros n l. destruct l as [|h t].\n  Case \"The list is empty\".\n  simpl. reflexivity.\n  Case \"The list is not empty\".\n  simpl. reflexivity.\nQed.\n\n\n\n(**************************************************\n  Exercise: 3 stars, advanced (bag_proofs)\n  Here are a couple of little theorems to prove about your definitions about bags in the previous problem.\n**************************************************)\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  intros s. induction s as [|h t].\n  Case \"bag is empty\".\n  simpl. reflexivity.\n  Case \"bag is not empty\".\n  destruct h as [|n].\n  SCase \"the head is a zero\".\n  simpl. rewrite -> ble_n_Sn.\n  reflexivity.\n  SCase \"the head is not zero\".\n  simpl. rewrite -> IHt. reflexivity.\nQed.\n\n\n\n(**************************************************\n  Exercise: 3 stars, optional (bag_count_sum)\n  Write down an interesting theorem about bags involving the functions count and sum, and prove it.\n **************************************************)\n\n(* no, thanks *)\n\n\n\n(**************************************************\n  Exercise: 4 stars, advanced (rev_injective)\n  Prove 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 solve this exercise.\n **************************************************)\n\nFixpoint length (l : natlist) : nat :=\nmatch l with\n| nil => O\n| h :: t => S (length t)\nend.\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\n(**************************************************\n  Exercise: 2 stars (hd_opt)\n  Using the same idea, fix the hd function from earlier so we don't have to pass a default element for the nil case.\n **************************************************)\n \nInductive natoption : Type :=\n| Some : nat -> natoption\n| None : natoption.\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.\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\n(**************************************************\n  Exercise: 1 star, optional (option_elim_hd)\n  This exercise relates your new hd_opt to the old hd.\n **************************************************)\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n    | nil => default\n    | h :: t => h\n  end.\n\nDefinition option_elim (d : nat) (o : natoption) : nat :=\nmatch o with\n| Some nn => nn\n| None => d\nend.\n\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n                           hd default l = option_elim default (hd_opt l).\nProof. \n  intros l n. destruct l as [| h t].\n  reflexivity. reflexivity.\nQed.\n\n\n\n(**************************************************\n  Exercise: 2 stars (beq_natlist)\n  Fill in the definition of beq_natlist, which compares lists of numbers for equality. Prove that beq_natlist l l ypields true for every list l.\n **************************************************)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\nmatch 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 => if beq_nat h1 h2 \n                        then beq_natlist t1 t2\n                        else false\n            end\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 intro l. induction l as [| h t].\n Case \"arg is an empty list\".\n simpl. reflexivity. \n Case \"arg is not an empty lst.\".\n simpl. \n rewrite <- IHt. \n rewrite -> beq_n_n.\n reflexivity. \nQed.\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n| empty : dictionary\n| record : nat -> nat -> dictionary -> dictionary. \n\nDefinition insert (key value : nat) (d : dictionary) :=\n  (record key value d).\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\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. assert (H : beq_nat k k = true).  \n  induction k as [| kk]. \n  reflexivity. \n  simpl. rewrite -> IHkk. reflexivity. \n  rewrite -> H. reflexivity. \nQed. \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.\n intro H. \n simpl. rewrite -> H. reflexivity. \nQed. \n\nEnd Dictionary.\n\nEnd NatList.", "meta": {"author": "madsravn", "repo": "software_foundations", "sha": "2a7cf402b0a05430961018bd113fb4b2ec03b113", "save_path": "github-repos/coq/madsravn-software_foundations", "path": "github-repos/coq/madsravn-software_foundations/software_foundations-2a7cf402b0a05430961018bd113fb4b2ec03b113/lesson3_Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7334623298795121}}
{"text": "(** * Rel: Properties of Relations *)\n\n(** This short (and optional) chapter develops some basic definitions\n    and a few theorems about binary relations in Coq.  The key\n    definitions are repeated where they are actually used (in the\n    \\CHAPV2{Smallstep} chapter of _Programming Language Foundations_),\n    so readers who are already comfortable with these ideas can safely\n    skim or skip this chapter.  However, relations are also a good\n    source of exercises for developing facility with Coq's basic\n    reasoning facilities, so it may be useful to look at this material\n    just after the [IndProp] chapter. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export IndProp.\nCheck evenb.\n\n(* ################################################################# *)\n(** * Relations *)\n\n(** A binary _relation_ on a set [X] is a family of propositions\n    parameterized by two elements of [X] -- i.e., a proposition about\n    pairs of elements of [X].  *)\n\nDefinition relation (X: Type) := X -> X -> Prop.\n\n(** Confusingly, the Coq standard library hijacks the generic term\n    \"relation\" for this specific instance of the idea. To maintain\n    consistency with the library, we will do the same.  So, henceforth\n    the Coq identifier [relation] will always refer to a binary\n    relation between some set and itself, whereas the English word\n    \"relation\" can refer either to the specific Coq concept or the\n    more general concept of a relation between any number of possibly\n    different sets.  The context of the discussion should always make\n    clear which is meant. *)\n\n(** An example relation on [nat] is [le], the less-than-or-equal-to\n    relation, which we usually write [n1 <= n2]. *)\n\nPrint le.\n(* ====> Inductive le (n : nat) : nat -> Prop :=\n             le_n : n <= n\n           | le_S : forall m : nat, n <= m -> n <= S m *)\nCheck le : nat -> nat -> Prop.\nCheck le_ind.\nCheck le : relation nat.\nCheck le_ind.\n(** (Why did we write it this way instead of starting with [Inductive\n    le : relation nat...]?  Because we wanted to put the first [nat]\n    to the left of the [:], which makes Coq generate a somewhat nicer\n    induction principle for reasoning about [<=].) *)\n\n(* ################################################################# *)\n(** * Basic Properties *)\n\n(** As anyone knows who has taken an undergraduate discrete math\n    course, there is a lot to be said about relations in general,\n    including ways of classifying relations (as reflexive, transitive,\n    etc.), theorems that can be proved generically about certain sorts\n    of relations, constructions that build one relation from another,\n    etc.  For example... *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Partial Functions *)\n\n(** A relation [R] on a set [X] is a _partial function_ if, for every\n    [x], there is at most one [y] such that [R x y] -- i.e., [R x y1]\n    and [R x y2] together imply [y1 = y2]. *)\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\n(** For example, the [next_nat] relation defined earlier is a partial\n    function. *)\n\nPrint next_nat.\n(* ====> Inductive next_nat (n : nat) : nat -> Prop :=\n           nn : next_nat n (S n) *)\nCheck next_nat : relation nat.\n\nTheorem next_nat_partial_function :\n   partial_function next_nat.\nProof.\n  unfold partial_function.\n  intros x y1 y2 H1 H2.\n  inversion H1. inversion H2.\n  reflexivity.  Qed.\n\n(** However, the [<=] relation on numbers is not a partial\n    function.  (Assume, for a contradiction, that [<=] is a partial\n    function.  But then, since [0 <= 0] and [0 <= 1], it follows that\n    [0 = 1].  This is nonsense, so our assumption was\n    contradictory.) *)\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply Hc with (x := 0).\n    - apply le_n.\n    - apply le_S. apply le_n. }\n  inversion Nonsense.   Qed.\n\n(** **** Exercise: 2 stars, optional (total_relation_not_partial)  *)\n(** Show that the [total_relation] defined in earlier is not a partial\n    function. *)\n \nCheck total_relation.\nPrint total_relation.\n\nTheorem total_relation_not_partial: ~(partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. \n  intros H. Print total_relation.\n  assert(0 = 1) as NOnsense.\n  - apply (H 0).\n     + apply tr2. + Print total_relation. apply (tr1_L 0 1).\n  - inversion NOnsense.\nQed.      \n\n\n(** **** Exercise: 2 stars, optional (empty_relation_partial)  *)\n(** Show that the [empty_relation] that we defined earlier is a\n    partial function. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reflexive Relations *)\n\n(** A _reflexive_ relation on a set [X] is one for which every element\n    of [X] is related to itself. *)\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive :\n  reflexive le.\nProof.\n  unfold reflexive. intros n. apply le_n.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Transitive Relations *)\n\n(** A relation [R] is _transitive_ if [R a c] holds whenever [R a b]\n    and [R b c] do. *)\n\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  - (* le_n *) apply Hnm.\n  - (* le_S *) apply le_S. apply IHHmo.  Qed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  apply le_S in Hnm.\n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. Qed.\n\n(** **** Exercise: 2 stars, optional (le_trans_hard_way)  *)\n(** We can also prove [lt_trans] more laboriously by induction,\n    without using [le_trans].  Do this.*)\n\nTheorem lt_trans' :\n  transitive lt.\nProof.\n  (* Prove this by induction on evidence that [m] is less than [o]. *)\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [| m' Hm'o].\n  - apply le_S. apply Hnm.\n  - apply le_S. apply IHHm'o.\nQed.\n\n\n(** **** Exercise: 2 stars, optional (lt_trans'')  *)\n(** Prove the same thing again by induction on [o]. *)\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  - inversion Hmo.\n  - induction Hmo.\n      + apply le_S. apply Hnm.\n      + apply le_S. apply IHHmo.\nQed.\n\n\n(** The transitivity of [le], in turn, can be used to prove some facts\n    that will be useful later (e.g., for the proof of antisymmetry\n    below)... *)\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof.\n  intros n m H. apply le_trans with (S n).\n  - apply le_S. apply le_n.\n  - apply H.\nQed.\n\n(** **** Exercise: 1 star, optional (le_S_n)  *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros n m H.\n  inversion H.\n  - apply le_n. - apply le_trans with (S n).\n  + apply le_S. apply le_n. + apply H1.\nQed.\n\n\n(** **** Exercise: 2 stars, optional (le_Sn_n_inf)  *)\n(** Provide an informal proof of the following theorem:\n\n    Theorem: For every [n], [~ (S n <= n)]\n\n    A formal proof of this is an optional exercise below, but try\n    writing an informal proof without doing the formal proof first.\n           by induction first n = 0. ~(1 ,<= 0 ) trivial\n           IH: Soupose n', ~(S n' <= n') <= is total relation that is to say n' < S n'\n           => S n' < S (S n') which is ~(S (S n')  <= S n')  \n\n    Proof: *)\n    (* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 1 star, optional (le_Sn_n)  *)\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n   intros n contra. induction n.\n  - inversion contra. - apply IHn. apply le_S_n. apply contra.\nQed.\n(** [] *)\n\n(** Reflexivity and transitivity are the main concepts we'll need for\n    later chapters, but, for a bit of additional practice working with\n    relations in Coq, let's look at a few other common ones... *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Symmetric and Antisymmetric Relations *)\n\n(** A relation [R] is _symmetric_ if [R a b] implies [R b a]. *)\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\n(** **** Exercise: 2 stars, optional (le_not_symmetric)  *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n   unfold symmetric. intros contra.\n   assert( 1 <= 0) as nonsense.\n  - apply contra. apply le_S. apply le_n.\n  - inversion nonsense.\nQed.\n(** [] *)\n\n(** A relation [R] is _antisymmetric_ if [R a b] and [R b a] together\n    imply [a = b] -- that is, if the only \"cycles\" in [R] are trivial\n    ones. *)\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\n(** **** Exercise: 2 stars, optional (le_antisymmetric)  *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  unfold antisymmetric.\n  intros a. \n  induction a as [|a' IHa'].\n  - intros. inversion H0. reflexivity.\n  - intros. destruct b.\n     + inversion H.\n     + Search (S _ = S _). apply eq_S. apply IHa'.\n        * Search (S _ <= S _). apply le_S_n in H. apply H. \n        * apply le_S_n in H0. apply H0.\nQed.\n\n\n(** **** Exercise: 2 stars, optional (le_step)  *)\nTheorem le_step : forall n m p,\n  n < m ->\n  m <= S p ->\n  n <= p.\nProof.\n   unfold lt. intros.\n   apply (le_trans (S n) (m) (S p) H ) in H0.\n   apply le_S_n in H0. apply H0.\nQed. \n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Equivalence Relations *)\n\n(** A relation is an _equivalence_ if it's reflexive, symmetric, and\n    transitive.  *)\n\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(* ----------------------------------------------------------------- *)\n(** *** Partial Orders and Preorders *)\n\n(** A relation is a _partial order_ when it's reflexive,\n    _anti_-symmetric, and transitive.  In the Coq standard library\n    it's called just \"order\" for short. *)\n\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\n(** A preorder is almost like a partial order, but doesn't have to be\n    antisymmetric. *)\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split.\n    - (* refl *) apply le_reflexive.\n    - split.\n      + (* antisym *) apply le_antisymmetric.\n      + (* transitive. *) apply le_trans.  Qed.\n\n(* ################################################################# *)\n(** * Reflexive, Transitive Closure *)\n\n(** The _reflexive, transitive closure_ of a relation [R] is the\n    smallest relation that contains [R] and that is both reflexive and\n    transitive.  Formally, it is defined like this in the Relations\n    module of the Coq standard library: *)\n\nInductive clos_refl_trans {A: Type} (R: relation A) : relation A :=\n    | rt_step : forall x y, R x y -> clos_refl_trans R x y\n    | rt_refl : forall x, clos_refl_trans R x x\n    | rt_trans : forall x y z,\n          clos_refl_trans R x y ->\n          clos_refl_trans R y z ->\n          clos_refl_trans R x z.\n\n(** For example, the reflexive and transitive closure of the\n    [next_nat] relation coincides with the [le] relation. *)\n\nTheorem next_nat_closure_is_le : forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m. split.\n  - (* -> *)\n    intro H. induction H.\n    + (* le_n *) apply rt_refl.\n    + (* le_S *)\n      apply rt_trans with m. apply IHle. apply rt_step.\n      apply nn.\n  - (* <- *)\n    intro H. induction H.\n    + (* rt_step *) inversion H. apply le_S. apply le_n.\n    + (* rt_refl *) apply le_n.\n    + (* rt_trans *)\n      apply le_trans with y.\n      apply IHclos_refl_trans1.\n      apply IHclos_refl_trans2. Qed.\n\n(** The above definition of reflexive, transitive closure is natural:\n    it says, explicitly, that the reflexive and transitive closure of\n    [R] is the least relation that includes [R] and that is closed\n    under rules of reflexivity and transitivity.  But it turns out\n    that this definition is not very convenient for doing proofs,\n    since the \"nondeterminism\" of the [rt_trans] rule can sometimes\n    lead to tricky inductions.  Here is a more useful definition: *)\n\nInductive clos_refl_trans_1n {A : Type}\n                             (R : relation A) (x : A)\n                             : A -> Prop :=\n  | rt1n_refl : clos_refl_trans_1n R x x\n  | rt1n_trans (y z : A) :\n      R x y -> clos_refl_trans_1n R y z ->\n      clos_refl_trans_1n R x z.\n\n(** Our new definition of reflexive, transitive closure \"bundles\"\n    the [rt_step] and [rt_trans] rules into the single rule step.\n    The left-hand premise of this step is a single use of [R],\n    leading to a much simpler induction principle.\n\n    Before we go on, we should check that the two definitions do\n    indeed define the same relation...\n\n    First, we prove two lemmas showing that [clos_refl_trans_1n] mimics\n    the behavior of the two \"missing\" [clos_refl_trans]\n    constructors.  *)\n\nLemma rsc_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> clos_refl_trans_1n R x y.\nProof.\n  intros X R x y H.\n  apply rt1n_trans with y. apply H. apply rt1n_refl.   Qed.\n\n(** **** Exercise: 2 stars, optional (rsc_trans)  *)\nLemma rsc_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      clos_refl_trans_1n R x y  ->\n      clos_refl_trans_1n R y z ->\n      clos_refl_trans_1n R x z.\nProof.\n   intros X R x y z Hxy. generalize dependent z.\n   induction Hxy.\n  - intros. apply H.\n  - intros. apply IHHxy in H0. apply rt1n_trans with y.\n     + apply H. + apply H0.\nQed.\n  \n   \n\n\n(** Then we use these facts to prove that the two definitions of\n    reflexive, transitive closure do indeed define the same\n    relation. *)\n\n(** **** Exercise: 3 stars, optional (rtc_rsc_coincide)  *)\nTheorem rtc_rsc_coincide :\n         forall (X:Type) (R: relation X) (x y : X),\n  clos_refl_trans R x y <-> clos_refl_trans_1n R x y. \nProof.\n   intros X R x y.\n   split.\n   - intros. induction H.\n      * apply rsc_R. apply H.\n     * apply rt1n_refl.\n     * apply (rsc_trans X R x y z IHclos_refl_trans1 IHclos_refl_trans2)  .\n   - intros. induction H.\n      + apply rt_refl.\n      + apply rt_trans with y.\n          * apply rt_step. apply H.\n         * apply IHclos_refl_trans_1n.\nQed.\n(** [] *)\n\n", "meta": {"author": "AKKID", "repo": "If", "sha": "de95d24a26d4a28e1ae11a4b962b4bce20c313f7", "save_path": "github-repos/coq/AKKID-If", "path": "github-repos/coq/AKKID-If/If-de95d24a26d4a28e1ae11a4b962b4bce20c313f7/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.8824278587245935, "lm_q1q2_score": 0.7334237837062768}}
{"text": "Require Export Induction.\n\nModule NatList.\n\nInductive natprod : Type :=\n  pair : nat -> nat -> natprod.\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\nNotation \"( x , y )\" := (pair x y).\n\nDefinition swap_pair (p : natprod) : natprod := \n  match p with\n  | (x,y) => (y,x)\n  end.\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as [m n].\n  simpl.\n  reflexivity.\nQed.\n\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  intros.\n  destruct p as [m n].\n  simpl.\n  reflexivity.\nQed.\n\nTheorem fst_swap_is_snd : forall (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  intros.\n  destruct p as [m n].\n  simpl.\n  reflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\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 length (l:natlist) : nat := \n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist := \n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\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\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\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | [] => []\n  | x :: xs =>\n    match x with\n    | 0 => nonzeros xs\n    | _ => x :: (nonzeros xs)\n    end\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  | [] => []\n  | x :: xs =>\n    match oddb x with\n    | true => x :: (oddmembers xs)\n    | false => oddmembers xs\n    end\n  end.\n\nExample test_oddmembers:            oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\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\nFixpoint rev (l:natlist) : natlist := \n  match l with\n  | nil    => nil\n  | h :: t => snoc (rev t) h\n  end.\n\nFixpoint subalternate (n : nat) (ys l1 l2 : natlist) : natlist :=\n  match n with\n  | 0 => rev ys\n  | S n' =>\n    match l1 with\n    | [] => (rev ys) ++ l2\n    | x :: xs => subalternate n' (x :: ys) l2 xs\n    end\n  end.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  subalternate (length l1 + length l2) nil l1 l2.\n\n\n(* Eval compute in alternate [1;2;3] [4;5;6]. *)\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\nTheorem nil_app_l : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\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\nTheorem app_assoc : forall l1 l2 l3 : natlist, \n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).   \nProof.\n  intros.\n  induction l1 as [|n l1'].\n  reflexivity.\n  simpl.\n  rewrite IHl1'.\n  reflexivity.\nQed.\n\nTheorem nil_app_r : forall l:natlist,\n  l ++ [] = l.\nProof.\n  intros.\n  induction l as [| n k].\n  reflexivity.\n  simpl.\n  rewrite IHk.\n  reflexivity.\nQed.\n\nTheorem app_length : forall l1 l2 : natlist, \n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros.\n  induction l1 as [| n l1'].\n  reflexivity.\n  simpl.\n  rewrite IHl1'.\n  reflexivity.\nQed.\n\nExample test_rev1:            rev [1;2;3] = [3;2;1].\nProof. reflexivity.  Qed.\nExample test_rev2:            rev nil = nil.\nProof. reflexivity.  Qed.\n\nTheorem length_snoc : forall n : nat, forall l : natlist,\n  length (snoc l n) = S (length l).\nProof.\n  intros.\n  induction l as [| n' l'].\n  reflexivity.\n  simpl.\n  rewrite IHl'.\n  reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros.\n  induction l as [| n l'].\n  reflexivity.\n  simpl.\n  rewrite length_snoc.\n  rewrite IHl'.\n  reflexivity.\nQed.\n\nTheorem absorb_snoc : forall n m: nat, forall l : natlist, n :: (snoc l m) = snoc (n :: l) m.\nProof.\n  intros.\n  reflexivity.\nQed.\n\n(* SearchAbout rev. *)\n\nTheorem rev_snoc : forall n : nat, forall l : natlist, rev (snoc l n) = n :: rev l.\nProof.\n  intros.\n  induction l as [| n' l'].\n  reflexivity.\n  simpl.\n  rewrite absorb_snoc.\n  rewrite IHl'.\n  reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist, rev (rev l) = l.\nProof.\n  intros. induction l as [| n l'].\n  reflexivity.\n  simpl.\n  rewrite rev_snoc.\n  rewrite IHl'.\n  reflexivity.\nQed.\n\nTheorem cons_append : forall n : nat, forall l : natlist, cons n l = [n] ++ l.\nProof.\n  intros.\n  induction l as [|m k].\n  reflexivity.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  intros.\n  induction l as [|m k].\n  reflexivity.\n  simpl.\n  rewrite IHk.\n  reflexivity.\nQed.\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 rev_injective : forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros.\n  assert (H4: rev (rev l1) = l2).\n    rewrite H.\n    rewrite rev_involutive.\n    reflexivity.\n  rewrite rev_involutive in H4.\n  assumption.\nQed.\n\nEnd NatList.\n", "meta": {"author": "ejconlon", "repo": "sfsolutions", "sha": "0bb5c48f00d10e80fe63220b0d7eeebcfb3e04d4", "save_path": "github-repos/coq/ejconlon-sfsolutions", "path": "github-repos/coq/ejconlon-sfsolutions/sfsolutions-0bb5c48f00d10e80fe63220b0d7eeebcfb3e04d4/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8918110461567923, "lm_q1q2_score": 0.7332373564006327}}
{"text": "(******************************************************************************)\n(* Chapter 1.6.1: Product Categories                                          *)\n(******************************************************************************)\n\n(*\n(0)\n同じディレクトリにある Categories.v と Functor.v を使う。\n\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Aw_0_Notations.              (* coq standard libs. *)\nRequire Import Aw_1_3_Categories.           (* same dir. *)\nRequire Import Aw_1_4_Functors.             (* same dir. *)\nRequire Import Aw_1_5_Isomorphisms.         (* same dir. *)\n\n(* 積圏 *)\nSection ProductCategories.\n\n  Locate \"_ ~~{ _ }~~> _\".                  (* Categories.v *)\n  \n(*\n  Context `(C1 : Category Obj1 Hom1).\n  Context `(C2 : Category Obj2 Hom2).\n*)  \n  Context `(C1 : Category).                 (* Obj Hom *)\n  Context `(C2 : Category).                 (* Obj0 Hom0 *)\n  \n  (* trying to use the standard \"prod\" here causes a universe\n  inconsistency once we get to coqBinoidal; moreover, using a\n  general fully-polymorphic pair type seems to trigger some serious\n  memory leaks in Coq *)\n  \n  Inductive  prod_obj : Type :=\n  | pair_obj : C1 -> C2 -> prod_obj.\n  \n  Definition fst_obj (x : prod_obj) : C1 :=\n    match x with\n      | pair_obj a _ => a\n    end.\n  \n  Definition snd_obj (x : prod_obj) : C2 :=\n    match x with\n      | pair_obj _ b => b\n    end.\n\n  Inductive prod_mor (a b : prod_obj) : Type :=\n    pair_mor :\n      ((fst_obj a) ~~{C1}~~> (fst_obj b)) -> (* f1 *)\n      ((snd_obj a) ~~{C2}~~> (snd_obj b)) -> (* f2 *)\n      prod_mor a b.                          (* f *)\n  Check prod_mor : prod_obj → prod_obj → Type.\n  \n  Definition prod_eqv (a b : prod_obj)\n             (f : prod_mor a b) (g : prod_mor a b) : Prop :=\n    match f with\n      | pair_mor f1 f2 =>\n        match g with\n          | pair_mor g1 g2 =>\n            f1 === g1 /\\ f2 === g2\n        end\n    end.\n  \n  Program Instance prod_Equiv (a b : prod_obj) : Equivalence (@prod_eqv a b).\n  Obligation 1.                             (* Reflexive *)\n  Proof.\n    rewrite /prod_eqv /Reflexive /=.\n    case=> f1 f2.\n    split.\n    - reflexivity.\n    - reflexivity.\n  Qed.\n  Obligation 2.                             (* Symmetric *)\n  Proof.\n    rewrite /prod_eqv /Symmetric /=.\n    case=> f1 f2.\n    case=> g1 g2.\n    case=> H1 H2.\n    split.\n    - rewrite H1.\n      reflexivity.\n    - rewrite H2.\n      reflexivity.\n  Qed.\n  Obligation 3.                             (* Transitive *)\n  Proof.\n    rewrite /prod_eqv /Transitive /=.\n    case=> f1 f2.\n    case=> g1 g2.\n    case=> h1 h2.\n    case=> Hfg1 Hfg2.\n    case=> Hgh1 Hgh2.\n    split.\n    - rewrite Hfg1 Hgh1.\n      reflexivity.\n    - rewrite Hfg2 Hgh2.\n      reflexivity.\n  Qed.\n  \n  (* 射はSetoidでないといけない。 *)\n  Instance PC_mor (a b : prod_obj) : Setoid :=\n    {\n      carrier := prod_mor a b;\n      eqv := @prod_eqv a b;\n      eqv_equivalence := prod_Equiv a b\n    }.\n  Check PC_mor : prod_obj → prod_obj → Setoid.\n  Print PC_mor.\n  \n  Definition fst_mor {a b : prod_obj} (f : prod_mor a b) :=\n    match f with\n      | pair_mor a _ => a\n    end.\n  \n  Definition snd_mor {a b : prod_obj} (f : prod_mor a b) :=\n    match f with\n      | pair_mor _ b => b\n    end.\n  \n  Check @Category.\n  Check prod_obj : Type.\n  Check prod_mor : prod_obj → prod_obj → Type.\n  Check PC_mor   : prod_obj → prod_obj → Setoid.\n  Check @Category prod_obj PC_mor.\n  \n  Program Instance ProductCategory : @Category prod_obj PC_mor.\n  Obligation 1.                             (* iid *)\n  Proof.\n    apply pair_mor.\n    - apply iid.\n    - apply iid.\n  Defined.\n  Obligation 2.                             (* comp *)\n  Proof.\n    apply pair_mor.\n    Check (fun (f1 : fst_obj a ~~{ C1 }~~> fst_obj b)\n               (g1 : fst_obj b ~~{ C1 }~~> fst_obj c) => (g1 \\\\o f1)).\n    - apply (fun (f1 : fst_obj a ~~{ C1 }~~> fst_obj b)\n                 (g1 : fst_obj b ~~{ C1 }~~> fst_obj c) => (g1 \\\\o f1));\n        by [apply X | apply X0].\n    - apply (fun (f2 : snd_obj a ~~{ C2 }~~> snd_obj b)\n                 (g2 : snd_obj b ~~{ C2 }~~> snd_obj c) => (g2 \\\\o f2));\n        by [apply X | apply X0].\n  Defined.\n  Obligation 3.                             (* comp_respects *)\n  Proof.\n    rewrite /ProductCategory_obligation_2.\n    move=> g1 g2 Hg.\n    move=> f1 f2 Hf.\n    move: Hg Hf.\n    rewrite /prod_eqv.\n    case g1 => gf1 gs1.\n    case f1 => ff1 fs1.\n    case g2 => gf2 gs2.\n    case f2 => ff2 fs2.\n    case=> Hgf Hgs.\n    case=> Hff Hfs.\n    split.\n    - rewrite Hgf Hff.\n      reflexivity.\n    - rewrite Hgs Hfs.\n      reflexivity.\n  Defined.\n  Obligation 4.                             (* iid \\\\o f === f  *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - rewrite left_identity.\n      reflexivity.\n    - rewrite left_identity.\n      reflexivity.\n  Defined.\n  Obligation 5.                             (* f \\\\o iid === f  *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - rewrite right_identity.\n      reflexivity.\n    - rewrite right_identity.\n      reflexivity.\n  Defined.\n  Obligation 6.                             (* f \\\\o g \\\\o h === f \\\\o (g \\\\o h) *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - case: g => gf gs.\n      case: h => hf hs.\n      rewrite associativity.\n      reflexivity.\n    - case: g => gf gs.\n      case: h => hf hs.\n      rewrite associativity.\n      reflexivity.\n  Defined.\nEnd ProductCategories.\n\nNotation \"C ×× D\" := (ProductCategory C D).\n\n(*\nImplicit Arguments pair_obj [ Ob1 Hom1 Ob2 Hom2 C1 C2 ].\nImplicit Arguments pair_mor [ Ob1 Hom1 Ob2 Hom2 C1 C2 ].\n *)\n\nCheck @pair_obj : ∀Obj Hom C1 Obj Hom C2 a b, prod_obj C1 C2.\nCheck @pair_mor : ∀Obj Hom C1 Obj Hom C2 a b f g, prod_mor a b.\nCheck @fst_obj.\nCheck @fst_mor.\nArguments pair_obj {Obj1 Hom1 C1 Obj2 Hom2 C2} a b : rename.\nArguments pair_mor {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} f g : rename.\nArguments fst_obj  {Obj1 Hom1 C1 Obj2 Hom2 C2} D : rename.\nArguments snd_obj  {Obj1 Hom1 C1 Obj2 Hom2 C2} D : rename.\nArguments fst_mor  {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} i : rename.\nArguments snd_mor  {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} i : rename.\nCheck pair_obj : _ -> _ -> prod_obj _ _.    (* 圏の指定は要らない。 *)\nCheck pair_mor : _ ~> _ ->  _ ~> _ -> prod_mor _ _.\nCheck fst_obj  : prod_obj _ _ -> _.\nCheck snd_obj  : prod_obj _ _ -> _.\nCheck fst_mor  : prod_mor _ _ -> _ ~> _.\n\nCheck @PC_mor : ∀Obj Hom C1 Obj0 Hom0 C2 _ _, Setoid.\nArguments PC_mor {Obj1 Hom1 C1 Obj2 Hom2 C2} f g : rename.\nCheck PC_mor : prod_obj _ _ → prod_obj _ _ → Setoid.\n\nCheck @Functor : ∀Obj Hom C1 Obj0 Hom0 C2 _, Type.\nArguments Functor {Obj Hom} C1 {Obj0 Hom0} C2 i : rename.\n\nSection ProductCategoryFunctors.\n\n  Context `{C : Category}.                  (* Obj Hom C *)\n  Context `{D:Category}.                    (* Obj0 Hom0 D *)\n\n  Check @Functor.\n  Check @Functor _ _ (C ×× D) Obj Hom C (fun c => fst_obj c).\n  Check Functor (C ×× D) C (fun c => fst_obj c).\n\n  Check @prod_obj Obj Hom C Obj0 Hom0 D.\n  Check prod_obj C D.\n\n  Check @PC_mor Obj Hom C Obj0 Hom0 D.\n  Check PC_mor.\n  \n  Check @fst_obj Obj Hom C Obj0 Hom0 D : prod_obj C D → C.\n  Check fst_obj : prod_obj C D → C.\n  \n  Check fun (c : prod_obj C D) => @fst_obj Obj Hom C Obj0 Hom0 D c.\n  Check fun (c : prod_obj C D) => fst_obj c.\n  \n  Check @Functor (prod_obj C D) (@PC_mor Obj Hom C Obj0 Hom0 D) (C ×× D)\n        Obj Hom C (fun c => fst_obj _ c).\n  Check Functor (C ×× D) C (fun (c : prod_obj C D) => @fst_obj Obj Hom C Obj0 Hom0 D c).\n  \n  (* 積圏からもとの圏をとりだす関手 *)\n  Program Instance func_pi1 : Functor (C ×× D) C\n                                      (fun (c : prod_obj C D) => fst_obj c).\n  Obligation 1.\n  (* fst_obj a ~~{ C }~~> fst_obj b *)\n  Proof.\n    by apply fst_mor.\n  Defined.\n  Obligation 2.\n  (* fst_mor f === fst_mor f' *)\n  Proof.\n    rewrite /func_pi1_obligation_1.\n    case: f H => ff fs.\n    case: f' => f'f f's H /=.\n    by case: H.\n  Defined.\n  Obligation 3.\n  (* iid === iid *)\n  Proof.\n    reflexivity.\n  Defined.\n  Obligation 4.\n  Proof.\n    rewrite /func_pi1_obligation_1.\n    case: f => ff fs.\n    case: g => gf gs.\n    reflexivity.\n  Defined.\n  \n  Program Instance func_pi2 : Functor (C ×× D) D\n                                      (fun (c : prod_obj C D) => snd_obj c).\n  Obligation 1.\n  (* snd_obj a ~~{ D }~~> snd_obj b *)\n  Proof.\n    by apply snd_mor.\n  Defined.\n  Obligation 2.\n  (* snd_mor f === snd_mor f' *)\n  Proof.\n    rewrite /func_pi2_obligation_1.\n    case: f H => ff fs.\n    case: f' => f'f f's H /=.\n    by case: H.\n  Defined.\n  Obligation 3.\n  (* iid === iid *)\n  Proof.\n    reflexivity.\n  Defined.\n  Obligation 4.\n  Proof.\n    rewrite /func_pi2_obligation_1.\n    case: f => ff fs.\n    case: g => gf gs.\n    reflexivity.\n  Defined.  \n  \n  (* 積圏の左が恒等射である場合 *)\n  Definition llecnac_fmor (I : C) (a b : D) (g : a ~~{D}~~> b) :\n    (pair_obj I a) ~~{C××D}~~> (pair_obj I b).\n  Proof.\n    apply: pair_mor => /=.\n    - by apply: iid.\n    - by apply: g.\n  Defined.\n  \n  (* 圏から左が恒等射である積圏への関手 *)\n  Program Instance func_llecnac (I : C) : Functor D (C ×× D) (pair_obj I).\n  Obligation 1.\n  (* prod_mor (pair_obj I a) (pair_obj I b) *)\n   Proof.\n    apply: pair_mor;\n      by apply llecnac_fmor.\n  Defined.\n  Obligation 2.\n  Proof.\n    split; [reflexivity | done].\n  Defined.\n  Obligation 3.\n    split; [reflexivity | reflexivity].\n  Defined.\n  Obligation 4.\n  Proof.\n    split.\n    - rewrite left_identity.\n      reflexivity.\n    - reflexivity.\n  Defined.\n  \n  (* 積圏の右が恒等射である場合 *)\n  Definition rlecnac_fmor (I : D) (a b : C) (f : a ~~{C}~~> b) :\n    (pair_obj a I) ~~{C××D}~~> (pair_obj b I).\n  Proof.\n    apply: pair_mor => /=.\n    - by apply: f.\n    - by apply: iid.\n  Defined.\n  \n  (* 圏から右が恒等射である積圏への関手 *)\n  Program Instance func_rlecnac (I : D) : Functor C (C ×× D) (fun c => (pair_obj c I)).\n  Obligation 1.\n  (* prod_mor (pair_obj a I) (pair_obj b I) *)\n  Proof.\n    apply: pair_mor;\n      by apply rlecnac_fmor.\n  Defined.\n  Obligation 2.\n  Proof.\n    split; [done | reflexivity].\n  Defined.\n  Obligation 3.\n    split; [reflexivity | reflexivity].\n  Defined.\n  Obligation 4.\n  Proof.\n    split.\n    - reflexivity.\n    - rewrite right_identity.\n      reflexivity.\n  Defined.\n  \n  Context `{E : Category}.\n  \n  (* 積圏の結合律 *)\n  Definition cossa : ((C ×× D) ×× E) -> (C ×× (D ×× E)).\n  Proof.\n    move=> [[HC HD] HE].\n    by [].\n  Defined.\n  \n  (* 次の定理のための補題 *)\n  Definition cossa_fmor (a : ((C ×× D) ×× E)) (b : ((C ×× D) ×× E))\n             (f : a ~~{(C ×× D) ×× E}~~> b) :\n    (cossa a) ~~{C ×× (D ×× E)}~~> (cossa b).\n  Proof.\n    case: a f => HCxD HE.\n    case: b => GCxD GE.\n    case: HCxD.\n    case: GCxD.\n    move=> HC HD GC GD.\n    case=> fCD fE.\n    case: fCD => fC fD.\n    done.\n  Defined.\n\n  (* cossa は、関手である。 *)\n  Program Instance func_cossa : Functor ((C ×× D) ×× E) (C ×× (D ×× E)) cossa :=\n    {|\n      fmor := fun a b f => cossa_fmor f\n    |}.\n  Obligation 1.\n  Proof.\n    move: a b f f' H.\n    (* ∀a b f f' _, cossa_fmor f === cossa_fmor f' *)\n    move=> [[a11 a12] a2].                  (* case a *)\n    move=> [[b11 b12] b2].                  (* case b *)\n    move=> [[f11 f12] f2].                  (* case f *)\n    move=> [[g11 g12] g2].                  (* case f' *)\n    case; case.\n    split; [exact | split; exact].\n  Defined.\n  Obligation 2.\n  Proof.\n    (* ∀ a : (C ×× D) ×× E, cossa_fmor iid === iid *)\n    case: a => HCxD HE.\n    case: HCxD => HC HD.\n    split; [reflexivity | split; reflexivity].\n  Defined.\n  Obligation 3.\n  Proof.\n    move: a b c f g.\n    (* ∀a b c f g, cossa_fmor g \\\\o cossa_fmor f === cossa_fmor (g \\\\o f) *)\n    move=> [[a11 a12] a2].                  (* case a *)\n    move=> [[b11 b12] b2].                  (* case b *)\n    move=> [[c11 c12] c2].                  (* case c *)\n    move=> [[f11 f12] f2].                  (* case f *)\n    move=> [[g11 g12] g2].                  (* case g *)\n    rewrite /=; split; [reflexivity | split; reflexivity].\n  Defined.\n  \n  (* 同じ圏の積 C^2 *)\n  Program Instance func_diagonal : Functor C (C ×× C) (fun c => (pair_obj c c)).\n  Obligation 1.\n  (* prod_mor (pair_obj a a) (pair_obj b b) *)\n  Proof.\n    by apply: pair_mor.\n  Defined.\n  Obligation 3.\n  (* iid === iid ∧ iid === iid *)\n  Proof.\n    split; reflexivity.\n  Defined.\n  Obligation 4.\n  (* g \\\\o f === g \\\\o f ∧ g \\\\o f === g \\\\o f *)\n  Proof.\n    split; reflexivity.\n  Defined.\nEnd ProductCategoryFunctors.\n\nSection func_prod.\n  \n  Context `{C1 : Category} `{C2 : Category} `{C3 : Category} `{C4 : Category}.\n  Variables (Fobj1 : C1 -> C2) (Fobj2 : C3 -> C4).\n  Variables (F1 : Functor C1 C2 Fobj1) (F2 : Functor C3 C4 Fobj2).\n\n  Definition functor_product_fobj (a : prod_obj C1 C3) :=\n    pair_obj (Fobj1 (fst_obj a)) (Fobj2 (snd_obj a)).  \n  Check functor_product_fobj.\n  Check functor_product_fobj : prod_obj C1 C3 → prod_obj C2 C4.\n\n  Definition functor_product_fmor (a b : (C1 ×× C3)) (f : a ~~{C1 ×× C3}~~> b) :\n    (functor_product_fobj a) ~~{C2 ×× C4}~~> (functor_product_fobj b).\n  Proof.\n    case: a f => HC1 HC3 H.\n    apply: pair_mor => /=.\n    - apply (fmor F1); by case H.\n    - apply (fmor F2); by case H.\n  Defined.\n  \n  Hint Unfold fst_obj.\n\n  Program Instance func_prod : Functor (C1 ×× C3) (C2 ×× C4) functor_product_fobj :=\n    {|\n      fmor := fun a b (f:a~~{C1 ×× C3}~~>b) => functor_product_fmor f\n    |}.\n  Obligation 1.\n  Proof.\n    move: a b f f' H.\n    (* ∀a b f f' _, functor_product_fmor f === functor_product_fmor f' *)\n    move=> [a1 a2].                         (* case a *)\n    move=> [b1 b2].                         (* case b *)\n    move=> [f1 f2].                         (* case f *)\n    move=> [g1 g2].                         (* case g *)\n    case=> H1 H2.                           (* case H *)\n    split; [rewrite H1 | rewrite H2]; reflexivity.\n  Defined.\n  Obligation 2.\n  Proof.\n  (* ∀ a : C1 ×× C3, functor_product_fmor iid === iid *)\n    case: a => [a1 a2] /=.\n      by split; apply fmor_preserves_id.\n  Defined.\n  Obligation 3.\n  Proof.\n    move: a b c f g.\n  (* ∀a b c f g,\n   functor_product_fmor g \\\\o functor_product_fmor f ===\n   functor_product_fmor (g \\\\o *)\n    move=> [a1 a2].                         (* case a *)\n    move=> [b1 b2].                         (* case b *)\n    move=> [c1 c2].                         (* case c *)\n    case=> f1 f3.                           (* case f *)\n    case=> g1 g3.                           (* csae g *)\n    by move=> /=; split; apply fmor_preserves_comp.\n  Defined.\nEnd func_prod.\n\nNotation \"f **** g\" := (func_prod f g).\n\nProgram Instance iso_prod `{C : Category} `{D : Category} {a b : C} {c d : D}\n         (ic : a ≅ b) (id : @Isomorphic _ _ D c d) :\n  @Isomorphic _ _ (C ×× D) (pair_obj a c) (pair_obj b d).\nObligation 1.                               (* prod_mor (pair_obj a c) (pair_obj b d) *)\nProof.\n  apply: pair_mor => /=.\n  - by case: ic.\n  - by case: id.\nDefined.\nObligation 2.                               (* prod_mor (pair_obj b d) (pair_obj a c) *)\nProof.\n  apply: pair_mor => /=.\n  - by case: ic.\n  - by case: id.\nDefined.\nObligation 3.\nProof.\n   by split; apply iso_comp1.\nDefined.\nObligation 4.\nProof.\n   by split; apply iso_comp2.\nDefined.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/categories/Aw_1_6_1_ProductCategories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7332373491384863}}
{"text": "(* For a equal function to be valid it should be reflexive, symmetric and transitive. *)\n\nDefinition Reflexive (T : Type) (equal : T -> T -> Prop) :=\n  forall e : T,\n    equal e e.\n\nDefinition Symmetric (T : Type) (equal : T -> T -> Prop) :=\n  forall e1 e2 : T,\n    equal e1 e2 -> equal e2 e1.\n\nDefinition Transitive (T : Type) (equal : T -> T -> Prop) :=\n  forall e1 e2 e3 : T,\n    equal e1 e2 ->\n    equal e2 e3 ->\n    equal e1 e3. \n\nDefinition Equal (T : Type)\n                 (equal : T -> T-> Prop) :=\n  Reflexive T equal /\\\n  Symmetric T equal /\\\n  Transitive T equal.\n\nCorollary eq_is_a_valid_Equal :\n  forall T : Type,\n    Equal T eq.\nProof.  \n  intro T.\n  unfold Equal.\n  split.\n    unfold Reflexive.\n    intro e.\n    reflexivity.\n\n    split.\n      unfold Symmetric.\n      intros e1 e2.\n      intro H.\n      symmetry.\n      exact H.\n\n      unfold Transitive.\n      intros e1 e2 e3.\n      intros H1 H2.\n      rewrite -> H2 in H1.\n      exact H1.\nQed.\n\n(* Please continue with Algebra *)\n", "meta": {"author": "klausfyhn", "repo": "A-Programming-Journey", "sha": "e8a669afd2cd0192c28639b5226fe8a1513d88c0", "save_path": "github-repos/coq/klausfyhn-A-Programming-Journey", "path": "github-repos/coq/klausfyhn-A-Programming-Journey/A-Programming-Journey-e8a669afd2cd0192c28639b5226fe8a1513d88c0/Equal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7332373405246034}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural :=\n  Succ (plus lf1 lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj153_coqofml_KARd2P.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7332001825835682}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\n(* Originally known as lemma_3_6a *)\nLemma lemma_orderofpoints_ABC_ACD_BCD :\n\tforall A B C D,\n\tBetS A B C ->\n\tBetS A C D ->\n\tBetS B C D.\nProof.\n\tintros A B C D.\n\tintros BetS_A_B_C.\n\tintros BetS_A_C_D.\n\tapply (axiom_betweennesssymmetry) in BetS_A_B_C as BetS_C_B_A.\n\tapply (axiom_betweennesssymmetry) in BetS_A_C_D as BetS_D_C_A.\n\tpose proof (axiom_orderofpoints_ABD_BCD_ABC D C B A BetS_D_C_A BetS_C_B_A) as BetS_D_C_B.\n\tapply (axiom_betweennesssymmetry) in BetS_D_C_B as BetS_B_C_D.\n\texact BetS_B_C_D.\nQed.\n\nEnd Euclid.\n\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_orderofpoints_ABC_ACD_BCD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7331692729288525}}
{"text": "From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\n(* Additional lemmas about counting. *)\nSection Counting.\n  \n  Lemma count_filter_fun :\n    forall (T: eqType) (l: seq T) P,\n      count P l = size (filter P l).\n  Proof.\n    intros T l P.\n    induction l; simpl; first by done.\n    by destruct (P a); [by rewrite add1n /=; f_equal | by rewrite add0n].\n  Qed.\n\nEnd Counting.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/util/counting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7331692604908505}}
{"text": "Require Import Coq.Relations.Relations.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\n\nModule Type SemigroupSig.\n  Parameters (Carrier: Type)(Req: relation Carrier).\n  Context `{Requiv: Equivalence Carrier Req}.\n  Parameters (op: Carrier -> Carrier -> Carrier).\n  Parameters (op_proper: Proper (Req ==> Req ==> Req) op).\n\n  Infix \"~\" := Req (at level 60, no associativity).\n  Infix \"<*>\" := op (at level 40, left associativity).\n\n  Axiom associativity:\n    forall (a b c: Carrier),\n      a <*> b <*> c ~ a <*> (b <*> c).\nEnd SemigroupSig.\n\nModule SemigroupTheory (Import SS: SemigroupSig).\n  Context `{Requiv: Equivalence Carrier Req}.\n  Theorem op_l:\n    forall (a b: Carrier),\n      a ~ b ->\n      forall (c: Carrier), c <*> a ~ c <*> b.\n  Proof.\n    intros a b Hab c.\n    apply op_proper;\n      [reflexivity | assumption].\n  Qed.\n\n  Theorem op_r:\n    forall (a b: Carrier),\n      a ~ b ->\n      forall (c: Carrier), a <*> c ~ b <*> c.\n  Proof.\n    intros a b Hab c.\n    apply op_proper;\n      [assumption | reflexivity].\n  Qed.\nEnd SemigroupTheory.\n", "meta": {"author": "ku-sldg", "repo": "algebra", "sha": "026fb7daeef2dcd88c7d6723929e90f261caf109", "save_path": "github-repos/coq/ku-sldg-algebra", "path": "github-repos/coq/ku-sldg-algebra/algebra-026fb7daeef2dcd88c7d6723929e90f261caf109/old_theories/attempt02/Semigroups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7331692583939707}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.Bool.Bool.\n\nOpen Scope list_scope.\n\nImport ListNotations.\n\n\nInductive QSAcc : list nat -> Type :=\n    | qsAcc_nil  : QSAcc nil\n    | qsAcc_cons : forall (x : nat) (xs : list nat),\n                    QSAcc (filter (fun y => ltb y x) xs) ->\n                    QSAcc (filter (fun y => negb (ltb y x)) xs) ->\n                    QSAcc (x :: xs).\n\nFixpoint quicksort (l : list nat)  (qs_acc : QSAcc l) : list nat :=\n    match qs_acc with\n    | qsAcc_nil => nil\n    | (qsAcc_cons p ps lesser greater) =>\n            quicksort (filter (fun y => ltb y p) ps) lesser\n            ++ p :: nil\n            ++ quicksort (filter (fun y => negb (ltb y p)) ps) greater\n    end.\n\n(* Example list and usage of quicksort with Bove-Capretta predicate *)\nDefinition list := 5::3::1::4::nil.\n\nTheorem exTerm: QSAcc list.\nProof.\n    apply qsAcc_cons.\n    apply qsAcc_cons.\n    apply qsAcc_cons.\n    simpl. apply qsAcc_nil.\n    simpl. apply qsAcc_nil.\n\n    apply qsAcc_cons; simpl; apply qsAcc_nil.\n    simpl. apply qsAcc_nil.\nQed.\n\nEval simpl in filter (fun y => ltb y 5) list.\n\nDefinition res := quicksort list exTerm.\n\nEval simpl in res.s\n\n\n", "meta": {"author": "ltbinsbe", "repo": "INFODTP", "sha": "2995a6503d4b8028f83a0907e83bcd85dd417d48", "save_path": "github-repos/coq/ltbinsbe-INFODTP", "path": "github-repos/coq/ltbinsbe-INFODTP/INFODTP-2995a6503d4b8028f83a0907e83bcd85dd417d48/coq/abandonware/QS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417878, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7331692566552818}}
{"text": "Theorem id: forall A : Prop, A -> A.\nProof.\nintros.\napply H.\nQed.\n\nTheorem const : forall A B : Prop, A -> B -> A.\nProof.\nintros.\napply H.\nQed.\n\nTheorem s_comb : forall A B C : Prop, (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\nintros.\napply H.\napply H1.\napply H0.\napply H1.\nQed.\n\nTheorem b_comb1 : forall A B C : Prop, (A -> B) -> (B -> C) -> A -> C.\nProof.\nintros.\napply H0.\napply H.\napply H1.\nQed.\n\nTheorem b_comb2 : forall A B C : Prop, (B -> C) -> (A -> B) -> A -> C.\nProof.\nintros.\napply H.\napply H0.\napply H1.\nQed.\n\nTheorem split : forall A B C : Prop, (A -> B -> C) -> (B -> A -> C).\nProof.\nintros.\napply H.\napply H1.\napply H0.\nQed.\n\nTheorem pair_intro : forall A B : Prop, (A -> (B -> (A /\\ B))).\nProof.\nintros.\nsplit.\napply H.\napply H0.\nQed.\n\nTheorem fst : forall A B : Prop, (A /\\ B) -> A.\nProof.\nintros.\napply H.\nQed.\n\nTheorem snd : forall A B : Prop, (A /\\ B) -> B.\nProof.\nintros.\napply H.\nQed.\n\nTheorem curry : forall A B C : Prop, (A /\\ B) -> C -> (A -> (B -> C)).\nProof.\nintros.\napply H0.\nQed.\n\nTheorem uncurry : forall A B C : Prop, (A -> (B -> C)) -> ((A /\\ B) -> C).\nProof.\nintros.\napply H.\napply H0.\napply H0.\nQed.\n\nTheorem uniProd : forall A B C : Prop, (A -> B) -> (A -> C) -> A -> (B /\\ C).\nProof.\nintros.\nsplit.\napply H.\napply H1.\napply H0.\napply H1.\nQed.\n\nTheorem prod2 : forall A B C D : Prop, (A -> B) -> (D -> C) -> (A /\\ D) -> (B /\\ C).\nProof.\nintros.\nsplit.\napply H.\napply H1.\napply H0.\napply H1.\nQed.\n\nTheorem trans2 : forall A B C : Prop, (A -> B) /\\ (B -> C) -> A -> C.\nProof.\nintros.\napply H.\napply H.\napply H0.\nQed.\n\nTheorem con_com : forall A B : Prop, (A /\\ B) -> (B /\\ A).\nProof.\nintros.\nsplit.\napply H.\napply H.\nQed.\n\nTheorem con_assoc : forall A B C: Prop, (A /\\ B) /\\ C -> A /\\ (B /\\ C).\nProof.\nintros.\nsplit.\napply H.\nsplit.\napply H.\napply H.\nQed.\n\nTheorem con_assoc1 : forall A B C : Prop, A /\\ (B /\\ C) -> (A /\\ B) /\\ C.\nProof.\nintros.\nsplit.\nsplit.\napply H.\napply H.\napply H.\nQed.\n\nTheorem con_assoc2 : forall A B C : Prop, A /\\ (B /\\ C) <-> (A /\\ B) /\\ C.\nProof.\nintros.\nsplit.\napply con_assoc1.\napply con_assoc.\nQed.\n\n\nTheorem disj_intro_left : forall A B : Prop, A -> A \\/ B.\nProof.\nintros.\nleft.\napply H.\nQed.\n\nTheorem disj_intro_right : forall A B : Prop, B -> A \\/ B.\nProof.\nintros.\nright.\napply H.\nQed.\n\nTheorem disj_elim : forall A B C : Prop, (A -> C) -> (B -> C) -> A \\/ B -> C.\nProof.\nintros.\ndestruct H1.\napply H.\napply H1.\napply H0.\napply H1.\nQed.\n\nTheorem disj_assoc : forall A B C : Prop, (A \\/ B) \\/ C -> A \\/ (B \\/ C).\nProof.\nintros.\ntauto.\nQed.\n\nTheorem disj_assoc1 : forall A B C : Prop, A \\/ (B \\/ C) -> (A \\/ B) \\/ C.\nProof.\nintros.\ntauto.\nQed.\n\nTheorem disj_assoc2 : forall A B C : Prop, (A \\/ B) \\/ C <-> A \\/ (B \\/ C).\nProof.\nintros.\nsplit.\napply disj_assoc.\napply disj_assoc1.\nQed.\n", "meta": {"author": "DanielRrr", "repo": "Coq-Studies", "sha": "a7cd6bd7f61e91ca118a615e62dfe8fec50b70d3", "save_path": "github-repos/coq/DanielRrr-Coq-Studies", "path": "github-repos/coq/DanielRrr-Coq-Studies/Coq-Studies-a7cd6bd7f61e91ca118a615e62dfe8fec50b70d3/IntuitionisticCalculus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7331692563687292}}
{"text": "(* Definitions and theory of natural numbers that is useful in cryptographi proofs. *)\n\nSet Implicit Arguments.\n\nRequire Export Arith.\nRequire Export Omega.\nRequire Export Arith.Div2.\nRequire Export Coq.Numbers.Natural.Peano.NPeano. \nRequire Import Coq.NArith.BinNat.\n\nLemma mult_same_r : forall n1 n2 n3,\n  n3 > 0 ->\n  n1 * n3 = n2 * n3 ->\n  n1 = n2.\n  \n  induction n1; destruct n2; intuition; simpl in *.\n  remember (n2 * n3) as x.\n  omega.\n  remember (n1 * n3) as x.\n  omega.\n  \n  f_equal.\n  eapply IHn1; eauto.\n  \n  eapply plus_reg_l. eauto.\nQed.\n\nLemma mult_same_l : forall n3 n1 n2,\n  n3 > 0 ->\n  n3 * n1 = n3 * n2 ->\n  n1 = n2.\n  \n  intuition.\n  eapply mult_same_r; eauto.\n  rewrite mult_comm.\n  rewrite (mult_comm n2 n3).\n  trivial.\nQed.\n\nLemma mult_gt_0 : forall n1 n2,\n  n1 > 0 ->\n  n2 > 0 ->\n  n1 * n2 > 0.\n  destruct n1; intuition; simpl in *.\n  remember (n1 * n2) as x.\n  omega.\nQed.\n\nLemma minus_eq_compat : forall n1 n2 n3 n4,\n  n1 = n2 ->\n  n3 = n4 ->\n  n1 - n3 = n2 - n4.\n  \n  intuition.\nQed.\n\nLemma plus_eq_compat : forall n1 n2 n3 n4,\n  n1 = n2 ->\n  n3 = n4 ->\n  n1 + n3 = n2 + n4.\n  \n  intuition.\nQed.\n\nLemma minus_diag_eq : forall n1 n2,\n  n1 = n2 ->\n  n1 - n2 = 0.\n  \n  intuition.\nQed.\n\nLemma le_eq : forall n1 n2,\n  n1 = n2 ->\n  n1 <= n2.\n  \n  intuition.\nQed.\n\nLemma minus_add_assoc : forall n1 n2 n3,\n  (n3 <= n2)%nat ->\n  (n1 + (n2 - n3) = n1 + n2 - n3)%nat.\n  \n  intuition.\nQed.\n\n\n\n\nClass nz (a : nat) := {\n  agz : a > 0\n}.\n\nInstance nz_nat : forall (n : nat), nz (S n).\nintuition.\neconstructor.\nomega.\nDefined.\n\nDefinition posnat := {n : nat | n > 0}.\n\n\nDefinition posnatToNat(p : posnat) :=\n  match p with\n    | exist n _ => n\n  end.\n\nInductive posnatEq : posnat -> posnat -> Prop :=\n  | posnatEq_intro : \n    forall (n1 n2 : nat) pf1 pf2,\n      n1 = n2 ->\n      posnatEq (exist _ n1 pf1) (exist _ n2 pf2).\n\nDefinition posnatMult(p1 p2 : posnat) : posnat :=\n    match (p1, p2) with\n      | (exist n1 pf1, exist n2 pf2) =>\n        (exist (fun n => n > 0) (n1 * n2) (mult_gt_0 pf1 pf2))\n    end.\n\nLemma posnatMult_comm : forall p1 p2,\n  (posnatEq (posnatMult p1 p2) (posnatMult p2 p1)).\n\n  intuition.\n  unfold posnatMult.\n  destruct p1; destruct p2.\n  econstructor.\n  apply mult_comm.\nQed.  \n\nCoercion posnatToNat : posnat >-> nat.\n\nLemma posnat_pos : forall (p : posnat),\n  p > 0.\n  \n  intuition.\n  destruct p.\n  unfold posnatToNat.\n  trivial.\nQed.\n\nInstance nz_posnat : forall (p : posnat),\n  nz p.\n\nintuition.\neconstructor.\neapply posnat_pos.\n\nQed.\n\nDefinition natToPosnat(n : nat)(pf : nz n) :=\n  (exist (fun x => x > 0) n agz).\n\nNotation \"'pos' x\" := (@natToPosnat x _) (at level 40).\n\nFixpoint expnat n1 n2 :=\n  match n2 with\n    | 0 => 1\n    | S n2' =>\n      n1 * (expnat n1 n2')\n  end.\n\nTheorem expnat_pos : forall x n,\n  x > 0 ->\n  expnat x n > 0.\n  \n  induction n; intuition; simpl in *.\n  remember (x * expnat x n) as y.\n  assert (y <> 0); try omega.\n  intuition; subst.\n  apply mult_is_O in H1.\n  destruct H1; omega.\n\nQed.\n\n\nLemma div2_le : forall n,\n  le (div2 n) n.\n  \n  intuition.\n  eapply NPeano.div2_decr.\n  omega.\n  \nQed.\n\nLemma div2_ge_double : forall n, \n  n >= (div2 n) + (div2 n).\n  \n  intuition.\n  destruct (Even.even_odd_dec n).\n  \n  rewrite (even_double n) at 1.\n  unfold double.\n  omega.\n  trivial.\n  rewrite (odd_double n) at 1.\n  unfold double.\n  omega.\n  trivial.\nQed.\n\nLocal Open Scope N_scope.\nDefinition modNat (n : nat)(p : posnat) : nat :=\n  N.to_nat ((N.of_nat n) mod (N.of_nat p)).\n\nLemma modNat_plus : forall n1 n2 p,\n    (modNat (n1 + n2) p = modNat ((modNat n1 p) + n2) p)%nat.\n  \n  unfold modNat.\n\n  intuition.\n  rewrite Nnat.Nat2N.inj_add.\n\n  rewrite <- N.add_mod_idemp_l.\n  f_equal.\n  rewrite <- (Nnat.Nat2N.id n2) at 2.\n  rewrite Nnat.Nat2N.inj_add.\n  repeat rewrite Nnat.N2Nat.id.\n  trivial.\n\n  destruct p.\n  simpl.\n  \n  destruct x;\n  simpl.\n  omega.\n  \n  Lemma Npos_nz : forall p, \n    Npos p <> N0.\n\n    destruct p; intuition; simpl in *.\n    inversion H.\n    inversion H.\n    inversion H.\n  Qed.\n\n  apply Npos_nz.\n\nQed.\n\n\nLemma modNat_arg_eq : forall (p : posnat),\n  modNat p p = O.\n\n  intuition.\n  unfold modNat.\n  rewrite N.mod_same.\n  trivial.\n  unfold N.of_nat, posnatToNat.\n  destruct p.\n  destruct x.\n  omega.\n  apply Npos_nz.\n\nQed.\n\nLemma of_nat_ge_0 : forall n,\n  0 <= N.of_nat n.\n\n  intuition.\n  unfold N.of_nat.\n  destruct n.\n  intuition.\n\n  simpl.\n  unfold N.le.\n  case_eq ((0 ?= N.pos (Pos.of_succ_nat n))); intuition;\n    try discriminate.\nQed.\n\nLemma of_posnat_gt_0 : forall (p : posnat),\n  0 < N.of_nat p.\n\n  intuition.\n  unfold N.of_nat, posnatToNat.\n  destruct p.\n  destruct x.\n  omega.\n  destruct x; intuition; simpl in *.\n  \n  case_eq (N.compare 0 1)%N; intuition.\n  inversion H.\n  inversion H.\n\n  case_eq (N.compare 0 (N.pos (Pos.succ (Pos.of_succ_nat x))))%N; intuition.\n  inversion H.\n  inversion H.\nQed.\n\nLemma modNat_lt : forall x p, (modNat x p < p)%nat.\n\n  intuition.\n  unfold modNat.\n  assert (N.of_nat x mod N.of_nat p < N.of_nat p)%N.\n  apply N.mod_bound_pos.\n  apply of_nat_ge_0.\n  apply of_posnat_gt_0.\n\n  specialize (Nnat.N2Nat.inj_compare); intuition.\n  rewrite <- (Nnat.Nat2N.id p) at 2.\n  apply nat_compare_lt.\n  rewrite <- H0.\n  apply N.compare_lt_iff.\n  trivial.\n\nQed.\n\nLemma modNat_eq : forall (n : posnat) x, (x < n -> modNat x n = x)%nat.\n  \n  intuition.\n  unfold modNat.\n  rewrite N.mod_small.\n  apply Nnat.Nat2N.id.\n  specialize (Nnat.N2Nat.inj_compare); intuition.\n  specialize (N.compare_lt_iff (N.of_nat x) (N.of_nat n)); intuition.\n  apply H2.\n  rewrite H0.\n  repeat rewrite Nnat.Nat2N.id.\n  apply nat_compare_lt.\n  trivial.\nQed.\n\nDefinition modNatAddInverse (n : nat)(p : posnat) :=\n  (p - (modNat n p))%nat.\n\nLemma modNatAddInverse_correct_gen : forall x y p,\n  modNat x p = modNat y p ->\n  modNat (x + modNatAddInverse y p) p = O.\n  \n  intuition.\n  unfold modNatAddInverse.\n  rewrite <- H.\n  rewrite modNat_plus.\n  rewrite minus_add_assoc.\n  rewrite (plus_comm).\n  rewrite <- minus_add_assoc.\n  rewrite minus_diag.\n  rewrite plus_0_r.\n  apply modNat_arg_eq.\n  \n  trivial.\n  \n  assert (modNat x p < p)%nat.\n  apply modNat_lt.\n  omega.\n  \nQed.\n\nLemma modNatAddInverse_correct : forall n p,\n    modNat (n + modNatAddInverse n p) p = O.\n\n  intuition.\n  eapply modNatAddInverse_correct_gen.\n  trivial.\n  \nQed.\n\nLemma modNat_correct : forall x (p : posnat),\n  exists k, (x = k * p + modNat x p)%nat.\n\n  intuition.\n  unfold modNat in *.\n  assert (p > 0)%nat.\n  eapply posnat_pos.\n  assert (posnatToNat p <> 0)%nat.\n  omega.\n  assert (N.of_nat p <> 0%N).\n  intuition.\n  eapply H0.\n  \n  rewrite <- Nnat.Nat2N.id.\n  rewrite <- (Nnat.Nat2N.id p).\n  f_equal.\n  trivial.\n\n  exists (N.to_nat (N.of_nat x / N.of_nat p)).\n  rewrite N.mod_eq; trivial.\n\n  rewrite <- (Nnat.Nat2N.id p) at 2.\n  rewrite <- Nnat.N2Nat.inj_mul.\n  rewrite <- Nnat.N2Nat.inj_add.\n  rewrite N.mul_comm.\n  remember (N.of_nat p * (N.of_nat x / N.of_nat p)) as z.\n  rewrite N.add_sub_assoc.\n  rewrite N.add_comm.\n  rewrite N.add_sub.\n  rewrite Nnat.Nat2N.id.\n  trivial.\n\n  subst.  \n  eapply N.mul_div_le.\n  trivial.\nQed.\n\nLemma modNat_divides : forall x p,\n  modNat x p = O ->\n  exists k, (x = k * p)%nat.\n\n  intuition.\n  destruct (modNat_correct x p).\n  rewrite H in H0.\n  econstructor.\n  rewrite plus_0_r in H0.\n  eauto.\nQed.\n\n\nLocal Open Scope nat_scope.\nLemma modNatAddInverse_sum_0 : forall x y p,\n  modNat (x + (modNatAddInverse y p)) p = O ->\n  modNat x p = modNat y p.\n  \n  intuition.\n  \n  assert (modNat x p < p).\n  eapply modNat_lt.\n  assert (modNat y p < p).\n  eapply modNat_lt.\n  \n  rewrite modNat_plus in H.\n  unfold modNatAddInverse in *.\n  rewrite minus_add_assoc in H; intuition.\n  rewrite plus_comm in H.\n  \n  apply modNat_divides in H.\n  destruct H.\n  \n  remember (modNat x p) as a.\n  remember (modNat y p) as b.\n  assert (p + a >= p).\n  omega.\n  assert (p + a < 2 * p)%nat.\n  omega.\n  assert (p + a - b < 2 * p).\n  omega.\n  assert (p + a - b > 0).\n  omega.\n  \n  assert (x0 * p > 0).\n  omega.\n  assert (x0 * p < 2 * p).\n  omega.\n  \n  destruct x0.\n  omega.\n  destruct x0.\n  \n  simpl in H.\n  rewrite plus_0_r in H.\n  omega.\n  \n  assert (p > 0).\n  eapply posnat_pos.\n  simpl in H7.\n  remember (x0 * p)%nat as c.\n  omega.\nQed.\n\nLemma modNat_correct_if : forall x y z (p : posnat),\n  x * p + y = z ->\n  modNat z p = modNat y p.\n  \n  induction x; intuition; simpl in *.\n  subst.\n  trivial.\n  \n  assert (x * p + (y + p) = z).\n  omega.\n  apply IHx in H0.\n  \n  rewrite H0.\n  rewrite plus_comm.\n  rewrite modNat_plus.\n  rewrite modNat_arg_eq.\n  rewrite plus_0_l.\n  trivial.\nQed.\n\nLemma modNat_mult : forall x (p : posnat),\n  modNat (x * p) p = 0.\n  \n  induction x; intuition; simpl in *.\n  rewrite modNat_plus.\n  rewrite modNat_arg_eq.\n  rewrite plus_0_l.\n  eauto.\n  \nQed.\n\nLemma modNat_add_same_l : forall x y z p,\n  modNat (x + y) p = modNat (x + z) p ->\n  modNat y p = modNat z p.\n  \n  induction x; intuition; simpl in *.\n  assert (S (x + y) = x + S y).\n  omega.\n  rewrite H0 in H.\n  clear H0.\n  assert (S (x + z) = x + S z).\n  omega.\n  rewrite H0 in H.\n  clear H0.\n  apply IHx in H.\n  \n  destruct (modNat_correct (S y) p).\n  destruct (modNat_correct (S z) p).\n  rewrite H in H0.\n  \n  assert (S y - x0 * p = modNat (S z) p).\n  omega.\n  assert (S z - x1 * p = modNat (S z) p).\n  omega.\n  rewrite <- H2 in H3.\n  \n  assert (z - x1 * p = y - x0 * p).\n  omega.\n  \n  assert (x1 * p + y = x0 * p + z).\n  omega.\n  \n  apply modNat_correct_if in H5.\n  rewrite modNat_plus in H5.\n  \n  rewrite modNat_mult in H5.\n  rewrite plus_0_l in H5.\n  auto.\n  \nQed.\n\nLemma modNat_add_same_r : forall x y z p,\n  modNat (y + x) p = modNat (z + x) p ->\n  modNat y p = modNat z p.\n  \n  intuition.\n  eapply (modNat_add_same_l x y z).\n  rewrite plus_comm.\n  rewrite H.\n  rewrite plus_comm.\n  trivial.\nQed.\n\nLemma expnat_base_S : forall n k,\n  ((expnat k n) + n * (expnat k (pred n)) <= expnat (S k) n)%nat.\n\n  induction n; intuition.\n  simpl in *.\n  eapply le_trans.\n  Focus 2.\n  eapply plus_le_compat.\n  eapply IHn.\n  eapply mult_le_compat.\n  eapply le_refl.\n  eapply IHn.\n\n  rewrite mult_plus_distr_l.\n  repeat rewrite mult_assoc.\n  repeat rewrite plus_assoc.\n  eapply plus_le_compat.\n  rewrite plus_comm.\n  eapply plus_le_compat.\n  rewrite <- (plus_0_r (expnat k n)) at 1.\n  eapply plus_le_compat. \n  omega.\n  intuition.\n  intuition.\n\n  rewrite (mult_comm k n).\n  rewrite <- (mult_assoc n).\n  destruct n; simpl; intuition.\nQed.\n\nLemma expnat_base_S_same : forall n,\n  n > 0 ->\n  (2 * (expnat n n) <= expnat (S n) n)%nat.\n\n  intuition.\n  simpl in *.\n  rewrite plus_0_r.\n  eapply le_trans.\n  Focus 2.\n  eapply expnat_base_S.\n  destruct n; simpl.\n  omega.\n  intuition.\nQed.\n\nLemma sqrt_le_lin_gen : forall a b,\n  (a <= b ->\n    sqrt a <= b)%nat.\n  \n  intuition.\n  eapply le_trans.\n  eapply Nat.sqrt_le_lin.\n  trivial.\nQed.\n\nLemma div2_le_mono : forall n1 n2,\n  (n1 <= n2 -> \n    div2 n1 <= div2 n2)%nat.\n  \n  induction n1; intuition.\n  destruct n2.\n  omega.\n  destruct (Even.even_odd_dec n1).\n  destruct (Even.even_odd_dec n2).\n  repeat rewrite <- even_div2; trivial.\n  eapply IHn1.\n  omega.\n  \n  rewrite <- even_div2; trivial.\n  rewrite <- odd_div2; trivial.\n  econstructor.\n  eapply IHn1.\n  omega.\n  \n  destruct (Even.even_odd_dec n2).\n  destruct (lt_dec n1 n2).\n  assert (n1 <= (S n2))%nat.\n  omega.\n  destruct n2.\n  omega.\n  rewrite <- odd_div2; trivial.\n  rewrite <- even_div2.\n  rewrite <- odd_div2.\n  eapply le_n_S.\n  eapply IHn1.\n  omega.\n  inversion e.\n  trivial.\n  trivial.\n  assert (n1 = n2).\n  omega.\n  subst.\n  exfalso.\n  eapply Even.not_even_and_odd; eauto.\n  \n  rewrite <- odd_div2; trivial.\n  rewrite <- odd_div2; trivial.\n  eapply le_n_S.\n  eapply IHn1.\n  omega.\n  \nQed.\n\nLemma div2_ge : forall n n',\n  n >= n' ->\n  forall x,\n    (n' = 2 * x)%nat ->\n    div2 n >= x.\n  \n  induction 1; intuition; subst; simpl in *.\n  specialize (div2_double x); intuition; simpl in *.\n  rewrite H.\n  omega.\n  \n  destruct m.\n  omega.\n  destruct (Even.even_odd_dec m).\n  rewrite even_div2.\n  assert (div2 (S m) >= x).\n  eapply IHle.\n  trivial.\n  omega.\n  trivial.\n  \n  rewrite odd_div2.\n  \n  eapply IHle.\n  trivial.\n  trivial.\nQed.\n\nInstance expnat_nz : forall k n (p : nz n),\n  nz (expnat n k).\n\nintuition.\n\ninduction k; intuition; simpl in *.\neconstructor.\nomega.\neconstructor.\nedestruct IHk; eauto.\ndestruct p.\neapply mult_gt_0; intuition.\n\nQed.\n  \nLemma expnat_2_ge_1 : forall n,\n  (1 <= expnat 2 n)%nat.\n\n  induction n; intuition; simpl in *.\n  omega.\nQed.\n\nLemma le_expnat_2 : forall n,\n  (n <= expnat 2 n)%nat.\n\n  induction n; intuition; simpl in *.\n  rewrite plus_0_r.\n  assert (S n = 1 + n)%nat.\n  omega.\n  rewrite H.\n  eapply plus_le_compat.\n  eapply expnat_2_ge_1.\n  trivial.\n  \nQed.\n\nLemma expnat_1 : forall k,\n  expnat 1%nat k = 1%nat.\n\n  induction k; intuition; simpl in *.\n  rewrite plus_0_r.\n  trivial.\n\nQed.\n\nTheorem expnat_base_le : \n  forall k n1 n2,\n    n1 <= n2 ->\n    expnat n1 k <=\n    expnat n2 k.\n  \n  induction k; intuition; simpl in *.\n  eapply mult_le_compat; intuition.\n  \nQed.\n\nTheorem expnat_double_le : \n  forall k n,\n    n >= 2 ->\n    expnat n (S k) >= 2 * expnat n k.\n\n  induction k; intuition; simpl in *.\n  omega.\n  rewrite plus_0_r.\n  rewrite <- mult_plus_distr_l.\n  eapply mult_le_compat.\n  trivial.\n  rewrite <- plus_0_r at 1.\n  rewrite <- plus_assoc.\n  eapply IHk.\n  trivial.\nQed.\n\nTheorem nat_half_plus : \n  forall x, \n    x > 1 ->\n    exists a b,\n      a > 0 /\\ b <= 1 /\\ x = 2 * a + b.\n  \n  induction x; intuition; simpl in *.\n  omega.\n  \n  destruct (eq_nat_dec x 1); subst.\n  exists 1.\n  exists 0.\n  intuition; omega.\n  \n  edestruct (IHx).\n  omega.\n  destruct H0.\n  intuition.\n  destruct x1.\n  rewrite plus_0_r in H3.\n  exists x0.\n  exists 1.\n  subst.\n  intuition; omega.\n  \n  exists (S x0).\n  exists 0.\n  subst.\n  intuition.\n            \nQed.\n\nTheorem log2_div2 : \n  forall x y,\n    S y = log2 x ->\n    log2 (div2 x) = y.\n  \n  intuition.\n  specialize (Nat.log2_double); intuition.\n  \n  destruct (@nat_half_plus x).\n  eapply Nat.log2_lt_cancel.\n  rewrite Nat.log2_1.\n  omega.\n  destruct H1.\n  intuition.\n  subst.\n  destruct x1.\n  rewrite plus_0_r in *.\n  rewrite div2_double.\n  rewrite H0 in H.\n  omega.\n  omega.\n  \n  destruct x1.\n  \n  rewrite plus_comm.\n  rewrite div2_double_plus_one.\n  \n  rewrite Nat.log2_succ_double in H.\n  omega.\n  omega.\n  \n  omega.\n  \nQed.\n\nLemma log2_0 : \n  log2 0 = 0.\n  trivial.\nQed.\n\nTheorem expnat_0 : \n  forall k,\n    k > 0 ->\n    expnat 0 k = 0.\n  \n  induction k; intuition; simpl in *.\n  \nQed.\n\nTheorem expnat_plus : \n  forall k1 k2 n,\n    expnat n (k1 + k2) = expnat n k1 * expnat n k2.\n  \n  induction k1; simpl in *; intuition.\n  rewrite IHk1.\n  rewrite mult_assoc.\n  trivial.\n  \nQed.\n\nTheorem expnat_ge_1 :\n  forall k n,\n    n > 0 ->\n    1 <= expnat n k.\n  \n  induction k; intuition; simpl in *.\n  rewrite <- mult_1_r at 1.\n  eapply mult_le_compat.\n  omega.\n  eauto.\nQed.\n\n\nTheorem expnat_exp_le : \n  forall n2 n4 n,\n    (n2 > 0 \\/ n > 0) ->\n    n2 <= n4 ->\n    expnat n n2 <= expnat n n4.\n  \n  induction n2; destruct n4; simpl in *; intuition.\n  rewrite <- mult_1_l at 1.\n  eapply mult_le_compat.\n  omega.\n  eapply expnat_ge_1; trivial.\n  \n  destruct (eq_nat_dec n 0); subst.\n  simpl; intuition.\n  eapply mult_le_compat; intuition.\n  \nQed.\n\nLemma mult_lt_compat : \n  forall a b c d,\n    a < b ->\n    c < d ->\n    a * c < b * d.\n  \n  intuition.\n  eapply le_lt_trans.\n  eapply mult_le_compat.\n  assert (a <= b).\n  omega.\n  eapply H1.\n  eapply le_refl.\n  eapply mult_lt_compat_l.\n  trivial.\n  omega.\nQed.\n\nTheorem orb_same_eq_if : \n  forall a b c,\n    (a = false -> b = c) ->\n    orb a b = orb a c.\n  \n  intuition.\n  destruct a; trivial; intuition.\n     \nQed.", "meta": {"author": "FreeAndFair", "repo": "RLA", "sha": "4295e4bb700ebbfe69affeb35dda7ed42273c3a1", "save_path": "github-repos/coq/FreeAndFair-RLA", "path": "github-repos/coq/FreeAndFair-RLA/RLA-4295e4bb700ebbfe69affeb35dda7ed42273c3a1/src/fcf/StdNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7331692523898844}}
{"text": "Add LoadPath \"megacz-coq-categories/build\".\n\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Unicode.Utf8.\n\nRequire Import Categories_ch1_3.\n\n\nDefinition Rel : Type -> Type -> Type\n  := fun a b : Type => a -> b -> Prop.\n\nDefinition rel_id : ∀ a : Type, Rel a a\n  := (fun a : Type => @eq a).\n\nDefinition rel_comp : ∀ a b c : Type, Rel a b -> Rel b c -> Rel a c\n  := fun a b c r1 r2 x y => exists z, r1 x z /\\ r2 z y.\n\n\nDefinition rel_eqv : ∀ a b : Type, Rel a b -> Rel a b -> Prop\n  := fun a b r1 r2 => ∀ x y, r1 x y <-> r2 x y.\n\n\nTheorem relation_category : Category Type Rel.\nProof.\n  apply (@Build_Category Type Rel rel_id rel_comp rel_eqv).\n  intros.\n  apply Build_Equivalence.\n  intro.\n  unfold rel_eqv.\n  intros.\n  reflexivity.\n\n  intro.\n  unfold rel_eqv.\n  intros.\n  symmetry.\n  auto.\n\n  intro.\n  unfold rel_eqv.\n  intros.\n  transitivity (y x0 y0).\n  auto.\n  auto.\n\n  intros.\n  constructor.\n  unfold rel_comp.\n\n  intros [z [??]].\n  exists z.\n  rewrite <- (H x1 z).\n  rewrite <- (H0 z y1).\n  auto.\n\n  unfold rel_comp.\n  intros [z [??]].\n  exists z.\n  rewrite (H x1 z).\n  rewrite (H0 z y1).\n  auto.\n\n  unfold rel_id.\n  unfold rel_comp.\n  unfold rel_eqv.\n  intros.\n  split.\n  intros.\n  destruct H.\n  destruct H.\n  rewrite H.\n  auto.\n\n  intros.\n  exists x.\n  auto.\n\n  intros.\n  unfold rel_id.\n  unfold rel_comp.\n  unfold rel_eqv.\n  intros.\n  split.\n  intro.\n  destruct H.\n  destruct H.\n  rewrite <- H0.\n  auto.\n\n  intro.\n  exists y.\n  auto.\n\n  intros.\n  unfold rel_comp.\n  unfold rel_eqv.\n  intros.\n  split.\n  intro.\n  destruct H.\n  destruct H.\n  destruct H.\n  destruct H.\n  exists x1.\n  split.\n  auto.\n\n  exists x0.\n  auto.\n\n  intro.\n  destruct H.\n  destruct H.\n  destruct H0.\n  destruct H0.\n  exists x1.\n  split.\n  exists x0.\n  auto.\n  auto.\nDefined.\n\n(*\nDefinition rel_comp : forall a b c : Type, Rel a b -> Rel b c -> Rel a c.\nProof.\n  intros.\n  intro.\n  intro.\n  refine (exists b' : b, _ /\\ _).\n  exact (X X1 b').\n  exact (X0 b' X2).\nDefined.\n*)\n", "meta": {"author": "khibino", "repo": "coq-Category-201205", "sha": "bcadb183fb95b66989738c7d7828f57a87caea44", "save_path": "github-repos/coq/khibino-coq-Category-201205", "path": "github-repos/coq/khibino-coq-Category-201205/coq-Category-201205-bcadb183fb95b66989738c7d7828f57a87caea44/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7331418452229347}}
{"text": "Structure BooleanAlgebra := {\n carrier :> Set; (* Coercion *)\n and : carrier -> carrier-> carrier;\n or : carrier -> carrier -> carrier;\n neg : carrier -> carrier;\n zero : carrier;\n one : carrier;\n and_p_0 : forall p, and p zero = zero;\n and_p_1 : forall p, and p one = p;\n and_p_Np : forall p, and p (neg p) = zero;\n and_p_p : forall p, and p p = p;\n neg_0 : neg zero = one;\n neg_neg : forall p, neg (neg p) = p;\n or_p_1 : forall p, or p one = one;\n or_p_0 : forall p, or p zero = p;\n or_p_Np : forall p, or p (neg p) = one;\n or_p_p : forall p, or p p = p;\n neg_or : forall p q, neg (or p q) = and (neg p) (neg q);\n neg_and : forall p q, neg (and p q) = or (neg p) (neg q);\n and_or : forall p q r, and p (or q r) = or (and p q) (and p r);\n or_and : forall p q r, or p (and q r) = and (or p q) (or p r);\n and_p_qr : forall p q r, and p (and q r) = and (and p q) r;\n or_p_qr : forall p q r, or p (or q r) = or (or p q) r;\n and_pq : forall p q, and p q = and q p;\n or_pq : forall p q, or p q = or q p\n}.\n\nNotation \"p & q\" := (and _ p q) (at level 40, left associativity).\nNotation \"p | q\" := (or _ p q) (at level 50, left associativity).\nNotation \"! p\" := (neg _ p) (at level 20).\nNotation \"1\" := (one _).\nNotation \"0\" := (zero _).\n\nStructure Hom (A B : BooleanAlgebra) := {\n  action :> A -> B;\n  mor_and: forall x y, action (x & y) = action x & action y;\n  mor_or: forall x y, action (x | y) = action x | action y;\n  mor_neg: forall x, action (! x) = !(action x)\n}.\n\nLemma id (B : BooleanAlgebra) : Hom B B.\nProof.\n  refine {| action := fun x => x |} ; reflexivity.\nDefined.\n\nDefinition compose A B C :\n  Hom B C -> Hom A B -> Hom A C.\nProof.\n  intros g f.\n  refine {| action := fun x => g (f x) |}.\n  -intros.\n  rewrite->mor_and.\n  rewrite->mor_and.\n  reflexivity.\n  -intros. rewrite->mor_or. rewrite->mor_or. reflexivity.\n  -intros. rewrite->mor_neg. rewrite ->mor_neg. reflexivity.\nDefined.\n\n\n\nNotation \"g 'o' f\" := (compose _ _ _ g f) (at level 65, left associativity).\n\n\nLemma Hom_0 (A B : BooleanAlgebra) (f : Hom A B) :\n  f 0 = 0.\nProof.\n  rewrite <- (and_p_Np A 0).\n  rewrite mor_and.\n  rewrite mor_neg.\n  rewrite and_p_Np.\n  reflexivity.\nQed.\n\nLemma Hom_1 (A B : BooleanAlgebra) (f: Hom A B):\n f 1 = 1.\nProof.\nAdmitted.\n\nLemma id_comp(A B : BooleanAlgebra)(f : Hom A B) : (id B) o f = f.\nAdmitted.\n\nLemma assos_o (A B C D : BooleanAlgebra)(f : Hom A B) (g : Hom B C) (h : Hom C D): h o (g o f) = (h o g) o f. \nAdmitted.\n\nLemma and_pq_r (B : BooleanAlgebra) (p q r : B) :\n  (p | q) & r = p & r | q & r.\nProof.\n rewrite <-and_pq.\n rewrite->and_or.\n rewrite->and_pq.\n rewrite->or_pq.\n rewrite->and_pq.\n rewrite->or_pq.\n reflexivity.\nQed.\n\n\n\n\nLemma neg_1 (L : BooleanAlgebra) : ! 1 = (0 : L).\nProof.\n  rewrite <- neg_0.\n  rewrite -> neg_neg.\n  reflexivity.\nQed.\n\nDefinition Two : BooleanAlgebra.\nProof.\n  (* We use bool and its operations from the standard library *)\n  refine {| carrier := bool ;\n            and := andb ;\n            or := orb ;\n            neg := negb ;\n            zero := false ;\n            one := true\n         |} ; repeat (intros [|]) ; reflexivity.\nDefined.\n\nDefinition pointwise0 {B : Set} (c : B) (I : Set) :\n  (I -> B) :=\n  fun i => c.\n\nDefinition pointwise1 {B : Set} (op : B -> B) (I : Set) :\n  (I -> B) -> (I -> B) :=\n  fun f i => op (f i).\n\nDefinition pointwise2 {B : Set} (op : B -> B -> B) (I : Set) :\n  (I -> B) -> (I -> B) -> (I -> B) :=\n  fun f g i => op (f i) (g i).\n\n(* Function extensionality. *)\nAxiom funext :\n  forall (X : Type) (P : X -> Type) (f g : (forall x, P x)),\n    (forall x, f x = g x) -> f = g.\n\n(* Function extensionality for simple types. *)\nLemma funext_simple (X Y : Type) (f g : X -> Y) :\n  (forall x, f x = g x) -> f = g.\nProof.\n  apply (funext X (fun x => Y)).\nDefined.\n\nDefinition Power (B : BooleanAlgebra) (I : Set) : BooleanAlgebra.\nProof.\n  refine {| carrier := I -> B ;\n            and := pointwise2 (and B) I ;\n            or := pointwise2 (or B) I ;\n            neg := pointwise1 (neg B) I ;\n            zero := pointwise0 (zero B) I ;\n            one := pointwise0 (one B) I\n         |} ;\n  (intros ; apply funext_simple ; intro i ; unfold pointwise0, pointwise1, pointwise2).\n  - apply and_p_0.\n  - apply and_p_1.\n  - apply and_p_Np.\n  - apply and_p_p.\n  - apply neg_0.\n  - apply neg_neg.\n  - apply or_p_1.\n  - apply or_p_0.\n  - apply or_p_Np.\n  - apply or_p_p.\n  - apply neg_or.\n  - apply neg_and.\n  - apply and_or.\n  - apply or_and.\n  - apply and_p_qr.\n  - apply or_p_qr.\n  - apply and_pq.\n  - apply or_pq.\nDefined.\n\nInductive Colors := Red | Green | Blue.\n\n(* Boolean algebra with eight elements. *)\nDefinition EightBA := Power Two Colors.\n\n(* The opposite algebra. *)\nDefinition Opposite (B : BooleanAlgebra) : BooleanAlgebra.\nProof.\n  refine {| carrier := carrier B ;\n            and := or B ;\n            or := and B ;\n            neg := neg B ;\n            one := zero B ;\n            zero := one B\n         |}.\nintros.\n-apply or_p_1.\n-apply or_p_0.\n-apply or_p_Np.\n-apply or_p_p.\n-apply neg_1.\n-apply neg_neg.\n-apply and_p_0.\n-apply and_p_1.\n-apply and_p_Np.\n-apply and_p_p.\n-apply neg_and.\n-apply neg_or.\n-apply or_and.\n-apply and_or.\n-apply or_p_qr.\n-apply and_p_qr.\n-apply or_pq.\n-apply and_pq.\nDefined.\n", "meta": {"author": "mmaleki", "repo": "LogicalDifferentiation", "sha": "2a46afc6ae55680fb4416dadbe295c0b617bc4f4", "save_path": "github-repos/coq/mmaleki-LogicalDifferentiation", "path": "github-repos/coq/mmaleki-LogicalDifferentiation/LogicalDifferentiation-2a46afc6ae55680fb4416dadbe295c0b617bc4f4/BooleanAlgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7331418394842715}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  plus lf2 (mult lf2 y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj282_coqofml_navk0v.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7331187877535594}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\n(* ** Definition of FRACTRAN *)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW \n  Require Import utils_tac utils_list utils_nat gcd rel_iter pos vec.\n\nRequire Import Undecidability.FRACTRAN.FRACTRAN.\n\nSet Default Proof Using \"Type\".\n\nSet Implicit Arguments.\n\nSection fractran_utils.\n\n  Implicit Type l : list (nat*nat).\n\n  Fact fractran_step_nil_inv x y : nil /F/ x → y <-> False.\n  Proof. split; inversion 1. Qed.\n\n  Fact fractran_step_cons_inv p q l x y : \n     (p,q)::l /F/ x → y <-> q*y = p*x \\/ ~ divides q (p*x) /\\ l /F/ x → y.\n  Proof.\n    split.\n    + inversion 1; auto.\n    + intros [ H | (H1 & H2) ]; [ constructor 1 | constructor 2 ]; auto. \n  Qed.\n\n  Fact mul_pos_inj_l q x y : q <> 0 -> q*x = q*y -> x = y.\n  Proof.\n    intros H1 H2.\n    destruct q; try lia.\n    apply le_antisym; apply mult_S_le_reg_l with q; lia.\n  Qed.\n\n  Lemma fractran_step_inv P x y : \n            P /F/ x → y \n         -> exists l p q r, P = l++(p,q)::r \n                         /\\ (forall u v, In (u,v) l -> ~ divides v (u*x))\n                         /\\ q*y=p*x.\n  Proof.\n    induction 1 as [ p q P x y H | u v P x y H1 H2 IH2 ].\n    + exists nil, p, q, P; simpl; tauto.\n    + destruct IH2 as (l & p & q & r & -> & H4 & H5).\n      exists ((u,v)::l), p, q, r; simpl; msplit 2; auto.\n      intros ? ? [ H | H ]; auto; inversion H; subst; auto.\n  Qed. \n\n  (* Regular FRACTRAN programs define a deterministic step relation *)\n\n  Lemma fractran_step_fun l x y1 y2 : \n           fractran_regular l \n        -> l /F/ x → y1 \n        -> l /F/ x → y2 -> y1 = y2.\n  Proof.\n    intros H1 H2 ; revert H2 H1 y2.\n    induction 1 as [ p q l x y1 H1 | p q l x y1 H1 H2 IH2 ]; \n      intros H0 y2 H3; rewrite fractran_step_cons_inv in H3; \n      destruct H3 as [ H3 | (H3 & H4) ].\n    + apply Forall_cons_inv, proj1 in H0.\n      simpl in H0.\n      revert H1; rewrite <- H3.\n      apply mul_pos_inj_l; auto.\n    + destruct H3; exists y1; rewrite <- H1; ring.\n    + destruct H1; exists y2; rewrite <- H3; ring.\n    + apply Forall_cons_inv, proj2 in H0; auto.\n  Qed.\n\n  (* Regular FRACTRAN programs deefine a linearly bounded step relation \n     The bound computed in the following proofs is very lazy. \n     Indeed we choose p1+...+pn whereas ideally,\n     one could choose max(ceil(pi/qi)) where l = [p1/q1;...;pn/qn] *)\n  \n  Lemma fractran_step_bound l : \n          fractran_regular l \n       -> { k | forall x y, l /F/ x → y -> y <= k*x }.\n  Proof.\n    unfold fractran_regular.\n    induction l as [ | (p,q) l IHl ].\n    + intros _; exists 1; auto.\n      intros ? ? H; exfalso; revert H; apply fractran_step_nil_inv.\n    + intros H; rewrite Forall_cons_inv in H; simpl in H.\n      destruct H as (Hq & H).\n      destruct (IHl H) as (k & H2).\n      exists (p+k).\n      intros x y Hxy.\n      apply fractran_step_cons_inv in Hxy.\n      destruct Hxy as [ Hxy | (_ & Hxy) ].\n      * rewrite Nat.mul_add_distr_r, <- Hxy.\n        destruct q; simpl; try lia.\n      * apply le_trans with (1 := H2 _ _ Hxy).\n        apply mult_le_compat; lia.\n  Qed.\n\n  Fact fractan_stop_nil_inv x : fractran_stop nil x <-> True.\n  Proof.\n    split; try tauto; intros _ z; rewrite fractran_step_nil_inv; tauto.\n  Qed.\n\n  Fact fractan_stop_cons_inv p q l x : \n       fractran_stop ((p,q)::l) x <-> ~ divides q (p*x) /\\ fractran_stop l x.\n  Proof.\n    split.\n      * intros H.\n        assert (~ divides q (p*x)) as H'.\n        { intros (z & Hz); apply (H z); constructor; rewrite Hz; ring. }\n        split; auto.\n        intros z Hz; apply (H z); constructor 2; auto.\n      * intros (H1 & H2) z Hz.\n        apply fractran_step_cons_inv in Hz. \n        destruct Hz as [ H3 | (H3 & H4) ].\n        - apply H1; exists z; rewrite <- H3; ring.\n        - apply (H2 _ H4).\n  Qed.\n\n  Fact fractran_step_dec l x : { y | l /F/ x → y } + { fractran_stop l x }.\n  Proof.\n    induction l as [ | (a,b) l IH ].\n    + right; rewrite fractan_stop_nil_inv; auto.\n    + destruct (divides_dec (a*x) b) as [ (y & Hy) | ].\n      * left; exists y; constructor 1; rewrite Hy; ring.\n      * destruct IH as [ (y & ?) | ].\n        - left; exists y; now constructor 2.\n        - right; apply fractan_stop_cons_inv; auto.\n  Qed.\n\n  (* Now we treat the cases where (_,0) occurs in l *)\n\n  Let remove_zero_den l := filter (fun c => if eq_nat_dec (snd c) 0 then false else true) l.\n\n  Let remove_zero_den_Forall l : fractran_regular (remove_zero_den l).\n  Proof.\n    unfold fractran_regular.\n    induction l as [ | (p,q) ]; simpl; auto.\n    destruct (eq_nat_dec q 0); auto.\n  Qed.\n\n  Section zero_cases.\n\n    Fact fractran_zero_num_step l : \n            Exists (fun c => fst c = 0) l \n         -> forall x, exists y, l /F/ x → y. \n    Proof.\n      induction 1 as [ (p,q) l Hl | (p,q) l Hl IHl ]; simpl in Hl.\n      + intros x; exists 0; subst; constructor; lia.\n      + intros x.\n        destruct (divides_dec (p*x) q) as [ (y & Hy) | C ].\n        * exists y; constructor; rewrite Hy, mult_comm; auto.\n        * destruct (IHl x) as (y & Hy); exists y; constructor 2; auto.\n    Qed.\n\n    Lemma FRACTRAN_HALTING_zero_num l x : \n             Exists (fun c => fst c = 0) l \n          -> FRACTRAN_HALTING (l,x) <-> False.\n    Proof.\n      intros H; split; try tauto.\n      intros (y & _ & H3). \n      destruct fractran_zero_num_step with (1 := H) (x := y) as (z & Hz). \n      apply H3 with (1 := Hz).\n    Qed.\n\n    Fact fractran_step_head_not_zero p q l y : q <> 0 -> (p,q)::l /F/ 0 → y -> y = 0.\n    Proof.\n      intros H2 H3.\n      apply fractran_step_cons_inv in H3.\n      destruct H3 as [ H3 | (H3 & _) ].\n      + rewrite Nat.mul_0_r in H3; apply mult_is_O in H3; lia.\n      + destruct H3; exists 0; ring.\n    Qed.\n\n    Fact fractran_rt_head_not_zero p q l n y : q <> 0 -> fractran_steps ((p,q)::l) n 0 y -> y = 0.\n    Proof.\n      intros H2.\n      induction n as [ | n IHn ].\n      + simpl; auto.\n      + intros (a & H3 & H4).\n        apply fractran_step_head_not_zero in H3; subst; auto.\n    Qed.\n\n    Lemma FRACTRAN_HALTING_on_zero_first_no_zero_den p q l : q <> 0 -> FRACTRAN_HALTING ((p,q)::l,0) <-> False. \n    Proof.\n      intros Hq; split; try tauto.\n      intros (y & (k & H1) & H2).\n      apply fractran_rt_head_not_zero in H1; auto.\n      subst y; apply (H2 0); constructor 1; ring.\n    Qed.\n\n    Fact fractran_step_no_zero_den l x y : fractran_regular l -> l /F/ x → y -> x = 0 -> y = 0.\n    Proof.\n      unfold fractran_regular.\n      intros H1 H2; revert H2 H1.\n      induction 1 as [ p q l x y H | p q l x y H1 H2 IH2 ]; rewrite Forall_cons_inv; simpl; intros (H3 & H4) ?; subst.\n      + rewrite Nat.mul_0_r in H; apply mult_is_O in H; lia.\n      + destruct H1; exists 0; ring.\n    Qed.\n\n    Fact fractran_step_no_zero_num l : Forall (fun c => fst c <> 0) l -> forall x y, l /F/ x → y -> y = 0 -> x = 0.\n    Proof.\n      intros H1 x y H2; revert H2 H1.\n      induction 1 as [ p q l x y H1 | p q l x y H1 H2 IH2 ]; intros H3; rewrite Forall_cons_inv in H3; simpl in H3; destruct H3 as (H3 & H4); auto.\n      intros; subst y; rewrite Nat.mul_0_r in H1; symmetry in H1; apply mult_is_O in H1; lia.\n    Qed.\n\n    Fact fractran_rt_no_zero_den l n y : fractran_regular l -> fractran_steps l n 0 y -> y = 0.\n    Proof.\n      intros H; induction n as [ | n IHn ].\n      + simpl; auto.\n      + intros (x & H1 & H2).\n        apply fractran_step_no_zero_den with (1 := H) in H1; subst; auto.\n    Qed.\n\n    Fact fractran_rt_no_zero_num l : Forall (fun c => fst c <> 0) l -> forall n x, fractran_steps l n x 0 -> x = 0.\n    Proof.\n      intros H; induction n as [ | n IHn ]; intros x; simpl; auto.\n      intros (y & H1 & H2).\n      apply IHn in H2.\n      revert H1 H2; apply fractran_step_no_zero_num; auto.\n    Qed.\n\n    Fact fractran_zero_num l x : Exists (fun c => fst c = 0) l -> exists y, l /F/ x → y.\n    Proof.\n      induction 1 as [ (p,q) l | (p,q) l Hl IHl ]; simpl in *.\n      + exists 0; constructor 1; subst; ring.\n      + destruct (divides_dec (p*x) q) as [ (y & Hy) | H ].\n        * exists y; constructor 1; rewrite Hy; ring.\n        * destruct IHl as (y & Hy); exists y; constructor 2; auto.\n    Qed.\n\n    Corollary FRACTRAN_HALTING_0_num l x : Exists (fun c => fst c = 0) l -> FRACTRAN_HALTING (l,x) <-> False.\n    Proof.\n      intros H1; split; try tauto; intros (y & H2 & H3).\n      destruct (fractran_zero_num y H1) as (z & ?).\n      apply (H3 z); auto.\n    Qed.\n\n    Lemma fractran_step_zero l : \n             Forall (fun c => fst c <> 0) l \n          -> forall x y, x <> 0 -> l /F/ x → y\n                     <-> remove_zero_den l /F/ x → y.\n    Proof.\n      induction 1 as [ | (p,q) l H1 H2 IH2 ]; intros x y Hxy; simpl in *.\n      * split; simpl; inversion 1.\n      * simpl; destruct (eq_nat_dec q 0) as [ Hq | Hq ].\n        - rewrite <- IH2; auto; subst; split; intros H.\n          + apply fractran_step_cons_inv in H; destruct H as [ H | (H3 & H4) ]; auto.\n            simpl in H; symmetry in H; apply mult_is_O in H; lia.\n          + constructor 2; auto; intros H'.\n            apply divides_0_inv, mult_is_O in H'; lia.\n        - split; intros H.\n          + apply fractran_step_cons_inv in H; destruct H as [ H | (H3 & H4) ]; auto.\n            -- constructor 1; auto.\n            -- constructor 2; auto; apply IH2; auto.\n          + apply fractran_step_cons_inv in H; destruct H as [ H | (H3 & H4) ]; auto.\n            -- constructor 1; auto.\n            -- constructor 2; auto; apply IH2; auto.\n    Qed.\n\n    Lemma fractran_rt_no_zero_den_0_0 l : \n           l <> nil -> fractran_regular l -> fractran_step l 0 0.\n    Proof.\n      destruct l as [ | (p,q) l ]; intros H1 H.\n      + destruct H1; auto.\n      + clear H1; apply Forall_cons_inv, proj1 in H.\n        constructor 1; ring.\n    Qed.\n\n    Corollary FRACTRAN_HALTING_l_0_no_zero_den l : \n            l <> nil -> fractran_regular l -> FRACTRAN_HALTING (l,0) <-> False.\n    Proof.\n      intros H1 H2; split; try tauto.\n      generalize (fractran_rt_no_zero_den_0_0 H1 H2); intros H3. \n      intros (y & (n & H5) & H6).\n      apply fractran_rt_no_zero_den in H5; auto; subst.\n      apply (H6 0); auto.\n    Qed.\n\n    Lemma FRACTRAN_HALTING_nil_x x : FRACTRAN_HALTING (nil,x) <-> True.\n    Proof.\n      split; try tauto; intros _. \n      exists x; split.\n      + exists 0; simpl; auto.\n      + inversion 1.\n    Qed.\n\n    Lemma FRACTRAN_HALTING_l_1_no_zero_den l x : \n           l <> nil \n        -> x <> 0 \n        -> Forall (fun c => fst c <> 0) l \n        -> FRACTRAN_HALTING (l,x) <-> FRACTRAN_HALTING (remove_zero_den l,x).\n    Proof.\n      intros H1 H2 H3.\n      generalize (fractran_step_zero H3); intros H4.\n      assert (forall n y, fractran_steps l n x y -> y <> 0) as H5.\n      { intros n y H ?; subst; apply H2; revert H; apply fractran_rt_no_zero_num; auto. }\n      assert (forall n y, fractran_steps (remove_zero_den l) n x y -> y <> 0) as H6.\n      { intros n y H ?; subst; apply H2; revert H; apply fractran_rt_no_zero_num; auto; apply Forall_filter; auto. }\n      assert (forall n y, rel_iter (fractran_step l) n x y <-> rel_iter (fractran_step (remove_zero_den l)) n x y) as H7.\n      { induction n as [ | n IHn ]; intros y.\n        + simpl; try tauto.\n        + do 2 rewrite rel_iter_S; split.\n          * intros (a & G1 & G2); exists a; split.\n            - apply IHn; auto.\n            - apply H4; auto.\n              apply H5 with (1 := G1).\n          * intros (a & G1 & G2); exists a; split.\n            - apply IHn; auto.\n            - apply H4; auto.\n              apply H6 with (1 := G1). }\n      split; intros (y & (n & G1) & G3); exists y; split.\n      + exists n; apply H7; auto.\n      + intros z Hz; apply (G3 z); revert Hz; apply H4, H5 with n; auto.\n      + exists n; apply H7; auto.\n      + intros z Hz; apply (G3 z); revert Hz; apply H4, H6 with n; auto.\n    Qed.\n   \n    Lemma FRACTRAN_HALTING_hard p l : \n           p <> 0 \n        -> FRACTRAN_HALTING ((p,0)::l,0) \n       <-> exists x, x <> 0 /\\ FRACTRAN_HALTING ((p,0)::l,x).\n    Proof.\n      intros H; split.\n      + intros (y & (n & H1) & H2).\n        assert (y <> 0) as Hy.\n        { intro; subst; apply (H2 0); constructor; auto. }\n        unfold fractran_steps in H1; rewrite rel_iter_sequence in H1.\n        destruct H1 as (f & F1 & F2 & F3).\n        destruct (first_non_zero f n) as (i & G1 & G2 & G3); subst; auto.\n        exists (f (i+1)); split; auto.\n        exists (f n); split; auto.\n        exists (n-i-1); red; rewrite rel_iter_sequence.\n        exists (fun j => f (j+i+1)); split; auto.\n        split; [ f_equal; lia | ].\n        intros j Hj; apply F3; lia.\n      + intros (x & H1 & (y & (n & Hn) & H2)).\n        exists y; split; auto.\n        exists (S n), x; split; auto.\n        constructor 1; ring.\n    Qed.\n\n  End zero_cases.\n\n  (* The case (l,0) where l does not contains (0,_) but is of the form (p,0)::_ (with p <> 0) is complicated \n     because first step could lead to any value and then we have to find some x <> 0 such that FRACTRAN_HALTING (l,x) \n \n     Summary: forall ll a list of nat*nat, x input\n\n       1) if (_,0) does not appear in ll, this is solved by FRACTRAN_HALTING_diophantine_0\n       2) if (_,0) occurs in ll\n        2.1) if (0,_) occurs in ll, then the program never halts\n        2.2) if (0,_) does not appear in ll\n          2.2.1) if x <> 0, the same halting as with removing all the (_,0) from ll\n          2.2.2) if x = 0,\n            2.2.2.1) if l starts with (_,0) let ll' be ll where (_,0) are removed\n                        halting equivalent to exists y, y <> 0 /\\ halting ll' y\n            2.2.2.2) if l starts with (_,q) and q <> 0, never halts\n\n   *)\n\n  Fact FRACTAN_cases ll :  { Exists (fun c => fst c = 0) ll }\n                         + { Forall (fun c => snd c <> 0) ll }\n                         + { p : nat & { mm | Forall (fun c => fst c <> 0) ll /\\ Exists (fun c => snd c = 0) ll \n                                           /\\ ll = (p,0):: mm /\\ p <> 0 } }\n                         + { p : nat & { q : nat & { mm | Forall (fun c => fst c <> 0) ll /\\ Exists (fun c => snd c = 0) ll \n                                          /\\ ll = (p,q):: mm /\\ q <> 0 /\\ p <> 0 } } }.\n  Proof.\n    destruct (Forall_Exists_dec (fun c : nat * nat => snd c <> 0)) with (l := ll) as [ ? | Hl1 ]; auto.\n    { intros (p, q); destruct (eq_nat_dec q 0); simpl; subst; [ right | left]; lia. }\n    assert (Exists (fun c => snd c = 0) ll) as H1.\n    { revert Hl1; induction 1; [ constructor 1 | constructor 2 ]; auto; lia. }\n    clear Hl1.\n    destruct (Forall_Exists_dec (fun c : nat * nat => fst c <> 0)) with (l := ll) as [ Hl3 | Hl3 ].\n    { intros (p, q); destruct (eq_nat_dec p 0); simpl; subst; [ right | left ]; lia. }\n    2: { do 3 left; clear H1; revert Hl3; induction 1; [ constructor 1 | constructor 2 ]; auto; lia. }\n    case_eq ll.\n    { intro; subst; exfalso; inversion H1. }\n    intros (p,q) mm Hll.\n    destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n    { subst; rewrite Forall_cons_inv in Hl3; simpl in Hl3; lia. }\n    destruct q.\n    + left; right; exists p, mm; subst; auto.\n    + right; exists p, (S q), mm; subst; repeat (split; auto).\n  Qed.\n\nEnd fractran_utils.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/FRACTRAN/FRACTRAN/fractran_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7331187863960401}}
{"text": "Include Nat.\nRequire Import ZArith.\nRequire Import NArith.\n\n\nLemma even_p : forall n, even n = true -> exists x, n = 2 * x.\nProof.\n  assert (Main: forall n, (even n = true -> exists x, n = 2 * x) /\\\n                  (even (S n) = true -> exists x, S n = 2 * x)).\n  induction n.\n  split.\n  exists 0.\n  simpl.\n  reflexivity.\n  simpl.\n  discriminate.\n  split.\n  intros.\n  apply IHn in H.\n  exact H.\n  intros.\n  destruct IHn as [H' _].\n  simpl even in H.\n  simpl even in H.\n  destruct H'.\n  exact H.\n  exists (x + 1).\n  simpl.\n  intuition.\n  intros.\n  destruct (Main n) as [H' _].\n  apply H'.\n  exact H.\nQed.\n\nLemma pred_S_eq : forall (x y : nat), x = S y -> pred x = y.\nProof.\nintros.\nunfold pred.\nrewrite H.\nreflexivity.\nQed.\n\n\n\nFixpoint sum_odd_n (n : nat) : nat :=\n  match n with\n    | 0 => 0\n    | S n => (2 * n + 1) + sum_odd_n n\n  end.\n\nCompute sum_odd_n 4.\n\nLemma lemma1 : forall (a b : nat), S (a + b) = S a + b.\nProof.\nintros.\ninduction a.\nintuition.\nsimpl.\nreplace (S (a + b)) with (S a + b).\nreflexivity.\nQed.\n\n\nLemma lemma3 : forall (a b : nat), S (a + b) = a + S b.\nProof.\nintros.\ninduction a.\nintuition.\nsimpl.\nreplace (S (a + b)) with (a + S b).\nreflexivity.\nQed.\n\nLemma lemma2 : forall (a b : nat), a * (S b) = a * b + a. \nProof.\nintros.\ninduction a.\nsimpl.\nreflexivity.\nsymmetry.\nintuition.\nQed.\n\nTheorem sum_odd_squares : forall (n : nat), sum_odd_n n = n * n.\nProof.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  replace (sum_odd_n n) with (n * n).\n  replace (n + 0) with n.\n  replace (S (n + n* S n)) with (n + 1 + (n * n) + n).\n  intuition.\n  replace (S (n + n * S n)) with (S n + n * S n).\n  replace (S n + n * S n) with (S n + n * n + n).\n  intuition.\n  replace (n * S n) with (n * n + n).\n  intuition.\n  replace (n * S n) with (n * n + n).\n  intuition. \n  symmetry.\n  apply lemma2.\n  simpl.\n  reflexivity.\n  intuition.\nQed.\n\nLemma succ_inj : forall (x y : nat), x = y -> pred x = pred y.\nProof.\nintros.\ndestruct x.\ndestruct y.\nunfold pred.\nreflexivity.\ndiscriminate.\ndestruct x.\nrewrite H.\nreflexivity.\nrewrite H.\nreflexivity.\nQed.\n\n\nSearchPattern (nat -> nat -> bool).\n\n\nFixpoint upTo (n : nat) : list nat :=\n  match n with\n  | 0 => 0 :: nil\n  | S k => S k :: upTo k\n  end.\n\nCompute upTo 3.\n\nLemma or_comm : forall (a b : Prop), a \\/ b -> b \\/ a.\nProof.\nintros.\ndestruct H as [H1 | H2].\nright.\nexact H1.\nleft.\nexact H2.\nQed.\n\n\nDefinition pierce := forall (p q : Prop), ((p -> q) -> p) -> p.\n\nDefinition lem := forall (p :Prop), p \\/ ~p.\n\nTheorem piece_lem_equiv : pierce <-> lem.\nProof.\n  unfold pierce, lem.\n  firstorder.\n  apply H with (q := ~(p \\/ ~p)).\n  tauto.\n  destruct (H p).\n  assumption.\n  tauto.\nQed.\n\nFixpoint add (a b : nat) : nat :=\n  match a with\n  | 0 => b\n  | S n => S (add n b)\n  end.\n\nTheorem left_add_ident : forall (a : nat), (add 0 a) = a.\nProof.\n  intro.\n  reflexivity.\nQed.\n\nTheorem right_add_ident : forall (a : nat), (add a 0) = a.\nProof.\n  induction a.\n  reflexivity.\n  simpl.\n  rewrite IHa.\n  reflexivity.\nQed.\n\nLemma eq_nat_inductive : forall (a b : nat), (a = b) -> (S a = S b).\nProof.\n  intros.\n  subst.\n  reflexivity.\nQed.\n\nTheorem add_comm : forall (a b : nat), add a b = add b a.\nProof.\n  induction a.\n  induction b.\n  reflexivity.\n  rewrite left_add_ident.\n  rewrite right_add_ident.\n  reflexivity.\n  induction b.\n  rewrite left_add_ident.\n  rewrite right_add_ident.\n  reflexivity.\n  simpl.\n  apply eq_nat_inductive.\n  symmetry in IHb.\n  assert (e := IHa).\n  change (add (S a) b) with (S (add a b)) in IHb.\n  specialize (IHa b).\n  apply eq_nat_inductive in IHa.\n  rewrite IHa in IHb.\n  change (S (add b a)) with (add (S b) a) in IHb.\n  symmetry in IHa.\n  change (S (add a b)) with (S (add b a)) in IHb.\n  symmetry in IHb.\n  specialize e with (b := S b).\n  rewrite <- IHb.\n  apply e.\nQed.\n\nTheorem add_assoc : forall (a b c : nat), add a (add b c) = add (add a b) c.\nProof.\n  induction a.\n  induction b.\n  intro c.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  intro b.\n  intro c.\n  specialize (IHa b c).\n  apply eq_nat_inductive in IHa.\n  apply IHa.\nQed.", "meta": {"author": "martyall", "repo": "coq-sandbox", "sha": "8a416dcca53a7fea7b9693edd9853623caa0d8dd", "save_path": "github-repos/coq/martyall-coq-sandbox", "path": "github-repos/coq/martyall-coq-sandbox/coq-sandbox-8a416dcca53a7fea7b9693edd9853623caa0d8dd/identity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.733117419997359}}
{"text": "Require Import List Bool Lia Classical.\n\nImport ListNotations.\nFrom mathcomp Require Import ssreflect.\n\nVariable var : Type.\nVariable fls tru : var.\n\nInductive prop :=\n  | Var : var -> prop\n  | Not : prop -> prop\n  | And : prop -> prop -> prop\n  | Or : prop -> prop -> prop\n  | Imp : prop -> prop -> prop\n  (* | Top : prop *)\n  (* | Bot : prop *)\n  .\n\n\n\nNotation \"# p\" := (Var p) (at level 1).\nNotation \"A ∨ B\" := (Or A B) (at level 15, right associativity).\nNotation \"A ∧ B\" := (And A B) (at level 15, right associativity).\nNotation \"A ⊃ B\" := (Imp A B) (at level 16, right associativity).\nNotation \"¬ A\" := (Not A) (at level 5).\n(* Notation \"⊥\" := Bot (at level 0). *)\n(* Notation \"⊤\" := ( Not Bot) (at level 0). *)\nNotation \"⊥\" := (# fls).\nNotation \"⊤\" := (# tru).\n\nDefinition assign := var -> bool.\nAxiom fls_false : forall f : assign, f fls = false.\nAxiom tru_true  : forall f : assign, f tru = true.\n\n\nFixpoint valuation (v : assign) (A : prop) :=\n  match A with\n  | # p => v p\n  | ¬ A => negb (valuation v A)\n  | A ∧ B => andb (valuation v A) (valuation v B)\n  | A ∨ B => orb (valuation v A) (valuation v B)\n  | A ⊃ B => implb (valuation v A) (valuation v B)\n  (* | ⊤ => true *)\n  (* | ⊥ => false *)\n  end.\n\nDefinition tautology A :=\n  forall v, valuation v A = true.\n\nDefinition equiv A B :=\n  (A ⊃ B) ∧ (B ⊃ A).\n\nDefinition eqtot A B :=\n  tautology (equiv A B).\n\nReserved Notation \"Γ → Δ\" (at level 80).\nInductive prv : list prop -> list prop -> Prop :=\n  | init A : [A] → [A]\n  | initTop : [] → [⊤]\n  | initBot : [⊥] → []\n\n  | weakL A Γ Δ : Γ → Δ -> (A :: Γ) → Δ\n  | weakR A Γ Δ : Γ → Δ -> Γ → (Δ ++ [A])\n\n  | contraL A Γ Δ : (A :: A :: Γ) → Δ -> (A :: Γ) → Δ\n  | contraR A Γ Δ : Γ → (Δ ++ [A ; A]) -> Γ → (Δ ++ [A])\n\n  | changeL A B Γ Π Δ : (Γ ++ A :: B :: Π) → Δ -> (Γ ++ B :: A :: Π) → Δ\n  | changeR A B Γ Δ Σ : Γ → (Δ ++ A :: B :: Σ) -> Γ → (Δ ++ B :: A :: Σ)\n\n  | cut A Γ Π Δ Σ : Γ → (Δ ++ [A]) -> A :: Π → Σ -> Γ ++ Π → Δ ++ Σ\n\n  | andL1 A B Γ Δ : A :: Γ → Δ ->  A ∧ B :: Γ → Δ\n  | andL2 A B Γ Δ : B :: Γ → Δ ->  A ∧ B :: Γ → Δ\n  | andR A B Γ Δ : Γ → Δ ++ [A] -> Γ → Δ ++ [B] ->  Γ → Δ ++ [A ∧ B]\n\n  | orL A B Γ Δ : A :: Γ → Δ -> B :: Γ → Δ -> A ∨ B :: Γ → Δ\n  | orR1 A B Γ Δ : Γ → Δ ++ [A] -> Γ → Δ ++ [A ∨ B]\n  | orR2 A B Γ Δ : Γ → Δ ++ [B] -> Γ → Δ ++ [A ∨ B]\n\n  | impL A B Γ Π Δ Σ : Γ → Δ ++ [A] -> B :: Π → Σ -> A ⊃ B :: Γ ++ Π → Δ ++ Σ\n  | impR A B Γ Δ : A :: Γ → Δ ++ [B] -> Γ → Δ ++ [A ⊃ B]\n\n  | notL A Γ Δ : Γ → Δ ++ [A] -> ¬ A :: Γ → Δ\n  | notR A Γ Δ : A :: Γ → Δ -> Γ → Δ ++ [¬ A]\n\n  where \"Γ → Δ\" := (prv Γ Δ).\n\nLemma cons_app {A} (a : A) l :\n  a :: l = [a] ++ l.\nProof.\n  induction l => //=.\nQed.\n\n(* 1.13 *)\nGoal forall A, [] → [A ∨ ¬ A].\nProof.\n  intro A.\n\n  rewrite <- app_nil_l;\n  apply contraR; simpl.\n\n  rewrite cons_app;\n  apply orR1; simpl.\n\n  rewrite <- app_nil_l;\n  apply changeR; simpl.\n\n  rewrite cons_app;\n  apply orR2.\n\n  apply notR.\n  apply init.\nQed.\n\n(*　問1.14 *)\nGoal forall A B, [(A ⊃ B)] → [¬ (A ∧ ¬ B)].\nProof.\n  intros A B.\n  rewrite <- app_nil_l;\n  apply notR.\n\n  rewrite <- (app_nil_l [_; _]);\n  apply contraL.\n  apply andL2.\n\n  rewrite <- (app_nil_l [¬ B; A ∧ ¬ B; A ⊃ B]);\n  apply changeL; simpl.\n  apply andL1.\n\n  rewrite cons_app;\n  apply changeL; simpl.\n\n  rewrite <- (app_nil_l ([A; A ⊃ B; ¬ B]));\n  apply changeL; simpl.\n\n  rewrite <- (app_nil_l nil);\n  rewrite (cons_app A [¬ B]);\n  eapply impL; simpl.\n  - apply init.\n  - rewrite <- (app_nil_l [B; ¬ B]);\n    apply changeL; simpl.\n    apply notL; simpl.\n    apply init.\nQed.\n\nGoal forall A B Γ Δ, A :: Γ → Δ ++ [B] -> Γ → Δ ++ [¬ A ∨ B].\nProof.\n  intros A B Γ Δ H.\n  apply contraR.\n  assert (Δ ++ [¬ A ∨ B; ¬ A ∨ B] = (Δ ++ [¬ A ∨ B]) ++  [¬ A ∨ B]). {\n    rewrite <- app_assoc; auto.\n  }\n  rewrite H0; clear H0.\n  apply orR1.\n  apply notR.\n  apply orR2.\n  apply H.\nQed.\n\n\n(* 1.115.1 *)\nTheorem cons_andor  A1 A2 B1 B2 :\n  [A1; A2] → [B1; B2] -> [A1 ∧ A2] → [B1 ∨ B2].\nProof.\n  intros H.\n  apply contraL.\n  apply andL2.\n  rewrite <- (app_nil_l [_; _]);\n  apply changeL; simpl.\n  apply andL1.\n  rewrite <- (app_nil_l [_ ∨ _]);\n  apply contraR; simpl.\n  assert ([B1 ∨ B2; B1 ∨ B2] = [B1 ∨ B2] ++ [B1 ∨ B2]) by auto;\n  rewrite H0; clear H0;\n  apply orR1; simpl.\n  rewrite <- (app_nil_l [_; B1]);\n  apply changeR; simpl.\n  assert ([B1; B1 ∨ B2] = [B1] ++  [B1 ∨ B2]) by auto;\n  rewrite H0; clear H0;\n  apply orR2; simpl.\n  auto.\nQed.\n\n(* 1.115.2 *)\nTheorem andor_imp A1 A2 B1 B2 :\n  [A1 ∧ A2] → [B1 ∨ B2] -> [] → [A1 ∧ A2 ⊃ B1 ∨ B2].\nProof.\n  intros H;\n  rewrite <- (app_nil_l [_ ⊃ _]);\n  apply impR; simpl.\n  auto.\nQed.\n\n(* 1.115.3 *)\nTheorem imp_cons A1 A2 B1 B2 :\n  [] → [A1 ∧ A2 ⊃ B1 ∨ B2] -> [A1 ; A2] → [B1 ; B2].\nProof.\n  intro H.\n  rewrite <- (app_nil_l [_; _]).\n  rewrite <- (app_nil_l [B1;_]).\n  apply cut with ( A := A1 ∧ A2 ⊃ B1 ∨ B2); simpl.\n  - auto.\n  - assert ([A1 ∧ A2 ⊃ B1 ∨ B2; A1; A2] = A1 ∧ A2 ⊃ B1 ∨ B2 ::  [A1; A2] ++ []) by auto;\n    rewrite H0; clear H0;\n    rewrite <- (app_nil_l [B1; B2]);\n    apply impL; simpl.\n    - rewrite <- (app_nil_l [_ ∧ _]);\n      apply andR; simpl.\n      - rewrite <- (app_nil_l [_ ; _]);\n        apply changeL; simpl.\n        apply weakL.\n        apply init.\n      - apply weakL.\n        apply init.\n    - apply orL.\n      * rewrite (cons_app B1 [B2]);\n        apply weakR.\n        apply init.\n      * rewrite <- app_nil_l;\n        rewrite <- (app_nil_r [B1; B2]);\n        apply changeR; simpl.\n        rewrite (cons_app B2 [B1]);\n        apply weakR.\n        apply init.\nQed.\n\n\nFixpoint bigAnd l :=\n  match l with\n  | [] => ⊤\n  | p :: l' => p ∧ bigAnd l'\n  end.\n\n\nFixpoint bigOr l :=\n  match l with\n  | [] => ⊥\n  | p :: l' => p ∨ bigOr l'\n  end.\n\nNotation \"Γ ₊\" := (bigAnd Γ)(at level 15).\nNotation \"Γ ⁺\" := (bigOr Γ)(at level 15).\n\nLemma bigOr_app l r v :\n  valuation v (bigOr (l ++ r)) = valuation v  (bigOr l ∨ bigOr r).\nProof.\n  induction l => //=.\n  rewrite fls_false => //=.\n  rewrite IHl => /=.\n  apply orb_assoc.\nQed.\n\nLemma bigAnd_app l r v :\n  valuation v (bigAnd (l ++ r)) = valuation v  (bigAnd l ∧ bigAnd r).\nProof.\n  induction l => //=.\n  rewrite tru_true; simpl; auto .\n  rewrite IHl => //=.\n  apply andb_assoc.\nQed.\n\n\nTheorem soundness Γ Δ :\n  Γ → Δ -> tautology (bigAnd Γ ⊃ bigOr Δ).\nProof.\n  induction 1; intro v; simpl;\n    try repeat match goal with\n    | [H : tautology _ |- _] => specialize (H v); simpl in H\n    end;\n\n    try rewrite bigOr_app in IHprv;\n    try rewrite bigOr_app in IHprv1;\n    try rewrite bigOr_app in IHprv2;\n    try rewrite bigAnd_app in IHprv;\n    try rewrite bigAnd_app in IHprv1;\n    try rewrite bigAnd_app in IHprv2; simpl in *;\n\n    try rewrite IHprv;\n    try rewrite IHprv1;\n    try rewrite IHprv2;\n    try rewrite bigAnd_app;\n    try rewrite bigOr_app;\n    try rewrite fls_false;\n    try rewrite tru_true; simpl; auto;\n\n    try destruct (valuation v (bigAnd Γ));\n    try destruct (valuation v (bigOr Δ));\n    try destruct (valuation v (bigAnd Π));\n    try destruct (valuation v (bigOr Σ));\n    try destruct (valuation v A);\n    try destruct (valuation v B); simpl; auto;\n\n    try rewrite fls_false in IHprv;\n    try rewrite fls_false in IHprv1;\n    try rewrite fls_false in IHprv2; simpl in *; auto;\n    inversion IHprv.\nQed.\n\n\nNotation sqc := (prod (list prop) (list prop)).\nNotation dcp :=( prod (option sqc) (option sqc)).\n\n(* Inductive decomp : dcp -> sqc -> Prop :=\n  | andRt A B Γ Δ1 Δ2 :\n    decomp (Some (Γ, ( Δ1 ++ A :: Δ2)), (Some (Γ ,( Δ1 ++ B :: Δ2)))) (Γ, ( Δ1 ++ A ∧ B :: Δ2))\n  | andLt A B Γ1 Γ2 Δ :\n     decomp ((Some (Γ1 ++ A :: B :: Γ2, Δ)), None) ((Γ1 ++ A ∧ B :: Γ2 ), Δ)\n  | orRt A B Γ Δ1 Δ2 :\n    decomp (Some (Γ, ( Δ1 ++ A :: B :: Δ2)), None) (Γ, ( Δ1 ++ A ∨ B :: Δ2))\n  | orLt A B Γ1 Γ2 Δ :\n    decomp (Some ((Γ1 ++ A :: Γ2 ), Δ), Some ((Γ1 ++ B :: Γ2 ),Δ )) ((Γ1 ++ A ∨ B :: Γ2 ), Δ)\n  | impRt A B Γ Δ1 Δ2 :\n    decomp (Some ((A :: Γ ), ( Δ1 ++ B :: Δ2)), None) (Γ, ( Δ1 ++ A ⊃ B :: Δ2))\n  | impLt A B Γ1 Γ2 Δ :\n    decomp (Some ((Γ1 ++  Γ2 ), ( Δ ++ [A])), Some ((Γ1 ++ B :: Γ2 ), Δ)) ((Γ1 ++ A ⊃ B :: Γ2 ), Δ)\n  | notRt A Γ Δ1 Δ2 :\n    decomp (Some ((A :: Γ ), ( Δ1 ++ Δ2)), None) (Γ, ( Δ1 ++ ¬ A :: Δ2))\n  | notLt A Γ1 Γ2 Δ :\n    decomp (Some ((Γ1 ++ Γ2 ), ( Δ ++ [A])), None) ((Γ1 ++ ¬ A :: Γ2 ), Δ). *)\n\n\n\n\n\nInductive decomp : list prop -> list prop -> list prop -> list prop -> Prop :=\n  | andR1P A B Γ Δ1 Δ2 : decomp Γ ( Δ1 ++ A :: Δ2) Γ ( Δ1 ++ A ∧ B :: Δ2)\n  | andR2P A B Γ Δ1 Δ2 : decomp Γ ( Δ1 ++ B :: Δ2) Γ ( Δ1 ++ A ∧ B :: Δ2)\n  | andLP A B Γ1 Γ2 Δ : decomp (Γ1 ++ A :: B :: Γ2 ) Δ (Γ1 ++ A ∧ B :: Γ2 ) Δ\n\n  | orRP A B Γ Δ1 Δ2 : decomp Γ ( Δ1 ++ A :: B :: Δ2) Γ ( Δ1 ++ A ∨ B :: Δ2)\n  | orLP1 A B Γ1 Γ2 Δ : decomp (Γ1 ++ A :: Γ2 ) Δ (Γ1 ++ A ∨ B :: Γ2 ) Δ\n  | orLP2 A B Γ1 Γ2 Δ : decomp (Γ1 ++ B :: Γ2 ) Δ (Γ1 ++ A ∨ B :: Γ2 ) Δ\n\n  | impRP A B Γ Δ1 Δ2 : decomp (A :: Γ ) ( Δ1 ++ B :: Δ2) Γ ( Δ1 ++ A ⊃ B :: Δ2)\n  | impLP1 A B Γ1 Γ2 Δ : decomp (Γ1 ++  Γ2 ) ( Δ ++ [A]) (Γ1 ++ A ⊃ B :: Γ2 ) Δ\n  | impLP2 A B Γ1 Γ2 Δ : decomp (Γ1 ++ B :: Γ2 ) Δ (Γ1 ++ A ⊃ B :: Γ2 ) Δ\n\n  | notRP A Γ Δ1 Δ2 : decomp (A :: Γ ) ( Δ1 ++ Δ2) Γ ( Δ1 ++ ¬ A :: Δ2)\n  | notLP A Γ1 Γ2 Δ : decomp (Γ1 ++ Γ2 ) ( Δ ++ [A]) (Γ1 ++ ¬ A :: Γ2 ) Δ.\n\n\nFixpoint count (A : prop) : nat :=\n  match A with\n  | # p => 0\n\n  (* | ⊥ => 0 *)\n  | ¬ B => 1 + count B\n  | B ∧ C => 1 + count B + count C\n  | B ∨ C => 1 + count B + count C\n  | B ⊃ C => 1 + count B + count C\n  end.\n\n\n\nFixpoint sum l : nat :=\n  match l with\n  | [] => 0\n  | a :: l' => a + sum l'\n  end.\n\nDefinition counts (l : list prop) := sum (map count l).\nDefinition counts' p := counts (fst p) + counts (snd p).\n\n\nTheorem sum_app l r :\n  sum (l ++ r) = sum l + sum r.\nProof.\n  induction l => //=.\n  rewrite IHl.\n  rewrite PeanoNat.Nat.add_assoc; auto.\nQed.\n\n(* Theorem decomp_lt pp p :\n  decomp pp p ->\n  match pp with\n  | (Some pl, None) => counts' pl < counts' p\n  | (Some pl, Some pr) => counts' pl < counts' p /\\ counts' pr < counts' p\n  | _ => False\n  end.\nProof.\n  move => H; induction H; try split;\n  rewrite /counts' /counts;\n  repeat rewrite  map_app sum_app => //=; lia.\nQed. *)\n\n\nTheorem decomp_lt Γ Δ Γ' Δ' :\n  decomp Γ' Δ' Γ Δ -> counts Γ' + counts Δ' < counts Γ + counts Δ.\nProof.\n  induction 1;\n  repeat rewrite /counts map_app sum_app //=; try lia.\nQed.\n\nDefinition tautology' p := tautology (((fst p)₊ ⊃ (snd p)⁺)).\n\n(* Theorem decomp_tautology pp p :\n  decomp pp p -> tautology' p ->\n  match pp with\n  | (Some pl, None) => tautology' p\n  | (Some pl, Some pr) => tautology' pl /\\ tautology' pr\n  | _ => False\n  end.\nProof.\n  inversion_clear 1 => H; try split;\n  move => f;\n  specialize (H f);\n  simpl in *;\n  try rewrite bigOr_app;\n  try rewrite bigAnd_app;\n  try rewrite bigOr_app in H;\n  try rewrite bigAnd_app in H;\n  simpl in *;\n  try destruct (valuation f A);\n  try destruct (valuation f B);\n  try destruct (valuation f (bigAnd Γ));\n  try destruct (valuation f (bigAnd Γ1));\n  try destruct (valuation f (bigAnd Γ2));\n  try destruct (valuation f (bigOr Δ));\n  try destruct (valuation f (bigOr Δ1));\n  try destruct (valuation f (bigOr Δ2));\n  simpl in *; auto; inversion H.\nQed. *)\n\n\n\n\n(* 1.10.2 *)\nTheorem decomp_tautology Γ Δ Γ' Δ' :\n  decomp Γ' Δ' Γ Δ -> tautology (Γ₊⊃Δ⁺) -> tautology (Γ'₊⊃Δ'⁺).\nProof.\n  move => H;\n    inversion_clear H => H f;\n    specialize (H f);\n    simpl in *;\n    try rewrite bigOr_app;\n    try rewrite bigAnd_app;\n    try rewrite bigOr_app in H;\n    try rewrite bigAnd_app in H;\n    simpl in *;\n    try destruct (valuation f A);\n    try destruct (valuation f B);\n    try destruct (valuation f (bigAnd Γ));\n    try destruct (valuation f (bigAnd Γ1));\n    try destruct (valuation f (bigAnd Γ2));\n    try destruct (valuation f (bigOr Δ));\n    try destruct (valuation f (bigOr Δ1));\n    try destruct (valuation f (bigOr Δ2));\n    simpl in *; auto; inversion H.\nQed.\n\nTheorem in_ex {A} (a : A) (l : list A) :\n  In a l -> exists h t, l = h ++ a :: t.\nProof.\n  induction l => H //=.\n  induction H; subst.\n  - exists [], l; auto.\n  - move : (IHl H) => [h [t Hl]]; subst.\n    exists (a0 :: h), t; auto.\nQed.\n\nDefinition allf := fun _ : var => false.\n\n\n\nDefinition allt := fun _ : var => true.\n\n\n\n\n\n\nReserved Notation \"Γ ⟶ Δ\" (at level 80).\nInductive prv' : list prop -> list prop -> Prop :=\n  | initc A : [A] ⟶ [A]\n  | initTopc : [] ⟶ [⊤]\n  | initBotc : [⊥] ⟶ []\n\n  | weakLc A Γ Δ : Γ ⟶ Δ -> (A :: Γ) ⟶ Δ\n  | weakRc A Γ Δ : Γ ⟶ Δ -> Γ ⟶ (Δ ++ [A])\n\n  | contraLc A Γ Δ : (A :: A :: Γ) ⟶ Δ -> (A :: Γ) ⟶ Δ\n  | contraRc A Γ Δ : Γ ⟶ (Δ ++ [A ; A]) -> Γ ⟶ (Δ ++ [A])\n\n  | changeLc A B Γ Π Δ : (Γ ++ A :: B :: Π) ⟶ Δ -> (Γ ++ B :: A :: Π) ⟶ Δ\n  | changeRc A B Γ Δ Σ : Γ ⟶ (Δ ++ A :: B :: Σ) -> Γ ⟶ (Δ ++ B :: A :: Σ)\n\n  | andL1c A B Γ Δ : A :: Γ ⟶ Δ ->  A ∧ B :: Γ ⟶ Δ\n  | andL2c A B Γ Δ : B :: Γ ⟶ Δ ->  A ∧ B :: Γ ⟶ Δ\n  | andRc A B Γ Δ : Γ ⟶ Δ ++ [A] -> Γ ⟶ Δ ++ [B] ->  Γ ⟶ Δ ++ [A ∧ B]\n\n  | orLc A B Γ Δ : A :: Γ ⟶ Δ -> B :: Γ ⟶ Δ -> A ∨ B :: Γ ⟶ Δ\n  | orR1c A B Γ Δ : Γ ⟶ Δ ++ [A] -> Γ ⟶ Δ ++ [A ∨ B]\n  | orR2c A B Γ Δ : Γ ⟶ Δ ++ [B] -> Γ ⟶ Δ ++ [A ∨ B]\n\n  | impLc A B Γ Π Δ Σ : Γ ⟶ Δ ++ [A] -> B :: Π ⟶ Σ -> A ⊃ B :: Γ ++ Π ⟶ Δ ++ Σ\n  | impRc A B Γ Δ : A :: Γ ⟶ Δ ++ [B] -> Γ ⟶ Δ ++ [A ⊃ B]\n\n  | notLc A Γ Δ : Γ ⟶ Δ ++ [A] -> ¬ A :: Γ ⟶ Δ\n  | notRc A Γ Δ : A :: Γ ⟶ Δ -> Γ ⟶ Δ ++ [¬ A]\n  where \"Γ ⟶ Δ\" := (prv' Γ Δ).\n\n\n\n\n\n\n\n\nTheorem changeL' A l1 l2 r :\n  l1 ++ l2 ++ [A] ⟶ r -> l1 ++ A :: l2 ⟶ r.\nProof.\n  move : l1; induction l2 => //= l1 H.\n  apply changeLc.\n  assert (a :: A :: l2 = [a] ++ A :: l2) by induction l2 => //=.\n  rewrite H0; clear H0.\n  rewrite app_assoc.\n  apply IHl2.\n  rewrite <- app_assoc.\n  assert ([a] ++ l2 ++ [A] = a :: l2 ++ [A]) by induction l2 => //=.\n  rewrite H0; clear H0; auto.\nQed.\n\nTheorem changeL'' A l1 l2 r :\n  l1 ++ A :: l2 ⟶ r -> l1 ++ l2 ++ [A] ⟶ r.\nProof.\n  move : l1.\n  induction l2 => /= l1 H //=.\n  rewrite app_comm_cons.\n  rewrite app_assoc.\n  assert (l1 ++ a :: l2 = (l1 ++ [a]) ++ l2). {\n    clear H.\n    induction l1 => //=.\n    rewrite IHl1; auto.\n  }\n  rewrite H0; clear H0.\n  rewrite <- app_assoc.\n  apply IHl2.\n  assert ((l1 ++ [a]) ++ A :: l2 = l1 ++ a :: A :: l2). {\n    clear H; induction l1 => //=; rewrite IHl1; auto.\n  }\n  rewrite H0; clear H0.\n  apply changeLc; auto.\nQed.\n\n\n\n\n\n\nTheorem changeR' A l r1 r2 :\n  l ⟶ r1 ++ r2 ++ [A] -> l ⟶ r1 ++ A :: r2.\nProof.\n  move : r1; induction r2 => //= r1 H.\n  apply changeRc.\n  assert (a :: A :: r2 = [a] ++ A :: r2) by induction r2 => //=.\n  rewrite H0; clear H0.\n  rewrite app_assoc.\n  apply IHr2.\n  rewrite <- app_assoc.\n  assert ([a] ++ r2 ++ [A] = a :: r2 ++ [A]) by induction r2 => //=.\n  rewrite H0; clear H0; auto.\nQed.\n\nTheorem changeR'' A l r1 r2 :\nl ⟶ r1 ++ A :: r2 ->  l ⟶ r1 ++ r2 ++ [A] .\nProof.\n  move : r1; induction r2 => r1 H //=.\n  rewrite app_comm_cons.\n  rewrite app_assoc.\n  assert (r1 ++ a :: r2 = (r1 ++ [a]) ++ r2). {\n    clear H.\n    induction r1 => //=.\n    rewrite IHr1; auto.\n  }\n  rewrite H0; clear H0.\n  rewrite <- app_assoc.\n  apply IHr2.\n  assert ((r1 ++ [a]) ++ A :: r2 = r1 ++ a :: A :: r2). {\n    clear H; induction r1 => //=; rewrite IHr1; auto.\n  }\n  rewrite H0; clear H0.\n  apply changeRc; auto.\nQed.\n\nTheorem swapL l1 l2 r :\n  (l1 ++ l2) ⟶ r -> (l2 ++ l1) ⟶ r.\nProof.\n  move : l1; induction l2 => l1 //= H.\n  - rewrite app_nil_r in H; auto.\n  - rewrite cons_app app_assoc in H.\n    apply IHl2 in H.\n    rewrite app_comm_cons.\n    assert (a :: l2 = [a] ++ l2) by (induction l2 => //=).\n    rewrite H0; clear H0.\n    rewrite <- app_assoc.\n    rewrite <- (app_nil_l (_ ++ _)).\n    apply changeL'; simpl.\n    rewrite <- app_assoc; auto.\nQed.\n\nTheorem swapR l r1 r2 :\n  l ⟶ r1 ++ r2 -> l ⟶ r2 ++ r1.\nProof.\n  move : r1; induction r2 => r1 //= H.\n  - rewrite app_nil_r in H; auto.\n  - rewrite cons_app app_assoc in H.\n    apply IHr2 in H.\n    rewrite app_comm_cons.\n    rewrite cons_app.\n    rewrite <- app_assoc.\n    rewrite <- (app_nil_l (_ ++ _)).\n    apply changeR'; simpl.\n    rewrite <- app_assoc; auto.\nQed.\n\nTheorem changeL''' A l1 l2 r :\n  A :: (l1 ++ l2) ⟶ r -> l1 ++ A :: l2 ⟶ r.\nProof.\n  move : r l2; induction l1 => //= r l2 H.\n  rewrite <- (app_nil_l (a :: _)).\n  apply changeL'; simpl.\n  rewrite <- app_assoc.\n  rewrite cons_app.\n  rewrite <- app_assoc.\n  rewrite <- (cons_app A).\n  apply IHl1.\n  rewrite cons_app.\n  apply swapL.\n  repeat rewrite <- app_assoc.\n  rewrite app_assoc; simpl.\n  apply changeLc.\n  apply swapL; simpl; auto.\nQed.\n\nTheorem weakL' A l r :\n  [A] ⟶ r -> A :: l ⟶ r .\nProof.\n  move : A r; induction l => // A r H.\n  rewrite <- (app_nil_l (A :: _)).\n  apply changeLc; simpl.\n  apply weakLc.\n  apply IHl; auto.\nQed.\n\nTheorem weakR' A l r :\n  l ⟶ [A] -> l ⟶ r ++ [A].\nProof.\n  move : A l; induction r => //= A l H.\n  rewrite <- (app_nil_l (a :: _)).\n  apply changeR'; simpl.\n  apply weakRc.\n  apply IHr; auto.\nQed.\n\n(* 1.11.2 *)\nTheorem same_elm A Γ1 Γ2 Δ1 Δ2 :\n  Γ1 ++ A :: Γ2 ⟶ Δ1 ++ A :: Δ2.\nProof.\n  apply changeL'''.\n  apply changeR'.\n  apply weakL'.\n  rewrite app_assoc.\n  apply weakR'.\n  apply initc.\nQed.\n\n\n\nTheorem contraR' l r1 r2 :\n  l ⟶ r1 ++ r2 ++ r2 -> l ⟶ r1 ++ r2.\nProof.\n  move : r1; induction r2 => r1 H //=.\n  rewrite cons_app app_assoc.\n  apply IHr2.\n  rewrite <- app_assoc.\n  apply changeR'.\n  rewrite app_assoc.\n  apply contraRc.\n  rewrite cons_app in H.\n  rewrite <- app_assoc in H.\n  apply changeR'' in H.\n  rewrite app_assoc in H.\n  rewrite (app_assoc r1 r2) in H.\n  rewrite <- app_assoc in H.\n  assert (([a] ++ r2) ++ [a] = [a] ++ r2 ++ [a]).\n    rewrite app_assoc; auto.\n  rewrite H0 in H.\n  apply changeR'' in H.\n  repeat rewrite <- app_assoc in H.\n  simpl in H.\n  repeat rewrite <- app_assoc; auto.\nQed.\n\nTheorem contraL' l1 l2 r :\n  l1 ++ l2 ++ l2 ⟶ r -> l1 ++ l2 ⟶ r.\nProof.\n  move : l1; induction l2 => l1 H //=.\n  rewrite cons_app app_assoc.\n  apply IHl2.\n  rewrite <- app_assoc.\n  apply swapL.\n  repeat rewrite  <- app_assoc.\n  rewrite <- cons_app.\n  apply contraLc.\n  repeat rewrite app_comm_cons.\n  rewrite app_assoc.\n  apply swapL.\n  repeat rewrite <- app_comm_cons.\n  apply changeL'.\n  rewrite <- app_comm_cons.\n  apply changeL'.\n  repeat rewrite <- app_assoc.\n  rewrite <- app_comm_cons in H.\n  apply changeL'' in H.\n  repeat rewrite app_assoc in H.\n  rewrite <- app_assoc in H.\n  rewrite <- app_comm_cons in H.\n  apply changeL'' in H.\n  repeat rewrite <- app_assoc in H; auto.\nQed.\n\nDefinition prv'' (pp : dcp) :=\n    match pp with\n    | (Some p, None) => fst p ⟶ snd p\n    | (Some pl, Some pr) => fst pl ⟶ snd pl /\\ fst pr ⟶ snd pr\n    | _ => False\n    end.\n\n\n\n\n\nTheorem decomp_prv A B X Y :\n  (* decomp X Y A B <==> X ⟶ Y が A ⟶ B の分解 *)\n  (forall X Y, decomp X Y A B -> X ⟶ Y) ->\n  decomp X Y A B ->\n  X ⟶ Y -> A ⟶ B.\nProof.\n  move => H0 Hd XY.\n  inversion Hd; subst.\n  - apply changeR'.\n    rewrite app_assoc.\n    apply andRc;\n      rewrite <- app_assoc;\n      eapply changeR'' => //.\n    apply H0; constructor.\n  - apply changeR'.\n    rewrite app_assoc.\n    apply andRc;\n      rewrite <- app_assoc;\n      eapply changeR'' => //.\n    apply H0; constructor.\n  - apply swapL.\n    rewrite <- app_comm_cons.\n    apply contraLc.\n    apply andL1c.\n    rewrite <- (app_nil_l (_ :: _)); apply changeL'; simpl.\n    apply andL2c.\n    rewrite <- (app_nil_l (_ :: _)); apply changeL'; simpl.\n    repeat rewrite <- app_assoc.\n    apply swapL.\n    repeat rewrite <- app_assoc.\n    repeat rewrite <- cons_app; auto.\n  - apply swapR.\n    rewrite cons_app.\n    rewrite <- app_assoc.\n    rewrite <- (app_nil_l).\n    apply changeR'; simpl.\n    apply contraRc.\n    rewrite cons_app app_assoc.\n    apply orR1c.\n    rewrite <- app_assoc.\n    apply changeR'.\n    rewrite app_assoc.\n    apply orR2c.\n    repeat rewrite <- app_assoc.\n    apply swapR.\n    repeat rewrite <- app_assoc.\n    repeat rewrite <- cons_app; auto.\n  - apply swapL.\n    rewrite <- app_comm_cons.\n    apply orLc.\n    - rewrite <- (app_nil_l (_ :: _)). apply changeL'; simpl.\n      rewrite <- app_assoc.\n      apply swapL.\n      rewrite <- app_assoc, <- cons_app; auto.\n    - rewrite <- (app_nil_l (_ :: _)). apply changeL'; simpl.\n      rewrite <- app_assoc.\n      apply swapL.\n      rewrite <- app_assoc, <- cons_app.\n      apply H0; constructor.\n  - apply swapL.\n    rewrite <- app_comm_cons.\n    apply orLc.\n    - rewrite <- (app_nil_l (_ :: _)). apply changeL'; simpl.\n      rewrite <- app_assoc.\n      apply swapL.\n      rewrite <- app_assoc, <- cons_app.\n      apply H0; constructor.\n    - rewrite <- (app_nil_l (_ :: _)). apply changeL'; simpl.\n      rewrite <- app_assoc.\n      apply swapL.\n      rewrite <- app_assoc, <- cons_app; auto.\n  - rewrite cons_app.\n    apply swapR.\n    rewrite <- app_assoc, <- app_nil_l.\n    apply changeR'; simpl.\n    apply impRc.\n    rewrite <- app_assoc.\n    apply swapR.\n    rewrite <- app_assoc.\n    rewrite <- cons_app; auto.\n  - apply swapL.\n    rewrite <- app_comm_cons.\n    rewrite <- app_nil_l.\n    apply contraR'; simpl.\n    rewrite cons_app.\n    apply contraL'.\n    rewrite <- cons_app.\n    apply impLc.\n    - apply swapL; auto.\n    - rewrite cons_app app_assoc.\n      apply swapL.\n      rewrite <- cons_app.\n      apply H0; constructor.\n  { apply swapL.\n    rewrite <- app_comm_cons;\n    rewrite <- app_nil_l;\n    apply contraR'; simpl.\n    rewrite cons_app;\n    apply contraL'.\n    rewrite <- cons_app;\n    apply impLc.\n    - apply swapL.\n      apply H0.\n      constructor.\n    - rewrite cons_app app_assoc;\n      apply swapL.\n      rewrite <- cons_app.\n      auto.\n  }\n  - apply changeR'.\n    rewrite app_assoc.\n    apply notRc; auto.\n  - apply swapL.\n    rewrite cons_app.\n    rewrite  <- app_assoc.\n    rewrite <- cons_app.\n    apply notLc.\n    apply swapL; auto.\nQed.\n\nSection computability.\n\nVariable A B : prop.\nDefinition S:= [A ⊃ B; A ⊃ B; A ⊃ B; A ⊃ B; A] → [B].\n\nGoal S.\nProof.\n  unfold S.\n\n  rewrite <- (app_nil_l [B]).\n  apply contraR; simpl.\n  rewrite (cons_app B _).\n  rewrite <- (app_nil_r (cons _ _)).\n  eapply impL; [|apply init].\n  apply weakR.\n\n  rewrite <- (app_nil_l [B]).\n  apply contraR; simpl.\n  rewrite (cons_app B _).\n  rewrite <- (app_nil_r (cons _ _)).\n  eapply impL; [|apply init].\n  apply weakR.\n\n  rewrite <- (app_nil_l [B]).\n  apply contraR; simpl.\n  rewrite (cons_app B _).\n  rewrite <- (app_nil_r (cons _ _)).\n  eapply impL; [|apply init].\n  apply weakR.\n\n\n  simpl.\n  rewrite <- app_nil_l.\n  rewrite <- (app_nil_r [A ⊃ B;A]).\n  apply impL; simpl ;apply init.\nQed.\n\n\n\n\nEnd computability.\n\n\n\n\n\n\n\n\n\n\n\n\nLemma op_ex l :\n  counts l > 1 ->\n    (exists A B, In (A ∧ B) l) \\/\n    (exists A B, In (A ∨ B) l) \\/\n    (exists A B, In (A ⊃ B) l) \\/\n    (exists A, In (¬ A) l).\nProof.\n  induction l => H; [inversion H|].\n  destruct a; try (\n    rewrite /counts in H;\n    move : (IHl H) => [[A [B H']] | [[A [B H']] | [[A [B H']] | [A  H']]]];\n    [left | right; left | right; right; left | right; right; right];\n    try (exists A, B; right; auto );\n    exists A; right; auto);\n    [right; right; right | left | right; left | right; right; left];\n    try (exists a; left; auto);\n    exists a1, a2; left; auto.\nQed.\n\n\n\nInductive tree : list prop -> list prop -> Type :=\n  | leaf l r : counts l = 0 -> counts r = 0 -> tree l r\n  | andRt A B Γ Δ1 Δ2 :\n    tree Γ ( Δ1 ++ A :: Δ2) -> tree Γ ( Δ1 ++ B :: Δ2) -> tree Γ ( Δ1 ++ A ∧ B :: Δ2)\n  | andLt A B Γ1 Γ2 Δ :\n    tree (Γ1 ++ A :: B :: Γ2 ) Δ -> tree (Γ1 ++ A ∧ B :: Γ2 ) Δ\n  | orRt A B Γ Δ1 Δ2 :\n    tree Γ ( Δ1 ++ A :: B :: Δ2) -> tree  Γ ( Δ1 ++ A ∨ B :: Δ2)\n  | orLt A B Γ1 Γ2 Δ :\n    tree (Γ1 ++ A :: Γ2 ) Δ -> tree  (Γ1 ++ B :: Γ2 ) Δ ->  tree (Γ1 ++ A ∨ B :: Γ2 ) Δ\n  | impRt A B Γ Δ1 Δ2 :\n    tree (A :: Γ ) ( Δ1 ++ B :: Δ2) -> tree Γ ( Δ1 ++ A ⊃ B :: Δ2)\n  | impLt A B Γ1 Γ2 Δ :\n    tree (Γ1 ++  Γ2 ) ( Δ ++ [A]) -> tree (Γ1 ++ B :: Γ2 ) Δ  ->tree (Γ1 ++ A ⊃ B :: Γ2 ) Δ\n  | notRt A Γ Δ1 Δ2 :\n    tree (A :: Γ ) ( Δ1 ++ Δ2) -> tree Γ ( Δ1 ++ ¬ A :: Δ2)\n  | notLt A Γ1 Γ2 Δ :\n    tree (Γ1 ++ Γ2 ) ( Δ ++ [A]) -> tree (Γ1 ++ ¬ A :: Γ2 ) Δ\n  .\n\nFixpoint leaves {l r} (t : tree l r) : list (list prop * list prop):=\n  match t with\n  | andRt _ _ _ _ _ l' r' => leaves l' ++ leaves r'\n  | andLt _ _ _ _ _ t' => leaves t'\n  | orRt _ _ _ _ _ t' => leaves t'\n  | orLt _ _ _ _ _ l' r' => leaves l' ++ leaves r'\n  | impRt _ _ _ _ _ t' => leaves t'\n  | impLt _ _ _ _ _ l' r' => leaves l' ++ leaves r'\n  | notRt _ _ _ _ t' => leaves t'\n  | notLt _ _ _ _ t' => leaves t'\n  | leaf l' r' _ _ => [(l',r')]\n  (* | _ => [] *)\n  end.\n\n\n\n\n\n\n\n\n\nTheorem leaves_counts0 l r (t : tree l r) :\n  Forall (fun p => counts' p = 0) (leaves t).\nProof.\n  induction t => //=; try (rewrite Forall_app; split; auto).\n  constructor => //=.\n  rewrite  /counts' => //=.\n  rewrite e e0; auto.\nQed.\n\n\n\nInductive path (p : list prop * list prop) : (list prop * list prop) -> Prop :=\n  | here : path p p\n  | step A B X Y : decomp X Y A B -> path p (A,B) -> path p (X,Y).\n\nTheorem path_taut p X Y :\n  tautology' p ->  path p (X, Y) -> tautology' (X,Y).\nProof.\n  move => H H0.\n  induction H0; subst => //=.\n  eapply decomp_tautology; eauto.\nQed.\n\nTheorem leaves_path l r (t : tree l r) :\n  forall p, In p (leaves t) -> path (l,r) p.\nProof.\n  induction t => /= p Hp;\n  try (case : Hp; [move ->; constructor| move => F; inversion F] );\n  try (apply in_app_or in Hp; case : Hp; [\n       move /IHt1 | move /IHt2] => H;\n       induction H; econstructor; eauto; constructor);\n  try (apply IHt in Hp; induction Hp; (econstructor; eauto); constructor).\nQed.\n\nTheorem leaves_taut l r (t : tree l r) :\n  tautology' (l,r) -> forall p, In p (leaves t) -> tautology' p.\nProof.\n  move => H [l' r'] /leaves_path /path_taut.\n  apply; auto.\nQed.\n\nTheorem tree_taut l r (t : tree l r) :\n  (forall l' r', In (l',r') (leaves t) -> l' ⟶ r') -> l ⟶ r.\nProof.\n  move => H.\n  induction t.\n  -apply H; left => //.\n  - apply changeR';\n    rewrite app_assoc;\n    apply andRc;\n    rewrite <- app_assoc;\n    apply swapR;\n    rewrite <- app_assoc;\n    apply changeR';\n    apply swapR;\n    rewrite <- app_assoc;\n    rewrite <- cons_app;\n    [apply IHt1| apply IHt2];\n    move => l' r' Hp; apply H => /=;\n    apply in_or_app;\n    [left| right]; auto.\nAdmitted.\n\nTheorem ex_tree l r :\n  counts l + counts r <> 0 -> tree l r.\nProof.\nAdmitted.\n\n\nTheorem completeness l r :\n  tautology' (l,r) -> l ⟶ r.\nProof.\n  move => H.\nAdmitted.\n\n\nFixpoint subform A B :=\n  match B with\n  | L ∧ R => A = B \\/ subform A L \\/ subform A R\n  | L ∨ R => A = B \\/ subform A L \\/ subform A R\n  | L ⊃ R => A = B \\/ subform A L \\/ subform A R\n  | ¬ B' => A = B \\/ subform A B'\n  | _ => A = B\n  end.\n\n\n\nFixpoint noImp (A : prop) : Prop :=\n  match A with\n  | L ∧ R => noImp L /\\ noImp R\n  | L ∨ R => noImp L /\\ noImp R\n  | _ ⊃ _ => False\n  | ¬ A' => noImp A'\n  | _ => True\n  end.\n\n\n\nFixpoint dual (A : prop) : prop :=\n  match A with\n  | L ∧ R => dual L ∨ dual R\n  | L ∨ R => dual L ∧ dual R\n  | L ⊃ R => dual L ⊃ dual R\n  | _ => A\n  end.\n\nAxiom entail_imp :\n  forall A B, A → B <-> [] → [bigAnd A ⊃ bigOr B].\n\nAxiom dummy : assign.\n(* Axiom dummy_bot : dummy fls = false. *)\n(* Axiom dummy_top : dummy tru = true. *)\n\nTheorem nil_entail_nil :\n  ~ ([] → []).\nProof.\n  move /entail_imp => /= /soundness F.\n  move : (F dummy); simpl.\n  repeat rewrite fls_false tru_true; simpl.\n  move => f; inversion f.\nQed.\n\n\n\n\n\n\n\n\n\n\n\nTheorem to_entail A :\n  [] → A -> In ⊤ A.\nProof.\n  induction A.\n  - move => F; case (nil_entail_nil F).\n  - move => H.\n    inversion a.\nAdmitted.\n\nTheorem dual_entail_extension L R:\n  Forall noImp L -> Forall noImp R -> L → R -> map dual L → map dual R.\nProof.\n  move : R; induction L => R HL HR H; simpl.\nAdmitted.\n\nTheorem cut_elim A B :\n  A → B -> A ⟶ B.\nProof.\n  move /soundness => H.\n  apply completeness; auto.\nQed.\n\nTheorem cut_intro A B :\n  A ⟶ B -> A → B.\nProof.\nAdmitted.\n\nAxiom entail_top :\n  forall v, [] → [# v] -> # v = ⊤.\n\nAxiom bot_entail :\n  forall v, [# v] → [] -> # v = ⊥.\n\nLemma var_entail v A :\n  [# v] → [A] -> A = # v \\/ A = ⊤ \\/ # v = ⊥.\nProof.\n  move : v.\n  induction A => u H.\n  { admit. }\n  {\n    admit.\n  }\n  {\n\n  }\n\nAdmitted.\n\n\n\n\nTheorem prv_prop_ind (P : prop -> prop -> Prop) :\n  (forall v B, # v = B -> P #v B) ->\n  (forall B, P ⊥ B) ->\n  (forall Al Ar B, [Al ∧ Ar] ⟶ [B] -> P (Al ∧ Ar) B) ->\n  (forall Al Ar B, [Al ∨ Ar] ⟶ [B] -> P (Al ∨ Ar) B) ->\n  (forall Al Ar B, [Al ⊃ Ar] ⟶ [B] -> P (Al ⊃ Ar) B) ->\n  (forall A B, [¬ A] ⟶ [B] -> P (¬ A) B) ->\n  forall A B, [A] ⟶ [B] -> P A B.\nProof.\n  intros.\n  destruct A; eauto.\nQed.\n\n\n\nTheorem dual_entail A B :\n  noImp A -> noImp B -> [A] → [B] -> [dual B] → [dual A].\nProof.\n  move  => HA HB /cut_elim H.\n  apply prv_prop_ind with (P := fun A B => [dual B] → [dual A]); intros; auto; simpl.\n  Check prv'_ind.\n  - admit.\n  - admit.\n  - apply cut_intro; apply completeness.\nRestart.\n  move => HA HB /soundness H.\n  apply cut_intro.\n  apply completeness => f.\n  move : (H f); clear H; simpl.\n  repeat rewrite andb_true_r orb_false_r.\n  induction A; simpl; auto => H.\nRestart.\n  move => HA HB /cut_elim H.\n  (* apply cut_intro. *)\n  inversion H; subst.\n  - constructor.\n  - apply cut_intro.\n    apply completeness => f.\n    apply cut_intro in H; apply soundness in H; move : (H f); clear H .\n    apply cut_intro in H3; apply soundness in H3; move : (H3 f); clear H3.\n    simpl.\n    repeat rewrite andb_true_r orb_false_r => fB.\n    rewrite andb_true_r orb_false_r.\n    rewrite fB.\n    rewrite implb_true_r => _.\n\nRestart.\n  move => HA HB.\n  move /cut_elim.\n  eapply (prv_prop_ind (fun )).\n  induction A; simpl.\n  try match goal with\n  | [ F : noImp (_ ⊃ _) |- _] => inversion F\n  end.\n  apply prv'_ind; intros; try solve [constructor].\n  -\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "ronkeisya", "sha": "76a9027ee20859369bfb2394eb0ec23fd2ea5dc4", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-ronkeisya", "path": "github-repos/coq/gaxiiiiiiiiiiii-ronkeisya/ronkeisya-76a9027ee20859369bfb2394eb0ec23fd2ea5dc4/logic/chapter1/prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7331174020628461}}
{"text": "(* Exercise 22 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_022 : (exists x : D, R x x /\\ P x) -> ~ (forall x : D, P x -> ~ (exists y : D, R x y)).\nProof.\nimp_i a1.\nexi_e (exists x:D, R x x /\\ P x) a a3.\nhyp a1.\nneg_i (exists y:D, R a y) a2.\nimp_e (P a).\nall_e (forall x : D, P x -> ~ (exists y : D, R x y)) a.\nhyp a2.\ncon_e2 (R a a).\nhyp a3.\nexi_i a.\ncon_e1 (P a).\nhyp a3.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred022.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.733108796352301}}
{"text": "(** * MoreCoq: More About Coq *)\n\nRequire Export Poly.\n\n(** This chapter introduces several more Coq tactics that,\n    together, allow us to prove many more theorems about the\n    functional programs we are writing. *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n,o] = [n,p] ->\n     [n,o] = [m,p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  (* At this point, we could finish with \n     \"[rewrite -> eq2. reflexivity.]\" as we have \n     done several times above. But we can achieve the\n     same effect in a single step by using the \n     [apply] tactic instead: *)\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q,o] = [r,p]) ->\n     [n,o] = [m,p].\nProof.\n  intros n m o p eq1 eq2. \n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex) *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex : \n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\nintros eq1 eq2.\napply eq1. apply eq2.\nQed.\n\n(** [] *)\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n  intros n m contra. inversion contra.  Qed.\n\n(** **** Exercise: 1 star (sillyex2) *)\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = [] ->\n     y :: l = z :: j ->\n     x = z.\nProof.\nintros X x y z l j contra.\ninversion contra.\nQed.\n  (* FILL IN HERE *) \n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    [forall (n m : nat), S n = S m -> n = m], the reverse direction of\n    the implication, provable by standard equational reasoning, is a\n    useful fact to record for cases we will see several times. *)\n\nLemma eq_remove_S : forall n m,\n  n = m -> S n = S m.\nProof. intros n m eq. rewrite -> eq. reflexivity. Qed.\n\n(** Here's another illustration of [inversion].  This is a slightly\n    roundabout way of stating a fact that we have already proved\n    above.  The extra equalities force us to do a little more\n    equational reasoning and exercise some of the tactics we've seen\n    recently. *)\n\nTheorem length_snoc' : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l. induction l as [| v' l'].\n  Case \"l = []\". intros n eq. rewrite <- eq. reflexivity.\n  Case \"l = v' :: l'\". intros n eq. simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply eq_remove_S. apply IHl'. inversion eq. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (practice) *)\n(** A couple more nontrivial but not-too-complicated proofs to work\n    together in class, or for you to work as exercises.  They may\n    involve applying lemmas from earlier lectures or homeworks. *)\n \n\nTheorem beq_nat_0_l : forall n,\n  true = beq_nat 0 n -> 0 = n.\nProof.\nintros n eq1. destruct n.\nCase \"n = 0\". reflexivity.\nCase \"n = S n'\". inversion eq1.\nQed.\n  (* FILL IN HERE *) \n\nTheorem beq_nat_0_r : forall n,\n  true = beq_nat 0 n -> 0 = n.\nProof.\n  intros n eq1. destruct n.\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". inversion eq1.\n  Qed.\n  (* FILL IN HERE *) \n(** [] *)\n\n\n(* ###################################################### *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b. \nProof. \n  intros n m b H. simpl in H. apply H.  Qed. \n\n(** Similarly, the tactic [apply L in H] matches some\n    conditional statement [L] (of the form [L1 -> L2], say) against a\n    hypothesis [H] in the context.  However, unlike ordinary\n    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),\n    [apply L in H] matches [H] against [L1] and, if successful,\n    replaces it with [L2].\n \n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\" -- from [L1 -> L2] and a hypothesis matching [L1], it\n    gives us a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\" -- it says that if we know [L1->L2] and we\n    are trying to prove [L2], it suffices to prove [L1].  \n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\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  symmetry in H. apply eq in H. symmetry in H. \n  apply H.  Qed.\n \n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, Coq tends to favor backward reasoning, but in some\n    situations the forward style can be easier to use or to think\n    about.  *)\n\n(** **** Exercise: 3 stars (plus_n_n_injective) *)\n(** Practice using \"in\" variants in this exercise. *)\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  Case \"n = 0\".\n  intros m eq1. destruct m.\n    SCase \"m = 0\". reflexivity.\n    SCase \"m = S m'\". inversion eq1.\n  Case \"n = S n'\".\n  intros m eq2. destruct m.\n    SCase \"m = 0\". inversion eq2.\n    SCase \"m = S m'\". inversion eq2.\n    rewrite <- plus_n_Sm in H0.\n    symmetry in H0. rewrite <- plus_n_Sm in H0. inversion H0.\n    symmetry in H1. apply IHn' in H1. rewrite H1. reflexivity.\n    (* Hint: use the plus_n_Sm lemma *)\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Varying the Induction Hypothesis *)\n\n(** In the previous chapter, we noticed the importance of\n    controlling the exact form of the induction hypothesis when\n    carrying out inductive proofs in Coq.  In particular, we need to\n    be careful about which of the assumptions we move (using [intros])\n    from the goal to the context before invoking the [induction]\n    tactic.  In this short chapter, we consider this point in a little\n    more depth and introduce one new tactic, called [generalize\n    dependent], that is sometimes useful in helping massage the\n    induction hypothesis into the required form.\n\n    First, let's review the basic issue.  Suppose we want to show that\n    the [double] function is injective -- i.e., that it always maps\n    different arguments to different results.  The way we _start_ this\n    proof is a little bit delicate: if we begin it with\n      intros n. induction n.\n]] \n    all is well.  But if we begin it with\n      intros n m. induction n.\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = O\". simpl. intros eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". intros eq. destruct m as [| m'].\n    SCase \"m = O\". inversion eq.\n    SCase \"m = S m'\". \n      assert (n' = m') as H.\n      SSCase \"Proof of assertion\". \n      (* Here we are stuck.  We need the assertion in order to\n         rewrite the final goal (subgoal 2 at this point) to an\n         identity.  But the induction hypothesis, [IHn'], does\n         not give us [n' = m'] -- there is an extra [S] in the\n         way -- so the assertion is not provable. *)\n      Admitted.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context -- \n    intuitively, we have told Coq, \"Let's consider some particular\n    [n] and [m]...\" and we now have to prove that, if [double n =\n    double m] for _this particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove that\n    the proposition\n\n      - [P n]  =  \"if [double n = double m], then [n = m]\"\n\n    holds for all [n] by showing\n\n      - [P O]              \n\n         (i.e., \"if [double O = double m] then [O = m]\")\n\n      - [P n -> P (S n)]  \n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help with proving [R]!  (If we\n    tried to prove [R] from [Q], we would say something like \"Suppose\n    [double (S n) = 10]...\" but then we'd be stuck: knowing that\n    [double (S n)] is [10] tells us nothing about whether [double n]\n    is [10], so [Q] is useless at this point.) *)\n\n(** To summarize: Trying to carry out this proof by induction on [n]\n    when [m] is already in the context doesn't work because we are\n    trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective' : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = O\". simpl. intros m eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". \n    (* Notice that both the goal and the induction\n       hypothesis have changed: the goal asks us to prove\n       something more general (i.e., to prove the\n       statement for _every_ [m]), but the IH is\n       correspondingly more flexible, allowing us to\n       choose any [m] we like when we apply the IH.  *)\n    intros m eq.\n    (* Now we choose a particular [m] and introduce the\n       assumption that [double n = double m].  Since we\n       are doing a case analysis on [n], we need a case\n       analysis on [m] to keep the two \"in sync.\" *)\n    destruct m as [| m'].\n    SCase \"m = O\". \n      (* The 0 case is trivial *)\n      inversion eq.  \n    SCase \"m = S m'\". \n      (* At this point, since we are in the second\n         branch of the [destruct m], the [m'] mentioned\n         in the context at this point is actually the\n         predecessor of the one we started out talking\n         about.  Since we are also in the [S] branch of\n         the induction, this is perfect: if we\n         instantiate the generic [m] in the IH with the\n         [m'] that we are talking about right now (this\n         instantiation is performed automatically by\n         [apply]), then [IHn'] gives us exactly what we\n         need to finish the proof. *)\n      assert (n' = m') as H.\n      SSCase \"Proof of assertion\". apply IHn'.\n        inversion eq. reflexivity.\n      rewrite -> H. reflexivity.  Qed.\n\n(** What this teaches us is that we need to be careful about using\n    induction to try to prove something too specific: If we're proving\n    a property of [n] and [m] by induction on [n], we may need to\n    leave [m] generic. *)\n\n(** **** Exercise: 2 stars (beq_nat_eq) *)\nTheorem beq_nat_eq : forall n m,\n  true = beq_nat n m -> n = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_eq_informal) *)\n(** Give a careful informal proof of [beq_nat_eq], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** The strategy of doing fewer [intros] before an [induction] doesn't\n    always work directly; sometimes a little _rearrangement_ of\n    quantified variables is needed.  Suppose, for example, that we\n    wanted to prove [double_injective] by induction on [m] instead of\n    [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  Case \"m = O\". simpl. intros eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq. \n  Case \"m = S m'\". intros eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\". \n      assert (n' = m') as H.\n      SSCase \"Proof of assertion\". \n        (* Stuck again here, just like before. *)\nAdmitted.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce\n    [n] for us!)   *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    will work, but it's not nice: We don't want to have to mangle the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them -- we want to state them in the most clear and\n    natural way. *)\n\n(**  What we can do instead is to first introduce all the\n    quantified variables and then _re-generalize_ one or more of\n    them, taking them out of the context and putting them back at\n    the beginning of the goal.  The [generalize dependent] tactic\n    does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. \n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  Case \"m = O\". simpl. intros n eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq.\n  Case \"m = S m'\". intros n eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\". \n      assert (n' = m') as H.\n      SSCase \"Proof of assertion\". \n        apply IHm'. inversion eq. reflexivity.\n      rewrite -> H. reflexivity.  Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n_Theorem_: For any nats [n] and [m], if [double n = double m], then\n  [n = m].\n\n_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n  any [n], if [double n = double m] then [n = m].\n\n  - First, suppose [m = 0], and suppose [n] is a number such\n    that [double n = double m].  We must show that [n = 0].\n\n    Since [m = 0], by the definition of [double] we have [double n =\n    0].  There are two cases to consider for [n].  If [n = 0] we are\n    done, since this is what we wanted to show.  Otherwise, if [n = S\n    n'] for some [n'], we derive a contradiction: by the definition of\n    [double] we would have [n = S (S (double n'))], but this\n    contradicts the assumption that [double n = 0].\n\n  - Otherwise, suppose [m = S m'] and that [n] is again a number such\n    that [double n = double m].  We must show that [n = S m'], with\n    the induction hypothesis that for every number [s], if [double s =\n    double m'] then [s = m'].\n \n    By the fact that [m = S m'] and the definition of [double], we\n    have [double n = S (S (double m'))].  There are two cases to\n    consider for [n].\n\n    If [n = 0], then by definition [double n = 0], a contradiction.\n    Thus, we may assume that [n = S n'] for some [n'], and again by\n    the definition of [double] we have [S (S (double n')) = S (S\n    (double m'))], which implies by inversion that [double n' = double\n    m'].\n\n    Instantiating the induction hypothesis with [n'] thus allows us to\n    conclude that [n' = m'], and it follows immediately that [S n' = S\n    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted\n    to show. [] *)\n\n(** **** Exercise: 3 stars (gen_dep_practice) *)\n\n(** Prove this by induction on [l]. *)\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     index (S n) l = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal) *)\n(** Write an informal proof corresponding to your Coq proof\n    of [index_after_last]:\n \n     _Theorem_: For all sets [X], lists [l : list X], and numbers\n      [n], if [length l = n] then [index (S n) l = None].\n \n     _Proof_:\n     (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (gen_dep_practice_more) *)\n(** Prove this by induction on [l]. *)\n\nTheorem length_snoc''' : forall (n : nat) (X : Type) \n                              (v : X) (l : list X),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (app_length_cons) *)\n(** Prove this by induction on [l1], without using [app_length]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X) \n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice) *)\n(** Prove this by induction on [l], without using app_length. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where the [destruct] tactic is\n    used to perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun. \n  destruct (beq_nat n 3).\n    Case \"beq_nat n 3 = true\". reflexivity.\n    Case \"beq_nat n 3 = false\". destruct (beq_nat n 5).\n      SCase \"beq_nat n 5 = true\". reflexivity.\n      SCase \"beq_nat n 5 = false\". reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,\n    either [n] is equal to [3] or it isn't, so we use [destruct\n    (beq_nat n 3)] to let us reason about the two cases. *)\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(** **** Exercise: 3 stars, optional (combine_split) *)\n(** Remove the comment brackets (needed because [split] was defined in \n    a previous exercise) and complete the proof. *)\n\n(* \nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n*)\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine) *)\n(** We have just proven that for all lists of pairs, [combine] is the\n    inverse of [split].  How would you formalize the statement that\n    [split] is the inverse of [combine]?\n \n    State this as a theorem in Coq, and prove it. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?) *)\n\n(* FILL IN HERE *) \n(** [] *)\n\n(* ###################################################### *)\n(** * The [remember] Tactic *)\n\n(** We have seen how the [destruct] tactic can be used to\n    perform case analysis of the results of arbitrary computations.\n    If [e] is an expression whose type is some inductively defined\n    type [T], then, for each constructor [c] of [T], [destruct e]\n    generates a subgoal in which all occurrences of [e] (in the goal\n    and in the context) are replaced by [c].\n\n    Sometimes, however, this substitution process loses information\n    that we need in order to complete the proof.  For example, suppose\n    we define a function [sillyfun1] like this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** And suppose that we want to convince Coq of the rather\n    obvious observation that [sillyfun1 n] yields [true] only when [n]\n    is odd.  By analogy with the proofs we did with [sillyfun] above,\n    it is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAdmitted.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution peformed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep at\n    least one of these because we need to be able to reason that\n    since, in this branch of the case analysis, [beq_nat n 3 = true],\n    it must be that [n = 3], from which it follows that [n] is odd.\n\n    What we would really like is not to use [destruct] directly on\n    [beq_nat n 3] and substitute away all occurrences of this\n    expression, but rather to use [destruct] on something else that is\n    _equal_ to [beq_nat n 3].  For example, if we had a variable that\n    we knew was equal to [beq_nat n 3], we could [destruct] this\n    variable instead.\n\n    The [remember] tactic allows us to introduce such a variable. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  remember (beq_nat n 3) as e3.\n  (* At this point, the context has been enriched with a new\n     variable [e3] and an assumption that [e3 = beq_nat n 3].\n     Now if we do [destruct e3]... *)\n  destruct e3.\n  (* ... the variable [e3] gets substituted away (it\n    disappears completely) and we are left with the same\n     state as at the point where we got stuck above, except\n     that the context still contains the extra equality\n     assumption -- now with [true] substituted for [e3] --\n     which is exactly what we need to make progress. *)\n    Case \"e3 = true\". apply beq_nat_eq in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    Case \"e3 = false\".\n     (* When we come to the second equality test in the\n       body of the function we are reasoning about, we can\n        use [remember] again in the same way, allowing us\n        to finish the proof. *)\n      remember (beq_nat n 5) as e5. destruct e5.\n        SCase \"e5 = true\".\n          apply beq_nat_eq in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        SCase \"e5 = false\". inversion eq.  Qed.\n\n(** **** Exercise: 2 stars *)\nTheorem bool_fn_applied_thrice : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (override_same) *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a,b] = [c,d] ->\n     [c,d] = [e,f] ->\n     [a,b] = [e,f].\nProof.\n  intros a b c d e f eq1 eq2. \n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might\n    abstract it out as a lemma recording once and for all\n    the fact that equality is transitive. *)\n\nTheorem trans_eq : forall {X:Type} (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. \n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to\n    prove the above example.  However, to do this we need\n    a slight refinement of the [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a,b] = [c,d] ->\n     [c,d] = [e,f] ->\n     [a,b] = [e,f].\nProof.\n  intros a b c d e f eq1 eq2. \n  (* If we simply tell Coq [apply trans_eq] at this point,\n     it can tell (by matching the goal against the\n     conclusion of the lemma) that it should instantiate [X]\n     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].\n     However, the matching process doesn't determine an\n     instantiation for [m]: we have to supply one explicitly\n     by adding [with (m:=[c,d])] to the invocation of\n     [apply]. *)\n  apply trans_eq with (m:=[c,d]). apply eq1. apply eq2.   Qed.\n\n(**  Actually, we usually don't have to include the name [m]\n    in the [with] clause; Coq is often smart enough to\n    figure out which instantiation we're giving. We could\n    instead write: apply trans_eq with [c,d]. *)\n\n(** **** Exercise: 3 stars (apply_with_exercise3) *)\nTheorem override_permute : forall {X:Type} x1 x2 k1 k2 k3 (f : nat->X),\n  false = beq_nat k2 k1 ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise1) *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o). \nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise2) *)\nTheorem beq_nat_trans : forall n m p,\n  true = beq_nat n m ->\n  true = beq_nat m p ->\n  true = beq_nat n p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen a bunch of Coq's fundamental tactics.  We'll\n    introduce a few more as we go along through the coming lectures,\n    and later in the course we'll introduce some more powerful\n    _automation_ tactics that make Coq do more of the low-level work\n    in many cases.  But basically we've got what we need to get work\n    done.\n\n    Here are the ones we've seen:\n\n      - [intros]: \n        move hypotheses/variables from goal to context \n\n      - [reflexivity]:\n        finish the proof (when the goal looks like [e = e])\n\n      - [apply]:\n        prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: \n        apply a hypothesis, lemma, or constructor to a hypothesis in\n        the context (forward reasoning)\n\n      - [apply... with...]:\n        explicitly specify values for variables that cannot be\n        determined by pattern matching\n\n      - [simpl]:\n        simplify computations in the goal \n\n      - [simpl in H]:\n        ... or a hypothesis \n\n      - [rewrite]:\n        use an equality hypothesis (or lemma) to rewrite the goal \n\n      - [rewrite ... in H]:\n        ... or a hypothesis \n\n      - [symmetry]:\n        changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]:\n        changes a hypothesis of the form [t=u] into [u=t]\n\n      - [unfold]:\n        replace a defined constant by its right-hand side in the goal \n\n      - [unfold... in H]:\n        ... or a hypothesis  \n\n      - [destruct... as...]:\n        case analysis on values of inductively defined types \n\n      - [induction... as...]:\n        induction on values of inductively defined types \n\n      - [inversion]:\n        reason by injectivity and distinctness of constructors\n\n      - [remember (e) as x]:\n        give a name ([x]) to an expression ([e]) so that we can\n        destruct [x] without \"losing\" [e]\n\n      - [assert (e) as H]:\n        introduce a \"local lemma\" [e] and call it [H] \n\n      - [generalize dependent x]:\n        move the variable [x] (and anything else that depends on it)\n        from the context back to an explicit hypothesis in the goal\n        formula \n*)\nCheck [1 :: nil].\n\n\n\n\n\n\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym) *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal) *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise) *)\n(** This one is a bit challenging.  Pay attention to the form of your IH. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (forall_exists_challenge) *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n      forallb oddb [1,3,5,7,9] = true\n\n      forallb negb [false,false] = true\n  \n      forallb evenb [0,2,4,5] = false\n  \n      forallb (beq_nat 5) [] = true\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n      existsb (beq_nat 5) [0,2,3,6] = false\n \n      existsb (andb true) [true,true,false] = true\n \n      existsb oddb [1,0,0,0,0,3] = true\n \n      existsb evenb [] = false\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n \n    Prove that [existsb'] and [existsb] have the same behavior.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* $Date: 2013-01-30 18:38:07 -0500 (Wed, 30 Jan 2013) $ *)\n\n\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/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.90990700787036, "lm_q1q2_score": 0.7330503830125353}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (x : natural) : natural :=\n  plus y (mult (Succ y) x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj144_coqofml_J4ordr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7329423860508986}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2022 - Pset 5 *)\n\nRequire Import Frap.Frap.\nRequire Import Pset5Sig.\n\nModule Impl.\n  (* In this pset, we will explore different ways of defining semantics for the\n     simple imperative language we used in Chapter 4 (Interpreters.v) and\n     Chapter 7 (OperationalSemantics.v).\n     Make sure to reread these two files, because many definitions we ask you\n     to come up with in this pset are similar to definitions in these two files.\n\n     Pset5Sig.v contains the number of points you get for each definition and\n     proof. Note that since we ask you to come up with some definitions\n     yourself, all proofs being accepted by Coq does not necessarily guarantee a\n     full score: you also need to make sure that your definitions correspond to\n     what we ask for in the instructions. *)\n\n  (* Our language has arithmetic expressions (note that we removed Times and Minus,\n     because they don't add anything interesting for this pset): *)\n  Inductive arith: Set :=\n  | Const (n: nat)\n  | Var (x: var)\n  | Plus (e1 e2: arith).\n\n  (* And it has commands, some of which contain arithmetic expressions: *)\n  Inductive cmd :=\n  | Skip\n  | Assign (x: var) (e: arith)\n  | Sequence (c1 c2: cmd)\n  | If (e: arith) (thn els: cmd)\n  | While (e: arith) (body: cmd).\n\n  (* As in the lecture, we use a finite map to store the values of the variables: *)\n  Definition valuation := fmap var nat.\n\n  (** * Part 1: Using a recursive function **)\n\n  (* To make it a bit more interesting, we add a twist:\n     If an arithmetic expression reads an undefined variable, instead of just\n     returning 0, we specify that an arbitrary value can be returned.\n     Therefore, the signature we used in class,\n\n       Fixpoint interp (e: arith) (v: valuation): nat :=\n         ...\n\n     will not work any more, because that one can only return one value.\n     Instead, we will use the following definition: *)\n\n  Fixpoint interp (e: arith) (v: valuation) (retval: nat): Prop :=\n    match e with\n    | Const n => retval = n\n    | Var x =>\n      match v $? x with\n      | None => True (* any retval is possible! *)\n      | Some n => retval = n\n      end\n    | Plus e1 e2 =>\n      exists a1 a2,\n      interp e1 v a1 /\\\n      interp e2 v a2 /\\\n      retval = a1 + a2\n    end.\n  (* You can read [interp e v retval] as the claim that \"interpreting expression\n     e under the valuation v can return the value retval\".\n     And if we don't provide the last argument, we can think of \"interp e v\",\n     which has type \"nat -> Prop\", as \"the set of all possible values e could\n     return\". *)\n\n  (* Let's look at some examples: *)\n\n  (* The only result allowed by [Const 3] is [3]: *)\n  Compute interp (Const 3) _.\n\n  (* If we interpret the expression \"y + z\" in a valuation where\n     y is 2 and z is 3, then the only possible result is 5. *)\n\n  Goal forall retval,\n      interp (Plus (Var \"y\") (Var \"z\"))\n             ($0 $+ (\"y\", 2) $+ (\"z\", 3))\n             retval <->\n      retval = 5.\n  Proof.\n    simplify; propositional.\n    - cases H; cases H.\n      linear_arithmetic.\n    - exists 2, 3.\n      propositional.\n  Qed.\n\n  (* We can also look at this in terms of a partial application: *)\n\n  Goal interp (Plus (Var \"y\") (Var \"z\"))\n              ($0 $+ (\"y\", 2) $+ (\"z\", 3)) =\n       (fun retval => retval = 5).\n  Proof.\n    simplify.\n    apply sets_equal; simplify; propositional.\n    - cases H; cases H.\n      linear_arithmetic.\n    - exists 2, 3.\n      propositional.\n  Qed.\n\n  (* But if we leave [z] unset in the valuation, then [Var \"z\"] can return any\n     value, and hence the complete program can return any value greater than or\n     equal to 2. *)\n  Goal interp (Plus (Var \"y\") (Var \"z\")) ($0 $+ (\"y\", 2)) = (fun retval => 2 <= retval).\n  Proof.\n    simplify.\n    apply sets_equal.\n    propositional.\n    - cases H. cases H. linear_arithmetic.\n    - exists 2, (x - 2). linear_arithmetic.\n  Qed.\n\n  (* Hint that will be useful later:\n     In the above proof, you can see how you can deal with existentials:\n     - If you have an [H: exists x, P] above the line, you can \"cases H\"\n       to obtain such an \"x\" and \"H: P\".\n     - If you have an [exists x, P] below the line, you can use \"exists x0\" to\n       provide the value [x0] for which you want to prove the existential.\n     Instead of repeating [cases], you can also use [first_order]. *)\n\n  (** * Part 2: Using an inductive relation **)\n\n  (* An alternative way of specifying how arithmetic expressions are evaluated\n     is by using inference rules, where we put preconditions above the line,\n     the conclusion below the line, and a name of the rule to the right of\n     the line, using \"Oxford brackets\" to write statements of the form\n     \"a ∈ ⟦e⟧ᵥ\" which we read as \"the natural number a is in the set of\n     values to which e can evaluate under the valuation v\".\n     If we were to write this on a blackboard, it might look like this:\n\n                           n1 = n2\n                        ------------ ValuesConst\n                         n1 ∈ ⟦n2⟧ᵥ\n\n                         (x ↦ a) ∈ v\n                        -------------- ValuesVarDefined\n                           a ∈ ⟦x⟧ᵥ\n\n                         x ∉ dom(v)\n                       ------------- ValuesVarUndefined\n                         a ∈ ⟦x⟧ᵥ\n\n            a1 ∈ ⟦e1⟧ᵥ   a2 ∈ ⟦e2⟧ᵥ   a=a1+a2\n            ----------------------------------- ValuesPlus\n                       a ∈ ⟦e1+e2⟧ᵥ\n\n     Let's translate this to an Inductive Prop in Coq called \"values\". That is,\n     [values e v a] should mean “the natural number a is in the set of\n     values to which e can evaluate under the valuation v”.\n\n     Define an Inductive with four constructors, one for each of the four rules\n     above, using the names written to the rights of the lines above as the\n     constructor names.  We have included ValuesConst to give you a hint.\n  *)\n  Inductive values: arith -> valuation -> nat -> Prop :=\n  | ValuesConst: forall v n1 n2,\n      n1 = n2 ->\n      values (Const n1) v n2\n  .\n\n  (* Note that the following alternative would also work for ValuesConst and\n     ValuesPlus:\n\n                    ---------- ValuesConst\n                     n ∈ ⟦n⟧ᵥ\n\n            a1 ∈ ⟦e1⟧ᵥ     a2 ∈ ⟦e2⟧ᵥ\n            --------------------------- ValuesPlus\n                a1+a2 ∈ ⟦e1+e2⟧ᵥ\n\n     But in Coq, this would be a bit less convenient, because the tactic\n     [eapply ValuesPlus] would only work if the goal is of the shape\n     [values _ _ (_ + _)], whereas if we add this extra equality,\n     [eapply ValuesPlus] works no matter what the last argument to [values] is,\n     and similarly for [ValuesConst]. *)\n\n  (* Contrary to the Fixpoint-based definition \"interp\", we can't do simplification\n     of the kind \"replace interp by its body and substitute the arguments in it\",\n     because an Inductive Prop describes a family of proof trees and isn't a\n     function with a right-hand side you could plug in somewhere else.\n     In order to prove the example Goal from above for \"values\", we need to construct\n     the following proof tree:\n\n    (\"y\"↦2) ∈ {\"y\"↦2}              \"z\" ∉ dom({\"y\"↦2})\n   -------------------- Defined    ----------------------- Undefined\n    2 ∈ ⟦\"y\"⟧_{\"y\"↦2}               a-2 ∈ ⟦\"z\"⟧_{\"y\"↦2}              a=2+a-2\n   ---------------------------------------------------------------------------- ValuesPlus\n                        a ∈ ⟦\"y\"+\"z\"⟧_{\"y\"↦2}\n  *)\n  Example values_example: forall a,\n      2 <= a ->\n      values (Plus (Var \"y\") (Var \"z\")) ($0 $+ (\"y\", 2)) a.\n  Proof.\n    (* \"simplify\" only introduces the hypotheses but can't really simplify\n       anything here. This is not a limitation of \"simplify\"; it's due to the\n       way [values] is defined. *)\n    simplify.\n    (* Once you define the four constructors for \"values\", you can uncomment\n       the script below. Make sure you understand how it relates to the proof\n       tree above! *)\n    (*\n    eapply ValuesPlus with (a1 := 2) (a2 := a - 2).\n    - eapply ValuesVarDefined. simplify. equality.\n    - eapply ValuesVarUndefined. simplify. equality.\n    - linear_arithmetic.\n      *)\n  Admitted.\n\n  (* Now, let's prove that \"interp\" and \"values\" are equivalent.\n     First, [interp -> values]: *)\n  Theorem interp_to_values: forall e v a,\n      interp e v a -> values e v a.\n  Proof.\n  Admitted.\n\n  (* To prove the other direction, we have a choice: we can either induct on\n     [e] or directly on the proof of [values e v a], because [values] is an\n     inductively defined predicate.\n\n     Let's do both proofs.  In general, inducting on the proof tree is the right\n     approach, so let's start with that: *)\n  Theorem values_to_interp: forall e v a,\n      values e v a -> interp e v a.\n  Proof.\n    induct 1; (* ← do not change this line *)\n      simplify.\n  Admitted.\n\n  (* Now let's see how things look with an induction on e.  In this simple case,\n     it's very similar: *)\n  Theorem values_to_interp_induction_on_e: forall e v a,\n      values e v a -> interp e v a.\n  Proof.\n    induct e; (* ← not the best, but for the sake of the exercise do not change this line *)\n      simplify.\n  Admitted.\n\n  (* Let's define nondeterministic big-step semantics for evaluating a command.\n     Define [eval] as an Inductive Prop such that [eval v1 c v2] means\n     \"If we run command c on valuation v1, we can obtain valuation v2\".\n     Whenever you encounter an arithmetic expression, use [values] to obtain a\n     value it can step to.\n     Hint: This will be quite similar to [eval] in OperationalSemantics.v! *)\n  Inductive eval: valuation -> cmd -> valuation -> Prop :=\n  | EvalSkip: forall v,\n      eval v Skip v\n  .\n\n  (* Hint: Many of the proofs below will depend on definitions we ask you to\n     find yourself, and if you get these definitions wrong, the proofs will\n     not work, so keep in mind that you might have to go back and adapt your\n     definitions!\n     Also, it can happen that many proofs go through and you become (overly)\n     confident that your definitions are correct, even though they aren't. *)\n\n  (* Here's an example program. If we run it on the empty valuation, reading the\n     variable \"oops\" can return any value, but after that, no matter whether\n     \"oops\" was zero or not, we assign a nonzero value to \"tmp\", so the answer\n     will always be 42. *)\n  Example the_answer_is_42 :=\n    Sequence (Assign \"x\" (Var \"oops\"))\n             (Sequence (If (Var \"x\")\n                           (Assign \"tmp\" (Plus (Var \"x\") (Var \"x\")))\n                           (Assign \"tmp\" (Const 1)))\n                       (If (Var \"tmp\")\n                           (Assign \"answer\" (Const 42))\n                           (Assign \"answer\" (Const 24)))).\n\n  (* To prove that this sample program always returns 42, we first prove a handy\n     helper lemma (the [simplify] tactic will help with [$+]): *)\n  Lemma read_last_value: forall x v c n,\n      values (Var x) (v $+ (x, c)) n -> n = c.\n  Proof.\n  Admitted.\n\n  (* Hint: This next theorem is a bit boring -- it's about 30 lines of \"invert\",\n     \"simplify\", \"discriminate\", \"equality\", \"linear_arithmetic\" and\n     \"apply read_last_value in H\", \"subst\" in our solution.\n\n     But it's a good test case to make sure you got the definition of \"eval\"\n     right! And note that inverting the hypotheses in the right order, i.e. in\n     the order the program is executed, as well as using \"read_last_value\"\n     whenever possible, will make your proof less long.\n\n     (Or, you could use automation — our automated proof is 8 lines long.) *)\n  Theorem the_answer_is_indeed_42:\n    forall v, eval $0 the_answer_is_42 v -> v $? \"answer\" = Some 42.\n  Proof.\n  Admitted.\n\n  (* Here's another example program. If we run it on a valuation that is\n     undefined for \"x\", it will read the undefined variable \"x\" to decide\n     whether to abort the loop, so any number of loop iterations is possible. *)\n  Example loop_of_unknown_length :=\n    (While (Var \"x\") (Assign \"counter\" (Plus (Var \"counter\") (Const 1)))).\n\n  (* Hint: you might need the \"maps_equal\" tactic to prove that two maps are the same. *)\n  Theorem eval_loop_of_unknown_length: forall n initialCounter,\n      eval ($0 $+ (\"counter\", initialCounter))\n           loop_of_unknown_length\n           ($0 $+ (\"counter\", initialCounter + n)).\n  Proof.\n    unfold loop_of_unknown_length.\n    induct n; simplify.\n  Admitted.\n\n  (* Wherever this TODO_FILL_IN is used, you should replace it with your own code *)\n  Axiom TODO_FILL_IN: Prop.\n\n  (** * Part 3: Fixpoints with fuel **)\n\n  (* You might wonder whether we can use \"Fixpoint\" instead of \"Inductive\" to define\n     such nondeterministic big-step evaluation of commands, and indeed we can.\n     But we need some trick to convince Coq that this Fixpoint will always terminate,\n     even though there could be infinite loops.\n\n     We achieve this by using a \"fuel\" argument that limits the recursion depth.\n     This does not exclude any possible final valuations, because for every final\n     valuation, there exists a recursion depth sufficient to reach it.\n\n     So let's define a Fixpoint [run] such that [run fuel v1 c v2] means\n     \"if we run command c on valuation v1 and limit the recursion depth to fuel,\n     we can obtain valuation v2\".\n\n     We already defined all cases for you except the [While] case, but all the\n     building blocks you need can be found in the other cases, too.\n   *)\n  Fixpoint run (fuel: nat) (v1: valuation) (c: cmd) (v2: valuation): Prop :=\n    match fuel with\n    | O => False\n    | S fuel' =>\n      match c with\n      | Skip => v1 = v2\n      | Assign x e => exists a, interp e v1 a /\\ v2 = (v1 $+ (x, a))\n      | Sequence c1 c2 => exists vmid, run fuel' v1 c1 vmid /\\ run fuel' vmid c2 v2\n      | If e c1 c2 =>\n        (exists r, interp e v1 r /\\ r <> 0 /\\ run fuel' v1 c1 v2) \\/\n        (interp e v1 0 /\\ run fuel' v1 c2 v2)\n      | While e c1 =>\n        TODO_FILL_IN\n      end\n    end.\n\n  (* Now let's prove that [run] and [eval] are equivalent! *)\n\n  Local Hint Constructors eval : core.\n\n  Theorem run_to_eval: forall fuel v1 c v2,\n      run fuel v1 c v2 ->\n      eval v1 c v2.\n  Proof.\n  Admitted.\n\n  (* To prove the other direction, we will need the following lemma, which shows\n     that excess fuel isn't an issue.\n\n     Hint: Here, some proof automation might pay off!\n\n     You could try writing a [repeat match goal] loop, to do all possible\n     simplifications on your hypotheses and then use [eauto] to solve\n     the goal. Maybe you need to increase the maximum search depth of eauto;\n     in our solution, we had to write [eauto 9] instead of just [eauto],\n     which defaults to [eauto 5].\n\n     Some useful documentation pointers:\n     - https://coq.inria.fr/refman/proofs/automatic-tactics/auto.html#coq:tacn.eauto\n     - https://coq.inria.fr/refman/proof-engine/ltac.html?highlight=repeat#pattern-matching-on-goals-and-hypotheses-match-goal\n\n     And note that [eauto] does not know about linear arithmetic by default,\n     so you could consider registering it as a [Hint Extern], but a simpler\n     way here would be to use the lemma \"le_S_n\" to turn \"S fuel1 <= S fuel2\"\n     into \"fuel1 <= fuel2\", which will be needed for the IH. *)\n\n  Lemma run_monotone: forall fuel1 fuel2 v1 c v2,\n      fuel1 <= fuel2 ->\n      run fuel1 v1 c v2 ->\n      run fuel2 v1 c v2.\n  Proof.\n  Admitted.\n\n  (* For the other direction, we could naively start proving it like this: *)\n  Theorem eval_to_run: forall v1 c v2,\n      eval v1 c v2 -> exists fuel, run fuel v1 c v2.\n  Proof.\n    induct 1; simplify.\n    (* This proof is relatively short and straightforward, but dealing with\n       existentials is not very pleasant!\n\n       This problem becomes worse if we make many proofs about \"run\".  So, instead,\n       let's look at a nicer formulation of this theorem. *)\n  Abort. (* <-- do not change this line *)\n\n\n  (* We will first define a wrapper around \"run\" that hides the existential: *)\n  Definition wrun (v1: valuation) (c: cmd) (v2: valuation): Prop :=\n    exists fuel, run fuel v1 c v2.\n\n  (* The idea is that in the run_to_eval proof above, using the constructors of\n     \"eval\", i.e. doing \"eapply EvalAssign\", \"eapply EvalSeq\", \"eapply EvalIfTrue\",\n     was quite convenient, so let's expose the same \"API\" for constructing proofs\n     of \"run\" (or actually, proofs of the slightly nicer \"wrun\"). *)\n\n  (* Now let's define proof rules to get the same \"API\" for \"wrun\" as for \"eval\".\n     Hint: Again, some proof automation might simplify the task (but manual proofs are\n     possible too, of course).  You may find the `max` function useful. *)\n\n  Definition WRunSkip_statement : Prop :=\n    forall v,\n      wrun v Skip v.\n  Lemma WRunSkip: WRunSkip_statement.\n  Proof.\n  Admitted.\n\n  Definition WRunAssign_statement : Prop :=\n    forall v x e a,\n      interp e v a ->\n      wrun v (Assign x e) (v $+ (x, a)).\n  Lemma WRunAssign: WRunAssign_statement.\n  Proof.\n  Admitted.\n\n  Definition WRunSeq_statement : Prop :=\n    forall v c1 v1 c2 v2,\n      wrun v c1 v1 ->\n      wrun v1 c2 v2 ->\n      wrun v (Sequence c1 c2) v2.\n  Lemma WRunSeq: WRunSeq_statement.\n  Proof.\n  Admitted.\n\n  (* For the next few lemmas, we've left you the job of stating the theorem as\n     well as proving it. *)\n\n  Definition WRunIfTrue_statement : Prop. Admitted.\n  Lemma WRunIfTrue: WRunIfTrue_statement.\n  Proof.\n  Admitted.\n\n  Definition WRunIfFalse_statement : Prop. Admitted.\n  Lemma WRunIfFalse: WRunIfFalse_statement.\n  Proof.\n  Admitted.\n\n  Definition WRunWhileTrue_statement : Prop. Admitted.\n  Lemma WRunWhileTrue: WRunWhileTrue_statement.\n  Proof.\n  Admitted.\n\n  Definition WRunWhileFalse_statement : Prop. Admitted.\n  Lemma WRunWhileFalse: WRunWhileFalse_statement.\n  Proof.\n  Admitted.\n\n  (* Now, thanks to these helper lemmas, proving the direction from eval to wrun\n     becomes easy: *)\n  Theorem eval_to_wrun: forall v1 c v2,\n      eval v1 c v2 ->\n      wrun v1 c v2.\n  Proof.\n  Admitted.\n\n  (* Remember when we said earlier that [induct 1] does induction on the proof\n     of [eval], whereas [induct c] does induction on the program itself?  Try\n     proving the above with [induct c] instead of [induct 1], skipping straight\n     to the [While] cases.  Why isn't the theorem provable this way? *)\n\n  (* The following definitions are needed because of a limitation of Coq\n     (the kernel does not recognize that a parameter can be instantiated by an\n     inductive type).\n     Please do not remove them! *)\n  Definition values_alias_for_grading := values.\n  Definition eval_alias_for_grading := eval.\n\n  (* You've reached the end of this pset, congratulations! *)\n\n  (* ****** Everything below this line is optional ****** *)\n\n  (* Many of the proofs above can be automated.  A good way to test your\n     automation is to make small changes to the language.\n\n     For example, you could add an [Unset: string -> cmd] constructor to the\n     definition of [cmd]; the semantics of that command should be to remove a\n     variable from the current valuation (use [v $- \"x\"] to remove [\"x\"] from\n     [v]).\n\n     In our solution, adding [Unset] and updating definitions and proofs\n     accordingly takes just a few extra lines.  Try it in yours! *)\n\n  (* Let's take the deterministic semantics we used in OperationalSemantics.v but\n     prefix them with \"d\" to mark them as deterministic: *)\n\n  Fixpoint dinterp (e: arith) (v: valuation): nat :=\n    match e with\n    | Const n => n\n    | Var x =>\n      match v $? x with\n      | None => 0\n      | Some n => n\n      end\n    | Plus e1 e2 => dinterp e1 v + dinterp e2 v\n    end.\n\n  Inductive deval: valuation -> cmd -> valuation -> Prop :=\n  | DEvalSkip: forall v,\n      deval v Skip v\n  | DEvalAssign: forall v x e,\n      deval v (Assign x e) (v $+ (x, dinterp e v))\n  | DEvalSeq: forall v c1 v1 c2 v2,\n      deval v c1 v1 ->\n      deval v1 c2 v2 ->\n      deval v (Sequence c1 c2) v2\n  | DEvalIfTrue: forall v e thn els v',\n      dinterp e v <> 0 ->\n      deval v thn v' ->\n      deval v (If e thn els) v'\n  | DEvalIfFalse: forall v e thn els v',\n      dinterp e v = 0 ->\n      deval v els v' ->\n      deval v (If e thn els) v'\n  | DEvalWhileTrue: forall v e body v' v'',\n      dinterp e v <> 0 ->\n      deval v body v' ->\n      deval v' (While e body) v'' ->\n      deval v (While e body) v''\n  | DEvalWhileFalse: forall v e body,\n      dinterp e v = 0 ->\n      deval v (While e body) v.\n\n  (* Now let's prove that if a program evaluates to a valuation according to the\n     deterministic semantics, it also evaluates to that valuation according to\n     the nondeterministic semantics (the other direction does not hold, though). *)\n  Theorem deval_to_eval: forall v1 v2 c,\n      deval v1 c v2 ->\n      eval v1 c v2.\n  Proof.\n  Admitted.\n\n  (* In deterministic semantics, Fixpoints work a bit better, because they\n     can return just one value, and let's use \"option\" to indicate whether\n     we ran out of fuel: *)\n  Fixpoint drun(fuel: nat) (v: valuation) (c: cmd): option valuation. Admitted.\n\n  (* More open-ended exercise:\n     Now we have six different definitions of semantics:\n\n                          deterministic     nondeterministic\n\n     Inductive            deval             eval\n\n     Wrapped Fixpoint     dwrun             wrun\n\n     Fixpoint             drun              run\n\n     We have proved that all the nondeterministic semantics are equivalent among\n     each other.\n     If you want, you could also prove that all the deterministic semantics are\n     equivalent among each other and experiment whether it's worth creating an\n     \"Inductive\"-like API for \"dwrun\", or whether you're ok dealing with drun's\n     existentials when proving deval_to_drun.\n     Moreover, we have proved that \"deval\" implies \"eval\", so every definition in\n     the left column of the above table implies every definition in the right\n     column of the table.\n     If you're curious to learn more about the trade-offs between Inductive Props\n     and Fixpoints, you can try to prove some of these implications directly\n     and see how much harder than \"deval_to_eval\" it is (we believe that\n     \"deval_to_eval\" is the simplest one).\n   *)\n\nEnd Impl.\n\nModule ImplCorrect : Pset5Sig.S := Impl.\n\n(* Authors:\n   Samuel Gruetter\n   Clément Pit-Claudel *)\n", "meta": {"author": "mit-frap", "repo": "spring22", "sha": "48a93f5874695099627e717ab44c77be4d7bd02a", "save_path": "github-repos/coq/mit-frap-spring22", "path": "github-repos/coq/mit-frap-spring22/spring22-48a93f5874695099627e717ab44c77be4d7bd02a/pset05_BigStepVsInterpreter/Pset5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.732891116981944}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) : natural := mult (Succ x) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj191_coqofml_nNJWbU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7328448249796662}}
{"text": "(** Calculation of an abstract machine for arithmetic expressions +\n state + unbounded loops. *)\n\nRequire Import List.\nRequire Import ListIndex.\nRequire Import Tactics.\n\n(** * Syntax *)\n\nInductive Expr : Set := \n| Val : nat -> Expr \n| Add : Expr -> Expr -> Expr\n| Get : Expr.\n\nInductive Stmt : Set :=\n| Put : Expr -> Stmt\n| Seqn : Stmt -> Stmt -> Stmt\n| While : Expr -> Stmt -> Stmt.\n\n(** * Semantics *)\n\nDefinition State := nat.\nReserved Notation \"x ⇓[ q ] y\" (at level 80, no associativity).\n\nInductive eval : Expr -> State -> nat -> Prop :=\n| eval_val q n : Val n ⇓[q] n\n| eval_add q x y m n : x ⇓[q] n -> y ⇓[q] m -> Add x y ⇓[q] (n + m)\n| eval_get q : Get ⇓[q] q\nwhere \"x ⇓[ q ] y\" := (eval x q y).\n\nReserved Notation \"x ↓[ q ] q'\" (at level 80, no associativity).\n\nInductive run : Stmt -> State -> State -> Prop :=\n| run_put x q v : x ⇓[q] v -> Put x ↓[q] v\n| run_seqn x1 x2 q1 q2 q3 : x1 ↓[q1] q2 -> x2 ↓[q2] q3 -> Seqn x1 x2 ↓[q1] q3\n| run_while_exit x1 x2 q : x1 ⇓[q] 0 -> While x1 x2 ↓[q] q\n| run_while_cont v x1 x2 q1 q2 q3 : x1 ⇓[q1] v -> v > 0 -> x2 ↓[q1] q2 -> While x1 x2 ↓[q2] q3 \n                   -> While x1 x2 ↓[q1] q3\nwhere \"x ↓[ q ] y\" := (run x q y).\n\n(** * Abstract machine *)\n\nInductive CONT : Set :=\n| NEXT : Expr -> State -> CONT -> CONT\n| ADD : nat -> CONT -> CONT\n| PUT : CONT -> CONT\n| SEQN : Stmt -> CONT -> CONT\n| CHECK : Expr -> Stmt -> State -> CONT -> CONT\n| WHILE : Expr -> Stmt -> CONT -> CONT\n| HALT : CONT\n.\n\n\nInductive Conf : Set := \n| eval'' : Expr -> State -> CONT -> Conf\n| run'' : Stmt -> State -> CONT -> Conf\n| exec : CONT -> nat -> Conf\n| exec' : CONT -> State -> Conf\n.\n\nNotation \"⟨ x , q , c ⟩\" := (eval'' x q c).\nNotation \"⟨| x , q , c |⟩\" := (run'' x q c).\nNotation \"⟪ c , v ⟫\" := (exec c v).\nNotation \"⟪| c , q |⟫\" := (exec' c q).\n\n\nReserved Notation \"x ==> y\" (at level 80, no associativity).\nInductive AM : Conf -> Conf -> Prop :=\n| am_val n q c : ⟨Val n, q, c⟩ ==> ⟪c, n⟫\n| am_add x y c q : ⟨Add x y, q, c⟩ ==> ⟨x, q, NEXT y q c⟩\n| am_get q c : ⟨Get, q, c ⟩ ==> ⟪c, q ⟫\n| am_put x q c : ⟨|Put x, q, c|⟩ ==> ⟨x, q, PUT c⟩                          \n| am_seqn x1 x2 q1 c : ⟨|Seqn x1 x2, q1, c|⟩ ==> ⟨|x1, q1, SEQN x2 c|⟩\n| am_while x1 x2 q c : ⟨|While x1 x2, q, c |⟩ ==> ⟨x1, q, CHECK x1 x2 q c⟩\n| am_NEXT y c n q : ⟪NEXT y q c, n⟫ ==> ⟨y, q, ADD n c⟩\n| am_ADD c n m : ⟪ADD n c, m⟫ ==> ⟪c, n+m⟫\n| am_PUT c n : ⟪PUT c, n⟫ ==> ⟪|c, n|⟫\n| am_SEQN x2 c q2 : ⟪| SEQN x2 c, q2|⟫ ==> ⟨|x2, q2, c |⟩\n| am_CHECK_0 c q x1 x2 : ⟪CHECK x1 x2 q c, 0⟫ ==> ⟪|c, q|⟫\n| am_CHECK_S c q v x1 x2 : v > 0 -> ⟪CHECK x1 x2 q c, v⟫ ==> ⟨|x2, q, WHILE x1 x2 c|⟩\n| am_WHILE x1 x2 c q2 : ⟪|WHILE x1 x2 c, q2 |⟫ ==> ⟨|While x1 x2, q2, c|⟩\nwhere \"x ==> y\" := (AM x y).\n\n(** * Calculation *)\n\n(** Boilerplate to import calculation tactics *)\n\nModule AM <: Preorder.\nDefinition Conf := Conf.\nDefinition VM := AM.\nEnd AM.\nModule AMCalc := Calculation AM.\nImport AMCalc.\n\n(** Specification of the abstract machine for expressions *)\n\nTheorem specExpr x q v c : x ⇓[q] v -> ⟨x, q, c⟩ =>> ⟪c, v⟫.\n(** Setup the induction proof *)\n\nProof.\n  intros.\n  generalize dependent c.\n  induction H;intros.\n\n(** Calculation of the abstract machine *)\n\n  begin\n  ⟪c, n⟫.\n  <== { apply am_val }\n  ⟨Val n, q, c⟩.\n  [].\n\n  begin\n    ⟪c, n + m ⟫.\n  <== { apply am_ADD }\n    ⟪ADD n c, m ⟫.\n  <<= { apply IHeval2 }\n    ⟨y, q, ADD n c⟩.\n  <<= { apply am_NEXT }\n    ⟪NEXT y q c , n⟫.\n  <<= { apply IHeval1 }\n      ⟨x, q, NEXT y q c⟩.\n  <== {apply am_add}\n      ⟨Add x y, q, c⟩.\n  [].\n\n\n  begin\n    ⟪c, q⟫.\n  <== {apply am_get}\n    ⟨Get, q, c ⟩.\n  [].\nQed.\n  \nTheorem specStmt x q q' c : x ↓[q] q' -> ⟨| x, q, c|⟩ =>> ⟪|c, q'|⟫.\n(** Setup the induction proof *)\n\nProof.\n  intros.\n  generalize dependent c.\n  induction H;intros.\n\n(** Calculation of the abstract machine *)\n\n  begin\n    ⟪|c, v|⟫.\n  <<= { apply am_PUT }\n    ⟪PUT c, v⟫.\n  <<= { apply specExpr }\n    ⟨x, q, PUT c⟩.\n  <<= { apply am_put }\n    ⟨|Put x, q, c|⟩.\n  [].\n\n  begin\n    ⟪|c, q3 |⟫.\n  <<= {apply IHrun2}\n    ⟨|x2, q2, c |⟩.\n  <== {apply am_SEQN}\n    ⟪| SEQN x2 c, q2|⟫.\n  <<= {apply IHrun1}\n    ⟨|x1, q1, SEQN x2 c |⟩.\n  <== {apply am_seqn}\n    ⟨|Seqn x1 x2, q1, c |⟩.\n  [].\n\n  begin\n    ⟪|c, q|⟫.\n  <== {apply am_CHECK_0}\n    ⟪CHECK x1 x2 q c, 0⟫.\n  <<= {apply specExpr}\n    ⟨x1, q, CHECK x1 x2 q c⟩.\n  <== {apply am_while}\n    ⟨|While x1 x2, q, c |⟩.\n  [].\n\n  begin\n    ⟪|c, q3 |⟫.\n  <<= {apply IHrun2}\n    ⟨|While x1 x2, q2, c|⟩.\n  <== {apply am_WHILE}\n    ⟪|WHILE x1 x2 c, q2|⟫.\n  <<= {apply IHrun1}\n    ⟨|x2, q1, WHILE x1 x2 c|⟩.\n  <== {apply am_CHECK_S}\n    ⟪CHECK x1 x2 q1 c, v⟫.\n  <<= {apply specExpr}\n    ⟨x1, q1, CHECK x1 x2 q1 c⟩.\n  <== {apply am_while}\n    ⟨|While x1 x2, q1, c |⟩.\n  [].\nQed.\n  \n(** * Soundness *)\n\nLemma determ_am : determ AM.\nProof.\n  intros C c1 c2 V.\n  induction V; intro V'; inversion V'; subst; try congruence;\n  match goal with\n  | [H : 0>0 |- _]  => inversion H\n  end.              \nQed.\n  \n\n\nDefinition terminates (p : Stmt) : Prop := exists r, p ↓[0] r.\n\nTheorem sound x C : terminates x -> ⟨|x, 0, HALT|⟩ =>>! C -> \n                    exists r, C = ⟪|HALT, r|⟫ /\\ x ↓[0] r.\nProof.\n  unfold terminates. intros. destruct H as [r T].\n  \n  pose (specStmt x 0 r HALT) as H'. exists r. split. pose (determ_trc determ_am) as D.\n  unfold determ in D. eapply D. eassumption. split. eauto. intro. destruct H. \n  inversion H. assumption.\nQed.\n  \n", "meta": {"author": "pa-ba", "repo": "cps-defun", "sha": "2f2c9d3e45f4a7fb12dadbff41579d0fa5a085bf", "save_path": "github-repos/coq/pa-ba-cps-defun", "path": "github-repos/coq/pa-ba-cps-defun/cps-defun-2f2c9d3e45f4a7fb12dadbff41579d0fa5a085bf/Loop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361628580401, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7328448233041834}}
{"text": "Require Import Arith.\n\nCompute 16.\n\nCompute 15+23.\n\nCompute 17*5.\n\nSearch nat.\n\nCheck 5.\nCheck nat.\nCheck gt.\n\nCompute gt 4.\nCompute gt 4 5.\n\nCheck gt 4.\n\nCompute Nat.double 8.\n\nCheck Nat.double.\n\nDefinition tres:nat := 3.\n\nCompute tres*5.\n\nDefinition mas (a:nat)(b:nat) := a+b+tres.\n\n(* Compute 4 mas 5. *)\n\nCompute mas 4 2.\nCheck mas.\nCheck mas 4 tres.\n\nSearch nat.\n\nDefinition uno := S 0.\n\nCompute uno.\nPrint uno.\nCheck uno.\n\nCompute S.\n\nDefinition five := S(S(S(S(S(0))))).\nCompute five.\n\nDefinition double (m:nat) := plus m m.\n\nCompute double 8.\n\nCompute plus.\n\nInductive NoTieneSentido : Set := \n|carita_feliz : NoTieneSentido\n|carita_triste : NoTieneSentido\n|emociones : nat->NoTieneSentido.\n\nCompute emociones 4.\n\nCheck nat.", "meta": {"author": "DavidContrerasFranco", "repo": "Logic-in-Computer-Science", "sha": "9aeaaa572834a87a921f321a92d1462034beece6", "save_path": "github-repos/coq/DavidContrerasFranco-Logic-in-Computer-Science", "path": "github-repos/coq/DavidContrerasFranco-Logic-in-Computer-Science/Logic-in-Computer-Science-9aeaaa572834a87a921f321a92d1462034beece6/Class Examples/Codigo_Clase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7328448228302772}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria.                       *)\n(* You may distribute this file under the terms of the CeCILL-B license *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nRequire Import finfun bigop prime binomial ssralg finset fingroup finalg.\nRequire Import perm zmodp matrix.\n\n(*****************************************************************************)\n(* In this file we develop the rank and row space theory of matrices, based  *)\n(* on an extended Gaussian elimination procedure similar to LUP              *)\n(* decomposition. This provides us with a concrete but generic model of      *)\n(* finite dimensional vector spaces and F-algebras, in which vectors, linear *)\n(* functions, families, bases, subspaces, ideals and subrings are all        *)\n(* represented using matrices. This model can be used as a foundation for    *)\n(* the usual theory of abstract linear algebra, but it can also be used to   *)\n(* develop directly substantial theories, such as the theory of finite group *)\n(* linear representation.                                                    *)\n(*   Here we define the following concepts and notations:                    *)\n(* Gaussian_elimination A == a permuted triangular decomposition (L, U, r)   *)\n(*                   of A, with L a column permutation of a lower triangular *)\n(*                   invertible matrix, U a row permutation of an upper      *)\n(*                   triangular invertible matrix, and r the rank of A, all  *)\n(*                   satisfying the identity L *m pid_mx r *m U = A.         *)\n(*        \\rank A == the rank of A.                                          *)\n(*    row_free A <=> the rows of A are linearly free (i.e., the rank and     *)\n(*                   height of A are equal).                                 *)\n(*    row_full A <=> the row-space of A spans all row-vectors (i.e., the     *)\n(*                   rank and width of A are equal).                         *)\n(*    col_ebase A == the extended column basis of A (the first matrix L      *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*    row_ebase A == the extended row base of A (the second matrix U         *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*     col_base A == a basis for the columns of A: a row-full matrix         *)\n(*                   consisting of the first \\rank A columns of col_ebase A. *)\n(*     row_base A == a basis for the rows of A: a row-free matrix consisting *)\n(*                   of the first \\rank A rows of row_ebase A.               *)\n(*       pinvmx A == a partial inverse for A in its row space (or on its     *)\n(*                   column space, equivalently). In particular, if u is a   *)\n(*                   row vector in the row_space of A, then u *m pinvmx A is *)\n(*                   the row vector of the coefficients of a decomposition   *)\n(*                   of u as a sub of rows of A.                             *)\n(*        kermx A == the row kernel of A : a square matrix whose row space   *)\n(*                   consists of all u such that u *m A = 0 (it consists of  *)\n(*                   the inverse of col_ebase A, with the top \\rank A rows   *)\n(*                   zeroed out). Also, kermx A is a partial right inverse   *)\n(*                   to col_ebase A, in the row space anihilated by A.       *)\n(*      cokermx A == the cokernel of A : a square matrix whose column space  *)\n(*                   consists of all v such that A *m v = 0 (it consists of  *)\n(*                   the inverse of row_ebase A, with the leftmost \\rank A   *)\n(*                   columns zeroed out).                                    *)\n(* eigenvalue g a <=> a is an eigenvalue of the square matrix g.             *)\n(* eigenspace g a == a square matrix whose row space is the eigenspace of    *)\n(*                   the eigenvalue a of g (or 0 if a is not an eigenvalue). *)\n(* We use a different scope %MS for matrix row-space set-like operations; to *)\n(* avoid confusion, this scope should not be opened globally. Note that the  *)\n(* the arguments of \\rank _ and the operations below have default scope %MS. *)\n(*    (A <= B)%MS <=> the row-space of A is included in the row-space of B.  *)\n(*                   We test for this by testing if cokermx B anihilates A.  *)\n(*     (A < B)%MS <=> the row-space of A is properly included in the         *)\n(*                   row-space of B.                                         *)\n(*  (A <= B <= C)%MS == (A <= B)%MS && (B <= C)%MS, and similarly for        *)\n(*                   (A < B <= C)%MS, (A < B <= C)%MS and (A < B < C)%MS.    *)\n(*    (A == B)%MS == (A <= B <= A)%MS (A and B have the same row-space).     *)\n(*   (A :=: B)%MS == A and B behave identically wrt. \\rank and <=. This      *)\n(*                   triple rewrite rule is the Prop version of (A == B)%MS. *)\n(*                   Note that :=: cannot be treated as a setoid-style       *)\n(*                   Equivalence because its arguments can have different    *)\n(*                   types: A and B need not have the same number of rows,   *)\n(*                   and often don't (e.g., in row_base A :=: A).            *)\n(*       <<A>>%MS == a square matrix with the same row-space as A; <<A>>%MS  *)\n(*                   is a canonical representation of the subspace generated *)\n(*                   by A, viewed as a list of row-vectors: if (A == B)%MS,  *)\n(*                   then <<A>>%MS = <<B>>%MS.                               *)\n(*     (A + B)%MS == a square matrix whose row-space is the sum of the       *)\n(*                   row-spaces of A and B; thus (A + B == col_mx A B)%MS.   *)\n(*  (\\sum_i <expr i>)%MS == the \"big\" version of (_ + _)%MS; as the latter   *)\n(*                   has a canonical abelian monoid structure, most generic  *)\n(*                   bigop lemmas apply (the other bigop indexing notations  *)\n(*                   are also defined).                                      *)\n(*   (A :&: B)%MS == a square matrix whose row-space is the intersection of  *)\n(*                   the row-spaces of A and B.                              *)\n(*  (\\bigcap_i <expr i>)%MS == the \"big\" version of (_ :&: _)%MS, which also *)\n(*                   has a canonical abelian monoid structure.               *)\n(*         A^C%MS == a square matrix whose row-space is a complement to the  *)\n(*                   the row-space of A (it consists of row_ebase A with the *)\n(*                   top \\rank A rows zeroed out).                           *)\n(*   (A :\\: B)%MS == a square matrix whose row-space is a complement of the  *)\n(*                   the row-space of (A :&: B)%MS in the row-space of A.    *)\n(*                   We have (A :\\: B := A :&: (capmx_gen A B)^C)%MS, where  *)\n(*                   capmx_gen A B is a rectangular matrix equivalent to     *)\n(*                   (A :&: B)%MS, i.e., (capmx_gen A B == A :&: B)%MS.      *)\n(*    proj_mx A B == a square matrix that projects (A + B)%MS onto A         *)\n(*                   parellel to B, when (A :&: B)%MS = 0 (A and B must also *)\n(*                   be square).                                             *)\n(*     mxdirect S == the sum expression S is a direct sum. This is a NON     *)\n(*                   EXTENSIONAL notation: the exact boolean expression is   *)\n(*                   inferred from the syntactic form of S (expanding        *)\n(*                   definitions, however); both (\\sum_(i | _) _)%MS and     *)\n(*                   (_ + _)%MS sums are recognized. This construct uses a   *)\n(*                   variant of the reflexive (\"quote\") canonical structure, *)\n(*                   mxsum_expr. The structure also recognizes sums of       *)\n(*                   matrix ranks, so that lemmas concerning the rank of     *)\n(*                   direct sums can be used bidirectionally.                *)\n(* The next set of definitions let us represent F-algebras using matrices:   *)\n(*   'A[F]_(m, n) == the type of matrices encoding (sub)algebras of square   *)\n(*                   n x n matrices, via mxvec; as in the matrix type        *)\n(*                   notation, m and F can be omitted (m defaults to n ^ 2). *)\n(*                := 'M[F]_(m, n ^ 2).                                       *)\n(*   (A \\in R)%MS <=> the square matrix A belongs to the linear set of       *)\n(*                    matrices (most often, a sub-algebra) encoded by the    *)\n(*                    row space of R. This is simply notation, so all the    *)\n(*                    lemmas and rewrite rules for (_ <= _)%MS can apply.    *)\n(*                := (mxvec A <= R)%MS.                                      *)\n(*     (R * S)%MS == a square n^2 x n^2 matrix whose row-space encodes the   *)\n(*                   linear set of n x n matrices generated by the pointwise *)\n(*                   product of the sets of matrices encoded by R and S.     *)\n(*       'C(R)%MS == a square matric encoding the centraliser of the set of  *)\n(*                   square matrices encoded by R.                           *)\n(*     'C_S(R)%MS := (S :&: 'C(R))%MS (the centraliser of R in S).           *)\n(*       'Z(R)%MS == the center of R (i.e., 'C_R(R)%MS).                     *)\n(*  left_mx_ideal R S <=> S is a left ideal for R (R * S <= S)%MS.           *)\n(* right_mx_ideal R S <=> S is a right ideal for R (S * R <= S)%MS.          *)\n(*       mx_ideal R S <=> S is a bilateral ideal for R.                      *)\n(*      mxring_id R e <-> e is an identity element for R (Prop predicate).   *)\n(*    has_mxring_id R <=> R has a nonzero identity element (bool predicate). *)\n(*           mxring R <=> R encodes a nontrivial subring.                    *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope.\nImport GRing.Theory.\nOpen Local Scope ring_scope.\n\nReserved Notation \"\\rank A\" (at level 10, A at level 8, format \"\\rank  A\").\nReserved Notation \"A ^C\"    (at level 8, format \"A ^C\").\n\nNotation \"''A_' ( m , n )\" := 'M_(m, n ^ 2)\n  (at level 8, format \"''A_' ( m ,  n )\") : type_scope.\n\nNotation \"''A_' ( n )\" := 'A_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A_' n\" := 'A_(n)\n  (at level 8, n at next level, format \"''A_' n\") : type_scope.\n\nNotation \"''A' [ F ]_ ( m , n )\" := 'M[F]_(m, n ^ 2)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ ( n )\" := 'A[F]_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ n\" := 'A[F]_(n)\n  (at level 8, n at level 2, only parsing) : type_scope.\n\nDelimit Scope matrix_set_scope with MS.\n\nNotation Local simp := (Monoid.Theory.simpm, oppr0).\n\n(*****************************************************************************)\n(******************** Rank and row-space theory ******************************)\n(*****************************************************************************)\n\nSection RowSpaceTheory.\n\nVariable F : fieldType.\nImplicit Types m n p r : nat.\n\nLocal Notation \"''M_' ( m , n )\" := 'M[F]_(m, n) : type_scope.\nLocal Notation \"''M_' n\" := 'M[F]_(n, n) : type_scope.\n\n(* Decomposition with double pivoting; computes the rank, row and column  *)\n(* images, kernels, and complements of a matrix.                          *)\n\nFixpoint Gaussian_elimination {m n} : 'M_(m, n) -> 'M_m * 'M_n * nat :=\n  match m, n with\n  | _.+1, _.+1 => fun A : 'M_(1 + _, 1 + _) =>\n    if [pick ij | A ij.1 ij.2 != 0] is Some (i, j) then\n      let a := A i j in let A1 := xrow i 0 (xcol j 0 A) in\n      let u := ursubmx A1 in let v := a^-1 *: dlsubmx A1 in\n      let: (L, U, r) := Gaussian_elimination (drsubmx A1 - v *m u) in\n      (xrow i 0 (block_mx 1 0 v L), xcol j 0 (block_mx a%:M u 0 U), r.+1)\n    else (1%:M, 1%:M, 0%N)\n  | _, _ => fun _ => (1%:M, 1%:M, 0%N)\n  end.\n\nSection Defs.\n\nVariables (m n : nat) (A : 'M_(m, n)).\n\nFact Gaussian_elimination_key : unit. Proof. by []. Qed.\n\nLet LUr := locked_with Gaussian_elimination_key (@Gaussian_elimination) m n A.\n\nDefinition col_ebase := LUr.1.1.\nDefinition row_ebase := LUr.1.2.\nDefinition mxrank := if [|| m == 0 | n == 0]%N then 0%N else LUr.2.\n\nDefinition row_free := mxrank == m.\nDefinition row_full := mxrank == n.\n\nDefinition row_base : 'M_(mxrank, n) := pid_mx mxrank *m row_ebase.\nDefinition col_base : 'M_(m, mxrank) := col_ebase *m pid_mx mxrank.\n\nDefinition complmx : 'M_n := copid_mx mxrank *m row_ebase.\nDefinition kermx : 'M_m := copid_mx mxrank *m invmx col_ebase.\nDefinition cokermx : 'M_n := invmx row_ebase *m copid_mx mxrank.\n\nDefinition pinvmx : 'M_(n, m) :=\n  invmx row_ebase *m pid_mx mxrank *m invmx col_ebase.\n\nEnd Defs.\n\nArguments Scope mxrank [nat_scope nat_scope matrix_set_scope].\nLocal Notation \"\\rank A\" := (mxrank A) : nat_scope.\nArguments Scope complmx [nat_scope nat_scope matrix_set_scope].\nLocal Notation \"A ^C\" := (complmx A) : matrix_set_scope.\n\nDefinition submx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  A *m cokermx B == 0).\nFact submx_key : unit. Proof. by []. Qed.\nDefinition submx := locked_with submx_key submx_def.\nCanonical submx_unlockable := [unlockable fun submx].\n\nArguments Scope submx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits submx.\nLocal Notation \"A <= B\" := (submx A B) : matrix_set_scope.\nLocal Notation \"A <= B <= C\" := ((A <= B) && (B <= C))%MS : matrix_set_scope.\nLocal Notation \"A == B\" := (A <= B <= A)%MS : matrix_set_scope.\n\nDefinition ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  (A <= B)%MS && ~~ (B <= A)%MS.\nArguments Scope ltmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits ltmx.\nLocal Notation \"A < B\" := (ltmx A B) : matrix_set_scope.\n\nDefinition eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  prod (\\rank A = \\rank B)\n       (forall m3 (C : 'M_(m3, n)),\n            ((A <= C) = (B <= C)) * ((C <= A) = (C <= B)))%MS.\nArguments Scope eqmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nLocal Notation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\n\nSection LtmxIdentities.\n\nVariables (m1 m2 n : nat) (A : 'M_(m1, n)) (B : 'M_(m2, n)).\n\nLemma ltmxE : (A < B)%MS = ((A <= B)%MS && ~~ (B <= A)%MS). Proof. by []. Qed.\n\nLemma ltmxW : (A < B)%MS -> (A <= B)%MS. Proof. by case/andP. Qed.\n\nLemma ltmxEneq : (A < B)%MS = (A <= B)%MS && ~~ (A == B)%MS.\nProof. by apply: andb_id2l => ->. Qed.\n\nLemma submxElt : (A <= B)%MS = (A == B)%MS || (A < B)%MS.\nProof. by rewrite -andb_orr orbN andbT. Qed.\n\nEnd LtmxIdentities.\n\n(* The definition of the row-space operator is rigged to return the identity  *)\n(* matrix for full matrices. To allow for further tweaks that will make the   *)\n(* row-space intersection operator strictly commutative and monoidal, we      *)\n(* slightly generalize some auxiliary definitions: we parametrize the         *)\n(* \"equivalent subspace and identity\" choice predicate equivmx by a boolean   *)\n(* determining whether the matrix should be the identity (so for genmx A its  *)\n(* value is row_full A), and introduce a \"quasi-identity\" predicate qidmx     *)\n(* that selects non-square full matrices along with the identity matrix 1%:M  *)\n(* (this does not affect genmx, which chooses a square matrix).               *)\n(*   The choice witness for genmx A is either 1%:M for a row-full A, or else  *)\n(* row_base A padded with null rows.                                          *)\nLet qidmx m n (A : 'M_(m, n)) :=\n  if m == n then A == pid_mx n else row_full A.\nLet equivmx m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  (B == A)%MS && (qidmx B == idA).\nLet equivmx_spec m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  prod (B :=: A)%MS (qidmx B = idA).\nDefinition genmx_witness m n (A : 'M_(m, n)) : 'M_n :=\n  if row_full A then 1%:M else pid_mx (\\rank A) *m row_ebase A.\nDefinition genmx_def := idfun (fun m n (A : 'M_(m, n)) =>\n   choose (equivmx A (row_full A)) (genmx_witness A) : 'M_n).\nFact genmx_key : unit. Proof. by []. Qed.\nDefinition genmx := locked_with genmx_key genmx_def.\nCanonical genmx_unlockable := [unlockable fun genmx].\nLocal Notation \"<< A >>\" := (genmx A) : matrix_set_scope.\n\n(* The setwise sum is tweaked so that 0 is a strict identity element for      *)\n(* square matrices, because this lets us use the bigop component. As a result *)\n(* setwise sum is not quite strictly extensional.                             *)\nLet addsmx_nop m n (A : 'M_(m, n)) := conform_mx <<A>>%MS A.\nDefinition addsmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if A == 0 then addsmx_nop B else if B == 0 then addsmx_nop A else\n  <<col_mx A B>>%MS : 'M_n).\nFact addsmx_key : unit. Proof. by []. Qed.\nDefinition addsmx := locked_with addsmx_key addsmx_def.\nCanonical addsmx_unlockable := [unlockable fun addsmx].\nArguments Scope addsmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits addsmx.\nLocal Notation \"A + B\" := (addsmx A B) : matrix_set_scope.\nLocal Notation \"\\sum_ ( i | P ) B\" := (\\big[addsmx/0]_(i | P) B%MS)\n  : matrix_set_scope.\nLocal Notation \"\\sum_ ( i <- r | P ) B\" := (\\big[addsmx/0]_(i <- r | P) B%MS)\n  : matrix_set_scope.\n\n(* The set intersection is similarly biased so that the identity matrix is a  *)\n(* strict identity. This is somewhat more delicate than for the sum, because  *)\n(* the test for the identity is non-extensional. This forces us to actually   *)\n(* bias the choice operator so that it does not accidentally map an           *)\n(* intersection of non-identity matrices to 1%:M; this would spoil            *)\n(* associativity: if B :&: C = 1%:M but B and C are not identity, then for a  *)\n(* square matrix A we have A :&: (B :&: C) = A != (A :&: B) :&: C in general. *)\n(* To complicate matters there may not be a square non-singular matrix        *)\n(* different than 1%:M, since we could be dealing with 'M['F_2]_1. We         *)\n(* sidestep the issue by making all non-square row-full matrices identities,  *)\n(* and choosing a normal representative that preserves the qidmx property.    *)\n(* Thus A :&: B = 1%:M iff A and B are both identities, and this suffices for *)\n(* showing that associativity is strict.                                      *)\nLet capmx_witness m n (A : 'M_(m, n)) :=\n  if row_full A then conform_mx 1%:M A else <<A>>%MS.\nLet capmx_norm m n (A : 'M_(m, n)) :=\n  choose (equivmx A (qidmx A)) (capmx_witness A).\nLet capmx_nop m n (A : 'M_(m, n)) := conform_mx (capmx_norm A) A.\nDefinition capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  lsubmx (kermx (col_mx A B)) *m A.\nDefinition capmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if qidmx A then capmx_nop B else\n  if qidmx B then capmx_nop A else\n  if row_full B then capmx_norm A else capmx_norm (capmx_gen A B) : 'M_n).\nFact capmx_key : unit. Proof. by []. Qed.\nDefinition capmx := locked_with capmx_key capmx_def.\nCanonical capmx_unlockable := [unlockable fun capmx].\nArguments Scope capmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits capmx.\nLocal Notation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nLocal Notation \"\\bigcap_ ( i | P ) B\" := (\\big[capmx/1%:M]_(i | P) B)\n  : matrix_set_scope.\n\nDefinition diffmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  <<capmx_gen A (capmx_gen A B)^C>>%MS : 'M_n).\nFact diffmx_key : unit. Proof. by []. Qed.\nDefinition diffmx := locked_with diffmx_key diffmx_def.\nCanonical diffmx_unlockable := [unlockable fun diffmx].\nArguments Scope diffmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits diffmx.\nLocal Notation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\n\nDefinition proj_mx n (U V : 'M_n) : 'M_n := pinvmx (col_mx U V) *m col_mx U 0.\n\nLocal Notation GaussE := Gaussian_elimination.\n\nFact mxrankE m n (A : 'M_(m, n)) : \\rank A = (GaussE A).2.\nProof. by rewrite /mxrank unlock /=; case: m n A => [|m] [|n]. Qed.\n\nLemma rank_leq_row m n (A : 'M_(m, n)) : \\rank A <= m.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma row_leq_rank m n (A : 'M_(m, n)) : (m <= \\rank A) = row_free A.\nProof. by rewrite /row_free eqn_leq rank_leq_row. Qed.\n\nLemma rank_leq_col m n (A : 'M_(m, n)) : \\rank A <= n.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma col_leq_rank m n (A : 'M_(m, n)) : (n <= \\rank A) = row_full A.\nProof. by rewrite /row_full eqn_leq rank_leq_col. Qed.\n\nLet unitmx1F := @unitmx1 F.\nLemma row_ebase_unit m n (A : 'M_(m, n)) : row_ebase A \\in unitmx.\nProof.\nrewrite /row_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] /= nzAij | //=]; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uU.\nrewrite unitmxE xcolE det_mulmx (@det_ublock _ 1) det_scalar1 !unitrM.\nby rewrite unitfE nzAij -!unitmxE uU unitmx_perm.\nQed.\n\nLemma col_ebase_unit m n (A : 'M_(m, n)) : col_ebase A \\in unitmx.\nProof.\nrewrite /col_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] _|] //=; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uL.\nrewrite unitmxE xrowE det_mulmx (@det_lblock _ 1) det1 mul1r unitrM.\nby rewrite -unitmxE unitmx_perm.\nQed.\nHint Resolve rank_leq_row rank_leq_col row_ebase_unit col_ebase_unit.\n\nLemma mulmx_ebase m n (A : 'M_(m, n)) :\n  col_ebase A *m pid_mx (\\rank A) *m row_ebase A = A.\nProof.\nrewrite mxrankE /col_ebase /row_ebase unlock.\nelim: m n A => [n A | m IHm]; first by rewrite [A]flatmx0 [_ *m _]flatmx0.\ncase=> [A | n]; first by rewrite [_ *m _]thinmx0 [A]thinmx0.\nrewrite -(add1n m) -?(add1n n) => A /=.\ncase: pickP => [[i0 j0] | A0] /=; last first.\n  apply/matrixP=> i j; rewrite pid_mx_0 mulmx0 mul0mx mxE.\n  by move/eqP: (A0 (i, j)).\nset a := A i0 j0 => nz_a; set A1 := xrow _ _ _.\nset u := ursubmx _; set v := _ *: _; set B : 'M_(m, n) := _ - _.\nmove: (rank_leq_col B) (rank_leq_row B) {IHm}(IHm n B); rewrite mxrankE.\ncase: (GaussE B) => [[L U] r] /= r_m r_n defB.\nhave ->: pid_mx (1 + r) = block_mx 1 0 0 (pid_mx r) :> 'M[F]_(1 + m, 1 + n).\n  rewrite -(subnKC r_m) -(subnKC r_n) pid_mx_block -col_mx0 -row_mx0.\n  by rewrite block_mxA castmx_id col_mx0 row_mx0 -scalar_mx_block -pid_mx_block.\nrewrite xcolE xrowE mulmxA -xcolE -!mulmxA.\nrewrite !(addr0, add0r, mulmx0, mul0mx, mulmx_block, mul1mx) mulmxA defB.\nrewrite addrC subrK mul_mx_scalar scalerA divff // scale1r.\nhave ->: a%:M = ulsubmx A1 by rewrite [_ A1]mx11_scalar !mxE !lshift0 !tpermR.\nrewrite submxK /A1 xrowE !xcolE -!mulmxA mulmxA -!perm_mxM !tperm2 !perm_mx1.\nby rewrite mulmx1 mul1mx.\nQed.\n\nLemma mulmx_base m n (A : 'M_(m, n)) : col_base A *m row_base A = A.\nProof. by rewrite mulmxA -[col_base A *m _]mulmxA pid_mx_id ?mulmx_ebase. Qed.\n\nLemma mulmx1_min_rank r m n (A : 'M_(m, n)) M N :\n  M *m A *m N = 1%:M :> 'M_r -> r <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) mulmxA -mulmxA; move/mulmx1_min. Qed.\nImplicit Arguments mulmx1_min_rank [r m n A].\n\nLemma mulmx_max_rank r m n (M : 'M_(m, r)) (N : 'M_(r, n)) :\n  \\rank (M *m N) <= r.\nProof.\nset MN := M *m N; set rMN := \\rank _.\npose L : 'M_(rMN, m) := pid_mx rMN *m invmx (col_ebase MN).\npose U : 'M_(n, rMN) := invmx (row_ebase MN) *m pid_mx rMN.\nsuffices: L *m M *m (N *m U) = 1%:M by exact: mulmx1_min.\nrewrite mulmxA -(mulmxA L) -[M *m N]mulmx_ebase -/MN.\nby rewrite !mulmxA mulmxKV // mulmxK // !pid_mx_id /rMN ?pid_mx_1.\nQed.\nImplicit Arguments mulmx_max_rank [r m n].\n\nLemma mxrank_tr m n (A : 'M_(m, n)) : \\rank A^T = \\rank A.\nProof.\napply/eqP; rewrite eqn_leq -{3}[A]trmxK -{1}(mulmx_base A) -{1}(mulmx_base A^T).\nby rewrite !trmx_mul !mulmx_max_rank.\nQed.\n\nLemma mxrank_add m n (A B : 'M_(m, n)) : \\rank (A + B)%R <= \\rank A + \\rank B.\nProof.\nby rewrite -{1}(mulmx_base A) -{1}(mulmx_base B) -mul_row_col mulmx_max_rank.\nQed.\n\nLemma mxrankM_maxl m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) -mulmxA mulmx_max_rank. Qed.\n\nLemma mxrankM_maxr m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank B.\nProof. by rewrite -mxrank_tr -(mxrank_tr B) trmx_mul mxrankM_maxl. Qed.\n\nLemma mxrank_scale m n a (A : 'M_(m, n)) : \\rank (a *: A) <= \\rank A.\nProof. by rewrite -mul_scalar_mx mxrankM_maxr. Qed.\n\nLemma mxrank_scale_nz m n a (A : 'M_(m, n)) :\n   a != 0 -> \\rank (a *: A) = \\rank A.\nProof.\nmove=> nza; apply/eqP; rewrite eqn_leq -{3}[A]scale1r -(mulVf nza).\nby rewrite -scalerA !mxrank_scale.\nQed.\n\nLemma mxrank_opp m n (A : 'M_(m, n)) : \\rank (- A) = \\rank A.\nProof. by rewrite -scaleN1r mxrank_scale_nz // oppr_eq0 oner_eq0. Qed.\n\nLemma mxrank0 m n : \\rank (0 : 'M_(m, n)) = 0%N.\nProof. by apply/eqP; rewrite -leqn0 -(@mulmx0 _ m 0 n 0) mulmx_max_rank. Qed.\n\nLemma mxrank_eq0 m n (A : 'M_(m, n)) : (\\rank A == 0%N) = (A == 0).\nProof.\napply/eqP/eqP=> [rA0 | ->{A}]; last exact: mxrank0.\nmove: (col_base A) (row_base A) (mulmx_base A); rewrite rA0 => Ac Ar <-.\nby rewrite [Ac]thinmx0 mul0mx.\nQed.\n\nLemma mulmx_coker m n (A : 'M_(m, n)) : A *m cokermx A = 0.\nProof.\nby rewrite -{1}[A]mulmx_ebase -!mulmxA mulKVmx // mul_pid_mx_copid ?mulmx0.\nQed.\n\nLemma submxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS = (A *m cokermx B == 0).\nProof. by rewrite unlock. Qed.\n\nLemma mulmxKpV m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> A *m pinvmx B *m B = A.\nProof.\nrewrite submxE !mulmxA mulmxBr mulmx1 subr_eq0 => /eqP defA.\nrewrite -{4}[B]mulmx_ebase -!mulmxA mulKmx //.\nby rewrite (mulmxA (pid_mx _)) pid_mx_id // !mulmxA -{}defA mulmxKV.\nQed.\n\nLemma submxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists D, A = D *m B) (A <= B)%MS.\nProof.\napply: (iffP idP) => [/mulmxKpV | [D ->]]; first by exists (A *m pinvmx B).\nby rewrite submxE -mulmxA mulmx_coker mulmx0.\nQed.\nImplicit Arguments submxP [m1 m2 n A B].\n\nLemma submx_refl m n (A : 'M_(m, n)) : (A <= A)%MS.\nProof. by rewrite submxE mulmx_coker. Qed.\nHint Resolve submx_refl.\n\nLemma submxMl m n p (D : 'M_(m, n)) (A : 'M_(n, p)) : (D *m A <= A)%MS.\nProof. by rewrite submxE -mulmxA mulmx_coker mulmx0. Qed.\n\nLemma submxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A <= B)%MS -> (A *m C <= B *m C)%MS.\nProof. by case/submxP=> D ->; rewrite -mulmxA submxMl. Qed.\n\nLemma mulmx_sub m n1 n2 p (C : 'M_(m, n1)) A (B : 'M_(n2, p)) :\n  (A <= B -> C *m A <= B)%MS.\nProof. by case/submxP=> D ->; rewrite mulmxA submxMl. Qed.\n\nLemma submx_trans m1 m2 m3 n\n                 (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B -> B <= C -> A <= C)%MS.\nProof. by case/submxP=> D ->{A}; exact: mulmx_sub. Qed.\n\nLemma ltmx_sub_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A < B)%MS -> (B <= C)%MS -> (A < C)%MS.\nProof.\ncase/andP=> sAB ltAB sBC; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltAB; exact: submx_trans.\nQed.\n\nLemma sub_ltmx_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B)%MS -> (B < C)%MS -> (A < C)%MS.\nProof.\nmove=> sAB /andP[sBC ltBC]; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltBC => sCA; exact: submx_trans sAB.\nQed.\n\nLemma ltmx_trans m n : transitive (@ltmx m m n).\nProof. by move=> A B C; move/ltmxW; exact: sub_ltmx_trans. Qed.\n\nLemma ltmx_irrefl m n : irreflexive (@ltmx m m n).\nProof. by move=> A; rewrite /ltmx submx_refl andbF. Qed.\n\nLemma sub0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) <= A)%MS.\nProof. by rewrite submxE mul0mx. Qed.\n\nLemma submx0null m1 m2 n (A : 'M[F]_(m1, n)) :\n  (A <= (0 : 'M_(m2, n)))%MS -> A = 0.\nProof. by case/submxP=> D; rewrite mulmx0. Qed.\n\nLemma submx0 m n (A : 'M_(m, n)) : (A <= (0 : 'M_n))%MS = (A == 0).\nProof. by apply/idP/eqP=> [|->]; [exact: submx0null | exact: sub0mx]. Qed.\n\nLemma lt0mx m n (A : 'M_(m, n)) : ((0 : 'M_n) < A)%MS = (A != 0).\nProof. by rewrite /ltmx sub0mx submx0. Qed.\n\nLemma ltmx0 m n (A : 'M[F]_(m, n)) : (A < (0 : 'M_n))%MS = false.\nProof. by rewrite /ltmx sub0mx andbF. Qed.\n\nLemma eqmx0P m n (A : 'M_(m, n)) : reflect (A = 0) (A == (0 : 'M_n))%MS.\nProof. by rewrite submx0 sub0mx andbT; exact: eqP. Qed.\n\nLemma eqmx_eq0 m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (A == 0) = (B == 0).\nProof. by move=> eqAB; rewrite -!submx0 eqAB. Qed.\n\nLemma addmx_sub m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= C)%MS -> (B <= C)%MS -> ((A + B)%R <= C)%MS.\nProof.\nby case/submxP=> A' ->; case/submxP=> B' ->; rewrite -mulmxDl submxMl.\nQed.\n\nLemma summx_sub m1 m2 n (B : 'M_(m2, n))\n                I (r : seq I) (P : pred I) (A_ : I -> 'M_(m1, n)) :\n  (forall i, P i -> A_ i <= B)%MS -> ((\\sum_(i <- r | P i) A_ i)%R <= B)%MS.\nProof.\nmove=> leAB; elim/big_ind: _ => // [|A1 A2]; [exact: sub0mx | exact: addmx_sub].\nQed.\n\nLemma scalemx_sub m1 m2 n a (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> (a *: A <= B)%MS.\nProof. by case/submxP=> A' ->; rewrite scalemxAl submxMl. Qed.\n\nLemma row_sub m n i (A : 'M_(m, n)) : (row i A <= A)%MS.\nProof. by rewrite rowE submxMl. Qed.\n\nLemma eq_row_sub m n v (A : 'M_(m, n)) i : row i A = v -> (v <= A)%MS.\nProof. by move <-; rewrite row_sub. Qed.\n\nLemma nz_row_sub m n (A : 'M_(m, n)) : (nz_row A <= A)%MS.\nProof. by rewrite /nz_row; case: pickP => [i|] _; rewrite ?row_sub ?sub0mx. Qed.\n\nLemma row_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall i, row i A <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i|sAB].\n  by apply: submx_trans sAB; exact: row_sub.\nrewrite submxE; apply/eqP/row_matrixP=> i; apply/eqP.\nby rewrite row_mul row0 -submxE.\nQed.\nImplicit Arguments row_subP [m1 m2 n A B].\n\nLemma rV_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB v Av | sAB]; first exact: submx_trans sAB.\nby apply/row_subP=> i; rewrite sAB ?row_sub.\nQed.\nImplicit Arguments rV_subP [m1 m2 n A B].\n\nLemma row_subPn m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists i, ~~ (row i A <= B)%MS) (~~ (A <= B)%MS).\nProof. by rewrite (sameP row_subP forallP) negb_forall; exact: existsP. Qed.\n\nLemma sub_rVP n (u v : 'rV_n) : reflect (exists a, u = a *: v) (u <= v)%MS.\nProof.\napply: (iffP submxP) => [[w ->] | [a ->]].\n  by exists (w 0 0); rewrite -mul_scalar_mx -mx11_scalar.\nby exists a%:M; rewrite mul_scalar_mx.\nQed.\n\nLemma rank_rV n (v : 'rV_n) : \\rank v = (v != 0).\nProof.\ncase: eqP => [-> | nz_v]; first by rewrite mxrank0.\nby apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0; exact/eqP.\nQed.\n\nLemma rowV0Pn m n (A : 'M_(m, n)) :\n  reflect (exists2 v : 'rV_n, v <= A & v != 0)%MS (A != 0).\nProof.\nrewrite -submx0; apply: (iffP idP) => [| [v svA]]; last first.\n  by rewrite -submx0; exact: contra (submx_trans _).\nby case/row_subPn=> i; rewrite submx0; exists (row i A); rewrite ?row_sub.\nQed.\n\nLemma rowV0P m n (A : 'M_(m, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v = 0)%MS (A == 0).\nProof.\nrewrite -[A == 0]negbK; case: rowV0Pn => IH.\n  by right; case: IH => v svA nzv IH; case/eqP: nzv; exact: IH.\nby left=> v svA; apply/eqP; apply/idPn=> nzv; case: IH; exists v.\nQed.\n\nLemma submx_full m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A <= B)%MS.\nProof.\nby rewrite submxE /cokermx =>/eqnP->; rewrite /copid_mx pid_mx_1 subrr !mulmx0.\nQed.\n\nLemma row_fullP m n (A : 'M_(m, n)) :\n  reflect (exists B, B *m A = 1%:M) (row_full A).\nProof.\napply: (iffP idP) => [Afull | [B kA]].\n  by exists (1%:M *m pinvmx A); apply: mulmxKpV (submx_full _ Afull).\nby rewrite [_ A]eqn_leq rank_leq_col (mulmx1_min_rank B 1%:M) ?mulmx1.\nQed.\nImplicit Arguments row_fullP [m n A].\n\nLemma row_full_inj m n p A : row_full A -> injective (@mulmx _ m n p A).\nProof.\ncase/row_fullP=> A' A'K; apply: can_inj (mulmx A') _ => B.\nby rewrite mulmxA A'K mul1mx.\nQed.\n\nLemma row_freeP m n (A : 'M_(m, n)) :\n  reflect (exists B, A *m B = 1%:M) (row_free A).\nProof.\nrewrite /row_free -mxrank_tr.\napply: (iffP row_fullP) => [] [B kA];\n  by exists B^T; rewrite -trmx1 -kA trmx_mul ?trmxK.\nQed.\n\nLemma row_free_inj m n p A : row_free A -> injective ((@mulmx _ m n p)^~ A).\nProof.\ncase/row_freeP=> A' AK; apply: can_inj (mulmx^~ A') _ => B.\nby rewrite -mulmxA AK mulmx1.\nQed.\n\nLemma row_free_unit n (A : 'M_n) : row_free A = (A \\in unitmx).\nProof.\napply/row_fullP/idP=> [[A'] | uA]; first by case/mulmx1_unit.\nby exists (invmx A); rewrite mulVmx.\nQed.\n\nLemma row_full_unit n (A : 'M_n) : row_full A = (A \\in unitmx).\nProof. exact: row_free_unit. Qed.\n  \nLemma mxrank_unit n (A : 'M_n) : A \\in unitmx -> \\rank A = n.\nProof. by rewrite -row_full_unit =>/eqnP. Qed.\n\nLemma mxrank1 n : \\rank (1%:M : 'M_n) = n.\nProof. by apply: mxrank_unit; exact: unitmx1. Qed.\n\nLemma mxrank_delta m n i j : \\rank (delta_mx i j : 'M_(m, n)) = 1%N.\nProof.\napply/eqP; rewrite eqn_leq lt0n mxrank_eq0.\nrewrite -{1}(mul_delta_mx (0 : 'I_1)) mulmx_max_rank.\nby apply/eqP; move/matrixP; move/(_ i j); move/eqP; rewrite !mxE !eqxx oner_eq0.\nQed.\n\nLemma mxrankS m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B.\nProof. by case/submxP=> D ->; rewrite mxrankM_maxr. Qed.\n\nLemma submx1 m n (A : 'M_(m, n)) : (A <= 1%:M)%MS.\nProof. by rewrite submx_full // row_full_unit unitmx1. Qed.\n\nLemma sub1mx m n (A : 'M_(m, n)) : (1%:M <= A)%MS = row_full A.\nProof.\napply/idP/idP; last exact: submx_full.\nby move/mxrankS; rewrite mxrank1 col_leq_rank.\nQed.\n\nLemma ltmx1 m n (A : 'M_(m, n)) : (A < 1%:M)%MS = ~~ row_full A.\nProof. by rewrite /ltmx sub1mx submx1. Qed.\n\nLemma lt1mx m n (A : 'M_(m, n)) : (1%:M < A)%MS = false.\nProof. by rewrite /ltmx submx1 andbF. Qed.\n\nLemma eqmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :=: B)%MS (A == B)%MS.\nProof.\napply: (iffP andP) => [[sAB sBA] | eqAB]; last by rewrite !eqAB.\nsplit=> [|m3 C]; first by apply/eqP; rewrite eqn_leq !mxrankS.\nsplit; first by apply/idP/idP; exact: submx_trans.\nby apply/idP/idP=> sC; exact: submx_trans sC _.\nQed.\nImplicit Arguments eqmxP [m1 m2 n A B].\n\nLemma rV_eqP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall u : 'rV_n, (u <= A) = (u <= B))%MS (A == B)%MS.\nProof.\napply: (iffP idP) => [eqAB u | eqAB]; first by rewrite (eqmxP eqAB).\nby apply/andP; split; apply/rV_subP=> u; rewrite eqAB.\nQed.\n\nLemma eqmx_refl m1 n (A : 'M_(m1, n)) : (A :=: A)%MS.\nProof. by []. Qed.\n\nLemma eqmx_sym m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (B :=: A)%MS.\nProof. by move=> eqAB; split=> [|m3 C]; rewrite !eqAB. Qed.\n\nLemma eqmx_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :=: B)%MS -> (B :=: C)%MS -> (A :=: C)%MS.\nProof. by move=> eqAB eqBC; split=> [|m4 D]; rewrite !eqAB !eqBC. Qed.\n\nLemma eqmx_rank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A == B)%MS -> \\rank A = \\rank B.\nProof. by move/eqmxP->. Qed.\n\nLemma lt_eqmx m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n    (A :=: B)%MS ->\n  forall C : 'M_(m3, n), (((A < C) = (B < C))%MS * ((C < A) = (C < B))%MS)%type.\nProof. by move=> eqAB C; rewrite /ltmx !eqAB. Qed.\n\nLemma eqmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A :=: B)%MS -> (A *m C :=: B *m C)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !submxMr ?eqAB. Qed.\n\nLemma eqmxMfull m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_full A -> (A *m B :=: B)%MS.\nProof.\ncase/row_fullP=> A' A'A; apply/eqmxP; rewrite submxMl /=.\nby apply/submxP; exists A'; rewrite mulmxA A'A mul1mx.\nQed.\n\nLemma eqmx0 m n : ((0 : 'M[F]_(m, n)) :=: (0 : 'M_n))%MS.\nProof. by apply/eqmxP; rewrite !sub0mx. Qed.\n\nLemma eqmx_scale m n a (A : 'M_(m, n)) : a != 0 -> (a *: A :=: A)%MS.\nProof.\nmove=> nz_a; apply/eqmxP; rewrite scalemx_sub //.\nby rewrite -{1}[A]scale1r -(mulVf nz_a) -scalerA scalemx_sub.\nQed.\n\nLemma eqmx_opp m n (A : 'M_(m, n)) : (- A :=: A)%MS.\nProof.\nby rewrite -scaleN1r; apply: eqmx_scale => //; rewrite oppr_eq0 oner_eq0.\nQed.\n\nLemma submxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C <= B *m C)%MS = (A <= B)%MS.\nProof.\ncase/row_freeP=> C' C_C'_1; apply/idP/idP=> sAB; last exact: submxMr.\nby rewrite -[A]mulmx1 -[B]mulmx1 -C_C'_1 !mulmxA submxMr.\nQed.\n\nLemma eqmxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C :=: B *m C)%MS -> (A :=: B)%MS.\nProof.\nby move=> Cfree eqAB; apply/eqmxP; move/eqmxP: eqAB; rewrite !submxMfree.\nQed.\n\nLemma mxrankMfree m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_free B -> \\rank (A *m B) = \\rank A.\nProof.\nby move=> Bfree; rewrite -mxrank_tr trmx_mul eqmxMfull /row_full mxrank_tr.\nQed.\n\nLemma eq_row_base m n (A : 'M_(m, n)) : (row_base A :=: A)%MS.\nProof.\napply/eqmxP; apply/andP; split; apply/submxP.\n  exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n  by rewrite -{8}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\nexists (col_ebase A *m pid_mx (\\rank A)).\nby rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nQed.\n\nLet qidmx_eq1 n (A : 'M_n) : qidmx A = (A == 1%:M).\nProof. by rewrite /qidmx eqxx pid_mx_1. Qed.\n\nLet genmx_witnessP m n (A : 'M_(m, n)) :\n  equivmx A (row_full A) (genmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /genmx_witness.\ncase fullA: (row_full A); first by rewrite eqxx sub1mx submx1 fullA.\nset B := _ *m _; have defB : (B == A)%MS.\n  apply/andP; split; apply/submxP.\n    exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n    by rewrite -{3}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\n  exists (col_ebase A *m pid_mx (\\rank A)).\n  by rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nrewrite defB -negb_add addbF; case: eqP defB => // ->.\nby rewrite sub1mx fullA.\nQed.\n\nLemma genmxE m n (A : 'M_(m, n)) : (<<A>> :=: A)%MS.\nProof.\nby rewrite unlock; apply/eqmxP; case/andP: (chooseP (genmx_witnessP A)).\nQed.\n\nLemma eq_genmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B -> <<A>> = <<B>>)%MS.\nProof.\nmove=> eqAB; rewrite unlock.\nhave{eqAB} eqAB: equivmx A (row_full A) =1 equivmx B (row_full B).\n  by move=> C; rewrite /row_full /equivmx !eqAB.\nrewrite (eq_choose eqAB) (choose_id _ (genmx_witnessP B)) //.\nby rewrite -eqAB genmx_witnessP.\nQed.\n\nLemma genmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (<<A>> = <<B>>)%MS (A == B)%MS.\nProof.\napply: (iffP idP) => eqAB; first exact: eq_genmx (eqmxP _).\nby rewrite -!(genmxE A) eqAB !genmxE andbb.\nQed.\nImplicit Arguments genmxP [m1 m2 n A B].\n\nLemma genmx0 m n : <<0 : 'M_(m, n)>>%MS = 0.\nProof. by apply/eqP; rewrite -submx0 genmxE sub0mx. Qed.\n\nLemma genmx1 n : <<1%:M : 'M_n>>%MS = 1%:M.\nProof.\nrewrite unlock; case/andP: (chooseP (@genmx_witnessP n n 1%:M)) => _ /eqP.\nby rewrite qidmx_eq1 row_full_unit unitmx1 => /eqP.\nQed.\n\nLemma genmx_id m n (A : 'M_(m, n)) : (<<<<A>>>> = <<A>>)%MS.\nProof. by apply: eq_genmx; exact: genmxE. Qed.\n\nLemma row_base_free m n (A : 'M_(m, n)) : row_free (row_base A).\nProof. by apply/eqnP; rewrite eq_row_base. Qed.\n\nLemma mxrank_gen m n (A : 'M_(m, n)) : \\rank <<A>> = \\rank A.\nProof. by rewrite genmxE. Qed.\n\nLemma col_base_full m n (A : 'M_(m, n)) : row_full (col_base A).\nProof.\napply/row_fullP; exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\nby rewrite !mulmxA mulmxKV // pid_mx_id // pid_mx_1.\nQed.\nHint Resolve row_base_free col_base_full.\n\nLemma mxrank_leqif_sup m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (B <= A)%MS.\nProof.\nmove=> sAB; split; first by rewrite mxrankS.\napply/idP/idP=> [| sBA]; last by rewrite eqn_leq !mxrankS.\ncase/submxP: sAB => D ->; rewrite -{-2}(mulmx_base B) mulmxA.\nrewrite mxrankMfree // => /row_fullP[E kE].\nby rewrite -{1}[row_base B]mul1mx -kE -(mulmxA E) (mulmxA _ E) submxMl.\nQed.\n\nLemma mxrank_leqif_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (A == B)%MS.\nProof. by move=> sAB; rewrite sAB; exact: mxrank_leqif_sup. Qed.\n\nLemma ltmxErank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS = (A <= B)%MS && (\\rank A < \\rank B).\nProof.\nby apply: andb_id2l => sAB; rewrite (ltn_leqif (mxrank_leqif_sup sAB)).\nQed.\n\nLemma rank_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS -> \\rank A < \\rank B.\nProof. by rewrite ltmxErank => /andP[]. Qed.\n\nLemma eqmx_cast m1 m2 n (A : 'M_(m1, n)) e :\n  ((castmx e A : 'M_(m2, n)) :=: A)%MS.\nProof. by case: e A; case: m2 / => A e; rewrite castmx_id. Qed.\n\nLemma eqmx_conform m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (conform_mx A B :=: A \\/ conform_mx A B :=: B)%MS.\nProof.\ncase: (eqVneq m2 m1) => [-> | neqm12] in B *.\n  by right; rewrite conform_mx_id.\nby left; rewrite nonconform_mx ?neqm12.\nQed.\n\nLet eqmx_sum_nop m n (A : 'M_(m, n)) : (addsmx_nop A :=: A)%MS.\nProof.\ncase: (eqmx_conform <<A>>%MS A) => // eq_id_gen.\nexact: eqmx_trans (genmxE A).\nQed.\n\nSection AddsmxSub.\n\nVariable (m1 m2 n : nat) (A : 'M[F]_(m1, n)) (B : 'M[F]_(m2, n)).\n\nLemma col_mx_sub m3 (C : 'M_(m3, n)) :\n  (col_mx A B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof.\nrewrite !submxE mul_col_mx -col_mx0.\nby apply/eqP/andP; [case/eq_col_mx=> -> -> | case; do 2!move/eqP->].\nQed.\n\nLemma addsmxE : (A + B :=: col_mx A B)%MS.\nProof.\nhave:= submx_refl (col_mx A B); rewrite col_mx_sub; case/andP=> sAS sBS.\nrewrite unlock; do 2?case: eqP => [AB0 | _]; last exact: genmxE.\n  by apply/eqmxP; rewrite !eqmx_sum_nop sBS col_mx_sub AB0 sub0mx /=.\nby apply/eqmxP; rewrite !eqmx_sum_nop sAS col_mx_sub AB0 sub0mx andbT /=.\nQed.\n\nLemma addsmx_sub m3 (C : 'M_(m3, n)) :\n  (A + B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof. by rewrite addsmxE col_mx_sub. Qed.\n\nLemma addsmxSl : (A <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmxSr : (B <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmx_idPr : reflect (A + B :=: B)%MS (A <= B)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS B.\nby rewrite addsmxSr addsmx_sub submx_refl !andbT.\nQed.\n\nLemma addsmx_idPl : reflect (A + B :=: A)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS A.\nby rewrite addsmxSl addsmx_sub submx_refl !andbT.\nQed.\n\nEnd AddsmxSub.\n\nLemma adds0mx m1 m2 n (B : 'M_(m2, n)) : ((0 : 'M_(m1, n)) + B :=: B)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSr /= andbT. Qed.\n\nLemma addsmx0 m1 m2 n (A : 'M_(m1, n)) : (A + (0 : 'M_(m2, n)) :=: A)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSl /= !andbT. Qed.\n\nLet addsmx_nop_eq0 m n (A : 'M_(m, n)) : (addsmx_nop A == 0) = (A == 0).\nProof. by rewrite -!submx0 eqmx_sum_nop. Qed.\n\nLet addsmx_nop0 m n : addsmx_nop (0 : 'M_(m, n)) = 0.\nProof. by apply/eqP; rewrite addsmx_nop_eq0. Qed.\n\nLet addsmx_nop_id n (A : 'M_n) : addsmx_nop A = A.\nProof. exact: conform_mx_id. Qed.\n\nLemma addsmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A + B = B + A)%MS.\nProof.\nhave: (A + B == B + A)%MS.\n  by apply/andP; rewrite !addsmx_sub andbC -addsmx_sub andbC -addsmx_sub.\nmove/genmxP; rewrite [@addsmx]unlock -!submx0 !submx0.\nby do 2!case: eqP => [// -> | _]; rewrite ?genmx_id ?addsmx_nop0.\nQed.\n\nLemma adds0mx_id m1 n (B : 'M_n) : ((0 : 'M_(m1, n)) + B)%MS = B.\nProof. by rewrite unlock eqxx addsmx_nop_id. Qed.\n\nLemma addsmx0_id m2 n (A : 'M_n) : (A + (0 : 'M_(m2, n)))%MS = A.\nProof. by rewrite addsmxC adds0mx_id. Qed.\n\nLemma addsmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A + (B + C) = A + B + C)%MS.\nProof.\nhave: (A + (B + C) :=: A + B + C)%MS.\n  by apply/eqmxP/andP; rewrite !addsmx_sub -andbA andbA -!addsmx_sub.\nrewrite {1 3}[in @addsmx m1]unlock [in @addsmx n]unlock !addsmx_nop_id -!submx0.\nrewrite !addsmx_sub ![@addsmx]unlock -!submx0; move/eq_genmx.\nby do 3!case: (_ <= 0)%MS; rewrite //= !genmx_id.\nQed.\n\nCanonical addsmx_monoid n :=\n  Monoid.Law (@addsmxA n n n n) (@adds0mx_id n n) (@addsmx0_id n n).\nCanonical addsmx_comoid n := Monoid.ComLaw (@addsmxC n n n).\n\nLemma addsmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A + B)%MS *m C :=: A *m C + B *m C)%MS.\nProof. by apply/eqmxP; rewrite !addsmxE -!mul_col_mx !submxMr ?addsmxE. Qed.\n\nLemma addsmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                            (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A + B <= C + D)%MS.\nProof.\nmove=> sAC sBD.\nby rewrite addsmx_sub {1}addsmxC !(submx_trans _ (addsmxSr _ _)).\nQed.\n\nLemma addmx_sub_adds m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m, n))\n                               (C : 'M_(m1, n)) (D : 'M_(m2, n)) :\n  (A <= C -> B <= D -> (A + B)%R <= C + D)%MS.\nProof.\nmove=> sAC; move/(addsmxS sAC); apply: submx_trans.\nby rewrite addmx_sub ?addsmxSl ?addsmxSr.\nQed.\n\nLemma addsmx_addKl n m1 m2 (A : 'M_(m1, n)) (B C : 'M_(m2, n)) :\n  (B <= A)%MS -> (A + (B + C)%R :=: A + C)%MS.\nProof.\nmove=> sBA; apply/eqmxP; rewrite !addsmx_sub !addsmxSl.\nby rewrite -{3}[C](addKr B) !addmx_sub_adds ?eqmx_opp.\nQed.\n\nLemma addsmx_addKr n m1 m2 (A B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (B <= C)%MS -> ((A + B)%R + C :=: A + C)%MS.\nProof. by rewrite -!(addsmxC C) addrC; exact: addsmx_addKl. Qed.\n\nLemma adds_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                              (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A + B :=: C + D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !addsmxS ?eqAC ?eqBD. Qed.\n\nLemma genmx_adds m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<(A + B)%MS>> = <<A>> + <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (adds_eqmx (genmxE A) (genmxE B))).\nby rewrite [@addsmx]unlock !addsmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\nQed.\n\nLemma sub_addsmxP m1 m2 m3 n\n                  (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  reflect (exists u, A = u.1 *m B + u.2 *m C) (A <= B + C)%MS.\nProof.\napply: (iffP idP) => [|[u ->]]; last by rewrite addmx_sub_adds ?submxMl.\nrewrite addsmxE; case/submxP=> u ->; exists (lsubmx u, rsubmx u).\nby rewrite -mul_row_col hsubmxK.\nQed.\nImplicit Arguments sub_addsmxP [m1 m2 m3 n A B C].\n\nVariable I : finType.\nImplicit Type P : pred I.\n\nLemma genmx_sums P n (B_ : I -> 'M_n) :\n  <<(\\sum_(i | P i) B_ i)%MS>>%MS = (\\sum_(i | P i) <<B_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_adds n n n) (@genmx0 n n)). Qed.\n\nLemma sumsmx_sup i0 P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  P i0 -> (A <= B_ i0)%MS -> (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\nby move=> Pi0 sAB; apply: submx_trans sAB _; rewrite (bigD1 i0) // addsmxSl.\nQed.\nImplicit Arguments sumsmx_sup [P m n A B_].\n\nLemma sumsmx_subP P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  reflect (forall i, P i -> A_ i <= B)%MS (\\sum_(i | P i) A_ i <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: submx_trans sAB; apply: sumsmx_sup Pi _.\nby elim/big_rec: _ => [|i Ai Pi sAiB]; rewrite ?sub0mx // addsmx_sub sAB.\nQed.\n\nLemma summx_sub_sums P m n (A : I -> 'M[F]_(m, n)) B :\n    (forall i, P i -> A i <= B i)%MS ->\n  ((\\sum_(i | P i) A i)%R <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply: summx_sub => i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma sumsmxS P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i <= B i)%MS ->\n  (\\sum_(i | P i) A i <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply/sumsmx_subP=> i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma eqmx_sums P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i :=: B i)%MS ->\n  (\\sum_(i | P i) A i :=: \\sum_(i | P i) B i)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !sumsmxS // => i; move/eqAB->. Qed.\n\nLemma sub_sumsmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (exists u_, A = \\sum_(i | P i) u_ i *m B_ i)\n          (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [| [u_ ->]]; last first.\n  by apply: summx_sub_sums => i _; exact: submxMl. \nelim: {P}_.+1 {-2}P A (ltnSn #|P|) => // b IHb P A.\ncase: (pickP P) => [i Pi | P0 _]; last first.\n  rewrite big_pred0 //; move/submx0null->.\n  by exists (fun _ => 0); rewrite big_pred0.\nrewrite (cardD1x Pi) (bigD1 i) //= => /IHb{b IHb} /= IHi /sub_addsmxP[u ->].\nhave [u_ ->] := IHi _ (submxMl u.2 _).\nexists [eta u_ with i |-> u.1]; rewrite (bigD1 i Pi) /= eqxx; congr (_ + _).\nby apply: eq_bigr => j /andP[_ /negPf->].\nQed.\n\nLemma sumsmxMr_gen P m n A (B : 'M[F]_(m, n)) :\n  ((\\sum_(i | P i) A i)%MS *m B :=: \\sum_(i | P i) <<A i *m B>>)%MS.\nProof.\napply/eqmxP/andP; split; last first.\n  by apply/sumsmx_subP=> i Pi; rewrite genmxE submxMr ?(sumsmx_sup i).\nhave [u ->] := sub_sumsmxP _ _ _ (submx_refl (\\sum_(i | P i) A i)%MS).\nby rewrite mulmx_suml summx_sub_sums // => i _; rewrite genmxE -mulmxA submxMl.\nQed.\n\nLemma sumsmxMr P n (A_ : I -> 'M[F]_n) (B : 'M_n) :\n  ((\\sum_(i | P i) A_ i)%MS *m B :=: \\sum_(i | P i) (A_ i *m B))%MS.\nProof.\nby apply: eqmx_trans (sumsmxMr_gen _ _ _) (eqmx_sums _) => i _; exact: genmxE.\nQed.\n\nLemma rank_pid_mx m n r : r <= m -> r <= n -> \\rank (pid_mx r : 'M_(m, n)) = r.\nProof.\ndo 2!move/subnKC <-; rewrite pid_mx_block block_mxEv row_mx0 -addsmxE addsmx0.\nby rewrite -mxrank_tr tr_row_mx trmx0 trmx1 -addsmxE addsmx0 mxrank1.\nQed.\n\nLemma rank_copid_mx n r : r <= n -> \\rank (copid_mx r : 'M_n) = (n - r)%N.\nProof.\nmove/subnKC <-; rewrite /copid_mx pid_mx_block scalar_mx_block.\nrewrite opp_block_mx !oppr0 add_block_mx !addr0 subrr block_mxEv row_mx0.\nrewrite -addsmxE adds0mx -mxrank_tr tr_row_mx trmx0 trmx1.\nby rewrite -addsmxE adds0mx mxrank1 addKn.\nQed.\n\nLemma mxrank_compl m n (A : 'M_(m, n)) : \\rank A^C = (n - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?rank_copid_mx. Qed.\n\nLemma mxrank_ker m n (A : 'M_(m, n)) : \\rank (kermx A) = (m - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma kermx_eq0 n m (A : 'M_(m, n)) : (kermx A == 0) = row_free A.\nProof. by rewrite -mxrank_eq0 mxrank_ker subn_eq0 row_leq_rank. Qed.\n\nLemma mxrank_coker m n (A : 'M_(m, n)) : \\rank (cokermx A) = (n - \\rank A)%N.\nProof. by rewrite eqmxMfull ?row_full_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma cokermx_eq0 n m (A : 'M_(m, n)) : (cokermx A == 0) = row_full A.\nProof. by rewrite -mxrank_eq0 mxrank_coker subn_eq0 col_leq_rank. Qed.\n\nLemma mulmx_ker m n (A : 'M_(m, n)) : kermx A *m A = 0.\nProof.\nby rewrite -{2}[A]mulmx_ebase !mulmxA mulmxKV // mul_copid_mx_pid ?mul0mx.\nQed.\n\nLemma mulmxKV_ker m n p (A : 'M_(n, p)) (B : 'M_(m, n)) :\n  B *m A = 0 -> B *m col_ebase A *m kermx A = B.\nProof.\nrewrite mulmxA mulmxBr mulmx1 mulmxBl mulmxK //.\nrewrite -{1}[A]mulmx_ebase !mulmxA => /(canRL (mulmxK (row_ebase_unit A))).\nrewrite mul0mx // => BA0; apply: (canLR (addrK _)).\nby rewrite -(pid_mx_id _ _ n (rank_leq_col A)) mulmxA BA0 !mul0mx addr0.\nQed.\n\nLemma sub_kermxP p m n (A : 'M_(m, n)) (B : 'M_(p, m)) :\n  reflect (B *m A = 0) (B <= kermx A)%MS.\nProof.\napply: (iffP submxP) => [[D ->]|]; first by rewrite -mulmxA mulmx_ker mulmx0.\nby move/mulmxKV_ker; exists (B *m col_ebase A).\nQed.\n\nLemma mulmx0_rank_max m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  A *m B = 0 -> \\rank A + \\rank B <= n.\nProof.\nmove=> AB0; rewrite -{3}(subnK (rank_leq_row B)) leq_add2r.\nrewrite -mxrank_ker mxrankS //; exact/sub_kermxP.\nQed.\n\nLemma mxrank_Frobenius m n p q (A : 'M_(m, n)) B (C : 'M_(p, q)) :\n  \\rank (A *m B) + \\rank (B *m C) <= \\rank B + \\rank (A *m B *m C).\nProof.\nrewrite -{2}(mulmx_base (A *m B)) -mulmxA (eqmxMfull _ (col_base_full _)).\nset C2 := row_base _ *m C.\nrewrite -{1}(subnK (rank_leq_row C2)) -(mxrank_ker C2) addnAC leq_add2r. \nrewrite addnC -{1}(mulmx_base B) -mulmxA eqmxMfull //.\nset C1 := _ *m C; rewrite -{2}(subnKC (rank_leq_row C1)) leq_add2l -mxrank_ker.\nrewrite -(mxrankMfree _ (row_base_free (A *m B))).\nhave: (row_base (A *m B) <= row_base B)%MS by rewrite !eq_row_base submxMl.\ncase/submxP=> D defD; rewrite defD mulmxA mxrankMfree ?mxrankS //.\nby apply/sub_kermxP; rewrite -mulmxA (mulmxA D) -defD -/C2 mulmx_ker.\nQed.\n\nLemma mxrank_mul_min m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank A + \\rank B - n <= \\rank (A *m B).\nProof.\nby have:= mxrank_Frobenius A 1%:M B; rewrite mulmx1 mul1mx mxrank1 leq_subLR.\nQed.\n\nLemma addsmx_compl_full m n (A : 'M_(m, n)) : row_full (A + A^C)%MS.\nProof.\nrewrite /row_full addsmxE; apply/row_fullP.\nexists (row_mx (pinvmx A) (cokermx A)); rewrite mul_row_col.\nrewrite -{2}[A]mulmx_ebase -!mulmxA mulKmx // -mulmxDr !mulmxA.\nby rewrite pid_mx_id ?copid_mx_id // -mulmxDl addrC subrK mul1mx mulVmx.\nQed.\n\nLemma sub_capmx_gen m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= capmx_gen B C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof.\napply/idP/andP=> [sAI | [/submxP[B' ->{A}] /submxP[C' eqBC']]].\n  rewrite !(submx_trans sAI) ?submxMl // /capmx_gen.\n   have:= mulmx_ker (col_mx B C); set K := kermx _.\n   rewrite -{1}[K]hsubmxK mul_row_col; move/(canRL (addrK _))->.\n   by rewrite add0r -mulNmx submxMl.\nhave: (row_mx B' (- C') <= kermx (col_mx B C))%MS.\n  by apply/sub_kermxP; rewrite mul_row_col eqBC' mulNmx subrr.\ncase/submxP=> D; rewrite -[kermx _]hsubmxK mul_mx_row.\nby case/eq_row_mx=> -> _; rewrite -mulmxA submxMl.\nQed.\n\nLet capmx_witnessP m n (A : 'M_(m, n)) : equivmx A (qidmx A) (capmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /qidmx /capmx_witness.\nrewrite -sub1mx; case s1A: (1%:M <= A)%MS => /=; last first.\n  rewrite !genmxE submx_refl /= -negb_add; apply: contra {s1A}(negbT s1A).\n  case: eqP => [<- _| _]; first by rewrite genmxE.\n  by case: eqP A => //= -> A; move/eqP->; rewrite pid_mx_1.\ncase: (m =P n) => [-> | ne_mn] in A s1A *.\n  by rewrite conform_mx_id submx_refl pid_mx_1 eqxx.\nby rewrite nonconform_mx ?submx1 ?s1A ?eqxx //; case: eqP.\nQed.\n\nLet capmx_normP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_norm A).\nProof. by case/andP: (chooseP (capmx_witnessP A)) => /eqmxP defN /eqP. Qed.\n\nLet capmx_norm_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A == B)%MS -> capmx_norm A = capmx_norm B.\nProof.\nmove=> eqABid /eqmxP eqAB.\nhave{eqABid eqAB} eqAB: equivmx A (qidmx A) =1 equivmx B (qidmx B).\n  by move=> C; rewrite /equivmx eqABid !eqAB.\nrewrite {1}/capmx_norm (eq_choose eqAB).\nby apply: choose_id; first rewrite -eqAB; exact: capmx_witnessP.\nQed.\n\nLet capmx_nopP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_nop A).\nProof.\nrewrite /capmx_nop; case: (eqVneq m n) => [-> | ne_mn] in A *.\n  by rewrite conform_mx_id.\nrewrite nonconform_mx ?ne_mn //; exact: capmx_normP.\nQed.\n\nLet sub_qidmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx B -> (A <= B)%MS.\nProof.\nrewrite /qidmx => idB; apply: {A}submx_trans (submx1 A) _.\nby case: eqP B idB => [-> _ /eqP-> | _ B]; rewrite (=^~ sub1mx, pid_mx_1).\nQed.\n\nLet qidmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx (A :&: B)%MS = qidmx A && qidmx B.\nProof.\nrewrite unlock -sub1mx.\ncase idA: (qidmx A); case idB: (qidmx B); try by rewrite capmx_nopP.\ncase s1B: (_ <= B)%MS; first by rewrite capmx_normP.\napply/idP=> /(sub_qidmx 1%:M).\nby rewrite capmx_normP sub_capmx_gen s1B andbF.\nQed.\n\nLet capmx_eq_norm m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A :&: B)%MS = capmx_norm (A :&: B)%MS.\nProof.\nmove=> eqABid; rewrite unlock -sub1mx {}eqABid.\nhave norm_id m (C : 'M_(m, n)) (N := capmx_norm C) : capmx_norm N = N.\n  by apply: capmx_norm_eq; rewrite ?capmx_normP ?andbb.\ncase idB: (qidmx B); last by case: ifP; rewrite norm_id.\nrewrite /capmx_nop; case: (eqVneq m2 n) => [-> | neqm2n] in B idB *.\n  have idN := idB; rewrite -{1}capmx_normP !qidmx_eq1 in idN idB.\n  by rewrite conform_mx_id (eqP idN) (eqP idB).\nby rewrite nonconform_mx ?neqm2n ?norm_id.\nQed.\n\nLemma capmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B :=: capmx_gen A B)%MS.\nProof.\nrewrite unlock -sub1mx; apply/eqmxP.\nhave:= submx_refl (capmx_gen A B); rewrite !sub_capmx_gen => /andP[sIA sIB].\ncase idA: (qidmx A); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase idB: (qidmx B); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase s1B: (1%:M <= B)%MS; rewrite !capmx_normP ?sub_capmx_gen sIA ?sIB //=.\nby rewrite submx_refl (submx_trans (submx1 _)).\nQed.\n\nLemma capmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= A)%MS.\nProof. by rewrite capmxE submxMl. Qed.\n\nLemma sub_capmx m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= B :&: C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof. by rewrite capmxE sub_capmx_gen. Qed.\n\nLemma capmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B = B :&: A)%MS.\nProof.\nhave [eqAB|] := eqVneq (qidmx A) (qidmx B).\n  rewrite (capmx_eq_norm eqAB) (capmx_eq_norm (esym eqAB)).\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbC.\n  by apply/andP; split; rewrite !sub_capmx andbC -sub_capmx.\nby rewrite negb_eqb !unlock => /addbP <-; case: (qidmx A).\nQed.\n\nLemma capmxSr m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= B)%MS.\nProof. by rewrite capmxC capmxSl. Qed.\n\nLemma capmx_idPr n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: B)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A :&: B)%MS B.\nby rewrite capmxSr sub_capmx submx_refl !andbT.\nQed.\n\nLemma capmx_idPl n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: A)%MS (A <= B)%MS.\nProof. by rewrite capmxC; exact: capmx_idPr. Qed.\n\nLemma capmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                           (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A :&: B <= C :&: D)%MS.\nProof.\nby move=> sAC sBD; rewrite sub_capmx {1}capmxC !(submx_trans (capmxSr _ _)).\nQed.\n\nLemma cap_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                             (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A :&: B :=: C :&: D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !capmxS ?eqAC ?eqBD. Qed.\n\nLemma capmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A :&: B) *m C <= A *m C :&: B *m C)%MS.\nProof. by rewrite sub_capmx !submxMr ?capmxSl ?capmxSr. Qed.\n\nLemma cap0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) :&: A)%MS = 0.\nProof. exact: submx0null (capmxSl _ _). Qed.\n\nLemma capmx0 m1 m2 n (A : 'M_(m1, n)) : (A :&: (0 : 'M_(m2, n)))%MS = 0.\nProof. exact: submx0null (capmxSr _ _). Qed.\n\nLemma capmxT m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A :&: B :=: A)%MS.\nProof.\nrewrite -sub1mx => s1B; apply/eqmxP.\nby rewrite capmxSl sub_capmx submx_refl (submx_trans (submx1 A)).\nQed.\n\nLemma capTmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full A -> (A :&: B :=: B)%MS.\nProof. by move=> Afull; apply/eqmxP; rewrite capmxC !capmxT ?andbb. Qed.\n\nLet capmx_nop_id n (A : 'M_n) : capmx_nop A = A.\nProof. by rewrite /capmx_nop conform_mx_id. Qed.\n\nLemma cap1mx n (A : 'M_n) : (1%:M :&: A = A)%MS.\nProof. by rewrite unlock qidmx_eq1 eqxx capmx_nop_id. Qed.\n\nLemma capmx1 n (A : 'M_n) : (A :&: 1%:M = A)%MS.\nProof. by rewrite capmxC cap1mx. Qed.\n\nLemma genmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  <<A :&: B>>%MS = (<<A>> :&: <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (cap_eqmx (genmxE A) (genmxE B))).\ncase idAB: (qidmx <<A>> || qidmx <<B>>)%MS.\n  rewrite [@capmx]unlock !capmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\n  by case: (qidmx _) idAB => //= ->.\ncase idA: (qidmx _) idAB => //= idB; rewrite {2}capmx_eq_norm ?idA //.\nset C := (_ :&: _)%MS; have eq_idC: row_full C = qidmx C.\n  rewrite qidmx_cap idA -sub1mx sub_capmx genmxE; apply/andP=> [[s1A]].\n  by case/idP: idA; rewrite qidmx_eq1 -genmx1 (sameP eqP genmxP) submx1.\nrewrite unlock /capmx_norm eq_idC.\nby apply: choose_id (capmx_witnessP _); rewrite -eq_idC genmx_witnessP.\nQed.\n\nLemma capmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :&: (B :&: C) = A :&: B :&: C)%MS.\nProof.\nrewrite (capmxC A B) capmxC; wlog idA: m1 m3 A C / qidmx A.\n  move=> IH; case idA: (qidmx A); first exact: IH.\n  case idC: (qidmx C); first by rewrite -IH.\n  rewrite (@capmx_eq_norm n m3) ?qidmx_cap ?idA ?idC ?andbF //.\n  rewrite capmx_eq_norm ?qidmx_cap ?idA ?idC ?andbF //.\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbAC.\n  by apply/andP; split; rewrite !sub_capmx andbAC -!sub_capmx.\nrewrite -!(capmxC A) [in @capmx m1]unlock idA capmx_nop_id.\nhave [eqBC |] :=eqVneq (qidmx B) (qidmx C).\n  rewrite (@capmx_eq_norm n) ?capmx_nopP // capmx_eq_norm //.\n  by apply: capmx_norm_eq; rewrite ?qidmx_cap ?capmxS ?capmx_nopP.\nby rewrite !unlock capmx_nopP capmx_nop_id; do 2?case: (qidmx _) => //.\nQed.\n\nCanonical capmx_monoid n :=\n   Monoid.Law (@capmxA n n n n) (@cap1mx n) (@capmx1 n).\nCanonical capmx_comoid n := Monoid.ComLaw (@capmxC n n n).\n\nLemma bigcapmx_inf i0 P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  P i0 -> (A_ i0 <= B -> \\bigcap_(i | P i) A_ i <= B)%MS.\nProof. by move=> Pi0; apply: submx_trans; rewrite (bigD1 i0) // capmxSl. Qed.\n\nLemma sub_bigcapmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (forall i, P i -> A <= B_ i)%MS (A <= \\bigcap_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: (submx_trans sAB); rewrite (bigcapmx_inf Pi).\nby elim/big_rec: _ => [|i Pi C sAC]; rewrite ?submx1 // sub_capmx sAB.\nQed.\n\nLemma genmx_bigcap P n (A_ : I -> 'M_n) :\n  (<<\\bigcap_(i | P i) A_ i>> = \\bigcap_(i | P i) <<A_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_cap n n n) (@genmx1 n)). Qed.\n\nLemma matrix_modl m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= C -> A + (B :&: C) :=: (A + B) :&: C)%MS.\nProof.\nmove=> sAC; set D := ((A + B) :&: C)%MS; apply/eqmxP.\nrewrite sub_capmx addsmxS ?capmxSl // addsmx_sub sAC capmxSr /=.\nhave: (D <= B + A)%MS by rewrite addsmxC capmxSl.\ncase/sub_addsmxP=> u defD; rewrite defD addrC addmx_sub_adds ?submxMl //.\nrewrite sub_capmx submxMl -[_ *m B](addrK (u.2 *m A)) -defD.\nby rewrite addmx_sub ?capmxSr // eqmx_opp mulmx_sub.\nQed.\n\nLemma matrix_modr m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (C <= A -> (A :&: B) + C :=: A :&: (B + C))%MS.\nProof. by rewrite !(capmxC A) -!(addsmxC C); exact: matrix_modl. Qed.\n\nLemma capmx_compl m n (A : 'M_(m, n)) : (A :&: A^C)%MS = 0.\nProof.\nset D := (A :&: A^C)%MS; have: (D <= D)%MS by [].\nrewrite sub_capmx andbC => /andP[/submxP[B defB]].\nrewrite submxE => /eqP; rewrite defB -!mulmxA mulKVmx ?copid_mx_id //.\nby rewrite mulmxA => ->; rewrite mul0mx.\nQed.\n\nLemma mxrank_mul_ker m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  (\\rank (A *m B) + \\rank (A :&: kermx B))%N = \\rank A.\nProof.\napply/eqP; set K := kermx B; set C := (A :&: K)%MS.\nrewrite -(eqmxMr B (eq_row_base A)); set K' := _ *m B.\nrewrite -{2}(subnKC (rank_leq_row K')) -mxrank_ker eqn_add2l.\nrewrite -(mxrankMfree _ (row_base_free A)) mxrank_leqif_sup.\n  rewrite sub_capmx -(eq_row_base A) submxMl. \n  by apply/sub_kermxP; rewrite -mulmxA mulmx_ker.\nhave /submxP[C' defC]: (C <= row_base A)%MS by rewrite eq_row_base capmxSl.\nrewrite defC submxMr //; apply/sub_kermxP.\nby rewrite mulmxA -defC; apply/sub_kermxP; rewrite capmxSr.\nQed.\n\nLemma mxrank_injP m n p (A : 'M_(m, n)) (f : 'M_(n, p)) :\n  reflect (\\rank (A *m f) = \\rank A) ((A :&: kermx f)%MS == 0).\nProof.\nrewrite -mxrank_eq0 -(eqn_add2l (\\rank (A *m f))).\nby rewrite mxrank_mul_ker addn0 eq_sym; exact: eqP.\nQed.\n\nLemma mxrank_disjoint_sum m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B)%MS = 0 -> \\rank (A + B)%MS = (\\rank A + \\rank B)%N.\nProof.\nmove=> AB0; pose Ar := row_base A; pose Br := row_base B.\nhave [Afree Bfree]: row_free Ar /\\ row_free Br by rewrite !row_base_free.\nhave: (Ar :&: Br <= A :&: B)%MS by rewrite capmxS ?eq_row_base.\nrewrite {}AB0 submx0 -mxrank_eq0 capmxE mxrankMfree //.\nset Cr := col_mx Ar Br; set Crl := lsubmx _; rewrite mxrank_eq0 => /eqP Crl0.\nrewrite -(adds_eqmx (eq_row_base _) (eq_row_base _)) addsmxE -/Cr.\nsuffices K0: kermx Cr = 0.\n  by apply/eqP; rewrite eqn_leq rank_leq_row -subn_eq0 -mxrank_ker K0 mxrank0.\nmove/eqP: (mulmx_ker Cr); rewrite -[kermx Cr]hsubmxK mul_row_col -/Crl Crl0.\nrewrite mul0mx add0r -mxrank_eq0 mxrankMfree // mxrank_eq0 => /eqP->.\nexact: row_mx0.\nQed.\n\nLemma diffmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B :=: A :&: (capmx_gen A B)^C)%MS.\nProof. by rewrite unlock; apply/eqmxP; rewrite !genmxE !capmxE andbb. Qed.\n\nLemma genmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<A :\\: B>> = A :\\: B)%MS.\nProof. by rewrite [@diffmx]unlock genmx_id. Qed.\n \nLemma diffmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :\\: B <= A)%MS.\nProof. by rewrite diffmxE capmxSl. Qed.\n\nLemma capmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B) :&: B)%MS = 0.\nProof.\napply/eqP; pose C := capmx_gen A B; rewrite -submx0 -(capmx_compl C).\nby rewrite sub_capmx -capmxE sub_capmx andbAC -sub_capmx -diffmxE -sub_capmx.\nQed.\n\nLemma addsmx_diff_cap_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B + A :&: B :=: A)%MS.\nProof.\napply/eqmxP; rewrite addsmx_sub capmxSl diffmxSl /=.\nset C := (A :\\: B)%MS; set D := capmx_gen A B.\nsuffices sACD: (A <= C + D)%MS.\n  by rewrite (submx_trans sACD) ?addsmxS ?capmxE.\nhave:= addsmx_compl_full D; rewrite /row_full addsmxE.\ncase/row_fullP=> U /(congr1 (mulmx A)); rewrite mulmx1.\nrewrite -[U]hsubmxK mul_row_col mulmxDr addrC 2!mulmxA.\nset V := _ *m _ => defA; rewrite -defA; move/(canRL (addrK _)): defA => defV.\nsuffices /submxP[W ->]: (V <= C)%MS by rewrite -mul_row_col addsmxE submxMl.\nrewrite diffmxE sub_capmx {1}defV -mulNmx addmx_sub 1?mulmx_sub //.\nby rewrite -capmxE capmxSl.\nQed.\n\nLemma mxrank_cap_compl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A :&: B) + \\rank (A :\\: B))%N = \\rank A.\nProof.\nrewrite addnC -mxrank_disjoint_sum ?addsmx_diff_cap_eq //.\nby rewrite (capmxC A) capmxA capmx_diff cap0mx.\nQed.\n\nLemma mxrank_sum_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A + B) + \\rank (A :&: B) = \\rank A + \\rank B)%N.\nProof.\nset C := (A :&: B)%MS; set D := (A :\\: B)%MS.\nhave rDB: \\rank (A + B)%MS = \\rank (D + B)%MS.\n  apply/eqP; rewrite mxrank_leqif_sup; first by rewrite addsmxS ?diffmxSl.\n  by rewrite addsmx_sub addsmxSr -(addsmx_diff_cap_eq A B) addsmxS ?capmxSr.\nrewrite {1}rDB mxrank_disjoint_sum ?capmx_diff //.\nby rewrite addnC addnA mxrank_cap_compl.\nQed.\n\nLemma mxrank_adds_leqif m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  \\rank (A + B) <= \\rank A + \\rank B ?= iff (A :&: B <= (0 : 'M_n))%MS.\nProof.\nrewrite -mxrank_sum_cap; split; first exact: leq_addr.\nby rewrite addnC (@eqn_add2r _ 0) eq_sym mxrank_eq0 -submx0.\nQed.\n\n(* Subspace projection matrix *)\n\nLemma proj_mx_sub m n U V (W : 'M_(m, n)) : (W *m proj_mx U V <= U)%MS.\nProof. by rewrite !mulmx_sub // -addsmxE addsmx0. Qed.\n\nLemma proj_mx_compl_sub m n U V (W : 'M_(m, n)) :\n  (W <= U + V -> W - W *m proj_mx U V <= V)%MS.\nProof.\nrewrite addsmxE => sWUV; rewrite mulmxA -{1}(mulmxKpV sWUV) -mulmxBr.\nby rewrite mulmx_sub // opp_col_mx add_col_mx subrr subr0 -addsmxE adds0mx.\nQed.\n\nLemma proj_mx_id m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= U)%MS -> W *m proj_mx U V = W.\nProof.\nmove=> dxUV sWU; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?proj_mx_sub //= -eqmx_opp opprB.\nby rewrite proj_mx_compl_sub // (submx_trans sWU) ?addsmxSl.\nQed. \n\nLemma proj_mx_0 m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= V)%MS -> W *m proj_mx U V = 0.\nProof.\nmove=> dxUV sWV; apply/eqP; rewrite -submx0 -dxUV.\nrewrite sub_capmx proj_mx_sub /= -[_ *m _](subrK W) addmx_sub // -eqmx_opp.\nby rewrite opprB proj_mx_compl_sub // (submx_trans sWV) ?addsmxSr.\nQed.\n\nLemma add_proj_mx m n U V (W : 'M_(m, n)) :\n    (U :&: V = 0)%MS -> (W <= U + V)%MS ->\n  W *m proj_mx U V + W *m proj_mx V U = W.\nProof.\nmove=> dxUV sWUV; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite -addrA sub_capmx {2}addrCA -!(opprB W).\nby rewrite !{1}addmx_sub ?proj_mx_sub ?eqmx_opp ?proj_mx_compl_sub // addsmxC.\nQed.\n\nLemma proj_mx_proj n (U V : 'M_n) :\n  let P := proj_mx U V in (U :&: V = 0)%MS -> P *m P = P.\nProof. by move=> P dxUV; rewrite -{-2}[P]mul1mx proj_mx_id ?proj_mx_sub. Qed.\n\n(* Completing a partially injective matrix to get a unit matrix. *)\n\nLemma complete_unitmx m n (U : 'M_(m, n)) (f : 'M_n) :\n  \\rank (U *m f) = \\rank U -> {g : 'M_n | g \\in unitmx & U *m f = U *m g}.\nProof.\nmove=> injfU; pose V := <<U>>%MS; pose W := V *m f.\npose g := proj_mx V (V^C)%MS *m f + cokermx V *m row_ebase W.\nhave defW: V *m g = W.\n  rewrite mulmxDr mulmxA proj_mx_id ?genmxE ?capmx_compl //.\n  by rewrite mulmxA mulmx_coker mul0mx addr0.\nexists g; last first.\n  have /submxP[u ->]: (U <= V)%MS by rewrite genmxE.\n  by rewrite -!mulmxA defW.\nrewrite -row_full_unit -sub1mx; apply/submxP.\nhave: (invmx (col_ebase W) *m W <= V *m g)%MS by rewrite defW submxMl.\ncase/submxP=> v def_v; exists (invmx (row_ebase W) *m (v *m V + (V^C)%MS)).\nrewrite -mulmxA mulmxDl -mulmxA -def_v -{3}[W]mulmx_ebase -mulmxA.\nrewrite mulKmx ?col_ebase_unit // [_ *m g]mulmxDr mulmxA.\nrewrite (proj_mx_0 (capmx_compl _)) // mul0mx add0r 2!mulmxA.\nrewrite mulmxK ?row_ebase_unit // copid_mx_id ?rank_leq_row //.\nrewrite (eqmxMr _ (genmxE U)) injfU genmxE addrC -mulmxDl subrK.\nby rewrite mul1mx mulVmx ?row_ebase_unit.\nQed.\n\n(* Mapping between two subspaces with the same dimension. *)\n\nLemma eq_rank_unitmx m1 m2 n (U : 'M_(m1, n)) (V : 'M_(m2, n)) :\n  \\rank U = \\rank V -> {f : 'M_n | f \\in unitmx & V :=: U *m f}%MS.\nProof.\nmove=> eqrUV; pose f := invmx (row_ebase <<U>>%MS) *m row_ebase <<V>>%MS.\nhave defUf: (<<U>> *m f :=: <<V>>)%MS.\n  rewrite -[<<U>>%MS]mulmx_ebase mulmxA mulmxK ?row_ebase_unit // -mulmxA.\n  rewrite genmxE eqrUV -genmxE -{3}[<<V>>%MS]mulmx_ebase -mulmxA.\n  move: (pid_mx _ *m _) => W; apply/eqmxP.\n  by rewrite !eqmxMfull ?andbb // row_full_unit col_ebase_unit.\nhave{defUf} defV: (V :=: U *m f)%MS.\n  by apply/eqmxP; rewrite -!(eqmxMr f (genmxE U)) !defUf !genmxE andbb.\nhave injfU: \\rank (U *m f) = \\rank U by rewrite -defV eqrUV.\nby have [g injg defUg] := complete_unitmx injfU; exists g; rewrite -?defUg.\nQed.\n\nSection SumExpr.\n\n(* This is the infrastructure to support the mxdirect predicate. We use a     *)\n(* bespoke canonical structure to decompose a matrix expression into binary   *)\n(* and n-ary products, using some of the \"quote\" technology. This lets us     *)\n(* characterize direct sums as set sums whose rank is equal to the sum of the *)\n(* ranks of the individual terms. The mxsum_expr/proper_mxsum_expr structures *)\n(* below supply both the decomposition and the calculation of the rank sum.   *)\n(* The mxsum_spec dependent predicate family expresses the consistency of     *)\n(* these two decompositions.                                                  *)\n(*   The main technical difficulty we need to overcome is the fact that       *)\n(* the \"catch-all\" case of canonical structures has a priority lower than     *)\n(* constant expansion. However, it is undesireable that local abbreviations   *)\n(* be opaque for the direct-sum predicate, e.g., not be able to handle        *)\n(* let S := (\\sum_(i | P i) LargeExpression i)%MS in mxdirect S -> ...).      *)\n(*   As in \"quote\", we use the interleaving of constant expansion and         *)\n(* canonical projection matching to achieve our goal: we use a \"wrapper\" type *)\n(* (indeed, the wrapped T type defined in ssrfun.v) with a self-inserting     *)\n(* non-primitive constructor to gain finer control over the type and          *)\n(* structure inference process. The innermost, primitive, constructor flags   *)\n(* trivial sums; it is initially hidden by an eta-expansion, which has been   *)\n(* made into a (default) canonical structure -- this lets type inference      *)\n(* automatically insert this outer tag.                                       *)\n(*   In detail, we define three types                                         *)\n(*  mxsum_spec S r <-> There exists a finite list of matrices A1, ..., Ak     *)\n(*                     such that S is the set sum of the Ai, and r is the sum *)\n(*                     of the ranks of the Ai, i.e., S = (A1 + ... + Ak)%MS   *)\n(*                     and r = \\rank A1 + ... + \\rank Ak. Note that           *)\n(*                     mxsum_spec is a recursive dependent predicate family   *)\n(*                     whose elimination rewrites simultaneaously S, r and    *)\n(*                     the height of S.                                       *)\n(*   proper_mxsum_expr n == The interface for proper sum expressions; this is *)\n(*                     a double-entry interface, keyed on both the matrix sum *)\n(*                     value and the rank sum. The matrix value is restricted *)\n(*                     to square matrices, as the \"+\"%MS operator always      *)\n(*                     returns a square matrix. This interface has two        *)\n(*                     canonical insances, for binary and n-ary sums.         *)\n(*   mxsum_expr m n == The interface for general sum expressions, comprising  *)\n(*                     both proper sums and trivial sums consisting of a      *)\n(*                     single matrix. The key values are WRAPPED as this lets *)\n(*                     us give priority to the \"proper sum\" interpretation    *)\n(*                     (see below). To allow for trivial sums, the matrix key *)\n(*                     can have any dimension. The mxsum_expr interface has   *)\n(*                     two canonical instances, for trivial and proper sums,  *)\n(*                     keyed to the Wrap and wrap constructors, respectively. *)\n(* The projections for the two interfaces above are                           *)\n(*   proper_mxsum_val, mxsum_val : these are respectively coercions to 'M_n   *)\n(*                     and wrapped 'M_(m, n); thus, the matrix sum for an     *)\n(*                     S : mxsum_expr m n can be written unwrap S.            *)\n(*   proper_mxsum_rank, mxsum_rank : projections to the nat and wrapped nat,  *)\n(*                     respectively; the rank sum for S : mxsum_expr m n is   *)\n(*                     thus written unwrap (mxsum_rank S).                    *)\n(* The mxdirect A predicate actually gets A in a phantom argument, which is   *)\n(* used to infer an (implicit) S : mxsum_expr such that unwrap S = A; the     *)\n(* actual definition is \\rank (unwrap S) == unwrap (mxsum_rank S).            *)\n(*   Note that the inference of S is inherently ambiguous: ANY matrix can be  *)\n(* viewed as a trivial sum, including one whose description is manifestly a   *)\n(* proper sum. We use the wrapped type and the interaction between delta      *)\n(* reduction and canonical structure inference to resolve this ambiguity in   *)\n(* favor of proper sums, as follows:                                          *)\n(*    - The phantom type sets up a unification problem of the form            *)\n(*         unwrap (mxsum_val ?S) = A                                          *)\n(*      with unknown evar ?S : mxsum_expr m n.                                *)\n(*    - As the constructor wrap is also a default Canonical instance for the  *)\n(*      wrapped type, so A is immediately replaced with unwrap (wrap A) and   *)\n(*      we get the residual unification problem                               *)\n(*         mxsum_val ?S = wrap A                                              *)\n(*    - Now Coq tries to apply the proper sum Canonical instance, which has   *)\n(*      key projection wrap (proper_mxsum_val ?PS) where ?PS is a fresh evar  *)\n(*      (of type proper_mxsum_expr n). This can only succeed if m = n, and if *)\n(*      a solution can be found to the recursive unification problem          *)\n(*         proper_mxsum_val ?PS = A                                           *)\n(*      This causes Coq to look for one of the two canonical constants for    *)\n(*      proper_mxsum_val (addsmx or bigop) at the head of A, delta-expanding  *)\n(*      A as needed, and then inferring recursively mxsum_expr structures for *)\n(*      the last argument(s) of that constant.                                *)\n(*    - If the above step fails then the wrap constant is expanded, revealing *)\n(*      the primitive Wrap constructor; the unification problem now becomes   *)\n(*         mxsum_val ?S = Wrap A                                              *)\n(*      which fits perfectly the trivial sum canonical structure, whose key   *)\n(*      projection is Wrap ?B where ?B is a fresh evar. Thus the inference    *)\n(*      succeeds, and returns the trivial sum.                                *)\n(* Note that the rank projections also register canonical values, so that the *)\n(* same process can be used to infer a sum structure from the rank sum. In    *)\n(* that case, however, there is no ambiguity and the inference can fail,      *)\n(* because the rank sum for a trivial sum is not an arbitrary integer -- it   *)\n(* must be of the form \\rank ?B. It is nevertheless necessary to use the      *)\n(* wrapped nat type for the rank sums, because in the non-trivial case the    *)\n(* head constant of the nat expression is determined by the proper_mxsum_expr *)\n(* canonical structure, so the mxsum_expr structure must use a generic        *)\n(* constant, namely wrap.                                                     *)\n\nInductive mxsum_spec n : forall m, 'M[F]_(m, n) -> nat -> Prop :=\n | TrivialMxsum m A\n    : @mxsum_spec n m A (\\rank A)\n | ProperMxsum m1 m2 T1 T2 r1 r2 of\n      @mxsum_spec n m1 T1 r1 & @mxsum_spec n m2 T2 r2\n    : mxsum_spec (T1 + T2)%MS (r1 + r2)%N.\nArguments Scope mxsum_spec [nat_scope nat_scope matrix_set_scope nat_scope].\n\nStructure mxsum_expr m n := Mxsum {\n  mxsum_val :> wrapped 'M_(m, n);\n  mxsum_rank : wrapped nat;\n  _ : mxsum_spec (unwrap mxsum_val) (unwrap mxsum_rank)\n}.\n\nCanonical trivial_mxsum m n A :=\n  @Mxsum m n (Wrap A) (Wrap (\\rank A)) (TrivialMxsum A).\n\nStructure proper_mxsum_expr n := ProperMxsumExpr {\n  proper_mxsum_val :> 'M_n;\n  proper_mxsum_rank : nat;\n  _ : mxsum_spec proper_mxsum_val proper_mxsum_rank\n}.\n\nDefinition proper_mxsumP n (S : proper_mxsum_expr n) :=\n  let: ProperMxsumExpr _ _ termS := S return mxsum_spec S (proper_mxsum_rank S)\n  in termS.\n\nCanonical sum_mxsum n (S : proper_mxsum_expr n) :=\n  @Mxsum n n (wrap (S : 'M_n)) (wrap (proper_mxsum_rank S)) (proper_mxsumP S).\n\nSection Binary.\nVariable (m1 m2 n : nat) (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n).\nFact binary_mxsum_proof :\n  mxsum_spec (unwrap S1 + unwrap S2)\n             (unwrap (mxsum_rank S1) + unwrap (mxsum_rank S2)).\nProof. by case: S1 S2 => [A1 r1 A1P] [A2 r2 A2P]; right. Qed.\nCanonical binary_mxsum_expr := ProperMxsumExpr binary_mxsum_proof.\nEnd Binary.\n\nSection Nary.\nContext J (r : seq J) (P : pred J) n (S_ : J -> mxsum_expr n n).\nFact nary_mxsum_proof :\n  mxsum_spec (\\sum_(j <- r | P j) unwrap (S_ j))\n             (\\sum_(j <- r | P j) unwrap (mxsum_rank (S_ j))).\nProof.\nelim/big_rec2: _ => [|j]; first by rewrite -(mxrank0 n n); left.\nby case: (S_ j); right.\nQed.\nCanonical nary_mxsum_expr := ProperMxsumExpr nary_mxsum_proof.\nEnd Nary.\n\nDefinition mxdirect_def m n T of phantom 'M_(m, n) (unwrap (mxsum_val T)) :=\n  \\rank (unwrap T) == unwrap (mxsum_rank T).\n\nEnd SumExpr.\n\nNotation mxdirect A := (mxdirect_def (Phantom 'M_(_,_) A%MS)).\n\nLemma mxdirectP n (S : proper_mxsum_expr n) :\n  reflect (\\rank S = proper_mxsum_rank S) (mxdirect S).\nProof. exact: eqnP. Qed.\nImplicit Arguments mxdirectP [n S].\n\nLemma mxdirect_trivial m n A : mxdirect (unwrap (@trivial_mxsum m n A)).\nProof. exact: eqxx. Qed.\n\nLemma mxrank_sum_leqif m n (S : mxsum_expr m n) :\n  \\rank (unwrap S) <= unwrap (mxsum_rank S) ?= iff mxdirect (unwrap S).\nProof.\nrewrite /mxdirect_def; case: S => [[A] [r] /= defAr]; split=> //=.\nelim: m A r / defAr => // m1 m2 A1 A2 r1 r2 _ leAr1 _ leAr2.\nby apply: leq_trans (leq_add leAr1 leAr2); rewrite mxrank_adds_leqif.\nQed.\n\nLemma mxdirectE m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) == unwrap (mxsum_rank S)).\nProof. by []. Qed.\n\nLemma mxdirectEgeq m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) >= unwrap (mxsum_rank S)).\nProof. by rewrite (geq_leqif (mxrank_sum_leqif S)). Qed.\n\nSection BinaryDirect.\n\nVariables m1 m2 n : nat.\n\nLemma mxdirect_addsE (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n) :\n   mxdirect (unwrap S1 + unwrap S2)\n    = [&& mxdirect (unwrap S1), mxdirect (unwrap S2)\n        & unwrap S1 :&: unwrap S2 == 0]%MS.\nProof.\nrewrite (@mxdirectE n) /=.\nhave:= leqif_add (mxrank_sum_leqif S1) (mxrank_sum_leqif S2).\nmove/(leqif_trans (mxrank_adds_leqif (unwrap S1) (unwrap S2)))=> ->.\nby rewrite andbC -andbA submx0.\nQed.\n\nLemma mxdirect_addsP (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B = 0)%MS (mxdirect (A + B)).\nProof. by rewrite mxdirect_addsE !mxdirect_trivial; exact: eqP. Qed.\n\nEnd BinaryDirect.\n\nSection NaryDirect.\n\nVariables (P : pred I) (n : nat).\n\nLet TIsum A_ i := (A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0 :> 'M_n)%MS.\n\nLet mxdirect_sums_recP (S_ : I -> mxsum_expr n n) :\n  reflect (forall i, P i -> mxdirect (unwrap (S_ i)) /\\ TIsum (unwrap \\o S_) i)\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\nrewrite /TIsum; apply: (iffP eqnP) => /= [dxS i Pi | dxS].\n  set Si' := (\\sum_(j | _) unwrap (S_ j))%MS.\n  have: mxdirect (unwrap (S_ i) + Si') by apply/eqnP; rewrite /= -!(bigD1 i).\n  by rewrite mxdirect_addsE => /and3P[-> _ /eqP].  \nelim: _.+1 {-2 4}P (subxx P) (ltnSn #|P|) => // m IHm Q; move/subsetP=> sQP.\ncase: (pickP Q) => [i Qi | Q0]; last by rewrite !big_pred0 ?mxrank0.\nrewrite (cardD1x Qi) !((bigD1 i) Q) //=.\nmove/IHm=> <- {IHm}/=; last by apply/subsetP=> j /andP[/sQP].\ncase: (dxS i (sQP i Qi)) => /eqnP=> <- TiQ_0; rewrite mxrank_disjoint_sum //.\napply/eqP; rewrite -submx0 -{2}TiQ_0 capmxS //=.\nby apply/sumsmx_subP=> j /= /andP[Qj i'j]; rewrite (sumsmx_sup j) ?[P j]sQP.\nQed.\n\nLemma mxdirect_sumsP (A_ : I -> 'M_n) :\n  reflect (forall i, P i -> A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0)%MS\n          (mxdirect (\\sum_(i | P i) A_ i)).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => dxA i /dxA; first by case.\nby rewrite mxdirect_trivial.\nQed.\n\nLemma mxdirect_sumsE (S_ : I -> mxsum_expr n n) (xunwrap := unwrap) :\n  reflect (and (forall i, P i -> mxdirect (unwrap (S_ i)))\n               (mxdirect (\\sum_(i | P i) (xunwrap (S_ i)))))\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => [dxS | [dxS_ dxS] i Pi].\n  by do [split; last apply/mxdirect_sumsP] => i; case/dxS.\nby split; [exact: dxS_ | exact: mxdirect_sumsP Pi].\nQed.\n\nEnd NaryDirect.\n\nSection SubDaddsmx.\n\nVariables m m1 m2 n : nat.\nVariables (A : 'M[F]_(m, n)) (B1 : 'M[F]_(m1, n)) (B2 : 'M[F]_(m2, n)).\n\nCoInductive sub_daddsmx_spec : Prop :=\n  SubDaddsmxSpec A1 A2 of (A1 <= B1)%MS & (A2 <= B2)%MS & A = A1 + A2\n                        & forall C1 C2, (C1 <= B1)%MS -> (C2 <= B2)%MS ->\n                          A = C1 + C2 -> C1 = A1 /\\ C2 = A2.\n\nLemma sub_daddsmx : (B1 :&: B2 = 0)%MS -> (A <= B1 + B2)%MS -> sub_daddsmx_spec.\nProof.\nmove=> dxB /sub_addsmxP[u defA].\nexists (u.1 *m B1) (u.2 *m B2); rewrite ?submxMl // => C1 C2 sCB1 sCB2.\nmove/(canLR (addrK _)) => defC1.\nsuffices: (C2 - u.2 *m B2 <= B1 :&: B2)%MS.\n  by rewrite dxB submx0 subr_eq0 -defC1 defA; move/eqP->; rewrite addrK.\nrewrite sub_capmx -opprB -{1}(canLR (addKr _) defA) -addrA defC1.\nby rewrite !(eqmx_opp, addmx_sub) ?submxMl.\nQed.\n\nEnd SubDaddsmx.\n\nSection SubDsumsmx.\n\nVariables (P : pred I) (m n : nat) (A : 'M[F]_(m, n)) (B : I -> 'M[F]_n).\n\nCoInductive sub_dsumsmx_spec : Prop :=\n  SubDsumsmxSpec A_ of forall i, P i -> (A_ i <= B i)%MS\n                        & A = \\sum_(i | P i) A_ i\n                        & forall C, (forall i, P i -> C i <= B i)%MS ->\n                          A = \\sum_(i | P i) C i -> {in SimplPred P, C =1 A_}.\n\nLemma sub_dsumsmx :\n    mxdirect (\\sum_(i | P i) B i) -> (A <= \\sum_(i | P i) B i)%MS ->\n  sub_dsumsmx_spec.\nProof.\nmove/mxdirect_sumsP=> dxB /sub_sumsmxP[u defA].\npose A_ i := u i *m B i.\nexists A_ => //= [i _ | C sCB defAC i Pi]; first exact: submxMl.\napply/eqP; rewrite -subr_eq0 -submx0 -{dxB}(dxB i Pi) /=.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?submxMl ?sCB //=.\nrewrite -(subrK A (C i)) -addrA -opprB addmx_sub ?eqmx_opp //.\n  rewrite addrC defAC (bigD1 i) // addKr /= summx_sub // => j Pi'j.\n  by rewrite (sumsmx_sup j) ?sCB //; case/andP: Pi'j.\nrewrite addrC defA (bigD1 i) // addKr /= summx_sub // => j Pi'j.\nby rewrite (sumsmx_sup j) ?submxMl.\nQed.\n\nEnd SubDsumsmx.\n\nSection Eigenspace.\n\nVariables (n : nat) (g : 'M_n).\n\nDefinition eigenspace a := kermx (g - a%:M).\nDefinition eigenvalue : pred F := fun a => eigenspace a != 0.\n\nLemma eigenspaceP a m (W : 'M_(m, n)) :\n  reflect (W *m g = a *: W) (W <= eigenspace a)%MS.\nProof.\nrewrite (sameP (sub_kermxP _ _) eqP).\nby rewrite mulmxBr subr_eq0 mul_mx_scalar; exact: eqP.\nQed.\n\nLemma eigenvalueP a :\n  reflect (exists2 v : 'rV_n, v *m g = a *: v & v != 0) (eigenvalue a).\nProof. by apply: (iffP (rowV0Pn _)) => [] [v]; move/eigenspaceP; exists v. Qed.\n\nLemma mxdirect_sum_eigenspace (P : pred I) a_ :\n  {in P &, injective a_} -> mxdirect (\\sum_(i | P i) eigenspace (a_ i)).\nProof.\nelim: {P}_.+1 {-2}P (ltnSn #|P|) => // m IHm P lePm inj_a.\napply/mxdirect_sumsP=> i Pi; apply/eqP/rowV0P => v.\nrewrite sub_capmx => /andP[/eigenspaceP def_vg].\nset Vi' := (\\sum_(i | _) _)%MS => Vi'v.\nhave dxVi': mxdirect Vi'.\n  rewrite (cardD1x Pi) in lePm; apply: IHm => //.\n  by apply: sub_in2 inj_a => j /andP[].\ncase/sub_dsumsmx: Vi'v => // u Vi'u def_v _.\nrewrite def_v big1 // => j Pi'j; apply/eqP.\nhave nz_aij: a_ i - a_ j != 0.\n  by case/andP: Pi'j => Pj ne_ji; rewrite subr_eq0 eq_sym (inj_in_eq inj_a).\ncase: (sub_dsumsmx dxVi' (sub0mx 1 _)) => C _ _ uniqC.\nrewrite -(eqmx_eq0 (eqmx_scale _ nz_aij)).\nrewrite (uniqC (fun k => (a_ i - a_ k) *: u k)) => // [|k Pi'k|].\n- by rewrite -(uniqC (fun _ => 0)) ?big1 // => k Pi'k; exact: sub0mx.\n- by rewrite scalemx_sub ?Vi'u.\nrewrite -{1}(subrr (v *m g)) {1}def_vg def_v scaler_sumr mulmx_suml -sumrB.\nby apply: eq_bigr => k /Vi'u/eigenspaceP->; rewrite scalerBl.\nQed.\n\nEnd Eigenspace.\n\nEnd RowSpaceTheory.\n\nHint Resolve submx_refl.\nImplicit Arguments submxP [F m1 m2 n A B].\nImplicit Arguments eq_row_sub [F m n v A].\nImplicit Arguments row_subP [F m1 m2 n A B].\nImplicit Arguments rV_subP [F m1 m2 n A B].\nImplicit Arguments row_subPn [F m1 m2 n A B].\nImplicit Arguments sub_rVP [F n u v].\nImplicit Arguments rV_eqP [F m1 m2 n A B].\nImplicit Arguments rowV0Pn [F m n A].\nImplicit Arguments rowV0P [F m n A].\nImplicit Arguments eqmx0P [F m n A].\nImplicit Arguments row_fullP [F m n A].\nImplicit Arguments row_freeP [F m n A].\nImplicit Arguments eqmxP [F m1 m2 n A B].\nImplicit Arguments genmxP [F m1 m2 n A B].\nImplicit Arguments addsmx_idPr [F m1 m2 n A B].\nImplicit Arguments addsmx_idPl [F m1 m2 n A B].\nImplicit Arguments sub_addsmxP [F m1 m2 m3 n A B C].\nImplicit Arguments sumsmx_sup [F I P m n A B_].\nImplicit Arguments sumsmx_subP [F I P m n A_ B].\nImplicit Arguments sub_sumsmxP [F I P m n A B_].\nImplicit Arguments sub_kermxP [F p m n A B].\nImplicit Arguments capmx_idPr [F m1 m2 n A B].\nImplicit Arguments capmx_idPl [F m1 m2 n A B].\nImplicit Arguments bigcapmx_inf [F I P m n A_ B].\nImplicit Arguments sub_bigcapmxP [F I P m n A B_].\nImplicit Arguments mxrank_injP [F m n A f].\nImplicit Arguments mxdirectP [F n S].\nImplicit Arguments mxdirect_addsP [F m1 m2 n A B].\nImplicit Arguments mxdirect_sumsP [F I P n A_].\nImplicit Arguments mxdirect_sumsE [F I P n S_].\nImplicit Arguments eigenspaceP [F n g a m W].\nImplicit Arguments eigenvalueP [F n g a].\n\nArguments Scope mxrank [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope complmx [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope row_full [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope submx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope ltmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope eqmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope addsmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope capmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope diffmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits mxrank genmx complmx submx ltmx addsmx capmx.\nNotation \"\\rank A\" := (mxrank A) : nat_scope.\nNotation \"<< A >>\" := (genmx A) : matrix_set_scope.\nNotation \"A ^C\" := (complmx A) : matrix_set_scope.\nNotation \"A <= B\" := (submx A B) : matrix_set_scope.\nNotation \"A < B\" := (ltmx A B) : matrix_set_scope.\nNotation \"A <= B <= C\" := ((submx A B) && (submx B C)) : matrix_set_scope.\nNotation \"A < B <= C\" := (ltmx A B && submx B C) : matrix_set_scope.\nNotation \"A <= B < C\" := (submx A B && ltmx B C) : matrix_set_scope.\nNotation \"A < B < C\" := (ltmx A B && ltmx B C) : matrix_set_scope.\nNotation \"A == B\" := ((submx A B) && (submx B A)) : matrix_set_scope.\nNotation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\nNotation \"A + B\" := (addsmx A B) : matrix_set_scope.\nNotation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nNotation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\nNotation mxdirect S := (mxdirect_def (Phantom 'M_(_,_) S%MS)).\n\nNotation \"\\sum_ ( <- r | P ) B\" :=\n  (\\big[addsmx/0%R]_(<- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r | P ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i | P ) B\" :=\n  (\\big[addsmx/0%R]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ i B\" :=\n  (\\big[addsmx/0%R]_i B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i : t | P ) B\" :=\n  (\\big[addsmx/0%R]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i : t ) B\" :=\n  (\\big[addsmx/0%R]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i < n ) B\" :=\n  (\\big[addsmx/0%R]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A | P ) B\" :=\n  (\\big[addsmx/0%R]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A ) B\" :=\n  (\\big[addsmx/0%R]_(i in A) B%MS) : matrix_set_scope.\n\nNotation \"\\bigcap_ ( <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(<- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i | P ) B\" :=\n  (\\big[capmx/1%:M]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ i B\" :=\n  (\\big[capmx/1%:M]_i B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t | P ) B\" :=\n  (\\big[capmx/1%:M]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t ) B\" :=\n  (\\big[capmx/1%:M]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n ) B\" :=\n  (\\big[capmx/1%:M]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A | P ) B\" :=\n  (\\big[capmx/1%:M]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A ) B\" :=\n  (\\big[capmx/1%:M]_(i in A) B%MS) : matrix_set_scope.\n\nSection CardGL.\n\nVariable F : finFieldType.\n\nLemma card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite big_nat_rev big_add1 -triangular_sum expn_sum -big_split /=.\npose fr m := [pred A : 'M[F]_(m, n) | \\rank A == m].\nset m := {-7}n; transitivity #|fr m|.\n  by rewrite cardsT /= card_sub; apply: eq_card => A; rewrite -row_free_unit.\nelim: m (leqnn m : m <= n) => [_|m IHm]; last move/ltnW=> le_mn.\n  rewrite (@eq_card1 _ (0 : 'M_(0, n))) ?big_geq //= => A.\n  by rewrite flatmx0 !inE !eqxx.\nrewrite big_nat_recr -{}IHm //= !subSS mulnBr muln1 -expnD subnKC //.\nrewrite -sum_nat_const /= -sum1_card -add1n.\nrewrite (partition_big dsubmx (fr m)) /= => [|A]; last first.\n  rewrite !inE -{1}(vsubmxK A); move: {A}(_ A) (_ A) => Ad Au Afull.\n  rewrite eqn_leq rank_leq_row -(leq_add2l (\\rank Au)) -mxrank_sum_cap.\n  rewrite {1 3}[@mxrank]lock addsmxE (eqnP Afull) -lock -addnA.\n  by rewrite leq_add ?rank_leq_row ?leq_addr.\napply: eq_bigr => A rAm; rewrite (reindex (col_mx^~ A)) /=; last first.\n  exists usubmx => [v _ | vA]; first by rewrite col_mxKu.\n  by case/andP=> _ /eqP <-; rewrite vsubmxK.\ntransitivity #|~: [set v *m A | v in 'rV_m]|; last first.\n  rewrite cardsCs setCK card_imset ?card_matrix ?card_ord ?mul1n //.\n  have [B AB1] := row_freeP rAm; apply: can_inj (mulmx^~ B) _ => v.\n  by rewrite -mulmxA AB1 mulmx1.\nrewrite -sum1_card; apply: eq_bigl => v; rewrite !inE col_mxKd eqxx.\nrewrite andbT eqn_leq rank_leq_row /= -(leq_add2r (\\rank (v :&: A)%MS)).\nrewrite -addsmxE mxrank_sum_cap (eqnP rAm) addnAC leq_add2r.\nrewrite (ltn_leqif (mxrank_leqif_sup _)) ?capmxSl // sub_capmx submx_refl.\nby congr (~~ _); apply/submxP/imsetP=> [] [u]; exists u.\nQed.\n\n(* An alternate, somewhat more elementary proof, that does not rely on the *)\n(* row-space theory, but directly performs the LUP decomposition.          *)\nLemma LUP_card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite cardsT /= card_sub /GRing.unit /= big_add1 /= -triangular_sum -/n.\nelim: {n'}n => [|n IHn].\n  rewrite !big_geq // mul1n (@eq_card _ _ predT) ?card_matrix //= => M.\n  by rewrite {1}[M]flatmx0 -(flatmx0 1%:M) unitmx1.\nrewrite !big_nat_recr /= expnD mulnAC mulnA -{}IHn -mulnA mulnC.\nset LHS := #|_|; rewrite -[n.+1]muln1 -{2}[n]mul1n {}/LHS.\nrewrite -!card_matrix subn1 -(cardC1 0) -mulnA; set nzC := predC1 _.\nrewrite -sum1_card (partition_big lsubmx nzC) => [|A]; last first.\n  rewrite unitmxE unitfE; apply: contra; move/eqP=> v0.\n  rewrite -[A]hsubmxK v0 -[n.+1]/(1 + n)%N -col_mx0.\n  rewrite -[rsubmx _]vsubmxK -det_tr tr_row_mx !tr_col_mx !trmx0.\n  by rewrite det_lblock [0]mx11_scalar det_scalar1 mxE mul0r.\nrewrite -sum_nat_const; apply: eq_bigr; rewrite /= -[n.+1]/(1 + n)%N => v nzv.\ncase: (pickP (fun i => v i 0 != 0)) => [k nza | v0]; last first.\n  by case/eqP: nzv; apply/colP=> i; move/eqP: (v0 i); rewrite mxE.\nhave xrkK: involutive (@xrow F _ _ 0 k).\n  by move=> m A /=; rewrite /xrow -row_permM tperm2 row_perm1.\nrewrite (reindex_inj (inv_inj (xrkK (1 + n)%N))) /= -[n.+1]/(1 + n)%N.\nrewrite (partition_big ursubmx xpredT) //= -sum_nat_const.\napply: eq_bigr => u _; set a : F := v _ _ in nza.\nset v1 : 'cV_(1 + n) := xrow 0 k v.\nhave def_a: usubmx v1 = a%:M.\n  by rewrite [_ v1]mx11_scalar mxE lshift0 mxE tpermL.\npose Schur := dsubmx v1 *m (a^-1 *: u).\npose L : 'M_(1 + n) := block_mx a%:M 0 (dsubmx v1) 1%:M.\npose U B : 'M_(1 + n) := block_mx 1 (a^-1 *: u) 0 B.\nrewrite (reindex (fun B => L *m U B)); last first.\n  exists (fun A1 => drsubmx A1 - Schur) => [B _ | A1].\n    by rewrite mulmx_block block_mxKdr mul1mx addrC addKr.\n  rewrite !inE mulmx_block !mulmx0 mul0mx !mulmx1 !addr0 mul1mx addrC subrK.\n  rewrite mul_scalar_mx scalerA divff // scale1r andbC; case/and3P => /eqP <- _.\n  rewrite -{1}(hsubmxK A1) xrowE mul_mx_row row_mxKl -xrowE => /eqP def_v.\n  rewrite -def_a block_mxEh vsubmxK /v1 -def_v xrkK.\n  apply: trmx_inj; rewrite tr_row_mx tr_col_mx trmx_ursub trmx_drsub trmx_lsub.\n  by rewrite hsubmxK vsubmxK.\nrewrite -sum1_card; apply: eq_bigl => B; rewrite xrowE unitmxE.\nrewrite !det_mulmx unitrM -unitmxE unitmx_perm det_lblock det_ublock.\nrewrite !det_scalar1 det1 mulr1 mul1r unitrM unitfE nza -unitmxE.\nrewrite mulmx_block !mulmx0 mul0mx !addr0 !mulmx1 mul1mx block_mxKur.\nrewrite mul_scalar_mx scalerA divff // scale1r eqxx andbT.\nby rewrite block_mxEh mul_mx_row row_mxKl -def_a vsubmxK -xrowE xrkK eqxx andbT.\nQed.\n\nLemma card_GL_1 : #|'GL_1[F]| = #|F|.-1.\nProof. by rewrite card_GL // mul1n big_nat1 expn1 subn1. Qed.\n\nLemma card_GL_2 : #|'GL_2[F]| = (#|F| * #|F|.-1 ^ 2 * #|F|.+1)%N.\nProof.\nrewrite card_GL // big_ltn // big_nat1 expn1 -(addn1 #|F|) -subn1 -!mulnA.\nby rewrite -subn_sqr.\nQed.\n\nEnd CardGL.\n\nLemma logn_card_GL_p n p : prime p -> logn p #|'GL_n(p)| = 'C(n, 2).\nProof.\nmove=> p_pr; have p_gt1 := prime_gt1 p_pr.\nhave p_i_gt0: p ^ _ > 0 by move=> i; rewrite expn_gt0 ltnW.\nrewrite (card_GL _ (ltn0Sn n.-1)) card_ord Fp_cast // big_add1 /=.\npose p'gt0 m := m > 0 /\\ logn p m = 0%N.\nsuffices [Pgt0 p'P]: p'gt0 (\\prod_(0 <= i < n.-1.+1) (p ^ i.+1 - 1))%N.\n  by rewrite lognM // p'P pfactorK //; case n.\napply big_ind => [|m1 m2 [m10 p'm1] [m20]|i _]; rewrite {}/p'gt0 ?logn1 //.\n  by rewrite muln_gt0 m10 lognM ?p'm1.\nrewrite lognE -if_neg subn_gt0 p_pr /= -{1 2}(exp1n i.+1) ltn_exp2r // p_gt1.\nby rewrite dvdn_subr ?dvdn_exp // gtnNdvd.\nQed.\n\nSection MatrixAlgebra.\n\nVariables F : fieldType.\n\nLocal Notation \"A \\in R\" := (@submx F _ _ _ (mxvec A) R).\n\nLemma mem0mx m n (R : 'A_(m, n)) : 0 \\in R.\nProof. by rewrite linear0 sub0mx. Qed.\n\nLemma memmx0 n A : (A \\in (0 : 'A_n)) -> A = 0.\nProof. by rewrite submx0 mxvec_eq0; move/eqP. Qed.\n\nLemma memmx1 n (A : 'M_n) : (A \\in mxvec 1%:M) = is_scalar_mx A.\nProof.\napply/sub_rVP/is_scalar_mxP=> [[a] | [a ->]].\n  by rewrite -linearZ scale_scalar_mx mulr1 => /(can_inj mxvecK); exists a.\nby exists a; rewrite -linearZ scale_scalar_mx mulr1.\nQed.\n\nLemma memmx_subP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, A \\in R1 -> A \\in R2) (R1 <= R2)%MS.\nProof.\napply: (iffP idP) => [sR12 A R1_A | sR12]; first exact: submx_trans sR12.\nby apply/rV_subP=> vA; rewrite -(vec_mxK vA); exact: sR12.\nQed.\nImplicit Arguments memmx_subP [m1 m2 n R1 R2].\n\nLemma memmx_eqP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, (A \\in R1) = (A \\in R2)) (R1 == R2)%MS.\nProof.\napply: (iffP eqmxP) => [eqR12 A | eqR12]; first by rewrite eqR12.\nby apply/eqmxP; apply/rV_eqP=> vA; rewrite -(vec_mxK vA) eqR12.\nQed.\nImplicit Arguments memmx_eqP [m1 m2 n R1 R2].\n\nLemma memmx_addsP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists D, [/\\ D.1 \\in R1, D.2 \\in R2 & A = D.1 + D.2])\n          (A \\in R1 + R2)%MS.\nProof.\napply: (iffP sub_addsmxP) => [[u /(canRL mxvecK)->] | [D []]].\n  exists (vec_mx (u.1 *m R1), vec_mx (u.2 *m R2)).\n  by rewrite /= linearD !vec_mxK !submxMl.\ncase/submxP=> u1 defD1 /submxP[u2 defD2] ->.\nby exists (u1, u2); rewrite linearD /= defD1 defD2.\nQed.\nImplicit Arguments memmx_addsP [m1 m2 n A R1 R2].\n\nLemma memmx_sumsP (I : finType) (P : pred I) n (A : 'M_n) R_ :\n  reflect (exists2 A_, A = \\sum_(i | P i) A_ i & forall i, A_ i \\in R_ i)\n          (A \\in \\sum_(i | P i) R_ i)%MS.\nProof.\napply: (iffP sub_sumsmxP) => [[C defA] | [A_ -> R_A] {A}].\n  exists (fun i => vec_mx (C i *m R_ i)) => [|i].\n    by rewrite -linear_sum -defA /= mxvecK.\n  by rewrite vec_mxK submxMl.\nexists (fun i => mxvec (A_ i) *m pinvmx (R_ i)).\nby rewrite linear_sum; apply: eq_bigr => i _; rewrite mulmxKpV.\nQed.\nImplicit Arguments memmx_sumsP [I P n A R_].\n\nLemma has_non_scalar_mxP m n (R : 'A_(m, n)) : \n    (1%:M \\in R)%MS ->\n  reflect (exists2 A, A \\in R & ~~ is_scalar_mx A)%MS (1 < \\rank R).\nProof.\ncase: (posnP n) => [-> | n_gt0] in R *; set S := mxvec _ => sSR.\n  by rewrite [R]thinmx0 mxrank0; right; case; rewrite /is_scalar_mx ?insubF.\nhave rankS: \\rank S = 1%N.\n  apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0 mxvec_eq0.\n  by rewrite -mxrank_eq0 mxrank1 -lt0n.\nrewrite -{2}rankS (ltn_leqif (mxrank_leqif_sup sSR)).\napply: (iffP idP) => [/row_subPn[i] | [A sAR]].\n  rewrite -[row i R]vec_mxK memmx1; set A := vec_mx _ => nsA.\n  by exists A; rewrite // vec_mxK row_sub.\nby rewrite -memmx1; apply: contra; exact: submx_trans.\nQed.\n\nDefinition mulsmx m1 m2 n (R1 : 'A[F]_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (\\sum_i <<R1 *m lin_mx (mulmxr (vec_mx (row i R2)))>>)%MS.\n\nArguments Scope mulsmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\n\nLocal Notation \"R1 * R2\" := (mulsmx R1 R2) : matrix_set_scope.\n\nLemma genmx_muls m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  <<(R1 * R2)%MS>>%MS = (R1 * R2)%MS.\nProof. by rewrite genmx_sums; apply: eq_bigr => i; rewrite genmx_id. Qed.\n\nLemma mem_mulsmx m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) A1 A2 :\n  (A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R1 * R2)%MS.\nProof.\nmove=> R_A1 R_A2; rewrite -[A2]mxvecK; case/submxP: R_A2 => a ->{A2}.\nrewrite mulmx_sum_row !linear_sum summx_sub // => i _.\nrewrite !linearZ scalemx_sub {a}//= (sumsmx_sup i) // genmxE.\nrewrite -[A1]mxvecK; case/submxP: R_A1 => a ->{A1}.\nby apply/submxP; exists a; rewrite mulmxA mul_rV_lin.\nQed.\n\nLemma mulsmx_subP m1 m2 m n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R : 'A_(m, n)) :\n  reflect (forall A1 A2, A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R)\n          (R1 * R2 <= R)%MS.\nProof.\napply: (iffP memmx_subP) => [sR12R A1 A2 R_A1 R_A2 | sR12R A].\n  by rewrite sR12R ?mem_mulsmx.\ncase/memmx_sumsP=> A_ -> R_A; rewrite linear_sum summx_sub //= => j _.\nrewrite (submx_trans (R_A _)) // genmxE; apply/row_subP=> i.\nby rewrite row_mul mul_rV_lin sR12R ?vec_mxK ?row_sub.\nQed.\nImplicit Arguments mulsmx_subP [m1 m2 m n R1 R2 R].\n\nLemma mulsmxS m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                            (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 <= R3 -> R2 <= R4 -> R1 * R2 <= R3 * R4)%MS.\nProof.\nmove=> sR13 sR24; apply/mulsmx_subP=> A1 A2 R_A1 R_A2.\nby apply: mem_mulsmx; [exact: submx_trans sR13 | exact: submx_trans sR24].\nQed.\n\nLemma muls_eqmx m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                              (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 :=: R3 -> R2 :=: R4 -> R1 * R2 = R3 * R4)%MS.\nProof.\nmove=> eqR13 eqR24; rewrite -(genmx_muls R1 R2) -(genmx_muls R3 R4).\nby apply/genmxP; rewrite !mulsmxS ?eqR13 ?eqR24.\nQed.\n\nLemma mulsmxP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists2 A1, forall i, A1 i \\in R1\n            & exists2 A2, forall i, A2 i \\in R2\n           & A = \\sum_(i < n ^ 2) A1 i *m A2 i)\n          (A \\in R1 * R2)%MS.\nProof.\napply: (iffP idP) => [R_A|[A1 R_A1 [A2 R_A2 ->{A}]]]; last first.\n  by rewrite linear_sum summx_sub // => i _; rewrite mem_mulsmx.\nhave{R_A}: (A \\in R1 * <<R2>>)%MS.\n  by apply: memmx_subP R_A; rewrite mulsmxS ?genmxE.\ncase/memmx_sumsP=> A_ -> R_A; pose A2_ i := vec_mx (row i <<R2>>%MS).\npose A1_ i := mxvec (A_ i) *m pinvmx (R1 *m lin_mx (mulmxr (A2_ i))) *m R1.\nexists (vec_mx \\o A1_) => [i|]; first by rewrite vec_mxK submxMl.\nexists A2_ => [i|]; first by rewrite vec_mxK -(genmxE R2) row_sub.\napply: eq_bigr => i _; rewrite -[_ *m _](mx_rV_lin (mulmxr_linear _ _)).\nby rewrite -mulmxA mulmxKpV ?mxvecK // -(genmxE (_ *m _)) R_A.\nQed.\nImplicit Arguments mulsmxP [m1 m2 n A R1 R2].\n\nLemma mulsmxA m1 m2 m3 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 * R3) = R1 * R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls (_ * _)%MS) -genmx_muls; apply/genmxP; apply/andP; split.\n  apply/mulsmx_subP=> A1 A23 R_A1; case/mulsmxP=> A2 R_A2 [A3 R_A3 ->{A23}].\n  by rewrite !linear_sum summx_sub //= => i _; rewrite mulmxA !mem_mulsmx.\napply/mulsmx_subP=> _ A3 /mulsmxP[A1 R_A1 [A2 R_A2 ->]] R_A3.\nrewrite mulmx_suml linear_sum summx_sub //= => i _.\nby rewrite -mulmxA !mem_mulsmx.\nQed.\n\nLemma mulsmx_addl m1 m2 m3 n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  ((R1 + R2) * R3 = R1 * R3 + R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls R2 R3) -(genmx_muls R1 R3) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> _ A3 /memmx_addsP[A [R_A1 R_A2 ->]] R_A3.\nby rewrite mulmxDl linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx_addr m1 m2 m3 n\n                  (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 + R3) = R1 * R2 + R1 * R3)%MS.\nProof.\nrewrite -(genmx_muls R1 R3) -(genmx_muls R1 R2) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> A1 _ R_A1 /memmx_addsP[A [R_A2 R_A3 ->]].\nby rewrite mulmxDr linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx0 m1 m2 n (R1 : 'A_(m1, n)) : (R1 * (0 : 'A_(m2, n)) = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A1 A0 _.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mulmx0 mem0mx.\nQed.\n\nLemma muls0mx m1 m2 n (R2 : 'A_(m2, n)) : ((0 : 'A_(m1, n)) * R2 = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A0 A2.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mul0mx mem0mx.\nQed.\n\nDefinition left_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R1 * R2 <= R2)%MS.\n\nDefinition right_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R2 * R1 <= R2)%MS.\n\nDefinition mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  left_mx_ideal R1 R2 && right_mx_ideal R1 R2.\n\nDefinition mxring_id m n (R : 'A_(m, n)) e :=\n  [/\\ e != 0,\n      e \\in R,\n      forall A, A \\in R -> e *m A = A\n    & forall A, A \\in R -> A *m e = A]%MS.\n\nDefinition has_mxring_id m n (R : 'A[F]_(m , n)) :=\n  (R != 0) &&\n  (row_mx 0 (row_mx (mxvec R) (mxvec R))\n    <= row_mx (cokermx R) (row_mx (lin_mx (mulmx R \\o lin_mulmx))\n                                  (lin_mx (mulmx R \\o lin_mulmxr))))%MS.\n\nDefinition mxring m n (R : 'A_(m, n)) :=\n  left_mx_ideal R R && has_mxring_id R.\n\nLemma mxring_idP m n (R : 'A_(m, n)) :\n  reflect (exists e, mxring_id R e) (has_mxring_id R).\nProof.\napply: (iffP andP) => [[nzR] | [e [nz_e Re ideR idRe]]].\n  case/submxP=> v; rewrite -[v]vec_mxK; move/vec_mx: v => e.\n  rewrite !mul_mx_row; case/eq_row_mx => /eqP.\n  rewrite eq_sym -submxE => Re.\n  case/eq_row_mx; rewrite !{1}mul_rV_lin1 /= mxvecK.\n  set u := (_ *m _) => /(can_inj mxvecK) idRe /(can_inj mxvecK) ideR.\n  exists e; split=> // [ | A /submxP[a defA] | A /submxP[a defA]].\n  - by apply: contra nzR; rewrite ideR => /eqP->; rewrite !linear0.\n  - by rewrite -{2}[A]mxvecK defA idRe mulmxA mx_rV_lin -defA /= mxvecK.\n  by rewrite -{2}[A]mxvecK defA ideR mulmxA mx_rV_lin -defA /= mxvecK.\nsplit.\n  by apply: contraNneq nz_e => R0; rewrite R0 eqmx0 in Re; rewrite (memmx0 Re).\napply/submxP; exists (mxvec e); rewrite !mul_mx_row !{1}mul_rV_lin1.\nrewrite submxE in Re; rewrite {Re}(eqP Re).\ncongr (row_mx 0 (row_mx (mxvec _) (mxvec _))); apply/row_matrixP=> i.\n  by rewrite !row_mul !mul_rV_lin1 /= mxvecK ideR vec_mxK ?row_sub.\nby rewrite !row_mul !mul_rV_lin1 /= mxvecK idRe vec_mxK ?row_sub.\nQed.\nImplicit Arguments mxring_idP [m n R].\n\nSection CentMxDef.\n\nVariables (m n : nat) (R : 'A[F]_(m, n)).\n\nDefinition cent_mx_fun (B : 'M[F]_n) := R *m lin_mx (mulmxr B \\- mulmx B).\n\nLemma cent_mx_fun_is_linear : linear cent_mx_fun.\nProof.\nmove=> a A B; apply/row_matrixP=> i; rewrite linearP row_mul mul_rV_lin.\nrewrite /= {-3}[row]lock row_mul mul_rV_lin -lock row_mul mul_rV_lin.\nby rewrite -linearP -(linearP [linear of mulmx _ \\- mulmxr _]).\nQed.\nCanonical cent_mx_fun_additive := Additive cent_mx_fun_is_linear.\nCanonical cent_mx_fun_linear := Linear cent_mx_fun_is_linear.\n\nDefinition cent_mx := kermx (lin_mx cent_mx_fun).\n\nDefinition center_mx := (R :&: cent_mx)%MS.\n\nEnd CentMxDef.\n\nLocal Notation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nLocal Notation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nLemma cent_rowP m n B (R : 'A_(m, n)) :\n  reflect (forall i (A := vec_mx (row i R)), A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP sub_kermxP); rewrite mul_vec_lin => cBE.\n  move/(canRL mxvecK): cBE => cBE i A /=; move/(congr1 (row i)): cBE.\n  rewrite row_mul mul_rV_lin -/A; move/(canRL mxvecK).\n  by move/(canRL (subrK _)); rewrite !linear0 add0r.\napply: (canLR vec_mxK); apply/row_matrixP=> i.\nby rewrite row_mul mul_rV_lin /= cBE subrr !linear0.\nQed.\nImplicit Arguments cent_rowP [m n B R].\n\nLemma cent_mxP m n B (R : 'A_(m, n)) :\n  reflect (forall A, A \\in R -> A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP cent_rowP) => cEB => [A sAE | i A].\n  rewrite -[A]mxvecK -(mulmxKpV sAE); move: (mxvec A *m _) => u.\n  rewrite !mulmx_sum_row !linear_sum mulmx_suml; apply: eq_bigr => i _ /=.\n  by rewrite !linearZ -scalemxAl /= cEB.\nby rewrite cEB // vec_mxK row_sub.\nQed.\nImplicit Arguments cent_mxP [m n B R].\n\nLemma scalar_mx_cent m n a (R : 'A_(m, n)) : (a%:M \\in 'C(R))%MS.\nProof. by apply/cent_mxP=> A _; exact: scalar_mxC. Qed.\n\nLemma center_mx_sub m n (R : 'A_(m, n)) : ('Z(R) <= R)%MS.\nProof. exact: capmxSl. Qed.\n\nLemma center_mxP m n A (R : 'A_(m, n)) :\n  reflect (A \\in R /\\ forall B, B \\in R -> B *m A = A *m B)\n          (A \\in 'Z(R))%MS.\nProof.\nrewrite sub_capmx; case R_A: (A \\in R); last by right; case.\nby apply: (iffP cent_mxP) => [cAR | [_ cAR]].\nQed.\nImplicit Arguments center_mxP [m n A R].\n\nLemma mxring_id_uniq m n (R : 'A_(m, n)) e1 e2 :\n  mxring_id R e1 -> mxring_id R e2 -> e1 = e2.\nProof.\nby case=> [_ Re1 idRe1 _] [_ Re2 _ ide2R]; rewrite -(idRe1 _ Re2) ide2R.\nQed.\n\nLemma cent_mx_ideal m n (R : 'A_(m, n)) : left_mx_ideal 'C(R)%MS 'C(R)%MS.\nProof.\napply/mulsmx_subP=> A1 A2 C_A1 C_A2; apply/cent_mxP=> B R_B.\nby rewrite mulmxA (cent_mxP C_A1) // -!mulmxA (cent_mxP C_A2).\nQed.\n\nLemma cent_mx_ring m n (R : 'A_(m, n)) : n > 0 -> mxring 'C(R)%MS.\nProof.\nmove=> n_gt0; rewrite /mxring cent_mx_ideal; apply/mxring_idP.\nexists 1%:M; split=> [||A _|A _]; rewrite ?mulmx1 ?mul1mx ?scalar_mx_cent //.\nby rewrite -mxrank_eq0 mxrank1 -lt0n.\nQed.\n\nLemma mxdirect_adds_center m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n    mx_ideal (R1 + R2)%MS R1 -> mx_ideal (R1 + R2)%MS R2 ->\n    mxdirect (R1 + R2) ->\n  ('Z((R1 + R2)%MS) :=: 'Z(R1) + 'Z(R2))%MS.\nProof.\ncase/andP=> idlR1 idrR1 /andP[idlR2 idrR2] /mxdirect_addsP dxR12.\napply/eqmxP/andP; split.\n  apply/memmx_subP=> z0; rewrite sub_capmx => /andP[].\n  case/memmx_addsP=> z [R1z1 R2z2 ->{z0}] Cz.\n  rewrite linearD addmx_sub_adds //= ?sub_capmx ?R1z1 ?R2z2 /=.\n    apply/cent_mxP=> A R1_A; have R_A := submx_trans R1_A (addsmxSl R1 R2).\n    have Rz2 := submx_trans R2z2 (addsmxSr R1 R2).\n    rewrite -{1}[z.1](addrK z.2) mulmxBr (cent_mxP Cz) // mulmxDl.\n    rewrite [A *m z.2]memmx0 1?[z.2 *m A]memmx0 ?addrK //.\n      by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  apply/cent_mxP=> A R2_A; have R_A := submx_trans R2_A (addsmxSr R1 R2).\n  have Rz1 := submx_trans R1z1 (addsmxSl R1 R2).\n  rewrite -{1}[z.2](addKr z.1) mulmxDr (cent_mxP Cz) // mulmxDl.\n  rewrite mulmxN [A *m z.1]memmx0 1?[z.1 *m A]memmx0 ?addKr //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nrewrite addsmx_sub; apply/andP; split.\n  apply/memmx_subP=> z; rewrite sub_capmx => /andP[R1z cR1z].\n  have Rz := submx_trans R1z (addsmxSl R1 R2).\n  rewrite sub_capmx Rz; apply/cent_mxP=> A0.\n  case/memmx_addsP=> A [R1_A1 R2_A2] ->{A0}.\n  have R_A2 := submx_trans R2_A2 (addsmxSr R1 R2).\n  rewrite mulmxDl mulmxDr (cent_mxP cR1z) //; congr (_ + _).\n  rewrite [A.2 *m z]memmx0 1?[z *m A.2]memmx0 //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\napply/memmx_subP=> z; rewrite !sub_capmx => /andP[R2z cR2z].\nhave Rz := submx_trans R2z (addsmxSr R1 R2); rewrite Rz.\napply/cent_mxP=> _ /memmx_addsP[A [R1_A1 R2_A2 ->]].\nrewrite mulmxDl mulmxDr (cent_mxP cR2z _ R2_A2) //; congr (_ + _).\nhave R_A1 := submx_trans R1_A1 (addsmxSl R1 R2).\nrewrite [A.1 *m z]memmx0 1?[z *m A.1]memmx0 //.\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nby rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\nQed.\n\nLemma mxdirect_sums_center (I : finType) m n (R : 'A_(m, n)) R_ :\n    (\\sum_i R_ i :=: R)%MS -> mxdirect (\\sum_i R_ i) ->\n    (forall i : I, mx_ideal R (R_ i)) ->\n  ('Z(R) :=: \\sum_i 'Z(R_ i))%MS.\nProof.\nmove=> defR dxR idealR.\nhave sR_R: (R_ _ <= R)%MS by move=> i; rewrite -defR (sumsmx_sup i).\nhave anhR i j A B : i != j -> A \\in R_ i -> B \\in R_ j -> A *m B = 0.\n  move=> ne_ij RiA RjB; apply: memmx0.\n  have [[_ idRiR] [idRRj _]] := (andP (idealR i), andP (idealR j)).\n  rewrite -(mxdirect_sumsP dxR j) // sub_capmx (sumsmx_sup i) //.\n    by rewrite (mulsmx_subP idRRj) // (memmx_subP (sR_R i)).\n  by rewrite (mulsmx_subP idRiR) // (memmx_subP (sR_R j)).\napply/eqmxP/andP; split.\n  apply/memmx_subP=> Z; rewrite sub_capmx => /andP[].\n  rewrite -{1}defR => /memmx_sumsP[z ->{Z} Rz cRz].\n  apply/memmx_sumsP; exists z => // i; rewrite sub_capmx Rz.\n  apply/cent_mxP=> A RiA; have:= cent_mxP cRz A (memmx_subP (sR_R i) A RiA).\n  rewrite (bigD1 i) //= mulmxDl mulmxDr mulmx_suml mulmx_sumr.\n  by rewrite !big1 ?addr0 // => j; last rewrite eq_sym; move/anhR->.\napply/sumsmx_subP => i _; apply/memmx_subP=> z; rewrite sub_capmx.\ncase/andP=> Riz cRiz; rewrite sub_capmx (memmx_subP (sR_R i)) //=.\napply/cent_mxP=> A; rewrite -{1}defR; case/memmx_sumsP=> a -> R_a.\nrewrite (bigD1 i) // mulmxDl mulmxDr mulmx_suml mulmx_sumr.\nrewrite !big1 => [|j|j]; first by rewrite !addr0 (cent_mxP cRiz).\n  by rewrite eq_sym => /anhR->.\nby move/anhR->.\nQed.\n\nEnd MatrixAlgebra.\n\nArguments Scope mulsmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope left_mx_ideal\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope right_mx_ideal\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope mx_ideal\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope mxring_id\n  [_ nat_scope nat_scope ring_scope matrix_set_scope].\nArguments Scope has_mxring_id\n  [_ nat_scope nat_scope ring_scope matrix_set_scope].\nArguments Scope mxring\n  [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope cent_mx\n  [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope center_mx\n  [_ nat_scope nat_scope matrix_set_scope].\n\nPrenex Implicits mulsmx.\n\nNotation \"A \\in R\" := (submx (mxvec A) R) : matrix_set_scope.\nNotation \"R * S\" := (mulsmx R S) : matrix_set_scope.\nNotation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nNotation \"''C_' R ( S )\" := (R :&: 'C(S))%MS : matrix_set_scope.\nNotation \"''C_' ( R ) ( S )\" := ('C_R(S))%MS (only parsing) : matrix_set_scope.\nNotation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nImplicit Arguments memmx_subP [F m1 m2 n R1 R2].\nImplicit Arguments memmx_eqP [F m1 m2 n R1 R2].\nImplicit Arguments memmx_addsP [F m1 m2 n R1 R2].\nImplicit Arguments memmx_sumsP [F I P n A R_].\nImplicit Arguments mulsmx_subP [F m1 m2 m n R1 R2 R].\nImplicit Arguments mulsmxP [F m1 m2 n A R1 R2].\nImplicit Arguments mxring_idP [m n R].\nImplicit Arguments cent_rowP [F m n B R].\nImplicit Arguments cent_mxP [F m n B R].\nImplicit Arguments center_mxP [F m n A R].\n\n(* Parametricity for the row-space/F-algebra theory.                         *)\nSection MapMatrixSpaces.\n\nVariables (aF rF : fieldType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nLemma Gaussian_elimination_map m n (A : 'M_(m, n)) :\n  Gaussian_elimination A^f = ((col_ebase A)^f, (row_ebase A)^f, \\rank A).\nProof.\nrewrite mxrankE /row_ebase /col_ebase unlock.\nelim: m n A => [|m IHm] [|n] A /=; rewrite ?map_mx1 //.\nset pAnz := [pred k | A k.1 k.2 != 0].\nrewrite (@eq_pick _ _ pAnz) => [|k]; last by rewrite /= mxE fmorph_eq0.\ncase: {+}(pick _) => [[i j]|]; last by rewrite !map_mx1.\nrewrite mxE -fmorphV  -map_xcol -map_xrow -map_dlsubmx -map_drsubmx.\nrewrite -map_ursubmx -map_mxZ -map_mxM -map_mx_sub {}IHm /=.\ncase: {+}(Gaussian_elimination _) => [[L U] r] /=; rewrite map_xrow map_xcol.\nby rewrite !(@map_block_mx _ _ f 1 _ 1) !map_mx0 ?map_mx1 ?map_scalar_mx.\nQed.\n\nLemma mxrank_map m n (A : 'M_(m, n)) : \\rank A^f = \\rank A.\nProof. by rewrite mxrankE Gaussian_elimination_map. Qed.\n\nLemma row_free_map m n (A : 'M_(m, n)) : row_free A^f = row_free A.\nProof. by rewrite /row_free mxrank_map. Qed.\n\nLemma row_full_map m n (A : 'M_(m, n)) : row_full A^f = row_full A.\nProof. by rewrite /row_full mxrank_map. Qed.\n\nLemma map_row_ebase m n (A : 'M_(m, n)) : (row_ebase A)^f = row_ebase A^f.\nProof. by rewrite {2}/row_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_col_ebase m n (A : 'M_(m, n)) : (col_ebase A)^f = col_ebase A^f.\nProof. by rewrite {2}/col_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_row_base m n (A : 'M_(m, n)) :\n  (row_base A)^f = castmx (mxrank_map A, erefl n) (row_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/row_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_row_ebase.\nQed.\n\nLemma map_col_base m n (A : 'M_(m, n)) :\n  (col_base A)^f = castmx (erefl m, mxrank_map A) (col_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/col_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_col_ebase.\nQed.\n\nLemma map_pinvmx m n (A : 'M_(m, n)) : (pinvmx A)^f = pinvmx A^f.\nProof.\nrewrite !map_mxM !map_invmx map_row_ebase map_col_ebase.\nby rewrite map_pid_mx -mxrank_map.\nQed.\n\nLemma map_kermx m n (A : 'M_(m, n)) : (kermx A)^f = kermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_col_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_cokermx m n (A : 'M_(m, n)) : (cokermx A)^f = cokermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_row_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_submx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f <= B^f)%MS = (A <= B)%MS.\nProof. by rewrite !submxE -map_cokermx -map_mxM map_mx_eq0. Qed.\n\nLemma map_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f < B^f)%MS = (A < B)%MS.\nProof. by rewrite /ltmx !map_submx. Qed.\n\nLemma map_eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f :=: B^f)%MS <-> (A :=: B)%MS.\nProof.\nsplit=> [/eqmxP|eqAB]; first by rewrite !map_submx => /eqmxP.\nby apply/eqmxP; rewrite !map_submx !eqAB !submx_refl.\nQed.\n\nLemma map_genmx m n (A : 'M_(m, n)) : (<<A>>^f :=: <<A^f>>)%MS.\nProof. by apply/eqmxP; rewrite !(genmxE, map_submx) andbb. Qed.\n\nLemma map_addsmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (((A + B)%MS)^f :=: A^f + B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !addsmxE -map_col_mx !map_submx !addsmxE andbb.\nQed.\n\nLemma map_capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (capmx_gen A B)^f = capmx_gen A^f B^f.\nProof. by rewrite map_mxM map_lsubmx map_kermx map_col_mx. Qed.\n\nLemma map_capmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :&: B)^f :=: A^f :&: B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !capmxE -map_capmx_gen !map_submx -!capmxE andbb.\nQed.\n\nLemma map_complmx m n (A : 'M_(m, n)) : (A^C^f = A^f^C)%MS.\nProof. by rewrite map_mxM map_row_ebase -mxrank_map map_copid_mx. Qed.\n\nLemma map_diffmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B)^f :=: A^f :\\: B^f)%MS.\nProof.\napply/eqmxP; rewrite !diffmxE -map_capmx_gen -map_complmx.\nby rewrite -!map_capmx !map_submx -!diffmxE andbb.\nQed.\n\nLemma map_eigenspace n (g : 'M_n) a : (eigenspace g a)^f = eigenspace g^f (f a).\nProof. by rewrite map_kermx map_mx_sub ?map_scalar_mx. Qed.\n\nLemma eigenvalue_map n (g : 'M_n) a : eigenvalue g^f (f a) = eigenvalue g a.\nProof. by rewrite /eigenvalue -map_eigenspace map_mx_eq0. Qed.\n\nLemma memmx_map m n A (E : 'A_(m, n)) : (A^f \\in E^f)%MS = (A \\in E)%MS.\nProof. by rewrite -map_mxvec map_submx. Qed.\n\nLemma map_mulsmx m1 m2 n (E1 : 'A_(m1, n)) (E2 : 'A_(m2, n)) :\n  ((E1 * E2)%MS^f :=: E1^f * E2^f)%MS.\nProof.\nrewrite /mulsmx; elim/big_rec2: _ => [|i A Af _ eqA]; first by rewrite map_mx0.\napply: (eqmx_trans (map_addsmx _ _)); apply: adds_eqmx {A Af}eqA.\napply/eqmxP; rewrite !map_genmx !genmxE map_mxM.\napply/rV_eqP=> u; congr (u <= _ *m _)%MS.\nby apply: map_lin_mx => //= A; rewrite map_mxM // map_vec_mx map_row.\nQed.\n\nLemma map_cent_mx m n (E : 'A_(m, n)) : ('C(E)%MS)^f = 'C(E^f)%MS.\nProof.\nrewrite map_kermx //; congr (kermx _); apply: map_lin_mx => // A.\nrewrite map_mxM //; congr (_ *m _); apply: map_lin_mx => //= B.\nby rewrite map_mx_sub ? map_mxM.\nQed.\n\nLemma map_center_mx m n (E : 'A_(m, n)) : (('Z(E))^f :=: 'Z(E^f))%MS.\nProof. by rewrite /center_mx -map_cent_mx; exact: map_capmx. Qed.\n\nEnd MapMatrixSpaces.\n\n\n", "meta": {"author": "beta-ziliani", "repo": "ssreflect-1.4", "sha": "2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571", "save_path": "github-repos/coq/beta-ziliani-ssreflect-1.4", "path": "github-repos/coq/beta-ziliani-ssreflect-1.4/ssreflect-1.4-2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571/theories/mxalgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7328448072938354}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* relation x / (s y) *)\nDefinition  d (x y a b: nat) := (x = a * (S y) + b) /\\ b <= y.\n(* a - quotient *)\n(* b - remainder *)\n\n(* 16.1.1 *)\nLemma d1: forall y, d 0 y 0 0.\nProof.\n  split.\n    by [].\n  by [].\nQed.\n\nLemma d2: forall x y a b, d x y a b -> b = y -> d (S x) y (S a) 0.\nProof.\n  move => x y a b H E.\n  move: E H ->.\n  rewrite /d.\n  move => [Hl Hr].\n  split; last by done.\n  by rewrite Hl -addnS mulSn addn0 addnC.\nQed.\n\nLemma d3: forall x y a b, d x y a b -> b <> y -> d (S x) y a (S b).\nProof.\n  move => x y a b [Hl Hr] Neq.\n  split; last first.\n    move: Hr.\n    rewrite leq_eqVlt; move => /orP; case; last by done.\n      move => /eqP Contra.\n      exfalso; apply (Neq Contra).\n  by rewrite Hl addnS.\nQed.\n\n(* 16.1.2 *)\nTheorem cert_div: forall x y, { ' (a, b) & d x y a b }.\nProof.\n  elim => [ y | x' IH y].\n    exists (0, 0).\n    apply d1.\n  set U := IH y.\n  move: (IH y) => [[a b] [Hl Hr]].\n  move: Hr.\n  case: (ltngtP b y) => //.\n    move => Lby _.\n    exists (a, (S b)).\n    apply d3.\n    split => //.\n      apply (ltnW Lby).\n    move => contra.\n    move: Lby.\n    rewrite contra /(_ < _) subSn.\n    rewrite subnn.\n    apply /eqP. by [].\n      by [].\n  move => H _.\n  exists ((S a), 0).\n  apply (d2 (b:=b)) => //.\n  split => //.\n  by rewrite H.\nDefined.\n\nPrint cert_div.\nDefinition x: nat := match cert_div 5 3 with (existT (a, b) _) => a end.\nCompute (cert_div 5 3).\nCompute (projT1 (cert_div 5 3)).\nCompute (x).\n\nLemma tst: forall n m k, n = m.+1 + k -> m < n.\nProof.\n  elim => [m k H | n IH m k].\n    exfalso; move: H.\n    rewrite addSn.\n    by [].\n  rewrite addSn. move /eq_add_S ->.\n  by rewrite /(_ < _) subSS subnDA subnn sub0n.\nQed.\n  \n(* 16.3.1 / 16.3.2 *)\nTheorem cert_div_unique: forall (x y a b a' b': nat), \n  d x y a b -> d x y a' b' -> a = a' /\\ b = b'.\nProof.\n  move => x y a.\n  move: a x y.\n  elim => [x y b a' b' | a IH x y b a' b'].\n    rewrite /d mul0n add0n.\n    move => [-> Hr] [Hl' Hr'].\n    case: a' Hl'.\n      by rewrite mul0n add0n.\n    move => a'' Hcontr.\n    exfalso; have: b > y.\n      move: Hcontr.\n      rewrite mulSn -addnA.\n      apply tst.\n    move => Hl.\n    move: (leq_gtF Hr).\n    by rewrite Hl.\n  case a' => [|a''].\n    move => [Hl Hr] [Hl' Hr'].\n    exfalso.\n    move: Hl'; rewrite Hl mul0n add0n => H.\n    move: Hr'.\n    rewrite -H mulSn 2!addSn -addnA.\n    rewrite -{3}(addn0 y).\n    by rewrite ltn_add2l.  \n  move => [Hl Hr] [Hl' Hr'].\n  move: (Hl) (Hl') => ->.\n  rewrite 2!mulSn 2!mulnS -addnA. \n  rewrite -[y.+1 + (a'' + a'' * y) + b']addnA.\n  move /eqP.\n  rewrite (eqn_add2l y.+1) => H.\n  have: d (a * y.+1 + b) y a b.\n    by split.\n  have: d (a'' * y.+1 + b') y a'' b'.\n    by split.\n  rewrite 2!mulnS.\n  move/eqP :H => ->.\n  move => D' D.\n  move: (IH _ _ _ _ _ D D') => [HL HR].\n  by rewrite HL HR.\nQed.\n\n(* 16.3.3 *)\nLemma d4: forall x y, x <= y -> d x y 0 x.\nProof.\n  move => x y Hl.\n  split => //.\nQed.\n\nLemma d5: forall x y a b, x > y -> d (x - y.+1) y a b -> d x y a.+1 b.\nProof.\n  move => x y a b L [Hl Hr].\n  split => //.\n  rewrite mulSn -addnA -Hl.\n  rewrite subnKC => //.\nQed.\n\n(* 16.3.4 *)\n(* TODO *)\n\n(* 16.3.5 *)\n(* TODO *)\n\n(* 16.3.6 *)\n(* TODO *)\n\n(* 16.3.7 *)\n(* TODO *)\n\n(* 16.3.8 *)\nLemma uniq2: forall (y a b a' b': nat), \n  (b <= y) -> (b' <= y) -> (a * y.+1 + b = a' * y.+1 + b') -> a = a' /\\ b = b'.\nProof.\n  move => y a b a' b' Hl Hl' H.\n  apply (cert_div_unique (x:=(a * y.+1 + b)) (y:=y)).\n  by split.\n  by split.\nQed.\n\nLemma ex1638: forall x y z, x * (z.+2) + 1 <> y * (z.+2) + 0.\nProof.\n  move => x y z H.\n  have Hl: 1 <= z.+2.\n    by [].\n  have Hl': 0 <= z.+2.\n    by [].\n  move: (uniq2 (a:=x) (a':=y) (y:= z.+1)(b:=1) (b':=0) Hl Hl' H).\n  by move => [_ Contra].\nQed.\n\n(* 16.3.9 *)\n(* TODO *)\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/model_and_prooving_CompTT/pt3/ch16_euclidean_div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7327522619657223}}
{"text": "Require Import Morphisms.\nRequire Import GeoCoq.Axioms.hilbert_axioms.\nRequire Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Meta_theory.Parallel_postulates.tarski_playfair.\nRequire Import GeoCoq.Meta_theory.Parallel_postulates.SPP_ID.\nRequire Import GeoCoq.Meta_theory.Dimension_axioms.upper_dim_3.\nRequire Import GeoCoq.Meta_theory.Parallel_postulates.parallel_postulates.\n\nRequire Export GeoCoq.Utils.triples.\n\nSection T.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(** We need a notion of line. *)\n\nDefinition Line := @Couple Tpoint.\nDefinition Lin := build_couple Tpoint.\n\nDefinition IncidentL := fun A l => Col A (P1 l) (P2 l).\n\n(** * Group I Incidence *)\n\n(** For every pair of distinct points there is a line containing them. *)\n\nLemma axiom_line_existence : forall A B, A<>B -> exists l, IncidentL A l /\\ IncidentL B l.\nProof.\nintros.\nexists (Lin A B H).\nunfold IncidentL.\nintuition.\nQed.\n\n(** We need a notion of equality over lines. *)\n\nDefinition EqL : relation Line := fun l m => forall X, IncidentL X l <-> IncidentL X m.\n\nInfix \"=l=\" := EqL (at level 70):type_scope.\n\nLemma incident_eq : forall A B l, forall H : A<>B,\n IncidentL A l -> IncidentL B l ->\n (Lin A B H) =l= l.\nProof.\nintros.\nunfold EqL.\nintros.\nunfold IncidentL in *.\nreplace (P1 (Lin A B H)) with A; trivial.\nreplace (P2 (Lin A B H)) with B; trivial.\nsplit;intro.\nassert (T:=Cond l).\nelim (eq_dec_points X B); intro.\nsubst X.\nauto.\nassert (Col (P1 l) A B).\napply col_transitivity_1 with (P2 l); Col.\nassert (Col (P2 l) A B).\napply (col_transitivity_2 (P1 l)); Col.\napply (col3 A B); Col.\n\nassert (U:=Cond l).\napply (col3 (P1 l) (P2 l)); Col.\nQed.\n\n(** Our equality is an equivalence relation. *)\n\nLemma eq_transitivity : forall l m n, l =l= m -> m =l= n -> l =l= n.\nProof.\nunfold EqL,IncidentL.\nintros.\nassert (T:=H X).\nassert (V:= H0 X).\nsplit;intro;intuition.\nQed.\n\nLemma eq_reflexivity : forall l, l =l= l.\nProof.\nintros.\nunfold EqL.\nintuition.\nQed.\n\nLemma eq_symmetry : forall l m, l =l= m -> m =l= l.\nProof.\nunfold EqL.\nintros.\nassert (T:=H X).\nintuition.\nQed.\n\nInstance EqL_Equiv : Equivalence EqL.\nProof.\nsplit.\nunfold Reflexive.\napply eq_reflexivity.\nunfold Symmetric.\napply eq_symmetry.\nunfold Transitive.\napply eq_transitivity.\nDefined.\n\n\n(** The equality is compatible with IncidentL *)\n\nLemma eq_incident : forall A l m, l =l= m ->\n (IncidentL A l <-> IncidentL A m).\nProof.\nintros.\nsplit;intros;\nunfold EqL in *;\nassert (T:= H A);\nintuition.\nQed.\n\nInstance incident_Proper (A:Tpoint) :\nProper (EqL ==>iff) (IncidentL A).\nProof.\nintros a b H .\napply eq_incident.\nassumption.\nDefined.\n\nLemma axiom_Incid_morphism :\n forall P l m, IncidentL P l -> EqL l m -> IncidentL P m.\nProof.\nintros.\ndestruct (eq_incident P l m H0).\nintuition.\nQed.\n\nLemma axiom_Incid_dec : forall P l, IncidentL P l \\/ ~IncidentL P l.\nProof.\nintros.\nunfold IncidentL.\napply col_dec.\nQed.\n\n(** There is only one line going through two points. *)\n\nLemma axiom_line_uniqueness : forall A B l m, A <> B ->\n IncidentL A l -> IncidentL B l -> IncidentL A m -> IncidentL B m ->\n l =l= m.\nProof.\nintros.\nassert ((Lin A B H) =l= l).\neapply incident_eq;assumption.\nassert ((Lin A B H) =l= m).\neapply incident_eq;assumption.\nrewrite <- H4.\nassumption.\nQed.\n\n(** Every line contains at least two points. *)\n\nLemma axiom_two_points_on_line : forall l,\n  { A : Tpoint & { B | IncidentL B l /\\ IncidentL A l /\\ A <> B}}.\nProof.\nintros.\nexists (P1 l).\nexists (P2 l).\nunfold IncidentL.\nrepeat split;Col.\nexact (Cond l).\nQed.\n\n(** Definition of the collinearity predicate.\n We say that three points are collinear if they belongs to the same line. *)\n\nDefinition Col_H := fun A B C =>\n  exists l, IncidentL A l /\\ IncidentL B l /\\ IncidentL C l.\n\n(** We show that the notion of collinearity we just defined is equivalent to the\n notion of collinearity of Tarski. *)\n\nLemma cols_coincide_1 : forall A B C, Col_H A B C -> Col A B C.\nProof.\nintros.\nunfold Col_H in H.\nDecompExAnd H l.\nunfold IncidentL in *.\nassert (T:=Cond l).\napply (col3 (P1 l) (P2 l)); Col.\nQed.\n\nLemma cols_coincide_2 : forall A B C, Col A B C -> Col_H A B C.\nProof.\nintros.\nunfold Col_H.\nelim (eq_dec_points A B); intro.\nsubst B.\nelim (eq_dec_points A C); intro.\nsubst C.\nassert (exists B, A<>B).\neapply another_point.\nDecompEx H0 B.\nexists (Lin A B H1).\nunfold IncidentL;intuition.\nexists (Lin A C H0).\nunfold IncidentL;intuition.\nexists (Lin A B H0).\nunfold IncidentL;intuition.\nQed.\n\nLemma cols_coincide : forall A B C, Col A B C <-> Col_H A B C.\nProof.\nintros.\nsplit.\napply cols_coincide_2.\napply cols_coincide_1.\nQed.\n\nLemma ncols_coincide : forall A B C, ~ Col A B C <-> ~ Col_H A B C.\nProof.\nintros.\nsplit; intros HNCol HCol; apply HNCol, cols_coincide, HCol.\nQed.\n\n(** There exists three non collinear points. *)\n\nLemma lower_dim' : PA <> PB /\\ PB <> PC /\\ PA <> PC /\\ ~ Col_H PA PB PC.\nProof.\nassert (HNCol : ~ Col PA PB PC) by (apply lower_dim).\nassert_diffs.\napply ncols_coincide in HNCol.\nrepeat split; auto.\nQed.\n\n(** We need a notion of plane. *)\n\nRecord Plane := Plan {M1; M2; M3; NCol : ~ Col_H M1 M2 M3}.\n\nDefinition IncidentP := fun A p => Coplanar (M1 p) (M2 p) (M3 p) A.\n\n(** For every triplet of non collinear points there is a plane containing them. *)\n\nLemma axiom_plane_existence : forall A B C, ~ Col_H A B C ->\n  exists p, IncidentP A p /\\ IncidentP B p /\\ IncidentP C p.\nProof.\nintros A B C HNCol.\nexists (Plan A B C HNCol).\nunfold IncidentP; simpl; repeat split; Cop.\nQed.\n\n(** We need a notion of equality over planes. *)\n\nDefinition EqP : relation Plane := fun p q => forall X, IncidentP X p <-> IncidentP X q.\n\nInfix \"=p=\" := EqP (at level 70):type_scope.\n\nLemma incidentp_eqp : forall A B C p, forall H : ~ Col_H A B C,\n IncidentP A p -> IncidentP B p -> IncidentP C p ->\n (Plan A B C H) =p= p.\nProof.\nintros A B C p HNCol HA HB HC X.\nunfold IncidentP in *; simpl.\nassert (Hp := NCol p).\napply ncols_coincide in Hp.\napply ncols_coincide in HNCol.\nsplit; intro; [apply coplanar_pseudo_trans with A B C; trivial|];\napply coplanar_pseudo_trans with (M1 p) (M2 p) (M3 p); Cop.\nQed.\n\n(** Our equality is an equivalence relation. *)\n\nLemma eqp_transitivity : forall p q r, p =p= q -> q =p= r -> p =p= r.\nProof.\nintros p q r H1 H2 X.\nrewrite (H1 X); apply H2.\nQed.\n\nLemma eqp_reflexivity : forall p, p =p= p.\nProof.\nintros.\nunfold EqP.\nintuition.\nQed.\n\nLemma eqp_symmetry : forall p q, p =p= q -> q =p= p.\nProof.\nunfold EqP.\nintros p q H X.\nassert (T := H X).\nintuition.\nQed.\n\nInstance EqP_Equiv : Equivalence EqP.\nProof.\nsplit.\nunfold Reflexive.\napply eqp_reflexivity.\nunfold Symmetric.\napply eqp_symmetry.\nunfold Transitive.\napply eqp_transitivity.\nDefined.\n\n\n(** The equality is compatible with IncidentL *)\n\nLemma eqp_incidentp : forall A p q, p =p= q ->\n (IncidentP A p <-> IncidentP A q).\nProof.\nintros A p q H.\nexact (H A).\nQed.\n\nInstance incidentp_Proper (A:Tpoint) :\nProper (EqP ==>iff) (IncidentP A).\nProof.\nintros a b H.\napply eqp_incidentp.\nassumption.\nDefined.\n\nLemma axiom_Incidp_morphism :\n forall M p q, IncidentP M p -> EqP p q -> IncidentP M q.\nProof.\nintros M p q Hp H.\ndestruct (eqp_incidentp M p q H).\nintuition.\nQed.\n\nLemma axiom_Incidp_dec : forall M p, IncidentP M p \\/ ~ IncidentP M p.\nProof.\nintros.\napply cop_dec.\nQed.\n\n(** There is only one plane going through three non collinear points. *)\n\nLemma axiom_plane_uniqueness : forall A B C p q, ~ Col_H A B C ->\n IncidentP A p -> IncidentP B p -> IncidentP C p ->\n IncidentP A q -> IncidentP B q -> IncidentP C q ->\n p =p= q.\nProof.\nintros A B C p q H; intros.\nassert (Heq : (Plan A B C H) =p= p).\napply incidentp_eqp;assumption.\nassert ((Plan A B C H) =p= q).\napply incidentp_eqp;assumption.\nrewrite <- Heq.\nassumption.\nQed.\n\n(** Every plane contains at least one point. *)\n\nLemma axiom_one_point_on_plane : forall p,\n  { A | IncidentP A p }.\nProof.\nintro p.\nexists (M1 p).\nunfold IncidentP; Cop.\nQed.\n\n(** Definition of a line belonging to a plane.\n  We say that a line belongs to a plane if every point of the line belongs to the plane. *)\n\nDefinition  IncidentLP := fun l p => forall A, IncidentL A l -> IncidentP A p.\n\n(** If two distinct points of a line belong to a plane, then the line belongs to the plane. *)\n\nLemma axiom_line_on_plane : forall A B l p, A <> B ->\n IncidentL A l -> IncidentL B l -> IncidentP A p -> IncidentP B p ->\n IncidentLP l p.\nProof.\nintros A B l p HAB HAl HBl HAp HBp X HXl.\ndestruct (ex_ncol_cop (M1 p) (M2 p) (M3 p) A B HAB) as [C [HCp HNCol]].\napply ncols_coincide in HNCol.\nassert (Heq : (Plan A B C HNCol) =p= p).\napply incidentp_eqp; auto.\nrewrite <- Heq.\nunfold IncidentP; simpl.\nexists X; left; split.\napply cols_coincide_1; exists l; repeat split; assumption.\nCol.\nQed.\n\n(** * Group II Order *)\n\n(** Definition of the Between predicate of Hilbert.\n    Note that it is different from the Between of Tarski.\n    The Between of Hilbert is strict. *)\n\nDefinition Between_H := fun A B C =>\n  Bet A B C /\\ A <> B /\\ B <> C /\\ A <> C.\n\nLemma axiom_between_col :\n forall A B C, Between_H A B C -> Col_H A B C.\nProof.\nintros.\nunfold Col_H, Between_H in *.\nDecompAndAll.\nexists (Lin A B H2).\nunfold IncidentL.\nintuition.\nQed.\n\nLemma axiom_between_diff :\n forall A B C, Between_H A B C -> A<>C.\nProof.\nintros.\nunfold Between_H in *.\nintuition.\nQed.\n\n(** If B is between A and C, it is also between C and A. *)\n\nLemma axiom_between_comm : forall A B C, Between_H A B C -> Between_H C B A.\nProof.\nunfold Between_H in |- *.\nintros.\nintuition.\nQed.\n\n\n\nLemma axiom_between_out :\n forall A B, A <> B -> exists C, Between_H A B C.\nProof.\nintros.\nprolong A B C A B.\nexists C.\nunfold Between_H.\nrepeat split;\nauto;\nintro;\ntreat_equalities;\ntauto.\nQed.\n\nLemma axiom_between_only_one :\n forall A B C,\n Between_H A B C -> ~ Between_H B C A.\nProof.\nunfold Between_H in |- *.\nintros.\nintro;\nspliter.\nassert (B=C) by\n (apply (between_equality B C A);Between).\nsolve [intuition].\nQed.\n\nLemma between_one : forall A B C,\n A<>B -> A<>C -> B<>C -> Col A B C ->\n Between_H A B C \\/ Between_H B C A \\/ Between_H B A C.\nProof.\nintros.\nunfold Col, Between_H in *.\ndestruct H2 as [|[|]]; [left|right..]; Between.\nQed.\n\n\nLemma axiom_between_one : forall A B C,\n A<>B -> A<>C -> B<>C -> Col_H A B C ->\n Between_H A B C \\/ Between_H B C A \\/ Between_H B A C.\nProof.\nintros.\napply between_one;try assumption.\napply cols_coincide_1.\nassumption.\nQed.\n\n(** Axiom of Pasch, (Hilbert version). *)\n\n(** First we define a predicate which means that the line l intersects the segment AB. *)\n\nDefinition cut := fun l A B =>\n  ~ IncidentL A l /\\ ~ IncidentL B l /\\ exists I, IncidentL I l /\\ Between_H A I B.\n\n(** We show that this definition is equivalent to the predicate TS of Tarski. *)\n\nLemma cut_two_sides : forall l A B, cut l A B <-> TS (P1 l) (P2 l) A B.\nProof.\nintros.\nunfold cut.\nunfold TS.\nsplit.\nintros.\nspliter.\nrepeat split; intuition.\nex_and H1 T.\nexists T.\nunfold IncidentL in H1.\nunfold Between_H in *.\nintuition.\n\nintros.\nspliter.\nex_and H1 T.\nunfold IncidentL.\nrepeat split; try assumption.\nexists T.\nsplit.\nassumption.\nunfold Between_H.\nrepeat split.\nassumption.\nintro.\nsubst.\ncontradiction.\nintro.\nsubst.\ncontradiction.\nintro.\ntreat_equalities.\ncontradiction.\nQed.\n\nLemma cop_plane_aux : forall A B C D, Coplanar A B C D -> A <> B ->\n  exists p, IncidentP A p /\\ IncidentP B p /\\ IncidentP C p /\\ IncidentP D p.\nProof.\n  intros A B C D HCop HAB.\n  destruct (col_dec A B C) as [|HNCol]; [destruct (col_dec A B D) as [|HNCol]|].\n  - destruct (not_col_exists A B HAB) as [E HNCol].\n    apply ncols_coincide in HNCol.\n    exists (Plan A B E HNCol).\n    unfold IncidentP; simpl; repeat split; Cop.\n  - apply ncols_coincide in HNCol.\n    exists (Plan A B D HNCol).\n    unfold IncidentP; simpl; repeat split; Cop.\n  - apply ncols_coincide in HNCol.\n    exists (Plan A B C HNCol).\n    unfold IncidentP; simpl; repeat split; Cop.\nQed.\n\nLemma cop_plane : forall A B C D, Coplanar A B C D ->\n  exists p, IncidentP A p /\\ IncidentP B p /\\ IncidentP C p /\\ IncidentP D p.\nProof.\n  intros A B C D HCop.\n  destruct (eq_dec_points A B) as [|HAB]; [destruct (eq_dec_points A C);\n    [destruct (eq_dec_points A D)|]|].\n  - destruct (another_point D) as [E].\n    destruct (cop_plane_aux D E E E) as [p []]; Cop.\n    subst; exists p; repeat split; assumption.\n  - destruct (cop_plane_aux A D B C) as [p]; Cop.\n    spliter; exists p; repeat split; assumption.\n  - destruct (cop_plane_aux A C B D) as [p]; Cop.\n    spliter; exists p; repeat split; assumption.\n  - apply (cop_plane_aux A B C D HCop HAB).\nQed.\n\nLemma plane_cop: forall A B C D p,\n  IncidentP A p -> IncidentP B p -> IncidentP C p -> IncidentP D p -> Coplanar A B C D.\nProof.\n  unfold IncidentP.\n  intros A B C D p HA HB HC HD.\n  assert (HNCol := NCol p).\n  apply ncols_coincide in HNCol.\n  apply coplanar_pseudo_trans with (M1 p) (M2 p) (M3 p); assumption.\nQed.\n\nLemma axiom_pasch : forall A B C l p, ~ Col_H A B C ->\n IncidentP A p -> IncidentP B p -> IncidentP C p -> IncidentLP l p -> ~ IncidentL C l ->\n cut l A B -> cut l A C \\/ cut l B C.\nProof.\nintros.\napply cut_two_sides in H5.\nassert(~Col A B C).\napply ncols_coincide.\nassumption.\n\nassert(HH:=H5).\nunfold TS in HH.\nspliter.\n\nunfold IncidentL in H4.\nassert (HCop : Coplanar (P1 l) (P2 l) A C).\napply plane_cop with p; trivial; apply H3; unfold IncidentL; simpl; Col.\n\nassert(HH:= cop__one_or_two_sides (P1 l)(P2 l) A C HCop H7 H4).\n\ninduction HH.\nleft.\napply <-cut_two_sides.\nassumption.\nright.\napply <-cut_two_sides.\napply l9_2.\neapply l9_8_2.\napply H5.\nassumption.\nQed.\n\nLemma Incid_line :\n forall P A B l, A<>B ->\n IncidentL A l -> IncidentL B l -> Col P A B -> IncidentL P l.\nProof.\nintros.\nunfold IncidentL in *.\ndestruct l as [C D HCD].\nsimpl in *.\nColR.\nQed.\n\n\n\n\n(** * Group III Congruence *)\n\n(** The cong predicate of Hilbert is the same as the one of Tarski: *)\n\nDefinition outH := fun P A B => Between_H P A B \\/ Between_H P B A \\/ (P <> A /\\ A = B).\n\nLemma out_outH : forall P A B, Out P A B -> outH P A B.\nunfold Out.\nunfold outH.\nintros.\nspliter.\ninduction H1.\n\ninduction (eq_dec_points A B).\nright; right.\nsplit; auto.\nleft.\nunfold Between_H.\nrepeat split; auto.\n\n\ninduction (eq_dec_points A B).\nright; right.\nsplit; auto.\nright; left.\nunfold Between_H.\nrepeat split; auto.\nQed.\n\nLemma axiom_hcong_1_existence : forall A B A' P l,\n  A <> B -> A' <> P ->\n  IncidentL A' l -> IncidentL P l ->\n  exists B', IncidentL B' l /\\ outH A' P B' /\\ Cong A' B' A B.\nProof.\nintros; destruct (l6_11_existence A' A B P) as [B' [HOut HCong]]; auto.\nexists B'; repeat split; try apply out_outH, l6_6; auto; unfold IncidentL in *.\ndestruct l; simpl in *; ColR.\nQed.\n\nLemma axiom_hcong_1_uniqueness :\n forall A B l M A' B' A'' B'', A <> B -> IncidentL M l ->\n  IncidentL A' l -> IncidentL B' l ->\n  IncidentL A'' l -> IncidentL B'' l ->\n  Between_H A' M B' -> Cong M A' A B ->\n  Cong M B' A B -> Between_H A'' M B'' ->\n  Cong M A'' A B -> Cong M B'' A B ->\n  (A' = A'' /\\ B' = B'') \\/ (A' = B'' /\\ B' = A'').\nProof.\nunfold Between_H.\nunfold IncidentL.\nintros.\nspliter.\n\nassert(A' <> M /\\ A'' <> M /\\ B' <> M /\\ B'' <> M /\\ A' <> B' /\\ A'' <> B'').\nrepeat split; intro; treat_equalities; tauto.\nspliter.\n\ninduction(out_dec M A' A'').\nleft.\nassert(A' = A'').\napply (l6_11_uniqueness M A B A''); try assumption.\napply out_trivial.\nassumption.\n\nsplit.\nassumption.\nsubst A''.\n\napply (l6_11_uniqueness M A B B''); try assumption.\n\nunfold Out.\nrepeat split; try assumption.\neapply l5_2.\napply H18.\nassumption.\nassumption.\napply out_trivial.\nassumption.\n\nright.\napply not_out_bet in H23.\n\nassert(A' = B'').\napply (l6_11_uniqueness M A B A'); try assumption.\napply out_trivial.\nassumption.\n\nunfold Out.\nrepeat split; try assumption.\n\neapply l5_2.\napply H18.\nassumption.\napply between_symmetry.\nassumption.\n\nsplit.\nassumption.\n\nsubst B''.\napply (l6_11_uniqueness M A B B'); try assumption.\napply out_trivial.\nassumption.\nunfold Out.\nrepeat split; try assumption.\neapply l5_2.\napply H20.\napply between_symmetry.\nassumption.\nassumption.\neapply col3.\napply (Cond l).\nCol.\nCol.\nCol.\nQed.\n\n(** As a remark we also prove another version of this axiom as formalized in Isabelle by\nPhil Scott. *)\n\nDefinition same_side_scott := fun E A B => E <> A /\\ E <> B /\\ Col_H E A B /\\ ~ Between_H A E B.\n\nRemark axiom_hcong_scott:\n forall P Q A C, A <> C -> P <> Q ->\n  exists B, same_side_scott A B C  /\\ Cong P Q A B.\nProof.\nintros.\nunfold same_side_scott.\nassert (exists X : Tpoint, Out A X C /\\ Cong A X P Q).\napply l6_11_existence;auto.\ndecompose [ex and] H1;clear H1.\nexists x.\nrepeat split.\nunfold Out in H3.\nintuition.\nunfold Out in H3.\nintuition.\napply cols_coincide_2.\napply out_col;assumption.\n\n\nunfold Out in H3.\nunfold Between_H.\nintro.\ndecompose [and] H3;clear H3.\ndecompose [and] H1;clear H1.\nclear H8.\ndestruct H7.\nassert (A = x).\neapply between_equality;eauto.\nintuition.\nassert (A = C).\neapply between_equality;eauto.\napply between_symmetry.\nauto.\nintuition.\nCong.\nQed.\n\n(** We define when two segments do not intersect. *)\n\nDefinition disjoint := fun A B C D => ~ exists P, Between_H A P B /\\ Between_H C P D.\n\n(** Note that two disjoint segments may share one of their extremities. *)\n\nLemma col_disjoint_bet : forall A B C, Col_H A B C -> disjoint A B B C -> Bet A B C.\nProof.\nintros.\napply cols_coincide_1 in H.\nunfold disjoint in H0.\n\ninduction (eq_dec_points A B).\nsubst  B.\napply between_trivial2.\ninduction (eq_dec_points B C).\nsubst  C.\napply between_trivial.\n\nunfold Col in H.\ninduction H.\nassumption.\n\ninduction H.\napply False_ind.\napply H0.\nassert(exists M, Midpoint M B C) by(apply midpoint_existence).\nex_and H3 M.\nexists M.\nunfold Midpoint in H4.\nspliter.\nsplit.\nunfold Between_H.\nrepeat split.\napply between_symmetry.\neapply between_exchange4.\napply H3.\nassumption.\nintro.\ntreat_equalities.\n(*\napply between_symmetry in H.\napply between_equality in H.\ntreat_equalities.\n*)\ntauto.\n(*\napply between_symmetry.\nassumption.\n*)\nintro.\ntreat_equalities.\ntauto.\nassumption.\nunfold Between_H.\nrepeat split.\nassumption.\nintro.\ntreat_equalities.\ntauto.\nintro.\ntreat_equalities.\ntauto.\nassumption.\n\napply False_ind.\napply H0.\nassert(exists M, Midpoint M A B) by(apply midpoint_existence).\nex_and H3 M.\nexists M.\nunfold Midpoint in H4.\nspliter.\nsplit.\nunfold Between_H.\nrepeat split.\nassumption.\nintro.\ntreat_equalities.\ntauto.\nintro.\ntreat_equalities.\ntauto.\nassumption.\n\nunfold Between_H.\nrepeat split.\n\neapply between_exchange4.\napply between_symmetry.\napply H3.\napply between_symmetry.\nassumption.\nintro.\ntreat_equalities.\ntauto.\nintro.\ntreat_equalities.\nintuition.\nassumption.\nQed.\n\n\nLemma axiom_hcong_3 : forall A B C A' B' C',\n   Col_H A B C -> Col_H A' B' C' ->\n  disjoint A B B C -> disjoint A' B' B' C' ->\n  Cong A B A' B' -> Cong B C B' C' -> Cong A C A' C'.\nProof.\nintros.\nassert(Bet A B C).\neapply col_disjoint_bet.\nassumption.\nassumption.\n\nassert(Bet A' B' C').\neapply col_disjoint_bet.\nassumption.\nassumption.\neapply l2_11;eauto.\nQed.\n\nLemma exists_not_incident : forall A B : Tpoint, forall  HH : A <> B , exists C, ~ IncidentL C (Lin A B HH).\nProof.\nintros.\nunfold IncidentL.\nassert(HC:=not_col_exists A B HH).\nex_and HC C.\nexists C.\nintro.\napply H.\nsimpl in H0.\nCol.\nQed.\n\nDefinition same_side := fun A B l => exists P, cut l A P /\\ cut l B P.\n\n(** Same side predicate corresponds to OS of Tarski. *)\n\nLemma same_side_one_side : forall A B l, same_side A B l -> OS (P1 l) (P2 l) A B.\nProof.\nunfold same_side.\nintros.\ndestruct H as [P []].\napply cut_two_sides in H.\napply cut_two_sides in H0.\neapply l9_8_1.\napply H.\napply H0.\nQed.\n\n\n\nLemma one_side_same_side : forall A B l, OS (P1 l) (P2 l) A B -> same_side A B l.\nProof.\nintros.\nunfold same_side.\nunfold OS in H.\ndestruct H as [P []].\nexists P.\nunfold cut.\nunfold IncidentL.\nunfold TS in H.\nunfold TS in H0.\nspliter.\nrepeat split; auto.\nex_and H4 T.\nexists T.\nunfold Between_H.\nrepeat split; auto.\nintro.\nsubst T.\ncontradiction.\nintro.\nsubst T.\ncontradiction.\nintro.\nsubst P.\napply between_identity in H5.\nsubst T.\ncontradiction.\nex_and H2 T.\nexists T.\nunfold Between_H.\nrepeat split; auto.\nintro.\nsubst T.\ncontradiction.\nintro.\nsubst T.\ncontradiction.\nintro.\nsubst P.\napply between_identity in H5.\nsubst T.\ncontradiction.\nQed.\n\nDefinition same_side' := fun A B X Y =>\n  X <> Y /\\ forall l, IncidentL X l -> IncidentL Y l -> same_side A B l.\n\nLemma OS_distinct : forall P Q A B,\n  OS P Q A B -> P<>Q.\nProof.\nintros.\napply one_side_not_col123 in H.\nassert_diffs;assumption.\nQed.\n\n\nLemma OS_same_side' :\n forall P Q A B, OS P Q A B -> same_side' A B P Q.\nProof.\nintros.\nunfold same_side'.\nintros.\nsplit.\napply OS_distinct with A B;assumption.\nintros.\n\napply  one_side_same_side.\ndestruct l.\nunfold IncidentL in *.\nsimpl in *.\napply col2_os__os with P Q; try assumption; ColR.\nQed.\n\nLemma same_side_OS :\n forall P Q A B, same_side' P Q A B -> OS A B P Q.\nProof.\nintros.\nunfold same_side' in *.\ndestruct H.\ndestruct (axiom_line_existence A B H).\ndestruct H1.\nassert (T:=H0 x H1 H2).\nassert (U:=same_side_one_side P Q x T).\ndestruct x.\nunfold IncidentL in *.\nsimpl in *.\napply col2_os__os with P1 P2;Col.\nQed.\n\n(** This is equivalent to the out predicate of Tarski. *)\n\nLemma outH_out : forall P A B, outH P A B -> Out P A B.\nProof.\nunfold outH.\nunfold Out.\nintros.\ninduction H.\nunfold Between_H in H.\nspliter.\nrepeat split; auto.\ninduction H.\nunfold Between_H in H.\nspliter.\nrepeat split; auto.\nspliter.\nrepeat split.\nauto.\nsubst B.\nauto.\nsubst B.\nleft.\napply between_trivial.\nQed.\n\n(** The 2D version of the fourth congruence axiom **)\n\nLemma incident_col : forall M l, IncidentL M l -> Col M (P1 l)(P2 l).\nProof.\nunfold IncidentL.\nintros.\nassumption.\nQed.\n\nLemma col_incident : forall M l, Col M (P1 l)(P2 l) -> IncidentL M l.\nProof.\nunfold IncidentL.\nintros.\nassumption.\nQed.\n\nLemma Bet_Between_H : forall A B C,\n Bet A B C -> A<>B -> B<>C -> Between_H A B C.\nProof.\nintros.\nunfold Between_H.\nrepeat split;try assumption.\nintro.\nsubst.\ntreat_equalities.\nintuition.\nQed.\n\nLemma axiom_cong_5' : forall A B C A' B' C', ~ Col_H A B C -> ~ Col_H A' B' C' ->\n           Cong A B A' B' -> Cong A C A' C' -> CongA B A C B' A' C' -> CongA A B C A' B' C'.\nProof.\nintros A B C A' B' C'.\nintros.\nassert (T:=l11_49 B A C B' A' C').\nassert (~ Col A B C).\nintro.\napply cols_coincide_2 in H4.\nintuition.\nassert_diffs.\nintuition.\nQed.\n\n\nLemma axiom_hcong_4_existence :  forall A B C O X P,\n   ~ Col_H P O X -> ~ Col_H A B C ->\n  exists Y, CongA A B C X O Y  (* /\\ ~Col O X Y *) /\\ same_side' P Y O X.\nProof.\nintros.\nrewrite <- cols_coincide in H.\nrewrite <- cols_coincide in H0.\n\nassert(~Col X O P).\nintro.\napply H.\nCol.\nassert(HH:=angle_construction_1 A B C X O P H0 H1).\n\nex_and HH Y.\n\nexists Y.\nsplit.\nassumption.\napply OS_same_side'.\napply invert_one_side.\napply one_side_symmetry.\nassumption.\nQed.\n\nLemma same_side_trans :\n forall A B C l,\n  same_side A B l -> same_side B C l -> same_side A C l.\nProof.\nintros.\napply one_side_same_side.\napply same_side_one_side in H.\napply same_side_one_side in H0.\neapply one_side_transitivity.\napply H.\nassumption.\nQed.\n\nLemma same_side_sym :\n forall A B l,\n  same_side A B l -> same_side B A l.\nProof.\nintros.\napply one_side_same_side.\napply same_side_one_side in H.\napply one_side_symmetry.\nassumption.\nQed.\n\n\nLemma axiom_hcong_4_uniqueness :\n  forall A B C O P X Y Y', ~ Col_H P O X  -> ~ Col_H A B C -> CongA A B C X O Y -> CongA A B C X O Y' -> \n  same_side' P Y O X -> same_side' P Y' O X -> outH O Y Y'.\nProof.\nintros.\nrewrite <- cols_coincide in H.\nrewrite <- cols_coincide in H0.\nassert (T:CongA X O Y X O Y').\neapply conga_trans.\napply conga_sym.\napply H1.\nassumption.\n\napply out_outH.\napply (conga_os__out X).\nassumption.\n\napply same_side_OS in H3.\napply same_side_OS in H4.\napply invert_one_side.\napply one_side_transitivity with P.\napply one_side_symmetry.\nassumption.\nassumption.\nQed.\n\nLemma axiom_conga_comm : forall A B C,\n ~ Col_H A B C -> CongA A B C C B A.\nProof.\nintros.\nrewrite <- cols_coincide in H.\nassert_diffs.\napply conga_pseudo_refl;auto.\nQed.\n\nLemma axiom_congaH_outH_congaH :\n forall A B C D E F A' C' D' F' : Tpoint,\n  CongA A B C D E F ->\n  Between_H B A A' \\/ Between_H B A' A \\/ B <> A /\\ A = A' ->\n  Between_H B C C' \\/ Between_H B C' C \\/ B <> C /\\ C = C' ->\n  Between_H E D D' \\/ Between_H E D' D \\/ E <> D /\\ D = D' ->\n  Between_H E F F' \\/ Between_H E F' F \\/ E <> F /\\ F = F' ->\n  CongA A' B C' D' E F'.\nProof.\nintros.\napply l11_10 with A C D F; trivial; apply l6_6; apply outH_out; auto.\nQed.\n\nLemma axiom_conga_permlr:\nforall A B C D E F : Tpoint, CongA A B C D E F -> CongA C B A F E D.\nProof.\napply Ch11_angles.conga_comm.\nQed.\n\n(*\nLemma axiom_inter_dec : forall l m,\n  (exists P, IncidentL P l /\\ IncidentL P m) \\/ ~ (exists P, IncidentL P l /\\ IncidentL P m).\nProof.\nintros l m;\nelim (inter_dec (P1 l) (P2 l) (P1 m) (P2 m));\nintro; [left|right]; auto.\nQed.\n*)\n\nLemma axiom_conga_refl : forall A B C, ~ Col_H A B C -> CongA A B C A B C.\nProof.\nintros A B C H.\napply Ch11_angles.conga_refl; intro; subst; apply H; apply cols_coincide; Col.\nQed.\n\nEnd T.\n\nSection Tarski_neutral_to_Hilbert_neutral.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nInstance Hilbert_neutral_follows_from_Tarski_neutral : Hilbert_neutral_dimensionless.\nProof.\nexact (Build_Hilbert_neutral_dimensionless Tpoint Line Plane EqL EqL_Equiv EqP EqP_Equiv IncidentL\n       IncidentP axiom_Incid_morphism axiom_Incid_dec axiom_Incidp_morphism axiom_Incidp_dec\n       eq_dec_points axiom_line_existence axiom_line_uniqueness axiom_two_points_on_line PA\n       PB PC lower_dim' axiom_plane_existence axiom_one_point_on_plane axiom_plane_uniqueness\n       axiom_line_on_plane Between_H axiom_between_diff axiom_between_col axiom_between_comm\n       axiom_between_out axiom_between_only_one axiom_pasch Cong cong_right_commutativity\n       axiom_hcong_1_existence cong_inner_transitivity\n        axiom_hcong_3 CongA axiom_conga_refl axiom_conga_comm\n       axiom_conga_permlr axiom_congaH_outH_congaH axiom_hcong_4_existence\n       axiom_hcong_4_uniqueness axiom_cong_5').\nDefined.\n\nEnd Tarski_neutral_to_Hilbert_neutral.\n\nSection Tarski_neutral_2D_to_Hilbert_neutral_2D.\n\nContext `{T2D:Tarski_2D}.\n\nInstance Hilbert_2D_follows_from_Tarski_2D : Hilbert_neutral_2D Hilbert_neutral_follows_from_Tarski_neutral.\nProof.\nsplit.\nintros A B C l HNCol HNCl Hcut.\napply axiom_pasch with (Plan A B C HNCol); trivial;\n  unfold IncidentLP, IncidentP; intros; try (apply all_coplanar).\nDefined.\n\nEnd Tarski_neutral_2D_to_Hilbert_neutral_2D.\n\nSection Tarski_neutral_3D_to_Hilbert_neutral_3D.\n\nContext `{T3D:Tarski_3D}.\n\nLemma lower_dim_3' : {A : Tpoint & {B : Tpoint & {C : Tpoint & {D |\n  ~ exists p, IncidentP A p /\\ IncidentP B p /\\ IncidentP C p /\\ IncidentP D p}}}}.\nProof.\nexists S1, S2, S3, S4.\nintros [p]; spliter.\napply tarski_axioms.lower_dim_3, plane_cop with p; assumption.\nQed.\n\nInstance Hilbert_3D_follows_from_Tarski_3D : Hilbert_neutral_3D Hilbert_neutral_follows_from_Tarski_neutral.\nProof.\ndestruct lower_dim_3' as [A [B [C [D n]]]].\nexists A B C D; [|assumption].\nclear A B C D n.\nintros A p q HAp HAq.\ndestruct p as [P1 P2 P3 HP].\ndestruct q as [Q1 Q2 Q3 HQ].\nunfold IncidP in *; simpl in *; unfold IncidentP in *; simpl in *.\nassert (pi : plane_intersection_axiom).\ncut upper_dim_3_axiom.\napply upper_dim_3_equivalent_axioms; simpl; tauto.\nunfold upper_dim_3_axiom.\napply upper_dim_3.\napply pi; assumption.\nDefined.\n\nEnd Tarski_neutral_3D_to_Hilbert_neutral_3D.\n\nSection Tarski_Euclidean_to_Hilbert_Euclidean.\n\nContext `{TE:Tarski_euclidean}.\n\n(** * Group Parallels *)\n\nDefinition Para := fun l m =>\n  (~ exists X, IncidentL X l /\\ IncidentL X m) /\\ exists p, IncidentLP l p /\\ IncidentLP m p.\n\nLemma Para_Par : forall A B C D (HAB : A<>B) (HCD: C<>D),\n Para (Lin A B HAB) (Lin C D HCD) -> Par A B C D.\nProof.\nunfold Para, IncidentL, Par, Par_strict; simpl.\nintros.\ndestruct H as [HNI [p []]].\nleft.\nrepeat split;auto.\napply plane_cop with p; [apply H|apply H|apply H0..]; unfold IncidentL; simpl; Col.\nQed.\n\nLemma axiom_euclid_uniqueness :\n  forall l P m1 m2,\n  ~ IncidentL P l ->\n   Para l m1 -> IncidentL P m1 ->\n   Para l m2 -> IncidentL P m2 ->\n   EqL m1 m2.\nProof.\nintros.\ndestruct l as [A B HAB].\ndestruct m1 as [C D HCD].\ndestruct m2 as [C' D' HCD'].\nunfold IncidentL in *;simpl in *.\napply Para_Par in H0.\napply Para_Par in H2.\nelim (tarski_s_euclid_implies_playfair euclid A B C D C' D' P H0 H1 H2 H3);intros.\napply axiom_line_uniqueness with C' D';\nunfold IncidentL;simpl;Col.\nQed.\n\nInstance Hilbert_euclidean_follows_from_Tarski_euclidean :\n  Hilbert_euclidean Hilbert_neutral_follows_from_Tarski_neutral.\nProof.\nsplit.\napply axiom_euclid_uniqueness.\nDefined.\n\nInstance Hilbert_euclidean_ID_follows_from_Tarski_euclidean :\n  Hilbert_euclidean_ID Hilbert_euclidean_follows_from_Tarski_euclidean.\nProof.\nsplit.\nintros l m.\nassert (ID : decidability_of_intersection).\napply strong_parallel_postulate_implies_inter_dec.\ncut tarski_s_parallel_postulate.\napply equivalent_postulates_without_decidability_of_intersection_of_lines_bis; simpl; tauto.\nunfold tarski_s_parallel_postulate.\napply euclid.\ndestruct l as [L1 L2 HL].\ndestruct m as [M1 M2 HM].\nsimpl; unfold IncidentL; simpl.\napply ID.\nDefined.\n\nEnd Tarski_Euclidean_to_Hilbert_Euclidean.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Meta_theory/Models/tarski_to_hilbert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8175744739711884, "lm_q1q2_score": 0.7327522472013083}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Omega.\n\nSet Implicit Arguments.\n\nParameter Var : Type.\n\n(* Definition of the terms of combinatory algebras *)\n\nInductive clterm : Type :=\n | cl_S   : clterm\n | cl_K   : clterm\n | cl_I   : clterm\n | cl_app : clterm -> clterm -> clterm\n | cl_var : Var -> clterm.\n   \n(* Some short notations *)\n   \nInfix \"o\" := (@cl_app) (at level 61, left associativity).\nNotation \" 'µ' x \" := (@cl_var x) (at level 0).\n  \n(* an n-iterate of cl_K *)\n  \nFixpoint cl_Kn n :=\n  match n with\n    | 0   => cl_K\n    | S n => cl_K o cl_Kn n\n  end.\n    \n(* A measure of the size of terms *)\n\nFixpoint cl_size f :=\n  match f with\n    | f o g => 1 + cl_size f + cl_size g\n    | _     => 1\n  end.\n    \n(** Some more short notations \n    Beware that S masks the S : nat -> nat\n    successor constructor of the type nat \n*)\n\nNotation K := cl_K.\nNotation S := cl_S.\nNotation I := cl_I.\n  \n(* cl_* constructors are injective *)\n  \nFact cl_var_inj p q : µ p = µ q -> p = q.\nProof.\n  injection 1; auto.\nQed.\n  \nFact cl_app_inj f g a b : f o a = g o b -> f = g /\\ a = b.\nProof.\n  injection 1; auto.\nQed.\n\n(* The size of cl_Kn *)\n\nFact cl_Kn_size i : cl_size (cl_Kn i) = 2*i+1.\nProof.\n  induction i; simpl; omega.\nQed.\n\n(* The map n -> cl_Kn is injective as well *)\n\nCorollary cl_Kn_inj i j : cl_Kn i = cl_Kn j -> i = j.\nProof.\n  intros H.\n  apply f_equal with (f := cl_size) in H.\n  do 2 rewrite cl_Kn_size in H.\n  omega.\nQed.\n\n", "meta": {"author": "DmxLarchey", "repo": "Combinatory-Logic-for-students", "sha": "0bceaae5f102ce59b3f6bc872beaf728f371ba59", "save_path": "github-repos/coq/DmxLarchey-Combinatory-Logic-for-students", "path": "github-repos/coq/DmxLarchey-Combinatory-Logic-for-students/Combinatory-Logic-for-students-0bceaae5f102ce59b3f6bc872beaf728f371ba59/cl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7327477961712897}}
{"text": "Require Export D.\n\n\n\n(** **** Problem : 2 stars (double_plus) *)\n\n(* See [D.v] for the definition of [double] *)\n\n(** Use induction to prove this simple fact about [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.  \n  intros. induction n. simpl. reflexivity.\n  simpl. rewrite -> IHn.\n  Lemma plus_Smn_mSn : forall m n:nat, S (m + n) = m + S n.\n  Proof.\n      intros. induction m. reflexivity.\n      simpl. rewrite -> IHm. reflexivity. Qed.\n  rewrite -> plus_Smn_mSn. reflexivity.\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/02/P05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7327477918253864}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import ZArith.\nRequire Import Rbase.\nDefinition unit  := unit.\n\nParameter mark : Type.\n\nParameter at1: forall (a:Type), a -> mark  -> a.\n\nImplicit Arguments at1.\n\nParameter old: forall (a:Type), a  -> a.\n\nImplicit Arguments old.\n\nInductive ref (a:Type) :=\n  | mk_ref : a -> ref a.\nImplicit Arguments mk_ref.\n\nDefinition contents (a:Type)(u:(ref a)): a :=\n  match u with\n  | mk_ref contents1 => contents1\n  end.\nImplicit Arguments contents.\n\nInductive even : Z -> Prop :=\n  | even_0 : (even 0%Z)\n  | even_odd : forall (x:Z), (even x) -> (even (x + 2%Z)%Z).\n\nTheorem even_not_odd : forall (x:Z), (even x) -> ~ (even (x + 1%Z)%Z).\n(* YOU MAY EDIT THE PROOF BELOW *)\nassert (nonneg: forall x:Z, even x -> (x >= 0)%Z).\ninduction 1; auto with *.\ninduction 1.\nred; intro.\ninversion H.\nassert (h: (x = -1)%Z) by omega.\nabsurd (-1 >= 0)%Z.\nomega.\napply nonneg.\nrewrite <- h; auto.\nintuition.\ninversion H0.\nassert (h: (x = -3)%Z) by omega.\nabsurd (-3 >= 0)%Z.\nomega.\napply nonneg.\nrewrite <- h; auto.\nassert (x0 = x+1)%Z by omega.\nsubst x0; auto.\nQed.\n(* DO NOT EDIT BELOW *)\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/examples/sf/sf_WP_HoareLogic_even_not_odd_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7327477854291808}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) (y : natural) : natural :=\n  mult x (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj2411_coqofml_aeug82.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7326337754567925}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult (Succ y) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj206_coqofml_wDHnor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7326337687643334}}
{"text": "(** CS6225 PSet5a *)\n\n(** * 6.822 Formal Reasoning About Programs, Spring 2018 - Pset 3 *)\n\nRequire Import Frap.\n\n(* In this problem set, we'll get some experience with higher-order functions,\n * which are functions that themselves take functions as arguments!\n *)\n\nInductive tree {A} :=\n| Leaf\n| Node (l : tree) (d : A) (r : tree).\nArguments tree : clear implicits.\n\nFixpoint flatten {A} (t : tree A) : list A :=\n  match t with\n  | Leaf => []\n  | Node l d r => flatten l ++ d :: flatten r\n  end.\n\nModule Type S.\n\n  (* Define the identity function [id], which just returns its\n   * argument without modification.\n   *)\n  Parameter id : forall {A : Type}, A -> A.\n  (* 5 points *)\n\n  (* [compose] is another higher-order function: [compose g f]\n   * applies [f] to its input and then applies [g]. Argument order\n   * follows the general convention of functional composition in\n   * mathematics denoted by the small circle.\n   *)\n  Parameter compose : forall {A B C : Type}, (B -> C) -> (A -> B) -> A -> C.\n  (* 5 points *)\n\n  (* If we map the [id] function over any list, we get the\n   * same list back.\n   *)\n  Axiom map_id : forall {A : Type} (xs : list A),\n    map id xs = xs.\n  (* 5 points *)\n\n  (* If we map the composition of two functions over the list,\n   * it's the same as mapping the first function over the whole list\n   * and then mapping the second function over that resulting list.\n   *)\n  Axiom map_compose : forall {A B C : Type} (g : B -> C) (f : A -> B)\n                             (xs : list A),\n    map (compose g f) xs = map g (map f xs).\n  (* 5 points *)\n\n  (* Next we can show some classic properties that demonstrate a\n   * certain sense in which [map] only modifies the elements of\n   * a list but preserves its structure: [map_length] shows it\n   * preserves length, and [map_append] and [map_rev] show that\n   * it commutes with [++] and [rev], respectively.\n   * For each of [length], [++], and [rev], it doesn't matter\n   * whether we apply [map] before the operation or after.\n   *)\n  Axiom map_length : forall {A B : Type} (f : A -> B) (xs : list A),\n    length (map f xs) = length xs.\n  (* 5 points *)\n\n  Axiom map_append : forall {A B : Type} (f : A -> B) (xs ys : list A),\n    map f (xs ++ ys) = map f xs ++ map f ys.\n  (* 5 points *)\n\n  Axiom map_rev : forall {A B : Type} (f : A -> B) (xs : list A),\n    map f (rev xs) = rev (map f xs).\n  (* 5 points *)\n\n  (* [fold] is a higher-order function that is even more general\n   * than [map]. In essence, [fold f z] takes as input a list\n   * and produces a term where the [cons] constructor is\n   * replaced by [f] and the [nil] constructor is replaced\n   * by [z].\n   *\n   * [fold] is a \"right\" fold, which associates the binary operation\n   * the opposite way as the [fold_left] function that we defined\n   * in lecture.\n   *)\n  Parameter fold : forall {A B : Type}, (A -> B -> B) -> B -> list A -> B.\n  (* 5 points *)\n\n  (* For instance, we should have\n       fold plus 10 [1; 2; 3]\n     = 1 + (2 + (3 + 10))\n     = 16\n   *)\n  Axiom fold_example : fold plus 10 [1; 2; 3] = 16.\n  (* 5 points *)\n\n  (* Prove that [map] can actually be defined as a particular\n   * sort of [fold].\n   *)\n  Axiom map_is_fold : forall {A B : Type} (f : A -> B) (xs : list A),\n    map f xs = fold (fun x ys => cons (f x) ys) nil xs.\n  (* 5 points *)\n\n  (* Since [fold f z] replaces [cons] with [f] and [nil] with\n   * [z], [fold cons nil] should be the identity function.\n   *)\n  Axiom fold_id : forall {A : Type} (xs : list A),\n    fold cons nil xs = xs.\n  (* 5 points *)\n\n  (* If we apply [fold] to the concatenation of two lists,\n   * it is the same as folding the \"right\" list, and using\n   * that as the starting point for folding the \"left\" list.\n   *)\n  Axiom fold_append : forall {A : Type} (f : A -> A -> A) (z : A)\n                        (xs ys : list A),\n    fold f z (xs ++ ys) =\n    fold f (fold f z ys) xs.\n  (* 5 points *)\n\n  (* Using [fold], define a function that computes the\n   * sum of a list of natural numbers.\n   *)\n  Parameter sum : list nat -> nat.\n  (* 5 points *)\n\n  (* Note that [simplify] fails to reduce [ sum [1; 2; 3] ].\n   * This is due to a quirk of [simplify]'s behavior: because\n   * unfolding [sum] does not present an immediate opportunity\n   * for reduction (since [fold] will still need to be unfolded\n   * to its fixpoint definition, no simplification is performed).\n   * A simple remedy is to use the tactic [unfold sum] prior to\n   * calling [simplify]. This should come in handy for future proofs\n   * involving definitions that use [fold], too.\n   *)\n  Axiom sum_example : sum [1; 2; 3] = 6.\n  (* 5 points *)\n\n  (* Using [fold], define a function that computes the\n   * conjunction of a list of Booleans (where the 0-ary\n   * conjunction is defined as [true]).\n   *)\n  Parameter all : list bool -> bool.\n  (* 5 points *)\n\n  Axiom all_example : all [true; false; true] = false.\n  (* 5 points *)\n\n  (* The following two theorems, [sum_append] and [all_append],\n   * say that the sum of the concatenation of two lists\n   * is the same as summing each of the lists first and then\n   * adding the result.\n   *)\n  Axiom sum_append : forall (xs ys : list nat),\n      sum (xs ++ ys) = sum xs + sum ys.\n  (* 5 points *)\n\n  Axiom all_append : forall (xs ys : list bool),\n      all (xs ++ ys) = andb (all xs) (all ys).\n  (* 5 points *)\n\n  (* Just like we defined [map] for lists, we can similarly define\n   * a higher-order function [tree_map] which applies a function on\n   * elements to all of the elements in the tree, leaving the tree\n   * structure intact.\n   *)\n  Parameter tree_map : forall {A B : Type}, (A -> B) -> tree A -> tree B.\n  (* 5 points *)\n\n  Axiom tree_map_example :\n    tree_map (fun x => x + 1) (Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 (Node Leaf 4 Leaf)))\n    = (Node (Node Leaf 2 Leaf) 3 (Node Leaf 4 (Node Leaf 5 Leaf))).\n  (* 5 points *)\n\n  (* [tree_map_flatten] shows that [map]\n   * and [tree_map] are related by the [flatten] function.\n   *)\n  Axiom tree_map_flatten : forall {A B : Type} (f : A -> B) (t : tree A),\n      flatten (tree_map f t) = map f (flatten t).\n  (* 5 points *)\n\n  (* Using [fold], define a function that composes a list of functions,\n   * applying the *last* function in the list *first*.\n   *)\n  Parameter compose_list : forall {A : Type}, list (A -> A) -> A -> A.\n  (* 5 points *)\n\n  Axiom compose_list_example :\n    compose_list [fun x => x + 1; fun x => x * 2; fun x => x + 2] 1 = 7.\n  (* 5 points *)\n\n  (* Show that [sum xs] is the same as converting each number\n   * in the list [xs] to a function that adds that number,\n   * composing all of those functions together, and finally\n   * applying that large composed function to [0].\n   * Note that function [plus], when applied to just one number as an\n   * argument, returns a function over another number, which\n   * adds the original argument to it!\n   *)\n  Axiom compose_list_map_add_sum : forall (xs : list nat),\n    compose_list (map plus xs) 0 = sum xs.\n  (* 5 points *)\n\nEnd S.\n", "meta": {"author": "kayceesrk", "repo": "cs6225_s20_iitm", "sha": "1cb2ad5a92ed9fadd0bc23218c159a762301ae0f", "save_path": "github-repos/coq/kayceesrk-cs6225_s20_iitm", "path": "github-repos/coq/kayceesrk-cs6225_s20_iitm/cs6225_s20_iitm-1cb2ad5a92ed9fadd0bc23218c159a762301ae0f/assignments/pset5a/Pset5aSig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.7326146354910006}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(* $Id: Field.v 14641 2011-11-06 11:59:10Z herbelin $ *)\n\n(**** Tests of Field with real numbers ****)\n\nRequire Import Reals RealField.\nOpen Scope R_scope.\n\n(* Example 1 *)\nGoal\nforall eps : R,\neps * (1 / (2 + 2)) + eps * (1 / (2 + 2)) = eps * (1 / 2).\nProof.\n  intros.\n   field.\nQed.\n\n(* Example 2 *)\nGoal\nforall (f g : R -> R) (x0 x1 : R),\n(f x1 - f x0) * (1 / (x1 - x0)) + (g x1 - g x0) * (1 / (x1 - x0)) =\n(f x1 + g x1 - (f x0 + g x0)) * (1 / (x1 - x0)).\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 3 *)\nGoal forall a b : R, 1 / (a * b) * (1 / (1 / b)) = 1 / a.\nProof.\n  intros.\n   field.\nAbort.\n\nGoal forall a b : R, 1 / (a * b) * (1 / 1 / b) = 1 / a.\nProof.\n  intros.\n   field_simplify_eq.\nAbort.\n\nGoal forall a b : R, 1 / (a * b) * (1 / 1 / b) = 1 / a.\nProof.\n  intros.\n   field_simplify (1 / (a * b) * (1 / 1 / b)).\nAbort.\n\n(* Example 4 *)\nGoal\nforall a b : R, a <> 0 -> b <> 0 -> 1 / (a * b) / (1 / b) = 1 / a.\nProof.\n  intros.\n   field; auto.\nQed.\n\n(* Example 5 *)\nGoal forall a : R, 1 = 1 * (1 / a) * a.\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 6 *)\nGoal forall a b : R, b = b * / a * a.\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 7 *)\nGoal forall a b : R, b = b * (1 / a) * a.\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 8 *)\nGoal forall x y : R,\n  x * (1 / x + x / (x + y)) =\n  - (1 / y) * y * (- (x * (x / (x + y))) - 1).\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 9 *)\nGoal forall a b : R, 1 / (a * b) * (1 / 1 / b) = 1 / a -> False.\nProof.\nintros.\nfield_simplify_eq in H.\nAbort.\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/Field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.732614620615625}}
{"text": "Require Import Problem Arith.\nFrom mathcomp Require Import ssreflect.\n\nLemma L0: forall n m, product_of_range n (S m) = (S n) * product_of_range (S n) m.\nProof.\n  by rewrite /=.\nQed.\n\nLemma L1: forall n m, product_of_range n (S m) = (n + S m) * product_of_range n m.\nProof.\n  intros n m.\n  revert n.\n  elim: m => [| m' IHm'].\n  intros n.\n  by rewrite /= !Nat.mul_1_r Nat.add_1_r.\n  intros.\n  rewrite L0.\n  rewrite IHm'.\n  rewrite L0.\n  by ring.\nQed.\n\nTheorem solution: task.\nProof.\n  rewrite /task.\n  intros n m.\n  revert n.\n  elim m => [| m' IHm].\n  rewrite /product_of_range. \n  exists 1. \n  by rewrite /=.\n  intros n.\n  elim n => [| n' IHn].\n  exists 1.\n  by rewrite /=.\n  case: (IHm (S n')) => p Hp.\n  case: IHn => k Hk.\n  exists (p + k).\n  rewrite L1.\n  rewrite L0 in Hk.\n  repeat rewrite Nat.mul_add_distr_r.\n  rewrite Hk.\n  rewrite Hp.\n  rewrite (_ : S m' * (p * product_of_range 0 m') = p * ((0 + S m') * product_of_range 0 m')).\n  rewrite -L1.\n  by rewrite Nat.add_comm.\n  rewrite Nat.add_0_l.\n  rewrite !Nat.mul_assoc.\n  by rewrite (Nat.mul_comm (S m') p).\nQed.", "meta": {"author": "matonix", "repo": "topprover", "sha": "c98d06ead25b865ef4b92313ef2a0d7f73422c33", "save_path": "github-repos/coq/matonix-topprover", "path": "github-repos/coq/matonix-topprover/topprover-c98d06ead25b865ef4b92313ef2a0d7f73422c33/7/Example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7326019413127972}}
{"text": "Require Import Arith.\nRequire Import Ascii.\nRequire Import Nat.\nRequire Import Bool.\nRequire Import Coq.Strings.Byte.\nRequire Import Strings.String.\nScheme Equality for string.\nLocal Open Scope string_scope.\n\nInductive NaturaL : Type :=\n| TypeNat : nat -> NaturaL\n| ErrorNat : NaturaL. \n\nInductive BooleaN : Type :=\n| TypeBool : bool -> BooleaN\n| ErrorBool : BooleaN.\n\nInductive StringS : Type :=\n| TypeString : string -> StringS\n| ErrorString : StringS.\n\n\nInductive DataS :=\n| undecl : DataS\n| assign : DataS\n| default : DataS\n| nat_type : NaturaL -> DataS\n| bool_type : BooleaN -> DataS.\n\nDefinition eqb_string (x y : String.string) : bool :=\n  if string_dec x y then true else false.\n\nCoercion TypeNat : nat >-> NaturaL.\nCoercion TypeBool : bool >-> BooleaN.\nCoercion TypeString : string >->StringS.\n\nScheme Equality for DataS.\n\nDefinition Env := string -> DataS.\n\n\nInductive list (T : Type) : Type :=\n| null\n| cons (t : T) (l : list T).\n\nCheck cons NaturaL 4 (cons NaturaL 3 (null NaturaL)).\nCheck cons BooleaN false (cons BooleaN true (null BooleaN)).\n\nArguments null {T}.\nNotation \"[]\" := null.\n\nNotation \"{ X , .. , Y }\" := (cons NaturaL X .. (cons NaturaL Y []) ..).\nNotation \"{ X ; .. ; Y }\" := (cons BooleaN X .. (cons BooleaN Y []) ..).\nNotation \"{ X ;;; .. ;;; Y }\" := (cons StringS X .. (cons StringS Y []) ..).\n\nCheck {1, 2, 3}.\nCheck {false; true; true; false}.\n\nDefinition listanat1 := {1, 2, 3, 4, 5}.\nDefinition listanat2 := {1, 4, 6, 8, 9}.\nDefinition listabool := {true; false; true; false; false}.\nDefinition listastring := { \"gabriel\" ;;; \"gabriela\" }.\n\n Inductive Vectori : Type :=\n| vector_natural : list NaturaL -> Vectori\n| vector_boolean : list BooleaN -> Vectori\n| vector_string : list StringS -> Vectori\n| Matrice : list Vectori -> Vectori. \n\n\nCheck vector_natural listanat1.\nCheck vector_boolean listabool.\n\nNotation \"{ X & .. & Y }\" := (cons Vectori X .. (cons Vectori Y []) ..).\nCheck Matrice { (vector_natural listanat1) & ( vector_natural listanat2) }.\n\nNotation \"'[Natural]' = V \" := (vector_natural V) (at level 20).\nNotation \"'[Boolean]' = V \" := (vector_boolean V) (at level 20).\nNotation \"'[String]' = V \" := (vector_string V) (at level 20).\nNotation \"'[[Matrice]]' = V\" := (Matrice V) (at level 20).\n\n\nDefinition vector_nat := [Natural] = listanat1.\nDefinition vector_bool := [Boolean] = listabool.\nDefinition vector_string1 := [String] = listastring.\n\n\nCompute vector_nat.\nCompute vector_bool.\nCompute vector_string.\n\n\n(*EXPRESII ARITMETICE *)\nInductive AExp :=\n| a_variabila : string -> AExp\n| a_numar : NaturaL -> AExp\n| a_plus : AExp -> AExp -> AExp\n| a_mul : AExp -> AExp -> AExp\n| a_min : AExp -> AExp -> AExp\n| a_mod : AExp -> AExp -> AExp \n| a_div : AExp -> AExp -> AExp.\n\nInductive Var := n | i | x | y | sum.\n\n(*Notatii folosite pentru expresii aritmetice*)\n\nNotation \"A +' B\" := (a_plus A B) (at level 48).\nNotation \"A -' B\" := (a_min A B) (at level 48).\nNotation \"A /' B\" := (a_div A B) (at level 46).\nNotation \"A *' B\" := (a_mul A B) (at level 46).\nNotation \"A %' B\" := (a_mod A B) (at level 47).\n\nCoercion a_numar: NaturaL >-> AExp.\nCoercion a_variabila: string >-> AExp.\n\nCheck \"y\".\nCheck( 1 %' 2).\n\nInductive BExp :=\n| btrue \n| bfalse\n| bvar: string->BExp\n| b_egal : AExp -> AExp -> BExp (* sintaxa pentru egal *)\n| b_less : AExp -> AExp -> BExp\n| b_lessequal : AExp -> AExp -> BExp\n| b_greater : AExp -> AExp -> BExp\n| b_greaterequal : AExp -> AExp -> BExp\n| b_notegal : AExp -> AExp -> BExp\n| b_not : BExp -> BExp (*sintaxa pentru not*)\n| b_and : BExp -> BExp -> BExp (*sintaxa pentru and *)\n| b_or : BExp -> BExp -> BExp (*sintaxa pentru or*)\n| b_xor : BExp -> BExp -> BExp. (*sintaxa pentru xor*)\nCoercion bvar: string>->BExp.\n(*Notatii  pentru expresii booleane*)\nNotation \"! A\" := (b_not A) (at level 52).\nNotation \"A &&' B\" := (b_and A B) (at level 53).\nNotation \"A ||' B\" := (b_or A B) (at level 54).\nNotation \"A \\\\' B \" := (b_xor A B) (at level 54).\nNotation \"A <' B\" := (b_less A B) (at level 70, no associativity).\nNotation \"A <=' B\" := (b_lessequal A B) (at level 70, no associativity).\nNotation \"A >' B\" := (b_greater A B) (at level 70, no associativity).\nNotation \"A >=' B\" := (b_greaterequal A B) (at level 70, no associativity).\nNotation \"A ==' B\" := (b_egal A B) (at level 70, no associativity).\nNotation \"A !=' B\" := (b_notegal A B) (at level 70, no associativity).\n\nCheck 4 +' 5.\nCheck (btrue &&' bfalse ).\nCheck ( ! btrue).\nCheck( btrue ||' bfalse).\nCheck( btrue \\\\' bfalse).\nCheck( 1 <' 2).\nCheck( 1 <=' 2).\n\n(* Functii predefinite *)\nInductive Functii :=\n| Max : AExp -> AExp -> Functii\n| Min : AExp -> AExp -> Functii\n| Egal : AExp -> AExp -> Functii\n| Putere : AExp -> AExp -> Functii.\n\nNotation \"'Max' '(' A , B ')'\" := (Max A B) (at level 50).\nNotation \"'Min' '(' A , B ')'\" := (Min A B) (at level 50).\nNotation \"'Egal' '(' A , B ')'\" := (Egal A B) (at level 50).\nNotation \"'Putere' '(' A , B ')'\" := (Putere A B) (at level 57).\n\nCheck ( Max(1, 2) ).\nCheck ( Min(1, 2) ).\nCheck ( Egal(19 +' 23 *' 3, 22 /' 4 -' 2) ).\nCheck ( Putere(2, 3) ).\n\nInductive Stmt : Type :=\n(*DECLARARI*)\n| declarareNatural :  string -> Stmt\n| declarareBoolean :  string -> Stmt\n| declarareString :  string -> Stmt\n\n(*ATRIBURI*)\n| atribuireNatural : string -> AExp -> Stmt\n| atribuireBoolean : string -> BExp -> Stmt\n| atribuireString : string -> AExp -> Stmt\n\n(*INITIALIZARI*)\n| initializareNatural : string -> AExp -> Stmt\n| initializareBoolean : string -> BExp -> Stmt\n| initializareString : string -> AExp -> Stmt\n\n(*INSTRUCTIUNI*)\n| pop : string -> Stmt\n| secventa : Stmt -> Stmt -> Stmt\n| incrementare : string -> AExp -> Stmt (*sintaxa pentru incrementare*)\n| decrementare : string -> AExp -> Stmt (*sintaxa pentru decrementare*)\n| if_then_else : BExp -> Stmt -> Stmt -> Stmt\n| if_then : BExp -> Stmt -> Stmt \n| while_do : BExp -> Stmt -> Stmt \n| for_do : Stmt -> BExp -> Stmt -> Stmt -> Stmt\n| break : Stmt\n| continue : Stmt\n| functie : string -> Stmt -> Stmt\n| comentariu  : string -> Stmt (*sintaxa pentru comentarii*)\n\n(*VECTORI*)\n| declarare_vector_natural : string -> Stmt\n| declarare_vector_boolean : string -> Stmt\n| declarare_vector_string : string -> Stmt\n| declarare_matrice : string -> Stmt\n\n| initializare_vector_natural : string -> list NaturaL -> Stmt\n| initializare_vector_boolean : string -> list BooleaN -> Stmt\n| initializare_vector_string : string -> list StringS-> Stmt\n| initializare_matrice : string -> list Vectori -> Stmt\n\n| element: string -> nat -> Stmt\n\n| valoareElemNatural : string -> nat -> NaturaL -> Stmt\n| valoareElemBoolean : string -> nat -> BooleaN -> Stmt\n| valoareElemString : string -> nat -> StringS-> Stmt\n| valoareElemMatrice : string -> nat -> Vectori -> Stmt\n\n| adaugareNatural : string -> NaturaL -> Stmt\n| adaugareBoolean : string -> BooleaN -> Stmt\n| adaugareString : string -> StringS -> Stmt\n| adaugareMatrice : string -> Vectori -> Stmt \n\n| eliminare : string -> Stmt.\n\n \nNotation \"'natural' S\" := (declarareNatural S) (at level 79).\nNotation \"'boolean' S\" := (declarareBoolean S) (at level 79).\nNotation \"'char' S\" := (declarareString S) (at level 79).\n\nNotation \"S =nat= X\" := (atribuireNatural S X) (at level 80).\nNotation \"S =bool= X\" := (atribuireBoolean S X) (at level 80).\nNotation \"S =string= X\" := (atribuireString S X) (at level 80).\n\nNotation \"'natural' S ::= A\" := (initializareNatural S A) (at level 78).\nNotation \"'boolean' S [=] A\" := (initializareBoolean S A) (at level 78).\nNotation \"'char' S [=] A\" := (initializareString S A) (at level 78).\n\nNotation \"S1 ;; S2\" := (secventa S1 S2 ) (at level 98, left associativity).\nNotation \"I ++\" := (incrementare I 1) (at level 60).\nNotation \"D --\" := (decrementare D 1) (at level 60).\nNotation \"'If' ( A ) 'Then' ( S1 ) 'Else' ( S2 ) 'EndIF'\" := (if_then_else A S1 S2) (at level 97).\nNotation \"'If' ( A ) 'Then' ( S ) 'EndIF1'\" := (if_then A S ) (at level 97).\nNotation \"'While' ( C ) # S # 'EndWhile' \" := (while_do C S) (at level 97).\nNotation \"'For' ( S1 ';' C ';' S2 ) { S3 }  'EndF'\" := (for_do S1 C S2 S3) (at level 97).\n\n\n\nNotation \"'Break'\" := (break) (at level 97).\nNotation \"'Continue'\" := (continue) (at level 97).\nNotation \" // A \\\\  \" := (comentariu A) (at level 99).\nNotation \" 'f' ( A ) { B } \" := (functie A B) (at level 90).\nNotation \"'switch'  'case' ( A ) ( B ) ( 'case' ( C )  ( D ) 'default' ( E ))\" := (if_then_else A B (if_then_else C D E)) (at level 66).\n\nNotation \"[Is_V_Natural] V\" := (declarare_vector_natural V) (at level 79).\nNotation \"[Is_V_Boolean] V\" := (declarare_vector_boolean V) (at level 79).\nNotation \"[Is_V_String] V\" := (declarare_vector_string V) (at level 79).\nNotation \"[Is_V_Matrice] V\" := (declarare_matrice V) (at level 79).\n\nNotation \"[Natural] V ::= W\" := (initializare_vector_natural V W) (at level 79).\nNotation \"[Boolean] V ::= W\" := (initializare_vector_boolean V W) (at level 79).\nNotation \"[String] V ::= W\" := (initializare_vector_string V W) (at level 79).\nNotation \"[[Matrice]] V ::= W\" := (initializare_matrice V W) (at level 79).\n\nNotation \"V [ P ]\" := (element V P)(at level 79).\n\nNotation \"V [ P ] :n= W\" := (valoareElemNatural V P W) (at level 78). \nNotation \"V [ P ] :b= W\" := (valoareElemBoolean V P W) (at level 78). \nNotation \"V [ P ] :s= W\" := (valoareElemString V P W) (at level 78). \nNotation \"V [ P ] :m= W\" := (valoareElemMatrice V P W) (at level 78). \n\nNotation \"pushnat( V ) X\" := (adaugareNatural V X) (at level 79).\nNotation \"pushbool( V ) X\" := (adaugareBoolean V X) (at level 79).\nNotation \"pushstring( V ) X\" := (adaugareString V X) (at level 79).\nNotation \"pushmatrice( V ) X\" := (adaugareMatrice V X) (at level 79).\n\nNotation \"pop ( V )\" := (pop V) (at level 79).\n\nCheck ( char \"c\" ) .\nCheck( boolean \"aux\").\nCheck( natural \"i\").\nCheck (\"i\" =nat= 1).\nCheck( \"i\" =bool= btrue).\nCheck( \"i\" =string= \"c\").\nCheck( \"i\" ++).\nCheck( \"a\" --).\nCheck( Break).\nCheck( Continue).\nCheck(  // \"acesta este un comentariu\" \\\\ ).\nCheck( If ( btrue ) Then ( \"i\" =nat= 1 ) EndIF1 ).\nCheck( \"s\" [ 23 ] :n= 434).\nCheck( \"s\" [ 23 ] :b= TypeBool true).\nCheck( pushnat( \"v\" ) 43 ).\nCheck( pushbool( \"v\" ) TypeBool true ).\nCheck( pushstring( \"v\" ) \"string\" ).\nCheck( pop ( \"v\" ) ).\n\nDefinition program1 :=\nboolean \"is_bool\";;\n\"is_bool\" =bool= btrue ;;\n\"is_bool\" =bool= \"is_bool\" &&' bfalse ;;\n[Is_V_Natural] \"vec\";;\npushnat( \"vec\" ) 1 ;;\npushnat( \"vec\" ) 2 ;;\npop (\"vec\");;\npushnat( \"vec\" ) 3 ;;\nnatural \"t\";;\n\"t\" =nat= 0 ;;\nnatural \"x\" ;;\n\"t\" =nat= 4 ;;\nWhile ( \"x\" <=' 1000 ) #\n\t\"x\" ++ ;;\n\tIf ( \"x\" %' 3 ==' 0 ) Then ( \"x\" =nat= \"x\" +' 3 ;; \"t\" =nat= \"t\" +' 1 ) EndIF1\n # EndWhile.\nCheck program1.\n\n\nDefinition program2 :=\nnatural \"a\" ;;\nnatural \"b\" ;;\nnatural \"c\" ;; // \"exemplu de comentariu\" \\\\ ;;\n\"c\" =nat= \"a\" +' \"b\" ;;\n\"c\" ++ ;;\nBreak ;;\nnatural  \"i\" ;;\nnatural \"p\" ;;\nIf ( btrue ) Then ( \"i\" =nat= 1 ) EndIF1 .\n\nCheck program2.\n\n\n", "meta": {"author": "Gabriela-Loghin", "repo": "Compiler-c-coq", "sha": "87911fc917cd026ed3fc1b421e20b1ec24f7edc5", "save_path": "github-repos/coq/Gabriela-Loghin-Compiler-c-coq", "path": "github-repos/coq/Gabriela-Loghin-Compiler-c-coq/Compiler-c-coq-87911fc917cd026ed3fc1b421e20b1ec24f7edc5/sintaxa_plp_proiect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7325538798662172}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import Nat.\n\n\n\nFixpoint myNth {X : Type} (n : nat) (ls : list X) : option X := \nmatch ls with\n| [] => None\n| x::xs => match n with \n           | 0 => None \n           | (S m) => if eqb m 0 then Some x else myNth m xs\n           end\nend.\n\nTheorem emptyList {X : Type} (n : nat) : myNth n ([] : list X) = None.\nProof.\n  destruct n; auto.\nQed.\n\nTheorem zeroNth {X : Type} (ls : list X) : myNth 0 ls = None.\nProof.\n  destruct ls; auto.\nQed.\n\nTheorem leLtN {X : Type} (ls : list X) (n : nat) : \n  length ls < n -> myNth n ls = None.\nProof.\n  generalize dependent n.\n  induction ls; intros.\n  + destruct n; auto.\n  + destruct n.\n    - inversion H.\n    - destruct n.\n      * inversion H.\n        inversion H1.\n      * assert (myNth (S (S n)) (a::ls) = myNth (S n) ls).\n        { clear; reflexivity. }\n        rewrite H0. clear H0.\n        apply IHls.\n        simpl in H.\n        intuition.\nQed.\n\nTheorem myNthCorrect {X : Type}: forall (ls xs ys : list X) n x, \n  length (xs ++ [x]) = n -> ls = xs ++ x :: ys -> myNth n ls = Some x.\nProof.\n  intro.\n  induction ls; intros.\n  + destruct xs; inversion H0.\n  + destruct n.\n    - destruct xs.\n      * inversion H.\n      * inversion H.\n    - destruct n. \n      * destruct xs.\n        ++ inversion H0.\n           auto.\n        ++ destruct xs.\n           -- inversion H.\n           -- inversion H.\n      * destruct xs.\n        ++ inversion H.\n        ++ inversion H0.\n           assert (myNth (S (S n)) (x0 :: xs ++ x :: ys) = myNth (S n) (xs ++ x :: ys)).\n           { clear. reflexivity. }\n           rewrite H1. clear H1. rewrite <- H3.\n           eapply IHls.\n           -- simpl in H.\n              apply eq_add_S in H.\n              exact H.\n           -- exact H3.\nQed.\n\n", "meta": {"author": "SvenWille", "repo": "Coq99Problems", "sha": "47002c12016120e3ab43c2591de25875b7067a99", "save_path": "github-repos/coq/SvenWille-Coq99Problems", "path": "github-repos/coq/SvenWille-Coq99Problems/Coq99Problems-47002c12016120e3ab43c2591de25875b7067a99/coqSrc/P3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7325397113050827}}
{"text": "Require Import Imp.\n\n(** Proving the correctness of a compiler.\n   Andrew W. Appel, Princeton University, December 2009.\n   Minor edits, March 2011 and May 2014.\n*)\n\n(** Let's start by defining a machine language.  The compiler will only use the\n   first 5 instructions, but the extra instructions don't hurt. *)\n\nInductive instr : Type :=\n| i_move: id -> id -> instr\n| i_num: nat -> id -> instr\n| i_plus: id -> id -> id -> instr\n| i_minus: id -> id -> id -> instr\n| i_mult: id -> id -> id -> instr\n| i_eq: id -> id -> id -> instr\n| i_le: id -> id -> id -> instr\n| i_not: id -> id -> instr\n| i_and: id -> id -> id -> instr\n| i_or: id -> id -> id -> instr.\n\n(** Operational semantics for instructions. *)\nInductive exec: state -> instr -> state -> Prop :=\n| exec_move: forall st i j, exec st (i_move i j) (update st j (st i))\n| exec_num: forall st n i, exec st (i_num n i) (update st i n)\n| exec_plus: forall st i j k, exec st (i_plus i j k) (update st k (st i + st j))\n| exec_minus: forall st i j k, exec st (i_minus i j k) (update st k (st i - st j))\n| exec_mult: forall st i j k, exec st (i_mult i j k) (update st k (st i * st j))\n| exec_eq_true : forall st i j k, st i = st j -> exec st (i_eq i j k) (update st k 1)\n| exec_eq_false : forall st i j k, st i <> st j -> exec st (i_eq i j k) (update st k 0).\n\nHint Constructors exec.\n\n(** Operational semantics for lists of instructions. *)\nInductive exec_list: state -> list instr -> state -> Prop :=\n| exec_nil: forall st, exec_list st nil st\n| exec_cons: forall h t st st' st'', exec st h st' -> exec_list st' t st'' -> exec_list st (h::t) st''.\n\nHint Constructors exec_list.\n\n(** Here's the compiler for arithmetic expressions.\n      It uses variables >= N as scratch temporaries for subexpressions *)\nFixpoint compile_aexp (N: nat) (a: aexp) : list instr :=\n  match a with\n  | ANum n =>  i_num n (Id N) :: nil\n  | AId i => i_move i (Id N) :: nil\n  | APlus a1 a2 => compile_aexp N a1 ++ compile_aexp (S N) a2 ++\n                               i_plus (Id N) (Id (S N)) (Id N) :: nil\n  | AMinus a1 a2 => compile_aexp N a1 ++ compile_aexp (S N) a2 ++\n                               i_minus (Id N) (Id (S N)) (Id N) :: nil\n  | AMult a1 a2 => compile_aexp N a1 ++ compile_aexp (S N) a2 ++\n                               i_mult (Id N) (Id (S N)) (Id N) :: nil\n end.\n\nFixpoint compile_com (N: nat) (c: com) : list instr :=\n match c with\n  | CSkip => nil\n  | CAss i a => compile_aexp N a ++ i_move (Id N) i :: nil\n  | CSeq c1 c2 => compile_com N c1 ++ compile_com N c2\n  | _ => nil\n end.\n\nFixpoint check_exp N (a: aexp) : Prop :=\n  match a with\n  | ANum n => True\n  | AId (Id i) => i < N\n  | APlus a1 a2 => check_exp N a1 /\\ check_exp N a2\n  | AMinus a1 a2 => check_exp N a1 /\\ check_exp N a2\n  | AMult a1 a2 => check_exp N a1 /\\ check_exp N a2\n end.\n\nFixpoint check_com N (c: com) : Prop :=\n  match c with\n  | CSkip => True\n  | CAss (Id i) a => i < N /\\ check_exp N a\n  | CSeq c1 c2 => check_com N c1 /\\ check_com N c2\n  | _ => False\n end.\n\n\nDefinition my_prog := (X ::= APlus (AId Y) (ANum 1) ;; Y ::= AMult (AId X)  (APlus (AId X) (AId Y))).\n\nExample check_my_prog:\n  check_com 10 my_prog.\nProof. simpl. intuition. Qed.\n\nExample compile_my_prog:\n   compile_com 10 my_prog =\n    i_move Y (Id 10)\n    :: i_num 1 (Id 11)\n    :: i_plus (Id 10) (Id 11) (Id 10)\n    :: i_move (Id 10) X\n    :: i_move X (Id 10)\n    :: i_move X (Id 11)\n    :: i_move Y (Id 12)\n    :: i_plus (Id 11) (Id 12) (Id 11)\n    :: i_mult (Id 10) (Id 11) (Id 10)\n    :: i_move (Id 10) Y\n    :: nil.\nProof. reflexivity. Qed.\n\nExample ceval_my_prog:\n     my_prog / empty_state || (update (update empty_state X 1) Y 1).\nProof.\nrepeat (econstructor; simpl; try reflexivity).\nQed.\n\nExample exec_my_prog:\n    exists st, exec_list empty_state (compile_com 10 my_prog) st.\nProof.\neconstructor.\nsimpl.\nrepeat (eapply exec_cons; [eauto|]).\napply exec_nil.\nQed.\n\n(*EX 3 (wrong_compiler_correctness) *)\nDefinition wrong_compiler_correctness_specification :=\n     forall c N, check_com N c ->\n           forall st stx, exec_list st (compile_com N c) stx ->\n                      ceval c st stx.\n\nTheorem wrong_specification_wrong:\n  ~ wrong_compiler_correctness_specification.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nDefinition same_below (N: nat) (st st': state) : Prop :=\n            forall i, i < N -> st (Id i) = st' (Id i).\n\nDefinition compiler_correctness_specification :=\n     forall c N, check_com N c ->\n           forall st stx, exec_list st (compile_com N c) stx ->\n                 forall sty, ceval c st sty ->\n                   same_below N stx sty.\n\nLtac inv H := inversion H; clear H; subst.\n\n(** **** Exercise: 3 stars (exec_list_lemmas) *)\nLemma exec_list_app:\n    forall il1 il2 st1 st2 st3,\n      exec_list st1 il1 st2 -> exec_list st2 il2 st3 ->\n      exec_list st1 (il1++il2) st3.\n(* FILL IN HERE *) Admitted.\nHint Resolve exec_list_app.\n\nLemma exec_list_app_inv:\n  forall il1 il2 st1 st3, exec_list st1 (il1++il2) st3 ->\n  exists st2, exec_list st1 il1 st2 /\\ exec_list st2 il2 st3.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nLtac overr := rewrite update_neq;\n                         [| intro Hx; inv  Hx; subst; omega].\n\n(* The tactic [crunch] is an example of the \"Adam Chlipala style\"; just\n  a baby example of course.  For a complete introduction to this style\n  of proof automation, see,\n   Certified Programming with Dependent Types\n   by Adam Chlipala, MIT Press, 2013.\n   http://adam.chlipala.net/cpdt/\n*)\n\nLtac crunch :=\n          intros;\n          repeat\n             first [rewrite update_eq\n                    | overr\n                    | match goal with\n                        | H: False |- _ => contradiction\n                        | H: _ /\\ _ |- _  => destruct H\n                        | H: exec_list _ (_ ++ _) _ |- _ =>\n                            apply exec_list_app_inv in H; destruct H as [?st [? ?]]\n                        | H: exec_list _ (_ :: _) _ |- _ => inv H\n                        | H: exec_list _ nil _ |- _ => inv H\n                        | H: exec _ (i_move _ _) _ |- _ => inv H\n                        | H: exec _ (i_num _ _) _ |- _ => inv H\n                        | H: exec _ (i_plus _ _ _) _ |- _ => inv H\n                        | H: exec _ (i_minus _ _ _) _ |- _ => inv H\n                        | H: exec _ (i_mult _ _ _) _ |- _ => inv H\n                        | H: match ?ii with Id _ => _ end |- _ => destruct ii\n                        | H: ceval _ CSkip _ |- _ => inv H\n                        | H: ceval _ (CAss _ _) _  |- _=> inv H\n                        end]; auto.\n\nLemma check_S:  forall N a, check_exp N a -> check_exp (S N) a.\nProof.\n(aexp_cases (induction a) Case); simpl; crunch.\nQed.\n\nLemma same_below_refl: forall N st, same_below N st st.\nProof. unfold same_below; auto.\nQed.\n\nHint Resolve same_below_refl.\n\nLemma same_below_sym: forall N st st',\n        same_below N st st' -> same_below N st' st.\nProof.\nunfold same_below; intros. symmetry; auto.\nQed.\n\nLemma same_below_trans:  forall N st1 st2 st3,\n        same_below N st1 st2 -> same_below N st2 st3 -> same_below N st1 st3.\nProof.\nunfold same_below; intros.\nrewrite H; auto.\nQed.\n\n(** **** Exercise: 2 stars (same_below_update) *)\nLemma same_below_update:\n  forall i N v v' st st',\n         v = v' ->\n        same_below N st st' ->\n        same_below N (update st i v) (update st' i v').\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\nHint Resolve same_below_update.\n\n(** **** Exercise: 3 stars (compile_aexp_same_below) *)\nLemma compile_aexp_same_below:\n  forall a N st st', exec_list st (compile_aexp N a) st' ->\n          same_below N st st'.\nProof.\nunfold same_below.\n(aexp_cases (induction a) Case); simpl; crunch.\n(** Instructions:  First, remove \"crunch\" from the line above, and use\n     \"Focus\" to examine each of the 5 subgoals.  Now, put \"crunch\" back,\n     notice that it has already disposed of 2 subgoals and made some progress\n     in the other 3, and finish the proof.\n*)\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (aeval_same_below) *)\nLemma aeval_same_below:\n  forall st st' a N,\n   check_exp N a ->\n   same_below N st st' ->\n   aeval st a = aeval st' a.\nProof.\nunfold same_below.\n(aexp_cases (induction a) Case); simpl; crunch.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars (compile_aexp_correct) *)\nTheorem compile_aexp_correct:\n     forall a N, check_exp N a ->\n           forall st st', exec_list st (compile_aexp N a) st' ->\n                    st' (Id N) = aeval st a.\nProof.\n(aexp_cases (induction a) Case); simpl; crunch.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(**  Consider an arithmetic expression [a] with no variables named N or above,\n      and compile it with [compile N a].\n      Now we believe that executing the compiled expression [compile N a]\n      should not affect any variables below N.  That is, if [st1] and [st1'] are\n      the same below N, and we can execute from [st1] to get [st2], then\n      we should be able to execute from st1' to get st2'.   Not only must\n     st2' exist, but it should be the same as st2, below N.\n\n    This can be explained by a  \"commutative diagram\".    The solid lines\n    ( st1---st1',  st1---st2) indicate sides that are given in the hypothesis.\n    The dotted lines  (st1' - - - st2',  st2 - - - st2') indicate sides that\n    we claim must exist.\n\n   (Caveat: This diagram works in Lucida Sans Unicode 10, looks terrible otherwise)\n\n      st1 ----------------------  st1'\n         |              same_below                 i\n         |                                                  i\n         | compile                                    i compile\n         |                                                  i\n         |              same_below                 i\n       st2 - - - - - - - - - - - - - - -  st2'\n\n   The formal statement of this is [comple_exp_fiddle], below.\n*)\n\n(** **** Exercise: 4 stars (compile_exp_fiddle) *)\nLemma compile_exp_fiddle:\n  forall a N, check_exp N a ->\n          forall J st1 st1', J <= N -> same_below J st1 st1' ->\n          forall st2, exec_list st1 (compile_aexp N a) st2 ->\n            exists st2', exec_list st1' (compile_aexp N a) st2' /\\ same_below J st2 st2'.\nProof.\n(aexp_cases (induction a) Case); simpl; crunch.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** We have the same kind of commutative diagram for compile_com. *)\n\n(** **** Exercise: 4 stars (compile_com_fiddle) *)\nLemma compile_com_fiddle:\n  forall c N,\n          check_com N c ->\n          forall st1 st1', same_below N st1 st1' ->\n          forall st2, exec_list st1 (compile_com N c) st2 ->\n                exists st2', exec_list st1' (compile_com N c) st2' /\\ same_below N st2 st2'.\nProof.\n(com_cases (induction c) Case); simpl; crunch.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars (compile_com_correct) *)\nTheorem compile_com_correct: compiler_correctness_specification.\nProof.\nunfold compiler_correctness_specification.\n(com_cases (induction c) Case); simpl; crunch.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n", "meta": {"author": "B-Rich", "repo": "vfa", "sha": "30fb3e6b13f949ce8b88c0159f7d2a4e726136c7", "save_path": "github-repos/coq/B-Rich-vfa", "path": "github-repos/coq/B-Rich-vfa/vfa-30fb3e6b13f949ce8b88c0159f7d2a4e726136c7/Compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7324811920586086}}
{"text": "Definition relation (A : Type) := A -> A -> Prop.\n\n(** The syntax {param} declares the parameter [param] as implicit. In the case\nof [rtc], it allows one to write [rtc R x y] instead of [rtc A R x y]. *)\n\n(** The reflexive transitive closure of a relation A. **)\n(** This signature reads: if R is a binary relation on type A, then it's\nreflexive transitive closure is also a binary relation on A **)\nInductive rtc {A} (R : relation A) : relation A :=\n  (** The first constructor reads: every A is in reflexive-transitive closure\n  to itself, no matter what the relation actually is **)\n  | rtc_refl x : rtc R x x\n  (** The second constructor reads: given that x is in relation R to y and  y\n  is in reflexive transitive closure to z then x is in rtc to z (one step plus\n  many steps is again many steps) **)\n  | rtc_l x y z : R x y -> rtc R y z -> rtc R x z.\n\nPrint rtc_ind.\n\n(** The diamond property, in general **)\n(** This definition reads: Two relations R and T together have the diamond property if:\n\n        x\n     R / \\ T\n      /   \\\n    y1     y2\n      \\   /\n     T \\ / R\n        z\n\nIf x R y1 and x T y2 there exists a z such that y1 T z and y2 R z.\n**)\nDefinition gen_dp {A} (R T : relation A) := forall x y1 y2,\n  R x y1 -> T x y2 -> exists z, T y1 z /\\ R y2 z.\n\n(** To prove: the diamond property is symmetrical.  **)\nLemma gen_dp_sym {A} (R T : relation A) :\n  gen_dp R T -> gen_dp T R.\nProof.\nunfold gen_dp.\nintro.\nintro.\nintro.\nintro.\nintro.\nintro.\nelim H with x y2 y1.\nintro.\nintro.\nexists x0.\nsplit.\nelim H2.\nintros.\nassumption.\nelim H2.\nintros.\nassumption.\nassumption.\nassumption.\nQed.\n\n(** Relation A has the diamond property if it has the generic diamond property\nwith itself **)\nDefinition dp {A} (R : relation A) := gen_dp R R.\n\n(** Relation A is church-rosser if it's reflexive-transitive closure has the\ndiamond property. **)\nDefinition cr {A} (R : relation A) := dp (rtc R).\n\nLemma rtc_reverse {A} (R : relation A) (x y : A) : R x y -> rtc R x y.\nProof.\nintros.\napply (rtc_l R x y).\nassumption.\napply (rtc_refl).\nQed.\n\n\n\n(** If two relation R, T have the generic diamond property together, then the\nreflexive-transitive closure of R and T have the generic diamond property.\n**)\nLemma rtc_gen_dp {A} (R T : relation A) :\n  gen_dp R T -> gen_dp (rtc R) T.\nProof.\n\n\n\nunfold gen_dp.\nintro.\nintros x y1 y2.\n\nintros.\n\nelim H with x y1 y2.\nintro.\nintro.\nFocus 2.\napply (rtc_reverse R x y1).\n\ninduction H0.\nexists y2.\nsplit.\nassumption.\napply rtc_refl.\n\napply IHrtc.\n\ninversion H0.\nexists y2.\nsplit.\nsubst y1.\nassumption.\napply rtc_refl.\n\nexists y.\nsplit.\nFocus 2.\napply (rtc_l R y2 z).\n\n\n\nQed.\n\nLemma dp_cr {A} (R : relation A) :\n  dp R -> cr R.\nProof.\n  (* exercise *)\nQed.\n\n(* vim: ft=coq\n*)\n", "meta": {"author": "mklinik", "repo": "radboud", "sha": "1b79730dbf7979221ca0de97fc369db82c405331", "save_path": "github-repos/coq/mklinik-radboud", "path": "github-repos/coq/mklinik-radboud/radboud-1b79730dbf7979221ca0de97fc369db82c405331/type-theory-IMC010/church_rosser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7324591284571944}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule PCMDef.\n\nRecord mixin_of (T : Type) := Mixin {\n    valid_op : T -> bool;\n    join_op : T -> T -> T;\n    unit_op : T;\n    _ : commutative join_op;\n    _ : associative join_op;\n    _ : left_id unit_op join_op;\n    _ : forall x y, valid_op (join_op x y) -> valid_op x; \n    _ : valid_op unit_op \n}.\n\nSection Packing.\n\nStructure pack_type : Type := Pack {type : Type; _ : mixin_of type}.\nLocal Coercion type : pack_type >-> Sortclass.\nVariable cT: pack_type.\nDefinition pcm_struct : mixin_of cT := \n    let: Pack _ c := cT return mixin_of cT in c.\n\nDefinition valid := valid_op pcm_struct.\nDefinition join := join_op pcm_struct.\nDefinition unit := unit_op pcm_struct.\n\nEnd Packing.\n\nModule Exports.\n\nNotation pcm := pack_type.\nNotation PCMMixin := Mixin.\nNotation PCM T m := (@Pack T m).\n\nNotation \"x \\+ y\" := (join x y) (at level 43, left associativity).\nNotation valid := valid.\nNotation Unit := unit.\n\n\nCoercion type : pack_type >-> Sortclass.\n\nSection PCMLemmas.\nVariable U : pcm.\n\nLemma joinC (x y : U) : x \\+ y = y \\+ x.\nProof.\nby case: U x y=> tp [v j z Cj *]; apply Cj.\nQed.\n\nLemma joinA (x y z : U) : x \\+ (y \\+ z) = x \\+ y \\+ z.\nProof. \nby case: U x y z=>tp [v j z Cj Aj *]; apply: Aj. \nQed.\n\n(*******************************************************************)\n(**                     * Exercices 1 *                            *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [PCM Laws]\n---------------------------------------------------------------------\n\nProove the rest of the PCM laws.\n*)\n\nLemma joinAC (x y z : U) : x \\+ y \\+ z = x \\+ z \\+ y.\nProof. by rewrite -joinA (joinC y) joinA. Qed.\n\nLemma joinCA (x y z : U) : x \\+ (y \\+ z) = y \\+ (x \\+ z).\nProof. by rewrite joinA (joinC x) -joinA. Qed.\n\nLemma validL (x y : U) : valid (x \\+ y) -> valid x.\nProof. \ncase: U x y=>tp [v j z Cj Aj Uj /= Mj inv f]. \nby apply: Mj. \nQed.\n\nLemma validR (x y : U) : valid (x \\+ y) -> valid y.\nProof. by rewrite joinC; apply: validL. Qed.\n\nLemma unitL (x : U) : (@Unit U) \\+ x = x.\nProof. by case: U x=>tp [v j z Cj Aj Uj *]; apply: Uj. Qed.\n\nLemma unitR (x : U) : x \\+ (@Unit U) = x.\nProof. by rewrite joinC unitL. Qed.\n\nLemma valid_unit : valid (@Unit U).\nProof. by case: U=>tp [v j z Cj Aj Uj Vm Vu *]. Qed.\n\n(*******************************************************************)\n(**                 * End of Exercices 1 *                         *)\n(*******************************************************************)\n\nEnd PCMLemmas.\n\nEnd Exports.\n\nEnd PCMDef.\n\nExport PCMDef.Exports.\n\n(*******************************************************************)\n(**                     * Exercices 2 *                            *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [Partially-ordered sets]\n---------------------------------------------------------------------\n\nA partially ordered set order is a triple (T, \\pre, \\bot), such that T\nis a carrier set, \\pre is a relation on T and \\bot is an element of T,\nsuch that\n\n- forall x in T, \\bot \\pre x (\\bot is a bottom element);\n\n- forall x in T, x \\pre x (reflexivity);\n\n- forall x, y in T, x \\pre y \\wedge y \\pre x \\implies x = y (antisymmetry);\n\n- forall x, y, z in T, x \\pre y \\wedge y \\pre z \\implies x \\pre z (transitivity).\n\nImplement a data structure for partially-ordered sets using mixins and\npacked classes. Prove the following laws:\n\nLemma botP (x : T) : bot <== x.\nLemma poset_refl (x : T) : x <== x.\nLemma poset_asym (x y : T) : x <== y -> y <== x -> x = y.\nLemma poset_trans (y x z : T) : x <== y -> y <== z -> x <== z.\n\n*)\n\nModule Poset.\nSection RawMixin.\n\nRecord mixin_of (T : Type) := Mixin {\n  mx_leq : T -> T -> Prop;\n  _ : forall x, mx_leq x x; \n  _ : forall x y, mx_leq x y -> mx_leq y x -> x = y; \n  _ : forall x y z, mx_leq x y -> mx_leq y z -> mx_leq x z}.\n\nEnd RawMixin.\nSection ClassDef.\n\nRecord class_of T := Class {mixin : mixin_of T}.\n\nStructure pack_type : Type := Pack {sort : Type; _ : mixin_of sort}.\nLocal Coercion sort : pack_type >-> Sortclass.\n\nVariables (cT : pack_type).\nDefinition poset_struct := let: Pack _ c := cT return mixin_of cT in c.\n\nDefinition leq := mx_leq poset_struct.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion sort : pack_type >-> Sortclass.\nNotation poset := pack_type.\nNotation PosetMixin := Mixin.\nNotation Poset T m := (@Pack T m).\n\nNotation \"x <== y\" := (Poset.leq x y) (at level 70).\n\nSection Laws.\nVariable T : poset.\n\nLemma poset_refl (x : T) : x <== x.\nProof. by case: T x=>S [leq B R]. Qed.\n\nLemma poset_asym (x y : T) : x <== y -> y <== x -> x = y.\nProof. by case: T x y=>S [l R A Tr] *; apply: (A). Qed.\n\nLemma poset_trans (y x z : T) : x <== y -> y <== z -> x <== z.\nProof. by case: T y x z=>S [l R A Tr] ? x y z; apply: (Tr). Qed.\nEnd Laws.\nEnd Exports.\nEnd Poset.\n\nExport Poset.Exports.\n\n(**\n---------------------------------------------------------------------\nExercise [Canonical instances of partially ordered sets]\n---------------------------------------------------------------------\n\nProvide canonical instances of partially ordered sets for the\nfollowing types:\n\n- [nat] and [<=];\n\n- [prod], whose components are posets;\n\n- functions [A -> B], whose codomain (range) [B] is a partially\n  ordered set.\n\nIn order to provide a canonical instance for functions, you will need\nto assume and make use of the following axiom of functional\nextensionality:\n\n*)\n\nSection NatPoset.\nLemma nat_refl x : x <= x. Proof. by []. Qed.\n\nLemma nat_asym x y : x <= y -> y <= x -> x = y.\nProof. by move=>H1 H2; apply: anti_leq; rewrite H1 H2. Qed. \n\nLemma nat_trans x y z : x <= y -> y <= z -> x <= z.\nProof. by apply: leq_trans. Qed.\n\nDefinition natPosetMixin := PosetMixin nat_refl nat_asym nat_trans.\nCanonical natPoset := Eval hnf in Poset nat natPosetMixin.\nEnd NatPoset.\n\n\nSection PairPoset. \nVariable (A B : poset). \nLocal Notation tp := (A * B)%type. \n\nDefinition pair_leq (p1 p2 : tp) := p1.1 <== p2.1 /\\ p1.2 <== p2.2.\n\nLemma pair_refl x : pair_leq x x.\nProof. by split; apply: poset_refl. Qed.\n\nLemma pair_asym x y : pair_leq x y -> pair_leq y x -> x = y.\nProof.\nmove: x y=>[x1 x2][y1 y2][/= H1 H2][/= H3 H4].\nby congr (_, _); apply: poset_asym.\nQed.\n\nLemma pair_trans x y z : pair_leq x y -> pair_leq y z -> pair_leq x z.\nProof. \nmove: x y z=>[x1 x2][y1 y2][z1 z2][/= H1 H2][/= H3 H4]; split=>/=.\n- by apply: poset_trans H3.\nby apply: poset_trans H4.\nQed.\n\nDefinition pairPosetMixin := \n  PosetMixin pair_refl pair_asym pair_trans.\nCanonical pairPoset := Eval hnf in Poset tp pairPosetMixin.\n\nEnd PairPoset.\n\nAxiom fext : forall A (B : A -> Type) (f1 f2 : forall x, B x), \n               (forall x, f1 x = f2 x) -> f1 = f2.\n\nSection FunPoset. \nVariable (A : Type) (B : poset).\nLocal Notation tp := (A -> B). \n\nDefinition fun_leq (p1 p2 : tp) := forall x, p1 x <== p2 x.\n\nLemma fun_refl x : fun_leq x x.\nProof. by move=>z; apply: poset_refl. Qed. \n\nLemma fun_asym x y : fun_leq x y -> fun_leq y x -> x = y.\nProof. \nmove=>H1 H2. apply: fext=>z; \nby apply: poset_asym; [apply: H1 | apply: H2]. \nQed.\n\nLemma fun_trans x y z : fun_leq x y -> fun_leq y z -> fun_leq x z.\nProof. by move=>H1 H2 t; apply: poset_trans (H2 t). Qed.\n\nDefinition funPosetMixin := PosetMixin fun_refl fun_asym fun_trans.\nCanonical funPoset := Eval hnf in Poset tp funPosetMixin.\n\nEnd FunPoset.\n\n\n(*******************************************************************)\n(**                 * End of Exercices 2 *                         *)\n(*******************************************************************)\n", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/solutions/DepRecords_solutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7324591222055601}}
{"text": "(* TP2 Langages formels\n\n   LISEZ BIEN TOUT CE QUI EST PRÉCISÉ EN COMMENTAIRES\n\n   Décommentez les 'Example' pour vérifier que vos fonctions fonctionnent correctement\n\n*)\n\n(******************************************************************************)\n(********** programmation fonctionnelle et automates en Coq (partie 1) ********)\n(******************************************************************************)\n\n(* L'objectif de LIFLF-TP2 est de définir tout ce dont on a besoin pour définir\n   des automates et de les faire s'exécuter dans la partie *programme* de Coq.\n\n   Les composants dont on aura besoin pour les automates :\n    - On va définir le type \"Alphabet\" avec une fonction qui teste l'égalité\n    - On va utiliser le type prédéfini \"option\" pour représenter les fonctions partielles\n    - On va utiliser le type prédéfini \"prod A B\" des paires\n    - On va définir la recherche dans une liste d'entiers et dans une liste de paires\n\n   Le quintuplet usuel M = <K, Sigma, delta : K*Sigma -> K, s, F> sera défini en coq\n   dans le TP3.\n*)\n\n\n\n(******************************************************************************)\n(* L'alphabet et son égalité calculable *)\n(******************************************************************************)\n\n(* On définit un petit alphabet d'exemple : c'est juste une énumération, représentée\n   en Coq par un type inductif avec 2 constructeurs sans argument (des constantes). *)\nInductive Alphabet : Type :=\n| a : Alphabet\n| b : Alphabet.\n\n(* Ici, Alphabet est 'le plus petit ensemble qui contient a, b et rien d'autre', donc\n   intuitivement, Alphabet est l'ensemble {a,b} *)\n\n(* EXERCICE *)\n(* Définir une fonction comp_alphabet qui teste si deux éléments de l'alphabet sont égaux\n   et énoncer son théorème de correction *)\nDefinition comp_alphabet (x : Alphabet)  (y : Alphabet) : bool :=\nmatch (x, y) with\n| (a, a) => true\n| (b, b) => true\n|_ => false \nend.\n\n\n\n\n\n\n(* On attend \"false\" comme résultat *)\nCompute (comp_alphabet a b).\n\n(* On peut aussi écrire les exemples précédents comme des tests unitaires\n\n   EXEMPLES À DÉCOMMENTER\n\n   Ici, la 'preuve' est obtenue par calcul :\n     - \"cbv\" (call by value) effectue le calcul\n     - la tactique \"reflexivity\" finit le job. *)\n(*\nExample comp_alphabet_ex1 : comp_alphabet a a = true.\nProof.\ncbv.         (* on effectue le calcul *)\nreflexivity. (* c'est bien l'axiome du prédicat d'égalité *)\nQed.\n\nExample comp_alphabet_ex2 : comp_alphabet a b = false.\nProof.\ncbv.\nreflexivity.\nQed.\n*)\n\n\n(* Le travail de définition d'une fonction déterminant l'égalité qui a été fait\n   sur Alphabet existe bien sûr pour les \"nat\". *)\n\n(* Les entiers *)\nRequire Import Nat.\nPrint nat.\n\n(* La fonction qui teste l'égalité de deux entiers. *)\nCheck Nat.eqb : nat -> nat -> bool.\nPrint Nat.eqb.\n\n\n(******************************************************************************)\n(* Le type prédéfini \"option A\" *)\n(******************************************************************************)\n\n(* Pour un type A, le type \"option A\" est\n   - Soit un élément de A,\n   - Soit rien.\n*)\n\n(* tout d'abord la définition (NE PAS DÉCOMMENTER, c'est un type prédéfini) :\n   Inductive option (A : Type) : Type := \n     | Some : A -> option A\n     | None : option A\n*)\n\nPrint option.\n\n(* EXERCICE *)\n(* Définir une fonction comp_option_nat qui teste si deux \"option nat\" sont égaux.\n   Par convention, comparer 'rien' et 'rien' renverra vrai.\n   Comparer 'rien' et 'qqchose' renverra forcément faux.\n   Pour le dernier cas, comparer deux 'qqchose' renverra la comparaison effective de ces deux qqchose.\n   Vérifier les tests unitaires et énoncer le théorème de correction associé *)\nDefinition comp_option_nat (x : option nat) (y : option nat) : bool :=\nmatch (x, y) with\n| (None, None) => true\n| (None, Some m) => false\n| (Some m, None) => false\n| (Some m, Some n) => Nat.eqb m n\nend.\n\n\nTheorem comp_option_nat_correct : forall (x : option nat), forall (y : option nat), comp_option_nat x y =true -> x=y.\nProof.\nAdmitted.\n\n(* Tests unitaires avec reflexivity *)\n\nExample comp_option_nat_ex1 : comp_option_nat (Some 1) (Some 2) = false.\nProof.\ncbv. reflexivity.\nQed.\n\nExample comp_option_nat_ex2 : comp_option_nat (Some 2) (Some 2) = true.\nProof.\ncbv. reflexivity.\nQed.\n\nExample comp_option_nat_ex3 : comp_option_nat (None) (Some 2) = false.\nProof.\ncbv. reflexivity.\nQed.\n\nExample comp_option_nat_ex4 : comp_option_nat (Some 2) (None) = false.\nProof.\ncbv. reflexivity.\nQed.\n\n\n\n(******************************************************************************)\n(* Le type prédéfini produit de A et B \"prod A B\" *)\n(******************************************************************************)\n\n(* Le type 'produit de A et B' est défini par \"prod A B\" dans la bibliothèque Coq\n   (NE PAS DECOMMENTER)\n\n   Inductive prod (A B : Type) : Type := \n     pair : A -> B -> A * B\n\n   En Coq, on écrit \"A * B\" au lieu de  \"prod A B\" (c'est juste une notation)\n*)\nPrint prod.\n\n(* Ce type n'a qu'un seul constructeur \"pair\" qui prend deux arguments : (x:A) et (y:B)\n   Prod A B est donc 'le plus petit ensemble qui contient tous les éléments\n   de la forme \"pair x y\" (avec x dans A et y dans B) et rien d'autre'\n   donc intuitivement, Prod A B est le produit cartésien de A et B, qui contient\n   toutes les paires (x,y) (et rien d'autres).\n*)\n\n(* EXERCICE *)\n(* Définir les fonctions \"fsta\" et \"snda\" de projection sur les couples d'éléments\n   de type Alphabet avec \"match\" : p:A*B correspond au motif (x,y) où x est de type A et\n   y de type B *)\n\nDefinition fsta (p : Alphabet*Alphabet) : Alphabet :=\nmatch p with\n|(x, y) => x\nend.\n\nDefinition snda (p : Alphabet*Alphabet) : Alphabet :=\nmatch p with\n|(x, y) => y\nend.\n\n\nExample fsta_ex1 : (fsta (a,b)) = a.\nProof.\n  cbv. reflexivity.\nQed.\n\nExample snda_ex1 : (snda (a,b)) = b.\nProof.\n  cbv. reflexivity.\nQed.\n\n\n(* On peut ré-écrire comp_alphabet en utilisant le pattern matching\n   sur la paire (x,y). Attention il y a un \"let\" caché dans cette\n   façon de faire (donc on évitera).  On remarque aussi l'utilisation\n   de \"_\" le joker pour les arguments génériques. *)\nDefinition comp_alphabet' (x y : Alphabet) : bool :=\n  match (x,y) with\n  | (a,a) => true\n  | (b,b) => true\n  | (_,_) => false (* pour tous les autres cas *)\nend.\n\nPrint comp_alphabet'.\n\nExample comp_alphabet'_ex1 : (comp_alphabet' a a) = true.\nProof.\n  cbv. reflexivity.\nQed.\n\n(* EXERCICE *)\n(* Définir la fonction comp_pair_nat qui compare deux paires d'entiers.\n   L'égalité sur les nat est \"Nat.eqb\" et le connecteur et sur les bool est \"andb\". *)\nDefinition comp_pair_nat (p1 : nat*nat) (p2 : nat*nat) : bool :=\nmatch (p1,p2) with\n| ((x, y),(x', y')) => andb (Nat.eqb x x') (Nat.eqb y y')\nend.\n\n(* Tests unitaires avec reflexivity *)\n\nExample comp_pair_nat_ex1 : comp_pair_nat (0,1) (0,0) = false.\nProof.\ncbv.\nreflexivity.\nQed.\nExample comp_pair_nat_ex2 : comp_pair_nat (0,1) (0,1) = true.\nProof.\nreflexivity.\nQed.\n\n(* EXERCICE *)\n(* Définir une fonction swap qui à la paire d'entiers (a,b) fait correspondre (b,a) *)\nDefinition swap (p : nat*nat) : nat*nat :=\nmatch p with\n|(x, y) => (y,x)\nend.\n\n\nExample swap_ex1 : swap (1,2) = (2,1).\nProof.\n  cbv. reflexivity.\nQed.\n\n\n(******************************************************************************)\n(* Recherche dans les listes d'entier  *)\n(******************************************************************************)\n\n(* On rappelle ici la définition des listes natives : on aurait pu\n   tout faire avec les listes définies dans les TP précédents, comme\n   avec nos entiers, mais c'est réinventer la roue\n\n   NE PAS DECOMMENTER\n\n   Inductive list (A : Type) : Type := \n   | nil : list A\n   | cons : A -> list A -> list A\n*)\nRequire Export List.\nImport ListNotations.\n\n(* à partir d'ici on a\n    - []   : la liste vide\n    - n::l : le constructeur d'ajout de n en tête de l\n    - ++   : la fonction de concaténation en position infixe *)\nPrint list.\n\n(* EXERCICE *)\n(* Définir la fonction \"concatene\" qui prend en paramètres deux listes d'entiers\n   (donc de type \"list nat\") et renvoie la concaténation de ces deux listes *)\nFixpoint concatene (l1 : list nat) (l2 : list nat) : list nat :=\nmatch l1 with\n| nil => l2\n| cons x l => cons x (concatene l l2)\nend.\n\nExample concatene_ex1 : concatene [1;2;3] [4;5] = [1;2;3;4;5].\nProof.\ncbv. reflexivity.\nQed.\n\n\n(* EXERCICE *)\n(* Définir la fonction \"appartient\" qui prend en paramètres un entier\n   n et une liste d'entiers (donc de type \"list nat\") et renvoie true\n   si et seulement si n est dans la liste *)\nFixpoint appartient (n : nat) (l : list nat) : bool :=\nmatch l with\n| nil => false\n| cons x l1 => match eqb n x with\n               | true => true\n               | false => appartient n l1\n               end\nend.\n\n(* Tests unitaires avec reflexivity *)\n\nExample appartient_ex1 : appartient 0 [1;3;0;5] = true.\nProof.\ncbv. reflexivity.\nQed.\n\nExample appartient_ex2 : appartient 4 [1;3;0;5] = false.\nProof.\ncbv. reflexivity.\nQed.\n\n\n(******************************************************************************)\n(* Recherche dans les listes de paires *)\n(******************************************************************************)\n\n(* on peut représenter un dictionnaire comme une liste de paire (clef, valeur) *)\n\n(* La principale fonctionnalité que l'on attend d'un dictionnaire est de pouvoir retrouver\n   la valeur associée à une clef. Si plusieurs valeurs sont associées, alors on retourne\n   la première qu'on trouve.\n\n   On comprend bien que rien ne garantit qu'on trouve toujours une valeur, donc le type\n   de retour de cette fonction est de type \"option valeur\"\n*)\n\n\n(* EXERCICE *)\n(* Définir la fonction \"trouve\" qui prend en paramètres\n    - une listes de paires (clef,valeur)\n    - une clef k\n   et renvoie la première valeur associée à k quand elle existe et None sinon.\n   Les clés seront des Alphabet, les valeurs des nat.\n*)\nFixpoint trouve (l : list (Alphabet*nat)) (x : Alphabet) : option nat :=\nmatch l with\n| nil => None\n| cons (y, n) l1 => match comp_alphabet x y with\n                    | true => Some n\n                    | false => trouve l1 x\n                    end\nend.\n\n\n(* Tests unitaires avec reflexivity *)\n\nExample trouve_ex1 :  trouve [(a,1); (b,2)] a = Some 1.\nProof.\ncbv. reflexivity.\nQed.\nExample trouve_ex2 :  trouve [(a,2); (a,1)] a = Some 2.\nProof.\ncbv. reflexivity.\nQed.\nExample trouve_ex3 :  trouve [(a,2); (a,1)] b = None.\nProof.\ncbv. reflexivity.\nQed.\n\n\n\n(* FIN DU TP2 *)\n\n(* ------------------------------------------------------------ *)\n\n\n(* EXERCICES A FAIRE CHEZ VOUS *)\n\n(* EXERCICE *)\n(* On va montrer que (comp_alphabet x y) = true si et seulement si (x = y).\n   Autrement dit, comp_alphabet *décide* l'égalité entre deux éléments de alphabet.\n   On va utiliser pour cela les tactiques vues dans les TP précédents\n   - intros [Id1] [Id2] ...\n   - destruct [Hypothèse]\n   - discriminate\n   - reflexivity\n   - cbv (in [Hypothèse])\n   - apply [Théorème] (in [Hypothèse])\n   - rewrite [Théorème d'égalité] (in [Hypothèse])\n\n   On peut décomposer la preuve :\n   - prouver comp_alphabet_correct : si comp_alphabet x y = true alors x = y\n   - prouver comp_alphabet_complet : si x = y alors comp_alphabet x y = true\n*)\n\nTheorem comp_alphabet_correct : forall (x : Alphabet), forall (y : Alphabet), comp_alphabet x y = true -> x=y.\nProof.\nintro h0.\nintro h1.\nintro h2.\n(* EXERCICE *)\n(* Enoncer et prouver la propriété que comparer un symbole de l'alphabet avec lui-même renvoie vrai.\n   HINT : \"comp_alphabet_complet\" fait exactement ce dont on a besoin, on peut donc l'utiliser *)\n\n\n(* EXERCICE *)\n(* Compléter la preuve suivante\n   HINT : \"destruct x\", \"left\" ou \"right\" pour \"\\/\" *)\nLemma alphabet_a_juste_deux_elements : forall x:Alphabet, x = a \\/ x = b.\nProof.\nAdmitted.\n\n\n(* EXERCICE *)\n(* Enoncer et prouver la propriété que la fonction \"comp_option_nat\" est correcte et complète *)\n(* HINT : si la tactique \"cbv\" ne calcule pas 'assez', remplacez le\n   nom de fonction par sa valeur avec \"unfold\", comme par exemple avec le\n   \"unfold not\" qui remplace \"~A\" par \"A -> False\". *)\n\n\n(* EXERCICE *)\n(* Prouver le lemme suivant *)\nLemma projection_product (A B : Type) : forall p:A*B, p = (fst p, snd p).\nProof.\nAdmitted.\n\n\n(* EXERCICE *)\n(* Prouver que \"swap\" est involutive.\n   Rappel. Une fonction f est une involution ssi quel que soit x, f(f(x)) = x\n   HINT : pour p:A*B une paire, utiliser \"destruct p\" pour retrouver \"(a,b)\"\n*)\n\n(* EXERCICE *)\n(* Enoncer et prouver la propriété que la fonction \"comp_pair_nat\" est correcte\n   HINT : utiliser \"Bool.andb_true_iff\"\n   Bool.andb_true_iff : forall b1 b2 : bool, (b1 && b2)%bool = true <-> b1 = true /\\ b2 = true\n   Ce théorème lie le *ET* des booléens, la fonction \"andb\" en Coq (qui se note aussi \"&&\")\n   et le *ET* logique, noté \"/\\\" en Coq (qui se note aussi \"and\" )\n*)\nCheck Bool.andb_true_iff.\nCheck PeanoNat.Nat.eqb_eq.\n\n\n\n(* EXERCICE *)\n(* Enoncer et prouver la propriété que l'appartenance d'un élément à une liste vide\n   est fausse *)\n\n\n(* EXERCICE *)\n(* Enoncer et prouver la propriété que l'appartenance d'un élément à une liste singleton\n   est vraie SSI l'élément recherché et celui du singleton sont égaux\n   On utilisera les théorèmes suivants\n   \"Bool.orb_false_r : forall b : bool, (b || false)%bool = b\"\n   \"PeanoNat.Nat.eqb_eq : forall n m : nat, PeanoNat.Nat.eqb n m = true <-> n = m\"\n*)\n\n\n(* EXERCICE *)\n(* Énoncer et prouver le lemme de correction de \"appartient\"\n   nommé \"appartient_correct\" qui dit en langue naturelle :\n   (appartient x ls) est vrai SI ET SEULEMENT SI il existe une décomposition \n   de ls de la forme ls = l1 ++ x :: l2.\n\n   NOTA BENE : c'est assez ambitieux à prouver à ce stade.\n*)\n\n\n(* EXERCICE *)\n(* Enoncer et prouver la propriété \"trouve_tete\" qui, pour toute liste l,\n   toute clé k et toute valeur v, trouve ((k,v)::l) k = Some v.\n\n   HINT : vous pouvez ajouter une nouvelle assertion dans le contexte avec \n   la tactique \"assert H\", un nouveau sous-but demandant de prouver \"H\"\n   est alors ajouté\n*)\n\n\n\n(* ------------------------------------------------------------ *)\n\n", "meta": {"author": "MartinLeocmach", "repo": "LIFLF", "sha": "effa54ad070752ed08ebec09fb6066b4e68f35d2", "save_path": "github-repos/coq/MartinLeocmach-LIFLF", "path": "github-repos/coq/MartinLeocmach-LIFLF/LIFLF-effa54ad070752ed08ebec09fb6066b4e68f35d2/LF-TP2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7323929552864743}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Ralph Matthes [+]                              *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [+] Affiliation IRIT -- CNRS   *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\n(* * Pigeonhole principle *)\n\nRequire Import Arith Lia List Permutation Relations.\n\nFrom Undecidability.Shared.Libs.DLW.Utils \n  Require Import utils_tac utils_list.\n\nSet Implicit Arguments.\n\nLocal Infix \"~p\" := (@Permutation _) (at level 70, no associativity).\n\nSection incl.\n\n  Variable X : Type.\n  \n  Implicit Type l : list X.\n  \n  Fact incl_cons_linv l m x : incl (x::m) l -> In x l /\\ incl m l.\n  Proof.\n    intros H; split.\n    + apply H; left; auto.\n    + intros ? ?; apply H; right; auto.\n  Qed.\n\n  Fact incl_app_rinv l m p : incl m (l++p) -> exists m1 m2, m ~p m1++m2 /\\ incl m1 l /\\ incl m2 p.\n  Proof.\n    induction m as [ | x m IHm ].\n    + exists nil, nil; simpl; repeat split; auto; intros ? [].\n    + intros H.\n      apply incl_cons_linv in H.\n      destruct H as (H1 & H2).\n      destruct (IHm H2) as (m1 & m2 & H3 & H4 & H5).\n      apply in_app_or in H1; destruct H1.\n      * exists (x::m1), m2; repeat split; auto.\n        - constructor 2; auto.\n        - intros ? [|]; subst; auto.\n      * exists m1, (x::m2); repeat split; auto.\n        - apply Permutation_cons_app; auto.\n        - intros ? [|]; subst; auto.\n  Qed.\n  \n  Fact incl_cons_rinv x l m : incl m (x::l) -> exists m1 m2, m ~p m1 ++ m2 /\\ Forall (eq x) m1 /\\ incl m2 l.\n  Proof.\n    intros H.\n    apply (@incl_app_rinv (x::nil) _ l) in H.\n    destruct H as (m1 & m2 & H1 & H2 & H3).\n    exists m1, m2; repeat split; auto.\n    rewrite Forall_forall.\n    intros a Ha; apply H2 in Ha; destruct Ha as [ | [] ]; auto.\n  Qed.\n\n  Fact incl_right_cons_choose x l m : incl m (x::l) -> In x m \\/ incl m l.\n  Proof.\n    intros H.\n    apply incl_cons_rinv in H.\n    destruct H as ( m1 & m2 & H1 & H2 & H3 ); simpl in H1.\n    destruct m1 as [ | y m1 ].\n    + right.\n      intros u H; apply H3; revert H.\n      apply Permutation_in; auto.\n    + left.\n      apply Permutation_in with (1 := Permutation_sym H1).\n      rewrite Forall_forall in H2.\n      rewrite (H2 y); left; auto.\n  Qed.\n\n  Fact incl_left_right_cons x l y m : incl (x::l) (y::m) -> y = x  /\\ In y l \n                                                         \\/ y = x  /\\ incl l m\n                                                         \\/ In x m /\\ incl l (y::m).\n  Proof.\n    intros H; apply incl_cons_linv in H.\n    destruct H as [ [|] H2 ]; auto.\n    apply incl_right_cons_choose in H2; tauto.\n  Qed.\n\n  Fact perm_incl_left m1 m2 l: m1 ~p m2 -> incl m2 l -> incl m1 l.\n  Proof. intros H1 H2 ? H. apply H2; revert H; apply Permutation_in; auto. Qed.\n\n  Fact perm_incl_right m l1 l2: l1 ~p l2 -> incl m l1 -> incl m l2.\n  Proof.\n    intros H1 H2 ? ?; apply Permutation_in with (1 := H1), H2; auto.\n  Qed.\n  \nEnd incl.\n\nSection Permutation_tools.\n\n  Variable X : Type.\n  \n  Implicit Types (l : list X).\n  \n  Theorem Permutation_In_inv l1 l2: l1 ~p l2 -> forall x, In x l1 -> exists l, exists r, l2 = l++x::r.\n  Proof. intros H ? ?; apply in_split, Permutation_in with (1 := H); auto. Qed.\n  \n  Fact perm_in_head x l : In x l -> exists m, l ~p x::m.\n  Proof.\n    induction l as [ | y l IHl ].\n    + destruct 1.\n    + intros [ ? | H ]; subst.\n      * exists l; apply Permutation_refl.\n      * destruct (IHl H) as (m & Hm).\n        exists (y::m).\n        apply Permutation_trans with (2 := perm_swap _ _ _).\n        constructor 2; auto.\n  Qed.\n\nEnd Permutation_tools.\n\nSection pigeon_list.\n\n  Variable (X : Type).\n\n  Implicit Types (l m : list X).\n  \n  Inductive list_has_dup : list X -> Prop :=\n    | in_list_hd0 : forall l x, In x l -> list_has_dup (x::l)\n    | in_list_hd1 : forall l x, list_has_dup l -> list_has_dup (x::l).\n  \n  Fact list_hd_cons_inv x l : list_has_dup (x::l) -> In x l \\/ list_has_dup l.\n  Proof. inversion 1; subst; auto. Qed.\n\n  Definition list_has_dup_cons_inv := list_hd_cons_inv.\n\n  Fact list_has_dup_cons_iff x l : list_has_dup (x::l) <-> In x l \\/ list_has_dup l.\n  Proof.\n    split.\n    + apply list_hd_cons_inv.\n    + intros []; [ constructor 1 | constructor 2 ]; auto.\n  Qed.\n  \n  Fact list_has_dup_app_left l m : list_has_dup m -> list_has_dup (l++m).\n  Proof. induction l; simpl; auto; constructor 2; auto. Qed.\n  \n  Fact list_has_dup_app_right l m : list_has_dup l -> list_has_dup (l++m).\n  Proof. \n    induction 1; simpl.\n    + constructor 1; apply in_or_app; left; auto.\n    + constructor 2; auto.\n  Qed.\n\n  Fact perm_list_has_dup l m : l ~p m -> list_has_dup l -> list_has_dup m.\n  Proof.\n    induction 1 as [ | x l m H1 IH1 | x y l | ]; auto; \n      intros H; apply list_hd_cons_inv in H.\n    + destruct H as [ H | H ].\n      * apply Permutation_in with (1 := H1) in H.\n        apply in_list_hd0; auto.\n      * apply in_list_hd1; auto.\n    + destruct H as [ [ H | H ] | H ]; subst.\n      * apply in_list_hd0; left; auto.\n      * apply in_list_hd1, in_list_hd0; auto.\n      * apply list_hd_cons_inv in H.\n        destruct H as [ H | H ].\n        - apply in_list_hd0; right; auto.\n        - do 2 apply in_list_hd1; auto.\n  Qed.\n\n  Fact list_has_dup_swap x y l : list_has_dup (x::y::l) -> list_has_dup (y::x::l).\n  Proof. apply perm_list_has_dup; constructor. Qed.\n\n  Fact list_has_dup_app_inv l m : list_has_dup (l++m) -> list_has_dup l \n                                                      \\/ list_has_dup m \n                                                      \\/ exists x, In x l /\\ In x m. \n  Proof.\n    induction l as [ | x l IHl ]; simpl; intros H; auto.\n    apply list_hd_cons_inv in H.\n    + destruct H as [ H | H ].\n      * apply in_app_or in H; destruct H as [ H | H ].\n        - left; constructor; auto.\n        - do 2 right; exists x; simpl; auto.\n      * destruct (IHl H) as [ H1 | [ H1 | (y & H1 & H2) ] ]; auto.\n        - left; constructor 2; auto.\n        - do 2 right; exists y; simpl; auto.\n  Qed.\n\n  Fact list_has_dup_eq_duplicates m: list_has_dup m <-> exists x aa bb cc, m = aa++x::bb++x::cc.\n  Proof.\n    split.\n    + induction 1 as [ m x Hm | m x _ IHm ].\n      - apply in_split in Hm.\n        destruct Hm as (bb & cc & Hm).\n        exists x, nil, bb, cc; subst; auto.\n      - destruct IHm as (y & aa & bb & cc & IHm).\n        exists y, (x::aa), bb, cc; subst; auto.\n    + intros (x & aa & bb & cc & Hm).\n      subst m.\n      apply list_has_dup_app_left.\n      constructor 1; apply in_or_app; right.\n      constructor 1; reflexivity.\n  Qed.\n\n  Definition list_has_dup_equiv := list_has_dup_eq_duplicates.\n\n  Fact repeat_choice_two x m : Forall (eq x) m -> (exists m', m = x::x::m') \\/ m = nil \\/ m = x::nil.\n  Proof.\n    intros H.\n    destruct m as [ | a [ | b m ] ]; auto.\n    + inversion H; subst; auto.\n    + rewrite Forall_forall in H.\n      rewrite <- (H a), <- (H b); simpl; auto; left; exists m; auto.\n  Qed.\n\n  (* If m in included in x::l then \n       a) either m is included in l\n       b) or m has a duplicate (x but that does not matter here)\n       c) or m is permutable with x::m' with m' included in l\n   *)\n\n  Fact incl_right_cons_incl_or_lhd_or_perm m x l : \n       incl m (x::l) -> incl m l \n                     \\/ list_has_dup m \n                     \\/ exists m', m ~p x::m' /\\ incl m' l.\n  Proof.\n    intros H.\n    apply incl_cons_rinv in H.\n    destruct H as (m1 & m2 & H1 & H2 & H3).\n    destruct (repeat_choice_two H2) as [ (?&?) | [|] ]; \n      subst m1; simpl in H1; clear H2.\n    + right; left; apply perm_list_has_dup with (1 := Permutation_sym H1), in_list_hd0; left; auto.\n    + left; revert H1 H3; apply perm_incl_left.\n    + firstorder.\n  Qed.\n\n  Fact incl_left_right_php x l y m : incl (y::m) (x::l) -> list_has_dup (y::m)\n                                                        \\/ x = y  /\\ incl m l\n                                                        \\/ In y l /\\ incl m l\n                                                        \\/ In y l /\\ exists m', m ~p x::m' /\\ incl m' l.\n  Proof.\n    intros H; apply incl_left_right_cons in H.\n    destruct H as [ (? & ?) | [ (? & ?) | (H1 & H2) ] ]; subst; auto.\n    + left; apply in_list_hd0; auto.\n    + apply incl_right_cons_incl_or_lhd_or_perm in H2; firstorder.\n      left; apply in_list_hd1; auto.\n  Qed.\n\n  (* length_le_and_incl_implies_dup_or_perm is a generalisation of the PHP\n      for which the inductive case works w/o needing decidable equality  \n\n      A shorter proof\n\n      The proof is by induction on l\n   *)\n\n  (* ** Generalized statement *)\n\n  Lemma length_le_and_incl_implies_dup_or_perm l m :  \n            length l <= length m \n         -> incl m l \n         -> list_has_dup m \\/ m ~p l.\n  Proof.\n    revert m; induction l as [ | x l IHl ]; intros m; simpl; intros H1 H2; auto.\n    + destruct m as [ | y ]; auto; destruct (H2 y); simpl; auto.\n    + destruct incl_right_cons_incl_or_lhd_or_perm with (1 := H2)\n        as [ H3 | [ H3 | (m' & H3 & H4) ] ]; auto.\n      * destruct IHl with (2 := H3) as [ | H ]; try lia; auto.\n        apply Permutation_length in H; lia.\n      * destruct IHl with (2 := H4) as [ H | H ]; try (simpl; lia).\n        - apply Permutation_length in H3; simpl in H3; lia.\n        - left; apply perm_list_has_dup with (1 := Permutation_sym H3).\n          constructor 2; auto.\n        - right; apply perm_trans with (1 := H3); auto.\n  Qed. \n\n  (* If  m is strictly longer than l \n      and m is (set) included in l\n      then it has a duplicate \n\n      This proof does not require weakly decidable equality\n      and it does not find where is the duplicate\n    *)\n\n  Theorem finite_php_dup l m : length l < length m\n                            -> incl m l \n                            -> list_has_dup m.\n  Proof.\n    intros H1 H2.\n    destruct (@length_le_and_incl_implies_dup_or_perm l m) as [ | H3 ]; auto; try lia.\n    apply Permutation_length in H3; lia.\n  Qed. \n\n  (* ** The Finite PHP on lists of the same type *)\n\n  Theorem finite_pigeon_hole l m :\n         length l < length m \n      -> incl m l \n      -> exists x aa bb cc, m = aa++x::bb++x::cc.\n  Proof.\n    intros; apply list_has_dup_eq_duplicates, finite_php_dup with l; auto.\n  Qed.\n\n  Theorem partition_intersection l m k :\n           length k < length (l++m)\n        -> incl (l++m) k\n        -> list_has_dup l \n        \\/ list_has_dup m \n        \\/ exists x, In x l /\\ In x m. \n  Proof.\n    intros H1 H2.\n    apply list_has_dup_app_inv, list_has_dup_eq_duplicates.\n    revert H1 H2; apply finite_pigeon_hole.\n  Qed.\n\nEnd pigeon_list.\n\nFact not_list_has_dup_an a n : ~ list_has_dup (list_an a n).\nProof.\n  revert a; induction n as [ | n IHn ]; simpl; intros a H.\n  + inversion H.\n  + apply list_hd_cons_inv in H.\n    rewrite list_an_spec in H.\n    destruct H as [ | H ]; try lia.\n    revert H; apply IHn.\nQed.\n\nFact list_has_dup_map_inv X Y (f : X -> Y) l : \n           (forall x y, In x l -> In y l -> f x = f y -> x = y) \n        -> list_has_dup (map f l) \n        -> list_has_dup l.\nProof.\n  intros H; do 2 rewrite list_has_dup_eq_duplicates.\n  intros (y & m1 & m2 & m3 & E).\n  apply map_app_inv in E; destruct E as (l1 & l10 & H1 & H2 & H3); symmetry in H3.\n  apply map_cons_inv in H3; destruct H3 as (x1 & l11 & H3 & H4 & H5).\n  apply map_app_inv in H5; destruct H5 as (l2 & l12 & H5 & H6 & H7); symmetry in H7.\n  apply map_cons_inv in H7; destruct H7 as (x2 & l3 & H7 & H8 & H9); subst.\n  apply H in H8; subst.\n  + exists x1, l1, l2, l3; auto.\n  + apply in_or_app; right; right; simpl.\n    apply in_or_app; simpl; auto.\n  + apply in_or_app; simpl; auto.\nQed.\n\nFact not_list_an_has_dup a n : ~ list_has_dup (list_an a n).\nProof.\n  revert a; induction n as  [ | n IHn ]; simpl; intros a H.\n  + inversion H.\n  + apply list_hd_cons_inv in H.\n    rewrite list_an_spec in H.\n    destruct H as [ | H ]; try lia.\n    revert H; apply IHn.\nQed.\n\nFact list_exists X Y (R : X -> Y -> Prop) l : (forall x, In x l -> exists y, R x y) -> exists ll, Forall2 R l ll.\nProof.\n  induction l as [ | x l IHl ]; intros Hl.\n  exists nil; constructor.\n  destruct (Hl x) as (y & Hy).\n  left; auto.\n  destruct IHl as (ll & Hll).\n  intros; apply Hl; right; auto.\n  exists (y::ll); constructor; auto.\nQed.\n\nFact Forall2_conj X Y (R S : X -> Y -> Prop) ll mm : Forall2 (fun x y => R x y /\\ S x y) ll mm <-> Forall2 R ll mm /\\ Forall2 S ll mm.\nProof.\n  split.\n  induction 1; split; constructor; tauto.\n  intros [H1 H2]; revert H1 H2.\n  induction 1 as [ | x ll y mm H1 H2 IH ]; intros H; auto.\n  apply Forall2_cons_inv in H; constructor; tauto.\nQed.\n\nFact Forall2_length X Y (R : X -> Y -> Prop) l m : Forall2 R l m -> length l = length m.\nProof. induction 1; simpl; f_equal; auto. Qed.\n\nFact Forall2_impl X Y (R S : X -> Y -> Prop) : \n     (forall x y, R x y -> S x y) -> forall l m, Forall2 R l m -> Forall2 S l m.\nProof. induction 2; constructor; auto. Qed.\n\nFact Forall2_right_Forall X Y (P : Y -> Prop) lx ly : Forall2 (fun (_ : X) y => P y) lx ly <-> Forall P ly /\\ length lx = length ly.\nProof.\n  split.\n  intros H; split.\n  induction H; constructor; auto.\n  revert H; apply Forall2_length.\n  intros (H1 & H2); revert lx H2.\n  induction H1; intros [ | ] H2; try discriminate H2; constructor; auto.\nQed.\n\nFact Forall2_app_inv_r X Y R l m1 m2 : \n       @Forall2 X Y R l (m1++m2) \n    -> { l1 : _ & { l2 | Forall2 R l1 m1 /\\ Forall2 R l2 m2 /\\ l = l1++l2 } }.\nProof.\n  revert m2 l;\n  induction m1 as [ | y m1 IH ]; simpl; intros m2 l H.\n  exists nil, l; repeat split; auto.\n  destruct l as [ | x l ].\n  apply Forall2_nil_inv_l in H; discriminate H.\n  apply Forall2_cons_inv in H; destruct H as [ H1 H2 ].\n  apply IH in H2.\n  destruct H2 as (l1 & l2 & H2 & H3 & H4); subst l.\n  exists (x::l1), l2; repeat split; auto.\nQed.\n\nSection PHP_rel.\n  \n  Variable (U V : Type) (R : U -> V -> Prop) (l : list U) (m : list V) \n                        (HR : forall x, In x l -> exists y, In y m /\\ R x y).\n                          \n  Let image_R_l : exists Rl, incl Rl m /\\ Forall2 R l Rl.\n  Proof.\n    destruct (list_exists _ l HR) as (Rl & HRl).\n    exists Rl; split.\n    + clear HR.\n      rewrite Forall2_conj in HRl.\n      apply proj1, Forall2_right_Forall, proj1 in HRl.\n      rewrite Forall_forall in HRl; auto.\n    + revert HRl; apply Forall2_impl; tauto.\n  Qed.\n\n  Hypothesis (Hlm : length m < length l).\n\n  (* ** The finite relational PHP *)\n                          \n  Theorem PHP_rel : exists a x b y c v, l = a++x::b++y::c\n                                       /\\ In v m /\\ R x v /\\ R y v.\n  Proof.\n    destruct image_R_l as (Rl & H1 & H2).\n    destruct finite_pigeon_hole with (2 := H1) as (v & x & y & z & H).\n    + apply Forall2_length in H2; lia.\n    + subst Rl.\n      apply Forall2_app_inv_r in H2; destruct H2 as (x' & l1 & H3 & H2 & ?); subst.\n      apply Forall2_cons_inv_r in H2; destruct H2 as (v' & l2 & H4 & ? & H2); subst.\n      apply Forall2_app_inv_r in H2; destruct H2 as (y' & l3 & H5 & H2 & ?); subst.\n      apply Forall2_cons_inv_r in H2; destruct H2 as (v'' & l4 & H6 & ? & H2); subst.\n      exists x', v', y', v'', l4, v; repeat (split; auto).\n      apply H1, in_or_app; simpl; auto.\n  Qed.\n\nEnd PHP_rel.\n\nSection php_upto.\n\n  (* If R is a partial equivalence relation, l is a\n      list contained in the list m (upto R), and m is \n      shorter than l, then l contains a duplicate upto R *)\n\n  Theorem php_upto X (R : X -> X -> Prop) (l m : list X) :\n            symmetric _ R -> transitive _ R                  (* PER *)\n         -> (forall x, In x l -> exists y, In y m /\\ R x y)  (* l contained in m *)\n         -> length m < length l                              (* shorter *)\n         -> exists a x b y c, l = a++x::b++y::c /\\ R x y.    (* duplicate *)\n  Proof.\n    intros HR1 HR2 H1 H2.\n    destruct PHP_rel with (R := R) (2 := H2)\n      as (a & x & b & y & c & z & G1 & G2 & G3 & G4); auto.\n    exists a, x, b, y, c; split; auto.\n    apply (HR2 _ z); auto.\n  Qed.\n\nEnd php_upto.\n\n\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/Shared/Libs/DLW/Utils/php.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7323929520550467}}
{"text": "(** %\\chapter{Encoding Mathematical Structures}% *)\n\nModule DepRecords.\n\nRequire Import ssreflect ssrbool ssrnat ssrfun.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Encoding partial commutative monoids *)\n\nModule PCMDef. \n\n(**\n\nWe have already seen a use of a dependent pair type, exemplified by\nthe Coq's definition of the universal quantification.\n\n*)\n\nPrint ex.\n\n(**\n[[\nInductive ex (A : Type) (P : A -> Prop) : Prop :=\n    ex_intro : forall x : A, P x -> ex P\n]]\n\n*)\n\nRecord mixin_of (T : Type) := Mixin {\n    valid_op : T -> bool;\n    join_op : T -> T -> T;\n    unit_op : T;\n    _ : commutative join_op;\n    _ : associative join_op;\n    _ : left_id unit_op join_op;\n    _ : forall x y, valid_op (join_op x y) -> valid_op x; \n    _ : valid_op unit_op \n}.\n\n(**\n[[\nmixin_of is defined\nmixin_of_rect is defined\nmixin_of_ind is defined\nmixin_of_rec is defined\nvalid_op is defined\njoin_op is defined\nunit_op is defined\n]]\n*)\n\nCheck valid_op.\n\n(**\n[[\nvalid_op\n     : forall T : Type, mixin_of T -> T -> bool\n]]\n*)\n\n\nLemma r_unit T (pcm: mixin_of T) (t: T) : (join_op pcm t (unit_op pcm)) = t.\nProof.\ncase: pcm=>_ join unit Hc _ Hlu _ _ /=.\n\n(** \n[[\n  T : Type\n  t : T\n  join : T -> T -> T\n  unit : T\n  Hc : commutative join\n  Hlu : left_id unit join\n  ============================\n   join t unit = t\n]]\n*)\n\nby rewrite Hc Hlu.\nQed.\n\n\n(** ** An alternative definition *)\n\nInductive mixin_of' (T: Type) := \n  Mixin' (valid_op: T -> bool) (join_op : T -> T -> T) (unit_op: T) of\n    commutative join_op &\n    associative join_op &\n    left_id unit_op join_op &\n    forall x y, valid_op (join_op x y) -> valid_op x &\n    valid_op unit_op.\n\n(**\n\nAlthough this definition seems more principled and is closer to what\nwe have seen in previous chapters, the record notation is more\nconvenient in this case, as it defined getters automatically as well\nas allows one to express inheritance between data structures by means\nof the coercion operator %\\texttt{:>}%\noperator%~\\cite{Garillot-al:TPHOL09}%.%\\footnote{In the next section\nwill show a different way to encode implicit inheritance, though.}%\n\n** Packaging the structure from mixins\n%\\label{sec:packaging}%\n\n*)\n\nSection Packing.\n\nStructure pack_type : Type := Pack {type : Type; _ : mixin_of type}.\n\n(** \n\nThe dependent data structure [pack_type] declares two fields: the\nfield [type] of type [Type], which described the carrier type of the\nPCM instance, and the actual PCM structure (without an explicit name\ngiven) of type [mixin_of type]. That is, in order to construct an\ninstance of [pack_type], one will have to provide _both_ arguments:\nthe carrier set and a PCM structure for it.\n\n*)\n\nLocal Coercion type : pack_type >-> Sortclass.\n\n(**\n\nNext, in the same section, we provide a number of abbreviations to\nsimplify the work with the PCM packed structure and prepare it to be\nexported by clients.\n\n*)\nVariable cT: pack_type.\n\nDefinition pcm_struct : mixin_of cT := \n    let: Pack _ c := cT return mixin_of cT in c.\n\nDefinition valid := valid_op pcm_struct.\nDefinition join := join_op pcm_struct.\nDefinition unit := unit_op pcm_struct.\n\nEnd Packing.\n\nModule Exports.\n\nNotation pcm := pack_type.\nNotation PCMMixin := Mixin.\nNotation PCM T m := (@Pack T m).\n\nNotation \"x \\+ y\" := (join x y) (at level 43, left associativity).\nNotation valid := valid.\nNotation Unit := unit.\n\n\nCoercion type : pack_type >-> Sortclass.\n\n\n(** * Properties of partial commutative monoids *)\n\nSection PCMLemmas.\nVariable U : pcm.\n\n(** \n\nFor instance, the following lemma re-establishes the commutativity of\nthe [\\+] operation:\n\n*)\n\nLemma joinC (x y : U) : x \\+ y = y \\+ x.\nProof.\nby case: U x y=> tp [v j z Cj *]; apply Cj.\nQed.\n\n\n(** \n\nNotice that in order to make the proof to go through, we had to \"push\"\nthe PCM elements [x] and [y] to be the assumption of the goal before\ncase-analysing on [U]. This is due to the fact that the structure of\n[U] affects the type of [x] and [y], therefore destructing it by means\nof [case] would change the representation of [x] and [y] as well,\ndoing some rewriting and simplifications. Therefore, when [U] is being\ndecomposed, al values, whose type depends on it (i.e., [x] and [y])\nshould be in the scope of decomposition. The naming pattern [*] helped\nus to give automatic names to all remaining assumptions, appearing\nfrom decomposition of [U]'s second component before moving it to the\ncontext before finishing the proof by applying the commutativity\n\"field\" [Cj].\n\n*)\n\nLemma joinA (x y z : U) : x \\+ (y \\+ z) = x \\+ y \\+ z.\nProof. \nby case: U x y z=>tp [v j z Cj Aj *]; apply: Aj. \nQed.\n\n(*******************************************************************)\n(**                     * Exercices 1 *                            *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [PCM Laws]\n---------------------------------------------------------------------\n\nProove the rest of the PCM laws.\n*)\n\nLemma joinAC (x y z : U) : x \\+ y \\+ z = x \\+ z \\+ y.\nProof.\n(* fill in your proof here instead of [admit] *)\nadmit.\nQed.\n\n\nLemma joinCA (x y z : U) : x \\+ (y \\+ z) = y \\+ (x \\+ z).\nProof.\n(* fill in your proof here instead of [admit] *)\nadmit.\nQed.\n\n\nLemma validL (x y : U) : valid (x \\+ y) -> valid x.\nProof.\n(* fill in your proof here instead of [admit] *)\nadmit.\nQed.\n\n\nLemma validR (x y : U) : valid (x \\+ y) -> valid y.\nProof.\n(* fill in your proof here instead of [admit] *)\nadmit.\nQed.\n\n\nLemma unitL (x : U) : (@Unit U) \\+ x = x.\nProof.\n(* fill in your proof here instead of [admit] *)\nadmit.\nQed.\n\n\nLemma unitR (x : U) : x \\+ (@Unit U) = x.\nProof.\n(* fill in your proof here instead of [admit] *)\nadmit.\nQed.\n\n\nLemma valid_unit : valid (@Unit U).\nProof.\n(* fill in your proof here instead of [admit] *)\nadmit.\nQed.\n\n\n(*******************************************************************)\n(**                 * End of Exercices 1 *                         *)\n(*******************************************************************)\n\nEnd PCMLemmas.\n\nEnd Exports.\n\nEnd PCMDef.\n\nExport PCMDef.Exports.\n\n(** * Implementing inheritance hierarchies\n\nWe will now go even further and show how to build hierarchies of\nmathematical structures using the same way of encoding inheritance. We\nwill use a _cancellative PCM_ as a running example.\n\n*)\n\nModule CancelPCM.\n\nRecord mixin_of (U : pcm) := Mixin {\n  _ : forall a b c: U, valid (a \\+ b) -> a \\+ b = a \\+ c -> b = c\n}.\n\nStructure pack_type : Type := Pack {pcmT : pcm; _ : mixin_of pcmT}.\n\nModule Exports.\n\nNotation cancel_pcm := pack_type.\nNotation CancelPCMMixin := Mixin.\nNotation CancelPCM T m:= (@Pack T m).\n\nCoercion pcmT : pack_type >-> pcm.\n\nLemma cancel (U: cancel_pcm) (x y z: U): \n  valid (x \\+ y) -> x \\+ y = x \\+ z -> y = z.\nProof.\nby case: U x y z=>Up [Hc] x y z; apply: Hc.\nQed.\n\nEnd Exports.\nEnd CancelPCM. \n\nExport CancelPCM.Exports.\n\nLemma cancelC (U: cancel_pcm) (x y z : U) :\n  valid (y \\+ x \\+ z) -> y \\+ x = x \\+ z -> y = z.\nProof.\nby move/validL; rewrite ![y \\+ _]joinC; apply: cancel.\nQed.\n\n\n(**\n\n* Instantiation and canonical structures\n\nNow, as we have defined a PCM structure along with its specialized\nversion, a cancellative PCM, it is time to see how to _instantiate_\nthese abstract definitions with concrete datatypes, i.e., _prove_ the\nlater ones to be instances of a PCM.\n\n** Defining arbitrary PCM instances\n\nNatural numbers form a PCM, in particular, with addition as a join\noperation and zero as a unit element. The validity predicate is\nconstant true, because the addition of two natural numbers is again a\nvalid natural number. Therefore, we can instantiate the PCM structure\nfor [nat] as follows, first by constructing the appropriate mixin.\n\n*)\n\nDefinition natPCMMixin := \n  PCMMixin addnC addnA add0n (fun x y => @id true) (erefl _).\n\nDefinition NatPCM := PCM nat natPCMMixin.\n\n(** \n\nThis definition will indeed work, although, being somewhat\nunsatisfactory. For example, assume we want to prove the following\nlemma for natural numbers treated as elements of a PCM, which should\ntrivially follow from the PCM properties of [nat] with addition and\nzero:\n\n[[\nLemma add_perm (a b c : nat) : a \\+ (b \\+ c) = a \\+ (c \\+ b).\n]]\n\n\n[[\nThe term \"a\" has type \"nat\" while it is expected to have type \"PCMDef.type ?135\".\n]]\n\n*)\n\nCanonical natPCM := PCM nat natPCMMixin.\n\nPrint Canonical Projections.\n\n(**\n[[\n...\nnat <- PCMDef.type ( natPCM )\npred_of_mem <- topred ( memPredType )\npred_of_simpl <- topred ( simplPredType )\nsig <- sub_sort ( sig_subType )\nnumber <- sub_sort ( number_subType )\n...\n]]\n*)\n\n\nLemma cancelNat : forall a b c: nat, true -> a + b = a + c -> b = c.\nProof.\nmove=> a b c; elim: a=>// n /(_ is_true_true) Hn _ H.\nby apply: Hn; rewrite !addSn in H; move/eq_add_S: H.\nQed.\n\nDefinition cancelNatPCMMixin := CancelPCMMixin cancelNat.\n\nCanonical cancelNatPCM := CancelPCM natPCM cancelNatPCMMixin.\n\n(** \n\nLet us now see the canonical instances in action, so we can prove a\nnumber of lemmas about natural numbers employing the general PCM\nmachinery.\n\n*)\n\nSection PCMExamples.\n\nVariables a b c: nat.\n\nGoal a \\+ (b \\+ c) =  c \\+ (b \\+ a).\nby rewrite joinA [c \\+ _]joinC [b \\+ _]joinC.\nQed.\n\nGoal c \\+ a = a \\+ b -> c = b.\nby rewrite [c \\+ _]joinC; apply: cancel.\nQed.\n\n(** \n\nIt might look a bit cumbersome, though, to write the PCM join\noperation [\\+] instead of the boolean addition when specifying the\nfacts about natural numbers (even though they are treated as elements\nof the appropriate PCM). Unfortunately, it is not trivial to encode\nthe mechanism, which will perform such conversion implicitly. Even\nthough Coq is capable of figuring out what PCM is necessary for a\nparticular type (if the necessary canonical instance is defined),\ne.g., when seeing [(a b : nat)] being used, it infers the [natPCM],\nalas, it's not powerful enough to infer that the by writing the\naddition function [+] on natural numbers, we mean the PCM's\njoin. However, if necessary, in most of the cases the conversion like\nthis can be done by manual rewriting using the following trivial\n\"conversion\" lemma.\n\n*)\n\nLemma addn_join (x y: nat): x + y = x \\+ y. \nProof. by []. Qed.\n\nEnd PCMExamples.\n\n(** ** Types with decidable equalities\n\nThe module [eqtype] of SSReflect's standard library provides a\ndefinition of the equality mixin and packaged class of the familiar\nshape, which, after some simplifications, boil to the following ones:\n\n[[\nModule Equality.\n\nDefinition axiom T (e : rel T) := forall x y, reflect (x = y) (e x y).\n\nStructure mixin_of T := Mixin {op : rel T; _ : axiom op}.\nStructure type := Pack {sort; _ : mixin_of sort}.\n\n...\n\nNotation EqMixin := Mixin.\nNotation EqType T m := Pack T m.\n\nEnd Equality.\n]]\n\nDEMO: check the corresponding files ssreflect-1.4/theories/eqtype.v\nand ssreflect-1.4/theories/ssrnat.v\n\n*)\n\n(*******************************************************************)\n(**                     * Exercices 2 *                            *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [Partially-ordered sets]\n---------------------------------------------------------------------\n\nA partially ordered set order is a pair (T, <==), where T is a carrier\nset and <== is a relation on T, such that\n\n- forall x in T, x <== x (reflexivity);\n\n- forall x, y in T, x <== y /\\ y <== x \\implies x = y (antisymmetry);\n\n- forall x, y, z in T, x <== y /\\ y <== z \\implies x <== z (transitivity).\n\nImplement a data structure for partially-ordered sets using mixins and\npacked classes. Prove the following laws:\n\nLemma poset_refl (x : T) : x <== x.\nLemma poset_asym (x y : T) : x <== y -> y <== x -> x = y.\nLemma poset_trans (y x z : T) : x <== y -> y <== z -> x <== z.\n*)\n\n(**\n---------------------------------------------------------------------\nExercise [Canonical instances of partially ordered sets]\n---------------------------------------------------------------------\n\nProvide canonical instances of partially ordered sets for the\nfollowing types:\n\n- [nat] and [<=];\n\n- [prod], whose components are posets;\n\n- functions [A -> B], whose codomain (range) [B] is a partially\n  ordered set.\n\nIn order to provide a canonical instance for functions, you will need\nto assume and make use of the following axiom of functional\nextensionality:\n\n*)\n\nAxiom fext : forall A (B : A -> Type) (f1 f2 : forall x, B x), \n               (forall x, f1 x = f2 x) -> f1 = f2.\n\n\n(*******************************************************************)\n(**                 * End of Exercices 2 *                         *)\n(*******************************************************************)\n\nEnd DepRecords.\n", "meta": {"author": "ForNeVeR", "repo": "pnp-exercises", "sha": "412d771cef7566a6e0446a9455f0f6df38bb03a0", "save_path": "github-repos/coq/ForNeVeR-pnp-exercises", "path": "github-repos/coq/ForNeVeR-pnp-exercises/pnp-exercises-412d771cef7566a6e0446a9455f0f6df38bb03a0/DepRecords.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7323929455080378}}
{"text": "Require Import Classical.\n\n(* Importando definiciones. *)\nFrom src Require Export Defs_LC.\n\n(* Lema auxiliar, a -> ~~a *)\nLemma double_neg_intro: forall (a: Prop), a -> ~~a.\nProof.\nintros.\nassert (~~a \\/ ~~~a).\n+ apply classic.\n+ destruct H0.\n  - trivial.\n  - apply NNPP in H0.\n    contradiction.\nQed.\n\n(* Lema auxiliar, a /\\ ~b -> ~(a -> b) *)\nLemma and_to_imply: forall (a b: Prop), a /\\ ~b -> ~(a -> b).\nProof.\nintros.\ndestruct H.\ncontradict H0.\napply H0.\ntrivial.\nQed.\n\n(* Lema auxiliar: Modus Tollens *)\nLemma modus_tollens: forall (a b: Prop), (a -> b) -> (~b -> ~a).\nProof.\nintros.\ncontradict H0.\napply H.\ntrivial.\nQed. \n\n(* Lema auxiliar: Implicación de ~forall -> exists~ se cumple con dos variables *)\nLemma not_forall_exists_not_double: forall (U1 U2: Type) (P: U1 -> U2 -> Prop), \n~(forall (x: U1),forall (y: U2), P x y) -> exists (x: U1), exists (y: U2), ~P x y.\nProof.\nintros.\nassert (exists x: U1, ~ forall y:U2, P x y).\n+ apply not_all_ex_not.\n  trivial.\n+ destruct H0.\n  exists x.\n  apply not_all_ex_not.\n  trivial.\nQed.\n\n(* Ejercicio 3a *)\nTheorem coten_conm: forall (a b: Prop), a ° b <-> b ° a.\nProof.\nunfold cotenability.\nsplit.\n+ intro.\n  contradict H.\n  intro.\n  assert (b \\/ ~b).\n  * apply classic.\n  * destruct H1.\n    - apply H in H1.\n      contradiction.\n    - trivial.\n+ intro.\n  contradict H.\n  intro.\n  assert (a \\/ ~a).\n  * apply classic.\n  * destruct H1.\n    - apply H in H1.\n      contradiction.\n    - trivial.\nQed.\n\n(* Ejercicio 3b *)\nTheorem coten_assoc: forall (a b c: Prop), a ° (b ° c) <-> (a ° b) ° c.\nProof.\nunfold cotenability.\nsplit.\n+ intro.\n  contradict H.\n  intro.\n  apply double_neg_intro.\n  intro.\n  apply H.\n  apply and_to_imply.\n  split.\n  - trivial.\n  - apply double_neg_intro.\n    trivial.\n+ intro.\n  contradict H.\n  intro.\n  contradict H0.\n  intro.\n  apply H in H1.\n  apply NNPP in H1.\n  apply imply_to_or in H1.\n  destruct H1.\n  - trivial.\n  - contradiction.\nQed.\n\n(* Ejercicio 3c *)\nTheorem coten_distr: forall (A B C: Prop), (A ° B) \\/ (A ° C) <-> A ° (B \\/ C).\nProof.\nunfold cotenability.\nintros.\nsplit.\n+ intro.\n  destruct H.\n  - contradict H.\n    intro.\n    apply H in H0.\n    apply not_or_and in H0.\n    destruct H0.\n    trivial.\n  - contradict H.\n    intro.\n    apply H in H0.\n    apply not_or_and in H0.\n    destruct H0.\n    trivial.\n+ intro.\n  apply imply_to_and in H.\n  destruct H.\n  apply NNPP in H0.\n  destruct H0.\n  - left.\n    apply and_to_imply.\n    split.\n    * trivial.\n    * apply double_neg_intro.\n      trivial.\n  - right.\n    apply and_to_imply.\n    split.\n    * trivial.\n    * apply double_neg_intro.\n      trivial.\nQed.\n\n(* Ejercicio 3d *)\nTheorem coten_fusion: forall (A B C: Prop), (A -> B -> C) <-> ((A ° B) -> C).\nProof.\nunfold cotenability.\nsplit.\n+ intros.\n  apply imply_to_and in H0.\n  destruct H0.\n  apply H.\n  * trivial.\n  * apply NNPP.\n    trivial.\n+ intros.\n  apply H.\n  apply and_to_imply.\n  split.\n  * trivial.\n  * apply double_neg_intro.\n    trivial.\nQed.\n\n(* Ejercicio 3e *)\nTheorem imply_def: forall (A B C: Prop), (A -> B) <-> ~(A ° ~B).\nProof.\nunfold cotenability.\nsplit.\n+ intro.\n  apply double_neg_intro.\n  intro.\n  apply double_neg_intro.\n  apply H.\n  trivial.\n+ intros.\n  apply NNPP in H.\n  apply H in H0.\n  apply NNPP.\n  trivial.\nQed.\n\n(* Ejercicio 4a *)\nTheorem foura: forall (T1: Type) (A B C: T1->Prop) (a: T1), ((exists x:T1, (A x /\\ B x)) -> (forall x:T1, B x -> C x))\n/\\ (B a /\\ ~ C a) -> ~(forall x:T1, A x).\nProof.\nintros.\ndestruct H.\napply ex_not_not_all.\nassert (B a /\\ ~ C a); trivial.\napply and_to_imply in H0.\napply modus_tollens in H.\n+ exists a.\n  destruct H1.\n  assert (forall x:T1, ~ (A x /\\  B x)).\n  - apply not_ex_all_not.\n    exact H.\n  - assert (~ (A a /\\ B a)).\n    * apply H3.\n    * apply not_and_or in H4.\n      destruct H4.\n      ++ trivial.\n      ++ contradiction.\n+ apply ex_not_not_all.\n  exists a.\n  trivial.\nQed.\n\n\n(* Ejercicio 4b *)\nTheorem fourb: forall (T1 T2 T3: Type) (B : T1 -> T2 -> Prop) (m: T2) (C W : T3 -> Prop) (G: T1 -> T3 -> Prop), \n((exists x: T1, ~ (B x m) /\\ forall y: T3, C y -> ~ G x y)\n/\\ (forall z: T1, ~ (forall y : T3, W y -> G z y) -> B z m)) -> forall x: T3, C x -> ~ W x.\nProof.\nintros.\ndestruct H.\ndestruct H.\ndestruct H.\napply H2 in H0.\nassert (forall z: T1, (exists y: T3, ~(W y -> G z y)) -> B z m).\n+ intros.\n  apply H1.\n  apply ex_not_not_all.\n  exact H3.\n+ assert((exists y : T3, ~ (W y -> G x0 y)) -> B x0 m).\n  - apply H3.\n  - apply modus_tollens in H4.\n    eapply not_ex_not_all in H4.\n    apply modus_tollens in H4.\n    apply H4.\n    trivial.\n    trivial.\nQed.\n\n\n(* Ejercicio 4c *)\nTheorem fourc: forall (T1 T3 T2 T4: Type) (P H : T1 -> Prop) (C: T1 -> Prop) (L: T3 -> Prop) (A: T1 -> T3 -> Prop) (R: T2 -> Prop) (B: T2 -> T4 -> Prop),\n((~forall x: T1, ~ P x \\/ ~ H x) -> (forall x: T1, C x /\\ forall y: T3, L y -> A x y)) /\\\n((exists x:T1, H x /\\ forall y: T3, L y -> A x y) -> (forall x: T2, R x /\\ forall y:T4, B x y)) ->\n((~forall x: T2, forall y: T4, B x y) -> forall x: T1, ~ P x \\/ ~ H x).\nProof.\nintros.\ndestruct H0.\napply not_forall_exists_not_double in H1.\ndestruct H1.\ndestruct H1.\napply modus_tollens in H2.\n+ eapply not_ex_all_not in H2.\n  apply not_and_or in H2.\n  destruct H2.\n  * right; apply H2.\n  * apply modus_tollens in H0.\n    - apply NNPP in H0.\n      apply H0.\n    - apply ex_not_not_all.\n      apply not_all_ex_not in H2.\n      destruct H2.\n      exists x.\n      apply or_not_and.\n      right.\n      apply ex_not_not_all.\n      exists x2.\n      trivial.\n+ apply ex_not_not_all.\n  exists x0.\n  apply or_not_and.\n  right.\n  apply ex_not_not_all.\n  exists x1; trivial.\nQed.\n\n\n", "meta": {"author": "victorz3", "repo": "Tarea3VF", "sha": "bfc5507760c435bae5358e4e70b14862e3f33ca1", "save_path": "github-repos/coq/victorz3-Tarea3VF", "path": "github-repos/coq/victorz3-Tarea3VF/Tarea3VF-bfc5507760c435bae5358e4e70b14862e3f33ca1/Props_LC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7323929332555547}}
{"text": "(* Exercise 9 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* Disjunction is commutative *)\n\nTheorem exercise_009 : (A \\/ B) -> (B \\/ A).\nProof.\nimp_i a1.\ndis_e (A \\/ B) a2 a2.\nhyp a1.\ndis_i2.\nhyp a2.\ndis_i1.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop009.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7323350824950272}}
{"text": "Require Import List.\nRequire Import Omega.\n\nLemma app_hd {A}:\n  forall (l1 l2:list A) d,\n  l1 <> nil -> hd d (l1 ++ l2) = hd d l1.\nProof.\n  intros l1 l2 d l1_non_nil; destruct l1.\n  + exfalso; apply l1_non_nil; auto.\n  + rewrite <-app_comm_cons; simpl; auto.\nQed.\n\nLemma app_last {A}:\n  forall (l1 l2:list A) d,\n  l2 <> nil -> last (l1 ++ l2) d = last l2 d.\nProof.\n  intros l1 l2 d l2_non_nil; induction l1.\n  + auto.\n  + cut (length (l1 ++ l2) > 0).\n    {\n      rewrite <-app_comm_cons; simpl; destruct (l1 ++ l2).\n      + simpl; intros; omega.\n      + rewrite IHl1; auto.\n    }\n    cut (length l2 > 0).\n    {\n      intros; rewrite app_length; omega.\n    }\n    destruct l2.\n    - exfalso; apply l2_non_nil; auto.\n    - simpl; omega.\nQed.\n\nLemma app_firstn {A}:\n  forall n (l1 l2:list A),\n  n <= length l1 -> firstn n (l1 ++ l2) = firstn n l1.\nProof.\n  induction n.\n  + auto.\n  + destruct l1.\n    - simpl in *; intros; omega.\n    - intros; rewrite <-app_comm_cons; simpl in *; rewrite IHn by omega; auto.\nQed.\n\nLemma app_firstn' {A}:\n  forall n (l1 l2:list A),\n  length l1 <= n -> firstn n (l1 ++ l2) = l1 ++ (firstn (n - length l1) l2).\nProof.\n  induction n.\n  + destruct l1; simpl; auto; intros; omega.\n  + destruct l1.\n    - simpl; auto.\n    - intros; simpl in *; rewrite IHn; auto; omega.\nQed.\n\nLemma app_skipn {A}:\n  forall n (l1 l2:list A),\n  n <= length l1 -> skipn n (l1 ++ l2) = (skipn n l1) ++ l2.\nProof.\n  induction n.\n  + auto.\n  + destruct l1.\n    - simpl in *; intros; omega.\n    - intros; rewrite <-app_comm_cons; simpl in *; rewrite IHn by omega; auto.\nQed.\n\nLemma app_skipn' {A}:\n  forall n (l1 l2:list A),\n  length l1 <= n -> skipn n (l1 ++ l2) = skipn (n - length l1) l2.\nProof.\n  induction n.\n  + destruct l1; auto; simpl; intros; omega.\n  + destruct l1.\n    - intros; simpl app; simpl length; rewrite <-minus_n_O; auto.\n    - simpl; intros; rewrite IHn; auto; omega.\nQed.\n\nLemma firstn_whole {A}:\n  forall n (l:list A),\n  length l <= n -> firstn n l = l.\nProof.\n  induction n.\n  + destruct l; auto; simpl; intros; omega.\n  + destruct l.\n    - auto.\n    - simpl; intros; rewrite IHn by omega; auto.\nQed.\n\nLemma hd_skip1_cons {A}:\n  forall (l:list A) d,\n  l <> nil -> (hd d l) :: (skipn 1 l) = l.\nProof.\n  intros; destruct l.\n  + exfalso; apply H; auto.\n  + simpl; auto.\nQed.\n\nLemma removelast_length {A}:\n  forall (l:list A),\n  l <> nil -> S (length (removelast l)) = length l.\nProof.\n  induction l.\n  + intros Habs; exfalso; apply Habs; auto.\n  + destruct l as [|b l].\n    - intros; simpl; auto.\n    - intros; simpl in *; apply f_equal, IHl; discriminate.\nQed.\n\nLemma skipn_length {A}:\n  forall (l:list A) n,\n  length (skipn n l) = length l - n.\nProof.\n  induction l.\n  + intros; case n; auto.\n  + destruct n.\n    - auto.\n    - intros; simpl in *; apply IHl; omega.\nQed.\n\nInductive paren :=\n  | open\n  | close.\n\nInductive wp: list paren -> Prop :=\n  | wp_e: wp nil\n  | wp_p: forall l, wp l -> wp (open :: l ++ close :: nil)\n  | wp_c: forall l1 l2, wp l1 -> wp l2 -> wp (l1 ++ l2).\n\nFixpoint is_wp_aux (l:list paren) (n:nat) :=\n  match l, n with\n  | nil, 0 => true\n  | open :: t, k => is_wp_aux t (S k)\n  | close :: t, S k => is_wp_aux t k\n  | _, _ => false\n  end.\n\nDefinition is_wp l := is_wp_aux l 0.\n\nLemma wp_implies_no_change: \n  forall l1 l2 n, wp l1 -> is_wp_aux (l1 ++ l2) n = is_wp_aux l2 n.\nProof.\n  intros l1 l2 n wp_l1.\n  generalize l2, n; clear l2 n.\n  induction wp_l1.\n  + simpl; auto.\n  + intros; simpl; rewrite <-app_assoc, IHwp_l1; simpl; auto.\n  + intros; rewrite <-app_assoc, IHwp_l1_1, IHwp_l1_2; auto.\nQed.\n    \nLemma wp_implies_is_wp: forall l, wp l -> is_wp l = true.\nProof.\n  intros; unfold is_wp; rewrite <-app_nil_r with (l := l).\n  rewrite wp_implies_no_change by auto; auto.\nQed.\n\nFixpoint rep_open (n:nat) :=\n  match n with\n  | 0 => nil\n  | S k => open :: (rep_open k)\n  end.\n\nLemma rep_open_split_last:\n  forall n l, rep_open n ++ open :: l = rep_open (S n) ++ l.\nProof.\n  intros; induction n.\n  + simpl; auto.\n  + simpl rep_open in *; repeat rewrite <-app_comm_cons; rewrite IHn.\n    repeat rewrite <-app_comm_cons; auto.\nQed.\n\nLemma wp_non_nil_starts_open:\n  forall l d, wp l -> l <> nil -> hd d l = open.\nProof.\n  intros l d wp_l l_non_nil.\n  induction wp_l.\n  + exfalso; apply l_non_nil; auto.\n  + simpl; auto.\n  + destruct l1, l2.\n    - simpl in l_non_nil; exfalso; apply l_non_nil; auto.\n    - simpl; apply IHwp_l2; discriminate.\n    - simpl; apply IHwp_l1; discriminate.\n    - simpl; apply IHwp_l1; discriminate.\nQed.\n\nLemma wp_non_nil_ends_close:\n  forall l d, wp l -> l <> nil -> last l d = close.\nProof.\n  intros l d wp_l l_non_nil.\n  induction wp_l.\n  + exfalso; apply l_non_nil; auto.\n  + rewrite app_comm_cons, app_last.\n    - auto.\n    - discriminate.\n  + destruct l1, l2.\n    - simpl in *; exfalso; apply l_non_nil; auto.\n    - rewrite app_nil_l, IHwp_l2; auto.\n    - rewrite app_nil_r, IHwp_l1; auto; discriminate.\n    - rewrite app_last.\n      * rewrite IHwp_l2; auto; discriminate.\n      * discriminate.\nQed.\n\nLemma open_close_ins_keeps_wp:\n  forall l l', wp (l ++ l') -> wp (l ++ open :: close :: nil ++ l').\nProof.\n  (* useful general assertion *)\n  assert (wp (open :: close :: nil)) as wp_oc.\n  {\n    assert (open :: close :: nil = (open :: nil) ++ (close :: nil)) as oc_eq by (simpl; auto).\n    rewrite oc_eq; apply wp_p, wp_e.\n  }\n  (* we do length induction *)\n  cut (forall n l l', length (l ++ l') <= n -> wp (l ++ l') -> wp (l ++ open :: close :: nil ++ l')).\n  {\n    intros H l l'; apply H with (n := length (l ++ l')); omega.\n  }\n  induction n.\n  {\n    (* trivial length 0 case *)\n    destruct l, l'; simpl; intros; try omega.\n    apply wp_oc.\n  }\n  {\n    (* now we do induction in the wp cases *)\n    intros l l' ll'_length_bounds wp_ll'.\n    remember (l ++ l') as ll'.\n    induction wp_ll'.\n    {\n      (* nil case is trivial *)\n      assert (l = nil /\\ l' = nil) as [l_is_nil l'_is_nil] by (apply app_eq_nil; auto).\n      rewrite l_is_nil, l'_is_nil; simpl; apply wp_oc.\n    }\n    {\n      (* the parenthesized one, not so much: we need to start by disposing of the easy cases first *)\n      destruct l, l'.\n      + simpl; apply wp_oc.\n      + assert (nil ++ open :: close :: nil ++ p :: l' = (open :: close :: nil) ++ p :: l') as Heq by auto.\n        rewrite Heq; apply wp_c.\n        - apply wp_oc.\n        - rewrite <-app_nil_l, <-Heqll'; apply wp_p; auto.\n      + assert ((p :: l) ++ open :: close :: nil ++ nil = (p :: l) ++ (open :: close :: nil)) as Heq by auto.\n        rewrite Heq; apply wp_c.\n        - rewrite <-app_nil_r, <-Heqll'; apply wp_p; auto.\n        - apply wp_oc.\n      (* now that we are in the main case, we start by showing the expression follows the\n         open :: x ++ close :: nil shape *)\n      + assert (p = open) as p_is_open.\n        {\n          assert (p = hd close ((p :: l) ++ p0 :: l')) as p_eq by auto.\n          assert (open = hd close (open :: l0 ++ close :: nil)) as open_eq by auto.\n          rewrite p_eq, open_eq, Heqll'; auto.\n        }\n        assert (last (p0 :: l') open = close) as last_is_close.\n        {\n          assert (last (p0 :: l') open = last ((p :: l) ++ p0 :: l') open) as last_eq\n            by (rewrite app_last by discriminate; auto).\n          assert (close = last (open :: l0 ++ close :: nil) open) as close_eq \n            by (rewrite app_comm_cons, app_last by discriminate; auto).\n          rewrite last_eq, close_eq, Heqll'; auto.\n        }\n        rewrite p_is_open, app_removelast_last with (d := open) (l := p0 :: l'), last_is_close\n          by discriminate.\n        assert ((open :: l) ++ open :: close :: nil ++ removelast (p0 :: l') ++ close :: nil =\n                open :: (l ++ open :: close :: nil ++ removelast (p0 :: l')) ++ close :: nil) as Heq.\n        repeat (repeat rewrite app_assoc; repeat rewrite app_comm_cons); auto.\n        (* now we can apply the usual machinery to shrink the string and call the inductive hypothesis *)\n        rewrite Heq; apply wp_p, IHn.\n        (* we have to prove the shrinking *)\n        - assert (S(length(removelast (p0 :: l'))) = S(length l')) as removelast_len_eq\n            by (rewrite removelast_length; try discriminate; auto).\n          rewrite Heqll', app_length in ll'_length_bounds; simpl in ll'_length_bounds.\n          rewrite app_length; omega.\n        (* then we have to prove everything is well founded *)\n        - assert (l0 = l ++ removelast (p0 :: l')) as l0_eq.\n          {\n            apply app_inv_head with (l := open :: nil); simpl app at 1.\n            apply app_inv_tail with (l := close :: nil).\n            rewrite <-app_comm_cons, Heqll', <-p_is_open, <-last_is_close.\n            repeat rewrite <-app_assoc; rewrite <-app_removelast_last by discriminate.\n            simpl; auto.\n          }\n          rewrite <-l0_eq; auto.\n    }\n    {\n      (* the concatenation case *)\n      (* we need to dispose of the easy cases *)\n      destruct l1, l2.\n      + apply IHwp_ll'1; auto; rewrite <-Heqll'.\n      + apply IHwp_ll'2; auto; rewrite <-Heqll'.\n      + apply IHwp_ll'1; rewrite app_nil_r in *; try omega; rewrite <-Heqll'; auto.\n      (* this is the main case *)\n      (* we need to handle the two cases, depending on where the added open :: close falls *)\n      + destruct (le_dec (length (p :: l1)) (length l)).\n        (* the easiest one: the open :: close is entirely beyond the first component *)\n        - rewrite <-firstn_skipn with (n := length (p :: l1)).\n          rewrite app_firstn, app_skipn by auto.\n          assert (firstn (length (p :: l1)) l = p :: l1) as l1_eq.\n          {\n            erewrite <-app_firstn by auto; instantiate (1 := l').\n            rewrite <-Heqll', app_firstn, firstn_whole by auto; auto.\n          }\n          assert (skipn (length (p :: l1)) l ++ l' = p0 :: l2) as l2_eq.\n          {\n            apply app_inv_head with (l := p :: l1).\n            rewrite <-l1_eq, app_assoc, firstn_skipn, Heqll' at 1; auto.\n          }\n          rewrite l1_eq; apply wp_c, IHn; auto.\n          * rewrite app_length, skipn_length.\n            rewrite Heqll', app_length in ll'_length_bounds.\n            assert (length (p :: l1) > 0) by (simpl; omega).\n            omega.\n          * rewrite l2_eq; auto.\n        (* the open :: close falls in the middle or on the first component entirely *)\n        - rewrite <-firstn_skipn with (n := length (p :: l1) + 2).\n          rewrite app_firstn', app_skipn' by omega.\n          assert (length (p :: l1) + 2 - length l - 2 = length (p :: l1) - length l) as len_eq by omega.\n          assert (skipn (length (p :: l1) + 2 - length l) (open :: close :: nil ++ l') = p0 :: l2) as l2_eq.\n          {\n            do 2 rewrite app_comm_cons; rewrite app_skipn' by (simpl length at 1; omega); simpl length at 3.  \n            rewrite len_eq, <-app_skipn' by omega.\n            apply app_inv_head with (l := p :: l1).\n            rewrite <-Heqll', app_skipn', <-minus_n_n by auto; auto.\n          }\n          assert (l ++ firstn (length (p :: l1) - length l) l' = p :: l1) as l1_eq\n            by (rewrite <-app_firstn', <-Heqll', app_firstn, firstn_whole by omega; auto).\n          rewrite l2_eq; apply wp_c; auto.\n          do 2 rewrite app_comm_cons; rewrite app_firstn' by (simpl length at 1; omega); simpl length at 3.\n          rewrite len_eq.\n          apply IHn; rewrite <-app_firstn', <-Heqll', app_firstn, firstn_whole by omega.\n          * rewrite app_length in ll'_length_bounds; simpl in *; omega.\n          * auto.\n    }\n  }\nQed.    \n\nLemma is_wp_implies_wp_aux:\n  forall l n, is_wp_aux l n = true -> wp ((rep_open n) ++ l).\nProof.\n  induction l.\n  {\n    simpl; intros; destruct n.\n    + simpl; apply wp_e.\n    + discriminate.\n  }\n  {\n    intros; destruct a.\n    + rewrite rep_open_split_last; apply IHl; simpl in *; auto.\n    + destruct n.\n      - simpl in *; discriminate.\n      - assert (rep_open (S n) ++ close :: l = rep_open n ++ open :: close :: nil ++ l) as Heq\n          by (rewrite <-rep_open_split_last; simpl; auto).\n        rewrite Heq.\n        apply open_close_ins_keeps_wp, IHl; simpl in *; auto.\n  }\nQed.\n\nLemma is_wp_implies_wp: forall l, is_wp l = true -> wp l.\nProof.\n  unfold is_wp; intros.\n  assert (nil = rep_open 0) as rep_open_0_is_nil by auto.\n  rewrite <-app_nil_l, rep_open_0_is_nil.\n  apply is_wp_implies_wp_aux; auto.\nQed.\n\nLemma is_wp_works:\n  forall l, is_wp l = true <-> wp l.\nProof.\n  split.\n  + apply is_wp_implies_wp.\n  + apply wp_implies_is_wp.\nQed.", "meta": {"author": "mchouza", "repo": "learning-verifiable-c", "sha": "961d28b937d77069532e3b4b0a0b61166f3a691c", "save_path": "github-repos/coq/mchouza-learning-verifiable-c", "path": "github-repos/coq/mchouza-learning-verifiable-c/learning-verifiable-c-961d28b937d77069532e3b4b0a0b61166f3a691c/wp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7322826379432081}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import relation.\n\nAxiom AxiomOfPower:\n  forall U:Type, forall x: Collection U, exists y':Collection (Collection U), forall z:Collection U,\n          (z ⊂ x -> z ∈ y').\n\nInductive PowerCollection {U:Type} (A:Collection U) : Collection (Collection U) :=\n| definition_of_power: forall x':Collection U, x' ⊂ A -> x' ∈ PowerCollection A.\n\n(* 𝔓:Unicode 1D513 *)\nNotation \"𝔓( X )\" := (PowerCollection X) (at level 15).\n\nSection AxiomOfPowerTest.\n  Variable U:Type.\n\n  Goal\n    forall x': Collection U, forall Z:Collection (Collection U),\n        Z = PowerCollection x' ->\n        exists y':Collection (Collection U), forall z:Collection U, (z ⊂ x' -> z ∈ y').\n  Proof.\n    move => x' Z HZ.\n    exists Z.\n    rewrite HZ.\n    move => z Hzx'.\n    apply definition_of_power.\n    apply Hzx'.\n  Qed.\nEnd AxiomOfPowerTest.\n\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/axiom_of_power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7322635864623124}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, b_timesm *)\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\nTheorem b_timesm: forall n m, beautiful n -> beautiful (m * n).\nProof.\n    intros. induction m as [|m'].\n    simpl. apply b_0.\n    simpl. apply b_sum with (n:=n)(m:=m'*n).\n    apply H.\n    apply IHm'.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter9_Library_Prop/b_timesm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7322635859363154}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Hints.ZArith.\nRequire Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos.\nRequire Import Crypto.Util.ZUtil.Testbit.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\n\nLocal Open Scope Z_scope.\n\nNotation stabilizes_after x l := (exists b, forall n, l < n -> Z.testbit x n = b).\n\nLemma stabilizes_after_Proper x\n  : Proper (Z.le ==> Basics.impl) (fun l => stabilizes_after x l).\nProof.\n  intros ?? H [b H']; exists b.\n  intros n H''; apply (H' n); lia.\nQed.\n\nModule Z.\n  Notation stabilization_time x := (Z.max (Z.log2 (Z.pred (- x))) (Z.log2 x)).\n  Notation stabilization_time_weaker x := (Z.log2_up (Z.abs x)).\n\n  Lemma stabilization_time_nonneg x : 0 <= stabilization_time x.\n  Proof. rewrite Z.max_le_iff; constructor; apply Z.log2_nonneg. Qed.\n#[global]\n  Hint Resolve Z.stabilization_time_nonneg : zarith.\n\n  Lemma stabilization_time_weaker_nonneg x : 0 <= stabilization_time_weaker x.\n  Proof. apply Z.log2_up_nonneg. Qed.\n#[global]\n  Hint Resolve Z.stabilization_time_weaker_nonneg : zarith.\nEnd Z.\nGlobal Hint Resolve Z.stabilization_time_nonneg Z.stabilization_time_weaker_nonneg : zarith.\n\nLemma stabilization_time (x:Z) : stabilizes_after x (Z.stabilization_time x).\nProof.\n  destruct (Z_lt_le_dec x 0); eexists; intros;\n    [ eapply Z.bits_above_log2_neg | eapply Z.bits_above_log2]; lia.\nQed.\n\nLemma stabilization_time_weaker (x:Z) : stabilizes_after x (Z.stabilization_time_weaker x).\nProof.\n  eapply stabilizes_after_Proper; try apply stabilization_time.\n  repeat match goal with\n         | [ |- context[Z.abs _ ] ] => apply Zabs_ind; intro\n         | [ |- context[Z.log2 ?x] ]\n           => rewrite (Z.log2_nonpos x) by lia\n         | [ |- context[Z.log2_up ?x] ]\n           => rewrite (Z.log2_up_nonpos x) by lia\n         | _ => rewrite Z.max_r by auto with zarith\n         | _ => rewrite Z.max_l by auto with zarith\n         | _ => etransitivity; [ apply Z.le_log2_log2_up | lia ]\n         | _ => progress Z.replace_all_neg_with_pos\n         | [ H : 0 <= ?x |- _ ]\n           => assert (x = 0 \\/ x = 1 \\/ 1 < x) by lia; clear H; destruct_head' or; subst\n         | _ => lia\n         | _ => simpl; lia\n         | _ => rewrite Z.log2_up_eqn by assumption\n         | _ => progress change (Z.log2_up 1) with 0\n         end.\nQed.\n\nLemma land_stabilizes (a b la lb:Z) (Ha:stabilizes_after a la) (Hb:stabilizes_after b lb) : stabilizes_after (Z.land a b) (Z.max la lb).\nProof.\n  destruct Ha as [ba Hba]. destruct Hb as [bb Hbb].\n  exists (andb ba bb); intros n Hn.\n  rewrite Z.land_spec, Hba, Hbb; trivial; lia.\nQed.\n\nLemma lor_stabilizes (a b la lb:Z) (Ha:stabilizes_after a la) (Hb:stabilizes_after b lb) : stabilizes_after (Z.lor a b) (Z.max la lb).\nProof.\n  destruct Ha as [ba Hba]. destruct Hb as [bb Hbb].\n  exists (orb ba bb); intros n Hn.\n  rewrite Z.lor_spec, Hba, Hbb; trivial; lia.\nQed.\n\nLocal Arguments Z.pow !_ !_.\nLocal Arguments Z.log2_up !_.\nLocal Arguments Z.add !_ !_.\nLemma testbit_nonneg_iff x\n  : (exists l, 0 <= l /\\ forall n : Z, l < n -> Z.testbit x n = false) <-> 0 <= x.\nProof.\n  split; intro H.\n  { destruct H as [l [Hl H]].\n    edestruct Z_lt_le_dec; [ | eassumption ].\n    pose proof (fun pf n => Z.bits_above_log2_neg x n pf) as H'.\n    specialize_by (lia || assumption).\n    specialize (H (1 + Z.max l (Z.log2 (Z.pred (- x))))).\n    specialize (H' (1 + Z.max l (Z.log2 (Z.pred (- x))))).\n    specialize_by (apply Z.max_case_strong; lia).\n    congruence. }\n  { pose proof (fun n => Z.bits_above_log2 x n H) as Hf.\n    eexists; split; [ | eapply Hf ]; auto with zarith. }\nQed.\n\nLemma stabilizes_bounded_pos (x l:Z) (H:stabilizes_after x l) (Hl : 0 <= l) (Hx : 0 < x)\n  : x <= 2^(l + 1) - 1.\nProof.\n  assert (Hlt : forall l n, l < n <-> l + 1 <= n) by (intros; lia).\n  destruct H as [b H].\n  destruct (proj2 (testbit_nonneg_iff x)) as [l' [H0' H1']]; [ lia | ].\n  pose proof (Z.testbit_false_bound x (l' + 1)) as Hf.\n  pose proof (Z.testbit_false_bound x (l + 1)) as Hf'.\n  pose proof (fun pf n => Z.bits_above_log2 x n pf) as Hf''.\n  pose proof (fun pf n => Z.log2_lt_pow2 x n pf) as Hlg.\n  specialize_by lia.\n  setoid_rewrite <- Z.le_ngt in Hf.\n  setoid_rewrite <- Z.le_ngt in Hf'.\n  setoid_rewrite <- Hlt in Hf; setoid_rewrite <- Hlt in Hf'; clear Hlt.\n  setoid_rewrite <- Hlg in Hf''; clear Hlg.\n  destruct b; specialize_by (lia || assumption); [ | lia ].\n  specialize (H (1 + Z.max l l')).\n  specialize (H1' (1 + Z.max l l')).\n  specialize_by (apply Z.max_case_strong; lia).\n  congruence.\nQed.\n\nLemma stabilizes_bounded (x l:Z) (H:stabilizes_after x l) (Hl : 0 <= l) : Z.abs x <= 2^(1 + l).\nProof.\n  assert (Hlt : forall l n, l < n <-> l + 1 <= n) by (intros; lia).\n  rewrite Z.add_comm.\n  destruct (Z_zerop x); subst; simpl.\n  { cut (0 < 2^(l + 1)); auto with zarith. }\n  apply Zabs_ind; intro.\n  { etransitivity; [ apply stabilizes_bounded_pos; eauto | ]; lia. }\n  { Z.replace_all_neg_with_pos.\n    destruct (Z.eq_dec x 1); subst.\n    { assert (1 < 2^(l+1)) by auto with zarith.\n      lia. }\n    { assert (H' : stabilizes_after (Z.pred x) l).\n      { destruct H as [b H]; exists (negb b).\n        do 2 let x := fresh in intro x; specialize (H x).\n        rewrite Z.bits_opp in H by lia.\n        destruct b; rewrite ?Bool.negb_true_iff, ?Bool.negb_false_iff in H; assumption. }\n      clear H.\n      apply stabilizes_bounded_pos in H'; auto; lia. } }\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/Stabilization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.732178842842324}}
{"text": "(**************************************\n  not Finish reading, not Finish exercise\n**************************************)\n\nRequire Import Coq.Init.Nat.\nRequire Import Coq.Lists.List.\n\n\n\n\n(* ================================================================= *)\n(** * The apply Tactic *)\n\n(* This is proved in chapter Lists. *)\nTheorem rev_involutive: forall l: list nat, rev (rev l) = l.\nProof. Admitted.\n\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\nTheorem silly_ex:\n  (forall n, even n = true -> odd (S n) = true) ->\n  even 3 = true ->\n  odd 4 = true.\nProof.\n  intros H.\n  apply H.\nQed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\nTheorem rev_exercise1: forall (l l': list nat),\n  l = rev l' -> l' = rev l.\nProof.\n  intros l l' H.\n  rewrite H.\n  symmetry.\n  apply rev_involutive.\nQed.\n\n\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n\n(**\n   apply: change goal by forall rule or non-forall rule.\n   rewrite: change goal by non-forall rule.\n **)\n\n\n\n\n\n(* ================================================================= *)\n(** * The apply ... with ... Tactic *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\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\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise: forall (n m o p: nat),\n   m = (minustwo o) ->\n   (n + p) = m ->\n   (n + p) = (minustwo o).\nProof.\n  intros n m o p P Q.\n  rewrite <- P.\n  rewrite -> Q.\n  reflexivity.\nQed. (* do not know how to use apply with *)\n\n\n\n\n\n(* ================================================================= *)\n(** * The inversion Tactic *)\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3: forall (X: Type) (x y z: X) (l j: list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros X x y z l j P Q.\n  inversion P.\n  inversion Q.\n  rewrite H0.\n  reflexivity.\nQed.\n\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6: forall (X: Type) (x y z: X) (l j: list X),\n  x :: y :: l = nil ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  intros X x y z l j P Q.\n  inversion P.\nQed.\n\n\n\n\n\n(* ================================================================= *)\n(** * Using Tactics on Hypotheses *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\nTheorem plus_n_n_injective: forall n m, n + n = m + m -> n = m.\nProof.\n  intros n m P.\n  induction n.\n  - simpl in P.\n    destruct m.\n    + reflexivity.\n    + inversion P.\n  - induction m.\n    + simpl in P.\n      inversion P.\n    + simpl in P.\n      inversion P.\n      rewrite <- plus_n_Sm in H0.\n      rewrite <- plus_n_Sm in H0.\n      inversion H0.\n      rewrite -> H1 in IHn.\nAbort. (* TODO *)\n\n\n\n(* ================================================================= *)\n(** * Varying the Induction Hypothesis *)\n\n\n\n\n\n\n(* ================================================================= *)\n(** * Using destruct on Compound Expressions *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\nTheorem combine_split: forall X Y (l: list (X * Y)) l1 l2,\n  split l = (l1, l2) -> combine l1 l2 = l.\nProof.\n  induction l as [|(x, y) l'].\n  + intros l1 l2 h1.\n    simpl in h1.\n    inversion h1.\n    reflexivity.\n  + simpl.\n    destruct (split l') as [xs ys].\n    intros l1 l2 h1.\n    inversion h1.\n    simpl.\n    rewrite IHl'.\n    - reflexivity.\n    - reflexivity.\nQed.\n\n\n\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\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  - destruct (f true) eqn:H.\n    + rewrite H.\n      rewrite H.\n      reflexivity.\n    + destruct (f false) eqn:H1.\n      * apply H.\n      * apply H1. \n  - destruct (f true) eqn:H.\n    + destruct (f false) eqn:H1.\n      * rewrite H.\n        rewrite H.\n        reflexivity.\n      * rewrite H1.\n        rewrite H1.\n        reflexivity.\n    + destruct (f false) eqn:H1.\n      * rewrite H.\n        rewrite H1.\n        reflexivity.\n      * rewrite H1.\n        rewrite H1.\n        reflexivity.\nQed.\n\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/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8856314617436728, "lm_q1q2_score": 0.7321619821858859}}
{"text": "Require Export Composition.\n\n\n\nDefinition Transitive R S :=\n    forall x y z, x ∈ S -> y ∈ S -> z ∈ S -> \n    <|x,y|> ∈ R -> <|y,z|> ∈ R -> <|x,z|> ∈ R.\n\nDefinition Symmetric R S :=\n  forall x y, x ∈ S -> y ∈ S -> \n  <|x,y|> ∈  R -> <|y,x|> ∈ R.\n      \nDefinition Antisymmetric R S :=\n  forall x y, x ∈ S -> y ∈ S -> \n  <|x,y|> ∈ R -> <|y,x|> ∈ R -> x = y.\n\nDefinition Asymmetric R S :=\n  forall x y, x ∈ S -> y ∈ S -> \n  <|x,y|> ∈ R -> ~ <|y,x|> ∈ R.\n\nDefinition Nonsymmetric R S :=\n  ~ Symmetric R S /\\ ~ Antisymmetric R S.\n  \nDefinition Connected R S :=\n  forall x y, x ∈ S -> y ∈ S -> <|x,y|> ∈ R \\/ <|y,x|> ∈ R.\n\nDefinition Reflexive R S :=\n  forall x, x ∈ S -> <|x,x|> ∈ R.\n\nDefinition Irreflexive R S :=\n  forall x, x ∈ S -> ~ <|x,x|> ∈ R.\n\nDefinition Nonreflexive R S :=\n  exists x y, x ∈ S /\\ y ∈ S /\\ <|x,x|> ∈ R /\\ ~ <|y,y|> ∈ R.\n\nTheorem asym_irr R S :\n    Asymmetric R S -> Irreflexive R S.\nProof.\n  intros H x xS xxR.\n  specialize (H x x xS xS xxR).\n  case (H xxR).\nQed.\n\nTheorem transirr_asym R S :\n  Transitive R S -> Irreflexive R S -> Asymmetric R S.\nProof.\n  intros trans irr x y xS yS xyR yxR.\n  specialize (trans x y x xS yS xS xyR yxR).\n  specialize (irr x xS).\n  case (irr trans).\nQed.\n\nDefinition Tiering R S :=\n  Transitive R S /\\ Nonsymmetric R S.\n\nDefinition Preordering R S :=\n    Transitive R S /\\ Reflexive R S.\n\n    \n\n\n\n\n      \n\n\n        \n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "arrow", "sha": "7b465196490274b9df04748ee8caf2aa3b1c3edb", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-arrow", "path": "github-repos/coq/gaxiiiiiiiiiiii-arrow/arrow-7b465196490274b9df04748ee8caf2aa3b1c3edb/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7321619820344183}}
{"text": "Set Warnings \"-notation-overidden,-parsing\".\n\nDefinition relation (X : Type) := X -> X -> Prop.\n\nPrint le.\n\nCheck le : nat -> nat -> Prop.\nCheck le : relation nat.\n\nDefinition partial_function {X : Type} (R : relation X) := \n forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\nTheorem ex_falso_quodlibet : forall (P : Prop), False -> P.\nProof. intros. destruct H. Qed.\n\nDefinition reflexive {X : Type} (R : relation X) :=\n forall a : X, R a a.\n\nDefinition transitive {X : Type} (R : relation X) :=\n forall a b c : X, R a b -> R b c -> R a c.\n\nDefinition symmetric {X : Type} (R : relation X) :=\n forall a b : X, R a b -> R b a -> R a b.\n\nDefinition equivalence {X : Type} (R : relation X) :=\n (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n", "meta": {"author": "scottviteri", "repo": "CoqProjects", "sha": "57ad9d6840ad3232d442861a0df3a583bef1ee62", "save_path": "github-repos/coq/scottviteri-CoqProjects", "path": "github-repos/coq/scottviteri-CoqProjects/CoqProjects-57ad9d6840ad3232d442861a0df3a583bef1ee62/LogicalFoundationsProblems/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.73216197651413}}
{"text": "Require Import Coq.Logic.Decidable.\n\n(**\n   This follows Chapter 14 (Least Number Search) of\n   #<a href=\"http://www.ps.uni-saarland.de/courses/cl-ss12/script/icl.pdf\">Geert Smolka's Introduction to Computational Logic</a>#\n  \n   The goal is to prove, for any decidable property [P : nat -> Prop], that [(exists n, P n) -> { n : nat | P n }].\n\n *)\n\nSection LNS.\n  Require Import PeanoNat.\n\n  Variable P : nat -> Prop.\n  Variable Pdec : forall n, {P n} + { ~ (P n)}.\n\n  Inductive safe (n : nat) : Prop :=\n  | safeI : P n -> safe n\n  | safeS : safe (S n) -> safe n.\n\n  Definition low (n : nat) :=\n    forall k, k <= n -> P k -> k = n.\n\n  Definition min (n : nat) :=\n    P n /\\ low n.\n\n  Lemma low_S : forall n, low n -> ~(P n) -> low (S n).\n  Proof.\n    unfold low. intros.\n    destruct (proj1 (Nat.le_succ_r _ _) H1).\n    (* k <= n *)\n    specialize (H k H3 H2). subst.\n    destruct (H0 H2).\n    (* k = S n *)\n    apply H3.\n  Qed.\n\n  Fixpoint firstc' (n : nat) (l : low n) (s : safe n) : { m | min m}.\n  Proof.\n    destruct (Pdec n).\n    exact (exist _ n (conj p l)).\n    apply firstc' with (n:= S n).\n    destruct s.\n    destruct (n0 H).\n    apply low_S ; assumption.\n    destruct s.\n    destruct (n0 H).\n    assumption.\n  Qed.\n\n  Lemma safe_O : forall n, safe n -> safe O.\n  Proof.\n    induction n. tauto. intro. apply IHn, safeS, H.\n  Defined.\n\n  Lemma exists_safe_O : ex P -> safe O.\n  Proof.\n    intros [n A]. apply (safe_O n). apply (safeI _ A).\n  Qed.\n  \n  Proposition least_witness : (exists n, P n) -> { n : nat | min n}.\n  Proof.\n    intro.\n    apply (firstc' O).\n    unfold low. intros. inversion H0. reflexivity.\n    apply (exists_safe_O H).\n  Qed.\n\n  Proposition some_witness : (exists n, P n) -> { n : nat | P n }.\n  Proof.\n    intro.\n    apply least_witness in H.\n    unfold min in H.\n    apply (exist P (proj1_sig H)).\n    apply (proj2_sig H).\n  Defined.\nEnd LNS.\n  \nSection LNS_Pi2.\n  Variable P : nat -> nat -> Prop.\n  Variable Pdec : forall n m, {P n m} + { ~ (P n m) }.\n  \n  Definition search (W : forall n, exists m, P n m) (n : nat) : { m : nat | min (P n) m }.\n  Proof.\n    apply (least_witness (P n) (Pdec n) (W n)).\n  Qed.\n\nEnd LNS_Pi2.", "meta": {"author": "wetneb", "repo": "sigmalocales", "sha": "a42975000c9e505103e4321f7413af992fea5e0c", "save_path": "github-repos/coq/wetneb-sigmalocales", "path": "github-repos/coq/wetneb-sigmalocales/sigmalocales-a42975000c9e505103e4321f7413af992fea5e0c/LeastNumberSearch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7321445342219861}}
{"text": "Require Import Frap.\n\nLemma add_comm :\n  forall a b,\n    a + b = b + a.\nProof.\nShow Proof.\n  induct a.\nShow Proof.\nPrint nat_ind.\n  + simplify.\nShow Proof. (* Notice simplify doesn't actually \"do\" anything to the proof term *)\n\n(* TIP 1: Try to avoid nested induction *)\n(* Instead: try searching through all the theorems to find something of a certain shape *)\nSearch (_ = _ + 0).  (* this found a plus_n_0 theorem *)\n  apply plus_n_O.\nShow Proof.\n  + simplify.\nShow Proof.\n  rewrite IHa. (* plug relevant vars into Inductive Hypothesis *)\nShow Proof.\n(* The current goal \"S (b + a) = b + S a\" would require induction on second arg *)\n(* Instead try search again *)\nSearch (_ + S _ = S (_ + _)).  (* and find Nat.add_succ_r *)\n  symmetry.\nShow Proof.\n  apply Nat.add_succ_r.\nShow Proof. (* Now there are no ?Goals, and we're done *)\nQed.\n\n(*  TIP 2: Use \"debug auto.\" to see what \"auto.\" is doing !  *)\n", "meta": {"author": "samtay", "repo": "uw-programming-languages", "sha": "8904613423bddfc295834741fbce7c50ab5dac5d", "save_path": "github-repos/coq/samtay-uw-programming-languages", "path": "github-repos/coq/samtay-uw-programming-languages/uw-programming-languages-8904613423bddfc295834741fbce7c50ab5dac5d/notes/02-lecture-04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7321445324504517}}
{"text": "Require Import Relation_Definitions  Morphisms.\nRequire Import Setoid.\nRequire Import Arith.\nRequire Import Pnat.\nRequire Import MyZ.\n\nClass Group:=\n{\n\tT:Set;\n\teq:T->T->Prop;\n\te:T;\n\tinv:T->T;\n\top:T->T->T;\n\tincl:T->Prop;\n\tequiv: Equivalence eq;\n\tequiv_dec:forall x y:T,{eq x y}+{~eq x y};\n\tclosed_op:forall x y:T,incl x->incl y->incl(op x y);\nclosed_inv:forall x:T,incl x->incl (inv x);\nincl_dec:forall x:T,{incl x}+{~incl x};\n\twell_inv:forall x y:T,eq x y->eq(inv x)(inv y);\n\twell_op:\n\tforall x1 y1 x2 y2:T,eq x1 y1->eq x2 y2->\n\teq(op x1 x2)(op y1 y2);\nwell_incl:forall x1 x2:T,eq x1 x2->incl x1->incl x2;\n\tassoc:forall x y z:T,eq (op(op x y)z)(op x (op y z));\n\te_r:forall x:T,eq(op x e)x;\n\te_l:forall x:T,eq(op e x)x;\n\tinv_r:forall x:T,eq (op x(inv x))e;\n\tinv_l:forall x:T,eq(op (inv x)x)e\n}.\n\nAdd Parametric Relation (G:Group): T eq\n reflexivity proved by (@Equivalence_Reflexive T  _ equiv)\n symmetry proved by (@Equivalence_Symmetric T _ equiv)\n transitivity proved by (@Equivalence_Transitive T _ equiv)\n as Group_equiv_x.\n\nAdd Parametric Morphism \n(G:Group):\ninv with signature (eq==>eq)as well_inv_x.\napply well_inv.\nQed.\nAdd Parametric Morphism\n(G:Group):\nop with signature(eq==>eq==>eq)as well_op_x.\nintros x y H x0 y0.\napply well_op.\nexact H.\nQed.\nAdd Parametric Morphism \n(G:Group):\nincl with signature (eq==>iff)as well_incl_x.\nintros.\nsplit.\napply well_incl.\nexact H.\napply well_incl.\nsymmetry.\nexact H.\nQed.\n\n\nTheorem right_law\n(g:Group)\n:forall a b c:T,eq (op a c)(op b c)->eq a b.\nintros.\nassert (eq (op (op a c)(inv c))(op(op b c)(inv c))).\nrewrite H.\nreflexivity.\nrewrite assoc in H0.\nrewrite (assoc b c)in H0.\nrewrite inv_r in H0.\nrewrite e_r in H0.\nrewrite e_r in H0.\nexact H0.\nQed.\nTheorem left_law\n(g:Group)\n:forall a b c:T,eq (op c a)(op c b)->eq a b.\nintros.\nassert (eq(op(inv c)(op c a))(op(inv c)(op c b))).\nrewrite H.\nreflexivity.\nrewrite <-assoc in H0.\nrewrite <-(assoc (inv c) c)in H0.\nrewrite inv_l in H0.\nrewrite e_l in H0.\nrewrite e_l in H0.\nexact H0.\nQed.\nTheorem inv_inv(G:Group)\n:forall x:T,eq (inv (inv x))x.\nintros.\napply left_law  with (c:=inv x).\nrewrite inv_l.\napply inv_r.\nQed.\nTheorem inv_op(G:Group)\n:forall x y:T,\neq(inv(op x y))(op(inv y)(inv x)).\nintros.\napply right_law with (c:=(op x y)).\nrewrite inv_l.\nrewrite assoc.\nrewrite <-(assoc(inv x)).\nrewrite inv_l.\nrewrite e_l.\nrewrite inv_l.\nreflexivity.\nQed.\n\nTheorem inv_e(G:Group):eq(inv e)e.\napply right_law with (c:=e).\nrewrite e_l.\napply inv_l.\nQed. \n\n\n\n\nProgram Definition TrivialGroup:Group\n:=\n{|\nT:=unit\n;eq:=(fun a b=>True)\n;e:=tt\n;inv:=(fun _=>tt)\n;op:=(fun _ _=>tt)\n;incl:=(fun _=>True)\n|}.\nObligation 1.\nsplit.\nauto.\nauto.\nauto.\nQed.\nObligation 2.\nleft.\nexact I.\nQed.\nObligation 5.\nleft.\nexact I.\nQed.\n\n\nProgram Definition ZGroup:Group\n:=\n{|\nT:=myZ\n;eq:=myZeq\n;e:=myZzero\n;inv:=myZopp\n;op:=myZplus\n;incl:=(fun _=>True)\n;equiv:=zequiv\n;well_inv:=well_myZopp\n;well_op:=well_myZplus\n;assoc:=myZplus_assoc\n;e_r:=(fun x=>(myZplus_zero_r x))\n;e_l:=(fun x=>(myZplus_zero_l x))\n;inv_r:=(fun x=>(myZplus_myZopp_r x))\n;inv_l:=(fun x=>(myZplus_myZopp_l x))\n |}.\nObligation 1 of ZGroup.\napply myZeq_dec.\nQed.\nObligation 4.\nauto.\nQed.\n\n\nClass SubGroup:Type:=\n{\nG:Group\n;sub:T->Prop\n;sub_then_incl:forall a:T,sub a->incl a\n;well_sub:forall x1 x2:T,eq x1 x2->sub x1->sub x2\n;op_inv_a_b:forall a b:T,sub a->sub b->sub (op (inv a)b)\n;sub_e:sub e\n;sub_dec:forall x:T,{sub x}+{~sub x}\n}.\nAdd Parametric Morphism\n(sg:SubGroup):\nsub with signature (eq==>iff) as well_sub_x.\nintros.\nsplit.\nexact (well_sub x y H).\napply (well_sub y x).\ninfo symmetry.\nexact H.\nQed.\n\nProgram Definition AsGroup(sg:SubGroup):Group:=\n{|\nT:=(@T G)\n;incl:=sub\n;eq:=eq\n;e:=(@e G)\n;inv:=(@inv G)\n;op:=(@op G)\n;equiv_dec:=(@equiv_dec (@G sg))\n;incl_dec:=sub_dec\n;assoc:=assoc\n;e_r:=e_r\n;e_l:=e_l\n;inv_r:=inv_r\n;inv_l:=inv_l\n|}.\nObligation 1.\ncut (eq x (inv(inv x))).\nintro.\napply (well_sub (op(inv(inv x))y)).\nrewrite <-H1.\nreflexivity.\napply op_inv_a_b.\nassert (sub(op (inv x)e)).\napply (op_inv_a_b x e).\nexact H.\nexact sub_e.\napply (well_sub  (op(inv x)e)) .\nrewrite e_r.\nreflexivity.\nexact H2.\nexact H0.\nsymmetry.\napply inv_inv.\nQed.\nObligation 2.\napply well_sub with (x1:=(op (inv x)e)).\napply e_r.\napply op_inv_a_b.\nexact H.\nexact sub_e.\nQed.\nObligation 3.\nAdmitted.\nObligation 4.\nrewrite H.\nrewrite H0.\nreflexivity.\nQed.\nObligation 5.\napply (well_sub x1 x2).\nexact H.\nexact H0.\nQed.\n\n\nDefinition Normal\n(sg:SubGroup):Prop\n:=forall a b:T,sub (op(inv a) b)->sub(op b(inv a)).\n\nTheorem Normal2\n(sg:SubGroup)\n:Normal sg\n->forall a g:T,\nsub a->sub (op (op (inv g)a)g).\nunfold Normal.\nintros.\ngeneralize (H (inv(op a g)) (inv g)).\nintros.\nrewrite inv_inv in H1.\nrewrite assoc in H1.\nrewrite inv_r in H1.\nrewrite e_r in H1.\nrewrite <-assoc in H1.\napply (H1 H0).\nQed.\n\n\n\nClass QuotientGroup:Type:=\n{\nsg:SubGroup\n;normal_sg:Normal sg\n}.\nProgram Definition AsQGroup(qg:QuotientGroup)\n:Group:=\n{|T:=(@T G)\n;incl:=(@incl (@G sg))\n;eq:=fun a b=>sub (op (inv a)b)\n;inv:=(@inv (@G (@sg qg)))\n;op:=op\n;e:=e\n;incl_dec:=_\n|}.\n\nObligation 1.\nsplit.\nunfold Reflexive.\nintros.\nrewrite inv_l.\napply sub_e.\nunfold Symmetric.\nintros.\nassert (sub(inv(op(inv y)x))).\nrewrite inv_op.\nrewrite inv_inv.\nexact H.\nrewrite <-(inv_inv _ (op(inv y)x)).\nrewrite <-e_r.\napply op_inv_a_b.\nexact H0.\nexact sub_e.\nunfold Transitive.\nintros.\n\nassert (sub (op(op(inv x)y)(op(inv y)z))).\napply (@closed_op (AsGroup sg) (op(inv x) y)).\nexact H.\nexact H0.\nrewrite assoc in H1.\nrewrite <-(assoc y (inv y)) in H1.\nrewrite inv_r in H1.\nrewrite e_l in H1.\nexact H1.\nQed.\nObligation 2.\nexact (sub_dec (op(inv x)y)).\nQed.\nObligation 3.\napply (closed_op x y H H0).\nQed.\nObligation 4.\napply closed_inv.\nexact H.\nQed.\nObligation 5.\napply incl_dec.\nQed.\nObligation 6.\napply normal_sg.\nrewrite <-inv_op.\ndestruct qg.\ndestruct sg0.\napply (@closed_inv (AsGroup sg) (op (inv x)y))  .\n\n\napply H.\nQed.\n\nObligation 7.\nassert (sub (op(op (inv x2)(op(inv x1)y1))(op x2(op(inv x2)y2)))).\nrewrite <-assoc.\ngeneralize normal_sg.\nintro.\nassert (sub (op(op(inv x2)(op(inv x1)y1))x2)).\napply Normal2.\nexact H1.\napply H.\n\n\napply (@closed_op (AsGroup sg) _ (op(inv x2)y2)).\nexact H2.\nexact H0.\n\nrewrite inv_op.\nrewrite <-(assoc x2)in H1.\nrewrite inv_r in H1.\nrewrite e_l in H1.\nrewrite <-assoc.\nrewrite (assoc _ _ y1).\nexact H1.\nQed.\nObligation 8.\napply sub_then_incl in H.\nassert (incl (op x1(op(inv x1)x2))).\napply (closed_op _ _ H0 H).\nrewrite <-assoc in H1.\nrewrite inv_r in H1.\nrewrite e_l in H1.\nexact H1.\nQed.\n\nObligation 9.\nrewrite inv_op.\nrewrite inv_op.\nrewrite assoc.\nrewrite assoc.\nrewrite <-(assoc (inv x)x).\nrewrite inv_l.\nrewrite e_l.\nrewrite <-(assoc(inv y)).\nrewrite inv_l.\nrewrite e_l.\nrewrite inv_l.\napply sub_e.\nQed.\nObligation 10.\nrewrite e_r.\nrewrite inv_l.\napply sub_e.\nQed.\n\nObligation 11.\nrewrite e_l.\nrewrite inv_l.\nexact sub_e.\nQed.\nObligation 12.\nrewrite inv_r.\nrewrite inv_l.\nexact sub_e.\nQed.\nObligation 13.\nrewrite inv_l.\nrewrite inv_l.\nexact sub_e.\nQed.\n\nProgram Definition nMyZ(n:nat):SubGroup\n:=\n{|\nG:=ZGroup\n;sub:=fun k:myZ=>(exists m:myZ,k==(myZpos n)*m)\n;sub_then_incl:=_\n;well_sub:=_\n;op_inv_a_b:=_\n;sub_e:=_\n;sub_dec:=_\n|}.\nObligation 2.\ndestruct x1,x2,H0.\nrewrite H in H1.\nexists (myZmake n4 n5).\napply H1.\nQed.\n\nObligation 3.\nexists ((myZopp H)+H0).\nrewrite H1.\nrewrite H2.\nchange (myZopp\n  ((myZpos n)*H)+\n  ((myZpos n)*H0)\n==((myZpos n)*(myZopp H + H0))).\nrewrite <-myZmul_myZopp_compat_r.\nsymmetry.\napply myZmul_myZplus_distr_l.\nQed.\nObligation 4.\nchange(exists m : myZ,\nmyZzero==(myZpos n)*m\n).\nexists myZzero.\nsimpl.\nring.\nQed.\nObligation 5.\nchange({(exists m : myZ,x ==(myZpos n)*m)} +\n{~(exists m : myZ,x ==(myZpos n)*m)}).\napply myZdivisible_dec.\n", "meta": {"author": "koba-e964", "repo": "coqworks", "sha": "d6d154e0fda8adc3d65a4ea78cdbc64993f7c59c", "save_path": "github-repos/coq/koba-e964-coqworks", "path": "github-repos/coq/koba-e964-coqworks/coqworks-d6d154e0fda8adc3d65a4ea78cdbc64993f7c59c/Group.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7321282481116888}}
{"text": "Require Export low_mods.\nRequire Import Num_Occ Indicies.\n\nFixpoint num_occ_l (l : list predicate) (P : predicate) : nat :=\n  match l with\n  | nil => 0\n  | cons Q l' => if predicate_dec P Q then 1 + num_occ_l l' P\n                                   else num_occ_l l' P\n  end.\n\nLemma num_occ_l_app : forall (l1 l2 : list predicate) (P : predicate),\n  num_occ_l (app l1 l2) P = num_occ_l l1 P + num_occ_l l2 P.\nProof.\n  induction l1.  intros. reflexivity.\n  intros l2 P. simpl. rewrite IHl1. \n  destruct (predicate_dec P a); lia.\nQed.\n\nLemma leb_num_occ : forall (alpha : SecOrder) (P : predicate),\n  (num_occ_l (preds_in alpha) P) <= (length (preds_in alpha)).\nProof.\n  intros alpha P.\n  induction alpha; simpl; auto;\n  try (destruct (predicate_dec P p); auto);\n  try (  rewrite num_occ_l_app; rewrite app_length; lia);\n  lia.\nQed.\n\nLemma leb_id_fwd_plus : forall (alpha1 alpha2: SecOrder) (P : predicate) \n                                    (n: nat),\n   n <=\n      (length (preds_in alpha1) - num_occ_l (preds_in alpha1) P) ->\n   n <=\n      (length (preds_in alpha1) + length (preds_in alpha2) -\n        (num_occ_l (preds_in alpha1) P + \n           num_occ_l (preds_in alpha2) P)).\nProof.\n  intros alpha1 alpha2 P n Hleb.\n  pose proof (leb_num_occ alpha2 P). firstorder.\nQed.\n\nLemma num_occ_l_ind_l_rev : forall l P,\n  num_occ_l l P = length (indicies_l_rev l P).\nProof.\n  induction l; intros P. auto.\n  simpl in *. dest_pred_dec a P. simpl.\n  firstorder. \nQed.\n\nLemma num_occ__l : forall (alpha : SecOrder) (P : predicate),\n  (num_occ_l (preds_in alpha) P) = (num_occ alpha P).\nProof.\n  intros. unfold num_occ.\n  unfold indicies. rewrite map_length.\n  apply num_occ_l_ind_l_rev.\nQed.\n", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq/coq_code/Num_occ_l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7321009154324398}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\n\nRequire Import Exponentiation.\n\n(* Why3 goal *)\nNotation power := Zpower.\n\nLemma power_is_exponentiation :\n  forall x n, (0 <= n)%Z -> power x n = Exponentiation.power _ 1%Z Zmult x n.\nProof.\nintros x [|n|n] H.\neasy.\n2: now elim H.\nunfold Exponentiation.power, power, Zpower_pos.\nnow rewrite iter_nat_of_P.\nQed.\n\n(* Why3 goal *)\nLemma Power_0 : forall (x:Z), ((power x 0%Z) = 1%Z).\nProof.\nintros x.\napply refl_equal.\nQed.\n\n(* Why3 goal *)\nLemma Power_s : forall (x:Z) (n:Z), (0%Z <= n)%Z -> ((power x\n  (n + 1%Z)%Z) = (x * (power x n))%Z).\nProof.\nintros x n h1.\nrewrite Zpower_exp.\nchange (power x 1) with (x * 1)%Z.\nring.\nnow apply Zle_ge.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Power_s_alt : forall (x:Z) (n:Z), (0%Z < n)%Z -> ((power x\n  n) = (x * (power x (n - 1%Z)%Z))%Z).\nintros x n h1.\nrewrite <- Power_s.\nf_equal; auto with zarith.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Power_1 : forall (x:Z), ((power x 1%Z) = x).\nProof.\nexact Zmult_1_r.\nQed.\n\n(* Why3 goal *)\nLemma Power_sum : forall (x:Z) (n:Z) (m:Z), (0%Z <= n)%Z -> ((0%Z <= m)%Z ->\n  ((power x (n + m)%Z) = ((power x n) * (power x m))%Z)).\nProof.\nintros x n m Hn Hm.\nnow apply Zpower_exp; apply Zle_ge.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult : forall (x:Z) (n:Z) (m:Z), (0%Z <= n)%Z -> ((0%Z <= m)%Z ->\n  ((power x (n * m)%Z) = (power (power x n) m))).\nProof.\nintros x n m Hn Hm.\nrewrite 3!power_is_exponentiation ; auto with zarith.\napply Power_mult ; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult2 : forall (x:Z) (y:Z) (n:Z), (0%Z <= n)%Z ->\n  ((power (x * y)%Z n) = ((power x n) * (power y n))%Z).\nProof.\nintros x y n Hn.\nrewrite 3!power_is_exponentiation ; auto with zarith.\napply Power_mult2 ; auto with zarith.\nQed.\n\n(* Why3 goal *)\nLemma Power_non_neg : forall (x:Z) (y:Z), ((0%Z <= x)%Z /\\ (0%Z <= y)%Z) ->\n  (0%Z <= (power x y))%Z.\nintros x y (h1,h2).\nnow apply Z.pow_nonneg.\nQed.\n\nOpen Scope Z_scope.\n\n(* Why3 goal *)\nLemma Power_monotonic : forall (x:Z) (n:Z) (m:Z), ((0%Z < x)%Z /\\\n  ((0%Z <= n)%Z /\\ (n <= m)%Z)) -> ((power x n) <= (power x m))%Z.\nintros.\napply Z.pow_le_mono_r; auto with zarith.\nQed.\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/int/Power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7321008945026412}}
{"text": "(** * Definition of terms of Riesz spaces *)\nRequire Import Reals.\n\n(** ** Term *)\nRequire Import RL.OLlibs.List_more.\n\nInductive Rterm : Type :=\n| R_var : nat -> Rterm\n| R_zero : Rterm\n| R_plus : Rterm -> Rterm -> Rterm\n| R_mul : R -> Rterm -> Rterm\n| R_max : Rterm -> Rterm -> Rterm\n| R_min : Rterm -> Rterm -> Rterm.\n\n(** Notations *)\n\nNotation \"A +R B\" := (R_plus A B) (at level 20, left associativity).\nNotation \"A \\/R B\" := (R_max A B) (at level 40, left associativity).\nNotation \"A /\\R B\" := (R_min A B) (at level 45, left associativity).\nNotation \"-R A\" := (R_mul (-1) A) (at level 15).\nNotation \"A -R B\" := (R_plus A (-R B)) (at level 10, left associativity).\nNotation \"r *R A\" := (R_mul r A) (at level 15).\n\nFixpoint R_sum_term k A :=\n  match k with\n  | 0 => R_zero\n  | 1 => A\n  | S n => A +R (R_sum_term n A)\n  end.\n\n(** Substitution *)\nFixpoint Rsubs (t1 : Rterm) (x : nat) (t2 : Rterm) : Rterm :=\n  match t1 with\n  | R_var y => if (beq_nat x y) then t2 else R_var y\n  | R_zero => R_zero\n  | R_plus t t' => R_plus (Rsubs t x t2) (Rsubs t' x t2)\n  | R_min t t' => R_min (Rsubs t x t2) (Rsubs t' x t2)\n  | R_max t t' => R_max (Rsubs t x t2) (Rsubs t' x t2)\n  | R_mul y t => R_mul y (Rsubs t x t2)\n  end.\n\n(** Definition of positive part, negative part and absolute value *)\nNotation \"'R_pos' A\" := (A \\/R R_zero) (at level 5).\nNotation \"'R_neg' A\" := ((-R A) \\/R R_zero) (at level 5).\nNotation \"'R_abs' A\" := (A \\/R (-R A)) (at level 5).\n", "meta": {"author": "clucas26e4", "repo": "riesz-logic", "sha": "6ad0da80c8922d186c777d2c8f1a42d381abfb2d", "save_path": "github-repos/coq/clucas26e4-riesz-logic", "path": "github-repos/coq/clucas26e4-riesz-logic/riesz-logic-6ad0da80c8922d186c777d2c8f1a42d381abfb2d/hr/Rterm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7321006759031944}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith List Omega Wellfounded.\n\nRequire Import php measure_ind wf_chains.\n\nSet Implicit Arguments.\n\n(** Results about the well-foundedness of strict (reverse)\n    inclusion between lists \n\n    These proofs avoid the need of decidable equality\n    and use the finitary Pigeon Hole Principle (PHP) \n    instead\n*)\n\nSection sincl.\n\n  (** Strict inclusion between lists is a well founded relation *)\n\n  Variable (X : Type).\n\n  Implicit Type (l m : list X).\n    \n  (* sincl l m if incl l m and there is a witness in m \\ l *)\n\n  Definition sincl l m := incl l m /\\ exists x, ~ In x l /\\ In x m.\n\n  (* Any n-chain m ~~> l contains a \n     duplication-free subset of l of size n \n     which does not intersect m  *)\n\n  Lemma sincl_chain n m l :   \n       chain sincl n m l -> incl m l \n                         /\\ exists ll, ~ list_has_dup ll \n                                      /\\ length ll = n \n                                      /\\ incl ll l\n                                      /\\ forall x, In x m -> In x ll -> False.\n  Proof.\n    induction 1 as [ m | n m l k H1 H2 (H7 & ll & H3 & H4 & H5 & H6) ].\n    + split.\n      * intros ?; auto.\n      * exists nil; simpl; repeat split; auto.\n        - inversion 1.\n        - intros _ [].\n    + split.\n      * intros ? ?; apply H7, H1; auto.\n      * destruct H1 as (G1 & x & G2 & G3).\n        exists (x::ll); simpl; repeat split; auto.\n        - contradict H3.\n          apply list_has_dup_cons_inv in H3.\n          destruct H3 as [ H3 | ]; auto.\n          destruct (H6 x); auto.\n        - apply incl_cons; auto.\n        - intros y F1 [ F2 | F2 ]; subst.\n          ** tauto.\n          ** apply (H6 y); auto.\n  Qed.\n\n  (* Hence, by the PHP, if there is a n-chain to l then n must be less than length l *)\n\n  Corollary sincl_chain_bounded l m n : chain sincl n m l -> n <= length l.\n  Proof.\n    intros H.\n    apply sincl_chain in H.\n    destruct H as (_ & ll & H1 & H2 & H3 & _).\n    destruct (le_lt_dec n (length l)) as [ | C ]; auto.\n    subst; destruct H1.\n    apply finite_pigeon_hole with l; auto.\n  Qed.\n\n  (* Hence sincl is well-founded because n-chains to l have length bounded by length l *)\n   \n  Theorem wf_sincl : well_founded sincl.\n  Proof.\n    apply wf_chains.\n    intros l; exists (length l).\n    intros ? ?; apply sincl_chain_bounded.\n  Qed.\n\nEnd sincl.\n\nArguments wf_sincl {X}.\n\nSection rincl_fin.\n\n  (** Strict reverse inclusion between lists is well founded over a finite domain *)\n \n  (* M the upper-bound/finiteness of the domain *)\n\n  Variable (X : Type) (M : list X). \n\n  (* l cap M strictly contains in m cap M *)\n\n  Definition rincl_fin l m := (forall x, In x m -> In x M -> In x l) \n                            /\\ exists x, ~ In x m /\\ In x l /\\ In x M.\n\n  (* Any n-chain m ~~> l contains a duplication-free subset of M of size n *)\n                            \n  Lemma rincl_fin_chains n m l :   chain rincl_fin n m l \n                   -> exists ll, ~ list_has_dup ll \n                                /\\ incl ll M \n                                /\\ length ll = n \n                                /\\ incl ll m.\n  Proof.\n    induction 1 as [ x | n m k l H1 H2 (ll & H3 & H4 & H5 & H6) ].\n    + exists nil.\n      repeat split; simpl; auto; inversion 1.\n    + destruct H1 as (H1 & a & G1 & G2 & G3).\n      exists (a::ll).\n      repeat split.\n      * contradict H3.\n        apply list_has_dup_cons_inv in H3.\n        destruct H3 as [ H3 | ]; auto.\n        destruct G1; apply H6; auto.\n      * apply incl_cons; auto.\n      * simpl; f_equal; auto.\n      * apply incl_cons; auto.\n        intros ? ?; auto.\n  Qed.\n\n  (* Hence, by the PHP, if there is a n-chain to l then n is less than length M *)\n\n  Corollary rincl_fin_chain_bounded l m n : chain rincl_fin n m l -> n <= length M.\n  Proof.\n    intros H.\n    apply rincl_fin_chains in H.\n    destruct H as (ll & H1 & H2 & H3 & _).\n    destruct (le_lt_dec n (length M)) as [ | C ]; auto.\n    subst n; destruct H1.\n    apply finite_pigeon_hole with M; auto.\n  Qed.\n\n  Theorem wf_rincl_fin : well_founded rincl_fin.\n  Proof.\n    apply wf_chains.\n    intros l; exists (length M).\n    intros ? ?; apply rincl_fin_chain_bounded.\n  Qed.\n\nEnd rincl_fin.\n\nArguments wf_rincl_fin {X}.\n", "meta": {"author": "DmxLarchey", "repo": "PC19", "sha": "0481befc4f7b57679000a0d6ae29940532f55026", "save_path": "github-repos/coq/DmxLarchey-PC19", "path": "github-repos/coq/DmxLarchey-PC19/PC19-0481befc4f7b57679000a0d6ae29940532f55026/wf_incl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8080672181749421, "lm_q1q2_score": 0.7321006738520519}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  mult lf1 x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj249_coqofml_nxL7qZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7321006737666894}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint plus (plus_arg0 : Nat) (plus_arg1 : Nat) : Nat\n           := match plus_arg0, plus_arg1 with\n              | zero, n => n\n              | succ n, m => succ (plus n m)\n              end.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : Lst) : Nat\n           := match len_arg0 with\n              | nil => zero\n              | cons x y => succ (len y)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : Lst) (qreva_arg1 : Lst) : Lst\n           := match qreva_arg0, qreva_arg1 with\n              | nil, x => x\n              | cons z x, y => qreva x (cons z y)\n              end.\n\nTheorem plus_comm: forall (n m: Nat), plus n m = plus m n.\nProof.\n  induction n; induction m.\n  { simpl. rewrite IHn. rewrite <- IHm. simpl. rewrite IHn. reflexivity. }\n  { simpl. rewrite IHn. simpl. reflexivity. }\n  { simpl. rewrite <- IHm. simpl. reflexivity. }\n  { reflexivity. }\nQed.\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (len (qreva x y)) (plus (len x) (len y)).\nProof.\n  induction x; induction y; simpl; try reflexivity.\n  { rewrite plus_comm. simpl.\n    rewrite IHx. simpl. rewrite plus_comm.\n    simpl. reflexivity. }\n  { rewrite plus_comm. simpl. rewrite IHx. rewrite plus_comm.\n    simpl. reflexivity. }\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7321006674852186}}
{"text": "(** * 6.512 Formal Reasoning About Programs, Spring 2023 - Pset 2 *)\n\n(* Author: Samuel Gruetter <gruetter@mit.edu>\n\nThis pset will introduce you to one of the major applications of formal\nreasoning about programs: proving that an optimized program behaves the same as\na simple program.\n\nOnce again, you can check the tips section near the bottom of this file for some\nuseful tips and tricks to help you navigate Coq and Ltac. In the signature file there\nis a hint specific to the problems in this pset that you can consult if you find\nyourself stuck!\n\nImagine you're writing a program that needs some function F. You know how to\nimplement F naively, but as you run your program, you notice that it spends a\nlot of time in the function F. You find a library which claims to provide a very\nefficient implementation of F, but looking at its source code, you don't really\nunderstand why this code should calculate F, and you've seen some bug reports\nagainst previous versions of the library, so you can't really know whether this\nlibrary implements F correctly.  Since you care a lot about writing a correct\nprogram, you finally decide to keep using your naive slow implementation.\nFormal reasoning about programs to the rescue! If the authors of the library\nwant to increase the user's trust in their library, they can include the naive\nbut simple-to-understand version of F in their library as well and write a\nproof that for all possible inputs, the optimized version of F returns the same\nvalue as the simple version of F.  If that proof is in a machine-checkable\nformat (e.g. in a Coq file), the library users do not need to understand the\nimplementation of the optimized F, nor the body of the proof, but can still use\nthe optimized F and be sure that it does the same as the simple implementation,\nas long as they trust the proof checker.\n\nIn this pset, we will put you in the role of the library author who writes a\nnaive version of F, an optimized implementation of F, and a proof that the two\nof them behave the same. *)\n\nRequire Import Coq.NArith.NArith. Open Scope N_scope.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.micromega.Lia.\nRequire Import Frap.Frap.\nRequire Import Pset2Sig.\n\n(* As usual, the grading rubric for this pset is in Pset2Sig.v. *)\n\nModule Impl.\n  (* Recursive functions *)\n  (* ******************* *)\n\n  (* We will need some recursive functions in this PSet. Defining recursive\n     functions in Coq can be a bit tricky, because Coq only accepts recursive\n     functions that very obviously terminate.\n\n     For natural numbers represented as \"nat\", and for data structures like the\n     abstract syntax trees we saw in class, recursive functions can usually be\n     defined using \"Fixpoint\", because each recursive call is made on a subterm of\n     the original argument, which is required for Coq to be convinced that the\n     recursive function terminates. Coq accepts the [fact_nat] function below\n     because the recursive call [fact_nat n'] operates on [n'], which is a subterm\n     of [n].\n   *)\n  \n  Fixpoint fact_nat (n : nat) : nat :=\n    match n with\n    | O => 1\n    | S n' => (n' + 1) * (fact_nat n')\n    end.\n  \n  (*\n     In this pset, however, we want to use the binary representation of natural\n     numbers, which is called \"N\" in Coq.  This representation stores numbers as\n     lists of binary digits, so recursive functions on these numbers don't\n     decrease by one on every call: they remove one binary digit on every call\n     (which corresponds to dividing by two).\n\n     So, a Fixpoint on N called with the binary number \"1101\" can only make\n     recursive calls with the number \"110\".  To make recursive calls with one\n     less than the argument, i.e. with 1100 in this example, we need a special\n     recursion operator:\n\n       N.recursion base_case update_fn n_iters\n\n    This pattern can only define functions recursing over a natural number until\n    it reaches 0, with one recursive case where the recursive call is for one less\n    than the argument. It corresponds to the following function on nat: *)\n\n  Fixpoint nat_recursion {A} (base_case: A) (update_fn: nat -> A -> A) n_iters :=\n    match n_iters with\n    | 0 => base_case\n    | S n => update_fn n (nat_recursion base_case update_fn n)\n    end%nat.\n\n  (*\n    To show how we can use this function, we can define an alternate version of\n    fact_nat as follows:\n   *)\n\n  Definition fact_nat' : nat -> nat :=\n    nat_recursion 1%nat (fun n recurse => (n + 1) * recurse)%nat.\n\n\n  (* To make definitions more readable, we have defined a notation for\n     N.recursion that mirrors the structure of the match statement in the original\n     fact_nat fixpoint but actually desugars to a definition like fact_nat'.\n     We'll be using the following factorial function, defined using our notation,\n     for the rest of this assignment:\n   *)\n\n  Definition fact: N -> N :=\n    recurse by cases\n    | 0 => 1\n    | n + 1 => (n + 1) * recurse\n    end.\n\n  (* The above function implements factorial, i.e. \"fact n = 1 * 2 * ... * n\".  In\n     the recursive case, you can use the word \"recurse\" to refer to the result of\n     the recursive call. *)\n\n  (* Aside: If you don't like the above notation and want to see the real\n     definition, you can do this:\n\n  Close Scope N_recursion_scope.\n  Print fact.\n  *)\n\n  (* Let's compute the first few values of fact: *)\n  Compute fact 0.\n  Compute fact 1.\n  Compute fact 2.\n  Compute fact 3.\n  Compute fact 4.\n\n  (* Instead of writing \"(fact x)\" all the time, it's more convenient to just\n     write \"x!\", so we make a Notation for this: *)\n  Local Notation \"x !\" := (fact x) (at level 12, format \"x !\").\n\n  (* Exercise: Define a simple exponentiation function in the same style, so that\n     \"exp base n\" equals \"base^n\". *)\n\n  Definition exp(base: N): N -> N. Admitted.\n\n  (* Once you define \"exp\", you can replace \"Admitted.\" below by \"Proof. equality. Qed.\" *)\n  Lemma test_exp_2_3: exp 2 3 = 8. Admitted.\n  Lemma test_exp_3_2: exp 3 2 = 9. Admitted.\n  Lemma test_exp_4_1: exp 4 1 = 4. Admitted.\n  Lemma test_exp_5_0: exp 5 0 = 1. Admitted.\n  Lemma test_exp_1_3: exp 1 3 = 1. Admitted.\n\n  (* Here's another recursive function defined in the same style to apply a\n     function f to a range of values:\n     \"seq f len start\" computes the list [f start; f (start+1); ... f (start+len-1)] *)\n  Definition seq(f: N -> N): N -> N -> list N :=\n    recurse by cases\n    | 0 => fun start => []\n    | n + 1 => fun start => f start :: recurse (start + 1)\n    end.\n\n  Compute (seq (fun x => x * x) 4 10).\n\n  (* \"ith i l\" returns the i-th element of the list l.\n     To understand the recursion, note that \"ith i\" returns a function which takes\n     a list and, depending on whether i was 0 or not, returns the head of the list\n     or the (i-1)-th element of the tail.  If the index is out of bounds, it\n     returns the default value 0. *)\n  Definition ith: N -> list N -> N :=\n    recurse by cases\n    | 0 => fun (l: list N) => match l with\n                              | h :: t => h\n                              | nil => 0\n                              end\n    | i + 1 => fun (l: list N) => match l with\n                                  | h :: t => recurse t\n                                  | nil => 0\n                                  end\n    end.\n\n  (* The standard library already contains a function called \"length\": *)\n  Check length.\n  (* However, it returns a \"nat\", i.e., the representation of natural numbers\n     using O and S, which is very inefficient: To represent the number n, it needs\n     roughly c*n bytes of RAM, where c is some constant, whereas \"N\", the binary\n     representation of natural numbers, only used c*log(n) bytes of RAM.\n     Therefore, we redefine our own length function which returns an N: *)\n  Fixpoint len(l: list N): N :=\n    match l with\n    | [] => 0\n    | h :: t => 1 + len t\n    end.\n  (* Note that since the recursion follows the structure of the data (the list)\n     here, we use Fixpoint instead of \"recurse by cases\". *)\n\n  (* Here's a simple lemma: If we tell \"seq\" to return a list of length \"count\",\n     it indeed does: *)\n  Lemma seq_len: forall f count start, len (seq f count start) = count.\n  Proof.\n    induct count; simplify.\n    - (* base case: count = 0 *)\n      equality.\n    - (* recursive case: assuming the statement holds for some \"count\", show that\n         it also holds for \"count + 1\".\n         This goal contains \"seq f (count + 1) start\", so we know that we're in\n         the recursive case of \"seq\", so we'd like to replace \"seq f (count + 1)\n         start\" by the recursive case we wrote in its definition.  Unfortunately,\n         neither \"unfold seq\" nor \"simplify\" can do this, but the tactic\n         \"unfold_recurse F k\", where F is the function in question and k its\n         argument, does the job: *)\n      unfold_recurse (seq f) count.\n      (* And here's a hint you'll need later: Sometimes, your goal won't exactly\n         contain (seq f (count + 1) start), but maybe (seq f someOtherExpression\n         start), but you still know that someOtherExpression is strictly greater\n         than 0.  In such cases, if you want to use \"unfold_recurse\", you first\n         have to run\n\n         <<<\n         replace someOtherExpression with (someOtherExpression - 1 + 1) by\n         linear_arithmetic.\n         >>>\n\n         Note that if someOtherExpression could be 0, this won't work, because\n         subtraction on natural numbers in Coq returns 0 if the result is\n         negative, so \"0 - 1 + 1\" equals 1 in Coq's natural numbers, and\n         linear_arithmetic can't prove \"0 = 1\" for you! *)\n\n      simplify. rewrite IHcount. linear_arithmetic.\n  Qed.\n\n  (* And here's another general hint: You don't always need induction.  Some lemmas\n     in this pset can be solved using induction but don't actually require it\n     and are simpler to solve if you don't use induction, so before doing\n     induction, try to think where/if you would need an inductive hypothesis. *)\n\n  (* Exercise: Prove that the i-th element of seq has the value we'd expect. *)\n  Lemma seq_spec: forall f count i start, i < count -> ith i (seq f count start) = f (start + i).\n  Proof.\n    induct count; simplify.\n  Admitted.\n\n  (* Exercise: Prove that if the index is out of bounds, \"ith\" returns 0. *)\n  Lemma ith_out_of_bounds_0: forall i l, len l <= i -> ith i l = 0.\n  Proof.\n  Admitted.\n\n\n  (* Binomial coefficients *)\n  (* ********************* *)\n\n  (* You might remember binomial coefficients from your math classes. They appear in many combinatorics\n     problems and form the coefficients of the expansion of the polynomial (x + y)^n.\n     In math notation, they are defined as follows:\n\n        / n \\        n!\n        |   |  = ---------\n        \\ k /    (n-k)! k!\n\n     We can transcribe this to Coq as follows: *)\n\n  Definition C(n k: N): N := n! / ((n - k)! * k!).\n\n  (* If we want to know how many ways there are to pick 2 items out of 4 items, we\n     can compute this in Coq: *)\n  Compute C 4 2.\n\n  (* And here are the coefficients of the expansion of (x + y)^3: *)\n  Compute [C 3 0; C 3 1; C 3 2; C 3 3].\n\n  (* For larger numbers, however, this way of computing C becomes quite slow:\n\n  Compute C 1000 100.\n\n     …takes about 2 seconds on my computer. You can measure the time by putting\n     \"Time\" in front of any command:\n\n  Time Compute C 1000 100.\n\n     In the fraction defining C, there are many factors which appear both in the\n     numerator and in the denominator, so it seems that we should be able to\n     cancel these out and write a more efficient implementation of C. Here is one\n     candidate: *)\n\n  Definition bcoeff(n: N): N -> N :=\n    recurse by cases\n    | 0 => 1\n    | k + 1 => recurse * (n - k) / (k + 1)\n    end.\n\n  (* Now if we do\n\n  Time Compute bcoeff 1000 100.\n\n     it only takes about 0.02 seconds on my computer, so we got a 100x speed\n     improvement, yay!  But how do we know whether it's correct?  We could do some\n     quick tests: *)\n\n  Compute [bcoeff 3 0; bcoeff 3 1; bcoeff 3 2; bcoeff 3 3].\n\n  (* This test produces the same values as for C, but we want to be sure that\n     bcoeff will *always* produce the same values as C, so let's prove it,\n     i.e. let's show that\n\n     forall n k, k <= n -> bcoeff n k = C n k\n\n     We will do so further below, but we first need a few helper lemmas and\n     techniques:\n\n     Many arithmetic goals in this pset are linear, i.e. there are only\n     multiplications by constants but no multiplications of two variables.  For\n     these linear-arithmetic goals, the linear_arithmetic tactic works just fine,\n     but for some non-linear goals which will appear in this Pset, you can try the\n     tactic \"nia\" (which stands for \"non-linear integer arithmetic\"), but it does\n     not always work, so sometimes you will have to search for appropriate lemmas\n     to apply manually.  For instance, to prove the following: *)\n  Goal forall n m, n <> 0 -> m <> 0 -> n * m <> 0.\n  Proof.\n    simplify.\n    (* you could use the \"Search\" command with a pattern: *)\n    Search (_ * _ <> 0).\n    (* which outputs the name of a handy lemma we can apply: *)\n    apply N.neq_mul_0.\n    split; assumption.\n    (* (Note that in this case \"nia\" would have worked as well, but in any case, it's good to know\n       the \"Search\" command.) *)\n  Qed.\n\n  (* Here's another example of how to use the \"Search\" command: Suppose you have\n     the goal *)\n  Goal forall n, n <> 0 -> n / n = 1.\n  Proof.\n    simplify.\n    (* If we do \"Search (_ / _)\" we get a very long list, but if we do *)\n    Search (?x / ?x).\n    (* we force the two numbers on both sides of the / to be the same, and we only get the lemma we need: *)\n    apply N.div_same.\n    assumption.\n  Qed.\n\n  (* Now we're ready to prove a few simple facts: *)\n\n  Lemma fact_nonzero: forall n, n! <> 0.\n  Proof.\n  Admitted.\n\n  Lemma Cn0: forall n, C n 0 = 1.\n  Proof.\n  Admitted.\n\n  Lemma Cnn: forall n, C n n = 1.\n  Proof.\n  Admitted.\n\n\n  (* It's somewhat surprising that in the definition of C(n, k),\n\n        n!\n    -----------\n    (n - k)! k!\n\n    the denominator always divides the numerator.\n    The following lemma proves it. Note that \"(a | b)\" means \"a divides b\".  We\n    provide the solution for you, so that you can step through it and use it as a\n    source of useful strategies you can apply in the exercises below.  Make sure\n    to step through it and to understand each proof step! *)\n  Lemma C_is_integer: forall n k, k <= n ->\n      (((n - k)! * k!) | n!).\n  Proof.\n    induct n; simplify.\n\n    - replace k with 0 by linear_arithmetic.\n      Search (1 * _).\n      rewrite N.mul_1_l; simplify.\n      Search (?a | ?a).\n      apply N.divide_refl.\n\n    - (* We want to use the induction hypothesis, but it is not directly\n         applicable to [k], since [k] could be equal to [n + 1]. *)\n      assert (k = 0 \\/ k = n + 1 \\/ 0 < k <= n) as Hk by linear_arithmetic;\n        cases Hk; subst; simplify.\n\n      + rewrite N.sub_0_r, N.mul_1_r.\n        apply N.divide_refl.\n\n      + rewrite N.sub_diag; simplify.\n        rewrite N.mul_1_l.\n        apply N.divide_refl.\n\n      + (* The key idea is to use the induction hypothesis twice. *)\n        assert (k <= n) as Hle by linear_arithmetic.\n        pose proof (IHn k Hle) as Hdk.\n\n        assert (k - 1 <= n) as Hle1 by linear_arithmetic.\n        pose proof (IHn (k - 1) Hle1) as Hdk1.\n\n        (* How can we use facts about divisibility?\n           Unfolding the definition helps: *)\n        (* Locate \"|\". (* Notation \"( p | q )\" := (N.divide p q) *) *)\n        (* unfold N.divide in *. *)\n\n        (* [invert] will give us a concrete value instead of an existential: *)\n        (* invert Hdk; invert Hdk1. *)\n\n        (* Next we proceed to harmonize the divisors to be able to sum them. *)\n        Search (_ * _ | _ * _).\n\n        (* The first equation is missing a (n - k + 1) factor *)\n        apply N.mul_divide_mono_l with (p := n + 1 - k) in Hdk.\n        replace ((n + 1 - k) * ((n - k)! * k!))\n          with ((n + 1 - k)! * k!) in Hdk; cycle 1.\n        { replace (n + 1 - k) with (n - k + 1) by linear_arithmetic.\n          unfold_recurse fact (n - k).\n          replace (n - k + 1) with (n + 1 - k) by linear_arithmetic.\n          linear_arithmetic. }\n\n        (* The second is missing a (k) factor *)\n        apply N.mul_divide_mono_l with (p := k) in Hdk1.\n        replace (n - (k - 1)) with (n + 1 - k) in Hdk1\n          by linear_arithmetic.\n        replace (k * ((n + 1 - k)! * (k - 1)!))\n          with ((n + 1 - k)! * k!) in Hdk1; cycle 1.\n        { replace k with (k - 1 + 1) at 2 by linear_arithmetic.\n          unfold_recurse fact (k - 1).\n          replace (k - 1 + 1) with k by linear_arithmetic.\n          linear_arithmetic. }\n\n        (* Now we can sum the equations: *)\n        Search (_ | _ + _).\n        pose proof N.divide_add_r _ _ _ Hdk Hdk1 as Hd.\n        replace ((n + 1 - k) * n! + k * n!) with ((n + 1)!) in Hd; cycle 1.\n        { unfold_recurse fact n. nia. }\n\n        equality.\n  Qed.\n\n  (* Now we're ready to prove correctness of our optimized implementation bcoeff.\n     Since this is not a class about math, we're providing a paper proof of each\n     proof step of the inductive case:\n\n    C(n, k + 1)\n\n               n!\n  = -----------------------\n    (n - (k + 1))! (k + 1)!\n\n               n!\n  = -----------------------\n    (n - k - 1)! k! (k + 1)\n\n           n! (n - k)\n  = -------------------------------\n    (n - k - 1)! (n - k) k! (k + 1)\n\n                 n! (n - k)\n  = ---------------------------------------\n    (n - k - 1)! (n - k - 1 + 1) k! (k + 1)\n\n            n! (n - k)\n  = ---------------------------\n    (n - k - 1 + 1)! k! (k + 1)\n\n        n! (n - k)\n  = -------------------\n    (n - k)! k! (k + 1)\n\n    n! (n - k)\n  = ----------- / (k + 1)\n    (n - k)! k!\n\n        n!\n  = ----------- * (n - k) / (k + 1)\n    (n - k)! k!\n\n  = C(n, k) * (n - k) / (k + 1)\n\n  = bcoeff(n, k) * (n - k) / (k + 1)\n\n  = bcoeff(n, k + 1)\n\n  Your task is to translate this proof into Coq!\n\n  Potentially useful hint:\n  Note that multiplication and division have the same operator priority, and both\n  are left-associative, so\n     \"a / b * c / d\" is \"((a / b) * c) / d\", NOT \"(a / b) * (c / d)\"\n\n  Here we go: *)\n  Lemma bcoeff_correct: forall n k, k <= n -> bcoeff n k = C n k.\n  Proof.\n    induct k; simplify.\n  Admitted.\n\n\n  (* All binomial coefficients for a given n *)\n  (* *************************************** *)\n\n  (* In some applications, we need to know all binomal coefficients C(n,k) for a fixed n.\n     For instance, if we want to symbolically evaluate (x + y)^4, the result is\n\n     C(4,0)*x^4 + C(4,1)*x^3*y + C(4,2)*x^2*y^2 + C(4,3)*x*y^3 + C(4,4)*y^4\n\n     The simplest way to compute such lists would be to just use the C we defined above: *)\n\n  Definition all_coeffs_slow1(n: N): list N :=\n    (recurse by cases\n     | 0 => [1]\n     | k + 1 => C n (k + 1) :: recurse\n     end) n.\n\n  Compute all_coeffs_slow1 0.\n  Compute all_coeffs_slow1 1.\n  Compute all_coeffs_slow1 2.\n  Compute all_coeffs_slow1 3.\n  Compute all_coeffs_slow1 4.\n  Compute all_coeffs_slow1 5.\n  Compute all_coeffs_slow1 15.\n  (* However, this is not very efficient:\n\n  Time Compute all_coeffs_slow1 100.\n\n  takes 0.8s on my machine *)\n\n  (* We could use our more efficient bcoeff from above: *)\n  Definition all_coeffs_slow2(n: N): list N :=\n    (recurse by cases\n     | 0 => [1]\n     | k + 1 => bcoeff n (k + 1) :: recurse\n     end) n.\n\n  Compute all_coeffs_slow2 5.\n  Compute all_coeffs_slow2 15.\n  (* This is faster:\n\n     Time Compute all_coeffs_slow2 100.\n\n  takes 0.2s on my machine and\n\n    Time Compute all_coeffs_slow2 200.\n\n  takes 1.7 s on my machine.\n\n  But we can do even better by using Pascal's triangle:\n\n        1\n       1 1\n      1 2 1\n     1 3 3 1\n    1 4 6 4 1\n\n  You can observe that the i-th row of this triangle is the result of\n  \"all_coeffs_slow1 i\", and that each value not at the boundary of the triangle is\n  the sum of the values to its upper left and its upper right. For instance, the 6\n  in the last row is the sum of the two 3s above it.\n  More formally, we can state this as follows: *)\n  Definition Pascal's_rule: Prop := forall n k,\n      1 <= k <= n ->\n      C (n+1) k = C n (k - 1) + C n k.\n  (* Note that the above is only a definition which gives a name to this\n     proposition but not a lemma.  We don't ask you to prove it, but it's a fun\n     optional exercise; have a look at the end of this file if you're\n     interested! *)\n\n  (* The following function takes in a line of Pascal's triangle and computes the\n     line below it: *)\n  Definition nextLine(l: list N): list N :=\n    1 :: seq (fun k => ith (k - 1) l + ith k l) (len l) 1.\n\n  Compute nextLine [1; 3; 3; 1].\n  Compute nextLine (nextLine [1; 3; 3; 1]).\n\n  (* This allows us to define a faster all_coeffs function: *)\n  Definition all_coeffs_fast: N -> list N :=\n    recurse by cases\n    | 0 => [1]\n    | n + 1 => nextLine recurse\n    end.\n\n  (* Time Compute all_coeffs_fast 200. takes 0.35s on my computer *)\n\n\n  (* Exercise: Let's prove that all_coeffs_fast is correct.\n     Note that you can assume Pascal's rule to prove this. *)\n  (* HINT 1 (see Pset2Sig.v) *)\n  Lemma all_coeffs_fast_correct:\n    Pascal's_rule ->\n    forall n k,\n      k <= n ->\n      ith k (all_coeffs_fast n) = C n k.\n  Proof.\n  Admitted.\n\n  (* ----- THIS IS THE END OF PSET2 ----- All exercises below this line are optional. *)\n\n  (* Optional exercise: Let's prove that Pascal's rule holds.\n     On paper, this can be proved as follows, but feel free to ignore this if you want\n     the full challenge!\n\n     C(n, k-1) + C(n, k)\n\n             n!                 n!\n  = --------------------- + -----------\n    (n - k + 1)! (k - 1)!   (n - k)! k!\n\n                n!                          n!\n  = ----------------------------- + -------------------\n    (n - k)! (n - k + 1) (k - 1)!   (n - k)! k (k - 1)!\n\n                 n! k                          n! (n - k + 1)\n  = ------------------------------- + -------------------------------\n    (n - k)! (n - k + 1) (k - 1)! k   (n - k)! k (k - 1)! (n - k + 1)\n\n           n! (k + n - k + 1)\n  = -------------------------------\n    (n - k)! (n - k + 1) (k - 1)! k\n\n      (n + 1)!\n  = ---------------\n    (n - k + 1)! k!\n\n  = C(n+1, k)\n  *)\n  Lemma Pascal's_rule_holds: Pascal's_rule.\n  Proof.\n    unfold Pascal's_rule.\n\n    (* Note: Proving\n         a     b     a+b\n        --- + --- =  ---\n         c     c      c\n       is a bit trickier than you might expect, because we're using integer division here.\n       So, for instance,\n        1     3                                                              1+3\n       --- + ---   equals 0 + 1 in round-down integer division, which is not ---\n        2     2                                                               2\n       To make sure this rule holds, we must also require that c and b both divide a: *)\n    assert (forall a b c, c <> 0 -> (c | a) -> (c | b) -> a / c + b / c = (a + b) / c)\n      as add_fractions. {\n      clear.\n      simplify.\n      unfold N.divide in *. invert H0. invert H1.\n      rewrite N.div_mul by assumption.\n      rewrite N.div_mul by assumption.\n      replace (x * c + x0 * c) with ((x + x0) * c) by nia.\n      rewrite N.div_mul by assumption.\n      reflexivity.\n    }\n\n  Admitted.\n\n  (* Optional exercise:\n     all_coeffs_fast is still not as fast as it could be, because nextLine uses ith\n     to access the elements of the previous line, and each invocation of ith takes\n     linear time in i.\n     It would be more efficient to implement nextLine as a recursive function\n     which iterates through the previous line just once and computes the next line\n     on the fly.\n     Define such a nextLine' function, and then use it to define all_coeffs_faster,\n     observe how it's even faster than all_coeffs_fast, and finally, prove that\n     it's correct. *)\n\n  Definition nextLine'(l: list N): list N. Admitted.\n\n  Definition all_coeffs_faster: N -> list N. Admitted.\n\n  Lemma all_coeffs_faster_correct: forall n k,\n      k <= n ->\n      ith k (all_coeffs_faster n) = C n k.\n  Proof.\n  Admitted.\nEnd Impl.\n\nModule ImplCorrect : Pset2Sig.S := Impl.\n\n(*|\nTIPS: A few things to keep in mind as you work through pset 2\n=============================================================\n|*)\n\n\nRequire Import Coq.NArith.NArith.\nOpen Scope N_scope.\nRequire Import Frap.Frap.\nImport Pset2.Impl.\n\nNotation \"x !\" := (fact x) (at level 12, format \"x !\"). (* local in Pset2 *)\n\n(* Here we demonstrate a number of useful Coq tactics.  Step though the\n   examples, and check Coq's reference manual or ask us in office hours if\n   you're confused about any of these tactics.\n\n   These are not exercises, just neat examples; feel free to work on it at your\n   pace over multiple psets and to refer to it at later points; no need to go\n   through it all at once.  *)\n\n(* The tactic we introduce in each example is underlined like this. *)\n                                             (********************)\n\nParameter whatever: Prop.\n\n(* ‘apply’ matches the conclusion of a theorem to the current goal, then\n   replaces it with one subgoal per premise of that theorem: *)\n\nGoal forall (P Q R: Prop) (H1: P) (H2: Q) (IH: P -> Q -> R), R.\nProof.\n  simplify.\n  apply IH.\n (********)\nAbort.\n\n(* Apply works with implications (`A -> B`) but also with equivalences, where\n   it tries to pick the right direction based on the goal: *)\nGoal forall (n m k: N), n = m.\nProof.\n  simplify.\n  Check N.mul_cancel_r.\n\n  (* Careful: apply only works if it's clear how the theorem applies to your goal: *)\n  Fail apply N.mul_cancel_r.\n  (* Here, Coq wants to know the value of ‘p’ before it can apply the lemma; so,\n     we use the ‘with’ for of ‘apply’ to supply it: *)\n  apply N.mul_cancel_r with (p := n - k + 1).\n (****)               (****)\nAbort.\n\n(* Apply also works in hypotheses, where it turns premises into conclusions: *)\nGoal forall (n m k: N), n = m -> whatever.\nProof.\n  simplify.\n  apply N.mul_cancel_r with (p := n - k + 1) in H.\n (*****)              (****)                (**)\nAbort.\n\nGoal forall (n m k: N), n - k + 1 <> 0 -> n = m -> whatever.\nProof.\n  simplify.\n\n  (* Specifying parameters by hand is not always convenient, so we can ask Coq\n     to create placeholders instead, to be filled later: *)\n  eapply N.mul_cancel_r in H0.\n (******)              (**)\n  2: { (* This ‘2:’ notation means: operate on the second goal *)\n    apply H.\n  } (* … and the curly braces delimit a subproof. *)\nAbort.\n\nGoal forall (P Q R S: Prop), (P -> S) -> (R -> S) -> P \\/ Q \\/ R -> S.\nProof.\n  simplify.\n  cases H1. (* You are familiar with ‘cases’ from pset 1. *)\n (*****)\n  - apply H. apply H1.\n  - admit. (* ‘admit’ is just like ‘Admitted’ but for a single goal *)\n   (*****)\n  - apply H0. apply H1.\nFail Qed. (* But if you use ‘admit’, no ‘Qed’ for you! *)\nAdmitted.\n\n(* Here is a convenient pattern that you will be familiar with from math\n   classes.  It's called a “cut”.  We state an intermediate fact and prove it\n   as part of a larger proof. *)\n\nGoal forall (f : N -> N) (count : N)\n       (IHcount : forall i start : N, i < count ->\n                                 ith i (seq f count start) = f (start + i))\n       (i start : N)\n       (H : i < count + 1),\n  ith i (f start :: seq f count (start + 1)) = f (start + i).\nProof.\n  simplify.\n\n  (* ‘assert’ introduces the fact that we want to prove, then uses *)\n  assert (i = 0 \\/ 0 < i) as A. { (* the ‘as’ clause to name the resulting fact *)\n (******)                (**)\n    linear_arithmetic.          (* The proof of the lemma comes first. *)\n  }\n  cases A.                      (* Then we get to use the lemma itself. *)\n  - subst. (* ‘subst’ rewrites all equalities. *)\n   (*****)  (* or \"subst i\" for just one var *)\n    simplify. admit.\n  - (* Another assertion! This time we fit the whole proof in a ‘by’ clause. *)\n    assert (i = i - 1 + 1) as E by linear_arithmetic.\n   (******)                    (**)\n    rewrite E.\n    unfold_recurse ith (i - 1).\nAbort.\n\nGoal forall (n x0 k: N),\n    0 < k ->\n    k + 1 < n ->\n    n! = x0 * ((n - (k - 1))! * (k - 1)!) ->\n    whatever.\nProof.\n  intros n m.\n (******)\n  (* ‘simplify’ takes care of moving variables into the “context” above the\n     line, but ‘intros’ gives finer grained control and lets you name\n     hypotheses.  Users of Proof General with company-coq can type ‘intros!’ to\n     get names automatically inserted. *)\n  intros. (* A plain ‘intros’ takes care of all remaining variables. *)\n  (******)\n\n  (* Sometimes we want to say “a = b, so replace all ‘a’s with ‘b’s.”.  Replace\n     is the perfect tactic for these cases; it's like ‘assert’ followed by\n     ‘rewrite’. *)\n  replace (n - (k - 1)) with (n - k + 1) in H1 by linear_arithmetic.\n (*******)             (****)           (**)  (**)\n  (* \"in\" and \"by\" are optional *)\n  unfold_recurse fact (n - k).\nAbort.\n\nGoal forall (P Q R: Prop) (H0: Q) (x: N) (H: forall (a b: N), P -> Q -> a < b -> R), whatever.\nProof.\n  simplify.\n  (* Often you have a general hypothesis, and you want to make it more specific\n     to your case.  Then, ‘specialize’ is the tactic you want: *)\n  specialize H with (b := x).\n (**********) (****)\n  assert (3 < x) by admit.\n  specialize H with (2 := H0) (3 := H1).\nAbort.\n\nGoal forall (f : N -> N) (start : N),\n    f start = f (start + 0).\nProof.\n  simplify.\n\n  (* We have seen ‘apply’ earlier, which applies a theorem ending with an\n     implication to a complete goal.  ‘rewrite’ takes a theorem ending in an\n     equality and replaces matching subterms of the goal according to that\n     equality: *)\n  rewrite N.add_0_r.\n (*******)\n  (* Options like \"with (a := 2)\", \"in H\", \"by tactic\" also work! *)\n  equality.\nAbort.\n\nGoal forall (f : N -> N) (start : N),\n    f start = f (start + 0).\nProof.\n  simplify.\n  (* Alternatively, sometimes, it helps to apply the principle that, if two\n     function arguments match, then the function calls themselves match: *)\n  f_equal.\n (*******)\n  linear_arithmetic.\nAbort.\n\nGoal forall (f : N -> N) (start : N),\n    f start = f (start + 0).\nProof.\n  simplify.\n  (* How many other ways can we find to deal with this theorem? *)\n  assert (start + 0 = start) as E by linear_arithmetic.\n  rewrite E.\nAbort.\n\nGoal forall (A B: Type) (f: A -> B) (a1 a2 a3: A),\n    Some a1 = Some a2 ->\n    Some a2 = Some a3 ->\n    f a3 = f a1.\nProof.\n  (* ‘simplify’ is a favorite of this class, which does all sorts of small goal\n     reorganization to make things more readable. *)\n  simplify.\n\n  (* ‘invert’ is another favorite: it “replaces hypothesis H with other facts that can be deduced from the structure of H's statement”.\n\n     Specifically, it looks at the structure of the arguments passed to the\n     constructors of inductive types appearing in H and deduces equalities from\n     that and then substitutes the equalities.  It's also particularly useful\n     for inductive ‘Prop’s, which we will see later in this class. *)\n  invert H. (* Watch what happens carefully in this example *)\n (******)\n  invert H0.\n  equality.\nAbort.\n\nGoal forall (A B: Type) (f: A -> B) (a1 a2 a3: A),\n    Some a1 = Some a2 ->\n    Some a2 = Some a3 ->\n    f a3 = f a1.\nProof.\n  simplify.\n  equality. (* Of course, ‘equality’ can do all the work for us here. *)\n (********)\nAbort.\n\nGoal forall (a1 a2 b1 b2: N) (l1 l2: list N),\n    a1 :: b1 :: l1 = a2 :: b2 :: l2 ->\n    a1 = a2 /\\ b1 = b2 /\\ l1 = l2.\nProof.\n  simplify.\n  (* ‘invert’ works at arbitrary depth, btw: *)\n  invert H.\n (******)\nAbort.\n\n(* If you ever end up with contradictory hypotheses, you'll want to apply the\n   pompously named “ex falso quodlibet” principle (also known under the\n   scary-sounding name of “principle of explosion”), through the aptly named\n   ‘exfalso’ tactic: *)\nGoal forall (P: Prop) (a b: N),\n    (a < b -> ~P) ->\n    P ->\n    whatever.\nProof.\n  simplify.\n  assert (a < b \\/ b <= a) as C by linear_arithmetic. cases C.\n  - exfalso.\n   (*******)\n    unfold not in H.\n    apply H.\n    all: assumption.\nAbort.\n\n(* Contradictions can take many forms; a common one is Coq is an impossible equality between two constructors; here the empty list ‘[]’ and a nonempty list ‘a :: l’. *)\nGoal forall (a : N) (l : list N),\n    a :: l = [] ->\n    whatever.\nProof.\n  simplify.\n  discriminate.\n (************)\nAbort.\n\nGoal forall (P Q R S T: Prop), (P \\/ Q -> T) -> (R \\/ S -> T) -> P \\/ S -> T.\nProof.\n  simplify.\n  cases H1.\n  - apply H. left. assumption.\n  - apply H0. right. assumption.\nAbort.\n\n(* Here are some more interesting tactics to look into along your Coq journey.\n   Happy proving!\n\n   - constructor, econstructor\n   - eassumption\n   - eexists\n   - first_order\n   - induct\n   - left, right\n   - trivial\n   - transitivity\n   - symmetry\n*)\n\n(* References:\n\n   - FRAP book Appendix A.2. Tactic Reference (http://adam.chlipala.net/frap/frap_book.pdf)\n   - Coq Reference Manual, Chapter on Tactics (https://coq.inria.fr/refman/proof-engine/tactics.html)\n*)\n", "meta": {"author": "mit-frap", "repo": "spring23", "sha": "10355d5a1cee8464cdd3722efa1fd58527c8a4d2", "save_path": "github-repos/coq/mit-frap-spring23", "path": "github-repos/coq/mit-frap-spring23/spring23-10355d5a1cee8464cdd3722efa1fd58527c8a4d2/pset02_BinomialCoefficients/Pset2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.8807970889295664, "lm_q1q2_score": 0.7320683733536435}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Binary relations                                                        *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic LibBool LibLogic LibProd LibSum.\nFrom TLC Require Export LibOperation.\n\n\n(* ********************************************************************** *)\n(** * Type of binary relations *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Type of endorelation, i.e. homogeneous binary relations *)\n\n(* --TODO: what would be a better name for [binary]? *)\n\nDefinition binary (A : Type) := A -> A -> Prop.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inhabited *)\n\nInstance Inhab_binary : forall A, Inhab (binary A).\nProof using. intros. apply (Inhab_of_val (fun _ _ => True)). Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Extensionality *)\n\nLemma binary_ext : forall A (R1 R2:binary A),\n  (forall x y, R1 x y <-> R2 x y) -> \n  R1 = R2.\nProof using. extens*. Qed.\n\nInstance Extensionality_binary : forall A, \n  Extensionality (binary A).\nProof using. intros. apply (Extensionality_make (@binary_ext A)). Defined.\n\n\n(* ********************************************************************** *)\n(** * Properties of relations *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexivity *)\n\nDefinition refl A (R:binary A) :=\n  forall x, R x x.\n\nSection Refl.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma refl_inv : forall x y R,\n  refl R -> \n  x = y ->\n  R x y.\nProof using. intros_all. subst~. Qed.\n\nEnd Refl.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Irreflexivity *)\n\nDefinition irrefl A (R:binary A) :=\n  forall x, ~ (R x x).\n\nSection Irrefl.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma irrefl_inv : forall x R,\n  irrefl R ->\n  R x x -> \n  False.\nProof using. introv H P. apply* H. Qed.\n\nLemma irrefl_eq_forall_neq : forall R,\n  irrefl R = (forall x y, R x y -> x <> y).\nProof using. \n  unfold irrefl. extens. iff M.\n  { introv H E. subst*. } \n  { autos*. }\nQed.\n\nLemma irrefl_inv_neq : forall x y R,\n  irrefl R ->\n  R x y -> \n  x <> y.\nProof using. introv H M. rewrite* irrefl_eq_forall_neq in H. Qed.\n\nEnd Irrefl.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Symmetry *)\n\nDefinition sym A (R:binary A) :=\n  forall x y, R x y -> R y x.\n\nSection Sym.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma sym_inv : forall x y R,\n  sym R -> \n  R x y -> \n  R y x.\nProof using. introv Sy R1. apply* Sy. Qed.\n\nLemma sym_inv_eq : forall x y R,\n  sym R ->\n  R x y = R y x.\nProof using. unfold sym. extens*. Qed.\n\nLemma sym_eq_forall_eq : forall R,\n  sym R = (forall x y, R x y = R y x).\nProof using.\n  unfold sym. extens. iff M.\n  { extens*. }\n  { intros. rewrite* M. }\nQed.\n\nEnd Sym.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Asymmetry *)\n\nDefinition asym A (R:binary A) :=\n  forall x y, R x y -> ~ R y x.\n\nSection Asym.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma asym_eq_forall_false : forall R,\n  asym R = (forall x y, R x y -> R y x -> False).\nProof using. unfold asym. extens*. Qed.\n\nLemma asym_inv : forall x y R,\n  asym R -> \n  R x y -> \n  R y x ->\n  False.\nProof using. introv H M1 M2. apply* H. Qed.\n\nEnd Asym.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Antisymmetry *)\n\nDefinition antisym A (R:binary A) :=\n  forall x y, R x y -> R y x -> x = y.\n\nSection Antisym.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma antisym_eq_forall_eq : forall R,\n  antisym R = (forall x y, R x y -> R y x -> x = y).\nProof using. unfold antisym. extens*. Qed.\n\nLemma antisym_inv : forall x y R,\n  antisym R -> \n  R x y -> \n  R y x -> \n  x <> y -> \n  False.\nProof using. intros_all*. Qed.\n\nEnd Antisym.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Antisymmetry with respect to an equivalence relation *)\n\nDefinition antisym_wrt A (E:binary A) R :=\n  forall x y, R x y -> R y x -> E x y.\n\n(* --LATER: lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Transitivity *)\n\nDefinition trans A (R:binary A) :=\n  forall y x z, R x y -> R y z -> R x z.\n\nSection Trans.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma trans_eq_forall_impl : forall R,\n  trans R = (forall y x z, R x y -> R y z -> R x z).\nProof using. unfold trans. extens*. Qed.\n\nLemma trans_inv : forall y x z R,\n  trans R -> \n  R x y -> \n  R y z -> \n  R x z.\nProof using. introv Tr R1 R2. apply* Tr. Qed.\n\nLemma trans_inv_swap : forall y x z R,\n  trans R -> \n  R y z -> \n  R x y -> \n  R x z.\nProof using. introv Tr R1 R2. apply* Tr. Qed.\n\n(** [trans] + [sym] *)\n\nDefinition trans_sym_ll := trans_inv.\n\nLemma trans_sym_lr : forall y x z R,\n  trans R -> \n  sym R -> \n  R x y -> \n  R z y -> \n  R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_rr : forall y x z R,\n  trans R -> \n  sym R -> \n  R y x -> \n  R z y -> \n  R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_rl : forall y x z R,\n  trans R -> \n  sym R -> \n  R y x -> \n  R y z -> \n  R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nEnd Trans.\n\nArguments trans_inv [A] y [x] [z] [R].\nArguments trans_inv_swap [A] y [x] [z] [R].\nArguments trans_sym_rr [A] y [x] [z] [R].\nArguments trans_sym_lr [A] y [x] [z] [R].\nArguments trans_sym_rl [A] y [x] [z] [R].\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Equivalence relation *)\n\nRecord equiv A (R:binary A) :=\n { equiv_refl : refl R;\n   equiv_sym : sym R;\n   equiv_trans : trans R }.\n\nSection Equiv.\nVariables (A : Type).\nImplicit Types R : binary A.\n\n(* --LATER: lemmas *)\n\nEnd Equiv.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion *)\n\n(* --LATER: see also typeclass [incl] *)\n\nDefinition rel_incl A B (R1 R2:A->B->Prop) :=\n  forall x y, R1 x y -> R2 x y.\n\nSection Incl.\nVariables (A B : Type).\nImplicit Types R : A->B->Prop.\n\nLemma rel_incl_eq_forall_impl : forall R1 R2,\n  rel_incl R1 R2 = (forall x y, R1 x y -> R2 x y).\nProof using. auto. Qed.\n\nLemma refl_rel_incl : \n  refl (@rel_incl A B).\n  (* forall (R:A->B->Prop), rel_incl R R *)\nProof using. unfolds refl, rel_incl. autos*. Qed.\n\nLemma refl_rel_incl' : forall R,\n  rel_incl R R.\nProof using. intros. applys refl_rel_incl. Qed.\n\nHint Resolve refl_rel_incl refl_rel_incl'.\n\nLemma antisym_rel_incl : \n  antisym (@rel_incl A B).\n  (* forall R1 R2, rel_incl R1 R2 -> rel_incl R2 R1 -> R1 = R2. *)\nProof using. unfolds rel_incl. extens*. Qed.\n  (* See also extensionality_pred_2 from LibEqual *)\n\nLemma trans_rel_incl : \n  trans (@rel_incl A B).\nProof using. unfold trans, rel_incl. autos*. Qed.  \n  (* forall R1 R2 R3, rel_incl R1 R2 -> rel_incl R2 R3 ->  rel_incl R1 R3. *)\n\nEnd Incl.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Totality *)\n\nDefinition total A (R:binary A) :=\n  forall x y, R x y \\/ R y x.\n\nSection Total.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma total_eq_forall_or : forall R,\n  total R = (forall x y, R x y \\/ R y x).\nProof using. auto. Qed.\n\nLemma total_inv : forall x y R,\n  total R -> \n  R x y \\/ R y x.\nProof using. introv H. apply* H. Qed.\n\nLemma total_inv_not_l : forall x y R,\n  total R -> \n  ~ R x y ->\n  R y x.\nProof using. introv H N. destruct* (H x y). Qed.\n\nLemma total_inv_not_r : forall x y R,\n  total R -> \n  ~ R y x ->\n  R x y.\nProof using. introv H N. destruct* (H x y). Qed.\n\nEnd Total.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Trichotomy *)\n\nInductive trichotomy A (R:binary A) : binary A :=\n  | trichotomy_left : forall x y,\n      R x y -> \n      x <> y -> \n      ~ R y x -> \n      trichotomy R x y\n  | trichotomy_eq : forall x,\n      ~ R x x -> \n      trichotomy R x x\n  | trichotomy_right : forall x y,\n      ~ R x y -> \n      x <> y -> \n      R y x -> \n      trichotomy R x y.\n\nDefinition trichotomous A (R:binary A) :=\n  forall x y, trichotomy R x y.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definedness *)\n\nDefinition defined A B (R:A->B->Prop) :=\n  forall x, exists y, R x y.\n\nSection Defined.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma total_eq_forall_exists : forall R,\n  defined R = (forall x, exists y, R x y).\nProof using. auto. Qed.\n\nLemma defined_inv : forall x R,\n  defined R -> \n  exists y, R x y.\nProof using. introv H. apply* H. Qed.\n\nLemma defined_inv_not : forall x R,\n  defined R -> \n  (forall y, ~ R x y) ->\n  False.\nProof using. introv H N. forwards* (?&?): H. Qed.\n\nEnd Defined.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Functionality *)\n\nDefinition functional A B (R:A->B->Prop) :=\n  forall x y z, R x y -> R x z -> y = z.\n\nSection Functional.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma functional_eq_forall_eq : forall R,\n  functional R = (forall x y z, R x y -> R x z -> y = z).\nProof using. auto. Qed.\n\nLemma functional_inv : forall x z y R,\n  functional R -> \n  R x y -> \n  R x z -> \n  y = z.\nProof using. introv H N1 N2. apply* H. Qed.\n\nEnd Functional.\n\n(* --TODO: define a tactic \"functional_exploit R\" that looks for two distinct\n   assumptions in the goal of the form [R ?x ?y] and produces [functional R]\n   as subgoal, and provides the equality [?y1 = ?y2]. *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Criteria for equality *)\n\nSection Equality.\nVariables (A : Type).\nImplicit Types R : binary A.\n\n(** If [R1] is defined, [R2] is functional, and [R1] is a subset of [R2],\n    then [R1] equals [R2]. In that case, [R1] and [R2] represent the graph\n    of a total function. *)\n\nLemma eq_of_incl_defined_functional : forall R1 R2,\n  rel_incl R1 R2 ->\n  defined R1 ->\n  functional R2 ->\n  R1 = R2.\nProof using.\n  introv Hincl Hdef Hfun. extens. intros x y. iff M.\n  { eauto. }\n  { forwards (w'&M1): Hdef x.\n    forwards M2: Hincl M1.\n    forwards: Hfun M M2. subst*. }\nQed.\n\nEnd Equality.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of the equality relation *)\n\n(** These results are not in [LibEqual] because the definitions from\n    [LibRelation] are not yet available from that file. *)\n\nSection Eq.\nVariables (A : Type).\n\nLemma refl_eq :\n  refl (@eq A).\nProof using. intros_all; subst~. Qed.\n\nLemma sym_eq :\n  sym (@eq A).\nProof using. intros_all; subst~. Qed.\n\nLemma trans_eq :\n  trans (@eq A).\nProof using. intros_all; subst~. Qed.\n\nLemma equiv_eq :\n  equiv (@eq A).\nProof using. intros. constructor; intros_all; subst~. Qed.\n\nEnd Eq.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of the equality relation *)\n\n(** These results are not in [LibLogic] because the definitions from\n    [LibRelation] are not yet available from that file. \n    See also [LibOrder] for a package of these properties. *)\n\nSection Pred_incl.\nVariables (A : Type).\n\nLemma refl_pred_incl : \n  refl (@pred_incl A).\nProof using. unfold refl, pred_incl. autos*. Qed.\n\nLemma antisym_pred_incl : \n  antisym (@pred_incl A).\nProof using. unfold antisym, pred_incl. extens*. Qed.\n\nLemma trans_pred_incl : \n  trans (@pred_incl A).\nProof using. unfold trans, pred_incl. autos*. Qed.  \n\nEnd Pred_incl.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of the equivalence relation *)\n\n(** These results are not in [LibLogic] because the definitions from\n    [LibRelation] are not yet available from that file. \n    See also [LibOrder] for a package of these properties. *)\n\nSection Iff.\n\nLemma refl_iff : \n  refl iff.\nProof using. unfold refl, iff. autos*. Qed.\n\nLemma antisym_iff : \n  antisym iff.\nProof using. unfold antisym, iff. extens*. Qed.\n\nLemma trans_iff : \n  trans iff.\nProof using. unfold trans, iff. autos*. Qed.  \n\nEnd Iff.\n\n\n(* ********************************************************************** *)\n(** * Basic constructions *)\n\n(** LATER: plan to use typeclasses from LibContainer:\n    - empty\n    - single\n    - in\n    - binds\n    - union\n    - inter\n    - incl\n    - disjoint\n    - restrict\n    - remove\n    - dom\n    - img\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** ** The empty relation *)\n\n(* --LATER: see also typeclass [empty] *)\n\nDefinition empty A : binary A :=\n  fun x y => False.\n\nSection Empty.\nVariables (A : Type).\nImplicit Types x y : A.\n\nLemma empty_eq : forall x y,\n  empty x y = False.\nProof using. auto. Qed.\n\nLemma empty_inv : forall x y,\n  empty x y ->\n  False.\nProof using. auto. Qed.\n\nLemma functional_empty : \n  functional (@empty A).\nProof using. unfolds* empty, functional. Qed.\n\nEnd Empty.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Union of two relations  *)\n\n(* --LATER: see also typeclass [union] *)\n\nDefinition union A (R1 R2:binary A) : binary A :=\n  fun x y => R1 x y \\/ R2 x y.\n\nSection Union.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma union_l : forall R1 R2 x y,\n  R1 x y ->\n  union R1 R2 x y.\nProof using. unfold union. eauto. Qed.\n\nLemma union_r : forall R1 R2 x y,\n  R2 x y ->\n  union R1 R2 x y.\nProof using. unfold union. eauto. Qed.\n\nLemma rel_incl_union_l : forall R1 R2,\n  rel_incl R1 (union R1 R2).\nProof using. unfold rel_incl, union. eauto. Qed.\n\nLemma rel_incl_union_r : forall R1 R2,\n  rel_incl R2 (union R1 R2).\nProof using. unfold rel_incl, union. eauto. Qed.\n\nLemma refl_union_l : forall R1 R2,\n  refl R1 ->\n  refl (union R1 R2).\nProof using. unfold refl, union. eauto. Qed.\n\nLemma refl_union_r : forall R1 R2,\n  refl R2 ->\n  refl (union R1 R2).\nProof using. unfold refl, union. eauto. Qed.\n\nLemma comm_union : \n  comm (@union A).\n  (* forall R1 R2, union R1 R2 = union R2 R1. *)\nProof using. unfold union. extens*. Qed.\n\nLemma comm_union_args : forall R1 R2 x y,\n  union R2 R1 x y ->\n  union R1 R2 x y.\nProof using. intros. rewrite~ comm_union. Qed.\n\n(** Union is functional provided disjoint domains *)\nLemma functional_union : forall R1 R2,\n  functional R1 ->\n  functional R2 ->\n  (forall x y z, R1 x y -> R2 x z -> False) ->\n  functional (union R1 R2).\nProof using.\n  intros. unfold union. intros x y z Hxy Hxz.\n  destruct Hxy; destruct Hxz; auto_false*.\nQed.\n\n(* --TODO: generic definition of covariant? *)\nLemma covariant_union : forall R1 R2 S1 S2,\n  rel_incl R1 S1 ->\n  rel_incl R2 S2 ->\n  rel_incl (union R1 R2) (union S1 S2).\nProof using. unfold rel_incl, union. autos*. Qed.\n\nEnd Union.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Intersection of two relations  *)\n\n(* --LATER: see also typeclass [inter] *)\n\nDefinition inter A (R1 R2:binary A) : binary A :=\n  fun x y => R1 x y /\\ R2 x y.\n\n(* --LATER: add lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Complement of a relation *)\n\nDefinition compl A (R:binary A) : binary A :=\n  fun x y => ~ R y x.\n\n(* --LATER: add lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inverse of a relation *)\n\nDefinition inverse A (R:binary A) : binary A :=\n  fun x y => R y x.\n\nSection Inverse.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma inverse_eq_fun : forall R,  \n  inverse R = (fun x y => R y x).\nProof using. auto. Qed.\n\nLemma inverse_eq : forall R x y,  \n  inverse R x y = R y x.\nProof using. auto. Qed.\n\nLemma injective_inverse : \n  injective (@inverse A).\nProof using.\n  intros R1 R2 E. extens. intros x y.\n  unfolds inverse. rewrite* (fun_eq_2 y x E).\nQed.\n\nLemma inverse_sym : forall R,\n  sym R -> \n  inverse R = R.\nProof using. intros. unfold inverse. extens*. Qed.\n\nLemma inverse_inverse : forall R,\n  inverse (inverse R) = R.\nProof using. extens*. Qed.\n\nLemma inverse_eq_l : forall R2 R1,\n  R1 = inverse R2 -> \n  inverse R1 = R2.\nProof using. intros. apply injective_inverse. rewrite~ inverse_inverse. Qed.\n\nLemma inverse_eq_r : forall R2 R1,\n  inverse R1 = R2 -> \n  R1 = inverse R2.\nProof using. intros. apply injective_inverse. rewrite~ inverse_inverse. Qed.\n\nLemma refl_inverse : forall R,\n  refl R -> \n  refl (inverse R).\nProof using. intros_all. unfolds inverse. auto. Qed.\n\nLemma trans_inverse : forall R,\n  trans R -> \n  trans (inverse R).\nProof using. intros_all. unfolds inverse. eauto. Qed.\n\nLemma antisym_inverse : forall R,\n  antisym R -> \n  antisym (inverse R).\nProof using. intros_all. unfolds inverse. auto. Qed.\n\nLemma antisym_wrt_inverse : forall E R,\n  antisym_wrt E R -> \n  antisym_wrt E (inverse R).\nProof using. intros_all. unfolds inverse. auto. Qed.\n\nLemma asym_inverse : forall R,\n  asym R -> \n  asym (inverse R).\nProof using. intros_all. unfolds inverse. apply* H. Qed.\n\nLemma total_inverse : forall R,\n  total R -> \n  total (inverse R).\nProof using. intros_all. unfolds inverse. auto. Qed.\n\nLemma trichotomous_inverse : forall R,\n  trichotomous R -> \n  trichotomous (inverse R).\nProof using.\n  introv H. intros x y. destruct (H x y).\n  apply~ trichotomy_right.\n  apply~ trichotomy_eq.\n  apply~ trichotomy_left.\nQed.\n\nLemma inverse_equiv : forall A (E:binary A),\n  equiv E -> \n  equiv (inverse E).\nProof using.\n  introv Equi. unfold inverse. constructor; intros_all;\n    dintuition eauto.\nQed.\n\nEnd Inverse.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** [preimage] *)\n\n(** Preimage, a.k.a. inverse image *)\n\nDefinition rel_preimage (A B:Type) (R:binary B) (f:A->B) : binary A :=\n  fun x y => R (f x) (f y).\n\n(* --TODO: lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** [rel_seq] *)\n\n(** Composition of two relations, usually written [R1; R2]. *)\n\nDefinition rel_seq (A B C:Type) (R1:A->B->Prop) (R2:B->C->Prop) : A->C->Prop :=\n  fun x z => exists y, R1 x y /\\ R2 y z.\n\n(** A relation [R] is functional if and only if [inverse R] composed\n    with [R] is a subset of the diagonal relation [eq]. *)\n\nLemma functional_eq_seq_inverse_incl_eq : forall A (R:binary A),\n  functional R = rel_incl (rel_seq (inverse R) R) eq.\nProof using.\n  unfold functional, rel_incl, rel_seq, inverse. extens. iff M; jauto.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Turning a function into a relation. *)\n\nDefinition rel_fun A B (f:A->B) :=\n  fun x y => (y = f x).\n\nSection Rel_fun.\nVariables (A : Type).\nImplicit Types R : binary A.\n\n(* --LATER: properties of [rel_fun] *)\n\nEnd Rel_fun.\n\n\n\n(* ********************************************************************** *)\n(** * Products *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Pointwise product *)\n\nDefinition prod2 (A1 A2:Type) \n  (R1:binary A1) (R2:binary A2) \n   : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => match p1,p2 with (x1,x2),(y1,y2) =>\n    R1 x1 y1 /\\ R2 x2 y2 end.\n\nDefinition prod3 (A1 A2 A3:Type)\n  (R1:binary A1) (R2:binary A2) (R3:binary A3)\n   : binary (A1*A2*A3) :=\n  prod2 (prod2 R1 R2) R3.\n\nDefinition prod4 (A1 A2 A3 A4:Type)\n  (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4)\n   : binary (A1*A2*A3*A4) :=\n  prod2 (prod3 R1 R2 R3) R4.\n\n(** Tactics *)\n\nTactic Notation \"unfold_prod\" :=\n  unfold prod4, prod3, prod2.\nTactic Notation \"unfolds_prod\" :=\n  unfold prod4, prod3, prod2 in *.\n\n(** Equivalence *)\n\nLemma prod2_equiv : forall A1 A2 (E1:binary A1) (E2:binary A2),\n  equiv E1 ->\n  equiv E2 -> \n  equiv (prod2 E1 E2).\nProof using.\n  introv [R1 S1 T1] [R2 S2 T2]. constructor.\n  { intros [x1 x2]. simple*. }\n  { intros [x1 x2] [y1 y2]. simple*. }\n  { intros [x1 x2] [y1 y2] [z1 z2]. simple*. }\nQed.\n\n(* --LATER: other lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Lexicographical product *)\n\nDefinition lexico2 {A1 A2} (R1:binary A1) (R2:binary A2)\n   : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => let (x1,x2) := p1 in let (y1,y2) := p2 in\n  (R1 x1 y1) \\/ (x1 = y1) /\\ (R2 x2 y2).\n\nDefinition lexico3 {A1 A2 A3}\n   (R1:binary A1) (R2:binary A2) (R3:binary A3) : binary (A1*A2*A3) :=\n  lexico2 (lexico2 R1 R2) R3.\n\nDefinition lexico4 {A1 A2 A3 A4}\n   (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4)\n   : binary (A1*A2*A3*A4) :=\n  lexico2 (lexico3 R1 R2 R3) R4.\n\n(** Tactics *)\n\nTactic Notation \"unfold_lexico\" :=\n  unfold lexico4, lexico3, lexico2.\nTactic Notation \"unfolds_lexico\" :=\n  unfold lexico4, lexico3, lexico2 in *.\n\n(** Elimination *)\n\nSection Lexico.\nVariables (A1 A2 A3 A4:Type).\nVariables (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4).\n\nLemma lexico2_1 : forall x1 x2 y1 y2,\n  R1 x1 y1 ->\n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof using. intros. left~. Qed.\n\nLemma lexico2_2 : forall x1 x2 y1 y2,\n  x1 = y1 -> \n  R2 x2 y2 ->\n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof using. intros. right~. Qed.\n\nLemma lexico3_1 : forall x1 x2 x3 y1 y2 y3,\n  R1 x1 y1 ->\n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intros. left. left~. Qed.\n\nLemma lexico3_2 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 -> \n  R2 x2 y2 ->\n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intro. left. right~. Qed.\n\nLemma lexico3_3 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 -> \n  x2 = y2 -> \n  R3 x3 y3 ->\n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intros. right~. Qed.\n\nLemma lexico4_1 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  R1 x1 y1 ->\n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. left. left~. Qed.\n\nLemma lexico4_2 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> \n  R2 x2 y2 ->\n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. left. right~. Qed.\n\nLemma lexico4_3 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> \n  x2 = y2 -> \n  R3 x3 y3 ->\n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. right~. Qed.\n\nLemma lexico4_4 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> \n  x2 = y2 -> \n  x3 = y3 -> \n  R4 x4 y4 ->\n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. right~. Qed.\n\nEnd Lexico.\n\n(** Transitivity *)\n\nLemma trans_lexico2 : forall A1 A2\n   (R1:binary A1) (R2:binary A2),\n  trans R1 -> \n  trans R2 -> \n  trans (lexico2 R1 R2).\nProof using.\n  introv Tr1 Tr2. intros [x1 x2] [y1 y2] [z1 z2] Rxy Ryz.\n  simpls. destruct Rxy as [L1|[Eq1 L1]];\n   destruct Ryz as [M2|[Eq2 M2]]; subst*.\nQed.\n\nLemma trans_lexico3 : forall A1 A2 A3\n   (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  trans R1 -> \n  trans R2 -> \n  trans R3 -> \n  trans (lexico3 R1 R2 R3).\nProof using.\n  introv Tr1 Tr2 Tr3. applys~ trans_lexico2. applys~ trans_lexico2.\nQed.\n\nLemma trans_lexico4 : forall A1 A2 A3 A4\n   (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  trans R1 ->\n  trans R2 ->\n  trans R3 -> \n  trans R4 -> \n  trans (lexico4 R1 R2 R3 R4).\nProof using.\n  introv Tr1 Tr2 Tr3. applys~ trans_lexico3. applys~ trans_lexico2.\nQed.\n\n(** Inclusion *)\n\nLemma rel_incl_lexico2 : forall A1 A2\n   (R1 R1':binary A1) (R2 R2':binary A2),\n  rel_incl R1 R1' -> \n  rel_incl R2 R2' -> \n  rel_incl (lexico2 R1 R2) (lexico2 R1' R2').\nProof using.\n  introv I1 I2. intros [x1 x2] [y1 y2] [H1|[H1 H2]].\n  { left~. } { subst. right~. }\nQed.\n\n(* --LATER: other lemmas *)\n\n\n\n(* ********************************************************************** *)\n(** * Closures *)\n\n(* --LATER: more lemmas about union and inter *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexive closure  *)\n\nInductive rclosure A (R:binary A) : binary A :=\n  | rclosure_once : forall x y,\n      R x y -> \n      rclosure R x y\n  | rclosure_refl : forall x,\n      rclosure R x x.\n\nSection Rclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rclosure.\n\n(** Equivalent definition *)\n\nLemma rclosure_eq_fun : forall R,  \n  rclosure R = (fun x y => R x y \\/ x = y).\nProof using. extens. iff M; destruct M; subst*. Qed.\n\nLemma rclosure_eq : forall R x y,  \n  rclosure R x y = (R x y \\/ x = y).\nProof using. extens. iff M; destruct M; subst*. Qed.\n\nLemma rclosure_inv : forall R x y,  \n  rclosure R x y ->\n  R x y \\/ x = y.\nProof using. introv M; rewrite* rclosure_eq in M. Qed.\n\n(** Properties *)\n\nLemma refl_rclosure : forall R,\n  refl (rclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_rclosure : forall R,\n  sym R ->\n  sym (rclosure R).\nProof using. unfolds sym. introv M N. destruct* N. Qed.\n\nLemma antisym_rclosure : forall R,\n  antisym R -> \n  antisym (rclosure R).\nProof using. \n  unfolds antisym. introv M N1 N2. \n  destruct N1; destruct N2; subst*.\nQed.\n\nLemma antisym_wrt_rclosure : forall E R,\n  antisym_wrt E R -> \n  antisym_wrt (rclosure E) (rclosure R).\nProof using. \n  unfolds antisym_wrt. introv M N1 N2. \n  destruct N1; destruct N2; subst*.\nQed.\n\nLemma trans_rclosure : forall R,\n  trans R ->\n  trans (rclosure R).\nProof using.\n  unfolds trans. introv H M1 M2.\n  destruct M1; destruct M2; subst*.\nQed.\n\nLemma total_rclosure : forall R,\n  total R -> \n  total (rclosure R).\nProof using. \n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma rclosure_eq_of_refl : forall R,\n  refl R ->\n  rclosure R = R.\nProof using.\n  unfolds refl. introv H. extens. iff M.\n  { destruct M; subst*. } { auto. }\nQed.\n\nLemma rclosure_inverse_eq : forall R,\n  rclosure (inverse R) = inverse (rclosure R).\nProof using. unfold inverse. extens. iff M; destruct* M. Qed.\n\n(** Constructors *)\n\n(** -- TODO: rename to\n   rclosure_of_rclosure_step \n   rclosure_of_step_rclosure\n   trans_inv_rclosure_step\n   trans_inv_step_rclosure *)\n\nLemma rclosure_trans_l : forall y x z R,\n  trans R -> \n  rclosure R x y -> \n  R y z -> \n  rclosure R x z.\nProof using. introv T M N. rewrite rclosure_eq in *. destruct M; subst*. Qed.\n\nLemma rclosure_trans_r : forall y x z R,\n  trans R -> \n  R x y -> \n  rclosure R y z -> \n  rclosure R x z.\nProof using. introv T M N. rewrite rclosure_eq in *. destruct N; subst*. Qed.\n\nLemma trans_rclosure_l : forall y x z R,\n  trans R -> \n  rclosure R x y -> \n  R y z -> \n  R x z.\nProof using. introv T M H. rewrite rclosure_eq in *. destruct M; subst*. Qed.\n\nLemma trans_rclosure_r : forall y x z R,\n  trans R -> \n  R x y -> \n  rclosure R y z -> \n  R x z.\nProof using. introv T M N. rewrite rclosure_eq in *. destruct N; subst*. Qed.\n\n(** Negation *)\n\nLemma not_rclosure_inv : forall R x y,\n  ~ rclosure R x y ->\n  ~ R x y /\\ x <> y.\nProof using. introv M. rewrite* rclosure_eq in M. Qed.\n\nLemma not_rclosure_inv_rel : forall R x y,\n  ~ rclosure R x y ->\n  ~ R x y.\nProof using. introv M. rewrite* rclosure_eq in M. Qed.\n\nLemma not_rclosure_inv_neq : forall R x y,\n  ~ rclosure R x y ->\n  x <> y.\nProof using. introv M. rewrite* rclosure_eq in M. Qed.\n\n(** Inclusions *)\n\nLemma rel_incl_rclosure : forall R,\n  rel_incl R (rclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma rclosure_of_rel : forall R x y,\n  R x y ->\n  rclosure R x y.\nProof using. intros. applys* rel_incl_rclosure. Qed.\n\nLemma covariant_rclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (rclosure R1) (rclosure R2).\nProof using. introv H M. destruct* M. Qed.\n\nLemma rel_incl_rclosure_rclosure : forall R1 R2,\n  rel_incl R1 (rclosure R2) ->\n  rel_incl (rclosure R1) (rclosure R2).\nProof using. introv H M. destruct* M. Qed.\n\nEnd Rclosure.\n\nHint Constructors rclosure : rclosure.\n(* --LATER: here and later, add more hints *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Symmetric closure  *)\n\nInductive sclosure A (R:binary A) : binary A :=\n  | sclosure_once : forall x y,\n      R x y -> \n      sclosure R x y\n  | sclosure_sym : forall x y,\n      sclosure R y x ->\n      sclosure R x y.\n\nSection Sclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors sclosure.\n\n(** Equivalent definition *)\n\nLemma sclosure_eq : forall R x y,  \n  sclosure R x y = (R x y \\/ R y x).\nProof using.\n  extens. iff M.\n  { induction* M. } \n  { destruct M; subst*. }\nQed.\n\nLemma sclosure_inv : forall R x y,  \n  sclosure R x y ->\n  R x y \\/ R y x.\nProof using. introv M; rewrite* sclosure_eq in M. Qed.\n\n(** Properties *)\n\nLemma refl_sclosure : forall R,\n  refl R ->\n  refl (sclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_sclosure : forall R,\n  sym (sclosure R).\nProof using. unfolds sym. introv N. destruct* N. Qed.\n\nLemma total_sclosure : forall R,\n  total R ->\n  total (sclosure R).\nProof using. \n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma sclosure_eq_of_sym : forall R,\n  sym R ->\n  sclosure R = R.\nProof using.\n  unfolds sym. introv H. extens. intros. rewrite sclosure_eq.\n  iff M. { destruct M; subst*. } { auto. }\nQed.\n\nLemma sclosure_inverse_eq : forall R,\n  sclosure (inverse R) = sclosure R.\nProof using. \n  unfolds inverse. extens. intros. do 2 rewrite sclosure_eq. autos*.\nQed.\n\n(** Negation *)\n\nLemma not_sclosure_inv : forall R x y,\n  ~ sclosure R x y ->\n  ~ R x y /\\ ~ R y x.\nProof using. introv M. rewrite* sclosure_eq in M. Qed.\n\nLemma not_sclosure_inv_l : forall R x y,\n  ~ sclosure R x y ->\n  R x y ->\n  False.\nProof using. introv M. rewrite* sclosure_eq in M. Qed.\n\nLemma not_sclosure_inv_r : forall R x y,\n  ~ sclosure R x y ->\n  R y x ->\n  False.\nProof using. introv M. rewrite* sclosure_eq in M. Qed.\n\n(** Inclusions *)\n\nLemma rel_incl_sclosure : forall R,\n  rel_incl R (sclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma rel_incl_inverse_sclosure : forall R,\n  rel_incl (inverse R) (sclosure R).\nProof using. unfolds* rel_incl, inverse. Qed.\n\nLemma covariant_sclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (sclosure R1) (sclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_sclosure_sclosure : forall R1 R2,\n  rel_incl R1 (sclosure R2) ->\n  rel_incl (sclosure R1) (sclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nEnd Sclosure.\n\nHint Constructors sclosure : sclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexive-symmetric closure  *)\n\nInductive rsclosure A (R:binary A) : binary A :=\n  | rsclosure_once : forall x y,\n      R x y -> \n      rsclosure R x y\n  | rsclosure_refl : forall x,\n      rsclosure R x x\n  | rsclosure_sym : forall x y,\n      rsclosure R x y ->\n      rsclosure R y x.\n\nSection Rsclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rsclosure.\n\n(** Equivalent definition *)\n\nLemma rsclosure_eq : forall R x y,  \n  rsclosure R x y = (R x y \\/ R y x \\/ x = y).\nProof using.\n  extens. iff M.\n  { induction* M. } \n  { destruct M as [M|[M|M]]; subst*. }\nQed.\n\nLemma rsclosure_inv : forall R x y,  \n  rsclosure R x y ->\n  R x y \\/ R y x \\/ x = y.\nProof using. introv M; rewrite* rsclosure_eq in M. Qed.\n\n(** Properties *)\n\nLemma refl_rsclosure : forall R,\n  refl (rsclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_rsclosure : forall R,\n  sym (rsclosure R).\nProof using. unfolds sym. introv N. destruct* N. Qed.\n\nLemma total_rsclosure : forall R,\n  total R ->\n  total (rsclosure R).\nProof using.\n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma rsclosure_inverse_eq : forall R,\n  rsclosure (inverse R) = rsclosure R.\nProof using.\n  unfold inverse. extens. intros. do 2 rewrite rsclosure_eq. autos*.\nQed.\n\n(** Negation *)\n\nLemma not_rsclosure_inv : forall R x y,\n  ~ rsclosure R x y ->\n  ~ R x y /\\ ~ R y x /\\ ~ x = y.\nProof using. introv M. rewrite* rsclosure_eq in M. Qed.\n\nLemma not_rsclosure_inv_l : forall R x y,\n  ~ rsclosure R x y ->\n  R x y ->\n  False.\nProof using. introv M. rewrite* rsclosure_eq in M. Qed.\n\nLemma not_rsclosure_inv_r : forall R x y,\n  ~ rsclosure R x y ->\n  R y x ->\n  False.\nProof using. introv M. rewrite* rsclosure_eq in M. Qed.\n\nLemma not_rsclosure_inv_neq : forall R x y,\n  ~ rsclosure R x y ->\n  x <> y.\nProof using. introv M. rewrite* rsclosure_eq in M. Qed.\n\n(** Inclusions *)\n\nLemma rel_incl_rsclosure : forall R,\n  rel_incl R (rsclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma rel_incl_inverse_rsclosure : forall R,\n  rel_incl (inverse R) (rsclosure R).\nProof using. unfolds* rel_incl, inverse. Qed.\n\nLemma covariant_rsclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (rsclosure R1) (rsclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_rsclosure_rsclosure : forall R1 R2,\n  rel_incl R1 (rsclosure R2) ->\n  rel_incl (rsclosure R1) (rsclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nEnd Rsclosure.\n\nHint Constructors rsclosure : rsclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Transitive closure ( R+ ), defined as [R \\o R*] *)\n\nInductive tclosure A (R:binary A) : binary A :=\n  | tclosure_once : forall x y,\n      R x y -> \n      tclosure R x y\n  | tclosure_trans : forall y x z,\n      tclosure R x y -> \n      tclosure R y z -> \n      tclosure R x z.\n\nSection Tclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors tclosure.\n\n(** Properties *)\n\nLemma refl_tclosure : forall R,\n  refl R ->\n  refl (tclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_tclosure : forall R,\n  sym R ->\n  sym (tclosure R).\nProof using. unfolds sym. introv H N. induction* N. Qed.\n\nLemma trans_tclosure : forall R,\n  trans (tclosure R).\nProof using. unfolds* trans. Qed.\n\nLemma total_tclosure : forall R,\n  total R ->\n  total (tclosure R).\nProof using. \n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma tclosure_eq_of_trans : forall R,\n  trans R ->\n  tclosure R = R.\nProof using.\n  unfolds trans. introv H. extens. iff M.\n  { induction M; subst*. }\n  { auto. }\nQed.\n\nLemma tclosure_inverse_eq : forall R,\n  tclosure (inverse R) = inverse (tclosure R).\nProof using. \n  unfolds inverse. extens. intros x y. iff M; induction* M. \nQed.\n\n(** Constructors *)\n\nLemma tclosure_l : forall R y x z,\n  R x y -> \n  tclosure R y z -> \n  tclosure R x z.\nProof using. autos*. Qed.\n\nLemma tclosure_r : forall R y x z,\n  tclosure R x y -> \n  R y z -> \n  tclosure R x z.\nProof using. autos*. Qed.\n\n(** Inclusions *)\n\nLemma rel_incl_tclosure : forall R,\n  rel_incl R (tclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma covariant_tclosure : forall A (R1 R2 : binary A),\n  rel_incl R1 R2 ->\n  rel_incl (tclosure R1) (tclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_tclosure_tclosure : forall R1 R2,\n  rel_incl R1 (tclosure R2) ->\n  rel_incl (tclosure R1) (tclosure R2).\nProof using. introv H M. induction* M. Qed.\n\n(** Induction principle with steps at head or tail *)\n\nSection Ind.\n\nInductive tclosure'l A (R:binary A) : binary A :=\n  | tclosure'l_once : forall x y,\n      R x y -> \n      tclosure'l R x y\n  | tclosure'l_step : forall y x z,\n      R x y -> \n      tclosure'l R y z -> \n      tclosure'l R x z.\n\nLemma trans_tclosure'l : forall R,\n  trans (tclosure'l R).\nProof using.\n  Hint Constructors tclosure'l.\n  intros R y x z M1. gen z. induction M1; introv M2; autos*.\nQed.  \n\nLemma tclosure_eq_tclosure'l : forall R,\n  tclosure R = tclosure'l R.\n  (* --LATER: tclosure'l = tclosure. *)\nProof using.\n  extens. intros x y. iff M.  \n  { induction* M. applys* trans_tclosure'l y. }\n  { induction* M. }\nQed.\n\nLemma tclosure_ind_l : forall R (P : A -> A -> Prop),\n  (forall x y, R x y -> P x y) ->\n  (forall y x z, R x y -> tclosure R y z -> P y z -> P x z) ->\n  (forall x y, tclosure R x y -> P x y).\nProof using.\n  introv H1 H2 M. rewrite tclosure_eq_tclosure'l in *. induction* M.\nQed.\n\nInductive tclosure'r A (R:binary A) : binary A :=\n  | tclosure'r_once : forall x y,\n      R x y -> \n      tclosure'r R x y\n  | tclosure'r_step : forall y x z,\n      tclosure'r R x y -> \n      R y z ->\n      tclosure'r R x z.\n\nLemma trans_tclosure'r : forall R,\n  trans (tclosure'r R).\nProof using.\n  Hint Constructors tclosure'r.\n  intros R y x z M1 M2. gen x. induction M2; introv M1; autos*.\nQed.  \n\nLemma tclosure_eq_tclosure'r : forall R,\n  tclosure R = tclosure'r R.\n  (* --LATER: tclosure'l = tclosure. *)\nProof using.\n  extens. intros x y. iff M.  \n  { induction* M. applys* trans_tclosure'r y. }\n  { induction* M. }\nQed.\n\nLemma tclosure_ind_r : forall R (P : A -> A -> Prop),\n  (forall x y, R x y -> P x y) ->\n  (forall y x z, tclosure R x y -> P x y -> R y z -> P x z) ->\n  (forall x y, tclosure R x y -> P x y).\nProof using.\n  introv H1 H2 M. rewrite tclosure_eq_tclosure'r in *. induction* M.\nQed.\n\n(* --LATER: can these induction principles be proved directly? *)\n\nEnd Ind.\n\n(** Inversion principle with steps at head or tail *)\n\nLemma tclosure_inv_l : forall R x z,\n  tclosure R x z ->\n  (R x z) \\/ (exists y, R x y /\\ tclosure R y z).\nProof using. intros R. applys* tclosure_ind_l. Qed.\n\nLemma tclosure_inv_r : forall R x z,\n  tclosure R x z ->\n  (R x z) \\/ (exists y, tclosure R x y /\\ R y z).\nProof using. intros R. applys* tclosure_ind_r. Qed.\n\nEnd Tclosure.\n\nHint Resolve tclosure_once tclosure_l tclosure_r\n  : rtclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexive-transitive closure ( R* ) *)\n\nInductive rtclosure A (R:binary A) : binary A :=\n  | rtclosure_once : forall x y,\n      R x y ->\n      rtclosure R x y\n  | rtclosure_refl : forall x,\n      rtclosure R x x\n  | rtclosure_trans : forall y x z,\n      rtclosure R x y -> \n      rtclosure R y z -> \n      rtclosure R x z.\n\nSection Rtclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rtclosure.\n\n(** Properties *)\n\nLemma refl_rtclosure : forall R,\n  refl (rtclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_rtclosure : forall R,\n  sym R ->\n  sym (rtclosure R).\nProof using. unfolds sym. introv M N. induction* N. Qed.\n\nLemma trans_rtclosure : forall R,\n  trans (rtclosure R).\nProof using. unfolds* trans. Qed.\n\nLemma total_rtclosure : forall R,\n  total R ->\n  total (rtclosure R).\nProof using. \n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma tclosure_eq_of_refl_trans : forall R,\n  refl R ->\n  trans R ->\n  rtclosure R = R.\nProof using.\n  unfolds refl, trans. introv H1 H2. extens. iff M.\n  { induction M; subst*. }\n  { autos*. }\nQed.\n\nLemma rtclosure_inverse_eq : forall R,\n  rtclosure (inverse R) = inverse (rtclosure R).\nProof using. unfold inverse. extens. iff M; induction* M. Qed.\n\n(** Constructors *)\n\nLemma rtclosure_l : forall R y x z,\n  R x y -> \n  rtclosure R y z -> \n  rtclosure R x z.\nProof using. autos*. Qed.\n\nLemma rtclosure_r : forall R y x z,\n  rtclosure R x y -> \n  R y z -> \n  rtclosure R x z.\nProof using. autos*. Qed.\n\n(* Same as above, reformulated to make [eauto] faster *)\nLemma rtclosure_r' : forall R y x z,\n  R y z -> \n  rtclosure R x y -> \n  rtclosure R x z.\nProof using. autos*. Qed.\n\n(** Inclusion *)\n\nLemma rel_incl_rtclosure : forall R,\n  rel_incl R (rtclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma covariant_rtclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (rtclosure R1) (rtclosure R2).\nProof using. unfolds rel_incl. introv H M. induction* M. Qed.\n\n(* --TODO: find better name for this one and similar *)\nLemma rel_incl_rtclosure_rtclosure : forall R1 R2,\n  rel_incl R1 (rtclosure R2) ->\n  rel_incl (rtclosure R1) (rtclosure R2).\nProof using. unfolds rel_incl. introv H M. induction* M. Qed.\n\nLemma rel_incl_union_rtclosure : forall R1 R2,\n  rel_incl (union (rtclosure R1) (rtclosure R2))\n           (rtclosure (union R1 R2)).\nProof using.\n  hint rel_incl_union_l, rel_incl_union_r. introv [M|M].\n  { applys* covariant_rtclosure R1. }\n  { applys* covariant_rtclosure R2. }\nQed.\n\n(** Negation *)\n\nLemma not_rtclosure_inv_neq : forall R x y,\n  ~ rtclosure R x y ->\n  x <> y.\nProof using. introv M E. subst. induction* M. Qed.\n\n(** Induction principle with steps at head or tail *)\n\nSection Ind.\n\nInductive rtclosure'l A (R:binary A) : binary A :=\n  | rtclosure'l_refl : forall x,\n      rtclosure'l R x x\n  | rtclosure'l_step : forall y x z,\n      R x y -> \n      rtclosure'l R y z -> \n      rtclosure'l R x z.\n\nLemma trans_rtclosure'l : forall R,\n  trans (rtclosure'l R).\nProof using.\n  Hint Constructors rtclosure'l.\n  intros R y x z M1. gen z. induction M1; introv M2; autos*.\nQed.  \n\nLemma rtclosure_eq_rtclosure'l : forall R,\n  rtclosure R = rtclosure'l R.\n  (* --LATER: tclosure'l = tclosure. *)\nProof using.\n  extens. intros x y. iff M.  \n  { induction* M. applys* trans_rtclosure'l y. }\n  { induction* M. }\nQed.\n\nLemma rtclosure_ind_l : forall R (P : A -> A -> Prop),\n  (forall x, P x x) ->\n  (forall y x z, R x y -> rtclosure R y z -> P y z -> P x z) ->\n  (forall x y, rtclosure R x y -> P x y).\nProof using.\n  introv H1 H2 M. rewrite rtclosure_eq_rtclosure'l in *. induction* M.\nQed.\n\nInductive rtclosure'r A (R:binary A) : binary A :=\n  | rtclosure'r_refl : forall x,\n      rtclosure'r R x x\n  | rtclosure'r_step : forall y x z,\n      rtclosure'r R x y -> \n      R y z ->\n      rtclosure'r R x z.\n\nLemma trans_rtclosure'r : forall R,\n  trans (rtclosure'r R).\nProof using.\n  Hint Constructors rtclosure'r.\n  intros R y x z M1 M2. gen x. induction M2; introv M1; autos*.\nQed.  \n\nLemma rtclosure_eq_rtclosure'r : forall R,\n  rtclosure R = rtclosure'r R.\n  (* --LATER: tclosure'l = tclosure. *)\nProof using.\n  extens. intros x y. iff M.  \n  { induction* M. applys* trans_rtclosure'r y. }\n  { induction* M. }\nQed.\n\nLemma rtclosure_ind_r : forall R (P : A -> A -> Prop),\n  (forall x, P x x) ->\n  (forall y x z, rtclosure R x y -> P x y -> R y z -> P x z) ->\n  (forall x y, rtclosure R x y -> P x y).\nProof using.\n  introv H1 H2 M. rewrite rtclosure_eq_rtclosure'r in *. induction* M.\nQed.\n\nEnd Ind.\n\n(** Inversion principle with steps at head or tail *)\n\nLemma rtclosure_inv_l : forall R x z,\n  rtclosure R x z ->\n  (x = z) \\/ (exists y, R x y /\\ rtclosure R y z).\nProof using. intros R. applys* rtclosure_ind_l. Qed.\n\nLemma rtclosure_inv_r : forall R x z,\n  rtclosure R x z ->\n  (x = z) \\/ (exists y, rtclosure R x y /\\ R y z).\nProof using. intros R. applys* rtclosure_ind_r. Qed.\n\nEnd Rtclosure.\n\nHint Resolve rtclosure_refl rtclosure_once \n  rtclosure_l rtclosure_r' : rtclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Symmetric-transitive closure *)\n\nInductive stclosure A (R:binary A) : binary A :=\n  | stclosure_once : forall x y,\n      R x y -> \n      stclosure R x y\n  | stclosure_sym : forall x y,\n      stclosure R x y -> \n      stclosure R y x\n  | stclosure_trans : forall y x z,\n      stclosure R x y -> \n      stclosure R y z -> \n      stclosure R x z.\n\nSection Stclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors stclosure.\n\n(** Properties *)\n\nLemma refl_stclosure : forall R,\n  refl R ->\n  refl (stclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_stclosure : forall R,\n  sym (stclosure R).\nProof using. unfolds sym. introv N. induction* N. Qed.\n\nLemma trans_stclosure : forall R,\n  trans (stclosure R).\nProof using. unfolds* trans. Qed.\n\nLemma total_stclosure : forall R,\n  total R ->\n  total (stclosure R).\nProof using. \n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma stclosure_eq_of_sym_trans : forall R,\n  sym R ->\n  trans R ->\n  stclosure R = R.\nProof using.\n  unfolds sym, trans. introv H1 H2. extens. iff M.\n  { induction M; subst*. }\n  { autos*. }\nQed.\n\nLemma stclosure_inverse_eq : forall R,\n  stclosure (inverse R) = inverse (stclosure R).\nProof using. \n  unfolds inverse. extens. intros x y. iff M; induction* M. \nQed.\n\n(** Constructors *)\n\nLemma stclosure_l : forall R y x z,\n  R x y -> \n  stclosure R y z -> \n  stclosure R x z.\nProof using. autos*. Qed.\n\nLemma stclosure_r : forall R y x z,\n  stclosure R x y -> \n  R y z -> \n  stclosure R x z.\nProof using. autos*. Qed.\n\n(** Inclusion *)\n\nLemma rel_incl_stclosure : forall R,\n  rel_incl R (stclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma covariant_stclosure : forall R1 R2,\n  rel_incl R1 R2 -> \n  rel_incl (stclosure R1) (stclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_stclosure_stclosure : forall R1 R2,\n  rel_incl R1 (stclosure R2) ->\n  rel_incl (stclosure R1) (stclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nEnd Stclosure.\n\nHint Constructors stclosure : stclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexive-symmetric-transitive closure *)\n\nInductive rstclosure A (R:binary A) : binary A :=\n  | rstclosure_once : forall x y,\n      R x y -> \n      rstclosure R x y\n  | rstclosure_refl : forall x,\n      rstclosure R x x\n  | rstclosure_sym : forall x y,\n      rstclosure R x y ->\n      rstclosure R y x\n  | rstclosure_trans : forall y x z,\n      rstclosure R x y -> \n      rstclosure R y z -> \n      rstclosure R x z.\n\nSection Rstclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rstclosure.\n\n(** Properties *)\n\nLemma refl_rstclosure : forall R,\n  refl (rstclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_rstclosure : forall R,\n  sym (rstclosure R).\nProof using. unfolds* sym. Qed.\n\nLemma trans_rstclosure : forall R,\n  trans (rstclosure R).\nProof using. unfolds* trans. Qed.\n\nLemma total_rstclosure : forall R,\n  total R ->\n  total (rstclosure R).\nProof using. \n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma rstclosure_eq_of_refl_sym_trans : forall R,\n  refl R ->\n  sym R ->\n  trans R ->\n  rstclosure R = R.\nProof using.\n  unfolds refl, sym, trans. introv H. extens. iff M.\n  { induction M; subst*. }\n  { auto. }\nQed.\n\nLemma rstclosure_inverse_eq : forall R,\n  rstclosure (inverse R) = rstclosure R.\nProof using. \n  unfolds inverse. extens. intros x y. iff M; induction* M. \nQed.\n\n(** Constructors *)\n\nLemma rstclosure_l : forall R y x z,\n  R x y -> \n  rstclosure R y z -> \n  rstclosure R x z.\nProof using. autos*. Qed.\n\nLemma rstclosure_r : forall R y x z,\n  rstclosure R x y -> \n  R y z -> \n  rstclosure R x z.\nProof using. autos*. Qed.\n\n(** Inclusion *)\n\nLemma rel_incl_rstclosure : forall R,\n  rel_incl R (rstclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma rel_incl_inverse_rstclosure : forall R,\n  rel_incl (inverse R) (rstclosure R).\nProof using. unfolds* rel_incl, inverse. Qed.\n\nLemma covariant_rstclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (rstclosure R1) (rstclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_rstclosure_rstclosure : forall R1 R2,\n  rel_incl R1 (rstclosure R2) ->\n  rel_incl (rstclosure R1) (rstclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_union_rstclosure : forall R1 R2,\n  rel_incl (union (rstclosure R1) (rstclosure R2))\n           (rstclosure (union R1 R2)).\nProof using.\n  hint rel_incl_union_l, rel_incl_union_r. introv [M|M].\n  { applys* covariant_rstclosure R1. }\n  { applys* covariant_rstclosure R2. }\nQed.\n\nEnd Rstclosure.\n\nHint Constructors rstclosure : rstclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Relationship between closures *)\n\nSection ClosuresRel.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rtclosure rsclosure stclosure rstclosure.\n\n(** [rclosure] to [rtclosure] *)\n\nLemma rtclosure_of_rclosure : forall R x y,\n  rclosure R x y -> \n  rtclosure R x y.\nProof using. intros. destruct* H. Qed.\n\nLemma rel_incl_rclosure_rtclosure : forall R,\n  rel_incl (rclosure R) (rtclosure R).\nProof using. intros. applys* rtclosure_of_rclosure. Qed.\n\n(** [tclosure] to [rtclosure] *)\n\nLemma rtclosure_of_tclosure : forall R x y,\n  tclosure R x y -> \n  rtclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_tclosure_rtclosure : forall R,\n  rel_incl (tclosure R) (rtclosure R).\nProof using. intros. applys* rtclosure_of_tclosure. Qed.\n\n(** [rclosure] to [rsclosure] *)\n\nLemma rsclosure_of_rclosure : forall R x y,\n  rclosure R x y -> \n  rsclosure R x y.\nProof using. intros. destruct* H. Qed.\n\nLemma rel_incl_rclosure_rsclosure : forall R,\n  rel_incl (rclosure R) (rsclosure R).\nProof using. intros. applys* rsclosure_of_rclosure. Qed.\n\n(** [sclosure] to [rsclosure] *)\n\nLemma rsclosure_of_sclosure : forall R x y,\n  sclosure R x y -> \n  rsclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_sclosure_rsclosure : forall R,\n  rel_incl (sclosure R) (rsclosure R).\nProof using. intros. applys* rsclosure_of_sclosure. Qed.\n\n(** [sclosure] to [stclosure] *)\n\nLemma stclosure_of_sclosure : forall R x y,\n  sclosure R x y -> \n  stclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_slosure_rsclosure : forall R,\n  rel_incl (sclosure R) (stclosure R).\nProof using. intros. applys* stclosure_of_sclosure. Qed.\n\n(** [tclosure] to [stclosure] *)\n\nLemma stclosure_of_tclosure : forall R x y,\n  tclosure R x y -> \n  stclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_tclosure_stclosure : forall R,\n  rel_incl (tclosure R) (stclosure R).\nProof using. intros. applys* stclosure_of_tclosure. Qed.\n\n(** [rclosure] to [rstclosure] *)\n\nLemma rstclosure_of_rclosure : forall R x y,\n  rclosure R x y -> \n  rstclosure R x y.\nProof using. intros. destruct* H. Qed.\n\nLemma rel_incl_rclosure_rstclosure : forall R,\n  rel_incl (rclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_rclosure. Qed.\n\n(** [sclosure] to [rstclosure] *)\n\nLemma rstclosure_of_sclosure : forall R x y,\n  sclosure R x y -> \n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_sclosure_rstclosure : forall R,\n  rel_incl (sclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_sclosure. Qed.\n\n(** [tclosure] to [tstclosure] *)\n\nLemma rstclosure_of_tclosure : forall R x y,\n  tclosure R x y -> \n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_tclosure_rstclosure : forall R,\n  rel_incl (tclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_tclosure. Qed.\n\n(** [rsclosure] to [rstclosure] *)\n\nLemma rstclosure_of_rsclosure : forall R x y,\n  rsclosure R x y -> \n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_rsclosure_rstclosure : forall R,\n  rel_incl (rsclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_rsclosure. Qed.\n\n(** [rtclosure] to [rstclosure] *)\n\nLemma rstclosure_of_rtclosure : forall R x y,\n  rtclosure R x y -> \n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_rtclosure_rstclosure : forall R,\n  rel_incl (rtclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_rtclosure. Qed.\n\n(** [stclosure] to [rstclosure] *)\n\nLemma rstclosure_of_stclosure : forall R x y,\n  stclosure R x y -> \n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_stclosure_rstclosure : forall R,\n  rel_incl (stclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_stclosure. Qed.\n\nEnd ClosuresRel.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Iterated closures *)\n\nSection IterClosures.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rclosure sclosure tclosure \n  rtclosure rsclosure stclosure rstclosure.\nHint Resolve sym_tclosure sym_sclosure sym_rclosure\n  sym_rtclosure sym_rsclosure sym_rtclosure sym_rstclosure.\n\nLemma rclosure_sclosure_eq_rsclosure : forall R,\n  rclosure (sclosure R) = rsclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { destruct* M. { applys* rsclosure_of_sclosure. } }\n  { induction* M. { applys* sym_inv. } }\nQed.\n\nLemma sclosure_rclosure_eq_rsclosure : forall R,\n  sclosure (rclosure R) = rsclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rsclosure_of_rclosure. } }\n  { induction* M. }\nQed.\n\nLemma rclosure_tclosure_eq_rtclosure : forall R,\n  rclosure (tclosure R) = rtclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rtclosure_of_tclosure. } }\n  { induction* M. { destruct IHM1; destruct IHM2; autos*. } }\nQed.\n\nLemma tclosure_rclosure_eq_rtclosure : forall R,\n  tclosure (rclosure R) = rtclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rtclosure_of_rclosure. } }\n  { induction* M. }\nQed.\n\nLemma tclosure_sclosure_eq_stclosure : forall R,\n  tclosure (sclosure R) = stclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* stclosure_of_sclosure. } }\n  { induction* M. { applys* sym_inv. } }\nQed.\n\nLemma rclosure_stclosure_eq_rstclosure : forall R,\n  rclosure (stclosure R) = rstclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rstclosure_of_stclosure. } }\n  { induction* M.\n    { destruct IHM; autos*. }\n    { destruct IHM1; destruct IHM2; autos*. } }\nQed.\n\nLemma stclosure_rclosure_eq_rstclosure : forall R,\n  stclosure (rclosure R) = rstclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rstclosure_of_rclosure. } }\n  { induction* M. }\nQed.\n\nLemma rtclosure_sclosure_eq_rstclosure : forall R,\n  rtclosure (sclosure R) = rstclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rstclosure_of_sclosure. } }\n  { induction* M. { applys* sym_inv. } }\nQed.\n\nLemma tclosure_rsclosure_eq_rstclosure : forall R,\n  tclosure (rsclosure R) = rstclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rstclosure_of_rsclosure. } }\n  { induction* M. { applys* sym_inv. } }\nQed.\n\nEnd IterClosures.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Other lemmas -- TODO *)\n\nSection EquivClosures.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rclosure sclosure tclosure rsclosure stclosure.\n\nLemma rsclosure_eq_union_rclosure_sclosure : forall R,\n  rsclosure R = union (rclosure R) (sclosure R).\nProof using.\n  extens. intros x y. unfold union. iff M.\n  { induction* M. destruct* IHM as [H|H]. destruct* H. }\n  { destruct* M as [H|H]. destruct* H. applys* rsclosure_of_sclosure. }\nQed.\n\nLemma rtclosure_eq_union_rclosure_tclosure : forall R,\n  rtclosure R = union (rclosure R) (tclosure R).\nProof using.\n  extens. intros x y. unfold union. iff M.\n  { induction* M. destruct IHM1 as [H1|H1]; destruct IHM2 as [H2|H2].\n     { destruct H1; destruct* H2. }\n     { destruct* H1. }\n     { destruct* H2. }\n     { autos*. } }\n  { destruct* M.\n    { applys* rtclosure_of_rclosure. }\n    { applys* rtclosure_of_tclosure. } }\nQed.\n\nLemma rtclosure_inv_rclosure_or_tclosure : forall R x y,\n  rtclosure R x y -> \n  x = y \\/ tclosure R x y.\nProof using.\n  introv M. rewrite rtclosure_eq_union_rclosure_tclosure in M.\n  destruct M as [M|M]. { destruct* M. } { auto. }\nQed.\n\nLemma stclosure_eq_rstclosure_of_refl : forall R,\n  refl R ->\n  stclosure R = rstclosure R.\nProof using.\n  introv H. extens. intros x y. iff M.\n  { applys* rstclosure_of_stclosure. }\n  { induction* M. }\nQed.\n\n(* --LATER: many lemmas like the above? *) \n\n(* --TODO: rename this lemma *)\nLemma rel_incl_tclosure_stclosure_l : forall R1 R2,\n  rel_incl R1 (stclosure R2) ->\n  rel_incl (tclosure R1) (stclosure R2).\nProof using. introv H M. induction* M. Qed.\n\n(* --LATER: many lemmas like the above? *)\n\nEnd EquivClosures.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Mixed transitivity between closures *)\n\nSection MixedClosures.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors tclosure.\n\nLemma tclosure_of_rtclosure_l : forall R x y z,\n  rtclosure R x y -> \n  R y z -> \n  tclosure R x z.\nProof using.\n  introv H M. destruct (rtclosure_inv_rclosure_or_tclosure H). \n  { subst*. }\n  { applys* tclosure_r. }\nQed.\n\nLemma tclosure_of_rtclosure_r : forall R x y z,\n  R x y -> \n  rtclosure R y z -> \n  tclosure R x z.\nProof using.\n  introv M H. destruct (rtclosure_inv_rclosure_or_tclosure H). \n  { subst*. }\n  { applys* tclosure_l. }\nQed.\n\nLemma tclosure_of_rtclosure_tclosure : forall R y x z,\n  rtclosure R x y -> \n  tclosure R y z -> \n  tclosure R x z.\nProof using.\n  introv H M. destruct (rtclosure_inv_rclosure_or_tclosure H); subst*. \nQed.\n\nLemma tclosure_of_tclosure_rtclosure : forall R y x z,\n  tclosure R x y -> \n  rtclosure R y z -> \n  tclosure R x z.\nProof using.\n  introv M H. destruct (rtclosure_inv_rclosure_or_tclosure H); subst*. \nQed.\n\nEnd MixedClosures.\n\n(* --LATER: similar lemmas relating [rstclosure] and [stclosure] *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Irreflexive restriction of a relation *)\n\nDefinition strict A (R:binary A) : binary A :=\n  fun x y => R x y /\\ x <> y.\n\nSection Strict.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Unfold strict.\n \nLemma strict_eq_fun : forall R,  \n  strict R = (fun x y => R x y /\\ x <> y).\nProof using. auto. Qed.\n\nLemma strict_eq : forall R x y,  \n  strict R x y = (R x y /\\ x <> y).\nProof using. auto. Qed.\n\nLemma inverse_strict : forall R,\n  inverse (strict R) = strict (inverse R).\nProof using. intros. unfold inverse, strict. extens*. Qed.\n\nLemma trans_strict_l : forall y x z R,\n  trans R -> \n  strict R x y -> \n  R y z -> \n  R x z.\nProof using. introv T (E&H) H'; subst*. Qed.\n\nLemma trans_strict_r : forall y x z R,\n  trans R -> \n  R x y -> \n  strict R y z -> \n  R x z.\nProof using. introv T H (E&H'); subst*. Qed.\n\nLemma irrefl_strict : forall R,\n  irrefl (strict R).\nProof using. unfold strict, irrefl. intros. rew_logic*. Qed.\n\nLemma antisym_strict : forall R,\n  antisym R -> \n  antisym (strict R).\nProof using. unfolds* antisym, strict. Qed.\n\nLemma trans_strict : forall R,\n  trans R -> \n  antisym R -> \n  trans (strict R).\nProof using.\n  introv T S. unfold strict. introv [H1 H2] [H3 H4]. split.\n  { apply* T. }\n  { intros K. subst. apply H2. apply~ S. }\nQed.\n\nLemma strict_rclosure : forall R,\n  irrefl R -> \n  strict (rclosure R) = R.\nProof using.\n  unfold strict. extens. intros x y. iff (K1&K2) K.\n  { destruct* K1. }\n  { split. { left*. } { apply* irrefl_inv_neq. } }\nQed.\n\nLemma rclosure_strict : forall R,\n  refl R -> \n  rclosure (strict R) = R.\nProof using.\n  Hint Constructors rclosure. \n  unfold strict. extens. intros x y. iff K.\n  { destruct K; subst*. }\n  { tests: (x = y); subst*. }\nQed.\n\nEnd Strict.\n\n\n(* ********************************************************************** *)\n(** Function to relation *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion of a function in a relation *)\n\n(** [fun_in_rel f R] asserts that input-output pairs of [f] are \n    included in the relation [R]. *)\n\nDefinition fun_in_rel A B (f:A->B) (R:A->B->Prop) :=\n  forall x, R x (f x).\n\nSection Fun_in_rel.\nVariables (A B : Type).\nImplicit Type f : A->B.\nImplicit Type R : A->B->Prop.\n\nLemma defined_of_fun_in_rel : forall f R,\n  fun_in_rel f R ->\n  defined R.\nProof using. unfolds* fun_in_rel, defined. Qed.\n\n(** The relation built from a function [f] is included in a relation  \n    [R] iff the function [f] is included in [R] *)\n\nLemma rel_incl_rel_fun_eq_fun_in_rel : forall f R,\n  rel_incl (rel_fun f) R = fun_in_rel f R.\nProof using.\n  extens. unfold rel_fun, fun_in_rel. iff H; intros x; specializes H x.\n  { applys* H. }\n  { intros y Hy. subst~. }\nQed.\n\nEnd Fun_in_rel.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion of a relation in a function *)\n\n(** [rel_in_fun R f] asserts that input-output pairs of [R] \n    are input-output for [f]. *)\n\nDefinition rel_in_fun A B (R:A->B->Prop) (f:A->B) :=\n  forall x y, R x y -> f x = y.\n\nSection Rel_in_fun.\nVariables (A B : Type).\nImplicit Type f : A->B.\nImplicit Type R : A->B->Prop.\n\nLemma functional_of_rel_in_fun : forall R f,\n  rel_in_fun R f ->\n  functional R.\nProof using.\n  unfold rel_in_fun, functional. introv M N1 N2. \n  lets: M N1. lets: M N2. congruence.\nQed.\n\n(* If the relation [R] is functional and if [f] is included in [R],\n   then [R] is included in [f], i.e., they coincide. *)\n\nLemma rel_in_fun_of_fun_in_rel_functional : forall f R,\n  fun_in_rel f R ->\n  functional R ->\n  rel_in_fun R f.\nProof using.\n  introv h1 h2. intros a b H. forwards M: h1 a. forwards*: h2 H M.\nQed.\n\nEnd Rel_in_fun.\n\n", "meta": {"author": "tilk", "repo": "tlc", "sha": "9a07c989dfc12aba4c5fb02107761c8d7e281996", "save_path": "github-repos/coq/tilk-tlc", "path": "github-repos/coq/tilk-tlc/tlc-9a07c989dfc12aba4c5fb02107761c8d7e281996/src/LibRelation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7320683716192459}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (z : natural) (x : natural) : natural :=\n  plus lf2 (mult z (Succ x)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj252_coqofml_6YaHbw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7320678543854909}}
{"text": "Theorem t1 : forall (P Q : Prop), (P /\\ Q) -> (Q /\\ P).\nintro.\nintro.\nintro.\ndestruct H.\nsplit.\napply H0.\napply H.\nQed.\n\nTheorem t2 : forall (P Q : Prop), (P /\\ Q) <-> (Q /\\ P).\nintro.\nintro.\nsplit.\napply t1.\napply t1.\nQed.\n\nLemma imply_and_or2 : forall P Q R:Prop, (P -> Q) -> (P \\/ R) -> (Q \\/ R).\nintro.\nintro.\nintro.\nintro.\nintro.\ndestruct H0.\nleft.\napply H.\napply H0.\nright.\napply H0.\nQed.\n\nTheorem neg_false : forall A : Prop, ~ A <-> (A <-> False).\nintro.\nsplit.\nunfold not.\nintro.\nsplit.\napply H.\nintro.\ndestruct H0.\nunfold not.\nintro.\ndestruct H.\nintro.\napply H.\napply H1.\nQed.\n", "meta": {"author": "robinrob", "repo": "coq", "sha": "b8f1b6386e8129c6498e1faa4b22f9464cfd27eb", "save_path": "github-repos/coq/robinrob-coq", "path": "github-repos/coq/robinrob-coq/coq-b8f1b6386e8129c6498e1faa4b22f9464cfd27eb/theorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7320678504494745}}
{"text": "Require Import Algebra.AbelianGroup.\nRequire Import Algebra.CommRing.\n\nSection Modules.\nContext {R: Set}(plusR: R -> R -> R)(zeroR: R)(minusR: R -> R).\nContext (multR: R -> R -> R)(oneR: R).\nContext `{Rcring: CommRing R plusR zeroR minusR multR oneR}.\nContext {A: Set}(plusA: A -> A -> A)(zeroA: A)(minusA: A -> A).\nContext `{Aagroup: AbelianGroup A plusA zeroA minusA}.\nContext (action: R -> A -> A).\n\nClass Module_ := {\n  module_distrib_plusA: forall (r: R)(a b: A), action r (plusA a b) = plusA (action r a) (action r b);\n  module_distrib_plusR: forall (r s: R)(a: A), action (plusR r s) a = plusA (action r a) (action s a);\n  module_distrib_multR: forall (r s: R)(a: A), action (multR r s) a = action r (action s a);\n  module_oneR: forall (a: A), action oneR a = a;\n}.\n\nContext `{ARmodule: Module_}.\n\nTheorem module_zeroR (a: A):\n  action zeroR a = zeroA.\nProof.\n  cut (plusA (action zeroR a) (action zeroR a) = action zeroR a).\n  { intros H.\n    apply (agroup_idemp_zero plusA zeroA minusA).\n    assumption. }\n  { rewrite <- module_distrib_plusR.\n    rewrite (cring_plus_ident plusR zeroR minusR multR oneR).\n    reflexivity. }\nQed.\n\nTheorem module_zeroA (r: R):\n  action r zeroA = zeroA.\nProof.\n  cut (plusA (action r zeroA) (action r zeroA) = action r zeroA).\n  { intros H.\n    apply (agroup_idemp_zero plusA zeroA minusA).\n    assumption. }\n  { rewrite <- module_distrib_plusA.\n    rewrite (agroup_ident plusA zeroA minusA).\n    reflexivity. }\nQed.\nEnd Modules.\n", "meta": {"author": "ku-sldg", "repo": "algebra", "sha": "026fb7daeef2dcd88c7d6723929e90f261caf109", "save_path": "github-repos/coq/ku-sldg-algebra", "path": "github-repos/coq/ku-sldg-algebra/algebra-026fb7daeef2dcd88c7d6723929e90f261caf109/old_theories/attempt01/Module.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.7320606303770041}}
{"text": "Theorem imp_trans: forall P Q R: Prop, \n(P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros.\n  apply H0.\n  apply H.\n  assumption.\nQed.\n\nPrint imp_trans.\n\nTheorem imp_perm: forall P Q R: Prop,\n(P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros.\n  apply H.\n  assumption.\n  assumption.\nQed.\n\nPrint imp_perm.\n\nTheorem ignore_Q: forall P Q R: Prop,\n(P -> R) -> P -> Q -> R.\nProof.\n  intros.\n  apply H.\n  assumption.\nQed.\n\nPrint ignore_Q.\n\nTheorem delta_imp: forall P Q: Prop,\n(P -> P -> Q) -> P -> Q.\nProof.\n  intros.\n  apply H.\n  assumption.\n  assumption.\nQed.\n\nPrint delta_imp.\n\nTheorem delta_impR: forall P Q: Prop,\n(P -> Q) -> (P -> P -> Q).\nProof.\n  intros.\n  apply H.\n  assumption.\nQed.\n\nPrint delta_impR.\n\nTheorem diamond: forall P Q R S: Prop,\n(P -> Q) -> (P -> R) -> (Q -> R -> S) -> P -> S.\nProof.\n  intros.\n  apply H1.\n  apply H.\n  assumption.\n  apply H0.\n  assumption.\nQed.\n\nPrint diamond.", "meta": {"author": "limitedeternity", "repo": "PrPr-Labs", "sha": "0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62", "save_path": "github-repos/coq/limitedeternity-PrPr-Labs", "path": "github-repos/coq/limitedeternity-PrPr-Labs/PrPr-Labs-0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62/PrPr-00/Раздел1/Ex5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564154, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7320118312342199}}
{"text": "Require Import XR_Rmax.\nRequire Import XR_Rmin.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rle_antisym.\nRequire Import XR_Ropp_le_contravar.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Ropp_Rmin : forall x y, - Rmin x y = Rmax (-x) (-y).\nProof.\n  intros x y.\n  unfold Rmin, Rmax.\n  destruct (Rle_dec x y) as [ hmin | hmin ] ;\n  destruct (Rle_dec (-x) (-y) ) as [ hmax | hmax ].\n  {\n    apply Rle_antisym.\n    { exact hmax. }\n    {\n      apply Ropp_le_contravar.\n      exact hmin.\n    }\n  }\n  { reflexivity. }\n  { reflexivity. }\n  {\n    apply Rle_antisym.\n    {\n      left.\n      apply Rnot_le_lt.\n      exact hmax.\n    }\n    {\n      left.\n      apply Ropp_lt_contravar.\n      apply Rnot_le_lt.\n      exact hmin.\n    }\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Ropp_Rmin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7320112359569135}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Permutation.v                        \n                                                                     \n    Defintion and properties of permutations                         \n   **********************************************************************)\nRequire Export List.\nRequire Export ListAux.\n \nSection permutation.\nVariable A : Set.\n\n(************************************** \n   Definition of permutations as sequences of adjacent transpositions\n **************************************)\n \nInductive permutation : list A -> list A -> Prop :=\n  | permutation_nil : permutation nil nil\n  | permutation_skip :\n      forall (a : A) (l1 l2 : list A),\n      permutation l2 l1 -> permutation (a :: l2) (a :: l1)\n  | permutation_swap :\n      forall (a b : A) (l : list A), permutation (a :: b :: l) (b :: a :: l)\n  | permutation_trans :\n      forall l1 l2 l3 : list A,\n      permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\nHint Constructors permutation.\n\n(************************************** \n   Reflexivity\n **************************************)\n \nTheorem permutation_refl : forall l : list A, permutation l l.\nsimple induction l.\napply permutation_nil.\nintros a l1 H.\napply permutation_skip with (1 := H).\nQed.\nHint Resolve permutation_refl.\n\n(************************************** \n   Symmetry\n   **************************************)\n \nTheorem permutation_sym :\n forall l m : list A, permutation l m -> permutation m l.\nintros l1 l2 H'; elim H'.\napply permutation_nil.\nintros a l1' l2' H1 H2.\napply permutation_skip with (1 := H2).\nintros a b l1'.\napply permutation_swap.\nintros l1' l2' l3' H1 H2 H3 H4.\napply permutation_trans with (1 := H4) (2 := H2).\nQed.\n\n(************************************** \n   Compatibility with list length\n   **************************************)\n \nTheorem permutation_length :\n forall l m : list A, permutation l m -> length l = length m.\nintros l m H'; elim H'; simpl in |- *; auto.\nintros l1 l2 l3 H'0 H'1 H'2 H'3.\nrewrite <- H'3; auto.\nQed.\n\n(************************************** \n   A permutation of the nil list is the nil list\n   **************************************)\n \nTheorem permutation_nil_inv : forall l : list A, permutation l nil -> l = nil.\nintros l H; generalize (permutation_length _ _ H); case l; simpl in |- *;\n auto.\nintros; discriminate.\nQed.\n \n(************************************** \n   A permutation of the singleton list is the singleton list\n   **************************************)\n \nLet permutation_one_inv_aux :\n  forall l1 l2 : list A,\n  permutation l1 l2 -> forall a : A, l1 = a :: nil -> l2 = a :: nil.\nintros l1 l2 H; elim H; clear H l1 l2; auto.\nintros a l3 l4 H0 H1 b H2.\ninjection H2; intros; subst; auto.\nrewrite (permutation_nil_inv _ (permutation_sym _ _ H0)); auto.\nintros; discriminate.\nQed.\n\nTheorem permutation_one_inv :\n forall (a : A) (l : list A), permutation (a :: nil) l -> l = a :: nil.\nintros a l H; apply permutation_one_inv_aux with (l1 := a :: nil); auto.\nQed.\n\n(************************************** \n   Compatibility with the belonging\n   **************************************)\n \nTheorem permutation_in :\n forall (a : A) (l m : list A), permutation l m -> In a l -> In a m.\nintros a l m H; elim H; simpl in |- *; auto; intuition.\nQed.\n\n(************************************** \n   Compatibility with the append function\n   **************************************)\n \nTheorem permutation_app_comp :\n forall l1 l2 l3 l4,\n permutation l1 l2 -> permutation l3 l4 -> permutation (l1 ++ l3) (l2 ++ l4).\nintros l1 l2 l3 l4 H1; generalize l3 l4; elim H1; clear H1 l1 l2 l3 l4;\n simpl in |- *; auto.\nintros a b l l3 l4 H.\ncut (permutation (l ++ l3) (l ++ l4)); auto.\nintros; apply permutation_trans with (a :: b :: l ++ l4); auto.\nelim l; simpl in |- *; auto.\nintros l1 l2 l3 H H0 H1 H2 l4 l5 H3.\napply permutation_trans with (l2 ++ l4); auto.\nQed.\nHint Resolve permutation_app_comp.\n\n(************************************** \n   Swap two sublists\n   **************************************)\n \nTheorem permutation_app_swap :\n forall l1 l2, permutation (l1 ++ l2) (l2 ++ l1).\nintros l1; elim l1; auto.\nintros; rewrite <- app_nil_end; auto.\nintros a l H l2.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\napply permutation_trans with (l ++ l2 ++ a :: nil); auto.\napply permutation_trans with (((a :: nil) ++ l2) ++ l); auto.\nsimpl in |- *; auto.\napply permutation_trans with (l ++ (a :: nil) ++ l2); auto.\napply permutation_sym; auto.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\napply permutation_app_comp; auto.\nelim l2; simpl in |- *; auto.\nintros a0 l0 H0.\napply permutation_trans with (a0 :: a :: l0); auto.\napply (app_ass l2 (a :: nil) l).\napply (app_ass l2 (a :: nil) l).\nQed.\n\n(************************************** \n   A transposition is a permutation\n   **************************************)\n \nTheorem permutation_transposition :\n forall a b l1 l2 l3,\n permutation (l1 ++ a :: l2 ++ b :: l3) (l1 ++ b :: l2 ++ a :: l3).\nintros a b l1 l2 l3.\napply permutation_app_comp; auto.\nchange\n  (permutation ((a :: nil) ++ l2 ++ (b :: nil) ++ l3)\n     ((b :: nil) ++ l2 ++ (a :: nil) ++ l3)) in |- *.\nrepeat rewrite <- app_ass.\napply permutation_app_comp; auto.\napply permutation_trans with ((b :: nil) ++ (a :: nil) ++ l2); auto.\napply permutation_app_swap; auto.\nrepeat rewrite app_ass.\napply permutation_app_comp; auto.\napply permutation_app_swap; auto.\nQed.\n\n(************************************** \n   An element of a list can be put on top of the list to get a permutation\n   **************************************)\n \nTheorem in_permutation_ex :\n forall a l, In a l -> exists l1 : list A, permutation (a :: l1) l.\nintros a l; elim l; simpl in |- *; auto.\nintros H; case H; auto.\nintros a0 l0 H [H0| H0].\nexists l0; rewrite H0; auto.\ncase H; auto; intros l1 Hl1; exists (a0 :: l1).\napply permutation_trans with (a0 :: a :: l1); auto.\nQed.\n \n(************************************** \n   A permutation of a cons can be inverted\n   **************************************)\n\nLet permutation_cons_ex_aux :\n  forall (a : A) (l1 l2 : list A),\n  permutation l1 l2 ->\n  forall l11 l12 : list A,\n  l1 = l11 ++ a :: l12 ->\n  exists l3 : list A,\n    (exists l4 : list A,\n       l2 = l3 ++ a :: l4 /\\ permutation (l11 ++ l12) (l3 ++ l4)).\nintros a l1 l2 H; elim H; clear H l1 l2.\nintros l11 l12; case l11; simpl in |- *; intros; discriminate.\nintros a0 l1 l2 H H0 l11 l12; case l11; simpl in |- *.\nexists (nil (A:=A)); exists l1; simpl in |- *; split; auto.\ninjection H1; intros; subst; auto.\ninjection H1; intros H2 H3; rewrite <- H2; auto.\nintros a1 l111 H1.\ncase (H0 l111 l12); auto.\ninjection H1; auto.\nintros l3 (l4, (Hl1, Hl2)).\nexists (a0 :: l3); exists l4; split; simpl in |- *; auto.\ninjection H1; intros; subst; auto.\ninjection H1; intros H2 H3; rewrite H3; auto.\nintros a0 b l l11 l12; case l11; simpl in |- *.\ncase l12; try (intros; discriminate).\nintros a1 l0 H; exists (b :: nil); exists l0; simpl in |- *; split; auto.\ninjection H; intros; subst; auto.\ninjection H; intros H1 H2 H3; rewrite H2; auto.\nintros a1 l111; case l111; simpl in |- *.\nintros H; exists (nil (A:=A)); exists (a0 :: l12); simpl in |- *; split; auto.\ninjection H; intros; subst; auto.\ninjection H; intros H1 H2 H3; rewrite H3; auto.\nintros a2 H1111 H; exists (a2 :: a1 :: H1111); exists l12; simpl in |- *;\n split; auto.\ninjection H; intros; subst; auto.\nintros l1 l2 l3 H H0 H1 H2 l11 l12 H3.\ncase H0 with (1 := H3).\nintros l4 (l5, (Hl1, Hl2)).\ncase H2 with (1 := Hl1).\nintros l6 (l7, (Hl3, Hl4)).\nexists l6; exists l7; split; auto.\napply permutation_trans with (1 := Hl2); auto.\nQed.\n \nTheorem permutation_cons_ex :\n forall (a : A) (l1 l2 : list A),\n permutation (a :: l1) l2 ->\n exists l3 : list A,\n   (exists l4 : list A, l2 = l3 ++ a :: l4 /\\ permutation l1 (l3 ++ l4)).\nintros a l1 l2 H.\napply (permutation_cons_ex_aux a (a :: l1) l2 H nil l1); simpl in |- *; auto.\nQed.\n\n(************************************** \n   A permutation can be simply inverted if the two list starts with a cons\n   **************************************)\n \nTheorem permutation_inv :\n forall (a : A) (l1 l2 : list A),\n permutation (a :: l1) (a :: l2) -> permutation l1 l2.\nintros a l1 l2 H; case permutation_cons_ex with (1 := H).\nintros l3 (l4, (Hl1, Hl2)).\napply permutation_trans with (1 := Hl2).\ngeneralize Hl1; case l3; simpl in |- *; auto.\nintros H1; injection H1; intros H2; rewrite H2; auto.\nintros a0 l5 H1; injection H1; intros H2 H3; rewrite H2; rewrite H3; auto.\napply permutation_trans with (a0 :: l4 ++ l5); auto.\napply permutation_skip; apply permutation_app_swap.\napply (permutation_app_swap (a0 :: l4) l5).\nQed.\n\n(************************************** \n   Take a list and return tle list of all pairs of an element of the \n   list and the remaining list\n   **************************************)\n \nFixpoint split_one (l : list A) : list (A * list A) :=\n  match l with\n  | nil => nil (A:=A * list A)\n  | a :: l1 =>\n      (a, l1)\n      :: map (fun p : A * list A => (fst p, a :: snd p)) (split_one l1)\n  end.\n\n(************************************** \n   The pairs of the list are a permutation\n   **************************************)\n \nTheorem split_one_permutation :\n forall (a : A) (l1 l2 : list A),\n In (a, l1) (split_one l2) -> permutation (a :: l1) l2.\nintros a l1 l2; generalize a l1; elim l2; clear a l1 l2; simpl in |- *; auto.\nintros a l1 H1; case H1.\nintros a l H a0 l1 [H0| H0].\ninjection H0; intros H1 H2; rewrite H2; rewrite H1; auto.\ngeneralize H H0; elim (split_one l); simpl in |- *; auto.\nintros H1 H2; case H2.\nintros a1 l0 H1 H2 [H3| H3]; auto.\ninjection H3; intros H4 H5; (rewrite <- H4; rewrite <- H5).\napply permutation_trans with (a :: fst a1 :: snd a1); auto.\napply permutation_skip.\napply H2; auto.\ncase a1; simpl in |- *; auto.\nQed.\n\n(************************************** \n   All elements of the list are there\n   **************************************)\n \nTheorem split_one_in_ex :\n forall (a : A) (l1 : list A),\n In a l1 -> exists l2 : list A, In (a, l2) (split_one l1).\nintros a l1; elim l1; simpl in |- *; auto.\nintros H; case H.\nintros a0 l H [H0| H0]; auto.\nexists l; left; subst; auto.\ncase H; auto.\nintros x H1; exists (a0 :: x); right; auto.\napply\n (in_map (fun p : A * list A => (fst p, a0 :: snd p)) (split_one l) (a, x));\n auto.\nQed.\n\n(************************************** \n   An auxillary function to generate all permutations\n   **************************************)\n \nFixpoint all_permutations_aux (l : list A) (n : nat) {struct n} :\n list (list A) :=\n  match n with\n  | O => nil :: nil\n  | S n1 =>\n      flat_map\n        (fun p : A * list A =>\n         map (cons (fst p)) (all_permutations_aux (snd p) n1)) (\n        split_one l)\n  end.\n(************************************** \n   Generate all the permutations\n   **************************************)\n \nDefinition all_permutations (l : list A) := all_permutations_aux l (length l).\n \n(************************************** \n   All the elements of the list are permutations\n   **************************************)\n\nLet all_permutations_aux_permutation :\n  forall (n : nat) (l1 l2 : list A),\n  n = length l2 -> In l1 (all_permutations_aux l2 n) -> permutation l1 l2.\nintros n; elim n; simpl in |- *; auto.\nintros l1 l2; case l2.\nsimpl in |- *; intros H0 [H1| H1].\nrewrite <- H1; auto.\ncase H1.\nsimpl in |- *; intros; discriminate.\nintros n0 H l1 l2 H0 H1.\ncase in_flat_map_ex with (1 := H1).\nclear H1; intros x; case x; clear x; intros a1 l3 (H1, H2).\ncase in_map_inv with (1 := H2).\nsimpl in |- *; intros y (H3, H4).\nrewrite H4; auto.\napply permutation_trans with (a1 :: l3); auto.\napply permutation_skip; auto.\napply H with (2 := H3).\napply eq_add_S.\napply trans_equal with (1 := H0).\nchange (length l2 = length (a1 :: l3)) in |- *.\napply permutation_length; auto.\napply permutation_sym; apply split_one_permutation; auto.\napply split_one_permutation; auto.\nQed.\n \nTheorem all_permutations_permutation :\n forall l1 l2 : list A, In l1 (all_permutations l2) -> permutation l1 l2.\nintros l1 l2 H; apply all_permutations_aux_permutation with (n := length l2);\n auto.\nQed.\n \n(************************************** \n   A permutation is in the list\n   **************************************)\n\nLet permutation_all_permutations_aux :\n  forall (n : nat) (l1 l2 : list A),\n  n = length l2 -> permutation l1 l2 -> In l1 (all_permutations_aux l2 n).\nintros n; elim n; simpl in |- *; auto.\nintros l1 l2; case l2.\nintros H H0; rewrite permutation_nil_inv with (1 := H0); auto with datatypes.\nsimpl in |- *; intros; discriminate.\nintros n0 H l1; case l1.\nintros l2 H0 H1;\n rewrite permutation_nil_inv with (1 := permutation_sym _ _ H1) in H0;\n discriminate.\nclear l1; intros a1 l1 l2 H1 H2.\ncase (split_one_in_ex a1 l2); auto.\napply permutation_in with (1 := H2); auto with datatypes.\nintros x H0.\napply in_flat_map with (b := (a1, x)); auto.\napply in_map; simpl in |- *.\napply H; auto.\napply eq_add_S.\napply trans_equal with (1 := H1).\nchange (length l2 = length (a1 :: x)) in |- *.\napply permutation_length; auto.\napply permutation_sym; apply split_one_permutation; auto.\napply permutation_inv with (a := a1).\napply permutation_trans with (1 := H2).\napply permutation_sym; apply split_one_permutation; auto.\nQed.\n \nTheorem permutation_all_permutations :\n forall l1 l2 : list A, permutation l1 l2 -> In l1 (all_permutations l2).\nintros l1 l2 H; unfold all_permutations in |- *;\n apply permutation_all_permutations_aux; auto.\nQed.\n\n(************************************** \n   Permutation is decidable\n   **************************************)\n \nDefinition permutation_dec :\n  (forall a b : A, {a = b} + {a <> b}) ->\n  forall l1 l2 : list A, {permutation l1 l2} + {~ permutation l1 l2}.\nintros H l1 l2.\ncase (In_dec (list_eq_dec H) l1 (all_permutations l2)).\nintros i; left; apply all_permutations_permutation; auto.\nintros i; right; contradict i; apply permutation_all_permutations; auto.\nDefined.\n \nEnd permutation.\n\n(************************************** \n   Hints\n   **************************************)\n\nHint Constructors permutation.\nHint Resolve permutation_refl.\nHint Resolve permutation_app_comp.\nHint Resolve permutation_app_swap.\n\n(************************************** \n   Implicits\n   **************************************)\n\nImplicit Arguments permutation [A].\nImplicit Arguments split_one [A].\nImplicit Arguments all_permutations [A].\nImplicit Arguments permutation_dec [A].\n\n(************************************** \n   Permutation is compatible with map\n   **************************************)\n \nTheorem permutation_map :\n forall (A B : Set) (f : A -> B) l1 l2,\n permutation l1 l2 -> permutation (map f l1) (map f l2).\nintros A B f l1 l2 H; elim H; simpl in |- *; auto.\nintros l0 l3 l4 H0 H1 H2 H3; apply permutation_trans with (2 := H3); auto.\nQed.\nHint Resolve permutation_map.\n \n(************************************** \n  Permutation  of a map can be inverted\n  *************************************)\n\nLet permutation_map_ex_aux :\n  forall (A B : Set) (f : A -> B) l1 l2 l3,\n  permutation l1 l2 ->\n  l1 = map f l3 -> exists l4, permutation l4 l3 /\\ l2 = map f l4.\nintros A1 B1 f l1 l2 l3 H; generalize l3; elim H; clear H l1 l2 l3.\nintros l3; case l3; simpl in |- *; auto.\nintros H; exists (nil (A:=A1)); auto.\nintros; discriminate.\nintros a0 l1 l2 H H0 l3; case l3; simpl in |- *; auto.\nintros; discriminate.\nintros a1 l H1; case (H0 l); auto.\ninjection H1; auto.\nintros l5 (H2, H3); exists (a1 :: l5); split; simpl in |- *; auto.\ninjection H1; intros; subst; auto.\nintros a0 b l l3; case l3.\nintros; discriminate.\nintros a1 l0; case l0; simpl in |- *.\nintros; discriminate.\nintros a2 l1 H; exists (a2 :: a1 :: l1); split; simpl in |- *; auto.\ninjection H; intros; subst; auto.\nintros l1 l2 l3 H H0 H1 H2 l0 H3.\ncase H0 with (1 := H3); auto.\nintros l4 (HH1, HH2).\ncase H2 with (1 := HH2); auto.\nintros l5 (HH3, HH4); exists l5; split; auto.\napply permutation_trans with (1 := HH3); auto.\nQed.\n \nTheorem permutation_map_ex :\n forall (A B : Set) (f : A -> B) l1 l2,\n permutation (map f l1) l2 ->\n exists l3, permutation l3 l1 /\\ l2 = map f l3.\nintros A0 B f l1 l2 H; apply permutation_map_ex_aux with (l1 := map f l1);\n auto.\nQed.\n\n(************************************** \n   Permutation is compatible with flat_map\n **************************************)\n \nTheorem permutation_flat_map :\n forall (A B : Set) (f : A -> list B) l1 l2,\n permutation l1 l2 -> permutation (flat_map f l1) (flat_map f l2).\nintros A B f l1 l2 H; elim H; simpl in |- *; auto.\nintros a b l; auto.\nrepeat rewrite <- app_ass.\napply permutation_app_comp; auto.\nintros k3 l4 l5 H0 H1 H2 H3; apply permutation_trans with (1 := H1); auto.\nQed.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/coqprime/Coqprime/Permutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7319297751130373}}
{"text": "\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export poly.\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1. apply eq2. Qed.\n\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     oddb 3 = true ->\n     evenb 4 = true.\nProof.\n  intros Hn H3. rewrite <- H3. rewrite Hn. reflexivity. reflexivity.\nQed.\n\n\n(*symmetry : =項の 左辺と右辺の入れ替え。*)\nTheorem silly3_firsttry : forall (n : nat),\n     true = (n == 5) ->\n     (S (S n)) == 7 = true.\nProof.\n  intros n H1.   symmetry. simpl. apply H1.\nQed.\n\nTheorem rev_doble : forall (l : list nat),\n  rev (rev l) = l.\nProof.\n  intros l. induction l.\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl. reflexivity.\nQed.\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros l1 l2 H. rewrite H. rewrite rev_doble. reflexivity.\nQed.\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity. Qed.\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  apply trans_eq with [c;d].\n  apply eq1. apply eq2. Qed.\n\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros n m o p H1 H2. rewrite H2. apply H1. \nQed.\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H1.\n  assert (H2: n = pred (S n)). { reflexivity. }\n  rewrite H2. rewrite H1. reflexivity.\nQed.\n\n\nTheorem S_injective' : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.  injection H. intros Hnm. apply Hnm.\nQed.\n\n\nTheorem injection_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H.\n  injection H. intros H1 H2.\n  rewrite H1. rewrite H2. reflexivity.\nQed.\n\nExample injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros X x y z l j H1 H2. injection H2. intros Hin. symmetry. apply H.\nQed.\n\nTheorem eqb_0_l : forall n,\n   0 == n = true -> n = 0.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  -\n    intros H. reflexivity.\n  -\n    simpl.  intros H. discriminate H.\nQed.\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra. Qed.\n \nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. discriminate contra. Qed.\n\nExample discriminate_ex3 :\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] ->\n    x = z.\nProof.\n  intros X x y z l j H. discriminate H. Qed.\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq. reflexivity. Qed.\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     (S n) == (S m) = b ->\n     n == m = b.\nProof.\n  intros n m b H. simpl in H. apply H. Qed.\n\nTheorem silly3' : forall (n : nat),\n  (n == 5 = true -> (S (S n)) == 7 = true) ->\n  true = (n == 5) ->\n  true = ((S (S n)) == 7).\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H. Qed.\n\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - simpl. intros m eq. destruct m as [| m'] eqn:E.\n    + reflexivity.\n    + discriminate eq.\n\n  - simpl. intros m eq. destruct m as [| m'] eqn:E.\n    + simpl. discriminate eq.\n    + apply f_equal.\n      apply IHn'. injection eq as goal. apply goal. Qed.\n\nTheorem succ_eq : forall n m,\n  S n = S m -> n = m.\nProof.\n  intros [] []. reflexivity. discriminate. discriminate.\n  intros H. injection H as goal. rewrite goal. reflexivity.\nQed.\n\nTheorem eqb_true : forall n m,\n    n == m = true -> n = m.\nProof.\n  intros n . induction n.\n  - simpl. intros [].   reflexivity. discriminate.\n  - intros m . destruct m.\n    + discriminate.\n    + simpl. intros H. apply IHn in H. rewrite H.\n      reflexivity.\nQed.\n\nTheorem eqb_id_true : forall x y,\n  eqb_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply eqb_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros.\n  generalize dependent n.\n  induction l as [| h t IH].\n  - intros.\n    rewrite <- H.\n    reflexivity.\n  - intros.\n    rewrite <- H.\n    simpl.\n    apply IH.\n    reflexivity.\nQed.\n\nDefinition square n := n * n.\n\n\nDefinition foo (x: nat) := 5.\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\nDefinition sillyfun (n : nat) : bool :=\n  if n == 3 then false\n  else if n == 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (n == 3) eqn:E1.\n    - reflexivity.\n    - destruct (n == 5) eqn:E2.\n      + reflexivity.\n      + reflexivity. Qed.\n\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x, y) :: t =>\n      match split t with\n      | (lx, ly) => (x :: lx, y :: ly)\n      end\n  end.\n\nTheorem tail_eq: forall (X: Type) (h: X) (l1 l2: list X),\n    l1 = l2 -> h :: l1 = h :: l2.\nProof.\n  intros. apply f_equal. apply H.\nQed.\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l. induction l as [| h t IH].\n   - intros. simpl in H. inversion H. reflexivity. \n   - intros l1 l2 H. inversion H. destruct h. \n     destruct (split t). inversion H1.     simpl.\n     apply tail_eq. apply IH. reflexivity.\nQed.\n\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n == 3 then true\n  else if n == 5 then true\n  else false.\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n == 3) eqn:Heqe3.\n    - apply eqb_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - destruct (n == 5) eqn:Heqe5.\n        +\n          apply eqb_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + discriminate eq. Qed.\n\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f []. \n   destruct (f true) eqn:fT. \n     - rewrite fT. rewrite fT. reflexivity.\n     -  destruct (f false) eqn: fF.\n        + rewrite fT. reflexivity.\n        + rewrite fF. reflexivity.\n     - destruct (f false) eqn:fF.\n       + destruct (f true ) eqn:fT. rewrite fT. reflexivity.\n        rewrite fF. reflexivity.\n       + rewrite fF. rewrite fF. reflexivity.\nQed.\n\nTheorem eqb_sym : forall (n m : nat),\n  (n == m) = (m == n).\nProof.\n  intros n. induction n.\n    - intros. induction m. + reflexivity. + reflexivity.\n    - induction m. + reflexivity. + simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem eqb_trans : forall n m p,\n  n == m = true ->\n  m == p = true ->\n  n == p = true.\nProof.\n   intros.  apply eqb_true in H. apply eqb_true in H0. induction H0. induction H. apply true_eq.\nQed.\n\n\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | nil => true\n  | h :: t => if (test h) then forallb test t else false\n  end.\n\nExample test_forallb_1 : forallb oddb [1;3;5;7;9] = true.\nProof. reflexivity. Qed.\n\nExample test_forallb_2 : forallb negb [false;false] = true.\nProof. reflexivity. Qed.\n\nExample test_forallb_3 : forallb evenb [0;2;4;5] = false.\nProof. reflexivity. Qed.\n\nExample test_forallb_4 : forallb (eqb 5) [] = true.\nProof. reflexivity. Qed.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | nil => false\n  | h :: t => if (test h) then true else existsb test t\n  end.\n\nExample test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\n\nExample test_existsb_2 : existsb (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\n\nExample test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\n\nExample test_existsb_4 : existsb evenb [] = false.\nProof. reflexivity. Qed.\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=\n   negb (forallb (fun x => negb (test x)) l) .\n\nTheorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),\n  existsb test l = existsb' test l.\nProof.\n  intros. unfold existsb'. unfold existsb. induction l. - simpl. reflexivity.\n  - simpl. destruct (test x). \n     + simpl. reflexivity.\n     + simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n m. rewrite <- double_plus. rewrite <- double_plus. Search double. apply double_injective.\nQed.\n\n(*-------------------------------*)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  intros.\n  generalize dependent lf.\n  induction l as [| h t IH].\n  - intros.\n    simpl in H.\n    inversion H.\n  - intros.\n    generalize dependent H.\n    destruct lf as [| hf tf].\n    + simpl.\n      intros.\n      destruct (test h) eqn:testH.\n      * inversion H.\n        rewrite -> H1 in testH.\n        apply testH.\n      * apply IH in H.\n        apply H.\n    + simpl.\n      intros.\n      destruct (test h) eqn:testH.\n      * inversion H.\n        rewrite -> H1 in testH.\n        apply testH.\n      * apply IH in H.\n        apply H.\nQed.\n\n\n", "meta": {"author": "NeM-T", "repo": "sfc", "sha": "e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e", "save_path": "github-repos/coq/NeM-T-sfc", "path": "github-repos/coq/NeM-T-sfc/sfc-e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e/practice/Coq/SF/1st/tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7319297730121977}}
{"text": "From mathcomp Require Export ssreflect.\nRequire Export Classical.\n\n\n\n\nDefinition set T := T -> Prop.\n\nDefinition In {T : Type} (x : T)(X : set T) := X x. \nNotation \"x ∈ X\" := (@In _ x X )(at level 60).\n\n\nDefinition setU {T : Type} (A B : set T) : set T := \n    fun x => x ∈ A \\/ x ∈ B .\nDefinition setI {T : Type} (A B : set T) : set T := \n    fun x => x ∈ A /\\ x ∈ B.\nDefinition subset {T : Type} (A B : set T) : Prop := \n    forall x, x ∈ A -> x ∈ B.\nDefinition setD {T : Type} (A B : set T) : set T \n    := fun x => x ∈ A /\\ ~ x ∈ B.\nDefinition setC {T : Type} (A : set T) : set T \n    := fun x => ~ x ∈ A.\nDefinition set0 {T : Type} : set T := \n    fun _ : T => False.\n\n\n\nNotation \"A ∩ B\" := (@setI _ A B)(at level 40).\nNotation \"A ∪ B\" := (@setU _ A B)(at level 40).\nNotation \"A ⊂ B\" := (@subset _ A B)(at level 30).\nNotation \"A // B\" := (@setD _ A B)(at level 40).\nNotation \"¬ A\" := (@setC _ A)(at level 40).\nNotation \"∅\" := set0.\n\nAxiom extension : forall {T : Type} (A B : set T),\n    A ⊂ B /\\ B ⊂ A -> A = B.\n\n\n\nSection SetsFacts.\n\nContext  {T : Type}.\n\n\nTheorem setCU (A B : set T):\n    ¬ (A ∪ B) = ¬ A ∩ ¬ B.\nProof.\n    apply extension; split => x Hx.\n    +   split => F; apply Hx; [left|right] => //.\n    +   move : Hx => [Ha_ Hb_].\n        move => [Ha|Hb]; [apply Ha_ | apply Hb_] => //.\nQed.\n\nTheorem setCI (A B : set T):\n    ¬ (A ∩ B) = ¬ A ∪ ¬ B.\nProof.\n    apply extension; split => x Hx.\n    +   apply NNPP => F.\n        rewrite /setC /setU /In /= in F.\n        move /not_or_and : F => [/NNPP HA /NNPP NB ].\n        apply Hx; split => //.\n    +   move => [HA HB].\n        move : Hx => [H|H]; apply H => //.\nQed.        ", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "RegLang", "sha": "d13e8f1ace07bf0e29a0915964e5de33a52a63c7", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-RegLang", "path": "github-repos/coq/gaxiiiiiiiiiiii-RegLang/RegLang-d13e8f1ace07bf0e29a0915964e5de33a52a63c7/Sets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.8031737869342624, "lm_q1q2_score": 0.7318356602050639}}
{"text": "Add LoadPath \"bezier-functions\".\n\nRequire Import polynomial.\nRequire Import auxiliary.\nRequire Import QArith.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.RelationClasses.\n\nLemma bezier_curve_polynomial_symm_fstdegree : \n  forall (P0 P1 : point) (q : Q),\n      calc_bezier_polynomial (P0 :: [P1]) q == calc_bezier_polynomial (rev (P0 :: [P1])) (1 - q).\nProof.\n  intros P0 P1 q.\n  unfold calc_bezier_polynomial. unfold rev. simpl.\n  unfold calc_fact_div. unfold minus_1_sgn. unfold inject_Z. simpl.\n  destruct P0 as [x0 y0]. destruct P1 as [x1 y1].\n  unfold \"==\". simpl. split.\n  { ring. }\n  { ring. }\nQed.\n\n", "meta": {"author": "tancredosouza", "repo": "TAES_bezier", "sha": "0f02a01996c55e6394ec312d7e902c12bc0e9d56", "save_path": "github-repos/coq/tancredosouza-TAES_bezier", "path": "github-repos/coq/tancredosouza-TAES_bezier/TAES_bezier-0f02a01996c55e6394ec312d7e902c12bc0e9d56/properties/fst_order_symm/fst_order_symm_polynomial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7318303696791556}}
{"text": "Add LoadPath \"MyAlgebraicStructure\" as MyAlgebraicStructure.\nAdd LoadPath \"BasicProperty\" as BasicProperty.\nAdd LoadPath \"Tools\" as Tools.\n\nFrom mathcomp Require Import ssreflect.\nRequire Import Classical.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import MyAlgebraicStructure.MyField.\nRequire Import BasicProperty.MappingProperty.\n\nSection VectorSpace.\n\nRecord VectorSpace (F : Field) : Type := mkVectorSpace\n{\nVT   : Type;\nVO : VT;\nVadd : VT -> VT -> VT;\nVmul : (FT F) -> VT -> VT;\nVopp : VT -> VT;\nVadd_comm : forall (x y : VT), (Vadd x y) = (Vadd y x);\nVadd_assoc : forall (x y z : VT), (Vadd (Vadd x y) z) = (Vadd x (Vadd y z));\nVadd_O_l : forall x : VT, (Vadd VO x) = x;\nVadd_opp_r : forall x : VT, (Vadd x (Vopp x)) = VO;\nVmul_add_distr_l : forall (x : FT F) (y z : VT), (Vmul x (Vadd y z)) = (Vadd (Vmul x y) (Vmul x z));\nVmul_add_distr_r : forall (x y : FT F) (z : VT), (Vmul (Fadd F x y) z) = (Vadd (Vmul x z) (Vmul y z));\nVmul_assoc : forall (x y : FT F) (z : VT), (Vmul x (Vmul y z)) = (Vmul (Fmul F x y) z);\nVmul_I_l : forall x : VT, (Vmul (FI F) x) = x;\n}.\n\nLemma Vadd_O_r : forall (F : Field) (v : VectorSpace F) (x : VT F v), (Vadd F v x (VO F v)) = x.\nProof.\nmove=> F v x.\nrewrite (Vadd_comm F v x (VO F v)).\napply (Vadd_O_l F v x).\nQed.\n\nLemma Vadd_ne : forall (F : Field) (v : VectorSpace F) (x : VT F v), (Vadd F v x (VO F v)) = x /\\ (Vadd F v (VO F v) x) = x.\nProof.\nmove=> F v x.\napply conj.\napply (Vadd_O_r F v x).\napply (Vadd_O_l F v x).\nQed.\n\nLemma Vadd_opp_l : forall (F : Field) (v : VectorSpace F) (x : VT F v), (Vadd F v (Vopp F v x) x) = (VO F v).\nProof.\nmove=> F v x.\nrewrite (Vadd_comm F v (Vopp F v x) x).\napply (Vadd_opp_r F v x).\nQed.\n\nLemma Vadd_opp_r_uniq : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vadd F v x y) = (VO F v) -> y = (Vopp F v x).\nProof.\nmove=> F v x y H1.\nsuff: (Vadd F v (Vopp F v x) (Vadd F v x y)) = (Vadd F v (Vopp F v x) (VO F v)).\nmove=> H2.\nrewrite - (Vadd_O_r F v (Vopp F v x)).\nrewrite - H2.\nrewrite - (Vadd_assoc F v (Vopp F v x) x y).\nrewrite (Vadd_opp_l F v x).\nrewrite (Vadd_O_l F v y).\nby [].\nrewrite H1.\nby [].\nQed.\n\nLemma Vadd_eq_compat_l : forall (F : Field) (v : VectorSpace F) (x y z : VT F v), y = z -> (Vadd F v x y) = (Vadd F v x z).\nProof.\nmove=> F v x y z H1.\nrewrite H1.\nby [].\nQed.\n\nLemma Vadd_eq_compat_r : forall (F : Field) (v : VectorSpace F) (x y z : VT F v), y = z -> (Vadd F v y x) = (Vadd F v z x).\nProof.\nmove=> F v x y z H1.\nrewrite H1.\nby [].\nQed.\n\nLemma Vadd_eq_reg_l : forall (F : Field) (v : VectorSpace F) (x y z : VT F v), (Vadd F v x y) = (Vadd F v x z) -> y = z.\nProof.\nmove=> F v x y z H1.\nrewrite - (Vadd_O_l F v y).\nrewrite - (Vadd_O_l F v z).\nrewrite - (Vadd_opp_l F v x).\nrewrite (Vadd_assoc F v (Vopp F v x) x y).\nrewrite (Vadd_assoc F v (Vopp F v x) x z).\napply (Vadd_eq_compat_l F v (Vopp F v x) (Vadd F v x y) (Vadd F v x z)).\nby [].\nQed.\n\nLemma Vadd_eq_reg_r : forall (F : Field) (v : VectorSpace F) (x y z : VT F v), (Vadd F v y x) = (Vadd F v z x) -> y = z.\nProof.\nmove=> F v x y z H1.\nrewrite - (Vadd_O_r F v y).\nrewrite - (Vadd_O_r F v z).\nrewrite - (Vadd_opp_r F v x).\nrewrite - (Vadd_assoc F v y x (Vopp F v x)).\nrewrite - (Vadd_assoc F v z x (Vopp F v x)).\napply (Vadd_eq_compat_r F v (Vopp F v x) (Vadd F v y x) (Vadd F v z x)).\nby [].\nQed.\n\nLemma Vadd_O_r_uniq : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vadd F v x y) = x -> y = (VO F v).\nProof.\nmove=> F v x y H1.\nrewrite - (Vadd_O_l F v y).\nrewrite - (Vadd_opp_l F v x).\nrewrite (Vadd_assoc F v (Vopp F v x) x y).\nrewrite H1.\nby [].\nQed.\n\nLemma Vmul_O_r : forall (F : Field) (v : VectorSpace F) (x : FT F), (Vmul F v x (VO F v)) = (VO F v).\nProof.\nmove=> F v x.\napply (Vadd_O_r_uniq F v (Vmul F v x (VO F v)) (Vmul F v x (VO F v))).\nrewrite - (Vmul_add_distr_l F v x (VO F v) (VO F v)).\nrewrite (Vadd_O_l F v (VO F v)).\nby [].\nQed.\n\nLemma Vmul_O_l : forall (F : Field) (v : VectorSpace F) (x : VT F v), (Vmul F v (FO F) x) = (VO F v).\nProof.\nmove=> F v x.\napply (Vadd_O_r_uniq F v (Vmul F v (FO F) x) (Vmul F v (FO F) x)).\nrewrite - (Vmul_add_distr_r F v (FO F) (FO F) x).\nrewrite (Fadd_O_l F (FO F)).\nby [].\nQed.\n\nLemma Vmul_eq_compat_l : forall (F : Field) (v : VectorSpace F) (x : FT F) (y z : VT F v), y = z -> (Vmul F v x y) = (Vmul F v x z).\nProof.\nmove=> F v x y z H1.\nrewrite H1.\nby [].\nQed.\n\nLemma Vmul_eq_compat_r : forall (F : Field) (v : VectorSpace F) (x : VT F v) (y z : FT F), y = z -> (Vmul F v y x) = (Vmul F v z x).\nProof.\nmove=> F v x y z H1.\nrewrite H1.\nby [].\nQed.\n\nLemma Vmul_eq_reg_l : forall (F : Field) (v : VectorSpace F) (x : FT F) (y z : VT F v), (Vmul F v x y) = (Vmul F v x z) -> x <> (FO F) -> y = z.\nProof.\nmove=> F v x y z H1 H2.\nrewrite - (Vmul_I_l F v y).\nrewrite - (Vmul_I_l F v z).\nrewrite - (Finv_l F x H2).\nrewrite - (Vmul_assoc F v (Finv F x) x y).\nrewrite - (Vmul_assoc F v (Finv F x) x z).\nrewrite H1.\nby [].\nQed.\n\nLemma Vmul_eq_reg_r : forall (F : Field) (v : VectorSpace F) (x : VT F v) (y z : FT F), (Vmul F v y x) = (Vmul F v z x) -> x <> (VO F v) -> y = z.\nProof.\nmove=> F v x y z H1 H2.\napply NNPP.\nmove=> H3.\napply H2.\nrewrite - (Vmul_I_l F v x).\nrewrite - (Finv_l F (Fadd F y (Fopp F z))).\nrewrite - (Vmul_assoc F v (Finv F (Fadd F y (Fopp F z))) (Fadd F y (Fopp F z)) x).\nsuff: ((Vmul F v (Fadd F y (Fopp F z)) x) = VO F v).\nmove=> H4.\nrewrite H4.\napply (Vmul_O_r F v (Finv F (Fadd F y (Fopp F z)))).\napply (Vadd_eq_reg_r F v (Vmul F v z x) (Vmul F v (Fadd F y (Fopp F z)) x) (VO F v)).\nrewrite (Vadd_O_l F v (Vmul F v z x)).\nrewrite (Vmul_add_distr_r F v y (Fopp F z) x).\nrewrite (Vadd_assoc F v (Vmul F v y x) (Vmul F v (Fopp F z) x) (Vmul F v z x)).\nrewrite - (Vmul_add_distr_r F v (Fopp F z) z x).\nrewrite (Fadd_opp_l F z).\nrewrite (Vmul_O_l F v x).\nrewrite H1.\napply (Vadd_O_r F v (Vmul F v z x)).\nmove=> H4.\napply H3.\napply (Fminus_diag_uniq F y z H4).\nQed.\n\nLemma Vmul_integral : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), (Vmul F v x y) = (VO F v) -> x = (FO F) \\/ y = (VO F v).\nProof.\nmove=> F v x y H1.\napply (NNPP (x = FO F \\/ y = VO F v)).\nmove=> H2.\napply H2.\nright.\napply (Vmul_eq_reg_l F v x y (VO F v)).\nrewrite H1.\nrewrite (Vmul_O_r F v x).\nby [].\nmove=> H3.\napply H2.\nleft.\napply H3.\nQed.\n\nLemma Vmul_eq_O_compat : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), (x = (FO F) \\/ y = (VO F v)) -> (Vmul F v x y) = (VO F v).\nProof.\nmove=> F v x y H1.\ncase H1.\nmove=> H2.\nrewrite H2.\napply (Vmul_O_l F v y).\nmove=> H2.\nrewrite H2.\napply (Vmul_O_r F v x).\nQed.\n\nLemma Vmul_eq_O_compat_r : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), x = (FO F) -> (Vmul F v x y) = (VO F v).\nProof.\nmove=> F v x y H1.\nrewrite H1.\napply (Vmul_O_l F v y).\nQed.\n\nLemma Vmul_eq_O_compat_l : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), y = (VO F v) -> (Vmul F v x y) = (VO F v).\nProof.\nmove=> F v x y H1.\nrewrite H1.\napply (Vmul_O_r F v x).\nQed.\n\nLemma Vmul_neq_O_reg : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), (Vmul F v x y) <> (VO F v) -> x <> (FO F) /\\ y <> (VO F v).\nProof.\nmove=> F v x y H1.\napply conj.\nmove=> H2.\napply H1.\nrewrite H2.\napply (Vmul_O_l F v y).\nmove=> H2.\napply H1.\nrewrite H2.\napply (Vmul_O_r F v x).\nQed.\n\nLemma Vmul_integral_contrapositive : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), x <> (FO F) /\\ y <> (VO F v) -> (Vmul F v x y) <> (VO F v).\nProof.\nmove=> F v x y H1 H2.\napply (proj1 H1).\napply (Vmul_eq_reg_r F v y x (FO F)).\nrewrite (Vmul_O_l F v y).\napply H2.\napply (proj2 H1).\nQed.\n\nLemma Vmul_integral_contrapositive_currified : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), x <> (FO F) -> y <> (VO F v) -> (Vmul F v x y) <> (VO F v).\nProof.\nmove=> F v x y H1 H2 H3.\napply H1.\napply (Vmul_eq_reg_r F v y x (FO F)).\nrewrite (Vmul_O_l F v y).\napply H3.\napply H2.\nQed.\n\nLemma Vopp_eq_compat : forall (F : Field) (v : VectorSpace F) (x y : VT F v), x = y -> (Vopp F v x) = (Vopp F v y).\nProof.\nmove=> F v x y H1.\nrewrite H1.\nby [].\nQed.\n\nLemma Vopp_O : forall (F : Field) (v : VectorSpace F), (Vopp F v (VO F v)) = (VO F v).\nProof.\nmove=> F v.\napply (Vadd_O_r_uniq F v (VO F v) (Vopp F v (VO F v))).\napply (Vadd_opp_r F v (VO F v)).\nQed.\n\nLemma Vopp_eq_O_compat : forall (F : Field) (v : VectorSpace F) (x : VT F v), x = (VO F v) -> (Vopp F v x) = (VO F v).\nProof.\nmove=> F v x H1.\nrewrite H1.\napply (Vopp_O F v).\nQed.\n\nLemma Vopp_involutive : forall (F : Field) (v : VectorSpace F) (x : VT F v), (Vopp F v (Vopp F v x)) = x.\nProof.\nmove=> F v x.\nsuff: x = Vopp F v (Vopp F v x).\nmove=> H1.\nrewrite{2} H1.\nby [].\napply (Vadd_opp_r_uniq F v (Vopp F v x)).\napply (Vadd_opp_l F v x).\nQed.\n\nLemma Vopp_neq_O_compat : forall (F : Field) (v : VectorSpace F) (x : VT F v), x <> (VO F v) -> (Vopp F v x) <> (VO F v).\nProof.\nmove=> F v x H1 H2.\napply H1.\nrewrite - (Vopp_involutive F v x).\napply (Vopp_eq_O_compat F v (Vopp F v x) H2).\nQed.\n\nLemma Vopp_add_distr : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vopp F v (Vadd F v x y)) = (Vadd F v (Vopp F v x) (Vopp F v y)).\nProof.\nmove=> F v x y.\nsuff: Vadd F v (Vopp F v x) (Vopp F v y) = Vopp F v (Vadd F v x y).\nmove=> H1.\nrewrite H1.\nby [].\napply (Vadd_opp_r_uniq F v (Vadd F v x y)).\nrewrite (Vadd_comm F v x y).\nrewrite - (Vadd_assoc F v (Vadd F v y x) (Vopp F v x) (Vopp F v y)).\nrewrite (Vadd_assoc F v y x (Vopp F v x)).\nrewrite (Vadd_opp_r F v x).\nrewrite (Vadd_O_r F v y).\napply (Vadd_opp_r F v y).\nQed.\n\nLemma Vopp_mul_distr_l : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), (Vopp F v (Vmul F v x y)) = (Vmul F v (Fopp F x) y).\nProof.\nmove=> F v x y.\nsuff: Vmul F v (Fopp F x) y = Vopp F v (Vmul F v x y).\nmove=> H1.\nrewrite H1.\nby [].\napply (Vadd_opp_r_uniq F v (Vmul F v x y)).\nrewrite - (Vmul_add_distr_r F v x (Fopp F x) y).\nrewrite (Fadd_opp_r F x).\napply (Vmul_O_l F v y).\nQed.\n\nLemma Vopp_mul_distr_l_reverse : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), (Vmul F v (Fopp F x) y) = (Vopp F v (Vmul F v x y)).\nProof.\nmove=> F v x y.\nrewrite (Vopp_mul_distr_l F v x y).\nreflexivity.\nQed.\n\nLemma Vopp_mul_distr_r : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), (Vopp F v (Vmul F v x y)) = (Vmul F v x (Vopp F v y)).\nProof.\nmove=> F v x y.\nsuff: Vmul F v x (Vopp F v y) = Vopp F v (Vmul F v x y).\nmove=> H1.\nrewrite H1.\nby [].\napply (Vadd_opp_r_uniq F v (Vmul F v x y)).\nrewrite - (Vmul_add_distr_l F v x y (Vopp F v y)).\nrewrite (Vadd_opp_r F v y).\napply (Vmul_O_r F v x).\nQed.\n\nLemma Vopp_mul_distr_r_reverse : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), (Vmul F v x (Vopp F v y)) = (Vopp F v (Vmul F v x y)).\nProof.\nmove=> F v x y.\nrewrite (Vopp_mul_distr_r F v x y).\nreflexivity.\nQed.\n\nLemma Vmul_opp_opp : forall (F : Field) (v : VectorSpace F) (x : FT F) (y : VT F v), (Vmul F v (Fopp F x) (Vopp F v y)) = (Vmul F v x y).\nProof.\nmove=> F v x y.\nrewrite (Vopp_mul_distr_l_reverse F v x (Vopp F v y)).\nrewrite (Vopp_mul_distr_r_reverse F v x y).\napply (Vopp_involutive F v (Vmul F v x y)).\nQed.\n\nLemma Vminus_O_r : forall (F : Field) (v : VectorSpace F) (x : VT F v), (Vadd F v x (Vopp F v (VO F v))) = x.\nProof.\nmove=> F v x.\nrewrite (Vopp_O F v).\napply (Vadd_O_r F v x).\nQed.\n\nLemma Vminus_O_l : forall (F : Field) (v : VectorSpace F) (x : VT F v), (Vadd F v (VO F v) (Vopp F v x)) = (Vopp F v x).\nProof.\nmove=> F v x.\napply (Vadd_O_l F v (Vopp F v x)).\nQed.\n\nLemma Vopp_minus_distr : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vopp F v (Vadd F v x (Vopp F v y))) = (Vadd F v y (Vopp F v x)).\nProof.\nmove=> F v x y.\nrewrite (Vopp_add_distr F v x (Vopp F v y)).\nrewrite (Vopp_involutive F v y).\napply (Vadd_comm F v (Vopp F v x) y).\nQed.\n\nLemma Vopp_minus_distr' : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vopp F v (Vadd F v y (Vopp F v x))) = (Vadd F v x (Vopp F v y)).\nProof.\nmove=> F v x y.\nrewrite (Vopp_add_distr F v y (Vopp F v x)).\nrewrite (Vopp_involutive F v x).\napply (Vadd_comm F v (Vopp F v y) x).\nQed.\n\nLemma Vminus_diag_eq : forall (F : Field) (v : VectorSpace F) (x y : VT F v), x = y -> (Vadd F v x (Vopp F v y)) = (VO F v).\nProof.\nmove=> F v x y H1.\nrewrite H1.\napply (Vadd_opp_r F v y).\nQed.\n\nLemma Vminus_diag_uniq : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vadd F v x (Vopp F v y)) = (VO F v) -> x = y.\nProof.\nmove=> F v x y H1.\nrewrite<- (Vadd_O_r F v x).\nrewrite<- (Vadd_opp_l F v y).\nrewrite<- (Vadd_O_l F v y) at 3.\nrewrite<- (Vadd_assoc F v x (Vopp F v y) y).\nrewrite H1.\nreflexivity.\nQed.\n\nLemma Vminus_diag_uniq_sym : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vadd F v y (Vopp F v x)) = (VO F v) -> x = y.\nProof.\nmove=> F v x y H1.\nrewrite (Vminus_diag_uniq F v y x H1).\nreflexivity.\nQed.\n\nLemma Vadd_minus : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vadd F v x (Vadd F v y (Vopp F v x))) = y.\nProof.\nmove=> F v x y.\nrewrite (Vadd_comm F v y (Vopp F v x)).\nrewrite<- (Vadd_assoc F v x (Vopp F v x) y).\nrewrite (Vadd_opp_r F v x).\napply (Vadd_O_l F v y).\nQed.\n\nLemma Vminus_eq_contra : forall (F : Field) (v : VectorSpace F) (x y : VT F v), x <> y -> (Vadd F v x (Vopp F v y)) <> (VO F v).\nProof.\nmove=> F v x y H1 H2.\napply H1.\napply (Vminus_diag_uniq F v x y H2).\nQed.\n\nLemma Vminus_not_eq : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vadd F v x (Vopp F v y)) <> (VO F v) -> x <> y.\nProof.\nmove=> F v x y H1 H2.\napply H1.\napply (Vminus_diag_eq F v x y H2).\nQed.\n\nLemma Vminus_not_eq_right : forall (F : Field) (v : VectorSpace F) (x y : VT F v), (Vadd F v y (Vopp F v x)) <> (VO F v) -> x <> y.\nProof.\nmove=> F v x y H1 H2.\napply H1.\napply (Vminus_diag_eq F v y x).\nrewrite H2.\nreflexivity.\nQed.\n\nLemma Vmul_minus_distr_l : forall (F : Field) (v : VectorSpace F) (x : FT F) (y z : VT F v), (Vmul F v x (Vadd F v y (Vopp F v z))) = (Vadd F v (Vmul F v x y) (Vopp F v (Vmul F v x z))).\nProof.\nmove=> F v x y z.\nrewrite (Vmul_add_distr_l F v x y (Vopp F v z)).\nrewrite (Vopp_mul_distr_r F v x z).\nreflexivity.\nQed.\n\nDefinition IsomorphicVS (F : Field) (v1 v2 : VectorSpace F) (f : VT F v1 -> VT F v2) := Bijective f /\\ (forall (x y : VT F v1), f (Vadd F v1 x y) = Vadd F v2 (f x) (f y)) /\\ (forall (c : FT F) (x : VT F v1), f (Vmul F v1 c x) = Vmul F v2 c (f x)).\n\nLemma IsomorphicChainVS : forall (F : Field) (v1 v2 v3 : VectorSpace F) (f : VT F v1 -> VT F v2) (g : VT F v2 -> VT F v3), IsomorphicVS F v1 v2 f -> IsomorphicVS F v2 v3 g -> IsomorphicVS F v1 v3 (fun (x : VT F v1) => g (f x)).\nProof.\nmove=> F v1 v2 v3 f g H1 H2.\napply conj.\napply (BijChain (VT F v1) (VT F v2) (VT F v3) f g (proj1 H1) (proj1 H2)).\napply conj.\nmove=> x y.\nrewrite ((proj1 (proj2 H1)) x y).\napply ((proj1 (proj2 H2)) (f x) (f y)).\nmove=> c x.\nrewrite (proj2 (proj2 H1) c x).\napply (proj2 (proj2 H2) c (f x)).\nQed.\n\nLemma IsomorphicInvVS : forall (F : Field) (v1 v2 : VectorSpace F) (f : VT F v1 -> VT F v2) (g : VT F v2 -> VT F v1), IsomorphicVS F v1 v2 f -> (forall (x : VT F v1), g (f x) = x) /\\ (forall (y : VT F v2), f (g y) = y) -> IsomorphicVS F v2 v1 g.\nProof.\nmove=> F v1 v2 f g H1 H2.\napply conj.\nexists f.\napply conj.\napply (proj2 H2).\napply (proj1 H2).\napply conj.\nmove=> x y.\napply (BijInj (VT F v1) (VT F v2) f (proj1 H1) (g (Vadd F v2 x y)) (Vadd F v1 (g x) (g y))).\nrewrite (proj1 (proj2 H1) (g x) (g y)).\nrewrite (proj2 H2 x).\nrewrite (proj2 H2 y).\napply (proj2 H2 (Vadd F v2 x y)).\nmove=> c x.\napply (BijInj (VT F v1) (VT F v2) f (proj1 H1) (g (Vmul F v2 c x)) (Vmul F v1 c (g x))).\nrewrite (proj2 (proj2 H1) c (g x)).\nrewrite (proj2 H2 x).\napply (proj2 H2 (Vmul F v2 c x)).\nQed.\n\nDefinition Fn (F : Field) (N : nat) := ({m : nat | m < N} -> FT F).\n\nDefinition Fnadd (F : Field) (N : nat) := fun (f1 f2 : Fn F N) => (fun (n : {m : nat | m < N}) => Fadd F (f1 n) (f2 n)).\n\nDefinition Fnmul (F : Field) (N : nat) := fun (c : FT F) (f : Fn F N) => (fun (n : {m : nat | m < N}) => Fmul F c (f n)).\n\nDefinition Fnopp (F : Field) (N : nat) := fun (f : (Fn F N)) => (fun (n : {m : nat | m < N}) => Fopp F (f n)).\n\nDefinition Fnminus (F : Field) (N : nat) := fun (f1 f2 : (Fn F N)) => (Fnadd F N f1 (Fnopp F N f2)).\n\nDefinition FnO (F : Field) (N : nat) := (fun (n : {m : nat | m < N}) => FO F).\n\nLemma Fnadd_comm : forall (F : Field) (N : nat) (f1 f2 : Fn F N), (Fnadd F N f1 f2) = (Fnadd F N f2 f1).\nProof.\nmove=> F N f1 f2.\napply functional_extensionality.\nmove=> n.\napply (Fadd_comm F (f1 n) (f2 n)).\nQed.\n\nLemma Fnadd_assoc : forall (F : Field) (N : nat) (f1 f2 f3 : Fn F N), (Fnadd F N (Fnadd F N f1 f2) f3) = (Fnadd F N f1 (Fnadd F N f2 f3)).\nProof.\nmove=> F N f1 f2 f3.\napply functional_extensionality.\nmove=> n.\napply (Fadd_assoc F (f1 n) (f2 n) (f3 n)).\nQed.\n\nLemma Fnadd_O_l : forall (F : Field) (N : nat) (f : Fn F N), (Fnadd F N (FnO F N) f) = f.\nProof.\nmove=> F N f.\napply functional_extensionality.\nmove=> n.\napply (Fadd_O_l F (f n)).\nQed.\n\nLemma Fnadd_opp_r : forall (F : Field) (N : nat) (f : Fn F N), (Fnadd F N f (Fnopp F N f)) = (FnO F N).\nProof.\nmove=> F N f.\napply functional_extensionality.\nmove=> n.\napply (Fadd_opp_r F (f n)).\nQed.\n\nLemma Fnadd_distr_l : forall (F : Field) (N : nat) (c : FT F) (f1 f2 : Fn F N), (Fnmul F N c (Fnadd F N f1 f2)) = (Fnadd F N (Fnmul F N c f1) (Fnmul F N c f2)).\nProof.\nmove=> F N c f1 f2.\napply functional_extensionality.\nmove=> n.\napply (Fmul_add_distr_l F c (f1 n) (f2 n)).\nQed.\n\nLemma Fnadd_distr_r : forall (F : Field) (N : nat) (c1 c2 : FT F) (f : Fn F N), (Fnmul F N (Fadd F c1 c2) f) = (Fnadd F N (Fnmul F N c1 f) (Fnmul F N c2 f)).\nProof.\nmove=> F N c1 c2 f.\napply functional_extensionality.\nmove=> n.\napply (Fmul_add_distr_r F c1 c2 (f n)).\nQed.\n\nLemma Fnmul_assoc : forall (F : Field) (N : nat) (c1 c2 : FT F) (f : Fn F N), (Fnmul F N c1 (Fnmul F N c2 f)) = (Fnmul F N (Fmul F c1 c2) f).\nProof.\nmove=> F N c1 c2 f.\napply functional_extensionality.\nmove=> n.\nunfold Fnmul.\nrewrite (Fmul_assoc F c1 c2 (f n)).\nreflexivity.\nQed.\n\nLemma Fnmul_I_l : forall (F : Field) (N : nat) (f : Fn F N), (Fnmul F N (FI F) f) = f.\nProof.\nmove=> F N f.\napply functional_extensionality.\nmove=> n.\napply (Fmul_I_l F (f n)).\nQed.\n\nDefinition FnVS (F : Field) (N : nat) := mkVectorSpace F (Fn F N) (FnO F N) (Fnadd F N) (Fnmul F N) (Fnopp F N) (Fnadd_comm F N) (Fnadd_assoc F N) (Fnadd_O_l F N) (Fnadd_opp_r F N) (Fnadd_distr_l F N) (Fnadd_distr_r F N) (Fnmul_assoc F N) (Fnmul_I_l F N).\n\nDefinition FVS (F : Field) := mkVectorSpace F (FT F) (FO F) (Fadd F) (Fmul F) (Fopp F) (Fadd_comm F) (Fadd_assoc F) (Fadd_O_l F) (Fadd_opp_r F) (Fmul_add_distr_l F) (Fmul_add_distr_r F) (Fmul_assoc_reverse F) (Fmul_I_l F).\n\nEnd VectorSpace.\n", "meta": {"author": "itleigns", "repo": "CoqLibrary", "sha": "de210b755ab010e835e3777b9b47351972bbb577", "save_path": "github-repos/coq/itleigns-CoqLibrary", "path": "github-repos/coq/itleigns-CoqLibrary/CoqLibrary-de210b755ab010e835e3777b9b47351972bbb577/MyAlgebraicStructure/MyVectorSpace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7318303634180402}}
{"text": "Add LoadPath \"/Users/danielle/projects/software-foundations/chapter03\".\nRequire Import case.\nRequire Import exercise02.\n\nRequire Import Utf8.\n\nTheorem plus_swap: ∀ n m p: nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  assert (H: m + (n + p) = (m + n) + p).\n    Case \"Associative property\".\n    rewrite -> plus_assoc.\n    reflexivity.\n  rewrite -> H.\n  assert (H': m + n = n + m).\n    Case \"Commutative property\".\n    rewrite -> plus_comm.\n    reflexivity.\n  rewrite -> H'.\n  assert (H'': n + (m + p) = (n + m) + p).\n    Case \"Associative property\".\n    rewrite -> plus_assoc.\n    reflexivity.\n  rewrite -> H''.\n  reflexivity.\n  Qed.", "meta": {"author": "quephird", "repo": "software-foundations", "sha": "645d3d9c5ce3abe6e63935dc92658061dfd2a6b9", "save_path": "github-repos/coq/quephird-software-foundations", "path": "github-repos/coq/quephird-software-foundations/software-foundations-645d3d9c5ce3abe6e63935dc92658061dfd2a6b9/chapter03/exercise04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7317210392830223}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus x (plus y (Succ lf1)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj203_coqofml_M8tyna.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7317210251137981}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import collect_operator.\nRequire Import direct_product.\nRequire Import mapping.\nRequire Import mapping_morphism.\nRequire Import family_collection.\n\nInductive EquivalenceClass {U:Type} (R:Relation U) (a:U) : Collection U :=\n  definition_of_equivalence_class: forall x:U, EquivalenceRelation U R /\\ R a x -> x ∈ EquivalenceClass R a.\n(*\nInductive QuotientSet {U:Type} (R:Relation U) (X:Collection U) : Collection (Collection U) :=\n  definition_of_quotinet_set: forall (A:Collection U), (forall x:U, x ∈ X -> A ⊂ EquivalenceClass R x) -> A ∈ QuotientSet R X.\n *)\nDefinition QuotientSet (U:Type) (R:Relation U) (a:U) := PowerCollection (EquivalenceClass R a).\n\nDefinition EquivalenceClassByFunction {U V:Type} (f:U->V) (a:U) :=\n  EquivalenceClass (fun x y:U => f x = f y) a.\n\nSection EquivalenceClass.\n  Variable U V:Type.\n  Variable R:Relation U.\n\n  Theorem a_element_in_equivalence_class_of_it_element:\n    EquivalenceRelation U R ->\n    forall a:U, a ∈ EquivalenceClass R a.\n  Proof.\n    move => H a.\n    split.\n    split.\n    split.\n    apply H.\n    apply H.\n    apply H.\n    inversion H.\n    apply H0.\n  Qed.\n\n  Theorem equivalence_relation_element_in_equivalence_class_of_it_element:\n    EquivalenceRelation U R ->\n    forall a x:U, R a x -> x ∈ EquivalenceClass R a.\n  Proof.\n    move => H a x HR.\n    split.\n    split; assumption.\n  Qed.\n\n  Theorem element_in_equivalence_class_of_it_element_to_relation:\n    EquivalenceRelation U R ->\n    forall a x:U, x ∈ EquivalenceClass R a -> R a x.\n  Proof.\n    move => HR a x H.\n    inversion H.\n    inversion H0.\n    apply H3.\n  Qed.\n  \n  Theorem equivalence_relation_to_equivalence_class_eq:\n    EquivalenceRelation U R ->\n    forall a b:U, R a b -> EquivalenceClass R a = EquivalenceClass R b.\n  Proof.\n    move => H a b HR.\n    inversion H.\n    apply mutally_included_to_eq.\n    split => x H';[inversion H' as [x0 [HR' HRax]]|\n                   inversion H' as [x0 [HR' HRbx]]];\n             split;split.\n    apply H.\n    apply H1.\n    apply (H2 x a b).\n    apply H1.\n    trivial.\n    assumption.\n    apply H.\n    apply (H2 a b x).\n    apply HR.\n    assumption.\n  Qed.\n\n  Theorem equivalence_class_eq_to_equivalence_relation:\n    EquivalenceRelation U R ->\n    forall a b:U, EquivalenceClass R a = EquivalenceClass R b -> R a b.\n  Proof.\n    move => HR a b H.\n    apply mutally_included_iff_eq in H.\n    inversion H.\n    move: (H1 b) => H1b.\n    apply element_in_equivalence_class_of_it_element_to_relation.\n    apply HR.\n    apply H1b.\n    apply a_element_in_equivalence_class_of_it_element.\n    apply HR.\n  Qed.\n\n  Theorem equivalence_relation_iff_equivalence_class_eq:\n    EquivalenceRelation U R ->\n    forall a b:U,  R a b <-> EquivalenceClass R a = EquivalenceClass R b.\n  Proof.\n    move => HR a b.\n    rewrite /iff.\n    split;[apply equivalence_relation_to_equivalence_class_eq|\n           apply equivalence_class_eq_to_equivalence_relation];trivial.\n  Qed.\n\n  Theorem same_relation_to_intersection_of_equivalence_class_not_empty:\n    EquivalenceRelation U R ->\n    forall a b:U, R a b -> EquivalenceClass R a ∩ EquivalenceClass R b <> `Ø`.\n  Proof.\n    move => HR a b H.\n    apply exists_element_in_collection_to_not_empty_collection.\n    exists a.\n    split;[apply a_element_in_equivalence_class_of_it_element|\n           apply equivalence_relation_element_in_equivalence_class_of_it_element];trivial.\n    inversion HR.\n    apply H1.\n    assumption.\n  Qed.\n\n  Theorem intersection_of_equivalence_class_not_empty_to_same_relation:\n    EquivalenceRelation U R ->\n    forall a b:U, EquivalenceClass R a ∩ EquivalenceClass R b <> `Ø` -> R a b.\n  Proof.\n    move => HR a b H.\n    apply not_empty_collection_to_exists_element_in_collection in H.\n    inversion H as [x].\n    inversion H0.\n    apply element_in_equivalence_class_of_it_element_to_relation.\n    trivial.\n    suff: R a b.\n    apply equivalence_relation_element_in_equivalence_class_of_it_element.\n    trivial.\n    inversion HR.\n    apply: (H6 a x b).\n    apply element_in_equivalence_class_of_it_element_to_relation;trivial.\n    apply H5.\n    apply element_in_equivalence_class_of_it_element_to_relation;trivial.\n  Qed.\n\n  Theorem same_relation_iff_intersection_of_equivalence_class_not_empty:\n    EquivalenceRelation U R ->\n    forall a b:U, R a b <-> EquivalenceClass R a ∩ EquivalenceClass R b <> `Ø`.\n  Proof.\n    move => HR a b.\n    rewrite /iff.\n    split;[apply same_relation_to_intersection_of_equivalence_class_not_empty|\n           apply intersection_of_equivalence_class_not_empty_to_same_relation];trivial.\n  Qed.\n\n  Theorem result_value_same_to_equivalence_class_eq:\n    forall (f:U->V), forall a b:U,\n        f a = f b -> EquivalenceClassByFunction f a = EquivalenceClassByFunction f b.\n  Proof.\n    move => f a b H.\n    apply mutally_included_to_eq.\n    split => x H'.\n    inversion H'.\n    inversion H0.\n    split.\n    split.\n    apply H2.\n    rewrite -H3.\n    apply eq_sym.\n    trivial.\n    inversion H'.\n    inversion H0.\n    split.\n    split.\n    apply H2.\n    rewrite -H3.\n    assumption.\n  Qed.\n\nEnd EquivalenceClass.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/equivalence_class.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.731721019381049}}
{"text": "Welcome to Coq ciosx:/builds/workspace/coq-8.5pl3-macos,(detached from 2290dbb) (2290dbb9c95b63e693ced647731623e64297f5c8)\n\nCoq < Theorem plus_id_example : forall n m:nat, n = m -> n + n = m + m.\n1 subgoal\n  \n  ============================\n  forall n m : nat, n = m -> n + n = m + m\n\nplus_id_example < Proof.\n1 subgoal\n  \n  ============================\n  forall n m : nat, n = m -> n + n = m + m\n\nplus_id_example < intros n m.\n1 subgoal\n  \n  n, m : nat\n  ============================\n  n = m -> n + n = m + m\n\nplus_id_example < intros H.\n1 subgoal\n  \n  n, m : nat\n  H : n = m\n  ============================\n  n + n = m + m\n\nplus_id_example < rewrite -> H.\n1 subgoal\n  \n  n, m : nat\n  H : n = m\n  ============================\n  m + m = m + m\n\nplus_id_example < reflexivity.\nNo more subgoals.\n\nplus_id_example < Qed.\nProof.\nintros n m.\nintros H.\nrewrite H.\nreflexivity.\n\nQed.\nplus_id_example is defined\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/foundations/basics013.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7317056207782884}}
{"text": "Require Import List.\nSection Last.\n\nVariable A : Type.\nSet Implicit Arguments.\n\nInductive last (a:A) : list A -> Prop :=\n   | last_hd : last a (a :: nil)\n   | last_tl : forall (b:A) (l:list A), last a l -> last a (b :: l).\n\n\nHint Constructors last.\n\nFixpoint last_fun (l:list A) : option A :=\n  match l with\n  | nil => None (A:=A)\n  | a :: nil => Some a\n  | a :: l' => last_fun l'\n  end.\n\nTheorem last_fun_correct :\n forall (a:A) (l:list A), last a l -> last_fun l = Some a.\nProof.\n intros a l H; induction H as [| b l H IH].  \n - reflexivity. \n -   destruct l; simpl in *.\n    +  discriminate IH.\n    +  assumption. \nQed.\n\nTheorem last_fun_correct_R :\n forall (a:A) (l:list A), last_fun l = Some a -> last a l.\nProof.\n intros a l ; induction l as [ |a0 l0 IHl0]; simpl.\n - discriminate.\n -  destruct l0.\n   + injection 1;intros;subst a0;auto.\n   +  intro e; simpl; auto. \nQed.\n\nLemma last_fun_of_cons : forall (l:list A) (a:A), last_fun (a :: l) <> None.\nProof.\n intros l ; induction l as [| a l0].\n -  discriminate.\n - destruct l0;simpl;auto.   \n   + discriminate.\nQed.\n\nTheorem last_fun_correct3 :\n forall l:list A, last_fun l = None -> forall b:A, ~ last b l.\nProof.\n intro l; case l.\n - simpl; red; inversion 2.\n -  intros a l0 H;  case (last_fun_of_cons l0 a H). \nQed.\n\nEnd Last.\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/ch8_inductive_predicates/SRC/last.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7317056080778856}}
{"text": "Require Import List. Import ListNotations.\nSet Implicit Arguments.\n\n(** * Preuve assistée en Coq *)\n\n(** Premier exemple de théorème *)\nParameters (p q : Prop).\nTheorem th0 : p -> ((p -> q) -> q).\nProof.\n  exact (fun (x : p) (f : p -> q) => f x).\nQed.\n\nTheorem th : p -> (p -> q) -> q.\nProof. auto. Qed.\n\nPrint th.\n(* th = fun (H : p) (H0 : p -> q) => H0 H\n : p -> (p -> q) -> q *)\n\n(** Exemple d'utilisation de \"reflexivity\" *)\nLemma facile : 1 + 1 = 2.\nreflexivity.\nQed.\n\n(** Exemple d'utilisation de \"rewrite\" *)\nLemma exemple (pred : nat -> nat) (E : forall n : nat, 0 < n -> S (pred n) = n) (n : nat) :\n  S (pred (2 * (n + 1))) = 2 * n + 2.\nrewrite E.\nShow 1.\nShow 2.\nAbort.\n\n(** Exemple d'utilisation de \"apply\" *)\nLemma exemple (le_S : forall n m, n <= m -> n <= S m) (n : nat) :\n  n <= S (S n).\napply le_S.\nShow 1.\nAbort.\n\n(** Exemple d'utilisation de \"induction\" *)\nTheorem add_comm : forall n m : nat, n + m = m + n.\ninduction n.\nShow 1.\nShow 2.\nAbort.\n\n(** Exemple d'utilisation de \"destruct\" *)\nTheorem addn1_neq0 : forall n : nat, n + 1 <> 0.\ndestruct n.\nShow 1.\nShow 2.\nAbort.\n\n(** Exemple d'utilisation de \"simpl\" *)\nLemma example (n : nat) : 1 + n = n + 1.\nsimpl.\nAbort.\n\n(** ** Exemples et exercices autour des listes *)\nPrint rev.\nPrint \"++\".\n\nLemma app_nil :\n  forall T (l : list T), l = l ++ [].\nProof.\ninduction l.\n  { simpl.\n    reflexivity. }\nsimpl.\nrewrite <- IHl. (* utilise l'hypothèse d'induction *)\nreflexivity.\nQed.\n\nLemma app_assoc :\n  forall T (l1 l2 l3 : list T),\n  l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\ninduction l1; simpl; intros; auto.\nrewrite IHl1.\nreflexivity.\nQed.\n\nLemma rev_app_distr :\n  forall T (l1 l2 : list T),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\ninduction l1; simpl; intros.\n{ apply app_nil. }\nrewrite IHl1.\nrewrite app_assoc.\nreflexivity.\nQed.\n\nTheorem rev_involutive :\n  forall T (l : list T),\n  rev (rev l) = l.\nProof.\nAdmitted.\n", "meta": {"author": "erikmd", "repo": "tryjscoq", "sha": "b5636d1b7bc6616fe7f136678e30bc4030484f22", "save_path": "github-repos/coq/erikmd-tryjscoq", "path": "github-repos/coq/erikmd-tryjscoq/tryjscoq-b5636d1b7bc6616fe7f136678e30bc4030484f22/tapfa/preuves.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7317056018897277}}
{"text": "(** * Types.v : Standard types and user-defined types *)\n\nSet Implicit Arguments.\n\nRequire Export BaseDef.\nRequire Export Dlist.\nRequire Export CCMisc.\n\n\nOpen Scope nat_scope.\n\n(** Polynomials *)\nModule Type POLYNOMIALS.\n\n Parameter polynomial : Type.\n\n Parameter pcst :> nat -> polynomial.\n Parameter pvar : polynomial.\n Parameter pplus : polynomial -> polynomial -> polynomial.\n Parameter pmult : polynomial -> polynomial -> polynomial.\n Parameter pcomp : polynomial -> polynomial -> polynomial.\n\n Parameter peval : polynomial -> nat -> nat.\n\n Coercion peval : polynomial >-> Funclass.\n\n Parameter pcst_spec : forall k n, peval (pcst k) n = k.\n \n Parameter pvar_spec : forall n, peval pvar n = n.\n\n Parameter pplus_spec : forall p1 p2 n, \n  peval (pplus p1 p2) n = peval p1 n + peval p2 n.\n\n Parameter pmult_spec : forall p1 p2 n, \n    peval (pmult p1 p2) n = peval p1 n * peval p2 n.\n\n Parameter pcomp_spec : forall (p q : polynomial) n,\n   peval (pcomp p q) n = peval p (peval q n).\n\n Parameter polynomial_bounded :\n  forall p, exists k, forall n, 2 <= n -> peval p n <= n ^ k.\n\n Parameter peval_monotonic : forall (p : polynomial) n1 n2,\n   n1 <= n2 -> p n1 <= p n2.\n\nEnd POLYNOMIALS.\n\nModule Poly : POLYNOMIALS.\n\n Definition polynomial : Type := list (nat * nat).\n\n Definition pcst (c:nat) : polynomial := (c,0) :: nil.\n\n Definition pvar : polynomial := (1,1) :: nil. \n\n Fixpoint mplus (c:nat) (k:nat) (p:polynomial) {struct p} : polynomial :=\n  match p with\n  | nil => (c,k) :: nil\n  | (c',k') :: p' =>\n   match nat_eqb k k' with\n   | true => (c + c', k) :: p'\n   | false => (c', k') :: mplus c k p'\n   end\n  end.\n \n Fixpoint pplus (p1 p2:polynomial) {struct p1} : polynomial :=\n  match p1 with\n  | nil => p2\n  | (c,k) :: p' => mplus c k (pplus p' p2)\n  end.\n\n Fixpoint mmult (c:nat) (k:nat) (p:polynomial) {struct p} : polynomial :=\n  match p with\n  | nil => nil\n  | (c', k') :: p' => (c*c', k + k') :: mmult c k p'\n  end.\n\n Fixpoint pmult (p1 p2:polynomial) {struct p1} : polynomial :=\n  match p1 with\n  | nil => nil\n  | (c,k)::p => pplus (mmult c k p2) (pmult p p2)\n  end.\n  \n Fixpoint ppow (p : polynomial) (n : nat) {struct n} : polynomial :=\n   match n with\n     | 0 => pcst 1\n     | S n' => pmult p (ppow p n')\n   end.\n\n Fixpoint pcomp (p q : polynomial) : polynomial :=\n   match p with\n     | nil => nil\n     | (c,k)::p' => pplus (pmult (pcst c) (ppow q k)) (pcomp p' q) \n   end.\n\n Fixpoint peval (p:polynomial) (n:nat) {struct p} : nat :=\n  match p with\n  | nil => 0\n  | (c,k) :: p' => c * n ^ k + peval p' n\n  end.\n\n Lemma pcst_spec : forall k n, peval (pcst k) n = k.\n Proof.\n  intros; simpl; ring.\n Qed.\n \n Lemma pvar_spec : forall n, peval pvar n = n.\n Proof.\n  intros; simpl; ring.\n Qed.\n\n Lemma peval_mplus : forall c k p n,\n  peval (mplus c k p) n = c * n ^ k + peval p n.\n Proof.\n  induction p; simpl.\n  intros; ring.\n  intros; destruct a.\n  case_eq (nat_eqb k n1); intro Heq.\n  rewrite (nat_eqb_true Heq); simpl; ring.\n  simpl; rewrite IHp; ring.\n Qed.\n\n Lemma pplus_spec : forall p1 p2 n, \n  peval (pplus p1 p2) n = peval p1 n + peval p2 n.\n Proof.\n  induction p1; simpl.\n  trivial.\n  intros; destruct a; rewrite peval_mplus, IHp1; simpl; ring.\n Qed.\n\n Lemma peval_mmult : forall c k p n,\n   peval (mmult c k p) n = (c*n^k)*peval p n.\n Proof.\n  induction p; simpl; intros.\n  ring.\n  destruct a; simpl.\n  rewrite IHp, <- pow_mult_plus; ring.\n Qed.\n\n Lemma pmult_spec : forall p1 p2 n,\n   peval (pmult p1 p2) n = peval p1 n * peval p2 n.\n Proof.\n  induction p1; simpl; intros.\n  trivial.\n  destruct a.\n  rewrite pplus_spec, peval_mmult, IHp1; ring.\n Qed.\n\n Lemma ppow_spec : forall p k n,\n   peval (ppow p k) n = (peval p n) ^ k.\n Proof.\n  induction k; simpl; intros; trivial.\n  rewrite pmult_spec, IHk; trivial.\n Qed.\n\n Lemma pcomp_spec : forall (p q : polynomial) n,\n   peval (pcomp p q) n = peval p (peval q n).\n Proof.\n   induction p; simpl; intros; trivial.\n   destruct a as (c, k).\n   rewrite pplus_spec, pplus_spec, peval_mmult, ppow_spec, IHp; simpl; ring.\n Qed.\n\n Lemma polynomial_bounded :\n  forall p, exists k, forall n, 2 <= n -> peval p n <= n ^ k.\n Proof.\n  induction p; intros; simpl.\n  exists 0; intros; simpl; auto.\n\n  destruct a as (c, k0).\n  destruct IHp as [k Hle].\n  destruct (pow_2_le c) as [kc Hc].\n  exists (S (Max.max (kc + k0) k)); intros n Hn.\n  apply le_trans with (2 ^ kc * n ^ k0 + n ^ k).\n  apply plus_le_compat; [ | auto].\n  apply mult_le_compat; trivial.\n  \n  apply le_trans with (n ^ kc * n ^ k0 + n ^ k).\n  apply plus_le_compat; [ | trivial].\n  apply mult_le_compat; [ | trivial].\n  apply pow_monotone_1; trivial.\n\n  apply le_trans with (2 * n ^ (Max.max (kc + k0) k)).\n  apply le_trans with (n ^ Max.max (kc + k0) k + n ^ Max.max (kc + k0) k).\n  rewrite pow_mult_plus.\n  apply plus_le_compat.\n  apply pow_monotone_2; auto with arith.\n  apply pow_monotone_2; auto with arith.\n  omega.\n  apply mult_le_compat; trivial.  \n Qed.\n\n Lemma peval_monotonic : forall (p : polynomial) n1 n2,\n   n1 <= n2 -> peval p n1 <= peval p n2.\n Proof.\n  induction p; simpl; intros; auto.\n  destruct a.\n  apply plus_le_compat; auto.\n  apply mult_le_compat; auto.\n  apply pow_monotone_1; trivial.\n Qed.\n\nEnd Poly.\n\nExport Poly.\n\nLemma pplus_assoc : forall p q r k,\n peval (pplus (pplus p q) r) k = peval (pplus p (pplus q r)) k.\nProof.\n intros p q r k.\n rewrite (pplus_spec (pplus p q) r).\n rewrite (pplus_spec p q).\n rewrite <- plus_assoc.\n repeat rewrite <- pplus_spec; trivial.\nQed.\n\nLemma pplus_comm : forall p q k,\n peval (pplus p q) k = peval (pplus q p) k.\nProof.\n intros p q k.\n rewrite pplus_spec.\n rewrite plus_comm.\n rewrite <- pplus_spec; trivial.\nQed.\n \nLemma pplus_le_l : forall p1 p2 n, peval p1 n <= peval (pplus p1 p2) n.\nProof.\n intros; rewrite pplus_spec; auto with arith.\nQed.\n\nLemma pplus_le_r : forall p1 p2 n, peval p2 n <= peval (pplus p1 p2) n.\nProof.\n intros; rewrite pplus_spec; auto with arith.\nQed.\n\n(** [size_nat] definition *)\n\nFixpoint log_inf (p:positive) : nat :=\n match p with\n | xH => O\n | xO q => S (log_inf q)\n | xI q => S (log_inf q)\n end.\n\nFixpoint log_sup (p:positive) : nat :=\n match p with\n | xH => O\n | xO q => S (log_sup q)\n | xI q => S (S (log_inf q))\n end.\n\nLemma log_inf_monotonic : forall (p q:positive), (p <= q)%positive ->\n log_inf p <= log_inf q.\nProof.\n unfold Ple; induction p; destruct q; simpl; intros; auto using le_n_S with arith.\n apply le_n_S; apply IHp; intro; apply H.\n case_eq ((p ?= q)%positive Gt); intros; trivial.\n destruct (Pcompare_not_Eq p q).\n elim (H2 H1).\n apply Pcompare_Gt_Lt in H1; rewrite H1 in H0; trivial.\n elim H; trivial.\n apply le_n_S; apply IHp; intro; apply H.\n rewrite <- Pcompare_eq_Gt; trivial.\n elim H; trivial.\nQed.\n\nLemma log_sup_inf_monotonic :forall p q, \n (p ?= q)%positive Eq = Lt ->\n S (log_inf p) <= log_sup q.\nProof.\n induction p; destruct q; simpl; intros H; try discriminate H; auto with arith.\n apply le_n_S; apply le_n_S; apply log_inf_monotonic; unfold Ple; rewrite H; intro; discriminate.\n apply le_n_S; apply IHp.\n rewrite Pcompare_eq_Lt; trivial.\n apply le_n_S; apply le_n_S; apply log_inf_monotonic; unfold Ple.\n apply Pcompare_Lt_Lt in H; destruct H.\n rewrite H; intro; discriminate.\n rewrite H, Pcompare_refl; intro; discriminate.\nQed.\n\nLemma log_inf_le_log_sup : forall p, log_inf p <= log_sup p.\nProof.\n induction p; intros; simpl; auto with arith.\nQed.\n\nLemma log_sup_le_Slog_inf : forall p, log_sup p <= S (log_inf p).\nProof.\n induction p; intros; simpl; auto with arith.\nQed.\n\nLemma log_sup_monotonic : forall (p q:positive), (p <= q)%positive ->\n log_sup p <= log_sup q.\nProof.\n unfold Ple; induction p; destruct q; simpl; intros; \n  auto using le_n_S, log_inf_monotonic with arith.\n apply le_n_S.\n case_eq ((p ?= q)%positive Gt); intros Heq; rewrite Heq in H.\n destruct (Pcompare_not_Eq p q).\n elim (H0 Heq).\n rewrite <- Pcompare_eq_Lt in Heq.\n apply log_sup_inf_monotonic; trivial.\n elim H; trivial.\n elim H; trivial.\n apply le_n_S.\n apply le_trans with (2:= log_sup_le_Slog_inf q); auto with arith.\n apply IHp; intro; apply H; rewrite <- Pcompare_eq_Gt; trivial.\n elim H; trivial.\nQed.\n\nDefinition size_nat (n:nat) : nat := \n match n with\n | O => S O\n | _ => log_sup (P_of_succ_nat n)\n end.\n\nLemma size_nat_double : forall n, \n 0 < n -> size_nat (2 * n) = S (size_nat n).\nProof.\n intros n Hn.\n destruct n; simpl; auto with arith.\n clear; rewrite plus_0_r, <- plus_n_Sm; simpl.\n rewrite ZL3.\n induction (P_of_succ_nat n); simpl.\n apply eq_S; rewrite <- IHp; trivial.\n trivial.\n trivial.\nQed.\n\nLemma size_nat_monotonic : forall n p,\n n <= p -> \n size_nat n <= size_nat p.\nProof.\n intros n p; case n; case p; intros.\n trivial.\n simpl.\n apply le_trans with (log_sup (P_of_succ_nat (S O))).\n trivial.\n apply log_sup_monotonic.\n simpl; intro.\n apply nat_of_P_gt_Gt_compare_morphism in H0.\n rewrite nat_of_P_succ_morphism, nat_of_P_o_P_of_succ_nat_eq_succ in H0.\n unfold nat_of_P in H0; simpl in H0; omega.\n omega.\n simpl; apply log_sup_monotonic; intro.\n apply nat_of_P_gt_Gt_compare_morphism in H0.\n repeat rewrite nat_of_P_succ_morphism, nat_of_P_o_P_of_succ_nat_eq_succ in H0; omega.\nQed.\n\nLemma size_nat_positive : forall n, 0 < size_nat n.\nProof.\n induction n.\n auto.\n apply lt_le_trans with (size_nat n).\n trivial.\n apply size_nat_monotonic; apply le_S; trivial.\nQed.\n\nLemma size_nat_plus_max : forall n m, n <= m -> size_nat (n + m) <= S (size_nat m).\nProof.\n intros; apply le_trans with (size_nat (2 * m)).\n apply size_nat_monotonic; omega.\n destruct m.\n simpl; auto with arith.\n rewrite size_nat_double; auto with arith.\nQed.\n\nLemma size_nat_plus : forall n m, size_nat (n + m) <= size_nat n + size_nat m.\nProof.\n intros n m.\n destruct (le_lt_dec n m).\n apply le_trans with (1 := size_nat_plus_max l).\n assert (W:= size_nat_positive n); omega.\n assert (m <= n) by omega; clear l.\n rewrite plus_comm, (plus_comm (size_nat n)).\n apply le_trans with (1 := size_nat_plus_max H).\n assert (W:= size_nat_positive m); omega.\nQed.\n\nFixpoint Ppow2 (n:nat) := match n with O => xH | S n => xO (Ppow2 n) end.\n\nLemma Ppow2_lt_compat : forall n m, n < m -> (Ppow2 n < Ppow2 m)%positive.\nProof.\n induction n; destruct m; simpl; intros.\n elimtype False; omega.\n red; trivial.\n elimtype False; omega.\n refine (IHn _ _); omega.\nQed.\n\nLemma Ppow2_monotonic : forall n m, n <= m -> (Ppow2 n <= Ppow2 m)%positive.\nProof.\n induction n; destruct m; simpl; intros.\n discriminate.\n discriminate.\n elimtype False; omega.\n refine (IHn _ _); omega.\nQed.\n\nLemma log_inf_pow : forall n, (Ppow2 (log_inf n) <= n < Ppow2 (S (log_inf n)))%positive.\nProof.\n induction n.\n destruct IHn; split.\n unfold Ple in *; simpl; intro; apply H.\n apply Pcompare_Lt_Gt; trivial.\n change ((n ?= (Ppow2 (log_inf n~1)))%positive Gt = Lt).\n rewrite <- Pcompare_eq_Lt; exact H0.\n exact IHn.\n unfold Ple, Plt; simpl; split;[discriminate | trivial].\nQed.\n\nLemma log_sup_inf : forall p, log_sup p = log_inf p \\/ log_sup p = S (log_inf p).\nProof.\n intros p; assert (W:= log_inf_le_log_sup p); assert (W':= log_sup_le_Slog_inf p).\n omega.\nQed.\n\nLemma log_pow_eq : forall n, log_sup n = log_inf n -> n = Ppow2 (log_sup n).\nProof.\n induction n; simpl; intros.\n elimtype False; omega.\n rewrite <- IHn; trivial.\n injection H; trivial.\n trivial.\nQed.\n\nLemma log_sup_pow : forall n, log_sup (Ppow2 n) = n.\nProof.\n induction n; simpl; trivial.\n rewrite IHn; trivial.\nQed.\n\nLemma log_pow : forall n, (n <= Ppow2 (log_sup n))%positive.\nProof.\n intros.\n assert (W:=log_inf_pow n).\n destruct (log_sup_inf n).\n rewrite <- (log_pow_eq _ H); intro H0; rewrite Pcompare_refl in H0; discriminate H0.\n destruct W.\n unfold Ple, Plt in *; rewrite H, H1; discriminate.\nQed.\n\nLemma nat_of_P_le_morphism : forall p q, Ple p q -> nat_of_P p <= nat_of_P q.\nProof.\n intros.\n assert (~ nat_of_P p > nat_of_P q);[ | omega].\n intro. \n apply nat_of_P_gt_Gt_compare_complement_morphism in H0.\n apply (H H0).\nQed.\n\nLemma nat_of_P_le_complement_morphism : forall p q, nat_of_P p <= nat_of_P q -> Ple p q.\nProof.\n intros.\n intro.\n apply nat_of_P_gt_Gt_compare_morphism in H0; omega.\nQed.\n \nLemma Ppow2_mult_add : forall n m, (Ppow2 n * Ppow2 m = Ppow2 (n + m))%positive.\nProof.\n induction n; simpl; intros; trivial.\n rewrite IHn; trivial.\nQed.\n\nLemma log_sup_mult : forall n m, log_sup (n * m) <= log_sup n + log_sup m.\nProof.\n intros.\n apply le_trans with (log_sup (Ppow2 (log_sup n) * Ppow2 (log_sup m))).\n apply log_sup_monotonic.\n apply nat_of_P_le_complement_morphism.\n repeat rewrite nat_of_P_mult_morphism.\n apply mult_le_compat; apply nat_of_P_le_morphism; apply log_pow.\n rewrite Ppow2_mult_add, log_sup_pow; trivial.\nQed.\n\nLemma size_nat_mult : forall n m, size_nat (n * m) <= size_nat n + size_nat m.\nProof.\n intros n m.\n destruct n.\n simpl; auto with arith.\n destruct m.\n rewrite mult_0_r, plus_comm; simpl; auto with arith. \n unfold size_nat.\n change (log_sup (P_of_succ_nat (S n * S m)) <=\n   log_sup (P_of_succ_nat (S n)) + log_sup (P_of_succ_nat (S m))).\n apply le_trans with (log_sup (P_of_succ_nat (S n) * P_of_succ_nat (S m))).\n apply log_sup_monotonic; intro.\n apply nat_of_P_gt_Gt_compare_morphism in H.\n rewrite nat_of_P_mult_morphism in H.\n repeat rewrite nat_of_P_o_P_of_succ_nat_eq_succ in H.\n ring_simplify in H; omega.\n apply log_sup_mult.\nQed.\n\nLemma log_sup_le : forall p, log_sup (Psucc p) <= S (log_sup p).\nProof.\n induction p; simpl.\n apply le_trans with (S (S (log_sup p))).\n apply le_n_S; trivial.\n apply le_n_S; apply le_n_S; apply log_sup_le_Slog_inf.\n apply le_n_S; apply le_n_S; apply log_inf_le_log_sup.\n trivial.\nQed.\n\nLemma log_sup_le_S : forall p,\n log_sup p <= log_sup (Psucc p).\nProof.\n destruct p; simpl.\n apply le_n_S.\n induction p; simpl.\n apply le_n_S; trivial.\n trivial.\n trivial.\n apply le_n_S; apply log_sup_le_Slog_inf.\n apply le_S; trivial.\nQed.\n\nLemma log_sup_monotonic_P_of : forall p n,\n n <= p ->\n log_sup (P_of_succ_nat n) <= log_sup (P_of_succ_nat p).\nProof.\n induction p; intros n Hn; inversion_clear Hn.\n trivial.\n trivial.\n apply le_trans with (log_sup (P_of_succ_nat p)).\n apply IHp; trivial.\n simpl; apply log_sup_le_S.\nQed.\n\nLemma size_nat_le : forall n, \n 0 < n -> size_nat n <= n.\nProof.\n intro n; case n.\n intro Hn; trivial.  \n intros n0 _.\n unfold size_nat.\n induction (S n0).\n trivial.\n simpl.\n apply le_trans with (S (log_sup (P_of_succ_nat n1))).\n apply log_sup_le.\n apply le_n_S; trivial.\nQed.\n\nLemma size_nat_pow_2 : forall n, size_nat (2^n) = S n.\nProof.\n induction n.\n trivial.\n change (2 ^ (S n)) with (2 * 2 ^ n).\n rewrite size_nat_double.\n rewrite IHn; trivial.\n apply pow_lt_0; auto.\nQed.\n\n(* REMARK: should add 1 to account for the sign *)\nDefinition size_Z (n:Z) : nat := size_nat (Zabs_nat n).\n\nLemma size_Z_positive : forall n, 0 < size_Z n.\nProof.\n unfold size_Z.\n intros.\n apply size_nat_positive.\nQed.\n\n\nSection EQLIST.\n\n Variables (A:Type) (eqb : A -> A -> bool).\n\n Hypothesis eqb_spec : forall x y, if eqb x y then x = y else x <> y.\n\n Lemma eqb_list_spec : forall x y, if eqb_list eqb x y then x = y else x <> y.\n Proof.\n  induction x; destruct y; simpl; trivial; try (intro; discriminate).\n  generalize (eqb_spec a a0); destruct (eqb a a0); intros; subst.\n  generalize (IHx y); destruct (eqb_list eqb x y); intros; subst; trivial.\n  intros H1; apply H; inversion H1; trivial.\n  intros H1; apply H; inversion H1; trivial.\n Qed.\n\n Hypothesis Aeq_dec : forall x y:A, {x = y} + {True}.\n Hypothesis Aeq_dec_r : forall x y i, Aeq_dec x y = right _ i -> x <> y.\n\n Fixpoint eq_dec_list (l1 l2 : list A) {struct l1} : {l1 = l2} + {True} :=\n  match l1 as l1_0 return {l1_0 = l2} + {True} with\n   | nil =>\n    match l2 as l2_0 return {nil = l2_0} + {True} with\n     | nil => left _ (refl_equal nil)\n     | _ => right _ I\n    end\n   | a1::l1 => \n    match l2 as l2_0 return {a1::l1 = l2_0} + {True} with\n     | nil => right _ I\n     | a2::l2 =>\n      match Aeq_dec a1 a2 with\n       | left H =>\n        match H in (_ = y0) return {a1::l1 = y0::l2} + {True} with\n         | refl_equal =>\n          match eq_dec_list l1 l2 with\n           | left H =>\n            match H in (_ = y0) return {a1::l1 = a1::y0} + {True} with\n             | refl_equal => left _ (refl_equal (a1::l1))\n            end\n           | _ => right _ I\n          end\n        end\n       | _ => right _ I\n      end\n    end\n  end.\n\n Lemma eq_dec_list_r : forall x y i, eq_dec_list x y = right _ i -> x <> y.\n Proof.\n  induction x; destruct y; simpl; intro i; try (intros; intro; discriminate).\n  generalize (@Aeq_dec_r a a0); destruct (Aeq_dec a a0).\n  case e.\n  generalize (IHx y); destruct (eq_dec_list x y).\n  case e0.\n  intros; discriminate.\n  case t; case i; intros; intro.\n  apply (H I); trivial; inversion H2; trivial. \n  case t; case i; intros; intro.\n  apply (H I); trivial; inversion H1; trivial.\n Qed.\n\nEnd EQLIST.\n\n\n(** * User-defined types *)\nModule Type UTYPE.\n\n Parameter t : Type. \n Parameter eqb : t -> t -> bool. \n Parameter eqb_spec : forall x y, if eqb x y then x = y else x <> y.\n\n Parameter eq_dec : forall (x y:t), {x = y} + {True}.\n\n Parameter eq_dec_r : forall x y i, eq_dec x y = right _ i -> x <> y.\n \n Parameter interp : nat -> t -> Type.\n\n Parameter size : forall k t, interp k t -> nat.\n\n Parameter default : forall k t, interp k t.\n\n Parameter default_poly : t -> polynomial.\n\n Parameter size_positive : forall k t (x:interp k t), 0 < size x.\n\n Parameter default_poly_spec : forall k t,\n  size (default k t) <= peval (default_poly t) k.\n\n Parameter i_eqb : forall k t, interp k t -> interp k t -> bool.\n Parameter i_eqb_spec : forall k t (x y:interp k t), \n  if i_eqb x y then x = y else x <> y.\n\nEnd UTYPE.\n\n\nModule EmptyType <: UTYPE.\n\n Inductive t_ := .\n\n Definition t := t_.\n\n Definition eqb : t -> t -> bool := fun _ _ => true.\n\n Lemma eqb_spec : forall x y, if eqb x y then x = y else x <> y.\n Proof.\n  destruct x.\n Qed.\n\n Lemma eq_dec : forall (x y:t), {x = y} + {True}.\n Proof.\n  destruct x.\n Qed.\n\n Lemma eq_dec_r : forall x y i, eq_dec x y = right _ i -> x <> y.\n Proof.\n  destruct x.\n Qed.\n\n Definition interp : nat -> t -> Type := fun _ _ => Datatypes.unit.\n\n Definition size : forall k t, interp k t -> nat := fun _ _ _ => O.\n\n Definition default : forall k t, interp k t := fun _ _ => tt.\n \n Definition i_eqb : forall k t, interp k t -> interp k t -> bool := \n  fun _ _ _ _  => true.\n\n Definition default_poly : t -> polynomial := fun _ => pcst O.\n\n Lemma size_positive :  forall k t (x:interp k t), 0 < size x.\n Proof.\n  intros k t0; elim t0.\n Qed.\n\n Lemma default_poly_spec : forall k t,\n  size (default k t) <= peval (default_poly t) k.\n Proof.\n  intros k t0; elim t0.\n Qed.\n\n Lemma i_eqb_spec : forall k t (x y:interp k t),\n  if i_eqb x y then x = y else x <> y.\n Proof.\n  intros k t0 x y; case x; case y.\n  simpl; trivial.\n Qed.\n\nEnd EmptyType.\n\n\n(** * Types *)\nModule Type TYPE (UT:UTYPE).\n\n Inductive type : Type :=\n | User (ut:UT.t)\n | Unit  \n | Nat\n | Zt\n | Bool\n | List (t:type)\n | Pair (t1 t2:type)\n | Sum (t1 t2:type)\n | Option (t:type).\n\n Parameter eqb : type -> type -> bool.\n Parameter eqb_spec : forall x y, if eqb x y then x = y else x <> y.\n \n Parameter eq_dec : forall (x y:type), {x = y} + {True}.\n Parameter eq_dec_r : forall x y i, eq_dec x y = right _ i -> x <> y.\n\n Section INTERP.\n\n  Variable k:nat.\n\n  Fixpoint interp (t : type) : Type :=\n   match t with\n    | User ut => UT.interp k ut\n    | Unit => Datatypes.unit\n    | Nat => nat\n    | Zt => Z\n    | Bool => bool\n    | List t => list (interp t)\n    | Pair t1 t2 => (interp t1 * interp t2)%type\n    | Sum t1 t2 => (interp t1 + interp t2)%type\n    | Option t => option (interp t) \n   end.\n  \n  Fixpoint type_op (dom:list type) (codom:type) {struct dom} : Type :=\n   match dom with\n    | nil => interp codom \n    | t1 :: dom => interp t1 -> type_op dom codom \n   end.\n\n  Fixpoint ctype_op (dom:list type) (codom:type) {struct dom} : Type :=\n   match dom with\n    | nil => (interp codom * nat)%type \n    | t1 :: dom => interp t1 -> ctype_op dom codom \n   end.\n\n  Fixpoint app_op (dom:list type) (codom:type) (op:type_op dom codom)\n   (args:dlist interp dom) {struct args} : interp codom :=\n   match args in (dlist _ dom0) return type_op dom0 codom -> interp codom with\n   | dnil => fun (op:interp codom) => op\n   | dcons t1 dom v args =>\n     fun (op:type_op (t1::dom) codom) => app_op codom (op v) args\n   end op.\n\n  Fixpoint capp_op (dom:list type) (codom:type) (op:ctype_op dom codom)\n   (args:dlist interp dom) {struct args} : interp codom * nat :=\n   match args in (dlist _ dom0) return ctype_op dom0 codom -> interp codom * nat with\n   | dnil => fun (op:interp codom * nat) => op\n   | dcons t1 dom v args =>\n     fun (op:ctype_op (t1::dom) codom) => capp_op codom (op v) args\n   end op.\n\n  Fixpoint default (t:type) {struct t} : interp t :=\n   match t as t0 return interp t0 with\n    | User ut => UT.default k ut\n    | Unit => tt\n    | Nat => 0%nat\n    | Zt => 0%Z\n    | Bool => false\n    | List t1 => @nil (interp t1)\n    | Pair t1 t2 => (default t1, default t2)\n    | Sum t1 t2 => inl _ (default t1)\n    | Option t => None\n   end.\n\n  Fixpoint default_poly (t:type) : polynomial :=\n   match t with\n    | User ut => UT.default_poly ut\n    | Unit => 1\n    | Nat => 1   \n    | Zt => 1\n    | Bool => 1\n    | List _ => 1\n    | Pair t1 t2 => pplus 1 (pplus (default_poly t1) (default_poly t2))\n    | Sum t1 t2 => pplus 1 (default_poly t1)\n    | Option t => 1\n   end.\n\n  Fixpoint size (t:type) {struct t} : interp t -> nat :=\n   match t as t0 return interp t0 -> nat with\n    | User ut => fun v => UT.size v\n    | Unit => fun _ => 1\n    | Nat => size_nat    \n    | Zt => size_Z\n    | Bool => fun _ => S O\n    | List t1 => fun l => List.fold_right (fun v n => S (size t1 v + n)) 1 l\n    | Pair t1 t2 => fun p => S (size t1 (fst p) + size t2 (snd p))%nat\n    | Sum t1 t2 => fun s => \n       S (match s with inl x => size t1 x | inr y => size t2 y end)   \n    | Option t => fun o => \n       match o with None => 1 | Some x => S (size t x) end \n   end.\n\n End INTERP.\n\n Parameter size_positive : forall k t (x:interp k t), 0 < size k t x.\n\n Parameter default_poly_spec : forall k t,\n  size k t (default k t) <= peval (default_poly t) k.\n \n Parameter i_eqb : forall k t, interp k t -> interp k t -> bool.\n Parameter i_eqb_spec : forall k t (x y:interp k t), \n  if i_eqb k t x y then x = y else x <> y.\n\n (* Dependant equality *)\n Parameter eq_dep_eq : forall (P:type->Type) (p:type) (x y:P p), \n  eq_dep type P p x p y -> x = y.\n \n Parameter UIP_refl : forall (x:type) (p:x = x), p = refl_equal x.\n\n Parameter inj_pair2 : forall (P:type -> Type) (p:type) (x y:P p),\n  existT P p x = existT P p y -> x = y.\n\n Parameter l_eq_dep_eq : forall (P : list type -> Type) \n  (p : list type) (x y : P p),\n  eq_dep (list type) P p x p y -> x = y.\n\n Parameter l_inj_pair2 : forall (P : list type -> Type) \n  (p : list type) (x y : P p),\n  existT P p x = existT P p y -> x = y.\n\n Parameter l_UIP_refl : forall (x : list type) (p : x = x), p = refl_equal x.\n\n\n Ltac dlist_inversion_aux l Heq :=\n  let H := fresh \"H\" in\n  let l1 := fresh \"l\" in\n   match type of l with\n   | dlist _ nil =>\n     rewrite (l_eq_dep_eq (dlist_nil l)) in Heq\n   | dlist _ (_::_) =>\n     destruct (dlist_cons l) as [? [l1 H] ];\n     rewrite (l_eq_dep_eq H) in Heq;\n     clear H; dlist_inversion_aux l1 Heq; clear l1\n   | _ => fail 1 \"dlist_inversion : Unexpected type\"\n   end.\n\n Ltac dlist_inversion l :=\n  let l' := fresh \"l\" in\n  let Heq := fresh \"Heq\" in\n   pose (l' := l);\n   assert (Heq : l' = l) by (vm_cast_no_check (refl_equal l'));\n   vm_compute in l;\n   dlist_inversion_aux l Heq;\n   unfold l' in Heq; clear l'.\n\nEnd TYPE.\n\n\nModule MakeType (UT:UTYPE) <: TYPE UT.\n\n Inductive type : Type :=\n | User (ut:UT.t)\n | Unit\n | Nat\n | Zt\n | Bool\n | List (t:type)\n | Pair (t1 t2:type)\n | Sum (t1 t2:type)\n | Option (t:type).\n\n Fixpoint eqb (x y : type) {struct x} : bool :=\n  match x, y with\n   | User ut1, User ut2 => UT.eqb ut1 ut2\n   | Unit, Unit => true\n   | Nat, Nat => true  \n   | Zt, Zt => true \n   | Bool, Bool => true\n   | List t1, List t2 => eqb t1 t2\n   | Pair x1 x2, Pair y1 y2 => if eqb x1 y1 then eqb x2 y2 else false\n   | Sum x1 x2, Sum y1 y2 => if eqb x1 y1 then eqb x2 y2 else false\n   | Option x, Option y => eqb x y\n   | _, _ => false\n  end.\n\n Lemma eqb_spec : forall x y, if eqb x y then x = y else x <> y.\n Proof.\n  induction x; destruct y; simpl; intros; trivial; try (intro; discriminate).\n  generalize (UT.eqb_spec ut ut0); destruct (UT.eqb ut ut0);\n   intros; subst; trivial.\n  intro H1; apply H; inversion H1; trivial.\n  generalize (IHx y); destruct (eqb x y); intros; subst; trivial.\n  intro H1; apply H; inversion H1; trivial.\n  generalize (IHx1 y1); destruct (eqb x1 y1); intros; subst.\n  generalize (IHx2 y2); destruct (eqb x2 y2); intros; subst; trivial.\n  intro H1; apply H; inversion H1; trivial.   \n  intro H1; apply H; inversion H1; trivial.   \n  generalize (IHx1 y1); destruct (eqb x1 y1); intros; subst.\n  generalize (IHx2 y2); destruct (eqb x2 y2); intros; subst; trivial.\n  intro H1; apply H; inversion H1; trivial.   \n  intro H1; apply H; inversion H1; trivial.   \n  generalize (IHx y); destruct (eqb x y); intros; subst; trivial.\n  intro H1; apply H; inversion H1; trivial.\n Qed.\n\n Definition eq_dec (x y:type) : {x = y} + {True}.\n  induction x; destruct y;\n  match goal with \n  | |- {?X _ _ = ?X _ _} + {True} => idtac\n  | |- {?X _ = ?X _} + {True} => idtac\n  | |- {?X = ?X} + {True} => left; apply refl_equal\n  | _ => right; trivial\n  end.\n  case (UT.eq_dec ut ut0).\n  intro Heq; rewrite Heq; left; trivial.\n  right; trivial.  \n  \n  case (IHx y).\n  intro Heq; rewrite Heq; left; trivial.\n  right; trivial.\n\n  case (IHx1 y1).\n  intro Heq1; rewrite Heq1.\n  case (IHx2 y2).\n  intro Heq2; rewrite Heq2; left; trivial.     \n  right; trivial.\n  right; trivial.\n\n  case (IHx1 y1).\n  intro Heq1; rewrite Heq1.\n  case (IHx2 y2).\n  intro Heq2; rewrite Heq2; left; trivial.     \n  right; trivial.\n  right; trivial.\n\n  case (IHx y).\n  intro Heq; rewrite Heq; left; trivial.\n  right; trivial.\n Defined.  \n \n Lemma eq_dec_r : forall x y i, eq_dec x y = right _ i -> x <> y.\n Proof.\n  induction x; destruct y; intros i; simpl; try (intros; intro; discriminate).\n  case_eq (UT.eq_dec ut ut0); intros.\n  clear H; generalize H0; case e; intros; discriminate.\n  clear H0; assert (H0 := UT.eq_dec_r H).\n  intros Heq; apply H0; inversion Heq; trivial.\n  generalize (IHx y); destruct (eq_dec x y); intros; try discriminate.\n  clear H; generalize H0; case e; intros; discriminate.\n  generalize H; clear H; case t; intros.\n  intros Heq; apply (H i); trivial; inversion Heq; trivial.\n  case i; trivial.\n  generalize (IHx1 y1); destruct (eq_dec x1 y1).\n  case e.\n  generalize (IHx2 y2); destruct (eq_dec x2 y2).\n  case e0.\n  intros; discriminate.\n  case t; intros; intro.\n  apply (H i); trivial; inversion H2; trivial.\n  case i; trivial.\n  case t; intros; intro.\n  apply (H i); trivial; inversion H1; trivial.\n  case i; trivial.\n  generalize (IHx1 y1); destruct (eq_dec x1 y1).\n  case e.\n  generalize (IHx2 y2); destruct (eq_dec x2 y2).\n  case e0.\n  intros; discriminate.\n  case t; intros; intro.\n  apply (H i); trivial; inversion H2; trivial.\n  case i; trivial.\n  case t; intros; intro.\n  apply (H i); trivial; inversion H1; trivial.\n  case i; trivial.\n  generalize (IHx y); destruct (eq_dec x y); intros; try discriminate.\n  clear H; generalize H0; case e; intros; discriminate.\n  generalize H; clear H; case t; intros.\n  intros Heq; apply (H i); trivial; inversion Heq; trivial.\n  case i; trivial.\n Qed.\n\n Section INTERP.\n\n  Variable k:nat.\n\n  Fixpoint interp (t : type) : Type :=\n   match t with\n    | User ut => UT.interp k ut\n    | Unit => Datatypes.unit\n    | Nat => nat\n    | Zt => Z\n    | Bool => bool\n    | List t => list (interp t)\n    | Pair t1 t2 => (interp t1 * interp t2)%type\n    | Sum t1 t2 => (interp t1 + interp t2)%type\n    | Option t => option (interp t) \n   end.\n  \n  Fixpoint type_op (dom:list type) (codom:type) {struct dom} : Type :=\n   match dom with\n    | nil => interp codom\n    | t1 :: dom => interp t1 -> type_op dom codom \n   end.\n\n  Fixpoint ctype_op (dom:list type) (codom:type) {struct dom} : Type :=\n   match dom with\n    | nil => (interp codom * nat)%type \n    | t1 :: dom => interp t1 -> ctype_op dom codom \n   end.\n\n  Fixpoint app_op (dom:list type) (codom:type) (op:type_op dom codom)\n   (args:dlist interp dom) {struct args} : interp codom :=\n   match args in (dlist _ dom0) return type_op dom0 codom -> interp codom with\n   | dnil => fun (op:interp codom) => op\n   | dcons t1 dom v args =>\n     fun (op:type_op (t1::dom) codom) => app_op codom (op v) args\n   end op.\n\n  Fixpoint capp_op (dom:list type) (codom:type) (op:ctype_op dom codom)\n   (args:dlist interp dom) {struct args} : interp codom * nat :=\n   match args in (dlist _ dom0) return ctype_op dom0 codom -> interp codom * nat with\n   | dnil => fun (op:interp codom * nat) => op\n   | dcons t1 dom v args =>\n     fun (op:ctype_op (t1::dom) codom) => capp_op codom (op v) args\n   end op.\n\n  Fixpoint default (t:type) {struct t} : interp t :=\n   match t as t0 return interp t0 with\n    | User ut => UT.default k ut\n    | Unit => tt\n    | Nat => 0%nat\n    | Zt => 0%Z\n    | Bool => false\n    | List t1 => @nil (interp t1)\n    | Pair t1 t2 => (default t1, default t2)\n    | Sum t1 t2 => inl _ (default t1)\n    | Option t => None\n   end.\n\n  Fixpoint default_poly (t:type) : polynomial :=\n   match t with\n    | User ut => UT.default_poly ut\n    | Unit => 1   \n    | Nat => 1   \n    | Zt => 1\n    | Bool => 1\n    | List _ => 1\n    | Pair t1 t2 => pplus 1 (pplus (default_poly t1) (default_poly t2))\n    | Sum t1 t2 => pplus 1 (default_poly t1)\n    | Option t => 1\n   end.\n\n  Fixpoint size (t:type) {struct t} : interp t -> nat :=\n   match t as t0 return interp t0 -> nat with\n    | User ut => fun v => UT.size v\n    | Unit  => fun _ => 1\n    | Nat => size_nat    \n    | Zt => size_Z\n    | Bool => fun _ => S O\n    | List t1 => fun l => List.fold_right (fun v n => S (size t1 v + n)) 1 l\n    | Pair t1 t2 => fun p => S (size t1 (fst p) + size t2 (snd p))%nat\n    | Sum t1 t2 => fun s => \n       S (match s with inl x => size t1 x | inr y => size t2 y end)   \n    | Option t => fun o => \n       match o with None => 1 | Some x => S (size t x) end \n   end.\n  \n  Fixpoint i_eqb (t:type) {struct t} : interp t -> interp t -> bool :=\n   match t as t0 return interp t0 -> interp t0 -> bool with\n    | User ut => @UT.i_eqb k ut\n    | Unit => fun _ _ => true\n    | Nat => nat_eqb\n    | Zt => Zeq_bool\n    | Bool => Bool.eqb \n    | List t1 => eqb_list (i_eqb t1) \n    | Pair t1 t2 => \n      fun (v1 v2:interp t1 * interp t2) =>\n       if i_eqb t1 (fst v1) (fst v2) then i_eqb t2 (snd v1) (snd v2) else false\n    | Sum t1 t2 =>\n      fun (v1 v2:interp t1 + interp t2) =>\n       match v1, v2 with\n       | inl x1, inl x2 => i_eqb t1 x1 x2\n       | inr y1, inr y2 => i_eqb t2 y1 y2 \n       | _, _ => false\n       end\n    | Option t =>\n       fun v1 v2 =>\n        match v1, v2 with \n        | None, None => true\n        | Some x1, Some x2 => i_eqb t x1 x2\n        | _, _ => false\n        end \n   end. \n\n  Lemma i_eqb_spec : forall t (x y:interp t), \n   if i_eqb t x y then x = y else x <> y.\n  Proof.\n   induction t; simpl; intros.\n   apply UT.i_eqb_spec.\n   destruct x; destruct y; trivial.\n   apply nat_eqb_spec.\n   case_eq (Zeq_bool x y); intros.\n   apply Zeq_bool_eq; exact H.\n   apply Zeq_bool_neq; exact H.\n   case_eq (Bool.eqb x y); intros.\n   apply eqb_prop; trivial.\n   intro; subst; rewrite eqb_reflx in H; discriminate.\n   apply eqb_list_spec; auto.\n   generalize (IHt1 (fst x) (fst y)); destruct (i_eqb t1 (fst x) (fst y));\n    intros; subst.\n   generalize (IHt2 (snd x) (snd y)); destruct (i_eqb t2 (snd x) (snd y));\n    intros; subst; trivial.\n   destruct x; destruct y; simpl in H, H0; subst; trivial.\n   intro H1; apply H0; inversion H1; trivial.\n   intro H1; apply H; inversion H1; trivial.\n\n   destruct x as [x1 | y1]; destruct y as [x2 | y2].\n   generalize (IHt1 x1 x2); destruct (i_eqb t1 x1 x2).\n   intro; subst; trivial.   \n   intros H0 H1; apply H0; injection H1; trivial.\n   discriminate.\n   discriminate.\n   generalize (IHt2 y1 y2); destruct (i_eqb t2 y1 y2).\n   intro; subst; trivial.   \n   intros H0 H1; apply H0; injection H1; trivial.\n   \n   destruct x; destruct y.  \n   generalize (IHt i i0); case (i_eqb t i i0). \n   intro; subst; trivial. \n   intros H0 H1; apply H0; injection H1; trivial.\n   discriminate.\n   discriminate.  \n   trivial.\n  Qed.\n\n End INTERP.\n\n Lemma size_positive :  forall k t (x:interp k t), 0 < size k t x.\n Proof.\n  intros k t x.\n  destruct t; simpl.\n  apply UT.size_positive.\n  auto.\n  apply size_nat_positive.\n  apply size_Z_positive.\n  auto.\n  induction x; simpl; auto with arith.\n  auto with arith.\n  auto with arith.\n  case x; auto with arith.\n Qed.\n\n Lemma default_poly_spec : forall k t,\n  size k t (default k t) <= peval (default_poly t) k.\n Proof.\n  intros k t.\n  induction t.\n  simpl; apply UT.default_poly_spec.\n  simpl; rewrite pcst_spec; trivial.\n  simpl; rewrite pcst_spec; trivial.\n  simpl; rewrite pcst_spec; trivial.\n  simpl; rewrite pcst_spec; trivial.  \n  simpl; rewrite pcst_spec; trivial.\n  simpl; rewrite pplus_spec, pcst_spec, pplus_spec; simpl.\n  apply le_n_S; apply plus_le_compat; trivial.\n  simpl; rewrite pplus_spec, pcst_spec.\n  apply le_n_S; trivial.\n  simpl; rewrite pcst_spec; trivial.\n Qed.\n\n (** Dependant equality *) \n Module Tdec <: DecidableType.\n\n  Definition U := type.\n\n  Lemma eq_dec : forall (t1 t2:type), {t1 = t2} + {t1 <> t2}.\n  Proof.\n   intros t1 t2; generalize (eqb_spec t1 t2); destruct (eqb t1 t2); auto.\n  Qed.\n\n End Tdec.\n\n Include DecidableEqDepSet Tdec.\n \n\n Module LTdec <: DecidableType.\n\n  Definition U := list type.\n\n  Lemma eq_dec : forall (l1 l2:list type), {l1 = l2} + {l1 <> l2}.\n  Proof.\n   intros l1 l2; generalize (eqb_list_spec eqb eqb_spec l1 l2).\n   destruct (eqb_list eqb l1 l2); auto.\n  Qed.\n\n End LTdec.\n \n Module LTeqdep := DecidableEqDepSet LTdec.\n\n Lemma l_eq_dep_eq : forall (P : list type -> Type) (p : list type) (x y : P p),\n  eq_dep (list type) P p x p y -> x = y.\n Proof LTeqdep.eq_dep_eq.\n \n Lemma l_inj_pair2 : forall (P : list type -> Type) (p : list type) (x y : P p),\n  existT P p x = existT P p y -> x = y.\n Proof LTeqdep.inj_pair2.\n \n Lemma l_UIP_refl : forall (x : list type) (p : x = x), p = refl_equal x.\n Proof LTeqdep.UIP_refl.\n\n\n Ltac dlist_inversion_aux l Heq :=\n  let H := fresh \"H\" in\n  let l1 := fresh \"l\" in\n   match type of l with\n   | dlist _ nil =>\n     rewrite (l_eq_dep_eq (dlist_nil l)) in Heq\n   | dlist _ (_::_) =>\n     destruct (dlist_cons l) as [? [l1 H] ];\n     rewrite (l_eq_dep_eq H) in Heq;\n     clear H; dlist_inversion_aux l1 Heq; clear l1\n   | _ => fail 1 \"dlist_inversion : Unexpected type\"\n   end.\n\n Ltac dlist_inversion l :=\n  let l' := fresh \"l\" in\n  let Heq := fresh \"Heq\" in\n   pose (l' := l);\n   assert (Heq : l' = l) by (vm_cast_no_check (refl_equal l'));\n   vm_compute in l;\n   dlist_inversion_aux l Heq;\n   unfold l' in Heq; clear l'.\n\nEnd MakeType.\n\nClose Scope nat_scope.\n", "meta": {"author": "initc3", "repo": "certipriv", "sha": "95e089a46715ebb5931eb54e0828dd20e70dcd58", "save_path": "github-repos/coq/initc3-certipriv", "path": "github-repos/coq/initc3-certipriv/certipriv-95e089a46715ebb5931eb54e0828dd20e70dcd58/Semantics/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7316872295465021}}
{"text": "(* -*- coq-prog-name: \"~/research/coq/trunk/bin/coqtop.byte\"; coq-prog-args: (\"-emacs-U\" \"-R\" \".\" \"FingerTree\" \"-R\" \"../../safe\" \"Safe\" \"-R\" \"../../monads\" \"Monad\") -*- *)\n(* begin hide *)\nRequire Import FingerTree.Monoid.\nRequire Import FingerTree.Notations.\nRequire Import Coq.Program.Program.\nSet Implicit Arguments.\n(* end hide *)\n(** ** Digits *)\nSection Digit.\n  Variable A : Type.\n\n  (** A digit is simply a buffer of one to four values. *)\n\n  Inductive digit : Type := \n  | One : A -> digit\n  | Two : A -> A -> digit\n  | Three : A -> A -> A -> digit\n  | Four : A -> A -> A -> A -> digit.\n  \n  (** We build simple functional predicates on digits for use in specifications. *)\n\n  Definition full (x : digit) := \n    match x with Four _ _ _ _ => True | _ => False  end.\n\n  (* begin hide *)\n  Definition single (x : digit) := \n    match x with One _ => True | _ => False end.\n  (* end hide *)\n  (** We now define addition of an element to the left of a digit. *)\n\n  Program Definition add_digit_left (a : A)\n    (d : digit | ~ full d) : digit :=\n    match d with\n      | One x => Two a x\n      | Two x y => Three a x y\n      | Three x y z => Four a x y z\n      | Four _ _ _ _ => !\n    end.\n\n  (** It has become a little more interesting here, as we define our first %\\emph{partial}%\n     function. We can add to a digit if and only if it is not already full. \n     So, we require the argument digit to be accompanied by a proof that it is not full.\n     We will use it to prove that the last branch is inaccessible ; \n     we use the notation ! ('bang') to denote inaccessible program points, which are\n     points where [False] can be proved.\n     Note that we can pattern-match on \n     [d] as if it was just a digit: properties have no influence on code, only on proofs.\n     \n     The generated obligation (figure \\ref{fig:}) is easily solved, as we have a contradiction in the context: \n     both [~ full d] and [d = Four _ _ _ _] are present.\n     We can define in a similar fashion addition on the right and the various \n     accessors on digits ([head], [tail], [last] and [liat]). \n     From now on we will omit the proof scripts used to solve obligations.\n     *)\n\n\n  Next Obligation.\n    intros ; simpl in H ; auto.\n  Qed.\n  \n  (* begin hide *)  \n  Program Definition add_digit_right (d : digit | ~ full d ) (a : A) : digit :=\n    match d with\n      | One x => Two x a\n      | Two x y => Three x y a\n      | Three x y z => Four x y z a\n      | Four _ _ _ _ => !\n    end.\n  \n  Next Obligation.\n  Proof.\n    intros ; simpl in H ; elim H ; auto.\n  Qed.\n\n  Definition digit_head (d : digit) : A :=\n    match d with\n      | One x => x\n      | Two x _ => x\n      | Three x _ _ => x\n      | Four x _ _ _ => x\n    end.\n  \n  Program Definition digit_tail (d : digit | ~ single d) : digit :=\n    match d with\n      | One _ => !\n      | Two x y => One y\n      | Three x y z => Two y z\n      | Four x y z w => Three y z w\n    end.\n\n  Next Obligation.\n  Proof.\n    intros ; simpl in H ; auto.\n  Qed.\n\n  Definition digit_last (d : digit) : A :=\n    match d with\n      | One x => x\n      | Two _ x => x\n      | Three _ _ x => x\n      | Four _ _ _ x => x\n    end.\n  \n  Program Definition digit_liat (d : digit | ~ single d) : digit :=\n    match d with\n      | One _ => !\n      | Two x y => One x\n      | Three x y z => Two x y\n      | Four x y z w => Three x y z\n    end.\n\n  Next Obligation.\n  Proof.\n    intros ; elim H ; simpl ; auto.\n  Qed.\n\nEnd Digit.\n\nRequire Import Modules.\n\n(* begin hide *)\nModule DigitMeasure(M : Monoid).\n  Import M.\n  Definition v := M.m.\n  \n  Section Measure.\n    Variable A : Type.\n    Variable measure : A -> v.\n    Notation \" 'lparr' x 'rparr' \" := (measure x) (x ident, no associativity).\n    \n    Definition digit_measure (d : digit A) : v :=\n      match d with\n        | One x => measure x\n        | Two x y => measure x cdot measure y\n        | Three x y z => measure x cdot measure y cdot measure z\n        | Four x y z w => measure x cdot measure y cdot measure z cdot measure w\n      end.\n    \n    Definition option_measure (A:Type) (measure : A -> v) (x : option A) := \n      match x with Some x => measure x | None => epsilon end.\n  End Measure.\n\n  Definition option_digit_measure (A : Type) (measure : A -> v) := \n     option_measure (digit_measure measure).\n\n  Ltac splitTac := \n    program_simpl ; auto with * ; intuition ; try right ; unfold option_measure ; unfold digit_measure ; simpl ; \n      monoid_tac ; auto ; repeat rewrite <- monoid_assoc ; auto.\n  \n  Obligation Tactic := splitTac.\n\n  Section Digits.\n    Variable A : Type.\n    Variable measure : A -> v.\n    Notation \" 'lparr' x 'rparr' \" := (measure x) (x ident, no associativity).\n\n    Program Definition get_digit (p : v -> bool) (d : digit A) \n      (i : v | p i = false /\\ p (i cdot digit_measure measure d) = true) : \n      { (s, x) : v * A | p s = false /\\ p (s cdot lparr x rparr) = true } :=\n      match d with\n        | One x => (i, x)\n        | Two x y => \n          let i' := i cdot lparr x rparr in\n            if dec (p i') then (i, x) else (i', y)\n        | Three x y z =>\n          let i' := i cdot lparr x rparr in\n            if dec (p i') then (i, x)\n            else\n              let i'' := i' cdot lparr y rparr in\n              if dec (p i'') then (i', y) else (i'', z)\n        | Four x y z w =>\n          let i' := i cdot lparr x rparr in\n            if dec (p i') then (i, x)\n            else\n              let i'' := i' cdot lparr y rparr in\n              if dec (p i'') then (i', y)\n              else\n                let i''' := i'' cdot lparr z rparr in\n                if dec (p i''') then (i'', z) else  (i''', w)\n      end.\n\n    Program Definition split_digit (p : v -> bool) (i : v) (d : digit A) : \n      { (l, x, r) : option (digit A) * A * option (digit A) | \n        digit_measure measure d = option_digit_measure measure l cdot measure x cdot option_digit_measure measure r /\\\n        (l = None \\/ p (i cdot (option_measure (digit_measure measure) l)) = false) /\\\n        (r = None \\/ p (i cdot (option_measure (digit_measure measure) l) cdot (measure x)) = true) } :=\n      match d with\n        | One x => (None, x, None)\n        | Two x y => \n          let i' := i cdot lparr x rparr in\n            if dec (p i') then (None, x, Some (One y))\n            else (Some (One x), y, None)\n        | Three x y z =>\n          let i' := i cdot lparr x rparr in\n          let i'' := i' cdot lparr y rparr in\n            if dec (p i') then\n              (None, x, Some (Two y z))\n            else if dec (p i'') then\n              (Some (One x), y, Some (One z))\n            else \n              (Some (Two x y), z, None)\n        | Four x y z w =>\n          let i' := i cdot lparr x rparr in\n            if dec (p i') then\n              (None, x, Some (Three y z w))\n            else let i'' := i' cdot lparr y rparr in\n              if dec (p i'') then\n                (Some (One x), y, Some (Two z w))\n              else let i''' := i'' cdot lparr z rparr in\n                if dec (p i''') then\n                  (Some (Two x y), z, Some (One w))\n                else \n                  (Some (Three x y z), w, None)\n      end.\n\n  End Digits.\nEnd DigitMeasure.\n\n(* end hide *)\n", "meta": {"author": "coq-contribs", "repo": "finger-tree", "sha": "cf0c7c74df63bd3eea88b4b60f3a062cf01ad791", "save_path": "github-repos/coq/coq-contribs-finger-tree", "path": "github-repos/coq/coq-contribs-finger-tree/finger-tree-cf0c7c74df63bd3eea88b4b60f3a062cf01ad791/DigitModule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7316872222338576}}
{"text": "(**********************************)\n(**********************************)\n(****                          ****)\n(****   Admissibility graphs   ****)\n(****                          ****)\n(**********************************)\n(**********************************)\n\nRequire Import Coq.Relations.Relation_Operators.\n\nModule Type AdmissibilityGraph.\n  #[local] Arguments clos_trans {A} _ _ _.\n\n  (* A *admissibility graph* has a set of nodes, just like any graph. *)\n\n  Parameter node : Type.\n\n  (* Nodes may *depend on* each other. *)\n\n  Parameter dependency : node -> node -> Prop.\n\n  (* Nodes may also be related via *child-parent* relationships. *)\n\n  Parameter parent : node -> node -> Prop.\n\n  (* *Ancestorship* is the reflexive transitive closure of parenthood. *)\n\n  Definition ancestor := clos_trans parent.\n\n  #[export] Hint Unfold ancestor : main.\n\n  (*\n    A dependency on a target by a source is *admissible* if some ancestor of\n    the source is a parent of some descendant of the target.\n  *)\n\n  Definition admissible n1 n2 :=\n    exists n3 n4, ancestor n1 n3 /\\ parent n4 n3 /\\ ancestor n4 n2.\n\n  #[export] Hint Unfold admissible : main.\n\n  (* Parenthood is reflexive. *)\n\n  Axiom reflexivity : forall n, parent n n.\n\n  #[export] Hint Resolve reflexivity : main.\n\n  (* Ancestorship is antisymmetric and thus a partial order. *)\n\n  Axiom antisymmetry :\n    forall n1 n2, ancestor n1 n2 -> ancestor n2 n1 -> n1 = n2.\n\n  #[export] Hint Resolve antisymmetry : main.\n\n  (* Every dependency is admissible. *)\n\n  Axiom admissibility : forall n1 n2, dependency n1 n2 -> admissible n1 n2.\n\n  #[export] Hint Resolve admissibility : main.\nEnd AdmissibilityGraph.\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/AdmissibilityGraph/AdmissibilityGraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.73157348074542}}
{"text": "Require Import Lia Arith.\n\nRecord iso (A B : Set) : Set :=\n  bijection {\n    A_to_B : A -> B;\n    B_to_A : B -> A;\n    A_B_A  : forall a : A, B_to_A (A_to_B a) = a;\n    B_A_B  : forall b : B, A_to_B (B_to_A b) = b\n  }.\n\nNotation \"x # y\" := (prod x y) (at level 50, left associativity).\n\n(* Cartesian power of a set. Zeroth power is the singleton set (unit). *)\nFixpoint set_power (A : Set) (n : nat) := match n with\n  | O => unit\n  | S n' => A # set_power A n'\n  end.\n\nNotation \"x ^^ y\" := (set_power x y) (at level 30).\n\n(* Unlike Agda, Coq has a feature to print the definition of any variables, so\n   you should copy your own solution for these properties if you want to use them.\n   These theorems are not tested. *)\n\n(* Any set has the same cardinality as itself. *)\nTheorem iso_refl : forall A : Set, iso A A.\nProof.\n  intros.\n  apply (bijection _ _ (fun a => a) (fun a => a)).\n  - intros.\n    easy.\n  - intros.\n    easy.\nQed.\n\n\n(* iso is symmetric. *)\nTheorem iso_sym : forall A B : Set, iso A B -> iso B A.\nProof.\n  intros.\n  destruct H as [ab ba aba bab].\n  apply (bijection B A ba ab bab aba).\nQed.\n\n(* iso is transitive. *)\nTheorem iso_trans : forall A B C : Set, iso A B -> iso B C -> iso A C.\nProof.\n  intros.\n  destruct H as [ab ba aba bab].\n  destruct H0 as [bc cb bcb cbc].\n  apply (bijection _ _ (fun a => bc (ab a)) (fun c => ba (cb c))).\n  - intros.\n    rewrite bcb.\n    rewrite aba.\n    easy.\n  - intros.\n    rewrite bab.\n    rewrite cbc.\n    easy.\nQed.\n\n(* Given two functions A->B and B->A, if A->B->A is satisfied and B->A is injective, A <=> B. *)\nTheorem bijection_alt : forall (A B : Set) (A2B : A -> B) (B2A : B -> A),\n  (forall a, B2A (A2B a) = a) -> (forall b1 b2, B2A b1 = B2A b2 -> b1 = b2) -> iso A B.\nProof.\n  intros.\n  econstructor.\n  - intros.\n    apply H.\n  - intros.\n    simpl.\n    apply H0.\n    rewrite H.\n    easy.\nQed.\n\nFixpoint isosi (n : nat) : (nat # nat) :=\n  match n with\n    | 0 => (0, 0)\n    | S m => match isosi m with\n              | (0, a) => (S a, 0)\n              | (S b, a) => (b, S a)\n             end\n  end.\n\nFixpoint summy (n : nat) : nat :=\n  match n with\n    | 0 => 0\n    | (S a) => n + summy a\n  end.\n\nDefinition osiso (nn : nat # nat) : nat :=\n  let '(a, b) := nn in b + summy (a + b).\n\n(* Task 1. Prove that nat has the same cardinality as nat * nat. *)\n\nLemma summy_inj_gen : forall n m k, k*n + summy n = k*m + summy m -> n = m.\nProof.\n  fix H 1.\n  intros.\n  destruct n.\n  - simpl in *.\n    destruct m.\n    easy.\n    simpl in H0.\n    lia.\n  - destruct m.\n    simpl in H0.\n    lia.\n    simpl in H0.\n    f_equal.\n    apply (H n m (S k)).\n    simpl.\n    lia.\nQed.\n\nLemma summy_inj : forall n m, summy n = summy m -> n = m.\nProof.\n  intros.\n  pose proof (summy_inj_gen n m 0).\n  simpl in H0.\n  auto.\nQed.\n\nTheorem nat_iso_natxnat : iso nat (nat # nat).\nProof.\n  apply (bijection_alt _ _ isosi osiso).\n  - intros.\n    induction a.\n    * easy.\n    * simpl.\n      destruct (isosi a).\n      destruct n.\n      simpl in *.\n      rewrite Nat.add_0_r.\n      lia.\n      simpl in *.\n      rewrite (Nat.add_comm n (S n0)).\n      simpl.\n      rewrite (Nat.add_comm n0 n).\n      lia.\n  - intros.\n    unfold osiso in *.\n    destruct b1, b2.\n    revert n n0 n1 n2 H.\n    fix H 1.\n    intros.\n\n\n\n\n(* Task 2. Prove that nat has the same cardinality as nat ^ n, where n is nonzero and finite. *)\n\nTheorem nat_iso_nat_power : forall n, iso nat (nat ^^ S n).\nProof. Admitted.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/bijec2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7315734779914247}}
{"text": "Require Export floyd.sublist.\nRequire Export Integers.\nRequire Export Coqlib.\nRequire Export List. Import ListNotations.\nRequire Export aes.sbox.\n\n(* substitute b for its counterpart in the sbox *)\nDefinition look_sbox (b: int) : int :=\n  (* All possible values of b are covered in the sbox so the default should never be returned *)\n  Int.repr (Znth (Int.unsigned b) sbox 0).\n\n(* substitute b for its counterpart in the inverse sbox *)\nDefinition look_inv_sbox (b: int) : int :=\n  Int.repr (Znth (Int.unsigned b) inv_sbox 0).\n\n(********************* GF(256) arithmetic *******************)\n\n(* xtime operation from section 4.2.1. Corresponds to multiplying by 2 in GF(256) *)\nDefinition xtime (b: int) : int :=\n  let b' := Int.modu (Int.shl b (Int.one)) (Int.repr 256) in (* shift left by one, mod 256 *)\n  let c_1b := Int.repr 27 in (* 0x1b *)\n  let c_80 := Int.repr 128 in (* 0x80 *)\n  (* test if highest bit of b is one. If so, then XOR b' with 0x1b, otherwise return b' *)\n  if Int.eq (Int.and b c_80) Int.zero then b'\n  else Int.xor b' c_1b.\n\n(* Finite field multiplication using xtime operation and xor for finite field addition\n * (Russian peasant multiplication), not described directly but suggested in section 4.2.1. *)\n\n(* Repeatedly double b using xtime as per Russian peasant multiplication. Add b to accumulator\n * if there is a \"remainder,\" i.e., the tested bit of a is 1 *)\nDefinition ff_checkbit (a b : int) (acc : int) : int :=\n  (* if lowest bit of a is one, add (xor) b to acc. Otherwise do nothing *)\n  if Int.eq (Int.and a Int.one) Int.zero then acc\n  else Int.xor acc b.\n\nFixpoint xtime_test (a b : int) (acc : int) (shifts : nat) : int :=\n  if Int.eq a Int.zero then acc (* if a or b are zero, nothing to do *)\n  else if Int.eq b Int.zero then acc\n  else\n    (* check lowest bit of a, add b to acc if it is positive. Shift a\n     * right for next iteration unless we're finished *)\n    match shifts with\n    | S n =>\n      let acc' := ff_checkbit a b acc in\n      (* shift a right and double b *)\n      let a' := Int.shru a Int.one in\n      let b' := xtime b in\n      xtime_test a' b' acc' n\n    | O => acc\n    end.\n\nDefinition ff_mult (a b : int) : int := xtime_test a b Int.zero 8%nat.\n\n(******************************************************************************************)\n\n\n(* Defining words and state as they are considered in the specification, using tuples\n * to enforce the length requirement -- a word is 4 bytes, while a state is 4 words,\n * illustrated as 4 rows of 4 bytes *)\nDefinition word := (int * int * int * int) % type.\nDefinition state := (word * word * word * word) % type.\nDefinition block := state%type. (* Used synonymously with state in the spec, aliased here for readability *)\n\n(* SubBytes() transformation described in section 5.1.1 *)\nDefinition sub_word (w: word) : word :=\n  match w with (b1, b2, b3, b4) => (look_sbox b1, look_sbox b2, look_sbox b3, look_sbox b4) end.\nDefinition SubBytes (s: state) : state :=\n  match s with (w1, w2, w3, w4) => (sub_word w1, sub_word w2, sub_word w3, sub_word w4) end.\n\n(* ShiftRows() transformation described in section 5.1.2 *)\nDefinition ShiftRows (s : state) : state :=\n  match s with\n  ((b11, b12, b13, b14),\n   (b21, b22, b23, b24),\n   (b31, b32, b33, b34),\n   (b41, b42, b43, b44)) =>\n\n  ((b11, b12, b13, b14),\n   (b22, b23, b24, b21),\n   (b33, b34, b31, b32),\n   (b44, b41, b42, b43))\n  end.\n\n(* MixColumns() transformation described in section 5.1.3 *)\n\nDefinition transform_column (col: word) : word :=\n  match col with (b1, b2, b3, b4) =>\n    let two := Int.repr 2 in\n    let three := Int.repr 3 in\n    (* (2*b1)^(3*b2)^b3^b4 *)\n    let c0 := Int.xor (Int.xor (ff_mult two b1) (ff_mult three b2)) (Int.xor b3 b4) in\n    (* b1^(2*b2)^(3*b3)^b4 *)\n    let c1 := Int.xor (Int.xor b1 (ff_mult two b2)) (Int.xor (ff_mult three b3) b4) in\n    (* b1^b2^(2*b3)^(3*b4)*)\n    let c2 := Int.xor (Int.xor b1 b2) (Int.xor (ff_mult two b3) (ff_mult three b4)) in\n    (* (3*b1)^b2^b3^(2*b4)*)\n    let c3 := Int.xor (Int.xor (ff_mult three b1) b2) (Int.xor b3 (ff_mult two b4)) in\n    (c0, c1, c2, c3)\n  end.\n\n(* lets us treat state by columns rather than rows *)\nDefinition transpose (s: state) : state :=\n  match s with\n   ((b11, b12, b13, b14),\n    (b21, b22, b23, b24),\n    (b31, b32, b33, b34),\n    (b41, b42, b43, b44)) =>\n\n   ((b11, b21, b31, b41),\n    (b12, b22, b32, b42),\n    (b13, b23, b33, b43),\n    (b14, b24, b34, b44))\nend.\n\n(* apply column transformation to each column in the state *)\nDefinition MixColumns (s: state) : state :=\n  let cols := transpose s in\n  match cols with (c1, c2, c3, c4) =>\n    transpose (transform_column c1, transform_column c2, transform_column c3, transform_column c4)\n  end.\n\n(* Key expansion functions, section 5.2 *)\n\n(* SubWord function from section 5.2: apply S-box to each byte in a word *)\nDefinition SubWord (w: word) : word :=\n  match w with (b1, b2, b3, b4) => (look_sbox b1, look_sbox b2, look_sbox b3, look_sbox b4) end.\n\n(* RotWord function from section 5.2: rotate bytes left, wrapping around *)\nDefinition RotWord (w: word) : word :=\n  match w with (b1, b2, b3, b4) => (b2, b3, b4, b1) end.\n\n(* round constant (RCon) array, described in section 5.2 and explicitly written\n * out in appendix A.3 (256-bit key expansion example) *)\nDefinition RCon : list word := [\n  (* 0x01000000 *) (Int.repr 1, Int.zero, Int.zero, Int.zero);\n  (* 0x02000000 *) (Int.repr 2, Int.zero, Int.zero, Int.zero);\n  (* 0x04000000 *) (Int.repr 4, Int.zero, Int.zero, Int.zero);\n  (* 0x08000000 *) (Int.repr 8, Int.zero, Int.zero, Int.zero);\n  (* 0x10000000 *) (Int.repr 16, Int.zero, Int.zero, Int.zero);\n  (* 0x20000000 *) (Int.repr 32, Int.zero, Int.zero, Int.zero);\n  (* 0x40000000 *) (Int.repr 64, Int.zero, Int.zero, Int.zero)\n].\n\n(* For AES-256, figure 4 fixes the key length in words at 8 and the number\n * of rounds at 14 *)\nDefinition Nk := 8. (* number of words in key *)\nDefinition Nr := 14. (* number of cipher rounds *)\nDefinition Nb := 4. (* number of words in a block (state) *)\n\n(* xor two words together, i.e., apply xor byte by byte *)\nDefinition xor_word (w1 w2 : word) : word :=\n  match w1, w2 with (b1, b2, b3, b4), (b1', b2', b3', b4') =>\n    (Int.xor b1 b1', Int.xor b2 b2', Int.xor b3 b3', Int.xor b4 b4')\n  end.\n\n(* Expanded key is Nb*(Nr+1) words, or Nr+1 blocks *)\nDefinition extended_key_blocks := Nr+1.\n\n(* Based on Figure 11 and diagram in appendex A.3 *)\n\n(* Note that \"even\" and \"odd\" are if you start counting blocks at 1, rather than 0 *)\n(* b1 and b2 are the two blocks generated before this round. *)\nDefinition odd_round (b1 b2 : block) (rcon: word) : block :=\n  match b1, b2 with (w1, w2, w3, w4), (_, _, _, w8) =>\n    let w1' := xor_word w1 (xor_word (SubWord (RotWord w8)) rcon) in\n    let w2' := xor_word w2 w1' in\n    let w3' := xor_word w3 w2' in\n    let w4' := xor_word w4 w3' in\n    (w1', w2', w3', w4')\n  end.\nDefinition even_round (b1 b2: block) : block :=\n  match b1, b2 with (w1, w2, w3, w4), (_, _, _, w8) =>\n    let w1' := xor_word w1 (SubWord w8) in\n    let w2' := xor_word w2 w1' in\n    let w3' := xor_word w3 w2' in\n    let w4' := xor_word w4 w3' in\n    (w1', w2', w3', w4')\n  end.\n\nFixpoint grow_key (b1 b2: block) (rcs: list word) : list block :=\n  match rcs with\n  | rc :: [] =>\n    (* for the last round constant, only apply an odd round *)\n    (odd_round b1 b2 rc) :: []\n  | rc :: tl =>\n    (* generate a block with an odd round, use it in the next even round and keep going *)\n    let b3 := odd_round b1 b2 rc in\n\tlet b4 := even_round b2 b3 in\n\tb3 :: b4 :: (grow_key b3 b4 tl)\n  | [] => [] (* should not happen *)\n  end.\n\n(* Note that RCon list (round constants) is described in section 5.2 and its values are given in A.3.\n * k should be a list of words of length Nk. Returns a list of blocks of length Nr+1 *)\nDefinition KeyExpansion (k : list word) : list block :=\n  match k with\n  | [w1; w2; w3; w4; w5; w6; w7; w8] =>\n    let b1 := (w1, w2, w3, w4) in\n\tlet b2 := (w5, w6, w7, w8) in\n\tb1 :: b2 :: (grow_key b1 b2 RCon)\n  | l => [] (* should not happen *)\n  end.\n\n(* AddRoundKey() described in section 5.1.4: it uses a block from the expanded key, xoring\n * each word from the expanded key block with a column from the state *)\nDefinition AddRoundKey (s : state) (kb : block) : state :=\n  let cols := transpose s in\n  match cols, kb with (c1,c2,c3,c4), (k1,k2,k3,k4) =>\n    transpose (xor_word c1 k1, xor_word c2 k2, xor_word c3 k3, xor_word c4 k4)\n  end.\n\n(* Based on figure 5, description of the cipher *)\nDefinition round (s : state) (kb: block) : state :=\n  AddRoundKey (MixColumns (ShiftRows (SubBytes s))) kb.\n(* omits mix columns step *)\nDefinition last_round (s : state) (kb : block) : state :=\n  AddRoundKey (ShiftRows (SubBytes s)) kb.\n\n(* Applies cipher rounds given an expanded key *)\nFixpoint apply_rounds (s : state) (ek: list block) : state :=\n  match ek with\n  | rk :: [] => last_round s rk (* last round *)\n  | rk :: tl => apply_rounds (round s rk) tl\n  | [] => s (* should not happen *)\n  end.\n\n(* exp_key should be length Nr+1 blocks, produced by applying KeyExpansion on a valid key. *)\nDefinition Cipher (exp_key : list block) (init : state) : state :=\n  match exp_key with\n  | k1 :: tl =>\n    let r1 := AddRoundKey init k1 in\n\tapply_rounds r1 tl\n  | [] => init (* should not happen *)\n  end.\n\n(* Inverse cipher and inverse operations -- section 5.3 *)\n\n(* InvShiftRows in section 5.3.1 *)\nDefinition InvShiftRows (s: state) : state :=\n  match s with\n    ((b11, b12, b13, b14),\n     (b21, b22, b23, b24),\n\t (b31, b32, b33, b34),\n\t (b41, b42, b43, b44)) =>\n\t\n\t((b11, b12, b13, b14),\n\t (b24, b21, b22, b23),\n\t (b33, b34, b31, b32),\n\t (b42, b43, b44, b41))\n  end.\n\n(* InvSubBytes in section 5.3.2 *)\nDefinition inv_sub_word (w: word) : word :=\n  match w with (b1, b2, b3, b4) =>\n    (look_inv_sbox b1, look_inv_sbox b2, look_inv_sbox b3, look_inv_sbox b4)\n  end.\n\nDefinition InvSubBytes (s : state) : state :=\n  match s with (w1, w2, w3, w4) =>\n    (inv_sub_word w1, inv_sub_word w2, inv_sub_word w3, inv_sub_word w4)\n  end.\n\n(* InvMixColumns in 5.3.3 *)\nDefinition inv_transform_column (w: word) : word :=\n  let c_e := Int.repr 14 in (* 0x0e *)\n  let c_b := Int.repr 11 in (* 0x0b *)\n  let c_d := Int.repr 13 in (* 0x0d *)\n  let c_9 := Int.repr 9 in (* 0x09 *)\n  match w with (b1, b2, b3, b4) =>\n    (* (0x0e * b1) ^ (0x0b * b2) ^ (0x0d * b3) ^ (0x09 * b4) *)\n    let b1' := Int.xor (Int.xor (ff_mult c_e b1) (ff_mult c_b b2)) (Int.xor (ff_mult c_d b3) (ff_mult c_9 b4)) in\n    (* (0x09 * b1) ^ (0x0e * b2) ^ (0x0b * b3) ^ (0x0d * b4) *)\n    let b2' := Int.xor (Int.xor (ff_mult c_9 b1) (ff_mult c_e b2)) (Int.xor (ff_mult c_b b3) (ff_mult c_d b4)) in\n    (* (0x0d * b1) ^ (0x09 * b2) ^ (0x0e * b3) ^ (0x0b * b4) *)\n    let b3' := Int.xor (Int.xor (ff_mult c_d b1) (ff_mult c_9 b2)) (Int.xor (ff_mult c_e b3) (ff_mult c_b b4)) in\n    (* (0x0b * b1) ^ (0x0d * b2) ^ (0x09 * b3) ^ (0x0e * b4) *)\n    let b4' := Int.xor (Int.xor (ff_mult c_b b1) (ff_mult c_d b2)) (Int.xor (ff_mult c_9 b3) (ff_mult c_e b4)) in\n    (b1', b2', b3', b4')\n  end.\n\nDefinition InvMixColumns (s : state) : state :=\n  let cols := transpose s in\n  match cols with (c1, c2, c3, c4) =>\n    transpose (inv_transform_column c1, inv_transform_column c2, inv_transform_column c3, inv_transform_column c4)\n  end.\n\n(* applies InvMixColumns to all members of expanded key but the last *)\nFixpoint grow_inv_key (ek : list block) : list block :=\n  match ek with\n  | rk :: [] => rk :: [] (* don't do anything to last one *)\n  | rk :: tl => InvMixColumns rk :: grow_inv_key tl\n  | [] => [] (* should not happen *)\n  end.\n\n(* Inverse key expansion briefly described at end of figure 15. k should be of length Nk. *)\nDefinition InverseKeyExpansion (k : list word) : list block :=\n  let exp_key := KeyExpansion k in\n  match exp_key with\n  (* don't apply inv mix columns to first round key either *)\n  | k1 :: tl => k1 :: grow_inv_key tl\n  | ek => [] (* should not happen *)\n  end.\n\n(* Inverse cipher described in figure 15 *)\nDefinition inv_round (s : state) (kb : block) : state :=\n  AddRoundKey (InvMixColumns (InvShiftRows (InvSubBytes s))) kb.\n(* omits mix columns *)\nDefinition inv_last_round (s : state) (kb : block) : state :=\n  AddRoundKey (InvShiftRows (InvSubBytes s)) kb.\n\nFixpoint apply_inv_rounds (s: state) (ek: list block) : state :=\n  match ek with\n  | kb :: [] => inv_last_round s kb\n  | kb :: tl => apply_inv_rounds (inv_round s kb) tl\n  | [] => s (* should not happen *)\n  end.\n\n(* exp_key should be length Nr+1 blocks, produced by applying InverseKeyExpansion on a valid\n * key and reversing the result, since the round keys are supposed to be applied starting with\n * the last. (We pass the key in this way for simplifying verification, since the implementation's\n * key expansion process also reverses the key, whereas the specification reverses it during the\n * decryption process) *)\nDefinition EqInvCipher (exp_key: list block) (init: state) : state :=\n  match exp_key with\n  | kb :: tl => apply_inv_rounds (AddRoundKey init kb) tl\n  | l => init (* should not happen *)\n  end.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/aes/spec_AES256_HL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7315734761093495}}
{"text": "Require Export A_2_2.\n\nModule A2_3.\n\n(* 2.3 数列极限存在的条件 *)\n\n(* 定义:单调增数列 *)\nDefinition IncreaseSeq (x : Seq) : Prop :=\n    IsSeq x /\\ (∀ n : nat, x[n] <= x[S n]).\n\n(* 定义:单调减数列 *)\nDefinition DecreaseSeq (x : Seq) : Prop :=\n    IsSeq x /\\ (∀ n : nat, x[n] >= x[S n]).\n\n(* 定义: 单调数列 *)\nDefinition MonotonicSeq (x : Seq) : Prop := IncreaseSeq x \\/ DecreaseSeq x.\n\n(* 定理:单调增数列的等价性 *)\nTheorem EqualIncrease : ∀ (x : Seq), IncreaseSeq x <->\n  (IsSeq x /\\ (∀ (n1 n2 : nat), (n1 < n2)%nat -> x[n1] <= x[n2])).\nProof.\n  intro x; split; intro H0.\n  - destruct H0 as [H0 H1]. split; auto. intros n1 n2.\n    induction n2 as [|n2 IHn2].\n    + intro H2. exfalso. apply (Nat.nlt_0_r n1). auto.\n    + destruct (Nat.lt_total n1 n2) as [H2 | [H2 | H2]]; intro H3.\n      * apply Rle_trans with (r2 := x[n2]); auto.\n      * rewrite <- H2. auto.\n      * apply lt_n_Sm_le in H3. exfalso. apply lt_not_le in H2. auto.\n  - destruct H0 as [H0 H1]. split; auto.\nQed.\n\n(* 定理:单调减数列的等价性 *)\nTheorem EqualDecrease : ∀ (x : Seq), DecreaseSeq x <->\n  (IsSeq x /\\ (∀ (n1 n2 : nat), (n1 < n2)%nat -> x[n1] >= x[n2])).\nProof.\n  intro x; split; intro H0.\n  - destruct H0 as [H0 H1]. split; auto. intros n1 n2.\n    induction n2 as [|n2 IHn2].\n    + intro H2. exfalso. apply (Nat.nlt_0_r n1). auto.\n    + destruct (Nat.lt_total n1 n2) as [H2 | [H2 | H2]]; intro H3.\n      * apply Rge_trans with (r2 := x[n2]); auto.\n      * rewrite <- H2. auto.\n      * apply lt_n_Sm_le in H3. exfalso. apply lt_not_le in H2. auto.\n  - destruct H0 as [H0 H1]. split; auto.\nQed.\n\n(* 定义: 有界数列 *)\nDefinition BoundedSeq (x : Seq) : Prop := IsSeq x /\\\n  (∃ M, ∀ n, Abs[x[n]] <= M).\n\n(* 定理2.9 单调有界定理 *)\nTheorem Theorem2_9 : ∀ (x : Seq), MonotonicSeq x ->\n  BoundedSeq x -> Convergence x.\nProof.\n  intros x H0 H1. destruct H1 as [H [M H1]].\n  assert (H2 : IsSeq x).\n  { destruct H0 as [H0 | H0]; apply H0. }\n  destruct H2 as [H2 H3].\n  assert (H4 : NotEmpty ran[x]).\n  { unfold NotEmpty. exists (x[0%nat]). apply fx_ran; auto.\n    rewrite H3. apply AxiomII. auto. }\n  apply Sup_inf_principle in H4 as H5. destruct H5 as [H5 H6].\n  destruct H0 as [H0 | H0].\n  - assert (H7 : ∃M : R,Upper ran[x] M).\n    { exists M. unfold Upper. intros xn I1. applyAxiomII I1.\n      destruct I1 as [n I1]. apply f_x in I1 as I2; auto.\n      rewrite <- I2. generalize (H1 n). intro I3.\n      apply Abs_le_R in I3. apply I3. }\n    apply H5 in H7 as H8. destruct H8 as [a H8]. exists a. unfold sup in H8.\n    destruct H8 as [H8 H9]. unfold limit_seq. repeat split; auto.\n    intros ε H10. assert (H11 : a - ε < a).\n    { apply Ropp_lt_gt_0_contravar in H10 as H11.\n      apply Rplus_lt_compat_l with (r := a) in H11 as H12.\n      rewrite Rplus_0_r in H12. auto. }\n    apply H9 in H11 as H12. destruct H12 as [xN [H12 H13]].\n    applyAxiomII H12. destruct H12 as [N H12]. exists N.\n    apply EqualIncrease in H0 as H14. destruct H14 as [H14 H15].\n    apply f_x in H12 as H16; auto. rewrite <- H16 in H13.\n    intros n H17. apply H15 in H17 as H18.\n    apply Rlt_le_trans with (r1 := a - ε) in H18 as H19; auto.\n    apply Abs_R. unfold Upper in H8. assert (H20 : x[n] ∈ ran[x]).\n    { apply fx_ran; auto. rewrite H3. apply AxiomII. auto. }\n    apply H8 in H20 as H21. assert (H22 : a < a + ε).\n    { apply Rplus_lt_compat_l with (r := a) in H10.\n      rewrite Rplus_0_r in H10. auto. }\n    assert (H24 : x[n] < a + ε).\n    { apply Rle_lt_trans with (r2 := a); auto. }\n    split.\n    + apply Rplus_lt_reg_l with (r := a).\n      assert (H23 : a + (x [n] - a) = x[n]). field. rewrite H23. auto.\n    + apply Rplus_lt_reg_l with (r := a).\n      assert (H23 : a + (x [n] - a) = x[n]). field. rewrite H23. auto.\n  - assert (H7 : ∃L : R,Lower ran[ x] L).\n    { exists (-M). unfold Lower. intros xn I1. applyAxiomII I1.\n      destruct I1 as [n I1]. apply f_x in I1 as I2; auto.\n      rewrite <- I2. generalize (H1 n). intro I3.\n      apply Abs_le_R in I3. apply Rle_ge. apply I3. }\n    apply H6 in H7 as H8. destruct H8 as [a H8]. exists a. unfold inf in H8.\n    destruct H8 as [H8 H9]. unfold limit_seq. repeat split; auto.\n    intros ε H10. assert (H11 : a < a + ε).\n    { apply Rplus_lt_compat_l with (r := a) in H10 as H12.\n      rewrite Rplus_0_r in H12. auto. }\n    apply H9 in H11 as H12. destruct H12 as [xN [H12 H13]].\n    applyAxiomII H12. destruct H12 as [N H12]. exists N.\n    apply EqualDecrease in H0 as H14. destruct H14 as [H14 H15].\n    apply f_x in H12 as H16; auto. rewrite <- H16 in H13.\n    intros n H17. apply H15 in H17 as H18. apply Rge_le in H18.\n    apply Rle_lt_trans with (r3 := a + ε) in H18 as H19; auto.\n    apply Abs_R. unfold Lower in H8. assert (H20 : x[n] ∈ ran[x]).\n    { apply fx_ran; auto. rewrite H3. apply AxiomII. auto. }\n    apply H8 in H20 as H21. assert (H22 : a - ε < a).\n    { apply Ropp_lt_gt_0_contravar in H10 as H22.\n      apply Rplus_lt_compat_l with (r := a) in H22.\n      rewrite Rplus_0_r in H22. auto. }\n    assert (H24 : a - ε < x[n]).\n    { apply Rlt_le_trans with (r2 := a); auto. apply Rge_le. auto. }\n    split.\n    + apply Rplus_lt_reg_l with (r := a).\n      assert (H23 : a + (x [n] - a) = x[n]). field. rewrite H23. auto.\n    + apply Rplus_lt_reg_l with (r := a).\n      assert (H23 : a + (x [n] - a) = x[n]). field. rewrite H23. auto.\nQed.\n\n\n(* 定义: 数列 x 第 n 项之后的最大项 *)\nDefinition Max_Seq_n (x : Seq) (n m : nat) :=\n  IsSeq x /\\ (n <= m)%nat /\\ (∀ (i : nat), (n <= i)%nat -> x[i] <= x[m]).\n\nFixpoint Fun_Lemma2_10 (x : Seq) (n : nat) :=\n  match n with\n  | 0%nat => cN \\{ λ (m : nat), Max_Seq_n x 1%nat m \\}\n  | S n => cN \\{ λ (m : nat), Max_Seq_n x (S (Fun_Lemma2_10 x n)) m \\}\n  end.\n\nFixpoint Fun_Lemma2_10' (x : Seq) (n k : nat) :=\n  match n with\n  | 0%nat => k\n  | S n => cN \\{ λ (m : nat), (m > (Fun_Lemma2_10' x n k))%nat /\\\n      x[m] > x[Fun_Lemma2_10' x n k] \\}\n  end.\n\n(* 定理: 任何数列都存在单调子列 *)\n\n(* 引理2-10-1: x是有界数列,y是x的子列,推得y是有界数列 *)\nLemma Lemma2_10_1 : ∀ (x y : Seq), BoundedSeq x ->\n    SubSeq x y -> BoundedSeq y.\nProof.\n  intros x y H0 H1. unfold BoundedSeq in *. unfold SubSeq in H1.\n  destruct H0 as [H0 H2]. destruct H1 as [H1 [H3 [f [H4 [H5 H6]]]]].\n  clear H1. split; auto. destruct H2 as [M H2].\n  exists M. intro n. rewrite H6. apply H2.\nQed.\n\n(* 引理2-10-2: 数列x存在一个最大项x[k] *)\nLemma Lemma2_10_2 : ∀ (x : Seq) (m n : nat), IsSeq x -> (m >= n)%nat ->\n  (∃ (k : nat), (k >= n)%nat /\\ (k <= m)%nat  /\\ (∀ (i : nat), (i >= n)%nat ->\n  (i <= m)%nat -> x[i] <= x[k] )).\nProof.\n  intros x m n H0 H1. induction m as [|m IHm].\n  - apply le_n_0_eq in H1. rewrite <- H1. exists 0%nat. repeat split; auto.\n    intros i I1 I2. apply le_n_0_eq in I2. rewrite I2. right. reflexivity.\n  - generalize (Nat.lt_ge_cases m n). intro H2.\n    destruct H2 as [H2 | H2].\n    + apply lt_le_S in H2. apply Nat.le_antisymm in H2 as H3; auto.\n      rewrite <- H3. exists n. repeat split; auto. intros i I1 I2.\n      apply Nat.le_antisymm in I2 as I3; auto. rewrite I3.\n      right; reflexivity.\n    + apply IHm in H2 as H3. destruct H3 as [k [H3 [H4 H5]]].\n      generalize (Rlt_or_le x[k] x[S m]). intro H6.\n      destruct H6 as [H6 | H6].\n      * exists (S m). repeat split; auto. intros i H7 H8.\n        apply le_lt_or_eq in H8. destruct H8 as [H8 | H8].\n        -- apply lt_n_Sm_le in H8. generalize (H5 i H7 H8). intro H9.\n          apply Rlt_le. apply Rle_lt_trans with (r2 := x[k]); auto.\n        -- rewrite H8. right; reflexivity.\n      * exists k. repeat split; auto. intros i H7 H8.\n        apply le_lt_or_eq in H8. destruct H8 as [H8 | H8].\n        -- apply lt_n_Sm_le in H8. auto.\n        -- rewrite H8. apply H6.\nQed.\n\n(* 引理2-10-3: x是一个数列,存在一个y数列是x的子列,且这个子列是单调数列 *)\nLemma Lemma2_10_3 : ∀ (x : Seq), IsSeq x ->\n  (∃ (y : Seq), SubSeq x y /\\ MonotonicSeq y).\nProof.\n  intros x H0. destruct classic with (P := ∀ (k : nat),\n    ∃ (m : nat), Max_Seq_n x k m) as [H1 | H1].\n  - assert (H2 : ∃ (y : Seq), y = {` λ n v, v = x [Fun_Lemma2_10 x n] `}).\n    { exists {` λ n v, v = x [Fun_Lemma2_10 x n] `}; auto. }\n    destruct H2 as [y H2]. exists y.\n    assert (H3 : ∀ (n : nat),\n      ((Fun_Lemma2_10 x n) < (Fun_Lemma2_10 x (S n)))%nat).\n    { intro n. induction n as [|n IHn].\n      - simpl. assert (I1 :  cN \\{ λ m : nat, Max_Seq_n x (S (cN \\{ λ m0 : nat,\n        Max_Seq_n x 1 m0 \\})) m \\} ∈ \\{ λ m : nat, Max_Seq_n x\n        (S (cN \\{ λ m0 : nat, Max_Seq_n x 1 m0 \\})) m \\}).\n        { apply AxiomcN. unfold NotEmpty.\n          generalize (H1 (S (cN \\{ λ m0 : nat, Max_Seq_n x 1 m0 \\}))).\n          intro I1. destruct I1 as [m I1]. exists m.\n          apply <- AxiomII. auto. }\n        applyAxiomII I1. destruct I1 as [I1 [I2 I3]].\n        apply le_S_gt in I2. auto.\n      - simpl. assert (I1 : cN \\{ λ m : nat, Max_Seq_n x\n          (S (cN \\{ λ m0 : nat, Max_Seq_n x (S (Fun_Lemma2_10 x n)) m0 \\})) m \\}\n              ∈ \\{ λ m : nat, Max_Seq_n x (S (cN \\{ λ m0 : nat,\n           Max_Seq_n x (S (Fun_Lemma2_10 x n)) m0 \\})) m \\}).\n        { apply AxiomcN. unfold NotEmpty. generalize (H1 (S (cN \\{ λ m0 : nat,\n          Max_Seq_n x (S (Fun_Lemma2_10 x n)) m0 \\}))). intro I1.\n          destruct I1 as [m I1]. exists m. apply AxiomII. auto. }\n        applyAxiomII I1. destruct I1 as [I1 [I2 I3]].\n        apply le_S_gt in I2. auto. }\n    assert (H4 : ∃ f, f = {` λ n v, v = Fun_Lemma2_10 x n `}).\n    { exists {` λ n v, v = Fun_Lemma2_10 x n `}; auto. }\n    destruct H4 as [f H4]. assert (H5 : StrictlyIncreaseFun_nat f).\n    { assert (I1 : Function f).\n      { unfold Function. intros x0 y0 z0 I1 I2. rewrite H4 in *.\n        applyAxiomII' I1. applyAxiomII' I2. rewrite I2. auto. }\n      split; auto. intros x1 y1 x2. induction x2 as [|x2 IHx2].\n      - intros y2 I2 I3 I4. exfalso. apply (Nat.nlt_0_r x1). auto.\n      - destruct (Nat.lt_total x1 x2) as [I2 | [I2 | I2]]; intros y2 I3 I4 I5.\n        + assert (I6 : [x2, f\\[x2\\]] ∈ f).\n          { apply x_fx_N; auto. apply AxiomII.\n            exists (Fun_Lemma2_10 x x2). rewrite H4. apply AxiomII'.\n            auto. }\n          apply Nat.lt_trans with (m := f\\[x2\\]).\n          * apply IHx2; auto.\n          * rewrite H4 in I4. apply -> AxiomII' in I4; lazy beta in I4.\n            pattern f at 2 in I6. rewrite H4 in I6. applyAxiomII' I6.\n            rewrite I6. rewrite I4. apply H3.\n        + rewrite <- I2 in *. rewrite H4 in I3. applyAxiomII' I3.\n          rewrite H4 in I4. apply -> AxiomII' in I4. lazy beta in I4.\n          rewrite I3; rewrite I4. apply H3.\n        + apply lt_n_Sm_le in I5. exfalso. apply lt_not_le in I2. auto. }\n    assert (H6 : IsSeq y).\n    { split.\n      - unfold Function. intros x0 y0 z0 I1 I2. rewrite H2 in *.\n        applyAxiomII' I1. applyAxiomII' I2. rewrite I2. auto.\n      - apply AxiomI; intro z; split; intro I1.\n        + apply AxiomII. auto.\n        + apply AxiomII. exists (x[Fun_Lemma2_10 x z]).\n          rewrite H2. apply AxiomII'. auto. }\n    assert (H7 : dom[f] = Full nat).\n    { apply AxiomI; intro z; split; intro I1.\n      - apply AxiomII. auto.\n      - apply AxiomII. exists (Fun_Lemma2_10 x z).\n        rewrite H4. apply AxiomII'. auto. }\n    split.\n    + unfold SubSeq. split; auto; split; auto. exists f.\n      split; auto; split; auto.\n      intro n. assert (I1 : n ∈ dom[y]).\n      { destruct H6 as [H6 I1]. rewrite I1. apply AxiomII; auto. }\n      apply x_fx in I1 as I2; try apply H6. pattern y at 2 in I2.\n      rewrite H2 in I2. applyAxiomII' I2. rewrite I2.\n      assert (I3 : n ∈ dom[f]).\n      { rewrite H7. apply AxiomII; auto. }\n      apply x_fx_N in I3 as I4; try apply H5. pattern f at 2 in I4.\n      rewrite H4 in I4. applyAxiomII' I4. rewrite I4. reflexivity.\n    + unfold MonotonicSeq. right. unfold DecreaseSeq. split; auto.\n      intro n. assert (I1 : ∀ m : nat, m ∈ dom[y]).\n      { intro m. destruct H6 as [H6 I1]. rewrite I1. apply AxiomII; auto. }\n      generalize (I1 n). intro I2. generalize (I1 (S n)). intro I3.\n      apply x_fx in I2 as I4; try apply H6.\n      apply x_fx in I3 as I5; try apply H6.\n      pattern y at 2 in I4; rewrite H2 in I4.\n      pattern y at 2 in I5; rewrite H2 in I5.\n      applyAxiomII' I4. apply -> AxiomII' in I5. lazy beta in I5.\n      destruct n as [|n].\n      * assert (I6 : Max_Seq_n x 1%nat (Fun_Lemma2_10 x 0)).\n        { assert (I6 : (Fun_Lemma2_10 x 0) ∈\n            \\{ λ (m : nat), Max_Seq_n x 1%nat m \\}).\n          { simpl. apply AxiomcN. unfold NotEmpty. generalize (H1 1%nat).\n            intro I6. destruct I6 as [m I6]. exists m. apply AxiomII.\n            apply I6. }\n          apply -> AxiomII in I6. lazy beta in I6. auto. }\n        rewrite I4. rewrite I5. unfold Max_Seq_n in I6.\n        destruct I6 as [I6 [I7 I8]].\n        assert (I9 : (1 <= (Fun_Lemma2_10 x 1))%nat).\n        { apply Nat.le_trans with (m := (Fun_Lemma2_10 x 0)); auto.\n          apply Nat.lt_le_incl. apply H3. }\n        apply I8 in I9. apply Rle_ge. auto.\n      * rewrite I4. rewrite I5.\n        assert (I6 : Max_Seq_n x (S (Fun_Lemma2_10 x n))\n          (Fun_Lemma2_10 x (S n))).\n        { assert (I6 : (Fun_Lemma2_10 x (S n)) ∈\n            \\{ λ (m : nat), Max_Seq_n x (S (Fun_Lemma2_10 x n)) m \\}).\n          { simpl Fun_Lemma2_10 at 1.\n            apply AxiomcN. unfold NotEmpty.\n            generalize (H1 (S (Fun_Lemma2_10 x n))).\n            intro I6. destruct I6 as [m I6]. exists m. apply AxiomII.\n            apply I6. }\n          apply -> AxiomII in I6. lazy beta in I6. auto. }\n        unfold Max_Seq_n in I6. destruct I6 as [I6 [I7 I8]].\n        assert (I9 : ((S (Fun_Lemma2_10 x n)) <=\n          (Fun_Lemma2_10 x (S (S n))))%nat).\n        { apply Nat.le_trans with (m := (Fun_Lemma2_10 x (S n))); auto.\n          apply Nat.lt_le_incl. apply H3. }\n        apply I8 in I9. apply Rle_ge. auto.\n  - apply not_all_ex_not in H1. destruct H1 as [k H1].\n    assert (H2 : ∀ m : nat, ~ (Max_Seq_n x k m)).\n    { apply not_ex_all_not. auto. }\n    assert (H3 : ∃ (y : Seq), y = {` λ n v, v = x[Fun_Lemma2_10' x n k] `}).\n    { exists {` λ n v, v = x[Fun_Lemma2_10' x n k] `}; auto. }\n    destruct H3 as [y H3]. exists y.\n    assert (H4 : ∀ (n1 : nat), (n1 >= k)%nat ->\n      (∃ (n2 : nat), (n2 > n1)%nat /\\ x[n2] > x[n1])).\n    { intros n1 I1. apply not_all_not_ex. intro I2. apply H1.\n      generalize (Lemma2_10_2 x n1 k H0 I1). intro I3.\n      destruct I3 as [m [I3 [I4 I5]]].\n      exists m. unfold Max_Seq_n. split; auto; split; auto.\n      intros i I6. generalize (Nat.lt_ge_cases n1 i). intro I7.\n      destruct I7 as [I7 | I7]; auto.\n      generalize (I2 i). intro I8. apply not_and_or in I8.\n      destruct I8 as [I8 | I8]; [exfalso | idtac]; auto.\n      apply Rnot_gt_le in I8. apply Rle_trans with (r2 := x[n1]); auto. }\n    assert (H5 : ∀ (n : nat), ((Fun_Lemma2_10' x n k) >= k)%nat).\n    { intro n. induction n as [|n IHn].\n      - simpl. auto.\n      - assert (I1 : (Fun_Lemma2_10' x (S n) k) ∈ \\{ λ (m : nat),\n          (m > (Fun_Lemma2_10' x n k))%nat /\\\n           x[m] > x[Fun_Lemma2_10' x n k] \\}).\n        { apply AxiomcN. unfold NotEmpty. apply H4 in IHn as I1.\n          destruct I1 as [m [I1 I2]]. exists m. apply AxiomII.\n          split; auto. }\n        apply -> AxiomII in I1. lazy beta in I1. destruct I1 as [I1 I2].\n        apply Nat.lt_le_incl. eapply Nat.le_lt_trans; eauto. }\n    assert (H6 : ∀ (n : nat),\n      ((Fun_Lemma2_10' x n k) < (Fun_Lemma2_10' x (S n) k))%nat).\n    { intro n.\n      assert (I1 : (Fun_Lemma2_10' x (S n) k) ∈ \\{ λ (m : nat),\n        (m > (Fun_Lemma2_10' x n k))%nat /\\\n        x[m] > x[Fun_Lemma2_10' x n k] \\} ).\n      { apply AxiomcN. unfold NotEmpty.\n        generalize (H4 (Fun_Lemma2_10' x n k) (H5 n)). intro I1.\n        destruct I1 as [n2 [I1 I2]]. exists n2. apply AxiomII.\n        split; auto. }\n      apply -> AxiomII in I1. lazy beta in I1. apply I1. }\n    assert (H7 : ∃ f, f = {` λ n v, v = Fun_Lemma2_10' x n k `}).\n    { exists {` λ n v, v = Fun_Lemma2_10' x n k `}; auto. }\n    destruct H7 as [f H7]. assert (H8 : StrictlyIncreaseFun_nat f).\n    { assert (I1 : Function f).\n      { unfold Function. intros x0 y0 z0 I1 I2. rewrite H7 in *.\n        applyAxiomII' I1. applyAxiomII' I2. rewrite I2. auto. }\n      split; auto. intros x1 y1 x2. induction x2 as [|x2 IHx2].\n      - intros y2 I2 I3 I4. exfalso. apply (Nat.nlt_0_r x1). auto.\n      - destruct (Nat.lt_total x1 x2) as [I2 | [I2 | I2]]; intros y2 I3 I4 I5.\n        + assert (I6 : [x2, f\\[x2\\]] ∈ f).\n          { apply x_fx_N; auto. apply AxiomII.\n            exists (Fun_Lemma2_10' x x2 k). rewrite H7. apply AxiomII'.\n            auto. }\n          apply Nat.lt_trans with (m := f\\[x2\\]).\n          * apply IHx2; auto.\n          * rewrite H7 in I4. apply -> AxiomII' in I4; lazy beta in I4.\n            pattern f at 2 in I6. rewrite H7 in I6. applyAxiomII' I6.\n            rewrite I6. rewrite I4. apply H6.\n        + rewrite <- I2 in *. rewrite H7 in I3. applyAxiomII' I3.\n          rewrite H7 in I4. apply -> AxiomII' in I4. lazy beta in I4.\n          rewrite I3; rewrite I4. apply H6.\n        + apply lt_n_Sm_le in I5. exfalso. apply lt_not_le in I2. auto. }\n    assert (H9 : IsSeq y).\n    { split.\n      - unfold Function. intros x0 y0 z0 I1 I2. rewrite H3 in *.\n        applyAxiomII' I1. applyAxiomII' I2. rewrite I2. auto.\n      - apply AxiomI; intro z; split; intro I1.\n        + apply AxiomII. auto.\n        + apply AxiomII. exists (x[Fun_Lemma2_10' x z k]).\n          rewrite H3. apply AxiomII'. auto. }\n    assert (H10 : dom[f] = Full nat).\n    { apply AxiomI; intro z; split; intro I1.\n      - apply AxiomII. auto.\n      - apply AxiomII. exists (Fun_Lemma2_10' x z k).\n        rewrite H7. apply AxiomII'. auto. }\n    split.\n    + unfold SubSeq. split; auto; split; auto. exists f.\n      split; auto; split; auto.\n      intro n. assert (I1 : n ∈ dom[y]).\n      { destruct H9 as [H9 I1]. rewrite I1. apply AxiomII; auto. }\n      apply x_fx in I1 as I2; try apply H9. pattern y at 2 in I2.\n      rewrite H3 in I2. applyAxiomII' I2. rewrite I2.\n      assert (I3 : n ∈ dom[f]).\n      { rewrite H10. apply AxiomII; auto. }\n      apply x_fx_N in I3 as I4; try apply H8. pattern f at 2 in I4.\n      rewrite H7 in I4. applyAxiomII' I4. rewrite I4. reflexivity.\n    + left. unfold IncreaseSeq. split; auto. intro n.\n      assert (I1 : ∀ m : nat, m ∈ dom[y]).\n      { intro m. destruct H9 as [H9 I1]. rewrite I1. apply AxiomII; auto. }\n      generalize (I1 n). intro I2. generalize (I1 (S n)). intro I3.\n      apply x_fx in I2 as I4; try apply H9.\n      apply x_fx in I3 as I5; try apply H9.\n      pattern y at 2 in I4. rewrite H3 in I4. applyAxiomII' I4.\n      pattern y at 2 in I5. rewrite H3 in I5.\n      apply -> AxiomII' in I5; lazy beta in I5.\n      rewrite I4; rewrite I5.\n      assert (I6 : (Fun_Lemma2_10' x (S n) k) ∈ \\{ λ (m : nat),\n        (m > (Fun_Lemma2_10' x n k))%nat /\\\n        x[m] > x[Fun_Lemma2_10' x n k] \\}).\n      { apply AxiomcN. generalize (H4 (Fun_Lemma2_10' x n k) (H5 n)).\n        intro I6. destruct I6 as [m [I6 I7]]. exists m.\n        apply AxiomII; split; auto. }\n      apply -> AxiomII in I6; lazy beta in I6.\n      destruct I6 as [I6 I7]. left; auto.\nQed.\n\n(* 定理2.10 致密性定理——有界数列必有收敛的子数列 *)\nTheorem Theorem2_10 : ∀ (x : Seq), BoundedSeq x ->\n  (∃ (y : Seq), SubSeq x y /\\ Convergence y).\nProof.\n  intros x H0. assert (H1 : ∀ (y : Seq), SubSeq x y -> BoundedSeq y).\n  { intro y. apply Lemma2_10_1. auto. }\n  destruct H0 as [H0 [M H2]]. apply Lemma2_10_3 in H0 as H3.\n  destruct H3 as [y [H3 H4]]. exists y. split; auto.\n  apply H1 in H3. apply Theorem2_9; auto.\nQed.\n\n(* 定理2.11 柯西收敛准则 *)\nTheorem Theorem2_11 : ∀ (x : Seq), IsSeq x ->\n  (Convergence x <-> (∀ ε, ε > 0 -> ∃ N : nat, ∀ (n m : nat),\n    (n > N)%nat -> (m > N)%nat -> Abs[x[n] - x[m]] < ε)).\nProof.\n  intros x H0. split.\n  - intros H1 ε H2. destruct H1 as [A H1]. assert (H3 : ε / 2 > 0).\n    { generalize (Rinv_0_lt_compat 2 Rlt_0_2). intro I1.\n      apply Rmult_gt_0_compat; auto. }\n    apply H1 in H3 as H4. destruct H4 as [N H4].\n    exists N. intros n m H5 H6. apply H4 in H5 as H7.\n    apply H4 in H6 as H8.\n    assert (H9 : Abs[x[n] - x[m]] <= Abs[x[n] - A] + Abs[x[m] - A]).\n    { assert (I1 : x[n] - x[m] = (x[n] - A) - (x[m] - A)). field.\n      rewrite I1. apply Abs_minus_le. }\n    apply Rle_lt_trans with (r2 := Abs[x[n] - A] + Abs[x[m] - A]); auto.\n    assert (H10 : ε = ε/2 + ε/2). field. rewrite H10.\n    apply Rplus_lt_compat; auto.\n  - intro H1. assert (H2 : BoundedSeq x).\n    { unfold BoundedSeq. split; auto.\n      generalize (H1 1 Rlt_0_1). intro I1. destruct I1 as [N0 I1].\n      assert (I2 : ∀ n : nat, (n > N0)%nat -> Abs[x[n] - x[S N0]] < 1).\n      { intros n I2. apply I1; auto. }\n      assert (I3 : ∀ n : nat, (n > N0)%nat -> Abs[x[n]] < Abs[x[S N0]] + 1).\n      { intros n I3. apply I2 in I3 as I4.\n        apply Rplus_lt_compat_l with (r := Abs[x[S N0]]) in I4 as I5.\n        apply Rle_lt_trans with (r2 := Abs[x[S N0]] + Abs[x[n] - x[S N0]]);\n        auto. assert (I6 : x[n] = x[S N0] + (x[n] - x[S N0])). field.\n        pattern x[n] at 1. rewrite I6. apply Abs_plus_le. }\n      assert (I4 : ∀ N : nat, ∃ M0, ∀ n : nat,\n        (n <= N)%nat -> Abs[x[n]] <= M0).\n      { intro N. induction N as [|N IHN].\n        - exists (Abs[x[0%nat]]). intros n J1. apply le_n_0_eq in J1.\n          rewrite <- J1. right. reflexivity.\n        - destruct IHN as [M0 IHN].\n          destruct (Rlt_or_le M0 Abs[x[S N]]) as [J1 | J1].\n          + exists (Abs[x[S N]]). intros n J2. apply le_lt_or_eq in J2.\n            destruct J2 as [J2 | J2].\n            * apply lt_n_Sm_le in J2. left.\n              apply Rle_lt_trans with (r2 := M0); auto.\n            * rewrite J2. right; reflexivity.\n          + exists M0. intros n J2. apply le_lt_or_eq in J2.\n            destruct J2 as [J2 | J2].\n            * apply lt_n_Sm_le in J2. auto.\n            * rewrite J2. auto. }\n      generalize (I4 N0). intro I5. destruct I5 as [M0 I5].\n      destruct (Rlt_or_le M0 (Abs[x[S N0]] + 1)) as [I6 | I6].\n      - exists (Abs[x[S N0]] + 1). intro n. generalize (Nat.le_gt_cases n N0).\n        intro I7. destruct I7 as [I7 | I7].\n        + left. apply Rle_lt_trans with (r2 := M0); auto.\n        + left. auto.\n      - exists M0. intro n. generalize (Nat.le_gt_cases n N0).\n        intro I7. destruct I7 as [I7 | I7]; auto.\n        left. apply Rlt_le_trans with (r2 := (Abs[x[S N0]] + 1)); auto. }\n    apply Theorem2_10 in H2 as H3. destruct H3 as [y [H3 H4]].\n    destruct H4 as [a H4]. exists a. unfold limit_seq. split; auto.\n    intros ε H5. assert (H6 : ε / 2 > 0).\n    { generalize (Rinv_0_lt_compat 2 Rlt_0_2). intro I1.\n      apply Rmult_gt_0_compat; auto. }\n    apply H1 in H6 as H7. destruct H7 as [N H7]. exists N.\n    intros n H8. assert (H9 : ∀ m, (m > N)%nat -> Abs[x[n] - y[m]] < ε/2).\n    { intros m I6. assert (I7 : ∃ m1, (m1 > N)%nat /\\ y[m] = x[m1]).\n      { unfold SubSeq in H3. destruct H3 as [H3 [I1 [f [I2 [I3 I4]]]]].\n        exists (f\\[m\\]). split; auto.\n        apply fn_ge_n with (n := m) in I2 as I5; auto.\n        apply Nat.lt_le_trans with (m := m); auto. }\n      destruct I7 as [m1 [I7 I8]]. rewrite I8. auto. }\n    assert (H10 : ∃ z : Seq, z = {` λ m v, v = Abs [x[n] - y[m]] `}).\n    { exists {` λ m v, v = Abs [x[n] - y[m]] `}; auto. }\n    destruct H10 as [z H10]. assert (H11 : IsSeq z).\n    { unfold IsSeq. split.\n      - unfold Function. rewrite H10. intros x0 y0 z0 I1 I2.\n        applyAxiomII' I1. applyAxiomII' I2. rewrite I2. apply I1.\n      - apply AxiomI. intro z0; split; intro I1.\n        + apply AxiomII. reflexivity.\n        + apply AxiomII. exists (Abs [x[n] - y[z0]]). rewrite H10.\n          apply AxiomII'. reflexivity. }\n    assert (H12 : limit_seq z (Abs[x[n] - a])).\n    { unfold limit_seq in H4. destruct H4 as [H4 I1]. split; auto.\n      intros ε0 I2. apply I1 in I2 as I3. destruct I3 as [N0 I3].\n      exists N0. intros n0 I4. apply I3 in I4 as I5.\n      assert (I6 : z[n0] = Abs [x[n] - y[n0]]).\n      { apply f_x; try apply H11. rewrite H10. apply AxiomII'.\n        reflexivity. }\n      rewrite I6. apply Rle_lt_trans with (r2 := Abs[y[n0] - a]); auto.\n      assert (I7 : y[n0] - a = -((x[n] - y[n0])-(x[n] - a))). field.\n      rewrite I7. rewrite <- Abs_eq_neg. apply Abs_abs_minus. }\n    assert (H13 : ∃ w : Seq, w = {` λ m v, v = ε/2 `}).\n    { exists {` λ m v, v = ε/2 `}. reflexivity. }\n    destruct H13 as [w H13]. assert (H14 : IsSeq w).\n    { split.\n      - unfold Function. rewrite H13. intros x0 y0 z0 I1 I2.\n        applyAxiomII' I1. applyAxiomII' I2. rewrite I2. apply I1.\n      - apply AxiomI. intro z0; split; intro I1.\n        + apply AxiomII. reflexivity.\n        + apply AxiomII. exists (ε/2). rewrite H13. apply AxiomII'.\n          reflexivity. }\n    assert (H15 : limit_seq w (ε/2)).\n    { split; auto. intros ε0 I1. exists 0%nat. intros n0 I2.\n      assert (I3 : w[n0] = ε/2).\n      { apply f_x; try apply H14. rewrite H13. apply AxiomII'.\n        reflexivity. }\n      rewrite I3. unfold Rminus. rewrite Rplus_opp_r. rewrite Abs_ge; auto.\n      right; auto. }\n    assert (H16 : lim z <= lim w).\n    { apply Theorem2_5; [exists (Abs[x[n] - a]) | exists (ε/2) | idtac]; auto.\n      exists N. intros n0 I1. assert (I2 : z[n0] = Abs[x[n] - y[n0]]).\n      { apply f_x; try apply H11. rewrite H10. apply AxiomII'.\n        reflexivity. }\n      assert (I3 : w[n0] = ε/2).\n      { apply f_x; try apply H14. rewrite H13. apply AxiomII'.\n        reflexivity. }\n      rewrite I2. rewrite I3. left. apply H9. apply I1. }\n    rewrite lim_a with (a := (Abs[x[n] - a])) in H16; auto.\n    rewrite lim_a with (a := (ε/2)) in H16; auto.\n    apply Rle_lt_trans with (r2 := ε/2); auto. lra.\nQed.\n\nEnd A2_3.\n\nExport A2_3.", "meta": {"author": "zhaobaoq", "repo": "MathAnalysis", "sha": "f51d41fc9ddfcbe4ac2560e4bda43540b1be2f6a", "save_path": "github-repos/coq/zhaobaoq-MathAnalysis", "path": "github-repos/coq/zhaobaoq-MathAnalysis/MathAnalysis-f51d41fc9ddfcbe4ac2560e4bda43540b1be2f6a/A_2_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7315570370068945}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria.                       *)\n(* You may distribute this file under the terms of the CeCILL-B license *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq path fintype.\nRequire Import div bigop.\n\n(******************************************************************************)\n(* This file contains the definitions of:                                     *)\n(*        prime p <=> p is a prime.                                           *)\n(*       primes m == the sorted list of prime divisors of m > 1, else [::].   *)\n(*        pfactor == the type of prime factors, syntax (p ^ e)%pfactor.       *)\n(* prime_decomp m == the list of prime factors of m > 1, sorted by primes.    *)\n(*       logn p m == the e such that (p ^ e) \\in prime_decomp n, else 0.      *)\n(*  trunc_log p m == the largest e such that p ^ e <= m, or 0 if p or m is 0. *)\n(*         pdiv n == the smallest prime divisor of n > 1, else 1.             *)\n(*     max_pdiv n == the largest prime divisor of n > 1, else 1.              *)\n(*     divisors m == the sorted list of divisors of m > 0, else [::].         *)\n(*      totient n == the Euler totient (#|{i < n | i and n coprime}|).        *)\n(*       nat_pred == the type of explicit collective nat predicates.          *)\n(*                := simpl_pred nat.                                          *)\n(*    -> We allow the coercion nat >-> nat_pred, interpreting p as pred1 p.   *)\n(*    -> We define a predType for nat_pred, enabling the notation p \\in pi.   *)\n(*    -> We don't have nat_pred >-> pred, which would imply nat >-> Funclass. *)\n(*           pi^' == the complement of pi : nat_pred, i.e., the nat_pred such *)\n(*                   that (p \\in pi^') = (p \\notin pi).                       *)\n(*         \\pi(n) == the set of prime divisors of n, i.e., the nat_pred such  *)\n(*                   that (p \\in \\pi(n)) = (p \\in primes n).                  *)\n(*         \\pi(A) == the set of primes of #|A|, with A a collective predicate *)\n(*                   over a finite Type.                                      *)\n(*     -> The notation \\pi(A) is implemented with a collapsible Coercion, so  *)\n(*        the type of A must coerce to finpred_class (e.g., by coercing to    *)\n(*        {set T}), not merely implement the predType interface (as seq T     *)\n(*        does).                                                              *)\n(*     -> The expression #|A| will only appear in \\pi(A) after simplification *)\n(*        collapses the coercion stack, so it is advisable to do so early on. *)\n(*     pi.-nat n <=> n > 0 and all prime divisors of n are in pi.             *)\n(*          n`_pi == the pi-part of n -- the largest pi.-nat divisor of n.    *)\n(*               := \\prod_(0 <= p < n.+1 | p \\in pi) p ^ logn p n.            *)\n(*     -> The nat >-> nat_pred coercion lets us write p.-nat n and n`_p.      *)\n(* In addition to the lemmas relevant to these definitions, this file also    *)\n(* contains the dvdn_sum lemma, so that bigop.v doesn't depend on div.v.      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* The complexity of any arithmetic operation with the Peano representation *)\n(* is pretty dreadful, so using algorithms for \"harder\" problems such as    *)\n(* factoring, that are geared for efficient artihmetic leads to dismal      *)\n(* performance -- it takes a significant time, for instance, to compute the *)\n(* divisors of just a two-digit number. On the other hand, for Peano        *)\n(* integers, prime factoring (and testing) is linear-time with a small      *)\n(* constant factor -- indeed, the same as converting in and out of a binary *)\n(* representation. This is implemented by the code below, which is then     *)\n(* used to give the \"standard\" definitions of prime, primes, and divisors,  *)\n(* which can then be used casually in proofs with moderately-sized numeric  *)\n(* values (indeed, the code here performs well for up to 6-digit numbers).  *)\n\n(* We start with faster mod-2 functions. *)\n\nFixpoint edivn2 q r := if r is r'.+2 then edivn2 q.+1 r' else (q, r).\n\nLemma edivn2P n : edivn_spec n 2 (edivn2 0 n).\nProof.\nrewrite -[n]odd_double_half addnC -{1}[n./2]addn0 -{1}mul2n mulnC.\nelim: n./2 {1 4}0 => [|r IHr] q; first by case (odd n) => /=.\nrewrite addSnnS; exact: IHr.\nQed.\n\nFixpoint elogn2 e q r {struct q} :=\n  match q, r with\n  | 0, _ | _, 0 => (e, q)\n  | q'.+1, 1 => elogn2 e.+1 q' q'\n  | q'.+1, r'.+2 => elogn2 e q' r'\n  end.\n\nCoInductive elogn2_spec n : nat * nat -> Type :=\n  Elogn2Spec e m of n = 2 ^ e * m.*2.+1 : elogn2_spec n (e, m).\n\nLemma elogn2P n : elogn2_spec n.+1 (elogn2 0 n n).\nProof.\nrewrite -{1}[n.+1]mul1n -[1]/(2 ^ 0) -{1}(addKn n n) addnn.\nelim: n {1 4 6}n {2 3}0 (leqnn n) => [|q IHq] [|[|r]] e //=; last first.\n  by move/ltnW; exact: IHq.\nclear 1; rewrite subn1 -[_.-1.+1]doubleS -mul2n mulnA -expnSr.\nrewrite -{1}(addKn q q) addnn; exact: IHq.\nQed.\n\nDefinition ifnz T n (x y : T) := if n is 0 then y else x.\n\nCoInductive ifnz_spec T n (x y : T) : T -> Type :=\n  | IfnzPos of n > 0 : ifnz_spec n x y x\n  | IfnzZero of n = 0 : ifnz_spec n x y y.\n\nLemma ifnzP T n (x y : T) : ifnz_spec n x y (ifnz n x y).\nProof. by case: n => [|n]; [right | left]. Qed.\n\n(* For pretty-printing. *)\nDefinition NumFactor (f : nat * nat) := ([Num of f.1], f.2).\n\nDefinition pfactor p e := p ^ e.\n\nDefinition cons_pfactor (p e : nat) pd := ifnz e ((p, e) :: pd) pd.\n\nNotation Local \"p ^? e :: pd\" := (cons_pfactor p e pd)\n  (at level 30, e at level 30, pd at level 60) : nat_scope.\n\nSection prime_decomp.\n\nImport NatTrec.\n\nFixpoint prime_decomp_rec m k a b c e :=\n  let p := k.*2.+1 in\n  if a is a'.+1 then\n    if b - (ifnz e 1 k - c) is b'.+1 then\n      [rec m, k, a', b', ifnz c c.-1 (ifnz e p.-2 1), e] else\n    if (b == 0) && (c == 0) then\n      let b' := k + a' in [rec b'.*2.+3, k, a', b', k.-1, e.+1] else\n    let bc' := ifnz e (ifnz b (k, 0) (edivn2 0 c)) (b, c) in\n    p ^? e :: ifnz a' [rec m, k.+1, a'.-1, bc'.1 + a', bc'.2, 0] [:: (m, 1)]\n  else if (b == 0) && (c == 0) then [:: (p, e.+2)] else p ^? e :: [:: (m, 1)]\nwhere \"[ 'rec' m , k , a , b , c , e ]\" := (prime_decomp_rec m k a b c e).\n\nDefinition prime_decomp n :=\n  let: (e2, m2) := elogn2 0 n.-1 n.-1 in\n  if m2 < 2 then 2 ^? e2 :: 3 ^? m2 :: [::] else\n  let: (a, bc) := edivn m2.-2 3 in\n  let: (b, c) := edivn (2 - bc) 2 in\n  2 ^? e2 :: [rec m2.*2.+1, 1, a, b, c, 0].\n\n(* The list of divisors and the Euler function are computed directly from *)\n(* the decomposition, using a merge_sort variant sort the divisor list.   *)\n\nDefinition add_divisors f divs :=\n  let: (p, e) := f in\n  let add1 divs' := merge leq (map (NatTrec.mul p) divs') divs in\n  iter e add1 divs.\n\nDefinition add_totient_factor f m := let: (p, e) := f in p.-1 * p ^ e.-1 * m.\n\nEnd prime_decomp.\n\nDefinition primes n := unzip1 (prime_decomp n).\n\nDefinition prime p := if prime_decomp p is [:: (_ , 1)] then true else false.\n\nDefinition nat_pred := simpl_pred nat.\n\nDefinition pi_unwrapped_arg := nat.\nDefinition pi_wrapped_arg := wrapped nat.\nCoercion unwrap_pi_arg (wa : pi_wrapped_arg) : pi_unwrapped_arg := unwrap wa.\nCoercion pi_arg_of_nat (n : nat) := Wrap n : pi_wrapped_arg.\nCoercion pi_arg_of_fin_pred T pT (A : @fin_pred_sort T pT) : pi_wrapped_arg :=\n  Wrap #|A|.\n\nDefinition pi_of (n : pi_unwrapped_arg) : nat_pred := [pred p in primes n].\n\nNotation \"\\pi ( n )\" := (pi_of n)\n  (at level 2, format \"\\pi ( n )\") : nat_scope.\nNotation \"\\p 'i' ( A )\" := \\pi(#|A|)\n  (at level 2, format \"\\p 'i' ( A )\") : nat_scope.\n\nDefinition pdiv n := head 1 (primes n).\n\nDefinition max_pdiv n := last 1 (primes n).\n\nDefinition divisors n := foldr add_divisors [:: 1] (prime_decomp n).\n\nDefinition totient n := foldr add_totient_factor (n > 0) (prime_decomp n).\n\n(* Correctness of the decomposition algorithm. *)\n\nLemma prime_decomp_correct :\n  let pd_val pd := \\prod_(f <- pd) pfactor f.1 f.2 in\n  let lb_dvd q m := ~~ has [pred d | d %| m] (index_iota 2 q) in\n  let pf_ok f := lb_dvd f.1 f.1 && (0 < f.2) in\n  let pd_ord q pd := path ltn q (unzip1 pd) in\n  let pd_ok q n pd := [/\\ n = pd_val pd, all pf_ok pd & pd_ord q pd] in\n  forall n, n > 0 -> pd_ok 1 n (prime_decomp n).\nProof.\nrewrite unlock => pd_val lb_dvd pf_ok pd_ord pd_ok.\nhave leq_pd_ok m p q pd: q <= p -> pd_ok p m pd -> pd_ok q m pd.\n  rewrite /pd_ok /pd_ord; case: pd => [|[r _] pd] //= leqp [<- ->].\n  by case/andP=> /(leq_trans _)->.\nhave apd_ok m e q p pd: lb_dvd p p || (e == 0) -> q < p ->\n     pd_ok p m pd -> pd_ok q (p ^ e * m) (p ^? e :: pd).\n- case: e => [|e]; rewrite orbC /= => pr_p ltqp.\n    rewrite mul1n; apply: leq_pd_ok; exact: ltnW.\n  by rewrite /pd_ok /pd_ord /pf_ok /= pr_p ltqp => [[<- -> ->]].\ncase=> // n _; rewrite /prime_decomp.\ncase: elogn2P => e2 m2 -> {n}; case: m2 => [|[|abc]]; try exact: apd_ok.\nrewrite [_.-2]/= !ltnS ltn0 natTrecE; case: edivnP => a bc ->{abc}.\ncase: edivnP => b c def_bc /= ltc2 ltbc3; apply: (apd_ok) => //.\nmove def_m: _.*2.+1 => m; set k := {2}1; rewrite -[2]/k.*2; set e := 0.\npose p := k.*2.+1; rewrite -{1}[m]mul1n -[1]/(p ^ e)%N.\nhave{def_m bc def_bc ltc2 ltbc3}:\n   let kb := (ifnz e k 1).*2 in\n   [&& k > 0, p < m, lb_dvd p m, c < kb & lb_dvd p p || (e == 0)]\n    /\\ m + (b * kb + c).*2 = p ^ 2 + (a * p).*2.\n- rewrite -{-2}def_m; split=> //=; last first.\n    by rewrite -def_bc addSn -doubleD 2!addSn -addnA subnKC // addnC.\n  rewrite ltc2 /lb_dvd /index_iota /= dvdn2 -def_m.\n  by rewrite [_.+2]lock /= odd_double.\nmove: {2}a.+1 (ltnSn a) => n; clearbody k e.\nelim: n => // n IHn in a k p m b c e *; rewrite ltnS => le_a_n [].\nset kb := _.*2; set d := _ + c => /and5P[lt0k ltpm leppm ltc pr_p def_m].\nhave def_k1: k.-1.+1 = k := ltn_predK lt0k.\nhave def_kb1: kb.-1.+1 = kb by rewrite /kb -def_k1; case e.\nhave eq_bc_0: (b == 0) && (c == 0) = (d == 0).\n  by rewrite addn_eq0 muln_eq0 orbC -def_kb1.\nhave lt1p: 1 < p by rewrite ltnS double_gt0.\nhave co_p_2: coprime p 2 by rewrite /coprime gcdnC gcdnE modn2 /= odd_double.\nhave if_d0: d = 0 -> [/\\ m = (p + a.*2) * p, lb_dvd p p & lb_dvd p (p + a.*2)].\n  move=> d0; have{d0 def_m} def_m: m = (p + a.*2) * p.\n    by rewrite d0 addn0 -mulnn -!mul2n mulnA -mulnDl in def_m *.\n  split=> //; apply/hasPn=> r /(hasPn leppm); apply: contra => /= dv_r.\n    by rewrite def_m dvdn_mull.\n  by rewrite def_m dvdn_mulr.\ncase def_a: a => [|a'] /= in le_a_n *; rewrite !natTrecE -/p {}eq_bc_0.\n  case: d if_d0 def_m => [[//| def_m {pr_p}pr_p pr_m'] _ | d _ def_m] /=.\n    rewrite def_m def_a addn0 mulnA -2!expnSr.\n    by split; rewrite /pd_ord /pf_ok /= ?muln1 ?pr_p ?leqnn.\n  apply: apd_ok; rewrite // /pd_ok /= /pfactor expn1 muln1 /pd_ord /= ltpm.\n  rewrite /pf_ok !andbT /=; split=> //; apply: contra leppm.\n  case/hasP=> r /=; rewrite mem_index_iota => /andP[lt1r ltrm] dvrm; apply/hasP.\n  have [ltrp | lepr] := ltnP r p.\n    by exists r; rewrite // mem_index_iota lt1r.\n  case/dvdnP: dvrm => q def_q; exists q; last by rewrite def_q /= dvdn_mulr.\n  rewrite mem_index_iota -(ltn_pmul2r (ltnW lt1r)) -def_q mul1n ltrm.\n  move: def_m; rewrite def_a addn0 -(@ltn_pmul2r p) // mulnn => <-.\n  apply: (@leq_ltn_trans m); first by rewrite def_q leq_mul.\n  by rewrite -addn1 leq_add2l.\nhave def_k2: k.*2 = ifnz e 1 k * kb.\n  by rewrite /kb; case: (e) => [|e']; rewrite (mul1n, muln2).\ncase def_b': (b - _) => [|b']; last first.\n  have ->: ifnz e k.*2.-1 1 = kb.-1 by rewrite /kb; case e.\n  apply: IHn => {n le_a_n}//; rewrite -/p -/kb; split=> //.\n    rewrite lt0k ltpm leppm pr_p andbT /=.\n    by case: ifnzP; [move/ltn_predK->; exact: ltnW | rewrite def_kb1].\n  apply: (@addIn p.*2).\n  rewrite -2!addnA -!doubleD -addnA -mulSnr -def_a -def_m /d.\n  have ->: b * kb = b' * kb + (k.*2 - c * kb + kb).\n    rewrite addnCA addnC -mulSnr -def_b' def_k2 -mulnBl -mulnDl subnK //.\n    by rewrite ltnW // -subn_gt0 def_b'.\n  rewrite -addnA; congr (_ + (_ + _).*2).\n  case: (c) ltc; first by rewrite -addSnnS def_kb1 subn0 addn0 addnC.\n  rewrite /kb; case e => [[] // _ | e' c' _] /=; last first.\n    by rewrite subnDA subnn addnC addSnnS.\n  by rewrite mul1n -doubleB -doubleD subn1 !addn1 def_k1.\nhave ltdp: d < p.\n  move/eqP: def_b'; rewrite subn_eq0 -(@leq_pmul2r kb); last first.\n    by rewrite -def_kb1.\n  rewrite mulnBl -def_k2 ltnS -(leq_add2r c); move/leq_trans; apply.\n  have{ltc} ltc: c < k.*2.\n    by apply: (leq_trans ltc); rewrite leq_double /kb; case e.\n  rewrite -{2}(subnK (ltnW ltc)) leq_add2r leq_sub2l //.\n  by rewrite -def_kb1 mulnS leq_addr.\ncase def_d: d if_d0 => [|d'] => [[//|{def_m ltdp pr_p} def_m pr_p pr_m'] | _].\n  rewrite eqxx -doubleS -addnS -def_a doubleD -addSn -/p def_m.\n  rewrite mulnCA mulnC -expnSr.\n  apply: IHn => {n le_a_n}//; rewrite -/p -/kb; split.\n    rewrite lt0k -addn1 leq_add2l {1}def_a pr_m' pr_p /= def_k1 -addnn.\n    by rewrite leq_addr.\n  rewrite -addnA -doubleD addnCA def_a addSnnS def_k1 -(addnC k) -mulnSr.\n  rewrite -[_.*2.+1]/p mulnDl doubleD addnA -mul2n mulnA mul2n -mulSn.\n  by rewrite -/p mulnn.\nhave next_pm: lb_dvd p.+2 m.\n  rewrite /lb_dvd /index_iota 2!subSS subn0 -(subnK lt1p) iota_add.\n  rewrite has_cat; apply/norP; split=> //=; rewrite orbF subnKC // orbC.\n  apply/norP; split; apply/dvdnP=> [[q def_q]].\n     case/hasP: leppm; exists 2; first by rewrite /p -(subnKC lt0k).\n    by rewrite /= def_q dvdn_mull // dvdn2 /= odd_double.\n  move/(congr1 (dvdn p)): def_m; rewrite -mulnn -!mul2n mulnA -mulnDl.\n  rewrite dvdn_mull // dvdn_addr; last by rewrite def_q dvdn_mull.\n  case/dvdnP=> r; rewrite mul2n => def_r; move: ltdp (congr1 odd def_r).\n  rewrite odd_double -ltn_double {1}def_r -mul2n ltn_pmul2r //.\n  by case: r def_r => [|[|[]]] //; rewrite def_d // mul1n /= odd_double.\napply: apd_ok => //; case: a' def_a le_a_n => [|a'] def_a => [_ | lta] /=.\n  rewrite /pd_ok /= /pfactor expn1 muln1 /pd_ord /= ltpm /pf_ok !andbT /=.\n  split=> //; apply: contra next_pm.\n  case/hasP=> q; rewrite mem_index_iota => /andP[lt1q ltqm] dvqm; apply/hasP.\n  have [ltqp | lepq] := ltnP q p.+2.\n    by exists q; rewrite // mem_index_iota lt1q.\n  case/dvdnP: dvqm => r def_r; exists r; last by rewrite def_r /= dvdn_mulr.\n  rewrite mem_index_iota -(ltn_pmul2r (ltnW lt1q)) -def_r mul1n ltqm /=.\n  rewrite -(@ltn_pmul2l p.+2) //; apply: (@leq_ltn_trans m).\n    by rewrite def_r mulnC leq_mul.\n  rewrite -addn2 mulnn sqrnD mul2n muln2 -addnn addnCA -addnA addnCA addnA.\n  by rewrite def_a mul1n in def_m; rewrite -def_m addnS -addnA ltnS leq_addr.\nset bc := ifnz _ _ _; apply: leq_pd_ok (leqnSn _) _.\nrewrite -doubleS -{1}[m]mul1n -[1]/(k.+1.*2.+1 ^ 0)%N.\napply: IHn; first exact: ltnW.\nrewrite doubleS -/p [ifnz 0 _ _]/=; do 2?split => //.\n  rewrite orbT next_pm /= -(leq_add2r d.*2) def_m 2!addSnnS -doubleS leq_add.\n  - move: ltc; rewrite /kb {}/bc andbT; case e => //= e' _; case: ifnzP => //.\n    by case: edivn2P.\n  - by rewrite -{1}[p]muln1 -mulnn ltn_pmul2l.\n  by rewrite leq_double def_a mulSn (leq_trans ltdp) ?leq_addr.\nrewrite mulnDl !muln2 -addnA addnCA doubleD addnCA.\nrewrite (_ : _ + bc.2 = d); last first.\n  rewrite /d {}/bc /kb -muln2.\n  case: (e) (b) def_b' => //= _ []; first by case: edivn2P.\n  by case c; do 2?case; rewrite // mul1n /= muln2.\nrewrite def_m 3!doubleS addnC -(addn2 p) sqrnD mul2n muln2 -3!addnA.\ncongr (_ + _); rewrite 4!addnS -!doubleD; congr _.*2.+2.+2.\nby rewrite def_a -add2n mulnDl -addnA -muln2 -mulnDr mul2n.\nQed.\n\nLemma primePn n :\n  reflect (n < 2 \\/ exists2 d, 1 < d < n & d %| n) (~~ prime n).\nProof.\nrewrite /prime; case: n => [|[|p2]]; try by do 2!left.\ncase: (@prime_decomp_correct p2.+2) => //; rewrite unlock.\ncase: prime_decomp => [|[q [|[|e]]] pd] //=; last first; last by rewrite andbF.\n  rewrite {1}/pfactor 2!expnS -!mulnA /=.\n  case: (_ ^ _ * _) => [|u -> _ /andP[lt1q _]]; first by rewrite !muln0.\n  left; right; exists q; last by rewrite dvdn_mulr.\n  have lt0q := ltnW lt1q; rewrite lt1q -{1}[q]muln1 ltn_pmul2l //.\n  by rewrite -[2]muln1 leq_mul.\nrewrite {1}/pfactor expn1; case: pd => [|[r e] pd] /=; last first.\n  case: e => [|e] /=; first by rewrite !andbF.\n  rewrite {1}/pfactor expnS -mulnA.\n  case: (_ ^ _ * _) => [|u -> _ /and3P[lt1q ltqr _]]; first by rewrite !muln0.\n  left; right; exists q; last by rewrite dvdn_mulr.\n  by rewrite lt1q -{1}[q]mul1n ltn_mul // -[q.+1]muln1 leq_mul.\nrewrite muln1 !andbT => def_q pr_q lt1q; right=> [[]] // [d].\nby rewrite def_q -mem_index_iota => in_d_2q dv_d_q; case/hasP: pr_q; exists d.\nQed.\n\nLemma primeP p :\n  reflect (p > 1 /\\ forall d, d %| p -> xpred2 1 p d) (prime p).\nProof.\nrewrite -[prime p]negbK; have [npr_p | pr_p] := primePn p.\n  right=> [[lt1p pr_p]]; case: npr_p => [|[d n1pd]].\n    by rewrite ltnNge lt1p.\n  by move/pr_p=> /orP[] /eqP def_d; rewrite def_d ltnn ?andbF in n1pd.\nhave [lep1 | lt1p] := leqP; first by case: pr_p; left.\nleft; split=> // d dv_d_p; apply/norP=> [[nd1 ndp]]; case: pr_p; right.\nexists d; rewrite // andbC 2!ltn_neqAle ndp eq_sym nd1.\nby have lt0p := ltnW lt1p; rewrite dvdn_leq // (dvdn_gt0 lt0p).\nQed.\n\nLemma prime_nt_dvdP d p : prime p -> d != 1 -> reflect (d = p) (d %| p).\nProof.\ncase/primeP=> _ min_p d_neq1; apply: (iffP idP) => [/min_p|-> //].\nby rewrite (negPf d_neq1) /= => /eqP.\nQed.\n\nImplicit Arguments primeP [p].\nImplicit Arguments primePn [n].\nPrenex Implicits primePn primeP.\n\nLemma prime_gt1 p : prime p -> 1 < p.\nProof. by case/primeP. Qed.\n\nLemma prime_gt0 p : prime p -> 0 < p.\nProof. by move/prime_gt1; exact: ltnW. Qed.\n\nHint Resolve prime_gt1 prime_gt0.\n\nLemma prod_prime_decomp n :\n  n > 0 -> n = \\prod_(f <- prime_decomp n) f.1 ^ f.2.\nProof. by case/prime_decomp_correct. Qed.\n\nLemma even_prime p : prime p -> p = 2 \\/ odd p.\nProof.\nmove=> pr_p; case odd_p: (odd p); [by right | left].\nhave: 2 %| p by rewrite dvdn2 odd_p.\nby case/primeP: pr_p => _ dv_p /dv_p/(2 =P p).\nQed.\n\nLemma prime_oddPn p : prime p -> reflect (p = 2) (~~ odd p).\nProof.\nby move=> p_pr; apply: (iffP idP) => [|-> //]; case/even_prime: p_pr => ->.\nQed.\n\nLemma odd_prime_gt2 p : odd p -> prime p -> p > 2.\nProof. by move=> odd_p /prime_gt1; apply: odd_gt2. Qed.\n\nLemma mem_prime_decomp n p e :\n  (p, e) \\in prime_decomp n -> [/\\ prime p, e > 0 & p ^ e %| n].\nProof.\ncase: (posnP n) => [-> //| /prime_decomp_correct[def_n mem_pd ord_pd pd_pe]].\nhave /andP[pr_p ->] := allP mem_pd _ pd_pe; split=> //; last first.\n  case/splitPr: pd_pe def_n => pd1 pd2 ->.\n  by rewrite big_cat big_cons /= mulnCA dvdn_mulr.\nhave lt1p: 1 < p.\n  apply: (allP (order_path_min ltn_trans ord_pd)).\n  by apply/mapP; exists (p, e).\napply/primeP; split=> // d dv_d_p; apply/norP=> [[nd1 ndp]].\ncase/hasP: pr_p; exists d => //.\nrewrite mem_index_iota andbC 2!ltn_neqAle ndp eq_sym nd1.\nby have lt0p := ltnW lt1p; rewrite dvdn_leq // (dvdn_gt0 lt0p).\nQed.\n\nLemma prime_coprime p m : prime p -> coprime p m = ~~ (p %| m).\nProof.\ncase/primeP=> p_gt1 p_pr; apply/eqP/negP=> [d1 | ndv_pm].\n  case/dvdnP=> k def_m; rewrite -(addn0 m) def_m gcdnMDl gcdn0 in d1.\n  by rewrite d1 in p_gt1.\nby apply: gcdn_def => // d /p_pr /orP[] /eqP->.\nQed.\n\nLemma dvdn_prime2 p q : prime p -> prime q -> (p %| q) = (p == q).\nProof.\nmove=> pr_p pr_q; apply: negb_inj.\nby rewrite eqn_dvd negb_and -!prime_coprime // coprime_sym orbb.\nQed.\n\nLemma Euclid_dvdM m n p : prime p -> (p %| m * n) = (p %| m) || (p %| n).\nProof.\nmove=> pr_p; case dv_pm: (p %| m); first exact: dvdn_mulr.\nby rewrite Gauss_dvdr // prime_coprime // dv_pm.\nQed.\n\nLemma Euclid_dvd1 p : prime p -> (p %| 1) = false.\nProof. by rewrite dvdn1; case: eqP => // ->. Qed.\n\nLemma Euclid_dvdX m n p : prime p -> (p %| m ^ n) = (p %| m) && (n > 0).\nProof.\ncase: n => [|n] pr_p; first by rewrite andbF Euclid_dvd1.\nby apply: (inv_inj negbK); rewrite !andbT -!prime_coprime // coprime_pexpr.\nQed.\n\nLemma mem_primes p n : (p \\in primes n) = [&& prime p, n > 0 & p %| n].\nProof.\nrewrite andbCA; case: posnP => [-> // | /= n_gt0].\napply/mapP/andP=> [[[q e]]|[pr_p]] /=.\n  case/mem_prime_decomp=> pr_q e_gt0; case/dvdnP=> u -> -> {p}.\n  by rewrite -(prednK e_gt0) expnS mulnCA dvdn_mulr.\nrewrite {1}(prod_prime_decomp n_gt0) big_seq.\napply big_ind => [| u v IHu IHv | [q e] /= mem_qe dv_p_qe].\n- by rewrite Euclid_dvd1.\n- by rewrite Euclid_dvdM // => /orP[].\nexists (q, e) => //=; case/mem_prime_decomp: mem_qe => pr_q _ _.\nby rewrite Euclid_dvdX // dvdn_prime2 // in dv_p_qe; case: eqP dv_p_qe.\nQed.\n\nLemma sorted_primes n : sorted ltn (primes n).\nProof.\nby case: (posnP n) => [-> // | /prime_decomp_correct[_ _]]; exact: path_sorted.\nQed.\n\nLemma eq_primes m n : (primes m =i primes n) <-> (primes m = primes n).\nProof.\nsplit=> [eqpr| -> //].\nby apply: (eq_sorted_irr ltn_trans ltnn); rewrite ?sorted_primes.\nQed.\n\nLemma primes_uniq n : uniq (primes n).\nProof. exact: (sorted_uniq ltn_trans ltnn (sorted_primes n)). Qed.\n\n(* The smallest prime divisor *)\n\nLemma pi_pdiv n : (pdiv n \\in \\pi(n)) = (n > 1).\nProof.\ncase: n => [|[|n]] //; rewrite /pdiv !inE /primes.\nhave:= prod_prime_decomp (ltn0Sn n.+1); rewrite unlock.\nby case: prime_decomp => //= pf pd _; rewrite mem_head.\nQed.\n\nLemma pdiv_prime n : 1 < n -> prime (pdiv n).\nProof. by rewrite -pi_pdiv mem_primes; case/and3P. Qed.\n\nLemma pdiv_dvd n : pdiv n %| n.\nProof.\nby case: n (pi_pdiv n) => [|[|n]] //; rewrite mem_primes=> /and3P[].\nQed.\n\nLemma pi_max_pdiv n : (max_pdiv n \\in \\pi(n)) = (n > 1).\nProof.\nrewrite !inE -pi_pdiv /max_pdiv /pdiv !inE.\nby case: (primes n) => //= p ps; rewrite mem_head mem_last.\nQed.\n\nLemma max_pdiv_prime n : n > 1 -> prime (max_pdiv n).\nProof. by rewrite -pi_max_pdiv mem_primes => /andP[]. Qed.\n\nLemma max_pdiv_dvd n : max_pdiv n %| n.\nProof.\nby case: n (pi_max_pdiv n) => [|[|n]] //; rewrite mem_primes => /andP[].\nQed.\n\nLemma pdiv_leq n : 0 < n -> pdiv n <= n.\nProof. by move=> n_gt0; rewrite dvdn_leq // pdiv_dvd. Qed.\n\nLemma max_pdiv_leq n : 0 < n -> max_pdiv n <= n.\nProof. by move=> n_gt0; rewrite dvdn_leq // max_pdiv_dvd. Qed.\n\nLemma pdiv_gt0 n : 0 < pdiv n.\nProof. by case: n => [|[|n]] //; rewrite prime_gt0 ?pdiv_prime. Qed.\n\nLemma max_pdiv_gt0 n : 0 < max_pdiv n.\nProof. by case: n => [|[|n]] //; rewrite prime_gt0 ?max_pdiv_prime. Qed.\nHint Resolve pdiv_gt0 max_pdiv_gt0.\n\nLemma pdiv_min_dvd m d : 1 < d -> d %| m -> pdiv m <= d.\nProof.\nmove=> lt1d dv_d_m; case: (posnP m) => [->|mpos]; first exact: ltnW.\nrewrite /pdiv; apply: leq_trans (pdiv_leq (ltnW lt1d)).\nhave: pdiv d \\in primes m.\n  by rewrite mem_primes mpos pdiv_prime // (dvdn_trans (pdiv_dvd d)).\ncase: (primes m) (sorted_primes m) => //= p pm ord_pm.\nrewrite inE => /predU1P[-> //|].\nmove/(allP (order_path_min ltn_trans ord_pm)); exact: ltnW.\nQed.\n\nLemma max_pdiv_max n p : p \\in \\pi(n) -> p <= max_pdiv n.\nProof.\nrewrite /max_pdiv !inE => n_p.\ncase/splitPr: n_p (sorted_primes n) => p1 p2; rewrite last_cat -cat_rcons /=.\nrewrite headI /= cat_path -(last_cons 0) -headI last_rcons; case/andP=> _.\nmove/(order_path_min ltn_trans); case/lastP: p2 => //= p2 q.\nby rewrite all_rcons last_rcons ltn_neqAle -andbA => /and3P[].\nQed.\n\nLemma ltn_pdiv2_prime n : 0 < n -> n < pdiv n ^ 2 -> prime n.\nProof.\ncase def_n: n => [|[|n']] // _; rewrite -def_n => lt_n_p2.\nsuffices ->: n = pdiv n by rewrite pdiv_prime ?def_n.\napply/eqP; rewrite eqn_leq leqNgt andbC pdiv_leq; last by rewrite def_n.\nmove: lt_n_p2; rewrite ltnNge; apply: contra => lt_pm_m.\ncase/dvdnP: (pdiv_dvd n) => q def_q.\nrewrite {2}def_q -mulnn leq_pmul2r // pdiv_min_dvd //.\n  by rewrite -[pdiv n]mul1n {2}def_q ltn_pmul2r in lt_pm_m.\nby rewrite def_q dvdn_mulr.\nQed.\n\nLemma primePns n :\n  reflect (n < 2 \\/ exists p, [/\\ prime p, p ^ 2 <= n & p %| n]) (~~ prime n).\nProof.\napply: (iffP idP) => [npr_p|]; last first.\n  case=> [|[p [pr_p le_p2_n dv_p_n]]]; first by case: n => [|[]].\n  apply/negP=> pr_n; move: dv_p_n le_p2_n; rewrite dvdn_prime2 //; move/eqP->.\n  by rewrite leqNgt -{1}[n]muln1 -mulnn ltn_pmul2l ?prime_gt1 ?prime_gt0.\ncase: leqP => [lt1p|]; [right | by left].\nexists (pdiv n); rewrite pdiv_dvd pdiv_prime //; split=> //.\nby case: leqP npr_p => //; move/ltn_pdiv2_prime->; auto.\nQed.\n\nImplicit Arguments primePns [n].\nPrenex Implicits primePns.\n\nLemma pdivP n : n > 1 -> {p | prime p & p %| n}.\nProof. by move=> lt1n; exists (pdiv n); rewrite ?pdiv_dvd ?pdiv_prime. Qed.\n\nLemma primes_mul m n p : m > 0 -> n > 0 ->\n  (p \\in primes (m * n)) = (p \\in primes m) || (p \\in primes n).\nProof.\nmove=> m_gt0 n_gt0; rewrite !mem_primes muln_gt0 m_gt0 n_gt0.\nby case pr_p: (prime p); rewrite // Euclid_dvdM.\nQed.\n\nLemma primes_exp m n : n > 0 -> primes (m ^ n) = primes m.\nProof.\ncase: n => // n _; rewrite expnS; case: (posnP m) => [-> //| m_gt0].\napply/eq_primes => /= p; elim: n => [|n IHn]; first by rewrite muln1.\nby rewrite primes_mul ?(expn_gt0, expnS, IHn, orbb, m_gt0).\nQed.\n\nLemma primes_prime p : prime p -> primes p = [::p].\nProof.\nmove=> pr_p; apply: (eq_sorted_irr ltn_trans ltnn) => // [|q].\n  exact: sorted_primes.\nrewrite mem_seq1 mem_primes prime_gt0 //=.\nby apply/andP/idP=> [[pr_q q_p] | /eqP-> //]; rewrite -dvdn_prime2.\nQed.\n\nLemma coprime_has_primes m n : m > 0 -> n > 0 ->\n  coprime m n = ~~ has (mem (primes m)) (primes n).\nProof.\nmove=> m_gt0 n_gt0; apply/eqnP/hasPn=> [mn1 p | no_p_mn].\n  rewrite /= !mem_primes m_gt0 n_gt0 /= => /andP[pr_p p_n].\n  have:= prime_gt1 pr_p; rewrite pr_p ltnNge -mn1 /=; apply: contra => p_m.\n  by rewrite dvdn_leq ?gcdn_gt0 ?m_gt0 // dvdn_gcd ?p_m.\ncase: (ltngtP (gcdn m n) 1) => //; first by rewrite ltnNge gcdn_gt0 ?m_gt0.\nmove/pdiv_prime; set p := pdiv _ => pr_p.\nmove/implyP: (no_p_mn p); rewrite /= !mem_primes m_gt0 n_gt0 pr_p /=.\nby rewrite !(dvdn_trans (pdiv_dvd _)) // (dvdn_gcdl, dvdn_gcdr).\nQed.\n\nLemma pdiv_id p : prime p -> pdiv p = p.\nProof. by move=> p_pr; rewrite /pdiv primes_prime. Qed.\n\nLemma pdiv_pfactor p k : prime p -> pdiv (p ^ k.+1) = p.\nProof. by move=> p_pr; rewrite /pdiv primes_exp ?primes_prime. Qed.\n\n(* \"prime\" logarithms and p-parts. *)\n\nFixpoint logn_rec d m r :=\n  match r, edivn m d with\n  | r'.+1, (_.+1 as m', 0) => (logn_rec d m' r').+1\n  | _, _ => 0\n  end.\n\nDefinition logn p m := if prime p then logn_rec p m m else 0.\n\nLemma lognE p m :\n  logn p m = if [&& prime p, 0 < m & p %| m] then (logn p (m %/ p)).+1 else 0.\nProof.\nrewrite /logn /dvdn; case p_pr: (prime p) => //.\nrewrite /divn modn_def; case def_m: {2 3}m => [|m'] //=.\ncase: edivnP def_m => [[|q] [|r] -> _] // def_m; congr _.+1; rewrite [_.1]/=.\nhave{m def_m}: q < m'.\n  by rewrite -ltnS -def_m addn0 mulnC -{1}[q.+1]mul1n ltn_pmul2r // prime_gt1.\nelim: {m' q}_.+1 {-2}m' q.+1 (ltnSn m') (ltn0Sn q) => // s IHs.\ncase=> [[]|r] //= m; rewrite ltnS => lt_rs m_gt0 le_mr.\nrewrite -{3}[m]prednK //=; case: edivnP => [[|q] [|_] def_q _] //.\nhave{def_q} lt_qm': q < m.-1.\n  by rewrite -[q.+1]muln1 -ltnS prednK // def_q addn0 ltn_pmul2l // prime_gt1.\nhave{le_mr} le_m'r: m.-1 <= r by rewrite -ltnS prednK.\nby rewrite (IHs r) ?(IHs m.-1) // ?(leq_trans lt_qm', leq_trans _ lt_rs).\nQed.\n\nLemma logn_gt0 p n : (0 < logn p n) = (p \\in primes n).\nProof. by rewrite lognE -mem_primes; case: {+}(p \\in _). Qed.\n\nLemma ltn_log0 p n : n < p -> logn p n = 0.\nProof. by case: n => [|n] ltnp; rewrite lognE ?andbF // gtnNdvd ?andbF. Qed.\n\nLemma logn0 p : logn p 0 = 0.\nProof. by rewrite /logn if_same. Qed.\n\nLemma logn1 p : logn p 1 = 0.\nProof. by rewrite lognE dvdn1 /= andbC; case: eqP => // ->. Qed.\n\nLemma pfactor_gt0 p n : 0 < p ^ logn p n.\nProof. by rewrite expn_gt0 lognE; case: (posnP p) => // ->. Qed.\nHint Resolve pfactor_gt0.\n\nLemma pfactor_dvdn p n m : prime p -> m > 0 -> (p ^ n %| m) = (n <= logn p m).\nProof.\nmove=> p_pr; elim: n m => [|n IHn] m m_gt0; first exact: dvd1n.\nrewrite lognE p_pr m_gt0 /=; case dv_pm: (p %| m); last first.\n  apply/dvdnP=> [] [/= q def_m].\n  by rewrite def_m expnS mulnCA dvdn_mulr in dv_pm.\ncase/dvdnP: dv_pm m_gt0 => q ->{m}; rewrite muln_gt0 => /andP[p_gt0 q_gt0].\nby rewrite expnSr dvdn_pmul2r // mulnK // IHn.\nQed.\n\nLemma pfactor_dvdnn p n : p ^ logn p n %| n.\nProof.\ncase: n => // n; case pr_p: (prime p); first by rewrite pfactor_dvdn.\nby rewrite lognE pr_p dvd1n.\nQed.\n\nLemma logn_prime p q : prime q -> logn p q = (p == q).\nProof.\nmove=> pr_q; have q_gt0 := prime_gt0 pr_q; rewrite lognE q_gt0 /=.\ncase pr_p: (prime p); last by case: eqP pr_p pr_q => // -> ->.\nby rewrite dvdn_prime2 //; case: eqP => // ->; rewrite divnn q_gt0 logn1.\nQed.\n\nLemma pfactor_coprime p n :\n  prime p -> n > 0 -> {m | coprime p m & n = m * p ^ logn p n}.\nProof.\nmove=> p_pr n_gt0; set k := logn p n.\nhave dv_pk_n: p ^ k %| n by rewrite pfactor_dvdn.\nexists (n %/ p ^ k); last by rewrite divnK.\nrewrite prime_coprime // -(@dvdn_pmul2r (p ^ k)) ?expn_gt0 ?prime_gt0 //.\nby rewrite -expnS divnK // pfactor_dvdn // ltnn.\nQed.\n\nLemma pfactorK p n : prime p -> logn p (p ^ n) = n.\nProof.\nmove=> p_pr; have pn_gt0: p ^ n > 0 by rewrite expn_gt0 prime_gt0.\napply/eqP; rewrite eqn_leq -pfactor_dvdn // dvdnn andbT.\nby rewrite -(leq_exp2l _ _ (prime_gt1 p_pr)) dvdn_leq // pfactor_dvdn.\nQed.\n\nLemma pfactorKpdiv p n : prime p -> logn (pdiv (p ^ n)) (p ^ n) = n.\nProof. by case: n => // n p_pr; rewrite pdiv_pfactor ?pfactorK. Qed.\n\nLemma dvdn_leq_log p m n : 0 < n -> m %| n -> logn p m <= logn p n.\nProof.\nmove=> n_gt0 dv_m_n; have m_gt0 := dvdn_gt0 n_gt0 dv_m_n.\ncase p_pr: (prime p); last by do 2!rewrite lognE p_pr /=.\nby rewrite -pfactor_dvdn //; apply: dvdn_trans dv_m_n; rewrite pfactor_dvdn.\nQed.\n\nLemma ltn_logl p n : 0 < n -> logn p n < n.\nProof.\nmove=> n_gt0; have [p_gt1 | p_le1] := boolP (1 < p).\n  by rewrite (leq_trans (ltn_expl _ p_gt1)) // dvdn_leq ?pfactor_dvdnn.\nby rewrite lognE (contraNF (@prime_gt1 _)).\nQed.\n\nLemma logn_Gauss p m n : coprime p m -> logn p (m * n) = logn p n.\nProof.\nmove=> co_pm; case p_pr: (prime p); last by rewrite /logn p_pr.\nhave [-> | n_gt0] := posnP n; first by rewrite muln0.\nhave [m0 | m_gt0] := posnP m; first by rewrite m0 prime_coprime ?dvdn0 in co_pm.\nhave mn_gt0: m * n > 0 by rewrite muln_gt0 m_gt0.\napply/eqP; rewrite eqn_leq andbC dvdn_leq_log ?dvdn_mull //.\nset k := logn p _; have: p ^ k %| m * n by rewrite pfactor_dvdn.\nby rewrite Gauss_dvdr ?coprime_expl // -pfactor_dvdn.\nQed.\n\nLemma lognM p m n : 0 < m -> 0 < n -> logn p (m * n) = logn p m + logn p n.\nProof.\ncase p_pr: (prime p); last by rewrite /logn p_pr.\nhave xlp := pfactor_coprime p_pr.\ncase/xlp=> m' co_m' def_m /xlp[n' co_n' def_n] {xlp}.\nby rewrite {1}def_m {1}def_n mulnCA -mulnA -expnD !logn_Gauss // pfactorK.\nQed.\n\nLemma lognX p m n : logn p (m ^ n) = n * logn p m.\nProof.\ncase p_pr: (prime p); last by rewrite /logn p_pr muln0.\nelim: n => [|n IHn]; first by rewrite logn1.\nhave [->|m_gt0] := posnP m; first by rewrite exp0n // lognE andbF muln0.\nby rewrite expnS lognM ?IHn // expn_gt0 m_gt0.\nQed.\n\nLemma logn_div p m n : m %| n -> logn p (n %/ m) = logn p n - logn p m.\nProof.\nrewrite dvdn_eq => /eqP def_n.\ncase: (posnP n) => [-> |]; first by rewrite div0n logn0.\nby rewrite -{1 3}def_n muln_gt0 => /andP[q_gt0 m_gt0]; rewrite lognM ?addnK.\nQed.\n\nLemma dvdn_pfactor p d n : prime p ->\n  reflect (exists2 m, m <= n & d = p ^ m) (d %| p ^ n).\nProof.\nmove=> p_pr; have pn_gt0: p ^ n > 0 by rewrite expn_gt0 prime_gt0.\napply: (iffP idP) => [dv_d_pn|[m le_m_n ->]]; last first.\n  by rewrite -(subnK le_m_n) expnD dvdn_mull.\nexists (logn p d); first by rewrite -(pfactorK n p_pr) dvdn_leq_log.\nhave d_gt0: d > 0 by exact: dvdn_gt0 dv_d_pn.\ncase: (pfactor_coprime p_pr d_gt0) => q co_p_q def_d.\nrewrite {1}def_d ((q =P 1) _) ?mul1n // -dvdn1.\nsuff: q %| p ^ n * 1 by rewrite Gauss_dvdr // coprime_sym coprime_expl.\nby rewrite muln1 (dvdn_trans _ dv_d_pn) // def_d dvdn_mulr.\nQed.\n\nLemma prime_decompE n : prime_decomp n = [seq (p, logn p n) | p <- primes n].\nProof.\ncase: n => // n; pose f0 := (0, 0); rewrite -map_comp.\napply: (@eq_from_nth _ f0) => [|i lt_i_n]; first by rewrite size_map.\nrewrite (nth_map f0) //; case def_f: (nth _ _ i) => [p e] /=.\ncongr (_, _); rewrite [n.+1]prod_prime_decomp //.\nhave: (p, e) \\in prime_decomp n.+1 by rewrite -def_f mem_nth.\ncase/mem_prime_decomp=> pr_p _ _.\nrewrite (big_nth f0) big_mkord (bigD1 (Ordinal lt_i_n)) //=.\nrewrite def_f mulnC logn_Gauss ?pfactorK //.\napply big_ind => [|m1 m2 com1 com2| [j ltj] /=]; first exact: coprimen1.\n  by rewrite coprime_mulr com1.\nrewrite -val_eqE /= => nji; case def_j: (nth _ _ j) => [q e1] /=.\nhave: (q, e1) \\in prime_decomp n.+1 by rewrite -def_j mem_nth.\ncase/mem_prime_decomp=> pr_q e1_gt0 _; rewrite coprime_pexpr //.\nrewrite prime_coprime // dvdn_prime2 //; apply: contra nji => eq_pq.\nrewrite -(nth_uniq 0 _ _ (primes_uniq n.+1)) ?size_map //=.\nby rewrite !(nth_map f0) //  def_f def_j /= eq_sym.\nQed.\n\n(* Some combinatorial formulae. *)\n\nLemma divn_count_dvd d n : n %/ d = \\sum_(1 <= i < n.+1) (d %| i).\nProof.\nhave [-> | d_gt0] := posnP d; first by rewrite big_add1 divn0 big1.\napply: (@addnI (d %| 0)); rewrite -(@big_ltn _ 0 _ 0 _ (dvdn d)) // big_mkord.\nrewrite (partition_big (fun i : 'I_n.+1 => inord (i %/ d)) 'I_(n %/ d).+1) //=.\nrewrite dvdn0 add1n -{1}[_.+1]card_ord -sum1_card; apply: eq_bigr => [[q ?] _].\nrewrite (bigD1 (inord (q * d))) /eq_op /= !inordK ?ltnS -?leq_divRL ?mulnK //.\nrewrite dvdn_mull ?big1 // => [[i /= ?] /andP[/eqP <- /negPf]].\nby rewrite eq_sym dvdn_eq inordK ?ltnS ?leq_div2r // => ->.\nQed.\n\nLemma logn_count_dvd p n : prime p -> logn p n = \\sum_(1 <= k < n) (p ^ k %| n).\nProof.\nrewrite big_add1 => p_prime; case: n => [|n]; first by rewrite logn0 big_geq.\nrewrite big_mkord -big_mkcond (eq_bigl _ _ (fun _ => pfactor_dvdn _ _ _)) //=.\nby rewrite big_ord_narrow ?sum1_card ?card_ord // -ltnS ltn_logl.\nQed.\n\n(* Truncated real log. *)\n\nDefinition trunc_log p n :=\n  let fix loop n k :=\n    if k is k'.+1 then if p <= n then (loop (n %/ p) k').+1 else 0 else 0\n  in loop n n.\n\nLemma trunc_log_bounds p n :\n  1 < p -> 0 < n -> let k := trunc_log p n in p ^ k <= n < p ^ k.+1.\nProof.\nrewrite {+}/trunc_log => p_gt1; have p_gt0 := ltnW p_gt1.\nelim: n {-2 5}n (leqnn n) => [|m IHm] [|n] //=; rewrite ltnS => le_n_m _.\nhave [le_p_n | // ] := leqP p _; rewrite 2!expnSr -leq_divRL -?ltn_divLR //.\nby apply: IHm; rewrite ?divn_gt0 // -ltnS (leq_trans (ltn_Pdiv _ _)).\nQed.\n\nLemma trunc_log_ltn p n : 1 < p -> n < p ^ (trunc_log p n).+1.\nProof.\nhave [-> | n_gt0] := posnP n; first by move=> /ltnW; rewrite expn_gt0.\nby case/trunc_log_bounds/(_ n_gt0)/andP.\nQed.\n\nLemma trunc_logP p n : 1 < p -> 0 < n -> p ^ trunc_log p n <= n.\nProof. by move=> p_gt1 /(trunc_log_bounds p_gt1)/andP[]. Qed.\n\nLemma trunc_log_max p k j : 1 < p -> p ^ j <= k -> j <= trunc_log p k.\nProof.\nmove=> p_gt1 le_pj_k; rewrite -ltnS -(@ltn_exp2l p) //.\nexact: leq_ltn_trans (trunc_log_ltn _ _).\nQed.\n\n(* pi- parts *)\n\n(* Testing for membership in set of prime factors. *)\n\nCanonical nat_pred_pred := Eval hnf in [predType of nat_pred].\n\nCoercion nat_pred_of_nat (p : nat) : nat_pred := pred1 p.\n\nSection NatPreds.\n\nVariables (n : nat) (pi : nat_pred).\n\nDefinition negn : nat_pred := [predC pi].\n\nDefinition pnat : pred nat := fun m => (m > 0) && all (mem pi) (primes m).\n\nDefinition partn := \\prod_(0 <= p < n.+1 | p \\in pi) p ^ logn p n.\n\nEnd NatPreds.\n\nNotation \"pi ^'\" := (negn pi) (at level 2, format \"pi ^'\") : nat_scope.\n\nNotation \"pi .-nat\" := (pnat pi) (at level 2, format \"pi .-nat\") : nat_scope.\n\nNotation \"n `_ pi\" := (partn n pi) : nat_scope.\n\nSection PnatTheory.\n\nImplicit Types (n p : nat) (pi rho : nat_pred).\n\nLemma negnK pi : pi^'^' =i pi.\nProof. move=> p; exact: negbK. Qed.\n\nLemma eq_negn pi1 pi2 : pi1 =i pi2 -> pi1^' =i pi2^'.\nProof. by move=> eq_pi n; rewrite 3!inE /= eq_pi. Qed.\n\nLemma eq_piP m n : \\pi(m) =i \\pi(n) <-> \\pi(m) = \\pi(n).\nProof.\nrewrite /pi_of; have eqs := eq_sorted_irr ltn_trans ltnn.\nby split=> [|-> //]; move/(eqs _ _ (sorted_primes m) (sorted_primes n)) ->.\nQed.\n\nLemma part_gt0 pi n : 0 < n`_pi.\nProof. exact: prodn_gt0. Qed.\nHint Resolve part_gt0.\n\nLemma sub_in_partn pi1 pi2 n :\n  {in \\pi(n), {subset pi1 <= pi2}} -> n`_pi1 %| n`_pi2.\nProof.\nmove=> pi12; rewrite ![n`__]big_mkcond /=.\napply (big_ind2 (fun m1 m2 => m1 %| m2)) => // [*|p _]; first exact: dvdn_mul.\nrewrite lognE -mem_primes; case: ifP => pi1p; last exact: dvd1n.\nby case: ifP => pr_p; [rewrite pi12 | rewrite if_same].\nQed.\n\nLemma eq_in_partn pi1 pi2 n : {in \\pi(n), pi1 =i pi2} -> n`_pi1 = n`_pi2.\nProof.\nby move=> pi12; apply/eqP; rewrite eqn_dvd ?sub_in_partn // => p /pi12->.\nQed.\n\nLemma eq_partn pi1 pi2 n : pi1 =i pi2 -> n`_pi1 = n`_pi2.\nProof. by move=> pi12; apply: eq_in_partn => p _. Qed.\n\nLemma partnNK pi n : n`_pi^'^' = n`_pi.\nProof. by apply: eq_partn; exact: negnK. Qed.\n\nLemma widen_partn m pi n :\n  n <= m -> n`_pi = \\prod_(0 <= p < m.+1 | p \\in pi) p ^ logn p n.\nProof.\nmove=> le_n_m; rewrite big_mkcond /=.\nrewrite [n`_pi](big_nat_widen _ _ m.+1) // big_mkcond /=.\napply: eq_bigr => p _; rewrite ltnS lognE.\nby case: and3P => [[_ n_gt0 p_dv_n]|]; rewrite ?if_same // andbC dvdn_leq.\nQed.\n\nLemma partn0 pi : 0`_pi = 1.\nProof. by apply: big1_seq => [] [|n]; rewrite andbC. Qed.\n\nLemma partn1 pi : 1`_pi = 1.\nProof. by apply: big1_seq => [] [|[|n]]; rewrite andbC. Qed.\n\nLemma partnM pi m n : m > 0 -> n > 0 -> (m * n)`_pi = m`_pi * n`_pi.\nProof.\nhave le_pmul m' n': m' > 0 -> n' <= m' * n' by move/prednK <-; exact: leq_addr.\nmove=> mpos npos; rewrite !(@widen_partn (n * m)) 3?(le_pmul, mulnC) //.\nrewrite !big_mkord -big_split; apply: eq_bigr => p _ /=.\nby rewrite lognM // expnD.\nQed.\n\nLemma partnX pi m n : (m ^ n)`_pi = m`_pi ^ n.\nProof.\nelim: n => [|n IHn]; first exact: partn1.\nrewrite expnS; case: (posnP m) => [->|m_gt0]; first by rewrite partn0 exp1n.\nby rewrite expnS partnM ?IHn // expn_gt0 m_gt0.\nQed.\n\nLemma partn_dvd pi m n : n > 0 -> m %| n -> m`_pi %| n`_pi.\nProof.\nmove=> n_gt0 dvmn; case/dvdnP: dvmn n_gt0 => q ->{n}.\nby rewrite muln_gt0 => /andP[q_gt0 m_gt0]; rewrite partnM ?dvdn_mull.\nQed.\n\nLemma p_part p n : n`_p = p ^ logn p n.\nProof.\ncase (posnP (logn p n)) => [log0 |].\n  by rewrite log0 [n`_p]big1_seq // => q; case/andP; move/eqnP->; rewrite log0.\nrewrite logn_gt0 mem_primes; case/and3P=> _ n_gt0 dv_p_n.\nhave le_p_n: p < n.+1 by rewrite ltnS dvdn_leq.\nby rewrite [n`_p]big_mkord (big_pred1 (Ordinal le_p_n)).\nQed.\n\nLemma p_part_eq1 p n : (n`_p == 1) = (p \\notin \\pi(n)).\nProof.\nrewrite mem_primes p_part lognE; case: and3P => // [[p_pr _ _]].\nby rewrite -dvdn1 pfactor_dvdn // logn1.\nQed.\n\nLemma p_part_gt1 p n : (n`_p > 1) = (p \\in \\pi(n)).\nProof. by rewrite ltn_neqAle part_gt0 andbT eq_sym p_part_eq1 negbK. Qed.\n\nLemma primes_part pi n : primes n`_pi = filter (mem pi) (primes n).\nProof.\nhave ltnT := ltn_trans.\ncase: (posnP n) => [-> | n_gt0]; first by rewrite partn0.\napply: (eq_sorted_irr ltnT ltnn); rewrite ?(sorted_primes, sorted_filter) //.\nmove=> p; rewrite mem_filter /= !mem_primes n_gt0 part_gt0 /=.\napply/andP/and3P=> [[p_pr] | [pi_p p_pr dv_p_n]].\n  rewrite /partn; apply big_ind => [|n1 n2 IHn1 IHn2|q pi_q].\n  - by rewrite dvdn1; case: eqP p_pr => // ->.\n  - by rewrite Euclid_dvdM //; case/orP.\n  rewrite -{1}(expn1 p) pfactor_dvdn // lognX muln_gt0.\n  rewrite logn_gt0 mem_primes n_gt0 - andbA /=; case/and3P=> pr_q dv_q_n.\n  by rewrite logn_prime //; case: eqP => // ->.\nhave le_p_n: p < n.+1 by rewrite ltnS dvdn_leq.\nrewrite [n`_pi]big_mkord (bigD1 (Ordinal le_p_n)) //= dvdn_mulr //.\nby rewrite lognE p_pr n_gt0 dv_p_n expnS dvdn_mulr.\nQed.\n\nLemma filter_pi_of n m : n < m -> filter \\pi(n) (index_iota 0 m) = primes n.\nProof.\nmove=> lt_n_m; have ltnT := ltn_trans; apply: (eq_sorted_irr ltnT ltnn).\n- by rewrite sorted_filter // iota_ltn_sorted.\n- exact: sorted_primes.\nmove=> p; rewrite mem_filter mem_index_iota /= mem_primes; case: and3P => //.\ncase=> _ n_gt0 dv_p_n; apply: leq_ltn_trans lt_n_m; exact: dvdn_leq.\nQed.\n\nLemma partn_pi n : n > 0 -> n`_\\pi(n) = n.\nProof.\nmove=> n_gt0; rewrite {3}(prod_prime_decomp n_gt0) prime_decompE big_map.\nby rewrite -[n`__]big_filter filter_pi_of.\nQed.\n\nLemma partnT n : n > 0 -> n`_predT = n.\nProof.\nmove=> n_gt0; rewrite -{2}(partn_pi n_gt0) {2}/partn big_mkcond /=.\nby apply: eq_bigr => p _; rewrite -logn_gt0; case: (logn p _).\nQed.\n\nLemma partnC pi n : n > 0 -> n`_pi * n`_pi^' = n.\nProof.\nmove=> n_gt0; rewrite -{3}(partnT n_gt0) /partn.\ndo 2!rewrite mulnC big_mkcond /=; rewrite -big_split; apply: eq_bigr => p _ /=.\nby rewrite mulnC inE /=; case: (p \\in pi); rewrite /= (muln1, mul1n).\nQed.\n\nLemma dvdn_part pi n : n`_pi %| n.\nProof. by case: n => // n; rewrite -{2}[n.+1](@partnC pi) // dvdn_mulr. Qed.\n\nLemma logn_part p m : logn p m`_p = logn p m.\nProof.\ncase p_pr: (prime p); first by rewrite p_part pfactorK.\nby rewrite lognE (lognE p m) p_pr.\nQed.\n    \nLemma partn_lcm pi m n : m > 0 -> n > 0 -> (lcmn m n)`_pi = lcmn m`_pi n`_pi.\nProof.\nmove=> m_gt0 n_gt0; have p_gt0: lcmn m n > 0 by rewrite lcmn_gt0 m_gt0.\napply/eqP; rewrite eqn_dvd dvdn_lcm !partn_dvd ?dvdn_lcml ?dvdn_lcmr //.\nrewrite -(dvdn_pmul2r (part_gt0 pi^' (lcmn m n))) partnC // dvdn_lcm !andbT.\nrewrite -{1}(partnC pi m_gt0) andbC -{1}(partnC pi n_gt0).\nby rewrite !dvdn_mul ?partn_dvd ?dvdn_lcml ?dvdn_lcmr.\nQed. \n\nLemma partn_gcd pi m n : m > 0 -> n > 0 -> (gcdn m n)`_pi = gcdn m`_pi n`_pi.\nProof.\nmove=> m_gt0 n_gt0; have p_gt0: gcdn m n > 0 by rewrite gcdn_gt0 m_gt0.\napply/eqP; rewrite eqn_dvd dvdn_gcd !partn_dvd ?dvdn_gcdl ?dvdn_gcdr //=.\nrewrite -(dvdn_pmul2r (part_gt0 pi^' (gcdn m n))) partnC // dvdn_gcd.\nrewrite -{3}(partnC pi m_gt0) andbC -{3}(partnC pi n_gt0).\nby rewrite !dvdn_mul ?partn_dvd ?dvdn_gcdl ?dvdn_gcdr.\nQed. \n\nLemma partn_biglcm (I : finType) (P : pred I) F pi :\n    (forall i, P i -> F i > 0) ->\n  (\\big[lcmn/1%N]_(i | P i) F i)`_pi = \\big[lcmn/1%N]_(i | P i) (F i)`_pi.\nProof.\nmove=> F_gt0; set m := \\big[lcmn/1%N]_(i | P i) F i.\nhave m_gt0: 0 < m by apply big_ind => // p q p_gt0; rewrite lcmn_gt0 p_gt0.\napply/eqP; rewrite eqn_dvd andbC; apply/andP; split.\n  by apply/dvdn_biglcmP=> i Pi; rewrite partn_dvd // (@biglcmn_sup _ i).\nrewrite -(dvdn_pmul2r (part_gt0 pi^' m)) partnC //.\napply/dvdn_biglcmP=> i Pi; rewrite -(partnC pi (F_gt0 i Pi)) dvdn_mul //.\n  by rewrite (@biglcmn_sup _ i).\nby rewrite partn_dvd // (@biglcmn_sup _ i).\nQed.\n\nLemma partn_biggcd (I : finType) (P : pred I) F pi :\n    #|SimplPred P| > 0 -> (forall i, P i -> F i > 0) ->\n  (\\big[gcdn/0]_(i | P i) F i)`_pi = \\big[gcdn/0]_(i | P i) (F i)`_pi.\nProof.\nmove=> ntP F_gt0; set d := \\big[gcdn/0]_(i | P i) F i.\nhave d_gt0: 0 < d.\n  case/card_gt0P: ntP => i /= Pi; have:= F_gt0 i Pi.\n  rewrite !lt0n -!dvd0n; apply: contra => dv0d.\n  by rewrite (dvdn_trans dv0d) // (@biggcdn_inf _ i).\napply/eqP; rewrite eqn_dvd; apply/andP; split.\n  by apply/dvdn_biggcdP=> i Pi; rewrite partn_dvd ?F_gt0 // (@biggcdn_inf _ i).\nrewrite -(dvdn_pmul2r (part_gt0 pi^' d)) partnC //.\napply/dvdn_biggcdP=> i Pi; rewrite -(partnC pi (F_gt0 i Pi)) dvdn_mul //.\n  by rewrite (@biggcdn_inf _ i).\nby rewrite partn_dvd ?F_gt0 // (@biggcdn_inf _ i).\nQed.\n\nLemma sub_in_pnat pi rho n :\n  {in \\pi(n), {subset pi <= rho}} -> pi.-nat n -> rho.-nat n.\nProof.\nrewrite /pnat => subpi /andP[-> pi_n].\napply/allP=> p pr_p; apply: subpi => //; exact: (allP pi_n).\nQed.\n\nLemma eq_in_pnat pi rho n : {in \\pi(n), pi =i rho} -> pi.-nat n = rho.-nat n.\nProof. by move=> eqpi; apply/idP/idP; apply: sub_in_pnat => p /eqpi->. Qed.\n\nLemma eq_pnat pi rho n : pi =i rho -> pi.-nat n = rho.-nat n.\nProof. by move=> eqpi; apply: eq_in_pnat => p _. Qed.\n\nLemma pnatNK pi n : pi^'^'.-nat n = pi.-nat n.\nProof. exact: eq_pnat (negnK pi). Qed.\n\nLemma pnatI pi rho n : [predI pi & rho].-nat n = pi.-nat n && rho.-nat n.\nProof. by rewrite /pnat andbCA all_predI !andbA andbb. Qed.\n\nLemma pnat_mul pi m n : pi.-nat (m * n) = pi.-nat m && pi.-nat n.\nProof.\nrewrite /pnat muln_gt0 andbCA -andbA andbCA.\ncase: posnP => // n_gt0; case: posnP => //= m_gt0.\napply/allP/andP=> [pi_mn | [pi_m pi_n] p].\n  by split; apply/allP=> p m_p; apply: pi_mn; rewrite primes_mul // m_p ?orbT.\nrewrite primes_mul // => /orP[]; [exact: (allP pi_m) | exact: (allP pi_n)].\nQed.\n\nLemma pnat_exp pi m n : pi.-nat (m ^ n) = pi.-nat m || (n == 0).\nProof. by case: n => [|n]; rewrite orbC // /pnat expn_gt0 orbC primes_exp. Qed.\n\nLemma part_pnat pi n : pi.-nat n`_pi.\nProof.\nrewrite /pnat primes_part part_gt0.\nby apply/allP=> p; rewrite mem_filter => /andP[].\nQed.\n\nLemma pnatE pi p : prime p -> pi.-nat p = (p \\in pi).\nProof. by move=> pr_p; rewrite /pnat prime_gt0 ?primes_prime //= andbT. Qed.\n\nLemma pnat_id p : prime p -> p.-nat p.\nProof. by move=> pr_p; rewrite pnatE ?inE /=. Qed.\n\nLemma coprime_pi' m n : m > 0 -> n > 0 -> coprime m n = \\pi(m)^'.-nat n.\nProof.\nby move=> m_gt0 n_gt0; rewrite /pnat n_gt0 all_predC coprime_has_primes.\nQed.\n\nLemma pnat_pi n : n > 0 -> \\pi(n).-nat n.\nProof. rewrite /pnat => ->; exact/allP. Qed.\n\nLemma pi_of_dvd m n : m %| n -> n > 0 -> {subset \\pi(m) <= \\pi(n)}.\nProof.\nmove=> m_dv_n n_gt0 p; rewrite !mem_primes n_gt0 => /and3P[-> _ p_dv_m].\nexact: dvdn_trans p_dv_m m_dv_n.\nQed.\n\nLemma pi_ofM m n : m > 0 -> n > 0 -> \\pi(m * n) =i [predU \\pi(m) & \\pi(n)].\nProof. move=> m_gt0 n_gt0 p; exact: primes_mul. Qed.\n\nLemma pi_of_part pi n : n > 0 -> \\pi(n`_pi) =i [predI \\pi(n) & pi].\nProof. by move=> n_gt0 p; rewrite /pi_of primes_part mem_filter andbC. Qed.\n\nLemma pi_of_exp p n : n > 0 -> \\pi(p ^ n) = \\pi(p).\nProof. by move=> n_gt0; rewrite /pi_of primes_exp. Qed.\n\nLemma pi_of_prime p : prime p -> \\pi(p) =i (p : nat_pred).\nProof. by move=> pr_p q; rewrite /pi_of primes_prime // mem_seq1. Qed.\n\nLemma p'natEpi p n : n > 0 -> p^'.-nat n = (p \\notin \\pi(n)).\nProof. by case: n => // n _; rewrite /pnat all_predC has_pred1. Qed.\n\nLemma p'natE p n : prime p -> p^'.-nat n = ~~ (p %| n).\nProof.\ncase: n => [|n] p_pr; first by case: p p_pr.\nby rewrite p'natEpi // mem_primes p_pr.\nQed.\n\nLemma pnatPpi pi n p : pi.-nat n -> p \\in \\pi(n) -> p \\in pi.\nProof. by case/andP=> _ /allP; exact. Qed.\n\nLemma pnat_dvd m n pi : m %| n -> pi.-nat n -> pi.-nat m.\nProof. by case/dvdnP=> q ->; rewrite pnat_mul; case/andP. Qed.\n\nLemma pnat_div m n pi : m %| n -> pi.-nat n -> pi.-nat (n %/ m).\nProof.\ncase/dvdnP=> q ->; rewrite pnat_mul andbC => /andP[].\nby case: m => // m _; rewrite mulnK.\nQed.\n\nLemma pnat_coprime pi m n : pi.-nat m -> pi^'.-nat n -> coprime m n.\nProof.\ncase/andP=> m_gt0 pi_m /andP[n_gt0 pi'_n].\nrewrite coprime_has_primes //; apply/hasPn=> p /(allP pi'_n).\napply: contra; exact: allP.\nQed.\n\nLemma p'nat_coprime pi m n : pi^'.-nat m -> pi.-nat n -> coprime m n.\nProof. by move=> pi'm pi_n; rewrite (pnat_coprime pi'm) ?pnatNK. Qed.\n\nLemma sub_pnat_coprime pi rho m n :\n  {subset rho <= pi^'} -> pi.-nat m -> rho.-nat n -> coprime m n.\nProof.\nby move=> pi'rho pi_m; move/(sub_in_pnat (in1W pi'rho)); exact: pnat_coprime.\nQed.\n\nLemma coprime_partC pi m n : coprime m`_pi n`_pi^'.\nProof. by apply: (@pnat_coprime pi); exact: part_pnat. Qed.\n\nLemma pnat_1 pi n : pi.-nat n -> pi^'.-nat n -> n = 1.\nProof.\nby move=> pi_n pi'_n; rewrite -(eqnP (pnat_coprime pi_n pi'_n)) gcdnn.\nQed.\n\nLemma part_pnat_id pi n : pi.-nat n -> n`_pi = n.\nProof.\ncase/andP=> n_gt0 pi_n.\nrewrite -{2}(partnT n_gt0) /partn big_mkcond; apply: eq_bigr=> p _.\ncase: (posnP (logn p n)) => [-> |]; first by rewrite if_same.\nby rewrite logn_gt0 => /(allP pi_n)/= ->.\nQed.\n\nLemma part_p'nat pi n : pi^'.-nat n -> n`_pi = 1.\nProof.\ncase/andP=> n_gt0 pi'_n; apply: big1_seq => p /andP[pi_p _].\ncase: (posnP (logn p n)) => [-> //|].\nby rewrite logn_gt0; move/(allP pi'_n); case/negP.\nQed.\n\nLemma partn_eq1 pi n : n > 0 -> (n`_pi == 1) = pi^'.-nat n.\nProof.\nmove=> n_gt0; apply/eqP/idP=> [pi_n_1|]; last exact: part_p'nat.\nby rewrite -(partnC pi n_gt0) pi_n_1 mul1n part_pnat.\nQed.\n\nLemma pnatP pi n :\n  n > 0 -> reflect (forall p, prime p -> p %| n -> p \\in pi) (pi.-nat n).\nProof.\nmove=> n_gt0; rewrite /pnat n_gt0.\napply: (iffP allP) => /= pi_n p => [pr_p p_n|].\n  by rewrite pi_n // mem_primes pr_p n_gt0.\nby rewrite mem_primes n_gt0 /=; case/andP; move: p.\nQed.\n\nLemma pi_pnat pi p n : p.-nat n -> p \\in pi -> pi.-nat n.\nProof.\nmove=> p_n pi_p; have [n_gt0 _] := andP p_n.\nby apply/pnatP=> // q q_pr /(pnatP _ n_gt0 p_n _ q_pr)/eqnP->.\nQed.\n\nLemma p_natP p n : p.-nat n -> {k | n = p ^ k}.\nProof. by move=> p_n; exists (logn p n); rewrite -p_part part_pnat_id. Qed.\n\nLemma pi'_p'nat pi p n : pi^'.-nat n -> p \\in pi -> p^'.-nat n.\nProof.\nmove=> pi'n pi_p; apply: sub_in_pnat pi'n => q _.\nby apply: contraNneq => ->.\nQed.\n \nLemma pi_p'nat p pi n : pi.-nat n -> p \\in pi^' -> p^'.-nat n.\nProof. by move=> pi_n; apply: pi'_p'nat; rewrite pnatNK. Qed.\n \nLemma partn_part pi rho n : {subset pi <= rho} -> n`_rho`_pi = n`_pi.\nProof.\nmove=> pi_sub_rho; have [->|n_gt0] := posnP n; first by rewrite !partn0 partn1.\nrewrite -{2}(partnC rho n_gt0) partnM //.\nsuffices: pi^'.-nat n`_rho^' by move/part_p'nat->; rewrite muln1.\napply: sub_in_pnat (part_pnat _ _) => q _; apply: contra; exact: pi_sub_rho.\nQed.\n\nLemma partnI pi rho n : n`_[predI pi & rho] = n`_pi`_rho.\nProof.\nrewrite -(@partnC [predI pi & rho] _`_rho) //.\nsymmetry; rewrite 2?partn_part; try by move=> p /andP [].\nrewrite mulnC part_p'nat ?mul1n // pnatNK pnatI part_pnat andbT.\nexact: pnat_dvd (dvdn_part _ _) (part_pnat _ _).\nQed.\n\nLemma odd_2'nat n : odd n = 2^'.-nat n.\nProof. by case: n => // n; rewrite p'natE // dvdn2 negbK. Qed.\n\nEnd PnatTheory.\nHint Resolve part_gt0.\n\n(************************************)\n(* Properties of the divisors list. *)\n(************************************)\n\nLemma divisors_correct n : n > 0 ->\n  [/\\ uniq (divisors n), sorted leq (divisors n)\n    & forall d, (d \\in divisors n) = (d %| n)].\nProof.\nmove/prod_prime_decomp=> def_n; rewrite {4}def_n {def_n}.\nhave: all prime (primes n) by apply/allP=> p; rewrite mem_primes; case/andP.\nhave:= primes_uniq n; rewrite /primes /divisors; move/prime_decomp: n.\nelim=> [|[p e] pd] /=; first by split=> // d; rewrite big_nil dvdn1 mem_seq1.\nrewrite big_cons /=; move: (foldr _ _ pd) => divs.\nmove=> IHpd /andP[npd_p Upd] /andP[pr_p pr_pd].\nhave lt0p: 0 < p by exact: prime_gt0.\nhave {IHpd Upd}[Udivs Odivs mem_divs] := IHpd Upd pr_pd.\nhave ndivs_p m: p * m \\notin divs.\n  suffices: p \\notin divs; rewrite !mem_divs.\n    by apply: contra => /dvdnP[n ->]; rewrite mulnCA dvdn_mulr.\n  have ndv_p_1: ~~(p %| 1) by rewrite dvdn1 neq_ltn orbC prime_gt1.\n  rewrite big_seq; elim/big_ind: _ => [//|u v npu npv|[q f] /= pd_qf].\n    by rewrite Euclid_dvdM //; apply/norP.\n  elim: (f) => // f'; rewrite expnS Euclid_dvdM // orbC negb_or => -> {f'}/=.\n  have pd_q: q \\in unzip1 pd by apply/mapP; exists (q, f).\n  by apply: contra npd_p; rewrite dvdn_prime2 // ?(allP pr_pd) // => /eqP->.\nelim: e => [|e] /=; first by split=> // d; rewrite mul1n.\nhave Tmulp_inj: injective (NatTrec.mul p).\n  by move=> u v /eqP; rewrite !natTrecE eqn_pmul2l // => /eqP.\nmove: (iter e _ _) => divs' [Udivs' Odivs' mem_divs']; split=> [||d].\n- rewrite merge_uniq cat_uniq map_inj_uniq // Udivs Udivs' andbT /=.\n  apply/hasP=> [[d dv_d /mapP[d' _ def_d]]].\n  by case/idPn: dv_d; rewrite def_d natTrecE.\n- rewrite (merge_sorted leq_total) //; case: (divs') Odivs' => //= d ds.\n  rewrite (@map_path _ _ _ _ leq xpred0) ?has_pred0 // => u v _.\n  by rewrite !natTrecE leq_pmul2l.\nrewrite mem_merge mem_cat; case dv_d_p: (p %| d).\n  case/dvdnP: dv_d_p => d' ->{d}; rewrite mulnC (negbTE (ndivs_p d')) orbF.\n  rewrite expnS -mulnA dvdn_pmul2l // -mem_divs'.\n  by rewrite -(mem_map Tmulp_inj divs') natTrecE.\ncase pdiv_d: (_ \\in _).\n  by case/mapP: pdiv_d dv_d_p => d' _ ->; rewrite natTrecE dvdn_mulr.\nrewrite mem_divs Gauss_dvdr // coprime_sym.\nby rewrite coprime_expl ?prime_coprime ?dv_d_p.\nQed.\n\nLemma sorted_divisors n : sorted leq (divisors n).\nProof. by case: (posnP n) => [-> | /divisors_correct[]]. Qed.\n\nLemma divisors_uniq n : uniq (divisors n).\nProof. by case: (posnP n) => [-> | /divisors_correct[]]. Qed.\n\nLemma sorted_divisors_ltn n : sorted ltn (divisors n).\nProof. by rewrite ltn_sorted_uniq_leq divisors_uniq sorted_divisors. Qed.\n\nLemma dvdn_divisors d m : 0 < m -> (d %| m) = (d \\in divisors m).\nProof. by case/divisors_correct. Qed.\n\nLemma divisor1 n : 1 \\in divisors n.\nProof. by case: n => // n; rewrite -dvdn_divisors // dvd1n. Qed.\n\nLemma divisors_id n : 0 < n -> n \\in divisors n.\nProof. by move/dvdn_divisors <-. Qed.\n\n(* Big sum / product lemmas*)\n\nLemma dvdn_sum d I r (K : pred I) F :\n  (forall i, K i -> d %| F i) -> d %| \\sum_(i <- r | K i) F i.\nProof. move=> dF; elim/big_ind: _ => //; exact: dvdn_add. Qed.\n\nLemma dvdn_partP n m : 0 < n ->\n  reflect (forall p, p \\in \\pi(n) -> n`_p %| m) (n %| m).\nProof.\nmove=> n_gt0; apply: (iffP idP) => n_dvd_m => [p _|].\n  apply: dvdn_trans n_dvd_m; exact: dvdn_part.\nhave [-> // | m_gt0] := posnP m.\nrewrite -(partnT n_gt0) -(partnT m_gt0).\nrewrite !(@widen_partn (m + n)) ?leq_addl ?leq_addr // /in_mem /=.\nelim/big_ind2: _ => // [* | q _]; first exact: dvdn_mul.\nhave [-> // | ] := posnP (logn q n); rewrite logn_gt0 => q_n.\nhave pr_q: prime q by move: q_n; rewrite mem_primes; case/andP.\nby have:= n_dvd_m q q_n; rewrite p_part !pfactor_dvdn // pfactorK.\nQed.\n\nLemma modn_partP n a b : 0 < n ->\n  reflect (forall p : nat, p \\in \\pi(n) -> a = b %[mod n`_p]) (a == b %[mod n]).\nProof.\nmove=> n_gt0; wlog le_b_a: a b / b <= a.\n  move=> IH; case: (leqP b a) => [|/ltnW] /IH {IH}// IH.\n  by rewrite eq_sym; apply: (iffP IH) => eqab p; move/eqab.\nrewrite eqn_mod_dvd //; apply: (iffP (dvdn_partP _ n_gt0)) => eqab p /eqab;\n  by rewrite -eqn_mod_dvd // => /eqP.   \nQed.\n\n(* The Euler totient function *)\n\nLemma totientE n :\n  n > 0 -> totient n = \\prod_(p <- primes n) (p.-1 * p ^ (logn p n).-1).\nProof.\nmove=> n_gt0; rewrite /totient n_gt0 prime_decompE unlock.\nby elim: (primes n) => //= [p pr ->]; rewrite !natTrecE.\nQed.\n\nLemma totient_gt0 n : (0 < totient n) = (0 < n).\nProof.\ncase: n => // n; rewrite totientE // big_seq_cond prodn_cond_gt0 // => p.\nby rewrite mem_primes muln_gt0 expn_gt0; case: p => [|[|]].\nQed.\n\nLemma totient_pfactor p e :\n  prime p -> e > 0 -> totient (p ^ e) = p.-1 * p ^ e.-1.\nProof.\nmove=> p_pr e_gt0; rewrite totientE ?expn_gt0 ?prime_gt0 //.\nby rewrite primes_exp // primes_prime // unlock /= muln1 pfactorK.\nQed.\n\nLemma totient_coprime m n :\n  coprime m n -> totient (m * n) = totient m * totient n.\nProof.\nmove=> co_mn; have [-> //| m_gt0] := posnP m.\nhave [->|n_gt0] := posnP n; first by rewrite !muln0.\nrewrite !totientE ?muln_gt0 ?m_gt0 //.\nhave /(eq_big_perm _)->: perm_eq (primes (m * n)) (primes m ++ primes n).\n  apply: uniq_perm_eq => [||p]; first exact: primes_uniq.\n    by rewrite cat_uniq !primes_uniq -coprime_has_primes // co_mn.\n  by rewrite mem_cat primes_mul.\nrewrite big_cat /= !big_seq.\ncongr (_ * _); apply: eq_bigr => p; rewrite mem_primes => /and3P[_ _ dvp].\n  rewrite (mulnC m) logn_Gauss //; move: co_mn.\n  by rewrite -(divnK dvp) coprime_mull => /andP[].\nrewrite logn_Gauss //; move: co_mn.\nby rewrite coprime_sym -(divnK dvp) coprime_mull => /andP[].\nQed.\n\nLemma totient_count_coprime n : totient n = \\sum_(0 <= d < n) coprime n d.\nProof.\nelim: {n}_.+1 {-2}n (ltnSn n) => // m IHm n; rewrite ltnS => le_n_m.\ncase: (leqP n 1) => [|lt1n]; first by rewrite unlock; case: (n) => [|[]].\npose p := pdiv n; have p_pr: prime p by exact: pdiv_prime.\nhave p1 := prime_gt1 p_pr; have p0 := ltnW p1.\npose np := n`_p; pose np' := n`_p^'.\nhave co_npp': coprime np np' by rewrite coprime_partC.\nhave [n0 np0 np'0]: [/\\ n > 0, np > 0 & np' > 0] by rewrite ltnW ?part_gt0.\nhave def_n: n = np * np' by rewrite partnC.\nhave lnp0: 0 < logn p n by rewrite lognE p_pr n0 pdiv_dvd.\npose in_mod k (k0 : k > 0) d := Ordinal (ltn_pmod d k0).\nrewrite {1}def_n totient_coprime // {IHm}(IHm np') ?big_mkord; last first.\n  apply: leq_trans le_n_m; rewrite def_n ltn_Pmull //.\n  by rewrite /np p_part -(expn0 p) ltn_exp2l.\nhave ->: totient np = #|[pred d : 'I_np | coprime np d]|.\n  rewrite {1}[np]p_part totient_pfactor //=; set q := p ^ _.\n  apply: (@addnI (1 * q)); rewrite -mulnDl [1 + _]prednK // mul1n.\n  have def_np: np = p * q by rewrite -expnS prednK // -p_part.\n  pose mulp := [fun d : 'I_q => in_mod _ np0 (p * d)].\n  rewrite -def_np -{1}[np]card_ord -(cardC (mem (codom mulp))).\n  rewrite card_in_image => [|[d1 ltd1] [d2 ltd2] /= _ _ []]; last first.\n    move/eqP; rewrite def_np -!muln_modr ?modn_small //.\n    by rewrite eqn_pmul2l // => eq_op12; exact/eqP.\n  rewrite card_ord; congr (q + _); apply: eq_card => d /=.\n  rewrite !inE /= {6}[np]p_part coprime_pexpl ?prime_coprime //; congr (~~ _).\n  apply/codomP/idP=> [[d' -> /=] | /dvdnP[r def_d]].\n    by rewrite def_np -muln_modr // dvdn_mulr.\n  do [rewrite mulnC; case: d => d ltd /=] in def_d *.\n  have ltr: r < q by rewrite -(ltn_pmul2l p0) -def_np -def_d.\n  by exists (Ordinal ltr); apply: val_inj; rewrite /= -def_d modn_small.\npose h (d : 'I_n) := (in_mod _ np0 d, in_mod _ np'0 d).\npose h' (d : 'I_np * 'I_np') := in_mod _ n0 (chinese np np' d.1 d.2).\nrewrite -!big_mkcond -sum_nat_const pair_big (reindex_onto h h') => [|[d d'] _].\n  apply: eq_bigl => [[d ltd] /=]; rewrite !inE /= -val_eqE /= andbC.\n  rewrite !coprime_modr def_n -chinese_mod // -coprime_mull -def_n.\n  by rewrite modn_small ?eqxx.\napply/eqP; rewrite /eq_op /= /eq_op /= !modn_dvdm ?dvdn_part //.\nby rewrite chinese_modl // chinese_modr // !modn_small ?eqxx ?ltn_ord.\nQed.\n\n\n\n", "meta": {"author": "beta-ziliani", "repo": "ssreflect-1.4", "sha": "2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571", "save_path": "github-repos/coq/beta-ziliani-ssreflect-1.4", "path": "github-repos/coq/beta-ziliani-ssreflect-1.4/ssreflect-1.4-2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571/theories/prime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7315570270637466}}
{"text": "Require Import Arith Bool List.\nSet Implicit Arguments.\n\n(* Our language of types *)\nInductive type: Set := Nat | Bool.\n\n\n(* Set of binary operators *)\n(* Here tbinop is an indexed family type \n *)\nInductive tbinop: type -> type -> type -> Set :=\n  | TPlus: tbinop Nat Nat Nat\n  | TTimes: tbinop Nat Nat Nat\n  (* Polymorphism, we want to allow equality comparison of two values\n   * that have the same type\n   *)\n  | TEq: forall t, tbinop t t Bool\n  | TLt: tbinop Nat Nat Bool.\n\n\n(* typed expression *)\nInductive texp: type -> Set :=\n  | TNConst: nat -> texp Nat\n  | TBConst: bool -> texp Bool\n  | TBinop: forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\n(* Semantics for types *)\nDefinition typeDenote (t: type) : Set :=\n  match t with\n    | Nat => nat\n    | Bool => bool\n  end.\n\nPrint lt.\nPrint gt.\nPrint eqb.\nPrint leb.\nPrint plus.\n\n\n\nFixpoint my_lt (m n: nat) : bool :=\n  match m, n with\n    | O, O => true\n    | O, _ => false\n    | _, O => false\n    | S m', S n' => my_lt m' n'\n  end.\n\n\n(* XXX: Why it has been written like this??\n *\n * Since tbinop is an indexed type, its indices become\n * additional arguments to tbinopDenote.\n *\n * We need to do a genuine dependent pattern match,\n * where the necessary type of each case body depends\n * on the the value that has been matched.\n *)\nDefinition tbinopDenote arg1 arg2 res (b: tbinop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b in tbinop arg1 arg2 res \n    return typeDenote arg1 -> typeDenote arg2 -> typeDenote res with\n    | TPlus => plus\n    | TTimes => mult\n    | TEq Nat => beq_nat\n    | TEq Bool => eqb\n    | TLt => my_lt\n  end.\n\n\n(* Semantics for exp evaluation *)\nFixpoint texpDenote t (e: texp t): typeDenote t :=\n  match e with\n    | TNConst n => n\n    | TBConst b => b\n    | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nEval simpl in texpDenote (TNConst 42).\nEval simpl in texpDenote (TBConst true).\nEval simpl in texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\nEval simpl in texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)).\n\n\n\nDefinition tstack := list type.\n\n\n(* Define instruction classified by tstack must have exactly as many elements, and each stack\n * element must have the type found in the same position of the stack type\n *)\n(* Instructions in terms of stack types, where every instruction's type tells us what initial\n * stack type it expects and what final stack type it will produce.\n *)\nInductive tinstr: tstack -> tstack -> Set :=\n  | TiNConst : forall s, nat -> tinstr s (Nat :: s)\n  | TiBConst : forall s, bool  -> tinstr s (Bool :: s)\n  | TiBinop : forall arg1 arg2 res s,\n      tbinop arg1 arg2 res -> tinstr (arg1 :: arg2 :: s) (res :: s).\n\nInductive tprog: tstack -> tstack -> Set :=\n  | TNil : forall s, tprog s s\n  | TCons : forall s1 s2 s3,\n      tinstr s1 s2 -> tprog s2 s3 -> tprog s1 s3.\n\nFixpoint vstack (ts: tstack): Set := \n  match ts with\n    | nil => unit\n    | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\n\n\nDefinition tinstrDenote ts ts' (i: tinstr ts ts'): vstack ts -> vstack ts' :=\n  match i with\n    | TiNConst _ n => fun s => (n, s)\n    | TiBConst _ b => fun s => (b, s)\n    | TiBinop _ _ _ _ b => \n       fun s => \n         let '(arg1, (arg2, s')) := s in ((tbinopDenote b) arg1 arg2, s')\n  end.\n\n\nFixpoint tprogDenote ts ts' (p: tprog ts ts'): vstack ts -> vstack ts' :=\n  match p with\n    | TNil _ => fun s => s \n    | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\nFixpoint tconcat ts ts' ts'' (p: tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n    | TNil _ => fun p' => p'\n    | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e: texp t) (ts: tstack) : tprog ts (t :: ts) :=\n  match e with\n    | TNConst n => TCons (TiNConst _ n) (TNil _)\n    | TBConst b => TCons (TiBConst _ b) (TNil _)\n    | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)\n         (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\nEval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.\nEval simpl in tprogDenote (tcompile (TBConst true) nil) tt.\n\n\n\n", "meta": {"author": "nimishgupta", "repo": "CPDT", "sha": "ce92051b376041833f06327705cf9e5586a3d94c", "save_path": "github-repos/coq/nimishgupta-CPDT", "path": "github-repos/coq/nimishgupta-CPDT/CPDT-ce92051b376041833f06327705cf9e5586a3d94c/Coq/cpdt_2_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7315570258430227}}
{"text": "  Lemma plus_one : forall x, x + 1 = S x.\n  Proof.\n    intros. induction x.\n    - simpl. reflexivity.\n    - simpl. f_equal. assumption.\n  Qed.\n\n  Lemma plus_one' : forall x y, x + S y = S x + y.\n  Proof.\n    intros; simpl. induction x.\n    - simpl. reflexivity.\n    - simpl. f_equal. assumption.\n  Qed.\n\n\n  Lemma plus_comm : forall x y, x + y = y + x.\n  Proof.\n    intros. induction x.\n    - induction y.\n      + simpl; reflexivity.\n      + simpl. rewrite <- IHy. simpl. reflexivity.\n    - simpl. rewrite IHx. rewrite plus_one'. simpl. reflexivity.\n  Qed.\n\n  Lemma plus_assoc : forall x y z, x + (y + z) = x + y + z.\n  Proof.\n    intros. induction x.\n    - simpl. reflexivity.\n    - simpl. f_equal. assumption.\n  Qed.\n    \n  Lemma mult_plus_one' : forall x y, x + x * y = x * S y.\n  Proof.\n    induction x.\n    - simpl. reflexivity.\n    - simpl. intro. rewrite <- IHx. f_equal.\n      rewrite plus_assoc. rewrite plus_comm with (x:=x).\n      rewrite plus_assoc. reflexivity.\n  Qed.\n  \n  Lemma mult_comm : forall x y, x * y = y * x.\n  Proof.\n    induction x.\n    - simpl. induction y.\n      + simpl; reflexivity.\n      + simpl; assumption.\n    - simpl. intro. rewrite IHx. apply mult_plus_one'. \n  Qed.\n\n    ", "meta": {"author": "corwin-of-amber", "repo": "various-proofs", "sha": "e7c19549f1d573487f9fb3ebd5d6b80b2c52184b", "save_path": "github-repos/coq/corwin-of-amber-various-proofs", "path": "github-repos/coq/corwin-of-amber-various-proofs/various-proofs-e7c19549f1d573487f9fb3ebd5d6b80b2c52184b/ssar-class/comm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7315222547062753}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (z : natural) (x : natural) : natural :=\n  plus (mult z (Succ x)) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj253_coqofml_L06owW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.7315222438988606}}
{"text": "Require Import Classical.\n\nTheorem Ex008 (A B : Prop): ~(A/\\ B) -> ~A \\/ ~B.\nProof.\n  intros.\n  destruct (classic (~A \\/ ~B)).\n  + exact H0.\n  + right.\n    destruct (classic (~A)).\n    - intro.\n      apply H0.\n      left.\n      exact H1.\n    - apply NNPP in H1.\n      intro.\n      apply H.\n      split.\n      * exact H1.\n      * exact H2.\nQed.", "meta": {"author": "SvenWille", "repo": "CoqLogicExercises", "sha": "b4c1aea30abb95dc7ba81fa42ccb914d534d65e5", "save_path": "github-repos/coq/SvenWille-CoqLogicExercises", "path": "github-repos/coq/SvenWille-CoqLogicExercises/CoqLogicExercises-b4c1aea30abb95dc7ba81fa42ccb914d534d65e5/src/propLogic/Ex008.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7314854948169354}}
{"text": "(*|\n#######################\nCoq induction on modulo\n#######################\n\n:Link: https://stackoverflow.com/q/29189073\n|*)\n\n(*|\nQuestion\n********\n\nI'm new with Coq and I really have difficulty in applying the\ninduction. As long as I can use theorems from the library, or tactics\nsuch as ``lia``, all this is \"not a problem\". But as soon as these do\nnot work, I'm always stuck.\n\nTo be precise, now I try to prove\n|*)\n\nRequire Import ZArith. (* .none *)\nLemma mod_diff : forall n m : nat, n >= m /\\ m <> 0 -> (n - m) mod m = n mod m.\n\n(*| the case ``n = 0`` I already have. |*)\n\nProof.\n  intros. destruct H as [H1 H2]. induction n.\n  - now rewrite Nat.mod_0_l, Nat.mod_0_l.\n\n(* | But how to make the induction step? |*)\n\n  - Show. (* .unfold .messages *)\nAbort. (* .none *)\n\n(*|\nAnswer (Atsby)\n**************\n\nInduction is not necessary for the proof, there are sufficient lemmas\nin the Coq library that can be used. To find these lemmas, I used\n``SearchAbout modulo`` and ``SearchAbout plus``.\n\nThen, I did:\n|*)\n\nRequire Import Lia. (* .none *)\nLemma mod_add_back : forall n m : nat, m <> 0 -> (n + m) mod m = n mod m.\nProof.\n  intros. rewrite Nat.add_mod, Nat.mod_same.\n  - now rewrite plus_0_r, Nat.mod_mod.\n  - assumption.\n  - assumption.\nQed.\n\nLemma mod_diff : forall n m : nat, n >= m /\\ m <> 0 -> (n - m) mod m = n mod m.\nProof.\n  intros. intuition. rewrite <- mod_add_back.\n  - assert (n - m + m = n) by lia.\n    rewrite H. reflexivity.\n  - intuition.\nQed.\n\n(*|\nNotice the use of ``assert ... by lia`` to prove an instance of a\nrewriting that doesn't seem to be available as a built-in lemma. It's\na bit tricky because with nats it does not work in general, but only\nif ``n >= m``. (\\ **EDIT**: actually the built-in lemma\n``Nat.sub_add`` would've worked).\n\nSo the idea in the proof is to first prove a lemma that allows you to\n\"add back\" ``m``, as this seems like a good idea to have a separate\nlemma. However, I suppose it could also have been done as a single\nproof.\n\nIndeed, induction on ``n`` does not advance the proof at all, because\nthere is no way to show the preconditions of the inductive hypothesis\n(cannot derive ``n >= m`` from ``S n >= m``). While induction is an\nimportant building block it is not always the right tool.\n|*)\n\n(*|\nAnswer (larsr)\n**************\n\nAs @Atsby said, there is already useful lemmas in the library, so you\ncan for instance do\n|*)\n\nReset Initial. (* .none *)\nRequire Import ZArith.\nRequire Import Lia.\n\nLemma mod_diff : forall n m : nat, n >= m /\\ m <> 0 -> (n - m) mod m = n mod m.\nProof.\n  intros n m [H1 H2].\n  rewrite <- (Nat.mod_add _ 1); try rewrite mult_1_l, Nat.sub_add; auto.\nQed.\n\n(*|\nRegarding your question about how to do it with induction, my general\nadvice is to get an induction hypothesis that is as general as\npossible, i.e. don't introduce the quantified variables before you do\n``induction``. And also, try to get an induction hypothesis that is\nalso useful for \"the next\" value. I would therefore try to prove\nanother formula ``(n + k * m) mod m = n mod m`` and do induction on\n``k``, because then only algebraic rewriting is necessary to prove the\n``k + 1`` case from ``k``. However, in this case, that 'other formula'\nwas already in the library, called ``Nat.sub_add``.\n|*)\n\n(*|\nAnswer (Partial)\n****************\n\nYou should use a different induction principle.\n\nThe ``mod`` function obeys the following relation.\n|*)\n\nReset Initial. (* .none *)\nInductive mod_rel : nat -> nat -> nat -> Prop :=\n| mod_rel_1 : forall n1 n2, n2 = 0 -> mod_rel n1 n2 0\n| mod_rel_2 : forall n1 n2, n2 > 0 -> n1 < n2 -> mod_rel n1 n2 n1\n| mod_rel_3 : forall n1 n2 n3,\n    n2 > 0 -> n1 >= n2 -> mod_rel (n1 - n2) n2 n3 -> mod_rel n1 n2 n3.\n\n(*|\nIn standard math it's usually assumed modulo by zero is undefined. The\ntruth is all theorems involving modulo have the precondition that the\nsecond argument not be zero, so it doesn't really matter whether\nmodulo by zero is defined or not.\n\nThe following is the domain of the ``mod`` function.\n|*)\n\nInductive mod_dom : nat -> nat -> Prop :=\n| mod_dom_1 : forall n1 n2, n2 = 0 -> mod_dom n1 n2\n| mod_dom_2 : forall n1 n2, n2 > 0 -> n1 < n2 -> mod_dom n1 n2\n| mod_dom_3 : forall n1 n2,\n    n2 > 0 -> n1 >= n2 -> mod_dom (n1 - n2) n2 -> mod_dom n1 n2.\n\n(*|\nIn Coq there are only total functions, so any pair of natural numbers\nis in the domain of ``mod``. This is provable by well-founded\ninduction and case analysis.\n|*)\n\nConjecture wf_ind : forall P1,\n    (forall n1, (forall n2, n2 < n1 -> P1 n2) -> P1 n1) -> forall n1, P1 n1.\nConjecture O_gt : forall n1, n1 = 0 \\/ n1 > 0.\nConjecture lt_ge : forall n1 n2, n1 < n2 \\/ n1 >= n2.\n\nConjecture mod_total : forall n1 n2, mod_dom n1 n2.\n\n(*| The induction principle associated with ``mod``'s domain is |*)\n\nCheck mod_dom_ind : forall P1 : nat -> nat -> Prop,\n    (forall n1 n2, n2 = 0 -> P1 n1 n2) ->\n    (forall n1 n2, n2 > 0 -> n1 < n2 -> P1 n1 n2) ->\n    (forall n1 n2, n2 > 0 -> n1 >= n2 ->\n                   mod_dom (n1 - n2) n2 -> P1 (n1 - n2) n2 -> P1 n1 n2) ->\n    forall n1 n2, mod_dom n1 n2 -> P1 n1 n2.\n\n(*| But since ``mod`` is total, it's possible to simplify this to |*)\n\nConjecture mod_ind : forall P1 : nat -> nat -> Prop,\n    (forall n1 n2, n2 = 0 -> P1 n1 n2) ->\n    (forall n1 n2, n2 > 0 -> n1 < n2 -> P1 n1 n2) ->\n    (forall n1 n2, n2 > 0 -> n1 >= n2 -> P1 (n1 - n2) n2 -> P1 n1 n2) ->\n    forall n1 n2, P1 n1 n2.\n\n(*|\nThis induction principle applies to any pair of natural numbers. It's\nbetter suited to proving facts about ``mod`` because follows the\nstructure of the definition of ``mod``. ``mod`` can't be defined\ndirectly using structural recursion, so structural induction will only\nget you so far when proving things about ``mod``.\n\nNot every proof should be tackled with induction though. You need to\nask yourself why you believe something to be true and translate that\nto a rigorous proof. If you're not sure why it's true, you need to\nlearn or discover why it is or isn't.\n\nBut division and modulo can be defined indirectly by structural\nrecursion. In the following function, ``n3`` and ``n4`` serve as an\nintermediate quotient and remainder. You define it by decrementing the\ndividend and incrementing the remainder until the remainder reaches\nthe divisor, at which point you increment the quotient and reset the\nremainder and continue. When the dividend reaches zero, you have the\ntrue quotient and remainder (assuming you didn't divide by zero).\n|*)\n\nConjecture ltb : nat -> nat -> bool.\n\nFixpoint div_mod (n1 n2 n3 n4 : nat) : nat * nat :=\n  match n1 with\n  | 0 => (n3, n4)\n  | S n1 => if ltb (S n4) n2\n            then div_mod n1 n2 n3 (S n4)\n            else div_mod n1 n2 (S n3) 0\n  end.\n\nDefinition div (n1 n2 : nat) : nat := fst (div_mod n1 n2 0 0).\n\nDefinition mod (n1 n2 : nat) : nat := snd (div_mod n1 n2 0 0).\n\n(*|\nYou still don't use structural induction to prove things about ``div``\nand ``mod``. You use it to prove things about ``div_mod``. These\nfunctions correspond to the following (structurally inductive)\ntheorem.\n|*)\n\nTheorem augmented_division_algorithm : forall n1 n2 n3 n4,\n    n4 < n2 -> exists n5 n6, n1 + n3 * n2 + n4 = n5 * n2 + n6 /\\ n6 < n2.\nProof.\n  induction n1.\n  - firstorder. exists n3. exists n4. firstorder.\n  - firstorder. destruct (lt_ge (S n4) n2).\n    + specialize (IHn1 n2 n3 (S n4) H0). firstorder.\n      exists x. exists x0. firstorder.\n      admit. (* H1 implies the conclusion. *)\n    + Conjecture C2 : forall n1 n2, n1 < n2 -> 0 < n2.\n      pose proof (C2 _ _ H). specialize (IHn1 n2 (S n3) 0).\n      firstorder. exists x. exists x0. firstorder.\n      Conjecture C3 : forall n1 n2, n1 < n2 -> S n1 >= n2 -> S n1 = n2.\n      pose proof (C3 _ _ H H0). subst. cbn in *.\n      admit. (* H2 implies the conclusion. *)\nAdmitted.\n\n(*|\nThe usual division algorithm can be derived by setting ``n3`` and\n``n4`` to zero.\n|*)\n\nConjecture division_algorithm : forall n1 n2, 0 < n2 -> exists n5 n6,\n      n1 = n5 * n2 + n6 /\\ n6 < n2.\n\n(*| Disclaimer: conjectures and simply-typed functions. |*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/coq-induction-on-modulo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8824278664544911, "lm_q1q2_score": 0.7314787040483952}}
{"text": "Require Export P05.\n\n\n\n(** **** Problem #2 : 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  | nil => l2\n  | h1 :: t1 =>\n    match l2 with\n    | nil => l1\n    | h2 :: t2 => h1 :: (h2 :: (alternate t1 t2))\n    end\n  end.\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", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/02/P06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.8872045966995027, "lm_q1q2_score": 0.731466426191517}}
{"text": "Require Import Orders XRbase XRbasic_fun XROrderedType GenericMinMax.\n\nLocal Open Scope XR_scope.\n\nLemma Rmax_l : forall x y, y<=x -> Rmax x y = x.\nProof.\n unfold Rmax. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmax_r : forall x y, x<=y -> Rmax x y = y.\nProof.\n unfold Rmax. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmin_l : forall x y, x<=y -> Rmin x y = x.\nProof.\n unfold Rmin. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmin_r : forall x y, y<=x -> Rmin x y = y.\nProof.\n unfold Rmin. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nModule RHasMinMax <: HasMinMax R_as_OT.\n Definition max := Rmax.\n Definition min := Rmin.\n Definition max_l := Rmax_l.\n Definition max_r := Rmax_r.\n Definition min_l := Rmin_l.\n Definition min_r := Rmin_r.\nEnd RHasMinMax.\n\nModule R.\n\nInclude UsualMinMaxProperties R_as_OT RHasMinMax.\n\nLemma plus_max_distr_l : forall n m p, Rmax (p + n) (p + m) = p + Rmax n m.\nProof.\n intros. apply max_monotone.\n intros x y. apply Rplus_le_compat_l.\nQed.\n\nLemma plus_max_distr_r : forall n m p, Rmax (n + p) (m + p) = Rmax n m + p.\nProof.\n intros. rewrite (Rplus_comm n p), (Rplus_comm m p), (Rplus_comm _ p).\n apply plus_max_distr_l.\nQed.\n\nLemma plus_min_distr_l : forall n m p, Rmin (p + n) (p + m) = p + Rmin n m.\nProof.\n intros. apply min_monotone.\n intros x y. apply Rplus_le_compat_l.\nQed.\n\nLemma plus_min_distr_r : forall n m p, Rmin (n + p) (m + p) = Rmin n m + p.\nProof.\n intros. rewrite (Rplus_comm n p), (Rplus_comm m p), (Rplus_comm _ p).\n apply plus_min_distr_l.\nQed.\n\nLemma opp_max_distr : forall n m : R, -(Rmax n m) = Rmin (- n) (- m).\nProof.\n intros. symmetry. apply min_max_antimonotone.\n do 3 red. intros; apply Rge_le. apply Ropp_le_ge_contravar; auto.\nQed.\n\nLemma opp_min_distr : forall n m : R, - (Rmin n m) = Rmax (- n) (- m).\nProof.\n intros. symmetry. apply max_min_antimonotone.\n do 3 red. intros; apply Rge_le. apply Ropp_le_ge_contravar; auto.\nQed.\n\nLemma minus_max_distr_l : forall n m p, Rmax (p - n) (p - m) = p - Rmin n m.\nProof.\n unfold Rminus. intros. rewrite opp_min_distr. apply plus_max_distr_l.\nQed.\n\nLemma minus_max_distr_r : forall n m p, Rmax (n - p) (m - p) = Rmax n m - p.\nProof.\n unfold Rminus. intros. apply plus_max_distr_r.\nQed.\n\nLemma minus_min_distr_l : forall n m p, Rmin (p - n) (p - m) = p - Rmax n m.\nProof.\n unfold Rminus. intros. rewrite opp_max_distr. apply plus_min_distr_l.\nQed.\n\nLemma minus_min_distr_r : forall n m p, Rmin (n - p) (m - p) = Rmin n m - p.\nProof.\n unfold Rminus. intros. apply plus_min_distr_r.\nQed.\n\nEnd R.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/Reals/XRminmax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7314664122527728}}
{"text": "Require Import Vector.\nRequire Import Numbers.Natural.Peano.NPeano.\nRequire Import Strings.String.\nRequire Import Strings.Ascii.\nRequire Import List.\n\n\nDefinition Vec := VectorDef.t.\nDefinition Fin := Fin.t.\nDefinition Alpha := Fin 26.\n\n\nDefinition alpha_to_ascii (a : Alpha) : ascii :=\n  match Fin.to_nat a with\n  | exist _ a pf => ascii_of_nat ((nat_of_ascii \"A\") + a)\n  end.\n\n\nDefinition ascii_to_alpha (a : ascii) : Alpha :=\n  match Compare_dec.lt_dec (nat_of_ascii a - nat_of_ascii \"A\") 26 with\n  | left pf_lt => Fin.of_nat_lt pf_lt\n  | right pf_ge => Fin.F1\n  end.\n\n\nFixpoint string_to_alpha (str : string) : list Alpha :=\n  match str with\n  | EmptyString => nil\n  | String a str' => ascii_to_alpha a :: string_to_alpha str'\n  end.\n\n\nDefinition alpha_to_string (alphas : list Alpha) : string :=\n  fold_left (fun str a => String (alpha_to_ascii a) str) (rev alphas) EmptyString.\n\n\nFixpoint string_to_vec (str : string) : Vec Alpha (String.length str) :=\n  match str as str' return Vec Alpha (String.length str') with\n  | EmptyString => VectorDef.nil Alpha\n  | String a str' => VectorDef.cons Alpha (ascii_to_alpha a) (String.length str') (string_to_vec str')\n  end.\n\n\nDefinition alphabet : Vec Alpha 26 :=\n  string_to_vec \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".\n\n\nExample alpha_to_string_inverse_test :\n  alpha_to_string (string_to_alpha \"HELLOWORLD\") = \"HELLOWORLD\"%string.\nProof. reflexivity. Qed.\n\n\nDefinition step_fin {n : nat} (f : Fin (S n)) : Fin (S n) :=\n  match (Fin.to_nat f) with\n  | exist _ i pf =>\n    match Compare_dec.lt_dec (S i) (S n) return Fin (S n) with\n    | left pf_lt => Fin.of_nat_lt pf_lt\n    | right pf_nlt => Fin.F1\n    end\n  end.\n", "meta": {"author": "Chobbes", "repo": "coq-enigma", "sha": "3809e43b458c7fb586a5a297ba78e2c31196ad43", "save_path": "github-repos/coq/Chobbes-coq-enigma", "path": "github-repos/coq/Chobbes-coq-enigma/coq-enigma-3809e43b458c7fb586a5a297ba78e2c31196ad43/alphabet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7314663953095961}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) (z : natural) (x : natural)\n  : natural := plus lf2 (mult z x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj194_coqofml_JqgWi5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.7905303285397348, "lm_q1q2_score": 0.7314223435846178}}
{"text": "Theorem ex27: forall a b c : Prop,\n              a /\\ (b \\/ c) <-> a /\\ b \\/ a /\\ c.\nProof.\n  split. intro. elim H. intros. elim H1. intro.\n  left. split. assumption. assumption.\n  intro. right. split. assumption. assumption.\n  intro. elim H. intro. elim H0. intros.\n  split. assumption. left. assumption.\n  intro. elim H0. intros. split. assumption.\n  right. assumption.\nQed.\n\nTheorem ex28: forall a b c : Prop,\n              a \\/ (b /\\ c) <-> (a \\/ b) /\\ (a \\/ c).\nProof.\n  split. intro. elim H. intro. split. left. assumption.\n  left. assumption. intro. elim H0. intros. split.\n  right. assumption. right. assumption. intro. elim H.\n  intros. elim H0. intro. left. assumption. intro.\n  elim H1. intro. left. assumption. intro. right. split.\n  assumption. assumption.\nQed.\n\nTheorem ex29: forall a b c : Prop,\n              a \\/ (b -> c) <-> ((a \\/ b) -> (a \\/ c)).\nProof.\n  Require Import Classical.\n  split. intros. elim H0. intro. left. assumption.\n  elim H. intros. left. assumption.\n  intros. right. apply (H1 H2).\n  intros. apply NNPP. intro.\n  elim H. intro. apply H0. left. assumption.\n  intro. apply H0. right. intro. assumption.\n  apply NNPP. intro. apply H0. right. intro.\n  elim H1. right. assumption.\nQed.\n\n(* ------------------- *)\n\nTheorem ex15: forall a b : Prop,\n               (a -> b) <-> (~a \\/ b).\nProof.\n  Require Import Classical.\n  Require Import Coq.Program.Basics.\n  intros. split. intro. generalize (classic a).\n  intro. elim H0. intro. right. apply (H H1).\n  intro. left. assumption.\n  intros. elim H. intro. contradiction. apply id.\nQed.\n\nTheorem ex30: forall a b c : Prop,\n              a \\/ (b <-> c) <-> (a \\/ b <-> a \\/ c).\nProof.\n  Require Import Setoid.\n  split. intro. split. intro.\n  elim H0. elim H. intro. left. assumption.\n  intros. left. assumption. elim H. intros.\n  left. assumption. intros. right. apply H1.\n  assumption. intro. elim H0. intro. left. assumption.\n  elim H. intros. left. assumption.\n  intros. right. apply H1. assumption.\n  intro. elim H. intros. rewrite ex15 in H0.\n  rewrite ex15 in H1. elim H0. intro.\n  elim H1. intro. right. split. rewrite ex15.\n  left. intro. apply H2. right. assumption.\n  intro. elim H3. right. assumption. intro.\n  contradiction. intro. decompose [or] H1.\n  contradiction. left. assumption. decompose [or] H0.\n  elim H3. right. assumption. left. assumption.\n  right. split. refine (fun H4 => H5).\n  refine (fun H5 => H4).\nQed.\n\n(* ------------------- *)\n\nTheorem ex30_1: forall a b c : Prop,\n                (a -> b) -> (a /\\ c) -> (b /\\ c).\nProof.\n  intros. elim H0. intros. split. apply (H H1).\n  assumption.\nQed.\n\nTheorem ex30_2: forall a b c : Prop,\n                (a -> b) -> (c /\\ a) -> (c /\\ b).\nProof.\n  intros. elim H0. split. assumption. apply (H H2).\nQed.\n\nTheorem ex30_3: forall a b c : Prop,\n                (a <-> b) -> ((c /\\ a) <-> (c /\\ b)).\nProof.\n  intros. split. intro. elim H0. intros.\n  elim H. intros. split. assumption.\n  apply (H3 H2). intros. elim H0. intros.\n  elim H. intros. split. assumption.\n  apply (H4 H2).\nQed.\n\nTheorem ex30_4: forall a b c : Prop,\n                (a -> b) -> (a \\/ c) -> (b \\/ c).\nProof.\n  intros. elim H0. intros. left. apply (H H1).\n  intro. right. assumption.\nQed.\n\nTheorem ex30_5: forall a b c : Prop,\n                (a -> b) -> (c \\/ a) -> (c \\/ b).\nProof.\n  intros. elim H0. intros. left. assumption.\n  intro. right. apply (H H1).\nQed.\n\nTheorem ex30_6: forall a b c : Prop,\n                (a <-> b) -> ((c \\/ a) <-> (c \\/ b)).\nProof.\n  intros. elim H. intros. split. intro.\n  elim H2. intro. left. assumption.\n  intro. right. apply (H0 H3).\n  intro. elim H2. intros. left. assumption.\n  intro. right. apply (H1 H3).\nQed.\n\nTheorem ex30_7: forall a b c d : Prop,\n                (a -> b) -> (b /\\ c -> d) -> (a /\\ c -> d).\nProof.\n  intros. elim H1. intros. apply H0. split.\n  apply (H H2). assumption.\nQed.\n\nTheorem ex30_8: forall a b c d : Prop,\n                (a -> b) -> (c /\\ d -> a) -> (c /\\ d -> b).\nProof.\n  intros. elim H1. intros. apply H. apply H0.\n  split. assumption. assumption.\nQed.\n\nTheorem ex31: forall a b c d : Prop,\n              (a -> b /\\ c) <-> (a -> b) /\\ (a -> c).\nProof.\n  split. intro. split. intro. apply (H H0).\n  intro. apply (H H0). intros. elim H.\n  intros. split. apply (H1 H0). apply (H2 H0).\nQed.\n\nTheorem ex31_1: forall a b c d : Prop,\n                (a -> c) /\\ (b -> d) -> (a /\\ b -> c /\\ d).\nProof.\n  intros. elim H. elim H0. intros. split.\n  apply (H3 H1). apply (H4 H2).\nQed.\n\nTheorem ex31_2: forall a b c d : Prop,\n                (a -> b) /\\ (c -> d) -> (a \\/ c -> b \\/ d).\nProof.\n  intros. elim H. elim H0. intros. left. apply (H2 H1).\n  intros. right. apply (H3 H1).\nQed.\n\n(* ------------------- *)\n\nTheorem ex20: forall a b : Prop,\n               (a \\/ b) <-> (~a -> b).\nProof.\n  Require Import Classical.\n  intros. split. intros. apply NNPP. intro. elim H.\n  intro. contradiction. intro. contradiction. intro.\n  apply NNPP. intro. elim H0. right. apply NNPP. intro.\n  apply H1. apply H. intro. apply H0. left. assumption.\nQed.\n\nTheorem ex32: forall a b c : Prop,\n              (a -> b \\/ c) <-> (a -> b) \\/ (a -> c).\nProof.\n  Require Import Setoid.\n  Require Import Coq.Program.Basics.\n  intros. split. Focus 2. \n  intros. elim H. intro. left. apply (H1 H0).\n  intro. right. apply (H1 H0).\n  intros. rewrite (ex20 (a -> b) (a -> c)).\n  intros. elim H. intro. elim H0. refine (fun H1 => H2).\n  apply id. assumption.\nQed.\n\n(* ---------------- *)\n\nTheorem ex32_1: forall a b c : Prop,\n                (a \\/ b -> c) <-> (a -> c) /\\ (b -> c).\nProof.\n  intros. split. intro. split. intro. apply H. left.\n  assumption. intro. apply H. right. assumption.\n  intros. elim H0. elim H. intros.\n  apply (H1 H3). elim H. intros. apply (H2 H3).\nQed.\n\nTheorem ex32_2: forall a b c : Prop,\n                ((a -> c) \\/ (b -> c)) <-> (a /\\ b -> c).\nProof.\n  Require Import Classical.\n  intros. split. intros. elim H0. elim H. intros.\n  apply (H1 H2). intros. apply (H1 H3).\n  intro. apply NNPP. intro. elim H0. right. intro. elim H0.\n  left. intro. apply H. split. assumption. assumption.\nQed.\n\n(* --------------- *)\n\nTheorem ex14: forall a b : Prop,\n              (a <-> b) <-> (a -> b) /\\ (b -> a).\nProof.\n  intros. split. split. elim H. intros.\n  apply (H0 H2). elim H. intros.\n  apply (H1 H2). split. elim H. intros.\n  apply (H0 H2). elim H. intros.\n  apply (H1 H2).\nQed.\n\nTheorem ex33: forall a b c : Prop,\n              a -> ((b <-> c) <-> ((a -> b) <-> (a -> c))).\nProof.\n  Require Import Setoid.\n  intros. rewrite ex14. split. intro.\n  split. intros. apply H0. apply (H1 H2).\n  intros. apply H0. apply (H1 H2).\n  split. elim H0. intros. apply H1.\n  refine (fun H => H3). assumption.\n  elim H0. intros. apply H2.\n  refine (fun H => H3). assumption.\nQed.\n\n(* --------------- *)\n\nTheorem ex33_1: forall a b c : Prop,\n                (a -> (b -> c)) <-> ((a -> b) -> (a -> c)).\nProof.\n  intros. split. intros. apply H. assumption. apply H0. assumption.\n  intros. apply H. intro. assumption. assumption.\nQed.\n\n", "meta": {"author": "limitedeternity", "repo": "PrPr-Labs", "sha": "0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62", "save_path": "github-repos/coq/limitedeternity-PrPr-Labs", "path": "github-repos/coq/limitedeternity-PrPr-Labs/PrPr-Labs-0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62/PrPr-01/Distributivity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7314006621208605}}
{"text": "(* Exercise 32 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_032 : (forall x, (P x /\\ ~ Q x) -> S x) /\\ (exists x, ~ S x /\\ ~ Q x) -> (exists x, ~ P x).\nProof.\nimp_i a1.\nexi_e (exists x:D, ~S x /\\ ~Q x) a a2.\ncon_e2 (forall x:D, P x /\\ ~Q x -> S x).\nhyp a1.\ndis_e (P a \\/ ~P a) a3 a3.\nLEM.\nneg_e (S a).\ncon_e1 (~Q a).\nhyp a2.\nimp_e (P a /\\ ~Q a).\nall_e (forall x:D, P x /\\ ~Q x -> S x) a.\ncon_e1 (exists x:D, ~S x /\\ ~Q x).\nhyp a1.\ncon_i.\nhyp a3.\ncon_e2 (~S a).\nhyp a2.\nexi_i a.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred032.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.731343709069866}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Chapter 8: Lambda Calculus and Simple Type Soundness\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)\n\nRequire Import Frap.\n\n(* The last few chapters have focused on small programming languages that are\n * representative of the essence of the imperative languages.  We now turn to\n * lambda-calculus, the usual representative of functional languages. *)\n\nModule Ulc.\n  Inductive exp : Set :=\n  | Var (x : var)\n  | Abs (x : var) (body : exp)\n  | App (e1 e2 : exp).\n\n  Fixpoint subst (rep : exp) (x : var) (e : exp) : exp :=\n    match e with\n    | Var y => if string_dec y x then rep else Var y\n    | Abs y e1 => Abs y (if y ==v x then e1 else subst rep x e1)\n    | App e1 e2 => App (subst rep x e1) (subst rep x e2)\n    end.\n\n\n  (** * Big-step semantics *)\n\n  Inductive eval : exp -> exp -> Prop :=\n  | BigAbs : forall x e,\n    eval (Abs x e) (Abs x e)\n  | BigApp : forall e1 x e1' e2 v2 v,\n    eval e1 (Abs x e1')\n    -> eval e2 v2\n    -> eval (subst v2 x e1') v\n    -> eval (App e1 e2) v.\n\n  Inductive value : exp -> Prop :=\n  | Value : forall x e, value (Abs x e).\n\n  Hint Constructors eval value.\n\n  Theorem value_eval : forall v,\n    value v\n    -> eval v v.\n  Proof.\n    invert 1; eauto.\n  Qed.\n\n  Hint Resolve value_eval.\n\n  Theorem eval_value : forall e v,\n    eval e v\n    -> value v.\n  Proof.\n    induct 1; eauto.\n  Qed.\n\n  Hint Resolve eval_value.\n\n  (* Some notations, to let us write more normal-looking lambda terms *)\n  Coercion Var : var >-> exp.\n  Notation \"\\ x , e\" := (Abs x e) (at level 50).\n  Infix \"@\" := App (at level 49, left associativity).\n\n  (* Believe it or not, this is a Turing-complete language!  Here's an example\n   * nonterminating program. *)\n  Example omega := (\\\"x\", \"x\" @ \"x\") @ (\\\"x\", \"x\" @ \"x\").\n\n\n  (** * Church Numerals, everyone's favorite example of lambda terms in\n      * action *)\n\n  (* Here are two curious definitions. *)\n  Definition zero := \\\"f\", \\\"x\", \"x\".\n  Definition plus1 := \\\"n\", \\\"f\", \\\"x\", \"f\" @ (\"n\" @ \"f\" @ \"x\").\n\n  (* We can build up any natural number [n] as [plus1^n @ zero].  Let's prove\n   * that, in fact, these definitions constitute a workable embedding of the\n   * natural numbers in lambda-calculus. *)\n\n  (* A term [plus^n @ zero] evaluates to something very close to what this\n   * function returns. *)\n  Fixpoint canonical' (n : nat) : exp :=\n    match n with\n    | O => \"x\"\n    | S n' => \"f\" @ ((\\\"f\", \\\"x\", canonical' n') @ \"f\" @ \"x\")\n    end.\n\n  (* This missing piece is this wrapper. *)\n  Definition canonical n := \\\"f\", \\\"x\", canonical' n.\n\n  (* Let's formalize our definition of what it means to represent a number. *)\n  Definition represents (e : exp) (n : nat) :=\n    eval e (canonical n).\n\n  (* Zero passes the test. *)\n  Theorem zero_ok : represents zero 0.\n  Proof.\n    unfold zero, represents, canonical.\n    simplify.\n    econstructor.\n  Qed.\n\n  (* So does our successor operation. *)\n  Theorem plus1_ok : forall e n, represents e n\n                                 -> represents (plus1 @ e) (S n).\n  Proof.\n    unfold plus1, represents, canonical; simplify.\n    econstructor.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n  Qed.\n\n  (* What's basically going on here?  The representation of number [n] is [N]\n   * such that, for any function [f]:\n   *   N(f) = f^n\n   * That is, we represent a number as its repeated-composition operator.\n   * So, given a number, we can use it to repeat any operation.  In particular,\n   * to implement addition, we can just repeat [plus1]! *)\n  Definition add := \\\"n\", \\\"m\", \"n\" @ plus1 @ \"m\".\n\n  (* Our addition works properly on this test case. *)\n  Example add_1_2 : exists v,\n      eval (add @ (plus1 @ zero) @ (plus1 @ (plus1 @ zero))) v\n      /\\ eval (plus1 @ (plus1 @ (plus1 @ zero))) v.\n  Proof.\n    eexists; propositional.\n    repeat (econstructor; simplify).\n    repeat econstructor.\n  Qed.\n\n  (* By the way: since [canonical'] doesn't mention variable \"m\", substituting\n   * for \"m\" has no effect.  This fact will come in handy shortly. *)\n  Lemma subst_m_canonical' : forall m n,\n    subst m \"m\" (canonical' n) = canonical' n.\n  Proof.\n    induct n; simplify; equality.\n  Qed.\n\n  (* This inductive proof is the workhorse for the next result, so let's skip\n   * ahead there. *)\n  Lemma add_ok' : forall m n,\n      eval\n        (subst (\\ \"f\", (\\ \"x\", canonical' m)) \"x\"\n               (subst (\\ \"n\", (\\ \"f\", (\\ \"x\", \"f\" @ ((\"n\" @ \"f\") @ \"x\")))) \"f\"\n                      (canonical' n))) (canonical (n + m)).\n  Proof.\n    induct n; simplify.\n\n    econstructor.\n\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    simplify.\n    eassumption.\n\n    simplify.\n    econstructor.\n  Qed.\n\n  (* [add] properly encodes the usual addition. *)\n  Theorem add_ok : forall n ne m me,\n      represents ne n\n      -> represents me m\n      -> represents (add @ ne @ me) (n + m).\n  Proof.\n    unfold represents; simplify.\n\n    econstructor.\n    econstructor.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    rewrite subst_m_canonical'.\n    apply add_ok'.\n  Qed.\n\n  (* Let's repeat the same exercise for multiplication. *)\n\n  Definition mult := \\\"n\", \\\"m\", \"n\" @ (add @ \"m\") @ zero.\n\n  Example mult_1_2 : exists v,\n      eval (mult @ (plus1 @ zero) @ (plus1 @ (plus1 @ zero))) v\n      /\\ eval (plus1 @ (plus1 @ zero)) v.\n  Proof.\n    eexists; propositional.\n    repeat (econstructor; simplify).\n    repeat econstructor.\n  Qed.\n\n  Lemma mult_ok' : forall m n,\n      eval\n        (subst (\\ \"f\", (\\ \"x\", \"x\")) \"x\"\n               (subst\n                  (\\ \"m\",\n                   ((\\ \"f\", (\\ \"x\", canonical' m)) @\n                                                   (\\ \"n\", (\\ \"f\", (\\ \"x\", \"f\" @ ((\"n\" @ \"f\") @ \"x\"))))) @ \"m\")\n                  \"f\" (canonical' n))) (canonical (n * m)).\n  Proof.\n    induct n; simplify.\n\n    econstructor.\n\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    simplify.\n    eassumption.\n\n    simplify.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    rewrite subst_m_canonical'.\n    apply add_ok'. (* Note the recursive appeal to correctness of [add]. *)\n  Qed.\n\n  Theorem mult_ok : forall n ne m me,\n      represents ne n\n      -> represents me m\n      -> represents (mult @ ne @ me) (n * m).\n  Proof.\n    unfold represents; simplify.\n\n    econstructor.\n    econstructor.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    simplify.\n    rewrite subst_m_canonical'.\n    apply mult_ok'.\n  Qed.\n\n\n  (** * Small-step semantics with evaluation contexts *)\n\n  Inductive context : Set :=\n  | Hole : context\n  | App1 : context -> exp -> context\n  | App2 : exp -> context -> context.\n\n  Inductive plug : context -> exp -> exp -> Prop :=\n  | PlugHole : forall e,\n    plug Hole e e\n  | PlugApp1 : forall c e1 e2 e,\n    plug c e1 e\n    -> plug (App1 c e2) e1 (App e e2)\n  | PlugApp2 : forall c e1 e2 e,\n    value e1\n    -> plug c e2 e\n    -> plug (App2 e1 c) e2 (App e1 e).\n\n  Inductive step : exp -> exp -> Prop :=\n  | ContextBeta : forall c x e v e1 e2,\n    value v\n    -> plug c (App (Abs x e) v) e1\n    -> plug c (subst v x e) e2\n    -> step e1 e2.\n\n  Hint Constructors plug step.\n\n  (* Here we now go through a proof of equivalence between big- and small-step\n   * semantics, though we won't spend any further commentary on it. *)\n\n  Lemma step_eval'' : forall v c x e e1 e2 v0,\n    value v\n    -> plug c (App (Abs x e) v) e1\n    -> plug c (subst v x e) e2\n    -> eval e2 v0\n    -> eval e1 v0.\n  Proof.\n    induct c; invert 2; invert 1; simplify; eauto.\n    invert H0; eauto.\n    invert H0; eauto.\n  Qed.\n\n  Hint Resolve step_eval''.\n\n  Lemma step_eval' : forall e1 e2,\n    step e1 e2\n    -> forall v, eval e2 v\n      -> eval e1 v.\n  Proof.\n    invert 1; simplify; eauto.\n  Qed.\n\n  Hint Resolve step_eval'.\n\n  Theorem step_eval : forall e v,\n    step^* e v\n    -> value v\n    -> eval e v.\n  Proof.\n    induct 1; eauto.\n  Qed.\n\n  Lemma plug_functional : forall C e e1,\n      plug C e e1\n      -> forall e2, plug C e e2\n                    -> e1 = e2.\n  Proof.\n    induct 1; invert 1; simplify; try f_equal; eauto.\n  Qed.\n\n  Lemma plug_mirror : forall C e e', plug C e e'\n    -> forall e1, exists e1', plug C e1 e1'.\n  Proof.\n    induct 1; simplify; eauto.\n\n    specialize (IHplug e0); first_order; eauto.\n\n    specialize (IHplug e0); first_order; eauto.\n  Qed.    \n\n  Fixpoint compose (C1 C2 : context) : context :=\n    match C2 with\n    | Hole => C1\n    | App1 C2' e => App1 (compose C1 C2') e\n    | App2 v C2' => App2 v (compose C1 C2')\n    end.\n\n  Lemma compose_ok : forall C1 C2 e1 e2 e3,\n      plug C1 e1 e2\n      -> plug C2 e2 e3\n      -> plug (compose C1 C2) e1 e3.\n  Proof.\n    induct 2; simplify; eauto.\n  Qed.\n\n  Hint Resolve compose_ok.\n\n  Lemma step_plug : forall e1 e2,\n    step e1 e2\n    -> forall C e1' e2', plug C e1 e1'\n                         -> plug C e2 e2'\n                         -> step e1' e2'.\n  Proof.\n    invert 1; simplify; eauto.\n  Qed.\n\n  Lemma stepStar_plug : forall e1 e2,\n    step^* e1 e2\n    -> forall C e1' e2', plug C e1 e1'\n                         -> plug C e2 e2'\n                         -> step^* e1' e2'.\n  Proof.\n    induct 1; simplify.\n\n    assert (e1' = e2') by (eapply plug_functional; eassumption).\n    subst.\n    constructor.\n\n    assert (exists y', plug C y y') by eauto using plug_mirror.\n    invert H3.\n    eapply step_plug in H.\n    econstructor.\n    eassumption.\n    eapply IHtrc.\n    eassumption.\n    assumption.\n    eassumption.\n    assumption.\n  Qed.\n\n  Hint Resolve stepStar_plug eval_value.\n\n  Theorem eval_step : forall e v,\n    eval e v\n    -> step^* e v.\n  Proof.\n    induct 1; eauto.\n\n    eapply trc_trans.\n    eapply stepStar_plug with (e1 := e1) (e2 := Abs x e1') (C := App1 Hole e2); eauto.\n    eapply trc_trans.\n    eapply stepStar_plug with (e1 := e2) (e2 := v2) (C := App2 (Abs x e1') Hole); eauto.\n    eauto.\n  Qed.\nEnd Ulc.\n\n\nModule Stlc.\n  Inductive exp : Set :=\n  | Var (x : var)\n  | Const (n : nat)\n  | Plus (e1 e2 : exp)\n  | Abs (x : var) (e1 : exp)\n  | App (e1 e2 : exp).\n\n  Inductive value : exp -> Prop :=\n  | VConst : forall n, value (Const n)\n  | VAbs : forall x e1, value (Abs x e1).\n\n  Fixpoint subst (e1 : exp) (x : string) (e2 : exp) : exp :=\n    match e2 with\n      | Var y => if y ==v x then e1 else Var y\n      | Const n => Const n\n      | Plus e2' e2'' => Plus (subst e1 x e2') (subst e1 x e2'')\n      | Abs y e2' => Abs y (if y ==v x then e2' else subst e1 x e2')\n      | App e2' e2'' => App (subst e1 x e2') (subst e1 x e2'')\n    end.\n\n  Inductive context : Set :=\n  | Hole : context\n  | Plus1 : context -> exp -> context\n  | Plus2 : exp -> context -> context\n  | App1 : context -> exp -> context\n  | App2 : exp -> context -> context.\n\n  Inductive plug : context -> exp -> exp -> Prop :=\n  | PlugHole : forall e, plug Hole e e\n  | PlugPlus1 : forall e e' C e2,\n    plug C e e'\n    -> plug (Plus1 C e2) e (Plus e' e2)\n  | PlugPlus2 : forall e e' v1 C,\n    value v1\n    -> plug C e e'\n    -> plug (Plus2 v1 C) e (Plus v1 e')\n  | PlugApp1 : forall e e' C e2,\n    plug C e e'\n    -> plug (App1 C e2) e (App e' e2)\n  | PlugApp2 : forall e e' v1 C,\n    value v1\n    -> plug C e e'\n    -> plug (App2 v1 C) e (App v1 e').\n\n  Inductive step0 : exp -> exp -> Prop :=\n  | Beta : forall x e v,\n    value v\n    -> step0 (App (Abs x e) v) (subst v x e)\n  | Add : forall n1 n2,\n    step0 (Plus (Const n1) (Const n2)) (Const (n1 + n2)).\n\n  Inductive step : exp -> exp -> Prop :=\n  | StepRule : forall C e1 e2 e1' e2',\n    plug C e1 e1'\n    -> plug C e2 e2'\n    -> step0 e1 e2\n    -> step e1' e2'.\n\n  Definition trsys_of (e : exp) := {|\n    Initial := {e};\n    Step := step\n  |}.\n\n\n  Inductive type :=\n  | Nat                  (* Numbers *)\n  | Fun (dom ran : type) (* Functions *).\n\n  Inductive hasty : fmap var type -> exp -> type -> Prop :=\n  | HtVar : forall G x t,\n    G $? x = Some t\n    -> hasty G (Var x) t\n  | HtConst : forall G n,\n    hasty G (Const n) Nat\n  | HtPlus : forall G e1 e2,\n    hasty G e1 Nat\n    -> hasty G e2 Nat\n    -> hasty G (Plus e1 e2) Nat\n  | HtAbs : forall G x e1 t1 t2,\n    hasty (G $+ (x, t1)) e1 t2\n    -> hasty G (Abs x e1) (Fun t1 t2)\n  | HtApp : forall G e1 e2 t1 t2,\n    hasty G e1 (Fun t1 t2)\n    -> hasty G e2 t1\n    -> hasty G (App e1 e2) t2.\n\n  Hint Constructors value plug step0 step hasty.\n\n  (* Some notation to make it more pleasant to write programs *)\n  Infix \"-->\" := Fun (at level 60, right associativity).\n  Coercion Const : nat >-> exp.\n  Infix \"^+^\" := Plus (at level 50).\n  Coercion Var : var >-> exp.\n  Notation \"\\ x , e\" := (Abs x e) (at level 51).\n  Infix \"@\" := App (at level 49, left associativity).\n\n  (* Some examples of typed programs *)\n\n  Example one_plus_one : hasty $0 (1 ^+^ 1) Nat.\n  Proof.\n    repeat (econstructor; simplify).\n  Qed.\n\n  Example add : hasty $0 (\\\"n\", \\\"m\", \"n\" ^+^ \"m\") (Nat --> Nat --> Nat).\n  Proof.\n    repeat (econstructor; simplify).\n  Qed.\n\n  Example eleven : hasty $0 ((\\\"n\", \\\"m\", \"n\" ^+^ \"m\") @ 7 @ 4) Nat.\n  Proof.\n    repeat (econstructor; simplify).\n  Qed.\n\n  Example seven_the_long_way : hasty $0 ((\\\"x\", \"x\") @ (\\\"x\", \"x\") @ 7) Nat.\n  Proof.\n    repeat (econstructor; simplify).\n  Qed.\n\n\n  (** * Let's prove type soundness. *)\n\n  Definition unstuck e := value e\n    \\/ (exists e' : exp, step e e').\n\n  (* For class, we'll stick with this magic tactic, to save proving time. *)\n\n  Ltac t0 := match goal with\n             | [ H : ex _ |- _ ] => invert H\n             | [ H : _ /\\ _ |- _ ] => invert H\n             | [ |- context[?x ==v ?y] ] => cases (x ==v y)\n             | [ H : Some _ = Some _ |- _ ] => invert H\n\n             | [ H : step _ _ |- _ ] => invert H\n             | [ H : step0 _ _ |- _ ] => invert1 H\n             | [ H : hasty _ ?e _, H' : value ?e |- _ ] => invert H'; invert H\n             | [ H : hasty _ _ _ |- _ ] => invert1 H\n             | [ H : plug _ _ _ |- _ ] => invert1 H\n             end; subst.\n\n  Ltac t := simplify; propositional; repeat (t0; simplify); try equality; eauto 6.\n\n  Lemma progress : forall e t,\n    hasty $0 e t\n    -> value e\n    \\/ (exists e' : exp, step e e').\n  Proof.\n  Admitted.\n\n  (* Replacing a typing context with an equal one has no effect (useful to guide\n   * proof search as a hint). *)\n  Lemma hasty_change : forall G e t,\n    hasty G e t\n    -> forall G', G' = G\n      -> hasty G' e t.\n  Proof.\n    t.\n  Qed.\n\n  Hint Resolve hasty_change.\n\n  Lemma preservation : forall e1 e2,\n    step e1 e2\n    -> forall t, hasty $0 e1 t\n      -> hasty $0 e2 t.\n  Proof.\n  Admitted.\n\n  Theorem safety : forall e t, hasty $0 e t\n    -> invariantFor (trsys_of e) unstuck.\n  Proof.\n    simplify.\n\n    (* Step 1: strengthen the invariant.  In particular, the typing relation is\n     * exactly the right stronger invariant!  Our progress theorem proves the\n     * required invariant inclusion. *)\n    apply invariant_weaken with (invariant1 := fun e' => hasty $0 e' t).\n\n    (* Step 2: apply invariant induction, whose induction step turns out to match\n     * our preservation theorem exactly! *)\n    apply invariant_induction; simplify.\n    equality.\n\n    eapply preservation.\n    eassumption.\n    assumption.\n\n    simplify.\n    eapply progress.\n    eassumption.\n  Qed.\nEnd Stlc.\n", "meta": {"author": "svanderbleek", "repo": "frap-psets", "sha": "63d80f65dd5e873436dd3a81f88c10302a4a7f5a", "save_path": "github-repos/coq/svanderbleek-frap-psets", "path": "github-repos/coq/svanderbleek-frap-psets/frap-psets-63d80f65dd5e873436dd3a81f88c10302a4a7f5a/frap/LambdaCalculusAndTypeSoundness_template.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7312229923479787}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\nClassical logic is somewhat surprising!\nProve that given two arbitrary propositions\na and b, either a implies b or the converse *)\n\nLemma CL_is_wrong_and_boolrefl_is_nice (A B : (*D*)bool(*D*)) :\n  (A -> B) \\/ (B -> A).\n(*A*)Proof. case: A; case: B; by [left | right]. Qed.\n\n(** Enrico is a lazy student.  When asked to reverse and filter\na list he comes up with the following ugly code. *)\n\nFixpoint filtrev T (p : pred T) (acc : seq T) (l : seq T) : seq T :=\n  if l is x :: xs then\n    if p x then filtrev p (x :: acc) xs\n           else filtrev p       acc  xs\n  else acc.\n\n(**  The teacher asks him to prove that his ugly code is equivalent\n to the nicer code [[seq x <- rev l | p x]] he could have written\nby reusing the seq library.\n\nSuch proof is not trivial:\n  - [filtrev] has an accumulator, [rev] (at least apparently)\n    does not.\n  - which is the invariant linking the accumulator [acc] and [p]\n    in the code of [filtrev]?  Depending on how you expose\n    the accumulator on the right hand side of the goal,\n    such invariant may need to be taken into account by the induction.\n\nRelevant keywords for [Search] are: rev cons cat filter rcons\nHint: it is perfectly fine to state intermediate lemmas\n*)\n\nLemma filterrev_ok T p (l : seq T) :\n  filtrev p [::] l = [seq x <- rev l | p x ].\nProof.\n(*X*)rewrite -[RHS]cats0; elim: l [::] => [|x l ihl] l' //=.\n(*X*)by case: ifP => px; rewrite ihl rev_cons filter_rcons ?px ?cat_rcons.\n(*A*)Qed.\n\n(** Prove that if (s1 :|: s2) is disjoint from (s1 :|: s3) then\n    s1 is empty *)\nLemma disjoint_setU2l (T : finType) (s1 s2 s3 : {set T}) :\n   [disjoint s1 :|: s2 & s1 :|: s3] -> s1 = set0.\n(*A*)Proof. by rewrite -setI_eq0 -setUIr setU_eq0 => /andP [/eqP]. Qed.\n\n(** Prove the equivalence of these two sums.\n    E.g. (n=8)\n<<\n    1 + 3 + 5 + 7 = 7-0 + 7-2 + 7-4 + 7-6\n>>\n*)\nLemma sum_odd n :\n  ~~ odd n -> \\sum_(i < n | odd i) i = \\sum_(i < n | ~~ odd i) (n.-1 - i).\nProof.\n(*X*)rewrite (reindex_inj rev_ord_inj) /= => /negPf n_oddF.\n(*X*)by apply: eq_big => i; rewrite odd_sub ?n_oddF //; case: n i {n_oddF}.\n(*A*)Qed.\n(**\n\nNow, some algebra.\n\n*)\nFrom mathcomp Require Import all_algebra.\nFrom mathcomp Require Import algC zmodp.\n\nSection AlgebraicHierarchy.\nSection GaussIntegers.\nImport GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n(**\n\nWe remind what Gauss integer are and recall some theory about it.\n\n*)\nDefinition gaussInteger := [qualify a x | ('Re x \\in Cint) && ('Im x \\in Cint)].\nAxiom Cint_GI : forall (x : algC), x \\in Cint -> x \\is a gaussInteger.\nAxiom GI_subring : subring_closed gaussInteger.\n\nFact GI_key : pred_key gaussInteger. Proof. by []. Qed.\nCanonical GI_keyed := KeyedQualifier GI_key.\nCanonical GI_opprPred := OpprPred GI_subring.\nCanonical GI_addrPred := AddrPred GI_subring.\nCanonical GI_mulrPred := MulrPred GI_subring.\nCanonical GI_zmodPred := ZmodPred GI_subring.\nCanonical GI_semiringPred := SemiringPred GI_subring.\nCanonical GI_smulrPred := SmulrPred GI_subring.\nCanonical GI_subringPred := SubringPred GI_subring.\n\nRecord GI := GIof {algGI : algC; algGIP : algGI \\is a gaussInteger }.\nHint Resolve algGIP.\n\nCanonical GI_subType := [subType for algGI].\nDefinition GI_eqMixin := [eqMixin of GI by <:].\nCanonical GI_eqType := EqType GI GI_eqMixin.\nDefinition GI_choiceMixin := [choiceMixin of GI by <:].\nCanonical GI_choiceType := ChoiceType GI GI_choiceMixin.\nDefinition GI_countMixin := [countMixin of GI by <:].\nCanonical GI_countType := CountType GI GI_countMixin.\nDefinition GI_zmodMixin := [zmodMixin of GI by <:].\nCanonical GI_zmodType := ZmodType GI GI_zmodMixin.\nDefinition GI_ringMixin := [ringMixin of GI by <:].\nCanonical GI_ringType := RingType GI GI_ringMixin.\nDefinition GI_comRingMixin := [comRingMixin of GI by <:].\nCanonical GI_comRingType := ComRingType GI GI_comRingMixin.\n\nLemma conjGIE x : (x^* \\is a gaussInteger) = (x \\is a gaussInteger).\nProof. by rewrite ![_ \\is a _]qualifE algRe_conj algIm_conj rpredN. Qed.\n\nFact conjGI_subproof (x : GI) : (val x)^* \\is a gaussInteger.\nProof. by rewrite conjGIE. Qed.\n\nCanonical conjGI x := GIof (conjGI_subproof x).\n\nDefinition gaussNorm (x : algC) := x * x^*.\n\nAxiom gaussNormE : forall x, gaussNorm x = `|x| ^+ 2.\nAxiom gaussNormCnat : forall (x : GI), gaussNorm (val x) \\in Cnat.\n(**\n\nProve these two facts. (Hint: conjugation is a morphism)\n\n*)\nLemma gaussNorm1 : gaussNorm 1 = 1.\n(*A*)Proof. by rewrite /gaussNorm rmorph1 mulr1. Qed.\n\nLemma gaussNormM : {morph gaussNorm : x y / x * y}.\n(*A*)Proof. by move=> x y; rewrite /gaussNorm rmorphM mulrACA. Qed.\n(**\n\n** Question: Prove that GI euclidean for the stasm gaussNorm.\n\n - i.e. ∀ (a, b) ∈ GI × GI*, ∃ (q, r) ∈ GI² s.t. a = q b + r and φ(r) < φ(b)\n - Suggested strategy: sketch the proof on a paper first, don't let Coq\n   divert you from your proofsketch\n - We first sketch the \"paper proof\" here and then do it in Coq:\n  - take a / b = x + i y\n  - take u the closest integer to x, and v the closest integer to y\n  - satisfy the existential with q = u + i v and r = a - q b,\n    which are both Gauss integers.\n  - We want to show that |a - q b|² < |b|².\n  - It suffices to show |a / b - q|² < 1\n  - But |a / b - q|² = (u - x)² + (v - x)² ≤ ‌½² + ½² < 1\n - Now we give a Coq proof with holes, fill in the holes.\n*)\nLemma euclideanGI (a b : GI) : b != 0 ->\n  exists2 qr : GI * GI, a = qr.1 * b + qr.2\n                      & (gaussNorm (val qr.2) < gaussNorm (val b)).\nProof.\nmove=> b_neq0.\n\n(* Trivial preliminaries *)\nhave oneV2 : 1 = 2%:R^-1 + 2%:R^-1 :> algC.\n  by rewrite -mulr2n -[_ *+ 2]mulr_natr mulVf ?pnatr_eq0.\nhave V2ge0 : 0 <= 2%:R^-1 :> algC by (*a*)rewrite invr_ge0 ler0n.\nhave V2real : (2%:R^-1 : algC) \\is Num.real by (*a*)rewrite realE V2ge0.\n\n(* Closest integer to x, when x is real *)\npose approx (x : algC) : int :=\n  floorC x + (if `|x - (floorC x)%:~R| <= 2%:R^-1 then 0 else 1).\nhave approxP x : x \\is Creal -> `|x - (approx x)%:~R| <= 2%:R^-1.\n  rewrite /approx => x_real; have /andP [x_ge x_le] := floorC_itv x_real.\n  have [] // := @real_lerP _  `|_ - (floorC _)%:~R| _;\n    first by rewrite addr0.\n  rewrite [`|_ - (_ + 1)%:~R|]distrC !ger0_norm ?subr_ge0 //=;\n     last by rewrite ltrW.\n  move=> Dx1_gtV2; rewrite real_lerNgt ?rpredB // ?Creal_Cint ?Cint_int //.\n  apply/negP=> /ltr_add /(_ Dx1_gtV2); rewrite -oneV2 !addrA addrNK.\n  by rewrite [_ + 1]addrC rmorphD /= addrK ltrr.\nhave approxP2 x (_ : x \\is Creal) : `|x - (approx x)%:~R| ^+ 2 < 2%:R^-1.\n  rewrite (@ler_lt_trans _ (2%:R^-1 ^+ 2)) // ?ler_expn2r ?qualifE ?approxP //.\n  by rewrite exprVn -natrX ltf_pinv ?qualifE ?ltr_nat ?ltr0n.\n\n(* Proper proof *)\npose u := 'Re (val a / val b); pose v := 'Im (val a / val b).\nhave qGI : (approx u)%:~R + algCi * (approx v)%:~R \\is a gaussInteger.\n  (* Hint: use qualifE, alg*_rect and lemmas about Creal, Cint and _%:~R *)\n  (*a*)by rewrite qualifE /= algRe_rect ?algIm_rect // ?Creal_Cint ?Cint_int.\npose q := GIof qGI.\nexists (q, a - q * b); first by rewrite addrC addrNK.\nrewrite !gaussNormE /=.\nrewrite -(@ltr_pmul2r _ (`|val b| ^-2)) ?invr_gt0 ?exprn_gt0 ?normr_gt0 //.\nrewrite mulfV ?expf_eq0 /= ?normr_eq0 // -exprVn -exprMn.\nrewrite -normfV -normrM mulrBl mulfK //.\nsuff uvP : `|u - (approx u)%:~R + 'i * (v - (approx v)%:~R)| ^+ 2 < 1.\n  (* Hint: use algCrect and algebraic transformations *)\n  (*a*)by rewrite [X in X - _]algCrect opprD addrACA -mulrBr.\nset Du := _ - _; set Dv := _ - _.\nhave /andP [DuReal DvReal] : (Du \\is Creal) && (Dv \\is Creal).\n(* Hint: use rpred*, Creal_*, normC2_rect, ream_normK and approxP2 *)\n(*a*)  by rewrite ?rpredB ?Creal_Re ?Creal_Im ?Creal_Cint ?Cint_int.\n(*X*)rewrite normC2_rect // oneV2.\n(*X*)by rewrite ltr_add // -real_normK // approxP2 ?Creal_Re ?Creal_Im.\n(*A*)Qed.\n\nEnd GaussIntegers.\nEnd AlgebraicHierarchy.\n\nSection PolynomialsLagrange.\n\nOpen Scope ring_scope.\nImport GRing.Theory Num.Theory.\n(**\n\nDefinition and properties of lagrange polynomials.\n\nProve only one of the following lemmas\n*)\nVariables (n : nat) (x : algC ^ n).\n\nDefinition lagrange (i : 'I_n) : {poly algC} :=\n  let p := \\prod_(j < n | j != i) ('X - (x j)%:P) in (p.[x i]^-1)%:P * p.\n\nHypothesis n_gt0 : (0 < n)%N.\nHypothesis x_inj : injective x.\n\nLemma lagrangeE (i j : 'I_n) : (lagrange i).[x j] = (i == j)%:R.\nProof using x_inj.\n(*X*)rewrite /lagrange hornerM hornerC; set p := (\\prod_(_ < _ | _) _).\n(*X*)have [<-|neq_ij] /= := altP eqP.\n(*X*)  rewrite mulVf // horner_prod; apply/prodf_neq0 => k neq_ki.\n(*X*)  by rewrite hornerXsubC subr_eq0 inj_eq // eq_sym.\n(*X*)rewrite [X in _ * X]horner_prod (bigD1 j) 1?eq_sym //=.\n(*X*)by rewrite hornerXsubC subrr mul0r mulr0.\n(*A*)Qed.\n\n\nLemma size_lagrange i : size (lagrange i) = n.\nProof using n_gt0 x_inj.\n(*X*)rewrite size_Cmul; last first.\n(*X*)  suff : (lagrange i).[x i] != 0 by rewrite hornerE mulf_eq0 => /norP [].\n(*X*)  by rewrite lagrangeE ?eqxx ?oner_eq0.\n(*X*)rewrite size_prod /=; last first.\n(*X*)  by move=> j neq_ji; rewrite polyXsubC_eq0.\n(*X*)rewrite (eq_bigr (fun=> (2 * 1)%N)); last first.\n(*X*)  by move=> j neq_ji; rewrite size_XsubC.\n(*X*)rewrite -big_distrr /= sum1_card cardC1 card_ord /=.\n(*X*)by case: (n) {i} n_gt0 => ?; rewrite mul2n -addnn -addSn addnK.\n(*A*)Qed.\n\nLemma lagrange_free (lambda : 'rV_n):\n  \\sum_i (lambda 0 i)%:P * lagrange i = 0 -> lambda = 0.\nProof using x_inj.\n(*X*)move=> eq_l; apply/rowP=> i; rewrite mxE.\n(*X*)have /(congr1 (fun p => p.[x i])) := eq_l.\n(*X*)rewrite horner_sum horner0 (bigD1 i) //= hornerE lagrangeE // eqxx mulr1.\n(*X*)rewrite big1 ?addr0 // => j neq_ji.\n(*X*)by rewrite hornerM lagrangeE // (negPf neq_ji) mulr0.\n(*A*)Qed.\n\nLemma lagrange_gen (p : {poly algC}) :\n   (size p <= n)%N -> p = \\sum_i p.[x i]%:P * lagrange i.\nProof using n_gt0 x_inj.\n(*X*)(* fancy proof using marix spaces *)\n(*X*)move=> sp_le_n; pose L := \\matrix_(i < n) @poly_rV _ n (lagrange i).\n(*X*)suff /(congr1 rVpoly) : poly_rV p = \\row_i p.[x i] *m L.\n(*X*)  rewrite poly_rV_K // => {1}->; rewrite mulmx_sum_row raddf_sum /=.\n(*X*)  apply: eq_bigr=> i _; rewrite linearZ /= mxE mul_polyC.\n(*X*)  by rewrite rowK poly_rV_K ?size_lagrange.\n(*X*)have /submxP [u puL]: (poly_rV p <= L)%MS.\n(*X*)  rewrite (submx_trans (submx1 _)) // sub1mx row_full_unit -row_free_unit.\n(*X*)  rewrite -kermx_eq0; apply/rowV0P => v /sub_kermxP.\n(*X*)  move=> /(congr1 rVpoly); rewrite !raddf0 mulmx_sum_row raddf_sum /= => vL0.\n(*X*)  rewrite [v]lagrange_free // -[RHS]vL0; apply: eq_bigr => i _.\n(*X*)  by rewrite linearZ rowK mul_polyC /= poly_rV_K ?size_lagrange.\n(*X*)rewrite puL; congr (_ *m _); apply/rowP=> i; rewrite mxE.\n(*X*)have /(congr1 (fun v => (rVpoly v).[x i])) := puL.\n(*X*)rewrite poly_rV_K // mulmx_sum_row raddf_sum /=.\n(*X*)rewrite (bigD1 i) //= linearZ /= rowK poly_rV_K ?size_lagrange //.\n(*X*)rewrite 2!hornerE lagrangeE eqxx mulr1 horner_sum big1 ?addr0 //.\n(*X*)move=> j neq_ji; rewrite linearZ rowK /= ?poly_rV_K ?size_lagrange //.\n(*X*)by rewrite hornerZ lagrangeE (negPf neq_ji) mulr0.\n\n(*X*)Restart. (* shorter proof, direct *)\n\n(*X*)move=> sp_le_n; apply/eqP; rewrite -subr_eq0; apply: contraTT isT.\n(*X*)move=> /max_poly_roots - /(_ [seq x i | i <- enum 'I_n]).\n(*X*)rewrite size_map size_enum_ord map_inj_uniq ?enum_uniq //.\n(*X*)rewrite [(n < _)%N]negbTE; [apply=>//|rewrite -leqNgt].\n(*X*)  apply/allP=> /= _ /imageP [/= i _ ->].\n(*X*)  rewrite rootE !hornerE horner_sum (bigD1 i) //=.\n(*X*)  rewrite hornerM hornerC lagrangeE // eqxx mulr1 opprD addNKr.\n(*X*)  rewrite big1 ?oppr0 // => j neq_ji.\n(*X*)  by rewrite hornerM lagrangeE // (negPf neq_ji) mulr0.\n(*X*)rewrite (leq_trans (size_add _ _)) // size_opp geq_max sp_le_n /=.\n(*X*)rewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP=> j _.\n(*X*)rewrite (leq_trans (size_mul_leq _ _)) // size_polyC size_lagrange //.\n(*X*)by move: (n) n_gt0 (_ == _) => [] // ? _ [].\n(*A*)Qed.\n\nEnd PolynomialsLagrange.\n\nSection PolynomialsTaylor.\n(**\nTaylor formula for polynomials\n\n*)\nImport GRing.Theory.\nOpen Scope ring_scope.\nVariable R: idomainType.\n\n(*X*)(* This is the strongest statement I could prove *)\n(*X*)(* uses max_poly_roots and nderiv_taylor *)\n(*X*)Lemma Taylor_formula_strong (p : {poly R}) (x : R) (rs : seq R) :\n(*X*)  (size p <= size rs)%N -> uniq rs ->\n(*X*)  p = \\sum_ (i < size p) p^`N(i).[x] *: ('X - x%:P) ^+ i.\n(*X*)Proof.\n(*X*)move=> sprs /max_poly_roots prs; apply/eqP; rewrite -subr_eq0.\n(*X*)apply: contraTT isT => /prs; rewrite [(_ < _)%N]negbTE; [apply|rewrite -leqNgt].\n(*X*)  apply/allP=> y y_rs; rewrite rootE hornerD hornerN subr_eq0; apply/eqP.\n(*X*)  rewrite -[y in X in p.[X]](addrNK x) [_ + x]addrC.\n(*X*)  rewrite nderiv_taylor; last exact: mulrC.\n(*X*)  by rewrite horner_sum; apply: eq_bigr=> i _; rewrite !(hornerE, horner_exp).\n(*X*)rewrite (leq_trans (size_add _ _)) // geq_max sprs /= size_opp.\n(*X*)rewrite (leq_trans (size_sum _ _ _)) //; apply/bigmax_leqP=> i _.\n(*X*)rewrite (leq_trans (size_scale_leq _ _)) //.\n(*X*)by rewrite size_exp_XsubC (leq_trans _ sprs).\n(*X*)Qed.\n\n(*X*)Lemma natr_injP (D : idomainType) :\n(*X*)  (forall n, (n%:R == 0 :> D) = (n == 0)%N) <-> injective (@GRing.natmul D 1).\n(*X*)Proof.\n(*X*)split=> [natr_eq0 i j|natr_inj n]; last by rewrite -(inj_eq natr_inj).\n(*X*)wlog: i j / (j <= i)%N => [hwlog|].\n(*X*)  by have [/hwlog//|/ltnW/hwlog/(_ (esym _))/esym] := leqP j i.\n(*X*)by move=> /subnK<- /eqP; rewrite -subr_eq0 natrD addrK natr_eq0 => /eqP->.\n(*X*)Qed.\n\n(*X*) (* This is the statement we ask the students to prove *)\nHypothesis charR_eq0 : [char R] =i pred0.\nLemma Taylor_formula (p : {poly R}) (x : R) :\n  p = \\sum_ (i < size p) p^`N(i).[x] *: ('X - x%:P) ^+ i.\n(*X*)Proof. (* Proof using the stronger version *)\n(*X*)apply: (@Taylor_formula_strong _ _ [seq i%:R | i <- iota 0 (size p)]).\n(*X*)  by rewrite size_map size_iota.\n(*X*)by rewrite map_inj_uniq ?iota_uniq //; apply/natr_injP/charf0P.\n(*X*)\n(*X*)Restart. (* Proof for the students *)\n(*X*)\nProof.\nwlog: p x / x = 0 => [hwlog|->]; rewrite ?subr0; last first.\n(*X*)  transitivity (\\poly_(i < size p) p^`N(i).[0]);\n(*X*)    last by rewrite poly_def.\n(*X*)  apply/polyP=> /= i; rewrite coef_poly.\n(*X*)  have [i_small|i_big]:= ltnP; last by rewrite nth_default.\n  (*a*)by rewrite horner_coef0 coef_nderivn addn0 binn mulr1n.\nrewrite -[LHS](comp_polyXaddC_K _ x) -[RHS](comp_polyXaddC_K _ x).\ncongr (_ \\Po _); rewrite [LHS](hwlog _ 0 erefl) ?subr0 [RHS]raddf_sum /=.\nrewrite size_comp_poly2; last first.\n  by rewrite -[x%:P as X in 'X + X]opprK -[- x%:P]raddfN /= size_XsubC.\n(*X*)apply: eq_bigr => i _.\n(*X*)have nderivn_compXD q (a : R) j :\n(*X*)  (q \\Po ('X + a%:P))^`N(j) = q^`N(j) \\Po ('X + a%:P).\n       have /charf0P/natr_injP natr_inj := charR_eq0.\n(*X*)  apply: (@mulfI _ j`!%:R%:P).\n(*X*)     rewrite polyC_eq0; have/charf0P -> := charR_eq0.\n     (*a*)by rewrite -lt0n fact_gt0.\n(*X*)  rewrite !mul_polyC !scaler_nat -rmorphMn /= -!nderivn_def.\n  (*a*)by elim: j => //= j ->; rewrite deriv_comp !derivE addr0 mulr1.\n(*X*)rewrite nderivn_compXD horner_comp !hornerE // linearZ rmorphX /=.\n(*X*)rewrite -['X - x%:P]comp_polyX -[x%:P as X in 'X + X]opprK.\n(*X*)by rewrite -[- x%:P]raddfN /= comp_polyXaddC_K.\n(*A*)Qed.\n\nEnd PolynomialsTaylor.\n\nSection LinearAlgebra.\nImport GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n(**\n\n* Endomorphisms u such that Ker u ⊕ Im u = E.\n\nThe endomorphisms of a space E of finite dimension n, such that u o v\n= 0 and v + u is invertible are exactly the endomorphisms such that\nKer u ⊕ Im u = E.\n\n - Assume u o v = 0 and v + u is invertible,\n  - we have rank (v + u) = n\n  - we have rank v + rank u = n and we have Im v ⊂ Ker u\n  - Hence we have Im v = Ker u\n  - We deduce that Ker u ⊕ Im u = Im v ⊕ Im u = E\n\n*)\nVariables (F : fieldType) (n' : nat).\nLet n := n'.+1.\n\nLemma ex_6_13 (u : 'M[F]_n):\n  reflect (exists2 v : 'M_n, v * u = 0 & v + u \\is a GRing.unit)\n          ((kermx u + u == 1)%MS && mxdirect (kermx u + u)).\nProof.\n(* Hint: use mxrank* lemmas and search on addsmx, submx and eqmx\nsometimes. Don't forget about mxdirect_addsP and sub_kermxP. *)\napply: (iffP idP) => [|[v vMu vDu]]; last first.\n  have rkvDu: \\rank (v + u)%R = n by (*a*)rewrite mxrank_unit.\n  have /eqP rkvDrku : (\\rank v + \\rank u)%N == n.\n    by rewrite eqn_leq; (*a*)rewrite mulmx0_rank_max //= -{1}rkvDu mxrank_add.\n  have sub_v_ku : (v <= kermx u)%MS by (*a*)apply/sub_kermxP.\n  have /eqmxP/eqmx_sym eq_vu: (v == kermx u)%MS.\n    rewrite -(geq_leqif (mxrank_leqif_eq _)) //.\n(*X*)    rewrite -(leq_add2r (\\rank u)) rkvDrku.\n    (*a*)by rewrite mxrank_ker subnK // rank_leq_row.\n  rewrite submx1 sub1mx -col_leq_rank mxdirectEgeq /=.\n  (* use adds_eqmx to lift eq_vu to a sum *)\n(*X*)  rewrite eq_vu (adds_eqmx eq_vu (eqmx_refl _)).\n  (* Warning: - (u + v)%R  is a sum of matrices\n              - (u + v)%MS is a sum of spaces\n     use addmx_sub_adds and mxrankS\n     to compare the rank (u + v) with dim (Im u + Im v) *)\n(*X*)  have /mxrankS leq_rk := addmx_sub_adds (submx_refl v) (submx_refl u).\n  (* finish using hypothesis *)\n  (*a*)by rewrite !(leq_trans _ leq_rk) //= ?rkvDu ?rkvDrku.\nmove=> /andP [/eqmxP kuDu_eq1 /mxdirect_addsP kvDu_direct].\npose v := proj_mx (kermx u) u; exists v.\n  (*a*)by apply/sub_kermxP; rewrite -[X in (X <= _)%MS]mul1r proj_mx_sub.\nrewrite -row_free_unit -kermx_eq0.\napply/negP => /negP /rowV0Pn [x /sub_kermxP]; rewrite mulmxDr.\nmove=> /(canRL (addrK _)); rewrite sub0r => eq_xv_Nxu.\napply/negP; rewrite negbK; apply/eqP.\nhave : (x *m v <= kermx u :&: u)%MS.\n(* Hint: use sub_*, proj_mx*, eqmx_*, mxdirect_addsP, *)\n  (*a*)by rewrite sub_capmx proj_mx_sub eq_xv_Nxu eqmx_opp submxMl.\n(*X*)rewrite kvDu_direct ?submx0 // => /eqP xv_eq0.\n(*X*)move/eqP : eq_xv_Nxu; rewrite xv_eq0 eq_sym oppr_eq0 => /eqP.\n(*X*)by move=> /sub_kermxP x_in_keru; move: xv_eq0; rewrite proj_mx_id.\n(*A*)Qed.\n\nEnd LinearAlgebra.\n\n(*X*)(*\n(*X*)*** Local Variables: ***\n(*X*)*** coq-prog-args: (\"-emacs-U\" \"-R\" \"/Users/lrg/coq/math-comp/mathcomp\" \"mathcomp\" \"-I\" \"/Users/lrg/coq/math-comp/mathcomp\" ) ***\n(*X*)*** End: ***\n(*X*)*)\n", "meta": {"author": "gares", "repo": "CWS16", "sha": "608148973a715994ebbedb0a48724f2755c7bc89", "save_path": "github-repos/coq/gares-CWS16", "path": "github-repos/coq/gares-CWS16/CWS16-608148973a715994ebbedb0a48724f2755c7bc89/exam.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245994514082, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.7312229897861701}}
{"text": "(*begin hide*)\nRequire Import Bool Arith List CpdtTactics.\nSet Implicit Arguments.\n(*end hide*)\n\n(** * Inductive Predicates\n\nCurry-Howard correspondence states formal connection between\nfunctional programs and mathematical proofs. The definitions of [True]\nand [unit] help clarify:*)\n\nPrint unit.\n(**\n[[\nInductive unit : Set :=  tt : unit\n]]\n*)\n\nPrint True.\n(**\n[[\nInductive True : Prop :=  I : True\n]]\n\nSpecifically, one is a type with a single value, and the other is a\nproposition that always holds; the same induction principle can be\nused for both. Substituting names gives the same definition, but the\ntype is the distinguisher: [T] of type [Set] is a type of programs,\nwhile [T] of type [Prop] is a logical proposition. Understanding why\nthe distinction is made helps to avoid conflating programming and\nproving.\n\nEngineering-wise, not all functions of type [A->B] are equally\nconstructed, but all proofs of the proposition [P->Q] are (_proof\nirrelevance_). We program by applying functional programming\ntechniques to dependent types, and prove by writing custom decision\nprocedures.\n\n** Propositional Logic*)\n\nSection Propositional.\n  Variables P Q R : Prop.\n\n(** The most basic propositional construct is [->], implies. It's built into\nCoq as the function type constructor.\n\nThe trivial proof of [True]:*)\n\n  Theorem obvious: True.\n  Proof.\n    apply I.\n  Qed.\n\n(** [apply] is a tactic allowing us to use a particular constructor of\nthe inductive predicate being established. A shortcut:*)\n\n  Theorem obvious': True.\n  Proof.\n    constructor.\n  Qed.\n\n(** The predicate [False] is the Curry-Howard mirror of [Empty_set]: *)\n\n  Print False.\n\n(**\n[[\nInductive False : Prop :=  \n]]\n\nDoing case analysis on a proof of [False] has no cases:*)\n\n  Theorem False_imp: False -> 2 + 2 = 5.\n  Proof. destruct 1. Qed.\n\n(** No proof of [False] can be constructed in a consistent contex.*)\n\n  Theorem arith_neq: 2 + 2 = 5 -> 9 + 9 = 835.\n  Proof. intro. elimtype False. crush. Qed.\n\n(** Related is logical negation:*)\n\n  Print not.\n(**\n[[\nnot = fun A : Prop => A -> False\n     : Prop -> Prop\n\nArgument scope is [type_scope]\n]]\n\nThe syntax [~P] expands to [not P].\n*)\n\n  Theorem arith_neq': ~(2 + 2 = 5).\n  Proof. unfold not. crush. Qed.\n\n(** Conjunction:*)\n\n  Print and.\n(**\n[[\nInductive and (A B : Prop) : Prop :=  conj : A -> B -> A /\\ B\n\nFor conj: Arguments A, B are implicit\nFor and: Argument scopes are [type_scope type_scope]\nFor conj: Argument scopes are [type_scope type_scope _ _]\n]]\n\n[and] has a Curry-Howard equivalent [prod].\n\nWe can reason about conjunction with tactics; for example, through an\nexplicit proof of commutivity: *)\n\n  Theorem and_comm: P /\\ Q -> Q /\\ P.\n  Proof.\n    destruct 1. split.\n    assumption. assumption. (* for each case, conclusion is among hypotheses. *)\n  Qed.\n\n(** Disjunction occurs via [or]:*)\n\n  Print or.\n\n(**\n[[\nInductive or (A B : Prop) : Prop :=\n    or_introl : A -> A \\/ B | or_intror : B -> A \\/ B\n\nFor or_introl, when applied to less than 1 argument:\n  Arguments A, B are implicit\nFor or_introl, when applied to 2 arguments:\n  Argument A is implicit\nFor or_intror, when applied to less than 1 argument:\n  Arguments A, B are implicit\nFor or_intror, when applied to 2 arguments:\n  Argument B is implicit\nFor or: Argument scopes are [type_scope type_scope]\nFor or_introl: Argument scopes are [type_scope type_scope _]\nFor or_intror: Argument scopes are [type_scope type_scope _]\n]]\n\nThere are two ways to prove a disunction: prove the first disjunct or prove the second. (The Curry-Howard analogue is the [sum] type.)\n*)\n\n  Theorem or_comm: P \\/ Q -> Q \\/ P.\n  Proof.\n    destruct 1.\n    right; assumption. (*Prove disjunction by proving the right disjunct.*)\n    left; assumption.\n  Qed.\n\n(** The [tauto] tactic is a complete decision procedure for\nconstructive propositional logic. [intuition] is a generalisation of\n[tauto] proving everything it can through propositional\nreasoning. Consider:*)\n\n  Theorem arith_comm: forall ls1 ls2 : list nat,\n          length ls1 = length ls2 \\/ length ls1 + length ls2 = 6 ->\n          length (ls1 ++ ls2) = 6 \\/ length ls1 = length ls2.\n  Proof.\n    intuition.\n    rewrite app_length.\n    tauto.\n  Qed.\n\n(** Each of these theorems becomes universally quantified over the\npropositional variables.*)\n\nEnd Propositional.", "meta": {"author": "kisom", "repo": "cpdt", "sha": "f29b8d0fdbbcc7fccf5a6e9eccb99e67dd5001fb", "save_path": "github-repos/coq/kisom-cpdt", "path": "github-repos/coq/kisom-cpdt/cpdt-f29b8d0fdbbcc7fccf5a6e9eccb99e67dd5001fb/src/predicates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7311899456132327}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Classes.EquivDec.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Init.Nat.\nImport Coq.Lists.List.ListNotations.\n\nRequire Import BWT.Lib.Permutation.\nRequire Import BWT.Lib.Sumbool.\nRequire Import BWT.Lib.List.\nRequire Import BWT.Lib.FindIndex.\nRequire Import BWT.Sorting.StablePerm.\n\nDefinition PermFun (n : nat) (p : list nat) : Prop :=\n    NoDup p /\\ forall i, In i p <-> i < n.\n\nRemark PermFun_0 : forall p,\n    PermFun 0 p <-> p = [].\nProof.\n  split; intros Hp; [|subst p; split; [constructor|easy]].\n  destruct p as [|i p]; [easy|].\n  exfalso; apply (Nat.nlt_0_r i).\n  apply Hp; left; easy.\nQed.\n\nRemark PermFun_nil : forall n,\n    PermFun n [] <-> n = 0.\nProof.\n  split; intros Hp; [|subst n; split; [constructor|easy]].\n  destruct n; [easy|].\n  destruct Hp as [_ Hp].\n  specialize (Hp 0); cbn in Hp.\n  exfalso; apply Hp.\n  apply Nat.lt_0_succ.\nQed.\n\nRemark PermFun_S_nil : forall n,\n    ~ PermFun (S n) [].\nProof.\n  intros n c.\n  remember (S n) as n'.\n  apply PermFun_nil in c.\n  subst; discriminate.\nQed.\n\nTheorem PermFun_Permutation_seq : forall n p,\n    PermFun n p <-> Permutation p (seq 0 n).\nProof.\n  split.\n  - intros [HND Hp].\n    apply NoDup_Permutation; [easy|apply seq_NoDup|].\n    intros i; specialize (Hp i).\n    rewrite (in_seq n 0 i); cbn.\n    intuition.\n  - intros HP.\n    split; [eapply Permutation_NoDup; [symmetry; eauto|apply seq_NoDup]|].\n    split.\n    + intros HIn. apply (in_seq n 0 i).\n      eapply Permutation_in; eauto.\n    + intros HB. eapply Permutation_in; [symmetry; apply HP|].\n      apply in_seq. omega.\nQed.\n\nTheorem PermFun_range : forall p i n,\n    PermFun n p -> In i p -> i < n.\nProof. intros p i n [_ Hp]. apply Hp. Qed.\n\nTheorem PermFun_length : forall p n,\n    PermFun n p -> length p = n.\nProof.\n  intros p n Hp.\n  apply PermFun_Permutation_seq in Hp.\n  apply Permutation_length in Hp.\n  rewrite seq_length in Hp.\n  easy.\nQed.\n\nSection Image.\n  Context {A : Type}.\n\n  Definition image (p : list nat) i := nth i p 0.\n  Definition preimage (p : list nat) i := findIndex i p.\n\n  Variables (p : list nat) (n :nat).\n\n  Hypothesis HP : PermFun n p.\n\n  Lemma PermFun_i_exists : forall i,\n      i < n -> Exists (equiv i) p.\n  Proof.\n    intros i HI.\n    eapply Permutation_exists;\n      [symmetry; apply PermFun_Permutation_seq with (n := n); easy|].\n    apply Exists_exists.\n    exists i. split; [|easy].\n    apply in_seq; omega.\n  Qed.\n\n  Theorem preimage_image : forall i,\n      i < n -> preimage p (image p i) = i.\n  Proof.\n    intros i HI.\n    unfold image, preimage.\n    rewrite findIndex_nth;\n      [.. |apply HP |erewrite PermFun_length by apply HP]; easy.\n  Qed.\n\n  Theorem image_preimage : forall i,\n      i < n -> image p (preimage p i) = i.\n  Proof.\n    intros i HI.\n    unfold image, preimage.\n    rewrite findIndex_correct by (eapply PermFun_i_exists; omega).\n    reflexivity.\n  Qed.\n\n  Theorem image_inj : forall i j,\n      i < n -> j < n -> image p i = image p j -> i = j.\n  Proof.\n    intros i j HI HJ HE.\n    apply (NoDup_nth p 0); [|erewrite PermFun_length by apply HP..|]; [|easy..].\n    apply HP.\n  Qed.\n\n  Theorem preimage_inj : forall i j,\n      i < n -> j < n ->\n      preimage p i = preimage p j -> i = j.\n  Proof.\n    intros i j HI HJ HE.\n    unfold preimage in HE.\n    apply f_equal with (f := fun x => nth x p 0) in HE.\n    rewrite !findIndex_correct in HE by (eapply PermFun_i_exists; easy).\n    easy.\n  Qed.\n\n  Theorem image_bound : forall i,\n      i < n -> image p i < n.\n  Proof.\n    intros i HI.\n    apply PermFun_range with (p := p); [easy|].\n    apply nth_In.\n    rewrite PermFun_length with (n := n) by easy.\n    easy.\n  Qed.\n\n  Theorem preimage_bound : forall i,\n      i < n -> preimage p i < n.\n  Proof.\n    intros i HI.\n    rewrite <- PermFun_length with (p := p) by easy.\n    apply findIndex_bounds.\n    eapply PermFun_i_exists; easy.\n  Qed.\nEnd Image.\n\nSection Apply.\n  Context {A : Type}.\n\n  Implicit Types (p : list nat) (l : list A).\n\n  Definition apply p l : list A :=\n    match l with\n    | [] => []\n    | d :: _ => map (fun i => nth i l d) p\n    end.\n\n  Theorem apply_def : forall p l d,\n      PermFun (length l) p ->\n      apply p l = map (fun i => nth i l d) p.\n  Proof.\n    intros p [|h t] d HP.\n    - apply PermFun_0 in HP; subst; easy.\n    - cbn [apply]. apply map_ext_in.\n      intros; apply nth_indep.\n      apply (PermFun_range p); easy.\n  Qed.\n\n  Theorem nth_preimage_apply : forall p i l d,\n      PermFun (length l) p -> i < length l ->\n      nth (preimage p i) (apply p l) d = nth i l d.\n  Proof.\n    intros p i l d HP HI.\n    rewrite apply_def with (d := d) by easy.\n    unfold preimage.\n    assert (E : Exists (equiv i) p)\n      by (eapply PermFun_i_exists; [apply HP|easy]).\n    assert (In (findIndex i p) p). {\n      eapply Permutation_in; [symmetry; apply PermFun_Permutation_seq; eauto|].\n      apply in_seq.\n      pose proof (findIndex_bounds i p E).\n      erewrite PermFun_length in H by apply HP.\n      omega.\n    }\n    rewrite nth_indep with (d := d) (d' := nth 0 l d)\n      by (apply PermFun_range with (p := p);\n          [erewrite map_length, PermFun_length|]; [apply HP..|easy]).\n    rewrite map_nth with (f := (fun i0 : nat => nth i0 l d)).\n    rewrite findIndex_correct by easy.\n    reflexivity.\n  Qed.\n\n  Theorem nth_image_apply : forall p i l d,\n      PermFun (length l) p -> i < length l ->\n      nth (image p i) l d = nth i (apply p l) d.\n  Proof.\n    intros p i l d HP HI.\n    rewrite <- preimage_image with (i := i) (p := p) (n := length l) at 2 by easy.\n    rewrite nth_preimage_apply; [..|apply image_bound]; [|easy..].\n    reflexivity.\n  Qed.\n\n  Theorem map_seq_id : forall l d,\n      map (fun x : nat => nth x l d) (seq 0 (length l)) = l.\n  Proof.\n    induction l; intros d; [easy|].\n    cbn [length seq map]; f_equal.\n    rewrite <- seq_shift, map_map.\n    apply IHl.\n  Qed.\n\n  Theorem apply_id : forall l,\n      apply (seq 0 (length l)) l = l.\n  Proof.\n    destruct l; [easy|].\n    apply map_seq_id with (d := a).\n  Qed.\n\n  Section RemPermFun.\n    Definition rem_PermFun i := map (fun j => if lt_dec i j then pred j else j).\n\n    Theorem rem_PermFun_0 : forall p n, PermFun n (0 :: p) -> rem_PermFun 0 p = map pred p.\n    Proof.\n      induction p; intros n HP; [easy|].\n      unfold rem_PermFun. apply map_ext_in.\n      intros x HIn.\n      assert (1 <= x). {\n        apply PermFun_Permutation_seq in HP.\n        destruct n;\n          [symmetry in HP; apply Permutation_nil in HP; inversion HP|cbn in HP].\n        apply (in_seq n 1 x).\n        eapply Permutation_in; [eapply Permutation_cons_inv; apply HP|easy].\n      }\n      destruct (lt_dec 0 x); omega.\n    Qed.\n\n    Theorem rem_PermFun_NoDup : forall p i,\n        NoDup p -> ~ In i p -> NoDup (rem_PermFun i p).\n    Proof.\n      intros p i ND.\n      induction ND; intros NIn; [constructor|].\n      cbn. destruct (lt_dec i x) as [HLt | HGe].\n      - rewrite not_in_cons in NIn.\n        destruct NIn as [HNeq Nin].\n        apply NoDup_cons; [|apply IHND; apply Nin].\n        unfold rem_PermFun. rewrite in_map_iff.\n        destruct x; [omega|cbn in *].\n        intros [y [Hy HIn]].\n        destruct (lt_dec i y).\n        + destruct y; [omega|cbn in *].\n          subst. contradiction.\n        + subst.\n          assert (i = x) by omega; subst.\n          contradiction.\n      - rewrite not_in_cons in NIn.\n        destruct NIn as [HNeq Nin].\n        apply NoDup_cons; [|apply IHND; apply Nin].\n        unfold rem_PermFun. rewrite in_map_iff.\n        intros [y [Hy HIn]].\n        destruct (lt_dec i y).\n        + destruct y; [omega|cbn in *].\n          subst. omega.\n        + subst. contradiction.\n    Qed.\n\n    Theorem rem_PermFun_preserve : forall p i n,\n        PermFun (S n) (i :: p) ->\n        PermFun n (rem_PermFun i p).\n    Proof.\n      intros p i n Hp.\n      rewrite PermFun_Permutation_seq.\n      pose proof (proj1 (PermFun_Permutation_seq (S n) (i :: p)) Hp) as P.\n      apply NoDup_Permutation; [|apply seq_NoDup|].\n      - symmetry in P; apply Permutation_NoDup in P; [|apply seq_NoDup].\n        apply NoDup_cons_iff in P.\n        apply rem_PermFun_NoDup; easy.\n      - intro x; split; intros HIn.\n        + apply in_seq; split; [omega|cbn].\n          unfold rem_PermFun in HIn.\n          apply in_map_iff in HIn.\n          destruct HIn as [y [Hy HIn]].\n          assert (y < S n)\n            by (apply PermFun_range with (p := i :: p); [|right]; easy).\n          assert (i < S n)\n            by (apply PermFun_range with (p := i :: p); [|left]; easy).\n          assert (y <> i). {\n            intro c; subst. clear -HIn P.\n            symmetry in P; apply Permutation_NoDup in P; [|apply seq_NoDup].\n            apply NoDup_cons_iff in P.\n            destruct P; contradiction.\n          }\n          destruct (Nat.eq_dec y n); [subst; rewrite if_true; omega|].\n          destruct (lt_dec i y); omega.\n        + unfold rem_PermFun; rewrite in_map_iff.\n          destruct (Nat.eq_dec i n). {\n            subst. apply seq_last_perm in P.\n            exists x. rewrite if_false by (apply in_seq in HIn; omega).\n            split; [easy|].\n            eapply Permutation_in; [symmetry; apply P|easy..].\n          }\n          destruct (le_lt_dec i x).\n          * exists (S x).\n            rewrite if_true by omega.\n            split; [easy|].\n            eapply or_ind with (A := i = S x); [omega|intro H; exact H|].\n            eapply Permutation_in with (l' := i :: p);\n              [symmetry; apply P|].\n            apply in_seq in HIn.\n            apply in_seq. omega.\n          * exists x.\n            rewrite if_false by omega.\n            split; [easy|].\n            assert (x < n) by (apply in_seq in HIn; easy).\n            eapply or_ind with (A := i = x); [omega|intro R; exact R|].\n            eapply Permutation_in with (l' := i :: p);\n              [symmetry; apply P|].\n            apply in_seq in HIn.\n            apply in_seq. omega.\n    Qed.\n\n    Theorem rem_PermFun_correct : forall l i p d,\n        PermFun (length l) (i::p) ->\n        apply (i::p) l = nth i l d :: apply (rem_PermFun i p) (rem_nth i l).\n    Proof.\n      intros.\n      assert (length l > 0). {\n        apply PermFun_length in H.\n        cbn in H. destruct l; cbn in *; omega.\n      }\n      assert (~ In i p) by (apply NoDup_cons_iff; apply H).\n      rewrite apply_def with (d := d) by easy.\n      cbn [map]. f_equal.\n      rewrite apply_def with (d := d)\n        by (apply rem_PermFun_preserve;\n            rewrite rem_nth_length\n              by (apply PermFun_range with (p := i :: p); [easy|left; easy]);\n            rewrite <- S_pred_pos by omega;\n            easy).\n      unfold rem_PermFun. rewrite map_map.\n      apply map_ext_in.\n      intros j HIn.\n      assert (i <> j) by (intro c; subst; contradiction).\n      destruct (lt_dec i j).\n      - rewrite nth_ge_rem_nth by omega.\n        destruct j; easy.\n      - assert (i > j) by omega. rewrite nth_lt_rem_nth by easy; easy.\n    Qed.\n  End RemPermFun.\n\n  Theorem apply_correct : forall p l,\n      PermFun (length l) p -> Permutation (apply p l) l.\n  Proof.\n    intros p l.\n    remember (length l) as n.\n    revert p l Heqn.\n    induction n as [|n IH]; intros p l HN HP.\n    - symmetry in HN; apply length_zero_iff_nil in HN; subst.\n      apply PermFun_0 in HP; subst.\n      reflexivity.\n    - destruct l as [|a l]; [inversion HN|].\n      destruct p as [|i p]; [apply PermFun_S_nil in HP; contradiction|].\n    rewrite rem_PermFun_correct with (d := a) by (rewrite <- HN; easy).\n    assert (i < length (a :: l))\n      by (apply PermFun_range with (p := i :: p); [rewrite <- HN|left]; easy).\n    etransitivity;\n      [apply perm_skip|symmetry; apply rem_nth_Perm; easy].\n    apply IH; [|apply rem_PermFun_preserve; easy].\n    rewrite rem_nth_length by easy. cbn in *; omega.\n  Qed.\n\n  Theorem apply_length : forall p l,\n      PermFun (length l) p -> length (apply p l) = length l.\n  Proof.\n    intros.\n    destruct l as [|d t] eqn:HL; [easy|rewrite <- HL in *; clear HL t].\n    rewrite apply_def with (d := d) by easy.\n    apply PermFun_length in H.\n    rewrite map_length. easy.\n  Qed.\n\n  Theorem apply_map : forall p l f,\n      PermFun (length l) p ->\n      apply p (map f l) = map f (apply p l).\n  Proof.\n    intros p l f Hp.\n    destruct l as [|d t] eqn:HL; [easy|]; rewrite <- HL in *; clear t HL.\n    rewrite !apply_def with (d := d) by (rewrite ?map_length; easy).\n    rewrite map_map.\n    apply map_ext_in.\n    intros x Hx.\n    rewrite nth_indep with (d' := f d)\n      by (rewrite map_length; eapply PermFun_range; [apply Hp|apply Hx]).\n    rewrite map_nth. easy.\n  Qed.\nEnd Apply.\n\nSection Compose.\n  Implicit Types (p : list nat).\n\n  Definition compose p2 p1 := apply p2 p1.\n\n  Remark compose_length : forall n p1 p2,\n      PermFun n p1 -> PermFun n p2 -> length (compose p1 p2) = n.\n  Proof.\n    intros n p1 p2 HP1 HP2.\n    apply PermFun_length in HP2; subst.\n    apply apply_length. easy.\n  Qed.\n\n  Remark compose_preserve : forall n p1 p2,\n      PermFun n p1 -> PermFun n p2 ->\n      PermFun n (compose p1 p2).\n  Proof.\n    intros n p1 p2 HP1 HP2.\n    apply PermFun_Permutation_seq.\n    transitivity p2; [|apply PermFun_Permutation_seq; easy].\n    apply apply_correct.\n    erewrite PermFun_length by apply HP2.\n    easy.\n  Qed.\n\n  Theorem compose_id_l : forall p n,\n      PermFun n p ->\n      compose (seq 0 n) p = p.\n  Proof.\n    intros p n HP.\n    apply PermFun_length in HP. subst.\n    apply apply_id.\n  Qed.\n\n  Theorem compose_id_r : forall p n,\n      PermFun n p ->\n      compose p (seq 0 n) = p.\n  Proof.\n    intros p n HP.\n    rewrite apply_def with (d := 0) by (rewrite seq_length; easy).\n    rewrite <- map_id.\n    apply map_ext_in.\n    intros a HIn.\n    apply seq_nth.\n    eapply PermFun_range; [apply HP|easy].\n  Qed.\n\n  Theorem apply_combine {A B} : forall n p (l : list A) (r : list B),\n      PermFun n p -> length l = n -> length r = n ->\n      apply p (combine l r) = combine (apply p l) (apply p r).\n  Proof.\n    induction n; intros p l r HP HL HR.\n    - apply PermFun_0 in HP.\n      apply length_zero_iff_nil in HL.\n      apply length_zero_iff_nil in HR.\n      subst. reflexivity.\n    - destruct p as [|i p]; [apply PermFun_S_nil in HP; contradiction|].\n      destruct l as [|xl l]; [inversion HL|].\n      destruct r as [|xr r]; [inversion HR|].\n      rewrite rem_PermFun_correct with (d := (xl, xr))\n        by (rewrite combine_length, HL, HR, Nat.min_id; easy).\n      rewrite rem_PermFun_correct with (d := xl) by (rewrite HL; easy).\n      rewrite rem_PermFun_correct with (d := xr) by (rewrite HR; easy).\n      cbn [combine]; rewrite <- combine_nth by (rewrite HL, HR; easy).\n      f_equal.\n      rewrite <- IHn;\n        [|apply rem_PermFun_preserve; easy|rewrite rem_nth_length; rewrite ?HL, ?HR..];\n        [|easy| |easy|];\n        [|apply PermFun_range with (p := i :: p); [|left]; easy..].\n      rewrite <- rem_nth_combine; cbn [combine].\n      reflexivity.\n  Qed.\n\n  Theorem compose_apply {A} : forall p1 p2 (l : list A),\n      PermFun (length l) p1 -> PermFun (length l) p2 ->\n      apply (compose p2 p1) l = apply p2 (apply p1 l).\n  Proof.\n    intros p1 p2 l HP1 HP2.\n    destruct l as [|d t] eqn:HL; [easy|rewrite <- HL in *; clear t HL].\n    remember (seq 0 (length l)) as I.\n    remember (@combine nat A I l) as Z.\n    assert (L: length Z = length l). {\n      rewrite HeqZ, combine_length, HeqI, seq_length, Nat.min_id.\n      easy.\n    }\n    assert (L1 : length p1 = length l) by (apply PermFun_length; easy).\n    assert (L2 : length p2 = length l) by (apply PermFun_length; easy).\n    assert (P1 : Permutation (apply p2 (apply p1 Z)) Z). {\n      rewrite apply_correct; [|rewrite apply_length; rewrite L; easy].\n      rewrite apply_correct; [reflexivity|rewrite L; easy].\n    }\n    assert (P2 : Permutation (apply (compose p2 p1) Z) Z). {\n      rewrite apply_correct; [reflexivity|].\n      rewrite L.\n      apply compose_preserve; easy.\n    }\n    symmetry in P2; pose proof (Permutation_trans P1 P2) as P; clear P1 P2.\n    rewrite HeqZ in P.\n    rewrite !apply_combine with (n := length l) in P\n      by (repeat (rewrite ?apply_length, ?L1,\n                  ?HeqI, ?seq_length || apply compose_preserve); easy || omega).\n    rewrite HeqI, !compose_id_r in P;\n      [|apply compose_preserve|]; [|easy..].\n    symmetry.\n    apply (Permutation_combine_eq _ _ _ P);\n      [repeat (rewrite ?apply_length, ?L1 || apply compose_preserve); easy..|].\n    apply (compose_preserve (length l)); easy.\n  Qed.\nEnd Compose.\n\nSection PermutationEx.\n  Context {A : Type}.\n\n  Implicit Type l : list A.\n\n  Definition PermutationEx l l' : Prop :=\n    exists p, PermFun (length l) p /\\ apply p l = l'.\n\n  Theorem PermutationEx_iff : forall l l',\n      Permutation l l' <-> PermutationEx l l'.\n  Proof.\n    split;\n      [|intros [p [Hp HA]]; subst; symmetry; apply apply_correct; easy].\n    intros HP; induction HP.\n    - exists []. split; [apply PermFun_0|]; easy.\n    - destruct IHHP as [p [Hp HA]].\n      exists (0 :: map S p). cbn [length apply]; split.\n      + apply PermFun_Permutation_seq.\n        cbn; apply perm_skip.\n        rewrite <- seq_shift.\n        apply Permutation_map.\n        apply PermFun_Permutation_seq; easy.\n      + cbn [map]. f_equal.\n        rewrite apply_def with (d := x) in HA by easy.\n        rewrite map_map. cbn. easy.\n    - exists (1 :: 0 :: map (fun x => S (S x)) (seq 0 (length l))).\n      split.\n      + apply PermFun_Permutation_seq. cbn [length seq].\n        rewrite <- map_map, !seq_shift.\n        apply perm_swap.\n      + cbn [apply map]; do 2 f_equal.\n        rewrite map_map. cbn [nth].\n        rewrite <- apply_def by (apply PermFun_Permutation_seq; reflexivity).\n        apply apply_id.\n    - destruct IHHP1 as [p1 [Hp1 HA1]].\n      destruct IHHP2 as [p2 [Hp2 HA2]].\n      assert (PermFun (length l) p2). {\n        rewrite <- HA1 in Hp2.\n        rewrite apply_length in Hp2 by easy.\n        easy.\n      }\n      exists (compose p2 p1).\n      split; [apply compose_preserve; easy|].\n      rewrite compose_apply by easy.\n      rewrite HA1, HA2.\n      easy.\n  Qed.\nEnd PermutationEx.\n\nSection Stable.\n  Context {A} `{EqDec A}.\n\n  Definition StablePermFun (l : list A) (p : list nat) :=\n    PermFun (length l) p /\\ forall i j d,\n      nth i (apply p l) d === nth j (apply p l) d ->\n      i < j < length l ->\n      image p i < image p j.\n\n  Definition StablePermFun_preimage (l : list A) (p : list nat) :=\n    PermFun (length l) p /\\ forall i j d,\n      nth i l d === nth j l d ->\n      i < j < length l ->\n      preimage p i < preimage p j.\n\n  Theorem StablePermFun_iff : forall l p,\n      StablePermFun l p <-> StablePermFun_preimage l p.\n  Proof.\n    intros; split; (intros [HP HS]; split; [easy|]); intros i j d HE HIJ.\n    - rewrite <- image_preimage with (i := i) (p := p) (n := length l) in HE\n        by (omega || easy).\n      rewrite <- image_preimage with (i := j) (p := p) (n := length l) in HE\n        by (omega || easy).\n      rewrite !nth_image_apply in HE by (try apply preimage_bound; omega || easy).\n      apply Nat.nle_gt. intro c.\n      destruct (le_lt_or_eq _ _ c) as [HLt|HEq];\n        [|apply preimage_inj with (n := length l) in HEq; [omega|easy..|omega]].\n      assert (c2 : ~ j < i) by omega. apply c2; clear c2.\n      rewrite <- image_preimage with (i := i) (n := length l) (p := p)\n        by (omega || easy).\n      rewrite <- image_preimage with (i := j) (n := length l) (p := p)\n        by (omega || easy).\n      apply HS with (d := d); [easy|].\n      split; [omega|].\n      apply preimage_bound; [easy|omega].\n    - rewrite <- preimage_image with (i := i) (p := p) (n := length l) in HE\n        by (omega || easy).\n      rewrite <- preimage_image with (i := j) (p := p) (n := length l) in HE\n        by (omega || easy).\n      rewrite !nth_preimage_apply in HE by (try apply image_bound; omega || easy).\n      apply Nat.nle_gt. intro c.\n      destruct (le_lt_or_eq _ _ c) as [HLt|HEq];\n        [|apply image_inj with (n := length l) in HEq; [omega|easy..|omega]].\n      assert (c2 : ~ j < i) by omega. apply c2; clear c2.\n      rewrite <- preimage_image with (i := i) (n := length l) (p := p)\n        by (omega || easy).\n      rewrite <- preimage_image with (i := j) (n := length l) (p := p)\n        by (omega || easy).\n      apply HS with (d := d); [easy|].\n      split; [omega|].\n      apply image_bound; [easy|omega].\n  Qed.\n\n  Definition StablePermEx l l' :=\n    exists p, StablePermFun l p /\\ apply p l = l'.\n\n  Theorem StablePermFun_nil : StablePermFun [] [].\n  Proof.\n    split; [apply PermFun_nil; easy|].\n    intros i j d HE HIJ.\n    cbn in HIJ. omega.\n  Qed.\n\n  Theorem StablePermFun_compose : forall p1 p2 l,\n      StablePermFun l p1 -> StablePermFun (apply p1 l) p2 ->\n      StablePermFun l (compose p2 p1).\n  Proof.\n    intros p1 p2 l [HP1 HS1] [HP2 HS2].\n    rewrite apply_length in HP2 by easy.\n    split; [apply compose_preserve; easy|].\n    intros i j d HE HIJ.\n    rewrite @apply_def with (d := 0)\n      by (apply PermFun_length in HP1; rewrite HP1; easy).\n    unfold image.\n    rewrite nth_indep with (n := i) (d' := nth 0 p1 0)\n      by (rewrite map_length; apply PermFun_length in HP2; omega).\n    rewrite nth_indep with (n := j) (d' := nth 0 p1 0)\n      by (rewrite map_length; apply PermFun_length in HP2; omega).\n    rewrite !map_nth with (f := fun x => nth x p1 0).\n    apply HS1 with (d := d).\n    - rewrite compose_apply in HE by easy.\n      rewrite @apply_def with (d := d) in HE\n        by (rewrite apply_length; easy).\n      rewrite nth_indep with (n := i) (d := d) (d' := nth j (apply p1 l) d) in HE\n        by (rewrite map_length; apply PermFun_length in HP2; omega).\n      rewrite !map_nth with (f := (fun i => nth i (apply p1 l) d)) in HE.\n      rewrite nth_indep with (n := j) (d := d) (d' := nth j (apply p1 l) d) in HE\n        by (rewrite map_length; apply PermFun_length in HP2; omega).\n      rewrite !map_nth with (f := (fun i => nth i (apply p1 l) d)) in HE.\n      rewrite !nth_indep with (d := 0) (d' := j)\n        by (apply PermFun_length in HP2; omega).\n      apply HE.\n    - split; [|apply PermFun_range with (p := p2);\n             [easy|apply nth_In; apply PermFun_length in HP2; omega]].\n      apply HS2 with (d := d);\n        [|rewrite apply_length; [omega|easy]].\n      rewrite <- compose_apply by easy. easy.\n  Qed.\n\n  Theorem preimage_lt_rem_perm : forall p j i n,\n      PermFun (S n) (i :: p) ->\n      j < i -> preimage (rem_PermFun i p) j = pred (preimage (i :: p) j).\n  Proof.\n    intros p j i n HP HIJ.\n    unfold preimage, rem_PermFun.\n    cbn. rewrite if_false by (intro c; unfold equiv in c; omega).\n    cbn.\n    match goal with\n    | |- context [findIndex ?j (map ?f ?l)] =>\n      rewrite <- (findIndex_map f p)\n    end; [|easy|fold (rem_PermFun i p)|].\n    rewrite if_false by omega.\n    easy.\n    eapply rem_PermFun_preserve; apply HP.\n    apply Exists_exists.\n    exists j; split; [|easy].\n    apply in_cons_neq with (y := i); [omega|].\n    eapply Permutation_in; [symmetry; apply PermFun_Permutation_seq; apply HP|].\n    apply in_seq.\n    split; [omega|].\n    transitivity i; [omega|].\n    eapply PermFun_range; [apply HP|left]; easy.\n  Qed.\n\n  Theorem preimage_ge_rem_perm : forall p j i n,\n      PermFun (S n) (i :: p) ->\n      i <= j < n -> preimage (rem_PermFun i p) j = pred (preimage (i :: p) (S j)).\n  Proof.\n    intros p j i n HP HIJ.\n    unfold preimage, rem_PermFun.\n    cbn [findIndex]. rewrite if_false by (intro c; unfold equiv in c; omega).\n    cbn.\n    match goal with\n    | |- context [findIndex ?j (map ?f ?l)] =>\n      rewrite <- (findIndex_map f p)\n    end; [|easy|fold (rem_PermFun i p)|].\n    rewrite if_true by omega.\n    easy.\n    eapply rem_PermFun_preserve; apply HP.\n    apply Exists_exists.\n    exists (S j); split; [|easy].\n    apply in_cons_neq with (y := i); [omega|].\n    eapply Permutation_in; [symmetry; apply PermFun_Permutation_seq; apply HP|].\n    apply in_seq. omega.\n  Qed.\n\n  Theorem rem_PermFun_preserve_Stable : forall p i l,\n      i < length l ->\n      StablePermFun l (i :: p) ->\n      StablePermFun (rem_nth i l) (rem_PermFun i p).\n  Proof.\n    setoid_rewrite StablePermFun_iff.\n    intros p k l HI [HP HS].\n    split; [apply rem_PermFun_preserve; rewrite rem_nth_length; destruct l; easy|].\n    intros i j d HE HIJ.\n    assert (IK : preimage (k :: p) k = 0) by (cbn; rewrite if_true; easy).\n    remember (length l) as n.\n    destruct n; [apply PermFun_length in HP; omega|].\n    rewrite rem_nth_length in HIJ by omega.\n    destruct (le_lt_dec k i); [|destruct (le_lt_dec k j)].\n    - assert (k <= j) by omega.\n      rewrite !preimage_ge_rem_perm with (n := n) by (omega || easy).\n      apply (Nat.pred_lt_mono (preimage (k :: p) (S i))).\n      rewrite <- IK.\n      intro c.\n      apply preimage_inj with (n := S n) in c; (omega || easy).\n      apply HS with (d := d); [|omega].\n      rewrite !nth_ge_rem_nth in HE by omega.\n      easy.\n    - rewrite preimage_ge_rem_perm with (j := j) (n := n) by (omega || easy).\n      rewrite preimage_lt_rem_perm with (j := i) (n := n) by (omega || easy).\n      apply (Nat.pred_lt_mono (preimage (k :: p) i)).\n      rewrite <- IK.\n      intro c.\n      apply preimage_inj with (n := S n) in c; (omega || easy).\n      apply HS with (d := d); [|omega].\n      rewrite @nth_ge_rem_nth with (j := j) in HE by omega.\n      rewrite @nth_lt_rem_nth with (j := i) in HE by omega.\n      easy.\n    - rewrite !preimage_lt_rem_perm with (n := n) by easy.\n      apply (Nat.pred_lt_mono (preimage (k :: p) i)).\n      rewrite <- IK.\n      intro c.\n      apply preimage_inj with (n := S n) in c; (omega || easy).\n      apply HS with (d := d); [|omega].\n      rewrite !nth_lt_rem_nth in HE by omega.\n      easy.\n  Qed.\n\n  Theorem StablePermEx_imp : forall l l',\n      StablePerm l l' -> StablePermEx l l'.\n  Proof.\n    intros l l' HS.\n    apply StablePermInd_iff in HS.\n    induction HS.\n    - exists []. split; [apply StablePermFun_nil|easy].\n    - destruct IHHS as [p [HSP HA]].\n      exists (0 :: map S p).\n      destruct HSP as [HP HSP].\n      split; [split|].\n      + apply PermFun_Permutation_seq. cbn. apply perm_skip.\n        rewrite <- seq_shift.\n        apply Permutation_map.\n        apply PermFun_Permutation_seq.\n        easy.\n      + intros i j d HE HIJ.\n        pose proof (PermFun_length _ _ HP); cbn in HIJ.\n        unfold image.\n        rewrite !nth_indep with (d := 0) (d' := 1)\n          by (cbn; rewrite map_length; omega).\n        destruct i; destruct j; [omega| |omega|].\n        * cbn [nth]. rewrite map_nth. omega.\n        * cbn. rewrite !map_nth.\n          apply lt_n_S.\n          apply HSP with (d := d); [|omega].\n          cbn [apply map] in HE.\n          rewrite map_map in HE.\n          cbn in HE.\n          rewrite @apply_def with (d := x); easy.\n      + cbn [apply map]; rewrite nth_first; cbn [hd].\n        f_equal. rewrite <- HA.\n        rewrite apply_def with (d := x) by easy.\n        rewrite map_map. apply map_ext.\n        easy.\n    - exists (1 :: 0 :: map (fun x => S (S x)) (seq 0 (length l))).\n      split; [split|].\n      + apply PermFun_Permutation_seq. cbn [length seq].\n        rewrite <- map_map, !seq_shift.\n        apply perm_swap.\n      + intros i j d HE HIJ.\n        destruct i; destruct j;\n          [omega|destruct j|omega|\n           destruct i; destruct j; [omega| |omega|]];\n          [exfalso; cbn in HE; contradiction\n          |cbn in *;\n           rewrite nth_indep with (d' := 2)\n             by (rewrite map_length, seq_length; omega);\n           rewrite map_nth with (d := 0);\n           omega..\n          |].\n        cbn.\n        rewrite !nth_indep with (d := 0) (d' := S (S 0))\n          by (rewrite map_length, seq_length; cbn in *; omega).\n        rewrite !map_nth with (d := 0).\n        do 2 apply lt_n_S.\n        rewrite !seq_nth by (cbn in *; omega).\n        omega.\n      + cbn [apply map]; rewrite nth_first; cbn [hd].\n        do 2 f_equal. rewrite <- map_seq_id with (d := y).\n        rewrite map_map. apply map_ext.\n        easy.\n    - destruct IHHS1 as [p1 [HSP1 HA1]].\n      destruct IHHS2 as [p2 [HSP2 HA2]].\n      exists (compose p2 p1).\n      split; [apply StablePermFun_compose;\n              [|rewrite <- HA1 in HSP2]; easy|].\n      rewrite compose_apply, HA1, HA2\n        by (destruct HSP1 as [HP1 _]; destruct HSP2 as [HP2 _];\n            rewrite <- HA1, apply_length in HP2 by easy; easy).\n      reflexivity.\n  Qed.\n\n  Theorem apply_correct_stable : forall p l,\n      StablePermFun l p -> StablePerm (apply p l) l.\n  Proof.\n    intros p l.\n    remember (length l) as n.\n    revert p l Heqn.\n    induction n as [|n IH]; intros p l HL [HP HS].\n    - symmetry in HL; apply length_zero_iff_nil in HL; subst.\n      apply PermFun_0 in HP; subst.\n      reflexivity.\n    - destruct l as [|a l]; [inversion HL|].\n      destruct p as [|i p]; [apply PermFun_S_nil in HP; contradiction|].\n      rewrite rem_PermFun_correct with (d := a) by easy.\n      assert (forall k, k < i -> nth i (a :: l) a =/= nth k (a::l) a). {\n        intros k HK.\n        assert (k < length (a :: l)). {\n          transitivity i; [easy|].\n          apply PermFun_range with (p := i :: p); [|left]; easy.\n        }\n        specialize (HS 0 (preimage (i::p) k) a).\n        rewrite nth_preimage_apply in HS by easy.\n        cbn [apply map] in HS; rewrite !nth_first in HS; cbn [hd] in HS.\n        rewrite image_preimage with (n := length (a :: l)) in HS by easy.\n        assert (L: 0 < preimage (i :: p) k < length (a :: l)). {\n          destruct (Nat.eq_dec (preimage (i :: p) k) 0).\n          - subst. unfold preimage in e.\n            apply f_equal with (f := fun x => nth x (i :: p) 0) in e.\n            rewrite findIndex_correct in e. cbn in e.\n            omega.\n            apply PermFun_i_exists with (n := length (a :: l)); [easy|].\n            transitivity i; [easy|].\n            apply PermFun_range with (p := i :: p); [|left]; easy.\n          - split; [omega|].\n            unfold preimage.\n            erewrite <- PermFun_length by apply HP.\n            apply findIndex_bounds.\n            apply PermFun_i_exists with (n := length (a :: l)); [easy|].\n            transitivity i; [easy|].\n            apply PermFun_range with (p := i :: p); [|left]; easy.\n        }\n        intro c.\n        specialize (HS c L).\n        cbn in HS.\n        omega.\n      }\n      transitivity (nth i (a :: l) a :: rem_nth i (a :: l)).\n      apply StablePerm_skip.\n      apply IH.\n      rewrite rem_nth_length;\n        [cbn in *; omega|eapply PermFun_range; [apply HP|left; easy]].\n      apply rem_PermFun_preserve_Stable;\n        [eapply PermFun_range; [apply HP|left; easy]|easy].\n      symmetry. apply rem_nth_StablePerm;\n                  [eapply PermFun_range; [apply HP|left; easy]|easy].\n  Qed.\n\n  Theorem StablePermEx_iff : forall l l',\n       StablePerm l l' <-> StablePermEx l l'.\n  Proof.\n    split.\n    - apply StablePermEx_imp.\n    - intros [p []].\n      subst l'.\n      symmetry; apply apply_correct_stable.\n      easy.\n  Qed.\nEnd Stable.\n", "meta": {"author": "jbaum98", "repo": "verified_bzip2", "sha": "d8ffd2e181f4951f588cce596b68fb2d0ebe7964", "save_path": "github-repos/coq/jbaum98-verified_bzip2", "path": "github-repos/coq/jbaum98-verified_bzip2/verified_bzip2-d8ffd2e181f4951f588cce596b68fb2d0ebe7964/theories/BWT/Sorting/PermFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7311899416885}}
{"text": "Require Import Equations.Equations.\nRequire Import Arith Lia.\n\n\n(** Formalized Solution for the following riddle *)\n\n(* You’re facing your friend, Caryn, in a “candy-off,” which works as follows: There’s a pile of 100 caramels and one peppermint patty. \nYou and Caryn will go back and forth taking at least one and no more than five caramels from the candy pile in each turn. The person \nwho removes the last caramel will also get the peppermint patty. And you love peppermint patties.\n\nSuppose Caryn lets you decide who goes first. Who should you choose in order to make sure you win the peppermint patty?\n\n*)\n\n\n(*** Preliminaries *)\n(*We need some facts about division with remainder *)\n\nDefinition iffT (X Y : Type) : Type := (X -> Y) * (Y -> X).\nNotation \"X <=> Y\" := (iffT X Y) (at level 95, no associativity).\n\n\nDefinition DIV y x :\n  sigT(fun a => sigT (fun b => x = a * y + b /\\ (0 < y -> b < y)  )).\nProof.\n  destruct y as [|y].\n  exists 0, x. repeat split. lia.\n  induction x as [|x IH].\n  - exists 0, 0. repeat split. tauto.\n  - destruct IH as (a&b&H).\n    destruct (Nat.eq_dec b y).\n    + exists (S a), 0. repeat split; lia.\n    + exists a, (S b). repeat split; lia.\nDefined.\n\n\n(* D y x gives the number of times y can be substracted from x *)\nDefinition D y x := projT1 (DIV y x).\n(* M y x gives the remainder of x after division by y *)\nDefinition M y x := projT1 (projT2 (DIV y x)).\n\n\nFact Factor y x : x = (D y x)*y + M y x.\nProof.\n  apply (projT2 (projT2 (DIV _ _))).\nQed.\n\nFact M_bound y x : 0 < y -> M y x < y.\nProof.\n  apply (projT2 (projT2 (DIV _ _))).\nQed.\n\n\nSection Uniqueness.\n\n  Variables y : nat.\n\n  Lemma Fac_unique a1 b1 a2 b2 : b1 < y -> b2 < y ->\n    a1*y + b1 = a2*y + b2 -> a1 = a2 /\\ b1 = b2.\n  Proof.\n    intros.\n    destruct (Nat.lt_trichotomy a1 a2) as [ |[]]; nia.\n  Qed.\n\n\n  Theorem unique x a b : b < y ->\n    x = a*y + b <-> a = D y x /\\ b = M y x.\n  Proof.\n    split.\n    - rewrite (Factor y x) at 1. intros.\n      specialize (M_bound y x) as ?.\n      apply Fac_unique; lia.\n    - intros [-> ->]. apply Factor.\n  Qed.\n\n  \n  Corollary Fac_eq a b : b < y ->\n      a = D y (a*y + b) /\\ b = M y (a*y + b).\n  Proof.\n    intros. now apply (unique _).\n  Qed.  \n\n\nEnd Uniqueness.\n\n\nLemma M_for_multiple : forall y x, M y x = 0 <=> { k & x = k*y }.\nProof.\n  split.\n  - intros H. exists (D y x). rewrite plus_n_O. rewrite <- H. apply Factor.\n  - intros [k ->]. destruct y. cbn. lia.\n    assert (0 < S y) as [? H]%(Fac_eq _ k) by lia. now rewrite <- plus_n_O in H. \nQed.\n\n\nLemma non_div y x z : 0 < x -> M y x = 0 -> 0 < z < y -> M y (x - z) <> 0.\nProof.\n  intros Hx [k ->]%M_for_multiple Hz [l Hl]%M_for_multiple. \n  apply Nat.lt_0_mul' in Hx. destruct Hx.\n  enough (k * y + 0 = l * y + z) as G%Fac_unique; destruct k; lia.\nQed.\n\n\nLemma complete_ind (P : nat -> Type) :\n  (forall x, (forall y, y < x -> P y) -> P x) -> forall x, P x.\nProof.\n  intros H x. apply H.\n  induction x.\n  - intros y. now intros F % PeanoNat.Nat.nlt_0_r. \n  - intros y Hy. apply H.\n    intros z Hz. apply IHx. lia.\nQed.\n\n\n\n\n\n(*** Riddle Solution *)\nSection Riddle.\n\n  (* The pile has *) Variable N : nat. (* patties in it *)\n  (* And there are two players *)\n  Inductive player := Caryn | Me.\n  (* Who must remove at least 1 and less than*) Variable t : nat. (* patties every turn. *)\n  \n  Definition switch p := match p with\n                         | Caryn => Me\n                         | Me => Caryn end.\n\n  \n  (* A player looks at how many patties there are left and removes 1,...,5 of them. So his choices can be modeled as a function with bounded output possibilities *)\n  Definition choice := { f : nat -> nat | forall k, 0 < f k < 6}.\n  Variable CarynChoice : choice.\n\n\n  (* This calculates the winner of the game given the choices c m, the starting height N of the stack and starting player p *)\n  Equations Game (N : nat) (p : player) (c m : choice) : player by wf N :=\n    Game O p c m := switch p;\n    Game N Caryn c m := Game (N - (proj1_sig c) N) Me c m;\n    Game N Me c m := Game (N - (proj1_sig m) N) Caryn c m.\n  Next Obligation.\n    destruct c as [f Hf]. cbn. destruct (f (S n)) eqn:Bot.\n    specialize (Hf (S n)). all : lia.\n  Defined.\n  Next Obligation.\n    destruct m as [f Hf]. cbn. destruct (f (S n)) eqn:Bot.\n    specialize (Hf (S n)). all : lia.\n  Defined.\n  \n  \n  (* This specifies my choice on every turn: I will always take a number of patties such that the height becomes divisible my 6 again. *)\n  Lemma MyChoice : choice.\n  Proof.\n    exists (fun k => if nat_eqdec (M 6 k) O then 1 else M 6 k).\n    intros k. destruct (nat_eqdec (M 6 k) O).\n    - lia.\n    - split. lia. apply M_bound. lia.\n  Defined.\n\n\n  \n  Definition myChoice := proj1_sig MyChoice.\n\n  Lemma MyChoiceSpec n : M 6 n <> 0 -> myChoice n = M 6 n.\n  Proof.\n    unfold myChoice. cbn. now destruct (nat_eqdec (M 6 n) O).\n  Qed.\n\n\n  (* This gives the winner of the game between me and Caryn *)\n  Definition Winner N First := Game N First CarynChoice MyChoice.\n\n  \n  Theorem WinChoice :\n    (M 6 N = 0 -> Winner N Caryn = Me) /\\ (M 6 N <> 0 -> Winner N Me = Me).    \n  Proof.\n    pattern N. revert N. apply complete_ind. intros N IH.\n    destruct (nat_eqdec (M 6 N) O) as [H|H].\n    - split. 2 : tauto. intros _.\n      destruct N. now simp Game.\n      specialize (proj2_sig CarynChoice (S n)) as Rules.\n      unfold Winner; simp Game. apply IH.\n      lia. apply non_div; lia.\n    - split. tauto. intros _. destruct N.\n      + cbn in H. congruence.\n      + unfold Winner. simp Game.\n        fold myChoice. rewrite (MyChoiceSpec _ H).\n        rewrite (Factor 6 (S n) ) at 1. rewrite Nat.add_sub. apply IH.\n        rewrite (Factor 6 (S n) ) at 2. lia.\n        rewrite (plus_n_O (_*_) ). symmetry. apply Fac_eq; lia.\n  Qed.\n\n  \n  (* From the above we immediately get that it is always possible to choose the starting player so that I can win  *)\n  Corollary Winable :\n    exists p : player, Winner N p = Me.\n  Proof.\n    destruct (nat_eqdec (M 6 N) O);\n    [exists Caryn | exists Me]; now apply WinChoice.\n  Qed.\n  \n  \nEnd Riddle.", "meta": {"author": "HermesMarc", "repo": "Coq_files", "sha": "1eea4f8c843f6ed43fca1c793c78b52ab9a45986", "save_path": "github-repos/coq/HermesMarc-Coq_files", "path": "github-repos/coq/HermesMarc-Coq_files/Coq_files-1eea4f8c843f6ed43fca1c793c78b52ab9a45986/patties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7311899377637673}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith List Permutation.\n\nRequire Import list_utils.\nRequire Import formula.\n\nSet Implicit Arguments.\n\n(** Hilbert rules for the implicational fragment of intuitionistic logic *)\n\nSection Hilbert.\n\n  Reserved Notation \"'|--' x\" (at level 70, no associativity).\n\n  (* Łukasiewicz axiom system for the positive implicational calculus *)\n   \n  Inductive HI_proof : Form -> Set :=\n    | in_HI_K  : forall A B,   |-- A %> B %> A\n    | in_HI_S  : forall A B C, |-- (A %> B %> C) %> (A %> B) %> (A %> C) \n    | in_HI_MP : forall A B,   |-- A %> B -> |-- A -> |-- B\n  where \"|-- A\" := (HI_proof A).\n  \n  (* This is the I combinator : W = S K K *)\n  \n  Fact HI_I A : |-- A %> A.\n  Proof.\n    exact (in_HI_MP (in_HI_MP (in_HI_S _ _ _) (in_HI_K _ _)) (in_HI_K _ A)).\n  Qed.\n  \n  (* This is the W combinator : W = S S (S K) *)\n  \n  Fact HI_W A B : |-- (A %> A %> B) %> (A %> B).\n  Proof.\n    exact (in_HI_MP (in_HI_MP (in_HI_S _ _ _) (in_HI_S _ _ _))\n                    (in_HI_MP (in_HI_S _ _ _) (in_HI_K _ _))).\n  Qed.\n  \n  (* This is the B combinator : B = S (K S) K *)\n  \n  Fact HI_B A B C : |-- (B %> C) %> (A %> B) %> A %> C.\n  Proof.\n    exact (in_HI_MP (in_HI_MP (in_HI_S _ _ _) \n                       (in_HI_MP (in_HI_K _ _) (in_HI_S _ _ _)))\n                    (in_HI_K _ _)).\n  Qed.\n  \n  Fact HI_KK A B C : |-- C %> A %> B %> A.\n  Proof.\n    apply in_HI_MP with (1 := in_HI_K _ _), in_HI_K.\n  Qed.\n\n  (* This is the C combinator : C = S (S (K B) S) (K K) *)\n  \n  Fact HI_C A B C : |-- (A %> B %> C) %> (B %> A %> C).\n  Proof.\n    exact (in_HI_MP \n             (in_HI_MP (in_HI_S _ _ _) \n                       (in_HI_MP (in_HI_MP (in_HI_S _ _ _) \n                                 (in_HI_MP (in_HI_K _ _) (HI_B _ _ _))) (in_HI_S _ _ _)))\n             (HI_KK _ _ _)).\n  Qed.\n\n  Fact HI_SI A B : |-- ((A %> B) %> A) %> (A %> B) %> B.\n  Proof.\n    apply in_HI_MP with (1 := in_HI_S _ _ _), HI_I.\n  Qed.\n  \n  Fact HI_KSI A B C : |-- C %> ((A %> B) %> A) %> (A %> B) %> B.\n  Proof.\n    apply in_HI_MP with (1 := in_HI_K _ _), HI_SI.\n  Qed.\n  \n  Fact HI_S_KSI A B : |-- (A %> (A %> B) %> A) %> A %> (A %> B) %> B.\n  Proof.\n    apply in_HI_MP with (1 := in_HI_S _ _ _), HI_KSI.\n  Qed.\n  \n  Fact HI_app A B : |-- A %> (A %> B) %> B.\n  Proof.\n    apply in_HI_MP with (1 := HI_S_KSI _ _), in_HI_K.\n  Qed.\n\n  (* Another proof *)\n  \n  Fact HI_cntr A B : |-- (A %> A %> B) %> (A %> B).\n  Proof.\n    apply in_HI_MP with (1 := in_HI_S A (A %> B) B), HI_app.\n  Qed.\n  \n  Fact HI_KS A B C D : |-- D %> (A %> B %> C) %> (A %> B) %> (A %> C).\n  Proof.\n    apply in_HI_MP with (1 := in_HI_K _ _), in_HI_S.\n  Qed.\n  \n  Fact HI_S_KS A B C D : |-- (D %> A %> B %> C) %> D %> (A %> B) %> A %> C.\n  Proof.\n    apply in_HI_MP with (1 := in_HI_S _ _ _), HI_KS.\n  Qed.\n  \n  Fact HI_tran A B C : |-- (A %> B) %> (B %> C) %> A %> C.\n  Proof.\n    apply in_HI_MP with (1 := HI_C _ _ _), HI_B.\n  Qed.\n  \n  Lemma HI_list_Form_to_Form_HI_proof l a b : \n      |-- a %> b -> |-- l %%> a -> |-- l %%> b.\n  Proof.\n    revert a b; induction l as [ | c l IHl ]; intros a b H1 H2.\n    apply in_HI_MP with (2 := H2), H1.\n    revert H2; simpl. \n    apply IHl, in_HI_MP with (2 := H1), HI_B.\n  Qed.\n  \n  Lemma HI_list_MP l a b : \n      |-- l%%> a %> b -> |-- l %%> a -> |-- l %%> b.\n  Proof.\n    revert a b; induction l as [ | x l IHl ]; intros a b.\n    apply in_HI_MP.\n    simpl; intros H; apply IHl.\n    revert H; apply HI_list_Form_to_Form_HI_proof, in_HI_S.\n  Qed.\n\n  (** This one needs Permutation_rect (decidability of @eq is required)\n      to compute an actual permutation from the knowledge that there\n      exists one *)\n  \n  Lemma HI_proof_perm l m a : l ~p m -> |-- l %%> a -> |-- m %%> a.\n  Proof.\n    intros H; revert a.\n    apply Permutation_rect with (1 := Form_eq_dec) (6 := H); \n      clear l m H; try (intros; simpl; auto; fail).\n      \n    intros ? ? ? ?; simpl; apply HI_list_Form_to_Form_HI_proof, HI_C.\n  Qed.\n  \n  Fact HI_proof_contract th a x : |-- (a::a::th) %%> x -> |-- (a::th) %%> x.\n  Proof. simpl; apply HI_list_Form_to_Form_HI_proof, HI_W. Qed.\n  \n  Fact HI_proof_weak th a x : |-- th %%> x -> |-- (a::th) %%> x.\n  Proof. simpl; apply HI_list_Form_to_Form_HI_proof, in_HI_K. Qed.\n  \n  Fact HI_proof_weakening th x : |-- x -> |-- th %%> x.\n  Proof.\n    intros; induction th as [ | a th IH ].\n    simpl; trivial.\n    apply HI_proof_weak; trivial.\n  Qed.\n  \n  (** This one needs list_contract_rect (decidability of @eq _ is required)\n      to compute an actual contraction sequence from the knowledge that there\n      exists one *)\n  \n  Lemma HI_proof_list_contract ga de x : \n          list_contract Form_eq_dec ga de -> |-- ga %%> x -> |-- de %%> x.\n  Proof.\n    intros H; revert x.\n    apply list_contract_one_rect with (eqX_dec := Form_eq_dec) \n                                      (4 := H); clear ga de H.\n    \n    intros ? ? ? ?; apply HI_proof_perm; auto.\n    intros ? ? ?; apply HI_proof_contract.\n    intros; auto.\n  Qed.\n\nEnd Hilbert.\n\n", "meta": {"author": "DmxLarchey", "repo": "Relevant-decidability", "sha": "6b1c4d48f734c4d440d9756630998d231b2cc02f", "save_path": "github-repos/coq/DmxLarchey-Relevant-decidability", "path": "github-repos/coq/DmxLarchey-Relevant-decidability/Relevant-decidability-6b1c4d48f734c4d440d9756630998d231b2cc02f/mini_HI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7311899283335168}}
{"text": "Require Import Coq.Arith.Minus.\n\n(** Redefinition of simple arithmetic *)\n\n(* The definitions already present in the standard library are very complicated and take ages to quote *)\n\nTheorem le_0_n : forall n, 0 <= n.\nProof.\n  intro n. induction n.\n  - apply le_n.\n  - apply le_S. exact IHn.\nQed.\n\nTheorem lt_0_succ : forall n, 0 < S n.\nProof.\n  intro n. induction n.\n  - now apply le_n.\n  - apply le_S. exact IHn.\nQed.\n\nTheorem pos_ge_0 : forall n, S n <= 0 -> False.\nProof.\n  intros n H. inversion H.\nQed.\n\nTheorem le_S_n : forall n m, S n <= S m -> n <= m.\nProof.\n  intros n m. revert n. induction m.\n  - intros n H. inversion H.\n    + apply le_n.\n    + apply pos_ge_0 in H1. destruct H1.\n  - intros n H. inversion H.\n    + apply le_n.\n    + apply IHm in H1. apply le_S. exact H1.\nQed.\n\nTheorem le_n_S : forall n m, n <= m -> S n <= S m.\nProof.\n  intros n m. revert n. induction m.\n  - intros n H. inversion H. apply le_n.\n  - intros n H. inversion H.\n    + apply le_n.\n    + apply le_S. now apply IHm.\nQed.\n\nTheorem add_0_r : forall n, n + 0 = n.\nProof.\n  intro n. induction n.\n  - reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem add_S : forall n m : nat, n + S m = S (n + m).\nProof.\n  intro n. induction n.\n  - intro m. reflexivity.\n  - intro m. simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem add_comm : forall n m : nat, n + m = m + n.\nProof.\n  intro n. induction n.\n  - intro m. rewrite (add_0_r m). reflexivity.\n  - intro m. simpl. rewrite IHn. rewrite add_S. reflexivity.\nQed.\n\nTheorem le_plus_n : forall n m p, p + n <= p + m -> n <= m.\nProof.\n  intros n m. induction p.\n  - intro H. exact H.\n  - intro H. simpl in H. apply le_S_n in H. exact (IHp H).\nQed.\n\nDefinition le_imp_eq_lt : forall n m : nat, n <= m -> (n = m) + (n < m).\n  intro n. induction n.\n  - intros m H. destruct m.\n    + left. reflexivity.\n    + right. apply lt_0_succ.\n  - intros m H. destruct m.\n    + apply pos_ge_0 in H. destruct H.\n    + destruct (IHn m).\n      * now apply le_S_n.\n      * rewrite e. left. reflexivity.\n      * right. now apply le_n_S.\nDefined.\n\nDefinition lt_eq_lt_dec :  forall n m : nat, {n < m} + {n = m} + {m < n}.\n  intros n m. induction m.\n  - assert (0 <= n). apply le_0_n. apply le_imp_eq_lt in H. destruct H.\n    + left. now right.\n    + now right.\n  - destruct IHm as [[H | H] | H].\n    + left. left. now apply le_S.\n    + rewrite H. left. left. now apply le_n.\n    + apply le_imp_eq_lt in H. destruct H.\n      * left. right. now rewrite e.\n      * right. exact l.\nDefined.\n\nDefinition le_lt_dec : forall n m : nat, {n <= m} + {m < n}.\n  intros n m. destruct (lt_eq_lt_dec n m) as [[H | H] | H].\n  - left. apply le_S_n. apply le_S. exact H.\n  - left. rewrite H. apply le_n.\n  - right. exact H.\nDefined.\n\nDefinition lt_eq_lt_dec' :  forall n m : nat, {n < m} + {n = m} + {m < n}.\n  intros n m. induction n.\n  - assert (0 <= m). apply le_0_n. apply le_imp_eq_lt in H. destruct H.\n    + left. now right.\n    + left. now left.\n  - destruct IHn as [[H | H] | H].\n    + apply le_imp_eq_lt in H. destruct H.\n      * left. right. exact e.\n      * left. left. exact l.\n    + rewrite H. right. now apply le_n.\n    + right. now apply le_S.\nDefined.\n\nDefinition lt_eq_eq_lt_dec (m n : nat) : {m < n} + {m = n} + {m = S n} + {m > S n}.\nProof.\n  destruct (lt_eq_lt_dec m n) as [[H | H] | H].\n  - left. left. now left.\n  - left. left. now right.\n  - apply le_imp_eq_lt in H. destruct H.\n    + left. now right.\n    + right. exact l.\nDefined.\n\nTheorem le_trans : forall n m p, n <= m -> m <= p -> n <= p.\nProof.\n  intros n m p. revert n m. induction p.\n  - destruct m.\n    + trivial.\n    + intros H H'. apply pos_ge_0 in H'. destruct H'.\n  - intros n m H. destruct m, n.\n    + intro H'. apply le_0_n.\n    + apply pos_ge_0 in H. destruct H.\n    + intro H'. apply le_0_n.\n    + intro H'. apply le_S_n in H. apply le_S_n in H'. apply le_n_S.\n      eapply IHp. apply H. exact H'.\nQed.\n\nTheorem sub_add_S {a b c : nat} : S b <= a -> a - S b + S c = a - b + c.\nProof.\n  revert c. induction b.\n  - intros c H. destruct a.\n    + inversion H.\n    + simpl. rewrite <- Minus.minus_n_O. apply add_S.\n  - intros c H. destruct a.\n    + inversion H.\n    + simpl. apply eq_add_S.\n      change (S (a - S b + S c)) with (S (a - S b) + S c). erewrite Minus.minus_Sn_m.\n      change (S (a - b + c)) with (S (a - b) + c). erewrite Minus.minus_Sn_m.\n      apply IHb.\n      * apply le_S_n. eapply le_trans. exact H. apply le_S. apply le_n.\n      * apply le_S_n. apply le_S_n. eapply le_trans. exact H. apply le_S. apply le_n.\n      * now apply le_S_n.\nQed.\n\nTheorem sub_sub {a b c : nat} : b <= a -> c <= b -> a - (b - c) = a - b + c.\nProof.\n  revert c. induction b.\n  - intros c Hb Hc. inversion Hc. easy.\n  - intros c Hb Hc. destruct c.\n    + simpl. easy.\n    + simpl. erewrite IHb.\n      * symmetry. apply sub_add_S. exact Hb.\n      * apply le_S_n. eapply le_trans. exact Hb. apply le_S. apply le_n.\n      * apply le_S_n. exact Hc.\nQed.", "meta": {"author": "loic-p", "repo": "cubical_forcing", "sha": "3c606c3e5f2cb85a397dc13851fc43ace816b4a1", "save_path": "github-repos/coq/loic-p-cubical_forcing", "path": "github-repos/coq/loic-p-cubical_forcing/cubical_forcing-3c606c3e5f2cb85a397dc13851fc43ace816b4a1/cubes/arith_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7311899240135877}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nLemma exists_pred x :\n  x > 0 ->\n  exists y, x = S y.\nProof.\n  case x => // n _. (* case: x と同じだが項が読みやすい*)\n    by exists n.\nQed.\nPrint exists_pred.\n(*\nexists_pred = \n  fun x : nat =>\n    match x as n return (0 < n -> exists y : nat, n = y.+1) with\n    | 0 =>\n        fun H : 0 < 0 =>\n        let H0 : False := eq_ind (0 < 0) (fun e : bool => if e then False else True) I true H in\n        False_ind (exists y : nat, 0 = y.+1) H0\n    | n.+1 =>\n        fun=> ex_intro (fun y : nat => n.+1 = y.+1) n (erefl n.+1)\n    end\n       : forall x : nat, 0 < x -> exists y : nat, x = y.+1\n*)\n\nRequire Extraction.\nExtraction exists_pred.                     (* 何も抽出されない*)\n\nPrint sig.\n(*\nInductive sig (A : Type) (P : A -> Prop) : Type :=\n  exist : forall x : A, P x -> {x : A | P x}\n*)\n\nDefinition safe_pred x :\n  x > 0 -> {y | x = S y}.\nProof.\n  case x => // n _.        (* exists_pred と同じ*)\n    by exists n. (* こちらもexists を使う*)\nDefined.         (* 定義を透明にし，計算に使えるようにする*)\n\nRequire Extraction.\nExtraction safe_pred.\n(*\nlet safe_pred = function\n                | O   -> assert false (* absurd case *)\n                | S n -> n\n*)\n(* 自己確認\nlet safe_pred = fun x ->\n                  match x with\n                  | O   -> assert false (* absurd case *)\n                  | S n -> n\nと同じことらしい。\n*)\n\nSection Sort.\n\n  Variables (A : Set) (le : A -> A -> bool).    (* データ型A とのその順序le *)\n  (* 既に整列されたリストl の中にa を挿入する*)\n  \n  Fixpoint insert a (l : list A) :=\n    match l with\n    | nil     => (a :: nil)\n    | b :: l' => if le a b\n                 then a :: l            (* a が l の先頭要素以下なら l の先頭にコンスする *)\n                 else b :: insert a l'  (* a が l の先頭要素より大なら l の残りに関数を再帰的に適用した結果に l の先頭要素をコンスする *)\n    end.\n  (* 自己確認ここから *)\n  (*\n    insert は、第1引数 a を、第2引数のリスト l に挿入する。\n    挿入する位置は、値が a 以上の要素の直前となる。\n  *)\n  (* 自己確認ここまで *)\n  \n  (* 繰り返しの挿入でリストl を整列する*)\n  Fixpoint isort (l : list A) : list A :=\n    match l with\n    | nil     => nil\n    | a :: l' => insert a (isort l')\n    end.\n  (* 自己確認ここから *)\n  (*\n    isort は、引数のリスト l が\n    空リストなら、何もしない。\n    空リストでないなら、l の先頭要素 a を l の残りのリスト l' を isort したリストに\n    insert を使って挿入する。\n    (insertion sort というものか？)\n  *)\n  (* 自己確認ここまで *)\n  \n  (* le は推移律と完全性をみたす*)\n  Hypothesis le_trans : (* 推移律 *)\n    forall x y z,\n      le x y ->\n      le y z ->\n      le x z.\n  Hypothesis le_total : (* 完全性 *)\n    forall x y,\n      ~~ le x y ->\n      le y x.\n  \n  (* le_list x l : x はあるリストl の全ての要素以下である*)\n  Inductive le_list x : list A -> Prop :=\n  | le_nil  : le_list x nil\n  | le_cons : forall y l,\n                le x y ->\n                le_list x l ->\n                le_list x (y::l).\n  (* 自己確認ここから *)\n  Check le_list\n        : A -> seq A -> Prop.\n  Check le_nil\n        : forall x : A,\n            le_list x [::].\n  Check le_cons\n        : forall (x y : A) (l : seq A),\n            le x y ->\n            le_list x l ->\n            le_list x (y :: l).\n  (* 自己確認ここまで *)\n  \n  (* sorted l : リストl は整列されている*)\n  Inductive sorted : list A -> Prop :=\n  | sorted_nil  : sorted nil\n  | sorted_cons : forall a l,\n                    le_list a l ->\n                    sorted l ->\n                    sorted (a::l).\n  (* 自己確認ここから *)\n  Check sorted\n        : seq A -> Prop.\n  Check sorted_nil\n        : sorted [::].\n  Check sorted_cons\n        : forall (a : A) (l : seq A),\n            le_list a l ->\n            sorted l ->\n            sorted (a :: l).\n  (* 自己確認ここまで *)\n\n  Hint Constructors le_list sorted.         (* auto の候補にする*)\n  \n  Lemma le_list_insert a b l :\n    le a b ->\n    le_list a l ->\n    le_list a (insert b l).\n  (*\n    要素 a が要素 b 以下であり、\n    要素 a がリスト l の全要素以下であるなら、\n    要素 a は、リスト l に要素 b を insert してできたリストの全要素以下である。\n  *)\n  Proof.\n    move=> leab.\n    (* 自己確認ここから *)\n    (*\n    Check le_list_ind\n          : forall (x : A) (P : seq A -> Prop),\n              P [::] -> (* 前提1 *)\n              (forall (y : A) (l : seq A), le x y -> le_list x l -> P l -> P (y :: l)) -> (* 前提2 *)\n              forall l : seq A, le_list x l -> P l. (* 結論 *)\n    Check insert : A -> seq A -> seq A.\n    Check insert b : seq A -> seq A.\n    Check insert b l : seq A.\n    Check le_list : A -> seq A -> Prop.\n    Check le_list a : seq A -> Prop.\n    Check le_list a (insert b l) : Prop.\n    Check (fun l => le_list a (insert b l)) : seq A -> Prop.\n    Check le_list_ind a (fun l => le_list a (insert b l))\n          : le_list a (insert b [::]) -> (* これが、le_list_ind の前提1に該当 *) (* ★1 *)\n            (forall (y : A) (l : seq A),\n               le a y ->\n               le_list a l ->\n               le_list a (insert b l) ->\n               le_list a (insert b (y :: l))) -> (* これば、le_list_ind の前提2に該当 *) (* ★2 *)\n            forall l : seq A,\n              le_list a l ->\n              le_list a (insert b l). (* これが、le_list_ind の結論に該当 *)\n    apply: (le_list_ind a (fun l => le_list a (insert b l))).\n    以下のelimは、上記のapplyと同じ意味\n    *)\n    (* 自己確認ここまで *)\n    elim.\n    - (* le_list_ind に渡した (fun l => le_list a (insert b l)) に空リストが渡された場合 *)\n      rewrite /=.\n      info_auto.\n      (*\n        (* info auto: *)\n        simple apply le_cons (in core).\n         assumption.\n         simple apply le_nil (in core).\n      *)\n    - (* le_list_ind に渡した (fun l => le_list a (insert b l)) に空リストでないリストが渡された場合 *)\n      move=> {l}. (* 詳細不明だが、コンテキストから l を削除しているように見える。 *)\n      move=> c l.\n      rewrite /=. (* これにより、ゴールの insert の定義が展開される模様(第2引数のリストは明らかに空リストではないことがわかる)。 *)\n      Check ifPn\n            : forall (A : Type) (b : bool) (vT vF : A),\n                if_spec b vT vF (~~ b) b (if b then vT else vF).\n      case: ifPn.\n      + info_auto.\n        (*\n          (* info auto: *)\n          intro.\n          intro.\n          intro.\n          intro.\n          simple apply le_cons (in core).\n           assumption.\n           simple apply le_cons (in core).\n            assumption.\n            assumption.\n        *)\n      + info_auto.\n        (*\n          (* info auto: *)\n          intro.\n          intro.\n          intro.\n          intro.\n          simple apply le_cons (in core).\n           assumption.\n           assumption.\n        *)\n    Restart.\n    move=> leab; elim => {l} [|c l] /=. info_auto.\n    case: ifPn. info_auto. info_auto.\n  Qed.\n\n  Lemma le_list_trans a b l :\n    le a b ->\n    le_list b l ->\n    le_list a l.\n  Proof.\n    move=> leab; elim. info_auto.\n    info_eauto using le_trans.              (* 推移律はeauto が必要*)\n  Qed.\n  \n  Hint Resolve le_list_insert le_list_trans. (* 補題も候補に加える*)\n\n  Theorem insert_ok a l :\n    sorted l ->\n    sorted (insert a l).\n  Proof.\n    (* 追加ここから *)\n    Check sorted_ind\n          : forall P : seq A -> Prop,\n              P [::] ->\n              (forall (a : A) (l : seq A),\n                 le_list a l ->\n                 sorted l ->\n                 P l ->\n                 P (a :: l)) ->\n              forall l : seq A,\n                sorted l ->\n                P l.\n    Check (fun l => sorted (insert a l)) : seq A -> Prop.\n    Check sorted_ind (fun l => sorted (insert a l))\n          : sorted (insert a [::]) -> (* ★1 *)\n            (forall (a0 : A) (l : seq A),\n               le_list a0 l ->\n               sorted l ->\n               sorted (insert a l) ->\n               sorted (insert a (a0 :: l))) -> (* ★2 *)\n            forall l : seq A,\n              sorted l ->\n              sorted (insert a l).\n    elim.\n    - (* ★1の場合 *)\n      rewrite /=.\n      by apply: sorted_cons.\n    - (* ★2の場合 *)\n      move=> a' l'.\n      rewrite /=.\n      case: ifPn.\n      + (* le a a' が true の場合 *)\n        info_eauto using le_trans.\n      + (* le a a' が false の場合 *)\n        info_eauto using le_trans.\n    Restart.\n    elim => /= {l} [| h l]. by apply: sorted_cons.\n    case: ifPn. info_eauto using le_trans. info_eauto using le_trans.\n    (* 追加ここまで *)\n  Qed.\n\n  Hint Resolve insert_ok.\n\n  Theorem isort_ok l :\n    sorted (isort l).\n  Proof.\n    (* 追加ここから *)\n    elim: l => //= a l IH.\n    by apply: insert_ok.\n    Restart.\n    elim: l => //= a l IH.\n    info_auto.\n    (*\n      (* info auto: *)\n      simple apply insert_ok (in core).\n       assumption.\n    *)\n    (* 追加ここまで *)\n  Qed.\n\n  Hint Resolve isort_ok.\n\n  (* Permutation l1 l2 : リストl2 はl1 の置換である*)\n  Inductive Permutation : list A -> list A -> Prop :=\n  | perm_nil   : Permutation nil nil\n  | perm_skip  : forall x l l',\n                   Permutation l l' ->\n                   Permutation (x::l) (x::l')\n  | perm_swap  : forall x y l,\n                   Permutation (y::x::l) (x::y::l)\n  | perm_trans : forall l l' l'',\n                   Permutation l l' ->\n                   Permutation l' l'' ->\n                   Permutation l l''.\n\n  Hint Constructors Permutation.\n  \n  Theorem Permutation_refl l :\n    Permutation l l.\n  Proof.\n    (* 追加ここから *)\n    elim: l => //= a l IH.\n    by apply: perm_skip.\n    Restart.\n    elim: l => //= a l IH.\n    info_auto.\n    (*\n      (* info auto: *)\n      simple apply perm_skip (in core).\n       assumption.\n    *)\n    (* 追加ここまで *)\n  Qed.\n\n  Hint Resolve Permutation_refl.\n\n  Theorem insert_perm l a :\n    Permutation (a :: l) (insert a l).\n  Proof.\n    (* 追加ここから *)\n    elim: l => /=; first apply: Permutation_refl.\n    move=> a' l' IH.\n    case: ifPn => Haa'; first apply: Permutation_refl.\n    apply: (perm_trans [:: a, a' & l'] [:: a', a & l'] (a' :: insert a l')); first apply: perm_swap.\n    by apply/perm_skip/IH.\n    Restart.\n    elim: l => //= a' l' IH.\n    case: ifPn => Haa'.\n    - info_auto.\n    - info_eauto using perm_trans.\n    (*\n      (* info eauto: *)\n      simple eapply perm_trans.\n       simple apply Permutation_refl.\n       simple eapply perm_trans.\n        simple apply Permutation_refl.\n        simple eapply perm_trans.\n         simple apply perm_swap.\n         simple apply perm_skip.\n          exact IH.\n    *)\n    (* 追加ここまで *)\n  Qed.\n\n  Hint Resolve insert_perm.\n\n  Theorem isort_perm l :\n    Permutation l (isort l).\n  Proof.\n    (* 追加ここから *)\n    elim: l => //= a l IH.\n    apply: (perm_trans (a :: l) (a :: isort l) (insert a (isort l))); last apply: insert_perm.\n    by apply/perm_skip/IH.\n    Restart.\n    elim: l => //= a l IH.\n    info_eauto using perm_trans.\n    (*\n      (* info eauto: *)\n      simple eapply perm_trans.\n       simple apply Permutation_refl.\n       simple eapply perm_trans.\n        simple apply Permutation_refl.\n        simple eapply perm_trans.\n         simple apply perm_skip.\n          exact IH.\n          simple apply insert_perm.\n    *)\n    (* 追加ここまで *)\n  Qed.\n  \n  (* 証明付き整列関数*)\n  Definition safe_isort l :\n    {l'|sorted l' /\\ Permutation l l'}.\n  Proof.\n    exists (isort l).\n    auto using isort_ok, isort_perm.\n  Defined.\n\n  Print safe_isort.\n\nEnd Sort.\n\nCheck safe_isort.           (* le と必要な補題を与えなければならない*)\n\nExtraction leq.             (* mathcomp のeqType の抽出が汚ない*)\n\nDefinition leq' m n :=\n  if m - n is 0\n  then true\n  else false.\n\nExtraction leq'.                            (* こちらはすっきりする*)\n(*\nlet leq' m n =\n  match subn m n with\n  | O   -> True\n  | S _ -> False\n*)\n\nLemma leq'E m n :\n  leq' m n = (m <= n).\nProof.\n  rewrite /leq' /leq.\n  by case: (m-n).\nQed.\n\nLemma leq'_trans m n p :\n  leq' m n ->\n  leq' n p ->\n  leq' m p.\nProof.\n  rewrite !leq'E; apply leq_trans.\nQed.\n\nLemma leq'_total m n :\n  ~~ leq' m n ->\n  leq' n m.\nProof.\n  (* 追加ここから *)\n  rewrite !leq'E -ltnNge [n <= m]leq_eqVlt => Hnltm.\n  by apply/orP; right.\n  (* 追加ここまで *)\nQed.\n\nDefinition isort_leq :=\n  safe_isort nat leq' leq'_trans leq'_total.\n\nEval compute in proj1_sig (isort_leq (3 :: 1 :: 2 :: 0 :: nil)).\n(* = [:: 0; 1; 2; 3] : seq nat *)\n\nExtraction \"isort.ml\" isort_leq.\n\nSection Sort'.\n\n  Variables (A : Set) (le : A -> A -> bool).    (* データ型A とのその順序le *)\n\n  Inductive All (P : A -> Prop) : list A -> Prop :=\n  | All_nil  : All P nil\n  | All_cons : forall y l,\n                 P y ->\n                 All P l ->\n                 All P (y::l).\n\n  (*\n  ``All (le a) l`` が ``le list a l`` と同じ意味になる．\n  こちらを使うように証明を修正せよ．\n   *)\n  \n  (* 追加ここから *)\n  Check All_nil\n        : forall P : A -> Prop,\n            All P [::].\n\n  Check All_cons\n        : forall (P : A -> Prop) (y : A) (l : seq A),\n            P y ->\n            All P l ->\n            All P (y :: l).\n\n  Hint Constructors All.\n\n  Check le : A -> A -> bool.\n  Check insert : forall A : Set, (A -> A -> bool) -> A -> seq A -> seq A.\n\n  Lemma le_list_insert' a b l :\n    le a b ->\n    All (le a) l ->\n    All (le a) (insert A le b l).\n  Proof.\n    Check All_ind\n          : forall (P : A -> Prop) (P0 : seq A -> Prop),\n              P0 [::] ->\n              (forall (y : A) (l : seq A),\n                 P y -> All P l -> P0 l -> P0 (y :: l)) ->\n              forall l : seq A,\n                All P l -> P0 l.\n    Check (fun x : A => le a x) : A -> bool.\n    Check (fun l : seq A => All (fun x : A => le a x) (insert A le b l)) : seq A -> Prop.\n    Check (All_ind (fun x : A => le a x) (fun l : seq A => All (fun x : A => le a x) (insert A le b l)))\n          : All (fun x : A => le a x) (insert A le b [::]) -> (* ★1 *)\n            (forall (y : A) (l : seq A),\n               le a y ->\n               All (fun x : A => le a x) l ->\n               All (fun x : A => le a x) (insert A le b l) ->\n               All (fun x : A => le a x) (insert A le b (y :: l))) -> (* ★2 *)\n            forall l : seq A,\n              All (fun x : A => le a x) l ->\n              All (fun x : A => le a x) (insert A le b l).\n    move=> Hab.\n    elim => /=.\n    - (* ★1 *)\n      by apply: All_cons.\n    -  (* ★1 *)\n      move=> y l0.\n      case: ifPn.\n      + (* le b y = true *)\n        move=> Hby Hay H0 H1.\n        apply: All_cons; first done.\n        by apply: All_cons.\n      + (* le b y = false *)\n        move=> Hby Hay H0 H1.\n        by apply: All_cons.\n    Restart.\n    move=> Hab.\n    elim => /=.\n    - (* ★1 *)\n      info_auto.\n    -  (* ★1 *)\n      move=> y l0.\n      case: ifPn.\n      + (* le b y = true *)\n        info_auto.\n      + (* le b y = false *)\n        info_auto.\n  Qed.\n\n  (* le は推移律と完全性をみたす*)\n  Hypothesis le_trans : (* 推移律 *)\n    forall x y z,\n      le x y ->\n      le y z ->\n      le x z.\n  Hypothesis le_total : (* 完全性 *)\n    forall x y,\n      ~~ le x y ->\n      le y x.\n\n  Lemma le_list_trans' a b l :\n    le a b ->\n    All (le b) l ->\n    All (le a) l.\n  Proof.\n    move=> Hab.\n    elim => //=.\n    move=> y l0 Hby H0 H1.\n    apply: All_cons; last done.\n    by apply: (le_trans a b y).\n    Restart.\n    move=> Hab.\n    elim.\n    - info_auto.\n    - info_eauto using le_trans.\n  Qed.\n\n  Inductive sorted' : list A -> Prop :=\n  | sorted'_nil  : sorted' nil\n  | sorted'_cons : forall a l,\n                     All (le a) l ->\n                     sorted' l ->\n                     sorted' (a::l).\n\n  Hint Constructors sorted'.\n\n  Hint Resolve le_list_insert' le_list_trans'.\n\n  Theorem insert_ok' a l :\n    sorted' l ->\n    sorted' (insert A le a l).\n  Proof.\n    elim => /=.\n    - (* ★1の場合 *)\n      by apply: sorted'_cons.\n    - (* ★2の場合 *)\n      move=> a' l' H0 H1 H2.\n      case: ifPn => Haa'.\n      + (* le a a' が true の場合 *)\n        apply: sorted'_cons.\n        * (* All (le a) (a' :: l') の証明 *)\n          apply: All_cons; first done.\n          by apply: (le_list_trans' a a' l').\n        * (* sorted' (a' :: l') の証明 *)\n          by apply: sorted'_cons.\n      + (* le a a' が false の場合 *)\n        apply: sorted'_cons; last done.\n        apply: (le_list_insert' a' a l'); last done.\n        by apply: (le_total a a').\n    Restart.\n    elim => /=.\n    - (* ★1の場合 *)\n      info_auto.\n    - (* ★2の場合 *)\n      move=> a' l'.\n      case: ifPn.\n      + (* le a a' が true の場合 *)\n        info_eauto using le_trans.\n      + (* le a a' が false の場合 *)\n        info_eauto using le_trans.\n  Qed.\n\n  Hint Resolve insert_ok'.\n\n  Theorem isort_ok' l :\n    sorted' (isort A le l).\n  Proof.\n    elim: l => //= a l IH.\n    by apply: insert_ok'.\n    Restart.\n    elim: l => //= a l IH.\n    info_auto.\n  Qed.\n\n  (* Permutation の定義に変更は必要ない模様 *)\n\n  Hint Constructors Permutation.\n\n  Theorem Permutation_refl' l :\n    Permutation A l l.\n  Proof.\n    elim: l => /=; first apply: perm_nil.\n    move=> a l IH.\n    by apply: perm_skip.\n    Restart.\n    elim: l => /=.\n    - (* l が空リストの場合 *)\n      info_auto.\n    - (* l が空リストでない場合 *)\n      info_auto.\n  Qed.\n\n  Hint Resolve Permutation_refl'.\n\n  Theorem insert_perm' l a :\n    Permutation A (a :: l) (insert A le a l).\n  Proof.\n    elim: l => /=; first apply: Permutation_refl'.\n    move=> a' l' IH.\n    case: ifPn => Haa'; first apply: Permutation_refl'.\n    apply: (perm_trans A [:: a, a' & l'] [:: a', a & l'] (a' :: insert A le a l')); first apply: perm_swap.\n    by apply/perm_skip/IH.\n    Restart.\n    elim: l => /=.\n    - (* l が空リストの場合 *)\n      info_auto.\n    - (* l が空リストでない場合 *)\n      move=> a' l' IH.\n      case: ifPn => Haa'.\n      + (* le a a' の場合 *)\n        info_auto.\n      + (* ~~ le a a' の場合 *)\n        info_eauto using perm_trans.\n  Qed.\n\n  Hint Resolve insert_perm'.\n\n  Theorem isort_perm' l :\n    Permutation A l (isort A le l).\n  Proof.\n    elim: l => /=; first apply: perm_nil.\n    move=> a l IH.\n    apply: (perm_trans A (a :: l) (a :: isort A le l) (insert A le a (isort A le l))); last apply: insert_perm.\n    by apply/perm_skip/IH.\n    Restart.\n    elim: l.\n    - (* l が空リストの場合 *)\n      info_auto.\n    - (* l が空リストでない場合 *)\n      info_eauto using perm_trans.\n  Qed.\n  (* 追加ここまで *)\n\nEnd Sort'.\n\n(* Hintにするしないで証明が変わってくる。\n   できるだけHintを増やして、なるべくautoを使って証明する。 *)\n\n(* END *)\n", "meta": {"author": "wakaba2017", "repo": "ProofCafe", "sha": "f2dd32225e2a9ed38577621e228d0adc1e1cd0b5", "save_path": "github-repos/coq/wakaba2017-ProofCafe", "path": "github-repos/coq/wakaba2017-ProofCafe/ProofCafe-f2dd32225e2a9ed38577621e228d0adc1e1cd0b5/ssrcoq7-self_learning.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.8705972801594707, "lm_q1q2_score": 0.7310701048211623}}
{"text": "(* Examples.v *)\n\nRequire Import Maple.\nRequire Import Reals.\nOpen Scope R_scope.\n\nSection MapleExamples.\n\nVariable x y a b : R.\n\n(**** Tactic Simplify ****)\n\nLemma simp0 : x <> 0 -> x / x = 1.\nProof.\n  intros.\n  simplify (x / x).\n  reflexivity.\n  assumption.\nQed.\n\nLemma simp1 : 1 + x <> 0 -> (1 + x) / (1 + x) * (1 + y) - (1 + y) >= 0.\nProof.\n  intros.\n  simplify ((1 + x) / (1 + x)).\n  ring_simplify (1 * (1 + y) - (1 + y)).\n  unfold Rge in |- *; right; reflexivity.\n  assumption.\nQed.\n\nLemma simp2 :\n x <> 0 ->\n y <> 0 -> (x / y + y / x) * x * y - (x^2 + y^2) + 1 > 0.\nProof.\n  intros.\n  simplify ((x / y + y / x) * x * y - (x^2 + y^2) + 1).\n  prove_sup0.\n  split; assumption.\nQed.\n\nLemma simp3 : x + y <> 0 -> x / (x + y) + y / (x + y) = 1.\nProof.\n  intros.\n  simplify (x / (x + y) + y / (x + y)).\n  reflexivity.\n  assumption.\nQed.\n\n(**** Tactic Factor ****)\n\nLemma fact0 : a^2 + 2*a*b + b^2 = (a+b)^2.\nProof.\n  factor (a^2 + 2*a*b + b^2).\n  reflexivity.\nQed.\n\nLemma fact1 : a^2 - 2*a*b + b^2 = (a-b)^2.\nProof.\n  factor (a^2 - 2*a*b + b^2).\n  reflexivity.\nQed.\n\nLemma fact2 : a^2 - b^2 = (a-b) * (a+b).\nProof.\n  factor (a^2 - b^2).\n  reflexivity.\nQed.\n\nLemma fact3 : a^3 + 3*a^2*b + 3*a*b^2 + b^3 = (a+b)^3.\nProof.\n  factor (a^3 + 3*a^2*b + 3*a*b^2 + b^3).\n  reflexivity.\nQed.\n\n(**** Tactic Expand ****)\n\nLemma expd0 : (a+b)^2 = a^2 + 2*a*b + b^2.\nProof.\n  expand ((a + b)^2).\n  reflexivity.\nQed.\n\nLemma expd1 : (a-b)^2 = a^2 - 2*a*b + b^2.\nProof.\n  expand ((a-b)^2).\n  reflexivity.\nQed.\n\nLemma expd2 : (a-b) * (a+b) = a^2 - b^2.\nProof.\n  expand ((a-b) * (a+b)).\n  reflexivity.\nQed.\n\nLemma expd3 : (a+b)^3 = a^3 + 3*a^2*b + 3*a*b^2 + b^3.\nProof.\n  expand ((a+b)^3).\n  reflexivity.\nQed.\n\n(**** Tactic Normal ****)\n\nLemma norm0 : x <> 0 -> y <> 0 -> x / y + y / x = (x^2 + y^2) * / y * / x.\nProof.\n  intros.\n  normal (x / y + y / x).\n  reflexivity.\n  split; assumption.\nQed.\n\nLemma norm1 :\n x <> 0 ->\n x + 1 <> 0 ->\n / x + x / (x + 1) = (x + 1 + x^2) * / x * / (x + 1).\nProof.\n  intros.\n  normal (/ x + x / (x + 1)).\n  reflexivity.\n  split; assumption.\nQed.\n\nLemma norm2 :\n x - y <> 0 ->\n x * (x / (x-y)^2) - y * (y / (x-y)^2) = (x + y) / (x - y).\nProof.\n  intros H.\n  normal (x * (x / (x-y)^2) - y * (y / (x-y)^2)).\n  reflexivity.\n  assumption.\nQed.\n\nLemma norm3 :\n x - y <> 0 ->\n x + y <> 0 ->\n x^2 - y^2 <> 0 ->\n x / (x - y) + y / (x + y) + 2 * y * (y / (x^2 - y^2)) =\n (x + y) / (x - y).\nProof.\n  intros H H0 H1.\n  normal (x / (x - y) + y / (x + y) + 2 * y * (y / (x^2 - y^2))).\n  reflexivity.\n  repeat split; assumption.\nQed.\n\n(**** Eval <Maple Tactic> in ****)\n\nLemma eval_simp0 : x <> 0 -> y <> 0 -> x / x + y / y = 2.\nProof.\n  intros.\n  let t := eval simplify in (x / x + y / y) in\n  replace (x / x + y / y)%R with t.\n  reflexivity.\n  cbn; field; auto.\nQed.\n\nLemma eval_fact0 : x <> 0 -> y <> 0 -> x / x + x / y = (x + y) / y.\nProof.\n  intros.\n  let t := eval factor in (x / x + x / y) in\n  replace (x / x + x / y) with t.\n  rewrite Rplus_comm; reflexivity.\n  cbn; field; auto.\nQed.\n\nLemma eval_expd0 :\n (3 * x + 3) * (y - 5 / 3) = 3 * x * y + - (5 * x) + 3 * y + -5.\nProof.\n  intros.\n  let t := eval expand in ((3*x+3)*(y-5/3)) in\n  replace ((3*x+3)*(y-5/3)) with t.\n  reflexivity.\n  cbn; field.\nQed.\n\nLemma eval_norm0 : x <> 0 -> y <> 0 -> y / (x * y) + y / x = (1 + y) / x.\nProof.\n  intros.\n  let t := eval normal in (y / (x * y) + y / x) in\n  replace (y / (x * y) + y / x) with t.\n  unfold Rdiv in |- *; reflexivity.\n  cbn; field; auto.\nQed.\n\nDefinition def0 := Eval simplify in 1 / 1.\n\nDefinition def1 := Eval simplify in (x/y+y)*y.\n\nDefinition def2 := Eval factor in x*y+x.\n\nDefinition def3 := Eval factor in x*y-3*x+7*y-21.\n\nDefinition def4 := Eval expand in (x+y)*x.\n\nDefinition def5 := Eval expand in (x-7)*(y+4).\n\nDefinition def6 := Eval normal in /x+/y.\n\nDefinition def7 := Eval normal in x^2*y/(x+y)+y*x*y/(x+y).\n\nEnd MapleExamples.\n", "meta": {"author": "coq-contribs", "repo": "maple-mode", "sha": "88b1f43e9438cc06b8aceee41c2c510af8bd8e41", "save_path": "github-repos/coq/coq-contribs-maple-mode", "path": "github-repos/coq/coq-contribs-maple-mode/maple-mode-88b1f43e9438cc06b8aceee41c2c510af8bd8e41/Examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8397339676722394, "lm_q1q2_score": 0.7310700956257932}}
{"text": "Require Import Bool Arith String List CpdtTactics.\nOpen Scope string_scope.\n\nDefinition var := string.\n\nInductive binop := Plus | Times | Minus.\n\nInductive aexp : Type := \n| Const : nat -> aexp\n| Var : var -> aexp\n| Binop : aexp -> binop -> aexp -> aexp.\n\nInductive bexp : Type := \n| Tt : bexp\n| Ff : bexp\n| Eq : aexp -> aexp -> bexp\n| Lt : aexp -> aexp -> bexp\n| And : bexp -> bexp -> bexp\n| Or : bexp -> bexp -> bexp\n| Not : bexp -> bexp.\n\nInductive com : Type := \n| Skip : com\n| Assign : var -> aexp -> com\n| Rand : var -> com\n| Seq : com -> com -> com\n| If : bexp -> com -> com -> com\n| While : bexp -> com -> com.\n\nDefinition state := var -> nat.\n\nDefinition get (x:var) (s:state) : nat := s x.\n\nDefinition set (x:var) (n:nat) (s:state) : state := \n  fun y => \n    match string_dec x y with \n        | left H => n \n        | right H' => get y s\n    end.\n\nDefinition eval_binop (b:binop) : nat -> nat -> nat := \n  match b with \n    | Plus => plus\n    | Times => mult\n    | Minus => minus\n  end.\n\nFixpoint eval_aexp (e:aexp) (s:state) : nat := \n  match e with \n    | Const n => n\n    | Var x => get x s\n    | Binop e1 b e2 => (eval_binop b) (eval_aexp e1 s) (eval_aexp e2 s)\n  end.\n\n\n\nFixpoint eval_bexp (b:bexp) (s:state) : bool := \n  match b with \n    | Tt => true\n    | Ff => false\n    | Eq e1 e2 => Nat.eqb (eval_aexp e1 s) (eval_aexp e2 s)\n    | Lt e1 e2 => Nat.ltb (eval_aexp e1 s) (eval_aexp e2 s)\n    | And b1 b2 => eval_bexp b1 s && eval_bexp b2 s\n    | Or b1 b2 => eval_bexp b1 s || eval_bexp b2 s\n    | Not b => negb (eval_bexp b s)\n  end.\n\n(** thisis a partial function. data structure*)\nInductive eval_com : com -> state -> state -> Prop := \n| Eval_skip : forall s, eval_com Skip s s\n| Eval_assign : forall s x e, eval_com (Assign x e) s (set x (eval_aexp e s) s)\n| Eval_rand: forall s x n, eval_com (Rand x) s (set x n s)\n| Eval_seq : forall c1 s0 s1 c2 s2, \n               eval_com c1 s0 s1 -> eval_com c2 s1 s2 -> eval_com (Seq c1 c2) s0 s2\n| Eval_if_true : forall b c1 c2 s s',\n                   eval_bexp b s = true -> \n                   eval_com c1 s s' -> eval_com (If b c1 c2) s s'\n| Eval_if_false : forall b c1 c2 s s',\n                   eval_bexp b s = false -> \n                   eval_com c2 s s' -> eval_com (If b c1 c2) s s'\n| Eval_while_false : forall b c s, \n                       eval_bexp b s = false -> \n                       eval_com (While b c) s s\n| Eval_while_true : forall b c s1 s2 s3, \n                      eval_bexp b s1 = true -> \n                      eval_com c s1 s2 -> \n                      eval_com (While b c) s2 s3 -> \n                      eval_com (While b c) s1 s3.\n\n(** Notation \"âŸ¨ A , S âŸ© â‡“ T\" := (eval_com A S T) (at level 100). *)\n\n(* y := 1; x := 2; while 0 < x { y := y * 2; x := x - 1 } *)\nDefinition prog1 := \n  Seq (Assign \"y\" (Const 1))\n  (Seq (Assign \"x\" (Const 2))\n       (While (Lt (Const 0) (Var \"x\"))\n              (Seq (Assign \"y\" (Binop (Var \"y\") Times (Const 2)))\n                   (Assign \"x\" (Binop (Var \"x\") Minus (Const 1)))))).\nLtac myinv H:= inversion H; subst; simpl in *; clear H.\n\nTheorem prog1_prop: forall s1 s2, eval_com prog1 s1 s2 -> get \"x\" s2 =0.\nProof.\nunfold prog1; intros.\nLtac foo :=\nmatch goal with\n| [H: eval_com (Seq _ _) _ _ |- _] => myinv H\n| [H: eval_com (Assign _ _) _ _ |- _] => myinv H\nend.\n\nLtac bar :=\nmatch goal with\n| [H: eval_com (While _ _) _ _ |- _] => myinv H; try discriminate; repeat foo\nend.\nrepeat foo.\nbar.\nbar. compute in H1. clear H1. myinv H7; simpl in *.\n- compute . reflexivity.\n- compute in H2. compute in H1. discriminate.\nQed.\n\n\nTheorem seq_assoc : \n  forall c1 c2 c3 s1 s2, \n    eval_com (Seq (Seq c1 c2) c3) s1 s2 -> \n    eval_com (Seq c1 (Seq c2 c3)) s1 s2.\nProof.\nintros. repeat foo. apply Eval_seq with (s1:=s4).\n- assumption.\n- apply Eval_seq with (s1:=s3) ; assumption.\n\n(**\nAbhishek's proof\nintros. repeat foo. eauto using Eval_seq.\n*)\nQed.\n\n\n\nDefinition prog2 := While Tt Skip.\n\nLemma wtce: forall c s1 s2, \n    eval_com c s1 s2 -> c = prog2 -> False.\nProof.\n intros c s1 s2 H. unfold prog2.\n induction H; repeat (intros; try discriminate).\n- myinv H0. discriminate.\n- myinv H2. apply IHeval_com2. reflexivity.\nQed.\n\nLemma while_true_cant_eval: forall s1 s2, ~ eval_com prog2 s1 s2.\nProof.\n  unfold not, prog2. intros.\n  apply (wtce _ s1 s2 H eq_refl).\nQed.\n\n\nLtac myinj H := injection H ; intros ; subst ; clear H.\n\nLemma while_true_imp_false : forall c s1 s2, eval_com c s1 s2 -> \n                               forall b c', (forall s, eval_bexp b s = true) -> \n                                             c = While b c' -> False. \nProof.\n  intros c s1 s2 H. induction H; repeat (intros; try discriminate).\n  - intros. myinv H1. congruence.\n  - intros. apply IHeval_com2 with (b0:=b0)(c':=c'); assumption.\n\n(** greg's proof\n  Ltac foo' := \n  match goal with \n    | [ H : ?x _ _ = ?x _ _ |- _ ] => myinj H\n    | [ H : forall s, eval_bexp _ s = _,\n        H' : eval_bexp _ ?s0 = _ |- _] => \n      specialize (H s0) ; congruence\n    | [ H : forall b c, _ -> _ |- _ ] => eapply H ; eauto\n  end.\n\n  induction 1 ; intros ; try discriminate ; repeat foo'.\n*)\nQed.\n  \nLemma prog2_div : forall s1 s2, eval_com prog2 s1 s2 -> False.\n\n  Lemma prog2_div' : forall c s1 s2, eval_com c s1 s2 -> c = prog2 -> False.\n  Proof.\n    unfold prog2 ; induction 1; crush.\n  Qed.\n  Show.\n  intros. apply (prog2_div' _ _ _ H eq_refl).\nQed.\n\n(** A simple chained tactic *)\nLtac myinv' H := inversion H ; subst ; clear H ; simpl in *.\n\n(** This tactic applies when we have a hypothesis involving\n   eval_com of either a Seq or an Assign.  It inverts the\n   hypothesis, and performs substitution, simplifying things.\n*)\nLtac eval_inv := \n  match goal with \n    | [ H : eval_com (Seq _ _) _ _ |- _ ] => myinv H\n    | [ H : eval_com (Assign _ _) _ _ |- _ ] => myinv H\n  end.\n\n(** This tactic inverts an eval_com of a While, producing\n   two sub-goals.  It tries to eliminate one (or both) of the goals\n   through discrimination on the hypotheses.\n*)\nLtac eval_while_inv := \n  match goal with\n    | [ H : eval_com (While _ _) _ _ |- _ ] => myinv H ; try discriminate\n  end.\n\nTheorem prog1_prop' : forall s1 s2, eval_com prog1 s1 s2 -> get \"x\" s2 = 0.\nProof.\n  unfold prog1 ; intros.\n  repeat ((repeat eval_inv) ; eval_while_inv).\n  auto.\nQed.\n\nTheorem seq_assoc' : \n  forall c1 c2 c3 s1 s2, \n    eval_com (Seq (Seq c1 c2) c3) s1 s2 -> \n    eval_com (Seq c1 (Seq c2 c3)) s1 s2.\n  Lemma seq_assoc'' : \n    forall c s1 s2, \n      eval_com c s1 s2 -> \n      forall c1 c2 c3,\n        c = Seq (Seq c1 c2) c3 -> \n        eval_com (Seq c1 (Seq c2 c3)) s1 s2.\n  Proof.\n    (** Adds all of the eval_com constructors as hints for auto/crush *)\n    Hint Constructors eval_com.\n    induction 1 ; crush.\n    inversion H ; clear H ; subst ; \n    econstructor ; eauto.\n  Qed.\n\n  intros. eapply seq_assoc'' ; eauto.\nQed.\n\n(** Returns true when the variable x occurs as a subexpression of a *)\nFixpoint contains (x:var) (a:aexp) : bool := \n  match a with \n    | Const _ => false\n    | Var y => if string_dec x y then true else false\n    | Binop a1 _ a2 => contains x a1 || contains x a2\n  end.\n\nSearchAbout (or).\n(** Changing a variable x that doesn't occur in a doesn't effect the \n   value of a. *)\nLemma eval_exp_set : \n  forall s x n a,\n    contains x a = false -> \n    eval_aexp a (set x n s) = eval_aexp a s.\nProof.\n  induction a.\n  - intros. simpl. reflexivity.\n  - intros. simpl. myinv H. unfold set. unfold get. destruct (string_dec x v).\n   + discriminate.\n   + reflexivity.\n  - intros. myinv H. SearchAbout (_ || _ = false). \n    apply orb_false_elim in H1. destruct H1. apply IHa1 in H. rewrite H.\n    apply IHa2 in H0. rewrite H0. reflexivity.\n\n(** Greg'g Proof\ndestruct H1. eapply (or_introl ) in IHa1. destruct IHa1.\n    + Print or_intror . apply (or_intror (contains x a1 = contains x a1)).\n  induction a ; unfold set, get ; simpl ; unfold get ; crush.\n  destruct (string_dec x v) ; crush.\n  destruct (contains x a1) ; crush.\n*)\nQed.\n\n(** \nProblem Set 3\nIn class we saw a relational small-step semantics for IMP. \nAbhishek observed that the small-step semantics could be written\nas a function instead, since there is no recursion in the 'while' case.\nHowever, there is a loss of extensibility to some nondeterministic\n features like concurrency.) Are these semantics really equivalent?\nHere is the relational semantics we saw in class:\n\n*)\n\nInductive step_com : com -> state -> com -> state -> Prop := \n| Step_assign: forall s x e,\n       step_com (Assign x e) s\n                (Skip) (set x (eval_aexp e s) s)\n| Step_rand: forall s x n, step_com (Rand x) s (Skip) (set x n s)\n| Step_seqL: forall c1 c2 c1' s s', step_com c1 s c1' s' ->\n                step_com (Seq c1 c2) s (Seq c1' c2) s'\n| Step_seqR: forall c s, step_com (Seq Skip c) s c s\n| Step_if_true: forall b c1 c2 s, eval_bexp b s = true ->\n                 step_com (If b c1 c2) s c1 s\n| Step_if_false: forall b c1 c2 s, eval_bexp b s = false ->\n                 step_com (If b c1 c2) s c2 s\n| Step_while: forall b c s,\n                 step_com (While b c) s\n                          (If b (Seq c (While b c)) Skip) s.\n\nSearchAbout (Some ).\n(** Problem1: Give a definition of the same small-step semantics,\n as a function.\n*)\n\n(*Fixpoint  step_com_fn  (c: com) (s: state) : option (com * state) :=\n  match c with \n    | Skip => None\n    | Assign v a => Some (Skip, (set v (eval_aexp a s) s))\n    | Seq c1 c2 => match (step_com_fn c1 s) with \n                    | None => Some (c2, s) (** this is skip case*)\n                    | Some (c3, s1) => Some ((Seq c3 c2), s1)\n                   end\n    | If b c1 c2  => match eval_bexp b s with\n                        | true => Some (c1, s)\n                        | false => Some (c2, s)\n                       end\n    | While b c1 => Some ((If b (Seq c1 (While b c1)) Skip), s)\n   end.\n\n\n(** Prove that only Skip fails to step: *)\nLemma progress : forall c s, step_com_fn c s = None -> c = Skip.\nProof.\n  intro c.\n  induction c.\n(** ; intros; simpl in *; try( reflexivity); try (discriminate). *)\n  - intros. reflexivity. (**skip case*)\n  - intros. simpl in *. discriminate. (**Assign case*)\n  (**Seq case*)\n  - simpl in *. intros. destruct (step_com_fn c1 s) in H.\n    + destruct p. discriminate.\n    + discriminate.\n  - simpl in *. intros. destruct (eval_bexp b s) in H; discriminate.\n  - simpl in *. intros. remember ((eval_bexp b s)) as bb. \n      destruct bb. \n    + inversion H.\n    + discriminate.\nQed.\n\n\nLemma ss {A:Type} : forall (a b:A), Some a= Some b -> a =b.\nProof using.\n  intros. inversion H. reflexivity.\nQed.\n\n\n(** Prove that all steps in the functional semantics work in the\n   relational one.*) \nTheorem forward_sim : forall c s c' s', \n          step_com_fn c s = Some (c', s') -> step_com c s c' s'.\nProof.\n intro c. induction c.\n * intros. simpl in *. discriminate.\n * intros. simpl in *. myinv H. constructor.\n * intros. simpl in *. remember (step_com_fn c1 s) as ss.\n   destruct ss.\n  + destruct p. myinv H. constructor. apply IHc1. \n    symmetry in Heqss. assumption.\n  + inversion H. symmetry in Heqss. \n    apply progress in Heqss. subst. constructor.\n * intros. simpl in H. remember (eval_bexp b s) as bb.\n   destruct bb; myinv H; symmetry in Heqbb; constructor; apply Heqbb.\n * intros. simpl in H. Print step_com. remember (eval_bexp b s) as bb.\n   destruct bb.\n   + myinv H. symmetry in Heqbb. constructor.\n   + myinv H. constructor.\nQed.\n\n\nTheorem backward_sim : forall c s c' s', \n  step_com c s c' s' -> step_com_fn c s = Some (c', s').\nProof.\nintro c. induction c; intros; myinv H; try (reflexivity).\n* remember (step_com_fn c1 s) as stf. \n    destruct stf.\n    - destruct p. apply IHc1 in H5. \n      rewrite H5 in Heqstf. myinv Heqstf. reflexivity.\n    - symmetry in Heqstf. apply progress in Heqstf. \n      subst. myinv H5.\n* rewrite H6; reflexivity.\n* rewrite H6; reflexivity.\nQed.\n**)\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** We can commute assignments x:=ax; y:=ay  as long as the\n   variables don't overlap. *)\nLemma assign_comm : \n  forall x ax y ay s1 s2,\n    eval_com (Seq (Assign x ax) (Assign y ay)) s1 s2 -> \n    contains x ay = false -> \n    contains y ax = false -> \n    x <> y -> \n    forall s3, eval_com (Seq (Assign y ay) (Assign x ax)) s1 s3 -> s2 = s3.\n(*\n               forall z, get z s3 = get z s2.\n*)\nProof.\n  intros.\n  repeat eval_inv.\n  repeat unfold set, get.\n  apply functional_extensionality. intro z.\n  destruct (string_dec x z); destruct (string_dec y z); try congruence.\n  (**\n    Greg's proof\n    specialize (eval_exp_set s1 y (eval_aexp ay s1) ax H1).\n    unfold set. crush.\n    specialize (eval_exp_set s1 x (eval_aexp ax s1) ay H0).\n    unfold set. crush.\n  *)\n  - subst. pose proof (eval_exp_set s1 y (eval_aexp ay s1) ax H1). \n    rewrite <- H.\n    unfold set, get. reflexivity.\n  - subst. pose proof (eval_exp_set s1 x (eval_aexp ax s1) ay H0).\n    rewrite <- H. unfold set, get. reflexivity.\nQed.\n\n\nLemma assign_comm2 : \n  forall x ax y ay s1 s2,\n    eval_com (Seq (Assign x ax) (Assign y ay)) s1 s2 -> \n    contains x ay = false -> \n    contains y ax = false -> \n    x <> y -> \n    eval_com (Seq (Assign y ay) (Assign x ax)) s1 s2.\nProof.\n  intros.\n  remember (set x (eval_aexp ax (set y (eval_aexp ay s1) s1))\n                (set y (eval_aexp ay s1) s1)) as s3.\n  assert (eval_com (Seq (Assign y ay) (Assign x ax)) s1 s3).\n  rewrite Heqs3.\n  eauto.\n  specialize (assign_comm x ax y ay s1 s2 H H0 H1 H2 _ H3).\n  intro.\n  assert (s3 = s2).\n  Focus 2.\n  rewrite <- H5.\n  auto.\n  symmetry in H4. apply H4.\n  Qed.\n\nInductive steps_com : com -> state -> com -> state -> Prop :=\n| Steps_none : forall c s, steps_com c s c s\n| Steps_some : forall c s c' s' c'' s'', step_com c s c' s' ->\n                steps_com c' s' c'' s'' -> steps_com c s c'' s''.\n\nHint Constructors steps_com step_com eval_com.\nLemma concat_seq : forall c1 c2 s1 s2 s3,\n              steps_com c1 s1 Skip s2 ->\n               steps_com c2 s2 Skip s3 ->\n                steps_com (Seq c1 c2) s1 Skip s3.\nProof.\nintros c1 c2 s1 s2 s3.\nremember Skip as ss.\nintros p. induction p; subst; eauto.\nQed.\n\nTheorem big_to_small:\n  forall c s s',\n   eval_com c s s' -> steps_com c s Skip s'.\nProof.\nintros c s s1 H.\ninduction H; eauto.\n* eapply concat_seq; eauto.\n* pose proof (concat_seq c (While b c) s1 s2 s3 IHeval_com1 IHeval_com2 ).\n  apply (Steps_some (While b c) s1 (If b (Seq c (While b c)) Skip) s1 Skip s3); eauto.\n  (** - auto. (** apply  Step_while.**)\n  - eauto. pose proof (Step_if_true b (Seq c (While b c)) Skip s1 H). eauto. **)\nQed.\n\nLemma steps_com_skip: forall s1 s2, steps_com Skip s1 Skip s2 -> s1 = s2.\nProof.\nintros.\nmyinv H.\n- reflexivity.\n- myinv H0.\nQed.\n\n\nTheorem small_to_big:\n  forall c s s',\n   steps_com c s Skip s' -> eval_com c s s'.\nProof.\nintros. remember Skip as ss. induction H;subst;auto.\n  specialize (IHsteps_com (@eq_refl _ Skip)).\n  revert dependent s''.\n  induction H.\n  - intros. inversion IHsteps_com; auto.\n  - intros. inversion IHsteps_com; auto.\n  - intros. rename s'' into f. myinv IHsteps_com. myinv H0. \n    econstructor; [| apply H6].\n    apply IHstep_com; eauto.\n    apply  big_to_small. auto.\n  - intros.  \n    pose proof (Eval_skip s). econstructor.\n    + apply H.\n    + apply IHsteps_com.\n  - intros. auto.\n  - intros. auto.\n  - intros. myinv IHsteps_com; myinv H6; eauto.\nQed.\n\n\n", "meta": {"author": "gunjanaggarwal", "repo": "Coq-Class", "sha": "4b6437bea170279d6b7610ab2e8684c889b4250d", "save_path": "github-repos/coq/gunjanaggarwal-Coq-Class", "path": "github-repos/coq/gunjanaggarwal-Coq-Class/Coq-Class-4b6437bea170279d6b7610ab2e8684c889b4250d/lecture6_non_deterministic_imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7310700847493312}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) : natural :=\n  Succ (plus lf3 lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj122_coqofml_Ks1Gjb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7310184330102973}}
{"text": "Fixpoint even (n:nat) : bool :=\n  match n with\n  | O        => true\n  | S O      => false\n  | S (S n') => even n'\n  end.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  - reflexivity.\n  - reflexivity.  Qed.\n\nTheorem even_S : forall n : nat,\n  even (S n) = negb (even n).\nProof.\n  intros n.\n  induction n as [| n' IHn'].\n  - simpl. reflexivity.\n  - rewrite -> IHn'. simpl. rewrite -> negb_involutive. reflexivity.\nQed.", "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/even_S.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7310184308926886}}
{"text": "Require Import Relation_Definitions Setoid Omega.\nInductive mod_equiv : nat -> nat -> nat -> Prop :=\n  | mod_intro_same : forall m n, mod_equiv m n n\n  | mod_intro_plus_l : forall m n1 n2, mod_equiv m n1 n2 -> mod_equiv m (m + n1) n2\n  | mod_intro_plus_r : forall m n1 n2, mod_equiv m n1 n2 -> mod_equiv m n1 (m + n2).\n\n(* Analogous to the mathematical notation `x == y (mod z)` *)\nNotation \"x == y %% z\" := (mod_equiv z x y) (at level 70).\n\nNotation \"'x==x'\" := mod_intro_same.\nNotation \"'m+x==y'\" := mod_intro_plus_l.\nNotation \"'x==m+y'\" := mod_intro_plus_r.\n\nLemma silly : forall m n1 n2,  (m + n1) == n2 %% m -> n1 == n2 %% m.\nProof. \n  intros. remember (m + n1) as n'. induction H;subst;try constructor.\n  constructor. replace n1 with n0. auto. omega. apply IHmod_equiv. auto.\nQed.\n\nLemma mod_sym : forall m n1 n2, n1 == n2 %% m -> n2 == n1 %% m.\nProof.\n  intros. induction H;simpl;constructor;auto. Qed.\n\nLemma mod_trans : forall m n1 n2 n3, n1 == n2 %% m -> n2 == n3 %% m -> n1 == n3 %% m.\nProof. \n  intros. induction H. auto. \n  constructor. apply IHmod_equiv. auto.\n  apply silly in H0. apply IHmod_equiv. auto.\nQed.\n\nAdd Parametric Relation (m:nat) : nat (mod_equiv m)\n  reflexivity proved by (mod_intro_same m)\n  symmetry proved by (mod_sym m)\n  transitivity proved by (mod_trans m) as mod_equiv_rel.\n\nLemma plus_one_side : forall m n1 n2 n', n1 == n2 %% m -> n' + n1 == n' + n2 %% m.\nProof.\n  intros;induction H;try reflexivity;rewrite plus_assoc;rewrite (plus_comm n' m);\n  rewrite <- plus_assoc;constructor;auto.\nQed. \n\nAdd Parametric Morphism (m: nat) : plus\n  with signature (mod_equiv m) ==> (mod_equiv m) ==> (mod_equiv m) as plus_mor.\nProof.\n  intros. induction H;try (apply plus_one_side;auto);\n  try rewrite <- plus_assoc;constructor;apply IHmod_equiv;auto.\nQed.\n\nLemma mult_one_side : forall m n1 n2 n', n1 == n2 %% m -> n' * n1 == n' * n2 %% m.\nProof.\n  assert (H' : forall m n1 n2 p, n1 == n2 %% m -> (p * m + n1) == n2 %% m).\n  intros;induction p;auto;simpl. rewrite <- plus_assoc. constructor. auto.\n  intros;induction H;try reflexivity. rewrite Nat.mul_add_distr_l.\n  apply H'. auto. rewrite Nat.mul_add_distr_l. symmetry. apply H'. symmetry. auto.\nQed.\n\nAdd Parametric Morphism (m:nat) : mult\n  with signature (mod_equiv m) ==> (mod_equiv m) ==> (mod_equiv m) as mult_mor.\nProof.\n  assert (H' : forall m n1 n2 p, n1 == n2 %% m -> (p * m + n1) == n2 %% m).\n  intros;induction p;auto;simpl. rewrite <- plus_assoc. constructor. auto.\n  intros. induction H.\n  - apply mult_one_side. auto.\n  - rewrite Nat.mul_add_distr_r. rewrite mult_comm. apply H'. apply IHmod_equiv. auto.\n  - symmetry. rewrite Nat.mul_add_distr_r. rewrite mult_comm. apply H'. symmetry.\n    apply IHmod_equiv. auto.\nQed.", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/Generalized_Rewriting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7310177715540663}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nTheorem theorem0 : forall (x : Lst) (y : Lst) (z : Nat), eq (append (append x y) (cons z nil)) (append x (append y (cons z nil))).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal63.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7310177660716873}}
{"text": "Require Import Reals.\nRequire Import Lra.\nRequire Import Rtopology.\nRequire Import Rminmax.\nRequire Import Ensembles.\nLocal Open Scope R_scope.\n\nLtac rabs_delta F Heqdelt :=\n  unfold Rabs; destruct Rcase_abs;\n  unfold Rabs in F; destruct Rcase_abs in F;\n  unfold Rmin in Heqdelt; destruct Rle_dec in Heqdelt;\n  try lra.\n\n\nTheorem intersection_open_sets_is_open (A B : Ensemble R) :\n  open_set A -> open_set B -> open_set (Intersection R A B).\nProof.\n  intros H1 H2.\n  unfold open_set in *.\n  intros x G.\n  destruct G as [x G1 G2]; unfold In in *.\n  unfold included.\n  specialize (H1 x G1); destruct H1 as [[delt1 delt1pos] H1].\n  specialize (H2 x G2); destruct H2 as [[delt2 delt2pos] H2].\n  unfold included, disc, included in H1; simpl in H1.\n  unfold included, disc, included in H2; simpl in H2.\n  remember (Rmin delt1 delt2) as delt; assert (deltpos : delt > 0).\n  { rewrite Heqdelt.\n    compute; destruct Rle_dec.\n    - apply delt1pos.\n    - apply delt2pos.\n  }\n  exists (mkposreal delt deltpos).\n  unfold included, disc; intros x' F; simpl in F.\n\n  apply Intersection_intro; unfold In.\n  - apply H1; rabs_delta F Heqdelt.\n  - apply H2; rabs_delta F Heqdelt.\nQed.\n", "meta": {"author": "quinn-dougherty", "repo": "rca", "sha": "e5d5344e2880e80a3ac395772db7fc193566a63c", "save_path": "github-repos/coq/quinn-dougherty-rca", "path": "github-repos/coq/quinn-dougherty-rca/rca-e5d5344e2880e80a3ac395772db7fc193566a63c/with-standard-library/open.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7309876960873146}}
{"text": "(* Coq' Art *)\n\n\n(* A brief presentation of Coq *)\n\n\n(* A sorting example : \n   (C) Yves Bertot, Pierre Casteran \n*)\n\n\nRequire Import List.\nRequire Import ZArith.\nOpen Scope Z_scope.\n\n\n(* Sorted の公理 *)\nInductive sorted : list Z -> Prop :=\n  | sorted0 : sorted nil\n  | sorted1 : forall z:Z, sorted (z :: nil)\n  | sorted2 :\n      forall (z1 z2:Z) (l:list Z),\n        z1 <= z2 -> sorted (z2 :: l) -> sorted (z1 :: z2 :: l).\n\n\nHint Resolve sorted0 sorted1 sorted2 : sort.\n\n\nLemma sort_2357 :\n   sorted (2 :: 3 :: 5 :: 7 :: nil).\nProof.\n  auto with sort zarith.\nQed.\n\n\n(* Sortedの逆を証明する *)\n\n\nTheorem sorted_inv :\n  forall (z:Z) (l:list Z), sorted (z :: l) -> sorted l.\nProof.\n  intros z l H.\n  inversion H.                              (* sorted0とsorted1で分ける。 *)\n  apply sorted0.                            (* auto with sort. *)\n  apply H3.\nQed.\n\n\n(* 出現回数を数える関数 *)\n(* Number of occurrences of z in l *)\n\n\nFixpoint nb_occ (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%nat                            (* 0はZでなく、natであるとする。 *)\n  | (z' :: l') =>\n      match Z_eq_dec z z' with\n      | left _ => S (nb_occ z l')\n      | right _ => nb_occ z l'\n      end\n  end.\n\n\nEval compute in (nb_occ 3 (3 :: 7 :: 3 :: nil)). (* 2 *)\nEval compute in (nb_occ 36725 (3 :: 7 :: 3 :: nil)). (* 0 *)\n\n\n(* ふたつのリストが、そのすべての要素の出現回数が同じであるとき、equivという。*)\n(* list l' is a permutation of list l *)\n\n\nDefinition equiv (l l':list Z) := \n  forall z:Z, nb_occ z l = nb_occ z l'.\n\n\n(* equiv is an equivalence ! *)\n(* equiv についての定理を証明する。*)\n\n\nLemma equiv_refl : forall l:list Z, equiv l l.\nProof.\n  unfold equiv.\n  intros l z.                               (* trivial. *)\n  reflexivity.\nQed.\n\n\nLemma equiv_sym : forall l l':list Z, equiv l l' -> equiv l' l.\nProof.\n  unfold equiv.\n  intros.                                   (* auto. *)\n  rewrite H.\n  reflexivity.\nQed.\n\n\nLemma equiv_trans :\n  forall l l' l'' :\n  list Z, equiv l l' -> equiv l' l'' -> equiv l l''.\nProof.\n  intros l l' l'' H H0 z.\n  eapply trans_eq.\n  eauto.\n  eauto.\nQed.\n\n\nLemma equiv_cons :\n forall (z:Z) (l l':list Z), equiv l l' -> equiv (z :: l) (z :: l').\nProof.\n  intros z l l' H z'.\n  simpl.\n  case (Z_eq_dec z' z).\n  intros e.                                 (* auto *)\n  apply f_equal.\n  apply H.\n  \n  intros.\n  apply H.\nQed.\n\n\n\n\nLemma equiv_perm :\n  forall (a b:Z) (l l':list Z),\n    equiv l l' -> equiv (a :: b :: l) (b :: a :: l').\nProof.\n  intros a b l l' H z.\n  simpl.\n  case (Z_eq_dec z a).\n\n\n  intros.\n  case (Z_eq_dec z b).\n  intros.\n  case (H z).\n  auto.\n  auto.\n\n\n  intros.\n  case (Z_eq_dec z b).\n  intros.\n  auto.\n\n\n  auto.\nQed.\n\n\nHint Resolve equiv_cons equiv_refl equiv_perm : sort.\n\n\n(* インサート関数 *)\n\n\n(* insertion of z into l at the right place \n   (assuming l is sorted) \n*)\n\n\nFixpoint aux (z:Z) (l:list Z) {struct l} : list Z :=\n  match l with\n  | nil => z :: nil\n  | cons a l' =>\n      match Z_le_gt_dec z a with\n      | left _ =>  z :: a :: l'\n      | right _ => a :: (aux z l')\n      end\n  end.\n   \n\n\nEval compute in (aux 4 (2 :: 5 :: nil)).    (* 2 :: 4 :: 5 :: nil *)\nEval compute in (aux 4 (24 :: 50 ::nil)).   (* 4 :: 24 :: 50 :: nil *)\n\n\n(* the aux function seems to be a good tool for sorting ... *)\n\n\nLemma aux_equiv :\n  forall (l:list Z) (x:Z), equiv (x :: l) (aux x l).\nProof.\n  induction l as [ |a l H].                 (* as以降は省いてよい。 *)\n  simpl.\n  auto with sort.\n  intros x.\n  simpl.\n\n\n  case (Z_le_gt_dec x a).\n  simpl.\n  auto with sort.\n  \n  intro.\n  apply equiv_trans with (a :: x :: l).\n  auto with sort.\n  auto with sort.\nQed.\n\n\n\n\nLemma aux_sorted :\n  forall (l:list Z) (x:Z), sorted l -> sorted (aux x l).\nProof.\n  intros l x H.\n  elim H; simpl.                            (* elim H. simpl. ではうまくいかない。 *)\n  auto with sort.\n\n\n  intro z.\n  case (Z_le_gt_dec x z).\n  simpl.\n  auto with sort zarith.\n  auto with sort zarith.\n\n\n  intros z1 z2.\n  case (Z_le_gt_dec x z2).\n  \n  intros.\n  case (Z_le_gt_dec x z1).\n  auto with sort zarith.\n  auto with sort zarith.\n\n\n  intros.\n  case (Z_le_gt_dec x z1).\n  auto with sort zarith.\n  auto with sort zarith.\nQed.\n\n\n(* the sorting function *)\n\n\nDefinition sort :\n  forall l:list Z, {l' : list Z | equiv l l' /\\ sorted l'}.\n\n\n  induction l as [ | a l IHl].              (* as以降は省いてよい。 *)\n  exists (nil (A := Z)).\n  split.\n  auto with sort.\n  auto with sort.\n\n\n  case IHl.\n  intros l' [H0 H1].\n\n\n  exists (aux a l').\n  split.\n\n\n  apply equiv_trans with (a :: l').\n  auto with sort.\n  apply aux_equiv.\n  apply aux_sorted.\n  auto.\nDefined.\n\n\nEval compute in proj1_sig (sort (3::1::2::0::nil)).\n\n\nExtraction \"insert-sort\" aux sort.\n\n\n(* END *)", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/coqart_insersion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7309599332971783}}
{"text": "(** * Category **)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nGeneralizable All Variables.\n\nSet Primitive Projections.\nSet Universe Polymorphism.\n\nRequire Export COC.Base.Setoid.\n\nClass IsCategory\n      (obj: Type)\n      (hom: obj -> obj -> Setoid)\n      (comp: forall {X Y Z: obj}, hom X Y -> hom Y Z -> hom X Z)\n      (id: forall (X: obj), hom X X) :=\n  {\n    cat_comp_proper:>\n      forall (X Y Z: obj),\n        Proper ((==) ==> (==) ==> (==)) (@comp X Y Z);\n    \n    cat_comp_assoc:\n      forall X Y Z W (f: hom X Y)(g: hom Y Z)(h: hom Z W),\n        comp f (comp g h) == comp (comp f g) h;\n    \n    cat_comp_id_dom:\n      forall X Y (f: hom X Y),\n        comp (id X) f == f;\n    \n    cat_comp_id_cod:\n      forall X Y (f: hom X Y),\n        comp f (id Y) == f\n  }.\nHint Resolve cat_comp_assoc cat_comp_id_dom cat_comp_id_cod.\n\nStructure Category :=\n  {\n    cat_obj:> Type;\n    cat_hom:> cat_obj -> cat_obj -> Setoid;\n    cat_comp:\n      forall (X Y Z: cat_obj),\n        cat_hom X Y -> cat_hom Y Z -> cat_hom X Z;\n    cat_id: forall X: cat_obj, cat_hom X X;\n\n    cat_prf:> IsCategory cat_comp cat_id\n  }.\nExisting Instance cat_prf.\n\nNotation \"[ 'Category' 'by' hom 'with' comp , id ]\" :=\n  (@Build_Category _ hom comp id _).\nNotation \"[ 'Category' 'by' hom 'with' 'comp' := comp 'with' 'id' := id ]\" :=\n  [Category by hom with comp , id].\n\nNotation \"g \\o{ C } f\" := (@cat_comp C _ _ _ f g) (at level 60, right associativity).\nNotation \"g \\o f\" := (g \\o{_} f) (at level 60, right associativity) .\nNotation \"Id_{ C } X\" := (@cat_id C X) (at level 20, no associativity).\nNotation \"'Id' X\" := (Id_{_} X) (at level 30, right associativity).\n\nDefinition domain {C: Category}{X Y: C}(f: C X Y) := X.\nDefinition codomain {C: Category}{X Y: C}(f: C X Y) := Y.\n\nClass Isomorphic (C: Category)(X Y: C)(f: C X Y)(g: C Y X) :=\n  {\n    isomorphic_iso: g \\o f == Id X;\n    isomorphic_inv: f \\o g == Id Y\n  }.\n\nDefinition isomorphic (C: Category)(X Y: C) :=\n  exists (f: C X Y)(g: C Y X), Isomorphic f g.\n\nProgram Definition isomorphic_setoid (C: Category) :=\n  [Setoid by isomorphic C on C].\nNext Obligation.\n  - intros X.\n    exists (Id X), (Id X); split.\n    + now rewrite cat_comp_id_dom.\n    + now rewrite cat_comp_id_cod.\n  - intros X Y [f [g [Heqfg Heqgf]]].\n    now exists g, f.\n  - intros X Y Z [f [f' [Heqf Heqf']]] [g [g' [Heqg Heqg']]].\n    exists (g \\o f), (f' \\o g'); split.\n    + rewrite cat_comp_assoc, <- (cat_comp_assoc f), Heqg.\n      now rewrite cat_comp_id_cod, Heqf.\n    + rewrite cat_comp_assoc, <- (cat_comp_assoc g'), Heqf'.\n      now rewrite cat_comp_id_cod, Heqg'.\nQed.\nNotation \"X === Y 'in' C\" := (X == Y in (isomorphic_setoid C)) (at level 70, no associativity, Y at next level).\nNotation \"X === Y\" := (X === Y in _) (at level 70, no associativity).\n\n(** Category of Type **)\nProgram Definition Types :=\n  [Category by function\n   with (fun X Y Z f g x => g (f x)),\n        (fun X x => x)].\nNext Obligation.\n  intros f f' Heqf g g' Heqg x; simpl.\n  now rewrite Heqf, Heqg.\nQed.\nCanonical Structure Types.\n\n(** Category of Setoid **)\nProgram Definition Setoids :=\n  [Category by Map_setoid with Map_compose, Map_id].\nNext Obligation.\n  intros f f' Heqf g g' Heqg x; simpl.\n  now rewrite (Heqf x), (Heqg (f' x)).\nQed.\nCanonical Structure Setoids.\n\n(** Discrete category **)\nProgram Definition Prop_setoid (P: Prop) :=\n  [Setoid by (fun _ _ => True) on P].\n\nProgram Definition DiscreteCategory (X: Setoid): Category :=\n  [Category by `(Prop_setoid (x == y)) with _,_].\nNext Obligation.\n  revert H H0.\n  now apply transitivity.\nQed.\n\n(** Dual category **)\nProgram Definition DualCategory (C: Category): Category :=\n  [Category by (fun X Y => C Y X)\n   with (fun X Y Z (f: C Y X)(g: C Z Y) => f \\o g),\n        (fun X => Id X)].\nNext Obligation.\n  - now intros f f' Heqf g g' Heqg; rewrite Heqf, Heqg.\n  - now rewrite cat_comp_assoc.\n  - now rewrite cat_comp_id_cod.\n  - now rewrite cat_comp_id_dom.\nQed.\nNotation \"C ^op\" := (DualCategory C) (at level 0, format \"C ^op\").\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Cat_on_coq/theories/Base/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7308663867464225}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Permutation.\n\nRequire Import list_perm list_in.\nRequire Import sublist.\n\nSet Implicit Arguments.\n\nSection list_power.\n\n  Variable (X : Type).\n\n  Implicit Type ll : list X.  \n\n  Fixpoint list_power ll :=\n    match ll with\n      | nil  => nil::nil\n      | x::ll => map (cons x) (list_power ll) ++ list_power ll\n    end.\n    \n  Fact list_power_spec ll m : In m (list_power ll) <-> m <sl ll.\n  Proof.\n    revert m; induction ll as [ | x l IHl ]; intros m; simpl; split.\n    intros [ ? | [] ]; subst; apply sl_refl.\n    intros H; apply sublist_nil_inv in H; subst; auto.\n\n    intros H.\n    apply in_app_or in H.\n    rewrite in_map_iff in H.\n    destruct H as [ (p & H1 & H2)  | H2 ];\n       apply IHl in H2.\n    subst; constructor 2; auto.\n    constructor 3; auto.\n    \n    intros H.\n    apply sublist_cons_inv_rt in H.\n    destruct H as [ H2 | (p & H1 & H2) ];\n      apply IHl in H2.\n    apply in_or_app; right; auto.\n    subst; apply in_or_app; left.\n    apply in_map_iff; exists p; auto.\n  Qed.\n  \n  Fact list_power_equiv ll l : incl l ll <-> exists m, In m (list_power ll) /\\ eql l m.\n  Proof.\n    split.\n    \n    revert l; induction ll as [ | x ll ].\n    \n    intros [ | y l ] Hl.\n    exists nil; simpl; repeat split; auto.\n    exfalso; apply (Hl y); left; auto.\n    \n    intros l Hl.\n    apply incl_cons_rinv in Hl.\n    destruct Hl as (m1 & m2 & H1 & H2 & H3).\n    apply IHll in H3.\n    destruct H3 as (m3 & H3 & H4).\n    \n    destruct m1 as [ | a m1 ].\n    \n    exists m3; split.\n    simpl; apply in_or_app; right; auto.\n    simpl in H1.\n    split; intros y Hy.\n    apply H4, Permutation_in with (1 := H1); trivial.\n    apply Permutation_in with (1 := Permutation_sym H1), H4; trivial.\n    \n    rewrite (H2 a) in H1.\n    2: left; auto.\n    exists (x::m3); split.\n    simpl; apply in_or_app; left.\n    apply in_map_iff.\n    exists m3; auto.\n    split.\n    intros y Hy.\n    apply Permutation_in with (1 := H1), in_app_or in Hy.\n    destruct Hy as [ [ Hy | Hy ] | Hy ].\n    subst; left; auto.\n    left; symmetry; apply H2; right; auto.\n    right; apply H4; auto.\n    intros y [ Hy | Hy ].\n    subst; apply Permutation_in with (1 := Permutation_sym H1).\n    left; auto.\n    apply Permutation_in with (1 := Permutation_sym H1).\n    right; apply in_or_app; right; apply H4; auto.\n    \n    intros (m & H1 & H2 & H3).\n    apply list_power_spec in H1.\n    intros x Hx; apply H2 in Hx; revert Hx.\n    apply sl_In; trivial.\n  Qed.\n\nEnd list_power.\n\n    \n    \n", "meta": {"author": "DmxLarchey", "repo": "Relevant-decidability", "sha": "6b1c4d48f734c4d440d9756630998d231b2cc02f", "save_path": "github-repos/coq/DmxLarchey-Relevant-decidability", "path": "github-repos/coq/DmxLarchey-Relevant-decidability/Relevant-decidability-6b1c4d48f734c4d440d9756630998d231b2cc02f/list_power.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.730845706302772}}
{"text": "(* Gabriel Braun February 2013 *)\n\nRequire Export GeoCoq.Tarski_dev.Annexes.quadrilaterals_inter_dec.\n\nSection Vectors.\n\nContext `{T2D:Tarski_2D}.\nContext `{TE:@Tarski_euclidean Tn TnEQD}.\n\nLemma eqv_refl : forall A B, EqV A B A B.\nProof.\nintros.\nunfold EqV.\ninduction (eq_dec_points A B).\nright.\nsplit; auto.\nleft.\nright.\napply plgf_trivial.\nassumption.\nQed.\n\nLemma eqv_sym : forall A B C D, EqV A B C D -> EqV C D A B.\nProof.\nintros.\nunfold EqV in *.\ninduction H.\nleft.\napply plg_sym.\napply plg_comm2.\nassumption.\nright.\ntauto.\nQed.\n\nLemma eqv_trans : forall A B C D E F, EqV A B C D -> EqV C D E F -> EqV A B E F.\nProof.\nintros.\nunfold EqV in *.\n\ninduction H; induction H0.\nassert(Parallelogram A B F E \\/ A = B /\\ D = C /\\ E = F /\\ A = E).\napply (plg_pseudo_trans A B D C E F); auto.\napply plg_comm2.\nassumption.\ninduction H1.\nleft.\nauto.\nright.\ntauto.\nspliter.\nsubst D.\nsubst F.\ninduction (eq_dec_points A B).\nright.\ntauto.\nleft.\ninduction H.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H3.\nCol.\napply plgf_sym in H.\napply plgf_trivial_neq in H.\ntauto.\nspliter.\nsubst B.\nsubst D.\ninduction H0.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H.\nCol.\napply plgf_trivial_neq in H.\nright.\nspliter.\nsubst F.\ntauto.\nright.\ntauto.\nQed.\n\nLemma eqv_comm : forall A B C D, EqV A B C D -> EqV B A D C.\nProof.\nintros.\nunfold EqV in *.\ninduction H.\nleft.\napply plg_comm2.\nassumption.\nright.\nspliter.\nsubst B.\nsubst D.\ntauto.\nQed.\n\nLemma vector_construction : forall A B C, exists D, EqV A B C D.\nProof.\nintros.\ninduction (eq_dec_points A B).\nexists C.\nright.\ntauto.\nassert(HH:= midpoint_existence B C).\nex_and HH M.\nprolong A M D A M.\nexists D.\nleft.\napply (mid_plg _ _ _ _ M).\n\ninduction(eq_dec_points A D).\nsubst D.\nright.\nintro.\nsubst C.\napply l7_3 in H0.\napply between_identity in H1.\nsubst M.\ncontradiction.\nleft.\nassumption.\nsplit; Cong.\nassumption.\nQed.\n\nLemma vector_construction_uniqueness :\n forall A B C D D',\n EqV A B C D ->\n EqV A B C D' ->\n D = D'.\nProof.\nintros.\nunfold EqV in *.\ninduction H; induction H0.\napply plg_comm2 in H.\napply plg_comm2 in H0.\napply (plg_uniqueness B A C); auto.\nspliter.\nsubst B.\nsubst D'.\ninduction H.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H.\nCol.\napply (plgf_trivial_neq A D C ).\nassumption.\nspliter.\nsubst B.\nsubst D.\ninduction H0.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H.\nCol.\napply plgf_comm2 in H.\napply (plgf_trivial_neq A C D').\nassumption.\nspliter.\nsubst C.\nauto.\nQed.\n\nLemma null_vector : forall A B C, EqV A A B C -> B = C.\nProof.\nintros.\nunfold EqV in H.\ninduction H.\ninduction H.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H.\nCol.\napply plgf_trivial_neq in H.\nspliter.\nsubst C.\ntauto.\ntauto.\nQed.\n\nLemma vector_uniqueness : forall A B C, EqV A B A C -> B = C.\nProof.\nintros.\nunfold EqV in H.\ninduction H.\ninduction H.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H2.\nCol.\napply plgf_permut in H.\napply plgf_sym in H.\napply (plgf_trivial_neq A B C ).\nassumption.\nspliter.\nsubst A.\nauto.\nQed.\n\nLemma eqv_trivial : forall A B , EqV A A B B.\nProof.\nintros.\nunfold EqV.\nright.\ntauto.\nQed.\n\nLemma eqv_permut :\n  forall A B C D,\n  EqV A B C D ->\n  EqV A C B D.\nProof.\nintros.\ninduction (eq_dec_points A C).\nsubst C.\nassert(B = D).\napply (vector_uniqueness A).\nassumption.\nsubst D.\napply eqv_trivial.\n\nunfold EqV in *.\ninduction H.\nleft.\napply plg_permut.\napply plg_comm2.\nassumption.\nleft.\nspliter.\nsubst B.\nsubst D.\napply plg_trivial.\nassumption.\nQed.\n\nLemma eqv_par :\n forall A B C D,\n  A <> B ->\n  EqV A B C D ->\n  Par A B C D.\nProof.\nintros.\nunfold EqV in H0.\ninduction H0.\nunfold Parallelogram in H0.\ninduction H0.\nunfold Parallelogram_strict in H0.\nspliter.\napply par_right_comm.\nassumption.\nunfold Parallelogram_flat in H0.\nspliter.\nright.\nspliter.\nrepeat split; Col.\nintro.\nsubst D.\napply cong_identity in H2.\ncontradiction.\nColR.\nColR.\n\nspliter.\ncontradiction.\nQed.\n\nLemma eqv_opp_null :\n  forall A B,\n  EqV A B B A ->\n  A = B.\nProof.\nintros.\nunfold EqV in H.\ninduction H.\napply plg_irreflexive in H.\ntauto.\ntauto.\nQed.\n\nLemma eqv_sum :\n  forall A B C A' B' C',\n  EqV A B A' B' ->\n  EqV B C B' C' ->\n  EqV A C A' C'.\nProof.\nintros.\n\nunfold EqV in *.\ninduction H.\ninduction H0.\napply plg_comm2 in H.\napply plg_permut in H.\napply plg_permut in H0.\napply plg_sym in H0.\nassert(HH:= plg_pseudo_trans A A' B' B C C' H H0).\ninduction HH.\nleft.\napply plg_permut.\napply plg_comm2.\nassumption.\nspliter.\nright.\nsubst A'.\nsubst C'.\ntauto.\nspliter.\nsubst C.\nsubst C'.\nleft.\nassumption.\nspliter.\nsubst B.\nsubst B'.\nassumption.\nQed.\n\nLemma null_sum :\n forall A B C,\n  SumV A B B A C C.\nProof.\nintros.\nunfold SumV.\nintros D H.\nassert(A = D).\napply (vector_uniqueness B).\napply H.\nsubst D.\napply eqv_trivial.\nQed.\n\nLemma chasles :\n forall A B C,\n  SumV A B B C A C.\nProof.\nintros.\nunfold SumV.\nintros D H.\nassert(C = D).\napply (vector_uniqueness B).\nassumption.\nsubst D.\napply eqv_refl.\nQed.\n\nLemma eqv_mid :\n forall A B C,\n  EqV A B B C ->\n  Midpoint B A C.\nProof.\nintros.\nunfold EqV in H.\ninduction H.\napply plg_mid in H.\nex_and H M.\napply l7_3 in H0.\nsubst M.\nassumption.\nspliter.\nsubst C.\nsubst B.\napply l7_3_2.\nQed.\n\nLemma mid_eqv :\n  forall A B C, Midpoint A B C ->\n  EqV B A A C.\nProof.\nintros.\nunfold EqV.\ninduction(eq_dec_points A B).\nsubst B.\napply is_midpoint_id in H.\nsubst C.\nright.\ntauto.\nleft.\n\napply (mid_plg _ _ _ _ A).\nleft.\nintro.\nsubst C.\napply l7_3 in H.\ncontradiction.\nassumption.\nMidpoint.\nQed.\n\n\nLemma sum_sym :\n  forall A B C D E F,\n  SumV A B C D E F ->\n  SumV C D A B E F.\nProof.\nintros.\nunfold SumV in *.\nassert(HH:=vector_construction C D B).\nex_and HH D'.\n\n\nassert(HH:= (H D' H0)).\nclear H.\n\nassert(EqV C B D D').\napply eqv_permut.\nassumption.\n\nassert(EqV A D B D'0).\napply eqv_permut.\nassumption.\n\ninduction (eq_dec_points A D'0).\nsubst D'0.\n\napply eqv_comm in H1.\nassert(HP:= (eqv_mid B A D H1)).\n\nunfold EqV in H0.\ninduction H0.\napply plg_mid in H0.\nex_and H0 M.\nassert( A = M).\napply (l7_17 B D).\napply HP.\nMidpoint.\nsubst M.\n\napply mid_eqv in H0.\napply (eqv_trans _ _ A D').\napply H0.\nassumption.\n\nspliter.\nsubst D.\nsubst D'.\napply (eqv_trans _ _ A B).\napply eqv_sym.\napply eqv_comm.\napply H1.\nassumption.\n\ninduction H0; induction H1.\napply plg_mid in H0.\napply plg_mid in H1.\nex_and H0 M0.\nex_and H1 M1.\n\nassert(M1 = M0).\napply (l7_17 B D).\napply H5.\nMidpoint.\nsubst M1.\nassert(Parallelogram A D' D'0 C).\napply (mid_plg _ _ _ _ M0).\nleft.\nassumption.\nassumption.\nMidpoint.\nassert(EqV C D'0 A D').\nunfold EqV.\nleft.\napply plg_comm2.\napply plg_sym.\nassumption.\napply (eqv_trans _ _ A D').\napply H7.\nassumption.\nspliter.\nsubst B.\nsubst D'0.\nassert(EqV C D A D').\napply eqv_permut.\nassumption.\napply (eqv_trans _ _ A D').\napply H1.\nassumption.\nspliter.\nsubst D.\nsubst D'.\n\nassert(EqV A B C D'0).\napply eqv_permut.\nassumption.\napply (eqv_trans _ _ A B).\napply eqv_sym.\napply H0.\nassumption.\nspliter.\nsubst D.\nsubst D'.\nsubst B.\nsubst D'0.\napply null_vector in HH.\nsubst F.\napply eqv_trivial.\nQed.\n\n\nLemma opposite_sum :\n  forall A B C D E F,\n  SumV A B C D E F ->\n  SumV B A D C F E.\nProof.\nintros.\nunfold SumV in *.\nintros D0 H0.\nassert(HH:=vector_construction C D B).\nex_and HH D'.\nassert(HH:= (H D' H1)).\nclear H.\n\nassert(EqV D' B A D0).\napply (eqv_trans _ _ D C).\napply eqv_sym.\napply eqv_comm.\napply H1.\nassumption.\napply eqv_permut in H.\neapply (eqv_trans _ _ D' A).\napply eqv_sym.\napply H.\napply eqv_comm.\nassumption.\nQed.\n\nLemma null_sum_eq :\n  forall A B C D,\n  SumV A B B C D D ->\n  A = C.\nProof.\nintros.\nunfold SumV in H.\nassert(HH:= vector_construction B C B).\nex_and HH D'.\nassert(HH:= (H D' H0)).\nassert(A = D').\napply (null_vector D).\napply eqv_sym.\napply HH.\nsubst D'.\napply vector_uniqueness in H0.\nauto.\nQed.\n\nLemma is_to_ise :\n  forall A B C D E F,\n  SumV A B C D E F ->\n  SumV_exists A B C D E F.\nProof.\nintros.\nunfold SumV in H.\nunfold SumV_exists.\nassert(HH:= (vector_construction C D B)).\nex_and HH D'.\nassert(HH:=(H D' H0)).\nexists D'.\nsplit.\n\napply eqv_sym.\nassumption.\nassumption.\nQed.\n\nLemma ise_to_is :\n forall A B C D E F,\n  SumV_exists A B C D E F ->\n  SumV A B C D E F.\nProof.\nintros.\nex_and H D'.\nunfold SumV.\nintros.\nassert(D'= D'0).\napply (vector_construction_uniqueness C D B).\napply eqv_sym.\napply H.\nassumption.\nsubst D'0.\nassumption.\nQed.\n\nLemma sum_exists :\n forall A B C D, exists E, exists F, SumV A B C D E F.\nintros.\nassert(HH:= vector_construction C D B).\nex_and HH F.\nexists A.\nexists F.\nunfold SumV.\nintros.\nassert(D' = F).\napply (vector_construction_uniqueness C D B); auto.\nsubst D'.\napply eqv_refl.\nQed.\n\nLemma sum_uniqueness :\n forall A B C D E F E' F',\n SumV A B C D E F ->\n SumV A B C D E' F' ->\n EqV E F E' F'.\nProof.\nintros.\nunfold SumV in *.\nassert(HH:= vector_construction C D B).\nex_and HH D'.\nassert(HH:= (H D' H1)).\nassert(HP := (H0 D' H1)).\napply (eqv_trans _ _ A D').\napply eqv_sym.\nauto.\nauto.\nQed.\n\nLemma same_dir_refl : forall A B, Same_dir A B A B.\nintros.\nunfold Same_dir.\ninduction (eq_dec_points A B).\nleft.\ntauto.\nright.\nexists B.\nsplit.\napply out_trivial.\nauto.\napply eqv_refl.\nQed.\n\nLemma same_dir_ts :\n  forall A B C D,\n  Same_dir A B C D ->\n  exists M, Bet A M D /\\ Bet B M C.\nProof.\nintros.\ninduction H.\nspliter.\nsubst B.\nsubst D.\nexists A.\nsplit; Between.\n\nex_and H D'.\ninduction H0.\n\nassert(exists M : Tpoint, Midpoint M A D' /\\ Midpoint M B C).\napply plg_mid.\nassumption.\nex_and H1 M.\nunfold Midpoint in *.\nspliter.\n\ninduction H0.\nassert(HH:=plgs_two_sides A B D' C H0).\nspliter.\n\nassert(B <> C).\nintro.\nsubst C.\nunfold TS in H6.\nspliter.\nCol.\nassert(~ Col B C D').\nintro.\nunfold TS in H6.\nspliter.\napply H9.\nCol.\n\nassert(OS B C D' D).\napply l6_6 in H.\napply (out_one_side_1 _ _ _ _ C); Col.\n\nassert(TS B C A D).\napply l9_2.\napply (l9_8_2 _ _ D').\napply l9_2.\napply H6.\nauto.\n\nassert(~ Col A B C).\ninduction H10.\nassumption.\ninduction H10.\nspliter.\nex_and H13 T.\n\nassert(OS A B D' C /\\ OS D' C A B).\napply(plgs_one_side A B D' C).\nassumption.\nspliter.\n\nassert(~Col A B C).\nassumption.\n\nassert(Par_strict A B D' C /\\ Par_strict A C B D').\n\napply(plgs_par_strict A B D' C).\nassumption.\nspliter.\n\nassert(A <> B).\nintro.\nsubst B.\napply H18.\nexists C.\nsplit; Col.\n\nassert(Par C D A B).\napply (par_col_par_2 _ D').\nunfold Out in H.\nspliter.\nauto.\napply out_col in H.\nCol.\napply par_symmetry.\napply par_right_comm.\nleft.\nassumption.\n\nassert(Par_strict A B C D).\napply par_strict_symmetry.\ninduction H21.\nauto.\nspliter.\napply False_ind.\napply H17.\nCol.\n\ninduction(col_dec A B T).\napply False_ind.\nassert(B = T).\napply (l6_21 A B C B); Col.\nsubst T.\napply H22.\nexists D.\napply bet_col in H14.\nsplit; Col.\n\ninduction(col_dec C D T).\napply False_ind.\nassert(C = T).\napply (l6_21 C D B C); Col.\nsubst T.\napply H22.\nexists A.\napply bet_col in H14.\nsplit; Col.\n\ninduction H13.\n\nassert(OS B A T D).\napply (out_one_side_1 _ _ _ _ A); Col.\n\nunfold Out.\nrepeat split.\nintro.\nsubst T.\napply H23.\nCol.\nintro.\nsubst D.\napply H22.\nexists A.\nsplit; Col.\nleft.\nauto.\n\nassert(OS B A T C).\napply (one_side_transitivity _ _ _ D).\napply H25.\napply (par_strict_one_side _ _ _ C).\napply par_strict_comm.\napply H22.\nCol.\n\nassert(TS B A T C).\nunfold TS.\nrepeat split; Col.\nexists B.\nsplit; Col.\napply l9_9 in H26.\ncontradiction.\nassumption.\n\ninduction H13.\n\nassert(OS C D T A).\napply (out_one_side_1 _ _ _ _ D).\nauto.\nCol.\nunfold Out.\nrepeat split.\nintro.\nsubst T.\napply H24.\nCol.\nintro.\nsubst D.\napply H22.\nexists A.\nsplit; Col.\nleft.\nBetween.\nassert(OS C D T B).\napply (one_side_transitivity _ _ _ A).\napply H25.\napply (par_strict_one_side _ _ _ B).\napply par_strict_symmetry.\napply H22.\nCol.\n\nassert(TS C D T B).\nunfold TS.\nrepeat split.\nunfold Out in H.\nspliter.\nauto.\n\nintro.\napply H24.\nCol.\nintro.\napply H22.\nexists B.\nsplit; Col.\nexists C.\nsplit.\nCol.\nBetween.\napply l9_9 in H27.\ncontradiction.\nexists T.\nsplit; Between.\n\nassert(HH:= plgf_bet A B C D' H0).\n\ninduction (eq_dec_points A D').\nsubst D'.\nunfold Parallelogram_flat in H0.\nspliter.\nassert(B = C \\/ Midpoint A B C).\napply l7_20.\nCol.\nCong.\ninduction H9.\nsubst C.\ntauto.\nexists A.\nsplit.\nBetween.\napply midpoint_bet.\nassumption.\n\ninduction (eq_dec_points B C).\nsubst C.\nunfold Parallelogram_flat in H0.\nspliter.\nassert(A = D' \\/ Midpoint B A D').\napply l7_20.\nCol.\nCong.\ninduction H10.\nsubst D'.\ntauto.\nexists B.\nsplit.\ninduction H10.\nunfold Out in H.\nspliter.\ninduction H13.\napply (between_inner_transitivity _ _ _ D').\napply H10.\nauto.\napply (outer_transitivity_between _ _ D').\napply H10.\nauto.\nauto.\nBetween.\n\ninduction HH.\nspliter.\nexists A.\nsplit.\nBetween.\napply (outer_transitivity_between _ _ D'); Between.\n\ninduction H7.\nspliter.\nexists A.\nsplit.\nBetween.\napply between_symmetry.\napply (outer_transitivity_between _ _ D'); Between.\n\ninduction H7.\nspliter.\nexists C.\nsplit.\ninduction H.\nspliter.\ninduction H10.\nassert(Bet C B D \\/ Bet C D B).\napply (l5_3 _ _ _ D'); auto.\ninduction H11.\napply (outer_transitivity_between _ _ B); Between.\napply (between_inner_transitivity _ _ _ B).\napply H7.\nauto.\napply (outer_transitivity_between _ _ B); Between.\napply (between_exchange4 _ _ D').\napply H8.\nauto.\nBetween.\nspliter.\n\nexists B.\nsplit.\nunfold Out in H.\nspliter.\ninduction H10.\nassert(Bet B C D).\napply (between_inner_transitivity _ _ _ D').\napply H8.\nassumption.\neBetween.\n\napply (outer_transitivity_between _ _ C).\napply H7.\napply (outer_transitivity_between _ _ D' ).\napply H8.\nauto.\nauto.\nauto.\nBetween.\nspliter.\nsubst B.\nsubst D'.\nexists A.\nsplit; Between.\nQed.\n\nLemma one_side_col_out :\n forall A B X Y,\n  Col A X Y ->\n  OS A B X Y ->\n  Out A X Y.\nProof.\nintros.\nassert(A <> B /\\ ~ Col X A B /\\ ~ Col Y A B /\\ X <> A /\\ Y <> A).\nunfold OS in H0.\nex_and H0 T.\nunfold TS in *.\nspliter.\nrepeat split; auto.\nintro.\nsubst B.\nCol.\nintro.\nsubst X.\napply H0.\nCol.\nintro;\nspliter.\nsubst Y.\napply H1.\nCol.\nspliter.\n\ninduction H.\nrepeat split; auto.\ninduction H.\nrepeat split; auto.\nright.\nBetween.\n\nassert(TS A B X Y).\nunfold TS.\nrepeat split; auto.\nexists A.\nsplit.\nCol.\nBetween.\napply l9_9 in H6.\ncontradiction.\nQed.\n\nLemma par_ts_same_dir :\n forall A B C D, Par_strict A B C D ->\n (exists M, Bet A M D /\\ Bet B M C) ->\n Same_dir A B C D.\nProof.\nintros.\nex_and H0 M.\nunfold Same_dir.\nright.\n\nassert(HH:=vector_construction A B C).\nex_and HH D'.\nexists D'.\nsplit.\n2: auto.\n\nassert(A <> B /\\ C <> D).\nunfold Par in H.\nunfold Par_strict in H.\ntauto.\nspliter.\n\nassert(A <> M).\nintro.\nsubst M.\napply False_ind.\napply H.\nexists C.\napply bet_col in H1.\nsplit; Col.\n\ninduction (eq_dec_points B D').\nsubst D'.\nassert( A = C).\napply (vector_uniqueness B).\napply eqv_comm.\napply H2.\nsubst C.\n\nassert(Bet A D B \\/ Bet A B D).\napply (l5_1 _ M).\napply H5.\nauto.\nBetween.\nunfold Out.\nrepeat split; auto.\ninduction H2.\n\nassert(Par A B D' C).\napply plg_par in H2; auto.\nspliter.\nauto.\n\nassert(Col C D D').\napply col_permutation_1.\napply (parallel_uniqueness A B _ _ C _ C).\nleft.\napply H.\n2: apply par_right_comm.\n2: apply H7.\nCol.\nCol.\n\ninduction H2.\n\nassert(HH := (plgs_two_sides A B D' C H2)).\nspliter.\n\nassert(TS B C A D).\nunfold TS.\nunfold TS in H10.\nspliter.\nrepeat split;\nauto.\nintro.\napply H11.\nColR.\nexists M.\nsplit.\napply bet_col in H1.\nCol.\nauto.\n\nassert(OS B C D D').\napply (l9_8_1 _ _ _ _ A).\napply l9_2.\napply H11.\napply l9_2.\nauto.\n\napply (one_side_col_out _ B).\nCol.\napply invert_one_side.\napply H12.\n\napply False_ind.\nunfold Parallelogram_flat in H2.\nspliter.\napply H.\nexists C.\nsplit; Col.\n\nspliter.\nsubst D'.\nsubst B.\ntauto.\nQed.\n\nLemma same_dir_out : forall A B C, Same_dir A B A C -> Out A B C \\/ A = B /\\ A = C.\nintros.\nunfold Same_dir in H.\ninduction H.\nright.\nauto.\nex_and H D'.\nunfold EqV in H0.\ninduction H0.\ninduction H0.\napply plgs_par_strict in H0.\nspliter.\napply False_ind.\napply H1.\nexists B.\nsplit; Col.\napply plgf_permut in H0.\napply plgf_sym in H0.\napply plgf_trivial_neq in H0.\nspliter.\nsubst D'.\nleft.\napply l6_6.\nassumption.\nspliter.\nsubst D'.\nsubst B.\nunfold Out in H.\ntauto.\nQed.\n\nLemma same_dir_out1 : forall A B C, Same_dir A B B C -> Out A B C \\/ A = B /\\ A = C.\nintros.\nunfold Same_dir in H.\ninduction H.\nright.\nspliter.\nsubst B.\ntauto.\nex_and H D'.\nunfold EqV in H0.\n\ninduction H0.\ninduction H0.\napply plgs_par_strict in H0.\nspliter.\napply False_ind.\napply H1.\nexists B.\nsplit; Col.\nunfold Parallelogram_flat in H0.\nspliter.\nassert(A = D' \\/ Midpoint B A D').\napply l7_20.\nCol.\nCong.\ninduction H5.\nsubst D'.\ntauto.\nleft.\nunfold Midpoint in H5.\nspliter.\nunfold Out.\nrepeat split.\nintro.\nsubst B.\napply cong_symmetry in H6.\napply cong_identity in H6.\ninduction H4; tauto.\nintro.\nsubst C.\nunfold Out in H.\nspliter.\ninduction H8.\napply H.\napply (between_equality _ _ D');\nBetween.\napply H7.\napply (between_equality _ _ A);\nBetween.\ninduction H.\nspliter.\ninduction H8.\nleft.\napply (between_inner_transitivity _ _ _ D').\napply H5.\napply H8.\nleft.\napply (outer_transitivity_between _ _  D').\napply H5.\nauto.\nauto.\nspliter.\nsubst B.\nsubst D'.\nunfold Out in H.\ntauto.\nQed.\n\nLemma same_dir_null : forall A B C, Same_dir A A B C -> B = C.\nintros.\nunfold Same_dir in H.\ninduction H.\ntauto.\nex_and H D.\napply null_vector in H0.\nsubst D.\nunfold Out in H.\ntauto.\nQed.\n\n\n\nLemma plgs_out_plgs :\n forall A B C D B' C',\n Parallelogram_strict A B C D ->\n Out A B B' ->\n Out D C C' ->\n Cong A B' D C' ->\n Parallelogram_strict A B' C' D.\nProof.\nintros.\nassert(OS A D C B /\\ OS C B A D).\napply plgs_one_side.\napply plgs_permut.\napply plgs_comm2.\nassumption.\n\nassert( A <> B /\\ A <> B' /\\ D <> C /\\ D <> C').\nunfold Out in *.\nspliter.\nrepeat split; auto.\nspliter.\n\nassert(Par_strict A B C D).\napply plgs_par_strict in H.\nspliter.\nauto.\n\nassert(Par_strict A B' D C').\nassert(Par A B' D C').\napply (par_col_par_2 _ B).\nauto.\napply out_col.\nauto.\napply par_symmetry.\napply (par_col_par_2 _ C).\nauto.\napply out_col.\nauto.\napply par_symmetry.\napply par_right_comm.\nleft.\nauto.\ninduction H10.\nauto.\nspliter.\napply False_ind.\napply out_col in H0.\napply out_col in H1.\n\nassert(~Col A C D).\nintro.\napply H9.\nexists A.\nsplit; Col.\napply H14.\nColR.\n\nassert(OS A D B B').\napply (out_one_side_1 A _ _ _ A).\nintro.\napply H9.\nexists D.\nsplit; Col.\nCol.\nauto.\n\nassert(OS A D C C').\napply (out_one_side_1 _ D _ _ D).\nintro.\napply H9.\nexists A.\nsplit; Col.\nCol.\nauto.\n\nassert(OS A D B' C').\napply (one_side_transitivity _ _ _ B).\napply one_side_symmetry.\napply H11.\napply (one_side_transitivity _ _ _ C).\napply one_side_symmetry.\napply H3.\nassumption.\n\n\nassert(HH:=par_cong_mid_os  A B' D C' H10 H2 H13).\nex_and HH M.\n\napply (mid_plgs _ _ _ _ M).\nintro.\napply H10.\nexists C'.\nsplit; Col.\nassumption.\nassumption.\nQed.\n\nLemma plgs_plgs_bet :\n forall A B C D B' C',\n Parallelogram_strict A B C D ->\n Bet A B B' ->\n Parallelogram_strict A B' C' D ->\n Bet D C C'.\nProof.\nintros.\nassert(Col C' C D /\\ Col D C D).\napply (parallel_uniqueness A B C D C' D D); Col.\nleft.\napply plgs_par_strict in H.\nspliter.\nassumption.\napply (par_col_par_2 _ B').\nintro.\nsubst B.\napply plgs_par_strict in H.\nspliter.\napply H.\nexists C.\nsplit; Col.\napply bet_col in H0.\nCol.\napply plgs_par_strict in H1.\nspliter.\nleft.\nassumption.\nspliter.\nclear H3.\ninduction H2.\nBetween.\ninduction H2.\napply False_ind.\n\napply plgs_permut in H.\napply plgs_permut in H1.\n\nassert(HH1:=plgs_one_side B C D A H).\nassert(HH2:=plgs_one_side B' C' D A H1).\nspliter.\nassert(OS D A C C').\napply (one_side_transitivity _ _ _ B).\napply one_side_symmetry.\napply H6.\napply one_side_symmetry.\napply (one_side_transitivity _ _ _ B').\napply one_side_symmetry.\napply H4.\napply (out_one_side_1 _ _ _ _ A).\nintro.\napply plgs_par_strict in H1.\nspliter.\napply H1.\nexists B'.\nsplit; Col.\nCol.\nrepeat split.\nintro.\nsubst B'.\napply H1.\nCol.\nintro.\nsubst B.\napply H.\nCol.\nright.\nassumption.\nassert(TS D A C C').\nrepeat split.\nintro.\napply plgs_par_strict in H.\nspliter.\napply H.\nexists C.\nsplit; Col.\nintro.\napply plgs_par_strict in H1.\nspliter.\napply H1.\nexists C'.\nsplit; Col.\nexists D.\nsplit.\nCol.\nassumption.\napply l9_9 in H8.\ncontradiction.\n\nassert(Parallelogram_strict B C D A).\napply plgs_permut.\nassumption.\nassert(Parallelogram_strict D A B' C').\napply plgs_permut.\napply plgs_sym.\nassumption.\n\ninduction (eq_dec_points C C').\nsubst C'.\nBetween.\n\nassert(HH:= plgs_pseudo_trans B C D A B' C' H3 H4).\nassert(Parallelogram_strict B C C' B').\ninduction HH.\nassumption.\nunfold Parallelogram_flat in H6.\nspliter.\napply False_ind.\n\napply plgs_par_strict in H.\napply plgs_par_strict in H1.\nspliter.\napply H.\nexists B.\nsplit.\nCol.\napply bet_col in H2.\nColR.\n\nassert(HH1:=plgs_one_side B C C' B' H6).\nassert(HH2:=plgs_one_side B C D A H3).\nspliter.\n\n(*******************************)\n\nassert(TS B C A B').\nunfold TS.\nrepeat split.\nintro.\napply plgs_par_strict in H.\nspliter.\napply H.\nexists C.\nsplit; Col.\nintro.\napply plgs_par_strict in H6.\nspliter.\napply H6.\nexists B'.\nsplit; Col.\nexists B.\nsplit.\nCol.\nassumption.\n\nassert(OS B C C' D).\napply (out_one_side_1 _ _ _ _ C).\nintro.\napply plgs_par_strict in H6.\nspliter.\napply H6.\nexists C'.\nsplit; Col.\napply col_trivial_2.\nrepeat split.\nauto.\nintro.\nsubst D.\napply plgs_par_strict in H3.\nspliter.\napply H3.\nexists C.\nsplit; Col.\nleft.\nBetween.\n\nassert(OS B C A B').\napply (one_side_transitivity _ _ _ D).\napply one_side_symmetry.\napply H7.\napply (one_side_transitivity _ _ _ C').\napply one_side_symmetry.\napply H12.\nassumption.\napply l9_9 in H11.\ncontradiction.\nQed.\n\nLemma plgf_plgf_bet :\n forall A B C D B' C',\n Parallelogram_flat A B C D ->\n Bet A B B' ->\n Parallelogram_flat A B' C' D ->\n Bet D C C'.\nProof.\nintros.\ninduction (eq_dec_points A B).\nsubst B.\nassert(C = D /\\ A <> C).\napply plgf_trivial_neq.\nauto.\nspliter.\nsubst D.\nBetween.\n\nassert(HH:=not_col_exists A B H2).\nex_and HH P.\nassert(HH:=plg_existence A B P H2).\nex_and HH Q.\n\nassert(Parallelogram_strict A B P Q).\ninduction H4.\nassumption.\nunfold Parallelogram_flat in H4.\nspliter.\ncontradiction.\n\nassert(Parallelogram_strict C D Q P).\n\napply(plgf_plgs_trans C D A B P Q).\nintro.\nsubst D.\nassert(A = B /\\ C <> A).\napply plgf_trivial_neq.\napply plgf_sym.\nassumption.\ntauto.\napply plgf_sym.\nassumption.\nassumption.\n\nassert(A <> B').\nintro.\nsubst B'.\napply between_identity in H0.\ncontradiction.\n\nassert(HH:=vector_construction A B' Q).\nex_and HH P'.\n\ninduction H8.\n2 : tauto.\n\nassert(B <> P).\nintro.\nsubst P.\napply H3.\nCol.\n\nassert(B' <> P').\nintro.\nsubst P'.\n\ninduction H8.\napply plgs_par_strict in H8.\nspliter.\napply H10.\napply plgs_par_strict in H5.\nexists A.\nsplit; Col.\napply plgf_permut in H8.\nassert(Q = A /\\ B' <> Q).\napply plgf_trivial_neq.\nauto.\nspliter.\nsubst Q.\napply H5.\nCol.\n\nassert(Par A B' P Q).\napply plg_par in H8; auto.\nspliter.\napply bet_col in H0.\n\napply (par_col_par_2 _ B); auto.\napply plg_par in H4; auto.\nspliter.\nassumption.\n\nassert(Col P' P Q /\\ Col Q P Q).\napply(parallel_uniqueness A B' P Q P' Q Q ); Col.\napply plg_par in H8; auto.\nspliter.\nauto.\nspliter.\nclear H13.\n\nassert(Parallelogram_strict A B' P' Q).\ninduction H8.\nauto.\nunfold Parallelogram_flat in H8.\nspliter.\napply False_ind.\nunfold Parallelogram_flat in *.\nspliter.\napply bet_col in H0.\nassert(Col B' P' Q).\nColR.\n\napply plgs_par_strict in H5.\nspliter.\napply H5.\nexists Q.\nsplit.\nColR.\nCol.\n\nassert(Parallelogram_strict D C' P' Q).\napply (plgf_plgs_trans _ _ B' A).\nintro.\nsubst C'.\napply plgf_sym in H1.\napply plgf_trivial_neq in H1.\ntauto.\napply plgf_comm2.\napply plgf_sym.\napply H1.\napply plgs_comm2.\nassumption.\n\nassert(Bet Q P P').\napply(plgs_plgs_bet A B P Q B' P'); auto.\napply(plgs_plgs_bet Q P C D P' C').\napply plgs_sym.\nauto.\nauto.\napply plgs_comm2.\napply plgs_sym.\nauto.\nQed.\n\nLemma plg_plg_bet :\n forall A B C D B' C',\n Parallelogram A B C D ->\n Bet A B B' ->\n Parallelogram A B' C' D ->\n Bet D C C'.\nProof.\nintros.\n\ninduction(eq_dec_points A B).\nsubst B.\ninduction H.\napply False_ind.\napply H.\napply plgs_sym in H.\napply False_ind.\napply H.\nCol.\napply plgf_trivial_neq in H.\nspliter.\nsubst D.\nBetween.\n\ninduction (eq_dec_points B C).\nsubst C.\ninduction H.\napply False_ind.\napply plgs_sym in H.\napply H.\nCol.\napply plgf_permut in H.\napply plgf_trivial_neq in H.\nspliter.\nsubst D.\ninduction H1.\napply False_ind.\napply H.\nCol.\napply plgf_permut in H.\napply plgf_sym in H.\napply plgf_trivial_neq in H.\nspliter.\nsubst C'.\nBetween.\n\nassert(A <> B').\nintro.\nsubst B'.\napply between_identity in H0.\ncontradiction.\n\nassert(B' <> C').\nintro.\nsubst C'.\napply plg_permut in H1.\ninduction H1.\napply plgs_par_strict in H1.\nspliter.\napply H1.\nexists A.\nsplit; Col.\napply plgf_trivial_neq in H1.\nspliter.\nsubst D.\napply plg_permut in H.\ninduction H.\napply plgs_par_strict in H.\nspliter.\napply H1.\nexists A.\nsplit; Col.\napply plgf_sym in H.\napply plgf_trivial_neq in H.\ntauto.\n\nassert(HH:=H).\nassert(HH1:=H1).\n\napply plg_par in H; auto.\napply plg_par in H1; auto.\nspliter.\n\nassert(Par A B C' D).\napply (par_col_par_2 _ B'); auto.\napply bet_col in H0.\nCol.\n\nassert(Col C' C D /\\ Col D C D).\n\napply(parallel_uniqueness A B C D C' D D); Col.\nspliter.\nclear H10.\n\ninduction HH; induction HH1.\napply (plgs_plgs_bet A B _ _ B').\napply H10.\napply H0.\nauto.\n\napply False_ind.\nunfold Parallelogram_flat in H11.\nspliter.\napply plgs_par_strict in H10.\nspliter.\napply bet_col in H0.\napply H10.\nassert(Col A B C').\nColR.\nexists C'.\nsplit; Col.\n\napply False_ind.\nunfold Parallelogram_flat in H10.\nspliter.\napply plgs_par_strict in H11.\nspliter.\napply bet_col in H0.\napply H11.\nassert(Col A B' C).\nColR.\nexists C.\nsplit; Col.\n\napply (plgf_plgf_bet A B _ _ B').\napply H10.\napply H0.\nauto.\nQed.\n\n\nLemma plgf_out_plgf :\n forall A B C D B' C',\n Parallelogram_flat A B C D ->\n Out A B B' ->\n Out D C C' ->\n Cong A B' D C' ->\n Parallelogram_flat A B' C' D.\nProof.\nintros.\nassert( A <> B /\\ A <> B' /\\ D <> C /\\ D <> C').\nunfold Out in *.\nspliter.\nrepeat split; auto.\nspliter.\n\nassert(HH:=not_col_exists A B H3).\nex_and HH P.\nassert(HH:=plg_existence A B P H3).\nex_and HH Q.\nassert(Parallelogram_strict A B P Q).\ninduction H8.\nassumption.\nunfold Parallelogram_flat in H8.\nspliter.\ncontradiction.\n\nassert(Parallelogram_strict C D Q P).\n\napply(plgf_plgs_trans C D A B P Q).\nauto.\napply plgf_sym.\nassumption.\nassumption.\n\nassert(HH:=vector_construction A B' Q).\nex_and HH P'.\ninduction H11.\n\nassert(B <> P).\nintro.\nsubst P.\napply plgs_par_strict in H9.\nspliter.\napply H9.\nexists B.\nsplit; Col.\n\nassert(B' <> P').\nintro.\nsubst P'.\ninduction H11.\napply plgs_par_strict in H11.\nspliter.\napply H11.\nexists B'.\nsplit; Col.\nunfold Parallelogram_flat in H11.\nspliter.\napply cong_identity in H15.\nsubst Q.\napply H9.\nCol.\n\nassert(Col Q P P').\napply plg_par in H8; auto.\napply plg_par in H11; auto.\nspliter.\n\nassert(Par A B' P Q).\napply (par_col_par_2 _ B).\nauto.\napply out_col.\napply H0.\nassumption.\n\nassert(Col P' P Q /\\ Col Q P Q).\napply(parallel_uniqueness A B' P Q P' Q Q); Col.\nspliter.\nCol.\n\n\nassert(Parallelogram_strict A B' P' Q).\ninduction H11.\nassumption.\nunfold Parallelogram_flat in H11.\nspliter.\napply False_ind.\n\napply plgs_par_strict in H9.\nspliter.\napply H9.\nexists Q.\nsplit.\n\napply out_col in H0.\nColR.\nCol.\n\nassert(P <> Q).\nintro.\nsubst Q.\napply H9.\nCol.\n\nassert(P' <> Q).\nintro.\nsubst Q.\napply H15.\nCol.\n\nassert(Parallelogram_strict D C' P' Q).\napply (plgs_out_plgs _ C P).\napply plgs_comm2.\napply H10.\nauto.\nrepeat split; auto.\n\nunfold Out in H0.\nspliter.\ninduction H19.\nleft.\n\napply (plgs_plgs_bet A B P Q B' P' H9); auto.\nright.\n\napply(plgs_plgs_bet A B' P' Q B P); auto.\n\napply plg_cong in H11.\nspliter.\neCong.\n\nassert(Parallelogram A B' C' D).\napply (plgs_pseudo_trans _ _ P' Q).\napply H15.\napply plgs_sym.\nassumption.\ninduction H19.\napply False_ind.\napply plgs_par_strict in H19.\nspliter.\nunfold Parallelogram_flat in H.\nspliter.\napply out_col in H0.\napply out_col in H1.\n\napply H19.\nexists B.\nsplit.\n\nCol.\nassert(Col B C D).\nColR.\nColR.\nassumption.\nspliter.\nsubst B'.\ntauto.\nQed.\n\n\n\n\nLemma plg_out_plg : \n forall A B C D B' C',\n Parallelogram A B C D ->\n Out A B B' ->\n Out D C C' ->\n Cong A B' D C' ->\n Parallelogram A B' C' D.\nProof.\nintros.\ninduction H.\nleft.\napply (plgs_out_plgs _ B C).\napply H.\nauto.\nauto.\nauto.\nright.\napply (plgf_out_plgf _ B C).\napply H.\nauto.\nauto.\nauto.\nQed.\n\n\nLemma same_dir_sym : forall A B C D, Same_dir A B C D -> Same_dir C D A B.\nintros.\n\ninduction (eq_dec_points A B).\nsubst B.\napply same_dir_null in H.\nsubst D.\nleft.\ntauto.\n\nunfold Same_dir in *.\ninduction H.\nleft.\ntauto.\n\nex_and H D'.\nright.\nassert(HH:=vector_construction C D A).\nex_and HH B'.\nexists B'.\nsplit.\nunfold EqV in H1.\nunfold EqV in H2.\nunfold Out in *.\nspliter.\ninduction H1; induction H2.\n\n\nrepeat split.\nauto.\nintro.\nsubst B'.\ninduction H2.\napply H2.\nCol.\napply plgf_sym in H2.\napply plgf_trivial_neq in H2.\nspliter.\nauto.\n\ninduction H4.\nright.\napply (plg_plg_bet C D _ _ D').\napply H2.\napply H4.\napply plg_sym.\napply plg_comm2.\nassumption.\n\nleft.\napply (plg_plg_bet C D' _ _ D).\napply plg_sym.\napply plg_comm2.\napply H1.\napply H4.\nassumption.\n\nspliter.\nsubst D.\ntauto.\nspliter.\nsubst B.\ntauto.\nspliter.\nsubst D.\ntauto.\nassumption.\nQed.\n\n\nLemma same_dir_trans : forall A B C D E F, Same_dir A B C D -> Same_dir C D E F -> Same_dir A B E F.\nintros.\nunfold Same_dir in *.\ninduction H; induction H0; spliter.\nleft.\ntauto.\nex_and H0 F'.\nsubst B.\nsubst D.\napply null_vector in H2.\nsubst F'.\nunfold Out in H0.\ntauto.\nex_and H D'.\nsubst D.\nsubst F.\nunfold Out in H.\ntauto.\nex_and H D'.\nex_and H0 F'.\nright.\n\n\ninduction(eq_dec_points A B).\nsubst B.\napply null_vector in H1.\nsubst D'.\nunfold Out in H.\ntauto.\n\nassert(HH:=vector_construction A B E).\nex_and HH F''.\nexists F''.\nsplit.\n\n2: auto.\nassert(C <> D /\\ C <> D' /\\ E <> F /\\ E <> F').\nunfold Out in *.\nspliter.\nrepeat split;\nauto.\nspliter.\n\nunfold EqV in *.\ninduction H1; induction H2; induction H4.\nunfold Out in *.\nspliter.\ninduction H10; induction H12.\nrepeat split.\nauto.\nintro.\nsubst F''.\n\ninduction H4.\napply H4.\nCol.\napply plgf_sym in H4.\napply plgf_trivial_neq in H4.\ntauto.\n\nleft.\nassert(Bet E F' F'').\n\napply (plg_plg_bet C D _ _ D').\napply H2.\napply H12.\n\nassert(Parallelogram C D' F'' E \\/ C = D' /\\ B = A /\\ E = F'' /\\ C = E).\n\napply(plg_pseudo_trans C D' B A E F'').\napply plg_sym.\napply plg_comm2.\nauto.\napply plg_comm2.\nauto.\ninduction H13.\n2:tauto.\nassumption.\napply (between_exchange4 _ _ F').\napply H10.\nauto.\n\nrepeat split.\nauto.\nintro.\nsubst F''.\ninduction H4.\napply H4.\nCol.\napply plgf_sym in H4.\napply plgf_trivial_neq in H4.\ntauto.\n\nassert(Bet E F'' F').\napply (plg_plg_bet C D' _ _ D).\n3: apply H2.\n2:apply H12.\n\nassert(Parallelogram C D' F'' E \\/ C = D' /\\ B = A /\\ E = F'' /\\ C = E).\napply plg_pseudo_trans.\napply plg_sym.\napply plg_comm2.\nauto.\napply plg_comm2.\nauto.\n\ninduction H13.\nassumption.\ntauto.\napply (l5_3 _ _ _ F').\napply H10.\nassumption.\n\nrepeat split.\nauto.\nintro.\nsubst F''.\ninduction H4.\napply H4.\nCol.\napply plgf_sym in H4.\napply plgf_trivial_neq in H4.\ntauto.\n\nassert(Bet E F' F'').\napply (plg_plg_bet C D _ _ D').\napply H2.\napply H12.\nassert(Parallelogram C D' F'' E \\/ C = D' /\\ B = A /\\ E = F'' /\\ C = E).\napply plg_pseudo_trans.\napply plg_sym.\napply plg_comm2.\nauto.\napply plg_comm2.\nauto.\n\ninduction H13.\nassumption.\ntauto.\napply (l5_1 _ F').\napply H8.\nauto.\nauto.\n\nrepeat split.\nauto.\nintro.\nsubst F''.\ninduction H4.\napply H4.\nCol.\napply plgf_sym in H4.\napply plgf_trivial_neq in H4.\ntauto.\n\nassert(Bet E F'' F').\napply (plg_plg_bet C D' _ _ D).\n3: apply H2.\n2: apply H12.\n\nassert(Parallelogram C D' F'' E \\/ C = D' /\\ B = A /\\ E = F'' /\\ C = E).\napply plg_pseudo_trans.\napply plg_sym.\napply plg_comm2.\nauto.\napply plg_comm2.\nauto.\n\ninduction H13.\nauto.\ntauto.\nright.\napply (between_exchange4 _ _ F').\napply H13.\nauto.\ntauto.\ntauto.\ntauto.\ntauto.\ntauto.\ntauto.\ntauto.\nQed.\n\nLemma same_dir_comm : forall A B C D, Same_dir A B C D -> Same_dir B A D C.\nintros.\n\nunfold Same_dir in *.\ninduction H.\nleft.\nauto.\nspliter.\nsplit; auto.\n\nright.\nex_and H D'.\nassert(A <> B).\nintro.\nsubst B.\napply null_vector in H0.\nunfold Out in H.\nspliter.\nauto.\n\nassert(HH:=vector_construction B A D).\nex_and HH C'.\nexists C'.\nsplit.\n2: auto.\n\nunfold Out in *.\nspliter.\n\nunfold EqV in *.\n\ninduction H4.\nrepeat split.\nauto.\nintro.\nsubst C'.\napply eqv_sym in H2.\napply null_vector in H2.\nsubst B.\ntauto.\nleft.\n\ninduction H0; induction H2;try tauto.\n\nassert(Parallelogram C D' D C' \\/ C = D' /\\ B = A /\\ C' = D /\\ C = C').\n\napply(plg_pseudo_trans C D' B A C' D).\napply plg_sym.\napply plg_comm2.\nassumption.\nassumption.\ninduction H5.\n\nassert(Parallelogram_flat C D' D C').\ninduction H5.\napply False_ind.\napply plgs_par_strict in H5.\nspliter.\napply H5.\nexists D.\napply bet_col in H4.\nsplit; Col.\nassumption.\n\nunfold Parallelogram_flat in H6.\nspliter.\n\napply (col_cong2_bet1 D').\n2:Between.\nCol.\nCong.\nCong.\nspliter.\nsubst B.\ntauto.\nspliter.\nsubst B.\ntauto.\n\nrepeat split.\nauto.\nintro.\nsubst C'.\ninduction H2.\ninduction H2.\napply H2.\nCol.\napply plgf_sym in H2.\napply plgf_trivial_neq in H2.\nspliter.\nauto.\nspliter.\nauto.\n\n\ninduction H0; induction H2;try tauto.\n\ninduction(eq_dec_points C C').\nsubst C'.\nleft.\nBetween.\n\nassert(Parallelogram C D' D C' \\/ C = D' /\\ B = A /\\ C' = D /\\ C = C').\n\napply(plg_pseudo_trans C D' B A C' D).\napply plg_sym.\napply plg_comm2.\nassumption.\nassumption.\ninduction H6.\n\nassert(Parallelogram_flat C D' D C').\ninduction H6.\napply False_ind.\napply plgs_par_strict in H6.\nspliter.\napply H6.\nexists D.\napply bet_col in H4.\nsplit; Col.\nassumption.\n\nright.\n\nassert(HH:= H7).\nunfold Parallelogram_flat in H7.\nspliter.\n\napply plgf_bet in HH.\ninduction HH.\nspliter.\n\napply False_ind.\n\napply H3.\napply (between_equality _ _ D).\napply between_symmetry.\napply H13.\nassumption.\ninduction H12.\nspliter.\n\nassert(D = D').\napply (between_equality _ _ C).\nBetween.\nBetween.\nsubst D'.\n\napply cong_identity in H10.\ncontradiction.\n\ninduction H12.\nspliter.\neBetween.\n\nspliter.\neBetween.\nspliter.\nsubst B.\ntauto.\nspliter.\nsubst B.\ntauto.\nQed.\n\nLemma bet_same_dir1 : forall A B C, A <> B -> B <> C -> Bet A B C -> Same_dir A B A C.\nintros.\nunfold Same_dir.\nright.\nexists B.\nsplit.\nunfold Out.\nrepeat split.\nintro.\nsubst C.\napply between_identity in H1.\ntauto.\nauto.\nright.\nassumption.\napply eqv_refl.\nQed.\n\nLemma bet_same_dir2 : forall A B C, A <> B -> B <> C -> Bet A B C -> Same_dir A B B C.\nintros.\nunfold Same_dir.\nright.\nassert(HH:=vector_construction A B B).\nex_and HH C'.\nexists C'.\nsplit.\n2: auto.\nunfold EqV in H2.\ninduction H2.\n2:tauto.\n\ninduction H2.\napply plgs_par_strict in H2.\nspliter.\napply False_ind.\napply H3.\nexists B.\nsplit; Col.\nassert(HH:= H2).\nunfold Parallelogram_flat in HH.\napply plgf_bet in H2.\nspliter.\n\nunfold Out.\nrepeat split.\nauto.\nintro.\nsubst C'.\napply cong_identity in H5.\ncontradiction.\n\ninduction H2.\n\nassert(Bet B A B).\nspliter.\napply (outer_transitivity_between2 _ C').\nBetween.\nauto.\ninduction H7.\nauto.\ntauto.\napply between_identity in H8.\nsubst B.\ntauto.\ninduction H2.\n\nassert(Bet B A B).\nspliter.\napply (outer_transitivity_between _ _ C').\napply H2.\nauto.\ninduction H7.\nauto.\ntauto.\napply between_identity in H8.\nsubst B.\ntauto.\n\ninduction H2.\n\nassert( A = C' \\/ Midpoint B A C').\napply l7_20.\nCol.\nCong.\ninduction H8.\ninduction H7.\ntauto.\ntauto.\nunfold Midpoint in H8.\nspliter.\napply (l5_2 A); auto.\n\nassert( A = C' \\/ Midpoint B A C').\napply l7_20.\nCol.\nCong.\ninduction H8.\ninduction H7.\ntauto.\ntauto.\nunfold Midpoint in H8.\nspliter.\napply (l5_2 A); auto.\nQed.\n\nLemma plg_opp_dir : forall A B C D, Parallelogram A B C D -> Same_dir A B D C.\nintros.\n\ninduction(eq_dec_points A B).\nsubst B.\ninduction H.\napply False_ind.\napply plgs_sym in H.\napply H.\nCol.\napply plgf_trivial_neq in H.\nspliter.\nsubst D.\nleft.\ntauto.\n\nunfold Same_dir.\nright.\nexists C.\nsplit.\napply out_trivial.\nintro.\nsubst D.\ninduction H.\napply H.\nCol.\napply plgf_sym in H.\napply plgf_trivial_neq in H.\ntauto.\nunfold EqV.\nleft.\nassumption.\nQed.\n\nLemma same_dir_dec : forall A B C D,\n  Same_dir A B C D \\/ ~ Same_dir A B C D.\nProof.\nintros.\nunfold Same_dir.\nunfold EqV.\nelim (eq_dec_points A B); intro HAB;\nelim (eq_dec_points C D); intro HCD; try tauto.\n\n  right; intro HFalse.\n  elim HFalse; clear HFalse; intro HFalse.\n\n    spliter; intuition.\n\n    destruct HFalse as [E [HFalse HElim]].\n    elim HElim; clear HElim; intro HElim.\n\n      subst.\n      apply plg_cong in HElim.\n      destruct HElim as [HCong1 HCong2].\n      treat_equalities.\n      apply out_diff2 in HFalse; intuition.\n\n      destruct HElim as [Hclear HCE]; clear Hclear; subst.\n      apply out_diff2 in HFalse; intuition.\n\n  right; intro HFalse.\n\n  elim HFalse; clear HFalse; intro HFalse.\n\n    spliter; intuition.\n\n    destruct HFalse as [E [HFalse Hclear]]; clear Hclear.\n    subst.\n    apply out_diff1 in HFalse; intuition.\n\n  assert (H := plg_existence B A C).\n  assert (HPar : B <> A) by finish.\n  apply H in HPar; clear H.\n  destruct HPar as [E HPar].\n  elim (out_dec C D E); intro Hout.\n\n    left.\n    right.\n    exists E.\n    split; try assumption.\n    left.\n    apply plg_comm2 in HPar.\n    assumption.\n\n    right.\n    intro H.\n    elim H; clear H; intro H.\n\n      spliter; subst; intuition.\n\n      destruct H as [F [Hout' HElim]].\n      elim HElim; clear HElim; intro HElim.\n\n        apply plg_comm2 in HElim.\n        assert (HEF := plg_uniqueness B A C E F HPar HElim).\n        subst; intuition.\n\n        spliter; intuition.\nQed.\n\nLemma same_or_opp_dir : forall A B C D, Par A B C D -> Same_dir A B C D \\/ Opp_dir A B C D.\nintros.\ninduction (same_dir_dec A B C D).\nleft.\nassumption.\nright.\nunfold Opp_dir.\n\nunfold Same_dir.\nright.\nassert(HH:= vector_construction A B D).\nex_and HH C'.\nexists C'.\nsplit.\n2:auto.\nunfold EqV in H1.\n\ninduction (eq_dec_points B C').\nsubst C'.\ninduction H1.\n\ninduction H1.\napply False_ind.\napply plgs_permut in H1.\napply plgs_sym in H1.\napply H1.\nCol.\napply plgf_permut in H1.\napply plgf_trivial_neq in H1.\nspliter.\nsubst D.\ninduction H.\napply False_ind.\napply H.\nexists A.\nsplit; Col.\nspliter.\ninduction H4.\nunfold Out.\nrepeat split; auto.\nleft.\nBetween.\ninduction H4.\nunfold Out.\nrepeat split; auto.\napply False_ind.\napply H0.\napply same_dir_sym.\napply bet_same_dir2; auto.\nunfold Out.\nrepeat split.\nauto.\nauto.\nright.\nassumption.\nspliter.\nsubst A.\nsubst D.\napply par_distinct in H.\ntauto.\n\ninduction H1.\n\nassert(Col C' C D /\\ Col D C D).\napply plg_par in H1.\nspliter.\n\napply(parallel_uniqueness A B C D C' D D); Col.\napply par_distinct in H.\ntauto.\nassumption.\nspliter.\nclear H4.\n\nunfold Out.\nrepeat split.\napply par_distinct in H.\ntauto.\nintro.\nsubst C'.\ninduction H1.\napply H1.\nCol.\napply plgf_sym in H1.\napply plgf_trivial_neq in H1.\nspliter.\napply par_distinct in H.\ntauto.\n\ninduction H3.\nleft.\nBetween.\ninduction H3.\napply False_ind.\n\nassert(Same_dir A B D C').\napply plg_opp_dir.\nassumption.\n\nassert(Same_dir C D D C').\napply bet_same_dir2.\napply par_distinct in H.\nspliter.\nauto.\nintro.\nsubst C'.\ninduction H1.\napply H1.\nCol.\napply plgf_sym in H1.\napply plgf_trivial_neq in H1.\nspliter.\napply par_distinct in H.\ntauto.\nassumption.\napply False_ind.\napply H0.\napply (same_dir_trans _ _ D C').\napply H4.\napply same_dir_sym.\nauto.\nright.\nassumption.\napply par_distinct in H.\ntauto.\nQed.\n\nLemma same_dir_id : forall A B, Same_dir A B B A -> A = B.\nintros.\nunfold Same_dir in H.\ninduction H.\ntauto.\nex_and H C.\napply eqv_mid in H0.\nunfold Midpoint in H0.\nunfold Out in H.\nspliter.\ninduction H3.\napply (between_equality _ _ C).\napply H0.\nassumption.\napply False_ind.\napply H2.\napply (between_equality _ _ A).\nBetween.\nassumption.\nQed.\n\nLemma opp_dir_id : forall A B, Opp_dir A B A B -> A = B.\nintros.\nunfold Opp_dir in H.\napply same_dir_id in H.\nauto.\nQed.\n\n\nLemma same_dir_to_null : forall A B C D, Same_dir A B C D -> Same_dir A B D C -> A = B /\\ C = D.\nintros.\n\nassert(Same_dir C D D C).\napply (same_dir_trans _ _ A B).\napply same_dir_sym.\napply H.\nassumption.\napply same_dir_id in H1.\nsubst D.\napply same_dir_sym in H.\napply same_dir_null in H.\nsubst B.\ntauto.\nQed.\n\nLemma opp_dir_to_null : forall A B C D, Opp_dir A B C D -> Opp_dir A B D C -> A = B /\\ C = D.\nunfold Opp_dir.\nintros.\napply same_dir_to_null; auto.\nQed.\n\nLemma same_not_opp_dir : forall A B C D, A <> B -> Same_dir A B C D -> ~ Opp_dir A B C D.\nintros.\nintro.\napply same_dir_to_null in H0.\ntauto.\nassumption.\nQed.\n\nLemma opp_not_same_dir : forall A B C D, A <> B -> Opp_dir A B C D -> ~ Same_dir A B C D.\nunfold Opp_dir.\nintros.\nintro.\napply same_dir_to_null in H0.\ntauto.\nassumption.\nQed.\n\nLemma vector_same_dir_cong : forall A B C D, A <> B -> C <> D -> exists X, exists Y, Same_dir A B X Y /\\ Cong X Y C D.\nintros.\nexists A.\nassert(HH:=segment_construction_3 A B C D H H0).\nex_and HH P.\nexists P.\nsplit; auto.\nunfold Same_dir.\nright.\nexists B.\nsplit.\napply l6_6.\nassumption.\napply eqv_refl.\nQed.\n\nEnd Vectors.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Tarski_dev/Annexes/vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7308222232785}}
{"text": "(** DISCLAIMER: the current presentation of monoids uses typeclasses,\n    but in fact it's not obvious that typeclasses are needed/useful here. \n    Indeed, there is no overloading involved.\n    Thus, the interface might change in the near future. *)\n\n(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Mathematical structures                                                 *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom SLF (* TLC *) Require Import LibTactics LibLogic LibOperation.\nGeneralizable Variables A B.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Monoids *)\n\n(* --------------------------------------------------------------------- *)\n(* ################################################################# *)\n(** * Structures *)\n\n(** Monoid structure: binary operator and neutral element *)\n\nRecord monoid_op (A:Type) : Type := monoid_make {\n   monoid_oper : A -> A -> A;\n   monoid_neutral : A }.\n\n(** Monoid properties \n    Note that field names are suffixed by [_prop] because the corresponding\n    properties are also available through typeclass instances. *)\n(* -- LATER: factorize [let (o,n) := m] for the record definition *)\n\nClass Monoid A (m:monoid_op A) : Prop := Monoid_make {\n   monoid_assoc_prop : let (o,n) := m in assoc o;\n   monoid_neutral_l_prop : let (o,n) := m in neutral_l o n;\n   monoid_neutral_r_prop : let (o,n) := m in neutral_r o n }.\n\n(** Commutative monoid *)\n\nClass Comm_monoid A (m:monoid_op A) : Prop := Comm_monoid_make {\n   comm_monoid_monoid : Monoid m;\n   comm_monoid_comm : let (o,n) := m in comm o }.\n\n(* --------------------------------------------------------------------- *)\n(* ################################################################# *)\n(** * Examples *)\n\n(** Example:\n\n  Instance monoid_plus_zero:\n    Monoid (monoid_make plus 0).\n  Proof using.\n    constructor; repeat intro; omega.\n  Qed.\n\n*)\n\n(* --------------------------------------------------------------------- *)\n(* ################################################################# *)\n(** * Properties *)\n\nSection MonoidProp.\nContext {A:Type}.\n\nClass Monoid_assoc {m:monoid_op A} := {\n  monoid_assoc : assoc (monoid_oper m) }.\n\nClass Monoid_neutral_l {m:monoid_op A} := {\n  monoid_neutral_l : neutral_l (monoid_oper m) (monoid_neutral m) }.\n\nClass Monoid_neutral_r {m:monoid_op A} := {\n  monoid_neutral_r : neutral_r (monoid_oper m) (monoid_neutral m) }.\n\nClass Monoid_comm {m:monoid_op A} := {\n  monoid_comm : comm (monoid_oper m) }.\n\nEnd MonoidProp.\n\n(* --------------------------------------------------------------------- *)\n(* ################################################################# *)\n(** * Derived Properties *)\n\nSection MonoidInst.\nVariables (A:Type).\nImplicit Types m : monoid_op A.\n\nGlobal Instance Monoid_assoc_of_Monoid : forall m (M:Monoid m),\n  Monoid_assoc (m:=m).\nProof using.\n  introv M. constructor. destruct M as [U ? ?]. destruct m. simpl. apply U.\nQed.\n\nGlobal Instance Monoid_neutral_l_of_Monoid : forall m (M:Monoid m),\n  Monoid_neutral_l (m:=m).\nProof using.\n  introv M. constructor. destruct M as [? U ?]. destruct m. simpl. apply U.\nQed.\n\nGlobal Instance Monoid_neutral_r_of_Monoid : forall m (M:Monoid m),\n  Monoid_neutral_r (m:=m).\nProof using.\n  introv M. constructor. destruct M as [? ? U]. destruct m. simpl. apply U.\nQed.\n\nGlobal Instance Monoid_of_Comm_monoid : forall m (M:Comm_monoid m),\n  Monoid m.\nProof using.\n  introv M. destruct M as [U ?]. destruct m. simpl. apply U.\nQed.\n\nGlobal Instance Monoid_comm_of_Comm_Monoid : forall m (M:Comm_monoid m),\n  Monoid_comm (m:=m).\nProof using.\n  introv M. constructor. destruct M as [? U]. destruct m. simpl. apply U.\nQed.\n\nEnd MonoidInst.\n\n\n(* 2020-03-09 15:04:12 (UTC+01) *)\n", "meta": {"author": "PKUTCS-CBS", "repo": "CBSVerifi", "sha": "2a71f58046fd77a9d13a4ab567417248eac34c43", "save_path": "github-repos/coq/PKUTCS-CBS-CBSVerifi", "path": "github-repos/coq/PKUTCS-CBS-CBSVerifi/CBSVerifi-2a71f58046fd77a9d13a4ab567417248eac34c43/TLC/LibMonoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.730822223215172}}
{"text": "(* week_38c_mystery_functions.v *)\n(* dIFP 2014-2015, Q1, Week 38 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\n(* Are the following specifications unique?\n   What are then the corresponding functions?\n\n   Spend the rest of your dIFP weekly time\n   to answer these questions\n   for the specifications below.\n   (* At least 7 specifications would be nice. *)\n*)\n\n(* ********** *)\nRequire Import Arith.\nRequire Import unfold_tactic.\n\n(* Helper stuff *)\n\nLemma unfold_plus_bc :\n  forall j : nat,\n    plus 0 j = j.\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_plus_ic :\n  forall i' j : nat,\n    plus (S i') j = S (plus i' j).\nProof.\n  unfold_tactic plus.\nQed.\n\n(* Helper for later *)\nProposition plus_1_S :\n  forall n : nat,\n    S n = plus 1 n.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    rewrite -> (plus_0_r 1).\n    reflexivity.\n  \n  (* Inductive case: *)\n    rewrite -> (unfold_plus_ic 0 (S n')).\n    rewrite -> (plus_0_l (S n')).\n    reflexivity.\nQed.\n\nProposition plus_S_1 :\n  forall n : nat,\n    S n = plus n 1.\nProof.\n  intro.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n    rewrite -> (plus_0_l 1).\n    reflexivity.\n\n  (* Inductive case: *)\n    rewrite -> (unfold_plus_ic n' 1).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\nLemma unfold_mult_bc :\n  forall y : nat,\n    0 * y = 0.\n(* left-hand side in the base case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic mult.\nQed.\n\nLemma unfold_mult_ic :\n  forall x' y : nat,\n    (S x') * y = y + (x' * y).\n(* left-hand side in the inductive case\n   =\n   the corresponding conditional branch *)\nProof.\n  unfold_tactic mult.\nQed.\n\nLemma nat_ind2 :\n  forall P : nat -> Prop,\n    P 0 ->\n    P 1 ->\n    (forall i : nat,\n      P i -> P (S i) -> P (S (S i))) ->\n    forall n : nat,\n      P n.\nProof.\n  intros P H_P0 H_P1 H_PSS n.\n  assert(consecutive :\n           forall x : nat,\n             P x /\\ P (S x)).\n    intro x.\n    induction x as [ | x' [IHx' IHSx']].\n      split.\n        exact H_P0.\n      exact H_P1.\n\n      split.\n        exact IHSx'.\n      exact (H_PSS x' IHx' IHSx').\n\n      destruct (consecutive n) as [ly _].\n\n      exact ly.\nQed.\n\n\nDefinition specification_of_the_mystery_function_0 (f : nat -> nat) :=\n  (f 0 = 1)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = f i + f j).\n\nProposition there_is_only_one_mystery_function_0 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_0 f ->\n    specification_of_the_mystery_function_0 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_0.  \n  intros [H_mys_bc1 H_mys_ic1].\n  intros [H_mys_bc2 H_mys_ic2].\n  intro n.\n  induction n as [ | n' IHn'].\n  (* Base case: *)\n    rewrite -> (H_mys_bc1).\n    rewrite -> (H_mys_bc2).\n    reflexivity.\n\n  (* Inductive case: *)\n    rewrite <- (plus_0_r n').\n    rewrite -> (H_mys_ic1 n' 0).\n    rewrite -> (H_mys_ic2 n' 0).\n    rewrite -> (H_mys_bc1).\n    rewrite -> (H_mys_bc2).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\nTheorem and_the_mystery_function_0_is_dot_dot_dot :\n  specification_of_the_mystery_function_0 S.\nProof.\n\n  unfold specification_of_the_mystery_function_0.\n  split.\n    reflexivity.\n\n    intros i j.\n    rewrite -> (plus_1_S).\n    rewrite -> (plus_S_1).\n    rewrite -> (plus_1_S).\n    rewrite -> (plus_assoc 1 i j).\n    Check(plus_1_S).\n    rewrite <- (plus_1_S i).\n    rewrite <- (plus_assoc (S i) j 1).\n    rewrite <- (plus_S_1 j).\n    reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_1 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (forall i j : nat,\n    f (i + S j) = f i + S (f j)).\n\nProposition there_is_only_one_mystery_function_1 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_1 f ->\n    specification_of_the_mystery_function_1 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_1.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n    rewrite <- (plus_0_l (S n')).\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    rewrite (IHn').\n    reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_1_is_id :\n  specification_of_the_mystery_function_1 id.\nProof.\n  unfold specification_of_the_mystery_function_1.\n  unfold id.\n  split.\n  \n    reflexivity.\n\n\n    intros i j.\n    reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_2 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = S (f i) + S (f j)).\n\nProposition there_is_only_one_mystery_function_2 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_2 f ->\n    specification_of_the_mystery_function_2 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_2.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n    Check(plus_n_Sm).\n    rewrite <- (plus_0_l (S n')).\n    rewrite <- (plus_n_Sm 0 n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\n\n\nTheorem and_the_mystery_function_2_is_mult_2 :\n  specification_of_the_mystery_function_2 (mult 2).\nProof.\n  unfold specification_of_the_mystery_function_2.\n  split.\n  \n    rewrite -> (mult_0_r 2).\n    reflexivity.\n\n    intros i j.\n    rewrite -> (plus_n_Sm i j).\n    rewrite <- (plus_0_r j).\n    rewrite -> (plus_n_Sm j 0).\n    rewrite -> (plus_assoc i j 1).\n    rewrite -> (plus_0_r j).\n    rewrite <- (plus_0_r (2*i)).\n    rewrite -> (plus_n_Sm (2*i) 0).\n    rewrite <- (plus_0_r (2*j)).\n    rewrite -> (plus_n_Sm (2*j) 0).\n    rewrite <- (plus_assoc i j 1).\n    rewrite -> (plus_comm j 1).\n    rewrite -> (plus_assoc i 1 j).\n    rewrite -> (mult_plus_distr_l 2 (i+1) j).\n    rewrite -> (mult_plus_distr_l 2 i 1).\n    rewrite -> (plus_comm (2*j) 1).\n    rewrite -> (plus_assoc (2*i+1) 1 (2*j)).\n    rewrite -> (mult_1_r 2).\n    Check(plus_assoc).\n    rewrite <- (plus_assoc (2*i) 1 1).\n    rewrite <- (plus_1_S 1).\n    reflexivity.\nQed.\n\n\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_3 (f : nat -> nat) :=\n  (f 0 = 1)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = S (f i) + S (f j)).\n\n\nProposition there_is_only_one_mystery_function_3 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_3 f ->\n    specification_of_the_mystery_function_3 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_3.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n    \n  \n  (* Inductive case: *)\n\n    rewrite <- (plus_0_l (S n')).\n    rewrite <- (plus_n_Sm 0 n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_3_is_mult_3_plus_1 :\n  specification_of_the_mystery_function_3 (fun x => (3*x +1)).\nProof.\n  unfold specification_of_the_mystery_function_3.\n  split.\n  \n    rewrite -> (mult_0_r).\n    rewrite -> (plus_0_l).\n    reflexivity.\n\n    intros i j.\n    rewrite -> (plus_S_1 (i + j)).\n    rewrite -> (mult_plus_distr_l).\n    rewrite -> (mult_plus_distr_l).\n    rewrite -> (plus_S_1 (3*i + 1)).\n    rewrite -> (plus_1_S (3*j + 1)).\n    rewrite <- (plus_assoc (3*i) 1 1).\n    rewrite <- (plus_1_S 1).\n    rewrite -> (mult_1_r 3).\n    rewrite <- (plus_assoc (3*i + 3*j) 3 1).\n    rewrite <- (plus_S_1 3).\n    rewrite -> (plus_comm (3*j) 1).\n    rewrite -> (plus_assoc 1 1 (3*j)).\n    rewrite <- (plus_S_1 1).\n    rewrite -> (plus_assoc (3*i + 2) 2 (3 * j)).\n    rewrite <- (plus_assoc (3*i) 2 2).\n    rewrite <- (plus_n_Sm 2 1).\n    rewrite <- (plus_n_Sm 2 0).\n    rewrite -> (plus_0_r 2).\n    rewrite <- (plus_assoc (3*i) 4 (3*j)).\n    rewrite -> (plus_comm 4 (3*j)).\n    rewrite -> (plus_assoc (3*i) (3*j) 4).\n    reflexivity.\nQed.\n\n\n(* ********** *)\n\n\nDefinition specification_of_the_mystery_function_4 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (forall i j : nat,\n    f (i + j) = f i + f j).\n\nProposition there_is_only_one_mystery_function_4 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_4 f ->\n    specification_of_the_mystery_function_4 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_4.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n    \n  \n  (* Inductive case: *)\n\n    rewrite -> (plus_1_S n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (plus_1_S 0).\nAbort.\n\nLemma mystery_function_4_is_not_unique :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_4 f ->\n    specification_of_the_mystery_function_4 g ->\n    exists n : nat,\n      ~(f n = g n).\n\nTheorem possible_mystery_function_4_is_plus_0 : \n  specification_of_the_mystery_function_4 (plus 0).\nProof.\n  unfold specification_of_the_mystery_function_4.\n  split.\n    rewrite -> (plus_0_l).\n    reflexivity.\n\n    intros i j.\n    rewrite ->3 (plus_0_l).\n    reflexivity.\nQed.\n\nTheorem another_possibility_for_mystery_function_4_is_mult_1 : \n  specification_of_the_mystery_function_4 (mult 1).\nProof.\n  unfold specification_of_the_mystery_function_4.\n  split.\n    rewrite -> (mult_0_r).\n    reflexivity.\n    \n    intros i j.\n    rewrite ->3 (mult_1_l).\n    reflexivity.\nQed.\n\nTheorem and_the_mystery_function_4_is_mult_id :\n  specification_of_the_mystery_function_4 id.\nProof.\n  unfold specification_of_the_mystery_function_4.\n  split.\n  \n    unfold id.\n    reflexivity.\n\n    intros i j.\n    unfold id.\n    reflexivity.\nQed.\n\n\n\n(* ********** *)\n\nLemma binomial_2 :\n  forall x y : nat,\n    (x + y) * (x + y) = (x * x) + 2 * x * y + (y * y).\nProof.\n  intros x y.\n\n  rewrite -> mult_plus_distr_r.\n  rewrite -> mult_plus_distr_l.\n  rewrite -> mult_plus_distr_l.\n  rewrite -> (mult_comm y x).\n  symmetry.\n\n  rewrite -> (unfold_mult_ic 1 x).\n  rewrite -> (unfold_mult_ic 0 x).\n  rewrite -> unfold_mult_bc.\n  rewrite -> plus_0_r.\n  rewrite -> mult_plus_distr_r.\n  rewrite -> plus_assoc.\n  rewrite -> plus_assoc.\n  reflexivity.\nQed.\n\nDefinition specification_of_the_mystery_function_5 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (forall i : nat,\n    f (S i) = S (2 * i + f i)).\n\n\nProposition there_is_only_one_mystery_function_5 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_5 f ->\n    specification_of_the_mystery_function_5 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_5.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n   \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite (IHn').\n    reflexivity.\nQed.\n\nTheorem and_the_mystery_function_5_is_square :\n  specification_of_the_mystery_function_5 (fun x => x * x).\nProof.\n  unfold specification_of_the_mystery_function_5.\n  split.\n    rewrite -> (mult_0_r).\n    reflexivity.\n\n    intro i.\n    rewrite -> (plus_1_S).\n    rewrite -> (plus_1_S (2*i + i*i)).\n    rewrite -> (plus_assoc 1 (2*i) (i*i)).\n    rewrite <- (mult_1_r (2*i)).\n    rewrite <- (mult_assoc 2 i 1).\n    rewrite -> (mult_comm i 1).\n    rewrite -> (mult_assoc 2 1 i).\n    rewrite -> (binomial_2).\n    rewrite <- (mult_1_l 1) at 5.\n    reflexivity.\nQed.\n\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_6 (f : nat -> nat) :=\n  (forall i j : nat,\n    f (i + j) = f i + 2 * i * j + f j).\n\n\nProposition there_is_only_one_mystery_function_6 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_6 f ->\n    specification_of_the_mystery_function_6 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_6.\n  intros H_f H_g.\n  intro n.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n   \n    rewrite <- (plus_0_l 0).\n    rewrite -> (H_f).\n    rewrite -> (H_g).\nAbort.\n\n\n\nTheorem and_the_mystery_function_6_is_power :\n  specification_of_the_mystery_function_6 (fun x => x*x).\nProof.\n  unfold specification_of_the_mystery_function_6.\n  intros i j.\n  apply (binomial_2).\nQed.\n\nLemma rewriting_in_short_form_v1 : \n  forall a b c d : nat,\n    a + b + c + d = a + d + b + c.\nProof.                    \n  intros a b c d.\n  rewrite <- (plus_assoc a d b).\n  rewrite -> (plus_comm d b).\n  rewrite <- (plus_assoc a (b + d) c).\n  rewrite -> (plus_comm b d).\n  rewrite <- (plus_assoc d b c).\n  rewrite -> (plus_comm d (b + c)).\n  rewrite -> (plus_assoc a (b + c) d).\n  rewrite -> (plus_assoc a b c).\n  reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_6_could_also_be : \n  specification_of_the_mystery_function_6 (fun x => x*x + 2*x).\nProof.\n  unfold specification_of_the_mystery_function_6.\n  intros i j.\n  rewrite -> (binomial_2).\n  rewrite -> (mult_plus_distr_l).\n  rewrite -> (plus_comm (2*i) (2*j)).\n  rewrite <- (plus_assoc (i*i) (2*i) (2*i*j)).\n  rewrite -> (plus_comm (2*i) (2*i*j)).\n  rewrite -> (plus_assoc (i*i) (2*i*j) (2*i)).\n  rewrite ->2 (plus_assoc).\n  rewrite -> (rewriting_in_short_form_v1 (i*i + 2*i*j) (j*j) (2*j) (2*i)).\n  reflexivity.\nQed.  \n  \n(* ********** *)\n\nFixpoint exp (x n : nat)  :=\n  match n with\n      | 0 => 1\n      | S n' => mult x (exp x n')\nend.               \n\nLemma unfold_exp_bc :\n  forall x : nat,\n    exp x 0 = 1.\nProof.\n  unfold_tactic exp.\nQed.\n\nLemma unfold_exp_ic :\n  forall (x n : nat),\n    exp x (S n) = mult x (exp x n).\nProof.\n  unfold_tactic exp.\nQed.\n\n\nDefinition specification_of_the_mystery_function_7 (f : nat -> nat) :=\n  (f 0 = 1)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = 2 * f i * f j).\n\nProposition there_is_only_one_mystery_function_7 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_7 f ->\n    specification_of_the_mystery_function_7 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_7.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n   \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n\n    rewrite <- (plus_0_l (S n')).\n    rewrite <- (plus_n_Sm 0 n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (IHn').\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\nQed.\n\n\n\nLemma exp_is_distributive :\n  forall (x n m : nat),\n    mult (exp x n) (exp x m) = exp x (n+m).\nProof.\n  intros x n m.\n  induction n as [ | n' IHn'].\n  \n  (*Base case: *)\n\n    rewrite -> (unfold_exp_bc).\n    rewrite -> (plus_0_l m).\n    rewrite -> (mult_1_l).\n    reflexivity.\n\n  (* Inductive case: *)\n\n    rewrite -> (unfold_exp_ic).\n    rewrite -> (plus_1_S).\n    rewrite <- (plus_assoc 1 n' m).\n    rewrite <- (plus_1_S (n' +m)).\n    rewrite -> (unfold_exp_ic).\n    rewrite <- (IHn').\n    rewrite -> (mult_assoc x (exp x n') (exp x m)).\n    reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_7_is_power_of_2 :\n  specification_of_the_mystery_function_7 (exp 2).\nProof.\n  unfold specification_of_the_mystery_function_7.\n  split.\n  \n    rewrite -> (unfold_exp_bc).\n    reflexivity.\n\n    intros i j.\n    rewrite -> (unfold_exp_ic).\n    rewrite <- (mult_assoc 2 (exp 2 i) (exp 2 j)).\n    rewrite -> (exp_is_distributive).\n    reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_power_8 (f : nat -> nat) :=\n  (f 0 = 2)\n  /\\\n  (forall i j : nat,\n    f (S (i + j)) = f i * f j).\n\n\nProposition there_is_only_one_mystery_function_power_8 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_power_8 f ->\n    specification_of_the_mystery_function_power_8 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_power_8.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n\n  (* Base case: *)\n   \n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n\n  (* Inductive case: *)\n    \n    rewrite <- (plus_0_l (S n')).\n    rewrite <- (plus_n_Sm 0 n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\n\nTheorem and_the_mystery_function_8_is_mult_2_power_of_2 :\n  specification_of_the_mystery_function_power_8 (fun x => mult 2 (exp 2 x)).\nProof.\n  unfold specification_of_the_mystery_function_power_8.\n  split.\n  \n    rewrite -> (unfold_exp_bc).\n    rewrite -> (mult_1_r).\n    reflexivity.\n\n\n    intros i j.\n    rewrite -> (unfold_exp_ic).\n    rewrite -> (mult_assoc 2 2 (exp 2 (i + j))).\n    rewrite <- (exp_is_distributive).\n    rewrite -> (mult_assoc).\n    rewrite -> (mult_assoc).\n    rewrite -> (mult_comm (2 * 2) (exp 2 i)).\n    rewrite -> (mult_comm 2 (exp 2 i)).\n    rewrite -> (mult_assoc).\n    reflexivity.\nQed.\n\n(* ********** *)\n\nDefinition specification_of_the_mystery_function_9 (f : nat -> nat) :=\n  (f 0 = 0)\n  /\\\n  (f 1 = 1)\n  /\\\n  (f 2 = 1)\n  /\\\n  (forall p q : nat,\n    f (S (p + q)) = f (S p) * f (S q) + f p * f q).\n\nProposition there_is_only_one_mystery_function_9 :\n  forall f g : nat -> nat,\n    specification_of_the_mystery_function_9 f ->\n    specification_of_the_mystery_function_9 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_9.\n  intros [H_f_bc0 [H_f_bc1 [H_f_bc2 H_f_ic]]]\n         [H_g_bc0 [H_g_bc1 [H_g_bc2 H_g_ic]]].\n  intro n.\n  induction n as [ | | n' IH_n' IH_Sn'] using nat_ind2.\n  \n  (* Base case 1: *)\n    rewrite -> H_f_bc0.\n    rewrite -> H_g_bc0.\n    reflexivity.\n\n  (* Base case 2: *)\n    rewrite -> H_f_bc1.\n    rewrite -> H_g_bc1.\n    reflexivity.\n  \n  (* Inductive case: *)\n    rewrite -> (plus_1_S n').\n    rewrite -> (H_f_ic 1 n').\n    rewrite -> (H_g_ic 1 n').\n    rewrite -> IH_n'.\n    rewrite -> (H_f_bc2).\n    rewrite -> (H_g_bc2).\n    rewrite -> IH_Sn'.\n    rewrite -> (H_f_bc1).\n    rewrite -> (H_g_bc1).\n    reflexivity.\nQed.\n\n\nFixpoint fib_ds (n : nat) : nat :=\n  match n with\n    | 0 => 0\n    | S n' => match n' with\n                | 0 => 1\n                | S n'' => fib_ds n' + fib_ds n''\n              end\n  end.\n\nLemma unfold_fib_ds_base_case_0 :\n  fib_ds 0 = 0.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma unfold_fib_ds_base_case_1 :\n  fib_ds 1 = 1.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nLemma shorthand_rewrite_with_fib : \n  forall a b c d : nat,\n    (a + b) * c + a* d = a*(c + d) + b*c.\nProof.\n  intros a b c d .\n  rewrite -> (mult_plus_distr_r).\n  rewrite <- (plus_assoc (a*c) (b*c) (a*d)).\n  rewrite -> (plus_comm (b*c) (a*d)).\n  rewrite -> (plus_assoc (a*c) (a*d) (b*c)).\n  Check(mult_plus_distr_l).\n  rewrite <- (mult_plus_distr_l a c d).\n  reflexivity.\nQed.\n\n\nLemma unfold_fib_ds_induction_case :\n  forall n'' : nat,\n    fib_ds (S (S n'')) = fib_ds (S n'') + fib_ds n''.\nProof.\n  unfold_tactic fib_ds.\nQed.\n\nTheorem and_the_mystery_function_9_is_fib :\n  specification_of_the_mystery_function_9 (fib_ds).\nProof.\n  unfold specification_of_the_mystery_function_9.\n  split.\n  \n    rewrite -> (unfold_fib_ds_base_case_0).\n    reflexivity.\n\n    split.\n\n      rewrite -> (unfold_fib_ds_base_case_1).\n      reflexivity.\n\n      split.\n\n        rewrite -> (unfold_fib_ds_induction_case).\n        rewrite -> (unfold_fib_ds_base_case_1).\n        rewrite -> (unfold_fib_ds_base_case_0).\n        rewrite -> (plus_0_r).\n        reflexivity.\n\n        intros p q.\n        revert p. (* To strengthen my hypothesis *)\n        induction q as [ | q' IHq'].\n        \n        (* Base case *)\n          intro p.\n          rewrite -> (plus_0_r).\n          rewrite -> (unfold_fib_ds_base_case_0).\n          rewrite -> (unfold_fib_ds_base_case_1).\n          rewrite -> (mult_0_r).\n          rewrite -> (mult_1_r).\n          rewrite -> (plus_0_r).\n          reflexivity.\n\n        (* Inductive case: *)\n        \n          intro p.\n          rewrite -> (plus_1_S q') at 1.\n          rewrite -> (plus_assoc p 1 q').\n          rewrite <- (plus_S_1 p).\n          rewrite -> (IHq' (S p)).\n          rewrite ->2 (unfold_fib_ds_induction_case).\n          rewrite -> (shorthand_rewrite_with_fib (fib_ds (S p)) (fib_ds p) (fib_ds (S q')) (fib_ds q')).\n          reflexivity.\nQed.\n\n(* ********** *)\n\n\nRequire Import Bool.\n\nDefinition specification_of_the_mystery_function_power_10 (f : nat -> bool) :=\n  (f 0 = true)\n  /\\\n  (f 1 = false)\n  /\\\n  (forall i j : nat,\n     f (i + j) = eqb (f i) (f j)).\n\nProposition there_is_only_one_mystery_function_power_10 :\n  forall f g : nat -> bool,\n    specification_of_the_mystery_function_power_10 f ->\n    specification_of_the_mystery_function_power_10 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_power_10.\n  intros [H_f_bc0 [H_f_bc1 H_f_ic]].\n  intros [H_g_bc0 [H_g_bc1 H_g_ic]].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case. *)\n    rewrite -> (H_f_bc0).\n    rewrite -> (H_g_bc0).\n    reflexivity.\n\n  (* Inductive case: *)\n    rewrite -> (plus_1_S n').\n    rewrite -> (H_f_ic).\n    rewrite -> (H_f_bc1).\n    rewrite -> (IHn').\n    rewrite -> (H_g_ic).\n    rewrite -> (H_g_bc1).\n    reflexivity.\nQed.\n\n\nFixpoint evenp (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | S 0 => false\n    | S (S n'') => evenp n''\n  end.\n\n\nLemma unfold_evenp_bc0 :\n  evenp 0 = true.\nProof.\n  unfold_tactic evenp.\nQed.\n\nLemma unfold_evenp_bc1 :\n  evenp 1 = false.\nProof.\n  unfold_tactic evenp.\nQed.\n\nLemma unfold_evenp_ic :\n  forall n'' : nat,\n    evenp (S (S n'')) = evenp n''.\nProof.\n  unfold_tactic evenp.\nQed.\n\n\nLemma about_mystery_evenp_v2 :\n    forall x : nat,\n      evenp (S x) = negb (evenp x).\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n\n  rewrite -> (unfold_evenp_bc0).\n  rewrite -> (unfold_evenp_bc1).\n  unfold negb.\n  reflexivity.\n  \n  rewrite -> (unfold_evenp_ic).\n  rewrite -> (IHx').\n  rewrite -> (negb_involutive).\n  reflexivity.\nQed.\n\n\nLemma eqb_if_both_even_or_odd : \n  forall x y : nat, \n    eqb (evenp x) (evenp y) = eqb (evenp (S x)) (evenp (S y)).\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n\n  (* Base case: *)\n  \n    intros [ | y'].\n\n      rewrite -> (unfold_evenp_bc0).\n      rewrite -> (unfold_evenp_bc1).\n      unfold eqb.\n      reflexivity.\n\n    rewrite -> (unfold_evenp_bc1).\n    rewrite -> (unfold_evenp_bc0).\n    rewrite -> (unfold_evenp_ic).\n    rewrite -> (about_mystery_evenp_v2 y').\n    destruct (evenp y') as [ | ] eqn:H_y.\n      unfold negb.\n      unfold eqb.\n      reflexivity.\n\n    unfold negb.\n    unfold eqb.\n    reflexivity.\n\n  (* Inductive case: *)\n\n    rewrite -> (unfold_evenp_ic).\n    rewrite -> (about_mystery_evenp_v2).\n    intros [ | y'].\n\n      rewrite -> (unfold_evenp_bc0).\n      rewrite -> (IHx' 1).\n      rewrite -> (unfold_evenp_ic).\n      rewrite -> (unfold_evenp_bc0).\n      rewrite -> (about_mystery_evenp_v2).\n      reflexivity.\n    \n    rewrite <- (about_mystery_evenp_v2).\n    rewrite <- (IHx' y').\n    rewrite -> (unfold_evenp_ic).\n    reflexivity.\nQed.\n\n\n\n\nTheorem fun_theorem_about_evenp : \n  forall x y : nat,\n    evenp (x + y) = eqb (evenp x) (evenp y).\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n  \n  (* Base case: *)\n  \n  intro y.\n  rewrite -> (plus_0_l).\n  rewrite -> (unfold_evenp_bc0).\n  unfold eqb.\n  destruct (evenp y) as [ | ] eqn:H_y. (* Boolean expression *)\n    reflexivity.\n  reflexivity.\n  \n  intros [ | y'].\n  rewrite -> (unfold_evenp_bc0).\n  rewrite -> (plus_0_r).\n  unfold eqb.\n  destruct (evenp (S x')) as [ | ] eqn:H_Sx'. (* Boolean expression *)\n    reflexivity.\n  reflexivity.\n  rewrite -> (plus_S_1 x').\n  rewrite <- (plus_assoc x' 1 (S y')).\n  rewrite <- (plus_1_S (S y')).\n  rewrite (IHx' (S (S y'))).\n  rewrite <- (plus_S_1 x').\n  rewrite -> (unfold_evenp_ic).\n  rewrite -> (eqb_if_both_even_or_odd).\n  reflexivity.\nQed.\n\n\n\nTheorem and_the_mystery_function_10_is_is_evenp : \n  specification_of_the_mystery_function_power_10 evenp.\nProof.\n  unfold specification_of_the_mystery_function_power_10.\n  split.\n    rewrite -> (unfold_evenp_bc0).\n    reflexivity.\n    split.\n      rewrite -> (unfold_evenp_bc1).\n      reflexivity.\n  \n    apply (fun_theorem_about_evenp).\nQed.\n\n\n\n\nDefinition specification_of_the_mystery_function_11 (f : nat -> nat * nat) :=\n  (f 0 = (1, 0))\n  /\\\n  (forall n' : nat,\n    f (S n') = let (x, y) := f n'\n               in (x + y, x)).\n\nFixpoint fib_co_acc (n : nat) : nat * nat :=\n  match n with\n    | O => (1, 0)\n    | S n' => let (x, y) := fib_co_acc n'\n              in (x + y, x)\n  end.\n\nLemma unfold_fib_co_acc_base_case :\n  fib_co_acc 0 = (1, 0).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\nLemma unfold_fib_co_acc_induction_case :\n  forall n' : nat,\n    fib_co_acc (S n') = let (x, y) := fib_co_acc n'\n                        in (x + y, x).\nProof.\n  unfold_tactic fib_co_acc.\nQed.\n\n\nProposition there_is_only_one_mystery_function_11 :\n  forall f g : nat -> nat * nat,\n    specification_of_the_mystery_function_11 f ->\n    specification_of_the_mystery_function_11 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_11.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n    \n  (* Inductive case: *)\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (IHn').\n    reflexivity.\nQed.    \n\nTheorem and_the_mystery_function_11_is_power_fibonacci_accumulator :\n  specification_of_the_mystery_function_11 fib_co_acc.\nProof.\n  unfold specification_of_the_mystery_function_11.\n  split.\n    rewrite -> (unfold_fib_co_acc_base_case).\n    reflexivity.\n\n    intro n'.\n    rewrite -> (unfold_fib_co_acc_induction_case).\n    reflexivity.\nQed.\n\n(* ********** *)\n\nFixpoint fac_co_acc (n : nat) : nat * nat :=\n  match n with\n    | 0 => (0, 1)\n    | S n' => let (x,y) := fac_co_acc n'\n              in (S x, y * S x)\nend.\n\nDefinition specification_of_the_mystery_function_12 (f : nat -> nat * nat) :=\n  (f 0 = (0, 1))\n  /\\\n  (forall n' : nat,\n    f (S n') = let (x, y) := f n'\n               in (S x, y * S x)).\n\nProposition there_is_only_one_mystery_function_12 :\n  forall f g : nat -> nat * nat,\n    specification_of_the_mystery_function_12 f ->\n    specification_of_the_mystery_function_12 g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_the_mystery_function_12.\n  intros [H_f_bc H_f_ic].\n  intros [H_g_bc H_g_ic].\n  intro n.\n  \n  induction n as [ | n' IHn'].\n  \n  (* Base case: *)\n    rewrite -> (H_f_bc).\n    rewrite -> (H_g_bc).\n    reflexivity.\n  \n  (* Inductive case: *)\n    rewrite -> (H_f_ic).\n    rewrite -> (H_g_ic).\n    rewrite -> (IHn').\n    reflexivity.\nQed.\n\n\nLemma unfold_fac_co_acc_base_case :\n  fac_co_acc 0 = (0, 1).\nProof.\n  unfold_tactic fac_co_acc.\nQed.\n\nLemma unfold_fac_co_acc_induction_case :\n  forall n' : nat,\n    fac_co_acc (S n') = let (x, y) := fac_co_acc n'\n                        in (S x, y * S x).\nProof.\n  unfold_tactic fac_co_acc.\nQed.\n\n\nTheorem and_the_mystery_function_12_is_tuple_index_and_factorial :\n  specification_of_the_mystery_function_12 fac_co_acc.\nProof.\n  unfold specification_of_the_mystery_function_12.\n  split.\n    rewrite -> (unfold_fac_co_acc_base_case).\n    reflexivity.\n\n    intro n'.\n    rewrite -> (unfold_fac_co_acc_induction_case).\n    reflexivity.\nQed.\n\n(* end of week_38c_mystery_functions.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/week_38c_genaflevering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7308222138175092}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf2 : natural) : natural :=\n  plus (plus y x) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj184_coqofml_37cxa3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7308134543790101}}
{"text": "Require Import Arith.\n\nRequire Import folLogic3.\nRequire Import folProp.\nRequire Import subProp.\nRequire Export NN.\n\nLemma natNE :\n forall a b : nat,\n a <> b -> SysPrf NN (notH (equal (natToTerm a) (natToTerm b))).\nProof.\nassert\n (forall a b : nat,\n  a < b -> SysPrf NN (notH (equal (natToTerm a) (natToTerm b)))).\nintro.\ninduction a as [| a Hreca]; intros.\ndestruct b as [| n].\nelim (lt_n_O _ H).\nsimpl in |- *.\napply impE with (notH (equal (Succ (natToTerm n)) Zero)).\napply cp2.\napply impI.\napply eqSym.\napply Axm; right; constructor.\napply nn1.\ndestruct b as [| n].\nelim (lt_n_O _ H).\nsimpl in |- *.\napply impE with (notH (equal (natToTerm a) (natToTerm n))).\napply cp2.\napply nn2.\napply Hreca.\napply lt_S_n.\nauto.\nintros.\ninduction (nat_total_order _ _ H0).\napply H.\nauto.\napply impE with (notH (equal (natToTerm b) (natToTerm a))).\napply cp2.\napply impI.\napply eqSym.\napply Axm; right; constructor.\napply H.\nauto.\nQed.\n\nLemma natLE :\n forall a b : nat,\n b <= a -> SysPrf NN (notH (LT (natToTerm a) (natToTerm b))).\nProof.\nintros.\ninduction b as [| b Hrecb].\napply nn7.\nsimpl in |- *.\napply\n impE\n  with\n    (notH\n       (orH (LT (natToTerm a) (natToTerm b))\n          (equal (natToTerm a) (natToTerm b)))).\napply cp2.\napply nn8.\napply nOr.\napply andI.\napply Hrecb.\napply le_S_n.\napply le_S.\nauto.\napply natNE.\nunfold not in |- *; intros.\napply (le_not_lt _ _ H).\nrewrite H0.\napply lt_n_Sn.\nQed.\n\nLemma natLT :\n forall a b : nat, a < b -> SysPrf NN (LT (natToTerm a) (natToTerm b)).\nProof.\nintros.\neapply orE.\napply nn9 with (a := natToTerm b) (b := natToTerm a).\napply impI.\napply contradiction with (LT (natToTerm b) (natToTerm a)).\napply Axm; right; constructor.\napply sysWeaken.\napply natLE.\napply lt_le_weak.\nauto.\napply impI.\napply orSys.\napply contradiction with (equal (natToTerm b) (natToTerm a)).\napply Axm; right; constructor.\napply sysWeaken.\napply natNE.\nunfold not in |- *; intros.\napply (le_not_lt _ _ H).\nrewrite H0.\napply lt_n_Sn.\napply Axm; right; constructor.\nQed.\n\nLemma natPlus :\n forall a b : nat,\n SysPrf NN (equal (Plus (natToTerm a) (natToTerm b)) (natToTerm (a + b))).\nProof.\nintros.\ninduction b as [| b Hrecb].\nrewrite plus_comm.\nsimpl in |- *.\napply nn3.\nrewrite plus_comm.\nsimpl in |- *.\napply eqTrans with (Succ (Plus (natToTerm a) (natToTerm b))).\napply nn4.\napply eqSucc.\nrewrite plus_comm.\napply Hrecb.\nQed.\n\nLemma natTimes :\n forall a b : nat,\n SysPrf NN (equal (Times (natToTerm a) (natToTerm b)) (natToTerm (a * b))).\nProof.\nintros.\ninduction b as [| b Hrecb].\nrewrite mult_comm.\nsimpl in |- *.\napply nn5.\nrewrite mult_comm.\nsimpl in |- *.\neapply eqTrans.\napply nn6.\nrewrite plus_comm.\napply eqTrans with (Plus (natToTerm (b * a)) (natToTerm a)).\napply eqPlus.\nrewrite mult_comm.\napply Hrecb.\napply eqRefl.\napply natPlus.\nQed.\n\nLemma boundedLT :\n forall (m : nat) (a : Formula) (x : nat),\n (forall n : nat,\n  n < m -> SysPrf NN (substituteFormula LNN a x (natToTerm n))) ->\n SysPrf NN (impH (LT (var x) (natToTerm m)) a).\nProof.\nsimple induction m; intros.\napply impI.\napply contradiction with (LT (var x) (natToTerm 0)).\napply Axm; right; constructor.\napply sysWeaken.\napply nn7.\napply impI.\neapply orE.\napply impE with (LT (var x) (natToTerm (S n))).\napply sysWeaken.\nsimpl in |- *.\napply nn8.\napply Axm; right; constructor.\napply sysWeaken.\napply H.\nintros.\napply H0.\napply lt_S.\nauto.\napply sysWeaken.\napply impI.\nrewrite <- (subFormulaId LNN a x).\napply impE with (substituteFormula LNN a x (natToTerm n)).\napply (subWithEquals LNN).\napply eqSym.\napply Axm; right; constructor.\napply sysWeaken.\napply H0.\napply lt_n_Sn.\nQed.\n\nLemma nnPlusNotNeeded :\n forall n : nat,\n SysPrf NN\n   (impH (orH (LT (var 1) (natToTerm n)) (equal (var 1) (natToTerm n)))\n      (LT (var 1) (Succ (natToTerm n)))).\nProof.\nintros.\ninduction n as [| n Hrecn].\nsimpl in |- *.\napply impI.\napply orSys.\napply contradiction with (LT (var 1) Zero).\napply Axm; right; constructor.\napply sysWeaken.\napply nn7.\nrewrite <- (subFormulaId LNN (LT (var 1) (Succ Zero)) 1).\napply impE with (substituteFormula LNN (LT (var 1) (Succ Zero)) 1 Zero).\napply (subWithEquals LNN).\napply eqSym.\napply Axm; right; constructor.\napply sysWeaken.\nreplace (substituteFormula LNN (LT (var 1) (Succ Zero)) 1 Zero) with\n (LT (natToTerm 0) (natToTerm 1)).\napply natLT.\nauto.\nunfold LT in |- *.\nrewrite (subFormulaRelation LNN).\nreflexivity.\nsimpl in |- *.\napply impI.\napply orSys.\napply\n impE with (orH (LT (var 1) (natToTerm n)) (equal (var 1) (natToTerm n))).\napply sysWeaken.\napply impTrans with (LT (var 1) (natToTerm (S n))).\napply Hrecn.\napply boundedLT.\nintros.\nreplace\n (substituteFormula LNN (LT (var 1) (Succ (Succ (natToTerm n)))) 1\n    (natToTerm n0)) with (LT (natToTerm n0) (natToTerm (S (S n)))).\napply natLT.\napply lt_S.\nassumption.\nunfold LT in |- *.\nrewrite (subFormulaRelation LNN).\nsimpl in |- *.\nrewrite (subTermNil LNN).\nreflexivity.\napply closedNatToTerm.\napply impE with (LT (var 1) (Succ (natToTerm n))).\napply sysWeaken.\napply nn8.\napply Axm; right; constructor.\nrewrite <- (subFormulaId LNN (LT (var 1) (Succ (Succ (natToTerm n)))) 1).\napply\n impE\n  with\n    (substituteFormula LNN (LT (var 1) (Succ (Succ (natToTerm n)))) 1\n       (Succ (natToTerm n))).\napply (subWithEquals LNN).\napply eqSym.\napply Axm; right; constructor.\napply sysWeaken.\nreplace\n (substituteFormula LNN (LT (var 1) (Succ (Succ (natToTerm n)))) 1\n    (Succ (natToTerm n))) with (LT (natToTerm (S n)) (natToTerm (S (S n)))).\napply natLT.\napply lt_n_Sn.\nunfold LT in |- *.\nrewrite (subFormulaRelation LNN).\nsimpl in |- *.\nrewrite (subTermNil LNN).\nreflexivity.\napply closedNatToTerm.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/goedel/NNtheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7307962370057988}}
{"text": "(* \n\n HUGHES LISTS\n\n Evgeny V Ivashkevich\n \n E-mail: ivashkev@yandex.ru\n\n March 2, 2019\n\n Abstract: In this file, we formalize the short paper by R. John Muir Hughes,\n           \"A novel repesentation of lists and its application to the function \n           reverse\". Information Pocessing Letters 22 (1986) 141-144,\n           where fast algorithm for lists reverse function was proposed.\n*)\n\nRequire Import FunctionalExtensionality.\nRequire Import List.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nModule ArrowType.\n\nSection Hughes.\n\nVariable T : Type.\n\nDefinition A := list T.\n\nDefinition R := A -> A.\n\nDefinition rep (x : A) : R := app x.\n\nCheck rep.\n\nDefinition abs (f : R) : A := f [].\n\nCheck abs.\n\nPrint abs.\n\nTheorem abs_rep :\n  forall a : A,\n  abs (rep a) = a.\nProof.\n  unfold abs, rep.\n  intros a.\n  rewrite app_nil_r.\n  reflexivity.\nQed.\n\nParameter find_rep : forall f : R, { F : A | f = rep F }.\n\nTheorem rep_abs :\n  forall f : R,\n  rep (abs f) = f.\nProof.\n  intros f.\n  destruct (find_rep f) as [ F Hf ].\n  rewrite Hf.\n  rewrite abs_rep.\n  reflexivity.\nQed.\n\nDefinition appendR (f g : R) : R := fun x => f (g x).\n\nCheck appendR.\n\nTheorem appendR_rep :\n  forall (a b : A),\n  appendR (rep a) (rep b) = rep (a ++ b).\nProof.\n  intros.\n  apply functional_extensionality.\n  intros.\n  unfold appendR, rep; simpl.\n  apply app_assoc.\nQed.\n\nTheorem abs_appendR :\n  forall (f g : R),\n  abs (appendR f g) = (abs f) ++ (abs g).\nProof.\n  intros.\n  destruct (find_rep f) as [ F Hf ].\n  destruct (find_rep g) as [ G Hg ].\n  rewrite Hf. rewrite Hg. rewrite appendR_rep.\n  unfold abs, rep; simpl.\n  repeat rewrite app_nil_r.\n  reflexivity.\nQed.\n\nFixpoint rev (x : A) : R :=\n  match x with\n  | nil => id\n  | a :: y => fun (t : A) => (rev y) (a :: t)\n  end.\n\nDefinition reverse (x : A) := (rev x) [].\n\nTheorem rev_app :\n  forall (x y : A),\n  rev x y = rev x [] ++ y.\nProof.\n  intros. \n  induction y as [| h t ].\n  { simpl. rewrite app_nil_r. reflexivity. }\n  { assert (H1 : rev x [] = abs (rev x)). reflexivity.\n    assert (H2 : h :: t = abs (app (h :: t))). \n    { unfold abs. rewrite app_nil_r. reflexivity. }\n    rewrite H1. rewrite H2 at 2.\n    rewrite <- abs_appendR.\n    unfold appendR, abs, rep; simpl.\n    rewrite app_nil_r. reflexivity.\n  }\nQed.\n\nTheorem rev_app_distr:\n  forall (x y : A),\n  reverse (x ++ y) = reverse y ++ reverse x.\nProof.\n  intros.\n  unfold reverse.\n  induction x as [| h t ].\n  { simpl. rewrite app_nil_r. reflexivity. }\n  { simpl.\n    rewrite (rev_app t [h]).\n    rewrite rev_app.\n    rewrite IHt.\n    rewrite app_assoc.\n    reflexivity.\n  }\nQed.\n\nTheorem app_length :\n  forall x y : A,\n  length (x ++ y) = length x + length y.\nProof.\n  intros x y. \n  induction x as [| h t ].\n  { reflexivity. }\n  { simpl. rewrite -> IHt. reflexivity. }\nQed.\n\nTheorem reverse_length :\n  forall x : A,\n  length (reverse x) = length x.\nProof.\n  intros x.\n  unfold reverse.\n  induction x as [| h t ].\n  { reflexivity. }\n  { assert (H : rev (h :: t) [] = rev t [] ++ [h]). \n    { simpl. rewrite rev_app. reflexivity. }\n    rewrite H. \n    rewrite app_length.\n    rewrite IHt.\n    rewrite PeanoNat.Nat.add_comm.\n    simpl. reflexivity.\n  }\nQed.\n\nTheorem reverse_involutive :\n  forall x : A,\n  reverse (reverse x) = x.\nProof.\n  induction x. \n  { reflexivity. }\n  { simpl.\n    replace (a :: x) with ([a] ++ x).\n    { repeat rewrite rev_app_distr. \n      rewrite IHx. reflexivity. \n    }\n    { reflexivity. }\n  }\nQed.\n\nTheorem rev_injective :\n  forall (x y : A),\n  reverse x = reverse y -> x = y.\nProof.\n  intros x y reveq.\n  rewrite <- reverse_involutive. \n  rewrite <- reveq.\n  rewrite -> reverse_involutive.\n  reflexivity.\nQed.\n\nEnd Hughes.\n\nCompute reverse [2;3;6;3;6;9].\n\nCompute reverse [true;true;true;false;false;false].\n\n\nEnd ArrowType.\n\n(* In the next module we change representation type from \n   functional (R := A -> A) to inductive type with additional condition \n   that we consider only those functions on lists that can be generated\n   with the help of the function append.\n*)\n\nModule InductiveType.\n\nSection Hughes.\n\nVariable T : Type.\n\nDefinition A := list T.\n\nRecord R : Type \n  := build { func : A -> A ; prop : exists x : A, func = app x }.\n\nDefinition rep (x : A) : R.\nProof.\n  apply build with (app x).\n  exists x; reflexivity.\nDefined.\n\nCheck rep.\n\nPrint rep.\n\nDefinition abs (F : R) : A.\nProof.\n  destruct F as [ f _ ].\n  apply (f []).\nDefined.\n\nCheck abs.\n\nPrint abs.\n\nTheorem abs_rep :\n  forall a : A,\n  abs (rep a) = a.\nProof.\n  unfold abs, rep.\n  intros a.\n  rewrite app_nil_r.\n  reflexivity.\nQed.\n\nDefinition find_rep :\n  forall F : R, \n  { x : A | F = rep x }.\nProof.\n  intros [ f Hf ].\n  exists (f []).\n  destruct Hf as [ x H ].\n  subst f. unfold rep.\n  rewrite app_nil_r.\n  reflexivity.\nDefined.\n\nTheorem rep_abs :\n  forall F : R,\n  rep (abs F) = F.\nProof.\n  intros F.\n  destruct (find_rep F) as [ x H ].\n  subst F. rewrite abs_rep.\n  reflexivity.\nQed.\n\nTheorem func_unique :\n  forall F G : R,\n  func F = func G -> F = G.\nProof.\n  intros.\n  rewrite <- (rep_abs F).\n  rewrite <- (rep_abs G).\n  destruct F as [ f [ x Hf ]].\n  destruct G as [ g [ y Hg ]].\n  simpl in *. rewrite H.\n  reflexivity.\nQed.\n\nDefinition appendR (F G : R) : R.\nProof.\n  destruct F as [ f Hf ].\n  destruct G as [ g Hg ].\n  exists (fun y => f (g y)).\n  destruct Hf as [ F Hf ].\n  destruct Hg as [ G Hg ].\n  subst f. subst g.\n  exists (app F G).\n  apply functional_extensionality.\n  intros x.\n  rewrite app_assoc.\n  reflexivity.\nDefined.\n\nCheck appendR.\n\nPrint appendR.\n\nTheorem appendR_rep :\n  forall (a b : A),\n  appendR (rep a) (rep b) = rep (a ++ b).\nProof.\n  intros. \n  apply func_unique. simpl. \n  apply functional_extensionality. \n  intros t. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem abs_appendR :\n  forall (f g : R),\n  abs (appendR f g) = (abs f) ++ (abs g).\nProof.\n  intros.\n  destruct (find_rep f) as [ F Hf ].\n  destruct (find_rep g) as [ G Hg ].\n  rewrite Hf. rewrite Hg. rewrite appendR_rep.\n  unfold abs, rep; simpl.\n  repeat rewrite app_nil_r.\n  reflexivity.\nQed.\n\nDefinition rev (x : A) : R.\nProof.\n  set (f := (fix rev (x : A) : A -> A :=\n    match x with\n    | [] => id\n    | a :: y => fun (t : A) => rev y (a :: t)\n    end)).\n  exists (f x).\n  exists ((f x) []).\n  induction x.\n  { simpl. reflexivity. }\n  { simpl. rewrite IHx.\n    apply functional_extensionality.\n    intros t; simpl. rewrite <- app_assoc. reflexivity.\n  }\nDefined.\n\nDefinition reverse (x : A) := func (rev x) [].\n\nTheorem rev_app :\n  forall (x y : A),\n  func (rev x) y = func (rev x) [] ++ y.\nProof.\n  intros. \n  induction y as [| h t ].\n  { rewrite app_nil_r. reflexivity. }\n  { assert (H1 : func (rev x) [] = abs (rev x)). reflexivity.\n    assert (H2 : h :: t = abs (rep (h :: t))). \n    { unfold abs, rep. rewrite app_nil_r. reflexivity. }\n    rewrite H1. rewrite H2 at 2.\n    rewrite <- abs_appendR.\n    unfold appendR, abs, rep; simpl.\n    rewrite app_nil_r. reflexivity.\n  }\nQed.\n\nTheorem rev_app_distr:\n  forall (x y : A),\n  reverse (x ++ y) = reverse y ++ reverse x.\nProof.\n  intros.\n  unfold reverse.\n  induction x as [| h t ].\n  { simpl. rewrite app_nil_r. reflexivity. }\n  { replace (func (rev ((h :: t) ++ y)) []) with (func (rev (t ++ y)) [h]).\n    replace (func (rev (h :: t)) []) with (func (rev t) [h]).\n    rewrite (rev_app t [h]).\n    rewrite rev_app.\n    rewrite IHt.\n    rewrite app_assoc.\n    reflexivity.\n    reflexivity.\n    reflexivity.\n  }\nQed.\n\nTheorem app_length :\n  forall x y : A,\n  length (x ++ y) = length x + length y.\nProof.\n  intros x y. \n  induction x as [| h t ].\n  { reflexivity. }\n  { simpl. rewrite -> IHt. reflexivity. }\nQed.\n\nTheorem reverse_length :\n  forall x : A,\n  length (reverse x) = length x.\nProof.\n  intros x.\n  unfold reverse.\n  induction x as [| h t ].\n  { reflexivity. }\n  { assert (H : func (rev (h :: t)) [] = func (rev t) [] ++ [h]). \n    { replace (func (rev (h :: t)) []) with (func (rev t) [h]).\n      rewrite rev_app. reflexivity.\n      reflexivity.\n    }\n    rewrite H. \n    rewrite app_length.\n    rewrite IHt.\n    rewrite PeanoNat.Nat.add_comm.\n    simpl. reflexivity.\n  }\nQed.\n\nTheorem reverse_involutive :\n  forall x : A,\n  reverse (reverse x) = x.\nProof.\n  induction x. \n  { reflexivity. }\n  { simpl.\n    replace (a :: x) with ([a] ++ x).\n    { repeat rewrite rev_app_distr. \n      rewrite IHx. reflexivity. \n    }\n    { reflexivity. }\n  }\nQed.\n\nTheorem rev_injective :\n  forall (x y : A),\n  reverse x = reverse y -> x = y.\nProof.\n  intros x y reveq.\n  rewrite <- reverse_involutive. \n  rewrite <- reveq.\n  rewrite -> reverse_involutive.\n  reflexivity.\nQed.\n\nEnd Hughes.\n\nCompute reverse [2;3;6;3;6;9].\n\nCompute reverse [true;true;true;false;false;false].\n\nEnd InductiveType.", "meta": {"author": "ivashkev", "repo": "math-formalizations", "sha": "2712ce673a8c647574099ffbcccf334bdbe0fedf", "save_path": "github-repos/coq/ivashkev-math-formalizations", "path": "github-repos/coq/ivashkev-math-formalizations/math-formalizations-2712ce673a8c647574099ffbcccf334bdbe0fedf/08_HughesLists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7307779389365411}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Permutation.v                        \n                                                                     \n    Defintion and properties of permutations                         \n   **********************************************************************)\nRequire Export List.\nRequire Export ListAux.\n \nSection permutation.\nVariable A : Set.\n\n(************************************** \n   Definition of permutations as sequences of adjacent transpositions\n **************************************)\n \nInductive permutation : list A -> list A -> Prop :=\n  | permutation_nil : permutation nil nil\n  | permutation_skip :\n      forall (a : A) (l1 l2 : list A),\n      permutation l2 l1 -> permutation (a :: l2) (a :: l1)\n  | permutation_swap :\n      forall (a b : A) (l : list A), permutation (a :: b :: l) (b :: a :: l)\n  | permutation_trans :\n      forall l1 l2 l3 : list A,\n      permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\nHint Constructors permutation : core.\n\n(************************************** \n   Reflexivity\n **************************************)\n \nTheorem permutation_refl : forall l : list A, permutation l l.\nsimple induction l.\napply permutation_nil.\nintros a l1 H.\napply permutation_skip with (1 := H).\nQed.\nHint Resolve permutation_refl : core.\n\n(************************************** \n   Symmetry\n   **************************************)\n \nTheorem permutation_sym :\n forall l m : list A, permutation l m -> permutation m l.\nintros l1 l2 H'; elim H'.\napply permutation_nil.\nintros a l1' l2' H1 H2.\napply permutation_skip with (1 := H2).\nintros a b l1'.\napply permutation_swap.\nintros l1' l2' l3' H1 H2 H3 H4.\napply permutation_trans with (1 := H4) (2 := H2).\nQed.\n\n(************************************** \n   Compatibility with list length\n   **************************************)\n \nTheorem permutation_length :\n forall l m : list A, permutation l m -> length l = length m.\nintros l m H'; elim H'; simpl in |- *; auto.\nintros l1 l2 l3 H'0 H'1 H'2 H'3.\nrewrite <- H'3; auto.\nQed.\n\n(************************************** \n   A permutation of the nil list is the nil list\n   **************************************)\n \nTheorem permutation_nil_inv : forall l : list A, permutation l nil -> l = nil.\nintros l H; generalize (permutation_length _ _ H); case l; simpl in |- *;\n auto.\nintros; discriminate.\nQed.\n \n(************************************** \n   A permutation of the singleton list is the singleton list\n   **************************************)\n \nLet permutation_one_inv_aux :\n  forall l1 l2 : list A,\n  permutation l1 l2 -> forall a : A, l1 = a :: nil -> l2 = a :: nil.\nintros l1 l2 H; elim H; clear H l1 l2; auto.\nintros a l3 l4 H0 H1 b H2.\ninjection H2; intros; subst; auto.\nrewrite (permutation_nil_inv _ (permutation_sym _ _ H0)); auto.\nintros; discriminate.\nQed.\n\nTheorem permutation_one_inv :\n forall (a : A) (l : list A), permutation (a :: nil) l -> l = a :: nil.\nintros a l H; apply permutation_one_inv_aux with (l1 := a :: nil); auto.\nQed.\n\n(************************************** \n   Compatibility with the belonging\n   **************************************)\n \nTheorem permutation_in :\n forall (a : A) (l m : list A), permutation l m -> In a l -> In a m.\nintros a l m H; elim H; simpl in |- *; auto; intuition.\nQed.\n\n(************************************** \n   Compatibility with the append function\n   **************************************)\n \nTheorem permutation_app_comp :\n forall l1 l2 l3 l4,\n permutation l1 l2 -> permutation l3 l4 -> permutation (l1 ++ l3) (l2 ++ l4).\nintros l1 l2 l3 l4 H1; generalize l3 l4; elim H1; clear H1 l1 l2 l3 l4;\n simpl in |- *; auto.\nintros a b l l3 l4 H.\ncut (permutation (l ++ l3) (l ++ l4)); auto.\nintros; apply permutation_trans with (a :: b :: l ++ l4); auto.\nelim l; simpl in |- *; auto.\nintros l1 l2 l3 H H0 H1 H2 l4 l5 H3.\napply permutation_trans with (l2 ++ l4); auto.\nQed.\nHint Resolve permutation_app_comp : core.\n\n(************************************** \n   Swap two sublists\n   **************************************)\n \nTheorem permutation_app_swap :\n forall l1 l2, permutation (l1 ++ l2) (l2 ++ l1).\nintros l1; elim l1; auto.\nintros; rewrite <- app_nil_end; auto.\nintros a l H l2.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\napply permutation_trans with (l ++ l2 ++ a :: nil); auto.\napply permutation_trans with (((a :: nil) ++ l2) ++ l); auto.\nsimpl in |- *; auto.\napply permutation_trans with (l ++ (a :: nil) ++ l2); auto.\napply permutation_sym; auto.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\napply permutation_app_comp; auto.\nelim l2; simpl in |- *; auto.\nintros a0 l0 H0.\napply permutation_trans with (a0 :: a :: l0); auto.\napply (app_ass l2 (a :: nil) l).\napply (app_ass l2 (a :: nil) l).\nQed.\n\n(************************************** \n   A transposition is a permutation\n   **************************************)\n \nTheorem permutation_transposition :\n forall a b l1 l2 l3,\n permutation (l1 ++ a :: l2 ++ b :: l3) (l1 ++ b :: l2 ++ a :: l3).\nintros a b l1 l2 l3.\napply permutation_app_comp; auto.\nchange\n  (permutation ((a :: nil) ++ l2 ++ (b :: nil) ++ l3)\n     ((b :: nil) ++ l2 ++ (a :: nil) ++ l3)) in |- *.\nrepeat rewrite <- app_ass.\napply permutation_app_comp; auto.\napply permutation_trans with ((b :: nil) ++ (a :: nil) ++ l2); auto.\napply permutation_app_swap; auto.\nrepeat rewrite app_ass.\napply permutation_app_comp; auto.\napply permutation_app_swap; auto.\nQed.\n\n(************************************** \n   An element of a list can be put on top of the list to get a permutation\n   **************************************)\n \nTheorem in_permutation_ex :\n forall a l, In a l -> exists l1 : list A, permutation (a :: l1) l.\nintros a l; elim l; simpl in |- *; auto.\nintros H; case H; auto.\nintros a0 l0 H [H0| H0].\nexists l0; rewrite H0; auto.\ncase H; auto; intros l1 Hl1; exists (a0 :: l1).\napply permutation_trans with (a0 :: a :: l1); auto.\nQed.\n \n(************************************** \n   A permutation of a cons can be inverted\n   **************************************)\n\nLet permutation_cons_ex_aux :\n  forall (a : A) (l1 l2 : list A),\n  permutation l1 l2 ->\n  forall l11 l12 : list A,\n  l1 = l11 ++ a :: l12 ->\n  exists l3 : list A,\n    (exists l4 : list A,\n       l2 = l3 ++ a :: l4 /\\ permutation (l11 ++ l12) (l3 ++ l4)).\nintros a l1 l2 H; elim H; clear H l1 l2.\nintros l11 l12; case l11; simpl in |- *; intros; discriminate.\nintros a0 l1 l2 H H0 l11 l12; case l11; simpl in |- *.\nexists (nil (A:=A)); exists l1; simpl in |- *; split; auto.\ninjection H1; intros; subst; auto.\ninjection H1; intros H2 H3; rewrite <- H2; auto.\nintros a1 l111 H1.\ncase (H0 l111 l12); auto.\ninjection H1; auto.\nintros l3 (l4, (Hl1, Hl2)).\nexists (a0 :: l3); exists l4; split; simpl in |- *; auto.\ninjection H1; intros; subst; auto.\ninjection H1; intros H2 H3; rewrite H3; auto.\nintros a0 b l l11 l12; case l11; simpl in |- *.\ncase l12; try (intros; discriminate).\nintros a1 l0 H; exists (b :: nil); exists l0; simpl in |- *; split; auto.\ninjection H; intros; subst; auto.\ninjection H; intros H1 H2 H3; rewrite H2; auto.\nintros a1 l111; case l111; simpl in |- *.\nintros H; exists (nil (A:=A)); exists (a0 :: l12); simpl in |- *; split; auto.\ninjection H; intros; subst; auto.\ninjection H; intros H1 H2 H3; rewrite H3; auto.\nintros a2 H1111 H; exists (a2 :: a1 :: H1111); exists l12; simpl in |- *;\n split; auto.\ninjection H; intros; subst; auto.\nintros l1 l2 l3 H H0 H1 H2 l11 l12 H3.\ncase H0 with (1 := H3).\nintros l4 (l5, (Hl1, Hl2)).\ncase H2 with (1 := Hl1).\nintros l6 (l7, (Hl3, Hl4)).\nexists l6; exists l7; split; auto.\napply permutation_trans with (1 := Hl2); auto.\nQed.\n \nTheorem permutation_cons_ex :\n forall (a : A) (l1 l2 : list A),\n permutation (a :: l1) l2 ->\n exists l3 : list A,\n   (exists l4 : list A, l2 = l3 ++ a :: l4 /\\ permutation l1 (l3 ++ l4)).\nintros a l1 l2 H.\napply (permutation_cons_ex_aux a (a :: l1) l2 H nil l1); simpl in |- *; auto.\nQed.\n\n(************************************** \n   A permutation can be simply inverted if the two list starts with a cons\n   **************************************)\n \nTheorem permutation_inv :\n forall (a : A) (l1 l2 : list A),\n permutation (a :: l1) (a :: l2) -> permutation l1 l2.\nintros a l1 l2 H; case permutation_cons_ex with (1 := H).\nintros l3 (l4, (Hl1, Hl2)).\napply permutation_trans with (1 := Hl2).\ngeneralize Hl1; case l3; simpl in |- *; auto.\nintros H1; injection H1; intros H2; rewrite H2; auto.\nintros a0 l5 H1; injection H1; intros H2 H3; rewrite H2; rewrite H3; auto.\napply permutation_trans with (a0 :: l4 ++ l5); auto.\napply permutation_skip; apply permutation_app_swap.\napply (permutation_app_swap (a0 :: l4) l5).\nQed.\n\n(************************************** \n   Take a list and return tle list of all pairs of an element of the \n   list and the remaining list\n   **************************************)\n \nFixpoint split_one (l : list A) : list (A * list A) :=\n  match l with\n  | nil => nil (A:=A * list A)\n  | a :: l1 =>\n      (a, l1)\n      :: map (fun p : A * list A => (fst p, a :: snd p)) (split_one l1)\n  end.\n\n(************************************** \n   The pairs of the list are a permutation\n   **************************************)\n \nTheorem split_one_permutation :\n forall (a : A) (l1 l2 : list A),\n In (a, l1) (split_one l2) -> permutation (a :: l1) l2.\nintros a l1 l2; generalize a l1; elim l2; clear a l1 l2; simpl in |- *; auto.\nintros a l1 H1; case H1.\nintros a l H a0 l1 [H0| H0].\ninjection H0; intros H1 H2; rewrite H2; rewrite H1; auto.\ngeneralize H H0; elim (split_one l); simpl in |- *; auto.\nintros H1 H2; case H2.\nintros a1 l0 H1 H2 [H3| H3]; auto.\ninjection H3; intros H4 H5; (rewrite <- H4; rewrite <- H5).\napply permutation_trans with (a :: fst a1 :: snd a1); auto.\napply permutation_skip.\napply H2; auto.\ncase a1; simpl in |- *; auto.\nQed.\n\n(************************************** \n   All elements of the list are there\n   **************************************)\n \nTheorem split_one_in_ex :\n forall (a : A) (l1 : list A),\n In a l1 -> exists l2 : list A, In (a, l2) (split_one l1).\nintros a l1; elim l1; simpl in |- *; auto.\nintros H; case H.\nintros a0 l H [H0| H0]; auto.\nexists l; left; subst; auto.\ncase H; auto.\nintros x H1; exists (a0 :: x); right; auto.\napply\n (in_map (fun p : A * list A => (fst p, a0 :: snd p)) (split_one l) (a, x));\n auto.\nQed.\n\n(************************************** \n   An auxillary function to generate all permutations\n   **************************************)\n \nFixpoint all_permutations_aux (l : list A) (n : nat) {struct n} :\n list (list A) :=\n  match n with\n  | O => nil :: nil\n  | S n1 =>\n      flat_map\n        (fun p : A * list A =>\n         map (cons (fst p)) (all_permutations_aux (snd p) n1)) (\n        split_one l)\n  end.\n(************************************** \n   Generate all the permutations\n   **************************************)\n \nDefinition all_permutations (l : list A) := all_permutations_aux l (length l).\n \n(************************************** \n   All the elements of the list are permutations\n   **************************************)\n\nLet all_permutations_aux_permutation :\n  forall (n : nat) (l1 l2 : list A),\n  n = length l2 -> In l1 (all_permutations_aux l2 n) -> permutation l1 l2.\nintros n; elim n; simpl in |- *; auto.\nintros l1 l2; case l2.\nsimpl in |- *; intros H0 [H1| H1].\nrewrite <- H1; auto.\ncase H1.\nsimpl in |- *; intros; discriminate.\nintros n0 H l1 l2 H0 H1.\ncase in_flat_map_ex with (1 := H1).\nclear H1; intros x; case x; clear x; intros a1 l3 (H1, H2).\ncase in_map_inv with (1 := H2).\nsimpl in |- *; intros y (H3, H4).\nrewrite H4; auto.\napply permutation_trans with (a1 :: l3); auto.\napply permutation_skip; auto.\napply H with (2 := H3).\napply eq_add_S.\napply trans_equal with (1 := H0).\nchange (length l2 = length (a1 :: l3)) in |- *.\napply permutation_length; auto.\napply permutation_sym; apply split_one_permutation; auto.\napply split_one_permutation; auto.\nQed.\n \nTheorem all_permutations_permutation :\n forall l1 l2 : list A, In l1 (all_permutations l2) -> permutation l1 l2.\nintros l1 l2 H; apply all_permutations_aux_permutation with (n := length l2);\n auto.\nQed.\n \n(************************************** \n   A permutation is in the list\n   **************************************)\n\nLet permutation_all_permutations_aux :\n  forall (n : nat) (l1 l2 : list A),\n  n = length l2 -> permutation l1 l2 -> In l1 (all_permutations_aux l2 n).\nintros n; elim n; simpl in |- *; auto.\nintros l1 l2; case l2.\nintros H H0; rewrite permutation_nil_inv with (1 := H0); auto with datatypes.\nsimpl in |- *; intros; discriminate.\nintros n0 H l1; case l1.\nintros l2 H0 H1;\n rewrite permutation_nil_inv with (1 := permutation_sym _ _ H1) in H0;\n discriminate.\nclear l1; intros a1 l1 l2 H1 H2.\ncase (split_one_in_ex a1 l2); auto.\napply permutation_in with (1 := H2); auto with datatypes.\nintros x H0.\napply in_flat_map with (b := (a1, x)); auto.\napply in_map; simpl in |- *.\napply H; auto.\napply eq_add_S.\napply trans_equal with (1 := H1).\nchange (length l2 = length (a1 :: x)) in |- *.\napply permutation_length; auto.\napply permutation_sym; apply split_one_permutation; auto.\napply permutation_inv with (a := a1).\napply permutation_trans with (1 := H2).\napply permutation_sym; apply split_one_permutation; auto.\nQed.\n \nTheorem permutation_all_permutations :\n forall l1 l2 : list A, permutation l1 l2 -> In l1 (all_permutations l2).\nintros l1 l2 H; unfold all_permutations in |- *;\n apply permutation_all_permutations_aux; auto.\nQed.\n\n(************************************** \n   Permutation is decidable\n   **************************************)\n \nDefinition permutation_dec :\n  (forall a b : A, {a = b} + {a <> b}) ->\n  forall l1 l2 : list A, {permutation l1 l2} + {~ permutation l1 l2}.\nintros H l1 l2.\ncase (In_dec (list_eq_dec H) l1 (all_permutations l2)).\nintros i; left; apply all_permutations_permutation; auto.\nintros i; right; contradict i; apply permutation_all_permutations; auto.\nDefined.\n \nEnd permutation.\n\n(************************************** \n   Hints\n   **************************************)\n\nGlobal Hint Constructors permutation : core.\nGlobal Hint Resolve permutation_refl : core.\nGlobal Hint Resolve permutation_app_comp : core.\nGlobal Hint Resolve permutation_app_swap : core.\n\n(************************************** \n   Implicits\n   **************************************)\n\nArguments permutation [A] _ _.\nArguments split_one [A] _.\nArguments all_permutations [A] _.\nArguments permutation_dec [A].\n\n(************************************** \n   Permutation is compatible with map\n   **************************************)\n \nTheorem permutation_map :\n forall (A B : Set) (f : A -> B) l1 l2,\n permutation l1 l2 -> permutation (map f l1) (map f l2).\nintros A B f l1 l2 H; elim H; simpl in |- *; auto.\nintros l0 l3 l4 H0 H1 H2 H3; apply permutation_trans with (2 := H3); auto.\nQed.\nGlobal Hint Resolve permutation_map : core.\n \n(************************************** \n  Permutation  of a map can be inverted\n  *************************************)\n\nLocal Definition permutation_map_ex_aux :\n  forall (A B : Set) (f : A -> B) l1 l2 l3,\n  permutation l1 l2 ->\n  l1 = map f l3 -> exists l4, permutation l4 l3 /\\ l2 = map f l4.\nintros A1 B1 f l1 l2 l3 H; generalize l3; elim H; clear H l1 l2 l3.\nintros l3; case l3; simpl in |- *; auto.\nintros H; exists (nil (A:=A1)); auto.\nintros; discriminate.\nintros a0 l1 l2 H H0 l3; case l3; simpl in |- *; auto.\nintros; discriminate.\nintros a1 l H1; case (H0 l); auto.\ninjection H1; auto.\nintros l5 (H2, H3); exists (a1 :: l5); split; simpl in |- *; auto.\ninjection H1; intros; subst; auto.\nintros a0 b l l3; case l3.\nintros; discriminate.\nintros a1 l0; case l0; simpl in |- *.\nintros; discriminate.\nintros a2 l1 H; exists (a2 :: a1 :: l1); split; simpl in |- *; auto.\ninjection H; intros; subst; auto.\nintros l1 l2 l3 H H0 H1 H2 l0 H3.\ncase H0 with (1 := H3); auto.\nintros l4 (HH1, HH2).\ncase H2 with (1 := HH2); auto.\nintros l5 (HH3, HH4); exists l5; split; auto.\napply permutation_trans with (1 := HH3); auto.\nQed.\n \nTheorem permutation_map_ex :\n forall (A B : Set) (f : A -> B) l1 l2,\n permutation (map f l1) l2 ->\n exists l3, permutation l3 l1 /\\ l2 = map f l3.\nintros A0 B f l1 l2 H; apply permutation_map_ex_aux with (l1 := map f l1);\n auto.\nQed.\n\n(************************************** \n   Permutation is compatible with flat_map\n **************************************)\n \nTheorem permutation_flat_map :\n forall (A B : Set) (f : A -> list B) l1 l2,\n permutation l1 l2 -> permutation (flat_map f l1) (flat_map f l2).\nintros A B f l1 l2 H; elim H; simpl in |- *; auto.\nintros a b l; auto.\nrepeat rewrite <- app_ass.\napply permutation_app_comp; auto.\nintros k3 l4 l5 H0 H1 H2 H3; apply permutation_trans with (1 := H1); auto.\nQed.\n", "meta": {"author": "dderjoel", "repo": "base", "sha": "2aa122fb618100b7fed3119ea3cef73cec5bf4a5", "save_path": "github-repos/coq/dderjoel-base", "path": "github-repos/coq/dderjoel-base/base-2aa122fb618100b7fed3119ea3cef73cec5bf4a5/fiat-crypto/coqprime/src/Coqprime/List/Permutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.730777935902215}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** Extraction of breadth-first numbering algorithm from Coq to Ocaml \n\n       see http://okasaki.blogspot.com/2008/07/breadth-first-numbering-algorithm-in.html\n       and https://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/jfp95queue.pdf\n       and https://www.cs.cmu.edu/~rwh/theses/okasaki.pdf\n       and https://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/icfp00bfn.pdf\n\n*)\n\nRequire Import List Arith Omega Wellfounded.\nRequire Import list_utils wf_utils bt bft.\n\nSet Implicit Arguments.\n\nImplicit Types (a n x: nat).\n\nSection seq_an.\n\n  (* seq_an a n = [a;a+1;...;a+(n-1)] *)\n\n  Fixpoint seq_an a n: list nat :=\n    match n with\n      | 0    => nil\n      | S n  => a::seq_an (S a) n\n    end.\n\n  Fact seq_an_length a n : length (seq_an a n) = n.\n  Proof. revert a; induction n; simpl; intros; f_equal; auto. Qed.\n\n  Fact seq_an_spec a n x : In x (seq_an a n) <-> a <= x < a+n.\n  Proof. \n    revert x a; induction n as [ | n IHn ]; intros x a; simpl;\n      [ | rewrite IHn ]; omega.\n  Qed.\n\n  Fixpoint is_seq_from n (l: list nat) { struct l }: Prop :=\n    match l with  \n      | nil  => True\n      | x::l => n=x /\\ is_seq_from (S n) l\n    end.\n\n  Theorem is_seq_from_spec a (l: list nat): is_seq_from a l <-> exists n, l = seq_an a n.\n  Proof.\n    revert a; induction l as [ | x l IH ]; intros a; simpl.\n    + split; auto; exists 0; auto.\n    + rewrite IH; split.\n      * intros (? & n & Hn); subst x; exists (S n); subst; auto.\n      * intros ([ | n ] & ?); subst; try discriminate.\n        simpl in H; inversion H; subst; split; auto.\n        exists n; auto.\n  Qed.\n\nEnd seq_an.\n\n(** Of course, this needs to be replaced by a queue to obtain something efficient *)\n\nDefinition list_snoc_match (X: Type) (l: list X) : 2 <= length l -> { x : X & { y : _ & { m | l = m++y::x::nil } } }.\nProof.\n  rewrite <- (rev_involutive l), rev_length.\n  destruct (rev l) as [ | x [ | y l' ] ]; simpl; try omega; intros _.\n  exists x, y, (rev l'); rewrite app_ass; simpl; auto.\nDefined.\n\nSection bfn.\n\n  Variable (X : Type).\n\n  Implicit Types (t : bt X) (l: list(bt X)).\n\n  (* the forest (list of bt nat) is a breadth first numbering from n if\n     its breadth first traversal yields [n;n+1;....;m[ for some m\n   *)\n\n  Definition is_bfn_from n (l: list (bt nat)): Prop := is_seq_from n (bft_f l).\n\n  (* Breadth First Numbering: maps a forest X to a forest nat such that\n          1) the two forests are of the same shape\n          2) the result is a breadth first numbering from n  \n   *)\n\n  Definition bfn_f n l : { m | l ~lt m /\\ is_bfn_from n m }.\n  Proof.\n    induction on n l as bfn_f with measure (lsum l).\n    refine (match l as l' return l = l' -> _ with\n      | nil              => fun H => exist _ nil _\n      | leaf x :: ll     => fun H => let (mm,Hm) := bfn_f (S n) ll _ in exist _ (leaf n::mm) _\n      | node a x b :: ll => fun H => let (mm,Hmm) := bfn_f (S n) (ll++a::b::nil) _ in \n                                     match list_snoc_match mm _ with\n                                       | existT _ v (existT _ u (exist _ m Hm)) => exist _ (node u n v::m) _\n                                     end\n    end eq_refl).\n    1,2,4,5: cycle 1.\n\n    + subst; simpl; auto.\n    + subst; simpl; rewrite lsum_app; simpl; omega.\n\n    + apply proj1, Forall2_length in Hmm.\n      rewrite <- Hmm, app_length; simpl; omega.\n    + subst; split.\n      * constructor.\n      * red; rewrite bft_f_fix_0; simpl; auto.\n    + destruct Hm as (H1 & H2).\n      subst; split; auto.\n      red in H2 |- *; rewrite bft_f_fix_3.\n      simpl; rewrite <- app_nil_end; auto.\n    + subst; destruct Hmm as (H1 & H2).\n      Forall2 inv H1 as H3.\n      * Forall2 inv H1 as H4.\n        Forall2 inv H1 as H5.\n        split; auto.\n        red in H2 |- *. \n        rewrite bft_f_fix_3; simpl; auto.\n      * apply Forall2_length in H1. \n        do 2 rewrite app_length in H1; simpl in H1; omega.\n  Defined.\n\n  Section bfn.\n\n    Let bfn_full t : { t' | t ~t t' /\\ is_seq_from 0 (bft_std t') }.\n    Proof.\n      refine (match @bfn_f 0 (t::nil) with\n        | exist _ l Hl      => \n        match l as l' return l = l' -> _ with\n          | nil   => fun E => _\n          | t'::l => fun E => exist _ t' _\n        end eq_refl\n      end); simpl in *.\n      + exfalso; subst; apply proj1 in Hl; inversion Hl.\n      + subst; destruct Hl as (H1 & H2).\n        Forall2 inv H1 as H3.\n        Forall2 inv H1 as H1.\n        subst; split; auto.\n        red in H2.\n        rewrite <- bft_std_eq_bft; auto.\n    Qed.\n\n    Definition bfn t := proj1_sig (bfn_full t).\n\n    Fact bfn_spec_1 t : t ~t bfn t.\n    Proof. apply (proj2_sig (bfn_full t)). Qed.\n\n    Fact bfn_spec_2 t : exists n, bft_std (bfn t) = seq_an 0 n.\n    Proof. apply is_seq_from_spec, (proj2_sig (bfn_full t)). Qed.\n\n  End bfn.\n\nEnd bfn.\n\nRecursive Extraction bfn.\n\nCheck bfn.\nCheck bfn_spec_1.\nCheck bfn_spec_2.\n             \n\n", "meta": {"author": "DmxLarchey", "repo": "Breadth-First-Numbering", "sha": "7f0fa3561968bef7f927d6bae4b1da6a67236762", "save_path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering", "path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering/Breadth-First-Numbering-7f0fa3561968bef7f927d6bae4b1da6a67236762/bfn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7307779279681104}}
{"text": "Require Import Coq.Arith.Div2.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.ZArith.ZArith.\nRequire Import bbv.N_Z_nat_conversions.\nRequire Export bbv.Nomega.\n\nSet Implicit Arguments.\n\nFixpoint mod2 (n : nat) : bool :=\n  match n with\n    | 0 => false\n    | 1 => true\n    | S (S n') => mod2 n'\n  end.\n\nLtac rethink :=\n  match goal with\n    | [ H : ?f ?n = _ |- ?f ?m = _ ] => replace m with n; simpl; auto\n  end.\n\nTheorem mod2_S_double : forall n, mod2 (S (2 * n)) = true.\n  induction n; simpl; intuition; rethink.\nQed.\n\nTheorem mod2_double : forall n, mod2 (2 * n) = false.\n  induction n; simpl; intuition; rewrite <- plus_n_Sm; rethink.\nQed.\n\nTheorem div2_double : forall n, div2 (2 * n) = n.\n  induction n; simpl; intuition; rewrite <- plus_n_Sm; f_equal; rethink.\nQed.\n\nTheorem div2_S_double : forall n, div2 (S (2 * n)) = n.\n  induction n; simpl; intuition; f_equal; rethink.\nQed.\n\nNotation pow2 := (Nat.pow 2).\n\nFixpoint Npow2 (n : nat) : N :=\n  match n with\n    | O => 1\n    | S n' => 2 * Npow2 n'\n  end%N.\n\nTheorem untimes2 : forall n, n + (n + 0) = 2 * n.\n  auto.\nQed.\n\nSection strong.\n  Variable P : nat -> Prop.\n\n  Hypothesis PH : forall n, (forall m, m < n -> P m) -> P n.\n\n  Lemma strong' : forall n m, m <= n -> P m.\n    induction n; simpl; intuition; apply PH; intuition.\n    elimtype False; lia.\n  Qed.\n\n  Theorem strong : forall n, P n.\n    intros; eapply strong'; eauto.\n  Qed.\nEnd strong.\n\nTheorem div2_odd : forall n,\n  mod2 n = true\n  -> n = S (2 * div2 n).\n  induction n as [n] using strong; simpl; intuition.\n\n  destruct n as [|n]; simpl in *.\n    discriminate.\n  destruct n as [|n]; simpl in *; intuition.\n  do 2 f_equal.\n  replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto.\nQed.\n\nTheorem div2_even : forall n,\n  mod2 n = false\n  -> n = 2 * div2 n.\n  induction n as [n] using strong; simpl; intuition.\n\n  destruct n as [|n]; simpl in *; intuition.\n  destruct n as [|n]; simpl in *.\n    discriminate.\n  f_equal.\n  replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto.\nQed.\n\nTheorem drop_mod2 : forall n k,\n  2 * k <= n\n  -> mod2 (n - 2 * k) = mod2 n.\n  induction n as [n] using strong; intros.\n\n  do 2 (destruct n; simpl in *; repeat rewrite untimes2 in *; intuition).\n\n  destruct k; simpl in *; intuition.\n\n  destruct k; simpl; intuition.\n  rewrite <- plus_n_Sm.\n  repeat rewrite untimes2 in *.\n  simpl; auto.\n  apply H; lia.\nQed.\n\nTheorem div2_minus_2 : forall n k,\n  2 * k <= n\n  -> div2 (n - 2 * k) = div2 n - k.\n  induction n as [n] using strong; intros.\n\n  do 2 (destruct n; simpl in *; intuition; repeat rewrite untimes2 in *).\n  destruct k; simpl in *; intuition.\n\n  destruct k; simpl in *; intuition.\n  rewrite <- plus_n_Sm.\n  apply H; lia.\nQed.\n\nTheorem div2_bound : forall k n,\n  2 * k <= n\n  -> k <= div2 n.\n  intros ? n H; case_eq (mod2 n); intro Heq.\n\n  rewrite (div2_odd _ Heq) in H.\n  lia.\n\n  rewrite (div2_even _ Heq) in H.\n  lia.\nQed.\n\nLemma two_times_div2_bound: forall n, 2 * Nat.div2 n <= n.\nProof.\n  eapply strong. intros n IH.\n  destruct n.\n  - constructor.\n  - destruct n.\n    + simpl. constructor. constructor.\n    + simpl (Nat.div2 (S (S n))).\n      specialize (IH n). lia.\nQed.\n\nLemma div2_compat_lt_l: forall a b, b < 2 * a -> Nat.div2 b < a.\nProof.\n  induction a; intros.\n  - lia.\n  - destruct b.\n    + simpl. lia.\n    + destruct b.\n      * simpl. lia.\n      * simpl. apply lt_n_S. apply IHa. lia.\nQed.\n\n(* otherwise b is made implicit, while a isn't, which is weird *)\nArguments div2_compat_lt_l {_} {_} _.\n\nLemma pow2_add_mul: forall a b,\n  pow2 (a + b) = (pow2 a) * (pow2 b).\nProof.\n  induction a; destruct b; firstorder auto with arith; simpl.\n  repeat rewrite Nat.add_0_r.\n  rewrite Nat.mul_1_r; auto.\n  repeat rewrite Nat.add_0_r.\n  rewrite IHa.\n  simpl.\n  repeat rewrite Nat.add_0_r.\n  rewrite Nat.mul_add_distr_r; auto.\nQed.\n\nLemma mult_pow2_bound: forall a b x y,\n  x < pow2 a -> y < pow2 b -> x * y < pow2 (a + b).\nProof.\n  intros.\n  rewrite pow2_add_mul.\n  apply Nat.mul_lt_mono_nonneg; lia.\nQed.\n\nLemma mult_pow2_bound_ex: forall a c x y,\n  x < pow2 a -> y < pow2 (c - a) -> c >= a -> x * y < pow2 c.\nProof.\n  intros.\n  replace c with (a + (c - a)) by lia.\n  apply mult_pow2_bound; auto.\nQed.\n\nLemma lt_mul_mono' : forall c a b,\n  a < b -> a < b * (S c).\nProof.\n  induction c; intros.\n  rewrite Nat.mul_1_r; auto.\n  rewrite Nat.mul_succ_r.\n  apply lt_plus_trans.\n  apply IHc; auto.\nQed.\n\nLemma lt_mul_mono : forall a b c,\n  c <> 0 -> a < b -> a < b * c.\nProof.\n  intros.\n  replace c with (S (c - 1)) by lia.\n  apply lt_mul_mono'; auto.\nQed.\n\nLemma zero_lt_pow2 : forall sz, 0 < pow2 sz.\nProof.\n  induction sz; simpl; lia.\nQed.\n\nLemma one_lt_pow2:\n  forall n,\n    1 < pow2 (S n).\nProof.\n  intros.\n  induction n.\n  simpl; lia.\n  remember (S n); simpl.\n  lia.\nQed.\n\nLemma one_le_pow2 : forall sz, 1 <= pow2 sz.\nProof.\n  intros. pose proof (zero_lt_pow2 sz). lia.\nQed.\n\nLemma pow2_ne_zero: forall n, pow2 n <> 0.\nProof.\n  intros.\n  pose proof (zero_lt_pow2 n).\n  lia.\nQed.\n\nLemma mul2_add : forall n, n * 2 = n + n.\nProof.\n  induction n; firstorder auto with zarith.\nQed.\n\nLemma pow2_le_S : forall sz, (pow2 sz) + 1 <= pow2 (sz + 1).\nProof.\n  induction sz; simpl; auto.\n  repeat rewrite Nat.add_0_r.\n  rewrite pow2_add_mul.\n  repeat rewrite mul2_add.\n  pose proof (zero_lt_pow2 sz).\n  lia.\nQed.\n\nLemma pow2_bound_mono: forall a b x,\n  x < pow2 a -> a <= b -> x < pow2 b.\nProof.\n  intros.\n  replace b with (a + (b - a)) by lia.\n  rewrite pow2_add_mul.\n  apply lt_mul_mono; auto.\n  pose proof (zero_lt_pow2 (b - a)).\n  lia.\nQed.\n\nLemma pow2_inc : forall n m, n < m -> pow2 n < pow2 m.\nProof.\n  intros n m; revert n; induction m as [|m IH]; intros n nLm; [lia|].\n  destruct n; [now apply one_lt_pow2|].\n  assert (H : pow2 n < pow2 m) by (apply IH; lia).\n  simpl; lia.\nQed.\n\nLemma pow2_S: forall x, pow2 (S x) = 2 * pow2 x.\nProof. intros. reflexivity. Qed.\n\nLemma mod2_S_S : forall n,\n  mod2 (S (S n)) = mod2 n.\nProof.\n  intros.\n  destruct n; auto; destruct n; auto.\nQed.\n\nLemma mod2_S_not : forall n,\n  mod2 (S n) = if (mod2 n) then false else true.\nProof.\n  intros.\n  induction n; auto.\n  rewrite mod2_S_S.\n  destruct (mod2 n); replace (mod2 (S n)); auto.\nQed.\n\nLemma mod2_S_eq : forall n k,\n  mod2 n = mod2 k ->\n  mod2 (S n) = mod2 (S k).\nProof.\n  intros.\n  do 2 rewrite mod2_S_not.\n  rewrite H.\n  auto.\nQed.\n\nTheorem drop_mod2_add : forall n k,\n  mod2 (n + 2 * k) = mod2 n.\nProof.\n  intros.\n  induction n.\n  simpl.\n  rewrite Nat.add_0_r.\n  replace (k + k) with (2 * k) by lia.\n  apply mod2_double.\n  replace (S n + 2 * k) with (S (n + 2 * k)) by lia.\n  apply mod2_S_eq; auto.\nQed.\n\nLemma mod2sub: forall a b,\n  b <= a ->\n  mod2 (a - b) = xorb (mod2 a) (mod2 b).\nProof.\n  intros. remember (a - b) as c. revert dependent b. revert a. revert c.\n  change (forall c,\n    (fun c => forall a b, b <= a -> c = a - b -> mod2 c = xorb (mod2 a) (mod2 b)) c).\n  apply strong.\n  intros c IH a b AB N.\n  destruct c.\n  - assert (a=b) by lia. subst. rewrite Bool.xorb_nilpotent. reflexivity.\n  - destruct c.\n    + assert (a = S b) by lia. subst a. simpl (mod2 1). rewrite mod2_S_not.\n      destruct (mod2 b); reflexivity.\n    + destruct a; [lia|].\n      destruct a; [lia|].\n      simpl.\n      apply IH; lia.\nQed.\n\nTheorem mod2_pow2_twice: forall n,\n  mod2 (pow2 n + (pow2 n + 0)) = false.\nProof.\n  intros.\n  replace (pow2 n + (pow2 n + 0)) with (2 * pow2 n) by lia.\n  apply mod2_double.\nQed.\n\nTheorem div2_plus_2 : forall n k,\n  div2 (n + 2 * k) = div2 n + k.\nProof.\n  induction n; intros.\n  simpl.\n  rewrite Nat.add_0_r.\n  replace (k + k) with (2 * k) by lia.\n  apply div2_double.\n  replace (S n + 2 * k) with (S (n + 2 * k)) by lia.\n  destruct (Even.even_or_odd n).\n  - rewrite <- even_div2.\n    rewrite <- even_div2 by auto.\n    apply IHn.\n    apply Even.even_even_plus; auto.\n    apply Even.even_mult_l; repeat constructor.\n\n  - rewrite <- odd_div2.\n    rewrite <- odd_div2 by auto.\n    rewrite IHn.\n    lia.\n    apply Even.odd_plus_l; auto.\n    apply Even.even_mult_l; repeat constructor.\nQed.\n\nLemma pred_add:\n  forall n, n <> 0 -> pred n + 1 = n.\nProof.\n  intros; rewrite pred_of_minus; lia.\nQed.\n\nLemma pow2_zero: forall sz, (pow2 sz > 0)%nat.\nProof.\n  induction sz; simpl; auto; lia.\nQed.\n\nTheorem Npow2_nat : forall n, nat_of_N (Npow2 n) = pow2 n.\n  induction n as [|n IHn]; simpl; intuition.\n  rewrite <- IHn; clear IHn.\n  case_eq (Npow2 n); intuition; zify; intuition.\nQed.\n\nTheorem pow2_N : forall n, Npow2 n = N.of_nat (pow2 n).\nProof.\n  intro n. apply nat_of_N_eq. rewrite Nat2N.id. apply Npow2_nat.\nQed.\n\nLemma Z_of_N_Npow2: forall n, Z.of_N (Npow2 n) = (2 ^ Z.of_nat n)%Z.\nProof.\n  intros.\n  rewrite pow2_N.\n  rewrite nat_N_Z.\n  rewrite Nat2Z.inj_pow.\n  reflexivity.\nQed.\n\nLemma pow2_S_z:\n  forall n, Z.of_nat (pow2 (S n)) = (2 * Z.of_nat (pow2 n))%Z.\nProof.\n  intros.\n  replace (2 * Z.of_nat (pow2 n))%Z with\n      (Z.of_nat (pow2 n) + Z.of_nat (pow2 n))%Z by lia.\n  simpl.\n  repeat rewrite Nat2Z.inj_add.\n  ring.\nQed.\n\nLemma pow2_le:\n  forall n m, (n <= m)%nat -> (pow2 n <= pow2 m)%nat.\nProof.\n  intros.\n  assert (exists s, n + s = m) by (exists (m - n); lia).\n  destruct H0; subst.\n  rewrite pow2_add_mul.\n  pose proof (pow2_zero x).\n  replace (pow2 n) with (pow2 n * 1) at 1 by lia.\n  apply mult_le_compat_l.\n  lia.\nQed.\n\nLemma Zabs_of_nat:\n  forall n, Z.abs (Z.of_nat n) = Z.of_nat n.\nProof.\n  unfold Z.of_nat; intros.\n  destruct n; auto.\nQed.\n\nLemma Npow2_not_zero:\n  forall n, Npow2 n <> 0%N.\nProof.\n  induction n; simpl; intros; [discriminate|].\n  destruct (Npow2 n); auto.\n  discriminate.\nQed.\n\nLemma Npow2_S:\n  forall n, Npow2 (S n) = (Npow2 n + Npow2 n)%N.\nProof.\n  simpl; intros.\n  destruct (Npow2 n); auto.\n  rewrite <-Pos.add_diag.\n  reflexivity.\nQed.\n\nLemma Npow2_pos: forall a,\n    (0 < Npow2 a)%N.\nProof.\n  intros.\n  destruct (Npow2 a) eqn: E.\n  - exfalso. apply (Npow2_not_zero a). assumption.\n  - constructor.\nQed.\n\nLemma minus_minus: forall a b c,\n  c <= b <= a ->\n  a - (b - c) = a - b + c.\nProof. intros. lia. Qed.\n\nLemma even_odd_destruct: forall n,\n  (exists a, n = 2 * a) \\/ (exists a, n = 2 * a + 1).\nProof.\n  induction n.\n  - left. exists 0. reflexivity.\n  - destruct IHn as [[a E] | [a E]].\n    + right. exists a. lia.\n    + left. exists (S a). lia.\nQed.\n\nLemma mul_div_undo: forall i c,\n    c <> 0 ->\n    c * i / c = i.\nProof.\n  intros.\n  pose proof (Nat.div_mul_cancel_l i 1 c) as P.\n  rewrite Nat.div_1_r in P.\n  rewrite Nat.mul_1_r in P.\n  apply P; auto.\nQed.\n\nLemma mod_add_r: forall a b,\n    b <> 0 ->\n    (a + b) mod b = a mod b.\nProof.\n  intros. rewrite <- Nat.add_mod_idemp_r by lia.\n  rewrite Nat.mod_same by lia.\n  rewrite Nat.add_0_r.\n  reflexivity.\nQed.\n\nLemma mod2_cases: forall (n: nat), n mod 2 = 0 \\/ n mod 2 = 1.\nProof.\n  intros.\n  assert (n mod 2 < 2). {\n    apply Nat.mod_upper_bound. congruence.\n  }\n  lia.\nQed.\n\nLemma div_mul_undo: forall a b,\n    b <> 0 ->\n    a mod b = 0 ->\n    a / b * b = a.\nProof.\n  intros.\n  pose proof Nat.div_mul_cancel_l as A. specialize (A a 1 b).\n  replace (b * 1) with b in A by lia.\n  rewrite Nat.div_1_r in A.\n  rewrite mult_comm.\n  rewrite <- Nat.divide_div_mul_exact; try assumption.\n  - apply A; congruence.\n  - apply Nat.mod_divide; assumption.\nQed.\n\nLemma Smod2_1: forall k, S k mod 2 = 1 -> k mod 2 = 0.\nProof.\n  intros k C.\n  change (S k) with (1 + k) in C.\n  rewrite Nat.add_mod in C by congruence.\n  pose proof (Nat.mod_upper_bound k 2).\n  assert (k mod 2 = 0 \\/ k mod 2 = 1) as E by lia.\n  destruct E as [E | E]; [assumption|].\n  rewrite E in C. simpl in C. discriminate.\nQed.\n\nLemma mod_0_r: forall (m: nat),\n    m mod 0 = match (1 mod 0) with | 0 => 0 | _ => m end.\nProof.\n  intros. reflexivity.\nQed.\n\nLemma sub_mod_0: forall (a b m: nat),\n    a mod m = 0 ->\n    b mod m = 0 ->\n    (a - b) mod m = 0.\nProof.\n  intros. assert (m = 0 \\/ m <> 0) as C by lia. destruct C as [C | C].\n  - subst. rewrite mod_0_r in *. simpl in *. now subst.\n  - assert (a - b = 0 \\/ b < a) as D by lia. destruct D as [D | D].\n    + rewrite D. apply Nat.mod_0_l. assumption.\n    + apply Nat2Z.inj. simpl.\n      rewrite Zdiv.mod_Zmod by assumption.\n      rewrite Nat2Z.inj_sub by lia.\n      rewrite Zdiv.Zminus_mod.\n      rewrite <-! Zdiv.mod_Zmod by assumption.\n      rewrite H. rewrite H0.\n      apply Z.mod_0_l.\n      lia.\nQed.\n\nLemma mul_div_exact: forall (a b: nat),\n    b <> 0 ->\n    a mod b = 0 ->\n    b * (a / b) = a.\nProof.\n  intros. edestruct Nat.div_exact as [_ P]; [eassumption|].\n  specialize (P H0). symmetry. exact P.\nQed.\n", "meta": {"author": "CTSRD-CHERI", "repo": "sail-cheri-mips", "sha": "13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724", "save_path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips", "path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips/sail-cheri-mips-13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724/prover_snapshots/coq/cheri-mips-snapshot/bbv/src/bbv/NatLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7307278211150141}}
{"text": "Require Import Coq.Init.Prelude Coq.ZArith.ZArith. Local Open Scope Z_scope.\n\nDefinition step (n : Z) :=\n  if Z.eqb n 1 then None else\n  if Z.even n\n  then Some (Z.div2 n)\n  else Some (3*n + 1).\n\nLtac collatz :=\n  intros;\n  repeat\n  lazymatch goal with\n  | H: _ = ?RHS |- _ =>\n    lazymatch RHS with\n    | Some ?n =>\n    let H := lazymatch goal with H:n = _ |- _ => H end in\n    first\n      [\n        let n' := open_constr:(_) in\n        let n'' := fresh \"n\" in\n        let Hn'' := fresh \"H\" n'' in\n        refine (let n'' : Z := n' in let Hn'' : n'' = n' := eq_refl in _); clearbody Hn'';\n        eassert (step n = Some n'') by (rewrite H; cbv; refine eq_refl); clearbody n''\n      | exists n; rewrite H; refine eq_refl ]\n    end\n  end.\n\n(* 350 steps *)\nGoal forall n, n = 77031 -> Some n = Some n -> exists n, step n = None.\nTime collatz. Time Qed.\n(*\nFinished transaction in 7.02 secs (6.882u,0.102s) (successful)\nFinished transaction in 0.119 secs (0.119u,0.s) (successful)\n*)\n\n(* 685 steps *)\nGoal forall n, n = 8400511 -> Some n = Some n -> exists n, step n = None.\nTime collatz. Time Qed.\n(*\nFinished transaction in 37.63 secs (37.103u,0.351s) (successful)\nFinished transaction in 0.286 secs (0.282u,0.003s) (successful)\n*)", "meta": {"author": "andres-erbsen", "repo": "coq-experiments", "sha": "2018edd397a23c0429d316c96e86f9be7a9678f1", "save_path": "github-repos/coq/andres-erbsen-coq-experiments", "path": "github-repos/coq/andres-erbsen-coq-experiments/coq-experiments-2018edd397a23c0429d316c96e86f9be7a9678f1/experiments/bench/collatz_rewrite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374122, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.730696839818241}}
{"text": "\n\nInductive and (P Q : Prop) : Prop  :=\n | conj : P -> Q -> and P Q\n.\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n\nInductive or (P Q : Prop) : Prop  :=\n | orl : P -> or P Q\n | orr : Q -> or P Q\n.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n\n\nInductive False : Prop := .\n(* nothing can prove False .  False is a inductive/type/proposition with no constructor/value/proof *)\n\nInductive True : Prop := truth : True.\n\nTheorem Truth : True.\nProof. apply truth. Qed.\n(*\napply :proof\ntrue witnesses True\ntrue proves proposition True\ntrue is of type True\n*)\n\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. assumption. Qed.\n\n\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop,\n  ~~P -> P.\nDefinition excluded_middle := 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\n\n\nTheorem peirce_to_classic : peirce -> classic.\nunfold classic. unfold peirce. unfold not. \nintro H. intro P. intro A. (* CONTRAPOSITIVE *)\n\nTheorem classicals :\n(*\npeirce <-> classic <-> excluded_middle <-> de_morgan_not_and_not <-> implies_to_or. \n*)", "meta": {"author": "sboosali", "repo": "coq", "sha": "c09f90a114ed7948f8cdf75828832e7d01093a84", "save_path": "github-repos/coq/sboosali-coq", "path": "github-repos/coq/sboosali-coq/coq-c09f90a114ed7948f8cdf75828832e7d01093a84/Classical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7306967283329661}}
{"text": "Require Import Coq.Logic.ClassicalFacts.\nRequire Import Essentials.Omega.\nRequire Import Essentials.Notations.\nRequire Import Essentials.Facts_Tactics Essentials.Definitions.\nRequire Import Lattice.PartialOrder Lattice.MLattice.\nRequire Import Metrics.Mappings.\n\nRequire Import Coq.Logic.Classical_Pred_Type.\n\n(** Propositional extensionality assumed locally. *)\nLocal Axiom PropExt : prop_extensionality.\n\nDelimit Scope bisected_scope with bisected.\n\nLocal Open Scope bisected_scope.\n\n(** Bisected distance. Distances are 2⁻ⁿ for n a natural number or zero.\nIntuitively, bisected distances are sequences of Prop such that whenever an element is\ninhabitted then so are all elements before it. In other words, they are of the form\n\n#\n<pre>\nTrue, True, True, True, True, True, True, ...\nor\nTrue, True, True, False, False, False, False, False, ...\n|...............|\n     n times\n</pre>\n#\nwhere True and False are archetypal inhabitted and uninhabitted Propositions.\n\nIn this encoding, a sequence with n inhabitted elements at its beginning represents\n2⁻ⁿ and the sequence of all trues represents zero (2^{-∞}).\n *)\nRecord BiDist : Type :=\n  {\n    BD_agree :> nat → Prop;\n    BD_decreases : ∀ n m, n ≤ m → BD_agree m → BD_agree n\n  }\n.\n\nArguments BD_agree _ _ : assert.\nArguments BD_decreases _ _ _ _ _ : assert.\n\nLocal Hint Resolve BD_decreases.\n\n(** Two bisected distances are equal if they are equal as sequences. *)\nTheorem BiDist_eq_simpl (d d' : BiDist) : BD_agree d = BD_agree d' → d = d'.\nProof.\n  intros H.\n  destruct d; destruct d'; cbn in *.\n  ElimEq.\n  PIR; trivial.\nQed.  \n\n(** The less than equal relation. *)\nDefinition BD_LE (d d' : BiDist) : Prop :=\n  ∀ n, d' n → d n\n.\n\nNotation \"d ⊑ d'\" := (BD_LE d d') : bisected_scope.\n\n(** The less than relation. *)\nDefinition BD_LT (d d' : BiDist) : Prop :=\n  d ⊑ d' ∧ d ≠ d'\n.\n                    \nNotation \"d ⊏ d'\" := (BD_LT d d') : bisected_scope.\n\n(** The bottom element (zero). *)\nDefinition BD_bot : BiDist :=\n  {|\n    BD_agree := fun _ => True;\n    BD_decreases := fun _ _ _ _ => I\n  |}\n.\n\nNotation \"⊥\" := BD_bot : bisected_scope.\n\n(** ⊥ is the least element. *)\nTheorem BD_bot_LE : ∀ d, ⊥ ⊑ d.\nProof.\n  intros d n.\n  cbn; tauto.  \nQed.\n\nLocal Hint Resolve BD_bot_LE.\n\n(** The top element (one). *)\nDefinition BD_top : BiDist :=\n  {|\n    BD_agree := fun _ => False;\n    BD_decreases := fun _ _ _ H => False_rect _ H\n  |}\n.\n\nNotation \"⊤\" := BD_top : bisected_scope.\n\n(** ⊤ is the greatest element. *)\nTheorem BD_LE_top : ∀ d, d ⊑ ⊤.\nProof.\n  intros d n.\n  cbn; tauto.  \nQed.\n\nLocal Hint Resolve BD_LE_top.\n\n(** Reflexivity of less than equal relation. *)\nTheorem BD_LE_Refl : ∀ d, d ⊑ d.\nProof.\n  intros d n; trivial.\nQed.  \n\n(** Asymmetry of less than equal relation. *)\nTheorem BD_LE_ASym : ∀ d d', d ⊑ d' → d' ⊑ d → d = d'.\nProof.\n  intros d d' H1 H2.\n  apply BiDist_eq_simpl.\n  extensionality n.\n  specialize (H1 n).\n  specialize (H2 n).\n  apply PropExt; intuition.\nQed.  \n\n(** Transitivity of less than equal relation. *)\nTheorem BD_LE_Trans : ∀ d d' d'', d ⊑ d' → d' ⊑ d'' → d ⊑ d''.\nProof.\n  intros d d' d'' H1 H2 n.\n  auto.\nQed.  \n                                    \nLocal Obligation Tactic := idtac.\n\n(** Half of the given distance. *)\nProgram Definition BD_Half_of (d : BiDist) : BiDist :=\n  {|\n    BD_agree :=\n      fun n =>\n        match n return Prop with\n        | O => True\n        | S n' => d n'\n        end\n  |}.\n\nNext Obligation.\nProof.\n  intros d n m H1 H2; cbn in *.\n  destruct n; destruct m; trivial; try omega.\n  eapply (BD_decreases _ _ m); trivial; omega.\nQed.\n\n(** Half of is a monotone function. *)\nTheorem BD_Half_of_monotone : ∀ (d d' : BiDist), d ⊑ d' → (BD_Half_of d) ⊑ (BD_Half_of d').\nProof.\n  intros d d' H1 n H2.\n  destruct n; cbn; trivial.\n  apply H1; trivial.\nQed.\n\n(** Half of is a non-expansive function. *)\nTheorem BD_Half_of_non_expansive : ∀ (d : BiDist), (BD_Half_of d) ⊑ d.\nProof.\n  intros d n H.\n  destruct n; cbn; trivial.\n  apply BD_decreases with (m := S n); [do 2 constructor|trivial].\nQed.\n  \n(** Given a positive distance, half of it is positive. *)\nTheorem BD_pos_half_pos : ∀ d, ⊥ ⊏ d → ⊥ ⊏ BD_Half_of d.\nProof.\n  intros d [H11 H12].\n  split.\n  {\n    intros n H2.\n    destruct n; cbn; auto.\n  }\n  {  \n    intros H2.\n    apply H12.\n    apply BiDist_eq_simpl.\n    extensionality n.\n    apply (f_equal (fun x => BD_agree x (S n))) in H2.\n    trivial.\n  }\nQed.\n\n(** If an element is positive then its half is strictly smaller than it. *)\nTheorem BD_pos_half_strictly_less : ∀ d, ⊥ ⊏ d → BD_Half_of d ⊏ d.\nProof.\n  intros d [H11 H12].\n  split.\n  {\n    intros n H2.\n    destruct n; cbn; eauto.\n  }\n  {\n    intros H2.\n    apply H12.\n    apply BD_LE_ASym; auto.\n    intros n _.\n    induction n.\n    + apply (f_equal (fun x => BD_agree x 0)) in H2.\n      rewrite <- H2; cbn; trivial.\n    + apply (f_equal (fun x => BD_agree x (S n))) in H2.\n      rewrite <- H2.\n      trivial.\n  }\nQed.\n\n(** Half of any distance is less than 1. *)\nTheorem BD_half_of_less_than_1 : ∀ d, BD_Half_of d ⊏ ⊤.\nProof.\n  intros d.\n  split.\n  + intros n H; cbn in H; tauto.\n  + intros H.\n    cbn_rewrite <- (equal_f (f_equal BD_agree H) 0).\n    trivial.\nQed.  \n\n(** nᵗʰ power of 1/2. *)\nDefinition BD_Half_pow (n : nat) := iterate BD_Half_of ⊤ n.\n\n(** The nᵗʰ element of the sequence for the (n+1)ᵗʰ power of 1/2 is inhabitted. *)\nTheorem BD_Half_pow_Sn_n (n : nat) : BD_Half_pow (S n) n.\nProof.\n  induction n; cbn; trivial.\nQed.\n\n(** The kᵗʰ element (k < n) of the sequence for the nᵗʰ power of 1/2 is inhabitted. *)\nTheorem BD_Half_pow_lt (n k : nat) : k < n → BD_Half_pow n k.\nProof.\n  intros H.\n  induction H.\n  apply BD_Half_pow_Sn_n.\n  apply BD_decreases with (m := S k); [do 2 constructor | trivial].\nQed.\n\n(** The kᵗʰ element (k < n) of the sequence for the nᵗʰ power of 1/2 is inhabitted. *)\nTheorem BD_Half_pow_ge (n k : nat) : n ≤ k → ¬ (BD_Half_pow n k).\nProof.\n  intros H.\n  induction H.\n  {\n    induction n; tauto.\n  }\n  {\n    intros H'.\n    contradict IHle.\n    apply BD_decreases with (m := S m); [do 2 constructor | trivial].\n  }\nQed.\n\n(** BD_Half_pow is monotone. *)\nTheorem BD_Half_pow_monotone (n k : nat) : n ≤ k → (BD_Half_pow k) ⊑ (BD_Half_pow n).\nProof.\n  intros H.\n  induction H.\n  + apply BD_LE_Refl.\n  + eapply BD_LE_Trans; [|apply IHle].\n    apply BD_Half_of_non_expansive.\nQed.\n\n(** Less than BD_Half_pow. *)\nTheorem Less_than_BD_Half_pow (d : BiDist) (n : nat) :\n  d n → d ⊑ (BD_Half_pow n).\nProof.\n  intros H m H'.\n  apply (BD_decreases d _ n); trivial.\n  destruct (le_lt_dec m n); trivial.\n  exfalso; eapply BD_Half_pow_ge; eauto.\nQed.\n  \n(** nᵗʰ power of 1/2 is positive. *)\nTheorem BD_Half_pow_pos (n : nat) : ⊥ ⊏ (BD_Half_pow n).\nProof.\n  split; trivial.\n  intros H.\n  apply (BD_Half_pow_ge n (S n)); [do 2 constructor |].\n  match goal with\n    [|- ?A] =>\n    replace A with (⊥ (S n)); cbn; trivial\n  end.\n  apply (equal_f (f_equal BD_agree H) (S n)).\nQed.  \n\n(** If an element is less than all finite powers 1/2 is the least element. *)\nTheorem BD_approach_bot : ∀ d, (∀ d', ⊥ ⊏ d' → d ⊏ d') → d = ⊥.\nProof.\n  intros d H1.\n  apply BD_LE_ASym; [|apply BD_bot_LE].\n  intros n H2.\n  cut (d ⊏ BD_Half_pow (S n)); [intros [H31 H32]|].\n  {\n    apply H31.\n    apply BD_Half_pow_Sn_n.\n  }\n  {\n    apply H1.\n    split; auto.\n    intros H3.\n    apply (f_equal (fun x => BD_agree x (S n))) in H3.\n    cbn in H3.\n    induction n.\n    + cbn in H3.\n      rewrite <- H3; trivial.\n    + apply IHn; trivial.\n  }\nQed.\n\n(** The least upper bound. *)\nProgram Definition BD_lub {X : Type} (f : X → BiDist) : BiDist :=\n  {|\n    BD_agree := fun n => ∀ x, f x n\n  |}\n.\n\nNext Obligation.\nProof.\n  cbn.\n  intros d d' n m H1 H2.\n  intuition eauto.\nQed.\n  \nNotation \"⊔ᵍ y\" := (BD_lub y) : bisected_scope.\n\n(** The least upper bound is an upper bound. *)\nTheorem BD_lub_ub : ∀ {X : Type} (f : X → BiDist),\n    ∀ x, f x ⊑ ⊔ᵍ f.\nProof.\n  intros f d d' n; cbn; intuition.  \nQed.\n\n(** The lease upper bound is indeed the least among upper bounds. *)\nTheorem BD_lub_lst : ∀ {X : Type} (f : X → BiDist) (d : BiDist),\n    (∀ x, f x ⊑ d) → (⊔ᵍ f) ⊑ d.\nProof.\n  intros X f d H1 n H2 x; apply H1; trivial.\nQed.\n\n(** BiDist forms a partial order. *)\nDefinition BiDistPO : PartialOrder :=\n  {|\n    PO_Carrier := BiDist;\n    PO_LE := BD_LE;\n    PO_Refl := BD_LE_Refl;\n    PO_ASym := BD_LE_ASym;\n    PO_Trans := BD_LE_Trans\n  |}.\n\n(** BiDist as a partial order has least upper bounds. *)\nProgram Definition BD_LUB {X : Type} (f : X → BiDist) : (@LUB BiDistPO _ f)%order :=\n  {|\n    lub := ⊔ᵍ f;\n    lub_ub := BD_lub_ub f;\n    lub_lst := BD_lub_lst f\n  |}.\n\nInductive BD_ApprType : BiDist → Type :=\n| Appr_Half_Pow : ∀ n, BD_ApprType (BD_Half_pow n)\n.\n\nDefinition BD_appr_pos := fun (x : BiDistPO) (H : BD_ApprType x) =>\n        match H in (BD_ApprType b) return ⊥ ⊏ b with\n        | Appr_Half_Pow n => BD_Half_pow_pos n\n        end.\n\nRequire Import Coq.Logic.Classical_Pred_Type\n        Coq.Logic.ChoiceFacts.\n\nLocal Axiom ConstructiveIndefiniteDescription_nat : ConstructiveIndefiniteDescription_on nat.\n\nTheorem EveryBiDistAppr_helper (b : BiDist) :\n  ⊥ ⊏ b → {n : nat | (BD_Half_pow n) ⊑ b}.\nProof.\n  intros H1.\n  apply ConstructiveIndefiniteDescription_nat.\n  cut (∃ n, ¬ b n).\n  {\n    intros [n H2].\n    exists n.\n    intros m H3.\n    destruct (le_gt_dec n m) as [H4|H4].\n    + contradict H2.\n      apply BD_decreases with (m := m); trivial.\n    + apply BD_Half_pow_lt; trivial.\n  }\n  {\n    apply not_all_ex_not.\n    intros H2.\n    apply H1.\n    apply BD_LE_ASym;trivial.\n    intros ? ?; trivial.\n  }\nQed.\n\nDefinition BD_dichotomy_left\n           (x : BiDist)\n           (H : BD_ApprType x)\n  :\n    {y : BiDist & BD_ApprType y & (⊥ ⊏ y) ∧ (y ⊏ x)}\n  :=\n    existT2\n      _\n      _\n      (BD_Half_of x)\n      match H in (BD_ApprType b) return (BD_ApprType (BD_Half_of b)) with\n      | Appr_Half_Pow n => Appr_Half_Pow (S n)\n      end\n      (conj (BD_pos_half_pos x (BD_appr_pos x H))\n            (BD_pos_half_strictly_less x (BD_appr_pos x H)))\n.\n  \n(** BiDist forms an MLattice. *)\nProgram Definition BiDistML : MLattice :=\n  {|\n    ML_PO := BiDistPO;\n    ML_meets := @BD_LUB;\n    ML_top := ⊤;\n    ML_top_top := BD_LE_top;\n    ML_bot := (⊥);\n    ML_bot_bottom := BD_bot_LE;\n    ML_appr_cond := BD_ApprType;\n    ML_appr_top := Appr_Half_Pow 0;\n    ML_appr_pos := BD_appr_pos;\n    ML_appr_dominate_pos := _;\n    ML_bottom_dichotomy := inl BD_dichotomy_left;\n    ML_all_approximatable :=\n      fun x H =>\n        existT2\n          _\n          _\n          (BD_Half_pow (proj1_sig (EveryBiDistAppr_helper x H)))\n          (proj2_sig (EveryBiDistAppr_helper x H))\n          (Appr_Half_Pow _)\n  |}.\n\nNext Obligation.\nProof.\n  intros x H1.\n  apply BD_LE_ASym; trivial.\n  intros n _.\n  specialize (H1 _ (Appr_Half_Pow (S n))).\n  apply H1.\n  apply BD_Half_pow_Sn_n.\nQed.\n\n(** Powers of 1/2 are strictly decreasing *)\nTheorem BD_Half_pow_strict_decreasing (n k : nat) : k < n → BD_Half_pow n ⊏ BD_Half_pow k.\nProof.\n  intros H.\n  induction H.\n  apply BD_pos_half_strictly_less; apply BD_Half_pow_pos.\n  eapply (@LE_LT_Trans BiDistPO); [|apply IHle].\n  apply BD_pos_half_strictly_less; apply BD_Half_pow_pos.\nQed.\n\n(** If a power of 1/2 is less than another, then the exponent is greater. *)\nTheorem BD_Half_pow_strictly_less_exponent_strictly_less\n        (n k : nat) : BD_Half_pow n ⊏ BD_Half_pow k → k < n.\nProof.\n  intros [H11 H12].\n  destruct (le_lt_dec n k) as [H2|H2]; trivial.\n  apply BD_Half_pow_monotone in H2.\n  contradict H12.\n  apply BD_LE_ASym; auto.\nQed.\n\n(** Given a positive distance, half of it is positive. *)\nTheorem Strictly_less_less_than_BD_pos_half_pos :\n  ∀ d d', d ⊏ d' → BD_ApprType d → BD_ApprType d' → d ⊑ BD_Half_of d'.\nProof.\n  intros d d' H1 H2 H3.\n  destruct H2 as [n].\n  destruct H3 as [m].\n  apply BD_Half_pow_strictly_less_exponent_strictly_less in H1.\n  assert (H5 : (S m) ≤ n) by omega.\n  apply (BD_Half_pow_monotone (S m) n H5).\nQed.\n\n(** half_of forms a contraction rate! *)\nProgram Definition Half_ContrRate : ContrRate BiDistML :=\n  {|\n    CR_fun := BD_Half_of;\n    CR_monotone := BD_Half_of_monotone;\n    CR_non_expansive := BD_Half_of_non_expansive;\n    CR_contracts := BD_pos_half_strictly_less;\n    CR_rate_indicator := _\n  |}.\n\nNext Obligation.\nProof.\n  intros ε ε'.\n  destruct ε as [ε [n]].\n  destruct ε' as [ε' [n']].\n  cbn.\n  exists (S (n - n')).\n  unfold BD_Half_pow.\n  rewrite iterate_after_iterate.\n  apply BD_Half_pow_strict_decreasing.\n  omega.\nQed.", "meta": {"author": "amintimany", "repo": "CTDT", "sha": "91e390152e09c554126b13fd953c905d16bfed5f", "save_path": "github-repos/coq/amintimany-CTDT", "path": "github-repos/coq/amintimany-CTDT/CTDT-91e390152e09c554126b13fd953c905d16bfed5f/Bisected/Bisected.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7306967254490616}}
{"text": "From Coq Require Import\n  Arith\n  List.\nFrom FunProofs.Lib Require Import\n  List.\n\n(* Enumerate all lists of length n using the elements of vals. *)\nFixpoint enumerate {A} (vals : list A) (n : nat) : list (list A) :=\n  match n with\n  | 0 => [[]]\n  | S n' =>\n    let fs := map cons vals in\n    let vs := enumerate vals n' in\n    flat_map (fun xs => map (fun f => f xs) fs) vs\n  end.\n\nSection Enumerate.\n  Context {A : Type}.\n\n  Lemma enumerate_length n : forall (vals : list A),\n    length (enumerate vals n) = length vals ^ n.\n  Proof.\n    induction n; cbn; intros; auto.\n    rewrite flat_map_concat_map.\n    rewrite (concat_length _ (length vals)).\n    { rewrite map_length, IHn; auto. }\n    rewrite Forall_forall; intros *.\n    rewrite in_map_iff; intros (? & ? & ?); subst.\n    rewrite !map_length; auto.\n  Qed.\n\n  (* For any finite type, enumerate contains all sets of that type. *)\n  Lemma enumerate_finite xs : forall (vals : list A),\n    (forall x : A, In x vals) -> In xs (enumerate vals (length xs)).\n  Proof.\n    induction xs; cbn; intros * Hfinite; auto.\n    rewrite in_flat_map.\n    eexists; rewrite map_map, in_map_iff; eauto.\n  Qed.\nEnd Enumerate.\n", "meta": {"author": "whonore", "repo": "FunProofs", "sha": "f87c0d56670af0903f2a50a52c5f1056703f31cc", "save_path": "github-repos/coq/whonore-FunProofs", "path": "github-repos/coq/whonore-FunProofs/FunProofs-f87c0d56670af0903f2a50a52c5f1056703f31cc/Lib/Enumerate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7306955780154315}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export Tactics.\n\nCheck 3 = 3.\nCheck forall n m : nat, n + m = m + n.\nCheck 2 = 2.\nCheck forall n : nat, n = 2.\nCheck 3 = 4.\n\nTheorem plus_2_2_is_4 : 2 + 2 = 4.\nProof. reflexivity. Qed.\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n\nTheorem plus_fact_is_true : plus_fact.\nProof. reflexivity. Qed.\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall (x y : A), f x = f y -> (x = y).\nCheck injective.\n\nCheck eq.\nCheck @eq.\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof. split; reflexivity. Qed.\n\nLemma and_intro : \n  forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. \n  split. { apply HA. } { apply HB. }\nQed.\n\nCheck and_intro.\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro; reflexivity. \nQed.\n\nExample and_exercise : \n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H. rewrite plus_comm in H. \n  apply and_intro; \n  destruct m in H. { simpl in H. apply H. }\n  { inversion H. }\n\n(* doing this forward may be a clue on \n   how to do this in a fxnal style *)", "meta": {"author": "scottviteri", "repo": "CoqProjects", "sha": "57ad9d6840ad3232d442861a0df3a583bef1ee62", "save_path": "github-repos/coq/scottviteri-CoqProjects", "path": "github-repos/coq/scottviteri-CoqProjects/CoqProjects-57ad9d6840ad3232d442861a0df3a583bef1ee62/LogicalFoundationsProblems/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7306955752356138}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(******************************************************************************)\n(*    The basic theory of paths over an eqType; this file is essentially a    *)\n(* complement to seq.v. Paths are non-empty sequences that obey a progression *)\n(* relation. They are passed around in three parts: the head and tail of the  *)\n(* sequence, and a proof of (boolean) predicate asserting the progression.    *)\n(* This \"exploded\" view is rarely embarrassing, as the first two parameters   *)\n(* are usually inferred from the type of the third; on the contrary, it saves *)\n(* the hassle of constantly constructing and destructing a dependent record.  *)\n(*    We define similarly cycles, for which we allow the empty sequence,      *)\n(* which represents a non-rooted empty cycle; by contrast, the \"empty\" path   *)\n(* from a point x is the one-item sequence containing only x.                 *)\n(*   We allow duplicates; uniqueness, if desired (as is the case for several  *)\n(* geometric constructions), must be asserted separately. We do provide       *)\n(* shorthand, but only for cycles, because the equational properties of       *)\n(* \"path\" and \"uniq\" are unfortunately  incompatible (esp. wrt \"cat\").        *)\n(*    We define notations for the common cases of function paths, where the   *)\n(* progress relation is actually a function. In detail:                       *)\n(*   path e x p == x :: p is an e-path [:: x_0; x_1; ... ; x_n], i.e., we     *)\n(*                 e x_i x_{i+1} for all i < n. The path x :: p starts at x   *)\n(*                 and ends at last x p.                                      *)\n(*  fpath f x p == x :: p is an f-path, where f is a function, i.e., p is of  *)\n(*                 the form [:: f x; f (f x); ...]. This is just a notation   *)\n(*                 for path (frel f) x p.                                     *)\n(*   sorted e s == s is an e-sorted sequence: either s = [::], or s = x :: p  *)\n(*                 is an e-path (this is oten used with e = leq or ltn).      *)\n(*    cycle e c == c is an e-cycle: either c = [::], or c = x :: p with       *)\n(*                 x :: (rcons p x) an e-path.                                *)\n(*   fcycle f c == c is an f-cycle, for a function f.                         *)\n(* traject f x n == the f-path of size n starting at x                        *)\n(*              := [:: x; f x; ...; iter n.-1 f x]                            *)\n(* looping f x n == the f-paths of size greater than n starting at x loop     *)\n(*                 back, or, equivalently, traject f x n contains all         *)\n(*                 iterates of f at x.                                        *)\n(* merge e s1 s2 == the e-sorted merge of sequences s1 and s2: this is always *)\n(*                 a permutation of s1 ++ s2, and is e-sorted when s1 and s2  *)\n(*                 are and e is total.                                        *)\n(*     sort e s == a permutation of the sequence s, that is e-sorted when e   *)\n(*                 is total (computed by a merge sort with the merge function *)\n(*                 above).                                                    *)\n(*   mem2 s x y == x, then y occur in the sequence (path) s; this is          *)\n(*                 non-strict: mem2 s x x = (x \\in s).                        *)\n(*     next c x == the successor of the first occurrence of x in the sequence *)\n(*                 c (viewed as a cycle), or x if x \\notin c.                 *)\n(*     prev c x == the predecessor of the first occurrence of x in the        *)\n(*                 sequence c (viewed as a cycle), or x if x \\notin c.        *)\n(*    arc c x y == the sub-arc of the sequece c (viewed as a cycle) starting  *)\n(*                 at the first occurrence of x in c, and ending just before  *)\n(*                 the next ocurrence of y (in cycle order); arc c x y        *)\n(*                 returns an unspecified sub-arc of c if x and y do not both *)\n(*                 occur in c.                                                *)\n(*  ucycle e c <-> ucycleb e c (ucycle e c is a Coercion target of type Prop) *)\n(* ufcycle f c <-> c is a simple f-cycle, for a function f.                   *)\n(*  shorten x p == the tail a duplicate-free subpath of x :: p with the same  *)\n(*                 endpoints (x and last x p), obtained by removing all loops *)\n(*                 from x :: p.                                               *)\n(* rel_base e e' h b <-> the function h is a functor from relation e to       *)\n(*                 relation e', EXCEPT at points whose image under h satisfy  *)\n(*                 the \"base\" predicate b:                                    *)\n(*                    e' (h x) (h y) = e x y UNLESS b (h x) holds             *)\n(*                 This is the statement of the side condition of the path    *)\n(*                 functorial mapping lemma map_path.                         *)\n(* fun_base f f' h b <-> the function h is a functor from function f to f',   *)\n(*                 except at the preimage of predicate b under h.             *)\n(* We also provide three segmenting dependently-typed lemmas (splitP, splitPl *)\n(* and splitPr) whose elimination split a path x0 :: p at an internal point x *)\n(* as follows:                                                                *)\n(*  - splitP applies when x \\in p; it replaces p with (rcons p1 x ++ p2), so  *)\n(*    that x appears explicitly at the end of the left part. The elimination  *)\n(*    of splitP will also simultaneously replace take (index x p) with p1 and *)\n(*    drop (index x p).+1 p with p2.                                          *)\n(*  - splitPl applies when x \\in x0 :: p; it replaces p with p1 ++ p2 and     *)\n(*    simulaneously generates an equation x = last x0 p.                      *)\n(*  - splitPr applies when x \\in p; it replaces p with (p1 ++ x :: p2), so x  *)\n(*    appears explicitly at the start of the right part.                      *)\n(* The parts p1 and p2 are computed using index/take/drop in all cases, but   *)\n(* only splitP attemps to subsitute the explicit values. The substitution of  *)\n(* p can be deferred using the dependent equation generation feature of       *)\n(* ssreflect, e.g.: case/splitPr def_p: {1}p / x_in_p => [p1 p2] generates    *)\n(* the equation p = p1 ++ p2 instead of performing the substitution outright. *)\n(*   Similarly, eliminating the loop removal lemma shortenP simultaneously    *)\n(* replaces shorten e x p with a fresh constant p', and last x p with         *)\n(* last x p'.                                                                 *)\n(*   Note that although all \"path\" functions actually operate on the          *)\n(* underlying sequence, we provide a series of lemmas that define their       *)\n(* interaction with thepath and cycle predicates, e.g., the cat_path equation *)\n(* can be used to split the path predicate after splitting the underlying     *)\n(* sequence.                                                                  *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Paths.\n\nVariables (n0 : nat) (T : Type).\n\nSection Path.\n\nVariables (x0_cycle : T) (e : rel T).\n\nFixpoint path x (p : seq T) :=\n  if p is y :: p' then e x y && path y p' else true.\n\nLemma cat_path x p1 p2 : path x (p1 ++ p2) = path x p1 && path (last x p1) p2.\nProof. by elim: p1 x => [|y p1 Hrec] x //=; rewrite Hrec -!andbA. Qed.\n\nLemma rcons_path x p y : path x (rcons p y) = path x p && e (last x p) y.\nProof. by rewrite -cats1 cat_path /= andbT. Qed.\n\nLemma pathP x p x0 :\n  reflect (forall i, i < size p -> e (nth x0 (x :: p) i) (nth x0 p i))\n          (path x p).\nProof.\nelim: p x => [|y p IHp] x /=; first by left.\napply: (iffP andP) => [[e_xy /IHp e_p [] //] | e_p].\nby split; [exact: (e_p 0) | apply/(IHp y) => i; exact: e_p i.+1].\nQed.\n\nDefinition cycle p := if p is x :: p' then path x (rcons p' x) else true.\n\nLemma cycle_path p : cycle p = path (last x0_cycle p) p.\nProof. by case: p => //= x p; rewrite rcons_path andbC. Qed.\n\nLemma rot_cycle p : cycle (rot n0 p) = cycle p.\nProof.\ncase: n0 p => [|n] [|y0 p] //=; first by rewrite /rot /= cats0.\nrewrite /rot /= -{3}(cat_take_drop n p) -cats1 -catA cat_path.\ncase: (drop n p) => [|z0 q]; rewrite /= -cats1 !cat_path /= !andbT andbC //.\nby rewrite last_cat; repeat bool_congr.\nQed.\n\nLemma rotr_cycle p : cycle (rotr n0 p) = cycle p.\nProof. by rewrite -rot_cycle rotrK. Qed.\n\nEnd Path.\n\nLemma eq_path e e' : e =2 e' -> path e =2 path e'.\nProof. by move=> ee' x p; elim: p x => //= y p IHp x; rewrite ee' IHp. Qed.\n\nLemma eq_cycle e e' : e =2 e' -> cycle e =1 cycle e'.\nProof. by move=> ee' [|x p] //=; exact: eq_path. Qed.\n\nLemma sub_path e e' : subrel e e' -> forall x p, path e x p -> path e' x p.\nProof. by move=> ee' x p; elim: p x => //= y p IHp x /andP[/ee'-> /IHp]. Qed.\n\nLemma rev_path e x p :\n  path e (last x p) (rev (belast x p)) = path (fun z => e^~ z) x p.\nProof.\nelim: p x => //= y p IHp x; rewrite rev_cons rcons_path -{}IHp andbC.\nby rewrite -(last_cons x) -rev_rcons -lastI rev_cons last_rcons.\nQed.\n\nEnd Paths.\n\nImplicit Arguments pathP [T e x p].\nPrenex Implicits pathP.\n\nSection EqPath.\n\nVariables (n0 : nat) (T : eqType) (x0_cycle : T) (e : rel T).\nImplicit Type p : seq T.\n\nCoInductive split x : seq T -> seq T -> seq T -> Type :=\n  Split p1 p2 : split x (rcons p1 x ++ p2) p1 p2.\n\nLemma splitP p x (i := index x p) :\n  x \\in p -> split x p (take i p) (drop i.+1 p).\nProof.\nmove=> p_x; have lt_ip: i < size p by rewrite index_mem.\nby rewrite -{1}(cat_take_drop i p) (drop_nth x lt_ip) -cat_rcons nth_index.\nQed.\n\nCoInductive splitl x1 x : seq T -> Type :=\n  Splitl p1 p2 of last x1 p1 = x : splitl x1 x (p1 ++ p2).\n\nLemma splitPl x1 p x : x \\in x1 :: p -> splitl x1 x p.\nProof.\nrewrite inE; case: eqP => [->| _ /splitP[]]; first by rewrite -(cat0s p).\nby split; exact: last_rcons.\nQed.\n\nCoInductive splitr x : seq T -> Type :=\n  Splitr p1 p2 : splitr x (p1 ++ x :: p2).\n\nLemma splitPr p x : x \\in p -> splitr x p.\nProof. by case/splitP=> p1 p2; rewrite cat_rcons. Qed.\n\nFixpoint next_at x y0 y p :=\n  match p with\n  | [::] => if x == y then y0 else x\n  | y' :: p' => if x == y then y' else next_at x y0 y' p'\n  end.\n\nDefinition next p x := if p is y :: p' then next_at x y y p' else x.\n\nFixpoint prev_at x y0 y p :=\n  match p with\n  | [::]     => if x == y0 then y else x\n  | y' :: p' => if x == y' then y else prev_at x y0 y' p'\n  end.\n\nDefinition prev p x := if p is y :: p' then prev_at x y y p' else x.\n\nLemma next_nth p x :\n  next p x = if x \\in p then\n               if p is y :: p' then nth y p' (index x p) else x\n             else x.\nProof.\ncase: p => //= y0 p. \nelim: p {2 3 5}y0 => [|y' p IHp] y /=; rewrite (eq_sym y) inE;\n  by case: ifP => // _; exact: IHp.\nQed.\n\nLemma prev_nth p x :\n  prev p x = if x \\in p then\n               if p is y :: p' then nth y p (index x p') else x\n             else x.\nProof.\ncase: p => //= y0 p; rewrite inE orbC.\nelim: p {2 5}y0 => [|y' p IHp] y; rewrite /= ?inE // (eq_sym y').\nby case: ifP => // _; exact: IHp.\nQed.\n\nLemma mem_next p x : (next p x \\in p) = (x \\in p).\nProof.\nrewrite next_nth; case p_x: (x \\in p) => //.\ncase: p (index x p) p_x => [|y0 p'] //= i _; rewrite inE.\nhave [lt_ip | ge_ip] := ltnP i (size p'); first by rewrite orbC mem_nth.\nby rewrite nth_default ?eqxx.\nQed.\n\nLemma mem_prev p x : (prev p x \\in p) = (x \\in p).\nProof.\nrewrite prev_nth; case p_x: (x \\in p) => //; case: p => [|y0 p] // in p_x *.\nby apply mem_nth; rewrite /= ltnS index_size.\nQed.\n\n(* ucycleb is the boolean predicate, but ucycle is defined as a Prop *)\n(* so that it can be used as a coercion target. *)\nDefinition ucycleb p := cycle e p && uniq p.\nDefinition ucycle p : Prop := cycle e p && uniq p.\n\n(* Projections, used for creating local lemmas. *)\nLemma ucycle_cycle p : ucycle p -> cycle e p.\nProof. by case/andP. Qed.\n\nLemma ucycle_uniq p : ucycle p -> uniq p.\nProof. by case/andP. Qed.\n\nLemma next_cycle p x : cycle e p -> x \\in p -> e x (next p x).\nProof.\ncase: p => //= y0 p; elim: p {1 3 5}y0 => [|z p IHp] y /=; rewrite inE.\n  by rewrite andbT; case: (x =P y) => // ->.\nby case/andP=> eyz /IHp; case: (x =P y) => // ->.\nQed.\n\nLemma prev_cycle p x : cycle e p -> x \\in p -> e (prev p x) x.\nProof.\ncase: p => //= y0 p; rewrite inE orbC.\nelim: p {1 5}y0 => [|z p IHp] y /=; rewrite ?inE.\n  by rewrite andbT; case: (x =P y0) => // ->.\nby case/andP=> eyz /IHp; case: (x =P z) => // ->.\nQed.\n\nLemma rot_ucycle p : ucycle (rot n0 p) = ucycle p.\nProof. by rewrite /ucycle rot_uniq rot_cycle. Qed.\n\nLemma rotr_ucycle p : ucycle (rotr n0 p) = ucycle p.\nProof. by rewrite /ucycle rotr_uniq rotr_cycle. Qed.\n\n(* The \"appears no later\" partial preorder defined by a path. *)\n\nDefinition mem2 p x y := y \\in drop (index x p) p.\n\nLemma mem2l p x y : mem2 p x y -> x \\in p.\nProof.\nby rewrite /mem2 -!index_mem size_drop => /ltn_predK; rewrite -subn_gt0 => <-.\nQed.\n\nLemma mem2lf {p x y} : x \\notin p -> mem2 p x y = false.\nProof. by apply: contraNF; exact: mem2l. Qed.\n\nLemma mem2r p x y : mem2 p x y -> y \\in p.\nProof.\nrewrite /mem2 => pxy.\nby rewrite -(cat_take_drop (index x p) p) mem_cat pxy orbT.\nQed.\n\nLemma mem2rf {p x y} : y \\notin p -> mem2 p x y = false.\nProof. by apply: contraNF; exact: mem2r. Qed.\n\nLemma mem2_cat p1 p2 x y :\n  mem2 (p1 ++ p2) x y = mem2 p1 x y || mem2 p2 x y || (x \\in p1) && (y \\in p2).\nProof.\nrewrite {1}/mem2 index_cat drop_cat; have [p1x | p1'x] := boolP (x \\in p1).\n  rewrite index_mem p1x mem_cat /= -orbA.\n  by have [|p2'y] := boolP (y \\in p2); [rewrite !orbT | rewrite (mem2rf p2'y)].\nby rewrite ltnNge leq_addr /= orbF addKn (mem2lf p1'x).\nQed.\n\nLemma mem2_splice p1 p3 x y p2 :\n   mem2 (p1 ++ p3) x y -> mem2 (p1 ++ p2 ++ p3) x y.\nProof.\nmove=> p13xy; move: p13xy; rewrite !mem2_cat mem_cat -orbA.\nby case/or3P=> [-> | -> | /andP[-> ->]]; rewrite ?orbT.\nQed.\n\nLemma mem2_splice1 p1 p3 x y z :\n  mem2 (p1 ++ p3) x y -> mem2 (p1 ++ z :: p3) x y.\nProof. exact: (mem2_splice [::z]). Qed.\n\nLemma mem2_cons x p y :\n  mem2 (x :: p) y =1 (if x == y then mem (x :: p) : pred T else mem2 p y).\nProof. by move=> z; rewrite {1}/mem2 /=; case (x == y). Qed.\n\nLemma mem2_last y0 p x : mem2 (y0 :: p) x (last y0 p) = (x \\in y0 :: p).\nProof.\napply/idP/idP; first exact: mem2l.\nrewrite -index_mem /mem2; move: (index x _) => i le_ip.\nby rewrite lastI drop_rcons ?size_belast // mem_rcons mem_head.\nQed.\n\nLemma mem2l_cat {p1 p2 x} : x \\notin p1 -> mem2 (p1 ++ p2) x =1 mem2 p2 x.\nProof. by move=> p1'x y; rewrite mem2_cat (negPf p1'x) mem2lf ?orbF. Qed.\n\nLemma mem2r_cat {p1 p2 x y} : y \\notin p2 -> mem2 (p1 ++ p2) x y = mem2 p1 x y.\nProof.\nby move=> p2'y; rewrite mem2_cat (negPf p2'y) -orbA orbC andbF mem2rf.\nQed.\n\nLemma mem2lr_splice {p1 p2 p3 x y} :\n  x \\notin p2 -> y \\notin p2 -> mem2 (p1 ++ p2 ++ p3) x y = mem2 (p1 ++ p3) x y.\nProof.\nmove=> p2'x p2'y; rewrite catA !mem2_cat !mem_cat.\nby rewrite (negPf p2'x) (negPf p2'y) (mem2lf p2'x) andbF !orbF.\nQed.\n\nCoInductive split2r x y : seq T -> Type :=\n  Split2r p1 p2 of y \\in x :: p2 : split2r x y (p1 ++ x :: p2).\n\nLemma splitP2r p x y : mem2 p x y -> split2r x y p.\nProof.\nmove=> pxy; have px := mem2l pxy.\nhave:= pxy; rewrite /mem2 (drop_nth x) ?index_mem ?nth_index //.\nby case/splitP: px => p1 p2; rewrite cat_rcons.\nQed.\n\nFixpoint shorten x p :=\n  if p is y :: p' then\n    if x \\in p then shorten x p' else y :: shorten y p'\n  else [::].\n\nCoInductive shorten_spec x p : T -> seq T -> Type :=\n   ShortenSpec p' of path e x p' & uniq (x :: p') & subpred (mem p') (mem p) :\n     shorten_spec x p (last x p') p'.\n\nLemma shortenP x p : path e x p -> shorten_spec x p (last x p) (shorten x p).\nProof.\nmove=> e_p; have: x \\in x :: p by exact: mem_head.\nelim: p x {1 3 5}x e_p => [|y2 p IHp] x y1.\n  by rewrite mem_seq1 => _ /eqP->.\nrewrite inE orbC /= => /andP[ey12 /IHp {IHp}IHp].\ncase: ifPn => [y2p_x _ | not_y2p_x /eqP def_x].\n  have [p' e_p' Up' p'p] := IHp _ y2p_x.\n  by split=> // y /p'p; exact: predU1r.\nhave [p' e_p' Up' p'p] := IHp y2 (mem_head y2 p).\nhave{p'p} p'p z: z \\in y2 :: p' -> z \\in y2 :: p.\n  by rewrite !inE; case: (z == y2) => // /p'p.\nrewrite -(last_cons y1) def_x; split=> //=; first by rewrite ey12.\nby rewrite (contra (p'p y1)) -?def_x.\nQed.\n\nEnd EqPath.\n\n\n(* Ordered paths and sorting. *)\n\nSection SortSeq.\n\nVariable T : eqType.\nVariable leT : rel T.\n\nDefinition sorted s := if s is x :: s' then path leT x s' else true.\n\nLemma path_sorted x s : path leT x s -> sorted s.\nProof. by case: s => //= y s /andP[]. Qed.\n\nLemma path_min_sorted x s :\n  {in s, forall y, leT x y} -> path leT x s = sorted s.\nProof. by case: s => //= y s -> //; exact: mem_head. Qed.\n\nSection Transitive.\n\nHypothesis leT_tr : transitive leT.\n\nLemma subseq_order_path x s1 s2 :\n  subseq s1 s2 -> path leT x s2 -> path leT x s1.\nProof.\nelim: s2 x s1 => [|y s2 IHs] x [|z s1] //= {IHs}/(IHs y).\ncase: eqP => [-> | _] IHs /andP[] => [-> // | leTxy /IHs /=].\nby case/andP=> /(leT_tr leTxy)->.\nQed.\n\nLemma order_path_min x s : path leT x s -> all (leT x) s.\nProof.\nmove/subseq_order_path=> le_x_s; apply/allP=> y.\nby rewrite -sub1seq => /le_x_s/andP[].\nQed.\n\nLemma subseq_sorted s1 s2 : subseq s1 s2 -> sorted s2 -> sorted s1.\nProof.\ncase: s1 s2 => [|x1 s1] [|x2 s2] //= sub_s12 /(subseq_order_path sub_s12).\nby case: eqP => [-> | _ /andP[]].\nQed.\n\nLemma sorted_filter a s : sorted s -> sorted (filter a s).\nProof. exact: subseq_sorted (filter_subseq a s). Qed.\n\nLemma sorted_uniq : irreflexive leT -> forall s, sorted s -> uniq s.\nProof.\nmove=> leT_irr; elim=> //= x s IHs s_ord.\nrewrite (IHs (path_sorted s_ord)) andbT; apply/negP=> s_x.\nby case/allPn: (order_path_min s_ord); exists x; rewrite // leT_irr.\nQed.\n\nLemma eq_sorted : antisymmetric leT ->\n  forall s1 s2, sorted s1 -> sorted s2 -> perm_eq s1 s2 -> s1 = s2.\nProof.\nmove=> leT_asym; elim=> [|x1 s1 IHs1] s2 //= ord_s1 ord_s2 eq_s12.\n  by case: {+}s2 (perm_eq_size eq_s12).\nhave s2_x1: x1 \\in s2 by rewrite -(perm_eq_mem eq_s12) mem_head.\ncase: s2 s2_x1 eq_s12 ord_s2 => //= x2 s2; rewrite in_cons.\ncase: eqP => [<- _| ne_x12 /= s2_x1] eq_s12 ord_s2.\n  by rewrite {IHs1}(IHs1 s2) ?(@path_sorted x1) // -(perm_cons x1).\ncase: (ne_x12); apply: leT_asym; rewrite (allP (order_path_min ord_s2)) //.\nhave: x2 \\in x1 :: s1 by rewrite (perm_eq_mem eq_s12) mem_head.\ncase/predU1P=> [eq_x12 | s1_x2]; first by case ne_x12.\nby rewrite (allP (order_path_min ord_s1)).\nQed.\n\nLemma eq_sorted_irr : irreflexive leT ->\n  forall s1 s2, sorted s1 -> sorted s2 -> s1 =i s2 -> s1 = s2.\nProof.\nmove=> leT_irr s1 s2 s1_sort s2_sort eq_s12.\nhave: antisymmetric leT.\n  by move=> m n /andP[? ltnm]; case/idP: (leT_irr m); exact: leT_tr ltnm.\nby move/eq_sorted; apply=> //; apply: uniq_perm_eq => //; exact: sorted_uniq.\nQed.\n\nEnd Transitive.\n\nHypothesis leT_total : total leT.\n\nFixpoint merge s1 :=\n  if s1 is x1 :: s1' then\n    let fix merge_s1 s2 :=\n      if s2 is x2 :: s2' then\n        if leT x2 x1 then x2 :: merge_s1 s2' else x1 :: merge s1' s2\n      else s1 in\n    merge_s1\n  else id.\n\nLemma merge_path x s1 s2 :\n  path leT x s1 -> path leT x s2 -> path leT x (merge s1 s2).\nProof.\nelim: s1 s2 x => //= x1 s1 IHs1.\nelim=> //= x2 s2 IHs2 x /andP[le_x_x1 ord_s1] /andP[le_x_x2 ord_s2].\ncase: ifP => le_x21 /=; first by rewrite le_x_x2 {}IHs2 // le_x21.\nby rewrite le_x_x1 IHs1 //=; have:= leT_total x2 x1; rewrite le_x21 /= => ->.\nQed.\n\nLemma merge_sorted s1 s2 : sorted s1 -> sorted s2 -> sorted (merge s1 s2).\nProof.\ncase: s1 s2 => [|x1 s1] [|x2 s2] //= ord_s1 ord_s2.\ncase: ifP => le_x21 /=.\n  by apply: (@merge_path x2 (x1 :: s1)) => //=; rewrite le_x21.\nby apply: merge_path => //=; have:= leT_total x2 x1; rewrite le_x21 /= => ->.\nQed.\n\nLemma perm_merge s1 s2 : perm_eql (merge s1 s2) (s1 ++ s2).\nProof.\napply/perm_eqlP; rewrite perm_eq_sym; elim: s1 s2 => //= x1 s1 IHs1.\nelim=> [|x2 s2 IHs2]; rewrite /= ?cats0 //.\ncase: ifP => _ /=; last by rewrite perm_cons.\nby rewrite (perm_catCA (_ :: _) [::x2]) perm_cons.\nQed.\n\nLemma mem_merge s1 s2 : merge s1 s2 =i s1 ++ s2.\nProof. by apply: perm_eq_mem; rewrite perm_merge. Qed.\n\nLemma size_merge s1 s2 : size (merge s1 s2) = size (s1 ++ s2).\nProof. by apply: perm_eq_size; rewrite perm_merge. Qed.\n\nLemma merge_uniq s1 s2 : uniq (merge s1 s2) = uniq (s1 ++ s2).\nProof. by apply: perm_eq_uniq; rewrite perm_merge. Qed.\n\nFixpoint merge_sort_push s1 ss :=\n  match ss with\n  | [::] :: ss' | [::] as ss' => s1 :: ss'\n  | s2 :: ss' => [::] :: merge_sort_push (merge s1 s2) ss'\n  end.\n\nFixpoint merge_sort_pop s1 ss :=\n  if ss is s2 :: ss' then merge_sort_pop (merge s1 s2) ss' else s1.\n\nFixpoint merge_sort_rec ss s :=\n  if s is [:: x1, x2 & s'] then\n    let s1 := if leT x1 x2 then [:: x1; x2] else [:: x2; x1] in\n    merge_sort_rec (merge_sort_push s1 ss) s'\n  else merge_sort_pop s ss.\n\nDefinition sort := merge_sort_rec [::].\n\nLemma sort_sorted s : sorted (sort s).\nProof.\nrewrite /sort; have allss: all sorted [::] by [].\nelim: {s}_.+1 {-2}s [::] allss (ltnSn (size s)) => // n IHn s ss allss.\nhave: sorted s -> sorted (merge_sort_pop s ss).\n  elim: ss allss s => //= s2 ss IHss /andP[ord_s2 ord_ss] s ord_s.\n  exact: IHss ord_ss _ (merge_sorted ord_s ord_s2).\ncase: s => [|x1 [|x2 s _]]; try by auto.\nmove/ltnW/IHn; apply=> {n IHn s}; set s1 := if _ then _ else _.\nhave: sorted s1 by exact: (@merge_sorted [::x2] [::x1]).\nelim: ss {x1 x2}s1 allss => /= [|s2 ss IHss] s1; first by rewrite andbT.\ncase/andP=> ord_s2 ord_ss ord_s1.\nby case: {1}s2=> /= [|_ _]; [rewrite ord_s1 | exact: IHss (merge_sorted _ _)].\nQed.\n\nLemma perm_sort s : perm_eql (sort s) s.\nProof.\nrewrite /sort; apply/perm_eqlP; pose catss := foldr (@cat T) [::].\nrewrite perm_eq_sym -{1}[s]/(catss [::] ++ s).\nelim: {s}_.+1 {-2}s [::] (ltnSn (size s)) => // n IHn s ss.\nhave: perm_eq (catss ss ++ s) (merge_sort_pop s ss).\n  elim: ss s => //= s2 ss IHss s1; rewrite -{IHss}(perm_eqrP (IHss _)).\n  by rewrite perm_catC catA perm_catC perm_cat2l -perm_merge.\ncase: s => // x1 [//|x2 s _]; move/ltnW; move/IHn=> {n IHn}IHs.\nrewrite -{IHs}(perm_eqrP (IHs _)) ifE; set s1 := if_expr _ _ _.\nrewrite (catA _ [::_;_] s) {s}perm_cat2r.\napply: (@perm_eq_trans _ (catss ss ++ s1)).\n  by rewrite perm_cat2l /s1 -ifE; case: ifP; rewrite // (perm_catC [::_]).\nelim: ss {x1 x2}s1 => /= [|s2 ss IHss] s1; first by rewrite cats0.\nrewrite perm_catC; case def_s2: {2}s2=> /= [|y s2']; first by rewrite def_s2.\nby rewrite catA -{IHss}(perm_eqrP (IHss _)) perm_catC perm_cat2l -perm_merge.\nQed.\n\nLemma mem_sort s : sort s =i s.\nProof. by apply: perm_eq_mem; rewrite perm_sort. Qed.\n\nLemma size_sort s : size (sort s) = size s.\nProof. by apply: perm_eq_size; rewrite perm_sort. Qed.\n\nLemma sort_uniq s : uniq (sort s) = uniq s.\nProof. by apply: perm_eq_uniq; rewrite perm_sort. Qed.\n\nLemma perm_sortP : transitive leT -> antisymmetric leT ->\n  forall s1 s2, reflect (sort s1 = sort s2) (perm_eq s1 s2).\nProof.\nmove=> leT_tr leT_asym s1 s2.\napply: (iffP idP) => eq12; last by rewrite -perm_sort eq12 perm_sort.\napply: eq_sorted; rewrite ?sort_sorted //.\nby rewrite perm_sort (perm_eqlP eq12) -perm_sort.\nQed.\n\nEnd SortSeq.\n\nLemma rev_sorted (T : eqType) (leT : rel T) s :\n  sorted leT (rev s) = sorted (fun y x => leT x y) s.\nProof. by case: s => //= x p; rewrite -rev_path lastI rev_rcons. Qed.\n\nLemma ltn_sorted_uniq_leq s : sorted ltn s = uniq s && sorted leq s.\nProof.\ncase: s => //= n s; elim: s n => //= m s IHs n.\nrewrite inE ltn_neqAle negb_or IHs -!andbA.\ncase sn: (n \\in s); last do !bool_congr.\nrewrite andbF; apply/and5P=> [[ne_nm lenm _ _ le_ms]]; case/negP: ne_nm.\nrewrite eqn_leq lenm; exact: (allP (order_path_min leq_trans le_ms)).\nQed.\n\nLemma iota_sorted i n : sorted leq (iota i n).\nProof. by elim: n i => // [[|n] //= IHn] i; rewrite IHn leqW. Qed.\n\nLemma iota_ltn_sorted i n : sorted ltn (iota i n).\nProof. by rewrite ltn_sorted_uniq_leq iota_sorted iota_uniq. Qed.\n\n(* Function trajectories. *)\n\nNotation fpath f := (path (coerced_frel f)).\nNotation fcycle f := (cycle (coerced_frel f)).\nNotation ufcycle f := (ucycle (coerced_frel f)).\n\nPrenex Implicits path next prev cycle ucycle mem2.\n\nSection Trajectory.\n\nVariables (T : Type) (f : T -> T).\n\nFixpoint traject x n := if n is n'.+1 then x :: traject (f x) n' else [::].\n\nLemma trajectS x n : traject x n.+1 = x :: traject (f x) n.\nProof. by []. Qed.\n\nLemma trajectSr x n : traject x n.+1 = rcons (traject x n) (iter n f x).\nProof. by elim: n x => //= n IHn x; rewrite IHn -iterSr. Qed.\n\nLemma last_traject x n : last x (traject (f x) n) = iter n f x.\nProof. by case: n => // n; rewrite iterSr trajectSr last_rcons. Qed.\n\nLemma traject_iteri x n :\n  traject x n = iteri n (fun i => rcons^~ (iter i f x)) [::].\nProof. by elim: n => //= n <-; rewrite -trajectSr. Qed.\n\nLemma size_traject x n : size (traject x n) = n.\nProof. by elim: n x => //= n IHn x //=; rewrite IHn. Qed.\n\nLemma nth_traject i n : i < n -> forall x, nth x (traject x n) i = iter i f x.\nProof.\nelim: n => // n IHn; rewrite ltnS leq_eqVlt => le_i_n x.\nrewrite trajectSr nth_rcons size_traject.\ncase: ltngtP le_i_n => [? _||->] //; exact: IHn.\nQed.\n\nEnd Trajectory.\n\nSection EqTrajectory.\n\nVariables (T : eqType) (f : T -> T).\n\nLemma eq_fpath f' : f =1 f' -> fpath f =2 fpath f'.\nProof. by move/eq_frel/eq_path. Qed.\n\nLemma eq_fcycle f' : f =1 f' -> fcycle f =1 fcycle f'.\nProof. by move/eq_frel/eq_cycle. Qed.\n\nLemma fpathP x p : reflect (exists n, p = traject f (f x) n) (fpath f x p).\nProof.\nelim: p x => [|y p IHp] x; first by left; exists 0.\nrewrite /= andbC; case: IHp => [fn_p | not_fn_p]; last first.\n  by right=> [] [[//|n]] [<- fn_p]; case: not_fn_p; exists n.\napply: (iffP eqP) => [-> | [[] // _ []//]].\nby have [n ->] := fn_p; exists n.+1.\nQed.\n\nLemma fpath_traject x n : fpath f x (traject f (f x) n).\nProof. by apply/(fpathP x); exists n. Qed.\n\nDefinition looping x n := iter n f x \\in traject f x n.\n\nLemma loopingP x n :\n  reflect (forall m, iter m f x \\in traject f x n) (looping x n).\nProof.\napply: (iffP idP) => loop_n; last exact: loop_n.\ncase: n => // n in loop_n *; elim=> [|m /= IHm]; first exact: mem_head.\nmove: (fpath_traject x n) loop_n; rewrite /looping !iterS -last_traject /=.\nmove: (iter m f x) IHm => y /splitPl[p1 p2 def_y].\nrewrite cat_path last_cat def_y; case: p2 => // z p2 /and3P[_ /eqP-> _] _.\nby rewrite inE mem_cat mem_head !orbT.\nQed.\n\nLemma trajectP x n y :\n  reflect (exists2 i, i < n & y = iter i f x) (y \\in traject f x n).\nProof.\nelim: n x => [|n IHn] x /=; first by right; case.\nrewrite inE; have [-> | /= neq_xy] := eqP; first by left; exists 0.\napply: {IHn}(iffP (IHn _)) => [[i] | [[|i]]] // lt_i_n ->.\n  by exists i.+1; rewrite ?iterSr.\nby exists i; rewrite ?iterSr.\nQed.\n\nLemma looping_uniq x n : uniq (traject f x n.+1) = ~~ looping x n.\nProof.\nrewrite /looping; elim: n x => [|n IHn] x //.\nrewrite {-3}[n.+1]lock /= -lock {}IHn -iterSr -negb_or inE; congr (~~ _).\napply: orb_id2r => /trajectP no_loop.\napply/idP/eqP => [/trajectP[m le_m_n def_x] | {1}<-]; last first.\n  by rewrite iterSr -last_traject mem_last.\nhave loop_m: looping x m.+1 by rewrite /looping iterSr -def_x mem_head.\nhave/trajectP[[|i] // le_i_m def_fn1x] := loopingP _ _ loop_m n.+1.\nby case: no_loop; exists i; rewrite -?iterSr // -ltnS (leq_trans le_i_m).\nQed.\n\nEnd EqTrajectory.\n\nImplicit Arguments fpathP [T f x p].\nImplicit Arguments loopingP [T f x n].\nImplicit Arguments trajectP [T f x n y].\nPrenex Implicits traject fpathP loopingP trajectP.\n\nSection UniqCycle.\n\nVariables (n0 : nat) (T : eqType) (e : rel T) (p : seq T).\n\nHypothesis Up : uniq p.\n\nLemma prev_next : cancel (next p) (prev p).\nProof.\nmove=> x; rewrite prev_nth mem_next next_nth; case p_x: (x \\in p) => //.\ncase def_p: p Up p_x => // [y q]; rewrite -{-1}def_p => /= /andP[not_qy Uq] p_x.\nrewrite -{2}(nth_index y p_x); congr (nth y _ _); set i := index x p.\nhave: ~~ (size q < i) by rewrite -index_mem -/i def_p leqNgt in p_x.\ncase: ltngtP => // [lt_i_q | ->] _; first by rewrite index_uniq.\nby apply/eqP; rewrite nth_default // eqn_leq index_size leqNgt index_mem.\nQed.\n\nLemma next_prev : cancel (prev p) (next p).\nProof.\nmove=> x; rewrite next_nth mem_prev prev_nth; case p_x: (x \\in p) => //.\ncase def_p: p p_x => // [y q]; rewrite -def_p => p_x.\nrewrite index_uniq //; last by rewrite def_p ltnS index_size.\ncase q_x: (x \\in q); first exact: nth_index.\nrewrite nth_default; last by rewrite leqNgt index_mem q_x.\nby apply/eqP; rewrite def_p inE q_x orbF eq_sym in p_x.\nQed.\n\nLemma cycle_next : fcycle (next p) p.\nProof.\ncase def_p: {-2}p Up => [|x q] Uq //.\napply/(pathP x)=> i; rewrite size_rcons => le_i_q.\nrewrite -cats1 -cat_cons nth_cat le_i_q /= next_nth {}def_p mem_nth //.\nrewrite index_uniq // nth_cat /= ltn_neqAle andbC -ltnS le_i_q.\nby case: (i =P _) => //= ->; rewrite subnn nth_default.\nQed.\n\nLemma cycle_prev : cycle (fun x y => x == prev p y) p.\nProof.\napply: etrans cycle_next; symmetry; case def_p: p => [|x q] //.\napply: eq_path; rewrite -def_p; exact (can2_eq prev_next next_prev).\nQed.\n\nLemma cycle_from_next : (forall x, x \\in p -> e x (next p x)) -> cycle e p.\nProof.\ncase: p (next p) cycle_next => //= [x q] n; rewrite -(belast_rcons x q x).\nmove: {q}(rcons q x) => q n_q; move/allP.\nby elim: q x n_q => //= _ q IHq x /andP[/eqP <- n_q] /andP[-> /IHq->].\nQed.\n\nLemma cycle_from_prev : (forall x, x \\in p -> e (prev p x) x) -> cycle e p.\nProof.\nmove=> e_p; apply: cycle_from_next => x p_x.\nby rewrite -{1}[x]prev_next e_p ?mem_next.\nQed.\n\nLemma next_rot : next (rot n0 p) =1 next p.\nProof.\nmove=> x; have n_p := cycle_next; rewrite -(rot_cycle n0) in n_p.\ncase p_x: (x \\in p); last by rewrite !next_nth mem_rot p_x.\nby rewrite (eqP (next_cycle n_p _)) ?mem_rot.\nQed.\n\nLemma prev_rot : prev (rot n0 p) =1 prev p.\nProof.\nmove=> x; have p_p := cycle_prev; rewrite -(rot_cycle n0) in p_p.\ncase p_x: (x \\in p); last by rewrite !prev_nth mem_rot p_x.\nby rewrite (eqP (prev_cycle p_p _)) ?mem_rot.\nQed.\n\nEnd UniqCycle.\n\nSection UniqRotrCycle.\n\nVariables (n0 : nat) (T : eqType) (p : seq T).\n\nHypothesis Up : uniq p.\n\nLemma next_rotr : next (rotr n0 p) =1 next p. Proof. exact: next_rot. Qed.\n\nLemma prev_rotr : prev (rotr n0 p) =1 prev p. Proof. exact: prev_rot. Qed.\n\nEnd UniqRotrCycle.\n\nSection UniqCycleRev.\n\nVariable T : eqType.\nImplicit Type p : seq T.\n\nLemma prev_rev p : uniq p -> prev (rev p) =1 next p.\nProof.\nmove=> Up x; case p_x: (x \\in p); last first.\n  by rewrite next_nth prev_nth mem_rev p_x.\ncase/rot_to: p_x (Up) => [i q def_p] Urp; rewrite -rev_uniq in Urp.\nrewrite -(prev_rotr i Urp); do 2 rewrite -(prev_rotr 1) ?rotr_uniq //.\nrewrite -rev_rot -(next_rot i Up) {i p Up Urp}def_p.\nby case: q => // y q; rewrite !rev_cons !(=^~ rcons_cons, rotr1_rcons) /= eqxx.\nQed.\n\nLemma next_rev p : uniq p -> next (rev p) =1 prev p.\nProof. by move=> Up x; rewrite -{2}[p]revK prev_rev // rev_uniq. Qed.\n\nEnd UniqCycleRev.\n\nSection MapPath.\n\nVariables (T T' : Type) (h : T' -> T) (e : rel T) (e' : rel T').\n\nDefinition rel_base (b : pred T) :=\n  forall x' y', ~~ b (h x') -> e (h x') (h y') = e' x' y'.\n\nLemma map_path b x' p' (Bb : rel_base b) :\n    ~~ has (preim h b) (belast x' p') ->\n  path e (h x') (map h p') = path e' x' p'.\nProof. by elim: p' x' => [|y' p' IHp'] x' //= /norP[/Bb-> /IHp'->]. Qed.\n\nEnd MapPath.\n\nSection MapEqPath.\n\nVariables (T T' : eqType) (h : T' -> T) (e : rel T) (e' : rel T').\n\nHypothesis Ih : injective h.\n\nLemma mem2_map x' y' p' : mem2 (map h p') (h x') (h y') = mem2 p' x' y'.\nProof. by rewrite {1}/mem2 (index_map Ih) -map_drop mem_map. Qed.\n\nLemma next_map p : uniq p -> forall x, next (map h p) (h x) = h (next p x).\nProof.\nmove=> Up x; case p_x: (x \\in p); last by rewrite !next_nth (mem_map Ih) p_x.\ncase/rot_to: p_x => i p' def_p.\nrewrite -(next_rot i Up); rewrite -(map_inj_uniq Ih) in Up.\nrewrite -(next_rot i Up) -map_rot {i p Up}def_p /=.\nby case: p' => [|y p''] //=; rewrite !eqxx.\nQed.\n\nLemma prev_map p : uniq p -> forall x, prev (map h p) (h x) = h (prev p x).\nProof.\nmove=> Up x; rewrite -{1}[x](next_prev Up) -(next_map Up).\nby rewrite prev_next ?map_inj_uniq.\nQed.\n\nEnd MapEqPath.\n\nDefinition fun_base (T T' : eqType) (h : T' -> T) f f' :=\n  rel_base h (frel f) (frel f').\n\nSection CycleArc.\n\nVariable T : eqType.\nImplicit Type p : seq T.\n\nDefinition arc p x y := let px := rot (index x p) p in take (index y px) px.\n\nLemma arc_rot i p : uniq p -> {in p, arc (rot i p) =2 arc p}.\nProof.\nmove=> Up x p_x y; congr (fun q => take (index y q) q); move: Up p_x {y}.\nrewrite -{1 2 5 6}(cat_take_drop i p) /rot cat_uniq => /and3P[_ Up12 _].\nrewrite !drop_cat !take_cat !index_cat mem_cat orbC.\ncase p2x: (x \\in drop i p) => /= => [_ | p1x].\n  rewrite index_mem p2x [x \\in _](negbTE (hasPn Up12 _ p2x)) /= addKn.\n  by rewrite ltnNge leq_addr catA.\nby rewrite p1x index_mem p1x addKn ltnNge leq_addr /= catA.\nQed.\n\nLemma left_arc x y p1 p2 (p := x :: p1 ++ y :: p2) :\n  uniq p -> arc p x y = x :: p1.\nProof.\nrewrite /arc /p [index x _]/= eqxx rot0 -cat_cons cat_uniq index_cat.\nmove: (x :: p1) => xp1 /and3P[_ /norP[/= /negbTE-> _] _].\nby rewrite eqxx addn0 take_size_cat.\nQed.\n\nLemma right_arc x y p1 p2 (p := x :: p1 ++ y :: p2) :\n  uniq p -> arc p y x = y :: p2.\nProof.\nrewrite -[p]cat_cons -rot_size_cat rot_uniq => Up.\nby rewrite arc_rot ?left_arc ?mem_head.\nQed.\n\nCoInductive rot_to_arc_spec p x y :=\n    RotToArcSpec i p1 p2 of x :: p1 = arc p x y\n                          & y :: p2 = arc p y x\n                          & rot i p = x :: p1 ++ y :: p2 :\n    rot_to_arc_spec p x y.\n\nLemma rot_to_arc p x y :\n  uniq p -> x \\in p -> y \\in p -> x != y -> rot_to_arc_spec p x y.\nProof.\nmove=> Up p_x p_y ne_xy; case: (rot_to p_x) (p_y) (Up) => [i q def_p] q_y.\nrewrite -(mem_rot i) def_p inE eq_sym (negbTE ne_xy) in q_y.\nrewrite -(rot_uniq i) def_p.\ncase/splitPr: q / q_y def_p => q1 q2 def_p Uq12; exists i q1 q2 => //.\n  by rewrite -(arc_rot i Up p_x) def_p left_arc.\nby rewrite -(arc_rot i Up p_y) def_p right_arc.\nQed.\n\nEnd CycleArc.\n\nPrenex Implicits arc.\n\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect1.4_v8.3/theories/path.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7306955739682737}}
{"text": "(* Definition *)\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\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\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nDefinition ltb (n m : nat) : bool :=\n    andb (n <=? m) (negb (n =? m)).\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nDefinition gtb (n m : nat) : bool := negb (leb n m).\nDefinition geb (n m : nat) : bool := negb (ltb n m).\n\nNotation \"x >? y\" := (gtb x y) (at level 70) : nat_scope.\nNotation \"x >=? y\" := (geb x y) (at level 70) : nat_scope.\n\n(* Definition *)\nInductive list (X : Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\nArguments nil {X}.\nArguments cons {X} _ _.\n\nFixpoint repeat {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil\n  | S count' => cons x (repeat x count')\n  end.\n\n(* Exercise *)\n(**no\n  yes\n  yes\n  yes\n  yes\n  no\n  no*)\n\n(* Definition *)\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\nFixpoint app {X : Type} (l1 l2 : list X) : (list X) :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(* Exercise *)\nTheorem app_nil_r : forall (X : Type), forall l : list X,\n  l ++ [] = l.\nProof.\n  intro X.\n  induction l as [| a t IH].\n  - reflexivity.\n  - simpl. rewrite -> IH. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n : list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intro A.\n  intros l m n.\n  induction l as [| a t IH].\n  - reflexivity.\n  - simpl. rewrite -> IH. reflexivity.\nQed.\n\nLemma app_length : forall (X : Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1 as [| a t IH].\n  - reflexivity.\n  - simpl. rewrite -> IH. reflexivity.\nQed.\n\n(* Exercise *)\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1 as [| a t IH].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IH, app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall (X : Type) (l : list X),\n  rev (rev l) = l.\nProof.\n  intros X l.\n  induction l as [| a t IH].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr, IH. reflexivity.\nQed.\n\n(* Definition *)\nInductive prod (X Y : Type) : Type :=\n  | pair (x : X) (y : Y).\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y) : list (X * Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(* Exercise *)\n(* forall X Y : Type,\n       list X -> list Y -> list (X * Y) *)\n(* [(1, false); (2, false)]\n     : list (nat * bool) *)\n\n(* Exercise *)\nFixpoint split {X Y : Type} (l : list (X * Y))\n               : (list X) * (list Y) :=\n  match l with\n  | nil => ([], [])\n  | (a, b) :: t => let (x', y') := split t in (a :: x', b :: y')\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n\n(* Definition *)\nModule OptionPlayground.\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\nArguments Some {X}.\nArguments None {X}.\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n  end.\n\n(* Exercise *)\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | nil => None\n  | a :: _ => Some a\n  end.\n\nCheck @hd_error : forall X : Type, list X -> option X.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error [[1];[2]] = Some [1].\nProof. reflexivity. Qed.\n\n(* Definition *)\nFixpoint filter {X : Type} (test : X -> bool) (l : list X)\n                : (list X) :=\n  match l with\n  | [] => []\n  | h :: t => if test h then h :: (filter test t)\n                        else filter test t\n  end.\n\n(* Exercise *)\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => andb (evenb n) (gtb n 7)) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\n(* Exercise *)\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X) : list X * list X :=\n  (filter test l, filter (fun x => negb (test x)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\n(* Definition *)\nFixpoint map {X Y: Type} (f:X -> Y) (l : list X) : (list Y) :=\n  match l with\n  | [] => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(* Exercise *)\nLemma map_app_r : forall\n  (X Y : Type) (f : X -> Y) (l : list X) (a : X),\n  map f (l ++ [a]) = map f l ++ [f a].\nProof.\n  intros X Y f l a.\n  induction l as [| h t IH].\n  - reflexivity.\n  - simpl. rewrite -> IH. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [| a t IH].\n  - reflexivity.\n  - simpl. rewrite -> map_app_r, IH. reflexivity.\nQed.\n\n(* Exercise *)\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X): (list Y) :=\n  match l with\n  | nil => nil\n  | a :: t => f a ++ flat_map f t\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n\n(* Definition *)\nFixpoint fold {X Y: Type} (f: X -> Y -> Y) (l: list X) (b: Y): Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(* Exercise *)\n(** For, example, while inserting a nat into a nat list, and \n  we always want to know the sum. *)\n\n(* Exercise *)\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1: fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\nTheorem fold_length_correct: forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [| a t IH].\n  - reflexivity.\n  - simpl. rewrite <- IH. reflexivity.\nQed.\n\n(* Exercise *)\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n  fold (fun x l => f x :: l) l [].\n\nExample test_fold_map1: fold_map negb [true;true;true] = [false;false;false].\nProof. reflexivity. Qed.\n\nTheorem fold_map_correct: forall\n  (X Y: Type) (f: X -> Y) (l: list X),\n  fold_map f l = map f l.\nProof.\n  intros X Y f l.\n  induction l as [| a t IH].\n  - reflexivity.\n  - simpl. rewrite <- IH. reflexivity.\nQed.\n\n(* Exercise *)\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  let (x, y) := p in f x y.\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nTheorem uncurry_curry: forall\n  (X Y Z : Type) (f : X -> Y -> Z) x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z f x y.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry: forall\n  (X Y Z : Type) (f : (X * Y) -> Z)\n  (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  destruct p.\n  reflexivity.\nQed.\n\n(* Definition *)\nModule Church.\n\nDefinition cnat := forall X: Type, (X -> X) -> X -> X.\n\nDefinition zero: cnat :=\n  fun (X: Type) (f: X -> X) (x: X) => x.\n\nDefinition one: cnat :=\n  fun (X: Type) (f: X -> X) (x: X) => f x.\n\nDefinition two: cnat :=\n  fun (X: Type) (f: X -> X) (x: X) => f (f x).\n\nDefinition three: cnat :=\n  fun (X: Type) (f: X -> X) (x: X) => f (f (f x)).\n\n(* Exercise *)\nDefinition succ (n: cnat): cnat :=\n  fun (X: Type) (f: X -> X) (x: X) => f (n X f x).\n\nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\n(* Exercise *)\nDefinition plus (n m : cnat): cnat :=\n  fun (X: Type) (f: X -> X) (x: X) => m X f (n X f x).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\n(* Exercise *)\nDefinition mult (n m : cnat): cnat :=\n  fun (X: Type) (f: X -> X) (x: X) => m X (n X f) x.\n\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\n(* Exercise *)\nDefinition exp (n m: cnat): cnat :=\n  fun (X: Type) => m (X -> X) (n X).\n  (* fun (X: Type) (f: X -> X) (x: X) => m cnat (mult n) one. *)\n\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\nExample exp_2 : exp three zero = one.\nProof. reflexivity. Qed.\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\nEnd Church.\n\n\n", "meta": {"author": "pikapikapikaori", "repo": "Coq", "sha": "d2af0d21f12b45ee70c3298882b219a133ba9425", "save_path": "github-repos/coq/pikapikapikaori-Coq", "path": "github-repos/coq/pikapikapikaori-Coq/Coq-d2af0d21f12b45ee70c3298882b219a133ba9425/sf-exercise/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.872347368040789, "lm_q1q2_score": 0.730695570432217}}
{"text": "(**\n* A vector library\nI am probably more or less reinventing the wheel here,\nbut I found the standard library's vector implementations\n([Coq.Vectors.*])\ninsufficient for two reasons.\nThe first reason is that\nvectors are defined as separate inductive types,\ninstead of as functions to [Type],\nwith which a lot would come for free by computation\nand with which induction proofs would be easier.\nThe second reason is that\nall functions are defined under the interpretation that\nvectors are built by appending a vector to an element.\nFor my purposes the reverse interpretation---that\nvectors are built by appending an element to a vector---is\nmore suitable.\n*)\n\nRequire Import Coq.Classes.Morphisms.\n\nRequire Import fin.\n\nImport FIN.NOTATIONS.\nLocal Open Scope FIN.\n\nLocal Infix \"∘\" :=\n  (fun g f => fun x => g (f x)) (at level 5, left associativity).\n\nModule VEC.\n\n  (**\n  ** Definitions\n  *)\n\n  (**\n  *** One empty vector for every type\n  *)\n\n  Inductive Empty (A : Type) := empty.\n  Arguments empty {_}.\n\n  (**\n  *** Vectors\n  For each type [A],\n  there is one [A]-vector of length [0]---the empty vector---and\n  the type of [A]-vectors of length [S n] is\n  the product of the type of [A]-vectors of length [n] and [A].\n  *)\n\n  Fixpoint t A (n : nat) : Type :=\n  match n with\n  | O   => Empty A\n  | S n => prod (t A n) A\n  end.\n  Local Notation \"()\" := (empty : t _ 0).\n  Local Infix \";;\" :=\n    ((fun A n (v : t A n) (a : A) => ((v, a) : t A (S n))) _ _)\n    (at level 40, left associativity).\n\n  (**\n  *** Accessing elements of a vector\n  *)\n\n  Fixpoint nth {A} {n} : t A n -> FIN.t n -> A :=\n  match n with\n  | O   => fun _ x => False_rect _ (FIN.THMS.t0Empty x)\n  | S n => fun v x => let (v, a) := v in\n                      match x with\n                      | inl x => nth v x\n                      | inr _ => a\n                      end\n  end.\n\n  (**\n  *** Vectors of copies of an element\n  *)\n\n  Fixpoint copies {A} (n : nat) (a : A) : t A n :=\n  match n with\n  | O   => ()\n  | S n => (copies n a, a)\n  end.\n\n  (**\n  *** Concatenation of vectors\n  *)\n\n  Fixpoint concat {A} {n m} (v : t A n) : t A m -> t A (m + n) :=\n  match m with\n  | O   => fun _ => v\n  | S m => fun w => let (w, a) := w in (concat v w, a)\n  end.\n\n  (**\n  *** Mapping functions on vectors\n  The map of [f : A -> B]\n  over an [A]-vector [((), a1, a2, .., an)]\n  is the [B]-vector [((), f a1, f a2, ..., f an)].\n  *)\n\n  Fixpoint map {A B} {n} (f : A -> B) : t A n -> t B n :=\n  match n with\n  | O   => fun _ => ()\n  | S n => fun v => let (v, a) := v in (map f v, f a)\n  end.\n\n  (**\n  *** Vectors as the image of functions on the canonically finite sets\n  *)\n\n  Fixpoint finMap {A} {n} : (FIN.t n -> A) -> t A n :=\n  match n with\n  | O   => fun _ => ()\n  | S n => fun f => (finMap (fun x => f ++x), f FIN.last)\n  end.\n\n  Definition finMap' {A} {n k} (f : FIN.t (k + n) -> A) : t A n :=\n    finMap (fun x => f (FIN.up' x)).\n\n  (**\n  *** Left fold\n  *)\n\n  Fixpoint foldl {A} {n} (f : A -> A -> A) : A -> t A n -> A :=\n  match n with\n  | O   => fun a _ => a\n  | S n => fun a v => let (v, b) := v in f (foldl f a v) b\n  end.\n\n  (**\n  ** Notations\n  *)\n\n  Module NOTATIONS.\n\n    Delimit Scope VEC with VEC.\n\n    Notation \"()\" := () : VEC.\n    Infix \";;\" := (fun v a => v;; a) (at level 40, left associativity) : VEC.\n\n  End NOTATIONS.\n\n  (**\n  ** Theorems\n  *)\n\n  Module Type THMS_SIG.\n\n    (**\n    *** Correctness of copies\n    *)\n\n    Axiom nthCopiesEq :\n      forall {A} {n} (a : A) (x : FIN.t n), nth (copies n a) x = a.\n\n    (**\n    *** Correctness of concatenation\n    *)\n\n    Axiom nthConcatEq1 :\n      forall  {A} {n m} (x : FIN.t n) (v : t A n) (w : t A m),\n      nth (concat v w) (FIN.up' x) = nth v x.\n\n    (**\n    It is harder to state that\n    concatenation is correct\n    with respect to\n    the second vector.\n    I do not need this fact so\n    I will skip it.\n    *)\n\n    (**\n    *** Correctness of map\n    *)\n\n    Axiom nthMapEq :\n      forall {A B} {n} (f : A -> B) (v : t A n) (x : FIN.t n),\n      nth (map f v) x = f (nth v x).\n\n    (**\n    *** Correctness of maps from canonically finite types\n    *)\n\n    Axiom nthFinMapEq :\n      forall {A} {n} (f : FIN.t n -> A) (x : FIN.t n),\n      VEC.nth (finMap f) x = f x.\n\n    Axiom nthFinMapEq' :\n      forall {A} {n k} (f : FIN.t (k + n) -> A) (x : FIN.t n),\n      VEC.nth (finMap' f) x = f (FIN.up' x).\n\n    (**\n    *** Equality is pointwise equality\n    *)\n\n    Axiom pointwiseEquality :\n      forall {A} {n} (v w : t A n),\n      v = w <-> (forall x : FIN.t n, nth v x = nth w x).\n\n    (**\n    *** Map respects extensionality\n    *)\n\n    Declare Instance mapRespectsExtensionality {A B} {n} :\n      Proper ((fun f g => forall a : A, f a = g a) ==> eq ==> eq) (@map A B n).\n\n    (**\n    *** Map and composition\n    *)\n\n    Axiom mapComposeEq :\n      forall {A B C} {n} (f : A -> B) (g : B -> C) (v : t A n),\n      map g (map f v) = map g∘f v.\n\n    (**\n    *** Map and concatenation\n    *)\n\n    Axiom mapConcatEq :\n      forall {A B} {n m} (f : A -> B) (v : VEC.t A n) (w : VEC.t A m),\n      map f (concat v w) = concat (map f v) (map f w).\n\n    (**\n    *** Maps from canonically finite types and composition\n    *)\n\n    Axiom finMapComposeEq :\n      forall {A B} {n} (f : FIN.t n -> A) (g : A -> B),\n      map g (finMap f) = finMap g∘f.\n\n    Axiom finMapComposeEq' :\n      forall {A B} {n k} (f : FIN.t (k+n) -> A) (g : A -> B),\n      map g (finMap' f) = finMap' g∘f.\n\n    (**\n    *** Left fold and concatenation\n    *)\n\n    Axiom foldlConcatEq :\n      forall {A} {n m} (f : A -> A -> A) (a : A) (v : t A n) (w : t A m),\n      foldl f a (concat v w) = foldl f (foldl f a v) w.\n\n  End THMS_SIG.\n\n  (**\n  ** Proofs\n  *)\n\n  Module THMS : THMS_SIG.\n\n    Theorem nthCopiesEq {A} {n} (a : A) (x : FIN.t n) : nth (copies n a) x = a.\n    Proof.\n      induction n as [ | n IHn]; simpl.\n      - inversion x.\n      - destruct x as [x | x].\n        + apply IHn.\n        + reflexivity.\n    Qed.\n\n    Theorem nthConcatEq1 {A} {n m} (x : FIN.t n) (v : t A n) (w : t A m) :\n      nth (concat v w) (FIN.up' x) = nth v x.\n    Proof.\n      induction m as [ | m IHm].\n      - reflexivity.\n      - destruct w as [w a]. apply IHm.\n    Qed.\n\n    Theorem nthMapEq {A B} {n} (f : A -> B) (v : t A n) (x : FIN.t n) :\n      nth (map f v) x = f (nth v x).\n    Proof.\n      induction n as [ | n IHn].\n      - inversion x.\n      - destruct v as [v a]. destruct x as [x | x].\n        + apply IHn.\n        + reflexivity.\n    Qed.\n\n    Theorem nthFinMapEq {A} {n} (f : FIN.t n -> A) (x : FIN.t n) :\n      VEC.nth (finMap f) x = f x.\n    Proof.\n      induction n as [ | n IHn].\n      - inversion x.\n      - destruct x as [x | x]; simpl.\n        + rewrite IHn. reflexivity.\n        + destruct x. reflexivity.\n    Qed.\n\n    Theorem nthFinMapEq' {A} {n k} (f : FIN.t (k + n) -> A) (x : FIN.t n) :\n      VEC.nth (finMap' f) x = f (FIN.up' x).\n    Proof. unfold finMap'. rewrite nthFinMapEq. reflexivity. Qed.\n\n    Theorem pointwiseEquality {A} {n} (v w : t A n) :\n      v = w <-> (forall x : FIN.t n, nth v x = nth w x).\n    Proof.\n      split; [intro; subst; tauto | ].\n      intro H.\n      induction n as [ | n IHn].\n      - destruct v, w. reflexivity.\n      - destruct v as [v a], w as [w b].\n        specialize (IHn v w).\n        pose proof (H FIN.last) as H'. simpl in H'. rewrite H'. clear H'.\n        lapply IHn; [intro; subst; tauto | ]. clear IHn.\n        intro x. exact (H ++x).\n    Qed.\n\n    Instance mapRespectsExtensionality {A B} {n} :\n      Proper ((fun f g => forall a : A, f a = g a) ==> eq ==> eq) (@map A B n).\n    Proof.\n      intros f g Hfg v' v H. subst.\n      induction n as [ | n IHn].\n      - reflexivity.\n      - destruct v as [v a]. simpl. rewrite IHn, Hfg. reflexivity.\n    Qed.\n\n    Theorem mapComposeEq {A B C} {n} (f : A -> B) (g : B -> C) (v : t A n) :\n      map g (map f v) = map g∘f v.\n    Proof.\n      induction n as [ | n IHn].\n      - reflexivity.\n      - destruct v as [v a]. simpl. rewrite IHn. reflexivity.\n    Qed.\n\n    Theorem mapConcatEq {A B} {n m} (f : A -> B) (v : VEC.t A n)\n                        (w : VEC.t A m) :\n      map f (concat v w) = concat (map f v) (map f w).\n    Proof.\n      induction m as [ | m IHm]; simpl.\n      - reflexivity.\n      - destruct w as [w a]. rewrite IHm. reflexivity.\n    Qed.\n\n    Theorem finMapComposeEq {A B} {n} (f : FIN.t n -> A) (g : A -> B) :\n      map g (finMap f) = finMap g∘f.\n    Proof.\n      induction n as [ | n IHn].\n      - reflexivity.\n      - simpl. rewrite IHn. reflexivity.\n    Qed.\n\n    Theorem finMapComposeEq' {A B} {n k} (f : FIN.t (k+n) -> A) (g : A -> B) :\n      map g (finMap' f) = finMap' g∘f.\n    Proof. unfold finMap'. apply finMapComposeEq. Qed.\n\n    Theorem foldlConcatEq {A} {n m} (f : A -> A -> A) (a : A) (v : t A n)\n                          (w : t A m) :\n      foldl f a (concat v w) = foldl f (foldl f a v) w.\n    Proof.\n      induction m as [ | m IHm]; simpl.\n      - reflexivity.\n      - destruct w as [w b]. rewrite IHm. reflexivity.\n    Qed.\n\n  End THMS.\n\nEnd VEC.\n", "meta": {"author": "anderslundstedt", "repo": "pca-realizability", "sha": "56d9d0aea258fabaef780eefabc49b75cd9be1ff", "save_path": "github-repos/coq/anderslundstedt-pca-realizability", "path": "github-repos/coq/anderslundstedt-pca-realizability/pca-realizability-56d9d0aea258fabaef780eefabc49b75cd9be1ff/coq/vec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.8499711718571774, "lm_q1q2_score": 0.730689402368054}}
{"text": "Require Import stdpp.list.\nRequire Import ssreflect.\nFrom Tweetnacl Require Import Libs.Export.\nFrom Tweetnacl Require Import ListsOp.Export.\n\nOpen Scope Z.\n\n(* Some definitions relating to the functional spec of this particular program.  *)\nFixpoint ZsumList (a b : list Z) : list Z := match a,b with\n| [], q => q\n| q,[] => q\n| h1::q1,h2::q2 => (Z.add h1 h2) :: ZsumList q1 q2\nend.\n\nNotation \"A ⊕ B\" := (ZsumList A B) (at level 60, right associativity).\n\nLemma ZsumList_Zipp_eq: forall  (a b : list Z), ZsumList a b = Zipp Z.add a b.\nProof.\n  elim => [|a l IHa] [|b Hb] ; go.\n  rewrite Zipp_nil_l ; go.\n  rewrite Zipp_nil_r ; go.\n  intro x ; go.\nQed.\n\nLemma ZsumList_nth : forall (n:nat) (a b : list Z),\n  length a = length b ->\n  (n < length a)%nat ->\n  nth n (a ⊕ b) 0 = (nth n a 0) + (nth n b 0).\nProof. intros; rewrite ?ZsumList_Zipp_eq; apply Zipp_nth_length ; auto. Qed.\n\nLemma ZsubList_nth_Zlength : forall (n:Z) (a b : list Z),\n  0 <= n ->\n  Zlength a = Zlength b ->\n  n < Zlength a ->\n  nth (Z.to_nat n) (a ⊕ b) 0 = (nth (Z.to_nat n) a 0) + (nth (Z.to_nat n) b 0).\nProof. intros; rewrite ?ZsumList_Zipp_eq; apply Zipp_nth_Zlength ; auto. Qed.\n\nLemma ZsumList_comm: forall a b, a ⊕ b = b ⊕ a.\nProof.\n  move => a b.\n  rewrite ?ZsumList_Zipp_eq.\n  apply Zipp_comm => x y ; omega.\nQed.\n\nLemma ZsumList_nil_r: forall a, a ⊕ [] = a.\nProof.\n  intros a.\n  rewrite ZsumList_Zipp_eq.\n  apply Zipp_nil_r => x ; omega.\nQed.\n\nLemma ZsumList_nil_l: forall a, [] ⊕ a = a.\nProof. go. Qed.\n\nLemma ZsumList_assoc : forall a b c, (a ⊕ b) ⊕ c = a ⊕ (b ⊕ c).\nProof.\n  move=> a b c.\n  rewrite ?ZsumList_Zipp_eq.\n  apply Zipp_assoc => x ; try omega.\n  move=> y z ; omega.\nQed.\n\nLemma ZsumList_take : forall n a b, take n (a ⊕ b) = (take n a) ⊕ (take n b).\nProof. intros n a b ; rewrite ?ZsumList_Zipp_eq ;  apply Zipp_take. Qed.\n\nLemma ZsumList_drop : forall n a b, drop n (a ⊕ b) = (drop n a) ⊕ (drop n b).\nProof. intros n a b ; rewrite ?ZsumList_Zipp_eq ;  apply Zipp_drop ; go. Qed.\n\nLemma ZsumList_length : forall a b, length (a ⊕ b) = length a \\/ length (a ⊕ b) = length b.\nProof. intros a b ; rewrite ?ZsumList_Zipp_eq; apply Zipp_length. Qed.\n\nLemma ZsumList_Zlength : forall a b, Zlength (a ⊕ b) = Zlength a \\/ Zlength (a ⊕ b) = Zlength b.\nProof. intros a b ; rewrite ?ZsumList_Zipp_eq; apply Zipp_Zlength. Qed.\n\nLemma ZsumList_length_max : forall a b, length (a ⊕ b) = max (length a) (length b).\nProof. intros a b ; rewrite ?ZsumList_Zipp_eq; apply Zipp_length_max. Qed.\n\nLemma ZsumList_Zlength_max : forall a b, Zlength (a ⊕ b) = Z.max (Zlength a) (Zlength b).\nProof. intros a b ; rewrite ?ZsumList_Zipp_eq; apply Zipp_Zlength_max. Qed.\n\nClose Scope Z.", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/proofs/spec/Mid/SumList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013355, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7305803502524307}}
{"text": "(** \n* Logic in Coq\n  \n  From: https://www.cs.cornell.edu/courses/cs3110/2018sp/l/20-coq-logic/notes.v \n-----\n#<i>#\nTopics:\n\n- propositions and proofs\n- [Prop] and [Set]\n- propositional logic\n- implication\n- conjunction\n- disjunction\n- [False] and [True]\n- negation\n- equality and implication revisited\n- tautologies\n\n#</i>#\n\n-----\n\n(**********************************************************************)\n\n\n** Propositions and proofs\n\nRecall that the [Check] command type checks an expression and causes Coq\nto output the type in the output window. \n*)\n\nCheck list.\n\n(** The type of [list] is [Type -> Type].  It takes a type as input and produces\na type as output.  Thus, like OCaml's [list], Coq's [list] is a type\nconstructor. But unlike OCaml, the type of Coq's [list] contains [->],\nindicating that it is a function.  In Coq, [list] truly is a function that can\nbe applied: *)\n\nDefinition natlist : Type := list nat.\nCheck natlist.\n\n(**\nThink of Coq's [list] as a _type-level function_:  it is a function that takes\ntypes as inputs and produces types as outputs.  OCaml doesn't have anything\nexactly equivalent to that.  \n\nWhat, then, is the type of a theorem?\n*)\n\nTheorem obvious_fact : 1 + 1 = 2.\nProof. trivial. Qed.\nCheck obvious_fact.\n\n(**\nCoq responds:\n<<\nobvious_fact : 1 + 1 = 2\n>>\n\nSo the type of [obvious_fact] is [1 + 1 = 2].  That might seem rather\nmysterious. After all, [1 + 1 = 2] is definitely not an OCaml type.  But Coq's\ntype system is far richer than OCaml's.  In OCaml, we could think of [42 : int]\nas meaning that [42] is a _meaningful_ expression of type [int].  There are\nlikewise _meaningless_ expressions---for example, [42+true] is meaningless in\nOCaml, and it therefore cannot be given a type.  The meaning of [int] in OCaml\nis that of a computation producing a value that fits within 2^63 bits and can be\ninterpreted as an element of Z, the mathematical set of integers.  \n\nSo what are meaningful Coq expressions of type [1 + 2 = 2]?  They are the\n_proofs_ of [1 + 1 = 2].  There might be many such proofs; here are two: \n\n- reduce [1+1] to [2], then note that [x=x]. \n\n- subtract [1] from both sides, resulting in [1 + 1 - 1 = 2 - 1], reduce both \n  sides to [1], then note that [x = x]. \n\nRegardless of the exact proof, it is an _argument_ for, or _evidence_ for, the\nassertion that [1 + 1 = 2].  So when we say that [obvious_fact : 1 + 1 = 2],\nwhat we're really saying is that [obvious_fact] is a proof of [1 + 1 = 2].\n\nLikewise, when we write [Definition x := 42.] in Coq, and then observe that [x :\nnat], what we're saying is not just that [x] has type [nat], but also that there\nis _evidence_ for the type [nat], i.e., that there do exist values of that type.\nMany of them, in fact---just like there are many proofs of [1 + 1 = 2].\n\nSo now we have an explanation for what the type of [obvious_fact] is. But what\nis its value?  Let's ask Coq.\n*)\n\nPrint obvious_fact.\n\n(**\nCoq responds:\n<<\nobvious_fact = eq_refl : 1 + 1 = 2\n>>\nSo what is [eq_refl]?\n*)\n\nPrint eq_refl.\n\n(** Amidst all the output that produces, you will spy \n<< \neq_refl : x = x \n>> \nThat is, [eq_refl] has type [x = x].  In other words, [eq_refl] asserts\nsomething is always equal to itself, a property known as the _reflexivity of\nequality_.\n\nSo the proof of [1 + 1 = 2] in Coq is really just that equality\nis reflexive.  It turns out that Coq evaluates expressions before applying that\nfact, so it evaluates [1+1] to [2], resulting in [2 = 2], which holds by\nreflexivity.  Thus the proof we found above, using the [trivial] tactic,\ncorresponds to the first of the two possible proofs we sketched.\n*)\n\n(**********************************************************************)\n\n(**\n** [Prop] and [Set]\n\nWe've now seen that there are programs and proofs in Coq.  Let's investigate\ntheir types.  We already know that [42], a program, has type [nat], and that\n[eq_refl : 1 + 1 = 2].  But let's now investigate what the types of [nat] and [1\n+ 1 = 2] are.  First, [nat]:\n*)\n\nCheck nat.\n\n(**\nCoq says that [nat : Set].  Here, [Set] is a predefined keyword in Coq that we\ncan think of as meaning all program data types.  Further, we can ask what the\ntype of [Set] is:\n*)\n\nCheck Set.\n\n(** \nCoq says that [Set : Type], so [Set] is a type.  The Coq documentation\ndescribes [Set] as being the type of _program specifications_, which describe\ncomputations.  For example, \n\n- [42] specifies a computation that simply returns [42].  It's a specification\n  because [42 : nat] and [nat : Set].\n\n- [fun x:nat => x+1] specifies a computation that increments a natural number.\n  It's a specification because it has type [nat -> nat], and [nat -> nat : Set].\n\n- We could also write more complicated specifications to express computations\n  such as list sorting functions, or binary search tree lookups.\n\nNext, let's investigate what the type of [1 + 1 = 2] is.\n*)\n\nCheck 1 + 1 = 2.\n\n(**\nCoq says that [1 + 1 = 2 : Prop].  This is the type of _propositions_, which are\nlogical formulas that we can attempt to prove.  Note that propositions are not\nnecessarily provable though. For example, [2110 = 3110] has type [Prop], even\nthough it obviously does not hold. What is the type of [Prop]?\n*)\n\nCheck Prop.\n\n(**\nCoq says that [Prop : Type].  So [Prop] is also a type.  So far we have seen one\nway of creating a proposition, by using the equality operator.  We could attempt\nto learn more about that operator with [Check =.], but that will result in an\nerror:  [Check] doesn't work on this kind of notation, and there isn't something\nlike in OCaml where we can wrap an operator in parentheses.  Instead, we need to\nfind out what function name that operator corresponds to.  The command for that\nis [Locate].\n*)\n\nLocate \"=\".\n\n(**\nCoq tells us two possible meanings for [=], and the second is what we want: \n<<\n\"x = y\" := eq x y\n>>\nThat means that anywhere [x = y] appears, Coq understands it as the function\n[eq] applied to [x] and [y].  Now that we know the name of that function, we can\ncheck it:\n*)\n\nCheck eq.\n\n(**\nThe output of that is a bit mysterious because of the [?A] that shows up in it.\nWhat's going on is that [eq] has an implicit type argument.  (Implicit arguments\nwere discussed in the previous set of notes.)  If we prefix [eq] with [@] to\ntreat the argument as explicit, we can get more readable output.\n*)\n\nCheck @eq.\n\n(**\nCoq says that \n<<\n@eq : forall A : Type, A -> A -> Prop\n>>\nIn other words, [@eq] takes a type argument [A], a value of type [A], another\nvalue of type [A], and returns a proposition, which is the proposition asserting\nthe equality of those two values. So:\n\n- [@eq nat 42 42] asserts the equality of [42] and [42], i.e., [42 = 42].  So \n  does [eq 42 42], where [nat] is implicit.\n\n- [@eq nat 2110 3110] asserts the equality of [2110] and [3110].  \n  So does [eq 2110 3110] and [2110=3110].  Of course they aren't equal, but\n  we're still allowed to form such a proposition, even if it isn't provable.\n\n- [@eq (nat->nat) (fun x => x+1) (fun n => 1+n)] asserts the equality of two \n  syntactically different increment functions, as does [eq (fun x => x+1) \n  (fun n => 1+n)] and [(fun x => x+1) = (fun x => 1+n)].\n\n*)\n\n(**********************************************************************)\n\n(**\n** Propositional logic\n\nThe standard propositional logic _connectives_ (ways of syntactically connecting\npropositions together) are:\n\n- Implication: [P -> Q].  In English we usually express this connective as \n   \"if [P], then [Q]\" or \"P implies Q\".\n\n- Conjunction: [P /\\ Q].  In English we usually express this connective as\n  \"P and Q\".\n\n- Disjunction: [P \\/ Q].  In English we usually express this connective as\n  \"P or Q\".  Keep in mind that this is the sense of the word \"or\" that\n  allows one or both of [P] and [Q] to hold, rather than exactly one.\n\n- Negation: [~P].  In English we usually express this connective as\n  \"not P\".\n\nAll of these are ways of creating propositions in Coq.  Implication is so\nprimitive that it's simply \"baked in\" to Coq.  But the other connectives are\ndefined as part of Coq's standard library under the very natural names of [and],\n[or], and [not].\n\nIn addition to those connectives, there are two propositions [True] and\n[False] which always and never hold, respectively.  And we can have\nvariables representing propositions.  Idiomatically, we usually choose\nnames like [P], [Q], [R], ... for those variables.\n*)\n\nCheck and.\nCheck or.\nCheck not.\n\n(**\n<<\nand : Prop -> Prop -> Prop\nor  : Prop -> Prop -> Prop\nnot : Prop -> Prop\n>>\nBoth [and] and [or] take two propositions as input and return a proposition;\n[not] takes one proposition as input and returns a proposition.\n\nAt this point, you might have noticed that [->] seems to be overloaded:\n\n- [t1 -> t2] is the type of functions that take an input of type [t1] and \n  return an output of type [t2].\n\n- [P -> Q] is an proposition that asserts [P] implies [Q].\n\nThere is a uniform way to think about both uses of [->], which is as a\n_transformer_.  A function of type [t1 -> t2] transforms a value of type [t1]\ninto a value of type [t2].  An implication [P -> Q] in a way transforms [P] into\n[Q]: if [P] holds, then [Q] also holds; or better yet, a proof of [P -> Q] can \nbe thought of as a function that transforms evidence for [P] into evidence for \n[Q].\n\nLet's do some proofs with these connectives to get a better sense of\nhow they work.\n\n(**********************************************************************)\n\n** Implication\n\nLet's try one of the simplest possible theorems we could prove using\nimplication:  P implies P.\n*)\n\nTheorem p_implies_p : forall P:Prop, P -> P.\n\n(** \nThat proposition says that for any proposition [P], it holds that [P] implies\n[P].\n\nIntuitively, why should be able able to prove this proposition?  That is, what\nis an argument you could give to another human?  We always encourage you to try\nto answer that question before launching into a Coq proof---for the same reason\nyour introductory programming instructor always encouraged you to think about\nprograms before you begin typing them.\n\nSo why does this proposition hold?  It's rather trivial, really.  If [P] holds,\nthen certainly [P] holds.  That is, [P] implies itself. An example in English\ncould be \"if 6225 is fun, then 6225 is fun.\" If you've already assumed [P], then\nnecessarily [P] follows from your assumptions:  that's what it means to be an\nassumption.  \n\nThe Coq proof below uses that reasoning. \n*)\n\nProof.\n    intros P. \n    intros P_assumed. \n    assumption.\nQed.\n\n(** The second step, [intros P_assumed], is a new use for the [intros] tactic.\nThis usage peels off the left-hand side of an implication and puts it into the\nproof assumptions.  The third step, [assumption] is a new tactic. It finishes a\nproof of a subgoal [G] whenever [G] is already an assumption in the proof. \n\nLet's look at the type of [p_implies_p].\n*)\n\nCheck p_implies_p.\n\n(**\nCoq says [p_implies_p : forall P : Prop, P -> P].  So [p_implies_p] is proof\nof, or evidence for, [forall P : Prop, P -> P], as we discussed above.\nWhat is that evidence?  We can use [Print] to find out:\n*)\n\nPrint p_implies_p.\n\n(** \nCoq responds\n<<\np_implies_p = \nfun (P : Prop) (P_assumed : P) => P_assumed\n     : forall P : Prop, P -> P\n>>\n\nLet's pull that apart.  Coq says that [p_implies_p] is a name that is \nbound to a value and has a type.  The type we already know.  The value\nis perhaps surprising:  it is a function!  Actually, maybe it shouldn't\nbe surprising given the discussion we had above about transformers.\n[P -> P] should transform evidence for [P] into evidence for [P].  Trivially,\nevidence for [P] already _is_ evidence for [P], so there's nothing to be done.\nAnd we can see that in the function itself:\n\n- it takes in an argument named [P], which is the proposition; and\n\n- it takes in another argument named [P_assumed] of type [P].  Since\n  [P_assumed] has a proposition as type, [P_assumed] must be evidence\n  for that proposition.\n\n- the function simply returns [P_assumed].  That is, it returns the\n  evidence for [P] that was already passed into it as an argument.\n\nNote that the names of the arguments to that function are the names\nthat we chose with the [intros] tactic.  \n\nLet's clarify a subtle piece of terminology, \"proof\".  The proof of\n[forall P:Prop, P -> P] is the anonymous function [fun (P : Prop) \n(P_assumed : P) => P_assumed ].  That is, the proof of a proposition\n[P] is a program that has type [P].  On the other hand, the commands\nwe used above\n<<\nProof.\n    intros P. \n    intros P_assumed. \n    assumption.\nQed.\n>>\nare how we help Coq find that proof.  We provide guidance using tactics,\nand Coq uses those tactics to figure out how to construct the program.\nSo although it's tempting to refer to [intros P. intros P_assumed.\nassumption.] as the \"proof\"---and we often will as a kind of shorthand\nterminology---the proof is really the program that is constructed, not\nthe tactics that help do the construction.\n\nIt is, by the way, possible to just directly tell Coq what the proof is\nby using the command [Definition]:\n*)\n\nDefinition p_implies_p_direct : forall P:Prop, P -> P := \n  fun p ev_p => ev_p.\n\n(**\nBut rarely do we directly write down proofs, because for most propositions\nthey are not so trivial.  Tactics are a huge help in constructing\ncomplicated proofs.\n\nLet's try another theorem.  A _syllogism_ is a classical form of argument\nthat typically goes something like this:\n\n- All humans are mortal.\n\n- Socrates is a human.\n\n- Therefore Socrates is mortal.\n\nThe first assumption in that proof, \"all humans are mortal\", is an implication:\nif X is a human, then X is mortal.  The second assumption is that\nSocrates is a human.  Putting those two assumptions together, we conclude\nthat Socrates is mortal.\n\nWe can formalize that kind of reasoning as follows:\n*)\n\nTheorem syllogism : forall P Q : Prop, \n  (P -> Q) -> P -> Q.\n\n(**\nHow would you convince a human that this theorem holds?  By the same\nreasoning as above.  Assume that [P -> Q].  Also assume [P].  Since\n[P] holds, and since [P] implies [Q], we know that [Q] must also hold.\n\nThe Coq proof below uses that style of argument.\n*)\n\nProof.\n  intros P Q evPimpQ evP.\n  apply evPimpQ. \n  assumption.\nQed.\n\n(** \nThe first line of the proof, [intros P Q evPimpQ evP] introduces four\nassumptions.  The first two are the variables [P] and [Q]. The third is [P->Q],\nwhich we give the name [evPimpQ] as a human-readable hint that it is evidence\nthat [P] implies [Q]. The fourth is [P], which we give the name [evP] as a hint\nthat we have assumed we have evidence for [P]. \n\nThe second line of the proof, [apply evPimpQ], uses a new tactic [apply] to\napply the evidence that [P -> Q] to the goal of the proof, which is [Q].  This\ntransforms the goal to be [P].  Think of this as _backward reasoning_:  we know\nwe want to show [Q], and since we have evidence that [P -> Q], we can work\nbackward to conclude that if we could only show [P], then we'd be done.  \n\nThe third line concludes by pointing out to Coq that in fact we do\nalready have evidence for [P] as an assumption.\n\nLet's look at the proof that these tactics cause Coq to create:\n*)\n\nPrint syllogism.\n\n(**\nWe see that\n<<\nsyllogism = \nfun (P Q : Prop) (evPimpQ : P -> Q) (evP : P) => evPimpQ evP\n     : forall P Q : Prop, (P -> Q) -> P -> Q\n>>\n\nPicking that apart, [syllogism] is a function that takes four arguments.\nThe third argument [evPimpQ] is of type [P -> Q].  Going back to our reading\nof [->] in different ways, we can think of [evPimpQ] as \n\n- a function that transforms something of type [P] into something of type [Q],\n  or\n\n- evidence for [P -> Q],\n  or\n\n- a transformer that takes in evidence of [P] and produces evidence of [Q].\n\nThe deep point here is:  _all of these are really the same interpretation_.\nThere's no difference between them.  The value [evPimpQ] is a function, \nand it is evidence, and it is an evidence transformer.  \n\nWe can see that [evPimpQ] is being used as a function in the body \n[evPimpQ evP] of the anonymous function, above.  It is applied to\n[evP], which is the evidence for [P], thus producing evidence for [Q].\nSo \"apply\" really is a great name for the tactic:  it causes a function\napplication to occur in the proof.\n\nLet's try one more proof with implication.\n*)\n\nTheorem imp_trans : forall P Q R : Prop,\n  (P -> Q) -> (Q -> R) -> (P -> R).\n\n(**\nAs usual, let's first try to give an argument in English.  We assume\nthat [P -> Q] and [Q -> R], and we want to conclude [P -> R].  So suppose\nthat [P] did hold.  Then from [P -> Q] we'd conclude [Q], and then from\n[Q -> R] we'd conclude [R].  So there's a kind of chain of evidence here\nfrom [P] to [Q] to [R].  This kind of chained relationship is called\n_transitive_, as you'll recall from CS 2800.  So what we're proving\nhere is that implication is transitive, hence the name [imp_trans]. \n*)\n\nProof.\n  intros P Q R evPimpQ evQimpR.\n  intros evP.\n  apply evQimpR.\n  apply evPimpQ.\n  assumption.\nQed.\n\n(**\nThe second line, [intros evP], wouldn't actually need to be separated\nfrom the first line; we could have introduced [evP] along with the rest.\nWe did it separately just so that we could see that it peels off the\n[P] from [P -> R].\n\nThe third line, [apply evQimpR] applies the evidence that [Q -> R] to\nthe goal [R], causing the goal to become [Q].  Again, this is backward\nreasoning:  we want to show [R], and we know that [Q -> R], so if \nwe could just show [Q] we'd be done.  \n\nThe fourth line, [apply evPimpQ], applies the evidence that [P -> Q]\nto the goal [Q], causing the goal to become [P].\n\nFinally, the fifth line, [assumption], finishes the proof by pointing\nout that [P] is already an assumption.\n\nLet's look at the resulting proof:\n*)\n\nPrint imp_trans.\n\n(**\nCoq says\n<<\nimp_trans = \nfun (P Q R : Prop) (evPimpQ : P -> Q) (evQimpR : Q -> R) (evP : P) =>\nevQimpR (evPimpQ evP)\n     : forall P Q R : Prop, (P -> Q) -> (Q -> R) -> P -> R\n>>\n\nDrilling down into the body of that anonymous function we see\n[evQimpR (evPimpQ evP)].  So we have [evPimpQ] being applied to [evP], which\ntransforms the evidence for [P] into the evidence for [Q].  Then we have\n[evQimpR] applied to that evidence for [Q], thus producing evidence for [R].  So\nthere are two function applications.  If Coq had the OCaml operator [|>], we\ncould rewrite that function body as [evP |> evPimpQ |> evQimpR], which might\nmake it even clearer what is going on:  the chain of reasoning just takes [P] to\n[Q] to [R].\n\n(**********************************************************************)\n\n** Conjunction\n\nNow we turn our attention to the conjunction connective.  Here's\na first theorem to prove.\n*)\n\nTheorem and_fst : forall P Q, P /\\ Q -> P.\n\n(** Why does that hold, intuitively?  Suppose we have evidence for [P /\\ Q].\nThen we must have evidence for both [P] and for [Q]. The evidence for [P] alone\nsuffices to conclude [P].  As an example, if we have evidence that [x > 0 /\\ y >\n0], then we must have evidence that [x > 0]; we're allowed to forget about the\nevidence for [y > 0].\n\nHaving established that intuition, let's create a proof with Coq.\n*)\n\nProof. \n    intros P Q PandQ.\n    destruct PandQ as [P_holds Q_holds]. \n    assumption.\nQed.\n\n(**\nThe second line of that proof uses a familiar tactic in a new way.\nPreviously we used [destruct] to do case analysis, splitting apart\na [day] into the seven possible constructors it could have.\nHere, we use [destruct] to split the evidence for [P /\\ Q] into\nits separate components.  To give names to those two components,\nwe use a new syntax, [as [...]], where the names appearing in \nthe [...] are used as the names for the components.  If we leave\noff the [as] clause, Coq will happily choose names for us, but\nthey won't be human-readable, descriptive names.  So it's good\nstyle to pick the names ourselves.  \n\nAfter destructing the evidence for [PandQ] into evidence for\n[P] and evidence for [Q], we can easily finish the proof\nwith [assumption].\n\nLet's look at the proof of [and_fst].\n*)\n\nPrint and_fst.\n\n(**\nCoq says that \n<<\nand_fst = \nfun (P Q : Prop) (PandQ : P /\\ Q) =>\nmatch PandQ with\n| conj P_holds _ => P_holds\nend\n     : forall P Q : Prop, P /\\ Q -> P\n>>\n\nLet's dissect that.  We see that [and_fst] is a function that takes three\narguments.  The third is evidence for [P /\\ Q].  The function then pattern\nmatches against that evidence, providing just a single branch in the pattern\nmatch.  The pattern it uses is [conj P_holds _].  As in OCaml, [_] is a wildcard\nthat matches anything.  The identifier [conj] is a constructor; unlike OCaml,\nit's fine for constructors to begin with lowercase characters.  So the pattern\nmatches against [conj] applied to two values, extracts the first value with the\nname [P_holds], and doesn't give a name to the second value.  The branch then\nreturns that argument [P_holds].  So we can already see that the function is\nsplitting apart the evidence into two pieces, and forgetting about one piece.\n\nBut to fully understand this, we need to know more about [/\\] and [conj].\nFirst, what is [/\\]?\n*)\n\nLocate \"/\\\".\n\n(**\nCoq says [\"A /\\ B\" := and A B].  That is, [/\\] is just an infix notation\nfor the [and] function.  What is [and]?\n*)\n\nPrint and.\n\n(**\nCoq says\n<<\nInductive and (A B : Prop) : Prop :=  \n  conj : A -> B -> A /\\ B\n>>\n\nIt might help to compare to lists.\n*)\n\nPrint list.\n\n(**\nCoq says\n<<\nInductive list (A : Type) : Type :=\n    nil : list A | cons : A -> list A -> list A\n>>\n\nIn Coq, [Inductive] defines a so-called _inductive_ type, and provides its\nconstructors.  In OCaml, the [type] keyword serves a similar purpose. So [list]\nin Coq is a type with two constructors named [nil] and [cons]. Similarly, [and]\nis a type with a single constructor named [conj], which is a function that takes\nin a value of type [A], a value of type [B], and returns a value of type [A /\\\nB], which is just infix notation for [and A B].  Another way of putting that is\nthat [conj] takes in evidence of [A], evidence of [B], and returns evidence of\n[and A B].  \n\nSo there's only one way of producing evidence of [A /\\ B], which is to\nseparately produce evidence of [A] and of [B], both of which are passed into\n[conj].  That's why when we destructed [A /\\ B], it had to produce both evidence\nof [A] and of [B]. \n\nGoing back to [and_fst]:\n<<\nand_fst = \nfun (P Q : Prop) (PandQ : P /\\ Q) =>\nmatch PandQ with\n| conj P_holds _ => P_holds\nend\n     : forall P Q : Prop, P /\\ Q -> P\n>>\nwe have a function that pattern matches against [PandQ], extracts the\nevidence for [P], forgets about the evidence for [Q], and simply returns\nthe evidence for [P].\n\nGiven all that, the following theorem and its program should be\nunsurprising.\n*)\n\nTheorem and_snd : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q PandQ.\n  destruct PandQ as [P_holds Q_holds].\n  assumption.\nQed.\n\nPrint and_snd.\n\n(**\nCoq responds:\n<<\nand_snd = \nfun (P Q : Prop) (PandQ : P /\\ Q) =>\nmatch PandQ with\n| conj _ Q_holds => Q_holds\nend\n     : forall P Q : Prop, P /\\ Q -> Q\n>>\n\nIn that program the pattern match returns the second piece of evidence, which\nshows [Q] holds, rather than the first, which would show that [P] holds.\n\nHere is another proof involving [and]. *)\n\nTheorem and_ex : 42=42 /\\ 43=43.\n\n(** Why does that hold, intuitively?  Because equality is reflexive, regardless\nof how many times we connect that fact with [/\\]. *)\n\nProof. \n  split. \n  trivial. trivial.\nQed.\n\n(** The first line of that proof, [split], is a new tactic.  It splits a goal of\nthe form [P /\\ Q] into two separate subgoals, one for [P], and another for [Q].\nBoth must be proved individually.  In the proof above, [trivial] suffices to\nprove them, because they are both trivial equalitiies.\n\nWhat is [and_ex]? *)\n\nPrint and_ex.\n\n(**\nCoq responds:\n<<\nand_ex = conj eq_refl eq_refl\n     : 42 = 42 /\\ 43 = 43\n>>\n\nSo [and_ex] is [conj] applied to [eq_refl] as its first argument and [eq_refl]\nas its second argument.\n\nAs another example of conjunction, let's prove that it is commutative. *)\n\nTheorem and_comm: forall P Q, P /\\ Q -> Q /\\ P.\n\n(**\nWhy does this hold?  If we assume that [P /\\ Q] holds, then separately we must\nhave evidence for [P] as well as [Q]. But the we could just assemble that\nevidence in the opposite order, producing evidence for [Q /\\ P].  That's what\nthe proof below does.\n*)\n\nProof.\n    intros P Q PandQ. \n    destruct PandQ as [P_holds Q_holds]. \n    split. \n    all: assumption.\nQed.\n\n(**\nThere's nothing new in that proof:  we split the evidence into two pieces using\npattern matching, then reassemble them in a different order.  We can see that in\nthe program:\n*)\n\nPrint and_comm.\n\n(**\nCoq responds:\n<<\nand_comm = \nfun (P Q : Prop) (PandQ : P /\\ Q) =>\nmatch PandQ with\n| conj P_holds Q_holds => conj Q_holds P_holds\nend\n     : forall P Q : Prop, P /\\ Q -> Q /\\ P\n>>\n\nNote how the pattern match binds two variables, then returns the [conj]\nconstructor applied to those variables in the opposite order.\n\nHere's one more proof involving implication and conjunction. *)\n\nTheorem and_to_imp : forall P Q R : Prop,\n  (P /\\ Q -> R) -> (P -> (Q -> R)).\n\n(** Intuitively, why does this hold?  Because we can assume [P], [Q] and [R]. as\nwell as that [P /\\ Q -> R], and that we have evidence for [P] and [Q] already.\nWe can combine those two pieces of evidence for [P] and [Q] into a single piece\nof evidence for [P /\\ Q], which then yields the desired evidence for [R]. *)\n\nProof.\n  intros P Q R evPandQimpR evP evQ.\n  apply evPandQimpR.\n  split.\n  all: assumption.\nQed.\n\n(** There are no new tactics in the proof above.   In line 2, we use [apply] to\nonce again do backwards reasoning, transforming the goal of [R] into [P /\\ Q].\nThen we split that goal into two pieces, each of which can be solved by\nassumption.\n\nLet's look at the resulting program: *)\n\nPrint and_to_imp.\n\n(**\n<<\nand_to_imp = \nfun (P Q R : Prop) (evPandQimpR : P /\\ Q -> R) (evP : P) (evQ : Q) => \n      evPandQimpR (conj evP evQ)\n  : forall P Q R : Prop, (P /\\ Q -> R) -> P -> Q -> R\n>>\n\nThat program constructs evidence for [P /\\ Q] using [P] and [Q], and \nuses the evidence to get [R] from [P /\\ Q].\n\n(**********************************************************************)\n\n** Disjunction\n\nLet's start with disjunction by proving a theorem very similar to the first\ntheorem we proved for conjunction: *)\n\nTheorem or_left : forall (P Q : Prop), P -> P \\/ Q.\n\n(** As always, what's the intuition?  Well, if we have evidence for [P], then we\nhave evidence for [P \\/ Q], because we have evidence already for the left-hand\nside of that connective.\n\nLet's formalize that argument in Coq. *)\n\nProof.\n    intros P Q P_holds. \n    left. \n    assumption.\nQed.\n\n(** The second line of that proof, [left], uses a new tactic that tells Coq we\nwant to prove the left-hand side of a disjunction.  Specifically, the goal at\nthat point is [P \\/ Q], and [left] tells Coq the throw out [Q] and just focus on\nproving [P].  That's easy, because [P] is already an assumption.\n\nLet's investigate the resulting program. *)\n\nPrint or_left.\n\n(**\nCoq responds\n<<\nor_left = \nfun (P Q : Prop) (P_holds : P) => or_introl P_holds\n     : forall P Q : Prop, P -> P \\/ Q\n>>\n\nThat function's arguments are no mystery by now, but what is its body?\nWe need to find out more about [or_introl].\n*)\n\nLocate \"\\/\".\nPrint or_introl.\n\n(**\nWe learn that \"\\/\" is infix notation for [or A B], and\n[or_introl] is one of two constructors of the type [or]:\n<<\nInductive or (A B : Prop) : Prop :=\n    or_introl : A -> A \\/ B \n  | or_intror : B -> A \\/ B\n>>\n\nThose constructors take evidence for either the left-hand side or right-hand\nside of the disjuncation.  So the body of [or_left] is just taking evidence for\n[A] and using [or_introl] to construct a value with that evidence.\n\nSimilarly, the following theorem constructs proof using evidence for the\nright-hand side of a disjunction. *)\n\nTheorem or_right : forall P Q : Prop, Q -> P \\/ Q.\n\n(** Much like with [or_left], this intuitively holds because evidence for [Q]\nsuffices as evidence for [P \\/ Q]. *)\n\nProof. \n  intros P Q Q_holds.\n  right.\n  assumption.\nQed.\n\nPrint or_right.\n\n(**\nThe resulting program uses the constructor [or_intror]:\n<<\nor_right = \nfun (P Q : Prop) (Q_holds : Q) => or_intror Q_holds\n     : forall P Q : Prop, Q -> P \\/ Q\n>>\n\nWe could use those theorems to prove some related theorems.\nFor example, [3110 = 3110] implies that [3110 = 3110 \\/ 2110 = 3110].\n*)\n\nTheorem or_thm : 3110 = 3110 \\/ 2110 = 3110.\n\n(**\nWhy does that hold?  Because the left-hand side holds---even though\nthe right hand side does not.\n*)\n\nProof. \n  left. trivial.\nQed.\n\nPrint or_thm.\n\n(**\nCoq responds that\n<<\nor_thm = or_introl eq_refl\n     : 3110 = 3110 \\/ 2110 = 3110\n>>\n\nIn other words, the theorem is proved by applying the [or_introl] constructor to\n[eq_refl].  It matters, though, that we provided Coq with the guidance to prove\nthe left-hand side. If we had chosen the right-hand side, we would have been\nstuck trying to prove that [2110 = 3110], which of course it does not.\n\nNext, let's prove that disjunction is commutative, as we did for conjunction\nabove. *)\n\n\nTheorem or_comm : forall P Q, P \\/ Q -> Q \\/ P.\n\n(** Why does this hold?  If you assume you have evidence for [P \\/ Q], then you\neither have evidence for [P] or evidence for [Q]. If it's [P], then you can\nprove [Q \\/ P] by providing evidence for the right-hand side; or if it's [Q],\nfor the left-hand side.  \n\nThat's what the Coq proof below does. *)\n\nProof.\n    intros P Q PorQ.\n    destruct PorQ as [P_holds | Q_holds].\n    - right. assumption.\n    - left. assumption.\nQed. \n\n(** In the second line of that proof, we destruct the disjunction [PorQ] with a\nslightly different syntax than when we destructed conjunction above.  There's\nnow a vertical bar.  The reason for that has to do with the definitions of [and]\nand [or].  \n\nThe definition of [and] had just a single constructor:\n<<\nconj : A -> B -> A /\\ B\n>>\nSo when we wrote [destruct PandQ as [P_holds Q_holds]], we were essentially\nwriting a pattern match against that single constructor [conj], and binding its\n[A] argument to the name [P_holds], and its [B] argument to the name [Q_holds].\n\nBut the definition of [or] has two constructors:\n<<\n    or_introl : A -> A \\/ B \n  | or_intror : B -> A \\/ B\n>>\nSo when we write [destruct PorQ as [P_holds | Q_holds]], we're providing two\npatterns: the first matches against the first constructor [or_introl], binding\nits [A] argument to the name [P_holds]; and the second against the second\nconstructor [or_intror], binding its [B] argument to [Q_holds]. \n\nWhat makes this confusing to an OCaml programmer is that the [as] clause doesn't\nactually name the constructors.  It might be clearer if Coq's [destruct] tactic\nused the following hypothetical syntax:\n<<\n  destruct PandQ as [conj P_holds Q_holds].\n  destruct PorQ as [or_introl P_holds | or_intror Q_holds].\n>>\nbut that's just not how [destruct..as] works.\n\nAfter the destruction occurs, we get two new subgoals to prove, corresponding to\nwhether [PorQ] matched [or_introl] or [or_intror]. In the third line of the\nproof, which corresponds to [PorQ] matching [or_introl], we have evidence for\n[P], so we choose to prove the right side of [Q \\/ P] by assumption.  The fourth\nline does a similar thing, but using evidence for [Q] hence proving the left\nside of [Q \\/ P].\n\nLet's look at the resulting proof. *)\n\nPrint or_comm.\n\n(**\nCoq responds\n<<\nor_comm = \nfun (P Q : Prop) (PorQ : P \\/ Q) =>\nmatch PorQ with\n| or_introl P_holds => or_intror P_holds\n| or_intror Q_holds => or_introl Q_holds\nend\n     : forall P Q : Prop, P \\/ Q -> Q \\/ P)\n>>\n\nThat function takes an argument [PorQ] is evidence for [P \\/ Q], pattern matches\nagainst that argument, extracts the evidence for either [P] or [Q], then returns\nthat evidence wrapped in the \"opposite\" constructor:  evidence that came in in\nthe left constructor is returned with the right constructor, and vice versa.  \n\nNext, let's prove a theorem involving both conjunction and disjunction. *)\n\n\nTheorem or_distr_and : forall P Q R, \n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\n\n(** This theorem says that \"or\" distributes over \"and\".  Intuitively, if we have\nevidence for [P \\/ (Q /\\ R)], then one of two things holds: either we have\nevidence for [P], or we have evidence for [Q /\\ R].\n\n- If we have evidence for [P], then we use that evidence to create evidence both\n  for [P \\/ Q] and for [P /\\ R].\n\n- If we have evidence for [Q /\\ R], then we split that evidence apart into\n  evidence separately for [Q] and for [R].  We use the evidence for\n  [Q] to create evidence for [P \\/ Q], and likewise the evidence for [R] to\n  create evidence for [P \\/ R].\n\nThe Coq proof below follows that intuition. *)\n\nProof.\n  intros P Q R PorQR.\n  destruct PorQR as [P_holds | QR_holds].\n  - split.\n    + left. assumption.\n    + left. assumption.\n  - destruct QR_holds as [Q_holds R_holds].\n    split.\n    + right. assumption.\n    + right. assumption.\nQed.\n\n(** We used _nested bullets_ in that proof to keep the structure of the proof\nclear to the reader, and to make it easier to follow the proof in the proof\nwindow when we step through it.  \n\nBut you'll notice there's a lot of repetition in the proof.  We can eliminate\nsome by using the [;] tactical (discussed in the previous notes) to chain\ntogether some proof steps. *)\n\nTheorem or_distr_and_shorter : forall P Q R, \n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R PorQR.\n  destruct PorQR as [P_holds | QR_holds].\n  - split; left; assumption.\n  - destruct QR_holds as [Q_holds R_holds].\n    split; right; assumption.\nQed.\n\nPrint or_distr_and.\n\n(**\nEither way, the resulting proof is\n<<\nor_distr_and = \nfun (P Q R : Prop) (PorQR : P \\/ Q /\\ R) =>\nmatch PorQR with\n| or_introl P_holds => conj (or_introl P_holds) (or_introl P_holds)\n| or_intror QR_holds =>\n    match QR_holds with\n    | conj Q_holds R_holds => conj (or_intror Q_holds) (or_intror R_holds)\n    end\nend\n     : forall P Q R : Prop, P \\/ Q /\\ R -> (P \\/ Q) /\\ (P \\/ R)\n>>\n\nThe nested pattern match in that proof corresponds to the nested [destruct]\nabove.  Note that Coq omits some parentheses around conjunction, because it is\ndefined to have higher precedence than disjunction---just like [*] has higher\nprecedence than [+].\n\n(**********************************************************************)\n\n** [False] and [True]\n\n[False] is the proposition that can never hold:  we can never actually have\nevidence for it.  If we did somehow have evidence for [False], our entire system\nof reasoning would be broken. There's a Latin phrase often used for that idea:\n_ex falso quodlibet_, meaning \"from false, anything\".  In English it's sometimes\nknown as the _Principle of Explosion_:  if you're able to show [False], then\neverything just explodes, and in fact anything at all becomes provable.\n\nHere's the definition of [False]: *)\n\nPrint False.\n\n(**\nCoq responds\n<<\nInductive False : Prop :=  \n>>\n\nNo, that isn't a typo above.  There is nothing on the right-hand side of the\n[:=].  The definition is saying that [False] is an inductive type, like [and]\nand [or], but it has zero constructors.  Since it has no constructors, we can\nnever create a value of type [False]---and that means we can never create\nevidence that [False] holds.  \n\nLet's prove the Principle of Explosion. *)\n\nTheorem explosion : forall P:Prop, False -> P.\n\n(** Why should this theorem hold?  Because of the intuition we gave above\nregarding _ex falso_. *)\n\nProof.\n    intros P false_holds. \n    contradiction.\nQed.\n\n(** The second line of the proof uses a new tactic, [contradiction].  This\ntactic looks for any contradictions or assumptions of [False], and uses those to\nconclude the proof.  In this case, it immediately finds [False] as an assumption\nnamed [false_holds].*)\n\nPrint explosion.\nPrint False_ind.\n\n(**\nThe proof that Coq finds for [explosion] given the above tactics is a little bit\nhard to follow because it uses [False_ind] that are already defined for us.\nIts definition is given below, but it's okay if you want to skip over reading \nthem at first.\n\n<<\nexplosion = \nfun (P : Prop) (false_holds : False) => False_ind P false_holds\n     : forall P : Prop, False -> P\n\nFalse_ind =\nfun (P : Prop) (f : False) => match f return P with\n                              end\n     : forall P : Type, False -> P\n>>\n\n(The [return P] in the pattern match above is a type annotation: it says\nthat the return type of the entire [match] expression is [P].)\n\nWe could simplify the proof of [explosion] by just directly writing that pattern match ourselves.  Let's do that using the [Definition] command we saw above. \n*)\n\nDefinition explosion' : forall (P:Prop), False -> P := \n  fun (P : Prop) (f : False) => \n    match f with \n    end.\n\n(** \nThe proof of [explosion'] is a function that takes two inputs, a proposition\n[P] and a value [f] of type [False].  As usual, we should understand that second\nargument as being evidence for [False].  But it should be impossible to\nconstruct such evidence!  And indeed it is, because [False] has no constructors.\nSo we have a function that we could never actually apply.\n\nIn the body of that function is a pattern match against [f].  That pattern match\nhas zero branches in it, exactly because [False] has zero constructors. There is\nnothing that could ever possibly match [f].\n\nThe return type of the function is [P], meaning it purportedly is evidence for\n[P].  But of course no such evidence is ever constructed by the function, nor\ncould it be.  So it's a good thing that it's impossible to apply the function.\nWere it possible, it would have to fabricate evidence for any proposition [P]\nwhatsoever---which is not possible. \n\nWe can never prove [P -> P /\\ False], because there is no way to construct the\nevidence for the right side. *)\n\nTheorem p_imp_p_and_false : forall P:Prop, P -> P /\\ False.\nProof.\n  intros P P_holds. split. assumption.  (* now we're stuck *)\nAbort.\n\n(** But we can always prove [P -> P \\/ False] by just focusing on the non-false\npart of the disjunction. *)\n\nTheorem p_imp_p_or_false : forall P:Prop, P -> P \\/ False.\nProof.\n  intros P P_holds. left. assumption.\nQed.\n\n(** [True] is the proposition that is always true, i.e., for which we can always\nprovide.  It is defined by Coq as an inductive type: *)\n\nPrint True.\n\n(**\nCoq responds:\n<<\nInductive True : Prop :=  I : True\n>>\n\nSo [True] has a single constructor [I], and anywhere we write [I], that provides\nevidence for [True].  Let's redo the two theorem we just did for [False], but\nwith [True] in place of [False]. *)\n\nTheorem p_imp_p_and_true : forall P:Prop, P -> P /\\ True.\nProof.\n  intros P P_holds. split. assumption. exact I.\nQed.\n\n(** The final tactic in that proof, [exact], can be used whenever you already\nknow exactly the program expression you want to write to provide evidence for\nthe goal you are trying to prove.  In this case, we know that [I] always\nprovides evidence for [true].  Instead of [exact] we could also have used\n[trivial], which is capable of proving trivial propositions like [True]. *)\n\nTheorem p_imp_p_or_true : forall P:Prop, P -> P \\/ True.\nProof.\n  intros P P_holds. left. assumption.\nQed.\n\n(**\n(**********************************************************************)\n\n** Negation\n\nThe negation connective can be the trickiest to work with in Coq.  Let's start\nby seeing how it is defined. *)\n\nLocate \"~\".\nPrint not.\n\n(**\nCoq responds\n<<\nnot = fun A : Prop => A -> False\n     : Prop -> Prop\n>>\n\nUnlike conjunction and disjunction, negation is defined as a function, rather\nthan an inductive type.  Anywhere we write [~P], it really means [not P], which\nis [(fun A => A -> False) P], which reduces to [P -> False].  In short, [~P] \nis effectively syntactic sugar for [P -> False].  \n\nHere are two proofs involving negation, so that we can get used to this\ndefinition of it. *)\n\nTheorem notFalse : ~False -> True.\n(** Intuition:  anything implies [True], regardless of what that anything is. *)\nProof.\n  unfold not.\n  intros.\n  exact I.\nQed.\n\n(** The first line of that proof, [unfold not], is a new tactic, which replaces\nthe [~] in the goal with its definition and simplifies it.  So [~False] becomes\n[False -> False]. The second line uses a familiar tactic in a new way. We don't\nprovide any names to [intros], which causes Coq to choose its own names.\nNormally we consider it good style to choose them ourselves, but here, we don't\ncare what they are, because we are never going to use them.  Finally, the third\nline uses [I] to prove [True].\n\nLooking at the actual program produced, we see that it's very simple:\n*)\n\nPrint notFalse.\n\n(**\nCoq responds\n<<\nnotFalse = fun _ : False -> False => I\n>>\n\nwhich is a function that takes an argument that is never used, and simply\nreturns [I], which is the evidence for [True].\n\nHere's a second proof involving negation. *)\n\nTheorem notTrue: ~True -> False.\n(** Intuition:  if [True] implies [False], and if [True], then [False]. *)\nProof.\n  unfold not. \n  intros t_imp_f. \n  apply t_imp_f. \n  exact I.\nQed.\n\n(** The first line of the proof replaces [~True] with [True -> False]. The rest\nof the proof proceeds by moving [True -> False] into the assumptions, then\napplying it to do backward reasoning, leaving us with needing to prove [True].\nThat holds by the [I] constructor.\n\nThe program that proof produces is interesting: *)\n\nPrint notTrue.\n\n(**\nCoq responds\n<<\nnotTrue = fun t_imp_f : True -> False => t_imp_f I\n     : ~ True -> False\n>>\n\nThat proof is actually a higher-order function that takes in a function\n[t_imp_f] and applies that function to [I], thus transforming evidence\nfor [True] into evidence for [False], and returning that evidence.  If\nthat seems impossible, it is!  We'll never be able to apply this function,\nbecause we'll never be able to construct a value to pass to it whose\ntype is [~True], i.e., [True -> False].   \n\nNext, let's return to the idea of explosion.  From a contradiction we should\nbe able to derive anything at all.  One kind of contradiction is for a \nproposition and its negation to hold simultaneously, e.g., [P /\\ ~P].\n*)\n\nTheorem contra_implies_anything : forall (P Q : Prop), P /\\ ~P -> Q.\n(** Intuition:  principle of explosion *)\nProof.\n    unfold not.\n    intros P Q PandnotP. \n    destruct PandnotP as [P_holds notP_holds]. \n    contradiction.\nQed.\n\n(** This proof proceeds along familiar lines:  We destruct the evidence of [P /\\\n~P] into two pieces.  That leaves us with [P] as an assumption as well as [~P].\nThe [contradiction] tactic detects those contradictory assumptions and finished\nthe proof.  By the way, we could have left out the [as] clause in the [destruct]\nhere, since we are never going to use the names we chose, but they will help\nmake the following program more readable: *)\n\nPrint contra_implies_anything.\n\n(**\nCoq responds:\n<<\ncontra_implies_anything = \nfun (P Q : Prop) (PandnotP : P /\\ (P -> False)) =>\nmatch PandnotP with\n| conj P_holds notP_holds => False_ind Q (notP_holds P_holds)\nend\n     : forall P Q : Prop, P /\\ ~ P -> Q\n>>\n\nThe really interesting part of this is the body of the pattern match,\n[False_rect Q (notP_holds P_holds)].  It applies [notP_holds] to [P_holds], thus\ntransforming evidence for [P] into evidence for [False]. It passes that\nhypothetical evidence for [False] to [False_ind], which as we've seen before\nuses such evidence to produce evidence for anything at all that we would\nlike---in this case, [Q], its first argument.\n\nNext, let's try a proof involving all the connectives we've seen: negation,\nconjunction, disjunction, and implication.  The following theorem shows how\nnegation distributes over disjunction, and in so doing, produces a conjunction.\nThe name we choose for this theorem is traditional and gives credit to Augustus\nDe Morgan, a 19th century logician, even though the theorem was known far\nearlier in history. *)\n\nTheorem deMorgan : forall P Q : Prop,\n  ~(P \\/ Q) -> ~P /\\ ~Q.\n\n(** Intuition: if evidence for [P] or [Q] would lead to an explosion (i.e.,\n   [False]), then evidence for [P] would lead to an explosion, and evidence \n   for [Q] would also lead to an explosion. *)\n   \nProof.\n  unfold not.\n  intros P Q PorQ_imp_false.\n  split.\n  - intros P_holds. apply PorQ_imp_false. left. assumption.\n  - intros Q_holds. apply PorQ_imp_false. right. assumption.\nQed.\n\n(** Nothing we've done in that proof is new, but it is longer than any of our\nproofs so far.  The same is true of the program it produces: *)\n\nPrint deMorgan.\n\n(**\nCoq responds:\n<<\ndeMorgan = \nfun (P Q : Prop) (PorQ_imp_false : P \\/ Q -> False) =>\nconj (fun P_holds : P => PorQ_imp_false (or_introl P_holds))\n     (fun Q_holds : Q => PorQ_imp_false (or_intror Q_holds))\n       : forall P Q : Prop, ~ (P \\/ Q) -> ~ P /\\ ~ Q\n>>\n\nThere is a second \"De Morgan's Law\", which says that negation distributes over\nconjunction, thus producing a disjunction.  But something seemingly goes very\nwrong when we try to prove it in Coq: *)\n\nTheorem deMorgan2 : forall P Q : Prop,\n  ~(P /\\ Q) -> ~P \\/ ~Q.\n\n(** Intuition: if evidence for P and Q would produce an explosion, then \neither evidence for P would produce an explosion, or evidence for Q would. *)\n\nProof.\n  unfold not.\n  intros P Q PQ_imp_false.\n  left.\n  intros P_holds. apply PQ_imp_false. split. assumption.\nAbort.\n\n(** When we get to the point in the proof above where we need to prove [Q], we\nhave no means to do so.  (The same problem would occur for [P] if instead of\n[left] we had gone [right].)  Why does this happen?  One reason is that the\nintuition we gave above is wrong!  There's no reason that \"if evidence for P and\nQ would produce an explosion\" implies \"either evidence for P would produce an\nexplosion, or evidence for Q would\". It's the combined evidence for [P] and [Q]\nthat produces the explosion in that assumption---nothing is said about evidence\nfor them individually.\n\nBut a deeper reason is that this theorem simply doesn't hold in Coq's logic:\nthere isn't any way to prove it.  That might surprise you if you've studied some\nlogic before, and you were taught that both De Morgan laws are sound reasoning\nprinciples.  Indeed they are in some logics, but not in others.\n\nIn _classical logic_, which is what you almost certainly would have studied\nbefore (e.g., in CS 2800), we are permitted to think of every proposition as\nhaving a _truth value_, which is either [True] or [False].  And one way to prove\na theorem is to construct a _truth table_ showing what truth value a proposition\nhas for any assignment of [True] or [False] to its variables. For example\n(writing [T] and [F] as abbreviations):\n\n<<\nP  Q  ~(P/\\Q) (~P \\/ ~Q) (~(P/\\Q) -> (~P \\/ ~Q))\nT  T  F       F          T\nT  F  T       T          T\nF  T  T       T          T\nF  F  T       T          T\n>>\n\nFor every possible assignment of truth values to [P] and [Q], we get that the\ntruth value of [~(P/\\Q) -> (~P \\/ ~Q)] is [True].  So in classical logic,\n[~(P/\\Q) -> (~P \\/ ~Q)] is a theorem.\n\nBut Coq uses a different logic called _constructive logic_.  Constructive logic\nis more convervative than classical logic, in that it always requires evidence\nto be produced as part of a proof.  As we saw above when we tried to prove\n[deMorgan2], there just isn't a way to construct evidence for [~P \\/ ~Q] out of\nevidence for [~(P/\\Q)].  \n\nThere are many other propositions that are provable in classical logic but not\nin constructive logic.  Another pair of such propositions involves _double\nnegation_:  [P -> ~~P] is provable in both logics, but [~~P -> P] is provable in\nclassical logic and not provable in constructive logic.  Let's try proving both\njust to see what happens. \n*)\n\nTheorem p_imp_nnp : forall P:Prop, P -> ~~P.\n\n(** Intuition: ~~P is (P -> False) -> False.  So the theorem could be\n   restated as P -> (P -> False) -> False.  That's really just a syllogism,\n   with the first two arguments in the opposite order:\n   - P implies False.\n   - P holds.\n   - Therefore False holds. *)\n   \nProof.\n  unfold not.  \n  intros P evP evPimpFalse.\n  apply evPimpFalse. \n  assumption.\nQed.\n\n(** We could make that intuition even more apparent by proving a version of the\nsyllogism theorem with its first two arguments swapped: *)\n\nTheorem syllogism' : forall P Q : Prop,\n  P -> (P -> Q) -> Q.\nProof.\n  intros P Q evP evPimpQ.\n  apply evPimpQ.\n  assumption.\nQed.\n\n(** Now we use [syllogism'] to prove [P -> ~~P]: *)\n\nTheorem p_imp_nnp' : forall P:Prop, P -> ~~P.\nProof.\n  unfold not. intros P. apply syllogism'.\nQed.\n\n(** In that proof, we have a new use for the [apply] tactic: we use it with the\nname of a theorem we've already proved, because our goal is in fact that\ntheorem.  In the resulting program, we saw this indeed becomes an application of\nthe [syllogism'] function: *)\n\nPrint p_imp_nnp'.\n\n(**\nCoq responds:\n<<\np_imp_nnp' = \nfun P : Prop => syllogism' P False\n     : forall P : Prop, P -> ~ ~ P\n>>\n\nNow let's try the other direction for double negation:\n*)\n\nTheorem nnp_imp_p : forall P : Prop, ~~P -> P.\n(* intuition: actually it doesn't hold *)\nProof.\n  unfold not.\n  intros P evNNP.\nAbort.\n\n(** Once we get past introducing assumptions in that proof, we're stuck. There's\nnothing we can do with [(P -> False) -> False] to prove [P]. Why?  Because in\nconstructive logic, to prove [P], we must produce evidence for [P].  Nothing in\n[(P -> False) -> False] gives us such evidence.  \n\nThat's very different from classical logic, where we could just construct a\ntruth table:\n\n<<\nP ~~P  (~~P -> P)\nT T    T\nF F    T\n>>\n\nHere's another even more brutally perplexing proposition that's provable in\nclassical logic but not in constructive logic.  It's called _excluded middle_,\nbecause it says that every proposition or its negation must hold; there is no\n\"middle ground\": *)\n\nTheorem excluded_middle : forall P, P \\/ ~P.\nProof.\n  intros P.\n  left.\nAbort.\n\n(** Whether we go left or right in the second step of that proof, we immediately\nget stuck.  If we go left, Coq challenges us to construct evidence for [P], but\nwe don't have any.  If we go right, Coq challenges us to construct evidence for\n[P -> False], but we don't have any. \n\nYet in classical logic, excluded middle is easily proved by a truth table:\n<<\nP  ~P  (P \\/ ~P)\nT  F   T\nF  T   T\n>>\n\nWhy does Coq use constructive logic rather than classical logic?  The reason\ngoes back to why we started looking at Coq, namely, program verification.  We'd\nlike to be able to extract verified programs.  Well, there simply is no program\nwhose type is [P \\/ ~P], because such a program would have to use either\n[or_introl] or [or_intror] to construct its result, and it would have to\nmagically guess which one to use, then magically somehow produce the appropriate\nevidence.  \n\nNonetheless, if all you want to do is reasoning in classical logic, and you\ndon't care about extracting verified programs, Coq does support that in a\nlibrary [Coq.Logic.Classical]. We'll load that library now in a nested [Module],\nwhich restricts its influence just to that module so that we don't pollute the\nrest of this file. *)\n\nRequire Coq.Logic.Classical.\n\nModule LetsDoClassicalReasoning.\n\nImport Coq.Logic.Classical.\n\nPrint classic.\n\n(**\nCoq responds:\n<<\n*** [ classic : forall P : Prop, P \\/ ~ P ]\n>>\n\nThe [***] indicates that [classic] is an _axiom_ that the library simply asserts\nwithout proof.  Using that axiom, all the usual theorems of classical logic can\nbe proved, such as double negation: *)\n\nPrint NNPP.\n\n(**\nCoq responds:\n<<\nNNPP = \nfun (p : Prop) (H : (p -> False) -> False) =>\nor_ind (fun H0 : p => H0) (fun NP : ~ p => False_ind p (H NP)) (classic p)\n     : forall p : Prop, ~ ~ p -> p\n>>\n\nYou can see on the last line that [NNPP] proves [~~p -> p], which we couldn't\nprove above.  And you'll see that [classic] shows up in the program to magically\nconstruct evidence of [p \\/ ~p]. *)\n\nEnd LetsDoClassicalReasoning.\n\n(**\n(**********************************************************************)\n\n** Equality and implication\n\nLet's return to the two connectives with which we started, equality and\nimplication.  Earlier we didn't explain them fully, but now we're equipped to\nappreciate their definitions.\n\nRecall how Coq defines equality:\n*)\n\nLocate \"=\".\nPrint eq.\n\n(**\nCoq responds:\n<<\nInductive eq (A : Type) (x : A) : A -> Prop :=  \n  eq_refl : x = x\n\nFor eq: Argument A is implicit ...\n>>\n\nReading that carefully, we see that [eq] is parameterized on \n\n- a type [A], and\n\n- a value [x] whose type is [A].\n\nWe also see that [A] is implicit, so let's use [@eq] from now on in our\ndiscussion just to be clear about [A].\n\nWhen we apply [@eq] to a type [A] and a value [x], we get back a function of\ntype [A -> Prop].  The idea is that function will take its argument, let's call\nit [y], and construct the proposition that asserts that [x] and [y] are equal.\nFor example: *)\n\nDefinition eq42 := @eq nat 42.\nCheck eq42.\nCheck (eq42 42).\nCheck (eq42 43).\n\n(**\n<<\neq42 : nat -> Prop\neq42 42 : Prop\neq42 43 : Prop\n>>\n\nThere's only one way to construct a value of type [eq], though, and that's with\nthe [eq_refl] constructor.  If we \"desugar\" the [=] notation, that constructor\nhas type [@eq A x x], where [x] must be of type [A]. *)\n\nCheck @eq_refl nat 42.\n\n(** \n<<\n@eq_refl nat 42 : 42 = 42\n>>\n\nNote how the constructor above takes just a single argument of type [nat], not\ntwo arguments:  it will only ever show that argument is equal to itself, never\nto anything else.  There's literally no way to write an expression using\n[eq_refl] to construct evidence that (e.g.) [42] and [43] are equal. \n\nSo instead of using [trivial], we could directly use [eq_refl] as a constructor\nto prove equalities, much like we directly used [I] as a constructor to prove\n[True] earlier in this file: *)\n\nTheorem direct_eq : 42 = 42.\nProof.\n  exact (eq_refl 42). \nQed.\n\n(** Equality, therefore, is not something that has to be \"baked in\" to Coq, but\nrather something that is definable as an inductive type---much like [and] and\n[or].\n\nAnd now back to implication.  It, too, is defined. *)\n\nLocate \"->\".\n\n(**\nCoq responds:\n<<\n\"A -> B\" := forall _ : A, B \n>>\n\nThat is, [A -> B] is really just syntactic sugar for [forall (_:A), B], where\nwe've added some parentheses for a little bit more clarity. Still, that\nexpression is tricky to read because of the wildcard in it. It might help if we\nmade [A] and [B] concrete, for example, if [A] is [P /\\ Q] and [B] is [Q], where\n[P] and [Q] are propositions. Then we could think of the type [forall (_ : P /\\\nQ), Q] as follows:\n\n- [(_ : P /\\ Q)] means an unnamed value of type [P /\\ Q].  Using the evidence \n  interpretation we've been developing throughout this file, that value would be \n  evidence that [P /\\ Q] holds.  It's unnamed because it's not used on the\n  right-hand side.\n\n- A value of type [Q] would be evidence for [Q].\n\n- So a value of type [forall (_ : P /\\ Q), Q] would be a \"thing\" that\n  for any piece of evidence that [P /\\ Q] holds can produce evidence\n  that [Q] holds.\n\nWhat is such a \"thing\"?  A function!  It transforms evidence for one proposition\ninto evidence for another proposition. *)\n\nDefinition pnqiq : forall P Q, P /\\ Q -> Q := fun P Q pnq =>\n  match pnq with\n  | conj evP evQ => evQ\n  end.\n  \nDefinition pnqiq' : forall P Q, forall (_: P /\\ Q), Q := pnqiq.\n\n(** \n You can also see this duality with familiar functions. For example, consider \n the [is_zero] function that returns [true] if the given number is [0]. *)\n\nDefinition is_zero n :=\n  match n with\n  | 0 => true\n  | _ => false\n  end.\n\n(**\n This function has the type [nat -> bool].\n *)\n\nDefinition is_zero' : nat -> bool := is_zero.\n\n(** \n Equivalently, we can also assign the type [forall (_:nat), bool] to the [is_zero]\n function. *)\n\nDefinition is_zero'' : forall (_:nat), bool := is_zero.\n\n(**\n\nSo of all the logic we've coded up in Coq in this file, the only truly primitive\npieces are [Inductive] definitions and [forall] types. Everything\nelse---equality, implication, conjunction, disjunction, true, false,\nnegation---can all be expressed in terms of those two primitives.\n\nAnd although we had to learn many tactics, every proof we constructed with them\nwas really just a program that used functions, application, and pattern\nmatching.\n\n(**********************************************************************)\n\n** Tautologies\n\n(Or, \"How to make the computer do your CS 2800 logic homework for you\".)\n\nWe needed to learn the tactics and definitions above for the more complicated\nproofs we will later want to do in Coq.  But if all you care about is proving\nsimple logical propositions, there's a tactic for that: [tauto].  It will\nsucceed in finding a proof of any propositional _tautology_, which is a formula\nthat must always hold regardless of the values of variables in it.\n\nFor example, one of the most complicated proofs we did above was De Morgan's\nlaw.  Here it is in just one tactic: *)\n\nTheorem deMorgan' : forall P Q : Prop,\n  ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\n  tauto.\nQed.\n\nPrint deMorgan'.\n\n(**\nCoq responds:\n\n<<\ndeMorgan' = \nfun (P Q : Prop) (H : ~ (P \\/ Q)) =>\nlet H0 := (fun H0 : P => H (or_introl H0)) : P -> False in\nlet H1 := (fun H1 : Q => H (or_intror H1)) : Q -> False in\nconj (fun H2 : P => let H3 := H0 H2 : False in False_ind False H3)\n  (fun H2 : Q => let H3 := H1 H2 : False in False_ind False H3)\n     : forall P Q : Prop, ~ (P \\/ Q) -> ~ P /\\ ~ Q\n>>\n\nThat's a bit more complicated of a proof than the one we constructed ourselves,\nmainly because of the [let] expressions, but it still is correct. \n\nSo if your CS 2800 prof wants you to prove a propositional tautology, and if\nit's a proposition that holds in constructive logic, Coq's got your back: just\nuse [tauto] to do it.  \n\nBut don't tell your 2800 prof I told you that.\n\n** Summary\n\nCoq's built-in logic is constructive:  it isn't sufficient to argue that\na proposition must be true or false; rather, we have to construct evidence\nfor the proposition.  Programs are how we construct and transform evidence.\nAll of the propositional connectives, except implication, are \"coded up\"\nin Coq using inductive types, and proofs about them routinely use pattern\nmatching and function application.\n\n** Terms and concepts\n\n- assumption\n- classical logic\n- conjunction\n- constructive logic\n- constructor\n- contradiction\n- De Morgan's laws\n- disjunction\n- double negation\n- evidence\n- excluded middle\n- implication\n- inductive type\n- negation\n- Principle of Explosion\n- [Prop]\n- proposition\n- reflexivity\n- [Set]\n- syllogism\n- tautology\n- transitivity\n- truth table\n\n** Tactics\n\n- [apply]\n- [assumption]\n- [contradiction]\n- [destruct..as]\n- [exact]\n- [left]\n- [right]\n- [split]\n- [tauto]\n- tacticals: nested bullets [-], [*], [+]\n\n** Further reading\n\n- _Software Foundations, Volume 1: Logical Foundations_. \n  #<a href=\"https://softwarefoundations.cis.upenn.edu/lf-current/Logic.html\">\n  Chapter 6: Logic.</a>#\n\n- _Interactive Theorem Proving and Program Development_.\n  Chapters 5 and 8.2. Available \n  #<a href=\"https://newcatalog.library.cornell.edu/catalog/10131206\">\n  online from the Cornell library</a>#.\n\n*)\n", "meta": {"author": "kayceesrk", "repo": "cs6225_s20_iitm", "sha": "1cb2ad5a92ed9fadd0bc23218c159a762301ae0f", "save_path": "github-repos/coq/kayceesrk-cs6225_s20_iitm", "path": "github-repos/coq/kayceesrk-cs6225_s20_iitm/cs6225_s20_iitm-1cb2ad5a92ed9fadd0bc23218c159a762301ae0f/lectures/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.9124361586911174, "lm_q1q2_score": 0.7305803390266639}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) : natural :=\n  plus (Succ Zero) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj63_coqofml_4WGWbB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.730580337233837}}
{"text": "Require Import List.  \n\nRequire Import Logic.Class.Ord.\n\nRequire Import Logic.List.In.\nRequire Import Logic.List.Equiv.\n\n(* Insert the element x inside the ordered list xs                              *)\nFixpoint insert (a:Type) (o:Ord a) (x:a) (xs:list a) : list a :=\n    match xs with\n    | nil       => cons x nil\n    | cons y ys => \n        match (leqDec x y) with\n        | left _    => cons y (insert a o x ys) (* x 'smaller' does inside      *)\n        | right _   => cons x (cons y ys)\n        end\n    end.\n\nArguments insert {a} {o}.\n\n(* Sorts a list by decreasing order                                             *)\nFixpoint sort (a:Type) (o:Ord a) (xs:list a) : list a :=\n    match xs with\n    | nil       => nil\n    | cons x xs => insert x (sort a o xs)\n    end.\n\nArguments sort {a} {o}.\n\n(* 'Sorted' means by decreasing order: need Ord instance for 'leq'              *)\nInductive Sorted (a:Type) (o:Ord a) : list a -> Prop :=\n| SortedNil    : Sorted a o nil\n| SortedSingle : forall (x:a), Sorted a o (cons x nil)\n| SortedCons   : forall (x y:a) (xs:list a), \n    leq x y -> Sorted a o (cons x xs) -> Sorted a o (cons y (cons x xs)) \n.\n\nArguments Sorted       {a} {o}.\nArguments SortedNil    {a} {o}.\nArguments SortedCons   {a} {o}.\nArguments SortedSingle {a} {o}.\n\nLemma insertEquivCons : forall (a:Type) (o:Ord a) (x:a) (xs:list a),\n    insert x xs == cons x xs.\nProof.\n    intros a o x xs. revert x. induction xs as [|x xs IH]; intros y.\n    - apply equivRefl.\n    - simpl. destruct (leqDec y x) as [H|H].\n        + split; intros z H1.\n            { destruct H1 as [H1|H1].\n                { subst. right. left. reflexivity. }\n                { destruct (IH y) as [H2 H3]. destruct ((H2 z) H1) as [H4|H4].\n                    { subst. left. reflexivity. }\n                    { right. right. assumption. }}}\n            { destruct H1 as [H1|H1].\n                { subst. destruct (IH z) as [H2 H3]. right. apply H3.\n                  left. reflexivity. }\n                { destruct H1 as [H1|H1].\n                    { subst. left. reflexivity. }\n                    { right. destruct (IH y) as [H2 H3]. apply H3.\n                      right. assumption. }}}\n        + split; intros z H1; assumption.\nQed.\n\nLemma sortEquiv : forall (a:Type) (o:Ord a) (xs:list a), sort xs == xs.\nProof.\n    intros a o. induction xs as [|x xs [IH1 IH2]].\n    - apply equivRefl.\n    - simpl. apply equivTrans with (cons x (sort xs)).\n        + apply insertEquivCons.\n        + split; intros z [H1|H1].\n            { subst. left. reflexivity. }\n            { right. apply IH1. assumption. }\n            { subst. left. reflexivity. }\n            { right. apply IH2. assumption. }\nQed.\n\nLemma insertIn : forall (a:Type) (o:Ord a) (x:a) (xs:list a), x :: insert x xs.\nProof.\n    intros a o x xs. revert x. induction xs as [|x xs IH]; intros y; simpl.\n    - left. reflexivity.\n    - destruct (leqDec y x) as [H|H].\n        + right. apply IH.\n        + left. reflexivity.\nQed.\n\nLemma sortInIff : forall (a:Type) (o:Ord a) (x:a) (xs:list a),\n    x :: xs <-> x :: sort xs.\nProof.\n    intros a o x xs. destruct (sortEquiv a o xs) as [H1 H2]. split; intros H.\n    - apply H2. assumption.\n    - apply H1. assumption.\nQed.\n\n\n(* Inserting an element into a sorted list leads to a sorted list.              *)\nLemma insertSorted : forall (a:Type) (o:Ord a) (x:a) (xs:list a),\n    Sorted xs -> Sorted (insert x xs).\nProof.\n    intros a o x xs H. revert x. induction H as [|x|x y xs H1 H2 IH]; intros u.\n    - simpl. constructor.\n    - simpl. destruct (leqDec u x) as [H'|H'].\n        + constructor.\n            { assumption. }\n            { constructor. } \n        + constructor.\n            { destruct (leqTotal u x) as [H1|H1].\n                { apply H' in H1. contradiction. }\n                { assumption. }}\n            { constructor. }\n    - simpl. simpl in IH. \n      destruct (leqDec u y) as [H3|H3].\n        + remember (IH u) as H5 eqn:F. clear F. \n          destruct (leqDec u x) as [H4|H4] eqn:E; constructor; assumption.\n        + constructor.\n            { destruct (leqTotal u y) as [H6|H6].\n                { apply H3 in H6. contradiction. }\n                { assumption. }}\n            { remember (IH y) as H5 eqn:F. clear F.\n                destruct (leqDec y x) as [H7|H7].\n                    { constructor; assumption. }\n                    { assumption. }}\nQed.\n\n(* Sorting a list leads to a sorted list.                                       *)\nLemma sortSorted : forall (a:Type) (o:Ord a) (xs:list a), Sorted (sort xs).\nProof.\n    intros a o. induction xs as [|x xs IH]; simpl.\n    - constructor.\n    - apply insertSorted. assumption.\nQed.\n\n\nLemma sortedConsInLeq : forall (a:Type) (o:Ord a) (x y:a) (xs:list a),\n    Sorted (cons x xs) -> y :: xs -> leq y x.\nProof.\n    intros a o x y xs H. remember (cons x xs) as ys eqn:E. revert E.\n    revert xs x y. induction H as [|u|u v us H1 H2 IH]; intros xs x y H.\n    - inversion H.\n    - inversion H. intros H'. inversion H'.\n    - inversion H. clear H. subst. intros [H3|H3].\n        + subst. assumption.\n        + apply leqTrans with u.\n            { apply IH with us.\n                { reflexivity. }\n                { assumption. }}\n            { assumption. }\nQed.\n\nLemma sortedCons : forall (a:Type) (o:Ord a) (x:a) (xs:list a),\n    (forall (z:a), z :: xs -> leq z x) -> Sorted xs -> Sorted (cons x xs).\nProof.\n    intros a o x xs H1 H2. revert H1. revert x.\n    induction H2 as [|x|x y xs H1 H2 IH]; intros z H.\n    - constructor.\n    - constructor.\n        + apply H. left. reflexivity.\n        + constructor.\n    - constructor.\n        + apply H. left. reflexivity.\n        + apply IH. clear H. clear z. intros z [H3|H3].\n            { subst. assumption. }\n            { apply leqTrans with x.\n                { apply sortedConsInLeq with xs; assumption. }\n                { assumption. }}\nQed.\n\nLemma insertIsCons : forall (a:Type) (o:Ord a) (x:a) (xs:list a),\n    (forall (y:a), y :: xs -> leq y x) -> insert x xs = cons x xs.\nProof.\n    intros a o x xs. revert x. induction xs as [|x xs IH]; intros y H.\n    - reflexivity.\n    - simpl. destruct (leqDec y x) as [H1|H1].\n        + assert (x = y) as H2.\n            { apply leqAsym.\n                { apply H. left. reflexivity. }\n                { assumption. }}\n          subst. rewrite IH.\n            { reflexivity. }\n            { intros x H2. apply H. right. assumption. }\n        + reflexivity.\nQed.\n\nLemma sortSame : forall (a:Type) (o:Ord a) (xs:list a),\n    Sorted xs -> sort xs = xs.\nProof.\n    intros a o xs H. induction H as [|x|x y xs H1 H2 IH].\n    - reflexivity.\n    - reflexivity.\n    - simpl. simpl in IH. rewrite IH. simpl. destruct (leqDec y x) as [H3|H3].\n        + destruct (eqDec x y) as [H4|H4].\n            { subst. clear H1 H3. simpl. rewrite insertIsCons.\n                { reflexivity. }\n                { intros x H3. apply sortedConsInLeq with xs; assumption. }}\n            { exfalso. apply H4. apply leqAsym; assumption. }\n        + reflexivity.\nQed.\n\nLemma sortedConsSortedTail : forall (a:Type) (o:Ord a) (x:a) (xs:list a),\n    Sorted (cons x xs) -> Sorted xs.\nProof.\n    intros a o x xs H. remember (cons x xs) as ys eqn:E.\n    revert E. revert x xs. destruct H as [|x|x y xs H1 H2]; intros z zs H.\n    - inversion H.\n    - inversion H. constructor.\n    - inversion H. assumption.\nQed.\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/Logic/List/Sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7305621290953977}}
{"text": "Require Import Omega.\n\nInductive Plus : nat -> nat -> nat -> Prop :=\n| PlusZero\n  : forall m, Plus 0 m m\n| PlusSucc\n  : forall n m r,\n    Plus n m r ->\n    Plus (S n) m (S r).\n\nHint Constructors Plus.\n\nDefinition plus_cert : forall (n m : nat), {r : nat | Plus n m r}.\n  refine (fix plus_cert (n m : nat) : {r | Plus n m r} :=\n            match n return {r | Plus n m r} with\n            | O    => exist _ m _\n            | S n1 =>\n              match plus_cert n1 m with\n              | exist _ r1 _ => exist _ (S r1) _\n              end\n            end) ; clear plus_cert ; auto.\nDefined.\n\nDefinition pred_cert : forall (n : nat), n > 0 -> {r | n = 1 + r}.\n  refine (fun n =>\n            match n return n > 0 -> {r | n = 1 + r} with\n            | O => fun _ => False_rec _ _\n            | S n' => fun _ => exist _ n' _\n            end) ; omega.\nDefined.\n\nNotation \"!\" := (False_rec _ _).\nNotation \"[ e ]\" := (exist _ e _).\n\nDefinition pred_cert1 : forall (n : nat), n > 0 -> {r | n = 1 + r}.\n  refine (fun n =>\n            match n return n > 0 -> {r | n = 1 + r} with\n            | O => fun _ => !\n            | S n' => fun _ => [ n' ]\n            end) ; omega.\nDefined.\n\nNotation \"'Yes'\" := (left _ _).\nNotation \"'No'\" := (right _ _).\nNotation \"'Reduce' x\" := (if x then Yes else No) (at level 50).\n\nDefinition eq_nat_dec : forall (n m : nat), {n = m} + {n <> m}.\n  refine (fix eq_nat n m : {n = m} + {n <> m} :=\n            match n , m with\n            | O    , O    => Yes\n            | S n' , S m' => Reduce (eq_nat n' m')\n            | _    , _    => No\n            end) ; clear eq_nat ; congruence.\nDefined.\n\n(** exercício 44 *)\n\nDefinition eq_bool_dec : forall (a b : bool), {a = b} + {a <> b}.\n  refine (fun (a b : bool) => \n                match a, b return {a = b} + {a <> b} with\n                | false, false => Yes\n                | true , true  => Yes\n                | _    , _     => No                    \n                end) ; auto ; intro ; congruence.\nDefined.\n\n(** exercício 45 *)\n\nDefinition eq_list_dec\n           {A : Type}\n           (eqAdec : forall (x y : A), {x = y} + {x <> y})\n  : forall (xs ys : list A), {xs = ys} + {xs <> ys}.\n  induction xs.\n  +\n    intro ys.\n    destruct ys.\n    -\n      left ; auto.\n    -\n      right ; intro ; congruence.\n  +\n    intro ys.\n    destruct ys.\n    -\n      right ; intro ; congruence.\n    -\n      destruct (eqAdec a a0).\n      *\n        subst.\n        destruct (IHxs ys).\n        ++\n          subst ; left ; f_equal.\n        ++\n          right ; intro ; congruence.\n      *\n        right ; intro ; congruence.\nDefined.\n\n\nNotation \"!!\" := (inright _ _).\nNotation \"[|| x ||]\" := (inleft _ [x]).\n\n\nDefinition pred_cert_full : forall n, {r | n = 1 + r} + {n = 0}.\n  refine (fun n =>\n            match n return {r | n = 1 + r} + {n = 0} with\n            | O => !!\n            | S n' => [|| n' ||] \n            end) ; auto.\nDefined.\n\nLtac inverts H := inversion H ; subst ; clear H.\n\nSection MAP.\n  Variable Key : Type.\n  Variable Value : Type.\n  Variable eqKeyDec : forall (x y : Key), {x = y} + {x <> y}.\n\n  Inductive Map : Type :=\n  | nil : Map\n  | cons : Key -> Value -> Map -> Map.\n\n  Inductive MapsTo : Key -> Value -> Map -> Prop :=\n  | Here  : forall k v m, MapsTo k v (cons k v m)\n  | There : forall k v m k' v', k <> k' ->\n            MapsTo k v m -> MapsTo k v (cons k' v' m).\n  \n  Hint Constructors MapsTo.\n  \n  Definition lookupMap\n    : forall (k : Key)(m : Map), {v | MapsTo k v m} + {forall v, ~ MapsTo k v m}.\n    refine (fix look k m : {v | MapsTo k v m} + {forall v, ~ MapsTo k v m} :=\n              match m return {v | MapsTo k v m} + {forall v, ~ MapsTo k v m} with\n              | nil => !!\n              | cons k' v' m' =>\n                match eqKeyDec k k' with\n                | Yes => [|| v' ||]\n                | No  =>\n                  match look k m' with\n                  | !! => !!\n                  | [|| v ||] => [|| v ||]\n                  end\n                end\n              end) ;\n      clear look ; subst ;\n        try (repeat (match goal with\n                     | [H : MapsTo _ _ nil |- _] => inverts H\n                     | [H : MapsTo _ _ (cons _ _ _) |- _] => inverts H\n                     | [|- forall x, ~ _ ] => unfold not ; intros\n                     | [ H : forall x, ~ (MapsTo _ _ _)\n                         , H1 : MapsTo _ _ _ |- _] => apply H in H1\n                     end)) ; auto.\n  Defined.\n\n  (** exercício 46 *)\n\n  Definition insertMap : forall (k : Key)(v : Value)(m : Map), {m' | MapsTo k v m'}.\n    intros k v m.\n    exists (cons k v m).\n    auto.\n  Defined.\n  \n  (** exercício 47 *)\n\n  Definition removeMap : forall (k : Key)(m : Map), {m' | forall v, ~ MapsTo k v m'}.\n    intros k m.\n    induction m.\n    +\n      exists nil.\n      intros v H.\n      inverts H.\n    +\n      destruct IHm as [m' Hm'].\n      destruct m'.\n      -\n        exists nil.\n        auto.\n      -\n        destruct (eqKeyDec k k1).\n        *\n          subst.\n          assert (H: ~ MapsTo k1 v0 (cons k1 v0 m')).\n          ** auto.\n          **\n            exists m'.\n            intros v1 H1.\n            apply H.\n            auto.\n        *\n          exists (cons k1 v0 m').\n          intros v1 ; auto.\n  Defined.\nEnd MAP.  \n\n\nSection VEC.\n\n  Inductive vector (A : Set) : nat -> Type :=\n  | vnil  : vector A 0\n  | vcons : forall n, A -> vector A n -> vector A (S n).\n\n  Fixpoint app {A : Set}{n1 n2}(ls1 : vector A n1)(ls2 : vector A n2) : vector A (n1 + n2) :=\n    match ls1 with\n    | vnil _ => ls2\n    | vcons _ _ x ls1' => vcons _ _ x (app ls1' ls2)\n    end.\n\n  Definition vhead {A : Set}{n}(v : vector A (S n)) : A :=\n    match v with\n    | vcons _ _ x _ => x  \n    end.\n\n  (** exercício 48 *)\n\n  Fixpoint vmap {A B : Set}{n}(f : A -> B)(v : vector A n) : vector B n :=\n    match v with\n    | vnil _ => vnil _\n    | vcons _ _ x vs => vcons _ _ (f x) (vmap f vs)\n    end.\n  \n\n  (** exercício 49 \n      Enuncie um teorema sobre a associatividade da \n      concatenação de vectors e o prove. *)\n\n  Inductive fin : nat -> Set :=\n  | fzero : forall {n}, fin (S n)\n  | fsucc : forall {n}, fin n -> fin (S n).                          \n\n  Fixpoint get {A}{n}(ls : vector A n) : fin n -> A :=\n    match ls with\n      | vnil _ => fun idx =>\n        match idx in fin n' return (match n' with\n                                        | O => A\n                                        | S _ => unit\n                                      end) with\n          | fzero => tt\n          | fsucc _ => tt\n        end\n      | vcons _ _ x ls' => fun idx =>\n        match idx in fin n' return (fin (pred n') -> A) -> A with\n          | fzero => fun _ => x\n          | fsucc idx' => fun get_ls' => get_ls' idx'\n        end (get ls')\n    end.\nEnd VEC.  \n", "meta": {"author": "rodrigogribeiro", "repo": "coqcourse", "sha": "1e39614285522cba5045b0a190e3bd19c560a2f7", "save_path": "github-repos/coq/rodrigogribeiro-coqcourse", "path": "github-repos/coq/rodrigogribeiro-coqcourse/coqcourse-1e39614285522cba5045b0a190e3bd19c560a2f7/code/dependenttypes_sol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7305566275181702}}
{"text": "Require Export SfLib.\nRequire Import ListSet.\n(* see http://coq.inria.fr/distrib/V8.4/stdlib/Coq.Lists.ListSet.html \n   for the ListSet library *)\nRequire Import Imp.\n\n(* acon true , acon false *)\nInductive assert: Type :=\n  | PTrue: assert  (* true *)\n  | PFalse: assert (* false *)\n  | PEq: aexp -> aexp -> assert  (* e1 = e2 *)\n  | PLt: aexp -> aexp -> assert  (* e1 < e2 *)\n  | PImp: assert -> assert -> assert (* a1 ==> a2 *)\n  | PAnd: assert -> assert -> assert (* a1 /\\ a2 *)\n  | PNot: assert -> assert (* not a *)\n  | POr : assert -> assert -> assert (* a1 \\/ a2 *)\n  | PForall: id -> assert -> assert (* forall x. a *)\n  | PExist: id -> assert -> assert  (* exists x. a *).\n\n\n\nFixpoint peval (p: assert) (st: state) : Prop :=\n  match p with\n  | PTrue => True\n  | PFalse => False\n  | PEq a1 a2 => (aeval st a1) = (aeval st a2)\n  | PLt a1 a2 => (aeval st a1) < (aeval st a2)\n  | PImp p1 p2 => (peval p1 st) -> (peval p2 st)\n  | PAnd p1 p2 => \n       (peval p1 st) /\\ (peval p2 st)\n  | POr p1 p2 => (peval p1 st) \\/ (peval p2 st)\n  | PNot p' => ~ (peval p' st)\n  | PForall x p' => forall n: nat, peval p' (update st x n)\n  | PExist x p' => exists n: nat, peval p' (update st x n) \n  end.\n\n\nDefinition valid (p: assert): Prop := \n  forall st : state, peval p st.\n\nDefinition strongerThan (p q: assert) : Prop := \n  forall st, peval p st -> peval q st.\n\n\n\n(* definition of judgment |- a *)\nInductive judge : assert -> Prop := \n  | xPlusZero : forall x: id, \n                  judge (PEq (APlus (AId x) (ANum 0)) (AId x))\n  | SymmObjEq : forall a1 a2 : aexp,\n                  judge (PImp (PEq a1 a2) (PEq a2 a1))\n  | ModusPonens: forall p q: assert, \n                  judge p -> judge (PImp p q) -> judge q\n  | Generalization: forall (x: id) (p: assert),\n                      judge p -> judge (PForall x p).\n\nCheck judge.\n\n\n(* prove the judgment |- forall x, x = x+0 *)\nLemma test: judge (PForall X (PEq (AId X) (APlus (AId X) (ANum 0)))).\nProof.\n  Admitted.\n\n(* exercise: prove the soundness of the simple logic theory *)\nLemma soundJudge: forall p, judge p -> valid p.\nProof.\n  Admitted.\n\n(* set of variables *)\nDefinition idSet := set id.\n\nDefinition emp_is : idSet := nil.\n\n(* eq_id_dec : forall id1 id2 : id, {id1 = id2} + {id1 <> id2}. *)\n\nDefinition is_add (i: id) (is: idSet) := set_add eq_id_dec i is.\n\nDefinition is_remove (i: id) (is: idSet) := set_remove eq_id_dec i is.\n\nDefinition is_union (is1 is2: idSet) := set_union eq_id_dec is1 is2.\n\nDefinition is_In (i: id) (is: idSet) : Prop := set_In i is.\n\nFixpoint fv_aexp (a : aexp) : idSet := \n  match a with\n  | ANum _ => emp_is\n  | AId x => [x]\n  | APlus a1 a2 => is_union (fv_aexp a1) (fv_aexp a2)\n  | AMinus a1 a2 => is_union (fv_aexp a1) (fv_aexp a2)\n  | AMult a1 a2 => is_union (fv_aexp a1) (fv_aexp a2)\n  end.\n  \n\nFixpoint fv_ast (p: assert) : idSet := \n  match p with\n  | PTrue => emp_is\n  | PFalse => emp_is\n  | PEq a1 a2 => is_union (fv_aexp a1) (fv_aexp a2)\n  | PLt a1 a2 => is_union (fv_aexp a1) (fv_aexp a2)\n  | PImp p1 p2 => is_union (fv_ast p1) (fv_ast p2) \n  | PAnd p1 p2 => is_union (fv_ast p1) (fv_ast p2)\n  | POr p1 p2 => is_union (fv_ast p1) (fv_ast p2)\n  | PNot p' => fv_ast p'\n  | PForall x p' => is_remove x (fv_ast p')\n  | PExist x p' => is_remove x (fv_ast p')\n  end.\n\n(* exercise: prove the coincidence theorem shown in class *)\nLemma coincidence_exp: forall (st st': state) (a: aexp),\n  (forall i: id, is_In i (fv_aexp a) -> st i = st' i)\n  -> aeval st a = aeval st' a.\nProof.\n  Admitted.\n\nTheorem coincidence: forall (st st': state) (p: assert),\n  (forall i: id, is_In i (fv_ast p) -> st i = st' i)\n  -> (peval p st <-> peval p st').\nProof.\n  Admitted.\n\nDefinition subst : Type := list (id * aexp).\n\nFixpoint lookup_subst (i: id) (delta: subst) : option aexp :=\n  match delta with\n  | nil => None\n  | (i', a') :: d => if eq_id_dec i i' then Some a' else lookup_subst i d\n  end.\n\n(* this is a five star exercise (very difficult):\n   define substitution, then formulate and prove \n   the substitution theorem shown in class. \n   *** Try to work on it early. Don't wait till \n       the last minute ***\n*)\n", "meta": {"author": "hchunhui", "repo": "sf", "sha": "3e95e8b0acd94fda30da4ef1fbcc662e49a007e2", "save_path": "github-repos/coq/hchunhui-sf", "path": "github-repos/coq/hchunhui-sf/sf-3e95e8b0acd94fda30da4ef1fbcc662e49a007e2/PredLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.730556608544014}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(*i $Id: Plus.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(** Properties of addition. [add] is defined in [Init/Peano.v] as:\n<<\nFixpoint plus (n m:nat) : nat :=\n  match n with\n  | O => m\n  | S p => S (p + m)\n  end\nwhere \"n + m\" := (plus n m) : nat_scope.\n>>\n *)\n\nRequire Import Le.\nRequire Import Lt.\n\nOpen Local Scope nat_scope.\n\nImplicit Types m n p q : nat.\n\n(** * Zero is neutral *)\n\nLemma plus_0_l : forall n, 0 + n = n.\nProof.\n  reflexivity.\nQed.\n\nLemma plus_0_r : forall n, n + 0 = n.\nProof.\n  intro; symmetry  in |- *; apply plus_n_O.\nQed.\n\n(** * Commutativity *)\n\nLemma plus_comm : forall n m, n + m = m + n.\nProof.\n  intros n m; elim n; simpl in |- *; auto with arith.\n  intros y H; elim (plus_n_Sm m y); auto with arith.\nQed.\nHint Immediate plus_comm: arith v62.\n\n(** * Associativity *)\n\nLemma plus_Snm_nSm : forall n m, S n + m = n + S m.\nProof.\n  intros.\n  simpl in |- *.\n  rewrite (plus_comm n m).\n  rewrite (plus_comm n (S m)).\n  trivial with arith.\nQed.\n\nLemma plus_assoc : forall n m p, n + (m + p) = n + m + p.\nProof.\n  intros n m p; elim n; simpl in |- *; auto with arith.\nQed.\nHint Resolve plus_assoc: arith v62.\n\nLemma plus_permute : forall n m p, n + (m + p) = m + (n + p).\nProof.\n  intros; rewrite (plus_assoc m n p); rewrite (plus_comm m n); auto with arith.\nQed.\n\nLemma plus_assoc_reverse : forall n m p, n + m + p = n + (m + p).\nProof.\n  auto with arith.\nQed.\nHint Resolve plus_assoc_reverse: arith v62.\n\n(** * Simplification *)\n\nLemma plus_reg_l : forall n m p, p + n = p + m -> n = m.\nProof.\n  intros m p n; induction n; simpl in |- *; auto with arith.\nQed.\n\nLemma plus_le_reg_l : forall n m p, p + n <= p + m -> n <= m.\nProof.\n  induction p; simpl in |- *; auto with arith.\nQed.\n\nLemma plus_lt_reg_l : forall n m p, p + n < p + m -> n < m.\nProof.\n  induction p; simpl in |- *; auto with arith.\nQed.\n\n(** * Compatibility with order *)\n\nLemma plus_le_compat_l : forall n m p, n <= m -> p + n <= p + m.\nProof.\n  induction p; simpl in |- *; auto with arith.\nQed.\nHint Resolve plus_le_compat_l: arith v62.\n\nLemma plus_le_compat_r : forall n m p, n <= m -> n + p <= m + p.\nProof.\n  induction 1; simpl in |- *; auto with arith.\nQed.\nHint Resolve plus_le_compat_r: arith v62.\n\nLemma le_plus_l : forall n m, n <= n + m.\nProof.\n  induction n; simpl in |- *; auto with arith.\nQed.\nHint Resolve le_plus_l: arith v62.\n\nLemma le_plus_r : forall n m, m <= n + m.\nProof.\n  intros n m; elim n; simpl in |- *; auto with arith.\nQed.\nHint Resolve le_plus_r: arith v62.\n\nTheorem le_plus_trans : forall n m p, n <= m -> n <= m + p.\nProof.\n  intros; apply le_trans with (m := m); auto with arith.\nQed.\nHint Resolve le_plus_trans: arith v62.\n\nTheorem lt_plus_trans : forall n m p, n < m -> n < m + p.\nProof.\n  intros; apply lt_le_trans with (m := m); auto with arith.\nQed.\nHint Immediate lt_plus_trans: arith v62.\n\nLemma plus_lt_compat_l : forall n m p, n < m -> p + n < p + m.\nProof.\n  induction p; simpl in |- *; auto with arith.\nQed.\nHint Resolve plus_lt_compat_l: arith v62.\n\nLemma plus_lt_compat_r : forall n m p, n < m -> n + p < m + p.\nProof.\n  intros n m p H; rewrite (plus_comm n p); rewrite (plus_comm m p).\n  elim p; auto with arith.\nQed.\nHint Resolve plus_lt_compat_r: arith v62.\n\nLemma plus_le_compat : forall n m p q, n <= m -> p <= q -> n + p <= m + q.\nProof.\n  intros n m p q H H0.\n  elim H; simpl in |- *; auto with arith.\nQed.\n\nLemma plus_le_lt_compat : forall n m p q, n <= m -> p < q -> n + p < m + q.\nProof.\n  unfold lt in |- *. intros. change (S n + p <= m + q) in |- *. rewrite plus_Snm_nSm.\n  apply plus_le_compat; assumption.\nQed.\n\nLemma plus_lt_le_compat : forall n m p q, n < m -> p <= q -> n + p < m + q.\nProof.\n  unfold lt in |- *. intros. change (S n + p <= m + q) in |- *. apply plus_le_compat; assumption.\nQed.\n\nLemma plus_lt_compat : forall n m p q, n < m -> p < q -> n + p < m + q.\nProof.\n  intros. apply plus_lt_le_compat. assumption.\n  apply lt_le_weak. assumption.\nQed.\n\n(** * Inversion lemmas *)\n\nLemma plus_is_O : forall n m, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intro m; destruct m as [| n]; auto.\n  intros. discriminate H.\nQed.\n\nDefinition plus_is_one :\n  forall m n, m + n = 1 -> {m = 0 /\\ n = 1} + {m = 1 /\\ n = 0}.\nProof.\n  intro m; destruct m as [| n]; auto.\n  destruct n; auto.\n  intros.\n  simpl in H. discriminate H.\nDefined.\n\n(** * Derived properties *)\n\nLemma plus_permute_2_in_4 : forall n m p q, n + m + (p + q) = n + p + (m + q).\nProof.\n  intros m n p q.\n  rewrite <- (plus_assoc m n (p + q)). rewrite (plus_assoc n p q).\n  rewrite (plus_comm n p). rewrite <- (plus_assoc p n q). apply plus_assoc.\nQed.\n\n(** * Tail-recursive plus *)\n\n(** [tail_plus] is an alternative definition for [plus] which is\n    tail-recursive, whereas [plus] is not. This can be useful\n    when extracting programs. *)\n\nFixpoint tail_plus n m : nat :=\n  match n with\n    | O => m\n    | S n => tail_plus n (S m)\n  end.\n\nLemma plus_tail_plus : forall n m, n + m = tail_plus n m.\ninduction n as [| n IHn]; simpl in |- *; auto.\nintro m; rewrite <- IHn; simpl in |- *; auto.\nQed.\n\n(** * Discrimination *)\n\nLemma succ_plus_discr : forall n m, n <> S (plus m n).\nProof.\n  intros n m; induction n as [|n IHn].\n  discriminate.\n  intro H; apply IHn; apply eq_add_S; rewrite H; rewrite <- plus_n_Sm;\n    reflexivity.\nQed.\n\nLemma n_SSn : forall n, n <> S (S n).\nProof.\n  intro n; exact (succ_plus_discr n 1).\nQed.\n\nLemma n_SSSn : forall n, n <> S (S (S n)).\nProof.\n  intro n; exact (succ_plus_discr n 2).\nQed.\n\nLemma n_SSSSn : forall n, n <> S (S (S (S n))).\nProof.\n  intro n; exact (succ_plus_discr n 3).\nQed.\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/theories/Arith/Plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7303796095996867}}
{"text": "(** 2. Lambda-term semantic and Beta reduction *)\n\nRequire Import lterm substitution.\n\n(** 2.1. One step of Beta-reduction *)\nInductive beta_reduct: lterm -> lterm -> Prop :=\n  | Beta_reduct_step:\n    forall t u: lterm, beta_reduct (Apply (Lambda t) u) (subst t 0 u)\n  | Beta_reduct_close_apply1:\n    forall t u v: lterm, beta_reduct t u -> beta_reduct (Apply t v) (Apply u v)\n  | Beta_reduct_close_apply2:\n    forall t u v: lterm, beta_reduct t u -> beta_reduct (Apply v t) (Apply v u)\n  | Beta_reduct_close_lambda:\n    forall t u: lterm, beta_reduct t u -> beta_reduct (Lambda t) (Lambda u)     \n.\n\n(** 2.2. Beta-reduction in any number of steps *)\nInductive beta_reduct_star: lterm -> lterm -> Prop :=\n  | Beta_reduct_star_eq: forall t: lterm, beta_reduct_star t t\n  | Beta_reduct_star_step: forall t u v: lterm,\n      beta_reduct t u -> beta_reduct_star u v -> beta_reduct_star t v\n.\n\n(** 2.3. Prove beta_reduct properties for beta_reduct_star *)\nTheorem beta_reduct_one_is_star:\n  forall t u: lterm, beta_reduct t u -> beta_reduct_star t u.\nProof.\n  intros t u H.\n  apply (Beta_reduct_star_step t u u); trivial.\n  apply Beta_reduct_star_eq.\nSave.\n\nTheorem beta_reduct_star_step:\n  forall t u: lterm, beta_reduct_star (Apply (Lambda t) u) (subst t 0 u).\nProof.\n  intros t u.\n  apply beta_reduct_one_is_star.\n  apply Beta_reduct_step.\nSave.\n\nTheorem beta_reduct_star_close_apply1:\n  forall t u v: lterm,\n  beta_reduct_star t u -> beta_reduct_star (Apply t v) (Apply u v).\nProof.\n  intros t u v H; induction H.\n  apply Beta_reduct_star_eq.\n  apply (Beta_reduct_star_step (Apply t v) (Apply u v) (Apply v0 v)); trivial.\n  apply Beta_reduct_close_apply1; trivial.\nSave.\n\nTheorem beta_reduct_star_close_apply2:\n  forall t u v: lterm,\n  beta_reduct_star t u -> beta_reduct_star (Apply v t) (Apply v u).\nProof.\n  intros t u v H; induction H.\n  apply Beta_reduct_star_eq.\n  apply (Beta_reduct_star_step (Apply v t) (Apply v u) (Apply v v0)); trivial.\n  apply Beta_reduct_close_apply2; trivial.\nSave.\n\nTheorem beta_reduct_star_close_lambda:\n  forall t u: lterm,\n  beta_reduct_star t u -> beta_reduct_star (Lambda t) (Lambda u).\nProof.\n  intros t u H; induction H.\n  apply Beta_reduct_star_eq.\n  apply (Beta_reduct_star_step (Lambda t) (Lambda u) (Lambda v)); trivial.\n  apply Beta_reduct_close_lambda; trivial.\nSave.\n", "meta": {"author": "fishilico", "repo": "INF565-coq-project", "sha": "fe2e9c7f18d450e73e0d281ce40d96fe13015ac6", "save_path": "github-repos/coq/fishilico-INF565-coq-project", "path": "github-repos/coq/fishilico-INF565-coq-project/INF565-coq-project-fe2e9c7f18d450e73e0d281ce40d96fe13015ac6/beta_reduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8459424450764199, "lm_q1q2_score": 0.7303796036525746}}
{"text": "Section Groups.\n\nRequire Omega.\n\nClass Group : Type :=\n{\n  G : Type;\n  dot : G -> G -> G;\n  e : G;\n  inv : G -> G;\n  dot_assoc :\n    forall x y z, dot (dot x y) z = dot x (dot y z);\n  id_left :\n    forall x, dot e x = x;\n  id_right :\n    forall x, dot x e = x;\n  inv_left :\n    forall x, dot (inv x) x = e;\n  inv_right :\n    forall x, dot x (inv x) = e\n}.\n\nInfix \"⊙\" := dot (at level 60).\nNotation \"- a\" := (inv a).\n\nContext `{Grp : Group}.\n\nTheorem identity_uniqueness :\n  forall u, (forall x, u ⊙ x = x) -> u = e.\n    intros u H.\n    rewrite <- (id_right u).\n    apply H.\nQed.\n\nTheorem inverse_uniqueness :\n  forall x u, u ⊙ x = e -> u = -x.\n    intros x u.\n    (*split*)\n\n    intro H.\n    rewrite <- (id_right u), <- (inv_right x), <- dot_assoc, H.\n    apply id_left.\n\n    (*\n    intro H.\n    rewrite H.\n    apply inv_left. *)\nQed.\n\nFact inverse_uniqueness_symmetry :\n  forall x u, u ⊙ x = e <-> x ⊙ u = e.\n    intros x u.\n    split.\n\n    intro H.\n    rewrite (inverse_uniqueness x u).\n    apply inv_right.\n    assumption.\n\n    intro H.\n    rewrite (inverse_uniqueness u x).\n    apply inv_right.\n    assumption.\nQed.\n\nLemma id_self_inverse :\n  e = -e.\n    apply (inverse_uniqueness e e).\n    apply id_left.\nQed.\n\nLemma double_inverse :\n  forall g, g = --g.\n    intro g.\n    apply (inverse_uniqueness (-g) g).\n    apply inv_right.\nQed.\n\nLemma equality :\n  forall x y, x = y -> x ⊙ -y = e.\n    intros x y H.\n    rewrite <- H.\n    apply inv_right.\nQed.\n\nLemma inverse_equality :\n  forall x y, x = -y -> x ⊙ y = e.\n    intros x y H.\n    rewrite H.\n    apply inv_left.\nQed.\n\nTheorem inverse_of_dot :\n  forall a b, -(a ⊙ b) = -b ⊙ -a.\n    intros.\n    symmetry.\n    apply (inverse_uniqueness (a ⊙ b) (-b ⊙ -a)).\n    rewrite dot_assoc, <- (dot_assoc (inv a) a b),\n            (inv_left a), (id_left b), (inv_left b).\n    trivial.\nQed.\n\nDefinition choice := nat -> G.\n\nFixpoint finite_dot (w : choice) (k : nat) :=\n  match k with\n  | O => e\n  | S m => (finite_dot w m) ⊙ (w m)\n  end.\n\nFixpoint finite_inv_dot (w : choice) (k : nat) :=\n  match k with\n  | O => e\n  | S m => -(w m) ⊙ (finite_inv_dot w m)\n  end.\n\nTheorem inverse_of_finite_dot :\n  forall w n, inv (finite_dot w n) = finite_inv_dot w n.\n    intros w n.\n    elim n.\n\n    simpl.\n    symmetry.\n    apply id_self_inverse.\n\n    intros n0 H.\n    simpl.\n    symmetry.\n    apply inverse_uniqueness.\n    symmetry in H.\n    apply inverse_equality in H.\n    rewrite dot_assoc.\n    rewrite <- (dot_assoc (finite_inv_dot w n0)\n                          (finite_dot w n0)\n                          (w n0)).\n    rewrite H.\n    rewrite id_left.\n    apply inv_left.\nQed.\n\nTheorem eq_left_solution :\n  forall a b x, x ⊙ a = b -> x = b ⊙ -a.\n    intros a b x H.\n    apply equality in H.\n    rewrite dot_assoc in H.\n    apply inverse_uniqueness in H.\n    rewrite (inverse_of_dot a (inv b)) in H.\n    rewrite <- (double_inverse b) in H.\n    assumption.\nQed.\n\nDefinition has_order t :=\n  exists f : G -> nat,\n    forall g h : G,\n      (f g < t /\\ f h < t) ->\n      (forall k : nat, k < t -> exists x : G, f x = k) /\\\n      (f g = f h -> g = h).\n\nDefinition finite :=\n  exists t, has_order t.\n\nDefinition singular :=\n  has_order 1.\n  \nTheorem singularity :\n  (forall x : G, x = e) -> singular.\n    unfold singular, has_order.\n    intro all_id.\n    exists (fun (x : G) => 0).\n    intros.\n    repeat split.\n    repeat auto.\n    omega.\n    intro.\n    rewrite (all_id g), (all_id h).\n    reflexivity.\nQed.\n\nEnd Groups.", "meta": {"author": "vtols", "repo": "GroupTheory", "sha": "ed75fa97081da38fbd7240097648dc62e1b8facc", "save_path": "github-repos/coq/vtols-GroupTheory", "path": "github-repos/coq/vtols-GroupTheory/GroupTheory-ed75fa97081da38fbd7240097648dc62e1b8facc/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7303469760266508}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2019   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Reals.Rtrigo_def.\nRequire Reals.Rpower.\nRequire BuiltIn.\nRequire real.Real.\n\nImport Rtrigo_def.\nImport Rpower.\n\n(* Why3 comment *)\n(* exp is replaced with (Reals.Rtrigo_def.exp x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Exp_zero : ((Reals.Rtrigo_def.exp 0%R) = 1%R).\nexact exp_0.\nQed.\n\nRequire Import Exp_prop.\n\n(* Why3 goal *)\nLemma Exp_sum :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R),\n  ((Reals.Rtrigo_def.exp (x + y)%R) =\n   ((Reals.Rtrigo_def.exp x) * (Reals.Rtrigo_def.exp y))%R).\nexact exp_plus.\nQed.\n\n(* Why3 comment *)\n(* log is replaced with (Reals.Rpower.ln x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Log_one : ((Reals.Rpower.ln 1%R) = 0%R).\nexact ln_1.\nQed.\n\n(* Why3 goal *)\nLemma Log_mul :\n  forall (x:Reals.Rdefinitions.R) (y:Reals.Rdefinitions.R),\n  (0%R < x)%R /\\ (0%R < y)%R ->\n  ((Reals.Rpower.ln (x * y)%R) =\n   ((Reals.Rpower.ln x) + (Reals.Rpower.ln y))%R).\nintros x y (Hx,Hy).\nnow apply ln_mult.\nQed.\n\n(* Why3 goal *)\nLemma Log_exp :\n  forall (x:Reals.Rdefinitions.R),\n  ((Reals.Rpower.ln (Reals.Rtrigo_def.exp x)) = x).\nexact ln_exp.\nQed.\n\n(* Why3 goal *)\nLemma Exp_log :\n  forall (x:Reals.Rdefinitions.R), (0%R < x)%R ->\n  ((Reals.Rtrigo_def.exp (Reals.Rpower.ln x)) = x).\nexact exp_ln.\nQed.\n\n(* Why3 assumption *)\nDefinition log2 (x:Reals.Rdefinitions.R) : Reals.Rdefinitions.R :=\n  ((Reals.Rpower.ln x) / (Reals.Rpower.ln 2%R))%R.\n\n(* Why3 assumption *)\nDefinition log10 (x:Reals.Rdefinitions.R) : Reals.Rdefinitions.R :=\n  ((Reals.Rpower.ln x) / (Reals.Rpower.ln 10%R))%R.\n\n", "meta": {"author": "schrodibear", "repo": "why3", "sha": "9f8eb767380987a28e43b81729ae1d682363bb49", "save_path": "github-repos/coq/schrodibear-why3", "path": "github-repos/coq/schrodibear-why3/why3-9f8eb767380987a28e43b81729ae1d682363bb49/lib/coq/real/ExpLog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.730346969059957}}
{"text": "\nRequire Import\n        Coq.QArith.QArith CoRN.model.Zmod.ZGcd\n        CoRN.model.totalorder.QposMinMax\n        CoRN.stdlib_omissions.Q.\nSet Automatic Introduction.\n\nOpen Scope Q_scope.\n\nDefinition Qgcd (a b: Q): Q :=\n  Zgcd_nat (Qnum a * Qden b) (Qnum b * Qden a) # (Qden a * Qden b).\n\nLemma Qgcd_sym (a b: Q): Qgcd a b = Qgcd b a.\nProof.\n unfold Qgcd. intros. rewrite Zgcd_nat_sym. rewrite Pmult_comm. reflexivity.\nQed.\n\nLemma Qgcd_divides (a b: Q): exists c: Z, inject_Z c * Qgcd a b == a.\nProof.\n revert a b.\n intros [an ad] [bn bd].\n unfold Qgcd. simpl.\n destruct (Zgcd_nat_divides (an * bd) (bn * ad)) as [c E].\n exists c.\n unfold Qmult, Qeq. simpl.\n rewrite E, Zpos_mult_morphism.\n ring.\nQed.\n\nLemma Qgcd_nonneg a b: 0 <= Qgcd a b.\nProof.\n revert a b.\n intros [an ad] [bn bd]. simpl. unfold Qle. simpl. auto with *.\nQed.\n\n#[global]\nHint Immediate Qgcd_nonneg.\n\nProgram Definition Qcd_pos: Qpos -> Qpos -> Qpos := Qgcd.\n\nNext Obligation. Proof with auto.\n simpl.\n destruct (Qle_lt_or_eq 0 _ (Qgcd_nonneg (proj1_sig x) (proj1_sig x0))) as [| B]...\n exfalso.\n destruct x.\n destruct (Qgcd_divides x (proj1_sig x0)) as [? E]. simpl in *.\n revert q.\n rewrite <- E, <- B, Qmult_0_r.\n apply Qlt_irrefl.\nQed.\n\nLemma Qgcd_pos_divides (a b: Qpos):\n  exists c: positive, inject_Z c * proj1_sig (Qcd_pos a b) == proj1_sig a.\nProof with auto with *.\n revert a b.\n intros [a ap] [b bp].\n simpl.\n destruct (Qgcd_divides a b) as [x E].\n destruct x.\n   exfalso.\n   ring_simplify in E.\n   revert ap. rewrite E. apply Qlt_irrefl.\n  exists p...\n exfalso.\n rewrite <- E in ap.\n apply (Qlt_irrefl 0).\n apply Qlt_le_trans with (inject_Z (Zneg p) * Qgcd a b)...\n rewrite Qmult_comm.\n apply Qmult_nonneg_nonpos...\nQed.\n\nLemma Qpos_gcd3 (a b c: Qpos):\n  exists g: Qpos,\n  exists i: positive, inject_Z i * proj1_sig g == proj1_sig a /\\\n  exists j: positive, inject_Z j * proj1_sig g == proj1_sig b /\\\n  exists k: positive, inject_Z k * proj1_sig g == proj1_sig c.\nProof with auto.\n intros.\n exists (Qcd_pos a (Qcd_pos b c)).\n destruct (Qgcd_pos_divides b c) as [x E].\n destruct (Qgcd_pos_divides c b) as [x0 F].\n simpl in F.\n rewrite Qgcd_sym in F.\n change (inject_Z x0 * proj1_sig (Qcd_pos b c) == proj1_sig c) in F.\n revert E F.\n generalize (Qcd_pos b c).\n intros.\n destruct (Qgcd_pos_divides a q) as [x1 G].\n destruct (Qgcd_pos_divides q a) as [x2 H].\n simpl in H.\n rewrite Qgcd_sym in H.\n change (inject_Z x2 * proj1_sig (Qcd_pos a q) == proj1_sig q) in H.\n exists x1.\n revert G H.\n generalize (Qcd_pos a q).\n split...\n exists (x * x2)%positive.\n split.\n  rewrite Q.Pmult_Qmult.\n  rewrite <- Qmult_assoc.\n  rewrite H...\n exists (x0 * x2)%positive.\n rewrite Q.Pmult_Qmult.\n rewrite <- Qmult_assoc.\n rewrite H...\nQed.\n", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/util/Qgcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7302837745169504}}
{"text": "Require Import ZArith Zpow_facts.\n\nOpen Scope Z_scope.\n\nFixpoint plength (p: positive) : positive :=\n  match p with \n    xH => xH\n  | xO p1 => Psucc (plength p1)\n  | xI p1 => Psucc (plength p1)\n  end.\n\nTheorem plength_correct: forall p, (Zpos p < 2 ^ Zpos (plength p))%Z.\nassert (F: (forall p, 2 ^ (Zpos (Psucc p)) = 2 * 2 ^ Zpos p)%Z).\nintros p; replace (Zpos (Psucc p)) with (1 + Zpos p)%Z.\nrewrite Zpower_exp; auto with zarith.\nred; intros; discriminate.\nrewrite Zpos_succ_morphism; unfold Zsucc; auto with zarith.\nintros p; elim p; simpl plength; auto.\nintros p1 Hp1; rewrite F; repeat rewrite Zpos_xI.\nassert (tmp: (forall p, 2 * p = p + p)%Z); \n  try repeat rewrite tmp; auto with zarith.\nintros p1 Hp1; rewrite F; rewrite (Zpos_xO p1).\nassert (tmp: (forall p, 2 * p = p + p)%Z); \n  try repeat rewrite tmp; auto with zarith.\nrewrite Zpower_1_r; auto with zarith.\nQed.\n\nTheorem plength_pred_correct: forall p, (Zpos p <= 2 ^ Zpos (plength (Ppred p)))%Z.\nintros p; case (Psucc_pred p); intros H1.\nsubst; simpl plength.\nrewrite Zpower_1_r; auto with zarith.\npattern p at 1; rewrite <- H1.\nrewrite Zpos_succ_morphism; unfold Zsucc; auto with zarith.\ngeneralize (plength_correct (Ppred p)); auto with zarith.\nQed.\n\nDefinition Pdiv p q :=\n  match Zdiv (Zpos p) (Zpos q) with\n    Zpos q1 => match (Zpos p) - (Zpos q) * (Zpos q1) with\n                 Z0 => q1\n               | _ => (Psucc q1)\n               end\n  |  _ => xH\n  end.\n\nTheorem Pdiv_le: forall p q,\n  Zpos p <= Zpos q * Zpos (Pdiv p q).\nintros p q.\nunfold Pdiv.\nassert (H1: Zpos q > 0); auto with zarith.\nassert (H1b: Zpos p >= 0).\n  red; intros; discriminate.\ngeneralize (Z_div_ge0 (Zpos p) (Zpos q) H1 H1b).\ngeneralize (Z_div_mod_eq (Zpos p) (Zpos q) H1); case Zdiv.\n  intros HH _; rewrite HH; rewrite Zmult_0_r; rewrite Zmult_1_r; simpl.\ncase (Z_mod_lt (Zpos p) (Zpos q) H1); auto with zarith.\nintros q1 H2.\nreplace (Zpos p - Zpos q * Zpos q1) with (Zpos p mod Zpos q).\n  2: pattern (Zpos p) at 2; rewrite H2; auto with zarith.\ngeneralize H2 (Z_mod_lt (Zpos p) (Zpos q) H1); clear H2; \n  case Zmod.\n  intros HH _; rewrite HH; auto with zarith.\n  intros r1 HH (_,HH1); rewrite HH; rewrite Zpos_succ_morphism.\n  unfold Zsucc; rewrite Zmult_plus_distr_r; auto with zarith.\n  intros r1 _ (HH,_); case HH; auto.\nintros q1 HH; rewrite HH.\nunfold Zge; simpl Zcompare; intros HH1; case HH1; auto.\nQed.\n\nDefinition is_one p := match p with xH => true | _ => false end.\n\nTheorem is_one_one: forall p, is_one p = true -> p = xH.\nintros p; case p; auto; intros p1 H1; discriminate H1.\nQed.\n\nDefinition get_height digits p :=\n  let r := Pdiv p digits in\n   if is_one r then xH else Psucc (plength (Ppred r)).\n\nTheorem get_height_correct:\n  forall digits N,\n   Zpos N <= Zpos digits * (2 ^ (Zpos (get_height digits N) -1)).\nintros digits N.\nunfold get_height.\nassert (H1 := Pdiv_le N digits).\ncase_eq (is_one (Pdiv N digits)); intros H2.\nrewrite (is_one_one _ H2) in H1.\nrewrite Zmult_1_r in H1.\nchange (2^(1-1))%Z with 1; rewrite Zmult_1_r; auto.\nclear H2.\napply Zle_trans with (1 := H1).\napply Zmult_le_compat_l; auto with zarith.\nrewrite Zpos_succ_morphism; unfold Zsucc.\nrewrite Zplus_comm; rewrite Zminus_plus.\napply plength_pred_correct.\nQed.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/coqprime/src/Coqprime/num/Bits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7302837689590942}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice.\nFrom mathcomp Require Import fintype finfun bigop finset fingroup perm order.\nFrom mathcomp Require Import div prime binomial ssralg finalg zmodp matrix.\n\n(*****************************************************************************)\n(* In this file we develop the rank and row space theory of matrices, based  *)\n(* on an extended Gaussian elimination procedure similar to LUP              *)\n(* decomposition. This provides us with a concrete but generic model of      *)\n(* finite dimensional vector spaces and F-algebras, in which vectors, linear *)\n(* functions, families, bases, subspaces, ideals and subrings are all        *)\n(* represented using matrices. This model can be used as a foundation for    *)\n(* the usual theory of abstract linear algebra, but it can also be used to   *)\n(* develop directly substantial theories, such as the theory of finite group *)\n(* linear representation.                                                    *)\n(*   Here we define the following concepts and notations:                    *)\n(* Gaussian_elimination A == a permuted triangular decomposition (L, U, r)   *)\n(*                   of A, with L a column permutation of a lower triangular *)\n(*                   invertible matrix, U a row permutation of an upper      *)\n(*                   triangular invertible matrix, and r the rank of A, all  *)\n(*                   satisfying the identity L *m pid_mx r *m U = A.         *)\n(*        \\rank A == the rank of A.                                          *)\n(*    row_free A <=> the rows of A are linearly free (i.e., the rank and     *)\n(*                   height of A are equal).                                 *)\n(*    row_full A <=> the row-space of A spans all row-vectors (i.e., the     *)\n(*                   rank and width of A are equal).                         *)\n(*    col_ebase A == the extended column basis of A (the first matrix L      *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*    row_ebase A == the extended row base of A (the second matrix U         *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*     col_base A == a basis for the columns of A: a row-full matrix         *)\n(*                   consisting of the first \\rank A columns of col_ebase A. *)\n(*     row_base A == a basis for the rows of A: a row-free matrix consisting *)\n(*                   of the first \\rank A rows of row_ebase A.               *)\n(*       pinvmx A == a partial inverse for A in its row space (or on its     *)\n(*                   column space, equivalently). In particular, if u is a   *)\n(*                   row vector in the row_space of A, then u *m pinvmx A is *)\n(*                   the row vector of the coefficients of a decomposition   *)\n(*                   of u as a sub of rows of A.                             *)\n(*        kermx A == the row kernel of A : a square matrix whose row space   *)\n(*                   consists of all u such that u *m A = 0 (it consists of  *)\n(*                   the inverse of col_ebase A, with the top \\rank A rows   *)\n(*                   zeroed out). Also, kermx A is a partial right inverse   *)\n(*                   to col_ebase A, in the row space anihilated by A.       *)\n(*      cokermx A == the cokernel of A : a square matrix whose column space  *)\n(*                   consists of all v such that A *m v = 0 (it consists of  *)\n(*                   the inverse of row_ebase A, with the leftmost \\rank A   *)\n(*                   columns zeroed out).                                    *)\n(*   maxrankfun A == injective function f so that rowsub f A is a submatrix  *)\n(*                   of A with the same rank as A.                           *)\n(* fullrankfun fA == injective function f so that rowsub f A is row full,    *)\n(*                   where fA is a proof of row_full A                       *)\n(* eigenvalue g a <=> a is an eigenvalue of the square matrix g.             *)\n(* eigenspace g a == a square matrix whose row space is the eigenspace of    *)\n(*                   the eigenvalue a of g (or 0 if a is not an eigenvalue). *)\n(* We use a different scope %MS for matrix row-space set-like operations; to *)\n(* avoid confusion, this scope should not be opened globally. Note that the  *)\n(* the arguments of \\rank _ and the operations below have default scope %MS. *)\n(*    (A <= B)%MS <=> the row-space of A is included in the row-space of B.  *)\n(*                   We test for this by testing if cokermx B anihilates A.  *)\n(*     (A < B)%MS <=> the row-space of A is properly included in the         *)\n(*                   row-space of B.                                         *)\n(*  (A <= B <= C)%MS == (A <= B)%MS && (B <= C)%MS, and similarly for        *)\n(*                   (A < B <= C)%MS, (A < B <= C)%MS and (A < B < C)%MS.    *)\n(*    (A == B)%MS == (A <= B <= A)%MS (A and B have the same row-space).     *)\n(*   (A :=: B)%MS == A and B behave identically wrt. \\rank and <=. This      *)\n(*                   triple rewrite rule is the Prop version of (A == B)%MS. *)\n(*                   Note that :=: cannot be treated as a setoid-style       *)\n(*                   Equivalence because its arguments can have different    *)\n(*                   types: A and B need not have the same number of rows,   *)\n(*                   and often don't (e.g., in row_base A :=: A).            *)\n(*       <<A>>%MS == a square matrix with the same row-space as A; <<A>>%MS  *)\n(*                   is a canonical representation of the subspace generated *)\n(*                   by A, viewed as a list of row-vectors: if (A == B)%MS,  *)\n(*                   then <<A>>%MS = <<B>>%MS.                               *)\n(*     (A + B)%MS == a square matrix whose row-space is the sum of the       *)\n(*                   row-spaces of A and B; thus (A + B == col_mx A B)%MS.   *)\n(*  (\\sum_i <expr i>)%MS == the \"big\" version of (_ + _)%MS; as the latter   *)\n(*                   has a canonical abelian monoid structure, most generic  *)\n(*                   bigop lemmas apply (the other bigop indexing notations  *)\n(*                   are also defined).                                      *)\n(*   (A :&: B)%MS == a square matrix whose row-space is the intersection of  *)\n(*                   the row-spaces of A and B.                              *)\n(*  (\\bigcap_i <expr i>)%MS == the \"big\" version of (_ :&: _)%MS, which also *)\n(*                   has a canonical abelian monoid structure.               *)\n(*         A^C%MS == a square matrix whose row-space is a complement to the  *)\n(*                   the row-space of A (it consists of row_ebase A with the *)\n(*                   top \\rank A rows zeroed out).                           *)\n(*   (A :\\: B)%MS == a square matrix whose row-space is a complement of the  *)\n(*                   the row-space of (A :&: B)%MS in the row-space of A.    *)\n(*                   We have (A :\\: B := A :&: (capmx_gen A B)^C)%MS, where  *)\n(*                   capmx_gen A B is a rectangular matrix equivalent to     *)\n(*                   (A :&: B)%MS, i.e., (capmx_gen A B == A :&: B)%MS.      *)\n(*    proj_mx A B == a square matrix that projects (A + B)%MS onto A         *)\n(*                   parallel to B, when (A :&: B)%MS = 0 (A and B must also *)\n(*                   be square).                                             *)\n(*     mxdirect S == the sum expression S is a direct sum. This is a NON     *)\n(*                   EXTENSIONAL notation: the exact boolean expression is   *)\n(*                   inferred from the syntactic form of S (expanding        *)\n(*                   definitions, however); both (\\sum_(i | _) _)%MS and     *)\n(*                   (_ + _)%MS sums are recognized. This construct uses a   *)\n(*                   variant of the reflexive (\"quote\") canonical structure, *)\n(*                   mxsum_expr. The structure also recognizes sums of       *)\n(*                   matrix ranks, so that lemmas concerning the rank of     *)\n(*                   direct sums can be used bidirectionally.                *)\n(* stablemx V f <=> the matrix f represents an endomorphism that preserves V *)\n(*               := (V *m f <= V)%MS                                         *)\n(* The next set of definitions let us represent F-algebras using matrices:   *)\n(*   'A[F]_(m, n) == the type of matrices encoding (sub)algebras of square   *)\n(*                   n x n matrices, via mxvec; as in the matrix type        *)\n(*                   notation, m and F can be omitted (m defaults to n ^ 2). *)\n(*                := 'M[F]_(m, n ^ 2).                                       *)\n(*   (A \\in R)%MS <=> the square matrix A belongs to the linear set of       *)\n(*                    matrices (most often, a sub-algebra) encoded by the    *)\n(*                    row space of R. This is simply notation, so all the    *)\n(*                    lemmas and rewrite rules for (_ <= _)%MS can apply.    *)\n(*                := (mxvec A <= R)%MS.                                      *)\n(*     (R * S)%MS == a square n^2 x n^2 matrix whose row-space encodes the   *)\n(*                   linear set of n x n matrices generated by the pointwise *)\n(*                   product of the sets of matrices encoded by R and S.     *)\n(*       'C(R)%MS == a square matric encoding the centraliser of the set of  *)\n(*                   square matrices encoded by R.                           *)\n(*     'C_S(R)%MS := (S :&: 'C(R))%MS (the centraliser of R in S).           *)\n(*       'Z(R)%MS == the center of R (i.e., 'C_R(R)%MS).                     *)\n(*  left_mx_ideal R S <=> S is a left ideal for R (R * S <= S)%MS.           *)\n(* right_mx_ideal R S <=> S is a right ideal for R (S * R <= S)%MS.          *)\n(*       mx_ideal R S <=> S is a bilateral ideal for R.                      *)\n(*      mxring_id R e <-> e is an identity element for R (Prop predicate).   *)\n(*    has_mxring_id R <=> R has a nonzero identity element (bool predicate). *)\n(*           mxring R <=> R encodes a nontrivial subring.                    *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDeclare Scope matrix_set_scope.\n\nImport GroupScope.\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nReserved Notation \"\\rank A\" (at level 10, A at level 8, format \"\\rank  A\").\nReserved Notation \"A ^C\"    (at level 8, format \"A ^C\").\n\nNotation \"''A_' ( m , n )\" := 'M_(m, n ^ 2)\n  (at level 8, format \"''A_' ( m ,  n )\") : type_scope.\n\nNotation \"''A_' ( n )\" := 'A_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A_' n\" := 'A_(n)\n  (at level 8, n at next level, format \"''A_' n\") : type_scope.\n\nNotation \"''A' [ F ]_ ( m , n )\" := 'M[F]_(m, n ^ 2)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ ( n )\" := 'A[F]_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ n\" := 'A[F]_(n)\n  (at level 8, n at level 2, only parsing) : type_scope.\n\nDelimit Scope matrix_set_scope with MS.\n\nLocal Notation simp := (Monoid.Theory.simpm, oppr0).\n\n(*****************************************************************************)\n(******************** Rank and row-space theory ******************************)\n(*****************************************************************************)\n\nSection RowSpaceTheory.\n\nVariable F : fieldType.\nImplicit Types m n p r : nat.\n\nLocal Notation \"''M_' ( m , n )\" := 'M[F]_(m, n) : type_scope.\nLocal Notation \"''M_' n\" := 'M[F]_(n, n) : type_scope.\n\n(* Decomposition with double pivoting; computes the rank, row and column  *)\n(* images, kernels, and complements of a matrix.                          *)\n\nFixpoint Gaussian_elimination {m n} : 'M_(m, n) -> 'M_m * 'M_n * nat :=\n  match m, n with\n  | _.+1, _.+1 => fun A : 'M_(1 + _, 1 + _) =>\n    if [pick ij | A ij.1 ij.2 != 0] is Some (i, j) then\n      let a := A i j in let A1 := xrow i 0 (xcol j 0 A) in\n      let u := ursubmx A1 in let v := a^-1 *: dlsubmx A1 in\n      let: (L, U, r) := Gaussian_elimination (drsubmx A1 - v *m u) in\n      (xrow i 0 (block_mx 1 0 v L), xcol j 0 (block_mx a%:M u 0 U), r.+1)\n    else (1%:M, 1%:M, 0%N)\n  | _, _ => fun _ => (1%:M, 1%:M, 0%N)\n  end.\n\nSection Defs.\n\nVariables (m n : nat) (A : 'M_(m, n)).\n\nFact Gaussian_elimination_key : unit. Proof. by []. Qed.\n\nLet LUr := locked_with Gaussian_elimination_key (@Gaussian_elimination) m n A.\n\nDefinition col_ebase := LUr.1.1.\nDefinition row_ebase := LUr.1.2.\nDefinition mxrank := if [|| m == 0 | n == 0]%N then 0%N else LUr.2.\n\nDefinition row_free := mxrank == m.\nDefinition row_full := mxrank == n.\n\nDefinition row_base : 'M_(mxrank, n) := pid_mx mxrank *m row_ebase.\nDefinition col_base : 'M_(m, mxrank) := col_ebase *m pid_mx mxrank.\n\nDefinition complmx : 'M_n := copid_mx mxrank *m row_ebase.\nDefinition kermx : 'M_m := copid_mx mxrank *m invmx col_ebase.\nDefinition cokermx : 'M_n := invmx row_ebase *m copid_mx mxrank.\n\nDefinition pinvmx : 'M_(n, m) :=\n  invmx row_ebase *m pid_mx mxrank *m invmx col_ebase.\n\nEnd Defs.\n\nArguments mxrank {m%N n%N} A%MS.\nLocal Notation \"\\rank A\" := (mxrank A) : nat_scope.\nArguments complmx {m%N n%N} A%MS.\nLocal Notation \"A ^C\" := (complmx A) : matrix_set_scope.\n\nDefinition submx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  A *m cokermx B == 0).\nFact submx_key : unit. Proof. by []. Qed.\nDefinition submx := locked_with submx_key submx_def.\nCanonical submx_unlockable := [unlockable fun submx].\n\nArguments submx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A <= B\" := (submx A B) : matrix_set_scope.\nLocal Notation \"A <= B <= C\" := ((A <= B) && (B <= C))%MS : matrix_set_scope.\nLocal Notation \"A == B\" := (A <= B <= A)%MS : matrix_set_scope.\n\nDefinition ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  (A <= B)%MS && ~~ (B <= A)%MS.\nArguments ltmx {m1%N m2%N n%N} A%MS B%MS.\nLocal Notation \"A < B\" := (ltmx A B) : matrix_set_scope.\n\nDefinition eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  prod (\\rank A = \\rank B)\n       (forall m3 (C : 'M_(m3, n)),\n            ((A <= C) = (B <= C)) * ((C <= A) = (C <= B)))%MS.\nArguments eqmx {m1%N m2%N n%N} A%MS B%MS.\nLocal Notation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\n\nNotation stablemx V f := (V%MS *m f%R <= V%MS)%MS.\n\nSection LtmxIdentities.\n\nVariables (m1 m2 n : nat) (A : 'M_(m1, n)) (B : 'M_(m2, n)).\n\nLemma ltmxE : (A < B)%MS = ((A <= B)%MS && ~~ (B <= A)%MS). Proof. by []. Qed.\n\nLemma ltmxW : (A < B)%MS -> (A <= B)%MS. Proof. by case/andP. Qed.\n\nLemma ltmxEneq : (A < B)%MS = (A <= B)%MS && ~~ (A == B)%MS.\nProof. by apply: andb_id2l => ->. Qed.\n\nLemma submxElt : (A <= B)%MS = (A == B)%MS || (A < B)%MS.\nProof. by rewrite -andb_orr orbN andbT. Qed.\n\nEnd LtmxIdentities.\n\n(* The definition of the row-space operator is rigged to return the identity  *)\n(* matrix for full matrices. To allow for further tweaks that will make the   *)\n(* row-space intersection operator strictly commutative and monoidal, we      *)\n(* slightly generalize some auxiliary definitions: we parametrize the         *)\n(* \"equivalent subspace and identity\" choice predicate equivmx by a boolean   *)\n(* determining whether the matrix should be the identity (so for genmx A its  *)\n(* value is row_full A), and introduce a \"quasi-identity\" predicate qidmx     *)\n(* that selects non-square full matrices along with the identity matrix 1%:M  *)\n(* (this does not affect genmx, which chooses a square matrix).               *)\n(*   The choice witness for genmx A is either 1%:M for a row-full A, or else  *)\n(* row_base A padded with null rows.                                          *)\nLet qidmx m n (A : 'M_(m, n)) :=\n  if m == n then A == pid_mx n else row_full A.\nLet equivmx m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  (B == A)%MS && (qidmx B == idA).\nLet equivmx_spec m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  prod (B :=: A)%MS (qidmx B = idA).\nDefinition genmx_witness m n (A : 'M_(m, n)) : 'M_n :=\n  if row_full A then 1%:M else pid_mx (\\rank A) *m row_ebase A.\nDefinition genmx_def := idfun (fun m n (A : 'M_(m, n)) =>\n   choose (equivmx A (row_full A)) (genmx_witness A) : 'M_n).\nFact genmx_key : unit. Proof. by []. Qed.\nDefinition genmx := locked_with genmx_key genmx_def.\nCanonical genmx_unlockable := [unlockable fun genmx].\nLocal Notation \"<< A >>\" := (genmx A) : matrix_set_scope.\n\n(* The setwise sum is tweaked so that 0 is a strict identity element for      *)\n(* square matrices, because this lets us use the bigop component. As a result *)\n(* setwise sum is not quite strictly extensional.                             *)\nLet addsmx_nop m n (A : 'M_(m, n)) := conform_mx <<A>>%MS A.\nDefinition addsmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if A == 0 then addsmx_nop B else if B == 0 then addsmx_nop A else\n  <<col_mx A B>>%MS : 'M_n).\nFact addsmx_key : unit. Proof. by []. Qed.\nDefinition addsmx := locked_with addsmx_key addsmx_def.\nCanonical addsmx_unlockable := [unlockable fun addsmx].\nArguments addsmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A + B\" := (addsmx A B) : matrix_set_scope.\nLocal Notation \"\\sum_ ( i | P ) B\" := (\\big[addsmx/0]_(i | P) B%MS)\n  : matrix_set_scope.\nLocal Notation \"\\sum_ ( i <- r | P ) B\" := (\\big[addsmx/0]_(i <- r | P) B%MS)\n  : matrix_set_scope.\n\n(* The set intersection is similarly biased so that the identity matrix is a  *)\n(* strict identity. This is somewhat more delicate than for the sum, because  *)\n(* the test for the identity is non-extensional. This forces us to actually   *)\n(* bias the choice operator so that it does not accidentally map an           *)\n(* intersection of non-identity matrices to 1%:M; this would spoil            *)\n(* associativity: if B :&: C = 1%:M but B and C are not identity, then for a  *)\n(* square matrix A we have A :&: (B :&: C) = A != (A :&: B) :&: C in general. *)\n(* To complicate matters there may not be a square non-singular matrix        *)\n(* different than 1%:M, since we could be dealing with 'M['F_2]_1. We         *)\n(* sidestep the issue by making all non-square row-full matrices identities,  *)\n(* and choosing a normal representative that preserves the qidmx property.    *)\n(* Thus A :&: B = 1%:M iff A and B are both identities, and this suffices for *)\n(* showing that associativity is strict.                                      *)\nLet capmx_witness m n (A : 'M_(m, n)) :=\n  if row_full A then conform_mx 1%:M A else <<A>>%MS.\nLet capmx_norm m n (A : 'M_(m, n)) :=\n  choose (equivmx A (qidmx A)) (capmx_witness A).\nLet capmx_nop m n (A : 'M_(m, n)) := conform_mx (capmx_norm A) A.\nDefinition capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  lsubmx (kermx (col_mx A B)) *m A.\nDefinition capmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if qidmx A then capmx_nop B else\n  if qidmx B then capmx_nop A else\n  if row_full B then capmx_norm A else capmx_norm (capmx_gen A B) : 'M_n).\nFact capmx_key : unit. Proof. by []. Qed.\nDefinition capmx := locked_with capmx_key capmx_def.\nCanonical capmx_unlockable := [unlockable fun capmx].\nArguments capmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nLocal Notation \"\\bigcap_ ( i | P ) B\" := (\\big[capmx/1%:M]_(i | P) B)\n  : matrix_set_scope.\n\nDefinition diffmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  <<capmx_gen A (capmx_gen A B)^C>>%MS : 'M_n).\nFact diffmx_key : unit. Proof. by []. Qed.\nDefinition diffmx := locked_with diffmx_key diffmx_def.\nCanonical diffmx_unlockable := [unlockable fun diffmx].\nArguments diffmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\n\nDefinition proj_mx n (U V : 'M_n) : 'M_n := pinvmx (col_mx U V) *m col_mx U 0.\n\nLocal Notation GaussE := Gaussian_elimination.\n\nFact mxrankE m n (A : 'M_(m, n)) : \\rank A = (GaussE A).2.\nProof. by rewrite /mxrank unlock /=; case: m n A => [|m] [|n]. Qed.\n\nLemma rank_leq_row m n (A : 'M_(m, n)) : \\rank A <= m.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma row_leq_rank m n (A : 'M_(m, n)) : (m <= \\rank A) = row_free A.\nProof. by rewrite /row_free eqn_leq rank_leq_row. Qed.\n\nLemma rank_leq_col m n (A : 'M_(m, n)) : \\rank A <= n.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma col_leq_rank m n (A : 'M_(m, n)) : (n <= \\rank A) = row_full A.\nProof. by rewrite /row_full eqn_leq rank_leq_col. Qed.\n\nLemma eq_row_full m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> row_full A = row_full B.\nProof. by rewrite /row_full => ->. Qed.\n\nLet unitmx1F := @unitmx1 F.\nLemma row_ebase_unit m n (A : 'M_(m, n)) : row_ebase A \\in unitmx.\nProof.\nrewrite /row_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] /= nzAij | //=]; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uU.\nrewrite unitmxE xcolE det_mulmx (@det_ublock _ 1) det_scalar1 !unitrM.\nby rewrite unitfE nzAij -!unitmxE uU unitmx_perm.\nQed.\n\nLemma col_ebase_unit m n (A : 'M_(m, n)) : col_ebase A \\in unitmx.\nProof.\nrewrite /col_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] _|] //=; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uL.\nrewrite unitmxE xrowE det_mulmx (@det_lblock _ 1) det1 mul1r unitrM.\nby rewrite -unitmxE unitmx_perm.\nQed.\nHint Resolve rank_leq_row rank_leq_col row_ebase_unit col_ebase_unit : core.\n\nLemma mulmx_ebase m n (A : 'M_(m, n)) :\n  col_ebase A *m pid_mx (\\rank A) *m row_ebase A = A.\nProof.\nrewrite mxrankE /col_ebase /row_ebase unlock.\nelim: m n A => [n A | m IHm]; first by rewrite [A]flatmx0 [_ *m _]flatmx0.\ncase=> [A | n]; first by rewrite [_ *m _]thinmx0 [A]thinmx0.\nrewrite -(add1n m) -?(add1n n) => A /=.\ncase: pickP => [[i0 j0] | A0] /=; last first.\n  apply/matrixP=> i j; rewrite pid_mx_0 mulmx0 mul0mx mxE.\n  by move/eqP: (A0 (i, j)).\nset a := A i0 j0 => nz_a; set A1 := xrow _ _ _.\nset u := ursubmx _; set v := _ *: _; set B : 'M_(m, n) := _ - _.\nmove: (rank_leq_col B) (rank_leq_row B) {IHm}(IHm n B); rewrite mxrankE.\ncase: (GaussE B) => [[L U] r] /= r_m r_n defB.\nhave ->: pid_mx (1 + r) = block_mx 1 0 0 (pid_mx r) :> 'M[F]_(1 + m, 1 + n).\n  rewrite -(subnKC r_m) -(subnKC r_n) pid_mx_block -col_mx0 -row_mx0.\n  by rewrite block_mxA castmx_id col_mx0 row_mx0 -scalar_mx_block -pid_mx_block.\nrewrite xcolE xrowE mulmxA -xcolE -!mulmxA.\nrewrite !(addr0, add0r, mulmx0, mul0mx, mulmx_block, mul1mx) mulmxA defB.\nrewrite addrC subrK mul_mx_scalar scalerA divff // scale1r.\nhave ->: a%:M = ulsubmx A1 by rewrite [_ A1]mx11_scalar !mxE !lshift0 !tpermR.\nrewrite submxK /A1 xrowE !xcolE -!mulmxA mulmxA -!perm_mxM !tperm2 !perm_mx1.\nby rewrite mulmx1 mul1mx.\nQed.\n\nLemma mulmx_base m n (A : 'M_(m, n)) : col_base A *m row_base A = A.\nProof. by rewrite mulmxA -[col_base A *m _]mulmxA pid_mx_id ?mulmx_ebase. Qed.\n\nLemma mulmx1_min_rank r m n (A : 'M_(m, n)) M N :\n  M *m A *m N = 1%:M :> 'M_r -> r <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) mulmxA -mulmxA; move/mulmx1_min. Qed.\nArguments mulmx1_min_rank [r m n A].\n\nLemma mulmx_max_rank r m n (M : 'M_(m, r)) (N : 'M_(r, n)) :\n  \\rank (M *m N) <= r.\nProof.\nset MN := M *m N; set rMN := \\rank _.\npose L : 'M_(rMN, m) := pid_mx rMN *m invmx (col_ebase MN).\npose U : 'M_(n, rMN) := invmx (row_ebase MN) *m pid_mx rMN.\nsuffices: L *m M *m (N *m U) = 1%:M by apply: mulmx1_min.\nrewrite mulmxA -(mulmxA L) -[M *m N]mulmx_ebase -/MN.\nby rewrite !mulmxA mulmxKV // mulmxK // !pid_mx_id /rMN ?pid_mx_1.\nQed.\nArguments mulmx_max_rank [r m n].\n\nLemma mxrank_tr m n (A : 'M_(m, n)) : \\rank A^T = \\rank A.\nProof.\napply/eqP; rewrite eqn_leq -{3}[A]trmxK -{1}(mulmx_base A) -{1}(mulmx_base A^T).\nby rewrite !trmx_mul !mulmx_max_rank.\nQed.\n\nLemma mxrank_add m n (A B : 'M_(m, n)) : \\rank (A + B)%R <= \\rank A + \\rank B.\nProof.\nby rewrite -{1}(mulmx_base A) -{1}(mulmx_base B) -mul_row_col mulmx_max_rank.\nQed.\n\nLemma mxrankM_maxl m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) -mulmxA mulmx_max_rank. Qed.\n\nLemma mxrankM_maxr m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank B.\nProof. by rewrite -mxrank_tr -(mxrank_tr B) trmx_mul mxrankM_maxl. Qed.\n\nLemma mxrank_scale m n a (A : 'M_(m, n)) : \\rank (a *: A) <= \\rank A.\nProof. by rewrite -mul_scalar_mx mxrankM_maxr. Qed.\n\nLemma mxrank_scale_nz m n a (A : 'M_(m, n)) :\n   a != 0 -> \\rank (a *: A) = \\rank A.\nProof.\nmove=> nza; apply/eqP; rewrite eqn_leq -{3}[A]scale1r -(mulVf nza).\nby rewrite -scalerA !mxrank_scale.\nQed.\n\nLemma mxrank_opp m n (A : 'M_(m, n)) : \\rank (- A) = \\rank A.\nProof. by rewrite -scaleN1r mxrank_scale_nz // oppr_eq0 oner_eq0. Qed.\n\nLemma mxrank0 m n : \\rank (0 : 'M_(m, n)) = 0%N.\nProof. by apply/eqP; rewrite -leqn0 -(@mulmx0 _ m 0 n 0) mulmx_max_rank. Qed.\n\nLemma mxrank_eq0 m n (A : 'M_(m, n)) : (\\rank A == 0%N) = (A == 0).\nProof.\napply/eqP/eqP=> [rA0 | ->{A}]; last exact: mxrank0.\nmove: (col_base A) (row_base A) (mulmx_base A); rewrite rA0 => Ac Ar <-.\nby rewrite [Ac]thinmx0 mul0mx.\nQed.\n\nLemma mulmx_coker m n (A : 'M_(m, n)) : A *m cokermx A = 0.\nProof.\nby rewrite -{1}[A]mulmx_ebase -!mulmxA mulKVmx // mul_pid_mx_copid ?mulmx0.\nQed.\n\nLemma submxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS = (A *m cokermx B == 0).\nProof. by rewrite unlock. Qed.\n\nLemma mulmxKpV m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> A *m pinvmx B *m B = A.\nProof.\nrewrite submxE !mulmxA mulmxBr mulmx1 subr_eq0 => /eqP defA.\nrewrite -{4}[B]mulmx_ebase -!mulmxA mulKmx //.\nby rewrite (mulmxA (pid_mx _)) pid_mx_id // !mulmxA -{}defA mulmxKV.\nQed.\n\nLemma mulmxVp m n (A : 'M[F]_(m, n)) : row_free A -> A *m pinvmx A = 1%:M.\nProof.\nmove=> fA; rewrite -[X in X *m _]mulmx_ebase !mulmxA mulmxK ?row_ebase_unit//.\nrewrite -[X in X *m _]mulmxA mul_pid_mx !minnn (minn_idPr _) ?rank_leq_col//.\nby rewrite (eqP fA) pid_mx_1 mulmx1 mulmxV ?col_ebase_unit.\nQed.\n\nLemma mulmxKp p m n (B : 'M[F]_(m, n)) : row_free B ->\n  cancel ((@mulmx _ p _ _)^~ B) (mulmx^~ (pinvmx B)).\nProof. by move=> ? A; rewrite -mulmxA mulmxVp ?mulmx1. Qed.\n\nLemma submxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists D, A = D *m B) (A <= B)%MS.\nProof.\napply: (iffP idP) => [/mulmxKpV | [D ->]]; first by exists (A *m pinvmx B).\nby rewrite submxE -mulmxA mulmx_coker mulmx0.\nQed.\nArguments submxP {m1 m2 n A B}.\n\nLemma submx_refl m n (A : 'M_(m, n)) : (A <= A)%MS.\nProof. by rewrite submxE mulmx_coker. Qed.\nHint Resolve submx_refl : core.\n\nLemma submxMl m n p (D : 'M_(m, n)) (A : 'M_(n, p)) : (D *m A <= A)%MS.\nProof. by rewrite submxE -mulmxA mulmx_coker mulmx0. Qed.\n\nLemma submxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A <= B)%MS -> (A *m C <= B *m C)%MS.\nProof. by case/submxP=> D ->; rewrite -mulmxA submxMl. Qed.\n\nLemma mulmx_sub m n1 n2 p (C : 'M_(m, n1)) A (B : 'M_(n2, p)) :\n  (A <= B -> C *m A <= B)%MS.\nProof. by case/submxP=> D ->; rewrite mulmxA submxMl. Qed.\n\nLemma submx_trans m1 m2 m3 n\n                 (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B -> B <= C -> A <= C)%MS.\nProof. by case/submxP=> D ->{A}; apply: mulmx_sub. Qed.\n\nLemma ltmx_sub_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A < B)%MS -> (B <= C)%MS -> (A < C)%MS.\nProof.\ncase/andP=> sAB ltAB sBC; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltAB; apply: submx_trans.\nQed.\n\nLemma sub_ltmx_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B)%MS -> (B < C)%MS -> (A < C)%MS.\nProof.\nmove=> sAB /andP[sBC ltBC]; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltBC => sCA; apply: submx_trans sAB.\nQed.\n\nLemma ltmx_trans m n : transitive (@ltmx m m n).\nProof. by move=> A B C; move/ltmxW; apply: sub_ltmx_trans. Qed.\n\nLemma ltmx_irrefl m n : irreflexive (@ltmx m m n).\nProof. by move=> A; rewrite /ltmx submx_refl andbF. Qed.\n\nLemma sub0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) <= A)%MS.\nProof. by rewrite submxE mul0mx. Qed.\n\nLemma submx0null m1 m2 n (A : 'M[F]_(m1, n)) :\n  (A <= (0 : 'M_(m2, n)))%MS -> A = 0.\nProof. by case/submxP=> D; rewrite mulmx0. Qed.\n\nLemma submx0 m n (A : 'M_(m, n)) : (A <= (0 : 'M_n))%MS = (A == 0).\nProof. by apply/idP/eqP=> [|->]; [apply: submx0null | apply: sub0mx]. Qed.\n\nLemma lt0mx m n (A : 'M_(m, n)) : ((0 : 'M_n) < A)%MS = (A != 0).\nProof. by rewrite /ltmx sub0mx submx0. Qed.\n\nLemma ltmx0 m n (A : 'M[F]_(m, n)) : (A < (0 : 'M_n))%MS = false.\nProof. by rewrite /ltmx sub0mx andbF. Qed.\n\nLemma eqmx0P m n (A : 'M_(m, n)) : reflect (A = 0) (A == (0 : 'M_n))%MS.\nProof. by rewrite submx0 sub0mx andbT; apply: eqP. Qed.\n\nLemma eqmx_eq0 m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (A == 0) = (B == 0).\nProof. by move=> eqAB; rewrite -!submx0 eqAB. Qed.\n\nLemma addmx_sub m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= C)%MS -> (B <= C)%MS -> ((A + B)%R <= C)%MS.\nProof.\nby case/submxP=> A' ->; case/submxP=> B' ->; rewrite -mulmxDl submxMl.\nQed.\n\nLemma rowsub_sub m1 m2 n (f : 'I_m2 -> 'I_m1) (A : 'M_(m1, n)) :\n  (rowsub f A <= A)%MS.\nProof. by rewrite rowsubE mulmx_sub. Qed.\n\nLemma summx_sub m1 m2 n (B : 'M_(m2, n))\n                I (r : seq I) (P : pred I) (A_ : I -> 'M_(m1, n)) :\n  (forall i, P i -> A_ i <= B)%MS -> ((\\sum_(i <- r | P i) A_ i)%R <= B)%MS.\nProof.\nby move=> leAB; elim/big_ind: _ => // [|C D]; [apply/sub0mx | apply/addmx_sub].\nQed.\n\nLemma scalemx_sub m1 m2 n a (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> (a *: A <= B)%MS.\nProof. by case/submxP=> A' ->; rewrite scalemxAl submxMl. Qed.\n\nLemma row_sub m n i (A : 'M_(m, n)) : (row i A <= A)%MS.\nProof. exact: rowsub_sub. Qed.\n\nLemma eq_row_sub m n v (A : 'M_(m, n)) i : row i A = v -> (v <= A)%MS.\nProof. by move <-; rewrite row_sub. Qed.\nArguments eq_row_sub [m n v A].\n\nLemma nz_row_sub m n (A : 'M_(m, n)) : (nz_row A <= A)%MS.\nProof. by rewrite /nz_row; case: pickP => [i|] _; rewrite ?row_sub ?sub0mx. Qed.\n\nLemma row_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall i, row i A <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i|sAB].\n  by apply: submx_trans sAB; apply: row_sub.\nrewrite submxE; apply/eqP/row_matrixP=> i; apply/eqP.\nby rewrite row_mul row0 -submxE.\nQed.\nArguments row_subP {m1 m2 n A B}.\n\nLemma rV_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB v Av | sAB]; first exact: submx_trans sAB.\nby apply/row_subP=> i; rewrite sAB ?row_sub.\nQed.\nArguments rV_subP {m1 m2 n A B}.\n\nLemma row_subPn m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists i, ~~ (row i A <= B)%MS) (~~ (A <= B)%MS).\nProof. by rewrite (sameP row_subP forallP); apply: forallPn. Qed.\n\nLemma sub_rVP n (u v : 'rV_n) : reflect (exists a, u = a *: v) (u <= v)%MS.\nProof.\napply: (iffP submxP) => [[w ->] | [a ->]].\n  by exists (w 0 0); rewrite -mul_scalar_mx -mx11_scalar.\nby exists a%:M; rewrite mul_scalar_mx.\nQed.\n\nLemma rank_rV n (v : 'rV_n) : \\rank v = (v != 0).\nProof.\ncase: eqP => [-> | nz_v]; first by rewrite mxrank0.\nby apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0; apply/eqP.\nQed.\n\nLemma rowV0Pn m n (A : 'M_(m, n)) :\n  reflect (exists2 v : 'rV_n, v <= A & v != 0)%MS (A != 0).\nProof.\nrewrite -submx0; apply: (iffP idP) => [| [v svA]]; last first.\n  by rewrite -submx0; apply: contra (submx_trans _).\nby case/row_subPn=> i; rewrite submx0; exists (row i A); rewrite ?row_sub.\nQed.\n\nLemma rowV0P m n (A : 'M_(m, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v = 0)%MS (A == 0).\nProof.\nrewrite -[A == 0]negbK; case: rowV0Pn => IH.\n  by right; case: IH => v svA nzv IH; case/eqP: nzv; apply: IH.\nby left=> v svA; apply/eqP/idPn=> nzv; case: IH; exists v.\nQed.\n\nLemma submx_full m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A <= B)%MS.\nProof.\nby rewrite submxE /cokermx => /eqnP->; rewrite /copid_mx pid_mx_1 subrr !mulmx0.\nQed.\n\nLemma row_fullP m n (A : 'M_(m, n)) :\n  reflect (exists B, B *m A = 1%:M) (row_full A).\nProof.\napply: (iffP idP) => [Afull | [B kA]].\n  by exists (1%:M *m pinvmx A); apply: mulmxKpV (submx_full _ Afull).\nby rewrite [_ A]eqn_leq rank_leq_col (mulmx1_min_rank B 1%:M) ?mulmx1.\nQed.\nArguments row_fullP {m n A}.\n\nLemma row_full_inj m n p A : row_full A -> injective (@mulmx _ m n p A).\nProof.\ncase/row_fullP=> A' A'K; apply: can_inj (mulmx A') _ => B.\nby rewrite mulmxA A'K mul1mx.\nQed.\n\nLemma row_freeP m n (A : 'M_(m, n)) :\n  reflect (exists B, A *m B = 1%:M) (row_free A).\nProof.\nrewrite /row_free -mxrank_tr.\napply: (iffP row_fullP) => [] [B kA];\n  by exists B^T; rewrite -trmx1 -kA trmx_mul ?trmxK.\nQed.\n\nLemma row_free_inj m n p A : row_free A -> injective ((@mulmx _ m n p)^~ A).\nProof.\ncase/row_freeP=> A' AK; apply: can_inj (mulmx^~ A') _ => B.\nby rewrite -mulmxA AK mulmx1.\nQed.\n\n(* A variant of row_free_inj that exposes mulmxr, an alias for mulmx^~ *)\n(* but which is canonically additive *)\nDefinition row_free_injr m n p A : row_free A -> injective (mulmxr A) :=\n  @row_free_inj m n p A.\n\nLemma row_free_unit n (A : 'M_n) : row_free A = (A \\in unitmx).\nProof.\napply/row_fullP/idP=> [[A'] | uA]; first by case/mulmx1_unit.\nby exists (invmx A); rewrite mulVmx.\nQed.\n\nLemma row_full_unit n (A : 'M_n) : row_full A = (A \\in unitmx).\nProof. exact: row_free_unit. Qed.\n\nLemma mxrank_unit n (A : 'M_n) : A \\in unitmx -> \\rank A = n.\nProof. by rewrite -row_full_unit => /eqnP. Qed.\n\nLemma mxrank1 n : \\rank (1%:M : 'M_n) = n. Proof. exact: mxrank_unit. Qed.\n\nLemma mxrank_delta m n i j : \\rank (delta_mx i j : 'M_(m, n)) = 1%N.\nProof.\napply/eqP; rewrite eqn_leq lt0n mxrank_eq0.\nrewrite -{1}(mul_delta_mx (0 : 'I_1)) mulmx_max_rank.\nby apply/eqP; move/matrixP; move/(_ i j); move/eqP; rewrite !mxE !eqxx oner_eq0.\nQed.\n\nLemma mxrankS m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B.\nProof. by case/submxP=> D ->; rewrite mxrankM_maxr. Qed.\n\nLemma submx1 m n (A : 'M_(m, n)) : (A <= 1%:M)%MS.\nProof. by rewrite submx_full // row_full_unit unitmx1. Qed.\n\nLemma sub1mx m n (A : 'M_(m, n)) : (1%:M <= A)%MS = row_full A.\nProof.\napply/idP/idP; last exact: submx_full.\nby move/mxrankS; rewrite mxrank1 col_leq_rank.\nQed.\n\nLemma ltmx1 m n (A : 'M_(m, n)) : (A < 1%:M)%MS = ~~ row_full A.\nProof. by rewrite /ltmx sub1mx submx1. Qed.\n\nLemma lt1mx m n (A : 'M_(m, n)) : (1%:M < A)%MS = false.\nProof. by rewrite /ltmx submx1 andbF. Qed.\n\nLemma pinvmxE n (A : 'M[F]_n) : A \\in unitmx -> pinvmx A = invmx A.\nProof.\nmove=> A_unit; apply: (@row_free_inj _ _ _ A); rewrite ?row_free_unit//.\nby rewrite -[pinvmx _]mul1mx mulmxKpV ?sub1mx ?row_full_unit// mulVmx.\nQed.\n\nLemma mulVpmx m n (A : 'M[F]_(m, n)) : row_full A -> pinvmx A *m A = 1%:M.\nProof. by move=> fA; rewrite -[pinvmx _]mul1mx mulmxKpV// sub1mx. Qed.\n\nLemma pinvmx_free m n (A : 'M[F]_(m, n)) : row_full A -> row_free (pinvmx A).\nProof. by move=> /mulVpmx pAA1; apply/row_freeP; exists A. Qed.\n\nLemma pinvmx_full m n (A : 'M[F]_(m, n)) : row_free A -> row_full (pinvmx A).\nProof. by move=> /mulmxVp ApA1; apply/row_fullP; exists A. Qed.\n\nLemma eqmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :=: B)%MS (A == B)%MS.\nProof.\napply: (iffP andP) => [[sAB sBA] | eqAB]; last by rewrite !eqAB.\nsplit=> [|m3 C]; first by apply/eqP; rewrite eqn_leq !mxrankS.\nsplit; first by apply/idP/idP; apply: submx_trans.\nby apply/idP/idP=> sC; apply: submx_trans sC _.\nQed.\nArguments eqmxP {m1 m2 n A B}.\n\nLemma rV_eqP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall u : 'rV_n, (u <= A) = (u <= B))%MS (A == B)%MS.\nProof.\napply: (iffP idP) => [eqAB u | eqAB]; first by rewrite (eqmxP eqAB).\nby apply/andP; split; apply/rV_subP=> u; rewrite eqAB.\nQed.\n\nLemma eqmx_refl m1 n (A : 'M_(m1, n)) : (A :=: A)%MS.\nProof. by []. Qed.\n\nLemma eqmx_sym m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (B :=: A)%MS.\nProof. by move=> eqAB; split=> [|m3 C]; rewrite !eqAB. Qed.\n\nLemma eqmx_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :=: B)%MS -> (B :=: C)%MS -> (A :=: C)%MS.\nProof. by move=> eqAB eqBC; split=> [|m4 D]; rewrite !eqAB !eqBC. Qed.\n\nLemma eqmx_rank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A == B)%MS -> \\rank A = \\rank B.\nProof. by move/eqmxP->. Qed.\n\nLemma lt_eqmx m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n    (A :=: B)%MS ->\n  forall C : 'M_(m3, n), (((A < C) = (B < C))%MS * ((C < A) = (C < B))%MS)%type.\nProof. by move=> eqAB C; rewrite /ltmx !eqAB. Qed.\n\nLemma eqmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A :=: B)%MS -> (A *m C :=: B *m C)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !submxMr ?eqAB. Qed.\n\nLemma eqmxMfull m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_full A -> (A *m B :=: B)%MS.\nProof.\ncase/row_fullP=> A' A'A; apply/eqmxP; rewrite submxMl /=.\nby apply/submxP; exists A'; rewrite mulmxA A'A mul1mx.\nQed.\n\nLemma eqmx0 m n : ((0 : 'M[F]_(m, n)) :=: (0 : 'M_n))%MS.\nProof. by apply/eqmxP; rewrite !sub0mx. Qed.\n\nLemma eqmx_scale m n a (A : 'M_(m, n)) : a != 0 -> (a *: A :=: A)%MS.\nProof.\nmove=> nz_a; apply/eqmxP; rewrite scalemx_sub //.\nby rewrite -{1}[A]scale1r -(mulVf nz_a) -scalerA scalemx_sub.\nQed.\n\nLemma eqmx_opp m n (A : 'M_(m, n)) : (- A :=: A)%MS.\nProof.\nby rewrite -scaleN1r; apply: eqmx_scale => //; rewrite oppr_eq0 oner_eq0.\nQed.\n\nLemma submxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C <= B *m C)%MS = (A <= B)%MS.\nProof.\ncase/row_freeP=> C' C_C'_1; apply/idP/idP=> sAB; last exact: submxMr.\nby rewrite -[A]mulmx1 -[B]mulmx1 -C_C'_1 !mulmxA submxMr.\nQed.\n\nLemma eqmxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C :=: B *m C)%MS -> (A :=: B)%MS.\nProof.\nby move=> Cfree eqAB; apply/eqmxP; move/eqmxP: eqAB; rewrite !submxMfree.\nQed.\n\nLemma mxrankMfree m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_free B -> \\rank (A *m B) = \\rank A.\nProof.\nby move=> Bfree; rewrite -mxrank_tr trmx_mul eqmxMfull /row_full mxrank_tr.\nQed.\n\nLemma eq_row_base m n (A : 'M_(m, n)) : (row_base A :=: A)%MS.\nProof.\napply/eqmxP/andP; split; apply/submxP.\n  exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n  by rewrite -{8}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\nexists (col_ebase A *m pid_mx (\\rank A)).\nby rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nQed.\n\nLemma row_base0 (m n : nat) : row_base (0 : 'M[F]_(m, n)) = 0.\nProof. by apply/eqmx0P; rewrite !eq_row_base !sub0mx. Qed.\n\nLet qidmx_eq1 n (A : 'M_n) : qidmx A = (A == 1%:M).\nProof. by rewrite /qidmx eqxx pid_mx_1. Qed.\n\nLet genmx_witnessP m n (A : 'M_(m, n)) :\n  equivmx A (row_full A) (genmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /genmx_witness.\ncase fullA: (row_full A); first by rewrite eqxx sub1mx submx1 fullA.\nset B := _ *m _; have defB : (B == A)%MS.\n  apply/andP; split; apply/submxP.\n    exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n    by rewrite -{3}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\n  exists (col_ebase A *m pid_mx (\\rank A)).\n  by rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nrewrite defB -negb_add addbF; case: eqP defB => // ->.\nby rewrite sub1mx fullA.\nQed.\n\nLemma genmxE m n (A : 'M_(m, n)) : (<<A>> :=: A)%MS.\nProof.\nby rewrite unlock; apply/eqmxP; case/andP: (chooseP (genmx_witnessP A)).\nQed.\n\nLemma eq_genmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B -> <<A>> = <<B>>)%MS.\nProof.\nmove=> eqAB; rewrite unlock.\nhave{} eqAB: equivmx A (row_full A) =1 equivmx B (row_full B).\n  by move=> C; rewrite /row_full /equivmx !eqAB.\nrewrite (eq_choose eqAB) (choose_id _ (genmx_witnessP B)) //.\nby rewrite -eqAB genmx_witnessP.\nQed.\n\nLemma genmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (<<A>> = <<B>>)%MS (A == B)%MS.\nProof.\napply: (iffP idP) => eqAB; first exact: eq_genmx (eqmxP _).\nby rewrite -!(genmxE A) eqAB !genmxE andbb.\nQed.\nArguments genmxP {m1 m2 n A B}.\n\nLemma genmx0 m n : <<0 : 'M_(m, n)>>%MS = 0.\nProof. by apply/eqP; rewrite -submx0 genmxE sub0mx. Qed.\n\nLemma genmx1 n : <<1%:M : 'M_n>>%MS = 1%:M.\nProof.\nrewrite unlock; case/andP: (chooseP (@genmx_witnessP n n 1%:M)) => _ /eqP.\nby rewrite qidmx_eq1 row_full_unit unitmx1 => /eqP.\nQed.\n\nLemma genmx_id m n (A : 'M_(m, n)) : (<<<<A>>>> = <<A>>)%MS.\nProof. exact/eq_genmx/genmxE. Qed.\n\nLemma row_base_free m n (A : 'M_(m, n)) : row_free (row_base A).\nProof. by apply/eqnP; rewrite eq_row_base. Qed.\n\nLemma mxrank_gen m n (A : 'M_(m, n)) : \\rank <<A>> = \\rank A.\nProof. by rewrite genmxE. Qed.\n\nLemma col_base_full m n (A : 'M_(m, n)) : row_full (col_base A).\nProof.\napply/row_fullP; exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\nby rewrite !mulmxA mulmxKV // pid_mx_id // pid_mx_1.\nQed.\nHint Resolve row_base_free col_base_full : core.\n\nLemma mxrank_leqif_sup m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (B <= A)%MS.\nProof.\nmove=> sAB; split; first by rewrite mxrankS.\napply/idP/idP=> [| sBA]; last by rewrite eqn_leq !mxrankS.\ncase/submxP: sAB => D ->; set r := \\rank B; rewrite -(mulmx_base B) mulmxA.\nrewrite mxrankMfree // => /row_fullP[E kE].\nby rewrite -[rB in _ *m rB]mul1mx -kE -(mulmxA E) (mulmxA _ E) submxMl.\nQed.\n\nLemma mxrank_leqif_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (A == B)%MS.\nProof. by move=> sAB; rewrite sAB; apply: mxrank_leqif_sup. Qed.\n\nLemma ltmxErank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS = (A <= B)%MS && (\\rank A < \\rank B).\nProof.\nby apply: andb_id2l => sAB; rewrite (ltn_leqif (mxrank_leqif_sup sAB)).\nQed.\n\nLemma rank_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS -> \\rank A < \\rank B.\nProof. by rewrite ltmxErank => /andP[]. Qed.\n\nLemma eqmx_cast m1 m2 n (A : 'M_(m1, n)) e :\n  ((castmx e A : 'M_(m2, n)) :=: A)%MS.\nProof. by case: e A; case: m2 / => A e; rewrite castmx_id. Qed.\n\nLemma row_full_castmx m1 m2 n (A : 'M_(m1, n)) e :\n  row_full (castmx e A  : 'M_(m2, n)) = row_full A.\nProof. exact/eq_row_full/eqmx_cast. Qed.\n\nLemma row_free_castmx m1 m2 n (A : 'M_(m1, n)) e :\n  row_free (castmx e A  : 'M_(m2, n)) = row_free A.\nProof. by rewrite /row_free eqmx_cast; congr (_ == _); rewrite e.1. Qed.\n\nLemma eqmx_conform m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (conform_mx A B :=: A \\/ conform_mx A B :=: B)%MS.\nProof.\ncase: (eqVneq m2 m1) => [-> | neqm12] in B *.\n  by right; rewrite conform_mx_id.\nby left; rewrite nonconform_mx ?neqm12.\nQed.\n\nLet eqmx_sum_nop m n (A : 'M_(m, n)) : (addsmx_nop A :=: A)%MS.\nProof.\ncase: (eqmx_conform <<A>>%MS A) => // eq_id_gen.\nexact: eqmx_trans (genmxE A).\nQed.\n\nLemma rowsub_comp_sub (m n p q : nat) f (g : 'I_n -> 'I_p) (A : 'M_(m, q)) :\n   (rowsub (f \\o g) A <= rowsub f A)%MS.\nProof. by rewrite rowsub_comp rowsubE mulmx_sub. Qed.\n\nLemma submx_rowsub (m n p q : nat) (h : 'I_n -> 'I_p) f g (A : 'M_(m, q)) :\n  f =1 g \\o h -> (rowsub f A <= rowsub g A)%MS.\nProof. by move=> /eq_rowsub->; rewrite rowsub_comp_sub. Qed.\nArguments submx_rowsub [m1 m2 m3 n] h [f g A] _ : rename.\n\nLemma eqmx_rowsub_comp_perm (m1 m2 n : nat) (s : 'S_m2) f (A : 'M_(m1, n)) :\n  (rowsub (f \\o s) A :=: rowsub f A)%MS.\nProof.\nrewrite rowsub_comp rowsubE; apply: eqmxMfull.\nby rewrite -perm_mxEsub row_full_unit unitmx_perm.\nQed.\n\nLemma eqmx_rowsub_comp (m n p q : nat) f (g : 'I_n -> 'I_p) (A : 'M_(m, q)) :\n  p <= n -> injective g -> (rowsub (f \\o g) A :=: rowsub f A)%MS.\nProof.\nmove=> leq_pn g_inj; have eq_np : n == p by rewrite eqn_leq leq_pn (inj_leq g).\nrewrite (eqP eq_np) in g g_inj *.\nrewrite (eq_rowsub (f \\o (perm g_inj))); last by move=> i; rewrite /= permE.\nexact: eqmx_rowsub_comp_perm.\nQed.\n\nLemma eqmx_rowsub (m n p q : nat) (h : 'I_n -> 'I_p) f g (A : 'M_(m, q)) :\n  injective h -> p <= n -> f =1 g \\o h -> (rowsub f A :=: rowsub g A)%MS.\nProof. by move=> leq_pn h_inj /eq_rowsub->; apply: eqmx_rowsub_comp. Qed.\nArguments eqmx_rowsub [m1 m2 m3 n] h [f g A] _ : rename.\n\nSection AddsmxSub.\n\nVariable (m1 m2 n : nat) (A : 'M[F]_(m1, n)) (B : 'M[F]_(m2, n)).\n\nLemma col_mx_sub m3 (C : 'M_(m3, n)) :\n  (col_mx A B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof.\nrewrite !submxE mul_col_mx -col_mx0.\nby apply/eqP/andP; [case/eq_col_mx=> -> -> | case; do 2!move/eqP->].\nQed.\n\nLemma addsmxE : (A + B :=: col_mx A B)%MS.\nProof.\nhave:= submx_refl (col_mx A B); rewrite col_mx_sub; case/andP=> sAS sBS.\nrewrite unlock; do 2?case: eqP => [AB0 | _]; last exact: genmxE.\n  by apply/eqmxP; rewrite !eqmx_sum_nop sBS col_mx_sub AB0 sub0mx /=.\nby apply/eqmxP; rewrite !eqmx_sum_nop sAS col_mx_sub AB0 sub0mx andbT /=.\nQed.\n\nLemma addsmx_sub m3 (C : 'M_(m3, n)) :\n  (A + B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof. by rewrite addsmxE col_mx_sub. Qed.\n\nLemma addsmxSl : (A <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmxSr : (B <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmx_idPr : reflect (A + B :=: B)%MS (A <= B)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS B.\nby rewrite addsmxSr addsmx_sub submx_refl !andbT.\nQed.\n\nLemma addsmx_idPl : reflect (A + B :=: A)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS A.\nby rewrite addsmxSl addsmx_sub submx_refl !andbT.\nQed.\n\nEnd AddsmxSub.\n\nLemma adds0mx m1 m2 n (B : 'M_(m2, n)) : ((0 : 'M_(m1, n)) + B :=: B)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSr /= andbT. Qed.\n\nLemma addsmx0 m1 m2 n (A : 'M_(m1, n)) : (A + (0 : 'M_(m2, n)) :=: A)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSl /= !andbT. Qed.\n\nLet addsmx_nop_eq0 m n (A : 'M_(m, n)) : (addsmx_nop A == 0) = (A == 0).\nProof. by rewrite -!submx0 eqmx_sum_nop. Qed.\n\nLet addsmx_nop0 m n : addsmx_nop (0 : 'M_(m, n)) = 0.\nProof. by apply/eqP; rewrite addsmx_nop_eq0. Qed.\n\nLet addsmx_nop_id n (A : 'M_n) : addsmx_nop A = A.\nProof. exact: conform_mx_id. Qed.\n\nLemma addsmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A + B = B + A)%MS.\nProof.\nhave: (A + B == B + A)%MS.\n  by apply/andP; rewrite !addsmx_sub andbC -addsmx_sub andbC -addsmx_sub.\nmove/genmxP; rewrite [@addsmx]unlock -!submx0 !submx0.\nby do 2!case: eqP => [// -> | _]; rewrite ?genmx_id ?addsmx_nop0.\nQed.\n\nLemma adds0mx_id m1 n (B : 'M_n) : ((0 : 'M_(m1, n)) + B)%MS = B.\nProof. by rewrite unlock eqxx addsmx_nop_id. Qed.\n\nLemma addsmx0_id m2 n (A : 'M_n) : (A + (0 : 'M_(m2, n)))%MS = A.\nProof. by rewrite addsmxC adds0mx_id. Qed.\n\nLemma addsmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A + (B + C) = A + B + C)%MS.\nProof.\nhave: (A + (B + C) :=: A + B + C)%MS.\n  by apply/eqmxP/andP; rewrite !addsmx_sub -andbA andbA -!addsmx_sub.\nrewrite {1 3}[in @addsmx m1]unlock [in @addsmx n]unlock !addsmx_nop_id -!submx0.\nrewrite !addsmx_sub ![@addsmx]unlock -!submx0; move/eq_genmx.\nby do 3!case: (_ <= 0)%MS; rewrite //= !genmx_id.\nQed.\n\nCanonical addsmx_monoid n :=\n  Monoid.Law (@addsmxA n n n n) (@adds0mx_id n n) (@addsmx0_id n n).\nCanonical addsmx_comoid n := Monoid.ComLaw (@addsmxC n n n).\n\nLemma addsmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A + B)%MS *m C :=: A *m C + B *m C)%MS.\nProof. by apply/eqmxP; rewrite !addsmxE -!mul_col_mx !submxMr ?addsmxE. Qed.\n\nLemma addsmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                            (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A + B <= C + D)%MS.\nProof.\nmove=> sAC sBD.\nby rewrite addsmx_sub {1}addsmxC !(submx_trans _ (addsmxSr _ _)).\nQed.\n\nLemma addmx_sub_adds m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m, n))\n                               (C : 'M_(m1, n)) (D : 'M_(m2, n)) :\n  (A <= C -> B <= D -> (A + B)%R <= C + D)%MS.\nProof.\nmove=> sAC; move/(addsmxS sAC); apply: submx_trans.\nby rewrite addmx_sub ?addsmxSl ?addsmxSr.\nQed.\n\nLemma addsmx_addKl n m1 m2 (A : 'M_(m1, n)) (B C : 'M_(m2, n)) :\n  (B <= A)%MS -> (A + (B + C)%R :=: A + C)%MS.\nProof.\nmove=> sBA; apply/eqmxP; rewrite !addsmx_sub !addsmxSl.\nby rewrite -{3}[C](addKr B) !addmx_sub_adds ?eqmx_opp.\nQed.\n\nLemma addsmx_addKr n m1 m2 (A B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (B <= C)%MS -> ((A + B)%R + C :=: A + C)%MS.\nProof. by rewrite -!(addsmxC C) addrC; apply: addsmx_addKl. Qed.\n\nLemma adds_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                              (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A + B :=: C + D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !addsmxS ?eqAC ?eqBD. Qed.\n\nLemma genmx_adds m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<(A + B)%MS>> = <<A>> + <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (adds_eqmx (genmxE A) (genmxE B))).\nby rewrite [@addsmx]unlock !addsmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\nQed.\n\nLemma sub_addsmxP m1 m2 m3 n\n                  (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  reflect (exists u, A = u.1 *m B + u.2 *m C) (A <= B + C)%MS.\nProof.\napply: (iffP idP) => [|[u ->]]; last by rewrite addmx_sub_adds ?submxMl.\nrewrite addsmxE; case/submxP=> u ->; exists (lsubmx u, rsubmx u).\nby rewrite -mul_row_col hsubmxK.\nQed.\nArguments sub_addsmxP {m1 m2 m3 n A B C}.\n\nVariable I : finType.\nImplicit Type P : pred I.\n\nLemma genmx_sums P n (B_ : I -> 'M_n) :\n  <<(\\sum_(i | P i) B_ i)%MS>>%MS = (\\sum_(i | P i) <<B_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_adds n n n) (@genmx0 n n)). Qed.\n\nLemma sumsmx_sup i0 P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  P i0 -> (A <= B_ i0)%MS -> (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\nby move=> Pi0 sAB; apply: submx_trans sAB _; rewrite (bigD1 i0) // addsmxSl.\nQed.\nArguments sumsmx_sup i0 [P m n A B_].\n\nLemma sumsmx_subP P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  reflect (forall i, P i -> A_ i <= B)%MS (\\sum_(i | P i) A_ i <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: submx_trans sAB; apply: sumsmx_sup Pi _.\nby elim/big_rec: _ => [|i Ai Pi sAiB]; rewrite ?sub0mx // addsmx_sub sAB.\nQed.\n\nLemma summx_sub_sums P m n (A : I -> 'M[F]_(m, n)) B :\n    (forall i, P i -> A i <= B i)%MS ->\n  ((\\sum_(i | P i) A i)%R <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply: summx_sub => i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma sumsmxS P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i <= B i)%MS ->\n  (\\sum_(i | P i) A i <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply/sumsmx_subP=> i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma eqmx_sums P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i :=: B i)%MS ->\n  (\\sum_(i | P i) A i :=: \\sum_(i | P i) B i)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !sumsmxS // => i; move/eqAB->. Qed.\n\nLemma sub_sums_genmxP P m n p (A : 'M_(m, p)) (B_ : I -> 'M_(n, p)) :\n  reflect (exists u_ : I -> 'M_(m, n), A = \\sum_(i | P i) u_ i *m B_ i)\n          (A <= \\sum_(i | P i) <<B_ i>>)%MS.\nProof.\napply: (iffP idP) => [| [u_ ->]]; last first.\n  by apply: summx_sub_sums => i _; rewrite genmxE; apply: submxMl.\nhave [b] := ubnP #|P|; elim: b => // b IHb in P A *.\ncase: (pickP P) => [i Pi | P0 _]; last first.\n  rewrite big_pred0 //; move/submx0null->.\n  by exists (fun _ => 0); rewrite big_pred0.\nrewrite (cardD1x Pi) (bigD1 i) //= => /IHb{b IHb} /= IHi.\nrewrite (adds_eqmx (genmxE _) (eqmx_refl _)) => /sub_addsmxP[u ->].\nhave [u_ ->] := IHi _ (submxMl u.2 _).\nexists [eta u_ with i |-> u.1]; rewrite (bigD1 i Pi)/= eqxx; congr (_ + _).\nby apply: eq_bigr => j /andP[_ /negPf->].\nQed.\n\nLemma sub_sumsmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (exists u_, A = \\sum_(i | P i) u_ i *m B_ i)\n          (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\nby rewrite -(eqmx_sums (fun _ _ => genmxE _)); apply/sub_sums_genmxP.\nQed.\n\nLemma sumsmxMr_gen P m n A (B : 'M[F]_(m, n)) :\n  ((\\sum_(i | P i) A i)%MS *m B :=: \\sum_(i | P i) <<A i *m B>>)%MS.\nProof.\napply/eqmxP/andP; split; last first.\n  by apply/sumsmx_subP=> i Pi; rewrite genmxE submxMr ?(sumsmx_sup i).\nhave [u ->] := sub_sumsmxP _ _ _ (submx_refl (\\sum_(i | P i) A i)%MS).\nby rewrite mulmx_suml summx_sub_sums // => i _; rewrite genmxE -mulmxA submxMl.\nQed.\n\nLemma sumsmxMr P n (A_ : I -> 'M[F]_n) (B : 'M_n) :\n  ((\\sum_(i | P i) A_ i)%MS *m B :=: \\sum_(i | P i) (A_ i *m B))%MS.\nProof.\nby apply: eqmx_trans (sumsmxMr_gen _ _ _) (eqmx_sums _) => i _; apply: genmxE.\nQed.\n\nLemma rank_pid_mx m n r : r <= m -> r <= n -> \\rank (pid_mx r : 'M_(m, n)) = r.\nProof.\ndo 2!move/subnKC <-; rewrite pid_mx_block block_mxEv row_mx0 -addsmxE addsmx0.\nby rewrite -mxrank_tr tr_row_mx trmx0 trmx1 -addsmxE addsmx0 mxrank1.\nQed.\n\nLemma rank_copid_mx n r : r <= n -> \\rank (copid_mx r : 'M_n) = (n - r)%N.\nProof.\nmove/subnKC <-; rewrite /copid_mx pid_mx_block scalar_mx_block.\nrewrite opp_block_mx !oppr0 add_block_mx !addr0 subrr block_mxEv row_mx0.\nrewrite -addsmxE adds0mx -mxrank_tr tr_row_mx trmx0 trmx1.\nby rewrite -addsmxE adds0mx mxrank1 addKn.\nQed.\n\nLemma mxrank_compl m n (A : 'M_(m, n)) : \\rank A^C = (n - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?rank_copid_mx. Qed.\n\nLemma mxrank_ker m n (A : 'M_(m, n)) : \\rank (kermx A) = (m - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma kermx_eq0 n m (A : 'M_(m, n)) : (kermx A == 0) = row_free A.\nProof. by rewrite -mxrank_eq0 mxrank_ker subn_eq0 row_leq_rank. Qed.\n\nLemma mxrank_coker m n (A : 'M_(m, n)) : \\rank (cokermx A) = (n - \\rank A)%N.\nProof. by rewrite eqmxMfull ?row_full_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma cokermx_eq0 n m (A : 'M_(m, n)) : (cokermx A == 0) = row_full A.\nProof. by rewrite -mxrank_eq0 mxrank_coker subn_eq0 col_leq_rank. Qed.\n\nLemma mulmx_ker m n (A : 'M_(m, n)) : kermx A *m A = 0.\nProof.\nby rewrite -{2}[A]mulmx_ebase !mulmxA mulmxKV // mul_copid_mx_pid ?mul0mx.\nQed.\n\nLemma mulmxKV_ker m n p (A : 'M_(n, p)) (B : 'M_(m, n)) :\n  B *m A = 0 -> B *m col_ebase A *m kermx A = B.\nProof.\nrewrite mulmxA mulmxBr mulmx1 mulmxBl mulmxK //.\nrewrite -{1}[A]mulmx_ebase !mulmxA => /(canRL (mulmxK (row_ebase_unit A))).\nrewrite mul0mx // => BA0; apply: (canLR (addrK _)).\nby rewrite -(pid_mx_id _ _ n (rank_leq_col A)) mulmxA BA0 !mul0mx addr0.\nQed.\n\nLemma sub_kermxP p m n (A : 'M_(m, n)) (B : 'M_(p, m)) :\n  reflect (B *m A = 0) (B <= kermx A)%MS.\nProof.\napply: (iffP submxP) => [[D ->]|]; first by rewrite -mulmxA mulmx_ker mulmx0.\nby move/mulmxKV_ker; exists (B *m col_ebase A).\nQed.\n\nLemma sub_kermx p m n (A : 'M_(m, n)) (B : 'M_(p, m)) :\n  (B <= kermx A)%MS = (B *m A == 0).\nProof. exact/sub_kermxP/eqP. Qed.\n\nLemma kermx0 m n : (kermx (0 : 'M_(m, n)) :=: 1%:M)%MS.\nProof. by apply/eqmxP; rewrite submx1/= sub_kermx mulmx0. Qed.\n\nLemma mulmx_free_eq0 m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_free B -> (A *m B == 0) = (A == 0).\nProof. by rewrite -sub_kermx -kermx_eq0 => /eqP->; rewrite submx0. Qed.\n\nLemma inj_row_free m n (A : 'M_(m, n)) :\n  (forall v : 'rV_m, v *m A = 0 -> v = 0) -> row_free A.\nProof.\nmove=> Ainj; rewrite -kermx_eq0; apply/eqP/row_matrixP => i.\nby rewrite row0; apply/Ainj; rewrite -row_mul mulmx_ker row0.\nQed.\n\nLemma row_freePn m n (M : 'M[F]_(m, n)) :\n reflect (exists i, (row i M <= row' i M)%MS) (~~ row_free M).\nProof.\nrewrite -kermx_eq0; apply: (iffP (rowV0Pn _)) => [|[i0 /submxP[D rM]]].\n  move=> [v /sub_kermxP vM_eq0 /rV0Pn[i0 vi0_neq0]]; exists i0.\n  have := vM_eq0; rewrite mulmx_sum_row (bigD1_ord i0)//=.\n  move=> /(canRL (addrK _))/(canRL (scalerK _))->//.\n  rewrite sub0r scalerN -scaleNr scalemx_sub// summx_sub// => l _.\n  by rewrite scalemx_sub// -row_rowsub row_sub.\nexists (\\row_j oapp (D 0) (- 1) (unlift i0 j)); last first.\n  by apply/rV0Pn; exists i0; rewrite !mxE unlift_none/= oppr_eq0 oner_eq0.\napply/sub_kermxP; rewrite mulmx_sum_row (bigD1_ord i0)//= !mxE.\nrewrite unlift_none scaleN1r rM mulmx_sum_row addrC -sumrB big1 // => l _.\nby rewrite !mxE liftK row_rowsub subrr.\nQed.\n\nLemma negb_row_free m n (M : 'M[F]_(m, n)) :\n  ~~ row_free M = [exists i, (row i M <= row' i M)%MS].\nProof. exact/row_freePn/existsP. Qed.\n\nLemma mulmx0_rank_max m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  A *m B = 0 -> \\rank A + \\rank B <= n.\nProof.\nmove=> AB0; rewrite -{3}(subnK (rank_leq_row B)) leq_add2r.\nby rewrite -mxrank_ker mxrankS // sub_kermx AB0.\nQed.\n\nLemma mxrank_Frobenius m n p q (A : 'M_(m, n)) B (C : 'M_(p, q)) :\n  \\rank (A *m B) + \\rank (B *m C) <= \\rank B + \\rank (A *m B *m C).\nProof.\nrewrite -{2}(mulmx_base (A *m B)) -mulmxA (eqmxMfull _ (col_base_full _)).\nset C2 := row_base _ *m C.\nrewrite -{1}(subnK (rank_leq_row C2)) -(mxrank_ker C2) addnAC leq_add2r.\nrewrite addnC -{1}(mulmx_base B) -mulmxA eqmxMfull //.\nset C1 := _ *m C; rewrite -{2}(subnKC (rank_leq_row C1)) leq_add2l -mxrank_ker.\nrewrite -(mxrankMfree _ (row_base_free (A *m B))).\nhave: (row_base (A *m B) <= row_base B)%MS by rewrite !eq_row_base submxMl.\ncase/submxP=> D defD; rewrite defD mulmxA mxrankMfree ?mxrankS //.\nby rewrite sub_kermx -mulmxA (mulmxA D) -defD -/C2 mulmx_ker.\nQed.\n\nLemma mxrank_mul_min m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank A + \\rank B - n <= \\rank (A *m B).\nProof.\nby have:= mxrank_Frobenius A 1%:M B; rewrite mulmx1 mul1mx mxrank1 leq_subLR.\nQed.\n\nLemma addsmx_compl_full m n (A : 'M_(m, n)) : row_full (A + A^C)%MS.\nProof.\nrewrite /row_full addsmxE; apply/row_fullP.\nexists (row_mx (pinvmx A) (cokermx A)); rewrite mul_row_col.\nrewrite -{2}[A]mulmx_ebase -!mulmxA mulKmx // -mulmxDr !mulmxA.\nby rewrite pid_mx_id ?copid_mx_id // -mulmxDl addrC subrK mul1mx mulVmx.\nQed.\n\nLemma sub_capmx_gen m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= capmx_gen B C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof.\napply/idP/andP=> [sAI | [/submxP[B' ->{A}] /submxP[C' eqBC']]].\n  rewrite !(submx_trans sAI) ?submxMl // /capmx_gen.\n   have:= mulmx_ker (col_mx B C); set K := kermx _.\n   rewrite -{1}[K]hsubmxK mul_row_col; move/(canRL (addrK _))->.\n   by rewrite add0r -mulNmx submxMl.\nhave: (row_mx B' (- C') <= kermx (col_mx B C))%MS.\n  by rewrite sub_kermx mul_row_col eqBC' mulNmx subrr.\ncase/submxP=> D; rewrite -[kermx _]hsubmxK mul_mx_row.\nby case/eq_row_mx=> -> _; rewrite -mulmxA submxMl.\nQed.\n\nLet capmx_witnessP m n (A : 'M_(m, n)) : equivmx A (qidmx A) (capmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /qidmx /capmx_witness.\nrewrite -sub1mx; case s1A: (1%:M <= A)%MS => /=; last first.\n  rewrite !genmxE submx_refl /= -negb_add; apply: contra {s1A}(negbT s1A).\n  have [<- | _] := eqP; first by rewrite genmxE.\n  by case: eqP A => //= -> A /eqP ->; rewrite pid_mx_1.\ncase: (m =P n) => [-> | ne_mn] in A s1A *.\n  by rewrite conform_mx_id submx_refl pid_mx_1 eqxx.\nby rewrite nonconform_mx ?submx1 ?s1A ?eqxx //; case: eqP.\nQed.\n\nLet capmx_normP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_norm A).\nProof. by case/andP: (chooseP (capmx_witnessP A)) => /eqmxP defN /eqP. Qed.\n\nLet capmx_norm_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A == B)%MS -> capmx_norm A = capmx_norm B.\nProof.\nmove=> eqABid /eqmxP eqAB.\nhave{eqABid} eqAB: equivmx A (qidmx A) =1 equivmx B (qidmx B).\n  by move=> C; rewrite /equivmx eqABid !eqAB.\nrewrite {1}/capmx_norm (eq_choose eqAB).\nby apply: choose_id; first rewrite -eqAB; apply: capmx_witnessP.\nQed.\n\nLet capmx_nopP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_nop A).\nProof.\nrewrite /capmx_nop; case: (eqVneq m n) => [-> | ne_mn] in A *.\n  by rewrite conform_mx_id.\nby rewrite nonconform_mx ?ne_mn //; apply: capmx_normP.\nQed.\n\nLet sub_qidmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx B -> (A <= B)%MS.\nProof.\nrewrite /qidmx => idB; apply: {A}submx_trans (submx1 A) _.\nby case: eqP B idB => [-> _ /eqP-> | _ B]; rewrite (=^~ sub1mx, pid_mx_1).\nQed.\n\nLet qidmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx (A :&: B)%MS = qidmx A && qidmx B.\nProof.\nrewrite unlock -sub1mx.\ncase idA: (qidmx A); case idB: (qidmx B); try by rewrite capmx_nopP.\ncase s1B: (_ <= B)%MS; first by rewrite capmx_normP.\napply/idP=> /(sub_qidmx 1%:M).\nby rewrite capmx_normP sub_capmx_gen s1B andbF.\nQed.\n\nLet capmx_eq_norm m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A :&: B)%MS = capmx_norm (A :&: B)%MS.\nProof.\nmove=> eqABid; rewrite unlock -sub1mx {}eqABid.\nhave norm_id m (C : 'M_(m, n)) (N := capmx_norm C) : capmx_norm N = N.\n  by apply: capmx_norm_eq; rewrite ?capmx_normP ?andbb.\ncase idB: (qidmx B); last by case: ifP; rewrite norm_id.\nrewrite /capmx_nop; case: (eqVneq m2 n) => [-> | neqm2n] in B idB *.\n  have idN := idB; rewrite -{1}capmx_normP !qidmx_eq1 in idN idB.\n  by rewrite conform_mx_id (eqP idN) (eqP idB).\nby rewrite nonconform_mx ?neqm2n ?norm_id.\nQed.\n\nLemma capmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B :=: capmx_gen A B)%MS.\nProof.\nrewrite unlock -sub1mx; apply/eqmxP.\nhave:= submx_refl (capmx_gen A B); rewrite !sub_capmx_gen => /andP[sIA sIB].\ncase idA: (qidmx A); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase idB: (qidmx B); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase s1B: (1%:M <= B)%MS; rewrite !capmx_normP ?sub_capmx_gen sIA ?sIB //=.\nby rewrite submx_refl (submx_trans (submx1 _)).\nQed.\n\nLemma capmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= A)%MS.\nProof. by rewrite capmxE submxMl. Qed.\n\nLemma sub_capmx m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= B :&: C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof. by rewrite capmxE sub_capmx_gen. Qed.\n\nLemma capmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B = B :&: A)%MS.\nProof.\nhave [eqAB|] := eqVneq (qidmx A) (qidmx B).\n  rewrite (capmx_eq_norm eqAB) (capmx_eq_norm (esym eqAB)).\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbC.\n  by apply/andP; split; rewrite !sub_capmx andbC -sub_capmx.\nby rewrite negb_eqb !unlock => /addbP <-; case: (qidmx A).\nQed.\n\nLemma capmxSr m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= B)%MS.\nProof. by rewrite capmxC capmxSl. Qed.\n\nLemma capmx_idPr n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: B)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A :&: B)%MS B.\nby rewrite capmxSr sub_capmx submx_refl !andbT.\nQed.\n\nLemma capmx_idPl n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: A)%MS (A <= B)%MS.\nProof. by rewrite capmxC; apply: capmx_idPr. Qed.\n\nLemma capmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                           (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A :&: B <= C :&: D)%MS.\nProof.\nby move=> sAC sBD; rewrite sub_capmx {1}capmxC !(submx_trans (capmxSr _ _)).\nQed.\n\nLemma cap_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                             (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A :&: B :=: C :&: D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !capmxS ?eqAC ?eqBD. Qed.\n\nLemma capmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A :&: B) *m C <= A *m C :&: B *m C)%MS.\nProof. by rewrite sub_capmx !submxMr ?capmxSl ?capmxSr. Qed.\n\nLemma cap0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) :&: A)%MS = 0.\nProof. exact: submx0null (capmxSl _ _). Qed.\n\nLemma capmx0 m1 m2 n (A : 'M_(m1, n)) : (A :&: (0 : 'M_(m2, n)))%MS = 0.\nProof. exact: submx0null (capmxSr _ _). Qed.\n\nLemma capmxT m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A :&: B :=: A)%MS.\nProof.\nrewrite -sub1mx => s1B; apply/eqmxP.\nby rewrite capmxSl sub_capmx submx_refl (submx_trans (submx1 A)).\nQed.\n\nLemma capTmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full A -> (A :&: B :=: B)%MS.\nProof. by move=> Afull; apply/eqmxP; rewrite capmxC !capmxT ?andbb. Qed.\n\nLet capmx_nop_id n (A : 'M_n) : capmx_nop A = A.\nProof. by rewrite /capmx_nop conform_mx_id. Qed.\n\nLemma cap1mx n (A : 'M_n) : (1%:M :&: A = A)%MS.\nProof. by rewrite unlock qidmx_eq1 eqxx capmx_nop_id. Qed.\n\nLemma capmx1 n (A : 'M_n) : (A :&: 1%:M = A)%MS.\nProof. by rewrite capmxC cap1mx. Qed.\n\nLemma genmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  <<A :&: B>>%MS = (<<A>> :&: <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (cap_eqmx (genmxE A) (genmxE B))).\ncase idAB: (qidmx <<A>> || qidmx <<B>>)%MS.\n  rewrite [@capmx]unlock !capmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\n  by case: (qidmx _) idAB => //= ->.\ncase idA: (qidmx _) idAB => //= idB; rewrite {2}capmx_eq_norm ?idA //.\nset C := (_ :&: _)%MS; have eq_idC: row_full C = qidmx C.\n  rewrite qidmx_cap idA -sub1mx sub_capmx genmxE; apply/andP=> [[s1A]].\n  by case/idP: idA; rewrite qidmx_eq1 -genmx1 (sameP eqP genmxP) submx1.\nrewrite unlock /capmx_norm eq_idC.\nby apply: choose_id (capmx_witnessP _); rewrite -eq_idC genmx_witnessP.\nQed.\n\nLemma capmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :&: (B :&: C) = A :&: B :&: C)%MS.\nProof.\nrewrite (capmxC A B) capmxC; wlog idA: m1 m3 A C / qidmx A.\n  move=> IH; case idA: (qidmx A); first exact: IH.\n  case idC: (qidmx C); first by rewrite -IH.\n  rewrite (@capmx_eq_norm n m3) ?qidmx_cap ?idA ?idC ?andbF //.\n  rewrite capmx_eq_norm ?qidmx_cap ?idA ?idC ?andbF //.\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbAC.\n  by apply/andP; split; rewrite !sub_capmx andbAC -!sub_capmx.\nrewrite -!(capmxC A) [in @capmx m1]unlock idA capmx_nop_id.\nhave [eqBC|] := eqVneq (qidmx B) (qidmx C).\n  rewrite (@capmx_eq_norm n) ?capmx_nopP // capmx_eq_norm //.\n  by apply: capmx_norm_eq; rewrite ?qidmx_cap ?capmxS ?capmx_nopP.\nby rewrite !unlock capmx_nopP capmx_nop_id; do 2?case: (qidmx _) => //.\nQed.\n\nCanonical capmx_monoid n :=\n   Monoid.Law (@capmxA n n n n) (@cap1mx n) (@capmx1 n).\nCanonical capmx_comoid n := Monoid.ComLaw (@capmxC n n n).\n\nLemma bigcapmx_inf i0 P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  P i0 -> (A_ i0 <= B -> \\bigcap_(i | P i) A_ i <= B)%MS.\nProof. by move=> Pi0; apply: submx_trans; rewrite (bigD1 i0) // capmxSl. Qed.\n\nLemma sub_bigcapmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (forall i, P i -> A <= B_ i)%MS (A <= \\bigcap_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: (submx_trans sAB); rewrite (bigcapmx_inf Pi).\nby elim/big_rec: _ => [|i Pi C sAC]; rewrite ?submx1 // sub_capmx sAB.\nQed.\n\nLemma genmx_bigcap P n (A_ : I -> 'M_n) :\n  (<<\\bigcap_(i | P i) A_ i>> = \\bigcap_(i | P i) <<A_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_cap n n n) (@genmx1 n)). Qed.\n\nLemma matrix_modl m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= C -> A + (B :&: C) :=: (A + B) :&: C)%MS.\nProof.\nmove=> sAC; set D := ((A + B) :&: C)%MS; apply/eqmxP.\nrewrite sub_capmx addsmxS ?capmxSl // addsmx_sub sAC capmxSr /=.\nhave: (D <= B + A)%MS by rewrite addsmxC capmxSl.\ncase/sub_addsmxP=> u defD; rewrite defD addrC addmx_sub_adds ?submxMl //.\nrewrite sub_capmx submxMl -[_ *m B](addrK (u.2 *m A)) -defD.\nby rewrite addmx_sub ?capmxSr // eqmx_opp mulmx_sub.\nQed.\n\nLemma matrix_modr m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (C <= A -> (A :&: B) + C :=: A :&: (B + C))%MS.\nProof. by rewrite !(capmxC A) -!(addsmxC C); apply: matrix_modl. Qed.\n\nLemma capmx_compl m n (A : 'M_(m, n)) : (A :&: A^C)%MS = 0.\nProof.\nset D := (A :&: A^C)%MS; have: (D <= D)%MS by [].\nrewrite sub_capmx andbC => /andP[/submxP[B defB]].\nrewrite submxE => /eqP; rewrite defB -!mulmxA mulKVmx ?copid_mx_id //.\nby rewrite mulmxA => ->; rewrite mul0mx.\nQed.\n\nLemma mxrank_mul_ker m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  (\\rank (A *m B) + \\rank (A :&: kermx B))%N = \\rank A.\nProof.\napply/eqP; set K := kermx B; set C := (A :&: K)%MS.\nrewrite -(eqmxMr B (eq_row_base A)); set K' := _ *m B.\nrewrite -{2}(subnKC (rank_leq_row K')) -mxrank_ker eqn_add2l.\nrewrite -(mxrankMfree _ (row_base_free A)) mxrank_leqif_sup.\n  by rewrite sub_capmx -(eq_row_base A) submxMl sub_kermx -mulmxA mulmx_ker/=.\nhave /submxP[C' defC]: (C <= row_base A)%MS by rewrite eq_row_base capmxSl.\nby rewrite defC submxMr // sub_kermx mulmxA -defC -sub_kermx capmxSr.\nQed.\n\nLemma mxrank_injP m n p (A : 'M_(m, n)) (f : 'M_(n, p)) :\n  reflect (\\rank (A *m f) = \\rank A) ((A :&: kermx f)%MS == 0).\nProof.\nrewrite -mxrank_eq0 -(eqn_add2l (\\rank (A *m f))).\nby rewrite mxrank_mul_ker addn0 eq_sym; apply: eqP.\nQed.\n\nLemma mxrank_disjoint_sum m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B)%MS = 0 -> \\rank (A + B)%MS = (\\rank A + \\rank B)%N.\nProof.\nmove=> AB0; pose Ar := row_base A; pose Br := row_base B.\nhave [Afree Bfree]: row_free Ar /\\ row_free Br by rewrite !row_base_free.\nhave: (Ar :&: Br <= A :&: B)%MS by rewrite capmxS ?eq_row_base.\nrewrite {}AB0 submx0 -mxrank_eq0 capmxE mxrankMfree //.\nset Cr := col_mx Ar Br; set Crl := lsubmx _; rewrite mxrank_eq0 => /eqP Crl0.\nrewrite -(adds_eqmx (eq_row_base _) (eq_row_base _)) addsmxE -/Cr.\nsuffices K0: kermx Cr = 0.\n  by apply/eqP; rewrite eqn_leq rank_leq_row -subn_eq0 -mxrank_ker K0 mxrank0.\nmove/eqP: (mulmx_ker Cr); rewrite -[kermx Cr]hsubmxK mul_row_col -/Crl Crl0.\nrewrite mul0mx add0r -mxrank_eq0 mxrankMfree // mxrank_eq0 => /eqP->.\nexact: row_mx0.\nQed.\n\nLemma diffmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B :=: A :&: (capmx_gen A B)^C)%MS.\nProof. by rewrite unlock; apply/eqmxP; rewrite !genmxE !capmxE andbb. Qed.\n\nLemma genmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<A :\\: B>> = A :\\: B)%MS.\nProof. by rewrite [@diffmx]unlock genmx_id. Qed.\n\nLemma diffmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :\\: B <= A)%MS.\nProof. by rewrite diffmxE capmxSl. Qed.\n\nLemma capmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B) :&: B)%MS = 0.\nProof.\napply/eqP; pose C := capmx_gen A B; rewrite -submx0 -(capmx_compl C).\nby rewrite sub_capmx -capmxE sub_capmx andbAC -sub_capmx -diffmxE -sub_capmx.\nQed.\n\nLemma addsmx_diff_cap_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B + A :&: B :=: A)%MS.\nProof.\napply/eqmxP; rewrite addsmx_sub capmxSl diffmxSl /=.\nset C := (A :\\: B)%MS; set D := capmx_gen A B.\nsuffices sACD: (A <= C + D)%MS.\n  by rewrite (submx_trans sACD) ?addsmxS ?capmxE.\nhave:= addsmx_compl_full D; rewrite /row_full addsmxE.\ncase/row_fullP=> U /(congr1 (mulmx A)); rewrite mulmx1.\nrewrite -[U]hsubmxK mul_row_col mulmxDr addrC 2!mulmxA.\nset V := _ *m _ => defA; rewrite -defA; move/(canRL (addrK _)): defA => defV.\nsuffices /submxP[W ->]: (V <= C)%MS by rewrite -mul_row_col addsmxE submxMl.\nrewrite diffmxE sub_capmx {1}defV -mulNmx addmx_sub 1?mulmx_sub //.\nby rewrite -capmxE capmxSl.\nQed.\n\nLemma mxrank_cap_compl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A :&: B) + \\rank (A :\\: B))%N = \\rank A.\nProof.\nrewrite addnC -mxrank_disjoint_sum ?addsmx_diff_cap_eq //.\nby rewrite (capmxC A) capmxA capmx_diff cap0mx.\nQed.\n\nLemma mxrank_sum_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A + B) + \\rank (A :&: B) = \\rank A + \\rank B)%N.\nProof.\nset C := (A :&: B)%MS; set D := (A :\\: B)%MS.\nhave rDB: \\rank (A + B)%MS = \\rank (D + B)%MS.\n  apply/eqP; rewrite mxrank_leqif_sup; first by rewrite addsmxS ?diffmxSl.\n  by rewrite addsmx_sub addsmxSr -(addsmx_diff_cap_eq A B) addsmxS ?capmxSr.\nrewrite {1}rDB mxrank_disjoint_sum ?capmx_diff //.\nby rewrite addnC addnA mxrank_cap_compl.\nQed.\n\nLemma mxrank_adds_leqif m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  \\rank (A + B) <= \\rank A + \\rank B ?= iff (A :&: B <= (0 : 'M_n))%MS.\nProof.\nrewrite -mxrank_sum_cap; split; first exact: leq_addr.\nby rewrite addnC (@eqn_add2r _ 0) eq_sym mxrank_eq0 -submx0.\nQed.\n\n(* rank of block matrices with 0s inside *)\n\nLemma rank_col_mx0 m n p (A : 'M_(m, n)) :\n  \\rank (col_mx A (0 : 'M_(p, n))) = \\rank A.\nProof. by rewrite -addsmxE addsmx0. Qed.\n\nLemma rank_col_0mx m n p (A : 'M_(m, n)) :\n  \\rank (col_mx (0 : 'M_(p, n)) A) = \\rank A.\nProof. by rewrite -addsmxE adds0mx. Qed.\n\nLemma rank_row_mx0 m n p (A : 'M_(m, n)) :\n  \\rank (row_mx A (0 : 'M_(m, p))) = \\rank A.\nProof. by rewrite -mxrank_tr -[RHS]mxrank_tr tr_row_mx trmx0 rank_col_mx0. Qed.\n\nLemma rank_row_0mx m n p (A : 'M_(m, n)) :\n  \\rank (row_mx (0 : 'M_(m, p)) A) = \\rank A.\nProof. by rewrite -mxrank_tr -[RHS]mxrank_tr tr_row_mx trmx0 rank_col_0mx. Qed.\n\nLemma rank_diag_block_mx m n p q\n    (A : 'M_(m, n)) (B : 'M_(p, q)) :\n  \\rank (block_mx A 0 0 B) = (\\rank A + \\rank B)%N.\nProof.\nrewrite block_mxEv -addsmxE mxrank_disjoint_sum ?rank_row_mx0 ?rank_row_0mx//.\napply/eqP/rowV0P => v; rewrite sub_capmx => /andP[/submxP[x ->]].\nrewrite mul_mx_row mulmx0 => /submxP[y]; rewrite mul_mx_row mulmx0.\nby move=> /eq_row_mx[-> _]; rewrite row_mx0.\nQed.\n\n(* Subspace projection matrix *)\n\nLemma proj_mx_sub m n U V (W : 'M_(m, n)) : (W *m proj_mx U V <= U)%MS.\nProof. by rewrite !mulmx_sub // -addsmxE addsmx0. Qed.\n\nLemma proj_mx_compl_sub m n U V (W : 'M_(m, n)) :\n  (W <= U + V -> W - W *m proj_mx U V <= V)%MS.\nProof.\nrewrite addsmxE => sWUV; rewrite mulmxA -{1}(mulmxKpV sWUV) -mulmxBr.\nby rewrite mulmx_sub // opp_col_mx add_col_mx subrr subr0 -addsmxE adds0mx.\nQed.\n\nLemma proj_mx_id m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= U)%MS -> W *m proj_mx U V = W.\nProof.\nmove=> dxUV sWU; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?proj_mx_sub //= -eqmx_opp opprB.\nby rewrite proj_mx_compl_sub // (submx_trans sWU) ?addsmxSl.\nQed.\n\nLemma proj_mx_0 m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= V)%MS -> W *m proj_mx U V = 0.\nProof.\nmove=> dxUV sWV; apply/eqP; rewrite -submx0 -dxUV.\nrewrite sub_capmx proj_mx_sub /= -[_ *m _](subrK W) addmx_sub // -eqmx_opp.\nby rewrite opprB proj_mx_compl_sub // (submx_trans sWV) ?addsmxSr.\nQed.\n\nLemma add_proj_mx m n U V (W : 'M_(m, n)) :\n    (U :&: V = 0)%MS -> (W <= U + V)%MS ->\n  W *m proj_mx U V + W *m proj_mx V U = W.\nProof.\nmove=> dxUV sWUV; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite -addrA sub_capmx {2}addrCA -!(opprB W).\nby rewrite !{1}addmx_sub ?proj_mx_sub ?eqmx_opp ?proj_mx_compl_sub // addsmxC.\nQed.\n\nLemma proj_mx_proj n (U V : 'M_n) :\n  let P := proj_mx U V in (U :&: V = 0)%MS -> P *m P = P.\nProof.\nby move=> P dxUV; rewrite -[P in P *m _]mul1mx proj_mx_id ?proj_mx_sub ?mul1mx.\nQed.\n\n(* Completing a partially injective matrix to get a unit matrix. *)\n\nLemma complete_unitmx m n (U : 'M_(m, n)) (f : 'M_n) :\n  \\rank (U *m f) = \\rank U -> {g : 'M_n | g \\in unitmx & U *m f = U *m g}.\nProof.\nmove=> injfU; pose V := <<U>>%MS; pose W := V *m f.\npose g := proj_mx V (V^C)%MS *m f + cokermx V *m row_ebase W.\nhave defW: V *m g = W.\n  rewrite mulmxDr mulmxA proj_mx_id ?genmxE ?capmx_compl //.\n  by rewrite mulmxA mulmx_coker mul0mx addr0.\nexists g; last first.\n  have /submxP[u ->]: (U <= V)%MS by rewrite genmxE.\n  by rewrite -!mulmxA defW.\nrewrite -row_full_unit -sub1mx; apply/submxP.\nhave: (invmx (col_ebase W) *m W <= V *m g)%MS by rewrite defW submxMl.\ncase/submxP=> v def_v; exists (invmx (row_ebase W) *m (v *m V + (V^C)%MS)).\nrewrite -mulmxA mulmxDl -mulmxA -def_v -{3}[W]mulmx_ebase -mulmxA.\nrewrite mulKmx ?col_ebase_unit // [_ *m g]mulmxDr mulmxA.\nrewrite (proj_mx_0 (capmx_compl _)) // mul0mx add0r 2!mulmxA.\nrewrite mulmxK ?row_ebase_unit // copid_mx_id ?rank_leq_row //.\nrewrite (eqmxMr _ (genmxE U)) injfU genmxE addrC -mulmxDl subrK.\nby rewrite mul1mx mulVmx ?row_ebase_unit.\nQed.\n\n(* Two matrices with the same shape represent the same subspace *)\n(* iff they differ only by a change of basis.                   *)\n\nLemma eqmxMunitP m n (U V : 'M_(m, n)) :\n  reflect (exists2 P, P \\in unitmx & U = P *m V) (U == V)%MS.\nProof.\napply: (iffP eqmxP) => [eqUV | [P Punit ->]]; last first.\n  by apply/eqmxMfull; rewrite row_full_unit.\nhave [D defU]: exists D, U = D *m V by apply/submxP; rewrite eqUV.\nhave{eqUV} [Pt Pt_unit defUt]: {Pt | Pt \\in unitmx & V^T *m D^T = V^T *m Pt}.\n  by apply/complete_unitmx; rewrite -trmx_mul -defU !mxrank_tr eqUV.\nby exists Pt^T; last apply/trmx_inj; rewrite ?unitmx_tr // defU !trmx_mul trmxK.\nQed.\n\n(* Mapping between two subspaces with the same dimension. *)\n\nLemma eq_rank_unitmx m1 m2 n (U : 'M_(m1, n)) (V : 'M_(m2, n)) :\n  \\rank U = \\rank V -> {f : 'M_n | f \\in unitmx & V :=: U *m f}%MS.\nProof.\nmove=> eqrUV; pose f := invmx (row_ebase <<U>>%MS) *m row_ebase <<V>>%MS.\nhave defUf: (<<U>> *m f :=: <<V>>)%MS.\n  rewrite -[<<U>>%MS]mulmx_ebase mulmxA mulmxK ?row_ebase_unit // -mulmxA.\n  rewrite genmxE eqrUV -genmxE -{3}[<<V>>%MS]mulmx_ebase -mulmxA.\n  move: (pid_mx _ *m _) => W; apply/eqmxP.\n  by rewrite !eqmxMfull ?andbb // row_full_unit col_ebase_unit.\nhave{defUf} defV: (V :=: U *m f)%MS.\n  by apply/eqmxP; rewrite -!(eqmxMr f (genmxE U)) !defUf !genmxE andbb.\nhave injfU: \\rank (U *m f) = \\rank U by rewrite -defV eqrUV.\nby have [g injg defUg] := complete_unitmx injfU; exists g; rewrite -?defUg.\nQed.\n\n(* maximal rank and full rank submatrices *)\n\nSection MaxRankSubMatrix.\nVariables (m n : nat) (A : 'M_(m, n)).\n\nDefinition maxrankfun : 'I_m ^ \\rank A :=\n  [arg max_(f > finfun (widen_ord (rank_leq_row A))) \\rank (rowsub f A)].\nLocal Notation mxf := maxrankfun.\n\nLemma maxrowsub_free : row_free (rowsub mxf A).\nProof.\nrewrite /mxf; case: arg_maxnP => //= f _ fM; apply/negP => /negP rfA.\nhave [i NriA] : exists i, ~~ (row i A <= rowsub f A)%MS.\n  by apply/row_subPn; apply: contraNN rfA => /mxrankS; rewrite row_leq_rank.\nhave [j rjfA] : exists j, (row (f j) A <= rowsub (f \\o lift j) A)%MS.\n  case/row_freePn: rfA => j.\n  by rewrite row_rowsub row'Esub -mxsub_comp; exists j.\npose g : 'I_m ^ \\rank A := finfun [eta f with j |-> i].\nsuff: (rowsub f A < rowsub g A)%MS by rewrite ltmxErank andbC ltnNge fM.\nrewrite ltmxE; apply/andP; split; last first.\n  apply: contra NriA; apply: submx_trans.\n  by rewrite (eq_row_sub j)// row_rowsub ffunE/= eqxx.\napply/row_subP => k; rewrite !row_rowsub.\nhave [->|/negPf eq_kjF] := eqVneq k j; last first.\n  by rewrite (eq_row_sub k)// row_rowsub ffunE/= eq_kjF.\nrewrite (submx_trans rjfA)// (submx_rowsub (lift j))// => l /=.\nby rewrite ffunE/= eq_sym (negPf (neq_lift _ _)).\nQed.\n\nLemma eq_maxrowsub : (rowsub mxf A :=: A)%MS.\nProof.\napply/eqmxP; rewrite -(eq_leqif (mxrank_leqif_eq _))//.\n  exact: maxrowsub_free.\napply/row_subP => i; apply/submxP; exists (delta_mx 0 (mxf i)).\nby rewrite -rowE; apply/rowP => j; rewrite !mxE.\nQed.\n\nLemma maxrankfun_inj : injective mxf.\nProof.\nmove=> i j eqAij; have /row_free_inj := maxrowsub_free.\nmove=> /(_ 1%N) /(_ (delta_mx 0 i) (delta_mx 0 j)).\nrewrite -!rowE !row_rowsub eqAij => /(_ erefl) /matrixP /(_ 0 i) /eqP.\nby rewrite !mxE eqxx/=; case: (i =P j); rewrite // oner_eq0.\nQed.\n\nVariable (rkA : row_full A).\n\nLemma maxrowsub_full : row_full (rowsub mxf A).\nProof. by rewrite /row_full eq_maxrowsub. Qed.\nHint Resolve maxrowsub_full : core.\n\nDefinition fullrankfun : 'I_m ^ n := finfun (mxf \\o cast_ord (esym (eqP rkA))).\nLocal Notation frf := fullrankfun.\n\nLemma fullrowsub_full : row_full (rowsub frf A).\nProof.\nby rewrite mxsub_ffunl rowsub_comp rowsub_cast esymK row_full_castmx.\nQed.\n\nLemma fullrowsub_unit : rowsub frf A \\in unitmx.\nProof. by rewrite -row_full_unit fullrowsub_full. Qed.\n\nLemma fullrowsub_free : row_free (rowsub frf A).\nProof.  by rewrite row_free_unit fullrowsub_unit. Qed.\n\nLemma mxrank_fullrowsub : \\rank (rowsub frf A) = n.\nProof. exact/eqP/fullrowsub_full. Qed.\n\nLemma eq_fullrowsub : (rowsub frf A :=: A)%MS.\nProof.\nrewrite mxsub_ffunl rowsub_comp rowsub_cast esymK.\nexact: (eqmx_trans (eqmx_cast _ _) eq_maxrowsub).\nQed.\n\nLemma fullrankfun_inj : injective frf.\nProof.\nby move=> i j; rewrite !ffunE => /maxrankfun_inj /(congr1 val)/= /val_inj.\nQed.\n\nEnd MaxRankSubMatrix.\n\nSection SumExpr.\n\n(* This is the infrastructure to support the mxdirect predicate. We use a     *)\n(* bespoke canonical structure to decompose a matrix expression into binary   *)\n(* and n-ary products, using some of the \"quote\" technology. This lets us     *)\n(* characterize direct sums as set sums whose rank is equal to the sum of the *)\n(* ranks of the individual terms. The mxsum_expr/proper_mxsum_expr structures *)\n(* below supply both the decomposition and the calculation of the rank sum.   *)\n(* The mxsum_spec dependent predicate family expresses the consistency of     *)\n(* these two decompositions.                                                  *)\n(*   The main technical difficulty we need to overcome is the fact that       *)\n(* the \"catch-all\" case of canonical structures has a priority lower than     *)\n(* constant expansion. However, it is undesireable that local abbreviations   *)\n(* be opaque for the direct-sum predicate, e.g., not be able to handle        *)\n(* let S := (\\sum_(i | P i) LargeExpression i)%MS in mxdirect S -> ...).      *)\n(*   As in \"quote\", we use the interleaving of constant expansion and         *)\n(* canonical projection matching to achieve our goal: we use a \"wrapper\" type *)\n(* (indeed, the wrapped T type defined in ssrfun.v) with a self-inserting     *)\n(* non-primitive constructor to gain finer control over the type and          *)\n(* structure inference process. The innermost, primitive, constructor flags   *)\n(* trivial sums; it is initially hidden by an eta-expansion, which has been   *)\n(* made into a (default) canonical structure -- this lets type inference      *)\n(* automatically insert this outer tag.                                       *)\n(*   In detail, we define three types                                         *)\n(*  mxsum_spec S r <-> There exists a finite list of matrices A1, ..., Ak     *)\n(*                     such that S is the set sum of the Ai, and r is the sum *)\n(*                     of the ranks of the Ai, i.e., S = (A1 + ... + Ak)%MS   *)\n(*                     and r = \\rank A1 + ... + \\rank Ak. Note that           *)\n(*                     mxsum_spec is a recursive dependent predicate family   *)\n(*                     whose elimination rewrites simultaneaously S, r and    *)\n(*                     the height of S.                                       *)\n(*   proper_mxsum_expr n == The interface for proper sum expressions; this is *)\n(*                     a double-entry interface, keyed on both the matrix sum *)\n(*                     value and the rank sum. The matrix value is restricted *)\n(*                     to square matrices, as the \"+\"%MS operator always      *)\n(*                     returns a square matrix. This interface has two        *)\n(*                     canonical insances, for binary and n-ary sums.         *)\n(*   mxsum_expr m n == The interface for general sum expressions, comprising  *)\n(*                     both proper sums and trivial sums consisting of a      *)\n(*                     single matrix. The key values are WRAPPED as this lets *)\n(*                     us give priority to the \"proper sum\" interpretation    *)\n(*                     (see below). To allow for trivial sums, the matrix key *)\n(*                     can have any dimension. The mxsum_expr interface has   *)\n(*                     two canonical instances, for trivial and proper sums,  *)\n(*                     keyed to the Wrap and wrap constructors, respectively. *)\n(* The projections for the two interfaces above are                           *)\n(*   proper_mxsum_val, mxsum_val : these are respectively coercions to 'M_n   *)\n(*                     and wrapped 'M_(m, n); thus, the matrix sum for an     *)\n(*                     S : mxsum_expr m n can be written unwrap S.            *)\n(*   proper_mxsum_rank, mxsum_rank : projections to the nat and wrapped nat,  *)\n(*                     respectively; the rank sum for S : mxsum_expr m n is   *)\n(*                     thus written unwrap (mxsum_rank S).                    *)\n(* The mxdirect A predicate actually gets A in a phantom argument, which is   *)\n(* used to infer an (implicit) S : mxsum_expr such that unwrap S = A; the     *)\n(* actual definition is \\rank (unwrap S) == unwrap (mxsum_rank S).            *)\n(*   Note that the inference of S is inherently ambiguous: ANY matrix can be  *)\n(* viewed as a trivial sum, including one whose description is manifestly a   *)\n(* proper sum. We use the wrapped type and the interaction between delta      *)\n(* reduction and canonical structure inference to resolve this ambiguity in   *)\n(* favor of proper sums, as follows:                                          *)\n(*    - The phantom type sets up a unification problem of the form            *)\n(*         unwrap (mxsum_val ?S) = A                                          *)\n(*      with unknown evar ?S : mxsum_expr m n.                                *)\n(*    - As the constructor wrap is also a default Canonical instance for the  *)\n(*      wrapped type, so A is immediately replaced with unwrap (wrap A) and   *)\n(*      we get the residual unification problem                               *)\n(*         mxsum_val ?S = wrap A                                              *)\n(*    - Now Coq tries to apply the proper sum Canonical instance, which has   *)\n(*      key projection wrap (proper_mxsum_val ?PS) where ?PS is a fresh evar  *)\n(*      (of type proper_mxsum_expr n). This can only succeed if m = n, and if *)\n(*      a solution can be found to the recursive unification problem          *)\n(*         proper_mxsum_val ?PS = A                                           *)\n(*      This causes Coq to look for one of the two canonical constants for    *)\n(*      proper_mxsum_val (addsmx or bigop) at the head of A, delta-expanding  *)\n(*      A as needed, and then inferring recursively mxsum_expr structures for *)\n(*      the last argument(s) of that constant.                                *)\n(*    - If the above step fails then the wrap constant is expanded, revealing *)\n(*      the primitive Wrap constructor; the unification problem now becomes   *)\n(*         mxsum_val ?S = Wrap A                                              *)\n(*      which fits perfectly the trivial sum canonical structure, whose key   *)\n(*      projection is Wrap ?B where ?B is a fresh evar. Thus the inference    *)\n(*      succeeds, and returns the trivial sum.                                *)\n(* Note that the rank projections also register canonical values, so that the *)\n(* same process can be used to infer a sum structure from the rank sum. In    *)\n(* that case, however, there is no ambiguity and the inference can fail,      *)\n(* because the rank sum for a trivial sum is not an arbitrary integer -- it   *)\n(* must be of the form \\rank ?B. It is nevertheless necessary to use the      *)\n(* wrapped nat type for the rank sums, because in the non-trivial case the    *)\n(* head constant of the nat expression is determined by the proper_mxsum_expr *)\n(* canonical structure, so the mxsum_expr structure must use a generic        *)\n(* constant, namely wrap.                                                     *)\n\nInductive mxsum_spec n : forall m, 'M[F]_(m, n) -> nat -> Prop :=\n | TrivialMxsum m A\n    : @mxsum_spec n m A (\\rank A)\n | ProperMxsum m1 m2 T1 T2 r1 r2 of\n      @mxsum_spec n m1 T1 r1 & @mxsum_spec n m2 T2 r2\n    : mxsum_spec (T1 + T2)%MS (r1 + r2)%N.\nArguments mxsum_spec {n%N m%N} T%MS r%N.\n\nStructure mxsum_expr m n := Mxsum {\n  mxsum_val :> wrapped 'M_(m, n);\n  mxsum_rank : wrapped nat;\n  _ : mxsum_spec (unwrap mxsum_val) (unwrap mxsum_rank)\n}.\n\nCanonical trivial_mxsum m n A :=\n  @Mxsum m n (Wrap A) (Wrap (\\rank A)) (TrivialMxsum A).\n\nStructure proper_mxsum_expr n := ProperMxsumExpr {\n  proper_mxsum_val :> 'M_n;\n  proper_mxsum_rank : nat;\n  _ : mxsum_spec proper_mxsum_val proper_mxsum_rank\n}.\n\nDefinition proper_mxsumP n (S : proper_mxsum_expr n) :=\n  let: ProperMxsumExpr _ _ termS := S return mxsum_spec S (proper_mxsum_rank S)\n  in termS.\n\nCanonical sum_mxsum n (S : proper_mxsum_expr n) :=\n  @Mxsum n n (wrap (S : 'M_n)) (wrap (proper_mxsum_rank S)) (proper_mxsumP S).\n\nSection Binary.\nVariable (m1 m2 n : nat) (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n).\nFact binary_mxsum_proof :\n  mxsum_spec (unwrap S1 + unwrap S2)\n             (unwrap (mxsum_rank S1) + unwrap (mxsum_rank S2)).\nProof. by case: S1 S2 => [A1 r1 A1P] [A2 r2 A2P]; right. Qed.\nCanonical binary_mxsum_expr := ProperMxsumExpr binary_mxsum_proof.\nEnd Binary.\n\nSection Nary.\nContext J (r : seq J) (P : pred J) n (S_ : J -> mxsum_expr n n).\nFact nary_mxsum_proof :\n  mxsum_spec (\\sum_(j <- r | P j) unwrap (S_ j))\n             (\\sum_(j <- r | P j) unwrap (mxsum_rank (S_ j))).\nProof.\nelim/big_rec2: _ => [|j]; first by rewrite -(mxrank0 n n); left.\nby case: (S_ j); right.\nQed.\nCanonical nary_mxsum_expr := ProperMxsumExpr nary_mxsum_proof.\nEnd Nary.\n\nDefinition mxdirect_def m n T of phantom 'M_(m, n) (unwrap (mxsum_val T)) :=\n  \\rank (unwrap T) == unwrap (mxsum_rank T).\n\nEnd SumExpr.\n\nNotation mxdirect A := (mxdirect_def (Phantom 'M_(_,_) A%MS)).\n\nLemma mxdirectP n (S : proper_mxsum_expr n) :\n  reflect (\\rank S = proper_mxsum_rank S) (mxdirect S).\nProof. exact: eqnP. Qed.\nArguments mxdirectP {n S}.\n\nLemma mxdirect_trivial m n A : mxdirect (unwrap (@trivial_mxsum m n A)).\nProof. exact: eqxx. Qed.\n\nLemma mxrank_sum_leqif m n (S : mxsum_expr m n) :\n  \\rank (unwrap S) <= unwrap (mxsum_rank S) ?= iff mxdirect (unwrap S).\nProof.\nrewrite /mxdirect_def; case: S => [[A] [r] /= defAr]; split=> //=.\nelim: m A r / defAr => // m1 m2 A1 A2 r1 r2 _ leAr1 _ leAr2.\nby apply: leq_trans (leq_add leAr1 leAr2); rewrite mxrank_adds_leqif.\nQed.\n\nLemma mxdirectE m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) == unwrap (mxsum_rank S)).\nProof. by []. Qed.\n\nLemma mxdirectEgeq m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) >= unwrap (mxsum_rank S)).\nProof. by rewrite (geq_leqif (mxrank_sum_leqif S)). Qed.\n\nSection BinaryDirect.\n\nVariables m1 m2 n : nat.\n\nLemma mxdirect_addsE (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n) :\n   mxdirect (unwrap S1 + unwrap S2)\n    = [&& mxdirect (unwrap S1), mxdirect (unwrap S2)\n        & unwrap S1 :&: unwrap S2 == 0]%MS.\nProof.\nrewrite (@mxdirectE n) /=.\nhave:= leqif_add (mxrank_sum_leqif S1) (mxrank_sum_leqif S2).\nmove/(leqif_trans (mxrank_adds_leqif (unwrap S1) (unwrap S2)))=> ->.\nby rewrite andbC -andbA submx0.\nQed.\n\nLemma mxdirect_addsP (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B = 0)%MS (mxdirect (A + B)).\nProof. by rewrite mxdirect_addsE !mxdirect_trivial; apply: eqP. Qed.\n\nEnd BinaryDirect.\n\nSection NaryDirect.\n\nVariables (P : pred I) (n : nat).\n\nLet TIsum A_ i := (A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0 :> 'M_n)%MS.\n\nLet mxdirect_sums_recP (S_ : I -> mxsum_expr n n) :\n  reflect (forall i, P i -> mxdirect (unwrap (S_ i)) /\\ TIsum (unwrap \\o S_) i)\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\nrewrite /TIsum; apply: (iffP eqnP) => /= [dxS i Pi | dxS].\n  set Si' := (\\sum_(j | _) unwrap (S_ j))%MS.\n  have: mxdirect (unwrap (S_ i) + Si') by apply/eqnP; rewrite /= -!(bigD1 i).\n  by rewrite mxdirect_addsE => /and3P[-> _ /eqP].\nset Q := P; have [m] := ubnP #|Q|; have: Q \\subset P by [].\nelim: m Q => // m IHm Q /subsetP-sQP.\ncase: (pickP Q) => [i Qi | Q0]; last by rewrite !big_pred0 ?mxrank0.\nrewrite (cardD1x Qi) !((bigD1 i) Q) //=.\nmove/IHm=> <- {IHm}/=; last by apply/subsetP=> j /andP[/sQP].\ncase: (dxS i (sQP i Qi)) => /eqnP=> <- TiQ_0; rewrite mxrank_disjoint_sum //.\napply/eqP; rewrite -submx0 -{2}TiQ_0 capmxS //=.\nby apply/sumsmx_subP=> j /= /andP[Qj i'j]; rewrite (sumsmx_sup j) ?[P j]sQP.\nQed.\n\nLemma mxdirect_sumsP (A_ : I -> 'M_n) :\n  reflect (forall i, P i -> A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0)%MS\n          (mxdirect (\\sum_(i | P i) A_ i)).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => dxA i /dxA; first by case.\nby rewrite mxdirect_trivial.\nQed.\n\nLemma mxdirect_sumsE (S_ : I -> mxsum_expr n n) (xunwrap := unwrap) :\n  reflect (and (forall i, P i -> mxdirect (unwrap (S_ i)))\n               (mxdirect (\\sum_(i | P i) (xunwrap (S_ i)))))\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => [dxS | [dxS_ dxS] i Pi].\n  by do [split; last apply/mxdirect_sumsP] => i; case/dxS.\nby split; [apply: dxS_ | apply: mxdirect_sumsP Pi].\nQed.\n\nEnd NaryDirect.\n\nSection SubDaddsmx.\n\nVariables m m1 m2 n : nat.\nVariables (A : 'M[F]_(m, n)) (B1 : 'M[F]_(m1, n)) (B2 : 'M[F]_(m2, n)).\n\nVariant sub_daddsmx_spec : Prop :=\n  SubDaddsmxSpec A1 A2 of (A1 <= B1)%MS & (A2 <= B2)%MS & A = A1 + A2\n                        & forall C1 C2, (C1 <= B1)%MS -> (C2 <= B2)%MS ->\n                          A = C1 + C2 -> C1 = A1 /\\ C2 = A2.\n\nLemma sub_daddsmx : (B1 :&: B2 = 0)%MS -> (A <= B1 + B2)%MS -> sub_daddsmx_spec.\nProof.\nmove=> dxB /sub_addsmxP[u defA].\nexists (u.1 *m B1) (u.2 *m B2); rewrite ?submxMl // => C1 C2 sCB1 sCB2.\nmove/(canLR (addrK _)) => defC1.\nsuffices: (C2 - u.2 *m B2 <= B1 :&: B2)%MS.\n  by rewrite dxB submx0 subr_eq0 -defC1 defA; move/eqP->; rewrite addrK.\nrewrite sub_capmx -opprB -{1}(canLR (addKr _) defA) -addrA defC1.\nby rewrite !(eqmx_opp, addmx_sub) ?submxMl.\nQed.\n\nEnd SubDaddsmx.\n\nSection SubDsumsmx.\n\nVariables (P : pred I) (m n : nat) (A : 'M[F]_(m, n)) (B : I -> 'M[F]_n).\n\nVariant sub_dsumsmx_spec : Prop :=\n  SubDsumsmxSpec A_ of forall i, P i -> (A_ i <= B i)%MS\n                        & A = \\sum_(i | P i) A_ i\n                        & forall C, (forall i, P i -> C i <= B i)%MS ->\n                          A = \\sum_(i | P i) C i -> {in SimplPred P, C =1 A_}.\n\nLemma sub_dsumsmx :\n    mxdirect (\\sum_(i | P i) B i) -> (A <= \\sum_(i | P i) B i)%MS ->\n  sub_dsumsmx_spec.\nProof.\nmove/mxdirect_sumsP=> dxB /sub_sumsmxP[u defA].\npose A_ i := u i *m B i.\nexists A_ => //= [i _ | C sCB defAC i Pi]; first exact: submxMl.\napply/eqP; rewrite -subr_eq0 -submx0 -{dxB}(dxB i Pi) /=.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?submxMl ?sCB //=.\nrewrite -(subrK A (C i)) -addrA -opprB addmx_sub ?eqmx_opp //.\n  rewrite addrC defAC (bigD1 i) // addKr /= summx_sub // => j Pi'j.\n  by rewrite (sumsmx_sup j) ?sCB //; case/andP: Pi'j.\nrewrite addrC defA (bigD1 i) // addKr /= summx_sub // => j Pi'j.\nby rewrite (sumsmx_sup j) ?submxMl.\nQed.\n\nEnd SubDsumsmx.\n\nSection Eigenspace.\n\nVariables (n : nat) (g : 'M_n).\n\nDefinition eigenspace a := kermx (g - a%:M).\nDefinition eigenvalue : pred F := fun a => eigenspace a != 0.\n\nLemma eigenspaceP a m (W : 'M_(m, n)) :\n  reflect (W *m g = a *: W) (W <= eigenspace a)%MS.\nProof. by rewrite sub_kermx mulmxBr subr_eq0 mul_mx_scalar; apply/eqP. Qed.\n\nLemma eigenvalueP a :\n  reflect (exists2 v : 'rV_n, v *m g = a *: v & v != 0) (eigenvalue a).\nProof. by apply: (iffP (rowV0Pn _)) => [] [v]; move/eigenspaceP; exists v. Qed.\n\nLemma eigenvectorP {v : 'rV_n} :\n  reflect (exists a, (v <= eigenspace a)%MS) (stablemx v g).\nProof. by apply: (iffP (sub_rVP _ _)) => -[a] /eigenspaceP; exists a. Qed.\n\nLemma mxdirect_sum_eigenspace (P : pred I) a_ :\n  {in P &, injective a_} -> mxdirect (\\sum_(i | P i) eigenspace (a_ i)).\nProof.\nhave [m] := ubnP #|P|; elim: m P => // m IHm P lePm inj_a.\napply/mxdirect_sumsP=> i Pi; apply/eqP/rowV0P => v.\nrewrite sub_capmx => /andP[/eigenspaceP def_vg].\nset Vi' := (\\sum_(i | _) _)%MS => Vi'v.\nhave dxVi': mxdirect Vi'.\n  rewrite (cardD1x Pi) in lePm; apply: IHm => //.\n  by apply: sub_in2 inj_a => j /andP[].\ncase/sub_dsumsmx: Vi'v => // u Vi'u def_v _.\nrewrite def_v big1 // => j Pi'j; apply/eqP.\nhave nz_aij: a_ i - a_ j != 0.\n  by case/andP: Pi'j => Pj ne_ji; rewrite subr_eq0 eq_sym (inj_in_eq inj_a).\ncase: (sub_dsumsmx dxVi' (sub0mx 1 _)) => C _ _ uniqC.\nrewrite -(eqmx_eq0 (eqmx_scale _ nz_aij)).\nrewrite (uniqC (fun k => (a_ i - a_ k) *: u k)) => // [|k Pi'k|].\n- by rewrite -(uniqC (fun _ => 0)) ?big1 // => k Pi'k; apply: sub0mx.\n- by rewrite scalemx_sub ?Vi'u.\nrewrite -{1}(subrr (v *m g)) {1}def_vg def_v scaler_sumr mulmx_suml -sumrB.\nby apply: eq_bigr => k /Vi'u/eigenspaceP->; rewrite scalerBl.\nQed.\n\nEnd Eigenspace.\n\nEnd RowSpaceTheory.\n\n#[global] Hint Resolve submx_refl : core.\nArguments submxP {F m1 m2 n A B}.\nArguments eq_row_sub [F m n v A].\nArguments row_subP {F m1 m2 n A B}.\nArguments rV_subP {F m1 m2 n A B}.\nArguments row_subPn {F m1 m2 n A B}.\nArguments sub_rVP {F n u v}.\nArguments rV_eqP {F m1 m2 n A B}.\nArguments rowV0Pn {F m n A}.\nArguments rowV0P {F m n A}.\nArguments eqmx0P {F m n A}.\nArguments row_fullP {F m n A}.\nArguments row_freeP {F m n A}.\nArguments eqmxP {F m1 m2 n A B}.\nArguments genmxP {F m1 m2 n A B}.\nArguments addsmx_idPr {F m1 m2 n A B}.\nArguments addsmx_idPl {F m1 m2 n A B}.\nArguments sub_addsmxP {F m1 m2 m3 n A B C}.\nArguments sumsmx_sup [F I] i0 [P m n A B_].\nArguments sumsmx_subP {F I P m n A_ B}.\nArguments sub_sumsmxP {F I P m n A B_}.\nArguments sub_kermxP {F p m n A B}.\nArguments capmx_idPr {F n m1 m2 A B}.\nArguments capmx_idPl {F n m1 m2 A B}.\nArguments bigcapmx_inf [F I] i0 [P m n A_ B].\nArguments sub_bigcapmxP {F I P m n A B_}.\nArguments mxrank_injP {F m n} p {A f}.\nArguments mxdirectP {F n S}.\nArguments mxdirect_addsP {F m1 m2 n A B}.\nArguments mxdirect_sumsP {F I P n A_}.\nArguments mxdirect_sumsE {F I P n S_}.\nArguments eigenspaceP {F n g a m W}.\nArguments eigenvalueP {F n g a}.\nArguments submx_rowsub [F m1 m2 m3 n] h [f g A] _ : rename.\nArguments eqmx_rowsub [F m1 m2 m3 n] h [f g A] _ : rename.\n\nArguments mxrank {F m%N n%N} A%MS.\nArguments complmx {F m%N n%N} A%MS.\nArguments row_full {F m%N n%N} A%MS.\nArguments submx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments ltmx {F m1%N m2%N n%N} A%MS B%MS.\nArguments eqmx {F m1%N m2%N n%N} A%MS B%MS.\nArguments addsmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments capmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments diffmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments genmx {F m%N n%N} A%R : rename.\nNotation \"\\rank A\" := (mxrank A) : nat_scope.\nNotation \"<< A >>\" := (genmx A) : matrix_set_scope.\nNotation \"A ^C\" := (complmx A) : matrix_set_scope.\nNotation \"A <= B\" := (submx A B) : matrix_set_scope.\nNotation \"A < B\" := (ltmx A B) : matrix_set_scope.\nNotation \"A <= B <= C\" := ((submx A B) && (submx B C)) : matrix_set_scope.\nNotation \"A < B <= C\" := (ltmx A B && submx B C) : matrix_set_scope.\nNotation \"A <= B < C\" := (submx A B && ltmx B C) : matrix_set_scope.\nNotation \"A < B < C\" := (ltmx A B && ltmx B C) : matrix_set_scope.\nNotation \"A == B\" := ((submx A B) && (submx B A)) : matrix_set_scope.\nNotation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\nNotation \"A + B\" := (addsmx A B) : matrix_set_scope.\nNotation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nNotation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\nNotation mxdirect S := (mxdirect_def (Phantom 'M_(_,_) S%MS)).\n\nNotation \"\\sum_ ( i <- r | P ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i | P ) B\" :=\n  (\\big[addsmx/0%R]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ i B\" :=\n  (\\big[addsmx/0%R]_i B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i : t | P ) B\" :=\n  (\\big[addsmx/0%R]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i : t ) B\" :=\n  (\\big[addsmx/0%R]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i < n ) B\" :=\n  (\\big[addsmx/0%R]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A | P ) B\" :=\n  (\\big[addsmx/0%R]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A ) B\" :=\n  (\\big[addsmx/0%R]_(i in A) B%MS) : matrix_set_scope.\n\nNotation \"\\bigcap_ ( i <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i | P ) B\" :=\n  (\\big[capmx/1%:M]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ i B\" :=\n  (\\big[capmx/1%:M]_i B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t | P ) B\" :=\n  (\\big[capmx/1%:M]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t ) B\" :=\n  (\\big[capmx/1%:M]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n ) B\" :=\n  (\\big[capmx/1%:M]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A | P ) B\" :=\n  (\\big[capmx/1%:M]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A ) B\" :=\n  (\\big[capmx/1%:M]_(i in A) B%MS) : matrix_set_scope.\n\nNotation stablemx V f := (V%MS *m f%R <= V%MS)%MS.\n\nSection Stability.\n\nVariable (F : fieldType).\n\nLemma eqmx_stable m m' n (V : 'M[F]_(m, n)) (V' : 'M[F]_(m', n)) (f : 'M[F]_n) :\n  (V :=: V')%MS -> stablemx V f = stablemx V' f.\nProof. by move=> eqVV'; rewrite (eqmxMr _ eqVV') eqVV'. Qed.\n\nSection FixedDim.\n\nVariables (m n : nat) (V W : 'M[F]_(m, n)) (f g : 'M[F]_n).\n\nLemma stablemx_row_base : (stablemx (row_base V) f) = (stablemx V f).\nProof. by apply: eqmx_stable; apply: eq_row_base. Qed.\n\nLemma stablemx_full : row_full V -> stablemx V f. Proof. exact: submx_full. Qed.\n\nLemma stablemxM : stablemx V f -> stablemx V g -> stablemx V (f *m g).\nProof. by move=> f_stab /(submx_trans _)->//; rewrite mulmxA submxMr. Qed.\n\nLemma stablemxD : stablemx V f -> stablemx V g -> stablemx V (f + g).\nProof. by move=> f_stab g_stab; rewrite mulmxDr addmx_sub. Qed.\n\nLemma stablemxN : stablemx V (- f) = stablemx V f.\nProof. by rewrite mulmxN eqmx_opp. Qed.\n\nLemma stablemxC x : stablemx V x%:M.\nProof. by rewrite mul_mx_scalar scalemx_sub. Qed.\n\nLemma stablemx0 : stablemx V 0. Proof. by rewrite mulmx0 sub0mx. Qed.\n\nLemma stableDmx : stablemx V f -> stablemx W f -> stablemx (V + W)%MS f.\nProof. by move=> fV fW; rewrite addsmxMr addsmxS. Qed.\n\nLemma stableNmx : stablemx (- V) f = stablemx V f.\nProof. by rewrite mulNmx !eqmx_opp. Qed.\n\nLemma stable0mx : stablemx (0 : 'M_(m, n)) f. Proof. by rewrite mul0mx. Qed.\n\nEnd FixedDim.\n\nLemma stableCmx (m n : nat) x (f : 'M[F]_(m, n)) : stablemx x%:M f.\nProof.\nhave [->|x_neq0] := eqVneq x 0; first by rewrite mul_scalar_mx scale0r sub0mx.\nby rewrite -![x%:M]scalemx1 eqmx_scale// submx_full// -sub1mx.\nQed.\n\nLemma stablemx_sums (n : nat) (I : finType) (V_ : I -> 'M[F]_n) (f : 'M_n) :\n  (forall i, stablemx (V_ i) f) -> stablemx (\\sum_i V_ i)%MS f.\nProof.\nby move=> fV; rewrite sumsmxMr; apply/sumsmx_subP => i; rewrite (sumsmx_sup i).\nQed.\n\nLemma stablemx_unit (n : nat) (V f : 'M[F]_n) : V \\in unitmx -> stablemx V f.\nProof. by move=> Vunit; rewrite submx_full ?row_full_unit. Qed.\n\nSection Commutation.\n\nVariable (n : nat).\nImplicit Types (f g : 'M[F]_n).\n\nLemma comm_mx_stable (f g : 'M[F]_n) : comm_mx f g -> stablemx f g.\nProof. by move=> comm_fg; rewrite [_ *m _]comm_fg mulmx_sub. Qed.\n\nLemma comm_mx_stable_ker (f g : 'M[F]_n) :\n  comm_mx f g -> stablemx (kermx f) g.\nProof.\nmove=> comm_fg; apply/sub_kermxP.\nby rewrite -mulmxA -[g *m _]comm_fg mulmxA mulmx_ker mul0mx.\nQed.\n\nLemma comm_mx_stable_eigenspace (f g : 'M[F]_n) a :\n  comm_mx f g -> stablemx (eigenspace f a) g.\nProof.\nmove=> cfg; rewrite comm_mx_stable_ker//.\nby apply/comm_mx_sym/comm_mxB => //; apply:comm_mx_scalar.\nQed.\n\nEnd Commutation.\n\nEnd Stability.\n\nSection DirectSums.\nVariables (F : fieldType) (I : finType) (P : pred I).\n\nLemma mxdirect_delta n f : {in P &, injective f} ->\n  mxdirect (\\sum_(i | P i) <<delta_mx 0 (f i) : 'rV[F]_n>>).\nProof.\npose fP := image f P => Uf; have UfP: uniq fP by apply/dinjectiveP.\nsuffices /mxdirectP : mxdirect (\\sum_i <<delta_mx 0 i : 'rV[F]_n>>).\n  rewrite /= !(bigID [in fP] predT) -!big_uniq //= !big_map !big_enum.\n  by move/mxdirectP; rewrite mxdirect_addsE => /andP[].\napply/mxdirectP=> /=; transitivity (mxrank (1%:M : 'M[F]_n)).\n  apply/eqmx_rank; rewrite submx1 mx1_sum_delta summx_sub_sums // => i _.\n  by rewrite -(mul_delta_mx (0 : 'I_1)) genmxE submxMl.\nrewrite mxrank1 -[LHS]card_ord -sum1_card.\nby apply/eq_bigr=> i _; rewrite /= mxrank_gen mxrank_delta.\nQed.\n\nEnd DirectSums.\n\nSection CardGL.\n\nVariable F : finFieldType.\n\nLemma card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite big_nat_rev big_add1 -triangular_sum expn_sum -big_split /=.\npose fr m := [pred A : 'M[F]_(m, n) | \\rank A == m].\nset m := n; rewrite [in m.+1]/m; transitivity #|fr m|.\n  by rewrite cardsT /= card_sub; apply: eq_card => A; rewrite -row_free_unit.\nhave: m <= n by []; elim: m => [_ | m IHm /ltnW-le_mn].\n  rewrite (@eq_card1 _ (0 : 'M_(0, n))) ?big_geq //= => A.\n  by rewrite flatmx0 !inE !eqxx.\nrewrite big_nat_recr // -{}IHm //= !subSS mulnBr muln1 -expnD subnKC //.\nrewrite -sum_nat_const /= -sum1_card -add1n.\nrewrite (partition_big dsubmx (fr m)) /= => [|A]; last first.\n  rewrite !inE -{1}(vsubmxK A); move: {A}(_ A) (_ A) => Ad Au Afull.\n  rewrite eqn_leq rank_leq_row -(leq_add2l (\\rank Au)) -mxrank_sum_cap.\n  rewrite {1 3}[@mxrank]lock addsmxE (eqnP Afull) -lock -addnA.\n  by rewrite leq_add ?rank_leq_row ?leq_addr.\napply: eq_bigr => A rAm; rewrite (reindex (col_mx^~ A)) /=; last first.\n  exists usubmx => [v _ | vA]; first by rewrite col_mxKu.\n  by case/andP=> _ /eqP <-; rewrite vsubmxK.\ntransitivity #|~: [set v *m A | v in 'rV_m]|; last first.\n  rewrite cardsCs setCK card_imset ?card_mx ?card_ord ?mul1n //.\n  have [B AB1] := row_freeP rAm; apply: can_inj (mulmx^~ B) _ => v.\n  by rewrite -mulmxA AB1 mulmx1.\nrewrite -sum1_card; apply: eq_bigl => v; rewrite !inE col_mxKd eqxx.\nrewrite andbT eqn_leq rank_leq_row /= -(leq_add2r (\\rank (v :&: A)%MS)).\nrewrite -addsmxE mxrank_sum_cap (eqnP rAm) addnAC leq_add2r.\nrewrite (ltn_leqif (mxrank_leqif_sup _)) ?capmxSl // sub_capmx submx_refl.\nby congr (~~ _); apply/submxP/imsetP=> [] [u]; exists u.\nQed.\n\n(* An alternate, somewhat more elementary proof, that does not rely on the *)\n(* row-space theory, but directly performs the LUP decomposition.          *)\nLemma LUP_card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite cardsT /= card_sub /GRing.unit /= big_add1 /= -triangular_sum -/n.\nelim: {n'}n => [|n IHn].\n  rewrite !big_geq // mul1n (@eq_card _ _ predT) ?card_mx //= => M.\n  by rewrite {1}[M]flatmx0 -(flatmx0 1%:M) unitmx1.\nrewrite !big_nat_recr //= expnD mulnAC mulnA -{}IHn -mulnA mulnC.\nset LHS := #|_|; rewrite -[n.+1]muln1 -{2}[n]mul1n {}/LHS.\nrewrite -!card_mx subn1 -(cardC1 0) -mulnA; set nzC := predC1 _.\nrewrite -sum1_card (partition_big lsubmx nzC) => [|A]; last first.\n  rewrite unitmxE unitfE; apply: contra; move/eqP=> v0.\n  rewrite -[A]hsubmxK v0 -[n.+1]/(1 + n)%N -col_mx0.\n  rewrite -[rsubmx _]vsubmxK -det_tr tr_row_mx !tr_col_mx !trmx0.\n  by rewrite det_lblock [0]mx11_scalar det_scalar1 mxE mul0r.\nrewrite -sum_nat_const; apply: eq_bigr => /= v /cV0Pn[k nza].\nhave xrkK: involutive (@xrow F _ _ 0 k).\n  by move=> m A /=; rewrite /xrow -row_permM tperm2 row_perm1.\nrewrite (reindex_inj (inv_inj (xrkK (1 + n)%N))) /= -[n.+1]/(1 + n)%N.\nrewrite (partition_big ursubmx xpredT) //= -sum_nat_const.\napply: eq_bigr => u _; set a : F := v _ _ in nza.\nset v1 : 'cV_(1 + n) := xrow 0 k v.\nhave def_a: usubmx v1 = a%:M.\n  by rewrite [_ v1]mx11_scalar mxE lshift0 mxE tpermL.\npose Schur := dsubmx v1 *m (a^-1 *: u).\npose L : 'M_(1 + n) := block_mx a%:M 0 (dsubmx v1) 1%:M.\npose U B : 'M_(1 + n) := block_mx 1 (a^-1 *: u) 0 B.\nrewrite (reindex (fun B => L *m U B)); last first.\n  exists (fun A1 => drsubmx A1 - Schur) => [B _ | A1].\n    by rewrite mulmx_block block_mxKdr mul1mx addrC addKr.\n  rewrite !inE mulmx_block !mulmx0 mul0mx !mulmx1 !addr0 mul1mx addrC subrK.\n  rewrite mul_scalar_mx scalerA divff // scale1r andbC; case/and3P => /eqP <- _.\n  rewrite -{1}(hsubmxK A1) xrowE mul_mx_row row_mxKl -xrowE => /eqP def_v.\n  rewrite -def_a block_mxEh vsubmxK /v1 -def_v xrkK.\n  apply: trmx_inj; rewrite tr_row_mx tr_col_mx trmx_ursub trmx_drsub trmx_lsub.\n  by rewrite hsubmxK vsubmxK.\nrewrite -sum1_card; apply: eq_bigl => B; rewrite xrowE unitmxE.\nrewrite !det_mulmx unitrM -unitmxE unitmx_perm det_lblock det_ublock.\nrewrite !det_scalar1 det1 mulr1 mul1r unitrM unitfE nza -unitmxE.\nrewrite mulmx_block !mulmx0 mul0mx !addr0 !mulmx1 mul1mx block_mxKur.\nrewrite mul_scalar_mx scalerA divff // scale1r eqxx andbT.\nby rewrite block_mxEh mul_mx_row row_mxKl -def_a vsubmxK -xrowE xrkK eqxx andbT.\nQed.\n\nLemma card_GL_1 : #|'GL_1[F]| = #|F|.-1.\nProof. by rewrite card_GL // mul1n big_nat1 expn1 subn1. Qed.\n\nLemma card_GL_2 : #|'GL_2[F]| = (#|F| * #|F|.-1 ^ 2 * #|F|.+1)%N.\nProof.\nrewrite card_GL // big_ltn // big_nat1 expn1 -(addn1 #|F|) -subn1 -!mulnA.\nby rewrite -subn_sqr.\nQed.\n\nEnd CardGL.\n\nLemma logn_card_GL_p n p : prime p -> logn p #|'GL_n(p)| = 'C(n, 2).\nProof.\nmove=> p_pr; have p_gt1 := prime_gt1 p_pr.\nhave p_i_gt0: p ^ _ > 0 by move=> i; rewrite expn_gt0 ltnW.\nrewrite (card_GL _ (ltn0Sn n.-1)) card_ord Fp_cast // big_add1 /=.\npose p'gt0 m := m > 0 /\\ logn p m = 0%N.\nsuffices [Pgt0 p'P]: p'gt0 (\\prod_(0 <= i < n.-1.+1) (p ^ i.+1 - 1))%N.\n  by rewrite lognM // p'P pfactorK // addn0; case n.\napply: big_ind => [|m1 m2 [m10 p'm1] [m20]|i _]; rewrite {}/p'gt0 ?logn1 //.\n  by rewrite muln_gt0 m10 lognM ?p'm1.\nrewrite lognE -if_neg subn_gt0 p_pr /= -{1 2}(exp1n i.+1) ltn_exp2r // p_gt1.\nby rewrite dvdn_subr ?dvdn_exp // gtnNdvd.\nQed.\n\nSection MatrixAlgebra.\n\nVariables F : fieldType.\n\nLocal Notation \"A \\in R\" := (@submx F _ _ _ (mxvec A) R).\n\nLemma mem0mx m n (R : 'A_(m, n)) : 0 \\in R.\nProof. by rewrite linear0 sub0mx. Qed.\n\nLemma memmx0 n A : (A \\in (0 : 'A_n)) -> A = 0.\nProof. by rewrite submx0 mxvec_eq0; move/eqP. Qed.\n\nLemma memmx1 n (A : 'M_n) : (A \\in mxvec 1%:M) = is_scalar_mx A.\nProof.\napply/sub_rVP/is_scalar_mxP=> [[a] | [a ->]].\n  by rewrite -linearZ scale_scalar_mx mulr1 => /(can_inj mxvecK); exists a.\nby exists a; rewrite -linearZ scale_scalar_mx mulr1.\nQed.\n\nLemma memmx_subP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, A \\in R1 -> A \\in R2) (R1 <= R2)%MS.\nProof.\napply: (iffP idP) => [sR12 A R1_A | sR12]; first exact: submx_trans sR12.\nby apply/rV_subP=> vA; rewrite -(vec_mxK vA); apply: sR12.\nQed.\nArguments memmx_subP {m1 m2 n R1 R2}.\n\nLemma memmx_eqP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, (A \\in R1) = (A \\in R2)) (R1 == R2)%MS.\nProof.\napply: (iffP eqmxP) => [eqR12 A | eqR12]; first by rewrite eqR12.\nby apply/eqmxP/rV_eqP=> vA; rewrite -(vec_mxK vA) eqR12.\nQed.\nArguments memmx_eqP {m1 m2 n R1 R2}.\n\nLemma memmx_addsP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists D, [/\\ D.1 \\in R1, D.2 \\in R2 & A = D.1 + D.2])\n          (A \\in R1 + R2)%MS.\nProof.\napply: (iffP sub_addsmxP) => [[u /(canRL mxvecK)->] | [D []]].\n  exists (vec_mx (u.1 *m R1), vec_mx (u.2 *m R2)).\n  by rewrite /= linearD !vec_mxK !submxMl.\ncase/submxP=> u1 defD1 /submxP[u2 defD2] ->.\nby exists (u1, u2); rewrite linearD /= defD1 defD2.\nQed.\nArguments memmx_addsP {m1 m2 n A R1 R2}.\n\nLemma memmx_sumsP (I : finType) (P : pred I) n (A : 'M_n) R_ :\n  reflect (exists2 A_, A = \\sum_(i | P i) A_ i & forall i, A_ i \\in R_ i)\n          (A \\in \\sum_(i | P i) R_ i)%MS.\nProof.\napply: (iffP sub_sumsmxP) => [[C defA] | [A_ -> R_A] {A}].\n  exists (fun i => vec_mx (C i *m R_ i)) => [|i].\n    by rewrite -linear_sum -defA /= mxvecK.\n  by rewrite vec_mxK submxMl.\nexists (fun i => mxvec (A_ i) *m pinvmx (R_ i)).\nby rewrite linear_sum; apply: eq_bigr => i _; rewrite mulmxKpV.\nQed.\nArguments memmx_sumsP {I P n A R_}.\n\nLemma has_non_scalar_mxP m n (R : 'A_(m, n)) :\n    (1%:M \\in R)%MS ->\n  reflect (exists2 A, A \\in R & ~~ is_scalar_mx A)%MS (1 < \\rank R).\nProof.\ncase: (posnP n) => [-> | n_gt0] in R *; set S := mxvec _ => sSR.\n  by rewrite [R]thinmx0 mxrank0; right; case; rewrite /is_scalar_mx ?insubF.\nhave rankS: \\rank S = 1%N.\n  apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0 mxvec_eq0.\n  by rewrite -mxrank_eq0 mxrank1 -lt0n.\nrewrite -{2}rankS (ltn_leqif (mxrank_leqif_sup sSR)).\napply: (iffP idP) => [/row_subPn[i] | [A sAR]].\n  rewrite -[row i R]vec_mxK memmx1; set A := vec_mx _ => nsA.\n  by exists A; rewrite // vec_mxK row_sub.\nby rewrite -memmx1; apply/contra/submx_trans.\nQed.\n\nDefinition mulsmx m1 m2 n (R1 : 'A[F]_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (\\sum_i <<R1 *m lin_mx (mulmxr (vec_mx (row i R2)))>>)%MS.\n\nArguments mulsmx {m1%N m2%N n%N} R1%MS R2%MS.\n\nLocal Notation \"R1 * R2\" := (mulsmx R1 R2) : matrix_set_scope.\n\nLemma genmx_muls m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  <<(R1 * R2)%MS>>%MS = (R1 * R2)%MS.\nProof. by rewrite genmx_sums; apply: eq_bigr => i; rewrite genmx_id. Qed.\n\nLemma mem_mulsmx m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) A1 A2 :\n  (A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R1 * R2)%MS.\nProof.\nmove=> R_A1 R_A2; rewrite -[A2]mxvecK; case/submxP: R_A2 => a ->{A2}.\nrewrite mulmx_sum_row !linear_sum summx_sub // => i _.\nrewrite !linearZ scalemx_sub {a}//= (sumsmx_sup i) // genmxE.\nrewrite -[A1]mxvecK; case/submxP: R_A1 => a ->{A1}.\nby apply/submxP; exists a; rewrite mulmxA mul_rV_lin.\nQed.\n\nLemma mulsmx_subP m1 m2 m n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R : 'A_(m, n)) :\n  reflect (forall A1 A2, A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R)\n          (R1 * R2 <= R)%MS.\nProof.\napply: (iffP memmx_subP) => [sR12R A1 A2 R_A1 R_A2 | sR12R A].\n  by rewrite sR12R ?mem_mulsmx.\ncase/memmx_sumsP=> A_ -> R_A; rewrite linear_sum summx_sub //= => j _.\nrewrite (submx_trans (R_A _)) // genmxE; apply/row_subP=> i.\nby rewrite row_mul mul_rV_lin sR12R ?vec_mxK ?row_sub.\nQed.\nArguments mulsmx_subP {m1 m2 m n R1 R2 R}.\n\nLemma mulsmxS m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                            (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 <= R3 -> R2 <= R4 -> R1 * R2 <= R3 * R4)%MS.\nProof.\nmove=> sR13 sR24; apply/mulsmx_subP=> A1 A2 R_A1 R_A2.\nby apply: mem_mulsmx; [apply: submx_trans sR13 | apply: submx_trans sR24].\nQed.\n\nLemma muls_eqmx m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                              (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 :=: R3 -> R2 :=: R4 -> R1 * R2 = R3 * R4)%MS.\nProof.\nmove=> eqR13 eqR24; rewrite -(genmx_muls R1 R2) -(genmx_muls R3 R4).\nby apply/genmxP; rewrite !mulsmxS ?eqR13 ?eqR24.\nQed.\n\nLemma mulsmxP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists2 A1, forall i, A1 i \\in R1\n            & exists2 A2, forall i, A2 i \\in R2\n           & A = \\sum_(i < n ^ 2) A1 i *m A2 i)\n          (A \\in R1 * R2)%MS.\nProof.\napply: (iffP idP) => [R_A|[A1 R_A1 [A2 R_A2 ->{A}]]]; last first.\n  by rewrite linear_sum summx_sub // => i _; rewrite mem_mulsmx.\nhave{R_A}: (A \\in R1 * <<R2>>)%MS.\n  by apply: memmx_subP R_A; rewrite mulsmxS ?genmxE.\ncase/memmx_sumsP=> A_ -> R_A; pose A2_ i := vec_mx (row i <<R2>>%MS).\npose A1_ i := mxvec (A_ i) *m pinvmx (R1 *m lin_mx (mulmxr (A2_ i))) *m R1.\nexists (vec_mx \\o A1_) => [i|]; first by rewrite vec_mxK submxMl.\nexists A2_ => [i|]; first by rewrite vec_mxK -(genmxE R2) row_sub.\napply: eq_bigr => i _; rewrite -[_ *m _](mx_rV_lin (mulmxr_linear _ _)).\nby rewrite -mulmxA mulmxKpV ?mxvecK // -(genmxE (_ *m _)) R_A.\nQed.\nArguments mulsmxP {m1 m2 n A R1 R2}.\n\nLemma mulsmxA m1 m2 m3 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 * R3) = R1 * R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls (_ * _)%MS) -genmx_muls; apply/genmxP/andP; split.\n  apply/mulsmx_subP=> A1 A23 R_A1; case/mulsmxP=> A2 R_A2 [A3 R_A3 ->{A23}].\n  by rewrite !linear_sum summx_sub //= => i _; rewrite mulmxA !mem_mulsmx.\napply/mulsmx_subP=> _ A3 /mulsmxP[A1 R_A1 [A2 R_A2 ->]] R_A3.\nrewrite mulmx_suml linear_sum summx_sub //= => i _.\nby rewrite -mulmxA !mem_mulsmx.\nQed.\n\nLemma mulsmxDl m1 m2 m3 n\n               (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  ((R1 + R2) * R3 = R1 * R3 + R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls R2 R3) -(genmx_muls R1 R3) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> _ A3 /memmx_addsP[A [R_A1 R_A2 ->]] R_A3.\nby rewrite mulmxDl linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmxDr m1 m2 m3 n\n               (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 + R3) = R1 * R2 + R1 * R3)%MS.\nProof.\nrewrite -(genmx_muls R1 R3) -(genmx_muls R1 R2) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> A1 _ R_A1 /memmx_addsP[A [R_A2 R_A3 ->]].\nby rewrite mulmxDr linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx0 m1 m2 n (R1 : 'A_(m1, n)) : (R1 * (0 : 'A_(m2, n)) = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A1 A0 _.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mulmx0 mem0mx.\nQed.\n\nLemma muls0mx m1 m2 n (R2 : 'A_(m2, n)) : ((0 : 'A_(m1, n)) * R2 = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A0 A2.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mul0mx mem0mx.\nQed.\n\nDefinition left_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R1 * R2 <= R2)%MS.\n\nDefinition right_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R2 * R1 <= R2)%MS.\n\nDefinition mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  left_mx_ideal R1 R2 && right_mx_ideal R1 R2.\n\nDefinition mxring_id m n (R : 'A_(m, n)) e :=\n  [/\\ e != 0,\n      e \\in R,\n      forall A, A \\in R -> e *m A = A\n    & forall A, A \\in R -> A *m e = A]%MS.\n\nDefinition has_mxring_id m n (R : 'A[F]_(m , n)) :=\n  (R != 0) &&\n  (row_mx 0 (row_mx (mxvec R) (mxvec R))\n    <= row_mx (cokermx R) (row_mx (lin_mx (mulmx R \\o lin_mulmx))\n                                  (lin_mx (mulmx R \\o lin_mulmxr))))%MS.\n\nDefinition mxring m n (R : 'A_(m, n)) :=\n  left_mx_ideal R R && has_mxring_id R.\n\nLemma mxring_idP m n (R : 'A_(m, n)) :\n  reflect (exists e, mxring_id R e) (has_mxring_id R).\nProof.\napply: (iffP andP) => [[nzR] | [e [nz_e Re ideR idRe]]].\n  case/submxP=> v; rewrite -[v]vec_mxK; move/vec_mx: v => e.\n  rewrite !mul_mx_row; case/eq_row_mx => /eqP.\n  rewrite eq_sym -submxE => Re.\n  case/eq_row_mx; rewrite !{1}mul_rV_lin1 /= mxvecK.\n  set u := (_ *m _) => /(can_inj mxvecK) idRe /(can_inj mxvecK) ideR.\n  exists e; split=> // [ | A /submxP[a defA] | A /submxP[a defA]].\n  - by apply: contra nzR; rewrite ideR => /eqP->; rewrite !linear0.\n  - by rewrite -{2}[A]mxvecK defA idRe mulmxA mx_rV_lin -defA /= mxvecK.\n  by rewrite -{2}[A]mxvecK defA ideR mulmxA mx_rV_lin -defA /= mxvecK.\nsplit.\n  by apply: contraNneq nz_e => R0; rewrite R0 eqmx0 in Re; rewrite (memmx0 Re).\napply/submxP; exists (mxvec e); rewrite !mul_mx_row !{1}mul_rV_lin1.\nrewrite submxE in Re; rewrite {Re}(eqP Re).\ncongr (row_mx 0 (row_mx (mxvec _) (mxvec _))); apply/row_matrixP=> i.\n  by rewrite !row_mul !mul_rV_lin1 /= mxvecK ideR vec_mxK ?row_sub.\nby rewrite !row_mul !mul_rV_lin1 /= mxvecK idRe vec_mxK ?row_sub.\nQed.\nArguments mxring_idP {m n R}.\n\nSection CentMxDef.\n\nVariables (m n : nat) (R : 'A[F]_(m, n)).\n\nDefinition cent_mx_fun (B : 'M[F]_n) := R *m lin_mx (mulmxr B \\- mulmx B).\n\nLemma cent_mx_fun_is_linear : linear cent_mx_fun.\nProof.\nmove=> a A B; apply/row_matrixP=> i; rewrite linearP row_mul mul_rV_lin.\nrewrite /= [row i _ as v in a *: v]row_mul mul_rV_lin row_mul mul_rV_lin.\nby rewrite -linearP -(linearP [linear of mulmx _ \\- mulmxr _]).\nQed.\nCanonical cent_mx_fun_additive := Additive cent_mx_fun_is_linear.\nCanonical cent_mx_fun_linear := Linear cent_mx_fun_is_linear.\n\nDefinition cent_mx := kermx (lin_mx cent_mx_fun).\n\nDefinition center_mx := (R :&: cent_mx)%MS.\n\nEnd CentMxDef.\n\nLocal Notation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nLocal Notation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nLemma cent_rowP m n B (R : 'A_(m, n)) :\n  reflect (forall i (A := vec_mx (row i R)), A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP sub_kermxP); rewrite mul_vec_lin => cBE.\n  move/(canRL mxvecK): cBE => cBE i A /=; move/(congr1 (row i)): cBE.\n  rewrite row_mul mul_rV_lin -/A; move/(canRL mxvecK).\n  by move/(canRL (subrK _)); rewrite !linear0 add0r.\napply: (canLR vec_mxK); apply/row_matrixP=> i.\nby rewrite row_mul mul_rV_lin /= cBE subrr !linear0.\nQed.\nArguments cent_rowP {m n B R}.\n\nLemma cent_mxP m n B (R : 'A_(m, n)) :\n  reflect (forall A, A \\in R -> A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP cent_rowP) => cEB => [A sAE | i A].\n  rewrite -[A]mxvecK -(mulmxKpV sAE); move: (mxvec A *m _) => u.\n  rewrite !mulmx_sum_row !linear_sum mulmx_suml; apply: eq_bigr => i _ /=.\n  by rewrite !linearZ -scalemxAl /= cEB.\nby rewrite cEB // vec_mxK row_sub.\nQed.\nArguments cent_mxP {m n B R}.\n\nLemma scalar_mx_cent m n a (R : 'A_(m, n)) : (a%:M \\in 'C(R))%MS.\nProof. by apply/cent_mxP=> A _; apply: scalar_mxC. Qed.\n\nLemma center_mx_sub m n (R : 'A_(m, n)) : ('Z(R) <= R)%MS.\nProof. exact: capmxSl. Qed.\n\nLemma center_mxP m n A (R : 'A_(m, n)) :\n  reflect (A \\in R /\\ forall B, B \\in R -> B *m A = A *m B)\n          (A \\in 'Z(R))%MS.\nProof.\nrewrite sub_capmx; case R_A: (A \\in R); last by right; case.\nby apply: (iffP cent_mxP) => [cAR | [_ cAR]].\nQed.\nArguments center_mxP {m n A R}.\n\nLemma mxring_id_uniq m n (R : 'A_(m, n)) e1 e2 :\n  mxring_id R e1 -> mxring_id R e2 -> e1 = e2.\nProof.\nby case=> [_ Re1 idRe1 _] [_ Re2 _ ide2R]; rewrite -(idRe1 _ Re2) ide2R.\nQed.\n\nLemma cent_mx_ideal m n (R : 'A_(m, n)) : left_mx_ideal 'C(R)%MS 'C(R)%MS.\nProof.\napply/mulsmx_subP=> A1 A2 C_A1 C_A2; apply/cent_mxP=> B R_B.\nby rewrite mulmxA (cent_mxP C_A1) // -!mulmxA (cent_mxP C_A2).\nQed.\n\nLemma cent_mx_ring m n (R : 'A_(m, n)) : n > 0 -> mxring 'C(R)%MS.\nProof.\nmove=> n_gt0; rewrite /mxring cent_mx_ideal; apply/mxring_idP.\nexists 1%:M; split=> [||A _|A _]; rewrite ?mulmx1 ?mul1mx ?scalar_mx_cent //.\nby rewrite -mxrank_eq0 mxrank1 -lt0n.\nQed.\n\nLemma mxdirect_adds_center m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n    mx_ideal (R1 + R2)%MS R1 -> mx_ideal (R1 + R2)%MS R2 ->\n    mxdirect (R1 + R2) ->\n  ('Z((R1 + R2)%MS) :=: 'Z(R1) + 'Z(R2))%MS.\nProof.\ncase/andP=> idlR1 idrR1 /andP[idlR2 idrR2] /mxdirect_addsP dxR12.\napply/eqmxP/andP; split.\n  apply/memmx_subP=> z0; rewrite sub_capmx => /andP[].\n  case/memmx_addsP=> z [R1z1 R2z2 ->{z0}] Cz.\n  rewrite linearD addmx_sub_adds //= ?sub_capmx ?R1z1 ?R2z2 /=.\n    apply/cent_mxP=> A R1_A; have R_A := submx_trans R1_A (addsmxSl R1 R2).\n    have Rz2 := submx_trans R2z2 (addsmxSr R1 R2).\n    rewrite -{1}[z.1](addrK z.2) mulmxBr (cent_mxP Cz) // mulmxDl.\n    rewrite [A *m z.2]memmx0 1?[z.2 *m A]memmx0 ?addrK //.\n      by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  apply/cent_mxP=> A R2_A; have R_A := submx_trans R2_A (addsmxSr R1 R2).\n  have Rz1 := submx_trans R1z1 (addsmxSl R1 R2).\n  rewrite -{1}[z.2](addKr z.1) mulmxDr (cent_mxP Cz) // mulmxDl.\n  rewrite mulmxN [A *m z.1]memmx0 1?[z.1 *m A]memmx0 ?addKr //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nrewrite addsmx_sub; apply/andP; split.\n  apply/memmx_subP=> z; rewrite sub_capmx => /andP[R1z cR1z].\n  have Rz := submx_trans R1z (addsmxSl R1 R2).\n  rewrite sub_capmx Rz; apply/cent_mxP=> A0.\n  case/memmx_addsP=> A [R1_A1 R2_A2] ->{A0}.\n  have R_A2 := submx_trans R2_A2 (addsmxSr R1 R2).\n  rewrite mulmxDl mulmxDr (cent_mxP cR1z) //; congr (_ + _).\n  rewrite [A.2 *m z]memmx0 1?[z *m A.2]memmx0 //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\napply/memmx_subP=> z; rewrite !sub_capmx => /andP[R2z cR2z].\nhave Rz := submx_trans R2z (addsmxSr R1 R2); rewrite Rz.\napply/cent_mxP=> _ /memmx_addsP[A [R1_A1 R2_A2 ->]].\nrewrite mulmxDl mulmxDr (cent_mxP cR2z _ R2_A2) //; congr (_ + _).\nhave R_A1 := submx_trans R1_A1 (addsmxSl R1 R2).\nrewrite [A.1 *m z]memmx0 1?[z *m A.1]memmx0 //.\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nby rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\nQed.\n\nLemma mxdirect_sums_center (I : finType) m n (R : 'A_(m, n)) R_ :\n    (\\sum_i R_ i :=: R)%MS -> mxdirect (\\sum_i R_ i) ->\n    (forall i : I, mx_ideal R (R_ i)) ->\n  ('Z(R) :=: \\sum_i 'Z(R_ i))%MS.\nProof.\nmove=> defR dxR idealR.\nhave sR_R: (R_ _ <= R)%MS by move=> i; rewrite -defR (sumsmx_sup i).\nhave anhR i j A B : i != j -> A \\in R_ i -> B \\in R_ j -> A *m B = 0.\n  move=> ne_ij RiA RjB; apply: memmx0.\n  have [[_ idRiR] [idRRj _]] := (andP (idealR i), andP (idealR j)).\n  rewrite -(mxdirect_sumsP dxR j) // sub_capmx (sumsmx_sup i) //.\n    by rewrite (mulsmx_subP idRRj) // (memmx_subP (sR_R i)).\n  by rewrite (mulsmx_subP idRiR) // (memmx_subP (sR_R j)).\napply/eqmxP/andP; split.\n  apply/memmx_subP=> Z; rewrite sub_capmx => /andP[].\n  rewrite -{1}defR => /memmx_sumsP[z ->{Z} Rz cRz].\n  apply/memmx_sumsP; exists z => // i; rewrite sub_capmx Rz.\n  apply/cent_mxP=> A RiA; have:= cent_mxP cRz A (memmx_subP (sR_R i) A RiA).\n  rewrite (bigD1 i) //= mulmxDl mulmxDr mulmx_suml mulmx_sumr.\n  by rewrite !big1 ?addr0 // => j; last rewrite eq_sym; move/anhR->.\napply/sumsmx_subP => i _; apply/memmx_subP=> z; rewrite sub_capmx.\ncase/andP=> Riz cRiz; rewrite sub_capmx (memmx_subP (sR_R i)) //=.\napply/cent_mxP=> A; rewrite -{1}defR; case/memmx_sumsP=> a -> R_a.\nrewrite (bigD1 i) // mulmxDl mulmxDr mulmx_suml mulmx_sumr.\nrewrite !big1 => [|j|j]; first by rewrite !addr0 (cent_mxP cRiz).\n  by rewrite eq_sym => /anhR->.\nby move/anhR->.\nQed.\n\nEnd MatrixAlgebra.\n\nArguments mulsmx {F m1%N m2%N n%N} R1%MS R2%MS.\nArguments left_mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments right_mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments mxring_id {F m%N n%N} R%MS e%R.\nArguments has_mxring_id {F m%N n%N} R%MS.\nArguments mxring {F m%N n%N} R%MS.\nArguments cent_mx {F m%N n%N} R%MS.\nArguments center_mx {F m%N n%N} R%MS.\n\nNotation \"A \\in R\" := (submx (mxvec A) R) : matrix_set_scope.\nNotation \"R * S\" := (mulsmx R S) : matrix_set_scope.\nNotation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nNotation \"''C_' R ( S )\" := (R :&: 'C(S))%MS : matrix_set_scope.\nNotation \"''C_' ( R ) ( S )\" := ('C_R(S))%MS (only parsing) : matrix_set_scope.\nNotation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nArguments memmx_subP {F m1 m2 n R1 R2}.\nArguments memmx_eqP {F m1 m2 n R1 R2}.\nArguments memmx_addsP {F m1 m2 n} A {R1 R2}.\nArguments memmx_sumsP {F I P n A R_}.\nArguments mulsmx_subP {F m1 m2 m n R1 R2 R}.\nArguments mulsmxP {F m1 m2 n A R1 R2}.\nArguments mxring_idP F {m n R}.\nArguments cent_rowP {F m n B R}.\nArguments cent_mxP {F m n B R}.\nArguments center_mxP {F m n A R}.\n\n(* Parametricity for the row-space/F-algebra theory.                         *)\nSection MapMatrixSpaces.\n\nVariables (aF rF : fieldType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nLemma Gaussian_elimination_map m n (A : 'M_(m, n)) :\n  Gaussian_elimination A^f = ((col_ebase A)^f, (row_ebase A)^f, \\rank A).\nProof.\nrewrite mxrankE /row_ebase /col_ebase unlock.\nelim: m n A => [|m IHm] [|n] A /=; rewrite ?map_mx1 //.\nset pAnz := [pred k | A k.1 k.2 != 0].\nrewrite (@eq_pick _ _ pAnz) => [|k]; last by rewrite /= mxE fmorph_eq0.\ncase: {+}(pick _) => [[i j]|]; last by rewrite !map_mx1.\nrewrite mxE -fmorphV  -map_xcol -map_xrow -map_dlsubmx -map_drsubmx.\nrewrite -map_ursubmx -map_mxZ -map_mxM -map_mxB {}IHm /=.\ncase: {+}(Gaussian_elimination _) => [[L U] r] /=; rewrite map_xrow map_xcol.\nby rewrite !(@map_block_mx _ _ f 1 _ 1) !map_mx0 ?map_mx1 ?map_scalar_mx.\nQed.\n\nLemma mxrank_map m n (A : 'M_(m, n)) : \\rank A^f = \\rank A.\nProof. by rewrite mxrankE Gaussian_elimination_map. Qed.\n\nLemma row_free_map m n (A : 'M_(m, n)) : row_free A^f = row_free A.\nProof. by rewrite /row_free mxrank_map. Qed.\n\nLemma row_full_map m n (A : 'M_(m, n)) : row_full A^f = row_full A.\nProof. by rewrite /row_full mxrank_map. Qed.\n\nLemma map_row_ebase m n (A : 'M_(m, n)) : (row_ebase A)^f = row_ebase A^f.\nProof. by rewrite {2}/row_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_col_ebase m n (A : 'M_(m, n)) : (col_ebase A)^f = col_ebase A^f.\nProof. by rewrite {2}/col_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_row_base m n (A : 'M_(m, n)) :\n  (row_base A)^f = castmx (mxrank_map A, erefl n) (row_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/row_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_row_ebase.\nQed.\n\nLemma map_col_base m n (A : 'M_(m, n)) :\n  (col_base A)^f = castmx (erefl m, mxrank_map A) (col_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/col_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_col_ebase.\nQed.\n\nLemma map_pinvmx m n (A : 'M_(m, n)) : (pinvmx A)^f = pinvmx A^f.\nProof.\nrewrite !map_mxM !map_invmx map_row_ebase map_col_ebase.\nby rewrite map_pid_mx -mxrank_map.\nQed.\n\nLemma map_kermx m n (A : 'M_(m, n)) : (kermx A)^f = kermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_col_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_cokermx m n (A : 'M_(m, n)) : (cokermx A)^f = cokermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_row_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_submx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f <= B^f)%MS = (A <= B)%MS.\nProof. by rewrite !submxE -map_cokermx -map_mxM map_mx_eq0. Qed.\n\nLemma map_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f < B^f)%MS = (A < B)%MS.\nProof. by rewrite /ltmx !map_submx. Qed.\n\nLemma map_eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f :=: B^f)%MS <-> (A :=: B)%MS.\nProof.\nsplit=> [/eqmxP|eqAB]; first by rewrite !map_submx => /eqmxP.\nby apply/eqmxP; rewrite !map_submx !eqAB !submx_refl.\nQed.\n\nLemma map_genmx m n (A : 'M_(m, n)) : (<<A>>^f :=: <<A^f>>)%MS.\nProof. by apply/eqmxP; rewrite !(genmxE, map_submx) andbb. Qed.\n\nLemma map_addsmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (((A + B)%MS)^f :=: A^f + B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !addsmxE -map_col_mx !map_submx !addsmxE andbb.\nQed.\n\nLemma map_capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (capmx_gen A B)^f = capmx_gen A^f B^f.\nProof. by rewrite map_mxM map_lsubmx map_kermx map_col_mx. Qed.\n\nLemma map_capmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :&: B)^f :=: A^f :&: B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !capmxE -map_capmx_gen !map_submx -!capmxE andbb.\nQed.\n\nLemma map_complmx m n (A : 'M_(m, n)) : (A^C^f = A^f^C)%MS.\nProof. by rewrite map_mxM map_row_ebase -mxrank_map map_copid_mx. Qed.\n\nLemma map_diffmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B)^f :=: A^f :\\: B^f)%MS.\nProof.\napply/eqmxP; rewrite !diffmxE -map_capmx_gen -map_complmx.\nby rewrite -!map_capmx !map_submx -!diffmxE andbb.\nQed.\n\nLemma map_eigenspace n (g : 'M_n) a : (eigenspace g a)^f = eigenspace g^f (f a).\nProof. by rewrite map_kermx map_mxB ?map_scalar_mx. Qed.\n\nLemma eigenvalue_map n (g : 'M_n) a : eigenvalue g^f (f a) = eigenvalue g a.\nProof. by rewrite /eigenvalue -map_eigenspace map_mx_eq0. Qed.\n\nLemma memmx_map m n A (E : 'A_(m, n)) : (A^f \\in E^f)%MS = (A \\in E)%MS.\nProof. by rewrite -map_mxvec map_submx. Qed.\n\nLemma map_mulsmx m1 m2 n (E1 : 'A_(m1, n)) (E2 : 'A_(m2, n)) :\n  ((E1 * E2)%MS^f :=: E1^f * E2^f)%MS.\nProof.\nrewrite /mulsmx; elim/big_rec2: _ => [|i A Af _ eqA]; first by rewrite map_mx0.\napply: (eqmx_trans (map_addsmx _ _)); apply: adds_eqmx {A Af}eqA.\napply/eqmxP; rewrite !map_genmx !genmxE map_mxM.\napply/rV_eqP=> u; congr (u <= _ *m _)%MS.\nby apply: map_lin_mx => //= A; rewrite map_mxM // map_vec_mx map_row.\nQed.\n\nLemma map_cent_mx m n (E : 'A_(m, n)) : ('C(E)%MS)^f = 'C(E^f)%MS.\nProof.\nrewrite map_kermx; congr kermx; apply: map_lin_mx => A; rewrite map_mxM.\nby congr (_ *m _); apply: map_lin_mx => B; rewrite map_mxB ?map_mxM.\nQed.\n\nLemma map_center_mx m n (E : 'A_(m, n)) : (('Z(E))^f :=: 'Z(E^f))%MS.\nProof. by rewrite /center_mx -map_cent_mx; apply: map_capmx. Qed.\n\nEnd MapMatrixSpaces.\n\nSection RowColDiagBlockMatrix.\nImport tagnat.\nContext {F : fieldType} {n : nat} {p_ : 'I_n -> nat}.\n\nLemma eqmx_col {m} (V_ : forall i, 'M[F]_(p_ i, m)) :\n  (\\mxcol_i V_ i :=: \\sum_i <<V_ i>>)%MS.\nProof.\napply/eqmxP/andP; split.\n  apply/row_subP => i; rewrite row_mxcol.\n  by rewrite (sumsmx_sup (sig1 i))// genmxE row_sub.\napply/sumsmx_subP => i0 _; rewrite genmxE; apply/row_subP => j.\napply: (eq_row_sub (Rank _ j)); apply/rowP => k.\nby rewrite !mxE Rank2K; case: _ / esym; rewrite cast_ord_id.\nQed.\n\nLemma rank_mxdiag (V_ : forall i, 'M[F]_(p_ i)) :\n  (\\rank (\\mxdiag_i V_ i) = \\sum_i \\rank (V_ i))%N.\nProof.\nelim: {+}n {+}p_ V_ => [|m IHm] q_ V_.\n  by move: (\\mxdiag__ _); rewrite !big_ord0 => M; rewrite flatmx0 mxrank0.\nrewrite mxdiag_recl [RHS]big_ord_recl/= -IHm.\nby case: _ / mxsize_recl; rewrite ?castmx_id rank_diag_block_mx.\nQed.\n\nEnd RowColDiagBlockMatrix.\n", "meta": {"author": "math-comp", "repo": "math-comp", "sha": "e39f9173b484f2e8e7f69f746a619dcc8f3abc1b", "save_path": "github-repos/coq/math-comp-math-comp", "path": "github-repos/coq/math-comp-math-comp/math-comp-e39f9173b484f2e8e7f69f746a619dcc8f3abc1b/mathcomp/algebra/mxalgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7302837688176222}}
{"text": "(* Set Printing All imi fuctiona doar cu optiunea \"Display all basic low-level contents\" (Shift + Alt + A) *)\n\n(* EX 1 : *)\n\n(* Vom considera cunoscute următoarele definiții: *)\nInductive Var := a | b | c | x | y | z | n | s | i .\n\nInductive AExp :=\n| anum : nat -> AExp\n| aplus : AExp -> AExp -> AExp\n| amul : AExp -> AExp -> AExp\n| avar : Var -> AExp. (*Modificare*)\n\nCoercion anum : nat >-> AExp.\nNotation \"A +' B\" := (aplus A B) (at level 60, right associativity).\nNotation \"A *' B\" := (amul A B) (at level 58, left associativity).\nCoercion avar : Var >-> AExp. (*Modificare*)\n\n(*Modificați definiția expresiilor aritmetice (AExp de mai sus) astfel încât aceasta să permită utilizarea de variabile (Var). \nTestați modificările făcute pe următoarele cazuri: *)\n\nCheck 2 +' (avar n).\nCheck n +' 1.\nCheck s +' i.\n\n\n\n(* EX 2 : *)\n\n(*Definiți un tip de date pentru expresii booleene care să includă valorile de adevăr, negații, conjuncții și comparații între expresii aritmetice. \nTestați modificările făcute pe următoarele cazuri: *)\n\nInductive BExp :=\n| btrue : BExp\n| bfalse : BExp\n| bnot : BExp -> BExp\n| band : BExp -> BExp -> BExp\n| blessthan : AExp -> AExp -> BExp\n| bmorethan : AExp -> AExp -> BExp.\n\nNotation \"A <' B\" := (blessthan A B) (at level 70).\nNotation \"A >' B\" := (bmorethan A B) (at level 70).\nInfix \"and'\" := band (at level 80). \n(* Se poate folosi si : Notation \"A 'and'' B\" := (band A B) (at level 80). *)\nNotation \"!\" := bnot (at level 80).\n(* Se poate folosi si : Notation \"! A\" := (bnot A) (at level 80) *)\n\nCheck btrue.\nCheck bfalse.\nCheck ! (x <' 10).\nCheck btrue and' (n >' 0).\n\n\n\n(* EX 3 : *)\n\n(*Definiți un tip de date pentru instrucțiunile unui limbaj de programare simplu. \nInstrucțiunile sunt: atribuiri, bucle (de tip while) și secvențe de instrucțiuni. \nPentru teste, utilizați cazurile de mai jos. \nAtenție la notații: acestea vă pot ajuta să determinați forma instrucțiunilor utilizate. *)\n\nRequire Import String.\nInductive Stmt :=\n| assignment : Var-> AExp -> Stmt\n| sequence : Stmt -> Stmt -> Stmt\n| iforelse : BExp -> Stmt -> Stmt.\n\nNotation \"X ::= A\" := (assignment X A) (at level 80).\nNotation \"S1 ;; S2\" := (sequence S1 S2) (at level 98, left associativity).\nNotation \"'while' ( A ) (  B )\":= (iforelse A B)(at level 99).\n(* Daca nu sunt puse parantezele de la ( A ) ( B ), va da eroare constructor operator level 200*)\n\n\nCheck n ::= 10.\nCheck s ::= 0.\nCheck n ::= 10 ;; s ::= 0 ;; i ::= 0.\nCheck n ::= 10 ;;\n      s ::= 0 ;;\n      i ::= 0 ;;\n      while (i <' n +' 1) (\n            s ::= s +' i ;;\n            i ::= i +' 1\n      ).", "meta": {"author": "andrei-v-stan", "repo": "PLP-Hw", "sha": "9d9e9460c2dc143c112617ef5b6a45e4b31ab34f", "save_path": "github-repos/coq/andrei-v-stan-PLP-Hw", "path": "github-repos/coq/andrei-v-stan-PLP-Hw/PLP-Hw-9d9e9460c2dc143c112617ef5b6a45e4b31ab34f/Stan_Andrei_2_E3_3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7302771482485068}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export IndProp.\nCheck evenb.\n\n(** \"_Algorithms are the computational content of proofs_.\"  --Robert Harper *)\n\n(** We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types like [nat] or [list] and functions over\n    these types, and for _proving_ properties of these programs, using\n    inductive propositions (like [ev]), implication, universal\n    quantification, and the like.  So far, we have mostly treated\n    these mechanisms as if they were quite separate, and for many\n    purposes this is a good way to think.  But we have also seen hints\n    that Coq's programming and proving facilities are closely related.\n    For example, the keyword [Inductive] is used to declare both data\n    types and propositions, and [->] is used both to describe the type\n    of functions on data and logical implication.  This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are\n    almost the same thing.  In this chapter we will study how this\n    works.\n\n    We have already seen the fundamental idea: provability in Coq is\n    represented by concrete _evidence_.  When we construct the proof\n    of a basic proposition, we are actually building a tree of\n    evidence, which can be thought of as a data structure.\n\n    If the proposition is an implication like [A -> B], then its proof\n    will be an evidence _transformer_: a recipe for converting\n    evidence for A into evidence for B.  So at a fundamental level,\n    proofs are simply programs that manipulate evidence. *)\n\n(** Question: If evidence is data, what are propositions themselves?\n\n    Answer: They are types! *)\n\n(** Look again at the formal definition of the [ev] property.  *)\n\nPrint ev.\n(* ==>\n  Inductive ev : nat -> Prop :=\n    | ev_0 : ev 0\n    | ev_SS : forall n, ev n -> ev (S (S n)).\n*)\n\n(** Suppose we introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can say \"is a proof of.\"  For example,\n    the second line in the definition of [ev] declares that [ev_0 : ev\n    0].  Instead of \"[ev_0] has type [ev 0],\" we can say that \"[ev_0]\n    is a proof of [ev 0].\" *)\n\n(** This pun between types and propositions -- between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\" -- is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation:\n\n                 propositions  ~  types\n                 proofs        ~  data values\n\n    See [Wadler 2015] for a brief history and an up-to-date exposition. *)\n\n(** Many useful insights follow from this connection.  To begin with,\n    it gives us a natural interpretation of the type of the [ev_SS]\n    constructor: *)\n\nCheck ev_SS.\n(* ===> ev_SS : forall n,\n                  ev n ->\n                  ev (S (S n)) *)\n\n(** This can be read \"[ev_SS] is a constructor that takes two\n    arguments -- a number [n] and evidence for the proposition [ev\n    n] -- and yields evidence for the proposition [ev (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [ev]. *)\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** As with ordinary data values and functions, we can use the [Print]\n    command to see the _proof object_ that results from this proof\n    script. *)\n\nPrint ev_4.\n(* ===> ev_4 = ev_SS 2 (ev_SS 0 ev_0)\n     : ev 4  *)\n\n(** Indeed, we can also write down this proof object _directly_,\n    without the need for a separate proof script: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n(* ===> ev 4 *)\n\n(** The expression [ev_SS 2 (ev_SS 0 ev_0)] can be thought of as\n    instantiating the parameterized constructor [ev_SS] with the\n    specific arguments [2] and [0] plus the corresponding proof\n    objects for its premises [ev 2] and [ev 0].  Alternatively, we can\n    think of [ev_SS] as a primitive \"evidence constructor\" that, when\n    applied to a particular number, wants to be further applied to\n    evidence that that number is even; its type,\n\n      forall n, ev n -> ev (S (S n)),\n\n    expresses this functionality, in the same way that the polymorphic\n    type [forall X, list X] expresses the fact that the constructor\n    [nil] can be thought of as a function from types to empty lists\n    with elements of that type. *)\n\n(** We saw in the [Logic] chapter that we can use function\n    application syntax to instantiate universally quantified variables\n    in lemmas, as well as to supply evidence for assumptions that\n    these lemmas impose.  For instance: *)\n\nTheorem ev_4': ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(* ################################################################# *)\n(** * Proof Scripts *)\n\n(** The _proof objects_ we've been discussing lie at the core of how\n    Coq operates.  When Coq is following a proof script, what is\n    happening internally is that it is gradually constructing a proof\n    object -- a term whose type is the proposition being proved.  The\n    tactics between [Proof] and [Qed] tell it how to build up a term\n    of the required type.  To see this process in action, let's use\n    the [Show Proof] command to display the current state of the proof\n    tree at various points in the following tactic proof. *)\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with a\n    \"hole\" (indicated by [?Goal] here, and so on), and it knows what\n    type of evidence is needed to fill this hole.  \n\n    Each hole corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    evidence we've built stored in the global context under the name\n    given in the [Theorem] command. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand, as shown above. Then we can use [Definition]\n    (rather than [Theorem]) to give a global name directly to this\n    evidence. *)\n\nDefinition ev_4''' : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint ev_4.\n(* ===> ev_4    =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\n\n(** **** Exercise: 2 stars (eight_is_even)  *)\n(** Give a tactic proof and a proof object showing that [ev 8]. *)\n\nTheorem ev_8 : ev 8.\nProof.\n  apply (ev_SS  6  (ev_SS 4 ev_4)).\nQed.\n\n\nDefinition ev_8' : ev 8 := ev_SS 6 (ev_SS 4 ev_4).\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Quantifiers, Implications, Functions *)\n\n(** In Coq's computational universe (where data structures and\n    programs live), there are two sorts of values with arrows in their\n    types: _constructors_ introduced by [Inductive]ly defined data\n    types, and _functions_.\n\n    Similarly, in Coq's logical universe (where we carry out proofs),\n    there are two ways of giving evidence for an implication:\n    constructors introduced by [Inductive]ly defined propositions,\n    and... functions! *)\n\n(** For example, consider this statement: *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\n(** What is the proof object corresponding to [ev_plus4]?\n\n    We're looking for an expression whose _type_ is [forall n, ev n ->\n    ev (4 + n)] -- that is, a _function_ that takes two arguments (one\n    number and a piece of evidence) and returns a piece of evidence!\n\n    Here it is: *)\nCheck ev_SS.\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah],\" and that Coq treats [4 + n] and [S (S (S (S n)))]\n    as synonyms. Another equivalent way to write this definition is: *)\n\nDefinition ev_plus4'' (n : nat) (H : ev n)\n                    : ev (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\n(* ===> \n     : forall n : nat, ev n -> ev (4 + n) *)\n\n(** When we view the proposition being proved by [ev_plus4] as a\n    function type, one interesting point becomes apparent: The second\n    argument's type, [ev n], mentions the _value_ of the first\n    argument, [n].\n\n    While such _dependent types_ are not found in conventional\n    programming languages, they can be useful in programming too, as\n    the recent flurry of activity in the functional programming\n    community demonstrates. *)\n\n(** Notice that both implication ([->]) and quantification ([forall])\n    correspond to functions on evidence.  In fact, they are really the\n    same thing: [->] is just a shorthand for a degenerate use of\n    [forall] where there is no dependency, i.e., no need to give a\n    name to the type on the left-hand side of the arrow:\n\n           forall (x:nat), nat  \n        =  forall (_:nat), nat  \n        =  nat -> nat\n*)\n\n\n(** For example, consider this proposition: *)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : ev n), ev (n + 2).\n\n(** A proof term inhabiting this proposition would be a function\n    with two arguments: a number [n] and some evidence [E] that [n] is\n    even.  But the name [E] for this evidence is not used in the rest\n    of the statement of [ev_plus2], so it's a bit silly to bother\n    making up a name for it.  We could write it like this instead,\n    using the dummy identifier [_] in place of a real name: *)\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : ev n), ev (n + 2).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, ev n -> ev (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\n(** If we can build proofs by giving explicit terms rather than\n    executing tactic scripts, you may be wondering whether we can\n    build _programs_ using _tactics_ rather than explicit terms.\n    Naturally, the answer is yes! *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n\nPrint add1.\n(* ==>\n    add1 = fun n : nat => S n\n         : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than\n    with [:=] followed by a term.  This tells Coq to enter _proof\n    scripting mode_ to build an object of type [nat -> nat].  Also, we\n    terminate the proof with [Defined] rather than [Qed]; this makes\n    the definition _transparent_ so that it can be used in computation\n    like a normally-defined function.  ([Qed]-defined objects are\n    opaque during computation.)\n\n    This feature is mainly useful for writing functions with dependent\n    types, which we won't explore much further in this book.  But it\n    does illustrate the uniformity and orthogonality of the basic\n    ideas in Coq. *)\n\n\n(* ################################################################# *)\n(** * Logical Connectives as Inductive Types *)\n\n(** Inductive definitions are powerful enough to express most of the\n    connectives and quantifiers we have seen so far.  Indeed, only\n    universal quantification (and thus implication) is built into Coq;\n    all the others are defined inductively.  We'll see these\n    definitions in this section. *)\n\nModule Props.\n\n(** ** Conjunction\n\n    To prove that [P /\\ Q] holds, we must present evidence for both\n    [P] and [Q].  Thus, it makes sense to define a proof object for [P\n    /\\ Q] as consisting of a pair of two proofs: one for [P] and\n    another one for [Q]. This leads to the following definition. *)\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\n\nEnd And.\n\n(** Notice the similarity with the definition of the [prod] type,\n    given in chapter [Poly]; the only difference is that [prod] takes\n    [Type] arguments, whereas [and] takes [Prop] arguments. *)\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\n\n(** This should clarify why [destruct] and [intros] patterns can be\n    used on a conjunctive hypothesis.  Case analysis allows us to\n    consider all possible ways in which [P /\\ Q] was proved -- here\n    just one (the [conj] constructor).  Similarly, the [split] tactic\n    actually works for any inductively defined proposition with only\n    one constructor.  In particular, it works for [and]: *)\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\nQed.\n\n(** This shows why the inductive definition of [and] can be\n    manipulated by tactics as we've been doing.  We can also use it to\n    build proofs directly, using pattern-matching.  For instance: *)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\nCheck and_comm'_aux.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, optional (conj_fact)  *)\n(** Construct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R:=\n  fun(P Q R:Prop) => fun (HPQ: P /\\ Q) => fun(HQR: Q/\\R) => match HPQ with\n        | conj HP HQ => match HQR with\n                                  | conj _ HR => conj HP HR\n                                 end\n        end.\nCheck conj_fact.\n(** [] *)\n\n\n\n(** ** Disjunction\n\n    The inductive definition of disjunction uses two constructors, one\n    for each side of the disjunct: *)\n\nModule Or.\n\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\n\nEnd Or.\n\n(** This declaration explains the behavior of the [destruct] tactic on\n    a disjunctive hypothesis, since the generated subgoals match the\n    shape of the [or_introl] and [or_intror] constructors.\n\n    Once again, we can also directly write proof objects for theorems\n    involving [or], without resorting to tactics. *)\n\n(** **** Exercise: 2 stars, optional (or_commut'')  *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\n\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P :=\n  fun(P Q:Prop) => fun(Hpq:P \\/ Q) => \n      match Hpq with\n      | or_introl HP => or_intror HP\n      | or_intror HQ => or_introl HQ\n      end.\n\nCheck or_comm.\nPrint or_commut.\n(** [] *)\n\n(** ** Existential Quantification\n\n    To give evidence for an existential quantifier, we package a\n    witness [x] together with a proof that [x] satisfies the property\n    [P]: *)\n\nModule Ex.\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro : forall x : A, P x -> ex P.\n\nEnd Ex.\n\n(** This may benefit from a little unpacking.  The core definition is\n    for a type former [ex] that can be used to build propositions of\n    the form [ex P], where [P] itself is a _function_ from witness\n    values in the type [A] to propositions.  The [ex_intro]\n    constructor then offers a way of constructing evidence for [ex P],\n    given a witness [x] and a proof of [P x]. *)\n\n(** The more familiar form [exists x, P x] desugars to an expression\n    involving [ex]: *)\n\nCheck ex (fun n => ev n).\n(* ===> exists n : nat, ev n\n        : Prop *)\nPrint ev.\nCheck ((ev_SS 2 (ev_SS 0 ev_0)) ).\n\n(** Here's how to define an explicit proof object involving [ex]: *)\nCheck ex_intro ev 2 (ev_SS 0 ev_0).\n\n(* ev is a parameter from outside*)\nDefinition some_nat_is_even : exists n, ev n :=\n  ex_intro  ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** **** Exercise: 2 stars, optional (ex_ev_Sn)  *)\n(** Complete the definition of the following proof object: *)\nCheck (ex (fun n => ev (S n))).\n\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) :=\n  ex_intro (fun n => ev (S n)) 1 (ev_SS 0 ev_0).\n\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** [True] and [False] *)\n\n(** The inductive definition of the [True] proposition is simple: *)\n\nInductive True : Prop :=\n  | I : True.\n\n(** It has one constructor (so every proof of [True] is the same, so\n    being given a proof of [True] is not informative.) *)\n\n(** [False] is equally simple -- indeed, so simple it may look\n    syntactically wrong at first glance! *)\n\nInductive False : Prop :=.\n\n(** That is, [False] is an inductive type with _no_ constructors --\n    i.e., no way to build evidence for it. *)\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has the\n    following inductive definition.  (Actually, the definition in the\n    standard library is a small variant of this, which gives an\n    induction principle that is slightly easier to use.) *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n| eq_refl : forall x, eq x x.\n\nNotation \"x = y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\n(** The way to think about this definition is that, given a set [X],\n    it defines a _family_ of propositions \"[x] is equal to [y],\"\n    indexed by pairs of values ([x] and [y]) from [X].  There is just\n    one way of constructing evidence for each member of this family:\n    applying the constructor [eq_refl] to a type [X] and a value [x :\n    X] yields evidence that [x] is equal to [x]. *)\n\n(** We can use [eq_refl] to construct evidence that, for example, [2 =\n    2].  Can we also use it to construct evidence that [1 + 1 = 2]?\n    Yes, we can.  Indeed, it is the very same piece of evidence!\n\n    The reason is that Coq treats as \"the same\" any two terms that are\n    _convertible_ according to a simple set of computation rules.\n\n    These rules, which are similar to those used by [Compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.  *)\n\nLemma four: 2 + 2 = 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove equalities up\n    to now is essentially just short-hand for [apply eq_refl].\n\n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).\n\n    But you can see them directly at work in the following explicit\n    proof objects: *)\n\nDefinition four' : 2 + 2 = 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), []++[x] = x::[]  :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\nEnd MyEquality.\n\n\n(** **** Exercise: 2 stars (equality__leibniz_equality)  *)\n(** The inductive definition of equality implies _Leibniz equality_:\n    what we mean when we say \"[x] and [y] are equal\" is that every\n    property on [P] that is true of [x] is also true of [y].  *)\n\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x = y -> forall P:X->Prop, P x -> P y.\nProof.\n  intros X x y H P Px.\n  rewrite <- H.\n  apply Px.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (leibniz_equality__equality)  *)\n(** Show that, in fact, the inductive definition of equality is\n    _equivalent_ to Leibniz equality: *)\nPrint excluded_middle.\n\n\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P:X->Prop, P x -> P y) -> x = y.\nProof.\n  intros X x y H.\n  apply H.\n  reflexivity.\nQed.\n\n\n(* ================================================================= *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves.\n\n    In general, the [inversion] tactic...\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n\n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are\n    two constructors, so two subgoals get generated.  The\n    conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [and], there is\n    only one constructor, so only one subgoal gets generated.  Again,\n    the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal.  The\n    constructor does have two arguments, though, and these can be seen\n    in the context in the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [eq], there is\n    again only one constructor, so only one subgoal gets generated.\n    Now, though, the form of the [refl_equal] constructor does give us\n    some extra information: it tells us that the two arguments to [eq]\n    must be the same!  The [inversion] tactic adds this fact to the\n    context. *)\n\n\n", "meta": {"author": "AKKID", "repo": "If", "sha": "de95d24a26d4a28e1ae11a4b962b4bce20c313f7", "save_path": "github-repos/coq/AKKID-If", "path": "github-repos/coq/AKKID-If/If-de95d24a26d4a28e1ae11a4b962b4bce20c313f7/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.8740772253241802, "lm_q1q2_score": 0.730277121173817}}
{"text": "Require Import init.\n\nDeclare Scope nat_scope.\nDelimit Scope nat_scope with nat.\n\nInductive nat : Set :=\n    | nat_zero : nat\n    | nat_suc : nat → nat.\nBind Scope nat_scope with nat.\n\nFixpoint iterate_func {U} (f : U → U) n :=\n    match n with\n    | nat_zero => identity\n    | nat_suc n' => λ x, f (iterate_func f n' x)\n    end.\n\nDefinition sequence (U : Type) := nat → U.\n\nTheorem nat_zero_suc : ∀ {n}, nat_zero ≠ nat_suc n.\nProof.\n    intros n eq.\n    inversion eq.\nQed.\n\nTheorem nat_suc_eq : ∀ {a b}, nat_suc a = nat_suc b ↔ a = b.\nProof.\n    intros a b.\n    split.\n    -   intros eq.\n        inversion eq.\n        reflexivity.\n    -   intros eq.\n        subst.\n        reflexivity.\nQed.\n\nTheorem nat_neq_suc : ∀ n, n ≠ nat_suc n.\nProof.\n    induction n.\n    -   apply nat_zero_suc.\n    -   intro contr.\n        rewrite nat_suc_eq in contr.\n        contradiction.\nQed.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Number/Nat/nat_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7302618463807455}}
{"text": "(** Well-founded order on product and applications to products of nat *)\n\nFrom Coq Require Import Relation_Definitions Wf_nat Lia.\n\nSet Implicit Arguments.\n\n\n(** * Non-Dependant Product of two [well_founded] relations *)\n\nSection Product.\n\n  Variable A B : Type.\n  Variable RA : relation A.\n  Variable RB : relation B.\n  Hypothesis WA : well_founded RA.\n  Hypothesis WB : well_founded RB.\n\n  (* more general but slightly different type\n  Definition lt_prod v1 v2 := lexprod _ _ RA (fun _ => RB) v1 v2.\n  Definition wf_prod := wf_lexprod _ _ _ _ WA (fun _ => WB).\n  *)\n  Definition lt_prod v1 v2 := RA (fst v1) (fst v2)\n       \\/ (fst v1 = fst v2 /\\ RB (snd v1) (snd v2)).\n\n  Lemma wf_prod : well_founded lt_prod.\n  Proof.\n  intros [a b]; revert b.\n  induction a using (well_founded_induction WA);\n    induction b using (well_founded_induction WB).\n  constructor.\n  intros [a' b'] [Ho | [L R]].\n  - now apply H.\n  - now simpl in L; subst; apply H0.\n  Qed.\n\nEnd Product.\n\n\n(** * Well founded order on pairs of [nat] *)\n\n(*\nDefinition lt_nat_nat := lexprod _ _ lt (fun _ => lt).\nDefinition wf_nat_nat := wf_lexprod _ _ _ _ lt_wf (fun _ => lt_wf).\n*)\nDefinition lt_nat_nat := lt_prod lt lt.\nDefinition wf_nat_nat := wf_prod lt_wf lt_wf.\n\nLtac lt_nat_nat_solve :=\n  match goal with\n  | |- lt_nat_nat ?v1 ?v2 => try (left; simpl; lia);\n                             try (right; split; simpl; lia);\n                             fail\n  | |- lt_prod lt lt ?v1 ?v2 => try (left; simpl; lia);\n                                try (right; split; simpl; lia);\n                                fail\n  end.\n\n(** * Well founded order on triples of [nat] *)\n\nDefinition lt_nat_nat_nat := lt_prod lt lt_nat_nat.\nDefinition wf_nat_nat_nat := wf_prod lt_wf wf_nat_nat.\n\nLtac lt_nat_nat_nat_solve :=\n  match goal with \n  | |- lt_nat_nat_nat ?v1 ?v2 =>\n     try (left; simpl; lia);\n     try (right; split; [ | left ]; simpl; lia);\n     try (right; split; [ | right; split ]; simpl; lia);\n     fail\n  | |- lt_prod lt lt_nat_nat ?v1 ?v2 =>\n     try (left; simpl; lia);\n     try (right; split; [ | left ]; simpl; lia);\n     try (right; split; [ | right; split ]; simpl; lia);\n     fail\n  | |- lt_prod lt (lt_prod lt lt) ?v1 ?v2 =>\n     try (left; simpl; lia);\n     try (right; split; [ | left ]; simpl; lia);\n     try (right; split; [ | right; split ]; simpl; lia);\n     fail\n  end.\n", "meta": {"author": "clucas26e4", "repo": "riesz-logic", "sha": "6ad0da80c8922d186c777d2c8f1a42d381abfb2d", "save_path": "github-repos/coq/clucas26e4-riesz-logic", "path": "github-repos/coq/clucas26e4-riesz-logic/riesz-logic-6ad0da80c8922d186c777d2c8f1a42d381abfb2d/OLlibs/wf_prod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.730169436693623}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Core logical definitions (all imported from the Prelude)                *\n**************************************************************************)\n\nSet Implicit Arguments.\n\n\n(* ********************************************************************** *)\n(** * Basic logical connectives *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [True] *)\n\n(** From Prelude:\n\n    Inductive True : Prop :=\n      | I : True.\n\n    Hint Constructors True : core.\n\n  Remark: [constructor] should be renamed to [True_intro].\n  Single-letter variable names should be reserved to the user.\n\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [False] *)\n\n(** From Prelude:\n\n    Inductive False : Prop := .\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [not] *)\n\n(** From Prelude:\n\n  Definition not (P : Prop) := P -> False.\n\n  Notation \"~ x\" := (not x) : type_scope.\n\n  Hint Unfold not : core.\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [and] *)\n\n(** From Prelude:\n\n    Inductive and (P Q : Prop) : Prop :=\n      | conj : P -> Q -> and P Q.\n\n    Notation \"P /\\ Q\" := (and P Q) : type_scope.\n\n    Hint Constructors and : core.\n\n    Lemma proj1 : forall (P Q : Prop), P /\\ Q -> P.\n    Proof using. autos*. Qed.\n\n    Lemma proj2 : forall (P Q : Prop), P /\\ Q -> Q.\n    Proof using. autos*. Qed.\n\n  Remark: to follow conventions, [conj] should be renamed to [and_intro].\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [or] *)\n\n(** From Prelude:\n\n    Inductive or (P Q : Prop) : Prop :=\n      | or_introl : P -> or P Q  \n      | or_intror : Q -> or P Q.\n\n    Notation \"A \\/ B\" := (or A B) : type_scope.\n\n    Hint Constructors or : core.\n\n  Remark: to follow conventions, constructors should be [or_l] and [or_r].\n\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [iff] *)\n\n(** From Prelude:\n\n      Definition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\n      Notation \"P <-> Q\" := (iff P Q) : type_scope.\n\n      Hint Unfold iff.\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [eq] *)\n\n(** From Prelude:\n\n      Inductive eq (A:Type) (x:A) : A -> Prop :=\n        | eq_refl : eq x y.\n\n      Notation \"x = y :> A\" := (@eq A x y) : type_scope.\n      Notation \"x = y\" := (eq x y) : type_scope.\n      Notation \"x <> y :> A\" := (~ @eq A x y) : type_scope.\n      Notation \"x <> y\" := (~ eq x y) : type_scope.\n\n      Arguments eq_ind [A].\n      Arguments eq_rec [A].\n      Arguments eq_rect [A].\n\n      Hint Constructors eq : core.\n\n  Remark : to follow conventions, constructors should be named [eq_intro],\n  or [refl_eq].\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [exists x, P] *)\n\n(** From Prelude:\n\n    Inductive ex (A : Type) (P : A->Prop) : Prop :=\n      | ex_intro : forall x, P x -> ex P.\n\n    Notation \"'exists' x , p\" := (ex (fun x => p))\n      (at level 200, x ident, right associativity) : type_scope.\n    Notation \"'exists' x : t , p\" := (ex (fun x:t => p))\n      (at level 200, x ident, right associativity,\n        format \"'[' 'exists'  '/  ' x  :  t ,  '/  ' p ']'\")\n      : type_scope.\n\n    Hint Constructors ex : core.\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [forall x, P] and [P -> Q] *)\n\n(** [forall] and [->] are builtin in the logic.\n    [P -> Q] is short for [forall (_:P), Q]. *)\n\n(** From Prelude: \n\n    Definition all (A : Type) (P : A->Prop) := forall (x:A), P x.\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [{x | P}] (subset type) *)\n\n(** From Prelude: \n\n    Inductive sig (A : Type) (P : A->Prop) : Type :=\n      | exist : forall x, P x -> sig P.\n\n    Notation \"{ x | P }\" := (sig (fun x => P)) : type_scope.\n    Notation \"{ x : A | P }\" := (sig (fun x:A => P)) : type_scope.\n    Add Printing Let sig.\n\n  Remark : to follow conventions, constructor should be named [sig_intro].\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [{x & P}] (subset type in Type) *)\n\n(** From Prelude: \n\n    Inductive sigT (A : Type) (P : A -> Type) : Type :=\n      | existT : forall x, P x -> sigT P.\n\n    Notation \"{ x & P }\" := (sigT (fun x:A => P)) : type_scope.\n    Notation \"{ x : A & P }\" := (sigT (fun x:A => P)) : type_scope.\n    Add Printing Let sigT.\n\n  Remark : to follow conventions, constructor should be named [sigT_intro].\n\n*)\n\n\n", "meta": {"author": "tilk", "repo": "tlc", "sha": "9a07c989dfc12aba4c5fb02107761c8d7e281996", "save_path": "github-repos/coq/tilk-tlc", "path": "github-repos/coq/tilk-tlc/tlc-9a07c989dfc12aba4c5fb02107761c8d7e281996/src/LibLogicCore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.73016942847512}}
{"text": "Require Export \"Prop_J\".\n\nInductive and (P Q: Prop) :Prop :=\n  conj: P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q): type_scope.\n\nCheck conj.\n\nTheorem and_example:\n  (ev 0) /\\ (ev 4).\nProof.\n  apply conj.\n  apply ev_0.\n  apply ev_SS. apply ev_SS. apply ev_0.\nQed.\n\nPrint and_example.\n\nTheorem and_example':\n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n  - apply ev_0.\n  - apply ev_SS. apply ev_SS. apply ev_0.\nQed.\n\nTheorem proj1: forall P Q: Prop,\n                 P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H.\n  apply H0.\nQed.\n\nTheorem proj2: forall P Q: Prop,\n                 P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  inversion H as [ Hp Hq].\n  apply Hq.\nQed.\n\nTheorem and_commut: forall P Q: Prop,\n                      P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q H.\n  inversion H as [Hp Hq].\n  split.\n  - apply Hq.\n  - apply Hp.\nQed.\n\nPrint and_commut.\n\nTheorem and_assoc: forall P Q R: Prop,\n                     P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [Hp Hqr].\n  inversion Hqr as [Hq Hr].\n  split.\n  split.\n  apply Hp.\n  apply Hq.\n  apply Hr.\nQed.\n\nTheorem even_ev: forall n: nat,\n                   (even n -> ev n)  /\\ (even (S n) -> ev (S n)).\nProof.\n  induction n.\n  + split.\n    intros H.\n    apply ev_0.\n    intros H.\n    inversion H.\n  + split.\n    apply IHn.\n    intros H.\n    apply ev_SS.\n    inversion IHn.\n    apply H0.\n    apply H.\nQed.\n\nDefinition conj_fact: forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  (fun (P Q R: Prop) =>\n    (fun (H0: and P Q) =>\n       (fun (H1: and Q R) =>\n       conj P R (proj1 P Q H0) (proj2 Q R H1)))\n  ).\n\nDefinition iff (P Q: Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                        (at level 95, no associativity): type_scope.\n\nTheorem iff_implies: forall P Q: Prop,\n                       (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  inversion H.\n  apply H0.\nQed.\n\nTheorem iff_sym: forall P Q: Prop,\n                   (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q H.\n  inversion H.\n  split.\n  apply H1.\n  apply H0.\nQed.\n\nTheorem iff_refl: forall P: Prop,\n                    P <-> P.\nProof.\n  intros P.\n  split.\n  intros H.\n  apply H.\n  intros H.\n  apply H.\nQed.\n\nTheorem iff_trans: forall P Q R: Prop,\n                     (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R H1 H2.\n  inversion H1.\n  inversion H2.\n  split.\n  intros Hp.\n  apply H3.\n  apply H.\n  apply Hp.\n  intros Hr.\n  apply H0.\n  apply H4.\n  apply Hr.\nQed.\n\nDefinition MyProp_iff_ev: forall n, MyProp n <-> ev n :=\n  (fun (n: nat) => conj (MyProp n -> ev n) (ev n -> MyProp n) (ev_MyProp n) (MyProp_ev n)).\n\nInductive or (P Q: Prop): Prop :=\n| or_introl: P -> or P Q\n| or_intror: Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q): type_scope.\n\nCheck or_introl.\nCheck or_intror.\n\nTheorem or_commut: forall P Q: Prop,\n                     P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H.\n  + apply or_intror.\n    apply H0.\n  + apply or_introl.\n    apply H0.\nQed.\n\nTheorem or_commut': forall P Q: Prop,\n                      P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n  + right. apply HP.\n  + left. apply HQ.\nQed.\n\nPrint or_commut.\n\nTheorem or_distributes_over_and_1: forall P Q R: Prop,\n                                     P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. inversion H as [HP | [HQ HR]].\n  + split.\n    left. apply HP.\n    left. apply HP.\n  + split.\n    right. apply HQ.\n    right. apply HR.\nQed.\n\nTheorem or_distributes_over_and_2: forall P Q R: Prop,\n                                     (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros P Q R. intros H. inversion H.\n  inversion H0. inversion H1.\n  left. apply H3.\n  left. apply H2.\n  inversion H1.\n  left. apply H3.\n  right. split. apply H2. apply H3.\nQed.\n\nTheorem or_distributes_over_and: forall P Q R: Prop,\n                                   P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n  + apply or_distributes_over_and_1.\n  + apply or_distributes_over_and_2.\nQed.\n\nTheorem andb_true__and: forall b c,\n                          andb b c = true -> b = true /\\ c = true.\nProof.\n  intros b c H.\n  destruct b.\n  + destruct c.\n    - apply conj. reflexivity. reflexivity.\n    - inversion H.\n      + inversion H.\nQed.\n\nTheorem and__andb_true: forall b c,\n                          b = true /\\ c = true -> andb b c = true.\nProof.\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity.\nQed.\n\nTheorem andb_false: forall b c,\n                      andb b c = false -> b = false \\/ c = false.\nProof.\n  intros b c H.\n  destruct H.\n  destruct b.\n  right.  reflexivity.\n  left. reflexivity.\nQed.\n\nTheorem orb_true: forall b c,\n                    orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H.\n  destruct b.\n  + left. reflexivity.\n  + simpl in H. right. apply H.\nQed.\n\nTheorem orb_false: forall b c,\n                     orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H.\n  destruct b.\n  + simpl in H. inversion H.\n  +  apply conj. reflexivity. simpl in H. apply H.\nQed.\n\nInductive False: Prop :=.\n\n\nTheorem False_implies_nonsense:\n  False -> 2 + 2 = 5.\nProof.\n  intros contra.\n  inversion contra.\nQed.\n\nTheorem nonsense_implies_False:\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.\nQed.\n\nTheorem ex_falso_quodlibet: forall (P:Prop),\n                              False -> P.\nProof.\n  intros P contra.\n  inversion contra.\nQed.\n\n\nDefinition not (P: Prop) := P -> False.\n\nNotation \"~ x\" := (not x): type_scope.\nCheck not.\n\nTheorem not_False:\n  ~ False.\nProof.\n  unfold not. intros H. inversion H.\nQed.\n\nTheorem contradiction_implies_anything: forall P Q: Prop,\n                                          (P /\\ ~P) -> Q.\nProof.\n  intros P Q H. inversion H as [HP HNP].\n  unfold not in HNP.\n  apply HNP in HP.\n  inversion HP.\nQed.\n\nTheorem double_neg: forall P: Prop,\n                      P -> ~~P.\nProof.\n  intros P H.\n  unfold not.\n  intros I.\n  apply I in H.\n  inversion H.\nQed.\n\nTheorem contrapositive: forall P Q: Prop,\n                          (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H.\n  unfold not.\n  intros I.\n  intros J.\n  apply H in J.\n  apply I in J.\n  inversion J.\nQed.\n\nTheorem not_both_true_and_false: forall P: Prop,\n                                   ~ (P /\\ ~ P).\nProof.\n  intros P.\n  unfold not.\n  intros H.\n  inversion H.\n  apply H1 in H0.\n  inversion H0.\nQed.\n\nTheorem five_not_even:\n  ~ ev 5.\nProof.\n  unfold not. intros H.\n  inversion H.\n  inversion H1.\n  inversion H3.\nQed.\n\nTheorem ev_not_ev_S: forall n,\n                       ev n -> ~ ev (S n).\nProof.\n  unfold not.\n  intros n H.\n  induction H.\n  + intros I. inversion I.\n  + intros I.\n    inversion I.\n    apply IHev in H1.\n    inversion H1.\nQed.\n\nNotation \"x <> y\" := (~ (x = y)): type_scope.\n\nTheorem not_false_then_true: forall b: bool,\n                               b <> false -> b = true.\nProof.\n  intros b H.\n  destruct b.\n  + reflexivity.\n  + unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\nQed.\n\nTheorem not_eq_beq_false: forall n n': nat,\n                            n <> n' -> beq_nat n n' = false.\nProof.\n  intros n.\n  induction n.\n  + intros n'.\n    induction n'.\n  - simpl. intros H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - intros H. simpl. reflexivity.\n    + intros n'. induction n'.\n  - intros H. reflexivity.\n  - intros H. simpl.\n    apply IHn.\n    unfold not in H.\n    unfold not.\n    replace (S n = S n') with (n = n') in H.\n    apply H.\nAdmitted.\n\n\nInductive ex (X: Type) (P: X -> Prop): Prop :=\n  ex_intro: forall(witness: X), P witness -> ex X P.\n\nDefinition some_nat_is_even: Prop :=\n  ex nat ev.\n\nDefinition snie: some_nat_is_even :=\n  ex_intro _ ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\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\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness := 2).\n  reflexivity.\nQed.\n\nExample exists_example_1': exists n,\n                             n + (n * n) = 6.\nProof.\n  exists 2.\n  reflexivity.\nQed.\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.\n  exists (2 + witness).\n  apply H0.\nQed.\n\nDefinition p: ex nat (fun n => ev (S n)) :=\n  ex_intro _ (fun n =>  ev (S n)) 1 (ev_SS 0 ev_0).\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. intros H.\n  unfold not.\n  intros I.\n  inversion I.\n  apply H0.\n  apply H.\nQed.\n\nDefinition peirce := forall P Q: Prop,\n  ((P -> Q)->P)->P.\nDefinition classic := forall P:Prop,\n  ~~P -> P.\nDefinition excluded_middle := 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 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).\n  intros X P Q.\n  split.\n  + intros H.\n    inversion H.\n    inversion H0.\n    left.  exists witness. apply H1.\n    right. exists witness. apply H1.\n  + intros H.\n    inversion H.\n    inversion H0.\n    exists witness. left. apply H1.\n    inversion H0.\n    exists witness. right. apply H1.\nQed.\n\nModule MyEquality.\n  Inductive eq (X: Type): X -> X -> Prop :=\n    refl_equal: forall x, eq X x x.\n  Notation \"x = y\" := (eq _ x y)\n                        (at level 70, no associativity): type_scope.\n\n  Inductive eq' (X: Type) (x: X): X -> Prop :=\n    refl_equal' : eq' X x x.\n\n  Notation \"x =' y\" := (eq' _ x y)\n                         (at level 70, no associativity): type_scope.\n  Theorem two_defs_of_equal_concide: forall (X: Type) (x y: X),\n                                       x = y <-> x =' y.\n  Proof.\n    intros X x y.\n    split.\n    intros H.\n    inversion H.\n    reflexivity.\n    intros H.\n    inversion H.\n    apply refl_equal.\n  Qed.\n\n  Definition four: 2 + 2 = 1 + 3 :=\n    refl_equal nat 4.\n  Definition singleton: forall (X: Set) (x: X), []++[x] = x::[] :=\n    fun (X: Set) (x: X) => refl_equal (list X) [x].\nEnd MyEquality.\n\nModule LeFirstTry.\n  Inductive 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)).\nEnd LeFirstTry.\n\n\nInductive le(n: nat): nat -> Prop :=\n| le_n: le n n\n| le_S: forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nCheck le_ind.\n\nTheorem test_le1:\n  3 <= 3.\nProof.\n  apply le_n.\nQed.\n\nTheorem test_le2:\n  3 <= 6.\nProof.\n  apply le_S. apply le_S. apply le_S.\n  apply le_n.\nQed.\n\nTheorem test_le3:\n  ~(2 <= 1).\nProof.\n  intros H.\n  inversion H.\n  inversion H1.\nQed.\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 (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\nModule R.\n  Inductive 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\nEnd R.\n\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  intros Ex X P H x.\n  unfold not in H.\n  unfold excluded_middle in Ex.\n  apply Ex with (P x)\n*)", "meta": {"author": "KeenS", "repo": "read_sf", "sha": "68bf80da32a1783540a7bef8d9171b2f94a17c1a", "save_path": "github-repos/coq/KeenS-read_sf", "path": "github-repos/coq/KeenS-read_sf/read_sf-68bf80da32a1783540a7bef8d9171b2f94a17c1a/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7301583785583882}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\n(** \"_Algorithms are the computational content of proofs_.\"  --Robert Harper *)\n\n(** We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types like [nat] or [list] and functions over\n    these types, and for _proving_ properties of these programs, using\n    inductive propositions (like [ev]), implication, universal\n    quantification, and the like.  So far, we have mostly treated\n    these mechanisms as if they were quite separate, and for many\n    purposes this is a good way to think.  But we have also seen hints\n    that Coq's programming and proving facilities are closely related.\n    For example, the keyword [Inductive] is used to declare both data\n    types and propositions, and [->] is used both to describe the type\n    of functions on data and logical implication.  This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are\n    almost the same thing.  In this chapter we will study how this\n    works.\n\n    We have already seen the fundamental idea: provability in Coq is\n    represented by concrete _evidence_.  When we construct the proof\n    of a basic proposition, we are actually building a tree of\n    evidence, which can be thought of as a data structure.\n\n    If the proposition is an implication like [A -> B], then its proof\n    will be an evidence _transformer_: a recipe for converting\n    evidence for A into evidence for B.  So at a fundamental level,\n    proofs are simply programs that manipulate evidence. *)\n\n(** Question: If evidence is data, what are propositions themselves?\n\n    Answer: They are types! *)\n\n(** Look again at the formal definition of the [ev] property.  *)\n\nPrint ev.\n(* ==>\n  Inductive ev : nat -> Prop :=\n    | ev_0 : ev 0\n    | ev_SS : forall n, ev n -> ev (S (S n)).\n*)\n\n(** Suppose we introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can say \"is a proof of.\"  For example,\n    the second line in the definition of [ev] declares that [ev_0 : ev\n    0].  Instead of \"[ev_0] has type [ev 0],\" we can say that \"[ev_0]\n    is a proof of [ev 0].\" *)\n\n(** This pun between types and propositions -- between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\" -- is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation:\n\n                 propositions  ~  types\n                 proofs        ~  data values\n\n    See [Wadler 2015] (in Bib.v) for a brief history and up-to-date exposition. *)\n\n(** Many useful insights follow from this connection.  To begin with,\n    it gives us a natural interpretation of the type of the [ev_SS]\n    constructor: *)\n\nCheck ev_SS.\n(* ===> ev_SS : forall n,\n                  ev n ->\n                  ev (S (S n)) *)\n\n(** This can be read \"[ev_SS] is a constructor that takes two\n    arguments -- a number [n] and evidence for the proposition [ev\n    n] -- and yields evidence for the proposition [ev (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [ev]. *)\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** As with ordinary data values and functions, we can use the [Print]\n    command to see the _proof object_ that results from this proof\n    script. *)\n\nPrint ev_4.\n(* ===> ev_4 = ev_SS 2 (ev_SS 0 ev_0)\n     : ev 4  *)\n\n(** Indeed, we can also write down this proof object _directly_,\n    without the need for a separate proof script: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n(* ===> ev 4 *)\n\n(** The expression [ev_SS 2 (ev_SS 0 ev_0)] can be thought of as\n    instantiating the parameterized constructor [ev_SS] with the\n    specific arguments [2] and [0] plus the corresponding proof\n    objects for its premises [ev 2] and [ev 0].  Alternatively, we can\n    think of [ev_SS] as a primitive \"evidence constructor\" that, when\n    applied to a particular number, wants to be further applied to\n    evidence that that number is even; its type,\n\n      forall n, ev n -> ev (S (S n)),\n\n    expresses this functionality, in the same way that the polymorphic\n    type [forall X, list X] expresses the fact that the constructor\n    [nil] can be thought of as a function from types to empty lists\n    with elements of that type. *)\n\n(** We saw in the [Logic] chapter that we can use function\n    application syntax to instantiate universally quantified variables\n    in lemmas, as well as to supply evidence for assumptions that\n    these lemmas impose.  For instance: *)\n\nTheorem ev_4': ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(* ################################################################# *)\n(** * Proof Scripts *)\n\n(** The _proof objects_ we've been discussing lie at the core of how\n    Coq operates.  When Coq is following a proof script, what is\n    happening internally is that it is gradually constructing a proof\n    object -- a term whose type is the proposition being proved.  The\n    tactics between [Proof] and [Qed] tell it how to build up a term\n    of the required type.  To see this process in action, let's use\n    the [Show Proof] command to display the current state of the proof\n    tree at various points in the following tactic proof. *)\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with a\n    \"hole\" (indicated by [?Goal] here, and so on), and it knows what\n    type of evidence is needed to fill this hole.  \n\n    Each hole corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    evidence we've built stored in the global context under the name\n    given in the [Theorem] command. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand, as shown above. Then we can use [Definition]\n    (rather than [Theorem]) to give a global name directly to this\n    evidence. *)\n\nDefinition ev_4''' : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint ev_4.\n(* ===> ev_4    =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\n\n(** **** Exercise: 2 stars (eight_is_even)  *)\n(** Give a tactic proof and a proof object showing that [ev 8]. *)\n\nTheorem ev_8 : ev 8.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nDefinition ev_8' : ev 8 \n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Quantifiers, Implications, Functions *)\n\n(** In Coq's computational universe (where data structures and\n    programs live), there are two sorts of values with arrows in their\n    types: _constructors_ introduced by [Inductive]ly defined data\n    types, and _functions_.\n\n    Similarly, in Coq's logical universe (where we carry out proofs),\n    there are two ways of giving evidence for an implication:\n    constructors introduced by [Inductive]ly defined propositions,\n    and... functions! *)\n\n(** For example, consider this statement: *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\n(** What is the proof object corresponding to [ev_plus4]?\n\n    We're looking for an expression whose _type_ is [forall n, ev n ->\n    ev (4 + n)] -- that is, a _function_ that takes two arguments (one\n    number and a piece of evidence) and returns a piece of evidence!\n\n    Here it is: *)\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah],\" and that Coq treats [4 + n] and [S (S (S (S n)))]\n    as synonyms. Another equivalent way to write this definition is: *)\n\nDefinition ev_plus4'' (n : nat) (H : ev n)\n                    : ev (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\n(* ===> \n     : forall n : nat, ev n -> ev (4 + n) *)\n\n(** When we view the proposition being proved by [ev_plus4] as a\n    function type, one interesting point becomes apparent: The second\n    argument's type, [ev n], mentions the _value_ of the first\n    argument, [n].\n\n    While such _dependent types_ are not found in conventional\n    programming languages, they can be useful in programming too, as\n    the recent flurry of activity in the functional programming\n    community demonstrates. *)\n\n(** Notice that both implication ([->]) and quantification ([forall])\n    correspond to functions on evidence.  In fact, they are really the\n    same thing: [->] is just a shorthand for a degenerate use of\n    [forall] where there is no dependency, i.e., no need to give a\n    name to the type on the left-hand side of the arrow:\n\n           forall (x:nat), nat  \n        =  forall (_:nat), nat  \n        =  nat -> nat\n*)\n\n\n(** For example, consider this proposition: *)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : ev n), ev (n + 2).\n\n(** A proof term inhabiting this proposition would be a function\n    with two arguments: a number [n] and some evidence [E] that [n] is\n    even.  But the name [E] for this evidence is not used in the rest\n    of the statement of [ev_plus2], so it's a bit silly to bother\n    making up a name for it.  We could write it like this instead,\n    using the dummy identifier [_] in place of a real name: *)\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : ev n), ev (n + 2).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, ev n -> ev (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\n(** If we can build proofs by giving explicit terms rather than\n    executing tactic scripts, you may be wondering whether we can\n    build _programs_ using _tactics_ rather than explicit terms.\n    Naturally, the answer is yes! *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n\nPrint add1.\n(* ==>\n    add1 = fun n : nat => S n\n         : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than\n    with [:=] followed by a term.  This tells Coq to enter _proof\n    scripting mode_ to build an object of type [nat -> nat].  Also, we\n    terminate the proof with [Defined] rather than [Qed]; this makes\n    the definition _transparent_ so that it can be used in computation\n    like a normally-defined function.  ([Qed]-defined objects are\n    opaque during computation.)\n\n    This feature is mainly useful for writing functions with dependent\n    types, which we won't explore much further in this book.  But it\n    does illustrate the uniformity and orthogonality of the basic\n    ideas in Coq. *)\n\n\n(* ################################################################# *)\n(** * Logical Connectives as Inductive Types *)\n\n(** Inductive definitions are powerful enough to express most of the\n    connectives and quantifiers we have seen so far.  Indeed, only\n    universal quantification (and thus implication) is built into Coq;\n    all the others are defined inductively.  We'll see these\n    definitions in this section. *)\n\nModule Props.\n\n(** ** Conjunction\n\n    To prove that [P /\\ Q] holds, we must present evidence for both\n    [P] and [Q].  Thus, it makes sense to define a proof object for [P\n    /\\ Q] as consisting of a pair of two proofs: one for [P] and\n    another one for [Q]. This leads to the following definition. *)\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\n\nEnd And.\n\n(** Notice the similarity with the definition of the [prod] type,\n    given in chapter [Poly]; the only difference is that [prod] takes\n    [Type] arguments, whereas [and] takes [Prop] arguments. *)\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\n\n(** This should clarify why [destruct] and [intros] patterns can be\n    used on a conjunctive hypothesis.  Case analysis allows us to\n    consider all possible ways in which [P /\\ Q] was proved -- here\n    just one (the [conj] constructor).  Similarly, the [split] tactic\n    actually works for any inductively defined proposition with only\n    one constructor.  In particular, it works for [and]: *)\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\nQed.\n\n(** This shows why the inductive definition of [and] can be\n    manipulated by tactics as we've been doing.  We can also use it to\n    build proofs directly, using pattern-matching.  For instance: *)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, optional (conj_fact)  *)\n(** Construct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R \n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n\n\n(** ** Disjunction\n\n    The inductive definition of disjunction uses two constructors, one\n    for each side of the disjunct: *)\n\nModule Or.\n\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\n\nEnd Or.\n\n(** This declaration explains the behavior of the [destruct] tactic on\n    a disjunctive hypothesis, since the generated subgoals match the\n    shape of the [or_introl] and [or_intror] constructors.\n\n    Once again, we can also directly write proof objects for theorems\n    involving [or], without resorting to tactics. *)\n\n(** **** Exercise: 2 stars, optional (or_commut'')  *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P \n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** ** Existential Quantification\n\n    To give evidence for an existential quantifier, we package a\n    witness [x] together with a proof that [x] satisfies the property\n    [P]: *)\n\nModule Ex.\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro : forall x : A, P x -> ex P.\n\nEnd Ex.\n\n(** This may benefit from a little unpacking.  The core definition is\n    for a type former [ex] that can be used to build propositions of\n    the form [ex P], where [P] itself is a _function_ from witness\n    values in the type [A] to propositions.  The [ex_intro]\n    constructor then offers a way of constructing evidence for [ex P],\n    given a witness [x] and a proof of [P x]. *)\n\n(** The more familiar form [exists x, P x] desugars to an expression\n    involving [ex]: *)\n\nCheck ex (fun n => ev n).\n(* ===> exists n : nat, ev n\n        : Prop *)\n\n(** Here's how to define an explicit proof object involving [ex]: *)\n\nDefinition some_nat_is_even : exists n, ev n :=\n  ex_intro ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** **** Exercise: 2 stars, optional (ex_ev_Sn)  *)\n(** Complete the definition of the following proof object: *)\n\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) \n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** [True] and [False] *)\n\n(** The inductive definition of the [True] proposition is simple: *)\n\nInductive True : Prop :=\n  | I : True.\n\n(** It has one constructor (so every proof of [True] is the same, so\n    being given a proof of [True] is not informative.) *)\n\n(** [False] is equally simple -- indeed, so simple it may look\n    syntactically wrong at first glance! *)\n\nInductive False : Prop :=.\n\n(** That is, [False] is an inductive type with _no_ constructors --\n    i.e., no way to build evidence for it. *)\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has the\n    following inductive definition.  (Actually, the definition in the\n    standard library is a small variant of this, which gives an\n    induction principle that is slightly easier to use.) *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n| eq_refl : forall x, eq x x.\n\nNotation \"x = y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\n(** The way to think about this definition is that, given a set [X],\n    it defines a _family_ of propositions \"[x] is equal to [y],\"\n    indexed by pairs of values ([x] and [y]) from [X].  There is just\n    one way of constructing evidence for each member of this family:\n    applying the constructor [eq_refl] to a type [X] and a value [x :\n    X] yields evidence that [x] is equal to [x]. *)\n\n(** We can use [eq_refl] to construct evidence that, for example, [2 =\n    2].  Can we also use it to construct evidence that [1 + 1 = 2]?\n    Yes, we can.  Indeed, it is the very same piece of evidence!\n\n    The reason is that Coq treats as \"the same\" any two terms that are\n    _convertible_ according to a simple set of computation rules.\n\n    These rules, which are similar to those used by [Compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.  *)\n\nLemma four: 2 + 2 = 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove equalities up\n    to now is essentially just short-hand for [apply eq_refl].\n\n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).\n\n    But you can see them directly at work in the following explicit\n    proof objects: *)\n\nDefinition four' : 2 + 2 = 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), []++[x] = x::[]  :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\nEnd MyEquality.\n\n\n(** **** Exercise: 2 stars (equality__leibniz_equality)  *)\n(** The inductive definition of equality implies _Leibniz equality_:\n    what we mean when we say \"[x] and [y] are equal\" is that every\n    property on [P] that is true of [x] is also true of [y].  *)\n\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x = y -> forall P:X->Prop, P x -> P y.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (leibniz_equality__equality)  *)\n(** Show that, in fact, the inductive definition of equality is\n    _equivalent_ to Leibniz equality: *)\n\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P:X->Prop, P x -> P y) -> x = y.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves.\n\n    In general, the [inversion] tactic...\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n\n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are\n    two constructors, so two subgoals get generated.  The\n    conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [and], there is\n    only one constructor, so only one subgoal gets generated.  Again,\n    the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal.  The\n    constructor does have two arguments, though, and these can be seen\n    in the context in the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [eq], there is\n    again only one constructor, so only one subgoal gets generated.\n    Now, though, the form of the [refl_equal] constructor does give us\n    some extra information: it tells us that the two arguments to [eq]\n    must be the same!  The [inversion] tactic adds this fact to the\n    context. *)\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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.7301583697600486}}
{"text": "(** * 3. Coq でのプログラミング *)\n(** 3.2 再帰的な型と関数 *)\nModule Section3_2.\n\n(** 自然数 nat について *)\nPrint nat.\n(* Inductive nat : Set :=  \n   O : nat \n | S : nat -> nat \n*)\n\nEval compute in (S (S (S O))).\n\n(** 自然数の加法 *)\nFixpoint add(n m:nat):nat :=\nmatch n with\n| O => m\n| S n' => S (add n' m)\nend.\n\nEval compute in (add (S (S O)) (S (S (S O)))).\n\n(** 自然数の比較 *)\nFixpoint eq_nat(n m:nat):bool :=\nmatch n,m with\n| O,O => true\n| S n', S m' => eq_nat n' m'\n| _,_ => false\nend.\n\nEval compute in (eq_nat 3 3).\nEval compute in (eq_nat 3 2).\n\n(* \nFixpoint le_nat(n m:nat):bool :=\n(* code here *)\n\nEval compute in (le_nat 2 3).  (* = true *) \nEval compute in (le_nat 3 3).  (* = true *)\nEval compute in (le_nat 4 3).  (* = false *)\n\n*)\n\n(** 再帰関数の停止性 *)\nFixpoint add'(n m:nat){struct n}:nat :=\nmatch n with\n| O => m\n| S n' => S (add n' m)\nend.\n\n(** 課題２：自然数の関数 *)\n(* 1. 掛け算を行う関数 mul を add を参考に定義せよ。 *)\n(*\nFixpoint mul(n m:nat) :=\n(* code here *)\n\nEval compute in (mul 2 3). (* = 6 *)\n*)\n\n(* 2. mul を用いて階乗を計算する関数 fact を定義せよ。*)\n(*\nFixpoint fact(n:nat) :=\n(* code here *)\n\nEval compute in (fact 4). (* = 24 *)\n*)\n\n(* 3. 引き算を行う関数 sub を定義してみよ。但し n = 0 の場合は sub 0 m = 0と定義する。*)\n(*\nFixpoint sub(n m:nat):nat :=\n(* code here *)\n\nEval compute in (sub 5 2). (* = 3 *)\nEval compute in (sub 4 4). (* = 0 *)\nEval compute in (sub 2 5). (* = 0 *)\n*)\n\n(* 4. 次の関数 div3 は何を計算する関数か考えよ。また Eval を用いて 動作を確認してみよ。*)\nFixpoint div3(n:nat) :=\nmatch n with\n| S (S (S n')) => S (div3 n')\n| _ => O\nend.\n\nEval compute in (div3 2).\nEval compute in (div3 6).\nEval compute in (div3 7).\n\nEnd Section3_2.\n\n(** 3.3 多相型 *)\nModule Section3_3. \n\n(** 多相型とは *)\nDefinition cond{A:Set}(c:bool)(vt vf:A) : A :=\nmatch c with\n| true => vt\n| false => vf\nend.\n\nEval compute in (cond true 2 3).\nEval compute in (cond false false true).\nEval compute in (@cond nat false 2 3).\n\n(** option型 *)\nPrint option.\n(* Inductive option (A : Type) : Type :=  Some : A -> option A | None : option A *)\n\nDefinition option_map {A B:Type}(f:A->B)(o:option A) :=\nmatch o with\n| Some a => Some (f a)\n| None => None\nend.\n\nEval compute in (option_map (fun x => x+1) (Some 1)).\nEval compute in (option_map (fun x => x+1) None).\n\n(** prod型とsum型 *)\n\nPrint prod.\n(* Inductive prod (A B : Type) : Type :=  pair : A -> B -> A * B *)\n\nPrint sum.\n(* Inductive sum (A B : Type) : Type :=  inl : A -> A + B | inr : B -> A + B *)\n\nCheck (2,true,3).\n\nDefinition test_sum(s:sum nat bool) :=\nmatch s with\n| inl n => n\n| inr true => 1\n| inr false => 0\nend.\n\n(** List型 *)\nRequire Import List.\nPrint list.\n(* Inductive list (A : Type) : Type :=\n    nil : list A \n  | cons : A -> list A -> list A\n*)\n\nCheck (1::2::nil).\n\n(** List に対する再帰関数 *)\n(* Listの連結 *)\nFixpoint append{A:Type}(xs ys:list A):=\nmatch xs with\n| nil => ys\n| x::xs' => x::(append xs' ys)\nend.\nEval compute in (append (1::2::nil) (3::4::nil)).\n\n(* Listの最後の要素 *)\nFixpoint olast{A:Type}(xs:list A):option A :=\nmatch xs with\n| nil => None\n| a::nil => Some a\n| _::xs' => olast xs'\nend.\nEval compute in (olast (1::2::3::nil)).\nEval compute in (olast (1::nil)).\nEval compute in (olast (@nil nat)).\n\n(** 課題３：Listへの関数 *)\n(* 1. リストの長さを与える関数 len{A:Type}(xs:list A):nat を定義 せよ。*)\n(*\nFixpoint len{A:Type}(xs:list A):nat :=\n\nEval compute in (len (1::2::3::nil)). (* = 3 *)\n*)\n\n(* 2. list bool の入力を受け取り、全要素が true の時 true を返す関数\n all_true(xs:list bool):bool を定義せよ。\n但し nil に対し ては true を返すとせよ。*)\n(*\nFixpoint all_true(xs:list bool):bool :=\n\nEval compute in (all_true (@nil bool)).  (* = true *)\nEval compute in (all_true (true::true::nil)).  (* = true *)\nEval compute in (all_true (true::true::false::nil)).  (* = false *)\n*)\n\n(* 3. リストの先頭要素 x があれば Some x を、空リストに対しては \nNone を返す、関数 ohead{A:Type}(xs:list A):option A を\n定義せよ。*)\n(*\nDefinition ohead{A:Type}(xs:list A):option A :=\n\nEval compute in (ohead (@nil nat)).  (* = None *)\nEval compute in (ohead (1::nil)).  (* = Some 1 *)\nEval compute in (ohead (1::2::nil)).  (* = Some 1 *)\n*)\n\n(* 4. 自然数s,nに対してs :: s+1 :: ... :: (s+n-1) :: nilを\n 返す関数 nat_list(s n:nat):list nat を定義せよ。*)\n(*\nFixpoint nat_list(s n:nat):list nat :=\n\nEval compute in (nat_list 3 5).  (* = 3::4::5::6::7::nil *)\n*)\n\n(* 5. リストを反転する関数 reverse{A:Type}(xs:list A):list A を\n 定義せよ。必要なら append を使え。*)\n(*\nFixpoint reverse{A:Type}(xs:list A):list A :=\n\nEval compute in (reverse (1::2::3::nil)). (* =  3::2::1::nil *)\n*)\nEnd Section3_3.\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/tutorial20120202/tutorial2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7301583679035383}}
{"text": "Require Import Nat PeanoNat Bool BoolEq EqNat Le Orders.\nRequire Import Lia ZifyBool.\n\nOpen Scope nat_scope.\n\nTheorem refl : forall a : nat, a = a.\nProof.\n  intro.\n  reflexivity.\nQed.\n\nLocate Nat.\nLocate beq_nat.\n\nDefinition refl_example : S (S (S O)) = 3 := eq_refl 3.\n\nInductive List : Set :=\n  | nil : List\n  | cons (n : nat) (tail : List) : List.\n\nDefinition Empty (l : List) : Prop := match l with\n  | nil => True\n  | cons _ _ => False\n  end.\n\nFixpoint length (l : List) : nat := match l with\n  | nil => 0\n  | cons _ rest => 1 + length rest\n  end.\n\nFixpoint sum (l : List) : nat := match l with\n  | nil => 0\n  | cons n rest => n + sum rest\n  end.\n\nTheorem sum_example : sum (cons 5 (cons 4 (cons 8 nil))) = 17.\nProof.\n  cbv delta; fold Nat.add; cbv iota; fold sum.\n  cbv beta.\n  cbv iota.\n  cbv.\n  reflexivity.\nQed.\n\nInductive Sorted: List -> Prop :=\n  | Sorted_empty : Sorted nil\n    (* prázdný List je vždy seřazen *)\n  | Sorted_one (n : nat) : Sorted(cons n nil)\n    (* List s jedním prvkem je také vždy seřazen *)\n  | Sorted_recursive (n : nat) (m : nat) (rest : List)\n    (* List s více prvky [n, m, ...rest] je seřazen, když:*)\n      (* 1. n a m jsou správně seřazeny: *)\n        (first_pair_sorted : n <= m) \n      (* 2. zbytek [m, ...rest] je seřazen: *)\n        (rest_sorted : Sorted (cons m rest))\n      : Sorted (cons n (cons m rest)).\n\nTheorem example_sorted : Sorted (cons 2 (cons 3 (cons 5 nil))).\nProof.\n  refine (Sorted_recursive 2 3 (cons 5 nil) _ _).\n  auto.\n  (* Dokonce lze odvodit úplně vše *)\n  (* refine (recursive_sorted _ _ _ _ _). *)\n  constructor.\n  auto.\n  (* Zbytek už je jednoduchý *)\n  refine (Sorted_one 5).\nQed.\n\nTheorem example_not_sorted : ~ Sorted (cons 5 (cons 5 (cons 2 nil))).\nProof.\n  unfold not.\n  intro S.\n  inversion S.\n  clear n m rest first_pair_sorted H0 H1 H2 S.\n\n  inversion rest_sorted.\n  clear n m rest H0 H1 H2 rest_sorted rest_sorted0.\n\n\n  repeat apply le_S_n in first_pair_sorted.\n  apply Nat.nle_succ_0 in first_pair_sorted.\n  apply first_pair_sorted.\nQed.\n\nFixpoint min_elem (l:List) : option nat := match l with\n  | nil => None\n  | cons n r => Some (match min_elem r with\n    | None => n\n    | Some m => if n <? m then n else m\n  end)\nend.\n\n\nTheorem example_min_elem : min_elem (cons 4 (cons 6 (cons 2 nil))) = Some 2.\nProof.\n  compute.\n  reflexivity.\nQed.\n\nTheorem has_min : forall (l : List), length l > 0 -> exists (n : nat), min_elem l = Some n.\nProof.\n  intros.\n  induction l.\n  - compute in H.\n    apply le_n_0_eq in H.\n    discriminate.\n  - clear IHl H.\n    simpl.\n    eauto.\n  (* Show Proof. *)\nQed.\n\nFixpoint elem (n:nat) (l:List) : bool := match l with\n  | nil => false\n  | cons m r => (if n =? m then true else elem n r)\nend.\n\nInductive Elem (n: nat) : List -> Prop :=\n  | Elem_triv : forall l, Elem n (cons n l)\n  | Elem_cons : forall l u, Elem n l -> Elem n (cons u l).\n\nTheorem Elem_tail: forall l n u, Elem n (cons u l) -> n <> u -> Elem n l.\nProof.\n  intros.\n  inversion H.\n  - contradiction.\n  - exact H2.\nQed.\n\nTheorem Elem_el: forall l n u, Elem n (cons u l) <-> n = u \\/ Elem n l.\nProof.\n  intros.\n  split.\n  - destruct (Nat.eq_decidable n u).\n    left. exact H.\n    right.\n    apply (Elem_tail _ _ _ H0 H).\n  - intros.\n    destruct H as [-> | E].\n    apply Elem_triv.\n    apply Elem_cons.\n    exact E.\nQed.\n\nTheorem elem_spec n l: Elem n l <-> elem n l = true.\nProof.\n  split.\n  - intro E.\n    induction l.\n    + inversion E.\n    + simpl.\n      Search reflect.\n      destruct (Nat.eqb_spec n n0); [reflexivity| ].\n      apply IHl.\n      apply Elem_el in E.\n      destruct E; [contradiction |].\n      exact H.\n  - intro E.\n    induction l.\n    + simpl in E.\n      discriminate E.\n    + simpl in E.\n      destruct (Nat.eqb_spec n n0) as [-> | D].\n      * apply Elem_triv.\n      * apply Elem_cons.\n        exact (IHl E).\nQed.\n\nTheorem elem_reflect n l: reflect (Elem n l) (elem n l).\n  induction l.\n  simpl.\n  apply ReflectF.\n  intro.\n  inversion H.\n  inversion IHl.\n  simpl.\n  destruct (Nat.eqb_spec n n0).\n  apply ReflectT.\n  rewrite e.\n  apply Elem_triv.\n  rewrite <- H.\n  apply ReflectT.\n  apply Elem_cons.\n  exact H0.\n  simpl.\n  destruct (Nat.eqb_spec n n0).\n  apply ReflectT.\n  rewrite e.\n  apply Elem_triv.\n  rewrite <- H.\n  apply ReflectF.\n  intro.\n  apply Elem_el in H1.\n  destruct H1; contradiction.\nQed.\n\nTheorem elem_not_nil : forall l n, Elem n l -> length l > 0. \nProof.\n  intros.\n  induction l.\n  - compute in H.\n    inversion H.\n  - compute.\n    apply le_n_S.\n    apply le_0_n.\nQed.\n\nFixpoint remove_elem n l: List :=\n  match l with\n    | nil => nil\n    | cons m l' => if m =? n then remove_elem n l' else cons m (remove_elem n l')\n  end.\n\nLtac conv_eq := match goal with\n                  | H : (?a =? ?b) = true  |- _ => apply beq_nat_true  in H; conv_eq\n                  | H : (?a =? ?b) = false |- _ => apply beq_nat_false in H; conv_eq\n                  | _ => idtac\n                end.\n\nLtac conv_ord := conv_eq; match goal with\n                  | H : (?a <? ?b) = true  |- _ => apply Nat.ltb_lt    in H; conv_ord\n                  | H : (?a <? ?b) = false |- _ => apply Nat.ltb_ge    in H; conv_ord\n                  | _ => idtac\n                end.\n\nTheorem elem_remove_elem: forall l n m, Elem n l -> n <> m -> Elem n (remove_elem m l).\nProof.\n  intros.\n  induction l.\n  compute.\n  exact H.\n  simpl.\n  destruct (n0 =? m) eqn:E.\n  - conv_eq.\n    destruct E.\n    pose proof (Elem_tail _ _ _ H H0).\n    exact (IHl H1).\n  -\n    destruct (Nat.eq_decidable n0 n).\n    + destruct H1.\n      apply Elem_triv.\n    + apply Elem_cons.\n      apply Elem_tail in H; [ |apply not_eq_sym; exact H1].\n      apply IHl.\n      exact H.\nQed.\n\n\nTheorem len_gt_0_cons : forall l, length l > 0 -> exists n i, l = cons n i.\nProof.\n  intros.\n  induction l.\n  compute in H.\n  apply Nat.nle_succ_0 in H.\n  contradiction.\n  eauto.\nQed.\n\nTheorem len_gt_0_not_nil : forall l, length l > 0 <-> l <> nil.\nProof.\n  split.\n  intros.\n  induction l.\n  compute in H.\n  apply Nat.nle_succ_0 in H.\n  contradiction.\n  discriminate.\n  intros.\n  induction l.\n  contradiction.\n  simpl.\n  compute.\n  apply le_n_S.\n  apply le_0_n.\nQed.\n\nTheorem min_elem_cons : forall l n, min_elem (cons n l) <> None.\nProof.\n  intros.\n  simpl.\n  discriminate.\nQed.\n\nTheorem total : forall l, length l > 0 -> min_elem l <> None.\nProof.\n  intros.\n  apply len_gt_0_cons in H.\n  destruct H as [n [ll e]].\n  rewrite e.\n  simpl.\n  discriminate.\nQed.\n\nDefinition min_elem1 (l:List) (D: length l > 0): nat :=\n  match min_elem l as min return min <> None -> nat with \n    | Some a => fun _ => a\n    | None => fun E => match E eq_refl with end\n  end (total l D).\n\nDefinition min_elem1_alt (l:List) (D: length l > 0): nat.\n  refine (match min_elem l as min return min <> None -> nat with \n    | Some a => fun _ => a\n    | None => fun E => _\n  end (total l D)).\n  destruct E.\n  reflexivity.\n  (* Show Proof. *)\nDefined.\n\nDefinition min_elem1_alt2 (l:List) (D: length l > 0): nat.\n  destruct (min_elem l) eqn:E.\n  - exact n.\n  - pose proof (total l D).\n    contradiction (H E).\nDefined.\n\nDefinition min_elem1_alt3 (l:List) (D: length l > 0): nat :=\n  match min_elem l as min return min <> None -> nat with \n    | Some a => fun _ => a\n    | None => fun E => ltac:(contradiction)\n  end (total l D).\n\nDefinition min_elem1_alt4 (l:List) (D: length l > 0): nat :=\n  match min_elem l as min return min <> None -> nat with \n    | Some a => fun _ => a\n    | None => fun E: None <> None => ltac:(contradiction) \n  end (total l D).\n\nPrint min_elem1_alt.\nPrint min_elem1_alt2.\nPrint min_elem1_alt3.\nPrint min_elem1_alt4.\n(* Search beq_nat. *)\n\nTheorem min_spec_elem: forall l H, Elem (min_elem1 l H) l.\nProof.\n  intro.\n  destruct l.\n  - intros L.\n    pose proof (Nat.nle_succ_0 _ L).\n    contradiction H.\n  - induction l; intros.\n    + unfold min_elem1.\n      simpl.\n      apply Elem_triv.\n    + assert (length (cons n l) > 0) by (simpl; lia).\n      pose proof (IHl H0).\n      clear IHl.\n      unfold min_elem1 in *.\n      simpl in *.\n      destruct (min_elem l).\n      destruct (n <? n1) eqn:E1;\n      destruct (n0 <? n1) eqn:E2;\n      destruct (n <? n0) eqn:E3;\n      try rewrite E1.\n      apply Elem_triv.\n      apply Elem_cons. apply Elem_triv.\n      apply Elem_triv.\n      apply Elem_triv.\n      apply Elem_triv.\n      apply Elem_cons. apply Elem_triv.\n      destruct (Nat.eq_dec n n1).\n      rewrite e.\n      apply Elem_triv.\n      assert (n1 <> n) by auto.\n      pose proof (Elem_tail _ _ _ H1 H2).\n      apply Elem_cons.\n      apply Elem_cons.\n      exact H3.\n      destruct (Nat.eq_dec n n1).\n      rewrite e.\n      apply Elem_triv.\n      assert (n1 <> n) by auto.\n      pose proof (Elem_tail _ _ _ H1 H2).\n      apply Elem_cons.\n      apply Elem_cons.\n      exact H3.\n      destruct (n <? n0) eqn:E3.\n      apply Elem_triv.\n      apply Elem_cons. apply Elem_triv.\nQed.\n\nTheorem min_spec_min: forall (l:List) (n:nat) (E : Elem n l),\n  let E1 := elem_not_nil l n E in min_elem1 l E1 <= n.\nProof.\n  intro l.\n  destruct l.\n  - intros.\n    compute in E.\n    inversion E.\n  - intros. induction l.\n    + compute.\n      destruct (n0 =? n) eqn:Eqn.\n      * lia.\n      * apply beq_nat_false in Eqn.\n        pose proof (Elem_tail _ _ _ E Eqn) as H.\n        inversion H.\n    + unfold min_elem1.\n      subst E1.\n      simpl.\n      destruct (n0 =? n1) eqn:Eqn.\n      * apply beq_nat_true in Eqn.\n        destruct (min_elem l).\n        -- destruct (n1 <? n2) eqn:Eqn1,\n                    (n  <? n1) eqn:Eqn2,\n                    (n  <? n2) eqn:Eqn3.\n           lia. lia. lia. lia. lia. lia. lia. lia.\n        -- destruct (n <? n1) eqn:Eqn2.\n           lia. lia.\n      * rewrite elem_spec in E.\n        simpl in E.\n        rewrite Eqn in E.\n        apply beq_nat_false in Eqn.\n        assert ((if n0 =? n then true else elem n0 l) = elem n0 (cons n l)) by auto.\n        rewrite H in E.\n        rewrite <- elem_spec in E.\n        clear H. pose proof (IHl E) as IHL. clear IHl.\n        unfold min_elem1 in IHL.\n        simpl in IHL.\n        destruct (min_elem l).\n        -- destruct (n1 <? n2) eqn:Eqn1,\n                    (n  <? n1) eqn:Eqn2,\n                    (n  <? n2) eqn:Eqn3;\n           lia.\n        -- destruct (n <? n1) eqn:Eqn2;\n           lia.\nQed.\n\n\nTheorem Min1_spec :\n  forall l n (E: Elem n l),\n  let D := elem_not_nil l n E in\n  Elem (min_elem1 l D) l\n  /\\ min_elem1 l D <= n.\nProof.\n intros.\n split.\n apply min_spec_elem.\n apply min_spec_min.\nQed.\n\nFixpoint min_def n l: nat:= match l with\n                            | nil => n\n                            | cons m l' => let min' := min_def n l' in if min' <? m then min' else m\n                          end.\n\nFixpoint remove_once n l: List := match l with\n                                    | nil => nil\n                                    | cons m l' => if n =? m then l' else cons m (remove_once n l')\n                                  end.\n\nFixpoint emplace n l: List := match l with\n  | nil => cons n nil\n  | cons m l' => if m <? n then cons m (emplace n l') else cons n l\nend.\n\nDefinition insert_sort l: List := (fix ins o i := match i with\n      | nil => o\n      | cons m l' => ins (emplace m o) l'\nend) nil l.\n\nEval vm_compute in insert_sort (cons 4 (cons 6 (cons 1 (cons 3 (cons 2 nil))))).\nEval vm_compute in insert_sort (cons 5 (cons 4 (cons 3 (cons 2 (cons 1 nil))))).\nEval vm_compute in insert_sort (cons 5 (cons 4 (cons 5 (cons 8 (cons 5 (cons 3 nil)))))).\n\n\nTheorem Sorted_le: forall a b l, Sorted (cons a (cons b l)) -> a <= b.\n  intros.\n  inversion H.\n  exact first_pair_sorted.\nQed.\n\nTheorem Sorted_tail: forall n l, Sorted (cons n l) -> Sorted l.\n  intros.\n  inversion H.\n  - apply Sorted_empty.\n  - exact  rest_sorted.\nQed.\n\nTheorem Sorted_under: forall a b l, Sorted (cons a (cons b l)) -> Sorted (cons a l).\n  intros.\n  destruct l.\n  apply Sorted_one.\n  inversion H.\n  inversion rest_sorted.\n  apply Sorted_recursive.\n  lia.\n  exact rest_sorted0.\nQed.\n\n\nLtac miniinv0 H := try pose proof (Sorted_tail _ _ H) as ?H;\n                   try pose proof (Sorted_le _ _ _ H) as ?Le;\n                   try pose proof (Sorted_under _ _ _ H) as ?U.\n\nLtac miniinv H := miniinv0 H.\n\nTheorem Sorted_under2: forall a b c l, Sorted (cons a (cons b (cons c l))) -> Sorted (cons a (cons b l)).\n  intros.\n  miniinv H.\n  apply Sorted_recursive.\n  lia.\n  miniinv H0.\n  assumption.\nQed.\n\nTheorem Sorted_min: forall n l, Sorted (cons n l) -> n <= min_def n l.\n  intros.\n  induction l.\n  - simpl.\n    lia.\n  - miniinv H.\n    miniinv U.\n    simpl.\n    pose proof (IHl U) as IH.\n    destruct (min_def n l <? n0).\n    exact IH.\n    lia.\nQed.\n\nLtac miniinv2 H := try pose proof (Sorted_tail _ _ H) as ?H;\n                   try pose proof (Sorted_min _ _ H) as ?Min;\n                   try pose proof (Sorted_le _ _ _ H) as ?Le;\n                   try pose proof (Sorted_under _ _ _ H) as ?U;\n                   try pose proof (Sorted_under2 _ _ _ _ H) as ?dU.\n\nLtac miniinv H ::= miniinv2 H.\n\nFixpoint append (a b : List) : List := match a with\n                              | nil => b\n                              | cons h t => cons h (append t b)\n                              end.\n\nTheorem Sorted_append1 : forall a b, Sorted (append a b) -> Sorted a.\nProof.\n  intros.\n  destruct a.\n  constructor.\n  simpl in *.\n  generalize dependent n.\n  induction a; intros.\n  constructor.\n  simpl in *.\n  miniinv H.\n  constructor.\n  exact Le.\n  pose proof (IHa n H0) as IH.\n  exact IH.\nQed.\n\nTheorem Sorted_under_n: forall a m b, Sorted (append a (cons m b)) -> Sorted (append a b).\nProof.\n  intros.\n  generalize dependent b.\n  induction a; intros.\n  - simpl in H |- *.\n    miniinv H.\n    exact H0.\n  - simpl in *.\n    miniinv H.\n    pose proof (IHa b H0) as IH.\n\n\n\n\n\n\nTheorem emplace_spec: forall n l, Sorted l -> Sorted (emplace n l).\nProof.\n  intros.\n  destruct l.\n    simpl. exact (Sorted_one _).\n  simpl.\n  destruct (n0 <? n) eqn:E.\n  conv_ord.\n  induction l.\n  - simpl.\n    apply Sorted_recursive;\n    [lia | apply Sorted_one].\n  - simpl.\n    destruct (n1 <? n) eqn: E1.\n    all: conv_ord.\n    apply Sorted_recursive.\n    miniinv H.\n    lia.\n    miniinv H.\n    miniinv H0.\n    pose proof (IHl U).\n    miniinv H2.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/zav.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7301583634303613}}
{"text": "Require Export Tactics.\n\nCheck (3 = 3).\nCheck forall n m : nat, n + m = m + n.\n\nCheck forall n : nat, n = 2.\nCheck 3 = 5.\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity. Qed.\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_injective: injective S.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\n\nCheck @eq.\n\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma and_intro: forall A B: Prop,\n    A -> B -> (A /\\ B).\nProof.\n  intros.\n  split.\n  - apply H.\n  - apply H0.\nQed.\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros.\n  split.\n  - destruct n as [| n'].\n    + reflexivity.\n    + inversion H.\n  - destruct m as [| m'].\n    + reflexivity.\n    + rewrite -> plus_comm in H.\n      inversion H.\nQed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros.\n  destruct H as [Hn Hm].\n  rewrite -> Hn.\n  rewrite -> Hm.\n  reflexivity.\nQed.\n\nLemma proj1: forall P Q: Prop,\n    P /\\ Q -> P.\nProof.\n  intros.\n  destruct H as [L R].\n  apply L.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros.\n  assert (J: n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct J as [L R].\n  rewrite -> L.\n  rewrite -> R.\n  reflexivity.\nQed.\n\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros.\n  destruct H as [L R].\n  apply R.\nQed.\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros.\n  destruct H as [L R].\n  split.\n  - apply R.\n  - apply L.\nQed.\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros.\n  destruct H as [Hl [Hm Hr]].\n  split.\n  - split.\n    + apply Hl.\n    + apply Hm.\n  - apply Hr.\nQed.\n\nCheck and.\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros.\n  destruct H as [Hl | Hr].\n  - rewrite -> Hl.\n    reflexivity.\n  - rewrite -> Hr.\n    rewrite -> mult_O_r.\n    reflexivity.\nQed.\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros.\n  left.\n  apply H.\nQed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros.\n  destruct n as [| n'].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros.\n  destruct n as [| n'].\n  - left. reflexivity.\n  - destruct m as [| m'].\n    + right. reflexivity.\n    + inversion H.\nQed.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\n  intros.\n  destruct H as [Hl | Hr].\n  - right. apply Hl.\n  - left. apply Hr.\nQed.\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nEnd MyNot.\n\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros.\n  destruct H.\nQed.\n\nFact not_implies_our_not : forall (P:Prop),\n  ~P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros.\n  destruct H.\n  apply H0.\nQed.\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros H. inversion H.\nQed.\n\nCheck (0 <> 1).\n\nTheorem zero_not_one': 0 <> 1.\nProof.\n  intros H. inversion H.\nQed.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not.\n  intros.\n  destruct H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  intros.\n  unfold not in H.\n  destruct H as [Hr Hl].\n  destruct Hl.\n  apply Hr.\nQed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  intros.\n  unfold not.\n  intros.\n  apply H0.\n  apply H.\nQed.\n\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros.\n  unfold not.\n  unfold not in H0.\n  intros.\n  apply H0 in H. \n  apply H.\n  apply H1.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros.\n  unfold not.\n  intros.\n  destruct H as [Hl Hr].\n  apply Hr in Hl.\n  apply Hl.\nQed.\n\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros.\n  destruct b.\n  - unfold not in H.\n    exfalso.\n    apply H.\n    reflexivity.\n  - reflexivity.\nQed.\n\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros.\n  destruct H as [Hl Hr].\n  split.\n  - apply Hr.\n  - apply Hl.\nQed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  intros.\n  split.\n  - apply not_true_is_false.\n  - intros.\n    rewrite -> H.\n    unfold not.\n    intros.\n    inversion H0.\nQed.\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros.\n  split.\n  - intros. apply H.\n  - intros. apply H.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros.\n  destruct H as [Hpq Hqp].\n  destruct H0 as [Hqr Hrq].\n  split.\n  - intros.\n    apply Hqr.\n    apply Hpq.\n    apply H.\n  - intros.\n    apply Hqp.\n    apply Hrq.\n    apply H.\nQed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros.\n  split.\n  - intros.\n    split.\n    + destruct H.\n      * left. apply H.\n      * destruct H.\n        right.\n        apply H.\n    + destruct H.\n      * left. apply H.\n      * destruct H.\n        right.\n        apply H0.\n  - intros.\n    destruct H.\n    destruct H.\n    + left. apply H.\n    + destruct H0.\n      * left.\n        apply H0.\n      * right.\n        split.\n          apply H.\n          apply H0.\nQed.\n\nRequire Import Coq.Setoids.Setoid.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  intros.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros.\n  split.\n  - intros.\n    destruct H.\n    + left. left. apply H.\n    + destruct H.\n      * left. right. apply H.\n      * right. apply H.\n  - intros.\n    destruct H.\n    + destruct H.\n      * left. apply H.\n      * right. left. apply H.\n    + right. right. apply H.\nQed.\n\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros.\n  rewrite -> mult_0.\n  rewrite -> mult_0.\n  rewrite -> or_assoc.\n  reflexivity.\nQed.\n\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros.\n  apply mult_0.\n  apply H.\nQed.\n\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2. reflexivity.\nQed.\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros.\n  destruct H as [m Hm].\n  exists (2 + m).\n  apply Hm.\nQed.\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros.\n  unfold not.\n  intros.\n  destruct H0.\n  apply H0.\n  apply H.\nQed.\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  intros.\n  split.\n  - intros.\n    destruct H as [x Hx].\n    destruct Hx.\n    + left. exists x. apply H.\n    + right. exists x. apply H.\n  - intros.\n    destruct H.\n    + destruct H as [x Hx].\n      exists x.\n      left.\n      apply Hx.\n    + destruct H as [x Hx].\n      exists x.\n      right.\n      apply Hx.\nQed.\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | h :: t => x = h \\/ In x t\n  end.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  simpl.\n  right. right. right. left.\n  reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros.\n  destruct H as [H' | [H' | []]].\n  - exists 1.\n    rewrite -> H'.\n    reflexivity.\n  - exists 2.\n    rewrite -> H'.\n    reflexivity.\nQed.\n\nLemma 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.\n  generalize dependent H.\n  induction l as [| h t IH].\n  - intros.\n    simpl in H.\n    destruct H.\n  - intros.\n    simpl in H.\n    destruct H as [Hl | Hr].\n    + rewrite -> Hl.\n      simpl.\n      left.\n      reflexivity.\n    + simpl.\n      right.\n      apply IH.\n      apply Hr.\nQed.\n\nLemma 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.\n  split.\n  - induction l as [| h t IH].\n    + intros. simpl in H. destruct H.\n    + intros.\n      simpl.\n      destruct H.\n      * exists h.\n        split.\n          rewrite -> H. reflexivity.\n          left. reflexivity.\n      * apply IH in H.\n        destruct H.\n          exists x.\n          destruct H.\n          split.\n            apply H.\n            right. apply H0.\n  - induction l as [| h t IH].\n    + intros.\n      simpl.\n      destruct H.\n      destruct H.\n      destruct H0.\n    + simpl.\n      intros.\n      destruct H.\n      destruct H.\n      destruct H0.\n      * rewrite -> H0 in H.\n        left.\n        rewrite -> H.\n        reflexivity.\n      * simpl.\n        right.\n        apply IH.\n        exists x.\n        split.\n          apply H.\n          apply H0.\nQed.\n\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros.\n  split.\n  - induction l as [| h t IH].\n    + simpl. intros. right. apply H.\n    + simpl. intros.\n      apply or_assoc.\n      destruct H.\n      * left. apply H.\n      * right. apply IH. apply H.\n  - induction l as [| h t IH].\n    + simpl. intros. destruct H.\n        destruct H.\n        apply H.\n    + simpl. intros. destruct H. destruct H.\n        left. apply H.\n        right. apply IH. left. apply H.\n        right. apply IH. right. apply H.\nQed.\n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n  | [] => True\n  | h :: t => P h /\\ All P t\n  end.\n\nLemma 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.\n  split.\n  - induction l as [| h t IH].\n    + simpl. intros. reflexivity.\n    + simpl. intros.\n      split.\n      * apply H. left. reflexivity.\n      * apply IH. intros.\n        apply H. right. apply H0.\n  - induction l as [| h t IH].\n    + simpl. intros. destruct H0.\n    + simpl. intros.\n      destruct H.\n      destruct H0.\n      * rewrite -> H0. apply H.\n      * apply IH.\n          apply H1.\n          apply H0.\nQed.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun (x:nat) => if oddb x then Podd x\n                           else Peven x.\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).\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    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\nCheck plus_comm.\n\nLemma plus_comm3 :\n  forall n m p, n + (m + p) = (p + m) + n.\nProof.\n  intros.\n  rewrite -> plus_comm.\n  rewrite -> (plus_comm m).\n  reflexivity.\nQed.\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros.\n  rewrite (In_map_iff _ _ _ _ _) in H.\n  destruct H.\n  apply proj1 in H.\n  rewrite -> mult_O_r in H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\n\nExample function_equality_ex1 : plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\nAxiom functional_extensionality : forall {X Y: Type} {f g: X -> Y},\n    (forall (x: X), f x = g x) -> f = g.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality.\n  intros.\n  apply plus_comm.\nQed.\n\nPrint Assumptions function_equality_ex2.\n\nFixpoint rev_append {X} (l1 l2: list X) : list X :=\n  match l1 with\n  | [] => l2\n  | h :: t => rev_append t (h :: l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\n\nLemma rev_append_correct :\n  forall (X: Type) (l1 l2: list X),\n  rev_append l1 l2 = rev l1 ++ l2.\nProof.\n  intros.\n  generalize dependent l2.\n  induction l1 as [| h1 t1 IH1].\n  - intros.\n    reflexivity.\n  - intros. \n    simpl.\n    rewrite -> IH1.\n    rewrite <- app_assoc.\n    simpl.\n    reflexivity.\nQed.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros.\n  apply functional_extensionality.\n  intros.\n  unfold tr_rev.\n  rewrite -> rev_append_correct.\n  apply app_nil_r.\nQed.\n\n\nTheorem evenb_double : forall k, evenb (double k) = true.\nProof.\n  intros.\n  induction k as [| k' IH].\n  - reflexivity. \n  - simpl. apply IH.\nQed.\n\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' IH].\n  - exists 0. reflexivity.\n  - rewrite -> evenb_S.\n    destruct (evenb n').\n    + simpl.\n      destruct IH.\n      exists x. rewrite -> H. reflexivity.\n    + simpl.\n      destruct IH.\n      exists (S x). rewrite -> H.\n      reflexivity.\nQed.\n\nTheorem even_bool_prop : forall n,\n  evenb n = true <-> exists k, n = double k.\nProof.\n  intros.\n  split.\n  - intros.\n    destruct (evenb_double_conv n).\n    rewrite -> H in H0.\n    exists x.\n    apply H0.\n  - intros.\n    destruct H.\n    rewrite -> H.\n    apply evenb_double.\nQed.\n\nTheorem beq_nat_true_iff : forall n1 n2 : nat,\n  beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  intros.\n  split.\n  - intros.\n    apply beq_nat_true in H.\n    apply H.\n  - intros.\n    rewrite -> H.\n    rewrite <- beq_nat_refl.\n    reflexivity.\nQed.\n\nLemma andb_true_l: forall (a: bool),\n  true && a = a.\nProof.\n  intros.\n  destruct a.\n  - reflexivity.\n  - reflexivity.\nQed.\n  \nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros.\n  split.\n  - intros.\n    split.\n    + destruct b2.\n      * rewrite -> andb_true_r in H.\n        apply H.\n      * destruct b1.\n          reflexivity.\n          destruct H. reflexivity.\n    + destruct b1.\n      * rewrite -> andb_true_l in H.\n        apply H.\n      * inversion H.\n   - intros.\n     destruct H.\n     rewrite -> H.\n     rewrite -> H0.\n     reflexivity.\nQed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros.\n  split.\n  - intros.\n    destruct b1.\n    + left. reflexivity.\n    + destruct b2.\n      * right. reflexivity.\n      * simpl in H. inversion H.\n  - intros.\n    destruct H.\n    + rewrite -> H. reflexivity.\n    + rewrite -> H.\n      destruct b1.\n      * reflexivity.\n      * reflexivity.\nQed.\n\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  intros.\n  split.\n  - unfold not.\n    intros.\n    rewrite -> H0 in H.\n    rewrite <- beq_nat_refl in H.\n    inversion H.\n  - unfold not.\n    intros.\n    destruct (beq_nat x y) eqn:beqnatxy.\n    + exfalso. apply H. apply beq_nat_true_iff in beqnatxy.\n      apply beqnatxy.\n    + reflexivity.\nQed.\n\nFixpoint beq_list {A : Type} (beq : A -> A -> bool)\n                  (l1 l2 : list A) : bool :=\n  match l1 with\n  | [] => match l2 with\n          | [] => true\n          | _  => false\n          end\n  | h1 :: t1 => match l2 with\n                | [] => false\n                | h2 :: t2 => (beq h1 h2) && (beq_list beq t1 t2)\n                end\n  end.\n\nLemma beq_list_true_iff :\n  forall A (beq : A -> A -> bool),\n    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n  intros.\n  split.\n  - intros.\n    generalize dependent l2.\n    induction l1 as [| h1 t1 IH1].\n    + intros. \n      destruct l2 as [| h2 t2].\n      * reflexivity.\n      * inversion H0.\n    + intros.\n      destruct l2 as [| h2 t2].\n      * inversion H0.\n      * simpl in H0.\n        apply andb_true_iff in H0.\n        destruct H0.\n        apply H in H0.\n        apply IH1 in H1.\n        rewrite -> H0.\n        rewrite -> H1.\n        reflexivity.\n  - intros.\n    generalize dependent l2.\n    induction l1 as [| h t IH].\n    + intros.\n      rewrite <- H0.\n      reflexivity.\n    + intros.\n      rewrite <- H0.\n      simpl.\n      apply andb_true_iff.\n      split.\n      * apply H.\n        reflexivity.\n      * apply IH.\n        reflexivity.\nQed.\n\nLemma forallb_test_elements:\n  forall X test (h: X) (t: list X),\n    forallb test (h :: t) = true ->\n    ((test h = true) /\\ (forallb test t = true)).\nProof.\n  intros.\n  inversion H.\n  apply andb_true_iff in H1.\n  destruct H1.\n  rewrite -> H0.\n  rewrite -> H1.\n  split.\n  - reflexivity.\n  - reflexivity.\nQed.\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.\n  split.\n  - induction l as [| h t IH].\n    + reflexivity.\n    + intros.\n      simpl.\n      apply forallb_test_elements in H.\n      destruct H.\n      split.    \n      * apply H.\n      * apply IH.\n        apply H0.\n  - induction l as [| h t IH].\n    + reflexivity.\n    + intros.\n      simpl.\n      destruct H.\n      rewrite -> H.\n      rewrite -> andb_true_l.\n      apply IH.\n      apply H0.\nQed.\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros.\n  destruct b.\n  - left. apply H. reflexivity.\n  - right.\n    rewrite -> H. \n    unfold not.\n    intros.\n    inversion H0.\nQed.\n\n\nTheorem restricted_excluded_middle_eq : forall(n m : nat),\n  n = m \\/ n <> m.\nProof.\n  intros.\n  apply (restricted_excluded_middle (n = m) (beq_nat n m)).\n  symmetry.\n  apply beq_nat_true_iff.\nQed.\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  unfold not.\n  intros.\n  apply H.\n  right.\n  intros.\n  apply H.\n  left.\n  apply H0.\nQed.\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  unfold excluded_middle.\n  intros.\n  assert (P x \\/ ~ P x).\n  - apply H.\n  - destruct H1.\n    + apply H1.\n    + exfalso.\n      apply H0.\n      exists x.\n      apply H1.\nQed.\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\n\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\n\nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n", "meta": {"author": "atungare", "repo": "coq-software-foundations", "sha": "49bf005d87f530a54274ce9de06b6bce99c1e8aa", "save_path": "github-repos/coq/atungare-coq-software-foundations", "path": "github-repos/coq/atungare-coq-software-foundations/coq-software-foundations-49bf005d87f530a54274ce9de06b6bce99c1e8aa/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.730158362966234}}
{"text": "Require Import List Arith BinNat.\nImport ListNotations.\n\nInductive digit : Set :=\n| Digit : forall n, n < 10 -> digit.\n\nDefinition denoteDigit (d : digit) : nat :=\n  match d with Digit n _ => n end.\n\nFixpoint denoteDigitList_helper (dl : list digit) (acc : nat) :=\n  match dl with\n  | [] => acc\n  | a :: dl => denoteDigitList_helper dl ((acc * 10) + (denoteDigit a))\n  end.\n\n(* using explicit recursion over fold_left because I can't figure out how re-\"fold\" the induction for induction proofs *)\nDefinition denoteDigitList dl := denoteDigitList_helper dl 0.\n\nDefinition D0 : digit.\n  refine (Digit 0 _).\n  auto with arith.\nDefined.\n\nDefinition D1 : digit.\n  refine (Digit 1 _).\n  auto with arith.\nDefined.\n\nDefinition D2 : digit.\n  refine (Digit 2 _).\n  auto with arith.\nDefined.\n\nDefinition D3 : digit.\n  refine (Digit 3 _).\n  auto with arith.\nDefined.\n\nDefinition D4 : digit.\n  refine (Digit 4 _).\n  auto with arith.\nDefined.\n\nDefinition D5 : digit.\n  refine (Digit 5 _).\n  auto with arith.\nDefined.\n\nDefinition D6 : digit.\n  refine (Digit 6 _).\n  auto with arith.\nDefined.\n\nDefinition D7 : digit.\n  refine (Digit 7 _).\n  auto with arith.\nDefined.\n\nDefinition D8 : digit.\n  refine (Digit 8 _).\n  auto with arith.\nDefined.\n\nDefinition D9 : digit.\n  refine (Digit 9 _).\n  auto with arith.\nDefined.\n\nCompute (denoteDigitList [D3 ; D4 ; D7]).\n\nDefinition toDigit (n : nat | n < 10) : digit.\n  inversion n.\n  intros.\n  exact (Digit x H).\nDefined.\n\nLemma all_nat_gte_zero : forall m, m >= 0.\n  intros.\n  induction m.\n  auto.\n  auto with arith.\nQed.\n\nLemma denoteDigit_is_lt_10 : forall (d : digit), denoteDigit d < 10.\nProof.\n  intro d; unfold denoteDigit; elim d.\n  intros; assumption.\nQed.\n\nLemma denoteDigit_is_le_9 : forall (d : digit), denoteDigit d <= 9.\nProof.\n  intro d.\n  assert (denoteDigit d < 10). apply denoteDigit_is_lt_10.\n  apply lt_n_Sm_le; assumption.\nQed.\n\nRequire Import Omega.\n\nInductive remainder := R0 | R1.\n\nDefinition denotePair p :=\n  match p with\n  | (R0, d) => (denoteDigit d)\n  | (R1, d) => 10 + (denoteDigit d)\n  end.\n\nDefinition addDigit (d1 : digit) (d2 : digit) : (remainder * digit).\n  pose (m := denoteDigit d1).\n  pose (n := denoteDigit d2).\n  destruct (lt_dec (m + n) 10) as [ TotalLt10 | TotalGt10 ].\n  exact (R0, Digit (m + n) TotalLt10).\n\n  assert (m <= 9). apply denoteDigit_is_le_9.\n  assert (n <= 9). apply denoteDigit_is_le_9.\n  assert (m + n <= 18) as SumMinus20.\n  replace 18 with (9 + 9).\n  apply plus_le_compat; [ assumption | assumption].\n  auto with arith.\n  cut (forall a b c, b <= a -> a <= b + c -> a - b <= c).\n  intros Cut.\n  replace 18 with (9 + 9) in SumMinus20.\n  apply Cut in SumMinus20.\n  Search (_ <= _ -> _ < _).\n  apply le_lt_n_Sm in SumMinus20.\n  assert (m + n - 10 < 10) as mPlusNLe10. omega.\n  exact (R1, Digit (m + n - 10) mPlusNLe10).\n  apply not_lt in TotalGt10; unfold ge in TotalGt10; omega.\n  ring.\n  intros; omega.\nDefined.\n\nCompute (denotePair (addDigit D3 D4)).\nCompute (denotePair (addDigit D8 D6)).\n\nTheorem addDigit_works_as_expected :\n  forall d1 d2 : digit,\n          (denoteDigit d1) + (denoteDigit d2) = (denotePair (addDigit d1 d2)).\nProof.\n  intros.\n  unfold denotePair, denoteDigit, addDigit.\n  destruct (lt_dec (denoteDigit d1 + denoteDigit d2) 10) as [d1_plus_d2_lt_10 | d1_plus_d2_gte_10].\n  - auto with arith.\n  - apply not_lt in d1_plus_d2_gte_10.\n    fold (denoteDigit d1); fold (denoteDigit d2).\n    auto with arith.\nQed.\n\nTheorem addDigit_assoc_r : forall (d1 d2 d3 : digit),\n    (denoteDigit d1) + (denotePair (addDigit d2 d3)) = (denotePair (addDigit d1 d2)) + denoteDigit d3.\nProof.\n  intros.\n  rewrite <- addDigit_works_as_expected.\n  rewrite <- addDigit_works_as_expected.\n  rewrite Nat.add_assoc.\n  reflexivity.\nQed.\n\nDefinition addDigitsWithRemainder (d1 d2 : digit) (r : remainder) : (remainder * digit).\n  destruct (addDigit d1 d2) as (r', subtotal).\n  case r.\n  exact (r', subtotal).\n  remember (denoteDigit subtotal) as n.\n  destruct (lt_dec (denoteDigit subtotal) 9) as [ SubtotalLt9 | SubtotalEq9 ].\n  apply lt_n_S in SubtotalLt9.\n  rewrite <- Heqn in SubtotalLt9.\n  exact (r', Digit (S n) SubtotalLt9).\n  (* this is the situation where d1 + d2 = 9 with one as r, so final answer is 10.\n     this means r' = zero by necessity. will need to show this in the theorem *)\n  exact (R1, D0).\nDefined.\n\n(*Compute (addDigitsWithRemainder D3 D8 R0).*)\nCompute (addDigitsWithRemainder D3 D8 R1).\nCompute (addDigitsWithRemainder D2 D8 R1).\nCompute (addDigitsWithRemainder D1 D8 R1).\n\nDefinition denoteRemainder r :=\n  match r with\n  | R0 => 0\n  | R1 => 1\n  end.\n\nLemma denotePair_S : forall r d H, denotePair (r, Digit (S (denoteDigit d)) H) = denotePair (r, d) + 1.\nProof.\n  intros r d H.\n  unfold denotePair, denoteDigit; destruct d; rewrite Nat.add_1_r.\n  destruct r; reflexivity.\nQed.\n\nLemma addDigit_bounded : forall d1 d2, denotePair (addDigit d1 d2) <= 18.\n  intros d1 d2.\n  rewrite <- addDigit_works_as_expected.\n  remember (denoteDigit_is_le_9 d1).\n  remember (denoteDigit_is_le_9 d2).\n  omega.\nQed.\n\nLemma addDigit_R0 : forall d d1 d2, addDigit d1 d2 = (R0, d) -> denoteDigit d1 + denoteDigit d2 = denoteDigit d.\n  intros d d1 d2 def_of_d.\n  remember (denotePair (addDigit d1 d2)) as n.\n  rewrite <- addDigit_works_as_expected in Heqn.\n  unfold addDigit in def_of_d.\n  destruct (lt_dec (denoteDigit d1 + denoteDigit d2) 10).\n  inversion def_of_d.\n  unfold denoteDigit.\n  auto with arith.\n  inversion def_of_d.\nQed.\n\nTheorem addDigitsWithRemainder_works: forall d1 d2 r, denotePair (addDigitsWithRemainder d1 d2 r) = denoteDigit d1 + denoteDigit d2 + denoteRemainder r.\nProof.\n  intros d1 d2 r.\n  unfold addDigitsWithRemainder.\n  remember (addDigit d1 d2) as p.\n  destruct p as (r', subtotal).\n  destruct r.\n  rewrite Heqp, <- addDigit_works_as_expected.\n  unfold denoteRemainder; auto with arith.\n  destruct (lt_dec (denoteDigit subtotal) 9).\n  rewrite denotePair_S.\n  rewrite Heqp, <- addDigit_works_as_expected.\n  unfold denoteRemainder; auto with arith.\n  (* must argue that subtotal = 9.  this is because ~(subtotal < 9), so obviously subtotal = 9 *)\n  assert (denoteDigit subtotal = 9) as SubtotalEq9.\n  remember (denoteDigit_is_lt_10 subtotal); omega.\n  induction r'.\n  symmetry in Heqp. apply addDigit_R0 in Heqp.\n  rewrite Heqp, SubtotalEq9. compute; auto with arith.\n  (* must argue that R1 is impossible because since subtotal = 9, so d1 + d2 can't be 19 *)\n  remember (addDigit_bounded d1 d2) as l.\n  destruct Heql.\n  rewrite <- Heqp in l.\n  unfold denotePair in l.\n  rewrite SubtotalEq9 in l.\n  omega.\nQed.\n\nLemma plus_reg_r : forall (a b c : nat), a + b = c + b <-> a = c.\nProof.\n  intros.\n  induction b.\n  rewrite Nat.add_0_r, Nat.add_0_r; reflexivity.\n  rewrite <- plus_n_Sm, <- plus_n_Sm.\n  split.\n  intros HSab_eq_Scb.\n  apply eq_add_S, IHb in HSab_eq_Scb; assumption.\n  intros.\n  apply eq_S, IHb; assumption.\nQed.\n\nFixpoint denoteDigitList_backwards (dl : list digit) : nat :=\n  match dl with\n  | [] => 0\n  | x :: dl => (denoteDigit x) + (10 * denoteDigitList_backwards dl)\n  end.\n\nFixpoint addDigitList_helper (dl1 dl2 : list digit) (rem : digit) :=\n  match (dl1, dl2) with\n  | ([], []) => [rem]\n  | ([], _) => addDigitList_helper_remainder dl2 rem\n  | (_, []) => addDigitList_helper_remainder dl1 rem\n  | (d1 :: tl1, d2 :: tl2) =>\n    let (rem', total) := addDigitsWithRemainder d1 d2 rem in\n    total :: (addDigitList_helper tl1 tl2 rem')\n  end.\n\nLemma list_cons_app : forall (A : Type) (a : A) (l : (list A)), a :: l = [a] ++ l.\nProof.\n  intros; simpl; reflexivity.\nQed.\n\nLemma denoteDigitList_backwards_single : forall d, denoteDigitList_backwards [d] = denoteDigit d.\nProof.\n  intros.\n  unfold denoteDigitList_backwards.\n  rewrite <- mult_n_O, <- plus_n_O; reflexivity.\nQed.\n\nLemma denoteDigitList_backwards_empty : denoteDigitList_backwards [] = 0.\nProof.\n  intros.\n  unfold denoteDigitList_backwards; reflexivity.\nQed.\n\nLemma addDigitList_helper_works :\n  forall dl1 dl2 rem,\n    denoteDigitList_backwards (addDigitList_helper dl1 dl2 rem) = denoteDigit rem + denoteDigitList_backwards dl1 + denoteDigitList_backwards dl2.\nProof.\n  induction dl1.\n  induction dl2.\n  intros.\n  unfold addDigitList_helper.\n  rewrite denoteDigitList_backwards_single.\n  rewrite denoteDigitList_backwards_empty.\n  ring.\n\n  intros.\n  unfold addDigitList_helper.\n  rewrite addDigitList_helper_remainder_works.\n  rewrite denoteDigitList_backwards_empty.\n  ring.\n\n  intros.\n  destruct dl2.\n  unfold addDigitList_helper at 1.\n  rewrite addDigitList_helper_remainder_works.\n  rewrite denoteDigitList_backwards_empty.\n  ring.\n\n  unfold addDigitList_helper.\n  remember (addThreeDigits a d rem) as p.\n  destruct p as (rem', total).\n  fold addDigitList_helper.\n  unfold denoteDigitList_backwards at 1.\n  fold denoteDigitList_backwards.\n  rewrite IHdl1.\n  unfold denoteDigitList_backwards at 3.\n  unfold denoteDigitList_backwards at 3.\n  fold denoteDigitList_backwards.\n  fold denoteDigitList_backwards.\n  (* playing with the terms so they end up with the right terms on LHS/RHS\n     annoying, feels like this should be easier *)\n  replace (denoteDigit total +\n           10 * (denoteDigit rem' +\n                 denoteDigitList_backwards dl1 +\n                 denoteDigitList_backwards dl2))\n    with (denoteDigit total +\n          10 * denoteDigit rem' +\n          10 * denoteDigitList_backwards dl1 +\n          10 * denoteDigitList_backwards dl2).\n  replace (denoteDigit rem +\n           (denoteDigit a + 10 * denoteDigitList_backwards dl1) +\n           (denoteDigit d + 10 * denoteDigitList_backwards dl2))\n    with (denoteDigit rem +\n          denoteDigit a +\n          denoteDigit d +\n          10 * denoteDigitList_backwards dl1 +\n          10 * denoteDigitList_backwards dl2).\n  rewrite plus_reg_r, plus_reg_r.\n  rewrite plus_comm.\n  fold (denotePair (rem', total)).\n  rewrite Heqp, addThreeDigits_works; ring.\n  ring.\n  ring.\nQed.\n\nDefinition addDigitList (dl1 : list digit) (dl2 : list digit) :=\n  rev (addDigitList_helper (rev dl1) (rev dl2) D0).\n\nLemma length_always_gte_0 : forall (A : Type) (l : list A), length l >= 0.\nProof.\n  intros.\n  induction l.\n  unfold length.\n  auto.\n  rewrite list_cons_app.\n  rewrite app_length.\n  unfold length at 1.\n  auto.\nQed.\n\nLemma denoteDigitList_backwards_app : forall dl1 dl2,\n    denoteDigitList_backwards (dl1 ++ dl2) = 10 ^ (length dl1) * denoteDigitList_backwards dl2 + denoteDigitList_backwards dl1.\nProof.\n  induction dl1.\n  intros.\n  rewrite app_nil_l.\n  symmetry.\n  unfold length.\n  rewrite Nat.pow_0_r.\n  unfold denoteDigitList_backwards at 2.\n  ring.\n\n  intros.\n  rewrite <- app_comm_cons.\n  unfold denoteDigitList_backwards at 1.\n  fold denoteDigitList_backwards.\n  rewrite IHdl1, Nat.mul_add_distr_l, Nat.mul_assoc, <- Nat.pow_succ_r.\n  (* need to drop the denoteDigitList_backwards dl2 term from both sides *)\n  replace (10 ^ S (length dl1)) with (10 ^ (length (a :: dl1))).\n  rewrite plus_comm, <- plus_assoc, Nat.add_cancel_l.\n  symmetry.\n  unfold denoteDigitList_backwards.\n  fold denoteDigitList_backwards.\n  ring.\n  auto with arith.\n  apply length_always_gte_0.\nQed.\n\nLemma denoteDigitList_backwards_rev_cons : forall dl a, denoteDigitList_backwards (rev (a :: dl)) = 10 ^ (length dl) * (denoteDigit a) + denoteDigitList_backwards (rev dl).\nProof.\n  induction dl.\n  intro a0; simpl; ring.\n  intro a0.\n  rewrite list_cons_app, rev_app_distr.\n  unfold rev at 2.\n  rewrite app_nil_l, denoteDigitList_backwards_app, IHdl, rev_length, Nat.add_cancel_r.\n  unfold denoteDigitList_backwards.\n  ring.\nQed.\n\nLemma denoteDigitList_helper_cons : forall dl a acc, denoteDigitList_helper (a :: dl) acc = denoteDigitList_helper dl (10 * acc + denoteDigit a).\nProof.\n  intros.\n  unfold denoteDigitList_helper at 1.\n  fold denoteDigitList_helper.\n  rewrite mult_comm.\n  reflexivity.\nQed.\n\nLemma denoteDigitList_helper_split : forall dl m n, denoteDigitList_helper dl (m + n) = denoteDigitList_helper dl m + n * 10 ^ (length dl).\nProof.\n  induction dl.\n  intros; unfold denoteDigitList_helper; simpl; ring.\n  intros m n.\n  rewrite denoteDigitList_helper_cons, Nat.mul_add_distr_l.\n  rewrite <- plus_assoc, IHdl, Nat.mul_add_distr_r.\n  replace (n * 10 ^ length (a :: dl)) with (10 * n * 10 ^ length dl).\n  rewrite plus_comm.\n  symmetry.\n  rewrite plus_comm, <- plus_assoc, Nat.add_cancel_l, denoteDigitList_helper_cons.\n  symmetry.\n  rewrite IHdl.\n  ring.\n  (* previous form was more convenient to show correctness, now we rewrite\n     again *)\n  replace (10 * n * 10 ^ length dl)\n    with ((10 * 10 ^ length dl) * n) ; [auto | ring].\n  rewrite <- Nat.pow_succ_r ; [auto | apply length_always_gte_0].\n  replace (length (a :: dl)) with (S (length dl)); [ring | auto].\nQed.\n\nLemma denoteDigitList_helper_cons_unwrap : forall dl a acc, denoteDigitList_helper (a :: dl) acc = 10 ^ length dl * denoteDigit a + denoteDigitList_helper dl (acc * 10).\nProof.\n  induction dl.\n  intros a acc.\n  rewrite denoteDigitList_helper_cons.\n  unfold denoteDigitList_helper.\n  symmetry.\n  unfold length; rewrite Nat.pow_0_r; ring.\n\n  intros a0 acc.\n  (* don't want to unfold both a0 :: a so we use a temp variable *)\n  remember (a :: dl) as dl'.\n  rewrite denoteDigitList_helper_cons, Heqdl', denoteDigitList_helper_split, plus_comm.\n  replace (10 * acc) with (acc * 10); [rewrite Nat.add_cancel_r ; ring | ring].\nQed.\n\nLemma denoteDigitList_unwrap : forall dl a, denoteDigitList (a :: dl) = 10 ^ length dl * denoteDigit a + denoteDigitList dl.\nProof.\n  induction dl.\n  intros.\n  unfold denoteDigitList, denoteDigitList_helper; simpl; ring.\n\n  intros.\n  unfold denoteDigitList.\n  rewrite denoteDigitList_helper_cons_unwrap, Nat.add_cancel_l.\n  simpl; reflexivity.\nQed.\n\nLemma denoteDigitList_backwards_rev : forall dl, denoteDigitList_backwards (rev dl) = denoteDigitList dl.\nProof.\n  induction dl.\n  intros; compute; reflexivity.\n\n  rewrite denoteDigitList_backwards_rev_cons.\n  rewrite IHdl.\n  symmetry.\n  rewrite denoteDigitList_unwrap; reflexivity.\nQed.\n\nLemma denoteDigitList_app : forall dl1 dl2, denoteDigitList (dl1 ++ dl2) = 10 ^ (length dl2) * denoteDigitList dl1 + denoteDigitList dl2.\nProof.\n  induction dl1.\n  intros.\n  rewrite app_nil_l.\n  symmetry.\n  unfold denoteDigitList at 1.\n  unfold denoteDigitList_helper.\n  ring.\n\n  intros.\n  rewrite <- app_comm_cons.\n  unfold denoteDigitList.\n  rewrite denoteDigitList_helper_cons_unwrap.\n  symmetry.\n  rewrite denoteDigitList_helper_cons_unwrap.\n  simpl.\n  fold (denoteDigitList dl1).\n  fold (denoteDigitList dl2).\n  fold (denoteDigitList (dl1 ++ dl2)).\n  rewrite Nat.mul_add_distr_l.\n  rewrite Nat.mul_assoc.\n\n  replace (10 ^ length dl2 * 10 ^ length dl1) with (10 ^ length (dl1 ++ dl2)).\n  rewrite <- Nat.add_assoc.\n  rewrite Nat.add_cancel_l.\n  symmetry.\n  rewrite IHdl1.\n  reflexivity.\n\n  (* proof of replacement *)\n  rewrite <- Nat.pow_add_r, plus_comm.\n  rewrite app_length.\n  reflexivity.\nQed.\n\nLemma denoteDigitList_rev : forall dl, denoteDigitList (rev dl) = denoteDigitList_backwards dl.\nProof.\n  induction dl.\n  compute.\n  reflexivity.\n\n  rewrite list_cons_app, rev_app_distr.\n  unfold rev at 2.\n  rewrite app_nil_l, denoteDigitList_app.\n  unfold length, denoteDigitList at 2, denoteDigitList_helper.\n  rewrite Nat.mul_0_l, Nat.pow_1_r, Nat.add_0_l.\n  rewrite denoteDigitList_backwards_app.\n  unfold length.\n  rewrite Nat.pow_1_r.\n  rewrite <- IHdl.\n  rewrite Nat.add_cancel_l.\n  unfold denoteDigitList_backwards.\n  ring.\nQed.\n\nTheorem addDigitList_works :\n  forall dl1 dl2, denoteDigitList dl1 + denoteDigitList dl2 = denoteDigitList (addDigitList dl1 dl2).\nProof.\n  intros.\n  unfold addDigitList.\n  symmetry.\n  rewrite denoteDigitList_rev, addDigitList_helper_works, denoteDigitList_backwards_rev, denoteDigitList_backwards_rev, Nat.add_cancel_r.\n  unfold denoteDigit.\n  simpl.\n  reflexivity.\nQed.\n\nLemma mod_is_lt : forall (m n : nat), n > 0 -> (m mod n) < n.\n  intros.\n  apply (Nat.mod_bound_pos m n (all_nat_gte_zero m)).\n  exact H.\nQed.\n\nLemma TenGt0 : 10 > 0.\nProof.\n  auto with arith.\nQed.\n\n(* https://stackoverflow.com/questions/33302526/well-founded-recursion-in-coq *)\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\nFixpoint convertToDigitList_helper (n i : nat) : (list digit) :=\n  match i with\n  | 0 => []\n  | (S p) =>\n    let a := n mod 10 in\n    let m := n / 10 in\n    let d := Digit a (mod_is_lt n 10 TenGt0) in\n    if eq_nat_dec m 0 then\n      [d]\n    else\n      (convertToDigitList_helper m p) ++ [d]\n  end.\n\nDefinition convertToDigitList (n : nat) : (list digit) :=\n  convertToDigitList_helper n n.\n\nCompute (convertToDigitList 123).\n\nLemma div_zero_implies_small : (forall a b, b <> 0 -> a / b = 0 -> a < b).\nProof.\n  intros a b b_neq_0 a_div_b_eq_0.\n  apply (Nat.div_str_pos_iff a b) in b_neq_0.\n  omega.\nQed.\n\n\nLemma div_nonzero_implies_not_small : (forall a b, b <> 0 -> a / b <> 0 -> b <= a).\n  intros a b b_neq_0.\n  apply (Nat.div_str_pos_iff a b) in b_neq_0.\n  intros a_b_neq_0.\n  omega.\nQed.\n\nLemma denoteDigitList_trivial : forall d : digit, denoteDigitList [d] = denoteDigit d.\nProof.\n  intro d.\n  unfold denoteDigitList.\n  unfold denoteDigitList_helper.\n  ring.\nQed.\n\nRequire Import Arith Wf.\n\nLemma convertToDigitList_helper_works :\n  forall m i, m <= i -> denoteDigitList (convertToDigitList_helper m i) = m.\nProof.\n  induction m as [ m IHn ] using (well_founded_induction lt_wf).\n  intros i m_bounded.\n  unfold convertToDigitList_helper.\n  destruct i.\n  compute; omega.\n\n  fold convertToDigitList_helper.\n  destruct (Nat.eq_dec (m / 10) 0) as [m_div_10_eq_0 | m_div_10_neq_0].\n  apply div_zero_implies_small in m_div_10_eq_0 ; [auto | auto].\n  apply Nat.mod_small in m_div_10_eq_0; auto.\n  cut (m / 10 < m).\n  intros m_lt_10_lt_m.\n  Search (denoteDigitList (_ ++ _)).\n  rewrite denoteDigitList_app.\n  rewrite IHn.\n  unfold length.\n  rewrite denoteDigitList_trivial.\n  unfold denoteDigit.\n  rewrite Nat.pow_1_r.\n  symmetry.\n  apply Nat.div_mod; [auto].\n  omega.\n  omega.\n  apply Nat.div_lt; [auto|auto with arith].\n  apply div_nonzero_implies_not_small; [auto | auto].\n  rewrite Nat.div_1_r.\n  unfold not.\n  intros Hm_0.\n  rewrite Hm_0 in m_div_10_neq_0.\n  auto.\nQed.\n\nTheorem convertToDigitList_works : forall n : nat, denoteDigitList (convertToDigitList n) = n.\nProof.\n  intros n.\n  unfold convertToDigitList.\n  apply convertToDigitList_helper_works ; auto.\nQed.\n\nCompute (convertToDigitList 123).\n\nTheorem grade_school_addition_correct: forall m n, denoteDigitList (addDigitList (convertToDigitList m) (convertToDigitList n)) = m + n.\nProof.\n  intros m n.\n  rewrite <- addDigitList_works.\n  repeat rewrite convertToDigitList_works.\n  reflexivity.\nQed.\n\nRecursive Extraction addDigitList convertToDigitList.\n\n  (* Multiplication *)\n\n(* 123 * 456 = (100 + 20 + 3) * (400 + 50 + 6) *)\n(* 100 * 400 + 100 * 50 + 100 * 6 + 20 * 400 + 20 * 50 + 20 * 6 + 3 * 400 + 3 * 50 + 3 * 6 *)\n\nFixpoint multiplyDigit (d1 : digit) (d2 : digit) : (digit * digit).\n  pose (m := denoteDigit d1).\n  pose (n := denoteDigit d2).\n  destruct (lt_dec (m * n) 10) as [ TotalLt10 | TotalGt10 ].\n  exact (D0, Digit (m * n) TotalLt10).\n\n  (* Must prove that multiplying two digits gives a remainder / modulus both < 10 *)\n  assert (m * n <= 81) as MultBounded.\n  Search (_ <= _ -> _ < _).\n  assert (m <= 9). apply denoteDigit_is_le_9.\n  assert (n <= 9). apply denoteDigit_is_le_9.\n  apply (mult_le_compat _ _ _ _ H H0).\n\n  pose (a := (m * n) / 10).\n  pose (b := (m * n) mod 10).\n\n  assert (b < 10) as ModLt10. apply mod_is_lt. auto with arith.\n  assert (a < 10) as RemainderLt10.\n  Search (_ <= _ -> _ / _ <= _).\n  apply (Nat.div_le_mono (m * n) 81 10) in MultBounded.\n  assert (81 / 10 = 8). auto with arith.\n  rewrite H in MultBounded.\n  apply le_lt_n_Sm in MultBounded.\n  apply Nat.lt_lt_succ_r in MultBounded.\n  exact MultBounded.\n  auto with arith.\n  exact (Digit a RemainderLt10, Digit b ModLt10).\nDefined.\n\nFixpoint multiplyDigitList_backwards_helper (dl : list digit) (d : digit) : list digit :=\n  match dl with\n  | [] => []\n  | d' :: dl =>\n    let (rem, d0) := (multiplyDigit d d') in\n    let dl' := (multiplyDigitList_backwards_helper dl d) in\n    d0 :: (addDigitList_helper dl' [rem] D0)\n  end.\n", "meta": {"author": "tildedave", "repo": "coq-playground", "sha": "860f5e68b6c0caed8a038f128ee298b504607c85", "save_path": "github-repos/coq/tildedave-coq-playground", "path": "github-repos/coq/tildedave-coq-playground/coq-playground-860f5e68b6c0caed8a038f128ee298b504607c85/digits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652496, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7299463066688631}}
{"text": "Require Import Bool Arith.\n\nInductive bintree :=\n| Leaf : nat -> bintree\n| Node : nat -> bintree -> bintree -> bintree.\n\nInductive is_post_order : bintree -> nat -> nat -> Prop :=\n| po_leaf k : is_post_order (Leaf k) k (S k)\n| po_node t1 t2 k l m :\n    is_post_order t1 k l -> is_post_order t2 l m ->\n    is_post_order (Node m t1 t2) k (S m).\n\nCoercion Leaf : nat >-> bintree.\nNotation \"[ x ; y ,  z ] \" :=  (Node x y z).\n\nDefinition task :=\n  forall i j k l m n : nat,\n    is_post_order [i; [j; k, l], m] 0 n <->\n    k = 0 /\\ l = 1 /\\ j = 2 /\\ m = 3 /\\ i = 4 /\\ n = 5.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/044/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286373, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.729903855382511}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus (Succ lf1) (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj242_coqofml_6CZfCu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7298975229375114}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  mult x lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj249_coqofml_3i242F.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7298945582383852}}
{"text": "Require Export Lists.\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nCheck nil.\n\nCheck cons.\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(* d (b a 5)\n   d mumble (b a 5)\n   d bool (b a 5) *)\n\nEnd MumbleGrumble.\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\nCheck repeat'.\n\nCheck repeat.\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0 => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\nInductive list' {X:Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\nFixpoint app {X : Type} (l1 l2 : list X) : (list X) :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X : Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nFail Definition mynil := nil.\n\nDefinition mynil : list nat := nil.\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\nDefinition list123''' := [1; 2; 3].\n\nTheorem app_nil_r : forall(X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X l. induction l as [|l' n IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A l m n. induction l as [|l' a IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl'.\n    reflexivity.\nQed.\n\nLemma app_length : forall(X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2. induction l1 as [|l1' n IHl1'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl1'.\n    reflexivity.\nQed.\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2. induction l1 as [|l1' n IHl1'].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1'.\n    rewrite -> app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros X l. induction l as [|l n IHl'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr.\n    rewrite -> IHl'. simpl. reflexivity.\nQed.\n\nInductive prod (X Y : Type) : Type :=\n| pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\nend.\n\nDefinition snd {X Y : Type} (p: X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\nFixpoint split {X Y : Type} (l : list (X * Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([],[])\n  | ([x;y],[tx;ty]) :: m => ([x :: tx], [y :: ty]) ++ (split m)\n  end.\n\n\n\n\n\n\n\n\n", "meta": {"author": "binaks", "repo": "funtp", "sha": "b196c7da3aecea3ff6afcc5902560dbc0afb5bad", "save_path": "github-repos/coq/binaks-funtp", "path": "github-repos/coq/binaks-funtp/funtp-b196c7da3aecea3ff6afcc5902560dbc0afb5bad/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.8670357649558007, "lm_q1q2_score": 0.7298929543462404}}
{"text": "(* This file another solution Ex 8.9 used by Coq.Arith.Even in Coq'Art. *)\n\nOpen Scope nat_scope.\n(* In Coq'Art's solution, following even definition is used. *)\n(* But, in this solution, this definition is not used. *)\n(* Inductive even : nat -> Prop := *)\n(* | O_even : even 0 *)\n(* | SS_even : forall n:nat, even n -> even (S (S n)). *)\n\n(* Hint Resolve O_even SS_even. *)\n\nRequire Import Coq.Arith.Even.\n\nHint Resolve even_O even_S.\nHint Resolve odd_S even_S.\n\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n    | O => 0\n    | S p => S (S (mult2 p))\n  end.\n\nTheorem even_mult2 :\n  forall n:nat, even (mult2 n).\nProof.\n  induction n.\n  simpl.\n  auto.\n  simpl.\n  auto.\nQed.\n\nTheorem sum_even :\n  forall n p:nat, even n -> even p -> even (n+p).\nProof.\n  intros n p H0 H1.\n  apply even_even_plus.\n  trivial.\n  auto.\nQed.\n\nHint Resolve sum_even.\n\nTheorem square_even :\n  forall n:nat, even n -> even (n*n).\nProof.\n  intros.\n  apply even_mult_l.\n  trivial.\nQed.\n", "meta": {"author": "cosmo0920", "repo": "CoqPractice", "sha": "f7eab87534324ee2dc60429232ef0cbfab62d614", "save_path": "github-repos/coq/cosmo0920-CoqPractice", "path": "github-repos/coq/cosmo0920-CoqPractice/CoqPractice-f7eab87534324ee2dc60429232ef0cbfab62d614/even_num.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7298929489110164}}
{"text": "\nSection Minimal_propositional_logic.\n Variables P Q R T : Prop.\n\n\n Theorem imp_trans : (P->Q)->(Q->R)->P->R.\n Proof.\n  intros H H' p.\n  apply H'.\n  apply H.\n  assumption.\n Qed.\n\n \n Theorem imp_trans' : (P->Q)->(Q->R)->P->R.\n Proof.\n  intros H H' p; apply H'; apply H; assumption.\n Qed.\n\n Theorem imp_trans'' : (P->Q)->(Q->R)->P->R.\n Proof.\n  auto. \n Qed.\n\n Theorem delta : (P->P->Q)->P->Q.\n Proof (fun (H:P->P->Q)(p:P) => H p p).\n\n Lemma apply_example : (Q->R->T)->(P->Q)->P->R->T.\n Proof.\n  intros H H0 p.\n  apply H.\n  exact (H0 p).\n Qed.\n\n Theorem imp_dist : (P->Q->R)->(P->Q)->(P->R).\n Proof.\n  intros H H' p.\n  apply H.  \n  - assumption.\n  - apply H'; assumption.\n Qed.\n\n Theorem K : P->Q->P.\n Proof.\n  intros p q;  assumption.\n Qed.\n\n\n \n Section proof_of_triple_impl.\n  Hypothesis H : ((P->Q)->Q)-> Q.\n  Hypothesis p : P.\n\n  Remark  R1 : (P->Q)->Q.\n  Proof fun H0:P->Q => H0 p.\n\n  Theorem triple_impl : Q.\n  Proof H R1.\n\n End proof_of_triple_impl.\n\n\n Theorem triple_impl_one_liner : (((P->Q)->Q)->Q)->P->Q.\n Proof.\n  intros H p; apply H; intro H0; apply H0; assumption.\n Qed.\n\n Lemma imp_dist' : (P->Q->R)->(P->Q)->(P->R).\n Proof.\n  intros H H' p.\n  apply H;[assumption | apply H'; assumption].\n Qed.\n\n Section section_assert_example.\n  Hypotheses (H : P->Q)\n             (H0 : Q->R)\n             (H1 : (P->R)->T->Q)\n             (H2 : (P->R)->T).\n \n  Lemma cut_example : Q.\n  Proof.\n    cut (P -> R).\n    intro H3.\n    apply H1; [ assumption | apply H2; assumption].\n    intro Hp; apply H0; apply H; assumption.\n  Qed.\n\n  (* 3.5 *)\n  Lemma cut_exercise : Q.\n  Proof.\n    apply H1; [intro Hp; apply H0; apply H; assumption |\n               apply H2; intro Hp; apply H0; apply H; assumption].\n  Qed.\n\n  Print cut_example.\n  Print cut_exercise.\n\n\n End section_assert_example.\n\n Lemma triple_impl2 : (((P->Q)->Q)->Q)->P->Q.\n Proof.\n  auto.\n Qed.\n\nEnd Minimal_propositional_logic.\n\nPrint imp_dist.\n\nSection using_imp_dist.\n Variables (P1 P2 P3 : Prop).\n\n Check imp_dist P1 P2 P3.\n\n Check imp_dist (P1->P2) (P2->P3) (P3->P1).\n\nEnd using_imp_dist.\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/chap3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7298929449219449}}
{"text": "(*\n * Coq code for \"Using XCAP to Certify Realistic System Code: Machine Context Management\"\n *\n * Math lemma library\n *\n * (for Coq version 8.0pl2)\n *)\n\nRequire Import Div2.\nRequire Import EqNat.\nRequire Import Lt.\nRequire Import Le.\nRequire Import ZArith.\n\nFixpoint bgt_nat (n m : nat) {struct n} : bool :=\n  match n, m with\n  | O, O => false\n  | O, S _ => false\n  | S _, O => true\n  | S n1, S m1 => bgt_nat n1 m1\n  end.\n\nFixpoint blt_nat (n m : nat) {struct n} : bool :=\n  match n, m with\n  | O, O => false\n  | O, S _ => true\n  | S _, O => false\n  | S n1, S m1 => blt_nat n1 m1\n  end.\n\nFixpoint ble_nat (n m : nat) {struct n} : bool :=\n  match n, m with\n  | O, O => true\n  | O, S _ => true\n  | S _, O => false\n  | S n1, S m1 => ble_nat n1 m1\n  end.\n\nLemma ble_le_true : forall a b : nat, a <= b -> ble_nat a b = true.\nintro.\ninduction  a as [| a Hreca].\n intros.\n   simpl in |- *.\n   destruct b as [| n].\n  auto.\n  auto.\n intros.\n   destruct H.\n  simpl in |- *.\n    apply Hreca.\n    auto.\n  simpl in |- *.\n    apply Hreca.\n    auto.\n    apply le_Sn_le.\n    auto.\nQed.\n\nLemma ble_gt_false : forall a b : nat, a > b -> ble_nat a b = false.\nunfold gt in |- *.\nsimple induction a.\n intros.\n   inversion H.\n intros.\n   destruct b as [| n0].\n  auto.\n  simpl in |- *.\n    apply H.\n    auto.\n    apply lt_S_n.\n    auto.\nQed.\n\nLemma blt_S_false : forall a : nat, blt_nat (S a) a = false.\nProof.\nsimple induction a.\nunfold blt_nat in |- *.\nauto.\nintros.\nunfold blt_nat in |- *.\nauto.\nQed.\n\nLemma blt_S_eq :\n forall (a b : nat) (t : bool), blt_nat a b = t -> blt_nat (S a) (S b) = t.\nProof.\nintros.\nunfold blt_nat in |- *.\nfold blt_nat in |- *.\nauto.\nQed.\n\nLemma blt_lt_true : forall a b : nat, a < b -> blt_nat a b = true.\nProof.\nsimple induction a.\nintros.\ninversion H.\nunfold blt_nat in |- *.\nauto.\nunfold blt_nat in |- *.\nauto.\nintros.\ninversion H0.\napply blt_S_eq.\napply H.\napply lt_n_Sn.\napply blt_S_eq.\napply H.\nrewrite <- H2 in H0.\napply lt_S_n.\nauto.\nQed.\n\nLemma blt_Sm_false :\n forall a b : nat, blt_nat a b = false -> blt_nat (S a) b = false.\nProof.\nsimple induction a.\nsimple induction b.\nintros.\nunfold blt_nat in |- *.\nauto.\nintros.\nunfold blt_nat in H0.\nabsurd (true = false).\ndiscriminate.\nauto.\nsimple induction b.\nintros.\nunfold blt_nat in |- *.\nauto.\nintros.\nintros.\nunfold blt_nat in H1.\nfold blt_nat in H1.\ncut (blt_nat (S n) n0 = false).\nintros.\napply blt_S_eq.\nauto.\napply (H n0).\nauto.\nQed.\n\nLemma blt_false : forall a b : nat, a < b -> blt_nat b a = false.\nProof.\nintros.\ninduction  H as [| m H HrecH].\napply blt_S_false.\napply blt_Sm_false.\nauto.\nQed.\n\nLemma blt_eq_false : forall a : nat, blt_nat a a = false.\nProof.\nsimple induction a.\nunfold blt_nat in |- *.\nauto.\nintros.\nunfold blt_nat in |- *.\nauto.\nQed.\n\nLemma beq_eq_true : forall a b : nat, a = b -> true = beq_nat a b.\nsimple induction a.\n simple induction b.\n  auto.\n  intros.\n    inversion H0.\n simple induction b.\n  intros.\n    inversion H0.\n  intros.\n    simpl in |- *.\n    auto.\nQed.\n\nLemma beq_neq_false : forall a b : nat, a <> b -> false = beq_nat a b.\nProof.\nsimple induction a.\nsimple induction b.\nintros.\nabsurd (0 <> 0).\nauto.\nauto.\nintros.\nunfold beq_nat in |- *.\nauto.\nintros.\nunfold beq_nat in |- *.\nauto.\ninduction  b as [| b Hrecb].\nauto.\nunfold beq_nat in |- *.\nfold beq_nat in |- *.\nunfold beq_nat in |- *.\nauto.\nQed.\n\n\nLemma eq_neq_Sl : forall a b : nat, a = b -> S a <> b.\nProof.\nsimple induction a.\nsimple induction b.\nintros.\nauto.\nintros.\nabsurd (0 = S n).\ndiscriminate.\nauto.\nsimple induction b.\nintros.\nabsurd (S n = 0).\ndiscriminate.\nauto.\nintros.\napply not_eq_S.\nauto.\nQed.\n\nTheorem eqorneq_nat : forall a a' : nat, a = a' \\/ a <> a'.\nProof.\nintros.\ncompare a a'.\nauto.\nauto.\nQed.\n\n\nTheorem le_or_gt : forall m n : nat, n <= m \\/ n > m.\nProof.\ndouble induction m n.\nleft.\nauto.\nintros.\nright.\nred in |- *.\nred in |- *.\napply le_n_S.\napply le_O_n.\nintros.\nleft.\napply le_O_n.\nintros.\ncut (n <= n1 \\/ n > n1).\nintros.\ninversion_clear H1.\nleft.\napply le_n_S.\nauto.\nright.\nunfold gt in |- *.\nunfold gt in H2.\napply lt_n_S.\nauto.\napply H0.\nQed.\n\nLemma lt_neq : forall m n : nat, n < m -> n <> m.\nProof.\nsimple induction m.\nintros.\ninversion H.\nintros.\ninduction  n0 as [| n0 Hrecn0].\nauto.\ncut (n0 < n).\nintros.\ncut (n0 <> n).\nintros.\nauto.\napply H.\nauto.\napply lt_S_n.\nauto.\nQed.\n\nLemma lt_S_neq : forall n x : nat, n < S x -> x <> n -> n < x.\nProof.\ndouble induction n x.\nintros.\nabsurd (0 <> 0).\nauto.\nauto.\nintros.\napply lt_O_Sn.\nintros.\nunfold lt in H0.\ncut (S n0 <= 0).\nintros.\nabsurd (S n0 <= 0).\napply le_Sn_O.\nauto.\napply le_S_n.\nauto.\nintros.\napply lt_n_S.\ncut (n1 = n0 \\/ n1 <> n0).\nintros.\ninversion_clear H3.\nabsurd (S n1 <> S n1).\nauto.\nrewrite <- H4 in H2.\nauto.\ncut (n1 < S n0).\nintros.\napply (H0 n0 H3).\nauto.\napply lt_S_n.\nauto.\napply eqorneq_nat.\nQed.\n\nLemma lt_S_eq_or_lt : forall n x : nat, n < S x -> x = n \\/ n < x.\nProof.\nintros.\ncut (x = n \\/ x <> n).\nintros.\ninversion_clear H0.\nleft;\nauto.\nright;\napply lt_S_neq.\nauto.\nauto.\napply eqorneq_nat.\nQed.\n\nLemma plus_n_O_n : forall n : nat, n + 0 = n.\nProof.\nsimple induction n.\nunfold plus in |- *.\nauto.\nintros.\nunfold plus in |- *.\nfold plus in |- *.\nrewrite H.\nauto.\nQed.\n\nLemma plus_S_neq : forall n m : nat, n <> n + S m.\nProof.\nsimple induction n.\nintros.\nunfold plus in |- *.\nauto.\nintros.\nunfold plus in |- *.\nfold plus in |- *.\nauto.\nQed.\n\nLemma Psucc_eq : forall a b, Psucc a = Psucc b -> a = b.\ninduction a; induction b; simpl; auto; intros; try (inversion H; fail).\ninversion H; rewrite IHa with b; auto.\ninduction a; inversion H.\ninversion H; auto.\ninduction b; inversion H.\nQed.\n\nLemma Z_eq_nat_eq : forall a b, Z_of_nat a = Z_of_nat b -> a = b.\ninduction a; induction b; auto; intros.\ninversion H. inversion H.\nrewrite (IHa b); auto.\nsimpl in H. inversion H.\nclear IHa IHb.\ngeneralize a b H1. clear a b H H1.\ninduction a; induction b; simpl; auto; intros.\ngeneralize (P_of_succ_nat b) H1; clear H1 IHb; induction p; simpl; intro; inversion H1.\ngeneralize (P_of_succ_nat a) H1; clear H1 IHa; induction p; simpl; intro; inversion H1.\nrewrite (Psucc_eq _ _ H1); auto.\nQed.\n\nLemma Zeq_bool_true_eq : forall a b, true = Zeq_bool a b -> a = b.\nintros a b; unfold Zeq_bool; generalize (Zcompare_Eq_eq a b); destruct (a?=b)%Z;\nauto; intros; inversion H0.\nQed.\n\nLemma Zeq_bool_neq_false : forall a b, a <> b -> false = Zeq_bool a b.\nintros a b; unfold Zeq_bool; generalize (Zcompare_Eq_eq a b); destruct (a?=b)%Z;\nauto.\nQed.\n\nLemma Zeq_bool_eq_true : forall a b, a = b -> true = Zeq_bool a b.\nintros. rewrite H. clear a H. destruct b; auto; induction p; auto.\nQed.\n", "meta": {"author": "mithrao", "repo": "Coq-assembly-verification", "sha": "c3ab9fea02cc7f94331888604231923069a01334", "save_path": "github-repos/coq/mithrao-Coq-assembly-verification", "path": "github-repos/coq/mithrao-Coq-assembly-verification/Coq-assembly-verification-c3ab9fea02cc7f94331888604231923069a01334/final-mctx/mathlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7298929403092955}}
{"text": "Require Export D.\n\n\n\n(** **** Problem  : 4 stars (plus_swap) *)\n(** Use [assert] to help prove this theorem if necessary.  \n    You shouldn't need to use induction. *)\n\nTheorem plus_swap : forall n m p : nat, \n  n + (m + p) = m + (n + p).\nProof.  \n  Lemma plus_assoc : forall a b c:nat, a + (b + c) = (a + b) + c.\n  Proof.\n    intros. induction a. reflexivity. simpl. rewrite -> IHa. reflexivity. Qed.\n    intros. rewrite -> plus_assoc. symmetry. rewrite -> plus_assoc.  assert (H : m + n = n + m).\n    induction n. simpl. induction m. reflexivity. simpl. rewrite -> IHm. reflexivity. simpl. rewrite <- IHn.\n    Lemma plus_mSn_Smn : forall n m : nat, m + S n = S (m + n). \n      intros. induction m. reflexivity. simpl. rewrite -> IHm. reflexivity. \n    Qed.\n    apply plus_mSn_Smn.\n    rewrite -> H. reflexivity.\n    \n    Qed.\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/02/P06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7298636048393796}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult x (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj206_coqofml_ZrpIIg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7298592948019645}}
{"text": "Require Import NormTypes.NormalizedTypes.\nRequire Import NormTypes.irreleventQuantifiers.\nRequire Import NPeano Omega.\n\nModule Mod3_byHand.\n  Definition mod3 (n:nat) := (Nat.modulo n 3).\n\n  (* Notation \"'class' nf a\" := (isig_intro _ (nf a) (iex_intro _ a eq_refl)) (at level 100). *)\n  Check (class mod3 3).\n  Check (class mod3 0).\n\n  Notation \"'[[' x ']N/3N]'\" := (class mod3 x) (at level 200).\n  Notation \"'N/3N'\" := (Norm mod3) (at level 200).\n  Check [[3]N/3N].\n  Check [[0]N/3N].\n\n\n  Lemma eq_3_0: [[3]N/3N] = [[0]N/3N].\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma eq_3_x: forall x , [[x]N/3N] = [[3+x]N/3N].\n  Proof.\n    intros x. \n    apply eqS_eq.\n    simpl.\n    unfold class.\n    unfold eqS, liftR.\n    simpl.\n    replace (S (S (S x))) with (x+1*3);try omega.\n    unfold mod3.\n    rewrite (Nat.mod_add x 1 3);auto.\n  Qed.\n\n  Lemma eq_3_mult_x: forall x , [[0]N/3N] = [[3*x]N/3N].\n  Proof.\n    intros x.\n    apply eqS_eq.\n    simpl.\n    unfold class.\n    unfold eqS, liftR.\n    simpl.\n    replace (x + (x + (x + 0))) with (0+x*3);try omega.\n    unfold mod3.\n\n    rewrite (Nat.mod_add 0 x 3);auto.\n  Qed.\n\n  Definition add1:= @lift _ _ mod3 _ (fun x:nat => [[ x +1 ]N/3N]).\n  Eval compute in (add1 ([[3]N/3N])).\n\n  Notation \"[[ x ]]\" := (isig_intro _ x _) (only printing, at level 200).\n  Eval compute in (add1 ([[3]N/3N])).\n  Eval compute in (add1 ([[4]N/3N])).\n\n  Definition add:=\n    @lift _ _ mod3 _ (fun n:nat =>\n                            @lift _ _ mod3 _ (fun x:nat => [[ x + n ]N/3N])).\n\n  Eval compute in (add ([[2]N/3N]) ([[2]N/3N])).\n\n  (* Definition toint (x:N/3N):nat := extract _ x. *)\n  (* Definition fromint (x:nat):N/3N := class _ x. *)\n\nEnd Mod3_byHand.\n\n\nModule Mod3_usingLibMod.\n\n  Definition mod3 (n:nat) := (Nat.modulo n 3).\n  Definition NMod3 := Norm mod3.\n\n  Check (class mod3 3).\n  Check (class mod3 0).\n\n  Notation \"'[[' x ']Z/3Z]'\" := (class mod3 x) (at level 200).\n  Notation \"A == B\" := (@eqS _ _ mod3 A B) (at level 200).\n  Check [[3]Z/3Z].\n  Check [[0]Z/3Z].\n\n\n  Lemma eq_3_0: [[3]Z/3Z] = [[0]Z/3Z].\n  Proof.\n    reflexivity.\n  Qed.\n\n\n  Lemma eq_3_x: forall x , [[x]Z/3Z] = [[3+x]Z/3Z].\n  Proof.\n    intros x.\n    apply eqS_eq.\n    simpl.\n    unfold class.\n    unfold eqS, liftR.\n    simpl.\n    replace (S (S (S x))) with (x+1*3);try omega.\n    unfold mod3.\n    rewrite (Nat.mod_add x 1 3);auto.\n  Qed.\n\nEnd Mod3_usingLibMod.\n\n(* Example: Z/3Z. *)\nRequire Import ZArith.\n\nModule Mod3Z.\n\n  Open Scope Z_scope.\n\n  Definition mod3Z (z:Z) := (Z.modulo z 3%Z).\n  Definition NMod3Z := Norm mod3Z.\n\n  Check (class mod3Z 3).\n  Check (class mod3Z 0).\n\n  Notation \"'[[' x ']Z/3Z]'\" := (class mod3Z x) (at level 200).\n  Check [[3]Z/3Z].\n  Check [[0]Z/3Z].\n\n\n  Lemma eq_3_0Z: [[3]Z/3Z] = [[0]Z/3Z].\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma eq_3_x: forall x , [[x]Z/3Z] = [[3+x]Z/3Z].\n  Proof.\n    intros x.\n    apply eqS_eq.\n    lazy beta delta -[Z.add Z.modulo] iota.\n    replace (3+x) with (x+1*3);try omega.\n    rewrite (Z.mod_add x 1 3);auto.\n    omega.\n  Qed.\nEnd Mod3Z.\n\n", "meta": {"author": "Matafou", "repo": "normalizedTypes", "sha": "bfa93499327c0cc377f986a5003495bd2671d8a1", "save_path": "github-repos/coq/Matafou-normalizedTypes", "path": "github-repos/coq/Matafou-normalizedTypes/normalizedTypes-bfa93499327c0cc377f986a5003495bd2671d8a1/src/NormTypes/tests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7298148530137886}}
{"text": "Theorem t1 (P Q R : Prop) : (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  intros H1 H2 H. apply H2, H1, H.\nQed.\n\nPrint t1.\n(* t1 = fun (P Q R : Prop)\n   (H1 : P -> Q) (H2 : Q -> R) (H : P) => H2 (H1 H)\n   : forall P Q R : Prop, (P -> Q) -> (Q -> R) -> P -> R *)\n\nTheorem t2 (P Q R : Prop) : (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n  exact (fun f g p => g (f p)).\nQed.\n\nPrint t2.\n(* t2 = fun (P Q R : Prop)\n   (f : P -> Q) (g : Q -> R) (p : P) => g (f p)\n   : forall P Q R : Prop, (P -> Q) -> (Q -> R) -> P -> R *)\n\nDefinition ex_middle := forall P : Prop, P \\/ ~P.\nDefinition pierce_law := forall P Q : Prop, ((P -> Q) -> P) -> P.\nDefinition pierce_law' := forall P : Prop, ((P -> False) -> P) -> P.\n\nTheorem ex_middle_impl_pierce_law : ex_middle -> pierce_law'.\nProof.\n  unfold ex_middle, pierce_law'. intros E P H.\n  pose (E P) as Hp. destruct Hp as [Hp | Hnp]; try assumption.\n  apply H. intro Hp. contradiction.\nQed.\n\nTheorem pierce : pierce_law <-> pierce_law'.\nProof.\n  unfold pierce_law, pierce_law'.\n  split; intro L.\n  - intro P. apply (L P False).\n  - intros P Q H. apply L. intro Hnp.\n    apply H. intro Hp.\n    contradiction. (* apply Hnp in Hp. destruct Hp. *)\nQed.\n\nPrint pierce.\n(* pierce = conj\n   (fun (L : forall P Q : Prop, ((P -> Q) -> P) -> P) (P : Prop) => L P False)\n   (fun (L : forall P : Prop, ((P -> False) -> P) -> P)\n     (P Q : Prop) (H : (P -> Q) -> P) =>\n       L P (fun Hnp : P -> False => H (fun Hp : P => False_ind Q (Hnp Hp))))\n     : pierce_law <-> pierce_law' *)\n\nTheorem pierce' : pierce_law' -> pierce_law.\nProof.\n  unfold pierce_law, pierce_law'. intro L.\n  intros P Q H. apply L. intro Hnp.\n  apply H. intro Hp.\n  apply Hnp in Hp. destruct Hp.\nQed.\n\nPrint pierce'.\n(* pierce' =\n   fun (L : forall P : Prop, ((P -> False) -> P) -> P)\n     (P Q : Prop) (H : (P -> Q) -> P) =>\n       L P (fun Hnp : P -> False =>\n         H (fun Hp : P => let Hp0 : False := Hnp Hp\n           in match Hp0 return Q with end))\n   : pierce_law' -> pierce_law *)\n\nSection Minimal_propositional_logic.\n  Variables P Q R T : Prop.\n\n  Theorem imp_trans : (P -> Q) -> (Q -> R) -> (P -> R).\n  Proof using. intros H H' p. apply H', H, p. Qed.\n\n  Print imp_trans.\n  (* imp_trans = [fun (f g p) => g (f p)]\n     fun (H : P -> Q) (H' : Q -> R) (p : P) => H' (H p)\n     : forall P Q R : Prop, (P -> Q) -> (Q -> R) -> P -> R *)\n\n  Theorem imp_trans' : (P -> Q) -> (Q -> R) -> (P -> R).\n  Proof using. auto. Qed.\n\n  Check Q. (* Q : Prop *)\n  Check (P -> Q) -> (Q -> R) -> (P -> R).\n  (*    (P -> Q) -> (Q -> R) -> P -> R : Prop *)\n\n\n  Section example_of_assumption.\n    Hypothesis H : P -> Q -> R.\n    Lemma L1 : P -> Q -> R.\n    Proof using H. assumption. Qed.\n  End example_of_assumption.\n\n  Theorem delta : (P -> P -> Q) -> P -> Q.\n  Proof using. exact (fun f p => f p p). Qed.\n\n  Theorem apply_example: (Q -> R -> T) -> (P -> Q) -> P -> R -> T.\n  Proof using.\n    intros H H0 p. apply H, H0, p.\n  Qed.\n\n  Theorem imp_dist : (P -> Q -> R) -> (P -> Q) -> P -> R.\n  Proof using.\n    intros H H' p. apply H.\n    - exact p.\n    - exact (H' p).\n  Qed.\n\n  Print imp_dist.\n  (* imp_dist = [fun f g x => f x (g x)]\n     fun (H : P -> Q -> R) (H' : P -> Q) (p : P) => H p (H' p)\n     : (P -> Q -> R) -> (P -> Q) -> P -> R *)\n\n  Theorem K : P -> Q -> P.\n  Proof using. intros p q. assumption. Qed.\n\n  Print K. (* K = [fun p q => p]\n                  fun (p : P) (_ : Q) => p\n                : P -> Q -> P *)\n\n  Definition f : (nat -> bool) -> (nat -> bool) -> nat -> bool.\n    intros f1 f2. assumption.\n  Defined.\n\n  Print f.\n  (* f = [fun f1 f2 => f2]\n       fun _ f2 : nat -> bool => f2\n     : (nat -> bool) -> (nat -> bool) -> nat -> bool *)\n\n  Eval compute in (f (fun n => true) (fun n => false) 45).\n  (* = false : bool *)\n\n  Opaque f.\n\n  Eval compute in (f (fun n => true) (fun n => false) 45).\n  (* = f (fun _ : nat => true) (fun _ : nat => false) 45 : bool *)\n\n  Section proof_of_triple_impl.\n    Hypothesis H : ((P -> Q) -> Q) -> Q.\n    Hypothesis p : P.\n\n    Lemma Rem: (P -> Q) -> Q.\n    Proof using p.\n      exact (fun H0 : P -> Q => H0 p).\n    Qed.\n\n    Theorem triple_impl : Q.\n    Proof using H p. exact (H Rem). Qed.\n  End proof_of_triple_impl.\n\n  Print triple_impl.\n  (* triple_impl = [fun H p => H (Rem p)]\n     fun (H : ((P -> Q) -> Q) -> Q) (p : P) => H (Rem p)\n     : (((P -> Q) -> Q) -> Q) -> P -> Q *)\n\n  Print Rem.\n  (* Rem = fun (p : P) (H0 : P -> Q) => H0 p\n         : P -> (P -> Q) -> Q *)\n\n  Theorem then_example : P -> Q -> (P -> Q -> R) -> R.\n  Proof using.\n    intros p q H.\n    apply H; assumption.\n  Qed.\n\n  Theorem triple_impl_one_shot : (((P -> Q) -> Q) -> Q) -> P -> Q.\n  Proof using.\n    intros H p; apply H; intro H0; apply H0; assumption.\n  Qed.\n\n  Theorem compose_example : (P -> Q -> R) -> (P -> Q) -> P -> R.\n  Proof using.\n    intros H H' p.\n    apply H; [exact p | exact (H' p)].\n  Qed.\n\n  Theorem compose_example' : (P -> Q -> R) -> (P -> Q) -> P -> R.\n  Proof using.\n    intros H H' p.\n    apply H; try apply H'; assumption.\n  Qed.\n\n  Theorem orelse_example\n    : (P -> Q) -> R -> ((P -> Q) -> R -> (T -> Q) -> T) -> T.\n  Proof.\n    intros H r H0. apply H0; (assumption || intro H1).\n  Abort.\n\n  Lemma L3 : (P -> Q) -> (P -> R) -> (P -> Q -> R -> T) -> P -> T.\n  Proof using.\n    intros H H0 H1 p.\n    apply H1; [idtac | apply H | apply H0]; assumption.\n  Qed.\n\n  Theorem then_fail_example : (P -> Q) -> (P -> Q).\n  Proof using.\n    intro X; apply X; fail.\n  Qed.\n\n  Theorem then_fail_example2 : ((P -> P) -> (Q -> Q) -> R) -> R.\n  Proof using.\n    (* intro X; apply X; fail. *)\n  Abort.\n\n  Theorem try_example : (P -> Q -> R -> T) -> (P -> Q) -> (P -> R -> T).\n  Proof using.\n    intros H H' p r.\n    apply H; try assumption. apply H', p.\n  Qed.\n\n  Theorem imp_dist' : (P -> Q -> R) -> (P -> Q) -> P -> R.\n  Proof using.\n    intros. apply H.\n    - exact H1.\n    - exact (H0 H1).\n  Qed.\n\n  Section section_for_cut_example.\n    Hypotheses (H : P -> Q)\n               (H0 : Q -> R)\n               (H1 : (P -> R) -> T -> Q)\n               (H2 : (P -> R) -> T).\n\n    Theorem cut_example : Q.\n    Proof using H H0 H1 H2.\n      cut (P -> R).\n      - intro H3. apply H1; [idtac | apply H2]; assumption.\n      - intro Hp. apply H0, H, Hp.\n    Qed.\n\n    Print cut_example.\n    (* cut_example =\n       let H3 : P -> R := fun Hp : P => H0 (H Hp)\n       in (fun H4 : P -> R => H1 H4 (H2 H4)) H3\n       : Q *)\n\n    Theorem cut_example' : Q.\n    Proof using H H0 H1 H2.\n      assert (P -> R) as H3.\n      { intro Hp. apply H0, H, Hp. }\n      apply H1; [idtac | apply H2]; assumption.\n    Qed.\n\n    Print cut_example'.\n    (* cut_example' =\n       let H3 : P -> R := fun Hp : P => H0 (H Hp)\n       in H1 H3 (H2 H3)\n       : Q *)\n\n    Theorem cut_example0 : Q.\n    Proof using H H0 H1 H2.\n      apply H1.\n      - intro Hp. apply H0, H, Hp.\n      - apply H2.\n        intro Hp. apply H0, H, Hp.\n    Qed.\n\n    Print cut_example0.\n    (* cut_example0 =\n       H1 (fun Hp : P => H0 (H Hp)) (H2 (fun Hp : P => H0 (H Hp)))\n       : Q *)\n  End section_for_cut_example.\n\n  Theorem triple_impl' : (((P -> Q) -> Q) -> Q) -> P -> Q.\n  Proof using. auto. Qed.\n\n  Theorem auto1 : (P -> Q) -> P -> Q.\n  Proof using. auto 0. auto 1. Qed.\n\n  Print auto1.\n  (* auto1 = fun H : P -> Q => H\n           : (P -> Q) -> P -> Q *)\n\n  Theorem auto2 : ((Q -> P) -> Q) -> P -> Q.\n  Proof using. auto 1. auto 2. Qed.\n\n  Print auto2.\n  (* auto2 = fun (H : (Q -> P) -> Q) (H0 : P) => H (fun _ : Q => H0)\n           : ((Q -> P) -> Q) -> P -> Q *)\n\n  Theorem auto_t2 : P -> (P -> Q) -> Q.\n  Proof using. auto 1. auto 2. Qed.\n\n  Theorem auto3 : (((P -> Q) -> Q) -> Q) -> P -> Q.\n  Proof using. auto 2. auto 3. Qed.\n\n  Print auto3.\n  (* auto3 = [fun H H0 => H (fun H1 => H1 H0)]\n     fun (H : ((P -> Q) -> Q) -> Q) (H0 : P) => H (fun H1 : P -> Q => H1 H0)\n     : (((P -> Q) -> Q) -> Q) -> P -> Q *)\n\n  Theorem auto3' : ((((Q -> P) -> Q) -> Q) -> Q) -> P -> Q.\n  Proof using. auto 2. auto 3. Qed.\n\n  Print auto3'.\n  (* auto3' = [fun H H0 => H (fun H1 => H1 (fun _ => H0))]\n     fun (H : (((Q -> P) -> Q) -> Q) -> Q) (H0 : P)\n         => H (fun H1 : (Q -> P) -> Q => H1 (fun _ : Q => H0))\n     : ((((Q -> P) -> Q) -> Q) -> Q) -> P -> Q *)\n\n  Theorem auto_t3 : P -> (P -> Q) -> (Q -> R) -> R.\n  Proof using. auto 2. auto 3. Qed.\n\n  Theorem auto4 : (((((P -> Q) -> Q) -> Q) -> Q) -> Q) -> P -> Q.\n  Proof using. auto 3. auto 4. Qed.\n\n  Theorem auto4' : ((((((Q -> P) -> Q) -> Q) -> Q) -> Q) -> Q) -> P -> Q.\n  Proof using. auto 3. auto 4. Qed.\n\n  Theorem auto_t4 : P -> (P -> Q) -> (Q -> R) -> (R -> T) -> T.\n  Proof using. auto 3. auto 4. Qed.\n\n  Theorem auto5 : (((((((P -> Q) -> Q) -> Q) -> Q) -> Q) -> Q) -> Q)\n                  -> P -> Q.\n  Proof using. auto 4. auto 5. Qed.\n\n  Variables S U : Prop.\n\n  Theorem auto_t5 : P -> (P -> Q) -> (Q -> R) -> (R -> T) -> (T -> S) -> S.\n  Proof using. auto 4. auto 5. Qed.\n\n  Theorem auto6 : (((((((((P -> Q) -> Q) -> Q) -> Q) -> Q)\n                      -> Q) -> Q) -> Q) -> Q)\n                  -> P -> Q.\n  Proof using. auto 5. auto 6. Qed.\n\n  Theorem auto_t6 : P -> (P -> Q) -> (Q -> R) -> (R -> T) -> (T -> S)\n                    -> (S -> U) -> U.\n  Proof using. auto 5. auto 6. Qed.\nEnd Minimal_propositional_logic.\n\nPrint imp_dist.\n(* imp_dist =\n   fun (P Q R : Prop) (H : P -> Q -> R) (H' : P -> Q) (p : P) => H p (H' p)\n   : forall P Q R : Prop, (P -> Q -> R) -> (P -> Q) -> P -> R *)\n\nSection using_imp_dist.\n  Variables (P1 P2 P3 : Prop).\n  Check (imp_dist P1 P2 P3).\n  (* imp_dist P1 P2 P3\n     : (P1 -> P2 -> P3) -> (P1 -> P2) -> P1 -> P3 *)\n\n  Check (imp_dist (P1 -> P2) (P2 -> P3) (P3 -> P1)).\n  (* imp_dist (P1 -> P2) (P2 -> P3) (P3 -> P1)\n     : ((P1 -> P2) -> (P2 -> P3) -> P3 -> P1) ->\n       ((P1 -> P2) -> P2 -> P3) -> (P1 -> P2) -> P3 -> P1 *)\nEnd using_imp_dist.\n", "meta": {"author": "anton0xf", "repo": "coq-art", "sha": "eed9782f0b62b4aaa9b33c2270931230ebb09ae6", "save_path": "github-repos/coq/anton0xf-coq-art", "path": "github-repos/coq/anton0xf-coq-art/coq-art-eed9782f0b62b4aaa9b33c2270931230ebb09ae6/ch03/3_logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7298148467214339}}
{"text": "Unset Elimination Schemes.\nDefinition dec (X: Type) : Type := X + (X -> False).\nDefinition eqdec X := forall x y: X, dec (x = y).\nDefinition iffT (X Y: Type) : Type := (X -> Y) * (Y -> X).\nNotation \"X <=> Y\" := (iffT X Y) (at level 95, no associativity).\nNotation sig := sigT.\nNotation Sig := existT.\nNotation pi1 := projT1.\nNotation pi2 := projT2.\nNotation \"'Sigma' x .. y , p\" :=\n  (sigT (fun x => .. (sigT (fun y => p)) ..))\n    (at level 200, x binder, right associativity,\n     format \"'[' 'Sigma'  '/  ' x  ..  y ,  '/  ' p ']'\")\n    : type_scope.\n\n(*** Numbers from first Principles *)\n\nModule Demo.\n  Inductive nat: Type := O | S (n: nat).\n\n  Implicit Types (n x y: nat).\n\n  Definition nat_elim (p: nat -> Type)\n    : p O -> (forall n, p n -> p (S n)) -> forall n, p n\n    := fun a f => fix F n := match n with O => a | S n' => f n' (F n') end.\n\n  Fact S_O n:\n      S n <> O.\n  Proof.\n    intros H.\n    change (if S n then True else False).\n    rewrite H. exact I.\n  Qed.\n\n  Fact S_injective n n' :\n      S n = S n' -> n = n'.\n  Proof.\n    intros H. \n    change (match S n with O => True | S n => n = n' end).\n    rewrite H. auto.\n  Qed.\n\n  Goal forall n,\n      S n <> n.\n  Proof.\n    refine (nat_elim _ _ _).\n    - apply S_O.\n    - intros n IH H. eapply IH, S_injective, H.\n  Qed.\nEnd Demo.\n\n(* From now on we use the predefined numbers from the library *)\n\nImplicit Types x y z n k : nat.\n\nFact nat_eqdec : eqdec nat.\nProof.\n  hnf.\n  induction x as [|x IH]; destruct y.\n  - left. reflexivity.\n  - right. intros [=].\n  - right. intros [=].\n  - destruct (IH y) as [H|H].\n    + left. f_equal. exact H.\n    + right. intros [= H1]. apply H, H1.\nDefined.\n\nLemma add_assoc x y z :\n  x + y + z = x + (y +z).\nProof.\n  induction x as [|x IH]; cbn; congruence.\nQed.\n\nLemma addO x :\n  x + 0 = x.\nProof.\n  induction x as [|x IH]; cbn; congruence.\nQed.\n\nLemma addS x y :\n  x + S y = S (x + y).\nProof.\n  induction x as [|x IH]; cbn. reflexivity.\n  rewrite IH. reflexivity.\nQed.\n\nLemma add_comm x y :\n  x + y = y + x.\nProof.\n  induction x as [|x IH]; cbn.\n  - rewrite addO. reflexivity.\n  - rewrite addS, IH. reflexivity.\nQed.\n\nLemma add_injective x y y' :\n  x + y = x + y' -> y = y'.\nProof.\n  induction x as [|x IH]; cbn.\n  - auto.\n  - intros [= H]. apply IH, H.\nQed.\n\nLemma add_injectiveO x y :\n  x + y = x -> y = 0.\nProof.\n  induction x as [|x IH]; cbn.\n  - auto.\n  - intros [= H]. auto.\nQed.\n\n(*** Subtraction *)\n\nLocate \"-\".\nArguments Nat.sub : simpl nomatch.\n\nFact sub_add_left x y :\n  (x + y) - x = y.\nProof.\n  induction x as [|x IH]; cbn.\n  - destruct y; reflexivity.\n  - exact IH.\nQed.\n\nFact sub_add_right x y :\n  x - (x + y) = 0.\nProof.\n  induction x as [|x IH]; cbn.\n  - reflexivity.\n  - exact IH.\nQed.\n\nFact sub_O_right x :\n  x - 0 = x.\nProof.\n  destruct x; reflexivity.\nQed.\n\nFact sub_xx x :\n  x - x = 0.\nProof.\n  induction x as [|x IH].\n  - reflexivity.\n  - exact IH.\nQed.\n\n(*** Order *)\n\nNotation \"x <= y\" := (x - y = 0) : nat_scope.\nNotation \"x < y\" := (S x - y = 0) : nat_scope.\nNotation \"x >= y\" := (y - x = 0) (only parsing) : nat_scope.\nNotation \"x > y\" := (S y - x = 0) (only parsing) : nat_scope.\n(* Negations ~(x < y) don't print correctly *)\n\n\n(** Case analysis *)\n\nDefinition le_dec x y : dec ( x <= y).\nProof.\n  apply nat_eqdec.\nDefined.\n\nFact le_lt_dec x y :\n  (x <= y) + (y < x).\nProof.\n  induction x as [|x IH] in y |-*.\n  - left. reflexivity.\n  - destruct y.\n    + right. reflexivity.\n    + apply (IH y).\nDefined.\n\nFact le_tricho x y :\n  (x < y) + (x = y) + (y < x).\nProof.\n  induction x as [|x IH] in y |-*; destruct y.\n  - auto.\n  - left. left. reflexivity.\n  - right. reflexivity.\n  - destruct (IH y) as [[H|H]|H].\n    + left. left. exact H.\n    + left. right. f_equal. exact H.\n    + right. exact H.\nDefined.\n\nFact le_lt_eq_dec x y :\n  x <= y -> (x < y) + (x = y).\nProof.\n  induction x as [|x IH] in y |-*; destruct y.\n  - auto.\n  - auto.\n  - intros [=].\n  - intros H. specialize (IH y H) as [IH|IH].\n    + left. exact IH.\n    + right. f_equal. exact IH.\nDefined.\n\nFact le_contra x y :\n  (y < x -> False) -> x <= y.\nProof.\n  destruct (le_lt_dec x y) as [H|H].\n  - intros _. exact H.\n  - intros H1. exfalso.  apply H1, H.\nQed.\n\n(** Existential characterization *)\n\nFact le_eq_sub x y :\n  x <= y -> x + (y - x) = y.\nProof.\n  induction x as [|x IH] in y |-*; cbn.\n  - intros _. apply sub_O_right.\n  - destruct y; cbn.\n    + intros [=].\n    + intros H%IH. f_equal. apply H.\nQed.\n \nFact le_ex x y :\n  x <= y <-> exists k, x + k = y.\nProof.\n  split.\n  - intros H. exists (y - x). apply le_eq_sub, H.\n  - intros [k <-]. apply sub_add_right.\nQed.\n\n(** Order properties *)\n\nFact le_add x y :\n  x <= x + y.\nProof.\n  apply sub_add_right.\nQed.\n\nFact le_S x :\n  x <= S x.\nProof.\n  replace (S x) with (x + 1).\n  - apply le_add.\n  - rewrite addS, addO. reflexivity.\nQed.\n\nFact le_add_O x y :\n  x + y <= x -> y = 0.\nProof.\n  rewrite sub_add_left. easy.\nQed.\n\nFact le_eq_O x :\n  x <= 0 -> x = 0.\nProof.\n  destruct x. auto. intros [=].\nQed.\n\nFact le_refl x :\n  x <= x.\nProof.\n  apply sub_xx.\nQed.\n\nFact le_trans x y z:\n  x <= y -> y <= z -> x <= z.\nProof.\n  intros [a <-]%le_ex [b <-]%le_ex.\n  rewrite add_assoc. rewrite sub_add_right. reflexivity.\nQed.\n  \nFact le_anti x y :\n  x <= y -> y <= x -> x = y.\nProof.\n  intros [a <-]%le_ex.\n  rewrite sub_add_left.\n  intros ->. symmetry. apply addO.\nQed.\n\nFact le_trans_lt_le x y z :\n  x < y -> y <= z -> x < z.\nProof.\n  intros [a <-]%le_ex [b <-]%le_ex.\n  cbn. rewrite add_assoc. apply le_add.\nQed.\n  \nFact le_strict_O x :\n  (x < 0) -> False.\nProof.\n  cbv. intros [=].\nQed.\n\nFact le_strict_add x y :\n  (x + y < x) -> False.\nProof.\n  rewrite <-addS. rewrite sub_add_left. intros [=].\nQed.\n\nFact le_strict x :\n  (x < x) -> False.\nProof.\n  pattern x at 1. rewrite <-(addO x). apply le_strict_add.\nQed.\n\nFact le_add_right x y z :\n  x <= y -> x <= y + z.\nProof.\n  intros [a <-]%le_ex. rewrite add_assoc. apply le_add.\nQed.\n\nFact le_add_S x y :\n  x <= y -> x <= S y.\nProof.\n  replace (S y) with (y + 1).\n  - apply le_add_right.\n  - rewrite addS, addO. reflexivity.\nQed.\n\nFact lt_le x y :\n  x < y -> x <= y.\nProof.\n  destruct y.\n  - intros [=].\n  - cbn. apply le_add_S.\nQed.\n\nFact lt_eq_le x y :\n   (x < y) \\/ (x = y) -> x <= y.\nProof.\n  intros [H|<-].\n  + apply lt_le, H.\n  + apply le_refl.\nQed.\n\nFact le_contra_eq x y :\n  (x < y -> False) -> (y < x -> False) -> x = y.\nProof.\n  intros H1%le_contra H2%le_contra.\n  eapply le_anti; eassumption.\nQed.\n  \nLemma bounded_forall_dec (p: nat -> Prop) k:\n  (forall x, dec (p x)) -> dec (forall x, x < k -> p x).\nProof.\n  intros H.\n  induction k as [|k IH].\n  - left. intros x [=].\n  - destruct (H k) as [H1|H1].\n    + destruct IH as [IH|IH]; cbn.\n      * left. intros x H2.\n        apply le_lt_eq_dec in H2 as [H2| ->]; auto.\n      * right. contradict IH. intros x H2. apply IH, lt_le, H2.\n    + right. contradict H1. apply H1, le_refl.\nQed.\n\nFact le_sub x y :\n  x - y <= x.\nProof.\n  induction x as [|x IH] in y |-*.\n  - reflexivity.\n  - destruct y; cbn.\n    + apply sub_xx.\n    + eapply le_trans.\n      * apply IH.\n      * apply le_S.\nQed.\n\n(*** Complete Induction  *)\n\nDefinition nat_compl_ind (p: nat -> Type) :\n  (forall x, (forall y, y < x -> p y) -> p x) -> forall x, p x.\nProof.\n  intros H x. apply H.\n  induction x as [|x IH]; intros y H1.\n  - exfalso. cbn in H1. discriminate H1.\n  - apply H. intros z H2. apply IH.\n    eapply le_trans_lt_le. exact H2. exact H1.\nDefined.\n\n(*** Euclidean Division *)\n\nDefinition delta x y a b := x = a * S y + b /\\ b <= y.\n\nFact delta1 y :\n  delta 0 y 0 0.\nProof.\n  unfold delta. cbn. easy.\nQed.\n\nFact delta2 x y a b :\n  delta x y a b -> b = y -> delta (S x) y (S a) 0.\nProof.\n  unfold delta. intros [-> H] ->. cbn. split.\n  - f_equal. rewrite addO. apply add_comm.\n  - reflexivity.\nQed.\n\nFact delta3 x y a b :\n  delta x y a b -> b <> y -> delta (S x) y a (S b).\nProof.\n  unfold delta. intros [-> H] H1. cbn. split.\n  - symmetry. apply addS. \n  - apply le_lt_eq_dec in H as [H| ->].\n    + exact H.\n    + easy.\nQed.\n\nFact delta_total :\n  forall x y, Sigma a b, delta x y a b.\nProof.\n  intros x y.\n  induction x as [|x (a&b&IH)].\n  - exists 0, 0. apply delta1.\n  - destruct (nat_eqdec b y) as [->|H].\n    + exists (S a), 0. eapply delta2. exact IH. reflexivity.\n    + exists a, (S b). apply delta3; assumption.\nDefined.\n\nDefinition D x y := pi1 (delta_total x y).\nDefinition M x y := pi1 (pi2 (delta_total x y)).\n\nCompute D 103 3.\nCompute M 103 3.\n\nFact delta_DM x y :\n  delta x y (D x y) (M x y).\nProof.\n  exact (pi2 (pi2 (delta_total x y))).\nQed.\n\nFixpoint Delta x y : nat * nat :=\n  match x with\n  | 0 => (0,0)\n  | S x' => let (a,b) := Delta x' y in\n           if nat_eqdec b y then (S a, 0) else (a, S b)\n  end.\n\nFact Delta_correct x y :\n  delta x y (fst (Delta x y)) (snd (Delta x y)).\nProof.\n  induction x as [|x IH].\n  - apply delta1.\n  - unfold delta. cbn.\n    destruct (Delta x y) as [a b]. cbn in IH.\n    destruct nat_eqdec as [->|H]; cbn [fst snd].\n    + eapply delta2. exact IH. reflexivity.\n    + eapply delta3. exact IH.  exact H.\nQed.\n\nFact delta_unique x y a b a' b' :\n  delta x y a b  -> delta x y a' b' -> a = a' /\\ b = b'.\nProof.\n  intros [-> H1] [H3 H2].\n  revert a a' H3.\n  induction a as [|a IH]; destruct a'; cbn.\n  - easy. \n  - intros ->. exfalso. clear H2. revert H1.\n    rewrite add_assoc. apply le_strict_add.\n  - intros <-. exfalso. clear H1 IH. revert H2.\n    rewrite add_assoc. apply le_strict_add.   \n  - intros [= H3]. rewrite !add_assoc in H3. \n    apply add_injective, IH in H3 as [<- <-].\n    easy.\nQed.\n\nFact delta4 x y:\n  x <= y -> delta x y 0 x.\nProof.\n  unfold delta. cbn. easy.\nQed.\n\nFact delta5 x y a b:\n  delta (x - S y) y a b -> x > y -> delta x y (S a) b.\nProof.\n  unfold delta. cbn [Nat.mul]. rewrite add_assoc. intros [<- H1] H2.\n  split. 2:exact H1.\n  symmetry. apply (le_eq_sub (S y) x), H2.\nQed.\n\nGoal forall x y,\n    (D x y = if le_lt_dec x y then 0 else S (D (x - S y) y)) /\\\n    (M x y = if le_lt_dec x y then x else M (x - S y) y).\nProof.\n  intros x y.\n  apply (delta_unique x y).\n  - apply delta_DM.\n  - destruct (le_lt_dec x y) as [H|H].\n    + apply delta4, H.\n    + apply delta5.\n      * apply delta_DM.\n      * exact H.\nQed.\n\n(*** Lia Demo *)\n\n(* The automation tactic lia provides an abstract treatment \n   of numbers that frees  us from knowing the basic definitions \n   and the basic lemmas. We shall use it from now on. *)\n\n(* Note that our definition of order via subtraction is still active.\n   All examples with lia will also work with Coq's definition of order *)\n\nFrom Coq Require Import Lia.\n\nGoal forall x y, x <= y -> y <= x -> x = y.\nProof.\n  lia.\nQed.\n\nGoal forall x y, ~ x < y -> ~ y < x -> x = y.\nProof.\n  lia.\nQed.\n\nGoal forall x y, x <= y -> x + (y - x) = y.\nProof.\n  lia.\nQed.\n\nGoal forall x y, x + y <= x -> y = 0.\nProof.\n  lia.\nQed.\n\n  Goal forall x y, x < y \\/ x = y \\/ y < x.\nProof.\n  lia.\nQed.\n\nLocate \"<=\".\n\n(* lia cannot do sums *)\nGoal forall x y, (x <= y) + (y < x).\nProof.\n  intros x y.\n  Fail lia.\n  destruct (x-y) as [|z] eqn:E.\n  - left. lia.\n  - right. lia.\nQed.\n\nGoal forall x y, x <= y <-> exists z, x + z = y.\nProof.\n  split.\n  - intros H. exists (y-x). lia.\n  - intros [z H]. lia. \nQed.\n\n \n\n", "meta": {"author": "uds-psl", "repo": "MPCTT", "sha": "8ab02bcad069d29105794e2a8fe03b07dcecb86e", "save_path": "github-repos/coq/uds-psl-MPCTT", "path": "github-repos/coq/uds-psl-MPCTT/MPCTT-8ab02bcad069d29105794e2a8fe03b07dcecb86e/coq/nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8757869965109765, "lm_q1q2_score": 0.7298148444470418}}
{"text": "Require Import Recdef List Omega Div2.\n\nImport ListNotations.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nLocal  Ltac name_term n t H := \n  assert (H: exists n', n' = t);\n  try (exists t; reflexivity);\n  destruct H as [n H]. \n\n\nSection UnApp.\n  Context {A: Type}.\n\n  Fixpoint unapp (n:nat)(m:list A) : list A * list A:=\n    match n with\n    | 0 => ([], m)\n    | S n => match m with\n             | nil => ([], [])\n             | x::xs => let (m1, m2) := unapp n xs in\n                        (x::m1, m2)\n             end\n    end.\n\n  Lemma unapp_wont_expand: \n    forall n (m m1 m2: list A), \n      unapp n m = (m1, m2) -> \n      length m1 <= length m /\\ length m2 <= length m. \n  Proof. \n    induction n as [| n]; intros * UA. \n    - simpl in UA. injection UA; intros M1 M2.\n      subst m1 m2. auto with arith.\n    - destruct m. \n      + simpl in UA.\n        injection UA; intros M1 M2. \n        subst m1 m2. auto with arith. \n      + simpl in UA.\n        name_term ua' (unapp n m) UA'.\n        rewrite <- UA' in UA.\n        destruct ua' as [m1' m2'].\n        injection UA; intros M1 M2; subst m1 m2; clear UA.\n        symmetry in UA'.\n        apply IHn in UA'.\n        simpl.\n        omega. \n  Qed.        \n  \n  Lemma unapp_app: \n    forall n (m m1 m2: list A),\n      (m1, m2) = unapp n m -> \n      m1 ++ m2 = m.\n  Proof. \n    intros n m.\n    revert n.\n    induction m as [| x xs]; intros * UA.\n    - destruct n as [| n'];\n        simpl in UA;\n        injection UA; intros M1 M2; subst m1 m2; clear UA;\n          simpl; auto with arith.\n    - destruct n as [| n'];\n        simpl in UA.\n      + injection UA; intros M1 M2; subst m1 m2; clear UA.\n        reflexivity.\n      + name_term ua' (unapp n' xs) UA'.  rewrite <- UA' in UA.\n        destruct ua' as [m1' m2'].\n        injection UA; intros M1 M2; subst m1 m2; clear UA.\n        simpl. \n        apply IHxs in UA'.\n        subst xs.\n        reflexivity.\n  Qed.\n\n  Lemma unapp_reduce_m1: \n    forall n (m m1 m2: list A), \n      unapp n m = (m1, m2) -> \n      n < length m -> \n      length m1 < length m. \n  Proof. \n    intros n m. \n    revert n.\n    induction m as [| x xs];\n      intros * UA NltM. \n    - simpl in NltM. inversion NltM.\n    - destruct n as [| n].\n      + unfold unapp in UA.\n        injection UA; intros M1 M2; subst m1 m2; clear UA.\n        simpl. auto with arith.\n      + simpl in UA.\n        simpl in NltM. \n        apply lt_S_n in NltM.\n        name_term ua' (unapp n xs) UA'.  rewrite <- UA' in UA.\n        destruct ua' as [m1' m2'].\n        injection UA; intros M1 M2; subst m1 m2; clear UA.\n        symmetry in UA'.\n        apply IHxs in UA'; auto.\n        simpl.\n        omega. \n  Qed. \n\n\n\n  Lemma unapp_reduce_m2: \n    forall n (m m1 m2: list A), \n      unapp n m = (m1, m2)-> \n      n > 0 ->\n      length m > 0 -> \n      length m2 < length m. \n  Proof. \n    intros * UA Ngt0 Mgt0. \n    cut (length m1 > 0). \n    {\n      intro H.\n      symmetry in UA.\n      apply unapp_app in UA.\n      subst m.\n      rewrite app_length in *.\n      omega. \n    }\n    destruct n as [| n']; destruct m as [| x xs].\n    - inversion Ngt0.\n    - inversion Ngt0.\n    - simpl in Mgt0.\n      inversion Mgt0.      \n    - simpl in UA.\n      name_term ua' (unapp n' xs) UA'.  rewrite <- UA' in UA.\n      destruct ua' as [m1' m2'].\n      injection UA; intros M1 M2; subst m1 m2; clear UA.\n      simpl. auto with arith.\n  Qed.\n\n  Definition unapp_half(m: list A) :=\n    let n := length m in \n    let n2 := div2 n in\n    let n1 := n - n2 in\n    unapp n1 m.\n\n  Lemma unapp_half_app: \n    forall m m1 m2,\n      (m1, m2) = unapp_half m -> \n      m1 ++ m2 = m.\n  Proof. \n    induction m as [| x xs]; intros * SP. \n    inversion SP; auto.\n    unfold unapp_half in SP.\n    apply unapp_app in SP.\n    auto.\n  Qed.\n\n  Lemma div2_SS: \n    forall n, div2 (S (S n)) > 0.\n  Proof. \n    induction n; simpl; auto with arith.\n  Qed. \n\n\n  \n  Lemma unapp_half_nonnil_reduces: \n    forall m m1 m2, \n      unapp_half m = (m1,m2) -> \n      length m > S 0 -> \n      length m1 < length m /\\ length m2 < length m.\n  Proof. \n    intros * SP MgtO.\n    unfold unapp_half in SP.\n    name_term k (length m) LEN. \n    rewrite <- LEN in *.\n    name_term n (k - div2 k) N1. \n    rewrite <- N1 in SP.     \n    assert (DK: div2 k < k) \n      by (apply lt_div2; auto with arith).\n    name_term d (div2 k) D. \n    rewrite <- D in *.\n    destruct m as [| x1 xs]. \n    simpl in LEN. subst k. inversion DK.\n    destruct xs as [| x2 xs].\n    simpl in LEN. subst k. inversion MgtO. inversion H0.\n    assert (DgtO: d > 0) by (subst k d; apply div2_SS). \n    assert (NltM: n < length (x1::x2::xs))\n      by (simpl in *; omega). \n    subst k.\n    split. \n    - apply unapp_reduce_m1 with (n:=n) (m2:=m2); auto.\n    - assert (n > 0) by omega. \n      assert (length (x1::x2::xs) > 0) by (simpl; omega).\n      apply unapp_reduce_m2 with (n:=n) (m1:=m1); auto.\n  Qed. \n\n\nEnd UnApp.\n\nLemma unapp_map A B (f: A -> B): \n  forall n (m m1 m2: list A),\n    (m1, m2) = unapp n m ->\n    (map f m1, map f m2) = unapp n (map f m).\nProof.\n    intros n m.\n    revert n.\n    induction m as [| x xs]; intros * UA.\n    - destruct n as [| n'];\n        simpl in UA;\n        injection UA; intros M1 M2; subst m1 m2; clear UA;\n          simpl; auto with arith.\n    - destruct n as [| n'];\n        simpl in UA.\n      + injection UA; intros M1 M2; subst m1 m2; clear UA.\n        reflexivity.\n      + name_term ua' (unapp n' xs) UA'.  rewrite <- UA' in UA.\n        destruct ua' as [m1' m2'].\n        injection UA; intros M1 M2; subst m1 m2; clear UA.\n        simpl. \n        apply IHxs in UA'.\n        rewrite <- UA'.\n        reflexivity.\nQed.\n\nLemma unapp_half_map A B (f: A -> B): \n  forall m m1 m2,\n    (m1, m2) = unapp_half m ->\n    (map f m1, map f m2) = unapp_half (map f m).\nProof.\n  intros.\n  eapply unapp_map with (f := f) in H.\n  unfold unapp_half.\n  rewrite map_length.\n  auto.\nQed.\n\nSection Folds.\n  Variable A: Type.\n  Variable f: A -> A -> A.\n  Variable fComm: forall a b, f a b = f b a.\n  Variable fAssoc: forall a b c, f (f a b) c = f a (f b c).\n  Variable unit: A.\n  Variable fUnit: forall x, f unit x = x.\n\n  Lemma fold_right_inclusion:\n    forall m1 m2 seed,\n      fold_right f seed (m1 ++ m2) = fold_right f (fold_right f seed m2) m1.\n  Proof.\n    intro m1.\n    induction m1 as [| x xs]; intros. \n    - reflexivity.\n    - cut (fold_right f seed (xs ++ m2)\n           = fold_right f (fold_right f seed m2) xs).\n      intro C; simpl.\n      now rewrite C.\n      apply IHxs.\n  Qed.\n\n  (* h := fold_tree *)\n  (* odot := f *)\n\n  Function fold_tree (ls: list A) {measure length ls} :=\n    match ls with\n    | nil => unit\n    | [x] => f x unit\n    | [x;y] => f x y\n    | _ => let (m1, m2) := unapp_half ls in\n           f (fold_tree m1) (fold_tree m2)\n    end.\n  Proof.\n    - abstract (intros;\n                unfold unapp_half in teq2;\n                symmetry in teq2;\n                name_term len_x_n_l0 (length (x::y::a::l1)) LEN;\n                rewrite <- LEN in *;\n                simpl in LEN;\n                assert (L0: len_x_n_l0 > 0) by omega;\n                apply lt_div2 in L0;\n                assert (len_x_n_l0 - div2 len_x_n_l0 > 0) by omega;\n                symmetry in teq2;\n                apply unapp_reduce_m2 in teq2; auto;\n                simpl in teq2;\n                [rewrite <- LEN in *;\n                 apply teq2|\n                 simpl;\n                 auto with arith]).\n    - abstract (intros;\n                unfold unapp_half in teq2;\n                apply unapp_reduce_m1 in teq2;\n                [apply teq2|\n                 clear teq2;\n                 name_term len_x_n_l0 (length (x::y::a::l1)) LEN;\n                 rewrite <- LEN in *;\n                 simpl in LEN;\n                 assert (L0: len_x_n_l0 > 0) by omega;\n                 apply lt_div2 in L0;\n                 assert (L1: len_x_n_l0 > 1) by omega;\n                 rewrite LEN at 2;\n                 simpl;\n                 omega]).\n  Defined.\n\n  Lemma f_comm1 a b c:\n    f a (f b c) = f b (f a c).\n  Proof.\n    rewrite <- fAssoc.\n    rewrite <- fAssoc.\n    assert (sth:f a b = f b a) by apply fComm; rewrite sth; rewrite <- sth.\n    auto.\n  Qed.\n\n  Lemma f_comm2 a b c:\n    f a (f b c) = f (f a b) c.\n  Proof.\n    rewrite <- fAssoc.\n    reflexivity.\n  Qed.\n\n  Lemma fold_right_f_assoc:\n    forall i m1 seed,\n      f i (fold_right f seed m1) = fold_right f (f i seed) m1.\n  Proof.\n    intros i m1.\n    assert (exists k, length m1 <= k) as [k K]\n        by (exists (length m1); auto).\n    revert i m1 K.\n    induction k as [| k]; intros * K *.\n    - assert (A1: length m1 = 0) by omega. \n      apply length_zero_iff_nil in A1.\n      subst m1. \n      reflexivity.\n    - destruct m1 as [| y ys].\n      + reflexivity.\n      + simpl in K.\n        apply le_S_n in K.\n        simpl.\n        rewrite <- IHk; auto.\n        apply f_comm1.\n  Qed.\n\n  Lemma fold_right_slideout:\n    forall m seed,\n      fold_right f seed m = f (fold_right f unit m) seed.\n  Proof.\n    induction m as [| x xs]; intros.\n    - now simpl.\n    - simpl.\n      rewrite IHxs.\n      destruct xs.\n      apply f_comm2.\n      apply f_comm2.\n  Qed.\n\n  Lemma fold_right_homomorphism:\n    forall m1 m2,\n      fold_right f unit (m1 ++ m2) = f (fold_right f unit m1) (fold_right f unit m2).\n  Proof.\n    intros *.\n    name_term lhs (f (fold_right f unit m1) (fold_right f unit m2)) LHS.\n    rewrite <- LHS.\n    rewrite fold_right_inclusion.\n    rewrite fold_right_slideout. \n    now subst lhs.\n  Qed.\n\n  Lemma fold_right_homomorphism_unapp:\n    forall m m1 m2,\n      (m1, m2) = unapp_half m ->\n      fold_right f unit m = f (fold_right f unit m1) (fold_right f unit m2).\n  Proof.\n    intros.\n    apply unapp_half_app in H.\n    rewrite <- H.\n    eapply fold_right_homomorphism.\n  Qed.\n  \n  Theorem fold_right_fold_tree:\n    forall m,\n      fold_right f unit m = fold_tree m.\n  Proof.\n    intro m.\n    assert (exists k, length m <= k) \n      as [k K] by (exists (length m); auto). \n    revert m K.\n    induction k as [| k]; intros * K.\n    - assert (A1: length m = 0) by omega. \n      apply length_zero_iff_nil in A1.\n      now subst m.\n    - destruct m as [| x1 xs]. now simpl.\n      destruct xs as [| x2 xs]. now simpl.\n      rewrite fold_tree_equation. \n      name_term tpl (unapp_half (x1::x2::xs)) Tpl;\n        rewrite <- Tpl; destruct tpl as [m1 m2].\n      simpl in K. \n      assert (K': S (length xs) <= k) by (rewrite le_S_n; auto); \n        clear K; rename K' into K.\n      assert (length m1 <= length (x2::xs) \n              /\\ length m2 <= length (x2::xs))\n        as [A1 A2]. {\n        symmetry in Tpl.\n        apply unapp_half_nonnil_reduces in Tpl; auto.\n        2: simpl; omega. \n        simpl in *.\n        omega. \n      }\n      simpl in A1, A2.\n      assert (A3: length m1 <= k) by omega; clear A1.\n      assert (A4: length m2 <= k) by omega; clear A2. \n      rewrite <- (IHk m1 A3); rewrite <- (IHk m2 A4).\n      rewrite fold_right_homomorphism_unapp with (m:=(x1::x2::xs)) (m1 := m1) (m2 := m2); destruct xs; auto.\n      unfold unapp_half in Tpl; simpl in *.\n      inversion Tpl; clear Tpl; subst.\n      simpl.\n      rewrite (fComm x1 unit), (fComm x2 unit).\n      rewrite ?fUnit.\n      auto.\n  Qed.\n\n  Theorem fold_left_fold_right:\n    forall m seed,\n      fold_left f m seed = fold_right f seed m.\n  Proof.\n    induction m; simpl; auto; intros.\n    rewrite IHm.\n    rewrite fold_right_f_assoc.\n    rewrite fComm.\n    auto.\n  Qed.\n\n\n  Theorem fold_left_fold_tree:\n    forall m,\n      fold_left f m unit = fold_tree m.\n  Proof.\n    intros.\n    rewrite fold_left_fold_right.\n    apply fold_right_fold_tree.\n  Qed.\n\nEnd Folds.\n\nSection FoldWhich.\n  Variable A: Type.\n  Variable decA: forall a b: A, {a = b} + {a <> b}.\n  Variable which: A -> A -> bool.\n  Variable whichRefl: forall a, which a a = true.\n  Variable whichSym: forall x y, x = y \\/ which x y = negb (which y x).\n  Variable whichTrans: forall a b c, which a b = which b c -> which a c = which a b.\n  \n  Definition pick x y := if which x y then x else y.\n\n  Local Lemma pickComm: forall a b, pick a b = pick b a.\n  Proof.\n    unfold pick; intros.\n    specialize (whichSym a b).\n    destruct whichSym; subst; auto.\n    rewrite H.\n    destruct (which b a); auto.\n  Qed.\n\n  Local Lemma pickAssoc: forall a b c, pick (pick a b) c = pick a (pick b c).\n  Proof.\n    unfold pick; intros.\n    case_eq (which b c); case_eq (which a b); intros; auto.\n    - erewrite whichTrans; eauto.\n      rewrite H; auto.\n    - rewrite H0; auto.\n    - rewrite H0.\n      erewrite whichTrans; eauto.\n      rewrite H; auto.\n  Qed.\n      \n  Variable unit: A.\n  Variable whichUnit: forall x, x <> unit -> which unit x = false.\n  \n  Local Lemma pickUnit: forall x, pick unit x = x.\n  Proof.\n    unfold pick; intros.\n    destruct (decA unit x); subst.\n    destruct (which x x); auto.\n    assert (sth: x <> unit) by (intro; subst; tauto).\n    specialize (whichUnit sth).\n    rewrite whichUnit; auto.\n  Qed.\n\n  Local Lemma pickUnit_both: forall x y, pick x y = unit -> x = unit /\\ y = unit.\n  Proof.\n    intros.\n    unfold pick in *.\n    case_eq (which x y); intros sth; rewrite sth in *; subst.\n    - split; auto.\n      destruct (decA y unit); auto.\n      specialize (whichUnit n).\n      congruence.\n    - split; auto.\n      specialize (whichSym x unit).\n      destruct whichSym; auto.\n      rewrite H in sth.\n      rewrite Bool.negb_false_iff in sth.\n      rewrite sth in *; simpl in *.\n      destruct (decA x unit); auto.\n      specialize (whichUnit n).\n      congruence.\n  Qed.\n\n  Lemma fold_right_unit ls:\n    fold_right pick unit ls = unit -> forall x, In x ls -> x = unit.\n  Proof.\n    induction ls; simpl; auto; intros.\n    - tauto.\n    - destruct H0; subst.\n      apply pickUnit_both in H.\n      destruct H as [s1 s2]; subst; auto.\n      apply pickUnit_both in H.\n      destruct H as [s3 s4].\n      eapply IHls; eauto.\n  Qed.\n\n  Theorem which1_fold_right:\n    forall ls,\n      forall i, i < length ls -> which (fold_right pick unit ls) (nth i ls unit) = true.\n  Proof.\n    induction ls; simpl; auto; intros.\n    - Omega.omega.\n    - unfold pick in *.\n      remember (fold_right (fun x y => if which x y then x else y) unit ls) as sth.\n      destruct i; simpl in *.\n      + case_eq (which a sth); intros sth2.\n        * subst; eapply whichRefl; eauto.\n        * destruct (decA sth a); simpl in *.\n          -- subst; rewrite whichRefl; auto.\n          -- specialize (whichSym sth a).\n             destruct whichSym; [tauto|].\n             rewrite H0 in *.\n             rewrite Bool.negb_true_iff.\n             auto.\n      + case_eq (which a sth); intros sth2.\n        * specialize (IHls i ltac:(Omega.omega)).\n          rewrite <- IHls in sth2.\n          pose proof (@whichTrans _ _ _ sth2).\n          congruence.\n        * specialize (IHls i ltac:(Omega.omega)).\n          auto.\n  Qed.\n\n  Theorem which1_fold_tree:\n    forall ls,\n      forall i, i < length ls -> which (fold_tree pick unit ls) (nth i ls unit) = true.\n  Proof.\n    intros.\n    rewrite <- fold_right_fold_tree; auto; intros.\n    - eapply which1_fold_right; eauto.\n    - apply pickComm.\n    - apply pickAssoc.\n    - apply pickUnit.\n  Qed.\n\n  Theorem which1_fold_left:\n    forall ls,\n      forall i, i < length ls -> which (fold_left pick ls unit) (nth i ls unit) = true.\n  Proof.\n    intros.\n    rewrite fold_left_fold_right; auto; intros.\n    - eapply which1_fold_right; eauto.\n    - apply pickComm.\n    - apply pickAssoc.\n  Qed.\n\n  Theorem which2_fold_right:\n    forall ls,\n      fold_right pick unit ls <> unit ->\n      exists n, n < length ls /\\ nth n ls unit = fold_right pick unit ls.\n  Proof.\n    induction ls; simpl; auto; intros.\n    - tauto.\n    - destruct (decA (fold_right pick unit ls) unit); simpl in *.\n      + rewrite e in *.\n        rewrite pickComm in *.\n        rewrite pickUnit in *; subst.\n        exists 0; repeat split; auto; try Omega.omega; intros.\n      + specialize (IHls n).\n        destruct IHls as [j [jLen cond1]].\n        subst.\n        rewrite <- cond1 in *.\n        unfold pick in *.\n        case_eq (which a (nth j ls unit)); intros sth; rewrite sth in *; subst.\n        * exists 0; repeat split; auto; try Omega.omega; intros.\n        * exists (S j); repeat split; auto; try Omega.omega; intros.\n  Qed.\n\n  Theorem which2_fold_tree:\n    forall ls,\n      fold_tree pick unit ls <> unit ->\n      exists n, n < length ls /\\ nth n ls unit = fold_tree pick unit ls.\n  Proof.\n    intros.\n    rewrite <- fold_right_fold_tree in *; auto; intros.\n    - eapply which2_fold_right; eauto; auto.\n    - apply pickComm.\n    - apply pickAssoc.\n    - apply pickUnit.\n    - apply pickComm.\n    - apply pickAssoc.\n    - apply pickUnit.\n  Qed.\n\n  Theorem which2_fold_left:\n    forall ls,\n      fold_left pick ls unit <> unit ->\n      exists n, n < length ls /\\ nth n ls unit = fold_left pick ls unit.\n  Proof.\n    intros.\n    rewrite fold_left_fold_right in *; auto; intros.\n    - eapply which2_fold_right; eauto; auto.\n    - apply pickComm.\n    - apply pickAssoc.\n    - apply pickComm.\n    - apply pickAssoc.\n  Qed.\n\n   Theorem whichNonUnit_fold_right:\n    forall ls val,\n      val = fold_right pick unit ls ->\n      val <> unit ->\n      exists n, n < length ls /\\ nth n ls unit = val /\\ forall i, i < length ls -> i <> n -> which val (nth i ls unit) = true.\n  Proof.\n    induction ls; simpl; auto; intros.\n    - tauto.\n    - destruct (decA (fold_right pick unit ls) unit); simpl in *.\n      + rewrite e in *.\n        rewrite pickComm in *.\n        rewrite pickUnit in *; subst.\n        exists 0; repeat split; auto; try Omega.omega; intros.\n        destruct i; auto.\n        pose proof (fold_right_unit _ e) as sth.\n        specialize (sth (nth i ls unit) (nth_In (n := i) ls unit ltac:(Omega.omega))).\n        rewrite sth.\n        specialize (whichSym a unit).\n        destruct whichSym as [whichSym0 | whichSym0]; auto.\n        rewrite whichSym0.\n        rewrite Bool.negb_true_iff.\n        auto.\n      + specialize (IHls _ eq_refl n).\n        destruct IHls as [j [jLen [cond1 cond2]]].\n        subst.\n        rewrite <- cond1 in *.\n        unfold pick in *.\n        case_eq (which a (nth j ls unit)); intros sth; rewrite sth in *; subst.\n        * exists 0; repeat split; auto; try Omega.omega; intros.\n          destruct i; auto.\n          destruct (Nat.eq_dec i j); subst; [auto|].\n          specialize (cond2 i ltac:(Omega.omega) n0).\n          rewrite <- cond2 in sth.\n          pose proof (whichTrans sth).\n          congruence.\n        * exists (S j); repeat split; auto; try Omega.omega; intros.\n          destruct i; auto.\n          -- specialize (whichSym (nth j ls unit) a).\n             destruct whichSym as [whichSym0 | whichSym0]; auto.\n             ++ rewrite whichSym0 in *.\n                eapply whichRefl; eauto.\n             ++ rewrite whichSym0.\n                rewrite Bool.negb_true_iff; auto.\n          -- eapply cond2; eauto; Omega.omega.\n  Qed.\n\n  Theorem whichNonUnit_fold_left:\n    forall ls val,\n      val = fold_left pick ls unit ->\n      val <> unit ->\n      exists n, n < length ls /\\ nth n ls unit = val /\\ forall i, i < length ls -> i <> n -> which val (nth i ls unit) = true.\n  Proof.\n    intros.\n    rewrite fold_left_fold_right in H; auto; intros.\n    - eapply whichNonUnit_fold_right; eauto.\n    - apply pickComm.\n    - apply pickAssoc.\n  Qed.\n\n  Theorem whichNonUnit_fold_tree:\n    forall ls val,\n      val = fold_tree pick unit ls ->\n      val <> unit ->\n      exists n, n < length ls /\\ nth n ls unit = val /\\ forall i, i < length ls -> i <> n -> which val (nth i ls unit) = true.\n  Proof.\n    intros.\n    rewrite <- fold_right_fold_tree in H; auto; intros.\n    - eapply whichNonUnit_fold_right; eauto.\n    - apply pickComm.\n    - apply pickAssoc.\n    - apply pickUnit.\n  Qed.\nEnd FoldWhich.\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Lib/Fold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.72981483495673}}
{"text": "From mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* disjointness *)\nGoal forall x, S x <> 0.\nProof. by []. Qed.\n\n(* injectivity *)\nLemma inj: forall x y, S x = S y -> x = y.\nProof. move => x y. by case. Qed.\n\n(* progress *)\nLemma progr: forall x, S x <> x.\nProof. move => x. elim: x => [//| n IH].\n  by move /inj.\nQed.\n\n(* Decidable type *)\nDefinition D (X: Type): Type := X + {X -> False}.\n\n(* 15.1.2 *)\nLemma discrete: forall (x y: nat), D (x = y).\nProof.\n  elim.\n    - case. \n        by left.\n      move => n. right. by [].\n    - move => n IH.\n      case.\n        by right.\n      move => y.\n      case (IH y).\n        left. by rewrite e.\n        right. move => H.\n          apply f.\n          move: H.\n          by case.\nQed.\n\nTheorem double_ind: forall (p: nat -> nat -> Type), \n  (forall x, p x 0) ->\n  (forall x y, p x y -> p y x -> p x (S y)) ->\n  (forall x y, p x y).\nProof.\n  move => p H0 H1 x y.\n  move: y.\n  elim.\n    by apply H0.\n  move => y H.\n  apply H1.\n    apply H.\n  move: x H.\n  elim => [H| n H H'].\n    apply H0.\n  apply H1.\nAdmitted.\n\nLemma leq0: forall x, x <= 0 -> x = 0.\nProof.\n  elim => [//|n IH].\n    move => contra.\n    by exfalso.\nQed.\n\n(* 15.5.2 *)\nLemma leq_unpack: forall x y, x <= y -> x < y \\/ x = y.\nProof.\n  move => x y.\n  rewrite leq_eqVlt.\n  move => /orP.\n  case.\n    right.\n    by move: a => /eqnP.\n  by left.\nQed.\n\n(* 15.5.5 *)\nLemma existential_characrerization: forall x y, x <= y -> exists k, x + k = y.\nProof.\n  move => x y.\n  elim: y x => [y /leq0 -> | y' IH x H].\n    by exists 0.\n  move: H => /leq_unpack.\n  case.\n    - move => /ltnSE H.\n      move : (IH x H) => [k H'].\n      exists k.+1.\n      by rewrite -H' addnS.\n  move => ->.\n  exists 0.\n  by rewrite addn0.\nQed.\n\n\n(* 15.6.2 *)\nLemma trans: forall x y z, x < y <= z -> x < z.\nProof.\n  move => x y z /andP [Hl Hr].\n  move: (existential_characrerization Hl) (existential_characrerization Hr).\n  move => [k <-] [k' Hr'].\n  move: Hr'.\n  rewrite 2!addSn.\n  rewrite addnC addnCA -addnS.\n  move => <-.\n  rewrite /(_ < _) addnS subSS.\n  rewrite subnDA.\n  rewrite subnn.\n  rewrite sub0n.\n  by [].\nQed.\n\n(* 15.7.1 *)\nTheorem complete_ind: forall (p: nat -> Type),\n  (forall x, (forall y, y < x -> p y) -> p x) ->\n  (forall x, p x).\nProof.\n  move => p H x.\n  have G: forall n x, x < n -> p x.\n    elim.\n      move => x' contra. by exfalso.\n    move => n IH x' L.\n    apply H => y Ly. \n    apply IH.\n    have G: y < x' <= n.\n      apply /andP.\n      split => [//|].\n      move: L.\n      rewrite [x' < n.+1]/(x'.+1 <= n.+1).\n      by rewrite subSS.\n    by apply (trans G).\n  apply H.\n  apply G.\nQed.\n    \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/model_and_prooving_CompTT/pt3/ch15_numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7298148241501099}}
{"text": "Global Set Default Goal Selector \"!\".\n\nRequire Import Arith.\nRequire Import Lia.\n\nRecord nbpair := mkpair {\n  first : nat;\n  second : bool;\n}.\n\nSearch negb.\n\nTheorem t2 :\n  forall x b,\n    mkpair (x+x-x) b = mkpair x (negb (negb b)).\nProof.\n  intros.\n  f_equal.\n  (*- rewrite Nat.add_sub. reflexivity.*)\n  (*- eauto. (* fully solves goal using \"hints\" or does nothing. not the same as \"auto\" due to\n   search differences. *)*)\n  - lia. (* can do anything: labs are practice where it doesn't apply. *)\n  - rewrite Bool.negb_involutive. reflexivity.\nQed.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n    (n + m) * p = (n * p) + (m * p).\n  induction n.\n  - simpl.\n    eauto.\n  - intros.\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  induction n.\n  - intros.\n    simpl.\n    reflexivity.\n  - intros.\n    simpl.\n", "meta": {"author": "kazimuth", "repo": "6.826", "sha": "74e9eb7dbe352394fae68e988fe338195969ede9", "save_path": "github-repos/coq/kazimuth-6.826", "path": "github-repos/coq/kazimuth-6.826/6.826-74e9eb7dbe352394fae68e988fe338195969ede9/3-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.729796225885766}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus (plus x y) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj206_coqofml_1PFstD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7297780751683084}}
{"text": "Require Import PeanoNat.\n\nInductive propvar : Type :=\n  pv : nat -> propvar.\n\nLemma propvar_dec : forall (p q : propvar), {p = q} + {p <> q}.\nProof.\n  intros [p] [q]. destruct (Nat.eq_dec p q).\n  subst. auto. right. intros H.\n  inversion H. subst. auto.\nQed.  \n  \nInductive Modal : Type :=\n    atom : propvar -> Modal  \n  | mneg : Modal -> Modal\n  | mconj : Modal -> Modal -> Modal\n  | mdisj : Modal -> Modal -> Modal\n  | mimpl : Modal -> Modal -> Modal\n  | box : Modal -> Modal\n  | dia : Modal -> Modal.\n\nNotation \"# p\" := (atom p) (at level 1) : modal_scope.\nNotation \"m~ ϕ\" := (mneg ϕ) (at level 2) : modal_scope.\nNotation \"ϕ1 m∧ ϕ2\" := (mconj ϕ1 ϕ2) (at level 15, right associativity) : modal_scope.\nNotation \"ϕ1 m∨ ϕ2\" := (mdisj ϕ1 ϕ2) (at level 15, right associativity) : modal_scope.\nNotation \"ϕ1 m→ ϕ2\" := (mimpl ϕ1 ϕ2) (at level 16, right associativity) : modal_scope.\nNotation \"'[.]' ϕ\" := (box ϕ) (at level 2) : modal_scope.\nNotation \"'<.>' ϕ\" := (dia ϕ) (at level 2) : modal_scope.\n\n(* Given a conditional, return the antecedent. Don't care about other inputs. *)\nDefinition calc_ante_modal ϕ :=\n  match ϕ with\n  | mimpl ψ1 ψ2 => ψ1\n  | _ => ϕ\n  end.\n\n(* Given a conditional, return the consequent. Don't care about other inputs. *)\nDefinition calc_cons_modal ϕ :=\n  match ϕ with\n  | mimpl ψ1 ψ2 => ψ2\n  | _ => ϕ\n  end.\n", "meta": {"author": "caitlindabrera", "repo": "Sahlqvist", "sha": "d0a755fb663a6cabc0babb691564cdf575fc8b36", "save_path": "github-repos/coq/caitlindabrera-Sahlqvist", "path": "github-repos/coq/caitlindabrera-Sahlqvist/Sahlqvist-d0a755fb663a6cabc0babb691564cdf575fc8b36/vsSahlq/coq_code/Modal_syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7297071772995531}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\n(* ** Base p representation *)\n\nRequire Import Arith Nat Lia.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_tac gcd rel_iter sums.\n\nSet Implicit Arguments.\n\nLocal Notation power := (mscal mult 1).\nLocal Notation \"∑\" := (msum plus 0).\n\nFact sum_0n_distr_in_out n a b f :\n      ∑ n (fun i => (a i+b i) * f i) \n    = ∑ n (fun i => a i * f i) \n    + ∑ n (fun i => b i * f i).\nProof.\n  rewrite <- msum_sum; auto.\n  + apply msum_ext; intros; ring.\n  + intros; ring.\nQed.\n\nSection power_decomp.\n\n  Variable (p : nat) (Hp : 2 <= p).\n\n  Let power_nzero x : power x p <> 0.\n  Proof. generalize (@power_ge_1 x p); lia. Qed.\n\n  Fact power_decomp_lt n f a q :  \n           (forall i j, i < j < n -> f i < f j)\n        -> (forall i, i < n -> f i < q)\n        -> (forall i, i < n -> a i < p)\n        -> ∑ n (fun i => a i * power (f i) p) < power q p.\n  Proof.\n    revert q; induction n as [ | n IHn ]; intros q Hf1 Hf2 Ha.\n    + rewrite msum_0; apply power_ge_1; lia.\n    + rewrite msum_plus1; auto.\n      apply lt_le_trans with (1*power (f n) p + a n * power (f n) p).\n      * apply plus_lt_le_compat; auto.\n        rewrite Nat.mul_1_l.\n        apply IHn.\n        - intros; apply Hf1; lia.\n        - intros; apply Hf1; lia.\n        - intros; apply Ha; lia.\n      * rewrite <- Nat.mul_add_distr_r.\n        replace q with (S (q-1)).\n        - rewrite power_S; apply mult_le_compat; auto.\n          ++ apply Ha; auto.\n          ++ apply power_mono_l; try lia.\n             generalize (Hf2 n); intros; lia.\n        - generalize (Hf2 0); intros; lia.\n  Qed.\n\n  Lemma power_decomp_is_digit n a f : \n           (forall i j, i < j < n -> f i < f j)\n        -> (forall i, i < n -> a i < p)\n        ->  forall i, i < n -> is_digit (∑ n (fun i => a i * power (f i) p)) p (f i) (a i).\n  Proof.\n    intros Hf Ha.\n    induction n as [ | n IHn ]; intros i Hi.\n    + lia.\n    + split; auto.\n      exists (∑ (n-i) (fun j => a (S i + j) * power (f (S i+j) - f i - 1) p)), \n             (∑ i (fun j => a j * power (f j) p)); split.\n      - replace (S n) with (S i + (n-i)) by lia.\n        rewrite msum_plus, msum_plus1; auto.\n        rewrite <- plus_assoc, plus_comm; f_equal.\n        rewrite Nat.mul_add_distr_r, plus_comm; f_equal.\n        rewrite <- mult_assoc, mult_comm, <- sum_0n_scal_l.\n        apply msum_ext.\n        intros j Hj.\n        rewrite (mult_comm (_ * _));\n        repeat rewrite <- mult_assoc; f_equal.\n        rewrite <- power_S, <- power_plus; f_equal.\n        generalize (Hf i (S i+j)); intros; lia.\n      - apply power_decomp_lt; auto.\n        * intros; apply Hf; lia.\n        * intros; apply Ha; lia.\n  Qed.\n\n  Theorem power_decomp_unique n f a b :\n            (forall i j, i < j < n -> f i < f j)\n         -> (forall i, i < n -> a i < p)\n         -> (forall i, i < n -> b i < p)\n         -> ∑ n (fun i => a i * power (f i) p)\n          = ∑ n (fun i => b i * power (f i) p)\n         -> forall i, i < n -> a i = b i.\n  Proof.\n    intros Hf Ha Hb E i Hi.\n    generalize (power_decomp_is_digit _ _ Hf Ha Hi)\n               (power_decomp_is_digit _ _ Hf Hb Hi).\n    rewrite E; apply is_digit_fun.\n  Qed.\n\nEnd power_decomp.\n\nSection power_decomp_uniq.\n\n  Variable (p : nat) (Hp : 2 <= p).\n\n  Theorem power_decomp_factor n f a : \n           (forall i, 0 < i < S n -> f 0 < f i)\n        -> ∑ (S n) (fun i => a i * power (f i) p) \n         = ∑ n (fun i => a (S i) * power (f (S i) - f 0 - 1) p) * power (S (f 0)) p\n         + a 0 * power (f 0) p.\n  Proof.\n    intros Hf.\n    rewrite msum_S, plus_comm; f_equal.\n    rewrite <- sum_0n_scal_r.\n    apply msum_ext.\n    intros i Hi.\n    rewrite <- mult_assoc; f_equal.\n    rewrite <- power_plus; f_equal.\n    generalize (Hf (S i)); intros; lia.\n  Qed.\n\n  Let power_nzero x : power x p <> 0.\n  Proof.\n    generalize (@power_ge_1 x p); lia.\n  Qed.\n\n  Let lt_minus_cancel a b c : a < b < c -> b - a - 1 < c - a - 1.\n  Proof. intros; lia. Qed. \n\n  (* Another proof of the above statement *)\n\n  Theorem power_decomp_unique' n f a b :\n            (forall i j, i < j < n -> f i < f j)\n         -> (forall i, i < n -> a i < p)\n         -> (forall i, i < n -> b i < p)\n         -> ∑ n (fun i => a i * power (f i) p)\n          = ∑ n (fun i => b i * power (f i) p)\n         -> forall i, i < n -> a i = b i.\n  Proof.\n    revert f a b.\n    induction n as [ | n IHn ]; intros f a b Hf Ha Hb.\n    + intros; lia.\n    + assert (forall i, 0 < i < S n -> f 0 < f i)\n        by (intros; apply Hf; lia). \n      do 2 (rewrite power_decomp_factor; auto).\n      intros E.\n      apply div_rem_uniq in E; auto.\n      * destruct E as (E1 & E2).\n        intros [ | i ] Hi.\n        - revert E2; rewrite Nat.mul_cancel_r; auto.\n        - apply IHn with (4 := E1); try lia.\n          ++ intros u j Hu; apply lt_minus_cancel; split; apply Hf; lia. \n          ++ intros; apply Ha; lia.\n          ++ intros; apply Hb; lia.\n      * rewrite power_S.\n        apply Nat.mul_lt_mono_pos_r.\n        - apply power_ge_1; lia.\n        - apply Ha; lia.\n      * rewrite power_S.\n        apply Nat.mul_lt_mono_pos_r.\n        - apply power_ge_1; lia.\n        - apply Hb; lia.\n  Qed.\n\nEnd power_decomp_uniq.\n\nFact mult_2_eq_plus x : x + x = 2 *x.\nProof. ring. Qed.\n\nSection power_injective.\n\n  Let power_2_inj_1 i j n : j < i -> 2* power n 2 <> power i 2 + power j 2.\n  Proof.\n    rewrite <- power_S; intros H4 E.\n     generalize (@power_ge_1 j 2); intro C.\n     destruct (lt_eq_lt_dec i (S n)) as [ [ H5 | H5 ] | H5 ].\n     + apply power_mono_l with (x := 2) in H5; auto.\n       rewrite power_S in H5.\n       apply power_mono_l with (x := 2) in H4; auto.\n       rewrite power_S in H4; lia.\n     + subst i; lia.\n     + apply power_mono_l with (x := 2) in H5; auto.\n      rewrite power_S in H5; lia.\n  Qed.\n\n  Fact power_2_inj i j : power i 2 = power j 2 -> i = j.\n  Proof.\n    intros H.\n    destruct (lt_eq_lt_dec i j) as [ [ C | C ] | C ]; auto;\n      apply power_smono_l with (x := 2) in C; lia.\n  Qed.\n\n  Let power_plus_lt a b c : a < b < c -> power a 2 + power b 2 < power c 2.\n  Proof.\n    intros [ H1 H2 ].\n    apply power_mono_l with (x := 2) in H2; auto.\n    apply power_smono_l with (x := 2) in H1; auto.\n    rewrite power_S in H2; lia.\n  Qed.\n\n  Let power_inj_2 i1 j1 i2 j2 : \n             j1 < i1 \n          -> j2 < i2 \n          -> power i1 2 + power j1 2 = power i2 2 + power j2 2\n          -> i1 = i2 /\\ j1 = j2.\n  Proof.\n    intros H1 H2 H3.\n    destruct (lt_eq_lt_dec i1 i2) as [ [ C | C ] | C ].\n    + generalize (@power_plus_lt j1 i1 i2); intros; lia.\n    + split; auto; apply power_2_inj; subst; lia.\n    + generalize (@power_plus_lt j2 i2 i1); intros; lia.\n  Qed.\n\n  Theorem sum_2_power_2_injective i1 j1 i2 j2 :\n              j1 <= i1 \n           -> j2 <= i2 \n           -> power i1 2 + power j1 2 = power i2 2 + power j2 2 \n           -> i1 = i2 /\\ j1 = j2.\n  Proof.\n    intros H1 H2 E.\n    destruct (eq_nat_dec i1 j1) as [ H3 | H3 ];\n    destruct (eq_nat_dec i2 j2) as [ H4 | H4 ].\n    + subst j1 j2.\n      assert (i1 = i2); auto.\n      do 2 rewrite mult_2_eq_plus, <- power_S in E.\n      apply power_2_inj in E; lia.\n    + subst j1; rewrite mult_2_eq_plus in E.\n      apply power_2_inj_1 in E; lia.\n    + subst j2; symmetry in E.\n      rewrite mult_2_eq_plus in E.\n      apply power_2_inj_1 in E; lia.\n    + revert E; apply power_inj_2; lia.\n  Qed. \n \nEnd power_injective.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/Shared/Libs/DLW/Utils/power_decomp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7296904509306633}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (z : natural) (x : natural) : natural :=\n  plus lf2 (mult z (plus x Zero)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj192_coqofml_F1pk8I.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7296904434938375}}
{"text": "Require Import rt.util.tactics rt.util.notation rt.util.sorting rt.util.nat.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop path.\n\n(* Lemmas about arithmetic with sums. *)\nSection SumArithmetic.\n\n  (* Inequality with sums is monotonic with their functions. *)\n  Lemma sum_diff_monotonic :\n    forall n G F,\n      (forall i : nat, i < n -> G i <= F i) ->\n      (\\sum_(0 <= i < n) (G i)) <= (\\sum_(0 <= i < n) (F i)).\n  Proof.\n    intros n G F ALL.\n    rewrite big_nat_cond [\\sum_(0 <= i < n) F i]big_nat_cond.\n    apply leq_sum; intros i LT; rewrite andbT in LT.\n    move: LT => /andP LT; des.\n    by apply ALL, leq_trans with (n := n); ins.\n  Qed.\n\n  Lemma sum_diff :\n    forall n F G,\n      (forall i (LT: i < n), F i >= G i) ->\n      \\sum_(0 <= i < n) (F i - G i) =\n        (\\sum_(0 <= i < n) (F i)) - (\\sum_(0 <= i < n) (G i)).       \n  Proof.\n    intros n F G ALL.\n    induction n; ins; first by rewrite 3?big_geq.\n    assert (ALL': forall i, i < n -> G i <= F i).\n      by ins; apply ALL, leq_trans with (n := n); ins.\n    rewrite 3?big_nat_recr // IHn //; simpl.\n    rewrite subh1; last by apply sum_diff_monotonic.\n    rewrite subh2 //; try apply sum_diff_monotonic; ins.\n    rewrite subh1; ins; apply sum_diff_monotonic; ins.\n    by apply ALL; rewrite ltnS leqnn. \n  Qed.\n\n  Lemma telescoping_sum :\n    forall (T: Type) (F: T->nat) r (x0: T),\n    (forall i, i < (size r).-1 -> F (nth x0 r i) <= F (nth x0 r i.+1)) ->\n      F (nth x0 r (size r).-1) - F (nth x0 r 0) =\n        \\sum_(0 <= i < (size r).-1) (F (nth x0 r (i.+1)) - F (nth x0 r i)).\n  Proof.\n    intros T F r x0 ALL.\n    have ADD1 := big_add1.\n    have RECL := big_nat_recl.\n    specialize (ADD1 nat 0 addn 0 (size r) (fun x => true) (fun i => F (nth x0 r i))).\n    specialize (RECL nat 0 addn (size r).-1 0 (fun i => F (nth x0 r i))).\n    rewrite sum_diff; last by ins.\n    rewrite addmovr; last by rewrite -[_.-1]add0n; apply prev_le_next; try rewrite add0n leqnn.\n    rewrite subh1; last by apply sum_diff_monotonic.\n    rewrite addnC -RECL //.\n    rewrite addmovl; last by rewrite big_nat_recr // -{1}[\\sum_(_ <= _ < _) _]addn0; apply leq_add.\n    by rewrite addnC -big_nat_recr.\n  Qed.\n\n  Lemma leq_sum_sub_uniq :\n    forall (T: eqType) (r1 r2: seq T) F,\n      uniq r1 ->\n      {subset r1 <= r2} ->\n      \\sum_(i <- r1) F i <= \\sum_(i <- r2) F i.\n  Proof.\n    intros T r1 r2 F UNIQ SUB; generalize dependent r2.\n    induction r1 as [| x r1' IH]; first by ins; rewrite big_nil.\n    {\n      intros r2 SUB.\n      assert (IN: x \\in r2).\n        by apply SUB; rewrite in_cons eq_refl orTb.\n      simpl in UNIQ; move: UNIQ => /andP [NOTIN UNIQ]; specialize (IH UNIQ).\n      destruct (splitPr IN).\n      rewrite big_cat 2!big_cons /= addnA [_ + F x]addnC -addnA leq_add2l.\n      rewrite mem_cat in_cons eq_refl in IN.\n      rewrite -big_cat /=.\n      apply IH; red; intros x0 IN0.\n      rewrite mem_cat.\n      feed (SUB x0); first by rewrite in_cons IN0 orbT.\n      rewrite mem_cat in_cons in SUB.\n      move: SUB => /orP [SUB1 | /orP [/eqP EQx | SUB2]];\n        [by rewrite SUB1 | | by rewrite SUB2 orbT].\n      by rewrite -EQx IN0 in NOTIN.\n    }\n  Qed.\n    \nEnd SumArithmetic.\n\n(* Additional lemmas about sum. *)\nSection ExtraLemmas.\n  \n  Lemma extend_sum :\n    forall t1 t2 t1' t2' F,\n      t1' <= t1 ->\n      t2 <= t2' ->\n      \\sum_(t1 <= t < t2) F t <= \\sum_(t1' <= t < t2') F t.\n  Proof.\n    intros t1 t2 t1' t2' F LE1 LE2.\n    destruct (t1 <= t2) eqn:LE12;\n      last by apply negbT in LE12; rewrite -ltnNge in LE12; rewrite big_geq // ltnW.\n    rewrite -> big_cat_nat with (m := t1') (n := t1); try (by done); simpl;\n      last by apply leq_trans with (n := t2).\n    rewrite -> big_cat_nat with (p := t2') (n := t2); try (by done); simpl.\n    by rewrite addnC -addnA; apply leq_addr.\n  Qed.\n\n  Lemma leq_sum_nat m n (P : pred nat) (E1 E2 : nat -> nat) :\n    (forall i, m <= i < n -> P i -> E1 i <= E2 i) ->\n    \\sum_(m <= i < n | P i) E1 i <= \\sum_(m <= i < n | P i) E2 i.\n  Proof.\n    intros LE.\n    rewrite big_nat_cond [\\sum_(_ <= _ < _| P _)_]big_nat_cond.\n    by apply leq_sum; move => j /andP [IN H]; apply LE.\n  Qed.\n\n  Lemma leq_sum_seq (I: eqType) (r: seq I) (P : pred I) (E1 E2 : I -> nat) :\n    (forall i, i \\in r -> P i -> E1 i <= E2 i) ->\n    \\sum_(i <- r | P i) E1 i <= \\sum_(i <- r | P i) E2 i.\n  Proof.\n    intros LE.\n    rewrite big_seq_cond [\\sum_(_ <- _| P _)_]big_seq_cond.\n    by apply leq_sum; move => j /andP [IN H]; apply LE.\n  Qed.\n\n  Lemma sum_nat_eq0_nat (T : eqType) (F : T -> nat) (r: seq T) :\n    all (fun x => F x == 0) r = (\\sum_(i <- r) F i == 0).\n  Proof.\n    destruct (all (fun x => F x == 0) r) eqn:ZERO.\n    {\n      move: ZERO => /allP ZERO; rewrite -leqn0.\n      rewrite big_seq_cond (eq_bigr (fun x => 0));\n        first by rewrite big_const_seq iter_addn mul0n addn0 leqnn.\n      intro i; rewrite andbT; intros IN.\n      specialize (ZERO i); rewrite IN in ZERO.\n      by move: ZERO => /implyP ZERO; apply/eqP; apply ZERO.\n    }\n    {\n      apply negbT in ZERO; rewrite -has_predC in ZERO.\n      move: ZERO => /hasP ZERO; destruct ZERO as [x IN NEQ]; simpl in NEQ.\n      rewrite (big_rem x) /=; last by done.\n      symmetry; apply negbTE; rewrite neq_ltn; apply/orP; right.\n      apply leq_trans with (n := F x); last by apply leq_addr.\n      by rewrite lt0n.\n    }\n  Qed.\n  \n  Lemma leq_sum1_smaller_range m n (P Q: pred nat) a b:\n    (forall i, m <= i < n /\\ P i -> a <= i < b /\\ Q i) ->\n    \\sum_(m <= i < n | P i) 1 <= \\sum_(a <= i < b | Q i) 1.\n  Proof.\n    intros REDUCE.\n    rewrite big_mkcond.\n    apply leq_trans with (n := \\sum_(a <= i < b | Q i) \\sum_(m <= i' < n | i' == i) 1).\n    {\n      rewrite (exchange_big_dep (fun x => true)); [simpl | by done].\n      apply leq_sum_nat; intros i LE _.\n      case TRUE: (P i); last by done.\n      move: (REDUCE i (conj LE TRUE)) => [LE' TRUE'].\n      rewrite (big_rem i); last by rewrite mem_index_iota.\n      by rewrite TRUE' eq_refl.\n    }\n    {\n      apply leq_sum_nat; intros i LE TRUE.\n      rewrite big_mkcond /=.\n      destruct (m <= i < n) eqn:LE'; last first.\n      {\n        rewrite big_nat_cond big1; first by done.\n        move => i' /andP [LE'' _]; case EQ: (_ == _); last by done.\n        by move: EQ => /eqP EQ; subst; rewrite LE'' in LE'.\n      }\n      rewrite (bigD1_seq i) /=; [ | by rewrite mem_index_iota | by rewrite iota_uniq ].\n      rewrite eq_refl big1; first by done.\n      by move => i' /negbTE NEQ; rewrite NEQ.\n    }\n  Qed.\n\nEnd ExtraLemmas.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/util/sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.7295833698138423}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\n(** Some usual integrals *)\n\n\nRequire Import Reals.\nRequire Import MyRfunctions.\nRequire Import Rintegral.\n\nOpen Scope R_scope.\n\nLemma Rint_inv a b : \n  0 < a <= b -> Rint (fun x => /x) a b (ln b - ln a).\nintros a b Hab.\napply Rint_derive.\n  intuition.\nintros x Hx.\n  apply derivable_pt_lim_ln.\n  apply Rlt_le_trans with a; intuition.\n  intros x Hx.\n  apply continuity_pt_inv.\n  apply derivable_continuous, derivable_id.\n  assert( 0 < x).\n  apply Rlt_le_trans with a; tauto.\n  auto with *.\nQed.\nHint Resolve Rint_inv : Rint.\n\nLemma Rint_exp a b : Rint exp a b (exp b - exp a).\nProof.\nintros a b.\napply Rint_derive2.\nintros; apply derivable_pt_lim_exp.\nintros; apply derivable_continuous_pt, derivable_pt_exp.\nQed.\nHint Resolve Rint_exp : Rint.\n\nLemma Rint_pow_pos n a b : \n  Rint (fun y : R => INR n * y ^ (pred n)) a b ((b ^ n - a ^ n)).\nProof.\nintros n a b.\ndestruct n.\n  replace (b ^ 0 - a ^ 0) with (0 * (b - a)) by ring.\n  apply Rint_eq_compat with (fct_cte 0).\n  unfold fct_cte; auto with *.\n  apply Rint_constant.\napply Rint_derive2 with (f := fun x => x ^ (S n)); intros.\napply derivable_pt_lim_pow_pos; omega.\napply continuity_pt_mult.\napply continuity_pt_const; intros u v ; reflexivity.\n\n  induction n.\n  apply continuity_pt_const; intros u v ; reflexivity.\n  simpl.\n  apply continuity_pt_mult.\n\nauto with Rcont.\nauto with Rcont.\nQed.\nHint Resolve Rint_pow_pos : Rint.\n\nLemma Rint_cos a b : \n  Rint cos a b (sin b - sin a).\nintros a b.\napply Rint_derive2.\nintros; apply derivable_pt_lim_sin.\nintros; apply continuity_cos.\nQed.\nHint Resolve Rint_cos : Rint.\n\nLemma Rint_sin a b : \n  Rint sin a b (cos a - cos b).\nintros a b.\nreplace (cos a - cos b) with (- cos b - -cos a) by ring.\napply Rint_derive2 with (f := (-cos)%F).\nintros; replace (sin x) with (--sin x) by ring; \n  apply derivable_pt_lim_opp, derivable_pt_lim_cos.\nintros; apply continuity_sin.\nQed.\nHint Resolve Rint_sin : Rint.\n\nLemma Rint_sqrt_inv a b : 0 < a -> 0 < b ->\n  Rint (fun x => /(sqrt x)) a b (2 *( sqrt b - sqrt a)).\nProof.\nintros a b Ha Hb.\nassert(Hneq : forall x, Rmin a b <= x <= Rmax a b -> 0 < sqrt x).\n  intros; \n    apply sqrt_lt_R0.\n    apply Rlt_le_trans with (Rmin a b).\n    apply Rmin_pos; assumption.\n    intuition.\napply Rint_eq_compat with (fun x => 2 * /(2 * sqrt x)).\n  intros; field.\n  auto with *.\napply Rint_scalar_mult_compat_l.\napply Rint_derive2.\nintros; apply derivable_pt_lim_sqrt.\n  apply Rlt_le_trans with (Rmin a b).\n  apply Rmin_pos; assumption.\n  intuition.\nintros.\napply continuity_pt_inv.\n  apply continuity_pt_mult.\n  apply continuity_pt_constant.\n  apply continuity_pt_sqrt.\n  apply Rle_trans with (Rmin a b).\n  apply Rmin_ge; intuition.\n  intuition.\nassert( 0 < 2 * sqrt x).\napply Rmult_lt_0_compat.\n  auto with *.\n  auto.\nauto with *.\nQed.\nHint Resolve Rint_sqrt_inv : Rint.\n\n(* cosh sinh  *)\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/rls/rls1/Reals/Rintegral_usual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7295833634769976}}
{"text": "(** * Rel: Properties of Relations *)\n\n(* $Date: 2013-04-01 09:15:45 -0400 (Mon, 01 Apr 2013) $ *)\n\nRequire Export DmoonTactics.\nRequire Export SfLib.\n\n(** A (binary) _relation_ is just a parameterized proposition. As you know\n    from your undergraduate discrete math course, there are a lot of\n    ways of discussing and describing relations _in general_ -- ways\n    of classifying relations (are they reflexive, transitive, etc.),\n    theorems that can be proved generically about classes of\n    relations, constructions that build one relation from another,\n    etc.  Let us pause here to review a few that will be useful in\n    what follows. *)\n\n(** A (binary) relation _on_ a set [X] is a proposition parameterized by two\n    [X]s -- i.e., it is a logical assertion involving two values from\n    the set [X].  *)\n\nDefinition relation (X: Type) := X->X->Prop.\n\n(** Somewhat confusingly, the Coq standard library hijacks the generic\n    term \"relation\" for this specific instance. To maintain\n    consistency with the library, we will do the same.  So, henceforth\n    the Coq identifier [relation] will always refer to a binary\n    relation between some set and itself, while the English word\n    \"relation\" can refer either to the specific Coq concept or the\n    more general concept of a relation between any number of possibly\n    different sets.  The context of the discussion should always make\n    clear which is meant. *)\n\n(** An example relation on [nat] is [le], the less-that-or-equal-to\n    relation which we usually write like this [n1 <= n2]. *)\n\nPrint le.\n(* ====>\nInductive le (n : nat) : nat -> Prop :=\n    le_n : n <= n\n  | le_S : forall m : nat, n <= m -> n <= S m\n*)\nCheck le : nat -> nat -> Prop.\nCheck le : relation nat.\n\nCheck le_ind.\n\n(* My addition: playing with propositions and induction. *)\n\nLemma one_le_three : 1 <= 3.\nProof.\n  assert (H12 : 1 <= 2).\n    assert (H11 : 1 <= 1).\n      apply le_n.\n    apply le_S in H11.\n    apply H11.\n  apply le_S in H12.\n  apply H12.\nDefined.\n\nEval compute in  one_le_three.\n\nDefinition evidence_one_le_three : 1 <= 3 := le_S 1 2 (le_S 1 1 (le_n 1)).\n\nDefinition evidence_two_le_five : 2 <= 5 := le_S 2 4 (le_S 2 3 (le_S 2 2 (le_n 2))).\n\n(* ######################################################### *)\n(** * Basic Properties of Relations *)\n\n(** A relation [R] on a set [X] is a _partial function_ if, for every\n    [x], there is at most one [y] such that [R x y] -- i.e., if [R x\n    y1] and [R x y2] together imply [y1 = y2]. *)\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2. \n\n(** For example, the [next_nat] relation defined in Logic.v is a\n    partial function. *)\n\nPrint next_nat.\n(* ====>\nInductive next_nat (n : nat) : nat -> Prop := \n  nn : next_nat n (S n)\n*)\nCheck next_nat : relation nat.\n\nTheorem next_nat_partial_function : \n   partial_function next_nat.\nProof. \n  unfold partial_function.\n  intros x y1 y2 H1 H2.\n  inversion H1. inversion H2.\n  reflexivity.  Qed. \n\n(** However, the [<=] relation on numbers is not a partial function.\n\n    This can be shown by contradiction.  In short: Assume, for a\n    contradiction, that [<=] is a partial function.  But then, since\n    [0 <= 0] and [0 <= 1], it follows that [0 = 1].  This is nonsense,\n    so our assumption was contradictory. *)\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense.\n   Case \"Proof of assertion\".\n   apply Hc with (x := 0). \n     apply le_n. \n     apply le_S. apply le_n. \n  inversion Nonsense.   Qed.\n\n(** **** Exercise: 2 stars, optional *)\n(** Show that the [total_relation] defined in Logic.v is not a partial\n    function. *)\n\nInductive total_relation (m n : nat) : Prop := R_total : total_relation m n.\n\nTheorem total_relation_not_partial_function : \n  ~ (partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros.\n  assert (H' : 0 = 1).\n    apply H with (x := 0); apply R_total.\n  inversion H'.\nQed.\n     \n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\n(** Show that the [empty_relation] defined in Logic.v is a partial\n    function. *)\n\nInductive empty_relation (m n : nat) : Prop := .\n\nTheorem empty_relation_partial_function : \n  partial_function empty_relation.\nProof.\n  unfold partial_function. intros.\n  inversion H.\nQed.\n\n(** [] *)\n\n(** A _reflexive_ relation on a set [X] is one for which every element\n    of [X] is related to itself. *)\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive :\n  reflexive le.\nProof. \n  unfold reflexive. intros n. apply le_n.  Qed.\n\n(** A relation [R] is _transitive_ if [R a c] holds whenever [R a b]\n    and [R b c] do. *)\n\nPrint eq.\n\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  Check le_ind.\n  Print le_ind.\n  Case \"le_n\". apply Hnm.\n  Case \"le_S\". apply le_S. apply IHHmo.  Qed.\n\nTheorem lt_trans:\n  transitive lt.\nProof. \n  unfold lt. unfold transitive. \n  intros n m o Hnm Hmo.\n  apply le_S in Hnm. \n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. Qed.\n\n(** **** Exercise: 2 stars, optional *)\n(** We can also prove [lt_trans] more laboriously by induction,\n    without using le_trans.  Do this.*)\n\nTheorem lt_trans' :\n  transitive lt.\nProof.\n  (* Prove this by induction on evidence that [m] is less than [o]. *)\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo; apply le_S; assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\n(** Prove the same thing again by induction on [o]. *)\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  Admitted.\n       \n(** [] *)\n\n(** The transitivity of [le], in turn, can be used to prove some facts\n    that will be useful later (e.g., for the proof of antisymmetry\n    below)... *)\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof. \n  intros n m H. apply le_trans with (S n).\n    apply le_S. apply le_n.\n    apply H.  Qed.\n\n(** **** Exercise: 1 star, optional *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  induction n.\n  - intros.\n    inversion H.\n    + apply le_n.\n    + cut (0 <= 1). intro H_zero_one.\n      apply (le_trans 0 1 m); assumption.\n      apply le_S. apply le_n.\n  - intros.\n    inversion H.\n    + apply le_n.\n    + cut (S n <= S (S n)). intro H_Sn_SSn.\n      apply (le_trans (S n) (S (S n)) m); assumption.\n      apply le_S. apply le_n.\nQed.\n    \n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_Sn_n_inf) *)\n(** Provide an informal proof of the following theorem:\n \n    Theorem: For every [n], [~(S n <= n)]\n \n    A formal proof of this is an optional exercise below, but try\n    the informal proof without doing the formal proof first.\n \n    Proof:\n    (* FILL IN HERE *)\n    []\n *)\n\n(** **** Exercise: 1 star, optional *)\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n  unfold not.\n  intros.\n  induction n.\n  - inversion H.\n  - apply IHn.\n    inversion H.\n    + assumption.\n    + apply le_Sn_le.\n      assumption.\nQed.\n    \n(** [] *)\n\n(** Reflexivity and transitivity are the main concepts we'll need for\n    later chapters, but, for a bit of additional practice working with\n    relations in Coq, here are a few more common ones.\n\n   A relation [R] is _symmetric_ if [R a b] implies [R b a]. *)\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  unfold not.\n  unfold symmetric.\n  intros.\n  assert (H' : 0 <= 1). auto.\n  invert_term (H 0 1 H').\nQed.\n(** [] *)\n\n(** A relation [R] is _antisymmetric_ if [R a b] and [R b a] together\n    imply [a = b] -- that is, if the only \"cycles\" in [R] are trivial\n    ones. *)\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  unfold antisymmetric.\n  intros a b H. \n  induction H.\n  - reflexivity.\n  - intros.\n    exfalso.\n    apply le_Sn_n with (n := m).\n    apply le_trans with (a := S m) (b := a) (c := m); assumption.\nQed.    \n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_step : forall n m p,\n  n < m ->\n  m <= S p ->\n  n <= p.\nProof. \n  intros n m p Hnm HmSp.\n  unfold lt in *.\n  invert_term (le_trans (S n) m (S p) Hnm HmSp).\n  - apply le_n.\n  - apply le_S_n.\n    apply le_trans with (a := S n) (b := m) (c := S p); assumption.\nQed.    \n  \n(** [] *)\n\n(** A relation is an _equivalence_ if it's reflexive, symmetric, and\n    transitive.  *)\n\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(** A relation is a _partial order_ when it's reflexive,\n    _anti_-symmetric, and transitive.  In the Coq standard library\n    it's called just \"order\" for short. *)\n\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\n(** A preorder is almost like a partial order, but doesn't have to be\n    antisymmetric. *)\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split. \n    Case \"refl\". apply le_reflexive.\n    split. \n      Case \"antisym\". apply le_antisymmetric. \n      Case \"transitive.\". apply le_trans.  Qed.\n\n(* ########################################################### *)\n(** * Reflexive, Transitive Closure *)\n\n(** The _reflexive, transitive closure_ of a relation [R] is the\n    smallest relation that contains [R] and that is both reflexive and\n    transitive.  Formally, it is defined like this in the Relations\n    module of the Coq standard library: *)\n\nInductive clos_refl_trans {A: Type} (R: relation A) : relation A :=\n    | rt_step : forall x y, R x y -> clos_refl_trans R x y\n    | rt_refl : forall x, clos_refl_trans R x x\n    | rt_trans : forall x y z,\n          clos_refl_trans R x y ->\n          clos_refl_trans R y z ->\n          clos_refl_trans R x z.\n\n(** For example, the reflexive and transitive closure of the\n    [next_nat] relation coincides with the [le] relation. *)\n\nTheorem next_nat_closure_is_le : forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m. split.\n    Case \"->\".\n      intro H. induction H.\n      SCase \"le_n\". apply rt_refl.\n      SCase \"le_S\".\n        apply rt_trans with m. apply IHle. apply rt_step. apply nn.\n    Case \"<-\".\n      intro H. induction H.\n      SCase \"rt_step\". inversion H. apply le_S. apply le_n.\n      SCase \"rt_refl\". apply le_n.\n      SCase \"rt_trans\".\n        apply le_trans with y.\n        apply IHclos_refl_trans1.\n        apply IHclos_refl_trans2. Qed.\n\n(** The above definition of reflexive, transitive closure is\n    natural -- it says, explicitly, that the reflexive and transitive\n    closure of [R] is the least relation that includes [R] and that is\n    closed under rules of reflexivity and transitivity.  But it turns\n    out that this definition is not very convenient for doing\n    proofs -- the \"nondeterminism\" of the [rt_trans] rule can sometimes\n    lead to tricky inductions.\n \n    Here is a more useful definition... *)\n\nInductive refl_step_closure {X:Type} (R: relation X) : relation X :=\n  | rsc_refl  : forall (x : X), refl_step_closure R x x\n  | rsc_step : forall (x y z : X),\n                    R x y ->\n                    refl_step_closure R y z ->\n                    refl_step_closure R x z.\n\n(** (Note that, aside from the naming of the constructors, this\n    definition is the same as the [multi] step relation used in many\n    other chapters.) *)\n\n(** (The following [Tactic Notation] definitions are explained in\n    Imp.v.  You can ignore them if you haven't read that chapter\n    yet.) *)\n\nTactic Notation \"rt_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"rt_step\" | Case_aux c \"rt_refl\" \n  | Case_aux c \"rt_trans\" ].\n\nTactic Notation \"rsc_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"rsc_refl\" | Case_aux c \"rsc_step\" ].\n\n(** Our new definition of reflexive, transitive closure \"bundles\"\n    the [rt_step] and [rt_trans] rules into the single rule step.\n    The left-hand premise of this step is a single use of [R],\n    leading to a much simpler induction principle.\n \n    Before we go on, we should check that the two definitions do\n    indeed define the same relation...\n    \n    First, we prove two lemmas showing that [refl_step_closure] mimics\n    the behavior of the two \"missing\" [clos_refl_trans]\n    constructors.  *)\n\nTheorem rsc_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> refl_step_closure R x y.\nProof.\n  intros X R x y H.\n  apply rsc_step with y. apply H. apply rsc_refl.   Qed.\n\n(** **** Exercise: 2 stars, optional (rsc_trans) *)\nTheorem rsc_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      refl_step_closure R x y  ->\n      refl_step_closure R y z ->\n      refl_step_closure R x z.\nProof.\n  intros. generalize dependent z.\n  induction H.\n  - intros. assumption.\n  - intros.\n    apply rsc_step with y.\n    + assumption.\n    + apply IHrefl_step_closure.\n      assumption.\nQed.\n\n(** [] *)\n\n(** Then we use these facts to prove that the two definitions of\n    reflexive, transitive closure do indeed define the same\n    relation. *)\n\n(** **** Exercise: 3 stars, optional (rtc_rsc_coincide) *)\nTheorem rtc_rsc_coincide : \n         forall (X:Type) (R: relation X) (x y : X),\n  clos_refl_trans R x y <-> refl_step_closure R x y.\nProof.\n  split.\n  - intros. induction H.\n    + apply rsc_R. assumption.\n    + apply rsc_refl.\n    + apply rsc_trans with y; assumption.\n  - intros. induction H.\n    + apply rt_refl.\n    + apply rt_trans with y.\n      * apply rt_step. assumption.\n      * assumption.\nQed.\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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.729583354765225}}
{"text": "Inductive bool : Type :=\n|true\n|false.\n\nDefinition negb (b:bool) : bool := \n    match b with\n    | true => false\n    | false => true\n    end.\n\nDefinition andb (b1 b2:bool) : bool :=\n    match b1 with\n    | true => b2\n    | false => false\n    end.\n\nDefinition orb (b1 b2:bool) : bool :=\nmatch b1 with\n| true => true\n| false => b2\nend.\n\nExample text_orb1: (orb true false) = true.\nProof. 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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition negb' (b: bool ): bool :=\n    if b then false else true.\nDefinition andb' (b1 b2: bool ): bool :=\n    if b1 then b2 else false.\nDefinition orb' (b1 b2: bool ): bool :=\n    if b1 then true else b2.\n", "meta": {"author": "ayushpandey8439", "repo": "CoqProofs", "sha": "a5e7c8ed86eed738a1b70a6a047a5408fdaa6c7b", "save_path": "github-repos/coq/ayushpandey8439-CoqProofs", "path": "github-repos/coq/ayushpandey8439-CoqProofs/CoqProofs-a5e7c8ed86eed738a1b70a6a047a5408fdaa6c7b/booleans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7295833531782354}}
{"text": "Inductive bit : Type :=\n  | B0\n  | B1.\n\nInductive nybble : Type :=\n  | bits (b0 b1 b2 b3 : bit).\n\nCheck (bits B1 B0 B1 B0).\n(* ==> bits B1 B0 B1 B0 : nybble *)\n\nDefinition all_zero (nb : nybble) : bool :=\n  match nb with\n    | (bits B0 B0 B0 B0) => true\n    | (bits _ _ _ _) => false\n  end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\n(* ===> false : bool *)\nCompute (all_zero (bits B0 B0 B0 B0)).\n(* ===> true : bool *)\n\nExample test_bits1:  (all_zero (bits B1 B0 B1 B0))  = false.\nProof. simpl. reflexivity.  Qed.\n\nExample test_bits2:  (all_zero (bits B0 B0 B0 B0))  = true.\nProof. simpl. reflexivity.  Qed.", "meta": {"author": "TysonSir", "repo": "coq", "sha": "3d5cd319a377acbdad1bec34061d298043c9bc18", "save_path": "github-repos/coq/TysonSir-coq", "path": "github-repos/coq/TysonSir-coq/coq-3d5cd319a377acbdad1bec34061d298043c9bc18/week2/demo_2_bits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8688267745399465, "lm_q1q2_score": 0.7295833476348853}}
{"text": "Require Arith.\nRequire Bool.\nRequire Compare_dec.\n\nInductive maxn (f:nat->nat):nat->nat->Prop :=\n  maxnO: (maxn f O (f O))\n |maxnSg : forall n m:nat, (maxn f n m)->(ge m (f (S n)))->(maxn f (S n) m)\n |maxnSl : forall n m:nat, (maxn f n m) -> (le m (f (S n)))-> (maxn f (S n) (f (S n))).\n\nLemma nat_well_ordered : forall n m:nat, le n m \\/ ge n m.\n  induction n.\n  - intros. left. apply le_0_n.\n  - destruct m. right. apply le_0_n.\n    destruct (IHn m).\n    + left; apply le_n_S. assumption.\n    + right; apply le_n_S. assumption. Qed.\nLemma max_val : forall (f:nat->nat) (n:nat), exists m:nat, maxn f n m.\n  intros f; induction n.\n  - exists (f O). apply maxnO.\n  - destruct IHn as [m]; destruct (nat_well_ordered m (f (S n))).\n    * exists (f (S n)). eapply maxnSl. eassumption. assumption.\n    * exists m. eapply maxnSg. assumption. assumption. Qed.\n\nExtraction Language Ocaml.\nExtraction \"maxv\" max_val.", "meta": {"author": "shij-hsu", "repo": "coq", "sha": "335711e36628d93d5723d8617b250e90be578d83", "save_path": "github-repos/coq/shij-hsu-coq", "path": "github-repos/coq/shij-hsu-coq/coq-335711e36628d93d5723d8617b250e90be578d83/tac/extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7295636383595906}}
{"text": "(* Parte 2 de la tarea: Lógica intuicionista. *)\n\n(* Ejercicio 2a *)\nTheorem double_neg_impl: forall (a b : Prop), ~~(a -> b) -> ~~a -> ~~b.\nProof.\nunfold not.\nintros.\napply H; intro.\napply H0; intro.\napply H1.\napply H2.\ntrivial.\nQed.\n\n(* Ejercicio 2b *)\nTheorem impl_double_neg: forall (a b: Prop), (~~a -> ~~b) -> ~~(a -> b).\nProof.\nunfold not.\nintros.\napply H0.\nintro.\nexfalso.\napply H.\n+ intro.\n  apply H2.\n  trivial.\n+ intro.\n  apply H0.\n  intro.\n  trivial.\nQed.\n\n(* Ejercicio 2 *)\nTheorem impl_double_neg_iff: forall (a b: Prop), ~~(a -> b) <-> (~~a -> ~~b).\nProof.\nsplit.\n+ apply double_neg_impl.\n+ apply impl_double_neg.\nQed.\n\n", "meta": {"author": "victorz3", "repo": "Tarea3VF", "sha": "bfc5507760c435bae5358e4e70b14862e3f33ca1", "save_path": "github-repos/coq/victorz3-Tarea3VF", "path": "github-repos/coq/victorz3-Tarea3VF/Tarea3VF-bfc5507760c435bae5358e4e70b14862e3f33ca1/Props_LI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.729513527037217}}
{"text": "Require Import demo.\n\n(* Compute a list of pairs of factors that multiply to a number. For example,\n   factor_pairs 6 includes (1,6), (2,3), (3,2), and (6,1). *)\nFixpoint build_factor_pairs n d :=\n  match d with\n  | 0 => nil\n  | S d' => if n mod d =? 0\n            then cons (d, n / d) (build_factor_pairs n d')\n            else build_factor_pairs n d'\n  end.\n\nDefinition factor_pairs n := build_factor_pairs n n.\n\n(* This lemma asserts that every pair in factor_pairs indeed multiplies to the original number *)\nLemma build_factor_pairs_correct : forall n d pair,\n    In pair (build_factor_pairs n d) -> (fst pair * snd pair = n).\nProof.\n  intro n. intro d.\n  induction d.\n  - intro pair.\n    simpl.\n    intro contra.\n    contradiction.\n  - intro pair.\n    destruct pair.\n    simpl.\n    remember (divmod n d 0 d).\n    destruct p.\n    simpl.\n    destruct (eq_nat_dec d n3).\n    + subst.\n      rewrite <- minus_diag_reverse.\n      simpl.\n      intro H.\n      destruct H.\n      * inversion H.\n        subst.\n        pose proof (Nat.divmod_spec n n3 0 n3).\n        assert (n3 <= n3) by omega.\n        specialize (H0 H1).\n        rewrite <- Heqp in H0.\n        rewrite <- minus_diag_reverse in H0.\n        rewrite <- mult_n_O in H0.\n        rewrite <- plus_n_O in H0.\n        rewrite <- plus_n_O in H0.\n        rewrite <- plus_n_O in H0.\n        destruct H0.\n        symmetry.\n        assumption.\n      * apply IHd with (pair := (n0,n1)).\n        assumption.\n    + pose proof (Nat.divmod_spec n d 0 d).\n      assert (d <= d) by omega.\n      specialize (H H0).\n      rewrite <- Heqp in H.\n      destruct H.\n      replace (d - n3 =? 0) with false.\n      intro H2.\n      apply IHd with (pair := (n0,n1)).\n      assumption.\n      clear H IHd Heqp H0.\n      symmetry.\n      rewrite Nat.eqb_neq.\n      omega.\nQed.\n\nLemma build_factors_1 : forall n d, n >= d -> d >= 1 -> In (1, n) (build_factor_pairs n d).\nProof.\n  intro n. intro d.\n  induction d.\n  - omega.\n  - intro Hnd. intro Hd1.\n    simpl.\n    destruct d.\n    + simpl.\n      left.\n      replace (fst (Nat.divmod n 0 0 0)) with n.\n      reflexivity.\n\n      pose proof (Nat.divmod_spec n 0 0 0).\n      assert (0 <= 0) by omega.\n      specialize (H H0).\n      remember (divmod n 0 0 0).\n      destruct p.\n      simpl.\n      omega.\n\n    + destruct (S d - snd (divmod n (S d) 0 (S d)) =? 0).\n      * simpl.\n        right.\n        apply IHd.\n        omega.\n        omega.\n      * apply IHd.\n        omega.\n        omega.\nQed.\n\nLemma build_factors_first_step :\n  forall n, build_factor_pairs (S n) (S n) = cons (S n, 1) (build_factor_pairs (S n) n).\nProof.\n  intro n.\n  unfold build_factor_pairs.\n  replace (S n mod S n =? 0) with true.\n  replace (S n / S n) with 1.\n  reflexivity.\n\n  symmetry.\n  apply Nat.div_same.\n  omega.\n\n  symmetry.\n  rewrite Nat.eqb_eq.\n  apply Nat.mod_same.\n  omega.\nQed.\n  \nLemma factors_len_ge_2 : forall n, n > 1 -> In (n, 1) (factor_pairs n) /\\ In (1, n) (factor_pairs n).\nProof.\n  intro n.\n  destruct n; [omega |].\n  destruct n; [omega |].\n  intro Hgt.\n  unfold factor_pairs.\n  split.\n  - rewrite build_factors_first_step.\n    unfold In.\n    left.\n    reflexivity.\n  - apply build_factors_1.\n    omega.\n    omega.\nQed.\n    \nTheorem prime_or_composite : forall n, n > 1 -> prime n \\/ composite n.\nProof.\n  intro n.\n  intro greater.\n  remember (factor_pairs n).\n  unfold factor_pairs in Heql.\n  destruct n; [omega |].\n  rewrite build_factors_first_step in Heql.\n  destruct l.\n  inversion Heql.\n  inversion Heql.\n  destruct l.\n  pose proof (build_factors_1 (S n) n).\n  assert (In (1, S n) (build_factor_pairs (S n) n)).\n  apply H.\n  omega.\n  omega.\n  rewrite <- H1 in H2.\n  inversion H2.\n  destruct p0.\n  destruct (eq_nat_dec n0 1).\n  - left.\n    admit.\n  - right.\n    unfold composite.\n    exists n0.\n    exists n1.\n    split.\n    + pose proof (build_factor_pairs_correct (S n) n (n0, n1)).\n      simpl in H.\n      assert (n0 * n1 = S n).\n      apply H.\n      rewrite <- H1.\n      simpl.\n      left.\n      reflexivity.\n      \n  set (len := length factors).\n  \n\nDefinition \n", "meta": {"author": "goldfirere", "repo": "cs231", "sha": "127294cc0d7a3369b3bd437b49eef3660179b57d", "save_path": "github-repos/coq/goldfirere-cs231", "path": "github-repos/coq/goldfirere-cs231/cs231-127294cc0d7a3369b3bd437b49eef3660179b57d/21_coq/prime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7295135234032148}}
{"text": "Require Import prosa.util.tactics prosa.util.notation.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat.\n\nSection StepFunction.\n\n  Section Defs.\n\n    (* We say that a function f... *)\n    Variable f: nat -> nat.\n\n    (* ...is a step function iff the following holds. *)\n    Definition is_step_function :=\n      forall t, f (t + 1) <= f t + 1.\n\n  End Defs.\n\n  Section Lemmas.\n\n    (* Let f be any step function over natural numbers. *)\n    Variable f: nat -> nat.\n    Hypothesis H_step_function: is_step_function f.\n\n    (* In this section, we prove a result similar to the intermediate\n       value theorem for continuous functions. *)\n    Section ExistsIntermediateValue.\n\n      (* Consider any interval [x1, x2]. *)\n      Variable x1 x2: nat.\n      Hypothesis H_is_interval: x1 <= x2.\n\n      (* Let t be any value such that f x1 < y < f x2. *)\n      Variable y: nat.\n      Hypothesis H_between: f x1 <= y < f x2.\n\n      (* Then, we prove that there exists an intermediate point x_mid such that\n         f x_mid = y. *)\n      Lemma exists_intermediate_point:\n        exists x_mid, x1 <= x_mid < x2 /\\ f x_mid = y.\n      Proof.\n        rename H_is_interval into INT, H_step_function into STEP, H_between into BETWEEN.\n        move: x2 INT BETWEEN; clear x2.\n        suff DELTA:\n          forall delta,\n            f x1 <= y < f (x1 + delta) ->\n            exists x_mid, x1 <= x_mid < x1 + delta /\\ f x_mid = y.\n        { move => x2 LE /andP [GEy LTy].\n          exploit (DELTA (x2 - x1));\n            first by apply/andP; split; last by rewrite addnBA // addKn.\n            by rewrite addnBA // addKn.\n        }\n        induction delta.\n        { rewrite addn0; move => /andP [GE0 LT0].\n            by apply (leq_ltn_trans GE0) in LT0; rewrite ltnn in LT0.\n        }\n        { move => /andP [GT LT].\n          specialize (STEP (x1 + delta)); rewrite leq_eqVlt in STEP.\n          have LE: y <= f (x1 + delta).\n          { move: STEP => /orP [/eqP EQ | STEP];\n              first by rewrite !addn1 in EQ; rewrite addnS EQ ltnS in LT.\n            rewrite [X in _ < X]addn1 ltnS in STEP.\n            apply: (leq_trans _ STEP).\n              by rewrite addn1 -addnS ltnW.\n          } clear STEP LT.\n          rewrite leq_eqVlt in LE.\n          move: LE => /orP [/eqP EQy | LT].\n          { exists (x1 + delta); split; last by rewrite EQy.\n              by apply/andP; split; [by apply leq_addr | by rewrite addnS].\n          }\n          { feed (IHdelta); first by apply/andP; split.\n            move: IHdelta => [x_mid [/andP [GE0 LT0] EQ0]].\n            exists x_mid; split; last by done.\n            apply/andP; split; first by done.\n              by apply: (leq_trans LT0); rewrite addnS.\n          }  \n        }\n      Qed.\n\n    End ExistsIntermediateValue.\n\n  End Lemmas.\n\n  (* In this section, we prove an analogue of the intermediate\n     value theorem, but for predicates of natural numbers. *) \n  Section ExistsIntermediateValuePredicates. \n\n    (* Let P be any predicate on natural numbers. *)\n    Variable P : nat -> bool.\n\n    (* Consider a time interval [t1,t2] such that ... *)\n    Variables t1 t2 : nat.\n    Hypothesis H_t1_le_t2 : t1 <= t2.\n\n    (* ... P doesn't hold for t1 ... *)\n    Hypothesis H_not_P_at_t1 : ~~ P t1.\n\n    (* ... but holds for t2. *)\n    Hypothesis H_P_at_t2 : P t2.\n    \n    (* Then we prove that within time interval [t1,t2] there exists time \n       instant t such that t is the first time instant when P holds. *)\n    Lemma exists_first_intermediate_point:\n      exists t, (t1 < t <= t2) /\\ (forall x, t1 <= x < t -> ~~ P x) /\\ P t.\n    Proof.\n      have EX: exists x, P x && (t1 < x <= t2).\n      { exists t2.\n        apply/andP; split; first by done.\n        apply/andP; split; last by done.\n        move: H_t1_le_t2; rewrite leq_eqVlt; move => /orP [/eqP EQ | NEQ1]; last by done.\n          by exfalso; subst t2; move: H_not_P_at_t1 => /negP NPt1. \n      }\n      have MIN := ex_minnP EX.\n      move: MIN => [x /andP [Px /andP [LT1 LT2]] MIN]; clear EX.\n      exists x; repeat split; [ apply/andP; split | | ]; try done.\n      move => y /andP [NEQ1 NEQ2]; apply/negPn; intros Py.\n      feed (MIN y). \n      { apply/andP; split; first by done.\n        apply/andP; split.\n        - move: NEQ1. rewrite leq_eqVlt; move => /orP [/eqP EQ | NEQ1]; last by done.\n            by exfalso; subst y; move: H_not_P_at_t1 => /negP NPt1. \n        - by apply ltnW, leq_trans with x.\n      }\n        by move: NEQ2; rewrite ltnNge; move => /negP NEQ2.\n    Qed.\n    \n  End ExistsIntermediateValuePredicates.  \n\nEnd StepFunction.", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/util/step_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7294614499218928}}
{"text": "Require Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Axioms.\n\nSet Implicit Arguments.\n\n\nSection FOLDN.\n\n  Fixpoint fold_n {T} (f: T -> T) (n: nat) (t: T) : T :=\n    match n with\n    | O => t\n    | S m => f (fold_n f m t)\n    end.\n\n  Lemma fold_n_2 {T} :\n    forall f (t: T), f (f t) = fold_n f 2 t.\n  Proof. ss. Qed.\n\n  Lemma fold_n_one_out {T} :\n    forall f (t: T) n, f (fold_n f n t) = fold_n f (1 + n) t.\n  Proof.\n    i. depgen t. induction n; i; ss; clarify.\n  Qed.\n\n  Lemma fold_n_one_in {T} :\n    forall f (t: T) n, (fold_n f n (f t)) = fold_n f (1 + n) t.\n  Proof.\n    i. depgen t. induction n; i; ss; clarify. rewrite IHn. ss.\n  Qed.\n\n  Lemma fold_n_add {T} :\n    forall f (t: T) n1 n2, fold_n f (n2 + n1) t = fold_n f n2 (fold_n f n1 t).\n  Proof.\n    i. depgen t. depgen n1. induction n2; i; ss; clarify.\n    rewrite fold_n_one_out at 1.\n    rewrite fold_n_one_out. rewrite <- ! fold_n_one_in.\n    rewrite fold_n_one_out. rewrite <- fold_n_one_in.\n    eauto.\n  Qed.\n\n  Lemma fold_n_fix {T} :\n    forall f (t: T) n, (f t) = t -> fold_n f n t = t.\n  Proof.\n    i. depgen t. depgen n. induction n; i; ss; clarify.\n    rewrite IHn; auto.\n  Qed.\n\n  Lemma fold_n_prop\n        (T: Type) x\n        (f: T -> T)\n        (P: T -> T -> Prop)\n        (REFL: forall x, P x x)\n        (TRANS: forall a b c, P a b -> P b c -> P a c)\n        (IND: forall x y: T, P x y -> P (f x) (f y))\n        (BASE: forall x, P (f (f x)) (f x))\n    :\n      forall n, P (fold_n f (S n) x) (f x).\n  Proof.\n    induction n; ss.\n    eapply TRANS. 2: eauto. eapply BASE.\n  Qed.\n\n  Lemma fold_n_mon\n        (T: Type) (x y: T)\n        (f: T -> T)\n        (P: T -> T -> Prop)\n        (IND: forall x y: T, P x y -> P (f x) (f y))\n        (BASE: P x y)\n    :\n      forall n, P (fold_n f n x) (fold_n f n y).\n  Proof.\n    induction n; ss; clarify; eauto.\n  Qed.\n\n  Lemma fold_n_curry\n        (T1: Type) (T2: Type)\n        (d: T1 -> T2)\n        (p: T1)\n        f n\n    :\n      fold_n (fun d p => f (d p)) n d p = fold_n f n (d p).\n  Proof.\n    induction n; ss; clarify.\n    rewrite IHn. ss.\n  Qed.\n\n  Lemma fold_n_curry2\n        (T1: Type) (T2: Type)\n        (d: T1 -> T2)\n        (p: T1)\n        f n\n    :\n      fold_n (fun d p => f p (d p)) n d p = fold_n (f p) n (d p).\n  Proof.\n    rewrite <- fold_n_curry. induction n; ss; clarify.\n    rewrite IHn. ss.\n  Qed.\n\nEnd FOLDN.\n\n\nSection FIX.\n\n  Definition is_fix_point {T} {eq} {EQ: Equivalence eq} (f: T -> T) (t: T) :=\n    eq (f t) t.\n\n  Definition is_fix {T} {eq} {EQ: Equivalence eq} (f fp: T -> T) :=\n    forall t, is_fix_point f (fp t).\n\n  Lemma is_fix_alt {T}:\n    forall (f fp: T -> T) (FIX: is_fix f fp), (forall (t: T), (f (fp t)) = (fp t)).\n  Proof.\n    i. unfold is_fix in FIX. unfold is_fix_point in FIX. auto.\n  Qed.\n\n  Lemma is_fix_alt_eq {T} {eq} {EQ: Equivalence eq}:\n    forall (f fp: T -> T) (FIX: is_fix f fp), (forall (t: T), eq (f (fp t)) (fp t)).\n  Proof.\n    i. unfold is_fix in FIX. unfold is_fix_point in FIX. auto.\n  Qed.\n\n  Definition n_fix {T} {eq} {EQ: Equivalence eq} (f: T -> T) n :=\n    is_fix f (fold_n f n).\n\n  Lemma n_fix_fix {T}:\n    forall (f: T -> T) n (NFIX: n_fix f n),\n      (forall t, f (fold_n f n t) = fold_n f n t).\n  Proof.\n    i. unfold n_fix in NFIX. eapply is_fix_alt in NFIX. eapply NFIX.\n  Qed.\n\n  Lemma n_fix_fix_eq {T} {eq} {EQ: Equivalence eq}:\n    forall (f: T -> T) n (NFIX: n_fix f n),\n      (forall t, eq (f (fold_n f n t)) (fold_n f n t)).\n  Proof.\n    i. unfold n_fix in NFIX. eapply is_fix_alt_eq in NFIX. eapply NFIX.\n  Qed.\n\n  Lemma n_fix_m_fix {T}:\n    forall (f: T -> T) n (NFIX: n_fix f n),\n      (forall m t, (fold_n f m (fold_n f n t)) = fold_n f n t).\n  Proof.\n    i. depgen f. depgen n. depgen t. induction m; i; ss; clarify.\n    erewrite IHm; auto. apply n_fix_fix; auto.\n  Qed.\n\n  Lemma n_fix_m_fix_eq {T} {eq} {EQ: Equivalence eq}:\n    forall (f: T -> T) n (NFIX: n_fix f n),\n      (forall m t, eq (fold_n f m (fold_n f n t)) (fold_n f n t)).\n  Proof.\n    i. depgen f. depgen n. depgen t. induction m; i; ss; clarify.\n    { reflexivity. }\n    etransitivity.\n    2: eapply IHm; eauto.\n    rewrite <- fold_n_add. rewrite PeanoNat.Nat.add_comm. rewrite fold_n_add.\n    eapply n_fix_fix_eq; eauto.\n  Qed.\n\nEnd FIX.\n\n\n\nSection GFIX.\n\n  Variable K: Type.\n  Variable P: Type.\n\n  Definition GD := P -> K.\n\n  Definition local_update := K -> K.\n  Definition pointwise_update := P -> local_update.\n  Definition global_update := GD -> GD.\n\n  Definition mk_global (fs: pointwise_update) : global_update :=\n    fun (d: GD) => (fun p => (fs p) (d p)).\n\n  Lemma mk_global_fold_n_comm\n        (fs: pointwise_update)\n        n\n    :\n      mk_global (fun p => (fold_n (fs p) n)) = (fold_n (mk_global fs) n).\n  Proof.\n    depgen fs. induction n; i.\n    { ss. }\n    ss. unfold mk_global in *. ss.\n    extensionality d. extensionality p. f_equal.\n    specialize IHn with fs.\n    assert (A: (fun (d : GD) (p : P) => fold_n (fs p) n (d p)) d p = fold_n (fs p) n (d p)).\n    { ss. }\n    rewrite IHn in A. rewrite <- A. ss.\n  Qed.\n\n  Lemma g_n_fix:\n    forall (fs: pointwise_update) n (NFIX: forall p, @n_fix K eq eq_equivalence (fs p) n),\n      @n_fix GD eq eq_equivalence (mk_global fs) n.\n  Proof.\n    i. unfold n_fix in *. unfold is_fix in *. i. unfold is_fix_point in *. ii.\n    unfold mk_global. extensionality p. setoid_rewrite fold_n_curry2. rewrite ! NFIX. ss.\n  Qed.\n\nEnd GFIX.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/optimizer/FoldN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7294614330182232}}
{"text": "Require Import String.\n\nInductive nat :=\n| O : nat\n| S : nat -> nat\n.\n\nFixpoint plus n m :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\nTheorem plus_O_right : forall n, plus n O = n.\nProof.\n  intros. induction n.\n  + simpl. reflexivity.\n  + simpl. rewrite -> IHn. reflexivity.\nQed.\n\nInductive binaryTree :=\n| Leaf : bool -> binaryTree\n| Node : binaryTree -> binaryTree -> binaryTree\n.\n\nFixpoint insertRight b t :=\n  match t with\n  | Leaf b2 => Node (Leaf b2) (Leaf b)\n  | Node t1 t2 => Node t1 (insertRight b t2)\n  end.\n\nFixpoint tSize t :=\n  match t with\n  | Leaf _ => 1\n  | Node t1 t2 => tSize t1 + tSize t2\n  end.\n\nTheorem insertRight_length : forall b t, tSize (insertRight b t) = 1 + tSize t.\nProof.\n  intros. induction t.\n  + simpl. reflexivity.\n  + simpl. rewrite -> IHt2. simpl. rewrite plus_n_Sm. reflexivity.\nQed.\n\nInductive expr :=\n| Var : string -> expr\n| App : expr -> expr -> expr\n.\n\nFixpoint renameAllVars s e :=\n  match e with\n  | Var _ => Var s\n  | App e1 e2 => App (renameAllVars s e1) (renameAllVars s e2)\n  end.\n\nFixpoint nbVars e :=\n  match e with\n  | Var _ => 1\n  | App e1 e2 => nbVars e1 + nbVars e2\n  end.\n\nTheorem renameAllVars_nbVars : forall e, nbVars e = nbVars (renameAllVars \"foo\" e).\nProof.\n  intros. induction e.\n", "meta": {"author": "Ptival", "repo": "PeaCoq", "sha": "4d186879910a327455e7b7b239d58a9502145680", "save_path": "github-repos/coq/Ptival-PeaCoq", "path": "github-repos/coq/Ptival-PeaCoq/PeaCoq-4d186879910a327455e7b7b239d58a9502145680/web/coq/small-study.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7294499759554418}}
{"text": "Print nat.\n(*\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n*)\n\nInductive Tree (A : Type) : Type :=\n| Leaf : A -> Tree A\n| Node : Tree A -> Tree A -> Tree A.\n\nArguments Leaf {A} _.\nArguments Node {A} _ _.\n\nFixpoint label\n  {A : Type} (t : Tree A) (n : nat) : nat * Tree (A * nat) :=\nmatch t with\n| Leaf x => (n, Leaf (x, n))\n| Node l r =>\n    let (n', l') := label l n in\n    let (n'', r') := label r (S n') in\n      (n'', Node  l' r')\nend.\n\nDefinition lbl {A : Type} (t : Tree A) : Tree (A * nat) :=\n  snd (label t 0).\n\nCompute lbl (Node (Node (Leaf true) (Leaf true)) (Leaf false)).\n(* = Node (Node (Leaf (true, 0)) (Leaf (true, 1))) (Leaf (false, 2))\n   : Tree (bool * nat) *)\n\nFixpoint size {A : Type} (t : Tree A) : nat :=\nmatch t with\n| Leaf _ => 1\n| Node l r => size l + size r\nend.\n\nRequire Import Arith.\n\nTheorem label_size :\n  forall (A : Type) (t : Tree A) (n n' : nat) (t' : Tree (A * nat)),\n    label t n = (n', t') -> S n' = n + size t.\nProof.\n  induction t as [| l IHl r IHr]; intros.\n    rewrite <- plus_comm. cbn. inversion H. reflexivity.\n    cbn. intros.\n      case_eq (label l n); intros m1 t1 H1.\n      case_eq (label r (S m1)); intros m2 t2 H2.\n      cbn in H. rewrite H1, H2 in H. inversion H; subst.\n      rewrite (IHr _ _ _ H2), (IHl _ _ _ H1), plus_assoc. reflexivity.\nQed.", "meta": {"author": "wkolowski", "repo": "coq-mtl", "sha": "e3ecb0cf0378e62816d391783e7421d769aec26b", "save_path": "github-repos/coq/wkolowski-coq-mtl", "path": "github-repos/coq/wkolowski-coq-mtl/coq-mtl-e3ecb0cf0378e62816d391783e7421d769aec26b/Thesis/snippets/snippet1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7294499628009343}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Structures.OrdersFacts.\nRequire Import Omega.\n\nInductive qs_tree : list nat -> Type :=\n| qs_tree_base : qs_tree nil\n| qs_tree_step : forall ( x: nat) (xs: list nat), \n  qs_tree (filter (fun y => leb y  x) (xs)) -> \n  qs_tree (filter (fun y => negb (leb y x)) (xs)) -> \n    qs_tree (cons x xs).\n\n(*new definition of quicksort using invariant*)\n\nLemma qs_acc_inv_1_0'' : forall (l:list nat)(x: nat)(xs : list nat),\nqs_tree l -> l = cons x xs -> qs_tree (filter (fun y => leb y  x) xs).\nintros l x xs H.\ninversion H.\ncongruence.\nintro H3.\ninversion H3.\nrewrite H5 in H0.\nrewrite H6 in H0.\nexact H0.\nDefined.\n\nLemma qs_acc_inv_1_1'' : forall (l:list nat)(x: nat)(xs : list nat),\nqs_tree l -> l = cons x xs -> qs_tree (filter (fun y => negb (leb y x)) xs).\nintros l x xs H.\ninversion H.\ncongruence.\nintro H3.\ninversion H3.\nrewrite H5 in H1.\nrewrite H6 in H1.\nexact H1.\nDefined.\n\nFixpoint qss (xl : list nat) (conc : qs_tree xl) {struct conc}:= \nmatch xl as _y0 return (xl = _y0) -> list nat with \n   | nil       => fun  _h0 => nil\n   | cons x xs => fun _h0 => \n      (qss (filter (fun y => leb y  x) xs)(qs_acc_inv_1_0'' _ _ _ conc _h0))\n      ++ (cons x (qss (filter (fun y => negb (leb y x)) xs)(qs_acc_inv_1_1'' _ _ _ conc _h0)))\n  end (refl_equal xl).\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "WouterSchols", "repo": "Coq_Quiksort", "sha": "0134e85462c2bb724cf2d66d5c78ef4c1679180d", "save_path": "github-repos/coq/WouterSchols-Coq_Quiksort", "path": "github-repos/coq/WouterSchols-Coq_Quiksort/Coq_Quiksort-0134e85462c2bb724cf2d66d5c78ef4c1679180d/quickSort_def2_Dijkstra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7293739786738551}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (x : natural) : natural :=\n  mult (Succ x) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj142_coqofml_151HQj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7293739679325943}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult (Succ x) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj305_coqofml_TvlM6H.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7293739654429247}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  mult (Succ y) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj207_coqofml_0xRmL7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.793105953629227, "lm_q1q2_score": 0.7293739649410261}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  plus x (plus y (Succ lf2)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj182_coqofml_AEGoif.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7293739634353306}}
{"text": "(*|\n##########################\nHow proof functions prove?\n##########################\n\n:Link: https://stackoverflow.com/q/61959394\n|*)\n\n(*|\nQuestion\n********\n\nIt'd help my understanding the 'programs/proofs' parallelism if\nsomebody was kind enough to explain me how the proof function is used\nin the following simple case:\n|*)\n\nTheorem ex1 : forall n : nat, 7*5 < n -> 6*6 <= n.\nProof.\n  intros. assumption.\nQed.\n\n(*| The proof function: |*)\n\nPrint ex1. (* .unfold .messages *)\n\n(*|\nIs the proof function executed in the proof process? How its return\nvalue is used? Is it correct to say that the return value of ``ex1``\nis an instance of the type ``forall n : nat, 7 * 5 < n -> 6 * 6 <=\nn``?\n|*)\n\n(*|\nAnswer\n******\n\n    Is it correct to say that the return value of ``ex1`` is an\n    instance of the type ``forall n : nat, 7 * 5 < n -> 6 * 6 <= n``?\n\nNot quite. It would be more correct to say that the return type of\n``ex1`` is ``6 * 6 <= n``, where ``n`` is the first argument passed to\n``ex1``, or that ``ex1`` has type ``forall n, 7 * 5 < n -> 6 * 6 <=\nn``.\n\n    Is the proof function executed in the proof process?\n\nNot necessarily. Execution here means \"simplification\" or\n\"normalization\". The term built by the proof is usually not\nsimplified. For example:\n|*)\n\nTheorem foo : True.\nProof.\n  assert (H : True -> True).\n  { intros H'. exact H'. }\n  apply H. exact I. (* I is a proof of True *)\nQed.\n\nPrint foo. (* .unfold *)\n\n(*|\nSimplifying this proof means replacing ``H`` by ``fun H' : True =>\nH'`` and reducing the application, which yields ``I``. You can see\nthis by asking Coq to compute this term:\n|*)\n\nCompute let H : True -> True := fun H' : True => H' in H I. (* .unfold *)\n\n(*|\n*However*:\n\n    How its return value is used?\n\nEvery proof that you enter in Coq goes a type-checking step to ensure\nit is correct. One of the things the type checker does is to simplify\nterms when comparing their types. In Coq, two terms that compute to\nthe same normal form are considered equal. The term given in the\nresult, ``H``, was given type ``7 * 5 < n``. But ``a < b`` is defined\nas ``S a <= b``; thus we can also view ``H`` as having type ``S (7 *\n5) <= n``. Coq now needs to ensure that ``H`` has type ``6 * 6 <= n``,\nwhich it does, because the two lower bounds compute to 36. Thus, there\nis computation happening when you enter a proof in Coq, but the\ncomputation is performed by the type-checker, not the proof term (even\nthough the proof term does have computational behavior).\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-proof-functions-prove.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940974, "lm_q2_score": 0.8311430520409024, "lm_q1q2_score": 0.7293087432318638}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* A \"real\" algorithm with nested recursion, unification\n\n   µ v : is a variable (term)\n   φ c : is a constant (term)\n   m⋄n : is a compound term\n\n   occ-check x (µ _)   = false\n   occ-check x (φ _)   = false\n   occ-check x (M  N)  = (µ x =? m) \n                      or (µ x =? n) \n                      or occ-check x m \n                      or occ-check x n\n\n   unify (µ v) m       = if occ-check v m \n                         then None \n                         else Some [(v,m)]\n\n   unify (φ c) (µ v)   = Some [(v,φ c)]\n\n   unify (φ c) (φ d)   = if c =? d \n                         then Some [] \n                         else None\n\n   unify (φ c) (_⋄_)   = None\n\n   unify (_⋄_) (φ c)   = None\n\n   unify (m⋄n) (µ v)   = if occ-check v (m⋄n) \n                         then None\n                         else Some [(v,m⋄n)]\n\n   unify (m⋄n) (m'⋄n') = match unify m m' with\n                           | None   ⇒ None\n                           | Some σ ⇒ match unify (σ n) (σ n') with\n                                   | None   ⇒ None\n                                   | Some υ ⇒ Some (σ o υ)\n\n\n  From http://www21.in.tum.de/~krauss/function/function.pdf\n  \n  orig algo from Z. Manna, R. Waldinger, \n  \n  \"Deductive synthesis of the unification algorithm\"\n  \n  https://www.sri.com/sites/default/files/uploads/publications/pdf/689.pdf\n\n  We synthesize something close to ...\n\n  Inductive d_unif : trm -> trm -> Prop := \n    | d_unif_1 : forall c m n,          d_unif (φ c) (m⋄n)\n    | d_unif_2 : forall c m n,          d_unif (m⋄n) (φ c)\n    | d_unif_3 : forall c x,            d_unif (φ c) (µ x)\n    | d_unif_4 : forall m n x,          d_unif (m⋄n) (µ x)\n    | d_unif_5 : forall x t,            d_unif (µ x) t\n    | d_unif_6 : forall c d,            d_unif (φ c) (φ d)\n    | d_unif_7 : forall m n m' n' D1,   unif m m' D1 = None     \n                                     -> d_unif (m⋄n) (m'⋄n')\n    | d_unif_8 : forall m n m' n' D1 σ, unif m m' D1 = Some σ \n                                     -> d_unif (subst σ n) (subst σ n') \n                                     -> d_unif (m°n) (m'⋄n')\n  with Fixpoint unif m n (D : d_unif m n) := \n  match D with\n    | d_unif_1 c m n => None\n    | d_unif_2 c m n => None\n    | d_unif_3 c x   => Some ((x,φ c)::∅)\n    | d_unif_4 m n x => if occ_check x (m ⋄ n) then None else Some ((x,m⋄n)::∅)\n    | d_unif_5 x m   => if occ_check x m       then None else Some ((x,m)::∅)\n    | d_unif_6 c d   => if c =? d then Some ∅ else None \n    | d_unif_7 _ _ _ _ _ _ => None\n    | d_unif_8 m n m' n' D1 σ H1 D2 => match unif (subst σ n) (subst σ n') D2 with\n                                         | None    => None\n                                         | Some υ => Some (σ o υ)\n                                       end\n  end.\n\n*)\n\nRequire Import List Bool Utf8. (* → λ ∀ ∃ ↔ ∧ ∨ ≤ ¬ *)\n\nSet Implicit Arguments.\n\n(** Small list goodies *)\n\nInfix \"∈\" := In (at level 70, no associativity).\nNotation \"x ∉ l\" := (¬ x ∈ l) (at level 70, no associativity).\nInfix \"⊆\" := incl (at level 70, no associativity).\n\nTactic Notation \"destruct\" \"∈\" \"at\" hyp(H) :=\n  repeat match type of H with \n    | In _ (_ ++ _)  => apply in_app_or in H; destruct H as [ H | H ]\n    | In _ (_ :: _)  => destruct H as [ H | H ]\n  end.\n\nParameter (𝓥  : Type) (eqV : 𝓥  → 𝓥  → bool) (eqV_spec : ∀ x y, eqV x y = true ↔ x = y).\nParameter (𝓒  : Type) (eqC : 𝓒  → 𝓒  → bool) (eqC_spec : ∀ x y, eqC x y = true ↔ x = y).\n\n(** A type of constants and a type of variables, both discrete *)\n\nLemma eq_bool_dec {X} (eqb : X → X → bool) :\n         (∀ x y, eqb x y = true ↔ x = y)\n      -> (∀ x y : X, { x=y } + { x≠y }).\nProof.\n  intros H x y; generalize (H x y).\n  refine (match eqb x y with true => _ | false => _ end); intros [ H1 H2 ].\n  + left; auto.\n  + right; intros ->; now specialize (H2 eq_refl).\nQed.\n\nFact eqV_dec (x y : 𝓥 ) : { x=y } + { x≠y }.\nProof. apply eq_bool_dec with (1 := eqV_spec). Qed.\n\nFact eqC_dec : forall x y : 𝓒 , { x=y } + { x≠y }.\nProof. apply eq_bool_dec with (1 := eqC_spec). Qed.\n\n(** The type of terms, ie binary trees built from C or V as leaves *)\n\nInductive trm : Type := \n  | Var : 𝓥  → trm\n  | Cst : 𝓒  → trm\n  | App : trm → trm → trm.\n\n(** Compact notations *)\n\nNotation Λ := trm.\nNotation µ := Var.\nNotation φ := Cst.\nNotation \"a ⋄ b\" := (App a b) (at level 61, left associativity, format \"a ⋄ b\").\n\n(** The inversion lemma (injectivity) for _⋄_ = _⋄_ and a tactic for it *)\n\n(* → λ ∀ ∃ ↔ ∧ ∨ ≤ ¬ ≠ *)\n\nFact term_eq_app_inv m n m' n' : m⋄n = m'⋄n' → m = m' ∧ n = n'.\nProof. now inversion 1. Qed.\n\nTactic Notation \"trm\" \"eq\" \"inv\" hyp(H) \"as\" ident(E1) ident(E2) :=\n  apply term_eq_app_inv in H; destruct H as [ E1 E2 ].\n\n(** Various equality deciders *)\n\nHint Resolve eqC_dec eqV_dec : core.\n\nDefinition trm_eq_dec (u v : Λ) : { u=v } + { u≠v }.\nProof. decide equality. Qed.\n\n(* Implemented with tight control of computational behavior because \n   it is extracted *)\n\nDefinition eq_Var_b x m : bool :=\n  match m with \n    | µ y => if eqV_dec x y then true else false\n    | _   => false\n  end.\n \nFact eq_Var_b_spec x m : eq_Var_b x m = true ↔ µ x = m.\nProof.\n  destruct m as [ y | | ]; simpl; try (split; discriminate).\n  destruct (eqV_dec x y); subst; split; try tauto; try discriminate.\n  now inversion 1.\nQed.\n\n(* We use the Boolean decider for better extraction *)\n\nDefinition eq_Var_dec (x : 𝓥 ) (t : Λ) : { µ x=t } + { µ x≠t }.\nProof.\n  generalize (eq_Var_b_spec x t).\n  destruct (eq_Var_b x t); intros [ H1 H2 ]; try tauto.\n  right; intros <-.\n  now specialize (H2 eq_refl).\nQed.\n\n(** Term size and variable list *)\n\nReserved Notation \"⟦ x ⟧\" (at level 1, format \"⟦ x ⟧\").\n\nFixpoint trm_size t :=\n  match t with\n    | m⋄n => 1+⟦m⟧+⟦n⟧\n    | _   => 0\n  end\nwhere \"⟦ t ⟧\" := (trm_size t).\n\nReserved Notation \"⟪ x ⟫\" (at level 1, format \"⟪ x ⟫\").\n\nFixpoint trm_vars t := \n  match t with\n    | µ x => x::nil\n    | φ _ => nil \n    | m⋄n => ⟪m⟫ ++ ⟪n⟫\n  end\nwhere \"⟪ t ⟫\" := (trm_vars t).\n\n(** Occur check, see below for charact. vs var list *)\n\n(* → λ ∀ ∃ ↔ ∧ ∨ ≤ ¬ ≠ *)\n\nReserved Notation \"x ≺ t\" (at level 70, no associativity).\n\nFixpoint occ_check (x : 𝓥 ) (t : Λ) :=\n  match t with\n    | m⋄n => µ x=m ∨ µ x=n ∨ x ≺ m ∨ x ≺ n\n    | _   => False\n  end\nwhere \"x ≺ t\" := (occ_check x t).\n\nNotation \"x ⊀ t\" := (~ x ≺ t) (at level 70).\n\n(* x occur checks in m is m is not µx and x belongs to the variables of m *)\n \nFact trm_vars_occ_check x m : x ≺ m ↔ m≠µ x ∧ x ∈ ⟪m⟫.\nProof.\n  induction m as [ y | c | m Hm n Hn ].\n  + simpl.\n    split; try tauto.\n    intros (H1 & [ H2 | [] ]); subst; tauto.\n  + simpl; tauto.\n  + simpl; rewrite Hm, Hn.\n    split.\n    * intros [|[|[|]]]; split; try discriminate;\n        subst; rewrite in_app_iff; simpl; tauto.\n    * intros (_ & H).\n      destruct ∈ at H.\n      - destruct (trm_eq_dec m (µ x)); subst; tauto.\n      - destruct (trm_eq_dec n (µ x)); subst; tauto.\nQed.\n\nFact trm_vars_nocc_check x m : x ⊀ m ↔ m=µ x ∨ x ∉ ⟪m⟫.\nProof.\n  rewrite trm_vars_occ_check.\n  destruct (trm_eq_dec m (Var x)); tauto.\nQed.\n\n(* Careful Boolean implementation for better extraction *)\n\nReserved Notation \"x '≺?' t\" (at level 1, no associativity).\n\nFixpoint occ_check_b (x : 𝓥 ) (t : Λ) :=\n  match t with\n    | µ _ => false\n    | φ _ => false \n    | m⋄n => eq_Var_b x m || eq_Var_b x n || x ≺? m || x ≺? n\n  end\nwhere \"x ≺? t\" := (occ_check_b x t).\n\nFact occ_check_b_spec x t : x ≺? t = true ↔ x ≺ t.\nProof.\n  induction t as [ y | c | m IHm n IHn ]; simpl; try easy.\n  rewrite !orb_true_iff, !eq_Var_b_spec, IHm, IHn; tauto.\nQed.\n \n(* We implement occ_check decision using the Boolean function \n   for better extraction, because this one is used in the\n   code of unif below *)\n \nDefinition occ_check_dec x t : { x ≺ t } + { x ⊀ t }.\nProof.\n  generalize (occ_check_b_spec x t).\n  refine (match x ≺? t with \n    | true => _\n    | false => _\n  end); intros [ H1 H2 ]; try tauto.\n  right; intro H; apply H2 in H; discriminate.\nQed.\n\n(** // Substitutions of variables and then inside terms *)\n\nNotation Σ := (list (𝓥 *Λ)).  (* the type of substitutions *)\nNotation \"∅\" := (@nil _).     (* Notation for the empty/identity substitution *)\n\nReserved Notation \"σ ↑ x\" (at level 61, format \"σ ↑ x\").\n\n(* We avoid unicode in extracted terms because \n   it does not mix well with OCaml. So here\n   the letter s is used instead of σ *)\n\nFixpoint subst_var s (x : 𝓥 ) : option Λ :=\n  match s with \n    | ∅      => None\n    | (y,t)::s => if eqV_dec x y then Some t else s↑x\n  end\nwhere \"σ ↑ x\" := (subst_var σ x).\n\n(* → λ ∀ ∃ ↔ ∧ ∨ ≤ ¬ ≠ *)\n\nFact subst_var_spec σ x : { m | σ↑x = Some m ∧ (x,m) ∈ σ } \n                        + { σ↑x = None ∧ ∀m, (x,m) ∉ σ }.\nProof.\n  induction σ as [ | (y,m) σ IHσ ].\n  + right; simpl; tauto.\n  + simpl.\n    destruct (eqV_dec x y) as [ H | H ].\n    * left; exists m; subst; tauto.\n    * destruct IHσ as [ (n & H1 & H2) | (H1 & H2) ].\n      - left; exists n; tauto.\n      - right; split; auto.\n        intros n [ H3 | H3 ].\n        ++ destruct H; inversion H3; auto.\n        ++ revert H3; apply H2.\nQed.\n\nReserved Notation \"t ⦃ s ⦄\" (at level 1, left associativity, format \"t ⦃ s ⦄\").\n\nFixpoint subst s t :=\n  match t with\n    | µ x => \n    match s↑x with \n      | Some v => v\n      | None   => µ x \n    end\n    | φ x      => φ x\n    | m⋄n      => m⦃s⦄⋄n⦃s⦄\n  end\nwhere \"t ⦃ σ ⦄\" := (subst σ t).\n\n(** The composition of substitutions *)\n\n  Definition subst_comp s r := map (fun c => (fst c, (snd c)⦃r⦄)) s ++ r.\n\nNotation \"x 'o' y\" := (subst_comp x y) (at level 60, format \"x  o  y\").\n\nFact subst_nil t : t⦃∅⦄  = t.\nProof. induction t; simpl; f_equal; auto. Qed.\n\nFact subst_comp_spec σ υ t : t⦃σ o υ⦄ = t⦃σ⦄⦃υ⦄.\nProof.\n  induction t as [ x | c | m IHm n IHn ]; simpl; auto.\n  + induction σ as [ | (y,t) s IHs ]; simpl.\n    * unfold subst_comp; simpl; auto.\n    * destruct (eqV_dec x y) as [ H | H ]; auto.\n  + f_equal; auto.\nQed.\n\n(** The graph of unif, ie a ⋉ b ⟼ r encodes \n    the ternary relation r = unif a b *)\n\n(* → λ ∀ ∃ ↔ ∧ ∨ ≤ ¬ ≠ *)\n\nReserved Notation \"a ⋉ b ⟼u r\" (at level 70).\n\nInductive 𝔾unif : Λ → Λ → option Σ → Prop :=\n    | in_gu_0 c m n :             φ c ⋉ m⋄n   ⟼u None\n    | in_gu_1 c m n :             m⋄n ⋉ φ c   ⟼u None\n    | in_gu_2 c x :               φ c ⋉ µ x   ⟼u Some ((x,φ c)::∅)\n    | in_gu_3 m n x :             x ≺ m⋄n\n                               →  m⋄n ⋉ µ x   ⟼u None\n    | in_gu_4 m n x :             x ⊀ m⋄n\n                               →  m⋄n ⋉ µ x   ⟼u Some ((x,m⋄n)::∅)\n    | in_gu_5 x m :               x ≺ m\n                               →  µ x ⋉ m     ⟼u None\n    | in_gu_6 x m :               x ⊀ m\n                               →  µ x ⋉ m     ⟼u Some ((x,m)::∅)\n    | in_gu_7 c d :               c = d\n                               →  φ c ⋉ φ d   ⟼u Some ∅\n    | in_gu_8 c d :               c ≠ d\n                               →  φ c ⋉ φ d   ⟼u None\n    | in_gu_9 m m' n n' :         m   ⋉ m'    ⟼u None\n                               →  m⋄n ⋉ m'⋄n' ⟼u None\n    | in_gu_a m m' n n' σ :       m   ⋉ m'    ⟼u Some σ\n                               → n⦃σ⦄ ⋉ n'⦃σ⦄ ⟼u None\n                               →  m⋄n ⋉ m'⋄n' ⟼u None\n    | in_gu_b m m' n n' σ υ :     m   ⋉ m'    ⟼u Some σ\n                               → n⦃σ⦄ ⋉ n'⦃σ⦄ ⟼u Some υ\n                               →  m⋄n ⋉ m'⋄n' ⟼u Some (σ o υ)\nwhere \"a ⋉ b ⟼u r\" := (𝔾unif a b r). \n\n(** The graph is functional *)\n\nFact 𝔾unif_fun m n o1 o2 : m ⋉ n ⟼u o1  →  m ⋉ n ⟼u o2  →  o1 = o2.\nProof.\n  intros H; revert H o2.\n  induction 1 as [ c m n \n                 | c m n \n                 | c x \n                 | m n x H1 \n                 | m n x H1 \n                 | x m H1\n                 | x m H1\n                 | c d H1\n                 | c d H1\n                 | m m' n n' H1 IH1\n                 | m m' n n' σ H1 IH1 H2 IH2\n                 | m m' n n' σ υ H1 IH1 H2 IH2\n                 ]; intros r2; inversion 1; subst; auto; try discriminate; try tauto.\n  + apply IH1 in H6; discriminate.\n  + apply IH1 in H7; inversion H7; subst.\n    apply IH2 in H8; discriminate.\n  + apply IH1 in H7; discriminate.\n  + apply IH1 in H7; inversion H7; subst.\n    apply IH2 in H8; discriminate.\n  + apply IH1 in H7; inversion H7; subst.\n    apply IH2 in H8; inversion H8; subst.\n    trivial.\nQed.\n", "meta": {"author": "DmxLarchey", "repo": "The-Braga-Method", "sha": "e4f51add22a73681103454ad94a05aeeda332c50", "save_path": "github-repos/coq/DmxLarchey-The-Braga-Method", "path": "github-repos/coq/DmxLarchey-The-Braga-Method/The-Braga-Method-e4f51add22a73681103454ad94a05aeeda332c50/theories/unif/unif_graph_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7293087350636278}}
{"text": "(**\nMathComp の環・体\n========================\n\n@suharahiromichi\n\n2020/07/17\n*)\n\nFrom mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\nRequire Import ssromega.                    (* ssromega タクティク *)\nRequire Import Recdef.                      (* Function コマンド *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.         (* mulrA などを使えるようにする。 *)\nImport Num.Theory.           (* unitf_gt0 などを使えるようにする。 *)\nImport intZmod.              (* addz など *)\nImport intRing.              (* mulz など *)\nOpen Scope ring_scope.       (* (x + y)%Rを省略時解釈とする。 *)\n\n(*\n# 加群 Zmodule\n *)\nSection ZModule.\n  Variable V : zmodType.\n\n  Check @addrC V : forall x y : V, (x + y) = (y + x).\n  Check @addrA V : forall x y z : V, (x + (y + z)) = (x + y + z).\n\n  (* opposite (単項マイナス演算子) は、 *)\n  Check @opprD V : {morph -%R : x y / x + y}.\n\nEnd ZModule.\n\n(**\n# 環 ring\n*)\nSection Ring.\n  Variable R : ringType.\n  \n  Check @mulrA R : forall x y z : R, (x * (y * z)) = (x * y * z).\nEnd Ring.\n\n(**\n# 1をもつ環\n*)\nSection UnitRing.\n  Variable R : unitRingType.\n  \n  Check @divrr R : forall x : R, x \\is a GRing.unit -> (x / x) = 1.\nEnd UnitRing.\n\n(**\n# 可換環 commutative ring\n*)\nSection ComRing.\n  Variable R : comRingType.\nEnd ComRing.\n\n(**\n# 1をもつ可換環\n*)\nSection ComUnitRing.\n  Variable R : comUnitRingType.\n  \n  Check @unitrM R\n    : forall x y : R,\n      (x * y) \\is a GRing.unit = (x \\is a GRing.unit) && (y \\is a GRing.unit).\nEnd ComUnitRing.\n\n(**\n# 整域 integral domain\n*)\nSection IntDomain.\n  Variable R : idomainType.\n\n  Check @mulf_eq0 R : forall x y : R,\n      ((x * y) == 0) = (x == 0) || (y == 0).\nEnd IntDomain.\n\n(**\n# number domain (number field)\n\norder (順番) と norm (絶対値) のある整域（または体）(例：ガウス整数)\n*)\nSection NumDomain.\n  Variable R : numDomainType.\n\n  Check @ler_norm_add R : forall x y : R,\n      `|x + y| <= `|x| + `|y|.\nEnd NumDomain.\n\n(**\n# 体 field\n*)\nSection Field.\n  Variable F : fieldType.\n  \n  Check @divff F : forall x : F,\n      x != 0 -> (x / x) = 1.\nEnd Field.\n\n(**\n# real field\n\n要素に正負のある number field （例：実数）\n*)\nSection RealField.\n  Variables rF : realFieldType.\n  \n  Check @lerif_mean_square rF : forall x y : rF,\n      x * y <= (x ^+ 2 + y ^+ 2) / 2%:R ?= iff (x == y).\n  \n  (* 左辺の=が成り立つことと、x = y であることが同値  *)\nEnd RealField.\n\n(**\n# 閉体 closed field\n\n多項式の根がある体。\n*)\nSection ClosedField.\n  (* 補足すること。 *)\nEnd ClosedField.\n\n\n(**\n# おまけ\n\n冒頭で ring_scope を設定しています。\nこれは + の省略時解釈を GRing.add とすることです。\n *)\nLocate \"_ + _\".\n(*\n\"m + n\" := Nat.add m n : coq_nat_scope\n\"A + B\" := addsmx A B : matrix_set_scope\n\"m + n\" := addn_rec m n : nat_rec_scope\n\"m + n\" := addn m n : nat_scope ← 通常、これが省略時解釈。\n\"x + y\" := addq x y : rat_scope ← ここでは、これが省略時解釈。\n\"x + y\" := GRing.add x y : ring_scope\n\"x + y\" := GRing.Add x y : term_scope\n\"x + y\" := sum x y : type_scope\n\"U + V\" := addv U V : vspace_scope\n*)\n\n(* 以下において、Checkの出力の %X が消えることに注意してください。 *)\n(* ProofGeneral では、読み直さないといけない場合があります。 *)\n\n(* ssrnat.v:Delimit Scope coq_nat_scope with coq_nat. *)\nOpen Scope coq_nat_scope.\nCheck (1 + 1)%coq_nat : nat.\n\n(* ssrnat.v:Delimit Scope nat_scope with N. *)\nOpen Scope nat_scope.\nCheck (1 + 1)%N : nat.\n\n(* ssralg.v:Delimit Scope ring_scope with R. *)\nOpen Scope ring_scope.\nVariable R : ringType.\nCheck (1 + 1)%R : R.\n\n(* ssralg.v:Delimit Scope term_scope with T. *)\nOpen Scope term_scope.\nCheck (1 + 1)%T : GRing.term R.\n\nOpen Scope type_scope.\nCheck (nat + nat)%type : Set.\n\n(* rat.v:Delimit Scope rat_scope with Q. *)\nOpen Scope rat_scope.\nCheck (1 + 1)%Q : rat.\n\n(* eqtype.v:Delimit Scope eq_scope with EQ. *)\nOpen Scope eq_scope.                (* 通常は省略時解釈のまま使う。 *)\nCheck (1 = 1)%EQ : Prop.\n\n(* bigop.v:Delimit Scope big_scope with BIG. *)\nOpen Scope big_scope.               (* 通常は省略時解釈のまま使う。 *)\nCheck (\\sum_(i < 2)i)%BIG : nat.\n\n(* ssrbool.v:Delimit Scope bool_scope with B. *)\nOpen Scope bool_scope.              (* 通常は省略時解釈のまま使う。 *)\nCheck (true && true)%B : bool.\n\n(* ssrfun.v:Delimit Scope pair_scope with PAIR. *)\nOpen Scope pair_scope.              (* 通常は省略時解釈のまま使う。 *)\nCheck (1, 1)%PAIR : (rat * rat)%type.\n\n(* ssrint.v:Delimit Scope int_scope with Z. *)\nOpen Scope int_scope.\n(* int は、+ - などはグローバルに定義されていない。 *)\nCheck (addz 1 1)%Z : int.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/math/ssr_ring_field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7292845216791757}}
{"text": "(**\n- Coq/SSReflectでperm_eqが不変条件であるような命題を証明するための帰納原理\n\nhttps://qiita.com/nekonibox/items/233d23bf0fb7cad79e01\n *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nLemma ubnP m : {n | m < n}.     (* 最新の ssrnat.v で導入された。 *)\nProof. by exists m.+1. Qed.\n\n(**\n# perm_eq\n*)\n(**\n## perm_eq (in seq.v)\n\nperm_eq は seq.v で定義されている。\n*)\nCheck @perm_eq : forall T : eqType, seq T -> seq T -> bool.\nCompute perm_eq [:: 1; 2; 3] [:: 2; 1; 3].  (* true *)\n\n(**\n## perm_eq についての帰納法\n*)\n\nLemma perm_ind (T : eqType) (P : seq T -> seq T -> Prop) :\n  P [::] [::] ->\n  (forall u s t, P s u -> P u t -> P s t) ->\n  (forall a s t, P s t -> P (a :: s) (a :: t)) ->\n  (forall a b s t, P [:: a, b & s] t -> P [:: b, a & s] t) ->\n  forall s t, perm_eq s t -> P s t.\nProof.\n    move=> Hnil Htrans Hcons Hcons2 s.\n    have [n] := ubnP (size s).\n    elim: n s => [|n IHn][|a s] //=.\n    Check permP.\n    - by move=> _ [|b t] // /permP /(_ predT).\n    - rewrite ltnS => Hs [/permP /(_ predT)|b t] // Hperm.\n      move: (perm_mem Hperm b) (Hperm).\n      rewrite !in_cons eq_refl => /= /orP[/eqP -> | Hb _].\n      + rewrite perm_cons => /(IHn _ Hs). exact: Hcons.\n      + apply: Htrans (Hcons a _ _ (IHn _ Hs _ (perm_to_rem Hb))) _.\n        apply: Hcons2 (Hcons _ _ _ (IHn _ _ _ _)) => /=.\n        * rewrite size_rem //.\n            by case : s Hs Hb {Hperm}.\n        * rewrite -(perm_cons b).\n          apply: perm_trans Hperm.\n          apply: (perm_trans (y := [:: a, b & rem b s])).\n          ** apply/permP => g /=.\n               by rewrite addnCA.\n          ** rewrite perm_cons perm_sym.\n             exact: perm_to_rem.\nQed.\n\nLemma perm_eq_ind (T : eqType) (S : Type) (f : seq T -> S) :\n  (forall a s t, f s = f t -> f (a :: s) = f (a :: t)) ->\n  (forall a b s, f [:: a, b & s] = f [:: b, a & s]) ->\n  forall s t, perm_eq s t -> f s = f t.\nProof.\n  move=> Hcons Hcons2.\n    by apply: perm_ind => [| u s t -> -> || a b s t <-].\nQed.\n\n(**\n## 応用例\n*)\nLemma foldr_addn_perm s t :\n  perm_eq s t -> foldr addn 0 s = foldr addn 0 t.\nProof.\n  move: s t.\n  apply: perm_eq_ind => [a s t /= -> | a b s] //=.\n    by rewrite addnCA.\nQed.\n\n(**\n## 補足説明\n*)\nCheck @permP : forall (T : eqType) (s1 s2 : seq T),\n    reflect (count^~ s1 =1 count^~ s2) (perm_eq s1 s2).\n\n(**\n# perm 型\n\nperm型とはordinal型の仲間で、\nperm_finType が定義されているが、\nリストの perm_eq とは直接関係ない。\n\nsee. csm_6_2_x_permutation.v\n*)\nFrom mathcomp Require Import all_fingroup.\n\n(*\npermP の定義が重複している。\n*)\nCheck permP : forall (T : finType) (s t : {perm T}), s =1 t <-> s = t.\n\n(*\nリスト(tuple)の perm_eq とのリフレクションの補題がひとつある。\n*)\nCheck @tuple_permP : forall (T : eqType) (n : nat) (s : seq T) (t : n.-tuple T),\n    reflect (exists p : 'S_n, s = [tuple tnth t (p i)  | i < n]) (perm_eq s t).\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/math/ssr_ind_of_perm_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7292296594313054}}
{"text": "(** * Logic: Logic in Coq *)\n\n(* $Date: 2012-07-22 18:36:58 -0400 (Sun, 22 Jul 2012) $ *)\n\nRequire Export \"Prop\". \n\n(** Coq's built-in logic is extremely small: only [Inductive]\n    definitions, universal quantification ([forall]), and\n    implication ([->]) are primitive, while all the other familiar\n    logical connectives -- conjunction, disjunction, negation,\n    existential quantification, even equality -- can be defined using\n    just these. *)\n\n(* ########################################################### *)\n(** * Quantification and Implication *)\n\n(** In fact, [->] and [forall] are the _same_ primitive!  Coq's [->]\n    notation is actually just a shorthand for [forall].  The [forall]\n    notation is more general, because it allows us to _name_ the\n    hypothesis. *)\n\n(** For example, consider this proposition: *)\n\nDefinition funny_prop1 := \n  forall n, forall (E : beautiful n), beautiful (n+3).\n\n(** If we had a proof term inhabiting this proposition, it would\n    be a function with two arguments: a number [n] and some evidence\n    that [n] is beautiful.  But the name [E] for this evidence is not\n    used in the rest of the statement of [funny_prop1], so it's a bit\n    silly to bother making up a name.  We could write it like this\n    instead, using the dummy identifier [_] in place of a real\n    name: *)\n\nDefinition funny_prop1' := \n  forall n, forall (_ : beautiful n), beautiful (n+3).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition funny_prop1'' := \n  forall n, beautiful n -> beautiful (n+3). \n\n(** This illustrates that \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ########################################################### *)\n(** * Conjunction *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q). \n\n(** Note that, like the definition of [ev] in the previous\n    chapter, this definition is parameterized; however, in this case,\n    the parameters are themselves propositions, rather than numbers. *)\n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q]. \n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example : \n  (beautiful 0) /\\ (beautiful 3).\nProof.\n  apply conj.\n  (* Case \"left\". *) apply b_0.\n  (* Case \"right\". *) apply b_3.  Qed.\n\n(** Let's take a look at the proof object for the above theorem. *)\n\nPrint and_example. \n(* ===>  conj (beautiful 0) (beautiful 3) b_0 b_3\n            : beautiful 0 /\\ beautiful 3 *)\n\n(** Note that the proof is of the form\n    conj (beautiful 0) (beautiful 3) \n         (...pf of beautiful 3...) (...pf of beautiful 3...)\n    as you'd expect, given the type of [conj]. *)\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n    Case \"left\". apply ev_0.\n    Case \"right\". apply ev_SS. apply ev_SS. apply ev_0.  Qed.\n\n(** Conversely, the [inversion] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop, \n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ]. \n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2) *)\nTheorem proj2 : forall P Q : Prop, \n  P /\\ Q -> Q.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop, \n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HP HQ]. \n  split.  \n    (* Case \"left\". *) apply HQ. \n    (* Case \"right\".*) apply HP.  Qed.\n  \n(** Once again, we have commented out the [Case] tactics to make the\n    proof object for this theorem easy to understand.  Examining it\n    shows that all that is really happening is taking apart a record\n    containing evidence for [P] and [Q] and rebuilding it in the\n    opposite order: *)\n\nPrint and_commut.\n(* ===>\n   and_commut = \n     fun (P Q : Prop) (H : P /\\ Q) =>\n     let H0 := match H with\n               | conj HP HQ => conj Q P HQ HP\n               end \n     in H0\n     : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\n\n(** **** Exercise: 2 stars (and_assoc) *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [inversion] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop, \n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (even__ev) *)\n(** Now we can prove the other direction of the equivalence of [even]\n   and [ev], which we left hanging in chapter [Prop].  Notice that the\n   left-hand conjunct here is the statement we are actually interested\n   in; the right-hand conjunct is needed in order to make the\n   induction hypothesis strong enough that we can carry out the\n   reasoning in the inductive step.  (To see why this is needed, try\n   proving the left conjunct by itself and observe where things get\n   stuck.) *)\n\nTheorem even__ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  (* Hint: Use induction on [n]. *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (conj_fact) *)\n(** Construct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The familiar logical \"if and only if\" is just the\n    conjunction of two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) \n                      (at level 95, no associativity) : type_scope.\n\nTheorem iff_implies : forall P Q : Prop, \n  (P <-> Q) -> P -> Q.\nProof.  \n  intros P Q H. \n  inversion H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop, \n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. \n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties) *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop, \n  P <-> P.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beautiful_iff_gorgeous) *)\n\n(** We have seen that the families of propositions [beautiful] and\n    [gorgeous] actually characterize the same set of numbers.\n    Prove that [beautiful n <-> gorgeous n] for all [n].  Just for\n    fun, write your proof as an explicit proof object, rather than\n    using tactics. (_Hint_: if you make use of previously defined\n    theorems, you should only need a single line!) *)\n\nDefinition beautiful_iff_gorgeous :\n  forall n, beautiful n <-> gorgeous n :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q. \n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** Since [P \\/ Q] has two constructors, doing [inversion] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". right. apply HP.\n    Case \"right\". left. apply HQ.  Qed.\n\n(** **** Exercise: 2 stars, optional (or_commut'') *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof. \n  intros P Q R. intros H. inversion H as [HP | [HQ HR]]. \n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars, recommended (or_distributes_over_and_2) *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_distributes_over_and) *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_true__and : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n\nTheorem and__andb_true : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := . \n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n(** **** Exercise: 1 star (False_ind_principle) *)\n(** Can you predict the induction principle for falsehood? *)\n\n(* Check False_ind. *)\n(** [] *)\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof. \n  intros contra.\n  inversion contra.  Qed. \n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, optional (True_induction) *)\n(** Define [True] as another inductively defined proposition.  What\n    induction principle will Coq generate for your definition?  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.  Alternatively, you may find it easiest\n    to start with the induction principle and work backwards to the\n    inductive definition.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    just a theoretical curiosity: it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False : \n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof. \n  (* WORKED IN CLASS *)\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA. \n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, recommended (double_neg_inf) *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (informal_not_PNP) *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nTheorem five_not_even :  \n  ~ ev 5.\nProof. \n  (* WORKED IN CLASS *)\n  unfold not. intros Hev5. inversion Hev5 as [|n Hev3 Heqn]. \n  inversion Hev3 as [|n' Hev1 Heqn']. inversion Hev1.  Qed.\n\n(** **** Exercise: 1 star (ev_not_ev_S) *)\n(** Theorem [five_not_even] confirms the unsurprising fact that five\n    is not an even number.  Prove this more interesting fact: *)\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof. \n  unfold not. intros n H. induction H. (* not n! *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H. \n  (* But now what? There is no way to \"invent\" evidence for [P]. *) \n  Admitted.\n\n(** **** Exercise: 5 stars, optional (classical_axioms) *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop, \n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop, \n  ~~P -> P.\nDefinition excluded_middle := 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\n(* FILL IN HERE *)\n(** [] *)\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.  \n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n(** **** Exercise: 2 stars, recommended (not_eq_beq_false) *)\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_false_not_eq) *)\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can capture what this means with the\n    following 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    For example, consider this existentially quantified proposition: *)\n\nDefinition some_nat_is_even : Prop := \n  ex nat ev.\n\n(** To prove this proposition, we need to choose a particular number\n    as witness -- say, 4 -- and give some evidence that that number is\n    even. *)\n\nDefinition snie : some_nat_is_even := \n  ex_intro _ ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** Coq's notation definition facility can be used to introduce\n    more 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(** We can use the same set of tactics as always for\n    manipulating existentials.  For example, if to prove an\n    existential, we [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, again, that we have to explicitly give the witness. *)\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 * n) = 6.\nProof.\n  exists 2. \n  reflexivity.  Qed.\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(** **** 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(** Complete the definition of the following proof object: *)\n\nDefinition p : ex nat (fun n => beautiful (S n)) :=\n(* FILL IN HERE *) admit.\n(** [] *)\n\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" and \"there is no [x] for\n    which [P] does not hold\" are equivalent assertions. *)\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 requires the classical \"law of the excluded\n    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(* Print dist_exists_or. *)\n\n\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has\n    roughly the following inductive definition.  (We enclose the\n    definition in a module to avoid confusion with the standard\n    library equality, which we have used extensively already.) *)\n\nModule MyEquality.\n\nInductive eq (X:Type) : X -> X -> Prop :=\n  refl_equal : forall x, eq X x x.\n\n(** Standard infix notation (using Coq's type argument synthesis): *)\n\nNotation \"x = y\" := (eq _ x y) \n                    (at level 70, no associativity) : type_scope.\n\n(** This is a bit subtle.  The way to think about it is that, given a\n    set [X], it defines a _family_ of propositions \"[x] is equal to\n    [y],\" indexed by pairs of values ([x] and [y]) from [X].  There is\n    just one way of constructing evidence for members of this family:\n    applying the constructor [refl_equal] to a type [X] and a value [x\n    : X] yields evidence that [x] is equal to [x]. *)\n\n(** Here is a slightly different definition -- the one that actually\n    appears in the Coq standard library. *)\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\nNotation \"x =' y\" := (eq' _ x y) \n                     (at level 70, no associativity) : type_scope.\n\n(** **** Exercise: 3 stars, optional (two_defs_of_eq_coincide) *)\n(** Verify that the two definitions of equality are equivalent. *)\n\nTheorem two_defs_of_eq_coincide : forall (X:Type) (x y : X),\n  x = y <-> x =' y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The advantage of the second definition is that the induction\n    principle that Coq derives for it is precisely the familiar\n    principle of _Leibniz equality_: what we mean when we say \"[x] and\n    [y] are equal\" is that every property on [P] that is true of [x]\n    is also true of [y].  *)\n\nCheck eq'_ind.\n(* ===> \n     forall (X : Type) (x : X) (P : X -> Prop),\n       P x -> forall y : X, x =' y -> P y \n\n   ===>  (i.e., after a little reorganization)\n     forall (X : Type) (x : X) forall y : X, \n       x =' y -> \n       forall P : X -> Prop, P x -> P y *)\n\n(** One important consideration remains.  Clearly, we can use\n    [refl_equal] to construct evidence that, for example, [2 = 2].\n    Can we also use it to construct evidence that [1 + 1 = 2]?  Yes:\n    indeed, it is the very same piece of evidence!  The reason is that\n    Coq treats as \"the same\" any two terms that are _convertible_\n    according to a simple set of computation rules.  These rules,\n    which are similar to those used by [Eval simpl], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.\n    \n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).  But you can see them\n    directly at work in the following explicit proof objects: *)\n\nDefinition four : 2 + 2 = 1 + 3 :=  \n  refl_equal nat 4. \n\nDefinition singleton : forall (X:Set) (x:X), []++[x] = x::[]  :=\n  fun (X:Set) (x:X) => refl_equal (list X) [x]. \n\nEnd MyEquality.\n\n(* ####################################################### *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves...\n\n    In general, the [inversion] tactic\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n        \n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are two\n   constructors, so two subgoals get generated.  The\n   conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.\n\n   _Example_: If we invert a hypothesis built with [and], there is\n   only one constructor, so only one subgoal gets generated.  Again,\n   the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.  The\n   constructor does have two arguments, though, and these can be seen\n   in the context in the subgoal.\n\n   _Example_: If we invert a hypothesis built with [eq], there is\n   again only one constructor, so only one subgoal gets generated.\n   Now, though, the form of the [refl_equal] constructor does give us\n   some extra information: it tells us that the two arguments to [eq]\n   must be the same!  The [inversion] tactic adds this fact to the\n   context.  *)\n\n(* ####################################################### *)\n(** * Relations as Propositions *)\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 LeFirstTry.  \n\n(** We've already seen an inductive definition of one\n    fundamental relation: equality.  Another useful one is the \"less\n    than or equal to\" 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\nEnd LeFirstTry.\n\n(** This is a reasonable definition of the [<=] relation, but we\n    can streamline it a little by observing that the left-hand\n    argument [n] is the same everywhere in the definition, so we can\n    actually make it a \"general parameter\" to the whole definition,\n    rather than an argument to each constructor.  This is similar to\n    what we did in our second definition of the [eq] relation,\n    above. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. \n    (The same was true of our second version of [eq].) *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(** By contrast, the induction principle that Coq calculates for the\n    first definition has a lot of extra quantifiers, which makes it\n    messier to work with when proving things by induction.  Here is\n    the induction principle for the first [le]: *)\n\n(* le_ind : \n     forall P : nat -> nat -> Prop,\n     (forall n : nat, P n n) ->\n     (forall n m : nat, le n m -> P n m -> P n (S m)) ->\n     forall n n0 : nat, le n n0 -> P n n0 *)\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)].) *)\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).\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H1.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\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, recommended (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: 3 stars, recommended (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(** State and prove an equivalent characterization of the relation\n    [R].  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(** **** Exercise: 3 stars, recommended (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, optional (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, 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, optional (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(** ** Digression: More Facts about [<=] and [<] *)\n\n(** Let's pause briefly to record several facts about the [<=]\n    and [<] relations that we are going to need later in the\n    course.  The proofs make good practice exercises. *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\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\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  intros n m.  generalize dependent n.  induction m. \n  (* FILL IN HERE *) Admitted. \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 (* 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 ble_nat_n_Sn_false : forall n m,\n  ble_nat n (S m) = false ->\n  ble_nat n m = false.\nProof. \n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* Hint: Do the right induction! *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_2:  nostutter [].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_false_not_eq; 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, optional (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 this 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 an\n   assignment of items to labels: if there are more items than labels,\n   at least two items must have the same label.  You will almost\n   certainly need to use 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.  intros X l1. induction l1.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ####################################################### *)\n(** * Informal Proofs *)\n\n(** Q: What is the relation between a formal proof of a proposition\n       [P] and an informal proof of the same proposition [P]?\n\n    A: The latter should _teach_ the reader how to produce the\n       former.\n\n    Q: How much detail is needed?\n\n    A: There is no single right answer; rather, there is a range\n       of choices.  \n\n      At one end of the spectrum, we can essentially give the\n      reader the whole formal proof (i.e., the informal proof\n      amounts to just transcribing the formal one into words).\n      This gives the reader the _ability_ to reproduce the formal\n      one for themselves, but it doesn't _teach_ them anything.\n\n      At the other end of the spectrum, we can say \"The theorem\n      is true and you can figure out why for yourself if you\n      think about it hard enough.\"  This is also not a good\n      teaching strategy, because usually writing the proof\n      requires some deep insights into the thing we're proving,\n      and most readers will give up before they rediscover all\n      the same insights as we did.\n\n      In the middle is the golden mean -- a proof that includes\n      all of the essential insights (saving the reader the hard\n      part of work that we went through to find the proof in the\n      first place) and clear high-level suggestions for the more\n      routine parts to save the reader from spending too much\n      time reconstructing these parts (e.g., what the IH says and\n      what must be shown in each case of an inductive proof), but\n      not so much detail that the main ideas are obscured. \n\n   Another key point: if we're talking about a formal proof of a\n   proposition P and an informal proof of P, the proposition P doesn't\n   change.  That is, formal and informal proofs are _talking about the\n   same world_ and they _must play by the same rules_. *)\n\n(* ####################################################### *)\n(** ** Informal Proofs by Induction *)\n\n(** Since we've spent much of this chapter looking \"under the hood\" at\n    formal proofs by induction, now is a good moment to talk a little\n    about _informal_ proofs by induction.\n\n    In the real world of mathematical communication, written proofs\n    range from extremely longwinded and pedantic to extremely brief\n    and telegraphic.  The ideal is somewhere in between, of course,\n    but while you are getting used to the style it is better to start\n    out at the pedantic end.  Also, during the learning phase, it is\n    probably helpful to have a clear standard to compare against.\n    With this in mind, we offer two templates below -- one for proofs\n    by induction over _data_ (i.e., where the thing we're doing\n    induction on lives in [Type]) and one for proofs by induction over\n    _evidence_ (i.e., where the inductively defined thing lives in\n    [Prop]).  In the rest of this course, please follow one of the two\n    for _all_ of your inductive proofs. *)\n\n(** *** Induction Over an Inductively Defined Set *)\n \n(** _Template_: \n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n \n    _Example_:\n \n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if length [[] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of index.\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n            length l = length (x::l') = S (length l'),\n          it suffices to show that \n            index (S (length l')) l' = None.\n]]  \n          But this follows directly from the induction hypothesis,\n          picking [n'] to be length [l'].  [] *)\n \n(** *** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_. \n\n    _Template_:\n \n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n \n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(* ################################################### *)\n(** ** Induction Principles for [/\\] and [\\/] *)\n\n(** The induction principles for conjunction and disjunction are a\n    good illustration of Coq's way of generating simplified induction\n    principles for [Inductive]ly defined propositions, which we\n    discussed in the last chapter.  You try first: *)\n\n(** **** Exercise: 1 star, optional (and_ind_principle) *)\n(** See if you can predict the induction principle for conjunction. *)\n\n(* Check and_ind. *)\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_ind_principle) *)\n(** See if you can predict the induction principle for disjunction. *)\n\n(* Check or_ind. *)\n(** [] *)\n\nCheck and_ind.\n\n(** From the inductive definition of the proposition [and P Q]\n     Inductive and (P Q : Prop) : Prop :=\n       conj : P -> Q -> (and P Q).\n    we might expect Coq to generate this induction principle\n     and_ind_max :\n       forall (P Q : Prop) (P0 : P /\\ Q -> Prop),\n            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->\n            forall a : P /\\ Q, P0 a\n    but actually it generates this simpler and more useful one:\n     and_ind :\n       forall P Q P0 : Prop,\n            (P -> Q -> P0) ->\n            P /\\ Q -> P0\n    In the same way, when given the inductive definition of [or P Q]\n     Inductive or (P Q : Prop) : Prop :=\n       | or_introl : P -> or P Q\n       | or_intror : Q -> or P Q.\n    instead of the \"maximal induction principle\"\n     or_ind_max :\n       forall (P Q : Prop) (P0 : P \\/ Q -> Prop),\n            (forall a : P, P0 (or_introl P Q a)) ->\n            (forall b : Q, P0 (or_intror P Q b)) ->\n            forall o : P \\/ Q, P0 o\n    what Coq actually generates is this:\n     or_ind :\n       forall P Q P0 : Prop,\n            (P -> P0) ->\n            (Q -> P0) ->\n            P \\/ Q -> P0\n]] \n*)\n\n(* ######################################################### *)\n(** ** Explicit Proof Objects for Induction *)\n\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n    \n(** Recall the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\n(* Check nat_ind. *)\n(* ===> \n   nat_ind : forall P : nat -> Prop,\n      P 0%nat -> \n      (forall n : nat, P n -> P (S n)) -> \n      forall n : nat, P n  *)\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n \nPrint nat_ind.  \n(* ===> (after some manual tidying)\n   nat_ind =\n    fun (P : nat -> Type) \n        (f : P 0) \n        (f0 : forall n : nat, P n -> P (S n)) =>\n          fix F (n : nat) : P n :=\n             match n as n0 return (P n0) with\n            | 0 => f\n            | S n0 => f0 n0 (F n0)\n            end.\n*)\n\n(** We can read this as follows: \n     Suppose we have evidence [f] that [P] holds on 0,  and \n     evidence [f0] that [forall n:nat, P n -> P (S n)].  \n     Then we can prove that [P] holds of an arbitrary nat [n] via \n     a recursive function [F] (here defined using the expression \n     form [Fix] rather than by a top-level [Fixpoint] \n     declaration).  [F] pattern matches on [n]: \n      - If it finds 0, [F] uses [f] to show that [P n] holds.\n      - If it finds [S n0], [F] applies itself recursively on [n0] \n         to obtain evidence that [P n0] holds; then it applies [f0] \n         on that evidence to show that [P (S n)] holds. \n    [F] is just an ordinary recursive function that happens to \n    operate on evidence in [Prop] rather than on terms in [Set].\n \n    Aside to those interested in functional programming: You may\n    notice that the [match] in [F] requires an annotation [as n0\n    return (P n0)] to help Coq's typechecker realize that the two arms\n    of the [match] actually return the same type (namely [P n]).  This\n    is essentially like matching over a GADT (generalized algebraic\n    datatype) in Haskell.  In fact, [F] has a _dependent_ type: its\n    result type depends on its argument; GADT's can be used to\n    describe simple dependent types like this.\n \n    We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  Recall our desire to\n    prove that\n\n    [forall n : nat, even n -> ev n].\n \n    Attempts to do this by standard induction on [n] fail, because the\n    induction principle only lets us proceed when we can prove that\n    [even n -> even (S n)] -- which is of course never provable.  What\n    we did earlier in this chapter was a bit of a hack:\n \n    [Theorem even__ev : forall n : nat,\n     (even n -> ev n) /\\ (even (S n) -> ev (S n))].\n \n    We can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n \n *)\n \n Definition nat_ind2 : \n    forall (P : nat -> Prop), \n    P 0 -> \n    P 1 -> \n    (forall n : nat, P n -> P (S(S n))) -> \n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS => \n          fix f (n:nat) := match n return P n with \n                             0 => P0 \n                           | 1 => P1 \n                           | S (S n') => PSS n' (f n') \n                          end.\n \n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive (try\n     it!).\n\n     The [induction ... using] tactic gives a convenient way to\n     specify a non-standard induction principle like this. *)\n \nLemma even__ev' : forall n, even n -> ev n.\nProof. \n intros.  \n induction n as [ | |n'] using nat_ind2. \n  Case \"even 0\". \n    apply ev_0.  \n  Case \"even 1\". \n    inversion H.\n  Case \"even (S(S n'))\". \n    apply ev_SS. \n    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H. \nQed. \n\n(* ######################################################### *)\n(** ** The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is \"why\n    trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard Correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on.\n\n    There are a few additional wrinkles:\n\n    - Since Coq types can themselves be expressions, the checker must\n      normalize these (by using the conversion rules) before\n      comparing them.\n\n    - The checker must make sure that [match] expressions are\n      _exhaustive_.  That is, there must be an arm for every possible\n      constructor.  To see why, consider the following alleged proof\n      object:\n      Definition or_bogus : forall P Q, P \\/ Q -> P :=\n        fun (P Q : Prop) (A : P \\/ Q) =>\n           match A with\n           | or_introl H => H\n           end. \n      All the types here match correctly, but the [match] only\n      considers one of the possible constructors for [or].  Coq's\n      exhaustiveness check will reject this definition.\n\n    - The checker must make sure that each [fix] expression\n      terminates.  It does this using a syntactic check to make sure\n      that each recursive call is on a subexpression of the original\n      argument.  To see why this is essential, consider this alleged\n      proof:\n          Definition nat_false : forall (n:nat), False :=\n             fix f (n:nat) : False := f n. \n      Again, this is perfectly well-typed, but (fortunately) Coq will\n      reject it. *)\n\n(** Note that the soundness of Coq depends only on the correctness of\n    this typechecking engine, not on the tactic machinery.  If there\n    is a bug in a tactic implementation (and this certainly does\n    happen!), that tactic might construct an invalid proof term.  But\n    when you type [Qed], Coq checks the term for validity from\n    scratch.  Only lemmas whose proofs pass the type-checker can be\n    used in further proof developments.  *)\n\n", "meta": {"author": "mikea", "repo": "software-foundations", "sha": "ab5e8e5a51d6f05917e8e740c1173726c4fbf763", "save_path": "github-repos/coq/mikea-software-foundations", "path": "github-repos/coq/mikea-software-foundations/software-foundations-ab5e8e5a51d6f05917e8e740c1173726c4fbf763/sf/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7292296559023426}}
{"text": "Require Import Lia Frap Datatypes.\nRequire Import Compare_dec.\n\nNotation t := nat.\n\nInductive tree :=\n| Leaf (* an empty tree *)\n| Node (d : t) (l r : tree).\n\nNotation compare := Compare_dec.lt_eq_lt_dec.\nNotation Lt := (inleft (left _)) (only parsing).\nNotation Eq := (inleft (right _)) (only parsing).\nNotation Gt := (inright _) (only parsing).\n\nModule Type S.\n  Definition Singleton (v: t) := Node v Leaf Leaf.\n  Fixpoint bst (tr : tree) (s : t -> Prop) : Prop :=\n    match tr with\n    | Leaf => forall x, not (s x)\n    | Node d l r =>\n        s d /\\\n        bst l (fun x => s x /\\ x < d) /\\\n        bst r (fun x => s x /\\ d < x)\n    end.\n\n  Parameter rotate : tree -> tree.\n\n  (*[10%]*) Axiom bst_rotate : forall T s (H : bst T s), bst (rotate T) s.\n\n  Fixpoint insert (a: t) (tr: tree) : tree :=\n    match tr with\n    | Leaf => Singleton a\n    | Node v lt rt =>\n      match compare a v with\n      | Lt => Node v (insert a lt) rt\n      | Eq => tr\n      | Gt => Node v lt (insert a rt)\n      end\n    end.\n\n  Fixpoint rightmost (tr: tree) : option t :=\n    match tr with\n    | Leaf => None\n    | Node v _ rt =>\n      match rightmost rt with\n      | None => Some v\n      | r => r\n      end\n    end.\n\n  Definition is_leaf (tr : tree) : bool :=\n    match tr with Leaf => true | _ => false end.\n\n  Fixpoint delete_rightmost (tr: tree) : tree :=\n    match tr with\n    | Leaf => Leaf\n    | Node v lt rt =>\n      if is_leaf rt\n      then lt\n      else Node v lt (delete_rightmost rt)\n    end.\n\n  Definition merge_ordered lt rt :=\n    match rightmost lt with\n    | Some rv => Node rv (delete_rightmost lt) rt\n    | None => rt\n    end.\n\n  Fixpoint delete (a: t) (tr: tree) : tree :=\n    match tr with\n    | Leaf => Leaf\n    | Node v lt rt =>\n      match compare a v with\n      | Lt => Node v (delete a lt) rt\n      | Eq => merge_ordered lt rt\n      | Gt => Node v lt (delete a rt)\n      end\n    end.\n\n  (*[40%]*) Axiom bst_insert :\n    forall tr s a,\n      bst tr s ->\n      bst (insert a tr) (fun x => s x \\/ x = a).\n\n  (*[50%]*) Axiom bst_delete :\n    forall tr s a, bst tr s ->\n              bst (delete a tr) (fun x => s x /\\ x <> a).\nEnd S.\n\n(* three-way comparisions and [cases] support for them *)\nLtac cases E :=\n  (is_var E; destruct E) ||\n    match type of E with\n    | sumor (sumbool _ _) _ => destruct E as [[]|]\n    | {_} + {_} => destruct E\n    | _ => let Heq := fresh \"Heq\" in\n           destruct E eqn:Heq\n    end;\n   repeat\n    match goal with\n    | H:_ = left _ |- _ => clear H\n    | H:_ = right _ |- _ => clear H\n    | H:_ = inleft _ |- _ => clear H\n    | H:_ = inright _ |- _ => clear H\n    end.\n\n(*|\nTIPS: A few things that might be helpful keep in mind as you work on pset 4\n===========================================================================\n *)\n\n(*|\nPaper proof and reasoning will help\n===================================\nProblem set 4 is a a lot less guided than previous problems: you will need to prove mutiple lemmas for each of the BST theorems, and we did not give the exact statement of each lemma.  Think about the proofs on paper, take each proof slowly, and do not hesitate to prove useful intermediate results as separate lemmas.\n\nAnd if you get stuck, come to office hours!\n *)\n\n(*|\nTake advantage of propositional\n===============================\nWhen writing specifications, you can enable [propositional] to prove more stuff\nby sticking to a minimal convention about which comparison operators you use.\nWe chose to pick [x<y] over [y>x] and [not (y<x)] over [x<=y]. This helps just\na little.\n*)\n\n(*|\nHINTS: A few hints to help you if you get stuck on certain \n       problems in Pset 4.\n       Beware! Don't read further if you don't want spoilers!\n=============================================================\n|*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(*|\nHINT 1: \n=======\nDefinition rotR (T : tree) :=\n  match T with\n  | Node t L R =>\n      match L with\n       | Node l A B => Node l A (Node t B R)\n       | _ => T\n      end\n  | _ => T\n  end.\n\nLemma bst_rotR T S (H : bst T S) : bst (rotR T) S.\nProof.\n  cases T; propositional.\n  cases T1; propositional.\n  simplify; propositional;\n    use_bst_iff_assumption; propositional; linear_arithmetic.\nQed.\nDefinition rotL (T : tree) :=\n  match T with\n  | Node t A R =>\n      match R with\n       | Node r B X => Node r (Node t A B) X\n       | _ => T\n      end\n  | _ => T\n  end.\nLemma bst_rotL T S (H : bst T S) : bst (rotL T) S.\nProof.\n  cases T; propositional.\n  cases T2; propositional.\n  simplify; propositional.\n  { eapply bst_iff.\n    { eassumption. }\n    { propositional.\n      linear_arithmetic. } }\n  { eapply bst_iff; try eassumption. propositional; linear_arithmetic. }\n  { eapply bst_iff; try eassumption. propositional; linear_arithmetic. }\nQed.\n*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(*|\nHINT 2:\n=======\nConsider [cases (rightmost tr2)] or [cases (is_leaf tr2)] instead of [cases\ntr2]. Not breaking apart the tree itself can avoid a mess.\n*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(*|\nHINT 3:\n=======\nA convenient way to specify \"the largest element in this set\" is to say that\nall elements in this set are no larger than the given element.\n*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(*|\nHINT 4:\n=======\nmerge_ordered needs a rather strong preconditon. It does not work correctly\nfor merging just any two trees. However, it is called in a rather specific\nscenario. (And it is feasible to prove its use by inlining it, but we found a\nseparate specification helpful.) Why is it bad to call merge_ordered [3,4] [1,2]?\n*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(*|\nHINT 5:\n=======\nOur proof, if avoiding eapply, contains a couple of long apply-with invocations, for example:\napply bst_iff with (P:=let S := (fun x : t => S x /\\ d < x) in (fun x : t => S x /\\ x < rm)).\n*)\n", "meta": {"author": "mit-frap", "repo": "spring22", "sha": "48a93f5874695099627e717ab44c77be4d7bd02a", "save_path": "github-repos/coq/mit-frap-spring22", "path": "github-repos/coq/mit-frap-spring22/spring22-48a93f5874695099627e717ab44c77be4d7bd02a/pset04_BSTs/Pset4Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8376199694135333, "lm_q1q2_score": 0.72922964889889}}
{"text": "Set Warnings \"-notaion-overridden, -parsing\".\nFrom LF Require Export Tactics.\n\nCheck forall n : nat, pred (S n) = n.\nCheck fun n: nat => S (pred n) = n.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H.\n  injection H as H1. apply H1.\nQed.\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nSearch plus.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  split.\n  - destruct n.\n    + reflexivity.\n    + destruct m.\n      discriminate.\n      discriminate.\n  - destruct m.\n    reflexivity.\n    destruct n.\n    discriminate.\n    discriminate.\nQed.\n\nExample and_exercise' :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H.\n  split.\n  - destruct n.\n    + reflexivity.\n    + destruct m.\n      * inversion H.\n      * inversion H.\n  - destruct m.\n    + reflexivity.\n    + destruct n.\n      * inversion H.\n      * inversion H.\nQed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nTheorem and_commut : forall P Q : Prop,\n    P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n  - apply HQ.\n  - apply HP.\nQed.\n\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.\n  split.\n  apply HP.\n  apply HQ.\n  apply HR.\nQed.\n\nLemma eq_mult_0 :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m [Hn | Hm].\n  - rewrite Hn. reflexivity.\n  - rewrite Hm. rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\nLemma mult_eq_0:\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros.\n  destruct n.\n  - left. reflexivity.\n  - destruct m.\n    + right. reflexivity.\n    + simpl in H. discriminate H.\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 zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n'].\n  - left. reflexivity.\n  - right. simpl. reflexivity.\nQed.\n\nModule MyNot.\n\n  Definition not (P : Prop) := P -> False.\n  Notation \"~ x\" := (not x) : type_scope.\n  Check not : Prop -> Prop.\n\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n    False -> P.\nProof.\n  intros P contra.\n  destruct contra.\nQed.\n\nFact not_implies_our_not : forall (P : Prop),\n    not P -> (forall (Q: Prop), P -> Q).\nProof.\n  intros.\n  destruct H.\n  apply H0.\nQed.\n\nNotation \"x <> y\" := (~(x = y)).\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not.\n  intros.\n  destruct H.\nQed.\n\nTheorem not_False :\n  not False.\nProof.\n  unfold not.\n  intros H.\n  destruct H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n    (P /\\ not P) -> Q.\nProof.\n  intros P Q [HP HNA].\n  unfold not in HNA.\n  apply HNA in HP.\n  destruct HP.\nQed.\n\nTheorem double_neg : forall P : Prop,\n    P -> ~~P.\nProof.\n  intros P H.\n  unfold not.\n  intros G. apply G. apply H.\nQed.\n\nTheorem contrapositive : forall (P Q : Prop),\n    (P -> Q) -> (not Q -> not P).\nProof.\n  intros.\n  unfold not.\n  intros.\n  apply H in H1.\n  unfold not in H0.\n  apply H0 in H1.\n  destruct H1.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n    not (P /\\ not P).\nProof.\n  intros.\n  unfold not.\n  intros [H1 H2].\n  apply H2 in H1.\n  destruct H1.\nQed.\n\nTheorem not_true_is_false : forall b : bool,\n    b <> true -> b = false.\nProof.\n  intros b H.\n  destruct b eqn:HE.\n  - (* b = True *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem not_true_is_false' : forall b : bool,\n    b <> true -> b = false.\nProof.\n  intros [] H.\n  - unfold not.\n    exfalso.\n    apply H. reflexivity.\n  - reflexivity.\nQed.\n\nModule MyIff.\n  Definition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\n  Notation \"P <-> Q\" := (iff P Q)\n                          (at level 95, no associativity)\n                          : type_scope.\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n    (P <-> Q) -> (Q <-> P).\nProof.\n  intros.\n  split.\n  - apply H.\n  - apply H.\nQed.\n\nLemma not_true_iff_false : forall b,\n    b <> true <-> b = false.\nProof.\n  intros. split.\n  - intros. apply not_true_is_false. apply H.\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  intros P Q R.\n  split.\n  - intros [H1 | [H2 H3]].\n    + split.\n      * left. apply H1.\n      * left. apply H1.\n    + split.\n      * right. apply H2.\n      * right. apply H3.\n  - intros [[H1 | H2] [H3 | H4]].\n    + left. apply H1.\n    + left. apply H1.\n    + left. apply H3.\n    + right. split.\n      * apply H2.\n      * apply H4.\nQed.\n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply eq_mult_0.\nQed.\n\nTheorem or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R.\n  split.\n  - intros [H1 | [H2 | H3]].\n    + left. left. apply H1.\n    + left. right. apply H2.\n    + right. apply H3.\n  - intros [[H1 | H2] | H3].\n    + left. apply H1.\n    + right. left. apply H2.\n    + right. right. apply H3.\nQed.\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0.\n  rewrite or_assoc.\n  reflexivity.\nQed.\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H.\n  apply mult_0. apply H.\nQed.\n\nDefinition even x := exists n : nat, x = double n.\n\nLemma four_is_even :\n  even 4.\nProof.\n  unfold even.\n  exists 2.\n  reflexivity.\nQed.\n\nTheorem exists_example_2 : forall n,\n    (exists m, n = 4 + m) -> (exists o, n = 2 + o).\nProof.\n  intros n [m Hm].\n  exists (2 + m).\n  simpl.\n  apply Hm.\nQed.\n\nTheorem dist_not_exists : forall (X : Type) (P : X -> Prop),\n    (forall x, P x) -> not (exists x, not (P x)).\nProof.\n  intros X P H.\n  unfold not.\n  intros [x H0].\n  apply H0.\n  apply H.\nQed.\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  intros X P Q.\n  split.\n  - intros [x [H1 | H2]].\n    + left. exists x. apply H1.\n    + right. exists x. apply H2.\n  - intros [[x1 H1] | [x2 H2]].\n    + exists x1. left. apply H1.\n    + exists x2. right. apply H2.\nQed.\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\nExample In_example_l : In 4 [1;2;3;4;5].\nProof.\n  simpl. right. right. right. left.\n  reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2;4] -> exists n', n = 2 * n'.\nProof.\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\nTheorem In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l -> In (f x) (map f l).\nProof.\n  intros until x.\n  induction l as [| x' l' IHl'].\n  - simpl. intros. apply H.\n  - simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\nCheck plus_comm.\n\nTheorem in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H.\n  unfold not.\n  intros.\n  rewrite H0 in H.\n  simpl in H.\n  apply H.\nQed.\n\nAxiom functional_extensionality : forall {X Y : Type}\n                                    {f g : X -> Y},\n    (forall (x : X), f x = g x) -> f = g.\n\nExample function_extensionality_ex2:\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality.\n  intros.\n  apply plus_comm.\nQed.\n\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\nLemma tr_rev_lemma:\n  forall X (l1 l2 : list X),\n    rev_append l1 l2 = rev l1 ++ l2.\nProof.\n  intros X l1.\n  induction l1.\n  - intros l2. reflexivity.\n  - intros l2. simpl. rewrite <- app_assoc. simpl. apply IHl1.\nQed.\n\nTheorem tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros.\n  apply functional_extensionality.\n  intros.\n  unfold tr_rev.\n  rewrite tr_rev_lemma.\n  apply app_nil_r.\nQed.\n\nCheck app_nil_r.\n\nLemma evenb_double : forall k, evenb (double k) = true.\nProof.\n  intros.\n  induction k.\n  - simpl. reflexivity.\n  - simpl. apply IHk.\nQed.\n\nCheck evenb_S.\n\nSearch double.\n\nLemma evenb_double_conv : forall n, exists k,\n      n = if evenb n\n          then double k\n          else S (double k).\nProof.\n  intros.\n  induction n.\n  - simpl. exists 0. reflexivity.\n  - rewrite evenb_S. simpl.\n    destruct (evenb n) eqn:E.\n    + simpl. destruct IHn as [k H].\n      rewrite H. exists k. reflexivity.\n    + simpl. destruct IHn. exists (S x).\n      rewrite H. reflexivity.\nQed.\n\nCheck even.\n\nTheorem even_bool_prop : forall n,\n    evenb n = true <-> even n.\nProof.\n  intros n.\n  split.\n  - intros. destruct (evenb_double_conv n) as [k Hk].\n    rewrite H in Hk. rewrite Hk. simpl. exists k. reflexivity.\n  - intros [k Hk]. rewrite Hk. apply evenb_double.\nQed.\n\nTheorem eqb_eq : forall n1 n2 : nat,\n    n1 =? n2 = true <-> n1 = n2.\nProof.\n  Admitted.\n\nLemma plus_eqb_example : forall n m p: nat,\n    n =? m = true -> n + p =? m + p = true.\nProof.\n  Admitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "juniorxxue", "repo": "software-foundations", "sha": "e3f94a307eac2f0be0a5aa91f76abcfcb0b856ce", "save_path": "github-repos/coq/juniorxxue-software-foundations", "path": "github-repos/coq/juniorxxue-software-foundations/software-foundations-e3f94a307eac2f0be0a5aa91f76abcfcb0b856ce/lf/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7292296488988899}}
{"text": "(* _rec を使った関数定義 *)\n(* お茶大 浅井研、Coqゼミ 第5回 を参考にした。 *)\n\n\n(* one *)\n\n\nInductive one : Set :=\n  | One : one.                              (* : one は省略できる。 *)\n\n\nPrint one.\nCheck one.\nCheck One.\nPrint one_ind.\nCheck one_ind.\nPrint one_rec.\nCheck one_rec.\n\n\nDefinition f_one :=\n  one_rec (fun n : one => nat) 1.\nCheck f_one.\nEval compute in f_one One.                  (* 1 *)\n\n\nDefinition f_one' (m : nat) :=\n  one_rec (fun n : one => nat) m.\nCheck f_one'.\nEval compute in f_one'.\nEval compute in f_one' 11 One.              (* 11 *)\n\n\nDefinition f_one'' (m : nat) :=\n  one_rec (fun f : one => nat -> nat)\n    (fun n : nat => m + 1).\nCheck f_one''.\nEval compute in f_one''.\nEval compute in f_one'' 111 One.            (* 112 *)\n\n\n(* season *)\n\n\nInductive season : Set :=\n  | Spring : season\n  | Summer : season\n  | Fall : season\n  | Winter : season.\n\n\nPrint season_ind.\nCheck season_ind.\nPrint season_rec.\nCheck season_rec.\n\n\nDefinition f :=\n  season_rec (fun s : season => nat)\n    0 1 2 3.\n\n\nEval compute in f Spring.                   (* 0 *)\nEval compute in f Summer.                   (* 1 *)\nEval compute in f Fall.                     (* 2 *)\nEval compute in f Winter.                   (* 3 *)\n\n\n\n\n(* nat *)\n\n\nPrint nat_ind.\nCheck nat_ind.\nPrint nat_rec.\nCheck nat_rec.\n\n\nDefinition plus (m : nat) :=\n  nat_rec (fun n : nat => nat)\n   m\n   (fun (n : nat) (x : nat) => S x).\n\n\nEval compute in plus 1 2.                   (* 3 *)\n  \n  \nLemma plus_n_0 : forall n : nat, n = n + 0.\n  intros.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite <- IHn.\n  reflexivity.\n  Restart.\n\n\n  intros.\n  apply nat_ind with (n := n).\n  simpl.\n  reflexivity.\n  intros.                                   (* *** *)\n  simpl.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n\n\n\n(** おまけ **)\n\n\nDefinition pred_spec (n : nat) :=\n  {m : nat | n = 0 /\\ m = 0 \\/ n = S m}.\n\n\nDefinition predecessor : forall n : nat, pred_spec n.\n  intros n.\n  apply nat_rec with (n := n).              (* case n *)\n  (* ！！しかし、nat_ind ではだめであることに、注意！！ *)\n  \n  (* Goal : pred_spec 0 *)\n  unfold pred_spec.\n  exists 0.\n  auto.\n\n\n  (* Goal : forall n0 : nat, pred_spec n0 -> pred_spec (S n0) *)\n  intros.\n  unfold pred_spec.\n  exists n0.\n  auto.\nQed.\n\n\nPrint predecessor.\n\n\n(* END *)", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/coq__rec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7291670039392711}}
{"text": "(** * Logic: Logic in Coq *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export Tactics.\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 ([forall\n    x, P]).  In this chapter, we will see how Coq can be used to carry\n    out other familiar forms of logical reasoning.\n\n    Before diving into details, let's talk a bit about the status of\n    mathematical statements in Coq.  Recall that Coq is a _typed_\n    language, which means that every sensible expression in its world\n    has an associated type.  Logical claims are no exception: any\n    statement we might try to prove in Coq has a type, namely [Prop],\n    the type of _propositions_.  We can see this with the [Check]\n    command: *)\n\nCheck 3 = 3.\n(* ===> Prop *)\n\nCheck forall n m : nat, n + m = m + n.\n(* ===> Prop *)\n\n(** Note that _all_ syntactically well-formed propositions have type\n    [Prop] in Coq, regardless of whether they are true or not. *)\n\n(** Simply _being_ a proposition is one thing; being _provable_ is\n    something else! *)\n\nCheck 2 = 2.\n(* ===> Prop *)\n\nCheck forall n : nat, n = 2.\n(* ===> Prop *)\n\nCheck 3 = 4.\n(* ===> Prop *)\n\n(** Indeed, propositions don't just have types: they are\n    _first-class objects_ that can be manipulated in the same ways as\n    the other entities in Coq's world. *)\n\n(** So far, we've seen one primary place that propositions can appear:\n    in [Theorem] (and [Lemma] and [Example]) declarations. *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\n(** But propositions can be used in many other ways.  For example, we\n    can give a name to a proposition using a [Definition], just as we\n    have 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 can also write _parameterized_ propositions -- that is,\n    functions that take arguments of some type and return a\n    proposition. *)\n\n(** For instance, the following function takes a number\n    and returns a proposition asserting that this number is equal to\n    three: *)\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n(* ===> nat -> Prop *)\n\n(** In Coq, functions that return propositions are said to define\n    _properties_ of their arguments. \n\n    For instance, here's a (polymorphic) property defining the\n    familiar notion of an _injective function_. *)\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\n\n(** The equality operator [=] is also a function that returns a\n    [Prop].\n\n    The expression [n = m] is syntactic sugar for [eq n m], defined\n    using Coq's [Notation] mechanism. Because [eq] can be used with\n    elements of any type, it is also polymorphic: *)\n\nCheck @eq.\n(* ===> forall A : Type, A -> A -> Prop *)\n\n(** (Notice that we wrote [@eq] instead of [eq]: The type\n    argument [A] to [eq] is declared as implicit, so we need to turn\n    off implicit arguments to see the full type of [eq].) *)\n\n(* ################################################################# *)\n(** * Logical Connectives *)\n\n(* ================================================================= *)\n(** ** Conjunction *)\n\n(** The _conjunction_ (or _logical and_) of propositions [A] and [B]\n    is written [A /\\ B], representing the claim that both [A] and [B]\n    are true. *)\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\n\n(** To prove a conjunction, use the [split] tactic.  It will generate\n    two subgoals, one for each part of the statement: *)\n\nProof.\n  (* WORKED IN CLASS *)\n  split.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** For any propositions [A] and [B], if we assume that [A] is true\n    and we assume that [B] is true, we can conclude that [A /\\ B] is\n    also true. *)\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\n\n(** Since applying a theorem with hypotheses to some goal has the\n    effect of generating as many subgoals as there are hypotheses for\n    that theorem, we can apply [and_intro] to achieve the same effect\n    as [split]. *)\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - (* 3 + 4 = 7 *) reflexivity.\n  - (* 2 + 2 = 4 *) reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H. split.\n  destruct n as [|n'] eqn:H1.\n  { reflexivity. } { simpl in H. inversion H. }\n  destruct m as [|m'].\n  { reflexivity. } { simpl in H. rewrite <- plus_n_Sm in H. inversion H. }\nQed.\n(** [] *)\n\n(** So much for proving conjunctive statements.  To go in the other\n    direction -- i.e., to _use_ a conjunctive hypothesis to help prove\n    something else -- we employ the [destruct] tactic.\n\n    If the proof context contains a hypothesis [H] of the form\n    [A /\\ B], writing [destruct H as [HA HB]] will remove [H] from the\n    context and add two new hypotheses: [HA], stating that [A] is\n    true, and [HB], stating that [B] is true.  *)\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** As usual, we can also destruct [H] right when we introduce it,\n    instead of introducing and then destructing it: *)\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** You may wonder why we bothered packing the two hypotheses [n = 0]\n    and [m = 0] into a single conjunction, since we could have also\n    stated the theorem with two separate premises: *)\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\n(** For this theorem, both formulations are fine.  But it's important\n    to understand how to work with conjunctive hypotheses because\n    conjunctions often arise from intermediate steps in proofs,\n    especially in bigger developments.  Here's a simple example: *)\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\n(** Another common situation with conjunctions is that we know\n    [A /\\ B] but in some context we need just [A] (or just [B]).\n    The following lemmas are useful in such cases: *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ]. apply HQ.\nQed.\n(** [] *)\n\n(** Finally, we sometimes need to rearrange the order of conjunctions\n    and/or the grouping of multi-way conjunctions.  The following\n    commutativity and associativity theorems are handy in such\n    cases. *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HQ].\n  split.\n    - (* left *) apply HQ.\n    - (* right *) apply HP.  Qed.\n  \n(** **** Exercise: 2 stars (and_assoc)  *)\n(** (In the following proof of associativity, notice how the _nested_\n    intro pattern breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP : P], [HQ : Q], and [HR : R].  Finish the proof from\n    there.) *)\n\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.\n  - split. apply HP. apply HQ.\n  - apply HR.\nQed.\n(** [] *)\n\n(** By the way, the infix notation [/\\] is actually just syntactic\n    sugar for [and A B].  That is, [and] is a Coq operator that takes\n    two propositions as arguments and yields a proposition. *)\n\nCheck and.\n(* ===> and : Prop -> Prop -> Prop *)\n\n(* ================================================================= *)\n(** ** Disjunction *)\n\n(** Another important connective is the _disjunction_, or _logical or_\n    of two propositions: [A \\/ B] is true when either [A] or [B]\n    is.  (Alternatively, we can write [or A B], where [or : Prop ->\n    Prop -> Prop].) *)\n\n(** To use a disjunctive hypothesis in a proof, we proceed by case\n    analysis, which, as for [nat] or other data types, can be done\n    with [destruct] or [intros].  Here is an example: *)\n\nLemma or_example :\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(** Conversely, to show that a disjunction holds, we need to show that\n    one of its sides does. This is done via two tactics, [left] and\n    [right].  As their names imply, the first one requires\n    proving the left side of the disjunction, while the second\n    requires proving its right side.  Here is a trivial use... *)\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\n(** ... and a slightly more interesting example requiring both [left]\n    and [right]: *)\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(** **** Exercise: 1 star (mult_eq_0)  *)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. destruct n as [|n'].\n  - left. reflexivity.\n  - destruct m as [|m'].\n    + right. reflexivity.\n    + left. simpl in H. inversion H.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (or_commut)  *)\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q [HP | HQ].\n  - right. apply HP.\n  - left. apply HQ.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Falsehood and Negation *)\n\n(** So far, we have mostly been concerned with proving that certain\n    things are _true_ -- addition is commutative, appending lists is\n    associative, etc.  Of course, we may also be interested in\n    _negative_ results, showing that certain propositions are _not_\n    true. In Coq, such negative statements are expressed with the\n    negation operator [~]. *)\n\n(** To see how negation works, recall the discussion of the _principle\n    of explosion_ from the [Tactics] chapter; it asserts that, if we\n    assume a contradiction, then any other proposition can be derived.\n    Following this intuition, we could define [~ P] (\"not [P]\") as\n    [forall Q, P -> Q].  Coq actually makes a slightly different\n    choice, defining [~ P] as [P -> False], where [False] is a\n    particular contradictory proposition defined in the standard\n    library. *)\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\nEnd MyNot.\n\n(** Since [False] is a contradictory proposition, the principle of\n    explosion also applies to it. If we get [False] into the proof\n    context, we can use [destruct] (or [inversion]) on it to complete\n    any goal: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from falsehood\n    follows whatever you like\"; this is another common name for the\n    principle of explosion. *)\n\n(** **** Exercise: 2 stars, optional (not_implies_our_not)  *)\n(** Show that Coq's definition of negation implies the intuitive one\n    mentioned above: *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros P Hn Q HP. destruct Hn. apply HP.\nQed.\n(** [] *)\n\n(** This is how we use [not] to state that [0] and [1] are different\n    elements of [nat]: *)\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra. inversion contra.\nQed.\n\n(** Such inequality statements are frequent enough to warrant a\n    special notation, [x <> y]: *)\n\nCheck (0 <> 1).\n(* ===> Prop *)\n\nTheorem zero_not_one' : 0 <> 1.\nProof.\n  intros H. inversion H.\nQed.\n\n(** It takes a little practice to get used to working with negation in\n    Coq.  Even though you can see perfectly well why a statement\n    involving negation is true, it can be a little tricky at first to\n    get things into the right configuration so that Coq can understand\n    it!  Here are proofs of a few familiar facts to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced, recommended (double_neg_inf)  *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (contrapositive)  *)\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H1 H2. unfold not. unfold not in H2. intros HP.\n  apply H2. apply H1. apply HP.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false)  *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P. unfold not. intros [HP HNP].\n  apply HNP. apply HP.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** Similarly, since inequality involves a negation, it requires a\n    little practice to be able to work with it fluently.  Here is one\n    useful trick.  If you are trying to prove a goal that is\n    nonsensical (e.g., the goal state is [false = true]), apply\n    [ex_falso_quodlibet] to change the goal to [False].  This makes it\n    easier to use assumptions of the form [~P] that may be available\n    in the context -- in particular, assumptions of the form\n    [x<>y]. *)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\n(** Since reasoning with [ex_falso_quodlibet] is quite common, Coq\n    provides a built-in tactic, [exfalso], for applying it. *)\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = false *)\n    unfold not in H.\n    exfalso.                (* <=== *)\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\n\n(* ================================================================= *)\n(** ** Truth *)\n\n(** Besides [False], Coq's standard library also defines [True], a\n    proposition that is trivially true. To prove it, we use the\n    predefined constant [I : True]: *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n(** Unlike [False], which is used extensively, [True] is used quite\n    rarely, since it is trivial (and therefore uninteresting) to prove\n    as a goal, and it carries no useful information as a hypothesis.\n    But it can be quite useful when defining complex [Prop]s using\n    conditionals or as a parameter to higher-order [Prop]s.  We will\n    see examples of such uses of [True] later on.\n*)\n\n(* ================================================================= *)\n(** ** Logical Equivalence *)\n\n(** The handy \"if and only if\" connective, which asserts that two\n    propositions have the same truth value, is just the conjunction of\n    two implications. *)\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\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.  Qed.\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'. inversion H'.\nQed.\n\n(** **** Exercise: 1 star, optional (iff_properties)  *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros P. split.\n  - intros HP. apply HP.\n  - intros HP. apply HP.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R [HPQ HQP] [HQR HRQ]. split.\n  - intros HP. apply HQR. apply HPQ. apply HP.\n  - intros HR. apply HQP. apply HRQ. apply HR.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. split.\n  - intros [HP|[HQ HR]].\n    + split. { left. apply HP. } { left. apply HP. }\n    + split. { right. apply HQ. } { right. apply HR. }\n  - intros [[HP|HQ] [HP'|HR]].\n    + left. apply HP. + left. apply HP.\n    + left. apply HP'. + right. split. apply HQ. apply HR.\nQed.\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, avoiding\n    the need for some low-level proof-state manipulation.  In\n    particular, [rewrite] and [reflexivity] can be used with [iff]\n    statements, not just equalities.  To enable this behavior, we need\n    to import a special Coq library that allows rewriting with other\n    formulas besides equality: *)\n\nRequire Import Coq.Setoids.Setoid.\n\n(** Here is a simple example demonstrating how these tactics work with\n    [iff].  First, let's prove a couple of basic iff equivalences... *)\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. 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\n(** We can now use these facts with [rewrite] and [reflexivity] to\n    give smooth proofs of statements involving equivalences.  Here is\n    a ternary version of the previous [mult_0] result: *)\n\nLemma mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\n(** The [apply] tactic can also be used with [<->]. When given an\n    equivalence as its argument, [apply] tries to guess which side of\n    the equivalence to use. *)\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\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(** 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  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 (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  intros X P H. unfold not. intros [x H2].\n  apply H2. apply H.\nQed.\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  intros X P Q. split.\n  - intros [x [HPx|HQx]].\n    { left. exists x. apply HPx. }\n    { right. exists x. apply HQx. }\n  - intros [[x HPx]|[x HQx]].\n    { exists x. left. apply HPx. }\n    { exists x. right. apply HQx. }\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Programming with Propositions *)\n\n(** The logical connectives that we have seen provide a rich\n    vocabulary for defining complex propositions from simpler ones.\n    To illustrate, let's look at how to express the claim that an\n    element [x] occurs in a list [l].  Notice that this property has a\n    simple recursive structure: *)\n(**    - If [l] is the empty list, then [x] cannot occur on it, so the\n         property \"[x] appears in [l]\" is simply false. *)\n(**    - Otherwise, [l] has the form [x' :: l'].  In this case, [x]\n         occurs in [l] if either it is equal to [x'] or it occurs in\n         [l']. *)\n\n(** We can translate this directly into a straightforward recursive\n    function from taking an element and a list and returning a\n    proposition: *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\n(** When [In] is applied to a concrete list, it expands into a\n    concrete sequence of nested disjunctions. *)\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  (* WORKED IN CLASS *)\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  (* WORKED IN CLASS *)\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n(** (Notice the use of the empty pattern to discharge the last case\n    _en passant_.) *)\n\n(** We can also prove more generic, higher-level lemmas about [In].\n\n    Note, in the next, how [In] starts out applied to a variable and\n    only gets expanded when we do case analysis on this variable: *)\n\nLemma 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.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(** This way of defining propositions recursively, though convenient\n    in some cases, also has some drawbacks.  In particular, it is\n    subject to Coq's usual restrictions regarding the definition of\n    recursive functions, e.g., the requirement that they be \"obviously\n    terminating.\"  In the next chapter, we will see how to define\n    propositions _inductively_, a different technique with its own set\n    of strengths and limitations. *)\n\n(** **** Exercise: 2 stars (In_map_iff)  *)\nLemma 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  - induction l as [|h t IHl].\n    { simpl. intros []. }\n    { intros [H1|H1].\n      - exists h. split.\n        + apply H1.\n        + left. reflexivity.\n      - apply IHl in H1. inversion H1. inversion H.\n        exists x. split.\n        + apply H0. + simpl. right. apply H2.\n    }\n  - induction l as [|h t IHl].\n    { simpl. intros [x [_ []]]. }\n    { intros [x [H1 H2]]. simpl in H2.\n      inversion H2.\n      - simpl. left. rewrite H. apply H1.\n      - simpl. right. apply IHl. exists x.\n        + split. apply H1. apply H.\n    }\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (in_app_iff)  *)\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a. split.\n  - (* In a (l++l') -> In a l \\/ In a l' *)\n    intros H. induction l as [|h t IHl].\n    + simpl in H. right. apply H.\n    + simpl in H. inversion H.\n      { rewrite H0. simpl. left. left. reflexivity. }\n      { apply IHl in H0. inversion H0.\n        { simpl. left. right. apply H1. }\n        { right. apply H1. }\n      }\n  - (* In a l \\/ In a l' -> In a (l++l') *)\n    intros [Hel|Hel'].\n    { induction l as [|h t IHl].\n      - simpl. simpl in Hel. exfalso. apply Hel.\n      - simpl. simpl in Hel. inversion Hel as [H1|H2].\n        + left. apply H1.\n        + right. apply IHl. apply H2.\n    }\n    { induction l as [|h t IHl].\n      - simpl. apply Hel'.\n      - simpl. right. apply IHl.\n    }\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (All)  *)\n(** Recall that functions returning propositions can be seen as\n    _properties_ of their arguments. For instance, if [P] has type\n    [nat -> Prop], then [P n] states that property [P] holds of [n].\n\n    Drawing inspiration from [In], write a recursive function [All]\n    stating that some property [P] holds of all elements of a list\n    [l]. To make sure your definition is correct, prove the [All_In]\n    lemma below.  (Of course, your definition should _not_ just\n    restate the left-hand side of [All_In].) *)\n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n  | nil => True\n  | h :: t => P h /\\ All P t\n  end.\n\nLemma 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 T P l. split.\n  - (* _ -> All P l *)\n    induction l as [|h t IHl].\n    + simpl. intros _. apply I.\n    + simpl. intros H. split.\n      { apply H. left. reflexivity. }\n      { apply IHl. intros x H1.\n        apply H. right. apply H1. }\n  - (* All P l -> _ *)\n    induction l as [|h t IHl].\n    + simpl. intros _ x [].\n    + simpl. intros [H1 H2] x. intros [H3|H3].\n      { rewrite <- H3. apply H1. }\n      { apply IHl. apply H2. apply H3. }\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (combine_odd_even)  *)\n(** Complete the definition of the [combine_odd_even] function below.\n    It takes as arguments two properties of numbers, [Podd] and\n    [Peven], and it should return a property [P] such that [P n] is\n    equivalent to [Podd n] when [n] is odd and equivalent to [Peven n]\n    otherwise. *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\n  fun n =>\n    match oddb n with\n    | true => Podd n\n    | false => Peven n\n    end.\n\n(** To test your definition, prove the following 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 Ht Hf. unfold combine_odd_even.\n  destruct (oddb n).\n  - apply Ht. reflexivity.\n  - apply Hf. 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 Podd Peven n H1 H2. unfold combine_odd_even in H1.\n  destruct (oddb n).\n  - apply H1.\n  - inversion H2.\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 Podd Peven n H1 H2. unfold combine_odd_even in H1.\n  destruct (oddb n).\n  - inversion H2. - apply H1.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Applying Theorems to Arguments *)\n\n(** One feature of Coq that distinguishes it from many other proof\n    assistants is that it treats _proofs_ as first-class objects.\n\n    There is a great deal to be said about this, but it is not\n    necessary to understand it in detail in order to use Coq.  This\n    section gives just a taste, while a deeper exploration can be\n    found in the optional chapters [ProofObjects] and\n    [IndPrinciples]. *)\n\n(** We have seen that we can use the [Check] command to ask Coq to\n    print the type of an expression.  We can also use [Check] to ask\n    what theorem a particular identifier refers to. *)\n\nCheck plus_comm.\n(* ===> forall n m : nat, n + m = m + n *)\n\n(** Coq prints the _statement_ of the [plus_comm] theorem in the same\n    way that it prints the _type_ of any term that we ask it to\n    [Check].  Why? *)\n\n(**  The reason is that the identifier [plus_comm] actually refers to a\n    _proof object_ -- a data structure that represents a logical\n    derivation establishing of the truth of the statement [forall n m\n    : nat, n + m = m + n].  The type of this object _is_ the statement\n    of the theorem that it is a proof of. *)\n\n(** Intuitively, this makes sense because the statement of a theorem\n    tells us what we can use that theorem for, just as the type of a\n    computational object tells us what we can do with that object --\n    e.g., if we have a term of type [nat -> nat -> nat], we can give\n    it two [nat]s as arguments and get a [nat] back.  Similarly, if we\n    have an object of type [n = m -> n + n = m + m] and we provide it\n    an \"argument\" of type [n = m], we can derive [n + n = m + m]. *)\n\n(** Operationally, this analogy goes even further: by applying a\n    theorem, as if it were a function, to hypotheses with matching\n    types, we can specialize its result without having to resort to\n    intermediate assertions.  For example, suppose we wanted to prove\n    the following result: *)\n\nLemma plus_comm3 :\n  forall n m p, n + (m + p) = (p + m) + n.\n\n(** It appears at first sight that we ought to be able to prove this\n    by rewriting with [plus_comm] twice to make the two sides match.\n    The problem, however, is that the second [rewrite] will undo the\n    effect of the first. *)\n\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite plus_comm.\n  (* We are back where we started... *)\nAbort.\n\n(** One simple way of fixing this problem, using only tools that we\n    already know, is to use [assert] to derive a specialized version\n    of [plus_comm] that can be used to rewrite exactly where we\n    want. *)\n\nLemma plus_comm3_take2 :\n  forall n m p, n + (m + p) = (p + m) + n.\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  assert (H : m + p = p + m).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\n(** A more elegant alternative is to apply [plus_comm] directly to the\n    arguments we want to instantiate it with, in much the same way as\n    we apply a polymorphic function to a type argument. *)\n\nLemma plus_comm3_take3 :\n  forall n m p, n + (m + p) = (p + m) + n.\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite (plus_comm m).\n  reflexivity.\nQed.\n\n(** You can \"use theorems as functions\" in this way with almost all\n    tactics that take a theorem name as an argument.  Note also that\n    theorem application uses the same inference mechanisms as function\n    application; thus, it is possible, for example, to supply\n    wildcards as arguments to be inferred, or to declare some\n    hypotheses to a theorem as implicit by default.  These features\n    are illustrated in the proof below. *)\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(** We will see many more examples of the idioms from this section in\n    later chapters. *)\n\n(* ################################################################# *)\n(** * Coq vs. Set Theory *)\n\n(** Coq's logical core, the _Calculus of Inductive Constructions_,\n    differs in some important ways from other formal systems that are\n    used by mathematicians for writing down precise and rigorous\n    proofs.  For example, in the most popular foundation for\n    mainstream paper-and-pencil mathematics, Zermelo-Fraenkel Set\n    Theory (ZFC), a mathematical object can potentially be a member of\n    many different sets; a term in Coq's logic, on the other hand, is\n    a member of at most one type.  This difference often leads to\n    slightly different ways of capturing informal mathematical\n    concepts, but these are, by and large, quite natural and easy to\n    work with.  For example, instead of saying that a natural number\n    [n] belongs to the set of even numbers, we would say in Coq that\n    [ev n] holds, where [ev : nat -> Prop] is a property describing\n    even numbers.\n\n    However, there are some cases where translating standard\n    mathematical reasoning into Coq can be either cumbersome or\n    sometimes even impossible, unless we enrich the core logic with\n    additional axioms.  We conclude this chapter with a brief\n    discussion of some of the most significant differences between the\n    two worlds. *)\n\n(* ================================================================= *)\n(** ** Functional Extensionality *)\n\n(** The equality assertions that we have seen so far mostly have\n    concerned elements of inductive types ([nat], [bool], etc.).  But\n    since Coq's equality operator is polymorphic, these are not the\n    only possibilities -- in particular, we can write propositions\n    claiming that two _functions_ are equal to each other: *)\n\nExample function_equality_ex1 : plus 3 = plus (pred 4).\nProof. reflexivity. Qed.\n\n(** In common mathematical practice, two functions [f] and [g] are\n    considered equal if they produce the same outputs:\n\n    (forall x, f x = g x) -> f = g\n\n    This is known as the principle of _functional extensionality_.\n\n    Informally speaking, an \"extensional property\" is one that\n    pertains to an object's observable behavior.  Thus, functional\n    extensionality simply means that a function's identity is\n    completely determined by what we can observe from it -- i.e., in\n    Coq terms, the results we obtain after applying it.\n\n    Functional extensionality is not part of Coq's basic axioms.  This\n    means that some \"reasonable\" propositions are not provable. *)\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n   (* Stuck *)\nAbort.\n\n(** However, we can add functional extensionality to Coq's core logic\n    using the [Axiom] command. *)\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\n(** Using [Axiom] has the same effect as stating a theorem and\n    skipping its proof using [Admitted], but it alerts the reader that\n    this isn't just something we're going to come back and fill in\n    later! *)\n\n(** We can now invoke functional extensionality in proofs: *)\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply plus_comm.\nQed.\n\n(** Naturally, we must be careful when adding new axioms into Coq's\n    logic, as they may render it _inconsistent_ -- that is, they may\n    make it possible to prove every proposition, including [False]!\n\n    Unfortunately, there is no simple way of telling whether an axiom\n    is safe to add: hard work is generally required to establish the\n    consistency of any particular combination of axioms.\n\n    However, it is known that adding functional extensionality, in\n    particular, _is_ consistent. *)\n\n(** To check whether a particular proof relies on any additional\n    axioms, use the [Print Assumptions] command.  *)\n\nPrint Assumptions function_equality_ex2.\n(* ===>\n     Axioms:\n     functional_extensionality :\n         forall (X Y : Type) (f g : X -> Y),\n                (forall x : X, f x = g x) -> f = g *)\n\n(** **** Exercise: 4 stars (tr_rev)  *)\n(** One problem with the definition of the list-reversing function\n    [rev] that we have is that it performs a call to [app] on each\n    step; running [app] takes time asymptotically linear in the size\n    of the list, which means that [rev] has quadratic running time.\n    We can improve this with the following definition: *)\n\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\nLemma tr_rev_helper : forall X (l1 l2 : list X),\n  rev_append l1 l2 = rev l1 ++ l2.\nProof.\n  intros X l1. induction l1 as [|h1 t1 IHl1].\n  - reflexivity.\n  - simpl. intros l2. rewrite <- app_assoc. apply IHl1.\nQed.\n\n(** This version is said to be _tail-recursive_, because the recursive\n    call to the function is the last operation that needs to be\n    performed (i.e., we don't have to execute [++] after the recursive\n    call); a decent compiler will generate very efficient code in this\n    case.  Prove that the two definitions are indeed equivalent. *)\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros X. apply functional_extensionality.\n  induction x as [|h t IHl].\n  - reflexivity.\n  - simpl. rewrite <- IHl. unfold tr_rev.\n    rewrite tr_rev_helper. simpl. rewrite <- IHl.\n    rewrite app_nil_r. reflexivity.\nQed.\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             Indeed, these two notions of evenness are equivalent, as\n             can easily be shown with a couple of auxiliary lemmas.\n\n    We often say that the boolean [evenb n] _reflects_ the proposition\n    [exists k, n = double k].  *)\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 (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  induction n as [|n' Hn].\n  - exists 0. reflexivity.\n  - rewrite evenb_S. destruct Hn as [x Hx].\n    destruct (evenb n').\n    + exists x. rewrite Hx. reflexivity.\n    + exists (S x). rewrite Hx. 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(** Similarly, to state that two numbers [n] and [m] are equal, we can\n    say either (1) that [beq_nat n m] returns [true] or (2) that [n =\n    m].  These two notions are equivalent. *)\n\nTheorem beq_nat_true_iff : forall n1 n2 : nat,\n  beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply beq_nat_true.\n  - intros H. rewrite H. rewrite <- beq_nat_refl. reflexivity.\nQed.\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_.  Equality provides an extreme\n    example: knowing that [beq_nat n m = true] is generally of little\n    direct help in the middle of a proof involving [n] and [m];\n    however, if we convert the statement to the equivalent form [n =\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 an\n    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, the next chapter\n    shows how to define the property that a regular expression matches\n    a given string using [Prop].  Doing the same with [bool] would\n    amount to writing a regular expression matcher, which would be\n    more complicated, harder to understand, and harder to reason\n    about.\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\n    reflection_.  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 this\n    case, larger proofs can often be made considerably simpler by the\n    use of reflection.  As an extreme example, the Coq proof of the\n    famous _4-color theorem_ uses reflection to reduce the analysis of\n    hundreds of different cases to a boolean computation.  We won't\n    cover reflection in great detail, but it serves as a good example\n    showing the complementary strengths of booleans and general\n    propositions. *)\n\n(** **** Exercise: 2 stars (logical_connectives)  *)\n(** The following lemmas relate the propositional connectives studied\n    in this chapter to the corresponding boolean operations. *)\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  destruct b1.\n  + destruct b2.\n    { simpl. split.\n      + intros _. split. reflexivity. reflexivity.\n      + intros _. reflexivity.\n    }\n    { simpl. split.\n      + intros H. inversion H.\n      + intros [_ H]. inversion H.\n    }\n  + destruct b2.\n    { simpl. split.\n      + intros H. inversion H.\n      + intros [H _]. inversion H.\n    }\n    { simpl. split.\n      + intros H. inversion H.\n      + intros [H _]. inversion H.\n    }\nQed.\n\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  destruct b1.\n  + destruct b2.\n    { simpl. split.\n      + intros _. left. reflexivity.\n      + intros _. reflexivity.\n    }\n    { simpl. split.\n      + intros _. left. reflexivity.\n      + intros _. reflexivity.\n    }\n  + destruct b2.\n    { simpl. split.\n      + intros _. right. reflexivity.\n      + intros _. reflexivity.\n    }\n    { simpl. split.\n      + intros H. inversion H.\n      + intros [H|H].\n        - inversion H. - inversion H.\n    }\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (beq_nat_false_iff)  *)\n(** The following theorem is an alternate \"negative\" formulation of\n    [beq_nat_true_iff] that is more convenient in certain\n    situations (we'll see examples in later chapters). *)\n\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  split.\n  { destruct x.\n    - destruct y.\n      { simpl. intros H. inversion H. }\n      { simpl. intros _ H. inversion H. }\n    - destruct y.\n      { simpl. intros _ H. inversion H. }\n      { simpl. intros H1 H2. inversion H2.\n        rewrite H0 in H1. rewrite <- beq_nat_refl in H1.\n        inversion H1. }\n  }\n  { intros H. destruct x.\n    + destruct y.\n      { destruct H. reflexivity. }\n      { simpl. reflexivity. }\n    + destruct y.\n      { reflexivity. }\n      { simpl. destruct (beq_nat x y) eqn:He.\n        - rewrite beq_nat_true_iff in He.\n          rewrite He in H. destruct H. reflexivity.\n        - reflexivity.\n      }\n  }\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (beq_list)  *)\n(** Given a boolean operator [beq] for testing equality of elements of\n    some type [A], we can define a function [beq_list beq] for testing\n    equality of lists with elements in [A].  Complete the definition\n    of the [beq_list] function below.  To make sure that your\n    definition is correct, prove the lemma [beq_list_true_iff]. *)\n\nFixpoint beq_list {A : Type} (beq : A -> A -> bool)\n                  (l1 l2 : list A) : bool :=\n  match l1,l2 with\n  | nil, nil => true\n  | h1 :: t1, h2 :: t2 => beq h1 h2 && beq_list beq t1 t2\n  | _, _ => false\n  end.\n\nLemma beq_list_true_iff :\n  forall A (beq : A -> A -> bool),\n    (forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n    forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n  intros A beq H. intros l1 l2. generalize dependent l2.\n  induction l1 as [|h1 t1].\n  - destruct l2 as [|h2 t2].\n    + split. reflexivity. reflexivity.\n    + simpl. split. { intros H1. inversion H1. } { intros H1. inversion H1. }\n  - destruct l2 as [|h2 t2].\n    + simpl. split. { intros H1. inversion H1. } { intros H1. inversion H1. }\n    + simpl. destruct (beq h1 h2) eqn:He.\n      { simpl. rewrite IHt1. rewrite H in He.\n        split.\n        { intros He2. rewrite He, He2. reflexivity. }\n        { intros H1. inversion H1. reflexivity. }\n      }\n      { simpl. split.\n        { intros H1. inversion H1. }\n        { intros H1. inversion H1. rewrite <- H in H2. rewrite H2 in He.\n          inversion He. }\n      }\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (All_forallb)  *)\n(** Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Tactics]: *)\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(** Prove the theorem below, which relates [forallb] to the [All]\n    property of the above exercise. *)\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 X test l.\n  induction l as [|h t IHl].\n  - simpl. split.\n    { intros _. apply I. } { reflexivity. }\n  - simpl. split.\n    { intros H. rewrite andb_true_iff in H.\n      destruct H as [H1 H2]. split.\n      { apply H1. } { rewrite IHl in H2. apply H2. }\n    }\n    { intros [H1 H2]. rewrite <- IHl in H2.\n      rewrite H1, H2. reflexivity.\n    }\nQed.\n\n(** Are there any important properties of the function [forallb] which\n    are not captured by this specification? *)\n\n(* FILL IN HERE *)\n(** [] *)\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  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. inversion 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  n = m \\/ n <> m.\nProof.\n  intros n m.\n  apply (restricted_excluded_middle (n = m) (beq_nat n m)).\n  symmetry.\n  apply beq_nat_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\n    but we cannot determine what their actual values are (at least,\n    using 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\n    all!  Fortunately, like functional extensionality, the excluded\n    middle is known to be compatible with Coq's logic, allowing us to\n    add it safely as an axiom.  However, we will not need to do so in\n    this book: the results that we cover can be developed entirely\n    within constructive logic at negligible extra cost.\n\n    It takes some practice to understand which proof techniques must\n    be avoided in constructive reasoning, but arguments by\n    contradiction, in particular, are infamous for leading to\n    non-constructive proofs.  Here's a typical example: suppose that\n    we want to show that there exists [x] with some property [P],\n    i.e., such that [P x].  We start by assuming that our conclusion\n    is false; that is, [~ exists x, P x]. From this premise, it is not\n    hard to derive [forall x, ~ P x].  If we manage to show that this\n    intermediate fact results in a contradiction, we arrive at an\n    existence proof without ever exhibiting a value of [x] for which\n    [P x] holds!\n\n    The technical flaw here, from a constructive standpoint, is that\n    we claimed to prove [exists x, P x] using a proof of\n    [~ ~ (exists x, P x)].  Allowing ourselves to remove double\n    negations from arbitrary statements is equivalent to assuming the\n    excluded middle, as shown in one of the exercises below.  Thus,\n    this line of reasoning cannot be encoded in Coq without assuming\n    additional axioms. *)\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)\n(** The consistency of Coq with the general excluded middle axiom\n    requires complicated reasoning that cannot be carried out within\n    Coq itself.  However, the following theorem implies that it is\n    always safe to assume a decidability axiom (i.e., an instance of\n    excluded middle) for any _particular_ Prop [P].  Why? Because we\n    cannot prove the negation of such an axiom; if we could, we would\n    have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable:  forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  unfold not. intros P H. apply H.\n  right. intros H2. apply H.\n  left. apply H2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (not_exists_dist)  *)\n(** It is a theorem of classical logic that the following two\n    assertions are equivalent:\n\n    ~ (exists x, ~ P x)\n    forall x, P x\n\n    The [dist_not_exists] theorem above proves one side of this\n    equivalence. Interestingly, the other direction cannot be proved\n    in constructive logic. Your job is to show that it is implied by\n    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  intros Hem X P H x. assert (H1 : P x \\/ ~(P x)). { apply Hem. }\n  destruct H1 as [H2|H2].\n  - apply H2.\n  - destruct H. exists x. intros H3. apply H2. apply H3.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, optional (classical_axioms)  *)\n(** For those who like a challenge, here is an exercise taken from the\n    Coq'Art book by Bertot and Casteran (p. 123).  Each of the\n    following four statements, together with [excluded_middle], can be\n    considered as characterizing classical logic.  We can't prove any\n    of them in Coq, but we can consistently add any one of them as an\n    axiom if we wish to work in classical logic.\n\n    Prove that all five propositions (these four plus\n    [excluded_middle]) are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\n\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\n\nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\nTheorem excluded_middle_implies_peirce :\n  excluded_middle -> peirce.\nProof.\n  intros Hem. intros P.\n  assert (H : P \\/ ~P). { apply Hem. }\n  intros Q. destruct H as [H1|H1].\n  { intros _. apply H1. }\n  { intros H2. apply H2. intros H3. exfalso. apply H1. apply H3. }\nQed.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2017-09-06 10:45:52 -0400 (Wed, 06 Sep 2017) $ *)\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/revisit/lf/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7291447811180009}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Tactics.\n\nCheck forall n m: nat, n+m=m+n.\n\nCheck forall n: nat, n=2.\n\nCheck 3=4.\n\nLemma and_intro: forall A B: Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\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  - simpl. rewrite <- IHn'.\n    reflexivity. Qed.\n\n\nExample and_exercise:\n  forall n m: nat, n+m=0 -> n=0 /\\ m=0.\nProof.\n  intros.\n  destruct n.\n  - destruct m.\n    split. reflexivity. reflexivity.\n    split. reflexivity. discriminate.\n  - destruct m.\n    split. discriminate. reflexivity.\n    split. discriminate. discriminate.\nQed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\nLemma proj1 : forall P Q: Prop,\n    P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP. Qed.\n\nLemma proj2 : forall P Q: Prop,\n    P /\\ Q -> Q.\nProof.\n  intros P Q [HP HQ].\n  apply HQ. Qed.\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. Qed.\n\nTheorem and_assoc : forall P Q R: Prop,\n    P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP HQR].\n  split.\n  - split. apply HP.\n    apply proj1 in HQR.\n    apply HQR.\n  - apply proj2 in HQR.\n    apply HQR.\nQed.\n\nLemma or_example :\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\nLemma or_intro: forall A B: Prop, A -> A \\/ B.\nProof.\n  intros. left. apply H. Qed.\n\nLemma or_intro2: forall A B: Prop, B -> A \\/ B.\nProof.\n  intros. right. apply H. Qed.\n\nLemma zero_or_succ:\n  forall n: nat, n = 0 \\/ n = S(pred n).\nProof.\n  intros [| n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\nModule MyNot.\nDefinition not (P:Prop) := P -> False.\nNotation \"~ x\" := (not x) : type_scope.\nCheck not.\n(* ===> Prop -> Prop *)\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra. Qed.\n\nFact not_implies_our_not: forall(P: Prop),\n    not P -> (forall (Q: Prop), P -> Q). \nProof.\n  intros.\n  destruct H.\n  apply H0.\nQed.\n\nNotation \"x <> y\" := (~(x=y)).\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not.\n  intros constra.\n  discriminate.\nQed.\n\nTheorem not_false :\n  not False.\nProof.\n  unfold not.\n  intros. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ not P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP. Qed.\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H. Qed.\n\n\nTheorem contrapositive : forall (P Q: Prop),\n    (P -> Q) -> (not Q -> not P).\nProof.\n  unfold not.\n  intros.\n  apply H0. apply H. apply H1.\nQed.\n\nTheorem not_both_true_and_false: forall P: Prop, ~(P /\\ not P).\nProof.\n  unfold not.\n  intros P [Left Right].\n  apply Right. apply Left.\nQed.\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\nModule MyIff.\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\nEnd MyIff.\n\nTheorem iff_sym : forall P Q: Prop,\n    (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q [HAB HBA].\n  split. apply HBA. apply HAB. Qed.\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\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  (* FILL IN HERE *) Admitted.\n  \nFrom Coq Require Import Setoids.Setoid.\n\nLemma four_is_even: exists n: nat, 4=n+n.\nProof.\n  exists 2. reflexivity. Qed.\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\nTheorem dist_not_exists : forall (X: Type)(P:X -> Prop),\n    (forall x, P x) -> not(exists x, ~ P x).\nProof.\n  unfold not.\n  intros.\n  destruct H0 as [x E].\n  apply E. apply H. Qed.\n\n(* the exists of an element in a list *)\nFixpoint In {A: Type} (x: A) (l: list A): Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x'=x \\/ In x l'\n  end.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  (* WORKED IN CLASS *)\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  (* WORKED IN CLASS *)\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n\nLemma 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.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\nLemma 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. split.\n  - induction l.\n    + simpl. intros. destruct H.\n    + simpl. intros.\n      destruct H as [ HFX | HIN].\n      exists x. split.\n      (* left f x = y case*)\n      * apply HFX.\n      * apply or_intro. reflexivity.\n      (* right (In y map f l)*)\n      * apply  IHl in HIN.\n        destruct HIN. exists x0.\n        split.\n        apply proj1 in H. apply H. destruct H.\n        right. apply H0.\n  - intros. destruct H. destruct H as [ HFX HIN].\n    rewrite <- HFX. apply In_map. apply HIN.\nQed.\n\nLemma plus_comm3_take3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite (plus_comm y z).\n  reflexivity.\nQed.    \n\n\nLemma in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H. unfold not. intro Hl. destruct l.\n  - simpl in H. destruct H.\n  - discriminate Hl.\nQed.\n\nLemma in_not_nil_42_take2 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil with (x := 42).\n  apply H.\nQed.\n\n(* apply ... in ... *)\nLemma in_not_nil_42_take3 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil in H.\n  apply H.\nQed.\n\n(* Explicitly apply the lemma to the value for x. *)\nLemma in_not_nil_42_take4 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil nat 42).\n  apply H.\nQed.     \n\n(* Explicitly apply the lemma to a hypothesis. *)\nLemma in_not_nil_42_take5 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil _ _ _ H).\nQed.\n\nAxiom function_extensionality: forall {X Y: Type}\n                                 {f g: X -> Y},\n    (forall (x:X), f x = g x) -> f = g.\n\n\n\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.\nDefinition tr_rev {X} (l : list X) : list X :=\n  rev_append l [].\n\nPrint rev.\n\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\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    \nTheorem eqb_eq : forall n1 n2 : nat,\n  n1 =? n2 = true <-> n1 = n2.\nProof.\n  Admitted.\n\nPrint eqb_eq.\n\nLemma plus_eqb_example : forall n m p : nat,\n    n =? m = true -> n + p =? m + p = true.\nProof.\n  (* WORKED IN CLASS *)\nAdmitted.\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ not P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. discriminate contra.\nQed.\n\nTheorem restricted_excluded_middle_eq : forall (n m : nat),\n  n = m \\/ n <> m.\nProof.\n  intros n m.\n  apply (restricted_excluded_middle (n = m) (n =? m)).\n  symmetry.\n  apply eqb_eq.\nQed.\n\n", "meta": {"author": "StarGazerM", "repo": "my-foolish-code", "sha": "2991997f9be4523bf190ef4143df8b0d89e528cf", "save_path": "github-repos/coq/StarGazerM-my-foolish-code", "path": "github-repos/coq/StarGazerM-my-foolish-code/my-foolish-code-2991997f9be4523bf190ef4143df8b0d89e528cf/lf/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7291447732446834}}
{"text": "Require Import Coq.NArith.NArith.\n\nLocal Open Scope N_scope.\n\nDefinition Nlt_dec: forall (l r : N), {l < r} + {l >= r}.\n  refine (fun l r =>\n    match Ncompare l r as k return Ncompare l r = k -> _ with\n      | Lt => fun pf => left _ _\n      | _ => fun pf => right _ _\n    end (refl_equal _));\n  abstract congruence.\nDefined.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/bbv/NLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7290873945367655}}
{"text": "\n\n\n\n(* This file contains some important results on lists of elements from an ordered type. \n   Following are some important notions formalized in this file----------------------\n          \n IsOrd l           <==> l is an strictly increasing list\n isOrd l           ==> boolean function to check if the list is strictly increasing\n\n\n Some of the useful results in this file are:\n\n Lemma IsOrd_NoDup (l: list A): IsOrd l -> NoDup l.\n Lemma isOrdP (l:list A): reflect(IsOrd l)(isOrd l).\n \n Lemma head_equal (a b: A)(l s: list A): \n            IsOrd (a::l)-> IsOrd (b::s)-> Equal (a::l) (b::s)-> a=b.\n Lemma tail_equal (a b: A)(l s:list A):\n            IsOrd (a::l)->IsOrd (b::s)->Equal (a::l)(b::s)-> Equal l s.\n Lemma set_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> l=s.\n Lemma length_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> |l|=|s|. \n                                                                             ------- *)\n\n\nRequire Export Lists.List.\nRequire Export GenReflect SetSpecs OrdType.\n\nSet Implicit Arguments.\n\nSection OrderedLists.\n  Context {A: ordType}. \n  (* Variable A: ordType.  *)\n\n  Lemma decA (x y:A): {x=y}+{x<>y}.\n  Proof. eapply reflect_dec with (b:= eqb x y). apply eqP. Qed.\n  \n  Lemma EM_A (x y: A): x=y \\/ x<>y.\n  Proof. eapply reflect_EM with (b:= eqb x y). apply eqP. Qed.\n   \n  (* ------------IsOrd Predicate  -----------------------------------------------  *)\n  Inductive IsOrd :list A -> Prop:=\n  |  IsOrd_nil: IsOrd nil\n  | IsOrd_singl: forall x:A, IsOrd (x::nil)\n  | IsOrd_cons: forall (x y: A)(l: list A), (ltb x y)-> IsOrd (y::l) -> IsOrd (x::y::l).\n\n  Lemma IsOrd_elim (l: list A)(x y: A): IsOrd (x::y::l)-> IsOrd (y::l).\n  Proof. intro H;inversion H; auto. Qed.\n  Lemma IsOrd_elim1 (l: list A)(x y: A): IsOrd (x::y::l)-> (ltb x y).\n  Proof. intro H;inversion H; auto. Qed.\n  Lemma IsOrd_elim0 (l:list A)(x:A): IsOrd (x::l)-> IsOrd(l).\n  Proof. case l. constructor. intros s l0. apply IsOrd_elim. Qed.\n  \n  Lemma IsOrd_intro (a:A)(l: list A): IsOrd l-> (forall x, In x l -> ltb a x)-> IsOrd (a::l).\n  Proof. intros H H1. case l eqn:H2. constructor. constructor.\n         apply H1. all: auto. Qed.\n  \n  Hint Resolve IsOrd_elim IsOrd_elim1 IsOrd_elim0 IsOrd_intro: core.\n  \n  \n  Lemma IsOrd_elim2(l:list A): forall a:A, IsOrd (a::l)-> (forall x:A, In x l-> ltb a x).\n  Proof. { induction l.\n         { intros a H x H0. inversion H0.  }\n         { intros a0 H x H0.\n           assert (H1: x=a \\/ In x l); auto.\n           destruct H1 as [H1 | H1]. rewrite H1. eapply IsOrd_elim1; exact H.\n           assert (H2: a <b x). apply IHl; eauto.\n           assert (H3 : a0 <b a). eapply IsOrd_elim1;exact H. eauto.   } } Qed.\n  \n   Lemma IsOrd_elim2a(l:list A)(a x:A): IsOrd (a::l)-> In x l -> ltb a x.\n  Proof. { intros H H1. eapply (@IsOrd_elim2 l a) in H. exact H. auto. } Qed. \n      \n  \n  Lemma IsOrd_elim3 (x a: A)(l: list A): IsOrd (a::l)-> ltb x a -> ~ In x (a::l).\n  Proof. { intros H H0 H1.\n         assert (H2: x=a \\/ In x l); eauto.\n         destruct H2. eapply ltb_not_eq; eauto.\n         assert (H3: a <b x). eapply IsOrd_elim2;eauto.  eapply ltb_antisym;eauto. } Qed. \n  \n  Lemma IsOrd_elim4 (a:A)(l: list A): IsOrd (a::l)-> ~ In a l.\n  Proof. { intros H H1. assert (H2: ltb a a). eapply IsOrd_elim2;eauto.\n           absurd (a <b a); auto. } Qed.\n\n  Lemma IsOrd_elim5 (a b:A)(l: list A): IsOrd (a::l)-> In b (a::l)-> (b=a \\/ a <b b).\n    Proof.  { intros H1 H2. cut (b=a \\/ In b l).\n           intro H0; destruct H0 as [Ha | Hb]. left;auto.\n           right; eapply IsOrd_elim2;eauto.  eauto. } Qed.\n\n  Hint Resolve IsOrd_elim2a IsOrd_elim3 IsOrd_elim4 IsOrd_elim5: core.  \n\n  Lemma IsOrd_NoDup (l: list A): IsOrd l -> NoDup l.\n  Proof. { intros. induction l. constructor.\n         constructor. eapply IsOrd_elim4;auto.  eauto. } Qed. \n\n  Fixpoint isOrd (l: list A): bool:=\n    match l with\n    |nil => true\n    |x ::l1=> match l1 with\n             | nil => true\n             | y::l2 => (ltb x y) && (isOrd l1)\n             end\n    end.\n   Lemma isOrd_elim (l: list A)(x y: A): isOrd (x::y::l)-> isOrd (y::l).\n   Proof.  simpl; move /andP; tauto.  Qed.\n   Lemma isOrd_elim1 (l: list A)(x y: A): isOrd (x::y::l)-> (ltb x y).\n   Proof. simpl; move /andP; tauto. Qed.\n   Lemma isOrd_elim0 (l:list A)(x:A): isOrd (x::l)-> isOrd(l).\n   Proof. case l. simpl;auto.  intros s l0. simpl; move /andP; tauto. Qed.\n\n   Hint Resolve isOrd_elim isOrd_elim1 isOrd_elim0: core.\n\n  Lemma isOrdP (l:list A): reflect(IsOrd l)(isOrd l).\n  Proof. { apply reflect_intro. split.\n         { intro H. induction l. \n         { simpl;auto. }\n         { simpl. case l eqn:H1.  auto. apply /andP.\n           split. eapply IsOrd_elim1;exact H. apply IHl. eauto. } }\n         {  intro H. induction l. constructor. case l eqn:H1.\n            constructor. constructor. eapply isOrd_elim1;exact H.\n            apply IHl. eapply isOrd_elim. apply H.  } } Qed.\n\n  Hint Resolve isOrdP: core.\n\n  Lemma NoDup_elim1(a:A)(l:list A): NoDup (a::l) -> ~ In a l.\n  Proof. eapply NoDup_cons_iff. Qed.\n\n  Lemma NoDup_elim2 (a: A)(l: list A): NoDup (a::l) -> NoDup l.\n  Proof. eapply NoDup_cons_iff. Qed.\n\n  Lemma NoDup_intro (a: A)(l: list A): ~ In a l -> NoDup l -> NoDup (a::l).\n  Proof. intros; eapply NoDup_cons_iff;auto. Qed.\n\n  \n  Hint Resolve NoDup_elim1 NoDup_elim2 NoDup_intro: core.\n\n  (* --------------------Equality of Ordered Lists---------------------------------------*)\n\n  Definition empty: list A:= nil.\n  \n  Lemma empty_equal_nil (l: list A): l [=] empty -> l = empty.\n  Proof. { case l. auto. intros s l0. unfold \"[=]\". intro H. \n           destruct H as [H1 H2]. absurd (In s empty). all: eauto. } Qed.\n\n  Lemma head_equal (a b: A)(l s: list A): IsOrd (a::l)-> IsOrd (b::s)-> Equal (a::l) (b::s)-> a = b.\n  Proof. { intros H H1 H2.\n         assert(H3: In b (a::l)).\n         unfold \"[=]\" in H2. apply H2. auto.   \n         assert(H3A: b=a \\/ a <b b).  eapply IsOrd_elim5; eauto. \n         assert(H4: In a (b::s)). unfold \"[=]\" in H2. apply H2. auto. \n         assert(H4A: a = b \\/ b <b a). eapply IsOrd_elim5; eauto. \n         destruct H3A; destruct H4A.\n         auto. symmetry;auto. auto. absurd (b <b a); auto. } Qed.\n         \n\n  Lemma tail_equal (a b: A)(l s:list A):IsOrd (a::l)->IsOrd (b::s)->Equal (a::l)(b::s)-> Equal l s.\n  Proof. { intros H H1 H2. unfold \"[=]\". \n         assert(H0: a = b). eapply head_equal;eauto. subst b.\n         split; intro x.\n         { intro H3. assert (H3A: a <b x).\n           eapply IsOrd_elim2a. exact H. auto. \n           assert (H3B: In x (a::l)). auto.\n           assert (H3C: x=a \\/ In x s).\n           { cut (In x (a::s)). eauto. apply H2;auto. }\n           destruct H3C. absurd (a <b x); eauto. auto. }\n          { intro H3. assert (H3A: a <b x). eapply IsOrd_elim2a. exact H1. auto.  \n           assert (H3B: In x (a::s)). auto.\n           assert (H3C: x=a \\/ In x l).\n           { cut (In x (a::l)). auto.  apply H2;auto. }\n           destruct H3C. absurd (a <b x); auto. auto. } } Qed.\n         \n  Lemma set_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> l=s.\n  Proof. { revert s. induction l; induction s.\n         { auto. }\n         { intros; symmetry; apply empty_equal_nil; unfold empty; auto.  }\n         { intros; apply empty_equal_nil; unfold empty; auto. }\n         { intros H H1 H2. replace a0 with a. replace s with l.\n           auto. apply IHl. eauto. eauto. \n           eapply tail_equal; eauto. eapply head_equal;eauto. } } Qed.  \n  \n  Lemma length_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> |l|=|s|.\n  Proof. intros. replace s with l. auto. eapply set_equal; eauto. Qed.\n\n  Hint Resolve head_equal tail_equal set_equal length_equal: core.\n\n  (*----------Misc property on ordList-------------------------------*)\n  Lemma nodup_Subset_elim(a:A)(l s: list A):\n    NoDup (a::l)-> NoDup (a::s)-> a::l [<=] a::s -> l [<=] s.\n  Proof. { intros H H1 H2 x H3. assert (Hs: In x (a::s)). apply H2; auto.\n         destruct Hs. subst x; absurd (In a l); auto. auto. } Qed.\n\n  Lemma IsOrd_Subset_elim1 (e a: A)(l s: list A):\n    IsOrd (e::l)-> IsOrd (a::s) -> e::l [<=] a::s -> a <=b e.\n  Proof. intros H H1 H2. match_up a e. subst a;auto. auto. absurd (In e (a::s)); auto.  Qed.\n  \n  Lemma IsOrd_Subset_elim2 (e a: A)(l s: list A):\n    IsOrd (e::l)-> IsOrd (a::s) -> e::l [<=] a::s -> e<>a -> e::l [<=] s.\n  Proof. { intros H H1 H2 H3 x Hl.\n         destruct Hl.\n         { subst x. cut (In e (a::s)). intro H4. destruct H4.\n           symmetry in H0. contradiction. auto. auto. }\n         { assert(H4: In x (a::s)). auto. destruct H4. subst x.\n           assert (H4: e <b a).\n           { apply leb_antisym2. exact H3. apply ltb_leb; eapply IsOrd_elim2a.\n             exact H. auto. }\n           assert (H5: a <=b e). eapply IsOrd_Subset_elim1;eauto.\n           by_conflict. auto. } } Qed.\n  \n\nEnd OrderedLists.\n\n\n\nHint Resolve IsOrd_elim IsOrd_elim1 IsOrd_elim0 IsOrd_intro: core.\nHint Resolve IsOrd_elim2a IsOrd_elim3 IsOrd_elim4 IsOrd_elim5: core. \nHint Resolve isOrd_elim isOrd_elim1 isOrd_elim0: core.\nHint Resolve isOrdP: core.\n\nHint Resolve NoDup_elim1 NoDup_elim2 NoDup_intro: core.\nHint Immediate head_equal tail_equal set_equal length_equal: core.\nHint Resolve IsOrd_NoDup: core.\n\nHint Resolve nodup_Subset_elim IsOrd_Subset_elim1 IsOrd_Subset_elim2:core.\n\n\n\n\n           \n\n", "meta": {"author": "Abhishek-TIFR", "repo": "List-Set", "sha": "f22e828ca348c8317a5235491e7e1dac848a691f", "save_path": "github-repos/coq/Abhishek-TIFR-List-Set", "path": "github-repos/coq/Abhishek-TIFR-List-Set/List-Set-f22e828ca348c8317a5235491e7e1dac848a691f/OrdList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7290781613801489}}
{"text": "(* Exercise 63a *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\nTheorem exercise_063a : ~~((~A -> B) /\\ (~A -> ~B) -> A).\nProof.\nneg_i (((~A -> B) /\\ (~A -> ~B) -> A)) a1.\nhyp a1.\nimp_i a2.\nneg_e' (B) a3.\nimp_e (~A).\ncon_e2 (~A -> B).\nhyp a2.\nhyp a3.\nimp_e (~A).\ncon_e1 (~A -> ~B).\nhyp a2.\nhyp a3.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop063.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.729017544977629}}
{"text": "Require Export Axioms.\n\nDefinition Sing (x : set): set := {x, x}.\n\nLemma Sing_I : ∀ x, x ∈ (Sing x).\nProof. intros. compute. auto. Qed.\n\nHint Resolve Sing_I.\n\nLemma Sing_E : ∀ x y, y ∈ (Sing x) → y = x.\nProof.\n  intros. compute in *.\n  apply UPair_E in H. inversion H; auto.\nQed.\n\nHint Resolve Sing_E.\n\nLtac sing := apply Sing_I ; try auto.\nLtac sing_e H := apply Sing_E in H ; try auto.\n\nDefinition Zero := ∅.\nDefinition One := Sing ∅.\nDefinition Two := { ∅, One }.\n\n(* We need to be able to extract information from equalities of unordered\n   pairs and or singltons.\n*)\nLemma UU_ex : forall W X Y Z, UPair W X = UPair Y Z ->\n  ( W = Y /\\ X = Z ) \\/ ( W = Z /\\ X = Y ).\nProof.\n  intros.\n  assert (C: W ∈ UPair Y Z). rewrite <- H. pair_1.\n  assert (D: X ∈ UPair Y Z). rewrite <- H. pair_2.\n  assert (E: Y ∈ UPair W X). rewrite H. pair_1.\n  assert (F: Z ∈ UPair W X). rewrite H. pair_2.\n  pair_e C; pair_e D; pair_e E; pair_e F.\nQed.\n\nLemma SU_ex : forall X Y Z, Sing X = UPair Y Z -> X = Y /\\ X = Z.\nProof.\n  intros.\n  assert (C: X ∈ UPair Y Z). rewrite <- H. pair_1.\n  assert (D: Y ∈ Sing X). rewrite H. pair_1.\n  assert (E: Z ∈ Sing X). rewrite H. pair_2.\n  pair_e C; pair_e D; pair_e E.\nQed.\n\nLemma US_ex : forall X Y Z, UPair Y Z = Sing X -> X = Y /\\ X = Z.\nProof.\n  intros.\n  assert (C: Y ∈ Sing X). rewrite <- H. pair_1.\n  assert (D: Z ∈ Sing X). rewrite <- H. pair_2.\n  assert (E: X ∈ UPair Y Z). rewrite H. pair_1.\n  pair_e C; pair_e D; pair_e E.\nQed.\n\nLemma SS_ex : forall X Y, Sing X = Sing Y -> X = Y.\nProof.\n  intros.\n  assert (C: X ∈ Sing Y). rewrite <- H. sing.\n  assert (D: Y ∈ Sing X). rewrite H. sing.\n  pair_e C; pair_e D.\nQed.\n\nLtac inv_SU_eq :=\n  repeat let E1 := fresh \"E\" in\n         let E2 := fresh \"E\" in\n         let E3 := fresh \"E\" in\n         let E4 := fresh \"E\" in\n         match goal with\n         | [H : UPair ?A ?B = UPair ?C ?D |- _ ] =>\n             destruct (UU_ex H) as [[E1 E2] | [E3 E4]]; clear H; subst\n         | [H : Sing ?A = UPair ?B ?C |- _ ] =>\n             destruct (SU_ex H) as [E1 E2]; clear H; subst\n         | [H : UPair ?A ?B = Sing ?C |- _ ] =>\n             destruct (US_ex H) as [E1 E2]; clear H; subst\n         | [H : Sing ?A = Sing ?B |- _ ] =>\n             apply SS_ex in H; subst\n         end.\n", "meta": {"author": "jwiegley", "repo": "set-theory", "sha": "ae9714a5b7355fb23b7383a0bc4c90dc00c50264", "save_path": "github-repos/coq/jwiegley-set-theory", "path": "github-repos/coq/jwiegley-set-theory/set-theory-ae9714a5b7355fb23b7383a0bc4c90dc00c50264/Singletons.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7289671401756812}}
{"text": "Require Export Induction.\nRequire Export Basics.\n\nModule Lists.\n\nInductive natprod : Type :=\n  pair : nat -> nat -> natprod.\n\nCheck (pair 3 4).\n\nDefinition fst (p: natprod) :=\n  match p with\n      | pair x y => x\n  end.\n\nDefinition snd (p: natprod) :=\n  match p with\n      | pair x y => y\n  end.\n\nEval compute in (fst (pair 3 5)).\n\n(* Note the spacings! *)\nNotation \"( x , y )\" := (pair x y).\n\nEval compute in (fst (3,5)).\nEval compute in (snd (3,5)).\n\nDefinition fst' (p: natprod) :=\n  match p with\n    | (x,y) => x\n  end.\n\nDefinition snd' (p:natprod) :=\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\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  intros n m.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as [n m].\n  simpl.\n  reflexivity.\nQed.\n\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\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  reflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint repeat (n count : nat) : natlist := \n  match count with\n    | O => nil\n    | (S n') => cons n (repeat n n')\n  end.\n\nFixpoint length (l:natlist) : nat := \n  match l with\n    | [] => O\n    | x :: xs => 1 + length xs\n  end.\n\nCheck (length mylist).\nEval compute in (length mylist).\n\nFixpoint app (l1 l2 : natlist) : natlist := \n  match l1 with\n      | nil => l2\n      | x :: xs => x :: (app xs l2)\n  end.\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              \nDefinition hd (default:nat) (l:natlist) : nat :=\n  match l with\n    | nil => default\n    | (x :: xs) => x\n  end.\n\nDefinition tl (l:natlist) : natlist :=\n  match l with\n    | nil => nil\n    | (x::xs) => xs\n  end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\n\nExample test_hd2: hd 0 [] = 0.\nProof. reflexivity. Qed.\n\nExample test_tl: tl [1;2;3] = [2;3].\nProof. reflexivity. Qed.\n\nFixpoint listFilter (l:natlist) (fn: nat -> bool) : natlist :=\n  match l with\n    | nil => nil\n    | (x::xs) => match (fn x) with\n                   | true => (x::(listFilter xs fn))\n                   | false => listFilter xs fn\n                 end\n  end.\n\nDefinition checkZero (x : nat) : bool :=\n  match x with\n    | O => false\n    | S n => true\n  end.\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  listFilter l checkZero.\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  listFilter l (fun n => oddb n).\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. reflexivity. Qed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  length (oddmembers l).\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof. reflexivity. Qed.\n\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof. reflexivity. Qed.\n\nDefinition singleton (n : nat) : natlist :=\n  n :: nil.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n    | nil, _ => l2\n    | _, nil => l1\n    | x::xs, y::ys => (x::y::alternate xs ys)\n  end.\n\nExample test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\nProof. reflexivity. Qed.\n\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\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  length (listFilter s (fun n => beq_nat n v)).\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\nDefinition sum : bag -> bag -> bag :=\n  app.\n\nEval compute in (sum [1;2;3] [1]).\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 :=\nv :: 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\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    | (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: 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 :=\n  listFilter s (fun n => negb (beq_nat v 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    | nil => true\n    | (x::xs) => match (beq_nat (count x s2) 0) with\n                   | true => false\n                   | false => subset xs (remove_one x s2)\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\nTheorem same_equal: forall (n: nat),\n  beq_nat n n = true.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\nTheorem bag_theorem: forall n: nat, forall b: bag,\n  blt_nat O (count n (add n b)) = true.\nProof.\n  intros n b.\n  destruct n as [| n'].\n  Case \"n = 0\".\n    simpl.\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\n    assert (H1: beq_nat n' n' = true).\n      rewrite -> same_equal.\n      reflexivity.\n    rewrite -> H1.\n    simpl.\n    reflexivity.\nQed.\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  intros l.\n  destruct l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\".\n    reflexivity. Qed.\n\nCheck pred.\nExample pred_one: (pred 3 = 2).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample pred_two: (pred 0 = 0).\nProof.\n  simpl.\n  reflexivity.\nQed.\n  \nTheorem app_assoc : forall l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3.\n  induction l1 as [| n l1'].\n  - simpl. reflexivity.\n  - simpl.\n    rewrite -> IHl1'.\n    reflexivity.\nQed.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2.\n  induction l1 as [| n l1'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHl1'.\n    reflexivity.\nQed.\n\nFixpoint snoc (l:natlist) (v:nat) : natlist := \n  match l with\n    | nil => [v]\n    | (cons n l') => n :: (snoc l' v)\n  end.\n\nExample snoc_eg1: (snoc (1::2::3::nil)  4= [1;2;3;4]).\nProof.\n  reflexivity.\nQed.\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.\n  reflexivity.\nQed.\n  \nExample test_rev2: rev nil = nil.\nProof. reflexivity. Qed.\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 = cons n l'\".\n    simpl.\n    rewrite <- IHl'.\nAbort.\n\nLemma length_snoc : forall n : nat, forall l : natlist,\n  length (snoc l n) = S (length l).\nProof.\n  intros n l.\n  induction l as [| n' l'].\n  Case \"n = nil\".\n    reflexivity.\n  Case \"n = cons n' l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l.\n  induction l as [| n' l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n' l'\".\n    simpl.\n    rewrite -> length_snoc.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\n(* rev_length: forall l : natlist, length (rev l) = length l *)\n(* test_rev2: rev [] = [] *)\n(* test_rev1: rev [1; 2; 3] = [3; 2; 1] *)\n\nTheorem app_nil_end : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l.\n  induction l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nLemma rev_helper : forall l : natlist, forall n: nat,\n    rev (snoc l n) = n :: rev l.\nProof.\n  intros l n.\n  induction l as [| l' n'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons l' n'\".\n    simpl.\n    rewrite -> IHn'.\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'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = cons n l'\".\n    simpl.\n    rewrite -> rev_helper.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\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.\n  induction l1 as [| n l1'].\n  Case \"l1 = nil\".\n    simpl.\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl.\n    rewrite -> IHl1'.\n    reflexivity.\nQed.\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 = nil\".\n    reflexivity.\n  Case \"l = cons n' l'\".\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nLemma distr_snoc_helper : forall l1 l2:natlist, forall n:nat,\n  snoc (l1 ++ l2) n = l1 ++ snoc l2 n.\nProof.\n  intros l1 l2 n.\n  induction l1 as [| n' l1'].\n  Case \"l1 = nil\".\n    reflexivity.\n  Case \"l1 = cons n' l1'\".\n    simpl.\n    rewrite -> IHl1'.\n    reflexivity.\nQed.\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 [| n l1'].\n  Case \"l1 = nil\".\n    simpl.\n    rewrite -> app_nil_end.\n    reflexivity.\n  Case \"l1 = cons n l1'\".\n    simpl.\n    rewrite -> IHl1'.\n    rewrite -> distr_snoc_helper.\n    reflexivity.\nQed.\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'].\nAdmitted.\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1,l2 with\n    | nil, nil => true\n    | _, nil => false\n    | nil, _ => 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.\n\nExample test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\nProof. reflexivity. Qed.\n\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 l.\n  induction l as [| n l'].\n  Case \"l = nil\".\n    reflexivity.\n  Case \"l = n :: l'\".\n    simpl.\n    rewrite -> same_equal.\n    rewrite <- IHl'.\n    reflexivity.\nQed.\n\nInductive natoption : Type :=\n| Some : nat -> natoption\n| None : natoption.\n\nFixpoint index (n:nat) (l:natlist) : natoption :=\n  match l with\n    | nil => None\n    | a :: l => match beq_nat n 0 with\n                    | true => Some a\n                    | false => index (n-1) l\n                end\n  end.\n\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\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n    | Some o' => o'\n    | None => d\n  end.\n\nDefinition hd_opt (l : natlist) : natoption :=\n  match l with\n    | [] => None\n    | (x::xs) => Some x\n  end.\n\nExample test_hd_opt1 : hd_opt [] = None.\nreflexivity. Qed.\n\nExample test_hd_opt2 : hd_opt [1] = Some 1.\nreflexivity. Qed.\n\nExample test_hd_opt3 : hd_opt [5;6] = Some 5.\nreflexivity. Qed.\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. simpl. reflexivity. Qed.\n\n\nExample test_hd_error2 : hd_error [1] = Some 1.\nreflexivity. Qed.\n\n\nExample test_hd_error3 : hd_error [5;6] = Some 5.\nreflexivity. Qed.\n\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\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros l.\n  induction l as [| n l'].\n  - simpl. reflexivity.\n  - simpl. \n    rewrite <- IHl' at 2.\n    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'].\n  - simpl.\n    symmetry.\n    rewrite -> app_nil_r with (l := rev l2) at 1.\n    reflexivity.\n  - simpl. rewrite -> IHl1'. \n    rewrite -> snoc_append at 1.\n    symmetry.\n    rewrite -> snoc_append at 1.\n    rewrite -> app_assoc.\n    reflexivity.\nQed.\n\nTheorem count_member_nonzero : forall (s : bag),\n  leb 1 (count 1 (1 :: s)) = true.\nProof.\n  intros s.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall n,\n  leb n (S n) = true.\nProof.\n  intros n.\n  induction n as [| n'].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite -> IHn'.\n    reflexivity.\nQed.\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 as [| n s'].\n  - simpl. reflexivity.\n  - simpl.\nAbort.\n\nEnd Lists.\n\nModule PartialMap.\n\nExport Lists.\n\nInductive id: Type :=\n  | Id : nat -> id.\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall x, true = beq_id x x.\nProof.\n  intros x.\n  destruct x.\n  - simpl. rewrite -> same_equal. reflexivity.\nQed.\n\n\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\nDefinition update (d : partial_map) (x : id) (value : nat) : partial_map :=\n  record x value d.\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\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  destruct x. simpl. rewrite -> same_equal. reflexivity.\nQed.\n\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.\n  intros H1.\n  induction d as [| z o' d' IHdd'].\n  - simpl. rewrite -> H1. reflexivity.\n  - simpl. rewrite -> H1 at 1. reflexivity.\nQed.\n\nEnd PartialMap.\n", "meta": {"author": "psibi", "repo": "sf", "sha": "36d1f95b4d4ed894ecc2c55c81095c822f3e9c69", "save_path": "github-repos/coq/psibi-sf", "path": "github-repos/coq/psibi-sf/sf-36d1f95b4d4ed894ecc2c55c81095c822f3e9c69/chapter3-lists/NatList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7289671320455098}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\n\nInductive natural : Type :=   Zero : natural | Succ : natural -> natural .\n\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint qmult (qmult_arg0 : natural) (qmult_arg1 : natural) (qmult_arg2 : natural) : natural\n           := match qmult_arg0, qmult_arg1, qmult_arg2 with\n              | Zero, n, m => m\n              | Succ n, m, p => qmult n m (plus p m)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\n   intros.\n   induction x.\n   - rewrite plus_zero. reflexivity.\n   - simpl. rewrite plus_succ. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_qmult : forall (x y z a : natural), plus (qmult x y z) a = qmult x y (plus z a).\nProof.\n   intro.\n   induction x.\n   - reflexivity.\n   - intros.  simpl.  rewrite IHx. lfind.  rewrite (plus_commut y a).  \nAdmitted.\n\nTheorem mult_eq_qmult : forall (x : natural) (y : natural), eq (mult x y) (qmult x y Zero).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. rewrite plus_qmult. reflexivity.\nQed.\n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal34_plus_qmult_66_plus_assoc/goal34.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7288567361650903}}
{"text": "Require Import ZArith Omega Znumtheory.\nRequire Import Coq.micromega.Lia.\n\n(** * Contains some useful lemmas not in stdlib and a tactic *)\n\n\n(** A convenient and simple tactic to prove 0<x or 0<>x *)\n\nLemma Zmult_neq_0_compat : forall a b, 0 <> a -> 0 <> b -> 0 <> a * b.\nProof.\n  intros [] [] P Q I; simpl in *;\n    inversion I; tauto.\nQed.\n\nLemma Zmult_le_1_compat : forall a b, 1 <= a -> 1 <= b -> 1 <= a * b.\nProof.\n  intros a b.\n  replace a with (1 + (a - 1)) by omega.\n  replace b with (1 + (b - 1)) by omega.\n  generalize (a - 1).\n  generalize (b - 1).\n  intros c d.\n  intros.\n  assert (0 <= c) by omega.\n  assert (0 <= d) by omega.\n  ring_simplify.\n  assert (0 <= d * c) by auto with *.\n  omega.\nQed.\n\nLemma Zsquare_pos : forall x, 0 <> x -> 0 < x * x.\nProof.\n  intros [] E; simpl; reflexivity || tauto.\nQed.\n\nLtac notzero :=\n  lazymatch goal with\n  | |- ?a <> 0 => apply not_eq_sym; notzero\n  | |- ?a > 0 => cut (0 < a); [ apply Zcompare_Gt_Lt_antisym | ]; notzero\n  | |- 0 < ?a * ?a => apply Zsquare_pos; notzero\n  | |- 0 < ?a ^ 2 => replace (a ^ 2) with (a * a) by ring; notzero\n  | |- 0 <  ?a * ?b => apply Zmult_lt_0_compat; notzero\n  | |- 0 <> ?a * ?b => apply Zmult_neq_0_compat; notzero\n  | |- 0 < Zpos _ => reflexivity\n  | |- 0 > Zneg _ => reflexivity\n  | |- 0 <> Zpos _ => let I := fresh \"I\" in intros I; inversion I\n  | |- 0 <> Zneg _ => let I := fresh \"I\" in intros I; inversion I\n  | Pp : prime ?p |- 0 < ?p => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- 0 <> ?p => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- 1 <> ?p => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- ?p <> 0 => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- ?p <> 1 => pose proof prime_ge_2 p Pp; lia\n  | Pp : prime ?p |- ?p > 0 => pose proof prime_ge_2 p Pp; lia\n  | |- 0 < _  => auto with *; try (zify; omega)\n  | |- 0 <> _ => auto with *; try (zify; omega)\n  | |- _ => idtac\n  end.\n\n\n(** Subsumed by tactic [notzero] but also useful, since it shows up in\nSearch *)\n\nLemma prime_not_0 p : prime p -> p <> 0.\nProof.\n  intro; notzero.\nQed.\n\nLemma prime_not_1 p : prime p -> p <> 1.\nProof.\n  intro; notzero.\nQed.\n\n\n(** Extraction from the Zdivide predicate *)\n\nLemma Zdivide_inf : forall a b, (a | b) -> { q | b = q * a }.\nProof.\n  intros a b D.\n  exists (b / a).\n  rewrite Zmult_comm.\n  destruct (Z.eq_dec a 0).\n    subst; destruct D; omega.\n    \n    apply Z_div_exact_full_2; auto with *.\n    apply Zdivide_mod; auto.\nDefined.\n\n\n(** About Zmod or Zdiv *)\n\nLemma Z_mult_div_mod : forall a b, b <> 0 -> b * (a / b) = a - a mod b.\nProof.\n  intros a b N.\n  pose proof Z_div_mod_eq_full a b N; omega.\nQed.\n\nLemma Zdivide_square : forall a b, (a | b) -> (a * a | b * b).\nProof.\n  intros a b (k, Ek).\n  exists (k * k); subst; ring.\nQed.\n\nLemma Zmult_divide_compat_rev_l: forall a b c : Z, c <> 0 -> (c * a | c * b) -> (a | b).\nProof.\n  intros a b c Nc (k, Hk).\n  exists k.\n  eapply Zmult_reg_l; eauto.\n  rewrite Hk; ring.\nQed.\n\nLemma Z_mult_div_bounds : forall a b, 0 < b -> a - b < b * (a / b) <= a.\nProof.\n  intros a b N; split.\n    pose proof Z_mod_lt a b.\n    rewrite Z_mult_div_mod; omega.\n    \n    apply Z_mult_div_ge; omega.\nQed.\n\n\n(** About square *)\n\nLemma Zle_0_square : forall a, 0 <= a * a.\nProof.\n  intros []; intuition.\n  simpl; intro H; inversion H.\nQed.\n\nLemma Zeq_0_square : forall a, a * a = 0 -> a = 0.\nProof.\n  intros [] H; intuition simpl; inversion H.\nQed.\n\nLemma rewrite_power_2 : forall x, x ^ 2 = x * x.\nProof.\n  (* TODO virer ça .. ? *)\n  intros; ring.\nQed.\n\nLemma sqrt_eq_compat : forall a b, 0 <= a -> 0 <= b ->\n  a * a = b * b -> a = b.\nProof.\n  intros a b Pa Pb E.\n  destruct (Z.eq_dec 0 (a + b)) as [F|F].\n    omega.\n    \n    cut (a - b = 0); [ omega | ].\n    apply (Zmult_reg_l _ _ (a + b)); notzero.\n    ring_simplify.\n    rewrite rewrite_power_2, E.\n    ring.\nQed.\n\nLemma sqrt_eq_compat_abs : forall a b, a * a = b * b -> Z.abs a = Z.abs b.\nProof.\n  intros a b E.\n  destruct (Z.eq_dec 0 (Z.abs a + Z.abs b)) as [F|F].\n    zify; omega.\n    \n    cut (Z.abs a - Z.abs b = 0); [ omega | ].\n    apply (Zmult_reg_l _ _ (Z.abs a + Z.abs b)); notzero.\n    ring_simplify.\n    rewrite <- Z.abs_square, <- (Z.abs_square b) in E.\n    rewrite rewrite_power_2, E.\n    ring.\nQed.\n\nLemma sqrt_le_compat : forall a b, 0 <= a -> 0 <= b ->\n  a * a <= b * b -> a <= b.\nProof.\n  intros a b Pa Pb E.\n  destruct (Z.eq_dec 0 (a + b)) as [F|F].\n    omega.\n    \n    cut (0 <= b - a); [ omega | ].\n    apply Zmult_le_reg_r with (a + b); notzero.\n    ring_simplify.\n    do 2 rewrite rewrite_power_2; omega.\nQed.\n\n\n(** About Z.abs *)\n\nLemma Zabs_nat_inj : forall a b, 0 <= a -> 0 <= b -> Z.abs_nat a = Z.abs_nat b -> a = b.\nProof.\n  intros a b Pa Pb E.\n  rewrite <- (Z.abs_eq a), <- (Z.abs_eq b); eauto.\n  do 2 rewrite <- inj_Zabs_nat.\n  auto.\nQed.\n\n\n(* TODO (prouver et déplacer) ou virer *)\nLemma Zdivide_square_rev : forall a b, (a * a | b * b) -> (a | b).\nProof.\n  intros a b D.\n  destruct (Z.eq_dec a 0).\n    subst; simpl in D.\n    destruct D as (q, Hq); ring_simplify (q * 0) in Hq.\n    destruct b; inversion Hq.\n    exists 0; ring.\n    \n    exists (b / a).\n    rewrite Zmult_comm, Z_mult_div_mod; auto.\n\n    (* TODO déplacer et prouver : inutilisé mais intéressant.\n    un peu intéressant, c'est dur environ comme sqrt(n)∈Q => sqrt(n)∈N *)\nAbort.\n\nLemma Zpow_mod (a b m : Z) : (a ^ b) mod m = ((a mod m) ^ b) mod m.\nProof.\n  assert (b < 0 \\/ 0 <= b) as [bz | bz] by lia.\n  - rewrite 2 Z.pow_neg_r; auto.\n  - rewrite <-(Z2Nat.id b); auto.\n    rewrite <-2Zpower_nat_Z.\n    generalize (Z.to_nat b); intros n. clear b bz.\n    destruct (Z.eq_dec m 0).\n    + subst. now rewrite !Zmod_0_r.\n    + induction n. easy. simpl.\n      rewrite Z.mul_mod, IHn, Z.mul_mod_idemp_r; auto.\nQed.\n\n(* When we already have a proof [pr] of [P] and the goal is [Q], it is\n   enough to prove [P = Q] *)\n\nLtac exact_eq pr :=\n  generalize pr;\n  let A := fresh in\n  assert (A : forall P Q : Prop, P = Q -> P -> Q) by congruence;\n  apply A; clear A.\n\n(* If [H] is a hypothesis of the form [P -> Q], assert a proof of [P]\n   and remove the [P ->] from [H] *)\n\nTactic Notation \"spec\" hyp(H) :=\n  match type of H with\n  | ?P -> _ =>\n    let h := fresh in\n    assert (h : P); [ | specialize (H h); clear h ]\n  end.\n\nTactic Notation \"spec\" hyp(H) \"by\" tactic(t) :=\n  match type of H with\n  | ?P -> _ =>\n    let h := fresh in\n    assert (h : P) by t;\n    specialize (H h); clear h\n  end.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Arith/Ztools.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.728856734327983}}
{"text": "Require Import Basics.\nRequire Import Spaces.Int.\nRequire Import Spaces.Finite.\n\n(** * Successor Structures. *)\n\n(** A successor structure is just a type with a endofunctor on it, called 'successor'. Typical examples include either the integers or natural numbers with the successor (or predecessor) operation. *)\n\nRecord SuccStr : Type := {\n   ss_carrier : Type ;\n   ss_succ : ss_carrier -> ss_carrier ;\n}.\n\nCoercion ss_carrier : SuccStr >-> Sortclass.\n\nDeclare Scope succ_scope.\n\nLocal Open Scope nat_scope.\nLocal Open Scope succ_scope.\n\nDelimit Scope succ_scope with succ.\nArguments ss_succ {_} _.\n\nNotation \"x .+1\" := (ss_succ x) : succ_scope.\n\n(** Successor structure of naturals *)\nDefinition NatSucc : SuccStr := Build_SuccStr nat Nat.Core.succ.\n\n(** Successor structure of integers *)\nDefinition IntSucc : SuccStr := Build_SuccStr Int int_succ.\n\nNotation \"'+N'\" := NatSucc : succ_scope.\nNotation \"'+Z'\" := IntSucc : succ_scope.\n\n(** Stratified successor structures *)\n\nDefinition StratifiedType (N : SuccStr) (n : nat) : Type := N * Fin n.\n\nDefinition stratified_succ (N : SuccStr) (n : nat) (x : StratifiedType N n)\n  : StratifiedType N n.\nProof.\n  constructor.\n  + induction n.\n    - induction (snd x).\n    - destruct (dec (snd x = inr tt)).\n      * exact (ss_succ (fst x)).\n      * exact (fst x).\n  + exact (fsucc_mod (snd x)).\nDefined.\n\nDefinition Stratified (N : SuccStr) (n : nat) : SuccStr\n  := Build_SuccStr (StratifiedType N n) (stratified_succ N n).\n\n(** Addition in successor structures *)\nFixpoint ss_add {N : SuccStr} (n : N) (k : nat) : N :=\n  match k with\n  | O   => n\n  | S k => (ss_add n k).+1\n  end.\n\nInfix \"+\" := ss_add : succ_scope.\n\nDefinition ss_add_succ {N : SuccStr} (n : N) (k : nat)\n  : (n + k.+1) = n.+1 + k.\nProof.\n  induction k.\n  + reflexivity.\n  + exact (ap ss_succ IHk).\nDefined.\n\n(** Nat and Int segmented by triples *)\nNotation \"'N3'\" := (Stratified (+N) 3) : succ_scope.\nNotation \"'Z3'\" := (Stratified (+Z) 3) : succ_scope.\n\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Homotopy/SuccessorStructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7288567279961562}}
{"text": "(** * Logic: Logic in Coq *)\n\n(* $Date: 2012-07-22 18:36:58 -0400 (Sun, 22 Jul 2012) $ *)\n(*Require Import LibTactics.*)\nRequire Export \"Prop\". \n(** Coq's built-in logic is extremely small: only [Inductive]\n    definitions, universal quantification ([forall]), and\n    implication ([->]) are primitive, while all the other familiar\n    logical connectives -- conjunction, disjunction, negation,\n    existential quantification, even equality -- can be defined using\n    just these. *)\nSearchAbout beq_nat.\n(* ########################################################### *)\n(** * Quantification and Implication *)\n\n(** In fact, [->] and [forall] are the _same_ primitive!  Coq's [->]\n    notation is actually just a shorthand for [forall].  The [forall]\n    notation is more general, because it allows us to _name_ the\n    hypothesis. *)\n\n(** For example, consider this proposition: *)\n\nDefinition funny_prop1 := \n  forall n, forall (E : beautiful n), beautiful (n+3).\n\n(** If we had a proof term inhabiting this proposition, it would\n    be a function with two arguments: a number [n] and some evidence\n    that [n] is beautiful.  But the name [E] for this evidence is not\n    used in the rest of the statement of [funny_prop1], so it's a bit\n    silly to bother making up a name.  We could write it like this\n    instead, using the dummy identifier [_] in place of a real\n    name: *)\n\nDefinition funny_prop1' := \n  forall n, forall (_ : beautiful n), beautiful (n+3).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition funny_prop1'' := \n  forall n, beautiful n -> beautiful (n+3). \n\n(** This illustrates that \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ########################################################### *)\n(** * Conjunction *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q). \n\n(** Note that, like the definition of [ev] in the previous\n    chapter, this definition is parameterized; however, in this case,\n    the parameters are themselves propositions, rather than numbers. *)\n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q]. \n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example : \n  (beautiful 0) /\\ (beautiful 3).\nProof.\n  apply conj.\n  (* Case \"left\". *) apply b_0.\n  (* Case \"right\". *) apply b_3.  Qed.\n\n(** Let's take a look at the proof object for the above theorem. *)\n\nPrint and_example. \n(* ===>  conj (beautiful 0) (beautiful 3) b_0 b_3\n            : beautiful 0 /\\ beautiful 3 *)\n\n(** Note that the proof is of the form\n    conj (beautiful 0) (beautiful 3) \n         (...pf of beautiful 3...) (...pf of beautiful 3...)\n    as you'd expect, given the type of [conj]. *)\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' : \n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n    Case \"left\". apply ev_0.\n    Case \"right\". apply ev_SS. apply ev_SS. apply ev_0.  Qed.\n\n(** Conversely, the [inversion] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop, \n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ]. \n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2) *)\nTheorem proj2 : forall P Q : Prop, \n  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ]. \n  apply HQ.  Qed.\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop, \n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HP HQ]. \n  split.  \n    (* Case \"left\". *) apply HQ. \n    (* Case \"right\".*) apply HP.  Qed.\n  \n(** Once again, we have commented out the [Case] tactics to make the\n    proof object for this theorem easy to understand.  Examining it\n    shows that all that is really happening is taking apart a record\n    containing evidence for [P] and [Q] and rebuilding it in the\n    opposite order: *)\n\nPrint and_commut.\n(* ===>\n   and_commut = \n     fun (P Q : Prop) (H : P /\\ Q) =>\n     let H0 := match H with\n               | conj HP HQ => conj Q P HQ HP\n               end \n     in H0\n     : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\n\n(** **** Exercise: 2 stars (and_assoc) *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [inversion] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop, \n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n  split.  \n     Case \"left\".  \n       split.\n       SCase \"lleft\".\n         apply HP.\n       SCase \"lright\".\n         apply HQ.\n     Case \"right\". apply HR.  Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (even__ev) *)\n(** Now we can prove the other direction of the equivalence of [even]\n   and [ev], which we left hanging in chapter [Prop].  Notice that the\n   left-hand conjunct here is the statement we are actually interested\n   in; the right-hand conjunct is needed in order to make the\n   induction hypothesis strong enough that we can carry out the\n   reasoning in the inductive step.  (To see why this is needed, try\n   proving the left conjunct by itself and observe where things get\n   stuck.) *)\n\nTheorem even__ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  intros.\n    induction n as [| n'].\n    split.\n      Case \"n = 0\".\n      intros.\n      SearchAbout ev.\n      apply ev_0.\n      intros.\n      inversion H.\n      SearchAbout ev.\n      split.\n      apply IHn'.\n      SearchAbout ev.\n      intros.\n      apply ev_SS.\n      apply IHn'.\n      inversion H.\n      apply H1.\nQed.\n      \n  \n(** [] *)\n\n(** **** Exercise: 2 stars, optional (conj_fact) *)\n(** Construct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\nfun (P Q R :Prop) (H1:P /\\ Q) (H2:Q /\\ R) => conj P R (proj1 P Q H1) (proj2 Q R H2).\n(** [] *)\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The familiar logical \"if and only if\" is just the\n    conjunction of two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q) \n                      (at level 95, no associativity) : type_scope.\n\nTheorem iff_implies : forall P Q : Prop, \n  (P <-> Q) -> P -> Q.\nProof.  \n  intros P Q H. \n  inversion H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop, \n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. \n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties) *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop, \n  P <-> P.\nProof. \n  intros.\n  split.\n  intros.\n  apply H.\n  intros.\n  apply H.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop, \n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof. \n  intros.\n  split.\n  inversion H as [H'1 H'2].\n  inversion H0 as [H0'1 H0'2].\n  intros.\n  apply H0'1.\n  apply H'1.\n  apply H1.\n  intros.\n  inversion H as [H'1 H'2].\n  inversion H0 as [H0'1 H0'2].\n  apply H'2.\n  apply H0'2.\n  apply H1.\nQed.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beautiful_iff_gorgeous) *)\n\n(** We have seen that the families of propositions [beautiful] and\n    [gorgeous] actually characterize the same set of numbers.\n    Prove that [beautiful n <-> gorgeous n] for all [n].  Just for\n    fun, write your proof as an explicit proof object, rather than\n    using tactics. (_Hint_: if you make use of previously defined\n    theorems, you should only need a single line!) *)\nSearchAbout beautiful.\nDefinition beautiful_iff_gorgeous :\n  forall n, beautiful n <-> gorgeous n :=\n  fun n=>conj (beautiful n -> gorgeous n) (gorgeous n -> beautiful n) (beautiful__gorgeous n) (gorgeous__beautiful n).\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q. \n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** Since [P \\/ Q] has two constructors, doing [inversion] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". right. apply HP.\n    Case \"right\". left. apply HQ.  Qed.\n\n(** **** Exercise: 2 stars, optional (or_commut'') *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\nDefinition or_commut_obj: forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P :=\n  fun (P Q:Prop) (H:P \\/ Q) => match H with\n           | or_introl P1 => (or_intror Q P P1)\n           | or_intror Q1 => (or_introl Q P Q1)\n           end.\n\n(** [] *)\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof. \n  intros P Q R. intros H. inversion H as [HP | [HQ HR]]. \n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars, recommended (or_distributes_over_and_2) *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  Case \"left\".\n    left.\n    apply H2.\n  Case \"right\".\n    inversion H1.\n    SCase \"left\". left. apply H3.\n    SCase \"right\". right. split. apply H2. apply H3.  Qed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_distributes_over_and) *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros.\n  split.\n  Case \"->\".\n    intros.\n    inversion H.\n    SCase \"left\".\n      split.\n      SSCase \"lleft\".\n        left.\n        apply H0.\n      SSCase \"lright\".\n        left.\n        apply H0.\n    SCase \"right\".\n      split.\n      SSCase \"rleft\".\n        inversion H0.\n          right.\n          apply H1.\n      SSCase \"rright\".\n        inversion H0.\n          right.\n          apply H2.\n  Case \"<-\".\n    intros.\n    inversion H.\n    inversion H0.\n    SCase \"left\".\n      left.\n      apply H2.\n    SCase \"right\".\n      inversion H1.\n      SSCase \"rleft\".\n        left.\n        apply H3.\n      SSCase \"rright\".\n        right.\n        split.\n        SSSCase \"rrleft\".\n          apply H2.\n        SSSCase \"rrright\".\n          apply H3.\nQed.\n  \n      \n  \n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_true__and : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n\nTheorem and__andb_true : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof. \n  intros.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". inversion H.\n      SCase \"c = false\". right. reflexivity.\n    Case \"b = false\". left. reflexivity.  Qed.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros.\n  destruct b.\n    Case \"b = true\".\n      left. reflexivity.\n    Case \"b = false\".\n     destruct c.\n      SCase \"c = true\". right. reflexivity. \n      SCase \"c = false\". inversion H.  Qed.\n  \n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof. \n  intros.\n  destruct b.\n    Case \"b = true\".\n      inversion H.\n    Case \"b = false\".\n     destruct c.\n      SCase \"c = true\". inversion H.\n      SCase \"c = false\". split.\n        SSCase \"left\". reflexivity. \n        SSCase \"right\". reflexivity. Qed.\n  \n(** [] *)\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := . \n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n(** **** Exercise: 1 star (False_ind_principle) *)\n(** Can you predict the induction principle for falsehood? *)\n\n(* Check False_ind. *)\n(** [] *)\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof. \n  intros contra.\n  inversion contra.  Qed. \n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, optional (True_induction) *)\n(** Define [True] as another inductively defined proposition.  What\n    induction principle will Coq generate for your definition?  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.  Alternatively, you may find it easiest\n    to start with the induction principle and work backwards to the\n    inductive definition.) *)\n(*Inductive True :Prop:= \ntr:True.\nTruth_ind: forall (P:Truth->Prop), P(t) -> forall t : Truth , P m  \n*)(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    just a theoretical curiosity: it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False : \n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof. \n  (* WORKED IN CLASS *)\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA. \n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, recommended (double_neg_inf) *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H.\n  unfold not.\n  intros.\n  apply H0.\n  apply H.\n  apply H1.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof. \n  intros P.\n  unfold not.\n  intros.\n  inversion H.\n  apply H1.\n  apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (informal_not_PNP) *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nTheorem five_not_even :  \n  ~ ev 5.\nProof. \n  (* WORKED IN CLASS *)\n  unfold not. intros Hev5. inversion Hev5 as [|n Hev3 Heqn]. \n  inversion Hev3 as [|n' Hev1 Heqn']. inversion Hev1.  Qed.\n\n(** **** Exercise: 1 star (ev_not_ev_S) *)\n(** Theorem [five_not_even] confirms the unsurprising fact that five\n    is not an even number.  Prove this more interesting fact: *)\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof. \n  unfold not. intros n H. induction H. (* not n! *)\n  intros.\n  inversion H.\n  intros.\n  apply IHev.\n  inversion H0.\n  apply H2.\nQed.\n(** [] *)\n\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H. \n  (* But now what? There is no way to \"invent\" evidence for [P]. *) \n  Admitted.\n\n(** **** Exercise: 5 stars, optional (classical_axioms) *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop, \n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop, \n  ~~P -> P.\nDefinition excluded_middle := 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 peirce_classic: peirce -> classic.\nProof.\n  unfold peirce, classic, not.\n  intros.\n  assert ((P -> False) -> P) as P_False_P.\n  intros P_False.\n  apply H0 in P_False.\n  inversion P_False.\n  apply H in P_False_P.\n  apply P_False_P.\nQed.\n\nTheorem classic_excluded_middle: classic->excluded_middle.\nProof.\n  unfold classic, excluded_middle, not.\n  intros.\n  apply H.\n  intros.\n  assert ((P -> False) -> False) as P_False_False.\n  intros.\n  apply H0.\n  right.\n  apply H1.\n  apply H in P_False_False.\n  apply or_introl with (Q:=(P -> False)) in P_False_False.\n  apply H0.\n  apply P_False_False.\nQed.\n\nTheorem excluded_middle_de_morgan_not_and_not:\n  excluded_middle->de_morgan_not_and_not.\nProof.\n  unfold de_morgan_not_and_not, excluded_middle, not.\n  intros.\n  assert (P\\/~P) as exc.\n   unfold not. apply H.\n  inversion exc.\n   left. apply H1.\n   unfold not in H1.\n   assert (Q\\/~Q) as exc1.\n    unfold not.\n    apply H.\n   inversion exc1.\n   right. apply H2.\n   unfold not in H2. apply ex_falso_quodlibet. apply H0. intuition.\nQed.\n\nTheorem de_morgan_not_and_not_implies_to_or: \n  de_morgan_not_and_not->implies_to_or.\nProof.\n  unfold de_morgan_not_and_not.\n  unfold implies_to_or.\n  unfold not.\n  intros.\n  apply H.\n  intros.\n  inversion H1.\n  apply H2.\n  intros.\n  apply H3.\n  apply H0.\n  apply H4.\nQed.\n\nTheorem implies_to_or_excluded_middle: \n  implies_to_or->excluded_middle.\nProof.\n  unfold excluded_middle.\n  unfold implies_to_or.\n  unfold not.\n  intros.\n  SearchAbout or.\n  apply or_commut.\n  apply H.\n  intros.\n  apply H0.\nQed.\n\n\nTheorem classic_peirce:\n  classic->peirce.\nProof.\n  unfold peirce, classic, not.\n  intros.\n  apply H.\n  intros.\n  apply H1.\n  apply H0.\n  intros.\n  apply H1 in H2.\n  inversion H2.\nQed.\n\n(** [] *)\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.  \n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n(** **** Exercise: 2 stars, recommended (not_eq_beq_false) *)\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof. \n  unfold not.\n  intros.\n  SearchAbout beq_nat.\n  remember (beq_nat n n') as be.\n  destruct be.\n  apply ex_falso_quodlibet.\n  apply H.\n  SearchAbout beq_nat.\n  apply beq_nat_eq.\n  apply Heqbe.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_false_not_eq) *)\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  unfold not.\n  intros.\n  rewrite H0 in H.\n  SearchAbout beq_nat.\n  replace (beq_nat m m) with true in H.\n  inversion H.\n  apply beq_nat_refl.\nQed.\n  \n(** [] *)\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can capture what this means with the\n    following 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    For example, consider this existentially quantified proposition: *)\n\nDefinition some_nat_is_even : Prop := \n  ex nat ev.\n\n(** To prove this proposition, we need to choose a particular number\n    as witness -- say, 4 -- and give some evidence that that number is\n    even. *)\n\nDefinition snie : some_nat_is_even := \n  ex_intro _ ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** Coq's notation definition facility can be used to introduce\n    more 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(** We can use the same set of tactics as always for\n    manipulating existentials.  For example, if to prove an\n    existential, we [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, again, that we have to explicitly give the witness. *)\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 * n) = 6.\nProof.\n  exists 2. \n  reflexivity.  Qed.\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(** **** 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(* Exists natural number n that beautiful (S n) provable. *)\n\n(** Complete the definition of the following proof object: *)\n\nDefinition p : ex nat (fun n => beautiful (S n)) :=\nex_intro nat (fun n => beautiful (S n)) 2 b_3 .\n  \n  \n(** [] *)\n\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" and \"there is no [x] for\n    which [P] does not hold\" are equivalent assertions. *)\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof. \n  unfold not.\n  intros.\n  inversion H0.\n  apply H1.\n  apply H.\nQed. \n(** [] *)\n\n(** **** Exercise: 3 stars, optional (not_exists_dist) *)\n(** The other direction requires the classical \"law of the excluded\n    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  unfold not.\n  intros.\n  assert (P x \\/ ~P x).\n  apply H.\n  inversion H1.\n  Case \"P x\".\n    apply H2.\n  Case \"~P x\".\n    unfold not in H2.\n    apply ex_falso_quodlibet.\n    apply H0. \n    exists (x).  \n    unfold not in H2.\n    apply H2.\nQed.\n  \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  intros.\n  split.\n  Case \"->\".\n    intros.\n    inversion H.\n    inversion H0.\n    SCase \"P witness\".\n      left.\n      exists witness.\n      apply H1.\n    SCase \"Q witness\".\n      right.\n      exists witness.\n      apply H1.\n  Case \"->\".\n    intros.\n    inversion H.\n    SCase \"exists x : X, P x\".\n      inversion H0.\n      exists witness.\n      left.\n      apply H1.\n    SCase \"exists x : X, Q x\".\n      inversion H0.\n      exists witness.\n      right.\n      apply H1.\nQed.\n(** [] *)\n\n(* Print dist_exists_or. *)\n\n\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has\n    roughly the following inductive definition.  (We enclose the\n    definition in a module to avoid confusion with the standard\n    library equality, which we have used extensively already.) *)\n\nModule MyEquality.\n\nInductive eq (X:Type) : X -> X -> Prop :=\n  refl_equal : forall x, eq X x x.\n\n(** Standard infix notation (using Coq's type argument synthesis): *)\n\nNotation \"x = y\" := (eq _ x y) \n                    (at level 70, no associativity) : type_scope.\n\n(** This is a bit subtle.  The way to think about it is that, given a\n    set [X], it defines a _family_ of propositions \"[x] is equal to\n    [y],\" indexed by pairs of values ([x] and [y]) from [X].  There is\n    just one way of constructing evidence for members of this family:\n    applying the constructor [refl_equal] to a type [X] and a value [x\n    : X] yields evidence that [x] is equal to [x]. *)\n\n(** Here is a slightly different definition -- the one that actually\n    appears in the Coq standard library. *)\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\nNotation \"x =' y\" := (eq' _ x y) \n                     (at level 70, no associativity) : type_scope.\n\n(** **** Exercise: 3 stars, optional (two_defs_of_eq_coincide) *)\n(** Verify that the two definitions of equality are equivalent. *)\n\nTheorem two_defs_of_eq_coincide : forall (X:Type) (x y : X),\n  x = y <-> x =' y.\nProof.\n  intros.\n  split.\n  intros.\n  destruct H.\n  apply refl_equal'.\n  intros.\n  destruct H.\n  apply refl_equal.\nQed.\n(** [] *)\n\n(** The advantage of the second definition is that the induction\n    principle that Coq derives for it is precisely the familiar\n    principle of _Leibniz equality_: what we mean when we say \"[x] and\n    [y] are equal\" is that every property on [P] that is true of [x]\n    is also true of [y].  *)\n\nCheck eq'_ind.\n(* ===> \n     forall (X : Type) (x : X) (P : X -> Prop),\n       P x -> forall y : X, x =' y -> P y \n\n   ===>  (i.e., after a little reorganization)\n     forall (X : Type) (x : X) forall y : X, \n       x =' y -> \n       forall P : X -> Prop, P x -> P y *)\n\n(** One important consideration remains.  Clearly, we can use\n    [refl_equal] to construct evidence that, for example, [2 = 2].\n    Can we also use it to construct evidence that [1 + 1 = 2]?  Yes:\n    indeed, it is the very same piece of evidence!  The reason is that\n    Coq treats as \"the same\" any two terms that are _convertible_\n    according to a simple set of computation rules.  These rules,\n    which are similar to those used by [Eval simpl], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.\n    \n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).  But you can see them\n    directly at work in the following explicit proof objects: *)\n\nDefinition four : 2 + 2 = 1 + 3 :=  \n  refl_equal nat 4. \n\nDefinition singleton : forall (X:Set) (x:X), []++[x] = x::[]  :=\n  fun (X:Set) (x:X) => refl_equal (list X) [x]. \n\nEnd MyEquality.\n\n(* ####################################################### *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves...\n\n    In general, the [inversion] tactic\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n        \n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are two\n   constructors, so two subgoals get generated.  The\n   conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.\n\n   _Example_: If we invert a hypothesis built with [and], there is\n   only one constructor, so only one subgoal gets generated.  Again,\n   the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.  The\n   constructor does have two arguments, though, and these can be seen\n   in the context in the subgoal.\n\n   _Example_: If we invert a hypothesis built with [eq], there is\n   again only one constructor, so only one subgoal gets generated.\n   Now, though, the form of the [refl_equal] constructor does give us\n   some extra information: it tells us that the two arguments to [eq]\n   must be the same!  The [inversion] tactic adds this fact to the\n   context.  *)\n\n(* ####################################################### *)\n(** * Relations as Propositions *)\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 LeFirstTry.  \n\n(** We've already seen an inductive definition of one\n    fundamental relation: equality.  Another useful one is the \"less\n    than or equal to\" 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\nEnd LeFirstTry.\n\n(** This is a reasonable definition of the [<=] relation, but we\n    can streamline it a little by observing that the left-hand\n    argument [n] is the same everywhere in the definition, so we can\n    actually make it a \"general parameter\" to the whole definition,\n    rather than an argument to each constructor.  This is similar to\n    what we did in our second definition of the [eq] relation,\n    above. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. \n    (The same was true of our second version of [eq].) *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(** By contrast, the induction principle that Coq calculates for the\n    first definition has a lot of extra quantifiers, which makes it\n    messier to work with when proving things by induction.  Here is\n    the induction principle for the first [le]: *)\n\n(* le_ind : \n     forall P : nat -> nat -> Prop,\n     (forall n : nat, P n n) ->\n     (forall n m : nat, le n m -> P n m -> P n (S m)) ->\n     forall n n0 : nat, le n n0 -> P n n0 *)\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)].) *)\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).\nProof. \n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H1.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\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, recommended (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  total_relation1:forall n m:nat, total_relation n m.\n\n(** [] *)\n\n(** **** Exercise: 2 stars (empty_relation) *)\n(** Define an inductive binary relation [empty_relation] (on numbers)\n    that never holds. *)\nInductive empty_relation: nat -> nat -> Prop := .\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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(*\n      - [R 1 1 2] provable c2 c3 c1\n      - [R 2 2 6] not provable 2+2 <>6\n      c4 and c5 are useless.\n      We need only c2 and c3 to reduce m, n and o to 0. Then we can use c1.  \n*)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (R_fact) *)  \n(** State and prove an equivalent characterization of the relation\n    [R].  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 RT1 : forall n, R 0 n n.\nProof.\n  intros.\n  induction n as [| n'].\n  SSCase \"n = 0\".\n    apply c1.\n  SSCase \"n = S n'\".\n    apply c3.\n    apply IHn'.\nQed.\nTheorem RT2 : forall n m, R n m (n+m).\nProof.\n  intros.\n  induction n as [| n'].\n  SSCase \"n = 0\".\n    apply RT1.\n  SSCase \"n = S n'\".\n    apply c2.\n    apply IHn'.\nQed.\n\nTheorem RT : forall m n o,\n  R m n o <-> m+n=o.\nProof.\n  split.\n  Case \"->\".\n    intros.\n    induction H.\n    reflexivity.\n    rewrite <- IHR.\n    reflexivity.\n    rewrite <- IHR.\n    rewrite plus_n_Sm.\n    reflexivity.\n    inversion IHR.\n    rewrite <- plus_n_Sm in H1.\n    inversion H1.\n    reflexivity.\n    rewrite plus_comm.\n    apply IHR.\n  Case \"->\".\n    intros.\n    rewrite <- H.\n    apply RT2.\nQed.\n    \n      \n\n\nEnd R.\n\n(** **** Exercise: 3 stars, recommended (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  |all0 : all X P []\n  |all1 : forall h l, P h -> all X P l -> all X P (h::l). \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? *)\nSearchAbout bool.\nTheorem forallbT : forall (X : Type) (test : X -> bool) (l : list X) , \n  forallb test l=true<->all X (fun n=>test n=true) l.\nProof.\n  split.\n  Case \"->\".\n    intros.\n    induction l as [| h l'].\n    SCase \"l=[]\".\n      apply all0.\n    SCase \"l=h::l'\".\n      apply all1.\n      simpl in H.\n      SearchAbout andb.\n      rewrite andb_true_elim1 with (b:=test h) (c:=forallb test l').\n      reflexivity.\n      apply H.\n      apply IHl'.\n      rewrite andb_true_elim2 with (b:=test h) (c:=forallb test l').\n      reflexivity.\n      apply H.\n  Case \"<-\".\n    intros.\n    induction H.\n    SCase \"all0\".\n      reflexivity.\n    SCase \"all1\".\n      simpl.\n      rewrite H.\n      simpl.\n      apply IHall.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (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\nInductive mrg (X : Type) (P : X -> Prop) : list X -> list X -> list X -> Prop :=\n  |mrg0 : mrg X P [] [] []\n  |mrg1 : forall h l1 l2 l3, P h -> mrg X P l1 l2 l3 -> mrg X P (h::l1) (h::l2) l3\n  |mrg2 : forall h l1 l2 l3, ~P h -> mrg X P l1 l2 l3 -> mrg X P (h::l1) l2 (h::l3). \n\n\nTheorem mrgT : forall (X : Type) (test : X -> bool) (l1 l2 l3 : list X) , \n  mrg X (fun n=>test n=true) l1 l2 l3->  filter test l1=l2.\nProof.\n  intros.\n    induction H.\n    Case \"mrg0\".\n      simpl.\n      reflexivity.\n    Case \"mrg1\".\n      simpl.\n      rewrite H.\n      rewrite IHmrg.\n      reflexivity.\n    Case \"mrg2\".\n      simpl.\n      unfold not in H.\n      remember (test h) as t.\n      destruct t.\n      SCase \"true\".\n        apply ex_falso_quodlibet.\n        apply H.\n        reflexivity.\n      SCase \"false\".\n        apply IHmrg.\nQed.\n    \n(** [] *)\n\n(** **** Exercise: 5 stars, 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\nInductive subs (X : Type): list X -> list X -> Prop :=\n  |subs0 : subs X [] []\n  |subs1 : forall h l1 l2, subs X l1 l2 -> subs X (h::l1) (h::l2)\n  |subs2 : forall h l1 l2, subs X l1 l2 -> subs X l1 (h::l2). \nTheorem leT :forall n1 n2, n1<=n2->S n1<= S n2.\n  Proof.\n    intros.\n    induction H.\n      apply le_n.\n      apply le_S.\n      apply IHle.\nQed.\n\n\nTheorem fT : forall (X : Type) (test : X -> bool) (l1 l2: list X) , \n  ((subs X l1 l2)/\\forallb test l1=true)->((length l1) <= length (filter test l2)).\n  Proof.\n    intros.\n    induction H.\n    induction H.\n    Case \"subs0\".\n      simpl.\n      apply le_n.\n    Case \"subs1\".\n      simpl.\n      remember (test h) as t.\n      destruct t.\n      SCase \"true\".\n        simpl.\n        apply leT.\n        apply IHsubs.\n        inversion H0.\n        rewrite H2.\n        rewrite <- Heqt in H2.\n        simpl in H2.\n        apply H2.\n      SCase \"false\".\n        simpl in H0.\n        rewrite <- Heqt in H0.\n        inversion H0.        \n    Case \"subs2\".\n      simpl.\n      remember (test h) as t.\n      destruct t.\n      SCase \"true\".\n        simpl.\n        apply le_S.\n        apply IHsubs.\n        apply H0.\n      SCase \"false\".\n        apply IHsubs.\n        apply H0.\nQed.    \n      \n      \n(** [] *)\n\n(** **** Exercise: 4 stars, optional (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\nTheorem app_nil_end : forall (X:Type) (l : list X), l++[]=l.\nProof.\n  intros.\n  induction l. \n  reflexivity.\n  rewrite<- IHl at 2.\n  simpl.\n  reflexivity.\nQed.    \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*)\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.\n\nProof.\n  intros X.\n  induction xs.\n  simpl.\n  intros.\n  right.\n  apply H.\n  induction ys.\n  simpl.\n  rewrite app_nil_end.\n  intros.\n  left.\n  apply H.\n  intros.\n  inversion H.\n  \n  Case \"ai_here\".\n    left.\n    apply ai_here.\n  Case \"ai_later\".\n    subst.\napply IHxs in H1. \ninversion H1.\n  left.\n    apply ai_later.\n    apply H0.\n    right.\n    apply H0.\nQed.\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  intros.\n  inversion H.\n  Case \"left\".\n    induction xs.\n    SCase \"xs=[]\".\n      inversion H0.\n    SCase \"xs=x0 :: xs\".\n      inversion H0.\n      apply ai_here.\n      apply ai_later.\n      apply IHxs.\n      left.\n      apply H2.\n      apply H2.\n  Case \"right\".\n    induction xs.\n    SCase \"xs=[]\".\n      apply H0.\n    SCase \"xs=x0 :: xs\".\n      apply ai_later.\n      apply IHxs.\n      right.\n      apply H0.\nQed.\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\nInductive disjoint {X:Type} : list X -> list X -> Prop :=\n  | disjoint0 : forall l, disjoint [] l\n  | disjoint1 : forall h l1 l2, ~appears_in h l2 -> disjoint l1 l2 -> disjoint (h::l1) l2\n  | disjoint2 : forall h l1 l2, ~appears_in h l1 -> disjoint l1 l2 -> disjoint l1 (h::l2).\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\nInductive no_repeats {X:Type} : list X -> Prop :=\n  | no_repeats0 : no_repeats []\n  | no_repeats1 : forall h l, ~appears_in h l-> no_repeats (l) -> no_repeats (h::l).\n(** Finally, state and prove one or more interesting theorems relating\n    [disjoint], [no_repeats] and [++] (list append).  *)\n\n(** [] *)\n\n(* ######################################################### *)\n(** ** Digression: More Facts about [<=] and [<] *)\n\n(** Let's pause briefly to record several facts about the [<=]\n    and [<] relations that we are going to need later in the\n    course.  The proofs make good practice exercises. *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros.\n  induction n as [|n'].\n  Case \"n=0\".\n    apply le_n.\n  Case \"n=S n'\".\n    apply le_S.\n    apply IHn'.\nQed.\n    \n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof. \n  apply leT.\nQed.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof. \n  intros n m.  generalize dependent n.  induction m.\n  Case \"m=0\".\n    intros.\n    destruct n.\n    SCase \"n=0\".\n      apply le_n.\n    SCase \"n=S n'\".\n      inversion H.\n      inversion H1.\n  Case \"m=S m'\".\n    intros.\n    destruct n.\n    SCase \"n=0\".\n      apply le_S.\n      apply IHm.\n      inversion H.\n      apply H1.\n    SCase \"n=S n'\".\n      inversion H.\n      apply le_n.\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  intros.\n  rewrite plus_comm.\n  induction b as [| b'].\n  Case \"b=0\".\n    apply le_n.\n  Case \"b=S b'\".\n    apply le_S.\n    apply IHb'.\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  induction H.\n  Case \"le_n\".\n    split.\n    SCase \"left\".\n      replace (S (n1 + n2)) with (S n1 + n2).\n      apply le_plus_l.\n      simpl.\n      reflexivity.\n    SCase \"right\".\n      rewrite plus_comm.\n      replace (S (n2 + n1)) with (S n2 + n1).\n      apply le_plus_l.\n      simpl.\n      reflexivity.\n  Case \"le_S\".\n    inversion IHle.\n    split.\n    SCase \"left\".\n      apply le_S.\n      apply H0.\n    SCase \"right\".\n      apply le_S.\n      apply H1.\nQed.\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 ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof. \n  unfold lt.\n  intros.\n  generalize dependent m. \n  induction n.\n  Case \"n=0\".\n    intros.\n    replace (m) with (0 + m).\n    apply le_plus_l.\n    simpl.\n    reflexivity.\n  Case\"n=S n\".\n    intros.\n    destruct m.\n    SCase\"m=0\".\n      inversion H.\n    SCase\"m=S m\".\n      apply n_le_m__Sn_le_Sm.\n      apply IHn.  \n      simpl in H.\n      apply H.\nQed.\n\nTheorem ble_nat_n_Sn_false : forall n m,\n  ble_nat n (S m) = false ->\n  ble_nat n m = false.\nProof. \n  intros.\n  generalize dependent n. \n  induction m.\n  Case \"m=0\".\n    intros.\n    destruct n.\n    SCase\"n=0\".\n      inversion H.\n    SCase\"n=S n\".\n    simpl.\n    reflexivity.\n  Case\"m=S m\".\n    intros.\n    destruct n.\n    SCase\"n=0\".\n      inversion H.\n    SCase\"n=S n\".\n      simpl.\n      apply IHm.\n      simpl in H.\n      apply H.\nQed.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* Hint: Do the right induction! *)\n\n  unfold not.\n  intros. \n  generalize dependent n. \n  induction m.\n  Case \"m=0\".\n    intros.\n    destruct n.\n    SCase\"n=0\".\n      inversion H.\n    SCase\"n=S n\".\n      inversion H0.\n  Case\"m=S m\".\n    intros.\n    destruct n.\n    SCase\"n=0\".\n      inversion H.\n    SCase\"n=S n\".\n      apply Sn_le_Sm__n_le_m in H0.\n      apply IHm with (n:=n).\n      simpl in H.\n      apply H.\n      apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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  | nostutter0 : nostutter []\n  | nostutter1 : forall n, nostutter [n]\n  | nostutter2 : forall n m l, ~n=m -> nostutter (m::l)->nostutter(n::m::l)\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(*\n  apply nostutter2.\n  unfold not.\n  intros.\n  inversion H.\n  apply nostutter2.\n  unfold not.\n  intros.\n  inversion H.\n  apply nostutter2.\n  unfold not.\n  intros.\n  inversion H.\n  apply nostutter2.\n  unfold not.\n  intros.\n  inversion H.\n  apply nostutter2.\n  unfold not.\n  intros.\n  inversion H.\n  apply nostutter1.\n Qed.*) Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n(* \n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_2:  nostutter [].\n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n\nExample test_nostutter_3:  nostutter [5].\n  Proof. repeat constructor; apply beq_false_not_eq; 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 H1; auto. Qed.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (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 this 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  intros.\n  induction l1 as [|h l1'].\n  Case \"l1=[]\".\n    reflexivity.\n  Case \"l1=h::l1'\".\n    simpl.\n    rewrite IHl1'.\n    reflexivity.\nQed.\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  intros.\n  induction l as [|h l'].\n  Case \"l=[]\".\n    inversion H.\n  Case \"l=h::l'\".\n    induction H.\n    SCase \"ai_here\".\n      exists [].\n      exists l.\n      reflexivity.\n    SCase \"ai_later\".\n      inversion IHappears_in.\n      inversion H0.\n      exists (b::witness).\n      exists witness0.\n      rewrite H1.\n      reflexivity.\nQed.\n\n    \n    \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  repeats0 : forall l1 l2 l3 x,repeats (l1++(x::l2)++(x::l3))\n.\n*)\nInductive repeats {X:Type} : list X -> Prop :=\n  |repeats0 : forall l x,appears_in x l -> repeats (x::l)\n  |repeats1 : forall l x,repeats l -> repeats (x::l)\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 an\n   assignment of items to labels: if there are more items than labels,\n   at least two items must have the same label.  You will almost\n   certainly need to use the [excluded_middle] hypothesis. *)\n\n(*\nTheorem app_nil : forall {X:Type} (l:list X), \n   l ++ [] = l.\nProof.\n   intros.\n   induction l.\n   Case \"l = nil\".\n     reflexivity.\n   Case \"l = cons n l1'\".\n     simpl. rewrite IHl. reflexivity. Qed.\n\nTheorem app_ass : forall {X:Type} (l1 l2 l3:list X), \n   (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n   intros X 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\nTheorem app_dist : forall {X:Type} x (l1 l2:list X), \n   x::(l1 ++ l2) = (x::l1) ++ l2.\nProof.\n   intros. induction l1 as [| n l1'].\n   Case \"l1 = nil\".\n     reflexivity.\n   Case \"l1 = cons n l1'\".\n     simpl. reflexivity. Qed.\n\nTheorem app_dist1 : forall {X:Type} x (l1 l2 l3:list X), \n   x::(l1 ++ l2)++l3 = x::l1 ++ l2++l3.\nProof.\n   intros.\n   rewrite <-app_ass.\n   reflexivity.\n Qed.\n\nTheorem rep1:forall {X:Type} x (l:list X),\n  excluded_middle -> \n  repeats (x::l)->repeats (l++[x]).\nProof. \n  intros.\n  inversion H0.\n  induction l.\n  rewrite <- H2.\n  simpl.\n  apply repeats0.\n  destruct l1.\n  inversion H2.\n  replace ((l2 ++ x :: l3) ++ [x]) with (l2 ++ (x :: l3) ++ ([x])).\n  apply repeats0.\n  simpl.\n  rewrite app_ass.\n  reflexivity.\n  inversion H2.\n  replace ((l1 ++ x0 :: l2 ++ x0 :: l3) ++ [x]) with (l1 ++ (x0 :: l2) ++ (x0 :: l3 ++ [x])).\n  apply repeats0.\n  simpl.\n  rewrite app_ass.\n  replace ((x0 :: l2 ++ x0 :: l3) ++ [x]) with (x0 :: l2 ++ x0 :: l3 ++ [x]).\n  reflexivity.\n  simpl.\n  rewrite app_dist1.\n  rewrite <- app_dist.\n  reflexivity.\n Qed.\n\nTheorem app_dist2 : forall {X:Type} x1 x2 (l1 l2 :list X), \n   l1++[x1] = l2++[x2] ->x1=x2.\nProof. \n  intros X x1 x2 l1.\n  induction l1.\n  intros.\n  inversion H.\n  destruct l2.\n  inversion H.\n  reflexivity.\n  inversion H1.\n  destruct l2.\n  inversion H3.\n  inversion H3.\n  intros.\n  destruct l2.\n  inversion H.\n  destruct l1.\n  inversion H2.\n  inversion H2.\n  inversion H.\n  apply IHl1 with (l2:=l2).\n  apply H2.\n Qed.\n\nTheorem app_eq :forall {X:Type} x (l1 l2 :list X), \n   x::l1 = x::l2 <->l1=l2.\nProof. \n\n  intros X x1 x2 l1.\n  split.\n  induction l1.\n  intros.\n  inversion H.\n  reflexivity.\n  intros.\n  inversion H.\n  reflexivity.\n\n  intros.\n  rewrite H.\n  reflexivity.\n Qed.\n  \n\nTheorem app_dist3 : forall {X:Type} x1 x2 (l1 l2 :list X), \n   l1++[x1] = l2++[x2] ->l1=l2.\nProof. \n  intros X x1 x2 l1.\n  induction l1.\n  intros.\n  inversion H.\n  destruct l2.\n  inversion H.\n  reflexivity.\n  inversion H1.\n  destruct l2.\n  inversion H3.\n  inversion H3.\n  intros.\n  destruct l2.\n  inversion H.\n  destruct l1.\n  inversion H2.\n  inversion H2.\n  inversion H.\n  apply app_eq.\n  apply IHl1.\n  apply H2.\n Qed.\n  \nFixpoint wlast {X:Type} (l : list X) :\n  match l with\n  |[] => return []\n  |h::l' => .\n\nTheorem tl_intr : forall {X:Type} x1 x2 (l1 l2 :list X), \n   x1::l1 = l2++[x2] ->tl(x1::l1)=l2(*\\/x1=x2*).\nProof.\n  intros.\n  induction l2.\n  destruct l1.\n  simpl.\n  reflexivity.\n  inversion H.\n  \n\n\nTheorem rep2:forall {X:Type} x (l:list X),\n  excluded_middle ->repeats (l++[x])-> \n  repeats (x::l).\nProof. \n  intros.\n  inversion H0.\n  destruct l3.\n  replace (l1 ++ x0 :: l2 ++ [x0]) with ((l1 ++ x0 :: l2) ++ [x0]) in H2.\n  inversion H2.\n  apply app_dist2 in H2.\n  inversion H3.\n  apply app_dist3 in H3.\n  rewrite <- H2.\n  rewrite <- H3.\n  replace (x0 :: l1 ++ x0 :: l2) with ([]++(x0 :: l1) ++ x0 :: l2).\n  apply repeats0.\n  simpl.\n  reflexivity.\n  rewrite app_ass.\n  rewrite app_dist.\n  reflexivity.\n  \n  destruct l1.\n  inversion H2.\n  apply app_dist2 in H4.\n  rewrite H4.\n  replace (x :: x :: l) with ([]++ (x :: []) ++x :: l).\n  apply repeats0.\n  simpl.\n  reflexivity.\n  apply app_dist2 in H3.\n  replace ((l1 ++ x0 :: l2 ++ x0 :: l3) ++ [x]) with (l1 ++ (x0 :: l2) ++ (x0 :: l3 ++ [x])).\n  apply repeats0.\n  simpl.\n  rewrite app_ass.\n  replace ((x0 :: l2 ++ x0 :: l3) ++ [x]) with (x0 :: l2 ++ x0 :: l3 ++ [x]).\n  reflexivity.\n  simpl.\n  rewrite app_dist1.\n  rewrite <- app_dist.\n  reflexivity.\n Qed.\n\nTheorem rep2:forall {X:Type} (l1 l2:list X),\n  excluded_middle -> \n  repeats (l1++l2)->repeats (l2++l1).\nProof. \n  intros.\n  inversion H0.\n  generalize dependent l1. \n  induction l2.\n  intros.\n  rewrite app_nil in H2. \n  rewrite <- H2.\n  simpl.\n  apply repeats0.\n  intros.\n  rewrite <- app_dist.\n  apply rep1.\n  destruct l1.\n  inversion H2.\n  replace ((l2 ++ x :: l3) ++ [x]) with (l2 ++ (x :: l3) ++ ([x])).\n  apply repeats0.\n  simpl.\n  rewrite app_ass.\n  reflexivity.\n  inversion H2.\n  replace ((l1 ++ x0 :: l2 ++ x0 :: l3) ++ [x]) with (l1 ++ (x0 :: l2) ++ (x0 :: l3 ++ [x])).\n  apply repeats0.\n  simpl.\n  rewrite app_ass.\n  replace ((x0 :: l2 ++ x0 :: l3) ++ [x]) with (x0 :: l2 ++ x0 :: l3 ++ [x]).\n  reflexivity.\n  simpl.\n  rewrite app_dist1.\n  rewrite <- app_dist.\n  reflexivity.\n Qed.\n  \nTheorem rep1:forall {X:Type} (l1 l2 l3:list X),\n  excluded_middle -> \n  repeats (l1++l3)->repeats (l1++l2++l3).\nProof. \n  intros.\n  induction l1.\n  Case \"l1=[]\".\n    inversion H0.\n    simpl in H1.\n    rewrite <- H1.\n    simpl.\n    replace (l2 ++ l1 ++ x :: l0 ++ x :: l4) with ((l2 ++ l1 )++ (x :: l0) ++( x :: l4)).\n    apply repeats0.\n    simpl.\n    apply app_ass.\n  Case \"l1=x::l1\".\n    inversion H0.\n    assert (x=x0\\/~x=x0).\n    apply H.\n    inversion H1.\n    rewrite <- H3 in H2.\n    \n\nTheorem repAp:forall {X:Type} (x:X) (l:list X),\n  appears_in x l->repeats (x::l).\nProof. \n  intros. \n  induction H.\n  Case \"ap_here\".\n    replace (x :: x :: l) with ([]++(x::[])++(x::l)).\n    apply repeats0.\n    simpl.\n    reflexivity.\n  Case \"ap_later\".\n*)\n\nTheorem Slength : forall {X:Type} x (l:list X),\nlength (x::l)=S (length l).\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\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.  intros X l1. induction l1.\n  Case \"l1=[]\".\n    intros.\n    simpl in H1.\n    inversion H1.\n  Case \"l1=x::l1\".\n    intros.\n    assert (appears_in x l1 \\/ ~appears_in x l1).\n    SCase \"appears_in x l1\".\n      apply H.\n      inversion H2.\n      apply repeats0.\n      apply H3.\n    SCase \"~appears_in x l1\".\n    (*  destruct l2.\n      SSCase \"l2=[]\".\n        apply ex_falso_quodlibet.\n        assert (appears_in x []->False).\n        intros.\n        inversion H4.\n        apply H4.\n        apply H0.\n        apply ai_here.\n      SSCase \"l2=x0::l2\".*)\n        apply repeats1.\n        apply IHl1 with (l2:=remove x l2).\n        apply H.\n        intros.\n        apply H0.\n        apply ai_later.\n        apply H4.\n(** [] *)\n\n(* ####################################################### *)\n(** * Informal Proofs *)\n\n(** Q: What is the relation between a formal proof of a proposition\n       [P] and an informal proof of the same proposition [P]?\n\n    A: The latter should _teach_ the reader how to produce the\n       former.\n\n    Q: How much detail is needed?\n\n    A: There is no single right answer; rather, there is a range\n       of choices.  \n\n      At one end of the spectrum, we can essentially give the\n      reader the whole formal proof (i.e., the informal proof\n      amounts to just transcribing the formal one into words).\n      This gives the reader the _ability_ to reproduce the formal\n      one for themselves, but it doesn't _teach_ them anything.\n\n      At the other end of the spectrum, we can say \"The theorem\n      is true and you can figure out why for yourself if you\n      think about it hard enough.\"  This is also not a good\n      teaching strategy, because usually writing the proof\n      requires some deep insights into the thing we're proving,\n      and most readers will give up before they rediscover all\n      the same insights as we did.\n\n      In the middle is the golden mean -- a proof that includes\n      all of the essential insights (saving the reader the hard\n      part of work that we went through to find the proof in the\n      first place) and clear high-level suggestions for the more\n      routine parts to save the reader from spending too much\n      time reconstructing these parts (e.g., what the IH says and\n      what must be shown in each case of an inductive proof), but\n      not so much detail that the main ideas are obscured. \n\n   Another key point: if we're talking about a formal proof of a\n   proposition P and an informal proof of P, the proposition P doesn't\n   change.  That is, formal and informal proofs are _talking about the\n   same world_ and they _must play by the same rules_. *)\n\n(* ####################################################### *)\n(** ** Informal Proofs by Induction *)\n\n(** Since we've spent much of this chapter looking \"under the hood\" at\n    formal proofs by induction, now is a good moment to talk a little\n    about _informal_ proofs by induction.\n\n    In the real world of mathematical communication, written proofs\n    range from extremely longwinded and pedantic to extremely brief\n    and telegraphic.  The ideal is somewhere in between, of course,\n    but while you are getting used to the style it is better to start\n    out at the pedantic end.  Also, during the learning phase, it is\n    probably helpful to have a clear standard to compare against.\n    With this in mind, we offer two templates below -- one for proofs\n    by induction over _data_ (i.e., where the thing we're doing\n    induction on lives in [Type]) and one for proofs by induction over\n    _evidence_ (i.e., where the inductively defined thing lives in\n    [Prop]).  In the rest of this course, please follow one of the two\n    for _all_ of your inductive proofs. *)\n\n(** *** Induction Over an Inductively Defined Set *)\n \n(** _Template_: \n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n \n    _Example_:\n \n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if length [[] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of index.\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n            length l = length (x::l') = S (length l'),\n          it suffices to show that \n            index (S (length l')) l' = None.\n]]  \n          But this follows directly from the induction hypothesis,\n          picking [n'] to be length [l'].  [] *)\n \n(** *** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_. \n\n    _Template_:\n \n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n \n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(* ################################################### *)\n(** ** Induction Principles for [/\\] and [\\/] *)\n\n(** The induction principles for conjunction and disjunction are a\n    good illustration of Coq's way of generating simplified induction\n    principles for [Inductive]ly defined propositions, which we\n    discussed in the last chapter.  You try first: *)\n\n(** **** Exercise: 1 star, optional (and_ind_principle) *)\n(** See if you can predict the induction principle for conjunction. *)\n\n(* Check and_ind. *)\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_ind_principle) *)\n(** See if you can predict the induction principle for disjunction. *)\n\n(* Check or_ind. *)\n(** [] *)\n\nCheck and_ind.\n\n(** From the inductive definition of the proposition [and P Q]\n     Inductive and (P Q : Prop) : Prop :=\n       conj : P -> Q -> (and P Q).\n    we might expect Coq to generate this induction principle\n     and_ind_max :\n       forall (P Q : Prop) (P0 : P /\\ Q -> Prop),\n            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->\n            forall a : P /\\ Q, P0 a\n    but actually it generates this simpler and more useful one:\n     and_ind :\n       forall P Q P0 : Prop,\n            (P -> Q -> P0) ->\n            P /\\ Q -> P0\n    In the same way, when given the inductive definition of [or P Q]\n     Inductive or (P Q : Prop) : Prop :=\n       | or_introl : P -> or P Q\n       | or_intror : Q -> or P Q.\n    instead of the \"maximal induction principle\"\n     or_ind_max :\n       forall (P Q : Prop) (P0 : P \\/ Q -> Prop),\n            (forall a : P, P0 (or_introl P Q a)) ->\n            (forall b : Q, P0 (or_intror P Q b)) ->\n            forall o : P \\/ Q, P0 o\n    what Coq actually generates is this:\n     or_ind :\n       forall P Q P0 : Prop,\n            (P -> P0) ->\n            (Q -> P0) ->\n            P \\/ Q -> P0\n]] \n*)\n\n(* ######################################################### *)\n(** ** Explicit Proof Objects for Induction *)\n\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n    \n(** Recall the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\n(* Check nat_ind. *)\n(* ===> \n   nat_ind : forall P : nat -> Prop,\n      P 0%nat -> \n      (forall n : nat, P n -> P (S n)) -> \n      forall n : nat, P n  *)\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n \nPrint nat_ind.  \n(* ===> (after some manual tidying)\n   nat_ind =\n    fun (P : nat -> Type) \n        (f : P 0) \n        (f0 : forall n : nat, P n -> P (S n)) =>\n          fix F (n : nat) : P n :=\n             match n as n0 return (P n0) with\n            | 0 => f\n            | S n0 => f0 n0 (F n0)\n            end.\n*)\n\n(** We can read this as follows: \n     Suppose we have evidence [f] that [P] holds on 0,  and \n     evidence [f0] that [forall n:nat, P n -> P (S n)].  \n     Then we can prove that [P] holds of an arbitrary nat [n] via \n     a recursive function [F] (here defined using the expression \n     form [Fix] rather than by a top-level [Fixpoint] \n     declaration).  [F] pattern matches on [n]: \n      - If it finds 0, [F] uses [f] to show that [P n] holds.\n      - If it finds [S n0], [F] applies itself recursively on [n0] \n         to obtain evidence that [P n0] holds; then it applies [f0] \n         on that evidence to show that [P (S n)] holds. \n    [F] is just an ordinary recursive function that happens to \n    operate on evidence in [Prop] rather than on terms in [Set].\n \n    Aside to those interested in functional programming: You may\n    notice that the [match] in [F] requires an annotation [as n0\n    return (P n0)] to help Coq's typechecker realize that the two arms\n    of the [match] actually return the same type (namely [P n]).  This\n    is essentially like matching over a GADT (generalized algebraic\n    datatype) in Haskell.  In fact, [F] has a _dependent_ type: its\n    result type depends on its argument; GADT's can be used to\n    describe simple dependent types like this.\n \n    We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  Recall our desire to\n    prove that\n\n    [forall n : nat, even n -> ev n].\n \n    Attempts to do this by standard induction on [n] fail, because the\n    induction principle only lets us proceed when we can prove that\n    [even n -> even (S n)] -- which is of course never provable.  What\n    we did earlier in this chapter was a bit of a hack:\n \n    [Theorem even__ev : forall n : nat,\n     (even n -> ev n) /\\ (even (S n) -> ev (S n))].\n \n    We can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n \n *)\n \n Definition nat_ind2 : \n    forall (P : nat -> Prop), \n    P 0 -> \n    P 1 -> \n    (forall n : nat, P n -> P (S(S n))) -> \n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS => \n          fix f (n:nat) := match n return P n with \n                             0 => P0 \n                           | 1 => P1 \n                           | S (S n') => PSS n' (f n') \n                          end.\n \n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive (try\n     it!).\n\n     The [induction ... using] tactic gives a convenient way to\n     specify a non-standard induction principle like this. *)\n \nLemma even__ev' : forall n, even n -> ev n.\nProof. \n intros.  \n induction n as [ | |n'] using nat_ind2. \n  Case \"even 0\". \n    apply ev_0.  \n  Case \"even 1\". \n    inversion H.\n  Case \"even (S(S n'))\". \n    apply ev_SS. \n    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H. \nQed. \n\n(* ######################################################### *)\n(** ** The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is \"why\n    trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard Correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on.\n\n    There are a few additional wrinkles:\n\n    - Since Coq types can themselves be expressions, the checker must\n      normalize these (by using the conversion rules) before\n      comparing them.\n\n    - The checker must make sure that [match] expressions are\n      _exhaustive_.  That is, there must be an arm for every possible\n      constructor.  To see why, consider the following alleged proof\n      object:\n      Definition or_bogus : forall P Q, P \\/ Q -> P :=\n        fun (P Q : Prop) (A : P \\/ Q) =>\n           match A with\n           | or_introl H => H\n           end. \n      All the types here match correctly, but the [match] only\n      considers one of the possible constructors for [or].  Coq's\n      exhaustiveness check will reject this definition.\n\n    - The checker must make sure that each [fix] expression\n      terminates.  It does this using a syntactic check to make sure\n      that each recursive call is on a subexpression of the original\n      argument.  To see why this is essential, consider this alleged\n      proof:\n          Definition nat_false : forall (n:nat), False :=\n             fix f (n:nat) : False := f n. \n      Again, this is perfectly well-typed, but (fortunately) Coq will\n      reject it. *)\n\n(** Note that the soundness of Coq depends only on the correctness of\n    this typechecking engine, not on the tactic machinery.  If there\n    is a bug in a tactic implementation (and this certainly does\n    happen!), that tactic might construct an invalid proof term.  But\n    when you type [Qed], Coq checks the term for validity from\n    scratch.  Only lemmas whose proofs pass the type-checker can be\n    used in further proof developments.  *)\n\n\n", "meta": {"author": "AntonMilenin", "repo": "CoqBook", "sha": "2f8fc7f5da81079fbbb2a2fa86437d02adf7638f", "save_path": "github-repos/coq/AntonMilenin-CoqBook", "path": "github-repos/coq/AntonMilenin-CoqBook/CoqBook-2f8fc7f5da81079fbbb2a2fa86437d02adf7638f/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7288567279961562}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Logic.\nFrom Coq Require Export Lia.\n\nFixpoint div2(n:nat):=\n  match n with\n    0 => 0\n  | 1 => 0\n  | S (S n) => S (div2 n)\n  end.\n\nDefinition f(n:nat):=\n  if even n then div2 n\n  else (3 * n) + 1.\n\nInductive reaches_1: nat -> Prop :=\n  | term_done: reaches_1 1\n  | term_more (n:nat) : reaches_1 (f n) -> reaches_1 n.\n\nConjecture collatz: forall n, reaches_1 n.\n\nModule LePlayground.\n\nInductive le:nat->nat->Prop:=\n  | le_n (n : nat) : le n n\n  | le_S (n m : nat) : le n m -> le n (S m).\nEnd LePlayground.\n\nInductive clos_trans {X: Type} (R: X->X->Prop):X->X->Prop:=\n  | t_step (x y: X): R x y -> clos_trans R x y\n  | t_trans (x y z: X):\n    clos_trans R x y ->\n    clos_trans R y z ->\n    clos_trans R x z.\n\nInductive clos_reflex_trans {X: Type} (R: X->X->Prop):X->X->Prop:=\n  | t_step' (x y: X): R x y -> clos_reflex_trans R x y\n  | t_reflex' (x: X): clos_reflex_trans R x x\n  | t_trans' (x y z: X):\n    clos_reflex_trans R x y ->\n    clos_reflex_trans R y z ->\n    clos_reflex_trans R x z.\n\nInductive clos_reflex_symm_trans {X: Type} (R: X->X->Prop):X->X->Prop:=\n  | t_step'' (x y: X): R x y -> clos_reflex_symm_trans R x y\n  | t_reflex'' (x: X): clos_reflex_symm_trans R x x\n  | t_symm'' (x y: X): R x y -> clos_reflex_symm_trans R y x\n  | t_trans'' (x y z: X):\n    clos_reflex_symm_trans R x y ->\n    clos_reflex_symm_trans R y z ->\n    clos_reflex_symm_trans R x z.\n\nInductive Perm3 {X:Type}: list X -> list X -> Prop :=\n| perm3_swap12 (a b c:X):\n  Perm3 [a;b;c] [b;a;c]\n| perm3_swap23 (a b c:X):\n  Perm3 [a;b;c] [a;c;b]\n| perm3_trans (l1 l2 l3: list X):\n  Perm3 l1 l2 -> Perm3 l2 l3 -> Perm3 l1 l3.\n\n(* Evenness (yet again) *)\n\nInductive ev:nat -> Prop :=\n | ev_0 : ev 0\n | ev_SS (n:nat) (H:ev n): ev (S (S n)).\n\n\nTheorem ev_double: forall n,\n  ev (double n).\nProof.\n  induction n. simpl. apply ev_0.\n  simpl. apply ev_SS. apply IHn.\nQed.\n\nTheorem ev_inversion: forall n:nat,\n  ev n ->\n  (n = 0) \\/ (exists n', n = S (S n') /\\ ev n').\nProof.\n  intros n E. destruct E.\n  - left. reflexivity.\n  - right. exists n. split. reflexivity. apply E.\nQed.\n\nTheorem evSS_ev:forall n, ev (S (S n)) -> ev n.\nProof.\n  intros n H. apply ev_inversion in H. destruct H as [H0|H1].\n  - discriminate H0.\n  - destruct H1 as [n' [Hnm Hev]]. injection Hnm as Heq. rewrite Heq. apply Hev.\nQed.\n\nTheorem evSS_ev': forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. inversion E as [|n' E' Heq]. apply E'.\nQed.\n\nTheorem one_not_even: ~ ev 1.\nProof.\n  intros H. apply ev_inversion in H. destruct H as [|[m [Hm _]]].\n  - discriminate H.\n  - discriminate Hm.\nQed.\n\nTheorem one_not_even': ~ ev 1.\nProof.\n  intros H. inversion H.\nQed.\n\nTheorem SSSSev__even:forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros. inversion H. inversion H1. apply H3.\nQed.\n\nTheorem ev5_nonsense:\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros. inversion H. inversion H1. inversion H3.\nQed.\n\nTheorem inversion_ex1:forall n m o:nat,\n  [n; m] = [o; o] -> [n] = [m].\nProof.\n  intros n m o H. 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\nLemma ev_Even:forall n,\n  ev n -> Even n.\nProof.\n  intros n E.\n  induction E as [|n' E' IH].\n  - unfold Even. exists 0. reflexivity.\n  - unfold Even in IH.\n    destruct IH as [k Hk].\n    rewrite Hk.\n    unfold Even. exists (S k). reflexivity.\nQed.\n\nTheorem ev_Even_iff: forall n,\n  ev n <-> Even n.\nProof.\n  intros n. split.\n  - apply ev_Even.\n  - unfold Even. intros [k Hk]. rewrite Hk. apply ev_double.\nQed.\n\nTheorem ev_sum: forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  intros n m Hn Hm. induction Hn.\n  - apply Hm.\n  - replace (S (S n) + m) with (S (S (n + m))).\n    + apply ev_SS. apply IHHn.\n    + reflexivity.\nQed.\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\nTheorem ev'_ev:forall n, ev' n <-> ev n.\nProof.\n  induction n. split. intros. apply ev_0. intros. apply ev'_0. split.\n  - intros. induction H. apply ev_0. apply (ev_SS 0 ev_0).\n    apply (ev_sum n0 m IHev'1 IHev'2).\n  - intros. induction H. apply ev'_0. apply (ev'_sum 2 n0 ev'_2 IHev).\nQed.\n\nTheorem ev_ev__ev:forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m Hnm Hn. induction Hn. apply Hnm.\n  inversion Hnm. apply (IHHn H0).\nQed.\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 Hnm Hnp.\n  assert (ev ((n+m)+(n+p))). apply (ev_sum (n+m) (n+p) Hnm Hnp).\n  replace (n+m+(n+p)) with (n+n+(m+p)) in H.\n  assert (ev (n+n)). { rewrite <- (double_plus n). apply ev_double. }\n  apply (ev_ev__ev (n+n) (m+p) H H0).\n  rewrite add_assoc. rewrite add_assoc. replace (n+n+m) with (n+m+n).\n  reflexivity. rewrite add_comm. rewrite add_assoc. reflexivity.\nQed.\n\n(* Inductive Relations *)\n\nModule Playground.\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).\nNotation \"n <= m\" := (le n m).\n\nTheorem test_le1: 3<=3. Proof. apply le_n. Qed.\nTheorem test_le2: 3<=6. Proof. apply le_S. apply le_S. apply le_S. apply le_n.\nQed.\nTheorem test_le3:(2<=1)->2+2=5. Proof. intros H. inversion H. inversion H2. Qed.\n\nDefinition lt (n m:nat) := le (S n) m.\nNotation \"m < n\" := (lt m n).\nEnd Playground.\n\nInductive total_relation:nat->nat->Prop:=\n  total_r n m: total_relation n m.\n\nTheorem total_relation_is_total:forall n m, total_relation n m.\nProof. intros. apply (total_r n m). Qed.\n\nInductive empty_relation:nat->nat->Prop:=.\nTheorem empty_relation_is_empty: forall n m, ~ empty_relation n m.\nProof. intros n m H. inversion H. Qed.\n\nLemma le_trans: forall m n o, m<=n -> n <= o -> m <= o.\nProof.\n  intros m n o Hmn Hno. induction Hno. apply Hmn. apply (le_S m m0 IHHno).\nQed.\n\nTheorem O_le_n:forall n, 0 <= n.\nProof.\n    induction n. apply le_n. apply le_S. apply IHn.\nQed.\n\nTheorem n_le_m__Sn_le_Sm:forall n m, n <= m -> S n <= S m.\nProof.\n  intros n m H. induction H. apply le_n. apply le_S. apply IHle.\nQed.\n\nTheorem Sn_le_Sm__n_le_m:forall n m, S n <= S m -> n <= m.\nProof.\n  intros n m H. inversion H. apply le_n. assert (n <= S n).\n  - apply le_S. apply le_n.\n  - apply (le_trans _ _ _ H2 H1).\nQed.\n\nTheorem lt_ge_cases: forall n m, n<m \\/ n>=m.\nProof.\n  unfold lt. unfold ge.\n  induction n. induction m. right. apply le_n. left. apply n_le_m__Sn_le_Sm.\n  apply O_le_n.\n  induction m. right. apply O_le_n. destruct (IHn m).\n  - left. apply (n_le_m__Sn_le_Sm _ _ H).\n  - right. apply (n_le_m__Sn_le_Sm _ _ H).\nQed.\n\nTheorem le_plus_l: forall a b, a <= a + b.\nProof.\n  induction a. intros. apply O_le_n.\n  intros b. apply (n_le_m__Sn_le_Sm _ _ (IHa b)).\nQed.\n\nTheorem plus_le: forall n1 n2 m,\n  n1 + n2 <= m -> n1 <= m /\\ n2 <= m.\nProof.\n  induction n1. intros. split. apply O_le_n. apply H.\n  induction n2. intros. split. rewrite add_comm in H. apply H. apply O_le_n.\n  intros. inversion H. split. apply le_plus_l. rewrite add_comm. apply\n  le_plus_l.\n  split. apply n_le_m__Sn_le_Sm. assert (n1 <= S n1 + S n2). replace (S n1) with\n  (n1 + 1). rewrite <- add_assoc. apply le_plus_l. apply add_comm.\n  apply (le_trans _ _ _ H2 H0).\n  assert (n2 <= S n1 + S n2). replace (S n2) with (n2 + 1). rewrite add_assoc.\n  replace (S n1 + n2) with (n2 + S n1). rewrite <- add_assoc. apply le_plus_l.\n  apply add_comm. apply add_comm.\n  apply n_le_m__Sn_le_Sm. apply (le_trans _ _ _ H2 H0).\nQed.\n\nTheorem add_le_cases: forall n m p q,\n  n + m <= p + q -> n <= p \\/ m <= q.\nProof.\n  induction n. intros. left. apply O_le_n.\n  intros. destruct p.\n  - rewrite add_comm in H. simpl in H. assert (m <= m + S n). { apply le_plus_l.\n  } right. apply (le_trans _ _ _ H0 H).\n  - rewrite plus_Sn_m in H. rewrite plus_Sn_m in H. apply Sn_le_Sm__n_le_m in H.\n  apply IHn in H. destruct H. left. apply n_le_m__Sn_le_Sm. apply H.\n  right. apply H.\nQed.\n\nTheorem plus_le_compat_l: forall n m p,\n  n <= m -> p + n <= p + m.\nProof.\n  induction p.\n  - intros. apply H.\n  - intros. rewrite plus_Sn_m. rewrite plus_Sn_m. apply n_le_m__Sn_le_Sm. apply\n  (IHp H).\nQed.\n\nTheorem plus_le_compat_r: forall n m p,\n  n <= m -> n + p <= m + p.\nProof.\n  intros. rewrite add_comm. replace (m + p) with (p + m). apply\n  plus_le_compat_l. apply H. apply add_comm.\nQed.\n\nTheorem le_plus_trans: forall n m p,\n  n <= m -> n <= m + p.\nProof.\n  intros. assert (m <= m + p). replace m with (m + 0). rewrite <- add_assoc.\n  apply plus_le_compat_l. simpl. apply O_le_n. apply add_comm. apply (le_trans _\n_  _ H H0).\nQed.\n\nTheorem n_lt_m__n_le_m: forall n m,\n  n < m -> n <= m.\nProof.\n  unfold lt. intros. assert (n <= S n). apply le_S. apply le_n. apply (le_trans\n  _ _ _ H0 H).\nQed.\n\nTheorem plus_lt: forall n1 n2 m,\n  n1 + n2 < m -> n1 < m /\\ n2 < m.\nProof.\n  unfold lt. intros. destruct m. inversion H. apply Sn_le_Sm__n_le_m in H.\n  apply plus_le in H. destruct H. split. apply n_le_m__Sn_le_Sm. apply H. apply\n  n_le_m__Sn_le_Sm. apply H0.\nQed.\n\nTheorem leb_complete: forall n m,\n  n <=? m = true -> n <= m.\nProof.\n  induction n. intros. apply O_le_n. intros. destruct m. discriminate H. simpl\n  in H. apply n_le_m__Sn_le_Sm. apply IHn, H.\nQed.\n\nTheorem leb_correct: forall n m,\n  n <= m -> n <=? m = true.\nProof.\n  induction n.\n  - intros. simpl. reflexivity.\n  - induction m. intros. inversion H. intros. apply Sn_le_Sm__n_le_m in H. apply\n  IHn in H. simpl. apply H.\nQed.\n\nTheorem leb_iff: forall n m,\n  n <=? m = true <-> n <= m.\nProof.\n  split. apply leb_complete. apply leb_correct.\nQed.\n\nTheorem leb_true_trans: forall n m o,\n  n <=? m = true -> m <=? o = true -> n <=? o = true.\nProof.\n  intros. rewrite leb_iff in H. rewrite leb_iff in H0. rewrite leb_iff. apply\n  (le_trans _ _ _ H H0).\nQed.\n\nModule R.\n  Inductive 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  Definition fR (n:nat) (m:nat): nat := n + m.\n  Theorem R_equiv_fR: forall n m o, R m n o <-> fR m n = o.\n  Proof.\n    unfold fR.\n    split.\n    - intros H. induction H.\n      + reflexivity.\n      + rewrite plus_Sn_m. rewrite IHR. reflexivity.\n      + rewrite <- plus_n_Sm. rewrite IHR. reflexivity.\n      + rewrite plus_Sn_m in IHR. injection IHR as IHR. rewrite <- plus_n_Sm in\n    IHR. injection IHR as IHR. apply IHR.\n      + rewrite add_comm. apply IHR.\n    - generalize dependent m. generalize dependent n. induction o. intros. assert (m+n <= 0). replace (m+n) with 0. apply le_n.\n    apply plus_le in H0. destruct H0. inversion H0. inversion H1. apply c1.\n      + intros. destruct m. simpl in H. rewrite H. apply c3. apply IHo.\n      reflexivity.\n        apply c2. apply IHo. rewrite plus_Sn_m in H. injection H as H. apply H.\n  Qed.\nEnd R.\n\nInductive subseq : list nat -> list nat -> Prop :=\n  | subseq0: subseq [] []\n  | subseq1 (x: nat) (l1 l2: list nat) (H: subseq l1 l2): subseq l1 (x::l2)\n  | subseq2 (x: nat) (l1 l2: list nat) (H: subseq l1 l2): subseq (x::l1) (x::l2)\n.\n\nTheorem subseq_refl: forall (l : list nat), subseq l l.\nProof.\n  induction l.\n  - apply subseq0.\n  - apply (subseq2 x l l IHl).\nQed.\n\nLemma subseq_nil: forall l: list nat,\n  subseq [] l.\nProof.\n  induction l. apply subseq0. apply (subseq1 _ _ _ IHl).\nQed.\n\nTheorem subseq_app: forall l1 l2 l3: list nat,\n  subseq l1 l2 -> subseq l1 (l2 ++ l3).\nProof.\n  induction l1.\n  - intros. apply subseq_nil.\n  - intros. induction H. apply subseq_nil. simpl. apply subseq1. apply IHsubseq.\n    simpl. apply subseq2. apply IHsubseq.\nQed.\n\nTheorem subseq_trans: forall (l1 l2 l3: list nat),\n  subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros. generalize dependent l1. induction H0. intros. apply H.\n  - intros. apply IHsubseq in H. apply (subseq1 _ _ _ H).\n  - intros. inversion H. apply subseq1. apply IHsubseq. apply H3.\n    apply subseq2. apply IHsubseq. apply H3.\nQed.\n\n(* A Digression on Notation *)\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).\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\n  where \"s =~ re\" := (exp_match s re).\n\nExample reg_exp_ex1: [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2: [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1]). apply MChar. 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.\nExample reg_exp_ex4 : [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].\nProof.\n  simpl. apply (MApp [1]). apply MChar. apply (MApp [2]). apply MChar.\n  apply (MApp [3]). apply MChar. apply MEmpty.\nQed.\n\nLemma MStar1: forall T s (re:reg_exp T),\n  s =~ re -> s =~ Star re.\nProof.\n  intros. rewrite <- (app_nil_r _ s). apply MStarApp. apply H. apply MStar0.\nQed.\n\nLemma empty_is_empty: forall T (s: list T),\n  ~ (s =~ EmptySet).\nProof.\n  intros T s H. 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 T s re1 re2 H. destruct H.\n  - apply MUnionL. apply H.\n  - apply MUnionR. apply H.\nQed.\n\nLemma MStar': forall T (ss: list (list T)) (re: reg_exp T),\n  (forall s, In s ss -> s =~ re) -> fold app ss [] =~ Star re.\nProof.\n  intros T. induction ss.\n  - intros. simpl. apply MStar0.\n  - intros. simpl. apply (MStarApp x).\n    + apply H. left. reflexivity.\n    + apply IHss. intros. apply H. right. apply H0.\nQed.\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  (* WORKED IN CLASS *)\n  - (* MEmpty *)\n    simpl in Hin. destruct Hin.\n  - (* MChar *)\n    simpl. simpl in Hin.\n    apply Hin.\n  - (* MApp *)\n    simpl. rewrite In_app_iff. rewrite In_app_iff in Hin.\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. 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\nFixpoint re_not_empty {T: Type} (re: reg_exp T): bool :=\n  match re with\n  | EmptySet => false\n  | EmptyStr => true\n  | Char x => true\n  | App re1 re2 => (re_not_empty re1) && (re_not_empty re2)\n  | Union re1 re2 => re_not_empty re1 || re_not_empty re2\n  | Star re => 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. split; induction re; intros.\n  - inversion H. inversion H0.\n  - inversion H. simpl. reflexivity.\n  - inversion H. simpl. reflexivity.\n  - inversion H. simpl. inversion H0. rewrite andb_true_iff. split.\n    + apply IHre1. exists s1. apply H4.\n    + apply IHre2. exists s2. apply H5.\n  - inversion H. simpl. rewrite orb_true_iff. inversion H0.\n    + left. apply IHre1. exists x. apply H3.\n    + right. apply IHre2. exists x. apply H3.\n  - simpl. reflexivity.\n  - inversion H.\n  - exists []. apply MEmpty.\n  - exists [t]. apply MChar.\n  - simpl in H. apply andb_true_iff in H. destruct H. apply IHre1 in H. apply\n  IHre2 in H0. inversion H. inversion H0. exists (x ++ x0). apply (MApp x).\n  apply H1. apply H2.\n  - simpl in H. apply orb_true_iff in H. destruct H.\n    + apply IHre1 in H. inversion H. exists x. apply MUnionL. apply H0.\n    + apply IHre2 in H. inversion H. exists x. apply MUnionR. apply H0.\n  - exists []. apply MStar0.\nQed.\n\nLemma star_app: 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  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - injection Heqre' as Heqre''. intros. apply H.\n  - injection Heqre' as Heqre''. intros. rewrite <- app_assoc.\n    apply MStarApp. apply H1_. apply IHexp_match2. rewrite Heqre''. reflexivity.\n    apply H.\nQed.\n\nLemma MStar'': forall T (s: list T) (re: reg_exp T),\n  s =~ Star re -> \n  exists ss: list (list T), s = fold app ss [] /\\ forall s', In s' ss -> s' =~ re.\nProof.\n  intros. remember (Star re) as re'. induction H.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - discriminate.\n  - exists []. split. reflexivity. intros. destruct H.\n  - apply IHexp_match2 in Heqre' as Heqre''. inversion Heqre''. exists (s1::x). split.\n  destruct H1. simpl. rewrite H1. reflexivity. intros. simpl in H2. injection\n  Heqre' as Heqre'. destruct H2. rewrite <- H2. rewrite <- Heqre'. apply H.\n  destruct H1. apply H3. apply H2.\nQed.\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 => pumping_constant re1 + pumping_constant re2\n  | Union re1 re2 => pumping_constant re1 + pumping_constant re2\n  | Star r => pumping_constant r\n  end.\n\nLemma pumping_constant_ge_1: forall T (re: reg_exp T), pumping_constant re >= 1.\nProof.\n  intros. induction re.\n  - apply le_n.\n  - apply le_n.\n  - apply le_S. apply le_n.\n  - simpl. apply le_trans with (n := pumping_constant re1). apply IHre1. apply le_plus_l.\n  - simpl. apply le_trans with (n := pumping_constant re1). apply IHre1. apply\n  le_plus_l.\n  - simpl. apply IHre.\nQed.\n\nLemma pumping_consant_0_false: forall T (re: reg_exp T), pumping_constant re = 0\n-> False.\nProof.\n  intros. assert (pumping_constant re >= 1). apply pumping_constant_ge_1.\n  inversion H0. rewrite <- H2 in H. discriminate H. rewrite <- H1 in H.\n  discriminate H.\nQed.\n\nFixpoint napp {T} (n: nat) (l: list T): list T :=\n  match n with\n  | 0 => []\n  | S n' => l ++ napp n' l\nend.\n\nLemma napp_star:\n  forall T m s1 s2 (re: reg_exp T), s1 =~ re -> s2 =~ Star re -> napp m s1 ++ s2\n  =~ Star re.\nProof.\n  intros T. induction m. intros.\n  - simpl. apply H0.\n  - intros. simpl. rewrite <- app_assoc. apply MStarApp. apply H. apply IHm.\n  apply H. apply H0.\nQed.\n\nLemma weak_pumping: forall T (re: reg_exp T) s,\n  s =~ re -> pumping_constant re <= length s -> exists s1 s2 s3,\n    s = s1 ++ s2 ++ s3 /\\ s2 <> [] /\\ forall m, s1 ++ napp m s2 ++ s3 =~ re.\nProof.\n  intros T re s Hmatch.\n  induction Hmatch.\n  - simpl. intros contra. inversion contra.\n  - simpl. intros contra. inversion contra. inversion H0.\n  - simpl. intros. rewrite app_length in H. apply add_le_cases in H. destruct H.\n    + apply IHHmatch1 in H. destruct H. destruct H. destruct H. destruct H.\n    destruct H0. exists x. exists x0. exists (x1 ++ s2). split.\n      * rewrite H. rewrite <- app_assoc. rewrite <- app_assoc. reflexivity.\n      * split. apply H0. intros. rewrite app_assoc. rewrite app_assoc. apply\n      MApp. rewrite <- app_assoc. apply H1. apply Hmatch2.\n    + apply IHHmatch2 in H. destruct H. destruct H. destruct H. destruct H.\n    destruct H0. exists (s1++x). exists x0. exists x1. split.\n      * rewrite H. rewrite app_assoc. reflexivity.\n      * split. apply H0. intros. assert (s1 ++ (x ++ napp m x0 ++ x1) = (s1 ++ x)\n      ++ napp m x0 ++ x1). rewrite app_assoc. reflexivity. rewrite <- H2. apply\n      MApp. apply Hmatch1. apply H1.\n  - simpl. intros. apply plus_le in H. destruct H. apply IHHmatch in H. destruct\n  H. destruct H. destruct H. destruct H. destruct H1. exists x. exists x0.\n  exists x1. split. apply H. split. apply H1. intros. apply MUnionL. apply H2.\n  - simpl. intros. apply plus_le in H. destruct H. apply IHHmatch in H0. destruct\n  H0. destruct H0. destruct H0. destruct H0. destruct H1. exists x. exists x0.\n  exists x1. split. apply H0. split. apply H1. intros. apply MUnionR. apply H2.\n  - simpl. intros contra. inversion contra. apply pumping_consant_0_false in H0.\n  destruct H0.\n  - simpl. intros. rewrite app_length in H. simpl in IHHmatch2. destruct s1.\n    + simpl. simpl in H. apply IHHmatch2 in H. destruct H. destruct H. destruct\n    H. exists x. exists x0. exists x1. apply H.\n    + simpl. exists []. exists (x :: s1). exists s2. split. reflexivity. split.\n    intros contra. discriminate. intros. simpl. apply napp_star. apply Hmatch1.\n    apply Hmatch2.\nQed.\n\nLemma pumping: forall T (re: reg_exp T) s,\n  s =~ re -> pumping_constant re <= length s -> 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.\nProof.\n  intros T re s Hmatch.\n  induction Hmatch.\n  - simpl. intros contra. inversion contra.\n  - simpl. intros contra. inversion contra. inversion H0.\n  - simpl. intros. rewrite app_length in H. apply add_le_cases in H. destruct H.\n    + apply IHHmatch1 in H. destruct H as [s3[s4[s5[H[H0[]]]]]].\n    exists s3, s4, (s5 ++ s2). split. rewrite H. rewrite <- app_assoc. rewrite\n    <- app_assoc. reflexivity. split. apply H0. split. apply le_plus_trans.\n    apply H1. intros. rewrite app_assoc. rewrite app_assoc. apply MApp. rewrite\n    <- app_assoc. apply H2. apply Hmatch2.\n    + apply IHHmatch2 in H. destruct H as [s3[s4[s5[H[H0[]]]]]]. destruct\n    (lt_ge_cases (pumping_constant re1) (length s1)).\n      * apply n_lt_m__n_le_m in H3. apply IHHmatch1 in H3. destruct H3 as [s6[s7[s8[H4[H5[]]]]]].\n    exists s6, s7, (s8 ++ s2). split. rewrite H4. rewrite <- app_assoc. rewrite\n    <- app_assoc. reflexivity. split. apply H5. split. apply le_plus_trans.\n    apply H3. intros. rewrite app_assoc. rewrite app_assoc. apply MApp. rewrite\n    <- app_assoc. apply H6. apply Hmatch2.\n      * exists (s1 ++ s3), s4, s5. split. rewrite H. rewrite app_assoc.\n      reflexivity. split. apply H0. rewrite app_length. split. apply le_trans\n      with (n := (pumping_constant re1) + (length s3 + length s4)). rewrite <-\n      add_assoc. apply plus_le_compat_r. apply H3. apply plus_le_compat_l. apply\n      H1. intros. replace ((s1 ++ s3) ++ napp m s4 ++ s5) with (s1 ++ (s3 ++\n      napp m s4 ++ s5)). apply MApp. apply Hmatch1. apply H2. apply app_assoc.\n  - simpl. intros. apply plus_le in H. destruct H. apply IHHmatch in H. destruct\n  H as [s2[s3[s4[H[H1[]]]]]]. exists s2, s3, s4. split. apply H. split. apply\n  H1. split. apply le_plus_trans. apply H2. intros. apply MUnionL. apply H3.\n  - simpl. intros. apply plus_le in H. destruct H. apply IHHmatch in H0. destruct\n  H0 as [s3[s4[s5[H0[H1[]]]]]]. exists s3, s4, s5. split. apply H0. split. apply\n  H1. split. replace (pumping_constant re1 + pumping_constant re2) with\n  (pumping_constant re2 + pumping_constant re1). apply le_plus_trans. apply H2.\n  apply add_comm. intros. apply MUnionR. apply H3.\n  - intros. inversion H. apply pumping_consant_0_false in H1. inversion H1.\n  - simpl. intros. rewrite app_length in H. simpl in IHHmatch2. destruct\n  (lt_ge_cases (pumping_constant re) (length s1)).\n    + apply n_lt_m__n_le_m in H0. apply IHHmatch1 in H0. destruct H0 as\n    [s3[s4[s5[H0[H1[]]]]]]. exists s3, s4, (s5 ++ s2). split. rewrite H0.\n    rewrite <- app_assoc. rewrite <- app_assoc. reflexivity. split. apply H1.\n    split. apply H2. intros. rewrite app_assoc. rewrite app_assoc. apply\n    MStarApp. rewrite <- app_assoc. apply H3. apply Hmatch2.\n    + destruct s1. simpl in H. apply IHHmatch2 in H. destruct H as\n    [s3[s4[s5[H[H1[]]]]]]. exists s3, s4, s5. split. apply H. split. apply H1.\n    split. apply H2. apply H3.\n      exists [], (x :: s1), s2. split. reflexivity. split. intros contra.\n      inversion contra. split. apply H0. intros. apply napp_star. apply Hmatch1.\n      apply Hmatch2.\nQed.\n\nEnd Pumping.\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 eqn:Eb.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. intros H'. discriminate.\nQed.\n\nTheorem reflect_iff: forall P b, reflect P b -> (P <-> b = true).\nProof.\n  intros P b H. split. intros. destruct H. reflexivity. apply H in H0. inversion\n  H0. destruct H. intros. apply H. intros. discriminate.\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\nTheorem filter_not_empty_In: forall n l,\n  filter (fun x => n =? x) l <> [] -> In n l.\nProof.\n  intros n l. induction l as [|m l'].\n  - simpl. intros. apply H. reflexivity.\n  - simpl. destruct (eqbP n m).\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\nTheorem eqbP_practice: forall n l,\n  count n l = 0 -> ~(In n l).\nProof.\n  intros n l Hcount. induction l as [|m l' IHl'].\n  - intros H. simpl in H. apply H.\n  - intros H. simpl in Hcount, H. destruct (eqbP n m).\n    + discriminate.\n    + apply IHl' in Hcount. destruct H. symmetry in H. apply H0 in H. apply H.\n    apply Hcount in H. apply H.\nQed.\n\nInductive nostutter {X:Type}: list X -> Prop :=\n  | nostutter_nil: nostutter []\n  | nostutter_one (x: X): nostutter [x]\n  | nostutter_cons (x: X) (y: X) (l: list X) (H: nostutter (y::l)) (H2: x <> y):\n  nostutter (x::(y::l))\n.\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].\n  Proof. repeat constructor; auto. Qed.\n\nExample test_nostutter_4: not (nostutter [3;1;1;4]).\nProof. intro.\n  repeat match goal with\n    h: nostutter _ |- _ => inversion h; clear h; subst\n  end.\n  contradiction; auto.\nQed.\n\nInductive merge {X: Type}: list X -> list X -> list X -> Prop :=\n  | merge_nil: merge [] [] []\n  | merge_l (x: X) (a b c: list X) (H: merge a b c): merge (x::a) b (x::c)\n  | merge_r (x: X) (a b c: list X) (H: merge a b c): merge a (x::b) (x::c)\n.\n\nTheorem merge_filter: forall (X: Set) (test: X -> bool) (l l1 l2: list X),\n  merge l1 l2 l ->\n  All (fun n => test n = true) l1 ->\n  All (fun n => test n = false) l2 ->\n  filter test l = l1.\nProof.\n  intros. induction H.\n  - reflexivity.\n  - simpl in H0. destruct H0. simpl. rewrite H0. replace (filter test c) with a.\n  reflexivity. symmetry. apply IHmerge. apply H2. apply H1.\n  - simpl in H1. destruct H1. simpl. rewrite H1. apply IHmerge. apply H0. apply\n  H2.\nQed.\n\nTheorem filter_challenge_2: forall (test: nat -> bool) (sub l: list nat),\n  (subseq sub l) -> All (fun n => test n = true) sub -> length sub <= length\n  (filter test l).\nProof.\n  intros. induction H.\n  - simpl. apply le_n.\n  - simpl. apply IHsubseq in H0. apply le_trans with (n := length (filter test\n  l2)). apply H0. destruct (test x). simpl. apply le_S. apply le_n. apply le_n.\n  - simpl. simpl in H0. destruct H0. apply IHsubseq in H1. rewrite H0. simpl.\n  apply n_le_m__Sn_le_Sm. apply H1.\nQed.\n\nInductive pal {X:Type}: list X -> Prop :=\n  | pal_nil: pal []\n  | pal_one (x:X): pal [x]\n  | pal_add (x:X) (l: list X) (H: pal l): pal (x :: l ++ [x])\n.\n\nTheorem pal_app_rev: forall {X:Type} (l: list X),\n  pal (l ++ (rev l)).\nProof.\n  intros. induction l.\n  - simpl. apply pal_nil.\n  - simpl. rewrite app_assoc. apply pal_add. apply IHl.\nQed.\n\nTheorem rev_involutive: forall (X:Type) (l: list X),\n  rev (rev l) = l.\nProof.\n  induction l as [| n l IHl].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr. rewrite -> IHl. reflexivity.\nQed.\n\nTheorem pal_rev: forall (X:Type) (l: list X), pal l -> l = rev l.\nProof.\n  intros. induction H.\n  - reflexivity.\n  - reflexivity.\n  - assert ([x] ++ l ++ [x] = ([x] ++ l) ++ [x]). apply app_assoc.\n    rewrite <- (rev_involutive _ ([x] ++ l)) in H0. simpl in H0. simpl. rewrite\n    H0. simpl. rewrite <- IHpal. reflexivity.\nQed.\n\nLemma rev_app_distr : forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\nintros X l1 l2. induction l1 as [| n l1' IHl1'].\n- simpl. rewrite -> app_nil_r. reflexivity.\n- simpl. rewrite -> IHl1'. rewrite -> app_assoc. reflexivity.\nQed.\n\nLemma palindrome_converse': forall X (n: nat) (l:list X),\n  length l <= n -> l = rev l -> pal l.\nProof.\n  intros X. induction n.\n  - intros. inversion H. destruct l. apply pal_nil. discriminate.\n  - intros. destruct l. apply pal_nil. simpl in *. destruct (rev l) as [] eqn:E.\n    + rewrite H0. apply pal_one.\n    + injection H0 as H0. rewrite H1. apply pal_add. apply IHn. apply leb_iff in\n    H. simpl in H. apply leb_iff in H. rewrite H1 in H. rewrite app_length in H.\n    apply le_trans with (n := length l0 + length [x]). apply le_plus_l. apply H.\n    rewrite H1 in E. rewrite rev_app_distr in E. rewrite H0 in E. simpl in E.\n    injection E as E. rewrite E. reflexivity.\nQed.\n\nTheorem palindrome_converse: forall {X: Type} (l: list X),\n  l = rev l -> pal l.\nProof.\n  intros X l H. apply palindrome_converse' with (n := length l). apply le_n.\n  apply H.\nQed.\n\nInductive disjoint {X}: (list X) -> (list X) -> Prop :=\n  | disjoint_nil: disjoint [] []\n  | disjoint_l (x:X) (l1 l2:list X) (H: disjoint l1 l2) (HI: ~(In x l2)) : disjoint (x::l1) l2\n  | disjoint_r (x:X) (l1 l2:list X) (H: disjoint l1 l2) (HI: ~(In x l1)) : disjoint l1 (x::l2)\n.\n\nInductive NoDup {X}: list X -> Prop :=\n  | NoDup_nil: NoDup []\n  | NoDup_add (x:X) (l:list X) (H:NoDup l) (HI: ~(In x l)) : NoDup (x::l)\n.\n\nTheorem app_no_dup_disjoint: forall X (l1 l2: list X),\n  NoDup (l1 ++ l2) -> disjoint l1 l2.\nProof.\n  intros X. induction l1 as [|x' l1].\n  - intros l2 H. induction l2. apply disjoint_nil. apply disjoint_r. apply IHl2.\n  inversion H. apply H1. intros contra. simpl in contra. apply contra.\n  - intros l2 H. simpl in *. inversion H. apply IHl1 in H1. apply disjoint_l.\n  apply H1. unfold not in *. intros. apply HI. apply In_app_iff. right. apply H3.\nQed.\n\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. induction l.\n  - intros. destruct H.\n  - intros. destruct H.\n    + exists nil, l. rewrite H. reflexivity.\n    + apply IHl in H. destruct H as [l1[l2]]. exists (x0::l1), l2. rewrite H. reflexivity.\nQed.\n\nInductive repeats {X:Type}: list X -> Prop :=\n  | repeats_rep (x:X) (xs: list X) (H: In x xs): repeats (x::xs)\n  | repeats_add (x:X) (xs: list X) (H: repeats xs): repeats (x::xs)\n.\n\nLemma remove {X:Type}: forall (x:X) (xs:list X),\n  In x xs -> exists xs', (forall x', x<>x' -> In x' xs -> In x' xs') /\\ (length\n  xs = S(length xs')).\nProof.\n  intros. apply in_split in H. destruct H as [l1[l2]]. exists (l1 ++ l2).\n  rewrite H. intros. clear H. split.\n  - intros. apply In_app_iff in H0. apply In_app_iff. destruct H0. left. apply\n  H0. simpl in H0. destruct H0. apply H in H0. destruct H0. right. apply H0.\n  - rewrite app_length. simpl. rewrite app_length. replace (S (length l2)) with\n  (1 + length l2). replace (S (length l1 + length l2)) with (1 + length l1 +\n  length l2).\n  rewrite add_assoc. rewrite (add_comm (length l1) 1). reflexivity. reflexivity. reflexivity.\nQed.\n\nTheorem pigeonhole_principle: excluded_middle -> forall (X:Type) (l1 l2: list X),\n  (forall x, In x l1 -> In x l2) -> length l2 < length l1 -> repeats l1.\nProof.\n  intros ex. induction l1.\n  - intros. inversion H0.\n  - intros. destruct (ex (In x l1)).\n    + apply repeats_rep. apply H1.\n    + apply repeats_add. assert (In x l2). { apply H. simpl. left. reflexivity. }\n      apply (remove x l2) in H2. destruct H2 as [l2'[]]. apply (IHl1 l2').\n      * intros. apply H2. intros contra. rewrite <- contra in H4. apply H1 in\n      H4. apply H4. apply H. simpl. right. apply H4.\n      * rewrite H3 in H0. simpl in H0. apply Sn_le_Sm__n_le_m in H0. apply H0.\nQed.\n\n(* TODO: Extended Exercise: A Verified Regular-Expression Matcher *)\n", "meta": {"author": "ogiekako", "repo": "software_foundations", "sha": "95d160edc04f12e8c85cee86a63fd791df21da1e", "save_path": "github-repos/coq/ogiekako-software_foundations", "path": "github-repos/coq/ogiekako-software_foundations/software_foundations-95d160edc04f12e8c85cee86a63fd791df21da1e/v1/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7288567279961561}}
{"text": "Require Import QArith Quote List.\nRequire Import CpdtTactics.\n\nLocal Open Scope Q_scope.\n\nInductive Exp : Set :=\n| Const : Q -> Exp\n| Plus : Exp -> Exp -> Exp\n| Minus : Exp -> Exp -> Exp\n| Mult : Exp -> Exp -> Exp\n| Var : index -> Exp.\n\nDefinition bindings := varmap Q.\n\nFixpoint denote (G : bindings) (e : Exp) : Q :=\n  match e with\n  | Const x => x\n  | Plus x y => denote G x + denote G y\n  | Minus x y => denote G x - denote G y\n  | Mult x y => denote G x * denote G y\n  | Var idx => varmap_find 0 idx G\n  end.\n\nDefinition Coefficients := list (index * Q).\n\nFixpoint denoteCo (G : bindings) (ks : Coefficients) : Q :=\n  match ks with\n  | nil => 0\n  | (var, k) :: ks' => varmap_find 0 var G * k + denoteCo G ks'\n  end.\n\nFixpoint addCo (ks : Coefficients) var k : Coefficients :=\n  match ks with\n  | nil => (var, k) :: nil\n  | (var', k') :: ks' => if index_eq var var' then\n                           (var, k + k') :: ks'\n                         else\n                           (var', k') :: addCo ks' var k\n  end.\n\nDefinition Equation := prod Coefficients Q.\n\nNotation \"x <- e1 ; e2\" :=\n  match e1 with\n  | Some x => e2\n  | None => None\n  end\n    (right associativity, at level 60).\n\nFixpoint toQ (e : Exp) : option Q :=\n  match e with\n  | Const x => Some x\n  | Plus x y => x' <- toQ x ; y' <- toQ y ; Some (x' + y')\n  | Minus x y => x' <- toQ x ; y' <- toQ y ; Some (x' - y')\n  | Mult x y => x' <- toQ x ; y' <- toQ y ; Some (x' * y')\n  | _ => None\n  end.\n\nFixpoint add (eq : Equation) (e : Exp) (sign : Q) : option Equation :=\n  match eq with\n  | (l, r) =>  match e with\n               | Const x => Some (l, r + sign * x)\n               | Var idx => Some (addCo l idx sign, r)\n               | Plus x y => eq' <- add eq x sign ; add eq' y sign\n               | Minus x y => eq' <- add eq x sign; add eq' y (- sign)\n               | Mult x y => let eq1 := x' <- toQ x ; add eq y (x' * sign) in\n                             let eq2 := y' <- toQ y ; add eq x (y' * sign)\n                             in\n                             if eq1 then eq1 else eq2\n               end\n  end.\n\nDefinition denoteEquation (G : bindings) (eq : Equation) :=\n  match eq with\n  | (l, r) => denoteCo G l + r\n  end.\n\nDefinition normalize (e : Exp) : option Equation :=\n  add (nil, 0) e 1.\n\nLtac letpairs :=\n  repeat\n    match goal with\n    | [|- context[let (_, _) := ?p in _]] => rewrite (surjective_pairing p); simpl;\n                                             try rewrite <- (surjective_pairing p)\n    end;\n  repeat\n    match goal with\n    | [H : context[let (_, _) := ?p in _] |- _] => rewrite (surjective_pairing p) in H; simpl in H;\n                                                   try rewrite <- (surjective_pairing p) in H\n    end.\n\nLtac do_notation_case :=\n  match goal with\n  | [H : context[_ <- ?x ; _] |- _] => let Heq := fresh in\n                                       destruct x eqn:Heq; try solve [inversion H]\n  end.\n\nLtac if_case :=\n  match goal with\n  | [H : context[if ?x then _ else _] |- _] => let Heq := fresh in destruct x eqn:Heq\n  | [|- context[if ?x then _ else _]] => let Heq := fresh in destruct x eqn:Heq\n  end.\n     \nLtac newvar T k :=\n  let x := fresh in\n  evar (x : T); let y := eval unfold x in x\n                  in clear x; k y.\n\nLtac inst_hyp H :=\n  match type of H with\n  | forall (_ : _ = _), _ => match goal with\n                             | [x : _ = _ |- _] => specialize (H x)\n                             end || specialize (H (eq_refl _)) || fail 1\n  | forall (_ : ?T), _ => newvar T ltac:(fun x => specialize (H x)); inst_hyp H\n  | _ => fail\n  end.\n\nLtac inst_hyps :=\n  repeat match goal with\n         | [H : forall _, _ |- _] => inst_hyp H\n         end.\n\nLtac some_inversion :=\n  repeat match goal with\n         | [H : Some _ = Some _ |- _] => injection H; clear H; intro\n         end.\n\nLtac rewrite_with_hyps :=\n  repeat match goal with\n         | [ H : _ |- _ ] => rewrite H\n         end.\n\nLemma toQ_correct : forall e q G,\n    toQ e = Some q -> denote G e = q.\nProof.\n  induction e;\n  simpl;\n  intros;\n  repeat do_notation_case;\n  inversion H; \n  solve [reflexivity | inst_hyps; crush].\nQed.\n\nLemma add_correct : forall e eq eq' sign G,\n    add eq e sign = Some eq' ->\n    denoteEquation G eq' == denoteEquation G eq + sign * denote G e.\nProof.\n  unfold denoteEquation.\n  \n  induction e; simpl; intros; letpairs.\n\n  (* Const *)\n  inversion H; simpl; ring.\n\n  (* Plus *)\n  do_notation_case. inst_hyps. letpairs. rewrite_with_hyps. ring.\n\n  (* Minus *)\n  do_notation_case. inst_hyps. letpairs. rewrite_with_hyps. ring.\n  \n  (* Mult *)\n  do_notation_case;\n    try if_case;\n    try some_inversion;\n    try do_notation_case;\n    inst_hyps;\n    letpairs;\n    subst;\n    match goal with\n    | [H : toQ _ = Some _ |- _] =>  apply (toQ_correct _ _ G) in H\n    end;\n    rewrite_with_hyps;\n    ring.\n\n  (* Variable *)\n  some_inversion.\n  subst.\n  simpl.\n  induction (fst eq); simpl.\n  ring.\n  letpairs.\n  if_case; simpl.\n  apply index_eq_prop in H.\n  subst.\n  ring.\n  letpairs.\n  rewrite <- Qplus_assoc.\n  rewrite_with_hyps.\n  ring.\nQed.\n\nTheorem normalize_correct : forall e eq,\n    normalize e = Some eq -> forall G, denote G e == denoteEquation G eq.\nProof.\n  unfold normalize.\n  intros.\n  assert (L := add_correct e (nil, 0) eq 1 G H).\n  simpl in L.\n  ring_simplify in L.\n  symmetry.\n  assumption.\nQed.\n  \nLemma equation_addition : forall a b c d,\n    a == b -> c == d -> a + c == b + d.\nProof.\n  crush.\nQed.\n\nLemma left_constant : forall G ks q r,\n    denoteEquation G (ks, q) == r <-> denoteCo G ks == r - q.\nProof.\n  split; intros; unfold denoteEquation in *;\n  first [rewrite H | rewrite <- H];\n  ring.\nQed.\n\nLtac add_together :=\n  assert (H_sum : 0 == 0) by reflexivity;\n  repeat\n    match goal with\n    | [H_sum : _ |- _] => fail\n    | [H : ?l == ?r |- _] => match goal with\n                             | [_ : done H |- _] => fail 1\n                             | _ => assert (done H) by constructor;\n                                 apply (equation_addition l r _ _ H) in H_sum\n                             end\n    end;\n  un_done.\n\nLtac someOut e :=\n  match eval compute in e with\n  | Some ?x => x\n  end.\n\nLtac reify :=\n  add_together;\n  repeat match goal with\n         | [H : ?l == ?r |- _] =>\n           match l with\n           | denoteCo _ _ => fail 1\n           | _ => \n             quote denote [Qmake xI xO xH Z0 Zpos Zneg]\n               in l using (fun d =>\n                             match d with\n                             | denote _ ?e =>\n                               change (d == r) in H;\n                             let eq := (someOut (normalize e))\n                             in rewrite (normalize_correct e eq) in H;\n                             auto;\n                             rewrite left_constant in H\n                             end)\n           end\n         end;\n  repeat match goal with\n         | [H : denoteCo _ _ == _ |- _] => simpl in H; ring_simplify in H\n         end;\n  match goal with\n  | [|- ?l == ?r ] =>\n    quote denote [Qmake xI xO xH Z0 Zpos Zneg]\n      in l using (fun d =>\n                    match d with\n                    | denote _ ?e =>\n                      change (d == r);\n                    let eq := (someOut (normalize e))\n                    in rewrite (normalize_correct e eq);\n                    auto;\n                    rewrite left_constant;\n                    simpl;\n                    ring_simplify \n                    end)\n  end.\n\nLtac finish :=\n  match goal with\n  | [H : _ == ?r |- _ == ?r] => rewrite <- H; ring\n  end.\n\nTheorem test : forall x y z,\n    (2 # 1) * (x - (3 # 2) * y) == 15 # 1 ->\n    z + (8 # 1) * x == 20 # 1 ->\n    (-6 # 2) * y + (10 # 1) * x + z == 35 # 1.\nProof.\n  intros.\n  reify.\n  finish.\nQed.\n", "meta": {"author": "eldargab", "repo": "cpdt", "sha": "a7b41081e90e245014b4f4918c0a3837864bec56", "save_path": "github-repos/coq/eldargab-cpdt", "path": "github-repos/coq/eldargab-cpdt/cpdt-a7b41081e90e245014b4f4918c0a3837864bec56/Reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7288567260202915}}
{"text": "(*Ejericio 10 . formalizar y r\nsu validez;\n\n1. Si es falso que si un objeto flota en el agua es menos denso\n   que ésta, entonces se puede caminar sobre ella.\n\n2. Es claro que no se puede caminar sobre el agua.\n\n3. Si un objeto es menos denso que el agua entonces puede \n   desplazar una cantidad de agua igual a su propio peso.\n\n4. Un objeto puede desplazar una cantidad de agua igual a su \n   propio peso solo si flota en el agua.\n\nPor lo tanto, un objeto flota en el agua si y solo si \nes menos denso que ésta.*)\n\nAxiom classic : forall P:Prop, P \\/ ~ P.\n\nLemma NNPP : forall p:Prop, ~ ~ p -> p.\nProof.\nintros.\nelim (classic p).\nintro.\nassumption.\nintro.\nelim (H H0).\nQed.\n\nSection razonamiento.\nVariables p q r s t : Prop.\nHypothesis H0: p -> (q \\/ r).\nHypothesis H1: s -> ~q.\nHypothesis H2: t-> ~r.\nHypothesis H3: p /\\ t.\nLemma conclu :q.\nProof.\ndestruct H0.\ndestruct H3.\napply H.\napply H.\ndestruct H2.\napply H3.\napply H.\nQed.\nEnd razonamiento.\n\nSection razonamiento2.\n\nVariables p q r s : Prop.\n\nLemma neg_ant: (~(p -> q) -> r) -> (~r -> ~~(p -> q)).\nProof.\nintros.\nintro.\napply H0.\napply H.\nassumption.\nQed.\n\nHypothesis H0: ~(p -> q) -> r.\nHypothesis H1: ~r.\nHypothesis H2: q -> s.\nHypothesis H3: s -> p.\nLemma res: p <-> q.\nProof.\nsplit.\napply neg_ant in H0.\napply NNPP in H0.\nassumption.\nassumption.\nintro.\napply H2 in H.\napply H3 in H.\nassumption.\nQed.\n\nEnd razonamiento2.", "meta": {"author": "DavidContrerasFranco", "repo": "Logic-in-Computer-Science", "sha": "9aeaaa572834a87a921f321a92d1462034beece6", "save_path": "github-repos/coq/DavidContrerasFranco-Logic-in-Computer-Science", "path": "github-repos/coq/DavidContrerasFranco-Logic-in-Computer-Science/Logic-in-Computer-Science-9aeaaa572834a87a921f321a92d1462034beece6/Class Examples/Solucion_Ejercicio_Clase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7288567235014365}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                       *)\n(****************************************************************************)\n(*                 The Calculus of Inductive Constructions                  *)\n(*                                                                          *)\n(*                                Projet Coq                                *)\n(*                                                                          *)\n(*                     INRIA                        ENS-CNRS                *)\n(*              Rocquencourt                        Lyon                    *)\n(*                                                                          *)\n(*                                Coq V5.11                                 *)\n(*                              Feb 2nd 1996                                *)\n(*                                                                          *)\n(*                (notations and layout updated March 2009)                 *)\n(****************************************************************************)\n(*                               Schroeder.v                                *)\n(****************************************************************************)\n(* This file is distributed under the terms of the                          *) \n(* GNU Lesser General Public License Version 2.1                            *)\n(****************************************************************************)\n\n\n(**  If A is of cardinal less than B and conversely, then A and B           *)\n(**  are equipollent                                                        *)\n(**  In other words, if there is an injective map from A to B and           *)\n(**  an injective map from B to A then there exists a map from A onto B.    *)\n\n(**                  (based on a proof by Fraenkel)                         *)\n\nSet Nested Proofs Allowed.\nRequire Import Ensembles.      (* Ensemble, In, Included, Setminus *)\nRequire Import Relations_1.    (* Relation, Transitive *)\nRequire Import Powerset.       (* Inclusion_is_transitive *)\nRequire Import Classical_Prop. (* classic *)\n\nRequire Import Setminus_fact.\nRequire Import Sums.\nRequire Import Functions.\nRequire Import Equipollence.\n\nSection Schroeder_Bernstein.\n\n\n(****************************************************************************)\n(** We need the decidability of the belonging relation on sets              *)\n(** This is equivalent to classical logic                                   *)\n\nDefinition in_or_not_in (U : Type) (x : U) (A : Ensemble U) :=\n  classic (In U A x).\n\n\n(****************************************************************************)\n(**  A and B are sets of elements in the univers U                          *)\n\n\nVariable U : Type.\n\nLet SU := Ensemble U.\n\nVariable A B : SU.  (* A and B are sets of elements in the univers U *)\n\n\n  Section Bijection.\n\n  (**************************************************************************)\n  (** We now show that if f and g are injections resp from A to B and from  *)\n  (** B to A, then there is a subset J of A s.t. h, defined to be f on A    *)\n  (** and the converse of g on A\\J is a bijection from A to B               *)\n\n  Variable f g : Relation U.  (* f and g are relations *)\n\n  Hypothesis f_inj : injection U A B f. (* f and g are injections *)\n  Hypothesis g_inj : injection U B A g.\n\n  Let Imf : Ensemble U -> Ensemble U := Im U f.\n  Let Img : Ensemble U -> Ensemble U := Im U g.\n\n  (** Constructing J s.t. g(B\\f(J))=A\\J *)\n\n    (** (Setminus U A C) denotes the difference A\\C         *)\n    (** (Included U A C) means that A is included in C  *)\n\n    Let F (C : SU) := Setminus U A (Img (Setminus U B (Imf C))).\n\n    Let D (C : SU) := Included U C (F C).\n\n    Let J := Set_Sum U D.\n\n\n  (**  We show that so-built J is the subset we are looking for *)\n\n    (** J is Tarski's fix-point of F, a function which is growing *)\n    (** w.r.t. inclusion                                          *)\n\n    (** Lemma: F is growing *)\n\n      Lemma F_growing :\n       forall C C' : SU, Included U C C' -> Included U (F C) (F C').\n      Proof.\n        intros; unfold F in |- *.\n        apply Setminus_contravariant.\n        unfold Img in |- *.\n        apply Im_stable_par_incl.\n        apply Setminus_contravariant.\n        unfold Imf in |- *.\n        apply Im_stable_par_incl.\n        assumption.\n      Qed.\n\n    (** We show F(J)=A\\Img(B\\Imf(J))=J *)\n\n       (** First left-to-right inclusion *)\n\n         (** Lemma: J_is_in_FJ (Included U J (F J))  *)\n\n         Lemma J_is_in_FJ : Included U J (F J).\n         Proof.\n           unfold J in |- *.\n           apply Set_Sum_is_majoring.\n           intros C C_in_D.\n           cut (Transitive (Ensemble U) (Included U)).\n             2: apply Inclusion_is_transitive.\n           intro Incl_is_trans.\n           unfold Transitive in Incl_is_trans.\n           apply Incl_is_trans with (F C).\n           (* Show C subset of (F C) *)\n             assumption.\n           (* Show (F C) subset of (F (Set_Sum U D)) *)\n             apply F_growing.\n             apply Set_Sum_is_minoring.\n             assumption.\n         Qed.\n\n       (** Then right-to-left inclusion *)\n\n         (** Lemma: FJ_is_in_J (Included U (F J) J)  *)\n\n         Lemma FJ_is_in_J : Included U (F J) J.\n         Proof.\n           unfold J in |- *.\n           apply Set_Sum_is_minoring.\n           red in |- *.\n           red in |- *.\n           apply F_growing.\n           exact J_is_in_FJ.\n         Qed.\n\n\n  (** We show that h, which is f on J and g elsewhere, is a bijection *)\n\n    Inductive h (x y : U) : Prop :=\n      | hl_intro : In U J x -> f x y -> h x y\n      | hr_intro : Setminus U B (Imf J) y -> g y x -> h x y.\n\n\n  (** Theorem: h_bij (bijection U A B h) *)\n\n  Theorem h_bij : bijection U A B h.\n\n\n    (** h is from A to B *)\n    Lemma h1 : Rel U A B h.\n    Proof.\n        apply Rel_intro; do 2 intro; intro h_x_y.\n        (* h is on A *) \n          elim h_x_y.\n          (* on J : f is from A to B *)\n            elim f_inj.\n            intro f_Rel; intros.\n            elim f_Rel.\n            intros f_sur_A f_sur_B.\n            apply f_sur_A with y; assumption.\n\n        (* on A\\J: g is from B to A *)\n          elim g_inj.\n          intro g_Rel; intros.\n          elim g_Rel.\n          intros g_sur_B g_sur_A.\n          apply g_sur_A with y; assumption.\n\n      (* h is on B *) \n        elim h_x_y.\n        (* On J : f is from A to B *)\n          elim f_inj.\n          intro f_Rel; intros.\n          elim f_Rel.\n          intros f_sur_A f_sur_B.\n          apply f_sur_B with x; assumption.\n\n        (* On A\\J: g is from B to A *)\n        elim g_inj.\n        intro g_Rel; intros.\n        elim g_Rel.\n        intros g_sur_B g_sur_A.\n        apply g_sur_B with x; assumption.\n\n    Qed.\n\n\n    (** h satisfies to_at_most_one_output *)\n    Lemma h2 : to_at_most_one_output U h.\n    Proof.\n      red in |- *; intros x y z h_x_y h_x_z.\n      elim h_x_y.\n\n      (* on J *)\n        elim h_x_z.\n        (* case when (h x y) or (h x z) behaves as f: ok *)\n          elim f_inj.\n          unfold to_at_most_one_output in |- *; intros f_Rel f_au_plus_1_im; intros.\n          apply f_au_plus_1_im with x; assumption.\n\n        (* case when (h x y) behaves as f and (h x z) as g: contradiction *)\n          do 2 intro; intro x_in_J; intro.\n          cut (Included U J (F J)).\n            unfold Included in |- *; unfold F in |- *;\n             unfold Setminus in |- *; intro Hyp.\n            elim (Hyp x x_in_J).\n            intros x_in_A x_in_non_Img.\n            elim x_in_non_Img.\n            red in |- *.\n            red in |- *.\n            apply Im_intro with z; assumption.\n          exact J_is_in_FJ.\n\n      (* on A\\J *)\n        elim h_x_z.\n        (* case when (h x y) behaves as g and (h x z) as f: contradiction *)\n          intro x_in_J; intros.\n          cut (Included U J (F J)).\n            unfold Included in |- *; unfold F in |- *;\n             unfold Setminus in |- *; intro Hyp.\n            elim (Hyp x x_in_J).\n            intros x_in_A x_in_non_Img.\n            elim x_in_non_Img.\n            red in |- *.\n            red in |- *.\n            apply Im_intro with y; assumption.\n          exact J_is_in_FJ.\n\n\n        (* case when (h x y) and (h x z) behaves as g: ok *) \n          elim g_inj.\n          unfold from_at_most_one_input in |- *; do 3 intro; intro g_au_plus_1_ant;\n           intros.\n          apply g_au_plus_1_ant with x; assumption.\n\n    Qed.\n\n\n    (** h satisfies to_at_least_one_output *)\n    Lemma h3 : to_at_least_one_output U A h.\n    Proof.\n      red in |- *.\n      intros.\n      elim (in_or_not_in U x (Img (Setminus U B (Imf J)))).\n\n      (* on A\\J *)\n      unfold Img in |- *; intro x_in_Img.\n      elim x_in_Img.\n      intros y g_y_x H1.\n      exists y.\n      apply hr_intro; assumption.\n\n      (* on J *)\n      intros.\n        (* from f function, we deduce that f satisfies to_at_least_one_output *)\n        elim f_inj.\n        unfold to_at_least_one_output in |- *; do 2 intro; intro f_au_moins_1_im;\n         intro.\n        elim (f_au_moins_1_im x H).\n        intros y f_x_y.\n        exists y.\n        apply hl_intro.\n          apply FJ_is_in_J.\n          red in |- *; red in |- *; red in |- *.\n          split; assumption.\n        assumption.\n\n    Qed.\n\n\n    (** h satisfies from_at_most_one_input *)\n    Lemma h4 : from_at_most_one_input U h.\n    Proof.\n      red in |- *; do 3 intro; intros h_x_z h_y_z.\n      elim h_x_z.\n\n      (* on J *)\n        elim h_y_z.\n        (* case when (h x y) and (h x z) behave as f: ok *)\n          elim f_inj.\n          intros.\n          cut (forall x y z : U, f x z -> f y z -> x = y).\n          intro Hyp; apply Hyp with z; assumption.\n          assumption.\n\n        (* show that one cannot have (f x z) and (g z y) with x in J and\n            z outside of (Imf J) without contradiction *)\n          unfold Setminus in |- *; intro z_in_Setminus_B_Imf_J; intros.\n          elim z_in_Setminus_B_Imf_J.\n          intros z_in_B z_in_non_Imf_J.\n          elim z_in_non_Imf_J.\n          red in |- *.\n          red in |- *.\n          apply Im_intro with x; assumption.\n\n      (* on A\\J *)\n        elim h_y_z.\n        (* show that one cannot (f y z) and (g z x) with x in J and\n            z outside (Imf J) without contradiction *)\n          unfold Setminus in |- *; do 2 intro; intro z_in_Setminus_B_Imf_J;\n           intros.\n          elim z_in_Setminus_B_Imf_J.\n          intros z_in_B z_in_non_Imf_J.\n          elim z_in_non_Imf_J.\n          red in |- *.\n          red in |- *.\n          apply Im_intro with y; assumption.\n\n        (* from g function, one deduces that g satisfies to_at_most_one_output,\n           which means from_at_most_one_input for h *)\n          elim g_inj.\n          intros.\n          cut (forall z x y : U, g z x -> g z y -> x = y).\n          intro Hyp; apply Hyp with z; assumption.\n          assumption.\n\n    Qed.\n\n\n    (** h satisfies from_at_least_one_input *)\n    Lemma h5 : from_at_least_one_input U B h.\n    Proof.\n      red in |- *.\n      intros.\n      elim (in_or_not_in U y (Imf J)).\n\n      (* on J *)\n      unfold Imf in |- *; intro y_in_Imf.\n        (* from f injective, one deduces that f satisfies from_at_least_one_input *)\n          elim y_in_Imf.\n          intros x f_x_y; intro.\n          exists x.\n          apply hl_intro; assumption.\n\n      (* on A\\J *)\n        intros.\n        (* from g injective, one deduces g satisfies to_at_least_one_output,\n           which means from_at_least_one_input for h *)\n          elim g_inj.\n          unfold to_at_least_one_output in |- *; do 2 intro; intro g_au_moins_1_im;\n           intro.\n          elim (g_au_moins_1_im y H).\n          intros x g_y_x.\n          exists x.\n          apply hr_intro.\n          red in |- *.\n          split; assumption.\n          assumption.\n\n    Qed.\n\n    (** We can now resume the proof of h_bij *)\n\n    Proof.\n    exact (bijection_intro U A B h h1 h2 h3 h4 h5).\n    Qed.\n\n  End Bijection.\n\n\n(**    Schroeder-Bernstein-Cantor Theorem     *)\n\nTheorem Schroeder : A <=_card B -> B <=_card A -> A =_card B.\n\nProof.\n\n  intros A_inf_B B_inf_A.\n  elim A_inf_B.\n  intros.\n  elim B_inf_A.\n  intros.\n  apply equipollence_intro with (h f f0).\n  apply h_bij; assumption.\n\nQed.\n\n\nEnd Schroeder_Bernstein.\n\n\n                           (* The end *)\n\n\n(* $Id$ *)\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/schroeder/Schroeder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7288567203702123}}
{"text": "Require Import List Arith Omega Lia.\nImport ListNotations.\n\nInductive expr : Type :=\n| Const : nat -> expr\n| Plus : expr -> expr -> expr.\n\nFixpoint eval_expr (e : expr) : nat := \n  match e with\n  | Const n => n\n  | Plus e1 e2 => eval_expr e1 + eval_expr e2\n  end.\n\nFixpoint eval_expr_tail' (e : expr) (acc : nat) : nat :=\n  match e with\n  | Const n => n + acc\n  | Plus e1 e2 => eval_expr_tail' e2 (eval_expr_tail' e1 acc)\n  end.\n\nDefinition eval_expr_tail e := eval_expr_tail' e 0.\n\nFixpoint eval_expr_cont' {A} (e : expr) (k : nat -> A) : A :=\n  match e with\n  | Const n => k n\n  | Plus e1 e2 => eval_expr_cont' e2 (fun n2 =>\n                  eval_expr_cont' e1 (fun n1 => k (n1 + n2)))\n  end.\n\nDefinition eval_expr_cont (e : expr) : nat :=\n  eval_expr_cont' e (fun n => n).\n\nLemma silly1 : forall e n, eval_expr_tail' e n = n + eval_expr_tail' e 0.\nProof.\n  induction e;intros;simpl. omega.\n  rewrite (IHe1 n). rewrite (IHe2 (n + eval_expr_tail' e1 0)).\n  rewrite (IHe2 (eval_expr_tail' e1 0)). omega.\nQed.\n\nTheorem eval_expr_tail_correct : forall e, eval_expr_tail e = eval_expr e.\nProof.\n  induction e;unfold eval_expr_tail in *;simpl.\n  omega. rewrite IHe1. rewrite silly1. auto.\nQed.\n\nLemma silly2 : forall {A : Type} e (k : nat -> A), eval_expr_cont' e k\n                            = k (eval_expr e).\nProof.\n  induction e;intros;simpl. auto.\n  rewrite (IHe2 (fun n2 : nat => eval_expr_cont' e1 (fun n1 : nat => k (n1 + n2)))).\n  rewrite (IHe1 (fun n1 : nat => k (n1 + eval_expr e2))). auto.\nQed.\n\nTheorem eval_expr_cont_correct : forall e, eval_expr_cont e = eval_expr e.\nProof.\n  induction e;unfold eval_expr_cont in *;simpl. auto.\n  rewrite (silly2 _ (fun n2 : nat => eval_expr_cont' e1 (fun n1 : nat => n1 + n2))).\n  rewrite (silly2 _ (fun n1 : nat => n1 + eval_expr e2)). auto.\nQed.\n\nInductive instr := Push (n : nat) | Add.\n\nDefinition prog := list instr.\n\nDefinition stack := list nat.\n\nFixpoint run (p : prog) (s : stack) : stack := \n  match p with\n  | [] => s\n  | i :: p' => let s' :=\n                  match i with\n                  | Push n => n :: s\n                  | Add => match s with\n                          | a1 :: a2 :: s' => a1 + a2 :: s'\n                          | _ => s\n                          end\n                  end in\n              run p' s'\n  end.\n\nFixpoint compile (e : expr) : prog :=\n  match e with\n  | Const n => [Push n]\n  | Plus e1 e2 => compile e1 ++ compile e2 ++ [Add]\n  end.\n\nLemma silly3 : forall p1 p2 s, run (p1 ++ p2) s = run p2 (run p1 s).\nProof. induction p1;intros;simpl;auto. Qed.\n\nTheorem compile_correct_extend : forall e s, run (compile e) s = eval_expr e :: s.\nProof.\n  induction e;intros;simpl;auto.\n  repeat rewrite silly3. rewrite IHe2. rewrite IHe1. simpl. rewrite plus_comm. auto.\nQed.\n\nTheorem compile_correct : forall e, run (compile e) [] = [eval_expr e].\nProof. intros; apply (compile_correct_extend e []). Qed.", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/Simple_Lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7288318749237873}}
{"text": "(* author: Dimitur Krustev *)\n(* started: 20170526 *)\n\nRequire Import ZArith List.\n\nOpen Scope Z_scope.\n\nDefinition Model := Z.\n\nDefinition model : Model := 0.\n\nInductive Msg := Increment | Decrement.\n\nDefinition update (msg: Msg) (model: Model) : Model :=\n  match msg with\n  | Increment => model + 1\n  | Decrement => model - 1\n  end.\n\n(* *** *)\n\nTheorem update_ok: forall (msgs: list Msg) (model: Model), \n  let decrements := filter (fun msg => \n    match msg with Decrement => true | _ => false end) msgs in\n  let increments := filter (fun msg => \n    match msg with Increment => true | _ => false end) msgs in\n  fold_left (fun model msg => update msg model) msgs model\n    = model + Zlength increments - Zlength decrements.\nProof.\n  induction msgs.\n  - simpl. unfold Zlength. simpl. intros. unfold Model in *. ring.\n  - simpl. destruct a.\n    + simpl. intros. rewrite Zlength_cons. \n      rewrite IHmsgs.\n      unfold Model in *. ring.\n    + simpl. intros. rewrite Zlength_cons. \n      rewrite IHmsgs.\n      unfold Model in *. ring.\nQed.\n\n(* *** *)\n\nExtraction Language Haskell.\nRequire ExtrHaskellBasic.\nRequire ExtrHaskellZInt.\n\nRecursive Extraction update.\n", "meta": {"author": "dkrustev", "repo": "coq-misc-essays", "sha": "3cecd11e601dc64447820207240123e8f978366e", "save_path": "github-repos/coq/dkrustev-coq-misc-essays", "path": "github-repos/coq/dkrustev-coq-misc-essays/coq-misc-essays-3cecd11e601dc64447820207240123e8f978366e/ElmCounter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7288318699937559}}
{"text": "\nAdd LoadPath \"C:\\Users\\spide\\Documents\\Tareas\\VerificacionFormal\\Tareas\\Tarea3\\Tarea3VFLuisBLluis\" as camino. \n \n(** Tarea 3 Verificación Formal\n    Luis B. Lluis LL11\n    El siguiente script contiene las notaciones y definiciones \n    para números por paridad.\n    Este script es una concatenación \n    de scripts bn2.v , orderbn.v \n    de Favio Ezequiel Miranda. \n  Dependencias: NONE  \n  Contenido\n  1.- bn2----------------no depends\n      bn sucBN predBN toN toBN plusBN   \n  3.- orderbn------------depends bn2\n      ltBN lteqBN\n     \n*)\n\n\n(** 1.------------- bn-----------------------*)\n(*Datatype for our numerical system with 0, U and D*)\nInductive BN :=\n  Z: BN\n| U: BN -> BN\n| D: BN -> BN.\n\n(* Successor function for BN numbers  *)\nFixpoint sucBN (b:BN) : BN :=\n  match b with\n      Z => U Z\n    | U x => D x (*S(U x) = S(2x + 1) = 2x + 2 = D x*)\n    | D x => U (sucBN x) (*S(D x)= S(2x + 2) = S(S(2x + 1)) = S(2x + 1) + 1  *)\n                 (* 2(S(x)) + 1 = 2(x+1) + 1 = (2x + 2) + 1 = S(2x + 1) + 1*)  \n  end.\n  \n(* Predeccesor function with error *)\n\nParameter (undefBN: BN). (* we assume a constant undefBN:BN representing an undefined BN number *)\n\nFixpoint predBN (b:BN): BN :=\n match b with\n  Z => undefBN\n |U Z => Z\n |U x => D (predBN x)\n |D x => U x\n end.\n\n(* Conversion functions *)\n\n(* Recursive function that converts a number of type BN\n to its respective natural number*)\nFixpoint toN (b:BN) : nat :=\n  match b with \n      Z => 0\n    | U x => 2*(toN x) + 1\n    | D x => 2*(toN x) + 2\n  end.\n\n\n(* Converts a nat value to BN value. \n   Inverse of the above one.*)\nFixpoint toBN (n: nat) : BN :=\n  match n with\n      0 => Z\n    | S x => sucBN (toBN x)\n  end.\n\n(* Definition of sum of BN elements*)\n\nFixpoint plusBN (a b : BN) : BN :=\n  match a,b with\n    | Z, b => b\n    | a, Z  => a\n    | U x, U y => D(plusBN x y)\n    | D x, U y => U(sucBN (plusBN x y))\n    | U x, D y => U(sucBN (plusBN x y))\n    | D x, D y => D(sucBN (plusBN x y))                \n  end.\n\nNotation \"a ⊞ b\" := (plusBN a b) (at level 60). \n\n\n(** 3.----------------------- orderbn *)\nInductive ltBN : BN -> BN -> Prop :=\n | ltBNZU : forall (a:BN), ltBN Z (U a)\n | ltBNZD : forall (a:BN), ltBN Z (D a)\n | ltBNUU : forall (a b:BN), ltBN a b -> ltBN (U a) (U b)\n | ltBNUDeq : forall (a :BN), ltBN (U a) (D a) \n | ltBNUD : forall (a b:BN), ltBN a b -> ltBN (U a) (D b) \n | ltBNDU : forall (a b:BN), ltBN a b -> ltBN (D a) (U b)\n | ltBNDD : forall (a b:BN), ltBN a b -> ltBN (D a) (D b).\n\n\nInductive lteqBN: BN -> BN -> Prop :=\n | lteqBNref: forall (a:BN), lteqBN a a\n | lteqBNl: forall (a b: BN), ltBN a b -> lteqBN a b.\n\n\nNotation \"a <BN b\" := (ltBN a b) (at level 70).\nNotation \"a <BN b <BN c\" := (ltBN a b /\\ ltBN b c) (at level 70, b at next level).\n\nNotation \"a ≤BN b\" := (lteqBN a b) (at level 70).", "meta": {"author": "LuisBLluis11", "repo": "Tarea3VFLuisBLluis", "sha": "14252f935dd4b7ab914fca2e4ef30eacd357a7f8", "save_path": "github-repos/coq/LuisBLluis11-Tarea3VFLuisBLluis", "path": "github-repos/coq/LuisBLluis11-Tarea3VFLuisBLluis/Tarea3VFLuisBLluis-14252f935dd4b7ab914fca2e4ef30eacd357a7f8/Defs_BN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7288215933174642}}
{"text": "Require Import List.\n\nInductive swap_once: list nat -> list nat -> Prop :=\n| OnceSwap1: forall h1 h2 t, swap_once (h1 :: h2 :: t) (h2 :: h1 :: t)\n| OnceSwap2: forall h t1 t2, swap_once t1 t2 -> swap_once (h :: t1) (h :: t2).\n\nInductive is_odd_permutation: list nat -> list nat -> Prop :=\n| OddPermutation1: forall l1 l2,\n    swap_once l1 l2 -> is_odd_permutation l1 l2\n| OddPermutation2: forall l1 l2 l3 l4,\n    swap_once l1 l2 -> swap_once l2 l3 -> is_odd_permutation l3 l4 ->\n    is_odd_permutation l1 l4.\n\nDefinition task := forall l1 l2, NoDup l1 -> is_odd_permutation l1 l2 -> l1 <> l2.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/011/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.728815605512971}}
{"text": "(**************************************************************************)\n(*   Mechanised Framework for Local Interactions & Distributed Algorithms *)\n(*   P. Courtieu, L. Rieg, X. Urbain                                      *)\n(*   PACTOLE project                                                      *)\n(*                                                                        *)\n(*   This file is distributed under the terms of the CeCILL-C licence     *)\n(*                                                                        *)\n(**************************************************************************)\n\n\nRequire Import Reals.\nRequire Import SetoidList.\nRequire Import SetoidDec.\nRequire Import Pactole.Util.Coqlib.\nRequire Export Pactole.Spaces.RealVectorSpace.\n\n\nClass RealMetricSpace (T : Type) {S : Setoid T} `{@EqDec T S} {VS : RealVectorSpace T} := {\n  dist : T -> T -> R;\n  \n  dist_defined : forall u v, dist u v = 0%R <-> u == v;\n  dist_sym : forall u v, dist v u = dist u v;\n  triang_ineq : forall u v w, (dist u w <= dist u v + dist v w)%R}.\n\nArguments dist T%type _ _ _ _ u%VS v%VS.\n\nInstance dist_compat `{RealMetricSpace} : Proper (equiv ==> equiv ==> Logic.eq) dist.\nProof.\nintros x x' Hx y y' Hy. apply Rle_antisym.\n+ replace (dist x' y') with (0 + dist x' y' + 0)%R by ring. symmetry in Hy.\n  rewrite <- dist_defined in Hx. rewrite <- dist_defined in Hy.\n  rewrite <- Hx at 1. rewrite <- Hy. eapply Rle_trans. apply triang_ineq.\n  rewrite Rplus_assoc. apply Rplus_le_compat_l, triang_ineq.\n+ replace (dist x y) with (0 + dist x y + 0)%R by ring. symmetry in Hx.\n  rewrite <- dist_defined in Hx. rewrite <- dist_defined in Hy.\n  rewrite <- Hx at 1. rewrite <- Hy. eapply Rle_trans. apply triang_ineq.\n  rewrite Rplus_assoc. apply Rplus_le_compat_l, triang_ineq.\nQed.\n\nLemma dist_nonneg `{RealMetricSpace} : forall u v, (0 <= dist u v)%R.\nProof.\nintros x y. apply Rmult_le_reg_l with 2%R.\n+ apply Rlt_R0_R2.\n+ do 2 rewrite double. rewrite Rplus_0_r.\n  assert (Hx : equiv x x) by reflexivity. rewrite <- dist_defined in Hx. rewrite <- Hx.\n  setoid_rewrite dist_sym at 3. apply triang_ineq.\nQed.\n\nLemma dist_same `{RealMetricSpace} : forall u, (dist u u = 0)%R.\nProof. intro. rewrite dist_defined. reflexivity. Qed.\n\nSection MaxDist.\nContext `{RealMetricSpace}.\n\n(** Maximum distance of a list of points to a point. *)\nDefinition max_dist_pt_list pt := max_list (fun pt' => dist pt pt').\n\nLemma max_dist_pt_list_nonneg : forall pt l, 0 <= max_dist_pt_list pt l.\nProof using . intros. apply max_list_aux_min. Qed.\n\nLemma max_dist_pt_list_app : forall pt l1 l2,\n  max_dist_pt_list pt (l1 ++ l2) = Rmax (max_dist_pt_list pt l1) (max_dist_pt_list pt l2).\nProof using . intros. apply max_list_app. Qed.\n\nGlobal Instance max_dist_pt_list_compat :\n  Proper (equiv ==> equivlistA equiv ==> eq) max_dist_pt_list.\nProof using . intros ? ? Heq1. apply max_list_compat. intros ? ? Heq2. now rewrite Heq1, Heq2. Qed.\n\nLemma max_dist_pt_list_le : forall pt l pt1,\n  InA equiv pt1 l -> dist pt pt1 <= max_dist_pt_list pt l.\nProof using . intros. apply max_list_le; trivial; now apply dist_compat. Qed.\n\nLemma max_dist_pt_list_ex : forall pt l, l <> nil ->\n  exists pt1, InA equiv pt1 l /\\ dist pt pt1 = max_dist_pt_list pt l.\nProof using .\nintros pt l Hl. destruct (max_list_ex (dist pt) Hl) as [pt' [Hin Heq]].\nrewrite Rmax_left in Heq; try apply dist_nonneg; [].\neauto.\nQed.\n\nLemma max_dist_pt_list_eq_0 : forall pt l,\n  max_dist_pt_list pt l = 0%R <-> forall x, InA equiv x l -> x == pt.\nProof using .\nintros pt l. unfold max_dist_pt_list.\nrewrite (max_list_eq_0 (dist_compat _ _ (reflexivity pt)) (dist_nonneg pt)).\nsetoid_rewrite dist_sym. setoid_rewrite dist_defined.\nreflexivity.\nQed.\n\n(** Maximum distance of between lists of points. *)\nDefinition max_dist_list_list l1 l2 : R :=\n  max_list (fun pt => max_dist_pt_list pt l2) l1.\n\nGlobal Instance max_dist_list_list_compat :\n  Proper (equivlistA equiv ==> equivlistA equiv ==> eq) max_dist_list_list.\nProof using .\nrepeat intro. apply max_list_compat; trivial; [].\nrepeat intro. now apply max_dist_pt_list_compat.\nQed.\n\nLemma max_dist_list_list_le : forall pt1 l1 pt2 l2,\n  InA equiv pt1 l1 -> InA equiv pt2 l2 -> dist pt1 pt2 <= max_dist_list_list l1 l2.\nProof using .\nintros. transitivity (max_dist_pt_list pt1 l2).\n- now apply max_dist_pt_list_le.\n- now apply (max_list_le (fun x y Hxy => max_dist_pt_list_compat x y Hxy _ _ (reflexivity l2))).\nQed.\n\nLemma max_dist_list_list_ex : forall l1 l2, l1 <> nil -> l2 <> nil ->\n  exists pt1 pt2, InA equiv pt1 l1 /\\ InA equiv pt2 l2 /\\ dist pt1 pt2 = max_dist_list_list l1 l2.\nProof using .\nintros l1 l2 Hl1 Hl2.\ndestruct (max_list_ex (fun pt => max_dist_pt_list pt l2) Hl1) as [pt1 [Hin1 Heq1]].\ndestruct (max_dist_pt_list_ex pt1 _ Hl2) as [pt2 [Hin2 Heq2]].\nexists pt1, pt2. repeat split; auto.\nunfold max_dist_list_list. rewrite Heq1, Heq2.\nrewrite Rmax_left; trivial; [].\ntransitivity (dist pt1 pt2).\n- apply dist_nonneg.\n- now apply max_dist_pt_list_le.\nQed.\n\nLemma max_dist_list_list_cons_le : forall pt l,\n  max_dist_list_list l l <= max_dist_list_list (pt :: l) (pt :: l).\nProof using .\nintros pt [| pt' l].\n- cbn. repeat rewrite Rmax_left; apply dist_nonneg.\n- destruct (@max_dist_list_list_ex (pt' :: l) (pt' :: l))\n    as [pt1 [pt2 [Hpt1 [Hpt2 Heq]]]]; try discriminate; [].\n  rewrite <- Heq. apply max_dist_list_list_le; now right.\nQed.\n\nEnd MaxDist.\n", "meta": {"author": "MathisBD", "repo": "pactole_stage", "sha": "4b63da0898ae4f48956408dc31f7831d3ad8930f", "save_path": "github-repos/coq/MathisBD-pactole_stage", "path": "github-repos/coq/MathisBD-pactole_stage/pactole_stage-4b63da0898ae4f48956408dc31f7831d3ad8930f/Spaces/RealMetricSpace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129513, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7288156034020978}}
{"text": "\n  Require Export ZArith. \n  Require Export NPeano.\n\n  Require Export List. \n  Export ListNotations.\n\n  Require Import Sorting.Sorted.\n\n\n  Notation \"[ x , .. , y ]\" := (cons x .. (cons y []) ..).  \n\n(** Start with blank\n\n *)\n\n\n  Ltac name_term n t H := \n    assert (H: exists n', n' = t);\n      try (exists t; reflexivity);\n      destruct H as [n H]. \n\n\n  Require Import Coq.Arith.Wf_nat.                 (* [lt_wf] *)\n  Require Import Coq.Wellfounded.Inverse_Image.    (* [wf_inverse_image] *)\n\n  Section ListLen. \n    Context { A: Type }.\n    Definition lt_length (m1 m2: list A) := length m1 < length m2. \n    Lemma lt_length_wf: well_founded lt_length. \n    Proof.\n      unfold lt_length. \n      eapply wf_inverse_image. eapply lt_wf.\n    Defined.\n  End ListLen.\n\n  \n  Section ListId. \n    Context {A: Type}.\n\n    Definition list_id (l: list A) := l.\n\n    Lemma list_id_wont_expand: \n      forall (l_in l_out: list A), \n        l_out = list_id l_in -> length l_out <= length l_in.\n      intros l_in l_out H. \n      unfold list_id in H.\n      subst; auto.\n    Qed.\n    \n    Lemma id_lt: \n      forall m (x: A) xs, \n        list_id m = (x::xs) -> lt_length xs m. \n    Proof. \n      intros.\n      unfold list_id in H.\n      subst m.\n      unfold lt_length.\n      auto.\n    Qed.  \n  End ListId.\n  \n  Section ListOption. \n    Context {A: Type}.\n\n    Definition list_option (l: list A) := \n      match l with \n        | [] => None\n        | x :: xs => Some (x, xs)\n      end.\n\n    Lemma list_option_wont_expand: \n      forall (l_in l_out: list A) x o_out, \n        o_out = list_option l_in -> \n        o_out = None \\/ \n        (o_out = Some (x, l_out) -> length l_out <= length l_in).\n      intros l_in l_out * H. \n      unfold list_option in H.\n      destruct l_in as [| y ys].\n      - left; apply H.\n      - right; intro O; rewrite H in O; injection O; intros Ys Y.\n        subst; auto.\n        simpl; auto with arith.\n    Qed.\n    \n    Lemma list_option_lt: \n      forall m (x: A) l, \n        list_option m = Some (x, l) -> lt_length l m. \n    Proof. \n      intros.\n      unfold list_option in H.\n      destruct m as [| y ys].\n      - inversion H. \n      - injection H; intros Ys Y.\n        subst; auto.\n        unfold lt_length.\n        simpl; auto with arith.\n    Qed.  \n  End ListOption.\n\n\n\n  Section UnApp.\n    Context {A: Type}.\n\n    Fixpoint unapp (n:nat)(m:list A) : list A * list A:=\n      match n with\n        | 0 => ([], m)\n        | S n => match m with\n                   | nil => ([], [])\n                   | x::xs => let (m1, m2) := unapp n xs in\n                              (x::m1, m2)\n                 end\n      end.\n\n    Lemma unapp_wont_expand: \n      forall n (m m1 m2: list A), \n        unapp n m = (m1, m2) -> \n        length m1 <= length m /\\ length m2 <= length m. \n    Proof. \n      induction n as [| n]; intros * UA. \n      - simpl in UA. injection UA; intros M1 M2.\n        subst m1 m2. auto with arith.\n      - destruct m. \n        + simpl in UA.\n          injection UA; intros M1 M2. \n          subst m1 m2. auto with arith. \n        + simpl in UA.\n          name_term ua' (unapp n m) UA'.\n          rewrite <- UA' in UA.\n          destruct ua' as [m1' m2'].\n          injection UA; intros M1 M2; subst m1 m2; clear UA.\n          symmetry in UA'.\n          apply IHn in UA'.\n          simpl.\n          omega. \n    Qed.        \n    \n    Lemma unapp_app: \n      forall n (m m1 m2: list A),\n        (m1, m2) = unapp n m -> \n        m1 ++ m2 = m.\n    Proof. \n      intros n m.\n      revert n.\n      induction m as [| x xs]; intros * UA.\n      - destruct n as [| n'];\n        simpl in UA;\n        injection UA; intros M1 M2; subst m1 m2; clear UA;\n        simpl; auto with arith.\n      - destruct n as [| n'];\n        simpl in UA.\n        + injection UA; intros M1 M2; subst m1 m2; clear UA.\n          reflexivity.\n        + name_term ua' (unapp n' xs) UA'.  rewrite <- UA' in UA.\n          destruct ua' as [m1' m2'].\n          injection UA; intros M1 M2; subst m1 m2; clear UA.\n          simpl. \n          apply IHxs in UA'.\n          subst xs.\n          reflexivity.\n    Qed. \n\n    Lemma unapp_reduce_m1: \n      forall n (m m1 m2: list A), \n        unapp n m = (m1, m2) -> \n        n < length m -> \n        length m1 < length m. \n    Proof. \n      intros n m. \n      revert n.\n      induction m as [| x xs];\n        intros * UA NltM. \n      - simpl in NltM. inversion NltM.\n      - destruct n as [| n].\n        + unfold unapp in UA.\n          injection UA; intros M1 M2; subst m1 m2; clear UA.\n          simpl. auto with arith.\n        + simpl in UA.\n          simpl in NltM. \n          apply lt_S_n in NltM.\n          name_term ua' (unapp n xs) UA'.  rewrite <- UA' in UA.\n          destruct ua' as [m1' m2'].\n          injection UA; intros M1 M2; subst m1 m2; clear UA.\n          symmetry in UA'.\n          apply IHxs in UA'; auto.\n          simpl.\n          omega. \n    Qed. \n\n\n    Lemma unapp_reduce_m2: \n      forall n (m m1 m2: list A), \n        unapp n m = (m1, m2)-> \n        n > 0 ->\n        length m > 0 -> \n        length m2 < length m. \n    Proof. \n      intros * UA Ngt0 Mgt0. \n      cut (length m1 > 0). \n      {\n        intro H.\n        symmetry in UA.\n        apply unapp_app in UA.\n        subst m.\n        rewrite app_length in *.\n        omega. \n      }\n      destruct n as [| n']; destruct m as [| x xs].\n      - inversion Ngt0.\n      - inversion Ngt0.\n      - simpl in Mgt0.\n        inversion Mgt0.      \n      - simpl in UA.\n        name_term ua' (unapp n' xs) UA'.  rewrite <- UA' in UA.\n        destruct ua' as [m1' m2'].\n        injection UA; intros M1 M2; subst m1 m2; clear UA.\n        simpl. auto with arith.\n    Qed. \n\n\n  End UnApp.\n\n  Require Export Div2.\n  Lemma div2_SS: \n    forall n, div2 (S (S n)) > 0.\n  Proof. \n    induction n; simpl; auto with arith.\n  Qed. \n\n  Lemma le_div2: \n    forall n, n >= div2 n.\n  Proof.\n    intro n.\n    destruct n as [| n]; auto. \n    cut (S n > div2 (S n)).\n    intro C; auto with arith.\n    apply lt_div2; auto with arith.\n  Qed.\n\n  Section UnappHalf.\n    Context {A: Type}.\n\n    Definition unapp_half(m: list A) :=\n      let n := length m in \n      let n2 := div2 n in\n      let n1 := n - n2 in\n      unapp n1 m. \n    \n    Lemma unapp_half_app: \n      forall m m1 m2,\n        (m1, m2) = unapp_half m -> \n        m1 ++ m2 = m.\n    Proof. \n      induction m as [| x xs]; intros * SP. \n      inversion SP; auto.\n      unfold unapp_half in SP.\n      apply unapp_app in SP.\n      auto.\n    Qed. \n    \n    Lemma unapp_half_nonnil_reduces: \n      forall m m1 m2, \n        unapp_half m = (m1,m2) -> \n        length m > S 0 -> \n        length m1 < length m /\\ length m2 < length m.\n    Proof. \n      intros * SP MgtO.\n      unfold unapp_half in SP.\n      name_term k (length m) LEN. \n      rewrite <- LEN in *.\n      name_term n (k - div2 k) N1. \n      rewrite <- N1 in SP.     \n      assert (DK: div2 k < k) \n        by (apply lt_div2; auto with arith).\n      name_term d (div2 k) D. \n      rewrite <- D in *.\n      destruct m as [| x1 xs]. \n      simpl in LEN. subst k. inversion DK.\n      destruct xs as [| x2 xs].\n      simpl in LEN. subst k. inversion MgtO. inversion H0.\n      assert (DgtO: d > 0) by (subst k d; apply div2_SS). \n      assert (NltM: n < length (x1::x2::xs))\n        by (simpl in *; omega). \n      subst k.\n      split. \n      - apply unapp_reduce_m1 with (n0:=n) (m4:=m2); auto.\n      - assert (n > 0) by omega. \n        assert (length (x1::x2::xs) > 0) by (simpl; omega).\n        apply unapp_reduce_m2 with (n0:=n) (m3:=m1); auto.\n    Qed. \n\n    Lemma unapp_half_wont_expand: \n      forall m m1 m2, \n        unapp_half m = (m1,m2) -> \n        length m1 <= length m /\\ length m2 <= length m.\n    Proof. \n      intros * SP. \n      unfold unapp_half in SP.\n      apply unapp_wont_expand with (n:=length m - div2 (length m)); auto.\n    Qed. \n\n  End UnappHalf.\n\n  Lemma tuple_eq : \n    forall {A B: Type} (x a: A) (y b: B), \n      x = a /\\ y = b <-> (x,y) = (a,b). \n  Proof. \n    intros.\n    split.\n    - intros [L R]; now subst.\n    - intro H; now inversion H.\n  Qed.       \n\n  Lemma gt_minus: \n    forall x y, \n      x > y -> x - y > 0.\n  Proof. \n    induction x; intros * GT. \n    - inversion GT.\n    - destruct y. \n      + auto with arith.\n      + apply gt_S_n in GT.\n        apply IHx in GT.\n        auto with arith.\n  Qed. \n\n\n  Lemma nil_f_nil: \n    forall (A B: Type) (f: list A -> list B),\n      (forall l, length (f l) <= length l) -> \n      f [] = [].\n  Proof. \n    intros A B f PF.\n    name_term f_out (f []) F.\n    destruct f_out as [| x xs]. \n    - auto.\n    - assert (length (f []) <= length ([]: list A)) as A1. \n      {\n        apply PF.\n      }\n      rewrite <- F in A1.\n      simpl in A1.\n      inversion A1.\n  Qed.\n\n\n\n  Lemma rev_inv:\n    forall (X: Type) (l m: list X), \n      rev l = m ->\n      rev m = l. \n  Proof. \n    intros X l m L.\n    subst m.\n    apply rev_involutive.     \n  Qed.     \n  \n\n(** To add a new reference cell to the store, we use [snoc]. *)\n  Fixpoint snoc {A:Type} (l:list A) (x:A) : list A :=\n    match l with\n    | nil    => x :: nil\n    | h :: t => h :: snoc t x\n    end.\n  \n\n  (**\n     from Poly.v\n     *)\n  Theorem rev_snoc : forall X : Type, \n    forall v : X,\n      forall s : list X,\n        rev (snoc s v) = v :: (rev s).\n  Proof. \n    intros X v s. induction s as [|h t]. reflexivity. \n    simpl. rewrite -> IHt.\n    simpl. reflexivity. Qed. \n  \n  \n  Lemma length_snoc : forall A (l:list A) x,\n      length (snoc l x) = S (length l).\n  Proof.\n    induction l; intros; [ auto | simpl; rewrite IHl; auto ]. Qed.\n  \n  (* The \"solve by inversion\" tactic is explained in Stlc.v. *)\n  Lemma nth_lt_snoc : forall A (l:list A) x d n,\n      n < length l ->\n      nth n l d = nth n (snoc l x) d.\n  Proof.\n    induction l as [|a l']; intros.\n    inversion H. \n    destruct n; auto.\n    simpl. apply IHl'. \n    simpl in H. apply lt_S_n in H. assumption.\n  Qed.\n  \n  Lemma nth_eq_snoc : forall A (l:list A) x d,\n      nth (length l) (snoc l x) d = x.\n  Proof.\n    induction l; intros; [ auto | simpl; rewrite IHl; auto ].\n  Qed.\n  \n  Lemma nth_i_nil__default: forall (A: Type) (i: nat) (d: A),\n    nth i [] d = d. \n  Proof. \n    intros A i d.\n    induction i as [| i'].\n    simpl. auto.\n    simpl. auto.\n  Qed.\n\n\n  Lemma snoc_list: forall X: Type, forall y: X, forall l: list X,\n          snoc l y = l ++ [y].\n  Proof. intros X y l. induction l as [|x xs]. \n         reflexivity.\n         simpl. rewrite -> IHxs. reflexivity. Qed.\n  \n  \n  Theorem snoc_with_append : forall X : Type, \n      forall l1 l2 : list X,\n      forall v : X,\n        snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).\nProof.\n    intros X l1 l2 v. induction l2 as [|x xs].\n    simpl. \n    assert (l1 ++ [] = l1 ) as H.\n    rewrite app_nil_r. reflexivity. rewrite H.\n    rewrite snoc_list. reflexivity.     \n    simpl.\n    rewrite snoc_list. \n    rewrite snoc_list. \n    rewrite <- app_assoc. reflexivity. Qed.\n\n\n\n  Theorem snoc_with_tail : forall X : Type, \n                         forall l : list X,\n                         forall h v : X,\n    snoc (h::l) v = h :: (snoc l v).\n  Proof.\n    intros X l h v. \n    simpl.\n    reflexivity.\n  Qed.\n\n  \n  Lemma snoc__eq__snoc: forall (X: Type) (x y: X) (xs ys: list X),\n    snoc xs x = snoc ys y <-> xs = ys /\\ x = y.\n  Proof.\n    intros. \n    split.\n    - intro H.\n      split.\n      + generalize dependent ys. \n        induction xs as [| xh xt]; intros ys H. \n        * induction ys as [| yh yt]. inversion H. auto.\n          inversion H. destruct yt. inversion H2. inversion H2.\n        * induction ys as [| yh yt]. inversion H. \n          destruct xt. inversion H2. inversion H2.\n          \n          simpl in H.\n          inversion H.\n          apply IHxt in H2.\n          now subst.\n      + generalize dependent ys. \n        induction xs as [| xh xt]; intros ys H. \n        * induction ys as [| yh yt]. inversion H. auto.\n          inversion H. destruct yt. inversion H2. inversion H2.\n        * induction ys as [| yh yt]. inversion H. \n          destruct xt. inversion H2. inversion H2.\n          simpl in H.\n          inversion H.\n\n          rewrite IHxt with (ys:=yt); auto.\n    - intros [Hxs Hx].\n      now subst.\n  Qed.\n\n\n  Lemma snoc_l_eqv: forall (X: Type) (l m: list X) (r: X), \n    snoc l r = snoc m r <-> l = m.\n  Proof.\n    intros.\n    split; intro H;\n      try apply snoc__eq__snoc in H. \n    destruct H as [H1 H2]. exact H1.\n    subst l. reflexivity.\n  Qed.\n  \n  Lemma list__ex_snoc: forall (X: Type) (l xs: list X) (x: X),\n    l = (x::xs) -> exists l_front, exists l_end, l = (snoc l_front l_end). \n  Proof. \n    intros X l xs x H.\n    generalize dependent x. \n    generalize dependent l. \n    induction xs as [| x' xs']; intros l x H.\n    - exists []. exists x. simpl. auto.\n    - induction l. inversion H.\n      inversion H.\n\n      assert (exists l_front : list X, exists l_end : X, l = snoc l_front l_end) as EX_FE.\n        apply IHxs' with (x:=x'). auto.\n\n      destruct EX_FE as [l_front' [l_end' SNC]].\n\n      exists (x::l_front'). \n      exists l_end'.\n\n      simpl. \n      rewrite <- SNC.\n      rewrite <- H2.\n      auto.\n  Qed.\n\n\n   Lemma list_cat__with_empty_front: forall (X:Type) (l1 l2: list X),\n     l1 ++ l2 = l2 -> l1 = [].\n   Proof.     \n     intros X l1 l2 H.\n     assert (l1 ++ l2 = [] ++ l2) as EQ.\n     simpl. auto.\n     apply app_inv_tail in EQ.\n     rewrite EQ. \n     reflexivity.\n   Qed.\n\n\n\n  Definition eq_nat_tuple_dec : forall x y: nat * nat, \n                               {x = y} + {x <> y}.\n  Proof. \n    intros x y.\n    destruct x as [x1 x2]; destruct y as [y1 y2].\n\n    remember (beq_nat x1 y1) as r1.\n    remember (beq_nat x2 y2) as r2.\n    destruct r1; destruct r2.    \n\n    left. \n    apply beq_nat_eq in Heqr1.\n    apply beq_nat_eq in Heqr2.\n    subst. auto.\n\n    right.\n    intro cntr.\n    apply beq_nat_eq in Heqr1.\n    symmetry in Heqr2.\n    apply beq_nat_false in Heqr2.\n    subst.\n    inversion cntr.\n    apply Heqr2. auto.\n\n    right.\n    apply beq_nat_eq in Heqr2.\n    symmetry in Heqr1.\n    apply beq_nat_false in Heqr1.\n    intro cntr.\n    subst.\n    inversion cntr.\n    apply Heqr1. auto.\n\n    right.\n    intro cntr.\n    symmetry in Heqr1.\n    symmetry in Heqr2.\n    apply beq_nat_false in Heqr1.\n    apply beq_nat_false in Heqr2.\n    inversion cntr.\n    apply Heqr1.\n    subst. auto.\n  Qed.\n\n\n  Lemma tuple_exmid: forall (x1 x2 y1 y2: nat),\n    (x1,x2) = (y1,y2) \\/ (x1,x2) <> (y1,y2). \n  Proof.\n    intros.\n    destruct (eq_nat_tuple_dec (x1,x2) (y1,y2));\n    intuition.\n  Qed.\n\n\n  Fixpoint natInLst (n: nat) (l: list nat) : bool :=\n    match l with\n      | nil => false\n      | x::xs => if beq_nat n x then true\n                 else natInLst n xs\n    end.\n\n  Fixpoint lstSub_nat (lst_A: list nat) (lst_B: list nat) : list nat :=\n    match lst_A with \n      | nil => []\n      | x::xs => if natInLst x lst_B then lstSub_nat xs lst_B\n                 else x::(lstSub_nat xs lst_B)\n    end.\n\n   Lemma lstSub_hd: forall rl i h t,\n     h::t = lstSub_nat rl [i] ->\n     h <> i.\n   Proof.\n     intro rl.\n     induction rl as [| r rl']; intros i h t LS.\n     - simpl in LS. inversion LS.\n     - simpl in LS.\n       remember (r =? i) as ri.\n       destruct ri.\n       + apply beq_nat_eq in Heqri.\n         subst.\n         apply IHrl' with (t:=t).\n         auto.\n       + inversion LS.\n         subst.\n         symmetry in Heqri.\n         apply beq_nat_false in Heqri.\n         auto.\n\n  Qed.\n\n   Require Export Bool. \n   \n  (** From DeepSpec Summer School, Part29, Appel (July 24, 2017)    \n   *)\n  Lemma ble_reflect : forall x y, reflect (x <= y) (x <=? y).\n  Proof.\n    intros.\n    apply iff_reflect.\n    symmetry. apply Nat.leb_le.\n  Qed.\n\n  Lemma beq_reflect : forall x y, reflect (x = y) (x =? y).\n  Proof.\n    intros.\n    apply iff_reflect.\n    symmetry. apply Nat.eqb_eq.\n  Qed.\n  \n  Lemma blt_reflect : forall x y, reflect (x < y) (x <? y).\n  Proof.\n    intros.\n    apply iff_reflect.\n    symmetry. apply Nat.ltb_lt.\n  Qed.\n\n\n   \n   Fixpoint nat_in (n: nat) (l: list nat) : bool :=\n     match l with \n     | nil => false\n     | n'::l' => if n =? n' then true\n                  else nat_in n l'\n     end.\n\n   Lemma nat_in__existsb: forall l n,\n       nat_in n l = existsb (fun n' => n =? n') l. \n   Proof. \n     intro l. \n     induction l as [| x xs]; intro n; simpl.\n     - reflexivity.\n     - destruct (beq_reflect n x). \n       + subst n. \n         auto.\n       + rewrite <- IHxs.\n         auto.\n   Qed.          \n\n   Lemma In__nat_in: forall lst i,\n       In i lst <-> nat_in i lst = true. \n   Proof.\n     intros. \n     rewrite nat_in__existsb.\n     split; intro H.\n     - apply existsb_exists.\n       exists i.\n       split. apply H. \n       apply Nat.eqb_refl.\n     - apply existsb_exists in H.\n       inversion H.\n       destruct H0.\n       apply Nat.eqb_eq in H1. subst i.\n       apply H0.\n   Qed.\n\n  Lemma nat_in__app_to_front: forall l i m n,\n    nat_in i m = nat_in i n \n    -> nat_in i (l ++ m) = nat_in i (l ++ n).\n  Proof. \n    intro l.\n    induction l as [| x xs]; intros i m n H.\n    - simpl. apply H.\n    - simpl.\n      case (i =? x). auto.\n      apply IHxs. apply H.\n  Qed.\n\n  (** List/List.v in_app_or *)\n  Lemma nat_in_app_or: forall l m x,\n    nat_in x (l++m) = (nat_in x l) || (nat_in x m).\n  Proof.\n    intro l.\n    induction l as [| h t]; intros m x.\n    simpl. auto.\n    simpl. destruct (beq_nat x h).\n    simpl. auto. apply IHt.\n  Qed.\n\n  \n  Lemma nat_in_app_swap: forall l m i,\n    nat_in i (l++m) = nat_in i (m++l).\n  Proof.\n    (*\n    intros. \n    destruct (nat_in i (l++m)) eqn:H.\n    - apply In__nat_in in H.\n      apply in_app_or in H.\n      apply or_comm in H.\n      apply in_or_app in H.\n      apply In__nat_in in H.\n      symmetry.\n      apply H.\n    - \n      *)\n    intro l.\n    induction l as [| x xs]; intros m i.\n    - simpl. rewrite app_nil_r. auto.\n    - rewrite <- app_comm_cons.\n      simpl.\n      remember (beq_nat i x) as r.\n      destruct r.\n      + apply beq_nat_eq in Heqr.\n        rewrite Heqr.\n        rewrite nat_in_app_or.\n        simpl. rewrite <- beq_nat_refl with (n:=x).\n        destruct (nat_in x m); auto.\n      + rewrite IHxs.\n        assert (nat_in i (m ++ x :: xs) \n          = nat_in i m || nat_in i (x :: xs)) as A1.\n        rewrite nat_in_app_or; auto.\n        rewrite A1; clear A1.\n        simpl.\n        rewrite <- Heqr.\n        rewrite <- nat_in_app_or.\n        auto.\n  Qed.\n  \n  Lemma P_taut: forall (P: Prop), P -> P. \n  Proof. intros P H. auto. Qed. \n\n  \n  (** * From vMemo\n\n   *)\n\n\n  (** ** Utilities \n\n   *)\n\n  Definition nat_list_nil := (nil:(list nat)).\n\n  (** [destX x n] destructs [x], [n] times. It can be used to \n      break up n-tuple apart. \n   *)\n\n  Ltac dest_X x n :=\n  idtac; \n    let rec dest_X' n :=\n        match n with\n          | O => idtac\n          | S O => idtac\n          | S ?n' => let t_0 := fresh \"t_0\" in\n                     destruct x as [x t_0]\n                     ; dest_X' n'\n        end in\n    dest_X' n.\n\n    (** [match_succ_N_tac Sn n] checks if [Sn] has [n] in the form of \n       [n], [S n], or [S (S ... (S n))]. \n     *)\n    \n  Ltac match_succ_N_tac Sn n :=\n    idtac; \n    let rec match_succ_N_tac' Sn :=\n        match Sn with\n          | O => fail 1\n          | S ?Sn' => first [match_succ_N_tac' Sn'| fail 2]\n          | _ => \n            let p := fresh \"p\" in assert(p:=eq_refl n: Sn = n);\n                                  clear p; idtac\n        end in\n    match_succ_N_tac' Sn.\n\n\n\n  (** If the structure S (S ...) is not enough deep, then \n      returns fail, that means go on to the next term in [first] clause.\n      returning [idtac] means this is enough deep so get out of the loop when\n      used in [repeat match goal with].\n   *)\n\n  Ltac succ_enough Sn c :=\n    let rec succ_enough' x :=\n        match x with\n          | (_, O) => idtac \n          | (S ?Sn', S ?c') => first [succ_enough' (Sn', c') | fail 2]\n          | _ => fail 1\n        end in\n    succ_enough' (Sn, S c).\n\n  (** Just renamed from [succ_enough]\n   *)\n  Ltac succ_ge Sn c :=\n    let rec succ_ge' x :=\n        match x with\n          | (    _ ,     O) => idtac \n          | (S ?Sn', S ?c') => first [succ_ge' (Sn', c') | fail 2]\n          | _ => fail 1\n        end in\n    succ_ge' (Sn, c).\n\n  (*\n  Example succ_ge_test1: forall n:nat, n = n.\n  Proof.\n    intro n.\n    first [succ_ge (S n) 0| pose \"t\"].\n    first [succ_ge n 0| pose \"t\"].\n    first [succ_ge (S n) (S 0)| pose \"t\"].\n    first [succ_ge (S (S n)) (S 0)| pose \"t\"].\n    first [succ_ge (S n) (S (S 0))| pose \"f\"].\n    reflexivity.\n  Qed.\n  *)\n  \n  Ltac succ_lt Sn c :=\n      idtac \"succ_lt\"\n    ; let rec succ_lt' x :=\n          idtac \"x =\" x\n          ; match x with\n              | (  _ ,    O ) => \n                idtac \"1\"\n                ; fail 1\n              | (S ?Sn', S ?c') => \n                idtac \"2\"\n                ; first [succ_lt' (Sn', c')| fail 2]\n              | _ => \n                idtac \"3\"\n            end in\n      succ_lt' (Sn, c).\n\n  (*\n  Example succ_lt_test1: forall n:nat, n = n.\n  Proof.\n    intro n.\n\n    first [succ_lt (S n) 0| pose \"f\"].\n    first [succ_lt (S n) (S 0)| pose \"f\"].\n    first [succ_lt n 0| pose \"f\"].\n    first [succ_lt n (S n)| pose \"t\"].\n    first [succ_lt n (S 0)| pose \"t\"].\n    first [succ_lt (S n) (S (S 0))| pose \"t\"].\n    reflexivity.\n  Qed.\n  *)\n  \n  Ltac succ_le Sn c := succ_lt Sn (S c).\n\n  (*\n  Example succ_le_test1: forall n:nat, n = n.\n  Proof.\n    intro n.\n    first [succ_le (S n) 0| pose \"f\"].\n    first [succ_le n 0| pose \"t\"].\n    first [succ_le n (S 0)| pose \"t\"].\n    first [succ_le (S n) (S (S 0))| pose \"t\"].\n    reflexivity.\n  Qed.\n  *)\n\n  Ltac succ_eq Sn c := succ_le Sn c; succ_ge Sn c.\n\n  (*\n  Example succ_eq_test1: forall n:nat, n = n.\n  Proof.\n    intro n.\n    first [succ_eq (S n) 0| pose \"f\"].\n    first [succ_eq n 0| pose \"t\"].\n    first [succ_eq (S n) (S 0)| pose \"t\"].\n    first [succ_eq (S n) (S (S 0))| pose \"f\"].\n    first [succ_eq (S (S (S (S n)))) (S (S (S (S 0))))| pose \"t\"].\n    first [succ_eq (S (S (S (S n)))) (S (S (S 0)))| pose \"f\"].\n    reflexivity.\n  Qed.\n  *)\n\n\n\n  (** duplicate a hypothesis\n   *)\n\n  Ltac dupH H H':=\n    idtac\n    ; match type of H with\n        | ?X => assert (H':X) by apply H \n      end. \n\n\n  (** Next ltac [eqConj_tac] takes a hypothesis [H] in a form of \n      [H: T1 /\\ T2 /\\ ... /\\ True] and a tactic [tac] and \n      apply [tac] to each of the terms except for the last [True].\n\n      For example if the tactic is \n<<\n      Ltac rewrite_tac X := idtac; rewrite X. \n>>\n      and the hypothesis is \n<<\n      [H: x1 = x2 /\\ x2 = x3 /\\ x3 = x4 /\\ ... /\\ True] and \n>>      \n      Then [eqConj_tac H rewrite_tac.] will apply rewrite to each \n      equality of [H]. \n\n      Note: \n       - Directly using rewrite, instead of rewrite_tac, does \n         not work. \n       - Since [eqConj_tac] clears each term after applying [tac],\n         [tac] itself should not clear the hypothesis.\n   *)\n\n  Ltac eqConj_tac H tac :=\n    let rec eqConj_tac' H := \n        match type of H with \n          | ?T1 /\\ ?T2 => \n            let CH := fresh \"CH_0\" in \n            let CT := fresh \"CT_0\" in \n            destruct H as [CH CT]\n                          ; tac CH\n                          ; clear CH\n                          ; eqConj_tac' CT\n          | _ => clear H\n        end\n    in let H_dup := fresh \"H_dup\" in\n       dupH H H_dup \n       ; eqConj_tac' H_dup.\n\n  Ltac rewrite_tac X := idtac; rewrite X.\n  Ltac rewrite_all_tac X := idtac; rewrite X in *.\n\n  Example EqConj_tac_test2: \n    forall {A: Type} (x1 x2 x3 x4 :A),\n      x1 = x2 /\\ True ->\n      x1 = x2.\n  Proof.\n    intros.\n    eqConj_tac H rewrite_tac.\n    intuition.\n  Qed.\n\n  Example EqConj_tac_test3: \n    forall {A: Type} (x1 x2 x3 x4 :A),\n      x1 = x2 /\\ x2 = x3 /\\ x3 = x4 /\\ True ->\n      x1 = x4.\n  Proof.\n    intros.\n    eqConj_tac H rewrite_tac.\n    intuition.\n  Qed.\n \n\n  \n  (** When we have an equation of tuples as a hypothesis, \n      such as [H: (x1,x2) = (y1,y2)], \n      an inversion on that hypothesis equates the corresponding \n      tuple members. The next tactic [invertTupleRewriteRev] also does that \n      in a controled manner, in particular, trying to replace the \n      the members of right-side tuple with the corresponding \n      members in left-side tuple. \n      \n      The maximum size of tuple is now limited to six. \n\n   *)\n\n  Ltac invertTupleRewriteRev H :=\n    idtac \"invertTupleRewriteRev\"\n    ; match type of H with\n\n        | (?X1, ?X2, ?X3, ?X4, ?X5, ?X6) = (?Y1, ?Y2, ?Y3, ?Y4, ?Y5, ?Y6) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          let Tm3 := fresh \"Tm3\" in\n          let Tm4 := fresh \"Tm4\" in\n          let Tm5 := fresh \"Tm5\" in\n          let Tm6 := fresh \"Tm6\" in\n          assert (X1 = Y1 /\\ X2 = Y2 /\\ X3 = Y3 /\\ X4 = Y4 /\\ X5 = Y5 /\\ X6 = Y6) \n            as [Tm1 [Tm2 [Tm3 [Tm4 [Tm5 Tm6]]]]] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n          ; try rewrite <- Tm1\n          ; try rewrite <- Tm2\n          ; try rewrite <- Tm3\n          ; try rewrite <- Tm4\n          ; try rewrite <- Tm5\n          ; try rewrite <- Tm6\n\n        | (?X1, ?X2, ?X3, ?X4, ?X5) = (?Y1, ?Y2, ?Y3, ?Y4, ?Y5) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          let Tm3 := fresh \"Tm3\" in\n          let Tm4 := fresh \"Tm4\" in\n          let Tm5 := fresh \"Tm5\" in\n          assert (X1 = Y1 /\\ X2 = Y2 /\\ X3 = Y3 /\\ X4 = Y4 /\\ X5 = Y5) \n            as [Tm1 [Tm2 [Tm3 [Tm4 Tm5]]]] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n          ; try rewrite <- Tm1\n          ; try rewrite <- Tm2\n          ; try rewrite <- Tm3\n          ; try rewrite <- Tm4\n          ; try rewrite <- Tm5\n\n        | (?X1, ?X2, ?X3, ?X4) = (?Y1, ?Y2, ?Y3, ?Y4) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          let Tm3 := fresh \"Tm3\" in\n          let Tm4 := fresh \"Tm4\" in\n          assert (X1 = Y1 /\\ X2 = Y2 /\\ X3 = Y3 /\\ X4 = Y4) \n            as [Tm1 [Tm2 [Tm3 Tm4]]] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n          ; try rewrite <- Tm1\n          ; try rewrite <- Tm2\n          ; try rewrite <- Tm3\n          ; try rewrite <- Tm4\n        | (?X1, ?X2, ?X3) = (?Y1, ?Y2, ?Y3) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          let Tm3 := fresh \"Tm3\" in\n          assert (X1 = Y1 /\\ X2 = Y2 /\\ X3 = Y3) \n            as [Tm1 [Tm2 Tm3]] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n          ; try rewrite <- Tm1\n          ; try rewrite <- Tm2\n          ; try rewrite <- Tm3\n                  \n        | (?X1, ?X2) = (?Y1, ?Y2) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          assert (X1 = Y1 /\\ X2 = Y2) \n            as [Tm1 Tm2] by\n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n          ; try rewrite <- Tm1\n          ; try rewrite <- Tm2\n                                                         \n        | ?X = ?Y => idtac (* do nothign *)\n          ; try rewrite <- H                       \n\n        | _ => idtac \"invertTuple: error\"\n    end.\n\n\n\n  Example invertTupleRewriteRev_test6: \n    forall {A: Type} (x1 x2 x3 x4 x5 x6 y1 y2 y3 y4 y5 y6:A),\n      (x1,x2,x3,x4,x5,x6) = (y1,y2,y3,y4,y5,y6) ->\n      x1 = y1 /\\ x2 = y2 /\\ x3 = y3 /\\ x4 = y4\n      /\\ x5 = y5 /\\ x6 = y6.\n  Proof.\n    intros.\n    invertTupleRewriteRev H.\n    intuition.\n  Qed.\n\n  Example invertTupleRewriteRev_test5: \n    forall {A: Type} (x1 x2 x3 x4 x5 y1 y2 y3 y4 y5:A),\n      (x1,x2,x3,x4,x5) = (y1,y2,y3,y4,y5) ->\n      x1 = y1 /\\ x2 = y2 /\\ x3 = y3 /\\ x4 = y4\n      /\\ x5 = y5.\n  Proof.\n    intros.\n    invertTupleRewriteRev H.\n    intuition.\n  Qed.\n\n  Example invertTupleRewriteRev_test4: \n    forall {A: Type} (x1 x2 x3 x4 y1 y2 y3 y4:A),\n      (x1,x2,x3,x4) = (y1,y2,y3,y4) ->\n      x1 = y1 /\\ x2 = y2 /\\ x3 = y3 /\\ x4 = y4.\n  Proof.\n    intros.\n    invertTupleRewriteRev H.\n    intuition.\n  Qed.\n\n  Example invertTupleRewriteRev_test3: \n    forall {A: Type} (x1 x2 x3 y1 y2 y3 :A),\n      (x1,x2,x3) = (y1,y2,y3) ->\n      x1 = y1 /\\ x2 = y2 /\\ x3 = y3.\n  Proof.\n    intros.\n    invertTupleRewriteRev H.\n    intuition.\n  Qed.\n\n  Example invertTupleRewriteRev_test2: \n    forall {A: Type} (x1 x2 y1 y2 :A),\n      (x1,x2) = (y1,y2) ->\n      x1 = y1 /\\ x2 = y2.\n  Proof.\n    intros.\n    invertTupleRewriteRev H.\n    intuition.\n  Qed.\n\n  Example invertTupleRewriteRev_test1: \n    forall {A: Type} (x1 y1 :A),\n      x1 = y1 ->\n      x1 = y1.\n  Proof.\n    intros.\n    invertTupleRewriteRev H.\n    intuition.\n  Qed.\n\n  (** The next tactic [invertTuple] is similar to \n      [invertTupleRewriteRev] except it just put the equalities into \n      the context. \n   *)\n\n  Ltac invertTuple H :=\n    idtac \"invertTuple\"\n    ; match type of H with\n\n        | (?X1, ?X2, ?X3, ?X4, ?X5, ?X6) = (?Y1, ?Y2, ?Y3, ?Y4, ?Y5, ?Y6) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          let Tm3 := fresh \"Tm3\" in\n          let Tm4 := fresh \"Tm4\" in\n          let Tm5 := fresh \"Tm5\" in\n          let Tm6 := fresh \"Tm6\" in\n          assert (X1 = Y1 /\\ X2 = Y2 /\\ X3 = Y3 /\\ X4 = Y4 /\\ X5 = Y5 /\\ X6 = Y6) \n            as [Tm1 [Tm2 [Tm3 [Tm4 [Tm5 Tm6]]]]] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n        | (?X1, ?X2, ?X3, ?X4, ?X5) = (?Y1, ?Y2, ?Y3, ?Y4, ?Y5) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          let Tm3 := fresh \"Tm3\" in\n          let Tm4 := fresh \"Tm4\" in\n          let Tm5 := fresh \"Tm5\" in\n          assert (X1 = Y1 /\\ X2 = Y2 /\\ X3 = Y3 /\\ X4 = Y4 /\\ X5 = Y5) \n            as [Tm1 [Tm2 [Tm3 [Tm4 Tm5]]]] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n\n        | (?X1, ?X2, ?X3, ?X4) = (?Y1, ?Y2, ?Y3, ?Y4) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          let Tm3 := fresh \"Tm3\" in\n          let Tm4 := fresh \"Tm4\" in\n          assert (X1 = Y1 /\\ X2 = Y2 /\\ X3 = Y3 /\\ X4 = Y4) \n            as [Tm1 [Tm2 [Tm3 Tm4]]] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n\n        | (?X1, ?X2, ?X3) = (?Y1, ?Y2, ?Y3) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          let Tm3 := fresh \"Tm3\" in\n          assert (X1 = Y1 /\\ X2 = Y2 /\\ X3 = Y3) \n            as [Tm1 [Tm2 Tm3]] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n                  \n        | (?X1, ?X2) = (?Y1, ?Y2) => \n          let Tm1 := fresh \"Tm1\" in\n          let Tm2 := fresh \"Tm2\" in\n          assert (X1 = Y1 /\\ X2 = Y2) \n            as [Tm1 Tm2] by \n                (inversion H\n                 ; try subst\n                 ; intuition\n                )\n                                                         \n        | ?X = ?Y => idtac (* do nothign *)\n\n        | _ => idtac \"invertTuple: error\"\n    end.\n\n  Example invertTuple_test6: \n    forall {A: Type} (x1 x2 x3 x4 x5 x6 y1 y2 y3 y4 y5 y6:A),\n      (x1,x2,x3,x4,x5,x6) = (y1,y2,y3,y4,y5,y6) ->\n      x1 = y1 /\\ x2 = y2 /\\ x3 = y3 /\\ x4 = y4\n      /\\ x5 = y5 /\\ x6 = y6.\n  Proof.\n    intros.\n    invertTuple H.\n    intuition.\n  Qed.\n\n  Example invertTuple_test5: \n    forall {A: Type} (x1 x2 x3 x4 x5 y1 y2 y3 y4 y5:A),\n      (x1,x2,x3,x4,x5) = (y1,y2,y3,y4,y5) ->\n      x1 = y1 /\\ x2 = y2 /\\ x3 = y3 /\\ x4 = y4\n      /\\ x5 = y5.\n  Proof.\n    intros.\n    invertTuple H.\n    intuition.\n  Qed.\n\n\n  Example invertTuple_test3: \n    forall {A: Type} (x1 x2 x3 y1 y2 y3 :A),\n      (x1,x2,x3) = (y1,y2,y3) ->\n      x1 = y1 /\\ x2 = y2 /\\ x3 = y3.\n  Proof.\n    intros.\n    invertTuple H.\n    intuition.\n  Qed.\n\n  Example invertTuple_test2: \n    forall {A: Type} (x1 x2 y1 y2 :A),\n      (x1,x2) = (y1,y2) ->\n      x1 = y1 /\\ x2 = y2.\n  Proof.\n    intros.\n    invertTuple H.\n    intuition.\n  Qed.\n\n  Example invertTuple_test1: \n    forall {A: Type} (x1 y1 :A),\n      x1 = y1 ->\n      x1 = y1.\n  Proof.\n    intros.\n    invertTuple H.\n    intuition.\n  Qed.\n\n\n  (** [destN] stands for [destruct n]. If the parameter [n]\n      is a constant, then this recursion reaches [O] and execute \n      [idtac], that means get out of the first \n\n      e.g.\n      S (S (S n)) ==> S (S n) ==> S n ==> n ==> destruct n\n\n   *)\n\n  Ltac dest_N n :=\n    let rec dest_N' n :=\n        match n with\n          | O => fail 1\n          | S ?n' => first [dest_N' n'| fail 2]\n          | _ => destruct n; idtac\n        end in\n    dest_N' n.\n\n\n  Unset Ltac Debug.\n\n  Ltac clear_context_tac :=\n    idtac;\n    repeat match goal with \n             | [H: ?X|- _ ] => idtac H; clear H\n           end.\n  \n  Ltac revert_all_tac :=\n    idtac; \n    repeat match goal with \n             | [H: ?X |- _] => revert H\n           end. \n\n  Ltac revert_all_except_tac \n       T :=\n    idtac; \n    repeat match goal with \n             | [H: ?X |- _] => \n               match type of T with \n                 | X => idtac\n                 | _ => revert H\n               end\n           end. \n\n  \n\n  Ltac clear_context_except_tac \n       T :=\n    idtac;\n    repeat match goal with \n             | [H: ?X|- _ ] => \n               match type of T with\n                 | X => idtac\n                 | _ => clear H\n               end\n           end.\n\n  Ltac clear_context_except2_tac \n       T1 T2 :=\n    idtac;\n    repeat match goal with \n             | [H: ?X|- _ ] => \n               match type of T1 with\n                 | X => idtac\n                 | _ => \n                   match type of T2 with\n                     | X => idtac \n                     | _ => clear H\n                   end\n               end\n           end.\n\n\n  Ltac introN n :=\n    idtac; \n    match n with\n      | O => idtac\n      | S ?n' => intro; introN n'\n    end.\n\n\n\n\n\n  Ltac tac_le := fun a b => \n                   assert (leb a b = true); unfold leb;\n                   match goal with \n                     | [|- true = true ] => idtac \n                     | [|- false = true ] => fail 1\n                     | [H: leb a b = true |- _] => idtac\n                     | _ => fail 1\n                   end.\n\n  (*\n  (** [succ_X_auto_tac x] is [succ_X_tac x n] that detects [n] from the form [x > n] in \n     the context. \n   *)\n\n  Ltac succ_X_auto_tac x :=\n      repeat match goal with\n             | [NS: ?j > ?basecase_const |- _] => \n                 idtac \"succ_X_tac: 1st branch, j =\" j;\n                 (tac_le j basecase_const; \n                 absurd (j > basecase_const); auto with arith;\n                 idtac \"after inversion\")\n              | [NS: ?Sn > ?basecase_const |- _] => \n                 idtac \"succ_X_tac: 2nd branch, Sn =\" Sn;\n                (match_succ_N_tac Sn x;\n                 first [succ_enough Sn basecase_const | dest_N Sn ]; \n                 idtac \"Sn was not enoguh, so destructed again the boddom n of Sn\")\n\n           end.\n\n  Lemma n_gt_n__False: forall n,\n    n > n -> False.\n  Proof.\n    intros n H.\n    omega.\n  Qed.\n  \n  Example succ_X_auto_tac_test: \n    forall n, n > 1 -> n > 0. \n  intros. succ_X_auto_tac n;\n            inversion H; auto.\n  auto with arith.\n  Qed.\n\n\n  Ltac succ_auto_all_rev_tac:= \n    idtac; \n    repeat match goal with \n      | [H: ?v > ?c |- _] =>\n        assert (c < v) by auto with arith; \n          succ_X_auto_tac v;\n          clear H\n    end.\n\n  Ltac flip_lt_tac:= \n    idtac; \n    repeat match goal with \n             | [H: ?v < ?c |- _] =>\n               assert (c > v) by auto with arith; \n                 clear H\n           end.\n\n  Ltac succ_auto_all_tac:=\n    idtac; \n    succ_auto_all_rev_tac; flip_lt_tac.\n\n\n  Example succ_auto_all_tac_test1:\n    forall n1 n2, n1 > 1 -> n2 > 2 -> (n1 + n2) > 3.\n    intros.\n    succ_auto_all_tac.\n    omega.\n  Qed.\n  *)\n\n  (** Next function [disjnF] is to make disjunctions \n<<\n   n = 0 \\/ n = 1 \\/ n = 2 \\/ ... \\/ n = (bn - 1) \\/ n > (bn - 1)\n>>\n   *)\n\n  Definition disjnF (bn n:nat) :=\n    match bn with \n      | O => True\n      | S bn' => \n        let fix f c :=\n            match c with \n              | O => n = O\n              | S c' => (f c' \\/ n = c) \n            end\n        in (f bn' \\/ n > bn')\n    end.\n\n\n  (** This tactic [disj_N_tac] force case analysis over \n     [bn] base cases and one inductive case of [n].       \n   *)\n\n  Ltac disj_N_tac bn n:=\n    let N := fresh \"N\" in\n    assert (N: disjnF bn n) by (unfold disjnF; omega); unfold disjnF in N;\n    repeat match goal with \n             | [N : _ \\/ _ |- _] => destruct N as [N|N]\n           end.\n\n\n  Ltac succ_N_tac basecase_const :=\n      repeat match goal with\n             | [NS: ?j > basecase_const |- _] => \n                (tac_le j basecase_const; \n                 absurd (j > basecase_const); auto with arith; \n                 idtac \"after inversion\")\n              | [NS: ?Sn > basecase_const |- _] => \n                idtac; \n                (first [succ_enough Sn basecase_const | dest_N Sn ]; \n                 idtac \"Sn was not enoguh, so destructed again the boddom n of Sn\")\n\n           end.\n\n\n  Ltac pred_nat n :=\n    match n with \n      | O => O \n      | S ?n' => n'\n    end.\n\n\n  (* [] *)\n\n\n  (*\n  (** [succ_X_tac x n] destructs [x] in the context [n] + 1 times assuming that\n      [S x <= n] is absurd. This is a modification of [succ_N_tac] so that we can\n      specify the variable to work on. This is needed when we have two or\n      more variables that has the form [x > c] for some constant [basecase_const]\n      [c].  \n   *)\n\n  Ltac succ_X_tac x basecase_const :=\n      repeat match goal with\n             | [NS: ?j > basecase_const |- _] => \n                 idtac \"succ_X_tac: 1st branch, j =\" j;\n                 (tac_le j basecase_const; \n                 absurd (j > basecase_const); auto with arith;\n                 idtac \"after inversion\")\n              | [NS: ?Sn > basecase_const |- _] => \n                 idtac \"succ_X_tac: 2nd branch, Sn =\" Sn;\n                (match_succ_N_tac Sn x;\n                 first [succ_enough Sn basecase_const | dest_N Sn ]; \n                 idtac \"Sn was not enoguh, so destructed again the boddom n of Sn\")\n\n           end.\n\n\n  Ltac succ_auto_tac :=\n      repeat match goal with\n             | [NS: ?j > ?basecase_const |- _] => \n                 idtac \"succ_auto_tac: 1st branch, j =\" j;\n                 (tac_le j basecase_const; \n                 absurd (j > basecase_const); auto with arith;\n                 idtac \"after inversion\")\n              | [NS: ?Sn > ?basecase_const |- _] => \n                 idtac \"succ_auto_tac: 2nd branch, Sn =\" Sn;\n                (\n                 first [succ_enough Sn basecase_const | dest_N Sn ]; \n                 idtac \"Sn was not enoguh, so destructed again the boddom n of Sn\")\n           end.\n  Unset Ltac Debug.\n\n\n  Example succ_auto_tac_test: \n    forall n, n > 1 -> n > 0. \n    intros. succ_auto_tac. omega.\n  Qed.\n\n  *)", "meta": {"author": "yoy553", "repo": "fold-ud", "sha": "806c4481694002471eb62ed3fd2accd96ad717ae", "save_path": "github-repos/coq/yoy553-fold-ud", "path": "github-repos/coq/yoy553-fold-ud/fold-ud-806c4481694002471eb62ed3fd2accd96ad717ae/dual/MyLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7288155971890135}}
{"text": "Require Import List.\n\nNotation \"[]\"    := nil.\nNotation \"[ z ]\" := (cons z []) (z at level 200).\n\n(* Total order *)\n\nDefinition antisymmetric (A : Set) (rel : A -> A -> bool) :=\n  forall (x y : A),\n  (rel x y = true /\\ rel y x = true) -> x = y.\n\nDefinition transitive (A : Set) (rel : A -> A -> bool) :=\n  forall (x y z : A),\n  (rel x y = true /\\ rel y z = true) -> rel x z = true.\n\nDefinition connex (A : Set) (rel : A -> A -> bool) :=\n  forall (x y : A), rel x y = true \\/ rel y x = true.\n\nDefinition total_order (A : Set) : Set := {\n  cmp : A -> A -> bool |\n  antisymmetric A cmp /\\ transitive A cmp /\\ connex A cmp\n}.\n\n(* Permutations by transpositions *)\n\nInductive perm (a : Set)\n             : list a -> list a -> Prop :=\n  perm_nil   : perm a [] []\n| perm_cons  : forall (x : a) (s t : list a),\n               perm a s t -> perm a (x::s) (x::t)\n| perm_swap  : forall (x y : a) (s : list a),\n               perm a (x::y::s) (y::x::s)\n| perm_trans : forall (s t u : list a),\n               perm a s t -> perm a t u -> perm a s u.\n\nNotation \"s ~~ t\" := (perm _ s t) (at level 70, no associativity).\n\nTheorem perm_refl :\n  forall (a : Set) (s : list a), s ~~ s.\nProof.\nintros.\ninduction s as [| x s].\n  - apply perm_nil.\n  - apply perm_cons.\n    apply IHs.\nDefined.\n\nTheorem perm_symm : \n  forall (a : Set) (s t : list a), s ~~ t -> t ~~ s.\nProof.\nintros.\ninduction H.\n  - apply perm_nil.\n  - apply perm_cons.\n    apply IHperm.\n  - apply perm_swap.\n  - apply (perm_trans a u t s).\n    * apply IHperm2.\n    * apply IHperm1.\nDefined.\n\n(* Totally ordered lists *)\n\nInductive ord_list (a : Set) (cmp : total_order a)\n                 : list a -> Prop :=\n  ord_nil  : ord_list a cmp []\n| ord_one  : forall x : a, ord_list a cmp [x]\n| ord_more : forall (x y : a) (s : list a),\n                proj1_sig cmp x y = true  (* x <= y in mind *)\n             -> ord_list a cmp (y::s)\n             -> ord_list a cmp (x::y::s).\n\n(* Merging two sorted lists *)\n\nFixpoint merge (A : Set) (cmp : total_order A)\n               (s t : list A) : list A :=\n  let fix merge' t :=\n    match s, t with\n      [], _ => t\n    | _, [] => s\n    | x::s', y::t' =>\n        if proj1_sig cmp x y\n        then x :: merge A cmp s' t\n        else y :: merge' t'\n    end\n  in merge' t.\n\n(* Stable online bottom-up merge sort *)\n\nInductive bit (A : Set) : Set :=\n  Zero : bit A\n| One  : list A -> bit A.\n\nFixpoint unb (A : Set) (cmp : total_order A)\n             (s : list (bit A)) (u : list A) :=\n  match s with\n               [] => u\n  | Zero _  :: s' => unb A cmp s' u\n  | One _ t :: s' => unb A cmp s' (merge A cmp t u)\n  end.\n\nFixpoint add (A : Set) (cmp : total_order A)\n             (s : list A) (t : list (bit A)) :=\n  match t with\n               [] => [One A s]\n  | Zero _  :: t' => One A s :: t'\n  | One _ u :: t' => Zero A :: add A cmp (merge A cmp s u) t'\n  end.\n\nFixpoint sum (A : Set) (cmp : total_order A) \n             (s : list A) (t : list (bit A)) :=\n  match s with\n       [] => t\n  | x::s' => sum A cmp s' (add A cmp [x] t)\n  end.\n\nDefinition oms (A : Set) (cmp : total_order A) (s : list A) :=\n  unb A cmp (sum A cmp s []) [].\n\n(* Merge sort is indeed a sorting algorithm *)\n\nTheorem is_sorted :\n  forall (a : Set) (cmp: total_order a) (s : list a),\n  ord_list a cmp (oms a cmp s) /\\ perm a (oms a cmp s) s.\n\n(*\n(* Stable bottom-up merge sort *)\n\nFixpoint next (A : Set) (cmp : total_order A)\n              (u : list (list A)) : list (list A) :=\n  match u with\n    s::t::u' => merge A cmp s t :: next A cmp u'\n  |        _ => u\n  end.\n\n(* Require Import Omega. *)\nSearch (forall x y, S x < S y -> x < y).\nSearch (forall x y, x < y -> S x < S y).\n\nLemma next_level :\n  forall (A : Set) (cmp : total_order A)\n         (u s : list (list A)) (a b : list A),\n  a::b::s = u -> length (next A cmp u) < length u.\nProof.\nintros.\ninduction u.\n  - discriminate H.\n  - unfold next.\n    fold next.\n    case_eq u.\n      * intro uempty.\n        rewrite uempty in H. (* contradiction.? *)\n        inversion H.\n      * intros.\n        simpl.\n        apply Lt.lt_n_S.\n        apply IHu.\n        \n\nFixpoint solo (A : Set) (cmp : total_order A)\n              (s : list A) : list (list A) :=\n  match s with\n       [] => []\n  | x::s' => [x] :: solo A cmp s'\n  end.\n\nFixpoint all (A : Set) (cmp : total_order A)\n             (s : list (list A)) : list A :=\n  match s with\n    [s'] => s'\n  |    _ => all A cmp (next A cmp s)\n  end.\n*)\n\n(*\n(* Unstable top-down merge sort *)\n\nFixpoint cut (A : Set) (s t u : list A) :=\n  match t, u with\n    y::t', _::_::u' => cut A (y::s) t' u'\n  | _, _            => (s, t)\n  end.\n\nPrint cut.\n\nDefinition split (A : Set) (s : list A) :=\n  cut A [] s s.\n\nRequire Import FunInd Arith Recdef Wf_nat.\n\nFunction tms (A : Set) (cmp : total_order A)\n         (s : list A) {measure length s} : list A :=\n  match s with\n    [] | [_] => s\n  | _  =>\n      let (rpre, suff) := split A s\n      in merge A cmp (tms A cmp rpre) (tms A cmp suff)\n  end.\nProof.\n  - intros.\n\n    unfold split in teq1.\n (*   rewrite <- teq in *.\n    rewrite <- teq0 in *.\n*)    unfold cut in teq1.\n    simpl.\n\n    rewrite <- teq in *.\n    rewrite <- teq0 in *.\n\n      -\n\n    induction l0.\n    rewrite <- teq in *.\n    rewrite <- teq0 in *.\n*)\n*)\n\n(*Fixpoint rev_append (A : Set) (s t : list A) :=\n  match s with\n       [] => t\n  | x::s' => rev_append A s' (x::t)\n  end.\n\nLemma split_undone :\n  forall (A : Set) (s : list A),\n  let (rpre, suff) := split A s\n  in rev_append A rpre suff = s.\nAdmitted. (* TODO *)\n\nLemma rpre_suff :\n  forall (A : Set) (s t u : list A),\n  rev_append A s t = u -> length s + length t = length u.\nAdmitted. (* TODO *)\n*)\n\n(*\nDefinition pair_order (a b : Set)\n  (ord_a : total_order a) (ord_b : total_order b) :=\n    forall (p1 p2 : a * b), (* p1 <= p2 in mind *)\n       proj1_sig ord_a (fst p1) (fst p2) = true\n    \\/ proj1_sig ord_b (snd p1) (snd p2) = true.\n\n(*\nLemma pair_order_is_total :\n  forall (a b : Set) (ord_a : total_order a) (ord_b : total_order b),\n   pair_order a b ord_a ord_b -> total_order (a*b). (* Wrong. *)\nProof.\nintros.\n*)\n\n(* Partial order *)\n\nLemma partial_order : forall (a : Set) (cmp : total_order a) (x y : a),\n  proj1_sig cmp x y = false -> proj1_sig cmp y x = true /\\ x <> y.\nProof.\n  destruct cmp as (rel, (antisym, (trans, conn))).\n  simpl.\n  intros.\n  case (conn x y).\n  - rewrite H. intro. discriminate. (* or \"congruence\" *)\n  - intro Hyx.\n    split.\n    + assumption.\n    + intro Heq. (* x <> y is x = y -> False *)\n      rewrite Heq in *.\n      rewrite H in Hyx.\n      discriminate.\nQed.\n*)\n", "meta": {"author": "rinderknecht", "repo": "Coq", "sha": "8c25f60c8aad69f7c7ff0c9b3289f1824cf65543", "save_path": "github-repos/coq/rinderknecht-Coq", "path": "github-repos/coq/rinderknecht-Coq/Coq-8c25f60c8aad69f7c7ff0c9b3289f1824cf65543/merge_sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7288155949187609}}
{"text": "Require Export Complex. \n\n\n(******************************)\n(* Defining polar coordinates *)\n(******************************)\n\nDefinition get_arg (p : C) : R :=\n  match Rcase_abs (snd p) with\n  | left _ => 2 * PI - acos (fst p / Cmod p)\n  | right _ => acos (fst p / Cmod p)\n  end.\n\nDefinition rect_to_polar (z : C) : R * R :=\n  (Cmod z, get_arg z).\n\nDefinition polar_to_rect (p : R * R) : C := \n  fst p * (Cexp (snd p)).\n\n\nDefinition WF_polar (p : R * R) : Prop :=\n  0 < fst p /\\ 0 <= snd p < 2 * PI.\n\nDefinition polar_mult (p1 p2 : R * R) : R * R :=\n  match Rcase_abs (snd p1 + snd p2 - 2 * PI) with\n  | left _ => (fst p1 * fst p2, snd p1 + snd p2)%R\n  | right _ => (fst p1 * fst p2, snd p1 + snd p2 - 2 * PI)%R\n  end.\n\nFixpoint polar_pow (p : R * R) (n : nat) : R * R :=\n  match n with \n  | O => (1, 0)%R\n  | S n' => polar_mult p (polar_pow p n')\n  end.\n\n\n \n\n(* prelim sin and cos lemmas *)\n\n\nLemma cos_2PI_minus_x : forall (x : R), cos (2 * PI - x) = cos x.\nProof. intros. \n       rewrite cos_minus, cos_2PI, sin_2PI; lra.\nQed.\n\nLemma sin_2PI_minus_x : forall (x : R), sin (2 * PI - x) = (- sin x)%R.\nProof. intros. \n       rewrite sin_minus, cos_2PI, sin_2PI; lra.\nQed.\n\nLemma fst_div_Cmod : forall (x y : R),\n  (x, y) <> C0 ->\n  -1 <= x / Cmod (x, y) <= 1.\nProof. intros. \n       assert (H0 := Rmax_Cmod (x, y)).\n       apply (Rle_trans (Rabs (fst (x, y)))) in H0; try apply Rmax_l; simpl in *.\n       apply (Rmult_le_compat_r (/ Cmod (x, y))) in H0.\n       rewrite Rinv_r, <- (Rabs_pos_eq (Cmod _)), <- Rabs_Rinv, <- Rabs_mult in H0.\n       all : try (left; apply Rinv_0_lt_compat); try apply Cmod_ge_0; try apply Cmod_gt_0.\n       all : try (unfold not; intros; apply H; apply Cmod_eq_0; easy).\n       destruct H0.\n       - apply Rabs_def2 in H0; lra.\n       - unfold Rabs in H0; destruct (Rcase_abs (x * / Cmod (x, y))).\n         assert (H' : (x * / Cmod (x, y))%R = (-1)%R). lra.\n         unfold Rdiv; rewrite H'; lra.\n         unfold Rdiv; rewrite H0; lra.\nQed.\n\nLemma fst_div_Cmod_lt : forall (x y : R),\n  (y <> 0)%R ->\n  -1 < x / Cmod (x, y) < 1.\nProof. intros. \n       assert (H' : (x, y) <> C0).\n       { unfold not; intros; apply H.\n         apply (f_equal_gen snd snd) in H0; simpl in *; easy. }\n       assert (H0 := Rmax_Cmod (x, y)).\n       apply (Rle_trans (Rabs (fst (x, y)))) in H0; try apply Rmax_l; simpl in *.\n       destruct H0.\n       - apply (Rmult_lt_compat_r (/ Cmod (x, y))) in H0.\n         rewrite Rinv_r, <- (Rabs_pos_eq (Cmod _)), <- Rabs_Rinv, <- Rabs_mult in H0.\n         all : try (apply Rinv_0_lt_compat; apply Cmod_gt_0).\n         all : try apply Cmod_ge_0.\n         all : try (unfold not; intros; apply H'; apply Cmod_eq_0; easy).\n         apply Rabs_def2 in H0; unfold Rdiv; easy.\n       - unfold Cmod in H0; simpl fst in H0; simpl snd in H0.\n         assert (H1 : ((Rabs x) * (Rabs x))%R = ((√ (x ^ 2 + y ^ 2)) * (√ (x ^ 2 + y ^ 2)))%R).\n         { rewrite H0; easy. }\n         rewrite sqrt_def, <- Rabs_mult, Rabs_right in H1.\n         apply (f_equal_gen (Rminus (x ^ 2)) (Rminus (x ^ 2))) in H1; auto.\n         replace (x ^ 2 - x * x)%R with 0%R in H1 by lra.\n         replace (x ^ 2 - (x ^ 2 + y ^ 2))%R with (y ^ 2)%R in H1 by lra. \n         apply (Cpow_nonzero_real _ 2) in H. \n         assert (H'' : False). apply H; rewrite H1; lca.\n         easy. \n         replace (x * x)%R with (x ^ 2)%R by lra. \n         assert (H'' := pow2_ge_0 x). lra.\n         apply Rplus_le_le_0_compat; apply pow2_ge_0.\nQed.\n\n(* some lemmas about these defs *)\n\nLemma get_arg_ver : forall (r θ : R),\n  0 < r -> 0 <= θ < 2 * PI ->\n  get_arg (r * Cexp θ) = θ.\nProof. intros. \n       unfold get_arg; simpl.\n       do 2 rewrite Rmult_0_l; unfold Rminus. \n       rewrite Ropp_0, Rplus_0_r, Rplus_0_r, Cmod_mult, \n         Cmod_Cexp, Rmult_1_r, Cmod_R, Rabs_right; try lra. \n       replace (r * cos θ / r)%R with (cos θ)%R.\n       2 : unfold Rdiv; rewrite Rmult_comm, <- Rmult_assoc, Rinv_l; try lra.\n       destruct (Rle_lt_dec θ PI).\n       - assert (H' : 0 <= r * sin θ).\n         { apply Rmult_le_pos; try lra.\n           apply sin_ge_0; lra. }\n         destruct (Rcase_abs (r * sin θ)); try lra.\n         apply acos_cos; easy.\n       - assert (H' : r * sin θ < 0).\n         { rewrite <- (Rmult_0_r r).\n           apply Rmult_lt_compat_l; try lra.\n           apply sin_lt_0; easy. }\n         destruct (Rcase_abs (r * sin θ)); try lra.\n         rewrite <- cos_2PI_minus_x.\n         rewrite acos_cos; lra.\nQed.\n\nLemma get_arg_bound : forall (z : C),\n  0 <= get_arg z < 2 * PI. \nProof. intros.\n       unfold get_arg.\n       case (Rcase_abs (snd z)); intros.\n       - destruct z as [x y]; simpl in *.\n         assert (H' : y <> 0). lra. \n         apply (fst_div_Cmod_lt x y) in H'.\n         apply acos_bound_lt in H'.\n         lra.\n       - assert (H' := acos_bound (fst z / Cmod z)).\n         assert (H0 : PI < 2 * PI).\n         { replace PI with (1 * PI)%R by lra. \n           rewrite <- Rmult_assoc, Rmult_1_r.\n           apply Rmult_lt_compat_r; try lra.\n           apply PI_RGT_0. }\n         lra. \nQed.         \n\nLemma polar_to_rect_to_polar : forall (p : R * R),\n  WF_polar p ->\n  rect_to_polar (polar_to_rect p) = p.\nProof. intros.       \n       unfold polar_to_rect, rect_to_polar; destruct p; simpl.\n       destruct H; simpl in *.\n       rewrite Cmod_mult, Cmod_Cexp, Cmod_R, Rabs_right, get_arg_ver, Rmult_1_r; \n         try lra; easy.  \nQed.\n\nLemma div_subtract_helper : forall (x y : R),\n  (x, y) <> C0 ->\n  (1 - (x / Cmod (x, y))²)%R = (y² * / (Cmod (x, y))²)%R.\nProof. intros.  \n       unfold Rdiv.\n       rewrite Rsqr_mult.\n       rewrite Rsqr_inv.\n       rewrite <- (Rinv_r ((Cmod (x, y))²)).\n       replace (((Cmod (x, y))² * / (Cmod (x, y))² + - (x² * / (Cmod (x, y))²))%R) with\n         ( ((Cmod (x, y))² - x²) * / ((Cmod (x, y))²))%R by lra.\n       replace ((Cmod (x, y))²) with (x² + y²)%R; try lra. \n       unfold Cmod; simpl fst; simpl snd. \n       rewrite Rsqr_sqrt; try lra. \n       unfold Rsqr; lra.\n       apply Rplus_le_le_0_compat; apply pow2_ge_0.\n       all : unfold not; intros; apply H.\n       unfold Rsqr in H0.\n       apply Rmult_integral in H0; apply Cmod_eq_0. \n       destruct H0; easy.\n       apply Cmod_eq_0; easy.\nQed.\n\nLemma rect_to_polar_to_rect : forall (z : C),\n  z <> C0 ->\n  polar_to_rect (rect_to_polar z) = z.\nProof. intros.       \n       unfold polar_to_rect, rect_to_polar; destruct z as [x y]; simpl.\n       unfold get_arg, Cexp. \n       case (Rcase_abs (snd (x, y))); intros; simpl in *.\n       - rewrite cos_2PI_minus_x, sin_2PI_minus_x, cos_acos, sin_acos; \n           try apply fst_div_Cmod; auto.\n         unfold Cmult; simpl.\n         do 2 rewrite Rmult_0_l.\n         rewrite div_subtract_helper; auto.\n         unfold Rminus.\n         rewrite Ropp_0, Rplus_0_r, Rplus_0_r.\n         rewrite sqrt_mult, sqrt_inv, sqrt_Rsqr_abs, sqrt_Rsqr_abs, \n           (Rabs_left y), Rabs_right; auto.\n         replace (- (- y * / Cmod (x, y)))%R with (y * / Cmod (x, y))%R by lra.\n         unfold Rdiv.\n         apply injective_projections; simpl.\n         all : try (left; apply Rinv_0_lt_compat).\n         all : try apply Rsqr_pos_lt.\n         all : try (rewrite Rmult_comm, Rmult_assoc, Rinv_l; try lra).\n         all : try (unfold not; intros; apply H; apply Cmod_eq_0; easy). \n         assert (H' := Cmod_ge_0 (x, y)); lra.\n         apply Rle_0_sqr.\n       - rewrite cos_acos, sin_acos; \n           try apply fst_div_Cmod; auto.\n         rewrite div_subtract_helper; auto.\n         rewrite sqrt_mult, sqrt_inv, sqrt_Rsqr_abs, sqrt_Rsqr_abs, \n           (Rabs_right y), Rabs_right; auto.\n         unfold Rdiv, Cmult; simpl. \n         do 2 rewrite Rmult_0_l.\n         unfold Rminus; rewrite Ropp_0, Rplus_0_r, Rplus_0_r.\n         apply injective_projections; simpl.\n         all : try (left; apply Rinv_0_lt_compat).\n         all : try apply Rsqr_pos_lt.\n         all : try (rewrite Rmult_comm, Rmult_assoc, Rinv_l; try lra).\n         all : try (unfold not; intros; apply H; apply Cmod_eq_0; easy). \n         assert (H' := Cmod_ge_0 (x, y)); lra.\n         apply Rle_0_sqr.\nQed.\n\nLemma WF_rect_to_polar : forall (z : C),\n  z <> C0 -> WF_polar (rect_to_polar z).\nProof. intros. \n       unfold WF_polar, rect_to_polar; split; simpl.\n       apply Cmod_gt_0; easy.\n       apply get_arg_bound.\nQed.\n\nLemma WF_polar_mult : forall (p1 p2 : R * R),\n  WF_polar p1 -> WF_polar p2 ->\n  WF_polar (polar_mult p1 p2).\nProof. intros. \n       destruct H; destruct H0.\n       unfold polar_mult; split.\n       - destruct (Rcase_abs (snd p1 + snd p2 - 2 * PI)); simpl.\n         all : apply Rmult_lt_0_compat; easy.\n       - destruct (Rcase_abs (snd p1 + snd p2 - 2 * PI)); simpl.\n         all : lra. \nQed.         \n\nLemma WF_polar_pow : forall (p : R * R) (n : nat),\n  WF_polar p ->\n  WF_polar (polar_pow p n).\nProof. induction n as [| n']; intros. \n       - unfold WF_polar, polar_pow; simpl; split; try lra.\n         split; try lra. \n         apply Rmult_lt_0_compat; try lra.\n         apply PI_RGT_0.\n       - simpl. \n         apply WF_polar_mult; try apply IHn'; easy.\nQed.\n\nLemma polar_to_rect_mult_compat : forall (p1 p2 : R * R),\n  WF_polar p1 -> WF_polar p2 ->   \n  polar_to_rect (polar_mult p1 p2) = (polar_to_rect p1) * (polar_to_rect p2).\nProof. intros. \n       unfold polar_to_rect, polar_mult, Cmult.\n       destruct p1 as [x1 y1]; destruct p2 as [x2 y2]; simpl. \n       destruct (Rcase_abs (y1 + y2 - 2 * PI)); simpl. \n       - rewrite cos_plus, sin_plus.\n         apply injective_projections; simpl; lra.\n       - rewrite cos_minus, sin_minus, cos_2PI, sin_2PI, cos_plus, sin_plus. \n         apply injective_projections; simpl; lra.\nQed.\n\nLemma rect_to_polar_mult_compat : forall (z1 z2 : C),\n  z1 <> C0 -> z2 <> C0 -> \n  rect_to_polar (z1 * z2) = polar_mult (rect_to_polar z1) (rect_to_polar z2).\nProof. intros. \n       rewrite <- polar_to_rect_to_polar, polar_to_rect_mult_compat.\n       rewrite rect_to_polar_to_rect, rect_to_polar_to_rect; auto.\n       3 : apply WF_polar_mult.\n       all : apply WF_rect_to_polar; auto.\nQed.\n\nLemma polar_to_rect_pow_compat : forall (p : R * R) (n : nat),\n  WF_polar p ->   \n  polar_to_rect (polar_pow p n) = (polar_to_rect p) ^ n.\nProof. induction n as [| n']; intros. \n       - unfold polar_to_rect; simpl. \n         rewrite Cexp_0; lca.\n       - simpl. \n         rewrite polar_to_rect_mult_compat, IHn'; auto.\n         apply WF_polar_pow; easy. \nQed.\n\nLemma rect_to_polar_pow_compat : forall (z : C) (n : nat),\n  z <> C0 ->\n  rect_to_polar (z ^ n) = polar_pow (rect_to_polar z) n.\nProof. intros.\n       rewrite <- polar_to_rect_to_polar, polar_to_rect_pow_compat.\n       rewrite rect_to_polar_to_rect; easy.\n       2 : apply WF_polar_pow.\n       all : apply WF_rect_to_polar; auto.\nQed.       \n\n(******************)\n(* nth roots in C *)\n(******************)\n\n(* first we need to establish nth roots in R *)\n\nDefinition pow_n (n : nat) : R -> R :=\n  fun r => (r ^ n)%R.\n\nLemma pow_n_reduce : forall (n : nat),\n  mult_fct (pow_n 1) (pow_n n) = pow_n (S n).\nProof. unfold pow_n; intros. \n       apply functional_extensionality; intros. \n       unfold mult_fct; simpl; lra. \nQed.\n\nLemma continuous_const : continuity (pow_n 0).\nProof. unfold continuity, continuity_pt, continue_in, limit1_in, limit_in; intros. \n       exists eps; split; auto; intros. \n       unfold pow_n; simpl in *.\n       rewrite R_dist_eq; lra. \nQed.\n\nLemma continuous_linear : continuity (pow_n 1).\nProof. unfold continuity, continuity_pt, continue_in, limit1_in, limit_in; intros. \n       exists eps; split; auto; intros. \n       unfold pow_n; simpl in *.\n       do 2 rewrite Rmult_1_r; easy. \nQed.\n\nLemma continuous_pow_n : forall (n : nat), continuity (pow_n n).\nProof. induction n as [| n'].\n       - apply continuous_const. \n       - rewrite <- pow_n_reduce.\n         apply continuity_mult.\n         apply continuous_linear.\n         apply IHn'.\nQed.\n\nLemma nth_root_nonnegR : forall (r : R) (n : nat),\n  0 <= r -> (n > 0)%nat ->\n  exists r', 0 <= r' /\\ (r' ^ n = r)%R.\nProof. intros. \n       destruct (Req_dec r 0); subst.\n       exists 0; split; try lra. \n       rewrite pow_i; easy.\n       destruct (Ranalysis5.f_interv_is_interv (pow_n n) 0 (r + 1) r); try lra.\n       unfold pow_n; split; simpl.\n       rewrite pow_i; easy.\n       eapply Rle_trans; try apply (Rle_pow (r + 1) 1 n); try lra; lia.\n       intros. \n       apply continuous_pow_n.\n       exists x; split; try lra.\n       unfold pow_n in a.\n       easy.\nQed.\n\n(* now we show the existance of nth roots in C *)\n\nLemma polar_pow_n : forall (r θ : R) (n : nat),\n  0 < r -> 0 <= θ -> (INR n * θ < 2 * PI)%R ->\n  polar_pow (r, θ) n = (r ^ n, INR n * θ)%R.\nProof. induction n as [| n']; intros.\n       - simpl; rewrite Rmult_0_l; easy.\n       - simpl polar_pow. \n         rewrite IHn'; auto.\n         unfold polar_mult; simpl fst; simpl snd.\n         destruct (Rcase_abs (θ + INR n' * θ - 2 * PI)); try lra. \n         apply injective_projections; simpl; try lra.\n         destruct n'; simpl; try lra.\n         rewrite S_INR in H1; lra.\n         rewrite S_INR in H1; lra.\nQed.\n\nLemma nth_root_polar : forall (r θ : R) (n : nat), \n  (n > 0)%nat -> \n  WF_polar (r, θ) -> \n  exists p, WF_polar p /\\ polar_pow p n = (r, θ).\nProof. intros. \n       destruct H0; simpl in *.\n       destruct (nth_root_nonnegR r n) as [r' [H2 H3] ]; try lra; auto.\n       assert (0 < r').\n       destruct H2; auto; subst.\n       destruct n; try easy; simpl in H0.\n       rewrite Rmult_0_l in H0; lra.\n       exists (r', / (INR n) * θ)%R; split.\n       - split; simpl; auto.\n         split. \n         apply Rmult_le_pos; try easy. \n         left; apply Rinv_0_lt_compat.\n         apply lt_0_INR; auto.\n         assert (/ INR n * θ <= θ). \n         rewrite <- Rmult_1_l.\n         apply Rmult_le_compat_r; try lra.\n         apply (Rmult_le_reg_r (INR n)).\n         apply lt_0_INR; lia.\n         rewrite Rinv_l, Rmult_1_l.\n         replace 1 with (INR 1) by easy.\n         apply le_INR; lia.\n         apply not_0_INR; destruct n; easy.\n         lra. \n       - rewrite polar_pow_n; auto.\n         all : try rewrite <- Rmult_assoc, Rinv_r, Rmult_1_l. \n         rewrite H3; easy.\n         all : try (apply not_0_INR; destruct n; easy).\n         apply Rmult_le_pos; try easy. \n         left; apply Rinv_0_lt_compat.\n         apply lt_0_INR; auto.\n         easy.\nQed.\n\nTheorem nth_root_C : forall (z : C) (n : nat),\n  (n > 0)%nat -> \n  exists z', (Cpow z' n = z)%C.\nProof. intros. \n       destruct (Ceq_dec z C0); subst.\n       exists C0; destruct n; simpl; try easy; lca.\n       destruct (rect_to_polar z) as [r θ] eqn:E.\n       destruct (nth_root_polar r θ n) as [p [H0 H1] ]; auto.\n       rewrite <- E.\n       apply WF_rect_to_polar; auto.\n       exists (polar_to_rect p).\n       rewrite <- polar_to_rect_pow_compat; auto.\n       rewrite H1, <- E, rect_to_polar_to_rect; easy.\nQed.\n\nLemma nonzero_nth_root : forall (c c' : C) (n : nat),\n  (n > 0)%nat -> c' ^ n = c ->\n  c <> C0 -> \n  c' <> C0.\nProof. intros. \n       destruct n; try easy.\n       simpl in H0.\n       unfold not; intros; apply H1; subst.\n       lca.\nQed.\n\n\n(****)\n(*****)\n(***)\n", "meta": {"author": "inQWIRE", "repo": "QuantumLib", "sha": "d97ea40581961d7b53291a4a3dc7885fe7428060", "save_path": "github-repos/coq/inQWIRE-QuantumLib", "path": "github-repos/coq/inQWIRE-QuantumLib/QuantumLib-d97ea40581961d7b53291a4a3dc7885fe7428060/Polar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7288155887455214}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf2 : natural) : natural :=\n  plus z (plus lf2 Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj126_coqofml_zkIczG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7288125406189385}}
{"text": "Require Import ZArith Int.\nOpen Local Scope Z_scope.\n\nInductive Tree : Set :=\n| empty : Tree\n| node : Z -> Tree -> Tree -> Tree.\n\nDefinition left (t : Tree) :=\n  match t with\n  | empty => empty\n  | node x l r => l\n  end.\n\nDefinition right (t : Tree) :=\n  match t with\n  | empty => empty\n  | node x l r => r\n  end.\n\nInductive In (x : Z) : Tree -> Prop :=\n| in_left : forall l r y, In x l -> In x (node y l r)\n| in_right : forall l r y, In x r -> In x (node y l r)\n| in_root : forall l r, In x (node x l r).\n\nDefinition is_empty (t : Tree) : bool :=\n  match t with\n  | empty => true\n  | _ => false\n  end.\n\nLemma is_empty_correct : forall s, (is_empty s) = true <-> forall x, ~ (In x s).\nProof.\nAdmitted.\n\nFixpoint mem (x : Z) (t : Tree) : bool :=\n  match t with\n  | empty => false\n  | node y l r => match Z.compare x y with\n    | Lt => mem x l\n    | Eq => true\n    | Gt => mem x r\n    end\n  end.\n\nFixpoint nat_max (m n : nat) : nat :=\n  match (m,n) with\n  | (O,x) => x\n  | (x,O) => x\n  | (S m',S n') => S (nat_max m' n')\n  end.\n\nFixpoint height (t : Tree) : nat :=\n  match t with\n  | empty => O\n  | node x l r => 1 + nat_max (height l) (height r)\n  end.\n\nFixpoint cardinality (t : Tree) : nat :=\n  match t with\n  | empty => O\n  | node x l r => 1 + cardinality l + cardinality r\n  end.\n\nInductive BSTree : Tree -> Prop :=\n  | bst_empty : BSTree empty\n  | bst_node :\n      forall l x r,\n      BSTree l ->\n      BSTree r ->\n      (forall y, In y l -> y < x) ->\n      (forall y, In y r -> x < y) ->\n      BSTree (node x l r).\n\nLemma bst_left : forall t, BSTree t -> BSTree (left t).\nProof.\n  intros.\n  destruct H.\n  simpl.\n  exact bst_empty.\n  simpl.\n  exact H.\nQed.\n\nLemma bst_right : forall t, BSTree t -> BSTree (right t).\nProof.\n  intros.\n  destruct H.\n    simpl.\n    exact bst_empty.\n    simpl.\n    exact H0.\nQed.\n\nInductive AVLTree : Tree -> Prop :=\n  | avl_empty : AVLTree empty\n  | avl_node :\n      forall l r x,\n      AVLTree l ->\n      AVLTree r ->\n      (forall y, In y l -> y < x) ->\n      (forall y, In y r -> x < y) ->\n      (height l = height r \\/\n       height l = S(height r) \\/\n       S(height l) = height r) ->\n      AVLTree (node x l r).\n\nLemma avl_left : forall t, AVLTree t -> AVLTree (left t).\nProof.\n  intros.\n  destruct H.\n    simpl.\n    exact avl_empty.\n    simpl.\n    exact H.\nQed.\n\nLemma avl_right : forall t, AVLTree t -> AVLTree (right t).\nProof.\n  intros.\n  destruct H.\n    simpl.\n    exact avl_empty.\n    simpl.\n    exact H0.\nQed.\n\nLemma nat_gt_s : forall m n, (m > n)%nat -> (S m > S n)%nat.\nProof.\nAdmitted.\n\nLemma nat_gt_1_is_O : forall m, (1 > m)%nat -> (m = O)%nat.\nProof.\nAdmitted.\n\nLemma nat_add_id : forall m, (m + 0 = m)%nat.\nProof.\nAdmitted.\n\nLemma nat_add_id_exp : forall m n, (m^n + 0 = m^n)%nat.\nProof.\n  intros.\n  induction m.\n    simpl.\n    \n\nLemma nat_add_id_left : forall m, (0 + m = m)%nat.\nProof.\nAdmitted.\n\nLemma nat_gt_trans : forall m n x, (m > x)%nat -> (n > m)%nat -> (n > x)%nat.\nProof.\nAdmitted.\n\nLemma nat_add_mult : forall m, (m + m = 2 * m)%nat.\nProof.\n  intros.\n  induction m.\n    simpl.\n    reflexivity.\n    simpl.\n    rewrite nat_add_id.\n    reflexivity.\nQed.\n\nLemma gt_4_3 : (4 > 3)%nat. Proof. Admitted.\n\nLemma xxx : forall h1 h2 c1 c2 : nat, (2^h1 > c1)%nat -> (2^h2 > c2)%nat -> (2^(1 + nat_max h1 h2) > 1 + c1 + c2)%nat.\nProof.\n  intros.\n  simpl.\n  destruct h1.\n  destruct h2.\n  destruct c1.\n  destruct c2.\n  simpl.\n  auto.\n  simpl.\n  simpl in H.\n  simpl in H0.\n  apply nat_gt_s in H0.\n  exact H0.\n  simpl.\n  simpl in H.\n  simpl in H0.\n  apply nat_gt_1_is_O in H0.\n  rewrite H0.\n  simpl.\n  rewrite nat_add_id.\n  apply nat_gt_s in H.\n  exact H.\n  simpl.\n  simpl in H.\n  apply nat_gt_1_is_O in H.\n  rewrite H.\n  rewrite nat_add_id_left.\n  rewrite nat_add_id.\n  induction h2.\n    simpl.\n    simpl in H0.\n    apply nat_gt_s in H0.\n    pose (sc2 := S c2).\n    exact (nat_gt_trans 3 4 (S c2) H0 gt_4_3).\n    simpl.\n    simpl in IHh2.\n    rewrite nat_add_id in IHh2.\n    rewrite nat_add_id.\n    rewrite nat_add_mult.\n    rewrite nat_add_mult.\n    \n(*\nLemma max_height : forall t,\nAVLTree t -> (2 ^ (height t) > cardinality t)%nat.\nProof.\n  intros.\n  induction t.\n    simpl.\n    auto.\n    pose (t0 := node z t1 t2).\n    pose (left := avl_left t0 H).\n    simpl in left.\n    pose (right := avl_right t0 H).\n    simpl in right.\n    pose (ind_left := IHt1 left).\n    pose (ind_right := IHt2 right).\n*)\n  ", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/Algorithms/Tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7288125364500996}}
{"text": "(***\n  Boolean Unification Type Declarations.\n  Authors:\n    Joseph St. Pierre\n    Spyridon Antonatos\n***)\n\n(*** Required Libraries ***)\nRequire Import Bool.\nRequire Import Omega.\nRequire Import EqNat.\nRequire Import List.\nRequire Import Setoid.\nImport ListNotations.\n\n(** * Introduction **)\n\n(** In order for any proofs to be constructed in Coq, we need to formally define\n    the logic and data across which said proofs will operate. Since the heart of\n    our analysis is concerned with the unification of Boolean equations, it\n    stands to reason that we should articulate precisely how algebra functions\n    with respect to Boolean rings. To attain this, we shall formalize what an\n    equation looks like, how it can be composed inductively, and also how\n    substitutions behave when applied to equations. *)\n\n(** * Terms **)\n\n(** ** Definitions **)\n\n(** We shall now begin describing the rules of Boolean arithmetic as well as the\n    nature of Boolean equations. *)\n\n(** Define a variable to be a natural number *)\n\nDefinition var := nat.\n\n(** A _term_, as has already been previously described, is now inductively\n    declared to hold either a constant value, a single variable, a sum of terms,\n    or a product of terms. *)\n\nInductive term: Type :=\n  | T0  : term\n  | T1  : term\n  | VAR  : var -> term\n  | SUM : term -> term -> term\n  | PRODUCT : term -> term -> term.\n\n(** For convenience's sake, we define some shorthanded notation for readability.\n    *)\n\nImplicit Types x y z : term.\nImplicit Types n m : var.\n\nNotation \"x + y\" := (SUM x y) (at level 50, left associativity).\nNotation \"x * y\" := (PRODUCT x y) (at level 40, left associativity).\n\n(** ** Axioms *)\n\n(** Now that we have informed Coq on the nature of what a term is, it is now\n    time to propose a set of axioms that will articulate exactly how algebra\n    behaves across Boolean rings. This is a requirement since the very act of\n    unifying an equation is intimately related to solving it algebraically. Each\n    of the axioms proposed below describe the rules of Boolean algebra precisely\n    and in an unambiguous manner. None of these should come as a surprise to the\n    reader; however, if one is not familiar with this form of logic, the rules\n    regarding the summation and multiplication of identical terms might pose as\n    a source of confusion.\n\n    For reasons of keeping Coq's internal logic consistent, we roll our own\n    custom equivalence relation as opposed to simply using \"=\". This will\n    provide a surefire way to avoid any odd errors from later cropping up in our\n    proofs. Of course, by doing this we introduce some implications that we will\n    need to address later. *)\n\nParameter eqv : term -> term -> Prop.\n\n(**  Here we introduce some special notation for term equivalence *)\n\nInfix \" == \" := eqv (at level 70).\n\n(** Below is the set of fundamental axioms concerning the equivalence \"==\"\n    relation. They form the boolean ring (or system) on which Lowenheim's\n    formula and proof are developed.\n\n    Most of these axioms will appear familiar to anyone; however, certain ones\n    such as the summation of two identical terms are true only across Boolean\n    rings and as such might appear strange at first glance. *)\n\nAxiom sum_comm : forall x y, x + y == y + x.\n\nAxiom sum_assoc : forall x y z, (x + y) + z == x + (y + z).\n\nAxiom sum_id : forall x, T0 + x == x. \n\n(** Across boolean rings, the summation of two terms will always be 0 because\n    there are only two elements in the ring: 0 and 1. For this reason, the\n    mapping of [1 + 1] has nowhere else to go besides 0. *)\n\nAxiom sum_x_x : forall x, x + x == T0.\n\nAxiom mul_comm : forall x y, x * y == y * x.\n\nAxiom mul_assoc : forall x y z, (x * y) * z == x * (y * z).\n\n(** Across boolean rings, the multiplication of two identical terms will always\n    be the same as just having one instance of said term. This is because\n    $0 \\ast 0 = 0$ and $1 \\ast 1 = 1$ as one would expect normally. *)\n\nAxiom mul_x_x : forall x, x * x == x.\n\nAxiom mul_T0_x : forall x, T0 * x == T0.\n\nAxiom mul_id : forall x, T1 * x == x.\n\nAxiom distr : forall x y z, x * (y + z) == (x * y) + (x * z).\n\n(** Any axioms beyond this point of the development are not considered part of\n    the \"fundamental axiom system\", but they still need to exist for the\n    development and proofs to hold. *)\n\n(** Across all equations, adding an expression to both sides does not break the\n    equivalence of the relation. *)\n\nAxiom term_sum_symmetric :\n  forall x y z, x == y <-> x + z == y + z.\n\nAxiom refl_comm :\n  forall t1 t2, t1 == t2 -> t2 == t1.\n\nAxiom T1_not_equiv_T0 :\n  ~(T1 == T0).\n\nHint Resolve sum_comm sum_assoc sum_x_x sum_id distr\n             mul_comm mul_assoc mul_x_x mul_T0_x mul_id.\n\n(** Now that the core axioms have been taken care of, we need to handle the\n    implications posed by our custom equivalence relation. Below we inform Coq\n    of the behavior of our equivalence relation with respect to reflexivity,\n    symmetry, and transitivity in order to allow for rewrites during the\n    construction of proofs operating across our new equivalence relation. *)\n\n(* Mundane coq magic for custom equivalence relation *)\n\nAxiom eqv_ref : Reflexive eqv.\nAxiom eqv_sym : Symmetric eqv.\nAxiom eqv_trans : Transitive eqv.\n\nAdd Parametric Relation : term eqv\n  reflexivity proved by @eqv_ref\n  symmetry proved by @eqv_sym\n  transitivity proved by @eqv_trans\n  as eq_set_rel.\n\nAxiom SUM_compat :\n  forall x x', x == x' ->\n  forall y y', y == y' ->\n    (x + y) == (x' + y').\n\nAxiom PRODUCT_compat :\n  forall x x', x == x' ->\n  forall y y', y == y' ->\n    (x * y) == (x' * y').\n\nAdd Parametric Morphism : SUM with\n  signature eqv ==> eqv ==> eqv as SUM_mor.\nProof.\nexact SUM_compat.\nQed.\n\nAdd Parametric Morphism : PRODUCT with\n  signature eqv ==> eqv ==> eqv as PRODUCT_mor.\nProof.\nexact PRODUCT_compat.\nQed.\n\nHint Resolve eqv_ref eqv_sym eqv_trans SUM_compat PRODUCT_compat.\n\n(** ** Lemmas **)\n\n(** Since Coq now understands the basics of Boolean algebra, it serves as a good\n    exercise for us to generate some further rules using Coq's proving systems.\n    By doing this, not only do we gain some additional tools that will become\n    handy later down the road, but we also test whether our axioms are behaving\n    as we would like them to. *)\n\n(** This is a lemma for a sub-case of term multiplication. *)\n\nLemma mul_x_x_plus_T1 :\n  forall x, x * (x + T1) == T0.\nProof.\n  intros. rewrite distr. rewrite mul_x_x. rewrite mul_comm.\n  rewrite mul_id. apply sum_x_x.\nQed.\n\n(** This is a lemma to convert term equivalence to equivalence between their\n    addition and ground term [T0], and vice-versa. *)\n\nLemma x_equal_y_x_plus_y :\n  forall x y, x == y <-> x + y == T0.\nProof.\n  intros. split.\n  - intros. rewrite H. rewrite sum_x_x. reflexivity.\n  - intros. rewrite term_sum_symmetric with (y := y) (z := y). rewrite sum_x_x.\n    apply H.\nQed.\n\nHint Resolve mul_x_x_plus_T1 x_equal_y_x_plus_y.\n\n(** These lemmas just serve to make certain rewrites regarding the core axioms\n    less tedious to write. While one could certainly argue that they should be\n    formulated as axioms and not lemmas due to their triviality, being pedantic\n    is a good exercise. *)\n\n(** This is a lemma for identity addition between term and ground term [T0]. *)\n\nLemma sum_id_sym :\n  forall x, x + T0 == x.\nProof.\n  intros. rewrite sum_comm. apply sum_id.\nQed.\n\n(** Here is a lemma for identity multiplication between term and ground term\n    [T1]. *)\n\nLemma mul_id_sym :\n  forall x, x * T1 == x.\nProof.\n  intros. rewrite mul_comm. apply mul_id.\nQed.\n\n(** This is a lemma for multiplication between term and ground term [T0]. *)\n\nLemma mul_T0_x_sym :\n  forall x, x * T0 == T0.\nProof.\n  intros. rewrite mul_comm. apply mul_T0_x.\nQed.\n\nLemma sum_assoc_opp :\n forall x y z, x + (y + z) == (x + y) + z.\nProof.\n  intros. rewrite sum_assoc. reflexivity.\nQed.\n\nLemma mul_assoc_opp :\n forall x y z, x * (y * z) == (x * y) * z.\nProof.\n  intros. rewrite mul_assoc. reflexivity.\nQed.\n\nLemma distr_opp :\n forall x y z, x * y  +  x * z == x * ( y + z).\nProof.\n  intros. rewrite distr. reflexivity.\nQed.\n\n(** * Variable Sets **)\n\n(** Now that the underlying behavior concerning Boolean algebra has been\n    properly articulated to Coq, it is now time to begin formalizing the logic\n    surrounding our meta reasoning of Boolean equations and systems. While there\n    are certainly several approaches to begin this process, we thought it best\n    to ease into things through formalizing the notion of a set of variables\n    present in an equation. *)\n\n(** ** Definitions **)\n\n(** We now define a _variable set_ to be precisely a list of variables;\n    additionally, we include several functions for including and excluding\n    variables from these variable sets. Furthermore, since uniqueness is not a\n    property guaranteed by Coq lists and it has the potential to be desirable,\n    we define a function that consumes a variable set and removes duplicate\n    entries from it. For convenience, we also provide several examples to\n    demonstrate the functionalities of these new definitions. *)\n\n(** Here is a definition of the new type to represent a list (set) of variables\n    (natural numbers). *)\n\nDefinition var_set := list var.\nImplicit Type vars: var_set.\n\n(** Here is a simple function to check to see if a variable is in a variable\n    set. *)\n\nFixpoint var_set_includes_var (v : var) (vars : var_set) : bool :=\n  match vars with\n  | nil => false\n  | n :: n' => if (beq_nat v n) then true\n                                else var_set_includes_var v n'\n  end.\n\n(** Here is a function to remove all instances of var [v] from a list of vars.\n    *)\n\nFixpoint var_set_remove_var (v : var) (vars : var_set) : var_set :=\n  match vars with\n  | nil => nil\n  | n :: n' => if (beq_nat v n) then (var_set_remove_var v n')\n                                else n :: (var_set_remove_var v n')\n  end.\n\n(** Next is a function to return a unique [var_set] without duplicates. Found\n    vars should be empty for correctness guarantee. *)\n\nFixpoint var_set_create_unique (vars : var_set): var_set :=\n  match vars with\n  | nil => nil\n  | n :: n' => \n    if (var_set_includes_var n n') then var_set_create_unique n'\n                                   else n :: var_set_create_unique n'\n  end.\n\n(** This is a function to check if a given var_set is unique. *)\n\nFixpoint var_set_is_unique (vars : var_set): bool :=\n  match vars with\n  | nil => true\n  | n :: n' =>\n    if (var_set_includes_var n n') then false\n                                   else var_set_is_unique n'\n  end.\n\n(** This is a function to get the variables of a term as a var_set. *)\n\nFixpoint term_vars (t : term) : var_set :=\n  match t with\n  | T0 => nil\n  | T1 => nil\n  | VAR x => x :: nil\n  | PRODUCT x y => (term_vars x) ++ (term_vars y)\n  | SUM x y => (term_vars x) ++ (term_vars y)\n  end.\n\n(** This is a function to generate a list of unique variables that make up a\n    given term. *)\n\nDefinition term_unique_vars (t : term) : var_set :=\n  var_set_create_unique (term_vars t).\n\n(** ** Helper Lemmas for variable sets and lists *)\n\n(** Now that we have established the functionality for variable sets, let us\n    prove some properties about them. *)\n\nLemma vs_includes_true : forall (x : var) (lvar : list var),\n  var_set_includes_var x lvar = true -> In x lvar.\nProof.\n  intros.\n  induction lvar.\n  - simpl; intros. discriminate.\n  - simpl in H. remember (beq_nat x a) as H2. destruct H2.\n    + simpl. left. symmetry in HeqH2. pose proof beq_nat_true as H7.\n      specialize (H7 x a HeqH2). symmetry in H7. apply H7.\n    + specialize (IHlvar H). simpl. right. apply IHlvar.\nQed.\n\nLemma vs_includes_false : forall (x : var) (lvar : list var),\n  var_set_includes_var x lvar = false -> ~ In x lvar.\nProof.\n  intros.\n  induction lvar.\n  - simpl; intros. unfold not. intros. destruct H0.\n  - simpl in H. remember (beq_nat x a) as H2. destruct H2. inversion H.\n    specialize (IHlvar H). firstorder. intuition. apply IHlvar. simpl in H0.\n    destruct H0.\n    + inversion HeqH2. symmetry in H2. pose proof beq_nat_false as H7.\n      specialize (H7 x a H2). rewrite H0 in H7. destruct H7. intuition.\n    + apply H0.\nQed.\n\nLemma in_dup_and_non_dup : forall (x: var) (lvar : list var),\n  In x lvar <-> In x (var_set_create_unique lvar).\nProof.\n  intros. split.\n  - induction lvar.\n    + intros. simpl in H. destruct H.\n    + intros. simpl. remember (var_set_includes_var a lvar) as C. destruct C.\n      * symmetry in HeqC. pose proof vs_includes_true as H7.\n        specialize (H7 a lvar HeqC). simpl in H. destruct H.\n        -- rewrite H in H7. specialize (IHlvar H7). apply IHlvar.\n        -- specialize (IHlvar H). apply IHlvar.\n      * symmetry in HeqC. pose proof vs_includes_false as H7.\n        specialize (H7 a lvar HeqC). simpl in H. destruct H.\n        -- simpl. left. apply H.\n        -- specialize (IHlvar H). simpl. right. apply IHlvar.\n  - induction lvar.\n    + intros. simpl in H. destruct H.\n    + intros. simpl in H. remember (var_set_includes_var a lvar) as C.\n      destruct C.\n      * symmetry in HeqC. pose proof vs_includes_true as H7.\n        specialize (H7 a lvar HeqC). specialize (IHlvar H). simpl.\n        right. apply IHlvar.\n      * symmetry in HeqC. pose proof vs_includes_false as H7.\n        specialize (H7 a lvar HeqC). simpl in H. destruct H.\n        -- simpl.  left. apply H.\n        -- specialize (IHlvar H).  simpl. right. apply IHlvar.\nQed.\n\n(** ** Examples **)\n\n(** Below are some examples of the behaviors of variable sets. *)\n\nExample var_set_create_unique_ex1 :\n  var_set_create_unique [0;5;2;1;1;2;2;9;5;3] = [0;1;2;9;5;3].\nProof.\n  simpl. reflexivity.\nQed.\n\nExample var_set_is_unique_ex1 :\n  var_set_is_unique [0;2;2;2] = false.\nProof.\n  simpl. reflexivity.\nQed.\n\n(** Here are examples to demonstrate the correctness of the function [term_vars]\n    on specific cases. *)\n\nExample term_vars_ex1 :\n  term_vars (VAR 0 + VAR 0 + VAR 1) = [0;0;1].\nProof.\n  simpl. reflexivity.\nQed.\n\nExample term_vars_ex2 :\n  In 0 (term_vars (VAR 0 + VAR 0 + VAR 1)).\nProof.\n  simpl. left. reflexivity.\nQed.\n\n(** * Ground Terms **)\n\n(** Seeing as we just outlined the definition of a variable set, it seems fair\n    to now formalize the definition of a ground term, or in other words, a term\n    that has no variables and whose variable set is the empty set. *)\n\n(** ** Definitions **)\n\n(** A _ground term_ is a recursively defined proposition that is only true if\n    and only if no variable appears in it; otherwise it will be a false\n    proposition and no longer a ground term. *)\n\n(** In this subsection we declare definitions related to ground terms, inluding\n    functions and lemmas. *)\n\n(** This is a function to check if a given term is a ground term (i.e. has no\n    vars). *)\n\nFixpoint ground_term (t : term) : Prop :=\n  match t with\n    | VAR x => False\n    | SUM x y => ground_term x /\\ ground_term y\n    | PRODUCT x y => ground_term x /\\ ground_term y\n    | _ => True\n  end.\n\n(** ** Lemmas **)\n\n(** Our first real lemma (shown below), articulates an important property of\n    ground terms: all ground terms are equvialent to either 0 or 1. This curious\n    property is a direct result of the fact that these terms possess no\n    variables and additioanlly because of the axioms of Boolean algebra. *)\n\n(** This is a lemma (trivial, intuitively true) that proves that if the function\n    [ground_term] returns true then it is either [T0] or [T1]. *)\n\nLemma ground_term_equiv_T0_T1 : forall x,\n  ground_term x -> x == T0 \\/ x == T1.\nProof.\n  intros. induction x.\n  - left. reflexivity.\n  - right. reflexivity.\n  - contradiction.\n  - inversion H. destruct IHx1; destruct IHx2; auto. rewrite H2. left.\n    rewrite sum_id. apply H3. rewrite H2. rewrite H3. rewrite sum_id. right.\n    reflexivity. rewrite H2. rewrite H3. right. rewrite sum_comm.\n    rewrite sum_id. reflexivity. rewrite H2. rewrite H3. rewrite sum_x_x. left.\n    reflexivity.\n  - inversion H. destruct IHx1; destruct IHx2; auto. rewrite H2. left.\n    rewrite mul_T0_x. reflexivity. rewrite H2. left. rewrite mul_T0_x.\n    reflexivity. rewrite H3. left. rewrite mul_comm. rewrite mul_T0_x.\n    reflexivity. rewrite H2. rewrite H3. right. rewrite mul_id. reflexivity.\nQed.\n\n(** This lemma, while intuitively obvious by definition, nonetheless provides a\n    formal bridge between the world of ground terms and the world of variable\n    sets. *)\n\nLemma ground_term_has_empty_var_set : forall x,\n  ground_term x -> term_vars x = [].\nProof.\n  intros. induction x.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - contradiction.\n  - firstorder. unfold term_vars. unfold term_vars in H2. rewrite H2.\n    unfold term_vars in H1. rewrite H1. simpl. reflexivity.\n  - firstorder. unfold term_vars. unfold term_vars in H2. rewrite H2.\n    unfold term_vars in H1. rewrite H1. simpl. reflexivity.\nQed.\n\n(** ** Examples **)\n\n(** Here are some examples to show that our ground term definition is working\n    appropriately. *)\n\nExample ex_gt1 :\n  ground_term (T0 + T1).\nProof.\n  simpl. split.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nExample ex_gt2 :\n  ground_term (VAR 0 * T1) -> False.\nProof.\n  simpl. intros. destruct H. apply H.\nQed.\n\n(** * Substitutions **)\n\n(** It is at this point in our Coq development that we begin to officially\n    define the principal action around which the entirety of our efforts are\n    centered: the act of substituting variables with other terms. While\n    substitutions alone are not of great interest, their emergent properties as\n    in the case of whether or not a given substitution unifies an equation are\n    of substantial importance to our later research. *)\n\n(** ** Definitions **)\n\n(** In this subsection we make the fundamental definitions of substitutions,\n    basic functions for them, accompanying lemmas and some propsitions. *)\n\n(** Here we define a _substitution_ to be a list of ordered pairs where each\n    pair represents a variable being mapped to a term. For sake of clarity these\n    ordered pairs shall be referred to as _replacements_ from now on and as a\n    result, substitutions should really be considered to be lists of\n    replacements. *)\n\nDefinition replacement := prod var term.\n\n(** We define a new type [susbt] to represent a substitution as a list of\n    replacements. *)\n\nDefinition subst := list replacement.\n\nImplicit Type s : subst.\n\n(** Our first function, [find_replacement], is an auxilliary to [apply_subst].\n    This function will search through a substitution for a specific variable,\n    and if found, returns the variable's associated term. *)\n\nFixpoint find_replacement (x : var) (s : subst) : term :=\n  match s with\n  | nil => VAR x\n  | r :: r' =>\n      if beq_nat (fst r) x then snd r\n                           else find_replacement x r'\n  end.\n\n(** The [apply_subst] function will take a term and a substitution and will\n    produce a new term reflecting the changes made to the original one. *)\n\nFixpoint apply_subst (t : term) (s : subst) : term :=\n  match t with\n  | T0 => T0\n  | T1 => T1\n  | VAR x => find_replacement x s\n  | PRODUCT x y => PRODUCT (apply_subst x s) (apply_subst y s)\n  | SUM x y => SUM (apply_subst x s) (apply_subst y s)\n  end.\n\n(** For reasons of completeness, it is useful to be able to generate _identity\n    substitutions_; namely, substitutions that map the variables of a term to\n    themselves. *)\n\n(** This is a function when given a list of variables builds a list of\n    identity substitutions - one for each variable. *)\n\nFixpoint build_id_subst (lvar : var_set) : subst :=\n  match lvar with\n  | nil => nil\n  | v :: v' => (v , (VAR v)) :: build_id_subst v'\n  end.\n\n(** Since we now have the ability to generate identity substitutions, we should\n    now formalize a general proposition for testing whether or not a given\n    substitution is an identity substitution of a given term. *)\n\nDefinition subst_equiv (s1 s2: subst) : Prop :=\n  forall t, apply_subst t s1 == apply_subst t s2.\n\nDefinition subst_is_id_subst (t : term) (s : subst) : Prop :=\n  apply_subst t s == t.\n\n(** Given we now have definitions for substitutions, we should now introduce the\n    idea of a substitution composing another one. *)\n\nFixpoint subst_compose (s s' : subst) : subst :=\n  match s' with\n  | [] => s\n  | (x, t) :: s'' => (x, apply_subst t s) :: (subst_compose s s'')\n  end.\n\n(** Here we define the domain of a substituion, namely the list of variables for\n    which the substitution has a mapping (replacement). Essentially this acts as\n    a list of all the first parts of the replacement. *)\n\nDefinition subst_domain (sig : subst) : list var :=\n  map (fun r => (fst r)) sig.\n\n(** We define the concept of a sub list. If an element is a member of a list,\n    it is then a member of the other list as well. *)\n\nDefinition sub_dmn_list (l1 : list var) (l2 : list var) : Prop :=\n forall (x : var), In x l1 -> In x l2.\n\n(** ** Helper Lemmas for the [apply_subst] function **)\n\n(** Having now outlined the functionality of a subsitution, let us now begin to\n    analyze some implications of its form and composition by proving some\n    lemmas. *)\n\n(** Given that we have a definition for identity substitutions, we should prove\n    that identity substitutions do not modify a term. *)\n\nLemma id_subst: forall (t : term) (l : var_set),\n  apply_subst t (build_id_subst l) == t.\nProof.\n  intros. induction t.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. induction l.\n    + simpl. reflexivity.\n    + simpl. destruct (beq_nat a v) eqn: e.\n      * apply beq_nat_true in e. rewrite e. reflexivity.\n      * apply IHl.\n  - simpl. rewrite IHt1. rewrite IHt2. reflexivity.\n  - simpl. rewrite IHt1. rewrite IHt2. reflexivity.\nQed.\n\n(** These are helper lemmes for the [apply_subst] properties. *)\n\nLemma sum_comm_compat t1 t2: forall (sigma: subst),\n  apply_subst (t1 + t2) sigma == apply_subst (t2 + t1) sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve sum_comm_compat.\n\nLemma sum_assoc_compat t1 t2 t3: forall (sigma: subst),\n  apply_subst ((t1 + t2) + t3) sigma == apply_subst (t1 + (t2 + t3)) sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve sum_assoc_compat.\n\nLemma sum_id_compat t: forall (sigma: subst),\n  apply_subst (T0 + t) sigma == apply_subst t sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve sum_id_compat.\n\nLemma sum_x_x_compat t: forall (sigma: subst),\n  apply_subst (t + t) sigma == apply_subst T0 sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve sum_x_x_compat.\n\nLemma mul_comm_compat t1 t2: forall (sigma: subst),\n  apply_subst (t1 * t2) sigma == apply_subst (t2 * t1) sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve mul_comm_compat.\n\nLemma mul_assoc_compat t1 t2 t3: forall (sigma: subst),\n  apply_subst ((t1 * t2) * t3) sigma == apply_subst (t1 * (t2 * t3)) sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve mul_assoc_compat.\n\nLemma mul_x_x_compat t: forall (sigma: subst),\n  apply_subst (t * t) sigma == apply_subst t sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve mul_x_x_compat.\n\nLemma mul_T0_x_compat t: forall (sigma: subst),\n  apply_subst (T0 * t) sigma == apply_subst T0 sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve mul_T0_x_compat.\n\nLemma mul_id_compat t: forall (sigma: subst),\n  apply_subst (T1 * t) sigma == apply_subst t sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve mul_id_compat.\n\nLemma distr_compat t1 t2 t3: forall (sigma: subst),\n  apply_subst (t1 * (t2 + t3)) sigma ==\n  apply_subst ((t1 * t2) + (t1 * t3)) sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve distr_compat.\n\nLemma refl_comm_compat t1 t2: forall (sigma: subst),\n  apply_subst t1 sigma == apply_subst t2 sigma ->\n  apply_subst t2 sigma == apply_subst t1 sigma.\nProof.\n  intros. simpl. auto.\nQed.\nHint Resolve refl_comm_compat.\n\nLemma trans_compat t1 t2 t3 : forall (sigma: subst),\n  apply_subst t1 sigma == apply_subst t2 sigma ->\n  apply_subst t2 sigma == apply_subst t3 sigma ->\n  apply_subst t1 sigma == apply_subst t3 sigma.\nProof.\n  intros. eauto.\nQed.\nHint Resolve trans_compat.\n\nLemma trans_compat2 c1 c2 c3 : \n  c1 == c2 ->\n  c2 == c3 ->\n  c1 == c3.\nProof.\n  intros. eauto.\nQed.\n\n(** This is an axiom that states that if two terms are equivalent then applying\n    any substitution on them will also produce equivalent terms. The reason we\n    axiomatized this and we did not prove it as a lemma is because the set of\n    our fundamental axioms is not an inductive relation, so it would be\n    impossible to prove the lemma below with our fundamental axioms in the\n    currrent format. *)\n\nAxiom apply_subst_compat : forall (t t' : term),\n  t == t' ->\n  forall (sigma: subst), apply_subst t sigma == apply_subst t' sigma.\n\nAdd Parametric Morphism : apply_subst with\n      signature eqv ==> eq ==> eqv as apply_subst_mor.\nProof.\n  exact apply_subst_compat.\nQed.\n\n(** This is a simple lemma that states that an empty substitution cannot modify\n    a term. *)\n\nLemma subst_empty_no_change :\n  forall (t : term), (apply_subst t []) == t.\nProof.\n  intros. induction t.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. rewrite IHt1. rewrite IHt2. reflexivity.\n  - simpl. rewrite IHt1. rewrite IHt2. reflexivity.\nQed.\n\n\n(** An intuitive thing to prove for ground terms is that they cannot be modified\n    by applying substitutions to them. This will later prove to be very relevant\n    when we begin to talk about unification. *)\n\n(** This is a helpful lemma for showing substitutions do not affect ground\n    terms. *)\n\nLemma ground_term_cannot_subst : forall x,\n  ground_term x ->\n  forall s, apply_subst x s == x.\nProof.\n  intros. induction s.\n  - apply ground_term_equiv_T0_T1 in H. destruct H.\n    + rewrite H. simpl. reflexivity.\n    + rewrite H. simpl. reflexivity.\n  - apply ground_term_equiv_T0_T1 in H. destruct H. rewrite H.\n    + simpl. reflexivity.\n    + rewrite H. simpl. reflexivity.\nQed.\n\n(** A fundamental property of substitutions is their distributivity across the\n    summation and multiplication of terms. Again the importance of these proofs\n    will not become apparent until we talk about unification. *)\n\n(** This is a useful lemma for showing the distributivity of substitutions\n    across term summation. *)\n\nLemma subst_sum_distribution : forall s x y,\n  apply_subst x s + apply_subst y s == apply_subst (x + y) s.\nProof.\n  intro. induction s.\n  - simpl. intros. reflexivity.\n  - intros. simpl. reflexivity.\nQed.\n\n(** This is a lemma to prove the distributivity of the [apply_subst] function\n    across term multiplication. *)\n\nLemma subst_mul_distribution : forall s x y,\n  apply_subst x s * apply_subst y s == apply_subst (x * y) s.\nProof.\n  intro. induction s.\n  - intros. reflexivity.\n  - intros. simpl. reflexivity. \nQed.\n\n(** Here is a lemma to prove the opposite of summation distributivity of the\n    [apply_subst] function across term summation. *)\n\nLemma subst_sum_distr_opp : forall s x y,\n  apply_subst (x + y) s == apply_subst x s + apply_subst y s.\nProof.\n  intros.\n  apply refl_comm.\n  apply subst_sum_distribution.\nQed.\n\n(** This is a lemma to prove the opposite of multiplication distributivity of\n    the [apply_subst] function across term summation. *)\n\nLemma subst_mul_distr_opp : forall s x y,\n  apply_subst (x * y) s == apply_subst x s * apply_subst y s.\nProof.\n  intros.\n  apply refl_comm.\n  apply subst_mul_distribution.\nQed.\n\n(** This is an intutitive lemmas to apply a single replacement substitution on a\n    VAR term. *)\n\nLemma var_subst: forall (v : var) (ts : term),\n  apply_subst (VAR v) [(v , ts)] == ts.\nProof.\n  intros. simpl. destruct (beq_nat v v) eqn: e.\n  - apply beq_nat_true in e. reflexivity.\n  - apply beq_nat_false in e. firstorder.\nQed.\n\n(** ** Examples **)\n\n(** Here are some examples showcasing the nature of applying substitutions to\n    terms. *)\n\nExample subst_ex1 :\n  apply_subst (T0 + T1) [] == T0 + T1.\nProof.\n  intros. reflexivity.\nQed.\n\nExample subst_ex2 :\n  apply_subst (VAR 0 * VAR 1) [(0, T0)] == T0.\nProof.\n  intros. simpl. apply mul_T0_x.\nQed.\n\n(** ** Auxillary Definitions for Substitutions and Terms *)\n\n(** In this section we define more helper functions and lemmas related to\n    substitutions and ground terms. Specifically we are defining a ground term,\n    a ground substitution, a \"01\" term, a \"01\" substitution, and a substitution\n    composition. A [ground_term] is a term with no variables in it. \n    The terms that are used more in the future proofs are the \"01\"\n    term and \"01\" substitution. A \"01\" term is a term that is either exaclty\n    equal to [T0] or [T1]. A \"01\" substitution is a substitution in which each\n    variable (or the first part of each replacement) is mapped to a \"01\" term. A\n    \"01\" term is not necessarily a ground term (but it might be) and a \"01\"\n    substitution is not necessarily a ground substitution (but it might be). In\n    the proof file, we are mostly using the \"01\" term and substitution\n    terminology. \n*)\n\n(** We define a proposition for a [ground_subst]. A substitution is ground when\n    in all of its replacements, the second part is a [ground_term]. *)\n\nFixpoint ground_subst (sig : subst) : Prop :=\n  match sig with\n  | [] => True\n  | r :: r' => ground_term (snd r) /\\ ground_subst r'\n  end.\n\n\n(** This is a function to determine whether a term is a ground term, by\n    returning a boolean. *)\n\nFixpoint is_ground_term (t : term) : bool :=\n  match t with\n  | T0 => true\n  | T1 => true\n  | VAR x => false\n  | SUM a b => (is_ground_term a) && (is_ground_term b)\n  | PRODUCT a b => (is_ground_term a) && (is_ground_term b)\n  end.\n\n\n(** This is a function to determine whether a subsitution is a ground\n    substitution, by returning a boolean. *)\n\nFixpoint is_ground_subst (sig : subst) : bool :=\n  existsb is_ground_term (map snd sig).\n\n\n(** This is a function to determine whether a term is a [T0] or [T1] term by\n    returning a boolean. *)\n\nDefinition is_01_term (t : term) : bool :=\n  match t with\n  | T0 => true\n  | T1 => true\n  | _ => false\n  end.\n\n\n(** This is a function to determine whether a substitution is a \"01\"\n    substitution by returning a boolean, meaning that each second part of every\n    replacement is either a [T0] or a [T1] term. *)\n\nFixpoint is_01_subst (sig : subst) : bool :=\n  existsb is_01_term (map snd sig).\n\n\n(** This is a function to determine whether a term is a [T0] or [T1] term by\n    returning a proposition. *)\n\nFixpoint _01_term (t : term) : Prop :=\n  match t with\n  | T0 => True\n  | T1 => True\n  | _ => False\n  end.\n\n(** This is a function to determine whether a substitution is a \"01\"\n    substitution by returning a proposition, meaning that each second part of\n    every replacement is either a [T0] or a [T1] term. *)\n\nFixpoint _01_subst (sig : subst) : Prop :=\n  match sig with \n  | [] => True\n  | r :: r' => _01_term (snd r) /\\ _01_subst r'\n  end.\n\n\n\n(** * Unification **)\n\n(** Now that we have established the concept of term substitutions in Coq, it is\n    time for us to formally define the concept of Boolean unification.\n    _Unification_, in its most literal sense, refers to the act of applying a\n    substitution to terms in order to make them equivalent to each other. In\n    other words, to say that two terms are _unifiable_ is to really say that\n    there exists a substitution such that the two terms are equal. Interestingly\n    enough, we can abstract this concept further to simply saying that a single\n    term is unifiable if there exists a substitution such that the term will be\n    equivalent to [0]. By doing this abstraction, we can prove that equation\n    solving and unification are essentially the same fundamental problem. *)\n\n(** Below is the initial definition for unification, namely that two terms can\n    be unified to be equivalent to one another. By starting here we will show\n    each step towards abstracting unification to refer to a single term. *)\n\n(**  Proposition that a given substitution unifies (namely, makes equivalent),\n    two given terms *)\n\nDefinition unifies (a b : term) (s : subst) : Prop :=\n  apply_subst a s == apply_subst b s.\n\n(** Here is a simple example demonstrating the concept of testing whether two\n    terms are unified by a substitution. *)\n\nExample ex_unif1 :\n  unifies (VAR 0) (VAR 1) [(0, T1); (1, T1)].\nProof.\n  unfold unifies. simpl. reflexivity.\nQed.\n\n(** Now we are going to show that moving both terms to one side of the\n    equivalence relation through addition does not change the concept of\n    unification. *)\n\n(** This is a proposition that a given substitution makes equivalent the sum of\n    two terms when the substitution is applied to each of them, and ground term\n    [T0]. *)\n\nDefinition unifies_T0 (a b : term) (s : subst) : Prop :=\n  apply_subst a s + apply_subst b s == T0.\n\n(** This is a lemma that proves that finding a unifier for [x = y] is the same\n    as finding a unifier for [x + y = 0]. *)\n\nLemma unifies_T0_equiv : forall x y s,\n  unifies x y s <-> unifies_T0 x y s.\nProof.\n  intros. split.\n  - intros. unfold unifies_T0. unfold unifies in H. rewrite H.\n    rewrite sum_x_x. reflexivity.\n  - intros. unfold unifies_T0 in H. unfold unifies.\n    rewrite term_sum_symmetric with (x := apply_subst x s + apply_subst y s) \n    (z := apply_subst y s) in H. rewrite sum_id in H.\n    rewrite sum_comm in H.\n    rewrite sum_comm with (y := apply_subst y s) in H.\n    rewrite <- sum_assoc in H.\n    rewrite sum_x_x in H.\n    rewrite sum_id in H.\n    apply H.\nQed.\n\n(** Now we can define what it means for a substitution to be a unifier for a\n    given term. *)\n\n(** Here is a proposition that a given substitution unifies a given term, namely\n    it makes it equivalent with [T0]. *)\n\nDefinition unifier (t : term) (s : subst) : Prop :=\n  apply_subst t s == T0.\n\nExample unifier_ex1 :\n  unifier (VAR 0) [(0, T0)].\nProof.\n  unfold unifier. simpl. reflexivity.\nQed.\n\n(** To ensure our efforts were not in vain, let us now prove that this last\n    abstraction of the unification problem is still equivalent to the original.\n    *)\n\n(** This is a lemma that proves that the unifier proposition can distributes\n    over addition of terms. *)\n\nLemma unifier_distribution : forall x y s,\n  unifies_T0 x y s <-> unifier (x + y) s.\nProof.\n  intros. split.\n  - intros. unfold unifies_T0 in H. unfold unifier.\n    rewrite <- H. symmetry. apply subst_sum_distribution.\n  - intros. unfold unifies_T0. unfold unifier in H.\n    rewrite <- H. apply subst_sum_distribution.\nQed.\n\n\n(** Lastly let us define a term to be unifiable if there exists a substitution\n    that unifies it. *)\n\n(** This is a proposition that states when a term is unifiable. *)\n\nDefinition unifiable (t : term) : Prop :=\n  exists s, unifier t s.\n\nExample unifiable_ex1 :\n  exists x, unifiable (x + T1).\nProof.\n  exists T1. unfold unifiable. unfold unifier.\n  exists []. simpl. rewrite sum_x_x. reflexivity.\nQed.\n\n(** * Most General Unifier **)\n\n(** In this subsection we define propositions, lemmas and examples related to\n    the most general unifier. *)\n\n(** While the property of a term being unifiable is certainly important, it\n    should come as no surprise that not all unifiers are created equal; in fact,\n    certain unifiers possess the desirable property of being _more general_ than\n    others. For this reason, let us now formally define the concept of a _most\n    general unifier_ (mgu): a unifier such that with respect to a given term,\n    all other unifiers are instances of it, or in other words, less general than\n    it. *)\n\n(** The first step towards establishing the concept of a mgu requires us to\n    formalize the notion of a unifier being more general than another. To\n    accomplish this goal, let us formulate the definition of a substitution\n    composing another one; or in other words, to say that a substitution is more\n    general than another one. *)\n\n(** This is a proposition of sequential substition application. *)\n\nDefinition substitution_factor_through (s s' delta : subst) : Prop :=\n  forall (x : var), apply_subst (apply_subst (VAR x) s) delta ==\n                    apply_subst (VAR x) s' .\n\n(** This is the definition of a more general substition. *)\n\nDefinition more_general_substitution (s s': subst) : Prop :=\n  exists delta, substitution_factor_through s s' delta .\n\n(** Now that we have articulated the concept of composing substitutions, let us\n    now formulate the definition for a most general unifier. *)\n\n(** This is the definition of a Most General Unifier (mgu): A Most General\n    Unifier (MGU) takes in a term and a substitution and tells whether or not\n    said substitution is an mgu for the given term. *)\n\nDefinition most_general_unifier (t : term) (s : subst) : Prop :=\n  unifier t s /\\\n  forall (s' : subst),\n  unifier t s' ->\n  more_general_substitution s s'.\n\n(** While this definition of a most general unifier is certainly valid, we can\n    also characterize a unifier by other similar properties. For this reason,\n    let us now define an alternative definition called a _reproductive unifier_,\n    and then prove it to be equivalent to our definition of a most general\n    unifier. This will make our proofs easier to formulate down the road as the\n    task of proving a unifier to be reproductive is substantially easier than\n    proving it to be most general directly. *)\n\nDefinition reproductive_unifier (t : term) (sig : subst) : Prop :=\n  unifier t sig /\\\n  forall (tau : subst) (x : var),\n  unifier t tau ->\n  apply_subst (apply_subst (VAR x) sig ) tau == apply_subst (VAR x) tau.\n\n(** This is a lemma to show that a reproductive unifier is a most general\n    unifier. Since the ultimate goal is to prove that a specific algorithm\n    produces an mgu then if we could prove it is a reproductive unifier then we\n    could use this lemma to arrive at the desired conclusion. *)\n\nLemma reproductive_is_mgu : forall (t : term) (u : subst),\n  reproductive_unifier t u ->\n  most_general_unifier t u.\nProof.\n  intros. unfold most_general_unifier. unfold reproductive_unifier in H.\n  unfold more_general_substitution . destruct H. split.\n  - apply H.\n  - intros. specialize (H0 s'). exists s'. unfold substitution_factor_through.\n    intros. specialize (H0 x).\n    specialize (H0 H1). apply H0.\nQed.\n\n(** This is a lemma to show that if two terms are equivalent then for any\n    subsitution that is an mgu of one of the terms, then it is an mgu of the\n    other term as well. *)\n\nLemma most_general_unifier_compat : forall  (t t' : term),\n  t == t' ->\n  forall (sigma: subst),\n  most_general_unifier t sigma <-> most_general_unifier t' sigma.\nProof.\n  intros. split. \n  - intros. unfold most_general_unifier. unfold unifier in H0.\n    unfold unifier in *. split.\n    + unfold most_general_unifier in H0. destruct H0. unfold unifier in H0.\n      rewrite H in H0. apply H0.\n    + intros. unfold most_general_unifier in H0. destruct H0.\n      specialize (H2 s'). unfold unifier in H0. symmetry in H. rewrite H in H1.\n      unfold unifier in H2. specialize (H2 H1). apply H2.\n  - unfold most_general_unifier.  intros. destruct H0 . split.\n    + symmetry in H. unfold unifier in H0.  rewrite H in H0. unfold unifier.\n      apply H0.\n    + intros. specialize (H1 s'). unfold unifier in H2. rewrite H in H2.\n      unfold unifier in H1. specialize (H1 H2). apply H1.\nQed.\n\n\n(** * Auxilliary Computational Operations and Simplifications *)\n\n(** These functions below will come in handy later during the Lowenheim formula\n    proof. They mainly lay the groundwork for providing the computational nuts\n    and bolts for Lowenheim's algorithm for finding most general unifiers and\n    initial ground unifiers. *)\n\n(*  alternate defintion of functions related to term operations and evaluations\n    that take into consideration more sub-cases *)\n\n(** This is a function to check if two terms are exaclty identical. *)\n\nFixpoint identical (a b: term) : bool :=\n  match a , b with\n  | T0, T0 => true\n  | T0, _ => false\n  | T1 , T1 => true\n  | T1 , _ => false\n  | VAR x , VAR y => if beq_nat x y then true else false\n  | VAR x, _ => false\n  | PRODUCT x y, PRODUCT x1 y1 => identical x x1 && identical y y1\n  | PRODUCT x y, _ => false\n  | SUM x y, SUM x1 y1 => identical x x1 && identical y y1\n  | SUM x y, _ => false\n  end.\n\n\n(** This is basic addition for terms. *)\n\nDefinition plus_one_step (a b : term) : term :=\n  match a, b with\n  | T0, T0 => T0\n  | T0, T1 => T1\n  | T1, T0 => T1\n  | T1 , T1 => T0\n  | _ , _ => SUM a b\n  end.\n\n\n(** This is basic multiplication for terms. *)\n\nDefinition mult_one_step (a b : term) : term :=\n  match a, b with\n  | T0, T0 => T0\n  | T0, T1 => T0\n  | T1, T0 => T0\n  | T1 , T1 => T1\n  | _ , _ => PRODUCT a b\n  end.\n\n\n(** This is a function to simplify a term in very apparent and basic ways. They\n    are only simplified if they are ground terms. *)\n\nFixpoint simplify (t : term) : term :=\n  match t with\n  | T0 => T0\n  | T1 => T1\n  | VAR x => VAR x \n  | PRODUCT x y => mult_one_step (simplify x) (simplify y)\n  | SUM x y => plus_one_step (simplify x) (simplify y)\n  end.\n\n\n(** Some lemmas follow to prove intuitive facts for the basic multiplication and\n    addition of terms, leading up to proving the [simplify_eqv] lemma. *)\n\nLemma pos_left_sum_compat : forall (t t1 t2 : term),\n  t == t1 -> plus_one_step t1 t2 == plus_one_step t t2.\nProof.\n  intros. induction t1.\n  - induction t.\n    + reflexivity.\n    + apply T1_not_equiv_T0 in H. inversion H.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_x_x. rewrite H. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity. \n  - induction t.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_id. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n - induction t.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_id. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\nQed.\n\nLemma pos_right_sum_compat : forall  (t t1 t2 : term),\n     t == t2 -> plus_one_step t1 t2 == plus_one_step t1 t.\nProof.\nintros. induction t1.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. apply H.\n      * simpl. rewrite <- H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_x_x. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_id. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_id. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_id. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_id. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_id. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_comm. rewrite sum_id. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite sum_x_x. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite sum_comm. rewrite sum_id. reflexivity.\n      * simpl. rewrite H. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\nQed.\n\nLemma pos_left_mul_compat : forall  (t t1 t2 : term),\n  t == t1 -> mult_one_step t1 t2 == mult_one_step t t2.\nProof.\n  intros. induction t1.\n  - induction t.\n    + reflexivity.\n    + apply T1_not_equiv_T0 in H. inversion H.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity. \n  - induction t.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite <- H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\nQed.\n\nLemma pos_right_mul_compat : forall  (t t1 t2 : term),\n  t == t2 -> mult_one_step t1 t2 == mult_one_step t1 t.\nProof.\nintros. induction t1.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_x_x. reflexivity.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. reflexivity.\n    + induction t2.\n      * simpl. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n    + induction t2.\n      * simpl. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n    + induction t2.\n      * simpl. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite mul_T0_x. rewrite mul_T0_x. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite <- H. rewrite mul_x_x. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. rewrite mul_comm. rewrite mul_T0_x. reflexivity.\n      * simpl. rewrite H. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n  - induction t.\n    + induction t2.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\n    + induction t2.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite H. reflexivity.\n      * simpl. rewrite <- H. reflexivity.\nQed.\n\n(** Being able to simplify a term can be a useful tool. Being able to use the\n    simplified version of the term as the equivalent version of the original\n    term can also be useful since many of our functions simplify the term first.\n    *)\n\nLemma simplify_eqv : forall (t : term),\n  simplify t == t.\nProof.\n  intros. induction t.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - simpl. pose proof pos_left_sum_compat.\n    specialize (H t1 (simplify t1) (simplify t2)).\n    symmetry in IHt1. specialize (H IHt1). rewrite H.\n    pose proof pos_right_sum_compat. specialize (H0 (simplify t2) t1 t2).\n    specialize (H0 IHt2). symmetry in H0. rewrite H0.\n    induction t1.\n    + induction t2.\n      * simpl. rewrite sum_x_x. reflexivity.\n      * simpl. rewrite sum_id. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n    + induction t2.\n      * simpl. rewrite sum_id_sym. reflexivity.\n      * simpl. rewrite sum_x_x. reflexivity.  \n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.  \n    + simpl. reflexivity.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n  - simpl. pose proof pos_left_mul_compat.\n    specialize (H t1 (simplify t1) (simplify t2)).\n    symmetry in IHt1. specialize (H IHt1). rewrite H.\n    pose proof pos_right_mul_compat. specialize (H0 (simplify t2) t1 t2).\n    specialize (H0 IHt2). symmetry in H0. rewrite H0.\n    induction t1.\n    + induction t2.\n      * simpl. rewrite mul_x_x. reflexivity.\n      * simpl. rewrite mul_T0_x.  reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n    + induction t2.\n      * simpl. rewrite mul_T0_x_sym. reflexivity.\n      * simpl. rewrite mul_x_x. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n      * simpl. reflexivity.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\nQed.\n\n", "meta": {"author": "dandougherty", "repo": "mqpCoq2018", "sha": "bc8018a301e4ad2a8ea88b1381715b4e2084bdcd", "save_path": "github-repos/coq/dandougherty-mqpCoq2018", "path": "github-repos/coq/dandougherty-mqpCoq2018/mqpCoq2018-bc8018a301e4ad2a8ea88b1381715b4e2084bdcd/B_Unification/terms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7288125321435807}}
{"text": "Require Import Arith Omega.\n\nLemma test : forall p:nat, p<>0 -> p-1+1=p.\nProof.\n intros; omega.\nQed.\n\n(** Test of new syntax for rewrite : ! ? and so on... *)\n\nLemma but : forall a b c, a<>0 -> b<>0 -> c<>0 ->\n (a-1+1)+(b-1+1)+(c-1+1)=a+b+c.\nProof.\nintros.\nrewrite test.\nUndo.\nrewrite test,test.\nUndo.\nrewrite 2 test. (* or rewrite 2test or rewrite 2!test *)\nUndo.\nrewrite 2!test,2?test.\nUndo.\n(*rewrite 4!test.  --> error *)\nrewrite 3!test.\nUndo.\nrewrite <- 3?test.\nUndo.\n(*rewrite <-?test. --> loops*)\nrewrite !test by auto.\nreflexivity.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/success/rewrite_iterated.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7288071505633041}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_angledistinct.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_layoff.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_equalanglesNC.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_equalangleshelper.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_04.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_equalanglestransitive : \n   forall A B C D E F P Q R, \n   CongA A B C D E F -> CongA D E F P Q R ->\n   CongA A B C P Q R.\nProof.\nintros.\nassert (neq A B) by (forward_using lemma_angledistinct).\nassert (neq D E) by (forward_using lemma_angledistinct).\nassert (neq B A) by (conclude lemma_inequalitysymmetric).\nassert (neq E D) by (conclude lemma_inequalitysymmetric).\nassert (neq E F) by (forward_using lemma_angledistinct).\nassert (neq B C) by (forward_using lemma_angledistinct).\nassert (neq P Q) by (forward_using lemma_angledistinct).\nassert (neq Q P) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists U, (Out E D U /\\ Cong E U B A)) by (conclude lemma_layoff);destruct Tf as [U];spliter.\nlet Tf:=fresh in\nassert (Tf:exists V, (Out E F V /\\ Cong E V B C)) by (conclude lemma_layoff);destruct Tf as [V];spliter.\nassert (neq E U) by (conclude lemma_raystrict).\nassert (neq E V) by (conclude lemma_raystrict).\nassert (CongA P Q R D E F) by (conclude lemma_equalanglessymmetric).\nassert (neq Q R) by (forward_using lemma_angledistinct).\nlet Tf:=fresh in\nassert (Tf:exists u, (Out Q P u /\\ Cong Q u E U)) by (conclude lemma_layoff);destruct Tf as [u];spliter.\nlet Tf:=fresh in\nassert (Tf:exists v, (Out Q R v /\\ Cong Q v E V)) by (conclude lemma_layoff);destruct Tf as [v];spliter.\nassert (nCol A B C) by (conclude_def CongA ).\nassert (CongA A B C U E V) by (conclude lemma_equalangleshelper).\nassert (Cong B A E U) by (conclude lemma_congruencesymmetric).\nassert (Cong B C E V) by (conclude lemma_congruencesymmetric).\nassert ((Cong A C U V /\\ CongA B A C E U V /\\ CongA B C A E V U)) by (conclude proposition_04).\nassert (Cong E U Q u) by (conclude lemma_congruencesymmetric).\nassert (Cong E V Q v) by (conclude lemma_congruencesymmetric).\nassert (CongA D E F u Q v) by (conclude lemma_equalangleshelper).\nassert (CongA u Q v D E F) by (conclude lemma_equalanglessymmetric).\nassert (CongA u Q v U E V) by (conclude lemma_equalangleshelper).\nassert (CongA U E V u Q v) by (conclude lemma_equalanglessymmetric).\nassert ((Cong U V u v /\\ CongA E U V Q u v /\\ CongA E V U Q v u)) by (conclude proposition_04).\nassert (Cong A C u v) by (conclude lemma_congruencetransitive).\nassert (Cong B A Q u) by (conclude lemma_congruencetransitive).\nassert (Cong B C Q v) by (conclude lemma_congruencetransitive).\nassert (eq A A) by (conclude cn_equalityreflexive).\nassert (eq C C) by (conclude cn_equalityreflexive).\nassert (Out B A A) by (conclude lemma_ray4).\nassert (Out B C C) by (conclude lemma_ray4).\nassert (CongA A B C P Q R) by (conclude_def CongA ).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_equalanglestransitive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7287588846213675}}
{"text": "(* Exercise coq_list_08 *)\n\n(* Those are the definitions from the previous exercise: *)\n\nInductive natlist : Set :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nFixpoint append (l m : natlist) {struct l} : natlist :=\n  match l with\n  | nil => m\n  | cons x xs => cons x (append xs m)\n  end.\n\nFixpoint reverse (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | cons ele rem => append (reverse rem) (cons ele nil)\n  end.\n\n(* Now, let us prove that reversing a list twice gives back\n   the original list. *)\n   \n(* For that we may need the result proven in the previous\n   exercise *)   \nAxiom reverse_append : forall l m,\n  reverse (append l m) = append (reverse m) (reverse l).\n      \nLemma reverse_double : forall l, reverse (reverse l) = l.\n    \nProof.\n  intros.\n  induction l.\n  simpl; reflexivity.\n  simpl.\n  rewrite reverse_append.\n  rewrite IHl.\n  simpl.\n  reflexivity.\nQed.", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_list_08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7287588761004595}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus (plus x y) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj205_coqofml_dPmM5s.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7287294096118179}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Ralph Matthes [+]                              *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [+] Affiliation IRIT -- CNRS   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega.\n\nRequire Import wf_utils llist fifo.\n\nSet Implicit Arguments.\n\n(* We provide an implementation of FIFO as a triple of lazy lists \n   satisfying the axioms in fifo.v *)\n\nModule FIFO_3llists <: FIFO.\n\nSection fifo_three_lazy_lists.\n\n  (** From \"Simple and Efficient Purely Functional Queues and Deques\" by Chris Okasaki \n          Journal of Functional Programming 5(4):583-592\n\n      this implements and proves the spec from page 587 with lazy lists\n      with invariant (l,r,l') : lazy_length l' + lazy_length r = lazy_length l\n\n      let rec lazy_rotate l r a := match r with\n        | lcons y r' -> match l with\n          | lnil       -> lcons y a\n          | lcons x l' -> lcons x (lazy_rotate l' r' (lcons y a))\n\n      let empty = (lnil,lnil,lnil)\n\n      let make l r l' = match l' with\n        | lnil       -> let l' = lazy_rotate l r lnil in (l',lnil,l')\n        | lcons _ l' -> (l, r, l')\n\n      let enq (l,r,l') x = make l (lcons x r) l'\n\n      let deq (lcons x l,r,l') = (x,make l r l')\n\n      let void (l,r,n) = l = lnil\n\n    *)\n\n  Variable X : Type.\n\n  Implicit Types (l r : lazy_list X).\n\n  Let Q_spec (c : lazy_list X * lazy_list X * lazy_list X) :=\n    match c with (l,r,l') => lazy_length l' + lazy_length r = lazy_length l end.\n\n  Definition fifo := sig Q_spec.\n\n  Implicit Types (q : fifo) (x : X).\n\n  Definition f2l : fifo -> list X.\n  Proof.\n    intros (((l,r),l') & H).\n    exact (lazy2list l ++ rev (lazy2list r)).\n  Defined.\n\n  Definition empty : { q | f2l q = nil }.\n  Proof.\n    assert (H : Q_spec (lazy_nil,lazy_nil,lazy_nil)).\n    { red; rewrite lazy_length_nil; auto. }\n    exists (exist _ _ H).\n    unfold f2l; simpl; auto.\n  Defined.\n\n  Definition make l r l' : lazy_length l' + lazy_length r = 1 + lazy_length l -> { m | lazy2list l ++ rev (lazy2list r) = f2l m }.\n  Proof.\n    induction l' as [ | x l'' _ ] using lazy_list_rect; intros E.\n    + rewrite lazy_length_nil in E; simpl in E.\n      destruct (lazy_rotate l r lazy_nil E) as (l'' & H'').\n      assert (H : Q_spec (l'',lazy_nil,l'')).\n      { red; rewrite lazy_length_nil; omega. }\n      exists (exist _ _ H).\n      unfold Q_spec; simpl.\n      rewrite H''; simpl.\n      rewrite lazy2list_nil.\n      repeat rewrite <- app_nil_end; trivial.\n    + assert (H : Q_spec (l,r,l'')).\n      { red; rewrite lazy_length_cons in E; omega. }\n      exists (exist _ _ H).\n      unfold Q_spec; simpl; auto.\n  Defined.\n\n  Definition enq : forall q x, { q' | f2l q' = f2l q ++ x :: nil }.\n  Proof.\n    intros (((l,r),l') & H) x.\n    refine (let (m,Hm) := make l (lazy_cons x r) l' _ in _).\n    + red in H; rewrite lazy_length_cons; omega.\n    + exists m.\n      simpl; rewrite <- Hm.\n      rewrite lazy2list_cons, app_ass; simpl; auto.\n  Defined.\n\n  Definition deq : forall q, f2l q <> nil -> { c : X * fifo | let (x,q') := c in f2l q = x::f2l q' }.\n  Proof.\n    intros (((l,r),l') & H); revert H; simpl.\n    induction l as [ | x l _ ] using lazy_list_rect.\n    + induction r as [ | y r _ ] using lazy_list_rect; intros H1 H2; exfalso.\n      * destruct H2; rewrite lazy2list_nil; auto.\n      * rewrite lazy_length_cons, lazy_length_nil in H1; omega.\n    + intros H1 H2.\n      refine (let (m,Hm) := @make l r l' _ in _).\n      * rewrite lazy_length_cons in H1; omega.\n      * exists (x,m).\n        rewrite lazy2list_cons; simpl; f_equal; auto.\n  Defined.\n\n  Definition void : forall q, { b : bool | b = true <-> f2l q = nil }.\n  Proof.\n    intros (((l,r),l') & H).\n    induction l as [ | x l _ ] using lazy_list_rect; red in H.\n    + exists true; simpl.\n      split; auto; intros _.\n      induction r as [ | y r _ ] using lazy_list_rect.\n      * rewrite lazy2list_nil; auto.\n      * rewrite lazy_length_cons, lazy_length_nil in H; simpl in H; omega.\n    + exists false; simpl.\n      split; try discriminate.\n      rewrite lazy2list_cons; discriminate.\n  Defined.\n\nEnd fifo_three_lazy_lists.\n\nEnd FIFO_3llists.\n\n\n\n\n", "meta": {"author": "DmxLarchey", "repo": "BFE", "sha": "0bf8376a80ca4378be1630689f6561744d43474e", "save_path": "github-repos/coq/DmxLarchey-BFE", "path": "github-repos/coq/DmxLarchey-BFE/BFE-0bf8376a80ca4378be1630689f6561744d43474e/coq/fifo_3llists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7287293991739069}}
{"text": "Require Import ZArith.\n\nDefinition pos_even_bool (p:positive) : bool :=\n  match p with\n  | xO _ => true\n  | _ => false\n  end.\n\n(* Tests :\n\n\nCompute pos_even_bool 326%positive.\n\nCompute pos_even_bool 3261%positive.\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/ch6_inductive_data/SRC/pos_even_bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7287189169935672}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Ext_Cons.Prod_Cat.Prod_Cat.\nRequire Import Functor.Main.\nRequire Import Basic_Cons.Product.\n\nLocal Open Scope morphism_scope.\n\n(**\nGiven two objects a and b the exponential (bᵃ, denoted 'Exponential a b' below)\nis intuitively the internal representation of homomorphisms from a to b – it is\nsometimes referred to as the internal hom. The notion of exponential is a\ngeneralization of the notion function space from set theory.\n\nDefinition: bᵃ is an object equipped with an evaluation function eval: bᵃ×a -> b\nsuch that for any other object z with arrow f : z×a -> b, we have a unique arrow\nf^ that makes the following diagram commute:\n\n#\n<pre>\n               eval\n        bᵃ×a ——————————> b\n         ↑             ↗\n  bᵃ     |            /\n  ↑      | <f^,idₐ>  /\n  |      |          /\n  |∃!f̂ ^  |         /\n  |      |        / f\n  z      |       /\n         |      /\n         |     /\n         |    /\n         |   /\n         |  /\n         z×a\n</pre>\n#\nwhere <f, g> is the arrow map of the product functor.\n*)\nRecord Exponential {C : Category} {HP : Has_Products C} (c d : Obj) : Type :=\n{\n  exponential : C;\n\n  eval : ((×ᶠⁿᶜ C) _o (exponential, c))%object –≻ d;\n\n  Exp_morph_ex : ∀ (z : C), (((×ᶠⁿᶜ C) _o (z, c))%object –≻ d) → (z –≻ exponential);\n\n  Exp_morph_com : ∀ (z : C) (f : ((×ᶠⁿᶜ C) _o (z, c))%object –≻ d),\n      f = (eval ∘ ((×ᶠⁿᶜ C) @_a (_, _) (_, _) (Exp_morph_ex z f, id c)))%morphism;\n\n  Exp_morph_unique : ∀ (z : C) (f : ((×ᶠⁿᶜ C) _o (z, c))%object –≻ d)\n                       (u u' : z –≻ exponential),\n      f = (eval ∘ ((×ᶠⁿᶜ C) @_a (_, _) (_, _) (u, id c)))%morphism →\n      f = (eval ∘ ((×ᶠⁿᶜ C) @_a (_, _) (_, _) (u', id c)))%morphism →\n      u = u'\n}.\n\nCoercion exponential : Exponential >-> Obj.\n\nArguments Exponential _ {_} _ _, {_ _} _ _.\n\nArguments exponential {_ _ _ _} _, {_ _} _ _ {_}.\nArguments eval {_ _ _ _} _, {_ _} _ _ {_}.\nArguments Exp_morph_ex {_ _ _ _} _ _ _, {_ _} _ _ {_} _ _.\nArguments Exp_morph_com {_ _ _ _} _ _ _, {_ _} _ _ {_} _ _.\nArguments Exp_morph_unique {_ _ _ _} _ _ _ _ _ _ _, {_ _} _ _ {_} _ _ _ _ _ _.\n\nNotation \"a ⇑ b\" := (Exponential a b) : object_scope.\n\n(** Exponentials are unique up to isomorphism. *)\nTheorem Exponential_iso {C : Category} {HP : Has_Products C} (c d : C)\n        (E E' : (c ⇑ d)%object) : (E ≃ E')%isomorphism.\nProof.\n  eapply\n    (\n      Build_Isomorphism\n        _\n        _\n        _\n        (Exp_morph_ex E' _ (eval E))\n        (Exp_morph_ex E _ (eval E'))\n    );\n  eapply Exp_morph_unique; eauto;\n  simpl_ids;\n  match goal with\n      [|- (_ ∘ ?M)%morphism = _] =>\n      match M with\n        (?U _a (?A ∘ ?B, ?C))%morphism =>\n        cutrewrite (M = (U @_a (_, _) (_, _) (A, C))\n                          ∘ (U @_a (_, _) (_, _) (B, C)))%morphism;\n          [|simpl_ids; rewrite <- F_compose; simpl; simpl_ids; trivial]\n      end\n  end;\n  rewrite <- assoc;\n  repeat rewrite <- Exp_morph_com; auto.\nQed.\n\nDefinition Has_Exponentials (C : Category) {HP : Has_Products C} :=\n  ∀ a b, (a ⇑ b)%object.\n\nExisting Class Has_Exponentials.\n\nSection Curry_UnCurry.\n  Context (C : Category) {HP : Has_Products C} {HE : Has_Exponentials C}.\n\n  (** Given a arrow f: a×b -> c in a category with exponentials, the curry of f\n      is f̂f^ in the definition of Exponential above. *)\n  Definition curry :\n    forall {a b c : C},\n      (((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) → (a –≻ (HE b c)) :=\n    fun {a b c : C} (f : ((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) =>\n      Exp_morph_ex (HE b c) _ f.\n\n  (** Given an arrow f: a -> cᵇ, uncurry of f is the arrow \n      (eval_cᵇ ∘ <id_b, f>): a×b -> c.\n      See definition of Exponential above for details. *)\n  Definition uncurry : forall {a b c : C},\n      (a –≻ (HE b c)) → (((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) :=\n    fun {a b c : C} (f : a –≻ (HE b c)) =>\n      ((eval (HE b c)) ∘ ((×ᶠⁿᶜ C) @_a (_, _) (_, _) (f, id C b)))%morphism.\n\n  Section inversion.\n    Context {a b c : C}.\n\n    (** See definition of curry and uncurry above for details.\n        Frollows immediately from the definition of Exponential above. *)\n    Theorem curry_uncurry (f : a –≻ (HE b c)) : curry (uncurry f) = f.\n    Proof.\n      unfold curry, uncurry.\n      eapply Exp_morph_unique; trivial.\n      rewrite <- Exp_morph_com; trivial.\n    Qed.\n    \n    (** See definition of curry and uncurry above for details.\n        Follows immediately from the definition of Exponential above. *)\n    Theorem uncurry_curry (f : ((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) :\n      uncurry (curry f) = f.\n    Proof.\n      unfold curry, uncurry.\n      rewrite <- Exp_morph_com; trivial.\n    Qed.\n\n  End inversion.\n\n  Section injectivity.\n    Context {a b c : C}.\n\n    (** See definition of curry above for details. Follows immediately from \n        uncurry_curry above. *)\n    Theorem curry_injective (f g : ((×ᶠⁿᶜ C) _o (a, b))%object –≻ c) :\n      curry f = curry g → f = g.\n    Proof.\n      intros H.\n      rewrite <- (uncurry_curry f); rewrite <- (uncurry_curry g).\n      rewrite H; trivial.\n    Qed.\n\n    (** See definition of uncurry above for details. \n        Follows immediately from curry_uncurry above. *)\n    Theorem uncurry_injective (f g : a –≻ (HE b c)) :\n      uncurry f = uncurry g → f = g.\n    Proof.\n      intros H.\n      rewrite <- (curry_uncurry f); rewrite <- (curry_uncurry g).\n      rewrite H; trivial.\n    Qed.\n\n  End injectivity.\n\n  Section curry_compose.\n    Context {a b c : C}.\n\n    (** composing with curry is equivalent to compose and then curry: *)\n    Lemma curry_compose (f : ((×ᶠⁿᶜ C) _o (a, b))%object –≻ c)\n          {z : C} (g : z –≻ a)\n      : (curry f) ∘ g = curry (f ∘ (Prod_morph_ex _ _ (g ∘ Pi_1) Pi_2)).\n    Proof.\n      unfold curry.\n      eapply Exp_morph_unique; eauto.\n      rewrite <- Exp_morph_com.\n      match goal with\n          [|- ((_ ∘ (_ _a) ?M) ∘ _)%morphism = _] =>\n          match M with\n              ((?N ∘ ?x)%morphism, id ?y) =>\n              replace M with\n              (compose (_ × _) (_, _) (_, _) (_, _) (x, id y) (N,id y)) by\n                  (cbn; auto)\n          end\n      end.\n      rewrite F_compose.\n      cbn; simpl_ids.\n      rewrite assoc_sym.\n      match goal with\n          [|- (?A ∘ ?B = ?C ∘ ?B)%morphism] => cutrewrite (A = C); trivial\n      end.\n      transitivity (uncurry (curry f));\n        [unfold curry, uncurry; cbn; auto|apply uncurry_curry].\n    Qed.      \n\n  End curry_compose.\n\nEnd Curry_UnCurry.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Basic_Cons/Exponential.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7287189080973652}}
{"text": "\nRequire Import Ensembles Finite_sets Finite_sets_facts.\nRequire Import List ListSet.\nRequire Import util.\n\nOpen Scope list_scope.\n\nSection set_rep.\n\n\nVariable X : Type.\n Hypothesis Xeq_dec : forall (x y:X), {x = y} + {x <> y}.\n\nDefinition InSet : forall U : Type, Ensemble U -> U -> Prop := Ensembles.In.\n\nLemma set_imp_ensemble : forall (s: set X),\nNoDup s ->\nexists E:Ensemble X, (forall x, set_In x s <-> InSet X E x) /\\ \n  exists n, (length s = n) /\\ (cardinal X E n).\nProof.\n  intros s nodup. generalize dependent nodup.\n  induction s; intros nodup.\n  Case \"[]\".\n    exists (Empty_set X).\n    split.\n    SCase \"set_In <-> InSet\".\n      intros x.\n      split. intros setin. inversion setin.\n      intros  inset. inversion inset.\n   SCase \"length = size\".\n     exists 0. \n     split. simpl. reflexivity.\n     constructor.\n Case \"a :: s\".    \n   destruct IHs as [E [Hin Hcard]].\n   inversion nodup; subst. exact H2.\n   exists (Add X E a).\n   split.\n    SCase \"set_In <-> InSet\".\n      intros x.\n      split.\n      SSCase \"->\".\n        destruct (Xeq_dec a x) as [eqax | neqax].\n        intros setIn. subst x.\n        apply Add_intro2.\n        intros setIn.\n        destruct (Hin x) as [setInx InSetx].\n        inversion setIn. assert False as F. apply neqax. exact H. inversion F.\n        apply setInx in H. eapply Add_intro1 in H. exact H.\n      SSCase \"<-\".\n        intros inSet.\n        destruct (Xeq_dec a x) as [eqax | neqax].\n        subst. simpl. left. reflexivity. \n        inversion inSet; subst.\n        apply Hin in H.\n        simpl. right. exact H.\n        inversion H.\n        assert False as F. apply neqax. exact H0. inversion F.\n   SCase \"length = size\".\n     destruct (set_In_dec Xeq_dec a s) as [ins | nins].\n     inversion nodup; subst.\n     assert False as F. apply H1. exact ins. inversion F.\n     destruct Hcard as [n [len card]].\n     exists (S n).\n     split. simpl. auto.\n     apply card_add. exact card.\n     intros contra.\n     destruct (Hin a) as [setIna InSeta].\n     apply InSeta in contra.\n     apply nins. exact contra.\nQed.\n\nLemma set_add_Sn : forall (s: set X) (x: X) (n:nat),\n~ set_In x s ->\nlength s = n ->\nlength (set_add Xeq_dec x s) = S n.\nProof.\n  intros s.\n  induction s.\n  Case \"[]\".\n    intros x n notIn len.\n    simpl. simpl in len.\n    auto.\n  Case \"a :: s\".\n    intros x n notIn len.\n    simpl. destruct (Xeq_dec x a).\n    subst x.\n    assert False as F. apply notIn. simpl. left. reflexivity. inversion F.\n    simpl. rewrite <- len. simpl. destruct n. inversion len.\n    assert (~ set_In x s) as xnotIns. \n      intros contra. apply notIn. simpl. right. exact contra.\n    assert (length s = n) as slen. auto.      \n    rewrite (IHs x n xnotIns slen).\n    subst. \n    reflexivity.\nQed.\n\nLemma set_add_nodup : forall x s,\nNoDup (x :: s) ->\nNoDup (set_add Xeq_dec x s).\nProof.\n  intros x s. generalize dependent x.\n  induction s.\n  Case \"[]\".\n    intros x xnotIn.\n    simpl. exact xnotIn.\n  Case \"a :: s\".\n    intros x nodup.\n    simpl.\n    destruct (Xeq_dec x a) as [eqxa | neqxa].\n    subst. inversion nodup. assert False as F. apply H1. simpl. left. reflexivity. inversion F.\n    inversion nodup; subst. inversion H2; subst.\n    assert (~ In x s) as notxIns.\n      intros contra. apply H1. simpl. right. exact contra.\n    assert (NoDup (x :: s)) as xsnodup.\n      constructor. exact notxIns. exact H4.\n    constructor.\n    intros contra.\n    apply set_add_elim2 in contra.\n    apply H3. exact contra.\n    intros contra2. subst. inversion nodup. apply H5. simpl. left. reflexivity.\n    apply IHs. exact xsnodup.\nQed.\n\nLemma ensemble_imp_set : forall (E: Ensemble X),\nFinite X E ->\nexists s: set X, (forall x, set_In x s <-> InSet X E x) /\\\n  NoDup s /\\\n  exists n, (length s = n) /\\ (cardinal X E n).\nProof.\n  intros E fin.\n  induction fin.\n  Case \"Empty_set\".\n    exists nil.\n    split.\n    intros x. \n    split. intros setIn. inversion setIn.\n    intros inSetx. inversion inSetx.\n    split. constructor.\n    exists 0. split. simpl. reflexivity.\n    apply card_empty.\n  Case \"Add x\".\n    destruct IHfin as [s [Hin [Hnodup Hcard]]].\n    exists (set_add Xeq_dec x s).\n    split.\n     SCase \"set_In <-> InSet\".\n       intros a.\n       split.\n       SSCase \"->\".\n         intros setInx.\n         apply set_add_elim in setInx.\n         destruct setInx as [eqax | aIns].\n         subst a. apply Add_intro2. \n         apply Add_intro1. apply Hin. exact aIns.\n       SSCase \"<-\".\n         intros InSeta.\n         inversion InSeta; subst.\n         apply set_add_intro.\n         right.\n         destruct (Hin a) as [HsetIn HInSet].\n         apply HInSet.\n         exact H0.\n         inversion H0. subst.\n         apply set_add_intro. left. reflexivity.\n       split.\n     SCase \"NoDup s\".\n       assert (~ set_In x s) as xnotIns.\n         destruct (set_In_dec Xeq_dec x s).\n         apply Hin in s0. assert False as F. apply H. exact s0. inversion F.\n         exact n.\n         assert (NoDup (x :: s)) as xsnodup.\n           constructor. exact xnotIns. exact Hnodup.\n           apply set_add_nodup. exact xsnodup.\n     SCase \"length /\\ card\".\n       destruct Hcard as [n [slen Acard]].\n       destruct (set_In_dec Xeq_dec x s).\n       SSCase \"x in s\".\n         destruct (Hin x) as [HsetIn HInSet].\n         assert False as F. apply H. apply HsetIn.\n         exact s0. inversion F.\n       SSCase \"x not in s\".\n         exists (S n).\n         split.\n         apply set_add_Sn. exact n0. exact slen.\n         apply card_add. exact Acard. exact H.\nQed.\n\n\nEnd set_rep.", "meta": {"author": "pnwamk", "repo": "strands", "sha": "b9448aef62151d659cf90b96cc8247dcdd1dbeb5", "save_path": "github-repos/coq/pnwamk-strands", "path": "github-repos/coq/pnwamk-strands/strands-b9448aef62151d659cf90b96cc8247dcdd1dbeb5/set_rep_equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7286874255934329}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom GraphTheory Require Import edone preliminaries digraph mgraph sgraph set_tac.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n(** * Graph Connectivty *)\n\n(** In this file we prove Menger's Theorem and some of its most\nwell-known and most-used corollaries. The proof follows Göring's\n\"Short Proof of Menger's Theorem\".  The two most central notions in\nthe proof are those of an AB-separator and an AB-connector. *)\n\n(** ** Connectors, Separators, and Separations *)\n\nSection SeparatorConnector.\nVariables (G : diGraph).\nImplicit Types (x y z u v : G) (A B S U V : {set G}).\n\n(** There are two notions af separators used in the literature,\n\"AB-separators\" (i.e., sets disconnecting two not necessariliy\ndisjoint sets of vertices) and \"(vertex) separarors\" (i.e., sets of\nvertices disconnecting a given graph). *)\n\nDefinition separator (A B S : {set G}) :=\n  forall (a b : G) (p : Path a b), a \\in A -> b \\in B -> exists2 s, s \\in S & s \\in p.\n\nLemma separatorI A B S : \n  (forall (a b : G) (p : Path a b), irred p -> a \\in A -> b \\in B -> exists2 s, s \\in S & s \\in p)\n  -> separator A B S.\nProof. \n  move => H a b p aA bB. case: (uncycle p) => p' sub_p Ip. case: (H _ _ p') => //.\n  move => s sS /sub_p sp. by exists s.\nQed.\n\nDefinition separatorb (A B S : {set G}) := \n  [forall a in A, forall b in B, forall p : IPath a b, exists s in S, s \\in p].\n\nLemma separatorP (A B S : {set G}) : reflect (separator A B S) (separatorb A B S).\nProof.\n  rewrite /separatorb. apply: (iffP forall_inP) => [H|H a aA].\n  - apply: separatorI => a b p Ip aA bB. \n    move/(_ _ aA) : H => /forall_inP /(_ _ bB) /forallP /(_ (Sub p Ip)) /exists_inP [s sS in_p]. \n    by exists s.\n  - apply/forall_inP => b bB. apply/forallP => [[p ?]]. apply/exists_inP. \n    case: (H a b p) => // s S1 S2. by exists s.\nQed.\n\nLemma separatorPn (A B S : {set G}) : \n  reflect (exists x y (p: IPath x y), [/\\ x \\in A, y \\in B & [disjoint p & S]]) (~~ separatorb A B S).\nProof.\n  rewrite negb_forall_in. apply: (iffP exists_inP). \n  - case => x xA /forall_inPn [y] yB /forallPn [p] /exists_inPn H.\n    exists x; exists y; exists p; split => //. apply/disjointP => z Z1 /H. by rewrite Z1.\n  - case => x [y] [p] [aA yB /disjointP D]. exists x => //. apply/forall_inPn; exists y => //. \n    apply/forallPn; exists p. apply/exists_inPn => z /D H. exact/negP.\nQed.\n\nLemma separator_cap A B S : separator A B S -> A :&: B \\subset S.\nProof.\n  move => sepS. apply/subsetP => x /setIP [xA xB]. \n  case: (sepS _ _ (idp x)) => // s in_S. by rewrite mem_idp => /eqP <-.\nQed.\n\nLemma separator_min A B S : separator A B S -> #|A :&: B| <= #|S|.\nProof. move/separator_cap. exact: subset_leq_card. Qed.\n\nDefinition separates x y U := [/\\ x \\notin U, y \\notin U & forall p : Path x y, exists2 z, z \\in p & z \\in U].\n\n(** Standard trick to show decidability: quantify only over irredundant paths *)\nDefinition separatesb x y U := [&& x \\notin U, y \\notin U & [forall p : IPath x y, exists z in p, z \\in U]].\n\nLemma separatesI x y (U : {set G}) :\n  [/\\ x \\notin U, y \\notin U & forall p : Path x y, irred p -> exists2 z, z \\in p & z \\in U] -> separates x y U.\nProof.\n  case => S1 S2 S3. split => // p. case: (uncycle p) => p' sub_p Ip'. \n  case: (S3 _ Ip') => z Z1 Z2. exists z => //. exact: sub_p.\nQed.\n\nLemma separatesP x y U : reflect (separates x y U) (separatesb x y U).\nProof. \n  apply: (iffP and3P) => [[? ? A]|[? ? A]].\n  - apply: separatesI. split => // p Ip.\n    move/forallP/(_ (Build_IPath Ip)) : A. \n    case/exists_inP => z Z1 Z2. by exists z. \n  - split => //. apply/forallP => p. by move/exists_inP : (A p). \nQed.\nArguments separatesP {x y U}.\n\nFact separatesNeq x y U : separates x y U -> x != y.\nProof. \n  case => Hx _ Hp. apply: contraNN Hx => /eqP C. subst y. case: (Hp (idp x)).\n  move => ?. by rewrite mem_idp => /eqP->. \nQed.\n\n\n(** TOTHINK: [conn_disjoint] could also be expressed as [x \\in p i -> x \\in p j ->  i = j] *)\n(** NOTE: Unlike the definition of Göring, we do not allow single edge paths inside [A :&: B] *)\nRecord connector (A B : {set G}) n (p : 'I_n -> pathS G) : Prop := \n  { conn_irred    : forall i, irred (tagged (p i)); \n    conn_begin    : forall i, [set x in p i] :&: A = [set fst (p i)];\n    conn_end      : forall i, [set x in p i] :&: B = [set lst (p i)];\n    conn_disjoint :  forall i j, i != j -> [set x in p i] :&: [set x in p j] = set0 }.\n\nSection ConnectorTheory.\nVariables (A B : {set G}) (n : nat) (p : 'I_n -> pathS G).\nHypothesis conn_p : connector A B p.\n\nLemma connector_fst i : fst (p i) \\in A.\nProof. \n  move/setP : (conn_begin conn_p i) => /(_ (fst (p i))). \n  rewrite !inE eqxx. by case/andP.\nQed.\n\nLemma connector_lst i : lst (p i) \\in B.\nProof. \n  move/setP : (conn_end conn_p i) => /(_ (lst (p i))). \n  rewrite !inE eqxx. by case/andP.\nQed.\n\nLemma connector_left i x : x \\in p i -> x \\in A -> x = fst (p i).\nProof.\n  move => in_pi in_A. move/setP : (conn_begin conn_p i) => /(_ x). \n  rewrite !inE in_pi in_A /=. by move/esym/eqP.\nQed.\n\nLemma connector_right i x : x \\in p i -> x \\in B -> x = lst (p i).\nProof.\n  move => in_pi in_B. move/setP : (conn_end conn_p i) => /(_ x). \n  rewrite !inE in_pi in_B /=. by move/esym/eqP.\nQed.\n\nLemma lst_idp i : lst (p i) \\in A -> lst (p i) = fst (p i).\nProof.\n  move => H. move/setP : (conn_begin conn_p i) => /(_ (lst (p i))).\n  rewrite !inE H. by move/esym/eqP. \nQed.\n\nLemma fst_idp i : fst (p i) \\in B -> fst (p i) = lst (p i).\nProof.\n  move => H. move/setP : (conn_end conn_p i) => /(_ (fst (p i))).\n  rewrite !inE H. by move/esym/eqP. \nQed.\n\nLemma connector_eq i j x : x \\in p i -> x \\in p j -> i = j.\nProof. \n  move => Hi Hj. apply: contraTeq isT => /(conn_disjoint conn_p)/setP/(_ x).\n  by rewrite !inE Hi Hj.\nQed.\n\nLemma fst_lst_eq i j : fst (p i) = lst (p j) -> i = j.\nProof.\n  move => E. apply: (connector_eq (x := fst (p i))); first exact: fst_mem.\n  by rewrite E lst_mem.\nQed.\n\nLemma fst_inj : injective (@fst G \\o p).\nProof. \n  apply/injectiveP. \n  apply: wlog_neg => /injectivePn [i] [j] /(conn_disjoint conn_p)/setP S /= H.\n  move/(_ (fst (p i))) : S. by rewrite !inE H fst_mem.\nQed.\n\nLemma lst_inj : injective (@lst G \\o p).\nProof. \n  apply/injectiveP. \n  apply: wlog_neg => /injectivePn [i] [j] /(conn_disjoint conn_p)/setP S /= H.\n  move/(_ (lst (p i))) : S. by rewrite !inE H lst_mem. \nQed.\n\nEnd ConnectorTheory.\n\n\nLemma connector_extend A B n (p : 'I_n -> pathS G) x y i : \n  x \\notin \\bigcup_i [set z in p i] -> fst (p i) = y -> x -- y -> x \\notin B ->\n  connector A B p -> exists q : 'I_n -> pathS G, connector (x |: (A :\\ y)) B q.\nProof.\n  move => Hx Hy xy xB conn_p.\n  have xDy : x != y. \n  { apply: contraNneq Hx => ->. apply/bigcupP; exists i => //. by rewrite inE -Hy fst_mem. }\n  set A' := _ |: _.\n  pose q (j : 'I_n) := if j == i then pcatS (PathS (edgep xy)) (p j) else p j. \n  have Hj (j : 'I_n) u : j != i -> u \\in tagged (p j) -> (u == y = false)*(u == x = false).\n  { move => jDi u_pi. split. \n    - apply: contra_eqF (conn_disjoint conn_p jDi) => /eqP ?; subst.\n      apply/set0Pn; exists (fst (p i)). by rewrite !inE u_pi.\n    - apply: contraNF Hx => /eqP <-. apply/bigcupP; exists j => //. by rewrite inE. }\n  exists q. split.\n  - move => j. rewrite /q /=. \n    case: (altP (j =P i)) => [E|D]; last exact: (conn_irred conn_p).\n    subst j. rewrite [p i]pathS_eta. subst y. rewrite pcatSE /= irred_edgeL.\n    rewrite (conn_irred conn_p) andbT. apply: contraNN Hx => Hx.\n    apply/bigcupP. exists i => //. by rewrite inE.\n  - move => j. rewrite /q. case: (altP (j =P i)) => [E|D].\n    + subst j. rewrite [p i]pathS_eta. subst y. rewrite pcatSE /=.\n      apply/setP => u. rewrite [A']lock !inE -lock. apply/andP/idP.\n      * rewrite !inE mem_edgep /=. case: (altP (u =P x)) => [-> //|/=].\n        rewrite -/(fst (p i)). case: (altP (u =P fst (p i))) => [_ _ [_ ?] //|].\n        rewrite /= -/(fst (p i)) => [H1 H2 [H3 H4]].\n        by rewrite -(connector_left conn_p _ H4) ?eqxx in H1.\n      * move/eqP->. by rewrite mem_edgep /= !inE eqxx.\n    + rewrite -(conn_begin conn_p). \n      apply/setP => u. rewrite !inE. case e: (u \\in _) => //=. by rewrite !(Hj j) /=.\n  - move => j.  rewrite /q. case: (altP (j =P i)) => [E|D]; last exact: (conn_end conn_p). \n    subst j. rewrite [p i]pathS_eta. subst y. rewrite pcatSE /= -/(lst _).\n    apply/setP => u. rewrite -(conn_end conn_p i) !inE -mem_pcat. case uB : (u \\in B) => //.\n    rewrite !andbT. apply/edgeLP/idP => /=; last by right. case => [?|//]. \n    subst. by rewrite uB in xB. \n  - move => j1 j2. rewrite /q. \n    have jP j : i != j -> [set x0 in pcatS (PathS (edgep xy)) (p i)] :&: [set x0 in p j] = set0.\n    { move => jDi. rewrite [p i]pathS_eta. subst y. rewrite pcatSE. \n      apply: contra_eq (conn_disjoint conn_p jDi). case/set0Pn => u /setIP []. \n      rewrite 2!inE /=. case/edgeLP => /= [-> Hx'|Hu ?]. \n      * apply: contraNN Hx => _. apply/bigcupP; exists j => //. by rewrite inE.\n      * apply/set0Pn. exists u. by rewrite !inE Hu. }\n    case: (altP (j1 =P i)); case: (altP (j2 =P i)). \n    + move => -> -> . by rewrite eqxx.\n    + rewrite eq_sym => Hj2 ->. exact: jP.\n    + rewrite eq_sym setIC. move => -> Hj2 _. exact: jP.\n    + move => _ _. exact: (conn_disjoint conn_p).\nQed.\n\nLemma connector_sep P A B n (p q : 'I_n -> pathS G) i j x : \n  separator A B P -> connector A P p -> connector P B q -> \n  x \\in p i -> x \\in q j -> (x \\in P) (* * (lst (p i) = fst (q j)) *).\nProof.\n  move => sep_P con_p con_q x_pi x_qj. \n  case def_pi : (p i) => [[u v] /= pi]. \n  case def_qj : (q j) => [[u' v'] /= qj]. rewrite -!/(PathS _) in def_pi def_qj.\n  have [x_pi' x_qj'] : x \\in pi /\\ x \\in qj by rewrite def_pi def_qj in x_pi x_qj.\n  have Ip : irred pi. { move: (conn_irred con_p i). by rewrite def_pi. }\n  have Iq : irred qj. { move: (conn_irred con_q j). by rewrite def_qj. }\n  case/(isplitP Ip) def_p : _ / x_pi' => {Ip} [p1 p2 Ip1 Ip2 Ip].\n  case/(isplitP Iq) def_q : _ / x_qj' => {Iq} [q1 q2 Iq1 Iq2 Iq].\n  case: (sep_P _ _ (pcat p1 q2)).\n  - move: (connector_fst con_p i). by rewrite def_pi.\n  - move: (connector_lst con_q j). by rewrite def_qj.\n  - move => s in_P. rewrite inE. case/orP => [in_p1|in_q2].\n    + suff ? : s = v by subst s; rewrite [v]Ip // inE in in_P.\n      rewrite [s](connector_right con_p (i := i)) // def_pi //. \n      change (s \\in pi). by rewrite def_p inE in_p1.\n    + suff ? : s = u' by subst s; rewrite [u']Iq // inE in in_P.\n      rewrite [s](connector_left con_q (i := j)) // def_qj //. \n      change (s \\in qj). by rewrite def_q inE in_q2.\nQed.\n\nLemma connector_cat (P A B : {set G}) n (p q : 'I_n -> pathS G) : \n  #|P| = n -> separator A B P ->\n  connector A P p -> connector P B q -> \n  exists (r : 'I_n -> pathS G), connector A B r.\nProof.\n  move => card_P. subst n. move => sep_P con_p con_q. \n  (* For every [i], we can obtain some [j] such that [p i] and [q j] compose. *)\n  have mtch i : { j | fst (q j) = lst (p i) }.\n  { pose x := lst (p i).\n    have Hx : x \\in codom (@fst G \\o q). \n    { apply: (inj_card_onto_pred (P := mem P)). \n      - exact: fst_inj con_q.\n      - move => j. exact: connector_fst con_q _.\n      - by rewrite card_ord.\n      - exact: connector_lst con_p _. }\n    exists (iinv Hx). rewrite -[fst _]/((@fst G \\o q) (iinv Hx)). by rewrite f_iinv. }\n  have mtch_inj : injective (fun i => sval (mtch i)).\n  { move => i i' E. move: (svalP (mtch i')). rewrite -E (svalP (mtch i)).\n    exact : (lst_inj con_p). }\n  (* Compose matching paths *)\n  pose pq i := pcatS (p i) (q (sval (mtch i))).\n  (* Elimination lemma for pq to encapsulate dependent types reasoning *)\n  have pqE i : exists j x y z (pi : Path x y) (qi : Path y z), \n      [/\\ p i = PathS pi, j = sval (mtch i), q j = PathS qi & pq i = PathS (pcat pi qi) ].\n  { pose j := sval (mtch i). \n    have jP := svalP (mtch i) : fst (q j) = lst (p i). \n    exists j. exists (fst (p i)). exists (lst (p i)). exists (lst (q j)). \n    exists (tagged (p i)). exists (castL jP (tagged (q j))). split => //.\n    - by rewrite {1}[p i]pathS_eta. \n    - rewrite {1}[q j]pathS_eta. move: (jP). rewrite -jP => jP'.\n      by rewrite (eq_irrelevance jP' erefl).\n    - rewrite /pq -/j. rewrite -pcatSE -pathS_eta. move: (jP). rewrite -jP => jP'.\n      by rewrite (eq_irrelevance jP' erefl) /= -pathS_eta. }\n  have sepP i j x : x \\in p i -> x \\in q j -> x \\in P.\n  { exact: connector_sep sep_P con_p con_q. }\n  exists pq. split. \n  - move => i. move: (pqE i) => [j] [x] [y] [z] [pi] [qj] [Ep Ej Eq ->] /=. \n    apply: irred_catI => [u u_p u_q||]. \n    + have uP : u \\in P. apply: (sepP i j u); rewrite ?Ep ?Eq //.\n      move: (conn_end con_p i) => /setP/(_ u). rewrite Ep !inE /= u_p uP /=. \n      by move/esym/eqP.\n    + move: (conn_irred con_p i). by rewrite Ep.\n    + move: (conn_irred con_q j). by rewrite Eq.\n  - move => i. move: (pqE i) => [j] [x] [y] [z] [pi] [qj] [Ep Ej Eq ->] /=.\n    apply/setP => u. rewrite !inE /=. apply/andP/eqP => [[/orP[u_pi|u_qj] uA]|->].\n    + move/(_ i u): (connector_left con_p). rewrite Ep /= u_pi uA. by apply.\n    + suff ? : u = y. \n      { subst. suff: lst (p i) = fst (p i) by rewrite Ep. \n        apply: (lst_idp con_p _). by rewrite !Ep. }\n      (* y is the only element of P in qj, so if [u != y], the uz-path avoids P *) \n      have Iq : irred qj. move: (conn_irred con_q j). by rewrite Eq.\n      case/(isplitP Iq) def_q : _ / u_qj => [q1 q2 _ _ I].\n      have zB : z \\in B. { move: (connector_lst con_q j). by rewrite Eq. } \n      case: (sep_P _ _ q2) => // s sP in_q2. \n      have ? : s = y. \n      { by rewrite [s](connector_left con_q (i := j)) // Eq // def_q mem_pcat in_q2. }\n      subst s. by rewrite [y]I // inE. \n    + by rewrite inE /fst/= [x](_ : _ = fst (p i)) ?(connector_fst con_p) // Ep. \n  - (* symmetric to the argument above *)\n    move => i. move: (pqE i) => [j] [x] [y] [z] [pi] [qj] [Ep Ej Eq ->] /=.\n    apply/setP => u. rewrite !inE /=. apply/andP/eqP => [[/orP[u_pi|u_qj] uB]|->].\n    + have uz : u = y.\n      { have Ip : irred pi. move: (conn_irred con_p i). by rewrite Ep.\n        case/(isplitP Ip) def_p : _ / u_pi => [p1 p2 _ _ I].\n        have xA : x \\in A. { move: (connector_fst con_p i). by rewrite Ep. } \n        case: (sep_P _ _ p1) => // s sP in_p1. \n        have ? : s = y. \n        { by rewrite [s](connector_right con_p (i := i)) // Ep // def_p mem_pcat in_p1. }\n        subst s. by rewrite [y]I // inE. }\n      subst u. \n      suff: fst (q j) = lst (q j). by rewrite Eq. \n      apply: (fst_idp con_q _). by rewrite Eq. \n    + move/(_ j u): (connector_right con_q). rewrite Eq /= u_qj uB. by apply.\n    + by rewrite inE /lst/= [z](_ : _ = lst (q j)) ?(connector_lst con_q) // Eq.\n  - move => i j iDj.\n    move: (pqE i) => [i2] [x] [y] [z] [pi] [qi2] [Ep Ei Eq ->] /=. \n    move: (pqE j) => [j2] [x'] [y'] [z'] [pj] [qj2] [Ep' Ej Eq' ->] /=.\n    apply/eqP. apply: wlog_neg. case/set0Pn => u. rewrite !inE => /andP[]. \n    case/orP => Hi; case/orP => Hj; case: notF.\n    + move/setP/(_ u): (conn_disjoint con_p iDj). by rewrite Ep Ep' !inE Hi Hj.\n    + have uP : u \\in P. \n      { apply: (@connector_sep P A B _ p q i j2 u) => //; by rewrite ?Ep ?Eq'. }\n      have [? ?] : y' = u /\\ y = u.\n      { split.\n        - by rewrite {1}[u](connector_left con_q (i := j2)) ?Eq'. \n        - by rewrite {1}[u](connector_right con_p (i := i)) ?Ep. }\n      subst y' y. apply: contraNT iDj => _. apply/eqP. apply: mtch_inj. \n      rewrite -Ei -Ej. apply: (connector_eq con_q (x := u)); by rewrite ?Eq ?Eq' inE.\n    + have uP : u \\in P. \n      { apply: (@connector_sep P A B _ p q j i2 u) => // ; by rewrite ?Ep' ?Eq. }\n      have [? ?] : y' = u /\\ y = u. \n      { split.\n        - by rewrite {1}[u](connector_right con_p (i := j)) ?Ep'.\n        - by rewrite {1}[u](connector_left con_q (i := i2)) ?Eq. }\n      subst y' y. apply: contraNT iDj => _. apply/eqP. apply: mtch_inj. \n      rewrite -Ei -Ej. apply: (connector_eq con_q (x := u)); by rewrite ?Eq ?Eq' inE.\n    + apply: contraNT iDj => _. apply/eqP. apply: mtch_inj. rewrite -Ei -Ej.\n      apply: contraTeq isT => iDj.\n      move/setP/(_ u): (conn_disjoint con_q iDj). by rewrite Eq Eq' !inE Hi Hj.\nQed.\n\nLemma trivial_connector A B : exists p : 'I_#|A :&: B| -> pathS G, connector A B p.\nProof.\n  exists (fun i => PathS (idp (enum_val i))). split.\n  - move => i /=. exact: irred_idp.\n  - move => i /=. case/setIP : (enum_valP i) => iA iB. apply/setP => z.\n    rewrite !inE /= mem_idp. case e: (_ == _) => //. by rewrite (eqP e).\n  - move => i /=. case/setIP : (enum_valP i) => iA iB. apply/setP => z.\n    rewrite !inE /= mem_idp. case e: (_ == _) => //. by rewrite (eqP e).\n  - move => i j. apply: contraNeq => /set0Pn [x /setIP[]]. \n    by rewrite !inE /= !mem_idp => /eqP-> /eqP /enum_val_inj->. \nQed.\n\nLemma sub_connector A B n m (p : 'I_m -> pathS G) : \n  n <= m -> connector A B p -> exists q : 'I_n -> pathS G, connector A B q.\nProof.\n  move => n_leq_m conn_p. pose W := widen_ord n_leq_m. exists (fun i => p (W i)).\n  case: conn_p => C1 C2 C3 C4. split => // i j. exact:(C4 (W i) (W j)).\nQed.\n\nEnd SeparatorConnector.\nArguments separatesP {G x y U}.\n\nSection VSeparator.\nVariable (G : sgraph).\nImplicit Types (x y z u v : G) (S U V : {set G}).\n\nLemma separates_sym x y S : separates x y S <-> separates y x S.\nProof.\nsuff X u v: separates u v  S -> separates v u S by split; exact: X.\nmove => [uNS vNS P]; split => // p; have [z] := P (prev p). \nby rewrite mem_prev; exists z.\nQed.\n\nFact separates0P x y : reflect (separates x y set0) (~~ connect edge_rel x y).\nProof.\n  apply:(iffP idP) => [nconn_xy|]. \n  - rewrite /separates !inE. split => // p. by rewrite Path_connect in nconn_xy.\n  - case => _ _ H. apply/negP. case/connect_irredP => p _. case: (H p) => z. by rewrite inE.\nQed.\n\nLemma opn_separates x y : x != y -> ~~ x -- y -> separates x y N(x).\nProof.\nmove=> xDy xNy. split; rewrite ?inE ?sg_irrefl // => p.\ncase: (splitL p) => // x' [xx'] [p'] [->] _. by exists x'; rewrite !inE.\nQed.\n\n(** TODO: this does not actually depend on G being simple *)\nLemma separatesNE x y (U : {set G}) :\n  x \\notin U -> y \\notin U -> ~ separates x y U -> connect (restrict [predC U] edge_rel) x y.\nProof.\n  move => xU yU /(introN separatesP). rewrite /separatesb xU yU !negb_and //= negb_forall.\n  case: (altP (x =P y)) => [<-|xDy H]; first by rewrite connect0.\n  apply/connect_irredRP => //. case/existsP : H => p Hp. exists p => //.\n  exact/subsetP/(exists_inPn Hp). \nQed.\n\nLemma induced_separates (V : {set G}) (S : {set induced V}) (x y : induced V) :\n  separates x y S -> separates (val x) (val y) (val @: S :|: ~:V).\nProof.\ncase => xS yS sepS.\nsplit => [||p]; rewrite ?inE ?negb_or ?negbK ?mem_imset ?xS ?yS ?(valP x) ?(valP y) //=. \ncase: (boolP (p \\subset V)) => [/subsetP subA|/subsetPn [z Z1 Z2]]; last first.\n   by exists z; rewrite ?inE ?Z1 ?Z2.\nhave [q nodes_q] := Path_to_induced subA.\nhave [z Z1 Z2] := sepS q.\nexists (val z); by [rewrite mem_path -nodes_q map_f|rewrite !inE mem_imset ?Z2].\nQed.\n\n\nDefinition vseparator U := exists x y, separates x y U.\n\nLemma vseparatorNE U x y : ~ vseparator U -> ~ separates x y U.\nProof. move => nsepU sepU. by apply nsepU; exists x; exists y. Qed.\n\nLemma separates_vseparator (x y : G) (S : {set G}) : \n  separates x y S -> vseparator S. \nProof. by firstorder. Qed.\n\nLemma svseparator_connected S : \n  smallest vseparator S -> 0 < #|S| -> connected [set: G].\nProof.\n  move => SS gt0 x y _ _.\n  have: (connect (restrict [predC set0] sedge) x y).\n  { apply (@separatesNE x y set0); rewrite ?inE => //. rewrite -(@cards0 G) in gt0. \n    move: (below_smallest SS gt0). exact: vseparatorNE. }\n  rewrite !restrictE //; intro; rewrite !inE //.\nQed.\n\n(** vseparators do not make precises what the separated comonents are,\ni.e., a vseparator can disconnect the graph into more than two\ncomponents. Hence, we also define separations, which make the\nseparated sides explicit *)\nDefinition separation V1 V2 := \n  ((forall x, x \\in V1 :|: V2) * (forall x1 x2, x1 \\notin V2 -> x2 \\notin V1 -> x1 -- x2 = false))%type.\n\nLemma sep_inR x V1 V2 : separation V1 V2 -> x \\notin V1 -> x \\in V2.\nProof. move => sepV. by case/setUP : (sepV.1 x) => ->. Qed.\n\nLemma sep_inL x V1 V2 : separation V1 V2 -> x \\notin V2 -> x \\in V1.\nProof. move => sepV. by case/setUP : (sepV.1 x) => ->. Qed.\n\nDefinition proper_separation V1 V2 := separation V1 V2 /\\ exists x y, x \\notin V2 /\\ y \\notin V1.\n\nLemma separate_nonadjacent x y : x != y -> ~~ x -- y -> proper_separation [set~ x] [set~ y].\nProof.\n  move => xDy xNy. split; last by exists y; exists x; rewrite !inE !eqxx.\n  split => [z | x1 x2].\n  - rewrite !inE -negb_and. by apply: contraNN xDy => /andP[/eqP->/eqP->].\n  - rewrite !inE !negbK sg_sym => /eqP-> /eqP->. by rewrite (negbTE xNy).\nQed.\n\nLemma separation_separates x y V1 V2:\n  separation V1 V2 -> x \\notin V2 -> y \\notin V1 -> separates x y (V1 :&: V2).\nProof.\n  move => sepV Hx Hy. split; rewrite ?inE ?negb_and ?Hx ?Hy // => p.\n  case: (@split_at_first G (mem V2) x y p y) => // ; rewrite ?(sep_inR sepV) //.\n  move => z [p1 [p2 [H1 H2 H3]]]. rewrite inE in H2. \n  exists z; rewrite ?H1 !inE ?H2 // andbT.\n  case: (@splitR G x z p1) => [|z0 [p1' [z0z H4]]]. \n  { by apply: contraTneq H2 => <-. }\n  apply: contraTT (z0z) => Hz1. rewrite sepV ?inE //.\n  apply: contraTN (z0z) => H0. by rewrite [z0]H3 ?sgP // H4 !inE.\nQed.\n\nLemma proper_vseparator V1 V2 :\n  proper_separation V1 V2 -> vseparator (V1 :&: V2).\nProof.\n  case => Hsep [x] [y] [Hx Hy]. exists x. exists y. exact: separation_separates. \nQed.\n\nLemma vseparator_separation S : \n  vseparator S -> exists V1 V2, proper_separation V1 V2 /\\ S = V1 :&: V2.\nProof.\n  move => [x [y sepS]]; have xDy := separatesNeq sepS.  \n  set U := locked [set z in ~: S | connect (restrict (~: S) sedge) x z].\n  set V1 := U :|: S; set V2 := ~: U; exists V1, V2.\n  move: sepS => [S1 S2 P12];  split; first split; first split.\n  - by rewrite /V1 /V2; set_tac.\n  - move=> u v. rewrite !inE negbK negb_or => Hu /andP [Hv1 Hv2].\n    apply: contraNF Hv1 => uv.\n    move: (Hu); rewrite /U -lock !inE Hv2 /= => /andP [uNS H]. \n    by apply: connect_trans H (connect1 _); rewrite /= !inE uNS Hv2.\n  - exists x,y; split; first by rewrite !inE negbK /U -lock !inE connect0.\n    rewrite !inE negb_or S2 andbT; apply: contraTN isT.\n    rewrite /U -lock !inE => /andP [_ /connect_irredRP -/(_ xDy) [p Ip subS]].\n    by have [s ?] := P12 p; set_tac.\n  - apply/setP => z;rewrite !inE andb_orl andbN /= andb_idr // => z_S.\n    by rewrite /U -lock !inE z_S.\nQed.\n\nLemma proper_separation_card V1 V2 : \n  proper_separation V1 V2 -> (#|V1| < #|G|)%type * (#|V2| < #|G|)%type.\nProof.\nby case => [_ [x2 [x1 [HV1 HV2]]]]; rewrite (card_ltnT HV1) (card_ltnT HV2).\nQed.\n\nDefinition vseparatorb U := [exists x, exists y, separatesb x y U].\n\nLemma vseparatorP U : reflect (vseparator U) (vseparatorb U).\nProof. rewrite /vseparator /vseparatorb.\n  apply: (iffP existsP).\n  - move => [x /existsP [y /separatesP H]]. exists x; exists y; done.\n  - move => [x [y H]]. exists x. apply /existsP. exists y. by apply /separatesP.\nQed.\n\nLemma minimal_separation x y : x != y -> ~~ x -- y -> \n  exists V1 V2, proper_separation V1 V2 /\\ smallest vseparator (V1 :&: V2).\nProof.\n  move => xDy xNy. \n  move/proper_vseparator/vseparatorP : (separate_nonadjacent xDy xNy) => sep.\n  case: (arg_minnP (fun S => #|S|) sep) => U /vseparatorP sepU HU {sep xDy xNy}.\n  move: (vseparator_separation sepU) => [V1 [V2 [ps UV]]].\n  exists V1; exists V2. repeat split => //; rewrite -UV // => V /vseparatorP. exact: HU.\nQed.\n\nLemma separation_sym V1 V2 : separation V1 V2 <-> separation V2 V1.\nProof.\n  wlog suff W : V1 V2 / separation V1 V2 -> separation V2 V1. { split; exact: W. }\n  move => sepV. split => [x|x1 x2 A B]; by rewrite 1?setUC 1?sgP sepV. \nQed.\n\nLemma proper_separation_symmetry V1 V2 :\n  proper_separation V1 V2 <-> proper_separation V2 V1.\nProof. rewrite /proper_separation separation_sym. by firstorder. Qed.\n\nLemma svseparator_neighbours V1 V2 s : \n  proper_separation V1 V2 -> smallest vseparator (V1 :&: V2) -> \n  s \\in V1 :&: V2 -> exists x1 x2, [/\\ x1 \\notin V2, x2 \\notin V1, s -- x1 & s -- x2].\nProof.\n  wlog: V1 V2 / [forall x1, (x1 \\notin V2) ==> ~~ s -- x1].\n  { move => H ps ss sS.\n    case (boolP [forall x1, (x1 \\notin V2) ==> ~~ s -- x1]).\n    - move => HH. apply (H V1 V2) => //.\n    - move => /forall_inPn [x1 x1V /negPn sx1].\n      case (boolP [forall x, (x \\notin V1) ==> ~~ s -- x]).\n      + move => HH. rewrite setIC in sS ss. case (H V2 V1) => //.\n        * by apply proper_separation_symmetry.\n        * move => y [z [? ? ? ?]]. exists z; exists y. split; done.\n      + move => /forall_inPn [x2 x2V sx2].\n        exists x1; exists x2. split => //; by apply negbNE. }\n  move => /forall_inP Hwlog [sepV [x1] [x2] [x1V12  x2V21]] smallS sS.\n  pose S' := V1 :&: V2:\\ s. \n  suff: vseparator S'.\n  - move => sS'. case: (below_smallest (V := S') smallS) => //. \n    by rewrite /S' (cardsD1 s (V1 :&: V2)) sS. \n  - (* cant use [vseparator S], because the two vertices could be both in V2 *)\n    exists x1; exists x2. split; try by rewrite /S' notinD.\n    + move => p.\n      case: (@split_at_first G (mem V2) x1 x2 p x2) => //.\n      { by rewrite (sep_inR sepV x2V21). }\n      move => z [p1 [p2 [H1 H2 H3]]]. rewrite inE in H2. \n      exists z; first by rewrite H1 !inE. \n      case: (@splitR G x1 z p1).\n      { apply: contraTN isT => /eqP ?. subst x1; contrab. }\n      move => z0 [p' [z0z Hp']].\n      have z0V1: z0 \\notin V2. \n      { apply: contraTN (z0z) => ?. by rewrite [z0]H3 ?sgP // Hp' !inE. }\n      rewrite !inE H2 andbT. apply/andP; split.\n      * apply: contraTN (z0z) => /eqP->. by rewrite sgP Hwlog.\n      * apply: contraTT (z0z) => ?. by rewrite sepV.\nQed.\n\n(** Note: This generalizes the corresponding lemma on checkpoints *)\nLemma avoid_nonseperator U x y : ~ vseparator U -> x \\notin U -> y \\notin U -> \n  exists2 p : Path x y, irred p & [disjoint p & U].\nProof.\n  move => nsep_u xU yU. \n  case: (altP (x =P y)) => [?|A];first subst y.\n  - exists (idp x); first exact: irred_idp. \n    rewrite (@eq_disjoint1 _ x) // => y. by rewrite mem_idp.\n  - have/separatesNE/connect_irredRP : ~ separates x y U by apply vseparatorNE.\n    case => // p irr_p. rewrite -disjoint_subset. by exists p.\nQed.\n\nLemma svseparator_uniq x y S:\n  smallest vseparator S -> separates x y S -> S != set0 ->\n  exists2 p : Path x y, irred p & exists! z, z \\in p /\\ z \\in S.\nProof.\n  (* Since [S != set0], [G] is connected. Assume every path needs to\n  visit at least two distinct vertices fro [S]. Thus, there exists a\n  vertex in [S], say [s], such that every xy-path through [s] must\n  vist another node. Then [S :\\ s] separates [x] and [y],\n  contradiction. *)\nAbort.\n\n\nLemma separation_connected_same_component V1 V2:\n  separation V1 V2 -> forall x0 x, x0 \\notin V2 ->\n  connect (restrict [predC (V1:&:V2)] sedge) x0 x -> x \\notin V2.\nProof.\n  set S := V1 :&: V2.\n  move => sepV x0 x x0NV2.\n  case: (boolP (x0==x)) => [/eqP ? | x0x]; first by subst x0.\n  case/(connect_irredRP x0x) => p _ /subsetP Hp.\n  case: (boolP(x \\in V2)) => // xV2.\n  case: (@split_at_first G (mem V2) x0 x p x) => //.\n    move => z [p1 [p2 [H1 H2 H3]]]. rewrite inE /= in H2.\n  case: (altP (x0 =P z)) => ?; first by subst x0; contrab.\n  case: (@splitR G x0 z p1) => [|z0 [p1' [z0z H4]]] //.\n  apply: contraTT (z0z) => _. rewrite sepV //.\n  + apply: contraTN (z0z) => z0V2. by rewrite [z0]H3 ?sgP // H4 !inE.\n  + have ? : (z \\notin S) by apply: Hp; rewrite H1 !inE. by subst S; set_tac.\nQed.\n\nLemma diso_separation V1 V2 : \n  separation V1 V2 -> [disjoint V1 & V2] -> \n  diso ((induced V1) ∔ (induced V2))%sg G.\nProof.\nmove => sepV disV; have V2E : V2 = ~: V1.\n{ apply/setP => x; rewrite inE; apply/idP/idP => Hx.\n    by rewrite (disjointFl disV Hx).\n  exact: sep_inR Hx. }\nrewrite V2E; apply: ssplit_disconnected => x y ? ?.\nby rewrite sepV // V2E inE negbK.\nQed.\n\nEnd VSeparator.\nArguments vseparator {G} _.\n\n(** lifing a [vseparator] from an induced subgraph *)\nLemma induced_vseparator (G : sgraph) (A : {set G}) (S : {set induced A}) : \n  vseparator S -> vseparator (val @: S :|: ~: A).\nProof. by move => [x] [y] /induced_separates ?; exists (val x); exists (val y). Qed.\n\n\n(** Lifting separations to/from [add_edge] *)\n\nSection AddEdgeSep.\n\nLocal Arguments separation : clear implicits.\nLocal Arguments proper_separation : clear implicits.\nLocal Arguments vseparator : clear implicits.\n\nLemma add_edge_separation' (G : sgraph) (V1 V2 : {set G}) x y:\n  separation (add_edge x y) V1 V2 -> separation G V1 V2.\nProof.\n  move=> [covV sepV]; split => // u v Hu Hv. \n  by apply: contraFF (sepV _ _ Hu Hv); rewrite [in X in _ -> X]/edge_rel/= => ->.\nQed.\n\nLemma add_edge_separation (G : sgraph) V1 V2 x y:\n  x \\in V1:&:V2 -> y \\in V1:&:V2 -> separation G V1 V2 -> separation (add_edge x y) V1 V2.\nProof.\n  move => xS yS sep.\n  split; first by move => z; apply sep. \n  move => x1 x2 x1V2 x2V1 /=. rewrite /edge_rel/= sep //=.\n  apply: contraTF isT. case/orP => [] /and3P[_ /eqP ? /eqP ?]; by set_tac.\nQed.\n\nLemma add_edge_proper_separation (G : sgraph) (V1 V2 : {set G}) x y :\n  x \\in V1 :&: V2 -> y \\in V1 :&: V2 -> \n  proper_separation G V1 V2 -> proper_separation (add_edge x y) V1 V2.\nProof.\nmove => xV yV [sepV properV]; split => //. exact: add_edge_separation sepV.\nQed.\n\nLemma add_edge_proper_separation' (G : sgraph) (V1 V2 : {set G}) x y :\n  proper_separation (add_edge x y) V1 V2 -> proper_separation G V1 V2.\nProof.\nmove => [sepV properV]; split => //. exact: add_edge_separation' sepV.\nQed.\n\nLemma add_edge_vseparator' (G : sgraph) (x y : G) (S : {set G}) :\n  vseparator (add_edge x y) S -> vseparator G S.\nProof.\nmove=> /vseparator_separation [V1 [V2 [psepV ?]]]; subst S.\napply: proper_vseparator; exact: add_edge_proper_separation' psepV.\nQed.\n\nLemma add_edge_vseparator (G : sgraph) (x y : G) (S : {set G}) :\n  x \\in S -> y \\in S -> vseparator G S -> vseparator (add_edge x y) S.\nProof.\nmove => xS yS /vseparator_separation [V1 [V2 [psepV ?]]]; subst S.\nby apply: proper_vseparator; exact: add_edge_proper_separation.\nQed.\n\nLemma add_edge_smallest_vseparator (G : sgraph) (x y : G) (S : {set G}) :\n  x \\in S -> y \\in S -> \n  smallest (vseparator G) S -> smallest (vseparator (add_edge x y)) S.\nProof.\nmove=> xS yS [sepS smallS]; split => [|U]; first exact: add_edge_vseparator.\nmove/add_edge_vseparator'; exact: smallS.\nQed.\n\nEnd AddEdgeSep.\n\nArguments separator : clear implicits.\nArguments separatorb : clear implicits.\n\nLemma connector_nodes (T : finType) (e1 e2 : rel T) (A B : {set T}) : \n  forall s (p : 'I_s -> pathS (DiGraph e1)) (q : 'I_s -> pathS (DiGraph e2)), \n  (forall i, nodes (tagged (p i)) = nodes (tagged (q i)) :> seq T) -> \n  @connector (DiGraph e1) A B s p -> @connector (DiGraph e2) A B s q.\nProof.\n  set G1 := DiGraph e1. set G2 := DiGraph e2.\n  move => s p q Epq [C1 C2 C3 C4]. \n  have Spq : forall i, [set x in p i] = [set x in q i]. \n  { move => i. apply/setP => z. by rewrite !inE !mem_path Epq. }\n  split.\n  - move => i /=. rewrite irredE -Epq -(@irredE G1). exact: C1.\n  - move => i /=. rewrite -Spq C2. f_equal. \n    move: (Epq i). case: (p i) => [[x y] pi]. case: (q i) => [[x' y'] qi].\n    rewrite /fst /=. rewrite !nodesE. by case.\n  - move => i /=. rewrite -Spq C3. f_equal. \n    move: (Epq i). case: (p i) => [[x y] pi]. case: (q i) => [[x' y'] qi].\n    rewrite /lst /= in pi qi *. rewrite !nodesE => [[E1 E2]]. \n    by rewrite -(path_last pi) -(path_last qi) /= E2 E1.\n  - move => i j /C4. by rewrite -!Spq.\nQed.\n \nLemma del_edge_connector (G : diGraph) (a b : G) (A B : {set G}) s (p : 'I_s -> pathS (del_edge a b)) : \n  @connector (del_edge a b) A B s p -> connector A B (fun i : 'I_s => del_edge_liftS (p i)).\nProof.\n  destruct G. apply: connector_nodes => i. \n  case: (p i) => [[x y] pi] /=. by rewrite !nodesE. \nQed.\n\n(** ** Menger's Theorem *)\n\nTheorem Menger (G : diGraph) (A B : {set G}) s : \n  (forall S, separator G A B S -> s <= #|S|) -> exists (p : 'I_s -> pathS G), connector A B p.\nProof.\n  move: G s A B. elim/(size_ind num_edges) => G IH s A B min_s. \n  case: (boolP [exists x : G, exists y : G, x -- y]) => [E|E0]; last first.\n  - suff Hs : s <= #|A :&: B|. \n    { case: (trivial_connector A B) => p. exact: sub_connector. }\n    apply: min_s. apply: separatorI => a b p aA bB. case: (altP (a =P b)) => [?|aDb].\n    + subst b. exists a => //. by set_tac.\n    + move/existsPn : E0 => /(_ a). case: (splitL p aDb) => x [ax] _.\n      move/existsPn => /(_ x). by rewrite ax. \n  - case/existsP : E => x /existsP [y xy].\n    pose G' := del_edge x y.\n    have HG' : num_edges G' < num_edges G by exact: card_del_edge. \n    move/(_ _ HG' s) in IH.\n    case: (boolP [exists S : {set G'}, separatorb G' A B S && (#|S| < s)]); last first.\n    { move/exists_inPn => Hs. case: (IH A B) => [S sepS|p conn_p].\n      - rewrite leqNgt Hs //. exact/separatorP. \n      - exists (fun i : 'I_s => del_edge_liftS (p i)). exact: del_edge_connector. }\n    case/exists_inP => S /separatorP sepS ltn_s. \n    pose P := x |: S.\n    have xP : x \\in P by rewrite /P; set_tac.\n    pose Q := y |: S.\n    have yQ : y \\in Q by rewrite /Q; set_tac.\n    have [sep_G_P sep_G_Q] : separator G A B P /\\ separator G A B Q.\n    { have Hp (a b : G) (p : Path a b) : \n        irred p -> a \\in A -> b \\in B -> (x \\in p /\\ y \\in p) \\/ exists2 s, s \\in S & s \\in p.\n      { move => Ip aA bB. case: (del_edge_path_case x y Ip).\n        - move => [p1] [p2] [H1 H2 H3]. left. \n          rewrite !mem_path H1 !mem_cat. by rewrite -!(@mem_path G') !inE.\n        - move => [p1 Ep]. right. case/sepS : (p1) => // z Z1 Z2. exists z => //.\n          by rewrite (@mem_path G) Ep -(@mem_path G'). }\n      split; apply: separatorI => a b p Ip aA bB. \n      all: case: (Hp _ _ _ Ip aA bB) => [[xp yp]|[s0 in_S in_p]]. \n      all: solve [by exists x | by exists y | exists s0; rewrite /P /Q; set_tac]. }\n    have lift_AP T : separator G' A P T -> separator G A B T.\n    { move => sepT. apply/separatorI => a b p Ip aA bB. \n      case: (del_edge_path_case x y Ip).\n      - move => [p1] [p2] [E Nx Ny]. case/sepT : (p1) => // t T1 T2.  \n        exists t => //. by rewrite mem_path E mem_cat -(@mem_path G') T2.\n      - case. case => p' Ip' /= E. case/sep_G_P : (p) => // z zP zp. \n        have zp' : z \\in p' by rewrite (@mem_path G') -E -(@mem_path G).\n        case: (split_at_first (D := G') zP zp') => u [p1] [p2] [E' uP ?].\n        case/sepT : (p1) => // t tT tp1. exists t => //. \n        by rewrite mem_path E -(@mem_path G') E' mem_pcat tp1. }\n    have lift_QB T : separator G' Q B T -> separator G A B T.\n    { (* same as above -- generalize? *) \n      move => sepT. apply/separatorI => a b p Ip aA bB. \n      case/sep_G_Q : (p) => // z zP zp. case: (del_edge_path_case x y Ip).\n      - move => [p1] [p2] [E Nx Ny]. case/sepT : (p2) => // t T1 T2.  \n        exists t => //. by rewrite mem_path E mem_cat -(@mem_path G') T2.\n      - case. case => p' Ip' /= E. \n        have zp' : z \\in p' by rewrite (@mem_path G') -E -(@mem_path G). \n        case: (split_at_first (D := G') zP zp') => u [p1] [p2] [E' uP ?].\n        case/sepT : (p2) => // t tT tp1. exists t => //. \n        by rewrite mem_path E -(@mem_path G') E' mem_pcat tp1. } \n    have size_AP T : separator G' A P T -> s <= #|T|. move/lift_AP. exact: min_s.\n    have size_QB T : separator G' Q B T -> s <= #|T|. move/lift_QB. exact: min_s.\n    have card_S u : separator G A B (u |: S) -> u \\notin S /\\ s = #|u |: S|.\n    { move => HS. \n      have Hu : u \\notin S. \n      { apply: contraTN ltn_s => uS. by rewrite -leqNgt min_s // -(setU1_mem uS). }\n      split => //. apply: esym. apply/eqP. \n      by rewrite eqn_leq min_s // andbT cardsU1 Hu /= add1n. }\n    case: (IH _ _ size_AP) => X (* /del_edge_connector *) conn_X.\n    case: (IH _ _ size_QB) => Y (* /del_edge_connector *) conn_Y.\n    have [i Hi] : exists j, lst (X j) = x. \n    { suff : x \\in codom (fun j => lst (X j)) by case/mapP => j _ ->; exists j.\n      apply: inj_card_onto_pred xP. \n      - exact: lst_inj conn_X.\n      - exact: connector_lst conn_X.\n      - rewrite card_ord. by apply card_S. }\n    have xB : x \\notin B. \n    { move: (connector_fst conn_X i) => HA. \n      move: (conn_end conn_X i). rewrite Hi => HP.\n      case: (card_S _ sep_G_P) => xS _. apply: contraNN xS => xB. \n      have [u U1 U2] : exists2 u, u \\in S & u \\in X i. \n      { rewrite -Hi in xB. case: (X i) HA xB => [[a b] /= p]. exact: sepS. }\n      move/setP/(_ u)/esym : HP. by rewrite !inE U1 U2 orbT /= => /eqP <-. }\n    move/del_edge_connector : (conn_X) => conn_X'.\n    move/del_edge_connector : (conn_Y) => conn_Y'.\n    case: (altP (x =P y)) => [?|xDy]. \n    { subst y. apply: connector_cat conn_X' conn_Y' => //. by apply esym,card_S. } \n    have [j jP] : exists i : 'I_s, fst (Y i) = y :> G. \n    { suff : y \\in codom (fun j => fst (Y j)) by case/mapP => j _ ->; exists j.\n      apply: inj_card_onto_pred (_ : y \\in Q). \n      - exact: fst_inj conn_Y.\n      - exact: connector_fst conn_Y.\n      - rewrite card_ord. by apply card_S. \n      - by rewrite !inE eqxx. }\n    case: (connector_extend (G := G) (i := j) _ _ xy xB conn_Y') => //. \n    + move => {j jP}.\n      apply/negP => /bigcupP [j] _. rewrite inE mem_del_edge_liftS => xYj. \n      case EYj : (Y j) => [[u v] /= p]. rewrite -/(PathS p) in EYj.\n      have Ip : irred p. { move: (conn_irred conn_Y j). by rewrite EYj. }\n      have xp : x \\in p by rewrite EYj in xYj.\n      case/(isplitP Ip) def_p : _ / xp => [p1 p2 Ip1 Ip2 I]. \n      case EXi : (X i) => [[a x'] /= q]. rewrite -/(PathS q) in EXi.\n      have ? : x' = x by rewrite -Hi EXi. subst x'.\n      case: (sepS a v (pcat q p2)) => [||t t_in_S].\n      * move: (connector_fst conn_X i). by rewrite EXi.\n      * move: (connector_lst conn_Y j). by rewrite EYj.\n      * rewrite inE. case/orP => Ht.\n        -- move: (t_in_S).  \n           rewrite [t](connector_right conn_X (i := i)) ?EXi ?inE ?t_in_S /lst //=.\n           apply/negP. by apply card_S.\n        -- move: (t_in_S). apply/negP. rewrite [t]I //; first by apply card_S.\n           rewrite [t](connector_left conn_Y (i := j)) ?inE ?t_in_S //.\n           ++ rewrite EYj /fst /=. by rewrite (@path_begin G').\n           ++ by rewrite EYj -[_ \\in _]/(t \\in p) def_p inE Ht.\n    + by case: (Y j) jP => [[a b] p].\n    + move => Y'. rewrite [_ |: _](_ : _ = P) => [conn_xY|].\n      * apply: connector_cat conn_X' conn_xY => //. by apply esym,card_S.\n      * apply/setP => u. rewrite /Q setU1K //. by apply card_S.\nQed.\n\n(** ** Independent Path Corollaries *)\n\n(** *** Vertex version *)\n\n\nCorollary theta (G : diGraph) (x y : G) s :\n  ~~ x -- y -> x != y ->\n  (forall S, separates x y S -> s <= #|S|) -> \n  exists p : 'I_s -> IPath x y, forall i j : 'I_s, i != j -> independent (p i) (p j).\nProof.\n  move => xNy xDy min_s. \n  pose G' := digraph.induced (~: [set x;y]).\n  pose A := [set z : G' | x -- val z].\n  pose B := [set z : G' | val z -- y].\n  (* Every AB-separator also separates x and y *)\n  have sepAB S : separator G' A B S -> separates x y [set val x | x in S].\n  { move => sepS. apply: separatesI; split.\n    - apply/negP. case/imsetP => x' _ E. move: (valP x'). by rewrite !inE -E eqxx.\n    - apply/negP. case/imsetP => y' _ E. move: (valP y'). by rewrite !inE -E eqxx orbT.\n    - move => p Ip. case: (splitL p xDy) => a [xA] [p'] [Ep _].\n      have aDy : (a != y) by apply: contraNneq xNy => <-. \n      case: (splitR p' aDy) => b [q] [By] Ep'. \n      have Hq : {subset q <= ~: [set x;y]}.\n      { subst. rewrite irred_edgeL irred_edgeR mem_pcat_edgeR (negbTE xDy) /= in Ip.\n        case/and3P : Ip => I1 I2 _ u. rewrite inE. \n        apply: contraTN. case/setU1P => [->//|]. by move/set1P->. }\n      have [Ha Hb] : a \\in ~: [set x;y] /\\ b \\in ~: [set x;y] by split; apply: Hq.\n      case: (@digraph.Path_to_induced G (~: [set x;y]) (Sub a Ha) (Sub b Hb) q Hq) => q' Eq. \n      case: (sepS _ _ q'); rewrite ?inE // => s0 in_S in_q'.\n      exists (val s0); last exact: imset_f. subst. \n      by rewrite !inE [_ \\in q]mem_path -Eq map_f. }\n  have min_s' S : separator G' A B S -> s <= #|S|.\n  { move => HS. \n    rewrite -[#|S|](_ : #|[set val x | x in S]| = _) ?min_s ?card_imset //. \n    + exact: sepAB.\n    + exact: val_inj. }\n  have [p conn_p] := Menger min_s'.\n  have xA (i : 'I_s) : x -- val (fst (p i)).\n  { move: (connector_fst conn_p i). by rewrite inE. } \n  have By (i : 'I_s) : val (lst (p i)) -- y.\n  { move: (connector_lst conn_p i). by rewrite inE. } \n  have X (i : 'I_s) : { pi : @IPath G x y | interior pi = [set val x | x in p i] }.\n  { case def_pi : (p i) => [[a b] /= pi]. rewrite -/(PathS pi) in def_pi *.\n    case: (digraph.Path_from_induced pi) => pi' P1 P2. \n    have [? ?] : a = fst (p i) /\\ b = lst (p i) by rewrite def_pi.\n    subst. \n    set q := (pcat (edgep (xA i)) (pcat pi' (edgep (By i)))).\n    have Iq : irred q. \n    { rewrite /q irred_edgeL irred_edgeR mem_pcat_edgeR negb_or xDy /=. apply/and3P;split.\n      - apply/negP => /P1. by rewrite !inE eqxx.\n      - apply/negP => /P1. by rewrite !inE eqxx orbT.\n      - rewrite irredE P2 map_inj_uniq; last exact: val_inj. \n        move: (conn_irred conn_p i). by rewrite -(@irredE G') [in irred _]def_pi. }\n    exists (Sub q Iq).\n    apply/setP => u. apply/setDP/imsetP => [[U1 U2]|].\n    - move: (U2) U1. rewrite 4!inE negb_or mem_pcat_edgeL mem_pcat_edgeR => /andP [/negbTE-> /negbTE->] /=.\n      by rewrite mem_path P2 => /mapP. \n    - case => u' => U1' U2'. rewrite -in_setC U2' (valP u') !inE [_ \\in pi'](_ : _ = true) //.\n      rewrite mem_path P2 mem_map //. }\n  exists (fun i => sval (X i)). \n  + move => i j iDj. apply/disjointP => u. rewrite (svalP (X i)) (svalP (X j)).\n    case/imsetP => u1 UP1 UE1. case/imsetP => u2 UP2 UE2. \n    have ? : u1 = u2 by apply: val_inj; congruence.\n    subst u2. by rewrite [i](connector_eq conn_p UP1 UP2) eqxx in iDj.\nQed.\n\n(** In addition to the independent paths, we also get a function providing a\ndefault vertex on each path *)\nFact theta_vertices (G : diGraph) (x y : G) s (p : 'I_s -> IPath x y) :\n  x != y -> ~~ x -- y ->\n  exists (f : 'I_s -> G), forall i, f i \\in interior (p i).\nProof.\n  move => xDy xNy.\n  suff S i : { s | s \\in interior (p i) }. \n  { exists (fun i => val (S i)) => i. exact: (svalP (S i)). }\n  case: (set_0Vmem (interior (p i))) => [I0|//].\n  exfalso. case: (interior0E xDy (valP (p i)) I0) => xy.\n  by rewrite xy in xNy.\nQed.\n\n(** *** Edge Version *)\n\nCorollary independent_walks Lv Le (G : graph Lv Le) (a b : G) n : \n  a != b -> (forall E, eseparates a b E -> n <= #|E|) -> \n  exists2 W : 'I_n -> seq (edge G), \n    forall i, walk a b (W i) & forall i j, i != j -> [disjoint W i & W j].\nProof.\n  move => aDb min_sep.\n  pose A := [set e : line_graph G | source e == a].\n  pose B := [set e : line_graph G | target e == b].\n  have sep E : separator _ A B E -> n <= #|E|.\n  { move => sep_E. apply: min_sep => w walk_w. \n    have Nw : ~~ nilp w. { case: w walk_w => //=. by rewrite (negbTE aDb). }\n    case: (line_of_walk walk_w Nw) => e1 [e2] [p] [P1 P2 P3].\n    case: (sep_E _ _ p) => [||e in_E in_p]; rewrite ?inE ?P1 ?P2 //.\n    exists e => //. by rewrite mem_path P3 in in_p. }\n  case: (Menger sep) => X con_X. pose W i := nodes (tagged (X i)). exists W.\n  - move => i. rewrite /W. \n    case: (X i) (connector_fst con_X i) (connector_lst con_X i) => [[e1 e2] /= p].\n    rewrite /fst/lst/= !inE => /eqP<- /eqP <-. exact: walk_of_line.\n  - move => i j iDj. apply/disjointP => e. rewrite /W -!(@mem_path (line_graph G)).\n    move => in_i in_j. move/(_ i j e in_i in_j) : (connector_eq con_X) => E.\n    by rewrite E eqxx in iDj.\nQed.\n\n(** ** Hall's Marriage Theorem *)\n\n(** Neighboorhoods and bipartitions are the same for digraphs and simple graphs *)\n\nDefinition bipartition (G : diGraph) (A : {set G}) :=\n  forall x y : G, x -- y -> (x \\in A) = (y \\notin A).\n\nLemma bipartition_path (G : diGraph) (A : {set G}) (x : G) (s: seq G) : \n  bipartition A -> \n  path (--) x s -> ~~ odd (((last x s \\in A) (+) (x \\in A)) + size s).\nProof.\nmove=> bipA; elim: s x => [|/= y s IH] x; first by rewrite addbb. \nmove=> /andP[xy /IH]; rewrite (bipA _ _ xy) addbN. \nby case: (_ (+) _); rewrite //= negbK.\nQed.\n\nLemma bipartition_cycle (G : diGraph) (A : {set G}) (s: seq G) : \n  bipartition A -> cycle (--) s -> ~~ odd (size s).\nProof.\nmove => bipA; case: s => //= x s /(bipartition_path bipA); rewrite negbK.\nby rewrite last_rcons addbb size_rcons /= negbK.\nQed.\n\nLemma even_cycle_Knm n m (s : seq 'K_n,m) : cycle (--) s -> ~~ odd (size s).\nProof.\nsuff: bipartition [set x : 'K_n,m | x] by apply: bipartition_cycle.\nby move => [x|x] [y|y] //= _; rewrite !inE.\nQed.\n\n(** The (natural) notion of a matching on digraphs - a set of ordered\npairs - is not a resonable notion of matching on simple graphs, where\nwe should use unordered pairs. Hence, we have two separate definitions *)\n\nDefinition dimatching (G : diGraph) (M : {set G * G}) :=\n    (forall e, e \\in M -> e.1 -- e.2) \n  /\\ {in M &, forall e1 e2 x, x \\in [set e1.1;e1.2] -> x \\in [set e2.1 ; e2.2] -> e1 = e2}.\n\nDefinition matching (G : sgraph) (M : {set {set G}}) := \n  {subset M <= E(G) } /\\ \n  {in M&, forall (e1 e2 : {set G}) (x:G), x \\in e1 -> x \\in e2 -> e1 = e2}.\n\nLemma connectorC_edge (G : diGraph) (A : {set G}) n (p : 'I_n -> pathS G) i : \n  connector A (~: A) p -> \n  exists fl : fst (p i) -- lst (p i), p i = PathS (edgep fl).\nProof.\n  move => conn_p. \n  case def_q : (p i) => [[a b] /= q]. rewrite -/(PathS q) in def_q *.\n  case: (irred_is_edge q). \n  - move: (conn_irred conn_p i). by rewrite def_q.\n  - case: (altP (a =P b)) => // ?; subst. \n    move: (connector_fst conn_p i) (connector_lst conn_p i). \n    by rewrite def_q !inE => ->.\n  - move => z zq. rewrite !inE. case: (boolP (z \\in A)) => [zA|zNA].\n    + by rewrite [z](connector_left conn_p (i := i)) ?def_q // eqxx.\n    + by rewrite {2}[z](connector_right conn_p (i := i)) ?def_q ?inE // eqxx.\n  - move => ab ->. by exists ab.\nQed.\n\nDefinition dimatching_of (G : diGraph) n (p : 'I_n -> pathS G) := \n  [set (fst (p i),lst (p i)) | i : 'I_n].\n\nLemma connector_dimatching (G : diGraph) (A : {set G} ) n (p : 'I_n -> pathS G) :\n  connector A (~:A) p -> dimatching (dimatching_of p).\nProof. \n  move => con_p. split.\n  + move => e. case/imsetP => i _ -> /=. \n    by case: (connectorC_edge i con_p).\n  + move => [a b] [a' b'] /imsetP [i _ [-> ->]] /imsetP [j _ [-> ->]] /= x /set2P [->|->]. \n    * case/set2P; by [move/(fst_inj con_p) -> | move/(fst_lst_eq con_p) ->]. \n    * case/set2P; by [move/(lst_inj con_p) -> | move/esym/(fst_lst_eq con_p) ->].\nQed.\n\nLemma card_dimatching_of (G : diGraph) A B n (p : 'I_n -> pathS G) :\n  connector A B p -> #|dimatching_of p| = n.\nProof.\n  move => con_p. rewrite /dimatching_of card_imset ?card_ord // => i j.\n  case. by move/(fst_inj con_p).\nQed.\n\nDefinition matching_of (G : diGraph) (M' : {set G * G}) := \n  [set [set e.1;e.2] | e in M'].\n\nLemma matching_of_dimatching (G : sgraph) (A : {set G}) M : \n  dimatching M -> @matching G (matching_of M).\nProof.\n  move => [M1 M2]. split.  \n  - move => e. case/imsetP => x /M1 ? ?. apply/edgesP. by exists x.1; exists x.2. \n  - move => e1 e2 /imsetP [x X1 X2] /imsetP [y Y1 Y2] z. subst e1 e2.  \n    move => Z1 Z2. by rewrite (M2 x y X1 Y1 z Z1 Z2).\nQed.\n\nLemma card_matching_of (G : diGraph) (M : {set G * G}) : \n  dimatching M -> #|matching_of M| = #|M|.\nProof.\n  move => [? dim_M]. rewrite /matching_of card_in_imset //.\n  move => e1 e2 /= inM1 inM2 E. apply dim_M with e1.1 => //.\n  all: by rewrite -?E !inE eqxx.\nQed. \n\nTheorem diHall (G : diGraph) A : \n  bipartition A -> (forall S : {set G}, S \\subset A -> #|S| <= #|NS(S)|) -> \n  exists M, dimatching M /\\ A = [set x.1 | x in M].\nProof.\n  move => bip_A N_A. \n  have sep_A S : separator G A (~:A) S -> #|A| <= #|S|.\n  { move => sep_S. rewrite -[#|A|](cardsID S). \n    apply: (@leq_trans (#|A :&: S| + #|NS(A :\\: S)|)).\n    - by rewrite leq_add2l N_A // subsetDl.\n    - rewrite -cardsUI [X in _ + X]eq_card0 ?addn0.\n      + apply: subset_leq_card. rewrite subUset subsetIr /=.\n        apply/subsetP => z /bigcupP [x /setDP[xA xNS]]; rewrite in_opn => xz.\n        have [|s inS] := sep_S _ _ (edgep xz) xA; first by rewrite inE -(bip_A _ _ xz).\n        rewrite mem_edgep => /pred2P [?|<- //]; subst; contrab.\n      + move => z;rewrite !inE -andbA;apply/negbTE/negP.\n        move => /and3P [zA zS /bigcupP [x /setDP [xA xS] xz]].\n        rewrite in_opn in xz. by rewrite (bip_A _ _ xz) zA in xA . }\n  case: (Menger sep_A) => p con_p. clear sep_A bip_A.\n  exists (dimatching_of p). split; first exact: connector_dimatching con_p.\n  apply/setP => a. apply/idP/imsetP => [inA|[x]].\n  + move: (inj_card_onto_pred (f := fun i => fst (p i)) (P := (mem A))) => /=.\n    case/(_ _ _ _ _ inA)/Wrap => //. \n    * apply: fst_inj con_p. \n    * apply: connector_fst con_p.\n    * by rewrite card_ord.\n    * case/mapP => i _ ->. exists (fst (p i),lst (p i)) => //. by rewrite imset_f.\n  + case/imsetP => i _ -> /= ->. apply: connector_fst. exact: con_p.\nQed.\n\nTheorem Hall (G : sgraph) A : \n  bipartition A -> (forall S : {set G}, S \\subset A -> #|S| <= #|NS(S)|) -> \n  exists M, matching M /\\ A \\subset cover M.\nProof.\n  move => bip_A N_A. case: (@diHall G A) => [//|//|M' [M1 M2]].\n  - case: M1 => M1 M1'. exists (matching_of M'). \n    split; first exact: matching_of_dimatching.\n    rewrite M2. apply/subsetP => a. case/imsetP => e E1 E2. apply/bigcupP. \n    exists [set e.1; e.2]; last by rewrite E2 !inE eqxx. exact: imset_f.\nQed.\n\n(** ** König's Theorem *)\n\nSection vcover.\nVariables (G : sgraph) (V :{set G}).\n\nDefinition vcover := [forall x, forall (y | x -- y), (x \\in V) || (y \\in V)].\n\nLemma vcoverP : reflect (forall x y, x -- y -> (x \\in V) \\/ (y \\in V)) vcover.\nProof. \n  apply: (equivP idP).\n  rewrite /vcover -(rwP forallP).\n  setoid_rewrite <- (rwP forall_inP).\n  by setoid_rewrite <- (rwP orP).\nQed.\n\n(** The [x0] is needed to ensure that [G] is inhabited. \n    Otherwise, [{set G} -> G] is empty as well. *)\nLemma matching_cover_map (x0 : G) M :\n  matching M -> vcover -> \n  exists2 f : {set G} -> G, (forall e : {set G}, e \\in M -> f e \\in V :&: e) & {in M&, injective f}.\nProof.\n  move => [M1 M2] cover_V.\n  pose f (A : {set G}) := if [pick x | x \\in V :&: A] is Some x then x else x0.\n  have fP e : e \\in M -> f e \\in V :&: e.\n  { move/M1. case/edgesP => x [y] [E xy]. \n    rewrite /f. case: pickP => [//|]. \n    case/(vcoverP cover_V) : xy => xV; \n    [move/(_ x)|move/(_ y)]; by rewrite E !inE xV eqxx ?orbT. }\n  exists f => // e1 e2 eM1 eM2. \n  move: (eM1) (eM2) => /fP /setIP [V1 E1] /fP /setIP [V2 E2] E.\n  apply M2 with (f e1) => //. by rewrite E.\nQed.\n\nLemma cover_matching (M :{set {set G}}) : \n  matching M -> vcover -> #|M| <= #|V|.\nProof.\n  move => [M1 M2] cover_V.\n  wlog [x0] : / inhabited G.\n  { move => W. case: (set_0Vmem M) => [->|[e /M1]]; first by rewrite cards0.\n    case/edgesP => x _. exact: W. }\n  case: (matching_cover_map x0 (conj M1 M2) cover_V) => f F1 F2.\n  have f_V e : e \\in M -> f e \\in V by move/F1 => /setIP[].\n  rewrite -(card_in_image F2). apply: subset_leq_card.\n  apply/subsetP => y /mapP [x Hx ->]. apply: f_V. by rewrite mem_enum in Hx.\nQed.\n\nProposition min_max_cover (M : {set {set G}}) :  \n  vcover -> matching M -> #|M| = #|V| -> V \\subset cover M.\nProof.\n  move => cov_V match_V MV. \n  wlog [x0] : / inhabited G.\n  { move => W. case: (set_0Vmem V) => [-> //|[x _]]; first by rewrite sub0set.\n    exact: W. }\n  case: (matching_cover_map x0 match_V cov_V) => f F1 F2.\n  pose f' (e : { e | e \\in M}) := f (val e).\n  have inj_f' : injective f'. \n  { case => e1 M1. case => e2 M2. rewrite /f' /= => E. \n    apply/eqP. change (e1 == e2). by rewrite (F2 _ _ M1 M2 E). }\n  move: (inj_card_onto_pred (P := (mem V)) inj_f') => /=. case/(_ _ _)/Wrap.\n  - case => e inM. by case/setIP : (F1 _ inM).\n  - by rewrite card_sig. \n  - move => X. apply/subsetP => v vV. case/mapP : (X _ vV) => /= [[e inM] _ E].\n    apply/bigcupP. exists e => //. rewrite E /f' /=. by case/setIP : (F1 _ inM).\nQed. \n\nEnd vcover.\nPrenex Implicits vcover.\nPrenex Implicits matching.\n\nLemma bip_separation_vcover (G : sgraph) (A S : {set G}) : \n  bipartition A -> separator G A (~: A) S -> vcover S.\nProof.\n  move => bip_A sep_S. apply/vcoverP => x y xy.\n  wlog/andP [xA yNA] : x y xy / (x \\in A) && (y \\notin A). \n  { move: (bip_A x y xy). case: (boolP (y \\in A)) => /= yA xA; last by apply.\n    rewrite or_comm. apply; by rewrite 1?sgP ?xA ?yA. }\n  move: (sep_S _ _ (edgep xy)). rewrite xA inE yNA. case => // s sS. \n  rewrite mem_edgep => /orP [/eqP<-|/eqP<-]; by tauto.\nQed.\n\nLemma min_vcover_matching (G : sgraph) (A V : {set G}) : \n  bipartition A -> smallest vcover V ->\n  exists2 M, @matching G M & #|V| = #|M|.\nProof.\n  move => bip_A [cover_V min_V]. \n  have sep_A S : separator G A (~:A) S -> #|V| <= #|S|.\n  { move/bip_separation_vcover => /(_ bip_A). exact: min_V. }\n  case: (Menger sep_A) => p conn_p. \n  move/connector_dimatching : (conn_p) => dim_M.\n  exists (matching_of (dimatching_of p)). exact: matching_of_dimatching.\n  by rewrite card_matching_of // (card_dimatching_of conn_p).\nQed.\n\nTheorem Konig (G : sgraph) (A V : {set G}) (M : {set {set G}}) : \n  bipartition A -> smallest vcover V -> largest matching M -> #|V| = #|M|.\nProof.\n  move => bip_A [cov_V min_V] [match_M max_M]. apply/eqP.\n  rewrite eqn_leq cover_matching // andbT.\n  case: (min_vcover_matching (V := V) bip_A _) => // M' H ->. exact: max_M.\nQed.\n\n\n(** ** k-connectivity *)\n\nDefinition kconnected (k : nat) (G : sgraph) := \n  k < #|G| /\\ forall S : {set G}, vseparator S -> k <= #|S|.\n\nDefinition kconnectedb (k : nat) (G : sgraph) := \n  (k < #|G|) && [forall (S | @vseparatorb G S), k <= #|S|].\n\nLemma kconnectedP k G : reflect (kconnected k G) (kconnectedb k G).\nProof.\napply: (iffP andP) => [[gtk /forall_inP sepG]|[gtk sepG]]; split => //.\n- move => S /vseparatorP; exact: sepG.\n- apply/forall_inP => S /vseparatorP; exact: sepG.\nQed.\n\nNotation \"k .-connected\" := (kconnected k)\n  (at level 2, format \"k .-connected\") : type_scope.\n\nLemma connectedVseparator (G : sgraph) k : \n  k < #|G| -> k.-connected G + { S : {set G} | #|S| < k & vseparator S}.\nProof. \nmove => gtk. case: (boolP (kconnectedb k G)) => [/kconnectedP|]; first by left.\nrewrite negb_and gtk /= => /forallPn => ex_S.\nhave := xchooseP (ex_S); rewrite negb_imply -ltnNge => /andP [/vseparatorP ? ?].\nby right; exists (xchoose ex_S).\nQed.\n\nLemma kconnected_degree (G : sgraph) k (x : G) : k.-connected G -> k <= #|N(x)|.\nProof.\nmove => [card_G sep_G].\ncase: (boolP [exists (y | x != y), ~~ x -- y]).\n- case/exists_inP => y xDy xNy. \n  by apply/sep_G/separates_vseparator; apply: opn_separates xNy.\n- rewrite negb_exists_in => /forall_inP; setoid_rewrite negbK => Hx.\n  apply: (@leq_trans #|[set~ x]|). \n  + by rewrite cardsC1 -ltnS (@ltn_predK k).\n  + apply/subset_leq_card/subsetP => x'. rewrite !inE eq_sym. exact: Hx.\nQed.\n\n\nLemma kconnected_edge (G : sgraph) (k : nat) : \n  k.+1.-connected G -> exists x y : G , x -- y.\nProof.\nmove=> k1G. have [gt1kG _] := k1G.\nhave/card_gt0P [x _] : 0 < #|G| by apply: leq_trans gt1kG.\nhave k_edge := kconnected_degree x k1G.\nhave/card_gt0P [y /in_setP xy] : 0 < #|N(x)| by apply: leq_trans k_edge.\nby exists x,y.\nQed.\n\nLemma kconnected_induced (G : sgraph) (A : {set G}) k : \n  (k + #|~: A|).-connected G -> k.-connected (induced A).\nProof.\nmove => [cardG sepG]; split => [|S].\n- by rewrite card_sig -(leq_add2r #|~: A|) cardsC addSn.\n- move/induced_vseparator/sepG. rewrite cardsU card_imset //.\n  rewrite [#|_ :&: _|]eq_card0 ?subn0 ?leq_add2r // => z.\n  by apply: contraTF isT => /setIP [/imsetP[x _ ->]]; rewrite inE (valP x).\nQed.\n\nLemma konnected_del1 k (G : sgraph) (x : G) : \n  k.+1.-connected G -> k.-connected (induced [set~ x]).\nProof.\nby move => kG; apply: kconnected_induced; rewrite setCK cards1 addn1.\nQed.\n\nLemma kconnected_bounds (G : sgraph) k : \n  k.+1 < #|G| -> k.-connected G -> ~ k.+1.-connected G -> \n  exists2 S : {set G}, #|S| == k & smallest vseparator S.\nProof.\nmove => large_G [_ min_k]. \nmove/kconnectedP; rewrite negb_and large_G /= => /forall_inPn [S].\nmove/vseparatorP; rewrite -leqNgt => S1 S2; exists S => //.\n- by rewrite eqn_leq S2 min_k.\n- split => // V /min_k. exact: leq_trans.\nQed.\n\nLemma kconnectedW n k G : (k+n).-connected G -> k.-connected G.\nProof. \ncase => lt_kn_G sep_kn; split; first exact: leq_ltn_trans (leq_addr _ _) lt_kn_G.\nby move=> S /sep_kn; apply/leq_trans/leq_addr.\nQed.\n\nLemma kconnected_complete G k : \n  k.-connected G -> #|G| <= k.+1 -> (forall x y : G, x != y -> x -- y).\nProof.\nmove => [lt_k_G sepG] le_G_k x y xDy; pose S := [set~ x] :&: [set~ y].\napply: contraTT le_G_k => xNy; rewrite -ltnNge.\nhave/sepG le_k_S : vseparator S.\n  by apply/proper_vseparator/separate_nonadjacent.\nby rewrite -(cardsC S) setCI !setCK cards2 xDy /= addn2.\nQed.\n", "meta": {"author": "coq-community", "repo": "graph-theory", "sha": "18bdabc919f6b20946f40cd5d4fbb5143c46a2bf", "save_path": "github-repos/coq/coq-community-graph-theory", "path": "github-repos/coq/coq-community-graph-theory/graph-theory-18bdabc919f6b20946f40cd5d4fbb5143c46a2bf/theories/core/connectivity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7286119482771958}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria.                       *)\n(* You may distribute this file under the terms of the CeCILL-B license *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(******************************************************************************)\n(* This file deals with divisibility for natural numbers.                     *)\n(* It contains the definitions of:                                            *)\n(*      edivn m d   == the pair composed of the quotient and remainder        *)\n(*                     of the Euclidean division of m by d.                   *)\n(*          m %/ d  == quotient of m by d.                                    *)\n(*          m %% d  == remainder of m by d.                                   *)\n(*  m = n %[mod d]  <-> m equals n modulo d.                                  *)\n(*  m == n %[mod d] <=> m equals n modulo d (boolean version).                *)\n(*  m <> n %[mod d] <-> m differs from n modulo d.                            *)\n(*  m != n %[mod d] <=> m differs from n modulo d (boolean version).          *)\n(*           d %| m <=> d divides m.                                          *)\n(*         gcdn m n == the GCD of m and n.                                    *)\n(*        egcdn m n == the extended GCD of m and n.                           *)\n(*         lcmn m n == the LCM of m and n.                                    *)\n(*      coprime m n <=> m and n are coprime (:= gcdn m n == 1).               *)\n(*  chinese m n r s == witness of the chinese remainder theorem.              *)\n(* We adjoin an m to operator suffixes to indicate a nested %% (modn), as in  *)\n(*   modnDml : m %% d + n = m + n %[mod d].                                   *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** Euclidean division *)\n\nDefinition edivn_rec d :=\n  fix loop m q := if m - d is m'.+1 then loop m' q.+1 else (q, m).\n\nDefinition edivn m d := if d > 0 then edivn_rec d.-1 m 0 else (0, m).\n\nCoInductive edivn_spec m d : nat * nat -> Type :=\n  EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r).\n\nLemma edivnP m d : edivn_spec m d (edivn m d).\nProof.\nrewrite -{1}[m]/(0 * d + m) /edivn; case: d => //= d.\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //= le_mn.\nhave le_m'n: m - d <= n by rewrite (leq_trans (leq_subr d m)).\nrewrite subn_if_gt; case: ltnP => [// | le_dm].\nby rewrite -{1}(subnKC le_dm) -addSn addnA -mulSnr; exact: IHn.\nQed.\n\nLemma edivn_eq d q r : r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> lt_rd; have d_gt0: 0 < d by exact: leq_trans lt_rd.\ncase: edivnP lt_rd => q' r'; rewrite d_gt0 /=.\nwlog: q q' r r' / q <= q' by case/orP: (leq_total q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case/predU1P => [-> /addnI-> |] //=.\nrewrite -(leq_pmul2r d_gt0) => /leq_add lt_qr eq_qr _ /lt_qr {lt_qr}.\nby rewrite addnS ltnNge mulSn -addnA eq_qr addnCA addnA leq_addr.\nQed.\n\nDefinition divn m d := (edivn m d).1.\n\nNotation \"m %/ d\" := (divn m d) : nat_scope.\n\n(* We redefine modn so that it is structurally decreasing. *)\n\nDefinition modn_rec d := fix loop m := if m - d is m'.+1 then loop m' else m.\n\nDefinition modn m d := if d > 0 then modn_rec d.-1 m else m.\n\nNotation \"m %% d\" := (modn m d) : nat_scope.\nNotation \"m = n %[mod d ]\" := (m %% d = n %% d) : nat_scope.\nNotation \"m == n %[mod d ]\" := (m %% d == n %% d) : nat_scope.\nNotation \"m <> n %[mod d ]\" := (m %% d <> n %% d) : nat_scope.\nNotation \"m != n %[mod d ]\" := (m %% d != n %% d) : nat_scope.\n\nLemma modn_def m d : m %% d = (edivn m d).2.\nProof.\ncase: d => //= d; rewrite /modn /edivn /=.\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=.\nrewrite ltnS !subn_if_gt; case: (d <= m) => // le_mn.\nby apply: IHn; apply: leq_trans le_mn; exact: leq_subr.\nQed.\n\nLemma edivn_def m d : edivn m d = (m %/ d, m %% d).\nProof. by rewrite /divn modn_def; case: (edivn m d). Qed.\n\nLemma divn_eq m d : m = m %/ d * d + m %% d.\nProof. by rewrite /divn modn_def; case: edivnP. Qed.\n\nLemma div0n d : 0 %/ d = 0. Proof. by case: d. Qed.\nLemma divn0 m : m %/ 0 = 0. Proof. by []. Qed.\nLemma mod0n d : 0 %% d = 0. Proof. by case: d. Qed.\nLemma modn0 m : m %% 0 = m. Proof. by []. Qed.\n\nLemma divn_small m d : m < d -> m %/ d = 0.\nProof. by move=> lt_md; rewrite /divn (edivn_eq 0). Qed.\n\nLemma divnMDl q m d : 0 < d -> (q * d + m) %/ d = q + m %/ d.\nProof.\nmove=> d_gt0; rewrite {1}(divn_eq m d) addnA -mulnDl.\nby rewrite /divn edivn_eq // modn_def; case: edivnP; rewrite d_gt0.\nQed.\n\nLemma mulnK m d : 0 < d -> m * d %/ d = m.\nProof. by move=> d_gt0; rewrite -[m * d]addn0 divnMDl // div0n addn0. Qed.\n\nLemma mulKn m d : 0 < d -> d * m %/ d = m.\nProof. by move=> d_gt0; rewrite mulnC mulnK. Qed.\n\nLemma expnB p m n : p > 0 -> m >= n -> p ^ (m - n) = p ^ m %/ p ^ n.\nProof.\nby move=> p_gt0 /subnK{2}<-; rewrite expnD mulnK // expn_gt0 p_gt0.\nQed.\n\nLemma modn1 m : m %% 1 = 0.\nProof. by rewrite modn_def; case: edivnP => ? []. Qed.\n\nLemma divn1 m : m %/ 1 = m.\nProof. by rewrite {2}(@divn_eq m 1) // modn1 addn0 muln1. Qed.\n\nLemma divnn d : d %/ d = (0 < d).\nProof. by case: d => // d; rewrite -{1}[d.+1]muln1 mulKn. Qed.\n\nLemma divnMl p m d : p > 0 -> p * m %/ (p * d) = m %/ d.\nProof.\nmove=> p_gt0; case: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nrewrite {2}/divn; case: edivnP; rewrite d_gt0 /= => q r ->{m} lt_rd.\nrewrite mulnDr mulnCA divnMDl; last by rewrite muln_gt0 p_gt0.\nby rewrite addnC divn_small // ltn_pmul2l.\nQed.\nImplicit Arguments divnMl [p m d].\n\nLemma divnMr p m d : p > 0 -> m * p %/ (d * p) = m %/ d.\nProof. by move=> p_gt0; rewrite -!(mulnC p) divnMl. Qed.\nImplicit Arguments divnMr [p m d].\n\nLemma ltn_mod m d : (m %% d < d) = (0 < d).\nProof. by case: d => // d; rewrite modn_def; case: edivnP. Qed.\n\nLemma ltn_pmod m d : 0 < d -> m %% d < d.\nProof. by rewrite ltn_mod. Qed.\n\nLemma leq_trunc_div m d : m %/ d * d <= m.\nProof. by rewrite {2}(divn_eq m d) leq_addr. Qed.\n\nLemma leq_mod m d : m %% d  <= m.\nProof. by rewrite {2}(divn_eq m d) leq_addl. Qed.\n\nLemma leq_div m d : m %/ d <= m.\nProof.\nby case: d => // d; apply: leq_trans (leq_pmulr _ _) (leq_trunc_div _ _).\nQed.\n\nLemma ltn_ceil m d : 0 < d -> m < (m %/ d).+1 * d.\nProof.\nby move=> d_gt0; rewrite {1}(divn_eq m d) -addnS mulSnr leq_add2l ltn_mod.\nQed.\n\nLemma ltn_divLR m n d : d > 0 -> (m %/ d < n) = (m < n * d).\nProof.\nmove=> d_gt0; apply/idP/idP.\n  by rewrite -(leq_pmul2r d_gt0); apply: leq_trans (ltn_ceil _ _).\nrewrite !ltnNge -(@leq_pmul2r d n) //; apply: contra => le_nd_floor.\nexact: leq_trans le_nd_floor (leq_trunc_div _ _).\nQed.\n\nLemma leq_divRL m n d : d > 0 -> (m <= n %/ d) = (m * d <= n).\nProof. by move=> d_gt0; rewrite leqNgt ltn_divLR // -leqNgt. Qed.\n\nLemma ltn_Pdiv m d : 1 < d -> 0 < m -> m %/ d < m.\nProof. by move=> d_gt1 m_gt0; rewrite ltn_divLR ?ltn_Pmulr // ltnW. Qed.\n\nLemma divn_gt0 d m : 0 < d -> (0 < m %/ d) = (d <= m).\nProof. by move=> d_gt0; rewrite leq_divRL ?mul1n. Qed.\n\nLemma leq_div2r d m n : m <= n -> m %/ d <= n %/ d.\nProof.\nhave [-> //| d_gt0 le_mn] := posnP d.\nby rewrite leq_divRL // (leq_trans _ le_mn) -?leq_divRL.\nQed.\n\nLemma leq_div2l m d e : 0 < d -> d <= e -> m %/ e <= m %/ d.\nProof.\nmove/leq_divRL=> -> le_de.\nby apply: leq_trans (leq_trunc_div m e); apply: leq_mul.\nQed.\n\nLemma leq_divDl p m n : (m + n) %/ p <= m %/ p + n %/ p + 1.\nProof.\nhave [-> //| p_gt0] := posnP p; rewrite -ltnS -addnS ltn_divLR // ltnW //.\nrewrite {1}(divn_eq n p) {1}(divn_eq m p) addnACA !mulnDl -3!addnS leq_add2l.\nby rewrite mul2n -addnn -addSn leq_add // ltn_mod.\nQed.\n\nLemma geq_divBl k m p : k %/ p - m %/ p <= (k - m) %/ p + 1.\nProof.\nrewrite leq_subLR addnA; apply: leq_trans (leq_divDl _ _ _).\nby rewrite -maxnE leq_div2r ?leq_maxr.\nQed.\n\nLemma divnMA m n p : m %/ (n * p) = m %/ n %/ p. \nProof.\ncase: n p => [|n] [|p]; rewrite ?muln0 ?div0n //.\nrewrite {2}(divn_eq m (n.+1 * p.+1)) mulnA mulnAC !divnMDl //.\nby rewrite [_ %/ p.+1]divn_small ?addn0 // ltn_divLR // mulnC ltn_mod.\nQed.\n\nLemma divnAC m n p : m %/ n %/ p =  m %/ p %/ n.\nProof. by rewrite -!divnMA mulnC. Qed.\n\nLemma modn_small m d : m < d -> m %% d = m.\nProof. by move=> lt_md; rewrite {2}(divn_eq m d) divn_small. Qed.\n\nLemma modn_mod m d : m %% d = m %[mod d].\nProof. by case: d => // d; apply: modn_small; rewrite ltn_mod. Qed.\n\nLemma modnMDl p m d : p * d + m = m %[mod d].\nProof.\ncase: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nby rewrite {1}(divn_eq m d) addnA -mulnDl modn_def edivn_eq // ltn_mod.\nQed.\n\nLemma muln_modr {p m d} : 0 < p -> p * (m %% d) = (p * m) %% (p * d).\nProof.\nmove=> p_gt0; apply: (@addnI (p * (m %/ d * d))).\nby rewrite -mulnDr -divn_eq mulnCA -(divnMl p_gt0) -divn_eq.\nQed.\n\nLemma muln_modl {p m d} : 0 < p -> (m %% d) * p = (m * p) %% (d * p).\nProof. by rewrite -!(mulnC p); apply: muln_modr. Qed.\n\nLemma modnDl m d : d + m = m %[mod d].\nProof. by rewrite -{1}[d]mul1n modnMDl. Qed.\n\nLemma modnDr m d : m + d = m %[mod d].\nProof. by rewrite addnC modnDl. Qed.\n\nLemma modnn d : d %% d = 0.\nProof. by rewrite -{1}[d]addn0 modnDl mod0n. Qed.\n\nLemma modnMl p d : p * d %% d = 0.\nProof. by rewrite -[p * d]addn0 modnMDl mod0n. Qed.\n\nLemma modnMr p d : d * p %% d = 0.\nProof. by rewrite mulnC modnMl. Qed.\n\nLemma modnDml m n d : m %% d + n = m + n %[mod d].\nProof. by rewrite {2}(divn_eq m d) -addnA modnMDl. Qed.\n\nLemma modnDmr m n d : m + n %% d = m + n %[mod d].\nProof. by rewrite !(addnC m) modnDml. Qed.\n\nLemma modnDm m n d : m %% d  + n %% d = m + n %[mod d].\nProof. by rewrite modnDml modnDmr. Qed.\n\nLemma eqn_modDl p m n d : (p + m == p + n %[mod d]) = (m == n %[mod d]).\nProof.\ncase: d => [|d]; first by rewrite !modn0 eqn_add2l.\napply/eqP/eqP=> eq_mn; last by rewrite -modnDmr eq_mn modnDmr.\nrewrite -(modnMDl p m) -(modnMDl p n) !mulnSr -!addnA.\nby rewrite -modnDmr eq_mn modnDmr.\nQed.\n\nLemma eqn_modDr p m n d : (m + p == n + p %[mod d]) = (m == n %[mod d]).\nProof. by rewrite -!(addnC p) eqn_modDl. Qed.\n\nLemma modnMml m n d : m %% d * n = m * n %[mod d].\nProof. by rewrite {2}(divn_eq m d) mulnDl mulnAC modnMDl. Qed.\n\nLemma modnMmr m n d : m * (n %% d) = m * n %[mod d].\nProof. by rewrite !(mulnC m) modnMml. Qed.\n\nLemma modnMm m n d : m %% d * (n %% d) = m * n %[mod d].\nProof. by rewrite modnMml modnMmr. Qed.\n\nLemma modn2 m : m %% 2 = odd m.\nProof. by elim: m => //= m IHm; rewrite -addn1 -modnDml IHm; case odd. Qed.\n\nLemma divn2 m : m %/ 2 = m./2.\nProof. by rewrite {2}(divn_eq m 2) modn2 muln2 addnC half_bit_double. Qed.\n\nLemma odd_mod m d : odd d = false -> odd (m %% d) = odd m.\nProof.\nby move=> d_even; rewrite {2}(divn_eq m d) odd_add odd_mul d_even andbF.\nQed.\n\nLemma modnXm m n a : (a %% n) ^ m = a ^ m %[mod n].\nProof.\nby elim: m => // m IHm; rewrite !expnS -modnMmr IHm modnMml modnMmr.\nQed.\n\n(** Divisibility **)\n\nDefinition dvdn d m := m %% d == 0.\n\nNotation \"m %| d\" := (dvdn m d) : nat_scope.\n\nLemma dvdnP d m : reflect (exists k, m = k * d) (d %| m).\nProof.\napply: (iffP eqP) => [md0 | [k ->]]; last by rewrite modnMl.\nby exists (m %/ d); rewrite {1}(divn_eq m d) md0 addn0.\nQed.\nImplicit Arguments dvdnP [d m].\nPrenex Implicits dvdnP.\n\nLemma dvdn0 d : d %| 0.\nProof. by case: d. Qed.\n\nLemma dvd0n n : (0 %| n) = (n == 0).\nProof. by case: n. Qed.\n\nLemma dvdn1 d : (d %| 1) = (d == 1).\nProof. by case: d => [|[|d]] //; rewrite /dvdn modn_small. Qed.\n\nLemma dvd1n m : 1 %| m.\nProof. by rewrite /dvdn modn1. Qed.\n\nLemma dvdn_gt0 d m : m > 0 -> d %| m -> d > 0.\nProof. by case: d => // /prednK <-. Qed.\n\nLemma dvdnn m : m %| m.\nProof. by rewrite /dvdn modnn. Qed.\n\nLemma dvdn_mull d m n : d %| n -> d %| m * n.\nProof. by case/dvdnP=> n' ->; rewrite /dvdn mulnA modnMl. Qed.\n\nLemma dvdn_mulr d m n : d %| m -> d %| m * n.\nProof. by move=> d_m; rewrite mulnC dvdn_mull. Qed.\nHint Resolve dvdn0 dvd1n dvdnn dvdn_mull dvdn_mulr.\n\nLemma dvdn_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\nby move=> /dvdnP[q1 ->] /dvdnP[q2 ->]; rewrite mulnCA -mulnA 2?dvdn_mull.\nQed.\n\nLemma dvdn_trans n d m : d %| n -> n %| m -> d %| m.\nProof. by move=> d_dv_n /dvdnP[n1 ->]; exact: dvdn_mull. Qed.\n\nLemma dvdn_eq d m : (d %| m) = (m %/ d * d == m).\nProof.\napply/eqP/eqP=> [modm0 | <-]; last exact: modnMl.\nby rewrite {2}(divn_eq m d) modm0 addn0.\nQed.\n\nLemma dvdn2 n : (2 %| n) = ~~ odd n.\nProof. by rewrite /dvdn modn2; case (odd n). Qed.\n\nLemma dvdn_odd m n : m %| n -> odd n -> odd m.\nProof.\nby move=> m_dv_n; apply: contraTT; rewrite -!dvdn2 => /dvdn_trans->.\nQed.\n\nLemma divnK d m : d %| m -> m %/ d * d = m.\nProof. by rewrite dvdn_eq; move/eqP. Qed.\n\nLemma leq_divLR d m n : d %| m -> (m %/ d <= n) = (m <= n * d).\nProof. by case: d m => [|d] [|m] ///divnK=> {2}<-; rewrite leq_pmul2r. Qed.\n\nLemma ltn_divRL d m n : d %| m -> (n < m %/ d) = (n * d < m).\nProof. by move=> dv_d_m; rewrite !ltnNge leq_divLR. Qed.\n\nLemma eqn_div d m n : d > 0 -> d %| m -> (n == m %/ d) = (n * d == m).\nProof. by move=> d_gt0 dv_d_m; rewrite -(eqn_pmul2r d_gt0) divnK. Qed.\n\nLemma eqn_mul d m n : d > 0 -> d %| m -> (m == n * d) = (m %/ d == n).\nProof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqn_div // eq_sym. Qed.\n\nLemma divn_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d.\nProof.\ncase: d m => [[] //| d m] dv_d_m; apply/eqP.\nby rewrite eqn_div ?dvdn_mulr // mulnAC divnK.\nQed.\n\nLemma muln_divA d m n : d %| n -> m * (n %/ d) = m * n %/ d.\nProof. by move=> dv_d_m; rewrite !(mulnC m) divn_mulAC. Qed.\n\nLemma muln_divCA d m n : d %| m -> d %| n -> m * (n %/ d) = n * (m %/ d).\nProof. by move=> dv_d_m dv_d_n; rewrite mulnC divn_mulAC ?muln_divA. Qed.\n\nLemma divnA m n p : p %| n -> m %/ (n %/ p) = m * p %/ n.\nProof. by case: p => [|p] dv_n; rewrite -{2}(divnK dv_n) // divnMr. Qed.\n\nLemma modn_dvdm m n d : d %| m -> n %% m = n %[mod d].\nProof.\nby case/dvdnP=> q def_m; rewrite {2}(divn_eq n m) {3}def_m mulnA modnMDl.\nQed.\n\nLemma dvdn_leq d m : 0 < m -> d %| m -> d <= m.\nProof. by move=> m_gt0 /dvdnP[[|k] Dm]; rewrite Dm // leq_addr in m_gt0 *. Qed.\n\nLemma gtnNdvd n d : 0 < n -> n < d -> (d %| n) = false.\nProof. by move=> n_gt0 lt_nd; rewrite /dvdn eqn0Ngt modn_small ?n_gt0. Qed.\n\nLemma eqn_dvd m n : (m == n) = (m %| n) && (n %| m).\nProof.\ncase: m n => [|m] [|n] //; apply/idP/andP; first by move/eqP->; auto.\nrewrite eqn_leq => [[Hmn Hnm]]; apply/andP; have:= dvdn_leq; auto.\nQed.\n\nLemma dvdn_pmul2l p d m : 0 < p -> (p * d %| p * m) = (d %| m).\nProof. by case: p => // p _; rewrite /dvdn -muln_modr // muln_eq0. Qed.\nImplicit Arguments dvdn_pmul2l [p m d].\n\nLemma dvdn_pmul2r p d m : 0 < p -> (d * p %| m * p) = (d %| m).\nProof. by move=> p_gt0; rewrite -!(mulnC p) dvdn_pmul2l. Qed.\nImplicit Arguments dvdn_pmul2r [p m d].\n\nLemma dvdn_divLR p d m : 0 < p -> p %| d -> (d %/ p %| m) = (d %| m * p).\nProof. by move=> /(@dvdn_pmul2r p _ m) <- /divnK->. Qed.\n\nLemma dvdn_divRL p d m : p %| m -> (d %| m %/ p) = (d * p %| m).\nProof.\nhave [-> | /(@dvdn_pmul2r p d) <- /divnK-> //] := posnP p.\nby rewrite divn0 muln0 dvdn0.\nQed.\n\nLemma dvdn_div d m : d %| m -> m %/ d %| m.\nProof. by move/divnK=> {2}<-; apply: dvdn_mulr. Qed.\n\nLemma dvdn_exp2l p m n : m <= n -> p ^ m %| p ^ n.\nProof. by move/subnK <-; rewrite expnD dvdn_mull. Qed.\n\nLemma dvdn_Pexp2l p m n : p > 1 -> (p ^ m %| p ^ n) = (m <= n).\nProof.\nmove=> p_gt1; case: leqP => [|gt_n_m]; first exact: dvdn_exp2l.\nby rewrite gtnNdvd ?ltn_exp2l ?expn_gt0 // ltnW.\nQed.\n\nLemma dvdn_exp2r m n k : m %| n -> m ^ k %| n ^ k.\nProof. by case/dvdnP=> q ->; rewrite expnMn dvdn_mull. Qed.\n\nLemma dvdn_addr m d n : d %| m -> (d %| m + n) = (d %| n).\nProof. by case/dvdnP=> q ->; rewrite /dvdn modnMDl. Qed.\n\nLemma dvdn_addl n d m : d %| n -> (d %| m + n) = (d %| m).\nProof. by rewrite addnC; exact: dvdn_addr. Qed.\n\nLemma dvdn_add d m n : d %| m -> d %| n -> d %| m + n.\nProof. by move/dvdn_addr->. Qed.\n\nLemma dvdn_add_eq d m n : d %| m + n -> (d %| m) = (d %| n).\nProof. by move=> dv_d_mn; apply/idP/idP => [/dvdn_addr | /dvdn_addl] <-. Qed.\n\nLemma dvdn_subr d m n : n <= m -> d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> le_n_m dv_d_m; apply: dvdn_add_eq; rewrite subnK. Qed.\n\nLemma dvdn_subl d m n : n <= m -> d %| n -> (d %| m - n) = (d %| m).\nProof. by move=> le_n_m dv_d_m; rewrite -(dvdn_addl _ dv_d_m) subnK. Qed.\n\nLemma dvdn_sub d m n : d %| m -> d %| n -> d %| m - n.\nProof.\nby case: (leqP n m) => [le_nm /dvdn_subr <- // | /ltnW/eqnP ->]; rewrite dvdn0.\nQed.\n\nLemma dvdn_exp k d m : 0 < k -> d %| m -> d %| (m ^ k).\nProof. by case: k => // k _ d_dv_m; rewrite expnS dvdn_mulr. Qed.\n\nHint Resolve dvdn_add dvdn_sub dvdn_exp.\n\nLemma eqn_mod_dvd d m n : n <= m -> (m == n %[mod d]) = (d %| m - n).\nProof.\nby move=> le_mn; rewrite -{1}[n]add0n -{1}(subnK le_mn) eqn_modDr mod0n.\nQed.\n\nLemma divnDl m n d : d %| m -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by case: d => // d /divnK{1}<-; rewrite divnMDl. Qed.\n\nLemma divnDr m n d : d %| n -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by move=> dv_n; rewrite addnC divnDl // addnC. Qed.\n\n(***********************************************************************)\n(*   A function that computes the gcd of 2 numbers                     *)\n(***********************************************************************)\n\nFixpoint gcdn_rec m n :=\n  let n' := n %% m in if n' is 0 then m else\n  if m - n'.-1 is m'.+1 then gcdn_rec (m' %% n') n' else n'.\n\nDefinition gcdn := nosimpl gcdn_rec.\n\nLemma gcdnE m n : gcdn m n = if m == 0 then n else gcdn (n %% m) m.\nProof.\nrewrite /gcdn; elim: m {-2}m (leqnn m) n => [|s IHs] [|m] le_ms [|n] //=.\ncase def_n': (_ %% _) => // [n'].\nhave{def_n'} lt_n'm: n' < m by rewrite -def_n' -ltnS ltn_pmod.\nrewrite {}IHs ?(leq_trans lt_n'm) // subn_if_gt ltnW //=; congr gcdn_rec.\nby rewrite -{2}(subnK (ltnW lt_n'm)) -addnS modnDr.\nQed.\n\nLemma gcdnn : idempotent gcdn.\nProof. by case=> // n; rewrite gcdnE modnn. Qed.\n\nLemma gcdnC : commutative gcdn.\nProof.\nmove=> m n; wlog lt_nm: m n / n < m.\n  by case: (ltngtP n m) => [||-> //]; last symmetry; auto.\nby rewrite gcdnE -{1}(ltn_predK lt_nm) modn_small.\nQed.\n\nLemma gcd0n : left_id 0 gcdn. Proof. by case. Qed.\nLemma gcdn0 : right_id 0 gcdn. Proof. by case. Qed.\n\nLemma gcd1n : left_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnE modn1. Qed.\n\nLemma gcdn1 : right_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnC gcd1n. Qed.\n\nLemma dvdn_gcdr m n : gcdn m n %| n.\nProof.\nelim: m {-2}m (leqnn m) n => [|s IHs] [|m] le_ms [|n] //.\nrewrite gcdnE; case def_n': (_ %% _) => [|n']; first by rewrite /dvdn def_n'.\nhave lt_n's: n' < s by rewrite -ltnS (leq_trans _ le_ms) // -def_n' ltn_pmod.\nrewrite /= (divn_eq n.+1 m.+1) def_n' dvdn_addr ?dvdn_mull //; last exact: IHs.\nby rewrite gcdnE /= IHs // (leq_trans _ lt_n's) // ltnW // ltn_pmod.\nQed.\n\nLemma dvdn_gcdl m n : gcdn m n %| m.\nProof. by rewrite gcdnC dvdn_gcdr. Qed.\n\nLemma gcdn_gt0 m n : (0 < gcdn m n) = (0 < m) || (0 < n).\nProof.\nby case: m n => [|m] [|n] //; apply: (@dvdn_gt0 _ m.+1) => //; exact: dvdn_gcdl.\nQed.\n\nLemma gcdnMDl k m n : gcdn m (k * m + n) = gcdn m n.\nProof. by rewrite !(gcdnE m) modnMDl mulnC; case: m. Qed.\n\nLemma gcdnDl m n : gcdn m (m + n) = gcdn m n.\nProof. by rewrite -{2}(mul1n m) gcdnMDl. Qed.\n\nLemma gcdnDr m n : gcdn m (n + m) = gcdn m n.\nProof. by rewrite addnC gcdnDl. Qed.\n\nLemma gcdnMl n m : gcdn n (m * n) = n.\nProof. by case: n => [|n]; rewrite gcdnE modnMl gcd0n. Qed.\n\nLemma gcdnMr n m : gcdn n (n * m) = n.\nProof. by rewrite mulnC gcdnMl. Qed.\n\nLemma gcdn_idPl {m n} : reflect (gcdn m n = m) (m %| n).\nProof.\nby apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (gcdnMl, dvdn_gcdr).\nQed.\n\nLemma gcdn_idPr {m n} : reflect (gcdn m n = n) (n %| m).\nProof. by rewrite gcdnC; apply: gcdn_idPl. Qed.\n\nLemma expn_min e m n : e ^ minn m n = gcdn (e ^ m) (e ^ n).\nProof.\nrewrite /minn; case: leqP; [rewrite gcdnC | move/ltnW];\n  by move/(dvdn_exp2l e)/gcdn_idPl.\nQed.\n\nLemma gcdn_modr m n : gcdn m (n %% m) = gcdn m n.\nProof. by rewrite {2}(divn_eq n m) gcdnMDl. Qed.\n\nLemma gcdn_modl m n : gcdn (m %% n) n = gcdn m n.\nProof. by rewrite !(gcdnC _ n) gcdn_modr. Qed.\n\n(* Extended gcd, which computes Bezout coefficients. *)\n\nFixpoint Bezout_rec km kn qs :=\n  if qs is q :: qs' then Bezout_rec kn (NatTrec.add_mul q kn km) qs'\n  else (km, kn).\n\nFixpoint egcdn_rec m n s qs :=\n  if s is s'.+1 then\n    let: (q, r) := edivn m n in\n    if r > 0 then egcdn_rec n r s' (q :: qs) else\n    if odd (size qs) then qs else q.-1 :: qs\n  else [::0].\n\nDefinition egcdn m n := Bezout_rec 0 1 (egcdn_rec m n n [::]).\n\nCoInductive egcdn_spec m n : nat * nat -> Type :=\n  EgcdnSpec km kn of km * m = kn * n + gcdn m n & kn * gcdn m n < m :\n    egcdn_spec m n (km, kn).\n\nLemma egcd0n n : egcdn 0 n = (1, 0).\nProof. by case: n. Qed.\n\nLemma egcdnP m n : m > 0 -> egcdn_spec m n (egcdn m n).\nProof.\nrewrite /egcdn; have: (n, m) = Bezout_rec n m [::] by [].\ncase: (posnP n) => [-> /=|]; first by split; rewrite // mul1n gcdn0.\nmove: {2 6}n {4 6}n {1 4}m [::] (ltnSn n) => s n0 m0.\nelim: s n m => [[]//|s IHs] n m qs /= le_ns n_gt0 def_mn0 m_gt0.\ncase: edivnP => q r def_m; rewrite n_gt0 /= => lt_rn.\ncase: posnP => [r0 {s le_ns IHs lt_rn}|r_gt0]; last first.\n  by apply: IHs => //=; [rewrite (leq_trans lt_rn) | rewrite natTrecE -def_m].\nrewrite {r}r0 addn0 in def_m; set b := odd _; pose d := gcdn m n.\npose km := ~~ b : nat; pose kn := if b then 1 else q.-1.\nrewrite (_ : Bezout_rec _ _ _ = Bezout_rec km kn qs); last first.\n  by rewrite /kn /km; case: (b) => //=; rewrite natTrecE addn0 muln1.\nhave def_d: d = n by rewrite /d def_m gcdnC gcdnE modnMl gcd0n -[n]prednK.\nhave: km * m + 2 * b * d = kn * n + d.\n  rewrite {}/kn {}/km def_m def_d -mulSnr; case: b; rewrite //= addn0 mul1n.\n  by rewrite prednK //; apply: dvdn_gt0 m_gt0 _; rewrite def_m dvdn_mulr.\nhave{def_m}: kn * d <= m.\n  have q_gt0 : 0 < q by rewrite def_m muln_gt0 n_gt0 ?andbT in m_gt0.\n  by rewrite /kn; case b; rewrite def_d def_m leq_pmul2r // leq_pred.\nhave{def_d}: km * d <= n by rewrite -[n]mul1n def_d leq_pmul2r // leq_b1.\nmove: km {q}kn m_gt0 n_gt0 def_mn0; rewrite {}/d {}/b.\nelim: qs m n => [|q qs IHq] n r kn kr n_gt0 r_gt0 /=.\n  case=> -> -> {m0 n0}; rewrite !addn0 => le_kn_r _ def_d; split=> //.\n  have d_gt0: 0 < gcdn n r by rewrite gcdn_gt0 n_gt0.\n  have: 0 < kn * n by rewrite def_d addn_gt0 d_gt0 orbT.\n  rewrite muln_gt0 n_gt0 andbT; move/ltn_pmul2l <-.\n  by rewrite def_d -addn1 leq_add // mulnCA leq_mul2l le_kn_r orbT.\nrewrite !natTrecE; set m:= _ + r; set km := _ * _ + kn; pose d := gcdn m n.\nhave ->: gcdn n r = d by rewrite [d]gcdnC gcdnMDl.\nhave m_gt0: 0 < m by rewrite addn_gt0 r_gt0 orbT.\nhave d_gt0: 0 < d by rewrite gcdn_gt0 m_gt0.\nmove/IHq=> {IHq} IHq le_kn_r le_kr_n def_d; apply: IHq => //; rewrite -/d.\n  by rewrite mulnDl leq_add // -mulnA leq_mul2l le_kr_n orbT.\napply: (@addIn d); rewrite -!addnA addnn addnCA mulnDr -addnA addnCA.\nrewrite /km mulnDl mulnCA mulnA -addnA; congr (_ + _).\nby rewrite -def_d addnC -addnA -mulnDl -mulnDr addn_negb -mul2n.\nQed.\n\nLemma Bezoutl m n : m > 0 -> {a | a < m & m %| gcdn m n + a * n}.\nProof.\nmove=> m_gt0; case: (egcdnP n m_gt0) => km kn def_d lt_kn_m.\nexists kn; last by rewrite addnC -def_d dvdn_mull.\napply: leq_ltn_trans lt_kn_m.\nby rewrite -{1}[kn]muln1 leq_mul2l gcdn_gt0 m_gt0 orbT.\nQed.\n\nLemma Bezoutr m n : n > 0 -> {a | a < n & n %| gcdn m n + a * m}.\nProof. by rewrite gcdnC; exact: Bezoutl. Qed.\n\n(* Back to the gcd. *)\n\nLemma dvdn_gcd p m n : p %| gcdn m n = (p %| m) && (p %| n).\nProof.\napply/idP/andP=> [dv_pmn | [dv_pm dv_pn]].\n  by rewrite !(dvdn_trans dv_pmn) ?dvdn_gcdl ?dvdn_gcdr.\ncase (posnP n) => [->|n_gt0]; first by rewrite gcdn0.\ncase: (Bezoutr m n_gt0) => // km _ /(dvdn_trans dv_pn).\nby rewrite dvdn_addl // dvdn_mull.\nQed.\n\nLemma gcdnAC : right_commutative gcdn.\nProof.\nsuffices dvd m n p: gcdn (gcdn m n) p %| gcdn (gcdn m p) n.\n  by move=> m n p; apply/eqP; rewrite eqn_dvd !dvd.\nrewrite !dvdn_gcd dvdn_gcdr.\nby rewrite !(dvdn_trans (dvdn_gcdl _ p)) ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma gcdnA : associative gcdn.\nProof. by move=> m n p; rewrite !(gcdnC m) gcdnAC. Qed.\n\nLemma gcdnCA : left_commutative gcdn.\nProof. by move=> m n p; rewrite !gcdnA (gcdnC m). Qed.\n\nLemma gcdnACA : interchange gcdn gcdn.\nProof. by move=> m n p q; rewrite -!gcdnA (gcdnCA n). Qed.\n\nLemma muln_gcdr : right_distributive muln gcdn.\nProof.\nmove=> p m n; case: (posnP p) => [-> //| p_gt0].\nelim: {m}m.+1 {-2}m n (ltnSn m) => // s IHs m n; rewrite ltnS => le_ms.\nrewrite gcdnE [rhs in _ = rhs]gcdnE muln_eq0 (gtn_eqF p_gt0) -muln_modr //=.\nby case: posnP => // m_gt0; apply: IHs; apply: leq_trans le_ms; apply: ltn_pmod.\nQed.\n\nLemma muln_gcdl : left_distributive muln gcdn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_gcdr. Qed.\n\nLemma gcdn_def d m n :\n    d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) ->\n  gcdn m n = d.\nProof.\nmove=> dv_dm dv_dn gdv_d; apply/eqP.\nby rewrite eqn_dvd dvdn_gcd dv_dm dv_dn gdv_d ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma muln_divCA_gcd n m : n * (m %/ gcdn n m)  = m * (n %/ gcdn n m).\nProof. by rewrite muln_divCA ?dvdn_gcdl ?dvdn_gcdr. Qed.\n\n(* We derive the lcm directly. *)\n\nDefinition lcmn m n := m * n %/ gcdn m n.\n\nLemma lcmnC : commutative lcmn.\nProof. by move=> m n; rewrite /lcmn mulnC gcdnC. Qed.\n\nLemma lcm0n : left_zero 0 lcmn.  Proof. by move=> n; exact: div0n. Qed.\nLemma lcmn0 : right_zero 0 lcmn. Proof. by move=> n; rewrite lcmnC lcm0n. Qed.\n\nLemma lcm1n : left_id 1 lcmn.\nProof. by move=> n; rewrite /lcmn gcd1n mul1n divn1. Qed.\n\nLemma lcmn1 : right_id 1 lcmn.\nProof. by move=> n; rewrite lcmnC lcm1n. Qed.\n\nLemma muln_lcm_gcd m n : lcmn m n * gcdn m n = m * n.\nProof. by apply/eqP; rewrite divnK ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma lcmn_gt0 m n : (0 < lcmn m n) = (0 < m) && (0 < n).\nProof. by rewrite -muln_gt0 ltn_divRL ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma muln_lcmr : right_distributive muln lcmn.\nProof.\ncase=> // m n p; rewrite /lcmn -muln_gcdr -!mulnA divnMl // mulnCA.\nby rewrite muln_divA ?dvdn_mull ?dvdn_gcdr.\nQed.\n\nLemma muln_lcml : left_distributive muln lcmn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_lcmr. Qed.\n\nLemma lcmnA : associative lcmn.\nProof.\nmove=> m n p; rewrite {1 3}/lcmn mulnC !divn_mulAC ?dvdn_mull ?dvdn_gcdr //.\nrewrite -!divnMA ?dvdn_mulr ?dvdn_gcdl // mulnC mulnA !muln_gcdr.\nby rewrite ![_ * lcmn _ _]mulnC !muln_lcm_gcd !muln_gcdl -!(mulnC m) gcdnA.\nQed.\n\nLemma lcmnCA : left_commutative lcmn.\nProof. by move=> m n p; rewrite !lcmnA (lcmnC m). Qed.\n\nLemma lcmnAC : right_commutative lcmn.\nProof. by move=> m n p; rewrite -!lcmnA (lcmnC n). Qed.\n\nLemma lcmnACA : interchange lcmn lcmn.\nProof. by move=> m n p q; rewrite -!lcmnA (lcmnCA n). Qed.\n\nLemma dvdn_lcml d1 d2 : d1 %| lcmn d1 d2.\nProof. by rewrite /lcmn -muln_divA ?dvdn_gcdr ?dvdn_mulr. Qed.\n\nLemma dvdn_lcmr d1 d2 : d2 %| lcmn d1 d2.\nProof. by rewrite lcmnC dvdn_lcml. Qed.\n\nLemma dvdn_lcm d1 d2 m : lcmn d1 d2 %| m = (d1 %| m) && (d2 %| m).\nProof.\ncase: d1 d2 => [|d1] [|d2]; try by case: m => [|m]; rewrite ?lcmn0 ?andbF.\nrewrite -(@dvdn_pmul2r (gcdn d1.+1 d2.+1)) ?gcdn_gt0 // muln_lcm_gcd.\nby rewrite muln_gcdr dvdn_gcd {1}mulnC andbC !dvdn_pmul2r.\nQed.\n\nLemma lcmnMl m n : lcmn m (m * n) = m * n.\nProof. by case: m => // m; rewrite /lcmn gcdnMr mulKn. Qed.\n\nLemma lcmnMr m n : lcmn n (m * n) = m * n.\nProof. by rewrite mulnC lcmnMl. Qed.\n\nLemma lcmn_idPr {m n} : reflect (lcmn m n = n) (m %| n).\nProof.\nby apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (lcmnMr, dvdn_lcml).\nQed.\n\nLemma lcmn_idPl {m n} : reflect (lcmn m n = m) (n %| m).\nProof. by rewrite lcmnC; apply: lcmn_idPr. Qed.\n\nLemma expn_max e m n : e ^ maxn m n = lcmn (e ^ m) (e ^ n).\nProof.\nrewrite /maxn; case: leqP; [rewrite lcmnC | move/ltnW];\n by move/(dvdn_exp2l e)/lcmn_idPr.\nQed.\n\n(* Coprime factors *)\n\nDefinition coprime m n := gcdn m n == 1.\n\nLemma coprime1n n : coprime 1 n.\nProof. by rewrite /coprime gcd1n. Qed.\n\nLemma coprimen1 n : coprime n 1.\nProof. by rewrite /coprime gcdn1. Qed.\n\nLemma coprime_sym m n : coprime m n = coprime n m.\nProof. by rewrite /coprime gcdnC. Qed.\n\nLemma coprime_modl m n : coprime (m %% n) n = coprime m n.\nProof. by rewrite /coprime gcdn_modl. Qed.\n\nLemma coprime_modr m n : coprime m (n %% m) = coprime m n.\nProof. by rewrite /coprime gcdn_modr. Qed.\n\nLemma coprime2n n : coprime 2 n = odd n.\nProof. by rewrite -coprime_modr modn2; case: (odd n). Qed.\n\nLemma coprimen2 n : coprime n 2 = odd n.\nProof. by rewrite coprime_sym coprime2n. Qed.\n\nLemma coprimeSn n : coprime n.+1 n.\nProof. by rewrite -coprime_modl (modnDr 1) coprime_modl coprime1n. Qed.\n\nLemma coprimenS n : coprime n n.+1.\nProof. by rewrite coprime_sym coprimeSn. Qed.\n\nLemma coprimePn n : n > 0 -> coprime n.-1 n.\nProof. by case: n => // n _; rewrite coprimenS. Qed.\n\nLemma coprimenP n : n > 0 -> coprime n n.-1.\nProof. by case: n => // n _; rewrite coprimeSn. Qed.\n\nLemma coprimeP n m :\n  n > 0 -> reflect (exists u, u.1 * n - u.2 * m = 1) (coprime n m).\nProof.\nmove=> n_gt0; apply: (iffP eqP) => [<-| [[kn km] /= kn_km_1]].\n  by have [kn km kg _] := egcdnP m n_gt0; exists (kn, km); rewrite kg addKn.\napply gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m.\nby rewrite -kn_km_1 dvdn_subr ?dvdn_mull // ltnW // -subn_gt0 kn_km_1.\nQed.\n\nLemma modn_coprime k n : 0 < k -> (exists u, (k * u) %% n = 1) -> coprime k n.\nProof.\nmove=> k_gt0 [u Hu]; apply/coprimeP=> //.\nby exists (u, k * u %/ n); rewrite /= mulnC {1}(divn_eq (k * u) n) addKn.\nQed.\n\nLemma Gauss_dvd m n p : coprime m n -> (m * n %| p) = (m %| p) && (n %| p).\nProof. by move=> co_mn; rewrite -muln_lcm_gcd (eqnP co_mn) muln1 dvdn_lcm. Qed.\n\nLemma Gauss_dvdr m n p : coprime m n -> (m %| n * p) = (m %| p).\nProof.\ncase: n => [|n] co_mn; first by case: m co_mn => [|[]] // _; rewrite !dvd1n.\nby symmetry; rewrite mulnC -(@dvdn_pmul2r n.+1) ?Gauss_dvd // andbC dvdn_mull.\nQed.\n\nLemma Gauss_dvdl m n p : coprime m p -> (m %| n * p) = (m %| n).\nProof. by rewrite mulnC; apply: Gauss_dvdr. Qed.\n\nLemma Gauss_gcdr p m n : coprime p m -> gcdn p (m * n) = gcdn p n.\nProof.\nmove=> co_pm; apply/eqP; rewrite eqn_dvd !dvdn_gcd !dvdn_gcdl /=.\nrewrite andbC dvdn_mull ?dvdn_gcdr //= -(@Gauss_dvdr _ m) ?dvdn_gcdr //.\nby rewrite /coprime gcdnAC (eqnP co_pm) gcd1n.\nQed.\n\nLemma Gauss_gcdl p m n : coprime p n -> gcdn p (m * n) = gcdn p m.\nProof. by move=> co_pn; rewrite mulnC Gauss_gcdr. Qed.\n\nLemma coprime_mulr p m n : coprime p (m * n) = coprime p m && coprime p n.\nProof.\ncase co_pm: (coprime p m) => /=; first by rewrite /coprime Gauss_gcdr.\napply/eqP=> co_p_mn; case/eqnP: co_pm; apply gcdn_def => // d dv_dp dv_dm.\nby rewrite -co_p_mn dvdn_gcd dv_dp dvdn_mulr.\nQed.\n\nLemma coprime_mull p m n : coprime (m * n) p = coprime m p && coprime n p.\nProof. by rewrite -!(coprime_sym p) coprime_mulr. Qed.\n\nLemma coprime_pexpl k m n : 0 < k -> coprime (m ^ k) n = coprime m n.\nProof.\ncase: k => // k _; elim: k => [|k IHk]; first by rewrite expn1.\nby rewrite expnS coprime_mull -IHk; case coprime.\nQed.\n\nLemma coprime_pexpr k m n : 0 < k -> coprime m (n ^ k) = coprime m n.\nProof. by move=> k_gt0; rewrite !(coprime_sym m) coprime_pexpl. Qed.\n\nLemma coprime_expl k m n : coprime m n -> coprime (m ^ k) n.\nProof. by case: k => [|k] co_pm; rewrite ?coprime1n // coprime_pexpl. Qed.\n\nLemma coprime_expr k m n : coprime m n -> coprime m (n ^ k).\nProof. by rewrite !(coprime_sym m); exact: coprime_expl. Qed.\n\nLemma coprime_dvdl m n p : m %| n -> coprime n p -> coprime m p.\nProof. by case/dvdnP=> d ->; rewrite coprime_mull => /andP[]. Qed.\n\nLemma coprime_dvdr m n p : m %| n -> coprime p n -> coprime p m.\nProof. by rewrite !(coprime_sym p); exact: coprime_dvdl. Qed.\n\nLemma coprime_egcdn n m : n > 0 -> coprime (egcdn n m).1 (egcdn n m).2.\nProof.\nmove=> n_gt0; case: (egcdnP m n_gt0) => kn km /= /eqP.\nhave [/dvdnP[u defn] /dvdnP[v defm]] := (dvdn_gcdl n m, dvdn_gcdr n m).\nrewrite -[gcdn n m]mul1n {1}defm {1}defn !mulnA -mulnDl addnC.\nrewrite eqn_pmul2r ?gcdn_gt0 ?n_gt0 //; case: kn => // kn /eqP def_knu _.\nby apply/coprimeP=> //; exists (u, v); rewrite mulnC def_knu mulnC addnK.\nQed.\n\nLemma dvdn_pexp2r m n k : k > 0 -> (m ^ k %| n ^ k) = (m %| n).\nProof.\nmove=> k_gt0; apply/idP/idP=> [dv_mn_k|]; last exact: dvdn_exp2r.\ncase: (posnP n) => [-> | n_gt0]; first by rewrite dvdn0.\nhave [n' def_n] := dvdnP (dvdn_gcdr m n); set d := gcdn m n in def_n.\nhave [m' def_m] := dvdnP (dvdn_gcdl m n); rewrite -/d in def_m.\nhave d_gt0: d > 0 by rewrite gcdn_gt0 n_gt0 orbT.\nrewrite def_m def_n !expnMn dvdn_pmul2r ?expn_gt0 ?d_gt0 // in dv_mn_k.\nhave: coprime (m' ^ k) (n' ^ k).\n  rewrite coprime_pexpl // coprime_pexpr // /coprime -(eqn_pmul2r d_gt0) mul1n.\n  by rewrite muln_gcdl -def_m -def_n.\nrewrite /coprime -gcdn_modr (eqnP dv_mn_k) gcdn0 -(exp1n k).\nby rewrite (inj_eq (expIn k_gt0)) def_m; move/eqP->; rewrite mul1n dvdn_gcdr.\nQed.\n\nSection Chinese.\n\n(***********************************************************************)\n(*   The chinese remainder theorem                                     *)\n(***********************************************************************)\n\nVariables m1 m2 : nat.\nHypothesis co_m12 : coprime m1 m2.\n\nLemma chinese_remainder x y :\n  (x == y %[mod m1 * m2]) = (x == y %[mod m1]) && (x == y %[mod m2]).\nProof.\nwlog le_yx : x y / y <= x; last by rewrite !eqn_mod_dvd // Gauss_dvd.\nby case/orP: (leq_total y x); last rewrite !(eq_sym (x %% _)); auto.\nQed.\n\n(***********************************************************************)\n(*   A function that solves the chinese remainder problem              *)\n(***********************************************************************)\n\nDefinition chinese r1 r2 :=\n  r1 * m2 * (egcdn m2 m1).1 + r2 * m1 * (egcdn m1 m2).1.\n\nLemma chinese_modl r1 r2 : chinese r1 r2 = r1 %[mod m1].\nProof.\nrewrite /chinese; case: (posnP m2) co_m12 => [-> /eqnP | m2_gt0 _].\n  by rewrite gcdn0 => ->; rewrite !modn1.\ncase: egcdnP => // k2 k1 def_m1 _.\nrewrite mulnAC -mulnA def_m1 gcdnC (eqnP co_m12) mulnDr mulnA muln1.\nby rewrite addnAC (mulnAC _ m1) -mulnDl modnMDl.\nQed.\n\nLemma chinese_modr r1 r2 : chinese r1 r2 = r2 %[mod m2].\nProof.\nrewrite /chinese; case: (posnP m1) co_m12 => [-> /eqnP | m1_gt0 _].\n  by rewrite gcd0n => ->; rewrite !modn1.\ncase: (egcdnP m2) => // k1 k2 def_m2 _.\nrewrite addnC mulnAC -mulnA def_m2 (eqnP co_m12) mulnDr mulnA muln1.\nby rewrite addnAC (mulnAC _ m2) -mulnDl modnMDl.\nQed.\n\nLemma chinese_mod x : x = chinese (x %% m1) (x %% m2) %[mod m1 * m2].\nProof.\napply/eqP; rewrite chinese_remainder //.\nby rewrite chinese_modl chinese_modr !modn_mod !eqxx.\nQed.\n\nEnd Chinese.\n", "meta": {"author": "beta-ziliani", "repo": "ssreflect-1.4", "sha": "2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571", "save_path": "github-repos/coq/beta-ziliani-ssreflect-1.4", "path": "github-repos/coq/beta-ziliani-ssreflect-1.4/ssreflect-1.4-2b3cfcb0fa4e1dcdc9cac2bad282a667abfa8571/theories/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.843895098628499, "lm_q1q2_score": 0.7286119419211232}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus (plus y x) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj206_coqofml_v8XoJk.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7285552584734271}}
{"text": "Parameters A B C : Set.\n\nDefinition curry (f : A * B -> C) := fun a => fun b => f (a, b).\nDefinition uncurry (g : A -> B -> C) := fun p => g (fst p) (snd p).\n\nTheorem better : forall f a b, uncurry (curry f) (a, b) = f (a, b).\nTheorem converse : forall f a b, curry (uncurry f) a b = f a b.\nProof.\n  intros.\n  unfold curry, uncurry.\n  simpl.\n  reflexivity.\nQed.\nInductive ev : nat -> Prop :=\n  | ev_0 : ev O\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n H.\n  inversion H as [|n'].\n  inversion H1 as [|n''].\n  assumption.\nQed.\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", "meta": {"author": "MichaelBurge", "repo": "matroids", "sha": "a9e42e2f93af300caf408ad9b25712431a2f79fe", "save_path": "github-repos/coq/MichaelBurge-matroids", "path": "github-repos/coq/MichaelBurge-matroids/matroids-a9e42e2f93af300caf408ad9b25712431a2f79fe/polymorphic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7285552565172703}}
{"text": "(* Reference: https://www.cs.umd.edu/~rrand/vqc/Matrix.html#Matrix *)\n\nRequire Import Psatz.\nRequire Import Setoid.\nRequire Import Arith.\nRequire Import Bool.\nRequire Import Program.\nRequire Import ZSum.\nRequire Export Coq.ZArith.ZArith.\n\nDelimit Scope matrix_scope with M.\nOpen Scope matrix_scope.\nOpen Scope nat_scope.\n\n(* We define a _matrix_ as a simple function from two nats\n(corresponding to a row and a column) to a integer. *)\nDefinition Matrix (m n : nat) := nat -> nat -> Z.\n\nBind Scope matrix_scope with Matrix.\nNotation Vector n := (Matrix n 1).\nNotation Square n := (Matrix n n).\n\nDefinition mat_equiv {m n : nat} (A B : Matrix m n) : Prop :=\n  forall i j, i < m -> j < n -> A i j = B i j.\n\nInfix \"==\" := mat_equiv (at level 80).\n\n(* Some important notions about matrix equality. *)\nLemma mat_equiv_refl : forall {m n} (A : Matrix m n), A == A.\nProof.\n  intros.\n  unfold mat_equiv. \n  intros. \n  reflexivity.\nQed.\n\nLemma mat_equiv_sym : forall {m n} (A B : Matrix m n), A == B -> B == A.\nProof.\n  unfold mat_equiv.\n  intros.\n  specialize (H i j H0 H1).\n  rewrite H. \n  reflexivity.\nQed.\n\nLemma mat_equiv_trans : forall {m n} (A B C : Matrix m n),\n    A == B -> B == C -> A == C.\nProof.\n  unfold mat_equiv.\n  intros.\n  specialize (H i j H1 H2).\n  specialize (H0 i j H1 H2).\n  rewrite H, H0. \n  reflexivity.\nQed.\n\nAdd Parametric Relation m n : (Matrix m n) (@mat_equiv m n)\n  reflexivity proved by mat_equiv_refl\n  symmetry proved by mat_equiv_sym\n  transitivity proved by mat_equiv_trans\n    as mat_equiv_rel.\n\n(* ################################################################# *)\n(** * Basic Matrices and Operations *)\n\nClose Scope nat_scope.\nOpen Scope Z_scope.\n\n(** Because we will use these so often, it is good to have them in matrix scope. *)\nNotation \"m =? n\" := (Nat.eqb m n) (at level 70) : matrix_scope.\nNotation \"m <? n\" := (Nat.ltb m n) (at level 70) : matrix_scope.\nNotation \"m <=? n\" := (Nat.leb m n) (at level 70) : matrix_scope.\n\nOpen Scope matrix_scope.\n\nDefinition I (n : nat) : Matrix n n := fun i j => if (i =? j)%nat then 1 else 0.\n\nDefinition Zero (m n : nat) : Matrix m n := fun _ _ => 0.\n\nDefinition Mplus {m n : nat} (A B : Matrix m n) : Matrix m n :=\n  fun i j => A i j + B i j.\n\nDefinition Mminus {m n : nat} (A B : Matrix m n) : Matrix m n :=\n  fun i j => A i j - B i j.\n\nInfix \"+\" := Mplus (at level 50, left associativity) : matrix_scope.\nInfix \"-\" := Mminus (at level 50, left associativity) : matrix_scope.\n\nLemma Mplus_assoc : forall {m n} (A B C : Matrix m n), (A + B) + C == A + (B + C).\nProof.\n  intros m n A B C i j Hi Hj.\n  unfold Mplus.\n  lia.\nQed.\n\nLemma Mplus_comm : forall {m n} (A B : Matrix m n), A + B == B + A.\nProof.\n  intros m n A B i j Hi Hj.\n  unfold Mplus.\n  lia.\nQed.\n\nLemma Mplus_0_l : forall {m n} (A : Matrix m n), Zero m n + A == A.\nProof.\n  intros m n A i j Hi Hj.\n  unfold Zero, Mplus.\n  lia.\nQed.\n\nLemma Mplus_0_r : forall {m n} (A : Matrix m n), A + Zero m n == A.\nProof.\n  intros m n A.\n  rewrite Mplus_comm.\n  apply Mplus_0_l.\nQed.\n\nLemma Mplus_compat : forall {m n} (A B A' B' : Matrix m n),\n  A == A' -> B == B' -> A + B == A' + B'.\nProof.\n  intros m n A B A' B' HA HB.\n  intros i j Hi Hj.\n  unfold Mplus.\n  rewrite HA, HB; tauto.\nQed.\n\nAdd Parametric Morphism m n : (@Mplus m n)\n  with signature mat_equiv ==> mat_equiv ==> mat_equiv as Mplus_mor.\nProof.\n  intros A A' HA B B' HB.\n  apply Mplus_compat; tauto.\nQed.\n\nLemma Mminus_compat : forall {m n} (A B A' B' : Matrix m n),\n  A == A' -> B == B' -> A - B == A' - B'.\nProof.\n  intros m n A B A' B' HA HB.\n  intros i j Hi Hj.\n  unfold Mminus.\n  rewrite HA, HB; tauto.\nQed.\n\nAdd Parametric Morphism m n : (@Mminus m n)\n  with signature mat_equiv ==> mat_equiv ==> mat_equiv as Mminus_mor.\nProof.\n  intros A A' HA B B' HB.\n  apply Mminus_compat; tauto.\nQed.\n\nDefinition Mmult {m n o : nat} (A : Matrix m n) (B : Matrix n o) : Matrix m o :=\n  fun x z => Zsum (fun y => A x y * B y z)%Z n.\n\nInfix \"×\" := Mmult (at level 40, left associativity) : matrix_scope.\n\nLemma Mmult_compat : forall {m n o} (A A' : Matrix m n) (B B' : Matrix n o),\n    A == A' -> B == B' -> A × B == A' × B'.\nProof.\n  intros m n o A A' B B' HA HB i j Hi Hj.\n  unfold Mmult.\n  apply Zsum_eq; intros x Hx.\n  rewrite HA, HB; tauto.\nQed.\n\nAdd Parametric Morphism m n o : (@Mmult m n o)\n  with signature mat_equiv ==> mat_equiv ==> mat_equiv as Mmult_mor.\nProof. intros. apply Mmult_compat; easy. Qed.\n\nDefinition SubMat {m n} (A : Matrix m n) (rowl rowh coll colh : nat) : Matrix (rowh - rowl)%nat (colh - coll)%nat :=\n  fun i j => A (i + rowl)%nat (j + coll)%nat.\n\nDefinition Split(n : nat) (A : Square (2 * n)) (A11 A12 A21 A22 : Square n): Prop :=\n  A11 = SubMat A 0 n 0 n  /\\\n  A12 = SubMat A 0 n n (2 * n) /\\\n  A21 = SubMat A n (2 * n) 0 n /\\ \n  A22 = SubMat A n (2 * n) n (2 * n)\n.\n\nLemma Splitable(n : nat) (A : Square (2 * n)): \n  n <> Z.to_nat 0 ->\n  exists (A11 A12 A21 A22 : Square n), Split n A A11 A12 A21 A22.\nProof.\n  intros.\n  exists \n    (SubMat A 0 n 0 n),\n    (SubMat A 0 n n (2 * n)), \n    (SubMat A n (2 * n) 0 n), \n    (SubMat A n (2 * n) n (2 * n))\n  .\n  unfold Split.\n  tauto.\nQed.\n\n(* ################################################################# *)\n(** * Matrix Properties *)\n\nTheorem Mmult_assoc : forall {m n o p : nat} (A : Matrix m n) (B : Matrix n o) \n  (C: Matrix o p), A × B × C == A × (B × C).\nProof.\n  intros m n o p A B C i j Hi Hj.\n  unfold Mmult.\n  induction n.\n  + simpl.\n    clear B.\n    induction o. reflexivity.\n    simpl. rewrite IHo.\n    - lia.\n    - tauto. \n  + simpl. \n    rewrite <- IHn.\n    simpl.\n    rewrite Zsum_mult_l.\n    rewrite <- Zsum_plus.\n    apply Zsum_eq; intros.\n    rewrite Zmult_plus_dist_r.\n    rewrite Zmult_assoc.\n    reflexivity.\nQed.\n\n                                                   \n(* ################################################################# *)\n(** * Matrix Library *)\n\nLemma Mmult_plus_dist_l : forall {m n o : nat} (A : Matrix m n) (B C : Matrix n o), \n                           A × (B + C) == A × B + A × C.\nProof. \n  intros. intros i j _ _.\n  unfold Mplus, Mmult.\n  rewrite <- Zsum_plus.\n  apply Zsum_eq_bounded; intros.\n  rewrite Zmult_plus_dist_l. \n  reflexivity.\nQed.\n\nLemma Mmult_plus_dist_r : forall {m n o : nat} (A B : Matrix m n) (C : Matrix n o), \n                           (A + B) × C == A × C + B × C.\nProof. \n  intros. intros i j _ _.\n  unfold Mplus, Mmult.\n  rewrite <- Zsum_plus.\n  apply Zsum_eq_bounded; intros.\n  rewrite Zmult_plus_dist_r. \n  reflexivity.\nQed.\n\nLemma Mmult_plus_dist : forall {m n o : nat} (A B : Matrix m n) (C D : Matrix n o), \n                           (A + B) × (C + D) == A × C + A × D + B × C + B × D.\nProof. \n  intros.\n  pose proof (Mmult_plus_dist_l (A + B) C D).\n  rewrite H.\n  pose proof (Mmult_plus_dist_r A B C).\n  pose proof (Mmult_plus_dist_r A B D).\n  rewrite H0, H1.\n  intros i j _ _.\n  unfold Mplus.\n  lia.\nQed.\n\nLemma Mmult_minus_dist_l : forall {m n o : nat} (A : Matrix m n) (B C : Matrix n o), \n                           A × (B - C) == A × B - A × C.\nProof. \n  intros. intros i j _ _.\n  unfold Mminus, Mmult.\n  rewrite <- Zsum_minus.\n  apply Zsum_eq_bounded; intros.\n  rewrite Zmult_minus_dist_l. \n  reflexivity.\nQed.\n\nLemma Mmult_minus_dist_r : forall {m n o : nat} (A B : Matrix m n) (C : Matrix n o), \n                           (A - B) × C == A × C - B × C.\nProof. \n  intros. intros i j _ _.\n  unfold Mminus, Mmult.\n  rewrite <- Zsum_minus.\n  apply Zsum_eq_bounded; intros.\n  rewrite Zmult_minus_dist_r. \n  reflexivity.\nQed.\n\nLemma Mmult_minus_dist : forall {m n o : nat} (A B : Matrix m n) (C D : Matrix n o), \n                           (A - B) × (C - D) == A × C - A × D - B × C + B × D.\nProof. \n  intros.\n  pose proof (Mmult_minus_dist_l (A - B) C D).\n  rewrite H.\n  pose proof (Mmult_minus_dist_r A B C).\n  pose proof (Mmult_minus_dist_r A B D).\n  rewrite H0, H1.\n  intros i j _ _.\n  unfold Mplus, Mminus.\n  lia.\nQed.\n\nLemma Mmult_minus_plus_dist : forall {m n o : nat} (A B : Matrix m n) (C D : Matrix n o), \n                           (A - B) × (C + D) == A × C + A × D - B × C - B × D.\nProof. \n  intros.\n  pose proof (Mmult_plus_dist_l (A - B) C D).\n  rewrite H.\n  pose proof (Mmult_minus_dist_r A B C).\n  pose proof (Mmult_minus_dist_r A B D).\n  rewrite H0, H1.\n  intros i j _ _.\n  unfold Mplus, Mminus.\n  lia.\nQed.\n\nLemma Mmult_plus_minus_dist : forall {m n o : nat} (A B : Matrix m n) (C D : Matrix n o), \n                           (A + B) × (C - D) == A × C - A × D + B × C - B × D.\nProof. \n  intros.\n  pose proof (Mmult_minus_dist_l (A + B) C D).\n  rewrite H.\n  pose proof (Mmult_plus_dist_r A B C).\n  pose proof (Mmult_plus_dist_r A B D).\n  rewrite H0, H1.\n  intros i j _ _.\n  unfold Mplus, Mminus.\n  lia.\nQed.\n\n(* Haoxuan Xu, Yichen Tao *)\n(* 2021-05-26 14:34 *)", "meta": {"author": "TerryXhx", "repo": "Correctness-of-Strassen-Algorithm", "sha": "b27bf99233a76e4b3b7dbd1936c03243829024ec", "save_path": "github-repos/coq/TerryXhx-Correctness-of-Strassen-Algorithm", "path": "github-repos/coq/TerryXhx-Correctness-of-Strassen-Algorithm/Correctness-of-Strassen-Algorithm-b27bf99233a76e4b3b7dbd1936c03243829024ec/Matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7285334648922579}}
{"text": "Require Export SfLib.\n\nModule AExp.\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n  | BTrue : bexp\n  | BFalse : bexp\n  | BEq : aexp -> aexp -> bexp\n  | BLe : aexp -> aexp -> bexp\n  | BNot : bexp -> bexp\n  | BAnd : bexp -> bexp -> bexp.\n\nFixpoint aeval (e : aexp) : nat :=\n  match e with\n  | ANum n => n\n  | APlus a1 a2 => (aeval a1) + (aeval a2)\n  | AMinus a1 a2 => (aeval a1) - (aeval a2)\n  | AMult a1 a2 => (aeval a1) * (aeval a2)\n  end.\n\nExample test_aeval1:\n  aeval (APlus (ANum 2) (ANum 2)) = 4.\nProof.\n  reflexivity.\nQed.\n\nFixpoint beval (e : bexp) : bool :=\n  match e with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => beq_nat (aeval a1) (aeval a2)\n  | BLe a1 a2 => ble_nat (aeval a1) (aeval a2)\n  | BNot b1 => negb (beval b1)\n  | BAnd b1 b2 => andb (beval b1) (beval b2)\n  end.\n\nFixpoint optimize_0plus (e : aexp) : aexp :=\n  match e with\n  | ANum n => ANum n\n  | APlus (ANum 0) n => n\n  | APlus e1 e2 => APlus (optimize_0plus e1) (optimize_0plus e2)\n  | AMinus e1 e2 => AMinus (optimize_0plus e1) (optimize_0plus e2)\n  | AMult e1 e2 => AMult (optimize_0plus e1) (optimize_0plus e2)\n  end.\n\nTheorem optimize_0plus_sound : forall e,\n  aeval (optimize_0plus e) = aeval e.\nProof.\n  intros e. induction e; try (simpl; auto; fail).\n\n  destruct e1.\n  + destruct n; simpl; auto.\n  + destruct e1_1; simpl; auto.\n  + destruct e1_1; simpl; auto.\n  + destruct e1_1; simpl; auto.\nQed.\n\nFixpoint bexp_map_aexp (f : aexp -> aexp) (b : bexp) :=\n  match b with\n  | BTrue => BTrue\n  | BFalse => BFalse\n  | BEq a1 a2 => BEq (f a1) (f a2)\n  | BLe a1 a2 => BLe (f a1) (f a2)\n  | BNot b => BNot (bexp_map_aexp f b)\n  | BAnd b1 b2 => BAnd (bexp_map_aexp f b1) (bexp_map_aexp f b2)\n  end.\n\nTheorem beval_map_aexp_sound \n  (f : aexp -> aexp) \n  (H : forall a:aexp, aeval (f a) = aeval a) :\n  forall b: bexp, beval (bexp_map_aexp f b) = beval b.\nProof.\n  intro b.\n  induction b; simpl; auto.\n  + rewrite IHb; trivial. \n  + rewrite IHb1, IHb2; trivial.\nQed.\n\nReserved Notation \"e '==>' n\" (at level 40).\nInductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum : forall (n:nat), (ANum n) ==> n\n  | E_APlus : forall (e1 e2 : aexp) (n1 n2 : nat),\n      (e1 ==> n1) -> (e2 ==> n2) -> (APlus e1 e2) ==> (n1 + n2)\n  | E_AMinus : forall (e1 e2 : aexp) (n1 n2 : nat),\n      (e1 ==> n1) -> (e2 ==> n2) -> (AMinus e1 e2) ==> (n1 - n2)\n  | E_AMult : forall (e1 e2 : aexp) (n1 n2 : nat),\n      (e1 ==> n1) -> (e2 ==> n2) -> (AMult e1 e2) ==> (n1 * n2)\n  where \"e '==>' n\" := (aevalR e n).\n\nTheorem aeval_iff_aevalR : forall a n,\n  aeval a = n <-> (a ==> n).\nProof.\n  split.\n  + generalize dependent n.\n    induction a; intros; subst; constructor;\n      try apply IHa1; try apply IHa2; reflexivity.\n  + intros. induction H; simpl; auto.\nQed.\n\nEnd AExp.\n\n(* States *)\nDefinition state := id -> nat.\nDefinition empty_state : state := fun _ => 0.\nDefinition update (st : state) (V : id) (n : nat) : state :=\n  fun V' => if beq_id V V' then n else st V'.\n\nTheorem update_eq : forall n V st,\n  (update st V n) V = n.\nProof.\n  intros.\n  unfold update.\n  assert (beq_id V V = true).\n    destruct V. induction n0; auto.\n  rewrite H; auto.\nQed.\n\nTheorem update_neq : forall V2 V1 n st,\n  beq_id V2 V1 = false ->\n  (update st V2 n) V1 = (st V1).\nProof.\n  intros.\n  unfold update. rewrite H.\n  reflexivity.\nQed.\n\nTheorem update_example : forall (n:nat),\n  (update empty_state (Id 2) n) (Id 3) = 0.\nProof.\n  intro.\n  compute.\n  reflexivity.\nQed.\n\nTheorem update_shadow : forall x1 x2 k1 k2 (f : state),\n   (update (update f k2 x1) k2 x2) k1 = (update f k2 x2) k1.\nProof.\n  intros.\n  unfold update.\n  destruct (beq_id k2 k1); auto.\nQed.\n\nTheorem beq_id_eq k1 k2 : beq_id k1 k2 = true <-> k1 = k2.\nProof.\n  split.\n\n  - destruct k1. \n    destruct k2. \n    revert n0.\n\n    induction n; induction n0.\n\n    + auto.\n    + intros; inversion H.\n    + intros; inversion H.\n    + intros. repeat f_equal.\n      assert (beq_id (Id n) (Id n0) = true).\n      rewrite <- H.\n      compute. auto.\n      assert (Id n = Id n0) by apply (IHn n0 H0).\n      injection H1; intro; auto.\n  - intro.\n    rewrite H.\n    destruct k2.\n    unfold beq_id; simpl.\n    clear H; clear k1.\n    induction n; auto.\nQed.\n\nTheorem update_same : forall x1 k1 k2 (f : state),\n  f k1 = x1 ->\n  (update f k1 x1) k2 = f k2.\nProof.\n  intros.\n  unfold update.\n  remember (beq_id k1 k2) as H'.\n  destruct H'; auto.\n  symmetry in HeqH'.\n  rewrite <- H.\n  assert (k1 = k2) by\n    (apply (beq_id_eq _ _); auto).\n  subst. auto.\nQed.\n \nTheorem update_permute : forall x1 x2 k1 k2 k3 f,\n  beq_id k2 k1 = false ->\n  (update (update f k2 x1) k1 x2) k3 = (update (update f k1 x2) k2 x1) k3.\nProof.\n  intros.\n  unfold update.\n  remember (beq_id k1 k3) as b.\n  destruct b.\n  remember (beq_id k2 k3) as b'.\n  destruct b'.\n  + symmetry in Heqb; symmetry in Heqb'.\n    assert (k1 = k3) by (apply (beq_id_eq _ _); auto).\n    assert (k2 = k3) by (apply (beq_id_eq _ _); auto).\n    rewrite H0 in H.\n    rewrite H1 in H.\n    assert (beq_id k3 k3 = true)\n      by (apply (beq_id_eq k3 k3); auto).\n      rewrite H2 in H; inversion H.\n  + auto.\n  + auto.\nQed.\n\n\nInductive aexp : Type :=\n  | ANum : nat -> aexp\n  | AId : id -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n  | BTrue : bexp\n  | BFalse : bexp\n  | BEq : aexp -> aexp -> bexp\n  | BLe : aexp -> aexp -> bexp\n  | BNot : bexp -> bexp\n  | BAnd : bexp -> bexp -> bexp.\n\nDefinition X : id := Id 0.\nDefinition Y : id := Id 1.\nDefinition Z : id := Id 2.\n\nFixpoint aeval (st : state) (e : aexp) : nat :=\n  match e with\n  | AId id => st id\n  | ANum n => n\n  | APlus a1 a2 => (aeval st a1) + (aeval st a2)\n  | AMinus a1 a2 => (aeval st a1) - (aeval st a2)\n  | AMult a1 a2 => (aeval st a1) * (aeval st a2)\n  end.\n\nFixpoint beval (st : state) (e : bexp) : bool :=\n  match e with\n  | BTrue => true\n  | BFalse => false\n  | BEq a1 a2 => beq_nat (aeval st a1) (aeval st a2)\n  | BLe a1 a2 => ble_nat (aeval st a1) (aeval st a2)\n  | BNot b1 => negb (beval st b1)\n  | BAnd b1 b2 => andb (beval st b1) (beval st b2)\n  end.\n\nInductive com : Type :=\n  | CSkip : com\n  | CAss : id -> aexp -> com\n  | CSeq : com -> com -> com\n  | CIf : bexp -> com -> com -> com\n  | CWhile : bexp -> com -> com.\n\nNotation \"'SKIP'\" :=\n  CSkip.\nNotation \"l '::=' a\" :=\n  (CAss l a) (at level 60).\nNotation \"c1 ; c2\" :=\n  (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity).\nNotation \"'IFB' e1 'THEN' e2 'ELSE' e3 'FI'\" :=\n  (CIf e1 e2 e3) (at level 80, right associativity).\n\nFixpoint ceval_step1 (st : state) (c : com) : state :=\n  match c with\n  | SKIP => st\n  | l ::= a1 =>\n      update st l (aeval st a1)\n  | c1 ; c2 =>\n      let st' := ceval_step1 st c1 in\n      ceval_step1 st' c2\n  | IFB b THEN c1 ELSE c2 FI =>\n      if (beval st b)\n      then ceval_step1 st c1\n      else ceval_step1 st c2\n  | WHILE b1 DO c1 END => st\n  end.\n\n\nFixpoint ceval_step2 (st : state) (c : com) (i : nat) : state :=\n  match i with\n  | O => empty_state\n  | S i' =>\n    match c with\n      | SKIP =>\n          st\n      | l ::= a1 =>\n          update st l (aeval st a1)\n      | c1 ; c2 =>\n          let st' := ceval_step2 st c1 i' in\n          ceval_step2 st' c2 i'\n      | IFB b THEN c1 ELSE c2 FI =>\n          if (beval st b) then ceval_step2 st c1 i' else ceval_step2 st c2 i'\n      | WHILE b1 DO c1 END =>\n          if (beval st b1)\n          then let st' := ceval_step2 st c1 i' in\n               ceval_step2 st' c i'\n          else st\n    end\n  end.\n\n\nFixpoint ceval_step3 (st : state) (c : com) (i : nat)\n                    : option state :=\n  match i with\n  | O => None\n  | S i' =>\n    match c with\n      | SKIP =>\n          Some st\n      | l ::= a1 =>\n          Some (update st l (aeval st a1))\n      | c1 ; c2 =>\n          match (ceval_step3 st c1 i') with\n          | Some st' => ceval_step3 st' c2 i'\n          | None => None\n          end\n      | IFB b THEN c1 ELSE c2 FI =>\n          if (beval st b) then ceval_step3 st c1 i' else ceval_step3 st c2 i'\n      | WHILE b1 DO c1 END =>\n          if (beval st b1)\n          then match (ceval_step3 st c1 i') with\n               | Some st' => ceval_step3 st' c i'\n               | None => None\n               end\n          else Some st\n    end\n  end.\n\n\nDefinition bind_option {X Y : Type} (xo : option X) (f : X -> option Y)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => f x\n  end.\n\nFixpoint ceval_step (st : state) (c : com) (i : nat)\n                    : option state :=\n  match i with\n  | O => None\n  | S i' =>\n    match c with\n      | SKIP =>\n          Some st\n      | l ::= a1 =>\n          Some (update st l (aeval st a1))\n      | c1 ; c2 =>\n          bind_option\n            (ceval_step st c1 i')\n            (fun st' => ceval_step st' c2 i')\n      | IFB b THEN c1 ELSE c2 FI =>\n          if (beval st b) then ceval_step st c1 i' else ceval_step st c2 i'\n      | WHILE b1 DO c1 END =>\n          if (beval st b1)\n          then bind_option\n                 (ceval_step st c1 i')\n                 (fun st' => ceval_step st' c i')\n          else Some st\n    end\n  end.\n\nDefinition test_ceval (st:state) (c:com) :=\n  match ceval_step st c 500 with\n  | None => None\n  | Some st => Some (st X, st Y, st Z)\n  end.\n\nDefinition pup_to_n : com :=\n  Z ::= ANum 1;\n  Y ::= ANum 0;\n  WHILE BLe (AId Z) (AId X) DO\n    Y ::= APlus (AId Y) (AId Z);\n    Z ::= APlus (AId Z) (ANum 1)\n  END;\n  X ::= ANum 0;\n  Z ::= ANum 0.\n\n\n\nExample pup_to_n_1 : \n  test_ceval (update empty_state X 5) pup_to_n\n  = Some (0, 15, 0).\nProof. reflexivity. Qed.\n\nDefinition even_X : com :=\n  Z ::= ANum 1;\n  WHILE BNot (BEq (AId X) (ANum 0)) DO\n    X ::= AMinus (AId X) (ANum 1);\n    Z ::= AMinus (ANum 1) (AId Z)\n  END.\n\nReserved Notation \"c1 '/' st '==>' st'\" (at level 40, st at level 39).\nInductive ceval : com -> state -> state -> Prop :=\n  | E_Skip : forall st,\n      SKIP / st ==> st\n  | E_Ass : forall st a1 n l,\n      aeval st a1 = n ->\n      (l ::= a1) / st ==> (update st l n)\n  | E_Seq : forall c1 c2 st st' st'',\n      c1 / st ==> st' ->\n      c2 / st' ==> st'' ->\n      (c1 ; c2) / st ==> st''\n  | E_IfTrue : forall st st' b1 c1 c2,\n      beval st b1 = true ->\n      c1 / st ==> st' ->\n      (IFB b1 THEN c1 ELSE c2 FI) / st ==> st'\n  | E_IfFalse : forall st st' b1 c1 c2,\n      beval st b1 = false ->\n      c2 / st ==> st' ->\n      (IFB b1 THEN c1 ELSE c2 FI) / st ==> st'\n  | E_WhileEnd : forall b1 st c1,\n      beval st b1 = false ->\n      (WHILE b1 DO c1 END) / st ==> st\n  | E_WhileLoop : forall st st' st'' b1 c1,\n      beval st b1 = true ->\n      c1 / st ==> st' ->\n      (WHILE b1 DO c1 END) / st' ==> st'' ->\n      (WHILE b1 DO c1 END) / st ==> st''\n\n  where \"c1 '/' st '==>' st'\" := (ceval c1 st st').\n\nTheorem ceval_step__ceval: forall c st st',\n      (exists i, ceval_step st c i = Some st') ->\n      c / st ==> st'.\nProof.\n  intros.\n  destruct H; rename H into E.\n  generalize dependent st.\n  generalize dependent st'.\n  generalize dependent c.\n  induction x.\n  + (* x = 0 *)\n    intros; inversion E.\n  + induction c; intros; inversion E; try (constructor; auto; fail).\n    - unfold bind_option in H0.\n      remember (ceval_step st c1 x).\n      induction o.\n      * apply E_Seq with (st' := a);\n        apply IHx; auto.\n      * inversion H0.\n    - remember (beval st b) as bval.\n      induction bval.\n      * apply E_IfTrue; auto.\n      * apply E_IfFalse; auto.\n    - remember (beval st b) as bval.\n      induction bval.\n      * unfold bind_option in H0.\n        remember (ceval_step st c x).\n        destruct o.\n        apply E_WhileLoop with (st':=s); auto.\n        try inversion H0.\n      * inversion H0.\n        apply E_WhileEnd.\n        subst; auto.\nQed.\n\nTheorem ceval_step_more: forall i1 i2 st st' c,\n  i1 <= i2 -> ceval_step st c i1 = Some st' ->\n  ceval_step st c i2 = Some st'.\nProof.\n  induction i1.\n  * intros; inversion H0.\n  * intros.\n    induction i2; [inversion H | .. ].\n    apply le_S_n in H.\n    destruct c.\n    - (* SKIP *) simpl; inversion H0; auto.\n    - (* ::= *) simpl; inversion H0; auto.\n    - (* ; *)\n      inversion H0.  \n      remember (ceval_step st c1 i1) as st'c1.\n      destruct st'c1; symmetry in Heqst'c1.\n      + simpl.\n        pose Heqst'c1.\n        apply IHi1 with (i2:=i2) in e; auto.\n        rewrite e; simpl.\n        simpl in H2.\n        rewrite (IHi1 i2 _ _ _ H H2).\n        auto.\n      + inversion H2.\n   - (* IF *)\n     inversion H0; simpl.\n     destruct (beval st b).\n     + rewrite (IHi1 i2 _ _ _ H H2).\n       auto.\n     + rewrite (IHi1 i2 _ _ _ H H2).\n       auto.\n   - (* WHILE *)\n     inversion H0; simpl.\n     destruct (beval st b); try reflexivity.\n     remember (ceval_step st c i1) as st'c1.\n     destruct st'c1. \n     + simpl. simpl in H2.\n       symmetry in Heqst'c1.\n       assert (ceval_step st c i2 = Some s) as Heqst'c1'\n         by (apply IHi1; auto).\n       rewrite Heqst'c1'.\n       simpl.\n       rewrite H2.\n       apply IHi1 with (i2:=i2) in H2; auto.\n     + inversion H2.\nQed.\n\nTheorem ceval_deterministic: forall c st st1 st2,\n     c / st ==> st1 ->\n     c / st ==> st2 ->\n     st1 = st2.\nProof.\n  intros.\n  generalize dependent st2.\n  (*induction c. \n  - inversion H; intros; inversion H0; auto.\n  - inversion H; intros. inversion H5.\n    rewrite <- H10, <- H4; reflexivity.\n  - inversion H; subst.\n    intros.\n    inversion H0; subst.\n\n  inversion H6; subst.*)\n\n  induction H.\n  - intros. inversion H0. auto.\n  - intros. inversion H0; subst. auto.\n  - intros. inversion H1; subst.\n    apply IHceval2.\n    rewrite (IHceval1 st'0 H4).\n    auto.\n  - intros.\n    inversion H1; subst.\n    + apply IHceval; auto. \n    + rewrite H7 in H.\n      inversion H.\n  - intros.\n    inversion H1; subst.\n    + congruence.\n    + apply IHceval; auto.\n  - intros.\n    inversion H0; subst; auto.\n    congruence.\n  - intros.\n    inversion H2; subst.\n    + congruence.\n    + apply IHceval2.\n      rewrite IHceval1 with (st2:=st'0); auto.\nQed.\n\nInductive sinstr : Type :=\n  | SPush : nat -> sinstr\n  | SLoad : id -> sinstr\n  | SPlus : sinstr\n  | SMinus : sinstr\n  | SMult : sinstr.\n     \nFixpoint s_execute (st : state) (stack : list nat)\n  (prog : list sinstr) : list nat :=\n  match prog with\n  | instr :: prog' =>\n      match instr with\n      | SPush n => s_execute st (n :: stack) prog'\n      | SLoad V => s_execute st (st V :: stack) prog'\n      | SPlus =>\n          match stack with\n          | a :: b :: stack' =>\n              s_execute st ((b + a) :: stack') prog'\n          | _ => s_execute st stack prog'\n          end\n      | SMult =>\n          match stack with\n          | a :: b :: stack' => \n              s_execute  st ((b * a) :: stack') prog'\n          | _ => s_execute st stack prog'\n          end\n      | SMinus =>\n          match stack with\n          | a :: b :: stack' =>\n              s_execute  st ((b - a) :: stack') prog'\n          | _ => s_execute st stack prog'\n          end\n      end\n  | nil => stack\n  end.\n\nFixpoint s_compile (e : aexp) : list sinstr :=\n  match e with\n  | ANum n => [SPush n]\n  | AId V => [SLoad V]\n  | APlus e1 e2 => s_compile e1 ++ s_compile e2 ++ [SPlus]\n  | AMult e1 e2 => s_compile e1 ++ s_compile e2 ++ [SMult]\n  | AMinus e1 e2 => s_compile e1 ++ s_compile e2 ++ [SMinus]\n  end.\n \nTheorem s_execute_compose : forall st stk x xs,\n s_execute st stk (x :: xs) = s_execute st (s_execute st stk [x]) xs.\nProof.\n  induction stk. \n  - intros.\n    destruct x; auto.\n  - intros.\n    simpl.\n    destruct x; destruct stk; auto.\nQed.\n\nTheorem s_execute_compose' st stk l1 l2:\n s_execute st stk (l1 ++ l2) = s_execute st (s_execute st stk l1) l2.\nProof.\n  generalize dependent stk.\n  induction l1.\n  - auto.\n  - rewrite <- app_comm_cons.\n    intro.\n    rewrite s_execute_compose.\n    rewrite IHl1.\n    rewrite <- s_execute_compose.\n    auto.\nQed.\n\nTheorem s_compile_correct : forall (st : state) (e : aexp) stk,\n  s_execute st stk (s_compile e) = (aeval st e) :: stk.\nProof.\n  induction e; simpl; auto;\n   (intros;\n    rewrite s_execute_compose';\n    rewrite s_execute_compose';\n    rewrite IHe1;\n    rewrite IHe2;\n    reflexivity).\nQed.\n\n", "meta": {"author": "let-def", "repo": "ml-test", "sha": "b5cdf9ebe71c4892163a0f97e7636197d9c7982f", "save_path": "github-repos/coq/let-def-ml-test", "path": "github-repos/coq/let-def-ml-test/ml-test-b5cdf9ebe71c4892163a0f97e7636197d9c7982f/coq/test_imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7285334484190894}}
{"text": "\n(*partie 2.2*)\n(* ATTENTION !!!!!\nIl faut lancer coqide avec la cmd = coqide -impredicative-set*) \n(*L'identité polymorphe*)\n\n(*2.2.1*)\nDefinition tid : Set := forall T : Set, T -> T.\nDefinition id : tid := fun T:Set => fun x : T => x.\n\n(*TESTS OF IDENTITY*)\n(* 5 est nat? *)\nCompute id nat 5.\n(* true est boolean? *)\nCompute id bool true.\n(* BAD TEST | UNCOMMENT *)\n(*Compute id bool 0.*)\n\nDefinition nbtrue1 := \nfun b => match b with true => 1 | \nfalse => 0 end.\n\n(*Verif : la fonction rend bien un nat*)\nCompute id nat (nbtrue1 false).\nCompute id tid id.\n\n(*2.2.2*)\n(*booleans*)\nDefinition pbool : Set := forall T : Set, T -> T -> T.\n(*vrai*)\nDefinition ptr : pbool := fun T:Set => fun x:T => fun y:T => x .\n(*faux*)\nDefinition pfa : pbool := fun T:Set => fun (x:T) (y:T) => y.\nPrint ptr.\nPrint pfa.\n\n(*first negation*)\nDefinition cneg1 : pbool -> pbool := fun b => fun T:Set => fun x => fun y => b T y x.\n\nCompute cneg1 ptr.\nCompute cneg1 pfa.\n(*second negation*)\nDefinition cneg2 : pbool -> pbool:= fun b => b pbool pfa ptr.\n\nCompute cneg2 ptr.\nCompute cneg2 pfa.\n(*conj*)\nDefinition conjonc : pbool -> pbool -> pbool := fun a b => a pbool b a.\nCompute conjonc ptr pfa.\nCompute conjonc pfa ptr.\nCompute conjonc ptr ptr.\n\n(*disonj*)\nDefinition disjonc : pbool -> pbool -> pbool := fun a b => a pbool a b.\n\nCompute disjonc ptr pfa.\nCompute disjonc pfa ptr.\nCompute disjonc pfa pfa.\n\n(*3 si vrai. 5, sinon.*)\nDefinition foo35 : pbool -> nat := fun b => b nat 3 5.\nCompute foo35 ptr.\nCompute foo35 pfa.\n\n(*BONUS : lui-meme*)\nDefinition bluimeme := fun (b:pbool) => b pbool b. \nCompute bluimeme ptr pfa.\nCompute bluimeme pfa ptr.\nCompute bluimeme pfa pfa.\nCompute bluimeme ptr ptr.\n(*C'est la fonction OR .*)\n\n(*2.2.3.1*)\n\n(*A -> B -> T) ->T*)\nDefinition pprod_nb : Set := forall T: Set, (nat -> bool -> T) -> T.\nDefinition pcpl_nb : nat -> bool -> pprod_nb := fun a b => fun T => fun k => k a b.\n\n(* (5,true) *)\nCompute pcpl_nb 5 true.\n(*2.2.3.2*)\nDefinition pprod_bn : Set := forall T: Set, (bool -> nat -> T) -> T.\nDefinition pcpl_bn : bool -> nat -> pprod_bn := fun a b => fun T => fun k => k a b.\n(* (true,5) *)\nCompute pcpl_bn true 5.\n\n(*2.2.3.3*)\nDefinition convertProd : pprod_nb -> pprod_bn := fun c => c pprod_bn (fun n b => pcpl_bn b n).\n(*TEST : (5,true) => (true, 5)*)\nDefinition c1 := pcpl_nb 5 true.\nDefinition res := convertProd c1.\nCompute c1.\nCompute res.\n(*produit universel*)\nDefinition pprod : Set -> Set -> Set := fun A B => forall T:Set, (A -> B -> T) -> T.\nDefinition pcpl : forall A B:Set, A -> B -> pprod A B := fun A B:Set => fun (a:A) (b:B) => fun T:Set => fun k:(A -> B -> T) => k a b.\n(* couple = (99,true) *)\nCompute pcpl nat bool 99 true.\n(* couple = (1,0) *)\nCompute pcpl nat nat 1 0.\n(* couple = (1,(3, si vrai, 5 sinon) *)\nCompute pcpl pbool nat ptr (foo35 ptr).\n\n\n(*Choix (Sommes de Types) *)\n(*On a juste implementé ça : A+B = ∀T, (A→T)→(B→T)→T.)*)\nDefinition psom (A B : Set) : Set := forall T:Set, (A -> T) -> (B -> T) -> T.\nDefinition inj1 (A B : Set) : A -> psom A B := fun a => fun T:Set => fun k1 : (A ->  T) => fun k2 : (B ->  T) => k1 a.\n(*Inspirée par inj1*)\nDefinition inj2 (A B : Set) : B -> psom A B := fun b => fun T:Set => fun k1 : (A ->  T) => fun k2 : (B ->  T) => k2 b.\n\n(*2.2.4  Entiers de Church avec typage polymorphe *)\n\n(*Base form*)\n(*On a re-utilisé les definitions de la partie1.v*)\nDefinition pnat := forall (T:Set), (T->T) -> (T->T).\nDefinition p0 : pnat := fun (T:Set) => fun (f:T->T) => fun (x:T) => x.\nDefinition pS : pnat -> pnat :=  fun (n: pnat) => fun (T : Set) f  x => f (n  T f x).\n(*Definition de 1 2 et 3 on utilisant pS*)\nDefinition p1 := pS p0.\nDefinition p2 := pS p1.\nDefinition p3 := pS p2.\n(*Definition cadd := \\n m·\\f x·n f(m f x).*)\nDefinition padd : pnat -> pnat -> pnat := fun n m => fun f x => n f (m f x ).\n(* 2 + 2 = 4 *)\nCompute padd p2 p2.\n(*Definition cmult := \\n m · \\f· n(m f).*)\nDefinition pmult : pnat -> pnat -> pnat := fun m n =>  fun T:Set => (fun f => n T (m T f)).\n(* 2 X 3 = 6 *)\nCompute pmult p2 p3.\n(*Definition ceq0 := \\n·\\x y· n(\\z·x) y.*)\nDefinition peq0 : pnat -> pbool := fun n => fun T:Set => fun (x:T) (y:T) => (n T (fun z => y) x).\n(* 3 X 0 == 0 ? *)\nCompute peq0 (pmult p3 p0).\n(* 3 == 0 ? *)\nCompute peq0  p3.\n\n(* special pplus *)\nDefinition pplus : pnat -> pnat -> pnat := fun n : pnat => fun m : pnat =>  n pnat pS m.\n(* Test : 1 + 3 *)\nCompute pplus p1 p3.\n\n(*prédécesseur : We did not implement it... No time :-( *)\n\n(* 2.2.5  Listes (bonus) *)\n(*On a fait que la premiere question.*)\n(*listen = ∀T, T→(pnat→T→T)→T.*)\nDefinition listen : Set := forall T: Set, T -> (pnat -> T -> T) -> T.\n(*liste A = ∀T, T→(A→T→T)→T.*)\n(*L'espace entre liste et A EST MANDATORY.*) \nDefinition liste A : Set := forall T: Set, T -> (A -> T -> T) -> T.\n(*pnil A :liste A = ΛT.λxTcA→T→T.x*)\nDefinition pnil A : liste A := fun T:Set => fun x : T => fun c : (A -> T -> T) =>x.\n(*pcons A :  A→ liste A →liste A = λaAq liste A.ΛT.λxTcA→T→T.c a(qTx c).*)\nDefinition pcons A : A -> liste A -> liste A :=  fun (a : A) (q : liste A) => fun T: Set => fun (x:T) (c : A -> T -> T)=> c a (q T x c).\n\n\n(*2.2.6  Super bonus : arbres binaires et tri par arbre binaire de recherche*)\n(*Reference*)\nDefinition arbin (A : Set) := forall T: Set, T -> (T -> A -> T -> T) -> T.\n(*arbre Vide.*)\nDefinition pV (A:Set) := fun T:Set=> fun x : T => fun c : T -> A -> T -> T=> x.\n(*le nœud comprenant un sous-arbre gauche, un habitant de A et un sous-arbre droit*)\nDefinition pN (A : Set):= fun (g : arbin A) (a : A) (d : arbin A) => fun T : Set  => fun(x : T) (c : T -> A -> T -> T) => c (g T x c) a (d T x c ). \n", "meta": {"author": "alaabenfatma", "repo": "LC_BinaryTree", "sha": "5a37ecf432c2f7475c62fba84fe6b898ec578220", "save_path": "github-repos/coq/alaabenfatma-LC_BinaryTree", "path": "github-repos/coq/alaabenfatma-LC_BinaryTree/LC_BinaryTree-5a37ecf432c2f7475c62fba84fe6b898ec578220/partie2_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7284521498272757}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Properties of subtraction between natural numbers.\n\n This file is mostly OBSOLETE now, see module [PeanoNat.Nat] instead.\n\n [minus] is now an alias for [Nat.sub], which is defined in [Init/Nat.v] as:\n<<\nFixpoint sub (n m:nat) : nat :=\n  match n, m with\n  | S k, S l => k - l\n  | _, _ => n\n  end\nwhere \"n - m\" := (sub n m) : nat_scope.\n>>\n*)\n\nRequire Import PeanoNat Lt Le.\n\nLocal Open Scope nat_scope.\n\n(** * 0 is right neutral *)\n\nLemma minus_n_O n : n = n - 0.\nProof.\n symmetry. apply Nat.sub_0_r.\nQed.\n\n(** * Permutation with successor *)\n\nLemma minus_Sn_m n m : m <= n -> S (n - m) = S n - m.\nProof.\n intros. symmetry. now apply Nat.sub_succ_l.\nQed.\n\nTheorem pred_of_minus n : pred n = n - 1.\nProof.\n symmetry. apply Nat.sub_1_r.\nQed.\n\n(** * Diagonal *)\n\nNotation minus_diag := Nat.sub_diag (only parsing). (* n - n = 0 *)\n\nLemma minus_diag_reverse n : 0 = n - n.\nProof.\n symmetry. apply Nat.sub_diag.\nQed.\n\nNotation minus_n_n := minus_diag_reverse.\n\n(** * Simplification *)\n\nLemma minus_plus_simpl_l_reverse n m p : n - m = p + n - (p + m).\nProof.\n now rewrite Nat.sub_add_distr, Nat.add_comm, Nat.add_sub.\nQed.\n\n(** * Relation with plus *)\n\nLemma plus_minus n m p : n = m + p -> p = n - m.\nProof.\n symmetry. now apply Nat.add_sub_eq_l.\nQed.\n\nLemma minus_plus n m : n + m - n = m.\nProof.\n rewrite Nat.add_comm. apply Nat.add_sub.\nQed.\n\nLemma le_plus_minus_r n m : n <= m -> n + (m - n) = m.\nProof.\n rewrite Nat.add_comm. apply Nat.sub_add.\nQed.\n\nLemma le_plus_minus n m : n <= m -> m = n + (m - n).\nProof.\n intros. symmetry. rewrite Nat.add_comm. now apply Nat.sub_add.\nQed.\n\n(** * Relation with order *)\n\nNotation minus_le_compat_r :=\n  Nat.sub_le_mono_r (only parsing). (* n <= m -> n - p <= m - p. *)\n\nNotation minus_le_compat_l :=\n  Nat.sub_le_mono_l (only parsing). (* n <= m -> p - m <= p - n. *)\n\nNotation le_minus := Nat.le_sub_l (only parsing). (* n - m <= n *)\nNotation lt_minus := Nat.sub_lt (only parsing). (* m <= n -> 0 < m -> n-m < n *)\n\nLemma lt_O_minus_lt n m : 0 < n - m -> m < n.\nProof.\n apply Nat.lt_add_lt_sub_r.\nQed.\n\nTheorem not_le_minus_0 n m : ~ m <= n -> n - m = 0.\nProof.\n intros. now apply Nat.sub_0_le, Nat.lt_le_incl, Nat.lt_nge.\nQed.\n\n(** * Hints *)\n\nHint Resolve minus_n_O: arith.\nHint Resolve minus_Sn_m: arith.\nHint Resolve minus_diag_reverse: arith.\nHint Resolve minus_plus_simpl_l_reverse: arith.\nHint Immediate plus_minus: arith.\nHint Resolve minus_plus: arith.\nHint Resolve le_plus_minus: arith.\nHint Resolve le_plus_minus_r: arith.\nHint Resolve lt_minus: arith.\nHint Immediate lt_O_minus_lt: arith.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Arith/Minus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.728390058304993}}
{"text": "Require Import Setoid.\nRequire Import SetoidClass.\nOpen Scope type_scope.\n\nInductive andT (A B:Type) : Prop :=\n  conjT : A -> B -> andT A B.\n\nDefinition equivT (A B:Type) : Prop := andT (A ->B) (B-> A).\n\n\n\nLemma equivT_refl : forall A, equivT A A.\nProof.\n  intros A.\n  split;tauto.\nQed.\n\nLemma equivT_sym : forall A B, equivT A B -> equivT B A.\nProof.\n  intros A B X.\n  destruct X;split;tauto.\nQed.\n\nLemma equivT_trans : forall A B C, equivT A B -> equivT B C -> equivT A C.\nProof.\n  intros A B C [H1 H2] [H3 H4].\n  split;eauto.\nQed.\n\nAdd  Relation Type equivT\n  reflexivity proved by equivT_refl\n  symmetry proved by equivT_sym\n  transitivity proved by equivT_trans \nas toto.\n\n", "meta": {"author": "Matafou", "repo": "ill_narratives", "sha": "02eee90891ebedf78a1a86e58ad084358d2b028f", "save_path": "github-repos/coq/Matafou-ill_narratives", "path": "github-repos/coq/Matafou-ill_narratives/ill_narratives-02eee90891ebedf78a1a86e58ad084358d2b028f/basic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7282944815935722}}
{"text": "Require Export Category.\nRequire Export Functor.\n\nGeneralizable All Variables.\nOpen Scope signature.\n\nSection natrual_transformation.\nCheck @Functor.\nContext (C D : Type)\n        {aC:Arrows C} {aD:Arrows D}\n        {catC:Category C} {catD:Category D}\n       `{@Functor C aC catC D aD catD F Fmor}\n       `{@Functor C aC catC D aD catD G Gmor}.\n     \nNotation \" a ~{ X }{ Y }~> b \" := (@Hom X Y a b) (at level 40).\n\nClass NatTrans \n  (trans : forall x : C, (F x) ~> (G x))\n  :=\n  { nt_trans := trans\n  ; nt_natural : forall (x y : C) (f : x ~> y),\n    (nt_trans y) ∘ (Fmor x y f) == (Gmor x y f) ∘ (nt_trans x)\n  }.\n\nNotation \"η_{ x }\" := (nt_trans x) (at level 40).\nEnd natrual_transformation.\n\nSection id_nat_trans.\nContext `{aC:Arrows C} `{aD:Arrows D}\n        {catC:Category C} {catD:Category D}\n        `(F : C->D) `(F_f : @Functor C aC catC D aD catD F Fmor).\n\nDefinition idN (x:C) := @cat_id D aD catD (F x).\nGlobal Program Instance : \n  @NatTrans C D aC aD catD F Fmor F Fmor idN.\nNext Obligation.\n  unfold idN. \n  rewrite id_r. symmetry. apply id_l.\n  Qed.\n\nEnd id_nat_trans.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/category/NatTrans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7282944815935722}}
{"text": "(******************************************************************************)\n(* Chapter 1.6.1: Product Categories                                          *)\n(******************************************************************************)\n\n(*\n(0)\n同じディレクトリにある Categories.v と Functor.v を使う。\n\n(1) ベースライン\nhttp://www.megacz.com/berkeley/coq-categories/\nこれをもとに改変。Instance ... Proper を使うようにした。\n *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Notations.                   (* coq standard libs. *)\nRequire Import Categories.                  (* same dir. *)\nRequire Import Functors.                    (* same dir. *)\nRequire Import Isomorphisms.                (* same dir. *)\n\n(* 積圏 *)\nSection ProductCategories.\n\n  Locate \"_ ~~{ _ }~~> _\".                  (* Categories.v *)\n  \n(*\n  Context `(C1 : Category Obj1 Hom1).\n  Context `(C2 : Category Obj2 Hom2).\n*)  \n  Context `(C1 : Category).                 (* Obj Hom *)\n  Context `(C2 : Category).                 (* Obj0 Hom0 *)\n  \n  (* trying to use the standard \"prod\" here causes a universe\n  inconsistency once we get to coqBinoidal; moreover, using a\n  general fully-polymorphic pair type seems to trigger some serious\n  memory leaks in Coq *)\n  \n  Inductive  prod_obj : Type :=\n  | pair_obj : C1 -> C2 -> prod_obj.\n  \n  Definition fst_obj (x : prod_obj) : C1 :=\n    match x with\n      | pair_obj a _ => a\n    end.\n  \n  Definition snd_obj (x : prod_obj) : C2 :=\n    match x with\n      | pair_obj _ b => b\n    end.\n\n  Inductive prod_mor (a b : prod_obj) : Type :=\n    pair_mor :\n      ((fst_obj a) ~~{C1}~~> (fst_obj b)) -> (* f1 *)\n      ((snd_obj a) ~~{C2}~~> (snd_obj b)) -> (* f2 *)\n      prod_mor a b.                          (* f *)\n  Check prod_mor : prod_obj → prod_obj → Type.\n  \n  Definition prod_eqv (a b : prod_obj)\n             (f : prod_mor a b) (g : prod_mor a b) : Prop :=\n    match f with\n      | pair_mor f1 f2 =>\n        match g with\n          | pair_mor g1 g2 =>\n            f1 === g1 /\\ f2 === g2\n        end\n    end.\n  \n  Program Instance prod_Equiv (a b : prod_obj) : Equivalence (@prod_eqv a b).\n  Obligation 1.                             (* Reflexive *)\n  Proof.\n    rewrite /prod_eqv /Reflexive /=.\n    case=> f1 f2.\n    split.\n    - reflexivity.\n    - reflexivity.\n  Qed.\n  Obligation 2.                             (* Symmetric *)\n  Proof.\n    rewrite /prod_eqv /Symmetric /=.\n    case=> f1 f2.\n    case=> g1 g2.\n    case=> H1 H2.\n    split.\n    - rewrite H1.\n      reflexivity.\n    - rewrite H2.\n      reflexivity.\n  Qed.\n  Obligation 3.                             (* Transitive *)\n  Proof.\n    rewrite /prod_eqv /Transitive /=.\n    case=> f1 f2.\n    case=> g1 g2.\n    case=> h1 h2.\n    case=> Hfg1 Hfg2.\n    case=> Hgh1 Hgh2.\n    split.\n    - rewrite Hfg1 Hgh1.\n      reflexivity.\n    - rewrite Hfg2 Hgh2.\n      reflexivity.\n  Qed.\n  \n  (* 射はSetoidでないといけない。 *)\n  Instance PC_mor (a b : prod_obj) : Setoid :=\n    {\n      carrier := prod_mor a b;\n      eqv := @prod_eqv a b\n    }.\n  Check PC_mor : prod_obj → prod_obj → Setoid.\n  Print PC_mor.\n  \n  Definition fst_mor {a b : prod_obj} (f : prod_mor a b) :=\n    match f with\n      | pair_mor a _ => a\n    end.\n  \n  Definition snd_mor {a b : prod_obj} (f : prod_mor a b) :=\n    match f with\n      | pair_mor _ b => b\n    end.\n  \n  Check @Category.\n  Check prod_obj : Type.\n  Check prod_mor : prod_obj → prod_obj → Type.\n  Check PC_mor   : prod_obj → prod_obj → Setoid.\n  Check @Category prod_obj PC_mor.\n  \n  Program Instance ProductCategory : @Category prod_obj PC_mor.\n  Obligation 1.                             (* id *)\n  Proof.\n    apply pair_mor.\n    - apply id.\n    - apply id.\n  Defined.\n  Obligation 2.                             (* comp *)\n  Proof.\n    apply pair_mor.\n    Check (fun (f1 : fst_obj a ~~{ C1 }~~> fst_obj b)\n               (g1 : fst_obj b ~~{ C1 }~~> fst_obj c) => (g1 \\\\o f1)).\n    - apply (fun (f1 : fst_obj a ~~{ C1 }~~> fst_obj b)\n                 (g1 : fst_obj b ~~{ C1 }~~> fst_obj c) => (g1 \\\\o f1));\n        by [apply X | apply X0].\n    - apply (fun (f2 : snd_obj a ~~{ C2 }~~> snd_obj b)\n                 (g2 : snd_obj b ~~{ C2 }~~> snd_obj c) => (g2 \\\\o f2));\n        by [apply X | apply X0].\n  Defined.\n  Obligation 3.                             (* comp_respects *)\n  Proof.\n    rewrite /ProductCategory_obligation_2.\n    move=> g1 g2 Hg.\n    move=> f1 f2 Hf.\n    move: Hg Hf.\n    rewrite /prod_eqv.\n    case g1 => gf1 gs1.\n    case f1 => ff1 fs1.\n    case g2 => gf2 gs2.\n    case f2 => ff2 fs2.\n    case=> Hgf Hgs.\n    case=> Hff Hfs.\n    split.\n    - rewrite Hgf Hff.\n      reflexivity.\n    - rewrite Hgs Hfs.\n      reflexivity.\n  Defined.\n  Obligation 4.                             (* id \\\\o f === f  *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - rewrite left_identity.\n      reflexivity.\n    - rewrite left_identity.\n      reflexivity.\n  Defined.\n  Obligation 5.                             (* f \\\\o id === f  *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - rewrite right_identity.\n      reflexivity.\n    - rewrite right_identity.\n      reflexivity.\n  Defined.\n  Obligation 6.                             (* f \\\\o g \\\\o h === f \\\\o (g \\\\o h) *)\n  Proof.\n    case: f => ff fs.\n    split.\n    - case: g => gf gs.\n      case: h => hf hs.\n      rewrite associativity.\n      reflexivity.\n    - case: g => gf gs.\n      case: h => hf hs.\n      rewrite associativity.\n      reflexivity.\n  Defined.\nEnd ProductCategories.\n\nNotation \"C ×× D\" := (ProductCategory C D).\n\n(*\nImplicit Arguments pair_obj [ Ob1 Hom1 Ob2 Hom2 C1 C2 ].\nImplicit Arguments pair_mor [ Ob1 Hom1 Ob2 Hom2 C1 C2 ].\n *)\n\nCheck @pair_obj : ∀Obj Hom C1 Obj Hom C2 a b, prod_obj C1 C2.\nCheck @pair_mor : ∀Obj Hom C1 Obj Hom C2 a b f g, prod_mor a b.\nCheck @fst_obj.\nCheck @fst_mor.\nArguments pair_obj {Obj1 Hom1 C1 Obj2 Hom2 C2} a b : rename.\nArguments pair_mor {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} f g : rename.\nArguments fst_obj  {Obj1 Hom1 C1 Obj2 Hom2 C2} D : rename.\nArguments snd_obj  {Obj1 Hom1 C1 Obj2 Hom2 C2} D : rename.\nArguments fst_mor  {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} i : rename.\nArguments snd_mor  {Obj1 Hom1 C1 Obj2 Hom2 C2 a b} i : rename.\nCheck pair_obj : _ -> _ -> prod_obj _ _.    (* 圏の指定は要らない。 *)\nCheck pair_mor : _ ~> _ ->  _ ~> _ -> prod_mor _ _.\nCheck fst_obj  : prod_obj _ _ -> _.\nCheck snd_obj  : prod_obj _ _ -> _.\nCheck fst_mor  : prod_mor _ _ -> _ ~> _.\n\nCheck @PC_mor : ∀Obj Hom C1 Obj0 Hom0 C2 _ _, Setoid.\nArguments PC_mor {Obj1 Hom1 C1 Obj2 Hom2 C2} f g : rename.\nCheck PC_mor : prod_obj _ _ → prod_obj _ _ → Setoid.\n\nCheck @Functor : ∀Obj Hom C1 Obj0 Hom0 C2 _, Type.\nArguments Functor {Obj Hom} C1 {Obj0 Hom0} C2 i : rename.\n\nSection ProductCategoryFunctors.\n\n  Context `{C : Category}.                  (* Obj Hom C *)\n  Context `{D:Category}.                    (* Obj0 Hom0 D *)\n\n  Check @Functor.\n  Check @Functor _ _ (C ×× D) Obj Hom C (fun c => fst_obj c).\n  Check Functor (C ×× D) C (fun c => fst_obj c).\n\n  Check @prod_obj Obj Hom C Obj0 Hom0 D.\n  Check prod_obj C D.\n\n  Check @PC_mor Obj Hom C Obj0 Hom0 D.\n  Check PC_mor.\n  \n  Check @fst_obj Obj Hom C Obj0 Hom0 D : prod_obj C D → C.\n  Check fst_obj : prod_obj C D → C.\n  \n  Check fun (c : prod_obj C D) => @fst_obj Obj Hom C Obj0 Hom0 D c.\n  Check fun (c : prod_obj C D) => fst_obj c.\n  \n  Check @Functor (prod_obj C D) (@PC_mor Obj Hom C Obj0 Hom0 D) (C ×× D)\n        Obj Hom C (fun c => fst_obj _ c).\n  Check Functor (C ×× D) C (fun (c : prod_obj C D) => @fst_obj Obj Hom C Obj0 Hom0 D c).\n  \n  (* 積圏からもとの圏をとりだす関手 *)\n  Program Instance func_pi1 : Functor (C ×× D) C\n                                      (fun (c : prod_obj C D) => fst_obj c).\n  Obligation 1.\n  (* fst_obj a ~~{ C }~~> fst_obj b *)\n  Proof.\n    by apply fst_mor.\n  Defined.\n  Obligation 2.\n  (* fst_mor f === fst_mor f' *)\n  Proof.\n    rewrite /func_pi1_obligation_1.\n    case: f H => ff fs.\n    case: f' => f'f f's H /=.\n    by case: H.\n  Defined.\n  Obligation 3.\n  (* id === id *)\n  Proof.\n    reflexivity.\n  Defined.\n  Obligation 4.\n  Proof.\n    rewrite /func_pi1_obligation_1.\n    case: f => ff fs.\n    case: g => gf gs.\n    reflexivity.\n  Defined.\n  \n  Program Instance func_pi2 : Functor (C ×× D) D\n                                      (fun (c : prod_obj C D) => snd_obj c).\n  Obligation 1.\n  (* snd_obj a ~~{ D }~~> snd_obj b *)\n  Proof.\n    by apply snd_mor.\n  Defined.\n  Obligation 2.\n  (* snd_mor f === snd_mor f' *)\n  Proof.\n    rewrite /func_pi2_obligation_1.\n    case: f H => ff fs.\n    case: f' => f'f f's H /=.\n    by case: H.\n  Defined.\n  Obligation 3.\n  (* id === id *)\n  Proof.\n    reflexivity.\n  Defined.\n  Obligation 4.\n  Proof.\n    rewrite /func_pi2_obligation_1.\n    case: f => ff fs.\n    case: g => gf gs.\n    reflexivity.\n  Defined.  \n  \n  (* 積圏の左が恒等射である場合 *)\n  Definition llecnac_fmor (I : C) (a b : D) (g : a ~~{D}~~> b) :\n    (pair_obj I a) ~~{C××D}~~> (pair_obj I b).\n  Proof.\n    apply: pair_mor => /=.\n    - by apply: id.\n    - by apply: g.\n  Defined.\n  \n  (* 圏から左が恒等射である積圏への関手 *)\n  Program Instance func_llecnac (I : C) : Functor D (C ×× D) (pair_obj I).\n  Obligation 1.\n  (* prod_mor (pair_obj I a) (pair_obj I b) *)\n   Proof.\n    apply: pair_mor;\n      by apply llecnac_fmor.\n  Defined.\n  Obligation 2.\n  Proof.\n    split; [reflexivity | done].\n  Defined.\n  Obligation 3.\n    split; [reflexivity | reflexivity].\n  Defined.\n  Obligation 4.\n  Proof.\n    split.\n    - rewrite left_identity.\n      reflexivity.\n    - reflexivity.\n  Defined.\n  \n  (* 積圏の右が恒等射である場合 *)\n  Definition rlecnac_fmor (I : D) (a b : C) (f : a ~~{C}~~> b) :\n    (pair_obj a I) ~~{C××D}~~> (pair_obj b I).\n  Proof.\n    apply: pair_mor => /=.\n    - by apply: f.\n    - by apply: id.\n  Defined.\n  \n  (* 圏から右が恒等射である積圏への関手 *)\n  Program Instance func_rlecnac (I : D) : Functor C (C ×× D) (fun c => (pair_obj c I)).\n  Obligation 1.\n  (* prod_mor (pair_obj a I) (pair_obj b I) *)\n  Proof.\n    apply: pair_mor;\n      by apply rlecnac_fmor.\n  Defined.\n  Obligation 2.\n  Proof.\n    split; [done | reflexivity].\n  Defined.\n  Obligation 3.\n    split; [reflexivity | reflexivity].\n  Defined.\n  Obligation 4.\n  Proof.\n    split.\n    - reflexivity.\n    - rewrite right_identity.\n      reflexivity.\n  Defined.\n  \n  Context `{E : Category}.\n  \n  (* 積圏の結合律 *)\n  Definition cossa : ((C ×× D) ×× E) -> (C ×× (D ×× E)).\n  Proof.\n    move=> [[HC HD] HE].\n    by [].\n  Defined.\n  \n  (* 次の定理のための補題 *)\n  Definition cossa_fmor (a : ((C ×× D) ×× E)) (b : ((C ×× D) ×× E))\n             (f : a ~~{(C ×× D) ×× E}~~> b) :\n    (cossa a) ~~{C ×× (D ×× E)}~~> (cossa b).\n  Proof.\n    case: a f => HCxD HE.\n    case: b => GCxD GE.\n    case: HCxD.\n    case: GCxD.\n    move=> HC HD GC GD.\n    case=> fCD fE.\n    case: fCD => fC fD.\n    done.\n  Defined.\n\n  (* cossa は、関手である。 *)\n  Program Instance func_cossa : Functor ((C ×× D) ×× E) (C ×× (D ×× E)) cossa :=\n    {|\n      fmor := fun a b f => cossa_fmor f\n    |}.\n  Obligation 1.\n  Proof.\n    move: a b f f' H.\n    (* ∀a b f f' _, cossa_fmor f === cossa_fmor f' *)\n    move=> [[a11 a12] a2].                  (* case a *)\n    move=> [[b11 b12] b2].                  (* case b *)\n    move=> [[f11 f12] f2].                  (* case f *)\n    move=> [[g11 g12] g2].                  (* case f' *)\n    case; case.\n    split; [exact | split; exact].\n  Defined.\n  Obligation 2.\n  Proof.\n    (* ∀ a : (C ×× D) ×× E, cossa_fmor id === id *)\n    case: a => HCxD HE.\n    case: HCxD => HC HD.\n    split; [reflexivity | split; reflexivity].\n  Defined.\n  Obligation 3.\n  Proof.\n    move: a b c f g.\n    (* ∀a b c f g, cossa_fmor g \\\\o cossa_fmor f === cossa_fmor (g \\\\o f) *)\n    move=> [[a11 a12] a2].                  (* case a *)\n    move=> [[b11 b12] b2].                  (* case b *)\n    move=> [[c11 c12] c2].                  (* case c *)\n    move=> [[f11 f12] f2].                  (* case f *)\n    move=> [[g11 g12] g2].                  (* case g *)\n    rewrite /=; split; [reflexivity | split; reflexivity].\n  Defined.\n  \n  (* 同じ圏の積 C^2 *)\n  Program Instance func_diagonal : Functor C (C ×× C) (fun c => (pair_obj c c)).\n  Obligation 1.\n  (* prod_mor (pair_obj a a) (pair_obj b b) *)\n  Proof.\n    by apply: pair_mor.\n  Defined.\n  Obligation 3.\n  (* id === id ∧ id === id *)\n  Proof.\n    split; reflexivity.\n  Defined.\n  Obligation 4.\n  (* g \\\\o f === g \\\\o f ∧ g \\\\o f === g \\\\o f *)\n  Proof.\n    split; reflexivity.\n  Defined.\nEnd ProductCategoryFunctors.\n\nSection func_prod.\n  \n  Context `{C1 : Category} `{C2 : Category} `{C3 : Category} `{C4 : Category}.\n  Variables (Fobj1 : C1 -> C2) (Fobj2 : C3 -> C4).\n  Variables (F1 : Functor C1 C2 Fobj1) (F2 : Functor C3 C4 Fobj2).\n\n  Definition functor_product_fobj (a : prod_obj C1 C3) :=\n    pair_obj (Fobj1 (fst_obj a)) (Fobj2 (snd_obj a)).  \n  Check functor_product_fobj.\n  Check functor_product_fobj : prod_obj C1 C3 → prod_obj C2 C4.\n\n  Definition functor_product_fmor (a b : (C1 ×× C3)) (f : a ~~{C1 ×× C3}~~> b) :\n    (functor_product_fobj a) ~~{C2 ×× C4}~~> (functor_product_fobj b).\n  Proof.\n    case: a f => HC1 HC3 H.\n    apply: pair_mor => /=.\n    - apply (fmor F1); by case H.\n    - apply (fmor F2); by case H.\n  Defined.\n  \n  Hint Unfold fst_obj.\n\n  Program Instance func_prod : Functor (C1 ×× C3) (C2 ×× C4) functor_product_fobj :=\n    {|\n      fmor := fun a b (f:a~~{C1 ×× C3}~~>b) => functor_product_fmor f\n    |}.\n  Obligation 1.\n  Proof.\n    move: a b f f' H.\n    (* ∀a b f f' _, functor_product_fmor f === functor_product_fmor f' *)\n    move=> [a1 a2].                         (* case a *)\n    move=> [b1 b2].                         (* case b *)\n    move=> [f1 f2].                         (* case f *)\n    move=> [g1 g2].                         (* case g *)\n    case=> H1 H2.                           (* case H *)\n    split; [rewrite H1 | rewrite H2]; reflexivity.\n  Defined.\n  Obligation 2.\n  Proof.\n  (* ∀ a : C1 ×× C3, functor_product_fmor id === id *)\n    case: a => [a1 a2] /=.\n      by split; apply fmor_preserves_id.\n  Defined.\n  Obligation 3.\n  Proof.\n    move: a b c f g.\n  (* ∀a b c f g,\n   functor_product_fmor g \\\\o functor_product_fmor f ===\n   functor_product_fmor (g \\\\o *)\n    move=> [a1 a2].                         (* case a *)\n    move=> [b1 b2].                         (* case b *)\n    move=> [c1 c2].                         (* case c *)\n    case=> f1 f3.                           (* case f *)\n    case=> g1 g3.                           (* csae g *)\n    by move=> /=; split; apply fmor_preserves_comp.\n  Defined.\nEnd func_prod.\n\nNotation \"f **** g\" := (func_prod f g).\n\nProgram Instance iso_prod `{C : Category} `{D : Category} {a b : C} {c d : D}\n         (ic : a ≅ b) (id : @Isomorphic _ _ D c d) :\n  @Isomorphic _ _ (C ×× D) (pair_obj a c) (pair_obj b d).\nObligation 1.                               (* prod_mor (pair_obj a c) (pair_obj b d) *)\nProof.\n  apply: pair_mor => /=.\n  - by case: ic.\n  - by case: id.\nDefined.\nObligation 2.                               (* prod_mor (pair_obj b d) (pair_obj a c) *)\nProof.\n  apply: pair_mor => /=.\n  - by case: ic.\n  - by case: id.\nDefined.\nObligation 3.\nProof.\n   by split; apply iso_comp1.\nDefined.\nObligation 4.\nProof.\n   by split; apply iso_comp2.\nDefined.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/monad/ProductCategories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.728294477502846}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  plus (Succ lf2) (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj235_coqofml_YsdUqn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7282663599078946}}
{"text": "Require Import List.\n\nRequire Import Bool.\n\nRequire Import Lia.\n\nVariable T : Type.\n\nHypothesis T_eq_dec : forall (x y :T), {x=y} + {~x=y}.\n\n\n(** Definition **)\n\nDefinition multiset := list (T*nat).\n\nDefinition empty:multiset := nil.\n\nFixpoint member (x : T) (ms : multiset) : bool :=\n  match ms with\n  |nil => false\n  |(a,b)::r => match T_eq_dec a x with\n                    |left _ => true\n                    |right _ => (member x r)\n               end\n  end.\n\nDefinition singleton (x : T) := (x,1)::empty .\n\nFixpoint add (x : T) (n : nat) (ms : multiset) : multiset :=\n match ms with \n  |nil => match n with \n                  |0 => nil\n                  |_ => (x,n)::nil\n          end\n  |(a,b)::r =>  match T_eq_dec a x with\n                    |left _ => (a,n+b)::r\n                    |right _ => (a,b)::(add x n r)\n               end\nend.\n\nFixpoint union (ms1 : multiset) (ms2 : multiset) : multiset :=\nmatch ms1 with\n  |nil => ms2\n  |(a,b)::r => union r (add a b ms2)\nend.\n\nFixpoint multiplicity (x : T) (ms : multiset) : nat := \nmatch ms with\n  |nil =>0\n  |(a,b)::r => match T_eq_dec a x with\n                    |left _ => b\n                    |right _ => multiplicity x r\n              end\nend.\n\nFixpoint removeOne (x : T) (ms : multiset) : multiset :=\nmatch ms with\n  |nil => nil\n  |(a,b)::r => match T_eq_dec a x with\n                     |right _ => (a,b)::(removeOne x r)\n                     |left _ => match b with \n                                              |0 | S(0) => r\n                                              | S(m) => (a,m)::r\n                                end\n              end\nend.\n\nFixpoint removeAll (x : T) (ms : multiset) : multiset :=\nmatch ms with\n  |nil => nil\n  |(a,b)::r => match T_eq_dec a x with\n                     |right _ => (a,b)::(removeAll x r)\n                     |left _ => removeAll x r\n              end\nend.\n\n(** Rq : Cette definition est redondante car elle laisse croire que l'on peut trouver plusieurs couples pour un même élément x, cependant cela facilite les preuves de correction **)\n\nInductive InMultiset : T -> multiset -> Prop :=\n  | TL : forall h x ms, InMultiset x ms -> InMultiset x (cons h ms)\n  | HD : forall x n ms, InMultiset x (cons (x,S(n)) ms).\n\nInductive wf : multiset -> Prop :=\n | Empt : wf empty\n | Cons : forall x n t,(wf t)/\\~(InMultiset x t) -> wf (cons (x,S(n)) t).\n\nGoal wf empty.\nProof.\napply Empt.\nQed.\n\nGoal forall x, wf (singleton x).\nProof.\nintro x. apply (Cons x 0 empty).\nsplit. apply Empt. intro H. inversion H.\nQed.\n\n\nLemma Add0 : forall x ms, (add x 0 ms)=ms.\nProof.\ninduction ms as [|hd tl]. \n  + simpl. reflexivity.\n  + simpl. destruct hd as [a n]. destruct (T_eq_dec a x).\n    ++ reflexivity.\n    ++ rewrite IHtl. reflexivity.\nQed.\n\nLemma AddDistinct : forall (a x : T) (n : nat) (ms : multiset), ~(InMultiset a ms) -> ~(a=x) -> ~(InMultiset a (add x (S n) ms)).\nProof.\nintros a x n ms. intros Happ Hdist. induction ms.\n  + simpl. intro Hneg. inversion Hneg. inversion H1. contradiction.\n  + intro Hneg. Admitted.\n\n\nGoal forall x n ms, wf ms -> wf (add x n ms).\ndestruct n.\n  +intros ms H. rewrite (Add0 x ms). exact H.\n  + induction ms as [ |hd tl].\n    ++ intro H. apply (Cons x n nil). split. exact H. intro Hneg. inversion Hneg.\n    ++ intro H. simpl. destruct hd as [a m]. destruct (T_eq_dec a x).\n        +++ apply (Cons a (n+m) tl). inversion H. destruct H1. split. exact H1. exact H4.\n        +++ destruct m. inversion H. apply (Cons a m (add x (S n) tl)). inversion H. destruct H1. split.\n            ++++ apply IHtl in H1. exact H1.\n            ++++ intro Hneg. destruct Hneg. Admitted.\n\n\n\n\n\n(** Question 3 **)\n\nGoal forall x, ~InMultiset x empty.\nProof.\nintro x. intro Hneg. inversion Hneg.\nQed.\n\nGoal forall x y, InMultiset y (singleton x) -> x=y.\nProof.\nintros x y. intro Hyp. inversion Hyp. inversion H1. reflexivity.\nQed.\n\nGoal forall x y, x=y -> InMultiset y (singleton x).\nProof.\nintros x y. intro Hyp. rewrite Hyp. apply (HD y 0 empty).\nQed.\n\nGoal forall x, multiplicity x (singleton x) = 1.\nProof.\nintro x. simpl. destruct (T_eq_dec x x). reflexivity. contradiction.\nQed.\n\n\nLemma WfSub : forall a ms, wf(a::ms)-> wf ms.\nProof.\nintros a ms. intro Hform. inversion Hform. destruct H0. exact H0.\nQed.\n\nGoal forall x s, wf s -> (member x s = true <-> InMultiset x s).\nintros x s. intro Hform. split.\n  + intro Hmem. induction s.\n    ++ inversion Hmem.\n    ++ pose proof (WfSub a s Hform) as Hform2. destruct a as [a1 n]. destruct (T_eq_dec a1 x). \n      +++ destruct n. inversion Hform. rewrite e. apply (HD x n s).\n      +++ apply IHs in Hform2. apply (TL (a1,n) x s Hform2). inversion Hmem. destruct (T_eq_dec a1 x). contradiction. reflexivity.\n  + intro Hyp. induction Hyp.\n    ++ pose proof (WfSub h ms Hform) as Hform2. apply IHHyp in Hform2. destruct h as [a n]. simpl. destruct (T_eq_dec a x). reflexivity. exact Hform2.\n    ++ simpl. destruct (T_eq_dec x x). reflexivity. contradiction.\nQed.\n\n\nGoal forall x n s, n>0 -> InMultiset x (add x n s).\nintros x n s Hstr. destruct n. lia. induction s.\n  + simpl. apply (HD x n empty).\n  + destruct a as [a1 m]. simpl. destruct (T_eq_dec a1 x).\n    ++ rewrite e. apply (HD x (n+m) s).\n    ++ apply (TL (a1,m) x (add x (S n) s)). exact IHs.\nQed.\n\nLemma CoqEstPerdu : forall (a : T) (k : nat) (h : T*nat) (ms tl : multiset), h::ms = (a,k)::tl -> tl=ms.\nProof.\nintros a k h ms tl. Admitted.\n\n\nGoal forall x y n s, x<>y ->(InMultiset y (add x n s) <-> InMultiset y s).\nProof.\nintros x y n s. intro Hdiff. split.\n  + intro Happ. induction s as [|hd tl].\n    ++ destruct n. \n      +++ inversion Happ.\n      +++ inversion Happ. inversion H1. admit. (** on a x<>y et x=y mais Coq ne voit pas la contradiction ... **)\n   ++ destruct hd as [a m]. destruct (T_eq_dec a x).\n      +++ rewrite e. apply (TL (x,m) y tl). rewrite -> e in Happ. inversion Happ. destruct (T_eq_dec x x). pose proof (CoqEstPerdu x (n+m) h ms tl H). rewrite <- H2 in H1. exact H1. contradiction. \n\n\n\n\n\ninversion Happ. destruct (T_eq_dec a x). apply (TL (a,m) y tl). pose proof (CoqEstPerdu a (n+m) h ms tl H). rewrite H2. exact H1.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Hazdard", "repo": "Coq_L3", "sha": "8d0625c0dedcc9e121a6ef153a0a97cc33cc7cb3", "save_path": "github-repos/coq/Hazdard-Coq_L3", "path": "github-repos/coq/Hazdard-Coq_L3/Coq_L3-8d0625c0dedcc9e121a6ef153a0a97cc33cc7cb3/TD3part2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7282548525538001}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Omega List Permutation.\n\nRequire Import utils ill_form ill_rules.\n\nSet Implicit Arguments.\n\nSection Relational_phase_semantics.\n\n  (** We define a sound relational phase sematics for ILL \n      based on stable closures \n\n      The algebraic developments below follow the sketch\n      in the book \"Lectures on Linear Logic\"\n\n      http://phil.gu.se/logic/books/Troelstra:Lectures_on_Linear_Logic.pdf\n\n    *)\n\n  Variable M : Type.\n\n  Implicit Types A B C : M -> Prop.\n\n  Variable cl : (M -> Prop) -> (M -> Prop).\n\n  Hypothesis cl_increase   : forall A, A ⊆ cl A.\n  Hypothesis cl_monotone   : forall A B, A ⊆ B -> cl A ⊆ cl B.\n  Hypothesis cl_idempotent : forall A, cl (cl A) ⊆ cl A.\n  \n  Proposition cl_prop A B : A ⊆ cl B <-> cl A ⊆ cl B.\n  Proof.\n    split; intros H x Hx.\n    apply cl_idempotent; revert Hx; apply cl_monotone; auto.\n    apply H, cl_increase; auto.\n  Qed.\n  \n  Definition cl_inc A B := proj1 (cl_prop A B).\n  Definition inc_cl A B := proj2 (cl_prop A B). \n  \n  Fact cl_eq1 A B : A ≃ B -> cl A ≃ cl B.\n  Proof. intros []; split; apply cl_monotone; auto. Qed.\n\n  Hint Resolve cl_inc cl_eq1.\n\n  Notation closed := (fun x : M -> Prop => cl x ⊆ x).\n  \n  Fact cl_closed A B : closed B -> A ⊆ B -> cl A ⊆ B.\n  Proof.\n    intros H1 H2.\n    apply inc1_trans with (2 := H1), cl_inc, \n          inc1_trans with (1 := H2), cl_increase.\n  Qed.\n\n  Fact cap_closed A B : closed A -> closed B -> closed (A ∩ B).\n  Proof.\n    intros HA HB x Hx; split; [ apply HA | apply HB ]; revert Hx; apply cl_monotone; tauto.\n  Qed.\n\n  Hint Resolve cap_closed.\n\n  (* this is a relational/non-deterministic monoid *)\n\n  Variable Compose : M -> M -> M -> Prop.\n\n  (* Composition lifted to predicates *)\n\n  Inductive Composes (A B : M -> Prop) : M -> Prop :=\n    In_composes : forall a b c, A a -> B b -> Compose a b c -> Composes A B c.\n\n  (* ⊆ ≃ ∩ ∪ ∘ *)\n\n  Infix \"∘\" := Composes (at level 50, no associativity).\n\n  Proposition composes_monotone A A' B B' : A ⊆ A' -> B ⊆ B' ->  A ∘ B ⊆ A' ∘ B'.\n  Proof. intros ? ? _ [ ? ? ? ? ? H ]; apply In_composes with (3 := H); auto. Qed.\n\n  Hint Resolve composes_monotone.\n\n  Variable e : M.\n\n  (* Stability is the important axiom in phase semantics *)\n\n  Definition cl_stability   := forall A B, cl A ∘ cl B ⊆ cl (A ∘ B).\n  Notation cl_stability_l  := (forall A B, cl A ∘    B ⊆ cl (A ∘ B)).\n  Definition cl_stability_r := forall A B,    A ∘ cl B ⊆ cl (A ∘ B).\n\n  Proposition cl_stable_imp_stable_l : cl_stability -> cl_stability_l.\n  Proof. \n    intros H ? ? x Hx.\n    apply H; revert x Hx. \n    apply composes_monotone; auto.\n  Qed.\n\n  Proposition cl_stable_imp_stable_r : cl_stability -> cl_stability_r.\n  Proof. \n    intros H ? ? x Hx.\n    apply H; revert x Hx. \n    apply composes_monotone; auto.\n  Qed.\n\n  Proposition cl_stable_lr_imp_stable : cl_stability_l -> cl_stability_r -> cl_stability.\n  Proof. \n    intros H1 H2 A B x Hx.\n    apply cl_idempotent.\n    generalize (H1 _ _ _ Hx).\n    apply cl_monotone, H2.\n  Qed.\n\n  Hint Resolve cl_stable_imp_stable_l cl_stable_imp_stable_r cl_stable_lr_imp_stable.\n  \n  Notation sg := (@eq _).\n\n  Notation cl_neutrality_1  := (forall a, cl (sg e ∘ sg a) a).\n  Notation cl_neutrality_2  := (forall a, sg e ∘ sg a ⊆ cl (sg a)).\n  Notation cl_commutativity := (forall a b, sg a ∘ sg b ⊆ cl (sg b ∘ sg a)).\n  Notation cl_associativity := (forall a b c, sg a ∘ (sg b ∘ sg c) ⊆ cl ((sg a ∘ sg b) ∘ sg c)).\n\n  Hypothesis cl_commute : cl_commutativity.\n\n  Proposition composes_commute_1 A B : A ∘ B ⊆ cl (B ∘ A).\n  Proof.\n    intros _ [ a b c Ha Hb Hc ].\n    apply cl_monotone with (sg b ∘ sg a).\n    apply composes_monotone; apply sg_inc1; auto.\n    apply cl_commute.\n    constructor 1 with (3 := Hc); auto.\n  Qed.\n\n  Hint Resolve composes_commute_1.\n\n  (* ⊆ ≃ ∩ ∪ ∘ *)\n\n  Proposition composes_commute A B : cl (A∘B) ≃ cl (B∘A).\n  Proof. \n    split; intros x Hx; apply cl_idempotent; revert Hx; apply cl_monotone; auto. \n  Qed. \n\n  Proposition cl_stable_l_imp_r : cl_stability_l -> cl_stability_r.\n  Proof.\n    intros Hl A B x Hx.\n    apply cl_idempotent.\n    apply cl_monotone with (cl B ∘ A).\n    apply inc1_trans with (cl ((cl B) ∘ A)); auto.\n    rewrite <- cl_prop; auto.\n    generalize (@composes_commute_1 B A); intros H.\n    rewrite cl_prop in H; auto.\n    apply composes_commute_1; auto.\n  Qed.\n  \n  Proposition cl_stable_r_imp_l : cl_stability_r -> cl_stability_l.\n  Proof.\n    intros Hl A B.\n    generalize (@composes_commute_1 B A); intros H.\n    rewrite cl_prop in H; auto.\n    apply inc1_trans with (B := cl (B ∘ cl A)),\n          inc1_trans with (2 := H); auto.\n    rewrite <- cl_prop; apply Hl.\n  Qed.\n\n  Hint Resolve cl_stable_l_imp_r cl_stable_r_imp_l.\n  \n  Proposition cl_stable_l_imp_stable : cl_stability_l -> cl_stability.    Proof. auto. Qed. \n  Proposition cl_stable_r_imp_stable : cl_stability_r -> cl_stability.    Proof. auto. Qed.\n\n  Hypothesis cl_stable_l : cl_stability_l.\n  \n  Proposition cl_stable_r : cl_stability_r.                               Proof. auto. Qed.\n  Proposition cl_stable : cl_stability.                                   Proof. auto. Qed.\n\n  Hint Resolve cl_stable_r cl_stable.\n\n  Hypothesis cl_neutral_1 : cl_neutrality_1.\n  Hypothesis cl_neutral_2 : cl_neutrality_2.\n  Hypothesis cl_associative : cl_associativity.\n\n  (* ⊆ ≃ ∩ ∪ ∘ ⊸ *)\n\n  Definition Magicwand A B k := sg k ∘ A ⊆ B.\n  Infix \"⊸\" := Magicwand (at level 51, right associativity).\n\n  Proposition magicwand_spec A B C : A ∘ B ⊆ C <-> A ⊆ B ⊸ C.\n  Proof.\n    split; intros H x Hx.\n    intros y Hy; apply H; revert Hy; apply composes_monotone; auto.\n    apply sg_inc1; auto.\n    destruct Hx as [ a b x Ha Hb Hx ].\n    apply (H _ Ha).\n    constructor 1 with a b; auto.\n  Qed.\n\n  Definition magicwand_adj_1 A B C := proj1 (magicwand_spec A B C).\n  Definition magicwand_adj_2 A B C := proj2 (magicwand_spec A B C).\n\n(*  Hint Resolve magicwand_adj_1 magicwand_adj_2. *)\n\n  Proposition magicwand_monotone A A' B B' : A ⊆ A' -> B ⊆ B' -> A' ⊸ B ⊆ A ⊸ B'.\n  Proof.\n    intros ? HB; apply magicwand_adj_1, inc1_trans with (2 := HB).\n    intros _ [? ? ? Ha ? Hc]; apply Ha, In_composes with (3 := Hc); auto.\n  Qed.\n\n  Hint Resolve magicwand_monotone.\n\n  Proposition cl_magicwand_1 X Y : cl (X ⊸ cl Y) ⊆ X ⊸ cl Y.\n  Proof. \n    apply magicwand_adj_1, \n          inc1_trans with (B := cl ((X ⊸ cl Y) ∘ X)); auto.\n    rewrite <- cl_prop; apply magicwand_spec; auto. \n  Qed.\n\n  Proposition cl_magicwand_2 X Y : cl X ⊸ Y ⊆ X ⊸ Y.\n  Proof. apply magicwand_monotone; auto. Qed.\n \n  Hint Immediate cl_magicwand_1 cl_magicwand_2.\n\n  Proposition cl_magicwand_3 X Y : X ⊸ cl Y ⊆ cl X ⊸ cl Y.\n  Proof.\n    intros c Hc y.\n    apply inc1_trans with (B := cl (sg c ∘ X)); auto.\n    rewrite <- cl_prop.\n    intros ? [ a b d [] Hb ].\n    intros; apply Hc. \n    constructor 1 with c b; auto.\n  Qed.\n\n  Hint Immediate cl_magicwand_3.\n\n  Proposition closed_magicwand X Y : closed Y -> closed (X ⊸ Y).\n  Proof. \n    simpl; intros ?.\n    apply inc1_trans with (B := cl (X ⊸ cl Y)); auto.\n    apply cl_monotone, magicwand_monotone; auto.\n    apply inc1_trans with (B := X ⊸ cl Y); auto.\n    apply magicwand_monotone; auto.\n  Qed.\n\n  Hint Resolve closed_magicwand.\n\n  Proposition magicwand_eq_1 X Y : X ⊸ cl Y ≃ cl X ⊸ cl Y.\n  Proof. split; auto. Qed.\n\n  Proposition magicwand_eq_2 X Y : cl (X ⊸ cl Y) ≃ X ⊸ cl Y.\n  Proof. split; auto. Qed.\n\n  Proposition magicwand_eq_3 X Y : cl (X ⊸ cl Y) ≃ cl X ⊸ cl Y.\n  Proof.\n    split; auto.\n    apply inc1_trans with (B := X ⊸ cl Y); auto.\n  Qed.\n\n  Hint Resolve magicwand_eq_1 magicwand_eq_2 magicwand_eq_3.\n\n  (* ⊆ ≃ ∩ ∪ ∘ ⊸ *)\n\n  Proposition cl_equiv_2 X Y : cl (cl X ∘ Y) ≃ cl (X ∘ Y).\n  Proof. \n    split.\n    rewrite <- cl_prop; auto.\n    apply cl_monotone, composes_monotone; auto.\n  Qed.\n\n  Proposition cl_equiv_3 X Y : cl (X ∘ cl Y) ≃ cl (X ∘ Y).\n  Proof.\n    split.\n    rewrite <- cl_prop; auto.\n    apply cl_monotone, composes_monotone; auto.\n  Qed.\n\n  Proposition cl_equiv_4 X Y : cl (cl X ∘ cl Y) ≃ cl (X ∘ Y).\n  Proof. \n    split.\n    rewrite <- cl_prop; auto.\n    apply cl_monotone, composes_monotone; auto.\n  Qed.\n\n  Hint Immediate cl_equiv_2 cl_equiv_3 cl_equiv_4.\n\n  Proposition composes_associative_1 A B C : A ∘ (B ∘ C) ⊆ cl ((A ∘ B) ∘ C).\n  Proof.\n    intros _ [a _ k Ha [b c y Hb Hc Hy] Hk].\n    generalize (@cl_associative a b c k); intros H.\n    spec all in H.\n    apply In_composes with (3 := Hk); auto.\n    apply In_composes with (3 := Hy); auto.\n    revert H.\n    apply cl_monotone.\n    repeat apply composes_monotone; apply sg_inc1; auto.\n  Qed.\n\n  Hint Immediate composes_associative_1.\n\n  Proposition composes_associative A B C : cl (A ∘ (B ∘ C)) ≃ cl ((A ∘ B) ∘ C).\n  Proof.\n    split; auto.\n    rewrite <- cl_prop; auto.\n    rewrite <- cl_prop; auto.\n    apply inc1_trans with (1 := @composes_commute_1 _ _).\n    rewrite <- cl_prop.\n    apply inc1_trans with (B := C ∘ cl (A ∘ B)); auto.\n    apply composes_monotone; auto.\n    apply inc1_trans with (B := C ∘ cl (B ∘ A)); auto.\n    apply composes_monotone; auto.\n    apply composes_commute.\n    apply inc1_trans with (1 := @cl_stable_r _ _).\n    rewrite <- cl_prop.\n    apply inc1_trans with (1 := @composes_associative_1 _ _ _).\n    rewrite <- cl_prop.\n    apply inc1_trans with (1 := @composes_commute_1 _ _). \n    rewrite <- cl_prop.\n    apply inc1_trans with (B := A ∘ cl (C ∘ B)); auto.\n    apply composes_monotone; auto.\n    apply inc1_trans with (B := A ∘ cl (B ∘ C)); auto.\n    apply composes_monotone; auto.\n    apply composes_commute.\n  Qed.\n\n  Hint Immediate composes_associative.\n\n  (* ⊆ ≃ ∩ ∪ ∘ ⊸ *)\n\n  Proposition composes_congruent_1 A B C : A ⊆ cl B -> C ∘ A ⊆ cl (C ∘ B).\n  Proof.\n    intros ?.\n    apply inc1_trans with (B := cl (C ∘ cl B)); auto.\n    apply cl_prop, cl_monotone, composes_monotone; auto.\n    apply cl_equiv_3.\n  Qed.\n\n  Hint Resolve composes_congruent_1.\n\n  Proposition composes_congruent A B C : cl A ≃ cl B -> cl (C ∘ A) ≃ cl (C ∘ B).\n  Proof. \n    intros [H1 H2].\n    rewrite <- cl_prop in H1.\n    rewrite <- cl_prop in H2.\n    split; rewrite <- cl_prop;\n    apply inc1_trans with (2 := @cl_stable_r _ _), composes_monotone; auto.\n  Qed.\n\n  Proposition composes_assoc_special A A' B B' : cl((A∘A') ∘ (B∘B')) ≃ cl ((A∘B) ∘ (A'∘B')).\n  Proof.\n    do 2 apply eq1_sym, eq1_trans with (2 := composes_associative _ _ _).\n    apply composes_congruent.\n    apply eq1_sym, eq1_trans with (1 := composes_commute _ _).\n    apply eq1_sym, eq1_trans with (2 := composes_associative _ _ _).\n    apply composes_congruent, composes_commute.\n  Qed.\n\n  Definition composes_assoc_special_1 A A' B B' := proj1 (composes_assoc_special A A' B B').\n  \n  Proposition composes_neutral_1 A : A ⊆ cl (sg e ∘ A).\n  Proof.\n    intros a Ha.\n    generalize (cl_neutral_1 a).\n    apply cl_monotone, composes_monotone; auto.\n    apply sg_inc1; auto.\n  Qed.\n\n  Proposition composes_neutral_2 A : sg e ∘ A ⊆ cl A.\n  Proof.\n    intros _ [y a x [] Ha Hx].\n    generalize (@cl_neutral_2 a x); intros H.\n    spec all in H.\n    constructor 1 with e a; auto.\n    revert H; apply cl_monotone, sg_inc1; auto.\n  Qed.\n  \n  Hint Resolve composes_neutral_1 composes_neutral_2.\n\n  Proposition composes_neutral A : cl (sg e ∘ A) ≃ cl A.\n  Proof. split; rewrite <- cl_prop; auto. Qed.\n\n  (* ⊆ ≃ ∩ ∪ ∘ ⊸ ⊛ *)\n\n  Notation \"x 'glb' y \" := (x ∩ y) (at level 50, no associativity).\n  Notation \"x 'lub' y\" := (cl (x ∪ y)) (at level 50, no associativity).\n\n  Proposition closed_glb A B : closed A -> closed B -> closed (A glb B).\n  Proof. \n    simpl; intros HA HB x Hx; split; \n      [ apply HA | apply HB ]; revert x Hx; \n      apply cl_monotone; tauto. \n  Qed.\n\n  Proposition lub_out A B C : closed C -> A ⊆ C -> B ⊆ C -> A lub B ⊆ C.\n  Proof. \n    simpl.\n    intros H1 H2 H3.\n    apply inc1_trans with (2 := H1), cl_monotone.\n    intros ? [ ]; auto.\n  Qed.\n\n  Proposition glb_in A B C : C ⊆ A -> C ⊆ B -> C ⊆ A glb B.\n  Proof. simpl; split; auto. Qed. \n\n  Proposition closed_lub A B : closed (A lub B).        Proof. simpl; apply cl_idempotent. Qed.\n  Proposition glb_out_l A B  : A glb B ⊆ A .            Proof. simpl; tauto. Qed.\n  Proposition glb_out_r A B  : A glb B ⊆ B.             Proof. simpl; tauto. Qed.\n  Proposition lub_in_l A B   : A ⊆ A lub B.             Proof. apply inc1_trans with (2 := cl_increase _); tauto. Qed.\n  Proposition lub_in_r A B   : B ⊆ A lub B.             Proof. apply inc1_trans with (2 := cl_increase _); tauto. Qed.\n\n  (* ⊆ ≃ ∩ ∪ ∘ ⊸ ⊛ *)\n\n  Notation \"x ⊛ y \" := (cl (x ∘ y)) (at level 59).\n\n  Proposition closed_times A B : closed (A⊛B).\n  Proof. simpl; apply cl_idempotent. Qed.\n\n  Proposition times_monotone A A' B B' : A ⊆ A' -> B ⊆ B' -> A⊛B ⊆ A'⊛B'.\n  Proof. simpl; intros ? ?; apply cl_monotone, composes_monotone; auto. Qed.\n\n  Notation top := (fun _ : M => True).\n  Notation bot := (cl (fun _ => False)).\n  Notation unit := (cl (sg e)). \n\n  Proposition closed_top     : closed top.         Proof. simpl; intros; auto. Qed. \n  Proposition closed_bot     : closed bot.         Proof. simpl; apply cl_idempotent. Qed.\n  Proposition closed_unit    : closed unit.        Proof. simpl; apply cl_idempotent. Qed.\n  Proposition top_greatest A : A ⊆ top.            Proof. simpl; tauto. Qed.\n\n  Hint Resolve closed_glb closed_top.\n\n  Fact closed_mglb ll : Forall closed ll -> closed (fold_right (fun x y => x ∩ y) top ll). \n  Proof. induction 1; simpl; auto. Qed.\n\n  Hint Resolve closed_mglb.\n\n  Proposition bot_least A : closed A -> bot ⊆ A.\n  Proof. intro H; apply inc1_trans with (2 := H), cl_monotone; tauto. Qed.\n\n  Proposition unit_neutral_1 A : closed A -> unit ⊛ A ⊆ A.\n  Proof. \n    intros H; apply inc1_trans with (2 := H).\n    rewrite <- cl_prop.\n    apply inc1_trans with (1 := @cl_stable_l _ _).\n    rewrite <- cl_prop.\n    apply composes_neutral_2.\n  Qed.\n\n  Proposition unit_neutral_2 A : A ⊆ unit ⊛ A.\n  Proof. \n    intros a Ha; simpl.\n    generalize (composes_neutral_1 _ _ Ha).\n    apply cl_monotone, composes_monotone; auto.\n  Qed.\n  \n(*  Hint Resolve unit_neutral_1 unit_neutral_2. *)\n\n  Proposition unit_neutral A : closed A -> unit ⊛ A ≃ A.\n  Proof. \n    intros H; split. \n    revert H; apply unit_neutral_1.\n    apply unit_neutral_2.\n  Qed.\n\n  (* ⊆ ≃ ∩ ∪ ∘ ⊸ ⊛ *)\n\n  Proposition times_commute_1 A B : A⊛B ⊆ B⊛A.\n  Proof. simpl; apply cl_inc, composes_commute_1. Qed.\n\n  Hint Resolve unit_neutral times_commute_1.\n \n  Proposition times_commute A B : A⊛B ≃ B⊛A.\n  Proof. split; auto. Qed.\n\n  Proposition unit_neutral' A : closed A -> A ⊛ unit ≃ A.\n  Proof. intros ?; apply eq1_trans with (1 := times_commute _ _); auto. Qed.\n\n  Proposition times_associative A B C : (A⊛B)⊛C ≃ A⊛(B⊛C).\n  Proof.\n    apply eq1_sym, eq1_trans with (1 := cl_equiv_3 _ _ ).\n    apply eq1_sym, eq1_trans with (1 := cl_equiv_2 _ _ ).\n    apply eq1_sym, composes_associative.\n  Qed.\n\n  Proposition times_associative_1 A B C : (A⊛B)⊛C ⊆ A⊛(B⊛C).     Proof. apply times_associative. Qed.\n  Proposition times_associative_2 A B C : A⊛(B⊛C) ⊆ (A⊛B)⊛C.     Proof. apply times_associative. Qed.\n\n  Hint Resolve times_associative_1 times_associative_2.\n\n  Proposition times_congruence A A' B B' : A ≃ A' -> B ≃ B' -> A⊛B ≃ A'⊛B'.\n  Proof. \n    intros H1 H2.\n    apply eq1_trans with (A ⊛ B').\n    apply composes_congruent; auto.\n    do 2 apply eq1_sym, eq1_trans with (1 := times_commute _ _).\n    apply composes_congruent; auto.\n  Qed.\n\n  (* ⊆ ≃ ∩ ∪ ∘ ⊸ ⊛ *)\n \n  Proposition adjunction_1 A B C : closed C -> A ⊛ B ⊆ C -> A ⊆ B ⊸ C.\n  Proof. intros ? H; apply magicwand_adj_1, inc1_trans with (2 := H); auto. Qed.\n\n  Proposition adjunction_2 A B C : closed C -> A ⊆ B ⊸ C -> A ⊛ B ⊆ C.\n  Proof. intros H ?; apply inc1_trans with (2 := H), cl_monotone, magicwand_adj_2; auto. Qed.\n\n  Hint Resolve times_congruence adjunction_1 (* adjunction_2 *).\n \n  Proposition adjunction A B C : closed C -> (A ⊛ B ⊆ C <-> A ⊆ B ⊸ C).\n  Proof.\n    split; [ apply adjunction_1 | apply  adjunction_2 ]; auto.\n  Qed.\n\n  Proposition times_bot_distrib_l A : bot ⊛ A ⊆ bot.\n  Proof.\n    apply adjunction_2; auto.\n    apply bot_least; auto.\n  Qed.\n\n  Proposition times_bot_distrib_r A : A ⊛ bot ⊆ bot.\n  Proof. apply inc1_trans with (1 := @times_commute_1 _ _), times_bot_distrib_l. Qed.\n \n  Hint Immediate times_bot_distrib_l times_bot_distrib_r.\n\n  Proposition times_lub_distrib_l A B C : (A lub B) ⊛ C ⊆ (A ⊛ C) lub (B ⊛ C).\n  Proof. \n    apply adjunction, lub_out; auto;\n    apply adjunction; auto. \n  Qed.\n\n  Proposition times_lub_distrib_r A B C : C ⊛ (A lub B) ⊆ (C ⊛ A) lub (C ⊛ B).\n  Proof. \n    apply inc1_trans with (1 := @times_commute_1 _ _),\n          inc1_trans with (1 := @times_lub_distrib_l _ _ _); auto.\n    apply lub_out; auto.\n  Qed.\n\n(*  Section bang. *)\n\n    (* J := { x | x ∈ unit /\\ x ∈ x ⊛ x } with unit = cl e and x ⊛ x = cl (x∘x) *)\n\n    Let J x := cl (sg e) x /\\ (cl (sg x ∘ sg x)) x.\n\n    Let In_J : forall x, cl (sg e) x -> (cl (sg x ∘ sg x)) x -> J x.\n    Proof. split; auto. Qed.\n\n    Let J_inv x : J x -> unit x /\\ cl (sg x ∘ sg x) x.\n    Proof. auto. Qed.\n\n    Proposition J_inc_unit : J ⊆ unit.\n    Proof. induction 1; trivial. Qed.\n\n    Variable K : M -> Prop.\n\n    Notation sub_monoid_hyp_1 := ((cl K) e).\n    Notation sub_monoid_hyp_2 := (K ∘ K ⊆ K).\n    Notation sub_J_hyp := (K ⊆ J).\n\n    Hypothesis sub_monoid_1 : sub_monoid_hyp_1.\n    Hypothesis sub_monoid_2 : sub_monoid_hyp_2.\n    Hypothesis sub_J : sub_J_hyp.\n\n    Proposition K_inc_unit : K ⊆ unit.\n    Proof. apply (inc1_trans _ J); trivial; apply J_inc_unit. Qed.\n\n   (* ⊆ ≃ ∩ ∪ ∘ ⊸ ⊛ ❗ *)\n\n    Proposition K_compose A B : (K ∩ A) ∘ (K ∩ B) ⊆ K ∩ (A ∘ B).\n    Proof.\n      intros x Hx.\n      induction Hx as [ a b c [ ] [ ] Hc ]; split.\n      + apply sub_monoid_2; constructor 1 with a b; auto.\n      + constructor 1 with a b; auto.\n    Qed.\n\n    Let bang A := cl (K∩A).\n\n    Notation \"❗ A\" := (bang A) (at level 40, no associativity).\n\n    Fact store_inc_unit A : ❗ A ⊆ unit.\n    Proof. \n      apply inc1_trans with (cl K).\n      + apply cl_monotone; tauto.\n      + apply cl_inc, K_inc_unit.\n    Qed.\n\n    Hint Resolve store_inc_unit.\n\n    Proposition closed_store A : closed (❗A).\n    Proof. simpl; apply cl_idempotent. Qed.\n\n    Proposition store_dec A : closed A -> ❗A ⊆ A.\n    Proof.\n      intros HA; simpl.\n      apply inc1_trans with (cl A); trivial.\n      apply cl_monotone.\n      apply glb_out_r.\n    Qed.\n\n    Fact store_monotone A B : A ⊆ B -> ❗A ⊆ ❗B.\n    Proof.\n      intro; apply cl_monotone.\n      intros ? []; split; auto.\n    Qed.\n\n    Proposition store_der A B : closed B -> ❗A ⊆ B -> ❗A ⊆ ❗B.\n    Proof.\n      unfold bang.\n      intros ? ?; apply cl_monotone; intros x []; split; auto.\n    Qed.\n \n    Proposition store_unit_1 : unit ⊆ ❗top.\n    Proof.\n      apply cl_inc.\n      intros ? []; apply cl_monotone with K; auto.\n    Qed.\n\n    Hint Resolve J_inc_unit.\n \n    Proposition store_unit_2 : ❗top ⊆ unit.\n    Proof.\n      apply cl_inc; trivial.\n      apply inc1_trans with J; auto.\n      intros ? []; auto.\n    Qed.\n\n    Hint Resolve store_unit_1 store_unit_2.\n\n    Proposition store_unit : unit ≃ ❗top.\n    Proof. split; auto. Qed.\n\n    (* ⊆ ≃ ∩ ∪ ∘ ⊸ ⊛ ❗ *)\n\n    Proposition store_comp A B : closed A -> closed B -> ❗A ⊛ ❗B ≃ ❗(A∩B).\n    Proof.\n      intros HA HB; split.\n      + apply inc1_trans with (cl ((K glb A) ∘ (K glb B))).\n        * apply cl_inc; trivial; apply cl_stable.\n        * apply cl_monotone.\n          intros x [ a b c [ H1 H2 ] [ H3 H4 ] Hc ].\n          assert (H5 : unit a). { apply K_inc_unit; auto. }\n          assert (H6 : unit b). { apply K_inc_unit; auto. }\n          split; [ | split ].\n          - apply sub_monoid_2; constructor 1 with a b; auto.\n          - apply unit_neutral_1; auto; apply times_commute_1, cl_increase.\n            constructor 1 with a b; auto.\n          - apply unit_neutral_1; auto; apply cl_increase.\n            constructor 1 with a b; auto.\n      + apply cl_inc; trivial.\n        intros x (H1 & H2 & H3).\n        apply cl_monotone with (sg x ∘ sg x).\n        2: { apply sub_J in H1; destruct H1; trivial. }\n        intros d [ a b ? ? Hab ]; subst a b; constructor 1 with x x; auto; \n          apply cl_increase; auto.\n    Qed.\n\n    Let ltimes := fold_right (fun x y => x ⊛ y) unit.\n    Let lcap := fold_right (fun x y => x∩y) top.\n\n    Proposition ltimes_store ll : \n           Forall closed ll \n        -> ltimes (map bang  ll)\n         ≃ ❗(lcap ll).\n    Proof.\n      unfold ltimes, lcap.\n      induction 1 as [ | A ll H1 H2 IH2 ]; auto.\n      + simpl; auto.\n      + simpl.\n        apply eq1_trans with (❗A ⊛ ❗(fold_right (fun x y => x ∩ y) top ll)).\n        * apply times_congruence; auto.\n        * apply eq1_trans with (❗(A ∩ fold_right (fun x y => x ∩ y) top ll)); auto.\n          apply store_comp; auto.\n    Qed.\n\n    Proposition store_compose_idem A : closed A -> ❗A ⊆ ❗A⊛❗A.\n    Proof.\n      intros HA.\n      apply inc1_trans with (❗(A∩A)).\n      + apply store_der. \n        * apply closed_glb; trivial.\n        * apply inc1_trans with A.\n          - apply store_dec; trivial.\n          - tauto.\n      + apply (proj2 (store_comp HA HA)).\n    Qed.\n\n(*  End bang. *)\n\n  Reserved Notation \"'⟦' A '⟧'\" (at level 49).\n  Reserved Notation \"'⟬߭' A '⟭'\" (at level 49).\n  \n  Variable (v : ill_vars -> M -> Prop) (Hv : forall x, cl (v x) ⊆ v x).\n  \n  Fixpoint Form_sem f :=\n    match f with\n      | ⟘             => bot\n      | ⟙             => top\n      | 𝝐              => unit\n      | £ x    => v x\n      | a -o b => ⟦a⟧ ⊸ ⟦b⟧\n      | a ⊗ b  => ⟦a⟧ ⊛ ⟦b⟧\n      | a ⊕ b  => ⟦a⟧ lub ⟦b⟧\n      | a & b  => ⟦a⟧ glb ⟦b⟧\n      | !a     => ❗⟦a⟧\n    end\n  where \"⟦ a ⟧\" := (Form_sem a).\n  \n  Fact closed_Form_sem f : cl (⟦f⟧) ⊆ ⟦f⟧.\n  Proof. induction f as [ | [] | | [] ]; simpl; unfold bang; auto. Qed.\n  \n  Definition list_Form_sem ll := fold_right (fun x y => x⊛y) unit (map Form_sem ll).\n   \n  Notation \"⟬߭  ll ⟭\" := (list_Form_sem ll).\n\n  Fact list_Form_sem_cons f ll : ⟬߭f::ll⟭  = ⟦f⟧ ⊛ ⟬߭ll⟭.\n  Proof. auto. Qed.\n\n  Fact closed_list_Form_sem ll : cl (⟬߭ll⟭) ⊆ ⟬߭ll⟭.\n  Proof. unfold list_Form_sem; induction ll; simpl; auto. Qed.\n  \n  Hint Resolve closed_Form_sem closed_list_Form_sem.\n  \n  Fact list_Form_sem_app ll mm : ⟬߭ll++mm⟭ ≃ ⟬߭ll⟭ ⊛⟬߭mm⟭.\n  Proof.\n    induction ll as [ | f ll IHll ]; simpl app; auto.\n    + apply eq1_sym, unit_neutral; auto.\n    + apply eq1_sym, eq1_trans with (1 := @times_associative _ _ _), eq1_sym.\n      apply times_congruence; auto.\n  Qed.\n  \n  Fact list_Form_sem_perm ll mm: ll ~p mm -> ⟬߭ll⟭  ≃ ⟬߭mm⟭ .\n  Proof.\n    induction 1 as [ | x l m _ IHl | x y l | l m k ]; auto.\n    + apply composes_congruent, cl_eq1; auto.\n    + simpl; do 2 apply eq1_sym, eq1_trans with (2 := @times_associative _ _ _).\n      apply times_congruence; auto.\n    + apply eq1_trans with (⟬߭m⟭ ); auto.\n  Qed.\n\n  Fact list_Form_sem_bang ll : ⟬߭‼ll⟭ ≃ ❗ (lcap (map Form_sem ll)).\n  Proof.\n    unfold list_Form_sem.\n    assert (Forall closed (map Form_sem ll)) as Hll.\n    { apply Forall_map, Forall_forall; auto. } \n    apply eq1_trans with (2 := ltimes_store Hll).\n    rewrite map_map.\n    apply equal_eq1; clear Hll.\n    induction ll as [ | a ll IHll ]; simpl; auto.\n    rewrite IHll; auto.\n  Qed.\n\n  (* All the rules of the ILL sequent calculus (including cut) are closed\n     under relational phase semantics, hence we deduce the following\n     soundness theorem *)\n\n  Theorem ill_Form_sem_sound Γ a : Γ ⊢ a -> ⟬߭Γ⟭  ⊆ ⟦a⟧.\n  Proof.\n    induction 1 as [ a \n                   | Ga De a H1 H2 IH2\n                   | Ga De a b c H1 IH1 H2 IH2\n                   | Ga a b H1 IH1\n                   | Ga a b c H1 IH1\n                   | Ga a b c H1 IH1\n                   | Ga a b H1 IH1 H2 IH2\n                   | Ga a b H1 IH1 \n                   | Ga a H1 IH1\n                   | Ga a b H1 IH1\n                   | Ga a b H1 IH1\n\n                   | Ga De a b H1 IH1 H2 IH2\n                   | Ga a b c H1 IH1\n                   | Ga De a b H1 IH1 H2 IH2\n                   | Ga a b c H1 IH1 H2 IH2\n                   | Ga a b H1 IH1\n                   | Ga a b H1 IH1\n                   | Ga a\n                   | Ga\n                   | Ga a H1 IH1\n                   |\n                   ]; simpl in *; auto.\n      (* axiom *)\n    + intro; apply unit_neutral'; auto.\n\n      (* permutation *)\n    + intros x Hx; apply IH2; revert Hx; apply list_Form_sem_perm; auto.\n\n      (* -o left *)\n    + intros x Hx.\n      apply IH2.\n      revert x Hx.\n      apply inc1_trans with (((⟦ a ⟧ ⊸ ⟦ b ⟧) ⊛ ⟬߭Ga⟭)⊛ ⟬߭De⟭).\n      * apply inc1_trans with (2 := @times_associative_2 _ _ _).\n        apply times_monotone; auto.\n        apply list_Form_sem_app.\n      * apply times_monotone; auto.\n        apply adjunction; auto.\n        apply magicwand_monotone; auto.\n    + apply adjunction; auto.\n      rewrite list_Form_sem_cons in IH1.\n      intros; apply IH1; auto.\n\n      (* plus *)\n    + apply inc1_trans with (2 := IH1), times_monotone; simpl; tauto.\n    + apply inc1_trans with (2 := IH1), times_monotone; simpl; tauto.\n\n      (* bang *)\n    + apply inc1_trans with (2 := IH1), times_monotone; auto.\n      apply cl_closed; auto; tauto.\n    + intros x Hx.\n      apply list_Form_sem_bang in Hx; revert x Hx.\n      apply store_der; auto.\n      intros x Hx; apply IH1, list_Form_sem_bang; auto.\n    + intros x Hx; apply IH1.\n      apply unit_neutral_1; auto.\n      revert x Hx; apply times_monotone; auto.\n      apply store_inc_unit.\n    + intros x Hx; apply IH1.\n      apply times_associative_1.\n      revert x Hx; apply times_monotone; auto.\n      simpl; intros x Hx; apply store_comp; auto.\n      revert x Hx; apply store_monotone; tauto.\n\n      (* cut rule *)\n    + intros x Hx.\n      apply list_Form_sem_app in Hx.\n      apply IH2.\n      revert x Hx; apply times_monotone; auto.\n\n      (* times *)\n    + intros x Hx; simpl.\n      apply IH1.\n      revert Hx; do 3 rewrite list_Form_sem_cons; simpl; auto.\n    + intros x Hx; apply list_Form_sem_app in Hx.\n      revert x Hx; apply times_monotone; auto.\n\n      (* plus *)\n    + intros x Hx.\n      apply times_lub_distrib_l in Hx.\n      revert Hx; apply cl_closed; auto.\n      intros ? []; auto.\n  \n    + (* bot *)\n      intros x Hx.\n      apply times_bot_distrib_l in Hx.\n      revert x Hx; apply bot_least; auto.\n\n      (* unit *)\n    + intros x Hx.\n      rewrite list_Form_sem_cons in Hx; simpl in Hx.\n      apply unit_neutral_1 in Hx; auto.\n  Qed.\n   \nEnd Relational_phase_semantics.\n\nLocal Infix \"∘\" := (@Composes _ _) (at level 50, no associativity).\n\nCheck ill_Form_sem_sound.\nPrint Assumptions ill_Form_sem_sound.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Coq-Phase-Semantics", "sha": "52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17", "save_path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics", "path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics/Coq-Phase-Semantics-52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17/coq.prop/phase_sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7282347599013151}}
{"text": "Require Export NArith.\nRequire Import ZArith.\nRequire Import NatAux.\n\nOpen Scope N_scope.\n\nTheorem Nle_le n m : (N.to_nat n <= N.to_nat m)%nat -> n <= m.\nProof.\ncase n; case m; unfold N.le; simpl; try (intros; discriminate).\nintros p; elim p using Pind; simpl.\nintros H1; inversion H1.\nintros n1 _; rewrite nat_of_P_succ_morphism.\nintros H1; inversion H1.\nintros p1 p2 H1 H2; absurd (nat_of_P p2 > nat_of_P p1)%nat; auto with arith.\napply nat_of_P_gt_Gt_compare_morphism; auto.\nQed.\n\nTheorem le_Nle n m : N.of_nat n <= N.of_nat m -> (n <= m)%nat.\nProof.\ncase n; case m; unfold N.le; simpl; auto with arith.\nintros n1 H1; case H1; auto.\nintros m1 n1 H1; case (Nat.le_gt_cases n1 m1); auto with arith.\nintros H2; case H1.\napply nat_of_P_gt_Gt_compare_complement_morphism.\nrepeat rewrite nat_of_P_o_P_of_succ_nat_eq_succ; auto with arith.\nQed.\n\nTheorem Nle_le_rev n m : n <= m -> (N.to_nat n <= N.to_nat m)%nat.\nProof. intros; apply le_Nle; repeat rewrite N2Nat.id; auto. Qed.\n\nTheorem Nlt_lt n m : (N.to_nat n < N.to_nat m)%nat -> n < m.\nProof.\ncase n; case m; unfold N.lt; simpl; try (intros; discriminate); auto.\nintros H1; inversion H1.\nintros p H1; inversion H1.\nintros; apply nat_of_P_lt_Lt_compare_complement_morphism; auto.\nQed.\n\nTheorem lt_Nlt n m : N.of_nat n < N.of_nat m -> (n < m)%nat.\nProof.\ncase n; case m; unfold N.lt; simpl; try (intros; discriminate); auto with arith.\nintros m1 n1 H1.\nrewrite <- (Nat2N.id (S n1)); rewrite <- (Nat2N.id (S m1)).\nsimpl; apply nat_of_P_lt_Lt_compare_morphism; auto.\nQed.\n\nTheorem Nlt_lt_rev n m : n < m -> (N.to_nat n < N.to_nat m)%nat.\nProof. intros; apply lt_Nlt; repeat rewrite N2Nat.id; auto. Qed.\n\n\nTheorem Nge_ge n m : (N.to_nat n >= N.to_nat m)%nat -> n >= m.\nProof.\ncase n; case m; unfold N.ge; simpl; try (intros; discriminate); auto.\nintros p; elim p using Pind; simpl.\nintros H1; inversion H1.\nintros n1 _; rewrite nat_of_P_succ_morphism.\nintros H1; inversion H1.\nintros p1 p2 H1 H2; absurd (nat_of_P p2 < nat_of_P p1)%nat; auto with arith.\napply nat_of_P_lt_Lt_compare_morphism; auto.\nQed.\n\nTheorem ge_Nge n m : N.of_nat n >= N.of_nat m -> (n >= m)%nat.\nProof.\ncase n; case m; unfold N.ge; simpl; try (intros; discriminate); auto with arith.\nintros n1 H1; case H1; auto.\nintros m1 n1 H1.\ncase (Nat.le_gt_cases m1 n1); auto with arith.\nintros H2; case H1.\napply nat_of_P_lt_Lt_compare_complement_morphism.\nrepeat rewrite nat_of_P_o_P_of_succ_nat_eq_succ; auto with arith.\nQed.\n\nTheorem Nge_ge_rev n m : n >= m -> (N.to_nat n >= N.to_nat m)%nat.\nProof. intros; apply ge_Nge; repeat rewrite N2Nat.id; auto. Qed.\n\nTheorem Ngt_gt n m : (N.to_nat n > N.to_nat m)%nat -> n > m.\nProof.\ncase n; case m; unfold N.gt; simpl; try (intros; discriminate); auto.\nintros H1; inversion H1.\nintros p H1; inversion H1.\nintros; apply nat_of_P_gt_Gt_compare_complement_morphism; auto.\nQed.\n\nTheorem gt_Ngt n m : N.of_nat n > N.of_nat m -> (n > m)%nat.\nProof.\ncase n; case m; unfold N.gt; simpl; try (intros; discriminate); auto with arith.\nintros m1 n1 H1.\nrewrite <- (Nat2N.id (S n1)); rewrite <- (Nat2N.id (S m1)).\nsimpl; apply nat_of_P_gt_Gt_compare_morphism; auto.\nQed.\n\nTheorem Ngt_gt_rev n m : n > m -> (N.to_nat n > N.to_nat m)%nat.\nProof. intros; apply gt_Ngt; repeat rewrite N2Nat.id; auto. Qed.\n\nTheorem Neq_eq_rev n m : n = m -> (N.to_nat n = N.to_nat m)%nat.\nProof. intros H; rewrite H; auto. Qed.\n\nTheorem Nmult_lt_compat_l n m p : n < m -> 0 < p -> p * n < p * m.\nProof.\nintros H1 H2; apply Nlt_lt; repeat rewrite N2Nat.inj_mul.\napply mult_lt_compat_l; apply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_le_compat_l n m p : n <= m -> p * n <= p * m.\nProof.\nintros H1; apply Nle_le; repeat rewrite N2Nat.inj_mul.\napply Nat.mul_le_mono_l; apply le_Nle; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_ge_compat_l n m p : n >= m -> p * n >= p * m.\nProof.\nintros H1; apply Nge_ge; repeat rewrite N2Nat.inj_mul.\napply mult_ge_compat_l; apply ge_Nge; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_gt_compat_l n m p : n > m -> p > 0 -> p * n > p * m.\nProof.\nintros H1 H2; apply Ngt_gt; repeat rewrite N2Nat.inj_mul.\napply mult_gt_compat_l; apply gt_Ngt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_lt_compat_rev_l1 n m p : p * n < p * m -> 0 < p.\nProof.\nintros H1; apply Nlt_lt.\napply mult_lt_compat_rev_l1 with (nat_of_N n) (nat_of_N m).\nrepeat rewrite <- N2Nat.inj_mul; apply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_lt_compat_rev_l2 n m p : p * n < p * m -> n < m.\nProof.\nintros H1; apply Nlt_lt; apply mult_lt_compat_rev_l2 with (nat_of_N p).\nrepeat rewrite <- N2Nat.inj_mul; apply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_gt_compat_rev_l1 n m p : p * n > p * m -> p > 0.\nProof.\nintros H1; apply Ngt_gt.\napply mult_gt_compat_rev_l1 with (nat_of_N n) (nat_of_N m).\nrepeat rewrite <- N2Nat.inj_mul; apply gt_Ngt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_gt_compat_rev_l2 n m p : p * n > p * m -> n > m.\nProof.\nintros H1; apply Ngt_gt; apply mult_gt_compat_rev_l2 with (nat_of_N p).\nrepeat rewrite <- N2Nat.inj_mul; apply gt_Ngt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_le_compat_rev_l n m p : p * n <= p * m -> 0 < p -> n <= m.\nProof.\nintros H1 H2; apply Nle_le; apply mult_le_compat_rev_l with (nat_of_N p).\nrepeat rewrite <- N2Nat.inj_mul; apply le_Nle; repeat rewrite N2Nat.id; auto.\napply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nmult_ge_compat_rev_l n m p : p * n >= p * m -> 0 < p -> n >= m.\nProof.\nintros H1 H2; apply Nge_ge; apply mult_ge_compat_rev_l with (nat_of_N p).\nrepeat rewrite <- N2Nat.inj_mul; apply ge_Nge; repeat rewrite N2Nat.id; auto.\napply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nlt_mult_0 a b : 0 < a -> 0 < b -> 0 < a * b.\nProof.\nintros H1 H2; apply Nlt_lt; rewrite N2Nat.inj_mul; apply lt_mult_0;\n  apply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Ngt_mult_0 a b : a > 0 -> b > 0 -> a * b > 0.\nProof.\nintros H1 H2; apply Ngt_gt; rewrite N2Nat.inj_mul; apply gt_mult_0;\n    apply gt_Ngt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nlt_mult_rev_0_l a b : 0 < a * b -> 0 < a .\nProof.\nintros H1; apply Nlt_lt; apply lt_mult_rev_0_l with (nat_of_N b).\nrewrite <- N2Nat.inj_mul; apply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nlt_mult_rev_0_r a b : 0 < a * b -> 0 < b .\nProof.\nintros H1; apply Nlt_lt; apply lt_mult_rev_0_r with (nat_of_N a).\nrewrite <- N2Nat.inj_mul; apply lt_Nlt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Ngt_mult_rev_0_l a b : a * b > 0 -> a > 0.\nProof.\nintros H1; apply Ngt_gt; apply gt_mult_rev_0_l with (nat_of_N b).\nrewrite <- N2Nat.inj_mul; apply gt_Ngt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Ngt_mult_rev_0_r a b : a * b > 0 -> b > 0 .\nProof.\nintros H1; apply Ngt_gt; apply gt_mult_rev_0_r with (nat_of_N a).\nrewrite <- N2Nat.inj_mul; apply gt_Ngt; repeat rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nle_0_eq_0 n : n <= 0 -> n = 0.\nProof.\nintros H1; rewrite <- (N2Nat.id n).\nrewrite (le_0_eq_0 (nat_of_N n)); auto.\napply le_Nle; rewrite N2Nat.id; auto.\nQed.\n\nTheorem Nge_0_eq_0 n : 0 >= n -> n = 0.\nProof.\nintros H1; rewrite <- (N2Nat.id n).\nrewrite (le_0_eq_0 (nat_of_N n)); auto.\nchange (0 >= nat_of_N n)%nat.\napply ge_Nge; rewrite N2Nat.id; auto.\nQed.\n\nImport BinPos.\n\nLtac to_nat_op :=\n  match goal with\n  | H: (N.lt _ _) |- _ => generalize (Nlt_lt_rev _ _ H); clear H; intros H\n  | H: (N.gt _ _) |- _ => generalize (Ngt_gt_rev _ _ H); clear H; intros H\n  | H: (N.le _ _) |- _ => generalize (Nle_le_rev _ _ H); clear H; intros H\n  | H: (N.ge _ _) |- _ => generalize (Nge_ge_rev _ _ H); clear H; intros H\n  | H: (@eq N _ _) |- _ => generalize (Neq_eq_rev _ _ H); clear H; intros H\n  | |- (N.lt _ _) => apply Nlt_lt\n  | |- (N.le _ _) => apply Nle_le\n  | |- (N.gt _ _) => apply Ngt_gt\n  | |- (N.ge _ _) => apply Nge_ge\n  | |- (@eq N _ _) => apply Nat2N.inj\n  end.\n\nLtac set_to_nat :=\n  let nn := fresh \"nn\" in\n  match goal with\n  | |- context [(N.to_nat (?X + ?Y)%N)] => rewrite N2Nat.inj_add\n  | |- context [(N.to_nat (?X * ?Y)%N)] => rewrite N2Nat.inj_mul\n  | |- context [(N.to_nat ?X)] => set (nn:=N.to_nat X) in * |- *\n  | H: context [(N.to_nat (?X + ?Y)%N)] |- _ => rewrite N2Nat.inj_add in H\n  | H: context [(N.to_nat (?X + ?Y)%N)] |- _ => rewrite N2Nat.inj_mul in H\n  | H: context [(N.to_nat ?X)] |- _ => set (nn:=N.to_nat X) in * |- *\n  end.\n\nLtac to_nat := repeat to_nat_op; repeat set_to_nat.\n\nTheorem Nle_gt_trans n m p : m <= n -> m > p -> n > p.\nProof. intros; to_nat; apply Nat.lt_le_trans with nn1; auto. Qed.\n\nTheorem Ngt_le_trans n m p : n > m -> p <= m -> n > p.\nProof. intros; to_nat; apply Nat.le_lt_trans with nn1; auto. Qed.\n\nTheorem Nle_add_l x y : x <= y + x.\nProof. intros; to_nat; auto with arith. Qed.\n\nClose Scope N_scope.\n", "meta": {"author": "thery", "repo": "PolTac", "sha": "cb5e530fdd8a1c72882d33b49146d397363103f2", "save_path": "github-repos/coq/thery-PolTac", "path": "github-repos/coq/thery-PolTac/PolTac-cb5e530fdd8a1c72882d33b49146d397363103f2/NAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7281653381880977}}
{"text": "Require Import Nat\n  PeanoNat Coq.Logic.EqdepFacts\n  Coq.Logic.Eqdep_dec\n  Coq.Arith.Peano_dec.\n\n\n\nSection Vector.\n\n\n\n  Inductive Vector (A : Type) : nat -> Type := \n  | Nil : Vector A 0 \n  | Cons n : A -> Vector A n -> Vector A (S n).\n\n  \n  Check Nil.\n  Eval compute in Nil nat.\n  Check Cons.\n  Eval compute in Cons _ _ 10 (Nil nat).\n  Eval compute in Cons _ _ 20 (Cons _ _ 10 (Nil nat)).\n  \n  Arguments Nil {A}.\n  Arguments Cons {A n}.\n  Eval compute in Cons 20 (Cons 10 Nil).\n\n\n  Fixpoint vector_append_first {A : Type} {m n : nat} \n    (u : Vector A m) (v : Vector A n) : Vector A (m + n) :=\n    match u with \n    | Nil => v \n    | Cons h t => Cons h (vector_append_first t v)\n    end.\n    \n  Fixpoint vector_append_second {A : Type} {m n : nat} \n    (u : Vector A m) (v : Vector A n) : Vector A (m + n) :=\n    match u as u' in Vector _ m' \n      return m = m' -> Vector A (m' + n)\n    with \n    | Nil => fun Hm => v (* m = 0 *)\n    | Cons h t => fun Hm => Cons h (vector_append_second t v) \n      (* m = S m' for some m' *)\n    end eq_refl.\n\n  Fixpoint vector_append_third {A : Type} {m n : nat} \n    (u : Vector A m) (v : Vector A n) : Vector A (m + n).\n  Proof.\n    refine(\n      match u as u' in Vector _ m' \n      return m = m' -> Vector A (m' + n)\n    with \n    | Nil => fun _ => v  \n    | Cons h t => fun _ => \n      (Cons h (vector_append_third _ _ _ t v))\n    end eq_refl).\n  Defined.\n   \n  \n\n\n  Definition vector_append_fourth {A : Type} {m n : nat} \n     (u : Vector A m) (v : Vector A n) : Vector A (m + n).\n  Proof.\n    generalize dependent n.\n    generalize dependent m.\n    refine(\n      fix Fn m u {struct u} := \n      match u as u' in Vector _ m'  \n        return forall (pf : m = m'), \n          u = eq_rect m' (fun w => Vector A w) \n              u' m (eq_sym pf) ->\n          forall n : nat, \n          Vector A n -> Vector A (m' + n) \n      with \n      | Nil => fun _ _ _  v => v  \n      | Cons h t => fun _ _ _ v =>\n      (Cons h (Fn _ t _ v))\n      end eq_refl eq_refl).\n  Defined.\n\n\n  Lemma append_nil_left {A : Type} {n : nat} :\n    forall (v : Vector A n), \n    vector_append_fourth Nil v = v.\n  Proof.  \n    refine (fun v => eq_refl).\n  Defined.\n  \n\n  Definition cast_vector {A : Type} {m n : nat} :\n    Vector A m -> m = n -> Vector A n.\n  Proof.\n    intros u H.\n    refine \n      match H with \n      | eq_refl => u \n      end.\n  Defined.\n\n  \n  Lemma uip_nat {n : nat} (pf : n = n) : pf = eq_refl.\n  Proof.\n    apply UIP_dec,\n    eq_nat_dec.\n  Qed.\n  \n\n  Lemma append_nil_right_ind_gen_tactic {A : Type}\n    {n m : nat} :\n    forall (a : A) (u : Vector A n)\n    (Ha : S n = S m)\n    (Hb : n = m),\n    cast_vector (Cons a u) Ha = \n    Cons a (cast_vector u Hb).\n  Proof.\n    intros *.\n    subst.\n    assert (Hapf : Ha = eq_refl).\n    apply uip_nat.\n    rewrite Hapf.\n    simpl.\n    reflexivity.\n  Defined.\n\n  Lemma append_nil_right_ind_gen_prog {A : Type}\n    {n m : nat} :\n    forall (a : A) u\n    (Ha : S m = S n)\n    (Hb : m = n),\n    cast_vector (Cons a u) Ha = \n    Cons a (cast_vector u Hb).\n  Proof.\n    intros a u Ha.\n    refine(\n      match Ha as Ha' in (_ = S n')\n        return forall (pf : n = n'), \n        Ha = eq_rect (S n') _ Ha' (S n) \n            (eq_S _ _ (eq_sym pf)) -> \n        forall Hb : m = n',\n        cast_vector (Cons a u) Ha' =\n        Cons a (cast_vector u Hb)\n      with \n      | eq_refl => fun Hpf Hb Hbpf => \n        match Hbpf as Hbpf' in (_ = m')\n        return forall (pf : m = m'), \n          Hbpf' = eq_rect m _ eq_refl m' pf -> \n          cast_vector (Cons a u) eq_refl =\n          eq_rect (S m') _ (Cons a (cast_vector u Hbpf'))\n          (S m) (eq_S _ _ (eq_sym pf)) \n        with\n        | eq_refl => _\n        end eq_refl _ \n      end eq_refl eq_refl).\n    + intros *.\n      cbn.\n      rewrite (uip_nat pf).\n      simpl.\n      reflexivity.\n    + simpl.\n      apply uip_nat. \n  Defined.\n  \n\n  Lemma append_nil_right_ind {A : Type} {n : nat} :\n    forall (a : A) (u : Vector A n),\n    cast_vector (Cons a u) (plus_n_O (S n)) = \n    Cons a (cast_vector u (plus_n_O n)). \n  Proof.\n    intros *.\n    apply append_nil_right_ind_gen_tactic.\n  Qed.\n\n\n  Lemma append_nil_right {A : Type} {n : nat} : \n    forall (u : Vector A n),\n    vector_append_fourth u Nil = \n    cast_vector u (plus_n_O n).\n  Proof.\n    induction u.\n    + simpl.\n      refine \n        match (plus_n_O 0) with \n        | eq_refl => eq_refl\n        end.\n    + simpl.\n      rewrite IHu.\n      symmetry.\n      apply append_nil_right_ind.\n  Qed.\n\n  \n  (* generalisation is the key *)\n  Lemma append_associative_gen {A : Type} :\n    forall {m : nat} (u : Vector A m) \n    {n o : nat} (v : Vector A n) (w : Vector A o)\n    (Ha : m + n + o = m + (n + o)),\n    vector_append_fourth u (vector_append_fourth v w) =\n    cast_vector (vector_append_fourth (vector_append_fourth u v) w) Ha.\n  Proof.\n    refine(\n      fix Fn m u {struct u} := \n      match u as u' in Vector _ m' \n      return m = m' ->  _ \n      with \n      | Nil => _ \n      | Cons _ _ => _ \n      end eq_refl).\n      + intros Hb ? ? ? ? ?;\n        simpl in * |- *.\n        assert (Ht : Ha = eq_refl).\n        apply uip_nat.\n        subst; simpl.\n        exact eq_refl.\n      + intros Hb ? ? ? ? ?; \n        simpl in * |- *.\n        inversion Ha as (Haa).\n        erewrite append_nil_right_ind_gen_prog \n        with (Hb := Haa).\n        f_equal.\n        apply Fn.\n  Defined.\n\n  \n  Lemma append_associative {A : Type} :\n    forall {m : nat} (u : Vector A m) \n    {n o : nat} (v : Vector A n) (w : Vector A o),\n    vector_append_fourth u (vector_append_fourth v w) =\n    cast_vector (vector_append_fourth (vector_append_fourth u v) w)\n    (eq_sym (Nat.add_assoc m n o)).\n  Proof.\n    intros until w.\n    eapply append_associative_gen.\n  Defined.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    \n   ", "meta": {"author": "mukeshtiwari", "repo": "CoqUtil", "sha": "1652ce26841d9eb706d0c0b847dc2c66283646cb", "save_path": "github-repos/coq/mukeshtiwari-CoqUtil", "path": "github-repos/coq/mukeshtiwari-CoqUtil/CoqUtil-1652ce26841d9eb706d0c0b847dc2c66283646cb/src/Vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970685907242, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7281653323078883}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Logic.FunctionalExtensionality.\nSet Implicit Arguments.\n\nSection Base.\n\n  Variable Var : Set.\n  Variable Val : Set.\n\n  Definition State := Var -> Val.\n  Definition StateFunc := State -> Val.\n  Definition Predicate := State -> Prop.\n  Definition Action := State -> State -> Prop.\n\n  Definition unchanged (f : StateFunc) : Action :=\n    fun st st' => f st = f st'.\n\n  Definition pred (P : Predicate) : Action :=\n    fun st st' => P st.\n\n  Definition prime (P : Predicate) : Action :=\n    fun st st' => P st'.\n\n  Inductive Formula :=\n  | F_Act : Action -> Formula\n  | F_Enabled : Action -> Formula\n  | F_Always : Formula -> Formula\n  | F_Eventually : Formula -> Formula\n  | F_Not : Formula -> Formula\n  | F_And : Formula -> Formula -> Formula\n  | F_Or : Formula -> Formula -> Formula\n  | F_Imp : Formula -> Formula -> Formula\n  | F_Iff : Formula -> Formula -> Formula.\n\n  Definition Trace := nat -> State.\n  Definition shift (t : Trace) (n : nat) : Trace := fun m => t (n + m).\n  Infix \"<<\" := shift (at level 55, left associativity).\n\n  Section Shift.\n    Variable t : Trace.\n    (* Make sure we got the precedence and associativity right. *)\n    (* Check (t << 10 << 5 + 1 << 2 * 10 << 10 - 9). *)\n\n    Theorem shift_id :\n      t << 0 = t.\n    Proof.\n      reflexivity.\n    Qed.\n\n    Theorem shift_add :\n      forall n m, t << n << m = t << n + m.\n    Proof.\n      unfold shift.\n      intros n m.\n      apply functional_extensionality.\n      intros x.\n      f_equal.\n      apply Nat.add_assoc.\n    Qed.\n\n    Theorem shift_app :\n      forall n i, (t << n) i = t (n + i).\n    Proof.\n      intros n i.\n      unfold shift.\n      reflexivity.\n    Qed.\n\n    Lemma shift_app_add :\n      forall i j k, (t << i + j) k = (t << i) (j + k).\n    Proof.\n      intros i j k.\n      repeat (rewrite shift_app).\n      intuition.\n    Qed.\n\n  End Shift.\n\n  Fixpoint satisfies (fm : Formula) (t : Trace) : Prop :=\n    match fm with\n    | F_Act A => A (t 0) (t 1)\n    | F_Enabled A => exists st', A (t 0) st'\n    | F_Always p => forall n, satisfies p (t << n)\n    | F_Eventually p => exists n, satisfies p (t << n)\n    | F_Not p => ~satisfies p t\n    | F_And p q => satisfies p t /\\ satisfies q t\n    | F_Or p q => satisfies p t \\/ satisfies q t\n    | F_Imp p q => satisfies p t -> satisfies q t\n    | F_Iff p q => satisfies p t <-> satisfies q t\n    end.\n\n  Notation \"~ A\" := (F_Not A) : tla_scope.\n  Infix \"/\\\" := F_And : tla_scope.\n  Infix \"\\/\" := F_Or : tla_scope.\n  Infix \"==>\" := F_Imp (at level 99, right associativity) : tla_scope.\n  Infix \"<==>\" := F_Iff (at level 95, no associativity) : tla_scope.\n  Notation \"[] F\" := (F_Always F) (at level 75, right associativity) : tla_scope.\n  Notation \"<> F\" := (F_Eventually F) (at level 75, right associativity) : tla_scope.\n\n  Delimit Scope tla_scope with tla.\n\n  Definition F_Pred (P : Predicate) : Formula :=\n    F_Act (pred P).\n\n  Definition F_Box (A : Action) (f : StateFunc) : Formula :=\n    F_Or (F_Act A) (F_Act (unchanged f)).\n\n  Coercion F_Act : Action >-> Formula.\n  Coercion F_Pred : Predicate >-> Formula.\n\n  Local Open Scope tla_scope.\n\n  Definition valid (fm : Formula) := forall t, satisfies fm t.\n\n  Theorem STL2 :\n    forall F, valid ([]F ==> F).\n  Proof.\n    intros F t; simpl.\n    intros H.\n    specialize H with 0.\n    assumption.\n  Qed.\n\n  Theorem STL3 :\n    forall F, valid ([][]F <==> []F).\n  Proof.\n    intros F t; simpl.\n    split; intros H.\n\n    intros n.\n    specialize (H n 0).\n    assumption.\n\n    intros n m.\n    specialize H with (n + m).\n    rewrite shift_add.\n    assumption.\n  Qed.\n\n  Theorem STL4 :\n    forall F G, valid (F ==> G) -> valid ([]F ==> []G).\n  Proof.\n    intros F G.\n    unfold valid; simpl.\n    intuition.\n  Qed.\n\n  Theorem STL5 :\n    forall F G,\n      valid ( [](F /\\ G) <==> []F /\\ []G).\n  Proof.\n    intros F G.\n    unfold valid; simpl.\n    split; [intros H; split; intros n; specialize (H n) | idtac]; intuition.\n  Qed.\n\n  Theorem TLA1 :\n    forall (P : Predicate) f,\n      valid (P /\\ unchanged f ==> prime P) ->\n      valid ([]P <==> P /\\ []((P ==> prime P) \\/ unchanged f)).\n  Proof.\n    intros P f.\n    unfold valid, unchanged; simpl.\n    unfold pred, prime; simpl.\n    intros H t; split.\n\n    intros Hn; split.\n    specialize Hn with 0; assumption.\n\n    left; intros.\n    specialize Hn with (n+1).\n    rewrite shift_app_add in Hn.\n    assumption.\n\n    intros (HP, Hn).\n    induction n; try assumption.\n    replace (S n) with (n+1) by apply Nat.add_1_r.\n    rewrite shift_app_add.\n    specialize H with (t << n).\n    specialize Hn with n.\n    intuition.\n  Qed.\n\n  Theorem TLA2 :\n    forall (P Q : Predicate) (A B : Action) (f g : StateFunc),\n      valid (P /\\ (F_Box A f) ==> Q /\\ (F_Box B g)) ->\n      valid ([]P /\\ [](F_Box A f) ==> []Q /\\ [](F_Box B g)).\n  Proof.\n    intros P Q A B f g.\n    unfold valid, unchanged; simpl.\n    unfold pred; simpl.\n    intros Ht t (HP, HA).\n    split;\n      intros n;\n      specialize Ht with (t << n);\n      specialize HP with n;\n      specialize HA with n;\n      intuition.\n  Qed.\n\n  Theorem INV1 :\n    forall (I : Predicate) (N : Action) (f : StateFunc),\n      valid (I /\\ (F_Box N f) ==> prime I) ->\n      valid (I /\\ [](F_Box N f) ==> []I).\n  Proof.\n    intros I N f.\n    unfold valid, unchanged; simpl.\n    unfold pred, prime; simpl.\n    intros Ht t.\n    intros (H0, Hn) n.\n    induction n; try assumption.\n    replace (S n) with (n+1) by apply Nat.add_1_r.\n    rewrite shift_app_add.\n    specialize Hn with n.\n    intuition.\n  Qed.\n\nEnd Base.\n", "meta": {"author": "sampollard", "repo": "q-supplement", "sha": "2b5290074d3055509b77508e5a8e411f23f68640", "save_path": "github-repos/coq/sampollard-q-supplement", "path": "github-repos/coq/sampollard-q-supplement/q-supplement-2b5290074d3055509b77508e5a8e411f23f68640/semantics/coq/src/TLA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7281565802438466}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(* Course of values induction                                               *)\n(* To be integrated in ARITH library                                        *)\n(*                                                                          *)\n(****************************************************************************)\n(*                           Complete_induction.v                           *)\n(****************************************************************************)\n\nRequire Import Lt.\nRequire Import Le.\n\nDefinition lt_hereditary (P : nat -> Prop) :=\n  forall n : nat, (forall m : nat, m < n -> P m) -> P n.\n\nLemma le_split : forall m n : nat, m <= S n -> m <= n \\/ m = S n.\nProof.\nintros m n H; elim (le_lt_or_eq m (S n)); auto with arith.\nQed.\n\nLemma course_of_values :\n forall P : nat -> Prop, lt_hereditary P -> forall n m : nat, m <= n -> P m.\nProof.\nunfold lt_hereditary in |- *; simple induction n.\nintros; apply H.\nelim (le_n_O_eq m); trivial with arith.\nintros p abs; elim lt_n_O with p; trivial with arith.\nintros p lemp m lemSp; elim le_split with m p; auto with arith.\nintro E; rewrite E; auto with arith. (* using lt_n_Sm_le *)\nQed.\n\nLemma complete_induction :\n forall P : nat -> Prop, lt_hereditary P -> forall n : nat, P n.\nProof.\nintros; apply course_of_values with (m := n) (n := n); auto with arith.\nQed.\n\n(* Version Ledinot *)\nLemma nat_wf_ind :\n forall P : nat -> Prop,\n P 0 ->\n (forall k : nat, (forall l : nat, l <= k -> P l) -> P (S k)) ->\n forall n : nat, P n.\nProof.\nintros P H0 Hk.\ncut (forall n k : nat, k <= n -> P k).\nintros HC n.\napply HC with (n := n); auto with arith.\nsimple induction n.\nintros k Def_k.\nelimtype (0 = k); auto with arith.\nclear n.\nintros n Hn k k_le_Sn.\nelim (le_split k n); auto with arith.\nintro Def_k.\nrewrite Def_k.\nauto with arith.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "canon-bdds", "sha": "1420af91ba2f898b70404a6600c2b87881338a0e", "save_path": "github-repos/coq/coq-contribs-canon-bdds", "path": "github-repos/coq/coq-contribs-canon-bdds/canon-bdds-1420af91ba2f898b70404a6600c2b87881338a0e/canonicite/Complete_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7281565681153869}}
{"text": "\n(* This file contains the definition of the base 2 logarithm function (rounded down) over natural numbers. *)\n\n(* Some of the definitions and theory in this file were added to Coq 8.4, so we should refactor this at some point. *)\n\nSet Implicit Arguments.\n\nRequire Import ZArith.\n\n(* log2 is like log_inf except it returns nat, so I don't have to reason about an unnecessary conversion. This function is only used to implement lognat below.*)\nFixpoint log2(n : positive) : nat :=\n  match n with \n    | xH => 0\n    | xO n' | xI n' => (S (log2 n'))\n  end.\n\nLemma log2_prod_sum : forall(a : positive),\n  (S (log2 a)) = (log2 (Pmult 2 a)).\n  \n  intros. auto.\nQed.\n\n\nLemma le_s : forall a b,\n  (a <= b) -> S a <= S b.\n\n  intros. omega.\nQed.\n\n\n\nLemma log2_monotonic_b : forall(a : positive),\n  (log2 a) <= (log2 (Psucc a)).\n\n  induction a; \n  simpl in *; try apply le_s; auto.\nQed.\n\nLemma log2_ge_monotonic : forall(a : positive),\n  (log2 (Psucc a)) >= (log2 a).\n\n  induction a; \n  simpl in *; try apply le_s; auto.\nQed.\n\n\nDefinition nat_to_pos (n : nat) : (n <> 0) -> positive :=\n  fun _ => (P_of_succ_nat (pred n)).\n\nLemma double_nat_nz : forall(a : nat)(pf : a <> 0),\n  ((2 * a) <> 0).\n  intros. omega.\nQed.\nLemma s_nat_nz : forall(a : nat)(pf : a <> 0),\n  ((S a) <> 0).\n  intros. omega.\nQed.\n\nLemma factor_s_conv : forall(a : nat)(pf1 : (a <> 0))(pf2 : (S a) <> 0),\n  (nat_to_pos (pf2)) = (Psucc (nat_to_pos pf1)).\n  \n  intros. \n  destruct a.\n  congruence.\n\n  unfold nat_to_pos in *.\n  simpl in *.\n  intros. auto.\nQed.\n\nLemma add_s_r : forall a b,\n  a + (S b) = S (a + b).\n  intros. omega.\nQed.\n\nLemma factor_double_s : forall a,\n  (2 * (S a)) = (S (S (2 * a))).\n\n  intros. omega.\nQed.\n\nLemma factor_double_conv : forall(a : nat)(pf1 : (a <> 0))(pf2 : (2 * a) <> 0),\n  (nat_to_pos pf2) = (Pmult 2 (nat_to_pos pf1)).\n\n  induction a; intros; simpl in *.\n  congruence.\n\n  destruct (eq_nat_dec a 0).\n  subst. \n  unfold nat_to_pos.\n  auto.\n\n  assert (a + S (a + 0) <> 0) by omega.\n  specialize (factor_s_conv H). intros. \n  unfold nat_to_pos in *.\n\n  rewrite (H0 pf2). clear H0.  clear pf2.\n  assert (a + S (a + 0) = S (a + (a + 0))) by omega.\n  rewrite H0.  \n  assert (a + (a + 0) <> 0) by omega.\n  specialize (factor_s_conv H1). intros. \n  \n  unfold nat_to_pos in H2.\n  rewrite <- H0 in H2.\n  rewrite <- H0.\n  rewrite (H2 H). clear H. clear H2.\n  \n  rewrite (IHa n). clear IHa.\n  simpl.\n  destruct a. intros. destruct n. auto.\n\n  auto.\n  omega. \nQed.\n\nDefinition lognat(n : nat) : (n <> 0) -> nat := \n  fun pf => (log2 (nat_to_pos pf)).\n\nTheorem lognat_prod_sum : forall(a : nat)(pf1 : (a <> 0))(pf2: (2 * a) <> 0),\n  (S (lognat pf1)) = (lognat pf2).\n  \n  intros. \n  unfold lognat in *.\n  rewrite (factor_double_conv pf1 pf2).\n  eapply log2_prod_sum.\nQed.  \n\nTheorem lognat_monotonic_b : forall(a : nat)(pf1 : (a <> 0))(pf2: (S a) <> 0),\n  (lognat pf1) <= (lognat pf2).\n  \n  induction a.\n  intros. \n  destruct pf1. auto.\n\n  intros. \n  unfold lognat in *.\n  rewrite (factor_s_conv pf1).\n  apply log2_monotonic_b.\nQed.\n\n(* for good measure, we will define exponentiation for nat and prove that lognat is correct *)\nFixpoint expnat(a e : nat) : nat :=\n  match e with\n    | 0 => 1\n    | (S e') => a * (expnat a e')\n  end.\n\nLemma mult_ne : forall a b,\n  a <> 0 -> b <> 0 -> a * b <> 0.\n\n  intros. \n  destruct a. omega. \n  destruct b. omega. \n  simpl. \n  remember (b + a * (S b)) as c.\n  omega. \nQed.\n  \n\nTheorem expnat_nz : forall a e,\n  (a <> 0) -> (expnat a e) <> 0.\n\n  induction e.\n  simpl. auto.\n\n  simpl. \n  intros. \n  eapply mult_ne; eauto.\nQed.\n\nLemma nz_2 : 2 <> 0.\n  omega.\nQed.\n\nTheorem expnat_2_nz: forall e,\n  (expnat 2 e) <> 0.\n  \n  intros. \n  apply (expnat_nz e nz_2).\nQed.\n\nTheorem expnat_2_monotonic : forall e1 e2,\n  e1 <= e2 ->\n  (expnat 2 e1 <= expnat 2 e2).\n  \n  induction e1.\n  intros.\n  simpl.\n  specialize (expnat_2_nz e2). intros.\n  omega.\n\n  induction e2;\n  intros.\n  omega.\n\n  simpl. \n  specialize (IHe1 e2).\n  omega.\nQed.\n\nTheorem lognat_correct_eq : forall(b : nat)(pf : (expnat 2 b) <> 0),\n  (lognat pf) = b.\n\n  induction b.\n  intros. simpl in *. auto.\n  \n  intros. \n  specialize (lognat_prod_sum (expnat_2_nz b)). intros. \n  specialize (IHb (expnat_2_nz b)). \n  rewrite IHb in H.\n  symmetry in H.\n  simpl in *.\n  apply H.\nQed.\n\n\nLemma fold_add : forall a,\n  a + (a + 0) = 2*a.\n  intros. omega.\nQed.\n\nTheorem lognat_ge_monotonic_b : forall(a : nat)(pf1 : (a <> 0))(pf2: (S a) <> 0),\n  (lognat pf2) >= (lognat pf1).\n  \n  induction a.\n  intros. \n  destruct pf1. auto.\n\n  intros. \n  unfold lognat in *.\n  rewrite (factor_s_conv pf1).\n  apply log2_monotonic_b.\nQed.\n\nLemma ge_trans : forall a b c,\n  a >= b -> b >= c -> a >= c.\n  intuition.\nQed.\n\nLemma lognat_ge_monotonic_h : forall (c a b : nat)(pfa : a <> 0)(pfb : b <> 0), \n    a >= b -> c = (a - b) -> (lognat pfa) >= (lognat pfb).\n\n  induction c.\n  intros. \n  assert (a = b) by intuition.\n  subst. auto.\n\n  intros. \n  assert (a >= (S b)) by omega. \n  assert (c = a - (S b)) by omega.\n  eapply ge_trans.\n  apply (IHc a (S b) pfa (s_nat_nz pfb)).\n  apply H1.\n  apply H2.\n  apply lognat_ge_monotonic_b.\nQed.\n\nLemma lognat_ge_monotonic : forall (a b : nat)(pfa : a <> 0)(pfb : b <> 0), \n    a >= b -> (lognat pfa) >= (lognat pfb).\n\n  intros.\n  remember (a - b) as c.\n  apply (@lognat_ge_monotonic_h c); auto.\nQed.\n\nLemma lognat_monotonic : forall (a b : nat)(pfa : a <> 0)(pfb : b <> 0), \n    a <= b -> (lognat pfa) <= (lognat pfb).\n\n  intros.\n  remember (b - a) as c.\n  apply (@lognat_ge_monotonic_h c); auto.\nQed.\n\nTheorem mt : forall P Q: Prop, (P -> Q) -> (~Q -> ~P).\n  unfold not in *.\n  intros. \n  apply H0.\n  apply H.\n  apply H1.\nQed.\n\nLemma ge_not : forall a b,\n  ~(a >= b) -> a < b.\n  intuition.\nQed.\n\nLemma lognat_ge_monotonic_mt : forall (a b : nat)(pfa : a <> 0)(pfb : b <> 0), \n    (lognat pfa) < (lognat pfb) -> a < b.\n\n  intros. \n  specialize (lognat_ge_monotonic pfa pfb).\n  intros. \n  specialize (mt H0).\n  intros. \n  apply ge_not. omega.\nQed.\n\nLemma lognat_correct2 : forall(a : nat)(pf : a <> 0),\n  a < (expnat 2 (S (lognat pf))).\n  \n  intros. \n\n  simpl.\n  rewrite fold_add.\n  assert (expnat 2 (lognat pf) <> 0). apply expnat_nz. auto.\n  assert (2 * (expnat 2 (lognat pf)) <> 0). omega. \n  eapply (lognat_ge_monotonic_mt pf H0). \n  rewrite <- (lognat_prod_sum H).\n  rewrite lognat_correct_eq.\n  omega.\nQed.\n\nLemma lognat_odd : forall(a : nat)(pf1 : (2 * a) <> 0)(pf2 : (S (2 * a)) <> 0),\n  ((lognat pf2) = (lognat pf1)).\n\n  intros. \n  unfold lognat in *.\n  rewrite (factor_s_conv pf1 pf2).\n  assert (a <> 0). omega.\n  rewrite (factor_double_conv H pf1).\n  simpl. \n  auto.\nQed.\n\nLemma double_s : forall a, (S (S (2 * a))) = 2 * (S a).\n  intros. omega.\nQed.\n\n\nLemma lognat_double_eq : forall a b (pf1: 2 * a <> 0)(pf2: 2 * b <> 0)(pf3 : a <> 0) (pf4: b <> 0),\n  lognat pf3 = lognat pf4 -> \n  lognat pf1 = lognat pf2.\n\n  intros. \n  rewrite <- (lognat_prod_sum pf3).\n  rewrite <- (lognat_prod_sum pf4).\n  omega.\nQed.\n\nLemma nat_comp : forall(a : nat),\n  exists x : nat,\n  (a = (2 * x) \\/ a = (S (2 * x))).\n\n  induction a.\n  exists 0. simpl.  auto.\n\n  elim IHa. clear IHa.\n  intros. \n  destruct H.\n  subst. simpl.\n  exists x.\n  right. auto.\n\n  subst. simpl. \n  exists (S x).\n  left.\n  simpl. \n  omega. \nQed.\n\nLemma lognat_correct1 : forall(b a : nat)(pf : a <> 0),\n  (lognat pf) = b -> \n  (expnat 2 b) <= a.\n\n  induction b.\n\n  intros. simpl in *. omega.\n\n  intros. \n  elim (nat_comp a). intros. \n  destruct H0.\n  subst. \n  destruct (eq_nat_dec x 0).\n  subst. omega. \n  rewrite <- (lognat_prod_sum n pf) in H.\n  inversion H. clear H.\n  rewrite H1.\n  apply IHb in H1.\n  simpl in *. omega. \n\n  subst. \n  destruct (eq_nat_dec x 0).\n  subst. unfold lognat in H. simpl in *. omega. \n  assert ((2 * x) <> 0). omega.\n  rewrite (lognat_odd x H0 pf) in H.\n  \n  rewrite <- (lognat_prod_sum n H0) in H.\n  inversion H.\n  rewrite H2.\n  apply IHb in H2.\n  simpl. \n  omega.\nQed.  \n  \n  \nTheorem lognat_correct : forall(a : nat)(pf : a <> 0),\n  (expnat 2 (lognat pf)) <= a < (expnat 2 (S (lognat pf))).\n\n  intros.\n  split.\n  remember (lognat pf) as b.\n  apply (lognat_correct1 pf). auto.\n  apply lognat_correct2.\nQed.\n\nLemma lognat_prod_sum_gen_h : forall (a' a b: nat)(pf1 : (a <> 0))(pf2 : (b <> 0))(pf3 : a * b <> 0), \n  lognat pf1 = a' ->\n  a' + lognat pf2 <= lognat pf3.\n \n  induction a'; intros. \n  simpl. \n  eapply lognat_monotonic. \n  induction a.\n  congruence.\n  simpl. \n  intuition.\n\n  destruct (nat_comp a).\n  destruct H0.\n  subst.\n  assert (x <> 0). omega.\n  assert (x * b <> 0). destruct x; destruct b; simpl; congruence.\n  rewrite <- (lognat_prod_sum H0) in H.\n  assert (lognat pf3 = S (lognat H1)). \n  generalize pf3.\n  rewrite mult_assoc_reverse.\n  intros. \n  rewrite (lognat_prod_sum _ pf0).\n  trivial.\n\n  rewrite H2.\n  inversion H.\n  specialize (IHa' x b H0 pf2 H1 H4).\n  subst.\n  omega. \n\n  destruct (eq_nat_dec x 0).\n  subst.\n  unfold lognat in *.\n  simpl in *.\n  discriminate.\n\n  assert (2 * x <> 0). omega. \n  assert (x * b <> 0). destruct x; destruct b; simpl; congruence.\n  assert (2 * x * b <> 0). rewrite mult_assoc_reverse. omega.\n  subst.\n  rewrite (lognat_odd _ H1) in H.\n  rewrite <- (lognat_prod_sum n) in H.\n  inversion H.\n  subst. \n  assert (lognat n = lognat n). trivial.\n  specialize (IHa' x b n pf2 H2 H0).\n\n  generalize pf3.\n  assert (S (2 * x) * b = b + 2 * x * b). intuition.\n  rewrite H4.\n  intros. \n  eapply le_trans.\n  Focus 2.\n  eapply (lognat_monotonic H3). intuition.\n  generalize H3.\n  rewrite mult_assoc_reverse.\n  intros. \n  rewrite <- (lognat_prod_sum H2).\n  omega.\nQed.\n\nTheorem lognat_prod_sum_gen : forall (a b: nat)(pf1 : (a <> 0))(pf2 : (b <> 0))(pf3 : a * b <> 0), \n  lognat pf1 + lognat pf2 <= lognat pf3.\n\n  intros.\n  eapply lognat_prod_sum_gen_h.\n  eauto.\nQed.\n\nLemma lognat_0_1 : forall n (pf : n <> 0),\n  lognat pf = 0 -> n = 1.\n\n  intros. \n  destruct n.\n  omega.\n  \n  destruct n.\n  trivial.\n\n  assert (2 <> 0). omega.\n  assert (lognat pf >= lognat H0).\n  eapply lognat_ge_monotonic.\n  omega. \n\n  unfold lognat in *.\n  simpl in *.\n  omega.\nQed.\n\nLemma lognat_succ_h : forall a n (pf1 : n <> 0)(pf2: (S n) <> 0),\n  a = lognat pf1 -> \n    lognat pf2 = a \\/\n    lognat pf2 = S (a).\n\n  induction a; intros. \n  assert (n = 1). \n  apply (lognat_0_1 pf1).\n  auto.\n  subst. \n  unfold lognat.\n  simpl. \n  auto.\n\n  destruct (nat_comp n).\n  destruct H0.\n  subst. \n  assert (x <> 0). omega.\n  rewrite <- (lognat_prod_sum H0) in H.\n  inversion H.\n  subst. \n  rewrite (lognat_odd _ pf1).\n  rewrite <- (lognat_prod_sum H0).\n  auto.\n\n  subst.\n  destruct (eq_nat_dec x 0).\n  subst. \n  unfold lognat in *.\n  simpl in *.\n  omega. \n\n  generalize pf2.\n  assert (S (S (2 * x)) = 2 * (S x)). omega.\n  rewrite H0.\n  intros. \n  assert (S x <> 0). omega. \n  assert (2 * x <> 0). omega.\n  rewrite (lognat_odd _ H2) in H.\n  rewrite <- (lognat_prod_sum n) in H.\n  inversion H.\n  rewrite <- (lognat_prod_sum H1).\n  specialize (IHa x n H1 H4). \n  destruct IHa.\n  subst. \n  rewrite H4.\n  auto.\n  subst. \n  right.\n  rewrite H3.\n  auto.\n\nQed.\n\nLemma lognat_succ : forall n (pf1 : n <> 0)(pf2: (S n) <> 0),\n  lognat pf2 = lognat pf1 \\/\n  lognat pf2 = S (lognat pf1).\n\n  intros.\n  eapply lognat_succ_h.\n  eauto.\nQed.\n\nLemma logn_ge_1 : forall n (pf : n <> 0),\n  n > 1 -> lognat pf >= 1.\n\n  intros. \n  destruct n.\n  congruence.\n  \n  destruct n.\n  omega.\n\n  assert (2 <> 0).\n  omega.\n\n  assert (forall n (pf1 : S (S n) <> 0)(pf2 : 2 <> 0), lognat pf1 >= lognat pf2).\n  intros.\n  eapply lognat_ge_monotonic.\n  omega.\n\n  assert (forall (pf : 2 <> 0), 1 = lognat pf).\n  intros. \n  unfold lognat. \n  auto.\n\n  rewrite (H2 H0).\n  eauto.\n\nQed.", "meta": {"author": "FreeAndFair", "repo": "RLA", "sha": "4295e4bb700ebbfe69affeb35dda7ed42273c3a1", "save_path": "github-repos/coq/FreeAndFair-RLA", "path": "github-repos/coq/FreeAndFair-RLA/RLA-4295e4bb700ebbfe69affeb35dda7ed42273c3a1/src/fcf/Lognat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7281565656335034}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nTheorem append_nil: forall (l: Lst), append l nil = l.\nProof.\n  induction l.\n  { simpl. f_equal. assumption. }\n  { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n  forall (l1 l2 l3: Lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n  induction l1; induction l2; induction l3; try (simpl; reflexivity).\n  { simpl. rewrite <- IHl1. f_equal. }\n  { simpl. rewrite 2 append_nil. reflexivity. }\n  { simpl. rewrite append_nil.  reflexivity. }\n  { simpl. rewrite 2 append_nil. reflexivity. }\nQed.\n\nTheorem append_rev_cons:\n  forall (l1 l2: Lst) (x: Nat),\n    rev (append l1 (cons x l2)) = append (rev l2) (cons x (rev l1)).\nProof.\n  induction l1; induction l2; try (simpl; reflexivity).\n  { intro. simpl. rewrite IHl1. simpl. rewrite <- append_assoc.\n    f_equal. }\n  { intro. simpl. rewrite IHl1. simpl. reflexivity. }\nQed.\n\nTheorem rev_append: forall (l1 l2: Lst), rev (append l1 l2) = append (rev l2) (rev l1).\nProof.\n  induction l1.\n  { induction l2.\n    { simpl. rewrite append_rev_cons.\n      rewrite <- 2 append_assoc.\n      f_equal. }\n    { simpl. rewrite append_nil. reflexivity. }\n  }\n  { intro. simpl. rewrite append_nil. reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : Lst), eq (rev (rev x)) x.\nProof.\n  induction x.\n  { simpl. rewrite rev_append. simpl. f_equal.\n    assumption. }\n  { simpl. reflexivity. }\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7281565645283665}}
{"text": "Require Import Arith.\n\nFixpoint sum_odd(n:nat) : nat :=\n  match n with\n    | O => O\n    | S m => 1 + m + m + sum_odd m\n  end.\n\nGoal forall n, sum_odd n = n * n.\nProof.\n  intros.\n  induction n.\n  reflexivity.\n  simpl.\n  rewrite IHn.\n  ring.\nQed.\n", "meta": {"author": "kitayuta", "repo": "CoqEx2014", "sha": "ed9e347270aaed9872b4ebc50ab44a7c1e7ea24c", "save_path": "github-repos/coq/kitayuta-CoqEx2014", "path": "github-repos/coq/kitayuta-CoqEx2014/CoqEx2014-ed9e347270aaed9872b4ebc50ab44a7c1e7ea24c/Ex3/11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.7281166855145051}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export Omega.\nRequire Export Zwf.\n\nLtac caseEq f := generalize (refl_equal f); pattern f at -1; case f.\n\n(* taken from chapter 5 *)\n\nInductive plane : Set :=\n    point : Z->Z->plane.\n\nInductive htree (A:Set) : nat->Set :=\n  | hleaf : A -> htree A 0%nat\n  | hnode : forall n:nat, A -> htree A n -> htree A n -> htree A (S n).\n\nInductive south_west : plane->plane->Prop :=\n  south_west_def :\n  forall a1 a2 b1 b2:Z, (a1 <= b1)%Z -> (a2 <= b2)%Z -> \n        south_west (point a1 a2)(point b1 b2).\n\nInductive even : nat->Prop :=\n  | O_even : even 0\n  | plus_2_even : forall n:nat, even n -> even (S (S n)).\n\nInductive sorted (A:Set)(R:A->A->Prop) : list A -> Prop :=\n  | sorted0 : sorted A R nil\n  | sorted1 : forall x:A, sorted A R (cons x nil)\n  | sorted2 :\n      forall (x y:A)(l:list A),\n        R x y ->\n        sorted A R (cons y l)-> sorted A R (cons x (cons y l)).\n\nImplicit Arguments sorted [A].\nHint Resolve sorted0 sorted1 sorted2 : sorted_base.\n\nRequire Export Relations.\n\n\nInductive clos_trans (A:Type)(R:relation A) : A->A->Prop :=\n  | t_step : forall x y:A, R x y -> clos_trans A R x y\n  | t_trans :\n    forall x y z:A, clos_trans A R x y -> clos_trans A R y z -> \n        clos_trans A R x z.\n\n\nTheorem sorted_nat_123 : sorted le (1::2::3::nil).\nProof.\n auto with sorted_base arith.\nQed.\n\nTheorem xy_ord :\n forall x y:nat, le x y -> sorted  le (x::y::nil).\nProof.\n auto with sorted_base.\nQed.\n\nTheorem zero_cons_ord :\n forall l:list nat, sorted le l -> sorted le (cons 0 l).\nProof.\n induction 1; auto with sorted_base arith.\nQed.\n\nTheorem sorted1_inv :\n forall (A:Set)(le:A->A->Prop)(x:A)(l:list A),\n   sorted  le (cons x l)-> sorted  le l.\nProof.\n inversion 1; auto with sorted_base.\nQed.\n\nTheorem sorted2_inv :\n forall (A:Set)(le:A->A->Prop)(x y:A)(l:list A),\n   sorted  le (cons x (cons y l))-> le x y.\nProof.\n inversion 1; auto with sorted_base.\nQed.\n\nTheorem not_sorted_132 :  ~ sorted le (1::3::2::nil).\nProof.\n intros H;assert (H1:sorted le (3::2::nil)).\n apply sorted1_inv with (1:= H).\n assert (H2 : 3<=2).\n apply sorted2_inv with (1:= H1).\n omega.\nQed.\n\nCheck True_ind.\n\nCheck False_ind.\n\nCheck and_ind.\n\nCheck or_ind.\n\nCheck ex_ind.\n\nCheck eq_ind.\n\nRequire Import JMeq.\n\nCheck JMeq_eq.\n\nCheck JMeq_ind.\n\n\nInductive ahtree : Set :=\n  any_height : forall n:nat, htree nat n -> ahtree.\n\nTheorem any_height_inj2 :\n forall (n1 n2:nat)(t1:htree nat n1)(t2:htree nat n2),\n   any_height n1 t1 = any_height n2 t2 -> JMeq t1 t2.\nProof.\n intros n1 n2 t1 t2 H.\n injection H.\n intros H1 H2.\n dependent rewrite <- H1.\n simpl.\n Undo 4.\n change (match any_height n2 t2 with\n        | any_height n t => JMeq t1 t\n        end);\n   rewrite <- H.\n auto.\nQed.\n\nRequire Import Bvector.\nRequire Import List.\n\nSection vectors_and_lists.\n Variable A : Set.\n Fixpoint vector_to_list (n:nat)(v:vector A n){struct v} \n  : list A :=\n  match v with\n  | Vnil => nil \n  | Vcons a p tl => cons a (vector_to_list p tl)\n  end.\n\n Fixpoint list_to_vector (l:list A) : vector A (length l) :=\n   match l as x return vector A (length x) with\n   | nil => Vnil A\n   | cons a tl => Vcons A a (length tl)(list_to_vector tl)\n   end.\n\n Theorem keep_length :\n  forall (n:nat)(v:vector A n), length (vector_to_list n v) = n.\n Proof.\n   intros n v; elim v; simpl; auto.\n Qed.\n\n Lemma Vconseq :\n  forall (a:A)(n m:nat),\n   n = m ->\n   forall (v:vector A n)(w:vector A m),\n     JMeq v w -> JMeq (Vcons A a n v)(Vcons A a m w).\n Proof.\n  intros a n m Heq; rewrite Heq.\n  intros v w HJeq.\n  elim HJeq; reflexivity.\n Qed. \n\n Theorem vect_to_list_and_back :\n  forall n (v:vector A n),\n    JMeq v (list_to_vector (vector_to_list n v)).\n Proof.\n  intros n v; elim v.\n  simpl; auto.\n  intros a n' v' HJeq.\n  simpl.\n  apply Vconseq.\n  symmetry; apply keep_length.\n  assumption.\n Qed.\n\nEnd vectors_and_lists.\n\nTheorem structured_intro_example1 : forall A B C:Prop, A/\\B/\\C->A.\nProof.\n intros A B C [Ha [Hb Hc]].\n auto.\nQed.\n\nTheorem structured_intro_example2 : forall A B:Prop, A \\/ B/\\(B->A)->A.\nProof.\n intros A B [Ha | [Hb Hi]].\n auto.\n auto.\nQed.\n\nTheorem sum_even : forall n p:nat, even n -> even p -> even (n+p).\nProof.\n intros n; elim n.\n auto.\n intros n' Hrec p Heven_Sn' Heven_p.\nRestart.\n intros n p Heven_n; elim Heven_n.\n trivial.\n intros x Heven_x Hrec Heven_p; simpl.\n apply plus_2_even; auto.\nQed.\n\nCheck le_ind.\n\nTheorem lt_le : forall n p:nat, n < p -> n <= p.\nProof.\n intros n p H; elim H; repeat constructor; assumption.\nQed.\n\n\nOpen Scope Z_scope.\nInductive Pfact : Z->Z->Prop :=\n  Pfact0 : Pfact 0 1\n| Pfact1 : forall n v:Z, n <> 0 -> Pfact (n-1) v -> Pfact n (n*v).\n\nTheorem pfact3 : Pfact 3 6.\nProof.\n apply Pfact1 with (n := 3)(v := 2).\n discriminate.\n apply (Pfact1 2 1).\n discriminate.\n apply (Pfact1 1 1).\n discriminate.\n apply Pfact0.\nQed.\n \nTheorem fact_def_pos : forall x y:Z, Pfact x y ->  0 <= x.\nProof.\n intros x y H; elim H.\n auto with zarith.\n intros n v Hneq0 HPfact Hrec.\n omega.\nQed.\n\nCheck Zwf_well_founded. \n\nCheck well_founded_ind. \n\nTheorem Zle_Pfact : forall x:Z, 0 <= x -> exists y:Z, Pfact x y.\nProof.\n intros x0.\n elim x0 using (well_founded_ind (Zwf_well_founded 0)).\n intros x Hrec Hle.\n  elim (Zle_lt_or_eq  _ _ Hle).\n 2:intros Heq; rewrite <- Heq; exists 1; constructor.\n intro Hlt; elim (Hrec (x-1)).\n intros x1 Hfact; exists (x*x1); apply Pfact1; auto with zarith.\n unfold Zwf; omega.\n omega.\nQed.\n\nSection little_semantics.\n Variables Var aExp bExp : Set.\n Inductive inst : Set :=\n | Skip : inst\n | Assign : Var->aExp->inst\n | Sequence : inst->inst->inst\n | WhileDo : bExp->inst->inst.\n\n Variables\n  (state : Set)\n  (update : state->Var->Z -> option state)\n  (evalA : state->aExp -> option Z)\n  (evalB : state->bExp -> option bool).\n\n Inductive exec : state->inst->state->Prop :=\n | execSkip : forall s:state, exec s Skip s\n | execAssign :\n    forall (s s1:state)(v:Var)(n:Z)(a:aExp),\n     evalA s a = Some n -> update s v n = Some s1 ->\n     exec s (Assign v a) s1\n | execSequence :\n    forall (s s1 s2:state)(i1 i2:inst),\n     exec s i1 s1 -> exec s1 i2 s2 ->\n     exec s (Sequence i1 i2) s2\n | execWhileFalse :\n    forall (s:state)(i:inst)(e:bExp),\n     evalB s e = Some false -> exec s (WhileDo e i) s\n | execWhileTrue :\n    forall (s s1 s2:state)(i:inst)(e:bExp),\n     evalB s e = Some true ->\n     exec s i s1 ->\n     exec s1 (WhileDo e i) s2 ->\n     exec s (WhileDo e i) s2.\n\n Theorem HoareWhileRule :\n  forall (P:state->Prop)(b:bExp)(i:inst)(s s':state),\n    (forall s1 s2:state,\n      P s1 -> evalB s1 b = Some true -> exec s1 i s2 -> P s2)->\n    P s -> exec s (WhileDo b i) s' ->\n    P s' /\\ evalB s' b = Some false.\n Proof.\n  intros P b i s s' H Hp Hexec; elim Hexec.\n Restart.\n  intros P b i s s' H Hp Hexec; generalize H Hp; elim Hexec.\n Restart.\n  intros P b i s s' H.\n  cut\n   (forall i':inst,\n     exec s i' s' ->\n     i' = WhileDo b i -> P s -> P s' /\\ evalB s' b = Some false); \n   eauto.\n  intros i' Hexec; elim Hexec; try (intros; discriminate).\n  intros s0 i0 e Heval Heq; injection Heq; intros H1 H2.\n  match goal  with\n  | id:(e = b) |- _ => rewrite <- id; auto\n  end.\n  intros;\n   match goal with\n   | id:(_ = _) |- _ => injection id; intros H' H''\n   end.\n    subst i0 b;eauto.\n Qed.\n\nEnd little_semantics.\n\nOpen Scope nat_scope.\n\nInductive is_0_1 : nat->Prop :=\n  is_0 : is_0_1 0 | is_1 : is_0_1 1.\n\nHint Resolve is_0 is_1 .\n\nLemma sqr_01 : forall x:nat, is_0_1 x -> is_0_1 (mult x x).\nProof.\n  induction 1; simpl; auto.\nQed.\n\nTheorem elim_example : forall n:nat, n <= 1 -> n*n <= 1.\nProof.\n intros n H.\n elim sqr_01.\n auto.\n auto.\n inversion_clear H; auto.\n inversion_clear H0; auto.\nQed.\n\nPrint even.\n\nSection bad_proof_for_inversion.\n\n Theorem not_1_even : ~even 1.\n Proof.\n  red; intros H; elim H.\n Abort.\n\nEnd bad_proof_for_inversion.\n\nTheorem not_even_1 : ~even 1.\nProof.\n unfold not; intros H.\n inversion H.\nQed.\n\nTheorem plus_2_even_inv : forall n:nat, even (S (S n))-> even n.\nProof.\n intros n H; inversion H.\n assumption.\nQed.\n\nTheorem not_even_1' : ~even 1.\nProof.\n intro H.\n generalize (refl_equal 1).\n pattern 1 at -2.\n elim H.\n discriminate.\n discriminate 3.\nQed.\n\nTheorem plus_2_even_inv' : forall n:nat, even (S (S n))-> even n.\nProof.\n intros n H.\n generalize (refl_equal (S (S n))); pattern (S (S n)) at -2.\n elim H.\n intros H1; discriminate H1.\n intros n0 H'0 H' H'1.\n injection H'1; intros H'2; rewrite <- H'2; assumption.\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/Tsinghua Coq Summer School/booksite83-export/inductive-prop-chap/SRC/chap8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8397339756938819, "lm_q1q2_score": 0.7280793856474425}}
{"text": "Require Import Domino List.\nImport ListNotations.\n\nCreate HintDb disjoints_hints.\n\n(** des dominos sont « disjoints » s'ils ne recouvrent pas de case en commun *)\nDefinition disjoints2_dominos (d1 d2:domino) :=\n  match d1, d2 with\n  | Hauteur c1, Hauteur c2 =>\n              c1 <> c2 /\\\n      dessous c1 <> c2 /\\\n              c1 <> dessous c2 /\\\n      dessous c1 <> dessous c2\n  | Largeur c1, Largeur c2 =>\n              c1 <> c2 /\\\n       droite c1 <> c2 /\\\n              c1 <> droite c2 /\\\n       droite c1 <> droite c2\n  | Hauteur c1, Largeur c2\n  | Largeur c2, Hauteur c1 =>\n              c1 <> c2 /\\\n              c1 <> droite c2 /\\\n      dessous c1 <> c2 /\\\n      dessous c1 <> droite c2\n  end.\n\nInfix \"#\" := (fun a b => disjoints2_dominos a b) (at level 32, left associativity).\n\n(** déduction de la commutativité de [pose_domino] *)\nFixpoint disjoints_dominos_l (d : domino) (dl : list domino) :=\n  match dl with\n  | [] => True\n  | h :: t => disjoints2_dominos d h /\\ disjoints_dominos_l d t\n  end.\n\nInfix \"##\" := (fun a b => disjoints_dominos_l a b) (at level 33, left associativity).\n\nFixpoint disjoints_dominos_lo_aux (d : domino) (dl : list domino) :=\n  match dl with\n  | [] => True\n  | h::t => (d # h /\\ disjoints_dominos_lo_aux d t)\n  end.\n\nFixpoint disjoints_dominos (dl : list domino) :=\n  match dl with\n  | [] => True\n  | h::t => disjoints_dominos_lo_aux h t /\\ disjoints_dominos t\n  end.\n\n(*****************************************************************************************)\n(****************************** { Lemmes sur \"disjoints\" } *******************************)\n(*****************************************************************************************)\n\nLemma simp_disjlo0 : disjoints_dominos [].\nProof.\n  unfold disjoints_dominos.\n  simpl.\n  auto.\nQed.\n\n#[local]\nHint Resolve simp_disjlo0 : disjoints_hints.\n\nLemma simp_disjlo0b : forall d, d ## [].\nProof.\n  simpl.\n  auto.\nQed.\n\n#[local]\nHint Resolve simp_disjlo0b : disjoints_hints.\n\nLemma rw_util_disj : forall a d, d ## [a] <-> d # a.\nProof.\n  split.\n  - intros H.\n    case d, a;\n    split;\n    try\n     (destruct H;\n      destruct H;\n      assumption).\n  - intros H.\n    case d, a;\n    cbv;\n    auto.\nQed.\n\n#[local]\nHint Resolve simp_disjlo0b : disjoints_hints.\n\nLemma simp_disjlo1 :\n  forall d dl,\n  disjoints_dominos (d :: dl) ->\n  disjoints_dominos dl.\nProof.\n  intros d dl.\n  revert d.\n  induction dl.\n  - intros. apply simp_disjlo0.\n  - intros d H.\n    unfold disjoints_dominos in H.\n    unfold disjoints_dominos.\n    destruct H.\n    destruct H0.\n    split; assumption.\nQed.\n\n#[local]\nHint Resolve simp_disjlo1 : disjoints_hints.\n\nLemma simp_disjlo2 :\n  forall d dl,\n  disjoints_dominos (d :: dl) ->\n  d ## dl.\nProof.\n  intros d dl H.\n  destruct dl.\n  { auto with disjoints_hints. }\n  { destruct H.\n    split;\n    unfold disjoints_dominos_lo_aux in H;\n    destruct H;\n    assumption. }\nQed.\n\n#[local]\nHint Resolve simp_disjlo2 : disjoints_hints.\n", "meta": {"author": "paulpatault", "repo": "mutilated-chessboard", "sha": "5823802d0412d95fa7a896aadd08874145dc533a", "save_path": "github-repos/coq/paulpatault-mutilated-chessboard", "path": "github-repos/coq/paulpatault-mutilated-chessboard/mutilated-chessboard-5823802d0412d95fa7a896aadd08874145dc533a/src/Disjoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8397339596505965, "lm_q1q2_score": 0.7280793717373403}}
{"text": "Add LoadPath \"$COQ_PROOFS\" as Path.\nLoad unit_1_008_rewriting.\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  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem andb_commutative: forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem andb_commutative' : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  { destruct c.\n    { reflexivity. }\n    { reflexivity. } }\n  { destruct c.\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.\n  - destruct c.\n  {\n    destruct d.\n    - reflexivity.\n    - reflexivity.\n  }\n  {\n    destruct d.\n    - reflexivity.\n    - reflexivity.\n  }\n  - destruct c.\n  {\n    destruct d.\n    - reflexivity.\n    - reflexivity.\n  }\n  {\n    destruct d.\n    - reflexivity.\n    - reflexivity.\n  }\nQed.\n\nTheorem plus_1_neq_0' : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity. Qed.\n\nLemma minus_n_O : forall n : nat, n = n - 0.\nProof.\n  intros [|n].\n  {\n    reflexivity.\n  }\n  {\n    reflexivity.\n  }\nQed.\n\nLemma n_plus_0_same_n : forall n : nat, 0 + n = n + 0.\nProof.\n  intros.\n  Admitted.\n\nLemma plus_n_O : forall n : nat, n = n + 0.\nProof.\n  intros [|n].\n  {\n    reflexivity.\n  }\n  {\n    simpl. rewrite <- n_plus_0_same_n. reflexivity.\n  }\nQed.\n\nFixpoint beq_bool (n m: bool) : bool :=\n  match n with\n  | true => match m with\n    | true => true\n    | false => false\n    end\n  | false => match m with\n    | true => false\n    | false => true\n    end\n  end.\n\nTheorem andb_true_elim2: forall b c: bool,\n  andb b c = true -> b = true.\nProof.\n  intros.\n  destruct b.\n  - reflexivity.\n  - rewrite <- H. reflexivity.\nQed.\n\n\nTheorem andb_true_elim2': forall b c: bool,\n  andb b c = true -> c = true.\nProof.\n  intros.\n  destruct c.\n  - rewrite <- H. simpl. reflexivity.\n  - rewrite <- H. rewrite <- andb_commutative. reflexivity.\nQed.  \n\n\nTheorem andb_true_elim2'': forall b c: bool,\n  andb b c = true -> c = true.\nProof.\n  intros.\n  destruct b.\n  - rewrite <- H. simpl. reflexivity.\n  - rewrite <- H. inversion H.\nQed.\n\nDefinition nandb (b1: bool) (b2: bool) : bool :=\n  negb (andb b1 b2).\n\nTheorem nandb__negb_andb : forall b1 b2 : bool,\n    nandb b1 b2 = negb (andb b1 b2).\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nDefinition impb (b1: bool) (b2: bool) : bool :=\n  orb (negb b1) b2.\n\nTheorem impb_spec : forall b1 b2 : bool,\n  impb b1 b2 = orb (negb b1) b2.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem impb_spec' : forall b1 b2 : bool,\n  impb b1 b2 = orb (negb b1) b2.\nProof.\n  intros. destruct b1.\n  - destruct b2. reflexivity. reflexivity.\n  - destruct b2. reflexivity. reflexivity.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  intros. simpl. destruct n.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\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. rewrite -> H. rewrite -> H. reflexivity.\nQed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros.\n  destruct b.\n  - simpl in H. rewrite -> H. reflexivity.\n  - simpl in H. rewrite -> H. reflexivity.\nQed.\n\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_1_009_case_analysis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8670357546485408, "lm_q1q2_score": 0.7280793674096622}}
{"text": "Require Import Coq.Init.Decimal.\nRequire Import Coq.ZArith.ZArith.\n\nInductive positive : Set :=\n    xI : positive -> positive | xO : positive -> positive | xH : positive.\n\nDeclare Scope local_scope.\nOpen Scope  local_scope.\n\nNotation \"p ~ 1\" := (xI p)\n (at level 7, left associativity, format \"p '~' '1'\") : local_scope.\nNotation \"p ~ 0\" := (xO p)\n (at level 7, left associativity, format \"p '~' '0'\") : local_scope.\n\nDefinition succ := \nfix succ (x : positive) : positive :=\n  match x with\n  | (p~1) => ((succ p)~0)\n  | (p~0) => (p~1)\n  | xH => xH~0\n  end.\n\nFixpoint add x y :=\n  match x, y with\n    | p~1, q~1 => (add_carry p q)~0\n    | p~1, q~0 => (add p q)~1\n    | p~1, xH => (succ p)~0\n    | p~0, q~1 => (add p q)~1\n    | p~0, q~0 => (add p q)~0\n    | p~0, xH => p~1\n    | xH, q~1 => (succ q)~0\n    | xH, q~0 => q~1\n    | xH, xH => xH~0\n  end\n\nwith add_carry x y :=\n  match x, y with\n    | p~1, q~1 => (add_carry p q)~1\n    | p~1, q~0 => (add_carry p q)~0\n    | p~1, xH => (succ p)~1\n    | p~0, q~1 => (add_carry p q)~0\n    | p~0, q~0 => (add p q)~1\n    | p~0, xH => (succ p)~0\n    | xH, q~1 => (succ q)~1\n    | xH, q~0 => (succ q)~0\n    | xH, xH => xH~1\n  end.\n\nDefinition mul := \nfix mul (x y : positive) {struct x} : positive :=\n  match x with\n  | (p~1) => add y (mul p y)~0\n  | (p~0) => ((mul p y)~0)\n  | xH => y\n  end.\n\nInductive N :=\n| O : N\n| N_pos : positive -> N.\n\nDefinition N_succ(n:N) : N :=\n  match n with\n   | O => N_pos xH\n   | N_pos p => N_pos (succ p)\n  end.\n\nDefinition N_add(n m:N) : N :=\n  match n, m with\n   |O, m => m\n   |n, O => n\n   |N_pos p, N_pos q => N_pos (add p q)\n  end.\n\nDefinition N_mul(n m:N) : N :=\n  match n, m with\n   |O, _ => O\n   |_, O => O\n   |N_pos p, N_pos q => N_pos (mul p q)\n  end.\n\nInfix \"+\" := N_add : local_scope.\nInfix \"*\" := N_mul : local_scope.\n\n\n\nDefinition one := N_pos xH.\nDefinition two := N_pos xH~0.\nDefinition three := N_pos xH~1.\nDefinition four := N_pos xH~0~0.\nDefinition five := N_pos xH~0~1.\nDefinition six := N_pos xH~1~0.\nDefinition seven := N_pos xH~1~1.\nDefinition eight := N_pos xH~0~0~0.\nDefinition nine := N_pos xH~0~0~1.\nDefinition ten := N_pos xH~0~1~0.\nDefinition eleven := N_pos xH~0~1~1.\nDefinition twelve := N_pos xH~1~0~0.\nDefinition thirteen := N_pos xH~1~0~1.\nDefinition fourteen := N_pos xH~1~1~0.\nDefinition fifteen := N_pos xH~1~1~1.\nDefinition sixteen := N_pos xH~0~0~0~0.\n\nFixpoint N_uparse_rev (u:Decimal.uint) : N :=\nmatch u with\n  |Nil => O\n  |D0 k => ten * N_uparse_rev k\n  |D1 k => one + ten * N_uparse_rev k\n  |D2 k => two + ten * N_uparse_rev k\n  |D3 k => three + ten * N_uparse_rev k\n  |D4 k => four + ten * N_uparse_rev k\n  |D5 k => five + ten * N_uparse_rev k\n  |D6 k => six + ten * N_uparse_rev k\n  |D7 k => seven + ten * N_uparse_rev k\n  |D8 k => eight + ten * N_uparse_rev k\n  |D9 k => nine + ten * N_uparse_rev k\nend.\n\nDefinition N_uparse (n:Decimal.uint) : N := N_uparse_rev (rev n).\n\nPrint Hexadecimal.uint.\n\nFixpoint N_uhparse_rev (u:Hexadecimal.uint) : N :=\nmatch u with\n  |Hexadecimal.Nil => O\n  |Hexadecimal.D0 k => sixteen * N_uhparse_rev k\n  |Hexadecimal.D1 k => one + sixteen * N_uhparse_rev k\n  |Hexadecimal.D2 k => two + sixteen * N_uhparse_rev k\n  |Hexadecimal.D3 k => three + sixteen * N_uhparse_rev k\n  |Hexadecimal.D4 k => four + sixteen * N_uhparse_rev k\n  |Hexadecimal.D5 k => five + sixteen * N_uhparse_rev k\n  |Hexadecimal.D6 k => six + sixteen * N_uhparse_rev k\n  |Hexadecimal.D7 k => seven + sixteen * N_uhparse_rev k\n  |Hexadecimal.D8 k => eight + sixteen * N_uhparse_rev k\n  |Hexadecimal.D9 k => nine + sixteen * N_uhparse_rev k\n  |Hexadecimal.Da k => ten + sixteen * N_uhparse_rev k\n  |Hexadecimal.Db k => eleven + sixteen * N_uhparse_rev k\n  |Hexadecimal.Dc k => twelve + sixteen * N_uhparse_rev k\n  |Hexadecimal.Dd k => thirteen + sixteen * N_uhparse_rev k\n  |Hexadecimal.De k => fourteen + sixteen * N_uhparse_rev k\n  |Hexadecimal.Df k => fifteen + sixteen * N_uhparse_rev k\nend.\n\nDefinition N_uhparse (n:Hexadecimal.uint) : N := N_uhparse_rev (Hexadecimal.rev n).\n\nDefinition N_parse (n:Number.int) : option N :=\n  match n with\n   |Number.IntDecimal d => match d with\n                     |Decimal.Pos u => Some (N_uparse u)\n                     |Decimal.Neg u => None\n                    end\n   |Number.IntHexadecimal h => match h with\n                     |Hexadecimal.Pos u => Some (N_uhparse u)\n                     |Hexadecimal.Neg u => None\n                    end\n  end.\n\n\nFixpoint pos_for_pos(p:positive) : BinNums.positive :=\n match p with\n |xH => BinNums.xH\n |p~0 => BinNums.xO (pos_for_pos p)\n |p~1 => BinNums.xI (pos_for_pos p)\n end.\n\nDefinition N_print (n:N) : Z :=\n match n with\n  | O => Z0\n  | N_pos p => Zpos (pos_for_pos p)\n end.\n\nNumber Notation N N_parse N_print : local_scope.\n\nExample q : ((14 * 13) + (12 * 11)) = 314.\ncompute.\ntrivial.\nDefined.\n\nExample q2 : ((fourteen * thirteen) + (twelve * eleven)) = 314.\ncompute.\ntrivial.\nDefined.\n\nLemma add_one : forall n:positive, (succ n) = (add n xH).\ndestruct n.\nall: simpl.\nall: trivial.\nDefined.\n\nLemma carry_one : forall n m:positive, (add_carry n m) = (add n (succ m)).\ninduction n.\nall: induction m.\nall: simpl.\nall: try rewrite IHn.\nall: try rewrite add_one.\nall: try easy.\nDefined.\n\nLemma ringer_pos : forall n m:positive, succ (add n m) = add n (succ m).\ninduction n.\nall: induction m.\nall: simpl.\nall: try rewrite add_one.\nall: try trivial.\n3: rewrite <- IHn.\n3: rewrite add_one.\n3: trivial.\nall: try rewrite <- add_one.\nall: try rewrite carry_one.\ntrivial.\nrewrite IHn.\ntrivial.\nDefined.\n\nTheorem ringer : forall n m:N, N_succ (n + m) = n + (N_succ m).\nintros.\ndestruct n.\nall: destruct m.\nall: simpl.\nall: try trivial.\nall: try rewrite <- add_one.\ntrivial.\nrewrite ringer_pos.\ntrivial.\nDefined.\n", "meta": {"author": "bowtochris", "repo": "CoqStuff", "sha": "80ffef00b18a23b85f66fcb5b198d2730a49a362", "save_path": "github-repos/coq/bowtochris-CoqStuff", "path": "github-repos/coq/bowtochris-CoqStuff/CoqStuff-80ffef00b18a23b85f66fcb5b198d2730a49a362/ringer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7280694135845106}}
{"text": "From mathcomp Require Import ssreflect.\nRequire Import Classical.\nRequire Import Coq.Logic.Description.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.Sets.Finite_sets.\nRequire Import Coq.Sets.Finite_sets_facts.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Arith.Le.\nRequire Import Coq.Arith.Lt.\n\nDefinition is_max_nat := fun (E : (Ensemble nat)) (m : nat) => (In nat E m) /\\ forall x : nat, (In nat E x) -> (x <= m)%nat.\n\nDefinition is_min_nat := fun (E : (Ensemble nat)) (m : nat) => (In nat E m) /\\ forall x : nat, (In nat E x) -> (x >= m)%nat.\n\nLemma is_max_nat_unique : forall (E : (Ensemble nat)) (m1 m2 : nat), is_max_nat E m1 -> is_max_nat E m2 -> m1 = m2.\nProof.\nmove=> E m1 m2 H1 H2.\napply (le_antisym m1 m2).\napply (proj2 H2 m1 (proj1 H1)).\napply (proj2 H1 m2 (proj1 H2)).\nQed.\n\nLemma is_min_nat_unique : forall (E : (Ensemble nat)) (m1 m2 : nat), is_min_nat E m1 -> is_min_nat E m2 -> m1 = m2.\nProof.\nmove=> E m1 m2 H1 H2.\napply (le_antisym m1 m2).\napply (proj2 H1 m2 (proj1 H2)).\napply (proj2 H2 m1 (proj1 H1)).\nQed.\n\nLemma nat_cardinal : forall (n : nat) , cardinal nat (fun x : nat => (x < n)%nat) n.\nProof.\nmove=> n.\nelim n.\nsuff: (fun x : nat => (x < 0)%nat) = (Empty_set nat).\nmove=> H1.\nrewrite H1.\napply (card_empty nat).\napply (Extensionality_Ensembles nat (fun x : nat => (x < 0)%nat) (Empty_set nat)).\napply conj.\nmove=> m H1.\napply False_ind.\napply (le_not_lt 0 m).\napply (le_O_n m).\napply H1.\nmove=> m.\nelim.\nmove=> n0 H1.\nsuff: (Add nat (fun x : nat => (x < n0)%nat) n0) = (fun x : nat => (x < S n0)%nat).\nmove=> H2.\nrewrite - H2.\napply (card_add nat (fun x : nat => (x < n0)%nat) n0 H1 n0).\nmove=> H3.\napply (le_Sn_n n0 H3).\napply (Extensionality_Ensembles nat (Add nat (fun x : nat => (x < n0)%nat) n0) (fun x : nat => (x < S n0)%nat)).\napply conj.\nmove=> x.\nelim.\nmove=> x0 H2.\napply (lt_trans x0 n0 (S n0)).\napply H2.\nby [].\nmove=> x0 H2.\nrewrite H2.\nby [].\nmove=> x H2.\nelim (le_lt_or_eq (S x) (S n0)).\nmove=> H3.\napply (Union_introl nat (fun x0 : nat => (x0 < n0)%nat) (Singleton nat n0) x).\napply (lt_S_n x n0 H3).\nmove=> H3.\napply (Union_intror nat (fun x0 : nat => (x0 < n0)%nat) (Singleton nat n0) x).\nrewrite - (Nat.pred_succ n0).\nrewrite - (Nat.pred_succ x).\nrewrite H3.\nby [].\napply H2.\nQed.\n\nLemma Finite_max_nat_exist : forall (U : Ensemble nat), (Finite nat U) -> (Inhabited nat U) -> exists m : nat, (is_max_nat U m).\nProof.\nmove=> U H1.\nelim H1.\nmove=> H2.\napply False_ind.\nelim H2.\nmove=> x H3.\nelim H3.\nmove=> A H2 H3 x H4 H5.\nmove: H3.\nelim H2.\nexists x.\napply conj.\napply (Union_intror nat (Empty_set nat) (Singleton nat x) x).\napply (In_singleton nat x).\nmove=> x0.\nelim.\nmove=> x1.\nelim.\nmove=> x1.\nelim.\nby [].\nmove=> A0 H6 H7 x0 H8.\nelim.\nmove=> x1.\nmove=> H9.\nexists (max x x1).\napply conj.\napply (Nat.max_case_strong x x1).\nmove=> H10.\napply (Union_intror nat (Add nat A0 x0) (Singleton nat x) x).\napply (In_singleton nat x).\nmove=> H10.\napply (Union_introl nat (Add nat A0 x0) (Singleton nat x) x1).\napply (proj1 H9).\nmove=> x2.\nelim.\nmove=> x3 H10.\napply (le_trans x3 x1 (Init.Nat.max x x1)).\napply (proj2 H9 x3 H10).\napply (Nat.le_max_r x x1).\nmove=> x3.\nelim.\napply (Nat.le_max_l x x1).\nexists x0.\napply (Union_intror nat A0 (Singleton nat x0) x0).\napply (In_singleton nat x0).\nQed.\n\nLemma min_nat_exist : forall (U : Ensemble nat), (Inhabited nat U) -> exists m : nat, (is_min_nat U m).\nProof.\nsuff: (forall (U : Ensemble nat), (Finite nat U) -> (Inhabited nat U) -> exists m : nat, (is_min_nat U m)).\nmove=> H1 U.\nelim.\nmove=> n H2.\nelim (classic (Inhabited nat (Intersection nat U (fun x:nat => (x < n)%nat)))).\nmove=> H3.\nelim (H1 (Intersection nat U (fun x : nat => (x < n)%nat))).\nmove=> x H4.\nexists x.\napply conj.\nelim (proj1 H4).\nmove=> y H5 H6.\napply H5.\nmove=> y.\nelim (le_or_lt n y).\nmove=> H5 H6.\napply (le_trans x n y).\napply (le_trans x (S x) n).\napply (le_S x).\napply (le_n x).\nelim (proj1 H4).\nmove=> y0 H7.\napply.\napply H5.\nmove=> H5 H6.\napply ((proj2 H4) y).\napply (Intersection_intro nat U (fun x0 : nat => (x0 < n)%nat) y H6).\napply H5.\nsuff: (Finite nat (fun x : nat => (x < n)%nat)).\nmove=> H4.\napply (Intersection_preserves_finite nat (fun x : nat => (x < n)%nat) H4 U).\napply (cardinal_finite nat (fun x : nat => (x < n)%nat) n (nat_cardinal n)).\napply H3.\nmove=> H3.\nexists n.\napply conj.\napply H2.\nmove=> x H4.\nelim (le_or_lt n x).\napply.\nmove=> H5.\napply False_ind.\napply H3.\napply (Inhabited_intro nat (Intersection nat U (fun x0 : nat => (x0 < n)%nat)) x).\napply (Intersection_intro nat U (fun x0 : nat => (x0 < n)%nat) x H4 H5).\nmove=> U H1.\nelim H1.\nmove=> H2.\napply False_ind.\nelim H2.\nmove=> x H3.\nelim H3.\nmove=> A H2 H3 x H4 H5.\nsuff: (Inhabited nat A -> exists m : nat, is_min_nat A m).\nelim H2.\nmove=> H6.\nexists x.\napply conj.\napply (Union_intror nat (Empty_set nat) (Singleton nat x) x).\napply (In_singleton nat x).\nmove=> x0.\nelim.\nmove=> x1.\nelim.\nmove=> x1.\nelim.\nby [].\nmove=> A0 H6 H7 x0 H8.\nelim.\nmove=> x1 H9.\nexists (min x x1).\napply conj.\napply (Nat.min_case_strong x x1).\nmove=> H10.\napply (Union_intror nat (Add nat A0 x0) (Singleton nat x) x).\napply (In_singleton nat x).\nmove=> H10.\napply (Union_introl nat (Add nat A0 x0) (Singleton nat x) x1).\napply (proj1 H9).\nmove=> x2.\nelim.\nmove=> x3 H10.\napply (le_trans (min x x1) x1 x3).\napply (Nat.le_min_r x x1).\napply (proj2 H9 x3 H10).\nmove=> x3.\nelim.\napply (Nat.le_min_l x x1).\nexists x0.\napply (Union_intror nat A0 (Singleton nat x0) x0).\napply (In_singleton nat x0).\napply H3.\nQed.\n\nLemma min_nat_get : forall (U : Ensemble nat), (Inhabited nat U) -> {m : nat | is_min_nat U m}.\nProof.\nmove=> U H1.\napply (constructive_definite_description (fun (m : nat) => is_min_nat U m)).\napply (proj1 (unique_existence (fun (m : nat) => is_min_nat U m))).\napply conj.\nelim (min_nat_exist U H1).\nmove=> n H2.\nexists n.\napply H2.\nunfold uniqueness.\napply (is_min_nat_unique U).\nQed.\n", "meta": {"author": "itleigns", "repo": "CoqLibrary", "sha": "de210b755ab010e835e3777b9b47351972bbb577", "save_path": "github-repos/coq/itleigns-CoqLibrary", "path": "github-repos/coq/itleigns-CoqLibrary/CoqLibrary-de210b755ab010e835e3777b9b47351972bbb577/BasicProperty/NatProperty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7280693988228008}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (z : natural) : natural :=\n  mult y (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj157_coqofml_3i8b4K.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7279483437778309}}
{"text": "Require Import SetoidClass.\n\n(* Standard Setoid Instances *)\n\n(* Pointwise equivalence of pairs *)\n\nDefinition prod_equiv {A} {B} { _ : Setoid A } { _ : Setoid B } \n  := (fun (x : prod A B) (y : prod A B) => fst x == fst y /\\ snd x == snd y).\n\nInstance prod_equiv_Equiv A B ( s : Setoid A ) ( t : Setoid B ) \n  : Equivalence (prod_equiv (A:=A) (B:=B)).\nunfold prod_equiv. split.\n  (* Refl *) intuition. \n  (* Sym *)  intros x y; destruct x; destruct y; intuition.\n  (* Trans *) intros x y z; destruct x; destruct y; destruct z; simpl; \n              split; intuition; etransitivity; eauto.\nQed.\n\nInstance setoid_prod A B ( _ : Setoid A ) ( _ : Setoid B ) : Setoid (prod A B)\n  := { equiv := prod_equiv }.\n\n(* Pointwise equivalence of functions *)\n\nProgram Instance setoid_arrow S T (s : Setoid S) (t : Setoid T) : Setoid (T -> S). \n\n(* Equivalence on option types *)\n\nDefinition option_equiv {A} {_ : Setoid A} : option A -> option A -> Prop :=  \n     fun x y => \n\tmatch x,y with\n\t| None, None => True\n\t| Some x,Some y => x==y\n\t| _,_ => False end.\nInstance eq_opt {A} {_ : Setoid A} : Equivalence option_equiv. \nsplit;\ncompute -[equiv];\nintros;\nrepeat match goal with | H : option _ |- _ => destruct H end;\nintuition. \netransitivity; eauto.\nQed.\n\nInstance setoid_option S (s : Setoid S) : Setoid (option S)\n  := {equiv := option_equiv}.\n\nProgram Instance lift_setoid T : Setoid (T -> Prop).", "meta": {"author": "resource-reasoning", "repo": "coq", "sha": "6561111ab25f5e956a1fe726d5e244a92f893850", "save_path": "github-repos/coq/resource-reasoning-coq", "path": "github-repos/coq/resource-reasoning-coq/coq-6561111ab25f5e956a1fe726d5e244a92f893850/coq/Views/BasicSetoids.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7279121530840615}}
{"text": "(** * Rel: Properties of Relations *)\n\n(** This short (and optional) chapter develops some basic definitions\n    and a few theorems about binary relations in Coq.  The key\n    definitions are repeated where they are actually used (in the\n    \\CHAPV2{Smallstep} chapter of _Programming Language Foundations_),\n    so readers who are already comfortable with these ideas can safely\n    skim or skip this chapter.  However, relations are also a good\n    source of exercises for developing facility with Coq's basic\n    reasoning facilities, so it may be useful to look at this material\n    just after the [IndProp] chapter. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export IndProp.\n\n(** A binary _relation_ on a set [X] is a family of propositions\n    parameterized by two elements of [X] -- i.e., a proposition about\n    pairs of elements of [X].  *)\n\nDefinition relation (X: Type) := X -> X -> Prop.\n\n(** Confusingly, the Coq standard library hijacks the generic term\n    \"relation\" for this specific instance of the idea. To maintain\n    consistency with the library, we will do the same.  So, henceforth\n    the Coq identifier [relation] will always refer to a binary\n    relation between some set and itself, whereas the English word\n    \"relation\" can refer either to the specific Coq concept or the\n    more general concept of a relation between any number of possibly\n    different sets.  The context of the discussion should always make\n    clear which is meant. *)\n\n(** An example relation on [nat] is [le], the less-than-or-equal-to\n    relation, which we usually write [n1 <= n2]. *)\n\nPrint le.\n(* ====> Inductive le (n : nat) : nat -> Prop :=\n             le_n : n <= n\n           | le_S : forall m : nat, n <= m -> n <= S m *)\nCheck le : nat -> nat -> Prop.\nCheck le : relation nat.\n(** (Why did we write it this way instead of starting with [Inductive\n    le : relation nat...]?  Because we wanted to put the first [nat]\n    to the left of the [:], which makes Coq generate a somewhat nicer\n    induction principle for reasoning about [<=].) *)\n\n(* ################################################################# *)\n(** * Basic Properties *)\n\n(** As anyone knows who has taken an undergraduate discrete math\n    course, there is a lot to be said about relations in general,\n    including ways of classifying relations (as reflexive, transitive,\n    etc.), theorems that can be proved generically about certain sorts\n    of relations, constructions that build one relation from another,\n    etc.  For example... *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Partial Functions *)\n\n(** A relation [R] on a set [X] is a _partial function_ if, for every\n    [x], there is at most one [y] such that [R x y] -- i.e., [R x y1]\n    and [R x y2] together imply [y1 = y2]. *)\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\n(** For example, the [next_nat] relation defined earlier is a partial\n    function. *)\n\nPrint next_nat.\n(* ====> Inductive next_nat (n : nat) : nat -> Prop :=\n           nn : next_nat n (S n) *)\nCheck next_nat : relation nat.\n\nTheorem next_nat_partial_function :\n   partial_function next_nat.\nProof.\n  unfold partial_function.\n  intros x y1 y2 H1 H2.\n  inversion H1. inversion H2.\n  reflexivity.  Qed.\n\n(** However, the [<=] relation on numbers is not a partial\n    function.  (Assume, for a contradiction, that [<=] is a partial\n    function.  But then, since [0 <= 0] and [0 <= 1], it follows that\n    [0 = 1].  This is nonsense, so our assumption was\n    contradictory.) *)\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. { \n    apply Hc with (x := 0).\n    - apply le_n.\n    - apply le_S. apply le_n. }\n  inversion Nonsense.   Qed.\n\n(** **** Exercise: 2 stars, optional  *)\n(** Show that the [total_relation] defined in earlier is not a partial\n    function. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional  *)\n(** Show that the [empty_relation] that we defined earlier is a\n    partial function. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Reflexive Relations *)\n\n(** A _reflexive_ relation on a set [X] is one for which every element\n    of [X] is related to itself. *)\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive :\n  reflexive le.\nProof.\n  unfold reflexive. intros n. apply le_n.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Transitive Relations *)\n\n(** A relation [R] is _transitive_ if [R a c] holds whenever [R a b]\n    and [R b c] do. *)\n\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  - (* le_n *) apply Hnm.\n  - (* le_S *) apply le_S. apply IHHmo.  Qed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  apply le_S in Hnm.\n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. Qed.\n\n(** **** Exercise: 2 stars, optional  *)\n(** We can also prove [lt_trans] more laboriously by induction,\n    without using [le_trans].  Do this.*)\n\nTheorem lt_trans' :\n  transitive lt.\nProof.\n  (* Prove this by induction on evidence that [m] is less than [o]. *)\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [| m' Hm'o].\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional  *)\n(** Prove the same thing again by induction on [o]. *)\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The transitivity of [le], in turn, can be used to prove some facts\n    that will be useful later (e.g., for the proof of antisymmetry\n    below)... *)\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof.\n  intros n m H. apply le_trans with (S n).\n  - apply le_S. apply le_n.\n  - apply H.\nQed.\n\n(** **** Exercise: 1 star, optional  *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_Sn_n_inf)  *)\n(** Provide an informal proof of the following theorem:\n\n    Theorem: For every [n], [~ (S n <= n)]\n\n    A formal proof of this is an optional exercise below, but try\n    writing an informal proof without doing the formal proof first.\n\n    Proof:\n    (* FILL IN HERE *)\n    []\n *)\n\n(** **** Exercise: 1 star, optional  *)\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Reflexivity and transitivity are the main concepts we'll need for\n    later chapters, but, for a bit of additional practice working with\n    relations in Coq, let's look at a few other common ones... *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Symmetric and Antisymmetric Relations *)\n\n(** A relation [R] is _symmetric_ if [R a b] implies [R b a]. *)\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\n(** **** Exercise: 2 stars, optional  *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** A relation [R] is _antisymmetric_ if [R a b] and [R b a] together\n    imply [a = b] -- that is, if the only \"cycles\" in [R] are trivial\n    ones. *)\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\n(** **** Exercise: 2 stars, optional  *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional  *)\nTheorem le_step : forall n m p,\n  n < m ->\n  m <= S p ->\n  n <= p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Equivalence Relations *)\n\n(** A relation is an _equivalence_ if it's reflexive, symmetric, and\n    transitive.  *)\n\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(* ----------------------------------------------------------------- *)\n(** *** Partial Orders and Preorders *)\n\n(** A relation is a _partial order_ when it's reflexive,\n    _anti_-symmetric, and transitive.  In the Coq standard library\n    it's called just \"order\" for short. *)\n\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\n(** A preorder is almost like a partial order, but doesn't have to be\n    antisymmetric. *)\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split.\n    - (* refl *) apply le_reflexive.\n    - split.\n      + (* antisym *) apply le_antisymmetric.\n      + (* transitive. *) apply le_trans.  Qed.\n\n(* ################################################################# *)\n(** * Reflexive, Transitive Closure *)\n\n(** The _reflexive, transitive closure_ of a relation [R] is the\n    smallest relation that contains [R] and that is both reflexive and\n    transitive.  Formally, it is defined like this in the Relations\n    module of the Coq standard library: *)\n\nInductive clos_refl_trans {A: Type} (R: relation A) : relation A :=\n    | rt_step : forall x y, R x y -> clos_refl_trans R x y\n    | rt_refl : forall x, clos_refl_trans R x x\n    | rt_trans : forall x y z,\n          clos_refl_trans R x y ->\n          clos_refl_trans R y z ->\n          clos_refl_trans R x z.\n\n(** For example, the reflexive and transitive closure of the\n    [next_nat] relation coincides with the [le] relation. *)\n\nTheorem next_nat_closure_is_le : forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m. split.\n  - (* -> *)\n    intro H. induction H.\n    + (* le_n *) apply rt_refl.\n    + (* le_S *)\n      apply rt_trans with m. apply IHle. apply rt_step.\n      apply nn.\n  - (* <- *)\n    intro H. induction H.\n    + (* rt_step *) inversion H. apply le_S. apply le_n.\n    + (* rt_refl *) apply le_n.\n    + (* rt_trans *)\n      apply le_trans with y.\n      apply IHclos_refl_trans1.\n      apply IHclos_refl_trans2. Qed.\n\n(** The above definition of reflexive, transitive closure is natural:\n    it says, explicitly, that the reflexive and transitive closure of\n    [R] is the least relation that includes [R] and that is closed\n    under rules of reflexivity and transitivity.  But it turns out\n    that this definition is not very convenient for doing proofs,\n    since the \"nondeterminism\" of the [rt_trans] rule can sometimes\n    lead to tricky inductions.  Here is a more useful definition: *)\n\nInductive clos_refl_trans_1n {A : Type}\n                             (R : relation A) (x : A)\n                             : A -> Prop :=\n  | rt1n_refl : clos_refl_trans_1n R x x\n  | rt1n_trans (y z : A) :\n      R x y -> clos_refl_trans_1n R y z ->\n      clos_refl_trans_1n R x z.\n\n(** Our new definition of reflexive, transitive closure \"bundles\"\n    the [rt_step] and [rt_trans] rules into the single rule step.\n    The left-hand premise of this step is a single use of [R],\n    leading to a much simpler induction principle.\n\n    Before we go on, we should check that the two definitions do\n    indeed define the same relation...\n\n    First, we prove two lemmas showing that [clos_refl_trans_1n] mimics\n    the behavior of the two \"missing\" [clos_refl_trans]\n    constructors.  *)\n\nLemma rsc_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> clos_refl_trans_1n R x y.\nProof.\n  intros X R x y H.\n  apply rt1n_trans with y. apply H. apply rt1n_refl.   Qed.\n\n(** **** Exercise: 2 stars, optional (rsc_trans)  *)\nLemma rsc_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      clos_refl_trans_1n R x y  ->\n      clos_refl_trans_1n R y z ->\n      clos_refl_trans_1n R x z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Then we use these facts to prove that the two definitions of\n    reflexive, transitive closure do indeed define the same\n    relation. *)\n\n(** **** Exercise: 3 stars, optional (rtc_rsc_coincide)  *)\nTheorem rtc_rsc_coincide :\n         forall (X:Type) (R: relation X) (x y : X),\n  clos_refl_trans R x y <-> clos_refl_trans_1n R x y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** $Date: 2017-04-26 17:33:43 -0400 (Wed, 26 Apr 2017) $ *)\n", "meta": {"author": "QuickChick", "repo": "QuickChick", "sha": "ca56cc21ecc76bc0e1443e917ce26c010980ae2f", "save_path": "github-repos/coq/QuickChick-QuickChick", "path": "github-repos/coq/QuickChick-QuickChick/QuickChick-ca56cc21ecc76bc0e1443e917ce26c010980ae2f/sf-experiment/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409024, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.7279042785651593}}
{"text": "(*******************************************************************)\n(*  This is part of RelationAlgebra, it is distributed under the   *)\n(*    terms of the GNU Lesser General Public License version 3     *)\n(*              (see file LICENSE for more details)                *)\n(*                                                                 *)\n(*  Copyright 2012: Damien Pous. (CNRS, LIP - ENS Lyon, UMR 5668)  *)\n(*******************************************************************)\n\n(** * kat_completeness: completeness of Kleene algebra with tests *)\n\n(** We closely follow Dexter Kozen and Frederick Smith' proof:\n   Kleene algebra with tests: Completeness and decidability. \n   In Proc. CSL'96, vol. 1258 of LNCS, pages 244-259, 1996. Springer-Verlag.\n\n   The only difference is that we do the proof directly for _typed_ KAT.\n\n   (We cannot easily exploit an untyping theorem, like we do in the\n   case of KA: although the untyping theorem holds for KAT, it\n   actually follows from typed completeness - at least we did not find\n   an alternative way of proving it)\n\n   The proof can be summarised as follows:\n   one exhibits a function [hat: gregex n m -> gregex n m] such that:\n   1. forall x, KAT |- hat x == x \n   2. forall x, G(hat x) == R(hat x), where \n      . G(y) is the typed guarded strings interpretation of y\n      . R(y) is the language interpretation of y, seen as a regular expression\n   (the concrete coercions will be specified later on)\n\n   From these properties, it follows that for all x,y: gregex n m, we have\n           G(x) == G(y)\n =>    G(hat x) == G(hat y)          (1, and G is a model)\n =>    R(hat x) == R(hat x)          (2)\n => KA |- hat x == hat y             (KA completeness)\n => KA |- hat x == hat y : n -> m    (untyping theorem for KA)\n => KAT|- hat x == hat y : n -> m    (KA theorems hold in KAT)\n => KAT|-     x == y : n -> m        (1, and transitivity)\n   \n   (the converse is immediate, G being a model) *)\n\nRequire Import denum lset sums normalisation.\nRequire Import kat ka_completeness untyping.\nRequire Import regex gregex lsyntax syntax lang glang boolean atoms.\nSet Implicit Arguments.\n\n(** abbreviations: [R] is the module about regular expressions, while\n   [G] is the module about generalised regular expressions *)\nModule R := regex.\nModule G := gregex.\n\nSection s.\nNotation Sigma := positive.\nVariable pred: nat.\nVariables src tgt: Sigma -> positive.\nNotation gregex := (gregex_kat_ops pred src tgt).\nNotation Atom := (ord (pow2 pred)).\nNotation gword := (trace Atom).\nNotation glang := (tglang_kat_ops pred src tgt). \nNotation g_atom n a := (@g_prd pred src tgt n (@atom pred a)).\nNotation test := (lsyntax.expr (ord pred)).\n\n(** * 1. Definition of the [hat] function, and correctness *)\n\n(** ** externally guarded terms *)\n\n(** the hat function is defined by induction on the structure of its\n   argument, but it actually produces formal sums of \"externally\n   guarded terms\", defined by the following inductive *)\n\nInductive guard: positive -> positive -> Type :=\n| g_pred: forall {n} (a: Atom), guard n n\n| g_elem: forall n m (a: Atom) (e: gregex n m) (b: Atom), guard n m.\nNotation guards n m := (list (guard n m)).\n\n(** externally guarded terms, and sums of such terms can be converted\n   back to [gregex] in the obvious way *)\nDefinition geval n m (x: guard n m) :=\n  match x with \n    | @g_pred n a => g_atom n a\n    | @g_elem n m a e b => g_atom n a * e * g_atom m b\n  end.\nNotation teval := (sup (@geval _ _)).\n\n(** ** inductive cases for the [hat] function *)\n\n(** *** predicates *)\n\n(** a predicate is mapped to the set of atoms under which it is satisfied *)\nDefinition g_prd' n p: guards n n  := \n  map g_pred (filter (fun a => lsyntax.eval (set.mem a) p) (seq (pow2 pred))).\n\nLemma teval_prd n (p: tst n): teval (g_prd' n p) == inj p. \nProof.\n  unfold g_prd'. rewrite sup_map. unfold geval. \n  setoid_rewrite <-inj_sup. apply inj_weq.\n  symmetry. apply decomp_expr.\nQed.\n\n(** *** unit *)\n\n(** accordingly, [1] is simply mapped to the set of all atoms *)\nDefinition g_one' n := g_prd' n (@lsyntax.e_top _).\n\nLemma teval_one n: teval (g_one' n) == 1. \nProof. unfold g_one'. rewrite teval_prd. apply inj_top. Qed.\n\n(** *** letters *)\n\n(** a Kleene variable [i] is mapped to the sum of all [f*i*g], for f,g\n   arbitrary atoms *)\n\nDefinition g_var' i := \\sup_(f<_) \\sup_(g<_) [g_elem f (g_var i) g]%list.\n\nLemma sum_atoms n: \\sup_(i<pow2 pred) g_atom n i == 1.\nProof.\n  rewrite <- teval_one. unfold g_one', g_prd'. rewrite sup_map.\n  apply sup_weq. reflexivity. \n  induction seq. reflexivity. now apply (cup_weq [_] [_])%list.\nQed.\n\nLemma teval_var i: teval (g_var' i) == g_var i.\nProof.\n  unfold g_var'. rewrite sup_sup. setoid_rewrite sup_sup.\n  setoid_rewrite sup_singleton. unfold geval.\n  setoid_rewrite <-dotxsum. setoid_rewrite <-dotA. rewrite <-dotsumx.\n  setoid_rewrite sum_atoms. ra. \nQed.\n\n(** *** composition *)\n\n(** composition is defined by a kind of coalesced product: we take all\n   products such that the post-guard of the former element coincides\n   with the pre-guard of the latter *)\n\n(** [g_dot1 x y] tries to compose two externally guarded terms *)\nDefinition g_dot1 n m (x: guard n m): forall p, guard m p -> guards n p  := \n  match x with\n    | g_pred a => fun p y => \n      match y with \n        | g_pred b       => if eqb a b then [g_pred a] else []\n        | g_elem b e c => if eqb a b then [g_elem b e c] else []\n      end\n    | g_elem a e b => fun p y => \n      match y with \n        | g_pred c => fun e => if eqb b c then [g_elem a e b] else []\n        | g_elem c f d => fun e => if eqb b c then [g_elem a (e*g_atom _ b*f) d] else []\n      end e\n  end%list.\n\n(** [g_dot' h k] does the composition of two lists of externally guarded terms *)\nDefinition g_dot' n m p (h: guards n m) (k: guards m p) := \n  \\sup_(x\\in h) \\sup_(y\\in k) g_dot1 x y.\n\n(** the correctness of this construction relies on the following two lemma *)\nLemma empty_atom_dot n a b: a<>b -> g_atom n a * g_atom n b == 0.\nProof. \n  intros. setoid_rewrite <-inj_cap.\n  rewrite (empty_atom_cap H). apply inj_bot. \nQed.\n\nLemma idem_atom_dot n a: g_atom n a * g_atom n a == g_atom n a.\nProof. setoid_rewrite <-inj_cap. now rewrite capI. Qed.\n\n(** correctness of [g_dot1] *)\nLemma geval_dot n m p (x: guard n m) (y: guard m p): teval (g_dot1 x y) == geval x * geval y.\nProof.\n  destruct x as [? a|? ? a e b]; destruct y as [? c|? ? c f d]; unfold g_dot1; \n    (case eqb_spec; [intros <-|intro E]); unfold geval; rewrite ?sup_singleton; unfold sup.\n  - now rewrite idem_atom_dot.\n  - symmetry. apply (empty_atom_dot _ E). \n  - now rewrite 2dotA, idem_atom_dot.\n  - rewrite 2dotA, (empty_atom_dot _ E). ra.\n  - now rewrite <-3dotA, idem_atom_dot.\n  - rewrite <-2dotA, (empty_atom_dot _ E). ra.\n  - transitivity (g_atom _ a*(e*(g_atom _ b*g_atom _ b)*f)*g_atom _ d). 2:ra. \n    now rewrite idem_atom_dot.\n  - transitivity (g_atom _ a*(e*(g_atom _ b*g_atom _ c)*f)*g_atom _ d). 2:ra. \n    rewrite (empty_atom_dot _ E). ra.\nQed.\n\n(** correctness of [g_dot'] *)\nLemma teval_dot n m p (x: guards n m) (y: guards m p):\n  teval (g_dot' x y) == teval x * teval y.\nProof.\n  unfold g_dot'. rewrite sup_sup. setoid_rewrite sup_sup.\n  setoid_rewrite geval_dot. \n  rewrite dotsumx. now setoid_rewrite dotxsum. \nQed.\n\n\n(** *** Kleene star *)\n\n(** Kleene star is defined by induction on the list of externally\n   guarded terms, see Kozen and Smith' paper *)\n\nDefinition fst n m (x: guard n m) := match x with g_pred a | g_elem a _ _ => a end.\nDefinition lst n m (x: guard n m) := match x with g_pred a | g_elem _ _ a => a end.\nDefinition g_inner_dot n m (x: guard n m): forall p, guard m p -> gregex n p :=\n  match x with\n    | g_pred a => fun p y => \n      match y with \n        | g_pred b       => 0\n        | g_elem b e c => if eqb a b \\cap eqb a c then e else 0\n      end\n    | g_elem a e b => fun p y => \n      match y with \n        | g_pred c => fun e => if eqb a b \\cap eqb b c  then e else 0\n        | g_elem c f d => fun e => if eqb b c \\cap eqb a d then e*g_atom _ b*f else 0\n      end e\n  end.\n\nDefinition xitr n m (r: guard n m) q' :=\n  let rq' := g_dot' [r] q' in\n  let a := fst r in\n  let p := sup (@g_inner_dot _ _ r _) q' in\n    g_dot' ([g_elem a (p*(g_atom _ a*p)^*) a]++g_one' _) rq'.\n\nFixpoint g_str' n (x: guards n n) := \n  match x with\n    | [] => g_one' _\n    | r::q => \n      let q' := g_str' q in\n      q' ++ g_dot' q' (xitr r q')\n  end.\n\n(** the correctness of this construction is substantially more involved than for the other ones *)\n\nLemma geval_fst n m (r: guard n m): geval r == g_atom _ (fst r) * geval r. \nProof.\n  destruct r.\n   simpl fst; unfold geval. now rewrite idem_atom_dot. \n   simpl fst; unfold geval. now rewrite 2dotA, idem_atom_dot.\nQed.\n\nLemma geval_lst n m (r: guard n m): geval r == geval r * g_atom _ (lst r). \nProof.\n  destruct r.\n   simpl fst; unfold geval. now rewrite idem_atom_dot. \n   simpl fst; unfold geval. now rewrite <-3dotA, idem_atom_dot.\nQed.\n\nDefinition dirac n m: gregex n m.\ncase (eqb_pos_spec n m). intros <-. exact 1. intros _. exact 0. \nDefined.\n\nLemma dirac_refl n: dirac n n = 1.\nProof.\n  unfold dirac. case eqb_pos_spec. 2: congruence. \n  intro. now rewrite cmp_eq_rect_eq. \nQed.\n\nLemma teval_inner_dot n m p (x: guard n m) (y: guard m p):\n  dirac n p + g_atom _ (fst x) * g_inner_dot x y * g_atom _ (fst x) == \n  dirac n p + ofbool (eqb (fst x) (lst y)) * geval x * geval y.\nProof.\n  unfold g_inner_dot.\n  revert p y. destruct x as [n a|n m a e b]; destruct y as [p c|p q c f d];\n    simpl fst; simpl lst; simpl geval. \n   rewrite dirac_refl. case eqb. 2: ra. ra_normalise. \n    setoid_rewrite <-inj_cap. rewrite <-inj_top, <-inj_cup. apply inj_weq. lattice. \n   case eqb_spec; intro E. subst. case eqb_spec; intro E'. subst. \n    simpl. ra_normalise. now rewrite idem_atom_dot.\n    ra. \n    simpl. ra_normalise. rewrite <-(dotA _ (g_atom p a)). \n    rewrite empty_atom_dot by assumption. ra.\n   case eqb_spec; intro E. subst. case eqb_spec; intro E'. subst. \n    simpl. ra_normalise. now rewrite <-3dotA, idem_atom_dot.\n    ra. \n    simpl. case eqb_spec; intro E'. subst. ra_normalise. \n     rewrite <-dotA. rewrite empty_atom_dot by congruence. ra.\n     ra. \n   case eqb_spec; intro E. subst. case eqb_spec; intro E'. subst. \n    simpl. ra_normalise. now rewrite <-(dotA _ (g_atom p c) (g_atom p c)), idem_atom_dot.\n    ra. \n    simpl. case eqb_spec; intro E'. subst. \n     ra_normalise. rewrite <-(dotA _ (g_atom p b) (g_atom p c)), empty_atom_dot by assumption.\n      ra. \n     ra. \nQed.\n\nLemma teval_xitr n m (r: guard n m) q: teval (xitr r q) == (geval r * teval q)^+.\nProof.\n  unfold xitr. \n  rewrite 2teval_dot, sup_app, 2sup_singleton, teval_one. \n  symmetry. rewrite itr_str_l. rewrite (geval_fst r) at 2. \n  rewrite <-(dotA (g_atom _ _)), str_dot. \n  apply dot_weq. 2: reflexivity. \n  rewrite cupC. unfold geval at 3. rewrite dotA. rewrite <-itr_str_l. \n  rewrite itr_aea by now rewrite idem_atom_dot. rewrite <-str_itr. apply str_weq1.\n  induction q as [|e q IH]. ra. \n  simpl (sup _ _). \n  rewrite 2dotxpls, 2dotplsx. rewrite <-(cupI 1), 2cupA, 2comm4. apply cup_weq. \n  2: assumption. clear IH.\n  rewrite <-dirac_refl. rewrite teval_inner_dot. \n  case eqb_spec; intro E. \n   setoid_rewrite dot1x. rewrite E. now rewrite <-dotA, <-geval_lst.\n  rewrite (geval_lst e), <-2dotA, empty_atom_dot by congruence. ra. \nQed.\n\nLemma teval_str n (x: guards n n): teval (g_str' x) == teval x ^*.\nProof.\n  induction x as [|r q IH]; simpl g_str'. \n  rewrite teval_one. symmetry. apply str0.\n  simpl (sup _ _). setoid_rewrite (cupC (geval r)). rewrite str_pls.\n  rewrite sup_app, teval_dot, teval_xitr, IH. rewrite (str_itr (_*_)). ra. \nQed.\n\n(** ** summing up the constructions, by induction *)\n\nFixpoint hat n m (e: gregex n m): guards n m := \n  match e with\n    | g_zer _ _ _ => []\n    | g_prd _ _ p => g_prd' _ p\n    | g_pls e f => hat e \\cup hat f\n    | g_dot e f => g_dot' (hat e) (hat f)\n    | g_itr e => g_dot' (hat e) (g_str' (hat e))\n    | g_var i => g_var' i\n  end.\n\nTheorem teval_hat n m (e: gregex n m): teval (hat e) == e.\nProof.\n  induction e; simpl hat. \n   reflexivity.\n   apply teval_prd. \n   apply teval_var. \n   setoid_rewrite sup_app. now apply cup_weq. \n   rewrite teval_dot. now apply dot_weq.\n   rewrite teval_dot, teval_str, <-itr_str_l. now apply itr_weq. \nQed.\n\n\n\n(** * Relationship between generalised regular expressions and (plain) regular expressions *)\n\n(** ** extended alphabet *)\n\n(** a letter in the extended alphabet is either a Kleene variable, a\n   positive predicate variable, or a negative one. We moreover need to\n   record the type of the corresponding test in the two latter cases *)\n\nInductive letter :=\n| l_pos (n: positive) (p: ord pred)\n| l_neg (n: positive) (p: ord pred)\n| l_var (i: Sigma).\n\n(** the above type can be retracted into positives: this saves us from\n   proving KA completeness on an arbitrary alphabet (this would\n   require a lot of polymorphic definitions) *)\n\nDefinition lp (l: letter): positive :=\n  match l with\n    | l_pos n x => mk_sum (inl (mk_sum (inl (mk_pair (n, mk_ord x)))))\n    | l_neg n x => mk_sum (inl (mk_sum (inr (mk_pair (n, mk_ord x)))))\n    | l_var i   => mk_sum (inr i)\n  end.\nDefinition pl (p: positive): letter :=\n  match get_sum p with\n    | inl p => match get_sum p with\n                 | inl p => let '(n,p) := get_pair p in \n                   match get_ord _ p with None => l_var 1 | Some x => l_pos n x end\n                 | inr p => let '(n,p) := get_pair p in \n                   match get_ord _ p with None => l_var 1 | Some x => l_neg n x end\n               end\n    | inr i => l_var i\n  end.\nLemma plp l: pl (lp l) = l. \nProof. destruct l; unfold pl, lp; now rewrite !get_mk_sum, ?get_mk_pair, ?get_mk_ord. Qed.\n\n(** the retraction into positives also equips [letter] with a\n   [cmpType] structure *)\nDefinition compare_letter (a b: letter) := cmp (lp a) (lp b).\nLemma compare_letter_spec a b: compare_spec (a=b) (compare_letter a b). \nProof.\n  unfold compare_letter. case cmp_spec; intro E; constructor. \n  now rewrite <-(plp a), <-(plp b), E. congruence. congruence. \nQed.\nCanonical Structure cmp_letter := mk_simple_cmp _ compare_letter_spec.\n\n(** typing extended letters: \n   - predicate letters come with their type\n   - Kleene letters use the typing environment *)\nDefinition src' l := \n  match l with\n    | l_pos n _ | l_neg n _ => n\n    | l_var i => src i \n  end.\n\nDefinition tgt' l := \n  match l with\n    | l_pos n _ | l_neg n _ => n\n    | l_var i => tgt i \n  end.\n\n(** ** regular expressions on the extended alphabet *)\n \n(** [expr3] is intuitively the set of typed regular expressions on [letter],\n   while [uexpr3] is the set of untyped regular expressions on [letter] \n\n   we use [uexpr3] rather than [regex] to use the untyping theorem\n   (which we proved on generic expressions rather than regular\n   expressions). \n\n   we now define several maps between these representations:\n   - [o : gregex n m -> expr3 n m] (injective)\n   - [o': expr3 n m -> gregex]     (partial, since expr3 has to many operations)\n   - [v : expr3 n m -> regex]      (type-erasing, partial for the same reasons)\n   - [w : regex -> uexpr3]         (injective, even if we do not prove it)\n   - [u : expr3 n m -> uexpr3]     (type-erasing, actually [untyping.erase])\n   \n   and we prove the following properties:\n   - [o'o = id]                 (yielding injectivity of [o])\n   - [wvo = uo]                 (allowing us to use the untyping theorem)\n\n*)\nNotation expr3 n m := (expr_ops src' tgt' BKA n m).\nNotation uexpr3 := (expr_ops (fun _ => xH) (fun _ => xH) BKA xH xH). \n\n\n(** ** [o: gregex n m -> expr3 n m] *)\n\nSection n.\nVariable n: positive.\nImport lsyntax.\n(** we need to push negation to leaves in Boolean expressions *)\nFixpoint o_pred (x: test): expr3 n n :=\n  match x with\n    | e_bot => 0\n    | e_top => 1\n    | e_cup x y => o_pred x + o_pred y\n    | e_cap x y => o_pred x * o_pred y\n    | e_neg x => o_npred x\n    | e_var a => syntax.e_var (l_pos n a)\n  end\nwith o_npred (x: test): expr3 n n :=\n  match x with\n    | e_bot => 1\n    | e_top => 0\n    | e_cup x y => o_npred x * o_npred y\n    | e_cap x y => o_npred x + o_npred y\n    | e_neg x => o_pred x\n    | e_var a => syntax.e_var (l_neg n a)\n  end.\nImport syntax.\nLemma o_pred_level x: e_level (o_pred x) << BKA\n  with o_npred_level x: e_level (o_npred x) << BKA. \nProof.\n  destruct x; simpl o_pred; simpl e_level; rewrite ?merge_spec; intuition. \n  destruct x; simpl o_npred; simpl e_level; rewrite ?merge_spec; intuition. \nQed.\nEnd n.\n\nFixpoint o n m (e: gregex n m): expr3 n m:=\n  match e with\n    | g_zer _ _ _ => 0\n    | g_prd _ _ p => o_pred _ p\n    | g_pls e f => o e + o f\n    | g_dot e f => o e * o f\n    | g_itr e => o e ^+\n    | g_var j => e_var (l_var j)\n  end.\n\nLemma o_sup n m I J (f: I -> gregex n m): o (sup f J) = \\sup_(i\\in J) (o (f i)).\nProof. apply f_sup_eq; now f_equal. Qed.\n\nLemma o_level n m (e: gregex n m): e_level (o e) << BKA. \nProof.\n  pose proof o_pred_level. \n  induction e; simpl o; simpl e_level; rewrite ?merge_spec; intuition. \nQed.\n\n(** ** [o': expr3 n m -> gregex n m] *)\n\nDefinition o': forall n m, expr3 n m -> gregex n m :=\n  @eval _ src' tgt' (gregex_monoid_ops pred src tgt) id \n  (fun l => match l return gregex (src' l) (tgt' l) with\n              | l_pos n p => g_prd _ _ (lsyntax.e_var p)\n              | l_neg n p => g_prd _ _ (! lsyntax.e_var p)\n              | l_var i => g_var i\n            end).\n\nLemma o'o_pred: forall n (a: test), o' (o_pred n a) == g_prd _ _ a\n with o'o_npred: forall n (a: test), o' (o_npred n a) == g_prd _ _ (!a).\nProof.\n  destruct a.\n   symmetry. apply inj_bot. \n   symmetry. apply inj_top.\n   setoid_rewrite inj_cup. apply cup_weq; apply o'o_pred. \n   setoid_rewrite inj_cap. apply dot_weq; apply o'o_pred. \n   apply o'o_npred. \n   reflexivity. \n  destruct a.\n   symmetry. etransitivity. apply inj_weq. apply negbot. apply inj_top. \n   symmetry. etransitivity. apply inj_weq. apply negtop. apply inj_bot. \n   etransitivity. 2: apply inj_weq; symmetry; apply negcup. rewrite inj_cap.\n    apply dot_weq; apply o'o_npred. \n   etransitivity. 2: apply inj_weq; symmetry; apply negcap. rewrite inj_cup.\n    apply cup_weq; apply o'o_npred. \n   etransitivity. 2: apply inj_weq; symmetry; apply negneg. apply o'o_pred. \n   reflexivity. \nQed.\n\n(** [o] admits [o'] as left-inverse *)\nLemma o'o: forall n m (e: gregex n m), o' (o e) == e.\nProof.\n  induction e; simpl o; simpl o'. \n   reflexivity. \n   apply o'o_pred.\n   reflexivity. \n   now apply cup_weq. \n   now apply dot_weq. \n   now apply itr_weq.\nQed.\n\nLemma o'_weq n m: Proper (weq ==> weq) (@o' n m). \nProof. intros ? ? H. apply (H (gregex_monoid_ops _ _ _) _ id). Qed.\n\n(** so that [o] is injective *)\nCorollary o_inj n m (e f: gregex n m): o e == o f -> e == f.\nProof. intro H. apply o'_weq in H. revert H. now rewrite 2o'o. Qed.\n\n\n(** ** [expr3 -v-> regex -w-> uexpr3] *)\n\nDefinition v: forall n m, expr3 n m -> regex :=\n  eval (f':=fun _ => regex_tt) (fun l => r_var (lp l)).\n\nDefinition w (e: regex): uexpr3 :=\n  eval (X:=expr_ops _ _ BKA) (f':=fun _ => xH) (fun p => e_var (pl p)) (to_expr e).\n\nLemma wv_u n m (e: expr3 n m): e_level e << BKA -> w (v e) == erase BKA e.\nProof.\n  unfold w.\n  induction e; simpl e_level; intro Hl; try discriminate_levels;\n    try (first [reflexivity|apply dot_weq|apply cup_weq|apply str_weq]);\n      try (first [apply IHe1|apply IHe2|apply IHe]; solve_lower').\n  symmetry. simpl (erase _ _). rewrite itr_str_l, <-IHe. reflexivity. solve_lower'.\n  simpl. now rewrite plp.\nQed.\n\n(** key lemma to be able to use the untyping theorem *)\nLemma wvo_uo n m (e: gregex n m): w (v (o e)) == erase BKA (o e).\nProof. apply wv_u, o_level. Qed. (* note: on doit pouvoir prouver une égalité forte *)\n\nLemma w_weq: Proper (weq ==> weq) w. \nProof. intros ? ? H. apply (H (expr_ops _ _ _) _ (fun _ => xH)). Qed.\n\nLemma v_sup n m I J (f: I -> expr3 n m): v (sup f J) = \\sup_(i\\in J) (v (f i)).\nProof. apply f_sup_eq; now f_equal. Qed.\n\n\n\n(** * From guarded string languages to languages on the extended alphabet *)\n(** i.e., we define a coercion from [glang] [lang] *)\n\nNotation word := (list positive).\nNotation lang := (lang_ops positive lang_tt lang_tt).\n\n(** converting an atom into a word of the extended alphabet. \n   this word has length [pred]: each predicate variable appears\n   exactly once, with its assigned truth value *)\nDefinition atom_to_word n (a: Atom) := \n  map (fun i => if set.mem a i then lp (l_pos n i) else lp (l_neg n i)) (seq pred).\n\n(** converting an guarded string into a word of the extended alphabet\n   the resulting word has length [pred+(1+pred)*n], where [n] is the\n   length of the guarded string *)\nFixpoint gword_to_word n (w: gword) :=\n  match w with\n    | tnil a => atom_to_word n a\n    | tcons a i w => atom_to_word n a ++ lp (l_var i) :: gword_to_word (tgt i) w\n  end.\n\n(** we convert a guarded string language by converting its words *)\nDefinition gl n m (G: glang n m): lang :=\n  fun w => exists g, w = gword_to_word n g /\\ proj1_sig G g.\n\n\nInstance gl_leq n m: Proper (leq ==> leq) (@gl n m).\nProof. intros G G' H w [t [? Hw]]. exists t. split. assumption. apply H, Hw. Qed.\nInstance gl_weq n m: Proper (weq ==> weq) (@gl n m) := op_leq_weq_1.\n\n\n(** auxiliary definition for the following auxiliary lemma:\n   [gword_to_word' w] return the suffix of the word corresponding to\n   [w], where the initial atom has been omitted *)\nDefinition gword_to_word' (w: gword) :=\n  match w with\n    | tnil a => []\n    | tcons a i w => lp (l_var i) :: gword_to_word (tgt i) w\n  end.\n\nLemma gword_to_word_cut n w: \n  gword_to_word n w = atom_to_word n (thead w) ++ gword_to_word' w.\nProof. destruct w. apply app_nil_end. reflexivity. Qed.\n\nLemma gword_tapp: forall x y z, tapp x y z -> \n  forall n, gword_to_word n z = gword_to_word n x ++ gword_to_word' y. \nProof.\n  induction 1; simpl; intros n. \n   apply app_nil_end.\n   reflexivity. \n   now rewrite IHtapp, app_ass. \nQed.\n\n\n\n\n(** * 2. G (hat e) = R (hat e)\n\n   (more formally, gl (G (hat e)) == R (v (o (hat e))))\n\n  *)\n\nNotation R := R.lang.\nNotation G := G.lang.\n\nNotation latom n a := (eq (atom_to_word n a): lang).\n\n\n(** regular language corresponding to an atom *)\n\nLemma R_lang_atom n a: R (v (o (g_atom n a))) == latom n a.\nProof.\n  simpl o. unfold atom, atom_to_word. \n  induction (seq pred). apply R.lang_1. simpl (sup _ _). \n  setoid_rewrite R.lang_dot. setoid_rewrite (eq_app_dot _ [_]). apply dot_weq. \n  case set.mem; apply R.lang_var. assumption. \nQed.\n\n\n(** ** properties of [gl]  *)\n\n(** [gl] is a semilattice morphism (note that it does not preserve products/iterations) *)\n\nLemma gl_bot n m: @gl n m bot == bot.\nProof. split. intros [? [? []]]. intros []. Qed.\n\nLemma gl_cup n m (e f: glang n m): gl (e \\cup f) == gl e \\cup gl f.\nProof. \n  split. \n   intros [w [-> [H|H]]]; [left|right]; exists w; split; auto.\n   intros [H|H]; destruct H as [w [-> H]]; exists w; split; trivial; (now left) || (now right).\nQed.\n\nLemma gl_sup n m I J (f: I -> glang n m): gl (sup f J) == \\sup_(i\\in J) gl (f i).\nProof. apply f_sup_weq. apply gl_bot. apply gl_cup. Qed.\n\n(** [gl] maps atoms to atoms *)\n\nLemma gl_atom n a: gl (tatom n a) == latom n a.\nProof.\n  intro w; split. \n  intros [g [-> <-]]. reflexivity. \n  intros <-. eexists. split. 2: reflexivity. reflexivity. \nQed.\n\n(** image of single letter traces under [gl] *)\nLemma gl_single' a i b:\n  gl (tsingle' a i b) == \n  eq (atom_to_word (src i) a++[lp (l_var i)]++atom_to_word (tgt i) b).\nProof.\n  intro w; split. \n  intros [g [-> <-]]. reflexivity. \n  intros <-. eexists. split. 2: reflexivity. reflexivity. \nQed.\n\n(** key auxiliary lemma for composition: we need to use an atom as a cutting point *)\nLemma gl_dot n m p (e: glang n m) a (f: glang m p) (e' f': lang): \n  gl (e * tatom m a) == e' * latom m a ->  \n  gl (tatom m a * f) == latom m a * f' ->  \n  gl (e * tatom m a * f) == e' * latom m a * f'.\nProof.\n  setoid_rewrite weq_spec.\n  intros He Hf. split; intro w.\n  - apply proj1 in He. apply proj1 in Hf.\n    intros [g [-> [xa [x Hx [? <- Hxa]] [y Hy Hg]]]].\n    apply tapp_x_nil_eq in Hxa as [Ha ->].\n    destruct (tapp_bounds Hg) as (H1&H2&H3). (* TOSIMPL *)\n    destruct (He (gword_to_word n x)) as [x' Hx' [? <- Hxa']].\n     repeat eexists; eauto. rewrite Ha. apply tapp_x_nil.\n    destruct (Hf (gword_to_word m y)) as [? <- [y' Hy' Hay']].\n     repeat eexists; eauto. rewrite Ha. rewrite H1. apply tapp_nil_x.\n    repeat eexists; eauto.\n    rewrite app_ass, <-Hay', (gword_to_word_cut m y), (gword_tapp Hg), <-app_ass.\n    congruence.\n  - apply proj2 in He. apply proj2 in Hf.\n    intros [ea [x Hx [? <- ->]] [y Hy ->]].\n    edestruct (He (x++atom_to_word m a)) as [xa [Hxa [x' Hx' [? <- Hxa']]]]. eexists; eauto.\n    edestruct (Hf (atom_to_word m a++y)) as [ay [Hay [? <- [y' Hy' Hay']]]]. eexists; eauto.\n    apply tapp_x_nil_eq in Hxa' as [-> ->].\n    apply tapp_nil_x_eq in Hay' as [Ha ->].\n    destruct (tapp_cat x' y' Ha) as [z Hz]. \n    repeat eexists; eauto. 2: apply tapp_x_nil.\n    rewrite (gword_tapp Hz), <-Hxa, app_ass, Hay, gword_to_word_cut, ass_app.\n    congruence.\nQed.\n\nLemma gl_nildot a n m (e: glang n m): exists e', gl (tatom n a * e) == latom n a * e'.\nProof.\n  exists (fun w => exists g, proj1_sig e g /\\ thead g = a /\\ w = gword_to_word' g).\n  rewrite weq_spec. split; intro w.\n   intros [u [-> [? <- [v Hv H]]]]. apply tapp_nil_x_eq in H as [-> ->].\n   repeat eexists; eauto. apply gword_to_word_cut.\n   intros [? <- [u (x&He&<-&->) ->]].\n   repeat eexists; eauto. apply eq_sym, gword_to_word_cut. apply tapp_nil_x.\nQed.\n\n(** key auxiliary lemma for iteration: we need to use an atom as bounds *)\nLemma gl_itr n (e: glang n n) a (e': lang): \n  gl (tatom n a * e * tatom n a) == e' * latom n a ->  \n  gl ((tatom n a * e)^+ * tatom n a) == e'^+ * latom n a.\nProof.\n  rename n into m.\n  intro H. rewrite <-itr_dot. apply antisym.\n  - apply weq_spec in H as [H _]. intros w [g [-> [? <- [u [n Hn] Hg]]]].\n    apply tapp_nil_x_eq in Hg as [Hu ->]. revert u Hu Hn. induction n; intros u Hu Hn.\n    destruct Hn as [v Hv [? <- Hn]]. apply tapp_x_nil_eq in Hn as [Hn ->].\n    destruct (H (gword_to_word m v)) as [u He [? <- H']].\n     repeat eexists; eauto. rewrite Hu. apply tapp_nil_x. rewrite Hn. apply tapp_x_nil.\n    exists u. now exists O. eauto.\n    destruct Hn as [w [v Hv [? <- Hn]] [w' Hw' H']].\n    apply tapp_x_nil_eq in Hn as [Hn ->].\n    assert (H'' := tapp_bounds H'). (* TOSIMPL *)\n    assert (Haw: a=thead w') by (rewrite Hn; intuition congruence).\n    destruct (H (gword_to_word m v)) as [xe He [? <- Hxe]].\n    repeat eexists; eauto.\n     rewrite Hu, <-(tapp_head H'). apply tapp_nil_x.\n     rewrite Hn; apply tapp_x_nil.\n    assert (Hext: e' * (e'^+ * latom m a) <== e'^+ * latom m a).\n     now rewrite dotA, itr_cons.\n    apply Hext. clear Hext.\n    eexists. eassumption. eexists. apply IHn. apply Haw. \n    assumption.\n    rewrite (gword_tapp H'), Hxe, gword_to_word_cut, Haw, app_ass. congruence.\n  - apply itr_ind_l.\n    now rewrite <-H, <-itr_ext, dotA.\n    rewrite <-itr_cons at 2.\n    destruct (gl_nildot a ((e * tatom m a)^+)) as [f' Hf].\n    rewrite 2dotA. rewrite gl_dot by eassumption.\n    now rewrite Hf, dotA.\nQed.\n\n\n(** ** clean terms: those on which [G] and [R] coincide *)\n\nDefinition clean1 n m (e: guard n m) := gl (G (geval e)) == R (v (o (geval e))).\nDefinition clean n m (e: guards n m) := forall g, In g e -> clean1 g.\n\nLemma G_clean n m (e: guards n m): clean e -> gl (G (teval e)) == R (v (o (teval e))).\nProof.\n  intro He. rewrite o_sup, v_sup, lang_sup, R.lang_sup, gl_sup.\n  apply sup_weq'. reflexivity. intros g Hg. apply He, Hg. \nQed.\n\n(** basic constructors for clean terms *)\n\nLemma clean_bot n m: @clean n m bot. \nProof. intros _ []. Qed.\n\nLemma clean_cup n m (e f: guards n m): clean e -> clean f -> clean (e++f). \nProof. unfold clean. setoid_rewrite in_app_iff. intuition. Qed.\n\nLemma clean_single n m (g: guard n m): clean1 g -> clean [g].\nProof. now intros ? ? [<-|[]]. Qed.\n\nLemma clean_sup n m I J (f: I -> guards n m): (forall i, In i J -> clean (f i)) -> clean (sup f J).\nProof. apply P_sup. apply clean_bot. apply clean_cup. Qed.\n\nLemma clean_map n m I J (f: I -> guard n m): (forall i, In i J -> clean1 (f i)) -> clean (map f J).\nProof. rewrite map_sup. intro. apply clean_sup. intros. apply clean_single. auto. Qed.\n\n\n(** ** the basic ingredients of the [hat] function preserve cleaness  *)\n\nLemma clean_pred n a: clean1 (@g_pred n a). \nProof. unfold clean1, geval. rewrite G.lang_atom, R_lang_atom. apply gl_atom. Qed.\n\nLemma clean_elem_var a i b: clean1 (g_elem a (g_var i) b).\nProof.\n  unfold clean1, geval.\n  rewrite 2G.lang_dot, 2G.lang_atom. \n  setoid_rewrite atom_single_atom. rewrite gl_single'. rewrite 2eq_app_dot. \n  do 2 setoid_rewrite R.lang_dot. setoid_rewrite R.lang_var.\n  setoid_rewrite <- R_lang_atom. apply dotA.\nQed.\n\nLemma clean_dot' n m p (e: guards n m) (f: guards m p): clean e -> clean f -> clean (g_dot' e f). \nProof.\n  intros He Hf. apply clean_sup. intros x Hx. apply clean_sup. intros y Hy. \n  apply He in Hx. apply Hf in Hy. clear e f He Hf. \n  destruct x as [a|a e b]; destruct y as [c|c f d]; unfold g_dot1; \n    (case eqb_spec; [intros <-|intro E]); try apply clean_bot; apply clean_single; trivial.\n  revert Hx Hy. unfold clean1, geval. rewrite 8G.lang_dot, 3G.lang_atom.\n  simpl o; simpl v. fold_regex. rewrite 8R.lang_dot. repeat change (o_pred ?a (atom ?b)) with (o (g_atom a b)). setoid_rewrite R_lang_atom. \n  intros Hx Hy. rewrite 4dotA, <-dotA, <-(dotA _ _ (latom _ _)). \n  apply gl_dot. assumption. rewrite 2dotA. assumption. \nQed.\n\nLemma clean_one' n: clean (g_one' n).\nProof. apply clean_map. intros. apply clean_pred. Qed.\n\nLemma clean_inner_dot n m (e: guard n m) (He: clean1 e):\n  forall p (f: guard m p), clean1 f -> \n   gl (tatom n (fst e) * G (g_inner_dot e f) * tatom p (fst e)) ==\n   latom n (fst e) * R (v (o (g_inner_dot e f))) * latom p (fst e).\nProof.\n  assert (Z: forall n m p q (e: glang n m) (f: glang p q) e' f', gl (e*G 0*f) == e'*R 0*f').\n   intros. rewrite G.lang_0, dotx0, dot0x, gl_bot. setoid_rewrite R.lang_0. ra. \n  destruct e as [n a|n m a e b]; destruct f as [p c|p q c f d]; intros Hf;\n    simpl fst; simpl lst; simpl g_inner_dot.\n  - apply Z. \n  - case eqb_spec. intros <-. 2: intros; apply Z. \n    case eqb_spec. intros <-. 2: intros; apply Z. \n    unfold andb. unfold clean1, geval in Hf. \n    rewrite 2G.lang_dot, 2G.lang_atom in Hf. rewrite Hf. \n    rewrite <-2R_lang_atom, <-2R.lang_dot. reflexivity. \n  - case eqb_spec. intros <-. 2: intros; apply Z. \n    case eqb_spec. intros <-. 2: intros; apply Z. \n    unfold andb. unfold clean1, geval in He. \n    rewrite 2G.lang_dot, 2G.lang_atom in He. rewrite He. \n    rewrite <-2R_lang_atom, <-2R.lang_dot. reflexivity. \n  - case eqb_spec. intros <-. 2: intros; apply Z. \n    case eqb_spec. intros <-. 2: intros; apply Z. \n    unfold andb. \n    unfold clean1, geval in He. rewrite 2G.lang_dot, 2G.lang_atom in He. \n    unfold clean1, geval in Hf. rewrite 2G.lang_dot, 2G.lang_atom in Hf. \n    simpl o in *; simpl v in *. \n    rewrite 2R.lang_dot in He. repeat change (o_pred ?a (atom ?b)) with (o (g_atom a b)) in He. setoid_rewrite R_lang_atom in He. \n    rewrite 2R.lang_dot in Hf. repeat change (o_pred ?a (atom ?b)) with (o (g_atom a b)) in Hf. setoid_rewrite R_lang_atom in Hf. \n    rewrite 2R.lang_dot. repeat change (o_pred ?a (atom ?b)) with (o (g_atom a b)). setoid_rewrite R_lang_atom. \n    setoid_rewrite G.lang_dot. rewrite dotA. setoid_rewrite G.lang_dot. \n    rewrite G.lang_atom. \n    rewrite dotA. rewrite <-(dotA _ (G f)). \n    rewrite <-2dotA in Hf. \n    rewrite gl_dot by eassumption. ra. \nQed.  \n\nLemma clean_str' n (e: guards n n): clean e -> clean (g_str' e). \nProof.\n  induction e; intro Hae; simpl g_str'. apply clean_one'.\n  assert (He: clean e) by (intros ? ?; apply Hae; now right). specialize (IHe He). \n  assert (Ha: clean1 a) by (apply Hae; now left). clear Hae. \n  apply clean_cup. assumption.\n  apply clean_dot'. assumption. \n  apply clean_dot'. apply clean_cup. 2: apply clean_one'. \n  2: apply clean_dot'; [now apply clean_single | assumption]. \n  revert IHe. generalize (g_str' e). clear e He. intros e He. \n  apply clean_single. unfold clean1. unfold geval. simpl o; simpl v; fold_regex. \n  rewrite 2dotA, <-str_itr, <-2itr_str_l. \n  rewrite G.lang_dot, G.lang_itr, G.lang_dot, G.lang_sup, G.lang_atom.\n  rewrite R.lang_dot, R.lang_itr, R.lang_dot, o_sup, v_sup, R.lang_sup.\n  repeat change (o_pred ?a (atom ?b)) with (o (g_atom a b)). setoid_rewrite R_lang_atom. \n  apply gl_itr. rewrite 2dotxsum, 2dotsumx, gl_sup. \n  apply sup_weq'. reflexivity. intros f Hf. \n  apply clean_inner_dot. apply Ha. apply He, Hf. \nQed.\n\n(** ** the [hat] function produces clean terms *)\n\nTheorem clean_hat n m (e: gregex n m): clean (hat e).\nProof.\n  induction e; simpl hat. \n   apply clean_bot. \n   apply clean_map. intros ? _. apply clean_pred. \n   apply clean_sup. intros ? _. apply clean_sup. intros ? _. apply clean_single, clean_elem_var.\n   now apply clean_cup. \n   now apply clean_dot'. \n   apply clean_dot'. assumption. apply clean_str'. assumption. \nQed.\n\n(** whence the desired property, as a corollary *)\n\nCorollary G_hat n m (e: gregex n m): gl (G e) == R (v (o (teval (hat e)))).\nProof. rewrite <-(teval_hat e) at 1. apply G_clean, clean_hat. Qed.\n\n(** * KAT completeness *)\n\n(** we assemble all the pieces as explained at the beginning of this file *)\nTheorem kat_complete_weq n m: forall e f: gregex n m, G e == G f -> e == f.\nProof.\n  intros e f H.\n  apply gl_weq in H. \n  rewrite 2G_hat in H. \n  apply ka_complete_weq in H.\n  apply w_weq in H. \n  rewrite 2wvo_uo in H. \n  apply erase_faithful_weq in H. \n   2: now rewrite 2o_level. \n   2: reflexivity. \n  apply o_inj in H. \n  rewrite 2teval_hat in H. \n  assumption.\nQed.\n\n(** we deduce a similar result for language inclusions *)\nCorollary kat_complete_leq n m: forall e f: gregex n m, G e <== G f -> e <== f.\nProof. intros e f. rewrite 2leq_iff_cup, <-G.lang_pls. apply kat_complete_weq. Qed.\n\n(** and the above implications actually are equivalences *)\nCorollary kat_correct_complete_weq n m: forall e f: gregex n m, G e == G f <-> e == f.\nProof. split. apply kat_complete_weq. apply G.lang_weq. Qed.\n\nCorollary kat_correct_complete_leq n m: forall e f: gregex n m, G e <== G f <-> e <== f.\nProof. split. apply kat_complete_leq. apply G.lang_leq. Qed.\n\n(** * KAT decidability  *)\n\n(** additional corollaries (not used): \n   - KAT proofs reduce to KA proofs \n   - KAT equality is decidable *)\n\nCorollary kat_reduces_to_ka n m: forall e f: gregex n m, \n  e==f <-> v (o (teval (hat e))) == v (o (teval (hat f))).\nProof.\n   intros. split; intro H. \n    apply ka_complete_weq. now rewrite <-2G_hat, H.\n    apply w_weq in H. \n    rewrite 2wvo_uo in H. \n    apply erase_faithful_weq in H. \n     2: now rewrite 2o_level. \n     2: reflexivity. \n    apply o_inj in H. \n    now rewrite 2teval_hat in H. \nQed.\n\nCorollary kat_dec n m: forall e f: gregex n m, {e==f} + {~(e==f)}.\nProof. intros. eapply sumbool_iff. symmetry. apply kat_reduces_to_ka. apply ka_weq_dec. Qed.\n\nEnd s.\n", "meta": {"author": "coq-contribs", "repo": "relation-algebra", "sha": "2d9066e917400dc3e2b10ad9c12710620d20644b", "save_path": "github-repos/coq/coq-contribs-relation-algebra", "path": "github-repos/coq/coq-contribs-relation-algebra/relation-algebra-2d9066e917400dc3e2b10ad9c12710620d20644b/kat_completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7279042721021062}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* Require Import Arith Omega Max List. *)\n\nRequire Import Arith Omega List Permutation.\nRequire Import utils pos.\n\nSet Implicit Arguments.\n\nSection vector.\n\n  Variable X : Type.\n\n  Inductive vec : nat -> Type :=\n    | vec_nil  : vec 0\n    | vec_cons : forall n, X -> vec n -> vec (S n).\n\n  Let vec_decomp_type n := \n    match n with\n      | 0   => Prop\n      | S n => (X * vec n)%type\n    end.\n\n  Definition vec_decomp n (v : vec n) :=\n    match v in vec k return vec_decomp_type k with\n      | vec_nil  => False\n      | @vec_cons n x v => (x,v)\n    end.\n    \n  Definition vec_head n (v : vec (S n)) := match v with @vec_cons _ x _ => x end.\n  Definition vec_tail n (v : vec (S n)) := match v with @vec_cons _ _ w => w end.\n\n  Let vec_head_tail_type n : vec n -> Prop := \n    match n with\n      | 0   => fun v => v = vec_nil\n      | S n => fun v => v = vec_cons (vec_head v) (vec_tail v)\n    end.\n\n  Let vec_head_tail_prop n v :  @vec_head_tail_type n v.\n  Proof. induction v; simpl; auto. Qed.\n\n  Fact vec_0_nil (v : vec 0) : v = vec_nil.\n  Proof. apply (vec_head_tail_prop v). Qed.\n\n  Fact vec_head_tail n (v : vec (S n)) : v = vec_cons (vec_head v) (vec_tail v).\n  Proof. apply (vec_head_tail_prop v). Qed.\n\n  Fixpoint vec_pos n (v : vec n) : pos n -> X.\n  Proof.\n    refine (match v with\n      | vec_nil => fun p => _\n      | @vec_cons n x v => fun p => _\n    end); invert pos p.\n    exact x.\n    exact (vec_pos _ v p).\n  Defined.\n\n  Fact vec_pos0 n (v : vec (S n)) : vec_pos v pos0 = vec_head v.\n  Proof. \n    rewrite (vec_head_tail v).\n    reflexivity.\n  Qed.\n  \n  Fact vec_pos_tail n (v : vec (S n)) p : vec_pos (vec_tail v) p = vec_pos v (pos_nxt p).\n  Proof.\n    rewrite vec_head_tail at 2; simpl; auto.\n  Qed.\n  \n  Fact vec_pos1 n (v : vec (S (S n))) : vec_pos v pos1 = vec_head (vec_tail v).\n  Proof.\n    rewrite <- vec_pos0, vec_pos_tail; auto.\n  Qed.\n\n  Fact vec_pos_ext n (v w : vec n) : (forall p, vec_pos v p = vec_pos w p) -> v = w.\n  Proof.\n    revert v w; induction n as [ | n IHn ]; intros v w H.\n    rewrite (vec_0_nil v), (vec_0_nil w); auto.\n    revert H; rewrite (vec_head_tail v), (vec_head_tail w); f_equal.\n    intros H; f_equal.\n    apply (H pos0).\n    apply IHn.\n    intros p; apply (H (pos_nxt p)).\n  Qed.\n\n  Fixpoint vec_set_pos n : (pos n -> X) -> vec n :=\n    match n return (pos n -> X) -> vec n with \n      | 0   => fun _ => vec_nil\n      | S n => fun g => vec_cons (g pos0) (vec_set_pos (fun p => g (pos_nxt p)))\n    end.\n\n  Fact vec_pos_set n (g : pos n -> X) p : vec_pos (vec_set_pos g) p = g p. \n  Proof.\n    revert g p; induction n as [ | n IHn ]; intros g p; pos_inv p; auto.\n    apply IHn.\n  Qed.\n\n  Fixpoint vec_change n (v : vec n) : pos n -> X -> vec n.\n  Proof.\n    refine (match v with\n      | vec_nil         => fun _ _ => vec_nil\n      | @vec_cons n y v => fun p x => _\n    end).\n    pos_inv p.\n    exact (vec_cons x v).\n    apply (vec_cons y), (vec_change _ v p x).\n  Defined.\n\n  Fact vec_change_eq n v p q x : p = q -> vec_pos (@vec_change n v p x) q = x.\n  Proof. \n    intro; subst q; revert p x.\n    induction v; intros p ?; invert pos p; auto.\n  Qed.\n\n  Fact vec_change_neq n v p q x : p <> q -> vec_pos (@vec_change n v p x) q = vec_pos v q.\n  Proof. \n    revert p q x.\n    induction v as [ | n y v IH ]; intros p q x H; invert pos p; invert pos q; auto.\n    destruct H; auto.\n    apply IH; contradict H; subst; auto.\n  Qed.\n\n  Fact vec_change_idem n v p x y : vec_change (@vec_change n v p x) p y = vec_change v p y.\n  Proof.\n    apply vec_pos_ext; intros q.\n    destruct (pos_eq_dec p q).\n    repeat rewrite vec_change_eq; auto.\n    repeat rewrite vec_change_neq; auto.\n  Qed.\n\n  Fact vec_change_same n v p : @vec_change n v p (vec_pos v p) = v.\n  Proof.\n    apply vec_pos_ext; intros q.\n    destruct (pos_eq_dec p q).\n    repeat rewrite vec_change_eq; subst; auto.\n    repeat rewrite vec_change_neq; auto.\n  Qed.\n\n  Variable eq_X_dec : forall x y : X, { x = y } + { x <> y }.\n\n  Fixpoint vec_eq_dec n (u v : vec n) : { u = v } + { u <> v }.\n  Proof.\n    destruct u as [ | n x u ].\n    left.\n    rewrite vec_0_nil; trivial.\n    destruct (eq_X_dec x (vec_head v)) as [ E1 | D ].\n    destruct (vec_eq_dec _ u (vec_tail v)) as [ E2 | D ].\n    left; subst; rewrite <- vec_head_tail; auto.\n    right; contradict D; subst; rewrite <- D; auto.\n    right; contradict D; subst; auto.\n  Defined.\n  \n  Fixpoint vec_list n (v : vec n) := \n    match v with  \n      | vec_nil      => nil\n      | vec_cons x v => x::vec_list v\n    end.\n    \n  Fact vec_list_length n v : length (@vec_list n v) = n.\n  Proof. induction v; simpl; f_equal; auto. Qed.\n\n  Fact vec_list_inv n v x : In x (@vec_list n v) -> exists p, x = vec_pos v p.\n  Proof.\n    induction v as [ | n y v IHl ].\n    intros [].\n    intros [ H | H ]; subst.\n    exists pos0; auto.\n    destruct IHl as (p & Hp); auto.\n    subst; exists (pos_nxt p); auto.\n  Qed.\n\nEnd vector.\n\n(* notations *)\n\nArguments vec_nil { X }.\n\nInfix \"##\" := vec_cons (at level 60, right associativity).\n\nSection vec_app_split.\n\n  Variable (X : Type) (n m : nat).\n\n  Definition vec_app (v : vec X n) (w : vec X m) : vec X (n+m).\n  Proof. \n    apply vec_set_pos; intros p.\n    destruct (pos_both _ _ p) as [ q | q ]; refine (vec_pos _ q); assumption.\n  Defined.\n\n  Definition vec_split (v : vec X (n+m)) : vec X n * vec X m.\n  Proof.\n    split; apply vec_set_pos; intros p; refine (vec_pos v _).\n    + apply pos_left, p.\n    + apply pos_right, p.\n  Defined.\n\n  Fact vec_app_split u : let (v,w) := vec_split u in vec_app v w = u.\n  Proof.\n    case_eq (vec_split u); intros v w; unfold vec_split, vec_app; intros H.\n    injection H; clear H; intros Hw Hv.\n    apply vec_pos_ext; unfold vec_app; simpl.\n    intros p; rewrite vec_pos_set. \n    case_eq (pos_both n m p); intros q Hq.\n    + rewrite <- Hv, vec_pos_set; f_equal.\n      apply f_equal with (f := @pos_lr _ _) in Hq.\n      simpl in Hq; rewrite <- Hq; apply pos_lr_both.\n    + rewrite <- Hw, vec_pos_set; f_equal.\n      apply f_equal with (f := @pos_lr _ _) in Hq.\n      simpl in Hq; rewrite <- Hq; apply pos_lr_both.\n  Qed.\n\n  Fact vec_split_app v w : vec_split (vec_app v w) = (v,w).\n  Proof.\n    unfold vec_split, vec_app; f_equal; apply vec_pos_ext; intros p; repeat rewrite vec_pos_set.\n    + rewrite pos_both_left; auto.\n    + rewrite pos_both_right; auto.\n  Qed.\n\n  Fact vec_pos_app_left v w i : vec_pos (vec_app v w) (pos_left _ i) = vec_pos v i.\n  Proof. unfold vec_app; rewrite vec_pos_set, pos_both_left; auto. Qed.\n\n  Fact vec_pos_app_right v w i : vec_pos (vec_app v w) (pos_right _ i) = vec_pos w i.\n  Proof. unfold vec_app; rewrite vec_pos_set, pos_both_right; auto. Qed.\n\nEnd vec_app_split.\n\nFact vec_app_nil X n v : @vec_app X 0 n vec_nil v = v.\nProof.\n  apply vec_pos_ext; unfold vec_app; simpl; intros p.\n  rewrite vec_pos_set; auto.\nQed.\n\nFact vec_app_cons X n m x v w : @vec_app X (S n) m (x##v) w = x##vec_app v w.\nProof.\n  apply vec_pos_ext; unfold vec_app; intros p.\n  rewrite vec_pos_set; simpl in p.\n  analyse pos p.\n  + simpl; auto.\n  + simpl vec_pos at 3; rewrite vec_pos_set.\n    simpl pos_both.\n    destruct (pos_both n m p); auto.\nQed.\n\nSection vec_map.\n\n  Variable (X Y : Type) (f : X -> Y). \n\n  Fixpoint vec_map n (v : vec X n) :=\n    match v with \n      | vec_nil => vec_nil\n      | x ## v  => f x ## vec_map v \n    end.\n\nEnd vec_map.\n\nSection vec_map2.\n\n  (* Definitions taken from stdlib *)\n  \n  Definition case0 {A} (P:vec A 0 -> Type) (H:P (@vec_nil A)) v:P v :=\n    match v with\n    |vec_nil => H\n    |_ => fun devil => False_ind (@IDProp) devil (* subterm !!! *)\n    end.\n\n  Definition caseS' {A} {n : nat} (v : vec A (S n)) : forall (P : vec A (S n) -> Type)\n                                                      (H : forall h t, P (h ## t)), P v :=\n    match v with\n    | h ## t => fun P H => H h t\n    | _ => fun devil => False_rect (@IDProp) devil\n    end.\n\n  Definition rect2 {A B} (P:forall {n}, vec A n -> vec B n -> Type)\n             (bas : P vec_nil vec_nil) (recvec : forall {n v1 v2}, P v1 v2 ->\n                                                              forall a b, P (a ## v1) (b ## v2)) :=\n    fix rect2_fix {n} (v1 : vec A n) : forall v2 : vec B n, P v1 v2 :=\n      match v1 with\n      | vec_nil => fun v2 => case0 _ bas v2\n      | @vec_cons _ n' h1 t1 => fun v2 =>\n                                 caseS' v2 (fun v2' => P (h1##t1) v2') (fun h2 t2 => recvec (rect2_fix t1 t2) h1 h2)\n      end.\n\n  Definition vec_map2 {A B C} (g:A -> B -> C) :\n    forall (n : nat), vec A n -> vec B n -> vec C n :=\n    @rect2 _ _ (fun n _ _ => vec C n) (@vec_nil C) (fun _ _ _ H a b => (g a b) ## H).\n  Global Arguments vec_map2 {A B C} g {n} v1 v2.\n\nEnd vec_map2.\n\nFact vec_pos_map X Y (f : X -> Y) n (v : vec X n) p : vec_pos (vec_map f v) p = f (vec_pos v p).\nProof.\n  revert p; induction v; intros p; pos_inv p; simpl; auto.\nQed.\n\n  \nSection vec_plus.\n\n  Variable n : nat.\n\n  Definition vec_plus (v w : vec nat n) := vec_set_pos (fun p => vec_pos v p + vec_pos w p).\n  Definition vec_zero : vec nat n := vec_set_pos (fun _ => 0).\n  \n  Fact vec_pos_plus v w p : vec_pos (vec_plus v w) p = vec_pos v p + vec_pos w p.\n  Proof.\n    unfold vec_plus; rewrite vec_pos_set; auto.\n  Qed.\n\n  Fact vec_zero_plus v : vec_plus vec_zero v = v.\n  Proof. \n    apply vec_pos_ext.\n    intros p; unfold vec_zero, vec_plus. \n    repeat rewrite vec_pos_set; auto.\n  Qed.\n  \n  Fact vec_zero_spec p : vec_pos vec_zero p = 0.\n  Proof. unfold vec_zero; rewrite vec_pos_set; trivial. Qed.\n\n  Fact vec_plus_comm v w : vec_plus v w = vec_plus w v.\n  Proof.\n    apply vec_pos_ext.\n    intros p; unfold vec_zero, vec_plus.\n    repeat rewrite vec_pos_set; omega.\n  Qed.\n\n  Fact vec_plus_assoc u v w : vec_plus u (vec_plus v w) = vec_plus (vec_plus u v) w.\n  Proof.\n    apply vec_pos_ext.\n    intros p; unfold vec_zero, vec_plus.\n    repeat rewrite vec_pos_set; omega.\n  Qed.\n\n  Fact vec_plus_is_zero u v : vec_zero = vec_plus u v -> u = vec_zero /\\ v = vec_zero.\n  Proof.\n   unfold vec_zero, vec_plus; intros H; split; apply vec_pos_ext;\n   intros p; apply f_equal with (f := fun v => vec_pos v p) in H;\n   repeat rewrite vec_pos_set in * |- *; omega.\n  Qed.\n  \n  Definition vec_one p : vec _ n := vec_set_pos (fun q => if pos_eq_dec p q then 1 else 0).\n  \n  Fact vec_one_spec_eq p q : p = q -> vec_pos (vec_one p) q = 1.\n  Proof.\n    intros [].\n    unfold vec_one; rewrite vec_pos_set.\n    destruct (pos_eq_dec p p) as [ | [] ]; auto.\n  Qed.\n  \n  Fact vec_one_spec_neq p q : p <> q -> vec_pos (vec_one p) q = 0.\n  Proof.\n    intros H.\n    unfold vec_one; rewrite vec_pos_set.\n    destruct (pos_eq_dec p q) as [ | ]; auto.\n    destruct H; auto.\n  Qed.\n  \nEnd vec_plus.\n\nArguments vec_plus {n}.\nArguments vec_zero {n}.\nArguments vec_one {n}.\n\nReserved Notation \" e '#>' x \" (at level 58).\nReserved Notation \" e [ v / x ] \" (at level 57, v at level 0, x at level 0, left associativity).\n\nLocal Notation \" e '#>' x \" := (vec_pos e x) (at level 58).\nLocal Notation \" e [ v / x ] \" := (vec_change e x v) (at level 57, v at level 0, x at level 0, left associativity).\n\nTactic Notation \"rew\" \"vec\" :=\n  repeat lazymatch goal with \n    |              |- context[ _[_/?x]#>?x ] => rewrite vec_change_eq with (p := x) (1 := eq_refl)\n    | _ : ?x = ?y  |- context[ _[_/?x]#>?y ] => rewrite vec_change_eq with (p := x) (q := y)\n    | _ : ?y = ?x  |- context[ _[_/?x]#>?y ] => rewrite vec_change_eq with (p := x) (q := y)\n    | _ : ?x <> ?y |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y)\n    | _ : ?y <> ?x |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y)\n    |              |- context[ vec_pos vec_zero ?x ] => rewrite vec_zero_spec with (p := x)\n    |              |- context[ vec_pos (vec_one ?x) ?x ] => rewrite vec_one_spec_eq with (p := x) (1 := eq_refl)\n    | _ : ?x = ?y  |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_eq with (p := x) (q := y)\n    | _ : ?y = ?x  |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_eq with (p := x) (q := y)\n    | _ : ?x <> ?y |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_neq with (p := x) (q := y)\n    | _ : ?y <> ?x |- context[ vec_pos (vec_one ?x) ?y ] => rewrite vec_one_spec_neq with (p := x) (q := y)\n    | |- context[ _[_/?x][_/?x] ] => rewrite vec_change_idem with (p := x) \n    | |- context[ ?v[(?v#>?x)/?x] ] => rewrite vec_change_same with (p := x)\n    | |- context[ _[_/?x]#>?y ] => rewrite vec_change_neq with (p := x) (q := y); [ | discriminate ]\n    | |- context[ vec_plus vec_zero ?x ] => rewrite vec_zero_plus with (v := x)\n    | |- context[ vec_plus ?x vec_zero ] => rewrite (vec_plus_comm x vec_zero); rewrite vec_zero_plus with (v := x)\n    | |- vec_plus ?x ?y = vec_plus ?y ?x => apply vec_plus_comm\n  end; auto.\n\nTactic Notation \"vec\" \"split\" hyp(v) \"with\" ident(n) :=\n  rewrite (vec_head_tail v); generalize (vec_head v) (vec_tail v); clear v; intros n v.\n\nTactic Notation \"vec\" \"nil\" hyp(v) := rewrite (vec_0_nil v).\n\nFact vec_zero_S n : @vec_zero (S n) = 0##vec_zero.\nProof. auto. Qed.\n\nFact vec_one_fst n : @vec_one (S n) pos0 = 1##vec_zero.\nProof.\n  apply vec_pos_ext.\n  intros p; pos_inv p; rew vec.\nQed.\n\nFact vec_one_nxt n p : @vec_one (S n) (pos_nxt p) = 0##vec_one p.\nProof.\n  apply vec_pos_ext.\n  unfold vec_one.\n  intros q; rewrite vec_pos_set.\n  pos_inv q.\n  simpl; auto.\n  rewrite <- vec_pos_tail.\n  simpl vec_tail.\n  rewrite vec_pos_set.\n  destruct (pos_eq_dec p q) as [ | C ].\n  subst.\n  destruct (pos_eq_dec (pos_nxt q) (pos_nxt q)) as [ | [] ]; auto.\n  destruct (pos_eq_dec (pos_nxt p) (pos_nxt q)) as [ | ]; auto.\n  destruct C; apply pos_nxt_inj; auto.\nQed.\n\nFact vec_plus_cons n x v y w : @vec_plus (S n) (x##v) (y##w) = x+y ## vec_plus v w.\nProof.\n  apply vec_pos_ext; unfold vec_plus.\n  intros p; pos_inv p; repeat (rewrite vec_pos_set; simpl; auto).\nQed.\n\nFact vec_change_succ n v p : v[(S (v#>p))/p] = @vec_plus n (vec_one p) v.\nProof.\n  apply vec_pos_ext.\n  intros q.\n  destruct (pos_eq_dec p q); rew vec;\n  rewrite vec_pos_plus; rew vec; subst; auto.\nQed.\n\nFact vec_change_pred n v p u : v#>p = S u -> v = @vec_plus n (vec_one p) (v[u/p]).\nProof.\n  intros Hu.\n  apply vec_pos_ext.\n  intros q.\n  destruct (pos_eq_dec p q); rew vec;\n  rewrite vec_pos_plus; rew vec; subst; auto.\nQed.\n\nFixpoint vec_sum n (v : vec nat n) := \n  match v with \n    | vec_nil       => 0\n    | vec_cons x w  => x + vec_sum w\n  end.\n  \nFact vec_sum_plus n v w : @vec_sum n (vec_plus v w) = vec_sum v + vec_sum w.\nProof.\n  revert w; induction v; intros w.\n  rewrite (vec_0_nil (vec_plus _ _)), (vec_0_nil w); auto.\n  rewrite (vec_head_tail w), vec_plus_cons; simpl.\n  rewrite IHv; omega.\nQed.\n\nFact vec_sum_zero n : @vec_sum n vec_zero = 0.\nProof. induction n; simpl; auto. Qed.\n\nFact vec_sum_one n p : @vec_sum n (vec_one p) = 1.\nProof.\n  revert p; induction n; intros p.\n  pos_inv p.\n  pos_inv p.\n  rewrite vec_one_fst.\n  simpl; f_equal; apply vec_sum_zero.\n  rewrite vec_one_nxt.\n  unfold vec_sum; fold vec_sum.\n  rewrite IHn; auto.\nQed.\n  \nFact vec_sum_is_zero n v : @vec_sum n v = 0 -> v = vec_zero.\nProof.\n  induction v; simpl; auto.\n  simpl; rewrite vec_zero_S; intros; f_equal.\n  omega.\n  apply IHv; omega.\nQed.\n\nFact vec_sum_is_nzero n v : 0 < @vec_sum n v -> { p : _ & { w | v = vec_plus (vec_one p) w } }.\nProof.\n  induction v as [ | n x v IHv ]; intros Hv; simpl in Hv.\n  omega.\n  destruct x as [ | x ].\n  apply IHv in Hv.\n  destruct Hv as (p & w & Hw).\n  exists (pos_nxt p), (0##w); rewrite vec_one_nxt.\n  rewrite vec_plus_cons; f_equal; auto.\n  exists pos0, (x##v).\n  rewrite vec_one_fst, vec_plus_cons; rew vec.\nQed.\n\nSection vec_nat_induction.\n\n  (* Specialized induction on vec nat n, with constant n *)\n\n  Variable (n : nat) (P : vec nat n -> Type).\n  \n  Hypothesis HP0 : P vec_zero.\n  Hypothesis HP1 : forall p, P (vec_one p).\n  Hypothesis HP2 : forall v w, P v -> P w -> P (vec_plus v w).\n  \n  Theorem vec_nat_induction v : P v.\n  Proof.\n    induction v as [ v IHv ] using (measure_rect (@vec_sum n)).\n    case_eq (vec_sum v).\n    \n    intros Hv.\n    apply vec_sum_is_zero in Hv; subst; auto.\n    \n    intros x Hx.\n    destruct (vec_sum_is_nzero v) as (p & w & Hw).\n    omega.\n    subst.\n    apply HP2; auto.\n    apply IHv.\n    rewrite vec_sum_plus, vec_sum_one; auto.\n  Qed.\n  \nEnd vec_nat_induction.\n\nSection vec_map_list.\n\n  Variable X : Type.\n\n  (* morphism between vec nat n and (list X)/~p *)\n\n  Fixpoint vec_map_list X n v : (pos n -> X) -> list X :=\n    match v in vec _ m return (pos m -> _) -> _ with\n      | vec_nil => fun _ => nil\n      | a##v    => fun f => list_repeat (f pos0) a ++ vec_map_list v (fun p => f (pos_nxt p))\n    end.\n\n  Fact vec_map_list_zero n f : vec_map_list (@vec_zero n) f = @nil X.\n  Proof. revert f; induction n; intros f; simpl; auto. Qed.\n\n  Fact vec_map_list_one n p f : vec_map_list (@vec_one n p) f = f p :: @nil X.\n  Proof.\n    revert f; induction p; intro.\n    rewrite vec_one_fst; simpl; rewrite vec_map_list_zero; auto.\n    rewrite vec_one_nxt; simpl; rewrite IHp; auto.\n  Qed.\n\n  (* The morphism *)\n\n  Fact vec_map_list_plus n v w f : @vec_map_list X n (vec_plus v w) f ~p vec_map_list v f ++ vec_map_list w f.\n  Proof.\n    revert v w f; induction n as [ | n IHn ]; intros v w f.\n    rewrite (vec_0_nil (vec_plus v w)), (vec_0_nil v), (vec_0_nil w); simpl; auto.\n    rewrite (vec_head_tail v), (vec_head_tail w), vec_plus_cons.\n    generalize (vec_head v) (vec_tail v) (vec_head w) (vec_tail w); clear v w; intros x v y w.\n    simpl.\n    rewrite list_repeat_plus.\n    solve list eq; apply Permutation_app; auto.\n    apply Permutation_trans with (list_repeat (f pos0) y \n                               ++ vec_map_list v (fun p => f (pos_nxt p)) \n                               ++ vec_map_list w (fun p => f (pos_nxt p))).\n    apply Permutation_app; auto.\n    do 2 rewrite <- app_ass.\n    apply Permutation_app; auto.\n    apply Permutation_app_comm.\n  Qed.\n\nEnd vec_map_list.\n\nFact map_vec_map_list X Y (f : X -> Y) n v g : map f (@vec_map_list _ n v g) = vec_map_list v (fun p => f (g p)).\nProof.\n  revert g; induction v; intro; simpl; auto.\n  rewrite map_app; f_equal; auto.\n  rewrite map_list_repeat; auto.\nQed.\n\nDefinition list_vec X (l : list X) : { v : vec X (length l) | vec_list v = l }.\nProof.\n  induction l as [ | x l (v & Hv) ]; simpl.\n  exists vec_nil; auto.\n  exists (x##v); simpl; f_equal; auto.\nQed.\n\nFact vec_reif X n (R : pos n -> X -> Prop) : (forall p, ex (R p)) -> exists v, forall p, R p (vec_pos v p).\nProof.\n  intros H.\n  apply pos_reification in H.\n  destruct H as (f & Hf).\n  exists (vec_set_pos f).\n  intro; rewrite vec_pos_set; trivial.\nQed.\n\nFact vec_reif_t X n (R : pos n -> X -> Prop) : (forall p, sig (R p)) -> { v | forall p, R p (vec_pos v p) }.\nProof.\n  intros H.\n  apply pos_reif_t in H.\n  destruct H as (f & Hf).\n  exists (vec_set_pos f).\n  intro; rewrite vec_pos_set; trivial.\nQed.\n\nSection fun2vec.\n\n  Variable X : Type.\n\n  Fixpoint fun2vec i n f : vec X _ :=\n    match n with \n      | 0   => vec_nil\n      | S n => f i##fun2vec (S i) n f\n    end.\n\n  Fact fun2vec_id i n f : fun2vec i n f = vec_set_pos (fun p => f (i+pos2nat p)).\n  Proof.\n    revert i; induction n as [ | n IHn ]; intros i; simpl; f_equal; auto.\n    rewrite IHn.\n    apply vec_pos_ext; intros; do 2 rewrite vec_pos_set; f_equal.\n    rewrite pos2nat_nxt; omega.\n  Qed.\n\n  Fact fun2vec_lift i n f : fun2vec i n (fun j => f (S j)) = fun2vec (S i) n f.\n  Proof. revert i f; induction n; intros; simpl; f_equal; auto. Qed.\n\n  Fact vec_pos_fun2vec i n f p : vec_pos (fun2vec i n f) p = f (i+pos2nat p).\n  Proof. rewrite fun2vec_id, vec_pos_set; auto. Qed.\n\n  Definition vec2fun n (v : vec X n) x i := \n    match le_lt_dec n i with\n      | left  _ => x\n      | right H => vec_pos v (nat2pos H)\n    end.\n\n  Fact fun2vec_vec2fun n v x : fun2vec 0 n (@vec2fun n v x) = v.\n  Proof.\n    apply vec_pos_ext.\n    intros p; rewrite vec_pos_fun2vec; simpl.\n    unfold vec2fun.\n    generalize (pos2nat_prop p).\n    destruct (le_lt_dec n (pos2nat p)); try omega. \n    rewrite nat2pos_pos2nat; auto.\n  Qed.\n\n  Fact vec2fun_fun2vec n f x i : i < n -> @vec2fun n (fun2vec 0 n f) x i = f i.\n  Proof.\n    intros H.\n    unfold vec2fun.\n    destruct (le_lt_dec n i); try omega.\n    rewrite vec_pos_fun2vec, pos2nat_nat2pos; auto.\n  Qed. \n\nEnd fun2vec.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/Shared/Libs/DLW/Vec/vec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.727904269407524}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Main.\n\nLocal Open Scope morphism_scope.\n\nSection PullBack.\n  Context {C : Category} {a b x : C} (f : a –≻ x) (g : b –≻ x).\n\n  (**\nGiven two arrows f : a -> x and g : b -> x, their pullback is an object p\ntogether with two arrows π₁ : p -> a and π₂ : p -> b such that the following\ndiagram commutes:\n\n#\n<pre>\n        π₂   \n   p ————————–> b\n   |            |\nπ₁ |            | g\n   |            |\n   ↓            ↓\n   a —————————> x\n        f\n</pre>\n#\n\nProvided that for any object q and arrows p1 : q -> a and p2 : q -> b that the\nfollowing diagram commutes:\n\n#\n<pre>\n        p2   \n   q ————————–> b\n   |            |\np1 |            | g\n   |            |\n   ↓            ↓\n   a —————————> x\n        f\n</pre>\n#\n\nthere is a unique arrow h : q -> p that makes the following diagram commute:\n\n#\n<pre>\n                p2\n      q ———————————————————–\n      |  \\                   |\n      |    \\ ∃!h             |\n      |      \\               |\n      |        ↘     π₂      ↓\n  p1  |         p ————————–> b\n      |         |            |\n      |      π₁ |            | g\n      |         |            |\n      |         ↓            ↓\n       ——————–> a —————————> x\n                    f\n</pre>\n#\n\nWe usually use a half square in the corner of p to denote p is the pullback of\nf and g. Like so:\n#\n<pre>\n        π₂   \n   p ————————–> b\n   |__|         |\nπ₁ |            | g\n   |            |\n   ↓            ↓\n   a —————————> x\n        f\n</pre>\n#\n*)\n  Record PullBack : Type :=\n    {\n      pullback : C;\n\n      pullback_morph_1 : pullback –≻ a;\n\n      pullback_morph_2 : pullback –≻ b;\n\n      pullback_morph_com : f ∘ pullback_morph_1 = g ∘ pullback_morph_2;\n\n      pullback_morph_ex (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b) :\n        f ∘ pm1 = g ∘ pm2 → p' –≻ pullback;\n\n      pullback_morph_ex_com_1 (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)\n                              (pmc : f ∘ pm1 = g ∘ pm2)\n      :\n        pullback_morph_1 ∘ (pullback_morph_ex p' pm1 pm2 pmc) = pm1;\n\n      pullback_morph_ex_com_2 (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)\n                              (pmc : f ∘ pm1 = g ∘ pm2)\n      :\n        pullback_morph_2 ∘ (pullback_morph_ex p' pm1 pm2 pmc) = pm2;\n\n      pullback_morph_ex_unique\n        (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)\n        (pmc : f ∘ pm1 = g ∘ pm2) (u u' : p' –≻ pullback) :\n        pullback_morph_1 ∘ u = pm1 →\n        pullback_morph_2 ∘ u = pm2 →\n        pullback_morph_1 ∘ u' = pm1 →\n        pullback_morph_2 ∘ u' = pm2 → u = u'\n    }.\n\n  Coercion pullback : PullBack >-> Obj.\n\n  (** Pullbacks are unique up to isomorphism. *)\n  Theorem PullBack_iso (p1 p2 : PullBack) : (p1 ≃ p2)%isomorphism.\n  Proof.\n    apply\n      (\n        Build_Isomorphism\n          _\n          _\n          _\n          (\n            pullback_morph_ex\n              p2\n              _\n              (pullback_morph_1 p1)\n              (pullback_morph_2 p1)\n              (pullback_morph_com p1)\n          )\n          (\n            pullback_morph_ex\n              p1\n              _\n              (pullback_morph_1 p2)\n              (pullback_morph_2 p2)\n              (pullback_morph_com p2)\n          )\n      ); eapply pullback_morph_ex_unique;\n    match goal with\n      | [|- _ ∘ id = _] => simpl_ids; trivial\n      | _ => idtac\n    end; try apply pullback_morph_com;\n    rewrite <- assoc;\n    repeat (rewrite pullback_morph_ex_com_1 || rewrite pullback_morph_ex_com_2);\n    trivial.\n  Qed.\n\nEnd PullBack.\n\n(** The predicate form of pullback: *)\nSection is_PullBack.\n  Context {C : Category} {a b x pb : C} (p1 : pb –≻ a)\n          (p2 : pb –≻ b) (f : a –≻ x) (g : b –≻ x).\n\n  Local Open Scope morphism_scope.\n  \n  Record is_PullBack : Type :=\n    {\n      is_pullback_morph_com : f ∘ p1 = g ∘ p2;\n\n      is_pullback_morph_ex (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b) :\n        f ∘ pm1 = g ∘ pm2 → p' –≻ pb;\n\n      is_pullback_morph_ex_com_1 (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)\n                                 (pmc : f ∘ pm1 = g ∘ pm2)\n      :\n        p1 ∘ (is_pullback_morph_ex p' pm1 pm2 pmc) = pm1;\n\n      is_pullback_morph_ex_com_2 (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)\n                                 (pmc : f ∘ pm1 = g ∘ pm2)\n      :\n        p2 ∘ (is_pullback_morph_ex p' pm1 pm2 pmc) = pm2;\n\n      is_pullback_morph_ex_unique\n        (p' : Obj) (pm1 : p' –≻ a) (pm2 : p' –≻ b)\n        (pmc : f ∘ pm1 = g ∘ pm2) (u u' : p' –≻ pb) :\n        p1 ∘ u = pm1 →\n        p2 ∘ u = pm2 →\n        p1 ∘ u' = pm1 →\n        p2 ∘ u' = pm2 → u = u'\n    }.\n\nEnd is_PullBack.\n\nDefinition Has_PullBacks (C : Category) : Type :=\n  ∀ (a b c : C) (f : a –≻ c) (g : b –≻ c), PullBack f g.\n\nExisting Class Has_PullBacks.\n\nArguments PullBack _ {_ _ _} _ _, {_ _ _ _} _ _.\nArguments pullback {_ _ _ _ _ _} _.\nArguments pullback_morph_1 {_ _ _ _ _ _} _.\nArguments pullback_morph_2 {_ _ _ _ _ _} _.\nArguments pullback_morph_com {_ _ _ _ _ _} _.\nArguments pullback_morph_ex {_ _ _ _ _ _} _ _ _ _ _.\nArguments pullback_morph_ex_com_1 {_ _ _ _ _ _} _ _ _ _ _.\nArguments pullback_morph_ex_com_2 {_ _ _ _ _ _} _ _ _ _ _.\nArguments pullback_morph_ex_unique {_ _ _ _ _ _} _ _ _ _ _ _ _ _ _ _ _.\n\nArguments is_PullBack _ { _ _ _ _} _ _ _ _, {_ _ _ _ _ } _ _ _ _.\n\nArguments is_pullback_morph_com {_ _ _ _ _ _ _ _ _} _.\nArguments is_pullback_morph_ex {_ _ _ _ _ _ _ _ _} _ _ _ _ _.\nArguments is_pullback_morph_ex_com_1 {_ _ _ _ _ _ _ _ _} _ _ _ _ _.\nArguments is_pullback_morph_ex_com_2 {_ _ _ _ _ _ _ _ _} _ _ _ _ _.\nArguments is_pullback_morph_ex_unique {_ _ _ _ _ _ _ _ _} _ _ _ _ _ _ _ _ _ _ _.\n\nSection is_PullBack_PullBack.\n  Context {C : Category} {a b x pb : C} {p1 : pb –≻ a} {p2 : pb –≻ b} {f : a –≻ x}\n          {g : b –≻ x} (iPB : is_PullBack p1 p2 f g).\n\n  (** The predicate form of pullbacks implies the compact from of pullbacks.\n       See above for details.*)\n  Definition is_PullBack_PullBack : PullBack f g :=\n    {|\n      pullback := pb;\n      pullback_morph_1 := p1;\n      pullback_morph_2 := p2;\n      pullback_morph_com := is_pullback_morph_com iPB;\n      pullback_morph_ex := fun p' pm1 pm2 => is_pullback_morph_ex iPB p' pm1 pm2;\n      pullback_morph_ex_com_1 :=\n        fun p' pm1 pm2 pmc => is_pullback_morph_ex_com_1 iPB p' pm1 pm2 pmc;\n      pullback_morph_ex_com_2 :=\n        fun p' pm1 pm2 pmc => is_pullback_morph_ex_com_2 iPB p' pm1 pm2 pmc;\n      pullback_morph_ex_unique :=\n        fun p' pm1 pm2 pmc u u' => is_pullback_morph_ex_unique iPB p' pm1 pm2 pmc u u'\n    |}.\n\nEnd is_PullBack_PullBack.\n\nSection PullBack_is_PullBack.\n  Context {C : Category} {a b x : C} {f : a –≻ x}\n          {g : b –≻ x} (PB : PullBack f g).\n\n  (** Compact form of pullback implies the predicate form of pullback.\n      See above for details. *)\n  Definition PullBack_is_PullBack :\n    is_PullBack (pullback_morph_1 PB) (pullback_morph_2 PB) f g :=\n    {|\n      is_pullback_morph_com := pullback_morph_com PB;\n      is_pullback_morph_ex := fun p' pm1 pm2 => pullback_morph_ex PB p' pm1 pm2;\n      is_pullback_morph_ex_com_1 :=\n        fun p' pm1 pm2 pmc => pullback_morph_ex_com_1 PB p' pm1 pm2 pmc;\n      is_pullback_morph_ex_com_2 :=\n        fun p' pm1 pm2 pmc => pullback_morph_ex_com_2 PB p' pm1 pm2 pmc;\n      is_pullback_morph_ex_unique :=\n        fun p' pm1 pm2 pmc u u' => pullback_morph_ex_unique PB p' pm1 pm2 pmc u u'\n    |}.\n\nEnd PullBack_is_PullBack.\n  \n(** PushOut is the dual of PullBack *)\nDefinition PushOut (C : Category) := @PullBack (C^op).\n\nArguments PushOut _ {_ _ _} _ _, {_ _ _ _} _ _.\n\nDefinition Has_PushOuts (C : Category) : Type :=\n  ∀ (a b c : C) (f : c –≻ a) (g : c –≻ b), PushOut f g.\n\nExisting Class Has_PushOuts.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/Categories/Basic_Cons/PullBack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7279042640183596}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Well-founded relations and natural numbers *)\n\nRequire Import PeanoNat Lt.\n\nLocal Open Scope nat_scope.\n\nImplicit Types m n p : nat.\n\nSection Well_founded_Nat.\n\nVariable A : Type.\n\nVariable f : A -> nat.\nDefinition ltof (a b:A) := f a < f b.\nDefinition gtof (a b:A) := f b > f a.\n\nTheorem well_founded_ltof : well_founded ltof.\nProof.\n  assert (H : forall n (a:A), f a < n -> Acc ltof a).\n  { induction n.\n    - intros; absurd (f a < 0); auto with arith.\n    - intros a Ha. apply Acc_intro. unfold ltof at 1. intros b Hb.\n      apply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }\n  intros a. apply (H (S (f a))). auto with arith.\nDefined.\n\nTheorem well_founded_gtof : well_founded gtof.\nProof.\n  exact well_founded_ltof.\nDefined.\n\n(** It is possible to directly prove the induction principle going\n   back to primitive recursion on natural numbers ([induction_ltof1])\n   or to use the previous lemmas to extract a program with a fixpoint\n   ([induction_ltof2])\n\nthe ML-like program for [induction_ltof1] is :\n[[\nlet induction_ltof1 f F a =\n  let rec indrec n k =\n    match n with\n    | O -> error\n    | S m -> F k (indrec m)\n  in indrec (f a + 1) a\n]]\n\nthe ML-like program for [induction_ltof2] is :\n[[\n   let induction_ltof2 F a = indrec a\n   where rec indrec a = F a indrec;;\n]]\n*)\n\nTheorem induction_ltof1 :\n  forall P:A -> Set,\n    (forall x:A, (forall y:A, ltof y x -> P y) -> P x) -> forall a:A, P a.\nProof.\n  intros P F.\n  assert (H : forall n (a:A), f a < n -> P a).\n  { induction n.\n    - intros; absurd (f a < 0); auto with arith.\n    - intros a Ha. apply F. unfold ltof. intros b Hb.\n      apply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }\n  intros a. apply (H (S (f a))). auto with arith.\nDefined.\n\nTheorem induction_gtof1 :\n  forall P:A -> Set,\n    (forall x:A, (forall y:A, gtof y x -> P y) -> P x) -> forall a:A, P a.\nProof.\n  exact induction_ltof1.\nDefined.\n\nTheorem induction_ltof2 :\n  forall P:A -> Set,\n    (forall x:A, (forall y:A, ltof y x -> P y) -> P x) -> forall a:A, P a.\nProof.\n  exact (well_founded_induction well_founded_ltof).\nDefined.\n\nTheorem induction_gtof2 :\n  forall P:A -> Set,\n    (forall x:A, (forall y:A, gtof y x -> P y) -> P x) -> forall a:A, P a.\nProof.\n  exact induction_ltof2.\nDefined.\n\n(** If a relation [R] is compatible with [lt] i.e. if [x R y => f(x) < f(y)]\n    then [R] is well-founded. *)\n\nVariable R : A -> A -> Prop.\n\nHypothesis H_compat : forall x y:A, R x y -> f x < f y.\n\nTheorem well_founded_lt_compat : well_founded R.\nProof.\n  assert (H : forall n (a:A), f a < n -> Acc R a).\n  { induction n.\n    - intros; absurd (f a < 0); auto with arith.\n    - intros a Ha. apply Acc_intro. intros b Hb.\n      apply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }\n  intros a. apply (H (S (f a))). auto with arith.\nDefined.\n\nEnd Well_founded_Nat.\n\nLemma lt_wf : well_founded lt.\nProof.\n  exact (well_founded_ltof nat (fun m => m)).\nDefined.\n\nLemma lt_wf_rec1 :\n  forall n (P:nat -> Set), (forall n, (forall m, m < n -> P m) -> P n) -> P n.\nProof.\n  exact (fun p P F => induction_ltof1 nat (fun m => m) P F p).\nDefined.\n\nLemma lt_wf_rec :\n  forall n (P:nat -> Set), (forall n, (forall m, m < n -> P m) -> P n) -> P n.\nProof.\n  exact (fun p P F => induction_ltof2 nat (fun m => m) P F p).\nDefined.\n\nLemma lt_wf_ind :\n  forall n (P:nat -> Prop), (forall n, (forall m, m < n -> P m) -> P n) -> P n.\nProof.\n  intro p; intros; elim (lt_wf p); auto with arith.\nQed.\n\nLemma gt_wf_rec :\n  forall n (P:nat -> Set), (forall n, (forall m, n > m -> P m) -> P n) -> P n.\nProof.\n  exact lt_wf_rec.\nDefined.\n\nLemma gt_wf_ind :\n  forall n (P:nat -> Prop), (forall n, (forall m, n > m -> P m) -> P n) -> P n.\nProof lt_wf_ind.\n\nLemma lt_wf_double_rec :\n forall P:nat -> nat -> Set,\n   (forall n m,\n     (forall p q, p < n -> P p q) ->\n     (forall p, p < m -> P n p) -> P n m) -> forall n m, P n m.\nProof.\n  intros P Hrec p; pattern p; apply lt_wf_rec.\n  intros n H q; pattern q; apply lt_wf_rec; auto with arith.\nDefined.\n\nLemma lt_wf_double_ind :\n  forall P:nat -> nat -> Prop,\n    (forall n m,\n      (forall p (q:nat), p < n -> P p q) ->\n      (forall p, p < m -> P n p) -> P n m) -> forall n m, P n m.\nProof.\n  intros P Hrec p; pattern p; apply lt_wf_ind.\n  intros n H q; pattern q; apply lt_wf_ind; auto with arith.\nQed.\n\nHint Resolve lt_wf: arith.\nHint Resolve well_founded_lt_compat: arith.\n\nSection LT_WF_REL.\n  Variable A : Set.\n  Variable R : A -> A -> Prop.\n\n  (* Relational form of inversion *)\n  Variable F : A -> nat -> Prop.\n  Definition inv_lt_rel x y := exists2 n, F x n & (forall m, F y m -> n < m).\n\n  Hypothesis F_compat : forall x y:A, R x y -> inv_lt_rel x y.\n  Remark acc_lt_rel : forall x:A, (exists n, F x n) -> Acc R x.\n  Proof.\n    intros x [n fxn]; generalize dependent x.\n    pattern n; apply lt_wf_ind; intros.\n    constructor; intros.\n    destruct (F_compat y x) as (x0,H1,H2); trivial.\n    apply (H x0); auto.\n  Qed.\n\n  Theorem well_founded_inv_lt_rel_compat : well_founded R.\n  Proof.\n    constructor; intros.\n    case (F_compat y a); trivial; intros.\n    apply acc_lt_rel; trivial.\n    exists x; trivial.\n  Qed.\n\nEnd LT_WF_REL.\n\nLemma well_founded_inv_rel_inv_lt_rel :\n  forall (A:Set) (F:A -> nat -> Prop), well_founded (inv_lt_rel A F).\nProof.\n  intros; apply (well_founded_inv_lt_rel_compat A (inv_lt_rel A F) F); trivial.\nQed.\n\n(** A constructive proof that any non empty decidable subset of\n    natural numbers has a least element *)\n\nSet Implicit Arguments.\n\nRequire Import Le.\nRequire Import Compare_dec.\nRequire Import Decidable.\n\nDefinition has_unique_least_element (A:Type) (R:A->A->Prop) (P:A->Prop) :=\n  exists! x, P x /\\ forall x', P x' -> R x x'.\n\nLemma dec_inh_nat_subset_has_unique_least_element :\n  forall P:nat->Prop, (forall n, P n \\/ ~ P n) ->\n    (exists n, P n) -> has_unique_least_element le P.\nProof.\n  intros P Pdec (n0,HPn0).\n  assert\n    (forall n, (exists n', n'<n /\\ P n' /\\ forall n'', P n'' -> n'<=n'')\n               \\/ (forall n', P n' -> n<=n')).\n  { induction n.\n    - right. intros. apply Nat.le_0_l.\n    - destruct IHn as [(n' & IH1 & IH2)|IH].\n      + left. exists n'; auto with arith.\n      + destruct (Pdec n) as [HP|HP].\n        * left. exists n; auto with arith.\n        * right. intros n' Hn'.\n          apply Nat.le_neq; split; auto. intros <-. auto. }\n  destruct (H n0) as [(n & H1 & H2 & H3)|H0]; [exists n | exists n0];\n   repeat split; trivial;\n   intros n' (HPn',Hn'); apply Nat.le_antisymm; auto.\nQed.\n\nUnset Implicit Arguments.\n\nNotation iter_nat n A f x := (nat_rect (fun _ => A) x (fun _ => f) n) (only parsing).\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Arith/Wf_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7278818319966599}}
{"text": "\n(* 5 Infinite Data and Proofs *)\n\nRequire Import List Cpdt.CpdtTactics.\nRequire Import Arith.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n(* 5.1 Computing with Infinite Data *)\n\nSection stream.\n  Variable A : Type.\n  CoInductive stream : Type :=\n  | Cons : A -> stream -> stream\n  .\nEnd stream.\n\n(*\nRather, whereas recursive definitions were necessary to use values of recursive\ninductive types effectively, here we find that we need co-recursive definitions\nto build values of co-inductive types effectively.\n*)\n\nCoFixpoint zeroes : stream nat := Cons 0 zeroes.\n\nCoFixpoint trues_falses : stream bool := Cons true falses_trues\nwith falses_trues : stream bool := Cons false trues_falses\n.\n\nFixpoint approx A (s : stream A) (n : nat) : list A :=\n  match n with\n  | O => nil\n  | S n' =>\n    match s with\n    | Cons h t => h :: approx t n'\n    end\n  end\n.\n\nEval simpl in approx zeroes 10.\nEval simpl in approx trues_falses 10.\n\nSection map.\n  Variables A B : Type.\n  Variable f : A -> B .\n  CoFixpoint map (s : stream A) : stream B :=\n    match s with\n      | Cons h t => Cons (f h) (map t)\n    end.\nEnd map.\n\nSection interleave.\n  Variable A : Type.\n  CoFixpoint interleave (s1 s2 : stream A) : stream A :=\n    match s1,s2 with\n    | Cons h1 t1 , Cons h2 t2 => Cons h1 (Cons h2 (interleave t1 t2))\n    end.\nEnd interleave.\n\nDefinition tl A (s : stream A) : stream A :=\n  match s with\n  | Cons _ s' => s'\n  end\n.\n\n(* 5.2 Infinite Proofs *)\n\nCoFixpoint ones : stream nat := Cons 1 ones.\nDefinition ones' := map S zeroes.\n\nTheorem ones_eq : ones = ones'.\nAbort.\n\nSection stream_eq.\n  Variable A : Type.\n  CoInductive stream_eq : stream A -> stream A -> Prop :=\n  | Stream_eq : forall h t1 t2,\n      stream_eq t1 t2 -> stream_eq (Cons h t1) (Cons h t2).\nEnd stream_eq.\n\nTheorem oneS_eq : stream_eq ones ones'.\n                    cofix.\nAbort.\n\nDefinition frob A (s : stream A) : stream A :=\n  match s with\n  | Cons h t => Cons h t\n  end.\n\nTheorem frob_eq : forall A (s : stream A) , s = frob s.\n                                              destruct s; reflexivity.\nQed.\n\nTheorem ones_eq : stream_eq ones ones'.\n                    cofix.\n                    rewrite (frob_eq ones).\n                    rewrite (frob_eq ones').\n                    simpl.\n                    constructor.\n                    assumption.\nQed.\n\nTheorem ones_eq' : stream_eq ones ones'.\n                     cofix; crush.\n                     (* Guarded ** TODO: Figure out guarded. *)\nAbort.\n\nDefinition hd A (s : stream A) : A :=\n  match s with\n  | Cons x _ => x\n  end.\n\nSection stream_eq_coind.\n  Variable A : Type.\n  Variable R : stream A -> stream A -> Prop.\n  Hypothesis Cons_case_hd : forall s1 s2, R s1 s2 -> hd s1 = hd s2.\n  Hypothesis Cons_case_tl : forall s1 s2, R s1 s2 -> R (tl s1) (tl s2).\n\n  Theorem stream_eq_coind : forall s1 s2 , R s1 s2 -> stream_eq s1 s2.\n                                             cofix; destruct s1; destruct s2; intro.\n                                             generalize (Cons_case_hd H); intro Heq; simpl in Heq; rewrite Heq.\n                                             constructor.\n                                             apply stream_eq_coind.\n                                             apply (Cons_case_tl H).\n  Qed.\nEnd stream_eq_coind.\n\nPrint stream_eq_coind.\n\nTheorem ones_eq'' : stream_eq ones ones'.\n                      apply (stream_eq_coind (fun s1 s2 => s1 = ones /\\ s2 = ones')); crush.\nQed.\n\nSection stream_eq_loop.\n  Variable A : Type.\n  Variable s1 s2 : stream A.\n  Hypothesis Cons_case_hd : hd s1 = hd s2.\n  Hypothesis loop1 : tl s1 = s1.\n  Hypothesis loop2 : tl s2 = s2.\n  Theorem stream_eq_loop : stream_eq s1 s2.\n                             apply (stream_eq_coind (fun s1' s2' => s1 = s1' /\\ s2 = s2')); crush.\n  Qed.\nEnd stream_eq_loop.\n\nTheorem ones_eq''' : stream_eq ones ones'.\n                       apply stream_eq_loop; crush.\nQed.\n\nPrint fact.\n\nCoFixpoint fact_slow' (n : nat) := Cons (fact n) (fact_slow' (S n)).\nDefinition fact_slow := fact_slow' 1.\n\nCoFixpoint fact_iter' (cur acc : nat) := Cons acc (fact_iter' (S cur) (acc * cur)).\nDefinition fact_iter := fact_iter' 2 1.\n\nEval simpl in approx fact_iter 5.\nEval simpl in approx fact_slow 5.\n\nLemma fact_def : forall x n,\n    fact_iter' x (fact n * S n) = fact_iter' x (fact (S n)).\n      simpl; intros; f_equal; ring.\nQed.\n\nHint Resolve fact_def.\n\nLemma fact_eq' : forall n , stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).\n      intro; apply (stream_eq_coind (fun s1 s2 => exists n, s1 = fact_iter' (S n) (fact n) /\\ s2 = fact_slow' n)); crush; eauto.\nQed.\n\nTheorem fact_eq : stream_eq fact_iter fact_slow.\n                    apply fact_eq'.\nQed.\n\nSection stream_eq_onequant.\n  Variables A B : Type.\n  Variables f g : A -> stream B.\n\n  Hypothesis Cons_case_hd : forall x , hd (f x) = hd (g x).\n  Hypothesis Cons_case_tl : forall x , exists y , tl (f x) = f y /\\ tl (g x) = g y.\n  Theorem stream_eq_onequant : forall x , stream_eq (f x) (g x).\n        intro; apply (stream_eq_coind (fun s1 s2 => exists x , s1 = f x /\\ s2 = g x)); crush; eauto.\n  Qed.\nEnd stream_eq_onequant.\n\nLemma fact_eq'' : forall n, stream_eq (fact_iter' (S n) (fact n)) (fact_slow' n).\n      apply stream_eq_onequant; crush; eauto.\nQed.\n\n(* 5.3 Simple Modeling of Non-Terminating Programs *)\n\nDefinition var := nat.\n\nDefinition vars := var -> nat.\nDefinition set (vs : vars) (v : var) (n : nat) : vars :=\n  fun v' => if beq_nat v v' then n else vs v'.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Var : var -> exp\n| Plus : exp -> exp -> exp\n.\n\nFixpoint evalExp (vs : vars) (e : exp) : nat :=\n  match e with\n  | Const n => n\n  | Var v => vs v\n  | Plus e1 e2 => evalExp vs e1 + evalExp vs e2\n  end\n.\n\nInductive cmd : Set :=\n| Assign : var -> exp -> cmd\n| Seq : cmd -> cmd -> cmd\n| While : exp -> cmd -> cmd\n.\n\nCoInductive evalCmd : vars -> cmd -> vars -> Prop :=\n| EvalAssign : forall vs v e , evalCmd vs (Assign v e) (set vs v (evalExp vs e))\n| EvalSeq : forall vs1 vs2 vs3 c1 c2 ,\n    evalCmd vs1 c1 vs2\n    -> evalCmd vs2 c2 vs3\n    -> evalCmd vs1 (Seq c1 c2) vs3\n| EvalWhileFalse : forall vs e c ,\n    evalExp vs e = 0\n    -> evalCmd vs (While e c) vs\n| EvalWhileTrue : forall vs1 vs2 vs3 e c ,\n    evalExp vs1 e <> 0\n    -> evalCmd vs1 c vs2\n    -> evalCmd vs2 (While e c) vs3\n    -> evalCmd vs1 (While e c) vs3\n.\n\n(*\n\n----------------------------------------- (EvalAssign)\n{vs} Assign v e {set vs v (evalExp vs e)}\n\n{vs1} c1 {vs2}           {vs2} c2 {vs3}\n--------------------------------------- (EvalSeq)\n         {vs1} Seq c1 c2 {vs3}\n\n evalExp vs e = 0\n------------------- (EvalWhileFalse)\n{vs} While e c {vs}\n\nevalExp vs1 e <> 0     {vs1} c {vs2}      {vs2} While e c {vs3}\n--------------------------------------------------------------- (EvalWhileTrue)\n                   {vs1} While e c {vs3}\n\n*)\n\nSection evalCmd_coind.\n  Variable R : vars -> cmd -> vars -> Prop.\n\n  Hypothesis AssignCase : forall vs1 vs2 v e, R vs1 (Assign v e) vs2\n    -> vs2 = set vs1 v (evalExp vs1 e).\n\n  Hypothesis SeqCase : forall vs1 vs3 c1 c2, R vs1 (Seq c1 c2) vs3\n    -> exists vs2, R vs1 c1 vs2 /\\ R vs2 c2 vs3.\n\n  Hypothesis WhileCase : forall vs1 vs3 e c, R vs1 (While e c) vs3\n    -> (evalExp vs1 e = 0 /\\ vs3 = vs1)\n    \\/ exists vs2, evalExp vs1 e <> 0 /\\ R vs1 c vs2 /\\ R vs2 (While e c) vs3.\n\n  Theorem evalCmd_coind : forall vs1 c vs2, R vs1 c vs2 -> evalCmd vs1 c vs2.\n    cofix; intros; destruct c.\n    rewrite (AssignCase H); constructor.\n    destruct (SeqCase H) as [? [? ?]]; econstructor; eauto.\n    destruct (WhileCase H) as [[? ?] | [? [? [? ?]]]]; subst; econstructor; eauto.\n  Qed.\nEnd evalCmd_coind.\n\nFixpoint optExp (e : exp) : exp :=\n  match e with\n  | Plus (Const 0) e => optExp e\n  | Plus e1 e2 => Plus (optExp e1) (optExp e2)\n  | _ => e\n  end\n.\n\nFixpoint optCmd (c : cmd) : cmd :=\n  match c with\n  | Assign v e => Assign v (optExp e)\n  | Seq c1 c2 => Seq (optCmd c1) (optCmd c2)\n  | While e c => While (optExp e) (optCmd c)\n  end\n.\n\nLemma optExp_correct : forall vs e ,\n    evalExp vs (optExp e) = evalExp vs e.\n      induction e; crush;\n      repeat (match goal with\n              | [ |- context[match ?E with Const _ => _ | _ => _ end]] => destruct E\n              | [ |- context [match ?E with O => _ | S _ => _ end ]] => destruct E\n              end; crush).\nQed.\n\nHint Rewrite optExp_correct.\n\nLtac finisher :=\n  match goal with\n  | [ H : evalCmd _ _ _ |- _ ] => ((inversion H; [])\n                                   || (inversion H; [|])); subst\n  end; crush; eauto 10.\n\nLemma optCmd_correct1 : forall vs1 c vs2 ,\n    evalCmd vs1 c vs2 -> evalCmd vs1 (optCmd c) vs2.\n      intros; apply (evalCmd_coind (fun vs1 c' vs2 => exists c , evalCmd vs1 c vs2 /\\ c' = optCmd c)); eauto; crush; match goal with\n  | [ H : _ = optCmd ?E |- _ ] => destruct E; simpl in *; discriminate || injection H; intros; subst\n                                                                                                                     end; finisher.\nQed.\n\nLemma optCmd_correct2 : forall vs1 c vs2 ,\n    evalCmd vs1 (optCmd c) vs2 -> evalCmd vs1 c vs2.\n      intros; apply (evalCmd_coind (fun vs1 c vs2 => evalCmd vs1 (optCmd c) vs2));\n      crush; finisher.\nQed.\n\nTheorem optCmd_correct : forall vs1 c vs2 ,\n    evalCmd vs1 (optCmd c) vs2 <-> evalCmd vs1 c vs2.\n      intuition; apply optCmd_correct1\n                 || apply optCmd_correct2; assumption.\nQed.\n", "meta": {"author": "andorp", "repo": "cpdt", "sha": "dd2099eeae2f12e1379a8706420f072aa174adc5", "save_path": "github-repos/coq/andorp-cpdt", "path": "github-repos/coq/andorp-cpdt/cpdt-dd2099eeae2f12e1379a8706420f072aa174adc5/chapter05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7278818280393817}}
{"text": "(** ** Some useful instances of Monoid classes \n\nFile %\\href{../Powers/SRC/Monoid_instances.v}{Powers/SRC/Monoid\\_instances}\ndefines various instances of [Monoid] and [EMonoid].\n*)\n\nRequire Export Monoid_def.\nRequire Import RelationClasses Morphisms.\n\nRequire Import ZArith PArith.\nRequire Import Arith.\nRequire Import NArith.\nRequire Import Ring31.\n\nOpen Scope Z_scope.\n\n(** *** Multiplicative monoid on [Z] *)\n\n(* begin snippet ZMultDef *)\n#[ global ] Instance Z_mult_op : Mult_op Z := Z.mul.\n\n#[ global ] Instance ZMult : Monoid  Z_mult_op 1. (* .no-out *)\nProof. (* .no-out *)\n  split.\n    all: unfold Z_mult_op, mult_op;intros;ring.\nQed.\n(* end snippet ZMultDef *)\n\n\n#[ global ] Instance ZMult_Abelian : Abelian_Monoid ZMult.\nProof.\n  split; exact Zmult_comm.\nQed.\n\n\n(** *** Multiplicative monoid on [nat] *)\n\n(* begin snippet natMult:: no-out *)\n\n#[ global ] Instance nat_mult_op : Mult_op nat | 5 := Nat.mul.\n\n#[ global ] Instance  Natmult : Monoid nat_mult_op  1%nat | 5.\nProof.\n   split;unfold nat_mult_op, mult_op; intros; ring.\nQed.\n(* end snippet natMult *)\n\n(** *** Additive monoid on [nat] \n\nThe following monoid is useful for proving the correctness of complex\nexponentiation algorithms. In effect, the $n$-th \"power\" of $1$ is\nequal to $n$. See Sect.%~\\ref{chains-exponent}.\n*)\n\n(* begin snippet natPlus:: no-out *)\n#[ global ] Instance nat_plus_op : Mult_op nat | 12 := Nat.add.\n\n#[ global ] Instance Natplus : Monoid nat_plus_op  0%nat | 12.\nProof.\n   split;unfold nat_plus_op, mult_op; intros; ring.\nQed.\n\n(* end snippet natPlus *)\n\n\nOpen Scope N_scope.\n\n#[ global ] Instance N_mult_op  : Mult_op N | 5 := N.mul.\n\n#[ global ] Instance NMult : Monoid N_mult_op 1 | 5.\nProof.\n  split;unfold N_mult_op, mult_op; intros; ring.\nQed.\n\n\n(* begin snippet CheckCoercion *)\nCheck NMult : EMonoid  N.mul 1%N eq.\n(* end snippet CheckCoercion *)\n\n\n#[ global ] Instance N_plus_op  : Mult_op N | 12 := N.add.\n\n#[ global ] Instance NPlus : Monoid N_plus_op 0 | 12.\nProof.\n  split;unfold N_plus_op, mult_op; intros; ring.\nQed.\n\n\n(** Multiplicative Monoid on [positive] \n*)\n\n#[ global ] Instance P_mult_op : Mult_op positive | 5  := Pos.mul .\n\n#[ global ] Instance PMult : Monoid P_mult_op xH | 5.\nProof.\n split;unfold P_mult_op, Mult_op;intros.  \n -  now rewrite Pos.mul_assoc.\n - reflexivity.\n - now rewrite Pos.mul_1_r.\nQed.\n\n\nImport Int31.\nOpen Scope int31_scope.\n\n(** ***  Multiplicative monoid on 31-bits integers \n\nCyclic numeric types are  good candidates for testing exponentiations\nwith big exponents, since the size of data is bounded.\n\n\nThe type [int31] is defined in Standard Library in Module\n[Coq.Numbers.Cyclic.Int31.Int31].\n*)\n\n(* begin snippet int31:: no-out *)\n#[ global ] Instance int31_mult_op : Mult_op int31 := mul31.\n\n#[ global ] Instance  Int31mult : Monoid int31_mult_op  1.\nProof.\n   split;unfold int31_mult_op, mult_op; intros; ring.\nQed.\n(* end snippet int31 *)\n\n\n\n  (* begin snippet BadFact *)\nModule Bad.\n  \n  Fixpoint int31_from_nat (n:nat) :=\n    match n with\n    | O => 1\n    | S p => 1 + int31_from_nat p\n    end.\n  \n  Coercion int31_from_nat : nat >-> int31.\n  \n  Fixpoint fact (n:nat) := match n with\n                             O => 1\n                           | S p => n * fact p\n                           end.\n  Compute fact 40. \n\nEnd Bad. \n(* end snippet BadFact *)\n\n\nClose Scope int31_scope.\n\n\n(** *** Monoid of 2x2 matrices \n\nLet $A$ be some type, provided with a ring structure. We define the multiplication \nof $2\\times 2$-matrices, the coefficients of which have type $A$.\n\n*)\n\n(* begin snippet M2Defsa *)\n\nSection M2_def.\nVariables (A:Type)\n           (zero one : A) \n           (plus mult  : A -> A -> A).\n\n Notation \"0\" := zero.  \n Notation \"1\" := one.\n Notation \"x + y\" := (plus x y).  \n Notation \"x * y \" := (mult x y).\n\n Variable rt : semi_ring_theory  zero one plus mult (@eq A).\n Add  Ring Aring : rt.\n\n\nStructure M2 : Type := {c00 : A;  c01 : A;\n                        c10 : A;  c11 : A}.\n\nDefinition Id2 : M2 := Build_M2 1 0 0 1.\n\nDefinition M2_mult (m m':M2) : M2 :=\n Build_M2 (c00 m * c00 m' + c01 m * c10 m')\n          (c00 m * c01 m' + c01 m * c11 m')\n          (c10 m * c00 m' + c11 m * c10 m')\n          (c10 m * c01 m' + c11 m * c11 m').\n\n(* end snippet M2Defsa *)\n\n\nLemma M2_eq_intros : forall a b c d a' b' c' d',\n  a=a' -> b=b' -> c=c' -> d=d' ->\n   Build_M2 a b c d = Build_M2 a' b' c' d'.\nProof. \n intros; now f_equal.\nQed.\n\n(* begin snippet M2Defsb:: no-out *)\n\n#[global] Instance M2_op : Mult_op M2 := M2_mult.\n\n#[global] Instance M2_Monoid : Monoid   M2_op Id2.\n(* ... *)\n(* end snippet M2Defsb *)\nProof. \n unfold M2_op, mult_op; split.\n - destruct x;destruct y;destruct z;simpl.\n   unfold M2_mult; apply M2_eq_intros; simpl; ring.\n - destruct x;simpl;\n   unfold M2_mult; apply M2_eq_intros; simpl; ring. \n - destruct x;simpl;\n   unfold M2_mult;apply M2_eq_intros;simpl;ring. \nQed.\n\nEnd M2_def.\n\nArguments M2_Monoid {A zero one plus mult} rt.\nArguments Build_M2 {A} _ _ _ _.\n\n(** Matrices over N *)\nDefinition M2N := M2_Monoid Nth.\n\n\n(** *** Integers modulo m\n\nThe following instance of [EMonoid] describes the set of integers modulo\n$m$, where $m$ is some integer greater or equal than $2$.\nFor simplicity's sake, we represent such values using the type [N],\nand consider \"equivalence modulo $m$\" instead of equality.\n*)\n\n(* begin snippet Nmoduloa:: no-out *)\nSection Nmodulo.\n  Variable m : N.\n  Hypothesis m_gt_1 : 1 < m.\n  (* end snippet Nmoduloa *)\n  \n  Remark m_neq_0 : m <> 0.\n    intro H;subst m. discriminate. \n  Qed.\n  \n  #[local] Hint Resolve m_neq_0 : chains.\n  \n  (* begin snippet Nmodulob:: no-out *)\n  Definition mult_mod (x y : N) := (x * y) mod m.\n  Definition mod_eq (x y: N) := x mod m = y mod m.\n  \n  Instance mod_equiv : Equiv N := mod_eq.\n\n  Instance mod_op : Mult_op N := mult_mod.\n  \n  Instance mod_Equiv : Equivalence mod_equiv.\n  (* end snippet Nmodulob *)\n  Proof.\n    split.\n    - intros x; reflexivity.\n    - intros x y H; now symmetry.  \n    - intros x y z Hxy Hyz; transitivity (y mod m) ; auto.\n  Qed.\n  \n  (* begin snippet Nmoduloc:: no-out *)\n  #[global] Instance mult_mod_proper :\n    Proper (mod_equiv ==> mod_equiv ==> mod_equiv) mod_op.\n  (* end snippet Nmoduloc *)\n  Proof.\n    unfold mod_equiv, mod_op, mult_mod, mod_eq.\n    intros x y Hxy z t Hzt.\n    repeat rewrite N.mod_mod; auto with chains.\n    rewrite (N.mul_mod x z);auto with chains.\n    rewrite (N.mul_mod y t);auto with chains.\n    rewrite Hxy, Hzt; reflexivity.\n  Qed.\n\n  (* begin snippet Nmodulod:: no-out *)\n  #[local]  Open Scope M_scope.\n\n  Lemma mult_mod_associative :  forall x y z,\n      x * (y * z) = x * y * z.\n  (* end snippet Nmodulod *)\n  Proof.\n    intros  x y z.\n    unfold mod_op, mult_op, mult_mod.\n    rewrite N.mul_mod_idemp_r;auto with chains.\n    rewrite N.mul_mod_idemp_l;auto with chains.\n    now rewrite  N.mul_assoc.\n  Qed.\n\n  (* begin snippet Nmoduloe:: no-out *)\n  Lemma one_mod_neutral_l  : forall x, 1 * x == x.\n  (* end snippet Nmoduloe *)\n  Proof.\n    unfold equiv, mod_equiv, mod_eq, mult_op, mod_op, mult_mod.\n    intro x; rewrite N.mul_1_l, N.mod_mod; auto with chains.\n  Qed.\n  (* begin snippet Nmodulof:: no-out *)\n  Lemma one_mod_neutral_r  : forall x, x * 1 == x.\n  (* end snippet Nmodulof *)\n  Proof.\n    unfold equiv, mod_equiv, mod_eq, mult_op, mod_op, mult_mod.\n    intro x; rewrite N.mul_1_r, N.mod_mod; auto with chains.\n  Qed.\n  \n\n  (* begin snippet Nmodulog:: no-out *)  \n  #[global] Instance Nmod_Monoid : EMonoid  mod_op 1 mod_equiv.\n  (* end snippet Nmodulog *)\n  Proof.\n    unfold equiv, mod_equiv, mod_eq, mult_op, mod_op, mult_mod.\n    split.\n    - exact mod_Equiv.\n    - exact mult_mod_proper.\n    - intros; rewrite mult_mod_associative; reflexivity.\n    - exact one_mod_neutral_l.\n    - exact one_mod_neutral_r.\n  Defined.\n  \n  (* begin snippet Nmodulog *)\nEnd Nmodulo.\n\nSection S256.\n\n  Let mod256 :=  mod_op 256.\n\n  #[local] Existing Instance mod256 | 1.\n\n  Compute (211 * 67)%M.\n\n  (* end snippet Nmodulog *)\n\n  (* begin snippet Nmoduloh *)\n\nEnd S256.\n\nCompute (211 * 67)%M.\n\n(* end snippet Nmoduloh *)\n\n\nClose Scope N_scope.\nClose Scope positive_scope.\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/additions/Monoid_instances.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7276885993039348}}
{"text": "(** * MoreCoq: More About Coq *)\n\nRequire Export Poly.\n\n(** This chapter introduces several more Coq tactics that,\n    together, allow us to prove many more theorems about the\n    functional programs we are writing. *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  (* At this point, we could finish with \n     \"[rewrite -> eq2. reflexivity.]\" as we have \n     done several times above. But we can achieve the\n     same effect in a single step by using the \n     [apply] tactic instead: *)\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1.\n\n  intros eq2.\n\n  rewrite eq2 with (r := m).\n  reflexivity.\n  apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex) *)\n(** Complete the following proof without using [simpl]. *)\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 H.\n    apply H.\nQed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal _exactly_ -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\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  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since \n            [apply] will perform simplification first. *)\n  apply H.  Qed.         \n\n(** **** Exercise: 3 stars (apply_exercise1) *)\n(** Hint: you can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend. *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros l l'.\n  symmetry.\n  rewrite -> H.\n  apply rev_involutive.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite) *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  Are there situations where both can usefully be\n    applied?\n  (* FILL IN HERE *)\n*)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might\n    abstract it out as a lemma recording once and for all\n    the fact that equality is transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. \n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to\n    prove the above example.  However, to do this we need\n    a slight refinement of the [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  (* If we simply tell Coq [apply trans_eq] at this point,\n     it can tell (by matching the goal against the\n     conclusion of the lemma) that it should instantiate [X]\n     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].\n     However, the matching process doesn't determine an\n     instantiation for [m]: we have to supply one explicitly\n     by adding [with (m:=[c,d])] to the invocation of\n     [apply]. *)\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(**  Actually, we usually don't have to include the name [m]\n    in the [with] clause; Coq is often smart enough to\n    figure out which instantiation we're giving. We could\n    instead write: [apply trans_eq with [c,d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise) *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o). \nProof.\n    intros m n o p.\n    intros eq1 eq2.\n    apply trans_eq with (m:=n).\n    apply eq2. apply eq1.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [inversion] tactic *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is clear from this definition that every number has one of two\n    forms: either it is the constructor [O] or it is built by applying\n    the constructor [S] to another number.  But there is more here than\n    meets the eye: implicit in the definition (and in our informal\n    understanding of how datatype declarations work in other\n    programming languages) are two other facts:\n\n    - The constructor [S] is _injective_.  That is, the only way we can\n      have [S n = S m] is if [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor is\n    injective and [nil] is different from every non-empty list.  For\n    booleans, [true] and [false] are unequal.  (Since neither [true]\n    nor [false] take any arguments, their injectivity is not an issue.) *)\n\n(** Coq provides a tactic called [inversion] that allows us to exploit\n    these principles in proofs.\n \n    The [inversion] tactic is used like this.  Suppose [H] is a\n    hypothesis in the context (or a previously proven lemma) of the\n    form\n      c a1 a2 ... an = d b1 b2 ... bm\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] instructs Coq to \"invert\" this\n    equality to extract the information it contains about these terms:\n\n    - If [c] and [d] are the same constructor, then we know, by the\n      injectivity of this constructor, that [a1 = b1], [a2 = b2],\n      etc.; [inversion H] adds these facts to the context, and tries\n      to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory.  That is, a false assumption has crept\n      into the context, and this means that any goal whatsoever is\n      provable!  In this case, [inversion H] marks the current goal as\n      completed and pops it off the goal stack. *)\n\n(** The [inversion] tactic is probably easier to understand by\n    seeing it in action than from general descriptions like the above.\n    Below you will find example theorems that demonstrate the use of\n    [inversion] and exercises to test your understanding. *)\n\nTheorem eq_add_S : forall (n m : nat),\n     S n = S m ->\n     n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.  Qed.\n\nTheorem silly4 : forall (n m : nat),\n     [n] = [m] ->\n     n = m.\nProof.\n  intros n o eq. inversion eq. reflexivity.  Qed.\n\n(** As a convenience, the [inversion] tactic can also\n    destruct equalities between complex values, binding\n    multiple variables as it goes. *)\n\nTheorem silly5 : forall (n m o : nat),\n     [n;m] = [o;o] ->\n     [n] = [m].\nProof.\n  intros n m o eq. inversion eq. reflexivity. Qed.\n\n(** **** Exercise: 1 star (sillyex1) *) \nExample sillyex1 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof.\n    intros X x y z l j.\n    intros eq1. intros eq2.\n    inversion eq1.\n    inversion eq2.\n    symmetry.\n    apply H0.\nQed.\n(** [] *)\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n  intros n m contra. inversion contra.  Qed.\n\n(** **** Exercise: 1 star (sillyex2) *)\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = [] ->\n     y :: l = z :: j ->\n     x = z.\nProof.\n  intros X x y z l j.\n  intros eq. inversion eq.\nQed.\n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    [forall (n m : nat), S n = S m -> n = m], the reverse direction of\n    the implication is an instance of a more general fact about\n    constructors and functions, which we will often find useful: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A), \n    x = y -> f x = f y. \nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed. \n\n\n(** **** Exercise: 2 stars, optional (practice) *)\n(** A couple more nontrivial but not-too-complicated proofs to work\n    together in class, or for you to work as exercises. *)\n \n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n    intros n.\n    intros eq.\n    inversion eq.\n    destruct n. reflexivity.\n    inversion H0.\nQed.\n\nTheorem beq_nat_0_r : forall n,\n   beq_nat n 0 = true -> n = 0.\nProof.\n  intros n.\n  intros eq.\n  destruct n. reflexivity.\n  inversion eq.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b. \nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, the tactic [apply L in H] matches some\n    conditional statement [L] (of the form [L1 -> L2], say) against a\n    hypothesis [H] in the context.  However, unlike ordinary\n    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),\n    [apply L in H] matches [H] against [L1] and, if successful,\n    replaces it with [L2].\n \n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\" -- from [L1 -> L2] and a hypothesis matching [L1], it\n    gives us a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\" -- it says that if we know [L1->L2] and we\n    are trying to prove [L2], it suffices to prove [L1].  \n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\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  symmetry in H. apply eq in H. symmetry in H. \n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, Coq tends to favor backward reasoning, but in some\n    situations the forward style can be easier to use or to think\n    about.  *)\n\n(** **** Exercise: 3 stars (plus_n_n_injective) *)\n(** Practice using \"in\" variants in this exercise. *)\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 m. simpl. destruct m. reflexivity. intros. inversion H.\n    simpl.\n\n    rewrite <- plus_n_Sm.\n    intros m.\n    intros H.\n    destruct m. inversion H.\n    inversion H.\n    rewrite <- plus_n_Sm in H1.\n    inversion H1.\n    apply IHn' in H2.\n    rewrite -> H2.\n    reflexivity.\nQed.\n\n(** [] *)\n\n(* ###################################################### *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose \n    we want to show that the [double] function is injective -- i.e., \n    that it always maps different arguments to different results:  \n    Theorem double_injective: forall n m, double n = double m -> n = m. \n    The way we _start_ this proof is a little bit delicate: if we \n    begin it with\n      intros n. induction n.\n]] \n    all is well.  But if we begin it with\n      intros n m. induction n.\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = O\". simpl. intros eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". intros eq. destruct m as [| m'].\n    SCase \"m = O\". inversion eq.\n    SCase \"m = S m'\".  apply f_equal. \n      (* Here we are stuck.  The induction hypothesis, [IHn'], does\n         not give us [n' = m'] -- there is an extra [S] in the\n         way -- so the goal is not provable. *)\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context -- \n    intuitively, we have told Coq, \"Let's consider some particular\n    [n] and [m]...\" and we now have to prove that, if [double n =\n    double m] for _this particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove that\n    the proposition\n\n      - [P n]  =  \"if [double n = double m], then [n = m]\"\n\n    holds for all [n] by showing\n\n      - [P O]              \n\n         (i.e., \"if [double O = double m] then [O = m]\")\n\n      - [P n -> P (S n)]  \n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help with proving [R]!  (If we\n    tried to prove [R] from [Q], we would say something like \"Suppose\n    [double (S n) = 10]...\" but then we'd be stuck: knowing that\n    [double (S n)] is [10] tells us nothing about whether [double n]\n    is [10], so [Q] is useless at this point.) *)\n\n(** To summarize: Trying to carry out this proof by induction on [n]\n    when [m] is already in the context doesn't work because we are\n    trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = O\". simpl. intros m eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". \n    (* Notice that both the goal and the induction\n       hypothesis have changed: the goal asks us to prove\n       something more general (i.e., to prove the\n       statement for _every_ [m]), but the IH is\n       correspondingly more flexible, allowing us to\n       choose any [m] we like when we apply the IH.  *)\n    intros m eq.\n    (* Now we choose a particular [m] and introduce the\n       assumption that [double n = double m].  Since we\n       are doing a case analysis on [n], we need a case\n       analysis on [m] to keep the two \"in sync.\" *)\n    destruct m as [| m'].\n    SCase \"m = O\". \n      (* The 0 case is trivial *)\n      inversion eq.  \n    SCase \"m = S m'\".  \n      apply f_equal. \n      (* At this point, since we are in the second\n         branch of the [destruct m], the [m'] mentioned\n         in the context at this point is actually the\n         predecessor of the one we started out talking\n         about.  Since we are also in the [S] branch of\n         the induction, this is perfect: if we\n         instantiate the generic [m] in the IH with the\n         [m'] that we are talking about right now (this\n         instantiation is performed automatically by\n         [apply]), then [IHn'] gives us exactly what we\n         need to finish the proof. *)\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What this teaches us is that we need to be careful about using\n    induction to try to prove something too specific: If we're proving\n    a property of [n] and [m] by induction on [n], we may need to\n    leave [m] generic. *)\n\n(** The proof of this theorem (left as an exercise) has to be treated similarly: *)\n\n(** **** Exercise: 2 stars (beq_nat_true) *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n    intros n. induction n.\n    simpl. intros m. destruct m. reflexivity. intros H. inversion H.\n\n    simpl. intros m. destruct m. intros H. inversion H.\n    intros H. apply IHn in H. apply f_equal. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal) *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** The strategy of doing fewer [intros] before an [induction] doesn't\n    always work directly; sometimes a little _rearrangement_ of\n    quantified variables is needed.  Suppose, for example, that we\n    wanted to prove [double_injective] by induction on [m] instead of\n    [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  Case \"m = O\". simpl. intros eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq. \n  Case \"m = S m'\". intros eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\".  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce\n    [n] for us!)   *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    will work, but it's not nice: We don't want to have to mangle the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them -- we want to state them in the most clear and\n    natural way. *)\n\n(**  What we can do instead is to first introduce all the\n    quantified variables and then _re-generalize_ one or more of\n    them, taking them out of the context and putting them back at\n    the beginning of the goal.  The [generalize dependent] tactic\n    does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. \n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  Case \"m = O\". simpl. intros n eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq.\n  Case \"m = S m'\". intros n eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\". apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n_Theorem_: For any nats [n] and [m], if [double n = double m], then\n  [n = m].\n\n_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n  any [n], if [double n = double m] then [n = m].\n\n  - First, suppose [m = 0], and suppose [n] is a number such\n    that [double n = double m].  We must show that [n = 0].\n\n    Since [m = 0], by the definition of [double] we have [double n =\n    0].  There are two cases to consider for [n].  If [n = 0] we are\n    done, since this is what we wanted to show.  Otherwise, if [n = S\n    n'] for some [n'], we derive a contradiction: by the definition of\n    [double] we would have [double n = S (S (double n'))], but this\n    contradicts the assumption that [double n = 0].\n\n  - Otherwise, suppose [m = S m'] and that [n] is again a number such\n    that [double n = double m].  We must show that [n = S m'], with\n    the induction hypothesis that for every number [s], if [double s =\n    double m'] then [s = m'].\n \n    By the fact that [m = S m'] and the definition of [double], we\n    have [double n = S (S (double m'))].  There are two cases to\n    consider for [n].\n\n    If [n = 0], then by definition [double n = 0], a contradiction.\n    Thus, we may assume that [n = S n'] for some [n'], and again by\n    the definition of [double] we have [S (S (double n')) = S (S\n    (double m'))], which implies by inversion that [double n' = double\n    m'].\n\n    Instantiating the induction hypothesis with [n'] thus allows us to\n    conclude that [n' = m'], and it follows immediately that [S n' = S\n    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted\n    to show. [] *)\n\n\n\n(** Here's another illustration of [inversion] and using an\n    appropriately general induction hypothesis.  This is a slightly\n    roundabout way of stating a fact that we have already proved\n    above.  The extra equalities force us to do a little more\n    equational reasoning and exercise some of the tactics we've seen\n    recently. *)\n\nTheorem length_snoc' : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l. induction l as [| v' l'].\n\n  Case \"l = []\". \n    intros n eq. rewrite <- eq. reflexivity.\n\n  Case \"l = v' :: l'\". \n    intros n eq. simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.\n\n(** It might be tempting to start proving the above theorem\n    by introducing [n] and [eq] at the outset.  However, this leads\n    to an induction hypothesis that is not strong enough.  Compare\n    the above to the following (aborted) attempt: *)\n\nTheorem length_snoc_bad : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l n eq. induction l as [| v' l'].\n\n  Case \"l = []\". \n    rewrite <- eq. reflexivity.\n\n  Case \"l = v' :: l'\". \n    simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)\n\n\n(** As in the double examples, the problem is that by\n    introducing [n] before doing induction on [l], the induction\n    hypothesis is specialized to one particular natural number, namely\n    [n].  In the induction case, however, we need to be able to use\n    the induction hypothesis on some other natural number [n'].\n    Retaining the more general form of the induction hypothesis thus\n    gives us more flexibility.\n\n    In general, a good rule of thumb is to make the induction hypothesis\n    as general as possible. *)\n\n(** **** Exercise: 3 stars (gen_dep_practice) *)\n\n(** Prove this by induction on [l]. *)\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     index n l = None.\nProof.\n    intros n.\n    intros X.\n    intros l.\n    generalize dependent n.\n    induction l.\n\n    destruct n. reflexivity. intros H. inversion H.\n\n    intros n.\n    destruct n. intros H. inversion H.\n\n    simpl. intros H. \n    apply IHl.\n    inversion H.\n    reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal) *)\n(** Write an informal proof corresponding to your Coq proof\n    of [index_after_last]:\n \n     _Theorem_: For all sets [X], lists [l : list X], and numbers\n      [n], if [length l = n] then [index n l = None].\n \n     _Proof_:\n     (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (gen_dep_practice_more) *)\n(** Prove this by induction on [l]. *)\n\nTheorem length_snoc''' : forall (n : nat) (X : Type) \n                              (v : X) (l : list X),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n    intros n X v l.\n    generalize dependent n.\n    induction l.\n    intros n. simpl. intros H. rewrite -> H. reflexivity.\n\n    intros n.\n    simpl.\n    intros H.\n    apply f_equal.\n    rewrite <- H.\n    apply IHl.\n    reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (app_length_cons) *)\n(** Prove this by induction on [l1], without using [app_length]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X) \n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n    intros X l1 l2 x n.\n    generalize dependent n.\n    induction l1.\n    intros n. simpl. intros. rewrite H. reflexivity.\n\n    intros n.\n    simpl. intros H. rewrite <- H.\n    apply f_equal.\n    apply IHl1.\n    reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice) *)\n(** Prove this by induction on [l], without using app_length. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n    intros X n l.\n    generalize dependent n.\n    induction l. intros n. intros H. rewrite <- H. reflexivity.\n\n    intros n. simpl. \n    replace (length (l ++ x :: l)) with (S(length (l ++ l))).\n    intros H.\n    destruct n. \n    \n        inversion H.\n    \n        rewrite <- plus_n_Sm.\n        apply f_equal.\n        simpl.\n        apply f_equal.\n        apply IHl.\n        inversion H. reflexivity.\n\n    apply app_length_cons with (x:=x).\n    reflexivity.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 3 stars, optional (double_induction) *)\n(** Prove the following principle of induction over two naturals. *)\n\nTheorem double_induction: forall (P : nat -> nat -> Prop), \n  P 0 0 ->\n  (forall m, P m 0 -> P (S m) 0) ->\n  (forall n, P 0 n -> P 0 (S n)) ->\n  (forall m n, P m n -> P (S m) (S n)) ->\n  forall m n, P m n.\nProof.\n    intros P.\n    intros H.\n    intros Hm.\n    intros Hn. \n    intros Hmn.\n\n    \n    intros m n.\n    generalize dependent m.\n    induction n.\n    Case \"n = 0\".\n        induction m.\n        apply H. apply Hm. apply IHm.\n\n    Case \"n > 0\". \n        induction m.\n        apply Hn.\n        apply IHn.\n\n        apply Hmn.\n        apply IHn.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where the [destruct] tactic is\n    used to perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun. \n  destruct (beq_nat n 3).\n    Case \"beq_nat n 3 = true\". reflexivity.\n    Case \"beq_nat n 3 = false\". destruct (beq_nat n 5).\n      SCase \"beq_nat n 5 = true\". reflexivity.\n      SCase \"beq_nat n 5 = false\". reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,\n    either [n] is equal to [3] or it isn't, so we use [destruct\n    (beq_nat n 3)] to let us reason about the two cases. \n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c].\n\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  intros X.\n  intros x1 x2 k1 k2.\n  intros f.\n  unfold override.\n  destruct (beq_nat k1 k2).\n  reflexivity. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (combine_split) *)\n(** Complete the proof below *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l l1 l2.\n  generalize dependent l2.\n  generalize dependent l1.\n  induction l.\n  intros l1 l2.\n  intros H.\n  inversion H.\n  reflexivity.\n\n  intros l1 l2.\n  simpl.\n  destruct x.\n  destruct (split l).\n  intros H.\n  destruct l1.\n  inversion H.\n  destruct l2.\n  inversion H.\n  simpl.\n  inversion H.\n  apply f_equal.\n  apply IHl.\n  rewrite H2. \n  rewrite H4.\n  reflexivity.\nQed.\n(** [] *)\n\n(** Sometimes, doing a [destruct] on a compound expression (a\n    non-variable) will erase information we need to complete a proof. *)\n(** For example, suppose\n    we define a function [sillyfun1] like this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** And suppose that we want to convince Coq of the rather\n    obvious observation that [sillyfun1 n] yields [true] only when [n]\n    is odd.  By analogy with the proofs we did with [sillyfun] above,\n    it is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution peformed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that since, in this branch of the case\n    analysis, [beq_nat n 3 = true], it must be that [n = 3], from\n    which it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation (with whatever\n    name we choose). *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got stuck\n    above, except that the context contains an extra equality\n    assumption, which is exactly what we need to make progress. *)\n    Case \"e3 = true\". apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    Case \"e3 = false\".\n     (* When we come to the second equality test in the body of the\n       function we are reasoning about, we can use [eqn:] again in the\n       same way, allow us to finish the proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5. \n        SCase \"e5 = true\".\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        SCase \"e5 = false\". inversion eq.  Qed.\n\n\n(** **** Exercise: 2 stars (destruct_eqn_practice) *)\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 (f b) eqn:fb.\n  destruct b.\n  rewrite -> fb. apply fb.\n  destruct (f true) eqn:ft.\n  apply ft.\n  apply fb.\n  destruct b.\n  destruct (f false) eqn:ff.\n  apply fb.\n  apply ff.\n  rewrite -> fb. apply fb.\nQed. \n\n(** [] *)\n\n(** **** Exercise: 2 stars (override_same) *)\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.\n  intros h.\n  unfold override.\n  destruct (beq_nat k1 k2) eqn:beq.\n  apply beq_nat_true in beq.\n  rewrite <- beq.\n  symmetry.\n  apply h.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen a bunch of Coq's fundamental tactics.  We'll\n    introduce a few more as we go along through the coming lectures,\n    and later in the course we'll introduce some more powerful\n    _automation_ tactics that make Coq do more of the low-level work\n    in many cases.  But basically we've got what we need to get work\n    done.\n\n    Here are the ones we've seen:\n\n      - [intros]: \n        move hypotheses/variables from goal to context \n\n      - [reflexivity]:\n        finish the proof (when the goal looks like [e = e])\n\n      - [apply]:\n        prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: \n        apply a hypothesis, lemma, or constructor to a hypothesis in\n        the context (forward reasoning)\n\n      - [apply... with...]:\n        explicitly specify values for variables that cannot be\n        determined by pattern matching\n\n      - [simpl]:\n        simplify computations in the goal \n\n      - [simpl in H]:\n        ... or a hypothesis \n\n      - [rewrite]:\n        use an equality hypothesis (or lemma) to rewrite the goal \n\n      - [rewrite ... in H]:\n        ... or a hypothesis \n\n      - [symmetry]:\n        changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]:\n        changes a hypothesis of the form [t=u] into [u=t]\n\n      - [unfold]:\n        replace a defined constant by its right-hand side in the goal \n\n      - [unfold... in H]:\n        ... or a hypothesis  \n\n      - [destruct... as...]:\n        case analysis on values of inductively defined types \n\n      - [destruct... eqn:...]:\n        specify the name of an equation to be added to the context,\n        recording the result of the case analysis\n\n      - [induction... as...]:\n        induction on values of inductively defined types \n\n      - [inversion]:\n        reason by injectivity and distinctness of constructors\n\n      - [assert (e) as H]:\n        introduce a \"local lemma\" [e] and call it [H] \n\n      - [generalize dependent x]:\n        move the variable [x] (and anything else that depends on it)\n        from the context back to an explicit hypothesis in the goal\n        formula \n*)\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym) *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n    intros n m.\n    generalize dependent m.\n    induction n. \n    simpl.\n    destruct m. reflexivity. reflexivity.\n\n    simpl. destruct m.\n    reflexivity.\n    simpl.\n    apply IHn.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal) *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans) *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  intros m n p.\n  intros H. apply beq_nat_true in H.\n  intros H1. apply beq_nat_true in H1.\n  rewrite -> H. rewrite -> H1.\n  symmetry.\n  apply beq_nat_refl.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine) *)\n(** We have just proven that for all lists of pairs, [combine] is the\n    inverse of [split].  How would you formalize the statement that\n    [split] is the inverse of [combine]?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)\n\nDefinition split_combine_statement : Prop :=\n    forall X Y: Type, forall l1: list X, forall l2: list Y,\n    length l1 = length l2 -> split (combine l1 l2) = (l1, l2).\n\nTheorem split_combine : split_combine_statement.\nProof.\n    unfold split_combine_statement.\n    intros X Y.\n    intros l1.\n    induction l1.\n    simpl.\n    intros l2.\n    intros H.\n    destruct l2. reflexivity. inversion H.\n\n    intros l2.\n    simpl.\n    intros H.\n    destruct l2.\n    inversion H.\n\n    simpl.\n    rewrite -> IHl1.\n    reflexivity.\n    simpl in H.\n    inversion H.\n    reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (override_permute) *)\nTheorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),\n  beq_nat k2 k1 = false ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n    intros X x1 x2 k1 k2 k3 f.\n    intros H.\n    unfold override.\n    destruct (beq_nat k1 k3) eqn:k13.\n    destruct (beq_nat k2 k3) eqn:k23.\n    apply beq_nat_true in k13.\n    apply beq_nat_true in k23.\n    rewrite k13 in H.\n    rewrite k23 in H.\n    rewrite <- beq_nat_refl in H.\n    inversion H.\n    reflexivity.\n    destruct (beq_nat k2 k3) eqn:k23.\n    reflexivity.\n    reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise) *)\n(** This one is a bit challenging.  Pay attention to the form of your IH. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n    intros X.\n    intros test.\n    intros x.\n    induction l.\n    intros lf.\n    intros H.\n    inversion H.\n    intros lf.\n    simpl.\n    destruct (test x0) eqn:tx0.\n    intros H.\n    inversion H.\n    rewrite <- H1.\n    apply tx0.\n\n    apply IHl.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (forall_exists_challenge) *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n  \n      forallb evenb [0;2;4;5] = false\n  \n      forallb (beq_nat 5) [] = true\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n      existsb (beq_nat 5) [0;2;3;6] = false\n \n      existsb (andb true) [true;true;false] = true\n \n      existsb oddb [1;0;0;0;0;3] = true\n \n      existsb evenb [] = false\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n \n    Prove that [existsb'] and [existsb] have the same behavior.\n*)\nFixpoint forallb  {X: Type} (f: X -> bool) (l: list X) :=\n    match l with\n    | nil => true\n    | h :: t => (andb (f h) (forallb f t)) \n    end.\n\nFixpoint existsb  {X: Type} (f: X -> bool) (l: list X) :=\n    match l with\n    | nil => false\n    | h :: t => (orb (f h) (existsb f t)) \n    end.\n\nExample foo0 : forallb oddb [1;3;5;7;9] = true.\nProof. reflexivity. Qed.\nExample foo1 : forallb negb [false;false] = true.\nProof. reflexivity. Qed.\nExample foo2 : forallb evenb [0;2;4;5] = false.\nProof. reflexivity. Qed.\nExample foo3 : forallb (beq_nat 5) [] = true.\nProof. reflexivity. Qed.\nExample foo4 : existsb (beq_nat 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\nExample foo5 : existsb (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\nExample foo6 : existsb oddb [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\nExample foo7 : existsb evenb [] = false.\nProof. reflexivity. Qed.\n\nDefinition existsb' {X: Type} (f: X -> bool) (l: list X) :=\n    negb (forallb (fun x => negb (f x)) l).\nExample foo8 : existsb' (beq_nat 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\nExample foo9 : existsb' (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\nExample fox0 : existsb' oddb [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\nExample fox1 : existsb' evenb [] = false.\nProof. reflexivity. Qed.\n\nTheorem same_existsb_existsb' : \n    forall (X: Type) (f: X -> bool) (l: list X),\n        existsb f l = existsb' f l.\nProof.\n    intros X. intros f.\n    intros l.\n    induction l.\n    reflexivity.\n\n    simpl.\n    destruct (f x) eqn:fx.\n    simpl.\n    unfold existsb'. simpl. rewrite fx. simpl. reflexivity.\n\n    simpl. unfold existsb'. simpl. rewrite fx. simpl. rewrite -> IHl.\n    unfold existsb'. reflexivity.\nQed.\n(* FILL IN HERE *)\n(** [] *)\n\n(* $Date: 2014-02-04 07:15:43 -0500 (Tue, 04 Feb 2014) $ *)\n\n\n\n", "meta": {"author": "darioush", "repo": "sf", "sha": "454c7f98022e2d935703c3038caa041cda835a17", "save_path": "github-repos/coq/darioush-sf", "path": "github-repos/coq/darioush-sf/sf-454c7f98022e2d935703c3038caa041cda835a17/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.9005297847831081, "lm_q1q2_score": 0.7276885980733655}}
{"text": "Require Import Bool Arith Coq.Arith.Euclid List.\nRequire Import BellantoniCook.Lib BellantoniCook.Bitstring BellantoniCook.BC BellantoniCook.BCLib.\n\nFixpoint unary_preserv (e : BC) : bool :=\n  match e with\n    | zero => true\n    | proj n s j => true\n    | succ b => b\n    | pred => true\n    | cond => true\n    | rec g h0 h1 => unary_preserv g  &&\n                     unary_preserv h0 && \n                     unary_preserv h1 \n    | comp _ _ h nl sl => unary_preserv h && \n                          forallb unary_preserv nl &&\n                          forallb unary_preserv sl\n  end.\n\n Lemma preservation : forall (e : BC) (vnl vsl : list bs),\n  unary_preserv e = true ->\n  forallb unary vnl = true ->\n  forallb unary vsl = true ->\n  unary (sem e vnl vsl) = true.\nProof.\n induction e using BC_ind2; simpl; intros; trivial.\n\n case n; simpl.\n apply forallb_nth; simpl; trivial.\n intros; case (leb i n0); apply forallb_nth; simpl; trivial.\n\n subst; simpl; apply forallb_hd; simpl; trivial.\n\n apply forallb_tl; trivial.\n apply forallb_hd; simpl; trivial.\n\n destruct vsl; simpl; trivial.\n simpl in H1;rewrite andb_true_iff in H1.\n destruct vsl; simpl; trivial.\n simpl in H1;rewrite andb_true_iff in H1.\n destruct vsl; simpl; trivial.\n case l; trivial; tauto.\n destruct vsl; simpl; trivial.\n simpl in H1;rewrite andb_true_iff in H1.\n case l; trivial; intros.\n tauto.\n case b; tauto.\n simpl in H1;rewrite andb_true_iff,andb_true_iff in H1.\n case l; trivial; try tauto; intros.\n case b; tauto.\n\n repeat rewrite andb_true_iff in H.  \n assert (unary (hd nil vnl) = true).\n apply forallb_hd; trivial.\n induction (hd nil vnl); simpl in *; intros.\n apply IHe1; [ tauto | apply forallb_tl | ];  trivial.\n case a.\n rewrite andb_true_iff in H2.\n apply IHe3; [ tauto | | ]; simpl.\n rewrite andb_true_iff; split; [tauto | ].\n apply forallb_tl; trivial.\n rewrite andb_true_iff; split.\n apply IHl; tauto.\n trivial.\n rewrite andb_true_iff in H2.\n apply IHe2; [ tauto | | ]; simpl.\n rewrite andb_true_iff; split; [tauto | ].\n apply forallb_tl; trivial.\n rewrite andb_true_iff; split.\n apply IHl; tauto.\n trivial.\n\n repeat rewrite andb_true_iff in H1.\n apply IHe; [ tauto | | ].\n apply forallb_map; auto; intros.\n apply H; trivial.\n rewrite forallb_forall in H1.\n decompose [and] H1.\n auto.\n apply forallb_map; auto; intros.\n apply H0; trivial.\n decompose [and] H1.\n rewrite forallb_forall in H6.\n auto.\nQed.\n\n(** * Zero\n\n  - with any arities (n, s)\n*)\n\nLemma zero_correct n s l1 l2: \n length (sem (zero_e n s) l1 l2) = 0.\nProof.\n intros; simpl; trivial.\nQed.\n\n(** * One\n\n  - with any arities (n, s)\n*)\n\nDefinition one_e (n s:nat) : BC :=\n  comp n s (comp 0 0 (succ true) nil (zero :: nil)) nil nil.\n\nLemma one_correct n s l1 l2: \n length (sem (one_e n s) l1 l2) = 1.\nProof.\n intros; simpl; trivial.\nQed.\n\n(** * Successor\n\n  - arities: (1, 0)\n*)\n\nDefinition succ_e : BC := succ true.\n\nLemma succ_correct :\n  forall n, length (sem succ_e nil [n]) = S (length n).\nProof.\n intros; simpl; trivial.\nQed.\n\n(** * Conversion from [nat] to [BC]\n\n  - with any arities (n, s)\n*)\n\nFixpoint nat2BC (n s x:nat) : BC :=\n  match x with\n    | 0 => zero_e n s\n    | S x' => comp n s succ_e nil [nat2BC n s x']\n  end.\n\nLemma nat2BC_arities : forall n s x, arities (nat2BC n s x) = ok_arities n s.\nProof.\ninduction x as [ | x IH].\ntrivial.\nsimpl nat2BC.\nrewrite comp_arities.\ntrivial.\ntrivial.\nsimpl; trivial.\nsimpl; tauto.\nQed.\n\nLemma nat2BC_correct :\n  forall n s x nl sl, length (sem (nat2BC n s x) nl sl) = x.\nProof.\ninduction x as [ | x IH].\ntrivial.\nintros nl sl.\nsimpl nat2BC.\nrewrite sem_comp.\nsimpl.\nrewrite IH.\ntrivial.\nQed.\n\nOpaque succ_e.\n\n(** * Addition\n\n  - arities: (1,1)\n*)\n\nDefinition plus_e : BC :=\n  rec (proj 0 1 0)\n      (comp 1 2 succ_e nil ((proj 1 2 1) :: nil))\n      (comp 1 2 succ_e nil ((proj 1 2 1) :: nil)).\n\nLemma plus_correct :\n  forall m n, length (sem plus_e [m] [n]) = length m + length n.\nProof.\n  induction m; simpl in *; intros; trivial.\n  case a; simpl; rewrite succ_correct; auto.\nQed.\n\nOpaque plus_e.\n\nFixpoint plusl_e (n:nat)(el:list BC) : BC :=\n  match el with\n    | nil => zero_e n 0\n    | e' :: el' => comp n 0 plus_e [e'] [plusl_e n el']\n  end.\n\nLemma plusl_arities n el : \n  andl (fun e => arities e = ok_arities n 0) el ->\n  arities (plusl_e n el) = ok_arities n 0.\nProof.\ninduction el as [ | e' el' IH].\ntrivial.\nintro H.\nsimpl in H.\nsimpl plusl_e.\nrewrite comp_arities.\ntrivial.\ntrivial.\nsimpl; tauto.\nsimpl; tauto.\nQed.\n\nLemma plusl_correct :\n  forall n nl el,\n  length (sem (plusl_e n el) nl nil) = plusl (map (fun e => length (sem e nl nil)) el).\nProof.\ninduction el as [ | e el IH]; simpl.\ntrivial.\nrewrite plus_correct, IH.\ntrivial.\nQed.\n\n(** * Logical or\n\n  - arities: (1,1)\n*)\n\nNotation or_e := plus_e (only parsing).\n\nLemma or_correct :\n  forall b1 b2, bs2bool (sem or_e [bool2bs b1] [bool2bs b2]) = b1 || b2.\nProof.\nintros [ | ] [ | ]; reflexivity.\nQed.\n\n(** * Multiplication\n\n  - arities: (2,0)\n*)\n\nDefinition mult_e : BC :=\n  rec (zero_e 1 0)\n      (comp 2 1 plus_e ((proj 2 0 1) :: nil) ((proj 2 1 2) :: nil))\n      (comp 2 1 plus_e ((proj 2 0 1) :: nil) ((proj 2 1 2) :: nil)).\n\nLemma mult_correct :\n  forall m n, length (sem mult_e [m; n] nil) = (length m) * (length n).\nProof.\ninduction m; intro n; trivial; simpl in *.\ncase a; rewrite plus_correct; auto.\nQed.\n\nOpaque mult_e.\n\n(** Logical and\n\n  - arities: (2,0)\n*)\n\nNotation and_e := mult_e (only parsing).\n\nLemma and_correct :\n  forall b1 b2, bs2bool \n    (sem and_e [bool2bs b1; bool2bs b2] nil) = b1 && b2.\nProof.\nintros [ | ] [ | ]; reflexivity.\nQed.\n\n(** * Minus (with reversed arguments)\n\n  - arities: (1,1)\n*)\n\nDefinition minus_rev_e : BC :=\n  rec (proj 0 1 0)\n      (comp 1 2 pred nil ((proj 1 2 1) :: nil))\n      (comp 1 2 pred nil ((proj 1 2 1) :: nil)).\n\nLemma minus_rev_correct :\n  forall m n, length (sem minus_rev_e [n] [m]) = (length m) - (length n).\nProof.\n induction n; simpl in *; [ omega | ].\n case a; rewrite length_tail, IHn; omega.\nQed.  \n\nOpaque minus_rev_e.\n\n(** * Less than predicate\n\n  - arities: (1,1)\n*)\n\nNotation lt_e := minus_rev_e.\n\nLemma lt_correct v1 v2:\n  bs2bool (sem lt_e [v1] [v2]) = true ->\n  length v1 < length v2.\nProof.\n  intros; simpl in *.\n  apply bs_nat2bool_true in H.\n  rewrite minus_rev_correct in H; omega.\nQed.\n\nLemma unary_tl l :\n  unary l = true ->\n  unary (tl l) = true.\nProof.\n intros.\n destruct l; simpl; trivial.\n simpl in H.\n rewrite andb_true_iff in H; tauto.\nQed.\n\nLemma lt_correct_conv_bool v1 v2:\n  unary v2 = true ->\n  length v1 < length v2 ->\n  bs2bool (sem lt_e [v1] [v2]) = true.\nProof.\n  intros; simpl in *.\n  apply bs_nat2bool_true_conv.\n  Transparent lt_e.\n  simpl.\n  Opaque lt_e.\n  induction v1; simpl; trivial.\n  case a.\n  apply unary_tl.\n  apply IHv1.\n  simpl in *; omega.\n  apply unary_tl.\n  apply IHv1.\n  simpl in *; omega.\n  rewrite minus_rev_correct.\n  omega.\nQed.\n\nLemma lt_correct_conv v1 v2 :\n  unary v1 = true ->\n  unary v2 = true ->\n  bs2bool (sem lt_e [v1] [v2]) = false ->\n  length v2 <= length v1.\nProof.\n  intros; trivial.\n  apply bs_nat2bool_false in H1.\n  rewrite minus_rev_correct in H1.\n  omega.\n  apply preservation; simpl; try reflexivity;\n  rewrite andb_true_iff; auto.\nQed.\n\nLemma lt_correct_conv_nil v1 v2 :\n  unary v1 = true ->\n  unary v2 = true ->\n  sem lt_e [v1] [v2] = nil ->\n  length v2 <= length v1.\nProof.\n  intros; trivial.\n  assert (bs2bool (sem lt_e [v1] [v2]) = false).\n  rewrite H1; simpl; trivial.\n  apply bs_nat2bool_false in H2.\n  rewrite minus_rev_correct in H2.\n  omega.\n  apply preservation; simpl; try reflexivity;\n  rewrite andb_true_iff; auto.\nQed.\n\n(** * Less than or equal to predicate\n\n  - arities: (1,1)\n*)\n\nDefinition le_e : BC :=\n  comp 1 1 lt_e (proj 1 0 0 :: nil) (comp 1 1 succ_e nil (proj 1 1 1 :: nil) :: nil).\n\nLemma le_correct : forall v1 v2,\n  bs2bool (sem le_e [v1] [v2]) = true ->\n  length v1 <= length v2.\nProof.\n  intros v1 v2 H; simpl in H.\n  apply lt_correct in H.\n  rewrite succ_correct in H.\n  omega.\nQed.\n\nLemma le_correct_conv v1 v2 :\n  unary v1 = true ->\n  unary v2 = true ->\n  bs2bool (sem le_e [v1] [v2]) = false ->\n  length v2 < length v1.\nProof.\n  intros; trivial.\n  simpl in H1.\n  apply lt_correct_conv in H1.\n  rewrite succ_correct in H1.\n  omega.\n  trivial.\n  apply preservation; simpl; try reflexivity;\n    rewrite andb_true_iff; auto.\nQed.\n\nLemma le_correct_conv_nil v1 v2 :\n  unary v1 = true ->\n  unary v2 = true ->\n  sem le_e [v1] [v2] = nil ->\n  S (length v2) <= length v1.\nProof.\n  intros; trivial.\n  simpl in H1.\n  apply lt_correct_conv_nil in H1.\n  rewrite succ_correct in H1.\n  omega.\n  trivial.\n  apply preservation; simpl; try reflexivity;\n  rewrite andb_true_iff; auto.\nQed.\n \nOpaque le_e.\n\n(** * Minus\n\n  - arities: (2,0)\n*)\n\nNotation minus_e := (inv_e (from_11_to_20 minus_rev_e)) (only parsing).\n\nLemma minus_correct :\n  forall m n, length (sem minus_e [n; m] nil) = (length n) - (length m).\nProof.\n intros; simpl; rewrite minus_rev_correct; trivial.\nQed.\n\n(** * Maximum\n\n  - arities: (2,0)\n*)\n\nDefinition max_e : BC :=\n  comp 2 0 (rec (proj 2 0 0) (proj 3 1 2) (proj 3 1 2) )\n  [ P'_e; proj 2 0 0; proj 2 0 1] nil.\n\nLemma max_correct_l v1 v2 : length v2 <= length v1 ->\n  sem max_e [v1; v2] nil = v1.\nProof.\n  simpl; intros.\n  rewrite P_correct; unfold P.\n  rewrite skipn_nil; simpl; trivial.\nQed.\n\nLemma max_correct_r v1 v2 : length v1 < length v2 ->\n  sem max_e [v1; v2] nil = v2.\nProof.\n  simpl; intros.\n  rewrite P_correct; unfold P.\n  case_eq (  (skipn (length v1) v2) ); simpl; intros.\n  contradict H.\n  apply le_not_lt.\n  apply skipn_nil_length; trivial.\n  case b; trivial.\nQed.\n\n(** * Euclidean division\n\n  - arities: (2,0)\n*)\n\nFixpoint div' (q y:nat)(x:nat) : nat :=\n  match q with\n  | 0 => 0\n  | S q' => if leb (q' * y) x then q' else div' q' y x\n  end.\n\nLemma div'_coq_correct : forall (q x y : nat) (Hy:y>0),\n  (q > proj1_sig (quotient y Hy x) -> \n    div' q y x = proj1_sig (quotient y Hy x)) /\\\n  (q <= proj1_sig (quotient y Hy x) -> \n    div' q y x = Peano.pred q).\nProof.\nintros q x y Hy.\ndestruct (quotient y Hy x) as (qu & r & H1 & H2); simpl.\ninduction q as [ | q' IH]; simpl; [ omega | ].\ncase_eq (leb (q' * y) x); intro H.\nclear IH.\napply leb_complete in H; split; subst x; intros; trivial.\nassert (qu <= q') as H1 by omega; clear H0.\napply le_lt_or_eq in H1.\ndestruct H1; auto.\ncontradict H.\napply lt_not_le.\napply lt_le_trans with (qu * y + y); [ omega | ].\nrewrite <- mult_succ_l.\napply mult_le_compat_r; omega.\napply leb_complete_conv in H; split; intros; subst.\nassert (q'=qu \\/ q'>qu) as [H3 | H3]; subst; omega.\nassert (S q' = qu \\/ S q' < qu) as [H4 | H4] by omega; subst.\ncontradict H.\napply le_not_lt; simpl; omega.\ncontradict H4.\napply le_not_lt.\napply mult_S_le_reg_l with (Peano.pred y).\nrewrite <- S_pred with (m:=0), mult_comm, (mult_comm y (S q')).\nsimpl; omega.\nomega.\nQed.\n\nDefinition div (x y:nat) : nat := div' (S x) y x.\n\nLemma div_coq_correct : forall (x y:nat) (Hy:y>0),\n  div x y = proj1_sig (quotient y Hy x).\nProof.\nunfold div; intros x y Hy.\ngeneralize (div'_coq_correct (S x) x y Hy).\ndestruct (quotient y Hy x) as (q & r & H1 & H2); simpl.\nintros [H3 _].\napply H3; subst x.\napply le_gt_S.\napply le_trans with (q*y); [ | omega ].\nrewrite <- (mult_1_r q) at 1.\napply mult_le_compat_l; omega.\nQed.\n\nDefinition div'_e : BC :=\n  rec (zero_e 1 1)\n  (comp 2 2 cond nil\n    [comp 2 2 le_e [comp 2 0 mult_e [proj 2 0 0; proj 2 0 1] nil]\n      [proj 2 2 3]; proj 2 2 2; proj 2 2 0; proj 2 2 2])\n  (comp 2 2 cond nil\n    [comp 2 2 le_e [comp 2 0 mult_e [proj 2 0 0; proj 2 0 1] nil]\n      [proj 2 2 3]; proj 2 2 2; proj 2 2 0; proj 2 2 2]).\n\nLemma hd_cons l a l' :\n  l = a :: l' ->\n  bs2bool l = a.\nProof.\n  intros; subst; trivial.\nQed.\n\nLtac elim_if :=  match goal with \n   | |- context [if ?c then ?c1 else ?c2]  => case_eq c\n end.\n\nLemma div'_correct v1 v2 v3 :\n  unary v1 = true -> unary v2 = true -> unary v3 = true ->\n  length (sem div'_e [v1;v2] [v3]) = \n  div' (length v1) (length v2) (length v3).\nProof.\n intros; induction v1; simpl in *; intros; trivial.\n rewrite andb_true_iff in H.\n case a; simpl.\n case_eq ( sem le_e [sem mult_e [v1; v2] nil] [v3] ); intros.\n rewrite IHv1; trivial.\n apply le_correct_conv_nil in H2.\n rewrite mult_correct in H2.\n rewrite leb_correct_conv; trivial.\n apply preservation; trivial; simpl.\n repeat rewrite andb_true_iff; tauto.\n trivial.\n tauto. \n apply hd_cons in H2.\n destruct b.\n apply le_correct in H2.\n rewrite mult_correct in H2.\n rewrite leb_correct; trivial.\n apply le_correct_conv in H2; trivial.\n simpl in IHv1; rewrite IHv1; clear IHv1; try tauto.\n rewrite leb_correct_conv; trivial.\n rewrite mult_correct in H2; trivial.\n apply preservation; trivial; simpl.\n do 2 rewrite andb_true_iff; tauto.\n case_eq ( sem le_e [sem mult_e [v1; v2] nil] [v3] ); intros.\n rewrite IHv1; trivial.\n apply le_correct_conv_nil in H2.\n rewrite mult_correct in H2.\n rewrite leb_correct_conv; trivial.\n apply preservation; trivial; simpl.\n repeat rewrite andb_true_iff; tauto.\n trivial.\n tauto. \n apply hd_cons in H2.\n destruct b.\n apply le_correct in H2.\n rewrite mult_correct in H2.\n rewrite leb_correct; trivial.\n apply le_correct_conv in H2; trivial.\n simpl in IHv1; rewrite IHv1; clear IHv1; try tauto.\n rewrite leb_correct_conv; trivial.\n rewrite mult_correct in H2; trivial.\n apply preservation; trivial; simpl.\n do 2 rewrite andb_true_iff; tauto.\nQed.\n\nOpaque div'_e.\n\nDefinition div_e : BC :=\n  comp 2 0 div'_e [comp 2 0 succ_e nil [proj 2 0 0]; proj 2 0 1] [proj 2 0 0].\n\nLemma div_correct v1 v2 :\n  unary v1 = true -> unary v2 = true -> \n  length (sem div_e [v1; v2] nil) = div (length v1) (length v2).\nProof.\n  intros; simpl sem.\n  rewrite div'_correct; trivial.\nQed.\n\n(** * Multiplication by a constant\n\n  - with any arities: (n,0)\n*)\n\nFixpoint scalar_e (a:nat)(n:nat)(e:BC) : BC :=\n  match a with\n  | 0 => zero_e n 0\n  | S a' => comp n 0 plus_e [e] [scalar_e a' n e]\n  end.\n\nLemma scalar_arities :\n  forall a n e,\n  arities e = ok_arities n 0 ->\n  arities (scalar_e a n e) = ok_arities n 0.\nProof.\ninduction a as [ | a IH]; simpl.\ntrivial.\nintros n e H.\nrewrite H, (IH _ _ H).\nsimpl.\nrewrite <- beq_nat_refl.\ntrivial.\nQed.\n\nOpaque plus_e.\n\nLemma scalar_correct :\n  forall a n nl e,\n  length (sem (scalar_e a n e) nl nil) = a * length (sem e nl nil).\nProof.\ninduction a as [ | a IH]; simpl.\ntrivial.\nintros n nl e.\nrewrite plus_correct, IH.\ntrivial.\nQed.\n\n(** * Multiplication of a list of expressions\n\n  - with any arities: (n,0)\n*)\n\nFixpoint multl_e (n:nat)(el:list BC) : BC :=\n  match el with\n    | nil => one_e n 0\n    | e' :: el' => comp n 0 mult_e [e'; multl_e n el'] nil\n  end.\n\nLemma multl_arities :\n  forall el n,\n  andl (fun e => arities e = ok_arities n 0) el ->\n  arities (multl_e n el) = ok_arities n 0.\nProof.\ninduction el as [ | e el IH]; simpl.\ntrivial.\nintros n [H1 H2].\nrewrite H1, (IH _ H2).\nsimpl.\nrewrite <- beq_nat_refl.\ntrivial.\nQed.\n\nOpaque mult_e.\n\nLemma multl_correct :\n  forall n nl el,\n  length (sem (multl_e n el) nl nil) = multl (map (fun e => length (sem e nl nil)) el).\nProof.\ninduction el as [ | e el IH]; simpl.\ntrivial.\nrewrite mult_correct, IH.\ntrivial.\nQed.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/bellantonicook/src/BellantoniCook/BCUnary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483232, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7276885865887449}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus Zero (plus x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj207_coqofml_66JEw1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7276672895187456}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus (mult x y) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj196_coqofml_y0s40B.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7276672877664723}}
{"text": "(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\nRequire Import ZArith Znumtheory.\n\nSet Implicit Arguments.\n\nOpen Scope Z_scope.\n\nLemma rel_prime_mod: forall a b, 1 < b ->\n  rel_prime a b -> a mod b <> 0.\nProof.\nintros a b H H1 H2.\ncase (not_rel_prime_0 _ H).\nrewrite <- H2.\napply rel_prime_mod; auto with zarith.\nQed.\n\nLemma Zmodpl: forall a b n, 0 < n ->\n  (a mod n + b) mod n = (a + b) mod n.\nProof.\nintros a b n H.\nrewrite Zplus_mod; auto.\nrewrite Zmod_mod; auto.\napply sym_equal; apply Zplus_mod; auto.\nQed.\n\nLemma Zmodpr: forall a b n, 0 < n ->\n  (b + a mod n) mod n = (b + a) mod n.\nProof.\nintros a b n H; repeat rewrite (Zplus_comm b).\napply Zmodpl; auto.\nQed.\n\nLemma Zmodml: forall a b n, 0 < n ->\n  (a mod n * b) mod n = (a * b) mod n.\nProof.\nintros a b n H.\nrewrite Zmult_mod; auto.\nrewrite Zmod_mod; auto.\napply sym_equal; apply Zmult_mod; auto.\nQed.\n\nLemma Zmodmr: forall a b n, 0 < n ->\n  (b * (a mod n)) mod n = (b * a) mod n.\nProof.\nintros a b n H; repeat rewrite (Zmult_comm b).\napply Zmodml; auto.\nQed.\n\n\nLtac is_ok t :=\n  match t with \n  | (?x mod _ + ?y mod _) mod _ => constr:(false)\n  | (?x mod _ * (?y mod _)) mod _ => constr:(false)\n  |  ?x mod _ => x\n  end.\n \nLtac  rmod t :=\n  match t with \n    (?x + ?y) mod _ => \n     match (is_ok x) with\n     | false => rmod x\n     | ?x1   =>  match (is_ok y) with \n                |false => rmod y\n                | ?y1 => \n                   rewrite <- (Zplus_mod x1 y1)\n                |false => rmod y\n                end\n     end\n  | (?x * ?y) mod _ => \n     match (is_ok x) with\n     | false => rmod x\n     | ?x1 =>  match (is_ok y) with \n                |false => rmod y\n                | ?y1 => rewrite <- (Zmult_mod x1 y1)\n                end\n     | false => rmod x\n     end\n  end.\n\n\nLemma Zmod_div_mod: forall n m a, 0 < n -> 0 < m ->\n  (n | m) -> a mod n = (a mod m) mod n.\nProof.\nintros n m a H1 H2 H3.\npattern a at 1; rewrite (Z_div_mod_eq a m); auto with zarith.\ncase H3; intros q Hq; pattern m at 1; rewrite Hq.\nrewrite (Zmult_comm q).\nrewrite Zplus_mod; auto.\nrewrite <- Zmult_assoc; rewrite Zmult_mod; auto.\nrewrite Z_mod_same; try rewrite Zmult_0_l; auto with zarith.\nrewrite (Zmod_small 0); auto with zarith.\nrewrite Zplus_0_l; rewrite Zmod_mod; auto with zarith.\nQed.\n\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/coqprime/src/Coqprime/Z/Zmod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7276672858232336}}
{"text": "\nRequire Export Iron.Language.SystemF2Cap.Type.Exp.\nRequire Export Iron.Language.SystemF2Cap.Type.Relation.WfT.\nRequire Import Coq.Bool.Bool.\n\n\n(********************************************************************)\n(* Type variable is free in type *)\nFixpoint FreeT (n : nat) (tt : ty) {struct tt} := \n match tt with\n | TVar ix        => n = ix\n | TForall k t    => FreeT (S n) t\n | TApp t1 t2     => FreeT n t1 \\/ FreeT n t2\n | TSum t1 t2     => FreeT n t1 \\/ FreeT n t2\n | TBot k         => False\n\n | TCon0 tc       => False\n | TCon1 tc t1    => FreeT n t1\n | TCon2 tc t1 t2 => FreeT n t1 \\/ FreeT n t2\n | TCap _         => False\n end.\n\n\n(********************************************************************)\nLemma freeT_wfT\n :  forall n1 n2 t\n ,  n2 >= n1\n -> WfT n1 t\n -> ~FreeT n2 t.\nProof.\n intros. gen n1 n2.\n induction t; intros; inverts H0;\n  unfold not; intros; snorm; subst; try omega.\n\n - cut (~ FreeT (S n2) t); firstorder.\n\n - inverts H0.\n   cut (~ FreeT n2 t1); firstorder.\n   cut (~ FreeT n2 t2); firstorder.\n \n - inverts H0.\n   cut (~ FreeT n2 t1); firstorder.\n   cut (~ FreeT n2 t2); firstorder.\n\n - cut (~ FreeT n2 t0); firstorder.\n\n - inverts H0.\n   cut (~ FreeT n2 t2); firstorder.\n   cut (~ FreeT n2 t3); firstorder.\nQed.\nHint Resolve freeT_wfT.\n\n\nLemma freeT_closedT\n :  forall t n\n ,  ClosedT t\n -> ~FreeT n t.\nProof.\n intros. \n eapply freeT_wfT; eauto.\nQed.\n\n\nLemma freeT_wfT_drop\n :  forall n t\n ,  WfT (S n) t\n -> ~FreeT n t\n -> WfT  n    t.\nProof.\n intros. gen n.\n induction t; snorm; inverts H; firstorder.\nQed.\n\n\nLemma freeT_isEffectOnVar\n :  forall d t\n ,  ~FreeT d t\n -> isEffectOnVar d t = false.\nProof.\n intros. \n destruct t; snorm.\n destruct t0; snorm;\n  try (solve [rewrite andb_false_iff; tauto]).\n\n - rewrite andb_false_iff. right. \n   rewrite beq_nat_false_iff. auto.\nQed.\nHint Resolve freeT_isEffectOnVar.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/devel/Iron/Language/SystemF2Cap/Type/Relation/FreeT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7275630922832701}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\n(*                                                                          *)\n(* Licensed under the Apache License, Version 2.0 (the \"License\")           *)\n(* you may not use this file except in compliance with the License.         *)\n(* You may obtain a copy of the License at                                  *)\n(*                                                                          *)\n(*     http://www.apache.org/licenses/LICENSE-2.0                           *)\n(*                                                                          *)\n(* Unless required by applicable law or agreed to in writing, software      *)\n(* distributed under the License is distributed on an \"AS IS\" BASIS,        *)\n(* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *)\n(* See the License for the specific language governing permissions and      *)\n(* limitations under the License.                                           *)\n(****************************************************************************)\n\n(* Bit-vector arithmetic operations for Cava. *)\n\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Bool.Bvector.\nRequire Import Coq.Init.Byte.\nRequire Import Coq.Lists.List.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Vectors.Vector.\nRequire Import Cava.Util.Nat.\nRequire Import Cava.Util.Vector.\nRequire Import Cava.Util.Byte.\nRequire Coq.Strings.HexString.\nImport ListNotations.\nLocal Open Scope list_scope.\n\n(* List and vector functions for conversion between nats and bit-vectors *)\n\nModule N.\n  (* Converts list of bits to a binary natural number, interpreting list as\n     little-endian *)\n  Definition of_list_bits (bits : list bool) : N :=\n    Bv2N (Vector.of_list bits).\n\n  (* Converts an N to a (little-endian) list of bits *)\n  Definition to_list_bits (n : N) : list bool :=\n    Vector.to_list (N2Bv n).\n\n  (* Converts an N to a (little-endian) list of bits of the specified length *)\n  Definition to_list_bits_sized (size : nat) (n : N) : list bool :=\n    Vector.to_list (N2Bv_sized size n).\nEnd N.\n\nExample b2n_empty : N.of_list_bits [] = 0%N.\nProof. reflexivity. Qed.\n\nExample b2n_0 : N.of_list_bits [false] = 0%N.\nProof. reflexivity. Qed.\n\nExample b2n_1 : N.of_list_bits [true] = 1%N.\nProof. reflexivity. Qed.\n\nExample b2n_10 : N.of_list_bits [false; true] = 2%N.\nProof. reflexivity. Qed.\n\nExample b2n_01 : N.of_list_bits [true; false] = 1%N.\nProof. reflexivity. Qed.\n\nExample b2n_11 : N.of_list_bits [true; true] = 3%N.\nProof. reflexivity. Qed.\n\nExample n2b_0_1 : N.to_list_bits 0 = [].\nProof. reflexivity. Qed.\n\nExample n2b_1_1 : N.to_list_bits 1 = [true].\nProof. reflexivity. Qed.\n\nExample n2b_2_2 : N.to_list_bits 2 = [false; true].\nProof. reflexivity. Qed.\n\nExample n2b_2_3 : N.to_list_bits 3 = [true; true].\nProof. reflexivity. Qed.\n\n(******************************************************************************)\n(* Functions useful for Vector operations                                     *)\n(******************************************************************************)\n\nDefinition bitvec_to_nat {n : nat} (bits : Bvector n) : nat :=\n  N.to_nat (Bv2N n bits).\n\nDefinition bv3_0 : Bvector 3 := [false; false; false]%vector.\nExample bv3_0_ex : bitvec_to_nat bv3_0 = 0.\nProof. reflexivity. Qed.\n\nDefinition bv1 : Bvector 1 := [true]%vector.\nExample bv1_ex : bitvec_to_nat bv1 = 1.\nProof. reflexivity. Qed.\n\nDefinition bv3_1 : Bvector 3 := [true; false; false]%vector.\nExample bv3_1_ex : bitvec_to_nat bv3_1 = 1.\nProof. reflexivity. Qed.\n\nDefinition bv3_2 : Bvector 3 := [false; true; false]%vector.\nExample bv3_2_ex : bitvec_to_nat bv3_2 = 2.\nProof. reflexivity. Qed.\n\nDefinition nat_to_bitvec (v : nat) : Bvector (N.size_nat (N.of_nat v)) :=\n  N2Bv (N.of_nat v).\n\nDefinition nat_to_bitvec_sized (n : nat) (v : nat) : Bvector n :=\n  N2Bv_sized n (N.of_nat v).\n\nExample bv3_0_cancellev : nat_to_bitvec_sized 3 0 = bv3_0.\nProof. reflexivity. Qed.\n\nExample bv3_1_cancellev : nat_to_bitvec_sized 3 1 = bv3_1.\nProof. reflexivity. Qed.\n\nExample bv3_2_cancellev : nat_to_bitvec_sized 3 2 = bv3_2.\nProof. reflexivity. Qed.\n\n(******************************************************************************)\n(* Functions useful for examples and tests                                    *)\n(******************************************************************************)\n\nDefinition nat2bool (n : nat) : bool :=\n  match n with\n  | 0 => false\n  | _ => true\n  end.\n\nDefinition n2bool (n : N) : bool :=\n  match n with\n  | 0%N => false\n  | _   => true\n  end.\n\nDefinition fromVec := List.map Nat.b2n.\nDefinition toVec := List.map nat2bool.\n\nDefinition Bv2Hex {n} (x: Vector.t bool n) := HexString.of_N (Bv2N x).\nDefinition Hex2Bv {n} (s : String.string) := N2Bv_sized n (HexString.to_N s).\n\nDefinition byte_reverse {n} (x: Vector.t bool (n*8)) := flatten (reverse (reshape (m:=8) x)).\n\nDefinition bitvec_to_byte (v : Vector.t bool 8) : Byte.byte :=\n  let '(b0,v) := Vector.uncons v in\n  let '(b1,v) := Vector.uncons v in\n  let '(b2,v) := Vector.uncons v in\n  let '(b3,v) := Vector.uncons v in\n  let '(b4,v) := Vector.uncons v in\n  let '(b5,v) := Vector.uncons v in\n  let '(b6,v) := Vector.uncons v in\n  let '(b7,v) := Vector.uncons v in\n  Byte.of_bits (b0,(b1,(b2,(b3,(b4,(b5,(b6,b7))))))).\n\nDefinition byte_to_bitvec (b : Byte.byte) : Vector.t bool 8 :=\n  Ndigits.N2Bv_sized 8 (Byte.to_N b).\nDefinition bitvec_to_bytevec n (v : Vector.t bool (n * 8)) : Vector.t Byte.byte n :=\n  Vector.map bitvec_to_byte (reshape v).\nDefinition bytevec_to_bitvec n (v : Vector.t Byte.byte n) : Vector.t bool (n * 8) :=\n  flatten (Vector.map byte_to_bitvec v).\n\nDefinition bytevec_to_wordvec\n           bytes_per_word n (v : Vector.t Byte.byte (n * bytes_per_word))\n  : Vector.t (Vector.t Byte.byte bytes_per_word) n := reshape v.\n\nDefinition bitvec_to_wordvec\n           bits_per_word n (v : Vector.t bool (n * bits_per_word))\n  : Vector.t (Vector.t bool bits_per_word) n := reshape v.\n\nDefinition wordvec_to_bytevec\n           bytes_per_word {n} (v : Vector.t (Vector.t Byte.byte bytes_per_word) n)\n  : Vector.t Byte.byte (n * bytes_per_word) := flatten v.\nDefinition wordvec_to_bitvec\n           bits_per_word {n} (v : Vector.t (Vector.t bool bits_per_word) n)\n  : Vector.t bool (n * bits_per_word) := flatten v.\n\n(******************************************************************************)\n(* Arithmetic operations                                                      *)\n(******************************************************************************)\n\nDefinition unsignedAddBool {m n : nat}\n                           (av_bv : Bvector m *  Bvector n)\n: Bvector (1 + max m n) :=\n  let (av, bv) := av_bv in\n  let a := Bv2N av in\n  let b := Bv2N bv in\n  let sumSize := 1 + max m n in\n  let sum := (a + b)%N in\n  N2Bv_sized sumSize sum.\n\nDefinition unsignedMultBool {m n : nat}\n           (av_bv : Bvector m *  Bvector n)\n  : Bvector (m + n) :=\n  let (av, bv) := av_bv in\n  let a := Bv2N av in\n  let b := Bv2N bv in\n  let product := (a * b)%N in\n  N2Bv_sized (m + n) product.\n\nDefinition greaterThanOrEqualBool {m n : nat}\n           (av_bv : Bvector m *  Bvector n) : bool :=\n  let (av, bv) := av_bv in\n  (Bv2N bv <=? Bv2N av)%N.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/cava/Cava/Util/BitArithmetic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7275630900649896}}
{"text": "Lemma eq_sym : forall (X : Type)(x y : X), x = y -> y = x.\nintros X x y A.\nrewrite A.\nreflexivity.\nQed.\n\nLemma modus_ponens : forall X Y : Prop, X -> (X -> Y) -> Y.\nintros X Y x A.\nexact (A x).\nQed.\n\nLemma barbara : forall X Y Z : Prop, (X -> Y) -> (Y -> Z) -> (X -> Z).\nintros X Y Z A B x.\nexact (B (A x)).\nQed.\n\n\nLemma eq_trans : forall (X : Type)(x y z : X), x = y -> y = z -> x = z.\nintros.\ntransitivity y.\nassumption.\napply H0.\nQed.\n\nGoal forall p q : nat -> Prop, p 7 -> (forall x, p x -> q x) -> q 7.\nProof.\nintros p q A B.\napply B.\nexact A.\nQed.\n\nLemma const : forall X Y, X -> Y -> X.\nintros.\napply X0.\nQed.\n\nGoal forall X Y, (forall Z, (X -> Y -> Z) -> Z) -> X.\nintros X Y Z0.\napply Z0.\napply const.\nQed.\n\n\nLemma const' : forall X Y, X -> Y -> Y.\nintros.\napply X1.\nQed.\n\n\nGoal forall X Y, (forall Z, (X -> Y -> Z) -> Z) -> Y.\nintros.\napply X0.\napply const'.\nQed.\n\nGoal forall (p : bool -> Prop)(x : bool), p true -> p false -> p x.\nProof.\nintros.\ninduction x.\napply H.\napply H0.\nQed.\n\nGoal forall (p : nat -> Prop)(x : nat), p O -> (forall n, p n -> p (S n)) -> p x.\nintros.\ninduction x.\napply H.\napply H0.\napply IHx.\nQed.\n\nGoal forall (X : Type)(p : list X -> Prop)(xs : list X), p nil -> (forall x xs, p xs -> p (cons x xs)) -> p xs.\nProof.\nintros.\ninduction xs.\napply H.\napply H0.\napply IHxs.\nQed.\n\n\nGoal forall X : Type, (fun x : X => x) = (fun y : X => y).\nintros.\nreflexivity.\nQed.\n\nGoal forall X Y : Prop, (X -> Y) -> forall x : X, Y.\nintros.\napply (H x).\nQed.\n\nGoal forall X Y : Prop, (forall x : X, Y) -> X -> Y.\nintros.\napply (H H0).\nQed.\n\nGoal forall X Y : Prop, (X -> Y) = (forall x : X, Y).\nintros.\nreflexivity.\nQed.\n\nLemma double_negation : forall X : Prop, X -> ~~X.\nintros X x A.\nexact (A x).\nQed.\n\nGoal forall X : Prop, ~~X -> (X -> ~X) -> X.\nintros X A B.\nexfalso.\napply A.\nintros x.\nexact (B x x).\nQed.\n\nGoal forall X Y : Prop, ~~(((X -> Y) -> X) -> X).\nintros.\ntauto.\nQed.\n\nGoal forall X Y : Prop, X /\\ Y -> Y /\\ X.\nintros X Y A.\ndestruct A as [x y].\nsplit.\napply y.\napply x.\nQed.\n\nGoal forall X Y : Prop, X \\/ Y -> Y \\/ X.\nintros X Y A.\ndestruct A as [x|y].\nright. exact x.\nleft. exact y.\nQed.\n\nGoal forall X Y Z : Prop, X \\/ (Y /\\ Z) -> (X \\/ Y) /\\ (X \\/ Z).\nintros X Y Z [x|[y z]].\nsplit. left. exact x.\nleft. exact x.\nsplit. right. exact y.\nright. exact z.\nQed.\n\nGoal forall X Y Z W : Prop, (X -> Y) \\/ (X -> Z) -> (Y -> W) /\\ (Z -> W) -> X -> W.\ntauto.\nQed.\n\nGoal forall X Y: Prop, X /\\ Y -> Y /\\ X.\nintros X Y [x y].\nsplit.\nassumption.\napply x.\nQed.\n\nGoal forall (X : Type)(p q : X -> Prop),(exists x, p x /\\ q x) -> exists x, p x.\nintros X p q A.\ndestruct A as [x B].\ndestruct B as [C _].\nexists x.\napply C.\nQed.\n\nDefinition diagonal : Prop := forall (X : Type)(p : X -> X -> Prop), ~ exists x, forall y, p x y <-> ~ p y y.\n\nLemma circuit (X : Prop): ~(X <-> ~X).\ntauto.\nQed.\n\nGoal diagonal.\nProof.\nintros X p [x A].\napply (@circuit(p x x)).\nexact (A x).\nQed.\n\nGoal diagonal.\nintros X p [x A].\nspecialize (A x).\ntauto.\nQed.\n\nAxiom doub_neg : forall (X : Prop), ~~X -> X.\n\nVariable X : Type.\n\nLemma fst_law :\n forall (p : X -> Prop), ~ (forall x:X, ~ p x) -> exists x : X, p x.\nProof.\nintros P notall.\napply doub_neg.\nintro abs.\napply notall.\nintros x H.\napply abs.\nexists x.\nexact H.\nQed.\n\nLemma de_morgan_quatifier :\n forall p:X -> Prop, ~ (forall x:X, p x) -> exists x : X, ~ p x.\nProof.\nintros P notall.\napply fst_law.\nintro all; apply notall.\nintro n; apply doub_neg.\napply all.\nQed.\n\nLemma conj_intro : forall X Y : Prop, X -> Y -> X /\\ Y.\ntauto.\nDefined.\n\nLemma conj_elim_fst : forall X Y : Prop, X /\\ Y -> X.\ntauto.\nDefined.\n\nLemma conj_elim_snd : forall X Y : Prop, X /\\ Y -> Y.\ntauto. Defined.\n", "meta": {"author": "DanielRrr", "repo": "Coq-Studies", "sha": "a7cd6bd7f61e91ca118a615e62dfe8fec50b70d3", "save_path": "github-repos/coq/DanielRrr-Coq-Studies", "path": "github-repos/coq/DanielRrr-Coq-Studies/Coq-Studies-a7cd6bd7f61e91ca118a615e62dfe8fec50b70d3/Computational_Logic4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8244619177503206, "lm_q1q2_score": 0.7275281710533936}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := mult (Succ y) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj208_coqofml_ClzcyI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7275230934800904}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus (mult y x) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj208_coqofml_kWFzdg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7275230848373473}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  Succ (plus Zero x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj3411_coqofml_1BYAZH.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.727523076912005}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  plus (plus y x) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj184_coqofml_kmLbUu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7275230747513193}}
{"text": "(* Software Foundations *)\n(* Exercice 1 star, SSSSev__even *)\n\nInductive ev: nat -> Prop :=\n|ev_0: ev 0\n|ev_ss: forall n: nat, ev n -> ev (S (S n)).\n\n\nTheorem SSSSev__even : forall n, ev (S (S (S (S n)))) -> ev n.\nProof.\n    intros.\n    inversion H.\n    inversion H1.\n    apply H3.\nQed.\n\n\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter9_Library_Prop/SSSSev__even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.727518200597359}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus x (Succ (plus lf1 y)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj203_coqofml_f594aq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.7275181979045591}}
{"text": "From mathcomp Require Import all_ssreflect zify.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLemma odd_add (n m : nat) : odd (m + n) = odd m (+) odd n.\nProof. lia. Qed.\n", "meta": {"author": "math-comp", "repo": "mczify", "sha": "c396805d70ac6fb9f23dfbcf95682477142c6e84", "save_path": "github-repos/coq/math-comp-mczify", "path": "github-repos/coq/math-comp-mczify/mczify-c396805d70ac6fb9f23dfbcf95682477142c6e84/examples/boolean.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7931059462938814, "lm_q1q2_score": 0.7275181956616485}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  plus x (Succ (plus y lf2)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj185_coqofml_VTSGgH.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7275181947684053}}
{"text": "Require Import mathcomp.ssreflect.ssreflect.\n\nLemma foo2 : forall n: nat, n + 0 = n.\nProof.\n  intro.\n  induction n. {\n    simpl.\n    reflexivity.\n  } {\n    simpl.\n    have foo: 0 = 0 by simpl; reflexivity.\n    have foo2: 0 = 0 by assumption.\n    have foo3: 0 = 0 by trivial.\n    have foo4: 0 = 0 by exact foo3.\n    have foo5: 0 = 0 by apply foo4.\n    (* have ihn : 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 +  n + 0 = n by assumption. *)\n    rewrite -> IHn.\n    reflexivity.\n  }\nQed.\n  \n", "meta": {"author": "ml4tp", "repo": "gamepad", "sha": "7092f50a96eae9a862e72ecb8a55a217fa97723c", "save_path": "github-repos/coq/ml4tp-gamepad", "path": "github-repos/coq/ml4tp-gamepad/gamepad-7092f50a96eae9a862e72ecb8a55a217fa97723c/examples/foo3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7275181947618701}}
{"text": "Require Import Bool List Arith Nat Coq.Arith.Div2.\nImport ListNotations.\n\n\n\nFixpoint bit_n (l : list bool) : nat :=\n  match l with\n    | [] => 0\n    | a :: tl => 2 * bit_n tl + Nat.b2n a\n  end.\n\n\nFixpoint n_bit (n : nat) (k : nat) : option (list bool) :=\n    match n with\n      | 0 => match k with\n             | 0 => Some []\n             | S _ => None\n             end\n      | S n' => match n_bit n' (Nat.div2 k) with\n                  | None => None\n                  | Some l => Some (Nat.odd k :: l)\n                end\n    end.\n\nCompute pow 2 8.\nCheck leb 2 3.\n\n    \n\n\nSearchAbout (_ mod _).\n\nLemma size_n_bit : forall (n k: nat) (l : list bool),\n    n_bit n k = Some l -> length l = n.\nProof.\n  induction n.\n  -intros k l.\n   induction k.\n   +intros.\n    inversion H.\n    reflexivity.\n   +simpl.\n    discriminate.\n  -intros k l.\n   simpl.\n   case_eq (n_bit n (Nat.div2 k)).  \n   +intros.\n    inversion H0.\n    assert (help1: forall (l' : list bool) (b : bool), length l' = n -> length(b :: l') = S n).\n    {\n      induction l'.\n      -intros b.\n       simpl.\n       intros.\n       rewrite H1.\n       reflexivity.\n      -intros b.\n       simpl.\n       intros.\n       rewrite H1.\n       reflexivity.\n    }    \n    apply help1.\n    specialize (IHn (Nat.div2 k)).\n    apply IHn.\n    exact H.\n   +intros.\n    discriminate.\nQed.\n     \n\n(* first proof that we need on binary representation *)\nTheorem n_bit_n : forall (l : list bool) (n k : nat),\n                    n_bit n k = Some l -> bit_n l = k.\nProof.\n  assert (I : forall (l : list bool) (n k : nat), n_bit n k = Some l -> bit_n l = k).\n  {\n    intros l; induction l; intros n k.\n    simpl.\n    assert (I_1 : n_bit n k = Some [] -> bit_n [] = k).\n    {\n      induction k.\n      - reflexivity.\n       (* the hypothesis is false so we will need to find how to demonstrate this *)\n      - assert (I_1_1 : n_bit n (S k) = Some [] -> bit_n [] = S k).\n       {\n         induction n.\n         - discriminate.\n         - unfold n_bit; fold n_bit.\n           destruct (n_bit n (Nat.div2 (S k))); discriminate.\n       }\n       exact I_1_1.\n    }\n    exact I_1.\n    assert (I_2 : n_bit n k = Some (a :: l) -> bit_n (a :: l) = k).\n    {\n      intros H.\n      simpl.\n      About Nat.div2_odd.\n      rewrite (Nat.div2_odd k).\n      simpl.\n      destruct n; simpl in H.\n      - destruct k; discriminate.\n      - destruct (n_bit n (Nat.div2 k)) eqn:Hl; try discriminate.\n        inversion H; subst.\n        erewrite IHl; eauto.\n    }\n    assumption.\n  }\n  assumption.\nQed.\n\n\n(* second proof *)\nTheorem bit_n_bit : forall (l : list bool) (n : nat),\n                      n = length l -> (n_bit n (bit_n l)) = Some l.\nProof.\n  assert (I : forall (l : list bool) (n : nat), n = length l -> n_bit n (bit_n l) = Some l).\n  {\n    induction l.\n    assert (I_1 : forall n : nat, n = length ([] : list bool) -> n_bit n (bit_n []) = Some []).\n    {\n      simpl.\n      intros n H.\n      rewrite H.\n      reflexivity.\n    }\n    exact I_1.\n    assert (I_2 : forall n : nat, n = length (a :: l) -> n_bit n (bit_n (a :: l)) = Some (a :: l)).\n    {\n      intros n.\n      simpl.\n      destruct a.\n      assert (I_2_1 : n = length (true :: l) -> n_bit n (bit_n (true :: l)) = Some (true :: l)).\n      {\n        simpl.\n        Search (_ + 0).\n        rewrite <- plus_n_O.\n        intros H.\n        rewrite H.\n        simpl.\n        assert (I_2_1_1 : forall l' : (list bool), bit_n l' + bit_n l' = 2 * bit_n l').\n        {\n          induction l'.\n          -reflexivity.\n          -simpl.\n           rewrite <- plus_n_O.\n           rewrite <- plus_n_O.\n           reflexivity.\n        }        \n        rewrite I_2_1_1.\n        Search (_ + 1 = S _).\n        Search (Nat.div2 _).\n        rewrite Nat.add_1_r.\n        Check even_div2.\n        rewrite <- even_div2.\n        -Search (Nat.div2 (2 * _)).\n         rewrite div2_double.\n         rewrite IHl.\n         +assert (I_2_1_2 : forall (n' : nat), Nat.odd (S (2 * n')) = true).\n          {\n            intros n'.\n            induction n'.\n            -reflexivity.\n            -simpl.\n             rewrite <- plus_n_Sm.\n             simpl in IHn'.\n             rewrite <- IHn'.\n             Search (Nat.odd (S (S _))).\n             rewrite Nat.odd_succ_succ. reflexivity.\n          }\n          rewrite I_2_1_2.\n          reflexivity.\n         +reflexivity.\n        -assert (I_2_1_3 : Even.even (2 * bit_n l)).\n         {\n           (* this is supposed to be trivial -_-_-_-_-_-_-_-_-_-_-_-_- *)\n           Check Nat.even_add_mul_2.\n           Search (0 + _).\n           rewrite <- Nat.add_0_l.\n           SearchAbout (even (_ + _)).\n           specialize (Nat.even_add_mul_2 0 (bit_n l)).\n           intros.\n           Check Even.even_equiv.\n           apply Even.even_equiv.\n           (* even spec *)\n           Check Nat.even_spec.\n           simpl in H0.\n           Search (_ + _ = 2 * _).\n           Check I_2_1_1.\n           rewrite <- I_2_1_1.\n           assert (0 + (bit_n l + bit_n l) = bit_n l + (bit_n l + 0)).\n           { simpl. Search (_ + 0). rewrite <- plus_n_O. reflexivity. }\n           rewrite H1. \n           rewrite Nat.even_spec in H0.\n           exact H0.\n         }\n         exact I_2_1_3.\n      }\n      exact I_2_1.\n      assert (I_2_2 : n = S (length l) -> n_bit n (bit_n l + (bit_n l + 0) + Nat.b2n false) = Some (false :: l)).\n      {\n        simpl.\n        Search (_ + 0).\n        rewrite <- plus_n_O.\n        rewrite <- plus_n_O.\n        intros H.\n        rewrite H.\n        simpl.\n        Search (2 * _ = _).\n        assert (I_2_2_0 : forall (n' : nat), 2 * n' = n' + n').\n        {\n          intros n'. simpl. rewrite <- plus_n_O. reflexivity.\n        }\n        rewrite <- I_2_2_0.\n        rewrite div2_double.\n        rewrite IHl.\n        -assert (I_2_2_1 : forall (n' : nat), Nat.odd (2 * n') = false).\n         {\n           induction n'.\n           -simpl. Search (Nat.odd 0).\n            rewrite Nat.odd_0. reflexivity.\n           -simpl.\n            Search (_ + 0).\n            rewrite <- plus_n_O.\n            Search (_ + _ = _ + _).\n            rewrite <- plus_Snm_nSm.\n            Search (S _ + _).\n            rewrite plus_Sn_m.\n            Search (Nat.odd (S (S _))).\n            rewrite Nat.odd_succ_succ.\n            simpl in IHn'.\n            rewrite <- plus_n_O in IHn'.\n            rewrite IHn'.\n            reflexivity.            \n         }\n         rewrite I_2_2_1.\n         reflexivity.\n        -reflexivity.\n      }\n      exact I_2_2.\n    }\n    exact I_2.\n  }\n  exact I.\nQed.", "meta": {"author": "romisfrag", "repo": "little_mmx_encode-decode", "sha": "9f5a583fc2376f271bac30ec82c8800614a5fdd6", "save_path": "github-repos/coq/romisfrag-little_mmx_encode-decode", "path": "github-repos/coq/romisfrag-little_mmx_encode-decode/little_mmx_encode-decode-9f5a583fc2376f271bac30ec82c8800614a5fdd6/srcOld2/binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7275181844536297}}
{"text": "Require Import BinNat.\nRequire Import Program.Basics.\nRequire Import Logic.FunctionalExtensionality.\nRequire Import micromega.Lia.\nRequire Import Nnat.\nRequire Import Omega.\nRequire Import bin_prelims.\nRequire repeater.\nOpen Scope N_scope.\n\n(*\n====================================================================================\n*********** SECTION 9: BINARY HYPEROPS, ACKERMANN AND REPEATER *********************\n====================================================================================\n *)\n\n(* \n * We introduce \"bin_repeater\" and how to use it to define the \n * bin_hyperoperations and binary Ackermann function.\n * \n * We also prove several results about the value of hypeopererations at small\n * numbers and levels, which are treated as known in the paper but need to be\n * rigourously proven here to be used in the proofs of theorems in the paper.\n *\n * Several similar results for the Ackermann function are also provided.\n * Note that some results here may not be related to results in the paper, but\n * appear for reasons of completeness.\n *)\n\n\n(* ****** REPEATER ********************************* *)\n\nDefinition bin_repeater_from (f : N -> N) (a : N) (n : N) : N :=\n  match n with\n  | 0      => a\n  | Npos p =>\n      let fix bin_repeater_pos (g : N -> N) (p : positive) (a' : N) : N :=\n        match p with\n        | xH    => g a'\n        | xO p' => let g' := bin_repeater_pos g p' in g' (g' a')\n        | xI p' => let g' := bin_repeater_pos g p' in g (g' (g' a'))\n        end in bin_repeater_pos f p a\n  end.\n\n(* Repeater is a functional way to look at repeat.\n   See \"repeat\" in \"prelims.v\" *)\nTheorem bin_repeater_repeat :\n    forall a f n, bin_repeater_from f a n = repeat f (N.to_nat n) a.\nProof.\n  intros a f n. destruct n; trivial. simpl.\n  generalize dependent a.\n  induction p; intro a; [ | |trivial];\n  [replace (Pos.to_nat p~1) with\n    (S (Pos.to_nat p + Pos.to_nat p))%nat by lia|\n  replace (Pos.to_nat p~0) with\n    (Pos.to_nat p + Pos.to_nat p)%nat by lia];\n    simpl; f_equal; rewrite repeat_plus;\n      repeat rewrite IHp; trivial.\nQed.\n\n(* Repeater on N is consistent with its counterpart on nat *)\nTheorem bin_repeater_Nnat : \n    forall a f n, bin_repeater_from f a n =\n      N.of_nat (repeater.repeater_from\n                  (to_nat_func f) (N.to_nat a) (N.to_nat n)).\nProof.\n  intros a f n. rewrite bin_repeater_repeat.\n  rewrite repeater.repeater_from_repeat.\n  remember (N.to_nat n) as m. clear Heqm.\n  unfold to_nat_func.\n  induction m; simpl; [ |rewrite <- IHm];\n    rewrite N2Nat.id; trivial.\nQed.\n\n\n(* ****** HYPEROPS ********************************* *)\n\n(* A function to summarize the initial values of the bin_hyperoperations *)\nDefinition bin_hyperop_init (a : N) (n : nat) : N :=\n  match n with 0%nat => a | 1%nat => 0 | _ => 1 end.\n\n(* Our definition for bin_hyperops using bin_repeater_from *)\nFixpoint bin_hyperop (a : N) (n : nat) (b : N) : N :=\n  match n with\n  | 0%nat => 1 + b\n  | S n'  => bin_repeater_from (bin_hyperop a n') (bin_hyperop_init a n') b\n  end.\n\n(* A handy theorem to transform goals involving bin_hyperops *)\nLemma bin_hyperop_recursion :\n  forall (n : nat) (a : N),\n    bin_hyperop a (S n) = bin_repeater_from (bin_hyperop a n)\n                                            (bin_hyperop_init a n).\nProof. intros. apply functional_extensionality. intro b. trivial. Qed.\n\n(* Proof that the two bin_hyperops are the same *)\nTheorem bin_hyperop_correct :\n  forall n a b, bin_hyperop a n b =\n                N.of_nat (repeater.hyperop (N.to_nat a) n (N.to_nat b)).\nProof.\n  intros n a. induction n; intro b.\n  - unfold bin_hyperop. unfold repeater.hyperop. lia.\n  - rewrite bin_hyperop_recursion.\n    replace (repeater.hyperop (N.to_nat a) (S n) (N.to_nat b)) with\n    (repeater.repeater_from (repeater.hyperop (N.to_nat a) n)\n                          (repeater.hyperop_init (N.to_nat a) n)\n                          (N.to_nat b)) by trivial.\n    replace (repeater.hyperop_init (N.to_nat a) n) with\n    (N.to_nat (bin_hyperop_init a n)) by repeat (destruct n; trivial).\n    rewrite bin_repeater_Nnat. repeat f_equal.\n    apply functional_extensionality; intro c.\n    unfold to_nat_func. rewrite IHn. repeat rewrite Nat2N.id. trivial.\nQed.\n\n(* \n * The first few functions in the bin_hyperops. \n * Useful for pointing out their inverses specifically \n *)\n\nLemma bin_hyperop_1 : forall a b, bin_hyperop a 1 b = b + a.\nProof.\n  intros. rewrite bin_hyperop_correct. rewrite repeater.hyperop_1. lia.\nQed.\n\nLemma bin_hyperop_2 : forall a b, bin_hyperop a 2 b = b * a.\nProof.\n  intros. rewrite bin_hyperop_correct. rewrite repeater.hyperop_2. lia.\nQed.\n\nLemma bin_hyperop_3 : forall a b, bin_hyperop a 3 b = a ^ b.\nProof.\n  intros. rewrite bin_hyperop_correct. rewrite repeater.hyperop_3.\n  remember (N.to_nat a) as a0. replace a with (N.of_nat a0) by lia.\n  clear Heqa0.\n  remember (N.to_nat b) as b0. replace b with (N.of_nat b0) by lia.\n  clear Heqb0.\n  induction b0; trivial.\n  replace (N.of_nat (S b0)) with (1 + N.of_nat b0) by lia.\n  rewrite N.pow_add_r. rewrite N.pow_1_r. simpl. rewrite <- IHb0. lia.\nQed.\n\n(* \n * A beautiful result about hypeops value at b = 1.\n * Used in the proof of the theorem \"ack_bin_hyperop\",\n *  which is also included just for completeness \n *)\nLemma bin_hyperop_n_1 :\n    forall n a, (2 <= n)%nat -> bin_hyperop a n 1 = a.\nProof.\n  intros n a Hn. do 2 (destruct n; [omega|]).\n  clear Hn. induction n; trivial.\nQed.\n\n\n(* ****** ACKERMANN FUNCTION ********************************* *)\n\n(* Our definition using bin_repeater_from *)\nDefinition bin_ackermann (n m : N) : N :=\n  let fix ack_nat (n0 : nat) (m0 : N) : N :=\n   match n0 with\n   | 0%nat => 1 + m0\n   | S n1  => bin_repeater_from (ack_nat n1) (ack_nat n1 1) m0\n   end in ack_nat (N.to_nat n) m.\n\n(* Proof that the above are the same *)\nTheorem bin_ackermann_correct : forall n m,\n    bin_ackermann n m =\n      N.of_nat (repeater.ackermann (N.to_nat n) (N.to_nat m)).\nProof.\n  intros n m. unfold bin_ackermann. unfold repeater.ackermann.\n  generalize dependent m. induction (N.to_nat n); intro m; [lia| ].\n  rewrite bin_repeater_Nnat. repeat f_equal;\n  [unfold to_nat_func; apply functional_extensionality; intro p| ];\n  rewrite IHn0; repeat rewrite Nat2N.id; trivial.\nQed.", "meta": {"author": "inv-ack", "repo": "inv-ack", "sha": "195209ba895061fc51368c3c46c1d8760f05df50", "save_path": "github-repos/coq/inv-ack-inv-ack", "path": "github-repos/coq/inv-ack-inv-ack/inv-ack-195209ba895061fc51368c3c46c1d8760f05df50/bin_repeater.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7274933704532159}}
{"text": "Require Import ZArith.\n\nOpen Scope Z_scope.\n\nDefinition pol := fun x:Z => 2*x*x + 3*x +3.\nReset pol.\n\nDefinition pol (x:Z) : Z := 2*x*x + 3*x +3.\n\nEval compute in (pol (-6)).\nEval compute in (pol 1024).\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/specprog/SRC/polynom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7274676794810631}}
{"text": "Require Import Coq.ZArith.BinInt.\nRequire Import Coq.micromega.Psatz.\nRequire Import Crypto.Util.ForLoop.\nRequire Import Crypto.Util.ForLoop.InvariantFramework.\nRequire Import Crypto.Util.ZUtil.\n\nLocal Open Scope Z_scope.\n\nCheck (for i (:= 0; += 1; < 10) updating (v := 5) {{ v + i }}).\nCheck (for (int i = 0; i < 5; i++) updating ( '(v1, v2) = (0, 0) ) {{ (v1 + i, v2 + i) }}).\n\nCompute for (int i = 0; i < 5; i++) updating (v = 0) {{ v + i }}.\nCompute for (int i = 0; i <= 5; i++) updating (v = 0) {{ v + i }}.\nCompute for (int i = 5; i > -1; i--) updating (v = 0) {{ v + i }}.\nCompute for (int i = 5; i >= 0; i--) updating (v = 0) {{ v + i }}.\nCompute for (int i = 0; i < 5; i += 2) updating (v = 0) {{ v + i }}.\nCompute for (int i = 0; i <= 5; i += 2) updating (v = 0) {{ v + i }}.\nCompute for (int i = 5; i > -1; i -= 2) updating (v = 0) {{ v + i }}.\nCompute for (int i = 5; i >= 0; i -= 2) updating (v = 0) {{ v + i }}.\nCompute for (int i = 0; i < 6; i += 2) updating (v = 0) {{ v + i }}.\nCompute for (int i = 0; i <= 6; i += 2) updating (v = 0) {{ v + i }}.\nCompute for (int i = 6; i > -1; i -= 2) updating (v = 0) {{ v + i }}.\nCompute for (int i = 6; i >= 0; i -= 2) updating (v = 0) {{ v + i }}.\nCheck eq_refl : for (int i = 0; i <= 5; i++) updating (v = 0) {{ v + i }} = 15.\nCheck eq_refl : for (int i = 0; i < 5; i++) updating (v = 0) {{ v + i }} = 10.\nCheck eq_refl : for (int i = 5; i >= 0; i--) updating (v = 0) {{ v + i }} = 15.\nCheck eq_refl : for (int i = 5; i > -1; i--) updating (v = 0) {{ v + i }} = 15.\nCheck eq_refl : for (int i = 0; i <= 5; i += 2) updating (v = 0) {{ v + i }} = 6.\nCheck eq_refl : for (int i = 0; i < 5; i += 2) updating (v = 0) {{ v + i }} = 6.\nCheck eq_refl : for (int i = 5; i > -1; i -= 2) updating (v = 0) {{ v + i }} = 9.\nCheck eq_refl : for (int i = 5; i >= 0; i -= 2) updating (v = 0) {{ v + i }} = 9.\nCheck eq_refl : for (int i = 0; i <= 6; i += 2) updating (v = 0) {{ v + i }} = 12.\nCheck eq_refl : for (int i = 0; i < 6; i += 2) updating (v = 0) {{ v + i }} = 6.\nCheck eq_refl : for (int i = 6; i > -1; i -= 2) updating (v = 0) {{ v + i }} = 12.\nCheck eq_refl : for (int i = 6; i >= 0; i -= 2) updating (v = 0) {{ v + i }} = 12.\n\nLocal Notation for_sumT n'\n  := (let n := Z.pos n' in\n      (2 *\n       for (int i = 0; i <= n; i++) updating (v = 0) {{\n         v + i\n       }})%Z\n      = n * (n + 1))\n       (only parsing).\n\nCheck eq_refl : for_sumT 5.\n\n(** Here we show that if we add the numbers from 0 to n, we get [n * (n + 1) / 2] *)\nExample for_sum n' : for_sumT n'.\nProof.\n  intro n.\n  apply for_loop_ind_le1.\n  { compute; reflexivity. }\n  { intros; nia. }\nQed.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Util/ForLoop/Tests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7274488197023268}}
{"text": "Require Export Lists.\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\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.\n\nExample test_length1 :\n    length nat (cons nat 1 (cons nat 2 (nil nat))) = 2.\nProof. reflexivity.  Qed.\n\nExample test_length2 :\n    length bool (cons bool true (nil bool)) = 1.\nProof. reflexivity.  Qed.\n\nFixpoint app (X : Type) (l1 l2 : list X)\n                : (list X) :=\n  match l1 with\n  | nil _     => l2\n  | cons _ h t => cons X h (app X t l2)\n  end.\n\nFixpoint snoc (X:Type) (l:list X) (v:X) : (list X) :=\n  match l with\n  | nil _      => cons X v (nil X)\n  | cons _ h t => cons X h (snoc X t v)\n  end.\n\nFixpoint rev (X:Type) (l:list X) : list X :=\n  match l with\n  | nil _      => nil X\n  | cons _ h t => snoc X (rev X t) h\n  end.\n\nExample test_rev1 :\n    rev nat (cons nat 1 (cons nat 2 (nil nat)))\n  = (cons nat 2 (cons nat 1 (nil nat))).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev bool (nil bool) = nil bool.\nProof. reflexivity.  Qed.\n\nArguments nil {X}.\nArguments cons {X} _ _.  (* use underscore for argument position that has no name *)\nArguments length {X} l.\nArguments app {X} l1 l2.\nArguments rev {X} l. \nArguments snoc {X} l v.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\nFixpoint repeat {X : Type} (n : X) (count : nat) : list X :=\n  match count with\n  | 0 => []\n  | S count' => n :: (repeat n count')\n  end.\n\nExample test_repeat1:\n  repeat true 2 = cons true (cons true nil).\nProof. reflexivity. Qed.\n\nTheorem nil_app : forall X:Type, forall l:list X,\n  app [] l = l.\nProof. reflexivity. Qed.\n\nTheorem rev_snoc : forall X : Type,\n                     forall v : X,\n                     forall s : list X,\n  rev (snoc s v) = v :: (rev s).\nProof.\n  intros.\n  induction s as [| n t].\n  reflexivity.\n  simpl.\n  rewrite IHt.\n  reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l as [| n t].\n  reflexivity.\n  simpl.\n  rewrite rev_snoc.\n  rewrite IHt.\n  reflexivity.\nQed.\n\nTheorem snoc_with_append : forall X : Type,\n                         forall l1 l2 : list X,\n                         forall v : X,\n  snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).\nProof.\n  intros. induction l1 as [|v' l1'].\n  reflexivity.\n  simpl.\n  rewrite IHl1'.\n  reflexivity.\nQed.\n\nInductive prod (X Y : Type) : Type :=\n  pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with (x,y) => x end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with (x,y) => y end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match (lx,ly) with\n  | ([],_) => []\n  | (_,[]) => []\n  | (x::tx, y::ty) => (x,y) :: (combine tx ty)\n  end.\n\nFixpoint subsplit {X Y : Type} (l : list (X*Y)) (xs: list X) (ys: list Y)\n           : (list X) * (list Y) :=\n  match l with\n  | [] => (xs, ys)\n  | (x, y) :: xys => subsplit xys (x :: xs) (y :: ys)\n  end.\n\nDefinition split\n           {X Y : Type} (l : list (X*Y))\n           : (list X) * (list Y) :=\n  match subsplit l [] [] with\n  | (xs, ys) => (rev xs, rev ys)\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _. \nArguments None {X}. \n\nFixpoint index {X : Type} (n : nat)\n               (l : list X) : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else index (pred n) l'\n  end.\n\nExample test_index1 :    index 0 [4;5;6;7]  = Some 4.\nProof. reflexivity.  Qed.\nExample test_index2 :    index  1 [[1];[2]]  = Some [2].\nProof. reflexivity.  Qed.\nExample test_index3 :    index  2 [true]  = None.\nProof. reflexivity.  Qed.\n\nDefinition hd_opt {X : Type} (l : list X)  : option X :=\n  match l with\n  | [] => None\n  | v :: _ => Some v\n  end.\n\nExample test_hd_opt1 :  hd_opt [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_opt2 :   hd_opt  [[1];[2]]  = Some [1].\nProof. reflexivity. Qed.\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\nDefinition plus3 := plus 3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  match p with\n  | (x, y) => f x y\n  end.\n\nTheorem uncurry_curry : forall (X Y Z : Type) (f : X -> Y -> Z) x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof. reflexivity. Qed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                               (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros.\n  destruct p as [m n].\n  reflexivity.\nQed.\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7) *)\n\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun i => andb (evenb i) (blt_nat 7 i)) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\nDefinition partition {X : Type} (f: X -> bool) (l: list X) : list X * list X :=\n  (filter f l, filter (fun v => negb (f v)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\nFixpoint map {X Y:Type} (f:X->Y) (l:list X)\n             : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\nExample test_map1: map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\nExample test_map2: map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\nTheorem map_snoc: forall (X Y : Type) (f : X -> Y) (l : list X) (v : X),\n  map f (snoc l v) = snoc (map f l) (f v).\nProof.\n  intros.\n  induction l as [|w m].\n  reflexivity.\n  simpl.\n  rewrite IHm.\n  reflexivity.\nQed.\n\n(** ** Map for options *)\n(** **** Exercise: 3 stars (map_rev) *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\nTheorem map_rev: forall (X Y : Type) (f : X -> Y) (l : list X), map f (rev l) = rev (map f l).\nProof.\n  intros.\n  induction l as [|v m].\n  reflexivity.\n  simpl.\n  rewrite <- IHm.\n  rewrite map_snoc.\n  reflexivity.\nQed.\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                   : (list Y) :=\n  match l with\n  | [] => []\n  | x :: xs => f x ++ flat_map f xs\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y) : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\nExample fold_example1 : fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 : fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 : fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\nDefinition override {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if beq_nat k k' then x else f k'.\n\nDefinition fmostlytrue := override (override ftrue 1 false) 3 false.\n\nExample override_example1 : fmostlytrue 0 = true.\nProof. reflexivity. Qed.\n\nExample override_example2 : fmostlytrue 1 = false.\nProof. reflexivity. Qed.\n\nExample override_example3 : fmostlytrue 2 = true.\nProof. reflexivity. Qed.\n\nExample override_example4 : fmostlytrue 3 = false.\nProof. reflexivity. Qed.\n\nTheorem override_example : forall (b:bool),\n  (override (constfun b) 3 true) 2 = b.\nProof. reflexivity. Qed.\n\nTheorem unfold_example : forall m n,\n  3 + n = m ->\n  plus3 n + 1 = m + 1.\nProof.\n  intros m n H.\n  unfold plus3.\n  rewrite -> H.\n  reflexivity.  Qed.\n\nTheorem beq_nat_refl : forall n : nat, beq_nat n n = true.\nProof. intros. induction n as [| n']. reflexivity. simpl. rewrite IHn'. reflexivity. Qed.\n\nTheorem override_eq : forall {X:Type} x k (f:nat->X),\n  (override f k x) k = x.\nProof.\n  intros X x k f.\n  unfold override.\n  rewrite beq_nat_refl.\n  reflexivity.  Qed.\n\nTheorem override_neq : forall (X:Type) x1 x2 k1 k2 (f : nat->X),\n  f k1 = x1 ->\n  beq_nat k2 k1 = false ->\n  (override f k2 x2) k1 = x1.\nProof.\n  intros.\n  unfold override.\n  rewrite H0.\n  assumption.\nQed.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros.\n  induction l as [|n l'].\n  reflexivity.\n  simpl.\n  rewrite <- IHl'.\n  reflexivity.\nQed.\n\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=\n  fold (fun elem acc => f elem :: acc) l [].\n\nExample test_fold_map1: fold_map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\nExample test_fold_map2: fold_map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\nExample test_fold_map3:\n   fold_map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\nTheorem fold_map_eq: forall (X Y : Type) (f : X -> Y) (l : list X),\n  fold_map f l = map f l.\nProof.\n  intros. induction l as [|n l'].\n  reflexivity.\n  simpl.\n  rewrite <- IHl'.\n  reflexivity.\nQed.\n\n", "meta": {"author": "ejconlon", "repo": "sfsolutions", "sha": "0bb5c48f00d10e80fe63220b0d7eeebcfb3e04d4", "save_path": "github-repos/coq/ejconlon-sfsolutions", "path": "github-repos/coq/ejconlon-sfsolutions/sfsolutions-0bb5c48f00d10e80fe63220b0d7eeebcfb3e04d4/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571775, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7274488007605215}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  mult (Succ x) (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj251_coqofml_rAVhFI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7274342836075824}}
{"text": "Require Import Coq.Program.Basics.\n\nLemma rmConj (P Q R: Prop): iff (P /\\ Q -> R) (P -> Q -> R).\nProof.\n  unfold impl; tauto.\nQed.\n\nLemma rmDisj (P Q R: Prop): iff (P \\/ Q -> R) ((P -> R) /\\ (Q -> R)).\nProof.\n  unfold impl; tauto.\nQed.\n\nLemma dupConj (P Q R: Prop): iff (P -> (Q /\\ R)) ((P -> Q) /\\ (P -> R)).\nProof.\n  unfold impl; tauto.\nQed.\n\nLemma bool_true a: iff (a = true -> False) (a = false).\nProof.\n  destruct a; intuition discriminate.\nQed.\n\nLemma bool_false a: iff (a = false -> False) (a = true).\nProof.\n  destruct a; intuition discriminate.\nQed.\n\nLemma quantConj A (P Q: A -> Prop): iff (forall a, P a /\\ Q a) ((forall a, P a) /\\ (forall a, Q a)).\nProof.\n  split; intros; firstorder fail.\nQed.\n\n#[global] Hint Rewrite rmConj rmDisj dupConj bool_true bool_false quantConj: basicLogic.\n\n\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/Lib/BasicLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7274342679081796}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Properties of Unary and Binary Operations                               *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics.\n\n(* ********************************************************************** *)\n(** * Types of unary and binary operators and relations *)\n\nDefinition oper1 (A : Type) := A -> A.\nDefinition oper2 (A : Type) := A -> A -> A.\nDefinition predb (A:Type) := A -> bool.\n\n(* ********************************************************************** *)\n(** * Definition of the properties of operators *)\n\nSection Definitions.\n\nVariable (A : Type).\nImplicit Types f g : oper2 A.\nImplicit Types i : oper1 A.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Commutativity, associativity *)\n\n(** Commutativity *)\n\nDefinition comm f := forall x y,\n  f x y = f y x.\n\n(** Associativity *)\n\nDefinition assoc f := forall x y z,\n  f x (f y z) = f (f x y) z.\n\n(** Combined associativity commutativity *)\n\nDefinition comm_assoc f := forall x y z,\n  f x (f y z) = f y (f x z).\n\n(* ---------------------------------------------------------------------- *)\n(** ** Distributivity *)\n\n(** Distributivity of unary operator *)\n\nDefinition distrib i f := forall x y,\n  i (f x y) = f (i x) (i y).\n\n(** Commutative distributivity of unary operator *)\n\nDefinition distrib_comm i f := forall x y,\n  i (f x y) = f (i y) (i x).\n\n(** Left distributivity *)\n\nDefinition distrib_l f g := forall x y z,\n  f x (g y z) = g (f x y) (f x z).\n\n(** Right distributivity *)\n\nDefinition distrib_r f g := forall x y z,\n  f (g y z) x = g (f y x) (f z x).\n\n(* ---------------------------------------------------------------------- *)\n(** ** Neutral and absorbant *)\n\n(** Left Neutral *)\n\nDefinition neutral_l f e:= forall x,\n  f e x = x.\n\n(** Right Neutral *)\n\nDefinition neutral_r f e := forall x,\n  f x e = x.\n\n(** Left Absorbant *)\n\nDefinition absorb_l f a := forall x,\n  f a x = a.\n\n(** Right Absorbant *)\n\nDefinition absorb_r f a := forall x,\n  f x a = a.\n\n(** Idempotence *)\n\nDefinition idempotent i := forall x,\n  i (i x) = i x.\n\nLemma use_idempotent : forall i x y,\n  idempotent i ->\n  y = i x ->\n  i y = y.\n  (* Expanded statement, for easier use by [eauto]. *)\nProof using.\n  intros. subst. eauto.\nQed.\n\n(** Idempotence *)\n\nDefinition involutive i := forall x,\n  i (i x) = x.\n\n(** Idempotence for binary operators *) (* TEMPORARY strange terminology! *)\n\nDefinition idempotent2 f := forall x,\n  f x x = x.\n\n(** Self Neutral *)\n\nDefinition self_neutral f e x :=\n  f x x = e.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inverses *)\n\n(** Left Inverse *)\n\nDefinition inverse_for_l f e a b :=\n  f a b = e.\n\n(** Right Inverse *)\n\nDefinition inverse_for_r f e a b :=\n  f b a = e.\n\n(** Left Inverse function -- todo arguments in order f i e ? *)\n\nDefinition inverse_l f e i := forall x,\n  f (i x) x = e.\n\n(** Right Inverse function *)\n\nDefinition inverse_r f e i := forall x,\n  f x (i x) = e.\n\n(** Self Inverse *)\n\nDefinition self_inverse i x :=\n  i x = x.\n\nEnd Definitions.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Morphism and automorphism *)\n\n(** Morphism *)\n\nDefinition morphism (A B : Type) (h : A -> B) (f : oper2 A) (g : oper2 B) :=\n  forall x y, h (f x y) = g (h x) (h y).\n\n(** Auto-morphism *)\n\nDefinition automorphism A := @morphism A A.\nImplicit Arguments automorphism [A].\n\n(* ---------------------------------------------------------------------- *)\n(** ** Injectivity *)\n\nDefinition injective A B (f : A -> B) :=\n  forall x y, f x = f y -> x = y.\n\n\n(* ********************************************************************** *)\n(** * Derived properties *)\n\nSection OpProperties.\n\nVariable (A : Type).\nImplicit Types f g : oper2 A.\nImplicit Types h : oper1 A.\n\n(** For commutative operators, right-properties can be derived from\n    corresponding left-properties *)\n\nLemma neutral_r_from_comm_neutral_l : forall f e,\n  comm f -> neutral_l f e -> neutral_r f e.\nProof using. introv C N. intros_all. rewrite* C. Qed.\n\nLemma inverse_r_from_comm_inverse_l : forall f e i,\n  comm f -> inverse_l f e i -> inverse_r f e i.\nProof using. introv C I. intros_all. rewrite* C. Qed.\n\nLemma distrib_r_from_comm_distrib_l : forall f g,\n  comm f -> distrib_l f g -> distrib_r f g.\nProof using.\n  introv C N. intros_all. unfolds distrib_l.\n  do 3 rewrite <- (C x). auto.\nQed.\n\n(** [comm_assoc] derivable *)\n\nLemma comm_assoc_prove : forall f,\n  comm f -> assoc f -> comm_assoc f.\nProof using.\n  introv C S. intros_all. rewrite C.\n  rewrite <- S. rewrite~ (C x).\nQed.\n\nEnd OpProperties.\n\n\n", "meta": {"author": "zhiyuanshi", "repo": "intersection", "sha": "825f69cf7f70db7d0b829875f590fa38468bfad1", "save_path": "github-repos/coq/zhiyuanshi-intersection", "path": "github-repos/coq/zhiyuanshi-intersection/intersection-825f69cf7f70db7d0b829875f590fa38468bfad1/workinprogress/semantics/tlc/src/LibOperation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940974, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7273745742210443}}
{"text": "(* Basics: Functional Programming *)\n\nInductive 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\nEval simpl in (next_weekday friday).\n\nEval simpl in (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.\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\nDefinition xorb (b1:bool) (b2:bool) : bool := \n  match b1 with \n  | false => b2\n  | true => negb(b2)\n  end.\n\nExample test_xorb_10:\n   (xorb true false) = true.\nProof. simpl. reflexivity. Qed.\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\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.\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\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  match b1 with \n  | true => andb b2 b3\n  | false => false\n  end.\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 negb true.\nCheck negb.\nCheck andb3.\n\nModule Playground1.\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 m => m\n  end.\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\nCheck (S (S (S (S O)))).\nEval simpl in (minustwo 4).\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.\n\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.\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\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\n(* Exercise: 1 star (factorial) *)\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 3) = 6.\nProof. simpl. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n\n(* end of proof *)\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\n(* Exercise: 2 stars (blt_nat) *)\n\nDefinition blt_nat (n m : nat) : bool :=\n  andb (negb (beq_nat n m)) (ble_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.\n\n(* end of proof *)\n\n(* Proof By Simplification *)\nTheorem plus_O_n : forall n:nat, 0 + n = n.\nProof. simpl. reflexivity. Qed.\n\nEval simpl in (forall n:nat, n + 0 = n).\n\nEval simpl in (forall n:nat, 0 + n = n).\n\nTheorem plus_O_n'' : 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(* Proof by Rewriting *)\nTheorem plus_id_example : forall n m:nat,\n  n = m -> \n  n + n = m + m.\nProof.\n  intros n m. (* move both quantifiers into the context *)\n  intros H. (* move the hypothesis into the context *)\n  rewrite <- H. (* Rewrite the goal using the hypothesis *)\n  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 H.\n  rewrite -> H.\n  intros H2. \n  rewrite -> H2. 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_1_plus : forall n m : nat,\n  (1 + n) * m = m + (n * m).\nProof.\n  intros n m.\n  rewrite -> plus_1_l. \n  reflexivity. Qed.", "meta": {"author": "BrownFurSeal", "repo": "yet-another-coq", "sha": "a2d793d06f936b966da731c068bc25a8d9d8fd97", "save_path": "github-repos/coq/BrownFurSeal-yet-another-coq", "path": "github-repos/coq/BrownFurSeal-yet-another-coq/yet-another-coq-a2d793d06f936b966da731c068bc25a8d9d8fd97/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7273745654511661}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(** In this chapter we continue our development of basic \n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).\n*)\n\nRequire Export Lists.   \n\n(* ###################################################### *)\n(** * Polymorphism *)\n(* ###################################################### *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.)  for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.) *)\n\n(** What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are things of type [X]. *)\n\n(** With this definition, when we use the constructors [nil] and\n    [cons] to build lists, we need to tell Coq the type of the\n    elements in the lists we are building -- that is, [nil] and [cons]\n    are now _polymorphic constructors_.  Observe the types of these\n    constructors: *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier is\n    spelled out in letters.  In the generated HTML files, [forall] is\n    usually typeset as the usual mathematical \"upside down A,\" but\n    you'll see the spelled-out \"forall\" in a few places.  This is just\n    a quirk of typesetting: there is no difference in meaning. *)\n\n(** The \"[forall X]\" in these types can be read as an additional\n    argument to the constructors that determines the expected types of\n    the arguments that follow.  When [nil] and [cons] are used, these\n    arguments are supplied in the same way as the others.  For\n    example, the list containing [2] and [1] is written like this: *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've gone back to writing [nil] and [cons] explicitly here\n    because we haven't yet defined the [ [] ] and [::] notations for\n    the new version of lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic (or \"generic\")\n    versions of all the list-processing functions that we wrote\n    before.  Here is [length], for example: *)\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.\n\n(** Note that the uses of [nil] and [cons] in [match] patterns\n    do not require any type annotations: we already know that the list\n    [l] contains elements of type [X], so there's no reason to include\n    [X] in the pattern.  (More precisely, the type [X] is a parameter\n    of the whole definition of [list], not of the individual\n    constructors.  We'll come back to this point later.)\n\n    As with [nil] and [cons], we can use [length] by applying it first\n    to a type and then to its list argument: *)\n\nExample test_length1 :\n    length nat (cons nat 1 (cons nat 2 (nil nat))) = 2.\nProof. reflexivity.  Qed.\n\n(** To use our length with other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_length2 :\n    length bool (cons bool true (nil bool)) = 1.\nProof. reflexivity.  Qed.\n\n(** Let's close this subsection by re-implementing a few other\n    standard list functions on our new polymorphic lists: *)\n\nFixpoint app (X : Type) (l1 l2 : list X)\n                : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons X h (app X t l2)\n  end.\n\nFixpoint snoc (X:Type) (l:list X) (v:X) : (list X) :=\n  match l with\n  | nil      => cons X v (nil X)\n  | cons h t => cons X h (snoc X t v)\n  end.\n\nFixpoint rev (X:Type) (l:list X) : list X :=\n  match l with\n  | nil      => nil X\n  | cons h t => snoc X (rev X t) h\n  end.\n\nExample test_rev1 :\n    rev nat (cons nat 1 (cons nat 2 (nil nat)))\n  = (cons nat 2 (cons nat 1 (nil nat))).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev bool (nil bool) = nil bool.\nProof. reflexivity.  Qed.\n\nModule MumbleBaz.\n(** **** Exercise: 2 stars (mumble_grumble) *)\n(** Consider the following two inductively defined types. *)\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c] \n(* \nwell-typed:\n[d mumble (b a 5)]\n[d bool (b a 5)]\n[e bool true]\n[e mumble (b c 0)]\n[c]\n*)\n[] *)\n\n(** **** Exercise: 2 stars (baz_num_elts) *)\n(** Consider the following inductive definition: *)\n\nInductive baz : Type :=\n   | x : baz -> baz\n   | y : baz -> bool -> baz.\n\n(** How _many_ elements does the type [baz] have? \n(* 0: there is no base type. *)\n[] *)\n\nEnd MumbleBaz.\n\n(* ###################################################### *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [app] again, but this time we won't\n    specify the types of any of the arguments. Will Coq still accept\n    it? *)\n\nFixpoint app' X l1 l2 : list X :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons X h (app' X t l2)\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [app']: *)\n\nCheck app'.\n(* ===> forall X : Type, list X -> list X -> list X *)\nCheck app.\n(* ===> forall X : Type, list X -> list X -> list X *)\n\n(** It has exactly the same type type as [app].  Coq was able to\n    use a process called _type inference_ to deduce what the types of\n    [X], [l1], and [l2] must be, based on how they are used.  For\n    example, since [X] is used as an argument to [cons], it must be a\n    [Type], since [cons] expects a [Type] as its first argument;\n    matching [l1] with [nil] and [cons] means it must be a [list]; and\n    so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks.  You should try to find a balance in your own code between\n    too many type annotations (so many that they clutter and distract)\n    and too few (which forces readers to perform type inference in\n    their heads in order to understand your code). *)\n\n(* ###################################################### *)\n(** *** Type Argument Synthesis *)\n\n(** Whenever we use a polymorphic function, we need to pass it\n    one or more types in addition to its other arguments.  For\n    example, the recursive call in the body of the [length] function\n    above must pass along the type [X].  But just like providing\n    explicit type annotations everywhere, this is heavy and verbose.\n    Since the second argument to [length] is a list of [X]s, it seems\n    entirely obvious that the first argument can only be [X] -- why\n    should we have to write it explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write the \"implicit argument\"\n    [_], which can be read as \"Please figure out for yourself what\n    type belongs here.\"  More precisely, when Coq encounters a [_], it\n    will attempt to _unify_ all locally available information -- the\n    type of the function being applied, the types of the other\n    arguments, and the type expected by the context in which the\n    application appears -- to determine what concrete type should\n    replace the [_].\n\n    This may sound similar to type annotation inference -- and,\n    indeed, the two procedures rely on the same underlying mechanisms.\n    Instead of simply omitting the types of some arguments to a\n    function, like\n      app' X l1 l2 : list X :=\n    we can also replace the types with [_], like\n      app' (X : _) (l1 l2 : _) : list X :=\n    which tells Coq to attempt to infer the missing information, just\n    as with argument synthesis.\n\n    Using implicit arguments, the [length] function can be written\n    like this: *)\n\nFixpoint length' (X:Type) (l:list X) : nat :=\n  match l with\n  | nil      => 0\n  | cons h t => S (length' _ t)\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference can be significant.  For\n    example, suppose we want to write down a list containing the\n    numbers [1], [2], and [3].  Instead of writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use argument synthesis to write this: *)\n\nDefinition list123' := cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ###################################################### *)\n(** *** Implicit Arguments *)\n\n(** If fact, we can go further.  To avoid having to sprinkle [_]'s\n    throughout our programs, we can tell Coq _always_ to infer the\n    type argument(s) of a given function. *)\n\nImplicit Arguments nil [[X]].\nImplicit Arguments cons [[X]].\nImplicit Arguments length [[X]].\nImplicit Arguments app [[X]].\nImplicit Arguments rev [[X]].\nImplicit Arguments snoc [[X]].\n\n(* note: no _ arguments required... *)\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\nCheck (length list123'').\n\n(** Alternatively, we can declare an argument to be implicit while\n    defining the function itself, by surrounding the argument in curly\n    braces.  For example: *)\n\nFixpoint length'' {X:Type} (l:list X) : nat :=\n  match l with\n  | nil      => 0\n  | cons h t => S (length'' t)\n  end.\n\n(** (Note that we didn't even have to provide a type argument to\n    the recursive call to [length''].)  We will use this style\n    whenever possible, although we will continue to use use explicit\n    [Implicit Argument] declarations for [Inductive] constructors. *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly this time, even though\n    we've globally declared it to be [Implicit].  For example, suppose we\n    write this: *)\n\n(* Definition mynil := nil. *)\n\n(** If we uncomment this definition, Coq will give us an error,\n    because it doesn't know what type argument to supply to [nil].  We\n    can help it by providing an explicit type declaration (so that Coq\n    has more information available when it gets to the \"application\"\n    of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1, 2, 3].\n\n(* ###################################################### *)\n(** *** Exercises: Polymorphic Lists *)\n\n(** **** Exercise: 2 stars, optional (poly_exercises) *)\n(** Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Fill in the definitions\n    and complete the proofs below. *)\n\nFixpoint repeat (X : Type) (n : X) (count : nat) : list X :=\nmatch count with \n| 0 => @nil X\n| S n' => n :: (repeat X n n')\nend.\nExample test_repeat1:\n  repeat bool true 2 = cons true (cons true nil).\nProof. reflexivity. Qed.\n\nTheorem nil_app : forall X:Type, forall l:list X,\n  app [] l = l.\nProof.\nintros X l.\nreflexivity. Qed.\n\n\nTheorem rev_snoc : forall X : Type,\n                     forall v : X,\n                     forall s : list X,\n  rev (snoc s v) = v :: (rev s).\nProof.\nintros X v s. \ninduction s as [| n s'].\nCase \"s = []\".\nreflexivity.\nCase \"s = n :: s'\".\nsimpl.\nrewrite -> IHs'.\nreflexivity.\nQed.\n\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\nintros X l.\ninduction l  as [| n l'].\nCase \"l = []\".\nreflexivity.\nCase \"l = n::l'\".\nsimpl.\nrewrite -> rev_snoc.\nrewrite -> IHl'. \nreflexivity. Qed.\n\nTheorem snoc_with_append : forall X : Type,\n                         forall l1 l2 : list X,\n                         forall v : X,\n  snoc (l1 ++ l2) v = l1 ++ (snoc l2 v).\nProof.\nintros X l1 l2 v.\ninduction l1 as [| n l1'].\nCase \"l1 = []\".\nreflexivity.\nCase \"l1 = n :: l1'\".\nsimpl.\nrewrite -> IHl1'.\nreflexivity. Qed.\n\n\n(** [] *)\n\n(* ###################################################### *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_ (or _products_): *)\n\nInductive prod (X Y : Type) : Type :=\n  pair : X -> Y -> prod X Y.\n\nImplicit Arguments pair [[X] [Y]].\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for pair _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should be used when parsing types.  This avoids a clash with the\n    multiplication symbol.) *)\n\n(** A note of caution: it is easy at first to get [(x,y)] and\n    [X*Y] confused.  Remember that [(x,y)] is a _value_ built from two\n    other values; [X*Y] is a _type_ built from two other types.  If\n    [x] has type [X] and [y] has type [Y], then [(x,y)] has type\n    [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with (x,y) => x end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with (x,y) => y end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In many functional programming languages,\n    it is called [zip].  We call it [combine] for consistency with\n    Coq's standard library. *)\n(** Note that the pair notation can be used both in expressions and in\n    patterns... *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match (lx,ly) with\n  | ([],_) => []\n  | (_,[]) => []\n  | (x::tx, y::ty) => (x,y) :: (combine tx ty)\n  end.\n\n(** Indeed, when no ambiguity results, we can even drop the enclosing\n    parens: *)\n\nFixpoint combine' {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx,ly with\n  | [],_ => []\n  | _,[] => []\n  | x::tx, y::ty => (x,y) :: (combine' tx ty)\n  end.\n\n(** **** Exercise: 1 star, optional (combine_checks) *)\n(** Try answering the following questions on paper and\n    checking your answers in coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n        Eval simpl in (combine [1,2] [false,false,true,true]).\n      print?   []\n*)\n\n(** **** Exercise: 2 stars (split) *)\n(** The function [split] is the right inverse of combine: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    programing languages, this function is called [unzip].\n\n    Uncomment the material below and fill in the definition of\n    [split].  Make sure it passes the given unit tests. *)\n\n\nFixpoint split {X Y : Type} (l : list (X*Y)) : (list X)*(list Y) :=\nmatch l with \n | [] => ([], [])\n | (x, y) :: tl => match split tl with (lx, ly) => (x :: lx, y :: ly) \nend\nend.\n\nExample test_split:\n  split [(1,false),(2,false)] = ([1,2],[false,false]).\nProof. reflexivity.  Qed.\n\n(** (If you're reading the HTML version of this file, note that\n    there's an unresolved typesetting problem in the example: several\n    square brackets are missing.  Refer to the .v file for the correct\n    version. *)\n(** [] *)\n\n(* ###################################################### *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_.\n    The type declaration generalizes the one for [natoption] in the\n    previous chapter: *)\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nImplicit Arguments Some [[X]].\nImplicit Arguments None [[X]].\n\n(** We can now rewrite the [index] function so that it works\n    with any type of lists. *)\n\nFixpoint index {X : Type} (n : nat)\n               (l : list X) : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else index (pred n) l'\n  end.\n\nExample test_index1 :    index 0 [4,5,6,7]  = Some 4.\nProof. reflexivity.  Qed.\nExample test_index2 :    index  1 [[1],[2]]  = Some [2].\nProof. reflexivity.  Qed.\nExample test_index3 :    index  2 [true]  = None.\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, optional (hd_opt_poly) *)\n(** Complete the definition of a polymorphic version of the\n    [hd_opt] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_opt {X : Type} (l : list X)  : option X :=\nmatch l with \n| nil => None \n| h :: tl => Some h\nend.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_opt.\n\nExample test_hd_opt1 :  hd_opt [1,2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_opt2 :   hd_opt  [[1],[2]]  = Some [1].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Functions as Data *)\n(* ###################################################### *)\n(** ** Higher-Order Functions *)\n\n(** Like many other modern programming languages -- including\n    all _functional languages_ (ML, Haskell, Scheme, etc.) -- Coq\n    treats functions as first-class citizens, allowing functions to be\n    passed as arguments to other functions, returned as results,\n    stored in data structures, etc.\n\n    Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Partial Application *)\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  (This is the same as saying that Coq primitively\n    supports only one-argument functions -- do you see why?)  This\n    operator is _right-associative_, so the type of [plus] is really a\n    shorthand for [nat -> (nat -> nat)] -- i.e., it can be read as\n    saying that \"[plus] is a one-argument function that takes a [nat]\n    and returns a one-argument function that takes another [nat] and\n    returns a [nat].\"  In the examples above, we have always applied\n    [plus] to both of its arguments at once, but if we like we can\n    supply just the first.  This is called _partial application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Digression: Currying *)\n\n(** **** Exercise: 2 stars, advanced (currying) *)\n(** In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z := \nmatch p with (x,y) => f x y end.\n \n\n(** (Thought exercise: before running these commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]?) *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type) (f : X -> Y -> Z) x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\nintros X Y Z f x y.\nreflexivity.\nQed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                               (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\nintros X Y Z f p. \ndestruct p.\nreflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Filter *)\n\n(** Here is a useful higher-order function, which takes a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filters\" the list, returning a new list containing just those\n    elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1,2,3,4] = [2,4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1, 2], [3], [4], [5,6,7], [], [8] ]\n  = [ [3], [4], [8] ].\nProof. reflexivity.  Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1,0,3,1,4,5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0,2,4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ###################################################### *)\n(** ** Anonymous Functions *)\n\n(** It is a little annoying to be forced to define the function\n    [length_is_1] and give it a name just to be able to pass it as an\n    argument to [filter], since we will probably never use it again.\n    Moreover, this is not an isolated example.  When using\n    higher-order functions, we often want to pass as arguments\n    \"one-off\" functions that we will never use again; having to give\n    each of these functions a name would be tedious.\n\n    Fortunately, there is a better way. It is also possible to\n    construct a function \"on the fly\" without declaring it at the top\n    level or giving it a name; this is analogous to the notation we've\n    been using for writing down constant lists, natural numbers, and\n    so on. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** Here is the motivating example from before, rewritten to use\n    an anonymous function. *)\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1, 2], [3], [4], [5,6,7], [], [8] ]\n  = [ [3], [4], [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7) *)\n\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat := \nfilter (ble_nat 7) (filter evenb l).\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1,2,6,9,10,3,12,8] = [10,12,8].\nProof. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5,2,6,19,129] = [].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (partition) *)\n(** Use [filter] to write a Coq function [partition]:\n  partition : forall X : Type,\n              (X -> bool) -> list X -> list X * list X\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list.\n*)\n\n\nDefinition partition {X : Type} (test : X -> bool) (l : list X)\n                     : list X * list X :=\n(filter test l, filter (fun x => negb (test x)) l).\n\nExample test_partition1: partition oddb [1,2,3,4,5] = ([1,3,5], [2,4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5,9,0] = ([], [5,9,0]).\nProof. reflexivity. Qed. \n(** [] *)\n\n(* ###################################################### *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y:Type} (f:X->Y) (l:list X)\n             : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (plus 3) [2,0,2] = [5,3,5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same ([map] takes _two_ type arguments, [X] and [Y]).  This\n    version of [map] can thus be applied to a list of numbers and a\n    function from numbers to booleans to yield a list of booleans: *)\n\nExample test_map2: map oddb [2,1,2,5] = [false,true,false,true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a list of lists of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n,oddb n]) [2,1,2,5]\n  = [[true,false],[false,true],[true,false],[false,true]].\nProof. reflexivity.  Qed.\n\n\n(** **** Exercise: 3 stars (map_rev) *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nLemma map_snoc : forall (X Y : Type) (f :  X -> Y) (l :  list X) (n : X),\n  map f (snoc l n) = snoc (map f l) (f n).\nProof. \nintros X Y f l n.\ninduction l as [| x l'].\nCase \"l = []\".\nreflexivity.\nCase \"l = x :: l'\".\nsimpl.\nrewrite -> IHl'.\nreflexivity. Qed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\nintros X Y f l.\ninduction l as [| n l'].\nCase \"l = []\".\nreflexivity.\nCase \"l = n :: l'\".\nsimpl. \nrewrite <- IHl'.\nrewrite <- map_snoc.\nreflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (flat_map) *)\n(** The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n        flat_map (fun n => [n,n+1,n+2]) [1,5,10]\n      = [1, 2, 3, 5, 6, 7, 10, 11, 12].\n*)\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                   : (list Y) :=\nmatch l with \n| nil => nil\n| hd :: tl => app (f hd) (flat_map f tl)\nend. \n\nExample test_flat_map1:\n  flat_map (fun n => [n,n,n]) [1,5,4]\n  = [1, 1, 1, 5, 5, 5, 4, 4, 4].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** Lists are not the only inductive type that we can write a\n    [map] function for.  Here is the definition of [map] for the\n    [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, optional (implicit_args) *)\n(** The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)  [] *)\n\n(* ###################################################### *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y) : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(* /TERSE *)\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1,2,3,4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n   fold plus [1,2,3,4] 0\n    yields\n   1 + (2 + (3 + (4 + 0))).\n    Here are some more examples:\n*)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 : fold mult [1,2,3,4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 : fold andb [true,true,false,true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 : fold app  [[1],[],[2,3],[4]] [] = [1,2,3,4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different) *)\n(** Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* ###################################################### *)\n(** ** Functions For Constructing Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as _arguments_.  Now let's look at some\n    examples involving _returning_ functions as the results of other\n    functions.\n\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** Similarly, but a bit more interestingly, here is a function\n    that takes a function [f] from numbers to some type [X], a number\n    [k], and a value [x], and constructs a function that behaves\n    exactly like [f] except that, when called with the argument [k],\n    it returns [x]. *)\n\nDefinition override {X: Type} (f: nat->X) (k:nat) (x:X) : nat->X:=\n  fun (k':nat) => if beq_nat k k' then x else f k'.\n\n(** For example, we can apply [override] twice to obtain a\n    function from numbers to booleans that returns [false] on [1] and\n    [3] and returns [true] on all other arguments. *)\n\nDefinition fmostlytrue := override (override ftrue 1 false) 3 false.\n\nExample override_example1 : fmostlytrue 0 = true.\nProof. reflexivity. Qed.\n\nExample override_example2 : fmostlytrue 1 = false.\nProof. reflexivity. Qed.\n\nExample override_example3 : fmostlytrue 2 = true.\nProof. reflexivity. Qed.\n\nExample override_example4 : fmostlytrue 3 = false.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star (override_example) *)\n(** Before starting to work on the following proof, make sure you\n    understand exactly what the theorem is saying and can paraphrase\n    it in your own words.  The proof itself is straightforward. *)\n\nTheorem override_example : forall (b:bool),\n  (override (constfun b) 3 true) 2 = b.\nProof.\n  intros b. \n  destruct b.\n  Case \"b = true\".\n  reflexivity.\n  Case \"b = false\".\n  reflexivity.\n  Qed.\n\n(** [] *)\n\n(** We'll use function overriding heavily in parts of the rest of the\n    course, and we will end up needing to know quite a bit about its\n    properties.  To prove these properties, though, we need to know\n    about a few more of Coq's tactics; developing these is the main\n    topic of the next chapter.  For now, though, let's introduce just\n    one very useful tactic that will also help us with proving\n    properties of some of the other functions we have introduced in\n    this chapter. *)\n\n(* ###################################################### *)\n(** * The [unfold] Tactic *)\n\n(** Sometimes, a proof will get stuck because Coq doesn't\n    automatically expand a function call into its definition.  (This\n    is a feature, not a bug: if Coq automatically expanded everything\n    possible, our proof goals would quickly become enormous -- hard to\n    read and slow for Coq to manipulate!) *)\n\nTheorem unfold_example_bad : forall m n,\n  3 + n = m ->\n  plus3 n + 1 = m + 1.\nProof.\n  intros m n H.\n  (* At this point, we'd like to do [rewrite -> H], since \n     [plus3 n] is definitionally equal to [3 + n].  However, \n     Coq doesn't automatically expand [plus3 n] to its \n     definition. *)\n  Admitted.\n\n(** The [unfold] tactic can be used to explicitly replace a\n    defined name by the right-hand side of its definition.  *)\n\nTheorem unfold_example : forall m n,\n  3 + n = m ->\n  plus3 n + 1 = m + 1.\nProof.\n  intros m n H.\n  unfold plus3.\n  rewrite -> H.\n  reflexivity.  Qed.\n\n(** Now we can prove a first property of [override]: If we\n    override a function at some argument [k] and then look up [k], we\n    get back the overridden value. *)\n\nTheorem override_eq : forall {X:Type} x k (f:nat->X),\n  (override f k x) k = x.\nProof.\n  intros X x k f.\n  unfold override.\n  rewrite <- beq_nat_refl.\n  reflexivity.  Qed.\n\n(** This proof was straightforward, but note that it requires\n    [unfold] to expand the definition of [override]. *)\n\n(** **** Exercise: 2 stars (override_neq) *)\nTheorem override_neq : forall {X:Type} x1 x2 k1 k2 (f : nat->X),\n  f k1 = x1 ->\n  beq_nat k2 k1 = false ->\n  (override f k2 x2) k1 = x1.\nProof.\n intros X x1 x2 k1 k2.\n intros f H.\n unfold override. \n intros H'. \n rewrite -> H'.\n rewrite -> H.\n reflexivity.  \n Qed.\n\n\n\n(** [] *)\n\n(** As the inverse of [unfold], Coq also provides a tactic\n    [fold], which can be used to \"unexpand\" a definition.  It is used\n    much less often. *)\n\n(* ##################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 2 stars (fold_length) *)\n(** Many common functions on lists can be implemented in terms of\n   [fold].  For example, here is an alternate definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4,7,0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  unfold fold_length. \n  induction l as [| n l'].\n  Case \"l = []\".\n  reflexivity.\n  Case \"l = n :: l'\".\n  simpl.\n  rewrite -> IHl'.\n  reflexivity.\n  Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (fold_map) *)\n(** We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\n\n\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=\nfold (fun x list => (f x) :: list) l [].\n\n(** Write down a theorem in Coq stating that [fold_map] is correct,\n    and prove it. *)\n\nTheorem fold_map_correct : forall X Y (l : list X) (f : X -> Y), \n  fold_map f l = map f l.\nProof.\n  intros X Y l f.\n  unfold fold_map.\n  induction l as [| n l'].\n  Case \"l = []\".\n  reflexivity.\n  Case \"l = n :: l'\".\n  simpl.\n  rewrite -> IHl'.\n  reflexivity. \n  Qed.\n\n\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (index_informal) *)\n(** Recall the definition of the [index] function:\n   Fixpoint index {X : Type} (n : nat) (l : list X) : option X :=\n     match l with\n     | [] => None \n     | a :: l' => if beq_nat n O then Some a else index (pred n) l'\n     end.\n   Write an informal proof of the following theorem:\n   forall X n l, length l = n -> @index X (S n) l = None.\n(* FILL IN HERE *)\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (church_numerals) *)\n\nModule Church.\n\n(** In this exercise, we will explore an alternative way of defining\n    natural numbers, using the so-called _Church numerals_, named\n    after mathematician Alonzo Church. We can represent a natural\n    number [n] as a function that takes a function [f] as a parameter\n    and returns [f] iterated [n] times. More formally, *)\n\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Any\n    function [f] iterated once shouldn't change. Thus, *)\n\nDefinition one : nat := \n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** [two] should apply [f] twice to its argument: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** [zero] is somewhat trickier: how can we apply a function zero\n    times? The answer is simple: just leave the argument untouched. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n\n(** More generally, a number [n] will be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f]. Notice in particular\n    how the [doit3times] function we've defined previously is actually\n    just the representation of [3]. *)\n\nDefinition three : nat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)    \n\n(** Successor of a natural number *)\n\nDefinition succ (n : nat) : nat :=\nfun (X : Type) (f: X -> X) (x : X) => f(n X f x).\n\nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\n\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\n\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\n(** Addition of two natural numbers *)\n\nDefinition plus (n m : nat) : nat :=\nfun (X : Type) (f : X -> X) (x : X) => (n X f (m X f x)).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\n\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\n\n(** Multiplication *)\n\nDefinition mult (n m : nat) : nat := \nfun (X : Type) (f : X -> X) (x : X) => (n X (m X f) x).\n\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\n\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\n(** Exponentiation *)\n\n(** Hint: polymorphism plays a crucial role here. *)\n\nDefinition exp (n m : nat) : nat := \nfun (X : Type) (f : X -> X) (x : X) =>  (m (X -> X) (n X) f) x.\n\nCheck exp.\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\nExample exp_3 : exp three zero = one.\nProof. reflexivity. Qed.\n\nEnd Church.\n\n(** [] *)\n\n(* $Date: 2013-01-23 16:48:29 -0500 (Wed, 23 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/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7273696850826162}}
{"text": "From LF Require Import exercise1.\nFrom LF Require Import exercise2.\n\nModule NatList.\n\nInductive natprod : Type :=\n  | pair (n1 n2 : nat).\n\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\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | pair x y => pair y x\n  end.\n\nNotation \"( x , y )\" := (pair x y).\n\nTheorem surjective_pairing : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof. reflexivity. Qed.\n\nTheorem surjective_pairing_stuck : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p. reflexivity.\nQed.\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. simpl. reflexivity.\nQed.\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 p. destruct p. simpl. reflexivity.\nQed.\n\nInductive natlist: Type :=\n  | nil\n  | cons (n: nat) (l: natlist).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint repeat (n count: nat) : natlist :=\n  match count with\n  | O => nil\n  | S c' => cons (n) (repeat n c')\n  end.\n\nFixpoint length (l : natlist) : nat :=\n  match l with\n  | nil => O\n  | cons _ l' => 1 + length l'\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | cons n l => cons n (app l l2)\n  end.\n\nNotation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\n(* Here are two smaller examples of programming with lists. The hd function returns the first element (the \"head\") of the list, while tl returns everything but the first element (the \"tail\"). Since the empty list has no first element, we pass a default value to be returned in that case. *)\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n  | nil => default\n  | cons n _ => n\n  end.\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | cons _ l' => l'\n  end.\n\n\n(** **** Exercise: 2 stars, standard, especially useful (list_funs) *)\n(* Complete the definitions of nonzeros, oddmembers, and countoddmembers below.\nHave a look at the tests to understand what these functions should do. *)\n(* Returns all non-zero elements. *)\nFixpoint nonzeros (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | cons O l'     => nonzeros l'\n  | cons n l' => cons n (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\n(* Returns all odd elements. *)\nFixpoint oddmembers (l : natlist) : natlist :=\n  match l with\n  | nil => nil \n  | cons n l' => match even n with\n                 | true => oddmembers l'\n                 | false => cons n (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\n(* For countoddmembers, we're giving you a header that uses keyword Definition instead of Fixpoint. The point of stating the question this way is to encourage you to implement the function by using already-defined functions, rather than writing your own recursive definition. *)\nDefinition countoddmembers (l : natlist) : nat :=\n  match l with\n  | nil => O\n  | cons n l' => match even n with\n                 | true => length ( oddmembers l' ) \n                 | false => length ( oddmembers l' ) + 1\n                 end \n  end.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\nProof. simpl. reflexivity. Qed.\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\nProof. simpl. reflexivity. Qed.\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\nProof. simpl. reflexivity. Qed.\n  \n\n(** **** Exercise: 3 stars, advanced (alternate) *)\n(* Complete the following definition of alternate, which interleaves two lists into one, alternating\nbetween elements taken from the first list and elements from the second. See the tests below for more\nspecific examples.\nHint: there is an elegant way of writing alternate that fails to satisfy Coq's requirement that all\nFixpoint definitions be structurally recursing, as mentioned in Basics. If you encounter that\ndifficulty, consider pattern matching against both lists at the same time with the \"multiple pattern\"\nsyntax we've seen before. *)\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  (* Pick exactly one element from each list alternately. *)\n  match l1, l2 with\n  | nil, nil => nil\n  | _, nil => l1\n  | nil, _ => l2\n  | (cons n1 l1'), (cons n2 l2') => [n1;n2] ++ (alternate l1' l2')\n  end.\n\nCompute alternate [1;2;3] [4;5;6].\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\nDefinition bag := natlist.\n\n(** **** Exercise: 3 stars, standard, especially useful (bag_functions) *)\n(* Complete the following definitions for the functions count, sum, add, and member for bags. *)\nFixpoint count (v : nat) (s : bag) : nat :=\n  match s with\n  | nil => O\n  | cons n l' => match eqb n v with\n                 | true => 1 + (count v l')\n                 | false => (count v l')\n                 end\n  end.\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\nDefinition sum (lhs rhs : bag) : bag :=\n  match lhs, rhs with\n  | _, _ => lhs ++ rhs\n  end.\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]\n  | cons _ _ => [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\nFixpoint member (v : nat) (s : bag) : bool :=\n  match s with\n  | nil => false\n  | cons v' s' => match eqb v' v with\n                  | false => (member v s')\n                  | true => true\n                  end\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(** **** Exercise: 3 stars, standard, optional (bag_more_functions) *)\n(* Here are some more bag functions for you to practice with.\nWhen remove_one is applied to a bag without the number to remove, it should return the same bag\nunchanged. *)\nFixpoint remove_one (v : nat) (s : bag) : bag :=\n  match s with\n  | nil => s\n  | cons v' s' => match eqb v' v with\n                  | true => s'\n                  | false => cons v' (remove_one v s')\n                  end\n  end.\n\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 => s\n  | cons v' s' => match eqb v' v with\n                  | true => (remove_all v s')\n                  | false => cons v' (remove_all v s')\n                  end\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 included (s1 : bag) (s2 : bag) : bool :=\n  match s1 with\n  | nil => true\n  | cons n s' => match member n s2 with\n                 | true => included s' (remove_one n s2)\n                 | false => false\n                 end\n  end.\n\nExample test_included1: included [1;2] [2;1;4;1] = true.\nProof. simpl. reflexivity. Qed.\nExample test_included2: included [1;2;2] [2;1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\n\n(** **** Exercise: 2 stars, standard, especially useful (add_inc_count) *)\n(* Adding a value to a bag should increase the value's count by one.\n   State this as a theorem and prove it. *)\nTheorem add_inc_count : forall (n : nat) (s : bag),\n  count n (add n s) = count n s + 1.\nProof.\n  intros n s. destruct s.\n  - simpl. rewrite eqb_refl. reflexivity.\n  - simpl. rewrite eqb_refl. rewrite <- plus_n_Sm. rewrite add_0_r. reflexivity.\nQed.\n\n(* ++ is defined right associative.. *)\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  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nFixpoint rev (l : natlist) : natlist :=\n  match l with\n  | nil => nil \n  | cons n l' => app (rev l') [n]\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 we've seen so far, let's prove that reversing a\nlist does not change its length. Our first attempt gets stuck in the successor case... *)\nLemma app_length: forall l1 l2 : natlist,\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros l1 l2. induction l1 as [| n l' H].\n  - reflexivity.\n  - simpl.  rewrite -> H. reflexivity.\nQed.\n\nTheorem rev_length_firsttry : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' H].\n  - reflexivity.\n  - simpl. rewrite -> app_length. rewrite -> H. apply add_one_right.\nQed.\n\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' H].\n  - reflexivity.\n  - simpl. rewrite -> H. reflexivity.\nQed.\n\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 l' H].\n  - rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> H. rewrite -> app_assoc. reflexivity.\nQed.\n\n(* An involution is a function that is its own inverse. That is, applying the function twice yield the\noriginal input. *)\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l' H].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr. rewrite -> H. reflexivity.\nQed.\n\n(* There is a short solution to the next one. If you find yourself getting tangled up, step back and try\nto look for a simpler way. *)\nTheorem app_assoc4 : forall l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  (* Apply association twice. *)\n  intros.\n  rewrite <- app_assoc. rewrite <- app_assoc. reflexivity.\nQed.\n\n(* An exercise about your implementation of nonzeros: *)\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [| n l' H].\n  - simpl. reflexivity.\n  - simpl. rewrite -> H. destruct l2.\n    + rewrite -> app_nil_r. simpl. rewrite -> app_nil_r. reflexivity.\n    + simpl. destruct n.\n      * reflexivity.\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\nl yields true for every list l. *)\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil => true \n  | _, nil => false\n  | nil, _ => false\n  | cons n1 l1', cons n2 l2' =>\n    match eqb n1 n2 with \n      | true => (eqblist l1' l2')\n      | false => false\n    end\n  end.\n\nExample test_eqblist1 :\n  (eqblist nil nil = true).\nProof. simpl. reflexivity. Qed.\nExample test_eqblist2 :\n  eqblist [1;2;3] [1;2;3] = true.\n  Proof. 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.\n  - reflexivity.\n  - simpl. rewrite <- IHl. rewrite eqb_refl. reflexivity.\nQed.\n\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. destruct s.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* The following lemma about leb might help you in the next exercise (it will also be useful in later \nchapters). *)\nTheorem leb_n_Sn : forall n : nat,\n  n <=? (S n) = true.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\n  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 s' H].\n  - reflexivity.\n  - simpl. rewrite <- H. destruct n.\n    + rewrite eqb_refl. rewrite leb_n_Sn. rewrite H. reflexivity.\n    + reflexivity.\nQed.\n\n\n(** **** Exercise: 3 stars, standard, optional (bag_count_sum) *)\n(* Write down an interesting theorem bag_count_sum about bags involving the functions count and sum, and\nprove it using Coq. (You may find that the difficulty of the proof depends on how you defined count!\nHint: If you defined count using =? you may find it useful to know that destruct works on arbitrary\nexpressions, not just simple identifiers.) *)\nTheorem bag_count_sum: forall s1 s2 : bag,\n  count 0 (sum s1 s2) = (count 0 s1) + (count 0 s2).\nProof.\n  intros. induction s1 as [| n s1' H].\n  - reflexivity.\n  - destruct n.\n    + simpl. rewrite H. reflexivity.\n    + simpl. apply H.\nQed.\n\n(** **** Exercise: 3 stars, advanced (involution_injective) *)\n(* Prove that every involution is injective. Involutions were defined above in rev_involutive. An involution injective function is one-to-one: it maps distinct inputs to distinct outputs, without any collisions. *)\nTheorem involution_injective : forall (f : nat -> nat),\n  (forall n : nat, n = f (f n)) -> (forall n1 n2 : nat, f n1 = f n2 -> n1 = n2).\nProof.\n  intros f H0 n1 n2.\n  intros H1.\n  rewrite H0. rewrite <- H1. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, advanced (rev_injective) *)\n(* Prove that rev is injective. Do not prove this by induction -- that would be hard. Instead, re-use\nthe same proof technique that you used for involution_injective. Do not try to use that exercise\ndirectly as a lemma: the types are not the same. *)\nTheorem rev_injective : forall (l1 l2 : natlist),\n  rev l1 = rev l2 -> l1 = l2.\nProof.\n  intros l1 l2 H.\n  rewrite <- rev_involutive. rewrite <- H. rewrite -> rev_involutive. reflexivity.\nQed. \n\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  | cons n' l'\n    => match n with\n       | 0 => (Some n')\n       | S next => (nth_error l' next)\n       end\n  end.\n\n(* unwrap_or *)\nDefinition option_elim (d : nat) (o : natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | nil => None\n  | cons n _ => Some n\n  end.\n\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\n(** **** Exercise: 1 star, standard, optional (option_elim_hd) *)\n(* This exercise relates your new hd_error to the old hd. *)\nTheorem option_elim_hd : forall (l : natlist) (default : nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  intros. destruct l.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nEnd NatList.\n\nInductive id : Type :=\n  | Id (n : nat).\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,\n  eqb_id x x = true.\nProof.\n  intros x. destruct x as [n].\n  destruct n as [| n'].\n  - reflexivity.\n  - simpl. rewrite eqb_refl. reflexivity.\nQed.\n\nModule PartialMap.\nExport NatList.\n\nInductive partial_map : Type :=\n  | empty\n  | record (i : id) (v : nat) (m : partial_map).\n\n\n(* The update function overrides the entry for a given key in a partial map by shadowing it with a new one\n(or simply adds a new entry if the given key is not already present). *)\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\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(** **** 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.", "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/exercise3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.870597270087091, "lm_q1q2_score": 0.7273696723398636}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Contextual Implicit.\n\nRequire Import List.\nImport ListNotations.\n\n(** * Induction, inductive types, families & predicates *)\n\n(**\n\nYou spent high-school doing \"proofs by induction\" over natural\nnumbers. Working in a proof assistant is a bit like going back to\nhigh-school excepted that we shall be reasoning by induction on more\nstructured objects: inductive types, families and/or predicates.\n\n *)\n\n(** ** Motivation *)\n\n(** *** Practical limitations *)\n\n(**\n\nIn Coq, we can define the following datatype and, for example, a\nreversal function:\n\n *)\n\nInductive rosetree :=\n| rosenode : nat -> list rosetree -> rosetree.\n\nFixpoint rev_rosetree (t: rosetree): rosetree :=\n  match t with\n  | rosenode n ts => \n    rosenode n (fold_left \n                  (fun xs t => rev_rosetree t :: xs) ts [])\n  end.\n\nCompute (rev_rosetree (rosenode 1 [rosenode 2 []; rosenode 3 []])).\n\n(**\n\nHowever, the induction principle automatically generated by Coq is\nrather unsettling:\n\n *)\n\nCheck rosetree_rect.\n\n(** \n\nLet us try to use to prove a property of [rev_rosetree]:\n\n*)\n\nLemma rev_rev_rosetree: \n  forall t, rev_rosetree (rev_rosetree t) = t.\nProof. induction t. (* WTF?! *) Abort.\n\n\n(** **** Exercise: 5 stars (rosetree_ind')  *)\n(**\n\nImplement a valid induction principle of [rosetree] and prove the\nabove lemma.\n\n*)\n\n(** *** Theoretical limitations *)\n\n(**\n\nWhy is the following definition rejected?\n\n *)\n\nFail Inductive term :=\n| App : term -> term -> term\n| Abs : (term -> term) -> term.\n\n(* \nError: Non strictly positive occurrence \nof \"term\" in \"(term -> term) -> term\".\n*)\n\n(** ** Inductive types *)\n\n(** *** Signatures *)\n\n(**\n\nThe (little known) origins of inductive types is rooted in the\nmathematical study of (universal) algebra\n[http://dx.doi.org/10.1145/321992.321997]. We can therefore establish\na dictionary between the programming world and the mathematical world\nand exploit this connection to reason abstractly about datatypes as\nprogrammers manipulate them:\n\n  - an (algebraic) \"datatype\" corresponds to a \"signature\"\n  - a \"constructor\" corresponds to an \"operation\"\n  - a \"recursive argument\" in a constructor corresponds to its \"arity\"\n\n*)\n\n(** **** Exercise: 1 star (fml) *)\n(**\n\nImplement a datatype [Fml] of propositional formulas parameterized\nover [P : Set] that implements the following description found in\n\"Mathematical logic\" (Cori & Lascar):\n\n    ``The set [Fml] of propositional formulas over [P] is the\n      smallest set that\n\n    - contains [P]\n    - contains [¬ F], for every formula [F] it contains\n    - contains [F ∧ G], [F ∨ G] and [F ⇒ G], for\n      every [F] and [G] it contains''\n\n*)\n\n\n(** \n\nIn this section, we consider the familiar datatype of binary trees:\n\n*)\n\nInductive tree : Type := \n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\n(** **** Exercise: 1 star (tree)  *)\n(** What is the arity of the [Leaf] constructor? What is the arity of\nthe [Node] constructor? *)\n\n(**\n\nIn fact, given an inductive type, such as [tree] above, we can\n_always_ decompose it into a non-recursive signature ([sigma_tree],\nbelow) and a generic fixpoint operator ([tree'], below):\n\n *)\n\nInductive sigma_tree (X: Type): Type := \n| OpLeaf : sigma_tree X\n| OpNode : nat -> X -> X -> sigma_tree X.\n\nInductive tree' : Type :=\n  | Constr : sigma_tree tree' -> tree' .\n\n(**\n\nThe non-recursive definition [sigma_tree] is generally called the\n\"signature functor\" of the inductive type. It is built from a fixed\ngrammar of type operators: product, sums and functions. Put another\nway, algebraic datatypes are said to be defined by \"sums of\nproducts\". The generic fixpoint operator is said to \"tie the knot\" by\ndefining [tree'] through a layer of [sigma_tree] applied to [tree']\nitself.\n\n*)\n\n(** **** Exercise: 1 star (iso_tree_tree')  *)\n\n(** Implement a pair of functions [phi : tree -> tree'] and [psi :\ntree' -> tree] witnessing the fact that the types [tree'] and [tree]\nare isomorphic. *)\n\nAxiom phi: tree -> tree'. (* XXX: implement me! *)\nAxiom psi: tree' -> tree. (* XXX: implement me! *)\n\n\n(** **** Exercise: 2 stars (psi_phi)  *)\n(** Prove the following lemma: *)\n\nLemma psi_phi: forall t, psi (phi t) = t.\nProof.\n  admit.\nQed.\n\n(** **** Exercise: 5 stars (phi_psi)  *)\n(** Prove the following lemma: *)\n\nLemma phi_psi: forall t, phi (psi t) = t.\nProof.\n  admit.\nQed.\n\n(** *** Initiality *)\n\nSection List.\n\nVariable A X: Type.\n\n(** **** Exercise: 2 stars (sigma_list)  *)\n\n(** Decompose the datatype [list A] into a signature [sigma_list] and\nits fixpoint [list']. Convince yourself (or prove) that [list A] is\nisomorphic to [list']. *)\n\nInductive sigma_list (X: Type) :=\n.\n\nInductive list' : Type :=\n.\n\n(** We assume that we are given an _algebra_ [alpha] over lists: *)\n\nVariable alpha : sigma_list X -> X.\n\n(** **** Exercise: 3 stars (fold_list)  *)\n\n(** Using [alpha], implement a function [fold_list] of type [list A ->\nX]. You may find some inspiration by using [Print] on Coq's\nimplementation of [fold_right]. *)\n\n\nEnd List.\n\n(** **** Exercise: 3 stars (fold_length)  *)\n(** By defining a suitable algebra [alpha_length], implement the\nfunction [length : list A -> nat] using [fold_list]. *)\n\n\nSection FoldTree.\n\nVariable X: Type.\n\n(** **** Exercise: 4 stars (fold_tree)  *)\n(** Using [alpha], implement a function [fold_tree] of type [tree ->\nX]. *)\n\nAxiom fold_tree : forall (alpha : sigma_tree X -> X), tree -> X. (* XXX: implement me! *)\n\n\n(**\n\nWe can show (in meta-mathematics, not in Coq), that every algebra\n[alpha : sigma_tree X -> X] induces a unique function [tree -> X]: this\nis called the _initial algebra semantics_ of inductive types. This is\nthe equivalent of a Design Pattern for functional programmers: it is a\ngeneral principle for understanding recursion.\n\n*)\n\nEnd FoldTree.\n\n(** **** Exercise: 3 stars (fold_height)  *)\n(** By defining a suitable algebra [alpha_height], implement the\nfunction [height : tree -> nat] using [fold_tree]. *)\n\n\n(** *** Interlude: visitor pattern *)\n\n(** Object-oriented programmers will recognize a familiar (if more\nverbose) pattern in [fold_tree]: *)\n\n(**\n<<\ninterface TreeVisitor {\n    void visit(Node n);\n    void visit(Leaf l);\n}\n\ninterface TreeElement {\n    void accept(TreeVisitor visitor);\n}\n\nclass Node implements TreeElement {\n    private int x;\n    print TreeElement l, r;\n\n    public void accept(TreeVisitor visitor) {\n        l.accept(visitor); visitor.visit(this); \n        r.accept(visitor);\n    }\n    (...)\n}\n>> \n*)\n\n\n(** ** Induction over inductive types *)\n\n(** \n\nLet us consider the skeleton of a high-school proof by induction:\n\n  - Statement:\n    \"We show by recurrence the following property: ``for all n, P(n)''\"\n  - Initialization:\n    \"We show that the property is true for n = 0, ie. P(0).\"\n  - Heredity:\n    \"Assume that the property is true at m, ie. P(m). We show that the \n     property is true at P(m+1).\"\n  - Conclusion:\n    \"By recurrence, we conclude that the property is true for all n.\"\n\nIn type theory, this translates to:\n\n*)\n\nSection TestInd.\n\nHypothesis P: nat -> Type.              (** Statement *)\nHypothesis init: P 0.                (** Initialization *)\nHypothesis step: forall m, P m -> P (S m). (** Heredity *)\nCheck (nat_rect P init step).        (** Conclusion *)\n\nEnd TestInd.\n\n(**\n\nHowever, induction is not limited to natural numbers! In particular,\nin lecture 2, we shall see that we can perform induction on semantics\njudgements (ie. inductively defined relations). To understand\ninduction more generally, we consider the datatype of trees, whose\ninduction principle (automatically generated by Coq) is instructive:\n\n*)    \n\nCheck tree_rect.\n(* tree_rect\n     : forall P : tree -> Type,\n       P Leaf ->\n       (forall (n : nat) (t : tree), P t -> forall t0 : tree, P t0 -> P (Node n t t0)) ->\n       forall t : tree, P t\n*)\n\n(** This type signature exhibits some similarity with the type\nsignature of the recursion principle over trees [fold_tree]. To\nsimplify our study of induction principles, we adopt a _uniform_\ntreatment of the inductive hypothesis, using a gadget similar to\n[sigma_tree]. *)\n\nSection Tree_rect'.\n\nHypothesis P: tree -> Type.\n\n(** **** Exercise: 3 stars (sigma_ind_tree)  *)\n(** Define a non-recursive predicate [sigma_ind_tree : tree -> Type]\nthat asserts that [P] holds in every subtree of the given tree. Do you\nidentify any similarity with [sigma_tree]? *) \n\nInductive sigma_ind_tree: tree -> Type :=\n.\n\n(** [sigma_ind_tree] is called the _predicate lifting_: it applies the\npredicate [P] to all subtrees of a given node. *)\n\n(** **** Exercise: 5 stars (tree_rect')  *)\n(** Implement the uniform induction principle [tree_rect'] *) \n\nDefinition tree_rect':\n (forall t, sigma_ind_tree t -> P t) -> forall t : tree, P t.\nProof.\n  admit.\nDefined.\n\n\n(** The function of type [forall t, sigma_ind_tree t -> P t] required by the\ninduction principle is genuinely a (uniformly presented) _induction\nstep_: we must explain how we can transport an invariant [P] holding\non subtrees to an invariant holding on the whole node. *) \n\nEnd Tree_rect'.\n\n(** **** Exercise: 4 stars (nat_rect')  *)\n(** Following the previous example, implement the uniform induction\nprinciple [nat_rect'] over natural numbers. *) \n\n\n(** *** Induction vs. recursion *)\n\n(** There is a striking similarity between the recursion principles *)\n\nCheck sigma_tree.\nCheck fold_tree.\n\n(** and the induction principles. *)\n\nCheck sigma_ind_tree.\nCheck tree_rect'.\n\n(** Unsurprisingly, we can emulate recursion if we have induction. *)\n\n(** **** Exercise: 4 stars (recursion_from_induction)  *)\n\n(** Implement [fold_tree' : forall X : Type, (sigma_tree X -> X) -> tree -> X]\nusing _only_ [tree_rect'] (in particular, you are not allowed to\n[match] on a tree) *)\n\n(* Phantom type, to know where computations come from: *)\nDefinition fold_tree'_def : tree -> Type -> Type := fun t X => X.\n\nDefinition fold_tree' : forall X : Type, (sigma_tree X -> X) -> tree -> X.\nintros X IH t.\nchange X with (fold_tree'_def t X).\ninduction t using tree_rect'.\n  admit.\nDefined.\n\nSection TryInd.\n\nHypothesis P: tree -> Type.\nHypothesis init: P Leaf.\nHypothesis step: forall n l r, P l -> P r -> P (Node n l r).\n\n(** Sadly, the converse is impossible: ``Induction is not derivable in\n$\\lambda$P2'', [http://repository.tue.nl/661317]. The best we can do\nis to define an algebra on _pairs_ of the term and its predicate. *)\n\n(** **** Exercise: 5 stars (dep_algebra)  *)\n(** Define an algebra [alg (xs: sigma_tree { t : tree & P t }): { t :\ntree & P t }] for which the pseudo-induction principle [tree_ind'] is\n\"correct\" (see next exercise for the meaning of \"correctness\" in this\ncase). *)\n\nAxiom alg: sigma_tree { t : tree & P t } -> { t : tree & P t }. (* XXX: implement me! *)\n\n\nDefinition tree_ind' (t: tree): { t : tree & P t } :=\n  fold_tree alg t.\n\n(** **** Exercise: 4 stars (induction_from_recursion)  *)\n(** Prove that your pseudo-induction principle is correct, ie. that we have: *)\nLemma tree_ind'_correct: forall t, projT1 (tree_ind' t) = t.\nProof.\n  admit.\nQed.\n\nEnd TryInd.\n\n(** ** Inductive families *)\n\n(**\n\nOnce we have understood inductive types, their recursion schemes and\ntheir induction principles, inductive families come with no\nsurprises. In terms of universal algebra, we are merely going from\nmono-sorted signatures to multi-sorted signatures. For example, the\ndefinition of well-formed red-black trees below is basically a binary\ntree whose operations and arities carry an information about the arity\nat which these objects exist/must be:\n\n*)\n\nUnset Implicit Arguments. (* being fully explicit may help see the details *)\n\nInductive color := red | black.\n\nInductive rbt: color -> nat -> Type :=\n| bleaf: \n    nat -> rbt black 0\n| rnode: forall n,\n    rbt black n -> rbt black n -> rbt red n\n| bnode: forall c1 c2 n,\n    rbt c1 n -> rbt c2 n -> rbt black (S n).\n\n(** The induction principle may look slightly intimidating but, in fact,\nthe same principles govern the definition of the (uniform) induction\nprinciple of red-black trees. *)\n\nCheck rbt_rect.\n(* rbt_rect:\n  forall P : forall c n, rbt c n -> Type,\n    (forall n : nat, P black 0 (bleaf n)) ->\n    (forall n l r, \n         P black n l -> P black n r \n       -> P red n (rnode n l r)) ->\n    (forall c1 c2 n l r,\n        P c1 n l -> P c2 n r\n      -> P black (S n) (bnode c1 c2 n l r)) ->\n    forall c n t, P c n t\n*)\n\nSection RBTRect'.\n\nHypothesis P: forall c n, rbt c n -> Type.\n\n(** **** Exercise: 2 stars (rbt_sigma_ind)  *)\n(** Define the predicate lifting of red-black trees: *)\nInductive rbt_sigma_ind : forall c n, rbt c n -> Type :=\n.\n\n(** **** Exercise: 4 stars (rbt_rect')  *)\n(** Using the predicate lifting, implement the induction principle for\nred-black trees: *)\nDefinition rbt_rect':\n  (forall c n t, rbt_sigma_ind c n t -> P c n t) ->\n  forall c n (t: rbt c n), P c n t.\nProof.\n  admit.\nDefined.\n\n\nEnd RBTRect'.\n\nSection VecRect'.\n\nVariable A : Type.\n\n(** **** Exercise: 1 star (vect)  *)\n(** Define the inductive family [vect : nat -> Type] which is such that\ninhabitants of [vect n] are the lists containing [n] elements of [A],\nby construction (and only those lists).  *)\n\nInductive vect : nat -> Type :=\n.\n\nHypothesis P : forall n, vect n -> Type.\n\n(** **** Exercise: 2 star (vect_sigma_ind)  *)\n(** Implement the predicate lifting [vect_sigma_ind : forall n, vect n ->\nType] of vectors. *)\n\nInductive vect_sigma_ind : forall n, vect n -> Type :=\n.\n\n(** **** Exercise: 3 star (vect_rect')  *)\n(** Deduce its uniform induction principle. *)\n\nAxiom vect_rect' :\n         forall (IH: forall n t, vect_sigma_ind n t -> P n t)\n         {n} (t: vect n), P n t. (* XXX: implement me! *)\n\n(** ** Mutual induction *)\n\n\n(** Having developed a good understanding of inductive definitions and\ninduction, we can revisit the motivation for this lecture, ie. the\ninappropriate induction principle generated by Coq for [rosetree]. We\nmay be tempted to manually unfold the definition of [list rosetree]\ninto a mutually-inductive definition, without much luck. *)\n\nReset rosetree.\n\nInductive rosetree :=\n| rosenode: \n    nat -> list_rosetree -> rosetree\nwith list_rosetree :=\n| rosenil: \n    list_rosetree\n| rosecons: \n    rosetree -> list_rosetree -> list_rosetree.\n\nCheck rosetree_rect.\n(* rosetree_rect\n     : forall P : rosetree -> Type,\n       (forall (n : nat) (l : list_rosetree), P (rosenode n l)) -> forall r : rosetree, P r\n*)\n\nReset rosetree.\n\n(** **** Exercise: 2 star (rosetreeIx)  *)\n(** One way to effectively sidestep Coq's limitation is to define an\nindexed family [rosetreeIx: bool -> Type] which is equivalent to\n[rosetree]. Could this pattern be generalized to any\nmutually-inductive definition? *)\n\nInductive rosetreeIx: bool -> Type :=\n.\n\nCheck rosetreeIx_rect.\n\n(** Alternatively, the command [Combined Scheme] could have worked as\nwell. *)\n\n(** ** Strict positivity *) \n\nSection StrictPositivity.\n\nVariable A : Type.\n\n(** Some inductive definitions, such as the following, are rightfully\nrejected by Coq *)\n\nFail Inductive T :=\n| c : (T -> A) -> T.\n\n(** because, if we were to accept such definition, we could write the\nfollowing programs that build an inhabitant of _any_ type [A], thus\nincluding [False], which ought to be impossible. *)\n\n(* \n<<\nDefinition funny (t: T)(x: T): A :=\n  match t with\n  | c f => f x\n  end.\n\nDefinition haha (t: T): A := funny t t.\n\nDefinition bottom: A := haha (c haha).\n>> *)\n\n(** A _strictly positive_ definition admits \"no recursion to the left\nof an arrow\": the intuition is that if we were to allow a recursive\nargument to appear on the left of an arrow, we could suddenly encode a\ndiagonal argument, as we did above in [haha]. Coq only allows you to\nwrite strictly-positive inductive definitions. Being a syntactic\ncheck, it is necessarily conservative: sometimes you may need to\nmassage your definitions to convince Coq that they are legitimate. *)\n\nEnd StrictPositivity.\n\n(** ** Conclusion *)\n\n(** Today, you have learned:\n      - About Inductive definitions:\n        + Non-indexed ⊆ indexed\n        + Mutual ≈ indexed\n        + Positivity criteria\n      - About Induction\n        + Induction = recursion + proof\n        + Mechanically derivable from signature\n        + Not always fully supported by Coq...\n*)\n\n(** Take-aways:\n      - Recursion: for any inductive type, you are able to\n          + define its signature functor\n          + switch between uniform and specialized recursion\n          + implement a uniform recursion operator\n\n      - Induction: for any inductive type or inductive family, you are able to\n          + define its predicate lifting\n          + switch between uniform and specialized induction\n          + implement a uniform induction operator\n*) ", "meta": {"author": "pedagand", "repo": "5I554", "sha": "5e6ad3917ba1493e7c76a0b9c7e290c5533d8806", "save_path": "github-repos/coq/pedagand-5I554", "path": "github-repos/coq/pedagand-5I554/5I554-5e6ad3917ba1493e7c76a0b9c7e290c5533d8806/c1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7273597132495897}}
{"text": "Require Export List. \nRequire Export ListSet. \nSet Implicit Arguments.\nUnset Strict Implicit. \n \n(*********************************************************************) \n(*                  Some List Functions                              *) \n(*********************************************************************) \n\nDefinition front (A : Set) (l : list A) : list A := rev (tail (rev l)). \n \nDefinition last (A : Set) (l : list A) := head (rev l). \n \nFixpoint take (A : Set) (n : nat) (l : list A) {struct l} : \n list A :=\n  match l with\n  | nil => nil (A:=A)\n  | a :: l' => match n with\n               | O => nil (A:=A)\n               | S m => a :: take m l'\n               end\n  end. \n\nFixpoint allunique (A : Set) (l : list A) {struct l} : Prop :=\n  match l with\n  | nil => True\n  | x :: l' => IF In x l' then False else allunique l'\n  end. \n \n(*********************************************************************) \n(*                  Some Functions for ListSet                       *) \n(*********************************************************************) \n \nDefinition IsEmpty (A : Set) (B : set A) := forall x : A, ~ set_In x B. \n \nDefinition Included (A : Set) (B C : set A) :=\n  forall x : A, set_In x B -> set_In x C. \n \nLemma AllWaysIncluded : forall (A : Set) (B : set A), Included B B. \nintros. \nunfold Included in |- *. \nauto. \n \nQed. \n \n(*********************************************************************) \n(*                  Some Results about ListSet                       *) \n(*********************************************************************) \nSection ListSetLemmas. \n \nVariable A : Set. \n \nHypothesis Aeq_dec : forall x y : A, {x = y} + {x <> y}. \n \nLemma Set_union1 :\n forall (B C : set A) (x : A),\n set_In x (set_union Aeq_dec B C) -> ~ set_In x B -> set_In x C. \nintros. \ncut (set_In x B \\/ set_In x C). \nintro H1; elim H1. \ntauto. \n \nauto. \n \neapply (set_union_elim Aeq_dec); auto. \n \nQed. \n \nLemma Set_union2 :\n forall (B C : set A) (x : A),\n set_In x (set_union Aeq_dec B C) -> set_In x (set_union Aeq_dec C B). \nintros. \ncut (set_In x C \\/ set_In x B). \nintro; apply set_union_intro. \nauto. \n \ncut (set_In x B \\/ set_In x C). \ntauto. \n \neapply (set_union_elim Aeq_dec). \nauto. \n \nQed. \n \n \nLemma Set_remove2 :\n forall (B : set A) (x y : A),\n set_In x (set_remove Aeq_dec y B) -> set_In x B. \nintro; intro; intro. \ninduction  B as [| a B HrecB]. \nauto. \n \nsimpl in |- *. \nelim (Aeq_dec y a). \nintros. \nright. \nauto. \n \nsimpl in |- *. \nintro. \nintro. \nelim H. \nintro. \nleft; auto. \n \nintro. \nright. \nauto. \nQed. \n \n \nLemma Set_add1 :\n forall (B : set A) (x y : A),\n set_In x (set_add Aeq_dec y B) -> x <> y -> set_In x B. \nintros. \ncut (x = y \\/ set_In x B). \nintro. \nelim H1. \nintro. \nabsurd (x = y). \nauto. \n \nauto. \n \nintro. \nauto. \n \neapply (set_add_elim (A:=A) Aeq_dec). \nauto. \n \nQed. \n \n \nLemma Set_add2 :\n forall (B : set A) (x y : A),\n x <> y -> ~ set_In x B -> ~ set_In x (set_add Aeq_dec y B). \nintros. \nintro. \napply H0. \neapply (Set_add1 (B:=B) (x:=x) (y:=y)); auto. \n \nQed. \n \nEnd ListSetLemmas. \n \nHint Unfold IsEmpty Included. \nHint Resolve Set_remove2 Set_add1 AllWaysIncluded Set_union1 Set_union2\n  Set_add2. \n \n \n \nLemma Listeq_dec :\n forall A : Set,\n (forall a b : A, {a = b} + {a <> b}) ->\n forall x y : list A, {x = y} + {x <> y}. \nsimple induction x. \nsimple induction y. \nauto. \n \nintros. \nright. \nunfold not in |- *; intro D; discriminate D. \n \nintros. \ninduction  y as [| a0 y Hrecy]. \nright; unfold not in |- *; intro D; discriminate D. \n \nelim (H0 y). \nintro. \nrewrite a1. \nelim (H a a0). \nintro. \nrewrite a2. \nleft; auto. \n \nintro. \nright. \nunfold not in |- *. \nunfold not in b. \nintro; apply b. \ninjection H1. \nauto. \n \nunfold not in |- *; intro. \nright. \nintro; apply b. \ninjection H1. \nauto. \n \nQed. \n \nHint Resolve Listeq_dec. \n \n \nLemma Prodeq_dec :\n forall A B : Set,\n (forall x y : A, {x = y} + {x <> y}) ->\n (forall v w : B, {v = w} + {v <> w}) ->\n forall c d : A * B, {c = d} + {c <> d}. \nintros. \nelim c. \nelim d. \nintros. \nelim (H a a0); intro. \nrewrite a1. \nelim (H0 b b0); intro. \nrewrite a2. \nleft; auto. \n \nright. \nintro. \napply b1. \ninjection H1; auto. \n \nright; intro; apply b1. \ninjection H1; auto. \n \nQed. \n \nHint Resolve Prodeq_dec.", "meta": {"author": "kloisiie", "repo": "NFSModel", "sha": "f4027dd372151748fa4ade472e41af4484133c95", "save_path": "github-repos/coq/kloisiie-NFSModel", "path": "github-repos/coq/kloisiie-NFSModel/NFSModel-f4027dd372151748fa4ade472e41af4484133c95/ListFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7273597017149754}}
{"text": "Require Import Comparison.\nRequire Import ComparisonDecOrd.\n\nModule natComparision <: ComparisonSig.\n\nDefinition A := nat.\n\nFixpoint compare (a b : nat) {struct a} : comparison :=\nmatch a,b with\n| O, O => Eq\n| O, _ => Lt\n| _, O => Gt\n| (S a'), (S b') => compare a' b'\nend.\n\nInfix \"?=\" := compare (at level 70) : nat_scope.\n\nLemma compare_refl : forall a b, a ?= b = Eq <-> a = b.\nProof.\nintros.\nsplit.\ngeneralize b.\nclear b.\ninduction a; induction b; intros; try discriminate H.\nreflexivity.\nrewrite IHa with b.\nreflexivity.\napply H.\nintros.\nsubst.\ninduction b.\nreflexivity.\napply IHb.\nQed.\n\nLemma compare_antisym : forall a b, CompOpp (a ?= b) = (b ?= a).\nProof.\ninduction a; induction b; intros; try reflexivity.\nsimpl.\napply IHa.\nQed.\n\nLemma compare_trans : forall a b c, \n(a ?= b) = (b ?= c) -> (a ?= b) = (a ?= c) /\\ (b ?= c) = (a ?= c).\nProof.\napply trans_simp.\ninduction x; induction y; induction z; intros; auto.\nrewrite <- (compare_antisym 0 (S y)) in H.\ndestruct (0 ?= S y); try discriminate H.\nauto.\ndiscriminate H.\nsimpl.\napply IHx.\napply H.\nQed.\n\nEnd natComparision.\n\nModule natDecOrd <: DecidableOrder.Sig := CompareDecOrd natComparision.\nExport natDecOrd.\n", "meta": {"author": "coq-contribs", "repo": "karatsuba", "sha": "6c20ebe144d5c9a86ba47e11affecf11fa2c8881", "save_path": "github-repos/coq/coq-contribs-karatsuba", "path": "github-repos/coq/coq-contribs-karatsuba/karatsuba-6c20ebe144d5c9a86ba47e11affecf11fa2c8881/ArithEx/Compare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7273451130876817}}
{"text": "Require Coq.Logic.Classical_Prop.\nRequire Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_s_n_ncol_col.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_n_col_ncol :\n\tforall A B C,\n\t~ Col A B C ->\n\tnCol A B C.\nProof.\n\tintros A B C.\n\tintros n_Col_A_B_C.\n\tassert (~ ~ nCol A B C) as nn_nCol_A_B_C.\n\t{\n\t\tintros n_nCol_A_B_C.\n\n\t\tpose proof (lemma_s_n_ncol_col _ _ _ n_nCol_A_B_C) as Col_A_B_C.\n\n\t\tcontradict Col_A_B_C.\n\t\texact n_Col_A_B_C.\n\t}\n\tapply Classical_Prop.NNPP in nn_nCol_A_B_C.\n\texact nn_nCol_A_B_C.\nQed.\n\nEnd Euclid.\n\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_n_col_ncol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.727345102694287}}
{"text": "Require Import Tac.\nRequire Export Coq.Logic.Classical.\n\n\nDefinition excluded_middle := classic.\n\n\nLemma double_neg :\n  forall P,\n  ~~ P <-> P.\nProof. intuition tauto. Qed.\n\n\nLemma contrapositive :\n  forall P Q,\n  (~ Q -> ~ P) ->\n  P -> Q.\nProof. intros. pose proof (excluded_middle Q) as HQ. inverts1 HQ; tauto. Qed.\n\n\nLemma not_iff :\n  forall P Q,\n  (P <-> Q) <-> (~ P <-> ~ Q).\nProof. intuition tauto. Qed.\n\n\nLemma not_and__or :\n  forall P Q,\n  ~ (P /\\ Q) <-> ~ P \\/ ~ Q.\nProof. intuition tauto. Qed.\n\n\nLemma not_or__and :\n  forall P Q,\n  ~ (P \\/ Q) <-> ~ P /\\ ~ Q.\nProof. intuition tauto. Qed.\n\n\nLemma imply__or :\n  forall (P Q : Prop),\n  (P -> Q) <-> (~ P \\/ Q).\nProof. intuition tauto. Qed.\n\n\nLemma not_imply__and :\n  forall (P Q : Prop),\n  ~ (P -> Q) <-> (P /\\ ~ Q).\nProof. intuition tauto. Qed.\n\n\nLemma not_forall__exists_not :\n  forall A (P : A -> Prop),\n  ~ (forall x, P x) <-> (exists x, ~ P x).\nProof.\n  intros. split.\n  - apply contrapositive. rewrite double_neg. intros. destruct (classic (P x)).\n    * assumption.\n    * exfalso. eauto.\n  - iauto.\nQed.\n\n\nLemma forall_not__exists :\n  forall A (P : A -> Prop),\n  (forall x, P x) <-> ~ (exists x, ~ P x).\nProof.\n  intros. rewrite not_iff. rewrite double_neg. apply not_forall__exists_not.\nQed.", "meta": {"author": "JLimperg", "repo": "SessionTypes", "sha": "3cee38f62a153e5b04a6836e57ab0c851fcf44dd", "save_path": "github-repos/coq/JLimperg-SessionTypes", "path": "github-repos/coq/JLimperg-SessionTypes/SessionTypes-3cee38f62a153e5b04a6836e57ab0c851fcf44dd/src/Classical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7272916034994746}}
{"text": "Require Import Nat Arith.\n\nInductive lst : Type := Nil : lst | Cons : nat -> lst -> lst.\n\nInductive queue : Type := Queue : lst -> lst -> queue.\n\nFixpoint len (len_arg0 : lst) : nat\n           := match len_arg0 with\n              | Nil => 0\n              | Cons x y => plus 1 (len y)\n              end.\n\nDefinition qlen (qlen_arg0 : queue) : nat\n           := let 'Queue x y := qlen_arg0 in\n              plus (len x) (len y).\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nDefinition amortizeQueue (amortizeQueue_arg0 : lst) (amortizeQueue_arg1 : lst) : queue\n           := match amortizeQueue_arg0, amortizeQueue_arg1 with\n              | x, y => if leb (len y) (len x) then Queue x y else Queue (append x (rev y)) Nil\n              end.\n\nDefinition qpush (qpush_arg0 : queue) (qpush_arg1 : nat) : queue\n           := match qpush_arg0, qpush_arg1 with\n              | Queue x y, n => amortizeQueue x (Cons n y)\n              end.\n\nDefinition queue_to_lst (queue_to_lst_arg0 : queue) : lst\n           := let 'Queue x y := queue_to_lst_arg0 in\n              append x (rev y).\n\nLemma append_nil : forall (l : lst), append l Nil = l.\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem theorem0 : forall (q : queue) (n : nat), eq (append (queue_to_lst q) (Cons n Nil)) (queue_to_lst (qpush q n)).\nProof.\n  intros.\n  destruct q.\n  induction l.\n  - simpl. rewrite append_nil. reflexivity.\n  - simpl. simpl in IHl. rewrite IHl. unfold amortizeQueue. simpl. destruct (len l) eqn:?.\n    + simpl. destruct (len l0 <=? 0) eqn:?.\n      * simpl. rewrite append_nil. reflexivity.\n      * simpl. reflexivity.\n    + destruct (len l0 <=? n1) eqn:?.\n      * simpl. apply Nat.leb_le in Heqb. apply le_S in Heqb. rewrite <- Nat.leb_le in Heqb. rewrite Heqb. simpl. reflexivity.\n      * destruct (len l0 <=? S n1) eqn:?.\n        -- simpl. rewrite append_nil. reflexivity.\n        -- simpl. reflexivity.\nQed.\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/adtind/queue_push_to_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7272913579897888}}
{"text": "Require Import Common.\nRequire Import Types.\nRequire Import Syntax.\nSet Bullet Behavior \"Strict Subproofs\".\n\n(** Typechecking **)\n\n(*Signature*)\nRecord sig :=\n  {\n    sig_t : list typesym;\n    sig_f: list funsym;\n    sig_p: list predsym\n  }.\n\n(* Typing rules for types *)\n\nInductive valid_type : sig -> vty -> Prop :=\n  | vt_int: forall s,\n    valid_type s vty_int\n  | vt_real: forall s,\n    valid_type s vty_real\n  | vt_tycons: forall s ts vs,\n    In ts (sig_t s) ->\n    length vs = length (ts_args ts) ->\n    (forall x, In x vs -> valid_type s x) ->\n    (*Forall (fun x => valid_type s x) vs ->*)\n    valid_type s (vty_cons ts vs).\n(*Notation \"s '|-' t\" := (valid_type s t) (at level 40).*)\n\n(*Typing rules for patterns*)\nInductive pattern_has_type: sig -> pattern -> vty -> Prop :=\n  | P_Var: forall s x,\n    valid_type s (snd x) ->\n    pattern_has_type s (Pvar x) (snd x)\n  | P_Wild: forall s ty,\n    valid_type s ty ->\n    pattern_has_type s Pwild ty\n  | P_Constr: forall s (params : list vty) (ps : list pattern) (f: funsym),\n    In f (sig_f s) ->\n    Forall (valid_type s) params ->\n    (*NOTE: NOT included in paper - is this implied elsewhere?*)\n    valid_type s (f_ret f) ->\n    length ps = length (s_args f) ->\n    length params = length (s_params f) ->\n    (* For all i, [nth i tms] has type [sigma(nth i (s_args f))], where\n      sigma is the type substitution that maps f's type vars to [params] *)\n    let sigma : vty -> vty := ty_subst (s_params f) params in\n    (forall x, In x (combine ps (map sigma (s_args f))) ->\n      pattern_has_type s (fst x) (snd x)) ->\n    (* No free variables in common *)\n    (forall i j d x, i < length ps -> j < length ps -> i <> j ->\n      ~(In x (pat_fv (nth i ps d)) /\\ In x (pat_fv (nth j ps d)))) ->\n        pattern_has_type s (Pconstr f params ps) (sigma (f_ret f))\n  | P_Or: forall s p1 p2 ty,\n    pattern_has_type s p1 ty ->\n    pattern_has_type s p2 ty ->\n    (forall x, In x (pat_fv p1) <-> In x (pat_fv p2)) ->\n    pattern_has_type s (Por p1 p2) ty\n  | P_Bind: forall s x p,\n    ~ In x (pat_fv p) ->\n    pattern_has_type s p (snd x) ->\n    pattern_has_type s (Pbind p x) (snd x).\n\n(* Typing rules for terms *)\nInductive term_has_type: sig -> term -> vty -> Prop :=\n  | T_int: forall s z,\n    term_has_type s (Tconst (ConstInt z)) vty_int\n  | T_real: forall s r,\n    term_has_type s (Tconst (ConstReal r)) vty_real\n  | T_Var: forall s x,\n    valid_type s (snd x) ->\n    term_has_type s (Tvar x) (snd x)\n  | T_Fun: forall s (params : list vty) (tms : list term) (f: funsym),\n    In f (sig_f s) ->\n    Forall (valid_type s) params ->\n    (*NOTE: NOT included in paper - is this implied elsewhere?*)\n    valid_type s (f_ret f) ->\n    length tms = length (s_args f) ->\n    length params = length (s_params f) ->\n    (* For all i, [nth i tms] has type [sigma(nth i (s_args f))], where\n      sigma is the type substitution that maps f's type vars to [params] *)\n    (*let sigma : vty -> vty := ty_subst (s_params f) params in*)\n    Forall (fun x => term_has_type s (fst x) (snd x)) (combine tms\n      (map (ty_subst (s_params f) params) (s_args f))) ->\n    term_has_type s (Tfun f params tms) (ty_subst (s_params f) params (f_ret f))\n  | T_Let: forall s t1 x t2 ty2,\n    term_has_type s t1 (snd x) ->\n    term_has_type s t2 ty2 ->\n    term_has_type s (Tlet t1 x t2) ty2\n  | T_If: forall s f t1 t2 ty,\n    valid_formula s f ->\n    term_has_type s t1 ty ->\n    term_has_type s t2 ty ->\n    term_has_type s (Tif f t1 t2) ty\n  | T_Match: forall s tm ty1 (ps: list (pattern * term)) ty2,\n    (*we defer the check for algebraic datatypes or exhaustiveness until\n      later, because we need an additional context*)\n    term_has_type s tm ty1 ->\n    (forall x, In x ps -> pattern_has_type s (fst x) ty1) ->\n    (forall x, In x ps -> term_has_type s (snd x) ty2) ->\n    (*Makes things MUCH simpler to include this - TODO: is this a problem?\n    If not, need to prove by knowing that pattern matching exhaustive, so\n    nonempty, so can take 1st element. But then we need a context\n    and additional hypotheses in semantics.*)\n    (*valid_type s ty2 ->*)\n    (*need this to ensure that typing is decidable*)\n    negb (null ps) ->\n    term_has_type s (Tmatch tm ty1 ps) ty2\n  | T_eps: forall s x f,\n    (*TODO: is this the right typing rule?*)\n    valid_formula s f ->\n    valid_type s (snd x) ->\n    term_has_type s (Teps f x) (snd x)\n\n\n(* Typing rules for formulas *)\nwith valid_formula: sig -> formula -> Prop :=\n  | F_True: forall s,\n    valid_formula s Ftrue\n  | F_False: forall s,\n    valid_formula s Ffalse\n  | F_Binop: forall s b f1 f2,\n    valid_formula s f1 ->\n    valid_formula s f2 ->\n    valid_formula s (Fbinop b f1 f2)\n  | F_Not: forall s f,\n    valid_formula s f ->\n    valid_formula s (Fnot f)\n  | F_Quant: forall s q x f,\n    valid_type s (snd x) ->\n    valid_formula s f ->\n    valid_formula s (Fquant q x f)\n  | F_Pred: forall s (params: list vty) (tms: list term) (p: predsym),\n    (*Very similar to function case*)\n    In p (sig_p s) ->\n    Forall (valid_type s) params ->\n    length tms = length (s_args p) ->\n    length params = length (s_params p) ->\n    let sigma : vty -> vty := ty_subst (s_params p) params in\n    Forall (fun x => term_has_type s (fst x) (snd x))\n      (combine tms (map sigma (s_args p))) ->\n    valid_formula s (Fpred p params tms)\n  | F_Let: forall s t x f,\n    term_has_type s t (snd x) ->\n    valid_formula s f ->\n    valid_formula s (Flet t x f)\n  | F_If: forall s f1 f2 f3,\n    valid_formula s f1 ->\n    valid_formula s f2 ->\n    valid_formula s f3 ->\n    valid_formula s (Fif f1 f2 f3)\n  | F_Eq: forall s ty t1 t2,\n    term_has_type s t1 ty ->\n    term_has_type s t2 ty ->\n    valid_formula s (Feq ty t1 t2)\n  | F_Match: forall s tm ty (ps: list (pattern * formula)),\n    term_has_type s tm ty ->\n    Forall(fun x => pattern_has_type s (fst x) ty) ps ->\n    Forall (fun x => valid_formula s (snd x)) ps ->\n    (*See comment in term*)\n    negb (null ps) ->\n    valid_formula s (Fmatch tm ty ps).\n(*\nNotation \"s '|-' t ':' ty\" := (term_has_type s t ty) (at level 40).\nNotation \"s '|-' f\" := (valid_formula s f) (at level 40).*)\n\nLemma bool_dec: forall {A: Type} (f: A -> bool),\n  (forall x : A, {is_true (f x)} + {~ is_true (f x)}).\nProof.\n  intros A f x. destruct (f x) eqn : Hfx; auto.\nQed.\n\n(*First, try this: TODO move*)\nLemma fun_ty_inversion: forall s (f: funsym) (vs: list vty) (tms: list term) ty_ret,\n  term_has_type s (Tfun f vs tms) ty_ret ->\n  In f (sig_f s) /\\ Forall (valid_type s) vs /\\\n  length tms = length (s_args f) /\\\n  length vs = length (s_params f) /\\\n  Forall (fun x => term_has_type s (fst x) (snd x)) \n    (combine tms (map (ty_subst (s_params f) vs) (s_args f))) /\\\n  ty_ret = ty_subst (s_params f) vs (f_ret f).\nProof.\n  intros. inversion H; subst; repeat split; auto.\nQed.\n\nLemma pred_ty_inversion: forall s (p: predsym) (vs: list vty) (tms: list term),\n  valid_formula s (Fpred p vs tms) ->\n  In p (sig_p s) /\\ Forall (valid_type s) vs /\\\n  length tms = length (s_args p) /\\\n  length vs = length (s_params p) /\\\n  Forall (fun x => term_has_type s (fst x) (snd x)) \n    (combine tms (map (ty_subst (s_params p) vs) (s_args p))).\nProof.\n  intros. inversion H; subst; repeat split; auto.\nQed.\n\nLemma valid_type_v_subst: forall s (f: typevar -> vty) (ty: vty),\n  valid_type s ty ->\n  (forall x, valid_type s (f x)) ->\n  valid_type s (v_subst_aux f ty).\nProof.\n  intros.\n  induction H; simpl; constructor; auto.\n  rewrite map_length. apply H1.\n  intros x. rewrite in_map_iff. intros [x1 [Hx1 Hinx1]].\n  specialize (H3 _ Hinx1 H0). subst. apply H3.\nQed.\n\n(*TODO: use previous lemma to prove*)\nLemma valid_type_subst: forall s ty vars tys,\n  valid_type s ty ->\n  Forall (valid_type s) tys ->\n  valid_type s (ty_subst vars tys ty).\nProof.\n  intros. induction H; unfold ty_subst; simpl; constructor; auto.\n  rewrite map_length. apply H1.\n  intros x. rewrite in_map_iff. intros [x1 [Hx1 Hinx1]].\n  specialize (H3 _ Hinx1 H0). subst. apply H3.\nQed. \n\n\n\n(* Well-formed signmatures and Contexts *)\n\n(* A well-formed signature requires all types that appear in a function/predicate\n  symbol to be well-typed and for all free type variables in these types to appear\n  in the function/predicate type parameters*)\nDefinition wf_sig (s: sig) : Prop :=\n  (*For function symbols:*)\n  Forall (fun (f: funsym) =>\n    Forall (fun (t: vty) => \n      valid_type s t /\\ Forall (fun (fv: typevar) => In fv (s_params f)) (type_vars t)\n    ) ((f_ret f) :: (s_args f))\n  ) (sig_f s) /\\\n  (*Predicate symbols are quite similar*)\n  Forall (fun (p: predsym) =>\n    Forall (fun (t: vty) => \n      valid_type s t /\\ Forall (fun (fv: typevar) => In fv (s_params p)) (type_vars t)\n    ) (s_args p)\n  ) (sig_p s).\n\n(*A context includes definitions for some of the types/functions/predicates in\n  a signature*)\nDefinition context := list def.\n\nDefinition datatypes_of_context (c: context) : list (typesym * list funsym) :=\n  concat (map datatypes_of_def c).\n\nDefinition mut_of_context (c: context) : list mut_adt :=\n  fold_right (fun x acc => match x with\n    | datatype_def m => m :: acc\n    | _ => acc\n    end) nil c.\n\nDefinition mutrec_datatypes_of_context (c: context) : list (list (typesym * list funsym)) :=\n  map datatypes_of_def c.\n\nDefinition fundefs_of_context (c: context) : list (funsym * list vsymbol * term) :=\n  concat (map fundefs_of_def c).\n\nDefinition preddefs_of_context (c: context) : list (predsym * list vsymbol * formula) :=\n  concat (map preddefs_of_def c).\n\nDefinition indpreds_of_context (c: context) : list (predsym * list formula) :=\n  concat (map indpreds_of_def c).\n\nDefinition typesyms_of_context (c: context) : list typesym :=\n  map fst (datatypes_of_context c).\n\nDefinition funsyms_of_context (c: context) : list funsym :=\n  concat (map funsyms_of_def c).\n\nDefinition predsyms_of_context (c: context) : list predsym :=\n  concat (map predsyms_of_def c).\n\n(*Ways of dealing with adts and parts in context*)\n(*We want booleans for proof irrelevance*)\n\n(*TODO: dont duplicate*)\nLtac right_dec := \n  solve[let C := fresh \"C\" in right; intro C; inversion C; try contradiction].\n\nDefinition adt_dec: forall (x1 x2: alg_datatype), {x1 = x2} + {x1 <> x2}.\nintros [t1 c1] [t2 c2].\ndestruct (typesym_eq_dec t1 t2); [|right_dec].\ndestruct (ne_list_eq_dec funsym_eq_dec c1 c2); [|right_dec].\nleft. rewrite e, e0; reflexivity.\nDefined.\n\nDefinition mut_adt_dec: forall (m1 m2: mut_adt), {m1 = m2} + {m1 <> m2}.\nintros m1 m2. destruct m1, m2.\ndestruct (list_eq_dec adt_dec typs typs0); subst; [|right_dec].\ndestruct (list_eq_dec typevar_eq_dec m_params m_params0); subst;[|right_dec].\nleft. f_equal. apply bool_irrelevance.\nDefined.\n\nDefinition mut_in_ctx (m: mut_adt) (gamma: context) :=\n  in_bool mut_adt_dec m (mut_of_context gamma).\n\nLemma mut_in_ctx_eq: forall m gamma,\n  mut_in_ctx m gamma <-> In m (mut_of_context gamma).\nProof.\n  intros. symmetry. \n  apply (reflect_iff _ _ (in_bool_spec mut_adt_dec m (mut_of_context gamma))).\nQed.\n\nLemma mut_in_ctx_eq2: forall m gamma,\n  mut_in_ctx m gamma <-> In (datatype_def m) gamma.\nProof.\n  intros. rewrite mut_in_ctx_eq. symmetry.\n  unfold mut_of_context, mut_in_ctx.\n  induction gamma; simpl; intros; auto.\n  - reflexivity.\n  - split; intros.\n    + destruct H; subst; simpl; auto.\n      apply IHgamma in H.\n      destruct a; simpl; auto.\n    + destruct a; simpl in H; try solve[right; apply IHgamma; auto].\n      destruct H. left; subst; auto. right; apply IHgamma; auto.\nQed.\n\nDefinition mut_typs_in_ctx (l: list alg_datatype) (gamma: context) :=\n  exists (vars: list typevar) (H: nodupb typevar_eq_dec vars), \n  In (datatype_def (mk_mut l vars H)) gamma.\n\n(*For recursive functions, it is VERY helpful for this to be\n  a (proof irrelevant) boolean*)\nDefinition adt_in_mut (a: alg_datatype) (m: mut_adt) :=\n  in_bool adt_dec a (typs m).\n\nDefinition ts_in_mut_list (ts: typesym) (m: list alg_datatype) : bool :=\n  in_bool typesym_eq_dec ts (map adt_name m).\n\n\nLemma ts_in_mut_list_ex: forall ts m,\n  ts_in_mut_list ts (typs m) -> { a | ts = adt_name a /\\ \n  adt_in_mut a m}.\nProof.\n  unfold adt_in_mut, ts_in_mut_list; intros. induction (typs m); simpl.\n  - simpl in H. inversion H.\n  - simpl in H.\n    destruct (typesym_eq_dec ts (adt_name a)); subst.\n    + apply (exist _ a). rewrite eq_dec_refl. split; auto.\n    + specialize (IHl H).\n      destruct IHl as [a' [Ha' Hina']].\n      apply (exist _ a'). rewrite Hina'. subst; simpl_bool; split; auto.\nQed.\n\nLemma ts_in_mut_list_spec: forall ts m,\n  ts_in_mut_list ts (typs m) <-> exists a, ts = adt_name a /\\ \n  adt_in_mut a m.\nProof.\n  intros. unfold adt_in_mut, ts_in_mut_list. induction (typs m); simpl.\n  - split; intros; auto. inversion H. destruct H as [a [H]]; inversion H0.\n  - split; intros.\n    + destruct (typesym_eq_dec ts (adt_name a)).\n      * subst. exists a. rewrite eq_dec_refl. split; auto.\n      * apply IHl in H. destruct H as [a' [Ha' Hina']].\n        subst. exists a'. rewrite Hina'. simpl_bool. split; auto.\n    + destruct H as [a' [Ha' Hina']]; subst.\n      destruct (adt_dec a' a); subst; simpl in Hina'.\n      * rewrite eq_dec_refl. reflexivity.\n      * apply orb_true_iff. right. apply IHl.\n        exists a'. split; auto.\nQed.\n\nDefinition adt_mut_in_ctx (a: alg_datatype) (m: mut_adt) (gamma: context) :=\n  adt_in_mut a m /\\ mut_in_ctx m gamma.\n\nDefinition adt_in_ctx (a: alg_datatype) (gamma: context) :=\n  exists (m: mut_adt), adt_mut_in_ctx a m gamma.\n\nDefinition constr_in_adt (c: funsym) (a: alg_datatype) :=\n  in_bool_ne funsym_eq_dec c (adt_constrs a).\n\nDefinition constr_adt_mut_in_ctx (c: funsym) (a: alg_datatype) \n  (m: mut_adt) (gamma: context) :=\n  constr_in_adt c a /\\ adt_mut_in_ctx a m gamma.\n\nDefinition constr_adt_in_ctx (c: funsym) (a: alg_datatype) (gamma: context) :=\n  constr_in_adt c a /\\ adt_in_ctx a gamma.\n\n(*We also require that all type variables in mutually recursive types\n  are correct: all component types and constructors have the same\n  parameters*)\nDefinition valid_mut_rec (m: mut_adt) : Prop :=\n  Forall (fun a => (m_params m) = (ts_args (adt_name a)) /\\\n    Forall (fun (f: funsym) => (m_params m) = (s_params f)) \n      (ne_list_to_list (adt_constrs a))) (typs m).\n\n(*A context gamma extending signature s is well-formed if all type, function, and\n  predicate symbols in gamma appear in s, and none appear more than once*)\n(*Note: we do not check the type/function/pred symbols within the terms and formulas\n  in the definition - these will be checked for the validity check for each\n  definition.*)\nDefinition wf_context (s: sig) (gamma: context) :=\n  wf_sig s /\\\n  Forall (fun t => In t (sig_t s)) (typesyms_of_context gamma) /\\\n  Forall (fun f => In f (sig_f s)) (funsyms_of_context gamma) /\\\n  Forall (fun p => In p (sig_p s)) (predsyms_of_context gamma) /\\\n  NoDup (typesyms_of_context gamma) /\\\n  NoDup (funsyms_of_context gamma) /\\\n  NoDup (predsyms_of_context gamma).\n\n(*TODO: move this maybe*)\n\n(* Additional checks for pattern matches *)\n\n(*In addition to what we have above, we also need to know that pattern\n  matches operate on an algebraic data type and are exhaustive. We separate this\n  check from the main typing relation for 2 reasons:\n  1. The exhaustiveness check relies on well-typedness in a non-strictly-positive way\n  2. This check depends on the context, as opposed to the typing relation, which only\n    depends on the signature. *) \n\n(*TODO: this does NOT work for exhaustiveness checking,\n  since we can never prove it, we do need to check\n  that the pattern match occurs on an ADT \n*)\n\nSection MatchExhaustive.\n\nVariable sigma: sig.\nVariable gamma: context.\n\n(*\n(*Describes when a pattern matches a term*)\nInductive matches : pattern -> term -> Prop :=\n  | M_Var: forall v t,\n    matches (Pvar v) t\n  | M_Constr: forall (m: mut_adt) (a: alg_datatype) \n      (f: funsym) (vs: list vty) (ps: list pattern) (ts: list term),\n    mut_in_ctx m gamma ->\n    adt_in_mut a m ->\n    constr_in_adt f a ->\n    (forall x, In x (combine ps ts) -> matches (fst x) (snd x)) ->\n    matches (Pconstr f vs ps) (Tfun f vs ts)\n  | M_Wild: forall t,\n    matches Pwild t\n  | M_Or: forall p1 p2 t,\n    matches p1 t \\/ matches p2 t ->\n    matches (Por p1 p2) t\n  | M_Bind: forall p x t,\n    matches p t ->\n    matches (Pbind p x) t.\n\n(*A match is exhaustive if for every instance of an alg_datatype,\n  some pattern matches it*)\nDefinition exhaustive_match (a: alg_datatype) (args: list vty)\n  (ps: list pattern) : Prop :=\n  adt_in_ctx a gamma /\\\n  forall t, term_has_type sigma t (vty_cons (adt_name a) args) ->\n    exists p, In p ps /\\ matches p t.*)\n\n\n(*For now, we say that a valid pattern match is one that matches\n  on an ADT*)\nFixpoint All {A: Type} (P: A -> Prop) (l: list A) {struct l} : Prop :=\n  match l with\n  | nil => True\n  | x :: xs => P x /\\ All P xs\n  end.\nDefinition iter_and (l: list Prop) : Prop :=\n  fold_right and True l.\n(*TODO: need to require somewhere that pattern constructors\n  have to actually be constructors*)\nFixpoint valid_matches_tm (t: term) : Prop :=\n  match t with\n  | Tfun f vs tms => iter_and (map valid_matches_tm tms)\n  | Tlet tm1 v tm2 => valid_matches_tm tm1 /\\ valid_matches_tm tm2\n  | Tif f1 t1 t2 => valid_matches_fmla f1 /\\ valid_matches_tm t1 /\\\n    valid_matches_tm t2\n  | Tmatch tm v ps =>\n    valid_matches_tm tm /\\\n    (*the type v is an ADT applied to some valid arguments\n      (validity from typing)*)\n    (exists a m args, mut_in_ctx m gamma /\\\n      adt_in_mut a m /\\\n      v = vty_cons (adt_name a) args) /\\\n    iter_and (map (fun x => valid_matches_tm (snd x)) ps)\n      (*iter_and (map valid_matches_tm (map snd ps))*)\n  | Teps f x => valid_matches_fmla f\n  | _ => True\n  end\nwith valid_matches_fmla (f: formula) : Prop :=\n  match f with\n  | Fpred p vs tms => iter_and (map valid_matches_tm tms)\n  | Fquant q v f => valid_matches_fmla f\n  | Feq v t1 t2 => valid_matches_tm t1 /\\ valid_matches_tm t2\n  | Fbinop b f1 f2 => valid_matches_fmla f1 /\\\n    valid_matches_fmla f2\n  | Fnot f => valid_matches_fmla f\n  | Flet t v f => valid_matches_tm t /\\ valid_matches_fmla f\n  | Fif f1 f2 f3 => valid_matches_fmla f1 /\\\n    valid_matches_fmla f2 /\\ valid_matches_fmla f3\n  | Fmatch t v ps =>\n    valid_matches_tm t /\\\n    (*the type v is an ADT applied to some valid arguments\n      (validity from typing)*)\n    (exists a m args, mut_in_ctx m gamma /\\\n      adt_in_mut a m /\\\n      v = vty_cons (adt_name a) args) /\\\n    iter_and (map (fun x => valid_matches_fmla (snd x)) ps)\n  | _ => True\n  end.\n\nEnd MatchExhaustive.\n\n(*The full typing judgement for terms and formulas*)\nDefinition well_typed_term (s: sig) (gamma: context) (t: term) (ty: vty) : Prop :=\n  term_has_type s t ty /\\ valid_matches_tm gamma t.\n\nDefinition well_typed_formula (s: sig) (gamma: context) (f: formula) : Prop :=\n  valid_formula s f /\\ valid_matches_fmla gamma f.\n\n(** Validity of definitions *)\n\n(** Algebraic Data Types **)\n\n(*For an algebraic datatype to be valid, the following must hold:\n  1. All constructors must have the correct type and type parameters\n  2. The type must be inhabited (there must be 1 constructor with\n    only inhabited types)\n  3. Instances of the type must appear in strictly positive positions *)\n\n(*Types*)\n(*All constructors have the correct return type and the same parameters as\n  the declaration*)\nDefinition adt_valid_type (a : alg_datatype) : Prop :=\n  match a with\n  | alg_def ts constrs => \n    Forall (fun (c: funsym) => \n      (s_params c) = (ts_args ts) /\\ \n      (f_ret c) = vty_cons ts (map vty_var (ts_args ts))) \n        (ne_list_to_list constrs)\n  end.\n\n(*Inhabited types*)\nSection Inhab.\n\nVariable s: sig.\nVariable gamma: context.\nVariable gamma_wf: wf_context s gamma.\n\n(*This is more complicated than it seems, for 2 reasons:\n1. Whether a type symbol/type is inhabited depends on the current context. For\n  instance, we cannot assume that a recursive instance of a type is inhabited,\n  but we can assume that previously-declared types are. Similarly, if we know\n  that a type variable a is applied to a nonexistent type, we cannot assume\n  further instances of a are inhabited. So we need 2 lists representing the\n  known non-inhabited types in the current context.\n2. The cons case in vty_inhab involes a condition: In x new_tvs <-> ~ vty_inhab _ _ y.\n   This is not strictly positive, so we include an additional boolean parameter\n   to indicate truth or falsehood. Thus, we need to add all the \"false\" cases,\n   which otherwise would not be needed. It remains to show that this relation is\n   decidable and that the boolean parameter correctly shows whether \n   *_inhab tss tvs x true is provable. *)\nUnset Elimination Schemes.\nInductive typesym_inhab : list typesym -> list typevar -> typesym -> bool -> Prop :=\n  | ts_check_empty: forall tss tvs ts,\n    ~ In ts (sig_t s) ->\n    typesym_inhab tss tvs ts false\n  | ts_check_rec: forall tss tvs ts, (*recursive type*)\n    In ts tss ->\n    typesym_inhab tss tvs ts false\n  | ts_check_typeT: forall tss tvs ts, (*for abstract type*)\n    ~ In ts tss ->\n    ~ In ts (map fst (datatypes_of_context gamma)) ->\n    In ts (sig_t s) ->\n    (*no \"bad\" type variables in context - these are the uninhabited arguments of the\n      typesym (see vty_inhab below)*)\n    null tvs ->\n    typesym_inhab tss tvs ts true\n  | ts_check_typeF: forall tss tvs ts,\n    ~In ts tss  ->\n    ~ In ts (map fst (datatypes_of_context gamma)) ->\n    negb (null tvs) ->\n    typesym_inhab tss tvs ts false\n  | ts_check_adtT: forall tss tvs ts constrs c, (*for ADTs*)\n    In ts (sig_t s) ->\n    ~In ts tss ->\n    In (ts, constrs) (datatypes_of_context gamma) ->\n    negb (null constrs) ->\n    In c constrs ->\n    (constr_inhab (ts :: tss) tvs c true) ->\n    typesym_inhab tss tvs ts true\n  | ts_check_adtF1: forall tss tvs ts constrs,\n    ~In ts tss ->\n    In (ts, constrs) (datatypes_of_context gamma) ->\n    null constrs ->\n    typesym_inhab tss tvs ts false\n  | ts_check_adtF2: forall tss tvs ts constrs,\n    ~In ts tss ->\n    In (ts, constrs) (datatypes_of_context gamma) ->\n    negb( null constrs) ->\n    (forall c, In c constrs -> constr_inhab (ts :: tss) tvs c false) ->\n    typesym_inhab tss tvs ts false\nwith constr_inhab: list typesym -> list typevar -> funsym -> bool -> Prop :=\n  | constr_checkT: forall tss tvs (c: funsym),\n    (forall x, In x (s_args c) -> vty_inhab tss tvs x true) ->\n    constr_inhab tss tvs c true\n  | constr_checkF: forall tss tvs (c: funsym) v,\n    In v (s_args c) ->\n    vty_inhab tss tvs v false ->\n    constr_inhab tss tvs c false\n(*Here, need bool to deal with strict positivity issues*)\nwith vty_inhab: list typesym -> list typevar -> vty -> bool -> Prop :=\n  | vty_check_int: forall tss tvs,\n    vty_inhab tss tvs vty_int true\n  | vty_check_real: forall tss tvs,\n    vty_inhab tss tvs vty_real true\n  | vty_check_varT: forall tss tvs tv,\n    ~ In tv tvs ->\n    vty_inhab tss tvs (vty_var tv) true\n  | vty_check_varF: forall tss tvs tv,\n    In tv tvs ->\n    vty_inhab tss tvs (vty_var tv) false\n  | vty_check_consT: forall tss tvs new_tvs ts args,\n    (*making this condition strictly positive is not easy*)\n    (*Condition: for all x y, In (x, y) (combine (ts_args ts) args) ->\n    In x new_tvs <-> ~vty_inhab tss tvs y*)\n    (forall x y, In (x, y) (combine args (ts_args ts)) ->\n    ~ (In y new_tvs) -> vty_inhab tss tvs x true) ->\n    (forall x y, In (x, y) (combine args (ts_args ts)) ->\n      In y new_tvs -> vty_inhab tss tvs x false) ->\n    typesym_inhab tss new_tvs ts true ->\n    vty_inhab tss tvs (vty_cons ts args) true\n  | vty_check_consF: forall tss tvs new_tvs ts args,\n    (forall x y, In (x, y) (combine args (ts_args ts)) ->\n    ~ (In y new_tvs) -> vty_inhab tss tvs x true) ->\n    (forall x y, In (x, y) (combine args (ts_args ts)) ->\n      In y new_tvs -> vty_inhab tss tvs x false) ->\n    typesym_inhab tss new_tvs ts false ->\n    vty_inhab tss tvs (vty_cons ts args) false\n    .\n\nScheme typesym_inhab_ind := Minimality for typesym_inhab Sort Prop with\nconstr_inhab_ind := Minimality for constr_inhab Sort Prop with\nvty_inhab_ind := Minimality for vty_inhab Sort Prop.\n\nSet Elimination Schemes.\n\n(*An ADT is inhabited if its typesym is inhabited under the empty context*)\nDefinition adt_inhab (a : alg_datatype) : Prop :=\n  match a with\n  | alg_def ts constrs => typesym_inhab nil nil ts true\n  end.\n\n(*We want to prove that this definition corresponds to (closed) types being inhabited.\n  TODO: is it actually equivalent?*)\n\nDefinition find_constrs (gamma:context) (t: typesym) : option (list funsym) :=\n  fold_right (fun x acc => if typesym_eq_dec (fst x) t then Some (snd x) else acc)\n    None (datatypes_of_context gamma).\n\nLemma find_constrs_none: forall gamma t,\n  find_constrs gamma t = None <-> ~In t (map fst (datatypes_of_context gamma)).\nProof.\n  intros. unfold find_constrs. induction (datatypes_of_context gamma0); simpl; split; intros; auto.\n  - destruct (typesym_eq_dec (fst a) t); [inversion H |].\n    apply IHl in H. intro C. destruct C; auto.\n  - destruct (typesym_eq_dec (fst a) t).\n    + exfalso. apply H. left; auto.\n    + apply IHl. intro C. apply H. right; auto.\nQed.\n\nLemma find_constrs_some: forall gamma t cs,\n  NoDup (typesyms_of_context gamma) ->\n  find_constrs gamma t = Some cs <-> In (t, cs) (datatypes_of_context gamma).\nProof.\n  unfold typesyms_of_context, find_constrs. intros.\n  induction (datatypes_of_context gamma0); simpl; split; intros; auto; try (solve [inversion H0]).\n  - destruct (typesym_eq_dec (fst a) t); simpl; subst.\n    + inversion H0; subst. left. destruct a; reflexivity.\n    + apply IHl in H0. right; auto. simpl in H. inversion H; auto.\n  - destruct H0; subst; simpl.\n    + destruct (typesym_eq_dec t t); auto. contradiction.\n    + destruct (typesym_eq_dec (fst a) t); subst; simpl.\n      * simpl in H. inversion H; subst. exfalso. apply H3.\n        rewrite in_map_iff. exists (fst a, cs). split; auto.\n      * apply IHl; auto. inversion H; auto.\nQed.\n\n(*For now, we assume this as an axiom*)\n(*\nLemma adt_inhab_inhab: forall a,\n  adt_in_ctx a gamma ->\n  adt_inhab a ->\n  forall vs,\n    length vs = length (ts_args (adt_name a)) ->\n    exists t, term_has_type s t (vty_cons (adt_name a) vs).\nAdmitted.*)\n\nEnd Inhab.\n\n(*Strict Positivity for Types*)\n\nFixpoint typesym_in (t: typesym) (v: vty) : bool :=\n  match v with\n  | vty_int => false\n  | vty_real => false\n  | vty_var x => false\n  | vty_cons ts vs => typesym_eq_dec t ts || existsb (typesym_in t) vs\n  end.\n\nSection PosTypes.\n\n(*harder because we dont have function types - need to mention constructor,\n  not just type*)\n(*Adapted from https://coq.inria.fr/refman/language/core/inductive.html*)\n\nVariable gamma: context.\n\nInductive strictly_positive : vty -> list typesym -> Prop :=\n  | Strict_notin: forall (t: vty) (ts: list typesym),\n    (forall x, In x ts -> negb(typesym_in x t)) ->\n    strictly_positive t ts\n  | Strict_constr: forall (t: vty) (ts: list typesym),\n    (exists (x: typesym) vs, In x ts /\\ t = vty_cons x vs /\\\n      (forall (y: typesym) (v: vty), In y ts -> In v vs ->\n        negb (typesym_in y v))) ->\n    strictly_positive t ts\n  (*TODO: I don't think the 3rd case applies to us because\n    we don't have built in function types -  how to handle function types?\n    should we add function types? Then we need application and lambdas*)\n  | Strict_ind: forall (t: vty) (ts: list typesym) (I: typesym) \n    (constrs: ne_list funsym) (vs: list vty),\n    mut_typs_in_ctx [alg_def I constrs] gamma -> (*singleton list means non-mutually recursive*)\n    t = vty_cons I vs ->\n    (forall (x: typesym) (v: vty), In x ts -> In v vs ->\n      negb (typesym_in x v)) ->\n    (forall (c: funsym), In c (ne_list_to_list constrs) ->\n      nested_positive c (ts_args I) vs I ts) ->\n    strictly_positive t ts\n\n(*I believe this reduces to positive in our case, but it only applies\n  to non-mutual inductive types. How to encode this?*)\n(*We don't have to worry about uniform/non-uniform params because\n  our only params are type variables*)\n(*We say constructor T of (non-mutual) inductive type I is satisfies\n  nested positivity wrt ts*)\n(*We take in the type substitution (params_i -> substs_i) (or [p_j/a_j])\n  because this has to operate on a funsym, not a vty, since we don't have\n  function types. This makes the definition a bit ugly*)\nwith nested_positive: funsym -> list typevar -> list vty ->\n   typesym -> list typesym -> Prop :=\n  | Nested_constr: forall (T: funsym) (params: list typevar) (substs: list vty)\n     (I: typesym) (ts: list typesym),\n    (forall vty, In vty (s_args T) -> \n      strictly_positive (ty_subst params substs vty) ts) ->\n    (exists vs, (ty_subst params substs (f_ret T)) = vty_cons I vs /\\\n      (forall x v, In x ts -> In v vs -> negb (typesym_in x v))) ->\n    nested_positive T params substs I ts.\n\nInductive positive : funsym -> list typesym -> Prop :=\n  (*We combine into one case because of we don't have true function types*)\n  | Pos_constr: forall (constr: funsym) (ts: list typesym),\n    (forall vty, In vty (s_args constr) -> strictly_positive vty ts) ->\n    (exists t vtys, In t ts /\\ f_ret constr = vty_cons t vtys /\\\n      forall (v: vty) (x: typesym), In x ts -> In v vtys ->\n        negb (typesym_in x v)) ->\n    positive constr ts.\n\n(*Finally, we want to say the following well-formedness condition:*)\nDefinition adt_positive (l: list alg_datatype) : Prop :=\n  let ts : list typesym :=\n    map (fun a => match a with | alg_def ts _ => ts end) l in\n  let fs: list funsym :=\n    concat (map (fun a => match a with | alg_def _ constrs => ne_list_to_list constrs end) l) in\n  Forall (fun f => positive f ts) fs.\n\nEnd PosTypes.\n\n(* Recursive Functions and Predicates *)\nSection FunPredSym.\n\nVariable s: sig.\nVariable gamma: context.\n\n(*A function/pred symbol is well-typed if the term has the correct return type of\n  the function and all free variables in t are included in the arguments vars*)\n\nDefinition funpred_def_valid_type (fd: funpred_def) : Prop :=\n  match fd with\n  | fun_def f vars t =>\n    well_typed_term s gamma t (f_ret f) /\\\n    sublist (term_fv t) vars\n  | pred_def p vars f =>\n    well_typed_formula s gamma f /\\\n    sublist (form_fv f) vars\n  end.\n  (*TODO: handle type vars? Do we need to, or is that handled by wf of f?*)\n\n(*Termination*)\n\n(*TODO*)\n\n(*Inductive Predicates*)\n\n(*Each clause must be a closed formula, well-typed, and belong to a restricted grammar, which\n  we give both as an inductive definition and a computable Fixpoint below*)\n\nInductive valid_ind_form (p: predsym) : formula -> Prop :=\n  | VI_pred: forall (tys : list vty) tms,\n    tys = map vty_var (s_params p) ->\n    length (s_args p) = length tms ->\n    valid_ind_form p (Fpred p tys tms)\n  | VI_impl: forall f1 f2,\n    valid_ind_form p f2 ->\n    valid_ind_form p (Fbinop Timplies f1 f2)\n  | VI_forall: forall x f,\n    valid_ind_form p f ->\n    valid_ind_form p (Fquant Tforall x f)\n  | VI_let: forall x t f,\n    valid_ind_form p f ->\n    valid_ind_form p (Flet t x f).\n     \nFixpoint valid_ind_form_dec (p: predsym) (f: formula) : bool :=\n  match f with\n  | Fpred p' tys tms => predsym_eq_dec p p' && list_eq_dec vty_eq_dec tys (map vty_var (s_params p))\n    && (length (s_args p) =? length tms)\n  | Fquant Tforall x f' => valid_ind_form_dec p f'\n  | Fbinop Timplies f1 f2 => valid_ind_form_dec p f2\n  | Flet t x f' => valid_ind_form_dec p f'\n  | _ => false\n  end.\n\nLemma valid_ind_form_equiv: forall p f,\n  reflect (valid_ind_form p f) (valid_ind_form_dec p f).\nProof.\n  intros. apply iff_reflect. \n  induction f using formula_ind with (P1:=(fun _ => True)); auto; simpl;\n  (split; [intros C;inversion C; subst| intros]); auto; try solve[intuition]; try solve[constructor];\n  try match goal with | H: false = true |- _ => inversion H end.\n  - rewrite H4, Nat.eqb_refl, andb_true_r. apply andb_true_intro; split; simpl_sumbool. \n  - repeat(apply andb_prop in H0; destruct H0). repeat simpl_sumbool. constructor; auto.\n    apply Nat.eqb_eq. auto.\n  - destruct q;[constructor; intuition |inversion H].\n  - destruct b; try inversion H. constructor. intuition.\n  - constructor. intuition.\nQed.\n\nDefinition indprop_valid_type (i: indpred_def) : Prop :=\n  match i with\n  | ind_def p lf => Forall (fun f => well_typed_formula s gamma f /\\ \n      closed_formula f /\\ valid_ind_form p f) lf\n  end.\n\n(*Strict Positivity*)\n\n(*First, does a predicate symbol appear in a formula? Because of \"if\" expressions,\n  we also need a version for terms*)\nFixpoint predsym_in (p: predsym) (f: formula) {struct f}  : bool :=\n  match f with\n  | Fpred ps tys tms => predsym_eq_dec p ps || existsb (predsym_in_term p) tms\n  | Fquant q x f' => predsym_in p f'\n  | Feq ty t1 t2 => predsym_in_term p t1 || predsym_in_term p t2\n  | Fbinop b f1 f2 => predsym_in p f1 || predsym_in p f2\n  | Fnot f' => predsym_in p f'\n  | Ftrue => false\n  | Ffalse => false\n  | Flet t x f' => predsym_in_term p t || predsym_in p f'\n  | Fif f1 f2 f3 => predsym_in p f1 || predsym_in p f2 || predsym_in p f3\n  | Fmatch t ty ps => predsym_in_term p t || existsb (fun x => predsym_in p (snd x)) ps\n  end\n  \nwith predsym_in_term (p: predsym) (t: term) {struct t}  : bool :=\n  match t with\n  | Tconst _ => false\n  | Tvar _ => false\n  | Tfun fs tys tms => existsb (predsym_in_term p) tms\n  | Tlet t1 x t2 => predsym_in_term p t1 || predsym_in_term p t2\n  | Tif f t1 t2 => predsym_in p f || predsym_in_term p t1 || predsym_in_term p t2\n  | Tmatch t ty ps => predsym_in_term p t || existsb (fun x => predsym_in_term p (snd x)) ps\n  | Teps f x => predsym_in p f\n  end.\n  \n(*Here, strict positivity is a bit simpler, because predicates are not\n  higher-order; we only need to reason about implication, essentially *)\n\n(*Inductive case and nested positivity cannot occur because we cannot\n  take a predicate as an argument (ie: can't have list x, where x : Prop)*)\nInductive ind_strictly_positive (ps: list predsym) : formula -> Prop :=\n  | ISP_notin: forall (f: formula),\n    (forall p, In p ps -> negb (predsym_in p f)) ->\n    ind_strictly_positive ps f\n  | ISP_pred: forall (p: predsym) \n    (vs: list vty) (ts: list term),\n    In p ps ->\n    (forall x t, In t ts -> In x ps -> negb (predsym_in_term x t)) ->\n    ind_strictly_positive ps (Fpred p vs ts)\n  | ISP_impl: forall  (f1 f2: formula),\n    ind_strictly_positive ps f2 ->\n    (forall p, In p ps -> negb(predsym_in p f1)) ->\n    ind_strictly_positive ps (Fbinop Timplies f1 f2)\n  (*The rest of the cases are not too interesting*)\n  | ISP_quant: forall (q: quant) (x: vsymbol) (f: formula),\n    ind_strictly_positive ps f ->\n    ind_strictly_positive ps (Fquant q x f)\n  | ISP_and: forall (f1 f2 : formula),\n    ind_strictly_positive ps f1 ->\n    ind_strictly_positive ps f2 ->\n    ind_strictly_positive ps (Fbinop Tand f1 f2)\n  | ISP_or: forall (f1 f2 : formula),\n    ind_strictly_positive ps f1 ->\n    ind_strictly_positive ps f2 ->\n    ind_strictly_positive ps (Fbinop Tor f1 f2)\n  | ISP_let: forall (t: term) (x: vsymbol) (f: formula),\n    (forall p, In p ps -> negb (predsym_in_term p t)) ->\n    ind_strictly_positive ps f -> (*TODO: is this too restrictive as well? Think OK*)\n    ind_strictly_positive ps (Flet t x f)\n  | ISP_if: forall f1 f2 f3,\n    (*Cannot be in guard because get (essentially), f1 -> f2 /\\ ~f1 -> f3*)\n    (forall p, In p ps -> negb(predsym_in p f1)) ->\n    ind_strictly_positive ps f2 ->\n    ind_strictly_positive ps f3 ->\n    ind_strictly_positive ps (Fif f1 f2 f3)\n  | ISP_match: forall (t: term) ty (pats: list (pattern * formula)),\n    (forall p, In p ps -> negb (predsym_in_term p t)) ->\n    (forall f, In f (map snd pats) -> ind_strictly_positive ps f) ->\n    ind_strictly_positive ps (Fmatch t ty pats) \n  (*eq, not, iff covered by case \"notin\" - these cannot have even strictly\n    positive occurrences *).\n\n\nInductive ind_positive (ps: list predsym) : formula -> Prop :=\n  | IP_pred: forall (p: predsym) \n    (vs: list vty) (ts: list term),\n    In p ps ->\n    (forall x t, In t ts -> In x ps -> negb (predsym_in_term x t)) ->\n    ind_positive ps (Fpred p vs ts)\n  | IP_forall: forall (x: vsymbol) (f: formula),\n    ind_positive ps f ->\n    (* Don't need strict positivity for ty because we cannot quantify over formulas*)\n    ind_positive ps (Fquant Tforall x f)\n  | IP_let: forall (t: term) (x: vsymbol) (f: formula),\n    (*TODO: is this the right condition? I think so, but should we allow this\n      symbol to appear in terms in any cases?*)\n    (forall p, In p ps -> negb (predsym_in_term p t)) ->\n    ind_positive ps f ->\n    ind_positive ps (Flet t x f)\n  | IP_impl: forall (f1 f2: formula),\n    ind_strictly_positive ps f1 ->\n    ind_positive ps f2 ->\n    ind_positive ps (Fbinop Timplies f1 f2).\n\nDefinition indpred_positive (l: list indpred_def) : Prop :=\n  let ps : list predsym :=\n    map (fun i => match i with |ind_def p fs => p end) l in\n  let fs: list formula :=\n    concat (map (fun i => match i with |ind_def p fs => fs end) l) in\n  Forall (ind_positive ps) fs.\n\nEnd FunPredSym.\n\n(*Put it all together*)\nDefinition valid_context (s : sig) (gamma: context) :=\n  wf_context s gamma /\\\n  Forall (fun d =>\n    match d with\n    | datatype_def m => Forall adt_valid_type (typs m) /\\ \n                           Forall (adt_inhab s gamma) (typs m) /\\\n                           adt_positive gamma (typs m) /\\\n                           valid_mut_rec m\n    | recursive_def fs => Forall (funpred_def_valid_type s gamma) fs\n    | inductive_def is => Forall (indprop_valid_type s gamma) is /\\\n                          indpred_positive is\n    end) gamma.\n\nLemma wf_context_expand: forall s d gamma,\n  wf_context s (d :: gamma) ->\n  wf_context s gamma.\nProof.\n  intros s d gamma. unfold wf_context. intros.\n  unfold typesyms_of_context, datatypes_of_context, \n  funsyms_of_context, predsyms_of_context in *; \n  simpl in *; rewrite map_app in *.\n  repeat match goal with\n  | H: ?P /\\ ?Q |- _ => destruct H\n  | H: Forall ?P (?l1 ++ ?l2) |- _ => apply Forall_app in H\n  | H: NoDup (?l1 ++ ?l2) |- _ => apply NoDup_app in H\n  | |- ?P /\\ ?Q => split; auto\n  end.\nQed.\n\n(*TODO: move*)\nLemma in_bool_In  {A : Type} \n(eq_dec : forall x y : A, {x = y} + {x <> y}) \n(x : A) (l : list A): in_bool eq_dec x l -> In x l.\nProof.\n  intros Hin. apply (reflect_iff _ _ (in_bool_spec eq_dec x l)).\n  auto.\nQed. \n\nSection ValidContextLemmas.\n\nContext {s: sig} {gamma: context} (gamma_valid: valid_context s gamma).\n\n(*These lemmas all have the same form: keep applying Forall_forall, in_map_iff,\n  and similar, until we get what we want. Here we automate them*)\nLtac valid_context_tac :=\n  let Hwf := fresh \"Hwf\" in\n  let Hadts := fresh \"Hadts\" in\n  destruct gamma_valid as [Hwf Hadts];\n  rewrite Forall_forall in Hadts;\n  unfold adt_in_mut, constr_in_adt in *;\n  repeat match goal with\n  | Hin: is_true (mut_in_ctx ?m ?l) |- _ => \n    rewrite mut_in_ctx_eq2 in Hin\n  | Hin: is_true (in_bool adt_dec ?x ?l) |- _ =>\n    let Hinx := fresh \"Hin\" in\n    assert (Hinx: In x l) by (apply (in_bool_In _  _ _ Hin));\n    clear Hin\n  | Hin: In ?x (?p gamma) |- _ => unfold p in Hin\n  | Hin: In ?x (concat ?l) |- _ => rewrite in_concat in Hin\n  | Hex: exists x, ?p |- _ => destruct Hex; subst\n  | Hconj: ?P /\\ ?Q |- _ => destruct Hconj; subst\n  | Hmap: In ?x (map ?f ?l) |- _ => rewrite in_map_iff in Hmap\n  | Hgam: In ?x gamma |- _ => apply Hadts in Hgam\n  | Hdef: def |- _ => destruct Hdef; simpl in *\n  | Halg: match ?x with | alg_def ts fs => ?p end = ?q |- _ => \n    destruct x; inversion Halg; subst; clear Halg\n  | Halg: match ?x with | alg_def ts fs => ?p end |- _ => destruct x\n  | Hf: False |- _ => destruct Hf\n  | Hall: Forall ?P ?l |- _ => rewrite Forall_forall in Hall\n  | Hin: In ?x ?l, Hall: forall x : ?t, In x ?l -> ?P |- _ =>\n    specialize (Hall _ Hin)\n  end; auto.\n\n(*\n(a: typesym) (constrs: list funsym) (c: funsym),\n  In (a, constrs) (datatypes_of_context gamma) ->\n  In c constrs ->\n  s_ret c = vty_cons a (map vty_var (ts_args a)) /\\\n  s_params c = ts_args a.\nProof.\n  intros. valid_context_tac.\n  unfold adt_valid_type in H.\n  valid_context_tac.\nQed.\n\nLemma adt_constr_ret_params_eq: forall {a: typesym} {constrs: list funsym} {c1 c2: funsym},\n  In (a, constrs) (datatypes_of_context gamma) ->\n  In c1 constrs -> In c2 constrs ->\n  s_ret c1 = s_ret c2 /\\ s_params c1 = s_params c2.\nProof.\n  intros.\n  pose proof (adt_constr_ret_params _ _ _ H H0).\n  pose proof (adt_constr_ret_params _ _ _ H H1).\n  destruct H2; destruct H3; split; congruence.\nQed.*)\n\n(*TODO: automate this: just a bunch of Forall_forall, in_map_iff, etc*)\n(*\nDefinition args_params_eq: forall {l: list (typesym * list funsym)}\n  {c: funsym} {adt: typesym} {constrs: list funsym}\n  (Hin1: In l (mutrec_datatypes_of_context gamma))\n  (Hin2: In (adt, constrs) l)\n  (Hin3: In c constrs),\n  ts_args adt = s_params c.\nProof.\n  intros. valid_context_tac.\n  unfold adt_valid_type in H.\n  valid_context_tac.\nQed.\n*)\nLemma adt_args: forall {m: mut_adt} {a: alg_datatype}\n  (Hin: adt_mut_in_ctx a m gamma),\n  ts_args (adt_name a) = m_params m.\nProof.\n  intros. unfold adt_mut_in_ctx in Hin. destruct Hin.\n  unfold adt_in_mut in H.\n  valid_context_tac.\n  unfold valid_mut_rec in H2.\n  valid_context_tac.\nQed.\n\nLemma adt_constr_params: forall {m: mut_adt} {a: alg_datatype}\n  {c: funsym} (Hm: mut_in_ctx m gamma)\n  (Ha: adt_in_mut a m)\n  (Hc: constr_in_adt c a),\n  s_params c = m_params m.\nProof.\n  intros. unfold adt_in_mut in Ha.\n  unfold constr_in_adt in Hc.\n  valid_context_tac.\n  unfold valid_mut_rec in H2.\n  valid_context_tac. rewrite <- H3. reflexivity.\n  rewrite in_bool_ne_equiv in Hc.\n  apply (in_bool_In _ _ _ Hc).\nQed.\n\nLemma adt_constr_ret: forall {m: mut_adt} {a: alg_datatype}\n  {c: funsym} (Hm: mut_in_ctx m gamma) (Ha: adt_in_mut a m) \n  (Hc: constr_in_adt c a),\n  f_ret c = vty_cons (adt_name a) (map vty_var (m_params m)).\nProof.\n  intros.\n  (*This is an ugly hack, should change tactic so it leaves \"in\"\n  assumptions*)\n  assert (adt_mut_in_ctx a m gamma) by \n    (unfold adt_mut_in_ctx; split; assumption). \n  valid_context_tac.\n  unfold adt_valid_type in H0.\n  rewrite in_bool_ne_equiv in Hc.\n  apply in_bool_In in Hc.\n  valid_context_tac.\n  rewrite H4. f_equal.\n  f_equal. replace t with (adt_name ((alg_def t n))) by auto.\n  apply adt_args. auto.\nQed. \n\nLemma adts_names_nodups: forall {m: mut_adt}\n  (Hin: mut_in_ctx m gamma),\n  NoDup (map adt_name (typs m)).\nProof.\n  intros. \n  unfold valid_context in gamma_valid.\n  destruct gamma_valid as [Hwf _].\n  unfold wf_context in Hwf.\n  clear -Hin Hwf.\n  destruct Hwf as [_ [_ [_ [_ [Huniq _]]]]].\n  induction gamma.\n  - inversion Hin.\n  - simpl in *. unfold typesyms_of_context in *.\n    unfold datatypes_of_context in *. simpl in Huniq.\n    rewrite map_app in Huniq.\n    rewrite NoDup_app_iff in Huniq.\n    destruct Huniq as [Hn1 [Hn2 [Hi1 Hi2]]].\n    rewrite mut_in_ctx_eq2 in Hin.\n    simpl in Hin.\n    destruct Hin; subst.\n    + simpl in Hn1. rewrite map_map in Hn1.\n      unfold adt_name. \n      assert (forall {A} (l1 l2: list A), NoDup l1 -> l1 = l2\n      -> NoDup l2) by (intros; subst; auto).\n      apply (H _ _ _ Hn1).\n      apply map_ext. intros. destruct a; reflexivity.\n    + apply IHc. rewrite mut_in_ctx_eq2. apply H. apply Hn2.\nQed.\n\nLemma adts_nodups: forall {m: mut_adt}\n  (Hin: mut_in_ctx m gamma),\n  NoDup (typs m).\nProof.\n  intros.\n  eapply NoDup_map_inv. apply adts_names_nodups. apply Hin.\nQed.\n\n(*TODO: don't need these anymore but maybe useful later?*)\n\nLemma NoDup_equiv: forall {A: Type} (l: list A),\n  NoDup l <-> (forall n1 n2 d1 d2, n1 < length l -> n2 < length l ->\n    nth n1 l d1 = nth n2 l d2 -> n1 = n2).\nProof.\n  intros A l. induction l; simpl; split; intros.\n  - inversion H0.\n  - constructor.\n  - inversion H; subst.\n    destruct n1.\n    + destruct n2; auto.\n      exfalso. apply H5. subst. apply nth_In. lia.\n    + destruct n2. \n      * exfalso. apply H5. subst. apply nth_In. lia.\n      * f_equal. rewrite IHl in H6.\n        apply (H6 _ _ d1 d2); auto; lia.\n  - constructor.\n    + intro C.\n      pose proof (In_nth l a a C).\n      destruct H0 as [n [Hn Ha]].\n      assert (0 = S n). {\n        apply (H _ _ a a); try lia.\n        auto.\n      }\n      inversion H0.\n    + apply IHl. intros n1 n2 d1 d2 Hn1 Hn2 Heq.\n      assert (S n1 = S n2). {\n        apply (H _ _ d1 d2); try lia; auto.\n      }\n      inversion H0; auto.\nQed.\n(*\nLemma nth_concat: forall {A: Type} {l: list (list A)} {l2: list A} \n{n: nat}\n  {d} {n2 d2},\n  n2 < length l ->\n  n < length (concat l) ->\n  nth n2 l d2 = l2 ->\n  nth n (concat l) d =\n    nth (n - length (concat (firstn n2 l))) l2 d.\nProof.\n  intros A l; induction l; simpl; intros.\n  - inversion H0.\n  - destruct n2.\n    + subst. simpl. \n  \n  \n  destruct H0.\n  - induction l\n*)\n\nLemma NoDup_not_cons: forall {A: Type} \n(eq_dec: forall (x y : A), {x = y} + {x <> y}) {a : A} {l},\n  ~ NoDup (a :: l) <-> In a l \\/ ~NoDup l.\nProof.\n  intros.\n  rewrite (reflect_iff _ _ (nodup_NoDup eq_dec _)).\n  rewrite nodupb_cons.\n  rewrite (reflect_iff _ _ (nodup_NoDup eq_dec _)).\n  rewrite (reflect_iff _ _ (in_bool_spec eq_dec _ _)).\n  split; intros; auto.\n  - destruct (in_bool eq_dec a l); simpl. left; auto.\n    simpl in H. right; auto.\n  - destruct H.\n    + rewrite H. simpl; intro C; inversion C.\n    + intro C. destruct (nodupb eq_dec l). contradiction.\n      rewrite andb_false_r in C. inversion C.\nQed. \n\nLemma in_exists: forall {A: Type} {x: A} {l: list A},\n  In x l <-> exists l1 l2, l = l1 ++ [x] ++ l2.\nProof.\n  intros; induction l; simpl; split; intros.\n  - destruct H.\n  - destruct H as [l1 [l2 Hl]]. destruct l1; inversion Hl.\n  - destruct H; subst.\n    + exists nil. exists l. reflexivity.\n    + apply IHl in H. destruct H as [l1 [l2 Hl]]; rewrite Hl.\n      exists (a :: l1). exists l2. reflexivity.\n  - destruct H as [l1 [l2 Hl]]; subst.\n    destruct l1.\n    + inversion Hl; subst. left; auto.\n    + simpl in Hl. inversion Hl; subst.\n      right. apply IHl. exists l1. exists l2. reflexivity.\nQed.\n\nLemma not_NoDup: forall {A: Type}\n(eq_dec: forall (x y : A), {x = y} + {x <> y})\n  (l: list A),\n  ~NoDup l <->\n  exists x l1 l2 l3,\n    l = l1 ++ [x] ++ l2 ++ [x] ++ l3.\nProof.\n  intros A eq_dec l; induction l; simpl; intros; split; intros.\n  - exfalso. apply H. constructor.\n  - intro C. destruct H as [x [l1 [l2 [l3 Hl]]]]; subst.\n    destruct l1; inversion Hl.\n  - apply (NoDup_not_cons eq_dec) in H.\n    destruct H.\n    + exists a. exists nil.\n      apply in_exists in H. destruct H as [l1 [l2 Hl]].\n      rewrite Hl. exists l1. exists l2. reflexivity.\n    + apply IHl in H. destruct H as [x [l1 [l2 [l3 Hl]]]].\n      rewrite Hl. exists x. exists (a :: l1). exists l2. exists l3.\n      reflexivity.\n  - rewrite NoDup_not_cons by apply eq_dec.\n    destruct H as [x [l1 [l2 [l3 Hl]]]]. destruct l1.\n    + inversion Hl; subst. left. apply in_or_app. right. left; auto.\n    + inversion Hl; subst.\n      right. apply IHl. exists x. exists l1. exists l2. exists l3.\n      reflexivity.\nQed.\n\n(*Just need these*)\n\nLemma NoDup_concat: forall {A: Type}\n  (eq_dec: forall (x y: A), {x = y} + {x <> y})\n{l: list (list A)} \n  {l1: list A},\n  NoDup (concat l) ->\n  In l1 l ->\n  NoDup l1.\nProof.\n  intros A eq_dec; induction l; intros; simpl; auto.\n  - destruct H0. \n  - simpl in H. simpl in H0.\n    rewrite NoDup_app_iff in H.\n    destruct H as [Hna [Hnc [Hina Hinc]]].\n    destruct H0; subst.\n    + assumption.\n    + apply IHl; assumption.\nQed.\n\nLemma NoDup_concat': forall {A: Type}\n  (eq_dec: forall (x y: A), {x = y} + {x <> y})\n{l: list (list A)} \n  {l1: list (list A)} {l2: list A},\n  NoDup (concat l) ->\n  In (concat l1) l ->\n  In l2 l1 ->\n  NoDup l2.\nProof.\n  intros.\n  assert (NoDup (concat l1)). apply (NoDup_concat eq_dec H H0).\n  apply (NoDup_concat eq_dec H2 H1).\nQed.\n\n(*awful hack - TODO fix*)\nDefinition mut_in_ctx' := mut_in_ctx.\n\nLemma constrs_nodups: forall {m: mut_adt} {constrs: ne_list funsym}\n  {m_in: mut_in_ctx m gamma}\n  (Hin: In constrs (map adt_constrs (typs m))),\n  nodupb funsym_eq_dec (ne_list_to_list constrs).\nProof.\n  intros.\n  apply (reflect_iff _ _ (nodup_NoDup _ _)).\n  rewrite in_map_iff in Hin. destruct Hin as [a [Ha Hina]]; subst.\n  assert (m_in': mut_in_ctx' m gamma) by auto.\n  valid_context_tac.\n  unfold wf_context in Hwf. destruct Hwf as [_ [_ [_ [_ [_ [Hnodup _]]]]]].\n  clear Hadts. unfold funsyms_of_context in Hnodup.\n  assert (exists l l', In l (map funsyms_of_def gamma) /\\ l = concat l' /\\\n    In (ne_list_to_list (adt_constrs a)) l'). {\n      unfold funsyms_of_def. unfold adt_constrs.\n      exists (concat\n      (map\n         (fun a0 : alg_datatype =>\n          match a0 with\n          | alg_def _ fs => ne_list_to_list fs\n          end) (typs m))).\n    exists ((map\n    (fun a0 : alg_datatype =>\n     match a0 with\n     | alg_def _ fs => ne_list_to_list fs\n     end) (typs m))).\n      split; auto.\n      - rewrite in_map_iff. exists (datatype_def m).\n        split; auto. apply mut_in_ctx_eq2; auto.\n      - split; auto. rewrite in_map_iff.\n        exists a. split; auto. destruct a; reflexivity.\n  }\n  destruct H3 as [l [l' [Hinl [Hl Hinl']]]]; subst.\n  eapply NoDup_concat'. apply funsym_eq_dec. \n  3: apply Hinl'. 2: apply Hinl.\n  apply Hnodup.\nQed.\n\n(*We want to know: when we have a valid context, a list of\n  patterns in a valid match is nonempty*)\n\n  (*TODO: we need to do this when we have a valid context, so that we\n    know that mut adt is nonempty\n    TODO: change to NOT datatypes_of_context*)\n(*\nLemma valid_pattern_match_nil: forall s gamma,\n  valid_context s gamma ->\n  ~ valid_pattern_match s gamma nil.\nProof.\n  clear gamma_valid s gamma.\n  intros s gamma gamma_valid. intro C. unfold valid_pattern_match in C.\n  destruct C as [a [args [Hlen [Hina Hex]]]].\n  assert (adt_inhab s gamma a). {\n    unfold adt_in_ctx in Hina. destruct Hina as [m Hm].\n    unfold adt_mut_in_ctx, adt_in_mut, mut_in_ctx in Hm.\n    valid_context_tac.\n  }\n  assert (Hinhab:=H).\n  unfold adt_inhab in H. destruct a. \n  apply adt_inhab_inhab with (vs:=args) in Hinhab; auto.\n  2 : { apply gamma_valid. }\n  destruct Hinhab as [tm Htm].\n  specialize (Hex tm Htm). destruct Hex as [p [[] _]].\nQed.*)\n\nLemma pat_has_type_valid: forall p ty,\n  pattern_has_type s p ty ->\n  valid_type s ty.\nProof.\n  intros. induction H; try assumption; auto.\n  apply valid_type_subst; auto.\nQed.\n\n(*If a term has a type, that type is well-formed. We need the \n  [valid_pat_fmla] or else we could have an empty pattern*)\nLemma has_type_valid: forall (*s gamma*) t ty,\n  (*well_typed_term s gamma t ty ->*)\n  term_has_type s t ty ->\n  valid_type s ty.\nProof.\n  intros. induction H; try solve[constructor]; try assumption; auto.\n  apply valid_type_subst; assumption.\n  destruct ps. inversion H3.\n  apply (H2 p); auto. left; auto. \nQed.\n(*\n  - inversion H0; subst. auto.\n  - inversion H0; subst; auto.\n  - inversion H0; subst.\n    destruct ps.\n    simpl in H6. exfalso. apply (valid_pattern_match_nil _ _ gamma_valid H6).\n    simpl in H8. assert (valid_pat_tm s gamma (snd p)).\n      apply H8. left. auto.\n    apply (H3 p). left; auto. assumption. apply H8; left; auto.\nQed.*)\n\n(*TODO: move*)\nLemma in_bool_ne_In {A: Set} (eq_dec: forall (x y : A), {x = y} + {x <> y})\n  (x: A) (l: ne_list A):\n  in_bool_ne eq_dec x l ->\n  In x (ne_list_to_list l).\nProof.\n  rewrite in_bool_ne_equiv. intros.\n  apply (in_bool_In _ _ _ H).\nQed.\n  \n(*All constrs are in [funsym_of_context gamma]*)\nLemma constrs_in_funsyms: forall {gamma c a m},\n  mut_in_ctx m gamma ->\n  adt_in_mut a m ->\n  constr_in_adt c a ->\n  In c (funsyms_of_context gamma).\nProof.\n  clear.\n  intros gamma c a m. unfold adt_in_mut, constr_in_adt.\n  intros m_in a_in c_in; induction gamma; simpl. inversion m_in.\n  simpl in m_in. unfold funsyms_of_context in *. simpl.\n  rewrite mut_in_ctx_eq2 in m_in.\n  destruct m_in as [Ha0 | m_in]; [| apply in_or_app; right; auto].\n  subst. apply in_or_app; left. simpl.\n  rewrite in_concat. exists (ne_list_to_list (adt_constrs a)).\n  rewrite in_map_iff. split; [| eapply in_bool_ne_In; apply c_in].\n  exists a. split; auto. destruct a. reflexivity.\n  apply (in_bool_In _ _ _ a_in).\n  apply IHc0. apply mut_in_ctx_eq2; auto.\nQed. \n\n(*All constr args types are valid*)\nLemma constr_ret_valid: forall {c a m},\n  mut_in_ctx m gamma ->\n  adt_in_mut a m ->\n  constr_in_adt c a ->\n  forall x, In x (s_args c) -> valid_type s x.\nProof.\n  intros c a m m_in a_in c_in x Hinx.\n  unfold valid_context in gamma_valid.\n  unfold wf_context in gamma_valid.\n  destruct gamma_valid as [[Hsig [_ [Hfuns _]]] _].\n  clear gamma_valid.\n  unfold wf_sig in Hsig.\n  destruct Hsig as [Hsig _].\n  rewrite Forall_forall in Hsig, Hfuns.\n  assert (Hinsig: In c (sig_f s)). {\n    apply Hfuns. apply (constrs_in_funsyms m_in a_in c_in).\n  }\n  clear Hfuns. specialize (Hsig _ Hinsig).\n  rewrite Forall_forall in Hsig. apply Hsig. right; auto.\nQed. \n\nLemma adt_in_mut_alt {m: mut_adt} {a: alg_datatype}:\n  reflect (In (adt_name a, ne_list_to_list (adt_constrs a)) \n  (datatypes_of_def (datatype_def m))) (adt_in_mut a m).\nProof.\n  unfold adt_in_mut.\n  destruct m. simpl. induction typs; simpl.\n  - apply ReflectF; auto.\n  - apply ssrbool.orPP; auto. destruct a0; simpl in *.\n    destruct (adt_dec a (alg_def t n)) eqn : Hadteq; simpl.\n    + apply ReflectT. subst. simpl. reflexivity.\n    + apply ReflectF. intro Ht. inversion Ht; subst.\n      apply ne_list_list_inj in H1. subst.\n      destruct a; simpl in n0; contradiction.\nQed.\n\n(*If m1 and m2 have an ADT name in common, they are equal*)\nLemma mut_adts_inj {m1 m2: mut_adt} {a1 a2: alg_datatype}:\n  mut_in_ctx m1 gamma ->\n  mut_in_ctx m2 gamma ->\n  adt_in_mut a1 m1 ->\n  adt_in_mut a2 m2 ->\n  adt_name a1 = adt_name a2 ->\n  m1 = m2.\nProof.\n  intros m_in1 m_in2 a_in1 a_in2 Heq.\n  destruct gamma_valid as [Hwf _].\n  unfold wf_context in Hwf.\n  destruct Hwf as [_ [_ [_ [_ [Hnodup _]]]]].\n  unfold typesyms_of_context, datatypes_of_context in Hnodup.\n  rewrite concat_map in Hnodup.\n  rewrite map_map in Hnodup.\n  rewrite NoDup_concat_iff in Hnodup.\n  destruct_all. clear H.\n  rewrite mut_in_ctx_eq2 in m_in1, m_in2.\n  destruct (In_nth _ _ (recursive_def nil) m_in1) as [i [Hi Hith]].\n  destruct (In_nth _ _ (recursive_def nil) m_in2) as [j [Hj Hjth]].\n  rewrite map_length in H0.\n  destruct (Nat.eq_dec i j). {\n    (*If i=j, easy*)\n    subst. rewrite Hith in Hjth.\n    inversion Hjth; auto.\n  }\n  specialize (H0 i j nil (adt_name a1) Hi Hj n).\n  exfalso. apply H0; clear H0.\n  rewrite !map_nth_inbound with(d2:=(recursive_def [])); auto.\n  rewrite Hith, Hjth.\n  split; rewrite in_map_iff;\n  [exists (adt_name a1, ne_list_to_list (adt_constrs a1))| \n   exists (adt_name a2, ne_list_to_list (adt_constrs a2))]; \n   split; auto; apply (ssrbool.elimT adt_in_mut_alt); auto.\nQed.\n\n(*TODO: have similar lemma in IndTypes but for finite version*)\nLemma adt_names_inj' {a1 a2: alg_datatype} {m: mut_adt}:\n  adt_in_mut a1 m ->\n  adt_in_mut a2 m ->\n  mut_in_ctx m gamma ->\n  adt_name a1 = adt_name a2 ->\n  a1 = a2.\nProof.\n  intros. assert (NoDup (map adt_name (typs m))) by\n    apply (adts_names_nodups H1). \n  apply (@NoDup_map_in _ _ _ _ a1 a2) in H3; auto.\n  apply (in_bool_In _ _ _ H).\n  apply (in_bool_In _ _ _ H0).\nQed.\n\n(*\nDefinition constrs_ne: forall {l: list (typesym * list funsym)}\n  (Hin: In l (mutrec_datatypes_of_context gamma)),\n  forallb (fun b => negb (null b)) (map snd l).\nProof.\n  intros. apply forallb_forall. intros.\n  valid_context_tac.\n  unfold adt_inhab in H1.\n  valid_context_tac. simpl.\nQed.*)\n\nEnd ValidContextLemmas.", "meta": {"author": "joscoh", "repo": "why3-semantics", "sha": "d4d1801e43728a599ffd5442e3b6701797e61774", "save_path": "github-repos/coq/joscoh-why3-semantics", "path": "github-repos/coq/joscoh-why3-semantics/why3-semantics-d4d1801e43728a599ffd5442e3b6701797e61774/proofs/core/Typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7272913519474618}}
{"text": "Require Import Arith Bool List Omega.\nRequire Import Cpdt.CpdtTactics Cpdt.MoreSpecif.\nRequire Coq.extraction.Extraction.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n(* Chapter 8. More Dependent Types *)\n\n(* 8.1 Length-Indexed Lists *)\n\nSection ilist.\n  Variable A : Set.\n\n  Inductive ilist : nat -> Set :=\n  | Nil : ilist O\n  | Cons : forall n, A -> ilist n -> ilist (S n).\n\n  (* We may apply ilist to any natural number, even natural numbers that are\n     only known at runtime.  It is this breaking of the _phase distinction_\n     that characterizes ilist as _dependently typed_. *)\n\n  (* Old version of Coq rejects this *)\n  Fixpoint app n1 (ls1 : ilist n1) n2 (ls2 : ilist n2) : ilist (n1 + n2) :=\n    match ls1 with\n      | Nil => ls2\n      | Cons _ x ls1' => Cons x (app ls1' ls2)\n    end.\n\n  (* return: expresses dependency of the match result type on the _value_\n             being matched\n     in:     expresses dependency of the match result type on the _type_\n             being matched *)\n  Fixpoint app' n1 (ls1 : ilist n1) n2 (ls2 : ilist n2) : ilist (n1 + n2) :=\n    match ls1 in (ilist n1) return (ilist (n1 + n2)) with\n      | Nil => ls2\n      | Cons _ x ls1' => Cons x (app' ls1' ls2)\n          (* ^ parameters! *)\n    end.\n\n  (* app can be typed in \"stratified type systems\"\n     ... the length indices can be treated as compile-time-only type information\n         whereas the \"list\" type information cannot *)\n\n  (* example where length indices cannot be erased in the runtime *)\n  Fixpoint inject (ls : list A) : ilist (length ls) :=\n    match ls with\n      | nil => Nil\n      | h :: t => Cons h (inject t)\n    end.\n\n  Fixpoint unject n (ls : ilist n) : list A :=\n    match ls with\n      | Nil => nil\n      | Cons _ h t => h :: unject t\n    end.\n\n  Theorem inject_inverse : forall ls, unject (inject ls) = ls.\n  Proof.\n    induction ls.\n    - reflexivity.\n    - simpl. rewrite IHls. reflexivity.\n  Qed.\n\n  (* unsuccessful attempt to write \"hd\" function ...\n       Definition hd n (ls : ilist (S n)) : A :=\n         match ls with\n           | Nil => ???\n           | Cons _ h _ => h\n         end.\n\n     or...\n\n       Definition hd n (ls : ilist (S n)) : A :=\n         match ls with  (* inexhaustive pattern match *)\n           | Cons _ h _ => h\n         end.\n   *)\n\n  (* Actually the recent Coq supports inexhaustive match iff the return type\n     is correct. Let's try to use this...\n\n      Definition hd n (ls : ilist (S n)) : A :=\n        match ls in (ilist (S n)) with\n          | Cons _ h _ => h\n        end.\n\n      ... which fails, because S (in [ilist (S n)]) is not variable!\n          No non-variables are allowed in [in] clauses.\n          (Continues to next chapters)\n   *)\n\n  (* Our final definition *)\n  Definition hd' n (ls : ilist n) :=\n    match ls in (ilist n) return (match n with O => unit | S _ => A end) with\n      | Nil => tt\n      | Cons _ h _ => h\n    end.\n\n  (* This passes because the index of [ls] is known to be nonzero *)\n  Definition hd n (ls : ilist (S n)) : A := hd' ls.\nEnd ilist.\n\n\n(* 8.2 The One Rule of Dependent Pattern Matching in Coq *)\n\n(** The rest of this chapter will demonstrate a few other elegant applications of dependent types in Coq.  Readers encountering such ideas for the first time often feel overwhelmed, concluding that there is some magic at work whereby Coq sometimes solves the halting problem for the programmer and sometimes does not, applying automated program understanding in a way far beyond what is found in conventional languages.  The point of this section is to cut off that sort of thinking right now!  Dependent type-checking in Coq follows just a few algorithmic rules.  Chapters 10 and 12 introduce many of those rules more formally, and the main additional rule is centered on%\\index{dependent pattern matching}% _dependent pattern matching_ of the kind we met in the previous section.\n\nA dependent pattern match is a [match] expression where the type of the overall [match] is a function of the value and/or the type of the%\\index{discriminee}% _discriminee_, the value being matched on.  In other words, the [match] type _depends_ on the discriminee.\n\nWhen exactly will Coq accept a dependent pattern match as well-typed?  Some other dependently typed languages employ fancy decision procedures to determine when programs satisfy their very expressive types.  The situation in Coq is just the opposite.  Only very straightforward symbolic rules are applied.  Such a design choice has its drawbacks, as it forces programmers to do more work to convince the type checker of program validity.  However, the great advantage of a simple type checking algorithm is that its action on _invalid_ programs is easier to understand!\n\nWe come now to the one rule of dependent pattern matching in Coq.  A general dependent pattern match assumes this form (with unnecessary parentheses included to make the syntax easier to parse):\n[[\n  match E as y in (T x1 ... xn) return U with\n    | C z1 ... zm => B\n    | ...\n  end\n]]\n\nThe discriminee is a term [E], a value in some inductive type family [T], which takes [n] arguments.  An %\\index{as clause}%[as] clause binds the name [y] to refer to the discriminee [E].  An %\\index{in clause}%[in] clause binds an explicit name [xi] for the [i]th argument passed to [T] in the type of [E].\n\nWe bind these new variables [y] and [xi] so that they may be referred to in [U], a type given in the %\\index{return clause}%[return] clause.  The overall type of the [match] will be [U], with [E] substituted for [y], and with each [xi] substituted by the actual argument appearing in that position within [E]'s type.\n\nIn general, each case of a [match] may have a pattern built up in several layers from the constructors of various inductive type families.  To keep this exposition simple, we will focus on patterns that are just single applications of inductive type constructors to lists of variables.  Coq actually compiles the more general kind of pattern matching into this more restricted kind automatically, so understanding the typing of [match] requires understanding the typing of [match]es lowered to match one constructor at a time.\n\nThe last piece of the typing rule tells how to type-check a [match] case.  A generic constructor application [C z1 ... zm] has some type [T x1' ... xn'], an application of the type family used in [E]'s type, probably with occurrences of the [zi] variables.  From here, a simple recipe determines what type we will require for the case body [B].  The type of [B] should be [U] with the following two substitutions applied: we replace [y] (the [as] clause variable) with [C z1 ... zm], and we replace each [xi] (the [in] clause variables) with [xi'].  In other words, we specialize the result type based on what we learn based on which pattern has matched the discriminee.\n\nThis is an exhaustive description of the ways to specify how to take advantage of which pattern has matched!  No other mechanisms come into play.  For instance, there is no way to specify that the types of certain free variables should be refined based on which pattern has matched.  In the rest of the book, we will learn design patterns for achieving similar effects, where each technique leads to an encoding only in terms of [in], [as], and [return] clauses.\n\nA few details have been omitted above.  In Chapter 3, we learned that inductive type families may have both%\\index{parameters}% _parameters_ and regular arguments.  Within an [in] clause, a parameter position must have the wildcard [_] written, instead of a variable.  (In general, Coq uses wildcard [_]'s either to indicate pattern variables that will not be mentioned again or to indicate positions where we would like type inference to infer the appropriate terms.)  Furthermore, recent Coq versions are adding more and more heuristics to infer dependent [match] annotations in certain conditions.  The general annotation inference problem is undecidable, so there will always be serious limitations on how much work these heuristics can do.  When in doubt about why a particular dependent [match] is failing to type-check, add an explicit [return] annotation!  At that point, the mechanical rule sketched in this section will provide a complete account of \"what the type checker is thinking.\"  Be sure to avoid the common pitfall of writing a [return] annotation that does not mention any variables bound by [in] or [as]; such a [match] will never refine typing requirements based on which pattern has matched.  (One simple exception to this rule is that, when the discriminee is a variable, that same variable may be treated as if it were repeated as an [as] clause.) *)\n\n\n(** * A Tagless Interpreter *)\n\n(** A favorite example for motivating the power of functional programming is implementation of a simple expression language interpreter.  In ML and Haskell, such interpreters are often implemented using an algebraic datatype of values, where at many points it is checked that a value was built with the right constructor of the value type.  With dependent types, we can implement a%\\index{tagless interpreters}% _tagless_ interpreter that both removes this source of runtime inefficiency and gives us more confidence that our implementation is correct. *)\n\nInductive type : Set :=\n| Nat : type\n| Bool : type\n| Prod : type -> type -> type.\n\nInductive exp : type -> Set :=\n| NConst : nat -> exp Nat\n| Plus : exp Nat -> exp Nat -> exp Nat\n| Eq : exp Nat -> exp Nat -> exp Bool\n\n| BConst : bool -> exp Bool\n| And : exp Bool -> exp Bool -> exp Bool\n| If : forall t, exp Bool -> exp t -> exp t -> exp t\n\n| Pair : forall t1 t2, exp t1 -> exp t2 -> exp (Prod t1 t2)\n| Fst : forall t1 t2, exp (Prod t1 t2) -> exp t1\n| Snd : forall t1 t2, exp (Prod t1 t2) -> exp t2.\n\n(** We have a standard algebraic datatype [type], defining a type language of naturals, Booleans, and product (pair) types.  Then we have the indexed inductive type [exp], where the argument to [exp] tells us the encoded type of an expression.  In effect, we are defining the typing rules for expressions simultaneously with the syntax.\n\n   We can give types and expressions semantics in a new style, based critically on the chance for _type-level computation_. *)\n\nFixpoint typeDenote (t : type) : Set :=\n  match t with\n    | Nat => nat\n    | Bool => bool\n    | Prod t1 t2 => typeDenote t1 * typeDenote t2\n  end%type.\n\n(** The [typeDenote] function compiles types of our object language into \"native\" Coq types.  It is deceptively easy to implement.  The only new thing we see is the [%]%\\coqdocvar{%#<tt>#type#</tt>#%}% annotation, which tells Coq to parse the [match] expression using the notations associated with types.  Without this annotation, the [*] would be interpreted as multiplication on naturals, rather than as the product type constructor.  The token %\\coqdocvar{%#<tt>#type#</tt>#%}% is one example of an identifier bound to a%\\index{notation scope delimiter}% _notation scope delimiter_.  In this book, we will not go into more detail on notation scopes, but the Coq manual can be consulted for more information.\n\n   We can define a function [expDenote] that is typed in terms of [typeDenote]. *)\n\nFixpoint expDenote t (e : exp t) : typeDenote t :=\n  match e with\n    | NConst n => n\n    | Plus e1 e2 => expDenote e1 + expDenote e2\n    | Eq e1 e2 => if eq_nat_dec (expDenote e1) (expDenote e2) then true else false\n\n    | BConst b => b\n    | And e1 e2 => expDenote e1 && expDenote e2\n    | If _ e' e1 e2 => if expDenote e' then expDenote e1 else expDenote e2\n\n    | Pair _ _ e1 e2 => (expDenote e1, expDenote e2)\n    | Fst _ _ e' => fst (expDenote e')\n    | Snd _ _ e' => snd (expDenote e')\n  end.\n\n(* begin hide *)\n(* begin thide *)\nDefinition sumboool := sumbool.\n(* end thide *)\n(* end hide *)\n\n(** Despite the fancy type, the function definition is routine.  In fact, it is less complicated than what we would write in ML or Haskell 98, since we do not need to worry about pushing final values in and out of an algebraic datatype.  The only unusual thing is the use of an expression of the form [if E then true else false] in the [Eq] case.  Remember that [eq_nat_dec] has a rich dependent type, rather than a simple Boolean type.  Coq's native [if] is overloaded to work on a test of any two-constructor type, so we can use [if] to build a simple Boolean from the [sumbool] that [eq_nat_dec] returns.\n\n   We can implement our old favorite, a constant folding function, and prove it correct.  It will be useful to write a function [pairOut] that checks if an [exp] of [Prod] type is a pair, returning its two components if so.  Unsurprisingly, a first attempt leads to a type error.\n[[\nDefinition pairOut t1 t2 (e : exp (Prod t1 t2)) : option (exp t1 * exp t2) :=\n  match e in (exp (Prod t1 t2)) return option (exp t1 * exp t2) with\n    | Pair _ _ e1 e2 => Some (e1, e2)\n    | _ => None\n  end.\n]]\n\n<<\nError: The reference t2 was not found in the current environment\n>>\n\nWe run again into the problem of not being able to specify non-variable arguments in [in] clauses.  The problem would just be hopeless without a use of an [in] clause, though, since the result type of the [match] depends on an argument to [exp].  Our solution will be to use a more general type, as we did for [hd].  First, we define a type-valued function to use in assigning a type to [pairOut]. *)\n\n(* EX: Define a function [pairOut : forall t1 t2, exp (Prod t1 t2) -> option (exp t1 * exp t2)] *)\n\n(* begin thide *)\nDefinition pairOutType (t : type) := option (match t with\n                                               | Prod t1 t2 => exp t1 * exp t2\n                                               | _ => unit\n                                             end).\n\n(** When passed a type that is a product, [pairOutType] returns our final desired type.  On any other input type, [pairOutType] returns the harmless [option unit], since we do not care about extracting components of non-pairs.  Now [pairOut] is easy to write. *)\n\nDefinition pairOut t (e : exp t) :=\n  match e in (exp t) return (pairOutType t) with\n    | Pair _ _ e1 e2 => Some (e1, e2)\n    | _ => None\n  end.\n(* end thide *)\n\n(** With [pairOut] available, we can write [cfold] in a straightforward way.  There are really no surprises beyond that Coq verifies that this code has such an expressive type, given the small annotation burden.  In some places, we see that Coq's [match] annotation inference is too smart for its own good, and we have to turn that inference off with explicit [return] clauses. *)\n\nFixpoint cfold t (e : exp t) : exp t :=\n  match e with\n    | NConst n => NConst n\n    | Plus e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold e2 in\n      match e1', e2' return exp Nat with\n        | NConst n1, NConst n2 => NConst (n1 + n2)\n        | _, _ => Plus e1' e2'\n      end\n    | Eq e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold e2 in\n      match e1', e2' return exp Bool with\n        | NConst n1, NConst n2 => BConst (if eq_nat_dec n1 n2 then true else false)\n        | _, _ => Eq e1' e2'\n      end\n\n    | BConst b => BConst b\n    | And e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold e2 in\n      match e1', e2' return exp Bool with\n        | BConst b1, BConst b2 => BConst (b1 && b2)\n        | _, _ => And e1' e2'\n      end\n    | If _ e e1 e2 =>\n      let e' := cfold e in\n      match e' with\n        | BConst true => cfold e1\n        | BConst false => cfold e2\n        | _ => If e' (cfold e1) (cfold e2)\n      end\n\n    | Pair _ _ e1 e2 => Pair (cfold e1) (cfold e2)\n    | Fst _ _ e =>\n      let e' := cfold e in\n      match pairOut e' with\n        | Some p => fst p\n        | None => Fst e'\n      end\n    | Snd _ _ e =>\n      let e' := cfold e in\n      match pairOut e' with\n        | Some p => snd p\n        | None => Snd e'\n      end\n  end.\n\n(** The correctness theorem for [cfold] turns out to be easy to prove, once we get over one serious hurdle. *)\n\nTheorem cfold_correct : forall t (e : exp t), expDenote e = expDenote (cfold e).\n(* begin thide *)\n  induction e; crush.\n\n(** The first remaining subgoal is:\n\n   [[\n  expDenote (cfold e1) + expDenote (cfold e2) =\n   expDenote\n     match cfold e1 with\n     | NConst n1 =>\n         match cfold e2 with\n         | NConst n2 => NConst (n1 + n2)\n         | Plus _ _ => Plus (cfold e1) (cfold e2)\n         | Eq _ _ => Plus (cfold e1) (cfold e2)\n         | BConst _ => Plus (cfold e1) (cfold e2)\n         | And _ _ => Plus (cfold e1) (cfold e2)\n         | If _ _ _ _ => Plus (cfold e1) (cfold e2)\n         | Pair _ _ _ _ => Plus (cfold e1) (cfold e2)\n         | Fst _ _ _ => Plus (cfold e1) (cfold e2)\n         | Snd _ _ _ => Plus (cfold e1) (cfold e2)\n         end\n     | Plus _ _ => Plus (cfold e1) (cfold e2)\n     | Eq _ _ => Plus (cfold e1) (cfold e2)\n     | BConst _ => Plus (cfold e1) (cfold e2)\n     | And _ _ => Plus (cfold e1) (cfold e2)\n     | If _ _ _ _ => Plus (cfold e1) (cfold e2)\n     | Pair _ _ _ _ => Plus (cfold e1) (cfold e2)\n     | Fst _ _ _ => Plus (cfold e1) (cfold e2)\n     | Snd _ _ _ => Plus (cfold e1) (cfold e2)\n     end\n \n     ]]\n\n     We would like to do a case analysis on [cfold e1], and we attempt to do so in the way that has worked so far.\n     [[\n  destruct (cfold e1).\n]]\n\n<<\nUser error: e1 is used in hypothesis e\n>>\n\n    Coq gives us another cryptic error message.  Like so many others, this one basically means that Coq is not able to build some proof about dependent types.  It is hard to generate helpful and specific error messages for problems like this, since that would require some kind of understanding of the dependency structure of a piece of code.  We will encounter many examples of case-specific tricks for recovering from errors like this one.\n\n    For our current proof, we can use a tactic [dep_destruct]%\\index{tactics!dep\\_destruct}% defined in the book's [CpdtTactics] module.  General elimination/inversion of dependently typed hypotheses is undecidable, as witnessed by a simple reduction from the known-undecidable problem of higher-order unification, which has come up a few times already.  The tactic [dep_destruct] makes a best effort to handle some common cases, relying upon the more primitive %\\index{tactics!dependent destruction}%[dependent destruction] tactic that comes with Coq.  In a future chapter, we will learn about the explicit manipulation of equality proofs that is behind [dependent destruction]'s implementation, but for now, we treat it as a useful black box.  (In Chapter 12, we will also see how [dependent destruction] forces us to make a larger philosophical commitment about our logic than we might like, and we will see some workarounds.) *)\n  \n  dep_destruct (cfold e1).\n\n  (** This successfully breaks the subgoal into 5 new subgoals, one for each constructor of [exp] that could produce an [exp Nat].  Note that [dep_destruct] is successful in ruling out the other cases automatically, in effect automating some of the work that we have done manually in implementing functions like [hd] and [pairOut].\n\n     This is the only new trick we need to learn to complete the proof.  We can back up and give a short, automated proof (which again is safe to skip and uses Ltac features not introduced yet). *)\n\n  Restart.\n\n  induction e; crush;\n    repeat (match goal with\n              | [ |- context[match cfold ?E with NConst _ => _ | _ => _ end] ] =>\n                dep_destruct (cfold E)\n              | [ |- context[match pairOut (cfold ?E) with Some _ => _\n                               | None => _ end] ] =>\n                dep_destruct (cfold E)\n              | [ |- (if ?E then _ else _) = _ ] => destruct E\n            end; crush).\nQed.\n(* end thide *)\n\n(** With this example, we get a first taste of how to build automated proofs that adapt automatically to changes in function definitions. *)\n\n\n(** * Dependently Typed Red-Black Trees *)\n\n(** Red-black trees are a favorite purely functional data structure with an interesting invariant.  We can use dependent types to guarantee that operations on red-black trees preserve the invariant.  For simplicity, we specialize our red-black trees to represent sets of [nat]s. *)\n\nInductive color : Set := Red | Black.\n\nInductive rbtree : color -> nat -> Set :=\n| Leaf : rbtree Black 0\n| RedNode : forall n, rbtree Black n -> nat -> rbtree Black n -> rbtree Red n\n| BlackNode : forall c1 c2 n, rbtree c1 n -> nat -> rbtree c2 n -> rbtree Black (S n).\n\n(** A value of type [rbtree c d] is a red-black tree whose root has color [c] and that has black depth [d].  The latter property means that there are exactly [d] black-colored nodes on any path from the root to a leaf. *)\n\n(** At first, it can be unclear that this choice of type indices tracks any useful property.  To convince ourselves, we will prove that every red-black tree is balanced.  We will phrase our theorem in terms of a depth calculating function that ignores the extra information in the types.  It will be useful to parameterize this function over a combining operation, so that we can re-use the same code to calculate the minimum or maximum height among all paths from root to leaf. *)\n\n(* EX: Prove that every [rbtree] is balanced. *)\n\n(* begin thide *)\nRequire Import Max Min.\n\nSection depth.\n  Variable f : nat -> nat -> nat.\n\n  Fixpoint depth c n (t : rbtree c n) : nat :=\n    match t with\n      | Leaf => 0\n      | RedNode _ t1 _ t2 => S (f (depth t1) (depth t2))\n      | BlackNode _ _ _ t1 _ t2 => S (f (depth t1) (depth t2))\n    end.\nEnd depth.\n\n(** Our proof of balanced-ness decomposes naturally into a lower bound and an upper bound.  We prove the lower bound first.  Unsurprisingly, a tree's black depth provides such a bound on the minimum path length.  We use the richly typed procedure [min_dec] to do case analysis on whether [min X Y] equals [X] or [Y]. *)\n\nCheck min_dec.\n(** %\\vspace{-.15in}% [[\nmin_dec\n     : forall n m : nat, {min n m = n} + {min n m = m}\n   ]]\n   *)\n\nTheorem depth_min : forall c n (t : rbtree c n), depth min t >= n.\n  induction t; crush;\n    match goal with\n      | [ |- context[min ?X ?Y] ] => destruct (min_dec X Y)\n    end; crush.\nQed.\n\n(** There is an analogous upper-bound theorem based on black depth.  Unfortunately, a symmetric proof script does not suffice to establish it. *)\n\nTheorem depth_max : forall c n (t : rbtree c n), depth max t <= 2 * n + 1.\n  induction t; crush;\n    match goal with\n      | [ |- context[max ?X ?Y] ] => destruct (max_dec X Y)\n    end; crush.\n\n(** Two subgoals remain.  One of them is: [[\n  n : nat\n  t1 : rbtree Black n\n  n0 : nat\n  t2 : rbtree Black n\n  IHt1 : depth max t1 <= n + (n + 0) + 1\n  IHt2 : depth max t2 <= n + (n + 0) + 1\n  e : max (depth max t1) (depth max t2) = depth max t1\n  ============================\n   S (depth max t1) <= n + (n + 0) + 1\n \n   ]]\n\n   We see that [IHt1] is _almost_ the fact we need, but it is not quite strong enough.  We will need to strengthen our induction hypothesis to get the proof to go through. *)\n\nAbort.\n\n(** In particular, we prove a lemma that provides a stronger upper bound for trees with black root nodes.  We got stuck above in a case about a red root node.  Since red nodes have only black children, our IH strengthening will enable us to finish the proof. *)\n\nLemma depth_max' : forall c n (t : rbtree c n), match c with\n                                                  | Red => depth max t <= 2 * n + 1\n                                                  | Black => depth max t <= 2 * n\n                                                end.\n  induction t; crush;\n    match goal with\n      | [ |- context[max ?X ?Y] ] => destruct (max_dec X Y)\n    end; crush;\n    repeat (match goal with\n              | [ H : context[match ?C with Red => _ | Black => _ end] |- _ ] =>\n                destruct C\n            end; crush).\nQed.\n\n(** The original theorem follows easily from the lemma.  We use the tactic %\\index{tactics!generalize}%[generalize pf], which, when [pf] proves the proposition [P], changes the goal from [Q] to [P -> Q].  This transformation is useful because it makes the truth of [P] manifest syntactically, so that automation machinery can rely on [P], even if that machinery is not smart enough to establish [P] on its own. *)\n\nTheorem depth_max : forall c n (t : rbtree c n), depth max t <= 2 * n + 1.\n  intros; generalize (depth_max' t); destruct c; crush.\nQed.\n\n(** The final balance theorem establishes that the minimum and maximum path lengths of any tree are within a factor of two of each other. *)\n\nTheorem balanced : forall c n (t : rbtree c n), 2 * depth min t + 1 >= depth max t.\n  intros; generalize (depth_min t); generalize (depth_max t); crush.\nQed.\n(* end thide *)\n\n(** Now we are ready to implement an example operation on our trees, insertion.  Insertion can be thought of as breaking the tree invariants locally but then rebalancing.  In particular, in intermediate states we find red nodes that may have red children.  The type [rtree] captures the idea of such a node, continuing to track black depth as a type index. *)\n\nInductive rtree : nat -> Set :=\n| RedNode' : forall c1 c2 n, rbtree c1 n -> nat -> rbtree c2 n -> rtree n.\n\n(** Before starting to define [insert], we define predicates capturing when a data value is in the set represented by a normal or possibly invalid tree. *)\n\nSection present.\n  Variable x : nat.\n\n  Fixpoint present c n (t : rbtree c n) : Prop :=\n    match t with\n      | Leaf => False\n      | RedNode _ a y b => present a \\/ x = y \\/ present b\n      | BlackNode _ _ _ a y b => present a \\/ x = y \\/ present b\n    end.\n\n  Definition rpresent n (t : rtree n) : Prop :=\n    match t with\n      | RedNode' _ _ _ a y b => present a \\/ x = y \\/ present b\n    end.\nEnd present.\n\n(** Insertion relies on two balancing operations.  It will be useful to give types to these operations using a relative of the subset types from last chapter.  While subset types let us pair a value with a proof about that value, here we want to pair a value with another non-proof dependently typed value.  The %\\index{Gallina terms!sigT}%[sigT] type fills this role. *)\n\nLocate \"{ _ : _ & _ }\".\n(** %\\vspace{-.15in}%[[\nNotation            Scope     \n\"{ x : A  & P }\" := sigT (fun x : A => P)\n]]\n*)\n\nPrint sigT.\n(** %\\vspace{-.15in}%[[\nInductive sigT (A : Type) (P : A -> Type) : Type :=\n    existT : forall x : A, P x -> sigT P\n]]\n*)\n\n(** It will be helpful to define a concise notation for the constructor of [sigT]. *)\n\nNotation \"{< x >}\" := (existT _ _ x).\n\n(** Each balance function is used to construct a new tree whose keys include the keys of two input trees, as well as a new key.  One of the two input trees may violate the red-black alternation invariant (that is, it has an [rtree] type), while the other tree is known to be valid.  Crucially, the two input trees have the same black depth.\n\n   A balance operation may return a tree whose root is of either color.  Thus, we use a [sigT] type to package the result tree with the color of its root.  Here is the definition of the first balance operation, which applies when the possibly invalid [rtree] belongs to the left of the valid [rbtree].\n\n   A quick word of encouragement: After writing this code, even I do not understand the precise details of how balancing works!  I consulted Chris Okasaki's paper \"Red-Black Trees in a Functional Setting\" %\\cite{Okasaki} %and transcribed the code to use dependent types.  Luckily, the details are not so important here; types alone will tell us that insertion preserves balanced-ness, and we will prove that insertion produces trees containing the right keys.*)\n\nDefinition balance1 n (a : rtree n) (data : nat) c2 :=\n  match a in rtree n return rbtree c2 n\n    -> { c : color & rbtree c (S n) } with\n    | RedNode' _ c0 _ t1 y t2 =>\n      match t1 in rbtree c n return rbtree c0 n -> rbtree c2 n\n        -> { c : color & rbtree c (S n) } with\n        | RedNode _ a x b => fun c d =>\n          {<RedNode (BlackNode a x b) y (BlackNode c data d)>}\n        | t1' => fun t2 =>\n          match t2 in rbtree c n return rbtree Black n -> rbtree c2 n\n            -> { c : color & rbtree c (S n) } with\n            | RedNode _ b x c => fun a d =>\n              {<RedNode (BlackNode a y b) x (BlackNode c data d)>}\n            | b => fun a t => {<BlackNode (RedNode a y b) data t>}\n          end t1'\n      end t2\n  end.\n\n(** We apply a trick that I call the%\\index{convoy pattern}% _convoy pattern_.  Recall that [match] annotations only make it possible to describe a dependence of a [match] _result type_ on the discriminee.  There is no automatic refinement of the types of free variables.  However, it is possible to effect such a refinement by finding a way to encode free variable type dependencies in the [match] result type, so that a [return] clause can express the connection.\n\n   In particular, we can extend the [match] to return _functions over the free variables whose types we want to refine_.  In the case of [balance1], we only find ourselves wanting to refine the type of one tree variable at a time.  We match on one subtree of a node, and we want the type of the other subtree to be refined based on what we learn.  We indicate this with a [return] clause starting like [rbtree _ n -> ...], where [n] is bound in an [in] pattern.  Such a [match] expression is applied immediately to the \"old version\" of the variable to be refined, and the type checker is happy.\n\n   Here is the symmetric function [balance2], for cases where the possibly invalid tree appears on the right rather than on the left. *)\n\nDefinition balance2 n (a : rtree n) (data : nat) c2 :=\n  match a in rtree n return rbtree c2 n -> { c : color & rbtree c (S n) } with\n    | RedNode' _ c0 _ t1 z t2 =>\n      match t1 in rbtree c n return rbtree c0 n -> rbtree c2 n\n        -> { c : color & rbtree c (S n) } with\n        | RedNode _ b y c => fun d a =>\n          {<RedNode (BlackNode a data b) y (BlackNode c z d)>}\n        | t1' => fun t2 =>\n          match t2 in rbtree c n return rbtree Black n -> rbtree c2 n\n            -> { c : color & rbtree c (S n) } with\n            | RedNode _ c z' d => fun b a =>\n              {<RedNode (BlackNode a data b) z (BlackNode c z' d)>}\n            | b => fun a t => {<BlackNode t data (RedNode a z b)>}\n          end t1'\n      end t2\n  end.\n\n(** Now we are almost ready to get down to the business of writing an [insert] function.  First, we enter a section that declares a variable [x], for the key we want to insert. *)\n\nSection insert.\n  Variable x : nat.\n\n  (** Most of the work of insertion is done by a helper function [ins], whose return types are expressed using a type-level function [insResult]. *)\n\n  Definition insResult c n :=\n    match c with\n      | Red => rtree n\n      | Black => { c' : color & rbtree c' n }\n    end.\n\n  (** That is, inserting into a tree with root color [c] and black depth [n], the variety of tree we get out depends on [c].  If we started with a red root, then we get back a possibly invalid tree of depth [n].  If we started with a black root, we get back a valid tree of depth [n] with a root node of an arbitrary color.\n\n     Here is the definition of [ins].  Again, we do not want to dwell on the functional details. *)\n\n  Fixpoint ins c n (t : rbtree c n) : insResult c n :=\n    match t with\n      | Leaf => {< RedNode Leaf x Leaf >}\n      | RedNode _ a y b =>\n        if le_lt_dec x y\n          then RedNode' (projT2 (ins a)) y b\n          else RedNode' a y (projT2 (ins b))\n      | BlackNode c1 c2 _ a y b =>\n        if le_lt_dec x y\n          then\n            match c1 return insResult c1 _ -> _ with\n              | Red => fun ins_a => balance1 ins_a y b\n              | _ => fun ins_a => {< BlackNode (projT2 ins_a) y b >}\n            end (ins a)\n          else\n            match c2 return insResult c2 _ -> _ with\n              | Red => fun ins_b => balance2 ins_b y a\n              | _ => fun ins_b => {< BlackNode a y (projT2 ins_b) >}\n            end (ins b)\n    end.\n\n  (** The one new trick is a variation of the convoy pattern.  In each of the last two pattern matches, we want to take advantage of the typing connection between the trees [a] and [b].  We might %\\%naive%{}%ly apply the convoy pattern directly on [a] in the first [match] and on [b] in the second.  This satisfies the type checker per se, but it does not satisfy the termination checker.  Inside each [match], we would be calling [ins] recursively on a locally bound variable.  The termination checker is not smart enough to trace the dataflow into that variable, so the checker does not know that this recursive argument is smaller than the original argument.  We make this fact clearer by applying the convoy pattern on _the result of a recursive call_, rather than just on that call's argument.\n\n     Finally, we are in the home stretch of our effort to define [insert].  We just need a few more definitions of non-recursive functions.  First, we need to give the final characterization of [insert]'s return type.  Inserting into a red-rooted tree gives a black-rooted tree where black depth has increased, and inserting into a black-rooted tree gives a tree where black depth has stayed the same and where the root is an arbitrary color. *)\n\n  Definition insertResult c n :=\n    match c with\n      | Red => rbtree Black (S n)\n      | Black => { c' : color & rbtree c' n }\n    end.\n\n  (** A simple clean-up procedure translates [insResult]s into [insertResult]s. *)\n\n  Definition makeRbtree c n : insResult c n -> insertResult c n :=\n    match c with\n      | Red => fun r =>\n        match r with\n          | RedNode' _ _ _ a x b => BlackNode a x b\n        end\n      | Black => fun r => r\n    end.\n\n  (** We modify Coq's default choice of implicit arguments for [makeRbtree], so that we do not need to specify the [c] and [n] arguments explicitly in later calls. *)\n\n  Implicit Arguments makeRbtree [c n].\n\n  (** Finally, we define [insert] as a simple composition of [ins] and [makeRbtree]. *)\n\n  Definition insert c n (t : rbtree c n) : insertResult c n :=\n    makeRbtree (ins t).\n\n  (** As we noted earlier, the type of [insert] guarantees that it outputs balanced trees whose depths have not increased too much.  We also want to know that [insert] operates correctly on trees interpreted as finite sets, so we finish this section with a proof of that fact. *)\n\n  Section present.\n    Variable z : nat.\n\n    (** The variable [z] stands for an arbitrary key.  We will reason about [z]'s presence in particular trees.  As usual, outside the section the theorems we prove will quantify over all possible keys, giving us the facts we wanted.\n\n       We start by proving the correctness of the balance operations.  It is useful to define a custom tactic [present_balance] that encapsulates the reasoning common to the two proofs.  We use the keyword %\\index{Vernacular commands!Ltac}%[Ltac] to assign a name to a proof script.  This particular script just iterates between [crush] and identification of a tree that is being pattern-matched on and should be destructed. *)\n\n    Ltac present_balance :=\n      crush;\n      repeat (match goal with\n                | [ _ : context[match ?T with Leaf => _ | _ => _ end] |- _ ] =>\n                  dep_destruct T\n                | [ |- context[match ?T with Leaf => _ | _ => _ end] ] => dep_destruct T\n              end; crush).\n\n    (** The balance correctness theorems are simple first-order logic equivalences, where we use the function [projT2] to project the payload of a [sigT] value. *)\n\n    Lemma present_balance1 : forall n (a : rtree n) (y : nat) c2 (b : rbtree c2 n),\n      present z (projT2 (balance1 a y b))\n      <-> rpresent z a \\/ z = y \\/ present z b.\n      destruct a; present_balance.\n    Qed.\n\n    Lemma present_balance2 : forall n (a : rtree n) (y : nat) c2 (b : rbtree c2 n),\n      present z (projT2 (balance2 a y b))\n      <-> rpresent z a \\/ z = y \\/ present z b.\n      destruct a; present_balance.\n    Qed.\n\n    (** To state the theorem for [ins], it is useful to define a new type-level function, since [ins] returns different result types based on the type indices passed to it.  Recall that [x] is the section variable standing for the key we are inserting. *)\n\n    Definition present_insResult c n :=\n      match c return (rbtree c n -> insResult c n -> Prop) with\n        | Red => fun t r => rpresent z r <-> z = x \\/ present z t\n        | Black => fun t r => present z (projT2 r) <-> z = x \\/ present z t\n      end.\n\n    (** Now the statement and proof of the [ins] correctness theorem are straightforward, if verbose.  We proceed by induction on the structure of a tree, followed by finding case analysis opportunities on expressions we see being analyzed in [if] or [match] expressions.  After that, we pattern-match to find opportunities to use the theorems we proved about balancing.  Finally, we identify two variables that are asserted by some hypothesis to be equal, and we use that hypothesis to replace one variable with the other everywhere. *)\n\n    Theorem present_ins : forall c n (t : rbtree c n),\n      present_insResult t (ins t).\n      induction t; crush;\n        repeat (match goal with\n                  | [ _ : context[if ?E then _ else _] |- _ ] => destruct E\n                  | [ |- context[if ?E then _ else _] ] => destruct E\n                  | [ _ : context[match ?C with Red => _ | Black => _ end]\n                      |- _ ] => destruct C\n                end; crush);\n        try match goal with\n              | [ _ : context[balance1 ?A ?B ?C] |- _ ] =>\n                generalize (present_balance1 A B C)\n            end;\n        try match goal with\n              | [ _ : context[balance2 ?A ?B ?C] |- _ ] =>\n                generalize (present_balance2 A B C)\n            end;\n        try match goal with\n              | [ |- context[balance1 ?A ?B ?C] ] =>\n                generalize (present_balance1 A B C)\n            end;\n        try match goal with\n              | [ |- context[balance2 ?A ?B ?C] ] =>\n                generalize (present_balance2 A B C)\n            end;\n        crush;\n          match goal with\n            | [ z : nat, x : nat |- _ ] =>\n              match goal with\n                | [ H : z = x |- _ ] => rewrite H in *; clear H\n              end\n          end;\n          tauto.\n    Qed.\n\n    (** The hard work is done.  The most readable way to state correctness of [insert] involves splitting the property into two color-specific theorems.  We write a tactic to encapsulate the reasoning steps that work to establish both facts. *)\n\n    Ltac present_insert :=\n      unfold insert; intros n t; inversion t;\n        generalize (present_ins t); simpl;\n          dep_destruct (ins t); tauto.\n\n    Theorem present_insert_Red : forall n (t : rbtree Red n),\n      present z (insert t)\n      <-> (z = x \\/ present z t).\n      present_insert.\n    Qed.\n\n    Theorem present_insert_Black : forall n (t : rbtree Black n),\n      present z (projT2 (insert t))\n      <-> (z = x \\/ present z t).\n      present_insert.\n    Qed.\n  End present.\nEnd insert.\n\n(** We can generate executable OCaml code with the command %\\index{Vernacular commands!Recursive Extraction}%[Recursive Extraction insert], which also automatically outputs the OCaml versions of all of [insert]'s dependencies.  In our previous extractions, we wound up with clean OCaml code.  Here, we find uses of %\\index{Obj.magic}%<<Obj.magic>>, OCaml's unsafe cast operator for tweaking the apparent type of an expression in an arbitrary way.  Casts appear for this example because the return type of [insert] depends on the _value_ of the function's argument, a pattern that OCaml cannot handle.  Since Coq's type system is much more expressive than OCaml's, such casts are unavoidable in general.  Since the OCaml type-checker is no longer checking full safety of programs, we must rely on Coq's extractor to use casts only in provably safe ways. *)\n\n(* begin hide *)\nRecursive Extraction insert.\n(* end hide *)\n\n\n(** * A Certified Regular Expression Matcher *)\n\n(** Another interesting example is regular expressions with dependent types that express which predicates over strings particular regexps implement.  We can then assign a dependent type to a regular expression matching function, guaranteeing that it always decides the string property that we expect it to decide.\n\n   Before defining the syntax of expressions, it is helpful to define an inductive type capturing the meaning of the Kleene star.  That is, a string [s] matches regular expression [star e] if and only if [s] can be decomposed into a sequence of substrings that all match [e].  We use Coq's string support, which comes through a combination of the [String] library and some parsing notations built into Coq.  Operators like [++] and functions like [length] that we know from lists are defined again for strings.  Notation scopes help us control which versions we want to use in particular contexts.%\\index{Vernacular commands!Open Scope}% *)\n\nRequire Import Ascii String.\nOpen Scope string_scope.\n\nSection star.\n  Variable P : string -> Prop.\n\n  Inductive star : string -> Prop :=\n  | Empty : star \"\"\n  | Iter : forall s1 s2,\n    P s1\n    -> star s2\n    -> star (s1 ++ s2).\nEnd star.\n\n(** Now we can make our first attempt at defining a [regexp] type that is indexed by predicates on strings, such that the index of a [regexp] tells us which language (string predicate) it recognizes.  Here is a reasonable-looking definition that is restricted to constant characters and concatenation.  We use the constructor [String], which is the analogue of list cons for the type [string], where [\"\"] is like list nil.\n[[\nInductive regexp : (string -> Prop) -> Set :=\n| Char : forall ch : ascii,\n  regexp (fun s => s = String ch \"\")\n| Concat : forall (P1 P2 : string -> Prop) (r1 : regexp P1) (r2 : regexp P2),\n  regexp (fun s => exists s1, exists s2, s = s1 ++ s2 /\\ P1 s1 /\\ P2 s2).\n]]\n\n<<\nUser error: Large non-propositional inductive types must be in Type\n>>\n\nWhat is a %\\index{large inductive types}%large inductive type?  In Coq, it is an inductive type that has a constructor that quantifies over some type of type [Type].  We have not worked with [Type] very much to this point.  Every term of CIC has a type, including [Set] and [Prop], which are assigned type [Type].  The type [string -> Prop] from the failed definition also has type [Type].\n\nIt turns out that allowing large inductive types in [Set] leads to contradictions when combined with certain kinds of classical logic reasoning.  Thus, by default, such types are ruled out.  There is a simple fix for our [regexp] definition, which is to place our new type in [Type].  While fixing the problem, we also expand the list of constructors to cover the remaining regular expression operators. *)\n\nInductive regexp : (string -> Prop) -> Type :=\n| Char : forall ch : ascii,\n  regexp (fun s => s = String ch \"\")\n| Concat : forall P1 P2 (r1 : regexp P1) (r2 : regexp P2),\n  regexp (fun s => exists s1, exists s2, s = s1 ++ s2 /\\ P1 s1 /\\ P2 s2)\n| Or : forall P1 P2 (r1 : regexp P1) (r2 : regexp P2),\n  regexp (fun s => P1 s \\/ P2 s)\n| Star : forall P (r : regexp P),\n  regexp (star P).\n\n(** Many theorems about strings are useful for implementing a certified regexp matcher, and few of them are in the [String] library.  The book source includes statements, proofs, and hint commands for a handful of such omitted theorems.  Since they are orthogonal to our use of dependent types, we hide them in the rendered versions of this book. *)\n\n(* begin hide *)\nOpen Scope specif_scope.\n\nLemma length_emp : length \"\" <= 0.\n  crush.\nQed.\n\nLemma append_emp : forall s, s = \"\" ++ s.\n  crush.\nQed.\n\nLtac substring :=\n  crush;\n  repeat match goal with\n           | [ |- context[match ?N with O => _ | S _ => _ end] ] => destruct N; crush\n         end.\n\nLemma substring_le : forall s n m,\n  length (substring n m s) <= m.\n  induction s; substring.\nQed.\n\nLemma substring_all : forall s,\n  substring 0 (length s) s = s.\n  induction s; substring.\nQed.\n\nLemma substring_none : forall s n,\n  substring n 0 s = \"\".\n  induction s; substring.\nQed.\n\nHint Rewrite substring_all substring_none.\n\nLemma substring_split : forall s m,\n  substring 0 m s ++ substring m (length s - m) s = s.\n  induction s; substring.\nQed.\n\nLemma length_app1 : forall s1 s2,\n  length s1 <= length (s1 ++ s2).\n  induction s1; crush.\nQed.\n\nHint Resolve length_emp append_emp substring_le substring_split length_app1.\n\nLemma substring_app_fst : forall s2 s1 n,\n  length s1 = n\n  -> substring 0 n (s1 ++ s2) = s1.\n  induction s1; crush.\nQed.\n\nLemma substring_app_snd : forall s2 s1 n,\n  length s1 = n\n  -> substring n (length (s1 ++ s2) - n) (s1 ++ s2) = s2.\n  Hint Rewrite <- minus_n_O.\n\n  induction s1; crush.\nQed.\n\nHint Rewrite substring_app_fst substring_app_snd using solve [trivial].\n(* end hide *)\n\n(** A few auxiliary functions help us in our final matcher definition.  The function [split] will be used to implement the regexp concatenation case. *)\n\nSection split.\n  Variables P1 P2 : string -> Prop.\n  Variable P1_dec : forall s, {P1 s} + {~ P1 s}.\n  Variable P2_dec : forall s, {P2 s} + {~ P2 s}.\n  (** We require a choice of two arbitrary string predicates and functions for deciding them. *)\n\n  Variable s : string.\n  (** Our computation will take place relative to a single fixed string, so it is easiest to make it a [Variable], rather than an explicit argument to our functions. *)\n\n  (** The function [split'] is the workhorse behind [split].  It searches through the possible ways of splitting [s] into two pieces, checking the two predicates against each such pair.  The execution of [split'] progresses right-to-left, from splitting all of [s] into the first piece to splitting all of [s] into the second piece.  It takes an extra argument, [n], which specifies how far along we are in this search process. *)\n\n  Definition split' : forall n : nat, n <= length s\n    -> {exists s1, exists s2, length s1 <= n /\\ s1 ++ s2 = s /\\ P1 s1 /\\ P2 s2}\n    + {forall s1 s2, length s1 <= n -> s1 ++ s2 = s -> ~ P1 s1 \\/ ~ P2 s2}.\n    refine (fix F (n : nat) : n <= length s\n      -> {exists s1, exists s2, length s1 <= n /\\ s1 ++ s2 = s /\\ P1 s1 /\\ P2 s2}\n      + {forall s1 s2, length s1 <= n -> s1 ++ s2 = s -> ~ P1 s1 \\/ ~ P2 s2} :=\n      match n with\n        | O => fun _ => Reduce (P1_dec \"\" && P2_dec s)\n        | S n' => fun _ => (P1_dec (substring 0 (S n') s)\n            && P2_dec (substring (S n') (length s - S n') s))\n          || F n' _\n      end); clear F; crush; eauto 7;\n    match goal with\n      | [ _ : length ?S <= 0 |- _ ] => destruct S\n      | [ _ : length ?S' <= S ?N |- _ ] => destruct (eq_nat_dec (length S') (S N))\n    end; crush.\n  Defined.\n\n  (** There is one subtle point in the [split'] code that is worth mentioning.  The main body of the function is a [match] on [n].  In the case where [n] is known to be [S n'], we write [S n'] in several places where we might be tempted to write [n].  However, without further work to craft proper [match] annotations, the type-checker does not use the equality between [n] and [S n'].  Thus, it is common to see patterns repeated in [match] case bodies in dependently typed Coq code.  We can at least use a [let] expression to avoid copying the pattern more than once, replacing the first case body with:\n     [[\n        | S n' => fun _ => let n := S n' in\n          (P1_dec (substring 0 n s)\n            && P2_dec (substring n (length s - n) s))\n          || F n' _\n     ]]\n\n     The [split] function itself is trivial to implement in terms of [split'].  We just ask [split'] to begin its search with [n = length s]. *)\n\n  Definition split : {exists s1, exists s2, s = s1 ++ s2 /\\ P1 s1 /\\ P2 s2}\n    + {forall s1 s2, s = s1 ++ s2 -> ~ P1 s1 \\/ ~ P2 s2}.\n    refine (Reduce (split' (n := length s) _)); crush; eauto.\n  Defined.\nEnd split.\n\nImplicit Arguments split [P1 P2].\n\n(* begin hide *)\nLemma app_empty_end : forall s, s ++ \"\" = s.\n  induction s; crush.\nQed.\n\nHint Rewrite app_empty_end.\n\nLemma substring_self : forall s n,\n  n <= 0\n  -> substring n (length s - n) s = s.\n  induction s; substring.\nQed.\n\nLemma substring_empty : forall s n m,\n  m <= 0\n  -> substring n m s = \"\".\n  induction s; substring.\nQed.\n\nHint Rewrite substring_self substring_empty using omega.\n\nLemma substring_split' : forall s n m,\n  substring n m s ++ substring (n + m) (length s - (n + m)) s\n  = substring n (length s - n) s.\n  Hint Rewrite substring_split.\n\n  induction s; substring.\nQed.\n\nLemma substring_stack : forall s n2 m1 m2,\n  m1 <= m2\n  -> substring 0 m1 (substring n2 m2 s)\n  = substring n2 m1 s.\n  induction s; substring.\nQed.\n\nLtac substring' :=\n  crush;\n  repeat match goal with\n           | [ |- context[match ?N with O => _ | S _ => _ end] ] => case_eq N; crush\n         end.\n\nLemma substring_stack' : forall s n1 n2 m1 m2,\n  n1 + m1 <= m2\n  -> substring n1 m1 (substring n2 m2 s)\n  = substring (n1 + n2) m1 s.\n  induction s; substring';\n    match goal with\n      | [ |- substring ?N1 _ _ = substring ?N2 _ _ ] =>\n        replace N1 with N2; crush\n    end.\nQed.\n\nLemma substring_suffix : forall s n,\n  n <= length s\n  -> length (substring n (length s - n) s) = length s - n.\n  induction s; substring.\nQed.\n\nLemma substring_suffix_emp' : forall s n m,\n  substring n (S m) s = \"\"\n  -> n >= length s.\n  induction s; crush;\n    match goal with\n      | [ |- ?N >= _ ] => destruct N; crush\n    end;\n    match goal with\n      [ |- S ?N >= S ?E ] => assert (N >= E); [ eauto | omega ]\n    end.\nQed.\n\nLemma substring_suffix_emp : forall s n m,\n  substring n m s = \"\"\n  -> m > 0\n  -> n >= length s.\n  destruct m as [ | m]; [crush | intros; apply substring_suffix_emp' with m; assumption].\nQed.\n\nHint Rewrite substring_stack substring_stack' substring_suffix\n  using omega.\n\nLemma minus_minus : forall n m1 m2,\n  m1 + m2 <= n\n  -> n - m1 - m2 = n - (m1 + m2).\n  intros; omega.\nQed.\n\nLemma plus_n_Sm' : forall n m : nat, S (n + m) = m + S n.\n  intros; omega.\nQed.\n\nHint Rewrite minus_minus using omega.\n(* end hide *)\n\n(** One more helper function will come in handy: [dec_star], for implementing another linear search through ways of splitting a string, this time for implementing the Kleene star. *)\n\nSection dec_star.\n  Variable P : string -> Prop.\n  Variable P_dec : forall s, {P s} + {~ P s}.\n\n  (** Some new lemmas and hints about the [star] type family are useful.  We omit them here; they are included in the book source at this point. *)\n\n  (* begin hide *)\n  Hint Constructors star.\n\n  Lemma star_empty : forall s,\n    length s = 0\n    -> star P s.\n    destruct s; crush.\n  Qed.\n\n  Lemma star_singleton : forall s, P s -> star P s.\n    intros; rewrite <- (app_empty_end s); auto.\n  Qed.\n\n  Lemma star_app : forall s n m,\n    P (substring n m s)\n    -> star P (substring (n + m) (length s - (n + m)) s)\n    -> star P (substring n (length s - n) s).\n    induction n; substring;\n      match goal with\n        | [ H : P (substring ?N ?M ?S) |- _ ] =>\n          solve [ rewrite <- (substring_split S M); auto\n            | rewrite <- (substring_split' S N M); auto ]\n      end.\n  Qed.\n\n  Hint Resolve star_empty star_singleton star_app.\n\n  Variable s : string.\n\n  Lemma star_inv : forall s,\n    star P s\n    -> s = \"\"\n    \\/ exists i, i < length s\n      /\\ P (substring 0 (S i) s)\n      /\\ star P (substring (S i) (length s - S i) s).\n    Hint Extern 1 (exists i : nat, _) =>\n      match goal with\n        | [ H : P (String _ ?S) |- _ ] => exists (length S); crush\n      end.\n\n    induction 1; [\n      crush\n      | match goal with\n          | [ _ : P ?S |- _ ] => destruct S; crush\n        end\n    ].\n  Qed.    \n\n  Lemma star_substring_inv : forall n,\n    n <= length s\n    -> star P (substring n (length s - n) s)\n    -> substring n (length s - n) s = \"\"\n    \\/ exists l, l < length s - n\n      /\\ P (substring n (S l) s)\n      /\\ star P (substring (n + S l) (length s - (n + S l)) s).\n    Hint Rewrite plus_n_Sm'.\n\n    intros;\n      match goal with\n        | [ H : star _ _ |- _ ] => generalize (star_inv H); do 3 crush; eauto\n      end.\n  Qed.\n  (* end hide *)\n\n  (** The function [dec_star''] implements a single iteration of the star.  That is, it tries to find a string prefix matching [P], and it calls a parameter function on the remainder of the string. *)\n\n  Section dec_star''.\n    Variable n : nat.\n    (** Variable [n] is the length of the prefix of [s] that we have already processed. *)\n\n    Variable P' : string -> Prop.\n    Variable P'_dec : forall n' : nat, n' > n\n      -> {P' (substring n' (length s - n') s)}\n      + {~ P' (substring n' (length s - n') s)}.\n\n    (** When we use [dec_star''], we will instantiate [P'_dec] with a function for continuing the search for more instances of [P] in [s]. *)\n\n    (** Now we come to [dec_star''] itself.  It takes as an input a natural [l] that records how much of the string has been searched so far, as we did for [split'].  The return type expresses that [dec_star''] is looking for an index into [s] that splits [s] into a nonempty prefix and a suffix, such that the prefix satisfies [P] and the suffix satisfies [P']. *)\n\n    Definition dec_star'' : forall l : nat,\n      {exists l', S l' <= l\n        /\\ P (substring n (S l') s) /\\ P' (substring (n + S l') (length s - (n + S l')) s)}\n      + {forall l', S l' <= l\n        -> ~ P (substring n (S l') s)\n        \\/ ~ P' (substring (n + S l') (length s - (n + S l')) s)}.\n      refine (fix F (l : nat) : {exists l', S l' <= l\n          /\\ P (substring n (S l') s) /\\ P' (substring (n + S l') (length s - (n + S l')) s)}\n        + {forall l', S l' <= l\n          -> ~ P (substring n (S l') s)\n          \\/ ~ P' (substring (n + S l') (length s - (n + S l')) s)} :=\n        match l with\n          | O => _\n          | S l' =>\n            (P_dec (substring n (S l') s) && P'_dec (n' := n + S l') _)\n            || F l'\n        end); clear F; crush; eauto 7;\n        match goal with\n          | [ H : ?X <= S ?Y |- _ ] => destruct (eq_nat_dec X (S Y)); crush\n        end.\n    Defined.\n  End dec_star''.\n\n  (* begin hide *)\n  Lemma star_length_contra : forall n,\n    length s > n\n    -> n >= length s\n    -> False.\n    crush.\n  Qed.\n\n  Lemma star_length_flip : forall n n',\n    length s - n <= S n'\n    -> length s > n\n    -> length s - n > 0.\n    crush.\n  Qed.\n\n  Hint Resolve star_length_contra star_length_flip substring_suffix_emp.\n  (* end hide *)\n\n  (** The work of [dec_star''] is nested inside another linear search by [dec_star'], which provides the final functionality we need, but for arbitrary suffixes of [s], rather than just for [s] overall. *)\n  \n  Definition dec_star' : forall n n' : nat, length s - n' <= n\n    -> {star P (substring n' (length s - n') s)}\n    + {~ star P (substring n' (length s - n') s)}.\n    refine (fix F (n n' : nat) : length s - n' <= n\n      -> {star P (substring n' (length s - n') s)}\n      + {~ star P (substring n' (length s - n') s)} :=\n      match n with\n        | O => fun _ => Yes\n        | S n'' => fun _ =>\n          le_gt_dec (length s) n'\n          || dec_star'' (n := n') (star P)\n            (fun n0 _ => Reduce (F n'' n0 _)) (length s - n')\n      end); clear F; crush; eauto;\n    match goal with\n      | [ H : star _ _ |- _ ] => apply star_substring_inv in H; crush; eauto\n    end;\n    match goal with\n      | [ H1 : _ < _ - _, H2 : forall l' : nat, _ <= _ - _ -> _ |- _ ] =>\n        generalize (H2 _ (lt_le_S _ _ H1)); tauto\n    end.\n  Defined.\n\n  (** Finally, we have [dec_star], defined by straightforward reduction from [dec_star']. *)\n\n  Definition dec_star : {star P s} + {~ star P s}.\n    refine (Reduce (dec_star' (n := length s) 0 _)); crush.\n  Defined.\nEnd dec_star.\n\n(* begin hide *)\nLemma app_cong : forall x1 y1 x2 y2,\n  x1 = x2\n  -> y1 = y2\n  -> x1 ++ y1 = x2 ++ y2.\n  congruence.\nQed.\n\nHint Resolve app_cong.\n(* end hide *)\n\n(** With these helper functions completed, the implementation of our [matches] function is refreshingly straightforward.  We only need one small piece of specific tactic work beyond what [crush] does for us. *)\n\nDefinition matches : forall P (r : regexp P) s, {P s} + {~ P s}.\n  refine (fix F P (r : regexp P) s : {P s} + {~ P s} :=\n    match r with\n      | Char ch => string_dec s (String ch \"\")\n      | Concat _ _ r1 r2 => Reduce (split (F _ r1) (F _ r2) s)\n      | Or _ _ r1 r2 => F _ r1 s || F _ r2 s\n      | Star _ r => dec_star _ _ _\n    end); crush;\n  match goal with\n    | [ H : _ |- _ ] => generalize (H _ _ (eq_refl _))\n  end; tauto.\nDefined.\n\n(** It is interesting to pause briefly to consider alternate implementations of [matches].  Dependent types give us much latitude in how specific correctness properties may be encoded with types.  For instance, we could have made [regexp] a non-indexed inductive type, along the lines of what is possible in traditional ML and Haskell.  We could then have implemented a recursive function to map [regexp]s to their intended meanings, much as we have done with types and programs in other examples.  That style is compatible with the [refine]-based approach that we have used here, and it might be an interesting exercise to redo the code from this subsection in that alternate style or some further encoding of the reader's choice.  The main advantage of indexed inductive types is that they generally lead to the smallest amount of code. *)\n\n(* begin hide *)\nExample hi := Concat (Char \"h\"%char) (Char \"i\"%char).\nEval hnf in matches hi \"hi\".\nEval hnf in matches hi \"bye\".\n\nExample a_b := Or (Char \"a\"%char) (Char \"b\"%char).\nEval hnf in matches a_b \"\".\nEval hnf in matches a_b \"a\".\nEval hnf in matches a_b \"aa\".\nEval hnf in matches a_b \"b\".\n(* end hide *)\n\n(** Many regular expression matching problems are easy to test.  The reader may run each of the following queries to verify that it gives the correct answer.  We use evaluation strategy %\\index{tactics!hnf}%[hnf] to reduce each term to%\\index{head-normal form}% _head-normal form_, where the datatype constructor used to build its value is known.  (Further reduction would involve wasteful simplification of proof terms justifying the answers of our procedures.) *)\n\nExample a_star := Star (Char \"a\"%char).\nEval hnf in matches a_star \"\".\nEval hnf in matches a_star \"a\".\nEval hnf in matches a_star \"b\".\nEval hnf in matches a_star \"aa\".\n\n(** Evaluation inside Coq does not scale very well, so it is easy to build other tests that run for hours or more.  Such cases are better suited to execution with the extracted OCaml code. *)\n", "meta": {"author": "momohatt", "repo": "cpdt", "sha": "58ab808fbd6374b230f4123e3fa6c08fe9e93664", "save_path": "github-repos/coq/momohatt-cpdt", "path": "github-repos/coq/momohatt-cpdt/cpdt-58ab808fbd6374b230f4123e3fa6c08fe9e93664/textbook/MoreDep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7270478926767175}}
{"text": "\nRequire Import ZArith ROmega.\n\n(* Submitted by Xavier Urbain 18 Jan 2002 *)\n\nLemma lem1 :\n forall x y : Z, (-5 < x < 5)%Z -> (-5 < y)%Z -> (-5 < x + y + 5)%Z.\nProof.\nintros x y.\nromega.\nQed.\n\n(* Proposed by Pierre Crégut *)\n\nLemma lem2 : forall x : Z, (x < 4)%Z -> (x > 2)%Z -> x = 3%Z.\nintro.\n romega.\nQed.\n\n(* Proposed by Jean-Christophe Filliâtre *)\n\nLemma lem3 : forall x y : Z, x = y -> (x + x)%Z = (y + y)%Z.\nProof.\nintros.\nromega.\nQed.\n\n(* Proposed by Jean-Christophe Filliâtre: confusion between an Omega *)\n(* internal variable and a section variable (June 2001) *)\n\nSection A.\nVariable x y : Z.\nHypothesis H : (x > y)%Z.\nLemma lem4 : (x > y)%Z.\n romega.\nQed.\nEnd A.\n\n(* Proposed by Yves Bertot: because a section var, L was wrongly renamed L0 *)\n(* May 2002 *)\n\nSection B.\nVariable R1 R2 S1 S2 H S : Z.\nHypothesis I : (R1 < 0)%Z -> R2 = (R1 + (2 * S1 - 1))%Z.\nHypothesis J : (R1 < 0)%Z -> S2 = (S1 - 1)%Z.\nHypothesis K : (R1 >= 0)%Z -> R2 = R1.\nHypothesis L : (R1 >= 0)%Z -> S2 = S1.\nHypothesis M : (H <= 2 * S)%Z.\nHypothesis N : (S < H)%Z.\nLemma lem5 : (H > 0)%Z.\n romega.\nQed.\nEnd B.\n\n(* From Nicolas Oury (bug #180): handling -> on Set (fixed Oct 2002) *)\nLemma lem6 :\n forall (A : Set) (i : Z), (i <= 0)%Z -> ((i <= 0)%Z -> A) -> (i <= 0)%Z.\nintros.\n romega.\nQed.\n\n(* Adapted from an example in Nijmegen/FTA/ftc/RefSeparating (Oct 2002) *)\nRequire Import Omega.\nSection C.\nParameter g : forall m : nat, m <> 0 -> Prop.\nParameter f : forall (m : nat) (H : m <> 0), g m H.\nVariable n : nat.\nVariable ap_n : n <> 0.\nLet delta := f n ap_n.\nLemma lem7 : n = n.\n romega with nat.\nQed.\nEnd C.\n\n(* Problem of dependencies *)\nRequire Import Omega.\nLemma lem8 : forall H : 0 = 0 -> 0 = 0, H = H -> 0 = 0.\nintros.\nromega with nat.\nQed.\n\n(* Bug that what caused by the use of intro_using in Omega *)\nRequire Import Omega.\nLemma lem9 :\n forall p q : nat, ~ (p <= q /\\ p < q \\/ q <= p /\\ p < q) -> p < p \\/ p <= p.\nintros.\nromega with nat.\nQed.\n\n(* Check that the interpretation of mult on nat enforces its positivity *)\n(* Submitted by Hubert Thierry (bug #743) *)\n(* Postponed... problem with goals of the form \"(n*m=0)%nat -> (n*m=0)%Z\" *)\nLemma lem10 : forall n m : nat, le n (plus n (mult n m)).\nProof.\nintros; romega with nat.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/success/ROmega.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964035, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7270478829116942}}
{"text": "Require Import Arith.\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint eqb (n m: natural) : bool :=\n  match n, m with\n    | Zero, Zero => true\n    | Zero, Succ _ => false\n    | Succ _, Zero => false\n    | Succ n', Succ m' => eqb n' m'\n  end.\n\n  Fixpoint mem  (mem_arg1 : lst) (mem_arg0 : natural)\n  := match mem_arg0, mem_arg1 with\n    | x, Nil => false\n    | x, Cons y z => orb (eqb x y) (mem z x)\n    end.\n\nFixpoint less (less_arg0 : natural) (less_arg1 : natural) : bool\n           := match less_arg0, less_arg1 with\n              | x, Zero => false\n              | Zero, Succ x => true\n              | Succ x, Succ y => less x y\n              end.\n\n\n\nFixpoint insort  (insort_arg1 : lst) (insort_arg0 : natural) : lst\n           := match insort_arg1, insort_arg0 with\n              |  Nil, i => Cons i Nil\n              | Cons x y, i => if less i x then Cons i (Cons x y) else Cons x (insort y i)\n              end.\n\nFixpoint sort (sort_arg0 : lst) : lst\n           := match sort_arg0 with\n              | Nil => Nil\n              | Cons x y => insort (sort y) x\n              end.\n\nTheorem eqb_refl: forall n, eqb n n = true.\nProof.\n  induction n; simpl.\n  { assumption. }\n  { reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (z : lst), eq x y -> eq (mem (insort z y) x) true.\nProof.\n  intros.\n  induction z.\n  { subst. simpl. destruct (less y n).\n    { simpl. rewrite eqb_refl. simpl. reflexivity. }\n    { simpl. rewrite IHz. apply Bool.orb_true_r. }\n  }\n  { simpl. subst. rewrite eqb_refl. simpl. reflexivity. }\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal46.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.7772998714925402, "lm_q1q2_score": 0.7270447190990408}}
{"text": "Require Export ZArith.\nRequire Export ZArithRing.\nRequire Export Zcompare.\nRequire Export Zwf.\nOpen Scope Z_scope.\n \nDefinition factZ_it_F (fact : Z ->  Z) (x : Z) :=\n   match Z_lt_le_dec x 0 with\n     left h => 0\n    | right h =>\n        match Z_eq_dec 0 x with   left h' => 1\n                                 | right h'' => x * fact (x - 1) end\n   end.\n \nFixpoint iter (A : Set) (f : A ->  A) (k : nat) (a : A) {struct k} : A :=\n match k with   0%nat => a\n               | S p => f (iter A f p a) end.\nImplicit Arguments iter.\n \n \nDefinition factZ_terminates:\n forall (x : Z),\n  ({v : Z |\n   exists p : nat ,\n   forall k, forall g, (p < k)%nat ->  iter factZ_it_F k g x = v }).\nintros x; elim x  using (well_founded_induction (Zwf_well_founded 0)).\nclear x; intros x Hrec.\nunfold factZ_it_F.\ncase_eq (Z_lt_le_dec x 0).\nintros h heq1; exists 0; exists 1%nat.\nintros k; case k.\nintros; omega.\nintros; simpl; rewrite heq1; auto.\nintros h heq2.\ncase_eq (Z_eq_dec 0 x).\nintros h' heq3; exists 1; exists 1%nat.\nintros k; case k.\nintros; omega.\nintros; simpl. rewrite heq2.  simpl in heq3. rewrite heq3; auto.\nintros h'' heq4.\nassert (HZwf: Zwf 0 (x - 1) x).\nclear heq2 heq4.\nunfold Zwf; omega.\ndestruct (Hrec (x - 1) HZwf) as [v Hex].\nexists (x * v).\ndestruct Hex as [p Heq].\nexists (S p); intros k; case k.\nintros; omega.\nsimpl; intros k' hltk g; rewrite heq2; simpl in heq4;rewrite heq4.\nfold factZ_it_F.\nrewrite Heq.\ntrivial.\nomega.\nQed.\n \nDefinition factZ_it : Z ->  Z :=\n   fun x =>\n      match factZ_terminates x with exist v _ => v end.\n \nTheorem factZ_fix_eqn:\n forall x,\n  factZ_it x =\n  match Z_lt_le_dec x 0 with\n    left h => 0\n   | right h =>\n       match Z_eq_dec 0 x with   left h' => 1\n                                | right h'' => x * factZ_it (x - 1) end\n  end.\nintros x; unfold factZ_it.\nelim (factZ_terminates x).\nelim (factZ_terminates (x - 1)).\nintros v' Hex' v Hex.\nelim Hex; intros p Heq; elim Hex'; intros p' Heq'.\nrewrite <- (Heq (S ((p + p') + 1)) factZ_it).\n\nsimpl iter.\nunfold factZ_it_F.\n2:omega.\ncase (Z_lt_le_dec x 0); auto.\ncase (Z_eq_dec 0 x); auto.\nrewrite <- (Heq' ((p + p') + 1)%nat factZ_it).\n reflexivity.\nomega.\nQed.\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/gen-rec/SRC/factZ_it.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7270333452939989}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type :=  nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint mem (mem_arg0 : Nat) (mem_arg1 : Lst) : Prop\n           := match mem_arg0, mem_arg1 with\n              | x, nil => False\n              | x, cons y z => x = y \\/ mem x z\n              end.\n\nTheorem mem_append : forall (x : Nat) (y : Lst) (z : Lst), mem x y -> mem x (append y z).\nProof.\n  intros.\n  induction y.\n  - contradiction.\n  - simpl. destruct H.\n    + auto.\n    + apply IHy in H. auto.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal36.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7269741295919498}}
{"text": "(**************************************************************************)\n(**************************************************************************)\n(****                                                                  ****)\n(****   A demonstration that instead of having inductive families      ****)\n(****   (i.e., inductive types with indices) built into the type       ****)\n(****   theory, we can emulate them with families of inductive types   ****)\n(****   (i.e., inductive types with parameters) if propositional       ****)\n(****   equality is taken to be primitive                              ****)\n(****                                                                  ****)\n(**************************************************************************)\n(**************************************************************************)\n\nRequire Import Coq.Init.Nat.\nRequire Import Main.Tactics.\n\n(*\n  We define two inductive definitions and prove they are isomorphic. The first\n  definition is an inductive family, and the second is a family of inductive\n  types.\n\n  Note that `exp1` lives in `Type` because its `const1` constructor quantifies\n  over `Set`. `exp2`, however, can live in `Set` since parameter arguments are\n  not considered for universe constraints on inductive data types. In that\n  sense, we have gained something from using a parameter instead of an index.\n*)\n\nInductive exp1 : Set -> Type :=\n| const1 : forall (a : Set), a -> exp1 a\n| add1 : exp1 nat -> exp1 nat -> exp1 nat\n| lessThan1 : exp1 nat -> exp1 nat -> exp1 bool.\n\n#[export] Hint Constructors exp1 : main.\n\nInductive exp2 (a : Set) : Set :=\n| const2 : a -> exp2 a\n| add2 : nat = a -> exp2 nat -> exp2 nat -> exp2 a\n| lessThan2 : bool = a -> exp2 nat -> exp2 nat -> exp2 a.\n\n#[export] Hint Constructors exp2 : main.\n\nFixpoint exp1ToExp2 (a : Set) (e1 : exp1 a) : exp2 a :=\n  match e1 with\n  | const1 b x => const2 b x\n  | add1 e2 e3 => add2 nat eq_refl (exp1ToExp2 nat e2) (exp1ToExp2 nat e3)\n  | lessThan1 e2 e3 =>\n    lessThan2 bool eq_refl (exp1ToExp2 nat e2) (exp1ToExp2 nat e3)\n  end.\n\nFixpoint exp2ToExp1 (a : Set) (e1 : exp2 a) : exp1 a :=\n  match e1 with\n  | const2 _ x => const1 a x\n  | add2 _ H e2 e3 =>\n    match H in (_ = b) return exp1 b with\n    | eq_refl => add1 (exp2ToExp1 nat e2) (exp2ToExp1 nat e3)\n    end\n  | lessThan2 _ H e2 e3 =>\n    match H in (_ = b) return exp1 b with\n    | eq_refl => lessThan1 (exp2ToExp1 nat e2) (exp2ToExp1 nat e3)\n    end\n  end.\n\nTheorem exp1ToExp2ToExp1 :\n  forall (a : Set) (e : exp1 a), exp2ToExp1 a (exp1ToExp2 a e) = e.\nProof.\n  clean.\n  induction e; search.\nQed.\n\n#[export] Hint Resolve exp1ToExp2ToExp1 : main.\n\nTheorem exp2ToExp1ToExp2 :\n  forall (a : Set) (e : exp2 a), exp1ToExp2 a (exp2ToExp1 a e) = e.\nProof.\n  clean.\n  induction e; search.\nQed.\n\n#[export] Hint Resolve exp2ToExp1ToExp2 : main.\n\n(*\n  Just for fun, we implement evaluators for both of the inductive definitions\n  and prove they are preserved by the isomorphisms.\n*)\n\nFixpoint eval1 (a : Set) (e1 : exp1 a) : a :=\n  match e1 in exp1 b return b with\n  | const1 _ x => x\n  | add1 e2 e3 => eval1 nat e2 + eval1 nat e3\n  | lessThan1 e2 e3 => ltb (eval1 nat e2) (eval1 nat e3)\n  end.\n\nFixpoint eval2 (a : Set) (e1 : exp2 a) : a :=\n  match e1 with\n  | const2 _ x => x\n  | add2 _ H e2 e3 =>\n    match H in (_ = b) return b with\n    | eq_refl => eval2 nat e2 + eval2 nat e3\n    end\n  | lessThan2 _ H e2 e3 =>\n    match H in (_ = b) return b with\n    | eq_refl => ltb (eval2 nat e2) (eval2 nat e3)\n    end\n  end.\n\nTheorem exp1ToExp2PreservesEval :\n  forall (a : Set) (e : exp1 a), eval1 a e = eval2 a (exp1ToExp2 a e).\nProof.\n  clean.\n  induction e; search.\n  clean.\n  rewrite IHe1.\n  rewrite IHe2.\n  search.\nQed.\n\n#[export] Hint Resolve exp1ToExp2PreservesEval : main.\n\nTheorem exp2ToExp1PreservesEval :\n  forall (a : Set) (e : exp2 a), eval2 a e = eval1 a (exp2ToExp1 a e).\nProof.\n  clean.\n  induction e; search.\n  clean.\n  rewrite IHe1.\n  rewrite IHe2.\n  search.\nQed.\n\n#[export] Hint Resolve exp2ToExp1PreservesEval : main.\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/TypeTheory/Indices.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.72694853115726}}
{"text": "(* Practica 1 *)\n\nSection P1.\nVariables A B C:Prop.\n\n(* Ej 1.1 *)\nTheorem e11: A->A.\nProof.\n...\nQed.\n\n(* Ej 1.2 *)\nTheorem e12: A->B->A.\nProof.\n...\nQed.\n\n(* Ej 1.3 *)\nTheorem e13: (A->(B->C))->(A->B)->(A->C).\nProof.\n...\nQed.\n\n(*Ej 2.1 *)\nTheorem e21: (A->B)->(B->C)->A->C.\nProof.\n...\nQed.\n\n(*Ej 2.2 *)\nTheorem e22: (A->B->C)->B->A->C.\nProof.\n...\nQed.\n\n(*Ej 3.1 *)\nTheorem e31_1: A->A->A.\nProof.\n...\nQed.\n\nTheorem e31_2: A->A->A.\nProof.\n...\nQed.\n\n(* Ej 3.2 *)\nTheorem e32_1: (A->B->C)->A->(A->C)->B->C.\nProof.\n...\nQed.\n\nTheorem e32_2: (A->B->C)->A->(A->C)->B->C.\nProof.\n...\nQed.\n\n(* Ej 4.1 *)\nTheorem e41: A -> ~~A.\nProof.\n...\nQed.\n\n(* Ej 4.2 *)\nTheorem e42: A -> B -> (A /\\ B).\nProof.\n...\nQed.\n\n(* Ej 4.3 *)\nTheorem e43: (A->B->C) -> (A/\\B->C).\nProof.\n...\nQed.\n\n(* Ej 4.4 *)\nTheorem e44: A->(A\\/B).\nProof.\n...\nQed.\n\n(* Ej 4.5 *)\nTheorem e45: B->(A\\/B).\nProof.\n...\nQed.\n\n(* Ej 4.6 *)\nTheorem e46: (A \\/ B) -> (B \\/ A).\nProof.\n...\nQed.\n\n(* Ej 4.7 *)\nTheorem e47: (A->C)->(B->C)->A\\/B->C.\nProof.\n...\nQed.\n\n(* Ej 4.8 *)\nTheorem e48: False->A.\nProof.\n...\nQed.\n\n(* Ej 5.1 *)\nTheorem e51: (A->B)-> ~B-> ~A.\nProof.\n...\nQed.\n\n(* Ej 5.2 *)\nTheorem e52: ~(A/\\~A).\nProof.\n...\nQed.\n\n(* Ej 5.3 *)\nTheorem e53: (A->B)-> ~(A/\\~B).\nProof.\n...\nQed.\n\n(* Ej 5.4 *)\nTheorem e54: (A/\\B)->~(A->~B).\nProof.\n...\nQed.\n\n(* Ej 5.5 *)\nTheorem e55: (~A /\\ ~~A) -> False.\nProof.\n...\nQed.\n\n(* Ej 6.1 *)\nTheorem e61: (A\\/B) -> ~(~A/\\~B).\nProof.\n...\nQed.\n\n(* Ej 6.2 *)\nTheorem e62: A\\/B <-> B\\/A.\nProof.\n...\nQed.\n\n(* Ej 6.3 *)\nTheorem e63: A\\/B -> ((A->B)->B).\nProof.\n...\nQed.\n\nEnd P1.\n\n\nSection Logica_Clasica.\nVariables A B C: Prop.\n\n(* Ej 7.1 *)\nTheorem e71: A \\/ ~A -> ~~A->A.\nProof.\n...\nQed.\n\n(* Ej 7.2 *)\nTheorem e72: A\\/~A -> ((A->B) \\/ (B->A)).\nProof.\n...\nQed.\n\n(* Ej 7.3 *)\nTheorem e73: (A \\/ ~A) -> ~(A /\\ B) -> ~A \\/ ~B.\nProof.\n...\nQed.\n\n\nRequire Import Classical.\nCheck classic.\n\n(* Ej 8.1 *)\nTheorem e81: forall A:Prop, ~~A->A.\nProof.\n...\nQed.\n\n(* Ej 8.2 *)\nTheorem e82: forall A B:Prop, (A->B)\\/(B ->A).\nProof.\n...\nQed.\n\n(* Ej 8.3 *)\nTheorem e83: forall A B:Prop, ~(A/\\B)-> ~A \\/ ~B.\nProof.\n...\nQed.\n\nEnd Logica_Clasica.\n\n\nSection Traducciones.\n\n(* Ej 9 *)\n(* Definiciones *)\nVariable NM RED CONS UTIL : Prop.\n\nHypothesis H1 : ...\nHypothesis H2 : ...\n\nTheorem ej9 : ...\nProof.\n...\nQed.\n\n\n(* Ej 10 y 11 *)\n(* Formalizaciones a cargo del estudiante *)\n\n\n(* Ej 12 *)\n(* Definiciones *)\nVariable PF:Prop. (* el paciente tiene fiebre *)\nVariable PA:Prop. (* el paciente tiene piel amarillenta *)\nVariable PH:Prop. (* el paciente tiene hepatitis *)\nVariable PR:Prop. (* el paciente tiene rubeola *)\n\nHypothesis Regla1: ...\nHypothesis Regla2: ...\nHypothesis Regla3: ...\n\n\nTheorem ej12: (~PA /\\ PF) -> ...\n\nEnd Traducciones.\n", "meta": {"author": "elopez", "repo": "CFPTT", "sha": "5df066218d0acba5a009db498e6125d69865096a", "save_path": "github-repos/coq/elopez-CFPTT", "path": "github-repos/coq/elopez-CFPTT/CFPTT-5df066218d0acba5a009db498e6125d69865096a/práctica 1/plantilla p1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7268474820424159}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\nPrint even.\n(* ==>\n  Inductive even : nat -> Prop :=\n    | ev_0 : even 0\n    | ev_SS : forall n, even n -> even (S (S n)).\n*)\n\n\nTheorem ev_4'' : even 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\nDefinition ev_4''' : even 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n\nTheorem ev_plus4 : forall n, even n -> even (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\nDefinition ev_plus4' : forall n, even n -> \n                        even (4 + n) :=\n  fun (n : nat) => fun (H : even n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\nDefinition ev_plus4'' (n : nat) (H : even n)\n                    : even (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\n(* ===>\n     : forall n : nat, even n -> even (4 + n) *)\n\n(*\n     ∀(x:nat), nat \n  =  ∀(_:nat), nat \n  =  nat → nat\n*)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : even n), even (n + 2).\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : even n), even (n + 2).\n\nDefinition ev_plus2'' : Prop :=\n  forall n, even n -> even (n + 2).\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n\nPrint add1.\n\nModule Props.\n\nModule And.\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\nEnd And.\n\nPrint prod.\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) : \n                          Q /\\ P :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nLemma and_comm : forall P Q : Prop, \n        P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\nQed.\n\nPrint and_comm'_aux.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\nPrint and_comm'.\n\nDefinition conj_fact : forall P Q R, \n  P /\\ Q -> Q /\\ R -> P /\\ R.\nintros P Q R [H0 H1] [_ H2].\nsplit. apply H0. apply H2.\nDefined.\n\nModule Or.\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\nEnd Or.\n\nDefinition or_comm : forall P Q, \n  P \\/ Q -> Q \\/ P.\nintros P Q [H0 | H1].\nright. apply H0.\nleft. apply H1.\nDefined.\n\nModule Ex.\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro : forall x : A, P x -> ex P.\nEnd Ex.\n\nCheck ex (fun n => even n).\n\nDefinition some_nat_is_even : exists n, \n  even n :=\n  ex_intro even 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\nCheck ex_intro even 4.\nCheck ev_SS 2 (ev_SS 0 ev_0).\n\nDefinition ex_ev_Sn : ex (fun n => even (S n)).\n  exists 1. apply (ev_SS 0 ev_0). Defined.\n\nInductive True : Prop :=\n  | I : True.\n\nInductive False : Prop := .\n\nEnd Props.\n\nModule MyEquality.\nInductive eq {X:Type} : X -> X -> Prop :=\n| eq_refl : forall x, eq x x.\nNotation \"x == y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\nDefinition four' : 2 + 2 == 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), \n  []++[x] == x::[] :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\nCheck singleton nat 2.\n\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x == y -> forall P:X -> Prop, P x -> P y.\nProof.\n  intros. inversion H. rewrite <- H2.\n  apply H0.\nQed.\n\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P: X -> Prop, P x -> P y) -> x == y.\nProof.\n  intros. apply H. apply eq_refl.\nQed.\n\nEnd MyEquality.", "meta": {"author": "yzwqf", "repo": "software_foundations", "sha": "ac510433179dedf6b3102ac1509d3b1004f01c33", "save_path": "github-repos/coq/yzwqf-software_foundations", "path": "github-repos/coq/yzwqf-software_foundations/software_foundations-ac510433179dedf6b3102ac1509d3b1004f01c33/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064587, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7268252013648935}}
{"text": "Require Import Coq.Logic.Classical_Prop.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Psatz.\nRequire Import PL.CoqInductiveType.\nRequire Import PL.SetsDomain.\nRequire Import PL.SemanticsIntro.\nLocal Open Scope string.\nLocal Open Scope sets_scope.\n\n(** 之前我们已经学习了如何在Coq中用集合来定义正则表达式的语义。在这一讲中，我们\n    将在Coq中证明集合的相关性质，并进一步证明正则表达式的相关性质。*)\n\n(** * 集合与命题 *)\n\n(** 由于集合以及集合间的运算是基于Coq中的命题进行定义的，集合相关性质的证明也可\n    以规约为与命题有关的逻辑证明。例如，我们想要证明，交集运算具有交换律：*)\n\nLemma Sets_intersect_comm: forall (X Y: string -> Prop),\n  X ∩ Y == Y ∩ X.\nProof.\n  intros.\n  (** 下面一条命令_[sets_unfold]_是SetsDomain库提供的自动证明指令，它可以将有关\n      集合的性质转化为有关命题的性质。*)\n  sets_unfold.\n  (** 原本要证明的关于交集的性质现在就转化为了：\n        _[forall a : string, X a /\\ Y a <-> Y a /\\ X a]_\n      其中_[forall]_就是逻辑中『任意』的意思；_[/\\]_之前我们已经了解，它表示『并\n      且』的意思；_[<->]_表示『当且仅当』的意思；_[X a]_可以念做性质_[X]_对于\n      _[a]_成立，也可以理解为_[a]_是集合_[X]_的元素。\n\n      我们稍后再来完成相关性质的证明。在Coq中，要放弃当前的证明，可以用下面的\n      _[Abort]_指令。*)\nAbort.\n\n(** 下面是一条关于并集运算的性质。*)\n\nLemma Sets_included_union1: forall (X Y: string -> Prop),\n  X ⊆ X ∪ Y.\nProof.\n  intros.\n  sets_unfold.\n  (** 经过转化，要证明的结论是：_[forall a : string, X a -> X a \\/ Y a]_。这里，\n      _[\\/]_表示『或者』；_[->]_表示推出，也可以念做『如果...那么...』。*)\nAbort.\n\n(** 下面是一条关于一列集合的并集运算的性质。*)\n\nLemma Sets_included_omega_union0: forall (X: nat -> string -> Prop),\n  X 0 ⊆ ⋃ X.\nProof.\n  intros.\n  sets_unfold.\n  (** 经过转化，要证明的结论是：\n         _[forall a : string, X 0 a -> exists n : nat, X n a]_\n      它表示：对于任意一个字符串_[a]_，如果他是_[X 0]_的元素，那么就存在一个自然\n      数_[n]_使得_[a]_是_[X n]_的元素。*)\nAbort.\n\n(** * 逻辑命题的证明 *)\n\n(** ** 逻辑命题『真』的证明 *)\n\n(** 我们不需要任何前提就可以推出_[True]_。在Coq标准库中，_[I]_是_[True]_的一个证\n    明，我们可以用_[exact I]_来证明_[True]_。*)\n\nExample proving_True_1: 1 < 2 -> True.\nProof.\n  intros.\n  exact I.\nQed.\n\nExample proving_True_2: 1 > 2 -> True.\nProof.\n  intros.\n  exact I.\nQed.\n\n(** ** 关于『并且』的证明 *)\n\n(** 要证明『某命题并且某命题』成立，可以在Coq中使用_[split]_证明指令进行证明。该\n    指令会将当前的证明目标拆成两个子目标。*)\n\nLemma True2: True /\\ True.\nProof.\n  split.\n  + exact I.\n  + exact I.\nQed.\n\n(** 下面证明一个关于_[/\\]_的一般性结论：*)\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB.\n  split.\n  (** 下面的_[apply]_指令表示在证明中使用一条前提，或者使用一条已经经过证明的定\n      理或引理。*)\n  + apply HA.\n  + apply HB.\nQed.\n\nExample and_exercise :\n  forall n m : nat, n + 2*m = 10 -> 2*n + m = 5 -> n = 0 /\\ True.\nProof.\n  intros.\n  split.\n  - lia.\n  - exact I.\nQed.\n\n(** 如果当前一条前提假设具有『某命题并且某命题』的形式，我们可以在Coq中使用\n    _[destruct]_指令将其拆分成为两个前提。 *)\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros.\n  destruct H as [HP HQ].\n  apply HP.\nQed.\n\n(** _[destruct]_指令也可以不指名拆分后的前提的名字，Coq会自动命名。*)\n\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros.\n  destruct H. \n  (* 这里只用到第二个分支，因此可以用_[_]_把第一个扔掉： _[destruct H as [_ ?]]_ *)\n  (* _[?]_ 表示让Coq来命名 *)\n  apply H0.\nQed.\n\n(** 当前提与结论中，都有_[/\\]_的时候，我们就既需要使用_[split]_指令，又需要使用\n    _[destruct]_指令。*)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros.\n  destruct H as [HP HQ].\n  split.\n  - apply HQ.\n  - apply HP.\nQed.\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros.\n  destruct H as [HP HQR].\n  destruct HQR as [HQ HR].\n  split.\n  - split.\n    apply HP. apply HQ.\n  - apply HR.\nQed.\n\n(** ** 关于『或』的证明 *)\n\n(** 『或』是另一个重要的逻辑连接词。如果『或』出现在前提中，我们可以用Coq中的\n    _[destruct]_指令进行分类讨论。*)\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros.\n  destruct H as [H | H].\n  + rewrite H.\n    lia.\n  + rewrite H.\n    lia.\nQed.\n\n(** 在上面的例子中，我们对于形如_[A \\/ B]_的前提进行分类讨论。要证明_[A \\/ B]_能\n    推出原结论，就需要证明_[A]_与_[B]_中的任意一个都可以推出原结论。下面是一个一\n    般性的结论. *)\n\nLemma or_example2 :\n  forall P Q R: Prop, (P -> R) -> (Q -> R) -> (P \\/ Q -> R).\nProof.\n  intros.\n  destruct H1 as [HP | HQ].\n  + apply H.\n    (* 注意，_[apply]_指令不一定要前提与结论完全吻合才能使用。此处，只要_[H]_中\n       推导的结果与待证明的结论一致，就可以使用_[apply H]_。*)\n    apply HP.\n  + apply H0 in HQ.\n    (* _[apply]_指令还可以在前提中做推导，不过这时需要使用_[apply ... in]_这一语\n       法。*)\n    apply HQ.\nQed.\n\n(** 相反的，如果要证明一条形如_[A \\/ B]_的结论整理，我们就只需要证明_[A]_与_[B]_\n    两者之一成立就可以了。在Coq中的指令是：_[left]_与_[right]_。例如，下面是选择\n    左侧命题的例子。*)\n\nLemma or_introl : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros.\n  left.\n  apply H.\nQed.\n\n(** 下面是选择右侧命题的例子。*)\n\nLemma or_intror : forall A B : Prop, B -> A \\/ B.\nProof.\n  intros.\n  right.\n  apply H.\nQed.\n\n(** 下面性质请各位自行证明。*)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros.\n  destruct H as [HP | HQ].\n  - right. apply HP.\n  - left. apply HQ.\nQed.\n\n(** ** 关于『如果...那么...』的证明 *)\n\n(** 事实上，在之前的例子中，我们已经多次证明有关_[->]_的结论了。下面我们在看几个\n    例子，并额外介绍几条Coq证明指令。\n\n    下面的证明中，_[pose proof]_表示推导出一个新的结论，并将其用作之后证明中的前\n    提。*)\n\nTheorem modus_ponens: forall P Q: Prop,\n  P /\\ (P -> Q) -> Q.\nProof.\n  intros.\n  destruct H.\n  (** 将_[H0: P -> Q]_作用在_[H: P]_上，我们就可以得出一个新结论：_[Q]_。*)\n  pose proof H0 H.\n  apply H1.\nQed.\n\n(** 下面我们换一种方法证明。_[revert]_证明指令可以看做_[intros]_的反操作。 *)\n\nTheorem modus_ponens_alter1: forall P Q: Prop,\n  P /\\ (P -> Q) -> Q.\nProof.\n  intros.\n  destruct H.\n  (** 下面_[revert]_指令将前提中的_[P]_又放回了『结论中的前提』中去。*)\n  revert H.\n  apply H0.\nQed.\n\n(** 下面我们再换一种方式证明，_[specialize]_指令与_[apply ... in]_指令的效果稍有\n    不同。*)\n\nTheorem modus_ponens_alter2: forall P Q: Prop,\n  P /\\ (P -> Q) -> Q.\nProof.\n  intros.\n  destruct H.\n  specialize (H0 H).\n  apply H0.\nQed.\n\n(** 另外，我们可以直接使用_[exact]_指令，这个指令的效果像是_[pose proof]_或者\n    _[specialize]_与_[apply]_的组合。*)\n\nTheorem modus_ponens_alter3: forall P Q: Prop,\n  P /\\ (P -> Q) -> Q.\nProof.\n  intros.\n  destruct H.\n  exact (H0 H).\nQed.\n\n(** ** 关于『否定』与『假』的证明 *)\n\n(** 在Coq中[~]表示否定，_[False]_表示假。如果前提为假，那么，矛盾推出一切。在Coq\n    中，这可以用_[contradiction]_指令或_[destruct]_指令完成证明。*)\n\nTheorem ex_falso_quodlibet : forall (P: Prop),\n  False -> P.\nProof.\n  intros.\n  contradiction.\nQed.\n\nTheorem ex_falso_quodlibet_alter : forall (P: Prop),\n  False -> P.\nProof.\n  intros.\n  destruct H.\nQed.\n\n(** _[contradiction]_也可以用于_[P]_与_[~ P]_同时出现在前提中的情况： *)\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~ P) -> Q.\nProof.\n  intros.\n  destruct H.\n  contradiction.\nQed.\n\n(** 除了_[P]_与_[~ P]_不能同时为真之外，他们也不能同时为假，或者说，他们中至少有\n    一个要为真。这是Coq标准库中的_[classic]_。 *)\n\nCheck classic.\n\n(** 它说的是：_[forall P : Prop, P \\/ ~ P]_。下面我们利用它做一些证明。 *)\n\nTheorem double_neg_elim : forall P : Prop,\n  ~ ~ P -> P.\nProof.\n  intros.\n  pose proof classic P. (* 把P塞给_[classic]_里面的前提_[forall P]_ *)\n  destruct H0.\n  + apply H0.\n  + contradiction.\nQed.\n\nTheorem not_False :\n  ~ False.\nProof.\n  pose proof classic False.\n  destruct H.\n  - contradiction.\n  - apply H.\nQed.\n\nTheorem double_neg_intro : forall P : Prop,\n  P -> ~ ~ P.\nProof.\n  intros.\n  pose proof classic (~ P).\n  destruct H0.\n  - contradiction.\n  - apply H0.\nQed.\n\n(** ** 关于『当且仅当』的证明 *)\n\n(** 在Coq中，_[<->]_符号对应的定义是_[iff]_，其将_[P <-> Q]_定义为\n          _[(P -> Q) /\\ (Q -> P)]_\n    因此，要证明关于『当且仅当』的性质，首先可以使用其定义进行证明。*)\n\nTheorem iff_refl: forall P: Prop, P <-> P.\nProof.\n  intros.\n  unfold iff.\n  split.\n  + intros.\n    apply H.\n  + intros.\n    apply H.\nQed.    \n\nTheorem iff_imply: forall P Q: Prop, (P <-> Q) -> (P -> Q).\nProof.\n  intros P Q H.\n  unfold iff in H.\n  destruct H.\n  exact H.\nQed.\n\n(** 当某前提假设具有形式_[P <-> Q]_，那我们也可以使用_[apply]_指令进行证明。*)\n\nTheorem iff_imply_alter: forall P Q: Prop, (P <-> Q) -> (P -> Q).\nProof.\n  intros.\n  apply H.\n  apply H0.\nQed.\n\n(** 另外，_[rewrite]_指令也可以使用形如_[P <-> Q]_的等价性前提。*)\n\nTheorem iff_imply_alter2: forall P Q: Prop, (P <-> Q) -> (P -> Q).\nProof.\n  intros.\n  rewrite <- H.\n  apply H0.\nQed.\n\nTheorem iff_imply_alter3: forall P Q: Prop, (P <-> Q) -> (P -> Q).\nProof.\n  intros P Q.\n  tauto. (* tautology, 重言式 *)\nQed.\n\n(** ** 关于『存在』的证明 *)\n\n(** 当待证明结论形为：存在一个_[x]_使得...，那么可以用_[exists]_指明究竟哪个\n    _[x]_使得该性质成立。*)\n\nLemma four_is_even : exists n, 4 = n + n.\nProof.\n  exists 2.\n  lia.\nQed.\n\nLemma six_is_not_prime: exists n, 2 <= n < 6 /\\ exists q, n * q = 6.\nProof.\n  exists 2.\n  split.\n  + lia.\n  + exists 3.\n    lia.\nQed.\n\n(** 当某前提形为：存在一个_[x]_使得...，那么可以使用Coq中的_[destruct]_指令进行\n    证明。这一证明指令相当于数学证明中的：任意给定一个这样的_[x]_。 *)\n\nTheorem exists_example : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros.\n  destruct H as [m H].\n  exists (2 + m).\n  lia.\nQed.\n\nTheorem dist_exists_and : 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.\n  destruct H as [x [HP HQ]].\n  split.\n  - exists x.\n    apply HP.\n  - exists x.\n    apply HQ.\nQed.\n\nTheorem exists_exists : forall (X Y:Type) (P : X -> Y -> Prop),\n  (exists x y, P x y) <-> (exists y x, P x y).\nProof.\n  intros.\n  unfold iff.\n  split.\n  - intros H. destruct H as [x' [y' H']].\n    exists y'. exists x'. apply H'.\n  - intros H. destruct H as [x' [y' H']].\n    exists y'. exists x'. apply H'.\nQed.\n\n(** * 集合性质的证明 *)\n\nLemma Sets_intersect_comm: forall (X Y: string -> Prop),\n  X ∩ Y == Y ∩ X.\nProof.\n  intros.\n  sets_unfold.\n  (* 此处可直接用_[tauto]_ *)\n  intros.\n  unfold iff.\n  split.\n  - apply and_commut.\n  - apply and_commut.\nQed.\n\nLemma Sets_included_union1: forall (X Y: string -> Prop),\n  X ⊆ X ∪ Y.\nProof.\n  intros.\n  sets_unfold.\n  intros.\n  left.\n  apply H.\nQed.\n\nLemma Sets_included_omega_union0: forall (X: nat -> string -> Prop),\n  X 0 ⊆ ⋃ X.\nProof.\n  intros.\n  sets_unfold.\n  intros.\n  exists 0.\n  apply H.\nQed.\n\n(* reg_denote (app r EmptyStr) == reg_denote r *)\nLemma string_set_app_empty_string_r: forall X: string -> Prop,\n  X ∘ [\"\"] == X.\nProof.\n  intros.\n  unfold string_set_app; sets_unfold.\n  intros.\n  split; intros.\n  - destruct H as [s1 [s2 [? [? ?]]]].\n    rewrite H1.\n    rewrite <- H0.\n    rewrite string_app_empty_r.\n    exact H.\n  - exists a, \"\".\n    split.\n    -- apply H.\n    -- split.\n       --- reflexivity.\n       --- rewrite string_app_empty_r.\n           reflexivity.\nQed.\n\nLemma string_set_app_assoc: forall X Y Z: string -> Prop,\n  X ∘ (Y ∘ Z) == (X ∘ Y) ∘ Z.\nProof.\n  intros.\n  unfold string_set_app; sets_unfold.\n  intros.\n  split.\n  - intros H.\n    destruct H as [s1 H].\n    destruct H as [s2 H].\n    destruct H as [H1 H2].\n    destruct H2 as [H2 H3].\n    destruct H2 as [s3 [s4 H2]].\n    destruct H2 as [H21 [H22 H23]].\n    exists (string_app s1 s3). exists s4.\n    split.\n    -- exists s1. exists s3.\n       split.\n       --- apply H1.\n       --- split.\n           * apply H21.\n           * reflexivity.\n    -- split.\n       --- apply H22.\n       --- rewrite <- string_app_assoc.\n           rewrite <- H23.\n           rewrite <- H3.\n           reflexivity.\n  - intros H. \n    destruct H as [s1 [s2 H]].\n    destruct H as [H1 H2].\n    destruct H2 as [H2 H3].\n    destruct H1 as [s3 [s4 H1]].\n    destruct H1 as [H11 H12].\n    destruct H12 as [H12 H13].\n    exists s3. exists (string_app s4 s2).\n    split.\n    -- apply H11.\n    -- split.\n       --- exists s4. exists s2.\n           split.\n           * apply H12.\n           * split.\n             ** apply H2.\n             ** reflexivity.\n       --- rewrite string_app_assoc. \n           rewrite <- H13.\n           rewrite <- H3.\n           reflexivity.\nQed.\n", "meta": {"author": "gzqaq", "repo": "CS2612-PLaC", "sha": "fb7be0651785905b60d3e705324175daaadcc96b", "save_path": "github-repos/coq/gzqaq-CS2612-PLaC", "path": "github-repos/coq/gzqaq-CS2612-PLaC/CS2612-PLaC-fb7be0651785905b60d3e705324175daaadcc96b/code/Coq/lec_demo/CoqProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.7268251969262656}}
{"text": "From coqlearn Require Export wjm02.\n\nInductive natprod:Type:=\n    |pair (n1 n2:nat).\nCheck (pair 3 5).\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 (snd (pair 2 4)).\n\nNotation \"( x , y )\":=(pair x y).\nCheck (1,2).\n\nCompute (snd (12,23)).\n\nDefinition swap_pair (p:natprod):natprod:=\n    match p with\n        |(x,y)=>(y,x)\n    end.\n\nCompute (swap_pair (1,2)).\n\n\nTheorem surjective_pairing:forall p:natprod,p=(fst p,snd p).\nProof.\nintros p.\ndestruct p as [n m] eqn:E.\nsimpl. reflexivity.\nQed.\n\nTheorem snd_fst_is_swap:forall p:natprod,(snd p,fst p)=swap_pair p.\nProof.\nintros p.\nsimpl.\ndestruct p as [n m].\nsimpl. reflexivity.\nQed.\n\nTheorem fst_swap_is_snd:forall p:natprod,fst (swap_pair p)=snd p.\nProof.\nintros p.\ndestruct p as [n m].\nsimpl. reflexivity.\nQed.\n\nInductive natlist:Type:=\n    |nil\n    |cons (n:nat) (l:natlist).\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\nCheck (mylist).\n\nNotation \"x :: l\":=(cons x l) (at level 60,right associativity).\nNotation \"[]\":=nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nCheck ([1;2;3;4;5]).\n(*just for test\n\nNotation \"[ x | .. | y ]\" := (cons y .. (cons x nil) ..).\n\nCheck ([1|2|3|4|5]).\n\nDefinition fst_element_list (L:natlist):natlist:=\n    match L with\n        |nil=>nil\n        |cons x L'=>cons x nil\n    end.\n\nCompute (fst_element_list [1|2|3|4|5]).\n*)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => []\n  | S count' => n::(repeat n count')\n  end.\n\nFixpoint length (l:natlist):nat:=\n    match l with\n        |nil=>0\n        |h::t=>S (length t)\n    end.\n\nCompute (repeat 6 6).\nCompute (length [1;2;3]).\n\nFixpoint app (L1 L2:natlist):natlist:=\n    match L1 with\n        |nil=>L2\n        |h::t=>h::(app t L2)\n    end.\n\nCompute (app [1;2;3] [6;5;4]).\n\nCompute (app [] []).\n\nNotation \"x ++ y\":=(app x y) (right associativity,at level 60).\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\nFixpoint nonzeros(l:natlist):natlist:=\n    match l with\n        |nil=>nil\n        |0::t=>nonzeros t\n        |not0::t=>not0::(nonzeros t)\n    end.\n\nCompute (nonzeros [0;1;0;2;0;3;0;0]).\nCompute (nonzeros [1;2;3]).\nCompute (nonzeros [0;0;0]).\n\n\nFixpoint odd_fst_element(l:natlist):bool:=\n    match l with\n    |nil=>true\n    |O::t=>false\n    |(S O)::t=>true\n    |(S (S m))::t=>oddn m\n    end.\n\nCompute (odd_fst_element [2;1;2;3]).\n\n\nFixpoint oddmembers(l:natlist):natlist:=\n    match l,(odd_fst_element l) with\n        |[],_=>[]\n        |h::nil,false=>[]\n        |h::t,false=>oddmembers t\n        |h::t,true=>h::(oddmembers t)\n    end.\n\nCompute (oddmembers [12;43;5;32;0;12;11;666]).\n\nFixpoint countoddmembers (l:natlist):nat:=\n    match l,(odd_fst_element l) with\n        |[],_=>0\n        |h::nil,false=>0\n        |h::t,false=>countoddmembers t\n        |h::t,true=>S (countoddmembers t)\n    end.\n\nCompute (countoddmembers [0;2;4]).\n\nTheorem app_assoc:forall (l1 l2 l3:natlist),(l1++l2)++l3=l1++(l2++l3).\nProof.\nintros l1 l2 l3.\ninduction l1 as [|n l' IHl'].\n    -reflexivity.\n    -simpl. rewrite->IHl'. simpl. reflexivity.\nQed.\n\nInductive natoption : Type :=\n  | Some (n : nat)\n  | None.\n\nInductive id:Type:=\n    |Id (n:nat).\n\nDefinition eqb_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\nModule PartialMap.\n\nInductive partial_map:Type:=\n    |empty\n    |record (i:id) (v:nat) (m:partial_map).\n\nDefinition update (d:partial_map) (x:id) (value:nat):partial_map:=\n    record x value d.\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\nEnd PartialMap.\n\n\n\n\n", "meta": {"author": "10ca1h0st", "repo": "LearnCoq", "sha": "3a9a5b7a4a9acd178c35510006da6f8fe6086a4b", "save_path": "github-repos/coq/10ca1h0st-LearnCoq", "path": "github-repos/coq/10ca1h0st-LearnCoq/LearnCoq-3a9a5b7a4a9acd178c35510006da6f8fe6086a4b/wjm03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.7268010242863464}}
{"text": "(*|\n################################################\nPattern matching using information from theorems\n################################################\n\n:Link: https://stackoverflow.com/q/44413328\n|*)\n\n(*|\nQuestion\n********\n\nI have the following question, look in the code.\n|*)\n\n(* Suppose we have type A *)\nVariable A : Type.\n\n(* Also we have a function that returns the type (option A) *)\nVariable f_opt : A -> option A.\n\n(* Then, I can prove that this function always returns something: *)\nTheorem always_some : forall x, exists y, f_opt x = Some y.\nAdmitted.\n\n(* Or, equivalently: *)\nTheorem always_not_none : forall x, f_opt x <> None.\nAdmitted.\n\n(*|\nNow I would like to get a version of ``f_opt`` that always returns a\nvalue of type ``A``. Something like this:\n|*)\n\nFail Definition f x : A :=\n  match f_opt x with\n  | Some y => y\n  end. (* .fails .unfold *)\n\n(*|\nI understand that I need to do some kind of work with types, but I do\nnot understand what exactly i should do.\n|*)\n\n(*|\nAnswer (Arthur Azevedo De Amorim)\n*********************************\n\nIn Coq's underlying theory, every pattern matching must be exhaustive\n-- that is, it must explicitly consider all the constructors of the\ninductive type in question. This is why you are getting the error\nmessage you saw.\n\nHow do we get around this restriction? There are a few solutions.\nFirst, let's see how to convince Coq that the ``None`` branch can\nnever occur. For this, we will use your ``always_not_none`` theorem:\n|*)\n\nDefinition f x : A :=\n  match f_opt x as res return res <> None -> A with\n  | Some y => fun _ => y\n  | None => fun H => match H eq_refl with end\n  end (always_not_none x).\n\n(*|\nThis code might look strange at first sight, but it almost performs\nthe pattern match you want. To explain to Coq that the ``None`` case\nnever arises, it combines ``always_not_none`` with the fact that\n``f_opt x = None`` on that branch to derive a contradiction. This is\nthe ``H eq_refl`` term on that branch. Then, the ``match`` on that\ncontradiction suffices to convince Coq that the branch is spurious. A\nbit more formally, because ``False``, the contradictory proposition,\nis defined without any constructors, when we match on a term of type\n``False``, there are no branches to deal with, and the entire\nexpression can return any type that we want -- in this case, ``A``.\n\nWhat is strange about this code is the type annotations on the match,\nand that it returns a function instead of something of type ``A``\ndirectly. This is done because of how dependent pattern match works in\nCoq: whenever we want to make use of information that we obtain from\nbeing in a particular branch of a match (here, that ``f_opt x`` is\nequal to ``None`` in that branch), we must explicitly make the match\nreturn a function -- what Adam Chlipala calls the `convoy pattern\n<http://adam.chlipala.net/cpdt/html/MoreDep.html>`__. This is done so\nthat Coq knows where you plan to use that extra information and check\nthat it is done correctly. Here, we use that ``f_opt x`` is ``None``\nto feed the hypothesis needed by ``always_not_none x`` to derive a\ncontradiction.\n\nAlthough this will solve your problem, I would generally advise you\nagainst doing it this way. For instance, if you know that your ``A``\ntype is inhabited by some element ``a : A``, then you can simply make\n``f`` return ``a`` on that branch. This has the benefit of avoiding\nmentioning proofs inside your functions, which often gets in the way\nwhen simplifying and rewriting terms.\n|*)\n\n(*|\nAnswer (Daniel Schepler)\n************************\n\nUsing Coq's ``Program`` module, you can write an exhaustive pattern\nmatch, but annotate that some branches should be impossible to reach\nand then later provide the proof that this is the case:\n|*)\n\nReset f. (* .none *)\nRequire Import Program.\n\nProgram Definition f x : A :=\n  match f_opt x with\n  | Some a => a\n  | None => !\n  end.\nNext Obligation.\n  destruct (always_some x). congruence.\nQed.\n\n(*|\n(The ``Program`` module does a lot of the work behind the scenes that\nin a complete explicit definition you would have to write using the\n\"convoy pattern\". Do be aware, however, that sometimes ``Program``\ntends to generate lots of dependencies on ``JMeq`` and the axiom\n``JMeq_eq`` when dependent types are involved, even when it might not\nbe necessary.)\n\n----\n\n**A:** To check if ``f`` depends on any additional axioms one can use\n``Print Assumptions f.`` command.\n|*)\n\n(*|\nAnswer (Vinz)\n*************\n\nYou will need to put your existential proof ``always_not_none`` in\n``Set`` or ``Type`` to do so:\n|*)\n\nReset always_some. (* .none *)\nTheorem always_some : forall x, {y : A & f_opt x = Some y}.\nAdmitted.\n\n(*|\nThen you can do the following (or use ``refine`` or ``Program``):\n|*)\n\nDefinition f (x : A) : A :=\n  let s := always_some x in let (x0, _) := s in x0.\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/pattern-matching-using-information-from-theorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7268010023818943}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  plus (Succ lf2) (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj235_coqofml_vlJTsT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7266307286734667}}
{"text": "(*Dokaz algoritma insertion sort.*)\n\n(*KNJIŽNICE*)\nRequire Import List.\nRequire Import Bool.\nRequire Import ZArith.\nRequire Import Recdef.\n(*Notacija za sezname.*)\nOpen Scope list_scope.\nOpen Scope Z_scope.\n\n(*-----   INSERTION SORT   -----*)\n\n(*Funkcija, ki vstavi trenutni element na pravo mesto v seznam.*)\nFixpoint vstavi (x : Z) (l : list Z) : list Z :=\n  match l with\n    | nil => x :: nil\n    | y :: l' => if Z.leb x y\n                 then x :: y :: l'\n                 else y :: vstavi x l'\n  end.\n\n(*Funcija za insertion sort.*)\nFixpoint insertion_sort (l : list Z) : list Z:= \n  match l with\n  | nil => nil\n  | x::l' => vstavi x (insertion_sort l')\nend.\n\n(*-----   UREJEN SEZNAM   -----*)\n\n(*Funkcija, ki preveri ali je seznam urejen.*)\nFixpoint urejen (l : list Z) :=\n  match l with\n    | nil => True\n    | _ :: nil => True\n    | x :: ((y :: _) as l') => x <= y /\\ urejen l'\n  end.\n\nLemma urejen_tail(x : Z)(l:list Z): urejen(x::l)-> urejen l.\nProof.\n induction l; firstorder.\nQed.\n\n(*-----   PERMUTIRAN SEZNAM   -----*)\n\n(*Prešteje kolikokrat se pojavi iskani element.*)\nFixpoint pojavi (x : Z) (l : list Z) : nat :=\n  match l with\n    | nil => O\n    | y :: l' => if x =? y then S (pojavi x l') else pojavi x l'\n  end.\n\n(*Definicija, ki pove kaj pomeni, da je l' permutacija l.*)\nDefinition permutiran_seznam (l l' : list Z) := \n  forall x : Z, pojavi x l = pojavi x l'.\n\n(*Notacija za permutacijo.*)\nNotation \"l ~~ l'\" := (permutiran_seznam l l')(at level 70).\n\n(*-----    DOKAZ    -----*)\n\n(*Pomožna lema za dokaz urejenosti.*)\nLemma urejen_po_vstavljanju (x : Z) (l : list Z): urejen l -> urejen (vstavi x l).\nProof.\n  intro.\n  induction l ; simpl; auto.\n  case_eq (x <=? a)%Z.\n    + intro G.\n      simpl.\n      split.\n      *apply Zle_is_le_bool in G.\n       auto.\n      *apply H.\n    + intro G.\n      simpl.\n      destruct l.\n      * simpl.\n        split.\n        apply Z.lt_le_incl.\n        apply Z.leb_gt in G.\n        auto.\n        auto.\n      * simpl.\n        apply Z.leb_gt in G.\n        case_eq (x <=? z).\n        - intro A.\n          apply Z.leb_le in A.\n          split; firstorder.\n        - intro B.\n          apply Z.leb_gt in B.\n          split; firstorder.\n          replace (z :: vstavi x l) with (vstavi x(z :: l)).\n          apply H1.\n          simpl.\n          apply Z.leb_gt in B.\n          rewrite B.\n          reflexivity.\nQed.\n\n(*Pomožna lema za dokaz permutacije.*)\nLemma vstavi_enak (x : Z) (l : list Z): pojavi x (vstavi x l) = S (pojavi x l).\nProof.\n induction l.\n - simpl; rewrite Z.eqb_refl; auto.\n - simpl; case_eq (x <=? a).\n   + intro; simpl; rewrite Z.eqb_refl; auto.\n   + intro; simpl; case (x =? a); auto.  \nQed.\n\n(*Pomožna lema za dokaz permutacije.*)\nLemma vstavi_ni_enak (x y : Z) (l : list Z): (x =? y = false) -> pojavi x l = pojavi x (vstavi y l).\nProof.\n  induction l.\n  - intro; simpl; rewrite H; auto.\n  - intro; simpl.\n    case_eq (x =? a).\n    + intro G.\n      case_eq (y <=? a).\n      * intro G1; simpl; rewrite H, G; auto.\n      * intro G2; simpl; rewrite IHl, G; auto.   \n    + intro G.\n      case_eq (y <=? a).\n      * intro G1; simpl; rewrite H, G; auto.\n      * intro G2; simpl; rewrite IHl, G; auto.\nQed.\n\n(*Dokazati moramo, da je seznam v insertion_sort permutiran vhodni seznam in da je urejen.*)\nTheorem permutacija (l : list Z): l ~~ insertion_sort l.\nProof.\n induction l.\n - intro; auto.\n - intro; simpl.\n   case_eq (x =? a).\n   + intro; simpl.\n     rewrite IHl.\n     rewrite Z.eqb_eq in H.\n     rewrite H.\n     rewrite (vstavi_enak a (insertion_sort l)). \n     auto.\n   + intro.\n     rewrite IHl.\n     rewrite (vstavi_ni_enak x a (insertion_sort l)).\n     * auto.\n     * apply H.\nQed. \n\nTheorem urejenost (l : list Z): urejen(insertion_sort l).\nProof.\n - induction l.\n   + simpl; auto.\n   + simpl.\n     apply urejen_po_vstavljanju.\n     simpl.\n     auto.\nQed.", "meta": {"author": "TanjaM", "repo": "projekt2", "sha": "59971c777509746b850b75489f1e98073f923e47", "save_path": "github-repos/coq/TanjaM-projekt2", "path": "github-repos/coq/TanjaM-projekt2/projekt2-59971c777509746b850b75489f1e98073f923e47/insertion_sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7266265015353557}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\n\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=   Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint qmult (qmult_arg0 : natural) (qmult_arg1 : natural) (qmult_arg2 : natural) : natural\n           := match qmult_arg0, qmult_arg1, qmult_arg2 with\n              | Zero, n, m => m\n              | Succ n, m, p => qmult n m (plus p m)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\n   intros.\n   induction x.\n   - simpl. rewrite IHx. reflexivity.\n   - reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\n   intros.\n   induction x.\n   - simpl. rewrite IHx. reflexivity.\n   - reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\n   intros.\n   induction x.\n   - simpl. rewrite IHx. reflexivity.\n   - reflexivity.\n   \nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\n   intros.\n   induction x.\n   - simpl. lfind.  rewrite IHx.  reflexivity. \nAdmitted.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (z : natural), eq (plus (mult x y) z) (qmult x y z).\nProof.\n   induction x.\n   \n   - intros. simpl. rewrite <- IHx. rewrite plus_assoc. rewrite (plus_commut y z). reflexivity.\n   - reflexivity.\nQed.\n              \n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal85_plus_commut_58_plus_succ/goal85.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7266163310632315}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Psatz.\nRequire Import Init.\nRequire Import QArith.\nRequire Import QArith.Qround.\nRequire Import Omega.\n\n(***********   This is library ****************)\n\nDefinition INQ (n: nat) : Q := inject_Z (Z.of_nat n).\n\nCoercion INQ: nat >-> Q.\n\nTheorem INQ_plus : forall n m : nat , INQ n + INQ m == INQ (n + m).\nProof.\n  intros.\n  unfold INQ.\n  rewrite <- inject_Z_plus.\n  apply inject_Z_injective.\n  rewrite <- Nat2Z.inj_add. auto.\nQed.\n\nTheorem INQ_minus : forall n m : nat , (n >= m)%nat -> INQ (n - m) == INQ n - INQ m.\nProof.\n  intros.\n  assert (n - m >= 0)%nat. { omega. }\n  remember (n - m)%nat as p.\n  assert (n = p + m)%nat. { omega. }\n  unfold Qminus.\n  rewrite H1. \n  rewrite <- INQ_plus. field. \nQed.\n\nTheorem INQ_mult : forall n m : nat , INQ n * INQ m == INQ (n * m).\nProof.\n  intros.\n  unfold INQ.\n  rewrite <- inject_Z_mult.\n  apply inject_Z_injective.\n  rewrite <- Nat2Z.inj_mul. auto.\nQed.\n\nTheorem eq_INQ_Qeq : forall n m : nat, (n = m)%nat -> (INQ n == INQ m).\nProof.\n  intros.\n  unfold INQ.\n  rewrite H. reflexivity.\nQed.\n\nTheorem Qeq_INQ_eq : forall n m : nat ,(INQ n == INQ m) -> (n = m)%nat.\nProof.\n  intros.\n  unfold INQ in H.\n  rewrite inject_Z_injective in H.\n  apply Nat2Z.inj. auto.\nQed.\n\nTheorem INQ_le : forall n m : nat, (n >= m)%nat <-> (INQ n) >= (INQ m).\nProof.\n  intros.\n  unfold INQ.\n  split ; intros.\n  - rewrite <- Zle_Qle.\n    apply inj_le. auto.\n  - rewrite <- Zle_Qle in H.\n    apply Nat2Z.inj_le. auto.\nQed.\n\nTheorem INQ_lt : forall n m : nat, (n > m)%nat <-> (INQ n) > (INQ m).\nProof.\n  intros.\n  unfold INQ.\n  split ; intros.\n  - rewrite <- Zlt_Qlt.\n    apply inj_lt. auto.\n  - rewrite <- Zlt_Qlt in H.\n    apply Nat2Z.inj_lt. auto.\nQed.\n\nLemma INQ_nonneg: forall n, INQ n >= 0.\nProof.\n  intros.\n  unfold INQ.\n  change 0 with (inject_Z 0).\n  rewrite <- Zle_Qle.\n  omega.\nQed.\n\nLemma INQ_S: forall n,  (((S n):Q) = n + 1)%Q.\nProof.\n  intros.\n  unfold INQ.\n  change 1 with (inject_Z 1).\n  rewrite <- inject_Z_plus.\n  f_equal.\n  rewrite Nat2Z.inj_succ.\n  omega.\nQed.\n\nLemma INQ_Qeq_0 : (INQ 0 == 0)%Q.\nProof.\n  reflexivity.\nQed.\n\nLemma INQ_Qeq_1 : (INQ 1 == 1)%Q.\nProof.\n  reflexivity.\nQed.\n\nLemma INQ_eq_1 : (INQ 1 = 1)%Q.\nProof.\n  reflexivity.\nQed.\n\nLtac clear_INQ :=\n  repeat rewrite INQ_S in *;\n  try change (INQ 0) with (0 # 1) in *.\n\nLtac solve_nonzero :=\n  match goal with\n  | |- context [INQ ?n] =>\n    generalize (INQ_nonneg n);\n    let m := fresh n in\n    let H := fresh \"H\" in\n    remember (INQ n) as m eqn:H;\n    clear H; try clear n;\n    intros\n  end.\n\nLemma Max_pown_0 : forall n : nat , (2 ^ n > 0)%nat.\nProof.\n  intros. induction n.\n  + simpl. omega.\n  + rewrite Nat.pow_succ_r'. omega.\nQed.\n\nLemma Max_powan_0 : forall (a n : nat), (a > 0)%nat -> (a ^ n > 0)%nat.\nProof.\n  intros. induction n.\n  + simpl. omega.\n  + rewrite Nat.pow_succ_r'. \n    apply Nat.mul_pos_pos ; auto.\nQed.\n\nLemma Max_pown_0Q : forall n : nat , (INQ (2 ^ n) > 0)%Q.\nProof.\n  intros.\n  rewrite <- INQ_Qeq_0.\n  apply INQ_lt. apply Max_pown_0.\nQed.\n  \nLemma Max_powSn_1 : forall n : nat , ( n >= 1 -> 2 ^ n > 1)%nat.\nProof.\n  intros.\n  induction n.\n  - inversion H.\n  - simpl. rewrite <- plus_n_O. \n    apply Nat.lt_le_trans with (m := (1 + 2 ^ n) % nat).\n    simpl. apply lt_n_S. apply Max_pown_0. \n    apply plus_le_compat_r. \n    pose proof Max_pown_0 n.\n    apply H0.\nQed.\n  \nLemma Z_le_lt_trans : forall z1 z2 z3 :Z , (z1 <= z2 -> z2 < z3 -> z1 < z3)%Z.\nProof.\n  intros.\n  apply Zle_compare in H.\n  destruct ((z1 ?= z2) % Z) eqn : En.\n  - apply Z.compare_eq in En. rewrite En. auto.\n  - apply Zcompare_Lt_trans with z2 ; auto.\n  - inversion H.\nQed.\n  \nLemma Z_to_nat_le : forall z : Z , (inject_Z z <= Z.to_nat z)%Q.\nProof.\n  intros.\n  destruct z ; unfold Qle.\n  - simpl. omega.\n  - remember (Z.pos p) as p0.\n    simpl.\n    rewrite !Zmult_1_r.\n    pose proof Zle_0_pos p.\n    pose proof Z2Nat.id (Z.pos p) H.\n    rewrite <- Heqp0 in H0. omega.\n  - simpl.\n    apply Z.lt_le_incl.\n    apply Zlt_neg_0.\nQed.\n  \nLemma eps_lemma1 : forall eps : Q , (eps > 0)%Q -> { n : nat | (INQ (n) > 1 / eps)%Q}.\nProof.\n  intros.\n  exists (S (Z.to_nat (Qceiling (1 / eps)))).\n  rewrite INQ_S.\n  apply Qlt_le_trans with (y := (inject_Z (Qceiling (1/eps)) + 1)%Q).\n  - pose proof  (Qle_ceiling (1/eps)).\n    rewrite Qplus_comm.\n    rewrite <- Qplus_0_l at 1.\n    apply Qplus_lt_le_compat ; auto.\n    unfold Qlt. simpl. omega.\n  - apply Qplus_le_l.\n    remember (Qceiling (1 / eps)) as z.\n    apply Z_to_nat_le.\nQed.\n  \nLemma eps_lemma_total : forall eps : Q , { n : nat | (INQ (n) > 1 / eps)%Q}.\nProof.\n  intros.\n  destruct (Q_dec 0 eps).\n  - destruct s. \n    + apply eps_lemma1. auto.\n    + exists O.\n      rewrite INQ_Qeq_0.\n      rewrite <- Qopp_opp.\n      rewrite <- (Qopp_opp 0).\n      apply Qopp_lt_compat.\n      apply Qopp_lt_compat in q as goal.\n      assert ( -0 == 0). { reflexivity. }\n      rewrite H in *.\n      apply Qinv_lt_0_compat in goal.\n      assert (/ - eps == - (1 / eps)). \n      { field. unfold not. intros. rewrite H0 in q. apply (Qlt_irrefl 0). auto. }\n      rewrite <- H0. auto.\n  - exists 1%nat. rewrite <- q. \n    rewrite INQ_Qeq_1.\n    unfold Qlt. simpl. omega. \nQed.\n\nDefinition eps_arrow_nat(eps : Q) : nat.\n  pose proof eps_lemma_total eps.\n  inversion H.\n  apply x.\nDefined.\n  \nLemma eps_arrow_correct : forall eps : Q , (INQ(eps_arrow_nat eps ) >  1 / eps)%Q.\nProof.\n  intros.\n  unfold eps_arrow_nat.\n  destruct (eps_lemma_total eps).\n  auto.\nQed.\n  \nLemma eps_arrow_pro : forall eps : Q, (eps > 0)%Q -> (INQ(eps_arrow_nat eps) > 0)%Q.\nProof.\n  intros.\n  pose proof eps_arrow_correct eps.\n  remember (eps_arrow_nat eps) as n0.\n  apply Qlt_trans with (y := 1 / eps) ; auto.\n  assert (1 / eps == / eps). { field. unfold not. intros. rewrite H1 in H.\n         apply (Qlt_irrefl 0). auto. }\n  rewrite H1.\n  apply Qinv_lt_0_compat ; auto.\nQed.", "meta": {"author": "QinxiangCao", "repo": "ClassicalReal", "sha": "60860e58d1ca98251ce7fdd01a7175bb8c560dd8", "save_path": "github-repos/coq/QinxiangCao-ClassicalReal", "path": "github-repos/coq/QinxiangCao-ClassicalReal/ClassicalReal-60860e58d1ca98251ce7fdd01a7175bb8c560dd8/QArith_ext/INQ_libs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7266163288811676}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_NCdistinct.\nRequire Import ProofCheckingEuclid.lemma_collinear_ABC_ABD_ABE_CDE.\nRequire Import ProofCheckingEuclid.lemma_collinear_ABC_ABD_BCD.\nRequire Import ProofCheckingEuclid.lemma_collinearorder.\nRequire Import ProofCheckingEuclid.lemma_s_n_col_ncol.\nRequire Import ProofCheckingEuclid.lemma_s_ncol_n_col.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_NChelper :\n\tforall A B C P Q,\n\tnCol A B C ->\n\tCol A B P ->\n\tCol A B Q ->\n\tneq P Q ->\n\tnCol P Q C.\nProof.\n\tintros A B C P Q.\n\tintros nCol_A_B_C.\n\tintros Col_A_B_P.\n\tintros Col_A_B_Q.\n\tintros neq_P_Q.\n\n\tpose proof (lemma_NCdistinct _ _ _ nCol_A_B_C) as (neq_A_B & _ & _ & neq_B_A & _ & _).\n\tpose proof (lemma_s_ncol_n_col _ _ _ nCol_A_B_C) as n_Col_A_B_C.\n\n\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_A_B_P Col_A_B_Q neq_A_B) as Col_B_P_Q.\n\tpose proof (lemma_collinearorder _ _ _ Col_A_B_P) as (Col_B_A_P & _ & _ & _ & _).\n\tpose proof (lemma_collinearorder _ _ _ Col_A_B_Q) as (Col_B_A_Q & _ & _ & _ & _).\n\n\tpose proof (lemma_collinear_ABC_ABD_BCD _ _ _ _ Col_B_A_P Col_B_A_Q neq_B_A) as Col_A_P_Q.\n\tpose proof (lemma_collinearorder _ _ _ Col_A_P_Q) as (_ & Col_P_Q_A & _ & _ & _).\n\n\tpose proof (lemma_collinearorder _ _ _ Col_B_P_Q) as (_ & Col_P_Q_B & _ & _ & _).\n\n\tassert (~ Col P Q C) as n_Col_P_Q_C.\n\t{\n\t\tintros Col_P_Q_C.\n\n\t\tpose proof (lemma_collinear_ABC_ABD_ABE_CDE _ _ _ _ _ neq_P_Q Col_P_Q_A Col_P_Q_B Col_P_Q_C) as Col_A_B_C.\n\n\t\tcontradict Col_A_B_C.\n\t\texact n_Col_A_B_C.\n\t}\n\tpose proof (lemma_s_n_col_ncol _ _ _ n_Col_P_Q_C) as nCol_P_Q_C.\n\n\texact nCol_P_Q_C.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_NChelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7266163226258281}}
{"text": "\n\n(** 以下代码会预先导入关于整数的定义、证明以及自动证明指令。*)\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Psatz.\nLocal Open Scope Z.\n\n(** * 归纳类型的又一个例子：二叉树 *)\n\n\nInductive tree: Type :=\n| Leaf: tree\n| Node (l: tree) (v: Z) (r: tree): tree.\n\n(** 这个定义说的是，一棵二叉树要么是一棵空树_[Leaf]_，要么有一棵左子树、有一棵右\n    子树外加有一个根节点整数标号。Coq中，我们往往可以使用递归函数定义归纳类型元\n    素的性质。Coq中定义递归函数时使用的关键字是_[Fixpoint]_。下面的两个定义通过\n    递归定义了二叉树的高度和节点个数。*)\n\nFixpoint tree_height (t: tree): Z :=\n  match t with\n  | Leaf => 0\n  | Node l v r => Z.max (tree_height l) (tree_height r) + 1\n  end.\nFixpoint tree_size (t: tree): Z :=\n  match t with\n  | Leaf => 0\n  | Node l v r => tree_size l + tree_size r + 1\n  end.\n\n(** Coq中也可以定义树到树的函数。下面的_[tree_reverse]_函数把二叉树进行了左右翻转。 *)\n\nFixpoint tree_reverse (t: tree): tree :=\n  match t with\n  | Leaf => Leaf\n  | Node l v r => Node (tree_reverse r) v (tree_reverse l)\n  end.\n\n(** 下面画出的是一个二叉树左右翻转的例子。如果_[t]_是左边的树，那么\n    _[tree_reverse t]_的计算结果就是右边的树。*)\n\n(**      5                5\n        / \\              / \\\n       3   9            9   3\n          / \\          / \\\n         8  100      100  8     *)\n\n(** 这个例子中的树以及左右翻转的计算结果都可以在Coq中表示出来：*)\n\n(** Coq表示 *)\nExample tree_reverse_example:\n  tree_reverse\n    (Node\n       (Node Leaf 3 Leaf)\n       5\n       (Node (Node Leaf 8 Leaf) 9 (Node Leaf 100 Leaf)))\n  =\n  Node\n    (Node (Node Leaf 100 Leaf) 9 (Node Leaf 8 Leaf))\n    5\n    (Node Leaf 3 Leaf).\nProof. reflexivity. Qed.\n\n(** * 结构归纳法证明 *)\n\n(** 我们接下去将证明一些关于_[tree_height]_，_[tree_size]_与_[tree_reverse]_的基\n    本性质。我们在证明中将会使用的主要方法是归纳法。*)\n\n(** 相信大家都很熟悉自然数集上的数学归纳法。数学归纳法说的是：如果我们要证明某性\n    质_[P]_对于任意自然数_[n]_都成立，那么我可以将证明分为如下两步：*)\n\n(** 奠基步骤：证明_[P 0]_成立；*)\n(** 归纳步骤：证明对于任意自然数_[n]_，如果_[P n]_成立，那么_[P (n + 1)]_也成\n    立。*)\n\n\n(** 对二叉树的归纳证明与上面的数学归纳法稍有不同。具体而言，如果我们要证明某性质\n    _[P]_对于一切二叉树_[t]_都成立，那么我们只需要证明以下两个结论：*)\n\n\n(** 奠基步骤：证明_[P Leaf]_成立；*)\n(** 归纳步骤：证明对于任意二叉树_[l]_ _[r]_以及任意整数标签_[n]_，如果_[P l]_与\n    _[P r]_都成立，那么_[P (Node l n r)]_也成立。*)\n\n(** 这样的证明方法就成为结构归纳法。在Coq中，_[induction]_指令表示：使用结构归纳\n    法。下面是几个证明的例子。*)\n\n\n(** 第一个例子是证明_[tree_size]_与_[tree_reverse]_之间的关系。*)\n\nLemma reverse_size: forall t,\n  tree_size (tree_reverse t) = tree_size t.\nProof.\n  intros.\n  induction t.\n  (** 上面这个指令说的是：对_[t]_结构归纳。Coq会自动将原命题规约为两个证明目标，\n      即奠基步骤和归纳步骤。为了增加Coq证明的可读性，我们推荐大家使用bullet记号\n      把各个子证明过程分割开来，就像一个一个抽屉或者一个一个文件夹一样。Coq中可\n      以使用的bullet标记有：_[+ - * ++ -- **]_ ...*)\n  + simpl.\n    (** 第一个分支是奠基步骤。这个_[simpl]_指令表示将结论中用到的递归函数根据定\n        义化简。*)\n    reflexivity.\n  + simpl.\n    (** 第二个分支是归纳步骤。我们看到证明目标中有两个前提_[IHt1]_以及_[IHt2]_。\n        在英文中_[IH]_表示induction hypothesis的缩写，也就是归纳假设。在这个证明\n        中_[IHt1]_与_[IHt2]_分别是左子树_[t1]_与右子树_[t2]_的归纳假设。 *)\n\n    rewrite IHt1.\n    rewrite IHt2.\n    lia.\n    (** 这个_[lia]_指令的全称是linear integer arithmatic，可以用来自动证明关于整\n        数的线性不等式。*)\nQed.\n\n\n(** 第二个例子很类似，是证明_[tree_height]_与_[tree_reverse]_之间的关系。*)\n\nLemma reverse_height: forall t,\n  tree_height (tree_reverse t) = tree_height t.\nProof.\n  intros.\n  induction t.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHt1.\n    rewrite IHt2.\n    lia.\n    (** 注意：这个_[lia]_指令也是能够处理_[Z.max]_与_[Z.min]_的。*)\nQed.\n\n(** 下面我们将通过重写上面这一段证明，介绍Coq证明语言的一些其他功能。*)\n\nLemma reverse_height_attempt2: forall t,\n  tree_height (tree_reverse t) = tree_height t.\nProof.\n  intros.\n  induction t; simpl.\n  (** 在Coq证明语言中可以用分号将小的证明指令连接起来形成大的证明指令，其中\n      _[tac1 ; tac2]_这个证明指令表示先执行指令_[tac1]_，再对于_[tac1]_生成的每\n      一个证明目标执行_[tac2]_。分号是右结合的。*)\n  + reflexivity.\n  + simpl.\n    lia.\n    (** 此处的_[lia]_指令不仅可以处理结论中的整数线性运算，其自动证明过程中也会\n        使用前提中关于整数线性运算的假设。*)\nQed.\n\n(** 请各位同学证明下面结论。*)\n\nLemma reverse_involutive: forall t,\n  tree_reverse (tree_reverse t) = t.\nProof.\nAdmitted. (** *)\n\n\nLemma reverse_inv: forall t1 t2,\n  tree_reverse t1 = t2 ->\n  t1 = tree_reverse t2.\nProof.\nAdmitted. (** *)\n\n\n\n(** * 字符串 *)\n\n(** 以下代码会预先导入关于ascii码与字符串的定义。*)\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\nLocal Open Scope string.\n\n(** 字符串的定义 *)\n(** 下面Coq代码可以用于查看_[string]_在Coq中的定义。*)\nPrint string.\n(** 查询结果如下。*)\n(**\nInductive string :=\n| EmptyString : string\n| String : ascii -> string -> string. *)\n\n(** 当然，Coq也提供了专门表达字符串的符号。*)\n\n\nCheck EmptyString.\nCheck \"c\".\nCheck \"c\"%char.\nCheck String \"a\"%char (String \"b\"%char EmptyString).\n\n\n(** 查询结果 *)\n(**\n\"\": string\n\"c\": string\n\"c\"%char: ascii\n\"ab\": string\n*)\n\n(** 所以，字符串这样的链状结构其实是树状结构的一种退化情况，也可以用Coq的归纳类\n    型定义。下面我们可以定义字符串的拼接和取反。*)\n\nFixpoint string_app (s1 s2: string): string :=\n  match s1 with\n  | EmptyString => s2\n  | String c s1' => String c (string_app s1' s2)\n  end.\n\nFixpoint string_rev (s: string): string :=\n  match s with\n  | EmptyString => EmptyString\n  | String c s' => string_app (string_rev s') (String c EmptyString)\n  end.\n\n(** 接下来我们就可以证明一些简单的性质。 *)\n\n\n(** 引理_[string_app_assoc]_ *)\nLemma string_app_assoc: forall s1 s2 s3,\n  string_app s1 (string_app s2 s3) =\n  string_app (string_app s1 s2) s3.\nProof.\n  intros.\n  induction s1.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHs1.\n    reflexivity.\nQed.\n\n(** 引理_[string_app_empty_r]_ *)\nLemma string_app_empty_r: forall s,\n  string_app s \"\" = s.\nProof.\n  intros.\n  induction s.\n  + simpl.\n    reflexivity.\n  + simpl.\n    rewrite IHs.\n    reflexivity.\nQed.\n\n(** 下面性质请大家自行证明 *)\nLemma string_rev_app: forall s1 s2,\n  string_rev (string_app s1 s2) =\n  string_app (string_rev s2) (string_rev s1).\nProof.\nAdmitted. (** *)\n\n\n(** * 自然数 *)\n\n(** 将字符串等链状结构进一步退化，就会得到Coq中自然数的定义。*)\n\n\n(** 下面Coq代码可以用于查看_[nat]_在Coq中的定义。*)\nPrint nat.\n(** 查询结果如下。*)\n(**\nInductive nat := O : nat | S: nat -> nat. *)\n\n(** 下面我们在Coq中去定义自然数的加法，并且也试着证明一条基本性质：加法交换律。*)\n\n\n(** 由于Coq的标准库中已经定义了自然数以及自然数的加法。我们开辟一个_[NatDemo]_来\n    开发我们自己的定义与证明。以免与Coq标准库的定义相混淆。*)\nModule NatDemo.\n\n(** 先定义自然数_[nat]_。*)\n\nInductive nat :=\n| O : nat\n| S (n: nat): nat.\n\n(** 再定义自然数加法。*)\n\nFixpoint plus (n m: nat): nat :=\n  match n with\n  | O => m\n  | S n' => S (plus n' m)\n  end.\n\n(** 下面证明加法交换律。*)\n\nTheorem plus_comm: forall n m,\n  plus n m = plus m n.\nProof.\nAdmitted. (** *)\n\nEnd NatDemo.\n\n(** * While + DB语言的语法树 *)\n\n\n\nModule WhileDB.\n\n(** 先定义变量名，我们规定不同的变量名就是不同的字符串。*)\n\nDefinition var_name: Type := string.\n\n(** 再定义二元运算符和一元运算符。*)\n\nInductive binop : Type :=\n  | OOr | OAnd\n  | OLt | OLe | OGt | OGe | OEq | ONe\n  | OPlus | OMinus | OMul | ODiv | OMod.\n\nInductive unop : Type :=\n  | ONot | ONeg.\n\n(** 下面是表达式的抽象语法树。*)\n\nInductive expr : Type :=\n  | ENum (n : Z)\n  | EVar (x : var_name)\n  | EBinop (op: binop) (e1 e2 : expr)\n  | EUnop (op: unop) (e: expr)\n  | EDeref (e: expr)\n  | EMalloc (e: expr)\n  | EReadInt\n  | EReadChar.\n\n(** 下面是程序语句的抽象语法树。*)\n\nInductive com : Type :=\n  | CDecl (x: var_name)\n  | CAss (e1 e2: expr)\n  | CSeq (c1 c2 : com)\n  | CIf (e : expr) (c1 c2 : com)\n  | CWhile (e : expr) (c : com).\n\n(** 下面我们定义一项简单的程序变换：右结合变换。例如，将_[(c1;c2);c3]_变换为\n    _[c1;(c2;c3)]_。*)\n\n(** 首先，这里定义一个辅助函数，该函数假设_[c]_与_[c0]_已经是右结合的，计算\n    _[c; c0]_转换后的结果*)\nFixpoint CSeq_right_assoc (c c0: com): com :=\n  match c with\n  | CSeq c1 c2 => CSeq c1 (CSeq_right_assoc c2 c0)\n  | _ => CSeq c c0\n  end.\n\n(** 现在，可以在_[CSeq_right_assoc]_的基础上定义右结合变换_[right_assoc]_。*)\nFixpoint right_assoc (c: com): com :=\n  match c with\n  | CDecl x => CDecl x\n  | CAss e1 e2 => CAss e1 e2\n  | CSeq c1 c2 => CSeq_right_assoc (right_assoc c1) (right_assoc c2)\n  | CIf e c1 c2 => CIf e (right_assoc c1) (right_assoc c2)\n  | CWhile e c1 => CWhile e (right_assoc c1)\n  end.\n\n\nEnd WhileDB.\n\n", "meta": {"author": "gzqaq", "repo": "CS2612-PLaC", "sha": "fb7be0651785905b60d3e705324175daaadcc96b", "save_path": "github-repos/coq/gzqaq-CS2612-PLaC", "path": "github-repos/coq/gzqaq-CS2612-PLaC/CS2612-PLaC-fb7be0651785905b60d3e705324175daaadcc96b/assigns/assign0916/CoqInductiveType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.9046505421702797, "lm_q1q2_score": 0.726591618855428}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (z : natural) (lf2 : natural) : natural :=\n  plus lf3 (plus z lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj143_coqofml_no9AXh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7265719954347202}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Mathematical structures                                                 *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic LibOperation.\nGeneralizable Variables A B.\n\n(* ********************************************************************** *)\n(** * Monoids *)\n\nRecord monoid_def (A:Type) : Type := monoid_ { \n   monoid_oper : oper2 A;\n   monoid_neutral : A }.\n\nClass Monoid (A:Type) (m:monoid_def A) : Prop := {\n   monoid_assoc_prop : let (o,n) := m in assoc o;\n   monoid_neutral_l_prop : let (o,n) := m in neutral_l o n;\n   monoid_neutral_r_prop : let (o,n) := m in neutral_r o n }.\n\nSection MonoidProp.\nContext {A:Type} {m:monoid_def A}.\nClass Monoid_assoc := {\n  monoid_assoc : assoc (monoid_oper m) }.\nClass Monoid_neutral_l := {\n  monoid_neutral_l : neutral_l (monoid_oper m) (monoid_neutral m) }.\nClass Monoid_neutral_r := {\n  monoid_neutral_r : neutral_r (monoid_oper m) (monoid_neutral m) }.\nEnd MonoidProp.\n\nSection MonoidInst.\nContext {A:Type} {m:monoid_def A} {M:Monoid m}.\nGlobal Instance Monoid_Monoid_assoc : Monoid_assoc (m:=m).\nProof.\n  constructor. destruct M as [U ? ?]. destruct m. simpl. apply U.\nQed.\nGlobal Instance Monoid_Monoid_neutral_l : Monoid_neutral_l (m:=m).\nProof.\n  constructor. destruct M as [? U ?]. destruct m. simpl. apply U.\nQed.\nGlobal Instance Monoid_Monoid_neutral_r : Monoid_neutral_r (m:=m).\nProof.\n  constructor. destruct M as [? ? U]. destruct m. simpl. apply U.\nQed.\nEnd MonoidInst.\n\n", "meta": {"author": "Ayertienna", "repo": "IS5", "sha": "3bfd1b8510f269071d59d77818f8936d194364bc", "save_path": "github-repos/coq/Ayertienna-IS5", "path": "github-repos/coq/Ayertienna-IS5/IS5-3bfd1b8510f269071d59d77818f8936d194364bc/lib/tlc/LibStruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7265719931947267}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (z : natural) (lf2 : natural) : natural :=\n  plus z (plus lf3 lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj103_coqofml_nfMJUD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7265719877451567}}
{"text": "From mathcomp Require Import all_ssreflect.\n(*\n1 依存和\n存在 (∃) は帰納型の特殊な例である．\n*)\nPrint ex.\n(*\nInductive ex (A : Type) (P : A -> Prop) : Prop :=\nex_intro : forall x : A, P x -> ex P.\n*)\n\n(*\nex (fun x:A => P(x)) を exists x:A, P(x) と書いてもいい．\nこの定義を見ると，ex P = ∃x, P(x) は x と P(x) の対でしかない．\n対の第 2 要素に第 1 要素が現れているので，この積を「依存和」という．\n（元々依存のある関数型を定義域を添字とした依存積と見なすなら，\nこちらは A を添字とする直和集合になる）\n既に見ているように，証明の中で依存和を構築する時に，exists という作戦を使う．\n *)\n\nLemma exists_pred x : x > 0 -> exists y, x = S y.\nProof.\ncase x => // n _. (* case: x と同じだが項が読みやすい *)\nby exists n.\nQed.\nPrint exists_pred.\n(*\nexists_pred =\nfun x : nat =>\nmatch x as n return (0 < n -> exists y : nat, n = y.+1) with\n| 0 =>\n  fun H : 0 < 0 =>\n  let H0 : False :=\n    eq_ind (0 < 0) (fun e : bool => if e then False else True) I true H in\n  False_ind (exists y : nat, 0 = y.+1) H0 (* 0 はありえない *)\n| n.+1 =>\nfun _ : 0 < n.+1 => ex_intro (fun y : nat => n.+1 = y.+1) n (erefl n.+1)\nend (* n.+1 のとき n を返す *)\n    : forall x : nat, 0 < x -> exists y : nat, x = y.+1\n*)\nRequire Extraction.\nExtraction exists_pred. (* 何も抽出されない *)\n(*\n上記の ex は Prop に住むものなので，論理式の中でしか使えない．しかし，プログラムの中で\n依存和を使いたい時もある．この時には sig を使う．\n*)\nPrint sig.\n\n(* Inductive sig (A : Type) (P : A -> Prop) : Type :=\n exist : forall x : A, P x -> sig P. *)\n(*\nsig (fun x:T => Px) は {x:T | Px} とも書く．ex と同様に，\n具体的な値は exists で指定する．\nこういう条件付きな値を扱う安全な関数が書ける． \n*)\nDefinition safe_pred x : x > 0 -> {y | x = S y}.\ncase x => // n _. (* exists_pred と同じ *)\nby exists n. (* こちらも exists を使う *)\nDefined. (* 定義を透明にし，計算に使えるようにする *)\n\n(* 証明された関数を OCaml の関数として輸出できる．その場合，Prop の部分が消される．*)\nRequire Extraction.\n\nExtraction safe_pred.\n(** val safe_pred : nat -> nat **)\n(*\nlet safe_pred = function\n| O -> assert false (* absurd case *)\n| S x’ -> x’\n *)\n\n(*\n2 Hint と auto\n証明が冗長になることが多い．auto は簡単な規則で証明を補完しようとする．\n具体的には，autoは 仮定や Hint lem1 lem2 ... で登録した定理を \napplyで適用しようとする．\nこれらを組み合わせて，深さ 5 の項まで作れる (auto n で深さ n にできる)．\ninfo auto で使われたヒントを表示させる事もできる．\nHint Constructors で帰納型を登録すると，各構成子が定理として登録される．また，auto\nusing lem1, lem2, ... で一回だけヒントを追加することもできる．\nauto で定理が適用されるために，全ての変数が定理の結論に現れる必要がある．eauto を使う\nと simple apply が eapply に変わるので，決まらない変数が変数のまま残せる．\nその代わり，可能な導出木が増えるので，探索が中々終わらない場合もある．\n*)\n\n(*\n3 整列の証明\n *)\n\nSection Sort.\n  Variables (A:Set) (le:A->A->bool). (* データ型 A とのその順序 le *)\n  (* 既に整列されたリスト l の中に a を挿入する *)\n  Fixpoint insert a (l: list A) :=\n    match l with\n    | nil => (a :: nil)\n    | b :: l' => if le a b then a :: l else b :: insert a l'\n    end.\n  \n  (* 繰り返しの挿入でリスト l を整列する *)\n  Fixpoint isort (l : list A) : list A :=\n    match l with\n    | nil => nil\n    | a :: l' => insert a (isort l')\n    end.\n  \n  (* le は推移律と完全性をみたす *)\n  Hypothesis le_trans: forall x y z, le x y -> le y z -> le x z.\n  Hypothesis le_total: forall x y, ~~ le x y -> le y x.\n\n  (* le_list x l : x はあるリスト l の全ての要素以下である *)\n  Inductive le_list x : list A -> Prop :=\n  | le_nil : le_list x nil\n  | le_cons : forall y l,\n      le x y -> le_list x l -> le_list x (y::l).\n\n  (* sorted l : リスト l は整列されている *)\n  Inductive sorted : list A -> Prop :=\n  | sorted_nil : sorted nil\n  | sorted_cons : forall a l,\n      le_list a l -> sorted l -> sorted (a::l).\n  \nHint Constructors le_list sorted. (* auto の候補にする *)\nLemma le_list_insert a b l :\nle a b -> le_list a l -> le_list a (insert b l).\nProof.\n  move=> leab; elim => {l} [|c l] /=. info_auto.\n  case: ifPn. info_auto. info_auto.\nQed.\n\nLemma le_list_trans a b l :\nle a b -> le_list b l -> le_list a l.\nProof.\n  move=> leab; elim. info_auto.\n  info_eauto using le_trans. (* 推移律は eauto が必要 *)\nQed.\n\nHint Resolve le_list_insert le_list_trans. (* 補題も候補に加える *)\nTheorem insert_ok a l : sorted l -> sorted (insert a l). Admitted.\nTheorem isort_ok l : sorted (isort l). Admitted.\n\n(* Permutation l1 l2 : リスト l2 は l1 の置換である *)\nInductive Permutation : list A -> list A -> Prop :=\n| perm_nil: Permutation nil nil\n| perm_skip: forall x l l',\n    Permutation l l' -> Permutation (x::l) (x::l')\n| perm_swap: forall x y l, Permutation (y::x::l) (x::y::l)\n| perm_trans: forall l l' l'',\n    Permutation l l' ->\n    Permutation l' l'' -> Permutation l l''.\nHint Constructors Permutation.\n                     \nTheorem Permutation_refl l : Permutation l l. Admitted.\nTheorem insert_perm l a : Permutation (a :: l) (insert a l). Admitted.\nTheorem isort_perm l : Permutation l (isort l). Admitted.\n\n(* 証明付き整列関数 *)\nDefinition safe_isort l : {l'|sorted l' /\\ Permutation l l'}.\nexists (isort l).\nauto using isort_ok, isort_perm.\nDefined.\nPrint safe_isort.\nEnd Sort.\nCheck safe_isort. (* le と必要な補題を与えなければならない *)\nExtraction leq. (* mathcomp の eqType の抽出が汚ない *)\nDefinition leq' m n := if m - n is 0 then true else false.\nExtraction leq'. (* こちらはすっきりする *)\n\nLemma leq'E m n : leq' m n = (m <= n).\nProof. rewrite /leq' /leq. by case: (m-n). Qed.\n\nLemma leq'_trans m n p : leq' m n -> leq' n p -> leq' m p.\nProof. rewrite !leq'E; apply leq_trans. Qed.\n\nLemma leq'_total m n : ~~ leq' m n -> leq n m. Admitted.\n\nDefinition isort_leq := safe_isort nat leq' leq'_trans leq'_total.\nEval compute in proj1_sig (isort_leq (3 :: 1 :: 2 :: 0 :: nil)).\n= [:: 0; 1; 2; 3] : seq nat\nExtraction \"isort.ml\" isort_leq.\n\n(* 練習問題 3.1 \n1. Admitted を Proof に変え，証明を完成させよ．\n2. le list を以下のように一般化できる.\nInductive All (P : A -> Prop) : list A -> Prop :=\n| All_nil : All P nil\n| All_cons : forall y l, P y -> All P l -> All P (y::l).\nこのとき，All (le a) l が le list a l と同じ意味になる．\nこちらを使うように証明を修正せよ．*)\n", "meta": {"author": "nagaet", "repo": "garrigue-lecture-2020_AW", "sha": "e8d108a151d785629e8f29e035572038a8d23a6d", "save_path": "github-repos/coq/nagaet-garrigue-lecture-2020_AW", "path": "github-repos/coq/nagaet-garrigue-lecture-2020_AW/garrigue-lecture-2020_AW-e8d108a151d785629e8f29e035572038a8d23a6d/ssrcoq07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7265580524192422}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\n(** \"_Algorithms are the computational content of proofs_.\"\n    --Robert Harper *)\n\n(** We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types like [nat] or [list] and functions over\n    these types, and for _proving_ properties of these programs, using\n    inductive propositions (like [eveni]), implication, universal\n    quantification, and the like.  So far, we have mostly treated\n    these mechanisms as if they were quite separate, and for many\n    purposes this is a good way to think.  But we have also seen hints\n    that Coq's programming and proving facilities are closely related.\n    For example, the keyword [Inductive] is used to declare both data\n    types and propositions, and [->] is used both to describe the type\n    of functions on data and logical implication.  This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are\n    almost the same thing.  In this chapter we will study how this\n    works.\n\n    We have already seen the fundamental idea: provability in Coq is\n    represented by concrete _evidence_.  When we construct the proof\n    of a basic proposition, we are actually building a tree of\n    evidence, which can be thought of as a data structure.\n\n    If the proposition is an implication like [A -> B], then its proof\n    will be an evidence _transformer_: a recipe for converting\n    evidence for A into evidence for B.  So at a fundamental level,\n    proofs are simply programs that manipulate evidence. *)\n\n(** Question: If evidence is data, what are propositions themselves?\n\n    Answer: They are types! *)\n\n(** Look again at the formal definition of the [eveni] property.  *)\n\nPrint eveni.\n(* ==>\n  Inductive eveni : nat -> Prop :=\n    | eveni_0 : eveni 0\n    | eveni_SS : forall n, eveni n -> eveni (S (S n)).\n*)\n\n(** Suppose we introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can say \"is a proof of.\"  For example,\n    the second line in the definition of [eveni] declares that [eveni_0 : eveni\n    0].  Instead of \"[eveni_0] has type [eveni 0],\" we can say that \"[eveni_0]\n    is a proof of [eveni 0].\" *)\n\n(** This pun between types and propositions -- between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\" -- is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation:\n\n                 propositions  ~  types\n                 proofs        ~  data values\n\n    See [Wadler 2015] (in Bib.v) for a brief history and up-to-date\n    exposition. *)\n\n(** Many useful insights follow from this connection.  To begin with,\n    it gives us a natural interpretation of the type of the [eveni_SS]\n    constructor: *)\n\nCheck eveni_SS\n  : forall n,\n    eveni n ->\n    eveni (S (S n)).\n\n(** This can be read \"[eveni_SS] is a constructor that takes two\n    arguments -- a number [n] and evidence for the proposition [eveni\n    n] -- and yields evidence for the proposition [eveni (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [eveni]. *)\n\nTheorem eveni_4 : eveni 4.\nProof.\n  apply eveni_SS. apply eveni_SS. apply eveni_0. Qed.\n\n(** As with ordinary data values and functions, we can use the [Print]\n    command to see the _proof object_ that results from this proof\n    script. *)\n\nPrint eveni_4.\n(* ===> eveni_4 = eveni_SS 2 (eveni_SS 0 eveni_0)\n      : eveni 4  *)\n\n(** Indeed, we can also write down this proof object directly,\n    without the need for a separate proof script: *)\n\nCheck (eveni_SS 2 (eveni_SS 0 eveni_0))\n  : eveni 4.\n\n(** The expression [eveni_SS 2 (eveni_SS 0 eveni_0)] can be thought of as\n    instantiating the parameterized constructor [eveni_SS] with the\n    specific arguments [2] and [0] plus the corresponding proof\n    objects for its premises [eveni 2] and [eveni 0].  Alternatively, we can\n    think of [eveni_SS] as a primitive \"evidence constructor\" that, when\n    applied to a particular number, wants to be further applied to\n    evidence that this number is even; its type,\n\n      forall n, eveni n -> eveni (S (S n)),\n\n    expresses this functionality, in the same way that the polymorphic\n    type [forall X, list X] expresses the fact that the constructor\n    [nil] can be thought of as a function from types to empty lists\n    with elements of that type. *)\n\n(** We saw in the [Logic] chapter that we can use function\n    application syntax to instantiate universally quantified variables\n    in lemmas, as well as to supply evidence for assumptions that\n    these lemmas impose.  For instance: *)\n\nTheorem eveni_4': eveni 4.\nProof.\n  apply (eveni_SS 2 (eveni_SS 0 eveni_0)).\nQed.\n\n(* ################################################################# *)\n(** * Proof Scripts *)\n\n(** The _proof objects_ we've been discussing lie at the core of how\n    Coq operates.  When Coq is following a proof script, what is\n    happening internally is that it is gradually constructing a proof\n    object -- a term whose type is the proposition being proved.  The\n    tactics between [Proof] and [Qed] tell it how to build up a term\n    of the required type.  To see this process in action, let's use\n    the [Show Proof] command to display the current state of the proof\n    tree at various points in the following tactic proof. *)\n\nTheorem eveni_4'' : eveni 4.\nProof.\n  Show Proof.\n  apply eveni_SS.\n  Show Proof.\n  apply eveni_SS.\n  Show Proof.\n  apply eveni_0.\n  Show Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with a\n    \"hole\" (indicated by [?Goal] here, and so on), and it knows what\n    type of evidence is needed to fill this hole.\n\n    Each hole corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    evidence we've built is stored in the global context under the name\n    given in the [Theorem] command. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand, as shown above. Then we can use [Definition]\n    (rather than [Theorem]) to give a global name directly to this\n    evidence. *)\n\nDefinition eveni_4''' : eveni 4 :=\n  eveni_SS 2 (eveni_SS 0 eveni_0).\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint eveni_4.\n(* ===> eveni_4    =   eveni_SS 2 (eveni_SS 0 eveni_0) : eveni 4 *)\nPrint eveni_4'.\n(* ===> eveni_4'   =   eveni_SS 2 (eveni_SS 0 eveni_0) : eveni 4 *)\nPrint eveni_4''.\n(* ===> eveni_4''  =   eveni_SS 2 (eveni_SS 0 eveni_0) : eveni 4 *)\nPrint eveni_4'''.\n(* ===> eveni_4''' =   eveni_SS 2 (eveni_SS 0 eveni_0) : eveni 4 *)\n\n(** **** Exercise: 2 stars, standard (eight_is_even)\n\n    Give a tactic proof and a proof object showing that [eveni 8]. *)\n\nTheorem eveni_8 : eveni 8.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nDefinition eveni_8' : eveni 8\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Quantifiers, Implications, Functions *)\n\n(** In Coq's computational universe (where data structures and\n    programs live), there are two sorts of values that have arrows in\n    their types: _constructors_ introduced by [Inductive]ly defined\n    data types, and _functions_.\n\n    Similarly, in Coq's logical universe (where we carry out proofs),\n    there are two ways of giving evidence for an implication:\n    constructors introduced by [Inductive]ly defined propositions,\n    and... functions! *)\n\n(** For example, consider this statement: *)\n\nTheorem eveni_plus4 : forall n, eveni n -> eveni (4 + n).\nProof.\n  intros n H. simpl.\n  apply eveni_SS.\n  apply eveni_SS.\n  apply H.\nQed.\n\n(** What is the proof object corresponding to [eveni_plus4]?\n\n    We're looking for an expression whose _type_ is [forall n, eveni n ->\n    eveni (4 + n)] -- that is, a _function_ that takes two arguments (one\n    number and a piece of evidence) and returns a piece of evidence!\n\n    Here it is: *)\n\nDefinition eveni_plus4' : forall n, eveni n -> eveni (4 + n) :=\n  fun (n : nat) => fun (H : eveni n) =>\n    eveni_SS (S (S n)) (eveni_SS n H).\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah],\" and that Coq treats [4 + n] and [S (S (S (S n)))]\n    as synonyms. Another equivalent way to write this definition is: *)\n\nDefinition eveni_plus4'' (n : nat) (H : eveni n)\n                    : eveni (4 + n) :=\n  eveni_SS (S (S n)) (eveni_SS n H).\n\nCheck eveni_plus4''\n  : forall n : nat,\n    eveni n ->\n    eveni (4 + n).\n\n(** When we view the proposition being proved by [eveni_plus4] as a\n    function type, one interesting point becomes apparent: The second\n    argument's type, [eveni n], mentions the _value_ of the first\n    argument, [n].\n\n    While such _dependent types_ are not found in conventional\n    programming languages, they can be useful in programming too, as\n    the recent flurry of activity in the functional programming\n    community demonstrates. *)\n\n(** Notice that both implication ([->]) and quantification ([forall])\n    correspond to functions on evidence.  In fact, they are really the\n    same thing: [->] is just a shorthand for a degenerate use of\n    [forall] where there is no dependency, i.e., no need to give a\n    name to the type on the left-hand side of the arrow:\n\n           forall (x:nat), nat\n        =  forall (_:nat), nat\n        =  nat -> nat\n*)\n\n(** For example, consider this proposition: *)\n\nDefinition eveni_plus2 : Prop :=\n  forall n, forall (E : eveni n), eveni (n + 2).\n\n(** A proof term inhabiting this proposition would be a function\n    with two arguments: a number [n] and some evidence [E] that [n] is\n    even.  But the name [E] for this evidence is not used in the rest\n    of the statement of [eveni_plus2], so it's a bit silly to bother\n    making up a name for it.  We could write it like this instead,\n    using the dummy identifier [_] in place of a real name: *)\n\nDefinition eveni_plus2' : Prop :=\n  forall n, forall (_ : eveni n), eveni (n + 2).\n\n(** Or, equivalently, we can write it in a more familiar way: *)\n\nDefinition eveni_plus2'' : Prop :=\n  forall n, eveni n -> eveni (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\n(** If we can build proofs by giving explicit terms rather than\n    executing tactic scripts, you may be wondering whether we can\n    build _programs_ using _tactics_ rather than explicit terms.\n    Naturally, the answer is yes! *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n\nPrint add1.\n(* ==>\n    add1 = fun n : nat => S n\n         : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than\n    with [:=] followed by a term.  This tells Coq to enter _proof\n    scripting mode_ to build an object of type [nat -> nat].  Also, we\n    terminate the proof with [Defined] rather than [Qed]; this makes\n    the definition _transparent_ so that it can be used in computation\n    like a normally-defined function.  ([Qed]-defined objects are\n    opaque during computation.)\n\n    This feature is mainly useful for writing functions with dependent\n    types, which we won't explore much further in this book.  But it\n    does illustrate the uniformity and orthogonality of the basic\n    ideas in Coq. *)\n\n(* ################################################################# *)\n(** * Logical Connectives as Inductive Types *)\n\n(** Inductive definitions are powerful enough to express most of the\n    connectives we have seen so far.  Indeed, only universal\n    quantification (with implication as a special case) is built into\n    Coq; all the others are defined inductively.  We'll see these\n    definitions in this section. *)\n\nModule Props.\n\n(* ================================================================= *)\n(** ** Conjunction *)\n\n(** To prove that [P /\\ Q] holds, we must present evidence for both\n    [P] and [Q].  Thus, it makes sense to define a proof object for [P\n    /\\ Q] as consisting of a pair of two proofs: one for [P] and\n    another one for [Q]. This leads to the following definition. *)\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\n\nArguments conj [P] [Q].\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** Notice the similarity with the definition of the [prod] type,\n    given in chapter [Poly]; the only difference is that [prod] takes\n    [Type] arguments, whereas [and] takes [Prop] arguments. *)\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\n\n(** This similarity should clarify why [destruct] and [intros]\n    patterns can be used on a conjunctive hypothesis.  Case analysis\n    allows us to consider all possible ways in which [P /\\ Q] was\n    proved -- here just one (the [conj] constructor). *)\n\nTheorem proj1' : forall P Q,\n    P /\\ Q -> P.\nProof.\n  intros P Q HPQ. destruct HPQ as [HP HQ]. apply HP.\n  Show Proof.\nQed.\n\n(** Similarly, the [split] tactic actually works for any inductively\n    defined proposition with exactly one constructor.  In particular,\n    it works for [and]: *)\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HQ HP]. split.\n    + apply HP.\n    + apply HQ.\nQed.\n\nEnd And.\n\n(** This shows why the inductive definition of [and] can be\n    manipulated by tactics as we've been doing.  We can also use it to\n    build proofs directly, using pattern-matching.  For instance: *)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) : Q /\\ P :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, standard (conj_fact)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Disjunction *)\n\n(** The inductive definition of disjunction uses two constructors, one\n    for each side of the disjunct: *)\n\nModule Or.\n\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\n\nArguments or_introl [P] [Q].\nArguments or_intror [P] [Q].\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** This declaration explains the behavior of the [destruct] tactic on\n    a disjunctive hypothesis, since the generated subgoals match the\n    shape of the [or_introl] and [or_intror] constructors.\n\n    Once again, we can also directly write proof objects for theorems\n    involving [or], without resorting to tactics. *)\n\nDefinition inj_l : forall (P Q : Prop), P -> P \\/ Q :=\n  fun P Q HP => or_introl HP.\n\nTheorem inj_l' : forall (P Q : Prop), P -> P \\/ Q.\nProof.\n  intros P Q HP. left. apply HP.\nQed.\n\nDefinition or_elim : forall (P Q R : Prop), (P \\/ Q) -> (P -> R) -> (Q -> R) -> R :=\n  fun P Q R HPQ HPR HQR =>\n    match HPQ with\n    | or_introl HP => HPR HP\n    | or_intror HQ => HQR HQ\n    end.\n\nTheorem or_elim' : forall (P Q R : Prop), (P \\/ Q) -> (P -> R) -> (Q -> R) -> R.\nProof.\n  intros P Q R HPQ HPR HQR.\n  destruct HPQ as [HP | HQ].\n  - apply HPR. apply HP.\n  - apply HQR. apply HQ.\nQed.\n\nEnd Or.\n\n(** **** Exercise: 2 stars, standard (or_commut')\n\n    Construct a proof object for the following proposition. *)\n\nDefinition or_commut' : forall P Q, P \\/ Q -> Q \\/ P\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Existential Quantification *)\n\n(** To give evidence for an existential quantifier, we package a\n    witness [x] together with a proof that [x] satisfies the property\n    [P]: *)\n\nModule Ex.\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro : forall x : A, P x -> ex P.\n\nNotation \"'exists' x , p\" :=\n  (ex (fun x => p))\n    (at level 200, right associativity) : type_scope.\n\nEnd Ex.\n\n(** This may benefit from a little unpacking.  The core definition is\n    for a type former [ex] that can be used to build propositions of\n    the form [ex P], where [P] itself is a _function_ from witness\n    values in the type [A] to propositions.  The [ex_intro]\n    constructor then offers a way of constructing evidence for [ex P],\n    given a witness [x] and a proof of [P x].\n\n    The notation in the standard library is a slight variant of\n    the above, enabling syntactic forms such as [exists x y, P x y]. *)\n\n(** The more familiar form [exists x, P x] desugars to an expression\n    involving [ex]: *)\n\nCheck ex (fun n => eveni n) : Prop.\n\n(** Here's how to define an explicit proof object involving [ex]: *)\n\nDefinition some_nat_is_even : exists n, eveni n :=\n  ex_intro eveni 4 (eveni_SS 2 (eveni_SS 0 eveni_0)).\n\n(** **** Exercise: 2 stars, standard (ex_eveni_Sn)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition ex_eveni_Sn : ex (fun n => eveni (S n))\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** [True] and [False] *)\n\n(** The inductive definition of the [True] proposition is simple: *)\n\nInductive True : Prop :=\n  | I : True.\n\n(** It has one constructor (so every proof of [True] is the same, so\n    being given a proof of [True] is not informative.) *)\n\n(** **** Exercise: 1 star, standard (p_implies_true)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition p_implies_true : forall P, P -> True\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(** [False] is equally simple -- indeed, so simple it may look\n    syntactically wrong at first glance! *)\n\nInductive False : Prop := .\n\n(** That is, [False] is an inductive type with _no_ constructors --\n    i.e., no way to build evidence for it. For example, there is\n    no way to complete the following definition such that it\n    succeeds (rather than fails). *)\n\nFail Definition contra : False :=\n  0 = 1.\n\n(** But it is possible to destruct [False] by pattern matching. There can\n    be no patterns that match it, since it has no constructors.  So\n    the pattern match also is so simple it may look syntactically\n    wrong at first glance. *)\n\nDefinition false_implies_zero_eq_one : False -> 0 = 1 :=\n  fun contra => match contra with end.\n\n(** Since there are no branches to evaluate, the [match] expression\n    can be considered to have any type we want, including [0 = 1].\n    Indeed, it's impossible to ever cause the [match] to be evaluated,\n    because we can never construct a value of type [False] to pass to\n    the function. *)\n\n(** **** Exercise: 1 star, standard (ex_falso_quodlibet')\n\n    Construct a proof object for the following proposition. *)\n\nDefinition ex_falso_quodlibet' : forall P, False -> P\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  We can define\n    it ourselves: *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n| eq_refl : forall x, eq x x.\n\nNotation \"x == y\" := (eq x y)\n                       (at level 70, no associativity)\n                     : type_scope.\n\n(** The way to think about this definition (which is just a slight\n    variant of the standard library's) is that, given a set [X], it\n    defines a _family_ of propositions \"[x] is equal to [y],\" indexed\n    by pairs of values ([x] and [y]) from [X].  There is just one way\n    of constructing evidence for members of this family: applying the\n    constructor [eq_refl] to a type [X] and a single value [x : X],\n    which yields evidence that [x] is equal to [x].\n\n    Other types of the form [eq x y] where [x] and [y] are not the\n    same are thus uninhabited. *)\n\n(** We can use [eq_refl] to construct evidence that, for example, [2 =\n    2].  Can we also use it to construct evidence that [1 + 1 = 2]?\n    Yes, we can.  Indeed, it is the very same piece of evidence!\n\n    The reason is that Coq treats as \"the same\" any two terms that are\n    _convertible_ according to a simple set of computation rules.\n\n    These rules, which are similar to those used by [Compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.  *)\n\nLemma four: 2 + 2 == 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove\n    equalities up to now is essentially just shorthand for [apply\n    eq_refl].\n\n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).\n\n    But you can see them directly at work in the following explicit\n    proof objects: *)\n\nDefinition four' : 2 + 2 == 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), []++[x] == x::[]  :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\n(** **** Exercise: 2 stars, standard (equality__leibniz_equality)\n\n    The inductive definition of equality implies _Leibniz equality_:\n    what we mean when we say \"[x] and [y] are equal\" is that every\n    property on [P] that is true of [x] is also true of [y].  *)\n\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x == y -> forall P:X->Prop, P x -> P y.\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (leibniz_equality__equality)\n\n    Show that, in fact, the inductive definition of equality is\n    _equivalent_ to Leibniz equality.  Hint: the proof is quite short;\n    about all you need to do is to invent a clever property [P] to\n    instantiate the antecedent.*)\n\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P:X->Prop, P x -> P y) -> x == y.\nProof.\n(* FILL IN HERE *) Admitted.\n\n(** [] *)\n\nEnd MyEquality.\n\n(* ================================================================= *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves.\n\n    In general, the [inversion] tactic...\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n\n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are\n    two constructors, so two subgoals get generated.  The\n    conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [and], there is\n    only one constructor, so only one subgoal gets generated.  Again,\n    the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal.  The\n    constructor does have two arguments, though, and these can be seen\n    in the context in the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [eq], there is\n    again only one constructor, so only one subgoal gets generated.\n    Now, though, the form of the [eq_refl] constructor does give us\n    some extra information: it tells us that the two arguments to [eq]\n    must be the same!  The [inversion] tactic adds this fact to the\n    context. *)\n\n(* ################################################################# *)\n(** * The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is\n    \"why trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on. *)\n\n(** There are a few additional wrinkles:\n\n    First, since Coq types can themselves be expressions, the checker\n    must normalize these (by using the computation rules) before\n    comparing them.\n\n    Second, the checker must make sure that [match] expressions are\n    _exhaustive_.  That is, there must be an arm for every possible\n    constructor.  To see why, consider the following alleged proof\n    object: *)\n\nFail Definition or_bogus : forall P Q, P \\/ Q -> P :=\n  fun (P Q : Prop) (A : P \\/ Q) =>\n    match A with\n    | or_introl H => H\n    end.\n\n(** All the types here match correctly, but the [match] only\n    considers one of the possible constructors for [or].  Coq's\n    exhaustiveness check will reject this definition.\n\n    Third, the checker must make sure that each recursive function\n    terminates.  It does this using a syntactic check to make sure\n    that each recursive call is on a subexpression of the original\n    argument.  To see why this is essential, consider this alleged\n    proof: *)\n\nFail Fixpoint infinite_loop {X : Type} (n : nat) {struct n} : X :=\n  infinite_loop n.\nFail Definition falso : False := infinite_loop 0.\n\n(** Recursive function [infinite_loop] purports to return a\n    value of any type [X] that you would like.  (The [struct]\n    annotation on the function tells Coq that it recurses on argument\n    [n], not [X].)  Were Coq to allow [infinite_loop], then [falso]\n    would be definable, thus giving evidence for [False].  So Coq rejects\n    [infinite_loop]. *)\n\n(** Note that the soundness of Coq depends only on the\n    correctness of this typechecking engine, not on the tactic\n    machinery.  If there is a bug in a tactic implementation (and this\n    certainly does happen!), that tactic might construct an invalid\n    proof term.  But when you type [Qed], Coq checks the term for\n    validity from scratch.  Only theorems whose proofs pass the\n    type-checker can be used in further proof developments.  *)\n\n(* 2020-10-01 11:26 *)\n", "meta": {"author": "liqing-yang", "repo": "software-foundations", "sha": "99c7633e8e3e8f43b018ed864313e786236301cb", "save_path": "github-repos/coq/liqing-yang-software-foundations", "path": "github-repos/coq/liqing-yang-software-foundations/software-foundations-99c7633e8e3e8f43b018ed864313e786236301cb/LF/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339636614178, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7265580497768938}}
{"text": "(* --------------------------------------------------------------------\n * Copyright (c) - 2006--2012 - IMDEA Software Institute\n * Copyright (c) - 2006--2012 - Inria\n * Copyright (c) - 2006--2012 - Microsoft Coprporation\n *\n * Distributed under the terms of the CeCILL-B-V1 license\n * -------------------------------------------------------------------- *)\n\n\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(************************************************************************\n\n    Definition of the Euler Totient function\n\n*************************************************************************)\nRequire Import ZArith.\nRequire Export Znumtheory.\nRequire Import Tactic.\nRequire Export ZSum.\nRequire Import ZAux.\n\nOpen Scope Z_scope.\n\nDefinition phi n := Zsum 1 (n - 1) (fun x => if rel_prime_dec x n then 1 else 0).\n\nTheorem phi_def_with_0:  \n  forall n, 1< n -> phi n = Zsum 0 (n - 1) (fun x => if rel_prime_dec x n then 1 else 0).\nintros n H; rewrite Zsum_S_left; auto with zarith.\ncase (rel_prime_dec 0 n); intros H2.\ncontradict H2; apply not_rel_prime_0; auto.\nrewrite Zplus_0_l; auto.\nQed.\n\nTheorem phi_pos: forall n, 1 < n -> 0 < phi n.\nintros n H; unfold phi.\ncase (Zle_lt_or_eq 2 n); auto with zarith; intros H1; subst.\nrewrite Zsum_S_left; simpl; auto with zarith.\ncase (rel_prime_dec 1 n); intros H2.\napply Zlt_le_trans with (1 + 0); auto with zarith.\napply Zplus_le_compat_l.\npattern 0 at 1; replace 0 with  ((1 + (n - 1) - 2) * 0); auto with zarith.\nrewrite <- Zsum_c; auto with zarith.\napply Zsum_le; auto with zarith.\nintros x H3;  case (rel_prime_dec x n); auto with zarith.\ncase H2; apply rel_prime_1; auto with zarith.\nrewrite Zsum_nn.\ncase (rel_prime_dec (2 - 1) 2); auto with zarith.\nintros H1; contradict H1; apply rel_prime_1; auto with zarith.\nQed.\n\nTheorem phi_le_n_minus_1: forall n, 1 < n -> phi n <= n - 1.\nintros n H; replace (n-1) with ((1 +  (n - 1) - 1) * 1); auto with zarith.\nrewrite <- Zsum_c; auto with zarith. \nunfold phi; apply Zsum_le; auto with zarith.\nintros x H1; case (rel_prime_dec x n); auto with zarith.\nQed.\n\nTheorem prime_phi_n_minus_1: forall n, prime n -> phi n = n - 1.\nintros n H; replace (n-1) with ((1 +  (n - 1) - 1) * 1); auto with zarith.\nassert (Hu: 1 <= n - 1).\nassert (2 <= n); auto with zarith.\napply prime_le_2; auto.\nrewrite <- Zsum_c; auto with zarith; unfold phi; apply Zsum_ext; auto.\nintros x  (H2, H3); case H; clear H; intros H H1.\ngeneralize (H1 x); case (rel_prime_dec x n); auto with zarith. \nintros H6 H7; contradict H6; apply H7; split; auto with zarith.\nQed.\n\nTheorem phi_n_minus_1_prime: forall n, 1 < n -> phi n = n - 1 -> prime n.\nintros n H H1; case (prime_dec n); auto; intros H2.\nassert (H3: phi n < n - 1); auto with zarith.\nreplace (n-1) with ((1 +  (n - 1) - 1) * 1); auto with zarith.\nassert (Hu: 1 <= n - 1); auto with zarith.\nrewrite <- Zsum_c; auto with zarith; unfold phi; apply Zsum_lt; auto.\nintros x _; case (rel_prime_dec x n); auto with zarith.\ncase not_prime_divide with n; auto.\nintros x (H3, H4); exists x; repeat split; auto with zarith.\ncase (rel_prime_dec x n); auto with zarith.\nintros H5; absurd (x = 1 \\/ x = -1); auto with zarith.\ncase (Zis_gcd_unique  x n x 1); auto.\napply Zis_gcd_intro; auto; exists 1; auto with zarith.\napply Zis_gcd_sym; exact H5.\ncontradict H3; rewrite H1; auto with zarith.\nQed.\n\nTheorem phi_divide_prime: forall n, 1 < n -> (n - 1 | phi n) -> prime n.\nintros n H1 H2; apply  phi_n_minus_1_prime; auto.\napply Zle_antisym.\napply phi_le_n_minus_1; auto.\napply Zdivide_le; auto; auto with zarith.\napply phi_pos; auto.\nQed.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Examples/Indifferentiability/ECurve/PrimalityTest/Euler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7265580459513561}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural :=\n  plus Zero (plus lf1 y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj2010_coqofml_wXbmnT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7265505147135014}}
{"text": "(** * Perm: Basic techniques for permutations and ordering *)\n\n(** Consider these algorithms and data structures:\n - sort a sequence of numbers;\n - finite maps from numbers to (arbitrary-type) data\n - finite maps from any ordered type to (arbitrary-type) data\n - priority queues: finding/deleting the highest number in a set\n\n To prove the correctness of such programs, we need to reason\n about less-than comparisons (for example, on integers) and about\n \"these two sets/sequences have the same contents\".  In this\n chapter, we introduce some techniques for reasoning about:\n - less-than comparisons on natural numbers\n - permutations (rearrangements of lists)\n Then, in later chapters, we'll apply these proof techniques\n to reasoning about algorithms and data structures.\n *)\n\nRequire Export Coq.Bool.Bool.\nRequire Export Coq.Arith.Arith.\nRequire Export Coq.Arith.EqNat.\nRequire Export Coq.omega.Omega.\nRequire Export Coq.Lists.List. \nExport ListNotations.\nRequire Export Permutation.\n\n(* ################################################################# *)\n(** * The less-than order on the natural numbers *)\n\n(** These [Check] and [Locate] commands remind us about\n  _Propositional_ and the _Boolean_ less-than operators\n  in the Coq standard library. *)\n\nCheck Nat.lt.        (* : nat -> nat -> Prop *)\nCheck lt.             (* : nat -> nat -> Prop *)\nGoal Nat.lt = lt. Proof. reflexivity. Qed. (* They are the same *)\nCheck Nat.ltb.       (* : nat -> nat -> bool *)\nLocate \"_ < _\".  (* \"x < y\" := lt x y *)\nLocate \"<?\".     (* x <? y  := Nat.ltb x y *)\n\n(** We write [x < y] for the Proposition that [x] _is_ less than [y],\n    and we write [x <? y] for the computable _test_ that returns\n    [true] or [false] depending on whether [x<y].  The theorem that\n    [lt] is related in this way to [ltb] is this one: *)\n\nCheck Nat.ltb_lt.\n(* : forall n m : nat, (n <? m) = true <-> n < m *)\n\n(** For some reason, the Coq library has [ <? ] and [ <=? ] \n    notations, but is missing these three: *)\n\nNotation  \"a >=? b\" := (Nat.leb b a)\n                          (at level 70, only parsing) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a)\n                       (at level 70, only parsing) : nat_scope.\nNotation \" a =? b\"  := (beq_nat a b)\n                       (at level 70) : nat_scope.\n\n(* ================================================================= *)\n(** ** Relating [Prop] to [bool] *)\n\n(** The [reflect] relation connects a [Proposition] to a [Boolean]. *)\n\nPrint reflect.\n\n(** That is, [reflect P b] means that [P<->True] if and only if [b=true].\n     The way to use [reflect] is, for each of your operators, make a\n     lemma like these next three:\n*)\n\nLemma beq_reflect : forall x y, reflect (x = y) (x =? y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry.  apply beq_nat_true_iff.\nQed.\n\nLemma blt_reflect : forall x y, reflect (x < y) (x <? y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply Nat.ltb_lt.\nQed.\n\nLemma ble_reflect : forall x y, reflect (x <= y) (x <=? y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply Nat.leb_le.\nQed.\n\n(** Here's an example of how you could use these lemmas.\n    Suppose you have this simple program, [(if a <? 5 then a else 2)],\n    and you want to prove that it evaluates to a number smaller than 6.\n    You can use [blt_reflect] \"by hand\": *)\n    \nExample reflect_example1: forall a, (if a<?5 then a else 2) < 6.\nProof. \n  intros.\n  destruct (blt_reflect a 5) as [H|H].\n  * (* Notice that [H] above the line has a [Prop]ositional\n       fact _related_ to [a<?5]*)\n     omega.  (* More explanation of [omega] later in this chapter. *)\n  * (* Notice that [H] above the line has a a _different_\n       [Prop]ositional fact. *)\n     apply not_lt in H.  (* This step is not necessary,\n          it just makes the hypothesis [H] look pretty *)\n     omega.\nQed.\n\n(** But there's another way to use [blt_reflect], etc: read on. *)\n\n(* ================================================================= *)\n(** ** Some advanced tactical hacking. *)\n(** You may skip ahead to \"Inversion/clear/subst\".\n     Right here, we build some machinery that you'll want to\n     _use_, but you won't need to know how to _build_ it.\n\n    Let's put several of these [reflect] lemmas into a Hint database,\n    called [bdestruct] because we'll use it in our boolean-destruction\n    tactic: *)\n\nHint Resolve blt_reflect ble_reflect beq_reflect : bdestruct.\n\n(** Our high-tech _boolean destruction_ tactic: *)\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n       [ | try first [apply not_lt in H | apply not_le in H]]].\n\n(** Here's a brief example of how to use [bdestruct].  There\n     are more examples later. *)\n\nExample reflect_example2: forall a, (if a<?5 then a else 2) < 6.\nProof. \n  intros.\n  bdestruct (a<?5).  (* instead of: [destruct (blt_reflect a 5) as [H|H]]. *)\n  * (* Notice that [H] above the line has a [Prop]ositional\n       fact _related_ to [a<?5]*)\n     omega.  (* More explanation of [omega] later in this chapter. *)\n  * (* Notice that [H] above the line has a a _different_\n       [Prop]ositional fact. We don't need to apply [not_lt],\n       as [bdestruct] has already done it. *)\n     omega.\nQed.\n\n(* ================================================================= *)\n(** ** Inversion/clear/subst *)\n(** Coq's [inversion H] tactic is so good at extracting information\n    from the hypothesis [H] that [H] becomes completely redundant,\n    and one might as well [clear] it from the goal.  Then, since the\n    [inversion] typically creates some equality facts, why not then\n    [subst] ?   This motivates the following useful tactic, [inv]:  *)\n\nLtac inv H := inversion H; clear H; subst. \n\n(* ================================================================= *)\n(** ** Linear integer inequalities *)\n\n(** In our proofs about searching and sorting algorithms, we \n    sometimes have to reason about the consequences of \n    less-than and greater-than.  Here's a contrived example. *)\n\nModule Exploration1.\n\nTheorem omega_example1: \n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n\n(** Now, there's a hard way to prove this, and an easy way.\n    Here's the hard way. *)\n\n  (* try to remember the name of the lemma about negation and [<=] *)\n  SearchAbout (~ _ <= _ -> _). \n  apply not_le in H0.\n  (* try to remember the name of the transitivity lemma about [>] *)\n  SearchAbout (_ > _ -> _ > _ -> _ > _).  \n  apply gt_trans with j.\n  apply gt_trans with (k-3).\n  (* _OBVIOUSLY_, [k] is greater than [k-3].  But _OOPS_,\n     this is not actually true, because we are talking about\n     natural numbers with \"bogus subtraction.\" *)\nAbort.\n\nTheorem bogus_subtraction: ~ (forall k:nat, k > k - 3).\nProof.\n  (* [intro] introduces exactly one thing, like [intros ?] *)\n  intro.  \n  (* [specialize] applies a hypothesis to an argument *)\n  specialize (H O).  \n  simpl in H. inversion H.\nQed.\n\n(** With bogus subtraction, this omega_example1 theorem even True?\n    Yes it is; let's try again, the hard way, to find the proof. *)\n\nTheorem omega_example1: \n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof. (* try again! *)\n  intros.\n  apply not_le in H0.\n  unfold gt in H0.\n  unfold gt.\n  (* try to remember the name ... *)\n  SearchAbout (_ < _ -> _ <= _ -> _ < _).  \n  apply lt_le_trans with j.\n  apply H.\n  apply le_trans with (k-3).\n  SearchAbout (_ < _ -> _ <= _).\n  apply lt_le_weak.\n  auto.\n  apply le_minus.\nQed.  (* Oof!  That was exhausting and tedious.  *)\n\n(** And here's the easy way. *)\n\nTheorem omega_example2: \n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n  omega.\nQed.\n\n(** Here we have used the [omega] tactic, made available by importing\n    [Coq.omega.Omega] as we have done above.  Omega is an algorithm\n    for integer linear programming, invented in 1991 by William Pugh.\n    Because ILP is NP-complete, we might expect that this algorithm is\n    exponential-time in the worst case, and indeed that's true: if you\n    have [N] equations, it could take [2^N] time.  But in the typical\n    cases that result from reasoning about programs, omega is much\n    faster than that.  Coq's [omega] tactic is an implementation of\n    this algorithm that generates a machine-checkable Coq proof.  It\n    \"understands\" the types Z and nat, and these operators: [<] [=] [>] [<=]\n    [>=] [+] [-] [~], as well as multiplication by small integer\n    literals (such as 0,1,2,3...) and some uses of [\\/] and [/\\].\n\n    Omega does _not_ understand other operators.  It treats things\n    like [a*b] and [f x y] as if they were variables.  That is, it can\n    prove [f x y > a*b -> f x y + 3 >= a*b], in the same way it would\n    prove [u > v -> u+3 >= v]. \n\n    Now let's consider a silly little program: swap the first two\n    elements of a list, if they are out of order. *)\n\nDefinition maybe_swap (al: list nat) : list nat :=\n  match al with\n  | a :: b :: ar => if a >? b then b::a::ar else a::b::ar\n  | _ => al\n  end.\n\nExample maybe_swap_123:\n  maybe_swap [1; 2; 3] = [1; 2; 3].\nProof. reflexivity. Qed.\n\nExample maybe_swap_321:\n  maybe_swap [3; 2; 1] = [2; 3; 1].\nProof. reflexivity. Qed.\n\n(** In this program, we wrote [a>?b] instead of [a>b].  Why is that? *)\n\nCheck (1>2).  (* : Prop *)\nCheck (1>?2). (* : bool *)\n\n(** We cannot compute with elements of [Prop]: we need some kind of\n    constructible (and pattern-matchable) value.  For that we use\n    [bool]. *)\n\nLocate \">?\".  (* a >? b :=  ltb b a *)\n\n(** The name [ltb] stands for \"less-than boolean.\" *)\n\nPrint Nat.ltb.\n(* =  fun n m : nat => S n <=? m : nat -> nat -> bool  *)\nLocate \">=?\".\n\n(** Instead of defining an operator [Nat.geb], the standard library just\n    defines the notation for greater-or-equal-boolean as a\n    less-or-equal-boolean with the arguments swapped. *)\n\nLocate leb.\nPrint leb.\nPrint Nat.leb.  (* The computation to compare natural numbers. *)\n\n(** Here's a theorem: [maybe_swap] is idempotent -- that is, applying it\n    twice gives the same result as applying it once. *)\n\nTheorem maybe_swap_idempotent:\n  forall al, maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros.\n  destruct al as [ | a al].\n  simpl.\n  reflexivity.\n  destruct al as [ | b al].\n  simpl.\n  reflexivity.\n  simpl.\n\n  (** What do we do here?   We must proceed by case analysis on\n     whether a>b. *)\n\n  destruct (b <? a) eqn:H.\n  simpl.\n  destruct (a <? b) eqn:H0.\n\n  (** Now what?  Look at the hypotheses [H: b<a] and [H0: a<b]\n      above the line. They can't both be true.  In fact, [omega]\n      \"knows\" how to prove that kind of thing.  Let's try it: *)\n\n  try omega.\n\n  (** [omega] didn't work, because it operates on comparisons in [Prop],\n      such as [a>b]; not upon comparisons yielding bool, such as [a>?b].\n      We need to convert these comparisons to [Prop], so that we can use\n      [omega].\n\n      Actually, we don't \"need\" to.  Instead, we could reason directly\n      about these operations in [bool].  But that would be even more\n      tedious than the [omega_example1] proof.  Therefore: let's set up\n      some machinery so that we can use [omega] on boolean tests. *)\n\nAbort.\n\n(** Let's try again, a new way: *)\n\nTheorem maybe_swap_idempotent:\n  forall al, maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros.\n  destruct al as [ | a al].\n  simpl.\n  reflexivity.\n  destruct al as [ | b al].\n  simpl.\n  reflexivity.\n  simpl.\n\n  (** This is where we left off before. Now, watch: *)\n\n  destruct (blt_reflect b a).   (* THIS LINE *)\n  (* Notice that [b<a] is above the line as a Prop, not a bool.\n     Now, comment out THIS LINE, and uncomment THAT LINE.  *)\n  (* bdestruct (b <? a).    (* THAT LINE *) *)\n  (* THAT LINE, with [bdestruct], does the same thing as THIS LINE. *)\n* (* case b<a *)\n  simpl.\n  bdestruct (a <? b).\n  omega.\n\n  (** The [omega] tactic noticed that above the line we have an\n      arithmetic contradiction.  Perhaps it seems wasteful to bring\n      out the \"big gun\" to shoot this flea, but really, it's easier\n      than remembering the names of all those lemmas about\n      arithmetic! *)\n\n  reflexivity.\n* (* case a >= b *)\n  simpl.\n  bdestruct (b <? a).\n  omega.\n  reflexivity.\nQed.\n\n(** Moral of this story: When proving things about a program that uses\n    boolean comparisons [(a <? b)], use [bdestruct].  Then use\n    [omega].  Let's review that proof without all the comments. *)\n\nTheorem maybe_swap_idempotent':\n  forall al, maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros.\n  destruct al as [ | a al].\n  simpl.\n  reflexivity.\n  destruct al as [ | b al].\n  simpl.\n  reflexivity.\n  simpl.\n  bdestruct (b <? a).\n* \n  simpl.\n  bdestruct (a <? b).\n  omega.\n  reflexivity.\n*\n  simpl.\n  bdestruct (b <? a).\n  omega.\n  reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Permutations *)\n\n(** Another useful fact about [maybe_swap] is that it doesn't add or\n    remove elements from the list: it only reorders them.  We can say\n    that the output list is a _permutation_ of the input.  The Coq\n    [Permutation] library has an inductive definition of permutations,\n    along with some lemmas about them. *)\n\nLocate Permutation. (* Inductive Coq.Sorting.Permutation.Permutation *)\nCheck Permutation. (*  : forall {A : Type}, list A -> list A -> Prop *)\n\n(** We say \"list [al] is a permutation of list [bl]\",\n     written [Permutation al bl], if the elements of [al] can be \n     reordered (without insertions or deletions) to get the list [bl]. *)\n\nPrint Permutation. \n(*\n Inductive Permutation {A : Type} : list A -> list A -> Prop :=\n    perm_nil : Permutation [] []\n  | perm_skip : forall (x : A) (l l' : list A),\n                Permutation l l' -> \n                Permutation (x :: l) (x :: l')\n  | perm_swap : forall (x y : A) (l : list A),\n                Permutation (y :: x :: l) (x :: y :: l)\n  | perm_trans : forall l l' l'' : list A,\n                 Permutation l l' -> \n                 Permutation l' l'' -> \n                 Permutation l l''.\n*)\n\n(** You might wonder, \"is that really the right definition?\"  And\n    indeed, it's important that we get a right definition, because\n    [Permutation] is going to be used in the specification of\n    correctness of our searching and sorting algorithms.  If we have\n    the wrong specification, then all our proofs of \"correctness\" will\n    be useless.\n\n    It's not obvious that this is indeed the right specification of\n    permutations. (It happens to be true, but it's not obvious!)  In\n    order to gain confidence that we have the right specification, we\n    should use this specification to prove some properties that we\n    think permutations ought to have. *)\n\n(** **** Exercise: 2 stars (Permutation_properties)  *)\n(** Think of some properties of the [Permutation] relation and write\n    them down informally in English, or a mix of Coq and English.\n    Here are four to get you started:\n     - 1. If [Permutation al bl], then [length al = length bl].\n     - 2. If [Permutation al bl], then [Permutation bl al].\n     - 3. [[1;1]] is NOT a permutation of [[1;2]].\n     - 4. [[1;2;3;4]] IS a permutation of [[3;4;2;1]]. \n\n   YOUR ASSIGNMENT: Add three more properties. Write them here: *)\n\n(** Now, let's examine all the theorems in the Coq library about\n    permutations: *)\n\nSearchAbout Permutation.  (* Browse through the results of this query! *)\n\n(** Which of the properties that you wrote down above have already\n    been proved as theorems by the Coq library developers?  Answer\n    here:\n\n*)\n(** [] *)\n\n(** Let's use the permutation rules in the library to prove the\n    following theorem. *)\n    \nExample butterfly: forall b u t e r f l y : nat,\n  Permutation ([b;u;t;t;e;r]++[f;l;y]) ([f;l;u;t;t;e;r]++[b;y]).\nProof.\n intros.\n (* Just to illustrate a method, let's group [u;t;t;e;r] together: *)\n change [b;u;t;t;e;r] with ([b]++[u;t;t;e;r]).\n change [f;l;u;t;t;e;r] with ([f;l]++[u;t;t;e;r]).\n remember [u;t;t;e;r] as utter. \n clear Hequtter.\n (* Next, let's cancel [utter] from both sides.  In order to do that,\n    we need to bring [utter] to the beginning of each list. *)\nCheck app_assoc.\n  rewrite <- app_assoc.\n  rewrite <- app_assoc.\nCheck perm_trans.\n  apply perm_trans with (utter ++ [f;l;y] ++ [b]).\n  rewrite (app_assoc utter [f;l;y]).\nCheck Permutation_app_comm.\n  apply Permutation_app_comm.\n eapply perm_trans.\n 2: apply Permutation_app_comm.\n  rewrite <- app_assoc.\nSearch (Permutation (_++_) (_++_)).\n apply Permutation_app_head.\n (* Now that [utter] is utterly removed from the goal, let's cancel [f;l]. *)\n eapply perm_trans.\n 2: apply Permutation_app_comm.\n simpl.\nCheck perm_skip.\n apply perm_skip.\n apply perm_skip.\nSearch (Permutation (_::_) (_::_)).\n apply perm_swap.\nQed.\n\n(** That example illustrates a general method for proving\n  permutations involving cons [::] and append [++].  \n  You identify some portion appearing in both sides;\n  you bring that portion to the front on each side using\n  lemmas such as [Permutation_app_comm] and [perm_swap],\n  with generous use of [perm_trans].  Then, you use\n  [perm_skip] to cancel a single element, or [Permutation_app_head]\n  to cancel an append-chunk. *)\n\n(** **** Exercise: 3 stars (permut_example)  *)\n(** Use the permutation rules in the library (see the [SearchAbout],\n    above) to prove the following theorem.  These [Check] commands\n   are a hint about what lemmas you'll need. *)\n\nCheck perm_skip.\nCheck Permutation_refl.\nCheck Permutation_app_comm.\nCheck app_assoc.\n\nExample permut_example: forall (a b: list nat),\n  Permutation (5::6::a++b) ((5::b)++(6::a++[])).\nProof.\n (* After you cancel the [5], then bring the [6] to the front... *)\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (not_a_permutation)  *)\n(** Prove that [[1;1]] is not a permutation of [[1;2]].\n    Hints are given as [Check] commands. *)\n\nCheck Permutation_cons_inv.\nCheck Permutation_length_1_inv.\n\nExample not_a_permutation:\n  ~ Permutation [1;1] [1;2].\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Back to [maybe_swap].  We prove that it doesn't lose or gain\n   any elements, only reorders them. *)\n\nTheorem maybe_swap_perm: forall al,\n  Permutation al (maybe_swap al).\nProof.\n  (* WORKED IN CLASS *)\n  intros.\n  destruct al as [ | a al].\n  simpl. apply Permutation_refl.\n  destruct al as [ | b al].\n  simpl. apply Permutation_refl.\n  simpl.\n  bdestruct (a>?b).\n  apply perm_swap.\n  apply Permutation_refl.\nQed.\n\n(** Now let us specify functional correctness of [maybe_swap]:\n    it rearranges the elements in such a way that the first is\n    less-or-equal than the second. *)\n\nDefinition first_le_second (al: list nat) : Prop :=\n  match al with\n  | a::b::_ => a <= b\n  | _ => True\n  end.\n\nTheorem maybe_swap_correct: forall al,\n    Permutation al (maybe_swap al) \n    /\\ first_le_second (maybe_swap al).\nProof.\n  intros.\n  split.\n  apply maybe_swap_perm.\n  (* WORKED IN CLASS *)\n  destruct al as [ | a al].\n  simpl. auto.\n  destruct al as [ | b al].\n  simpl. auto.\n  simpl.\n  bdestruct (b <? a).\n  simpl.\n  omega.\n  simpl.\n  omega.\nQed.\n\nEnd Exploration1.\n\n(* ################################################################# *)\n(** * Summary: Comparisons and permutations *)\n\n(** To prove correctness of algorithms for sorting and searching,\n  we'll reason about comparisons and permutations using the tools\n  developed in this chapter.  The [maybe_swap] program is a tiny\n  little example of a sorting program.  The proof style in\n  [maybe_swap_correct] will be applied (at a larger scale) in\n  the next few chapters. *)\n\n(** **** Exercise: 2 stars (Forall_perm)  *)\n(** To close, a useful utility lemma.  Prove this by induction;\n  but is it induction on [al], or on [bl], or on [Permutation al bl],\n  or on [Forall f al]  ? *)\n\nTheorem Forall_perm: forall {A} (f: A -> Prop) al bl,\n  Permutation al bl ->\n  Forall f al -> Forall f bl.\nProof. \n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** $Date: 2017-05-18 12:44:19 -0400 (Thu, 18 May 2017) $ *)\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/SF/vfa/Perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.8991213664574069, "lm_q1q2_score": 0.7265504930830897}}
{"text": "Require Import ZArith.\n\nLemma eqb_refl :\n  forall (n : nat), (n =? n) = true.\nProof.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  assumption.\nQed.\n\nLemma eqb_symm :\n  forall (m n : nat),\n  (n =? m) = (m =? n).\nProof.\n  intro m.\n  induction m.\n  induction n.\n  simpl.\n  reflexivity.\n  reflexivity.\n  induction n.\n  reflexivity.\n  apply IHm with (n := n).\nQed.\n\nLemma eqb_true_iff (m n : nat) :\n  (m =? n) = true <-> m = n.\nProof.\n  split.\n  revert n.\n  induction m.\n  induction n.\n  intro.\n  reflexivity.\n  intro.\n  discriminate H.\n  induction n.\n  intro.\n  discriminate H.\n  intro.\n  apply f_equal with (f := S).\n  apply IHm with (n := n).\n  assumption.\n  intro.\n  rewrite H.\n  apply eqb_refl.\nQed.\n\nLemma leb_refl :\n  forall (n : nat), (n <=? n) = true.\nProof.\n  induction n.\n  reflexivity.\n  assumption.\nQed.\n\nLemma ltb_or_leb :\n  forall (m n : nat),\n  (n <? m) = true \\/ (m <=? n) = true.\nProof.\n  induction m.\n  induction n.\n  right.\n  reflexivity.\n  right.\n  reflexivity.\n  induction n.\n  left.\n  reflexivity.\n  destruct IHm with (n := n).\n  left.\n  assumption.\n  right.\n  assumption.\nQed.\n\nLemma ltb_compare_dec (m n : nat) :\n  (m <? n) = true \\/ (n <? m) = true \\/ m = n.\nProof.\n  revert n.\n  induction m.\n  induction n.\n  right.\n  right.\n  reflexivity.\n  left.\n  reflexivity.\n  induction n.\n  right.\n  left.\n  reflexivity.\n  destruct IHm with (n := n).\n  left.\n  assumption.\n  destruct H.\n  right.\n  left.\n  assumption.\n  right.\n  right.\n  apply f_equal with (f := S).\n  assumption.\nQed.\n\nLemma nat_compare_ltb (m n : nat) :\n  (m <? n) = true <-> Nat.compare m n = Lt.\nProof.\n  revert n.\n  induction m.\n  induction n.\n  split ; intro ; discriminate H.\n  split ; intro ; reflexivity.\n  induction n.\n  split ; intro ; discriminate H.\n  apply IHm.\nQed.\n\nLemma nat_compare_gtb (m n : nat) :\n  (n <? m) = true <-> Nat.compare m n = Gt.\nProof.\n  revert n.\n  induction m.\n  induction n ; split ; intro ; discriminate H.\n  induction n.\n  split ; intro ; reflexivity.\n  apply IHm.\nQed.\n\nLemma nat_compare_eq (n : nat) :\n  Nat.compare n n = Eq.\nProof.\n  induction n.\n  reflexivity.\n  apply IHn.\nQed.\n\nLemma leb_trans :\n  forall (m n p: nat),\n    (m <=? n) = true -> (n <=? p) = true -> (m <=? p) = true.\nProof.\n  induction m.\n  simpl.\n  reflexivity.\n\n  destruct n.\n  simpl.\n  intros.\n  discriminate H.\n\n  destruct p. \n  simpl.\n  intros.\n  discriminate H0.\n  simpl.\n  apply IHm.\nQed.\n\nLemma leb_antisymm :\n  forall (m n : nat),\n  (m <=? n) = true ->\n  (n <=? m) = true ->\n  m = n.\nProof.\n  induction m.\n  induction n.\n  intros.\n  reflexivity.\n  intro.\n  simpl.\n  intro.\n  discriminate H0.\n\n  induction n.\n  simpl.\n  intro.\n  discriminate H.\n\n  simpl.\n  intros.\n  apply f_equal with (f := S).\n  apply IHm with (n := n).\n  assumption.\n  assumption.\nQed.\n\nLemma leb_succ :\n  forall (n : nat),\n    (n <=? (S n)) = true.\nProof.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  assumption.\nQed.\n\nLemma ltb_is_neqb :\n  forall (m n : nat),\n  (m <? n) = true ->\n  (m =? n) = false.\nProof.\n  induction m.\n  induction n.\n  unfold Nat.ltb.\n  simpl.\n  intro.\n  discriminate H.\n  intro.\n  simpl.\n  reflexivity.\n\n  induction n.\n  intro.\n  simpl.\n  reflexivity.\n  unfold Nat.ltb.\n  simpl.\n  intro.\n  apply IHm with (n := n).\n  assumption.\nQed.\n\nLemma ltb_is_neqb2 :\n  forall (m n : nat),\n  (m <? n) = true ->\n  (n =? m) = false.\nProof.\n  induction m.\n  induction n.\n  unfold Nat.ltb.\n  simpl.\n  intro.\n  discriminate H.\n  intro.\n  simpl.\n  reflexivity.\n\n  induction n.\n  intro.\n  simpl.\n  reflexivity.\n  unfold Nat.ltb.\n  simpl.\n  intro.\n  apply IHm with (n := n).\n  assumption.\nQed.\n\n\nLemma ltb_antisymm :\n  forall (m n : nat),\n  (m <? n) = true ->\n  (n <? m) = false.\nProof.\n  induction m.\n  induction n.\n  intro.\n  unfold Nat.ltb.\n  simpl.\n  reflexivity.\n  intro.\n  unfold Nat.ltb.\n  simpl.\n  reflexivity.\n\n  induction n.\n  unfold Nat.ltb.\n  simpl.\n  intro.\n  discriminate H.\n  unfold Nat.ltb.\n  simpl.\n  intro.\n  apply IHm with (n := n).\n  assumption.\nQed.\n\nLemma ltb_leb :\n  forall (m n : nat),\n  (n <? m) = false <->\n  (m <=? n) = true.\nProof.\n  split.\n  unfold Nat.ltb.\n  revert m.\n  induction n.\n  induction m.\n  intro.\n  simpl.\n  reflexivity.\n  simpl.\n  intro.\n  discriminate H.\n\n  induction m.\n  intro.\n  simpl.\n  reflexivity.\n  intro.\n  simpl.\n  apply IHn with (m := m).\n  simpl in H.\n  assumption.\n\n  revert m.\n  induction n.\n  induction m.\n  intro.\n  simpl.\n  reflexivity.\n  simpl.\n  intro.\n  discriminate H.\n\n  induction m.\n  intro.\n  simpl.\n  reflexivity.\n  intro.\n  simpl.\n  apply IHn with (m := m).\n  simpl in H.\n  assumption.\nQed.\n\n\nLemma leb_ltb :\n  forall (m n : nat),\n  (n <=? m) = false <->\n  (m <? n) = true.\nProof.\n  split.\n  unfold Nat.ltb.\n  revert m.\n  induction n.\n  induction m.\n  discriminate.\n  discriminate.\n\n  induction m.\n  intro.\n  simpl.\n  reflexivity.\n  intro.\n  simpl.\n  apply IHn with (m := m).\n  simpl in H.\n  assumption.\n\n  revert m.\n  induction n.\n  induction m.\n  discriminate.\n  discriminate.\n  induction m.\n  intro.\n  simpl.\n  reflexivity.\n  intro.\n  simpl.\n  apply IHn with (m := m).\n  simpl in H.\n  assumption.\nQed.\n\n\nLemma leb_max_l (m n : nat) :\n  m <=? Nat.max m n = true.\nProof.\n  revert n.\n  induction m.\n  induction n.\n  reflexivity.\n  reflexivity.\n  induction n.\n  unfold Nat.max.\n  apply leb_refl.\n  apply IHm with (n := n).\nQed.\n\nLemma leb_max_r (m n : nat) :\n  n <=? Nat.max m n = true.\nProof.\n  revert m.\n  induction n.\n  induction m.\n  reflexivity.\n  reflexivity.\n  induction m.\n  apply leb_refl.\n  apply IHn with (m := m).\nQed.\n\nLemma leb_plus_simpl (m n c : nat) :\n  (m <=? n) = true -> (m + c <=? n + c) = true.\nProof.\n  induction c.\n  intro.\n  rewrite Nat.add_0_r.\n  rewrite Nat.add_0_r.\n  assumption.\n  rewrite Nat.add_comm with (m := S c) (n := m).\n  rewrite Nat.add_comm with (m := S c) (n := n).\n  intro.\n  simpl Nat.add.\n  simpl Nat.leb.\n  rewrite Nat.add_comm with (m := m) (n := c).\n  rewrite Nat.add_comm with (m := n) (n := c).\n  apply IHc.\n  assumption.\nQed.\n\nLemma leb_plus (m1 m2 n1 n2 : nat) :\n  (m1 <=? m2) = true -> (n1 <=? n2) = true -> m1 + n1 <=? m2 + n2 = true.\nProof.\n  intros.\n  apply leb_trans with (n := m1 + n2).\n  rewrite Nat.add_comm with (m := n1) (n := m1).\n  rewrite Nat.add_comm with (m := n2) (n := m1).\n  apply leb_plus_simpl.\n  assumption.\n  apply leb_plus_simpl.\n  assumption.\nQed.\n\nLemma rec_init :\n  forall (P : nat -> Prop),\n  (forall (n : nat), P n -> P (S n)) ->\n  forall (m n : nat), (m <=? n) = true -> P m -> P n.\nProof.\n  intros P H m n.\n  revert P H n.\n\n  induction m.\n  intros.\n  induction n.\n  assumption.\n  apply H.\n  apply IHn.\n  assumption.\n\n  induction n.\n  intro.\n  discriminate H0.\n\n  intros.\n  apply IHm with (P := fun i => P (S i)).\n  intro.\n  apply H with (n := S n0).\n  simpl in H0.\n  assumption.\n  assumption.\nQed.\n\nLemma z_integrity (m n : Z) :\n  (Z.mul m n = Z.zero) <-> (m = Z.zero) \\/ (n = Z.zero).\nProof.\n  split.\n  revert n.\n  induction m.\n  intros.\n  left.\n  reflexivity.\n  intros.\n  right.\n  induction n.\n  reflexivity.\n  simpl Z.mul in H.\n  discriminate H.\n  simpl Z.mul in H.\n  discriminate H.\n\n  intros.\n  induction n.\n  right.\n  reflexivity.\n  simpl Z.mul in H.\n  discriminate H.\n  simpl Z.mul in H.\n  discriminate H.\n\n  intro.\n  destruct H.\n  rewrite H.\n  simpl Z.mul.\n  reflexivity.\n  rewrite H.\n  induction m.\n  reflexivity.\n  reflexivity.\n  reflexivity.\nQed.\n\nImport Z.\n\nLemma excluded_middle_nat (m n : nat) :\n  m = n \\/ m <> n.\nProof.\n  revert n.\n  induction m.\n  induction n.\n  left.\n  reflexivity.\n  right.\n  discriminate.\n  induction n.\n  right.\n  discriminate.\n  destruct IHm with (n := n).\n  left.\n  apply f_equal with (f := S).\n  assumption.\n  right.\n  injection.\n  assumption.\nQed.\n\n", "meta": {"author": "TabetSalwa", "repo": "2.7.2-polynomials", "sha": "78bcea3ccdf0b614223266cf867b6954dc704dbf", "save_path": "github-repos/coq/TabetSalwa-2.7.2-polynomials", "path": "github-repos/coq/TabetSalwa-2.7.2-polynomials/2.7.2-polynomials-78bcea3ccdf0b614223266cf867b6954dc704dbf/Nat_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7264832236495657}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import NZAxioms NZBase NZAdd.\n\nModule Type NZMulProp (Import NZ : NZAxiomsSig')(Import NZBase : NZBaseProp NZ).\nInclude NZAddProp NZ NZBase.\n\nTheorem mul_0_r : forall n, n * 0 == 0.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_0_r\".  \nnzinduct n; intros; now nzsimpl.\nQed.\n\nTheorem mul_succ_r : forall n m, n * (S m) == n * m + n.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_succ_r\".  \nintros n m; nzinduct n. now nzsimpl.\nintro n. nzsimpl. rewrite succ_inj_wd, <- add_assoc, (add_comm m n), add_assoc.\nnow rewrite add_cancel_r.\nQed.\n\nHint Rewrite mul_0_r mul_succ_r : nz.\n\nTheorem mul_comm : forall n m, n * m == m * n.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_comm\".  \nintros n m; nzinduct n. now nzsimpl.\nintro. nzsimpl. now rewrite add_cancel_r.\nQed.\n\nTheorem mul_add_distr_r : forall n m p, (n + m) * p == n * p + m * p.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_add_distr_r\".  \nintros n m p; nzinduct n. now nzsimpl.\nintro n. nzsimpl. rewrite <- add_assoc, (add_comm p (m*p)), add_assoc.\nnow rewrite add_cancel_r.\nQed.\n\nTheorem mul_add_distr_l : forall n m p, n * (m + p) == n * m + n * p.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_add_distr_l\".  \nintros n m p.\nrewrite (mul_comm n (m + p)), (mul_comm n m), (mul_comm n p).\napply mul_add_distr_r.\nQed.\n\nTheorem mul_assoc : forall n m p, n * (m * p) == (n * m) * p.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_assoc\".  \nintros n m p; nzinduct n. now nzsimpl.\nintro n. nzsimpl. rewrite mul_add_distr_r.\nnow rewrite add_cancel_r.\nQed.\n\nTheorem mul_1_l : forall n, 1 * n == n.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_1_l\".  \nintro n. now nzsimpl'.\nQed.\n\nTheorem mul_1_r : forall n, n * 1 == n.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_1_r\".  \nintro n. now nzsimpl'.\nQed.\n\nHint Rewrite mul_1_l mul_1_r : nz.\n\nTheorem mul_shuffle0 : forall n m p, n*m*p == n*p*m.\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_shuffle0\".  \nintros n m p. now rewrite <- 2 mul_assoc, (mul_comm m).\nQed.\n\nTheorem mul_shuffle1 : forall n m p q, (n * m) * (p * q) == (n * p) * (m * q).\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_shuffle1\".  \nintros n m p q. now rewrite 2 mul_assoc, (mul_shuffle0 n).\nQed.\n\nTheorem mul_shuffle2 : forall n m p q, (n * m) * (p * q) == (n * q) * (m * p).\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_shuffle2\".  \nintros n m p q. rewrite (mul_comm p). apply mul_shuffle1.\nQed.\n\nTheorem mul_shuffle3 : forall n m p, n * (m * p) == m * (n * p).\nProof. hammer_hook \"NZMul\" \"NZMul.NZMulProp.mul_shuffle3\".  \nintros n m p. now rewrite mul_assoc, (mul_comm n), mul_assoc.\nQed.\n\nEnd NZMulProp.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/NatInt/NZMul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7264832027372374}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) : natural :=\n  plus Zero (Succ lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj63_coqofml_PuDfqi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7264776473760419}}
{"text": "Require Import Relations.\nSection leibniz.\n Variable A : Set.\n \n Set Implicit Arguments.\n\n Definition leibniz (a b:A) : Prop := forall P:A -> Prop, P a -> P b.\n\n Theorem leibniz_sym : symmetric A leibniz.\n Proof.\n  unfold symmetric, leibniz; intros a b H Q.\n  apply H; trivial.\n Qed.\n\n Theorem leibniz_refl : reflexive A leibniz. \n Proof.\n  unfold reflexive, leibniz; auto.\n Qed.\n\n\n\n Theorem leibniz_trans : transitive A leibniz.\n Proof.\n  unfold transitive.\n  intros x y z Hxy Hyz; unfold leibniz; intros.\n  apply Hyz.\n  apply Hxy; assumption.\n Qed.\n\n\n\n\n Hint Resolve leibniz_trans leibniz_sym leibniz_refl: sets. \n\n Theorem leibniz_equiv : equiv A leibniz.\n Proof.\n  unfold equiv; auto with sets.\n Qed.\n\n\n Theorem leibniz_least :\n  forall R:relation A, reflexive A R -> inclusion A leibniz R.\n Proof.\n  unfold inclusion, leibniz; intros R H x y H0.\n  apply H0.\n  apply H.\n Qed.\n\n\n Theorem leibniz_eq : forall a b:A, leibniz a b -> a = b.\n Proof.\n  intros.\n  apply H.\n  trivial.\n Qed.\n\n Theorem eq_leibniz : forall a b:A, a = b -> leibniz a b.\n Proof.\n  intros a b e; rewrite e; unfold leibniz; auto.\n Qed.\n\n Theorem leibniz_ind :\n  forall (x:A) (P:A -> Prop), P x -> forall y:A, leibniz x y -> P y.\n Proof.\n  intros.\n  apply H0.\n  assumption.\n Qed.\n\n Set Strict Implicit.\nUnset Implicit Arguments.\nEnd leibniz.\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/depprod/SRC/leibniz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.72641097869751}}
{"text": "Require Import List.\nRequire Import Bool.\n\nInductive nat : Type :=\n| Z : nat\n| S : nat -> nat.\n\nFixpoint add_nat (m n : nat): nat :=\n  match m with\n  | Z => n\n  | S m => S (add_nat m n)\n  end.\n\n\nLemma add_1 : forall m n : nat, S (add_nat n m) = add_nat n (S m).\nProof.\n  intros.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHn.\n  simpl.\n  auto.\nQed.\n  \n\nTheorem add_commutes : forall m n : nat, add_nat m n = add_nat n m.\nProof.\n  intros.\n  induction m.\n  simpl.\n  induction n.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite <- IHn.\n  reflexivity.\n  simpl.\n  rewrite -> IHm.\n  apply add_1.\nQed.\n\n\nTheorem reflex: forall A : Prop, A -> A.\nProof.\n  intros.\n  assumption.\nQed.\n\n\nTheorem and_commutes: forall A B: Prop, A /\\ B -> B /\\ A.\nProof.\n  intros.\n  elim H.\n  split.\n  assumption.\n  assumption.\nQed.\n\nTheorem and_intro: forall A B: Prop, A -> B -> A /\\ B.\nProof.\n  intros.\n  split; auto.\nQed.\n\nLemma tt: forall a b: nat, add_nat a (S b) = S (add_nat a b).\nProof.\n  intros a b.\n  rewrite -> add_commutes.\n  simpl.\n  rewrite -> add_commutes.\n  reflexivity.\nQed.  \n\n\n\nTheorem add_assoc_1 : forall a b c: nat, S (add_nat b (add_nat a c)) = S (add_nat a (add_nat b c)).\nProof.\n  intros a b c.\n  induction b.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHb.\n  symmetry.\n  assert ( H : add_nat a (S (add_nat b c)) = S (add_nat a (add_nat b c)) ).\n  apply tt.\n  rewrite -> H.\n  reflexivity.\nQed.\n  \n\n\nTheorem add_assoc : forall a b c: nat,  add_nat (add_nat a b) c = add_nat a (add_nat b c).\nProof.\n  intros a b c.\n  symmetry.\n  induction a.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite -> IHa.\n  reflexivity.\nQed.\n\nTheorem demorgan1 : forall A B : Prop, (~ A) \\/ (~ B) -> ~ (A /\\ B).\nProof.\n  intuition eauto.\nQed.\n\nAxiom axiom_of_choice: forall P: Prop, P \\/ (~ P) <-> True.\n  \n\nAxiom aa: forall x: Type, forall P : Type -> Prop, (P x) \\/ (~ (P x)) <-> True.\n\nTheorem absorption: forall P Q: Prop, (P \\/ (P /\\ Q)) <-> P.\nProof.\n  intros P Q.\n  split.\n  intros H.\n  elim H.\n  intros H0.\n  assumption.\n  intros H0.\n  elim H0.\n  intros H1 H2.\n  assumption.\n  intros H.\n  left.\n  assumption.\nQed.\n\n(* Multiplication *)\nFixpoint mult (m n: nat) :=\n  match m with\n  | Z => Z\n  | (S m) => add_nat n (mult m n)\n  end.\n\n\n  \nLemma lem_mul1: forall a b: nat, add_nat b (mult b a) = mult b (S a).\nProof.\n  intros a b.\n  simpl.\n  induction b.\n  simpl.\n  reflexivity.\n  simpl.\n  rewrite <- IHb.\n  apply add_assoc_1.\nQed.\n  \nTheorem mult_comm: forall a b: nat, mult a b = mult b a.\nProof.\n  intros a b.\n  induction a.\n  simpl.\n  induction b; simpl; auto.\n  simpl.\n  rewrite -> IHa.\n  apply lem_mul1.\nQed.\n\n\nLemma tt1: forall m n : nat, mult m (S n) = add_nat m (mult n m).\nProof.\n  intros m n.\n  simpl.\n  induction m; simpl; auto.\n  assert (Z = mult n Z).\n  rewrite <- mult_comm; simpl; auto.\n  assumption.\n  rewrite -> IHm.\n  symmetry.\n  rewrite -> mult_comm.\n  simpl.\n  rewrite <- mult_comm.\n  apply add_assoc_1.\nQed.\n\n\nLemma tty: forall a b m n:nat, add_nat (add_nat a m) (add_nat b n)\n                        = add_nat (add_nat a b) (add_nat m n).\nProof.\n  intros a b m n.\n  rewrite -> add_assoc.\n  assert (H : (add_nat m (add_nat b n)) = (add_nat (add_nat b n) m)).\n  rewrite -> add_commutes.\n  reflexivity.\n  rewrite -> H.\n  clear H.\n  assert (H : (add_nat (add_nat b n) m) = (add_nat b (add_nat n m))).\n  rewrite -> add_assoc.\n  reflexivity.\n  rewrite -> H.\n  clear H.\n  rewrite <- add_assoc.\n  assert (H : (add_nat n m) = (add_nat m n)).\n  rewrite <- add_commutes.\n  reflexivity.\n  rewrite -> H.\n  reflexivity.\nQed.\n  \nTheorem mul_assoc: forall a b c:nat, mult a (add_nat b c) = add_nat (mult a b) (mult a c).\nProof.\n  intros a b c.\n  induction a; simpl; auto.\n  rewrite -> IHa.\n  symmetry.\n  rewrite <- tt1; rewrite <- mult_comm.\n  rewrite <- add_commutes.\n  rewrite <- tt1; rewrite <- mult_comm.\n  simpl.\n  rewrite <- add_commutes.\n  apply tty.\nQed.\n\nTheorem nat_cong: forall x y: nat, forall (f : nat -> nat), (x = y) -> (f x) = (f y).\nProof.\n  intros x y f H.\n  rewrite H.\n  reflexivity.\nQed.\n\nFixpoint geq (x y : nat) : Prop :=\n                  match x with\n                  | Z => True\n                  | S x => geq x y\n                  end.\n\n\nTheorem geq_trans: forall x y z: nat, geq x y -> geq y z -> geq x z.\nProof.\n  intros x y z H H0.\n  induction x; simpl; auto.\nQed.\n\nInductive exp : Type -> Type :=\n| Const : forall T, T -> exp T\n| Pair : forall T1 T2, exp T1 -> exp T2 -> exp (T1 * T2)\n| Eq : forall T, exp T -> exp T -> exp bool.\n\nCheck 2+3.\nCheck (cons 2 nil).\n\nInductive List {A : Set}: Set :=\n| n : List \n| c : A -> List  -> List .\n\nCheck c (S Z) (n).\n\nSection Vector.\nInductive Vec (A: Set) : nat -> Set :=\n| VNil : Vec A Z\n| VCons : forall n : nat, A -> Vec A n -> Vec A (S n).\n\nArguments VCons [A] [n].\nArguments VNil [A].\n\nCheck VCons 2 (VCons 1 VNil).\nEnd Vector.\n\nInductive eqsat {A : Set} (f g : A -> A) : Type :=\n  feqg : forall x : A, (f x = g x) -> eqsat f g.\n\nDefinition f (A B C : bool): bool :=\n  (A && B) || ((B && C) && (B ||C)).\n\nDefinition g (A B C :bool) : bool :=\n  B && (A ||C).\n\nLemma fgsat : forall a b c: bool, eqsat (f a b) (g a b).\nProof.\n  intros a b c.\n  refine (feqg (f a b) (g a b) c _).\n  destruct a, b, c; simpl; auto.\nQed.", "meta": {"author": "amal029", "repo": "cgals_coq_semantic_equivalence", "sha": "4d030a845efc8792088e2985366884fa7f8432ab", "save_path": "github-repos/coq/amal029-cgals_coq_semantic_equivalence", "path": "github-repos/coq/amal029-cgals_coq_semantic_equivalence/cgals_coq_semantic_equivalence-4d030a845efc8792088e2985366884fa7f8432ab/tests/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7263928258077327}}
{"text": "Set Printing Universes.\nSet Universe Polymorphism.\n\nModule LC.\n\nDefinition boolean := forall A, A -> A -> A.\nDefinition true : boolean := fun A t f => t.\nDefinition false : boolean := fun A t f => f.\n\nDefinition not : boolean -> boolean :=\n  fun b => fun A t f => b A f t.\n\nDefinition and : boolean -> boolean -> boolean :=\n  fun l r => fun A t f => l A (r A t f) f.\n\nDefinition or : boolean -> boolean -> boolean :=\n  fun l r => fun A t f => l A t (r A t f).\n\nSection boolean_examples.\n  Variables (A: Type) (t f:A).\n  Example true_ex : true A t f = t.\n  Proof. trivial. Qed.\n\n  Example false_ex : false A t f = f.\n  Proof. trivial. Qed.\n\n  Example not_t : not false = true.\n  Proof. trivial. Qed.\n\n  Example not_f : not true = false.\n  Proof. trivial. Qed.\n\n  Example and_t_t : and true true = true.\n  Proof. trivial. Qed.\n\n  Example and_t_f : and true false = false.\n  Proof. trivial. Qed.\n\n  Example and_f_t : and false true = false.\n  Proof. trivial. Qed.\n\n  Example and_f_f : and false false = false.\n  Proof. trivial. Qed.\n\n  Example or_t_t : or true true = true.\n  Proof. trivial. Qed.\n  \n  Example or_t_f : or true false = true.\n  Proof. trivial. Qed.\n  \n  Example or_f_t : or false true = true.\n  Proof. trivial. Qed.\n  \n  Example or_f_f : or false false = false.\n  Proof. trivial. Qed.\nEnd boolean_examples.\n\nDefinition church := forall A, (A -> A) -> A -> A.\n\nDefinition zero : church := fun A (f:A->A) (x:A) => x.\nDefinition one : church := fun A (f:A->A) (x:A) => f x.\nDefinition two : church := fun A (f:A->A) (x:A) => f (f x).\nDefinition three : church := fun A (f:A->A) (x:A) => f (f (f x)).\nDefinition four : church := fun A (f:A->A) (x:A) => f (f (f (f x))).\nDefinition five : church := fun A (f:A->A) (x:A) => f (f (f (f (f x)))).\n\nDefinition succ : church -> church :=\n  fun (n: church) => fun A (f: A->A) (x: A) => f (n A f x).\n\nDefinition plus : church -> church -> church :=\n  fun m n => fun A (f: A->A) (x: A) => m A f (n A f x).\n\nDefinition plus' : church -> church -> church :=\n  fun m n => m church succ n.\n\nDefinition mult : church -> church -> church :=\n  fun m n => fun A (f: A->A) (x: A) => m A (n A f) x.\n  \nDefinition iszero : church -> boolean :=\n  fun n: church => n boolean (fun _ => false) true.\n\nFixpoint nat_to_church (n: nat): church :=\n  match n with\n    | 0 => zero\n    | S x => succ (nat_to_church x)\n  end.\n\nNotation \"<| n |>\" := (nat_to_church n).\n\nSection church_examples.\n  Example succ_0 : succ zero = one.\n  Proof. trivial. Qed.\n\n  Example succ_1 : succ one = two.\n  Proof. trivial. Qed.\n\n  Example succ_2 : succ two = three.\n  Proof. trivial. Qed.\n\n  Example succ_3 : succ three = four.\n  Proof. trivial. Qed.\n\n  Example plus_0_N : forall (n: church), plus zero n = n.\n  Proof. trivial. Qed.\n\n  Example plus_N_0 : forall (n: church), plus n zero = n.\n  Proof. trivial. Qed.\n\n  Example plus_1_1 : plus one one = two.\n  Proof. trivial. Qed.\n\n  Example plus_2_2 : plus two two = four.\n  Proof. trivial. Qed.\n\n  Example mult_0_N : forall (n: church), mult zero n = zero.\n  Proof. trivial. Qed.\n\n  Example mult_N_0 : forall (n: church), mult n zero = zero.\n  Proof. \n  (* type of n is too weak *)\n  Admitted.\n\n  Example mult_1_N : forall (n: church), mult one n = n.\n  Proof. trivial. Qed.\n\n  Example mult_N_1 : forall (n: church), mult n one = n.\n  Proof. trivial. Qed.\n\n  Example mult2_plus : forall (n: church), mult two n = plus n n.\n  Proof. trivial. Qed.\n\n  Example mult_n2_plus : forall (n: church), mult n two = plus n n.\n  Proof.\n  (* type of n is too weak *)\n  Admitted.\n\n  Example zero_iszero : iszero zero = true.\n  Proof. trivial. Qed.\n\n  Example one_iszero : iszero one = false.\n  Proof. trivial. Qed.\n\n  Example two_iszero : iszero two = false.\n  Proof. trivial. Qed.\n  \n  Lemma nat_succ : forall n:nat, <|S n|> = succ <|n|>.\n  Proof. trivial. Qed.\n\n  Lemma nat_plus : forall n m: nat, plus <|n|> <|m|> = <|n+m|>.\n  Proof.\n    intros n.\n    induction n.\n    + trivial.\n    + intros.\n      simpl.\n      rewrite <- IHn.\n      trivial.\n  Qed.\n  \n  Lemma nat_mult : forall n m: nat, mult <|n|> <|m|> = <|n*m|>.\n  Proof.\n    intros n.\n    induction n.\n    + trivial.\n    + intros.\n      simpl.\n      rewrite <- nat_plus.\n      rewrite <- IHn.\n      trivial.\n  Qed.\nEnd church_examples.\n\nDefinition pair A B := forall C, (A -> B -> C) -> C.\n\nDefinition make_pair {A B} : A -> B -> pair A B :=\n  fun (a:A) (b:B) => fun C p => p a b.\n\nDefinition fst {A B} : pair A B -> A := \n  fun p => p A (fun a b => a).\n\nDefinition snd {A B} : pair A B -> B := \n  fun p => p B (fun a b => b).\n\nSection pair_examples.\n  Example good_fst : forall A B, forall (a:A) (b:B),\n    fst (make_pair a b) = a.\n  Proof. trivial. Qed.\n\n  Example good_snd : forall A B, forall (a:A) (b:B),\n    snd (make_pair a b) = b.\n  Proof. trivial. Qed.\nEnd pair_examples.\n\nDefinition pred_step : pair church church -> pair church church :=\n  fun p => make_pair (snd p) (succ (snd p)).\n\nSection pred_step_examples.\n  Example pred_step_0 : pred_step (make_pair zero zero) = make_pair zero one.\n  Proof. trivial. Qed.\n  Example pred_step_1 : pred_step (make_pair zero one) = make_pair one two.\n  Proof. trivial. Qed.\n  \n  Example pred_step_2 : pred_step (make_pair one two) = make_pair two three.\n  Proof. trivial. Qed.\n  \n  Example pred_step_3 : pred_step (make_pair two three) = make_pair three four.\n  Proof. trivial. Qed.\nEnd pred_step_examples.\n  \nDefinition pred : church -> church :=\n  fun (n: church) => fst (n (pair church church) pred_step (make_pair zero zero)).\n  \nSection pred_examples.\n  Example pred_0 : pred zero = zero.\n  Proof. trivial. Qed.\n  \n  Example pred_1 : pred one = zero.\n  Proof. trivial. Qed.\n  \n  Example pred_2 : pred two = one.\n  Proof. trivial. Qed.\n  \n  Example pred_3 : pred three = two.\n  Proof. trivial. Qed.\n  \n  Example pred_4 : pred four = three.\n  Proof. trivial. Qed.\nEnd pred_examples.\n\nFail Definition sub_ch : church -> church -> church := \n  fun n m => m church pred n.\n\nFail Definition leq_ch : church -> church -> boolean :=\n  fun n m => iszero (sub_ch n m).\n  \nFail Definition le_ch : church -> church -> boolean :=\n  fun n m => leq_ch (succ n) m.\n  \nFail Definition iseq_ch : church -> church -> boolean :=\n  fun n m => and (leq_ch n m) (leq_ch m n).\n  \nDefinition fib_step : pair church church -> pair church church :=\n  fun p => make_pair (snd p) (plus (fst p) (snd p)).\n  \nSection fib_step_examples.\n  Example fib_step_0 : fib_step (make_pair zero one) = make_pair one one.\n  Proof. trivial. Qed.\n  \n  Example fib_step_1 : fib_step (make_pair one one) = make_pair one two.\n  Proof. trivial. Qed.\n  \n  Example fib_step_2 : fib_step (make_pair one two) = make_pair two three.\n  Proof. trivial. Qed.\n  \n  Example fib_step_3 : fib_step (make_pair two three) = make_pair three five.\n  Proof. trivial. Qed.\nEnd fib_step_examples.\n\nDefinition fib : church -> church :=\n  fun n => fst (n (pair church church) fib_step (make_pair zero one)).\n  \nSection fib_examples.\n  Example fib_0 : fib zero = zero.\n  Proof. trivial. Qed.\n  \n  Example fib_1 : fib one = one.\n  Proof. trivial. Qed.\n  \n  Example fib_2 : fib two = one.\n  Proof. trivial. Qed.\n  \n  Example fib_3 : fib three = two.\n  Proof. trivial. Qed.\n  \n  Example fib_4 : fib four = three.\n  Proof. trivial. Qed.\n  \n  Example fib_5 : fib five = five.\n  Proof. trivial. Qed.\nEnd fib_examples.\n\nEnd LC.\n\nRecursive Extraction LC.", "meta": {"author": "KatJon", "repo": "CoqProofs", "sha": "d01345015b6e6d137f7b4f2163ae418bc828c86a", "save_path": "github-repos/coq/KatJon-CoqProofs", "path": "github-repos/coq/KatJon-CoqProofs/CoqProofs-d01345015b6e6d137f7b4f2163ae418bc828c86a/LC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7263928220940951}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Vector theory of real numbers based on ListList\n  author    : ZhengPu Shi\n  date      : 2021.12\n  \n  remark    :\n  1. Use real numbers to represent components.\n  2. it is based on VectorThySig\n*)\n\nRequire Export DepRec.VectorThy.\nRequire Export FieldStruct.\nRequire Export ListListExt RExt.\n\nExport FieldR.\nModule Export VectorThyR := VectorThy FieldR.FieldDefR.\n\nOpen Scope R.\nOpen Scope mat_scope.\nOpen Scope vec_scope.\n\n(* ######################################################################### *)\n(** * Vector theory on Real numbers *)\n\n(* ==================================== *)\n(** ** Vector operations on any dimensions *)\nSection DimAny.\n\n  (** Length of a vector, also known as magnitude, and norm (Euclidean norm). *)\n  \n  (** Vector length squared. Note: it is suitable for compute *)\n  Definition vlen_sqr {n} (v : V n) : R := vdot v v.\n\n  (** Vector length. Note: it is a existential construct, suitable for proofs. *)\n  Definition vlen {n} (v : V n) : R := sqrt (vlen_sqr v).\n\n  (** Normalization of non-zero vector *)\n  Definition vnormalize {n} (v : V n) (H : vnonzero v) : V n :=\n    let k := 1 / (vlen v) in\n      vcmul k v.\n\n  (** The k times of a non-zero vector v is equal to 0, then k must be 0 *)\n  Lemma vcmul_nonzero_eq_zero_imply_k0 : forall {n} (v : V n) k,\n    vnonzero v -> k c* v = vec0 -> k = 0.\n  Proof.\n    intros. destruct v. unfold vnonzero in *. unfold vec0 in *.\n    unfold mcmul in *.\n    apply meq_iff in H0. apply meq_iff_not in H. simpl in *.\n    unfold dmap in *.\n    destruct (Xeqdec k 0); auto.\n    rename mat_data into dl.\n    generalize dependent n.\n    generalize dependent dl. induction dl; intros.\n    - simpl in *; subst; simpl in *. easy.\n    - simpl in *. destruct n; simpl in *. easy.\n      destruct mat_width. inversion mat_height.\n      unfold dlzero in H. simpl in H.\n      rewrite cons_neq_iff in H; try apply list_eq_dec.\n      + destruct H.\n        * (* a != [0] *)\n          destruct a; try easy.\n          assert (x <> 0 /\\ a = []).\n          { apply list_length1_neq. split; auto. }\n          destruct H3.\n          rewrite H5 in H0. simpl in H0. inversion H0.\n  (*         assert ({k = 0} + {k != 0}). apply Aeqdec. *)\n          destruct (Xeqdec k 0); auto.\n          assert (k * x <> 0)%X; try easy.\n          apply Rmult_integral_contrapositive_currified; auto.\n        * (* dl != repeat [A0] n *)\n          apply IHdl with (n:=n); auto.\n          inversion H0. rewrite H6. rewrite H5. auto.\n      + apply Xeqdec.\n  Qed.\n\n  (** Vector parallel (collinear): zero vector is parallel to any vector, \n      or two non-zero vectors has k times relation.\n      \n      Discussion:\n      The mainstream approach is that, the zero vector is parallel and perpendicular \n      to any vector. If we could discuss parallel only for non-zero vector?\n      A explicit reason is that, transitivity of parallel relation is not preserved \n      if contain zero vector.\n\n      Ref: https://www.zhihu.com/question/489006373\n      \n      关于零向量的平行？ 两个方面:\n      a. “平行”或“不平行”是对两个可以被识别的方向的比较，对于零向量，“方向”是不可\n         识别的，或说，是不确定的。从这个角度讲，“平行”这个概念不该被用到评价两个\n         零向量的关系上的。\n      b. 不过，两个零向量是“相等”的，对于向量而言，“相等”这件事包含了大小和方向\n         的相等，这么说来，说两个零向量“方向”相等，也就是“平行”或也是说得通的。\n  *)\n\n  (* 定义1：v0是v1的k倍，或者 v1是v0的k倍。*)\n  Definition vparallel_ver1 {n} (v0 v1 : V n) : Prop :=\n    exists k, (v0 = k c* v1 \\/ v1 = k c* v0).\n\n  (* 定义2：v0 是 0，或者 v1 是 0，或者 v0 是 v1 的 k 倍 *)\n  Definition vparallel_ver2 {n} (v0 v1 : V n) : Prop :=\n    (vzero v0) \\/ (vzero v1) \\/ (exists k, v0 = k c* v1).\n\n  (* 证明这两个定义等价 *)\n  Lemma vparallel_ver1_eq_ver2 : forall {n} (v0 v1 : V n),\n    vparallel_ver1 v0 v1 <-> vparallel_ver2 v0 v1.\n  Proof.\n    intros. unfold vparallel_ver1, vparallel_ver2.\n    unfold vzero, vnonzero. split; intros.\n    - assert ({v0 = vec0} + {v0 <> vec0}). apply meq_dec.\n      assert ({v1 = vec0} + {v1 <> vec0}). apply meq_dec.\n      destruct H0.\n      + left. auto.\n      + destruct H1.\n        * right. left. auto.\n        * right. right. destruct H. destruct H.\n          { exists x. auto. }\n          { exists (1/x). rewrite H.\n            rewrite mcmul_assoc.\n            replace ((1/x)%R * x)%X with 1.\n            rewrite mcmul_1_l. easy.\n            compute. field.\n            apply (vec_eq_vcmul_imply_coef_neq0 v1 v0); auto. }\n    - destruct H.\n      + exists 0. left. rewrite mcmul_0_l. rewrite H. rewrite vec0_eq_mat0.\n        easy.\n      + destruct H.\n        * exists 0. right. rewrite mcmul_0_l,H,vec0_eq_mat0. easy.\n        * destruct H. exists x. left. auto.\n  Qed.\n\n  (** 向量平行谓词的定义 *)\n  Definition vparallel {n} (v0 v1 : V n) : Prop :=\n    vparallel_ver2 v0 v1.\n\n  Notation \"v0 // v1\" := (vparallel (v0) (v1)) (at level 70) : vec_scope.\n\n\n  (** * 向量平行的性质 *)\n\n  (** 向量平行是等价关系 *)\n\n  (** 自反性 *)\n  Lemma vparallel_refl : forall {n} (v : V n), v // v.\n  Proof.\n    intros. unfold vparallel,vparallel_ver2. right. right. exists 1.\n    rewrite mcmul_1_l. easy.\n  Qed.\n\n  (** 对称性 *)\n  Lemma vparallel_sym : forall {n} (v0 v1 : V n), v0 // v1 -> v1 // v0.\n  Proof.\n    intros. unfold vparallel,vparallel_ver2 in *.\n    assert ({vzero v0} + {vnonzero v0}). apply meq_dec.\n    assert ({vzero v1} + {vnonzero v1}). apply meq_dec.\n    destruct H0.\n    - right; left; auto.\n    - destruct H1.\n      + left; auto.\n      + destruct H; auto. destruct H; auto. destruct H.\n        right; right. rewrite H.\n        exists (1/x). rewrite mcmul_assoc.\n        replace ((1/x)%R * x)%X with 1. rewrite mcmul_1_l; easy.\n        compute. field. apply (vec_eq_vcmul_imply_coef_neq0 v0 v1); auto.\n  Qed.\n\n  (** 传递性 *)\n  (* 要求v1是非零向量。因为若v1为0，v0//v1, v1//v2, 但 v0,v2 不平行 *)\n  Lemma vparallel_trans : forall {n} (v0 v1 v2 : V n), \n    vnonzero v1 -> v0 // v1 -> v1 // v2 -> v0 // v2.\n  Proof.\n    intros. unfold vparallel, vparallel_ver2 in *.\n    assert ({vzero v0} + {vnonzero v0}). apply meq_dec.\n    assert ({vzero v1} + {vnonzero v1}). apply meq_dec.\n    assert ({vzero v2} + {vnonzero v2}). apply meq_dec.\n    destruct H2.\n    - left; auto.\n    - destruct H4.\n      + right; left; auto.\n      + right; right.\n        destruct H3.\n        * destruct H0; try contradiction.\n        * destruct H0,H1; try contradiction.\n          destruct H0,H1; try contradiction.\n          destruct H0,H1. rewrite H0,H1.\n          exists (x*x0)%X. apply mcmul_assoc.\n  Qed.\n\n  (** 非零向量k倍相等，k唯一 *)\n  Lemma vcmul_vnonzero_eq_iff_unique_k : forall {n} (v : V n) (H : vnonzero v), \n    forall k1 k2, k1 c* v = k2 c* v -> k1 = k2.\n  Proof.\n    intros. destruct v. apply meq_iff in H0. simpl in *.\n    rename mat_data into dl. unfold vnonzero in H. apply meq_iff_not in H.\n    simpl in *.\n    unfold dmap in *.\n    (* hard part *)\n    generalize dependent n. \n    generalize dependent dl.\n    induction dl; intros.\n    - simpl in *; subst; simpl in *. easy.\n    - simpl in *. inversion H0. clear H0. destruct mat_width.\n      destruct n. easy. simpl in *.\n      apply cons_neq_iff in H. destruct H.\n      + (* a != [0] *)\n        destruct a. easy.\n        assert (a = []).\n        { simpl in *. inversion H0. rewrite length_zero_iff_nil in H5; auto. }\n        assert (x <> 0).\n        { rewrite H4 in *. apply cons_neq_iff in H. destruct H; auto.\n          apply Xeqdec. }\n        subst. simpl in H2. inversion H2.\n        apply Rmult_eq_reg_r with (r:=x); auto.\n      + (* dl != ListAux.cvt_row2col (repeat 0 n) *)\n        apply IHdl with (n:=n); auto.\n      + apply list_eq_dec. apply Xeqdec.\n  Qed.\n\n  (** 非零向量平行，则存在唯一比例系数k *)\n  Lemma vparallel_vnonezero_imply_unique_k : forall {n} (v0 v1 : V n) \n    (H1 : vnonzero v0) (H2 : vnonzero v1),\n    v0 // v1 -> (exists ! k, v0 = k c* v1).\n  Proof.\n    intros.\n    destruct H; try contradiction.\n    destruct H; try contradiction.\n    destruct H. exists x. unfold unique. split; auto.\n    intros. apply vcmul_vnonzero_eq_iff_unique_k with (v:=v1); auto.\n    rewrite <- H,H0. easy.\n  Qed.\n\n  (** 非零向量v0，v1 与 v0 平行，iff，存在唯一实数 a 使得 v1 = a * v0 *)\n  Lemma vparallel_iff1 : forall {n} (v0 v1 : V n) (H : vnonzero v0),\n    (v1 // v0) <-> (exists ! a, v1 = a c* v0).\n  Proof.\n    intros. split; intros.\n    - unfold vparallel, vparallel_ver2, vnonzero in *.\n      assert ({vzero v0} + {vnonzero v0}). apply meq_dec.\n      assert ({vzero v1} + {vnonzero v1}). apply meq_dec.\n      destruct H1; try contradiction.\n      destruct H2.\n      + (* {vzero v1} *) \n        exists 0. unfold unique. split.\n        * rewrite v2. rewrite mcmul_0_l. apply vec0_eq_mat0.\n        * rewrite v2. intros.\n          symmetry. symmetry in H1.\n          apply vcmul_nonzero_eq_zero_imply_k0 with (v:=v0); auto.\n      + (* {vnonzero v1} *)\n        destruct H0; try easy.\n        destruct H0; try easy.\n        destruct H0.\n        (* vnonzero v0 -> vnonzero v1 -> v1 = x * v0 -> exists ! x *)\n        exists x. unfold unique. split; auto.\n        intros. rewrite H0 in H1.\n        apply vcmul_vnonzero_eq_iff_unique_k in H1; auto.\n    - destruct H0. destruct H0.\n      unfold vparallel. unfold vparallel_ver2.\n      right. right. exists x. auto.\n  Qed.\n\nEnd DimAny.\n\n\n\n(* ==================================== *)\n(** ** 3-dim vector operations *)\nSection Dim3.\n   \n  (** 3阶方阵的行列式 *)\n  Definition det3 (m : M 3 3) : X :=\n    let '((a11,a12,a13),(a21,a22,a23),(a31,a32,a33)) :=\n      m2t_3x3 m in\n    let b1 := (a11 * a22 * a33)%X in\n    let b2 := (a12 * a23 * a31)%X in\n    let b3 := (a13 * a21 * a32)%X in\n    let c1 := (a11 * a23 * a32)%X in\n    let c2 := (a12 * a21 * a33)%X in\n    let c3 := (a13 * a22 * a31)%X in\n    let b := (b1 + b2 + b3)%X in\n    let c := (c1 + c2 + c3)%X in\n      (b - c)%X.\n\n  (** V3斜对称矩阵 *)\n  Definition skew_sym_mat_of_v3 (v : V 3) : M 3 3 :=\n    let '(x,y,z) := v2t_3 v in \n      (mk_mat_3_3\n        X0    (-z)  y\n        z     X0    (-x)\n        (-y)  x     X0)%X.\n\n  (** V3叉乘，向量积 *)\n  Definition vcross3 (v1 v2 : V 3) : V 3 := (skew_sym_mat_of_v3 v1) * v2.\n\n  (** 矩阵是否为SO3（李群，旋转群） *)\n  Definition so3 (m : M 3 3) : Prop := \n    let so3_mul_unit : Prop := (m ᵀ) * m = mat1 3 in\n    let so3_det : Prop := (det3 m) = X1 in\n      so3_mul_unit /\\ so3_det.\n  \n   (** 计算两个向量的夹角 *)\n  Definition vangle3 (v0 v1 : V 3) : R := \n    acos (scalar_of_mat (v0 ᵀ * v1)).\n  \n  (** (1,0,0) 和 (1,1,0) 的夹角是 45度，即 π/4 *)\n  Example vangle3_ex1 : vangle3 (l2v [1;0;0]) (l2v [1;1;0]) = PI/4.\n  Proof.\n    compute.\n(*     Search acos. *)\n    Abort. (* 暂不知哪里错了，要去查叉乘的意义 *)\n    \n  (** 根据两个向量来计算旋转轴 *)\n  Definition rot_axis_by_twovec (v0 v1 : V 3) : V 3 :=\n    let s : R := (vlen v0 * vlen v1)%R in\n      (s c* (vcross3 v0 v1))%M.\n\n  (* 谓词：两向量不共线（不平行的） *)\n  (* Definition v3_non_colinear (v0 v1 : V3) : Prop :=\n    v0 <> v1 /\\ v0 <> (-v1)%M.\n   *)\n  \nEnd Dim3.\n", "meta": {"author": "zhengpushi", "repo": "CoqMatrix", "sha": "28fa5f96e38a07659cfd373e09b0e75c24c22bfd", "save_path": "github-repos/coq/zhengpushi-CoqMatrix", "path": "github-repos/coq/zhengpushi-CoqMatrix/CoqMatrix-28fa5f96e38a07659cfd373e09b0e75c24c22bfd/CoqMatrix/DepRec/VectorR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7263052272852585}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus x (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj3411_coqofml_7idvID.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7262757436103667}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus Zero (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj287_coqofml_qKJNPq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7262757268397896}}
{"text": "Require Import String.\n\nDefinition prenom : string := \"Eve\".\nDefinition nom : string := \"Poitevin\".\n\n(* *)\n\nInductive arbint : Set :=\n  | F : arbint\n  | N : arbint -> nat -> arbint  -> arbint\n.\n\nFixpoint taille (a : arbint) : nat :=\n  match a with\n  | F => 0\n  | N g n d => taille g + S (taille d)\n  end.\n\nFixpoint arb_S (a : arbint) : arbint :=\n  match a with\n  | F => F\n  | N g n d => N (arb_S g) (S n) (arb_S d)\n  end.\n\n(* ComplÃ©ter la preuve. *)\nLemma meme_taille_arb_S : forall a, taille (arb_S a) = taille a.\nProof.\n  intro a.\n  induction a as [ | ].\n  - cbn [arb_S]. reflexivity.\n  - cbn [arb_S]. cbn [taille]. rewrite IHa1. rewrite IHa2. reflexivity.\nQed.\n\n(* QCM (Ã  questions binaires) *)\n(* Dans ce qui suit remplacer \". Admitted.\" par \":= votre reponse.\"\n   si vous connaissez la bonne rÃ©ponse, ou laisser \". Admitted.\" sinon.*)\n\n(* Question 1 :\n  la preuve prÃ©cÃ©dente est par rÃ©currence sur a *)\nDefinition reponse_1 : bool:= true.\n\n(* Question 2 :\n   la preuve prÃ©cÃ©dente est par rÃ©currence sur la taille de a *)\nDefinition reponse_2 : bool:= false.\n\n(* Question 3 :\n   dans la preuve prÃ©cÃ©dente, combien y a-t-il d'hypothÃ¨ses de rÃ©currence ? *)\nDefinition reponse_3 : nat:= 2.\n", "meta": {"author": "LilianSOLER", "repo": "PF7", "sha": "dbe343844a602990cc9061a37d175d4c46e3eef3", "save_path": "github-repos/coq/LilianSOLER-PF7", "path": "github-repos/coq/LilianSOLER-PF7/PF7-dbe343844a602990cc9061a37d175d4c46e3eef3/doc-pf/doc-eve/cclt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7262464683631968}}
{"text": "Require Import Cpdt.CpdtTactics.\nRequire Import Cpdt.Predicates.\n(* exercise 0.2-1\n   以下に示したタクティクのみを用いて、(a) ~ (c) を証明せよ。\n   apply, assumption, constructor, destruct, intro, intros, left, right, split, unfold *)\n\nTheorem tautology_a : and (or True False) (or True False).\n  constructor; constructor; apply I.\nQed.\n\nTheorem tautology_b : forall P : Prop, P -> ~ ~ P.\n  intros.\n  unfold not.\n  intro.\n  apply H0, H.\nQed.\n\nTheorem tautology_c : forall P Q R : Prop, (and P (or Q R)) -> (or (and P Q) (and P R)).\n  intros.\n  destruct H.\n  destruct H0.\n  left.\n  constructor.\n  apply H.\n  apply H0.\n  right.\n  constructor.\n  apply H.\n  apply H0.\nQed.\n      \n(* exercise 0.2-2 *)\nTheorem first_order_logic : forall (A : Type) (x y z : A) (P : A -> Prop)\n                                   (Q : A -> A -> Prop) (F : A -> A),\n    (P x) -> (forall x, P x -> exists y, Q x y) ->\n    (forall x y, Q x y -> Q y (F y)) ->\n    (exists z, Q z (F z)).\n  intros.\n  apply H0 in H.                (* 前提が forall なら apply *)\n  destruct H as [ y0 H2 ].      (* 前提が exists なら destruct/case *)\n  apply H1 in H2.\n  exists y0.                    (* exists を示したければ具体的に成り立つものを与える *)\n  assumption.\nQed.\n\nSection Two.                    (* こう書くと綺麗 *)\n  Variable T : Set.\n  Variable x : T.\n  Variable p : T -> Prop.\n  Variable q : T -> T -> Prop.\n  Variable f : T -> T.\n\n  Theorem ex : p x -> (forall x, p x -> exists y, q x y) ->\n               (forall x y, q x y -> q y (f y)) -> exists z, q z (f z).\n    intros.\n    assert (exists y, q x y).\n    apply H0; assumption.\n    destruct H2.\n    exists x0.\n    eapply H1.                  (* 普通のapplyだと死ぬ メタ変数を入れるようにする *)\n    eassumption.\n  Qed.\nEnd Two.\n\n(* exercise 0.2-3 *)\nInductive mult6 : nat -> Prop :=\n| Mult6   : mult6 O\n| MultS6  : forall n, mult6 n -> mult6 (S (S (S (S (S (S n)))))).\n\nInductive mult10 : nat -> Prop :=\n| Mult10  : mult10 O\n| MultS10 : forall n, mult10 n -> mult10 (S (S (S (S (S (S (S (S (S (S n)))))))))).\n\nInductive multiple : nat -> Prop :=\n| Multi6  : forall n, mult6 n -> multiple n\n| Multi10 : forall n, mult10 n -> multiple n.\n\nTheorem mult6_contra : mult6 13 -> False.\n  inversion 1.\n  inversion H1.\n  inversion H3.\nQed.\n\nTheorem not13 : ~ (mult6 13).   (* False を導いても、not を示してもOK *)\n  intro.\n  repeat (\n      match goal with\n      | [ H : mult6  ?N |- _] => inversion H\n      | [ H : mult10 ?N |- _] => inversion H\n      end\n    ).\nQed.\n  \nTheorem multiple_contra : multiple 13 -> False.\n  inversion 1.\n  inversion H0.\n  inversion H3.\n  inversion H5.\n\n  inversion H0.\n  inversion H3.\nQed.\n\nInductive oddness : nat -> Prop :=\n| Odd : forall n, oddness (S (n * 2)).\n\nEval simpl in oddness (S O).\nEval simpl in (S (S (S O)) * 2).\n\nTheorem not_6_or_10 : forall n, multiple n -> ~ exists m, n = 1 + 2 * m.\n  Admitted.", "meta": {"author": "chiaki-i", "repo": "lambda18", "sha": "846c3a836d6bf1a89d8d65f67749e36fae2c2716", "save_path": "github-repos/coq/chiaki-i-lambda18", "path": "github-repos/coq/chiaki-i-lambda18/lambda18-846c3a836d6bf1a89d8d65f67749e36fae2c2716/code/report03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7262464682104481}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Omega.\n \nLtac CaseEq f := generalize (refl_equal f); \n    pattern f at -1 in |- *; case f.\n \nFixpoint div4 (n:nat) : nat * nat :=\n  match n with\n  | S (S (S (S p))) => let (q, r) := div4 p in (S q, r)\n  | a => (0, a)\n  end.\n\nFixpoint bsqrt (n b:nat) {struct b} : nat * nat :=\n  match b with\n  | O => (0, 0)\n  | S b' =>\n      match div4 n with\n      | (O, O) => (0, 0)\n      | (O, S p) => (1, p)\n      | (q, r0) =>\n          let (s', r') := bsqrt q b' in\n          match le_gt_dec (4 * s' + 1) (4 * r' + r0) with\n          | left _ => (2 * s' + 1, 4 * r' + r0 - (4 * s' + 1))\n          | right _ => (2 * s', 4 * r' + r0)\n          end\n      end\n  end.\n\n(* We start by proving a few basic properties of division by 4.\n  As suggested in section 8.3.1, we can use a specific induction\n  principle to work on div4.  This is also the solution to exercise\n  \\ref{quadruple_induction}. *)\n \nTheorem div4_ind :\n forall P:nat -> Prop,\n   P 0 ->\n   P 1 ->\n   P 2 ->\n   P 3 -> (forall n:nat, P n -> P (S (S (S (S n))))) -> forall n:nat, P n.\nProof.\n intros P P0 P1 P2 P3 Prec n.\n cut (P n /\\ P (S n) /\\ P (S (S n)) /\\ P (S (S (S n)))).\n -  intuition.\n -  elim n; intuition.\nQed.\n\n(* Proving the main characteristics of div4 is easy using\n  div4_ind.  We avoid using Simpl so that multiplications\n  do not get unfolded into additions. *)\n \nLemma div4_exact : forall n:nat, let (q, r) := div4 n in n = 4 * q + r.\nProof.\n intros n; elim n using div4_ind; try (simpl in |- *; auto; fail).\n intros p; cbv beta iota zeta delta [div4] in |- *; fold div4 in |- *.\n case (div4 p).\n intros q r Hrec; rewrite Hrec; ring.\nQed.\n(* Since 4 is a constant, we can use div4_exact to\n   obtain a linear equality in the sense of Presburger arithmetic\n  and the Omega decision procedure can cope with the formula.*)\n \nTheorem div4_lt : forall n:nat, let (q, r) := div4 n in 0 < q -> q < n.\nProof.\n intros n; generalize (div4_exact n); case (div4 n).\n intros q r Heq; omega.\nQed.\n \nTheorem div4_lt_rem : forall n:nat, let (q, r) := div4 n in r < 4.\nProof.\n intros n; elim n using div4_ind; try (simpl in |- *; auto with arith).\n intros p; case (div4 p); auto.\nQed.\n\nLtac remove_minus :=\n  match goal with\n  |  |- context [(?X1 - ?X2 + ?X3)] =>\n      rewrite <- (plus_comm X3); remove_minus\n  |  |- context [(?X1 + (?X2 - ?X3) + ?X4)] =>\n      rewrite (plus_assoc_reverse X1 (X2 - X3)); remove_minus\n  |  |- context [(?X1 + (?X2 + (?X3 - ?X4)))] =>\n      rewrite (plus_assoc X1 X2 (X3 - X4))\n  |  |- (_ = ?X1 + (?X2 - ?X3)) =>\n      apply (fun n m p:nat => plus_reg_l m p n) with X3;\n       try rewrite (plus_permute X3 X1 (X2 - X3)); \n       rewrite le_plus_minus_r\n  end.\n\n(* The proof of this goal is a simple matter of computation, but\n   NatRing can't cope with it because of the irregular behavior of\n   minus.  The tactic remove_minus defined above takes care of that by\n   adding the subtracted term on both side of the equality, and then\n   simplifying with le_plus_minus.  This simplification only works\n   because the theorem has the right hypothesis.  *)\n \nTheorem bsqrt_exact_lemma_le :\n forall n q r s' r':nat,\n   n = 4 * q + r ->\n   q = s' * s' + r' ->\n   4 * s' + 1 <= 4 * r' + r ->\n   n = (2 * s' + 1) * (2 * s' + 1) + (4 * r' + r - (4 * s' + 1)).\nProof.\n intros; remove_minus.\n subst; ring.\n assumption.\nQed.\n \nLemma bsqrt_exact_lemma_gt :\n forall n q r s' r':nat,\n   n = 4 * q + r ->\n   q = s' * s' + r' ->\n   4 * s' + 1 > 4 * r' + r -> n = 2 * s' * (2 * s') + (4 * r' + r).\nProof.\n intros; subst; ring.\nQed.\n\nTheorem bsqrt_exact :\n forall b n:nat, n <= b -> let (s, r) := bsqrt n b in n = s * s + r.\nProof.\n (* Induction on the bound, as should always be the case\n   for bounded recursive functions. *)\n intros b; elim b.\n\n(* When the bound is zero, if n is lower than the bound, it\n  is also 0, it is only a matter of computation to check the\n  equality. *)\n intros n Hle; rewrite <- (le_n_O_eq _ Hle); simpl in |- *; auto.\n\n (*We limit simplification to the bsqrt function. *)\n intros b' Hrec n Hle; cbv beta iota zeta delta [bsqrt] in |- *;\n  fold bsqrt in |- *.\n\n (* We use the lemmas on div4.  To avoid CaseEq, we rely on\n   Generalize before doing a Case analysis. *)\n generalize (div4_lt n) (div4_exact n).\n case (div4 n).\n intros q r; case q.\n -  case r; intros; subst; ring.\n -  intros q' Hlt Heq; generalize (Hrec (S q')); case (bsqrt (S q') b').\n    intros s' r' Hrec'.\n\n (* Because le_gt_dec is a well-specified function,\n   there is no need to generalize hypotheses to perform\n  the case analysis on this function call. *)\n    case (le_gt_dec (4 * s' + 1) (4 * r' + r)).\n    apply bsqrt_exact_lemma_le with (S q'); auto; omega.\n    apply bsqrt_exact_lemma_gt with (S q'); auto; omega.\nQed.\n \nTheorem bsqrt_rem :\n forall b n:nat, n <= b -> \n   let (s, r) := bsqrt n b in n < (s + 1) * (s + 1).\nProof.\n intros b; elim b.\n -  intros n Hle; rewrite <- (le_n_O_eq _ Hle); \n  simpl in |- *; auto with arith.\n\n (*We limit simplification to the bsqrt function. *)\n -  intros b' Hrec n Hle; generalize (bsqrt_exact (S b') n Hle);\n    cbv beta iota zeta delta [bsqrt] in |- *; fold bsqrt in |- *.\n\n(* We use the lemmas on div4.  To avoid CaseEq, we rely on\n  Generalize before doing a Case analysis. *)\n generalize (div4_lt n) (div4_exact n) (div4_lt_rem n).\n case (div4 n);  intros q r;  case q.\n + case r; intros; subst; simpl in |- *; auto with arith.\n +  intros q' Hlt Heq Hlt_rem; generalize (Hrec (S q')).\n    case (bsqrt (S q') b').\n    intros s' r' Hrec'.\n\n (* Because le_gt_dec is a well-specified function,\n   there is no need to generalize hypothesese to perform\n   the case analysis on this function call. *)\n case (le_gt_dec (4 * s' + 1) (4 * r' + r)).\n *  intros Hle' Heq'; rewrite Heq.\n    apply lt_le_trans with (4 * S q' + 4).\n    auto with arith.\n     replace ((2 * s' + 1 + 1) * (2 * s' + 1 + 1)) with\n     (4 * ((s' + 1) * (s' + 1))).\n     abstract omega.\n     ring.\n *  intros Hgt Heq'; rewrite Heq'.\n    match goal with\n      |  |- (?X1 < ?X2) => ring_simplify X1; ring_simplify X2\n    end.\n    abstract omega.\nQed.\n \n\nDefinition sqrt_nat :\n  forall n:nat,\n    {s : nat &  {r : nat | n = s * s + r /\\ n < (s + 1) * (s + 1)}}.\n intros n; \n  generalize (bsqrt_exact n n (le_n n)) (bsqrt_rem n n (le_n n));\n  case (bsqrt n n).\n intros s r H1 H2; exists s; exists r; auto.\nDefined.\n\nExample test : bsqrt 37 37 = (6,1).\nProof. reflexivity.  Qed.\n\nExample test2 : bsqrt 49 49 = (7,0).\nProof. reflexivity.  Qed.\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/ch15_general_recursion/SRC/sqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7262464503066443}}
{"text": "Definition eventually_periodic (f : nat -> nat) (n : nat) : Prop :=\n  exists t m0,\n    t > 0 /\\ forall m, m0 < m -> Nat.iter (t + m) f n = Nat.iter m f n.\n\n(* Floyd's tortoise and hare algorithm *)\nInductive hare_catches_tortoise (f : nat -> nat) : nat -> nat -> Prop :=\n| CatchNext : forall x y, x = f y -> hare_catches_tortoise f x y\n| CatchLater : forall x y, hare_catches_tortoise f (f x) (f (f y)) ->\n                           hare_catches_tortoise f x y.\n\nDefinition task :=\n  forall f n, eventually_periodic f n <-> hare_catches_tortoise f n (f n).\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/045/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7261420157127151}}
{"text": "(*******************************************************************)\n(*  This is part of RelationAlgebra, it is distributed under the   *)\n(*    terms of the GNU Lesser General Public License version 3     *)\n(*              (see file LICENSE for more details)                *)\n(*                                                                 *)\n(*  Copyright 2012: Damien Pous. (CNRS, LIP - ENS Lyon, UMR 5668)  *)\n(*******************************************************************)\n\n(** * pair: encoding pairs of ordinals as ordinals *)\n(** more precisely, [ord n * ord m] into [ord (n*m)] *)\n\nRequire Import Lt Peano_dec Compare_dec Mult Euclid NPeano. (* TODO: se passer de NPeano? *)\nRequire Import ordinal.\n\nSet Asymmetric Patterns.\nSet Implicit Arguments.\n\n(** equivalence between our Boolean strict order on [nat],\n   and the standard one from the standard library  *)\nLemma ltb_lt x y: ltb x y = true <-> lt x y.\nProof.\n  revert y. induction x; destruct y; simpl.\n   split. discriminate. inversion 1. \n   split. intro. apply lt_0_Sn. reflexivity. \n   split. discriminate. inversion 1. \n   rewrite IHx. split. apply lt_n_S. apply lt_S_n. \nQed.\n\n(** auxiliary lemma *)\nLemma mk_lt n m x y: x<n -> y<m -> y*n+x < n*m. \nProof. \n  setoid_rewrite ltb_lt. \n  intros. apply lt_le_trans with (y*n+n). apply plus_le_lt_compat. apply le_n. assumption. \n  rewrite <-mult_succ_l, (mult_comm n). apply mult_le_compat. assumption. apply le_n. \nQed.\n\n(** since [x] is bounded by [n], we encode the pair [(x,y)] as [y*n+x] *)\nDefinition mk n m (x: ord n) (y: ord m): ord (n*m).\ndestruct x as [x Hx]; destruct y as [y Hy].\napply Ord with (y*n+x). \nnow apply mk_lt. \nDefined. \n\nLemma ord_nm_lt_O_n {n m} (x: ord (n*m)): lt 0 n. \nProof. destruct n. elim (ord_0_empty x). apply lt_0_Sn. Qed.\n\n(** first projection, by modulo *)\nDefinition pi1 {n m} (p: ord (n*m)): ord n := \n  let '(divex _ x Hx _) := eucl_dev n (ord_nm_lt_O_n p) p in (Ord x (proj2 (ltb_lt _ _) Hx)).\n\n(** second projection, by division *)\nDefinition pi2 {n m} (p: ord (n*m)): ord m. \ndestruct (eucl_dev n (ord_nm_lt_O_n p) p) as [y x Hx Hy]. \napply Ord with y. \nunfold gt in *.\ndestruct p as [p Hp]. simpl in Hy. rewrite Hy in Hp. clear p Hy.  \ndestruct (le_lt_dec m y) as [Hy|Hy]. 2: now apply ltb_lt. exfalso.\napply ltb_lt in Hp. apply (mult_le_compat_l _ _ n) in  Hy. \napply (lt_le_trans _ _ _ Hp) in Hy. rewrite mult_comm in Hy. \napply ltb_lt in Hy. rewrite leb_plus_r in Hy. discriminate. \nDefined.\n\nLemma euclid_unique n: lt 0 n -> \n  forall x y x' y', lt x n -> lt x' n -> y*n+x = y'*n+x' -> y=y' /\\ x=x'. \nProof.\n  intros Hn x y x' y' Hx Hx' H. rewrite mult_comm, (mult_comm y') in H. split. \n   erewrite Nat.div_unique. 3: eassumption. 2: assumption. \n   rewrite H. eapply Nat.div_unique. 2: symmetry; eassumption. assumption. \n   erewrite Nat.mod_unique. 3: eassumption. 2: assumption. \n   rewrite H. eapply Nat.mod_unique. 2: symmetry; eassumption. assumption. \nQed.\n\n(** projections bhave as expected *)\nLemma pi1mk n m: forall x y, pi1 (@mk n m x y) = x.\nProof.\n  intros [x Hx] [y Hy]. unfold pi1, mk. case eucl_dev. \n  intros y' x' Hx' H. apply eq_ord. apply euclid_unique in H as [_ ?]; auto.  \n  eapply le_lt_trans. apply le_0_n. eassumption. \n  now apply ltb_lt.\nQed.\n\nLemma pi2mk n m: forall x y, pi2 (@mk n m x y) = y.\nProof.\n  intros [x Hx] [y Hy]. unfold pi2, mk. case eucl_dev. \n  intros y' x' Hx' H. apply eq_ord. simpl. apply euclid_unique in H as [? _]; auto.  \n  eapply le_lt_trans. apply le_0_n. eassumption. \n  now apply ltb_lt.\nQed.\n\n(** surjective pairing *)\nLemma mkpi12 n m: forall p, @mk n m (pi1 p) (pi2 p) = p.\nProof.\n  intros [p Hp]. unfold pi1, pi2, mk. case eucl_dev. simpl. intros y x Hx Hy. \n  apply eq_ord. simpl. now rewrite Hy. \nQed.\n", "meta": {"author": "coq-contribs", "repo": "relation-algebra", "sha": "2d9066e917400dc3e2b10ad9c12710620d20644b", "save_path": "github-repos/coq/coq-contribs-relation-algebra", "path": "github-repos/coq/coq-contribs-relation-algebra/relation-algebra-2d9066e917400dc3e2b10ad9c12710620d20644b/pair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7261233406136469}}
{"text": "Require Import SQIR.UnitaryOps.\nRequire Import Utilities.\nRequire Import QuantumLib.Measurement.\n\nOpen Scope ucom.\nLocal Close Scope C_scope.\nLocal Close Scope R_scope.\n\nLocal Coercion Nat.b2n : bool >-> nat.\n\n(* This file contains a definition of the Deutsch-Jozsa program, which determines\n   whether a function is constant or balanced using one query to a boolean oracle.\n\n   See, e.g., https://en.wikipedia.org/wiki/Deutsch%E2%80%93Jozsa_algorithm\n\n   This file also contains proofs of correctness of the Deutsch-Jozsa program\n   using two different methods. The first uses a standard definition of boolean\n   oracles and follows the standard textbook proof of correctness. The second\n   uses an inductive definition of boolean oracles, which allows for an inductive\n   proof. *)\n\n(** Definition of Deutsch-Jozsa program. **)\n\nDefinition deutsch_jozsa {n} (U : base_ucom (S n)) : base_ucom (S n) :=\n  X n ; npar (S n) U_H ; U; npar (S n) U_H.\n\n(** Proof of correctness #1 **)\n\n(* Definition of boolean oracle U : ∣ x ⟩∣ y ⟩ ↦ ∣ x ⟩∣ y ⊕ f(x) ⟩ *)\nDefinition boolean_oracle {n} (U : base_ucom (S n)) (f : nat -> bool) :=\n  forall x (y : bool), (x < 2 ^ n)%nat -> \n    @Mmult _ _ 1 (uc_eval U) (basis_vector (2 ^ n) x ⊗ ∣ y ⟩) = \n      basis_vector (2 ^ n) x ⊗ ∣ xorb y (f x) ⟩.\n\nDefinition balanced f n := n > 0 /\\ count0 f (2 ^ n) = 2 ^ (n - 1).\n\nDefinition constant f n := count0 f (2 ^ n) = 0 \\/ count0 f (2 ^ n) = 2 ^ n.\n\nLocal Open Scope C_scope.\nLocal Open Scope R_scope.\n\n(* After running deutsch_jozsa, the probability of measuring the state\n   (n ⨂ ∣0⟩) ⊗ ∣1⟩ will be a sum of terms of the form (-1)^(f x). The\n   value of this sum can be rewritten as follows:\n       ∑ (-1)^(f x) / n = 1 - 2 * count f / n.\n   Note that if f is balanced, then this expression will be zero. If f is\n   constant then the expression will either be 1 or -1. *)\nLemma sum_of_minus_1 : forall (f : nat -> bool) n,\n  (n > 0)%nat ->\n  ((Σ (fun x => (-1) ^ f(x)) n) * / INR n)%C = 1 - 2 * INR (count0 f n) * / INR n.\nProof.\n  unfold count0.\n  intros.\n  destruct n; try lia.\n  clear H.\n  induction n.\n  simpl.\n  destruct (f O); simpl; lca.\n  repeat rewrite <- big_sum_extend_r in *.\n  simpl count in *. \n  remember (Σ (fun x : nat => (-1) ^ f x) n)%C as sum.\n  clear Heqsum.\n  rewrite Cmult_plus_distr_r.\n  rewrite <- (Cmult_1_r (_ * / _)).\n  rewrite <- (Cinv_r (INR (S n))).\n  assert (forall a b c d, ((a * b) * (c * d))%C = ((a * d) * (c * b))%C).\n  { intros. field. }\n  rewrite H, IHn; clear.\n  repeat rewrite plus_INR.\n  rewrite <- RtoC_inv.\n  rewrite RtoC_pow.\n  repeat rewrite <- RtoC_mult.\n  rewrite <- RtoC_plus.\n  apply injective_projections; simpl; try reflexivity.\n  field_simplify_eq.\n  destruct (f (S n)); subst; simpl; lra.\n  destruct n; try lra.\n  repeat rewrite <- S_INR.\n  split.\n  4: apply C0_fst_neq; remember (S n) as Sn; simpl; subst.\n  all: apply not_0_INR; lia.\nQed.\n\nLemma basis_vector_1_0 : basis_vector 1 0 = I 1.\nProof. \n  unfold basis_vector, I. \n  solve_matrix.\n  bdestruct_all; reflexivity.\nQed.\n\n(* In the Deutsch Jozsa problem we care about the probability of measuring ∣0...0⟩\n   in the first n qubits (the last qubit always ends up in the ∣1⟩ state). *)\nLocal Opaque pow.\nLemma deutsch_jozsa_success_probability :\n  forall {n : nat} (U : base_ucom (S n)) f,\n  (n > 0)%nat ->\n  boolean_oracle U f ->\n  @prob_partial_meas n 1 (n ⨂ ∣0⟩) (uc_eval (deutsch_jozsa U) × (S n ⨂ ∣0⟩)) =\n    (1 - 2 * INR (count0 f (2 ^ n)) * /2 ^ n) ^ 2.\nProof.\n  unfold count0.\n  intros n U f Hn H.\n  unfold deutsch_jozsa.\n  Opaque npar.\n  simpl uc_eval.\n  restore_dims. \n  rewrite npar_H by lia.\n  autorewrite with eval_db.\n  bdestruct_all.\n  replace (S n - (n + 1))%nat with O by lia.\n  simpl I.\n  Transparent npar. \n  simpl.\n  restore_dims. \n  repeat (rewrite Mmult_assoc; restore_dims).\n  Qsimpl. Qsimpl.\n  rewrite H0_kron_n_spec_alt by auto.\n  replace (hadamard × ∣1⟩) with ∣ - ⟩ by solve_matrix.\n  restore_dims. \n  distribute_scale. \n  rewrite kron_Msum_distr_r.\n  replace (2 ^ S n)%nat with (2 ^ n * 2)%nat by unify_pows_two.\n  rewrite 2 Mmult_Msum_distr_l. \n  erewrite big_sum_eq_bounded.  \n  2: { intros i Hi.\n       restore_dims.\n       distribute_plus.\n       distribute_scale.\n       unfold boolean_oracle in H.\n       repeat rewrite Nat.mul_1_r.\n       replace (2 ^ S n)%nat with (2 ^ n * 2)%nat in * by unify_pows_two.\n       replace ∣ 0 ⟩ with ∣ Nat.b2n false ⟩ by reflexivity.\n       rewrite (H i false) by assumption.\n       replace ∣ 1 ⟩ with ∣ Nat.b2n true ⟩ by reflexivity.\n       rewrite (H i true) by assumption.\n       restore_dims.\n       Qsimpl.\n       rewrite <- 2 Mscale_kron_dist_r. \n       rewrite <- kron_plus_distr_l.\n       rewrite <- 2 Mscale_mult_dist_r. \n       rewrite <- Mmult_plus_distr_l.\n       replace (/ √ 2 .* ∣ false ⊕ f i ⟩ .+ - / √ 2 .* ∣ true ⊕ f i ⟩) with ((-1)^(f i) .* ∣ - ⟩). \n       distribute_scale. \n       rewrite Hminus_spec.\n       rewrite <- Mscale_kron_dist_l.\n       reflexivity.\n       destruct (f i); simpl; lma. }\n  rewrite <- kron_Msum_distr_r.\n  rewrite <- Mscale_kron_dist_l.\n  specialize (@partial_meas_tensor n 1) as H1.\n  repeat rewrite Nat.pow_1_r in H1.\n  rewrite H1; clear H1.\n  2:{ split. auto with wf_db. apply bra1ket1. }\n  unfold probability_of_outcome, inner_product.\n  distribute_scale.\n  rewrite Mmult_Msum_distr_l.\n  erewrite big_sum_eq_bounded.\n  2: { intros i Hi.\n       rewrite basis_f_to_vec_alt by assumption.\n       rewrite H_kron_n_spec by assumption.\n       distribute_scale.\n       rewrite Mmult_Msum_distr_l.\n       erewrite big_sum_unique. \n       2: { exists O. \n            rewrite kron_n_0_is_0_vector.\n            split; [lia | split].\n            distribute_scale. \n            restore_dims.\n            rewrite basis_vector_product_eq by lia.\n            reflexivity.\n            intros j ? ?.\n            distribute_scale. \n            restore_dims.\n            rewrite basis_vector_product_neq by lia.\n            lma. }\n       rewrite product_comm, nat_to_funbool_0, product_0.\n       simpl.\n       rewrite Mscale_1_l.\n       rewrite Cmult_comm.\n       rewrite <- Mscale_assoc.\n       reflexivity. }\n  rewrite Mscale_Msum_distr_r, Mscale_Msum_distr_l.\n  restore_dims.\n  distribute_scale.\n  unfold scale, I; simpl.\n  rewrite Cmult_1_r. \n  rewrite <- Cinv_mult_distr by nonzero.\n  rewrite <- RtoC_mult.\n  rewrite sqrt_def.\n  rewrite Cmult_comm. \n  replace (2 ^ n)%R with (INR (2 ^ n)).\n  rewrite sum_of_minus_1.\n  rewrite Cmod_R.\n  rewrite <- 2 Rsqr_pow2.\n  rewrite <- Rsqr_abs.\n  reflexivity.\n  apply pow_positive. lia.\n  rewrite pow_INR.\n  reflexivity.\n  apply pow_le; lra.\nQed.\n\n(* accept := probability of measuring ∣0...0⟩ in the first n qubits is 1 *)\nDefinition accept {n : nat} (U : base_ucom (S n)) : Prop :=\n   @prob_partial_meas n 1 \n      (n ⨂ ∣0⟩) \n      (uc_eval (deutsch_jozsa U) × (S n ⨂ ∣0⟩)) = 1. \n\n(* reject := probability of measuring ∣0...0⟩ in the first n qubits is 0 *)\nDefinition reject {n : nat} (U : base_ucom (S n)) : Prop :=\n   @prob_partial_meas n 1 \n      (n ⨂ ∣0⟩) \n      (uc_eval (deutsch_jozsa U) × (S n ⨂ ∣0⟩)) = 0. \n\nTheorem deutsch_jozsa_correct :\n  forall {n} (f : nat -> bool) (U : base_ucom (S n)), \n  (n > 0)%nat -> boolean_oracle U f -> \n  (constant f n -> accept U) /\\ (balanced f n -> reject U).\nProof.\n  intros n f0 U Hn Hb. \n  unfold accept, reject.\n  split; intro H.\n  - rewrite deutsch_jozsa_success_probability with (f:=f0); auto.\n    unfold constant in H.\n    destruct H; rewrite H; simpl; try lra.\n    replace (INR (2 ^ n)) with (2 ^ n).\n    field. nonzero.\n    rewrite pow_INR. reflexivity.\n  - rewrite deutsch_jozsa_success_probability with (f:=f0); auto.\n    destruct H as [_ H].\n    rewrite H; simpl; try lra.\n    replace (INR (2 ^ (n - 1))) with (2 ^ n / 2).\n    field. nonzero.\n    rewrite pow_INR.\n    replace (INR 2) with 2 by reflexivity.\n    field_simplify_eq. \n    rewrite tech_pow_Rmult.\n    replace (S (n - 1)) with n by lia.\n    reflexivity.\nQed.\n\n(** Proof of correctness #2 **)\n\n(* Inductive definition of a boolean oracle. Note that in this definition\n   the result bit is stored at the beginning rather than the end, so\n   we have something like U : ∣ y ⟩∣ x ⟩ ↦ ∣ y ⊕ f(x) ⟩∣ x ⟩  *)\nInductive boolean : forall {n}, base_ucom (S n) -> Set :=\n  | boolean_I : forall u, u ≡ SKIP -> @boolean 0 u\n  | boolean_X : forall u, u ≡ X 0  -> @boolean 0 u\n  | boolean_U : forall dim (u : base_ucom (S (S dim))) (u1 u2 : base_ucom (S dim)),\n                boolean u1 -> boolean u2 ->\n                uc_eval u = (uc_eval u1 ⊗ ∣0⟩⟨0∣) .+ (uc_eval u2 ⊗ ∣1⟩⟨1∣) ->\n                boolean u.\n\n(* TODO: Can we prove equivalence between these definitions? i.e.\n     forall {n} (U : base_ucom (S n)),\n       boolean U <-> exists f, boolean_oracle U f. *)\n\n(* Slightly different version of DJ with the result bit at index 0. *)\nDefinition deutsch_jozsa' {n} (U : base_ucom n) : base_ucom n :=\n  X 0 ; npar n U_H ; U; npar n U_H.\n\n(* Counting for inductively defined oracles *)\nFixpoint count' {dim : nat} {u : base_ucom (S dim)} (P : boolean u) : nat :=\n  match P with\n  | boolean_I _ _ => 0\n  | boolean_X _ _ => 1\n  | boolean_U _ _ _ _ P1 P2 _ => (count' P1 + count' P2)\n  end.\n\nDefinition balanced' {dim : nat} {u : base_ucom (S dim)} (P : boolean u) : Prop :=\n  (dim > 0 /\\ count' P = 2 ^ (dim - 1))%nat.\n\nDefinition constant' {dim : nat} {u : base_ucom (S dim)} (P : boolean u) : Prop :=\n  (count' P = 0 \\/ count' P = 2 ^ dim)%nat.\n\nLocal Transparent pow.\nLemma deutsch_jozsa_success_probability' :\n  forall {n : nat} {U : base_ucom (S n)} (P : boolean U),\n  ((∣1⟩ ⊗ n ⨂ ∣0⟩)† × (uc_eval (deutsch_jozsa' U)) × ((S n) ⨂ ∣0⟩)) O O = \n      1 - 2 * INR (count' P) * /2 ^ n.\nProof.\n  intros.\n  unfold deutsch_jozsa'. \n  rewrite kron_n_assoc by auto with wf_db.\n  Opaque npar. \n  (* initial rewriting to get rid of X, H gates *)\n  simpl uc_eval. restore_dims. \n  rewrite npar_H by lia.\n  replace (S n - S n)%nat with O by lia.\n  autorewrite with eval_db.\n  bdestruct_all.\n  simpl I.\n  Msimpl_light.\n  replace (n - 0)%nat with n by lia.\n  rewrite kron_n_assoc by auto with wf_db.\n  restore_dims. \n  repeat rewrite Mmult_assoc.\n  restore_dims.\n  Qsimpl.\n  replace (hadamard × ∣1⟩) with ∣ - ⟩ by solve_matrix.\n  rewrite H0_kron_n_spec.\n  rewrite <- Mmult_assoc. \n  Qsimpl. \n  replace (hadamard) with (hadamard†) by (Qsimpl; easy).\n  rewrite <- kron_n_adjoint by auto with wf_db.\n  repeat rewrite <- Mmult_adjoint.\n  rewrite H0_kron_n_spec. \n  replace (hadamard × ∣1⟩) with ∣ - ⟩ by solve_matrix.\n  rewrite <- kron_adjoint.\n  (* interesting part of the proof that looks at the structure of P *)\n  induction n; dependent destruction P.\n  - simpl. rewrite u0. clear.\n    rewrite denote_SKIP; try lia.\n    Msimpl_light. restore_dims.\n    replace (∣ - ⟩† × ∣ - ⟩) with (I 1) by solve_matrix.\n    lca.\n  - simpl. rewrite u0. clear.\n    autorewrite with eval_db; simpl.\n    Msimpl_light. restore_dims.\n    replace (∣ - ⟩† × (σx × ∣ - ⟩)) with (-1 .* I 1) by solve_matrix.\n    lca.\n  - simpl. rewrite e.\n    restore_dims.\n    repeat rewrite <- kron_assoc by auto with wf_db.\n    restore_dims.\n    setoid_rewrite kron_adjoint.\n    rewrite Mmult_plus_distr_r.\n    restore_dims.\n    rewrite Mmult_plus_distr_l.\n    repeat rewrite kron_mixed_product.\n    replace ((∣+⟩) † × (∣0⟩⟨0∣ × ∣+⟩)) with ((1/2)%R .* I 1).\n    replace ((∣+⟩) † × (∣1⟩⟨1∣ × ∣+⟩)) with ((1/2)%R .* I 1).\n    repeat rewrite Mscale_kron_dist_r.\n    rewrite <- Mscale_plus_distr_r.\n    Msimpl_light. restore_dims.\n    unfold scale, Mplus in *. \n    setoid_rewrite (IHn u1 P1); try lia.\n    setoid_rewrite (IHn u2 P2); try lia.\n    clear.\n    rewrite <- RtoC_plus, <- RtoC_mult. \n    apply f_equal2; trivial. \n    rewrite plus_INR.\n    field_simplify_eq; trivial. \n    nonzero.\n    unfold xbasis_plus. solve_matrix.\n    unfold xbasis_plus. solve_matrix.\nQed.\n\n(* accept := probability of measuring ∣0...0⟩ in the last n qubits is 1 *)\nDefinition accept' {n : nat} {U : base_ucom (S n)} (P : boolean U) : Prop :=\n  @probability_of_outcome (2 ^ (S n)) \n    (∣1⟩ ⊗ n ⨂ ∣0⟩)\n    (uc_eval (deutsch_jozsa' U) × (S n ⨂ ∣0⟩)) = 1. \n\n(* reject := probability of measuring ∣0...0⟩ in the last n qubits is 0 *)\nDefinition reject' {n : nat} {U : base_ucom (S n)} (P : boolean U) : Prop :=\n  @probability_of_outcome (2 ^ (S n)) \n    (∣1⟩ ⊗ n ⨂ ∣0⟩) \n    (uc_eval (deutsch_jozsa' U) × (S n ⨂ ∣0⟩)) = 0. \n\nLocal Opaque pow.\nTheorem deutsch_jozsa_constant_correct' :\n  forall (n : nat) (U : base_ucom (S n)) (P : boolean U), constant' P -> accept' P.\nProof.\n  intros n U P H. \n  unfold accept', probability_of_outcome. \n  apply RtoC_inj.\n  rewrite <- RtoC_pow, Cmod_sqr.  \n  unfold inner_product.\n  restore_dims.\n  rewrite <- Mmult_assoc.\n  rewrite (deutsch_jozsa_success_probability' P). \n  destruct H; rewrite H; simpl; try lca.\n  autorewrite with RtoC_db R_db.\n  rewrite Cconj_R.\n  autorewrite with RtoC_db.\n  apply f_equal2; try reflexivity.\n  replace (INR (2 ^ n)) with (2 ^ n).\n  field. nonzero.\n  rewrite pow_INR.\n  reflexivity.\nQed.\n\nTheorem deutsch_jozsa_balanced_correct' :\n  forall (n : nat) (U : base_ucom (S n)) (P : boolean U), balanced' P -> reject' P.\nProof.\n  intros n U P [H1 H2].\n  unfold reject', probability_of_outcome. \n  apply RtoC_inj.\n  rewrite <- RtoC_pow, Cmod_sqr.\n  unfold inner_product.\n  restore_dims.\n  rewrite <- Mmult_assoc.\n  rewrite (deutsch_jozsa_success_probability' P).\n  rewrite H2; simpl.\n  autorewrite with RtoC_db R_db.\n  rewrite Cconj_R.\n  autorewrite with RtoC_db.\n  apply f_equal2; try reflexivity.\n  replace (INR (2 ^ (n - 1))) with (2 ^ n / 2).\n  field. nonzero.\n  rewrite pow_INR.\n  field_simplify_eq.\n  rewrite tech_pow_Rmult.\n  replace (S (n - 1)) with n by lia.\n  reflexivity.\nQed.\n", "meta": {"author": "inQWIRE", "repo": "SQIR", "sha": "7d2938bf63080e37d47059befa27a57f12cc099c", "save_path": "github-repos/coq/inQWIRE-SQIR", "path": "github-repos/coq/inQWIRE-SQIR/SQIR-7d2938bf63080e37d47059befa27a57f12cc099c/examples/examples/DeutschJozsa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.726123339931492}}
{"text": "Require Export P03.\n\n\n\n(** For those who like a challenge, here is an exercise taken from the\n    Coq'Art book by Bertot and Casteran (p. 123).  Each of the\n    following four statements, together with [excluded_middle], can be\n    considered as characterizing classical logic.  We can't prove any\n    of them in Coq, but we can consistently add any one of them as an\n    axiom if we wish to work in classical logic.\n\n    Prove that all five propositions (these four plus\n    [excluded_middle]) are equivalent. *)\n\nTheorem excluded_middle_to_double_negation_elimination:\n  excluded_middle -> double_negation_elimination.\nProof.\n  unfold excluded_middle, double_negation_elimination.\n  intros ex P neg. unfold not in neg. destruct (ex P).\n  - apply H.\n  - unfold not in H. apply neg in H. contradiction.\nQed.\n\nTheorem double_negation_elimination_to_excluded_middle:\n  double_negation_elimination -> excluded_middle.\nProof.\n  unfold excluded_middle, double_negation_elimination.\n  intros dn P. apply dn. intros H. apply H. right. intros H'. apply H. left. assumption.\nQed.\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/06/P04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7261233321364173}}
{"text": "Require Import HoTT.\nFrom GCTT Require Import finite_types permutations.\n\nSection Sign.\n  Lemma swap_fix_last {n : nat} (e : fintype n.+1 <~> fintype n.+1) :\n    (swap_last e oE e) (inr tt) = inr tt.\n  Proof.\n    apply fin_transpose_last_with_with.\n  Qed.\n\n  (* First sign of transpositions with the last element *)\n  Definition sgn_transpose {n : nat} (i : fintype n.+1) : (fintype 2 <~> fintype 2).\n  Proof.\n    destruct i as [i | []].\n    (* i is a nontrivial transposition, and has sign τ *)\n    - exact twist2.\n    (* i is the trivial transposition and has sign ι *)\n    - exact equiv_idmap.\n  Defined.\n\n  (** The sign of a permutations counts (modulo 2) how many nontrivial transpositions a permutation\n   can be factorized into. *)\n  Fixpoint sign (n : nat) :\n    (fintype n <~> fintype n) -> (fintype 2 <~> fintype 2).\n  Proof.\n    intro e.\n    (* For n = 0, the sign is trivial *)\n    destruct n. { exact equiv_idmap. }\n    exact (sgn_transpose (e (inr tt)) oE sign n (transpose_and_restrict e)).\n  Defined.\n\n  Lemma sgn_transpose_notlast {n : nat} (i : fintype n.+1) :\n        (i <> inr tt) -> sgn_transpose i = twist2.\n  Proof.\n    intro nlast.\n    destruct i as [i | []].\n    - reflexivity.\n    - destruct (nlast idpath).\n  Qed.\n\n  Definition sgn_id (m : nat) :\n    sign m (equiv_idmap) = equiv_idmap.\n  Proof.\n    induction m.\n    - reflexivity.\n    - simpl. refine (_ @ IHm).\n      refine (ecompose_1e _ @ _).\n      apply (ap (sign m)).\n      apply path_equiv. apply path_arrow.\n      apply transpose_and_restrict_id.\n  Qed.\n\n \n  Lemma sgn2_is_id : sign 2 == idmap.\n  Proof.\n    intro e.\n    unfold sign.\n    assert (h : (transpose_and_restrict e) (inr tt) = inr tt).\n    { recall ((transpose_and_restrict e) (inr tt)) as x eqn:p. rewrite p.\n      destruct x as [[] | []]; reflexivity. }\n    rewrite h. clear h.\n    rewrite (ecompose_e1).\n    recall (e (inr tt)) as x eqn:p. rewrite p. simpl.\n    destruct x as [ [[] | []] | []]; apply inverse; apply path_equiv; apply path_arrow.\n    - apply (sym2_notfixlast e p). \n    - apply (sym2_fixlast e p).\n  Qed.\n      \n  Definition sgn_beta_transpose (m : nat) (x y : fintype m) :\n    (x <> y) -> sign m (fin_transpose x y) = twist2.\n  Proof.\n    intro neq.\n    induction m.\n    - destruct x.\n    - change (sign m.+1 (fin_transpose x y))\n             with\n             (sgn_transpose (fin_transpose x y (inr tt)) oE\n              sign m (transpose_and_restrict (fin_transpose x y))).\n      destruct y as [y | []].\n      + destruct x as [x | []].\n        * rewrite\n            (path_equiv (path_arrow _ _ (transpose_and_restrict_transpose_fixlast x y))).\n          simpl. \n          refine (ecompose_1e _ @ _).\n          apply IHm. revert neq. apply functor_not.\n          apply (ap inl).\n        * rewrite (fin_transpose_beta_l).\n          change (sgn_transpose (inl y)) with twist2.\n          rewrite (path_equiv (path_arrow _ _\n                      (fin_transpose_sym (n := m.+1) (inr tt) (inl y)))).\n          rewrite (path_equiv (path_arrow _ _\n                      (transpose_and_restrict_transpose_nfx (inl y)))).\n          rewrite sgn_id. apply ecompose_e1.\n      + rewrite (fin_transpose_beta_r).\n        rewrite (path_equiv (path_arrow _ _\n                      (transpose_and_restrict_transpose_nfx x))).\n        rewrite (sgn_id). refine (ecompose_e1 _ @ _).\n        destruct x as [x | []].\n        * reflexivity.\n        * destruct (neq idpath).\n  Qed.    \n      \n\n  (** The sign sends block sum to composition  *)\n  Definition sgn_block_sum {m n : nat} (e1 : fintype m <~> fintype m) (e2 : fintype n <~> fintype n) :\n    sign (n+m) (block_sum e1 e2) = sign n e2 oE sign m e1.\n  Proof.\n    induction n.\n    - simpl.\n      refine (_ @ (ecompose_1e _)^).\n      apply (ap (sign m)).\n      apply path_equiv. apply path_arrow. intro.\n      apply (block_sum_beta_finl e1 e2 x).\n    - simpl. \n      rewrite (path_equiv (path_forall _ _ (transpose_and_restrict_block_sum e1 e2))).\n      rewrite (IHn (transpose_and_restrict e2)).\n      refine (ecompose_e_ee _ _ _ @ _).\n      apply (ap (fun g =>\n                   g oE sign n (transpose_and_restrict e2) oE\n                     sign m e1)).\n      cut (forall x : fintype n.+1,\n              sgn_transpose (functor_sum (finr m n) idmap x) = sgn_transpose x).\n      { intro H. apply H. }\n      intros [x | x]; reflexivity.\n  Qed.\n\n  Lemma functor_sum_compose {A1 A2 A3 B1 B2 B3 : Type}\n        (f1 : A1 -> A2) (f2 : A2 -> A3)\n        (g1 : B1 -> B2) (g2 : B2 -> B3) :\n    functor_sum (f2 o f1) (g2 o g1) == (functor_sum f2 g2) o (functor_sum f1 g1). \n  Proof.\n    intros [a | a]; reflexivity.\n  Defined.\n\n  Definition transpose_and_restrict_fixlast {n : nat}\n             (e : fintype n.+1 <~> fintype n.+1)\n             (fixlast : e (inr tt) = inr tt) :\n    transpose_and_restrict e == equiv_restrict e fixlast.\n  Proof.\n    apply inj_equiv_plus1.\n    intro x.\n    refine (transpose_and_restrict_eta _ x @ _ @ (equiv_restrict_eta _ _ x)^).\n    ev_equiv. unfold swap_last. rewrite fixlast.\n    apply (fin_transpose_same_is_id (n := n.+1) (inr tt) (e x)).\n  Defined.\n\n  Lemma transpose_and_restrict_fixlast1 {n : nat}\n             (e1 e2 : fintype n.+1 <~> fintype n.+1)\n             (fixlast_1: e1 (inr tt) = inr tt) :\n    transpose_and_restrict (e2 oE e1) ==\n    (transpose_and_restrict e2) oE (transpose_and_restrict e1).\n  Proof.\n    apply inj_equiv_plus1.\n    intro x.\n    refine (transpose_and_restrict_eta _ x @ _).\n    unfold swap_last. ev_equiv. rewrite fixlast_1.\n    transitivity (((transpose_and_restrict e2 +E 1) oE (transpose_and_restrict e1 +E 1)) x).\n    - ev_equiv.\n      apply inverse.\n      refine (transpose_and_restrict_eta e2 _ @ _). ev_equiv.\n      apply (ap (swap_last e2)). apply (ap e2).\n      refine (transpose_and_restrict_eta e1 _ @ _). ev_equiv.\n      unfold swap_last. rewrite fixlast_1.\n      apply (fin_transpose_same_is_id (n := n.+1)).\n    - destruct x as [x | []]; reflexivity.\n  Qed.\n\n  Lemma transpose_and_restrict_fixlast2 {n : nat}\n             (e1 e2 : fintype n.+1 <~> fintype n.+1)\n             (fixlast_2 : e2 (inr tt) = inr tt) :\n    transpose_and_restrict (e2 oE e1) ==\n    (transpose_and_restrict e2) oE (transpose_and_restrict e1).\n  Proof.\n    apply inj_equiv_plus1.\n    intro x.    \n    refine (transpose_and_restrict_eta _ _ @ _).\n    refine (_ @ (functor_sum_compose _ _ idmap idmap x)^).\n    refine (_ @ (transpose_and_restrict_eta e2 _)^).\n    refine (_ @ (ap ((swap_last e2) o e2) (transpose_and_restrict_eta e1 x)^)).\n    unfold swap_last. ev_equiv. rewrite fixlast_2.\n    refine (_ @ (fin_transpose_same_is_id (n := n.+1) _ _ )^).\n    apply inverse.\n    refine (natural_fin_transpose (e1 (inr tt)) (inr tt) e2  _ @ _).\n    rewrite fixlast_2. reflexivity.\n  Qed.\n\n  Lemma transpose_and_restrict_fixlast12 {n : nat}\n             (e1 e2 : fintype n.+1 <~> fintype n.+1)\n             (fixlast_12 : e2 (e1 (inr tt)) = inr tt) :\n    transpose_and_restrict (e2 oE e1) ==\n    (transpose_and_restrict e2) oE (transpose_and_restrict e1).\n  Proof.\n    apply inj_equiv_plus1.\n    intro x.    \n    refine (transpose_and_restrict_eta _ _ @ _).\n    refine (_ @ (functor_sum_compose _ _ idmap idmap x)^).\n    refine (_ @ (transpose_and_restrict_eta e2 _)^).\n    refine (_ @ (ap (swap_last e2 oE e2) (transpose_and_restrict_eta e1 x)^)).\n    ev_equiv.\n    refine (_ @ (ap (swap_last e2) (natural_fin_transpose (e1 (inr tt)) (inr tt) e2 (e1 x))^)).\n    unfold swap_last. ev_equiv. rewrite fixlast_12.\n    refine (fin_transpose_same_is_id (n := n.+1) (inr tt) _ @ _).\n    rewrite (fin_transpose_sym (e2 (inr tt)) (inr tt)).\n    refine ((fin_transpose_invol (n := n.+1) (inr tt) (e2 (inr tt)) _)^).\n  Qed.\n\n\n  Lemma transpose_and_restrict_nfx {n : nat}\n        (e1 e2 : fintype n.+1 <~> fintype n.+1)\n        (x2 x12: fintype n)\n        (* (p1 : e1 (inr tt) = inl x1) *)\n        (p2 : e2 (inr tt) = inl x2)\n        (p12 : e2 (e1 (inr tt)) = inl x12) :\n    transpose_and_restrict (e2 oE e1) ==\n    (fin_transpose x2 x12)\n      oE (transpose_and_restrict e2) oE (transpose_and_restrict e1).\n  Proof.\n    apply inj_equiv_plus1.\n    intro x.    \n    refine (transpose_and_restrict_eta _ _ @ _).\n    refine (_ @ (functor_sum_compose _ _ idmap idmap x)^).\n    rewrite (functor_sum_compose (transpose_and_restrict e2) (fin_transpose x2 x12) idmap idmap).\n    refine (_ @ ap ((functor_sum (fin_transpose x2 x12) idmap)\n                      o (functor_sum (transpose_and_restrict e2) idmap))\n              (transpose_and_restrict_eta e1 x)^).\n    refine (_ @ ap (functor_sum (fin_transpose x2 x12) idmap)\n              (transpose_and_restrict_eta e2 _)^).\n    ev_equiv.\n    assert (h : fin_transpose (e2 (inr tt)) (e2 (e1 (inr tt))) ==\n            functor_sum (B := Unit) (fin_transpose x2 x12) idmap ).\n    { rewrite p2.  rewrite p12. intro i. reflexivity. }\n    refine (_ @ h _). clear h.\n    unfold swap_last.  ev_equiv.\n\n    rewrite (natural_fin_transpose (e1 (inr tt)) (inr tt) e2 (e1 x)).\n    generalize (e2 (e1 x)). clear x. intro x.\n    (* four cases: x = n+1, e2 (e1 (n+1)) = x, e2 (n+1) = x, and everything else *)\n    destruct x as [x | []].\n    - rewrite p12. rewrite p2.\n      destruct (decidablepaths_fin n x12 x).\n      + rewrite p.\n        repeat rewrite fin_transpose_beta_l.\n        apply inverse.\n        apply fin_transpose_other; apply inr_ne_inl.\n      + transitivity (inl Unit x).\n        { apply fin_transpose_other.\n          - revert n0. apply functor_not.\n            intro p. exact (path_sum_inl Unit p^).\n          - apply inl_ne_inr. }\n        destruct (decidablepaths_fin n x2 x).\n        * rewrite p.\n          rewrite fin_transpose_beta_r.\n          assert (h : fin_transpose (n := n.+1) (inl x) (inr tt) (inl x12) = inl x12).\n          { apply fin_transpose_other; try (apply inl_ne_inr).\n            revert n0. apply functor_not. apply path_sum_inl. }\n          rewrite h. clear h.\n          apply inverse.\n          apply fin_transpose_beta_r.\n        * assert (h : fin_transpose (n := n.+1) (inl x12) (inl x2) (inl x) = inl x).\n          { apply fin_transpose_other;\n              apply (functor_not (path_sum_inl Unit));\n              apply (functor_not inverse).\n            - exact n0. - exact n1. }\n          rewrite h. clear h.\n          assert (h : fin_transpose (n := n.+1) (inl x2) (inr tt) (inl x) = inl x).\n          { apply fin_transpose_other; try (apply inl_ne_inr).\n            apply (functor_not (path_sum_inl Unit)).\n            apply (functor_not (inverse) n1). }\n          rewrite h. clear h.\n          apply inverse.\n          apply fin_transpose_other;\n            apply (functor_not (path_sum_inl Unit));\n            apply (functor_not inverse).\n          { exact n1. } { exact n0. }\n    - rewrite fin_transpose_beta_r.\n      rewrite p12.  rewrite p2.\n      rewrite (fin_transpose_other (n := n.+1) (inl x12) (inl x2) (inr tt)\n                                   (inr_ne_inl _ _) (inr_ne_inl _ _)).\n      rewrite fin_transpose_beta_r. rewrite fin_transpose_beta_l.\n      reflexivity.\n  Qed.\n          \n\n  (** The sign preserves composition  *)\n  Definition sgn_compose (n : nat) (e1 e2 : fintype n <~> fintype n) :\n    sign n (e2 oE e1) = (sign n e2) oE (sign n e1).\n  Proof.\n    induction n. { reflexivity. }\n    simpl. rewrite ecompose_e_ee.\n    rewrite (ecompose_ee_e _ (sign n (transpose_and_restrict e2)) _).\n    rewrite (symm_sym2 (sign n (transpose_and_restrict e2)) _).\n    rewrite (ecompose_ee_e _ _ (sgn_transpose (e2 (inr tt)))).\n    rewrite (ecompose_ee_e _ _ (sgn_transpose (e1 (inr tt)))).\n    rewrite (ecompose_e_ee _ _ (sgn_transpose (e2 (inr tt)))).\n    rewrite <- (IHn (transpose_and_restrict e1) (transpose_and_restrict e2)).\n    recall (e1 (inr tt)) as x1 eqn:p1.\n    destruct x1 as [x1 | []].\n    - recall (e2 (e1 (inr tt))) as x12 eqn:p12.\n         destruct x12 as [x12 | []].\n      +  recall (e2 (inr tt)) as x2 eqn:p2.\n         destruct x2 as [x2 | []].\n         * rewrite (path_equiv (path_forall _ _\n                                            (transpose_and_restrict_nfx e1 e2 x2 x12 p2 p12))).\n           (* rewrite p12. rewrite p2. *)\n           rewrite ecompose_ee_e.\n           rewrite (IHn\n                      (transpose_and_restrict e2 oE transpose_and_restrict e1) (fin_transpose x2 x12)).\n           rewrite (ecompose_ee_e).\n           rewrite p12. rewrite p2. simpl.\n           apply (ap (fun g => twist2 oE g)).\n           apply (ap\n                    (fun g => g oE\n                              sign n (transpose_and_restrict e2 oE transpose_and_restrict e1))).\n           rewrite p1.\n           apply (sgn_beta_transpose).\n           apply (functor_not (ap (fun x => (inl Unit x)))).\n           rewrite <- p12. rewrite <- p2.\n           apply (functor_not (equiv_inj e2)). rewrite p1.\n           apply inr_ne_inl.\n        * (* rewrite p1. refine (_ @ sgn_id n). *)\n          (* apply (ap (sign n)). *)\n          (* assert (h : x2 = x12). *)\n          (* { apply (path_sum_inl Unit). *)\n          (*   rewrite <- p2. rewrite <- p12.  rewrite p1.  reflexivity. } *)\n          (* rewrite h. clear h. *)\n          (* apply path_equiv. apply path_arrow. apply fin_transpose_same_is_id. *)\n          rewrite\n            (path_equiv (path_arrow _ _ (transpose_and_restrict_fixlast2 e1 e2 p2))).\n          apply (ap (fun g =>\n                       g oE sign n (transpose_and_restrict e2 oE transpose_and_restrict e1))).\n          rewrite p2. rewrite p1.\n          simpl. rewrite ecompose_1e.\n          apply sgn_transpose_notlast.\n          rewrite <- p2.\n          apply (functor_not (equiv_inj e2)).\n          apply inl_ne_inr. \n      + rewrite (path_equiv (path_arrow _ _\n                     (transpose_and_restrict_fixlast12 e1 e2 p12))).\n        apply (ap (fun g =>\n                       g oE sign n (transpose_and_restrict e2 oE transpose_and_restrict e1))).\n        rewrite p12. rewrite p1. simpl.\n        apply emoveL_eM. rewrite ecompose_1e.\n        simpl. \n        apply inverse. rewrite twist2_inv.\n        apply sgn_transpose_notlast.\n        intro false.\n        rewrite p1 in p12. apply (inl_ne_inr  x1 tt).\n        apply (equiv_inj e2).\n        exact (p12 @ false^).\n    - rewrite (path_equiv (path_arrow _ _ (transpose_and_restrict_fixlast1 e1 e2 p1))).\n      apply (ap (fun g =>\n                       g oE sign n (transpose_and_restrict e2 oE transpose_and_restrict e1))).\n      rewrite p1. simpl.\n      refine (ecompose_e1 _)^.\n  Qed.\n\nEnd Sign.\n\n    \n\n\n\n\n\n    \n  \n  ", "meta": {"author": "kalfsvag", "repo": "group_completions", "sha": "cc65e902a68dbb6dc05315651dce3064704a9815", "save_path": "github-repos/coq/kalfsvag-group_completions", "path": "github-repos/coq/kalfsvag-group_completions/group_completions-cc65e902a68dbb6dc05315651dce3064704a9815/finite/sign.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7260864898258671}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  mult (Succ x) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj205_coqofml_GMa3gH.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7260864792418}}
{"text": "Require Import Lia.\n\nExample silly_presburger_example : forall m n o p,\n    m + n <= n + o /\\ o + 3 = p + 3 -> m <= p.\nProof. intros. lia. Qed.\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/sf/lia.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.725987219663421}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Psatz.\n\nRequire Import kernel_graph.\nRequire Import graph_examples.\nRequire Import kernel_numeric.\n\n\n(* A walk in G from x to y. *)\nRecord walk (G : Graph) (x y : nat) := {\n  walk_intermediate : nat ; (* stevilo vmesnih vozlisc *)\n  walk_length := S (S walk_intermediate) ; (* stevilo vozlisc *)\n  walk_func :> nat -> nat ;\n  walk_in_graph : forall i, i < walk_length -> walk_func i < V G ;\n  walk_connected : forall i, i < S walk_intermediate -> G (walk_func i) (walk_func (S i)) ;\n  walk_start : walk_func 0 = x ;\n  walk_end : walk_func (S walk_intermediate) = y\n}.\n\nArguments walk_intermediate {_ _ _} _.\nArguments walk_length {_ _ _} _.\n\nTheorem mini_walk (G : Graph) (n : nat) (p : n > 0) (x y : nat) (Wxy : walk G x y):\n  walk_intermediate Wxy = n -> walk G x (walk_func G x y Wxy n).\nProof.\n  intro Wxyinl.\n  simple refine {| walk_intermediate := (n - 1) ;\n                   walk_func := (walk_func G x y Wxy) |}.\n  - intros i Ai.\n    apply walk_in_graph.\n    unfold walk_length.\n    rewrite Wxyinl.\n    omega.\n  - intros i Ai.\n    apply walk_connected.\n    rewrite Wxyinl.\n    omega.\n  - apply walk_start.\n  - replace (S (n - 1)) with n; auto.\n    omega.\nQed.\n  \n\n\n\n\nDefinition connected (G : Graph) :=\n  forall x y, x < G -> y < G -> x < y -> walk G x y.\n\nLemma prove_for_one (P : nat -> Prop) (i : nat) :\n  i < 1 -> P 0 -> P i.\nProof.\n  intros H G.\n  induction i.\n  - assumption.\n  - omega.\nQed.\n\nLemma prove_for_two (P : nat -> Prop) (i : nat) :\n  i < 2 -> P 0 -> P 1 -> P i.\nProof.\n  intros ilt2 H0 H1.\n  induction i.\n  - auto.\n  - induction i.\n    + auto.\n    + omega.\nQed.\n\nLemma complete_connected (n : nat) : connected (K n).\nProof.\n  intros x y xG yG x_lt_y.\n  simple refine {| walk_intermediate := 0 ;\n                   walk_func := (fun i => match i with\n                                       | 0 => x\n                                       | _ => y\n                                       end) |}.\n  - intros i H.\n    pattern i.\n    now apply prove_for_two.\n  - intros i H.\n    simpl ; pattern i.\n    apply prove_for_one.\n    + assumption.\n    + omega.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nLemma walk_transitive (G : Graph) (x y z : nat) :\n  x < G -> y < G -> z < G ->\n  walk G x y -> walk G y z -> walk G x z.\nProof.\n  intros ? ? ? s t.\n  assert (E : s (S (walk_intermediate s)) = t 0).\n  { rewrite walk_start. apply walk_end. }\n  simple refine {|\n           walk_intermediate := S (walk_intermediate s + walk_intermediate t) ;\n           walk_func := (fun i => if lt_dec i (walk_length s) then s i else t (S (i - walk_length s)))\n         |}.\n  - intros i ?.\n    simpl.\n    destruct (lt_dec i (walk_length s)).\n    + now apply walk_in_graph.\n    + apply walk_in_graph.\n      unfold walk_length.\n      omega.\n  - intros i ? ; simpl.\n    destruct (lt_dec i (walk_length s)) ; destruct (lt_dec (S i) (walk_length s)).\n    + apply walk_connected.\n      unfold walk_length in * ; omega.\n    + replace i with (walk_length s - 1) in *.\n      * { simpl.\n          rewrite Nat.sub_diag.\n          rewrite E.\n          apply walk_connected.\n          omega.\n        }\n      * omega.\n    + omega.\n    + unfold walk_length; simpl.\n      replace (S (i - S (walk_intermediate s))) with (S (S (i - S (S (walk_intermediate s))))).\n      * apply walk_connected.\n        unfold walk_length in *.\n        omega.\n      * unfold walk_length in *.\n        omega.\n  - now apply walk_start.\n  - simpl.\n    unfold walk_length in *.\n    destruct (lt_dec (S (S (walk_intermediate s + walk_intermediate t))) (S (S (walk_intermediate s)))).\n    + omega.\n    + rewrite minus_plus.\n      apply walk_end.\nDefined.\n\nLemma walk_symmetric (G : Graph) (x y : nat) :\n  x < G -> y < G ->\n  walk G x y -> walk G y x.\nProof.\n  intros p q Wxy.\n  simple refine {|\n    walk_intermediate := walk_intermediate Wxy ;\n    walk_func := (fun i => Wxy (walk_length Wxy - i - 1))\n  |}; unfold walk_length.\n  - intros i A.\n    apply (walk_in_graph _ _ _ Wxy).\n    unfold walk_length.\n    omega.\n  - intros i A.\n    apply E_symmetric.\n    + apply (walk_in_graph _ _ _ Wxy); unfold walk_length; omega.\n    + apply (walk_in_graph _ _ _ Wxy); unfold walk_length; omega.\n    + replace (S (S (walk_intermediate Wxy)) - i - 1) with \n              (S (S (S (walk_intermediate Wxy)) - S i - 1)).\n      * apply walk_connected.\n        omega.\n      * omega.\n  - apply walk_end.\n  - replace (S (S (walk_intermediate Wxy)) - S (walk_intermediate Wxy) - 1) with 0.\n    + apply walk_start.\n    + omega.\nQed.\n\nLemma path_is_connected (n : nat) : connected (Path n).\nProof.\n  intros x y xG yG x_lt_y.\n  simple refine {| \n    walk_intermediate := y - x - 1;\n    walk_func := (fun i => x + i) \n  |}.\n  - intros i A.\n    omega.\n  - intros i A.\n    simpl.\n    omega.\n  - auto. \n  - omega.\nQed.\n\nDefinition connectedA (G : Graph) :=\n  forall x, 0 < x < G -> walk G 0 x.\n\nLemma same_conected_zero_or_smallerP2 (G : Graph) :\n  connected G -> connectedA G.\nProof.\n  unfold connected.\n  intro Conn.\n  unfold connectedA.\n  intros x p.\n  apply Conn; omega.\nQed.\n\nLemma same_conected_zero_or_smallerP1 (G : Graph) :\n  connectedA G -> connected G.\nProof.\n  unfold connectedA.\n  intro ConnA.\n  unfold connected.\n  intros x y p q w.\n  destruct (Nat.eq_dec x 0) as [A|B].\n  - rewrite A.\n    apply ConnA.\n    omega.\n  - assert (x > 0). \n    + omega.\n    + assert (walk G 0 x).\n      * apply ConnA; omega.\n      * assert (walk G 0 y).\n        {\n        apply ConnA; omega.\n        }\n        {\n          assert (walk G x 0).\n          - apply walk_symmetric; auto; omega.\n          - apply (walk_transitive G x 0 y); auto; omega.\n        }\nQed.\n\nDefinition connectedB (G : Graph) :=\n  forall x y, x < G -> y < G -> not(x = y) -> walk G x y.\n\nLemma same_conected_smaller_or_allP2 (G : Graph) :\n  connectedB G -> connected G.\nProof.\n  unfold connectedB.\n  intro ConnB.\n  unfold connected.\n  intros x y xP yP P.\n  apply ConnB; omega.\nQed.\n\n(*\nSearch (_ < _).\n*)\n\nLemma same_conected_smaller_or_allP1 (G : Graph) :\n  connected G -> connectedB G.\nProof.\n  unfold connected.\n  intro Conn.\n  unfold connectedB.\n  intros x y xP yP P.\n  destruct (lt_eq_lt_dec x y) as [[A|B]|C].\n  - apply Conn; auto.\n  - absurd(x = y); auto.\n  - apply walk_symmetric; auto.\nQed.\n\n(* Search (_ = _). *)\n\n\n\n\nTheorem color_dec (col : nat -> bool) (x : nat):\n  {col x = false} + {col x = true}.\nProof.\n  destruct (col x); auto.\nQed.\n\nDefinition idecomposable (G : Graph) :=\n  forall col : nat -> bool, all x : G, all y : G,\n  (col x = true -> col y = false ->\n   some a : G, some b : G, (col a = true /\\ col b = false /\\ G a b)).\n\nTheorem change_location_simple1 (n : nat) :\n  forall col : nat -> bool,\n  (col 0 = true -> col n = false -> \n  some a : n, (col a = true /\\ col (S a) = false)).\nProof.\n  intros col xCol yCol.\n  induction n.\n  {\n    rewrite yCol in xCol.\n    absurd (false = true); auto.\n  }\n  {\n    destruct (color_dec col n).\n    - destruct IHn as [a [Aa H]]; auto.\n      exists a.\n      split.\n      + omega.\n      + apply H.\n    - exists n.\n      auto.\n  }\nQed.\n\nTheorem change_location_simple2 (n : nat) :\n  forall col : nat -> bool,\n  (col 0 = false -> col n = true -> \n  some a : n, (col a = false /\\ col (S a) = true)).\nProof.\n  intros col xCol yCol.\n  induction n.\n  {\n    rewrite yCol in xCol.\n    absurd (false = true); auto.\n  }\n  {\n    destruct (color_dec col n).\n    - exists n.\n      auto.\n    - destruct IHn as [a [Aa H]]; auto.\n      exists a.\n      split.\n      * omega.\n      * apply H.\n  }\nQed.\n\nTheorem change_location_simple1x (x n : nat) (Ax : x < n):\n  forall col : nat -> bool,\n  (col x = true -> col n = false -> \n  some a : n, (x <= a /\\ col a = true /\\ col (S a) = false)).\nProof.\n  intros col xCol yCol.\n  induction n.\n  {\n    omega.\n  }\n  {\n    destruct (lt_eq_lt_dec x n) as [[H1|H2]|H3].\n    {\n      destruct (color_dec col n).\n      - destruct IHn as [a [Aa H]]; auto.\n        exists a.\n        split.\n        * omega.\n        * apply H.\n      - exists n.\n        split; auto.\n        split; auto.\n        omega.\n    }\n    {\n      exists x.\n      replace x with n in *.\n      auto.\n    }\n    {\n      omega.\n    }\n  }\nQed.\n\nTheorem change_location_simple2x (x n : nat) (Ax : x < n):\n  forall col : nat -> bool,\n  (col x = false -> col n = true -> \n  some a : n, (x <= a /\\ col a = false /\\ col (S a) = true)).\nProof.\n  intros col xCol yCol.\n  induction n.\n  {\n    omega.\n  }\n  {\n    destruct (lt_eq_lt_dec x n) as [[H1|H2]|H3].\n    {\n      destruct (color_dec col n).\n      - exists n.\n        split; auto.\n        split; auto.\n        omega.\n      - destruct IHn as [a [Aa H]]; auto.\n        exists a.\n        split.\n        * omega.\n        * apply H.\n    }\n    {\n      exists x.\n      replace x with n in *.\n      auto.\n    }\n    {\n      omega.\n    }\n  }\nQed.\n\nTheorem change_location (n : nat): \n  forall col : nat -> bool, all x : n, all y : n,\n  (col x = true -> col y = false -> \n   some a : (n - 1), (\n  (col a = true /\\ col (S a) = false) \\/ \n  (col a = false /\\ col (S a) = true))).\nProof.\n  induction n.\n  {\n    intros col x Ax y Ay xCol yCol.\n    omega.\n  }\n  {\n    intros col x Ax y Ay xCol yCol.\n    destruct (lt_eq_lt_dec x y) as [[H1|H2]|H3].\n    - pose (change_location_simple1x x y H1 col xCol yCol) as CLS1x.\n      destruct CLS1x as [a H].\n      destruct H as [Aay [Axa [aCol saCol]]].\n      exists a.\n      split.\n      + omega.\n      + auto.\n    - replace x with y in *.\n      rewrite yCol in xCol.\n      absurd (false = true); auto.\n    - pose (change_location_simple2x y x H3 col yCol xCol) as CLS2x.\n      destruct CLS2x as [a [Aay [Axa [aCol saCol]]]].\n      exists a.\n      split.\n      + omega.\n      + auto.\n  }\nQed.\n\nTheorem change_location_function (n : nat) (An : n > 1): \n  forall col : nat -> bool, (forall f : nat -> nat,\n  col (f 0) = true -> col (f (n-1)) = false -> \n   some a : (n - 1), (\n  (col (f a) = true /\\ col (f (S a)) = false) \\/ \n  (col (f a) = false /\\ col (f (S a)) = true))).\nProof.\n  intros col f.\n  apply (change_location n (fun x => col (f x))); omega.\nQed.\n\n\nArguments walk_func {_ _ _} _ _.\n\nTheorem walk_idecomposable \n  (G : Graph) (col : nat -> bool) (x y n : nat) \n  (An : n > 1) (Wxy : walk G x y) :\n  walk_length Wxy = n -> \n  (col x = true -> col y = false -> \n   some a : (n - 1), (\n  (col ((walk_func Wxy) a) = true /\\ col ((walk_func Wxy) (S a)) = false) \\/ \n  (col ((walk_func Wxy) a) = false /\\ col ((walk_func Wxy) (S a)) = true))).\nProof.\n  intros Wxylen xCol yCol.\n  apply change_location_function.\n  - assumption.\n  - replace x with (walk_func Wxy 0) in xCol.\n    + assumption.\n    + apply walk_start.\n  - replace y with (walk_func Wxy (n - 1)) in yCol.\n    + assumption.\n    + replace (n - 1) with (S (walk_intermediate Wxy)).\n      * apply walk_end.\n      * rewrite <- Wxylen.\n        unfold walk_length.\n        omega.\nQed.\n\n\n\nTheorem connected_then_idecomposable (G : Graph) : \n  connected G -> idecomposable G.\nProof.\n  unfold connected.\n  intro Conn.\n  unfold idecomposable.\n  intros col x xA y yA xCol yCol.\n  assert (walk G x y) as Wxy.\n  {\n    destruct (lt_eq_lt_dec x y) as [[H1|H2]|H3].\n    - apply Conn; auto.\n    - replace y with x in yCol.\n      absurd (col x = true); auto.\n      rewrite yCol.\n      auto.\n    - apply walk_symmetric; auto.\n  }\n  {\n    assert (some a : (walk_length Wxy -1), (\n      (col ((walk_func Wxy) a) = true /\\ col ((walk_func Wxy) (S a)) = false) \\/ \n      (col ((walk_func Wxy) a) = false /\\ col ((walk_func Wxy) (S a)) = true))) \n      as H.\n    {\n      apply walk_idecomposable.\n      - unfold walk_length.\n        omega.\n      - auto.\n      - assumption.\n      - assumption.\n    }\n    {\n      destruct H as [q [Aq [[H0 H1]|[H2 H3]]]].\n      {\n        exists (Wxy q).\n        split.\n        - apply walk_in_graph.\n          omega.\n        - exists (Wxy (S q)).\n          split.\n          + apply walk_in_graph.\n            omega.\n          + split; auto; split; auto.\n            apply walk_connected.\n            unfold walk_length in Aq.\n            omega.\n      }\n      {\n        exists (Wxy (S q)).\n        split.\n        - apply walk_in_graph.\n          omega.\n        - exists (Wxy q).\n          split.\n          + apply walk_in_graph.\n            omega.\n          + split; auto; split; auto.\n            apply (E_symmetric G).\n            * apply walk_in_graph.\n              omega.\n            * apply walk_in_graph.\n              omega.\n            * apply walk_connected.\n              unfold walk_length in Aq.\n              omega.\n      }\n    }\n  }\nQed.\n\n\n\n\nDefinition increasing_connected_graph (G : Graph) :=\n  (forall x : nat, (0 < x < (V G) -> some y : x, (E G x y))).\n\n(*\nTheorem increasing_connected_then_connected (G : Graph) :\n  increasing_connected_graph G -> connectedA G.\nProof.\n  unfold increasing_connected_graph.\n  intro ICG.\n  unfold connectedA.\n  intros x Ax.\n  pose (ICG x Ax) as H.\n  destruct H.\n*)\n\nDefinition idecomposableA (G : Graph) :=\n  all x : G, all y : G, forall col : nat -> bool,\n  (col x = true -> col y = false ->\n   some a : G, some b : G, (col a = true /\\ col b = false /\\ G a b)).\n\nTheorem idecomposable_then_idecomposableA (G : Graph) : \n  idecomposable G -> idecomposableA G.\nProof.\n  unfold idecomposable.\n  intro Idec.\n  unfold idecomposableA.\n  intros x Ax y Ay col.\n  apply Idec; omega.\nQed.\n\n\n\n\nTheorem idecomposableA_then_someone_to_zero (G : Graph) (y : nat): \n  idecomposableA G -> \n  0 < y < G -> \n  some x : V G, G 0 x.\nProof.\n  unfold idecomposableA.\n  intros Idec H.\n  assert (0 < G) as A0. omega.\n  assert (y < G) as Ay. omega.\n  set (col := (fun i => match i with\n                 | 0 => true\n                 | _ => false\n               end)).\n  assert (col 0 = true) as Col0. auto.\n  assert (y <> 0). omega.\n  assert (exists y0 : nat, y = S y0). exists (y - 1). omega.\n  destruct H1.\n  assert (col y = false) as yCol. rewrite H1. auto.\n  pose (Idec 0 A0 y Ay col Col0 yCol) as Idec0y.\n  destruct Idec0y as [a [Aa [b [Bb K]]]].\n  destruct (Nat.eq_dec 0 a).\n  - exists b.\n    rewrite <- e in K.\n    split; auto.\n    apply K.\n  - absurd (col a = true).\n    + assert (a > 0).\n      * omega.\n      * assert (exists a0 : nat, a = S a0). exists (a - 1). omega.\n        destruct H3.\n        assert (col a = false). rewrite H3. auto.\n        rewrite H4. auto.\n    + apply K.\nQed.\n\n\n\nRecord connected_subgraph (G : Graph) (n : nat) := {\n  cs_size := n ;\n  cs_col : nat -> bool ;\n  cs_size_proof : sum' (V G) (fun x => if cs_col x then 1 else 0) = cs_size ;\n  cs_connected_proof : all x : (V G), all y : (V G), (\n    cs_col x = true-> cs_col y = true -> walk G x y)\n}.\n\nTheorem sum_max_simple (n : nat) (f : nat -> bool) :\n  sum' n (fun x => if f x then 1 else 0) <= n.\nProof.\n  induction n.\n  - auto.\n  - rewrite sum'_S.\n    assert ((if f n then 1 else 0) <= 1).\n    + destruct (f n); omega.\n    + omega.\nQed.\n\nTheorem sum_end (n : nat) (f : nat -> bool) \n  (P : sum' n (fun x => if f x then 1 else 0) = n) :\n  all y : n, ((fun x => if f x then 1 else 0) y = 1).\nProof.\n  induction n.\n  {\n    intros y Ay.\n    omega.\n  }\n  {\n    rewrite sum'_S in P.\n    destruct (color_dec f n).\n    - destruct (f n).\n      + absurd (false = true); auto.\n      + pose (sum_max_simple n f).\n        absurd (true = true); omega. (* ni v cilju ampak predpostavke *)\n    - destruct (f n) in P.\n      + assert (sum' n (fun x : nat => if f x then 1 else 0) = n).\n        * omega.\n        * assert (all y : n, ((if f y then 1 else 0) = 1)) as HH; auto.\n          intros y Ay.\n          destruct (Nat.eq_dec y n).\n          {\n            destruct (color_dec f y).\n            - rewrite e0 in e1. rewrite e in e1. absurd (false = true); auto.\n            - destruct (f y); auto; absurd (false = true); auto.\n          }\n          {\n            apply HH.\n            omega.\n          }\n      + absurd (0 + sum' n (fun x : nat => if f x then 1 else 0) = S n); auto.\n        pose (sum_max_simple n f).\n        omega.\n  }\nQed.\n\nTheorem sum_end_f (n : nat) (f : nat -> bool) \n  (P : sum' n (fun x => if f x then 1 else 0) = n) :\n  all y : n, (f y = true).\nProof.\n  intros y Ay.\n  pose (sum_end n f P y Ay).\n  assert ((if f y then 1 else 0) = 1).\n  - apply e.\n  - destruct (f y); auto.\n    omega.\nQed.\n\nTheorem conected_subgraph_connected (G : Graph):\n  connected_subgraph G (V G) -> connected G.\nProof.\n  intro ConnSub.\n  unfold connected.\n  intros x y Ax Ay Axy.\n  pose (cs_connected_proof G (V G) ConnSub x Ax y Ay) as H.\n  pose (cs_size_proof G (V G) ConnSub).\n  apply H.\n  - apply (sum_end_f (V G)).\n    + unfold cs_size in e; auto.\n    + apply Ax.\n  - apply (sum_end_f (V G)).\n    + unfold cs_size in e; auto.\n    + apply Ay.\nQed.\n\nTheorem conected_subgraph_extend (G : Graph) (n : nat) (P : 1 + n < (V G)):\n  idecomposable G -> connected_subgraph G n -> connected_subgraph G (1 + n).\nProof.\n  unfold idecomposable.\n  intros Idec ConnSub.\n  set (col := (cs_col G n ConnSub)).\n  (* sedaj potrebujemo nek x barve true in nek y barve false \n     potem poiscemo vozlisce b in dodamo novo barvo col' \n     ki je enaka povsod razen v vozliscu b je true\n     tako smo dobili vecji povezan podgarf\n  *)\n  pose (Idec col).\n\nTheorem idecomposable_extend (G : Graph) : \n  idecomposable G -> connectedA G.\n\n\nTheorem idecomposable_then_connectedA (G : Graph) : \n  idecomposable G -> connectedA G.\nProof.\n  unfold idecomposable.\n  intro Idec.\n  unfold connectedA.\n  intros x Ax.\n  assert (0 < V G) as B0.\n  {\n    omega.\n  }\n  {\n    assert (x < V G) as Bx.\n    - omega.\n    - pose (Idec 0 B0 x Bx).\n  }\n\n\n\nTheorem idecomposable_then_connected (G : Graph) : \n  idecomposable G -> connected G.\nProof.\n  unfold idecomposable.\n  intro Idec.\n  unfold connected.\n  intros x y Ax Ay Axy.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(**\n\nTheorem connected_then_idecomposable (G : Graph) : \n  connected G -> idecomposable G.\nProof.\n  unfold connected.\n  intro Conn.\n  unfold idecomposable.\n  intros col x xA y yA xCol yCol.\n  assert (walk G x y) as Wxy.\n  {\n    destruct (lt_eq_lt_dec x y) as [[H1|H2]|H3].\n    - apply Conn; auto.\n    - replace y with x in yCol.\n      absurd (col x = true); auto.\n      rewrite yCol.\n      auto.\n    - apply walk_symmetric; auto.\n  }\n  {\n    set (qqq := walk_intermediate Wxy).\n    induction (walk_intermediate Wxy).\n    {\n    exists x.\n    split; auto.\n    exists y.\n    split; auto.\n    split; auto.\n    split; auto.\n    assert (walk_func Wxy 0 = x).\n    - apply walk_start.\n    - assert (walk_func Wxy (S (walk_intermediate Wxy)) = y).\n      + apply walk_end.\n      + assert (walk_intermediate Wxy = 0) as IH0.\n        * replace (walk_intermediate Wxy) with qqq; auto.\n          admit.\n        * rewrite IH0 in H0.\n          rewrite <- H. (* to pomeni da naredis revrite H iz druge strani*)\n          rewrite <- H0.\n          apply walk_connected.\n          rewrite IH0.\n          auto.\n    }\n    {\n\n    }\n  }\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n  (col : nat -> bool) (x y : nat) \n  (Ax : x < (V G)) (Ay : y < (V G))\n  (xCol : col x = true) (yCol : col y = false) (Wxy : walk G x y):\n  (walk_intermediate Wxy = n) ->\n  (some i : (walk_length Wxy), \n  ((col (walk_func Wxy i) = true /\\ col (walk_func Wxy (S i)) = false) \\/\n  (col (walk_func Wxy i) = false /\\ col (walk_func Wxy (S i)) = true))).\nProof.\n  revert Wxy.\n  revert yCol xCol Ay Ax.\n  revert y.\n  unfold walk_length.\n  induction n.\n\nTheorem walk_idecomposable (G : Graph) (n : nat) \n  (col : nat -> bool) (x y : nat) \n  (Ax : x < (V G)) (Ay : y < (V G))\n  (xCol : col x = true) (yCol : col y = false) (Wxy : walk G x y):\n  (walk_intermediate Wxy = n) ->\n  (some i : (walk_length Wxy), \n  ((col (walk_func Wxy i) = true /\\ col (walk_func Wxy (S i)) = false) \\/\n  (col (walk_func Wxy i) = false /\\ col (walk_func Wxy (S i)) = true))).\nProof.\n  revert Wxy.\n  revert yCol xCol Ay Ax.\n  revert y.\n  unfold walk_length.\n  induction n.\n  \n\nTheorem walk_idecomposable (G : Graph) (n : nat) \n  (col : nat -> bool) (x y : nat) \n  (Ax : x < (V G)) (Ay : y < (V G))\n  (AWxy : walk_func Wxy x < walk_func Wxy y)\n  (xCol : col x = true) (yCol : col y = false) (Wxy : walk G x y):\n  (walk_intermediate Wxy = n) ->\n  (some i : (walk_length Wxy), \n  (col (walk_func Wxy i) = true /\\ col (walk_func Wxy (S i)) = false)).\nProof.\n  revert Wxy.\n  revert yCol xCol Ay Ax.\n  revert y.\n  unfold walk_length.\n  induction n.\n  {\n    intros y yCol xCol Ay Ax.\n    intro Wxy.\n    intro Wxyinl.\n    rewrite Wxyinl.\n    exists 0.\n    rewrite walk_start.\n    split; auto.\n    replace 1 with (S (walk_intermediate Wxy)).\n    - split; auto.\n      rewrite walk_end; auto.\n    - rewrite Wxyinl; auto.\n  }\n  {\n    intros y yCol xCol Ay Ax.\n    intro Wxy.\n    intro Wxyinl.\n    rewrite Wxyinl.\n    destruct (color_dec col (walk_func Wxy (S n))) as [yPredF|yPredT].\n    - (* set (yPred := walk_func Wxy (S (S n))). *)\n      assert (walk G x (walk_func Wxy (S n))) as mWxy.\n      + {\n          simple refine {| walk_intermediate := n;\n                           walk_func := (walk_func Wxy) |}.\n          - intros i Ai.\n            apply walk_in_graph.\n            unfold walk_length.\n            rewrite Wxyinl.\n            omega.\n          - intros i Ai.\n            apply walk_connected.\n            rewrite Wxyinl.\n            omega.\n          - apply walk_start.\n          - omega.\n        }\n        (*\n        apply mini_walk; auto.\n        omega.\n        *)\n      + assert (walk_intermediate mWxy = n) as mWxinl.\n        {\n          admit.\n        }\n        {\n          assert (some i : S (S (walk_intermediate mWxy)),\n                 (col (mWxy i) = true /\\ col (mWxy (S i)) = false)).\n          * apply IHn; auto.\n            {\n              apply walk_in_graph.\n              unfold walk_length.\n              rewrite Wxyinl.\n              omega.\n            }\n            {\n              destruct (Nat.eq_dec x (walk_func Wxy (S n))).\n              - replace (Wxy (S n)) with x in *.\n                rewrite yPredF in xCol.\n                absurd (false = true); auto.\n              - assert (walk_func Wxy (S (S n)) = y).\n                + rewrite <- Wxyinl.\n                  apply walk_end.\n                + rewrite <- H in Ax.\n                  destruct (lt_eq_lt_dec x (Wxy (S n))) as [[H1|H2]|H3]; auto.\n                  * absurd (x = Wxy (S n)); auto.\n                  * (admited****)\n(**\n            }\n          * rewrite mWxinl in H.\n            destruct H as [i [Ai [j [Aj H0]]]].\n            exists i.\n            split; auto.\n            exists j.\n            split; auto.\n            assert (walk_func mWxy = walk_func Wxy) as same_func.\n            {\n              admit.\n            }\n            {\n              rewrite same_func in H0.\n              auto.\n            }\n        }\n    -\n  }\n\n\n*)\n(*\nTheorem walk_idecomposable (G : Graph) (*(n : nat)*) (col : nat -> bool) (x y : nat) \n  (Ax : x < (V G)) (Ay : y < (V G)) \n  (Wxy : walk G x y)\n  (xCol : col x = true) (yCol : col y = false): \n  (*n = walk_intermediate Wxy ->*)\n  (some i : (walk_length Wxy), \n  (some j : (walk_length Wxy), \n  (col (walk_func Wxy i) = true /\\ col (walk_func Wxy j) = false))).\nProof.\n  unfold walk_length.\n  (* pose (walk_end G x y Wxy). *)\n  (**intro An.**)\n  induction (walk_intermediate Wxy).\n  {\n    exists 0.\n    split; auto.\n    rewrite walk_start.\n    exists 1.\n    split; auto.\n    assert (walk_func Wxy 1 = y) as Wf1y.\n    - replace 1 with (S (walk_intermediate Wxy)).\n      + apply (walk_end G x y Wxy).\n      + unfold walk_intermediate.\n        admit.\n    - rewrite Wf1y.\n      auto.\n  }\n  {\n\n  }\n\n\n\n\n\n\n\n\n\n\n\nTheorem change_location_functionB (n : nat) (f : nat -> nat): \n  forall col : nat -> bool, all x : n, all y : n,\n  (col (f x) = true -> col (f y) = false -> \n   some a : n, (\n  (col (f a) = true /\\ col (f (S a)) = false) \\/ \n  (col (f a) = false /\\ col (f (S a)) = true))).\nProof.\n  intro col.\n  apply (change_location n (fun x => col (f x))).\nQed.\n\nTheorem change_location_functionA (n : nat) : \n  forall col : nat -> bool, all x : n, all y : n,\n  (forall f : nat -> nat,\n  (col (f x) = true -> col (f y) = false -> \n   some a : n, (\n  (col (f a) = true /\\ col (f (S a)) = false) \\/ \n  (col (f a) = false /\\ col (f (S a)) = true)))).\nProof.\n  intros col x Ax y Ay f.\n  apply change_location_function; auto.\nQed.\n\n\n\n\n\n(* Search (_ < _).*)\n\n(* Search ((_ < _) -> (_ < _) -> (_ < _)). *)\n\nArguments walk_func {_ _ _} _ _.\n\nTheorem walk_idecomposable \n  (G : Graph) (col : nat -> bool) (x y n : nat)\n  (Ax : x < n) (Ay : y < n) (Wxy : walk G x y) :\n  walk_length Wxy = n -> \n  (col ((walk_func Wxy) x) = true -> col ((walk_func Wxy) y) = false -> \n   some a : n, (\n  (col ((walk_func Wxy) a) = true /\\ col ((walk_func Wxy) (S a)) = false) \\/ \n  (col ((walk_func Wxy) a) = false /\\ col ((walk_func Wxy) (S a)) = true))).\nProof.\n  intro Wxylen.\n  apply change_location_functionA; auto.\nQed.\n\nTheorem walk_idecomposableA \n  (G : Graph) (col : nat -> bool) (x y n : nat) (Wxy : walk G x y) :\n  walk_length Wxy = n -> \n  (col x = true -> col y = false -> \n   some a : n, (\n  (col ((walk_func Wxy) a) = true /\\ col ((walk_func Wxy) (S a)) = false) \\/ \n  (col ((walk_func Wxy) a) = false /\\ col ((walk_func Wxy) (S a)) = true))).\nProof.\n  intros Wxylen xCol yCol.\n  replace x with (walk_func Wxy 0) in xCol.\n  replace y with (walk_func Wxy (S (walk_intermediate Wxy))) in yCol.\n  - pose (change_location_functionA (walk_length Wxy) col (Wxy 0)).\nQed.\n**)\n\n(*\nTheorem idecomposableA_then_someone_to_zero (G : Graph) : \n  idecomposableA G -> 0 < V G -> some x : V G, G 0 x.\nProof.\n  unfold idecomposableA.\n  intros Idec Ag.\n  destruct (lt_eq_lt_dec 0 (V G - 1)) as [[H1|H2]|H3].\n  - pose (Idec 0 Ag).\n    \n  - admit.\n  - omega.\n  *)", "meta": {"author": "MitjaR", "repo": "Coq_Graph", "sha": "efe875c6d0eaf2f000598c2fc66f756de1a75b54", "save_path": "github-repos/coq/MitjaR-Coq_Graph", "path": "github-repos/coq/MitjaR-Coq_Graph/Coq_Graph-efe875c6d0eaf2f000598c2fc66f756de1a75b54/graph_connected.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7259872161903809}}
{"text": "(*Benjamin Bracquier et Lilian Soler*)\n(**\nObjectif de ce suppport de TD :\nfamiliarisation avec les AST winstr pour le langage WHILE.\n*)\n\n(* ------------------------------------------------------------ *)\n(** * Familiarisation avec les AST winstr pour le langage WHILE *)\n\n(** ** Syntaxe abstraite *)\nInductive aexp :=\n| Aco : nat -> aexp (* constantes *)\n| Ava : nat -> aexp (* variables *)\n| Apl : aexp -> aexp -> aexp\n| Amu : aexp -> aexp -> aexp\n| Amo : aexp -> aexp -> aexp\n.\n\nInductive bexp :=\n| Btrue : bexp\n| Bfalse : bexp\n| Bnot : bexp -> bexp\n| Band : bexp -> bexp -> bexp\n| Bor : bexp -> bexp -> bexp\n| Beq : bexp -> bexp -> bexp (* test égalité de bexp *)\n| Beqnat : aexp -> aexp -> bexp (* test égalité d'aexp *)\n.\n\nInductive winstr :=\n| Skip   : winstr\n| Assign : nat -> aexp -> winstr\n| Seq    : winstr -> winstr -> winstr\n| If     : bexp -> winstr -> winstr -> winstr\n| While  : bexp -> winstr -> winstr\n.\n\n(** Le langage IMP : comme WHILE mais sans While *)\nInductive instr :=\n| ISkip   : instr\n| IAssign : nat -> aexp -> instr\n| ISeq    : instr -> instr -> instr\n| IIf     : bexp -> instr -> instr -> instr\n.\n\n(** Définir les AST des programmes suivants *)\n(** x3 := 5 * x2 *)\nExample P1 : instr := IAssign 3 (Amu (Aco 5) (Ava 2)).\n\n(** x2 := x2 + 1 *)\nExample P2 : instr := IAssign 2 (Apl (Ava 2) (Aco 1)).\n\n(** if x1 = x3 then (x2 := x2 + 1; x2 := x2 + 1) else x3 := 5 * x2 *)\nExample P3 : instr := IIf (Beqnat (Ava 1) (Ava 3)) (ISeq (IAssign 2 (Apl (Ava 2) (Aco 1))) (IAssign 2 (Apl (Ava 2) (Aco 1)))) (IAssign 3 (Amu (Aco 5)  (Ava 2))). \n\n(** ** Sémantique fonctionnelle *)\n\nInductive state :=\n  | Nil : state\n  | Cons : nat -> state -> state\n.\n\n(** On se donne des notations préalables pour faciliter la présentation *)\nNotation \"[]\" := Nil.\nNotation \"x :: y\" := (Cons x y).\n\n(** L'appel [get i s] rend la valeur associée à xi dans l'état s *)\nFixpoint get (i: nat) (s: state) : nat :=\n  match s with\n  | []     => 0\n  | v :: s' =>\n    match i with\n    | O => v\n    | S i' => get i' s'\n    end\n  end.\n\n(** *** Sémantique fonctionnelle de aexp*)\nFixpoint evalA (a: aexp) (s: state) : nat :=\n  match a with\n  | Aco n => n\n  | Ava x => get x s\n  | Apl a1 a2 =>  evalA a1 s + evalA a2 s\n  | Amu a1 a2 =>  evalA a1 s * evalA a2 s\n  | Amo a1 a2 =>  evalA a1 s - evalA a2 s\n  end.\n\n\n(** *** Sémantique fonctionnelle de bexp*)\nDefinition eqboolb b1 b2 : bool :=\n  match b1, b2  with\n  | true, true   => true\n  | false, false => true\n  | _ , _        => false\n  end.\n\nFixpoint eqnatb n1 n2 : bool :=\n   match n1, n2 with\n  | O, O         => true\n  | S n1', S n2' => eqnatb n1' n2'\n  | _, _         => false\n  end.\n\n Fixpoint evalB (b : bexp) (s : state) : bool :=\n  match b with\n  | Btrue => true\n  | Bfalse => false\n  | Bnot b => negb (evalB b s)\n  | Band e1 e2 => (evalB e1 s) && (evalB e2 s)\n  | Bor e1 e2 => (evalB e1 s) || (evalB e2 s)\n  | Beq e1 e2 => eqboolb (evalB e1 s) (evalB e2 s)\n  | Beqnat n1 n2 => eqnatb (evalA n1 s) (evalA n2 s)\n  end.\n\n\n(** *** Sémantique fonctionnelle de IMP *)\n\n(** La mise à jour d'une variable [v] par un nouvel entier [n]\n    dans un état [s] s'écrit [update s v n'].\n    Cette fonction n'échoue jamais et écrit la valeur à sa place même\n    si elle n'est pas encore définie dans l'état [s]. *)\n\n(** À définir en TD *)\n(** [update i v s] rend l'état dans lequel xi vaut [v],\n    les valeurs des autres variables étant celles de [s].\n    Attention à bien traiter tous les cas, notament ceux\n    où l'état est représenté par une liste vide : tout se passe\n    comme si, à la place, on avait une liste comprenant\n    suffisamment de 0 (valeur par défaut).\n *)\nFixpoint update (i:nat) (v:nat) (s:state) : state :=\n  match i with\n  |O => match s with\n        |[] => v::[]\n        |v'::s' =>v::s'\n        end\n  |S i' => match s with\n           |[] => 0::update i' v []\n           |v'::s' =>v':: update i' v s'\n           end\n  end.\n\n\n\n(** Quelques états pour faire des tests *)\n(** S1 est un état dans lequel la variable \"x0\" vaut 1 et la variable \"x1\"\n    vaut 2 et toutes les autres valent 0 (valeur par défaut) *)\n\nExample S1 := 1 :: 2 :: Nil.\nExample S2 := 0 :: 3 :: Nil.\nExample S3 := 0 :: 7 :: 5 :: 41 :: Nil.\n\nExample S4 :=\n  let s1 := update 4 1 S1 in\n  let s2 := update 3 2 s1 in\n  let s3 := update 2 3 s2 in\n  let s4 := update 2 3 s3 in\n  update 0 5 s4.\nExample test_S4 : S4 = 5 :: 2 :: 3 :: 2 :: 1 :: [].\nProof. reflexivity. Qed. (*reflexivity. Qed.*)\n\n(** Peut s'écrire dans une premier temps avec update laissé \"Admitted\". *)\nFixpoint evalI (i : instr) (s : state) : state :=\n  match i with\n  | ISkip       => s\n  | IAssign x a => update x (evalA a s) s\n  | ISeq i1 i2  => evalI i2 (evalI i1 s)    \n  | IIf b i1 i2 => if evalB b s then evalI i1 s else evalI i2 s       \n  end.\n\n(** La pré-commande \"Fail\" indique que l'on s'attend à un échec *)\n(** La présence de [{struct i}] indique que l'argument devant\n    décroître structurellement est [i] ;\n    Pour [evalI] on aurait pu le préciser aussi mais Coq a su\n    reconstruire cette information à partir du corps de la fonction.\n*)\nFail Fixpoint evalW (i : winstr) (s : state) {struct i} : state :=\n  (** à compléter, en expliquant le diagnostic rendu par Coq *)\n  match i with\n  | Skip       => s\n  |Assign x a => update x (evalA a s) s\n  |Seq i1 i2 => evalW i2 (evalW i1 s)\n  |If b i1 i2 => if evalB b s then evalW i1 s else evalW i2 s\n  |While b i => if evalB b s then evalW (While b i) (evalW i s) else s \n  end.\n\n(** ** Tests *)\n\nExample test1 : evalI P1 S1 = 1 :: 2 :: 0 :: 0 :: [].\nProof. reflexivity. Qed.\n\nExample test2 : evalI P1 S4 = 5 :: 2 :: 3 :: 15 :: 1 :: [].\nProof. reflexivity. Qed.\n\nExample test3 : evalI P3 S1 = 1 :: 2 :: 0 :: 0 :: [].\nProof. reflexivity. Qed.\n\nExample test4 : evalI P3 S4 = 5 :: 2 :: 5 :: 2 :: 1 :: [].\nProof. reflexivity. Qed.\n\n", "meta": {"author": "LilianSOLER", "repo": "PF7", "sha": "dbe343844a602990cc9061a37d175d4c46e3eef3", "save_path": "github-repos/coq/LilianSOLER-PF7", "path": "github-repos/coq/LilianSOLER-PF7/PF7-dbe343844a602990cc9061a37d175d4c46e3eef3/tps-lt/td5_winstr_l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7259738278874825}}
{"text": "Require Import vcfloat.VCFloat.\nRequire Import List.\nImport ListNotations.\n\nRequire Import common op_defs dotprod_model sum_model.\nRequire Import dot_acc float_acc_lems list_lemmas.\n\nSection MVGenDefs. \n\nDefinition matrix {A : Type} := list (list A).\n\nDefinition vector {A : Type} := list A.\n\nFixpoint zero_vector {A: Type} (m : nat) (zero : A) : vector := \n  match m with \n  | S n => zero :: zero_vector n zero\n  | _ => []\n  end. \n\nFixpoint zero_matrix {A: Type} (m n: nat) (zero : A) : matrix := \n  match m with \n  | S m' => zero_vector n zero :: zero_matrix m' n zero\n  | _ => []\n  end. \n\nDefinition is_finite_vec {t : type} (v: vector) : Prop := \n  forall x, In x v -> Binary.is_finite (fprec t) (femax t) x = true.\n\nDefinition is_zero_vector {A: Type} v (zero : A) : Prop := forall x, In x v -> x = zero.\n\nDefinition map_mat {A B: Type} (f : A -> B) (M : matrix) : matrix :=\n  map (map f) M.  \n\nDefinition map2 {A B C: Type} (f: A -> B -> C) al bl :=\n  map (uncurry f) (List.combine al bl).\n\nFixpoint zero_map_vec {A B : Type} (zero : B) (v : @vector A) : @vector B :=\n  match v with \n  | [] => []\n  | h :: t => zero :: zero_map_vec zero t\nend. \n\nFixpoint zero_map_mat {A B : Type} (zero : B) (M : @matrix A) : @matrix B :=\n  match M with \n  | [] => []\n  | hM :: tM => zero_map_vec zero hM :: zero_map_mat zero tM\nend. \n\nDefinition in_matrix {T : Type} (A : list (list T)) (a : T) := \n  let A' := flat_map (fun x => x) A in In a A'.\n\nDefinition matrix_index {A} (m: matrix) (i j: nat) (zero: A) : A :=\n nth j (nth i m nil) zero.\n\nDefinition eq_size {T1 T2} \n  (A : list (list T1)) (B : list (list T2)) := length A = length B /\\\n  forall x y, In x A -> In y B -> length x = length y.\n\nEnd MVGenDefs.\n\nSection MVOpDefs.\n\n(* generic vector sum *)\nDefinition vec_sum {A: Type} (u v : vector) (sum : A -> A -> A)  : @vector A := \n  map2 sum u v.\n\n(* sum vectors of reals *)\nDefinition vec_sumR u v :=  vec_sum u v Rplus.\n\n(* generic matrix sum *)\nDefinition mat_sum {T: Type} (A B : matrix) (sum : T -> T -> T) : @matrix T := \n  map2 (map2 sum) A B.\n\n(* sum matrices of reals *)\nDefinition mat_sumR A B :=  mat_sum A B Rplus.\n\n(* floating-point matrix vector multiplication *)\nDefinition mvF {NAN : Nans}  {t: type} (m: matrix ) (v: vector ) : vector  :=\n      map (fun row => @dotprod NAN t row v) m.\n\n(* real valued matrix vector multiplication *)\nDefinition mvR  (m: matrix) (v: vector) : vector :=\n      map (fun row => dotprodR row v) m.\n\nEnd MVOpDefs.\n\nNotation \"A *f v\" := (mvF A v) (at level 40).\nNotation \"A *r v\"  := (mvR A v) (at level 40).\nNotation \"A *fr v\" := (map FT2R (mvF A v)) (at level 40).\n\nNotation \"u -v v\" := (vec_sum u v Rminus) (at level 40).\nNotation \"u +v v\" := (vec_sumR u v) (at level 40).\n\nNotation \"A -m B\" := (mat_sumR A (map_mat Ropp B)) (at level 40).\nNotation \"A +m B\" := (mat_sumR A B) (at level 40).\n\nNotation \"E _( i , j )\"  :=\n  (matrix_index E i j 0%R) (at level 15).\n\nSection MVLems.\n\nLemma map2_length {A B C: Type} (f: A -> B -> C) al bl : \n  length al = length bl -> \n  length (map2 f al bl) = length al.\nProof. intros; unfold map2; rewrite map_length, combine_length, H, Nat.min_id; auto. Qed.\n\nLemma map_mat_length {A B: Type} :\n  forall (f : A -> B) (M : @matrix A) ,\n  length (map_mat f M) = length M.\nProof. intros; induction M; [simpl; auto | simpl; rewrite IHM; auto]. Qed. \n\nLemma zero_matrix_length {A: Type} (m n: nat) (zero : A) :\n  length (zero_matrix m n zero) = m .\nProof. induction m; unfold zero_matrix; simpl; auto. Qed. \n\nLemma mvF_len {NAN : Nans} t m v:\n  length (@mvF NAN t m v)  = length m.\nProof. induction m; simpl; auto. Qed.\n\nLemma dotprodF_nil {NAN : Nans} {t: type} row :\ndotprod row [] = (Zconst t 0). \nProof. destruct row; simpl; auto. Qed. \n\nLemma mvF_nil {NAN : Nans} {t: type} : forall m, @mvF NAN t m [] = zero_vector (length m) (Zconst t 0).\nProof. \nintros; unfold mvF.\nset (f:= (fun row : list (ftype t) => dotprod row [])).\nreplace (map f m) with  (map (fun _ => Zconst t 0) m).\ninduction m; simpl; auto.\n{ rewrite IHm; auto. }\napply map_ext_in; intros.\nsubst f; simpl. rewrite dotprodF_nil; auto.\nQed.\n\nLemma mvR_nil : forall m, mvR m [] = zero_vector (length m) 0%R. \nProof.\nintros; unfold mvR.\nset (f:= (fun row : list R => dotprodR row [])).\nreplace (map f m) with  (map (fun _ => 0%R) m).\ninduction m; simpl; auto.\n{ rewrite IHm; auto. }\napply map_ext_in; intros.\nsubst f; simpl. rewrite dotprodR_nil_r; auto.\nQed.\n\nLemma mat_sum_length {T: Type} (sum: T -> T -> T) :  \n  forall (A B: matrix),\n  forall (Hlen : length A = length B),\n  length (mat_sum A B sum) = length A.\nProof. intros. unfold mat_sum; rewrite map2_length; auto. Qed.\n\nLemma zero_vector_length {A : Type} (m : nat) (zero : A) :\n  length (zero_vector m zero) =  m.\nProof. induction m; simpl; auto. Qed.\n\nLemma vec_sumR_cons : \nforall (u v : vector) u0 v0,\nvec_sum (u0 :: u) (v0 :: v) Rplus = (u0 + v0) :: vec_sum u v Rplus.\nProof. induction u; destruct v; (intros; unfold vec_sum, map2; simpl; auto). Qed.\n\nLemma vec_sum_zeroR:\n  forall (v : vector),\n  vec_sum v (zero_vector (length v) 0%R) Rplus = v.\nProof.\nintros; induction v; simpl; auto.\nrewrite vec_sumR_cons, IHv, Rplus_0_r; auto.\nQed.\n\nLemma map_nil {A B: Type} (f : A -> B) : map f [] = []. \nProof. simpl; auto. Qed.\n\n\nLemma mat_sumR_cons:  \n  forall (A B: matrix) av bv,\n  forall (Hlen : length A = length B),\n  mat_sumR (av :: A) (bv :: B) = vec_sumR av bv :: mat_sumR A B.\nProof. induction A; destruct B; (intros; unfold mat_sum, vec_sum, map2; simpl; auto). Qed.\n\nLemma mat_sumR_zero:\n  forall (B : matrix) (n : nat)\n  (Hin : forall row, In row B -> length row  = n), \n  mat_sum B (zero_matrix (length B) n 0%R) Rplus = B.\nProof.\nintros ? ? ?. induction B; auto.\nfold (mat_sumR (a :: B) (zero_matrix (length (a :: B)) n 0)).\nfold (mat_sumR B (zero_matrix (length B) n 0)) in IHB.\nsimpl; rewrite mat_sumR_cons.\nrewrite <- IHB; [ f_equal | intros; apply Hin; simpl; auto].\nrewrite <- vec_sum_zeroR; unfold vec_sumR; repeat f_equal.\nsymmetry; apply Hin; simpl; auto.\nrepeat f_equal; apply IHB; intros; apply Hin; simpl; auto.\nrewrite zero_matrix_length; auto.\nQed.\n\nLemma mat_sum_nil {A : Type} M (f: A -> A -> A) :\n  mat_sum M [] f = [].\nProof. destruct M; auto. Qed.\n\nLemma zero_map_mat_length {A B: Type} :\n  forall (M : @matrix A) (z : B), length (zero_map_mat z M) = length M. \nProof.\nintros; induction M; [simpl; auto | simpl; rewrite IHM; auto ].\nQed. \n\nLemma vec_sumR_bounds a b a' b':\na' + b' :: vec_sumR a b =  vec_sumR (a' :: a) (b' :: b).\nProof. unfold vec_sumR; simpl; auto. Qed.\n\nLemma vec_sumR_opp :\nforall u v, \nlength u = length v -> \nvec_sum u v Rminus = vec_sum u (map Ropp v) Rplus.\nProof.\nintros ?.\ninduction u.\n{ intros; simpl; auto. }\nintros; destruct v; simpl; auto.\nrewrite vec_sumR_cons.\nrewrite <- IHu; auto.\nQed.\n\nLemma vec_sumR_comm :\nforall u v , \nlength u = length v ->\nvec_sumR u v = vec_sumR v u.\nProof.\nintros ?.\ninduction u.\n{ intros. simpl in H; symmetry in H; apply length_zero_iff_nil in H; subst;\nsimpl; auto. }\nintros; destruct v; auto. \nunfold vec_sumR; rewrite !vec_sumR_cons.\nfold (vec_sumR v u);\nfold (vec_sumR u v).\nrewrite <- IHu. rewrite Rplus_comm; auto.\nsimpl in H; auto.\nQed.\n\nLemma vec_sumR_assoc :\nforall u v w, \nlength u = length v ->\nlength w = length v ->\nvec_sumR (vec_sumR u v) w = vec_sumR u (vec_sumR v w).\nProof.\nintros ?.\ninduction u.\n{ intros. simpl in H; symmetry in H; apply length_zero_iff_nil in H; subst;\nsimpl; auto. }\nintros; destruct v; simpl; auto.\ndestruct w; unfold vec_sumR; simpl; auto.\nunfold vec_sumR; rewrite !vec_sumR_cons.\nfold (vec_sumR v w). \nfold (vec_sumR u v). \nsimpl in H, H0.\nfold (vec_sumR (vec_sumR u v) w); \nrewrite IHu; [rewrite Rplus_assoc; auto  | lia | lia ].\nQed.\n\nLemma vec_sumR_minus :\nforall u , \nvec_sumR (map Ropp u) u = (zero_vector (length u) 0%R).\nProof.\nintros; induction u.\n{ simpl; auto. }\nunfold vec_sumR; simpl; rewrite !vec_sumR_cons.\nfold (vec_sumR (map Ropp u) u).\nrewrite IHu; f_equal; nra.\nQed. \n\nLemma vec_sum_length {A : Type} :\nforall u v (f : A -> A -> A) , \nlength u = length v -> \nlength u = length (vec_sum u v f).\nProof.\nintros ?; induction u.\n{ simpl; auto. }\nintros; destruct v; simpl; auto.\nspecialize (IHu v f); rewrite IHu.\nunfold vec_sum; auto.\nsimpl in H; auto.\nQed. \n\nLemma vec_sum_length2  {A B: Type} (f : B -> B-> B) :\nforall (u : list A) v w, \nlength u = length v -> \nlength v = length w -> \nlength u = length (vec_sum v w f).\nProof.\nintros ?;\ninduction u.\n{ intros. simpl in H; symmetry in H; apply length_zero_iff_nil in H; subst;\nsimpl; auto. }\nintros; destruct v; simpl; auto.\ndestruct w. { simpl in H0;  discriminate. }\nsimpl; auto.\nspecialize (IHu v w); rewrite IHu.\nunfold vec_sum; auto.\nsimpl in H; auto.\nsimpl in H; auto.\nQed. \n\nLemma nth_app_0 {T : Type} :\nforall (l0 l : list T),\nl0 <> [] ->\nnth 0 (l0 ++ l) = nth 0 l0.\nProof.\nintros.\ninduction l0; auto.\nsimpl. assert False by auto; contradiction.\nQed.\n\nLemma matrix_index_nil {A} (i j: nat) (zero: A) : \n   matrix_index [] i j zero = zero.\nProof. unfold matrix_index. destruct i; destruct j; simpl; auto. Qed.\n\nLemma vec_sumR_nth :\nforall j u a\n(Hlen: length a = length u), \nnth j u 0%R - nth j a 0%R = nth j (vec_sum u a Rminus) 0%R.\nProof.\ninduction j; destruct u; intros.\n{ simpl; apply length_zero_iff_nil in Hlen; subst; simpl; nra. }\n{ destruct a; try discriminate; auto. } \n{ destruct a; simpl; [nra | try discriminate; auto]. } \ndestruct a; try discriminate; auto.\nassert (length a = length u) by (simpl in Hlen; lia);\nspecialize (IHj u a H);\nsimpl; auto.\nQed.\n\nLemma nth_cons_vec_sumR a l r u2 : forall i,\n  nth i ((l) +v (u2)) 0 = nth i (l) 0 + nth i ( u2) 0 ->\n  nth (S i) ((a :: l) +v (r :: u2)) 0 = nth (S i) (a :: l) 0 + nth (S i) (r :: u2) 0.\nProof. intros; simpl; auto. Qed.\n\nLemma nth_cons_mvR b B u : forall i,\n  nth (S i) ( (b::B) *r u) = nth i (B *r u).\nProof. intros; simpl; auto. Qed.\n\nLemma length_mvR_mvF {NANS : Nans} {t : type} : forall (m : @matrix (ftype t)) v, \nlength ((map_mat FT2R m) *r (map FT2R v)) = length (m *fr v).\nProof.\n  intros. \n  unfold mvR, mvF, map_mat.\nrewrite !map_length; auto.\nQed.\n\nLemma nth_vec_sum op : forall u1 u2 \n  (Hlen: length u2 = length u1) i\n  (Hop : op 0 0 = 0),\n  nth i (vec_sum u1 u2 op) 0 = op (nth i u1 0) (nth i u2 0).\nProof.\ninduction u1. intros.\nrewrite length_zero_iff_nil in Hlen.\nsubst. simpl. destruct i; auto.\ndestruct u2; try discriminate. intros.\nsimpl; destruct i; auto.\nrewrite <- IHu1; auto.\nQed.\n\nLemma vec_sum_nth_plus : forall u1 u2 \n(Hlen: length u2 = length u1) i,\nnth i (u1 +v u2) 0 = nth i u1 0 + nth i u2 0.\nProof.\ninduction u1. intros. \nrewrite length_zero_iff_nil in Hlen.\nsubst. destruct i; simpl; ring.\ndestruct u2; intros.\ndestruct i; try discriminate.\ndestruct i; simpl; try ring.\napply IHu1. simpl in Hlen; lia.\nQed.\n\nEnd MVLems.", "meta": {"author": "ak-2485", "repo": "BLAS_fp_error", "sha": "286db6fc51f4160fc74abc2f129ea05f0a37cc54", "save_path": "github-repos/coq/ak-2485-BLAS_fp_error", "path": "github-repos/coq/ak-2485-BLAS_fp_error/BLAS_fp_error-286db6fc51f4160fc74abc2f129ea05f0a37cc54/accuracy_proofs/gem_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.725890467804787}}
{"text": "Set Warnings \"-local-declaration\".\n\nRequire Import\n  Coq.Unicode.Utf8\n  Coq.Classes.Morphisms\n  Coq.Setoids.Setoid.\n\n(***********************************************************************\n * This is a minimal Boolean Logic comprised of ∨, ¬ and three axioms. *)\n\nModule Type MinimalBooleanLogic.\n\nParameter t : Type.             (* The type of boolean propositions *)\n\n(** These three terms are syntactic and can be defined in terms of the\n    fundamentals above. They are given as parameters so that module authors\n    may chose economical definitions; we also provides implies as a relation\n    in Prop to facilitate use of Coq's rewriting system. *)\nParameter implies : t -> t -> Prop.\nParameter true    : t.\nParameter false   : t.\n\n#[global]\nDeclare Instance implies_Reflexive : Reflexive implies.\n#[global]\nDeclare Instance implies_Transitive : Transitive implies.\n\n(** The following are fundamental to a classical definition of this logic. *)\nParameter not : t -> t.\nParameter or  : t -> t -> t.\n\n#[global]\nDeclare Instance not_respects_implies : Proper (implies --> implies) not.\n#[global]\nDeclare Instance or_respects_implies : Proper (implies ==> implies ==> implies) or.\n\n#[global]\nDeclare Scope boolean_scope.\nBind Scope boolean_scope with t.\nDelimit Scope boolean_scope with boolean.\nOpen Scope boolean_scope.\n\nNotation \"¬ p\"   := (not p)   (at level 75, right associativity) : boolean_scope.\nInfix    \"∨\"     := or        (at level 85, right associativity) : boolean_scope.\nNotation \"p ⇒ q\" := (¬ p ∨ q) (at level 86, right associativity) : boolean_scope.\nNotation \"⊤\"     := true      (at level 0, no associativity) : boolean_scope.\nNotation \"⊥\"     := false     (at level 0, no associativity) : boolean_scope.\n\nDefinition equivalent p q := implies p q /\\ implies q p.\n\nInfix \"⟹\" := implies    (at level 99, right associativity) : boolean_scope.\nInfix \"≈\"  := equivalent (at level 90, no associativity) : boolean_scope.\n\n(** This is one set of fundamental axioms of boolean algebra.\n *\n * NOTE: It is possible to formulate the following using a single axiom:\n *\n *   ∀ p q r s,\n *     ¬(¬(¬(p ∨ q) ∨ r) ∨ ¬(p ∨ ¬(¬r ∨ ¬(r ∨ s)))) ≈ r\n *\n * However, the proofs of the three axioms below in terms of this single one\n * are laborious and left as an exercise to the motivated reader. Further\n * notes may be found in the paper \"Short Single Axioms for Boolean Algebra\"\n * by McCune, et al. *)\nAxiom or_comm    : ∀ p q,   p ∨ q ≈ q ∨ p.\nAxiom or_assoc   : ∀ p q r, (p ∨ q) ∨ r ≈ p ∨ (q ∨ r).\nAxiom huntington : ∀ p q,   ¬(¬p ∨ ¬q) ∨ ¬(¬p ∨ q) ≈ p.\n\n(** These axioms establish the meaning of the syntactic terms. *)\nAxiom or_inj      : ∀ p q,  p ⟹ p ∨ q.\nAxiom true_def    : ∀ p,    p ∨ ¬p ≈ ⊤.\nAxiom false_def   : ∀ p,    ¬(p ∨ ¬p) ≈ ⊥.\n\nEnd MinimalBooleanLogic.\n\nModule MinimalBooleanLogicFacts (Import B : MinimalBooleanLogic).\n\n#[global]\nProgram Instance equivalent_Equivalence : Equivalence equivalent.\nNext Obligation. now intro x; split. Qed.\nNext Obligation. repeat intro; split; destruct H; now intuition. Qed.\nNext Obligation. repeat intro; split; destruct H, H0; now transitivity y. Qed.\n\n#[global]\nProgram Instance implies_respects_implies :\n  Proper (implies --> implies ==> Basics.impl) implies.\nNext Obligation.\n  repeat intro.\n  unfold Basics.flip in H.\n  now rewrite <- H0, <- H1.\nQed.\n\n#[global]\nProgram Instance implies_respects_equivalent :\n  Proper (equivalent ==> equivalent ==> iff) implies.\nNext Obligation.\n  repeat intro.\n  destruct H, H0.\n  split; intros.\n  - now rewrite H1, H3, H0.\n  - now rewrite <- H2, <- H3, <- H.\nQed.\n\n#[global]\nProgram Instance equivalent_respects_equivalent :\n  Proper (equivalent ==> equivalent ==> iff) equivalent.\nNext Obligation.\n  repeat intro.\n  split; intros.\n  - now rewrite <- H, H1, H0.\n  - now rewrite H, H1, <- H0.\nQed.\n\n#[global]\nProgram Instance not_respects_equivalent :\n  Proper (equivalent ==> equivalent) not | 9.\nNext Obligation.\n  repeat intro.\n  destruct H.\n  split; intros.\n  - now rewrite H0.\n  - now rewrite H.\nQed.\n\n#[global]\nProgram Instance or_respects_equivalent :\n  Proper (equivalent ==> equivalent ==> equivalent) or.\nNext Obligation.\n  repeat intro.\n  destruct H, H0.\n  split.\n  - now rewrite H, H0.\n  - now rewrite H1, H2.\nQed.\n\nLtac one_arg :=\n  repeat intro;\n  match goal with\n    [ H : _ ≈ _ |- _ ≈ _ ] =>\n    let H1 := fresh \"H\" in\n    let H2 := fresh \"H\" in\n    destruct H as [H1 H2]; split;\n    first [ now rewrite H1\n          | now rewrite H2 ]\n  end.\n\nLtac two_arg :=\n  repeat intro;\n  match goal with\n    [ HA : _ ≈ _, HB : _ ≈ _ |- _ ≈ _ ] =>\n    let H1 := fresh \"H\" in\n    let H2 := fresh \"H\" in\n    let H3 := fresh \"H\" in\n    let H4 := fresh \"H\" in\n    destruct HA as [H1 H2], HB as [H3 H4]; split;\n    first [ now rewrite H1, H3\n          | now rewrite H2, H4 ]\n  end.\n\n#[local] Obligation Tactic := solve [ one_arg | two_arg ].\n\nTheorem or_inj_r p q : p ⟹ q ∨ p.\nProof.\n  rewrite or_comm.\n  now apply or_inj.\nQed.\n\nTheorem true_impl p : (⊤ ⟹ p) <-> p ≈ ⊤.\nProof.\n  split; intro.\n  - split; auto.\n    rewrite <- (true_def p).\n    now apply or_inj.\n  - now rewrite H.\nQed.\n\nTheorem impl_true p : p ⟹ ⊤.\nProof.\n  rewrite <- (true_def p).\n  now apply or_inj.\nQed.\n\n(** Many of the following proofs are based on work from:\n    \"A Complete Proof of the Robbins Conjecture\", by Allen L. Mann\n    May 25, 2003 *)\nTheorem or_not p : p ∨ ¬p ≈ ¬p ∨ ¬¬p.\nProof.\n  pose proof (huntington p (¬¬ p)) as H1.\n  pose proof (huntington (¬ p) (¬¬ p)) as H2.\n  pose proof (huntington (¬ p) (¬ p)) as H3.\n  pose proof (huntington (¬¬ p) (¬ p)) as H4.\n  rewrite <- H4.\n  rewrite <- H3 at 2.\n  rewrite <- H2 at 1.\n  rewrite <- H1 at 1.\n  rewrite <- !or_assoc.\n  rewrite (or_comm _ (¬ (¬ ¬ ¬ p ∨ ¬ p))).\n  rewrite !or_assoc.\n  apply or_respects_equivalent.\n    now rewrite or_comm.\n  rewrite <- !or_assoc.\n  rewrite (or_comm _ (¬ (¬ ¬ p ∨ ¬ ¬ p))).\n  rewrite !or_assoc.\n  apply or_respects_equivalent.\n    reflexivity.\n  apply or_respects_equivalent.\n    now rewrite or_comm.\n  now rewrite or_comm.\nQed.\n\nTheorem not_not p : ¬¬p ≈ p.\nProof.\n  pose proof (huntington (¬¬ p) (¬ p)) as H1.\n  pose proof (huntington p (¬¬ p)) as H2.\n  rewrite <- H1.\n  rewrite (or_comm _ (¬¬p)), <- or_not.\n  rewrite or_comm.\n  rewrite (or_comm _ (¬p)).\n  now apply huntington.\nQed.\n\nTheorem contrapositive p q : (p ⟹ q) <-> (¬q ⟹ ¬p).\nProof.\n  split; intro.\n  - rewrite H.\n    reflexivity.\n  - apply not_respects_implies in H.\n    now rewrite !not_not in H.\nQed.\n\nTheorem not_swap p q : ¬p ≈ q <-> p ≈ ¬q.\nProof.\n  split; intro.\n  - rewrite <- not_not.\n    now rewrite H.\n  - rewrite H.\n    now apply not_not.\nQed.\n\nTheorem not_inj p q : ¬p ≈ ¬q -> p ≈ q.\nProof.\n  intro.\n  rewrite <- (not_not p).\n  rewrite <- (not_not q).\n  now rewrite H.\nQed.\n\nTheorem not_true : ¬⊤ ≈ ⊥.\nProof. now rewrite <- (true_def ⊥), false_def. Qed.\n\nTheorem not_false : ¬⊥ ≈ ⊤.\nProof.\n  rewrite <- (false_def ⊤), true_def.\n  now apply not_not.\nQed.\n\nTheorem or_false p : p ∨ ⊥ ≈ p.\nProof.\n  pose proof (huntington ⊥ ⊥) as H1.\n  rewrite (or_comm _ ⊥) in H1.\n  rewrite false_def in H1.\n  rewrite !not_false in H1.\n  assert (H2 : ⊤ ∨ ¬(⊤ ∨ ⊤) ≈ ⊤).\n    rewrite <- (true_def ⊤) at 1.\n    rewrite or_assoc.\n    rewrite (or_comm (¬⊤)).\n    rewrite not_true at 1.\n    rewrite H1.\n    rewrite <- not_true.\n    now apply true_def.\n  assert (H3 : ⊤ ∨ ⊤ ≈ ⊤).\n    rewrite <- H2 at 2.\n    rewrite <- or_assoc.\n    now apply true_def.\n  assert (H4 : ⊥ ∨ ⊥ ≈ ⊥).\n    rewrite <- not_true at 1.\n    rewrite <- not_true at 1.\n    rewrite <- H3 at 1.\n    rewrite not_true.\n    exact H1.\n  rewrite <- (huntington p p) at 2.\n  rewrite (or_comm _ p).\n  rewrite false_def.\n  rewrite <- H4 at 2.\n  rewrite <- (false_def p) at 2.\n  rewrite <- or_assoc.\n  rewrite (or_comm p (¬p)).\n  now rewrite huntington.\nQed.\n\nTheorem false_or p : ⊥ ∨ p ≈ p.\nProof. now rewrite or_comm; apply or_false. Qed.\n\nTheorem or_idem p : p ∨ p ≈ p.\nProof.\n  assert (H1 : ∀ q, ¬ (¬ q ∨ ¬ q) ≈ q).\n    intro q.\n    rewrite <- (huntington q q) at 3.\n    rewrite (or_comm (¬q) q).\n    rewrite false_def.\n    now rewrite or_false.\n  specialize (H1 (¬p)).\n  rewrite not_not in H1.\n  apply not_inj.\n  exact H1.\nQed.\n\nTheorem or_true p : p ∨ ⊤ ≈ ⊤.\nProof.\n  rewrite <- (true_def p) at 1.\n  rewrite <- or_assoc.\n  rewrite or_idem.\n  now apply true_def.\nQed.\n\nTheorem true_or p : ⊤ ∨ p ≈ ⊤.\nProof. now rewrite or_comm; apply or_true. Qed.\n\n(** Either this or or_inj must be taken as an axiom *)\nTheorem impl_implies : ∀ p q, (p ⟹ q) <-> (⊤ ⟹ p ⇒ q).\nProof.\n  split; intros.\n  - rewrite <- H.\n    (* rewrite impl_def. *)\n    rewrite or_comm.\n    rewrite true_def.\n    reflexivity.\n  - rewrite <- (huntington p q).\n    (* rewrite impl_def in H. *)\n    rewrite <- H.\n    rewrite not_true.\n    rewrite or_false.\n    apply contrapositive.\n    rewrite not_not.\n    rewrite or_comm.\n    now apply or_inj.\nQed.\n\nTheorem false_impl p : ⊥ ⟹ p.\nProof.\n  rewrite <- (false_def p).\n  apply contrapositive.\n  rewrite not_not.\n  rewrite or_comm.\n  now apply or_inj.\nQed.\n\nEnd MinimalBooleanLogicFacts.\n", "meta": {"author": "jwiegley", "repo": "coq-cds4ltl", "sha": "2ff031b854cafbaa1e98239efc1fc486078b608d", "save_path": "github-repos/coq/jwiegley-coq-cds4ltl", "path": "github-repos/coq/jwiegley-coq-cds4ltl/coq-cds4ltl-2ff031b854cafbaa1e98239efc1fc486078b608d/src/MinBool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7258904631875769}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Functor.\n\n(** \nOpposite of a functor F : C -> D is a functor F^op : C^op -> D^op with the same object and arrow maps.\n *)\nSection Opposite_Functor.\n  Context {C D : Category} (F : (C –≻ D)%functor).\n  \n  Local Open Scope morphism_scope.\n  Local Open Scope object_scope.\n    \n  Program Definition Opposite_Functor : (C^op –≻ D^op)%functor :=\n    {|\n      FO := F _o;\n      FA := fun _ _ h => F @_a _ _ h;\n      F_id := fun a => F_id F a;\n      F_compose := fun _ _ _ f g => F_compose F g f\n    |}.\n\nEnd Opposite_Functor.\n\nNotation \"F '^op'\" := (Opposite_Functor F) : functor_scope.\n\n(* We can compose functors. The object and arrow maps are simply function compositions of object and arrow maps. *)\nSection Functor_Compose.\n  Context {C C' C'' : Category} (F : (C –≻ C')%functor) (F' : (C' –≻ C'')%functor).\n\n  Local Open Scope morphism_scope.\n  Local Open Scope object_scope.\n  \n  Program Definition Functor_compose : (C –≻ C'')%functor :=\n    {|\n      FO := fun c => F' _o (F _o c);\n      FA := fun c d f => F' _a (F _a f)\n    |}.\n  \nEnd Functor_Compose.\n\nNotation \"F ∘ G\" := (Functor_compose G F) : functor_scope. \n\n(** Associativity of functor composition *)\nSection Functor_Assoc.\n  Context {C1 C2 C3 C4 : Category}\n          (F : (C1 –≻ C2)%functor)\n          (G : (C2 –≻ C3)%functor)\n          (H : (C3 –≻ C4)%functor).\n\n  Local Open Scope functor_scope.\n    \n  Theorem Functor_assoc : (H ∘ G) ∘ F = H ∘ (G ∘ F).\n  Proof.\n    Func_eq_simpl; trivial.\n  Defined.    \n                              \nEnd Functor_Assoc.\n\n(** The identitiy functor *)\n\nProgram Definition Functor_id (C : Category) : (C –≻ C)%functor :=\n  {|\n    FO := fun x => x;\n    FA := fun c d f => f\n  |}.\n\nSection Functor_Identity_Unit.\n  Context  (C C' : Category) (F : (C –≻ C')%functor).\n\n  (** Fucntor_id is the left ididntity of functor composition. *)\n  Theorem Functor_id_unit_left : ((Functor_id C') ∘ F)%functor = F.\n  Proof.\n    Func_eq_simpl; trivial.\n  Defined.\n\n  (** Functor_id is the right identity of functor composition. *)\n  Theorem Functor_id_unit_right : (Functor_compose (Functor_id _) F) = F.\n  Proof.\n    Func_eq_simpl; trivial.\n  Defined.\n\nEnd Functor_Identity_Unit.\n\n", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/Functor/Functor_Ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7258235879902047}}
{"text": "(* Enumerated types *)\nInductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\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\nCompute (next_weekday friday).\n\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\n(* Booleans *)\nInductive bool : Type :=\n  | true\n  | false.\n\nDefinition negb (b : bool) : bool :=\n  match b with\n  | true  => false\n  | false => true\n  end.\n\nDefinition andb (b1 b2 : bool) : bool :=\n  match b1 with\n  | true  => b2\n  | false => false\n  end.\n\nDefinition orb (b1 b2 : bool) :=\n  match b1 with\n  | true  => true\n  | false => b2\n  end.\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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition nandb (b1 b2 : bool) : bool :=\n  negb (b1 && b2).\n\nExample test_nandb1: (nandb true false) = true.\nProof. reflexivity. Qed.\n\nExample test_nandb2: (nandb false false) = true.\nProof. reflexivity. Qed.\n\nExample test_nandb3: (nandb false true) = true.\nProof. reflexivity. Qed.\n\nExample test_nandb4: (nandb true true) = false.\nProof. reflexivity. Qed.\n\nDefinition andb3 (b1 b2 b3 : bool) : bool :=\n  b1 && b2 && b3.\n\nExample test_andb31: (andb3 true true true) = true.\nProof. reflexivity. Qed.\n\nExample test_andb32: (andb3 false true true) = false.\nProof. reflexivity. Qed.\n\nExample test_andb33: (andb3 true false true) = false.\nProof. reflexivity. Qed.\n\nExample test_andb34: (andb3 true true false) = false.\nProof. reflexivity. Qed.\n\nCheck true.\n\nCheck true \n    : bool.\n\nCheck (negb true) \n    : bool.\n\nCheck negb\n    : bool -> bool.\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black     => true\n  | white     => true\n  | primary _ => false\n  end.\n\nDefinition is_red (c : color) : bool :=\n  match c with\n  | primary red => true\n  | _           => false\n  end.\n\nModule Playground.\n  Definition b : rgb := blue.\nEnd Playground.\n\nCheck Playground.b.\n\nModule TuplePlayground.\n\nInductive bit : Type :=\n  | B0\n  | B1.\n\nInductive nybble : Type :=\n  | bits (b0 b1 b2 b3 : bit).\n\nCheck (bits B1 B0 B1 B0)\n    : nybble.\n\nDefinition all_zero (nb : nybble) : bool :=\n  match nb with\n  | bits B0 B0 B0 B0 => true\n  | bits _ _ _ _     => false\n  end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\n\nCompute (all_zero (bits B0 B0 B0 B0)).\n\nEnd TuplePlayground.\n\nModule NatPlayground.\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\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\nCheck S.\n\nCheck pred : nat -> nat.\n\nCheck minustwo : nat -> nat.\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 :=\n  negb (evenb n).\n\nExample test_oddb1: oddb 1 = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_oddb2: oddb 4 = false.\nProof. simpl. reflexivity. Qed.\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\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.\n\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.\n\nEnd NatPlayground2.\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\nFixpoint fact_tr (n acc : nat) : nat :=\n  match n with\n  | O    => acc\n  | S n' => fact_tr n' (mult n acc)\n  end.\n\nDefinition factorial (n : nat) : nat :=\n  fact_tr n 1.\n\nExample test_factorial1: (factorial 3) = 6.\nProof. reflexivity. Qed.\n\nExample test_factorial2: (factorial 5) = 120.\nProof. reflexivity. Qed.\n\nNotation \"x + y\" := (plus x y)\n                        (at level 50, left associativity)\n                        : nat_scope.\n\nNotation \"x - y\" := (minus x y)\n                       (at level 50, left associativity)\n                       : nat_scope.\n\nNotation \"x * y\" := (mult x y)\n                       (at level 40, left associativity)\n                       : nat_scope.\n\nCheck ((0 + 1) + 1) : nat.\n\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O => match m with\n         | O => true\n         | _ => 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' => 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\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nExample test_leb3': (4 <=? 2) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition ltb (n m : nat) : bool :=\n  leb (S n) m.\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1: (ltb 2 2) = false.\nProof. reflexivity. Qed.\n\nExample test_ltb2: (ltb 2 4) = true.\nProof. reflexivity. Qed.\n\nExample test_ltb3: (ltb 4 2) = false.\nProof. reflexivity. Qed.\n\n(* Proof by simplification *)\nTheorem plus_O_n : forall n : nat,\n  0 + n = n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem plus_1_l : forall n : nat,\n  1 + n = S n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem mult_0_l : forall n : nat,\n0 * n = 0.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\n(* Proof by rewrite *)\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 ->\n  m = o ->\n  n + m = m + o.\nProof.\n  intros n m o.\n  intros H0.\n  rewrite -> H0.\n  intros H1.\n  rewrite <- H1.\n  reflexivity.\nQed.\n\nCheck mult_n_O.\n(* 0 = n * 0 *)\n\nCheck mult_n_Sm.\n(* n * m + n = n * S m *)\n\nTheorem mult_n_0_m_0 : forall n m : nat,\n  (n * 0) + (m * 0) = 0.\nProof.\n  intros n m.\n  rewrite <- mult_n_O.\n  rewrite <- mult_n_O.\n  reflexivity.\nQed.\n\nTheorem mult_n_1 : forall n : nat,\n  n * 1 = n.\nProof.\n  intros n.\n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_O.\n  reflexivity.\nQed.\n\n(* Proof by case analysis *)\nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  destruct n.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative : forall b1 b2 : bool,\n  andb b1 b2 = andb b2 b1.\nProof.\n  intros b1 b2.\n  destruct b1.\n  - destruct b2.\n    + reflexivity.\n    + reflexivity.\n  - destruct b2.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  destruct b.\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 n m : bool,\n  andb n m = true -> m = true.\nProof.\n  intros.\n  destruct n.\n  - simpl in H. apply H.\n  - simpl in H. destruct m.\n    + reflexivity.\n    + apply H.\nQed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  intros n.\n  destruct n.\n  - reflexivity.\n  - reflexivity.\nQed.\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.\n  rewrite -> H.\n  rewrite -> H.\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.\n  rewrite -> H.\n  rewrite -> H.\n  apply negb_involutive.\nQed.\n\nTheorem andb_eq_orb : forall b c : bool,\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros .\n  destruct b.\n  - simpl in H. rewrite -> H. reflexivity.\n  - simpl in H. apply H.\nQed.\n\nInductive bin : Type :=\n  | Z  : bin\n  | B0 : bin -> bin\n  | B1 : bin -> bin.\n\nFixpoint incr (m : bin) : bin :=\n  match m with\n  | Z     => B1 Z\n  | B0 m' => B1 m'\n  | B1 m' => B0 (incr m')\n  end.\n\nExample test_bin_inrc1: (incr (B1 Z)) = B0 (B1 Z).\nProof. reflexivity. Qed.\n\nExample test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\nProof. reflexivity. Qed.\n\nExample test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\nProof. reflexivity. Qed.\n\nFixpoint bin_to_nat (m : bin) : nat :=\n  match m with\n  | Z     => 0\n  | B0 m' => 2 * bin_to_nat m'\n  | B1 m' => 1 + 2 * bin_to_nat m'\n  end.\n", "meta": {"author": "maxjanney", "repo": "Coq-Files", "sha": "9c47b1674315c48f7d2e102570af09f0dfefb59b", "save_path": "github-repos/coq/maxjanney-Coq-Files", "path": "github-repos/coq/maxjanney-Coq-Files/Coq-Files-9c47b1674315c48f7d2e102570af09f0dfefb59b/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7258235639718837}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint double (double_arg0 : Nat) : Nat\n           := match double_arg0 with\n              | zero => zero\n              | succ n => succ (succ (double n))\n              end.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : Lst) : Nat\n           := match len_arg0 with\n              | nil => zero\n              | cons x y => succ (len y)\n              end.\n\nLemma lem : forall l1 l2 n, succ (len (append l1 l2)) = len (append l1 (cons n l2)).\nProof.\n   induction l1.\n   - intros. simpl. f_equal. apply IHl1.\n   - intros. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Lst), eq (len (append x x)) (double (len x)).\nProof.\ninduction x.\n   - simpl. rewrite <- IHx. f_equal. rewrite (lem x x n). reflexivity.\n   - reflexivity.\nQed.\n              \n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7258124542772413}}
{"text": "Require Export P01.\n\n\n\n(** **** Exercise: 3 stars, recommended (t_update_permute)  *)\n(** Use [beq_idP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  intros n. induction n.\n  - reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n. induction n.\n  - intros m. simpl. destruct m.\n    + reflexivity.\n    + intros H. inversion H.\n  - intros m. simpl. induction m.\n    + intros H. inversion H.\n    + intros H. apply IHn in H. rewrite H. reflexivity.\nQed.\n\nTheorem beq_nat_true_iff : forall n1 n2 : nat,\n  beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  intros n1 n2. split.\n  - apply beq_nat_true.\n  - intros H. rewrite H. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\nTheorem beq_nat_false_iff : forall x y : nat,\n  beq_nat x y = false <-> x <> y.\nProof.\n  intros x y. unfold not. split.\n  - (* -> *) intros H0 H1. apply beq_nat_true_iff in H1. rewrite H1 in H0. inversion H0.\n  - (* <- *) intros H. induction x as [| x'].\n    + induction y as [| y'].\n      { exfalso. apply H. reflexivity. }\n      { generalize dependent y'. auto. }\n    + induction y as [| y'].\n      { generalize dependent x'. auto. }\n      { simpl. destruct (beq_nat x' y') eqn:Heq.\n        - exfalso. apply H. apply f_equal. apply beq_nat_true_iff. apply Heq.\n        - reflexivity. }\nQed.\n\nTheorem beq_id_true_iff : forall id1 id2 : id,\n  beq_id id1 id2 = true <-> id1 = id2.\nProof.\n   intros [n1] [n2].\n   unfold beq_id.\n   rewrite beq_nat_true_iff.\n   split.\n   - (* -> *) intros H. rewrite H. reflexivity.\n   - (* <- *) intros H. inversion H. reflexivity.\nQed.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  destruct contra.  Qed.\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  intros b. split.\n  - (* -> *) apply not_true_is_false.\n  - (* <- *) intros H. rewrite H. intros H'. inversion H'.\nQed.\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n    (t_update (t_update m x2 v2) x1 v1)\n  = (t_update (t_update m x1 v1) x2 v2).\nProof.\n  intros. unfold t_update. apply functional_extensionality.\n  intros x. destruct (beq_id x1 x) eqn: H1.\n  - apply beq_id_true_iff in H1. rewrite <- H1. rewrite <- beq_id_false_iff in H.\n    rewrite H. reflexivity.\n  - reflexivity.\nQed.", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/07/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7258012363562378}}
{"text": "Require Import Coq.Classes.Morphisms Coq.Program.Program Coq.Unicode.Utf8.\n\n(* First, two ways to do quoting in the naive scenario without\n holes/variables in the expression: *)\n\nModule simple.\n  (* An example term language and evaluation: *)\n  Inductive Expr := Plus (a b: Expr) | Mult (a b: Expr) | Zero | One.\n\n  Fixpoint eval (e: Expr): nat :=\n    match e with\n    | Plus a b => eval a + eval b\n    | Mult a b => eval a * eval b\n    | Zero => 0\n    | One => 1\n    end.\n\n  (* First up is the simplest approach I can think of. *)\n  Module approach_A.\n    Class Quote (n: nat) := quote: Expr.\n\n    Arguments quote _ {Quote}.\n\n    Section instances.\n\n      Context n m `{Quote n} `{Quote m}.\n\n      Global Instance: Quote 0 := Zero.\n      Global Instance: Quote 1 := One.\n      Global Instance: Quote (n + m) := Plus (quote n) (quote m).\n      Global Instance: Quote (n * m) := Mult (quote n) (quote m).\n\n    End instances.\n\n    Ltac do_quote :=\n      match goal with\n      |- (?a = ?b) => change (eval (quote a) = eval (quote b))\n      end.\n\n    Lemma example: (1 + 0 + 1) * (1 + 1) = (1 + 1) + (1 + 1).\n     do_quote.\n    Admitted.\n  End approach_A.\n\n  (* This works, but there's something unsatisfying about this quotation, because\n  the actual Quote instances are not validated until we get to the [change] tactic,\n  which validates the quotation by requiring convertibility.\n\n  Next, we show an alternative implementation where the Quote instances\n  are all proved locally correct at their definition: *)\n\n  Module approach_B.\n    Class Quote (n: nat) := { quote: Expr; eval_quote: n = eval quote  }.\n\n    Arguments quote _ {Quote}.\n    Arguments eval_quote _ {Quote}.\n\n    Section instances.\n\n      Context n m `{Quote n} `{Quote m}.\n\n      Global Program Instance: Quote 0 := { quote := Zero }.\n      Global Program Instance: Quote 1 := { quote := One }.\n\n      Global Instance: Quote (n + m).\n      Proof.\n      refine {| quote := Plus (quote n) (quote m) |}.\n      simpl. do 2 rewrite <- eval_quote. reflexivity.\n      Qed.\n\n      Global Instance: Quote (n * m).\n      Proof.\n      refine {| quote := Mult (quote n) (quote m) |}.\n      simpl. do 2 rewrite <- eval_quote. reflexivity.\n      Qed.\n\n    End instances.\n\n    Lemma do_quote {n m} `{Quote n} `{Quote m}: eval (quote n) = eval (quote m) → n = m.\n    Proof. intros. rewrite (eval_quote n), (eval_quote m). assumption. Qed.\n\n    Lemma example: (1 + 0 + 1) * (1 + 1) = (1 + 1) + (1 + 1).\n     apply do_quote.\n    Admitted.\n  End approach_B.\nEnd simple.\n\n(* So far so good, but the variable-less scenario isn't really interesting. We now rework approach B\n to include quotation of holes/variables, including recognition of syntactically identical ones. *)\n\nModule with_vars.\n(* Some random utilities: *)\n\nLemma sum_assoc {A B C}: (A+B)+C → A+(B+C). intuition. Defined.\nLemma bla {A B C}: (A+B) → A+(B+C). intuition. Defined.\nLemma monkey {A B}: False + A → A + B. intuition. Defined.\n\nSection obvious.\n  Class Obvious (T: Type) := obvious: T.\n\n  Context (A B C: Type).\n\n  Global Instance: Obvious (A → A) := id.\n  Global Instance: Obvious (False → A) := False_rect _.\n  Global Instance: Obvious (A → A + B) := inl.\n  Global Instance: Obvious (A → B + A) := inr.\n  Global Instance obvious_sum_src  `{Obvious (A → C)} `{Obvious (B → C)}: Obvious (A+B → C). repeat intro. intuition. Defined.\n  Global Instance obvious_sum_dst_l `{Obvious (A → B)}: Obvious (A → B+C). repeat intro. intuition. Defined.\n  Global Instance obvious_sum_dst_r `{Obvious (A → B)}: Obvious (A → C+B). repeat intro. intuition. Defined.\nEnd obvious.\n\n(* Again our example term language, this time without plus/one (they're boring), but with Var\n added: *)\n\nInductive Expr (V: Type) := Mult (a b: Expr V) | Zero | Var (v: V).\n\nArguments Var {V}.\nArguments Zero {V}.\nArguments Mult {V}.\n\n(*\nRequire Import monads canonical_names.\n\nInstance: MonadReturn Expr := fun _ => Var.\n\nInstance expr_bind: MonadBind Expr := fun A B =>\n  fix F (m: Expr A) (f: A → Expr B): Expr B :=\n    match m with\n    | Zero => Zero\n    | Mult x y => Mult (F x f) (F y f)\n    | Var v => f v\n    end.\n\nSection eqs.\n\n  Context `{e: Equiv A} `{Equivalence _ e}.\n\n  Global Instance expr_eq: Equiv (Expr A) :=\n    fix F (x y: Expr A) :=\n      match x, y with\n      | Var v, Var w => v = w\n      | Mult v w, Mult p q => F v p ∧ F w q\n      | Zero, Zero => True\n      | _, _ => False\n      end.\n\n  Instance: Reflexive expr_eq.\n  Proof. intro. induction x; simpl; intuition. Qed.\n\n  Instance: Symmetric expr_eq.\n  Proof. intro. induction x; destruct y; simpl in *; intuition. Qed.\n\n  Instance: Transitive expr_eq.\n  Admitted.\n\n  Global Instance expr_equivalence: Equivalence expr_eq.\n\nEnd eqs.\n\nInstance: ∀ `{Equiv A}, Proper ((=) ==> (=)) (ret Expr).\n repeat intro.\n assumption.\nQed.\n\nInstance bind_proper: ∀ `{Equiv A} `{Equiv B},\n Proper ((=) ==> pointwise_relation A (=) ==> (=)) (@expr_bind A B).\nProof.\n intros A H B H0 x y E.\n(*\n induction x.\n  destruct y; intuition.\n  intros f g E'.\n  simpl.\n  red.\n  simpl.\n  split.\n   red in E.\n   simpl in E.\n\n   apply IHx2.\n\n  simpl in *.\n\n unfold expr_bind.\n\n simpl.\n*)\nAdmitted.\n\n\nInstance: Monad Expr.\n  *)\n\n\n\n(* The expression type is parameterized over the set of variable indices. Hence, we diverge\n from Claudio, who uses nat indices for variables, thereby introducing bounds problems and\n dummy variables and other nastiness. *)\n\n(* An expression is only meaningful in the context of a variable assignment: *)\n\nDefinition Value := nat.\nDefinition Vars V := V → Value.\n\nFixpoint eval {V} (vs: Vars V) (e: Expr V): Value :=\n  match e with\n  | Zero => 0\n  | Mult a b => eval vs a * eval vs b\n  | Var v => vs v\n  end.\n\n#[global]\nInstance eval_proper V: Proper (pointwise_relation _ eq ==> eq ==> eq) (@eval V).\nProof.\n repeat intro. subst.\n induction y0; simpl.\n   congruence.\n  reflexivity.\n apply H.\nQed.\n\n(* Some simple combinators for variable packs: *)\n\nDefinition novars: Vars False := False_rect _.\nDefinition singlevar (x: Value): Vars unit := fun _ => x.\nDefinition merge {A B} (a: Vars A) (b: Vars B): Vars (A+B) :=\n  fun i => match i with inl j => a j | inr j => b j end.\n\n(* These last two combinators are the \"constructors\" of an implicitly defined subset of\n Gallina terms (representing Claudio's \"heaps\") for which we implement syntactic\n lookup with type classes: *)\n\nSection Lookup.\n  (* Given a heap and value, Lookup instances give the value's index in the heap: *)\n\n  Class Lookup {A} (x: Value) (f: Vars A) := { lookup: A; lookup_correct: f lookup = x }.\n\n  Global Arguments lookup {A} _ _ {Lookup}.\n\n  Context (x: Value) {A B} (va: Vars A) (vb: Vars B).\n\n  (* If the heap is a merge of two heaps and we can find the value's index in the left heap,\n   we can access it by indexing the merged heap: *)\n\n  Global Instance lookup_left `{!Lookup x va}: Lookup x (merge va vb).\n  Proof.\n  refine {| lookup := inl (lookup x va) |}.\n  apply lookup_correct.\n  Defined.\n\n  (* And vice-versa: *)\n\n  Global Instance lookup_right `{!Lookup x vb} : Lookup x (merge va vb).\n  Proof.\n  refine {| lookup := inr (lookup x vb) |}.\n  apply lookup_correct.\n  Defined.\n\n  (* If the heap is just a singlevar, we can easily index it. *)\n\n  Global Program Instance: Lookup x (singlevar x) := { lookup := tt }.\n\n  (* Note that we don't have any fallback/default instances at this point. We /will/ introduce\n  such an instance for our Quote class later on, which will add a new variable to the heap\n  if another Quote instance that relies on Lookup into the \"current\" heap fails. *)\nEnd Lookup.\n\n(* One useful operation we need before we get to Quote relates to variables and expression\n evaluation. As its name suggests, map_var maps an expression's variable indices. *)\n\nDefinition map_var {V W: Type} (f: V → W): Expr V → Expr W :=\n  fix F (e: Expr V): Expr W :=\n    match e with\n    | Mult a b => Mult (F a) (F b)\n    | Zero => Zero\n    | Var v => Var (f v)\n    end.\n\n(* An obvious identity is: *)\n\nLemma eval_map_var {V W} (f: V → W) v e:\n  eval v (map_var f e) = eval (v ∘ f) e.\nProof.\n induction e; simpl; try reflexivity.\n rewrite IHe1, IHe2.\n reflexivity.\nQed.\n\n(* Finally, Quote itself: *)\n\nSection Quote.\n  (* In Quote, the idea is that V, l, and n are all \"input\" variables, while V' and r are \"output\"\n  variables (in the sense that we will rely on unification to generate them. V and l represent\n  the \"current heap\", n represents the value we want to quote, and V' and r' represent the\n  heap of newly encountered variables during the quotation.\n    This explains the type of quote: it is an expression that refers either to variables from\n  the old heap, or to newly encountered variables.\n    eval_quote is the usual correctness property, which now merges the two heaps. *)\n\n  Class Quote {V} (l: Vars V) (n: Value) {V'} (r: Vars V') :=\n    { quote: Expr (V + V')\n    ; eval_quote: @eval (V+V') (merge l r) quote = n }.\n\n  Arguments quote {V l} _ {V' r Quote}.\n\n  (* Our first instance for Zero is easy. The \"novars\" in the result type reflects the fact that no new\n   variables are encountered. The correctness proof is easy enough for Program. *)\n\n  Global Program Instance quote_zero V (v: Vars V): Quote v 0 novars := { quote := Zero }.\n\n  (* The instance for multiplication is a bit more complex. The first line is just boring\n   variable declarations. The second line is important. \"Quote x y z\" must be read as\n   \"quoting y with existing heap x generates new heap z\", so the second line\n   basically just shuffles heaps around.\n     The third line has some ugly map_var's in it because the heap shuffling must be reflected\n   in the variable indices, but apart from that it's just constructing a Mult\n   term with quoted subterms. *)\n\n  Global Program Instance quote_mult V (v: Vars V) n V' (v': Vars V') m V'' (v'': Vars V'')\n    `{!Quote v n v'} `{!Quote (merge v v') m v''}: Quote v (n * m) (merge v' v'') :=\n      { quote := Mult (map_var bla (quote n)) (map_var sum_assoc (quote m)) }.\n\n  Next Obligation. Proof with auto.\n   destruct Quote0, Quote1.\n   subst. simpl.\n   do 2 rewrite eval_map_var.\n   f_equal; apply eval_proper; auto; intro; intuition.\n  Qed.\n\n  (* Now follows the instance where we recognize values that are already in the heap. This\n   is expressed by the Lookup requirement, which will only be fulfilled if the Lookup instances\n   defined above can find the value in the heap. The novars in the [Quote v x novars] result\n   reflects that this quotation does not generate new variables. *)\n\n  Global Program Instance quote_old_var V (v: Vars V) x {i: Lookup x v}:\n    Quote v x novars | 8 := { quote := Var (inl (lookup x v)) }.\n  Next Obligation. Proof. apply lookup_correct. Qed.\n\n  (* Finally, the instance for new variables. We give this lower priority so that it is only\n   used if Lookup fails. *)\n\n  Global Program Instance quote_new_var V (v: Vars V) x: Quote v x (singlevar x) | 9\n    := { quote := Var (inr tt) }.\nEnd Quote.\n\n(* Note: Explicitly using dynamically configured variable index sets instead of plain lists\n not only removes the need for an awkward dummy value to cope with out-of-bounds\n accesses, but also means that we can prove the correctness class fields in\n Lookup/Quote without having to take the potential for out-of-bounds indexing into\n account (which would be a nightmare). *)\n\n(* When quoting something from scratch we will want to start with an empty heap.\n To avoid having to mention this, we define quote' and eval_quote': *)\n\nDefinition quote': ∀ x {V'} {v: Vars V'} {d: Quote novars x v}, Expr _ := @quote _ _.\n\nDefinition eval_quote': ∀ x {V'} {v: Vars V'} {d: Quote novars x v},\n  eval (merge novars v) quote = x\n    := @eval_quote _ _ .\n\nArguments quote' _ {V' v d}.\nArguments eval_quote' _ {V' v d}.\n\n(* Time for some tests! *)\n\nGoal ∀ x y (P: Value → Prop), P ((x * y) * (x * 0)).\n  intros.\n  rewrite <- (eval_quote' _).\n    (* turns the goal into\n         P (eval some_variable_pack_composed_from_combinators quote)\n    *)\n  simpl quote.\nAdmitted.\n\n(* We can also inspect quotations more directly: *)\n\nSection inspect.\n  Variables x y: Value.\n  (* Eval compute in quote' ((x * y) * (x * 0)). *)\n    (* = Mult (Mult (Var (inr (inl (inl ())))) (Var (inr (inl (inr ())))))\n           (Mult (Var (inr (inl (inl ())))) Zero)\n       : Expr (False + (() + () + (False + False))) *)\n\n  (* The second occurrence of (Var (inr (inl (inl ())))) means\n   the quoting has successfully noticed that it's the same\n   expression. *)\n\n  (* The two units in the generated variable index type reflect the\n   fact that the expression contains two variables. *)\n\n  (* I think adding some additional Quote instances might let us\n   get rid of the False's, but at the moment I see little reason to. *)\nEnd inspect.\n\n(* If we want to quote an equation between two expressions we should make\n sure that the both sides refer to the same variable pack, and for that we write a\n little utility function. It does the same kind of shuffling that the mult\n Quote instance did. *)\n\nLemma quote_equality {V} {v: Vars V} {V'} {v': Vars V'} (l r: Value) `{!Quote novars l v} `{!Quote v r v'}:\n  let heap := (merge v v') in\n  eval heap (map_var monkey quote) = eval heap quote → l = r.\nProof with intuition.\n destruct Quote0 as [lq []].\n destruct Quote1 as [rq []].\n intros heap H.\n subst heap. simpl in H.\n rewrite <- H, eval_map_var.\n apply eval_proper... intro...\nQed.\n\nGoal ∀ x y, x * y = y * x.\n intros.\n apply (quote_equality _ _).\n simpl quote.\n unfold map_var, monkey, sum_rect.\nAdmitted.\n\nEnd with_vars.\n", "meta": {"author": "coq-community", "repo": "math-classes", "sha": "c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc", "save_path": "github-repos/coq/coq-community-math-classes", "path": "github-repos/coq/coq-community-math-classes/math-classes-c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc/quote/classquote.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7257967778424914}}
{"text": "Set Implicit Arguments. \n\n\nPrint nat. (* Inductive nat : Set :=  O : nat | S : nat -> nat *)\nCheck nat_ind.\n(*\nforall P : nat -> Prop,\n       P 0 -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n\n*)\n\nPrint nat_ind.\n(*\nnat_ind = \nfun P : nat -> Prop => nat_rect P\n     : forall P : nat -> Prop,\n              P 0 -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n\n*)\n\nPrint nat_rec.\n(*\nnat_rec = \nfun P : nat -> Set => nat_rect P\n     : forall P : nat -> Set,\n              P 0 -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n\n*)\n\n\nPrint nat_rect.\n(*\nfun (P : nat -> Type) (f : P 0) (f0 : forall n : nat, P n -> P (S n)) =>\nfix F (n : nat) : P n :=\n  match n as n0 return (P n0) with\n    | 0 => f\n    | S n0 => f0 n0 (F n0)\n  end\n  : forall P : nat -> Type,\n    P 0 -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n\n*)\n\nCheck plus_O_n. (* forall n : nat, 0 + n = n *)\nCheck plus_Sn_m. (* forall n m : nat, S n + m = S (n + m) *)\n\nTheorem plus_assoc: forall x y z:nat,\n  (x+y)+z = x+(y+z).\nProof.\n  intros x y z. elim x. rewrite plus_O_n. rewrite plus_O_n. reflexivity.\n  intros x' IH. rewrite plus_Sn_m. rewrite plus_Sn_m. rewrite plus_Sn_m.\n  rewrite IH. reflexivity.\nQed.\n\n(* defining (_ * 2) by recursion *)\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n  | 0   => 0\n  | S p => S (S (mult2 p))\n  end.\n\nPrint plus.\n\nFixpoint mult3 (n:nat) :nat :=\n  match n with\n  | 0   => 0\n  | S p => S (S (S (mult3 p)))\n  end.\n(*\nplus = \nfix plus (n m : nat) {struct n} : nat :=\n  match n with\n    | 0 => m\n    | S p => S (plus p m)\n  end\n: nat -> nat -> nat\n*)\n\nDefinition less_than_three (n:nat) : bool :=\n  match n with \n  | 0         => true\n  | S 0       => true\n  | S (S 0)   => true \n  | other     => false\n  end.\n\nEval compute in (less_than_three 0).\nEval compute in (less_than_three 1).\nEval compute in (less_than_three 2).\nEval compute in (less_than_three 3).\nEval compute in (less_than_three 4).\n\nFixpoint plus2 (n m : nat) : nat :=\n  match m with \n    | 0   => n\n    | S p => S (plus2 n p)\n  end.\nCheck plus_n_O.\nCheck plus_n_Sm. (* forall n m : nat, S (n + m) = n + S m *)\n\nTheorem same_plus: forall n m : nat, plus2 n m = n + m.\nProof.\n  intros n m. elim m. simpl. apply plus_n_O. clear m. intros m H. simpl.\n  rewrite <- plus_n_Sm. rewrite H. reflexivity.\nQed.\n\nFixpoint sum_f_acc (n:nat)(f: nat->nat)(acc: nat) :nat :=\n  match n with\n    | 0     => acc\n    | S p   => sum_f_acc p f (acc + (f p))\n  end.\n\nDefinition sum_f (n:nat)(f:nat->nat) : nat := sum_f_acc n f 0.\n\nEval compute in (sum_f 5 (fun n => (S n)*(S n))).\n\n\nFixpoint iterate (A:Set)(f:A->A)(n:nat)(x:A){struct n} : A :=\n  match n with\n    | 0   => x\n    | S p => f (iterate f p x)\n  end.\n\nFixpoint two_power (n:nat) : nat :=\n  match n with\n    | 0   => 1\n    | S p => 2 * two_power p\n  end.\n\nEval compute in two_power 10.\n\nCheck plus_n_Sm.\n\nLemma mult2_n_plus_n : forall (n:nat), mult2 n = n + n.\nProof.\n  intro n. elim n. simpl. reflexivity. clear n. intros n IH.\n  simpl. rewrite IH. simpl. cut (S (n+n) = n + S n). intro H. \n  rewrite H. reflexivity. simpl. apply plus_n_Sm.\nQed.\n\nFixpoint sum_n (n:nat) : nat :=\n  match n with\n    | 0       => 0\n    | S p     => S p + sum_n p\n  end.\n\nLemma plus_comm: forall (n m:nat), n + m = m + n.\nProof.\n  intros n m. elim n. simpl. auto. clear n. intros n IH.\n  simpl. rewrite IH. simpl. apply plus_n_Sm.\nQed.\n\nLemma sum_n_form : forall (n:nat), 2*(sum_n n) = n*(n + 1).\nProof.\n  intro n. elim n. simpl. reflexivity. clear n. intros n IH.\n  simpl. cut (n + sum_n n + S (n + sum_n n + 0) =  n + 1 + n * S (n + 1)).\n  intro H. rewrite H. reflexivity. \n  cut(n + sum_n n + S (n + sum_n n + 0) = n + (sum_n n + S (n + sum_n n + 0))). \n  cut(n + 1 + n * S (n + 1) = n + (1 + n * S (n + 1))). intros H0 H1.\n  rewrite H0, H1. cut (sum_n n + S (n + sum_n n + 0) = 1 + n * S (n + 1)).\n  intro H2. rewrite H2. reflexivity. cut (S (n + sum_n n + 0) = sum_n n + n + 1).\n  intro H3. rewrite H3. cut( sum_n n + (sum_n n + n + 1) = sum_n n + sum_n n + S n).\n  intro H2. rewrite H2. cut (sum_n n + sum_n n = 2*sum_n n). intro H4. rewrite H4.\n  rewrite IH. simpl. cut ( n * (n + 1) + S n = S  (n*(n+1) + n)). intro H5. rewrite H5.\n  cut(n * (n + 1) + n = n * S (n + 1)). intro H6. rewrite H6. reflexivity.\n  simpl. cut(forall (a b:nat), a*b + a = a*(S b)). intro H6. apply H6. \n  intros a b. generalize a. elim b. auto. intro c. intro H7. auto.\n  cut (S (n * (n + 1) + n) = n * (n + 1) + S n). intro H8. rewrite H8.\n  reflexivity. apply plus_n_Sm. simpl. auto. cut (n + 1 = S n).\n  intro H9. cut(sum_n n + n + 1 = sum_n n + (n + 1)). intro H10. rewrite H10.\n  rewrite H9. rewrite plus_assoc. reflexivity. apply plus_assoc. simpl.\n  cut(S n = n + 1). intro H11. rewrite H11. reflexivity. simpl.\n  elim n. simpl. reflexivity. intro m. intro H12. simpl. rewrite H12.\n  reflexivity. cut(forall n:nat, S n = n + 1). intro H13. rewrite H13.\n  cut (n + sum_n n = sum_n n + n). intro H14. rewrite H14.\n  cut( sum_n n + n + 0 = sum_n n + n). intro H15. rewrite H15. reflexivity.\n  rewrite <- plus_n_O. reflexivity. apply plus_comm. intro m. elim m. simpl.\n  reflexivity. clear m. intros m IH'. simpl. rewrite IH'. reflexivity.\n  apply plus_assoc. apply plus_assoc.\n  (* this was a complete nightmare. Obviously need automattion and use ring tactic or other *)\nQed.\n\nRequire Import Arith.\n\nLemma sum_n_n : forall (n:nat), n <= sum_n n.\nProof.\n  intro n. elim n. simpl. apply le_n. clear n. intros n IH.\n  simpl. apply le_n_S. apply le_plus_l.\nQed.\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/recursive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7257967674763072}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (x : natural) : natural :=\n  mult (Succ x) (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj142_coqofml_9cCBkV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7257365041893202}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (x : natural) : natural :=\n  mult (Succ x) (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj153_coqofml_hcyfdA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7257365011865472}}
{"text": "(** * IndProp: Индуктивно Определенные Пропозиции *)\n\nRequire Export Logic.\n\n(* ################################################################# *)\n(** * Индуктивно Определенные Пропозиции *)\n\n(** В главе [Логика] мы взглянули на несколько способов записывания\n    пропозиций, включая конъюнкцию, дизнъюнкцию и кванторы.\n    В данной главе, мы привнесем новый инстрмент: _индуктивные\n    определения_.\n\n    Вспомните что мы видели два способа утверждать что число [n]\n    четно: мы говорим (1) [evenb n = true], или (2) [exists k, n =\n    double k].  В то же время, другая возможность выразить то что\n    [n] четно это способ установить его четность исходя из\n    следующих правил:\n\n       - Правило [ev_0]: Число [0] четно.\n       - Правило [ev_SS]: Если [n] четно, тогдаn [S (S n)] также четно.\n\n    Чтобы проиллюстрировать как данное новое определение четности\n    работает, давайте воспользуемся его правилами, чтобы показать\n    что [4] четно. По правилу [ev_SS], достаточно показать, что \n    четно [2]. Это, в свою очередь, опять гарантировано правилом\n    [ev_SS], если мы можем показать четность [0]. Но данный последний\n    факт напрямую следует из правила [ev_0]. *)\n\n(** Мы увидем много определений наподобие предыдущего в течении\n    данного курса. Для целей неформального обсуждения, полезно\n    иметь легковесную нотацию, которая делает легким их запись\n    и чтение.  _Правила вывода_ одна такая нотация: *)\n(**\n\n                              ------------                        (ev_0)\n                                 ev 0\n\n                                  ev n\n                             --------------                      (ev_SS)\n                              ev (S (S n))\n*)\n\n(** Каждое текстовое правило сверху переформатировано здесь в\n    правило вывода; предполагаемое прочтение, если _предпосылки_\n    сверху линии справедливы, то _заключения_ под линией\n    следуют. Например, правило [ev_SS] говорит что, если [n]\n    удовлетворяет [ev], тогда [S (S n)] также. Если правило не\n    имеет предпоссылок над линией, то утверждение справедливо\n    без предусловий.\n\n    Мы можем представить доказательство используя данные правила\n    комбинируя применения правил в _дерево доказательств_. Вот как\n    мы може записать доказательство того что [4] четно: *)\n(**\n\n                ------  (ev_0)\n                 ev 0\n                ------ (ev_SS)\n                 ev 2\n                ------ (ev_SS)\n                 ev 4\n*)\n\n(** Почему мы называем это \"деревом\" (вместо \"стека\", например)?\n    Потому что, в общем случае, оравила вывода могут иметь много предпосылок.\n    Мы увидем примеры этого в дальнейшем. *)\n\n(** Объединяя все это вместе, мы можем перевести определение четности\n    в формальное определение Coq используя декларацию [Inductive],\n    в которой каждый конструктор соответствует правилу вывода: *)\n\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\n(** Данное определение отличается в одном важном смысле от предыдущих\n    использований [Inductive]: его результат не есть [Type], но\n    функция из [nat] в [Prop] -- т.е., свойство чисел. Заметьте,\n    что мы уже видели другие индуктивные определения, такие как\n    [list], чей тип есть [Type ->Type]. Что нового здесь, так это то, что\n    так как  аргумент [nat] для [ev] появляется _неназваным_, в _правой_\n    части от двоеточия ему позволительно принимать разные значения\n    в типах разных конструкторов: [0] в типе [ev_0] и [S (S n)] в типе [ev_SS].\n\n    В отличие, определение [list] называет параметр [X] \n    _глобально_, с _левок_ части двоеточия, заставляя, как результат,\n    [nil] и [cons] быть теми же ([list X]).  Если бы мы попробовали бы\n    перенести [nat] на лево в определении [ev], мы бы увидели бы ошибку: *)\n\nFail Inductive wrong_ev (n : nat) : Prop :=\n| wrong_ev_0 : wrong_ev 0\n| wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).\n(* ===> Error: A parameter of an inductive type n is not\n        allowed to be used as a bound variable in the type\n        of its constructor. *)\n\n(** (\"Parameter\" здесь есть жаргонизм Coq для аргумента слева от двоеточия\n    в определнии [Inductive] ; \"индекс\" используется для отмечания аргументов\n    из правой части двоеточия.) *)\n\n(** Мы можем думать об определении [ev] как об определении свойства a Coq\n    [ev : nat -> Prop], вместе с теоремами [ev_0 : ev 0] и\n    [ev_SS : forall n, ev n -> ev (S (S n))].  Такие \"теоремы конструкторы\"\n    имеют тот же статус, что и доказанные теоремы. В частности,\n    мы можем использовать тактику Coq [apply] вместе именами правил для\n    доказательства [ev] в случае заданных чисел... *)\n\nTheorem ev_4 : ev 4.\nProof. apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** ... или мы можем использовать синтакс применения функции: *)\n\nTheorem ev_4' : ev 4.\nProof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.\n\n(** Мы также можем доказать теоремы что имеют гипотезы включающие [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(** Более обще, мы можем показать что любое число умноженное на 2 четно: *)\n\n(** **** Упражнение: 1 звездочка (ev_double)  *)\nTheorem ev_double : forall n,\n  ev (double n).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.   \n(** [] *)\n\n(* ################################################################# *)\n(** * Используем Свидетельства в Доказательствах *)\n\n(** Кроме _конструирования_ свидетельств того что числа четные, мы также\n    можем _рассуждать о_ таких свидетельствах.\n\n    Введение [ev] с декларацией [Inductive] говорит Coq не только\n    что конструкторы [ev_0] и [ev_SS] есть валидные способы построить\n    свидетельство что некоторое число четно, но также что эти два\n    конструктора являются _единственными_ путями построить такое\n    свидетельство (в смысле [ev]). *)\n\n(** Другими словами, если кто то предоставляет вам свидетельство \n    [E] для утверждения [ev n], тогда мы знаем что [E] должно иметь одну\n    из двух форм:\n\n      - [E] есть [ev_0] (и [n] есть [O]), или\n      - [E] есть [ev_SS n' E'] (и [n] есть [S (S n')], где [E'] есть\n        свидетельство для [ev n']). *)\n\n(** Это предполагает что существует возможность для анализа\n    гипотезы в формеэ [ev n] примерно также как мы делали в \n    слуаче индуктивно определенных структур данных; в частности,\n    должно быть возможным аргументировать по _индукции_ и \n    _разбором случаев_ на данном свидетельстве. Давайте рассмотрим\n    несколько примеров, чтобы увидеть что это значит на практике. *)\n\n(* ================================================================= *)\n(** ** Инверсия на Свидетельстве *)\n\n(** Вычитание двойки из четного числа производит четное число.\n    Мы можем легко этп доказать с помощью техник, что мы уже видели,\n    если конечно сформулируем данный факт в нужной форме. Если\n    мы сформулируем его в терминах [evenb], например, мы сможем\n    использовать простой анализ случаев на [n]: *)\n\nTheorem evenb_minus2: forall n,\n  evenb n = true -> evenb (pred (pred n)) = true.\nProof.\n  intros [ | [ | n' ] ].\n  - (* n = 0 *) reflexivity.\n  - (* n = 1; contradiction *) intros H. inversion H.\n  - (* n = n' + 2 *) simpl. intros H. apply H.\nQed.\n\n(** Мы може сформулировать данное заявление в терминах [ev], но мы быстро\n    застреваем: Так как [ev] определено индуктивно -- ане как функция\n    -- Coq не знает как упрощать цель включающую [ev n] после разбора случаев \n    на [n]. Как следствие, эта стратегия доказательства не срабатывает: *)\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros [ | [ | n' ] ].\n  - (* n = 0 *) simpl. intros _. apply ev_0.\n  - (* n = 1; и тут мы застреваем! *) simpl.\nAbort.\n\n(** Решением будет применить разбор случаев на свидетельстве того что [ev\n    n] _напрямую_. По определению [ev], есь два случая на рассмотрение:\n\n    - Если свидетельство есть в форме [ev_0], мы знаем что [n = 0].\n      Таким образом, достаточно показать что [ev (pred (pred 0))] справедливо.\n      По определению [pred], это эквивалентно тому что\n      [ev 0] справедливо, что следует напрямую из [ev_0].\n\n    - Иначе, свидетельство должно иметь форму [ev_SS n' E'], где\n      [n = S (S n')] и [E'] есть свидетельство для [ev n']. Тогда мы\n      должны показать что [ev (pred (pred (S (S n'))))] справедливо,\n      что, после некоторого упрощения, следуе напрямую из [E']. *)\n\n(** Мы можем вызвать такой вид аргумента из Coq используя тактику [inversion].\n    Кроме того что она позволяет нам рассуждать о равенствах включающих\n    конструкторы, [inversion] предоставляет принцип разбора случаев для\n    индуктивно определенных пропозиций. Когда использована таким образом,\n    ее синтаксис похож на [destruct]: мы передаем список идентификаторов\n    разделеных символами [|] для называния их аргументов в случае каждого\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  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\n(** Заметьте чт0, в данном конкретном случае, также возможно заменить\n    [inversion] на [destruct]: *)\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0 *) simpl. apply ev_0.\n  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.\n\n(** Разнца в этих двух формах заключается в том, том [inversion] более\n    удобна когда применена на гипотезе состоящией из индуктивного\n    свойства примененного к сложному выраженип (в отличии от одной\n    переменной). Бот конкретный пример. Предположим, что мы хотим\n    доказать следующую вариацию [ev_minus2]: *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\n\n(** Интуитивно, мы знаем что свидетельство для гипотезы не может\n    состоять из одного лишь конструктора [ev_0], так как [O] и [S]\n    разные конструкторы типа [nat]; таким образом, [ev_SS] единственый\n    случай что применим. К несчастью, [destruct] неодстаточно умен чтобы\n    это понять, и всеравно генерирует две подцели. Даже хуже,\n    делая это, она оставляет финальную цель неизменной, не предоставляя\n    никакой полезной информации для завершения доказательства.  *)\n\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  - (* E = ev_0. *)\n    (* Мы должны доказать что [n] четное без каких либо предположений! *)\nAbort.\n\n(** Что же случилось конкретно?  Вызов [destruct] имеет эффект замены\n    всех появлений аргумента свойства значениями которые соответствуют\n    своему конструктору. Этого недостаточно для случая\n    [ev_minus2'] так как аргумент [n], нарямую указан в \n    финальной цели. Тем не менее, это не помогает в случае\n    [evSS_ev] так как терм который заменяется на ([S (S n)]) \n    нигде не упомянут. *)\n\n(** Тактика [inversion], с другой стороны, может задетектировать (1) \n    что первый случай не применим, и (2) что [n'] который появляется\n    в случае [ev_SS] должен быть тем же что и [n]. Это позволяет нам\n    завершить доказательство: *)\n\nTheorem evSS_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E as [| n' E'].\n  (* Мы теперь в случае [E = ev_SS n' E'] теперь. *)\n  apply E'.\nQed.\n\n(** Используя [inversion], мы можем применить принцип взрыва\n    к \"очевидно противоречивым\" гипотезам включающим индуктивные\n    свойства. Например: *)\n\nTheorem one_not_even : ~ ev 1.\nProof.\n  intros H. inversion H. Qed.\n\n(** **** Упражнение: 1 звездочка (inversion_practice)  *)\n(** Докажите следующие теоремы изпользуя [inversion]. *)\n\nTheorem SSSSev__even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted. \n\nTheorem even5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** Способ которым мы использовали [inversion] здесь может казаться\n    слегка мистическим поначалу. До сих пор, мы использовали [inversion]\n    только на пропозициях равенства, для утилизации инъективности конструкторов\n    или дискриминации между конструкторами. Но мы видим здесь что\n    [inversion] может быть также применена к анализу свидетельств для\n    индуктивно определенных пропозиций.\n\n    Вот как [inversion] работает в целом.  Предположим имя [I]\n    относится к предположению [P] в данном контексте, где [P] определена\n    с помощью декларации [Inductive].  Тогда, для каждого из конструкторов\n    [P], [inversion I] генерирует подцель, в которо [I] будет заменена\n    на точные, специальные условия при которых данный конструктор мог бы\n    использован для доказательства [P]. Некоторые из этих подцелей\n    будут противоречивыми; [inversion] выкидывает такие из рассмотрения.\n    Те что остаются представляют случаи которые должны быть доказаны\n    для установления оригинальной цели.  Для них, [inversion]\n    добавляет все уравнения в контекст доказательства, которые должны\n    иметь место для арументов заданных  [P] (т.е., [S (S n') = n] \n    в доказательстве [evSS_ev]). *)\n\n(* ================================================================= *)\n(** ** Индукция на Свидетельствах *)\n\n(** Упражнение [ev_double] сверху показывает что наше новое понятие\n    четности следует из двух предыдущих (так как, из\n    [even_bool_prop], мы уже знаем что те эквивалентны друг другу).\n    Чтобы показать что все три совпадают, нам нужна только следующая\n    лемма: *)\n\nLemma ev_even : forall n,\n  ev n -> exists k, n = double k.\nProof.\n\n(** Мы могли бы использовать разбор случаев или индукцию на [n].\n    Но так как [ev] упомянуто в предпосылке, данная стратегия вероятно\n    приведет к тупику, как и в предыдущей секции. Таким образом, кажется\n    что стоит попробовать инверсию на свидетельстве для [ev].  Действительно,\n    первый случая может быть решен тривиально. *)\n\n  intros n E. inversion E as [| n' E'].\n  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E' *) simpl.\n\n(** К несчастью, второй случай сложнее. Нам надо показать, что [exists\n    k, S (S n') = double k], но единственное имеющее предположение это\n    [E'], которое утверждает что [ev n'] имеет место. Так как это \n    не помогает напрямую, кажется что мы застряли и разбор случаев\n    на [E] это потеря времени.\n\n    Если мы посмотрим повнимательнее на нашу вторую цель, тем не менее,\n    мы увидем нечто интересное: производим разбор случаев на [E], \n    тот что включает _различные_ части свидетельства для: [E'].\n    Более формально, мы можем закончить наше доказательство показав\n\n        exists k', n' = double k',\n\n    что тоже самое, что и оригинальное утверждение, но с [n'] вместо\n    [n].  Десйтвительно, не трудно убедить Coq что этого\n    промежуточного результата достаточно. *)\n\n    assert (I : (exists k', n' = double k') ->\n                (exists k, S (S n') = double k)).\n    { intros [k' Hk']. rewrite Hk'. exists (S k').\n      reflexivity. }\n    apply I. (* редуцируем изначальную цель к новой *)\n\n(** Если вам это кажется знакомым, то это не совпадение: Мы уже встречали\n    похожие проблемы в главе [Индукция], когда пытались использовать анализ\n    слуачев для доказательства результатов требующих индукции. И снова\n    решение здесь... индукция!\n\n    Поведение [induction] на свидетельстве такое же как ее поведение\n    на данных: Она заставляет Coq генерировать одну подцель для каждого\n    конструктора что может быть использован для построения свидетельства,\n    в тоже время предоставляя индукционные гипотезы для рекурсивных\n    случаев.\n\n    Давайте попробуем снова с нашей текущей леммой: *)\n\nAbort.\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  - (* E = ev_0 *)\n    exists 0. reflexivity.\n  - (* E = ev_SS n' E'\n       с IH : exists k', n' = double k' *)\n    destruct IH as [k' Hk'].\n    rewrite Hk'. exists (S k'). reflexivity.\nQed.\n\n(** Здесь мы видим, что Coq произвел [IH] соответствующее\n    [E'], единственному реккурентному случаю [ev] в своем определении.\n    Так как [E'] упоминает [n'], индукционная гипотеза говорит о [n'],\n    а не о [n] или любом другом числе. *)\n\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. apply ev_double.\nQed.\n\n(** Как мы увидем в будущих главах, индукция на свидетельствах\n    частая техника при изучении семантики языков програмирования,\n    в которых многие интересные свойства определены индуктивно. \n    Следующее упражнение предоставлет простые примеры данной\n    техники, для практики. *)\n\n(** **** Упражнение: 2 звездочки (ev_sum)  *)\nTheorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 4 звездочки, продвинутое (ev_alternate)  *)\n(** В целомl, могут существовать многочисленные способы определения\n    свойства индуктивно. Например, вот (слегка замороченное)\n    альтернативное определение для [ev]: *)\n\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_2 : ev' 2\n| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).\n\n(** Докажите что оно логически эквивалентно старому. *)\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 3 звездочки, продвинутое, рекомендованное (ev_ev__ev)  *)\n(** Нахождение правильного объекта для индукции слегка\n    непреосто здесь: *)\n\nTheorem ev_ev__ev : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 3 звездочки, дополнительное (ev_plus_plus)  *)\n(** Данное упражнение просто требует применения существующих лемм.\n    Никакой индукции или разбора случаев не требуется, хотя часть\n    переписывания будет скучным. *)\n\nTheorem ev_plus_plus : forall n m p,\n  ev (n+m) -> ev (n+p) -> ev (m+p).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Индуктивные Отношения *)\n\n(** Пропозиция параметризованная числом (как [ev])\n    может быть рассмотрена как _свойство_ -- т.е., она определяет\n    подмножество [nat], а именно тех чисел для которых пропозиция\n    доказуема. Таким же путем, двух аргументная пропозиция может быть\n    рассмотрена как _отношение_ -- т.е., она определяет множество пат\n    для которых пропозиция доказуема. *)\n\nModule LeModule.\n\n(** Один полезный пример это отношение \"меньше либо равно чем\"\n    на числах. *)\n\n(** Следующее определение должно быть интуитивно понятно. Оно говорит,\n    что есть два способа предоставить свидетельство того, чтп одно\n    число меньше либо равно другому: или убедиться что числа одинаковы,\n    или предоставить свидетельство того, что первое меньше либо равно\n    предшественника второго. *)\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(** Доказательства фактов о [<=] использующих конструкторы [le_n] и\n    [le_S] следуют тем же шаблонам, что и доказательства о\n    свойствах, вроде [ev]. Мы можем применить [apply] конструкторы\n    для доказательства целей [<=] (т.е., показать [3<=3] или [3<=6]),\n    и можем использовать тактики вроде [inversion] для извлечения информации\n    [<=] гипотез в контексте (т.е., доказать что [(2 <= 1) ->\n    2+2=5].) *)\n\n(** Вот несколько проверок на здравый смысл для нашего определения. \n    (Обратите внимание на то что, хотя они являются просто версией\n    простый \"юнит тестов\" наподобие тех что мы использовали для\n    тестирования функций в первых лекциях, мы должны строить\n    их доказательство явно -- [simpl] и [reflexivity] не делают за нас\n    работу, так как доказательства не являются просто материалом\n    с упрощающими вычислениями.) *)\n\nTheorem test_le1 :\n  3 <= 3.\nProof.\n  (* ПРОРАБОТАНО В КЛАССЕ *)\n  apply le_n.  Qed.\n\nTheorem test_le2 :\n  3 <= 6.\nProof.\n  (* ПРОРАБОТАНО В КЛАССЕ *)\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  (* ПРОРАБОТАНО В КЛАССЕ *)\n  intros H. inversion H. inversion H2.  Qed.\n\n(** Отношение \"строго меньше чем\" [n < m] может теперь быть определено\n    в терминах [le]. *)\n\nEnd LeModule.\n\nDefinition lt (n m:nat) := le (S n) m.\n\nNotation \"m < n\" := (lt m n).\n\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(** **** Упражнение: 2 звездочки, рекомендованное (total_relation)  *)\n(** Определите индуктивное бинарное отношение [total_relation] которое\n    справедливо между любыми парами натуральных чисел. *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 2 звездочки (empty_relation)  *)\n(** Определите индуктивное бинарное отношение [empty_relation] (на числах)\n    которое никогда не справедливо. *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 3 звездочки, дополнительное (le_exercises)  *)\n(** Вот набор фактов об отношениях [<=] и [<] которые нам понадобятся\n    в дальнейшем в этом курсе. Доказательства послужат хорошими\n    упражнениями для практики. *)\n\nLemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n unfold lt.\n (* ЗАПОЛНИТЕ ЗДЕСЬ *)\nAdmitted.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem leb_complete : forall n m,\n  leb n m = true -> n <= m.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\n\n(** Подсказка: Следующее проще всего будет доказать индукцией по [m]. *)\n\nTheorem leb_correct : forall n m,\n  n <= m ->\n  leb n m = true.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n  \n(** Подсказка: Данная теорема может быть легко доказана без использования [induction]. *)\n\nTheorem leb_true_trans : forall n m o,\n  leb n m = true -> leb m o = true -> leb n o = true.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\n(** **** Упражнение: 2 звездочки, дополнительное (leb_iff)  *)\nTheorem leb_iff : forall n m,\n  leb n m = true <-> n <= m.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\nModule R.\n\n(** **** Упражнение: 3 звездочки, рекомендованное (R_provability2)  *)\n(** Мы можем определить отношения с тремя аргументами, с четырьмя и т.д.,\n    точно также как мы это сделали для бинарных отношений. Например,\n    рассмотрим следующуее трех аргументное отношение на числах: *)\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      - [R 1 1 2]\n      - [R 2 2 6]\n\n    - Если мы опустим конструктор [c5] из определения [R],\n      изменится ли множество доказуемых пропозиций? Коротко (1\n      предложение) объясните ответ.\n\n    - Если мы отбросим конструктор [c4] из определения [R],\n      изменится ли множество доказуемых пропозиций? Коротко (1\n      предложение) объясните ответ.\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n[]\n*)\n\n(** **** Упражнение: 3 звездочки, дополнительное (R_fact)  *)\n(** Отношение [R] сверху на самом деле кодирует знакомую функцию.\n    Выясните что это за функциял затем сформулируйте и докажите\n    эквивалентность в Coq? *)\n\nDefinition fR : nat -> nat -> nat \n  (* ЗАМЕНИТЕ ЭТУ СТРОКУ ЭТИМ   := _ваше определение_ . *) . Admitted.\n\nTheorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.\nProof.\n(* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\nEnd R.\n\n(** **** Упражнение: 4 звездочки, продвинутое (subsequence)  *)\n(** Список есть _подпоследовательность_ другого списка если все\n    элементы из первого появляются в том же порядке во втором,\n    возможно с некоторыми дополнительными элементами между.\n    Например,\n\n      [1;2;3]\n\n    есть подпоследовательность каждого из следующих списков\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    но _не_ является подпоследовательностью ни одного из этих списков\n\n      [1;2]\n      [1;3]\n      [5;6;2;1;7;3;8].\n\n    - Определите индуктивную пропозицию [subseq] на [list nat] так\n      чтобы она отражала то что мы понимаем под подпоследовательностью.\n      (Подсказка: Вам понадобятся три случая.)\n\n    - Докажите [subseq_refl] о том что подпоследовательность рефлексивна, т.е.,\n      любой список есть подпоследовательность для себя.\n\n    - Докажите [subseq_app] для любых списков [l1], [l2], и [l3],\n      если [l1] есть подпоследовательность [l2], тогда [l1] также подпоследовательность\n      для [l2 ++ l3].\n\n    - (Дополнительно, сложнее) Докажите [subseq_trans] о том что подпоследовательность\n      транзитивна -- т.е., если [l1] есть подпоследовательность для [l2] и [l2]\n      подпоследовательность для [l3], то [l1] подпоследовательность для [l3].\n      Подсказка: выберайте свою индукцию осторожно! *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 2 звездочки, дополнительное (R_provability)  *)\n(** Предположим мы зададим Coq следующее определение:\n\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\n    Какая из следующих пропозиций доказуема?\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(** Свойство [ev] предоставляет простой пример иллюстрирующий индуктивные\n    определения и базовые техники для рассуждения о них, но он не\n    сильно вдохновляющий -- в конце концов, он эквивалентен\n    двум неиндуктивным примерам четности которые мы уже видели\n    и будто не предоставляет какое либо конкретное преимущество\n    по сравнениями с предыдущими определениями.Чтобы лучше представить\n    мощь индуктивных определений, мы теперь покажем как использовать\n    их для моделирования классической концепции в компьютерной\n    науке: _регулярных выражений_. \n\n    Регулярные выражения представляют из себя простой язык для описания\n    строк, определнных как элементы следующего индуктивного типа.  (Имена\n    конструкторов станут понятнее как только мы объясним их смысл внизу.)  *)\n\nInductive reg_exp (T : Type) : Type :=\n| EmptySet : reg_exp T\n| EmptyStr : reg_exp T\n| Char : T -> reg_exp T\n| App : reg_exp T -> reg_exp T -> reg_exp T\n| Union : reg_exp T -> reg_exp T -> reg_exp T\n| Star : reg_exp T -> reg_exp T.\n\nArguments EmptySet {T}.\nArguments EmptyStr {T}.\nArguments Char {T} _.\nArguments App {T} _ _.\nArguments Union {T} _ _.\nArguments Star {T} _.\n\n(** Обратите внимание на то что это определение _полиморфно_:\n    Регулярные выражения в [reg_exp T] описывают строки с символами\n    взятыми и [T] -- т.е., списки элементов [T].  (Мы отходим слегка\n    от стандартной практики в том, что мы не требуем от типа [T] быть\n    конечным. Это приводит слегка другой теории регулярных выражений,\n    но разница не важна для наших целей.)\n\n    Мы связываем регулярные выражения и строки через следующие правила,\n    которые определяют когда регулярное выражение _соответствует_ \n    некоторой строке:\n\n    - Выражение [EmptySet] не соответствует никакой строке.\n\n    - Выражение [EmptyStr] соотвествует пустой строке [[]].\n\n    - Выражение [Char x] соответствует односимвольной строке [[x]].\n\n    - Если [re1] соответствует [s1], и [re2] соответствует [s2], тогда [App re1\n      re2] соответствует [s1 ++ s2].\n\n    - Если хотя бы один из [re1] и  [re2] соответствует [s], тогда [Union re1\n      re2] соответствует [s].\n\n    - Наконец, если мы можем записать какую либо строку как \n      конкатенацию последовательности строк [s = s_1 ++ ... ++ s_k],\n      и выражение [re] соответствует каждой из строк [s_i], тогда\n      [Star re] соответствует [s].  (Как специальный случай, последовательность\n      строк может быть пустой, так что [Star re] всегда соответствует\n      пустой строке [[]] не важно какой [re].) *)\n\n(** Мы можем перевести данное неформальное определение в\n    [Inductive] следующим образом: *)\n\nInductive exp_match {T} : list T -> reg_exp T -> 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(** И снова, для читаемости, мы также покажем данное определение используя\n    нотацию правил вывода. В тоже время, давайте введем более читаемую\n    инфикс нотацию. *)\n\nNotation \"s =~ re\" := (exp_match s re) (at level 80).\n\n(**\n\n                          ----------------                    (MEmpty)\n                           [] =~ EmptyStr\n\n                          ---------------                      (MChar)\n                           [x] =~ Char x\n\n                       s1 =~ re1    s2 =~ re2\n                      -------------------------                 (MApp)\n                       s1 ++ s2 =~ App re1 re2\n\n                              s1 =~ re1\n                        ---------------------                (MUnionL)\n                         s1 =~ Union re1 re2\n\n                              s2 =~ re2\n                        ---------------------                (MUnionR)\n                         s2 =~ Union re1 re2\n\n                          ---------------                     (MStar0)\n                           [] =~ Star re\n\n                      s1 =~ re    s2 =~ Star re\n                     ---------------------------            (MStarApp)\n                        s1 ++ s2 =~ Star re\n*)\n\n(** Заметьте что эти правила не _совсем_ теже что и в неформальном\n    определении, что мы предоставили в начале секции. Во превых,\n    нам нет нужны явно включать правило утверждающее, что ни одна\n    строка не соответствует [EmptySet]; мы просто не добавляем правила\n    эффектом которого было бы соответствие какой либо строки\n    [EmptySet].  (Действительно, синтаксис индуктивных определений\n    не позволяет даже _позволить_ нам такого \"отрицательного правила.\")\n\n    Более того, неформальные правила для [Union] и [Star] выражены\n    двумя конструкторами каждое: [MUnionL] / [MUnionR], и [MStar0] /\n    [MStarApp].  Результат логически эквивалентен оригинальным\n    правилам, но более удобен для использования в Coq, так как \n    рекурсивные случаи [exp_match] заданы как прямые аргументы конструкторам,\n    делая легче индукцию на свидетельствах.\n    (Упражнения [exp_match_ex1] и [exp_match_ex2] внизу просят доказать\n    что конструкторы данные в индуктивном определении и те которые \n    бы появились при прямой трансляции неформальных правил действительно\n    эквивалентны.) *)\n\n(** Давайте проиллюстрируем эти правила на нескольких примерах. *)\n\nExample reg_exp_ex1 : [1] =~ Char 1.\nProof.\n  apply MChar.\nQed.\n\nExample reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).\nProof.\n  apply (MApp [1] _ [2]).\n  - apply MChar.\n  - apply MChar.\nQed.\n\n(** (Заметьте как последний пример применяет [MApp] к строкам [[1]]\n    и [[2]] напрямую. Так как цель упоминает [[1; 2]] вместо\n    [[1] ++ [2]], Coq не смог бы определить сам как разбить строку\n    сам по себе.)\n\n    Используя [inversion], мы можем также показать что определенные строки\n    _не_ соответствуют регулярным выражениям: *)\n\nExample reg_exp_ex3 : ~ ([1; 2] =~ Char 1).\nProof.\n  intros H. inversion H.\nQed.\n\n(** Мы можем записать вспомогательные функции для записи регулярных\n    выражений. Функция [reg_exp_of_list] конструирует регулярное выражение\n    которое точно соответствует списку которое она принимает в качестве\n    аргумента: *)\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.\nQed.\n\n(** Мы также можем доказать общие факты о [exp_match]. Например,\n    следующая лемма показывает что каждая строка [s] которая\n    соответствуер [re] также соответствует [Star re]. *)\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(** (Заметьте использование [app_nil_r] для смены цели теоремы на\n    точно ту форму, что ожидает [MStarApp].) *)\n\n(** **** Упражнение: 3 звездочки (exp_match_ex1)  *)\n(** Следующие леммы показывают что неформальные правила соответствия\n    данные вначале главы могут быть получены из формального\n    индуктивного определения. *)\n\nLemma empty_is_empty : forall T (s : list T),\n  ~ (s =~ EmptySet).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\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  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\n(** Следующая лемма сформулирована в терминах функции [fold] из главы\n    [Poly]: Если [ss : list (list T)] представлает последовательность строк\n    [s1, ..., sn], тогда [fold app ss []] результат их конкатенации. *)\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  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\n(** [] *)\n\n(** **** Упражнение: 4 звездочки (reg_exp_of_list)  *)\n(** Докажите что [reg_exp_of_list] удовлетворяет\n    следующей спецификации: *)\n\n\nLemma reg_exp_of_list_spec : forall T (s1 s2 : list T),\n  s1 =~ reg_exp_of_list s2 <-> s1 = s2.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** Так как определение [exp_match] имеет реккурсивную структуру,\n    мы можем ожидать что доказательства включающие\n    регулярные выражения будут часто требовать индукцию на\n    свидетельствах. Например, предположим мы захотели доказать\n    следующий интуитивный результат: Если регулярное выражение [re]\n    соответствуер некоторой строке [s], то все элементы [s] должны\n    появится где то в [re]. Чтобы сформулировать данную теорему\n    мы вначале определим функцию [re_chars] которая перечисляет\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\n(** Мы можем выразить нашу теорему следующим образом: *)\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 [\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  - (* MEmpty *)\n    apply Hin.\n  - (* MChar *)\n    apply Hin.\n  - simpl. 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\n(** Нечто интересное происходит в случае [MStarApp].  Мы получаем \n    _две_ индуктивные гипотезы: Одна которая применяется если [x]\n    появляется в [s1] (соответствующее [re]), и вторая применяемая когда [x]\n    появляется в [s2] (соответствующее [Star re]). Это хорошее иллюстрация\n    того, почему нам нужна индукция на свидетельстве для [exp_match],\n    вместо [re]: последнее предоставит лишь индукционную гипотезу\n    для строк, которые соответствуют [re], что не позволит нам рассуждать\n    о случае [In x s2]. *)\n\n  - (* MStarApp *)\n    simpl. 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(** **** Упражнение: 4 звездочки (re_not_empty)  *)\n(** Запишите реккурсивную функцию [re_not_empty] которая тестирует\n    соответствует ли регулярному выражению какая либо строка.\n    Докажите что ваша функция корректна. *)\n\nFixpoint re_not_empty {T} (re : reg_exp T) : bool \n  (* ЗАМЕНИТЕ ДАННУЮ СТРОКУ НА   := _ваше определение_ . *) . Admitted.\n\nLemma re_not_empty_correct : forall T (re : reg_exp T),\n  (exists s, s =~ re) <-> re_not_empty re = true.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Тактика [remember] (помнить) *)\n\n(** Одно потенциально путающее свойство тактики [induction] состоит\n    в том, что она радостно позволяет вам попробовать индукцию над\n    термом, который не является достаточно общим. Суммарный эффект\n    будет в потере информации (также как и в случае [destruct]), \n    и состоянии в котором вы будете не способны завершить\n    доказательство. Вот пример: *)\n\nLemma star_app: 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\n(** Просто делая [inversion] на [H1] не заведет нас далеко в реккурсивных\n    случаях. (Попробуйте это!). Нам нужна индукция. Вот наивная первая\n    попытка: *)\n\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\n(** Но теперь, несмотря на то что мы получили семь случаев (как мы и ожидали\n    из определение [exp_match]), мы потеряли важный кусок информации из\n    [H1]: факт того что [s1] соответствует чему то из [Star re]. Это\n    означает что мы должны предоставить доказательства для _всех_\n    семи конструкторов определения, несмотря на то что все, кроме\n    двух из них ([MStar0] и [MStarApp]), противоречивы. Мы всеравно можем\n    получить доказательство для нескольких конструкторов, как\n    [MEmpty]... *)\n\n  - (* MEmpty *)\n    simpl. intros H. apply H.\n\n(** ... но большинство из них застревает.  Для [MChar], например,\n   мы должны показать что\n\n    s2 =~ Char x' -> x' :: s2 =~ Char x',\n\n    что безусловно невозможно. *)\n\n  - (* MChar. Застряли... *)\n\nAbort.\n\n(** Проблема в том, что [induction] над гипотезой Prop работает\n    хорошо только с гипотезами которые полностью общие, т.е., те\n    в которых все аргументы являются переменными, в отличие от\n    более общих выражений, таких как [Star re]. В этом случае она\n    работает более как [destruct] чем [inversion].\n\n    Мы можем решить данную проблему обобщая над проблемными\n    выражениями с явным равнеством: *)\n\nLemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp T),\n  s1 =~ re' ->\n  re' = Star re ->\n  s2 =~ Star re ->\n  s1 ++ s2 =~ Star re.\n\n(** Мы теперь можем работать с помощью индукции над свидетельством напрямую,\n    так как аргумент первой гипотезы достаточно общий, что означает\n    мы можем разобраться с большинством случаев инвертируя равенство\n    [re' = Star re] в контексте.\n\n    Данная идиома настолько обычна, что Coq предоставляет тактику\n    для автоматической генеразии таких уравнений для нас, избегая\n    необходимости изменения утверждений наших теорем. Вызывая\n    [remember e as x] заставляет Coq (1) заменить все случаи выражения\n    [e] на переменную [x], и (2) добавить равенство [x =\n    e] в контекст. Вот как мы можем использовать ее для того чтобы\n    показать предыдущий результат: *)\n\nAbort.\n\nLemma star_app: 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\n(** У нас теперь есть [Heqre' : re' = Star re]. *)\n\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\n(** [Heqre'] противоречива в большинстве случаев, что позволяет\n    завершить их сразу. *)\n\n  - (* MEmpty *)  inversion Heqre'.\n  - (* MChar *)   inversion Heqre'.\n  - (* MApp *)    inversion Heqre'.\n  - (* MUnionL *) inversion Heqre'.\n  - (* MUnionR *) inversion Heqre'.\n\n(** В интересных случаях (те что соответствуют [Star]), мы можем\n    идти как раньше. Заметьте что индукционная гипотеза [IH2] на случай\n    [MStarApp] упоминает дополнительную предпосылку [Star re'' = Star\n    re'], что является результатом равенства сгенерированного [remember]. *)\n\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\n(** **** Упражнение: 4 звездочки (exp_match_ex2)  *)\n\n(** Лемма [MStar''] снизу (объединенная со своей обратной, упражнение\n    [MStar'] сверху), показывает, что наше определение [exp_match]\n    для [Star] эквивалентно неформальному которое мы предоставили раньше. *)\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  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 5 звездочек, продвинутое (накачка)  *)\n(** Одна из первых интересных теорем в теории регулярных \n    выражений это так называемая _лемма о накачке_, которая\n    утверждает, неформально, что любая достаточно длинная строка [s]\n    соответствующая регулярному выраженип [re] может быть \"накачана\"\n    повторением некоторой серединной секции [s] произольное число раз\n    для получения новой строки также соответствующей [re]. \n\n    Для начала, мы должны определить \"достаточно длинное.\" Так как\n    мы работаем в конструктивной логике, мы на самом деле должны иметь\n    возможность вычислить для любого регулярного выражения [re] минимальную\n    длину строк [s] для которой гарантируется \"накачка.\" *)\n\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 =>\n      pumping_constant re1 + pumping_constant re2\n  | Union re1 re2 =>\n      pumping_constant re1 + pumping_constant re2\n  | Star _ => 1\n  end.\n\n(** Далее, полезно определить вспомогательную функцию которая повторяет строку\n   (присоединяет ее к самомй себе) некоторое число раз. *)\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 T n m l.\n  induction n as [|n IHn].\n  - reflexivity.\n  - simpl. rewrite IHn, app_assoc. reflexivity.\nQed.\n\n(** Теперь, лемма о накачке сама по себе утверждает что, если [s =~ re]\n    и если длина [s] хотябы равна константе накачки [re], тогда [s]\n    может быть разбита на три подстроки [s1 ++ s2 ++ s3] таким образом\n    что [s2] может быть повторенно любое число раз и результат, когда\n    объединен с [s1] и [s3] все еще будет соответствовать [re]. Так как [s2]\n    гарантирована не быть пустой строкой, это предоставляет на\n    (конструктивный!) способ сгенерировать строки соответствующие [re] \n    и при этом настолько длинные насколько мы захотим. *)\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    forall m, s1 ++ napp m s2 ++ s3 =~ re.\n\n(** Чтобы ускорить доказательство (которое вы должны заполнить), тактика [omega],\n    которая вступает в силу со следующим [Require], очень полезна в нескольких\n    местах для автоматического завершения длинных низкоуровневых аргументов,\n    включающих равенства или неравеснтва на натуральных числах. Мы возвратимся\n    к [omega] в следующих главах, но чувствуйте себя свободно в жкспериментированийй\n    с ней и сейчас. Первый случай индукции демонстрируер как она используется. *)\n\nRequire Import Coq.omega.Omega.\n\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. omega.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nEnd Pumping.\n(** [] *)\n\n(* ################################################################# *)\n(** * Улучшаем Рефлексию *)\n\n(** Мы уже видели в главе [Logic] что нам часто нужно связывать\n    булевы вычисления с утверждениями в [Prop]. К несчастью,\n    произведение такой конвертации руками часто приводит к\n    усложненным скриптам доказательств. Рассмотрим доказательство\n    следующей теоремы: *)\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  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_nat n m) eqn:H.\n    + (* beq_nat n m = true *)\n      intros _. rewrite beq_nat_true_iff in H. rewrite H.\n      left. reflexivity.\n    + (* beq_nat n m = false *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** В первой ветке после [destruct], мы напрямую применяем\n    лемму [beq_nat_true_iff] к уравнениям сгенерированным \n    разбором [beq_nat n m], для того чтобы сконвертировать предположение [beq_nat n m\n    = true] в предположение [n = m], которое нам и нужно для завершения\n    цели.\n\n    Мы можем упростить данное доказательство определением индуктивной\n    пропозиции которая производит более лучший принцип разбора случаев \n    для [beq_nat n m]. Вместо генерации уравнения вроде [beq_nat n m =\n    true], которое напрямую бесполезно, этот принцио дает нам\n    сразу предположение нужное нам: [n = m]. Мы на самом деле\n    определим нечто более обшее, что можно будет использовать с\n    любыми свойствами (и не только равенствами): *)\n\nInductive reflect (P : Prop) : bool -> Prop :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~ P -> reflect P false.\n\n(** Свойство [reflect] принимает два аргумента: пропозицию\n    [P] и булево значение [b].  Интуитивно, оно утверждает что свойство\n    [P] _отражено_ в (т.е., эквивалентно) булеву [b]: [P]\n    справедливо тогда и только тогда когда [b = true].  Чтобы увидеть это,\n    заметьте что, по определению, единственный способ которым мы можем\n    предоставить свидетельство того что [reflect P true] имеет место, это\n    показать что [P] справедливо и использовать конструктор\n    [ReflectT].  Если мы инвертируем данное утверждений, то это значит,\n    что должно быть возможно выделить свидетельство для [P] из\n    доказательства [reflect P true]. Обратно, единственный способ\n    показать [reflect P false] это объединить свидетельство для [~ P] \n    с конструктором [ReflectF].\n\n    Легко формализовать данную интуицию и показать, что два\n    утверждения действительно эквивалентны: *)\n\nTheorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.\nProof.\n  intros P [] H.\n  - apply ReflectT. rewrite H. reflexivity.\n  - apply ReflectF. rewrite H. intros H'. inversion H'.\nQed.\n\n(** **** Упражнение: 2 звездочки, рекомендаванное (reflect_iff)  *)\nTheorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** Преимущество [reflect] над нормальным связкой \"тогда и только тогда\"\n    состоит в том, что разбивая гипотезы или леммы в форме\n    [reflect P b], мы можем делать разбор случаев на [b] в тоже\n    время генерируя соответствующие гипотезы в двух ветках \n    ([P] в первой подцели и [~ P] во второй).\n\n    Для использования [reflect] чтобы сгенерировать более лучшее\n    доказательство [filter_not_empty_In], мы начнем с перевода леммы\n    [beq_nat_iff_true] в более удобную форму в терминах\n    [reflect]: *)\n\nLemma beq_natP : forall n m, reflect (n = m) (beq_nat n m).\nProof.\n  intros n m.\n  apply iff_reflect. rewrite beq_nat_true_iff. reflexivity.\nQed.\n\n(** Новое доказательство [filter_not_empty_In] теперь происходит\n    следующим образом. Заметьте как мы вызываем [destruct] и [apply] \n    объединенные в один вызов к [destruct].  (Чтобы увидеть это яснее,\n    посмотрите на два доказательства [filter_not_empty_In] в вашем окне Coq\n    и рассмотрите различия в состоянии доказательства вначале первого \n    случая [destruct].) *)\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  - (* l = [] *)\n    simpl. intros H. apply H. reflexivity.\n  - (* l = m :: l' *)\n    simpl. destruct (beq_natP n m) as [H | H].\n    + (* n = m *)\n      intros _. rewrite H. left. reflexivity.\n    + (* n <> m *)\n      intros H'. right. apply IHl'. apply H'.\nQed.\n\n(** Несмотря на то что данная техника возможно дает нам лишь небольшое\n    преимущество в удобстве для данного конкретного доказательства,\n    используя [reflect] последовательно часто приводит к более коротким\n    и ясным доказательствам. Мы увидем гораздо больше примеров, где\n    [reflect] становится удобным в дальнейших главах.\n\n    Использование свойства [reflect] было популяризовано Coq библиотекой\n    _SSReflect_, которая была использована для формализазии важных результатов\n    в математике, включая теорему о четырех красок и теорему Фейт Томпсона.\n    Имя SSReflect также означает _small-scale reflection_ (рефлексия малого\n    маштаба), т.е., всепроникающее использование рефлексии для упрощения\n    малых доказательств используя булевы вычисления. *) \n\n(* ################################################################# *)\n(** * Дополнительные Упражнения *)\n\n(** **** Упражнения: 4 звездочки, рекомендовано (палиндромы)  *)\n(** Палиндроме есть последовательность которая читается также задом\n    наперед как и в обычную сторону.\n\n    - Определите индуктивную пропозицию [pal] на [list X] которая\n      описывает что означает быть палиндромом. (Подсказка: Вам понадобится\n      три случая. Ваше определение должно базироваться на структуре\n      списка; просто иметь один конструктор\n\n        c : forall l, l = rev l -> pal l\n\n      может показаться очевидным, но не будет работать хорошо.)\n\n    - Докажите ([pal_app_rev]) о том что\n\n       forall l, pal (l ++ rev l).\n\n    - Докажите ([pal_rev] that)\n\n       forall l, pal l -> l = rev l.\n*)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 5 звездочек, дополнительное (palindrome_converse)  *)\n(** Опять, обратное направление значительно более трудное, из за отсутствия\n    свидетельства. Используя ваше определение [pal] из предыдущего\n    упражнения, докажите что\n\n     forall l, l = rev l -> pal l.\n*)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 4 звездочки, продвинутое (filter_challenge)  *)\n(** Давайте докажем, что наше определение [filter] из главы [Poly]\n    соответствует абстрактной спецификации. Вот спецификация,\n    записанная неформально:\n\n    Список [l] является \"объединенным с сохранением порядка\" [l1] и [l2] если он \n    содержит все теже элементы что [l1] и [l2], в том же порядке что [l1]\n    и [l2], но возможно чередующиеся. Например,\n\n    [1;4;6;2;3]\n\n    есть объединенные с сохранением порядка для\n\n    [1;6;2]\n\n    и\n\n    [4;3].\n\n    Теперь, предположим, что у нас есть множество [X], функция [test: X->bool],\n    и список [l] типа [list X].  Предположим далее, что [l] есть\n    объединение с сохранением порядка двух списков, [l1] и [l2], таких что\n    для любого терма в [l1] удовлетворяющего [test] и ни один элемент из [l2]\n    не удовлетворяет тесту, Тогда\n    [filter test l = l1].\n\n    Переведите данную спецификацию в теорему Coq и докажите ее.\n    (Вам надо будет начать определять что означает для одного списка\n    быть объединением двух других. Сделайте это с помощью индуктивного\n    отношения, а не [Fixpoint].)  *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 5 звездочек, продвинутое, дополнительное (filter_challenge_2)  *)\n(** Другой способ охарактеризовать поведение [filter] работает следующим\n    образом: Среди все подпоследовательностей [l] со свойством того что [test]\n    вычисляется в  [true] на всех ее членах, [filter test l] наиболее длинна.\n    Формализуйте данное заявление и докажите его. *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 4 звездочки, дополнительное (NoDup)  *)\n(** Вспомните определение свойства [In] из главы [Logic],\n    которое утверждает что значение [x] появляется хотя бы раз\n    в списке [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(** Ваша первая задача заключается в использовании [In] для определения\n    пропозиции [disjoint X l1 l2], которая должна быть доказуема точно тогда,\n    когда [l1] и [l2] списки (с элементами типа X) которые не имеют\n    общих элементов. *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n\n(** Далее, используйте [In] для определения индуктивного определения\n    [NoDup X l], которая должна быть доказуема точно тогда когда [l]\n    список (с элементами типа [X]) где каждый член не отличается от \n    любого другого. Например, [NoDup nat [1;2;3;4]] и [NoDup\n    bool []] должны быть доказуемы, в то время как [NoDup nat [1;2;1]] и\n    [NoDup bool [true;true]] нет.  *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n\n(** Наконец, сформулируйте и докажите одну или более интересных теорем связанных с\n    [disjoint], [NoDup] и [++] (конкатенация списков).  *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 3 звездочки, рекомендованное (nostutter)  *)\n(** Умение формулировать индуктивные определение свойств это важный\n    навык который будет нужен в данном курсе. Попробуйте решить\n    данное упражнение без какой либо помощи.\n\n    Мы говорим что We say that a list \"заикается\" если он повторяет\n    один и тот же элемент последовательно. Свойство \"[nostutter mylist]\"\n    означает, что [mylist] не заикается. Сформулируйте индуктивное\n    определение для [nostutter].  (Это свойство отличо от [NoDup]\n    из предыдущего упражнения; последовательность [1;4;1] \n    повторяется, но не заикается.) *)\n\nInductive nostutter {X:Type} : list X -> Prop :=\n (* ЗАПОЛНИТЕ ЗДЕСЬ *)\n.\n(** Убедитесь, что следующие тесты проходят, но можете менять\n    предложенное доказательство (в комментарияз) если предоставленное не\n    работает для вас. Ваше определение может быть отличным от нашего\n    и всеравно правильным. В этом случае примеры потребуют другого\n    доказательства.  (Вы заметите, что предложеные доказательства\n    используют некоторые тактики о которых мы еще не говорили. Это\n    сделано для того чтобы доказательства были более устойчивы\n    по отношению к разным способам определения [nostutter]. Вы можете\n    вероятно расскоментировать их и использовать как есть, но также\n    вы можете доказать каждый пример с использованием лишь\n    более базовых тактик.)  *)\n\nExample test_nostutter_1: nostutter [3;1;4;1;5;6].\n(* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n*)\n\nExample test_nostutter_2:  nostutter (@nil nat).\n(* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(* \n  Proof. repeat constructor; apply beq_nat_false_iff; auto.\n  Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* ЗАПОЛНИТЕ ЗДЕСЬ *) 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(* ЗАПОЛНИТЕ ЗДЕСЬ *) 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(** **** Упражнение: 4 звездочки, продвинутое (принцип Дирихле)  *)\n(**_Принцип Дирихле_ утверждает базовый факт о счете: если мы распределим более\n   чем [n] элементов в [n] ячеек, то некоторые из ячеек будут\n   содержать хотябы два элемента. Как часто бывает, этот очевидно\n   тривиальный факт о числах требует нетривиальной машинерии\n   для своего доказательства, но теперь у нас ее достаточно... *)\n\n(** Во первых докажите легкую полезную лемму. *)\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  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\n(** Теперь определите свойство [repeats] такое что [repeats X l] утверждает\n    что [l] содержит хотя бы один повторяющийся элемент (of type [X]).  *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *)\n.\n\n(** Теперь, вот способ формализовать принцип Дирихле. Предположим\n    список [l2] представляет из себя список идентификаторов ячеек, и\n    список [l1] представляет идентификаторы присвоенные списку \n    элементов. Если у нас больше элементов чем идентификаторов,\n    то хотя бы двое элементов должны уметь тот же идентификатор\n    -- т.е., список [l1] содержит повторения.\n\n    Это доказательство гораздо легче, если вы используете принцип\n    исключенного третьего [excluded_middle] для доказательства того\n    что [In] разрешима, т.е., [forall x l, (In x\n    l) \\/ ~ (In x l)].  Тем не меннее, также возможно доказать\n    _не_ предполагая что [In] разрешимо; если вы сможете сделать\n    это, вам не понадобится гипотеза [excluded_middle]. *)\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  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n\n(** $Date: 2015-08-11 12:03:04 -0400 (Tue, 11 Aug 2015) $ *)\n", "meta": {"author": "karsar", "repo": "SF_Russian", "sha": "653657985d4134973a512cc897bf1793c6ebd378", "save_path": "github-repos/coq/karsar-SF_Russian", "path": "github-repos/coq/karsar-SF_Russian/SF_Russian-653657985d4134973a512cc897bf1793c6ebd378/IndProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7257341850048898}}
{"text": "(*|\n#########################\nProve properties of lists\n#########################\n\n:Link: https://stackoverflow.com/q/52410544\n|*)\n\n(*|\nQuestion\n********\n\nMy aim is to prove that certain properties of generated lists hold.\nFor instance, a generator function produces a list of ``1``\\ s, the\nlength of the list is given as an argument; I'd like to prove that the\nlength of the list is what the argument specifies. This is what I have\nso far:\n|*)\n\nRequire Import List.\n\nFixpoint list_gen lng acc :=\n  match lng with\n  | 0 => acc\n  | S lng_1 => list_gen lng_1 (1 :: acc)\n  end.\n\nLemma lm0 : length (list_gen 0 nil) = 0.\n  intuition.\nQed.\n\nLemma lm1 : forall lng : nat, length (list_gen lng nil) = lng.\n  induction lng.\n  - apply lm0.\n  - (* .unfold *)\nAbort. (* .none *)\n\n(*|\nNow after applying ``lm0`` the induction step is left. I was hoping\nthat the proof of this step would be deduced from the code of\n``list_gen`` but it's most likely a mistaken concept. How can this\nsubgoal be proved?\n\n----\n\n**A (Daniel Schepler):** I would guess probably you need to generalize\nwhat you're proving to handle cases where the ``acc`` argument is not\n``nil``:\n\n.. code-block:: coq\n\n    forall (lng : nat) (acc : list nat),\n      length (list_gen lng acc) = lng + length acc.\n\n(And then simpl should be very helpful in proving the inductive\nstep...)\n|*)\n\n(*|\nAnswer\n******\n\nI would go with Daniel's approach, however a bit more general one is\nto write out a spec of ``list_gen``, e.g. using *non-tail-recursive*\n``repeat`` function:\n|*)\n\nRequire Import List Arith.\nImport ListNotations.\n\nLemma list_gen_spec : forall lng acc,\n    list_gen lng acc = repeat 1 lng ++ acc.\nAbort. (* .none *)\n\n(*|\nwhere I had to add a bunch of lemmas about ``repeat``'s interaction\nwith some standard list functions.\n|*)\n\nLemma repeat_singleton {A} (x : A) :\n  [x] = repeat x 1.\nAdmitted.\n\nLemma repeat_app {A} (x : A) n m :\n  repeat x n ++ repeat x m = repeat x (n + m).\nAdmitted.\n\nLemma app_cons {A} (x : A) xs :\n  x :: xs = [x] ++ xs.\nAdmitted.           (* this is a convenience lemma for the next one *)\n\nLemma app_cons_middle {A} (y : A) xs ys :\n  xs ++ y :: ys = (xs ++ [y]) ++ ys.\nAdmitted.\n\n(*|\nI'll leave the proofs of these lemmas as an exercise.\n\nAfter proving the spec, your lemma could be proved with a few\nrewrites.\n|*)\n\nLemma list_gen_spec : forall lng acc,\n    list_gen lng acc = repeat 1 lng ++ acc.\nProof.\n  induction lng as [| lng IH]; intros xs; simpl; trivial.\n  rewrite IH.\n  now rewrite app_cons_middle, repeat_singleton, repeat_app, Nat.add_comm.\nQed.\n\nLemma lm1 lng : length (list_gen lng nil) = lng.\nProof.\n  now rewrite list_gen_spec, app_nil_r, repeat_length.\nQed.\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/prove-properties-of-lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7257341723634526}}
{"text": "Require Import ZF.Axioms.\nRequire Import ZF.Constructions.\nRequire Import ZF.Tactics.\nRequire Import ZF.Omega.\n\nTheorem not_in_self x : ~(x in x).\nProof.\n  intros ?.\n  destruct (set_reg {x,}) as [? []]. { apply singleton_not_empty. }\n  unsettle. subst. firstorder.\nQed.\n\nTheorem not_in_eachother x y: ~(x in y /\\ y in x).\nProof.\n  intros ?.\n  destruct (set_reg {x, y}) as [? []]. { apply pair_not_empty. }\n  unsettle. intuition; subst; firstorder.\nQed.\n\nTheorem not_in_triple x y z : ~(x in y /\\ y in z /\\ z in x).\nProof.\n  intros ?.\n  destruct (set_reg (cup {x, y} {y, z})) as [w [i d]]. { exists x. unsettle. auto. }\n  unsettle. intuition; subst; firstorder.\nQed.\n\nTheorem in_well_founded s : nonempty s -> exists m, m in s /\\ forall w, w in s -> ~(w in m).\nProof. \n  intros e.\n  destruct (set_reg _ e) as [x [? H]].\n  exists x. intuition.\n  destruct H. exists w. auto.\nQed.\n\nDefinition transitive_closure a := union (c_repl omega (recurse a union)).\n\nTheorem transitive_closure_transitive a b c: b in c -> c in transitive_closure a -> b in transitive_closure a.\nProof.\n  intros ? i.\n  unfold transitive_closure in *.\n  unsettle.\n  destruct i as [l [? [n]]].\n  exists (union l).\n  unsettle. split.\n  + exists c. auto.\n  + exists (succ n).\n    intuition. subst.\n    rewrite recurse_s; auto.\nQed.\n\nTheorem set_ind (P : set -> Prop) : (forall x, (forall y, y in x -> P y) -> P x) -> forall z, P z.\nProof.\n  intros I a.\n  destruct (classic (P a)) as [ | na]; auto.\n  destruct (in_well_founded (c_specif (transitive_closure {a,}) (fun z => ~P z))) as [m [i min]]. {\n    exists a. unfold transitive_closure. unsettle. intuition.\n    exists {a,}. unsettle. intuition.\n    exists nothing.\n    intuition.\n    auto using recurse_z.\n  }\n  unsettle.\n  destruct i as [? u].\n  destruct u.\n  apply I.\n  intros y ?.\n  destruct (classic (P y)); auto.\n  destruct (min y); intuition.\n  eauto using transitive_closure_transitive.\nQed.\n\nPrint set_ind.\n\nTheorem in_accessible x : Acc elem x.\nProof. induction x using set_ind. constructor. auto. Qed.\n\n(*\nSection wf_recursion.\nVariable S : forall x, (forall y, y in x -> set) -> set.\n\nLocal Record is_wf_recursive i F : Prop := {\n  is_wf_rec_pairs : forall p, p in F -> exists s x, s in i /\\ p = (k, x);\n  is_wf_rec_functional : forall s, s in i -> exists! x, (k, x) in F;\n  is_wf_rec_s : forall s, s in i -> (forall (k, x) in F -> (succ k, S x) in F;\n}.\n\n*)\n\n\n", "meta": {"author": "mniip", "repo": "ZF", "sha": "870fa0012f33d373ae610772ca2620d78e3809db", "save_path": "github-repos/coq/mniip-ZF", "path": "github-repos/coq/mniip-ZF/ZF-870fa0012f33d373ae610772ca2620d78e3809db/Regularity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7256134066179034}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (y : natural) (lf2 : natural) : natural :=\n  plus y (plus lf3 lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj172_coqofml_XjOMtM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7256133999067891}}
{"text": "\nVariable Term : Type.\nVariable r : Term -> Term -> Prop.\nVariable A : Term. (* type is not empty                                          *)\n\nNotation \"M ~> N\" := (r M N) (at level 50).\n\nAxiom WeakDec : forall (M N:Term), (M ~> N) \\/ ~(M ~> N).\n\nDefinition confluence1 : Prop := forall (L M N:Term), \n    L ~> M -> L ~> N -> exists (P:Term), (M ~> P) /\\ (N ~> P).\n\n(* Seemingly as Stronger statement                                              *)\nDefinition confluence2 : Prop := forall (L M N:Term),\n    exists (P:Term), L ~> M -> L ~> N -> (M ~> P) /\\ (N ~> P).\n\nLemma L1 : confluence2 -> confluence1.\nProof.\n    unfold confluence1, confluence2. intros H L M N H1 H2.\n    destruct (H L M N) as [P H3]. exists P. apply H3; assumption.\nQed.\n\n(* Term is not an empty type and relation is weakly decidable.                  *)\nLemma L2 : confluence1 -> confluence2.\nProof.\n    unfold confluence1, confluence2. intros H L M N.\n    destruct (WeakDec L M) as [H1|H1];\n    destruct (WeakDec L N) as [H2|H2].\n    - destruct (H L M N H1 H2) as [P [H3 H4]]. exists P. \n      intros. split; assumption.\n    - exists A. intros H3 H4. apply H2 in H4. contradiction.\n    - exists A. intros H3 H4. apply H1 in H3. contradiction.\n    - exists A. intros H3 H4. apply H1 in H3. contradiction.\nQed.\n\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/confluence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7256133939892233}}
{"text": "(* Exercise 17 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_017 : ~(exists x : D, forall y : D, (R y x -> ~ R x y) /\\ (~ R x y -> R y x)).\nProof.\nneg_i (1=1) a1.\nexi_e (exists x : D, forall y : D, (R y x -> ~ R x y) /\\ (~ R x y -> R y x)) a a2.\nhyp a1.\ndis_e (R a a \\/ ~R a a) a3 a3.\nLEM.\nneg_e (R a a).\nimp_e (R a a).\ncon_e1 (~R a a -> R a a).\nall_e (forall y:D, (R y a -> ~ R a y) /\\ (~ R a y -> R y a)) a.\nhyp a2.\nhyp a3.\nhyp a3.\nneg_e (R a a).\nhyp a3.\nimp_e (~R a a).\ncon_e2 (R a a -> ~R a a).\nall_e (forall y : D, (R y a -> ~ R a y) /\\ (~ R a y -> R y a)) a.\nhyp a2.\nhyp a3.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred017.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368929, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.7255556504026743}}
{"text": "Require Import init.\n\nRequire Export topology_order_base.\nRequire Import topology_subspace.\nRequire Import topology_connected.\nRequire Export relation.\nRequire Import order_minmax.\n\nUnset Keyed Unification.\n\n(* begin hide *)\nSection OrderTopology.\n\nContext {U} `{\n    Order U,\n    Reflexive U le,\n    Connex U le,\n    Antisymmetric U le,\n    Transitive U le,\n    NotTrivial U\n}.\n(* end hide *)\nDefinition top_convex (S : U → Prop) :=\n    ∀ a b, S a → S b → closed_interval a b ⊆ S.\n\nTheorem open_interval_convex : ∀ a b, top_convex (open_interval a b).\nProof.\n    intros a b c d [ac cb] [ad db] x [cx dx].\n    split.\n    -   exact (lt_le_trans ac cx).\n    -   exact (le_lt_trans dx db).\nQed.\nTheorem open_closed_interval_convex:∀ a b,top_convex (open_closed_interval a b).\nProof.\n    intros a b c d [ac cb] [ad db] x [cx dx].\n    split.\n    -   exact (lt_le_trans ac cx).\n    -   exact (trans dx db).\nQed.\nTheorem closed_open_interval_convex:∀ a b,top_convex (closed_open_interval a b).\nProof.\n    intros a b c d [ac cb] [ad db] x [cx dx].\n    split.\n    -   exact (trans ac cx).\n    -   exact (le_lt_trans dx db).\nQed.\nTheorem closed_interval_convex : ∀ a b, top_convex (closed_interval a b).\nProof.\n    intros a b c d [ac cb] [ad db] x [cx dx].\n    split.\n    -   exact (trans ac cx).\n    -   exact (trans dx db).\nQed.\nTheorem open_inf_interval_convex : ∀ a, top_convex (open_inf_interval a).\nProof.\n    intros a b c ab ac x [bx xc].\n    exact (lt_le_trans ab bx).\nQed.\nTheorem closed_inf_interval_convex : ∀ a, top_convex (closed_inf_interval a).\nProof.\n    intros a b c ab ac x [bx xc].\n    exact (trans ab bx).\nQed.\nTheorem inf_open_interval_convex : ∀ a, top_convex (inf_open_interval a).\nProof.\n    intros a b c ab ac x [bx xc].\n    exact (le_lt_trans xc ac).\nQed.\nTheorem inf_closed_interval_convex : ∀ a, top_convex (inf_closed_interval a).\nProof.\n    intros a b c ab ac x [bx xc].\n    exact (trans xc ac).\nQed.\n\n(* begin hide *)\nContext `{SupremumComplete U le, Dense U (strict le)}.\n\nLet order_top := order_topology.\nExisting Instance order_top.\nExisting Instance subspace_topology.\n\nLemma convex_connected_wlog : ∀ S, top_convex S →\n    ∀ (A B : set_type S → Prop) a b, A a → B b → a < b → ¬(separation A B).\nProof.\n    intros S S_convex A B a b Aa Bb ab.\n    intros [A_empty [B_empty [A_open [B_open [AB_dis AB_all]]]]].\n    pose (A' x := A x ∧ x < b).\n    pose (A'' := from_set_type A').\n    assert (∃ x, A'' x) as A'_ex.\n    {\n        exists [a|].\n        split with [|a].\n        rewrite set_type_simpl.\n        split; assumption.\n    }\n    assert (has_upper_bound le A'') as A'_upper.\n    {\n        exists [b|].\n        intros x' [Sx' [Ax' x_lt]].\n        apply x_lt.\n    }\n    pose proof (sup_complete A'' A'_ex A'_upper) as [α [α_upper α_least]].\n    assert (A = 𝐂 B) as A_compl.\n    {\n        apply antisym.\n        -   intros x Ax Bx.\n            assert ((A ∩ B) x) as x_in by (split; assumption).\n            unfold disjoint in AB_dis.\n            rewrite AB_dis in x_in.\n            exact x_in.\n        -   intros x nBx.\n            assert (all x) as x_in by exact true.\n            rewrite <- AB_all in x_in.\n            destruct x_in as [Ax|Bx].\n            +   exact Ax.\n            +   contradiction.\n    }\n    assert (B = 𝐂 A) as B_compl.\n    {\n        rewrite A_compl.\n        rewrite compl_compl.\n        reflexivity.\n    }\n    assert (closed A) as A_closed.\n    {\n        unfold closed.\n        rewrite <- B_compl.\n        exact B_open.\n    }\n    assert (closed B) as B_closed.\n    {\n        unfold closed.\n        rewrite <- A_compl.\n        exact A_open.\n    }\n    assert (S α) as Sα.\n    {\n        apply (S_convex [a|] [b|] [|a] [|b]).\n        split.\n        -   apply α_upper.\n            split with [|a].\n            rewrite set_type_simpl.\n            split; assumption.\n        -   apply α_least.\n            intros x [x' [x_eq Ax]].\n            apply Ax.\n    }\n    assert (A [α|Sα]) as Aα.\n    {\n        classic_case (A [α|Sα]) as [A_in|A_nin]; try exact A_in.\n        classic_case (a = [α|Sα]) as [a_eq|a_neq].\n        {\n            rewrite <- a_eq.\n            exact Aa.\n        }\n        assert ([a|] < α) as a_lt.\n        {\n            split.\n            -   apply α_upper.\n                split with [|a].\n                rewrite set_type_simpl.\n                split; assumption.\n            -   intro; subst.\n                apply a_neq.\n                apply set_type_eq; cbn.\n                reflexivity.\n        }\n        rewrite closed_limit_points in A_closed.\n        apply A_closed.\n        intros SC SC_open SCα.\n        apply empty_neq.\n        destruct SC_open as [UC [UC_open C_eq]].\n        rewrite C_eq in SCα.\n        specialize (UC_open _ SCα) as [BC [BC_basis [BCα BC_sub]]].\n        assert (∀ c d, open_closed_interval c d α → open_interval c d ⊆ UC →\n            ∃ x, ((A - ❴[α | Sα]❵)%set ∩ SC) x) as wlog.\n        {\n            clear BCα BC_sub.\n            intros c d BCα BC_sub.\n            pose (m := max c [a|]).\n            assert (S m) as Sm.\n            {\n                apply (S_convex [a|] α [|a] Sα).\n                split.\n                -   apply rmax.\n                -   unfold m, max; case_if.\n                    +   apply a_lt.\n                    +   apply BCα.\n            }\n            classic_case (∃ n, m < [n|] ∧ [n|] < α ∧ A n) as [n_ex|m_max'].\n            +   destruct n_ex as [n [mn [nα An]]].\n                exists n.\n                repeat split.\n                *   exact An.\n                *   rewrite singleton_eq; intro; subst n.\n                    destruct nα; contradiction.\n                *   rewrite C_eq.\n                    unfold to_set_type.\n                    apply BC_sub.\n                    split.\n                    --  apply (le_lt_trans (lmax c [a|])).\n                        exact mn.\n                    --  apply (lt_le_trans nα).\n                        apply BCα.\n            +   rewrite not_ex in m_max'.\n                assert (is_upper_bound le A'' m) as m_max.\n                {\n                    intros x A''x.\n                    pose proof (α_upper x A''x) as x_le.\n                    destruct A''x as [Sx [Ax x_lt]].\n                    specialize (m_max' [x|Sx]).\n                    do 2 rewrite not_and in m_max'.\n                    destruct m_max' as [leq|[leq|nAx]].\n                    -   rewrite nlt_le in leq.\n                        exact leq.\n                    -   rewrite nlt_le in leq.\n                        pose proof (antisym leq x_le).\n                        subst α.\n                        cbn in *.\n                        rewrite (proof_irrelevance Sx Sα) in Ax.\n                        contradiction.\n                    -   contradiction.\n                }\n                specialize (α_least _ m_max).\n                assert (m < α) as ltq.\n                {\n                    unfold m, max; case_if.\n                    -   exact a_lt.\n                    -   apply BCα.\n                }\n                rewrite <- nle_lt in ltq.\n                contradiction.\n        }\n        destruct BC_basis as [BC_basis|[BC_basis|BC_basis]].\n        -   destruct BC_basis as [c [d BC_eq]].\n            subst BC.\n            assert (open_closed_interval c d α) as BCα2.\n            {\n                split; apply BCα.\n            }\n            exact (wlog c d BCα2 BC_sub).\n        -   destruct BC_basis as [c [d [BC_eq d_max]]].\n            subst BC.\n            assert (open_interval c d ⊆ UC) as BC_sub2.\n            {\n                apply (trans2 BC_sub).\n                intros x x_in.\n                split; apply x_in.\n            }\n            exact (wlog c d BCα BC_sub2).\n        -   destruct BC_basis as [c [d [BC_eq c_min]]].\n            subst BC.\n            assert (open_closed_interval c d α) as BCα2.\n            {\n                split.\n                -   split.\n                    +   apply BCα.\n                    +   intro; subst c.\n                        specialize (c_min [a|]).\n                        destruct (le_lt_trans c_min a_lt); contradiction.\n                -   apply BCα.\n            }\n            assert (open_interval c d ⊆ UC) as BC_sub2.\n            {\n                apply (trans2 BC_sub).\n                intros x x_in.\n                split; apply x_in.\n            }\n            exact (wlog c d BCα2 BC_sub2).\n    }\n    assert (B [α|Sα]) as Bα.\n    {\n        classic_case (B [α|Sα]) as [B_in|B_nin]; try exact B_in.\n        classic_case (b = [α|Sα]) as [b_eq|b_neq].\n        {\n            rewrite <- b_eq.\n            exact Bb.\n        }\n        assert (α < [b|]) as a_lt.\n        {\n            split.\n            -   apply α_least.\n                intros x [Sx [Ax x_lt]].\n                apply x_lt.\n            -   intro; subst.\n                apply b_neq.\n                apply set_type_eq; cbn.\n                reflexivity.\n        }\n        assert (∀ x, α < x → x < [b|] → S x) as in_S.\n        {\n            intros x x_lt1 x_lt2.\n            apply (S_convex α [b|] Sα [|b]).\n            split.\n            -   apply x_lt1.\n            -   apply x_lt2.\n        }\n        assert (∀ x (x_lt1 : α < x) (x_lt2 : x < [b|]),\n            B [x|in_S x x_lt1 x_lt2]) as in_B.\n        {\n            intros x x_lt1 x_lt2.\n            pose proof (in_S x x_lt1 x_lt2) as Sx.\n            rewrite (proof_irrelevance _ Sx).\n            classic_contradiction contr.\n            assert (all [x|Sx]) as x_in by exact true.\n            rewrite <- AB_all in x_in.\n            destruct x_in as [Ax|Bx]; try contradiction.\n            assert (A'' x) as Ax'.\n            {\n                split with Sx.\n                split.\n                -   exact Ax.\n                -   split.\n                    +   apply x_lt2.\n                    +   intros contr2.\n                        pose proof x_lt2 as x_lt2'.\n                        rewrite <- contr2 in x_lt2'.\n                        cbn in x_lt2'.\n                        destruct x_lt2'; contradiction.\n            }\n            specialize (α_upper _ Ax').\n            destruct (lt_le_trans x_lt1 α_upper); contradiction.\n        }\n        rewrite closed_limit_points in B_closed.\n        apply B_closed.\n        intros SC SC_open SCα.\n        apply empty_neq.\n        destruct SC_open as [UC [UC_open C_eq]].\n        rewrite C_eq in SCα.\n        specialize (UC_open _ SCα) as [BC [BC_basis [BCα BC_sub]]].\n        assert (∀ c d, closed_open_interval c d α → open_interval c d ⊆ UC →\n            ∃ x, ((B - ❴[α | Sα]❵)%set ∩ SC) x) as wlog.\n        {\n            clear BCα BC_sub.\n            intros c d BCα BC_sub.\n            pose (m := min [b|] d).\n            assert (α < m) as m_gt.\n            {\n                unfold m, min; case_if.\n                -   exact a_lt.\n                -   apply BCα.\n            }\n            pose proof (dense _ _ m_gt) as [n [αn nm]].\n            pose proof (lt_le_trans nm (lmin _ _)) as nb.\n            exists [n|in_S n αn nb].\n            repeat split.\n            +   apply in_B.\n            +   rewrite singleton_eq; intro contr.\n                inversion contr.\n                subst.\n                destruct αn; contradiction.\n            +   rewrite C_eq.\n                apply BC_sub; cbn.\n                split.\n                *   apply (le_lt_trans (land BCα)).\n                    exact αn.\n                *   apply (lt_le_trans nm).\n                    apply rmin.\n        }\n        destruct BC_basis as [BC_basis|[BC_basis|BC_basis]].\n        -   destruct BC_basis as [c [d BC_eq]].\n            subst BC.\n            assert (closed_open_interval c d α) as BCα2.\n            {\n                split; apply BCα.\n            }\n            exact (wlog c d BCα2 BC_sub).\n        -   destruct BC_basis as [c [d [BC_eq d_max]]].\n            subst BC.\n            assert (closed_open_interval c d α) as BCα2.\n            {\n                split.\n                -   apply BCα.\n                -   split.\n                    +   apply BCα.\n                    +   intro contr; subst d.\n                        specialize (d_max [b|]).\n                        destruct (lt_le_trans a_lt d_max); contradiction.\n            }\n            assert (open_interval c d ⊆ UC) as BC_sub2.\n            {\n                apply (trans2 BC_sub).\n                intros x x_in.\n                split; apply x_in.\n            }\n            exact (wlog c d BCα2 BC_sub2).\n        -   destruct BC_basis as [c [d [BC_eq c_min]]].\n            subst BC.\n            assert (open_interval c d ⊆ UC) as BC_sub2.\n            {\n                apply (trans2 BC_sub).\n                intros x x_in.\n                split; apply x_in.\n            }\n            exact (wlog c d BCα BC_sub2).\n    }\n    unfold disjoint in AB_dis.\n    assert ((A ∩ B) [α | Sα]) as AB by (split; assumption).\n    rewrite AB_dis in AB.\n    exact AB.\nQed.\n(* end hide *)\nTheorem convex_connected : ∀ S, top_convex S → connected (set_type S).\nProof.\n    intros S S_convex A B AB_sep.\n    pose proof (land AB_sep) as A_ex.\n    pose proof (land (rand AB_sep)) as B_ex.\n    apply empty_neq in A_ex, B_ex.\n    destruct A_ex as [a Aa].\n    destruct B_ex as [b Bb].\n    destruct (trichotomy a b) as [[ab|ab]|ab].\n    -   exact (convex_connected_wlog S S_convex A B a b Aa Bb ab AB_sep).\n    -   subst.\n        assert ((A ∩ B) b) as b_in by (split; assumption).\n        rewrite (land (rand (rand (rand (rand AB_sep))))) in b_in.\n        exact b_in.\n    -   rewrite separation_comm in AB_sep.\n        exact (convex_connected_wlog S S_convex B A b a Bb Aa ab AB_sep).\nQed.\n\nTheorem open_interval_connected :\n    ∀ a b, connected (set_type (open_interval a b)).\nProof.\n    intros a b.\n    apply convex_connected.\n    apply open_interval_convex.\nQed.\nTheorem open_closed_interval_connected :\n    ∀ a b, connected (set_type (open_closed_interval a b)).\nProof.\n    intros a b.\n    apply convex_connected.\n    apply open_closed_interval_convex.\nQed.\nTheorem closed_open_interval_connected :\n    ∀ a b, connected (set_type (closed_open_interval a b)).\nProof.\n    intros a b.\n    apply convex_connected.\n    apply closed_open_interval_convex.\nQed.\nTheorem closed_interval_connected :\n    ∀ a b, connected (set_type (closed_interval a b)).\nProof.\n    intros a b.\n    apply convex_connected.\n    apply closed_interval_convex.\nQed.\nTheorem open_inf_interval_connected :\n    ∀ a, connected (set_type (open_inf_interval a)).\nProof.\n    intros a.\n    apply convex_connected.\n    apply open_inf_interval_convex.\nQed.\nTheorem closed_inf_interval_connected :\n    ∀ a, connected (set_type (closed_inf_interval a)).\nProof.\n    intros a.\n    apply convex_connected.\n    apply closed_inf_interval_convex.\nQed.\nTheorem inf_open_interval_connected :\n    ∀ a, connected (set_type (inf_open_interval a)).\nProof.\n    intros a.\n    apply convex_connected.\n    apply inf_open_interval_convex.\nQed.\nTheorem inf_closed_interval_connected :\n    ∀ a, connected (set_type (inf_closed_interval a)).\nProof.\n    intros a.\n    apply convex_connected.\n    apply inf_closed_interval_convex.\nQed.\n(* begin hide *)\nEnd OrderTopology.\n(* end hide *)\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Topology/topology_order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7255556432054658}}
{"text": "Record WithHyps : Type :=\n  WrapHyps { hyps : list Prop ; p: Prop }.\n\nRequire Import Coq.Lists.List.\n\nImport ListNotations.\n\nFixpoint interp_hyps (hs : list Prop) : Prop := \n  match hs with \n  | [] => \n    True\n  | h :: hs => \n    h -> interp_hyps hs\n  end.\n\nDefinition interp_wh (x: WithHyps) : Prop := \n  interp_hyps x.(hyps) -> x.(p).\n\nLemma interp_hyps_sound : \n  forall P, \n    P <-> interp_wh (WrapHyps [] P).\nProof.\n  intros;\n  compute;\n  intuition eauto.\nQed.\n\nLemma add_hyp : \n  forall (hs : list Prop) (H P : Prop), \n    H -> \n    (interp_wh (WrapHyps hs P) <-> interp_wh (WrapHyps (H :: hs) P)).\nProof.\n  unfold interp_wh.\n  induction hs.\n  - compute. \n    intuition eauto.\n  - intros.\n    simpl in *.\n    intuition eauto.\nQed.\n\nLemma weaken_hyps : \n  forall (P: Prop) hs, \n    P -> interp_wh (WrapHyps hs P).\nProof.\n  intros;\n  compute;\n  intuition eauto.\nQed.\n\nRegister WrapHyps as ms.hyps.wrap_hyps.\nRegister interp_hyps as ms.hyps.interp_hyps.\nRegister interp_wh as ms.hyps.interp_wh.\n  \n\n", "meta": {"author": "jsarracino", "repo": "mirrorsolve", "sha": "74fc7790b21952d4f27ea70545b0038f298915b0", "save_path": "github-repos/coq/jsarracino-mirrorsolve", "path": "github-repos/coq/jsarracino-mirrorsolve/mirrorsolve-74fc7790b21952d4f27ea70545b0038f298915b0/src/theories/Hyps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7255226009512165}}
{"text": "(** * Correctness of Binary Search Trees (BSTs) *)\n\n(* This week we'll continue proving the correctness of a binary search tree implementation.\n * BSTs are a famous data structure for finite sets, allowing fast (log-time)\n * lookup, insertion, and deletion of items. (We omit the rebalancing heuristics\n * needed to achieve worst-case log-time operations, but you will prove the\n * correctness of rotation operations these heuristics use to modify the tree.)\n * In this problem set, we show that insertion and deletion functions are\n * correctly defined by relating them to operations on functional sets. *)\n\nRequire Import Frap Datatypes Pset4Sig.\nRequire Import Compare_dec.\n\n(* We will study binary trees of natural numbers only for convenience.\n   Almost everything here would also work with an arbitrary type\n   [t], but with [nat] you can use [linear_arithmetic] to prove\n   goals about ordering of multiple elements (e.g., transitivity). *)\nLocal Notation t := nat.\n\nModule Impl.\n  (* Trees are an inductive structure, where [Leaf] doesn't have any items,\n   * whereas [Node] has an item and two subtrees. Note that a [tree] can\n   * contain nodes in arbitrary order, so not all [tree]s are valid binary\n   * search trees. *)\n\n  (* (* Imported from Sig file: *)\n  Inductive tree :=\n  | Leaf (* an empty tree *)\n  | Node (d : t) (l r : tree).\n  *)\n  (* Then a singleton is just a node without subtrees. *)\n  Definition Singleton (v: t) := Node v Leaf Leaf.\n\n  (* [bst] relates a well-formed binary search tree to the set of elements it\n     contains. Note that invalid trees with misordered elements are not valid\n     representations of any set. All operations on a binary tree are specified\n     in terms of how they affect the set that the tree represents. That\n     set is encoded as function that takes a [t] and returns the proposition \"[t]\n     is in this set\". *)\n  Fixpoint bst (tr : tree) (s : t -> Prop) :=\n    match tr with\n    | Leaf => forall x, not (s x) (* s is empty set *)\n    | Node d l r =>\n        s d /\\\n        bst l (fun x => s x /\\ x < d) /\\\n        bst r (fun x => s x /\\ d < x)\n    end.\n\n  (* [member] computes whether [a] is in [tr], but to do so it *relies* on the\n     [bst] property -- if [tr] is not a valid binary search tree, [member]\n     will (and should, for performance) give arbitrarily incorrect answers. *)\n  Fixpoint member (a: t) (tr: tree) : bool :=\n    match tr with\n    | Leaf => false\n    | Node v lt rt =>\n      match compare a v with\n      | Lt => member a lt\n      | Eq => true\n      | Gt => member a rt\n      end\n    end.\n\n  (* Here is a typical insertion routine for BSTs.\n   * From a given value, we recursively compare the value with items in\n   * the tree from the root, until we find a leaf whose place the new value can take. *)\n  Fixpoint insert (a: t) (tr: tree) : tree :=\n    match tr with\n    | Leaf => Singleton a\n    | Node v lt rt =>\n      match compare a v with\n      | Lt => Node v (insert a lt) rt\n      | Eq => tr\n      | Gt => Node v lt (insert a rt)\n      end\n    end.\n\n  (* Helper functions for [delete] below. The *main task* in this pset\n     is to understand, specify, and prove these helpers. *)\n  Fixpoint rightmost (tr: tree) : option t :=\n    match tr with\n    | Leaf => None\n    | Node v _ rt =>\n      match rightmost rt with\n      | None => Some v\n      | r => r\n      end\n    end.\n  Definition is_leaf (tr : tree) : bool :=\n    match tr with Leaf => true | _ => false end.\n  Fixpoint delete_rightmost (tr: tree) : tree :=\n    match tr with\n    | Leaf => Leaf\n    | Node v lt rt =>\n      if is_leaf rt\n      then lt\n      else Node v lt (delete_rightmost rt)\n    end.\n  Definition merge_ordered lt rt :=\n    match rightmost lt with\n    | Some rv => Node rv (delete_rightmost lt) rt\n    | None => rt\n    end.\n\n  (* [delete] searches for an element by its value and removes it if it is found.\n     Removing an element from a leaf is degenerate (nothing to do), and\n     removing the value from a node with no other children (both Leaf) can be done\n     by replacing the node itself with a Leaf. Deleting a non-leaf node is\n     substantially trickier because the type of [tree] does not allow for a Node\n     with two subtrees but no value -- merging two trees is nontrivial. The\n     implementation here removes the value anyway and then moves the rightmost\n     node of the left subtree up to replace the removed value. This is equivalent\n     to using rotations to move the value to be removed into leaf position and\n     removing it there. *)\n  Fixpoint delete (a: t) (tr: tree) : tree :=\n    match tr with\n    | Leaf => Leaf\n    | Node v lt rt =>\n      match compare a v with\n      | Lt => Node v (delete a lt) rt\n      | Eq => merge_ordered lt rt\n      | Gt => Node v lt (delete a rt)\n      end\n    end.\n\n  (* Here is a lemma that you will almost definitely want to use. *)\n  Example bst_iff : forall tr P Q, bst tr P -> (forall x, P x <-> Q x) -> bst tr Q.\n  Proof.\n    induct tr; simplify.\n    { rewrite <- H0. apply H with (x:=x). }\n    rewrite H0 in H.\n    propositional.\n    { apply IHtr1 with (P:=(fun x : t => (fun d => P x /\\ x < d) d));\n        propositional; cycle 1.\n      { rewrite H0; trivial. }\n      { rewrite <-H0; trivial. } }\n    { apply IHtr2 with (P:=(fun x : t => (fun d => P x /\\ d < x) d));\n      propositional; cycle 2.\n      { rewrite <-H0; trivial. }\n      { rewrite H0; trivial. } }\n  Qed.\n\n  (* You may want to call these tactics to use the previous lemma. *)\n  (* They are just a means to save some typing of [apply ... with]. *)\n  Ltac use_bst_iff known_bst :=\n    lazymatch type of known_bst with\n    | bst ?tree2 ?set2 =>\n        lazymatch goal with\n        | |- bst ?tree1 ?set1 =>\n            apply bst_iff with (P:=set2) (Q := set1);\n            lazymatch goal with\n            |- bst tree2 set2 => apply known_bst\n            | _ => idtac\n            end\n        end\n    end.\n\n  Ltac use_bst_iff_assumption :=\n    match goal with\n    | H : bst ?t _ |- bst ?t _ =>\n      use_bst_iff H\n    end.\n\n  (* If you are comfortable with it, [eapply bst_iff] followed by careful\n   * application of other [bst] facts (e.g., inductive hypotheses) can\n   * save typing in some places where this tactic does not apply, though\n   * keep in mind that forcing an incorrect choice for a ?unification\n   * variable can make the goal false. *)\n\n  (* It may also be useful to know that you can switch to proving [False] by\n   * calling [exfalso]. This, for example, enables you to apply lemmas that end in\n   * [-> False]. Of course, only do this if the hypotheses are contradictory. *)\n\n  (* Other tactics used in our solution: apply, apply with, apply with in\n   * (including multiple \"with\" clauses like in [use_bst_iff]), cases, propositional,\n     linear_arithmetic, simplify, trivial, try, induct, equality, rewrite, assert. *)\n\n  (* Warm-up exercise: rebalancing rotations *)\n\n  (* Transcribe and prove one of the two rotations shown in [rotation1.svg] and [rotation2.svg].\n     The AA-tree rebalancing algorithm applies these only if the annotations of relevant\n     subtrees are in violation of a performance-critical invariant, but the rotations\n     themselves are correct regardless. (These are straight from\n     https://en.wikipedia.org/wiki/AA_tree#Balancing_rotations.) *)\n  (* Each one can be written as a simple non-recursive definition\n     containing two \"match\" expressions that returns the original\n     tree in cases where the expected structure is not present. *)\n\n  Definition rotate (T : tree) : tree.\n  Admitted.\n\n  Lemma bst_rotate T s (H : bst T s) : bst (rotate T) s.\n  Admitted.\n\n  (* There is a hint on the class website that completely gives away the proofs\n   * of these rotations. We recommend you study that code after completing this\n   * exercise to see how we did it, maybe picking up a trick or two to use below. *)\n\n  Lemma bst_insert : forall tr s a, bst tr s ->\n    bst (insert a tr) (fun x => s x \\/ x = a).\n  Proof.\n  Admitted.\n\n  (* To prove [bst_delete], you will need to write specifications for its helper\n     functions, find suitable statements for proving correctness by induction, and use\n     proofs of some helper functions in proofs of other helper functions. The hints\n     on the course website provide examples and guidance but no longer ready-to-prove\n     lemma statements. For time-planning purposes: you are not halfway done yet.\n     (The Sig file also has a rough point allocation between problems.)\n\n     It is up to you whether to use one lemma per function, multiple lemmas per\n     function, or (when applicable) one lemma per multiple functions. However,\n     the lemmas you prove about one function need to specify everything a caller\n     would need to know about this function. *)\n\n  Lemma bst_delete : forall tr s a, bst tr s ->\n    bst (delete a tr) (fun x => s x /\\ x <> a).\n  Admitted.\n\n  (* Great job! Now you have proven all tree-structure-manipulating operations\n     necessary to implement a balanced binary search tree. Rebalancing heuristics\n     that achieve worst-case-logarithmic running time maintain annotations on\n     nodes of the tree (and decide to rebalance based on these). The implementation\n     here omits them, but as the rotation operations are correct regardless of\n     the annotations, any way of calling them from heuristic code would result in a\n     functionally correct binary tree. *)\nEnd Impl.\n\nModule ImplCorrect : Pset4Sig.S := Impl.\n\n(* Authors:\n * Joonwon Choi\n * Adam Chlipala\n * Benjamin Sherman\n * Andres Erbsen\n *)\n", "meta": {"author": "mit-frap", "repo": "spring21", "sha": "20ecdeccfda50653abcdeb253dfc8118099f8c40", "save_path": "github-repos/coq/mit-frap-spring21", "path": "github-repos/coq/mit-frap-spring21/spring21-20ecdeccfda50653abcdeb253dfc8118099f8c40/pset04_BSTs/Pset4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7255225958040465}}
{"text": "(** * Sort: Insertion Sort *)\n\n(** Sorting can be done in expected O(N log N) time by various\n    algorithms (quicksort, mergesort, heapsort, etc.).  But for\n    smallish inputs, a simple quadratic-time algorithm such as\n    insertion sort can actually be faster.  It's certainly easier to\n    implement -- and to verify. *)\n\n(** If you don't recall insertion sort or haven't seen it in\n    awhile, see Wikipedia or read any standard textbook; for example:\n\n    - Sections 2.0 and 2.1 of _Algorithms, Fourth Edition_, by\n      Sedgewick and Wayne, Addison Wesley 2011; or\n\n    - Section 2.1 of _Introduction to Algorithms, 3rd Edition_, by\n      Cormen, Leiserson, and Rivest, MIT Press 2009. *)\n\nFrom VFA Require Import Perm.\n\n(* ################################################################# *)\n(** * The Insertion-Sort Program *)\n\n(** Insertion sort is usually presented as an imperative program\n    operating on arrays.  But it works just as well as a functional\n    program operating on linked lists. *)\n\n(* [insert i l] inserts [i] into its sorted place in list [l].\n   Precondition: [l] is sorted. *)\nFixpoint insert (i : nat) (l : list nat) :=\n  match l with\n  | [] => [i]\n  | h :: t => if i <=? h then i :: h :: t else h :: insert i t\n  end.\n\nFixpoint sort (l : list nat) : list nat :=\n  match l with\n  | [] => []\n  | h :: t => insert h (sort t)\n  end.\n\nExample sort_pi :\n  sort [3;1;4;1;5;9;2;6;5;3;5]\n  = [1;1;2;3;3;4;5;5;5;6;9].\nProof. simpl. reflexivity. Qed.\n\n\n(** We won't analyze or prove anything about the efficiency of\n    [sort]. Instead, we will verify its correctness: that it produces\n    the correct output for a given input. *)\n\n(* ################################################################# *)\n(** * Specification of Correctness *)\n\n(** A sorting algorithm must rearrange the elements into a list\n    that is totally ordered. There are many ways we might express that\n    idea formally in Coq.  One is with an inductively-defined\n    relatio that says: *)\n\n(** - The empty list is sorted.\n\n    - Any single-element list is sorted.\n\n    - For any two adjacent elements, they must be in the proper order. *)\n\nInductive sorted: list nat -> Prop :=\n| sorted_nil:\n    sorted []\n| sorted_1: forall x,\n    sorted [x]\n| sorted_cons: forall x y l,\n    x <= y -> sorted (y :: l) -> sorted (x :: y :: l).\n\nHint Constructors sorted.\n\n(** This definition might not be the most obvious. Another definition,\n    perhaps more familiar, might be: for any two elements of the list\n    (regardless of whether they are adjacent), they should be in the\n    proper order.  Let's try formalizing that.\n\n    We can think in terms of indices into a list [lst], and say: for\n    any valid indices [i] and [j], if [i < j] then [index lst i <=\n    index lst j], where [index lst n] means the element of [lst] at\n    index [n].  Unfortunately, formalizing this idea becomes messy,\n    because any Coq implementing [index] must be total: it must return\n    some result even if the index is out of range for the list.\n    The Coq standard library contains two such functions: *)\n\nCheck nth : forall A : Type, nat -> list A -> A -> A.\nCheck nth_error : forall A : Type, list A -> nat -> option A.\n\n(** These two functions ensure totality in different ways:\n\n    - [nth] takes an additional argument of type [A] --a _default_\n      value-- to be returned if the index is out of range, whereas\n\n    - [nth_error] returns [Some v] if the index is in range and [None]\n      --an error-- otherwise.\n\n    If we use [nth], we must ensure that indices are in range: *)\n\nDefinition sorted'' (al: list nat) := forall i j,\n    i < j < length al ->\n    nth i al 0 <= nth j al 0.\n\n(** The choice of default value, here 0, is unimportant, because it\n    will never be returned for the [i] and [j] we pass.\n\n    If we use [nth_error], we must add additional antecedents: *)\n\nDefinition sorted' (al: list nat) := forall i j iv jv,\n    i < j ->\n    nth_error al i = Some iv ->\n    nth_error al j = Some jv ->\n    iv <= jv.\n\n(** Here, the validity of [i] and [j] are implicit in the fact that we\n    get [Some] results back from each call to [nth_error].\n\n    All three definitions of sortedness we have given are reasonable.\n    In practice, [sorted'] is easier to work with than [sorted'']\n    because it doesn't need to mention the [length] function. And\n    [sorted] is easier than either.  *)\n\n(** Using [sorted], we specify what it means to be a correct sorting\n    algorthm: *)\n\nDefinition is_a_sorting_algorithm (f: list nat -> list nat) := forall al,\n    Permutation al (f al) /\\ sorted (f al).\n\n(** Function [f] is a correct sorting algorithm if [f al] is\n    [sorted] and is a permutation of its input. *)\n\n(* ################################################################# *)\n(** * Proof of Correctness *)\n\n(** In the following exercises, you will prove the correctness of\n    insertion sort. *)\n\n(** **** Exercise: 3 stars, standard (insert_sorted)  *)\n\n(* Prove that insertion maintains sortedness. Make use of tactic\n   [bdestruct], defined in [Perm]. *)\n\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (insert a l).\nProof.\n  intros a l S. induction S; simpl.\n  (* SOLUTION: *)\n  - constructor.\n  - bdestruct (x >=? a); auto.\n    constructor; auto. omega.\n  - bdestruct (x >=? a); auto.\n    bdestruct (y >=? a).\n    + constructor; auto. omega.\n    + constructor; auto.\n      simpl in IHS. bdestruct (y >=? a); auto. omega.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (sort_sorted)  *)\n\n(** Using [insert_sorted], prove that insertion sort makes a list\n    sorted. *)\n\nTheorem sort_sorted: forall l, sorted (sort l).\nProof.\n(* SOLUTION: *)\n  induction l; simpl; auto.\n  apply insert_sorted. auto.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (insert_perm)  *)\n\n(** The following lemma will be useful soon as a helper. Take\n    advantage of helpful theorems from the [Permutation] library. *)\n\nLemma insert_perm: forall x l,\n    Permutation (x :: l) (insert x l).\nProof.\n  (* SOLUTION: *)\n  induction l; simpl.\n  - apply Permutation_refl.\n  - destruct (x <=? a).\n    + apply Permutation_refl.\n    + apply perm_trans with (a :: x :: l).\n      * apply perm_swap.\n      * apply perm_skip. assumption.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (sort_perm)  *)\n\n(** Prove that [sort] is a permutation, using [insert_perm]. *)\n\nTheorem sort_perm: forall l, Permutation l (sort l).\nProof.\n(* SOLUTION: *)\n  induction l.\n  - apply Permutation_refl.\n  - simpl. apply Permutation_trans with (a :: (sort l)).\n    + apply perm_skip. assumption.\n    + apply insert_perm.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (insertion_sort_correct)  *)\n\n(** Finish the proof of correctness! *)\n\nTheorem insertion_sort_correct:\n    is_a_sorting_algorithm sort.\nProof.\n  (* SOLUTION: *)\n  split.\n  - apply sort_perm.\n  - apply sort_sorted.\nQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Validating the Specification (Advanced) *)\n\n(** You can prove that a program satisfies a specification, but how\n    can you prove you have the right specification?  Actually, you\n    cannot.  The specification is an informal requirement in your\n    mind.  As Alan Perlis quipped, \"One can't proceed from the\n    informal to the formal by formal means.\"\n\n    But one way to build confidence in a specification is to state it\n    in two different ways, then prove they are equivalent. *)\n\n(** **** Exercise: 4 stars, advanced (sorted_sorted')  *)\nLemma sorted_sorted': forall al, sorted al -> sorted' al.\n\n(** Hint: Instead of doing induction on the list [al], do induction on\n    the sortedness of [al]. This proof is a bit tricky, so you may\n    have to think about how to approach it, and try out one or two\n    different ideas.*)\nProof.\n(* SOLUTION: *)\n  unfold sorted'; induction 1; intros i j iv jv LT Hi Hj.\n  - destruct i; inv Hi.\n  - destruct j as [|j'].\n    + omega.\n    + destruct j'; inv Hj.\n  - destruct j as [|j'].\n    + omega.\n    + destruct i as [|i'].\n      * inv Hi.\n        destruct j' as [|j''].\n        -- inv Hj.  auto.\n        -- apply le_trans with y. auto.\n            eapply (IHsorted 0 (S j'')). omega. auto. auto.\n      * apply (IHsorted i' j'). omega. auto. auto. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (sorted'_sorted)  *)\nLemma sorted'_sorted : forall al, sorted' al -> sorted al.\nProof.\n(** Here, you can't do induction on the sortedness of the list,\n    because [sorted'] is not an inductive predicate. But the proof\n    is not hard. *)\n(* SOLUTION: *)\n  unfold sorted'. induction al; intros.\n  - constructor.\n  - destruct al.\n    + constructor.\n    + constructor.\n      * eapply (H 0 1). omega. auto. auto.\n      * apply IHal. intros.\n        apply (H (S i) (S j)). omega. auto. auto. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proving Correctness from the Alternative Spec (Optional) *)\n\n(** Depending on how you write the specification of a program, it can\n    be harder or easier to prove correctness.  We saw that predicates\n    [sorted] and [sorted'] are equivalent.  It is significantly\n    harder, though, to prove correctness of insertion sort directly\n    from [sorted'].\n\n    Give it a try!  The best proof we know of makes essential use of\n    the auxiliary lemma [nth_default_insert], so you may want to prove\n    that first.  And some other auxiliary lemmas may be needed too.\n    But maybe you will find a simpler appraoch!\n\n    DO NOT USE [sorted_sorted'], [sorted'_sorted], [insert_sorted], or\n    [sort_sorted] in these proofs.  That would defeat the purpose! *)\n\n(** **** Exercise: 5 stars, standard, optional (insert_sorted')  *)\n\nLemma nth_error_insert : forall l a i iv,\n    nth_error (insert a l) i = Some iv ->\n    a = iv \\/ exists i', nth_error l i' = Some iv.\nProof.\n(* SOLUTION: *)\n induction l; intros.\n - inv H. destruct i as [|i'].\n   + inv H1. auto.\n   + inv H1. destruct i'; inv H0.\n - simpl in H.\n   bdestruct (a0 <=? a).\n   + destruct i as [|i'].\n     * inv H. auto.\n     * simpl in H. right. eauto.\n   + destruct i as [|i'].\n     * right. exists 0. auto.\n     * simpl in H. destruct (IHl _ _ _ H) as [P|[i'' P]].\n       -- auto.\n       -- right; exists (S i''); auto. Qed.\n\nLemma insert_length: forall a l, length (insert a l) = S(length l).\nProof.\n  intros a l. induction l.\n  - auto.\n  - simpl. destruct (a <=? a0).\n    + auto.\n    + simpl. rewrite IHl.  auto. Qed.\n\nLemma insert_sorted':\n  forall a l, sorted' l -> sorted' (insert a l).\nProof.\n(* SOLUTION: *)\n  intros a l. generalize dependent a.\n  induction l; intros a0 H i j iv jv LT Hi Hj.\n  - simpl in Hi, Hj.\n    destruct j as [|j'].\n    + inversion LT.\n    + inversion Hj as [C].\n      destruct j'; inversion C.\n  - simpl in Hi, Hj.\n    destruct j as [|j'].  omega.\n    bdestruct (a0 <=? a).\n    + destruct i as [|i'].\n      * inv Hi.\n        apply le_trans with a. auto.\n        simpl in Hj.\n        destruct j' as [|j''].\n        -- inv Hj. omega.\n        -- apply (H 0 (S j'')); auto; omega.\n      * apply (H i' j'); auto; omega.\n    + destruct i as [|i'].\n      * inv Hi. simpl in Hj.\n        destruct (nth_error_insert _ _ _ _ Hj) as [P | [i' P]].\n        -- omega.\n        -- apply (H 0 (S i')); auto; omega.\n      * eapply IHl with (a := a0) (i := i') (j:= j'); auto; try omega.\n        intros i j iv0 jv0 LT0 Hi0 Hj0.\n        apply (H (S i) (S j)); auto; omega.\nQed.\n(** [] *)\n\nTheorem sort_sorted': forall l, sorted' (sort l).\nProof.\n  induction l.\n  - unfold sorted'. intros. destruct i; inv H0.\n  - simpl. apply insert_sorted'. auto.\nQed.\n\n(** If you complete the proofs above, you will note that the proof of\n    [insert_sorted] is relatively easy compared to the proof of\n    [insert_sorted'], even though [sorted al <-> sorted' al].  So,\n    suppose someone asked you to prove [sort_sorted'].  Instead of\n    proving it directly, it would be much easier to design predicate\n    [sorted], then prove [sort_sorted] and [sorted_sorted'].\n\n    The moral of the story is therefore: _Different formulations of\n    the functional specification can lead to great differences in the\n    difficulty of the correctness proofs_. *)\n\n\n(* Mon May 11 23:22:55 EDT 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/finalsrc/Sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.7255225874948623}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Problem(s):\n    Simple Semi-Thue System 01 Rewriting (SSTS01)\n*)\n\n(*\n  Literature:\n  [1] Dudenhefner, Andrej, and Jakob Rehof. \n      \"Undecidability of Intersection Type Inhabitation at Rank 3 and its Formalization.\" \n      Fundamenta Informaticae 170.1-3 (2019): 93-110.\n*)\n\nRequire Import List Relation_Operators.\n\n(* A simple semi-Thue system consists of rules \"ab -> cd\" where a, b, c, d : nat *)\nDefinition Ssts := list ((nat * nat) * (nat * nat)).\n\n(* one-step rewriting relation \n   if (ab -> cd) in ssts, then uabv -> ucdv where u, v : list nat *)\nInductive step (ssts: Ssts) : list nat -> list nat -> Prop := \n  | step_intro {u v: list nat} {a b c d: nat} : \n      In ((a, b), (c, d)) ssts -> step ssts (u ++ a :: b :: v) (u ++ c :: d :: v).\n\n(* reflexive, transitive closure of one-step rewriting *)\nDefinition multi_step (ssts: Ssts) : list nat -> list nat -> Prop := \n  clos_refl_trans (list nat) (step ssts).\n\n(* simple semi-Thue system 01 rewriting, that is\n   for given a simple semi-Thue system, does 0^(1+n) ->> 1^(1+n) hold for some n? *)\nDefinition SSTS01 : Ssts -> Prop :=\n  fun ssts => exists n, multi_step ssts (repeat 0 (1+n)) (repeat 1 (1+n)).\n  \n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/StringRewriting/SSTS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7255189097077007}}
{"text": "Welcome to Coq ciosx:/builds/workspace/coq-8.5pl3-macos,(detached from 2290dbb) (2290dbb9c95b63e693ced647731623e64297f5c8)\n\nCoq < Module Playground2.\nInteractive Module Playground2 started\n\nCoq < Require Import Arith Classical.\n[Loading ML file z_syntax_plugin.cmxs ... done]\n[Loading ML file quote_plugin.cmxs ... done]\n[Loading ML file newring_plugin.cmxs ... done]\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n<W> Grammar extension: in [tactic:simple_tactic], some rule has been masked\n\nCoq < Fixpoint plus (n : nat) (m : nat) : nat := match n with | O => m | S n' => S (plus n' m) end.\nplus is defined\nplus is recursively defined (decreasing on 1st argument)\n\nCoq < Fixpoint mult (n m : nat) : nat := match n with | O => O | S n' => plus m (mult n' m) end.\nmult is defined\nmult is recursively defined (decreasing on 1st argument)\n\nCoq < Example test_mult1: (mult 3 3) = 9.\n1 subgoal\n  \n  ============================\n  mult 3 3 = 9\n\ntest_mult1 < Proof.\n1 subgoal\n  \n  ============================\n  mult 3 3 = 9\n\ntest_mult1 < simpl.\n1 subgoal\n  \n  ============================\n  9 = 9\n\ntest_mult1 < reflexivity.\nNo more subgoals.\n\ntest_mult1 < Qed.\nProof.\nsimpl.\nreflexivity.\n\nQed.\ntest_mult1 is defined\n\nCoq < Fixpoint minus (n m:nat) : nat := match n, m with | O , _ => O | S _ , O => n | S n', S m' => minus n' m' end.\nminus is defined\nminus is recursively defined (decreasing on 1st argument)\n\nCoq < Compute (minus 8 6).\n     = 2\n     : nat\n\nCoq < Example test_minus1: (minus 7 3) = 4.\n1 subgoal\n  \n  ============================\n  minus 7 3 = 4\n\ntest_minus1 < Proof.\n1 subgoal\n  \n  ============================\n  minus 7 3 = 4\n\ntest_minus1 < simpl.\n1 subgoal\n  \n  ============================\n  4 = 4\n\ntest_minus1 < reflexivity.\nNo more subgoals.\n\ntest_minus1 < Qed.\nProof.\nsimpl.\nreflexivity.\n\nQed.\ntest_minus1 is defined\n\nCoq < End Playground2.\nModule Playground2 is defined\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/foundations/basics006.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.8705972734445508, "lm_q1q2_score": 0.7254901349878801}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n     Aux.v                                                                                           \n                                                                                                          \n     Auxillary functions & Theorems                                              \n **********************************************************************)\nRequire Export Arith.\n\n(**************************************\n  Some properties of minus\n**************************************)\n\nTheorem minus_O : forall a b : nat, a <= b -> a - b = 0.\nintros a; elim a; simpl in |- *; auto with arith.\nintros a1 Rec b; case b; elim b; auto with arith.\nQed.\n\n\n(**************************************\n  Definitions and properties of the power for nat \n**************************************)\n\nFixpoint pow (n m: nat)  {struct m} : nat := match m with O => 1%nat | (S m1) => (n * pow n m1)%nat  end.\n\nTheorem pow_add: forall n m p, pow n (m + p) = (pow n m * pow n p)%nat.\nintros n m; elim m; simpl.\nintros p; rewrite plus_0_r; auto.\nintros m1 Rec p; rewrite Rec; auto with arith.\nQed.\n\n\nTheorem pow_pos: forall p n, (0 < p)%nat -> (0 < pow p n)%nat.\nintros p1 n H; elim n; simpl; auto with arith.\nintros n1 H1; replace 0%nat with (p1 * 0)%nat; auto with arith.\nrepeat rewrite (mult_comm p1); apply mult_lt_compat_r; auto with arith.\nQed.\n\n\nTheorem pow_monotone: forall n p q, (1 < n)%nat -> (p < q)%nat -> (pow n p < pow n q)%nat.\nintros n p1 q1 H H1; elim H1; simpl.\npattern (pow n p1) at 1; rewrite <- (mult_1_l (pow n p1)).\napply mult_lt_compat_r; auto.\napply pow_pos; auto with arith.\nintros n1 H2 H3.\napply lt_trans with (1 := H3).\npattern (pow n n1) at 1; rewrite <- (mult_1_l (pow n n1)).\napply mult_lt_compat_r; auto.\napply pow_pos; auto with arith.\nQed.\n\n(************************************\n  Definition of the divisibility for nat \n**************************************)\n\nDefinition divide a b := exists c, b = a * c.\n\n\nTheorem divide_le: forall p q, (1 < q)%nat -> divide p q -> (p <= q)%nat.\nintros p1 q1 H (x, H1); subst.\napply le_trans with (p1 * 1)%nat; auto with arith.\nrewrite mult_1_r; auto with arith.\napply mult_le_compat_l.\ncase (le_lt_or_eq 0 x); auto with arith.\nintros H2; subst; contradict H; rewrite mult_0_r; auto with arith.\nQed.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/coqprime/Coqprime/NatAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807406, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7254901175622372}}
{"text": "(** * Types: Type Systems *)\n\nRequire Import Coq.Arith.Arith.\n\nRequire Import SfLib.\nRequire Import Maps.\nRequire Import Imp.\nRequire Import Smallstep.\n\n(* INSTRUCTORS. : APT: best place I could find for these without\n   requiring new Auto *)\nHint Constructors multi.\n\n(** Our next major topic is _type systems_ -- static program\n    analyses that classify expressions according to the \"shapes\" of\n    their results.  We'll begin with a typed version of a very simple\n    language with just booleans and numbers, to introduce the basic\n    ideas of types, typing rules, and the fundamental theorems about\n    type systems: _type preservation_ and _progress_.  Then we'll move\n    on to the _simply typed lambda-calculus_, which lives at the core\n    of every modern functional programming language (including\n    Coq). *)\n\n(* ###################################################################### *)\n(** * Typed Arithmetic Expressions *)\n\n(** To motivate the discussion of type systems, let's begin as\n    usual with an extremely simple toy language.  We want it to have\n    the potential for programs \"going wrong\" because of runtime type\n    errors, so we need something a tiny bit more complex than the\n    language of constants and addition that we used in chapter\n    [Smallstep]: a single kind of data (just numbers) is too simple,\n    but just two kinds (numbers and booleans) already gives us enough\n    material to tell an interesting story.\n\n    The language definition is completely routine.  *)\n\n(* ###################################################################### *)\n(** ** Syntax *)\n\n(** Informally:\n    t ::= true\n        | false\n        | if t then t else t\n        | 0\n        | succ t\n        | pred t\n        | iszero t\n    Formally:\n*)\n\nInductive tm : Type :=\n  | ttrue : tm\n  | tfalse : tm\n  | tif : tm -> tm -> tm -> tm\n  | tzero : tm\n  | tsucc : tm -> tm\n  | tpred : tm -> tm\n  | tiszero : tm -> tm.\n\n(** _Values_ are [true], [false], and numeric values... *)\n\nInductive bvalue : tm -> Prop :=\n  | bv_true : bvalue ttrue\n  | bv_false : bvalue tfalse.\n\nInductive nvalue : tm -> Prop :=\n  | nv_zero : nvalue tzero\n  | nv_succ : forall t, nvalue t -> nvalue (tsucc t).\n\nDefinition value (t:tm) := bvalue t \\/ nvalue t.\n\nHint Constructors bvalue nvalue.\nHint Unfold value.\nHint Unfold update.\n\n(* ###################################################################### *)\n(** ** Operational Semantics *)\n\n(** Informally: *)\n(**\n                    ------------------------------                  (ST_IfTrue)\n                    if true then t1 else t2 ==> t1\n\n                   -------------------------------                 (ST_IfFalse)\n                   if false then t1 else t2 ==> t2\n\n                              t1 ==> t1'\n                      -------------------------                         (ST_If)\n                      if t1 then t2 else t3 ==>\n                        if t1' then t2 else t3\n\n                              t1 ==> t1'\n                         --------------------                         (ST_Succ)\n                         succ t1 ==> succ t1'\n\n                             ------------                         (ST_PredZero)\n                             pred 0 ==> 0\n\n                           numeric value v1\n                        ---------------------                     (ST_PredSucc)\n                        pred (succ v1) ==> v1\n\n                              t1 ==> t1'\n                         --------------------                         (ST_Pred)\n                         pred t1 ==> pred t1'\n\n                          -----------------                     (ST_IszeroZero)\n                          iszero 0 ==> true\n\n                           numeric value v1\n                      --------------------------                (ST_IszeroSucc)\n                      iszero (succ v1) ==> false\n\n                              t1 ==> t1'\n                       ------------------------                     (ST_Iszero)\n                       iszero t1 ==> iszero t1'\n*)\n\n(** Formally: *)\n\nReserved Notation \"t1 '==>' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  | ST_IfTrue : forall t1 t2,\n      (tif ttrue t1 t2) ==> t1\n  | ST_IfFalse : forall t1 t2,\n      (tif tfalse t1 t2) ==> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      (tif t1 t2 t3) ==> (tif t1' t2 t3)\n  | ST_Succ : forall t1 t1',\n      t1 ==> t1' ->\n      (tsucc t1) ==> (tsucc t1')\n  | ST_PredZero :\n      (tpred tzero) ==> tzero\n  | ST_PredSucc : forall t1,\n      nvalue t1 ->\n      (tpred (tsucc t1)) ==> t1\n  | ST_Pred : forall t1 t1',\n      t1 ==> t1' ->\n      (tpred t1) ==> (tpred t1')\n  | ST_IszeroZero :\n      (tiszero tzero) ==> ttrue\n  | ST_IszeroSucc : forall t1,\n       nvalue t1 ->\n      (tiszero (tsucc t1)) ==> tfalse\n  | ST_Iszero : forall t1 t1',\n      t1 ==> t1' ->\n      (tiszero t1) ==> (tiszero t1')\n\nwhere \"t1 '==>' t2\" := (step t1 t2).\n\nHint Constructors step.\n(** Notice that the [step] relation doesn't care about whether\n    expressions make global sense -- it just checks that the operation\n    in the _next_ reduction step is being applied to the right kinds\n    of operands.\n\n    For example, the term [succ true] (i.e., [tsucc ttrue] in the\n    formal syntax) cannot take a step, but the almost as obviously\n    nonsensical term\n       succ (if true then true else true)\n    can take a step (once, before becoming stuck). *)\n\n(* ###################################################################### *)\n(** ** Normal Forms and Values *)\n\n(** The first interesting thing about the [step] relation in this\n    language is that the strong progress theorem from the Smallstep\n    chapter fails!  That is, there are terms that are normal\n    forms (they can't take a step) but not values (because we have not\n    included them in our definition of possible \"results of\n    evaluation\").  Such terms are _stuck_. *)\n\nNotation step_normal_form := (normal_form step).\n\nDefinition stuck (t:tm) : Prop :=\n  step_normal_form t /\\ ~ value t.\n\nHint Unfold stuck.\n\n(** **** Exercise: 2 stars (some_term_is_stuck)  *)\nExample some_term_is_stuck :\n  exists t, stuck t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** However, although values and normal forms are not the same in this\n    language, the former set is included in the latter.  This is\n    important because it shows we did not accidentally define things\n    so that some value could still take a step. *)\n\n(** **** Exercise: 3 stars, advanced (value_is_nf)  *)\n(** Hint: You will reach a point in this proof where you need to\n    use an induction to reason about a term that is known to be a\n    numeric value.  This induction can be performed either over the\n    term itself or over the evidence that it is a numeric value.  The\n    proof goes through in either case, but you will find that one way\n    is quite a bit shorter than the other.  For the sake of the\n    exercise, try to complete the proof both ways. *)\n\nLemma value_is_nf : forall t,\n  value t -> step_normal_form t.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars, optional (step_deterministic)  *)\n(** Using [value_is_nf], we can show that the [step] relation is\n    also deterministic... *)\n\nTheorem step_deterministic:\n  deterministic step.\nProof with eauto.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n\n(* ###################################################################### *)\n(** ** Typing *)\n\n(** The next critical observation about this language is that,\n    although there are stuck terms, they are all \"nonsensical\", mixing\n    booleans and numbers in a way that we don't even _want_ to have a\n    meaning.  We can easily exclude such ill-typed terms by defining a\n    _typing relation_ that relates terms to the types (either numeric\n    or boolean) of their final results.  *)\n\nInductive ty : Type :=\n  | TBool : ty\n  | TNat : ty.\n\n(** In informal notation, the typing relation is often written\n    [|- t \\in T], pronounced \"[t] has type [T].\"  The [|-] symbol is\n    called a \"turnstile\".  (Below, we're going to see richer typing\n    relations where an additional \"context\" argument is written to the\n    left of the turnstile.  Here, the context is always empty.) *)\n(** \n                           ----------------                            (T_True)\n                           |- true \\in Bool\n\n                          -----------------                           (T_False)\n                          |- false \\in Bool\n\n             |- t1 \\in Bool    |- t2 \\in T    |- t3 \\in T\n             --------------------------------------------                (T_If)\n                    |- if t1 then t2 else t3 \\in T\n\n                             ------------                              (T_Zero)\n                             |- 0 \\in Nat\n\n                            |- t1 \\in Nat\n                          ------------------                           (T_Succ)\n                          |- succ t1 \\in Nat\n\n                            |- t1 \\in Nat\n                          ------------------                           (T_Pred)\n                          |- pred t1 \\in Nat\n\n                            |- t1 \\in Nat\n                        ---------------------                        (T_IsZero)\n                        |- iszero t1 \\in Bool\n*)\n\nReserved Notation \"'|-' t '\\in' T\" (at level 40).\n\nInductive has_type : tm -> ty -> Prop :=\n  | T_True :\n       |- ttrue \\in TBool\n  | T_False :\n       |- tfalse \\in TBool\n  | T_If : forall t1 t2 t3 T,\n       |- t1 \\in TBool ->\n       |- t2 \\in T ->\n       |- t3 \\in T ->\n       |- tif t1 t2 t3 \\in T\n  | T_Zero :\n       |- tzero \\in TNat\n  | T_Succ : forall t1,\n       |- t1 \\in TNat ->\n       |- tsucc t1 \\in TNat\n  | T_Pred : forall t1,\n       |- t1 \\in TNat ->\n       |- tpred t1 \\in TNat\n  | T_Iszero : forall t1,\n       |- t1 \\in TNat ->\n       |- tiszero t1 \\in TBool\n\nwhere \"'|-' t '\\in' T\" := (has_type t T).\n\nHint Constructors has_type.\n\n(* ###################################################################### *)\n(** *** Examples *)\n\n(** It's important to realize that the typing relation is a\n    _conservative_ (or _static_) approximation: it does not calculate\n    the type of the normal form of a term. *)\n\nExample has_type_1 :\n  |- tif tfalse tzero (tsucc tzero) \\in TNat.\nProof.\n  apply T_If.\n    apply T_False.\n    apply T_Zero.\n    apply T_Succ.\n      apply T_Zero.\nQed.\n\n(** (Since we've included all the constructors of the typing relation\n    in the hint database, the [auto] tactic can actually find this\n    proof automatically.) *)\n\nExample has_type_not :\n  ~ (|- tif tfalse tzero ttrue \\in TBool).\nProof.\n  intros Contra. solve by inversion 2.  Qed.\n\n(** **** Exercise: 1 star, optional (succ_hastype_nat__hastype_nat)  *)\nExample succ_hastype_nat__hastype_nat : forall t,\n  |- tsucc t \\in TNat ->\n  |- t \\in TNat.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Canonical forms *)\n\n(** The following two lemmas capture the basic property that defines\n    the shape of well-typed values.  They say that the definition of value\n    and the typing relation agree. *)\n\nLemma bool_canonical : forall t,\n  |- t \\in TBool -> value t -> bvalue t.\nProof.\n  intros t HT HV.\n  inversion HV; auto.\n\n  induction H; inversion HT; auto.\nQed.\n\nLemma nat_canonical : forall t,\n  |- t \\in TNat -> value t -> nvalue t.\nProof.\n  intros t HT HV.\n  inversion HV.\n  inversion H; subst; inversion HT.\n\n  auto.\nQed.\n\n(* ###################################################################### *)\n(** ** Progress *)\n\n(** The typing relation enjoys two critical properties.  The first is\n    that well-typed normal forms are values (i.e., not stuck). *)\n\nTheorem progress : forall t T,\n  |- t \\in T ->\n  value t \\/ exists t', t ==> t'.\n\n(** **** Exercise: 3 stars (finish_progress)  *)\n(** Complete the formal proof of the [progress] property.  (Make sure\n    you understand the informal proof fragment in the following\n    exercise before starting -- this will save you a lot of time.) *)\n\nProof with auto.\n  intros t T HT.\n  induction HT...\n  (* The cases that were obviously values, like T_True and\n     T_False, were eliminated immediately by auto *)\n  - (* T_If *)\n    right. inversion IHHT1; clear IHHT1.\n    + (* t1 is a value *)\n    apply (bool_canonical t1 HT1) in H.\n    inversion H; subst; clear H.\n      exists t2...\n      exists t3...\n    + (* t1 can take a step *)\n      inversion H as [t1' H1].\n      exists (tif t1' t2 t3)...\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (finish_progress_informal)  *)\n(** Complete the corresponding informal proof: *)\n\n(** _Theorem_: If [|- t \\in T], then either [t] is a value or else\n    [t ==> t'] for some [t']. *)\n\n(** _Proof_: By induction on a derivation of [|- t \\in T].\n\n      - If the last rule in the derivation is [T_If], then [t = if t1\n        then t2 else t3], with [|- t1 \\in Bool], [|- t2 \\in T] and [|- t3\n        \\in T].  By the IH, either [t1] is a value or else [t1] can step\n        to some [t1'].\n\n            - If [t1] is a value, then by the canonical forms lemmas\n              and the fact that [|- t1 \\in Bool] we have that [t1]\n              is a [bvalue] -- i.e., it is either [true] or [false].\n              If [t1 = true], then [t] steps to [t2] by [ST_IfTrue],\n              while if [t1 = false], then [t] steps to [t3] by\n              [ST_IfFalse].  Either way, [t] can step, which is what\n              we wanted to show.\n\n            - If [t1] itself can take a step, then, by [ST_If], so can\n              [t].\n\n    (* FILL IN HERE *)\n[] *)\n\n(** This is more interesting than the strong progress theorem that we\n    saw in the Smallstep chapter, where _all_ normal forms were\n    values.  Here, a term can be stuck, but only if it is ill\n    typed. *)\n\n(** **** Exercise: 1 star (step_review)  *)\n(** Quick review.  Answer _true_ or _false_.  In this language...\n      - Every well-typed normal form is a value.\n\n      - Every value is a normal form.\n\n      - The single-step evaluation relation is\n        a partial function (i.e., it is deterministic).\n\n      - The single-step evaluation relation is a _total_ function.\n\n*)\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Type Preservation *)\n\n(** The second critical property of typing is that, when a well-typed\n    term takes a step, the result is also a well-typed term.\n\n    This theorem is often called the _subject reduction_ property,\n    because it tells us what happens when the \"subject\" of the typing\n    relation is reduced.  This terminology comes from thinking of\n    typing statements as sentences, where the term is the subject and\n    the type is the predicate. *)\n\nTheorem preservation : forall t t' T,\n  |- t \\in T ->\n  t ==> t' ->\n  |- t' \\in T.\n\n(** **** Exercise: 2 stars (finish_preservation)  *)\n(** Complete the formal proof of the [preservation] property.  (Again,\n    make sure you understand the informal proof fragment in the\n    following exercise first.) *)\n\nProof with auto.\n  intros t t' T HT HE.\n  generalize dependent t'.\n  induction HT;\n         (* every case needs to introduce a couple of things *)\n         intros t' HE;\n         (* and we can deal with several impossible\n            cases all at once *)\n         try (solve by inversion).\n    - (* T_If *) inversion HE; subst; clear HE.\n      + (* ST_IFTrue *) assumption.\n      + (* ST_IfFalse *) assumption.\n      + (* ST_If *) apply T_If; try assumption.\n        apply IHHT1; assumption.\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (finish_preservation_informal)  *)\n(** Complete the following proof: *)\n\n(** _Theorem_: If [|- t \\in T] and [t ==> t'], then [|- t' \\in T]. *)\n\n(** _Proof_: By induction on a derivation of [|- t \\in T].\n\n      - If the last rule in the derivation is [T_If], then [t = if t1\n        then t2 else t3], with [|- t1 \\in Bool], [|- t2 \\in T] and [|- t3\n        \\in T].\n\n        Inspecting the rules for the small-step reduction relation and\n        remembering that [t] has the form [if ...], we see that the\n        only ones that could have been used to prove [t ==> t'] are\n        [ST_IfTrue], [ST_IfFalse], or [ST_If].\n\n           - If the last rule was [ST_IfTrue], then [t' = t2].  But we\n             know that [|- t2 \\in T], so we are done.\n\n           - If the last rule was [ST_IfFalse], then [t' = t3].  But we\n             know that [|- t3 \\in T], so we are done.\n\n           - If the last rule was [ST_If], then [t' = if t1' then t2\n             else t3], where [t1 ==> t1'].  We know [|- t1 \\in Bool] so,\n             by the IH, [|- t1' \\in Bool].  The [T_If] rule then gives us\n             [|- if t1' then t2 else t3 \\in T], as required.\n\n    (* FILL IN HERE *)\n[] *)\n\n(** **** Exercise: 3 stars (preservation_alternate_proof)  *)\n(** Now prove the same property again by induction on the\n    _evaluation_ derivation instead of on the typing derivation.\n    Begin by carefully reading and thinking about the first few\n    lines of the above proof to make sure you understand what\n    each one is doing.  The set-up for this proof is similar, but\n    not exactly the same. *)\n\nTheorem preservation' : forall t t' T,\n  |- t \\in T ->\n  t ==> t' ->\n  |- t' \\in T.\nProof with eauto.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Type Soundness *)\n\n(** Putting progress and preservation together, we can see that a\n    well-typed term can _never_ reach a stuck state.  *)\n\nDefinition multistep := (multi step).\nNotation \"t1 '==>*' t2\" := (multistep t1 t2) (at level 40).\n\nCorollary soundness : forall t t' T,\n  |- t \\in T ->\n  t ==>* t' ->\n  ~(stuck t').\nProof.\n  intros t t' T HT P. induction P; intros [R S].\n  destruct (progress x T HT); auto.\n  apply IHP.  apply (preservation x y T HT H).\n  unfold stuck. split; auto.   Qed.\n\n\n(* ###################################################################### *)\n(** * Aside: the [normalize] Tactic *)\n\n(** When experimenting with definitions of programming languages in\n    Coq, we often want to see what a particular concrete term steps\n    to -- i.e., we want to find proofs for goals of the form [t ==>*\n    t'], where [t] is a completely concrete term and [t'] is unknown.\n    These proofs are simple but repetitive to do by hand. Consider for\n    example reducing an arithmetic expression using the small-step\n    relation [astep]. *)\n\n\nDefinition amultistep st := multi (astep st).\nNotation \" t '/' st '==>a*' t' \" := (amultistep st t t')\n  (at level 40, st at level 39).\n\nExample astep_example1 :\n  (APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state\n  ==>a* (ANum 15).\nProof.\n  apply multi_step with (APlus (ANum 3) (ANum 12)).\n    apply AS_Plus2.\n      apply av_num.\n      apply AS_Mult.\n  apply multi_step with (ANum 15).\n    apply AS_Plus.\n  apply multi_refl.\nQed.\n\n(** We repeatedly apply [multi_step] until we get to a normal\n    form. The proofs that the intermediate steps are possible are\n    simple enough that [auto], with appropriate hints, can solve\n    them. *)\n\nHint Constructors astep aval.\nExample astep_example1' :\n  (APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state\n  ==>a* (ANum 15).\nProof.\n  eapply multi_step. auto. simpl.\n  eapply multi_step. auto. simpl.\n  apply multi_refl.\nQed.\n\n\n(** The following custom [Tactic Notation] definition captures this\n    pattern.  In addition, before each [multi_step] we print out the\n    current goal, so that the user can follow how the term is being\n    evaluated. *)\n\nTactic Notation \"print_goal\" := match goal with |- ?x => idtac x end.\nTactic Notation \"normalize\" :=\n   repeat (print_goal; eapply multi_step ;\n             [ (eauto 10; fail) | (instantiate; simpl)]);\n   apply multi_refl.\n\n\nExample astep_example1'' :\n  (APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state\n  ==>a* (ANum 15).\nProof.\n  normalize.\n  (* At this point in the proof script, the Coq response shows\n     a trace of how the expression evaluated.\n\n   (APlus (ANum 3) (AMult (ANum 3) (ANum 4)) / empty_state ==>a* ANum 15)\n   (multi (astep empty_state) (APlus (ANum 3) (ANum 12)) (ANum 15))\n   (multi (astep empty_state) (ANum 15) (ANum 15))\n*)\nQed.\n\n(** The [normalize] tactic also provides a simple way to calculate\n    what the normal form of a term is, by proving a goal with an\n    existential variable in it. *)\n\nExample astep_example1''' : exists e',\n  (APlus (ANum 3) (AMult (ANum 3) (ANum 4))) / empty_state\n  ==>a* e'.\nProof.\n  eapply ex_intro. normalize.\n\n(* This time, the trace will be:\n\n    (APlus (ANum 3) (AMult (ANum 3) (ANum 4)) / empty_state ==>a* ??)\n    (multi (astep empty_state) (APlus (ANum 3) (ANum 12)) ??)\n    (multi (astep empty_state) (ANum 15) ??)\n\n   where ?? is the variable ``guessed'' by eapply.\n*)\nQed.\n\n\n(** **** Exercise: 1 star (normalize_ex)  *)\nTheorem normalize_ex : exists e',\n  (AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state\n  ==>a* e'.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 1 star, optional (normalize_ex')  *)\n(** For comparison, prove it using [apply] instead of [eapply]. *)\n\nTheorem normalize_ex' : exists e',\n  (AMult (ANum 3) (AMult (ANum 2) (ANum 1))) / empty_state\n  ==>a* e'.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################################### *)\n(** ** Additional Exercises *)\n\n(** **** Exercise: 2 stars, recommended (subject_expansion)  *)\n(** Having seen the subject reduction property, it is reasonable to\n    wonder whether the opposity property -- subject _expansion_ --\n    also holds.  That is, is it always the case that, if [t ==> t']\n    and [|- t' \\in T], then [|- t \\in T]?  If so, prove it.  If\n    not, give a counter-example.  (You do not need to prove your\n    counter-example in Coq, but feel free to do so if you like.)\n\n    (* FILL IN HERE *)\n[] *)\n\n\n\n\n(** **** Exercise: 2 stars (variation1)  *)\n(** Suppose, that we add this new rule to the typing relation:\n      | T_SuccBool : forall t,\n           |- t \\in TBool ->\n           |- tsucc t \\in TBool\n   Which of the following properties remain true in the presence of\n   this rule?  For each one, write either \"remains true\" or\n   else \"becomes false.\" If a property becomes false, give a\n   counterexample.\n      - Determinism of [step]\n\n      - Progress\n\n      - Preservation\n\n[] *)\n\n(** **** Exercise: 2 stars (variation2)  *)\n(** Suppose, instead, that we add this new rule to the [step] relation:\n      | ST_Funny1 : forall t2 t3,\n           (tif ttrue t2 t3) ==> t3\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (variation3)  *)\n(** Suppose instead that we add this rule:\n      | ST_Funny2 : forall t1 t2 t2' t3,\n           t2 ==> t2' ->\n           (tif t1 t2 t3) ==> (tif t1 t2' t3)\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (variation4)  *)\n(** Suppose instead that we add this rule:\n      | ST_Funny3 :\n          (tpred tfalse) ==> (tpred (tpred tfalse))\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (variation5)  *)\n(** Suppose instead that we add this rule:\n   \n      | T_Funny4 :\n            |- tzero \\in TBool\n   ]]\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 2 stars, optional (variation6)  *)\n(** Suppose instead that we add this rule:\n   \n      | T_Funny5 :\n            |- tpred tzero \\in TBool\n   ]]\n   Which of the above properties become false in the presence of\n   this rule?  For each one that does, give a counter-example.\n\n[] *)\n\n(** **** Exercise: 3 stars, optional (more_variations)  *)\n(** Make up some exercises of your own along the same lines as\n    the ones above.  Try to find ways of selectively breaking\n    properties -- i.e., ways of changing the definitions that\n    break just one of the properties and leave the others alone.\n[] *)\n\n(** **** Exercise: 1 star (remove_predzero)  *)\n(** The evaluation rule [E_PredZero] is a bit counter-intuitive: we\n    might feel that it makes more sense for the predecessor of zero to\n    be undefined, rather than being defined to be zero.  Can we\n    achieve this simply by removing the rule from the definition of\n    [step]?  Would doing so create any problems elsewhere?\n\n(* FILL IN HERE *)\n[] *)\n\n(** **** Exercise: 4 stars, advanced (prog_pres_bigstep)  *)\n(** Suppose our evaluation relation is defined in the big-step style.\n    What are the appropriate analogs of the progress and preservation\n    properties?\n\n(* FILL IN HERE *)\n[] *)\n\n(** $Date: 2016-01-24 21:56:22 +0000 (Sun, 24 Jan 2016) $ *)\n", "meta": {"author": "pierewoj", "repo": "tspl", "sha": "7b0f7edb08f04469bafdac804f22b347ea5574c4", "save_path": "github-repos/coq/pierewoj-tspl", "path": "github-repos/coq/pierewoj-tspl/tspl-7b0f7edb08f04469bafdac804f22b347ea5574c4/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7254901125823107}}
{"text": "\n\nInductive natural : Type :=   Zero : natural | Succ : natural -> natural .\n\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint qmult (qmult_arg0 : natural) (qmult_arg1 : natural) (qmult_arg2 : natural) : natural\n           := match qmult_arg0, qmult_arg1, qmult_arg2 with\n              | Zero, n, m => m\n              | Succ n, m, p => qmult n m (plus p m)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\n   intros.\n   induction x.\n   - rewrite plus_zero. reflexivity.\n   - simpl. rewrite plus_succ. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_qmult : forall (x y z a : natural), plus (qmult x y z) a = qmult x y (plus z a).\nProof.\n   intro.\n   induction x.\n   - reflexivity.\n   - intros. simpl. rewrite IHx. rewrite plus_assoc. rewrite (plus_commut y a). \n     rewrite <- plus_assoc. reflexivity.\nQed.\n\nTheorem mult_eq_qmult : forall (x : natural) (y : natural), eq (mult x y) (qmult x y Zero).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. rewrite plus_qmult. reflexivity.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal34.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7254901071767049}}
{"text": "Inductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n\nArguments nil {X}.\nArguments cons {X}.\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n\n(* exercise *)\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n    intros X. intros l. induction l as [| n l' IHl'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHl'. reflexivity.\n    Qed.\n\n(* exercise *)\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n    intros A l m n. induction l as [| k l' IHl'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHl'. reflexivity.\n    Qed.\n\n(* exercise *)\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n    intros X l1 l2. induction l1 as [| n l1' IHl1'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHl1'. 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/poly/exercises/poly_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.8596637559030337, "lm_q1q2_score": 0.7254660402003683}}
{"text": "\nRequire Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export ZArithRing.\nRequire Arith.\n\nParameters (prime_divisor : nat->nat)\n           (prime : nat->Prop)\n           (divides : nat->nat->Prop).\n\n(** Tests:\n\nCheck prime (prime_divisor 220).\n\nCheck divides (prime_divisor 220) 220.\n\nCheck divides 3.\n\n*)\n\nParameter binary_word : nat->Set.\n\nDefinition short : Set := binary_word 32.\nDefinition long : Set := binary_word 64.\n\n(** Tests :\n\nCheck ~ divides 3 81.\n\nCheck (let d := prime_divisor 220 in prime d /\\ divides d 220).\n\n*)\n\n\nParameters (decomp : nat -> list nat)\n           (decomp2 : nat->nat*nat).\n\n(** Tests :\n\nCheck decomp 220.\n\nCheck decomp2 284.\n\nCheck forall n:nat, 2<=n ->\n       prime (prime_divisor n) /\\\n       divides (prime_divisor n) n.\n*)\n\nParameter\n  prime_divisor_correct :\n     forall n:nat, 2 <= n -> \n       let d := prime_divisor n in prime d /\\ divides d n.\n\nParameter\n  binary_word_concat :\n     forall n p:nat,\n       binary_word n -> binary_word p -> binary_word (n+p).\n\n(* Tests :\n\nCheck (forall A B :Set, A->B->A*B).\n\n*)\n\nDefinition le_36_37 := le_S 36 36 (le_n 36).\n\nDefinition le_36_38 : 36 <= 38 := le_S 36 37 le_36_37.\n\n(** Tests :\n\nCheck (le_S _ _ (le_S _ _ (le_n 36))).\n\nCheck prime_divisor_correct 220.\n\n*)\n\n\nFixpoint iterate (A:Type)(f:A->A)(n:nat)(x:A) : A :=\n  match n with\n  | O => x\n  | S p => f (iterate A f p x)\n  end.\n\n(** Tests : \nCheck iterate nat.\n\nCheck iterate  _ (mult 2).\n\nCheck (iterate _ (mult 2) 10).\n\nCompute iterate _ (mult 2) 10 1.\n\n\nCheck binary_word_concat 32.\n\nCheck binary_word_concat 32 32.\n*)\n\nArguments iterate {A} _ _ _.\nArguments binary_word_concat {n p} _ _.\nArguments le_S {n m} _.\n\nDefinition binary_word_duplicate (n:nat)(w:binary_word n) \n : binary_word (n+n) :=\n  binary_word_concat  w w.\n\nDefinition short_concat : short -> short -> long \n                        := @binary_word_concat 32 32.\n\n\nTheorem le_i_SSi : forall i:nat, i <= S (S i).\nProof (fun i:nat => le_S  (le_S  (le_n i))).\n\n\nDefinition compose {A B C : Type} :  (A->B)->(B->C)->A->C\n   := fun f g x => g (f x).\n\n(** Tests :\n\nCheck fun (A:Type)(f:Z->A) => compose  Z_of_nat f.\n\nCheck compose  Zabs_nat (plus 78) 45%Z.\n\nCheck le_i_SSi 1515.\n\nCheck le_S  (le_i_SSi 1515).\n\nCheck compose (C := Z) S.\n\nCheck @le_S 45.\n\n*)\n\nDefinition thrice {A:Type} (f:A->A) := compose f (compose f f).\n\n\nLemma thrice_as_iter_3 {A:Type} (f: A -> A): thrice f = iterate f 3.\nProof. reflexivity. Qed.\n\nLemma thrice_thrice {A:Type} (f: A -> A): thrice (thrice f) = iterate f 9.\nProof. reflexivity. Qed.\n\nDefinition my_plus : nat->nat->nat := iterate  S.\n\nDefinition my_mult (n p:nat) : nat := iterate  (my_plus n) p 0.\n\nDefinition my_expt (x n:nat) : nat := iterate (my_mult x) n 1.\n\nDefinition ackermann (n:nat) : nat->nat :=\n  iterate (fun (f:nat->nat)(p:nat) => iterate  f (S p) 1) \n          n\n          S.\n\n\n(** Tests :\nCompute my_plus 9 7.\n\nCompute my_expt 2 5.\n\n*)\n\n\n(** Tests :\n\n\nCheck forall P:Prop, P->P.\n\nCheck fun (P:Prop)(p:P) => p.\n\nCheck @refl_equal.\n*)\n(*\nTheorem ThirtySix : 9*4=6*6.\nProof (refl_equal 36).\n *)\n\nDefinition eq_sym  {A:Type}{x y:A}(h : x=y) : y=x :=\n eq_ind  x (fun z => z=x) (refl_equal x) y h.\n\n(** Tests :\n Check eq_sym  ThirtySix. \n\nCheck conj.\n\nCheck or_introl.\n\nCheck or_intror.\n\nCheck and_ind.\n*)\n\nTheorem conj3 : forall P Q R:Prop, P->Q->R->P/\\Q/\\R.\nProof fun P Q R p q r => conj p (conj q r).\n\nTheorem disj4_3 : forall P Q R S:Prop, R -> P\\/Q\\/R\\/S.\nProof \n fun P Q R S r => or_intror _ (or_intror _ (or_introl _ r)).\n\nDefinition proj1' :  forall A B:Prop, A/\\B->A :=\n fun (A B:Prop)(H:A/\\B) => and_ind (fun (H0:A)(_:B) => H0) H.\n\n(** Tests :\n\nCheck ex (fun z:Z => (z*z <= 37 /\\ 37 < (z+1)*(z+1))%Z).\n\nCheck ex_intro.\n\nCheck ex_ind.\n\nCheck and.\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/chap4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7254660309274545}}
{"text": "Theorem thm2 :\n  forall A B C : Prop,\n    (A \\/ B) ->\n    (B -> C) ->\n    (A -> ~C) ->\n    ~C ->\n    A.\n(*\n\n前提\n\n  A:嬰児は精霊である。\n  B;嬰児は人間である。\n  C:嬰児は村に帰ってくる。\n\n  A \\/ B:嬰児は精霊か人間のいずれかである。\n  B -> C:嬰児が人間ならば、嬰児は村に帰ってくる。\n  A -> ~C:嬰児が精霊ならば、嬰児は村に帰ってこない。\n  ~C:嬰児は村に帰ってこなかった。\n\n結論\n\n  A:嬰児は精霊だった。\n\n*)\nProof.\n  intros A B C AorB_is_true BtoC_is_true AtoNotC_is_true NotC_is_true.\n  inversion AorB_is_true; subst; clear AorB_is_true.\n  - (* Aが成り立つ場合 *)\n    apply H.\n  - (* Bが成り立つ場合 *)\n    apply BtoC_is_true in H.\n    unfold not in NotC_is_true.\n    apply NotC_is_true in H.\n    exfalso.\n    apply H.\nQed.\n\nFrom mathcomp\nRequire Import ssreflect.\n\nTheorem thm2_ssr :\n  forall A B C : Prop,\n    (A \\/ B) ->\n    (B -> C) ->\n    (A -> ~C) ->\n    ~C ->\n    A.\nProof.\n  move=> A B C AorB_is_true BtoC_is_true AtoNotC_is_true NotC_is_true.\n  inversion AorB_is_true; subst; clear AorB_is_true.\n  -\n    done.\n  -\n    move: (BtoC_is_true H) => C_is_true.\n    move: NotC_is_true.\n    rewrite /not => CtoFalse_is_true.\n    move: (CtoFalse_is_true C_is_true) => Hypothesis_is_False.\n    done.\nQed.\n", "meta": {"author": "wakaba2017", "repo": "The_mathematical_reasoning_changes_the_world", "sha": "4f62e32d8ab939d0e5f728685c03906baf4d0f90", "save_path": "github-repos/coq/wakaba2017-The_mathematical_reasoning_changes_the_world", "path": "github-repos/coq/wakaba2017-The_mathematical_reasoning_changes_the_world/The_mathematical_reasoning_changes_the_world-4f62e32d8ab939d0e5f728685c03906baf4d0f90/thm2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7254660123645293}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2018   --   Inria - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\n\n(* Why3 comment *)\n(* abs is replaced with (ZArith.BinInt.Z.abs x) by the coq driver *)\n\n(* Why3 goal *)\nLemma abs_def :\nforall (x:Z),\n ((0%Z <= x)%Z -> ((ZArith.BinInt.Z.abs x) = x))\n /\\ ((~ (0%Z <= x)%Z) -> ((ZArith.BinInt.Z.abs x) = (-x)%Z)).\nintros x.\nsplit ; intros H.\nnow apply Zabs_eq.\napply Zabs_non_eq.\napply Znot_gt_le.\ncontradict H.\napply Zlt_le_weak.\nnow apply Zgt_lt.\nQed.\n\n(* Why3 goal *)\nLemma Abs_le :\nforall (x:Z) (y:Z),\n ((ZArith.BinInt.Z.abs x) <= y)%Z <-> (((-y)%Z <= x)%Z /\\ (x <= y)%Z).\nintros x y.\nzify.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Abs_pos :\nforall (x:Z), (0%Z <= (ZArith.BinInt.Z.abs x))%Z.\nexact Zabs_pos.\nQed.\n\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/int/Abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7254187986084588}}
{"text": "(**\n    The \"classical\" definition of well-foundedness\n\n  Pierre Casteran\n\n keywords :  well-founded relations, classical logic, axiom of choice\n\n *)\n\nRequire Import Relations.\n\n(** \n  Please consider the usual mathematical definition of well-founded relations :\n *)\n\n\n\nDefinition classic_wf {A}(R: relation A) :=\n  ~ exists (s: nat-> A),  forall i,  R (s (S i)) (s i).\n\n(** Prove that Coq's  definition entails the classical one *)\n\nTheorem wf_classic_wf {A} (R: relation A) : well_founded R -> classic_wf R.\nProof.\n  intros HR  [s Hs].\n  assert (forall x:A,  ~ exists i,  s i = x).\n  {\n    apply (well_founded_induction  HR).\n    intros x Hx [i Hi].\n    subst x;  specialize (Hs i).\n    specialize (Hx _ Hs).\n    apply Hx ; now exists (S i).\n  }\n  apply (H (s 0));  now exists 0.\nQed.\n\n\n(** Now, we work with some axioms (assumed in the following libraries) *)\n\nRequire Import Classical ClassicalChoice.\n\n\n(** In the current context, prove that the classical definition entails Coq's *)\n\n\nSection Classic_OK_R.\n  Variable (A:Type)(R: relation A).\n\n  Hypothesis H : classic_wf R.\n\n  Section Proof_by_absurd.\n\n    Hypothesis (H0: ~ well_founded R).\n\n    Lemma not_acc_ex : exists a:A,  ~ Acc R a.\n    Proof.\n      now apply not_all_ex_not.\n    Qed.\n\n\n    Lemma next_not_acc : forall a,  ~ Acc R a ->\n                                    exists b,  R b a /\\ ~ Acc R b.\n    Proof.\n      intros a H1;  apply not_all_not_ex.\n      intros H2; apply H1.\n      split; intros y H3.\n      specialize (H2 y); apply not_and_or in H2.\n      destruct H2;auto.\n      -  contradiction.\n      -  now apply NNPP in H2.\n    Qed.\n\n    (* In order to apply choice, we use an auxiliary sig type *)\n\n    Let B : Type := {a : A | ~ Acc R a}. \n\n    Let R1 : relation B :=\n      fun x y => R (proj1_sig y) (proj1_sig x).\n\n        \n    Lemma next_not_acc_R1 : forall x:B, exists y:B, R1 x y.\n    Proof.\n      destruct x as [a Ha].                                \n      destruct (next_not_acc a Ha) as [y [Hy Hy1]].\n      now exists (exist _ y Hy1).\n    Qed.\n\n        \n    Fixpoint iterate {B} (f : B -> B) b n : B :=\n      match n with 0 => b | S p => f (iterate f b p) end.\n\n    Lemma L : exists f: nat -> B, forall i, R1 (f i) (f (S i)).\n    Proof.\n      destruct not_acc_ex as [x H1].\n      destruct (choice _ next_not_acc_R1) as [h H2].\n      exists (iterate h (exist _ x H1)).\n      induction i; simpl; auto.\n    Qed.\n\n\n    Lemma L2: exists g : nat -> A, forall i, R (g (S i)) (g i).\n    Proof.\n      destruct L as [f Hf].\n      exists (fun i =>  proj1_sig (f i)).\n      intro; apply Hf.\n    Qed.\n\n    Lemma FF : False.\n    Proof.\n      apply H, L2.\n    Qed.\n\n  End Proof_by_absurd.\n\nEnd Classic_OK_R.\n\nTheorem classic_wf_wf  {A} (R: relation A) : classic_wf R -> well_founded R.\nProof.\n  intros; apply NNPP.\n  intro; now apply (FF _ R).\nQed.\n  \n\n\nArguments classic_wf_wf {A}.\n\nPrint Assumptions classic_wf_wf.\n\n(*\n\nAxioms:\nrelational_choice : forall (A B : Type) (R : A -> B -> Prop),\n                    (forall x : A, exists y : B, R x y) ->\n                    exists R' : A -> B -> Prop, subrelation R' R /\\ (forall x : A, exists ! y : B, R' x y)\ndependent_unique_choice : forall (A : Type) (B : A -> Type) (R : forall x : A, B x -> Prop),\n                          (forall x : A, exists ! y : B x, R x y) ->\n                          exists f : forall x : A, B x, forall x : A, R x (f x)\nclassic : forall P : Prop, P \\/ ~ P\n\n*)\n\nPrint Assumptions wf_classic_wf.\n\n(*\n\nClosed under the global context\n*)\n\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/more_exercises/solutions/classic_well_founded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7254187969420812}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural :=\n  plus Zero (plus y lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj2010_coqofml_Xs4nWE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7253981395365802}}
{"text": "Require Import init.\n\nRequire Export relation.\nRequire Import list_base.\n\nDeclare Scope set_scope.\nDelimit Scope set_scope with set.\n\n(* begin hide *)\nOpen Scope set_scope.\n(* end hide *)\n\nDefinition subset {U : Type} (S T : U → Prop) := ∀ x, S x → T x.\nInfix \"⊆\" := subset.\nInfix \"⊂\" := (strict subset) (at level 50, no associativity).\n\nDefinition empty {U : Type} := λ x : U, False.\nDefinition all {U : Type} := λ x : U, True.\nNotation \"∅\" := empty.\n\n(** This is used for purely notational purposes and should never be used\ndirectly. *)\nFixpoint list_to_set {U} l (a : U) :=\n    match l with\n    | list_end => False (* Not actually ever used *)\n    | list_add x list_end => x = a\n    | list_add x l' => x = a ∨ list_to_set l' a\n    end.\nArguments list_to_set : simpl never.\n(** Note that is not curly brackets!  That gets Coq confused with notations\nlike {A} + {B}.  Instead, these are U+2774 and U+2775, MEDIUM LEFT/RIGHT CURLY\nBRACKET ORNAMENT *)\nNotation \"❴ x , .. , y ❵\"\n    := (list_to_set (list_add x .. (list_add y list_end) ..)).\n\nDefinition union {U : Type} (S T : U → Prop) := λ x, S x ∨ T x.\nInfix \"∪\" := union.\nDefinition intersection {U : Type} (S T : U → Prop) := λ x, S x ∧ T x.\nInfix \"∩\" := intersection.\nDefinition set_minus {U : Type} (S T : U → Prop) := λ x, S x ∧ ¬T x.\nInfix \"-\" := set_minus : set_scope.\nDefinition symmetric_difference {U : Type} (S T : U → Prop) := (S-T) ∪ (T-S).\nInfix \"+\" := symmetric_difference : set_scope.\n(** This is \"\\\\mathbf C\" *)\nDefinition 𝐂 {U : Type} (S : U → Prop) := λ x, ¬S x.\n\nDefinition cartesian_product {U V : Type} (S : U → Prop) (T : V → Prop) :=\n    λ (x : U * V), S (fst x) ∧ T (snd x).\nInfix \"*\" := cartesian_product : set_scope.\n\nDefinition disjoint {U : Type} (S T : U → Prop) := S ∩ T = ∅.\nDefinition intersects {U : Type} (S T : U → Prop) := S ∩ T ≠ ∅.\n\n(* begin hide *)\nSection SetBase.\n\nContext {U : Type}.\n\nTheorem singleton_eq : ∀ a b : U, ❴a❵ b ↔ a = b.\nProof.\n    reflexivity.\nQed.\n\nTheorem pair_union : ∀ a b : U, ❴a, b❵ = ❴a❵ ∪ ❴b❵.\nProof.\n    reflexivity.\nQed.\n\n(* end hide *)\nGlobal Instance subset_refl : Reflexive (subset (U := U)).\nProof.\n    split.\n    intros S x Sx.\n    exact Sx.\nQed.\n\nGlobal Instance subset_trans : Transitive (subset (U := U)).\nProof.\n    split.\n    intros R S T RS ST x Rx.\n    apply ST.\n    apply RS.\n    exact Rx.\nQed.\n\nGlobal Instance subset_antisym : Antisymmetric (subset (U := U)).\nProof.\n    split.\n    intros S T ST TS.\n    apply predicate_ext; intro x.\n    split.\n    -   apply ST.\n    -   apply TS.\nQed.\n\nTheorem strict_subset_ex : ∀ (S T : U → Prop), S ⊂ T → ∃ x, ¬S x ∧ T x.\nProof.\n    intros S T sub.\n    classic_contradiction contr.\n    apply sub.\n    apply antisym; [>apply sub|].\n    intros x Tx.\n    rewrite not_ex in contr.\n    specialize (contr x).\n    rewrite and_comm, not_and_impl, not_not in contr.\n    exact (contr Tx).\nQed.\n\nTheorem empty_sub : ∀ S : U → Prop, ∅ ⊆ S.\nProof.\n    intros S x contr.\n    contradiction contr.\nQed.\nTheorem all_sub : ∀ S : U → Prop, S ⊆ all.\nProof.\n    intros S x Sx.\n    exact true.\nQed.\n\nTheorem empty_eq : ∀ S : U → Prop, S = ∅ ↔ (∀ x, ¬S x).\nProof.\n    intros S.\n    split.\n    -   intros eq x Sx.\n        rewrite eq in Sx.\n        contradiction Sx.\n    -   intros all_not.\n        apply antisym.\n        +   intros x Sx.\n            exact (all_not x Sx).\n        +   apply empty_sub.\nQed.\n\nTheorem empty_neq : ∀ S : U → Prop, S ≠ ∅ ↔ (∃ x, S x).\nProof.\n    intros S.\n    apply not_eq_iff.\n    rewrite not_not, not_ex.\n    apply empty_eq.\nQed.\n\nTheorem all_eq : ∀ S : U → Prop, S = all ↔ (∀ x, S x).\nProof.\n    intros S.\n    split.\n    -   intros eq x.\n        rewrite eq.\n        exact true.\n    -   intros all_in.\n        apply antisym.\n        +   apply all_sub.\n        +   intros x Sx.\n            apply all_in.\nQed.\n\nTheorem all_neq : ∀ S : U → Prop, S ≠ all ↔ (∃ x, ¬S x).\nProof.\n    intros S.\n    rewrite <- not_all.\n    rewrite <- not_eq_iff.\n    apply all_eq.\nQed.\n\nTheorem not_in_empty : ∀ x : U, ¬∅ x.\nProof.\n    intros x contr.\n    contradiction contr.\nQed.\n\nTheorem union_comm : ∀ S T : U → Prop, S ∪ T = T ∪ S.\nProof.\n    intros S T.\n    apply predicate_ext; intros x.\n    apply or_comm.\nQed.\n\nTheorem union_assoc : ∀ R S T : U → Prop, R ∪ (S ∪ T) = (R ∪ S) ∪ T.\nProof.\n    intros R S T.\n    apply predicate_ext; intros x.\n    apply or_assoc.\nQed.\n\nTheorem union_lid : ∀ S : U → Prop, ∅ ∪ S = S.\nProof.\n    intros S.\n    apply predicate_ext; intros x.\n    apply or_lfalse.\nQed.\nTheorem union_rid : ∀ S : U → Prop, S ∪ ∅ = S.\nProof.\n    intros S.\n    rewrite union_comm.\n    apply union_lid.\nQed.\n\nTheorem union_lanni : ∀ S : U → Prop, all ∪ S = all.\nProof.\n    intros S.\n    apply predicate_ext; intros x.\n    apply or_ltrue.\nQed.\nTheorem union_ranni : ∀ S : U → Prop, S ∪ all = all.\nProof.\n    intros S.\n    rewrite union_comm.\n    apply union_lanni.\nQed.\n\nTheorem union_lsub : ∀ S T : U → Prop, S ⊆ S ∪ T.\nProof.\n    intros S T x Sx.\n    left; exact Sx.\nQed.\nTheorem union_rsub : ∀ S T : U → Prop, T ⊆ S ∪ T.\nProof.\n    intros S T.\n    rewrite union_comm.\n    apply union_lsub.\nQed.\n\nTheorem union_compl_all : ∀ S : U → Prop, S ∪ 𝐂 S = all.\nProof.\n    intros S.\n    apply all_eq.\n    intros x.\n    apply em.\nQed.\n\nTheorem union_idemp : ∀ S : U → Prop, S ∪ S = S.\nProof.\n    intros S.\n    apply predicate_ext; intros x.\n    apply or_idemp.\nQed.\n\nLemma union_minus : ∀ A B : U → Prop, A ∩ B = ∅ → A ∪ B - B = A.\nProof.\n    intros A B dis.\n    apply antisym.\n    -   intros x [[Ax|Bx] nBx].\n        +   exact Ax.\n        +   contradiction.\n    -   intros x Ax.\n        split; [>left; exact Ax|].\n        intros contr.\n        rewrite empty_eq in dis.\n        exact (dis x (make_and Ax contr)).\nQed.\n\n\nTheorem inter_comm : ∀ S T : U → Prop, S ∩ T = T ∩ S.\nProof.\n    intros S T.\n    apply predicate_ext; intros x.\n    apply and_comm.\nQed.\n\nTheorem inter_assoc : ∀ R S T : U → Prop, R ∩ (S ∩ T) = (R ∩ S) ∩ T.\nProof.\n    intros R S T.\n    apply predicate_ext; intros x.\n    apply and_assoc.\nQed.\n\nTheorem inter_lid : ∀ S : U → Prop, all ∩ S = S.\nProof.\n    intros S.\n    apply predicate_ext; intros x.\n    apply and_ltrue.\nQed.\nTheorem inter_rid : ∀ S : U → Prop, S ∩ all = S.\nProof.\n    intros S.\n    rewrite inter_comm.\n    apply inter_lid.\nQed.\n\nTheorem inter_lanni : ∀ S : U → Prop, ∅ ∩ S = ∅.\nProof.\n    intros S.\n    apply predicate_ext; intros x.\n    apply and_lfalse.\nQed.\nTheorem inter_ranni : ∀ S : U → Prop, S ∩ ∅ = ∅.\nProof.\n    intros S.\n    rewrite inter_comm.\n    apply inter_lanni.\nQed.\n\nTheorem inter_lsub : ∀ S T : U → Prop, S ∩ T ⊆ S.\nProof.\n    intros S T x [Sx Tx].\n    exact Sx.\nQed.\nTheorem inter_rsub : ∀ S T : U → Prop, S ∩ T ⊆ T.\nProof.\n    intros S T.\n    rewrite inter_comm.\n    apply inter_lsub.\nQed.\n\nTheorem lsub_inter_equal : ∀ S T : U → Prop, S ⊆ T → S ∩ T = S.\nProof.\n    intros S T sub.\n    apply antisym.\n    -   intros x [Sx Tx].\n        exact Sx.\n    -   intros x Sx.\n        split.\n        +   exact Sx.\n        +   exact (sub x Sx).\nQed.\n\nTheorem rsub_inter_equal : ∀ S T : U → Prop, T ⊆ S → S ∩ T = T.\nProof.\n    intros S T sub.\n    rewrite inter_comm.\n    apply lsub_inter_equal.\n    exact sub.\nQed.\n\nTheorem inter_compl_empty : ∀ S : U → Prop, S ∩ 𝐂 S = ∅.\nProof.\n    intros S.\n    apply empty_eq.\n    intros x [Sx nSx].\n    contradiction.\nQed.\n\nTheorem inter_idemp : ∀ S : U → Prop, S ∩ S = S.\nProof.\n    intros S.\n    apply predicate_ext; intros x.\n    apply and_idemp.\nQed.\n\nTheorem union_ldist : ∀ R S T : U → Prop, R ∪ (S ∩ T) = (R ∪ S) ∩ (R ∪ T).\nProof.\n    intros R S T.\n    apply predicate_ext; intros x.\n    apply or_and_ldist.\nQed.\nTheorem union_rdist : ∀ R S T : U → Prop, (R ∩ S) ∪ T = (R ∪ T) ∩ (S ∪ T).\nProof.\n    intros R S T.\n    apply predicate_ext; intros x.\n    apply or_and_rdist.\nQed.\nTheorem inter_ldist : ∀ R S T : U → Prop, R ∩ (S ∪ T) = (R ∩ S) ∪ (R ∩ T).\nProof.\n    intros R S T.\n    apply predicate_ext; intros x.\n    apply and_or_ldist.\nQed.\nTheorem inter_rdist : ∀ R S T : U → Prop, (R ∪ S) ∩ T = (R ∩ T) ∪ (S ∩ T).\nProof.\n    intros R S T.\n    apply predicate_ext; intros x.\n    apply and_or_rdist.\nQed.\n\nTheorem union_inter_self : ∀ A B : U → Prop, A ∪ (A ∩ B) = A.\nProof.\n    intros A B.\n    apply antisym.\n    -   intros x [Ax|[Ax Bx]]; exact Ax.\n    -   intros x Ax.\n        left; exact Ax.\nQed.\nTheorem inter_union_self : ∀ A B : U → Prop, A ∩ (A ∪ B) = A.\nProof.\n    intros A B.\n    apply antisym.\n    -   intros x [Ax Bx]; exact Ax.\n    -   intros x Ax.\n        split; [>|left]; exact Ax.\nQed.\n\nTheorem compl_compl : ∀ A : U → Prop, 𝐂 (𝐂 A) = A.\nProof.\n    intros A.\n    apply predicate_ext; intros x.\n    unfold 𝐂.\n    apply not_not.\nQed.\n\nTheorem compl_empty : @𝐂 U ∅ = all.\nProof.\n    apply predicate_ext; intros x.\n    unfold 𝐂, empty.\n    rewrite not_false.\n    reflexivity.\nQed.\n\nTheorem compl_all : @𝐂 U all = ∅.\nProof.\n    apply predicate_ext; intros x.\n    unfold 𝐂, all.\n    rewrite not_true.\n    reflexivity.\nQed.\n\nTheorem union_compl : ∀ A B : U → Prop,\n    𝐂 (A ∪ B) = 𝐂 A ∩ 𝐂 B.\nProof.\n    intros A B.\n    apply predicate_ext; intros x.\n    apply not_or.\nQed.\n\nTheorem inter_compl : ∀ A B : U → Prop,\n    𝐂 (A ∩ B) = 𝐂 A ∪ 𝐂 B.\nProof.\n    intros A B.\n    apply predicate_ext; intros x.\n    apply not_and.\nQed.\n\nTheorem compl_eq : ∀ A B : U → Prop, 𝐂 A = 𝐂 B → A = B.\nProof.\n    intros A B eq.\n    apply predicate_ext; intros x.\n    pose proof (func_eq _ _ eq x) as eq2.\n    apply not_eq_eq in eq2.\n    rewrite eq2.\n    reflexivity.\nQed.\n\nTheorem set_minus_formula : ∀ S T : U → Prop, S - T = S ∩ 𝐂 T.\nProof.\n    reflexivity.\nQed.\n\nTheorem set_minus_rempty : ∀ S : U → Prop, S - ∅ = S.\nProof.\n    intros S.\n    rewrite set_minus_formula.\n    rewrite compl_empty.\n    apply inter_rid.\nQed.\n\nTheorem set_minus_lempty : ∀ S : U → Prop, ∅ - S = ∅.\nProof.\n    intros S.\n    rewrite set_minus_formula.\n    apply inter_lanni.\nQed.\n\nTheorem set_minus_inv : ∀ S : U → Prop, S - S = ∅.\nProof.\n    intros S.\n    rewrite set_minus_formula.\n    apply inter_compl_empty.\nQed.\n\nTheorem set_minus_twice : ∀ S T : U → Prop, S - T - T = S - T.\nProof.\n    intros S T.\n    do 2 rewrite set_minus_formula.\n    rewrite <- inter_assoc.\n    rewrite inter_idemp.\n    reflexivity.\nQed.\n\nTheorem symdif_formula : ∀ S T : U → Prop, S + T = (S ∪ T) - (S ∩ T).\nProof.\n    intros S T.\n    unfold symmetric_difference.\n    do 3 rewrite set_minus_formula.\n    rewrite inter_compl.\n    rewrite union_ldist.\n    do 2 rewrite union_rdist.\n    rewrite (union_comm (𝐂 T)).\n    do 2 rewrite union_compl_all.\n    rewrite inter_lid.\n    rewrite inter_rid.\n    apply f_equal.\n    apply union_comm.\nQed.\n\nTheorem symdif_comm : ∀ S T : U → Prop, S + T = T + S.\nProof.\n    intros S T.\n    unfold symmetric_difference.\n    apply union_comm.\nQed.\n\nTheorem symdif_assoc : ∀ R S T : U → Prop, R + (S + T) = (R + S) + T.\nProof.\n    intros R S T.\n    rewrite (symdif_comm R S).\n    rewrite (symdif_comm (S + R) T).\n    rewrite symdif_formula.\n    unfold symmetric_difference at 2.\n    rewrite (symdif_formula S T).\n    rewrite (symdif_formula T).\n    unfold symmetric_difference at 2.\n    rewrite (symdif_formula S R).\n    do 8 rewrite set_minus_formula.\n    do 4 rewrite inter_compl.\n    do 2 rewrite union_compl.\n    do 4 rewrite inter_compl.\n    do 3 rewrite compl_compl.\n    do 4 rewrite union_ldist.\n    assert (∀ X Y Z : U → Prop, X ∪ (Y ∪ Z) = Z ∪ (Y ∪ X)) as lemma.\n    {\n        intros X Y Z.\n        rewrite union_comm.\n        rewrite union_assoc.\n        rewrite (union_comm Y).\n        reflexivity.\n    }\n    do 2 rewrite (lemma R).\n    rewrite (lemma (𝐂 R)).\n    do 2 rewrite (union_assoc _ _ S).\n    rewrite (union_comm (𝐂 R) (𝐂 T)).\n    do 2 rewrite <- inter_assoc.\n    apply f_equal.\n    do 2 rewrite inter_assoc.\n    apply f_equal2; [>|reflexivity].\n    apply inter_comm.\nQed.\n\nTheorem symdif_lid : ∀ S : U → Prop, ∅ + S = S.\nProof.\n    intros S.\n    unfold symmetric_difference.\n    rewrite set_minus_rempty.\n    rewrite set_minus_lempty.\n    apply union_lid.\nQed.\nTheorem symdif_rid : ∀ S : U → Prop, S + ∅ = S.\nProof.\n    intros S.\n    rewrite symdif_comm.\n    apply symdif_lid.\nQed.\n\nTheorem symdif_inv : ∀ S : U → Prop, S + S = ∅.\nProof.\n    intros S.\n    unfold symmetric_difference.\n    rewrite set_minus_inv.\n    apply union_lid.\nQed.\n\nContext {V : Type}.\n\nTheorem cartesian_product_sub : ∀ (A B : U → Prop) (C D : V → Prop),\n    A ⊆ B → C ⊆ D → A * C ⊆ B * D.\nProof.\n    intros A B C D AB CD.\n    intros x [Ax Cx].\n    apply AB in Ax.\n    apply CD in Cx.\n    split; assumption.\nQed.\n\nTheorem cartesian_product_inter : ∀ (A B : U → Prop) (C D : V → Prop),\n    (A ∩ B) * (C ∩ D) = (A * C) ∩ (B * D).\nProof.\n    intros A B C D.\n    apply predicate_ext.\n    intros [a b].\n    unfold intersection, cartesian_product; cbn.\n    do 2 rewrite and_assoc.\n    do 4 rewrite <- (and_assoc (A a)).\n    rewrite (and_comm (B a) (C b)).\n    reflexivity.\nQed.\n(* begin hide *)\n\nEnd SetBase.\n\nClose Scope set_scope.\n(* end hide *)\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Set/set_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7253981248769757}}
{"text": "(** Common definitions *)\nFrom Coq Require Import Ensembles.\nFrom RelationAlgebra Require Import prop monoid kat relalg kat_tac.\nFrom Catincoq.lib Require Import proprel.\n\nDefinition partial_order {A} (R : relation A) := 1 ≦ R /\\ R ⋅ R ≦ R /\\ R ⊓ R° ≦ 1.\n\nDefinition strict_order {A} (R : relation A) := R ⋅ R ≦ R /\\ R ⊓ 1 ≦ 0.\n\nDefinition is_strict_order {A} (R : relation A) :=\n  relalg.is_irreflexive R /\\\n  is_transitive R.\n\nLemma is_strict_order_spec {A} (R : relation A) : is_strict_order R <-> strict_order R.\nProof.\n  compute. firstorder.\nQed.\n\nDefinition is_irreflexive {X} (R : relation X) := R ⊓ 1 ≦ 0.\n\nDefinition irreflexive {A} (R : relation A) := cap R 1 ≦ bot.\n\nLemma is_irreflexive_spec1 {X} (R : relation X) : irreflexive R <-> is_irreflexive R.\nProof.\n  reflexivity.\nQed.\n\nLemma is_irreflexive_spec2 {X} (R : relation X) : relalg.is_irreflexive R <-> is_irreflexive R.\nProof.\n  compute. firstorder (subst; firstorder).\nQed.\n\nLemma is_irreflexive_spec3 {X} (R : relation X) : RelationClasses.Irreflexive R <-> is_irreflexive R.\nProof.\n  compute. firstorder (subst; firstorder).\nQed.\n\nDefinition acyclic {A} (R : relation A) := leq (cap (itr _ R) 1) bot.\n\nDefinition is_acyclic {X} (R : relation X) := R^+ ⊓ 1 ≦ 0.\n\nLemma is_acyclic_spec {X} (R : relation X) : acyclic R <-> is_acyclic R.\nProof.\n  split; intros A x y; specialize (A x y); rewrite A; compute; tauto.\nQed.\n\nDefinition total {A} (R : relation A) := !1 ≦ R ⊔ R°.\n\n(** TODO merge those two *)\nDefinition total_on {A} (E : set A) (R : relation A) := [E] ⋅ !1 ⋅ [E] ≦ R ⊔ R°.\n\nDefinition linear_extension_on {A} (E : set A) (R : relation A) : set (relation A) :=\n  fun S => strict_order S /\\ S ≦ [E] ⋅ top ⋅ [E] /\\ total_on E S /\\ [E] ⋅ R ⋅ [E] ≦ S.\n\nDefinition finite_set {A} (E : set A) :=\n  exists (l : list A), forall a, E a -> List.In a l.\n\nDefinition relational_image {A B} (R : A -> B -> Prop) : Ensemble A -> Ensemble B :=\n  fun x b => exists a, x a /\\ R a b.\n\nDefinition functional_relation_domain {A B} (dom : Ensemble A) (R : A -> B -> Prop) :=\n  (forall a, dom a <-> exists b, R a b) /\\\n  (forall a b b', R a b -> R a b' -> b = b').\n\nDefinition one_of_each {X} : Ensemble (Ensemble X) -> Ensemble (Ensemble X) :=\n  fun A b => exists f : Ensemble X -> X -> Prop,\n      (forall e fe, f e fe -> e fe) /\\\n      functional_relation_domain A f /\\\n      Same_set _ b (relational_image f A).\n\nDefinition subset_image {A B} (f : A -> B) (X : Ensemble A) : Ensemble B\n  := fun y => exists x, X x /\\ y = f x.\n\nDefinition union_of_relations {A} : Ensemble (relation A) -> relation A :=\n  fun Rs x y => exists R, Rs R /\\ R x y.\n\nDefinition equivalence_classes {A} (R : relation A) : Ensemble (Ensemble A) :=\n  fun C => exists x, C x /\\ forall y, R x y <-> C y.\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/lib/defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7253558422433953}}
{"text": "From Coq Require Import List.\n\nImport ListNotations.\nLocal Open Scope list_scope.\nOpen Scope type_scope.\n\nSection PERM.\n\n  Context {A : Type}.\n\n(** Steve's version *)\n  \nInductive Permutation  : list A -> list A -> Type :=\n| perm_id: forall l, Permutation l l\n| perm_swap x y l : Permutation ([y] ++ [x] ++ l) ([x] ++ [y] ++ l)\n| perm_comp l1 l2 l3 :\n    Permutation l1 l2 -> Permutation l2 l3 -> Permutation l1 l3\n| perm_plus l11 l12 l21 l22 :\n  Permutation l11 l21 -> Permutation l12 l22 -> Permutation (l11 ++ l12) (l21 ++ l22).\n\nLemma PermutationSymmetric : forall (xs ys: list A),\n    Permutation xs ys -> Permutation ys xs.\nProof.\n  intros.\n  induction X.\n  - apply perm_id.\n  - apply perm_swap.\n  - eapply perm_comp; eauto.\n  - apply perm_plus; eauto.\nQed.    \n\n\n(** Thorsten's Version *)\n\nInductive Add : A -> list A -> list A -> Type :=\n| zero : forall a aS, Add a aS (a :: aS)\n| succ : forall a b aS bs, Add a aS bs -> Add a (b :: aS) (b :: bs).\n\nArguments zero {_ _}.\nArguments succ {_ _ _ _}.\n\nInductive Perm : list A -> list A -> Type :=\n| perm_nil  : Perm [] []\n| perm_cons : forall a aS bs cs, Perm aS cs -> Add a cs bs -> Perm (a :: aS) bs.\n\nArguments perm_cons {_ _ _ _}.\n\nFixpoint reflPerm (xs:list A) : Perm xs xs :=\n  match xs with\n  | [] => perm_nil\n  | x::xs => perm_cons (reflPerm xs) zero\n  end.\n\nLemma addLem : forall {a b aS bs cs} (P : Add a aS bs) (Q : Add b bs cs),\n    {ds : list A & Add b aS ds * (Add a ds cs)}.\nProof.\n  intros.\n  revert b cs Q.\n  induction P; intros.\n  - inversion Q; subst.\n    + exists (b :: aS). split.  apply zero. apply succ. apply zero.\n    + eexists. split. apply X. apply zero.\n  - inversion Q; subst.\n    + eexists. split. apply zero. apply succ. apply succ. apply P.\n    + specialize (IHP b0 bs0 X).\n      destruct IHP as [ds [HP HQ]].\n      eexists (b::ds). split. eapply succ. assumption. eapply succ. assumption.\nQed.      \n\nLemma transLem : forall {a bs cs bs'} (P : Perm bs cs) (H : Add a bs' bs),\n    { cs' : list A & Perm bs' cs' * Add a cs' cs}.\nProof.\n  intros.\n  revert a bs' H.\n  induction P; intros.\n  - inversion H.\n  - remember (a :: aS) as xs.\n    revert a aS P a0 IHP Heqxs.\n    inversion H; intros; inversion Heqxs; subst; clear Heqxs.\n    + exists cs. split; auto.\n    + destruct (IHP _ _ X) as [cs' [P' Q']].\n      destruct (addLem Q' a2) as [ds [Y Z]].\n      exists ds. split. eapply perm_cons; eauto. apply Z.\nQed.\n      \nLemma transPerm : forall {aS bs cs} (P : Perm aS bs) (Q : Perm bs cs),\n    Perm aS cs.\nProof.\n  intros aS bs cs P Q.\n  revert cs Q.\n  induction P; intros.\n  - assumption.\n  - destruct (transLem Q a0) as [cs' [Q' Y]].\n    apply (perm_cons (IHP cs' Q')).\n    assumption.\nQed.    \n\nLemma symLem : forall {a aS bs cs} (P: Perm cs aS) (X : Add a cs bs),\n    Perm bs (a :: aS).\nProof.\n  intros a aS bs cs P X.\n  revert aS P.\n  induction X; intros.\n  - eapply perm_cons. apply P. apply zero.\n  - inversion P; subst.\n    eapply perm_cons.\n    apply (IHX _ X0). apply succ. assumption.\nQed.    \n\nLemma symPerm : forall {aS bs} (P : Perm aS bs),\n    Perm bs aS.\nProof.\n  intros.\n  induction P.\n  - apply perm_nil.\n  - eapply symLem. apply IHP. assumption.\nQed.    \n\nLemma remPerm : forall {a aS bs} (P : Perm (a::aS) (a::bs)),\n    Perm aS bs.\nProof.\n  intros.\n  inversion P; subst.\n  inversion X0; subst.\n  - assumption.\n  - eapply transPerm. apply X.\n    eapply perm_cons. apply reflPerm.\n    assumption.\nQed.\n\nLemma swapPerm : forall {a b aS}, (Perm (a::b::aS) (b::a::aS)).\nProof.\n  intros.\n  eapply perm_cons.\n  2: { eapply succ. eapply zero. }\n  apply reflPerm.\nQed.\n\nLemma appendAdd : forall a aS bs cs,\n    Add a aS bs -> Add a (aS ++ cs) (bs ++ cs).\nProof.\n  intros a aS bs cs H.\n  revert cs.\n  induction H; intros.\n  - apply zero.\n  - simpl. apply succ. apply IHAdd.\nQed.    \n\nLemma appendPerm : forall aS bs cs ds,\n    Perm aS bs -> Perm cs ds -> Perm (aS++cs) (bs++ds).\nProof.\n  intros aS bs cs ds H.\n  revert cs ds.\n  induction H; intros.\n  - simpl. assumption.\n  - simpl. eapply perm_cons.\n    apply IHPerm. apply X.\n    apply appendAdd.\n    assumption.\nQed.\n\nLemma Permutation_Perm : forall xs ys, Permutation xs ys -> Perm xs ys.\nProof.\n  intros.\n  induction X.\n  - apply reflPerm.\n  - apply swapPerm.\n  - eapply transPerm. apply IHX1. apply IHX2.\n  - apply appendPerm; auto.\nQed.\n\nLemma Permutation_AddLem : forall a cs bs,\n    Add a cs bs -> Permutation (a::cs) bs.\nProof.\n  intros.\n  induction X.\n  - apply perm_id.\n  - eapply perm_comp.\n    eapply perm_swap.\n    replace (b :: bs) with ([b] ++ bs) by reflexivity.\n    apply perm_plus. apply perm_id.\n    apply IHX.\nQed.\n    \nLemma Permutation_Add : forall a aS bs cs, \n    Permutation aS cs -> Add a cs bs -> Permutation (a :: aS) bs.\nProof.\n  intros.\n  revert a bs X0.\n  induction X; intros.\n  - apply Permutation_AddLem. assumption.\n  - apply Permutation_AddLem in X0.\n    replace (a :: [y] ++ [x] ++ l) with ([a] ++ (y::x::l)) by reflexivity.\n    eapply perm_comp. eapply perm_plus. apply perm_id.\n    eapply perm_swap. assumption.\n  - apply IHX2 in X0.\n    eapply perm_comp. eapply PermutationSymmetric.\n    replace (a :: l1) with ([a] ++ l1) by reflexivity.\n    apply perm_plus. apply perm_id.\n    apply PermutationSymmetric. apply X1.\n    apply X0.\n  - apply Permutation_AddLem in X0.\n    eapply perm_comp.\n    2: { apply X0. }\n    replace (a :: l11 ++ l12) with ([a] ++ (l11 ++ l12)) by reflexivity.\n    replace (a :: l21 ++ l22) with ([a] ++ (l21 ++ l22)) by reflexivity.\n    apply perm_plus. apply perm_id.\n    apply perm_plus; assumption.\nQed.\n\nLemma Perm_Permutation : forall aS bs,\n    Perm aS bs -> Permutation aS bs.\nProof.\n  intros.\n  induction X.\n  - apply perm_id.\n  - eapply Permutation_Add; eauto.\nQed.    \n\nEnd PERM.\n", "meta": {"author": "Zdancewic", "repo": "graphs", "sha": "f2d623bf52170caff8cd804616cf32fbc12d7b2a", "save_path": "github-repos/coq/Zdancewic-graphs", "path": "github-repos/coq/Zdancewic-graphs/graphs-f2d623bf52170caff8cd804616cf32fbc12d7b2a/coq/Perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7253558216980928}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** Properties of arbitrary binary relations (not necessarily decidable) *)\n(** A functional or deterministic relation *)\nDefinition functional {X : Type} (R : X -> X -> Prop) : Prop :=\n  forall (s s1 s2 : X), R s s1 -> R s s2 -> s1 = s2.\n\nLemma func1 :\n  functional (fun x y => x.*2 == y).\nAdmitted.\n\nLemma func2 :\n  ~ functional (fun x y => (x.*2 == y) || ((x, y) == (0,1))).\nAdmitted.\n\n\n(** Define a notation such that {In C, functional R} restricts the domain of the relation like so:\n\n  forall (s s1 s2 : X), C s -> R s s1 -> R s s2 -> s1 = s2\n\nAnd prove the following lemma:\n*)\n(* Notation \"{ 'In' C , P }\" := *)\n(*   (...) (at level 0). *)\n\nLemma func3 :\n  {In (fun n => 0 < n), functional (fun x y => (x.*2 == y) || ((x, y) == (0,1)))}.\nAdmitted.\n\n\n(* prove without using [case] or [elim] tactics *)\nLemma Peirce p q : ((p ==> q) ==> p) ==> p.\nAdmitted.\n\n\n(* prove without using [case] or [elim] tactics *)\nLemma addb_neq12 p q :  ~~ p = q -> p (+) q.\nAdmitted.\n\n\nLemma div_fact_plus1 m p : 1 < p -> p %| m `! + 1 -> m < p.\nAdmitted.\n\n\n(* Prove [8x = 6y + 1] has no solutions in [nat] *)\nLemma no_solution x y :\n  8*x != 6*y + 1.\nAdmitted.\n\n\n\nLemma iota_add m n1 n2 :\n  iota m (n1 + n2) = iota m n1 ++ iota (m + n1) n2.\nAdmitted.\n\nDefinition mysum m n F := (foldr (fun i a => F i + a) 0 (iota m (n - m))).\n\n(* \"big\" operator *)\nNotation \"\\mysum_ ( m <= i < n ) F\" := (mysum m n (fun i => F))\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\mysum_ ( m  <=  i  <  n ) '/  '  F ']'\").\n\nLemma mysum_recl m n F :\n  m <= n ->\n  \\mysum_(m <= i < n.+1) F i = \\mysum_(m <= i < n) F i + F n.\nAdmitted.\n\nLemma sum_odds n :\n  \\mysum_(0 <= i < n) (2 * i + 1) = n ^ 2.\nAdmitted.\n\n\n", "meta": {"author": "anton-trunov", "repo": "coq-lecture-notes", "sha": "e012addae82da6d8d03f6e789e43f35140dcdfea", "save_path": "github-repos/coq/anton-trunov-coq-lecture-notes", "path": "github-repos/coq/anton-trunov-coq-lecture-notes/coq-lecture-notes-e012addae82da6d8d03f6e789e43f35140dcdfea/homework/hw07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7252467978923638}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_perp_at :\n\tforall P Q A B C X,\n\tCol P Q C ->\n\tCol A B C ->\n\tCol A B X ->\n\tRightTriangle X C P ->\n\tPerp_at P Q A B C.\nProof.\n\tintros P Q A B C X.\n\tintros Col_P_Q_C.\n\tintros Col_A_B_C.\n\tintros Col_A_B_X.\n\tintros RightTriangle_XCP.\n\n\tunfold Perp_at.\n\texists X.\n\trepeat split.\n\texact Col_P_Q_C.\n\texact Col_A_B_C.\n\texact Col_A_B_X.\n\texact RightTriangle_XCP.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_perp_at.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7252079988462461}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\nRequire Import List Bool.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_list finite fin_quotient fin_dec utils_decidable.\n\nFrom Undecidability.TRAKHTENBROT\n  Require Import notations utils decidable.\n\nSet Default Proof Using \"Type\".\n\nSet Implicit Arguments.\n\nLocal Infix \"∊\" := In (at level 70, no associativity).\n\nSection discernable.\n\n  Variable (X : Type).\n\n  Definition discernable x y := exists δ : X -> bool, δ x <> δ y.\n\n  Infix \"≢\" := discernable (at level 70, no associativity).\n\n  Fact discernable_equiv1 x y : x ≢ y <-> exists δ, δ x = true /\\ δ y = false.\n  Proof.\n    split.\n    + intros (f & Hf).\n      case_eq (f x); intros Hx.\n      * exists f; split; auto.\n        now rewrite Hx in Hf; destruct (f y).\n      * exists (fun x => negb (f x)).\n        rewrite Hx in *; split; auto.\n        now destruct (f y).\n    + intros (f & E1 & E2); exists f.\n      now rewrite E1, E2.\n  Qed.\n\n  Definition undiscernable x y := forall δ : X -> bool, δ x = δ y.\n\n  Infix \"≡\" := undiscernable (at level 70, no associativity).\n\n  Fact discernable_undiscernable x y : x ≢ y -> x ≡ y -> False.\n  Proof. intros (f & Hf) H; apply Hf, H. Qed.\n\n  Fact undiscernable_spec x y : x ≡ y <-> ~ x ≢ y.\n  Proof.\n    split.\n    + intros H1 H2; revert H2 H1; apply discernable_undiscernable.\n    + intros H f.\n      destruct (bool_dec (f x) (f y)); auto.\n      destruct H; exists f; auto.\n  Qed.\n\n  Fact undiscernable_refl x : x ≡ x.\n  Proof. red; auto. Qed.\n\n  Fact undiscernable_sym x y : x ≡ y -> y ≡ x.\n  Proof. red; auto. Qed.\n\n  Fact undiscernable_trans x y z : x ≡ y -> y ≡ z -> x ≡ z.\n  Proof. unfold undiscernable; eauto. Qed.\n\n  Fact undiscernable_discrete D (δ : X -> D) x y : discrete D -> x ≡ y -> δ x = δ y.\n  Proof.\n    intros d H.\n    set (g z := if d (δ x) (δ z) then true else false).\n    specialize (H g); unfold g in H.\n    destruct (d (δ x) (δ x)) as [ _ | [] ]; auto.\n    destruct (d (δ x) (δ y)) as [ | ]; easy.\n  Qed.\n\n  Fact discrete_undiscernable_implies_equal x y : discrete X -> x ≡ y -> x = y.\n  Proof. intro; now apply undiscernable_discrete with (δ := fun x => x). Qed.\n\n  Fact undiscernable_Prop_dec x y : x ≡ y -> forall P, (forall x, decidable (P x)) -> P x <-> P y.\n  Proof.\n    intros H P HP.\n    set (f x := if HP x then true else false).\n    specialize (H f); unfold f in H.\n    destruct (HP x); destruct (HP y); try tauto; easy.\n  Qed.\n\n  Hypothesis (H2 : forall x y, decidable (x ≢ y)).\n\n  Fact discernable_dec_undiscernable_dec x y : decidable (x ≡ y).\n  Proof using H2.\n    destruct (H2 x y); [ right | left ]; rewrite undiscernable_spec; tauto.\n  Qed.\n\n  Hint Resolve discernable_dec_undiscernable_dec : core.\n\n  (* There is a simultaneously discerning function for a list l *)\n\n  Definition discriminable_list l := \n    { D & { _ : discrete D & { _ : finite_t D & { δ : X -> D \n             | forall x y, x ∊ l -> y ∊ l -> x ≡ y <-> δ x = δ y } } } }.\n\n  Hint Resolve undiscernable_refl undiscernable_sym undiscernable_trans : core.\n\n  Theorem discernable_discriminable_list l : discriminable_list l. \n  Proof using H2.\n    apply DEC_PER_list_proj_finite_discrete with (l := l) (R := undiscernable).\n    + split; eauto.\n    + red; apply discernable_dec_undiscernable_dec.\n    + intros; auto.\n  Qed.\n\n  (* There is a simultaneously discerning function for a type *)\n\n  Definition discriminable_type := \n    { D & { _ : discrete D & { _ : finite_t D & { δ : X -> D \n             | forall x y, x ≡ y <-> δ x = δ y } } } }.\n\n  Hypothesis (H1 : finite_t X).\n\n  (* undiscernable is equivalent to a equality after mapping on some finite datatype *)\n\n  Theorem finite_discernable_discriminable_type : discriminable_type. \n  Proof using H1 H2.\n    destruct H1 as (l & Hl).\n    destruct discernable_discriminable_list with l\n      as (D & D1 & D2 & f & Hf).\n    exists D, D1, D2, f; intros; eauto.\n  Qed.\n\nEnd discernable.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/TRAKHTENBROT/discernable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7252079877025861}}
{"text": "Open Scope type_scope.\n\nDefinition pair_type   := (fun (x y :Type) => (x * y)).\nDefinition triple_type := (fun (x y z :Type) => (x * y * z)).\nDefinition quad_type   := (fun (x y z w:Type) => (x * y * z * w)).\nDefinition quint_type  := (fun (x y z w v:Type) => (x * y * z * w * v)).\nDefinition sext_type   := (fun (x y z w v u :Type) => (x * y * z * w * v * u)).\nDefinition sept_type   := (fun (x y z w v u t :Type) => (x * y * z * w * v * u * t)).\n\n\nDefinition pair2 := (fun {a} {b} (x:a) (y:b) => (x, y)).\nDefinition pair3 := (fun {a} {b} {c} (x:a) (y:b) (z:c) => (x, y, z)).\nDefinition pair4 := (fun {a} {b} {c} {d} (x:a) (y:b) (z:c) (w:d) => (x, y, z, w)).\nDefinition pair5 := (fun {a} {b} {c} {d} {e}\n                          (x:a) (y:b) (z:c) (w:d) (v:e) => (x, y, z, w,v)).\nDefinition pair6 := (fun {a} {b} {c} {d} {e} {f}\n                          (x:a) (y:b) (z:c) (w:d) (v:e) (u:f) => (x, y, z, w, v,u)).\nDefinition pair7 := (fun {a} {b} {c} {d} {e} {f} {g}\n                          (x:a) (y:b) (z:c) (w:d) (v:e) (u:f) (t:g) =>\n                          (x, y, z, w, v, u, t)).\n\n", "meta": {"author": "antalsz", "repo": "hs-to-coq", "sha": "cd62a35fff22cb6022a8935581746df658264f0f", "save_path": "github-repos/coq/antalsz-hs-to-coq", "path": "github-repos/coq/antalsz-hs-to-coq/hs-to-coq-cd62a35fff22cb6022a8935581746df658264f0f/examples/base-src/manual/GHC/Tuple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7252079861062463}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, ev_ev__ev *)\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_ev__ev : forall n m, ev (n + m) -> ev n -> ev m.\nProof.\n    intros.\n    induction H0.\n    apply H.\n    inversion H. apply IHev in H2. apply H2.\nQed.\n\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter9_Library_Prop/ev_ev__ev.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7251555719001532}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult y (plus Zero lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj305_coqofml_2jcTVC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.7905303236047048, "lm_q1q2_score": 0.7251555683257558}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  plus x (Succ (plus lf2 y)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj185_coqofml_4IFLRp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.7905303137346444, "lm_q1q2_score": 0.7251555628463205}}
{"text": "Require Export Gen.\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\n\nDefinition even_n__even_SSn (n:nat) : Prop :=\n  (even n) -> (even (S (S n))).\n\n\nDefinition true_for_zero (P:nat -> Prop) : Prop :=\n  P 0.\n\nDefinition preserved_by_S (P:nat -> Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\nDefinition our_nat_induction (P:nat->Prop) : Prop :=\n     (true_for_zero P) ->\n     (preserved_by_S P) ->\n     (true_for_all_numbers P).\n\n\nInductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\nInductive good_day : day -> Prop :=\n  | gd_sat : good_day saturday\n  | gd_sun : good_day sunday.\n\nTheorem gds : good_day sunday.\nProof. apply gd_sun. Qed.\n\n\nInductive day_before : day -> day -> Prop :=\n  | db_tue : day_before tuesday monday\n  | db_wed : day_before wednesday tuesday\n  | db_thu : day_before thursday wednesday\n  | db_fri : day_before friday thursday\n  | db_sat : day_before saturday friday\n  | db_sun : day_before sunday saturday\n  | db_mon : day_before monday sunday.\n\nInductive ok_day : day -> Prop :=\n  | okd_gd : forall d,\n      good_day d ->\n      ok_day d\n  | okd_before : forall d1 d2,\n      ok_day d2 ->\n      day_before d2 d1 ->\n      ok_day d1.\n\nTheorem okdw' : ok_day wednesday.\nProof.\n  apply okd_before with (d2:=thursday).\n  apply okd_before with (d2:=friday).\n  apply okd_before with (d2:=saturday).\n  apply okd_gd with (d:=saturday).\n  apply gd_sat.\n  apply db_sat.\n  apply db_fri.\n  apply db_thu.\nQed.\n\nDefinition okd_before2 := forall d1 d2 d3,\n  ok_day d3 ->\n  day_before d2 d1 ->\n  day_before d3 d2 ->\n  ok_day d1.\n\nTheorem okd_before2_valid : okd_before2.\nProof.\n  unfold okd_before2.\n  intros.\n  apply okd_before with (d2:=d2).\n  apply okd_before with (d2:=d3).\n  apply H.\n  apply H1.\n  apply H0.\nQed.\n\nPrint okd_before2_valid.\n\nDefinition okd_before2_valid' : okd_before2 :=\n  fun (d1 d2 d3 : day) =>\n  fun (H : ok_day d3) =>\n  fun (H0 : day_before d2 d1) =>\n  fun (H1 : day_before d3 d2) =>\n  okd_before d1 d2 (okd_before d2 d3 H H1) H0.\n\nPrint okd_before2_valid'.\n\nCheck nat_ind.\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  reflexivity.\n  intros.\n  apply eq_remove_S.\n  apply H.\nQed.\n\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind.\n\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n\n\nInductive ExSet : Type :=\n  | con1 : bool -> ExSet\n  | con2 : nat -> bool -> ExSet.\n\nCheck ExSet_ind.\n\n\nInductive tree (X:Type) : Type :=\n  | leaf : X -> tree X\n  | node : tree X -> tree X -> tree X.\nCheck tree_ind.\n\nInductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  intros.\n  induction n.\n  simpl.\n  apply ev_0.\n  simpl.\n  apply ev_SS.\n  apply IHn.\nQed.\n\n\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  Case \"E = ev_0\".\n  simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\".\n  simpl.\n  apply E'.\nQed.\n\n\nTheorem ev_sum : forall n m,\n   ev n -> ev m -> ev (n+m).\nProof.\n  intros n m E.\n  induction E.\n  simpl.\n  trivial.\n  simpl.\n  intros.\n  apply ev_SS.\n  apply IHE.\n  apply H.\nQed.\n\n\nTheorem SSev_even : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E']. apply E'. Qed.\n\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\n\nTheorem ev_ev_even : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m eq1 eq2.\n  induction eq2.\n  simpl in eq1.\n  apply eq1.\n\n  simpl in eq1.\n  inversion eq1.\n  apply IHeq2.\n  apply H0.\nQed.\n(* reference: https://github.com/flavioc/coq/blob/master/Ind.v *)\n\n\nInductive MyProp : nat -> Prop :=\n  | MyProp1 : MyProp 4\n  | MyProp2 : forall n:nat, MyProp n -> MyProp (4 + n)\n  | MyProp3 : forall n:nat, MyProp (2 + n) -> MyProp n.\n\nTheorem MyProp_0 : MyProp 0.\nProof.\n  apply MyProp3.\n  apply MyProp3.\n  simpl.\n  apply MyProp1.\nQed.\n\nTheorem MyProp_plustwo : forall n:nat, MyProp n -> MyProp (S (S n)).\nProof.\n  intros.\n  apply MyProp3.\n  simpl.\n  apply MyProp2.\n  apply H.\nQed.\n\n\nTheorem MyProp_ev : forall n:nat,\n  ev n -> MyProp n.\nProof.\n  intros n E.\n  induction E as [| n' E'].\n  Case \"E = ev_0\".\n    apply MyProp_0.\n  Case \"E = ev_SS n' E'\".\n    apply MyProp_plustwo. apply IHE'. Qed.\n\n\nTheorem ev_MyProp : forall n:nat,\n  MyProp n -> ev n.\nProof.\n  intros.\n  induction H.\n  apply ev_SS. apply ev_SS. apply ev_0.\n  apply ev_SS. apply ev_SS. apply IHMyProp.\n  simpl in IHMyProp.\n  apply ev_minus2 in IHMyProp.\n  simpl in IHMyProp.\n  apply IHMyProp.\nQed.\n", "meta": {"author": "egejjespersen", "repo": "software_foundation_exercise", "sha": "e2f788ff88b4b6a6cefc3f413e646c8a733232b2", "save_path": "github-repos/coq/egejjespersen-software_foundation_exercise", "path": "github-repos/coq/egejjespersen-software_foundation_exercise/software_foundation_exercise-e2f788ff88b4b6a6cefc3f413e646c8a733232b2/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.725019270246377}}
{"text": "(* ====================== *)\n(* ===== CH01_ccw.v ===== *)\n(* ====================== *)\n\nRequire Export Jordan5.\n\nOpen Scope R_scope.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nDefinition det (p q r : point) : R :=\n  (fst p * snd q) - (fst q * snd p) - (fst p * snd r) + (fst r * snd p) +\n  (fst q * snd r) - (fst r * snd q).\n\nLemma eq_det : forall (p q r : point),\n  det p q r = det q r p.\nProof.\nintros p q r.\nunfold det; ring.\nQed.\n\nLemma neq_det : forall (p q r : point),\n  det p q r = - det p r q.\nProof.\nintros p q r.\nunfold det; ring.\nQed.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nDefinition ccw (p q r : point) : Prop :=\n  (det p q r > 0).\n\nLemma ccw_dec : forall (p q r : point),\n  {ccw p q r} + {~ ccw p q r}.\nProof.\nintros p q r.\nunfold ccw; apply Rgt_dec.\nQed.\n\n(* ======= ####### ======= *)\n\nDefinition align (p q r : point) : Prop :=\n  (det p q r = 0).\n\nLemma align_dec : forall (p q r : point),\n  {align p q r} + {~align p q r}.\nProof.\nintros p q r.\nunfold align.\ngeneralize (total_order_T (det p q r) 0).\ngeneralize (Rlt_dichotomy_converse (det p q r) 0).\ntauto.\nQed.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nLemma Rle_neq_lt : forall (r1 r2 : R),\n  r1 <= r2 -> r1 <> r2 -> r1 < r2.\nProof.\nintros r1 r2 H1 H2.\nelim (Rdichotomy r1 r2).\ntrivial.\ngeneralize (Rle_not_lt r2 r1).\ntauto.\nassumption.\nQed.\n\nLemma R_gt_0_plus : forall (r1 r2 : R),\n  r1 > 0 -> r2 > 0 -> r1 + r2 > 0.\nProof.\nintros r1 r2 H1 H2.\napply Rgt_trans with r1.\n pattern r1 at 2; rewrite <- (Rplus_0_r r1).\n apply Rplus_gt_compat_l; assumption.\nassumption.\nQed.\n\nLemma R_gt_0_mult : forall (r1 r2 : R),\n  r1 > 0 -> r2 > 0 -> r1 * r2 > 0.\nProof.\napply Rmult_gt_0_compat.\nQed.\n\nLemma R_gt_0_div : forall (r1 r2 : R),\n  r1 > 0 -> r2 > 0 -> r1 * / r2 > 0.\nProof.\nintros r1 r2 H1 H2.\napply R_gt_0_mult.\n assumption.\n unfold Rgt in *; auto with real.\nQed.\n\nLemma R_mult_div : forall (r1 r2 r3 : R),\n  r1 = r2 * r3 -> r2 > 0 -> r1 * / r2 = r3.\nProof.\nintros r1 r2 r3 H1 H2.\nsubst r1; auto with real.\nQed.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nLemma axiom_orientation_1 :\n  forall (A:point)(B:point)(C:point),\n  ccw A B C -> ccw B C A.\nProof.\nintros A B C.\nunfold ccw; rewrite eq_det; trivial.\nQed.\n\nLemma axiom_orientation_2 :\n  forall (A:point)(B:point)(C:point),\n  align A B C -> align B C A.\nProof.\nintros A B C.\nunfold align; rewrite eq_det; trivial.\nQed.\n\nLemma axiom_orientation_3 :\n  forall (A:point)(B:point)(C:point),\n  align A B C -> align A C B.\nProof.\nintros A B C.\nunfold align; rewrite neq_det.\ngeneralize (Rplus_opp_r (det A C B)).\ngeneralize (Rplus_0_l (det A C B)).\nintros H1 H2 H3.\nrewrite H3 in H2; clear H3.\nrewrite Rplus_comm in H1.\nrewrite H1 in H2; clear H1.\nassumption.\nQed.\n\nHint Resolve axiom_orientation_1 axiom_orientation_2 axiom_orientation_3 : myorientation.\n\n(* ======================= *)\n\nLemma axiom_orientation_4 :\n  forall (A:point)(B:point)(C:point),\n  ccw A B C -> ~ ccw A C B.\nProof.\nintros A B C.\nunfold ccw; rewrite neq_det.\ngeneralize (Ropp_gt_lt_contravar (- det A C B) 0).\nrewrite Ropp_involutive; rewrite Ropp_0.\nintro H1; generalize (Rlt_le (det A C B) 0).\nintro H2; generalize (Rle_not_lt 0 (det A C B)).\nintro H3; tauto.\nQed.\n\nLemma axiom_orientation_5 :\n  forall (A:point)(B:point)(C:point),\n  ccw A B C -> ~ align A B C.\nProof.\nintros A B C.\nunfold ccw, align in *.\napply Rgt_not_eq; assumption.\nQed.\n\nLemma axiom_orientation_6 :\n  forall (A:point)(B:point)(C:point),\n  align A B C -> ~ ccw A B C.\nProof.\nintros A B C.\nunfold ccw, align in *.\nintro H1; rewrite H1.\nunfold not; intro H2.\napply Rgt_not_eq in H2; tauto.\nQed.\n\nHint Resolve axiom_orientation_4 axiom_orientation_5 axiom_orientation_6 : myorientation.\n\n(* ======================= *)\n\nLemma axiom_orientation_7 :\n  forall (A:point)(B:point)(C:point),\n  ~ ccw A B C -> ccw A C B \\/ align A B C.\nProof.\nintros A B C H.\nelim (ccw_dec A C B).\n intro H1; left; assumption.\n intro H1; right.\n unfold ccw, align in *.\n rewrite neq_det in H1.\n apply Rle_antisym.\n  apply Rnot_gt_le; assumption.\n  apply Rnot_gt_le; auto with real.\nQed.\n\nLemma axiom_orientation_8 :\n  forall (A:point)(B:point)(C:point),\n  ~ align A B C -> ccw A B C \\/ ccw A C B.\nProof.\nintros A B C H.\nelim (ccw_dec A B C).\n intro H0; left; assumption.\n intro H0; right.\n apply axiom_orientation_7 in H0.\n elim H0; [trivial|contradiction].\nQed.\n\nHint Resolve axiom_orientation_7 axiom_orientation_8 : myorientation.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nLemma ccw_axiom_1 : forall (p q r : point),\n  ccw p q r -> ccw q r p.\nProof.\nauto with myorientation.\nQed.\n\nLemma ccw_axiom_2 : forall (p q r : point),\n  ccw p q r -> ~ ccw p r q.\nProof.\nauto with myorientation.\nQed.\n\nLemma ccw_axiom_3 : forall (p q r : point),\n  ~ align p q r -> (ccw p q r) \\/ (ccw p r q).\nProof.\nauto with myorientation.\nQed.\n\nLemma ccw_axiom_4 : forall (p q r t : point),\n  (ccw t q r) -> (ccw p t r) -> (ccw p q t) -> (ccw p q r).\nProof.\nintros p q r t H1 H2 H3.\nunfold ccw in *.\nassert (det t q r + det p t r + det p q t = det p q r).\nunfold det; ring.\nrewrite <- H.\napply R_gt_0_plus; [apply R_gt_0_plus; assumption | assumption].\nQed.\n\nLemma ccw_axiom_5 : forall (p q r s t : point),\n  (ccw t s p) -> (ccw t s q) -> (ccw t s r) -> (ccw t p q) -> (ccw t q r) -> \n  (ccw t p r).\nProof.\nintros p q r s t H1 H2 H3 H4 H5.\nunfold ccw in *.\nreplace (det t p r) with ((det t p q * det t s r + det t q r * det t s p) * / (det t s q)).\napply R_gt_0_div.\n apply R_gt_0_plus.\n  apply R_gt_0_mult; assumption.\n  apply R_gt_0_mult; assumption.\n assumption.\napply R_mult_div.\n unfold det; ring.\n assumption.\nQed.\n\nLemma ccw_axiom_5_bis : forall (p q r s t : point),\n  (ccw s t p) -> (ccw s t q) -> (ccw s t r) -> (ccw t p q) -> (ccw t q r) -> \n  (ccw t p r).\nProof.\nintros p q r s t H1 H2 H3 H4 H5.\nunfold ccw in *.\nreplace (det t p r) with ((det t p q * det s t r + det t q r * det s t p) * / (det s t q)).\napply R_gt_0_div.\n apply R_gt_0_plus.\n  apply R_gt_0_mult; assumption.\n  apply R_gt_0_mult; assumption.\n assumption.\napply R_mult_div.\n unfold det; ring.\n assumption.\nQed.\n", "meta": {"author": "magaud", "repo": "ConvexHullV1", "sha": "25c4f9e2989c5c41ee31097a164014c0a6727498", "save_path": "github-repos/coq/magaud-ConvexHullV1", "path": "github-repos/coq/magaud-ConvexHullV1/ConvexHullV1-25c4f9e2989c5c41ee31097a164014c0a6727498/CH01_ccw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7249875254257926}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus y (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj2510_coqofml_kNmApu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7249875215876347}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** Properties of arbitrary binary relations (not necessarily decidable) *)\n(** A functional or deterministic relation *)\nDefinition functional {X : Type} (R : X -> X -> Prop) : Prop :=\n  forall (s s1 s2 : X), R s s1 -> R s s2 -> s1 = s2.\n\nLemma func1 :\n  functional (fun x y => x.*2 == y).\nAdmitted.\n\nLemma func2 :\n  ~ functional (fun x y => (x.*2 == y) || ((x, y) == (0,1))).\nAdmitted.\n\n\n(** Define a notation such that {In C, functional R} restricts the domain of the relation like so:\n\n  forall (s s1 s2 : X), C s -> R s s1 -> R s s2 -> s1 = s2\n\nAnd prove the following lemma:\n*)\n(* Notation \"{ 'In' C , P }\" := *)\n(*   (...) (at level 0). *)\n\nLemma func3 :\n  {In (fun n => 0 < n), functional (fun x y => (x.*2 == y) || ((x, y) == (0,1)))}.\nAdmitted.\n\n\n(* prove without using [case] or [elim] tactics *)\nLemma Peirce p q : ((p ==> q) ==> p) ==> p.\nAdmitted.\n\n\n(* prove without using [case] or [elim] tactics *)\nLemma addb_neq12 p q :  ~~ p = q -> p (+) q.\nAdmitted.\n\n\nLemma div_fact_plus1 m p : 1 < p -> p %| m `! + 1 -> m < p.\nAdmitted.\n\n\n(* Prove [8x = 6y + 1] has no solutions in [nat] *)\nLemma no_solution x y :\n  8*x != 6*y + 1.\nAdmitted.\n\n\n\nLemma iota_add m n1 n2 :\n  iota m (n1 + n2) = iota m n1 ++ iota (m + n1) n2.\nAdmitted.\n\nDefinition mysum m n F := (foldr (fun i a => F i + a) 0 (iota m (n - m))).\n\n(* \"big\" operator *)\nNotation \"\\mysum_ ( m <= i < n ) F\" := (mysum m n (fun i => F))\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\mysum_ ( m  <=  i  <  n ) '/  '  F ']'\").\n\nLemma mysum_recl m n F :\n  m <= n ->\n  \\mysum_(m <= i < n.+1) F i = \\mysum_(m <= i < n) F i + F n.\nAdmitted.\n\nLemma sum_odds n :\n  \\mysum_(0 <= i < n) (2 * i + 1) = n ^ 2.\nAdmitted.\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/hw07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7249875136228604}}
{"text": "Inductive natlist : Type :=\n\t| nil : natlist\n\t| cons : nat -> natlist -> natlist.\n\nInductive source_expr : Type :=\n\t| n : source_expr\n\t| expr : source_expr -> source_expr -> source_expr.\n\nInductive instr : Type :=\n\t| pop : instr\n\t| push : nat -> instr.\n\nInductive instrlist : Type :=\n\t| empty : instrlist\n\t| build : instr -> instrlist -> instrlist.\n\nDefinition pop_stack (s : natlist) : natlist :=\n\tmatch s with\n\t\t| nil => nil\n\t\t| cons h (cons h' t) => cons (h + h') t\n\t\t| _ => s\nend.\n\nFixpoint execute (lst : instrlist) (stack : natlist) : natlist :=\n\tmatch lst with\n\t\t| empty => stack \n\t\t| build h t => match h with\n\t\t\t| (push n') => execute t (cons n' stack)\n\t\t\t| pop => execute t (pop_stack stack)\n\t\tend\nend.\n\nExample test_execute1 : execute (build (push 5) empty) nil = cons 5 nil.\nProof. reflexivity. Qed.\n\nExample test_execute2 : execute (build (push 5) (build (push 3) (build pop empty))) nil = cons 8 nil.\nProof. reflexivity. Qed.\n\nExample test_execute3 : execute (build pop empty) (cons 1 (cons 2 nil)) = cons 3 nil.\nProof. reflexivity. Qed.\n", "meta": {"author": "erwanor", "repo": "stack-compiler", "sha": "da2b6b7b6b9d2653526ba1f6a928a6139995f362", "save_path": "github-repos/coq/erwanor-stack-compiler", "path": "github-repos/coq/erwanor-stack-compiler/stack-compiler-da2b6b7b6b9d2653526ba1f6a928a6139995f362/compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7249875108384063}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (x : natural) : natural :=\n  mult (Succ y) (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj152_coqofml_3ycyjA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.7249831596466639}}
{"text": "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. \nProof. \n    intros f. \n    intros H. \n    intros b. \n    rewrite <- H.\n    rewrite <- H.\n    reflexivity. \nQed.\n", "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/basics/exercises/identity_fn_applied_twice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7249569129543485}}
{"text": "Require Import FormalSystem Translation Classical\n        EqualityArithmetic.\n\n(* -------------------------- *)\n(*Consistency of PA via that of HA*)\n\n(*Question 5.1.1*)\n(*Interpretation of formulae as types of Coq (in the universe Prop)*)\nFixpoint intf f : Prop :=\n  match f with\n  | Tr => True\n  | Fa => False\n  | And g h => intf g /\\ intf h\n  | Or g h => intf g \\/ intf h\n  | Impl g h => intf g -> intf h\n  | @All A P => forall x:A, intf (P x)\n  | @Ex A P => exists x:A, intf (P x)\n  | Atom p => p\n  end.\n\n\n(*Question 5.2.1*)\n(*The soundness of the interpretation --- all derivable judgments L ⊢ f are valid, i.e., the type corresponding to the conclusion is inhabited when those corresponding to the premisses are inhabited.*)\nLemma intf_soundness (L:_->Prop) f:\n  (forall g, L g -> intf g) ->\n  L ⊢ f -> intf f.\nProof.\n  intros H' H. induction H; simpl in *; try auto.\n  - exfalso. apply IHderiv, H'.\n  - intro. apply IHderiv. intros g0 H1. case H1.\n    + apply H'.\n    + intro H2. rewrite H2. assumption.\n  - apply IHderiv, H'.\n  - apply IHderiv, H'.\n  - case IHderiv1. apply H'.\n    + intro. apply IHderiv2. intros g0 H1'. case H1'.\n      * apply H'.\n      * intro H1''. rewrite H1''. assumption.\n    + intro. apply IHderiv3. intros g0 H1'. case H1'.\n      * apply H'.\n      * intro H1''. rewrite H1''. assumption.\n  - exists t. auto.\n  - destruct IHderiv.\n    + assumption.\n    + apply (H0 x). intros g H''. case H''.\n      * apply H'.\n      * intro H3. rewrite H3. exact H2.\nQed.\n\n\n(*Question 5.3.1*)\n(*The interpretation of the theory E A holds for any type A*)\nLemma intf_E A f:\n  E A f ->\n  intf f.\nProof.\n  intro H; case H; simpl in *.\n  + reflexivity.\n  + symmetry. assumption.\n  + intros. transitivity y; assumption.\nQed.\n\n(*The same for the theory A*)\nLemma intf_A f:\n  A f ->\n  intf f.\nProof.\n  intro H; case H; simpl in *.\n  + apply O_S.\n  + apply eq_add_S.\n  + intros P. apply (nat_ind (fun x => intf (P x))).\nQed.\n\n\n(*Question 5.4.1*)\n(*Consistency of HA*)\nLemma HA_consistency :\n  ~ (Ø ⊢ₕ Fa).\nProof.\n  intro.\n  apply (intf_soundness (Ø ⋃ HA) Fa).\n  - destruct 1.\n    + exfalso. apply H0.\n    + destruct H0. apply intf_A. assumption.\n      apply (intf_E nat). assumption.\n  - assumption.\nQed.      \n\n(*Consistency of PA via that of HA*)\nLemma PA_consistency :\n  ~ (Ø ⊢ₚ Fa).\nProof.\n  intro.\n  assert (Ø ⊢ₕ Fa).\n  - apply (deriv_substitution (nnt_ctx Ø ⋃ HA)).\n    + apply (nnt_ha Ø Fa). assumption.\n    + intros. destruct H0.\n      * destruct H0 as [g [H' H'']]. exfalso. apply H'.\n      * apply ax; right; assumption.\n  - apply HA_consistency. assumption.\nQed.\n\n\n(*Fin*)", "meta": {"author": "huevosybacon", "repo": "mpri-272-exo1", "sha": "439b3065e6b7190836f24ed506c63c3c29c6483b", "save_path": "github-repos/coq/huevosybacon-mpri-272-exo1", "path": "github-repos/coq/huevosybacon-mpri-272-exo1/mpri-272-exo1-439b3065e6b7190836f24ed506c63c3c29c6483b/Consistency.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7249240629461979}}
{"text": "Require Import init.\n\nRequire Export plus_group.\nRequire Export mult_ring.\n\nRequire Import set.\nRequire Import unordered_list.\n\n#[universes(template)]\nRecord Ideal U `{Plus U, Mult U} := make_ideal {\n    ideal_set : U → Prop;\n    ideal_nempty : ∃ a, ideal_set a;\n    ideal_plus : ∀ a b, ideal_set a → ideal_set b → ideal_set (a + b);\n    ideal_lmult : ∀ a b, ideal_set b → ideal_set (a * b);\n    ideal_rmult : ∀ a b, ideal_set a → ideal_set (a * b);\n}.\nArguments make_ideal {U H H0}.\nArguments ideal_set {U H H0}.\nArguments ideal_nempty {U H H0}.\nArguments ideal_plus {U H H0}.\nArguments ideal_lmult {U H H0}.\nArguments ideal_rmult {U H H0}.\n\nTheorem ideal_eq_set {U} `{Plus U, Mult U} : ∀ I J : Ideal U,\n    ideal_set I = ideal_set J → I = J.\nProof.\n    intros [I_set I_nempty I_plus I_lmult I_rmult]\n           [J_set J_nempty J_plus J_lmult J_rmult] eq.\n    cbn in eq.\n    subst J_set.\n    rewrite (proof_irrelevance J_nempty I_nempty).\n    rewrite (proof_irrelevance J_plus I_plus).\n    rewrite (proof_irrelevance J_lmult I_lmult).\n    rewrite (proof_irrelevance J_rmult I_rmult).\n    reflexivity.\nQed.\n\nTheorem ideal_eq {U} `{Plus U, Mult U} : ∀ I J : Ideal U,\n    (∀ x, ideal_set I x ↔ ideal_set J x) → I = J.\nProof.\n    intros I J eq.\n    apply ideal_eq_set.\n    apply predicate_ext.\n    exact eq.\nQed.\n\n(* begin hide *)\nSection RingIdeal.\n\nContext {U} `{\n    UP : Plus U,\n    UZ : Zero U,\n    UN : Neg U,\n    UM : Mult U,\n    UO : One U,\n    @PlusAssoc U UP,\n    @PlusComm U UP,\n    @PlusLid U UP UZ,\n    @PlusLinv U UP UZ UN,\n    @Ldist U UP UM,\n    @Rdist U UP UM,\n    @MultAssoc U UM,\n    @MultComm U UM,\n    @MultLid U UM UO,\n    @MultRid U UM UO\n}.\n\n(* end hide *)\nVariable I : Ideal U.\n\nTheorem ideal_neg : ∀ a, ideal_set I a → ideal_set I (-a).\nProof.\n    intros a a_in.\n    rewrite <- mult_neg_one.\n    apply ideal_lmult.\n    exact a_in.\nQed.\n\nTheorem ideal_zero : ideal_set I 0.\nProof.\n    pose proof (ideal_nempty I) as [a a_in].\n    rewrite <- (plus_linv a).\n    apply ideal_plus.\n    1: apply ideal_neg.\n    all: exact a_in.\nQed.\n\nLet ideal_eq a b := ideal_set I (a - b).\nLocal Infix \"~\" := ideal_eq : algebra_scope.\n\nLemma ideal_eq_reflexive : ∀ a, a ~ a.\nProof.\n    intros a.\n    unfold ideal_eq.\n    rewrite plus_rinv.\n    apply ideal_zero.\nQed.\nInstance ideal_eq_reflexive_class : Reflexive _ := {\n    refl := ideal_eq_reflexive\n}.\n\nLemma ideal_eq_symmetric : ∀ a b, a ~ b → b ~ a.\nProof.\n    unfold ideal_eq.\n    intros a b ab.\n    apply ideal_neg in ab.\n    rewrite neg_plus in ab.\n    rewrite neg_neg in ab.\n    rewrite plus_comm in ab.\n    exact ab.\nQed.\nInstance ideal_eq_symmetric_class : Symmetric _ := {\n    sym := ideal_eq_symmetric\n}.\n\nLemma ideal_eq_transitive : ∀ a b c, a ~ b → b ~ c → a ~ c.\nProof.\n    unfold ideal_eq.\n    intros a b c ab bc.\n    pose proof (ideal_plus I _ _ ab bc) as eq.\n    rewrite plus_assoc in eq.\n    rewrite plus_rlinv in eq.\n    exact eq.\nQed.\nInstance ideal_eq_transitive_class : Transitive _ := {\n    trans := ideal_eq_transitive\n}.\n\nDefinition ideal_equiv := make_equiv _ ideal_eq_reflexive_class\n    ideal_eq_symmetric_class ideal_eq_transitive_class.\n\nDefinition quotient_ring := equiv_type ideal_equiv.\nDefinition to_qring a := to_equiv ideal_equiv a.\n\n(* begin show *)\nLocal Infix \"~\" := (eq_equal ideal_equiv).\n(* end show *)\n\nLemma qring_plus_wd : ∀ a b c d, a ~ b → c ~ d → a + c ~ b + d.\nProof.\n    cbn; unfold ideal_eq.\n    intros a b c d ab cd.\n    rewrite neg_plus.\n    rewrite <- plus_assoc.\n    rewrite (plus_assoc c).\n    rewrite (plus_comm c).\n    do 2 rewrite plus_assoc.\n    rewrite <- plus_assoc.\n    apply ideal_plus; assumption.\nQed.\n\nInstance quotient_ring_plus : Plus quotient_ring := {\n    plus := binary_op (binary_self_wd qring_plus_wd)\n}.\n\nProgram Instance quotient_ring_plus_assoc : PlusAssoc quotient_ring.\nNext Obligation.\n    equiv_get_value a b c.\n    unfold plus; equiv_simpl.\n    rewrite plus_assoc.\n    reflexivity.\nQed.\n\nProgram Instance quotient_ring_plus_comm : PlusComm quotient_ring.\nNext Obligation.\n    equiv_get_value a b.\n    unfold plus; equiv_simpl.\n    rewrite plus_comm.\n    reflexivity.\nQed.\n\nInstance quotient_ring_zero : Zero quotient_ring := {\n    zero := to_equiv ideal_equiv 0\n}.\n\nProgram Instance quotient_ring_plus_lid : PlusLid quotient_ring.\nNext Obligation.\n    equiv_get_value a.\n    unfold zero, plus; equiv_simpl.\n    rewrite plus_lid.\n    reflexivity.\nQed.\n\nLemma qring_neg_wd : ∀ a b, a ~ b → -a ~ -b.\nProof.\n    cbn; unfold ideal_eq.\n    intros a b eq.\n    rewrite <- neg_plus.\n    apply ideal_neg.\n    exact eq.\nQed.\nInstance quotient_ring_neg : Neg quotient_ring := {\n    neg := unary_op (unary_self_wd qring_neg_wd)\n}.\n\nProgram Instance quotient_ring_plus_linv : PlusLinv quotient_ring.\nNext Obligation.\n    equiv_get_value a.\n    unfold plus, neg, zero; equiv_simpl.\n    rewrite plus_linv.\n    reflexivity.\nQed.\n\nLemma qring_mult_wd : ∀ a b c d, a ~ b → c ~ d → a * c ~ b * d.\nProof.\n    cbn; unfold ideal_eq.\n    intros a b c d ab cd.\n    rewrite <- (plus_llinv (-(b * d)) (b * c)).\n    rewrite plus_assoc.\n    apply ideal_plus.\n    -   rewrite <- mult_lneg.\n        rewrite <- rdist.\n        apply ideal_rmult.\n        exact ab.\n    -   rewrite <- mult_rneg.\n        rewrite <- ldist.\n        apply ideal_lmult.\n        exact cd.\nQed.\n\nInstance quotient_ring_mult : Mult quotient_ring := {\n    mult := binary_op (binary_self_wd qring_mult_wd)\n}.\n\nProgram Instance quotient_ring_ldist : Ldist quotient_ring.\nNext Obligation.\n    equiv_get_value a b c.\n    unfold plus, mult; equiv_simpl.\n    rewrite ldist.\n    reflexivity.\nQed.\n\nProgram Instance quotient_ring_rdist : Rdist quotient_ring.\nNext Obligation.\n    equiv_get_value a b c.\n    unfold plus, mult; equiv_simpl.\n    rewrite rdist.\n    reflexivity.\nQed.\n\nProgram Instance quotient_ring_mult_assoc : MultAssoc quotient_ring.\nNext Obligation.\n    equiv_get_value a b c.\n    unfold mult; equiv_simpl.\n    rewrite mult_assoc.\n    reflexivity.\nQed.\n\nProgram Instance quotient_ring_mult_comm : MultComm quotient_ring.\nNext Obligation.\n    equiv_get_value a b.\n    unfold mult; equiv_simpl.\n    rewrite mult_comm.\n    reflexivity.\nQed.\n\nInstance quotient_ring_one : One quotient_ring := {\n    one := to_equiv ideal_equiv 1\n}.\n\nProgram Instance quotient_ring_mult_lid : MultLid quotient_ring.\nNext Obligation.\n    equiv_get_value a.\n    unfold one, mult; equiv_simpl.\n    rewrite mult_lid.\n    reflexivity.\nQed.\n\nProgram Instance quotient_ring_mult_rid : MultRid quotient_ring.\nNext Obligation.\n    equiv_get_value a.\n    unfold one, mult; equiv_simpl.\n    rewrite mult_rid.\n    reflexivity.\nQed.\n\nTheorem to_qring_plus : ∀ a b, to_qring (a + b) = to_qring a + to_qring b.\nProof.\n    intros a b.\n    unfold plus at 2, to_qring; equiv_simpl.\n    apply ideal_eq_reflexive.\nQed.\n\nTheorem to_qring_zero : to_qring 0 = 0.\nProof.\n    reflexivity.\nQed.\n\nTheorem to_qring_neg : ∀ a, to_qring (-a) = -to_qring a.\nProof.\n    intros a.\n    unfold neg at 2, to_qring; equiv_simpl.\n    apply ideal_eq_reflexive.\nQed.\n\nTheorem to_qring_mult : ∀ a b, to_qring (a * b) = to_qring a * to_qring b.\nProof.\n    intros a b.\n    unfold mult at 2, to_qring; equiv_simpl.\n    apply ideal_eq_reflexive.\nQed.\n\nTheorem to_qring_one : to_qring 1 = 1.\nProof.\n    reflexivity.\nQed.\n\n(* begin hide *)\nEnd RingIdeal.\n\nSection IdealGenerated.\n\nContext {U} `{\n    UP : Plus U,\n    UZ : Zero U,\n    UN : Neg U,\n    UM : Mult U,\n    UO : One U,\n    @PlusAssoc U UP,\n    @PlusComm U UP,\n    @PlusLid U UP UZ,\n    @PlusLinv U UP UZ UN,\n    @Ldist U UP UM,\n    @Rdist U UP UM,\n    @MultAssoc U UM,\n    @MultLid U UM UO,\n    @MultRid U UM UO\n}.\n\n(* end hide *)\nVariable S : U → Prop.\n\nDefinition ideal_generated_by_set x := ∃ l : ulist ((U * U) * set_type S),\n    x = ulist_sum (ulist_image (λ p, fst (fst p) * [snd p|] * snd (fst p)) l).\n\nLemma ideal_generated_by_nempty : ∃ x, ideal_generated_by_set x.\nProof.\n    exists 0.\n    exists ulist_end.\n    rewrite ulist_image_end, ulist_sum_end.\n    reflexivity.\nQed.\n\nLemma ideal_generated_by_plus : ∀ a b,\n    ideal_generated_by_set a → ideal_generated_by_set b →\n    ideal_generated_by_set (a + b).\nProof.\n    intros a b [al al_eq] [bl bl_eq]; subst a b.\n    exists (al + bl).\n    rewrite ulist_image_conc, ulist_sum_plus.\n    reflexivity.\nQed.\n\nLemma ideal_generated_by_lmult : ∀ a b,\n    ideal_generated_by_set b → ideal_generated_by_set (a * b).\nProof.\n    intros a b [l l_eq]; subst b.\n    exists (ulist_image (λ p, ((a * fst (fst p), snd (fst p)), snd p)) l).\n    rewrite ulist_image_comp.\n    cbn.\n    induction l as [|b l] using ulist_induction.\n    -   do 2 rewrite ulist_image_end, ulist_sum_end.\n        apply mult_ranni.\n    -   do 2 rewrite ulist_image_add, ulist_sum_add.\n        rewrite ldist.\n        rewrite IHl.\n        apply rplus.\n        do 2 rewrite mult_assoc.\n        reflexivity.\nQed.\n\nLemma ideal_generated_by_rmult : ∀ a b,\n    ideal_generated_by_set a → ideal_generated_by_set (a * b).\nProof.\n    intros a b [l l_eq]; subst a.\n    exists (ulist_image (λ p, ((fst (fst p), snd (fst p) * b), snd p)) l).\n    rewrite ulist_image_comp.\n    cbn.\n    induction l as [|a l] using ulist_induction.\n    -   do 2 rewrite ulist_image_end, ulist_sum_end.\n        apply mult_lanni.\n    -   do 2 rewrite ulist_image_add, ulist_sum_add.\n        rewrite rdist.\n        rewrite IHl.\n        apply rplus.\n        rewrite mult_assoc.\n        reflexivity.\nQed.\n\nDefinition ideal_generated_by := make_ideal\n    ideal_generated_by_set\n    ideal_generated_by_nempty\n    ideal_generated_by_plus\n    ideal_generated_by_lmult\n    ideal_generated_by_rmult.\n(* begin hide *)\n\nEnd IdealGenerated.\n(* end hide *)\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Algebra/Ring/ring_ideal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7248705808613173}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Testbit.\n\nRequire Import Crypto.Util.ZUtil.Tactics.SolveTestbit.\n\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma ones_from_spec m k i\n        (Hk : 0 <= k) :\n    Z.testbit (Z.ones_from m k) i = if (i <? 0) then false else ((m - k) <=? i) && (i <? m).\n  Proof. unfold Z.ones_from; Z.solve_testbit. Qed.\n\n  Lemma ones_from_spec_full m k i :\n    Z.testbit (Z.ones_from m k) i = if (i <? 0) then false else ((m - k) <=? i) && ((i <? m) || (k <? 0)).\n  Proof. unfold Z.ones_from; Z.solve_testbit. Qed.\n\n#[global]\n  Hint Rewrite ones_from_spec : testbit_rewrite.\n\n  Lemma ones_from_0 m : Z.ones_from m 0 = 0.\n  Proof. Z.solve_using_testbit. Qed.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/OnesFrom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7248705778859473}}
{"text": "(* Close Scope nat_scope. *)\n\nRequire Import ZArith.\n\n(* SearchAbout \"int\". *)\n(* Import Z_as_Int. *)\n(* Import Int. *)\n\nOpen Scope Z_scope.\n\nDefinition int := Z.\n\nCheck (fun x y => x + y).\n\nInductive Value : Set :=\n| V_Int  : int  -> Value\n| V_Bool : bool -> Value\n.\n\nInductive Prim : Set :=\n| P_Plus\n| P_Minus\n| P_Times\n| P_LT\n.\n\nInductive Exp : Set :=\n| EX_Int  : int  -> Exp\n| EX_Bool : bool -> Exp\n| EX_Prim : Prim -> Exp -> Exp -> Exp\n| EX_If   : Exp -> Exp -> Exp -> Exp\n.\n\nPrint Exp_ind.\n\n\nInductive Plus : Value -> Value -> Value -> Prop :=\n| B_Plus  : forall i1 i2 i3 : int,\n              i1 + i2 = i3 -> Plus (V_Int i1) (V_Int i2) (V_Int i3).\n\nNotation \"i1 'plus' i2 'is' i3\" :=\n  (Plus i1 i2 i3) (at level 31, left associativity).\n\nInductive Minus : Value -> Value -> Value -> Prop :=\n| B_Minus : forall i1 i2 i3 : int,\n              i1 - i2 = i3 -> Minus (V_Int i1) (V_Int i2) (V_Int i3).\n\nNotation \"i1 'minus' i2 'is' i3\" :=\n  (Minus i1 i2 i3) (at level 31, left associativity).\n\nInductive Times : Value -> Value -> Value -> Prop :=\n| B_Times : forall i1 i2 i3 : int,\n              i1 * i2 = i3 -> Times (V_Int i1) (V_Int i2) (V_Int i3).\n\nNotation \"i1 'times' i2 'is' i3\" :=\n  (Times i1 i2 i3) (at level 31, left associativity).\n\nCheck Z.compare.\nPrint comparison.\n\nDefinition Zlt x y :=\n  match Z.compare x y with\n    | Lt => true\n    | Eq => false\n    | Gt => false\n  end.\n\nInductive LT : Value -> Value -> Value -> Prop :=\n| B_LT : forall (i1 i2 : int) (b : bool),\n           (Zlt i1 i2) = b -> LT (V_Int i1) (V_Int i2) (V_Bool b).\n\nNotation \"i1 'less' 'than' i2 'is' b3\" :=\n  (LT i1 i2 b3) (at level 31, left associativity).\n\n(* Inductive LT : Value -> *)\n\nInfix \"+!\" := (EX_Prim P_Plus) (at level 51, left associativity).\n\nInfix \"-!\" := (EX_Prim P_Minus) (at level 51, left associativity).\n\nInfix \"*!\" := (EX_Prim P_Times) (at level 41, left associativity).\n\nInfix \"<!\" := (EX_Prim P_LT) (at level 61, left associativity).\n\nReserved Notation \"e '||!' v\" (at level 71, left associativity).\n\nInductive Eval1 : Exp -> Value -> Prop :=\n| E_Int   : forall i, EX_Int i ||! V_Int i\n| E_Bool  : forall b, EX_Bool b ||! V_Bool b\n| E_IfT   : forall e1 e2 e3 v,\n              e1 ||! V_Bool true ->\n              e2 ||! v ->\n              EX_If e1 e2 e3 ||! v\n| E_IfF   : forall e1 e2 e3 v,\n              e1 ||! V_Bool false ->\n              e3 ||! v ->\n              EX_If e1 e2 e3 ||! v\n| E_Plus  : forall e1 e2 i1 i2 i3,\n              e1 ||! i1 ->\n              e2 ||! i2 ->\n              i1 plus i2 is i3 ->\n              e1 +! e2 ||! i3\n| E_Minus : forall e1 e2 i1 i2 i3,\n              e1 ||! i1 ->\n              e2 ||! i2 ->\n              i1 minus i2 is i3 ->\n              e1 -! e2 ||! i3\n| E_Times : forall e1 e2 i1 i2 i3,\n              e1 ||! i1 ->\n              e2 ||! i2 ->\n              i1 times i2 is i3 ->\n              e1 *! e2 ||! i3\n| E_LT    : forall e1 e2 i1 i2 b3,\n              e1 ||! i1 ->\n              e2 ||! i2 ->\n              i1 less than i2 is b3 ->\n              e1 <! e2 ||! b3\nwhere \"e '||!' v\" := (Eval1 e v)\n.\n\n(* 3.2 *)\nLemma eval1Unique :\n  forall e v1 v2, e ||! v1 -> e ||! v2 -> v1 = v2.\nProof.\n  induction e as [ i | b | p e1 IHe1 e2 IHe2 | eP IHeP eT IHeT eE IHeE ]\n  ; intros v1 v2 E1 E2.\n\n    (* EX_Int *)\n    inversion E1; subst.\n    inversion E2; subst.\n    reflexivity.\n\n    (* EX_Bool *)\n    inversion E1; subst.\n    inversion E2; subst.\n    reflexivity.\n\n    (* EX_Prim *)\n    destruct p\n\n    ; inversion E1 as [ | | |\n                        | e1e1 e1e2 e1i1 e1i2 e1v e1E1H e1E2H e1BH\n                        | e1e1 e1e2 e1i1 e1i2 e1v e1E1H e1E2H e1BH\n                        | e1e1 e1e2 e1i1 e1i2 e1v e1E1H e1E2H e1BH\n                        | e1e1 e1e2 e1i1 e1i2 e1v e1E1H e1E2H e1BH\n                      ]\n    ; subst\n    ; inversion E2 as [ | | |\n                        | e2e1 e2e2 e2i1 e2i2 e2v1 e2E1H e2E2H e2BH (* EX_Plus *)\n                        | e2e1 e2e2 e2i1 e2i2 e2v1 e2E1H e2E2H e2BH (* EX_Minus *)\n                        | e2e1 e2e2 e2i1 e2i2 e2v1 e2E1H e2E2H e2BH (* EX_Times *)\n                        | e2e1 e2e2 e2i1 e2i2 e2v1 e2E1H e2E2H e2BH (* EX_LT *)\n                      ]\n    ; subst\n\n    ; rewrite <- (IHe1 e1i1 e2i1 e1E1H e2E1H) in e2BH\n    ; rewrite <- (IHe2 e1i2 e2i2 e1E2H e2E2H) in e2BH\n    ; inversion e1BH; subst\n    ; inversion e2BH; subst\n    ; reflexivity.\n\n    (* EX_If *)\n    inversion E1 as [ |\n                      | e1e1 e1e2 e1e3 e1v e1PH e1H\n                      | e1e1 e1e2 e1e3 e1v e1PH e1H\n                      | | | | ]\n    ; subst\n    ; inversion E2 as [ |\n                        | e2e1 e2e2 e2e3 e2v e2PH e2H\n                        | e2e1 e2e2 e2e3 e2v e2PH e2H\n                        | | | | ]; subst.\n\n    exact (IHeT v1 v2 e1H e2H).\n\n    assert (V_Bool true = V_Bool false) as N by\n          exact (IHeP (V_Bool true) (V_Bool false) e1PH e2PH)\n    ; inversion N.\n\n    assert (V_Bool false = V_Bool true) as N by\n          exact (IHeP (V_Bool false) (V_Bool true) e1PH e2PH)\n    ; inversion N.\n\n    exact (IHeE v1 v2 e1H e2H).\nQed.\n", "meta": {"author": "khibino", "repo": "CoPL-read", "sha": "025001d65bf4e1630ea684c9af65b87b9877fbec", "save_path": "github-repos/coq/khibino-CoPL-read", "path": "github-repos/coq/khibino-CoPL-read/CoPL-read-025001d65bf4e1630ea684c9af65b87b9877fbec/coq/ML1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.724870577536174}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (lf2 : natural) : natural :=\n  plus lf2 (mult z (Succ y)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj123_coqofml_SQlCeA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7248705695730892}}
{"text": "Require Import List Arith Lia.\n\nSection mirror.\n\n Variable A : Type.\n\n Inductive remove_last (a:A) : list A -> list A -> Prop :=\n   | remove_last_hd : remove_last a (a :: nil) nil\n   | remove_last_tl :\n       forall (b:A) (l m:list A),\n         remove_last a l m -> remove_last a (b :: l) (b :: m). \n\n Inductive palindrome : list A -> Prop :=\n   | empty_pal : palindrome nil\n   | single_pal : forall a:A, palindrome (a :: nil)\n   | cons_pal :\n       forall (a:A) (l m:list A),\n         palindrome l -> remove_last a m l -> palindrome (a :: m).\n \n #[local] Hint Constructors remove_last palindrome : core.\n\n\n Lemma ababa : forall a b:A, palindrome (a :: b :: a :: b :: a :: nil).\n Proof.\n  eauto 7.\n Qed.\n\n\n(* more about palindromes *)\n\nLemma remove_last_inv :\n forall (a:A) (l m:list A), remove_last a m l -> m = l ++ a :: nil.\nProof.\n intros a l m H; elim H; simpl; auto with datatypes.\n intros b l0 m0 H0 e; rewrite e; trivial.\nQed.\n\nLemma rev_app : forall l m:list A, rev (l ++ m) = rev m ++ rev l.\nProof.\n intros l m; elim l; simpl; auto with datatypes.\n intros a l0 H0; rewrite ass_app; rewrite H0; auto.\nQed.\n\nLemma palindrome_rev : forall l:list A, palindrome l -> rev l = l.\nProof.\n intros l H; elim H; simpl; auto with datatypes.\n intros a l0 m H0 H1 H2; generalize H1; inversion_clear H2.\n -  simpl; auto.\n -  rewrite (remove_last_inv _ _  _ H3); simpl; repeat (rewrite rev_app; simpl).\n    intro eg; rewrite eg;  simpl; auto.\nQed.\n\n(* A new induction principle for lists *)\n\n(* preliminaries *)\n\nLemma length_app :\n forall l l':list A, length (l ++ l') = length l + length l'.\nProof.\n  intro l; elim l; simpl; auto.\nQed.\n\nLemma fib_ind :\n forall P:nat -> Prop,\n   P 0 ->\n   P 1 -> \n  (forall n:nat, P n -> P (S n) -> P (S (S n))) -> \n  forall n:nat, P n.\nProof.\n intros P H0 H1 HSSn n.\n assert (H2 : P n /\\ P (S n)).\n - induction n ;[tauto | ].\n   destruct IHn;split;auto.\n -  destruct H2; auto.\nQed.\n\nSection Proof_of_list_new_ind.\nVariables (P : list A -> Prop).\n\nHypotheses (H0 : P nil)\n           (H1 : forall a: A, P (a::nil))\n           (H2 : forall (a b:A) (l:list A), P l -> P (a :: l ++ b :: nil)).  \n   \nLemma list_cut : \nforall (l:list A) (x:A),\n            exists b : A, exists l' : list A, x :: l = l' ++ b :: nil.\nProof.\nintro l; elim l; simpl.\n intro x; exists x; exists (nil (A:=A)); auto.\n intros a1 l3 H x.\n case (H a1).\n intros x0 H7.\n case H7; intros b Hb.\n rewrite Hb.\n exists x0.\n exists (x :: b); auto.\nQed.\n\n\n\nLemma list_new_ind_length :\nforall (n:nat) (l:list A), length l = n -> P l.\nProof.\nintro n; pattern n; apply fib_ind.\n  -  intro l; case l; [simpl; auto with datatypes |  discriminate].\n  -  intro l; case l; simpl; [ discriminate | ].\n     +  intros a l0; case l0; simpl; [auto | discriminate].\n  -  intros n0 H3 H4 l; case l; simpl;[discriminate |].\n     +  intros a l0 H5; generalize H5; case l0. \n       *   simpl; discriminate 1.\n       *   intros a0 l1 H6; destruct (list_cut l1 a0) as [x [l' Hx]];\n           rewrite Hx; apply H2.\n           apply H3.\n           rewrite Hx in H6.\n           rewrite length_app in H6.\n           simpl in H6; lia.\nQed.\n\n\nLemma list_new_ind :\n   forall l:list A, P l.\nProof.\n intro l; now apply list_new_ind_length with (length l).\nQed. \n\n\nEnd Proof_of_list_new_ind.\n\n\n\nLemma app_left_reg : forall l l1 l2:list A, l ++ l1 = l ++ l2 -> l1 = l2.\nProof.\n intro l; elim l; simpl; auto.\n intros a l0 H0 l1 l2 H; injection H; auto.\nQed.\n\nLemma app_right_reg : forall l l1 l2:list A, l1 ++ l = l2 ++ l -> l1 = l2.\nProof.\n intros l l1 l2 e.\n assert (H: rev (l1 ++ l) = rev (l2 ++ l)).\n - now rewrite e.\n -  repeat rewrite rev_app in H.\n    generalize (app_left_reg _ _ _ H).\n    intro H1;  rewrite <- (rev_involutive  l1) ; \n    rewrite <- (rev_involutive l2);\n    rewrite H1; auto.\n    Qed.\n\nTheorem rev_pal : forall l:list A, rev l = l -> palindrome  l. \nProof.\n intro l; elim l using list_new_ind; auto.\n -  intros a b l0 H H0.\n    apply cons_pal with l0.\n   +  apply H;  simpl in H0;  rewrite rev_app in H0.\n      simpl in H0; injection H0.\n      intros H1 e; generalize H1; rewrite e.\n      intro H2; generalize (app_right_reg _ _ _ H2); auto.\n   +  simpl in H0; rewrite rev_app in H0; simpl in H0.\n      injection H0; intros H1 H2; rewrite <- H2.\n      generalize l0; intro l1; induction l1; simpl; auto.\nQed.\n\n\nEnd mirror.\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch8_inductive_predicates/SRC/palindrome.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8198933447152498, "lm_q1q2_score": 0.7248179285802168}}
{"text": "(* ###################################################################### *)\n(** * Case study: Red-Black Trees *)\n\nOpen Scope bool_scope.\nRequire Import Coq.Arith.Arith_base.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Psatz.\n\n(** We will now see how we can use Coq's language to implement an\n    interesting functional program: a red-black tree module. Red-black\n    trees are binary search trees that use an intricate invariant to\n    guarantee that they are well-balanced.\n\n    We use Coq's [Section] mechanism to state our definitions within\n    the scope of common parameters. This makes our notation lighter by\n    avoiding having to redeclare these arguments in all\n    definitions. The [Variable] and [Hypothesis] keywords introduce\n    assumptions in our context that are in scope in the entire\n    [Section] declaration.\n\n    Our definitions are parameterized by a type [A] and a comparison\n    function [comp] between elements of [A]. The [comparison] type is\n    defined in the standard library, and includes the values [Lt],\n    [Gt], and [Eq]. Notice that we state a few hypotheses that are\n    needed for our results to hold. *)\n\nSection RedBlack.\n\nVariable A : Type.\nVariable comp : A -> A -> comparison.\n\nHypothesis comp_opp :\n  forall x y, comp x y = CompOpp (comp y x).\nHypothesis comp_trans :\n  forall x y z, comp x y = Lt ->\n                comp y z = Lt ->\n                comp x z = Lt.\nHypothesis comp_refl_iff :\n(* <-> ==== if and only if *)\n  forall x y, comp x y = Eq <-> x = y.\n\n(* Exercise: (Hint: [apply] works with [<->]) *)\nLemma comp_refl : forall x, comp x x = Eq.\nProof.\n  intros x.\n  rewrite comp_refl_iff.\n  reflexivity.\nQed.\n\n(** Red-black trees are binary search trees that contain elements of\n    [A] on their internal nodes, and such that every internal node is\n    colored with either [Red] or [Black]. *)\n\nInductive color := Red | Black.\n\nInductive tree :=\n| Leaf : tree\n| Node : color -> tree -> A -> tree -> tree.\n\n(** Before getting into details about the red-black invariants, we can\n    already define a search algorithm that looks up an element [x] of\n    [A] on a tree. Its definition is standard: *)\n\nFixpoint member x t : bool :=\n  match t with\n  | Leaf => false\n  | Node _ t1 x' t2 =>\n    match comp x x' with\n    | Lt => member x t1\n    | Eq => true\n    | Gt => member x t2\n    end\n  end.\n\n(** We want to formulate a specification for our algorithm and prove\n    that this implementation indeed satisfies it. We begin by\n    formalizing what it means for a tree to be a binary search\n    tree. This will require the following higher-order function, which\n    tests whether all elements of a tree [t] satisfy a property [f]: *)\n\nFixpoint all (f : A -> bool) (t : tree) : bool :=\n  match t with\n  | Leaf => true\n  | Node _ t1 x t2 => all f t1 && f x && all f t2\n  end.\n\n(** We can now state the familiar binary-tree search invariant: Each\n    element [x] on an internal node is strictly greater than those to\n    its left, and strictly smaller than those to its right. We use an\n    auxiliary function [ltb] that tests whether an element [x : A] is\n    smaller than some [y : A] with the [comp] function. *)\n\nDefinition ltb x y :=\n  match comp x y with\n  | Lt => true\n  | _ => false\n  end.\n\n(** The invariant is then expressed with a simple recursive function\n    that combines [all] and [ltb] above. *)\n\nFixpoint search_tree (t : tree) : bool :=\n  match t with\n  | Leaf => true\n  | Node _ t1 x t2 =>\n    all (fun y => ltb y x) t1\n    && all (ltb x) t2\n    && search_tree t1\n    && search_tree t2\n  end.\n\n(** The specification of [member] is given in terms of a function\n    [occurs] that looks for an element [x] on all nodes of a tree\n    [t]. The [eqb] function, as its name suggests, tests two elements\n    for equality. *)\n\nDefinition eqb x y :=\n  match comp x y with\n  | Eq => true\n  | _ => false\n  end.\n\nFixpoint occurs (x : A) (t : tree) : bool :=\n  match t with\n  | Leaf => false\n  | Node _ t1 y t2 => occurs x t1 || eqb x y || occurs x t2\n  end.\n\n(** New tactic\n    ----------\n\n    - [trivial]: solves simple goals through [reflexivity] and by\n      looking for assumptions in the context that apply directly. If\n      it cannot solve the goal, it does nothing.\n\n    - [try]: Calling [try foo] tries to execute [foo], doing nothing\n      if [foo] raises any errors. In particular, if [foo] is a\n      _terminating tactic_ such as [discriminate], [try foo] attempts\n      to solve the goal, and does nothing if it fails.\n\n    - [destruct ... eqn: ...]: Do case analysis on an expression while\n      generating an equation. *)\n\nLemma all_weaken :\n  forall f g,\n    (forall x, f x = true -> g x = true) ->\n    forall t, all f t = true -> all g t = true.\nProof. Admitted.\n\n(* Exercise: *)\nLemma none_occurs :\n  forall (x : A) (f : A -> bool) (t : tree),\n    f x = false ->\n    all f t = true ->\n    occurs x t = false.\nProof. (* fill in here *) Admitted.\n\n(** With these results, we are ready to prove the correctness of the\n    membership testing algorithm.\n\n    New Tactics\n    -----------\n\n    - [assert]: Introduce a new hypothesis in the context, requiring\n      us to prove that it holds. *)\n\nLemma member_correct :\n  forall x t,\n    search_tree t = true ->\n    member x t = occurs x t.\nProof. Admitted.\n\n(** We now turn our attention to the red-black invariant. A red-black\n    tree is _valid_ if (1) all paths from the root of the tree to its\n    leaves go through the same number of black nodes, and (2) if red\n    nodes only have black children (we stipulate that the leaves of\n    the tree are black). We begin by formalizing (2). *)\n\nDefinition tree_color (t : tree) : color :=\n  match t with\n  | Leaf => Black\n  | Node c _ _ _ => c\n  end.\n\nFixpoint well_colored (t : tree) : bool :=\n  match t with\n  | Leaf => true\n  | Node c t1 _ t2 =>\n\n    let colors_ok :=\n      match c, tree_color t1, tree_color t2 with\n      | Red, Black, Black => true\n      | Red, _, _ => false\n      | Black, _, _ => true\n      end in\n    colors_ok && well_colored t1 && well_colored t2\n  end.\n\n(** The [black_height] function computes the number of black nodes on\n    the path to the left-most leaf of the tree. It is used in the\n    [height_ok] function, which ensures that _all_ paths have the same\n    number of black nodes. *)\n\nFixpoint black_height (t : tree) : nat :=\n  match t with\n  | Leaf => 0\n  | Node Red t _ _ => black_height t\n  | Node Black t _ _ => S (black_height t)\n  end.\n\nFixpoint height_ok (t : tree) : bool :=\n  match t with\n  | Leaf => true\n  | Node _ t1 _ t2 =>\n    beq_nat (black_height t1) (black_height t2)\n    && height_ok t1\n    && height_ok t2\n  end.\n\nDefinition is_red_black (t : tree) : bool :=\n  well_colored t && height_ok t.\n\n(** The red-black invariant is important because it implies that the\n    height of the tree is logarithmic on the number of nodes. We will\n    now see how to formally show that this is the case. We begin by\n    defining a function [size] for computing various metrics about our\n    trees: *)\n\nFixpoint size (f : nat -> nat -> nat) (t : tree) : nat :=\n  match t with\n  | Leaf => 0\n  | Node _ t1 _ t2 => S (f (size f t1) (size f t2))\n  end.\n\n(** Note that [size plus] computes the number of elements stored in\n    the tree. [size max] computes the height of the tree, whereas\n    [size min] computes the length of the shortest path from the root\n    of the tree to a leaf.\n\n    As a warm-up exercise, let's show that the black height of a tree\n    is a lower bound on the length of its minimal path.\n\n    To facilitate low-level arithmetic reasoning, we can use the [lia]\n    tactic.\n\n    New Tactics\n    -----------\n\n    - [lia]: Short for \"Linear Integer Arithmetic\"; tries to solve\n      goals that involve linear systems of inequalites on integers. *)\n\nLemma size_min_black_height :\n  forall t,\n    if height_ok t then black_height t <= size min t\n    else True.\nProof. Admitted.\n\n(** We now need to relate the black height of a tree to its total\n    height, by proving the following fact: *)\n\nLemma size_max_black_height :\n  forall t,\n    if is_red_black t then size max t <= 2 * black_height t + 1\n    else True.\nProof. (* stuck ... *) Abort.\n\n(** Unfortunately, this won't work. We need to reason about the\n    coloring properties of red-black trees, and show the following\n    slightly stronger statement, which gives an improved bound for\n    black trees. *)\n\nLemma size_max_black_height :\n  forall t,\n    if is_red_black t then\n      match tree_color t with\n      | Red => size max t <= 2 * black_height t + 1\n      | Black => size max t <= 2 * black_height t\n      end\n    else True.\nProof. Admitted.\n\n(** Exercise: Prove the following result using the previous two lemmas\n    relating the height of the tree to the length of its mininal\n    path. *)\n\nLemma size_max_size_min :\n  forall t,\n    if is_red_black t then size max t <= 2 * size min t + 1\n    else True.\nProof. (* fill in here *) Admitted.\n\n(** The previous lemma implies that the tree is well-balanced thanks\n    to the following fact, which shows that the number of elements\n    stored in a tree is exponential in the length of the minimal path:\n    *)\n\nLemma size_min_size_plus :\n  forall t,\n    2 ^ size min t <= size plus t + 1.\nProof. Admitted.\n\n(** Take-home exercise: The extended version of this file contains an\n    implementation of red-black-tree insertion. Read through the basic\n    definitions and try to complete the missing proofs. *)\n\nEnd RedBlack.\n", "meta": {"author": "filippovitale", "repo": "cufp2015", "sha": "258ce9cded09a4cdd724eb3d8ac04b82c409ae70", "save_path": "github-repos/coq/filippovitale-cufp2015", "path": "github-repos/coq/filippovitale-cufp2015/cufp2015-258ce9cded09a4cdd724eb3d8ac04b82c409ae70/t12-coq/redblack_short.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7248179169086257}}
{"text": "(* T2: Demostraciones por inducción sobre los números naturales en Coq *)\n\nRequire Export T1_PF_en_Coq.\n\n(* El contenido de la teoría es\n   1. Demostraciones por inducción. \n   2. Demostraciones anidadas.\n   3. Demostraciones formales vs demostraciones informales.\n   4. Ejercicios complementarios *)\n\n(* =====================================================================\n   § 1. Demostraciones por inducción \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.1. Demostrar que\n      forall n:nat, n = n + 0.\n   ------------------------------------------------------------------ *)\n\n(* 1º intento: con métodos elementales *)\nTheorem suma_n_0_a: forall n:nat, n = n + 0.\nProof.\n  intros n. (* n : nat\n               ============================\n                n = n + 0 *)\n  simpl.    (* n : nat\n               ============================\n                n = n + 0 *)\nAbort.\n\n(* 2º intento: con casos *)\nTheorem suma_n_0_b : forall n:nat,\n  n = n + 0.\nProof.\n  intros n.             (* n : nat\n                           ============================\n                            n = n + 0 *)\n  destruct n as [| n']. \n  -                     (* \n                           ============================\n                            0 = 0 + 0 *)\n    reflexivity. \n  -                     (* n' : nat\n                           ============================\n                            S n' = S n' + 0  *)\n    simpl.              (* n' : nat\n                           ============================\n                            S n' = S (n' + 0) *)\nAbort.\n\n(* 3ª intento: con inducción *)\nTheorem suma_n_0 : forall n:nat,\n    n = n + 0.\nProof.\n  intros n.                   (* n : nat\n                                 ============================\n                                 n = n + 0 *) \n  induction n as [| n' IHn']. \n  +                           (*   \n                                 ============================\n                                 0 = 0 + 0 *)\n    reflexivity.\n  +                           (* n' : nat\n                                 IHn' : n' = n' + 0\n                                 ============================\n                                 S n' = S n' + 0 *)\n    simpl.                    (* S n' = S (n' + 0) *)\n    rewrite <- IHn'.          (* S n' = S n' *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 1.2. Demostrar que\n      forall n, n - n = 0.\n   ------------------------------------------------------------------ *)\n\nTheorem resta_n_n: forall n, n - n = 0.\nProof.\n  intros n.                   (* n : nat\n                                 ============================\n                                 n - n = 0 *)\n  induction n as [| n' IHn']. \n  +                           (*  \n                                 ============================\n                                 0 - 0 = 0 *)\n    reflexivity.\n  +                           (* n' : nat\n                                 IHn' : n' - n' = 0\n                                 ============================\n                                 S n' - S n' = 0 *)\n    simpl.                    (* n' - n' = 0 *)\n    rewrite -> IHn'.          (* 0 = 0 *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.1. Demostrar que\n      forall n:nat, n * 0 = 0.\n   ------------------------------------------------------------------ *)\n\nTheorem multiplica_n_0: forall n:nat, n * 0 = 0.\nProof.\n  intros n.                   (* n : nat\n                                 ============================\n                                 n * 0 = 0 *)\n  induction n as [| n' IHn']. \n  +                           (* \n                                 ============================\n                                 0 * 0 = 0 *)\n    reflexivity.      \n  +                           (* n' : nat\n                                 IHn' : n' * 0 = 0\n                                 ============================\n                                 S n' * 0 = 0 *)   \n    simpl.                    (* n' * 0 = 0 *)\n    rewrite IHn'.             (* 0 = 0 *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.2. Demostrar que, \n      forall n m : nat, S (n + m) = n + (S m).\n   ------------------------------------------------------------------ *)\n\nTheorem suma_n_Sm: forall n m : nat, S (n + m) = n + (S m).\nProof.\n  intros n m.                (*  n, m : nat\n                                 ============================\n                                 S (n + m) = n + S m *)\n  induction n as [|n' IHn']. \n  +                          (* m : nat\n                                ============================\n                                S (0 + m) = 0 + S m *)\n    simpl.                   (* m : nat\n                                ============================\n                                S m = S m *)\n    reflexivity.\n  +                          (* S (S n' + m) = S n' + S m *)\n    simpl.                   (* S (S (n' + m)) = S (n' + S m) *)\n    rewrite IHn'.            (* S (n' + S m) = S (n' + S m) *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.3. Demostrar que \n      forall n m : nat, n + m = m + n.\n   ------------------------------------------------------------------ *)\n\nTheorem suma_conmutativa: forall n m : nat,\n  n + m = m + n.\nProof.\n  intros  n m.               (* n, m : nat\n                                ============================\n                                n + m = m + n *)\n  induction n as [|n' IHn'].\n  +                          (* m : nat\n                                ============================\n                                0 + m = m + 0 *)\n    simpl.                   (* m = m + 0 *)\n    rewrite <- suma_n_0.     (* m = m *)\n    reflexivity.\n  +                          (* n', m : nat\n                                IHn' : n' + m = m + n'\n                                ============================\n                                S n' + m = m + S n' *)\n    simpl.                   (* S (n' + m) = m + S n' *)\n    rewrite IHn'.            (* S (m + n') = m + S n' *)\n    rewrite <- suma_n_Sm.    (* S (m + n') = S (m + n') *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.4. Demostrar que \n      forall n m p : nat, n + (m + p) = (n + m) + p.\n   ------------------------------------------------------------------ *)\n\nTheorem suma_asociativa: forall n m p : nat, n + (m + p) = (n + m) + p.\nProof.\n  intros n m p.              (* n, m, p : nat\n                                ============================\n                                n + (m + p) = (n + m) + p *)\n  induction n as [|n' IHn'].\n  +                          (* m, p : nat\n                                ============================\n                                0 + (m + p) = (0 + m) + p *)\n    reflexivity.\n  +                          (* n', m, p : nat\n                                IHn' : n' + (m + p) = n' + m + p\n                                ============================\n                                S n' + (m + p) = (S n' + m) + p *)\n    simpl.                   (* S (n' + (m + p)) = S ((n' + m) + p) *)\n    rewrite IHn'.            (* S ((n' + m) + p) = S ((n' + m) + p) *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.5. Se considera la siguiente función que dobla su argumento. \n      Fixpoint doble (n:nat) :=\n        match n with\n        | O    => O\n        | S n' => S (S (doble n'))\n        end.\n\n   Demostrar que \n      forall n, doble n = n + n. \n   ------------------------------------------------------------------ *)\n\nFixpoint doble (n:nat) :=\n  match n with\n  | O    => O\n  | S n' => S (S (doble n'))\n  end.\n\nLemma doble_suma : forall n, doble n = n + n .\nProof.\n  intros n.                  (* n : nat\n                                ============================\n                                doble n = n + n *)\n  induction n as [|n' IHn']. \n  +                          (* \n                                ============================\n                                doble 0 = 0 + 0 *)\n    reflexivity.\n  +                          (* n' : nat\n                                IHn' : doble n' = n' + n'\n                                ============================\n                                doble (S n') = S n' + S n' *)\n    simpl.                   (* S (S (doble n')) = S (n' + S n') *)\n    rewrite IHn'.            (* S (S (n' + n')) = S (n' + S n') *)\n    rewrite suma_n_Sm.       (* S (n' + S n') = S (n' + S n') *)\n    reflexivity.\nQed. \n\n(* ---------------------------------------------------------------------\n   Ejercicio 1.6. Demostrar que\n      forall n : nat, esPar (S n) = negacion (esPar n).\n   ------------------------------------------------------------------ *)\n\nTheorem esPar_S : forall n : nat,\n  esPar (S n) = negacion (esPar n).\nProof.\n  intros n.                      (* n : nat\n                                    ============================\n                                    esPar (S n) = negacion (esPar n) *)\n  induction n as [|n' IHn'].\n  +                              (* \n                                    ============================\n                                    esPar 1 = negacion (esPar 0) *)\n    simpl.                       (* \n                                    ============================\n                                    false = false *)\n    reflexivity.\n  +                              (* n' : nat\n                                    IHn' : esPar (S n') = negacion (esPar n')\n                                    ============================\n                                    esPar (S (S n')) = \n                                     negacion (esPar (S n')) *)\n    rewrite IHn'.                (* esPar (S (S n')) = \n                                     negacion (negacion (esPar n')) *)\n    rewrite negacion_involutiva. (* esPar (S (S n')) = esPar n' *)\n    simpl.                       (* esPar n' = esPar n' *)\n    reflexivity.\nQed.\n\n(* =====================================================================\n   § 2. Demostraciones anidadas\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.1. Demostrar que\n      forall n m : nat, (0 + n) * m = n * m.\n   ------------------------------------------------------------------ *)\n\nTheorem producto_0_suma': forall n m : nat, (0 + n) * m = n * m.\nProof.\n  intros n m.            (* n, m : nat\n                            ============================\n                            (0 + n) * m = n * m *)\n  assert (H: 0 + n = n). \n  -                      (* n, m : nat\n                            ============================\n                            0 + n = n *)\n    reflexivity.\n  -                      (* n, m : nat\n                            H : 0 + n = n\n                            ============================\n                            (0 + n) * m = n * m *)\n    rewrite -> H.        (* n * m = n * m *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejemplo 2.2. Demostrar que\n      forall n m p q : nat, (n + m) + (p + q) = (m + n) + (p + q)\n   ------------------------------------------------------------------ *)\n\n(* 1º intento sin assert*)\nTheorem suma_reordenada_1: forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.              (* n, m, p, q : nat\n                                  ============================\n                                  (n + m) + (p + q) = (m + n) + (p + q) *)\n  rewrite -> suma_conmutativa. (* n, m, p, q : nat\n                                  ============================\n                                  p + q + (n + m) = m + n + (p + q) *)\nAbort.\n\n(* 2º intento con assert *)\nTheorem suma_reordenada: forall n m p q : nat,\n  (n + m) + (p + q) = (m + n) + (p + q).\nProof.\n  intros n m p q.                (* n, m, p, q : nat\n                                    ============================\n                                    (n + m) + (p + q) = (m + n) + (p + q) *)\n  assert (H: n + m = m + n).\n  -                              (* n, m, p, q : nat\n                                    ============================\n                                    n + m = m + n *)\n    rewrite -> suma_conmutativa. (* m + n = m + n *)\n    reflexivity.\n  -                              (* n, m, p, q : nat\n                                    H : n + m = m + n\n                                    ============================\n                                    (n + m) + (p + q) = (m + n) + (p + q) *)\n    rewrite -> H.                (* m + n + (p + q) = m + n + (p + q) *)\n    reflexivity.\nQed.\n\n(* =====================================================================\n   § 3. Demostraciones formales vs demostraciones informales\n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.1. Escribir la demostración informal (en lenguaje natural)\n   correspondiente a la demostración formal de la asociatividad de la\n   suma del ejercicio 1.4.\n   ------------------------------------------------------------------ *)\n\n(* Demostración por inducción en n.\n\n   - Caso base: Se supone que n es 0 y hay que demostrar que\n        0 + (m + p) = (0 + m) + p.\n     Esto es consecuencia inmediata de la definición de suma.\n\n   - Paso de indución: Suponemos la hipótesis de inducción\n        n' + (m + p) = (n' + m) + p.                 \n     Hay que demostrar que\n        (S n') + (m + p) = ((S n') + m) + p.\n     que, por la definición de suma, se reduce a\n        S (n' + (m + p)) = S ((n' + m) + p)\n     que por la hipótesis de inducción se reduce a\n        S ((n' + m) + p) = S ((n' + m) + p)\n     que es una identidad. *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.2. Escribir la demostración informal (en lenguaje natural)\n   correspondiente a la demostración formal de la asociatividad de la\n   suma del ejercicio 1.3.\n   ------------------------------------------------------------------ *)\n\n(* Demostración por inducción en n.\n\n   - Caso base: Se supone que n es 0 y hay que demostrar que\n        0 + m = m + 0\n     que, por la definición de la suma, se reduce a\n        m = m + 0\n     que se verifica por el lema suma_n_0.\n\n   - Paso de indución: Suponemos la hipótesis de inducción\n        n' + m = m + n'\n     Hay que demostrar que\n        S n' + m = m + S n'\n     que, por la definición de suma, se reduce a\n        S (n' + m) = m + S n'\n     que, por la hipótesis de inducción, se reduce a\n        S (m + n') = m + S n'\n     que, por el lema suma_n_Sm, se reduce a\n        S (m + n') = S (m + n')\n     que es una identidad. *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.3. Demostrar que\n      forall n:nat, iguales_nat n n = true.\n   ------------------------------------------------------------------ *)\n\nTheorem iguales_nat_refl: forall n : nat,\n    iguales_nat n n = true.\nProof.\n  intros n.                  (* n : nat\n                                ============================\n                                iguales_nat n n = true *)\n  induction n as [|n' IHn']. \n  -                          (* \n                                ============================\n                                iguales_nat 0 0 = true *)\n    reflexivity.\n  -                          (* n' : nat\n                                IHn' : iguales_nat n' n' = true\n                                ============================\n                                iguales_nat (S n') (S n') = true *)\n    simpl.                   (* iguales_nat n' n' = true *)\n    rewrite <- IHn'.          (* true = true *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 3.4. Escribir la demostración informal (en lenguaje natural)\n   correspondiente la demostración del ejercicio anterior.\n   ------------------------------------------------------------------ *)\n\n(* Demostración por inducción en n.\n\n   - Caso base: Se supone que n es 0 y hay que demostrar que\n        true = iguales_nat 0 0\n     que se verifica por la definición de iguales_nat.\n\n   - Paso de indución: Suponemos la hipótesis de inducción\n        true = iguales_nat n' n'\n     Hay que demostrar que\n        true = iguales_nat (S n') (S n') \n     que, por la definición de iguales_nat, se reduce a\n        true = iguales_nat n' n\n     que, por la hipótesis de inducción, se reduce a\n        true = true\n     que es una identidad. *)\n\n(* =====================================================================\n   § 4. Ejercicios complementarios \n   ================================================================== *)\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.1. Demostrar, usando assert pero no induct,\n      forall n m p : nat, n + (m + p) = m + (n + p).\n   ------------------------------------------------------------------ *)\n\nTheorem suma_permutada: forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof. \n  intros n m p.               (* n, m, p : nat\n                                 ============================\n                                 n + (m + p) = m + (n + p) *)\n  rewrite suma_asociativa.    (* n, m, p : nat\n                                 ============================\n                                 (n + m) + p = m + (n + p) *)\n  rewrite suma_asociativa.    (* n, m, p : nat\n                                 ============================\n                                 n + m + p = m + n + p *)\n  assert (H : n + m = m + n). \n  -                           (* n, m, p : nat\n                                 ============================\n                                 n + m = m + n *)\n    rewrite suma_conmutativa. (* m + n = m + n *)\n    reflexivity. \n  -                           (* n, m, p : nat\n                                 H : n + m = m + n\n                                 ============================\n                                 (n + m) + p = (m + n) + p *)\n    rewrite H.                (* (m + n) + p = (m + n) + p *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.2. Demostrar que la multiplicación es conmutativa.\n   ------------------------------------------------------------------ *)\n\nLemma producto_n_1 : forall n: nat,\n    n * 1 = n.\nProof.\n  intro n.                   (* n : nat\n                                ============================\n                                n * 1 = n *)\n  induction n as [|n' IHn']. \n  -                          (* \n                                ============================\n                                0 * 1 = 0 *)\n    reflexivity.\n  -                          (* n' : nat\n                                IHn' : n' * 1 = n'\n                                ============================\n                                S n' * 1 = S n' *)\n    simpl.                   (* S (n' * 1) = S n' *)\n    rewrite IHn'.            (* S n' = S n' *)\n    reflexivity.\nQed.\n\nTheorem suma_n_1 : forall n : nat,\n    n + 1 = S n.\nProof.\n  intro n.                   (* n : nat\n                                ============================\n                                n + 1 = S n *)\n  induction n as [|n' HIn']. \n  -                          (* \n                                ============================\n                                0 + 1 = 1 *)\n    reflexivity.\n  -                          (* n' : nat\n                                HIn' : n' + 1 = S n'\n                                ============================\n                                S n' + 1 = S (S n') *)\n    simpl.                   (* S (n' + 1) = S (S n') *)\n    rewrite HIn'.            (* S (S n') = S (S n') *)\n    reflexivity.\nQed.\n\nTheorem producto_n_Sm: forall n m : nat, \n    n * (m + 1) = n * m + n.\nProof.\n  intros n m.                   (* n, m : nat\n                                   ============================\n                                   n * (m + 1) = n * m + n *)\n  induction n as [|n' IHn'].\n  -                             (* m : nat\n                                   ============================\n                                   0 * (m + 1) = 0 * m + 0 *)\n    reflexivity.\n  -                             (* n', m : nat\n                                   IHn' : n' * (m + 1) = n' * m + n'\n                                   ============================\n                                   S n' * (m + 1) = S n' * m + S n' *)\n    simpl.                      (* (m + 1) + n' * (m + 1) = \n                                    (m + n' * m) + S n' *)\n    rewrite IHn'.               (* (m + 1) + (n' * m + n') = \n                                    (m + n' * m) + S n' *)\n    rewrite suma_permutada.     (* n' * m + ((m + 1) + n') = \n                                    (m + n' * m) + S n' *)\n    rewrite <- suma_asociativa. (* n' * m + (m + (1 + n')) = \n                                    (m + n' * m) + S n' *)\n    rewrite <- suma_n_1.        (* n' * m + (m + (n' + 1)) = \n                                   (m + n' * m) + S n' *)\n    rewrite suma_n_1.           (* n' * m + (m + S n') = (m + n' * m) + S n' *)\n    rewrite suma_permutada.     (* m + (n' * m + S n') = (m + n' * m) + S n' *)\n    rewrite suma_asociativa.    (* m + (n' * m + S n') = (m + n' * m) + S n' *)\n    reflexivity.\nQed.\n\nTheorem producto_conmutativa: forall m n : nat,\n  m * n = n * m.\nProof.\n  intros n m.                 (* n, m : nat\n                                 ============================\n                                 n * m = m * n *)\n  induction n as [|n' HIn'].\n  -                           (* m : nat\n                                 ============================\n                                 0 * m = m * 0 *)\n    rewrite multiplica_n_0.   (* 0 * m = 0 *)\n    reflexivity.\n  -                           (* n', m : nat\n                                 HIn' : n' * m = m * n'\n                                 ============================\n                                 S n' * m = m * S n' *)\n    simpl.                    (* m + n' * m = m * S n' *)\n    rewrite HIn'.             (* m + m * n' = m * S n' *)\n    rewrite <- suma_n_1.      (* m + m * n' = m * (n' + 1) *)\n    rewrite producto_n_Sm.    (* m + m * n' = m * n' + m *)\n    rewrite suma_conmutativa. (* m * n' + m = m * n' + m *)\n   reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.3. Demostrar que \n      forall n : nat, true = menor_o_igual n n.  \n   ------------------------------------------------------------------ *)\n\n\nTheorem menor_o_igual_refl: forall n : nat,\n    true = menor_o_igual n n.\nProof.\n  intro n.                    (* n : nat\n                                 ============================\n                                 true = menor_o_igual n n *)\n  induction n as [| n' HIn']. \n  -                           (* \n                                 ============================\n                                 true = menor_o_igual 0 0 *)\n    reflexivity.\n  -                           (* n' : nat\n                                 HIn' : true = menor_o_igual n' n'\n                                 ============================\n                                 true = menor_o_igual (S n') (S n') *)\n    simpl.                    (* true = menor_o_igual n' n' *)\n    rewrite HIn'.             (* menor_o_igual n' n' = menor_o_igual n' n' *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.4. Demostrar que \n      forall n : nat, iguales_nat 0 (S n) = false. \n   ------------------------------------------------------------------ *)\n\nTheorem cero_distinto_S: forall n : nat,\n  iguales_nat 0 (S n) = false.\nProof.\n  intros n.    (* n : nat\n                  ============================\n                  iguales_nat 0 (S n) = false *)\n  simpl.       (* false = false *)\n  reflexivity. \nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.5. Demostrar que \n      forall b : bool, conjuncion b false = false.\n   ------------------------------------------------------------------ *)\n\nTheorem conjuncion_false_r : forall b : bool,\n  conjuncion b false = false.\nProof.\n  intros b.      (* b : bool\n                    ============================\n                    b && false = false *)\n  destruct b.\n  -              (* \n                    ============================\n                    true && false = false *)\n    simpl.       (* false = false *)\n    reflexivity.\n  -              (* \n                    ============================\n                    false && false = false *)\n    simpl.       (* false = false *)\n    reflexivity. \nQed. \n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.6. Demostrar que \n      forall n m p : nat, menor_o_igual n m = true -> \n                          menor_o_igual (p + n) (p + m) = true.\n   ------------------------------------------------------------------ *)\n\nTheorem menor_o_igual_suma: forall n m p : nat,\n  menor_o_igual n m = true -> menor_o_igual (p + n) (p + m) = true.\nProof.\n  intros n m p H.            (* n, m, p : nat\n                                H : menor_o_igual n m = true\n                                ============================\n                                menor_o_igual (p + n) (p + m) = true *)\n  induction p as [|p' HIp'].\n  -                          (* n, m : nat\n                                H : menor_o_igual n m = true\n                                ============================\n                                menor_o_igual (0 + n) (0 + m) = true *)\n    simpl.                   (* menor_o_igual n m = true *)\n    rewrite H.               (* true = true *)\n    reflexivity.\n  -                          (* n, m, p' : nat\n                                H : menor_o_igual n m = true\n                                HIp' : menor_o_igual (p' + n) (p' + m) = true\n                                ============================\n                                menor_o_igual (S p' + n) (S p' + m) = true *)\n    simpl.                   (* menor_o_igual (p' + n) (p' + m) = true *)\n    rewrite HIp'.            (* true = true *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.7. Demostrar que \n      forall n : nat, iguales_nat (S n) 0 = false.\n   ------------------------------------------------------------------ *)\n\nTheorem S_distinto_0 : forall n:nat,\n  iguales_nat (S n) 0 = false.\nProof.\n  intro n.     (* n : nat\n                  ============================\n                  iguales_nat (S n) 0 = false *)\n  simpl.       (* false = false *)\n  reflexivity. \nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.8. Demostrar que \n      forall n:nat, 1 * n = n.\n   ------------------------------------------------------------------ *)\n\nTheorem producto_1_n: forall n:nat, 1 * n = n.\nProof.\n  intro n.          (* n : nat\n                       ============================\n                       1 * n = n *)\n  simpl.            (* n + 0 = n *)\n  rewrite suma_n_0. (* n + 0 = n + 0 *)\n  reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.9. Demostrar que \n       forall b c : bool, disyuncion (conjuncion b c)\n                              (disyuncion (negacion b)\n                                          (negacion c))\n                          = true.\n   ------------------------------------------------------------------ *)\n\nTheorem alternativas: forall b c : bool,\n    disyuncion\n      (conjuncion b c)\n      (disyuncion (negacion b)\n                  (negacion c))\n    = true.\nProof.\n  intros [] [].\n  - reflexivity. (* (true && true) || (negacion true || negacion true) = true *)\n  - reflexivity. (* (true && false) || (negacion true || negacion false) = true *)\n  - reflexivity. (* (false && true) || (negacion false || negacion true) = true *)\n  - reflexivity. (* (false && false) || (negacion false || negacion false)=true *)\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.10. Demostrar que \n      forall n m p : nat, (n + m) * p = (n * p) + (m * p).\n   ------------------------------------------------------------------ *)\n\nTheorem producto_suma_distributiva_d: forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  intros n m p.              (* n, m, p : nat\n                                ============================\n                                (n + m) * p = n * p + m * p *)\n  induction n as [|n' HIn']. \n  -                          (* m, p : nat\n                                ============================\n                                (0 + m) * p = 0 * p + m * p *)\n    reflexivity.\n  -                          (* n', m, p : nat\n                                HIn' : (n' + m) * p = n' * p + m * p\n                                ============================\n                                (S n' + m) * p = S n' * p + m * p *)\n    simpl.                   (* p + (n' + m) * p = (p + n' * p) + m * p *)\n    rewrite HIn'.            (* p + (n' * p + m * p) = (p + n') * p + m * p *)\n    rewrite suma_asociativa. (* (p + n' * p) + m * p = (p + n' * p) + m * p *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 4.11. Demostrar que \n      forall n m p : nat, n * (m * p) = (n * m) * p.\n   ------------------------------------------------------------------ *)\n\nTheorem producto_asociativa: forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p.     (* n, m, p : nat\n                       ============================\n                       n * (m * p) = (n * m) * p *)\n  induction n as [|n' HIn'].\n  -                 (* m, p : nat\n                       ============================\n                       0 * (m * p) = (0 * m) * p *)\n    simpl.          (* 0 = 0 *)\n    reflexivity.\n  -                 (* n', m, p : nat\n                       HIn' : n' * (m * p) = (n' * m) * p\n                       ============================\n                       S n' * (m * p) = (S n' * m) * p *)\n    simpl.          (* m * p + n' * (m * p) = (m + n' * m) * p *)\n    rewrite HIn'.   (* m * p + (n' * m) * p = (m + n' * m) * p *)\n    rewrite producto_suma_distributiva_d.\n                    (* m * p + (n' * m) * p = m * p + (n' * m) * p *)\n    reflexivity.\nQed.\n\n(* ---------------------------------------------------------------------\n   Ejercicio 11. La táctica replace permite especificar el subtérmino\n   que se desea reescribir y su sustituto: \n      replace t with u\n   sustituye todas las copias de la expresión t en el objetivo por la\n   expresión u y añade la ecuación (t = u) como un nuevo subojetivo. \n \n   El uso de la táctica replace es especialmente útil cuando la táctica \n   rewrite actúa sobre una parte del objetivo que no es la que se desea. \n\n   Demostrar, usando la táctica replace y sin usar \n   [assert (n + m = m + n)], que\n      forall n m p : nat, n + (m + p) = m + (n + p).\n   ------------------------------------------------------------------ *)\n\nTheorem suma_permutada' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p.                 (* n, m, p : nat\n                                   ============================\n                                   n + (m + p) = m + (n + p) *)\n  rewrite suma_asociativa.      (* (n + m) + p = m + (n + p) *)\n  rewrite suma_asociativa.      (* (n + m) + p = (m + n) + p *)\n  replace (n + m) with (m + n). \n  -                             (* n, m, p : nat\n                                   ============================\n                                   (m + n) + p = (m + n) + p *)\n    reflexivity.\n  -                             (* n, m, p : nat\n                                   ============================\n                                   m + n = n + m *)\n    rewrite suma_conmutativa.   (* n + m = n + m *)\n    reflexivity.\nQed. \n\n(* =====================================================================\n   § Bibliografía\n   ================================================================== *)\n\n(*\n + \"Demostraciones por inducción\" de Peirce et als. http://bit.ly/2NRSWTF\n *)\n", "meta": {"author": "jaalonso", "repo": "DAOconCoq", "sha": "8546d31ef0827e6191427757737dfca24180f97f", "save_path": "github-repos/coq/jaalonso-DAOconCoq", "path": "github-repos/coq/jaalonso-DAOconCoq/DAOconCoq-8546d31ef0827e6191427757737dfca24180f97f/teorias/T2_Induccion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.7248179131512797}}
{"text": "\nRequire Import Lib Deci Arith Omega NArith PArith ZArith.\n\nOpen Scope list_scope.\n\n(** Correctness proofs for the nat conversions *)\n\nModule NatProofs.\n\nImport DecNat.\n\nLemma nat2digit2nat n : n < 10 -> digit2nat (nat2digit n) = n.\nProof.\n destruct n as [|[|[|[|[|[|[|[|[|[|]]]]]]]]]]; auto; omega.\nQed.\n\nLemma digit2nat2digit d : nat2digit (digit2nat d) = d.\nProof.\n now destruct d.\nQed.\n\n(** A naive version of dec2nat, for the proofs *)\nFixpoint of_dec (d:dec) :=\n  match d with\n  | nil => 0\n  | d :: l => of_dec l + digit2nat d * 10^length l\n  end.\n\nLemma d2n_eqn dg d acc :\n  d2n (dg::d) acc =\n  d2n d (digit2nat dg + 10 * acc).\nProof.\n rewrite <- TailNat.addmul_spec.\n reflexivity.\nQed.\n\nLemma d2n_add d n p :\n d2n d (n+p) = d2n d n + p * 10^length d.\nProof.\n revert n p.\n induction d.\n - simpl; auto with arith.\n - intros. rewrite !d2n_eqn.\n   rewrite Nat.mul_add_distr_l, Nat.add_assoc, IHd.\n   f_equal. simpl length.\n   rewrite Nat.pow_succ_r', Nat.mul_assoc. f_equal.\n   apply Nat.mul_comm.\nQed.\n\nLemma d2n_alt d acc : d2n d acc = dec2nat d + acc * 10^length d.\nProof.\n apply (d2n_add d 0 acc).\nQed.\n\nLemma dec2nat_alt d : dec2nat d = of_dec d.\nProof.\n induction d; simpl; auto.\n unfold dec2nat. simpl.\n rewrite <- IHd. unfold dec2nat. now rewrite <- d2n_add.\nQed.\n\nLemma n2d_eqn n acc count :\n  n2d (S n) acc (S count) =\n  n2d (S n / 10) (nat2digit (S n mod 10) :: acc) count.\nProof.\n change (n2d (S n) acc (S count)) with\n (let (q,r) := diveucl (S n) 10 in n2d q (nat2digit r :: acc) count).\n now rewrite diveucl_spec.\nQed.\n\nLemma n2d_eqn' n acc count :\n  n2d n acc (S count) =\n  if n =? 0 then acc\n  else\n   n2d (n/10) (nat2digit (n mod 10) :: acc) count.\nProof.\n destruct n. trivial. apply n2d_eqn.\nQed.\n\nLemma n2d_anycount count count' n acc :\n n <= count -> n <= count' ->\n n2d n acc count = n2d n acc count'.\nProof.\n revert count' n acc.\n induction count; destruct count'; auto.\n - now inversion 1.\n - now inversion 2.\n - intros.\n   destruct n; auto.\n   rewrite !n2d_eqn.\n   destruct (Nat.le_gt_cases 10 (S n)).\n   * apply IHcount; apply Nat.div_le_upper_bound; omega.\n   * rewrite Nat.div_small; auto. now destruct count, count'.\nQed.\n\nLemma n2d_mincount count n acc :\n n <= count -> n2d n acc count = n2d n acc n.\nProof.\n intros. now apply n2d_anycount.\nQed.\n\nLemma n2d_app n d d' count :\n n <= count ->\n n2d n (d++d') count = n2d n d count ++ d'.\nProof.\n revert n d d'.\n induction count.\n - now inversion 1.\n - intros. destruct n.\n   + auto.\n   + rewrite !n2d_eqn.\n     generalize (nat2digit (S n mod 10)); intros dg.\n     change (dg :: d ++ d') with ((dg::d)++d').\n     destruct (Nat.le_gt_cases 10 (S n)).\n     * apply IHcount.\n       apply Nat.div_le_upper_bound; omega.\n     * rewrite Nat.div_small; simpl; auto.\n       destruct count; auto.\nQed.\n\nLemma n2d_alt n acc count :\n n <= count ->\n n2d n acc count = nat2dec n ++ acc.\nProof.\n intros.\n unfold nat2dec. rewrite (n2d_anycount n count); auto.\n now apply (n2d_app n nil).\nQed.\n\nLemma of_dec_app d d' :\n  of_dec (d ++ d') =\n  of_dec d * 10^length d' + of_dec d'.\nProof.\n induction d; simpl; auto.\n rewrite IHd. rewrite List.app_length, Nat.pow_add_r.\n ring.\nQed.\n\nLemma nat2dec2nat n :\n dec2nat (nat2dec n) = n.\nProof.\n rewrite dec2nat_alt.\n induction n using lt_wf_ind.\n unfold nat2dec.\n destruct n.\n - simpl; auto.\n - rewrite n2d_eqn.\n   rewrite n2d_alt by (apply Nat.lt_succ_r, Nat.div_lt; omega).\n   rewrite of_dec_app.\n   simpl length.\n   rewrite H by (apply Nat.div_lt; omega).\n   unfold of_dec.\n   rewrite nat2digit2nat by (apply Nat.mod_upper_bound; auto).\n   simpl length.\n   rewrite Nat.pow_1_r, Nat.pow_0_r, Nat.add_0_l, Nat.mul_1_r.\n   rewrite Nat.mul_comm. symmetry. now apply Nat.div_mod.\nQed.\n\nLemma nat2dec_inj n n' : nat2dec n = nat2dec n' -> n = n'.\nProof.\n intro EQ.\n now rewrite <- (nat2dec2nat n), <- (nat2dec2nat n'), EQ.\nQed.\n\nLemma n2d_spec dg p d count :\n norm (n2d (digit2nat dg + 10*p) d (S count)) =\n norm (n2d p (dg::d) count).\nProof.\n rewrite n2d_eqn'.\n case Nat.eqb_spec; intros.\n - destruct dg; try discriminate. simpl digit2nat in e.\n   replace p with 0 by omega.\n   now destruct count.\n - f_equal. f_equal.\n   + rewrite Nat.mul_comm, Nat.div_add, Nat.div_small; auto.\n     destruct dg; simpl; omega.\n   + f_equal.\n     rewrite Nat.mul_comm, Nat.mod_add, Nat.mod_small; auto.\n     apply digit2nat2digit.\n     destruct dg; simpl; omega.\nQed.\n\n(*\n<n0>|      d      |d0|\n<...        n ...>|d0|\n*)\n\nLemma d2n2d count n n0 (d0 d : dec) :\n n <= count ->\n n = d2n d n0 ->\n norm (n2d n d0 count) =\n norm (n2d n0 (d ++ d0) count).\nProof.\n revert count n n0 d0.\n induction d.\n - intros. simpl in *. now subst.\n - intros count n n0 d0 LT EQ.\n   assert (LE' : n <= S count) by omega.\n   rewrite (n2d_anycount count (S count)) by auto.\n   rewrite d2n_eqn in EQ.\n   rewrite (IHd _ _ _ d0 LE' EQ).\n   now rewrite n2d_spec.\nQed.\n\nDefinition Normal d := norm d = d.\n\nLemma n2d_norm n count acc :\n 0<n<=count -> Normal (n2d n acc count).\nProof.\n revert n acc.\n induction count.\n - intros. omega.\n - intros. destruct n. omega.\n   rewrite n2d_eqn.\n   destruct (Nat.le_gt_cases 10 (S n)).\n   + apply IHcount.\n     split. apply Nat.div_str_pos. omega.\n     apply Nat.div_le_upper_bound; omega.\n   + rewrite Nat.div_small by auto.\n     rewrite Nat.mod_small by auto.\n     rewrite n2d_mincount by omega.\n     remember (nat2digit (S n)) as dg.\n     simpl. destruct dg; red; auto.\n     generalize (nat2digit2nat (S n) H0).\n     rewrite <- Heqdg; simpl. discriminate.\nQed.\n\nLemma nat2dec_norm n : Normal (nat2dec n).\nProof.\n destruct n.\n - red; auto.\n - apply n2d_norm; omega.\nQed.\n\nLemma dec2nat2dec (d:dec) :\n  nat2dec (dec2nat d) = norm d.\nProof.\n rewrite <- (nat2dec_norm (dec2nat d)).\n unfold nat2dec.\n rewrite d2n2d with (n0:=0)(d:=d); auto.\n rewrite List.app_nil_r.\n rewrite n2d_mincount; auto with arith.\nQed.\n\nLemma dec2nat_norm d d' : norm d = norm d' ->\n dec2nat d = dec2nat d'.\nProof.\n intros EQ. apply nat2dec_inj. now rewrite !dec2nat2dec.\nQed.\n\nLemma dec2nat_inj d d' :\n dec2nat d = dec2nat d' -> norm d = norm d'.\nProof.\n intros. rewrite <- !dec2nat2dec. now f_equal.\nQed.\n\nLemma dec2nat_iff d d' : dec2nat d = dec2nat d' <-> norm d = norm d'.\nProof.\n split. apply dec2nat_inj. apply dec2nat_norm.\nQed.\n\nEnd NatProofs.\n\n\n(** Correctness proofs for the N conversions *)\n\nModule NProofs.\n\nImport DecN.\nOpen Scope N.\n\n(** We first state that these N conversions behave like\n    the nat conversions *)\n\nLemma d2n_nat d acc :\n d2n d acc = N.of_nat (DecNat.d2n d (N.to_nat acc)).\nProof.\n revert acc.\n induction d.\n - intros; simpl; now rewrite N2Nat.id.\n - intros. rewrite NatProofs.d2n_eqn.\n   replace (DecNat.digit2nat a + 10 * N.to_nat acc)%nat\n   with (N.to_nat (digit2n a + 10*acc)).\n   rewrite <- IHd; auto.\n   rewrite N2Nat.inj_add, N2Nat.inj_mul. f_equal.\n   now destruct a.\nQed.\n\nLemma dec2n_nat d : dec2n d = N.of_nat (DecNat.dec2nat d).\nProof.\n unfold dec2n. now rewrite d2n_nat.\nQed.\n\n(** Complements for N2Nat ... *)\n\nLemma N2Nat_div n m :\n (N.to_nat (n / m) = N.to_nat n / N.to_nat m)%nat.\nProof.\n case (N.eqb_spec m 0); [ intros -> | intros H ].\n - simpl. destruct n; simpl; auto.\n - apply Nat.div_unique with (N.to_nat (n mod m)).\n   + generalize (N.mod_upper_bound n m H).\n     unfold N.lt. rewrite N2Nat.inj_compare.\n     apply Nat.compare_lt_iff.\n   + rewrite <- N2Nat.inj_mul, <- N2Nat.inj_add.\n     f_equal. now apply N.div_mod.\nQed.\n\nLemma N2Nat_mod n m : m<>0 ->\n (N.to_nat (n mod m) = (N.to_nat n) mod (N.to_nat m))%nat.\nProof.\n intros.\n apply Nat.mod_unique with (N.to_nat (n / m)).\n - generalize (N.mod_upper_bound n m H).\n   unfold N.lt. rewrite N2Nat.inj_compare.\n   apply Nat.compare_lt_iff.\n - rewrite <- N2Nat.inj_mul, <- N2Nat.inj_add.\n   f_equal. now apply N.div_mod.\nQed.\n\nLemma N2Nat_le n m : (N.to_nat n <= N.to_nat m)%nat <-> n<=m.\nProof.\n now rewrite <- Nat.compare_le_iff, <- N2Nat.inj_compare.\nQed.\n\nLemma N2Nat_lt n m : (N.to_nat n < N.to_nat m)%nat <-> n<m.\nProof.\n now rewrite <- Nat.compare_lt_iff, <- N2Nat.inj_compare.\nQed.\n\nLemma n2digit_nat n : n < 10 ->\n n2digit n = DecNat.nat2digit (N.to_nat n).\nProof.\n destruct n as [|p]; trivial.\n destruct p as [p|p|]; trivial;\n  destruct p as [p|p|]; trivial;\n   destruct p as [p|p|]; trivial;\n    now destruct p.\nQed.\n\nLemma n2d_nat n acc count :\n n < Npos count ->\n n2d n acc count = DecNat.n2d (N.to_nat n) acc (Pos.to_nat count).\nProof.\n revert n acc.\n induction count.\n - intros.\n   destruct n. auto.\n   case_eq (Pos.to_nat (count~1)).\n   + generalize (Pos2Nat.is_pos (count~1)); omega.\n   + intros c Hc.\n     rewrite NatProofs.n2d_eqn'.\n     simpl Nat.eqb.\n     case Nat.eqb_spec.\n     * intros. generalize (Pos2Nat.is_pos p); omega.\n     * intros.\n       change 10%nat with (N.to_nat 10).\n       rewrite <- N2Nat_div, <- N2Nat_mod by discriminate.\n       simpl n2d.\n       case_eq (N.pos_div_eucl p 10); intros q r Hqr.\n       assert (Hq : q = Npos p / 10)\n         by (unfold N.div; simpl; now rewrite Hqr).\n       assert (Hr : r = Npos p mod 10)\n         by (unfold N.modulo; simpl; now rewrite Hqr).\n       rewrite <- Hq, <-Hr.\n       rewrite IHcount.\n       replace (DecNat.nat2digit (N.to_nat r)) with (n2digit r).\n       apply NatProofs.n2d_anycount.\n       { apply (N2Nat_le q (Npos count)).\n         rewrite Hq. apply N.div_le_upper_bound. discriminate.\n         zify; omega. }\n       { apply Nat.succ_le_mono. rewrite <- Hc.\n         rewrite <- N2Nat.inj_succ.\n         apply (N2Nat_le (N.succ q) (N.pos (count~1))).\n         apply N.le_succ_l.\n         rewrite Hq. apply N.div_lt_upper_bound. discriminate.\n         zify; omega. }\n       { apply n2digit_nat. rewrite Hr. now apply N.mod_lt. }\n       { rewrite Hq. apply N.div_lt_upper_bound. discriminate.\n         zify; omega. }\n - intros.\n   destruct n.\n   + simpl. now destruct (Pos.to_nat count~0).\n   + case_eq (Pos.to_nat (count~0)).\n     * generalize (Pos2Nat.is_pos (count~0)); omega.\n     * intros c Hc.\n       rewrite NatProofs.n2d_eqn'.\n       simpl Nat.eqb.\n       case Nat.eqb_spec.\n       { intros. generalize (Pos2Nat.is_pos p); omega. }\n       { intros.\n         change 10%nat with (N.to_nat 10).\n         rewrite <- N2Nat_div, <- N2Nat_mod by discriminate.\n         simpl n2d.\n         case_eq (N.pos_div_eucl p 10); intros q r Hqr.\n         assert (Hq : q = Npos p / 10)\n           by (unfold N.div; simpl; now rewrite Hqr).\n         assert (Hr : r = Npos p mod 10)\n           by (unfold N.modulo; simpl; now rewrite Hqr).\n         rewrite <- Hq, <-Hr.\n         rewrite IHcount.\n         replace (DecNat.nat2digit (N.to_nat r)) with (n2digit r).\n         apply NatProofs.n2d_anycount.\n         { apply (N2Nat_le q (Npos count)).\n           rewrite Hq. apply N.div_le_upper_bound. discriminate.\n           zify; omega. }\n         { apply Nat.succ_le_mono. rewrite <- Hc.\n           rewrite <- N2Nat.inj_succ.\n           apply (N2Nat_le (N.succ q) (N.pos (count~0))).\n           apply N.le_succ_l.\n           rewrite Hq. apply N.div_lt_upper_bound. discriminate.\n           zify; omega. }\n         { apply n2digit_nat. rewrite Hr. now apply N.mod_lt. }\n         { rewrite Hq. apply N.div_lt_upper_bound. discriminate.\n           zify; omega. }}\n - intros. now replace n with 0 by (zify;omega).\nQed.\n\nLemma n2dec_nat n : n2dec n = DecNat.nat2dec (N.to_nat n).\nProof.\n unfold n2dec.\n rewrite n2d_nat.\n - apply NatProofs.n2d_anycount; auto.\n   destruct n; zify; omega.\n - destruct n; zify; omega.\nQed.\n\n(** We now state direct correctness results over the N conversions *)\n\nLemma n2dec2n (n:N) : dec2n (n2dec n) = n.\nProof.\n now rewrite n2dec_nat, dec2n_nat, NatProofs.nat2dec2nat, N2Nat.id.\nQed.\n\nLemma n2dec_inj n n' : n2dec n = n2dec n' -> n = n'.\nProof.\n intro EQ.\n now rewrite <- (n2dec2n n), <- (n2dec2n n'), EQ.\nQed.\n\nDefinition Normal d := norm d = d.\n\nLemma n2dec_norm n : Normal (n2dec n).\nProof.\n rewrite n2dec_nat. apply NatProofs.nat2dec_norm.\nQed.\n\nLemma dec2n2dec (d:dec) :\n  n2dec (dec2n d) = norm d.\nProof.\n now rewrite n2dec_nat, dec2n_nat, Nat2N.id, NatProofs.dec2nat2dec.\nQed.\n\nLemma dec2n_norm d d' : norm d = norm d' ->\n dec2n d = dec2n d'.\nProof.\n intros EQ. apply n2dec_inj. now rewrite !dec2n2dec.\nQed.\n\nLemma dec2n_inj d d' :\n dec2n d = dec2n d' -> norm d = norm d'.\nProof.\n intros. rewrite <- !dec2n2dec. now f_equal.\nQed.\n\nLemma dec2n_iff d d' : dec2n d = dec2n d' <-> norm d = norm d'.\nProof.\n split. apply dec2n_inj. apply dec2n_norm.\nQed.\n\nEnd NProofs.\n\n\n(** Correctness proofs for the Positive conversions *)\n\nModule PosProofs.\n\nImport DecPos.\n\nLemma pos2dec2pos p : dec2pos (pos2dec p) = Some p.\nProof.\n unfold dec2pos, pos2dec.\n now rewrite NProofs.n2dec2n.\nQed.\n\nLemma dec2pos2dec d p : dec2pos d = Some p -> pos2dec p = norm d.\nProof.\n unfold dec2pos, pos2dec.\n case_eq (DecN.dec2n d); try discriminate.\n intros p' E. injection 1 as ->. rewrite <- E.\n apply NProofs.dec2n2dec.\nQed.\n\nLemma dec2pos_none d : dec2pos d = None <-> norm d = nil.\nProof.\n rewrite <- NProofs.dec2n2dec. unfold dec2pos.\n split.\n - now case_eq (DecN.dec2n d).\n - change nil with (DecN.n2dec 0).\n   intros E. apply NProofs.n2dec_inj in E. now rewrite E.\nQed.\n\nEnd PosProofs.\n\nModule ZProofs.\n\nImport DecZ.\nOpen Scope Z.\n\nLemma z2dec2z z : 0<=z -> dec2z (z2dec z) = z.\nProof.\n unfold dec2z, z2dec.\n destruct z; simpl.\n - trivial.\n - now rewrite NProofs.n2dec2n.\n - now destruct 1.\nQed.\n\nLemma dec2z2dec d : z2dec (dec2z d) = norm d.\nProof.\n unfold z2dec, dec2z.\n case_eq (DecN.dec2n d).\n - rewrite <- NProofs.dec2n2dec. now intros ->.\n - intros p <-. apply NProofs.dec2n2dec.\nQed.\n\nEnd ZProofs.\n\n(** Proofs concerning [Deci.succ] *)\n\nImport DecNat NatProofs.\n\nLemma bounded_succ_length d :\n  length (carry_proj (bounded_succ d)) = length d.\nProof.\n induction d; simpl; auto.\n destruct (bounded_succ d); simpl in *; auto.\n destruct a; simpl; congruence.\nQed.\n\nLemma bounded_succ_spec d :\n match bounded_succ d with\n | Carry d' => S (dec2nat d) = 10^length d /\\ dec2nat d' = 0\n | NoCarry d' => S (dec2nat d) < 10^length d /\\ dec2nat d' = S (dec2nat d)\n end.\nProof.\n induction d.\n - simpl; auto.\n - simpl bounded_succ.\n   assert (L:=bounded_succ_length d).\n   destruct bounded_succ; simpl in L.\n   + destruct a;\n     rewrite !dec2nat_alt in *; simpl of_dec; simpl length;\n     rewrite Nat.pow_succ_r', !Nat.add_0_r, <- ?Nat.add_succ_l, ?L;\n     destruct IHd as (->,->); split; auto;\n     generalize (Nat.pow_nonzero 10 (length d)); omega.\n   + rewrite !dec2nat_alt in *; simpl of_dec; simpl length.\n     rewrite L.\n     destruct IHd as (IH,->). split; auto.\n     rewrite Nat.pow_succ_r'.\n     rewrite <- Nat.add_succ_l.\n     assert (digit2nat a * 10 ^ length d <= 9 * 10 ^ length d).\n     { apply Nat.mul_le_mono_nonneg_r; auto with arith.\n       destruct a; simpl; auto with arith. }\n     omega.\nQed.\n\nLemma norm_length d : length (norm d) <= length d.\nProof.\n induction d; simpl; auto.\n destruct a; auto.\nQed.\n\nLemma bounded_succ_norm d :\n match bounded_succ d with\n | Carry d' => Normal d\n | NoCarry d' => Normal d -> Normal d'\n end.\nProof.\n destruct d as [|a d']; simpl; auto. reflexivity.\n destruct (bounded_succ d'); destruct a; unfold Normal; simpl; auto.\n intros.\n generalize (norm_length d'). rewrite H. simpl. omega.\nQed.\n\nLemma succ_norm d : norm (succ d) = succ (norm d).\nProof.\n induction d as [|a d IH].\n - simpl; auto.\n - unfold succ.\n   assert (L := bounded_succ_length (a::d)).\n   assert (H := bounded_succ_spec (a::d)).\n   assert (N := bounded_succ_norm (a::d)).\n   destruct (bounded_succ (a::d)) eqn:E.\n   + now rewrite N, E.\n   + simpl in E, L.\n     unfold succ in IH.\n     destruct (bounded_succ d) eqn:E'.\n     * destruct a; simpl; try discriminate;\n       rewrite ?E'; now injection E as <-.\n     * injection E as <-.\n       destruct a; simpl; auto; now rewrite E'.\nQed.\n\nLemma succ_to n : succ (nat2dec n) = nat2dec (S n).\nProof.\n unfold succ.\n assert (L := bounded_succ_length (nat2dec n)).\n assert (H := bounded_succ_spec (nat2dec n)).\n assert (N := bounded_succ_norm (nat2dec n)).\n destruct (bounded_succ (nat2dec n)); simpl in *.\n - destruct H as (H,H').\n   rewrite nat2dec2nat in H.\n   change (D1 :: l) with (norm (D1 :: l)).\n   rewrite <- nat2dec_norm.\n   apply dec2nat_inj.\n   rewrite nat2dec2nat. rewrite H.\n   rewrite dec2nat_alt in *. simpl. rewrite H', L. omega.\n - rewrite nat2dec2nat in H.\n   rewrite <- (N (nat2dec_norm n)), <- (nat2dec_norm (S n)).\n   apply dec2nat_inj.\n   now rewrite nat2dec2nat.\nQed.\n\nLemma of_succ d : dec2nat (succ d) = S (dec2nat d).\nProof.\n apply nat2dec_inj.\n rewrite <- succ_to.\n rewrite !dec2nat2dec.\n apply succ_norm.\nQed.\n\nLemma succ_inj d d' :\n succ d = succ d' -> norm d = norm d'.\nProof.\n intros. apply dec2nat_inj.\n assert (E : S (dec2nat d) = S (dec2nat d')).\n { rewrite <- !of_succ. now f_equal. }\n now injection E.\nQed.\n\n(** Proofs concerning [Deci.succ] *)\n\nLemma to_lt n n' : n < n' -> lt (nat2dec n) (nat2dec n').\nProof.\n induction 1.\n + rewrite <- succ_to. apply Succ.\n + apply Trans with (nat2dec m); trivial.\n   rewrite <- succ_to. apply Succ.\nQed.\n\nLemma of_lt d d' : lt d d' -> dec2nat d < dec2nat d'.\nProof.\n induction 1.\n + rewrite of_succ. auto.\n + omega.\nQed.\n\nLemma to_lt_iff n n' :  n < n' <-> lt (nat2dec n) (nat2dec n').\nProof.\n split; [apply to_lt|].\n intros H. apply of_lt in H. now rewrite !nat2dec2nat in H.\nQed.\n\nLemma of_lt_iff d d' :\n  dec2nat d < dec2nat d' <-> lt (norm d) (norm d').\nProof.\n rewrite to_lt_iff. now rewrite !dec2nat2dec.\nQed.\n\nLemma lt_norm d d' : lt d d' -> lt (norm d) (norm d').\nProof.\n rewrite <- of_lt_iff. apply of_lt.\nQed.\n\nLemma lt_irrefl d d' : lt d d' -> norm d <> norm d'.\nProof.\n intros L E.\n apply of_lt in L.\n apply dec2nat_norm in E.\n omega.\nQed.\n\nLemma lt_antisym d d' : lt d d' -> ~lt d' d.\nProof.\n intros L L'. apply of_lt in L. apply of_lt in L'. omega.\nQed.\n\nLemma lt_trans d1 d2 d3 : lt d1 d2 -> lt d2 d3 -> lt d1 d3.\nProof.\n apply Trans.\nQed.\n\nLemma lt_norm_total d d' :\n { lt (norm d) (norm d') } + { norm d = norm d' } + { lt (norm d') (norm d) }.\nProof.\n destruct (CompareSpec2Type (Nat.compare_spec (dec2nat d) (dec2nat d'))).\n - left; right. now apply dec2nat_inj.\n - left; left. now apply of_lt_iff.\n - right; now apply of_lt_iff.\nQed.\n", "meta": {"author": "letouzey", "repo": "baseconv", "sha": "9acc385745c1ea27a2d7891726d190b6e50d3325", "save_path": "github-repos/coq/letouzey-baseconv", "path": "github-repos/coq/letouzey-baseconv/baseconv-9acc385745c1ea27a2d7891726d190b6e50d3325/DeciProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.724817911898831}}
{"text": "Require Import Coq.Sets.Ensembles.\nRequire Import Coq.Logic.Classical.\nRequire Import Coq.Logic.Epsilon.\nRequire Import Finite_sets.\nRequire Import Coq.Sets.Finite_sets_facts.\nRequire Import Coq.Sets.Image.\n\nNotation \"a ∈ A\" := (In _ A a) (at level 10).\nNotation \"a ∉ A\" := (~In _ A a) (at level 10).\nNotation \"A ⊆ B\" := (Included _ A B) (at level 70).\nNotation \"B ∩ C\" := (Intersection _ B C) (at level 60, right associativity).\nNotation \"B ∪ C\" := (Union _ B C) (at level 65, right associativity).\nNotation \"[ a ]\" := (Singleton _ a) (at level 0, right associativity).\n\nTheorem classicT : forall P:Prop, {P} + {~P}.\nProof.\n  intros. assert {x:bool | if x then P else ~P}.\n  { apply constructive_indefinite_description.\n    destruct (classic P).\n    - exists true. auto.\n    - exists false. auto. }\n  destruct H, x; auto.\nQed.\n\n(* 映射 *)\nDefinition Map {U V} A B (f : U -> V) :=\n  forall a, a ∈ A -> (f a) ∈ B.\n\n(* 原象集 preimage set *)\nDefinition preimage_set {U V} (f : U -> V) y:= fun x => (f x) = y.\n\n(* f是A到Ā的满射 *)\nDefinition Surjective {U V} A B (f : U -> V) :=\n  Map A B f /\\ forall y , y ∈ B -> exists x, x∈A /\\ (f x) = y.\n\n(* f是A到Ā的单射 a≠b => f(a)≠f(b) *)\nDefinition Injective {U V} A B (f : U -> V) :=\n  Map A B f /\\ forall a b, a ∈ A -> b ∈ A -> f a = f b -> a = b.\n\n(* f是A到Ā的双射 *)\nDefinition Bijective {U V} A B (f : U -> V) :=\n  Surjective A B f /\\ Injective A B f.\n\n(* f是A到Ā的双射 *)\nDefinition Bijective_ex {U V} A B  :=\n  exists (f : U -> V), Surjective A B f /\\ Injective A B f.\n\nDefinition pick {A} {P : A->Prop} (l :exists x, P x) :=\n  proj1_sig (constructive_indefinite_description _ l).\n\n(* 运算f在G中的封闭性 *)\nDefinition Closed {U:Type} (f:U->U->U) (G:Ensemble U):=\n  forall a b:U, a∈G -> b∈G -> (f a b)∈G.\n\n(* 函数f在G中封闭性 *)\nDefinition Closedfun {U:Type} (f:U->U) (G:Ensemble U):=\n  forall x:U, x∈G -> (f x)∈G.\n\n(* 结合律 *)\nDefinition associative {U:Type} (f:U->U->U) (G: Ensemble U):=\n  forall x y z: U, x∈G -> y∈G -> z∈G -> f (f x y) z = f x (f y z).\n\n(* 单位元 *)\nDefinition id {U:Type} f (e:U) x:=\n  f e x = x /\\ f x e = x.\n\n(* 逆元 *)\nDefinition idinv {U:Type} (f:U->U->U) (e:U) x y:=\n   f x y = e /\\ f y x = e.\n\n(*群*)\nClass Group (U: Type) :={\n  G: Ensemble U;\n  mul: U->U->U;\n  e: U;\n  inv : U->U;\n  closed_Gr: Closed mul G;\n  assoc_Gr: associative mul G;\n  e_In_G : e∈G;\n  id_Gr: forall x:U, x∈G ->  id mul e x;\n  closedinv_Gr : Closedfun inv G;\n  invGr : forall x:U, x∈G -> idinv mul e x (inv x)\n  }.\nNotation \"a · b\" := (mul a b)(at level 10, left associativity).\nNotation \"x ⁻¹\" := (inv x)(at level 5, left associativity).\n\nLemma id_l : forall {U} (GG: Group U) a, a∈G -> e·a=a.\nProof. intros. destruct (id_Gr a); auto. Qed.\nLemma id_r : forall {U} (GG: Group U) a, a∈G -> a·e=a.\nProof. intros. destruct (id_Gr a); auto. Qed.\nLemma inv_l : forall {U} (GG: Group U) a, a∈G -> a⁻¹·a=e.\nProof. intros. destruct (invGr a); auto. Qed.\nLemma inv_r : forall {U} (GG: Group U) a, a∈G -> a·a⁻¹=e.\nProof. intros. destruct (invGr a); auto. Qed.\n\nLtac simp :=\n  repeat (rewrite -> (id_l _ _) ||\n          rewrite -> (id_r _  _) ||\n          rewrite -> (inv_l _ _) ||\n          rewrite -> (inv_r _ _)).\nLtac simpH H:=\n         (rewrite -> (id_l _ _)  in H||\n          rewrite -> (id_r _  _) in H||\n          rewrite -> (inv_l _ _) in H||\n          rewrite -> (inv_r _ _) in H).\n\nClass subGroup {U:Type} (Gr:Group U) :={\n  H: Ensemble U;\n  subsG: H⊆G;\n  closed_H : Closed mul H;\n  id_H: e∈H;\n  closed_H_inv: Closedfun inv H\n  }.\nGlobal Hint Resolve e_In_G id_H : group.\nLtac autog :=\n  match goal with\n  | |- (?a · ?n) ∈ G => apply closed_Gr; autog\n  | |- (?a)⁻¹∈ G => apply closedinv_Gr; autog\n  | |- (?a=e·?a) => rewrite id_l; autog\n  | |- (?a=?a·e) => rewrite id_r; autog\n  | |- (e=?a⁻¹·?a) => rewrite inv_l; autog\n  | |- (e=?a·?a⁻¹) => rewrite inv_r; autog\n  | |- (e·?a=?a) => apply id_l; autog\n  | |- (?a·e=?a) => apply id_r; autog\n  | |- (?a⁻¹·?a=e) => apply inv_l; autog\n  | |- (?a·?a⁻¹=e) => apply inv_r; autog\n  | |- e∈G => apply e_In_G\n  | |- e∈H => apply id_H\n  | |- (?a · ?n) ∈ H => apply closed_H; autog\n  | |- (?a)⁻¹∈ H => apply closed_H_inv; autog\n  | _ : ?a∈ H |- (?a)∈ G => apply subsG; autog\n  | |- _ => auto with group\n  end.\n\n\n(* Definition invariant_subgroup {U} {Gr:Group U} (SG: subGroup Gr) :=\n  forall g, g∈G -> forall h, h∈G -> (g·h·g⁻¹) ∈ H. *)\n\n(* 模H同余 *)\nDefinition congruent {U} {Gr:Group U} (SG: subGroup Gr) a b : Prop :=\n  a∈G /\\ b∈G /\\ exists h, h∈H /\\ a = b · h.\n\nDefinition reflexive {A:Type} (R:A->A->Prop) (G: Ensemble A):=\n  forall x:A, x∈G -> R x x.\nDefinition transitive {A:Type} (R:A->A->Prop) (G: Ensemble A):=\n  forall x y z:A, x∈G -> y∈G -> z∈G -> R x y -> R y z -> R x z.\nDefinition symmetric {A:Type} (R:A->A->Prop) (G: Ensemble A):=\n  forall x y:A, x∈G -> y∈G -> R x y -> R y x.\n\nClass equivalence {A:Type} (R:A->A->Prop) (G: Ensemble A): Prop :=\n      { equiv_refl : reflexive R G;\n        equiv_trans : transitive R G;\n        equiv_sym : symmetric R G}.\n\nTheorem equi_congruent {U} {Gr:Group U} (SG: subGroup Gr): equivalence\n  (congruent SG) G.\nProof.\n  split.\n  - repeat split; auto. exists e. split; autog.\n  - repeat split; auto. destruct H3 as [? [? [? []]]], H4 as [? [? [? []]]].\n    subst. exists (x1·x0); split; autog. apply assoc_Gr; autog.\n  - repeat split; auto. destruct H2 as [? [? [? []]]]. subst.\n    exists x0⁻¹. split; autog. rewrite assoc_Gr; autog. simp; autog.\nQed.\n\n(*陪集 *)\nDefinition coset {U} {Gr:Group U} a (SG: subGroup Gr) :Ensemble U:=\n  fun x=> exists h, h∈H /\\ x = a·h.\n  \nTheorem eq_coset_congruent : forall {U} {Gr:Group U} (SG: subGroup Gr) a,\n  a∈G -> congruent SG a = coset a SG.\nProof.\n  intros. apply Extensionality_Ensembles. split.\n  - red; intros. destruct H1 as [? [? [? []]]]. red; red.\n    subst. exists x0⁻¹. split; autog. rewrite assoc_Gr; autog. simp; autog.\n  - red; intros. destruct H1 as [? []]. subst.\n    repeat split; autog. exists x0⁻¹. split; autog.\n    rewrite assoc_Gr; autog. simp; autog.\nQed.\n\n(*所有陪集的集族G/H 商集*)\nDefinition quotient_set {U} (Gr:Group U) (SG: subGroup Gr) :Ensemble (Ensemble U):=\n  fun x => exists a, a∈G /\\ x = coset a SG.\n\n(*子群是正规子群*)\nDefinition normal_subgroup {U} {Gr:Group U} (SG: subGroup Gr) :Prop :=\n  forall g h, g∈G -> h∈H -> g·h·g⁻¹ ∈H.\n\n(* 子群SG的陪集乘法 *)\nDefinition mul_coset {U} (Gr:Group U) (SG: subGroup Gr):\n  Ensemble U -> Ensemble U -> Ensemble U :=\n  fun x y => \n  match (classicT (x∈(quotient_set Gr SG))) with\n  | left l0 => match (classicT (y∈(quotient_set Gr SG))) with\n               | left l1 => coset ((pick l0)·(pick l1)) SG\n               | _ => Empty_set U\n               end\n  | _ => Empty_set U\n  end.\n\n(* 子群SG的陪集的逆运算 *)\nDefinition inv_coset {U} (Gr:Group U) (SG: subGroup Gr):\n  Ensemble U -> Ensemble U:= fun x=> \n  match (classicT (x∈(quotient_set Gr SG))) with\n  | left l0 => coset (inv (pick l0)) SG\n  | _ => Empty_set U\n  end.\n\n\nFact inv_inv : forall {U} (Gr:Group U) d, d∈G -> (d ⁻¹) ⁻¹ = d.\nProof.\n  intros. pose proof invGr. unfold idinv in H1.\n  assert (d ⁻¹ ⁻¹· d⁻¹ = d·d⁻¹).\n  { simp; autog. }\n  assert (d ⁻¹ ⁻¹ · d ⁻¹ ·d = d · d ⁻¹·d). { rewrite H2; auto. }\n  rewrite assoc_Gr in H3; autog. repeat (simpH H3; autog).\nQed.\nGlobal Hint Resolve inv_inv:group.\n\nLemma distr_inv : forall {U} (Gr:Group U) a b,\n  a∈G -> b∈G -> (a·b)⁻¹ = b⁻¹· a⁻¹.\nProof.\n  intros. pose proof id_Gr. pose proof invGr. red in H2, H3.\n  assert (Ha : a ⁻¹ ∈ G). { apply closedinv_Gr; auto. }\n  assert (Hb : b ⁻¹ ∈ G). { apply closedinv_Gr; auto. }\n  assert ((a · b) ⁻¹·(a · b) = b ⁻¹ · a ⁻¹·(a · b)).\n  { destruct (H3 (a · b)). apply closed_Gr; auto.\n    rewrite H5. rewrite assoc_Gr; auto.\n    pattern (a ⁻¹ · (a · b)). rewrite <-assoc_Gr; auto.\n    destruct (H3 a), (H3 b), (H2 b); auto. rewrite H7, H10, H9. auto.\n    apply closed_Gr; auto. }\n  assert ((a · b) ⁻¹ · (a · b)·(a · b) ⁻¹ = b ⁻¹ · a ⁻¹ · (a · b)·(a · b) ⁻¹).\n  { rewrite H4; auto. }\n  destruct (H3 (a · b)). apply closed_Gr; auto.\n  rewrite H7 in H5. destruct (H2 (a · b) ⁻¹).\n  apply closedinv_Gr; apply closed_Gr; auto. rewrite H8 in H5.\n  assert ((a · b) ∈ G). { apply closed_Gr; auto. }\n  assert ((a · b) ⁻¹∈ G). { apply closedinv_Gr; auto. }\n  rewrite assoc_Gr in H5; auto. rewrite H6 in H5. rewrite H5.\n  rewrite assoc_Gr; auto. f_equal. destruct (H2 (a⁻¹)); auto.\n  apply e_In_G. apply closed_Gr; auto.\nQed.\nGlobal Hint Resolve distr_inv:group.\n\n\nLemma coset_eq : forall {U} (Gr:Group U) (SG: subGroup Gr) a b, a∈G -> b∈G ->\n  congruent SG a b <-> coset a SG = coset b SG.\nProof.\n  split; intros.\n  - destruct H2 as [? [? [? []]]]. apply Extensionality_Ensembles.\n    split; red; intros.\n    + destruct H6 as [? []]. red; red.\n      subst. exists (x · x1). split; autog. apply assoc_Gr; autog.\n    + destruct H6 as [? []]. red; red. subst.\n      exists (x⁻¹·x1); split; autog. repeat rewrite <-assoc_Gr; autog.\n      f_equal. rewrite assoc_Gr; autog. simp; autog.\n  - pose proof eq_coset_congruent _ _ H0.\n    pose proof eq_coset_congruent _ _ H1.\n    rewrite H2 in H3. rewrite <-H4 in H3.\n    pose proof equi_congruent _ as [].\n    unfold reflexive in *. pose proof equiv_refl0 b.\n    rewrite H3; auto.\nQed.\n\nLemma congruent_inv : forall {U} (Gr:Group U) (SG: subGroup Gr) a b,\n  normal_subgroup SG ->\n  a∈G -> b∈G -> congruent SG a b ->\n  congruent SG a⁻¹ b⁻¹.\nProof.\n  intros. repeat split. apply closedinv_Gr; auto. apply closedinv_Gr; auto.\n  destruct H3 as [? [? [? []]]]. subst. pose proof subsG x H5.\n  rewrite distr_inv; auto. pose proof closedinv_Gr x H6.\n  pose proof closedinv_Gr _ H4.\n  pose proof closed_H_inv _ H5.\n  exists (b·x⁻¹·b⁻¹); split; auto.\n  repeat rewrite <-assoc_Gr; auto.\n  pose proof id_Gr. pose proof invGr. red in H10, H11.\n  destruct (H11 b); auto. rewrite H13. destruct (H10 x ⁻¹); auto.\n  rewrite H14; auto. apply closed_Gr; auto.\nQed.\n\n\n\n\nDefinition finite_group {U} (Gr: Group U) := Finite _ G.\n\n\n\nLemma empty_not_inhabited : forall {U} (A:Ensemble U),\n  (Empty_set _ = A) <-> (~ Inhabited _ A).\nProof.\n  split; intros.\n  - intro. destruct H1. rewrite <-H0 in H1. destruct H1.\n  - apply Extensionality_Ensembles; split.\n    + red; intros. destruct H1.\n    + red; intros. destruct H0. apply Inhabited_intro with x; auto.\nQed.\n\nLemma not_empty_inhabited : forall {U} (A:Ensemble U),\n  ~(Empty_set _ = A) <-> Inhabited _ A.\nProof.\n  split; intros.\n  - destruct (classic (Inhabited U A)); auto.\n    elim H0. apply Extensionality_Ensembles; split.\n    + red; intros. destruct H2.\n    + red; intros. destruct H1. apply Inhabited_intro with x; auto.\n  - intro. destruct H0. rewrite <-H1 in H0. destruct H0.\nQed.\n\nLemma singlelen_set : forall {U} (a x: U), a ∈ [x] -> a = x.\nProof.\n  intros. destruct H0. auto.\nQed.\n\nLemma eq_Add_Subtract: forall {U} (x:U) A,\n  x ∈ A ->  Add U (Subtract U A x) x = A.\nProof.\n  intros.\n  apply Extensionality_Ensembles; split.\n  - red; intros.\n    destruct H1.\n    + destruct H1; auto.\n    + destruct H1; auto.\n  - red; intros. destruct (classic (x0 ∈ [x])).\n    + apply Union_intror. auto.\n    + apply Union_introl. split; auto.\nQed.\n\nTheorem bijection_card : forall n {U V} A B (f : U -> V),\n  Bijective A B (f : U -> V) -> cardinal _ A n\n  -> cardinal _ B n.\nProof.\n  intro. induction n; intros.\n  - apply cardinalO_empty in H1.\n    destruct H0 as [[][]].\n    destruct (classic (B=(Empty_set _))).\n    + rewrite H5. constructor.\n    + assert (Inhabited _ B).\n      { apply not_empty_inhabited; auto. }\n      destruct H6. apply H2 in H6 as [x0 []].\n      rewrite H1 in H6; destruct H6.\n  - assert (Inhabited _ A).\n    { destruct (classic (Inhabited U A)); auto.\n      apply empty_not_inhabited in H2.\n      rewrite <-H2 in H1. pose proof cardinal_Empty U _ H1.\n      inversion H3.\n      }\n    destruct H2.\n    pose proof card_soustr_1 _ _ _ H1 _ H2. simpl in H3.\n    assert (HSx: Bijective (Subtract U A x) (Subtract V B (f x)) f).\n    { destruct H0 as [[][]].\n      split.\n      - split.\n        + red; intros. destruct H7. split. apply H0; auto.\n          intro. elim H8. apply singlelen_set in H9.\n          apply H6 in H9; autog. subst; split.\n        + intros. destruct H7. apply H4 in H7 as [x0 []].\n          exists x0. split; auto. split; auto.\n          intro. elim H8. apply singlelen_set in H10.\n          subst. split.\n      - split.\n        + red; intros. destruct H7. split.\n          apply H0; auto. intro. destruct H8.\n          apply singlelen_set in H9. apply H6 in H9; autog.\n          subst. split.\n        + intros. apply H6; auto.\n          * destruct H7; auto.\n          * destruct H8; auto.\n    }\n    pose proof IHn _ _ _ _ _ HSx H3.\n    assert (A = Add _ (Subtract U A x) x).\n    { apply Extensionality_Ensembles. split.\n      - red; intros. rewrite eq_Add_Subtract; auto.\n      - rewrite eq_Add_Subtract; auto.\n        red; intro; auto.\n      }\n    assert (B = Add _ (Subtract V B (f x)) (f x)).\n    { apply Extensionality_Ensembles. split.\n      - red; intros. rewrite eq_Add_Subtract; auto.\n        apply H0; auto.\n      - rewrite eq_Add_Subtract; auto.\n        red; intro; auto. apply H0; auto.\n      }\n    rewrite H6. constructor; auto. intro.\n    destruct H7. destruct H8. split.\nQed.\n\n\n\nDefinition family_union {U} (A: Ensemble (Ensemble U)) : Ensemble U:=\n  fun x => exists X, x∈X /\\ X∈A.\n\nLemma empty_family_empty : \n  forall {U}, (family_union (Empty_set (Ensemble U))) = Empty_set _.\nProof.\n  intros. apply Extensionality_Ensembles; split.\n  - red; intros. destruct H0 as [? [? []]].\n  - red; intros. destruct H0.\nQed.\n\nTheorem card_union : forall N {U} (A B: Ensemble U) M,\n  cardinal _ A M -> cardinal _ B N ->\n  A ∩ B = (Empty_set _) ->\n  cardinal _ (A∪B) (N+M).\nProof.\n  intro. induction N.\n  - intros. simpl. apply cardinalO_empty in H1. rewrite H1.\n    assert ((A ∪ Empty_set U)=A).\n    { apply Extensionality_Ensembles; split.\n      - red; intros. destruct H3; auto. destruct H3.\n      - red; intros. apply Union_introl; auto.\n      }\n    rewrite H3; auto.\n  - intros.\n    assert (Inhabited _ B).\n    { destruct (classic (Inhabited _ B)); auto.\n      apply empty_not_inhabited in H3.\n      rewrite <-H3 in H1. pose proof cardinal_Empty _ _ H1.\n      inversion H4.\n      } destruct H3 as [a ?].\n    assert (cardinal _ (Subtract _ B a) N).\n    { pose proof card_soustr_1 _ _ _ H1 _ H3. simpl in H4. auto. }\n    assert (~a∈A). { intro. assert (a∈(A ∩ B)). split; auto.\n      rewrite H2 in H6. destruct H6. }\n    assert (cardinal _ (Add _ A a) (S M)).\n      { apply card_add; auto. }\n    assert ((Add U A a)∪(Subtract U B a)=A∪B).\n      { apply Extensionality_Ensembles. split.\n        - red; intros. destruct H7.\n          + destruct H7. apply Union_introl; auto.\n            destruct H7. apply Union_intror; auto.\n          + destruct H7. apply Union_intror; auto.\n        - red; intros. destruct H7.\n          + apply Union_introl. apply Union_introl; auto.\n          + destruct (classic (x∈[a])).\n            * destruct H8. apply Union_introl.\n              apply Union_intror; split.\n            * apply Union_intror. split; auto.\n        }\n    assert ((Add U A a)∩(Subtract U B a)= (Empty_set _)).\n      { apply Extensionality_Ensembles. split.\n        - red; intros. destruct H8. destruct H9.\n          destruct H8.\n          + rewrite <- H2; split; auto.\n          + tauto.\n        - red; intros. destruct H8.\n        } simpl.\n    rewrite PeanoNat.Nat.add_comm.\n    assert (((S M) + N)=(S (M + N))). { simpl. auto. }\n    rewrite <- H9. rewrite PeanoNat.Nat.add_comm.\n    pose proof IHN _ _ _ _ H6 H4 H8. rewrite H7 in H10.\n    auto.\nQed.\n\n\nTheorem family_add : forall N {U} (A:Ensemble (Ensemble U)) x M,\n  cardinal _ (family_union A) M -> cardinal _ x N ->\n  (forall X, X∈A -> X ∩ x = (Empty_set _)) ->\n  cardinal _ (family_union (Add (Ensemble U) A x)) (N+M).\nProof.\n  intro. induction N.\n  - intros. simpl. pose proof cardinalO_empty _ _ H1.\n    rewrite H3 in *.\n    assert ((family_union A) = (family_union (Add (Ensemble U) A x))).\n    { apply Extensionality_Ensembles; split.\n      - red; intros. destruct H4 as [? []].\n        rewrite H3. unfold family_union. exists x1. split; auto.\n        apply Union_introl; auto.\n      - red; intros. destruct H4 as [? []].\n        red. red. unfold Add in H5. rewrite H3 in H5.\n        destruct H5. eauto. destruct H5. destruct H4.\n      }\n    rewrite H3 in *. rewrite <-H4. auto.\n  - intros. simpl. \n    assert ((family_union (Add (Ensemble U) A x) = (family_union A)∪x)).\n    { apply Extensionality_Ensembles; split.\n      - red; intros.\n        destruct H3. destruct H3. destruct H4.\n        + apply Union_introl. exists x1; auto.\n        + destruct H4.\n          apply Union_intror. auto.\n      - red; intros. destruct H3.\n        + destruct H3. destruct H3. \n          exists x1. split; auto. unfold Add.\n          apply Union_introl. auto.\n        + red. red. exists x.\n          split; auto.\n          apply Union_intror; split. }\n    rewrite H3.\n    assert (S (N + M) = S N + M); auto.\n    rewrite H4. apply card_union; auto.\n    apply Extensionality_Ensembles; split.\n    + red; intros.\n      destruct H5, H5, H5.\n      pose proof H2 _ H7. rewrite <- H8.\n      split; auto.\n    + red; intros. destruct H5.\nQed.\n\nTheorem family_card : \n  forall {U} Q (A:Ensemble (Ensemble U)) n,cardinal _ A Q ->\n  (forall X, X∈A -> cardinal _ X n) ->\n  (forall X Y, X∈A -> Y∈A -> X<>Y -> X ∩ Y = (Empty_set _)) ->\n  cardinal _ (family_union A) (Q*n).\nProof.\n  intros U Q. induction Q.\n  - intros. simpl. pose proof cardinalO_empty _ _ H0.\n    rewrite H3. rewrite empty_family_empty. constructor.\n  - intros. assert (Inhabited _ A).\n    { destruct (classic (Inhabited _ A)); auto.\n      apply empty_not_inhabited in H3.\n      rewrite <-H3 in H0. pose proof cardinal_Empty _ _ H0.\n      inversion H4.\n      } destruct H3 as [a ?].\n    assert (cardinal _ (Subtract _ A a) Q).\n    { pose proof card_soustr_1 _ _ _ H0 _ H3. simpl in H4. auto. }\n    assert (HS1: forall X, X ∈ (Subtract _ A a) -> cardinal U X n).\n    { intros. apply H1. destruct H5; auto. }\n    assert (HS2: forall X Y, X ∈ (Subtract _ A a) -> Y ∈ (Subtract _ A a)\n     -> X<>Y -> X ∩ Y = Empty_set _).\n    { intros. apply H2; destruct H5; auto. destruct H6; auto. }\n    pose proof IHQ _ _ H4 HS1 HS2.\n    assert (Add _ (Subtract (Ensemble U) A a) a = A).\n      { apply eq_Add_Subtract; auto. }\n    simpl. rewrite <-H6.\n    apply family_add; auto. intros. destruct H7.\n    apply H2; auto. intro. elim H8. subst; split.\nQed.\n\n(* 集合的阶 *)\nDefinition order {U} (A:Ensemble U) (FA: Finite _ A) :=\n  pick (finite_cardinal _ _ FA).\n\nTheorem eq_order : forall {U V} A B (f:U->V) (FA: Finite _ A)\n  (FB: Finite _ B), Bijective A B f -> order _ FA = order _ FB.\nProof.\n  intros.\n  unfold order. unfold pick.\n  repeat destruct constructive_indefinite_description; simpl.\n  pose proof bijection_card _ _ _ _ H0 c.\n  pose proof cardinal_unicity _ _ _ c0 _ H1. auto.\nQed.\n\n(* Langrange's_theorem *)\nSection Langrange's_theorem.\n\nContext \n  {U}\n  (Gr: Group U)\n  (SG : subGroup Gr)\n  (FG: finite_group Gr).\n\n(* 群的阶 *)\nDefinition order_group :=\n  order G FG.\n\n\nLemma finite_subgroup : Finite _ H. \nProof.\n  apply Finite_downward_closed with G; auto. apply subsG.\nQed.\n\nDefinition map_H_coset a := fun h => a·h.\n\nLemma bijective_H_coset :\n  forall a, a∈G -> Bijective H (coset a SG) (map_H_coset a).\nProof.\n  intros. split.\n  - split.\n    + red; intros. red; red. exists a0.\n      split; auto.\n    + intros. unfold map_H_coset.\n      destruct H1 as [? []]. exists x; split; auto.\n  - split.\n    + red; intros. red; red. exists a0.\n      split; auto.\n    + intros. unfold map_H_coset in H3.\n      assert (a⁻¹ ·(a · a0) = a⁻¹ ·(a · b)).\n      { rewrite H3; auto. }\n      rewrite <- assoc_Gr in H4; autog. simpH H4; autog.\n      simpH H4; autog. rewrite <- assoc_Gr in H4; autog.\n      simpH H4; autog. simpH H4; autog.\nQed.\n\nLemma finite_coset :\n  forall a, a∈G -> Finite _ (coset a SG).\nProof.\n  pose proof finite_cardinal _ _ finite_subgroup as [N CH].\n  intros. pose proof bijection_card.\n  pose proof H1 N _ _ _ _ _ (bijective_H_coset _ H0) CH.\n  apply cardinal_finite in H2. auto.\nQed.\n(* Theorem H_im_is_coset : forall a, a∈G -> \n  (Im _ _ H (map_H_coset a)) = (coset a SG).\nProof.\n  intros. *)\n\nDefinition map_G_quotient :U -> Ensemble U:=\n  fun a => coset a SG.\n\nLemma im_is_quotient_set: (Im _ _ G map_G_quotient) = (quotient_set Gr SG).\nProof.\n  apply Extensionality_Ensembles; split.\n  - red; intros.\n    destruct H0.\n    unfold map_G_quotient in H1.\n    red; red.\n    exists x; split; auto.\n  - red; intros.\n    destruct H0 as [? []].\n    unfold map_G_quotient.\n    pose proof Im_intro _ _ G map_G_quotient x0 H0.\n    apply H2.\n    unfold map_G_quotient; auto.\nQed.\n\nTheorem finite_quotient_set :\n  Finite _ (quotient_set Gr SG).\nProof.\n  pose proof finite_image.\n  pose proof H0 _ _ G map_G_quotient FG.\n  rewrite im_is_quotient_set in H1; auto.\nQed.\n\nTheorem quotient_set_inter_empty : \n  forall X Y, X∈(quotient_set Gr SG) -> Y∈(quotient_set Gr SG) ->\n    X<>Y -> X∩Y= (Empty_set _).\nProof.\n  intros. destruct H0, H0, H1, H1.\n  apply Extensionality_Ensembles; split.\n  - red; intros. elim H2. rewrite H3, H4.\n    apply coset_eq; autog. destruct H5.\n    repeat split; auto.\n    rewrite H3 in H5. rewrite H4 in H6.\n    destruct H5 as [? []], H6 as [? []].\n    rewrite H7 in H8. assert (x · x2· x2⁻¹ = x0 · x3· x2⁻¹).\n    { rewrite H8; auto. }\n    rewrite assoc_Gr in H9; autog. simpH H9; autog.\n    simpH H9; autog. rewrite assoc_Gr in H9; autog.\n    exists (x3 · x2 ⁻¹); split; autog.\n  - red; intros. destruct H5.\nQed.\n\nTheorem family_quotient_set_eq_G :\n  (family_union (quotient_set Gr SG)) = G.  \nProof.\n  apply Extensionality_Ensembles; split.\n  - red; intros. destruct H0 as [? []].\n    destruct H1 as [? []]. rewrite H2 in H0.\n    destruct H0 as [? []]. subst. autog.\n  - red; intros. red; red.\n    exists (coset x _); split.\n    + red; red. exists e; split; autog.\n    + red; red. exists x; split; auto.\nQed.\n\nTheorem Langrange's_theorem :\n  (order _ FG) = (order _ finite_quotient_set)* (order _ finite_subgroup).\nProof.\n  pose proof finite_cardinal _ _ finite_quotient_set as [Q ?].\n  assert ((order _ finite_quotient_set) = Q).\n  { unfold order. unfold pick.\n    destruct constructive_indefinite_description; simpl.\n    pose proof cardinal_unicity _ _ _ H0 _ c. auto. }\n  rewrite H1.\n  pose proof finite_cardinal _ _ finite_subgroup as [N ?].\n  assert ((order _ finite_subgroup) = N).\n  { unfold order. unfold pick.\n    destruct constructive_indefinite_description; simpl.\n    pose proof cardinal_unicity _ _ _ H2 _ c.\n    auto. }\n  rewrite H3.\n  assert (forall a (ag: a∈G),N = order (coset a SG) (finite_coset _ ag) ).\n  { intros. rewrite <- H3.\n    apply eq_order with (map_H_coset a). apply bijective_H_coset; auto. }\n  assert (forall A, A∈(quotient_set Gr SG) -> cardinal _ A N).\n  { intros. destruct H5. destruct H5. pose proof H4 _ H5.\n    unfold order in H7. unfold pick in H7.\n    destruct constructive_indefinite_description in H7. simpl in H7.\n    subst; auto. }  \n  pose proof family_card _ _ _ H0 H5 quotient_set_inter_empty.\n  rewrite family_quotient_set_eq_G in H6.\n  unfold order. unfold pick.\n  destruct constructive_indefinite_description; simpl.\n  pose proof cardinal_is_functional _ _ _ c _  _ H6.\n  apply H7; auto.\nQed.\n \n  \n  \n\n\n\n\n\n", "meta": {"author": "guodk", "repo": "Formalization-of-Lagrange-s-Theorem-in-Coq", "sha": "86f4d8474a1ffcd131ecabf56cd54364dd82f096", "save_path": "github-repos/coq/guodk-Formalization-of-Lagrange-s-Theorem-in-Coq", "path": "github-repos/coq/guodk-Formalization-of-Lagrange-s-Theorem-in-Coq/Formalization-of-Lagrange-s-Theorem-in-Coq-86f4d8474a1ffcd131ecabf56cd54364dd82f096/Langrange's_theorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7248179068890365}}
{"text": "Require Import Problem PeanoNat Omega.\n\nTheorem solution : task.\nProof.\n  unfold task.\n  intro.\n  remember n as m.\n  assert (m <= n) by omega; clear Heqm.\n  revert m H.\n\n  induction n; intros.\n  - apply Nat.le_0_r in H; subst m; auto.\n  - do 2 (destruct m; [auto|]).\n    simpl.\n    rewrite IHn; omega.\nQed.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/030/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686645, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.724795842986156}}
{"text": "(* Exercise 33 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_033 : ((A /\\ B) -> ~C) -> ((A /\\ C) -> ~B).\nProof.\nimp_i a1.\nimp_i a2.\nneg_i C a3.\nimp_e (A /\\ B).\nhyp a1.\ncon_i.\ncon_e1 C.\nhyp a2.\nhyp a3.\ncon_e2 A.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop033.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7247958275290478}}
{"text": "\nSection Minimal_propositional_logic.\n\nVariables P Q R T : Prop.\n\nTheorem imp_trans : (P->Q) -> (Q->R) -> P -> R.\nProof.\n  intros H H' p.\n  apply H'.\n  apply H.\n  assumption.\nQed.\n\nPrint imp_trans.", "meta": {"author": "baberrehman", "repo": "interactive-theorem-proving", "sha": "e8e9de4bc664f4dd1b0fd72d6edf84f736da8874", "save_path": "github-repos/coq/baberrehman-interactive-theorem-proving", "path": "github-repos/coq/baberrehman-interactive-theorem-proving/interactive-theorem-proving-e8e9de4bc664f4dd1b0fd72d6edf84f736da8874/ch3/ch3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7247801983247458}}
{"text": "\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\n\nImport ListNotations.\n\n(* pigeon hole principle *)\n\nLemma list_gen_ind_rec {X : Type} (P : list X -> Prop) \n(HP : forall l, (forall m, length m < length l -> P m)%nat -> P l)\nn : forall l, (length l < n)%nat -> P l.\nProof.\n  induction n as [ | n IHn ]; intros l Hl.\n  exfalso; revert Hl. intros; lia.\n  apply HP.\n  intros m Hm.\n  apply IHn.\n  lia.\nQed.\n\nTheorem list_gen_ind {X : Type}(P : list X -> Prop)\n(HP : forall l, (forall m, length m < length l -> P m)%nat -> P l): forall l, P l.\nProof.\n  intros l. \n  apply list_gen_ind_rec with (n := S (length l)).\n  intros. auto.\n  lia.\nQed.\n\nInductive perm {X:Type} : list X -> list X -> Prop :=\n| perm_nil   :                   perm nil nil\n| perm_cons  : forall x l1 l2,    perm l1 l2 \n                           ->   perm (x::l1) (x::l2)\n| perm_swap  : forall x y l,  perm (x::y::l) (y::x::l)\n| perm_trans : forall l1 l2 l3,    perm l1 l2 \n                           ->      perm l2 l3 \n                           ->      perm l1 l3.\nNotation \"x '~p' y \" := (perm x y) (at level 70, no associativity).\n\nFact perm_incl {X : Type} (l m: list X ): l ~p m -> incl l m.\nProof.\n  intros H.\n  induction H as [ \n                 | x l1 l2 H1 IH1 \n                 | x y l \n                 | l1 l2 l3 H1 IH1 H2 IH2 \n                 ]. \n  intros Hyp1 Hyp2 .\n  apply Hyp2.\n  intros Hyp1 Hyp2 .\n  destruct Hyp2.\n  left.\n  apply H.\n  right.\n  apply IH1.\n  apply H.\n  intros ? ?.\n  revert H.\n  simpl.\n  tauto.\n  revert IH2.\n  revert IH1.\n  apply incl_tran.\nQed.\n\nFact perm_refl {A:Type} (l:list A) : l ~p l.\nProof.\n induction l as [ |list head IH].\n apply perm_nil.\n apply perm_cons.\n apply IH.\nQed.\n\nFact perm_middle {A:Type}x (l r:list A) : x::l++r ~p l++x::r.\nProof.\n  induction l as [ | y list IHl ].\n  simpl. \n  apply perm_refl.\n  simpl. \n  apply perm_trans with (1 := perm_swap _ _ _).\n  apply perm_cons.\n  apply IHl.\nQed.\n\nFact incl_right_app {A:Type} (l m p:list A) : incl m (l++p) -> exists m1 m2, m ~p m1++m2 /\\ incl m1 l /\\ incl m2 p.\nProof.\n  induction m as [ | x m IHm ].\n  exists nil, nil; simpl; repeat split;intros;try easy.\n  apply perm_nil.\n  intros H.\n  apply incl_cons_inv in H. \n  destruct H as (H1 & H2).    \n  apply IHm in H2.\n  destruct H2 as (m1 & m2 & H3 & H4 & H5).\n  destruct IHm.\n  apply perm_incl in H3.\n  apply incl_appl with(m:=p) in H4.\n  apply incl_appr with(m:=l) in H5.\n  apply incl_app with(l:=m1) (m:=m2) (n:=l++p) in H4.\n  apply incl_tran with(l:=m) in H4.\n  apply H4.\n  apply H3.\n  apply H5.\n  destruct H.\n  destruct H.\n  destruct H0.\n  apply in_app_or in H1.\n  destruct H1.\n  exists (x::x0).\n  exists (x1).\n  split.\n  apply perm_cons with(x:=x) in H.\n  apply H.\n  split.\n  apply incl_cons with(a:=x) in H0.\n  apply H0.\n  apply H1.\n  apply H2.\n  exists (x0).\n  exists (x::x1).\n  split.\n  apply perm_cons with(x:=x) in H.\n  apply perm_trans with(l2:=(x::x0++x1)) (l3:= (x0++x::x1)) in H.\n  apply H.\n  apply perm_middle.\n  split.\n  apply H0.\n  apply incl_cons with(a:=x) in H2.\n  apply H2.\n  apply H1.\nQed. \n\nFact incl_right_cons_split {X : Type}  x (l m:list X) : incl m (x::l) -> exists m1 m2, m ~p m1 ++ m2 /\\ (forall a, In a m1 -> a = x) /\\ incl m2 l.\nProof.\n  intros H.\n  apply (incl_right_app (x::nil) _ l) in H.\n  destruct H.\n  destruct H.\n  destruct H.\n  destruct H0.\n  exists x0.\n  exists x1.\n  split.\n  apply H.\n  split.\n  2: apply H1.\n  intros.\n  apply perm_incl in H.\n  apply incl_cons with(l:=nil) in H2.\n  apply incl_tran with(l:=a::nil) in H0.\n  2: apply H2.\n  2: intros;easy.\n  apply incl_cons_inv in H0.\n  destruct H0.\n  induction H0.\n  subst.\n  trivial.\n  exfalso.\n  apply H0.\nQed.\n\nFact perm_sym {A:Type} (l1 l2:list A) : l1 ~p l2 -> l2 ~p l1.\nProof.\n  intros H.\n  induction H.\n  apply perm_nil.\n  apply perm_cons.\n  assumption.\n  apply perm_swap.\n  apply perm_trans with l2.\n  apply IHperm2.\n  apply IHperm1.\nQed.\n\nFact incl_right_cons_choose {A:Type}x (l m:list A) : incl m (x::l) -> In x m \\/ incl m l.\nProof.\n  intros H.\n  apply incl_right_cons_split in H.\n  destruct H as ( m1 & m2 & H1 & H2 & H3 ); simpl in H1.\n  destruct m1 as [ | y m1 ].\n  right.\n  simpl in H1.\n  apply perm_incl in H1.    \n  revert H1 H3.\n  apply incl_tran.\n  apply Forall_forall in H2.\n  apply Forall_inv in H2.\n  subst.\n  apply perm_sym in H1.\n  apply perm_incl in H1.\n  apply incl_cons_inv in H1.\n  destruct H1.\n  left.\n  apply H.\nQed.\n\nFact repeat_choice_two {X:Type} (x : X) m : (forall a, In a m -> a = x) -> (exists m', m = x::x::m') \\/ m = nil \\/ m = x::nil.\nProof.\n  intros H.\n  destruct m as [ | a [ | b m ] ].\n  right; left; auto.\n  right; right; rewrite (H a); auto; left; auto.\n  left; rewrite (H a), (H b).\n  exists m; auto.\n  right; left; auto.\n  left; auto.\nQed.\n\nInductive list_has_dup {X:Type} : list X -> Prop :=\n| in_lhd_1 : forall x l, In x l -> list_has_dup (x::l)\n| in_lhd_2 : forall x l, list_has_dup l -> list_has_dup (x::l).\n\nNotation lhd := list_has_dup.\n\nFact lhd_cons_inv {A:Type}x (l:list A) : lhd (x::l) -> In x l \\/ lhd l.\nProof.\n  inversion_clear 1;auto.\nQed.\n\nFact perm_lhd {A:Type} (l m:list A) : l ~p m -> lhd l -> lhd m.\nProof.\n  intros H.\n  induction H as [ | x l m H1 IH1 | x y l | ]; auto.\n  intros H.\n  apply lhd_cons_inv in H; destruct H as [ H | H ].\n  left.\n  apply perm_incl in H1. \n  apply H1.\n  apply H.\n  right.\n  apply IH1.\n  apply H.\n  intros H.\n  apply lhd_cons_inv in H. simpl in *.\n  destruct H as [H | H];subst.\n  destruct H as [H | H];subst.\n  induction l.\n  left.\n  left.\n  reflexivity.\n  left.\n  left.\n  reflexivity.\n  right.\n  left.\n  apply H.\n  apply lhd_cons_inv in H.\n  destruct H as [ H | H ].\n  left.\n  right.\n  apply H.\n  right.\n  right.\n  apply H.\nQed.\n\nFact incl_right_cons_incl_or_lhd_or_perm {A:Type} x (m l:list A) : incl m (x::l) -> incl m l \\/ (lhd m) \\/ exists m', m ~p x::m' /\\ incl m' l.\nProof.\n  intros H.\n  apply incl_right_cons_split in H.\n  destruct H as (m1 & m2 & H1 & H2 & H3).\n  destruct (repeat_choice_two _ _ H2) as [ (m3 & H4) | [ H4 | H4 ] ]; \n    subst m1; simpl in H1; clear H2.\n  apply perm_sym in H1.\n  right; left.\n  apply perm_lhd with (1 := H1).\n  constructor 1; left; auto.\n  left.\n  intros u Hu.\n  apply H3.\n  apply perm_incl with (1 := H1); auto.\n  right; right.\n  exists m2; auto.\nQed.\n\nFact In_perm_head {X:Type}(x : X) l : In x l -> exists m, l ~p x::m.\nProof.\n  intros H.\n  apply in_split in H.\n  destruct H as (u & v & ?).\n  subst l.\n  exists (u++v).\n  apply perm_sym, perm_middle.\nQed.\n\nFact perm_length {A:Type} (l1 l2:list A) : l1 ~p l2 -> length l1 = length l2.\nProof.\n  intros H.\n  induction H as [ \n                  | x l1 l2 H1 IH1 \n                  | x y l \n                  | l1 l2 l3 H1 IH1 H2 IH2 \n                  ].\n  apply refl_equal. \n  simpl. \n  f_equal.\n  apply IH1.\n  simpl. \n  apply refl_equal.\n  transitivity (length l2).\n  apply IH1.\n  apply IH2.\nQed.\n\nFact length_le_and_incl_implies_dup_or_perm {A:Type} (l:list A)  :  \nforall m, (length l <= length m)%nat\n                      -> incl m l \n                      -> (lhd m) \\/ m ~p l.\nProof.\ninduction l as [ [ | x l ] IHl ] using list_gen_ind.\n\n(* case l -> nil *)\n- intros ? ? ?.\n  right. \n  apply incl_l_nil in H0.\n  subst.\n  apply perm_nil.\n\n- intros [ | y m ] H1 H2.\n  (* case l -> x::l and m -> nil *)\n  + simpl in H1. lia.\n  (* case l -> x::l and m -> y :: m *)\n  + simpl in H1; apply le_S_n in H1.\n    apply incl_cons_inv in H2.\n    destruct H2 as [ H3 H4 ].\n    simpl in H3.\n    destruct H3 as [ H3 | H3 ].\n    (* case x = y *)\n    ++ subst y.\n       apply incl_right_cons_choose in H4.\n       destruct H4 as [ H4 | H4 ].\n\n      (* case x = y & In x m *)\n      +++ left.\n          left.\n          apply H4.\n\n      (* case x = y & incl m l *)\n      +++ destruct IHl with (3 := H4).\n          simpl; lia.\n          assumption.\n          left. right;auto.\n          right. constructor;auto.\n      (* case In y l *)\n    ++ apply incl_right_cons_incl_or_lhd_or_perm in H4.\n       destruct H4 as [ H4 | [ H4 | (m' & H4 & H5) ] ].\n       (* case In y l and incl m l *)\n      +++ destruct IHl with (3 := H4) as [ H5 | H5 ]; auto.\n          left;right;apply H5.\n          left.\n          left.\n          apply perm_sym in H5.\n          apply perm_incl in H5.\n          apply H5.\n          apply H3.\n          (* case In y l and lhd m *)\n      +++ left.\n          right.\n          apply H4.\n      (* case In y l and m ~p x::m' and incl m' l *)\n      +++ apply perm_sym in H4.\n          apply In_perm_head in H3.\n          destruct H3 as (l' & Hl').\n          (* l ~p y::l' for some l' *)\n          assert (incl m' (y::l')) as H6.\n          {intros ? ?; apply perm_incl with (1 := Hl'), H5; auto. }\n          clear H5.\n          (* and incl m' (y::l') *)\n          apply incl_right_cons_choose in H6.\n          destruct H6 as [ H6 | H6 ].\n          (* subcase In y m' *)\n          ++++ left.\n               left.\n               apply perm_incl in H4. \n               apply H4.\n               right.\n               apply H6.\n          (* subcase incl m' l' *)\n          ++++ apply IHl in H6.\n              destruct H6 as [ H6 | H6 ].\n              left.\n              apply perm_lhd in H4. \n              right.\n              apply H4.\n              right.\n              apply H6.\n              right.\n              move Hl' after m'.\n              apply perm_sym in H4.\n              apply perm_cons with(x:=y) in H4.\n              apply perm_cons with(x:=x) in H6.\n              apply perm_cons with(x:=y) in H6.\n              apply perm_cons with(x:=x) in Hl'.\n              apply perm_sym in Hl'.\n              apply perm_trans with(l2:=x::y::l')(l1:=y::x::l') in Hl' . \n              apply perm_trans with(l1:=y::m) in H6.\n              apply perm_trans with(l1:=y::m) in Hl'.\n              apply Hl'.\n              apply H6.\n              apply H4.\n              apply perm_swap.\n              apply perm_length in Hl'.\n              simpl in Hl' |- *.\n              rewrite Hl'.\n              lia.\n              apply perm_length in Hl'.\n              apply perm_length in H4.\n              simpl in H4, Hl'.\n              apply le_S_n.\n              rewrite <- Hl', H4; auto.\nQed.\n\nLemma NoDup_lhd_ff {A:Type}: forall l:list A, NoDup l -> lhd l -> False.\nProof.\n  intros l H.\n  induction H;try easy;simpl;intros.\n  inversion H1;subst;auto.\nQed.\n\nLemma In_pigeon_hole: forall {A: Type} ( X' X: list A), (*11*)\n  NoDup X ->\n  (length X > length X')%nat ->\n  (forall x, In x X -> In x X') ->\n  False.\nProof.\n  intros.\n  eapply length_le_and_incl_implies_dup_or_perm in H1;try lia.\n  destruct H1. \n  - eapply NoDup_lhd_ff;eauto.\n  - apply perm_length in H1;lia.\nQed.", "meta": {"author": "Veridise", "repo": "Coda", "sha": "d22d56c09ac541f012adae34820850ce6cd10270", "save_path": "github-repos/coq/Veridise-Coda", "path": "github-repos/coq/Veridise-Coda/Coda-d22d56c09ac541f012adae34820850ce6cd10270/BigInt/src/PigeonHole.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.724728967830444}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(**** Tests of Field with real numbers ****)\n\nRequire Import Reals RealField.\nOpen Scope R_scope.\n\n(* Example 1 *)\nGoal\nforall eps : R,\neps * (1 / (2 + 2)) + eps * (1 / (2 + 2)) = eps * (1 / 2).\nProof.\n  intros.\n   field.\nQed.\n\n(* Example 2 *)\nGoal\nforall (f g : R -> R) (x0 x1 : R),\n(f x1 - f x0) * (1 / (x1 - x0)) + (g x1 - g x0) * (1 / (x1 - x0)) =\n(f x1 + g x1 - (f x0 + g x0)) * (1 / (x1 - x0)).\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 3 *)\nGoal forall a b : R, 1 / (a * b) * (1 / (1 / b)) = 1 / a.\nProof.\n  intros.\n   field.\nAbort.\n\nGoal forall a b : R, 1 / (a * b) * (1 / 1 / b) = 1 / a.\nProof.\n  intros.\n   field_simplify_eq.\nAbort.\n\nGoal forall a b : R, 1 / (a * b) * (1 / 1 / b) = 1 / a.\nProof.\n  intros.\n   field_simplify (1 / (a * b) * (1 / 1 / b)).\nAbort.\n\n(* Example 4 *)\nGoal\nforall a b : R, a <> 0 -> b <> 0 -> 1 / (a * b) / (1 / b) = 1 / a.\nProof.\n  intros.\n   field; auto.\nQed.\n\n(* Example 5 *)\nGoal forall a : R, 1 = 1 * (1 / a) * a.\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 6 *)\nGoal forall a b : R, b = b * / a * a.\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 7 *)\nGoal forall a b : R, b = b * (1 / a) * a.\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 8 *)\nGoal forall x y : R,\n  x * (1 / x + x / (x + y)) =\n  - (1 / y) * y * (- (x * (x / (x + y))) - 1).\nProof.\n  intros.\n   field.\nAbort.\n\n(* Example 9 *)\nGoal forall a b : R, 1 / (a * b) * (1 / 1 / b) = 1 / a -> False.\nProof.\nintros.\nfield_simplify_eq in H.\nAbort.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/success/Field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7247289631658809}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, b_times2 *)\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\nTheorem b_times2: forall n, beautiful n -> beautiful (2 * n).\nProof.\n    intros. unfold \"*\". rewrite <- plus_n_O. apply b_sum with (n:=n)(m:=n).\n    apply H.\n    apply H.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter9_Library_Prop/b_times2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7246422896710817}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (lf1 : natural) : natural :=\n  plus y (plus lf2 lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj201_coqofml_b3N8w5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7246422896710817}}
{"text": "From GRP Require Export group.\nFrom GRP Require Export groupop.\n\nTheorem homo_preserves_id :\n  forall (G1 G2 : group) (f : grp_homo G1 G2),\n    f (gr_id G1) = gr_id G2.\nProof.\n  intros.\n  replace (gr_id G1) with (gr_op G1 (gr_id G1) (gr_inv G1 (gr_id G1))).\n  rewrite preserves_op. rewrite preserves_inv.\n  rewrite gr_inv_r. reflexivity.\n  rewrite gr_inv_r. reflexivity.\n  Qed.\n\nDefinition kernel (G1 G2 : group) (f : grp_homo G1 G2) : subgroup_prop G1.\nProof.\n  exists (fun g1 => f g1 = gr_id G2).\n  - apply homo_preserves_id.\n  - intros. rewrite preserves_op.\n    rewrite H. rewrite H0. rewrite gr_id_l. reflexivity.\n  - intros. rewrite preserves_inv. rewrite H.\n    apply grp_id_inv_id.\n  Defined.\n\nDefinition image (G1 G2 : group) (f : grp_homo G1 G2) : subgroup_prop G2.\nProof.\n  exists (fun g2 => exists g1, f g1 = g2).\n  - exists (gr_id G1). apply homo_preserves_id.\n  - intros. destruct H; destruct H0.\n    exists (gr_op G1 x x0). subst. apply preserves_op.\n  - intros. destruct H. exists (gr_inv G1 x).\n    subst. apply preserves_inv.\n  Defined.", "meta": {"author": "mekty2012", "repo": "Coq-Study", "sha": "d8d4d746bb2bbec41e4befbf1aace5ddf14a5b2a", "save_path": "github-repos/coq/mekty2012-Coq-Study", "path": "github-repos/coq/mekty2012-Coq-Study/Coq-Study-d8d4d746bb2bbec41e4befbf1aace5ddf14a5b2a/grouphomo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7246150397094752}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  Fcomp                                                     \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  ******************************************************************************)\nRequire Export Float.\nSection comparisons.\nVariable radix : Z.\nHypothesis radixMoreThanOne : (1 < radix)%Z.\n \nLet radixMoreThanZERO := Zlt_1_O _ (Zlt_le_weak _ _ radixMoreThanOne).\nHint Resolve radixMoreThanZERO: zarith.\n \nDefinition Fdiff (x y : float) :=\n  (Fnum x * Zpower_nat radix (Zabs_nat (Fexp x - Zmin (Fexp x) (Fexp y))) -\n   Fnum y * Zpower_nat radix (Zabs_nat (Fexp y - Zmin (Fexp x) (Fexp y))))%Z.\n\nLet FtoRradix := FtoR radix.\nLocal Coercion FtoRradix : float >-> R.\n\nTheorem Fdiff_correct :\n forall x y : float,\n (Fdiff x y * powerRZ radix (Zmin (Fexp x) (Fexp y)))%R = (x - y)%R.\nintros x y; unfold Fdiff in |- *.\nrewrite <- Z_R_minus.\nrewrite Rmult_comm; rewrite Rmult_minus_distr_l.\nrepeat rewrite Rmult_IZR.\nrepeat rewrite Zpower_nat_Z_powerRZ; auto.\nrewrite (Rmult_comm (Fnum x)); rewrite (Rmult_comm (Fnum y)).\nrepeat rewrite <- Rmult_assoc.\nrepeat rewrite <- powerRZ_add; auto with real zarith.\nrepeat rewrite inj_abs; auto with arith.\nrepeat rewrite Zplus_minus; auto.\nrewrite (fun t : R => Rmult_comm t (Fnum x));\n rewrite (fun t : R => Rmult_comm t (Fnum y)); auto.\napply Zplus_le_reg_l with (p := Zmin (Fexp x) (Fexp y)); auto with arith.\nrewrite Zplus_minus; rewrite Zplus_0_r; apply Zle_min_r; auto.\napply Zplus_le_reg_l with (p := Zmin (Fexp x) (Fexp y)); auto with arith.\nrewrite Zplus_minus; rewrite Zplus_0_r; apply Zle_min_l; auto.\nQed.\n(* Definition of  comparison functions*)\n \nDefinition Feq (x y : float) := x = y :>R.\n \nDefinition Fle (x y : float) := (x <= y)%R.\n \nDefinition Flt (x y : float) := (x < y)%R.\n \nDefinition Fge (x y : float) := (x >= y)%R.\n \nDefinition Fgt (x y : float) := (x > y)%R.\n \nDefinition Fcompare (x y : float) := (Fdiff x y ?= 0)%Z.\n \nDefinition Feq_bool (x y : float) :=\n  match Fcompare x y with\n  | Eq => true\n  | _ => false\n  end.\n \nTheorem Feq_bool_correct_t :\n forall x y : float, Feq_bool x y = true -> Feq x y.\nintros x y H'; red in |- *.\napply Rplus_eq_reg_l with (r := (- y)%R).\nrepeat rewrite (Rplus_comm (- y)).\nrewrite Rplus_opp_r.\nchange ((x - y)%R = 0%R) in |- *.\nrewrite <- Fdiff_correct.\napply Rmult_eq_0_compat_r; auto.\ncut (Fdiff x y = 0%Z); [ intros H; rewrite H | idtac ]; auto with real.\napply Zcompare_EGAL.\ngeneralize H'; unfold Feq_bool, Fcompare in |- *.\ncase (Fdiff x y ?= 0)%Z;auto; intros; discriminate.\nQed.\n \nTheorem Feq_bool_correct_r :\n forall x y : float, Feq x y -> Feq_bool x y = true.\nintros x y H'; cut ((x - y)%R = 0%R).\nrewrite <- Fdiff_correct; intros H'1; case Rmult_integral with (1 := H'1).\nintros H'0; unfold Feq_bool, Fcompare in |- *.\nrewrite eq_IZR_R0 with (1 := H'0); auto.\nintros H'0; Contradict H'0.\ncase (Zmin (Fexp x) (Fexp y)); simpl in |- *; auto with real zarith.\napply Rplus_eq_reg_l with (r := FtoR radix y); auto with real.\nQed.\n \nTheorem Feq_bool_correct_f :\n forall x y : float, Feq_bool x y = false -> ~ Feq x y.\nintros x y H'; Contradict H'.\nrewrite Feq_bool_correct_r; auto with arith.\nred in |- *; intros H'0; discriminate.\nQed.\n \nDefinition Flt_bool (x y : float) :=\n  match Fcompare x y with\n  | Lt => true\n  | _ => false\n  end.\n \nTheorem Flt_bool_correct_t :\n forall x y : float, Flt_bool x y = true -> Flt x y.\nintros x y H'; red in |- *.\napply Rplus_lt_reg_r with (r := (- y)%R).\nrepeat rewrite (Rplus_comm (- y)).\nrewrite Rplus_opp_r.\nchange (x - y < 0)%R in |- *.\nrewrite <- Fdiff_correct.\nreplace 0%R with (powerRZ radix (Zmin (Fexp x) (Fexp y)) * 0)%R;\n auto with real arith.\nrewrite (Rmult_comm (Fdiff x y)).\napply Rmult_lt_compat_l; auto with real zarith.\nreplace 0%R with (IZR 0); auto with real arith.\napply Rlt_IZR; red in |- *.\ngeneralize H'; unfold Flt_bool, Fcompare in |- *.\ncase (Fdiff x y ?= 0)%Z; auto; intros; try discriminate.\nQed.\n \nTheorem Flt_bool_correct_r :\n forall x y : float, Flt x y -> Flt_bool x y = true.\nintros x y H'.\ncut (0 < y - x)%R; auto with arith.\n2: apply Rplus_lt_reg_l with (r := FtoRradix x); rewrite Rplus_0_r;\n    rewrite Rplus_minus; auto with real.\nintros H'0.\ncut (Fdiff x y < 0)%R; auto with arith.\nintros H'1.\ncut (Fdiff x y < 0)%Z; auto with zarith.\nintros H'2; generalize (Zlt_compare _ _ H'2);\n unfold Flt_bool, Fcompare, Zcompare in |- *; case (Fdiff x y);\n auto with arith; intros; contradiction.\napply lt_IZR; auto with arith.\napply (Rlt_monotony_contra_exp radix) with (z := Zmin (Fexp x) (Fexp y));\n auto with arith real; rewrite Rmult_0_l.\nrewrite Fdiff_correct; auto with real.\nQed.\n \nTheorem Flt_bool_correct_f :\n forall x y : float, Flt_bool x y = false -> Fle y x.\nintros x y H'.\ncase (Rtotal_order (FtoRradix y) (FtoRradix x)); auto with real.\nintros H'0; red in |- *; apply Rlt_le; auto with real.\nintros H'0; elim H'0; clear H'0; intros H'1.\nred in |- *; rewrite H'1; auto with real.\nContradict H'; rewrite Flt_bool_correct_r; auto with real.\nred in |- *; intros H'; discriminate.\nQed.\n \nDefinition Fle_bool (x y : float) :=\n  match Fcompare x y with\n  | Lt => true\n  | Eq => true\n  | _ => false\n  end.\n \nTheorem Fle_bool_correct_t :\n forall x y : float, Fle_bool x y = true -> Fle x y.\nintros x y H'.\ncut (Feq x y \\/ Flt x y).\nintros H; case H; intros H1; auto with real.\nred in |- *; apply Req_le; auto with real.\nred in |- *; apply Rlt_le; auto with real.\ngeneralize H' (Feq_bool_correct_t x y) (Flt_bool_correct_t x y).\nunfold Fle_bool, Feq_bool, Flt_bool in |- *; case (Fcompare x y); auto.\nQed.\n \nTheorem Fle_bool_correct_r :\n forall x y : float, Fle x y -> Fle_bool x y = true.\nintros x y H'.\ncut (Feq x y \\/ Flt x y).\nintros H; case H; intros H1; auto with real.\ngeneralize (Feq_bool_correct_r x y).\nunfold Fle_bool, Feq_bool, Flt_bool in |- *; case (Fcompare x y); auto.\ngeneralize (Flt_bool_correct_r x y);\n unfold Fle_bool, Feq_bool, Flt_bool in |- *; case (Fcompare x y);\n auto with arith.\ncase H'; auto with arith.\nQed.\n \nTheorem Fle_bool_correct_f :\n forall x y : float, Fle_bool x y = false -> Flt y x.\nintros x y H'.\ncase (Rtotal_order (FtoRradix y) (FtoRradix x)); auto with real.\nintros H'0; elim H'0; clear H'0; intros H'1.\nContradict H'.\nrewrite Fle_bool_correct_r; auto with real.\nred in |- *; intros H'; discriminate.\nred in |- *; rewrite H'1; auto with real.\nContradict H'.\nrewrite Fle_bool_correct_r; auto with real.\nred in |- *; intros H'; discriminate.\nred in |- *; auto with real.\nQed.\n \nLemma Fle_Zle :\n forall n1 n2 d : Z, (n1 <= n2)%Z -> Fle (Float n1 d) (Float n2 d).\nintros; unfold Fle, FtoRradix, FtoR in |- *; simpl in |- *; auto.\ncase Zle_lt_or_eq with (1 := H); intros H1.\napply Rlt_le; auto with real.\nrewrite <- H1; auto with real.\nQed.\n \nLemma Flt_Zlt :\n forall n1 n2 d : Z, (n1 < n2)%Z -> Flt (Float n1 d) (Float n2 d).\nintros; unfold Flt, FtoRradix, FtoR in |- *; simpl in |- *; auto with real.\nQed.\n \nLemma Fle_Fge : forall x y : float, Fle x y -> Fge y x.\nunfold Fle, Fge in |- *; intros x y H'; auto with real.\nQed.\n \nLemma Fge_Zge :\n forall n1 n2 d : Z, (n1 >= n2)%Z -> Fge (Float n1 d) (Float n2 d).\nintros n1 n2 d H'; apply Fle_Fge; auto.\napply Fle_Zle; auto.\napply Zge_le; auto.\nQed.\n \nLemma Flt_Fgt : forall x y : float, Flt x y -> Fgt y x.\nunfold Flt, Fgt in |- *; intros x y H'; auto.\nQed.\n \nLemma Fgt_Zgt :\n forall n1 n2 d : Z, (n1 > n2)%Z -> Fgt (Float n1 d) (Float n2 d).\nintros n1 n2 d H'; apply Flt_Fgt; auto.\napply Flt_Zlt; auto.\napply Zgt_lt; auto.\nQed.\n(* Arithmetic properties on F : Fle is reflexive, transitive, antisymmetric *)\n \nLemma Fle_refl : forall x y : float, Feq x y -> Fle x y.\nunfold Feq in |- *; unfold Fle in |- *; intros.\nrewrite H; auto with real.\nQed.\n \nLemma Fle_trans : forall x y z : float, Fle x y -> Fle y z -> Fle x z.\nunfold Fle in |- *; intros.\napply Rle_trans with (r2 := FtoR radix y); auto.\nQed.\n \nTheorem Rlt_Fexp_eq_Zlt :\n forall x y : float, (x < y)%R -> Fexp x = Fexp y -> (Fnum x < Fnum y)%Z.\nintros x y H' H'0.\napply lt_IZR.\napply (Rlt_monotony_contra_exp radix) with (z := Fexp x);\n auto with real arith.\npattern (Fexp x) at 2 in |- *; rewrite H'0; auto.\nQed.\n \nTheorem Rle_Fexp_eq_Zle :\n forall x y : float, (x <= y)%R -> Fexp x = Fexp y -> (Fnum x <= Fnum y)%Z.\nintros x y H' H'0.\napply le_IZR.\napply (Rle_monotony_contra_exp radix) with (z := Fexp x);\n auto with real arith.\npattern (Fexp x) at 2 in |- *; rewrite H'0; auto.\nQed.\n \nTheorem LtR0Fnum : forall p : float, (0 < p)%R -> (0 < Fnum p)%Z.\nintros p H'.\napply lt_IZR.\napply (Rlt_monotony_contra_exp radix) with (z := Fexp p);\n auto with real arith.\nsimpl in |- *; rewrite Rmult_0_l; auto.\nQed.\n \nTheorem LeR0Fnum : forall p : float, (0 <= p)%R -> (0 <= Fnum p)%Z.\nintros p H'.\napply le_IZR.\napply (Rle_monotony_contra_exp radix) with (z := Fexp p);\n auto with real arith.\nsimpl in |- *; rewrite Rmult_0_l; auto.\nQed.\n \nTheorem LeFnumZERO : forall x : float, (0 <= Fnum x)%Z -> (0 <= x)%R.\nintros x H'; unfold FtoRradix, FtoR in |- *.\nreplace 0%R with (0%Z * 0%Z)%R; auto 6 with real zarith.\nQed.\n \nTheorem R0LtFnum : forall p : float, (p < 0)%R -> (Fnum p < 0)%Z.\nintros p H'.\napply lt_IZR.\napply (Rlt_monotony_contra_exp radix) with (z := Fexp p);\n auto with real arith.\nsimpl in |- *; rewrite Rmult_0_l; auto.\nQed.\n \nTheorem R0LeFnum : forall p : float, (p <= 0)%R -> (Fnum p <= 0)%Z.\nintros p H'.\napply le_IZR.\napply (Rle_monotony_contra_exp radix) with (z := Fexp p);\n auto with real arith.\nsimpl in |- *; rewrite Rmult_0_l; auto.\nQed.\n \nTheorem LeZEROFnum : forall x : float, (Fnum x <= 0)%Z -> (x <= 0)%R.\nintros x H'; unfold FtoRradix, FtoR in |- *.\napply Ropp_le_cancel; rewrite Ropp_0; rewrite <- Ropp_mult_distr_l_reverse.\nreplace 0%R with (- 0%Z * 0)%R; auto 6 with real zarith.\nQed.\nEnd comparisons.\nHint Resolve LeFnumZERO LeZEROFnum: float.", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/Fcomp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7246150345753057}}
{"text": "(* Chap 11 Rel *)\n(* PROPERTIES OF RELATIONS *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\n(* Chap 11.1 Relations *)\nDefinition relation (X: Type) := X -> X -> Prop.\n\nPrint le.\nCheck le: nat -> nat -> Prop.\nCheck le: relation nat.\n\n(* Chap 11.2 Basic Properties *)\n(* Chap 11.2.1 Partial Functions *)\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2: X, R x y1 -> R x y2 -> y1 = y2.\n\nCheck next_nat : relation nat.\n\nTheorem next_nat_partial_function:\n  partial_function next_nat.\nProof.\n  unfold partial_function.\n  intros.\n  inversion H.\n  inversion H0.\n  reflexivity.\nQed.\n\nTheorem le_not_a_partial_function:\n  ~ (partial_function le).\nProof.\n  unfold not.\n  unfold partial_function.\n  intros.\n  assert (0 = 1) as Nonsense.\n  { apply H with (x := 0).\n    apply le_n.\n    apply le_S, le_n. }\n  discriminate Nonsense.\nQed.\n\n(* Exercise total_relation_not_partial *)\nPrint total_relation.\n\nTheorem total_relation_not_partial:\n  ~ (partial_function total_relation).\nProof.\n  unfold not. unfold partial_function.\n  intros.\n  assert (0 = 1) as Nonsense.\n  { apply H with (x := 1).\n    apply re_S_0, re_0_0.\n    apply re_n_S, re_S_0, re_0_0.\n  }\n  discriminate.\nQed.\n\n(* Exercise empty_relation_partial *)\nPrint empty_relation.\n\nTheorem empty_relation_partial:\n  partial_function empty_relation.\nProof.\n  unfold partial_function.\n  intros.\n  inversion H.\nQed.\n\n(* Chap 11.2.2 Reflexive Relations *)\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a: X, R a a.\n\nTheorem le_reflexive:\n  reflexive le.\nProof.\n  unfold reflexive.\n  intros.\n  apply le_n.\nQed.\n\n(* Chap 11.2.3 Transitive Relations *)\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c: X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans:\n  transitive le.\nProof.\n  unfold transitive.\n  intros.\n  induction H0.\n  - apply H.\n  - apply le_S, IHle.\nQed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\n  unfold transitive.\n  intros.\n  unfold lt in *.\n  apply le_S in H.\n  apply (le_trans (S a) (S b) c).\n  - apply H.\n  - apply H0.\nQed.\n\n(* Exercise le_trans_hard_way *)\nTheorem lt_trans':\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [| m' Hm'o].\n  - apply le_S, Hnm.\n  - apply le_S, IHHm'o.\nQed.\n\n(* Exercise lt_trans'' *)\nTheorem lt_trans'':\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  - inversion Hmo.\n  - apply le_S.\n    inversion Hmo.\n    + rewrite <- H0, Hnm. \n      apply le_n.\n    + apply IHo', H0.\nQed.\n\nTheorem le_Sn_le: forall n m, S n <= m -> n <= m.\nProof.\n  intros.\n  apply le_trans with (S n).\n  - apply le_S, le_n.\n  - apply H.\nQed.\n\n(* Exercise le_S_n *)\nTheorem le_S_n: forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros.\n  inversion H.\n  - apply le_n.\n  - apply le_Sn_le in H1. apply H1.\nQed.\n\n(* Exercise le_Sn_n *)\nTheorem le_Sn_n: forall n,\n  ~ (S n <= n).\nProof.\n  unfold not.\n  intros.\n  induction n.\n  - inversion H.\n  - apply IHn. apply le_S_n, H.\nQed.\n\n(* Chap 11.2.4 Symmetric and Antisymmetric Relations *)\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b: X, (R a b) -> (R b a).\n\n(* Exercise le_not_symmetric *)\nTheorem le_not_symmetric:\n  ~ (symmetric le).\nProof.\n  unfold symmetric.\n  unfold not. \n  intros.\n  assert (1 <= 0) as Nonsense.\n  { apply (H 0 1). apply le_S, le_n. }\n  inversion Nonsense.\nQed.\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b: X, (R a b) -> (R b a) -> a = b.\n\n(* Exercise le_antisymmetric *)\nTheorem le_antisymmetric:\n  antisymmetric le.\nProof.\n  unfold antisymmetric.\n  intros a.\n  induction a.\n  - intros. inversion H.\n    + reflexivity.\n    + inversion H0. rewrite H3 in H2. discriminate.\n  - intros. inversion H.\n    + reflexivity.\n    + rewrite <- H2 in H0. inversion H0.\n      * reflexivity.\n      * apply f_equal. apply IHa.\n        rewrite <- H2 in H.\n        apply le_S_n, H.\n        apply le_S_n, H0.\nQed.\n\n(* Exercise le_step *)\nTheorem le_step: forall n m p,\n  n < m -> m <= S p -> n <= p.\nProof.  \n  unfold lt.\n  intros.\n  apply le_S_n.\n  apply (le_trans (S n) m (S p)).\n  apply H.\n  apply H0.\nQed.\n\n(* Chap 11.2.5 Equivalence Relations *)\nDefinition equivalence {X: Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(* Chap 11.2.6 Partial Orders and Preorders *)\nDefinition order {X: Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\nDefinition preorder {X: Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order:\n  order le.\nProof.\n  unfold order.\n  split.\n  - apply le_reflexive.\n  - split.\n    + apply le_antisymmetric.\n    + apply le_trans.\nQed.\n\n(* Chap 11.3 Reflexive, Transitive Closure *)\nInductive clos_refl_trans {A: Type} (R: relation A) : relation A :=\n  | rt_step x y (H: R x y): clos_refl_trans R x y\n  | rt_refl x: clos_refl_trans R x x\n  | rt_trans x y z (Hxy: clos_refl_trans R x y) (Hyz: clos_refl_trans R y z):\n      clos_refl_trans R x z.\n\nTheorem next_nat_closure_is_le: forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros. split.\n  - intros.\n    induction H.\n    + apply rt_refl.\n    + apply rt_trans with m.\n      apply IHle.\n      apply rt_step.\n      apply nn.\n  - intros.\n    induction H.\n    + inversion H. apply le_S, le_n.\n    + apply le_n.\n    + apply (le_trans x y z).\n      apply IHclos_refl_trans1.\n      apply IHclos_refl_trans2.\nQed.\n\nInductive clos_refl_trans_1n {A: Type} (R: relation A) (x: A): A -> Prop :=\n  | rt1n_refl: clos_refl_trans_1n R x x\n  | rt1n_trans (y z: A) (Hxy: R x y) (Hrest: clos_refl_trans_1n R y z):\n      clos_refl_trans_1n R x z.\n\nLemma rsc_R: forall (X: Type) (R: relation X) (x y: X),\n  R x y -> clos_refl_trans_1n R x y.\nProof.\n  intros.\n  apply (rt1n_trans R x y y).\n  apply H.\n  apply rt1n_refl.\nQed.\n\n(* Exercise rsc_trans *)\nLemma rsc_trans:\n  forall (X: Type) (R: relation X) (x y z: X),\n    clos_refl_trans_1n R x y -> clos_refl_trans_1n R y z ->\n    clos_refl_trans_1n R x z.\nProof.\n  intros.\n  induction H.\n  - apply H0.\n  - apply (rt1n_trans R x y z).\n    apply Hxy.\n    apply IHclos_refl_trans_1n, H0.\nQed.\n\n(* Exercise rtc_rsc_coincide *)\nTheorem rtc_rsc_coincide:\n  forall (X: Type) (R: relation X) (x y: X),\n    clos_refl_trans R x y <-> clos_refl_trans_1n R x y.\nProof.\n  intros. split.\n  - intros.\n    induction H.\n    + apply rsc_R, H.\n    + apply rt1n_refl.\n    + apply (rsc_trans X R x y z).\n      apply IHclos_refl_trans1. apply IHclos_refl_trans2.\n  - intros.\n    induction H.\n    + apply rt_refl.\n    + apply (rt_trans R x y z).\n      apply rt_step.\n      apply Hxy.\n      apply IHclos_refl_trans_1n.\nQed.", "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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7245565316942133}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint drop (drop_arg0 : natural) (drop_arg1 : lst) : lst\n           := match drop_arg0, drop_arg1 with\n              | x, Nil => Nil\n              | Zero, x => x\n              | Succ x, Cons y z => drop x z\n              end.\n\nTheorem drop_Nil: forall (x: natural), drop x Nil = Nil.\nProof.\n  induction x ; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons: forall (x n: natural) (l: lst), drop (Succ x) (Cons n l) = drop x l.\nProof.  induction l; induction x; simpl; reflexivity.\nQed.\n\nTheorem drop_Cons_assoc: forall (x1 x2 x3: natural) (l: lst),\n    drop x1 (drop x2 (Cons x3 l)) = drop x2 (drop x1 (Cons x3 l)).\nProof.\n  induction x1; induction x2; try (simpl; reflexivity).\n  + induction l.\n    * \n      rewrite 2 drop_Cons. rewrite <- IHx1.\n      rewrite IHx2. rewrite 2 drop_Cons.\n      induction l.\n      - rewrite IHx1. reflexivity. \n      - \n        rewrite 3 drop_Nil. reflexivity. \n    * simpl. rewrite 2 drop_Nil. reflexivity. \n  + intros. simpl. destruct (drop x1 l); reflexivity. \n  + intros. simpl. destruct (drop x2 l); reflexivity. \nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural) (z : lst), eq (drop x (drop y z)) (drop y (drop x z)).\nProof.\n  induction z.\n  + \n    rewrite 2 drop_Cons_assoc. reflexivity. \n  + \n    rewrite 3 drop_Nil. reflexivity. \nQed.\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7245450568430333}}
{"text": "Require Import Arith.\nRequire Import List.\n\n\nFixpoint split A (l:list A) :list A*list A:=\n  match l with\n  |nil=>(nil,nil)\n  |a::nil=>(a::nil,nil)\n  |a::b::l'=>let (l1,l2):=split A l' in (a::l1,b::l2)\n  end.\n\nFixpoint partition A (less:A->A->bool) (mid:A) (l:list A):list A*list A:=\n  match l with\n  |nil=>(nil,nil)\n  |a::l'=>let (l1,l2):=partition A less mid l' in\n          if less a mid then (a::l1,l2)\n          else (l1,a::l2)\n  end.\n\nFixpoint pluslist A (l1:list A) (l2:list A):=\n  match l1 with\n  |nil=>l2\n  |a::l'=>a::(pluslist A l' l2)\n  end.\n\nDefinition quicksortloop A (less:A->A->bool):=\n  fix loop (l:list A) (n:nat):=\n    match n with\n    |O=>nil\n    |S n=>match l with\n          |nil=>l\n          |x::l'=>let (l1,l2):=partition A less x l' in\n                  pluslist A (loop l1 n) (x::(loop l2 n))\n          end\n    end.\n\n\nDefinition quicksort A less (l:list A):=\n  quicksortloop A less l (length l).\n\nEval vm_compute in quicksort nat leb (2::1::3::10::100::59::1::0::nil).", "meta": {"author": "wzwmxd", "repo": "coq", "sha": "9c14fac4b77ed2c48368d6135ab4b69a9457f9f9", "save_path": "github-repos/coq/wzwmxd-coq", "path": "github-repos/coq/wzwmxd-coq/coq-9c14fac4b77ed2c48368d6135ab4b69a9457f9f9/quick_sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.724545054440988}}
{"text": "Require Import Tree List Omega.\n\nInductive BaseTree := B: list BaseTree -> BaseTree.\n\nSection ListProp.\n  Context {A: Type}.\n  Context (def: A).\n  Theorem appLastNth: forall {l i} a, i = length l -> nth i (l ++ (a :: nil)) def = a.\n  Proof.\n    intros l.\n    induction l.\n    intros i a i_len.\n    simpl in *.\n    rewrite i_len.\n    auto.\n    intros i a0 i_len.\n    unfold length in i_len.\n    fold (length l) in i_len.\n    rewrite i_len.\n    unfold app.\n    fold (app l (a0 :: nil)).\n    simpl.\n    specialize (IHl (length l) a0).\n    assert (length l = length l) by auto.\n    specialize (IHl H).\n    assumption.\n  Qed.\n\n  Theorem appNotLastNth: forall {l i} a, i < length l -> nth i (l ++ (a :: nil)) def = nth i l def.\n  Proof.\n    intros l.\n    induction l.\n    intros i a i_len.\n    simpl in *.\n    omega.\n    intros i a0 i_len.\n    unfold app.\n    fold (app l (a0::nil)).\n    destruct i.\n    simpl.\n    auto.\n    simpl.\n    simpl in i_len.\n    assert (i < length l) by omega.\n    specialize (IHl i a0 H).\n    assumption.\n  Qed.\n\n  Theorem appLen: forall (l: list A) a, length (l ++ a :: nil) = S (length l).\n  Proof.\n    intros l a.\n    induction l.\n    simpl.\n    auto.\n    unfold app.\n    fold (app l (a :: nil)).\n    simpl.\n    omega.\n  Qed.\n\n  Theorem revLen: forall (l: list A), length l = length (rev l).\n  Proof.\n    intros l.\n    induction l.\n    simpl.\n    auto.\n    simpl.\n    pose proof (appLen (rev l) a).\n    rewrite H; clear H.\n    omega.\n  Qed.\n\n  Theorem revProp: forall {l i}, i < length l -> nth i l def = nth (length l - S i) (rev l) def.\n  Proof.\n    intros l.\n    induction l.\n    intros i i_lt_len.\n    simpl in *.\n    omega.\n    intros i i_lt_len.\n    unfold rev.\n    fold (rev l).\n    unfold length.\n    fold (length l).\n    assert (S (length l) - S i = (length l) - i) by omega.\n    rewrite H.\n    clear H.\n    destruct i.\n    simpl.\n    assert (length l - 0 = length l) by omega.\n    rewrite H; clear H.\n    pose proof (revLen l) as H.\n    rewrite H; clear H.\n    assert (length (rev l) = length (rev l)) by reflexivity.\n    pose proof (appLastNth a H).\n    rewrite H0.\n    auto.\n    simpl in i_lt_len.\n    pose proof (revLen l) as H.\n    assert (length l - S i < length (rev l)) by omega.\n    pose proof (appNotLastNth a H0).\n    rewrite H1.\n    simpl.\n    assert (i < length l) by omega.\n    specialize (IHl i H2).\n    assumption.\n  Qed.\n\n  Section EqLen.\n    Context (l: list A).\n    Context {B: Type}.\n    Context (f: A -> list A -> B).\n    Fixpoint trans ls :=\n      match ls with\n        | nil => nil\n        | x :: xs => f x xs :: trans xs\n      end.\n    Theorem eqLen: length (trans l) = length l.\n    Proof.\n      induction l.\n      simpl.\n      reflexivity.\n      simpl.\n      f_equal.\n      assumption.\n    Qed.\n  End EqLen.\nEnd ListProp.\n\nSection Strange.\n  Context (nm: list nat).\n\n  Fixpoint mkNameList ls :=\n    match ls with\n      | nil => nil\n      | x :: xs => (C (length xs :: nm) x) :: mkNameList xs\n    end.\n\n  Theorem mkNameListLength ls: length (mkNameList ls) = length ls.\n  Proof.\n    induction ls.\n    simpl.\n    auto.\n    simpl.\n    f_equal.\n    auto.\n  Qed.\n\n  Theorem posValue: forall {ls i}, i < length ls -> match nth i (mkNameList ls) (C nil nil) with\n                                                      | C x _ => x = (length ls - S i) :: nm\n                                                    end.\n  Proof.\n    intros ls.\n    induction ls.\n    intros i i_lt_l.\n    simpl in i_lt_l.\n    omega.\n    intros i i_lt_l.\n    simpl in i_lt_l.\n    unfold mkNameList.\n    fold mkNameList.\n    destruct i.\n    simpl.\n    assert (H: length ls - 0 = length ls) by omega.\n    rewrite H; clear H.\n    auto.\n    simpl.\n    assert (H: i < length ls) by omega.\n    apply (IHls i H).\n  Qed.\n\n  Theorem posValueRev': forall {ls i}, i < length ls ->\n                                       match nth (length ls - S i) (rev (mkNameList ls)) (C nil nil) with\n                                         | C x _ => x = (length ls - S i) :: nm\n                                       end.\n  Proof.\n    intros ls i i_lt_n.\n    pose proof (posValue i_lt_n) as gdOne.\n    pose proof (mkNameListLength ls) as t1.\n    rewrite <- t1 in i_lt_n.\n    pose proof (revProp (C nil nil) i_lt_n) as bdOne.\n    rewrite t1 in bdOne.\n    rewrite bdOne in gdOne.\n    auto.\n  Qed.\n\n  Theorem posValueRev: forall {ls i}, i < length ls ->\n                                      match nth i (rev (mkNameList ls)) (C nil nil) with\n                                        | C x _ => x = i :: nm\n                                      end.\n  Proof.\n    intros ls i i_lt_n.\n    assert (sth: length ls - S i < length ls) by omega.\n    pose proof (posValueRev' sth) as sth2.\n    assert (H: length ls - S (length ls - S i) = i) by omega.\n    rewrite H in sth2.\n    assumption.\n  Qed.\nEnd Strange.\n\nFixpoint getCs nm b :=\n  match b with\n    | B bs => rev (mkNameList nm\n                              ((fix addC bs :=\n                                  match bs with\n                                    | nil => nil\n                                    | b' :: bs' => getCs (length bs' :: nm) b' :: addC bs'\n                                  end) bs))\n  end.\n\nDefinition getC nm b := C nm (getCs nm b).\n\nTheorem parentTreeName {c p np bp}: parent c p ->\n                                    p = getC np bp ->\n                              exists nc bc, c = getC nc bc.\nProof.\n  intros c_p pEq.\n  unfold parent in *; unfold getC in *.\n  destruct p.\n  injection pEq as lEqNp l0Eq.\n  rewrite lEqNp in *; rewrite l0Eq in *; clear lEqNp l0Eq.\n  clear pEq.\n  destruct bp.\n  simpl in c_p.\n  pose proof @In_rev as sth.\n  assert (In_rev: forall A l (x: A), In x (rev l) -> In x l) by\n         (generalize sth; clear;\n          intros sth A l x inl; specialize (sth A l x);\n          destruct sth;\n          intuition); clear sth.\n  pose proof (In_rev _ _ _ c_p) as inp; clear In_rev c_p l0 l.\n  induction l1.\n  simpl in *.\n  intuition.\n  simpl in inp.\n  pose proof (eqLen l1 (fun x y => getCs (length y :: np) x)) as sth.\n  unfold trans in sth.\n  rewrite sth in inp.\n  destruct inp.\n  exists (length l1 :: np); exists a; auto.\n  specialize (IHl1 H).\n  assumption.\nQed.\n\nTheorem treeNameHelp nm b:\n  match getC nm b with\n    | C x ls => treeNthName x ls\n  end.\nProof.\n  unfold treeNthName.\n  unfold getC.\n  destruct b.\n  simpl.\n  intros n n_lt_len.\n  apply posValueRev.\n  remember  ((fix addC (bs : list BaseTree) : list (list Tree) :=\n         match bs with\n         | nil => nil\n         | b' :: bs' => getCs (length bs' :: nm) b' :: addC bs'\n         end) l) as sth.\n  clear Heqsth.\n  pose proof (mkNameListLength nm sth) as H.\n  pose proof (revLen (mkNameList nm sth)) as H0.\n  rewrite H in H0.\n  rewrite <- H0 in n_lt_len.\n  assumption.\nQed.\n\nTheorem descImpGetc {p c}: descendent c p ->\n                           (exists np bp, p = getC np bp) ->\n                           exists nc bc, c = getC nc bc.\nProof.\n  intros desc.\n  induction desc.\n  intros [np [bp pEq]].\n  apply (parentTreeName H pEq).\n  intros [np [bp pEq]].\n  exists np; exists bp; intuition.\n  intros use.\n  specialize (IHdesc2 use).\n  specialize (IHdesc1 IHdesc2).\n  assumption.\nQed.\n\nParameter bHier : BaseTree.\n\nTheorem treeName2: forall {p}, descendent p (getC nil bHier) ->\n                               match p with\n                                 | C x ls => treeNthName x ls\n                               end.\nProof.\n  intros p desc.\n  remember (getC nil bHier) as y.\n  assert (sth: exists np bp, y = getC np bp) by (exists nil; exists bHier; intuition).\n  pose proof (descImpGetc desc sth) as [nc [bc cEq]].\n  rewrite cEq.\n  apply (treeNameHelp nc bc).\nQed.\n\nTheorem treeName1: match getC nil bHier with\n                     | C x ls => x = nil\n                   end.\nProof.\n  reflexivity.\nQed.\n", "meta": {"author": "vmurali", "repo": "CacheProofBetter", "sha": "e00bb4a4f1677c69969797c25ab9ef4bb8a213a0", "save_path": "github-repos/coq/vmurali-CacheProofBetter", "path": "github-repos/coq/vmurali-CacheProofBetter/CacheProofBetter-e00bb4a4f1677c69969797c25ab9ef4bb8a213a0/BaseTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7245450420646731}}
{"text": "Print nat.\n\n\nLemma plus_O_right: forall (n:nat), plus 0 n = n.\nProof.\nintro.\nreflexivity.\nQed.\n\n\nLemma plus_O_left: forall (n:nat), plus n O = n.\nProof.\ninduction n.\n- reflexivity.\n- simpl. \n  rewrite IHn.\n  reflexivity.\nQed.\n\nPrint plus_O_left.\n(*\napply (nat_ind (fun n => plus n O = n));\n[reflexivity |\nintros n IHn; simpl; rewrite IHn; reflexivity].\nQed.\n*)\n\nCheck nat_rec.\n\n\nDefinition msucc := nat_rec (fun n:nat => nat) (S 0) (fun (n:nat)(x:nat) => S x).\n\nEval compute in msucc 0.\nEval compute in msucc (S(S 0)).\n\nDefinition mpred := nat_rec (fun n:nat => nat) 0 (fun (n:nat)(x:nat) => n).\n\nEval compute in mpred 0.\nEval compute in mpred (S(S 0)).\n\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/Slajdy19/PlikiCoqa/plus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7245450328636831}}
{"text": "Require Export TopologicalSpaces.\n\nDefinition clopen {X:TopologicalSpace} (S:Ensemble (point_set X))\n  : Prop :=\n  open S /\\ closed S.\n\nDefinition connected (X:TopologicalSpace) : Prop :=\n  forall S:Ensemble (point_set X), clopen S ->\n        S = Empty_set \\/ S = Full_set.\n\nRequire Export Continuity.\n\nLemma connected_img: forall {X Y:TopologicalSpace}\n  (f:point_set X -> point_set Y),\n  connected X -> continuous f -> surjective f -> connected Y.\nProof.\nintros.\nred; intros.\ndestruct (H (inverse_image f S)).\nsplit.\napply H0.\napply H2.\nred.\nrewrite <- inverse_image_complement.\napply H0.\napply H2.\n\nleft.\napply Extensionality_Ensembles; split; red; intros.\ndestruct (H1 x).\nassert (In Empty_set x0).\nrewrite <- H3.\nconstructor.\nrewrite H5.\ntrivial.\ndestruct H6.\ndestruct H4.\n\nright.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\ndestruct (H1 x).\nrewrite <- H5.\nassert (In (inverse_image f S) x0).\nrewrite H3; constructor.\ndestruct H6; trivial.\nQed.\n\nRequire Export SubspaceTopology.\n\nLemma connected_union: forall {X:TopologicalSpace}\n  {A:Type} (S:IndexedFamily A (point_set X)),\n  (forall a:A, connected (SubspaceTopology (S a))) ->\n  Inhabited (IndexedIntersection S) ->\n  IndexedUnion S = Full_set -> connected X.\nProof.\nintros.\npose (inc := fun (a:A) => subspace_inc (S a)).\ndestruct H0.\ndestruct H0.\nred; intros.\nassert (forall a:A, clopen (inverse_image (inc a) S0)).\nintro.\nsplit.\napply subspace_inc_continuous.\napply H2.\nred.\nrewrite <- inverse_image_complement.\napply subspace_inc_continuous.\napply H2.\ndestruct (classic (In S0 x)).\nright.\nassert (forall a:A, inverse_image (inc a) S0 = Full_set).\nintro.\ndestruct (H a _ (H3 a)).\nassert (In (@Empty_set (point_set (SubspaceTopology (S a))))\n  (exist _ x (H0 a))).\nrewrite <- H5.\nconstructor.\nsimpl.\ntrivial.\ndestruct H6.\ntrivial.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\nassert (In (IndexedUnion S) x0).\nrewrite H1; constructor.\ndestruct H7.\nassert (In (@Full_set (point_set (SubspaceTopology (S a))))\n  (exist _ x0 H7)).\nconstructor.\nrewrite <- H5 in H8.\ndestruct H8.\nsimpl in H8.\ntrivial.\n\nleft.\nassert (forall a:A, inverse_image (inc a) S0 = Empty_set).\nintros.\ndestruct (H a _ (H3 a)).\ntrivial.\nassert (In (@Full_set (point_set (SubspaceTopology (S a))))\n  (exist _ x (H0 a))).\nconstructor.\nrewrite <- H5 in H6.\ndestruct H6.\nsimpl in H6.\ncontradiction H4.\n\napply Extensionality_Ensembles; split; red; intros.\nassert (In (IndexedUnion S) x0).\nrewrite H1; constructor.\ndestruct H7.\nassert (In (@Empty_set (point_set (SubspaceTopology (S a))))\n  (exist _ x0 H7)).\nrewrite <- H5.\nconstructor.\nsimpl.\ntrivial.\ndestruct H8.\ndestruct H6.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/Connectedness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658466, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.724399055898428}}
{"text": "Goal forall P Q : nat -> Prop, P 0 -> (forall x, P x -> Q x) -> Q 0.\nProof.\nintros.\napply (H0 0).\napply H.\nQed.\n\nGoal forall P : nat -> Prop, P 2 -> (exists y, P (1 + y)).\nProof.\nintros.\nexists 1.\napply H.\nQed.\n\nGoal forall P : nat -> Prop, (forall n m, P n -> P m) -> (exists p, P p) -> forall q, P q.\nProof.\nintros.\ndestruct H0.\napply (H x q).\napply H0.\nQed.\n\n", "meta": {"author": "ashiato45", "repo": "CoqEx2014", "sha": "83750632bf6a78db93ed493a739b4aeae8505df1", "save_path": "github-repos/coq/ashiato45-CoqEx2014", "path": "github-repos/coq/ashiato45-CoqEx2014/CoqEx2014-83750632bf6a78db93ed493a739b4aeae8505df1/2/7_quantified.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.7243990474071608}}
{"text": "Require Export IndPrinciples.\n\n(* ================================================================ *)\n\n(** * Casamento de Padrão Dependente *)\n\n(** Nós estudaremos a partir de agora a versão estendida do casamento\n    de padrão (\"match\"), que às vezes é necessário usar para que o Coq\n    reconheça que certos termos estão bem-tipados.\n\n    A compreensão desse recurso nos permite terminar de entender como\n    a igualdade funciona no Coq, e com ela a tática [rewrite], etc. O\n    mesmo se aplica às táticas de prova por absurdo no Coq. *)\n\n(** Primeiramente, portanto, recapitule que, até agora, quando\n    escrevíamos um \"match\", o tipo dele não dependia do termo\n    específico que estivesse sendo analisado. No caso da função\n    [evenb], por exemplo, o tipo do valor retornado é sempre [bool],\n    independentemente do valor ao qual ela é aplicado: *)\n\nCompute\n  (\n  fix 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  8.\n\n\n(** Considere agora o caso deste teorema:\n\n      forall n : nat, n + 0 = n\n\n    Nós sabemos que podemos prová-lo por meio de uma função\n    recursiva: *)\n\nFixpoint plus_0_r_po (n : nat) : n + 0 = n\n  :=\n  match n with\n  | O => @eq_refl nat 0\n  | S n' => f_equal nat nat S (n' + 0) n' (plus_0_r_po n')\n  end.\n\n(** Qual é, porém, o tipo do termo \"match ... end\"?\n\n    É \"n + 0 = n\", onde \"n\" é o próprio termo sendo analisado no\n    [match]. *)\n\n\n(** Como um segundo exemplo, considere a seguinte prova para o\n    princípio de indução para [ev]: *)\n\nFixpoint ev_ind_po\n  (P : nat -> Prop)\n  (p0: P 0)\n  (ps: forall n, ev n -> P n -> P (S (S n)) )\n  (n : nat)\n  (pevn : ev n)\n  :\n  P n\n    :=\n    match pevn with\n    | ev_0 => p0\n    | ev_SS n' evn' (* n = S (S n') /\\ ev n' *) =>\n        ps n' evn' (ev_ind_po P p0 ps n' evn')\n    end.\n\n(** Novamente: qual é o tipo do termo \"match ... end\"?\n\n    É \"P n\", onde \"n\", no que diz respeito ao \"match\", é o número \"x\"\n    tal que \"pevn\" tem tipo \"ev x\". Nesse caso, portanto, o tipo do\n    \"match\" depende do _tipo_ do termo sendo analisado. *)\n\n\n(** Para casos como esses 2 acima, em que o tipo do \"match\" depende do\n    valor e/ou tipo do termo sendo analisado, o Coq possui o\n    _casamento de padrão dependente_, cuja regra de funcionamento está\n    muito bem explicada no livro \"CPDT\", capítulo \"More Dependent\n    Types\" ( http://adam.chlipala.net/cpdt/html/Cpdt.MoreDep.html ):\n\n----------------------------------------------------------------------\nA dependent pattern match is a match expression where the type of the\noverall match is a function of the value and/or the type of the\ndiscriminee, the value being matched on. In other words, the match\ntype depends on the discriminee.\n\n[...]\n\nWe come now to the one rule of dependent pattern matching in Coq. A\ngeneral dependent pattern match assumes this form (with unnecessary\nparentheses included to make the syntax easier to parse):\n\n  match E as y in (T x1 ... xn) return U with\n    | C z1 ... zm => B\n    | ...\n  end\n\nThe discriminee is a term E, a value in some inductive type family T,\nwhich takes n arguments. An as clause binds the name y to refer to the\ndiscriminee E. An in clause binds an explicit name xi for the ith\nargument passed to T in the type of E.\n\nWe bind these new variables y and xi so that they may be referred to\nin U, a type given in the return clause. The overall type of the match\nwill be U, with E substituted for y, and with each xi substituted by\nthe actual argument appearing in that position within E's type.\n\n[...]\n\nThe last piece of the typing rule tells how to type-check a match\ncase. A generic constructor application C z1 ... zm has some type T\nx1' ... xn', an application of the type family used in E's type,\nprobably with occurrences of the zi variables. From here, a simple\nrecipe determines what type we will require for the case body B. The\ntype of B should be U with the following two substitutions applied: we\nreplace y (the as clause variable) with C z1 ... zm, and we replace\neach xi (the in clause variables) with xi'. In other words, we\nspecialize the result type based on what we learn based on which\npattern has matched the discriminee.\n----------------------------------------------------------------------\n\n*)\n\n(** Como exemplos concretos da explicação acima, aqui estão objetos de\n    prova que usam casamento de padrão dependente para os 2 teoremas\n    anteriores, mas ATENÇÃO:\n\n      Não apenas olhe para o que está escrito! Calcule por conta\n      própria, de acordo com a regra acima, o tipo esperado para o\n      termo retornado por cada caso de cada \"match\", e verifique se\n      o termo retornado realmente tem o tipo esperado. *)\n\nDefinition plus_0_r_dpm : forall n : nat, n + 0 = n\n  :=\n  fix f (n : nat) : n + 0 = n\n    :=\n    match n as v return v + 0 = v with\n    | O => @eq_refl nat 0\n    | S n' => f_equal nat nat S (n' + 0) n' (plus_0_r_po n')\n    end.\n\n(** Observação: em casos como o do termo acima, em que o objeto\n    analisado pelo match consiste apenas numa variável, a cláusula\n    \"as\" é pode ser omitida, e a variável em questão pode ser\n    diretamente mencionada na cláusula \"return\". Assim, o termo acima\n    poderia ter a seguinte linha, mais simples:\n\n      match n return n + 0 = n with\n*)\n\nDefinition ev_ind_dpm:\n  forall P : nat -> Prop,\n  P 0 ->\n  (forall n, ev n -> P n -> P (S (S n)) ) ->\n  forall n, ev n -> P n\n    :=\n    fun P p0 ps\n      =>\n      fix f n pevn : P n\n        :=\n        match pevn in ev a return P a with\n        | ev_0 => p0\n        | ev_SS n' evn' (* n = S (S n') *) =>\n            ps n' evn' (f n' evn')\n        end.\n\n(** Encaixando o \"match\" acima na forma geral da explicação anterior\n\n      match E as y in (T x1 ... xn) return U with\n      | C z1 ... zm  (* : T x1' ... xn' *)  => B\n      | ...\n      end\n\n    temos:\n\n      - E: pevn.\n      - T: ev, x1: a, n: 1.\n      - U: P a.\n      - (1º Caso) C: ev_0, m: 0, x1': 0.\n      - (2º Caso) C: ev_SS, z1: n', z2: evn', m: 2, x1': S (S n').\n\n    Observe que o termo retornado em cada caso tem tipo [P x1']\n\n      - p0 : P 0\n      - ps n' evn' (f n' evn') : P (S (S n'))\n\n    o que garante a boa-tipagem do \"match\". *)\n\n\n(** O trecho acima do CPDT tem a seguinte continuação, também\n    importante:\n\n----------------------------------------------------------------------\nA few details have been omitted above. In Chapter 3, we learned that\ninductive type families may have both _parameters_ and regular\narguments. Within an [in] clause, a parameter position must have the\nwildcard [_] written, instead of a variable. (In general, Coq uses\nwildcard [_]'s either to indicate pattern variables that will not be\nmentioned again or to indicate positions where we would like type\ninference to infer the appropriate terms.) Furthermore, recent Coq\nversions are adding more and more heuristics to infer dependent\n[match] annotations in certain conditions. The general annotation\ninference problem is undecidable, so there will always be serious\nlimitations on how much work these heuristics can do. When in doubt\nabout why a particular dependent [match] is failing to type-check, add\nan explicit [return] annotation! At that point, the mechanical rule\nsketched in this section will provide a complete account of \"what the\ntype checker is thinking.\" Be sure to avoid the common pitfall of\nwriting a [return] annotation that does not mention any variables\nbound by [in] or [as]; such a [match] will never refine typing\nrequirements based on which pattern has matched. (One simple exception\nto this rule is that, when the discriminee is a variable, that same\nvariable may be treated as if it were repeated as an [as] clause.)\n----------------------------------------------------------------------\n\n*)\n\n\n(** EXERCÍCIO: enuncie e prove um princípio de indução para [le'],\n               que é a relação <= como definida em IndProp: *)\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\nDefinition le'_ind_po : forall P : nat -> nat -> Prop,\n  (forall n : nat, P n n) -> \n  (forall n m : nat, le' n m -> P n m -> P n (S m)) ->\n  forall n m : nat, le' n m -> P n m :=\n  fun P pn ps =>\n    fix f n m ple' : P n m :=\n    match ple' in le' a b return P a b with\n    | le'_n n' => pn n'\n    | le'_S n' m' plenm => ps n' m' plenm (f n' m' plenm)\n    end. \n\n(** EXERCÍCIO: enuncie e prove o princípio de indução para [le],\n               cuja definição é:\n\n      Inductive le (n : nat) : nat -> Prop :=\n      | le_n : n <= n\n      | le_S : forall m : nat, n <= m -> n <= S m\n      end.\n*)\n\nDefinition le_ind_po : forall (n : nat) (P : nat -> Prop),\n  P n -> (forall m : nat, n <= m -> P m -> P (S m)) ->\n  forall m : nat, n <= m -> P m :=\n  fun n P pn ps =>\n    fix f m ple : P m :=\n    match ple in le _ b return P b with\n    | le_n => pn\n    | le_S m' plenm => ps m' plenm (f m' plenm)\n    end.\n\n(* ================================================================ *)\n\n(** * Objetos de Prova para Igualdade *)\n\n(** Recapitule a definição de igualdade no Coq: *)\n\nPrint eq.  (* Inductive eq (A : Type) (x : A) : A -> Prop :=\n              | eq_refl : x = x\n              end. *)\n\n(** Uma vez compreendido o casamento de padrão dependente, a definição\n    acima de igualdade se torna bastante simples: ela meramente diz\n    que nós podemos sempre substituir o termo à direita do '=' pelo\n    termo à esquerda!\n\n    De fato, suponha que nós queremos provar P(y), e que temos\n\n      hxy : x = y\n      px : P x\n\n    Nesse caso, basta fazer\n\n      match hxy in _ = a return P a with\n      | eq_refl => px\n      end\n\n    Usando esse conhecimento e a tática [refine], nós podemos\n    facilmente provar os teoremas que nós provávamos usando [rewrite]:\n*)\n\nDefinition eq_sym: forall (T : Type) (x y : T), x = y -> y = x\n  :=\n  fun T x y hxy\n    =>\n    match hxy in _ = y' return y' = x with\n    | eq_refl => @eq_refl T x\n    end.\n\n\n(** EXERCÍCIO: Prove usando um objeto de prova: *)\n\nDefinition eq_trans_po:\n  forall (T: Type) (x y z : T), x = y -> y = z -> x = z\n    :=\n    fun T x y z Hxy Hyz =>\n    match Hyz in _ = z' return x = z' with\n    | eq_refl => Hxy \n    end. \n\n\n(** EXERCÍCIO: Enuncie e prove o princípio de indução para [eq].\n\n    ATENÇÃO: Nós vimos no capítulo IndPrinciples como são obtidos os\n             enunciados dos princípios de indução para tipos\n    quaisquer. Assim sendo, é instrutivo tentar escrever a sua propria\n    versão do enunciado antes de executar [Check eq_ind]. *)\n\nCheck eq_ind.\n\nDefinition eq_ind_po : forall (A : Type) (x : A) (P : A -> Prop), P x -> forall y : A, x=y -> P y :=\n fun T x P Hx y Hxy => match Hxy in _ = y' return P y' with\n                       | eq_refl => Hx\n                       end.\n\n(** * Objetos de Prova para Contradição *)\n\n(** Uma vez compreendido o conteúdo acima, construir objetos de prova\n    para provas por contradição requer apenas mais uma observação: a\n    de que uma contradição como\n\n      eq10: 0 = 1\n\n    implica que nós podemos deduzir P(1) a partir de P(0), para\n    qualquer [P]! Além disso, já que nós podemos escolher [P] à\n    vontade, então P(1) pode ser [False] -- justamente o que\n    precisamos para obter qualquer conclusão a partir de [False_ind]\n    --, enquanto P(0) pode ser qualquer coisa trivial de demonstrar,\n    como [True]!\n\n    Essa estratégia é ilustrada a seguir. *)\n\nDefinition P_abs (n : nat) : Prop :=\n  match n with\n  | O => True\n  | _ => False\n  end.\n\nDefinition contradiction_explodes: 0 = 1 -> forall Q : Prop, Q\n  :=\n  fun eq01 Q\n    =>\n    False_ind Q\n      match eq01 in _ = a return P_abs a with\n      | eq_refl => I\n      end.\n\n\n(** Observe que o uso de False_ind não é obrigatório: *)\n\nDefinition abs_explodes: 0 = 1 -> forall Q : Prop, Q\n  :=\n  fun eq01 Q\n    =>\n    let P := fun n : nat => match n with\n                            | O => True\n                            | _ => Q\n                            end\n    in\n      match eq01 in _ = a return P a with\n      | eq_refl => I\n      end.\n\n(** E nós também podemos prová-lo: *)\n\nDefinition my_False_ind: forall P : Prop, False -> P\n  :=\n  fun P abs => match abs with\n               end.\n\n(* ================================================================ *)\n", "meta": {"author": "marcosfmmota", "repo": "software-foundations", "sha": "667f50300f3d2c117b3df2aa9175fdfb1f8c4be1", "save_path": "github-repos/coq/marcosfmmota-software-foundations", "path": "github-repos/coq/marcosfmmota-software-foundations/software-foundations-667f50300f3d2c117b3df2aa9175fdfb1f8c4be1/Objetos_de_Prova_para_Igualdade_e_Contradicao.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7243940969724836}}
{"text": "Require Import Arith.\nRequire Export List.\nImport ListNotations.\n\nInductive mark: Set:=\n  | B: mark\n  | X: mark\n  | O: mark.\n\nDefinition other_mark(mk: mark): mark:= \n  match mk with\n      | X => O\n      | O => X\n      | B => B\n  end.\n\nDefinition mark_eq(m1 m2: mark): bool:= \n  match m1, m2 with\n      | B, B => true\n      | X, X => true\n      | O, O => true\n      | _, _ => false\n  end.\n\n\n\nRecord board:= mk_board {\n                   m00: mark;  m01: mark; m02: mark;\n                   m10: mark; m11: mark; m12: mark;\n                   m20: mark; m21: mark; m22: mark\n}.\n\n\nRecord macro_board := mk_macro_board {\n                   b00: board;  b01: board; b02: board;\n                   b10: board; b11: board; b12: board;\n                   b20: board; b21: board; b22: board\n}.\n\nInductive cell: Set :=\n  | C00\n  | C01\n  | C02\n  | C10\n  | C11\n  | C12\n  | C20\n  | C21\n  | C22.\n  \n  \nDefinition cell_equal (c1 c2: cell) :=\n  match c1, c2 with\n    | C00, C00\n    | C01, C01\n    | C02, C02\n    | C10, C10\n    | C11, C11\n    | C12, C12\n    | C20, C20\n    | C21, C21\n    | C22, C22 => true\n    | _, _ => false\n  end.\n\nDefinition empty_board: board:= \n  (mk_board \n     B B B\n     B B B\n     B B B\n  ).\n  \nFixpoint lift_list_to_board (l : list mark) :=\n  match l with\n    | [x1; x2; x3; x4; x5; x6; x7; x8; x9] => mk_board x1 x2 x3 x4 x5 x6 x7 x8 x9 \n    | _ => empty_board\n  end.\n\nDefinition empty_macro_board: macro_board:= \n  (mk_macro_board \n     empty_board empty_board empty_board\n     empty_board empty_board empty_board\n     empty_board empty_board empty_board\n  ).\n\nInductive move: Set :=\n  | mk_move: cell -> cell -> mark -> move\n  | first_move.\n\nInductive outcome: Set :=\n  | Xwins\n  | Owins\n  | incomplete\n  | tie\n  | malformed.\n    \nInductive game: Set :=\n  | mk_game: list move -> nat -> macro_board -> outcome -> game.\n\nInductive polyboard: Set:=\n  | macro: macro_board -> polyboard\n  | micro: board -> polyboard.\n      ", "meta": {"author": "samchrisinger", "repo": "uttsolver", "sha": "225dcbe88bb3252d1fa78b95bbe203f18efea011", "save_path": "github-repos/coq/samchrisinger-uttsolver", "path": "github-repos/coq/samchrisinger-uttsolver/uttsolver-225dcbe88bb3252d1fa78b95bbe203f18efea011/src/coq/types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7243611297035004}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (z : natural) : natural :=\n  plus lf3 (plus Zero z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj146_coqofml_6pRUzz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.724361125188516}}
{"text": "(* I have not worked with any partners. *)\n(** * Induction: Proof by Induction *)\n\n(** Before getting started, we need to import all of our\n    definitions from the previous chapter: *)\n\nRequire Export LF.Basics.\n\n(** For the [Require Export] to work, you first need to use\n    [coqc] to compile [Basics.v] into [Basics.vo].  This is like\n    making a .class file from a .java file, or a .o file from a .c\n    file.  There are two ways to do it:\n\n     - In CoqIDE:\n\n         Open [Basics.v].  In the \"Compile\" menu, click on \"Compile\n         Buffer\".\n\n         (N.b.: These instructions need to be updated to take the \"-R\n         LF .\" into account.  Can a CoqIDE expert tell me how this is\n         done, please?)\n\n     - From the command line:\n\n         [make Basics.vo]\n\n   If you have trouble (e.g., if you get complaints about missing\n   identifiers later in the file), it may be because the \"load path\"\n   for Coq is not set up correctly.  The [Print LoadPath.] command may\n   be helpful in sorting out such issues. *)\n\n(* ################################################################# *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n    for [+] on the left, using an easy argument based on\n    simplification.  We also observed that proving the fact that it is\n    also a neutral element on the _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\n\n(** ... can't be done in the same simple way.  Just applying\n  [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n  unknown number, so the [match] in the definition of [+] can't be\n  simplified.  *)\n\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n    further: the branch of the case analysis where we assume [n = 0]\n    goes through fine, but in the branch where [n = S n'] for some [n'] we\n    get stuck in exactly the same way. *)\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(** We could use [destruct n'] to get one step further, but,\n    since [n] can be arbitrarily large, if we just go on like this\n    we'll never finish. *)\n\n(** To prove interesting facts about numbers, lists, and other\n    inductively defined sets, we usually need a more powerful\n    reasoning principle: _induction_.\n\n    Recall (from high school, a discrete math course, etc.) the\n    _principle of induction over natural numbers_: If [P(n)] is some\n    proposition involving a natural number [n] and we want to show\n    that [P] holds for all numbers [n], we can reason like this:\n         - show that [P(O)] holds;\n         - show that, for any [n'], if [P(n')] holds, then so does\n           [P(S n')];\n         - conclude that [P(n)] holds for all [n].\n\n    In Coq, the steps are the same: we begin with the goal of proving\n    [P(n)] for all [n] and break it down (by applying the [induction]\n    tactic) into two separate subgoals: one where we must show [P(O)]\n    and another where we must show [P(n') -> P(S n')].  Here's how\n    this works for the theorem at hand: *)\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\n(** Like [destruct], the [induction] tactic takes an [as...]\n    clause that specifies the names of the variables to be introduced\n    in the subgoals.  Since there are two subgoals, the [as...] clause\n    has two parts, separated by [|].  (Strictly speaking, we can omit\n    the [as...] clause and Coq will choose names for us.  In practice,\n    this is a bad idea, as Coq's automatic choices tend to be\n    confusing.)\n\n    In the first subgoal, [n] is replaced by [0].  No new variables\n    are introduced (so the first part of the [as...] is empty), and\n    the goal becomes [0 = 0 + 0], which follows by simplification.\n\n    In the second subgoal, [n] is replaced by [S n'], and the\n    assumption [n' + 0 = n'] is added to the context with the name\n    [IHn'] (i.e., the Induction Hypothesis for [n']).  These two names\n    are specified in the second part of the [as...] clause.  The goal\n    in this case becomes [S n' = (S n') + 0], which simplifies to\n    [S n' = S (n' + 0)], which in turn follows from [IHn']. *)\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(** (The use of the [intros] tactic in these proofs is actually\n    redundant.  When applied to a goal that contains quantified\n    variables, the [induction] tactic will automatically move them\n    into the context as needed.) *)\n\n(** **** Exercise: 2 stars, recommended (basic_induction)  *)\n(** Prove the following using induction. You might need previously\n    proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite -> IHn'. reflexivity. Qed.\n\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. intros [| m'].\n    + rewrite<-IHn'. reflexivity.\n    + rewrite->IHn'. reflexivity.\nQed.\n\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  - rewrite<-plus_n_O. reflexivity.\n  - simpl. rewrite->IHn'. rewrite->plus_n_Sm. reflexivity.\nQed. \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  - simpl. reflexivity.\n  - simpl. rewrite->IHn'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (double_plus)  *)\n(** Consider the following function, which doubles its argument: *)\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  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite->IHn'. rewrite->plus_n_Sm. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (evenb_S)  *)\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  induction n as [| n' IHn'].\n  - reflexivity.\n  - rewrite->IHn'. simpl. rewrite->negb_involutive. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (destruct_induction)  *)\n(** Briefly explain the difference between the tactics [destruct]\n    and [induction].\n\n- destruct and induction are both used to do case analysis in a proof.\nBesides, induction provides a inductive hypothesis. We prove that \nif a former hypothesis holds, the successor also holds. Since the basic\ncase holds, all these cases will hold, like a chain.\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\n(** In Coq, as in informal mathematics, large proofs are often\n    broken into a sequence of theorems, with later proofs referring to\n    earlier theorems.  But sometimes a proof will require some\n    miscellaneous fact that is too trivial and of too little general\n    interest to bother giving it its own top-level name.  In such\n    cases, it is convenient to be able to simply state and prove the\n    needed \"sub-theorem\" right at the point where it is used.  The\n    [assert] tactic allows us to do this.  For example, our earlier\n    proof of the [mult_0_plus] theorem referred to a previous theorem\n    named [plus_O_n].  We could instead use [assert] to state and\n    prove [plus_O_n] in-line: *)\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.  Qed.\n\n(** The [assert] tactic introduces two sub-goals.  The first is\n    the assertion itself; by prefixing it with [H:] we name the\n    assertion [H].  (We can also name the assertion with [as] just as\n    we did above with [destruct] and [induction], i.e., [assert (0 + n\n    = n) as H].)  Note that we surround the proof of this assertion\n    with curly braces [{ ... }], both for readability and so that,\n    when using Coq interactively, we can see more easily when we have\n    finished this sub-proof.  The second goal is the same as the one\n    at the point where we invoke [assert] except that, in the context,\n    we now have the assumption [H] that [0 + n = n].  That is,\n    [assert] generates one subgoal where we must prove the asserted\n    fact and a second subgoal where we can use the asserted fact to\n    make progress on whatever we were trying to prove in the first\n    place. *)\n\n(** Another example of [assert]... *)\n\n(** For example, suppose we want to prove that [(n + m) + (p + q)\n    = (m + n) + (p + q)]. The only difference between the two sides of\n    the [=] is that the arguments [m] and [n] to the first inner [+]\n    are swapped, so it seems we should be able to use the\n    commutativity of addition ([plus_comm]) to rewrite one into the\n    other.  However, the [rewrite] tactic is not very smart about\n    _where_ it applies the rewrite.  There are three uses of [+] here,\n    and it turns out that doing [rewrite -> plus_comm] will affect\n    only the _outer_ one... *)\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\n(** To use [plus_comm] at the point where we need it, we can introduce\n    a local lemma stating that [n + m = m + n] (for the particular [m]\n    and [n] that we are talking about here), prove this lemma using\n    [plus_comm], and then use it to do the desired rewrite. *)\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\n(* ################################################################# *)\n(** * Formal vs. Informal Proof *)\n\n(** \"_Informal proofs are algorithms; formal proofs are code_.\" *)\n\n(** What constitutes a successful proof of a mathematical claim?\n    The question has challenged philosophers for millennia, but a\n    rough and ready definition could be this: A proof of a\n    mathematical proposition [P] is a written (or spoken) text that\n    instills in the reader or hearer the certainty that [P] is true --\n    an unassailable argument for the truth of [P].  That is, a proof\n    is an act of communication.\n\n    Acts of communication may involve different sorts of readers.  On\n    one hand, the \"reader\" can be a program like Coq, in which case\n    the \"belief\" that is instilled is that [P] can be mechanically\n    derived from a certain set of formal logical rules, and the proof\n    is a recipe that guides the program in checking this fact.  Such\n    recipes are _formal_ proofs.\n\n    Alternatively, the reader can be a human being, in which case the\n    proof will be written in English or some other natural language,\n    and will thus necessarily be _informal_.  Here, the criteria for\n    success are less clearly specified.  A \"valid\" proof is one that\n    makes the reader believe [P].  But the same proof may be read by\n    many different readers, some of whom may be convinced by a\n    particular way of phrasing the argument, while others may not be.\n    Some readers may be particularly pedantic, inexperienced, or just\n    plain thick-headed; the only way to convince them will be to make\n    the argument in painstaking detail.  But other readers, more\n    familiar in the area, may find all this detail so overwhelming\n    that they lose the overall thread; all they want is to be told the\n    main ideas, since it is easier for them to fill in the details for\n    themselves than to wade through a written presentation of them.\n    Ultimately, there is no universal standard, because there is no\n    single way of writing an informal proof that is guaranteed to\n    convince every conceivable reader.\n\n    In practice, however, mathematicians have developed a rich set of\n    conventions and idioms for writing about complex mathematical\n    objects that -- at least within a certain community -- make\n    communication fairly reliable.  The conventions of this stylized\n    form of communication give a fairly clear standard for judging\n    proofs good or bad.\n\n    Because we are using Coq in this course, we will be working\n    heavily with formal proofs.  But this doesn't mean we can\n    completely forget about informal ones!  Formal proofs are useful\n    in many ways, but they are _not_ very efficient ways of\n    communicating ideas between human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\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\n(** Coq is perfectly happy with this.  For a human, however, it\n    is difficult to make much sense of it.  We can use comments and\n    bullets to show the structure a little more clearly... *)\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(** ... and if you're used to Coq you may be able to step\n    through the tactics one after the other in your mind and imagine\n    the state of the context and goal stack at each point, but if the\n    proof were even a little bit more complicated this would be next\n    to impossible.\n\n    A (pedantic) mathematician might write the proof something like\n    this: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n      n + (m + p) = (n + m) + p.\n\n    _Proof_: By induction on [n].\n\n    - First, suppose [n = 0].  We must show\n\n        0 + (m + p) = (0 + m) + p.\n\n      This follows directly from the definition of [+].\n\n    - Next, suppose [n = S n'], where\n\n        n' + (m + p) = (n' + m) + p.\n\n      We must show\n\n        (S n') + (m + p) = ((S n') + m) + p.\n\n      By the definition of [+], this follows from\n\n        S (n' + (m + p)) = S ((n' + m) + p),\n\n      which is immediate from the induction hypothesis.  _Qed_. *)\n\n(** The overall form of the proof is basically similar, and of\n    course this is no accident: Coq has been designed so that its\n    [induction] tactic generates the same sub-goals, in the same\n    order, as the bullet points that a mathematician would write.  But\n    there are significant differences of detail: the formal proof is\n    much more explicit in some ways (e.g., the use of [reflexivity])\n    but much less explicit in others (in particular, the \"proof state\"\n    at any given point in the Coq proof is completely implicit,\n    whereas the informal proof reminds the reader several times where\n    things stand). *)\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal)  *)\n(** Translate your solution for [plus_comm] into an informal proof:\n\n    Theorem: Addition is commutative.\n\n    Proof: By induction on [n].\n    - First, suppose [n = 0]. We must know \n        0 + m = m + 0.\n      The left side can be simplified to [m] by the definition of [+].\n      The right side can be simplified to [m] too by Theorem [plus_n_O].\n      Thus this holds.\n    - Next, suppose [n = S n'], where\n        n' + m = m + n'.\n      We must know\n        S n' + m = m + S n'.\n      By the definition of [+], this follows from\n        S (n' + m) = m + S n'.\n      By Theorem plus_n_Sm, this can be further simplified as\n        S (n' + m) = S (m + n').\n      which is immediate from the induction hypothesis.  \n    Qed.\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl_informal)  *)\n(** Write an informal proof of the following theorem, using the\n    informal proof of [plus_assoc] as a model.  Don't just\n    paraphrase the Coq tactics into English!\n\n    Theorem: [true = beq_nat n n] for any [n].\n\n    Proof: By induction on [n].\n    - First, suppose [n = 0]. We must know \n        true = beq_nat 0 0.\n      which is immediate from the definition of [beq_nat].\n    - Next, suppose [n = S n'], where\n        true = beq_nat n' n'.\n      We must know\n        true = beq_nat (S n') (S n').\n      By the definition of [beq_nat], this follows from\n        true = beq_nat n' n'.\n      which is immediate from the induction hypothesis.  \n    Qed.\n[] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, recommended (mult_comm)  *)\n(** Use [assert] to help prove this theorem.  You shouldn't need to\n    use induction on [plus_swap]. *)\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. rewrite->plus_assoc.\n  assert (H: n + m = m + n). { rewrite->plus_comm. reflexivity. }\n  rewrite->H. reflexivity.\nQed.\n\n(** Now 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\nLemma mult_n_O: forall n : nat, n * 0 = 0.\nProof.\n  induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite->IHn'. reflexivity.\nQed.\n\nLemma mult_plus_r: forall m n : nat, m * S n = m + m * n.\nProof.\n  intros m n. induction m as [|m' IHm'].\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 m n. induction m as [|m' IHm']. \n  - rewrite->mult_n_O. reflexivity.\n  - simpl. rewrite->mult_plus_r. rewrite->IHm'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (more_exercises)  *)\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 = leb n n.\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite<-IHn'. reflexivity.\nQed.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\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  leb n m = true -> leb (p + n) (p + m) = true.\nProof.\n  intros n m p H. induction p as [|p' IHp'].\n  - simpl. rewrite->H. reflexivity.\n  - simpl. rewrite->IHp'. reflexivity.\nQed.\n\nTheorem S_nbeq_0 : forall n:nat,\n  beq_nat (S n) 0 = false.\nProof.\n  reflexivity.\nQed.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  intros n. simpl. rewrite<-plus_n_O. 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. induction p as [|p' IHp'].\n  - rewrite mult_n_O. rewrite mult_n_O. rewrite mult_n_O. reflexivity.\n  - rewrite->mult_plus_r. rewrite->mult_plus_r. rewrite->mult_plus_r.\n    rewrite IHp'. rewrite->plus_assoc. rewrite->plus_assoc.\n    assert (H: n + m + n * p' = n + n * p' + m). {\n      rewrite<-plus_assoc. rewrite<-plus_assoc.\n      assert (H': m + n * p' =  n * p' + m). {\n        rewrite->plus_comm. reflexivity.\n      }\n      rewrite->H'. reflexivity.\n    }\n    rewrite->H. 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 m as [|m' IHm'].\n  - simpl. rewrite mult_n_O. reflexivity.\n  - simpl. assert (H: n * S m' = S m' * n). { rewrite->mult_comm. reflexivity. }\n    rewrite->H. simpl. rewrite->mult_comm. rewrite->mult_plus_distr_r. \n    rewrite->mult_plus_distr_r.\n    assert (H': m' * p * n = m' * n * p). {\n      rewrite->mult_comm. rewrite->IHm'.\n      assert (H0: n * m' = m' * n). { rewrite->mult_comm. reflexivity. }\n      rewrite->H0. reflexivity.\n    }\n    rewrite->H'.\n    assert (H1: p * n = n * p). { rewrite->mult_comm. reflexivity. }\n    rewrite->H1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_nat_refl)  *)\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.) *)\n\n\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite<-IHn'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap')  *)\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)]. *)\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. rewrite->plus_assoc.\n  replace (n + m) with (m + n). reflexivity.\n  rewrite->plus_comm. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (binary_commute)  *)\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! *)\n\nTheorem bin_to_nat_pres_incr: \n  forall b : bin, S (bin_to_nat b) = bin_to_nat (incr b).\nProof.\n  intros b. induction b as [|t' IHt'|p' IHp'].\n  - reflexivity.\n  - simpl. reflexivity.\n  - simpl. rewrite<-IHp'. simpl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse)  *)\n(** This exercise is a continuation of the previous exercise about\n    binary numbers.  You will need your definitions and theorems from\n    there to complete this one; please copy them to this file to make\n    it self contained for grading.\n\n    (a) First, write a function to convert natural numbers to binary\n        numbers.  Then prove that starting with any natural number,\n        converting to binary, then converting back yields the same\n        natural number you started with.\n\n    (b) You might naturally think 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 yields the\n        same number we started with.  However, this is not true!\n        Explain what the problem is.\n\n    (c) Define a \"direct\" normalization function -- i.e., a function\n        [normalize] from binary numbers to binary numbers such that,\n        for any binary number b, converting to a natural and then back\n        to binary yields [(normalize b)].  Prove it.  (Warning: This\n        part is tricky!)\n\n    Again, feel free to change your earlier definitions if this helps\n    here. *)\n\nFixpoint nat_to_bin (n : nat) : bin :=\n  match n with\n    | O => B\n    | S n' => incr (nat_to_bin n')\n  end.\n\nTheorem incr_bin_plus: \n  forall b : bin, bin_to_nat (incr b) = S (bin_to_nat b).\nProof.\n  intros b. induction b as [|t IHt|p IHp].\n  - reflexivity.\n  - simpl. reflexivity.\n  - simpl. rewrite IHp. simpl. reflexivity.\nQed.\n\nTheorem nat_to_bin_to_nat: \n  forall n : nat, bin_to_nat (nat_to_bin n) = n.\nProof.\n  intros n. induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite<-IHn'. rewrite<-incr_bin_plus. rewrite->IHn'. reflexivity.\nQed.\n\n\n(* b\nIf a binary is [T B], or [T (T B)] ... etc. Converting it to natural number \nwill give 0, and due to the definition of [nat_to_bin], 0 will give [B], with\nleading [T] removed. Also, any other binary number that contains this subsequence\nfaces the same problem like [P (T (T B))]. Shown as below:\n\n// THIS DO NOT HOLD!\nExample test_bin_nat_convert_twice:  nat_to_bin (bin_to_nat (P (T B))) = P (T B).\nProof. simpl. reflexivity.  Qed.\n*)\n\nFixpoint normalize (b : bin): bin :=\nmatch b with\n  | B => B\n  | T b' => match (normalize b') with\n    | B => B\n    | b' => T b'\n    end\n  | P b' => P (normalize b')\nend.\n\nExample test_bin_nat_convert_twice:  nat_to_bin (bin_to_nat (incr (P (incr (P B))))) = normalize (incr (P (incr (P B)))).\nProof. simpl. reflexivity.  Qed.\n\nExample test_bin_nat_convert_twice2:  nat_to_bin (bin_to_nat (T (T (T (T B))))) = normalize (T (T (T (T B)))).\nProof. simpl. reflexivity.  Qed.\n\nLemma norm_incr_comm : forall b : bin,\nnormalize (incr b) = incr (normalize b).\nProof.\n  induction b as [|b' IHb' |b' IHb'].\n  - reflexivity.\n  - simpl. destruct (normalize b').\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\n  - simpl. destruct (normalize b').\n    + rewrite->IHb'. simpl. reflexivity.\n    + rewrite->IHb'. simpl. reflexivity.\n    + rewrite->IHb'. simpl. reflexivity.\nQed.\n\nLemma doub_n_norm_T : forall n : nat,\n  nat_to_bin (mult n 2) = normalize(T (nat_to_bin n)).\nProof.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - simpl. rewrite->norm_incr_comm. rewrite->IHn'. simpl.\n    destruct (normalize (nat_to_bin n')).\n    + reflexivity.\n    + simpl. reflexivity.\n    + simpl. reflexivity.\nQed.\n\nLemma normalize_twice_eq : forall b : bin,\nnormalize (normalize b) = normalize b.\nProof. \n  induction b as [|b' IHb' |b' IHb'].\n  - simpl. reflexivity.\n  - simpl. destruct (normalize b').\n    + simpl. reflexivity.\n    + simpl. rewrite<-IHb'. simpl.\n      replace (match normalize b with\n        | B => B\n        | T b0 => T (T b0)\n        | P b0 => T (P b0)\n      end) with (T b). reflexivity.\n    + simpl. rewrite<-IHb'. simpl. reflexivity.\n  - simpl. rewrite->IHb'. reflexivity.\nQed.\n\n\nTheorem bin_to_nat_to_bin : forall b : bin,\n  nat_to_bin (bin_to_nat b) = normalize b.\nProof.\n  induction b as [|b' IHb'|b' IHb'].\n  - reflexivity.\n  - simpl. rewrite->doub_n_norm_T. simpl. rewrite->IHb'.\n    rewrite->normalize_twice_eq. reflexivity.\n  - simpl. rewrite->doub_n_norm_T. simpl. rewrite->IHb'.\n    rewrite->normalize_twice_eq. destruct (normalize b').\n    + reflexivity.\n    + reflexivity.\n    + reflexivity.\nQed.\n(** [] *)\n\n(** $Date: 2017-08-22 17:13:32 -0400 (Tue, 22 Aug 2017) $ *)\n", "meta": {"author": "qq456cvb", "repo": "lf", "sha": "1a0b565880df5f4d891aa88c9674afeff8991cc8", "save_path": "github-repos/coq/qq456cvb-lf", "path": "github-repos/coq/qq456cvb-lf/lf-1a0b565880df5f4d891aa88c9674afeff8991cc8/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.80563219364797, "lm_q2_score": 0.8991213711878918, "lm_q1q2_score": 0.7243611226258719}}
{"text": "From Coq Require Import Logic.FunctionalExtensionality.\nFrom CM Require Import Category.\n\nModule Inverse.\n  Definition inverse {A B: Object} (f: Morphism A B) (g: Morphism B A) :=\n    compose f g = identity A /\\ compose g f = identity B.\n\n  (** A morphism cannot have more than one inverse.\n    The Idea is to prove (g . f . k = g . f . g),\n    then use the associtivity law to prove ((g . f) . k = (g . f) . g),\n    finally use the identity law to prove (k = g).\n  *)\n  Theorem inverse_unique: forall (A B: Object) (f: Morphism A B) (g k: Morphism B A),\n    inverse f g ->\n    inverse f k ->\n    g = k.\n  Proof.\n    intros. unfold inverse in *. destruct H, H0.\n    assert (H3: compose g (compose f k) = compose g (compose f g)).\n    { rewrite H. rewrite H0. reflexivity. }\n    repeat rewrite <- composition_assoc in H3.\n    rewrite H1 in H3. repeat rewrite composition_id_left in H3.\n    symmetry. apply H3.\n  Qed.\nEnd Inverse.\n\nModule Isomorphism.\n  Import Inverse.\n  Definition isomorphism {A B: Object} (f: Morphism A B) :=\n    exists g: Morphism B A, inverse f g.\n\n  Theorem isomorphism_cancellation_left: \n    forall (A B C: Object) (f: Morphism A B) (h k: Morphism B C),\n      isomorphism f ->\n      compose f h = compose f k ->\n      h = k.\n  Proof.\n    intros. destruct H as [g H].\n    assert (compose (compose g f) h = compose (compose g f) k).\n    {\n      repeat rewrite composition_assoc. rewrite H0. reflexivity.\n    }\n    unfold inverse in H. destruct H. rewrite H2 in H1. \n    repeat rewrite composition_id_left in H1. apply H1.\n  Qed.\n\n  Theorem isomorphism_cancellation_right: \n    forall (A B C: Object) (f: Morphism A B) (h k: Morphism C A),\n      isomorphism f ->\n      compose h f = compose k f ->\n      h = k.\n  Proof.\n    intros. destruct H as [g H].\n    assert (compose h (compose f g) = compose k (compose f g)).\n    {\n      repeat rewrite <- composition_assoc. rewrite H0. reflexivity.\n    }\n    unfold inverse in H. destruct H. rewrite H in H1. \n    repeat rewrite composition_id_right in H1. apply H1.\n  Qed.\nEnd Isomorphism.\n\nModule Isomorphic.\n  Import Isomorphism.\n\n  Definition isomorphic (A B: Object) :=\n    exists f: Morphism A B, isomorphism f.\n\n  (* A is isomorphic to A. *)\n  Theorem isomorphic_refl: forall A: Object,\n    isomorphic A A.\n  Proof.\n    intros. unfold isomorphic. exists (identity A).\n    unfold isomorphism. exists (identity A). \n    split; apply composition_id.\n  Qed.\n\n  (* If A is isomorphic to B, then B is isomorphic to A. *)\n  Theorem isomorphic_symm: forall (A B: Object),\n    isomorphic A B -> isomorphic B A.\n  Proof.\n    intros. destruct H. destruct H. destruct H. \n    exists x0. exists x. split; assumption.\n  Qed.\n\n  (* If A is isomorphic to B, and B is isomorphic to C, then A is isomorphic to C. *)\n  Theorem isomorphic_tran: forall (A B C: Object),\n    isomorphic A B ->\n    isomorphic B C ->\n    isomorphic A C.\n  Proof.\n    intros. destruct H. destruct H0. exists (compose x x0).\n    destruct H. destruct H0. exists (compose x2 x1).\n    destruct H. destruct H0. split; rewrite composition_assoc.\n    - assert (compose x0 (compose x2 x1) = compose (compose x0 x2) x1).\n      { rewrite <- composition_assoc. reflexivity. }\n      rewrite H3. rewrite H0. destruct (composition_id B A x1). rewrite H4. assumption.\n    - assert (compose x1 (compose x x0) = compose (compose x1 x) x0).\n      { rewrite <- composition_assoc. reflexivity. }\n      rewrite H3. rewrite H1. destruct (composition_id B C x0). rewrite H4. assumption.\n  Qed.\nEnd Isomorphic.", "meta": {"author": "HaoYang670", "repo": "conceptual_mathematics", "sha": "465ee186e711076cf7d010c6325868944db927e6", "save_path": "github-repos/coq/HaoYang670-conceptual_mathematics", "path": "github-repos/coq/HaoYang670-conceptual_mathematics/conceptual_mathematics-465ee186e711076cf7d010c6325868944db927e6/Isomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7243611146188982}}
{"text": "Require Export Relation_Definitions.\nRequire Import Relation_Definitions_Implicit.\nRequire Import Classical_Wf.\nRequire Import Description.\nRequire Import FunctionalExtensionality.\nRequire Import Classical.\nRequire Import ZornsLemma.\nRequire Import ProofIrrelevance.\nRequire Import EnsemblesSpec.\n\nSection WellOrder.\n\n(* this definition is for the strict order, e.g. the\n   element relation for ordinals of ZFC *)\nVariable T:Type.\n\nDefinition total_strict_order (R:relation T) : Prop :=\n  forall x y:T, R x y \\/ x = y \\/ R y x.\n\nRecord well_order (R:relation T) : Prop := {\n  wo_well_founded: well_founded R;\n  wo_total_strict_order: total_strict_order R\n}.\n\nLemma wo_irrefl: forall R:relation T, well_order R ->\n  (forall x:T, ~ R x x).\nProof.\nintuition.\nassert (forall y:T, Acc R y -> y <> x).\nintros.\ninduction H1.\nintuition.\nrewrite H3 in H2.\napply H2 with x.\ntrivial.\ntrivial.\n\npose proof (wo_well_founded R H).\nunfold well_founded in H2.\npose proof (H1 x (H2 x)).\nauto.\nQed.\n\nLemma wo_antisym: forall R:relation T, well_order R ->\n  (forall x y:T, R x y -> ~ R y x).\nProof.\nintuition.\nassert (forall z:T, Acc R z -> z <> x /\\ z <> y).\nintros.\ninduction H2.\nintuition.\nrewrite H4 in H3.\npose proof (H3 y H1).\ntauto.\nrewrite H4 in H3.\npose proof (H3 x H0).\ntauto.\n\npose proof (wo_well_founded R H).\nunfold well_founded in H3.\npose proof (H2 x (H3 x)).\ntauto.\nQed.\n\nLemma wo_transitive: forall R:relation T, well_order R -> transitive R.\nProof.\nintros.\nunfold transitive.\nintros.\ncase (wo_total_strict_order R H x z).\ntrivial.\nintro.\ncase H2.\nintro.\nrewrite H3 in H0.\npose proof (wo_antisym R H y z).\ncontradict H0.\nauto.\n\nintro.\n\nassert (forall a:T, Acc R a -> a <> x /\\ a <> y /\\ a <> z).\nintros.\ninduction H4.\nintuition.\nrewrite H2 in H5.\npose proof (H5 z H3).\ntauto.\nrewrite H2 in H5.\npose proof (H5 x H0).\ntauto.\nrewrite H2 in H5.\npose proof (H5 y H1).\ntauto.\nrewrite H2 in H5.\npose proof (H5 z H3).\ntauto.\nrewrite H2 in H5.\npose proof (H5 x H0).\ntauto.\nrewrite H2 in H5.\npose proof (H5 y H1).\ntauto.\n\npose proof (wo_well_founded R H).\nunfold well_founded in H5.\npose proof (H4 x (H5 x)).\ntauto.\nQed.\n\nEnd WellOrder.\n\nArguments total_strict_order {T}.\nArguments well_order {T}.\nArguments wo_well_founded {T} {R}.\nArguments wo_transitive {T} {R}.\nArguments wo_total_strict_order {T} {R}.\nArguments wo_irrefl {T} {R}.\nArguments wo_antisym {T} {R}.\n\nSection WellOrderMinimum.\n\nVariable T:Type.\nVariable R:relation T.\nHypothesis well_ord: well_order R.\n\nDefinition WO_minimum:\n  forall S:Ensemble T, Inhabited S ->\n    { x:T | In S x /\\ forall y:T, In S y -> y = x \\/ R x y }.\nrefine (fun S H => constructive_definite_description _ _).\npose proof (WF_implies_MEP T R (wo_well_founded well_ord)).\nunfold minimal_element_property in H0.\npose proof (H0 S H).\n\ndestruct H1.\ndestruct H1.\nexists x.\nred.\nsplit.\nsplit.\nassumption.\nintros.\ncase (wo_total_strict_order well_ord x y).\ntauto.\nintro.\ncase H4.\nauto.\nintro.\ncontradict H5.\nauto.\n\nintros.\ndestruct H3.\ncase (wo_total_strict_order well_ord x x').\nintro.\npose proof (H4 x H1).\ncase H6.\ntrivial.\nintro.\ncontradict H7.\nauto.\n\nintro.\ncase H5.\ntrivial.\nintro.\ncontradict H6.\nauto.\nDefined.\n\nEnd WellOrderMinimum.\n\nArguments WO_minimum {T}.\n\nSection WellOrderConstruction.\n\nVariable T:Type.\n\nDefinition restriction_relation (R:relation T) (S:Ensemble T) :\n  relation ({z:T | In S z}) :=\n  fun (x y:{z:T | In S z}) => R (proj1_sig x) (proj1_sig y).\n\nRecord partial_WO : Type := {\n  pwo_S: Ensemble T;\n  pwo_R: relation T;\n  pwo_R_lives_on_S: forall (x y:T), pwo_R x y -> In pwo_S x /\\ In pwo_S y;\n  pwo_wo: well_order (restriction_relation pwo_R pwo_S)\n}.\n\n(* the last condition below says that S WO1 is a downward closed\n   subset of S WO2 *)\nRecord partial_WO_ord (WO1 WO2:partial_WO) : Prop := {\n  pwo_S_incl: Included (pwo_S WO1) (pwo_S WO2);\n  pwo_restriction: forall x y:T, In (pwo_S WO1) x -> In (pwo_S WO1) y ->\n    (pwo_R WO1 x y <-> pwo_R WO2 x y);\n  pwo_downward_closed: forall x y:T, In (pwo_S WO1) y -> In (pwo_S WO2) x ->\n    pwo_R WO2 x y -> In (pwo_S WO1) x\n}.\n\nLemma partial_WO_preord : preorder partial_WO_ord.\nProof.\nconstructor.\nunfold reflexive.\nintro.\ndestruct x.\nconstructor; simpl.\nauto with sets.\nsplit.\ntrivial.\ntrivial.\nauto.\n\nunfold transitive.\ndestruct x.\ndestruct y.\ndestruct z.\nintros.\ndestruct H.\ndestruct H0.\n\nsimpl in pwo_S_incl0; simpl in pwo_restriction0;\n  simpl in pwo_downward_closed0; simpl in pwo_S_incl1;\n  simpl in pwo_restriction1; simpl in pwo_downward_closed1.\nconstructor; simpl.\nauto with sets.\nintros.\napply iff_trans with (pwo_R1 x y).\napply pwo_restriction0; auto with sets.\napply pwo_restriction1; auto with sets.\n\nintros.\napply pwo_downward_closed0 with y; trivial.\napply pwo_downward_closed1 with y; trivial.\nauto with sets.\napply <- (pwo_restriction1 x y); trivial.\nauto with sets.\napply pwo_downward_closed1 with y; trivial.\nauto with sets.\nQed.\n\nDefinition partial_WO_chain_ub: forall C:Ensemble partial_WO,\n  chain partial_WO_ord C -> partial_WO.\nrefine (fun C H => let US := [ x:T | exists WO:partial_WO,\n                                     In C WO /\\ In (pwo_S WO) x ] in\n           let UR := fun x y:T => exists WO:partial_WO, In C WO /\\\n                                     pwo_R WO x y in\n        Build_partial_WO US UR _ _).\nintros.\nunfold UR in H0.\ndestruct H0.\ndestruct H0.\nsplit.\nconstructor.\nexists x0.\nsplit.\nassumption.\npose proof (pwo_R_lives_on_S x0 x y).\ntauto.\nconstructor.\nexists x0.\nsplit.\nassumption.\npose proof (pwo_R_lives_on_S x0 x y).\ntauto.\n\nconstructor.\nassert (forall (WO:partial_WO) (x:{z:T | In (pwo_S WO) z}),\n   In C WO -> In US (proj1_sig x)).\nintros.\nconstructor.\nexists WO.\nsplit.\nassumption.\nexact (proj2_sig x).\n\nassert (forall (WO:partial_WO) (iC:In C WO) (x:{z:T | In (pwo_S WO) z}),\n  Acc (restriction_relation (pwo_R WO) (pwo_S WO)) x ->\n  Acc (restriction_relation UR US)\n        (exist _ (proj1_sig x) (H0 WO x iC))).\nintros.\ninduction H1.\nconstructor.\nintros.\ndestruct x as [x ix].\ndestruct y as [y iy].\nunfold restriction_relation in H3.\nsimpl in H3.\nassert (In (pwo_S WO) y).\ndestruct H3.\ndestruct H3.\npose proof (H WO x0 iC H3).\ncase H5.\nintro.\ndestruct H6.\napply pwo_downward_closed0 with x.\nassumption.\npose proof (pwo_R_lives_on_S x0 y x).\ntauto.\nassumption.\nintro.\ndestruct H6.\napply pwo_S_incl0.\npose proof (pwo_R_lives_on_S x0 y x).\ntauto.\n\npose proof (H2 (exist (In (pwo_S WO)) y H4)).\nsimpl in H5.\nassert (iy = H0 WO (exist (In (pwo_S WO)) y H4) iC).\napply proof_irrelevance.\nrewrite <- H6 in H5.\napply H5.\nunfold restriction_relation.\nsimpl.\ndestruct H3.\ndestruct H3.\npose proof (H WO x0 iC H3).\ncase H8.\nintros.\ndestruct H9.\napply <- pwo_restriction0.\nassumption.\nassumption.\nassumption.\nintro.\ndestruct H9.\napply -> pwo_restriction0.\nassumption.\npose proof (pwo_R_lives_on_S x0 y x).\ntauto.\npose proof (pwo_R_lives_on_S x0 y x).\ntauto.\n\nred.\nintro.\ndestruct a.\ninversion i.\ndestruct H2.\ndestruct H2.\npose proof (H1 x0 H2 (exist _ x H3)).\nsimpl in H4.\nassert (i = H0 x0 (exist _ x H3) H2).\napply proof_irrelevance.\nrewrite <- H5 in H4.\napply H4.\napply (wo_well_founded (pwo_wo x0)).\n\nunfold total_strict_order.\nintros.\ndestruct x.\ndestruct y.\nunfold restriction_relation.\nsimpl.\ndestruct i.\ndestruct e.\ndestruct a.\ndestruct i0.\ndestruct e.\ndestruct a.\n\ncase (H x1 x2 i i0).\nintro.\nassert (In (pwo_S x2) x).\napply H0.\nassumption.\ncase (wo_total_strict_order (pwo_wo x2) (exist _ x H1) (exist _ x0 i2)).\nunfold restriction_relation.\nsimpl.\nleft.\nexists x2.\ntauto.\nintro.\ncase H2.\nright; left.\napply subset_eq_compat.\ninjection H3.\ntrivial.\nunfold restriction_relation.\nsimpl.\nright; right.\nexists x2.\ntauto.\n\nintro.\nassert (In (pwo_S x1) x0).\napply H0.\nassumption.\ncase (wo_total_strict_order (pwo_wo x1) (exist _ x i1) (exist _ x0 H1)).\nunfold restriction_relation.\nsimpl.\nleft.\nexists x1.\ntauto.\nintro.\ncase H2.\nright; left.\napply subset_eq_compat.\ninjection H3.\ntrivial.\nunfold restriction_relation; simpl.\nright; right.\nexists x1.\ntauto.\nDefined.\n\nLemma partial_WO_chain_ub_correct: forall (C:Ensemble partial_WO)\n  (c:chain partial_WO_ord C), forall WO:partial_WO, In C WO ->\n  partial_WO_ord WO (partial_WO_chain_ub C c).\nProof.\nintros.\nconstructor.\nunfold Included.\nintros.\nconstructor.\nexists WO.\ntauto.\n\nintros.\nsplit.\nintro.\nexists WO.\ntauto.\nintro.\ndestruct H2.\ndestruct H2.\ncase (c WO x0 H H2).\nintro.\ndestruct H4.\napply <- pwo_restriction0.\nassumption.\nassumption.\nassumption.\nintro.\ndestruct H4.\napply -> pwo_restriction0.\nassumption.\npose proof (pwo_R_lives_on_S x0 x y).\ntauto.\npose proof (pwo_R_lives_on_S x0 x y).\ntauto.\n\nintros.\ndestruct H2.\ndestruct H2.\ncase (c WO x0 H H2).\nintro.\ndestruct H4.\napply pwo_downward_closed0 with y.\nassumption.\npose proof (pwo_R_lives_on_S x0 x y).\ntauto.\nassumption.\nintro.\napply H4.\npose proof (pwo_R_lives_on_S x0 x y).\ntauto.\nQed.\n\nDefinition extend_strictly_partial_WO: forall (WO:partial_WO)\n  (a:T), ~ In (pwo_S WO) a -> partial_WO.\nrefine (fun WO a H => let S' := Add (pwo_S WO) a in\n  let R' := fun x y:T => pwo_R WO x y \\/ (In (pwo_S WO) x /\\ y = a) in\n  Build_partial_WO S' R' _ _).\nintros.\ncase H0.\nintros.\nsplit.\nleft.\npose proof (pwo_R_lives_on_S WO x y).\ntauto.\nleft.\npose proof (pwo_R_lives_on_S WO x y).\ntauto.\nintros.\ndestruct H1.\nsplit.\nleft.\nassumption.\nright.\nrewrite H2.\nauto with sets.\n\nconstructor.\nred.\nintros.\nassert (forall x:{y:T | In (pwo_S WO) y}, In S' (proj1_sig x)).\nintro.\ndestruct x.\nleft.\nsimpl.\nassumption.\n\nassert (forall x:{y:T | In (pwo_S WO) y},\n  Acc (restriction_relation R' S') (exist _ (proj1_sig x) (H0 x))).\nintro.\npose proof (wo_well_founded (pwo_wo WO) x).\ninduction H1.\nconstructor.\nintros.\ndestruct x.\ndestruct y.\nunfold restriction_relation in H3.\nsimpl in H3.\nassert (In (pwo_S WO) x0).\ncase H3.\nintro.\npose proof (pwo_R_lives_on_S WO x0 x).\ntauto.\ntauto.\nassert (pwo_R WO x0 x).\ncase H3.\ntrivial.\nintro.\ndestruct H5.\ncontradict H.\nrewrite <- H6.\nassumption.\n\npose proof (H2 (exist _ x0 H4)).\nsimpl in H6.\nassert (i0 = (H0 (exist (In (pwo_S WO)) x0 H4))).\napply proof_irrelevance.\nrewrite <- H7 in H6.\napply H6.\nred.\nsimpl.\nassumption.\n\ndestruct a0.\ncase i.\nintros.\npose proof (H1 (exist _ x0 i0)).\nsimpl in H2.\nassert (H0 (exist (In (pwo_S WO)) x0 i0) =\n  Union_introl T (pwo_S WO) (Singleton a) x0 i0).\napply proof_irrelevance.\nrewrite <- H3.\nassumption.\nintros.\ngeneralize i0.\ndestruct i0.\nintro.\nconstructor.\nintros.\nunfold restriction_relation in H2.\ndestruct y.\nsimpl in H2.\ncase H2.\nintro.\ncontradict H.\npose proof (pwo_R_lives_on_S WO x0 a).\ntauto.\nintros.\ndestruct H3.\npose proof (H1 (exist _ x0 H3)).\nsimpl in H5.\nassert (H0 (exist (In (pwo_S WO)) x0 H3) = i1).\napply proof_irrelevance.\nrewrite H6 in H5.\nassumption.\n\nred.\nintros.\ndestruct x.\ndestruct y.\nunfold restriction_relation.\nsimpl.\ncase i.\ncase i0.\nintros.\ncase (wo_total_strict_order (pwo_wo WO)\n  (exist _ x2 i2) (exist _ x1 i1)).\nintro.\nred in H0.\nsimpl in H0.\nleft.\nconstructor 1.\nassumption.\nintro.\ncase H0.\nright; left.\napply subset_eq_compat.\ninjection H1.\ntrivial.\n\nright; right.\nred in H1.\nsimpl in H1.\nconstructor 1.\nassumption.\n\nintros.\nleft.\ndestruct i1.\nconstructor 2.\ntauto.\n\ncase i0.\nintros.\nright; right.\ndestruct i2.\nconstructor 2.\ntauto.\n\nright; left.\napply subset_eq_compat.\ndestruct i1.\ndestruct i2.\ntrivial.\nDefined.\n\nLemma extend_strictly_partial_WO_correct: forall (WO:partial_WO)\n  (x:T) (ni:~ In (pwo_S WO) x),\n  partial_WO_ord WO (extend_strictly_partial_WO WO x ni).\nProof.\nintros.\nconstructor.\nunfold extend_strictly_partial_WO; simpl.\nconstructor 1.\nassumption.\nintros.\nunfold extend_strictly_partial_WO; simpl.\nsplit.\ntauto.\nintro.\ncase H1.\ntrivial.\nintro.\ndestruct H2.\ncontradict ni.\nrewrite <- H3.\nassumption.\n\nunfold extend_strictly_partial_WO; simpl.\nintros.\ncase H1.\nintro.\npose proof (pwo_R_lives_on_S WO x0 y).\ntauto.\nintro.\ntauto.\nQed.\n\nLemma premaximal_partial_WO_is_full: forall WO:partial_WO,\n  premaximal partial_WO_ord WO -> pwo_S WO = Full_set.\nProof.\nintros.\napply Extensionality_Ensembles.\nsplit.\nunfold Included.\nintros.\nconstructor.\nunfold Included.\nintros.\napply NNPP.\nunfold not; intro.\npose (WO' := extend_strictly_partial_WO WO x H1).\nassert (partial_WO_ord WO' WO).\napply H.\napply extend_strictly_partial_WO_correct.\nassert (In (pwo_S WO') x).\nsimpl.\nconstructor 2.\nauto with sets.\napply H1.\napply H2.\nassumption.\nQed.\n\nTheorem well_orderable: exists R:relation T, well_order R.\nProof.\nassert (exists WO:partial_WO, premaximal partial_WO_ord WO).\napply ZornsLemmaForPreorders.\nexact partial_WO_preord.\nintros.\nexists (partial_WO_chain_ub S H).\nexact (partial_WO_chain_ub_correct S H).\n\ndestruct H as [WO].\nexists (pwo_R WO).\nconstructor.\nassert (forall x:T, In (pwo_S WO) x).\nrewrite premaximal_partial_WO_is_full.\nintro.\nconstructor.\nassumption.\n\nassert (forall a:{x:T | In (pwo_S WO) x}, Acc (pwo_R WO) (proj1_sig a)).\nintro.\npose proof (wo_well_founded (pwo_wo WO)).\ninduction (H1 a).\ndestruct x.\nsimpl.\nunfold restriction_relation in H3; simpl in H3.\nconstructor.\nintros.\napply H3 with (y := exist _ y (H0 y)).\nassumption.\nred; intro.\napply H1 with (a := exist _ a (H0 a)).\n\nred; intros.\nassert (forall x:T, In (pwo_S WO) x).\nrewrite premaximal_partial_WO_is_full; intro.\nconstructor.\napply H.\ncase (wo_total_strict_order (pwo_wo WO)\n  (exist _ x (H0 x)) (exist _ y (H0 y))).\nunfold restriction_relation; tauto.\nintro.\ncase H1.\nintro.\nright; left.\ninjection H2.\ntrivial.\nunfold restriction_relation; tauto.\nQed.\n\nEnd WellOrderConstruction.\n\nSection WO_implies_AC.\n\nLemma WO_implies_AC: forall (A B:Type) (R: A -> B -> Prop)\n  (WO:relation B), well_order WO ->\n  (forall x:A, exists y:B, R x y) ->\n  exists f:A->B, forall x:A, R x (f x).\nProof.\nintros.\nassert (forall a:A, Inhabited [ b:B | R a b ]).\nintro.\npose proof (H0 a).\ndestruct H1.\nexists x.\nconstructor; assumption.\n\nexists (fun a:A => proj1_sig\n  (WO_minimum WO H [ b:B | R a b ] (H1 a))).\nintro.\ndestruct @WO_minimum.\nsimpl.\ndestruct a.\ndestruct H2.\nassumption.\nQed.\n\nEnd WO_implies_AC.\n", "meta": {"author": "coq-community", "repo": "zorns-lemma", "sha": "aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8", "save_path": "github-repos/coq/coq-community-zorns-lemma", "path": "github-repos/coq/coq-community-zorns-lemma/zorns-lemma-aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8/WellOrders.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7243611105824759}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) : natural := plus z (mult z y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj286_coqofml_768L8P.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7243464522637655}}
{"text": "Require Import Coq.Sets.Ensembles.\nRequire Import Coq.Sets.Powerset_facts.\n\nSection Lemma_1_18.\n\nVariable U : Type.\n\nVariable (A B C : Ensemble U).\n\nTheorem Union_increases_l: forall (U : Type) (a b : Ensemble U),\n  Included U a (Union U a b).\nProof.\n  unfold Included. intros. unfold In.\n  apply Union_introl. apply H.\nQed.\n\nTheorem Union_minimal: forall (U : Type) (a b X : Ensemble U),\n  Included U a X -> Included U b X -> Included U (Union U a b) X.\nProof.\n  unfold Included. intros. destruct H1.\n  - apply H. apply H1.\n  - apply H0. apply H1.\nQed.\n\n(* This is the same as Union_commutative *)\nLemma i_a: Union U A B = Union U B A.\nProof.\n  simple apply Extensionality_Ensembles.\n  unfold Same_set. split.\n  - simple apply Union_minimal.\n    + simple apply Union_increases_r.\n    + simple apply Union_increases_l.\n  - simple apply Union_minimal.\n    + simple apply Union_increases_r.\n    + simple apply Union_increases_l.\nQed.\n\n(* This is the same as Intersection_commutative *)\nLemma i_b : Intersection U A B = Intersection U B A.\nProof.\n  simple apply Extensionality_Ensembles.\n  unfold Same_set. split.\n  - unfold Included. intros. destruct H.\n    apply Intersection_intro. apply H0. apply H.\n  - unfold Included. intros. destruct H.\n    apply Intersection_intro. apply H0. apply H.\nQed.\n\n(* This is the same as Union_associative *)\nLemma ii_a: Union U A (Union U B C) = Union U (Union U A B) C.\nProof.\n  simple apply Extensionality_Ensembles.\n  unfold Same_set. split.\n  - unfold Included. intros.\n    destruct H.\n    + apply Union_introl. apply Union_introl. apply H.\n    + destruct H. \n      * apply Union_introl. apply Union_intror. apply H.\n      * apply Union_intror. apply H.\n  - unfold Included. intros. destruct H.\n    + destruct H.\n      * apply Union_introl. apply H.\n      * apply Union_intror. apply Union_introl. apply H.\n    + apply Union_intror. apply Union_intror. apply H.\nQed.\n \n(* This is the same as Intersection_associative *)\nLemma ii_b : Intersection U A (Intersection U B C) = Intersection U (Intersection U A B) C.\nProof.\n  simple apply Extensionality_Ensembles.\n  unfold Same_set.\n  split.\n  - unfold Included. intros.\n    unfold In. unfold In in H. destruct H.\n    * repeat apply Intersection_intro. destruct H0.\n      apply H. destruct H0. apply H0. \n      destruct H0. apply H1.\n  - unfold Included. intros.\n    repeat apply Intersection_intro. destruct H.\n    destruct H. apply H. destruct H. destruct H. apply H1.\n    destruct H. apply H0.\nQed.\n \n(* This is the same as Distributivity *)\nLemma iii_a :\n    Intersection U A (Union U B C) =\n    Union U (Intersection U A B) (Intersection U A C).\nProof.\n  admit.\nQed.\n \n(* This is the same as Distributivity' *)\nLemma iii_b :\n    Union U A (Intersection U B C) =\n    Intersection U (Union U A B) (Union U A C).\nProof.\n  admit.\nQed.\n \n(* Using intuitionistic logic, it is possible to prove that\n   (A intersection B) is a subset of (A \\ (A \\ B)), but proving the converse\n   requires classical logic. *)\nLemma iv_constructive :\n    Included U (Intersection U A B) (Setminus U A (Setminus U A B)).\nProof.\n  admit.\nQed.\n \n(* Either add this one classical axiom only to this section *)\nHypothesis NNPP : forall p:Prop, ~ ~ p -> p.\n(* or uncomment the following line to import all of Classical_Prop for this\n   whole module *)\n(* Require Import Coq.Logic.Classical_Prop. *)\nLemma iv : Setminus U A (Setminus U A B) = Intersection U A B.\nProof.\n  admit.\nQed.\n \nEnd Lemma_1_18.\n \nSection Lemma_1_19.\n \nVariable X : Type.\n \nVariable (A B : Ensemble X).\n \n(* This half is provable using intuitionistic logic *)\nLemma a_constructive :\n    Included X (Union X (Complement X A) (Complement X B))\n    (Complement X (Intersection X A B)).\nProof.\n  admit.\nQed.\n \nHypothesis NNPP : forall p:Prop, ~ ~ p -> p.\n \nLemma a :\n    Complement X (Intersection X A B) =\n    Union X (Complement X A) (Complement X B).\nProof.\n  admit.\nQed.\n \n(* This half is provable using intuitionistic logic *)\nLemma b_constructive :\n    Included X (Intersection X (Complement X A) (Complement X B))\n    (Complement X (Union X A B)).\nProof.\n  admit.\nQed. \n \nLemma b :\n    Complement X (Union X A B) = \n    Intersection X (Complement X A) (Complement X B).\nProof.\n  admit.\nQed.\n  \n", "meta": {"author": "d-krylov", "repo": "coq_set_theory", "sha": "8574f40b6898827bf48ae0fe782a3113ff8011a5", "save_path": "github-repos/coq/d-krylov-coq_set_theory", "path": "github-repos/coq/d-krylov-coq_set_theory/coq_set_theory-8574f40b6898827bf48ae0fe782a3113ff8011a5/set_part_one.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7243464521708425}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus (mult y x) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj196_coqofml_e7i2w9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129513, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7243464521708424}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) (y : natural) : natural :=\n  mult x y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj2411_coqofml_s0yWLT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.724346448332954}}
{"text": "(* The Cantor-Schröder-Bernstein theorem. *)\n\nFrom set_theory Require Import lib fn set.\n\n(* I use full types instead of Ensembles to make the proof more elegant. *)\nSection Aquivalenzsatz.\n\nVariable X : Type.\nVariable Y : Type.\nVariable f : X -> Y.\nVariable g : Y -> X.\nHypothesis f_inj : Injective f.\nHypothesis g_inj : Injective g.\n\n(* Infinite (ω) reflection of the set Y ⧵ Rng f. *)\nInductive CSB_Y : nat -> Y -> Prop :=\n  | CSB_Y_0 : ∀y, ¬Rng f y -> CSB_Y 0 y\n  | CSB_Y_S : ∀n x, CSB_X n x -> CSB_Y (S n) (f x)\nwith CSB_X : nat -> X -> Prop :=\n  | CSB_X_n : ∀n y, CSB_Y n y -> CSB_X n (g y).\n\n(* Bijective mapping as a functional relation. *)\nDefinition CSB_h x y : Prop :=\n  (g y = x /\\ ∃n, CSB_Y n y) \\/ (f x = y /\\ ¬∃n, CSB_X n x).\n\nLemma CSB_h_unique x :\n  ∃!y, CSB_h x y.\nProof.\ndestruct (classic (∃n, CSB_X n x)) as [[n Hn]|H].\n- inversion Hn; subst; exists y; split. left; split. easy. now exists n.\n  intros y' [[Hy' _]|[_ Hy']]. now apply g_inj.\n  exfalso; apply Hy'; now exists n.\n- exists (f x); split. now right. intros y' [[Hy' [n Hn]]|[Hy' _]].\n  exfalso; apply H; exists n. rewrite <-Hy'; now apply CSB_X_n. easy.\nQed.\n\nLemma CSB_h_inj x x' y :\n  CSB_h x y -> CSB_h x' y -> x = x'.\nProof.\nintros [[H1 [n Hn]]|[H1a H1b]] [[H2 [m Hm]]|[H2a H2b]].\n- now rewrite <-H1, <-H2.\n- exfalso; destruct n; inversion Hn; subst. apply H; now exists x'.\n  apply f_inj in H2; subst. apply H2b; now exists n.\n- exfalso; destruct m; inversion Hm; subst. apply H; now exists x.\n  apply f_inj in H1; subst. apply H1b; now exists m.\n- apply f_inj; now rewrite H1a, H2a.\nQed.\n\nLemma CSB_h_surj y :\n  ∃x, CSB_h x y.\nProof.\ndestruct (classic (∃n, CSB_Y n y)) as [[n Hn]|H].\n- exists (g y); left; split. easy. now exists n.\n- destruct (classic (Rng f y)) as [[x Hx]|Hy].\n  + exists x; right; split. easy. intros [n Hn].\n    apply H; exists (S n). rewrite <-Hx; now apply CSB_Y_S.\n  + exfalso; apply H; exists 0; now apply CSB_Y_0.\nQed.\n\nTheorem CSB :\n  ∃f : X -> Y, Bijective f.\nProof.\ndestruct (unique_choice _ _ _ CSB_h_unique) as [h Hh];\nexists h; apply fn_inj_surj_bi.\n- intros x x' H; apply CSB_h_inj with (y:=h x).\n  apply Hh. rewrite H; apply Hh.\n- intros y; destruct (CSB_h_surj y) as [x Hx]; exists x.\n  destruct (CSB_h_unique x) as [y' [_ Hy']].\n  now rewrite <-(Hy' y), <-(Hy' (h x)).\nQed.\n\nEnd Aquivalenzsatz.\n", "meta": {"author": "bergwerf", "repo": "settheory", "sha": "e3293df1f76ee7d7da46f2bf3993e8b4d9b3d1dd", "save_path": "github-repos/coq/bergwerf-settheory", "path": "github-repos/coq/bergwerf-settheory/settheory-e3293df1f76ee7d7da46f2bf3993e8b4d9b3d1dd/csb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7243464418791998}}
{"text": "Require Import Coq.NArith.NArith\n  Znumtheory Lia\n  Zdiv Zpow_facts.\n\nSection Fn.\n  \n\n\n  Fixpoint repeat_op_ntimes_rec (e : N) (n : positive) (w : N) : N :=\n    match n with\n    | xH => N.modulo e w\n    | xO p => let ret := repeat_op_ntimes_rec e p w in N.modulo (ret * ret) w\n    | xI p => let ret := repeat_op_ntimes_rec e p w in N.modulo (e * (ret * ret)) w \n    end.\n\n  Definition Npow_mod (e : N) (n w : N) :=\n    match n with\n    | N0 => Npos xH\n    | Npos p => repeat_op_ntimes_rec e p w \n    end.\n\n\n  (* slow function, will be used to prove that this slow function is \n    equivalent to Npow_mod, faster one. *)\n  Fixpoint Npow_mod_unary (e : N) (n : nat) (w : N) : N :=\n    match n with \n    | 0%nat => Npos xH\n    | S n' => N.modulo (e * Npow_mod_unary e n' w) w\n    end.\n\n\n  (* acc is accumulator, for efficient reduction of terms *)\n  Fixpoint repeat_op_ntimes_acc (e : N) (n : positive) (w acc : N) : N :=\n    match n with\n    | xH => N.modulo (e * acc) w\n    | xO p => let ee := (N.modulo (e * e) w) in repeat_op_ntimes_acc ee p w acc \n    | xI p => let ee := (N.modulo (e * e) w) in \n              let ea := (N.modulo (e * acc) w) in \n              repeat_op_ntimes_acc ee p w ea  \n    end.\n\n  Lemma op_pushes_out : forall n e w, prime (Z.of_N w) -> \n    repeat_op_ntimes_rec ((e * e) mod w) n w = \n    N.modulo ((repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)) w.\n  Proof.\n    induction n.\n    - simpl; intros ? ? Hw.\n      rewrite IHn.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      remember (repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)%N as enw.\n      rewrite <- N.mul_mod_idemp_r.\n      repeat rewrite N.mul_mod_idemp_l.\n      repeat rewrite N.mul_mod_idemp_r.\n      assert (Ht : (e * enw * (e * enw) = \n        e * e * (enw * enw))%N). lia.\n      rewrite Ht; clear Ht.\n      repeat rewrite N.mul_assoc.\n      rewrite N.mul_mod_idemp_r.\n      reflexivity.\n      all:(try lia; try assumption).\n    - simpl; intros ? ? Hw.\n      rewrite IHn.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      reflexivity. exact Hw.\n    - simpl; intros ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite N.mod_mod.\n      rewrite N.mul_mod_idemp_l.\n      rewrite N.mul_mod_idemp_r.\n      reflexivity.\n      all:lia.\n  Qed.\n\n\n  Lemma positive_mul_group_acc_rec_connection : forall n e w acc, prime (Z.of_N w) ->\n    repeat_op_ntimes_acc e n w acc = N.modulo (acc * repeat_op_ntimes_rec e n w) w.\n  Proof.\n    induction n.\n    - simpl; intros ? ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      specialize (IHn (N.modulo (e * e) w) w (N.modulo (e * acc) w)).\n      rewrite IHn.\n      rewrite op_pushes_out.\n      remember (repeat_op_ntimes_rec e n w * repeat_op_ntimes_rec e n w)%N as enw.\n      rewrite N.mul_mod_idemp_l.\n      repeat rewrite N.mul_mod_idemp_r.\n      assert (Ht : ((acc * (e * enw) = e * acc * enw)%N)).\n      lia.\n      rewrite Ht; clear Ht.\n      reflexivity.\n      all:(try lia; try assumption).\n    - simpl; intros ? ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite IHn. rewrite op_pushes_out.\n      reflexivity.\n      all:assumption.\n    - simpl; intros ? ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite N.mul_mod_idemp_r.\n      assert (Ht : (acc * e = e * acc)%N). lia.\n      rewrite Ht; clear Ht.\n      reflexivity.\n      lia.\n  Qed.\n\n      \n  Definition Npow_mod_constant_space (e : N) (n w : N) :=\n    match n with\n    | N0 => Npos xH\n    | Npos p => repeat_op_ntimes_acc e p w 1 \n    end.\n\n  \n  Lemma npow_mod_npow_constant_eqv : forall n e w, prime (Z.of_N w) ->\n    Npow_mod e n w = Npow_mod_constant_space e n w.\n  Proof.\n    destruct n; simpl; intros ? ? Hw.\n    - reflexivity.\n    - pose proof positive_mul_group_acc_rec_connection p e w 1 Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite H. rewrite N.mul_1_l.\n      destruct p.\n      all:simpl; rewrite N.mod_mod; lia.\n  Qed.\n\n\n  Lemma Npow_mod_unary_bound : forall (n : nat) (e w : N), prime (Z.of_N w) -> \n    (Npow_mod_unary e n w < w)%N.\n  Proof.\n    induction n.\n    - simpl; intros ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      lia.\n    - simpl; intros ? ? Hw.\n      apply N.mod_lt.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      lia.\n  Qed.\n\n  Lemma binnat_zero : forall (n : nat), 0%N = N.of_nat n -> n = 0%nat.\n  Proof.\n    induction n; try lia.\n  Qed.\n\n  Theorem Npow_mod_add_mul : forall n m e w, prime (Z.of_N w) ->\n    Npow_mod_unary e (n + m) w = N.modulo (Npow_mod_unary e n w * \n    Npow_mod_unary e m w) w.\n  Proof.\n    induction n.\n    - intros ? ? ? Hw.\n      rewrite Nat.add_0_l. \n      assert (Ht : Npow_mod_unary e 0 w = Npos xH).\n      simpl. reflexivity. \n      rewrite Ht.\n      rewrite N.mul_1_l.\n      induction m.\n      + simpl. rewrite N.mod_1_l.\n        reflexivity.\n        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n        lia.\n      + simpl. rewrite N.mod_mod.\n        reflexivity. \n        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n        lia.\n    - simpl; intros ? ? ? Hw.\n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n      rewrite IHn. \n      rewrite N.mul_mod_idemp_r.\n      rewrite N.mul_mod_idemp_l.\n      rewrite N.mul_assoc. reflexivity.\n      lia. lia. assumption.\n  Qed.\n\n\n\n  Lemma binnat_odd : forall (p : positive) (n : nat), \n    N.pos (xI p) = N.of_nat n -> \n    exists k,  n = (2 * k + 1)%nat /\\  (N.pos p) = (N.of_nat k).\n  Proof.\n    intros p n Hp.\n    destruct (Nat.Even_or_Odd n) as [H | H].\n    destruct H as [k Hk].\n    (* Even (impossible) Case *)\n    rewrite Hk in Hp; lia.\n    (* Odd (possible) case *)\n    destruct H as [k Hk].\n    rewrite Hk in Hp. \n    exists k.\n    split. exact Hk. lia.\n  Qed.\n\n\n  Lemma binnat_even : forall (p : positive) (n : nat), \n    N.pos (xO p) = N.of_nat n :> N -> \n    exists k, n = (Nat.mul 2 k) /\\  (N.pos p) = (N.of_nat k).\n  Proof.\n    intros p n Hp.\n    destruct (Nat.Even_or_Odd n) as [H | H].\n    destruct H as [k Hk].\n    (* Even (possible) case*)\n    rewrite Hk in Hp. exists k.\n    split. exact Hk. lia.\n    (* Odd (impossible) case *)\n    destruct H as [k Hk].\n    rewrite Hk in Hp. lia.\n  Qed.\n\n  (* slow is equivalent to fast *)\n  Lemma npow_mod_exp_unary_binary_eqv : forall (n : N) e w, prime (Z.of_N w) ->\n    Npow_mod_unary e (N.to_nat n) w = Npow_mod e n w.\n  Proof.\n    destruct n.\n    - simpl; intros ? ? Hw.\n      reflexivity.\n    - simpl; revert p.\n      induction p.\n      + simpl; intros ? ? Hw.\n        pose proof (prime_ge_2 (Z.of_N w) Hw) as Htt.\n        rewrite <-IHp.\n        rewrite ZL6.\n        rewrite Npow_mod_add_mul.\n        rewrite N.mul_mod_idemp_r.\n        reflexivity.\n        lia. exact Hw.\n        exact Hw.\n      + simpl; intros ? ? Hw.\n        rewrite <-IHp.\n        rewrite Pos2Nat.inj_xO.\n        assert (Ht : (2 * Pos.to_nat p = \n          Pos.to_nat p + Pos.to_nat p)%nat).\n        lia. rewrite Ht.\n        rewrite Npow_mod_add_mul.\n        reflexivity.\n        exact Hw.\n        exact Hw.\n      + simpl; intros ? ? Hw.\n        rewrite N.mul_1_r.\n        reflexivity.\n  Qed.\n        \n     \n\n  \n  Lemma mod_reduce_pow : forall n e w, prime (Z.of_N w) -> repeat_op_ntimes_rec e n w = \n    repeat_op_ntimes_rec (N.modulo e w) n w.\n  Proof.\n    induction n.\n    - simpl; intros ? ? Hp.\n      rewrite IHn.\n      remember (repeat_op_ntimes_rec (e mod w) n w *\n      repeat_op_ntimes_rec (e mod w) n w)%N as t.\n      rewrite N.mul_mod_idemp_l.\n      reflexivity.\n      pose proof (prime_ge_2 (Z.of_N w) Hp) as Ht.\n      lia. exact Hp.\n    - simpl; intros ? ? Hp.\n      rewrite IHn.\n      reflexivity.\n      exact Hp.\n    - simpl; intros ? ? Hp.\n      rewrite N.mod_mod.\n      reflexivity.\n      pose proof (prime_ge_2 (Z.of_N w) Hp) as Ht.\n      lia.\n  Qed.\n\n\n  Lemma Nmod_reduce_pow : forall n e w, prime (Z.of_N w) -> \n    Npow_mod e n w = Npow_mod (N.modulo e w) n w.\n  Proof.\n    destruct n.\n    - simpl; intros ? ? Hp.\n      reflexivity.\n    - simpl; intros ? ? Hp.\n      apply mod_reduce_pow.\n      exact Hp.\n  Qed.\n\n  Lemma wp_mod_zero : forall (w k p : N), prime (Z.of_N p) -> (2 <= k)%N -> (2 <= p)%N ->\n    (w mod p = 0)%N ->  (Npow_mod (w mod p) k p = 0)%N.\n  Proof.\n    intros ? ? ? Hp Hk Hpt Hwp.\n    rewrite Hwp.\n    unfold Npow_mod.\n    destruct k. lia.\n    clear Hk.\n    induction p0.\n    simpl. rewrite N.mod_0_l.\n    reflexivity. lia.\n    simpl. rewrite IHp0.\n    rewrite N.mod_0_l. \n    reflexivity. lia.\n    simpl. rewrite N.mod_0_l.\n    reflexivity. lia.\n  Qed.\n    \n  Lemma wp_mod_one : forall (w k p : N), prime (Z.of_N p) -> (2 <= k)%N -> (2 <= p)%N ->\n    (w mod p = 1)%N ->  (Npow_mod (w mod p) k p = 1)%N.\n  Proof.\n    intros ? ? ? Hp Hk Hpt Hwp.\n    rewrite Hwp.\n    unfold Npow_mod.\n    destruct k. lia.\n    clear Hk.\n    induction p0.\n    simpl. rewrite IHp0.\n    simpl. rewrite N.mod_1_l.\n    reflexivity. lia.\n    simpl. rewrite IHp0.\n    rewrite N.mod_1_l. \n    reflexivity. lia.\n    simpl. rewrite N.mod_1_l.\n    reflexivity. lia.\n  Qed.\n\n  \n    \n  Lemma zmod_nmod : forall (b a w : N), prime (Z.of_N w) ->\n    Z.of_N (Npow_mod a b w) = Zpow_mod (Z.of_N a) (Z.of_N b) (Z.of_N w).\n  Proof.\n    intros ? ? ? Hw.\n    rewrite Zpow_mod_correct.\n    destruct b; simpl.\n    - symmetry.\n      rewrite Z.mod_1_l.\n      reflexivity. \n      pose proof (prime_ge_2 (Z.of_N w) Hw) as Ht.\n      lia.\n    - revert p.\n      induction p.\n      + simpl. \n        assert (Ht : (p~1 = p + p + 1)%positive).\n        lia. rewrite Ht.\n        rewrite Zpower_pos_is_exp.\n        rewrite Zpower_pos_is_exp.\n        rewrite Zpower_pos_1_r.\n        rewrite N2Z.inj_mod.\n        rewrite N2Z.inj_mul.\n        rewrite N2Z.inj_mul.\n        rewrite IHp.\n        remember (Z.pow_pos (Z.of_N a) p) as zps.\n        remember (Z.of_N a) as za.\n        remember (Z.of_N w) as zw. \n        assert (Hzp: zps * zps * za = za * (zps * zps)).\n        lia. rewrite Hzp; clear Hzp; clear Ht.\n        rewrite <-Zmult_mod_idemp_l.\n        assert (Ht : (za * (zps * zps)) mod zw = (za mod zw * (zps * zps)) mod zw).\n        rewrite <-Zmult_mod_idemp_l.\n        reflexivity. rewrite Ht; clear Ht.\n        assert (Ht : (za mod zw * (zps * zps)) mod zw = \n        (za mod zw * ((zps * zps) mod zw)) mod zw).\n        rewrite <-Zmult_mod_idemp_r. reflexivity.\n        rewrite Ht; clear Ht.\n        assert (Ht : (zps * zps) mod zw = \n          (zps mod zw * (zps mod zw)) mod zw).\n        rewrite <-Zmult_mod_idemp_l.\n        rewrite <-Zmult_mod_idemp_r.\n        reflexivity.\n        rewrite Ht.\n        rewrite Zmult_mod_idemp_r.\n        reflexivity.\n      + simpl.\n        assert (Ht : (p~0 = p + p)%positive).\n        lia. rewrite Ht.\n        rewrite Zpower_pos_is_exp.\n        rewrite N2Z.inj_mod.\n        rewrite N2Z.inj_mul.\n        rewrite IHp.\n        remember (Z.pow_pos (Z.of_N a) p) as zps.\n        remember (Z.of_N a) as za.\n        remember (Z.of_N w) as zw.\n        rewrite Zmult_mod_idemp_l.\n        rewrite Zmult_mod_idemp_r.\n        reflexivity.\n      + simpl. rewrite Zpower_pos_1_r.\n        rewrite N2Z.inj_mod.\n        reflexivity.\n    - pose proof (prime_ge_2 (Z.of_N w) Hw) as Ht.\n      lia.\n  Qed.\n\n  Lemma npow_mod_nat : forall (n a p : nat), \n    prime (Z.of_nat p) ->\n    Npow_mod_unary (N.of_nat a) n (N.of_nat p) =\n    N.of_nat (Nat.modulo (Nat.pow a n) p).\n  Proof.\n    induction n.\n    + intros * Hp.\n      pose proof prime_ge_2 (Z.of_nat p) Hp as Hf.\n      simpl. rewrite Nat.mod_1_l.\n      lia. lia.\n    + intros * Hp.\n      simpl.\n      pose proof (IHn a p Hp).\n      rewrite H.\n      rewrite <-Nat2N.inj_mul,\n      <-Nat2N.inj_mod.\n      f_equal.\n      rewrite Nat.mul_mod_idemp_r.\n      reflexivity.\n      pose proof prime_ge_2 (Z.of_nat p) Hp as Hf.\n      lia.\n  Qed. \n      \n  Lemma N_to_nat_exp : forall (n a p : N), \n    prime (Z.of_N p) ->\n    N.modulo (N.pow a n) p = \n    N.of_nat (Nat.modulo (Nat.pow (N.to_nat a) \n      (N.to_nat n)) (N.to_nat p)).\n  Proof.\n    intros * Hp.\n    rewrite <-N2Nat.inj_pow.\n    rewrite <-N2Nat.inj_mod.\n    lia.\n  Qed.\n\n\nEnd Fn.  \n", "meta": {"author": "mukeshtiwari", "repo": "Formally_Verified_Verifiable_Group_Generator", "sha": "e80e8d43e81b5201d6ab82a8ebc07a5cef03476b", "save_path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator", "path": "github-repos/coq/mukeshtiwari-Formally_Verified_Verifiable_Group_Generator/Formally_Verified_Verifiable_Group_Generator-e80e8d43e81b5201d6ab82a8ebc07a5cef03476b/src/Functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7242124292882254}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult y (plus x Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj259_coqofml_Yc4pRo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7242124279274915}}
{"text": "Require Import Nat.\nRequire Import definitions.\n\nRecord ThetaLambdaInner := mkTLInner {\n  tl_eest      : nat;\n  tl_energy    : nat;\n  tl_energyΛ   : nat * option Activity;\n  tl_envelope  : nat;\n  tl_envelopeΛ : nat * option Activity;\n}.\n\nInductive ThetaLambdaLeaf :=\n| tl_theta : Activity -> ThetaLambdaLeaf\n| tl_lambda : Activity -> ThetaLambdaLeaf.\n\nDefinition thetaLambdaInnerFromLeaf (C: nat) (l: ThetaLambdaLeaf) :=\n  match l with\n  | tl_theta  a => mkTLInner (est a) (energy a) ((envelope_unit C a), None) 0 (0, None)\n  | tl_lambda a => mkTLInner (est a) 0 (0, None) (energy a) (envelope_unit C a, None)\n  end.\n\nDefinition rmax {R} (a b: nat*R) :=\n  match (a, b) with ((a, ra), (b, rb)) =>\n  let m := max a b in\n  (m, if m =? a then ra else rb)\n  end.\n\nDefinition radd1 {R} (a: nat*R) (b: nat) := ((fst a)+b, snd a).\nDefinition radd2 {R} (a: nat) (b: nat*R) := (a+(fst b), snd b).\n\nDefinition thetaLambdaPropagate (a b: ThetaLambdaInner) : ThetaLambdaInner :=\n  mkTLInner\n    (min (tl_eest a)   (tl_eest b))\n    (add (tl_energy a) (tl_energy b))\n    (rmax (radd1 (tl_energyΛ a) (tl_energy  b))\n          (radd2 (tl_energy  a) (tl_energyΛ b)))\n    (max (add (tl_envelope a) (tl_energy  b))\n         (tl_envelope b))\n    (rmax (tl_envelopeΛ b) (rmax\n          (radd1 (tl_envelopeΛ a) (tl_energy  b))\n          (radd2 (tl_envelope  a) (tl_energyΛ b))))\n.\n\nInductive AbstractTree {A B: Type} (f: A->B) (g: B->B->B) : B -> Type :=\n| at_inner {a b} : AbstractTree f g a -> AbstractTree f g b -> AbstractTree f g (g a b)\n| at_leaf  (a: A) : AbstractTree f g (f a).\n\nInductive Path {A B} {f: A->B} {g: B->B->B} : forall {b}, AbstractTree f g b -> Type :=\n| p_left  {bl} (l: AbstractTree f g bl)\n          {br} (r: AbstractTree f g br) :\n          Path l ->\n          Path (at_inner f g l r)\n| p_right {bl} (l: AbstractTree f g bl)\n          {br} (r: AbstractTree f g br) :\n          Path r ->\n          Path (at_inner f g l r)\n| p_here  {a} :\n          Path (at_leaf f g a).\n\nRequire Import Coq.Program.Equality.\n\nFixpoint lookupLeaf {A B: Type} (f: A->B) (g: B->B->B)\n    {b: B} {node: AbstractTree f g b} (path: Path node) : A :=\n  match path with\n  | p_left  l r pl => lookupLeaf f g pl\n  | p_right l r pr => lookupLeaf f g pr\n  | @p_here _ _ _ _ a => a\n  end.\n\nDefinition updateLeaf {A B: Type} (f: A->B) (g: B->B->B) (update: A->A)\n    {b: B} {node: AbstractTree f g b} (path: Path node) : { b': B & AbstractTree f g b' }.\ninduction path.\n+ exists bl. apply l.\n+ exists br. apply r.\n+ exists (f (update a)). apply at_leaf.\nDefined.\n\nDefinition updateLeafRel \n  {A B: Type} (f: A->B) (g: B->B->B) (update: A->A)\n  (y x: { b: B & AbstractTree f g b }) :=\n    exists (path: Path (projT2 x)), updateLeaf f g update path = y.\n\n\nRequire Import Coq.Init.Wf.\n\nDefinition wfFunc\n  {A}\n  (f: A -> A)\n:= {P: A->Prop | @well_founded A (fun a b => P b /\\ f b = a)}.\n\nLtac apply_clear X := apply X; clear X.\n\n(* just make sure wfFunc is sane *)\nTheorem wfDec : wfFunc (fun (a: nat) => a-1).\n  exists (fun x => x > 0).\n  intro.\n  induction a; constructor; intros y [precondition rel].\n  inversion precondition.\n  simpl in rel.\n  rewrite PeanoNat.Nat.sub_0_r in rel; subst.\n  apply IHa.\nQed.\n\nTheorem updateLeafWellFounded\n  {A B: Type} (f: A->B) (g: B->B->B) (update: A->A) (WF: wfFunc update) :\n  well_founded (updateLeafRel f g update).\nProof.\n  intro.\n  destruct a as [xb x].\n  constructor.\n  intros.\n  destruct y as [yb y].\n  (* it's tempting to destroy the 'Acc' in the goal here, but not so fast!\n     for the final element there -is- no even smaller element.\n     in that situation there should be a contradiction in the assumptions. *)\n  destruct H as [path HUpdate].\n  set (yby := existT (fun b : B => AbstractTree f g b) yb y) in *.\n  \n  induction path eqn:Z.\n  (*\n       x    y\n      / \\\n     l   r\n  *)\n  (* in the first two cases, the path taking the left or right side\n     implies that both x and y -have- to be at_inner, not at_leaf.\n     demonstrate this by destroying x and y and showing that their\n     at_inner cases are infeasible. *)\n  (*\n  + enough (xb = g bl br). subst xb.\n    enough (x = at_inner f g l r). subst x.\n    destruct y.\n    rewrite <- H. clear H.\n    simpl.*)\n  + admit.\n  + admit.\n  + \n\nDefinition ThetaLambdaNode (C: nat) :=\n  @AbstractTree\n    ThetaLambdaLeaf\n    ThetaLambdaInner\n    (thetaLambdaInnerFromLeaf C)\n    thetaLambdaPropagate.\n\nDefinition maxEnvelopeΛPath {C} {b} (node: ThetaLambdaNode C b) : Path node.\n  induction node.\n  pose (fst (tl_envelopeΛ b) <? fst (tl_envelopeΛ a)).\n  destruct b0 eqn:Z.\n  apply p_left.\n  apply IHnode1.\n  apply p_right.\n  apply IHnode2.\n  apply p_here.\nQed.\n", "meta": {"author": "rrika", "repo": "cumulative", "sha": "b9ab2af27a691249ec656bd482264324a7c8b9ab", "save_path": "github-repos/coq/rrika-cumulative", "path": "github-repos/coq/rrika-cumulative/cumulative-b9ab2af27a691249ec656bd482264324a7c8b9ab/src/theta_lambda_tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7242124215958389}}
{"text": "From mathcomp.ssreflect Require Import ssreflect ssrnat ssrbool.\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import Coq.Init.Wf.\n\nDefinition Fin (n : nat) := Acc lt n.\n\nDefinition all_fin : forall n, Fin n := Wf_nat.lt_wf.\n\nLemma inv_succ : forall n m, Fin n -> n = m.+1 -> Fin m.\nProof. by move=> n m H E; move: E H=>-> H; apply/(Acc_inv H). Defined.\n\nLemma inv_maxl: forall n l r, Fin n -> n = (maxn l r).+1 -> Fin l.\nProof.\n  move=> n l r H E; move: E H=>-> H; apply/(Acc_inv H)=>{H}.\n  by apply/(rwP leP); rewrite ltnS leq_maxl.\nDefined.\n\nLemma inv_maxr: forall n l r, Fin n -> n = (maxn l r).+1 -> Fin r.\nProof.\n  move=> n l r H E; move: E H=>-> H; apply/(Acc_inv H)=>{H}.\n  by apply/(rwP leP); rewrite ltnS leq_maxr.\nDefined.\n", "meta": {"author": "dcastrop", "repo": "coq_ind_coind", "sha": "f4e8ca5a9237829a14c7bc5bf8b7528a9c2773d3", "save_path": "github-repos/coq/dcastrop-coq_ind_coind", "path": "github-repos/coq/dcastrop-coq_ind_coind/coq_ind_coind-f4e8ca5a9237829a14c7bc5bf8b7528a9c2773d3/theories/pfin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.724207616627484}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom GraphTheory Require Import preliminaries digraph sgraph.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n(** * Domination Theory *)\n\n(** ** Hereditary and superhereditary properties *)\nSection Hereditary.\nVariable (T : finType).\n\nImplicit Types (p : pred {set T}) (F D : {set T}).\n\nDefinition hereditary p : bool := [forall (D : {set T} | p D), forall (F : {set T} | F \\subset D), p F].\n\nDefinition superhereditary p : bool := hereditary [pred D | p (~: D)].\n\nProposition hereditaryP p : \n  reflect (forall D F : {set T}, (F \\subset D) -> p D -> p F) (hereditary p).\nProof.\n  apply: (iffP forall_inP) => [H1 D F FsubD pD|H2 D pD].\n  - exact: (forall_inP (H1 _ pD)).\n  - apply/forall_inP => F FsubD; exact: H2 pD.\nQed.\n\nProposition superhereditaryP (p : pred {set T}) : \n  reflect (forall D F : {set T}, (D \\subset F) -> p D -> p F) (superhereditary p).\nProof.\n  apply: (iffP (hereditaryP _)) => /= sh_p D F.\n  all: by rewrite -setCS => /sh_p; rewrite ?setCK; auto.\nQed.\n\nProposition maximal_indsysP p D : hereditary p ->\n  reflect (p D /\\ forall v : T, v \\notin D -> ~~ p (v |: D)) (maxset p D).\nProof. \n  move/hereditaryP => p_hereditary; apply: (iffP maxset_properP).\n  - case => pD maxD; split => // v vD. apply: maxD.\n    by rewrite setUC properUl // sub1set. \n  - case => pD max1D; split => // A /properP [subA [v vA /max1D vD]].\n    apply: contraNN vD; apply: p_hereditary; by rewrite subUset sub1set vA.\nQed.\n\nProposition minimal_indsysP p D : superhereditary p ->\n  reflect (p D /\\ forall v : T, v \\in D -> ~~ p (D :\\ v)) (minset p D).\nProof.\n  rewrite minmaxset => sh_p; apply: (iffP (maximal_indsysP _ _)) => //=.\n  all: rewrite ?setCK => -[pD H]; split => // v; move: (H v).\n  all: by rewrite !inE ?setCU ?setCK ?negbK setDE setIC.\nQed.\n\nEnd Hereditary.\n\n(** ** Weighted Sets *)\n\nSection Weighted_Sets.\nVariables (T : finType) (weight : T -> nat).\nImplicit Types (A B S : {set T}) (p : pred {set T}).\n\nDefinition weight_set (S : {set T}) := \\sum_(v in S) weight v.\nLet W := weight_set.\n\nLemma leqwset A B : A \\subset B -> W A <= W B.\nProof. move=> AsubB ; by rewrite [X in _ <= X](big_setID A) /= (setIidPr AsubB) leq_addr. Qed.\n\nHypothesis positive_weights : forall v : T, weight v > 0.\n\nLemma wset0 A : (A == set0) = (W A == 0).\nProof.\n  apply/eqP/eqP.\n  - move=> Dempty ; rewrite /weight_set.\n    move: Dempty ->. exact: big_set0.\n  - move=> /eqP weightzero.\n    apply/eqP ; move: weightzero.\n    apply: contraLR => /set0Pn. elim=> x xinD.\n    apply: lt0n_neq0 ; rewrite /W /weight_set (bigD1 x) //=.\n    exact/ltn_addr/positive_weights.\nQed.\n\nLemma ltnwset A B :  A \\proper B -> W A < W B.\nProof.\n  move => /properP [AsubB].\n  elim=> x xinB xnotinA.\n  rewrite {2}/W /weight_set (big_setID A) /= (setIidPr AsubB).\n  rewrite -[X in X <= _]addn0 addSn -addnS leq_add2l lt0n.\n  rewrite -/(weight_set _) -wset0. \n  by apply/set0Pn; exists x; apply/setDP.\nQed.\n\n(* Sets of minimum/maximum weight *)\n\nLemma maxweight_maxset p A : p A -> (forall B, p B -> W B <= W A) -> maxset p A.\nProof.\n  move => pA maxA. apply/maxset_properP; split => // B /ltnwset; rewrite ltnNge.\n  exact/contraNN/maxA.\nQed.\n\nLemma minweight_minset p A : p A -> (forall B, p B -> W A <= W B) -> minset p A.\nProof.\n  move => pA minA; apply/minset_properP; split => // B /ltnwset; rewrite ltnNge.\n  exact/contraNN/minA.\nQed.\n\nLemma arg_maxset p A : p A -> maxset p (arg_max A p W).\nProof. by move => pA; apply/maxweight_maxset; case: arg_maxnP. Qed.\n\nLemma arg_minset p A : p A -> minset p (arg_min A p W).\nProof. by move => pA ; apply/minweight_minset; case: arg_minnP. Qed.\n\nEnd Weighted_Sets.\n\n\nSection Domination_Theory.\n\nVariable G : sgraph.\n\n(** ** Stable, Dominating and Irredundant Sets *)\nSection Stable_Set.\n\nVariable S : {set G}.\n\nDefinition stable : bool := [disjoint NS(S) & S].\n\nLocal Lemma stableP_alt :\n  reflect {in S&, forall u v, ~~ u -- v} [forall u in S, forall v in S, ~~ (u -- v)].\nProof. apply: equivP (in11_in2 S S). do 2 (apply: forall_inPP => ?). exact: idP. Qed.\n\nLemma stableEedge : stable = [forall u in S, forall v in S, ~~ (u -- v)].\nProof.\n  symmetry ; rewrite /stable ; apply/stableP_alt/disjointP => stS.\n  - move => x /bigcupP [y yS adjyx] xS. \n    move: adjyx. rewrite in_opn. apply/negP. by apply: stS.\n  - move => x y xS yS. apply/negP => adjxy.\n    exact: (stS y (mem_opns xS adjxy) yS).\nQed.\n\nProposition stableP : reflect {in S&, forall u v, ~~ u -- v} stable.\nProof. rewrite stableEedge ; exact: stableP_alt. Qed.\n\nProposition stablePn : reflect (exists x y, [/\\ x \\in S, y \\in S & x -- y]) (~~ stable).\nProof.\n  rewrite stableEedge.\n  set E := exists _, _.\n  have EE : (exists2 x, x \\in S & exists2 y, y \\in S & x -- y) <-> E by firstorder.\n  rewrite !negb_forall_in; apply: equivP EE; apply: exists_inPP => x.\n  rewrite negb_forall_in; apply: exists_inPP => y. exact: negPn.\nQed.\n\nEnd Stable_Set.\n\n(* the empty set is stable *)\nLemma stable0 : stable set0.\nProof. by apply/stableP=> ? ? ; rewrite in_set0. Qed.\n\nLemma stable1 x : stable [set x].\nProof. by apply/stableP => ? ? /set1P -> /set1P ->; rewrite sgP. Qed.\n\n(* if D is stable, any subset of D is also stable *)\nLemma st_hereditary : hereditary stable.\nProof.\n  apply/hereditaryP.\n  move=> D F FsubD /stableP Dstable.\n  apply/stableP => u v uinF vinF.\n  move: (subsetP FsubD u uinF) => uinD.\n  move: (subsetP FsubD v vinF) => vinD.\n  exact: Dstable.\nQed.\n\n(* TOTHINK: do we need that [hereditary] is a boolean predicate? *)\nLemma sub_stable (B A : {set G}) : \n  A \\subset B -> stable B -> stable A.\nProof.\nmove => subAB stB. exact: (hereditaryP _ st_hereditary _ _ subAB).\nQed.\n\n(**********************************************************************************)\nSection Dominating_Set.\n\nVariable D : {set G}.\n\nDefinition dominating : bool := [forall v, v \\in NS[D]].\n\nLocal Lemma dominatingP_alt : reflect\n  (forall v : G, v \\notin D -> exists2 u : G, u \\in D & u -- v)\n  [forall (v | v \\notin D), exists u in D, u -- v].\nProof. apply: forall_inPP => v; exact: exists_inP. Qed.\n\nLemma dominatingEedge : dominating = [forall (v | v \\notin D), exists u in D, u -- v].\nProof.\n  apply/forallP/forall_inP => [H v vND |H v].\n  - have [u udomv] := bigcupP (H v).\n    rewrite in_cln; case/predU1P => [?|uv]; first by subst;contrab.\n    by apply/exists_inP; exists u.\n  - case: (boolP (v \\in D)) => [|/H/exists_inP[u uD uv]]; last exact: mem_clns uv.\n    exact/subsetP/set_sub_clns.\nQed.\n\nProposition dominatingP : reflect\n  (forall v : G, v \\notin D -> exists2 u : G, u \\in D & u -- v) dominating.\nProof. rewrite dominatingEedge; apply/dominatingP_alt. Qed.\n\nLemma dominatingPn : \n  reflect (exists2 v : G, v \\notin D & {in D, forall u, ~~ u -- v}) (~~ dominating).\nProof.\n  rewrite dominatingEedge negb_forall_in.\n  apply: exists_inPP => x; exact: exists_inPn.\nQed.\n\nEnd Dominating_Set.\n\n(* V(G) is dominating *)\nLemma domT : dominating [set: G].\nProof. apply/forallP => x. exact: (subsetP (set_sub_clns _)). Qed.\n\n(* if D is dominating, any supraset of D is also dominating *)\nLemma dom_superhereditary : superhereditary dominating.\nProof.\n  apply/superhereditaryP => D F /subsetP DsubF /dominatingP Ddom.\n  apply/dominatingP => v vnotinF. \n  have/Ddom [w winD wv]: v \\notin D by apply: contraNN vnotinF; exact: DsubF.\n  exists w => //; exact: DsubF.\nQed.\n\n(**********************************************************************************)\nSection Irredundant_Set.\n\nVariable D : {set G}.\nImplicit Types x y v w : G.\n\nDefinition private_set (v : G) := N[v] :\\: NS[D :\\ v].\n\nLemma privateP v w : \n  reflect (v -*- w /\\ {in D, forall u, u -*- w -> u = v}) (w \\in private_set v).\nProof. \n  apply: (iffP setDP); rewrite !in_cln => -[v_dom_w H]; split => //.\n  - move => u inD u_dom_w; apply: contraNeq H => uDv.\n    apply/bigcupP; exists u; by [exact/setD1P|rewrite in_cln].\n  - apply/negP => /bigcupP [u /setD1P [uDv /H]]. rewrite in_cln => X {}/X.\n    exact/eqP.\nQed.\n\nDefinition irredundant : bool := [forall v : G, (v \\in D) ==> (private_set v != set0)].\n\nProposition irredundantP: reflect {in D, forall v, (private_set v != set0)} irredundant.\nProof.\n  rewrite /irredundant ; apply: (iffP forallP).\n  - move=> H1 v vinD. by move/implyP: (H1 v) => /(_ vinD).\n  - move=> H2 v. apply/implyP=> vinD. by move: (H2 v vinD).\nQed.\n\nProposition irredundantPn : reflect (exists2 v, v \\in D & private_set v == set0) (~~ irredundant).\nProof.\n  rewrite /irredundant ; apply: (iffP forall_inPn) ; last first.\n  - case => x xinD H1. by exists x ; rewrite ?xinD ?H1.\n  - case => x xinD H2; rewrite negbK in H2. by exists x.\nQed.\n\nEnd Irredundant_Set.\n\n(* the empty set is irredundant *)\nLemma irr0 : irredundant set0.\nProof. apply/irredundantP => v ; by rewrite in_set0. Qed.\n\n(* if D is irredundant, any subset of D is also irredundant *)\nLemma irr_hereditary : hereditary irredundant.\nProof.\n  apply/hereditaryP.\n  move=> D F FsubD /irredundantP Dirr.\n  apply/irredundantP => v vinF.\n  move: (subsetP FsubD v vinF) => vinD.\n  move: (Dirr v vinD).\n  case/set0Pn => x /privateP [vdomx H1]. apply/set0Pn; exists x.\n  apply/privateP ; split=> //.\n  move=> u uinF udomx. move: (subsetP FsubD u uinF) => uinD.\n  exact: (H1 u uinD udomx).\nQed.\n\n(** ** Fundamental facts about Domination Theory *)\nSection Relations_between_stable_dominating_irredundant_sets.\n\nVariable D : {set G}.\n\n(* A stable set D is maximal iff D is stable and dominating\n * See Prop. 3.5 of Fundamentals of Domination *)\nTheorem maximal_st_iff_st_dom : maxset stable D <-> (stable D /\\ dominating D).\nProof.\n  rewrite -(rwP (maximal_indsysP _ st_hereditary)).\n  rewrite /iff ; split ; last first.\n  - move=> [ stableD /dominatingP dominatingD].\n    split => // v vnotinD.\n    have [w winD adjwv] := dominatingD _ vnotinD.\n    apply/stablePn; exists v; exists w.\n    by rewrite !inE eqxx winD sgP adjwv orbT.\n  - move => [stableD H1]; split=> //.\n    apply/dominatingP => x xnotinD.\n    have/stablePn [w [z [winDcupx zinDcupx adjwz]]] := H1 x xnotinD.\n    case: (eqVneq z x) => [zisx|zisnotx].\n    + by subst z; exists w => //; rewrite !inE (sg_edgeNeq adjwz) in winDcupx.\n    + have zinD : z \\in D by rewrite !inE (negbTE zisnotx) /= in zinDcupx.\n      exists z => //.\n      move: winDcupx; rewrite in_setU in_set1.\n      case/predU1P => [|winD]; first by move<- ; rewrite sg_sym adjwz.\n      have := stableP D stableD w z winD zinD.\n      apply: contraR. by rewrite adjwz.\nQed.\n\n(* A maximal stable set is minimal dominating\n * See Prop. 3.6 of Fundamentals of Domination *)\nTheorem maximal_st_is_minimal_dom : maxset stable D -> minset dominating D.\nProof.\n  rewrite maximal_st_iff_st_dom => -[/stableP stableD dominatingD].\n  apply/(minimal_indsysP _ dom_superhereditary); split=> // x xinD.\n  apply/dominatingPn ; exists x ; first by rewrite in_setD1 eqxx andFb.\n  move=> y /setD1P [_ yinD]. exact: stableD.\nQed.\n\n(* A dominating set D is minimal iff D is dominating and irredundant\n * See Prop. 3.8 of Fundamentals of Domination *)\nTheorem minimal_dom_iff_dom_irr : minset dominating D <-> (dominating D /\\ irredundant D).\nProof.\n  rewrite -(rwP (minimal_indsysP _ dom_superhereditary)); split ; last first.\n  - move=> [dominatingD /irredundantP irredundantD]; split => // v vinD.\n    have/set0Pn [w /privateP [vdomw H1]] := irredundantD v vinD.\n    apply/dominatingPn; exists w.\n    + rewrite in_setD1 negb_and negbK orbC.\n      case: (boolP (w \\in D)) => //= /H1 -> //. exact: dominates_refl.\n    + move=> u /setD1P [uneqv uinD]. \n      apply: contra_neqN uneqv => uv. \n      by apply: H1 => //; rewrite /dominates uv orbT.\n  - move => [dominatingD H2] ; split=> //.\n    apply/irredundantP => v vinD.\n    have/dominatingPn[w wnotinDminusv H3] := H2 v vinD.\n    apply/set0Pn; exists w; apply/privateP ; split ; last first.\n    + move=> u uinD udomw.\n      apply: contraTeq udomw => uneqv.\n      have uinDminusv : u \\in D :\\ v by rewrite in_setD1 uneqv uinD.\n      rewrite /dominates negb_or (H3 u uinDminusv) andbT.\n      by apply: contraNneq wnotinDminusv => <-.\n    + rewrite /dominates ; case: (boolP (v == w)) => //= vneqw. \n      move: wnotinDminusv ; rewrite in_setD1 eq_sym vneqw andTb => wnotinD.\n      have [u uinD] := dominatingP _ dominatingD w wnotinD.\n      case: (boolP (u == v)) => [|uneqv] ; first by move/eqP->.\n      have uinDminusv : u \\in D :\\ v by rewrite in_setD1 uneqv uinD.\n      by rewrite (negbTE (H3 u uinDminusv)). \nQed.\n\n(* A minimal dominating set is maximal irredundant\n * See Prop. 3.9 of Fundamentals of Domination *)\nTheorem minimal_dom_is_maximal_irr : minset dominating D -> maxset irredundant D.\nProof.\n  rewrite minimal_dom_iff_dom_irr -(rwP (maximal_indsysP _ irr_hereditary)).\n  move=> [dominatingD irredundantD]; split=> // v vnotinD.\n  apply/irredundantPn; exists v; first by rewrite in_setU1 eqxx.\n  apply: contraNT vnotinD => /set0Pn [x /privateP [vdomx xpriv]].\n  have/bigcupP [u uinD udomx] := forallP dominatingD x.\n  by rewrite -[v](xpriv u) -?in_cln // inE uinD orbT.\nQed.\n\nEnd Relations_between_stable_dominating_irredundant_sets.\n\n\n(**********************************************************************************)\nSection Existence_of_stable_dominating_irredundant_sets.\n\n(* Definitions of \"maximal stable\", \"minimal dominating\" and \"maximal irredundant\" sets *)\n\nDefinition max_st := maxset stable.\n\nDefinition min_dom := minset dominating.\n\nDefinition max_irr := maxset irredundant.\n\n(* Inhabitants that are \"maximal stable\", \"minimal dominating\" and \"maximal irredundant\"\n * Recall that ex_minimal and ex_maximal requires a proof of an inhabitant of \"stable\",\n * \"dominating\" and \"irredudant\" to be able to generate the maximal/minimal set. *)\n\nDefinition inhb_max_st := s2val (maxset_exists stable0).\n\nDefinition inhb_min_dom := s2val (minset_exists domT).\n\nDefinition inhb_max_irr := s2val (maxset_exists irr0).\n\nLemma inhb_max_st_is_maximal_stable : max_st inhb_max_st.\nProof. exact: (s2valP (maxset_exists stable0)). Qed.\n\nLemma inhb_min_dom_is_minimal_dominating : min_dom inhb_min_dom.\nProof. exact: (s2valP (minset_exists domT)). Qed.\n\nLemma inhb_max_irr_is_maximal_irredundant : max_irr inhb_max_irr.\nProof. exact: (s2valP (maxset_exists irr0)). Qed.\n\nEnd Existence_of_stable_dominating_irredundant_sets.\n\n\n(**********************************************************************************)\nSection Weighted_domination_parameters.\n\nVariable weight : G -> nat.\nHypothesis positive_weights : forall v : G, weight v > 0.\n\nLet W := weight_set weight.\n\n(* Definition of weighted parameters. *)\n\nDefinition ir_w : nat := W (arg_min inhb_max_irr max_irr W).\n\nFact ir_min D : max_irr D -> ir_w <= W D.\nProof.\n  rewrite /ir_w.\n  by case: (arg_minnP W inhb_max_irr_is_maximal_irredundant) => A _ ; apply.\nQed.\n\nFact ir_witness : exists2 D, max_irr D & W D = ir_w.\nProof.\n  rewrite /ir_w.\n  case: (arg_minnP W inhb_max_irr_is_maximal_irredundant) => D.\n  by exists D.\nQed.\n\nFact ir_minset D : max_irr D -> W D = ir_w -> minset max_irr D.\nProof.\n  move => max_irrD irD; apply: minweight_minset => // A.\n  rewrite -/W irD; exact: ir_min.\nQed.\n\nDefinition gamma_w : nat := W (arg_min setT dominating W).\n\nFact gamma_min D : dominating D -> gamma_w <= W D.\nProof. rewrite /gamma_w. case: (arg_minnP W domT) => A _ ; apply. Qed.\n\nFact gamma_witness : exists2 D, dominating D & W D = gamma_w.\nProof.\n  rewrite /gamma_w.\n  case: (arg_minnP W domT) => D.\n  by exists D.\nQed.\n\nFact gamma_minset D : dominating D -> W D = gamma_w -> minset dominating D.\nProof.\n  move => domD gammaD; apply: minweight_minset => // A.\n  rewrite -/W gammaD; exact: gamma_min.\nQed.\n\nDefinition ii_w : nat := W (arg_min inhb_max_st max_st W).\n\nFact ii_min S : max_st S -> ii_w <= W S.\nProof.\n  rewrite /ii_w.\n  by case: (arg_minnP W inhb_max_st_is_maximal_stable) => A _ ; apply.\nQed.\n\nFact ii_witness : exists2 S, max_st S & W S = ii_w.\nProof.\n  rewrite /ii_w.\n  case: (arg_minnP W inhb_max_st_is_maximal_stable) => S.\n  by exists S.\nQed.\n\nFact ii_minset D : max_st D -> W D = ii_w -> minset max_st D.\nProof.\n  move => max_stD iiD; apply: minweight_minset => // A.\n  rewrite -/W iiD; exact: ii_min.\nQed.\n\nDefinition alpha_w : nat := W (arg_max set0 stable W).\n\nFact alpha_max S : stable S -> W S <= alpha_w.\nProof. by move: S; rewrite /alpha_w; case: (arg_maxnP W stable0). Qed.\n\nFact alpha_witness : exists2 S, stable S & W S = alpha_w.\nProof. by rewrite /alpha_w; case: (arg_maxnP W stable0) => A; exists A. Qed.\n\nFact alpha_maxset S : stable S -> W S = alpha_w -> maxset stable S.\nProof.\n  move => stS alphaS; apply: maxweight_maxset => // A.\n  rewrite -/W alphaS; exact: alpha_max.\nQed.\n\nDefinition Gamma_w : nat := W (arg_max inhb_min_dom min_dom W).\n\nFact Gamma_max D : min_dom D -> W D <= Gamma_w.\nProof. \n  move: D ; rewrite /Gamma_w.\n  by case: (arg_maxnP W inhb_min_dom_is_minimal_dominating).\nQed.\n\nFact Gamma_witness : exists2 D, min_dom D & W D = Gamma_w.\nProof.\n  rewrite /Gamma_w.\n  case: (arg_maxnP W inhb_min_dom_is_minimal_dominating) => D.\n  by exists D.\nQed.\n\nFact Gamma_maxset D : min_dom D -> W D = Gamma_w -> maxset min_dom D.\nProof.\n  move => min_domD GammaD; apply: maxweight_maxset => // A.\n  rewrite -/W GammaD; exact: Gamma_max.\nQed.\n\nDefinition IR_w : nat := W (arg_max set0 irredundant W).\n\nFact IR_max D : irredundant D -> W D <= IR_w.\nProof. by move: D; rewrite /IR_w; case: (arg_maxnP W irr0). Qed.\n\nFact IR_witness : exists2 D, irredundant D & W D = IR_w.\nProof. by rewrite /IR_w; case: (arg_maxnP W irr0) => D; exists D. Qed.\n\nFact IR_maxset D : irredundant D -> W D = IR_w -> maxset irredundant D.\nProof.\n  move => irrD IRD; apply: maxweight_maxset => // A.\n  rewrite -/W IRD; exact: IR_max.\nQed.\n\n(** ** Weighted version of the Cockayne-Hedetniemi domination chain. *)\n\nProposition ir_w_leq_gamma_w : ir_w <= gamma_w.\nProof.\n  rewrite /gamma_w.\n  have [D domD minWD] := arg_minnP W domT.\n  have min_domD := minweight_minset positive_weights domD minWD.\n  have max_irrD := minimal_dom_is_maximal_irr min_domD.\n  exact: ir_min.\nQed.\n\nProposition gamma_w_leq_ii_w : gamma_w <= ii_w.\nProof.\n  rewrite /ii_w.\n  have [S max_stS _] := arg_minnP W inhb_max_st_is_maximal_stable.\n  have domS := minsetp (maximal_st_is_minimal_dom max_stS).\n  exact: gamma_min.\nQed.\n\nProposition ii_w_leq_alpha_w : ii_w <= alpha_w.\nProof.\n  rewrite /alpha_w.\n  have [S stS maxWS] := arg_maxnP W stable0.\n  have max_stS := maxweight_maxset positive_weights stS maxWS.\n  exact: ii_min.\nQed.\n\nProposition alpha_w_leq_Gamma_w : alpha_w <= Gamma_w.\nProof.\n  rewrite /alpha_w.\n  have [S stS maxWS] := arg_maxnP W stable0.\n  have max_stS := maxweight_maxset positive_weights stS maxWS.\n  have min_domS := maximal_st_is_minimal_dom max_stS.\n  exact: Gamma_max.\nQed.\n\nProposition Gamma_w_leq_IR_w : Gamma_w <= IR_w.\nProof.\n  rewrite /Gamma_w.\n  have [D min_domD _] := arg_maxnP W inhb_min_dom_is_minimal_dominating.\n  have irrD := maxsetp (minimal_dom_is_maximal_irr min_domD).\n  exact: IR_max.\nQed.\n\nTheorem Cockayne_Hedetniemi_chain_w: \n  sorted leq [:: ir_w; gamma_w; ii_w; alpha_w; Gamma_w; IR_w].\nProof. \nrewrite /sorted /= ir_w_leq_gamma_w gamma_w_leq_ii_w ii_w_leq_alpha_w.\nby rewrite alpha_w_leq_Gamma_w Gamma_w_leq_IR_w.\nQed.\n\n(* Usage: [apply: (Cockayne_Hedetniemi_w i j)] with i,j concrete\nindices into the above list [i < j] *)\n\nDefinition Cockayne_Hedetniemi_w_leq := \n  @sorted_leq_nth nat leq leq_trans leqnn 0 _ Cockayne_Hedetniemi_chain_w.\n\nNotation Cockayne_Hedetniemi_w i j := \n  (@Cockayne_Hedetniemi_w_leq i j erefl erefl erefl).\n\n(** Example *)\nLet gamma_w_leq_Gamma_w: gamma_w <= Gamma_w. \nProof. exact: (Cockayne_Hedetniemi_w 1 4). Qed.\n\nEnd Weighted_domination_parameters.\n\n(* \"argument\" policy:\n   every weighted parameter requires a graph, the weight vector and a proof that their\n   components are positive *)\nArguments ir_w : clear implicits.\nArguments gamma_w : clear implicits.\nArguments ii_w : clear implicits.\nArguments alpha_w : clear implicits.\nArguments Gamma_w : clear implicits.\nArguments IR_w : clear implicits.\n\n(** ** Classic (unweighted) parameters (use cardinality instead of weight)        *)\n\nSection Classic_domination_parameters.\n\nDefinition ones : (G -> nat) := (fun _ => 1).\n\nLet W1 : ({set G} -> nat) := (fun A => #|A|).\n\nLemma cardwset1 (A : {set G}) : #|A| = weight_set ones A.\nProof. by rewrite /weight_set sum1dep_card cardsE. Qed.\n\nLocal Notation eq_arg_min := (eq_arg_min _ (frefl _) cardwset1).\nLocal Notation eq_arg_max := (eq_arg_max _ (frefl _) cardwset1).\n\n(** Definition of unweighted parameters and its conversion to weighted ones. *)\n\n\nDefinition ir : nat := #|arg_min inhb_max_irr max_irr W1|.\n\nFact eq_ir_ir1 : ir = ir_w ones.\nProof. by rewrite /ir /ir_w -cardwset1 eq_arg_min. Qed.\n\nDefinition gamma : nat := #|arg_min setT dominating W1|.\n\nFact eq_gamma_gamma1 : gamma = gamma_w ones.\nProof. by rewrite /gamma /gamma_w -cardwset1 eq_arg_min. Qed.\n\nDefinition ii : nat := #|arg_min inhb_max_st max_st W1|.\n\nFact eq_ii_ii1 : ii = ii_w ones.\nProof. by rewrite /ii /ii_w -cardwset1 eq_arg_min. Qed.\n\nDefinition alpha : nat := #|arg_max set0 stable W1|.\n\nFact eq_alpha_alpha1 : alpha = alpha_w ones.\nProof. by rewrite /alpha /alpha_w -cardwset1 eq_arg_max. Qed.\n\nDefinition Gamma : nat := #|arg_max inhb_min_dom min_dom W1|.\n\nFact eq_Gamma_Gamma1 : Gamma = Gamma_w ones.\nProof. by rewrite /Gamma /Gamma_w -cardwset1 eq_arg_max. Qed.\n\nDefinition IR : nat := #|arg_max set0 irredundant W1|.\n\nFact eq_IR_IR1 : IR = IR_w ones.\nProof. by rewrite /IR /IR_w -cardwset1 eq_arg_max. Qed.\n\n(** ** Classic Cockayne-Hedetniemi domination chain. *)\n\nCorollary ir_leq_gamma : ir <= gamma.\nProof. by rewrite eq_ir_ir1 eq_gamma_gamma1 ir_w_leq_gamma_w. Qed.\n\nCorollary gamma_leq_ii : gamma <= ii.\nProof. by rewrite eq_gamma_gamma1 eq_ii_ii1 gamma_w_leq_ii_w. Qed.\n\nCorollary ii_leq_alpha : ii <= alpha.\nProof. by rewrite eq_ii_ii1 eq_alpha_alpha1 ii_w_leq_alpha_w. Qed.\n\nCorollary alpha_leq_Gamma : alpha <= Gamma.\nProof. by rewrite eq_alpha_alpha1 eq_Gamma_Gamma1 alpha_w_leq_Gamma_w. Qed.\n\nCorollary Gamma_leq_IR : Gamma <= IR.\nProof. by rewrite eq_Gamma_Gamma1 eq_IR_IR1 Gamma_w_leq_IR_w. Qed.\n\nCorollary Cockayne_Hedetniemi_chain: \n  sorted leq [:: ir; gamma; ii; alpha; Gamma; IR].\nProof. \nrewrite /sorted /= ir_leq_gamma gamma_leq_ii ii_leq_alpha.\nby rewrite alpha_leq_Gamma Gamma_leq_IR.\nQed.\n\nDefinition Cockayne_Hedetniemi_leq := \n  @sorted_leq_nth nat leq leq_trans leqnn 0 _ Cockayne_Hedetniemi_chain.\n\nNotation Cockayne_Hedetniemi i j := \n  (@Cockayne_Hedetniemi_leq i j erefl erefl erefl).\n\n(** Example *)\nLet gamma_leq_Gamma: gamma <= Gamma. \nProof. exact: (Cockayne_Hedetniemi 1 4). Qed.\n\n\n\nEnd Classic_domination_parameters.\n\nEnd Domination_Theory.\n\nArguments ir_w : clear implicits.\nArguments gamma_w : clear implicits.\nArguments ii_w : clear implicits.\nArguments alpha_w : clear implicits.\nArguments Gamma_w : clear implicits.\nArguments IR_w : clear implicits.\nArguments ir : clear implicits.\nArguments gamma : clear implicits.\nArguments ii : clear implicits.\nArguments alpha : clear implicits.\nArguments Gamma : clear implicits.\nArguments IR : clear implicits.\n", "meta": {"author": "coq-community", "repo": "graph-theory", "sha": "18bdabc919f6b20946f40cd5d4fbb5143c46a2bf", "save_path": "github-repos/coq/coq-community-graph-theory", "path": "github-repos/coq/coq-community-graph-theory/graph-theory-18bdabc919f6b20946f40cd5d4fbb5143c46a2bf/theories/core/dom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940925, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7241817920808179}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Hints.ZArith.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma mod_mod_small a n m\n        (Hnm : (m mod n = 0)%Z)\n        (Hnm_le : (0 < n <= m)%Z)\n        (H : (a mod m < n)%Z)\n    : ((a mod n) mod m = a mod m)%Z.\n  Proof.\n    assert ((a mod n) < m)%Z\n      by (eapply Z.lt_le_trans; [ apply Z.mod_pos_bound | ]; omega).\n    rewrite (Z.mod_small _ m) by auto with zarith.\n    apply Z.mod_divide in Hnm; [ | omega ].\n    destruct Hnm as [x ?]; subst.\n    repeat match goal with\n           | [ H : context[(_ mod _)%Z] |- _ ]\n             => revert H\n           end.\n    Z.div_mod_to_quot_rem.\n    lazymatch goal with\n    | [ H : a = (?x * ?n * ?q) + _, H' : a = (?n * ?q') + _ |- _ ]\n      => assert (q' = x * q) by nia; subst q'; nia\n    end.\n  Qed.\n\n  (** [rewrite_mod_small] is a better version of [rewrite Z.mod_small\n      by rewrite_mod_small_solver]; it backtracks across occurences\n      that the solver fails to solve the side-conditions on. *)\n  Ltac rewrite_mod_small_solver :=\n    zutil_arith_more_inequalities.\n  Ltac rewrite_mod_small :=\n    repeat match goal with\n           | [ |- context[?x mod ?y] ]\n             => rewrite (Z.mod_small x y) by rewrite_mod_small_solver\n           end.\n  Ltac rewrite_mod_mod_small :=\n    repeat match goal with\n           | [ |- context[(?a mod ?n) mod ?m] ]\n             => rewrite (mod_mod_small a n m) by rewrite_mod_small_solver\n           end.\n  Ltac rewrite_mod_small_more :=\n    repeat (rewrite_mod_small || rewrite_mod_mod_small).\nEnd Z.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Util/ZUtil/Tactics/RewriteModSmall.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7241817830550202}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (lf2 : natural) : natural :=\n  plus (mult z (Succ y)) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj122_coqofml_37iRPe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7241522777147456}}
{"text": "(** DEPRECATED?  \n    \\o notation for composition is used in LibFixDemos\n*)\n\n(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Functions                                                               *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic LibContainer LibSet.\nGeneralizable Variables A.\n\n\n(* ********************************************************************** *)\n(* ================================================================= *)\n(** ** Indentity function *)\n\nDefinition id {A} (x : A) :=\n  x.\n\n\n(* ********************************************************************** *)\n(** Constant functions *)\n\nDefinition const {A B} (v : B) : A -> B :=\n  fun _ => v.\nDefinition const1 :=\n  @const.\nDefinition const2 {A1 A2 B} (v:B) : A1->A2->B :=\n  fun _ _ => v.\nDefinition const3 {A1 A2 A3 B} (v:B) : A1->A2->A3->B :=\n  fun _ _ _ => v.\nDefinition const4 {A1 A2 A3 A4 B} (v:B) : A1->A2->A3->A4->B :=\n  fun _ _ _ _ => v.\nDefinition const5 {A1 A2 A3 A4 A5 B} (v:B) : A1->A2->A3->A4->A5->B :=\n  fun _ _ _ _ _ => v.\n\n\n(* ********************************************************************** *)\n(** Function application *)\n\nDefinition apply {A B} (f : A -> B) (x : A) :=\n  f x.\n\nDefinition apply_to (A : Type) (x : A) (B : Type) (f : A -> B) :=\n  f x.\n\n\n(* ********************************************************************** *)\n(** Function composition *)\n\nDefinition compose {A B C} (g : B -> C) (f : A -> B) :=\n  fun x => g (f x).\n\nNotation \"f1 \\o f2\" := (compose f1 f2)\n  (at level 49, right associativity) : fun_scope.\n\nSection Combinators.\nOpen Scope fun_scope.\nVariables (A B C D : Type).\n\nLemma compose_id_l : forall (f:A->B),\n  id \\o f = f.\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_id_r : forall (f:A->B),\n  f \\o id = f.\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_assoc : forall (f:C->D) (g:B->C) (h:A->B),\n  (f \\o g) \\o h = f \\o (g \\o h).\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_eq_l : forall (f:B->C) (g1 g2:A->B),\n  g1 = g2 -> f \\o g1 = f \\o g2.\nProof using. intros. subst~. Qed.\n\nLemma compose_eq_r : forall (f:A->B) (g1 g2:B->C),\n  g1 = g2 -> g1 \\o f = g2 \\o f.\nProof using. intros. subst~. Qed.\n\n(** Composition of [LibList.map] behaves well. **)\n(* Could not be put in [LibList] because of circular dependencies. *)\nRequire Import LibList.\n\nLemma list_map_compose : forall A B C (f : A -> B) (g : B -> C) l,\n  LibList.map g (LibList.map f l) = LibList.map (g \\o f) l.\nProof using.\n  introv. induction l.\n   reflexivity.\n   rew_listx. fequals~.\nQed.\n\nEnd Combinators.\n\n(** Tactic for simplifying function compositions *)\n(* --TODO: not used; might become deprecated *)\n\nHint Rewrite compose_id_l compose_id_r compose_assoc : rew_compose.\nTactic Notation \"rew_compose\" :=\n  autorewrite with rew_compose.\nTactic Notation \"rew_compose\" \"in\" \"*\" :=\n  autorewrite with rew_compose in *.\nTactic Notation \"rew_compose\" \"in\" hyp(H) :=\n  autorewrite with rew_compose in H.\n\n\n(* ********************************************************************** *)\n(* ================================================================= *)\n(** ** Function update *)\n\n(** [fupdate f a b x] is like [f] except that it returns [b] for input [a] *)\n\nDefinition fupdate A B (f : A -> B) (a : A) (b : B) : A -> B :=\n  fun x => If (x = a) then b else f x.\n\nLemma fupdate_eq : forall A B (f:A->B) a b x,\n  fupdate f a b x = If (x = a) then b else f x.\nProof using. auto. Qed.\n\nLemma fupdate_same : forall A B (f:A->B) a b,\n  fupdate f a b a = b.\nProof using. intros. unfold fupdate. case_if*. Qed.\n\nLemma fupdate_neq : forall A B (f:A->B) a b x,\n  x <> a ->\n  fupdate f a b x = f x.\nProof using. intros. unfold fupdate. case_if*. Qed.\n\n(* Opaque fupdate. -- could be added in the future *)\n\n\n(* ********************************************************************** *)\n(* ================================================================= *)\n(** ** Function image *)\n\nSection FunctionImage.\nOpen Scope set_scope.\nRequire Import LibList.\n\nDefinition image A B (f : A -> B) (E : set A) : set B :=\n  \\set{ y | exists_ x \\in E, y = f x }.\n\nLemma in_image_prove_eq : forall A B x (f : A -> B) (E : set A),\n  x \\in E -> f x \\in image f E.\nProof using. introv N. unfold image. rew_set. exists* x. Qed.\n\nLemma in_image_prove : forall A B x y (f : A -> B) (E : set A),\n  x \\in E -> y = f x -> y \\in image f E.\nProof using. intros. subst. applys* in_image_prove_eq. Qed.\n\nLemma in_image_inv : forall A B y (f : A -> B) (E : set A),\n  y \\in image f E -> exists x, x \\in E /\\ y = f x.\nProof using. introv N. unfolds image. rew_set in N. auto. Qed.\n\nLemma finite_image : forall A B (f : A -> B) (E : set A),\n  finite E ->\n  finite (image f E).\nProof using.\n  introv M. lets (L&H): finite_inv_list_covers M.\n  applys finite_of_list_covers (LibList.map f L). introv N.\n  lets (y&Hy&Ey): in_image_inv (rm N). subst x. applys* mem_map.\nQed.\n\nLemma image_covariant : forall A B (f : A -> B) (E F : set A),\n  E \\c F ->\n  image f E \\c image f F.\nProof using.\n  introv. do 2 rewrite incl_in_eq. introv M N.\n  lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\nQed.\n\nLemma image_union : forall A B (f : A -> B) (E F : set A),\n  image f (E \\u F) = image f E \\u image f F.\nProof using.\n  Hint Resolve in_image_prove.\n  introv. apply in_extens. intros x. iff N.\n    lets (y&Hy&Ey): in_image_inv (rm N). rewrite in_union_eq in Hy.\n     rewrite in_union_eq. destruct* Hy.\n    rewrite in_union_eq in N. destruct N as [N|N].\n      lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\n       rewrite in_union_eq. eauto.\n      lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\n       rewrite in_union_eq. eauto.\nQed.\n\nLemma image_singleton : forall A B (f : A -> B) (x : A),\n  image f \\{x} = \\{f x}.\nProof using.\n  intros. apply in_extens. intros z. rewrite in_single_eq. iff N.\n    lets (y&Hy&Ey): in_image_inv (rm N). rewrite in_single_eq in Hy. subst~.\n    applys* in_image_prove. rewrite~ @in_single_eq. typeclass.\nQed.\n\nEnd FunctionImage.\n\nHint Resolve finite_image : finite.\n\n\n(* ********************************************************************** *)\n(* ================================================================= *)\n(** ** Function preimage *)\n\nSection FunctionPreimage.\nOpen Scope set_scope.\n\nDefinition preimage A B (f : A -> B) (E : set B) : set A :=\n  \\set{ x | exists_ y \\in E, y = f x }.\n\nEnd FunctionPreimage.\n\n\n(* ********************************************************************** *)\n(* ================================================================= *)\n(** ** Function iteration *)\n\nFixpoint applyn A n (f : A -> A) x :=\n  match n with\n  | O => x\n  | S n' => f (applyn n' f x)\n  end.\n\nLemma applyn_fix : forall A n f (x : A),\n  applyn (S n) f x = applyn n f (f x).\nProof using. introv. induction~ n. simpls. rewrite~ IHn. Qed.\n\nLemma applyn_comp : forall A n m f (x : A),\n  applyn n f (applyn m f x) = applyn (n + m) f x.\nProof using.\n  introv. gen m; induction n; introv; simpls~.\n  rewrite~ IHn.\nQed.\n\nLemma applyn_nested : forall A n m f (x : A),\n  applyn n (applyn m f) x = applyn (n * m) f x.\nProof using.\n  introv. gen m. induction n; introv; simpls~.\n  rewrite IHn. rewrite~ applyn_comp.\nQed.\n\nLemma applyn_altern : forall A B (f : A -> B) (g : B -> A) x n,\n  applyn n (fun x => f (g x)) (f x) =\n    f (applyn n (fun x => g (f x)) x).\nProof using. introv. gen x. induction~ n. introv. repeat rewrite applyn_fix. autos~. Qed.\n\nLemma applyn_ind : forall A (P : A -> Prop) (f : A -> A) x n,\n  (forall x, P x -> P (f x)) ->\n  P x ->\n  P (applyn n f x).\nProof using. introv I. induction n; introv Hx; autos*. Qed.\n\n\n(* --TODO: rename applyn to iter *)\n(* --TODO: migrate iteration of functionals from LibFix to here *)\n\n", "meta": {"author": "Artalik", "repo": "monad-frame-src", "sha": "7aa9364eb94c10f447a215351cd84dcbc8506714", "save_path": "github-repos/coq/Artalik-monad-frame-src", "path": "github-repos/coq/Artalik-monad-frame-src/monad-frame-src-7aa9364eb94c10f447a215351cd84dcbc8506714/src/LibFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.72413532469377}}
{"text": "Set Implicit Arguments.\nRequire Export Omega.\nRequire Export ArithRing.\nRequire Export Coq.Numbers.Natural.Peano.NPeano.\n  (* [Nat] is a sub-module of [NPeano], which seems to contain many things.\n     E.g. it defines [Nat.div], [Nat.pow], [Nat.log2].\n     E.g. it defines [Nat.max], which is the same as [max].\n     E.g. it has many properties of [max], see [Coq.Structures.GenericMinMax].\n     Unfortunately [Nat.le] is NOT the same as [le], which is [Peano.le].\n     For this reason, we do NOT import [Nat]. *)\n  Notation log2 := Nat.log2.\nRequire Import TLC.LibTactics.\nRequire Import LibFunOrd.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* A few simplification lemmas. *)\n\nLemma plus_lt_plus:\n  forall a x y,\n  x < y ->\n  x + a < y + a.\nProof using.\n  intros. omega.\nQed.\n\nLemma plus_le_plus:\n  forall a x y,\n  x <= y ->\n  x + a <= y + a.\nProof using.\n  intros. omega.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* [a <= b] is equivalent to [b = a + n] for some unknown [n]. *)\n\nLemma leq_to_eq_plus:\n  forall a b,\n  a <= b ->\n  exists n,\n  b = a + n.\nProof.\n  intros. exists (b - a). omega.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Make [omega] a hint. *)\n\nHint Extern 1 => omega : omega.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* This lemma allows simplifying a [max] expression, by cases. *)\n\nLemma max_case:\n  forall m1 m2,\n  m2 <= m1 /\\ max m1 m2 = m1 \\/\n  m1 <= m2 /\\ max m1 m2 = m2.\nProof using.\n  intros. destruct (@le_gt_dec m1 m2); eauto using max_r, max_l with omega.\nQed.\n\n(* This tactic looks for a [max] expression in the hypotheses or in the goal\n   and applies the above lemma. *)\n\nLtac max_case_m_n_as m n h :=\n  let i := fresh in\n  destruct (max_case m n) as [ [ h i ] | [ h i ] ];\n  rewrite i in *;\n  clear i.\n\nLtac max_case_as h :=\n  match goal with\n  | |- context[max ?m ?n] =>\n      max_case_m_n_as m n h\n  | foo: context[max ?m ?n] |- _ =>\n      max_case_m_n_as m n h\n  end.\n\nLtac max_case :=\n  let h := fresh in\n  max_case_as h.\n\n(* [max m1 m2] is an upper bound for [m1] and [m2]. This can be sufficient\n   to reason about [max] without introducing a case split. *)\n\nLemma max_ub:\n  forall m1 m2,\n  m1 <= max m1 m2 /\\ m2 <= max m1 m2.\nProof using.\n  intros. eauto using Nat.le_max_l, Nat.le_max_r.\nQed.\n\nLtac max_ub_m_n_as m n h1 h2 :=\n  destruct (max_ub m n) as [ h1 h2 ];\n  generalize dependent (max m n);\n  intros.\n\nLtac max_ub_as h1 h2 :=\n  match goal with\n  | |- context[max ?m ?n] =>\n      max_ub_m_n_as m n h1 h2\n  | foo: context[max ?m ?n] |- _ =>\n      max_ub_m_n_as m n h1 h2\n  end.\n\nLtac max_ub :=\n  let h1 := fresh in\n  let h2 := fresh in\n  max_ub_as h1 h2.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Properties of multiplication. *)\n\nLemma mult_positive:\n  forall m n,\n  0 < m ->\n  0 < n ->\n  0 < m * n.\nProof using.\n  intros.\n  destruct (eq_nat_dec (m * n) 0).\n  forwards [ ? | ? ]: mult_is_O. eauto. omega. omega.\n  generalize dependent (m * n). intros. omega.\nQed.\n\nHint Resolve mult_positive : positive.\n\nLemma mult_magnifies_left:\n  forall m n,\n  0 < n ->\n  m <= n * m.\nProof using.\n  intros.\n  destruct n; [ omega | simpl ].\n  generalize (n * m); intro.\n  omega.\nQed.\n\nLemma mult_magnifies_right:\n  forall m n,\n  0 < n ->\n  m <= m * n.\nProof using.\n  intros. rewrite mult_comm. eauto using mult_magnifies_left.\nQed.\n\nLemma mult_magnifies_right_strict:\n  forall m n,\n  0 < m ->\n  1 < n ->\n  m < m * n.\nProof using.\n  intros.\n  do 2 (destruct n; [ omega | ]).\n  rewrite mult_comm. simpl.\n  generalize (n * m). intros. omega.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Properties of division. *)\n\n(* It is strange that the Coq standard library offers [divmod_spec],\n   but lacks its corollary [div_spec]. *)\n\nLemma div_spec:\n  forall n k,\n  0 < k ->\n  exists r,\n  k * (n / k) + r = n /\\ 0 <= r < k.\nProof using.\n  intros. unfold Nat.div.\n  destruct k; [ false; omega | simpl ].\n  forwards: Nat.divmod_spec n k 0 k. eauto.\n  destruct (Nat.divmod n k 0 k) as [ q r ]. unpack. simpl.\n  exists (k - r). omega.\nQed.\n\n(* Avoid undesired simplifications. *)\n(* TEMPORARY [plus] should be opaque too? *)\nGlobal Opaque mult Nat.div max.\n\n(* A tactic to reason about [n/2] in terms of its specification. *)\n\nLtac div2 :=\n  match goal with |- context[?n/2] =>\n    let h := fresh in\n    forwards h: div_spec n 2; [ omega |\n      gen h; generalize (n/2); intros; unpack\n    ]\n  end.\n\n(* [./2] is monotonic. *)\n\nLemma div2_monotonic:\n  forall m n,\n  m <= n ->\n  m / 2 <= n / 2.\nProof using.\n  intros. repeat div2. omega.\nQed.\n\nLemma div2_step:\n  forall n,\n  (n + 2) / 2 = n/2 + 1.\nProof using.\n  intros. repeat div2. omega.\nQed.\n\nLemma div2_monotonic_strict:\n  forall m n,\n  m + 2 <= n ->\n  m / 2 < n / 2.\nProof using.\n  intros. cut (m/2 + 1 <= n/2). omega.\n  rewrite <- div2_step.\n  eauto using div2_monotonic.\nQed.\n\nLemma mult_div_2:\n  forall n,\n  2 * (n / 2) <= n.\nProof using.\n  intros. div2. omega.\nQed.\n\nLemma div_mult_2:\n  forall n,\n  (2 * n) / 2 = n.\nProof using.\n  intros. div2. omega.\nQed.\n\n(* A collection of lemmas about division by two and ordering. *)\n\nLemma prove_div2_le:\n  forall m n,\n  m <= 2 * n + 1 -> (* tight *)\n  m / 2 <= n.\nProof using.\n  intros. div2. omega.\nQed.\n\nLemma use_div2_plus1_le:\n  forall m n,\n  (n + 1) / 2 <= m -> (* tight *)\n  n <= 2 * m.\nProof using.\n  intros m n. div2. omega.\nQed.\n\nLemma use_div2_le:\n  forall m n,\n  n / 2 <= m -> (* tight *)\n  n <= 2 * m + 1.\nProof using.\n  intros m n. div2. omega.\nQed.\n\nLemma prove_le_div2:\n  forall m n,\n  2 * m <= n -> (* tight *)\n  m <= n / 2.\nProof using.\n  intros. div2. omega.\nQed.\n\nLemma use_le_div2:\n  forall m n,\n  n <= m / 2 -> (* tight *)\n  2 * n <= m.\nProof using.\n  intros m n. div2. omega.\nQed.\n\nLemma prove_div2_lt:\n  forall m n,\n  m < 2 * n -> (* tight *)\n  m / 2 < n.\nProof using.\n  intros. div2. omega.\nQed.\n\nLemma use_div2_lt:\n  forall m n,\n  m / 2 < n -> (* tight *)\n  m < 2 * n.\nProof using.\n  intros m n. div2. omega.\nQed.\n\nLemma prove_lt_div2:\n  forall m n,\n  2 * m < n - 1 -> (* tight *)\n  m < n / 2.\nProof using.\n  intros. div2. omega.\nQed.\n\nLemma prove_lt_div2_zero:\n  forall n,\n  1 < n -> (* tight *)\n  0 < n / 2.\nProof using.\n  intros. div2. omega.\nQed.\n\nLemma use_lt_div2:\n  forall m n,\n  m < (n + 1) / 2 -> (* tight *)\n  2 * m < n.\nProof using.\n  intros m n. div2. omega.\nQed.\n\nHint Resolve prove_lt_div2_zero : positive.\n\nHint Resolve prove_div2_le use_div2_plus1_le use_div2_le prove_le_div2\nuse_le_div2 prove_div2_lt use_div2_lt prove_lt_div2 use_lt_div2 :\ndiv2.\n\nGoal\n  forall n,\n  n <= 2 * (n / 2) + 1.\nProof using.\n  eauto with div2.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The [pow] function. *)\n\nLemma power_positive:\n  forall k n,\n  0 < n ->\n  0 < n^k.\nProof using.\n  induction k; simpl; intros.\n  omega.\n  eauto using mult_positive.\nQed.\n\nHint Resolve power_positive : positive.\n\nLemma power_plus:\n  forall k1 k2 n,\n  n^(k1 + k2) = n^k1 * n^k2.\nProof using.\n  induction k1; simpl; intros.\n  omega.\n  rewrite IHk1. ring.\nQed.\n\nLemma power_of_zero:\n  forall k,\n  0 < k ->\n  0^k = 0.\nProof using.\n  induction k; simpl; intros; omega.\nQed.\n\nLemma power_monotonic_in_k:\n  (* We must assume [n > 0], because [0^0] is 1, yet [0^1] is 0. *)\n  forall n,\n  0 < n ->\n  monotonic le le (fun k => n^k).\nProof using.\n  intros. intros k1 k2 ?.\n  assert (f: k2 = k1 + (k2 - k1)). omega.\n  rewrite f. rewrite power_plus.\n  eapply mult_magnifies_right.\n  eapply power_positive.\n  assumption.\nQed.\n\nLemma power_strictly_monotonic_in_k:\n  forall n,\n  1 < n ->\n  monotonic lt lt (fun k => n^k).\nProof using.\n  intros. intros k1 k2 ?.\n  assert (f: k2 = k1 + S (k2 - k1 - 1)). omega.\n  rewrite f. rewrite power_plus.\n  eapply mult_magnifies_right_strict.\n    { eauto with positive omega. }\n    { simpl.\n      eapply lt_le_trans with (m := n). omega.\n      eapply mult_magnifies_right.\n      eauto with positive omega. }\nQed.\n\nLemma power_strictly_monotonic_in_n:\n  forall k,\n  0 < k ->\n  monotonic lt lt (fun n => n^k).\nProof using.\n  (* We first prove that this holds when [n1] is nonzero,\n     and reformulate the hypothesis [k > 0] so that it is\n     amenable to induction. *)\n  assert (f:\n    forall k n1 n2,\n    0 < n1 < n2 ->\n    n1^(S k) < n2^(S k)\n  ).\n  { induction k; simpl; intros.\n    omega.\n    eapply lt_le_trans; [ eapply mult_lt_compat_r | eapply mult_le_compat_l ]. (* wow *)\n      omega.\n      eapply power_positive with (k := S k). omega.\n      forwards: IHk. eauto. simpl in *. omega. }\n  (* There remains to treat separately the case where [n1] is 0. *)\n  intros. intros n1 n2 ?.\n  destruct (le_gt_dec n1 0).\n    { assert (n1 = 0). omega. subst.\n      rewrite power_of_zero by assumption.\n      eapply power_positive. omega. }\n    { destruct k; [ omega | ].\n      eapply f. omega. } (* ouf *)\nQed.\n\nHint Resolve power_monotonic_in_k power_strictly_monotonic_in_k\npower_strictly_monotonic_in_n : monotonic typeclass_instances.\n\nLemma power_monotonic_in_n:\n  forall k,\n  monotonic le le (fun n => n^k).\nProof using.\n  intros.\n  destruct (eq_nat_dec k 0).\n  { subst. simpl. repeat intro. omega. }\n  { eauto with monotonic omega. }\nQed.\n\nHint Resolve power_monotonic_in_n : monotonic typeclass_instances.\n\n(* TEMPORARY maybe explicitly use [inverse_monotonic] in lemmas below *)\n\nLemma power_inverse_monotonic_in_k:\n  forall n,\n  1 < n ->\n  forall k1 k2,\n  n^k1 <= n^k2 ->\n  k1 <= k2.\nProof using.\n  intros.\n  eapply monotonic_lt_lt_implies_inverse_monotonic_le_le with (f := fun k => n^k);\n  eauto using power_strictly_monotonic_in_k.\nQed.\n\nLemma power_strictly_inverse_monotonic_in_k:\n  forall n k1 k2,\n  0 < n ->\n  n^k1 < n^k2 ->\n  k1 < k2.\nProof using.\n  intros.\n  eapply monotonic_le_le_implies_inverse_monotonic_lt_lt with (f := fun k => n^k);\n  eauto using power_monotonic_in_k.\nQed.\n\nLemma power_strictly_inverse_monotonic_in_k_variant:\n  forall n k1 k2,\n  0 < n ->\n  n^k1 < n^(1 + k2) ->\n  k1 <= k2.\nProof using.\n  intros. cut (k1 < 1 + k2). { omega. }\n  eauto using power_strictly_inverse_monotonic_in_k.\nQed.\n\nLemma power_strictly_inverse_monotonic_in_k_frame:\n  forall n k1 k2,\n  1 < n ->\n  n^k2 <= n^k1 < n^(1 + k2) ->\n  k1 = k2.\nProof using.\n  intros.\n  assert (k2 <= k1).\n    { eapply power_inverse_monotonic_in_k with (n := n); eauto with omega. }\n  assert (k1 < 1 + k2).\n    { eapply power_strictly_inverse_monotonic_in_k with (n := n); eauto with omega. }\n  omega.\nQed.\n\nLemma power_inverse_monotonic_in_n:\n  forall k,\n  0 < k ->\n  forall n1 n2,\n  n1^k <= n2^k ->\n  n1 <= n2.\nProof using.\n  intros.\n  eapply monotonic_lt_lt_implies_inverse_monotonic_le_le with (f := fun n => n^k);\n  eauto using power_strictly_monotonic_in_n.\nQed.\n\n(* A lower bound on [2^n]. *)\n\nLemma n_lt_power:\n  forall n,\n  n < 2^n.\nProof using.\n  induction n; simpl; omega.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Base 2 logarithm. *)\n\n(* The Coq standard library gives us the following:\n     Lemma log2_spec : forall n, 0<n ->\n       2^(log2 n) <= n < 2^(S (log2 n)).\n*)\n\nLtac log2_spec :=\n  match goal with |- context[log2 ?n] =>\n    let h := fresh in\n    forwards h: Nat.log2_spec n; [ eauto with positive omega |\n      gen h; generalize (log2 n); intros; unpack\n    ]\n  end.\n\n(* The above specification is functional, i.e., it defines [log2 n] in a\n   unique manner. *)\n\nLemma log2_uniqueness_half:\n  forall n k1 k2,\n  2^k1 <= n < 2^(1 + k1) ->\n  2^k2 <= n < 2^(1 + k2) ->\n  k1 <= k2.\nProof using.\n  simpl. intros. unpack.\n  eapply power_strictly_inverse_monotonic_in_k_variant with (n := 2). omega.\n  eauto using le_lt_trans.\nQed.\n\nLemma log2_uniqueness:\n  forall n k1 k2,\n  2^k1 <= n < 2^(1 + k1) ->\n  2^k2 <= n < 2^(1 + k2) ->\n  k1 = k2.\nProof using.\n  intros.\n  forwards: log2_uniqueness_half n k1 k2; eauto.\n  forwards: log2_uniqueness_half n k2 k1; eauto.\n  omega.\nQed.\n\n(* When applied to a power of two, [log2] yields the exponent. *)\n\nLemma log2_pow:\n  forall k,\n  log2 (2^k) = k.\nProof using.\n  intros k. log2_spec.\n  symmetry. eapply power_strictly_inverse_monotonic_in_k_frame with (n := 2). omega.\n  eauto.\nQed.\n\n(* This is just a repetition of one half of [log2_spec]. *)\n\nLemma pow_log2:\n  forall n,\n  0 < n ->\n  2 ^ (log2 n) <= n.\nProof using.\n  intros. eapply Nat.log2_spec. eauto.\nQed.\n\nLemma pow_succ_log2:\n  forall n,\n  n < 2^(1 + log2 n).\nProof using.\n  intros.\n  destruct (eq_nat_dec n 0).\n  { subst. simpl. omega. }\n  { eapply Nat.log2_spec. omega. }\nQed.\n\n(* The inductive step of many arguments that involve divide-and-conquer. *)\n\nLemma log2_step:\n  forall n,\n  2 <= n ->\n  1 + log2 (n/2) = log2 n.\nProof using.\n  intros. repeat log2_spec.\n  eapply log2_uniqueness; [ | eauto ].\n  simpl. eauto with div2.\nQed.\n\n(* [log2] is monotonic. *)\n\nLemma log2_monotonic:\n  monotonic le le log2.\nProof using.\n  intros m n ?.\n  (* A special case for [m = 0]. *)\n  destruct (eq_nat_dec m 0).\n  { subst. unfold log2. simpl. omega. }\n  (* Case [m > 0]. *)\n  do 2 log2_spec.\n  eapply power_strictly_inverse_monotonic_in_k_variant with (n := 2); simpl; omega.\nQed.\n\nHint Resolve log2_monotonic : monotonic typeclass_instances.\n\n(* A collection of lemmas involving [log2] and ordering. *)\n\nLemma prove_le_log2:\n  forall k n,\n  2^k <= n ->\n  k <= log2 n.\nProof using.\n  intros.\n  forwards: log2_monotonic. eauto.\n  rewrite log2_pow in *.\n  assumption.\nQed.\n\nLemma prove_log2_le:\n  forall k n,\n  n <= 2^k ->\n  log2 n <= k.\nProof using.\n  intros.\n  forwards: log2_monotonic. eauto.\n  rewrite log2_pow in *.\n  assumption.\nQed.\n\nLemma prove_log2_lt:\n  forall k n,\n  0 < n ->\n  n < 2^k ->\n  log2 n < k.\nProof using.\n  intros.\n  eapply monotonic_le_le_implies_inverse_monotonic_lt_lt with (f := fun n => 2^n).\n    { eauto with monotonic. }\n  eauto using le_lt_trans, pow_log2.\nQed.\n\nHint Resolve prove_le_log2 prove_log2_le prove_log2_lt : log2.\n\n(* An upper bound on [log2 n]. *)\n\nLemma log2_lt_n:\n  forall n,\n  0 < n ->\n  log2 n < n.\nProof using.\n  eauto using prove_log2_lt, n_lt_power.\nQed.\n\n(* ---------------------------------------------------------------------------- *)\n\n(* The existence of the function [log2] means that the sequence [n], [n/2],\n   [n/4], etc. tends towards zero. We can exploit this by giving the following\n   induction principle. *)\n\nLemma div2_induction:\n  forall (P : nat -> Prop),\n  P 0 ->\n  (forall n, P (n/2) -> P n) ->\n  forall n, P n.\nProof using.\n  introv hbase hstep.\n  assert (f: forall k n, log2 n < k -> P n).\n  { induction k; intros.\n    false. omega.\n    (* Special cases for [n = 0] and [n = 1]. *)\n    destruct (eq_nat_dec n 0); [ subst n | ]. { eauto. }\n    destruct (eq_nat_dec n 1); [ subst n | ]. { eauto. }\n    (* In the general case, [2 <= n], we use [log2_step]. *)\n    eapply hstep. eapply IHk.\n    cut (1 + log2 (n / 2) <= k). { omega. }\n    rewrite log2_step by omega.\n    omega.\n  }\n  intros. eapply f with (k := log2 n + 1). omega.\nQed.\n\n(* The following variant of the above induction principle allows\n   establishing a property [P] that mentions both [log2 n] and [n]. *)\n\nLemma log2_induction:\n  forall (P : nat -> nat -> Prop),\n  P 0 0 ->\n  P 0 1 ->\n  (forall k n, 2 <= n -> P k (n/2) -> P (1+k) n) ->\n  forall n, P (log2 n) n.\nProof using.\n  introv h00 h01 hkn.\n  (* Maybe one could give a direct proof; anyway, we choose to give\n     a proof based on the previous induction principle. *)\n  assert (forall n, 1 <= n -> P (log2 n) n).\n  { eapply (@div2_induction (fun n => 1 <= n -> P (log2 n) n)).\n    (* The base case cannot arise. *)\n    { intro. false. omega. }\n    (* Step. *)\n    { intros n IH ?.\n      (* Special case for [n = 1]. *)\n      destruct (eq_nat_dec n 1); [ subst n; exact h01 | ].\n      (* In the general case, [2 <= n], we use [log2_step]. *)\n      assert (2 <= n). { omega. }\n      rewrite <- log2_step by assumption.\n      eauto with div2. }\n  }\n  intro n.\n  (* Special case for [n = 0]. *)\n  destruct (eq_nat_dec n 0); [ subst n; exact h00 | ].\n  (* General case. *)\n  eauto with omega.\nQed.\n", "meta": {"author": "fakusb", "repo": "coq-bigO", "sha": "5607fd6cf3d9a30eac05c78f8efa500573b29630", "save_path": "github-repos/coq/fakusb-coq-bigO", "path": "github-repos/coq/fakusb-coq-bigO/coq-bigO-5607fd6cf3d9a30eac05c78f8efa500573b29630/src/LibNatExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7240904926847791}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Permutation.v\n\n    Defintion and properties of permutations\n   **********************************************************************)\nRequire Export List.\nRequire Export ListAux.\n\nSection permutation.\nVariable A : Set.\n\n(**************************************\n   Definition of permutations as sequences of adjacent transpositions\n **************************************)\n\nInductive permutation : list A -> list A -> Prop :=\n  | permutation_nil : permutation nil nil\n  | permutation_skip :\n      forall (a : A) (l1 l2 : list A),\n      permutation l2 l1 -> permutation (a :: l2) (a :: l1)\n  | permutation_swap :\n      forall (a b : A) (l : list A), permutation (a :: b :: l) (b :: a :: l)\n  | permutation_trans :\n      forall l1 l2 l3 : list A,\n      permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\nHint Constructors permutation : core.\n\n(**************************************\n   Reflexivity\n **************************************)\n\nTheorem permutation_refl : forall l : list A, permutation l l.\nsimple induction l.\napply permutation_nil.\nintros a l1 H.\napply permutation_skip with (1 := H).\nQed.\nHint Resolve permutation_refl : core.\n\n(**************************************\n   Symmetry\n   **************************************)\n\nTheorem permutation_sym :\n forall l m : list A, permutation l m -> permutation m l.\nintros l1 l2 H'; elim H'.\napply permutation_nil.\nintros a l1' l2' H1 H2.\napply permutation_skip with (1 := H2).\nintros a b l1'.\napply permutation_swap.\nintros l1' l2' l3' H1 H2 H3 H4.\napply permutation_trans with (1 := H4) (2 := H2).\nQed.\n\n(**************************************\n   Compatibility with list length\n   **************************************)\n\nTheorem permutation_length :\n forall l m : list A, permutation l m -> length l = length m.\nintros l m H'; elim H'; simpl in |- *; auto.\nintros l1 l2 l3 H'0 H'1 H'2 H'3.\nrewrite <- H'3; auto.\nQed.\n\n(**************************************\n   A permutation of the nil list is the nil list\n   **************************************)\n\nTheorem permutation_nil_inv : forall l : list A, permutation l nil -> l = nil.\nintros l H; generalize (permutation_length _ _ H); case l; simpl in |- *;\n auto.\nintros; discriminate.\nQed.\n\n(**************************************\n   A permutation of the singleton list is the singleton list\n   **************************************)\n\nLet permutation_one_inv_aux :\n  forall l1 l2 : list A,\n  permutation l1 l2 -> forall a : A, l1 = a :: nil -> l2 = a :: nil.\nintros l1 l2 H; elim H; clear H l1 l2; auto.\nintros a l3 l4 H0 H1 b H2.\ninjection H2; intros; subst; auto.\nrewrite (permutation_nil_inv _ (permutation_sym _ _ H0)); auto.\nintros; discriminate.\nQed.\n\nTheorem permutation_one_inv :\n forall (a : A) (l : list A), permutation (a :: nil) l -> l = a :: nil.\nintros a l H; apply permutation_one_inv_aux with (l1 := a :: nil); auto.\nQed.\n\n(**************************************\n   Compatibility with the belonging\n   **************************************)\n\nTheorem permutation_in :\n forall (a : A) (l m : list A), permutation l m -> In a l -> In a m.\nintros a l m H; elim H; simpl in |- *; auto; intuition.\nQed.\n\n(**************************************\n   Compatibility with the append function\n   **************************************)\n\nTheorem permutation_app_comp :\n forall l1 l2 l3 l4,\n permutation l1 l2 -> permutation l3 l4 -> permutation (l1 ++ l3) (l2 ++ l4).\nintros l1 l2 l3 l4 H1; generalize l3 l4; elim H1; clear H1 l1 l2 l3 l4;\n simpl in |- *; auto.\nintros a b l l3 l4 H.\ncut (permutation (l ++ l3) (l ++ l4)); auto.\nintros; apply permutation_trans with (a :: b :: l ++ l4); auto.\nelim l; simpl in |- *; auto.\nintros l1 l2 l3 H H0 H1 H2 l4 l5 H3.\napply permutation_trans with (l2 ++ l4); auto.\nQed.\nHint Resolve permutation_app_comp : core.\n\n(**************************************\n   Swap two sublists\n   **************************************)\n\nTheorem permutation_app_swap :\n forall l1 l2, permutation (l1 ++ l2) (l2 ++ l1).\nintros l1; elim l1; auto.\nintros; rewrite <- app_nil_end; auto.\nintros a l H l2.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\napply permutation_trans with (l ++ l2 ++ a :: nil); auto.\napply permutation_trans with (((a :: nil) ++ l2) ++ l); auto.\nsimpl in |- *; auto.\napply permutation_trans with (l ++ (a :: nil) ++ l2); auto.\napply permutation_sym; auto.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\napply permutation_app_comp; auto.\nelim l2; simpl in |- *; auto.\nintros a0 l0 H0.\napply permutation_trans with (a0 :: a :: l0); auto.\napply (app_ass l2 (a :: nil) l).\napply (app_ass l2 (a :: nil) l).\nQed.\n\n(**************************************\n   A transposition is a permutation\n   **************************************)\n\nTheorem permutation_transposition :\n forall a b l1 l2 l3,\n permutation (l1 ++ a :: l2 ++ b :: l3) (l1 ++ b :: l2 ++ a :: l3).\nintros a b l1 l2 l3.\napply permutation_app_comp; auto.\nchange\n  (permutation ((a :: nil) ++ l2 ++ (b :: nil) ++ l3)\n     ((b :: nil) ++ l2 ++ (a :: nil) ++ l3)) in |- *.\nrepeat rewrite <- app_ass.\napply permutation_app_comp; auto.\napply permutation_trans with ((b :: nil) ++ (a :: nil) ++ l2); auto.\napply permutation_app_swap; auto.\nrepeat rewrite app_ass.\napply permutation_app_comp; auto.\napply permutation_app_swap; auto.\nQed.\n\n(**************************************\n   An element of a list can be put on top of the list to get a permutation\n   **************************************)\n\nTheorem in_permutation_ex :\n forall a l, In a l -> exists l1 : list A, permutation (a :: l1) l.\nintros a l; elim l; simpl in |- *; auto.\nintros H; case H; auto.\nintros a0 l0 H [H0| H0].\nexists l0; rewrite H0; auto.\ncase H; auto; intros l1 Hl1; exists (a0 :: l1).\napply permutation_trans with (a0 :: a :: l1); auto.\nQed.\n\n(**************************************\n   A permutation of a cons can be inverted\n   **************************************)\n\nLet permutation_cons_ex_aux :\n  forall (a : A) (l1 l2 : list A),\n  permutation l1 l2 ->\n  forall l11 l12 : list A,\n  l1 = l11 ++ a :: l12 ->\n  exists l3 : list A,\n    (exists l4 : list A,\n       l2 = l3 ++ a :: l4 /\\ permutation (l11 ++ l12) (l3 ++ l4)).\nintros a l1 l2 H; elim H; clear H l1 l2.\nintros l11 l12; case l11; simpl in |- *; intros; discriminate.\nintros a0 l1 l2 H H0 l11 l12; case l11; simpl in |- *.\nexists (nil (A:=A)); exists l1; simpl in |- *; split; auto.\ninjection H1; intros; subst; auto.\ninjection H1; intros H2 H3; rewrite <- H2; auto.\nintros a1 l111 H1.\ncase (H0 l111 l12); auto.\ninjection H1; auto.\nintros l3 (l4, (Hl1, Hl2)).\nexists (a0 :: l3); exists l4; split; simpl in |- *; auto.\ninjection H1; intros; subst; auto.\ninjection H1; intros H2 H3; rewrite H3; auto.\nintros a0 b l l11 l12; case l11; simpl in |- *.\ncase l12; try (intros; discriminate).\nintros a1 l0 H; exists (b :: nil); exists l0; simpl in |- *; split; auto.\ninjection H; intros; subst; auto.\ninjection H; intros H1 H2 H3; rewrite H2; auto.\nintros a1 l111; case l111; simpl in |- *.\nintros H; exists (nil (A:=A)); exists (a0 :: l12); simpl in |- *; split; auto.\ninjection H; intros; subst; auto.\ninjection H; intros H1 H2 H3; rewrite H3; auto.\nintros a2 H1111 H; exists (a2 :: a1 :: H1111); exists l12; simpl in |- *;\n split; auto.\ninjection H; intros; subst; auto.\nintros l1 l2 l3 H H0 H1 H2 l11 l12 H3.\ncase H0 with (1 := H3).\nintros l4 (l5, (Hl1, Hl2)).\ncase H2 with (1 := Hl1).\nintros l6 (l7, (Hl3, Hl4)).\nexists l6; exists l7; split; auto.\napply permutation_trans with (1 := Hl2); auto.\nQed.\n\nTheorem permutation_cons_ex :\n forall (a : A) (l1 l2 : list A),\n permutation (a :: l1) l2 ->\n exists l3 : list A,\n   (exists l4 : list A, l2 = l3 ++ a :: l4 /\\ permutation l1 (l3 ++ l4)).\nintros a l1 l2 H.\napply (permutation_cons_ex_aux a (a :: l1) l2 H nil l1); simpl in |- *; auto.\nQed.\n\n(**************************************\n   A permutation can be simply inverted if the two list starts with a cons\n   **************************************)\n\nTheorem permutation_inv :\n forall (a : A) (l1 l2 : list A),\n permutation (a :: l1) (a :: l2) -> permutation l1 l2.\nintros a l1 l2 H; case permutation_cons_ex with (1 := H).\nintros l3 (l4, (Hl1, Hl2)).\napply permutation_trans with (1 := Hl2).\ngeneralize Hl1; case l3; simpl in |- *; auto.\nintros H1; injection H1; intros H2; rewrite H2; auto.\nintros a0 l5 H1; injection H1; intros H2 H3; rewrite H2; rewrite H3; auto.\napply permutation_trans with (a0 :: l4 ++ l5); auto.\napply permutation_skip; apply permutation_app_swap.\napply (permutation_app_swap (a0 :: l4) l5).\nQed.\n\n(**************************************\n   Take a list and return tle list of all pairs of an element of the\n   list and the remaining list\n   **************************************)\n\nFixpoint split_one (l : list A) : list (A * list A) :=\n  match l with\n  | nil => nil (A:=A * list A)\n  | a :: l1 =>\n      (a, l1)\n      :: map (fun p : A * list A => (fst p, a :: snd p)) (split_one l1)\n  end.\n\n(**************************************\n   The pairs of the list are a permutation\n   **************************************)\n\nTheorem split_one_permutation :\n forall (a : A) (l1 l2 : list A),\n In (a, l1) (split_one l2) -> permutation (a :: l1) l2.\nintros a l1 l2; generalize a l1; elim l2; clear a l1 l2; simpl in |- *; auto.\nintros a l1 H1; case H1.\nintros a l H a0 l1 [H0| H0].\ninjection H0; intros H1 H2; rewrite H2; rewrite H1; auto.\ngeneralize H H0; elim (split_one l); simpl in |- *; auto.\nintros H1 H2; case H2.\nintros a1 l0 H1 H2 [H3| H3]; auto.\ninjection H3; intros H4 H5; (rewrite <- H4; rewrite <- H5).\napply permutation_trans with (a :: fst a1 :: snd a1); auto.\napply permutation_skip.\napply H2; auto.\ncase a1; simpl in |- *; auto.\nQed.\n\n(**************************************\n   All elements of the list are there\n   **************************************)\n\nTheorem split_one_in_ex :\n forall (a : A) (l1 : list A),\n In a l1 -> exists l2 : list A, In (a, l2) (split_one l1).\nintros a l1; elim l1; simpl in |- *; auto.\nintros H; case H.\nintros a0 l H [H0| H0]; auto.\nexists l; left; subst; auto.\ncase H; auto.\nintros x H1; exists (a0 :: x); right; auto.\napply\n (in_map (fun p : A * list A => (fst p, a0 :: snd p)) (split_one l) (a, x));\n auto.\nQed.\n\n(**************************************\n   An auxillary function to generate all permutations\n   **************************************)\n\nFixpoint all_permutations_aux (l : list A) (n : nat) {struct n} :\n list (list A) :=\n  match n with\n  | O => nil :: nil\n  | S n1 =>\n      flat_map\n        (fun p : A * list A =>\n         map (cons (fst p)) (all_permutations_aux (snd p) n1)) (\n        split_one l)\n  end.\n(**************************************\n   Generate all the permutations\n   **************************************)\n\nDefinition all_permutations (l : list A) := all_permutations_aux l (length l).\n\n(**************************************\n   All the elements of the list are permutations\n   **************************************)\n\nLet all_permutations_aux_permutation :\n  forall (n : nat) (l1 l2 : list A),\n  n = length l2 -> In l1 (all_permutations_aux l2 n) -> permutation l1 l2.\nintros n; elim n; simpl in |- *; auto.\nintros l1 l2; case l2.\nsimpl in |- *; intros H0 [H1| H1].\nrewrite <- H1; auto.\ncase H1.\nsimpl in |- *; intros; discriminate.\nintros n0 H l1 l2 H0 H1.\ncase in_flat_map_ex with (1 := H1).\nclear H1; intros x; case x; clear x; intros a1 l3 (H1, H2).\ncase in_map_inv with (1 := H2).\nsimpl in |- *; intros y (H3, H4).\nrewrite H4; auto.\napply permutation_trans with (a1 :: l3); auto.\napply permutation_skip; auto.\napply H with (2 := H3).\napply eq_add_S.\napply trans_equal with (1 := H0).\nchange (length l2 = length (a1 :: l3)) in |- *.\napply permutation_length; auto.\napply permutation_sym; apply split_one_permutation; auto.\napply split_one_permutation; auto.\nQed.\n\nTheorem all_permutations_permutation :\n forall l1 l2 : list A, In l1 (all_permutations l2) -> permutation l1 l2.\nintros l1 l2 H; apply all_permutations_aux_permutation with (n := length l2);\n auto.\nQed.\n\n(**************************************\n   A permutation is in the list\n   **************************************)\n\nLet permutation_all_permutations_aux :\n  forall (n : nat) (l1 l2 : list A),\n  n = length l2 -> permutation l1 l2 -> In l1 (all_permutations_aux l2 n).\nintros n; elim n; simpl in |- *; auto.\nintros l1 l2; case l2.\nintros H H0; rewrite permutation_nil_inv with (1 := H0); auto with datatypes.\nsimpl in |- *; intros; discriminate.\nintros n0 H l1; case l1.\nintros l2 H0 H1;\n rewrite permutation_nil_inv with (1 := permutation_sym _ _ H1) in H0;\n discriminate.\nclear l1; intros a1 l1 l2 H1 H2.\ncase (split_one_in_ex a1 l2); auto.\napply permutation_in with (1 := H2); auto with datatypes.\nintros x H0.\napply in_flat_map with (b := (a1, x)); auto.\napply in_map; simpl in |- *.\napply H; auto.\napply eq_add_S.\napply trans_equal with (1 := H1).\nchange (length l2 = length (a1 :: x)) in |- *.\napply permutation_length; auto.\napply permutation_sym; apply split_one_permutation; auto.\napply permutation_inv with (a := a1).\napply permutation_trans with (1 := H2).\napply permutation_sym; apply split_one_permutation; auto.\nQed.\n\nTheorem permutation_all_permutations :\n forall l1 l2 : list A, permutation l1 l2 -> In l1 (all_permutations l2).\nintros l1 l2 H; unfold all_permutations in |- *;\n apply permutation_all_permutations_aux; auto.\nQed.\n\n(**************************************\n   Permutation is decidable\n   **************************************)\n\nDefinition permutation_dec :\n  (forall a b : A, {a = b} + {a <> b}) ->\n  forall l1 l2 : list A, {permutation l1 l2} + {~ permutation l1 l2}.\nintros H l1 l2.\ncase (In_dec (list_eq_dec H) l1 (all_permutations l2)).\nintros i; left; apply all_permutations_permutation; auto.\nintros i; right; contradict i; apply permutation_all_permutations; auto.\nDefined.\n\nEnd permutation.\n\n(**************************************\n   Hints\n   **************************************)\n\nGlobal Hint Constructors permutation : core.\nGlobal Hint Resolve permutation_refl : core.\nGlobal Hint Resolve permutation_app_comp : core.\nGlobal Hint Resolve permutation_app_swap : core.\n\n(**************************************\n   Implicits\n   **************************************)\n\nArguments permutation [A] _ _.\nArguments split_one [A] _.\nArguments all_permutations [A] _.\nArguments permutation_dec [A].\n\n(**************************************\n   Permutation is compatible with map\n   **************************************)\n\nTheorem permutation_map :\n forall (A B : Set) (f : A -> B) l1 l2,\n permutation l1 l2 -> permutation (map f l1) (map f l2).\nintros A B f l1 l2 H; elim H; simpl in |- *; auto.\nintros l0 l3 l4 H0 H1 H2 H3; apply permutation_trans with (2 := H3); auto.\nQed.\nGlobal Hint Resolve permutation_map : core.\n\n(**************************************\n  Permutation  of a map can be inverted\n  *************************************)\n\nLocal Definition permutation_map_ex_aux :\n  forall (A B : Set) (f : A -> B) l1 l2 l3,\n  permutation l1 l2 ->\n  l1 = map f l3 -> exists l4, permutation l4 l3 /\\ l2 = map f l4.\nintros A1 B1 f l1 l2 l3 H; generalize l3; elim H; clear H l1 l2 l3.\nintros l3; case l3; simpl in |- *; auto.\nintros H; exists (nil (A:=A1)); auto.\nintros; discriminate.\nintros a0 l1 l2 H H0 l3; case l3; simpl in |- *; auto.\nintros; discriminate.\nintros a1 l H1; case (H0 l); auto.\ninjection H1; auto.\nintros l5 (H2, H3); exists (a1 :: l5); split; simpl in |- *; auto.\ninjection H1; intros; subst; auto.\nintros a0 b l l3; case l3.\nintros; discriminate.\nintros a1 l0; case l0; simpl in |- *.\nintros; discriminate.\nintros a2 l1 H; exists (a2 :: a1 :: l1); split; simpl in |- *; auto.\ninjection H; intros; subst; auto.\nintros l1 l2 l3 H H0 H1 H2 l0 H3.\ncase H0 with (1 := H3); auto.\nintros l4 (HH1, HH2).\ncase H2 with (1 := HH2); auto.\nintros l5 (HH3, HH4); exists l5; split; auto.\napply permutation_trans with (1 := HH3); auto.\nQed.\n\nTheorem permutation_map_ex :\n forall (A B : Set) (f : A -> B) l1 l2,\n permutation (map f l1) l2 ->\n exists l3, permutation l3 l1 /\\ l2 = map f l3.\nintros A0 B f l1 l2 H; apply permutation_map_ex_aux with (l1 := map f l1);\n auto.\nQed.\n\n(**************************************\n   Permutation is compatible with flat_map\n **************************************)\n\nTheorem permutation_flat_map :\n forall (A B : Set) (f : A -> list B) l1 l2,\n permutation l1 l2 -> permutation (flat_map f l1) (flat_map f l2).\nintros A B f l1 l2 H; elim H; simpl in |- *; auto.\nintros a b l; auto.\nrepeat rewrite <- app_ass.\napply permutation_app_comp; auto.\nintros k3 l4 l5 H0 H1 H2 H3; apply permutation_trans with (1 := H1); auto.\nQed.\n", "meta": {"author": "thery", "repo": "coqprime", "sha": "431d7a66877cbe8688fc8864ef892369401440e1", "save_path": "github-repos/coq/thery-coqprime", "path": "github-repos/coq/thery-coqprime/coqprime-431d7a66877cbe8688fc8864ef892369401440e1/src/Coqprime/List/Permutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.724090479946484}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, hd_opt *)\n\nInductive natlist: Type:=\n|nil: natlist\n|cons: nat -> natlist -> natlist.\n\nNotation \"[]\" := nil.\nNotation \" x :: l\" := (cons x l).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nInductive natoption: Type :=\n|Some: nat -> natoption\n|None: natoption.\n\nDefinition hd_opt(l: natlist): natoption :=\nmatch l with\n|nil  => None\n|h::_ => Some h\nend.\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", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter5_Library_List/hd_opt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7240904798181936}}
{"text": "(* vectors *)\n\nSet Nested Proofs Allowed.\nSet Implicit Arguments.\n\nRequire Import Utf8 Arith.\nImport Init.Nat.\nImport List List.ListNotations.\n\nRequire Import Misc.\nRequire Import RingLike IterAdd.\n\nRecord vector T := mk_vect\n  { vect_list : list T }.\n\nDefinition vect_size {T} (v : vector T) := length (vect_list v).\n\nDefinition vect_el {T} {ro : ring_like_op T} (V : vector T) i :=\n  nth (i - 1) (vect_list V) 0%L.\n\nTheorem fold_vect_size {T} : ∀ (V : vector T),\n  length (vect_list V) = vect_size V.\nProof. easy. Qed.\n\nTheorem vector_eq : ∀ T {ro : ring_like_op T} (U V : vector T),\n  (∀ i, 1 ≤ i ≤ vect_size U → vect_el U i = vect_el V i)\n  → vect_size U = vect_size V\n  → U = V.\nProof.\nintros * Heq Huv.\ndestruct U as (lu).\ndestruct V as (lv).\ncbn in Heq, Huv; f_equal.\nrewrite (List_map_nth_seq _ 0%L); symmetry.\nrewrite (List_map_nth_seq _ 0%L); symmetry.\nrewrite <- Huv.\napply map_ext_in.\nintros i Hi; apply in_seq in Hi.\ndestruct Hi as (_, Hi); cbn in Hi.\nspecialize (Heq (S i)).\nrewrite Nat_sub_succ_1 in Heq.\napply Heq.\nsplit; [ now apply -> Nat.succ_le_mono | easy ].\nQed.\n\nSection a.\n\nContext {T : Type}.\nContext (ro : ring_like_op T).\nContext {rp : ring_like_prop T}.\n\nTheorem fold_vect_el : ∀ (V : vector T) i,\n  nth i (vect_list V) 0%L = vect_el V (S i).\nProof.\nintros.\nunfold vect_el.\nnow rewrite Nat_sub_succ_1.\nQed.\n\nDefinition vect_zero n : vector T := mk_vect (repeat 0%L n).\n\n(* addition, subtraction of vector *)\n\nDefinition vect_add (U V : vector T) :=\n  mk_vect (map2 rngl_add (vect_list U) (vect_list V)).\n\nDefinition vect_opp (V : vector T) :=\n  mk_vect (map rngl_opp (vect_list V)).\n\nDefinition vect_sub (U V : vector T) := vect_add U (vect_opp V).\n\n(* multiplication of a vector by a scalar *)\n\nDefinition vect_mul_scal_l s (V : vector T) :=\n  mk_vect (map (λ x, (s * x)%L) (vect_list V)).\n\n(* dot product *)\n\nDefinition vect_dot_mul (U V : vector T) :=\n  ∑ (t ∈ map2 rngl_mul (vect_list U) (vect_list V)), t.\nDefinition vect_dot_mul' (U V : vector T) :=\n  ∑ (i = 1, min (vect_size U) (vect_size V)),\n  vect_el U i * vect_el V i.\n\nTheorem vect_dot_mul_dot_mul' :\n  rngl_has_opp_or_subt = true →\n  ∀ U V,\n  vect_dot_mul U V = vect_dot_mul' U V.\nProof.\nintros Hos *.\nunfold vect_dot_mul, vect_dot_mul'.\ndestruct U as (lu).\ndestruct V as (lv).\ncbn.\nrevert lv.\ninduction lu as [| a]; intros. {\n  now cbn; rewrite rngl_summation_empty.\n}\ndestruct lv as [| b]. {\n  now cbn; rewrite rngl_summation_empty.\n}\ncbn - [ nth ].\nrewrite rngl_summation_shift with (s := 1). 2: {\n  split; [ easy | ].\n  now apply -> Nat.succ_le_mono.\n}\nrewrite Nat.sub_diag, Nat_sub_succ_1.\nrewrite rngl_summation_split_first; [ | easy ].\ndo 2 rewrite List_nth_0_cons.\nrewrite rngl_summation_list_cons.\nf_equal.\ndestruct (Nat.eq_dec (length lu) 0) as [Huz| Huz]. {\n  rewrite Huz; cbn - [ nth ].\n  apply length_zero_iff_nil in Huz; subst lu.\n  rewrite rngl_summation_empty; [ | easy ].\n  now rewrite map2_nil_l; unfold iter_list.\n}\ndestruct (Nat.eq_dec (length lv) 0) as [Hvz| Hvz]. {\n  rewrite Hvz; cbn - [ nth ].\n  apply length_zero_iff_nil in Hvz; subst lv.\n  rewrite Nat.min_r; [ | easy ].\n  rewrite rngl_summation_empty; [ | easy ].\n  now rewrite map2_nil_r; unfold iter_list.\n}\nerewrite rngl_summation_eq_compat. 2: {\n  intros i Hi.\n  rewrite <- Nat.add_sub_assoc; [ | easy ].\n  now do 2 rewrite List_nth_succ_cons.\n}\napply IHlu.\nQed.\n\nDefinition vect_squ_norm (V : vector T) := vect_dot_mul V V.\n\nDeclare Scope V_scope.\nDelimit Scope V_scope with V.\n\nArguments vect_dot_mul (U V)%V.\nArguments vector_eq {T}%type {ro} (U V)%V.\n\nNotation \"μ × V\" := (vect_mul_scal_l μ V) (at level 40) : V_scope.\nNotation \"≺ U , V ≻\" := (vect_dot_mul U V) (at level 35).\nNotation \"μ × V\" := (vect_mul_scal_l μ V) (at level 40) : V_scope.\n\nArguments vect_el {T}%type {ro} V%V i%nat.\nArguments vect_size {T}%type v%V.\n\nTheorem vect_mul_scal_l_mul_assoc : ∀ (a b : T) (V : vector T),\n  (a × (b × V))%V = ((a * b)%L × V)%V.\nProof.\nintros.\nunfold vect_mul_scal_l.\nf_equal; cbn.\nrewrite map_map.\napply map_ext_in.\nintros x Hx.\napply rngl_mul_assoc.\nQed.\n\nTheorem vect_mul_scal_reg_r :\n  rngl_has_inv_or_quot = true →\n  rngl_has_eqb = true →\n  ∀ (V : vector T) a b,\n  V ≠ vect_zero (vect_size V)\n  → (a × V = b × V)%V\n  → a = b.\nProof.\nintros Hii Heq * Hvz Habv.\nunfold vect_mul_scal_l in Habv.\ninjection Habv; clear Habv; intros Habv.\nspecialize (ext_in_map Habv) as H1.\ncbn in H1.\nremember (rngl_eqb a b) as ab eqn:Hab; symmetry in Hab.\ndestruct ab; [ now apply rngl_eqb_eq | ].\napply (rngl_eqb_neq Heq) in Hab.\nexfalso; apply Hvz; clear Hvz.\napply vector_eq; [ | now cbn; rewrite repeat_length ].\nintros i Hi; cbn.\nrewrite nth_repeat.\nspecialize (H1 (vect_el V i)) as H2.\nassert (H : vect_el V i ∈ vect_list V). {\n  unfold vect_el.\n  apply nth_In.\n  rewrite fold_vect_size.\n  now apply Nat_1_le_sub_lt.\n}\nspecialize (H2 H); clear H.\nremember (rngl_eqb (vect_el V i) 0%L) as vz eqn:Hvz; symmetry in Hvz.\ndestruct vz; [ now apply rngl_eqb_eq | ].\napply (rngl_eqb_neq Heq) in Hvz.\nnow apply rngl_mul_cancel_r in H2.\nQed.\n\nTheorem vect_mul_scal_size : ∀ a V, vect_size (a × V) = vect_size V.\nProof. now intros; cbn; rewrite map_length. Qed.\n\nTheorem vect_dot_mul_scal_mul_comm :\n  rngl_has_opp_or_subt = true →\n  rngl_mul_is_comm = true →\n  ∀ (a : T) (U V : vector T),\n  ≺ U, a × V ≻ = (a * ≺ U, V ≻)%L.\nProof.\nintros Hom Hic *.\nunfold vect_dot_mul.\nrewrite rngl_mul_summation_list_distr_l; [ | easy ].\nunfold \"×\"; cbn.\nunfold iter_list.\nrewrite map2_map_r.\nrewrite List_fold_left_map2.\nrewrite List_fold_left_map2.\napply List_fold_left_ext_in.\nintros * Hb.\nf_equal.\ndo 2 rewrite rngl_mul_assoc.\nf_equal.\nnow apply rngl_mul_comm.\nQed.\n\nTheorem vect_scal_mul_dot_mul_comm :\n  rngl_has_opp_or_subt = true →\n  ∀ (a : T) (U V : vector T),\n  ≺ a × U, V ≻ = (a * ≺ U, V ≻)%L.\nProof.\nintros Hom *.\nunfold vect_dot_mul; cbn.\nrewrite rngl_mul_summation_list_distr_l; [ | easy ].\nunfold \"×\"; cbn.\nunfold iter_list.\nrewrite map2_map_l.\nrewrite List_fold_left_map2.\nrewrite List_fold_left_map2.\napply List_fold_left_ext_in.\nintros * Hb.\nf_equal; symmetry.\napply rngl_mul_assoc.\nQed.\n\nTheorem vect_eq_dec :\n  rngl_has_eqb = true →\n  ∀ (U V : vector T), {U = V} + {U ≠ V}.\nProof.\nintros Heq *.\ndestruct U as (lu).\ndestruct V as (lv).\nremember (list_eqv rngl_eqb lu lv) as uv eqn:Huv.\nsymmetry in Huv.\ndestruct uv. {\n  left; f_equal.\n  apply list_eqb_eq in Huv; [ easy | ].\n  unfold equality.\n  apply (rngl_eqb_eq Heq).\n} {\n  right; f_equal.\n  apply list_eqb_neq in Huv. {\n    intros H; apply Huv; clear Huv.\n    now injection H.\n  }\n  unfold equality.\n  apply (rngl_eqb_eq Heq).\n}\nQed.\n\nEnd a.\n\nDeclare Scope V_scope.\nDelimit Scope V_scope with V.\n\nArguments vect_add {T}%type {ro} (U V)%V.\nArguments vect_sub {T ro} U%V V%V.\nArguments vect_opp {T ro} V%V.\nArguments vect_mul_scal_l {T ro} s%L V%V.\nArguments vect_mul_scal_reg_r {T}%type {ro rp} Hde Hii V%V (a b)%L.\nArguments vect_zero {T ro} n%nat.\nArguments vect_dot_mul {T}%type {ro} (U V)%V.\nArguments vect_dot_mul' {T}%type {ro} (U V)%V.\nArguments vect_dot_mul_dot_mul' {T}%type {ro rp} Hop (U V)%V.\nArguments vect_dot_mul_scal_mul_comm {T}%type {ro rp} Hom Hic a%L (U V)%V.\nArguments vect_scal_mul_dot_mul_comm {T}%type {ro rp} Hom a%L (U V)%V.\nArguments vect_eq_dec {T}%type {ro rp} Hde U%V V%V.\nArguments vect_el {T}%type {ro} V%V i%nat.\nArguments vect_size {T}%type v%V.\nArguments vect_squ_norm {T}%type {ro} V%V.\nArguments vector_eq {T}%type {ro} (U V)%V.\n\nNotation \"U + V\" := (vect_add U V) : V_scope.\nNotation \"U - V\" := (vect_sub U V) : V_scope.\nNotation \"μ × V\" := (vect_mul_scal_l μ V) (at level 40) : V_scope.\nNotation \"≺ U , V ≻\" := (vect_dot_mul U V) (at level 35).\nNotation \"- V\" := (vect_opp V) : V_scope.\n", "meta": {"author": "roglo", "repo": "coq_sensitivity", "sha": "398291aa86a447f0f35b4918043e94d9eb703c12", "save_path": "github-repos/coq/roglo-coq_sensitivity", "path": "github-repos/coq/roglo-coq_sensitivity/coq_sensitivity-398291aa86a447f0f35b4918043e94d9eb703c12/main/MyVector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7240696819030028}}
{"text": "\n(* ================================================================== *)\n(* ==================== Programming and proving ===================== *)\n(* ================================================================== *)\n\nRequire Import ZArith.\n\nRequire Import List.\n\n\n\nSet Implicit Arguments.\n\nFixpoint elem (a:Z) (l:list Z) {struct l} : bool :=   (* !!!!!!!!!!! *)\n    match l with\n      | nil => false\n      | cons x xs => if Z.eq_dec x a then true else (elem a xs)\n    end.\n\n\nProposition elem_corr : forall (a:Z) (l1 l2:list Z),\n                  elem a (app l1 l2) = orb (elem a l1) (elem a l2).\nProof.\n  induction l1.\n  - intros. simpl. reflexivity.\n  - intros. simpl.\n    elim (Z.eq_dec a0 a).     \n    +  SearchAbout orb. \n      rewrite Bool.orb_true_l.\n      trivial.\n    + auto.\nQed.\n\n\n(* Exercise: *)\nLemma ex : forall (a:Z) (l1 l2:list Z), elem a (app l1 (cons a l2)) = true.\nProof.\n  intros. rewrite elem_corr.\n SearchAbout \"orb\". \n  apply Bool.orb_true_iff. right. simpl.\n  elim (Z.eq_dec a a); auto.        \nQed.\n  \n(* ================================================================== *)\n(* ======================== Partiality ============================== *)\n\n(* defining the function head *)\n\nDefinition head (A:Type) (l:list A) : l<>nil -> A.\n(* \"refine term\" tactic applies to any goal. It behaves like exact with\na big difference: the user can leave some holes (denoted by _ or (_:type)) \nin the term. \nrefine will generate as many subgoals as there are holes in the term. *) \n  refine (\n  match l as l' return l'<>nil -> A with\n  | nil => fun H => _\n  | cons x xs => fun H => x\n  end ).  \n  elimtype False.         (* cut False; intro H1; elim H1; clear H1. *)\n  apply H; reflexivity.  (* elim H. reflexivity. *)\nDefined.\n\nPrint  head.\nPrint Implicit head.\n\n\n(* head precondition *)\nDefinition headPre (A:Type) (l:list A) : Prop := l<>nil.\n\n(* the specification of head *) \nInductive headRel (A:Type) (x:A) : list A -> Prop :=\n  headIntro : forall l, headRel x (cons x l).\n\nPrint Implicit headRel.\n\n\n(* we can prove the correctness of head w.r.t. its specification *)\nLemma head_correct : forall (A:Type) (l:list A) (p:headPre l), headRel (head  p) l.\nProof.\n  destruct l.\n  - intro H; elim H; reflexivity.\n  - intros;  destruct l; [simpl; constructor | simpl; constructor].\n    (* change de proof script so that you can see effect each tactic *)\nQed.\n\n\nPrint head.\nCheck head.\n\n\n(* ================================================================== *)\n(* ==================== Program Extraction ========================== *)\n\nRequire Extraction.  (* the extraction framework must be loaded explicitly *)\n\n\n(* we can convert to Haskell the function head defined *)\nExtraction Language Haskell.\n\nExtraction head.\n\nExtraction False_rect.\nExtraction Inline False_rect.  (* will make the code more readable *)\nExtraction head.\n\nRecursive Extraction head.\nExtraction \"exemplo1\" head.\n\nExtract Inductive list => \"[]\" [ \"[]\" \"(:)\" ].\n\nRecursive Extraction head.\nExtraction \"exemplo2\" head.\n\n(* We have just followed the \"weak specification\" approach: \n   we defined the function and add, as a companion lemma, that the function \n   satisfies its specification. \n*)\n\n\n(* ================================================================== *)\n\n(* Instead of this approach, we can give a \"strong specification\" of a\n   function  (using specification types), and extract the function from \n   its proof (the prove that the specification is inhabited).\n*)\n\n(* An inductive relation \"x is the last element of list l\" *)\nInductive Last (A:Type) (x:A) : list A -> Prop :=\n| last_base : Last x (cons x nil)\n| last_step : forall l y, Last x l -> Last x (cons y l).\n\n \nTheorem last_correct : forall (A:Type) (l:list A), l<>nil -> { x:A | Last x l }.\nProof.\n  induction l.\n  - intro H. elim H. reflexivity.\n  - intros. destruct l.\n    + exists a. constructor.\n    + elim IHl.\n      * intros. exists x. constructor. assumption.\n      * discriminate.\nQed.\n\n\n\nRecursive Extraction last_correct.\n\n\nExtraction Inline False_rect.\nExtraction Inline sig_rect.\nExtraction Inline list_rect.\n\nRecursive Extraction last_correct.\n\n\n\n(* ================================================================== *)\n\n(* Following this alternative approach we can give a \"strong specification\" of \n   function head (using specification types), and extract the function from \n   its proof (the prove that the specification is inhabited).\n*)\n\n(* Exercise: built an alternative definition of function head called “head corr” \n   based on the strong specification mechanism *)\n\n\n\n\n(* ================================================================== *)\n(* ======================= Sorting a list =========================== *)\n\nOpen Scope Z_scope. \n\nInductive Sorted : list Z -> Prop := \n  | sorted0 : Sorted nil \n  | sorted1 : forall z:Z, Sorted (z :: nil) \n  | sorted2 : forall (z1 z2:Z) (l:list Z), \n        z1 <= z2 -> Sorted (z2 :: l) -> Sorted (z1 :: z2 :: l). \n\n\nFixpoint count (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%nat     (* %nat to force the interpretation in nat, since have we open Z_scope *)\n  | (z' :: l') =>\n      match Z.eq_dec z z' with\n      | left _ => S (count z l')\n      | right _ => count z l'\n      end\n  end.\n\n\nDefinition Perm (l1 l2:list Z) : Prop :=\n                                 forall z, count z l1 = count z l2.\n\n\n(*\n Exercise: prove that Perm is an equivalence relation (i.e. is reflexive, symmetric and transitive)\n*)\n\nLemma Perm_reflex : forall l:list Z, Perm l l.\nProof. \n  unfold Perm.\n  intros.\n  reflexivity.\nQed.\n\nLemma Perm_sym : forall l1 l2, Perm l1 l2 -> Perm l2 l1.\nProof. \n  unfold Perm.\n  intros.\n  symmetry.\n  generalize z. \n  assumption.\nQed.\n\n\nLemma Perm_trans : forall l1 l2 l3, Perm l1 l2 -> Perm l2 l3 -> Perm l1 l3.\nProof. \n  unfold Perm.\n  induction l1.\n  intros.\n  - rewrite H. apply H0.\n  - intros. rewrite H. apply H0.\nQed.\n\n\n(*  Exercise: prove the following lemmas: *)\n\n\nLemma Perm_cons : forall a l1 l2, Perm l1 l2 -> Perm (a::l1) (a::l2).\nProof.\n  unfold Perm.\n  intros.\n  simpl.\n  elim Z.eq_dec.\n    - rewrite H. trivial.\n    - intros. generalize z. apply H.\nQed.\n\n\nLemma Perm_cons_cons : forall x y l, Perm (x::y::l) (y::x::l).\nProof.\n  unfold Perm.\n  intros.\n  simpl.\n  elim  Z.eq_dec.\n  - intros. elim Z.eq_dec.\n    + trivial.\n    + trivial.\n  - elim  Z.eq_dec.\n    + trivial.\n    + trivial.\nQed.\n\n\n\n\nFixpoint insert (x:Z) (l:list Z) {struct l} : list Z :=\n  match l with\n    nil => cons x (@nil Z)\n  | cons h t =>\n        match Z_lt_ge_dec x h with\n          left _ => cons x (cons h t)\n        | right _ => cons h (insert x t)\n        end\n  end.\n\nFixpoint isort (l:list Z) : list Z :=\n  match l with\n    nil => nil\n  | cons h t => insert h (isort t)\n  end.\n\nPrint isort.\n\n\n(* some  usefull lemmas about count *)\n\nLemma count_insert_eq : forall x l,\n                       count x (insert x l) = S (count x l).\nProof.\n  induction l.\n  - simpl. destruct (Z.eq_dec x x).\n    + reflexivity.\n    + destruct n. reflexivity.\n  - simpl insert. destruct (Z_lt_ge_dec x a).\n    + simpl. destruct (Z.eq_dec x x).\n      * reflexivity.\n      * easy.\n    + simpl. destruct (Z.eq_dec x a).\n      * rewrite IHl. reflexivity.\n      * assumption.\nQed.\n\nLemma count_cons_diff : forall z x l, z <> x -> count z l = count z  (x :: l).\nProof.\n  intros. induction l.\n  - simpl. destruct (Z.eq_dec z x); easy.\n  - simpl. destruct (Z.eq_dec z a).\n    + destruct (Z.eq_dec z x); easy.\n    + destruct (Z.eq_dec z x); easy.\nQed.\n\n \nLemma count_insert_diff : forall z x l, z <> x -> count z l = count z (insert x l).\nProof.\n  intros. induction l.\n  - simpl. destruct (Z.eq_dec z x); easy.\n  - simpl insert. destruct (Z_lt_ge_dec x a).\n    + simpl. destruct (Z.eq_dec z x); try easy.\n    + simpl. destruct (Z.eq_dec z a); try easy.\n      apply f_equal. apply IHl.\nQed.    \n\n\n(* the two auxiliary lemmas *)\n\nLemma insert_Perm : forall x l, Perm (x::l) (insert x l).\nProof.\n  unfold Perm; induction l.\n - simpl. reflexivity.\n - simpl insert. destruct (Z_lt_ge_dec x a).\n   + reflexivity.\n   + intros. rewrite Perm_cons_cons.\n     destruct (Z.eq_dec z a).\n     * simpl. destruct (Z.eq_dec z a).\n       -- destruct (Z.eq_dec z x). \n          ++ apply f_equal. rewrite e1. rewrite count_insert_eq. reflexivity.\n          ++ apply f_equal. apply count_insert_diff. assumption.\n       -- destruct (Z.eq_dec z x).\n          ++ destruct n. assumption.\n          ++ destruct n. assumption.\n     * simpl. destruct (Z.eq_dec z a).\n       -- destruct (Z.eq_dec z x); easy.\n       -- destruct (Z.eq_dec z x). \n          ++ rewrite e. rewrite count_insert_eq. reflexivity.\n          ++ rewrite <- count_insert_diff; [reflexivity|assumption].\nQed.\n\n\n\nLemma insert_Sorted : forall x l, Sorted l -> Sorted (insert x l).\nProof.\n  - intros x l H; elim H; simpl. \n    + constructor.\n    + intro z; elim (Z_lt_ge_dec x z); intros.\n      * constructor.\n        auto with zarith. constructor.\n      * constructor.\n        -- auto with zarith.\n        -- constructor.\n    + intros z1 z2 l0 H0 H1.\n      elim (Z_lt_ge_dec x z2); elim (Z_lt_ge_dec x z1).\n      * intros. constructor.\n        -- omega. (* auto with zarith.*)\n        -- constructor.\n           ++ omega.\n           ++ assumption.  \n      * intros. constructor.\n        -- omega.\n        -- assumption.\n      * intros. constructor.\n        -- omega.\n        -- constructor; [omega|assumption].\n      * intros. constructor; [omega|assumption].\nQed.\n\n\n(* the proof that isort is correct *)\nTheorem isort_correct : forall (l l':list Z), l'=isort l -> Perm l l' /\\ Sorted l'.\nProof.\n  induction l; intros.\n  - unfold Perm; rewrite H; split; auto. simpl. constructor.\n  - simpl in H.\n    rewrite H. (* ??????????? *) \n    elim (IHl (isort l)); intros; split.\n    + apply Perm_trans with (a::isort l).\n      * unfold Perm. intro z. simpl. elim (Z.eq_dec z a).\n        -- intros. elim H0; reflexivity.   (* auto with zarith. *)\n        -- auto with zarith.   (* intros. elim H0. reflexivity. *)\n      * apply insert_Perm.\n    + apply insert_Sorted. assumption.\nQed.\n\n\n(* EXTRACTION *)\n(* using specification types *)\nDefinition inssort : forall (l:list Z), { l' | Perm l l' & Sorted l' }.\nProof.\n  induction l.\n  - exists nil. constructor. constructor.\n  - elim IHl. intros. exists (insert a x).\n(* FILL IN HERE *) \n    + apply Perm_trans with (a::x).\n      * apply Perm_cons. assumption.\n      * apply insert_Perm.  \n    + apply insert_Sorted. assumption.\nDefined.\n\n\nExtraction Language Haskell.\nRecursive Extraction inssort.\n\nExtraction Inline list_rec.\nExtraction Inline list_rect.\nExtraction Inline sig2_rec.\nExtraction Inline sig2_rect.\n\nExtraction inssort.\nRecursive Extraction inssort.\nExtraction \"exemplo4\"inssort.\n\n\n(* ================================================================== *)\n(* =================== Non-structural recursion ===================== *)\n\nClose Scope Z_scope.\n\nRequire Import Recdef. (* because of Function *)\n\n\nFunction div (p:nat*nat) {measure fst} : nat*nat :=\n  match p with\n  | (_,0) => (0,0)\n  | (a,b) => if le_lt_dec b a\n             then let (x,y):=div (a-b,b) in (1+x,y)\n             else (0,a)\n  end.\nProof.\n intros. simpl. omega.\nQed.\n\n\n\n(* Exercise  *)\nFunction merge (p:list Z*list Z)\n{measure (fun p=>(length (fst p))+(length (snd p)))} : list Z :=\n  match p with\n  | (nil,l) => l\n  | (l,nil) => l\n  | (x::xs,y::ys) => if Z_lt_ge_dec x y\n                     then x::(merge (xs,y::ys))\n                     else y::(merge (x::xs,ys))\n  end.\n  Admitted.\n  \nTheorem merge_correct_sorted : forall l1 l2 :list Z, Sorted l1 /\\ Sorted l2 -> Sorted (merge(l1, l2)).\n  Admitted.\n\nTheorem merge_correct_permuted : forall l1 l2:list Z, Perm (l1++l2) (merge (l1 ,l2)).\n  Admitted.\n\n\n(* ========== Euclidean division correction =========== *)\n\nDefinition divRel (args:nat*nat) (res:nat*nat) : Prop := \n          let (n,d):=args in let (q,r):=res in q*d+r=n /\\ r<d. \n\nDefinition divPre (args:nat*nat) : Prop := (snd args)<>0.\n\n\nTheorem div_correct : forall (p:nat*nat),  divPre p -> divRel p (div p). \nProof. \n  unfold divPre, divRel. \n  intro p. \n  (* we make use of the specialised induction principle to conduct the proof... *) \n  functional induction (div p); simpl. \n  - intro H; elim H; reflexivity. \n  - (* a first trick: we expand (div (a-b,b)) in order to get rid of the let (q,r)=... *) \n    replace (div (a-b,b)) with (fst (div (a-b,b)),snd (div (a-b,b))) in IHp0. \n    + simpl in *. intro H; elim (IHp0 H); intros. split. \n      * (* again a similar trick: we expand \"x\" and \"y0\" in order to use an hypothesis *) \n        change (b + (fst (x,y0)) * b + (snd (x,y0)) = a). \n        rewrite <- e1. omega. \n      * (* and again... *) \n        change (snd (x,y0)<b); rewrite <- e1; assumption. \n    + symmetry; apply surjective_pairing. \n  - auto. \nQed. \n\n(* Exercício 4.3 (a)*)\n\nPrint length.\n\nLemma correct_ln : forall l:list Z, {x : nat | length l = x}.\n  Proof. \n  intros. induction l.\n  - simpl. exists 0. reflexivity.\n  - simpl. inversion IHl. exists (S x). rewrite H. reflexivity.\n  Qed.\n\nExtraction \"length\" correct_ln.\n  \n(* Exercício 4.3 (b)*)\n  \nFunction sum_pair (l:list (nat*nat)) : nat :=\n  match l with\n  | nil => 0\n  | (_,y)::t => y + sum_pair t\n  end.\n\nLemma correct_sum_pair : forall l:list (nat*nat), {x : nat | sum_pair l = x}.\n  Proof. \n  intros.\n  induction l.\n    - exists 0. simpl. auto.\n    - simpl. inversion IHl. elim a. intros. exists (b+x). auto.\n  Qed.\n\nRecursive Extraction correct_sum_pair.\n\nExtraction Inline prod_rec.\nExtraction Inline prod_rect.\nExtraction \"sum_pair\" correct_sum_pair.\n\n", "meta": {"author": "sir-onze", "repo": "Formal-Verification", "sha": "d55362a3c0f3e760d68b7e95b99d0a8b84d688da", "save_path": "github-repos/coq/sir-onze-Formal-Verification", "path": "github-repos/coq/sir-onze-Formal-Verification/Formal-Verification-d55362a3c0f3e760d68b7e95b99d0a8b84d688da/coq1/tpc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7240696799347264}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\nRequire Export Cbase.\nRequire Import Omega.\n\nOpen Scope C_scope.\n\n(** * Power definition on C *)\n\nFixpoint Cpow (z : C) (n : nat) {struct n} : C  :=\nmatch n with\n| 0%nat => 1\n| S m => z * (Cpow z m)\nend.\n\nInfix \"^\" := Cpow : C_scope.\n\n(** Rewrite lemmas on Cpow *)\n\nLemma Cpow_0 : forall z, z ^ 0 = 1. \nProof.\nauto with complex.\nQed.\n\nLemma C0_pow : forall n, (0 < n)%nat -> 0 ^ n = 0.\nProof.\nintros n n_lb ; induction n.\n inversion n_lb.\n simpl.\n destruct (0 ^ n) ; CusingR_f.\nQed.\n\nLemma Cpow_S : forall (z : C) (n : nat), z ^ (S n) = z ^ n * z.\nProof.\nintros. simpl. intuition.\nQed.\n\nLemma Cpow_add : forall (z : C) (n m : nat), z ^ (n + m) = z ^ n * z ^ m.\nProof.\nintros z n m.\ninduction n.\n auto with complex.\n replace (z ^ (S n + m)%nat) with (z * z ^ (n+m)%nat).\n  rewrite IHn. replace (z ^ S n) with (z * (z ^ n)).\n   auto with complex.\n  destruct n ; simpl ; auto with complex.\n replace (S n + m)%nat with (S (n + m))%nat.\n  destruct n; destruct m ; simpl ; auto with complex.\n  simpl ; reflexivity.\nQed.\n\nLemma Cpow_mul : forall z n m, z ^ (n * m) = (z ^ n) ^ m.\nProof.\nintros z n m ; induction m.\n rewrite mult_0_r ; reflexivity.\n simpl ; rewrite <- IHm ; rewrite <- Cpow_add ;\n replace (n * S m)%nat with (n + n * m)%nat by ring ; reflexivity.\nQed.\n\nLemma Cpow_mul_distr_l : forall z1 z2 n, (z1 * z2) ^ n = z1 ^ n * z2 ^ n.\nProof.\nintros z1 z2 n; induction n.\n  simpl; CusingR_f.\n  repeat rewrite Cpow_S; rewrite IHn.\n  rewrite Cmult_assoc.\n  rewrite <- (Cmult_assoc (z2 ^ n) z1 z2).\n  rewrite (Cmult_comm (z2 ^ n) z1).\n  repeat rewrite Cmult_assoc.\n  reflexivity.\nQed.\n\nLemma IRC_pow_compat : forall x n, IRC x ^ n = IRC (x ^ n).\nProof.\nintros x n ; induction n.\n reflexivity.\n simpl ; rewrite IHn.\n CusingR_f.\nQed.\t", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/rls/rls1/Complex/Cpow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.8688267847293731, "lm_q1q2_score": 0.7240147323772599}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import ListSet.\n\nInductive Ty : Set := \n| Bas : nat -> Ty\n| Arr : Ty -> Ty -> Ty.\nNotation \"T ⇒ S\" := (Arr T S) (at level 30, right associativity).\n\nInductive Term : Set := \n| v : nat -> Term \n| ƛ : Ty -> Term -> Term\n| app : Term -> Term -> Term.\nNotation \"t · s\" := (app t s) (at level 20, left associativity).\n\nFixpoint Free (n : nat) (A : Set) : Set := \n  match n with \n    | O => A\n    | S n' => Term -> Free n' A\n  end.\n\nNotation \"[]\" := nil.\nNotation \"[ x ]\" := (cons x nil).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) .. ).\n\nFixpoint idx (A : Set) (n : nat) (G : list A) : option A := \n  match G with \n    | [] => None\n    | (x::t) => match n with \n                  | O => Some x \n                  | S n' => idx A n' t\n                end\n  end.\nImplicit Arguments idx [A].\n\nDefinition Ctx := list Ty.\n\n(* Note : is \\colon, using TeX mode, and not : *)\nReserved Notation \"Γ ⊢ t @ A\" (at level 70, no associativity).\nInductive Derivation : Ctx -> Term -> Ty -> Set := \n| VarIntro : forall Γ n A, \n  idx n Γ = Some A -> \n  Γ ⊢ (v n) @ A\n| ImpIntro : forall Γ t A B,\n  A::Γ ⊢ t @ B ->\n  Γ ⊢ ƛ A t @ A ⇒ B\n| ImpElim : forall Γ f t A B, \n  Γ ⊢ f @ A ⇒ B -> \n  Γ ⊢ t @ A -> \n  Γ ⊢ f · t @ B\n where \"Γ ⊢ r @ A \" := (Derivation Γ r A) : type_scope.\n\nHint Constructors Derivation : derivation.\n\nFixpoint shiftat (d : nat) (x : Term) {struct x} : Term := \n  match x with\n    | v m => if le_lt_dec d m then v (S m) else v m\n    | ƛ A t => ƛ A (shiftat (S d) t)\n    | r · s => (shiftat d r) · (shiftat d s)\n  end.\nDefinition shift := shiftat 0.\n\nDefinition sub : forall (t : Term) (n : nat) (u : Term), Term.\nProof.\n  refine \n    (fix sub (t : Term) (n : nat) (u : Term) := \n      match t with \n        | v m => match le_lt_dec n m with \n                   | left p => \n                     match eq_nat_dec n m with \n                       | left _ => u \n                       | right p' => \n                         (match m as m' return (m = m' -> Term) with\n                            | 0 => (fun p'' => False_rec _ _ )\n                            | S m' => (fun _ => v m')\n                          end) (refl_equal m)\n                     end\n                   | right _ => v m\n                 end\n        | ƛ A t => ƛ A (sub t (S n) (shift u))\n        | r · s => (sub r n u) · (sub s n u)\n      end) ; subst ; auto. \n  destruct n. apply le_n_O_eq in p. apply p'. reflexivity.\n  inversion p.\nDefined.\n\nInductive Ev : Term -> Term -> Prop := \n| ev_app : forall r s t, Ev r s -> Ev (r · t) (s · t)\n| ev_beta : forall r s A, Ev ((ƛ A r) · s) (sub r 0 s).\n\nInductive Value : Term -> Prop := \n| Value_lam : forall A r, Value (ƛ A r).\n\nRequire Import Relations.\n\nNotation \"r ↝ s\" := (Ev r s) (at level 40, no associativity).\nDefinition Evplus := clos_trans Term Ev.\nNotation \"r ↝⁺ s\" := (Evplus r s) (at level 40, no associativity). \nDefinition Evstar := clos_refl_trans Term Ev.\nNotation \"r ↝* s\" := (Evstar r s) (at level 40, no associativity). \nNotation \"r ⇓ s\" := (r ↝* s /\\ Value s) (at level 40, no associativity). \nNotation \"t ⇓\" := (exists s, t ⇓ s) (at level 40, no associativity). \n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/ApplicativeBisim/Lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7240084373854327}}
{"text": "Require Import String.\nRequire Import Ascii.\nRequire Import NArith.\n\n(* Binary numbers. The operations assume little-endianness,\n   but this can also be used as a big-endian representation. *)\nInductive binary : Type :=\n| b0 : binary -> binary\n| b1 : binary -> binary\n| b_ : binary (* End *)\n.\n\nFixpoint zeroes (d : nat) : binary :=\n  match d with\n  | O => b_\n  | S d => b0 (zeroes d)\n  end.\n\nFixpoint positive_to_binary (d : nat) (n : positive) :=\n  match n, d with\n  | xI n, S d => b1 (positive_to_binary d n)\n  | xO n, S d => b0 (positive_to_binary d n)\n  | xH, _ => b1 (zeroes d)\n  | _, O => b_\n  end.\n\nDefinition N_to_binary (d : nat) (n : N) :=\n  match n with\n  | N0 => zeroes d\n  | Npos n => positive_to_binary d n\n  end.\n\nFixpoint binary_to_N (z : binary) :=\n  match z with\n  | b_ => 0%N\n  | b1 z => N.succ_double (binary_to_N z)\n  | b0 z => N.double (binary_to_N z)\n  end.\n    \nExample binary_from_to : (binary_to_N (N_to_binary 64 10) = 10)%N.\nProof. reflexivity. Qed.\n\nFixpoint length_binary (z : binary) : nat :=\n  match z with\n  | b0 z | b1 z => S (length_binary z)\n  | b_ => O\n  end.\n\nFixpoint rev' (y z : binary) : binary :=\n  match z with\n  | b0 z => rev' (b0 y) z\n  | b1 z => rev' (b1 y) z\n  | b_ => y\n  end.\n\n(* big-endian <-> little-endian *)\nDefinition rev : binary -> binary := rev' b_.\n\n(* Bitwise xor. The second operand is\n   extended/truncated to the length of the first one. *)\nFixpoint xor (z1 z2 : binary) :=\n  match z1, z2 with\n  | b0 z1, b0 z2 | b1 z1, b1 z2 => b0 (xor z1 z2)\n  | b0 z1, b1 z2 | b1 z1, b0 z2 => b1 (xor z1 z2)\n  | _, _ => z1\n  end.\n\nLemma xor_length :\n  forall z1 z2, length_binary (xor z1 z2) = length_binary z1.\nProof.\n  induction z1; destruct z2; simpl; try f_equal; auto.\nQed.\n\nFixpoint shiftr (n : nat) (z : binary) :=\n  match n, z with\n  | S n, (b0 z | b1 z) => shiftr n z\n  | _, _ => z\n  end.\n\nExample shiftr_test :\n  shiftr 3 (N_to_binary 10 30) = (N_to_binary 7 3%N).\nProof. reflexivity. Qed.\n\nLemma shiftr_length :\n  forall n z, length_binary (shiftr n z) = length_binary z - n.\nProof.\n  induction n; destruct z; simpl; auto.\nQed.\n\n(* [z ^ (z >>> n)]*)\nDefinition shift_xor z (n : nat) :=\n  xor z (shiftr n z).\n\nInductive bit := zero | one.\n\nDefinition of_bit (a : bit) : binary -> binary :=\n  match a with\n  | zero => b0\n  | one => b1\n  end.\n\nDefinition of_bool (a : bool) : binary -> binary :=\n  match a with\n  | false => b0\n  | true => b1\n  end.\n\nFixpoint succ (z : binary) : binary :=\n  match z with\n  | b1 z => b0 (succ z)\n  | _ => z\n  end.\n\nDefinition succ_length :\n  forall z, length_binary (succ z) = length_binary z.\nProof.\n  induction z; simpl; auto.\nQed.\n\n(* Add two numbers with carry. The result is truncated to the\n   length of the first operand. *)\nFixpoint plus' (c : bit) (z1 z2 : binary) :=\n  match z1, z2 with\n  | b0 z1, b0 z2 => of_bit c (plus' zero z1 z2)\n  | b1 z1, b0 z2 | b0 z1, b1 z2 =>\n    match c with\n    | zero => b1 (plus' zero z1 z2)\n    | one => b0 (plus' one z1 z2)\n    end\n  | b1 z1, b1 z2 =>\n    of_bit c (plus' one z1 z2)\n  | _, _ => succ z1\n  end.\n\nLemma plus'_length :\n  forall z1 z2 c, length_binary (plus' c z1 z2) = length_binary z1.\nProof.\n  induction z1; destruct z2; destruct c; simpl; auto using succ_length.\nQed.\n\nDefinition plus : binary -> binary -> binary := plus' zero.\n\nExample plus_test :\n  plus (N_to_binary 10 3) (N_to_binary 5 5) = N_to_binary 10 8.\nProof. reflexivity. Qed.\n\nLemma plus_length :\n  forall z1 z2, length_binary (plus z1 z2) = length_binary z1.\nProof.\n  intros; apply plus'_length.\nQed.\n\nFixpoint mul (z1 z2 : binary) :=\n  match z1 with\n  | b0 z1 => b0 (mul z1 z2)\n  | b1 z1 => plus (b0 (mul z1 z2)) z2\n  | b_ => b_\n  end.\n\nExample mul_test :\n  mul (N_to_binary 10 3) (N_to_binary 5 5) = N_to_binary 10 15.\nProof. reflexivity. Qed.\n\nLemma mul_length :\n  forall z1 z2, length_binary (mul z1 z2) = length_binary z1.\nProof.\n  induction z1; intro z2; simpl; auto.\n  rewrite plus_length; simpl; auto.\nQed.  \n\nFixpoint popcount_under (n : nat) (z : binary) : bool :=\n  match z, n with\n  | b1 _, O => false\n  | b1 z, S n => popcount_under n z\n  | b0 z, _ => popcount_under n z\n  | b_, _ => true\n  end.\n\nFixpoint hex' (acc : binary) (s : string) : binary :=\n  match s with\n  | EmptyString => acc\n  | String x s =>\n    let acc :=\n        match x with\n        (* Digit *)\n        | Ascii a0 a1 a2 a3 _ _ false _ =>\n          of_bool a0 (of_bool a1 (of_bool a2 (of_bool a3 acc)))\n        | \"a\" => b0 (b1 (b0 (b1 acc)))\n        | \"b\" => b1 (b1 (b0 (b1 acc)))\n        | \"c\" => b0 (b0 (b1 (b1 acc)))\n        | \"d\" => b1 (b0 (b1 (b1 acc)))\n        | \"e\" => b0 (b1 (b1 (b1 acc)))\n        | \"f\" => b1 (b1 (b1 (b1 acc)))\n        | _ => b0 (b0 (b0 (b0 acc)))\n        end%char in\n    hex' acc s\n  end.\n\nDefinition hex : string -> binary := hex' b_.\n\n(* Compute hex \"123\". *)\n\nDefinition golden_gamma : binary :=\n  Eval compute in hex \"9e3779b97f4a7c15\".\n\nDefinition c1 : binary :=\n  Eval compute in hex \"ff51afd7ed558ccd\".\nDefinition c2 : binary :=\n  Eval compute in hex \"c4ceb9fe1a85ec53\".\n\nDefinition mix64 z :=\n  let z := mul c1 (shift_xor z 33) in\n  let z := mul c2 (shift_xor z 33) in\n  shift_xor z 33.\n\nDefinition c3 : binary :=\n  Eval compute in hex \"bf58476d1ce4e5b9\".\nDefinition c4 : binary :=\n  Eval compute in hex \"94d049bb133111eb\".\n\nDefinition mix64variant13 z :=\n  let z := mul c3 (shift_xor z 30) in\n  let z := mul c4 (shift_xor z 27) in\n  shift_xor z 31.\n\nDefinition set_lsb z :=\n  match z with\n  | b0 z => b1 z\n  | _ => z\n  end.\n\nDefinition c5 : binary :=\n  Eval compute in hex \"aaaaaaaaaaaaaaaa\".\n\nDefinition mix_gamma z :=\n  let z := set_lsb (mix64 z) in\n  if popcount_under 24 (shift_xor z 1) then\n    xor z c5\n  else\n    z.\n\nDefinition N64 := binary.\n\nRecord State := MkState {\n  seed : N64;\n  gamma : N64;\n  counter : N64; (* big-endian *)\n  remaining : nat;\n}.\n\nDefinition split '(MkState s0 g c r) : State * State :=\n  match r with\n  | S r =>\n    let new bx := MkState s0 g (bx c) r in\n    (new b0, new b1)\n  | O =>\n    (* [b0 c = 2 * c], SplitMix's splitting increments the\n       counter by 2. *)\n    let s1 := plus s0 (mul g (b0 (rev c))) in\n    let s2 := plus s1 g in\n    let s' := mix64variant13 s1 in\n    let g' := mix_gamma s2 in\n    let new bx := MkState s' g' (bx b_) 63 in\n    (new b0, new b1)\n  end.\n\n(* Probably overkill if you just need a few bits. *)\nDefinition to_binary '(MkState s0 g c r) : binary :=\n  let s1 := plus s0 (mul g (b0 (rev c))) in\n  mix64variant13 s1.\n\nDefinition of_seed n : State :=\n  {| seed := N_to_binary 64 n;\n     gamma := golden_gamma;\n     counter := b_;\n     remaining := 64 |}.\n\nSection Ex.\n\nImport NArith.\n\nFixpoint split_many2 (n : nat) g :=\n  match n with\n  | O => g\n  | S n' => let (_, g) := split g in split_many2 n' g\n  end.\n\nEnd Ex.\n", "meta": {"author": "Lysxia", "repo": "coq-pseudorandom", "sha": "9c5d111199db228e9ab9d8a14ed7777506017674", "save_path": "github-repos/coq/Lysxia-coq-pseudorandom", "path": "github-repos/coq/Lysxia-coq-pseudorandom/coq-pseudorandom-9c5d111199db228e9ab9d8a14ed7777506017674/src/SplitMix2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755218, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7240084332961108}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Basic_Cons.Equalizer.\nRequire Import Coq_Cats.Type_Cat.Type_Cat.\n\nLocal Obligation Tactic := idtac.\n\n(** Just like in category of sets, in category of types, the equalizer is the type\nthat reperesents the subset of the cartesian profuct of the domain of the two functions\nthat is mapped to equal values by both functions. *)\nSection Equalizer.\n  Context {A B : Type} (f g : A → B).\n\n  Program Definition Type_Cat_Eq : Equalizer Type_Cat f g :=\n    {|\n      equalizer := {x : A | f x = g x};\n      equalizer_morph := @proj1_sig _ _;\n      equalizer_morph_ex :=\n        fun T eqm H x =>\n          exist _ (eqm x) _\n    |}.\n\n  Next Obligation.\n  Proof.\n    extensionality x; destruct x as [x Px]; trivial.\n  Qed.  \n\n  Next Obligation.\n  Proof.  \n    intros T eqm H x.\n    apply (fun w => equal_f w x) in H; trivial.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    trivial.\n  Qed.\n\n  Next Obligation.\n  Proof.\n    intros T eqm H1 u u' H2 H3.\n    extensionality x.\n    apply (fun w => equal_f w x) in H2; cbn in H2.\n    apply (fun w => equal_f w x) in H3; cbn in H3.\n    destruct (u x) as [ux e]; destruct (u' x) as [ux' e']; cbn in *.\n    destruct H2; destruct H3.\n    PIR.\n    trivial.\n  Qed.\n\nEnd Equalizer.\n\n(** Similar to the category set, in category of types, the coequalizer of two functions\nf,g : A -> B is quotient of B with respect to the equivalence relation ~. Here, ~\nis the equivalence closure of the relation for which we have\n\nx ~ y if and only if ∃z. (f(z) = x) ∧ (g(z) = y)\n\n*)\n\n\nProgram Instance Type_Cat_Has_Equalizers : Has_Equalizers Type_Cat := fun _ _ => Type_Cat_Eq.\n\nRequire Import Coq.Relations.Relations Coq.Relations.Relation_Definitions.\nRequire Import Coq.Logic.ClassicalChoice Coq.Logic.ChoiceFacts.\nRequire Coq.Logic.ClassicalFacts.\n                                         \nSection CoEqualizer.\n  Context {A B : Type} (f g : A → B).\n\n  Local Obligation Tactic := idtac.\n  \n  Definition CoEq_rel_base : relation B := fun x y => exists z, f z = x ∧ g z = y.\n\n  Definition CoEq_rel : relation B := clos_refl_sym_trans _ CoEq_rel_base.\n\n  Definition CoEq_rel_refl := equiv_refl _ _ (clos_rst_is_equiv _ CoEq_rel_base).\n  Definition CoEq_rel_sym := equiv_sym _ _ (clos_rst_is_equiv _ CoEq_rel_base).\n  Definition CoEq_rel_trans := equiv_trans _ _ (clos_rst_is_equiv _ CoEq_rel_base).\n\n  Definition CoEq_Type := {P : B → Prop | exists z : B, P z ∧ (∀ (y : B), (P y ↔ CoEq_rel z y))}.\n\n  Local Axiom ConstructiveIndefiniteDescription_B : ConstructiveIndefiniteDescription_on B.\n  \n  Definition CoEq_Choice (ct : CoEq_Type) : {x : B | (proj1_sig ct) x}.\n  Proof.\n    apply ConstructiveIndefiniteDescription_B.\n    destruct ct as [P [z [H1 H2]]].\n    exists z; trivial.\n  Defined.\n\n  Local Axiom PropExt : ClassicalFacts.prop_extensionality.\n\n  Theorem CoEq_rel_Ext : ∀ (x : A) (y : B), CoEq_rel (f x) y = CoEq_rel (g x) y.\n  Proof.\n    intros x y.\n    assert (Hx : CoEq_rel (f x) (g x)).\n    {\n      constructor 1.\n      exists x; split; trivial.\n    }\n    apply PropExt; split; intros H.\n    {\n      apply CoEq_rel_sym in Hx.\n      apply (CoEq_rel_trans _ _ _ Hx H).\n    }\n    {\n      apply (CoEq_rel_trans _ _ _ Hx H).\n    }\n  Qed.    \n    \n  Program Definition Type_Cat_CoEq  : CoEqualizer Type_Cat f g :=\n    {|\n      equalizer := CoEq_Type\n    |}.\n\n  Next Obligation.\n  Proof.  \n    cbn in *.\n    intros x.\n    exists (fun y => CoEq_rel x y).\n    exists x; split.\n    apply CoEq_rel_refl.\n    intros z; split; intros; trivial.\n  Defined.\n \n  Next Obligation.\n  Proof.\n    extensionality x.\n    apply sig_proof_irrelevance.\n    extensionality y.\n    apply CoEq_rel_Ext.\n  Qed.    \n\n  Next Obligation.\n  Proof.  \n    intros T F H x.\n    exact (F (proj1_sig (CoEq_Choice x))).\n  Defined.\n\n  Next Obligation.\n  Proof.\n    intros T eqm H.\n    unfold Type_Cat_CoEq_obligation_1, Type_Cat_CoEq_obligation_3.\n    extensionality x.\n    cbn in *.\n    match goal with\n      [|- eqm (proj1_sig ?A) = _] =>\n      destruct A as [z Hz]\n    end.\n    cbn in *.\n    induction Hz as [? ? [w [[] []]]| | |]; auto.\n    {\n      eapply equal_f in H; eauto.\n    }\n  Qed.\n\n  Next Obligation.\n  Proof.\n    intros T eqm H1 u u' H2 H3.\n    destruct H3.\n    extensionality x.\n    destruct x as [P [z [Hz1 Hz2]]].\n    unfold Type_Cat_CoEq_obligation_1 in H2; cbn in *.\n    apply equal_f with (x := z) in H2.\n    match goal with\n      [|- ?A = ?B] =>\n      match type of H2 with\n        ?C = ?D => cutrewrite (A = C); [cutrewrite (B = D)|]; trivial\n      end\n    end.\n    {\n      apply f_equal.\n      apply sig_proof_irrelevance; cbn.\n      extensionality y; apply PropExt; trivial.\n    }\n    {\n      apply f_equal.\n      apply sig_proof_irrelevance; cbn.\n      extensionality y; apply PropExt; trivial.\n    }\n  Qed.\n\nEnd CoEqualizer.\n\nProgram Instance Type_Cat_Has_CoEqualizers : Has_CoEqualizers Type_Cat := fun _ _ => Type_Cat_CoEq.", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/Coq_Cats/Type_Cat/Equalizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7240084299643691}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Lia Wellfounded Extraction.\n\nSet Implicit Arguments.\n\n(** Notations utilisées dans le projet \n\n    ⌊l⌋    :  longueur de la liste l\n    l ~p m :  les listes l et m sont permutables\n    x ∊ l  :  x appartient à la liste l\n    x ≤ y  :  x est plus petit que y (pour l'ordre R)\n    l ≲ r  :  tous les elements de la liste l sont plus petits que \n              tous les elements de la liste r (pour l'ordre R)\n\n    Les quatres lignes ci-dessous ne font que déclarer\n    la forme et les priorités des notations, leur sens\n    est déclaré plus loin, la première fois qu'on les\n    utilise. *)\n\nReserved Notation \"⌊ l ⌋\" (at level 1, format \"⌊ l ⌋\").\nReserved Notation \"l ~p m\" (at level 70, no associativity, format \"l  ~p  m\").\nReserved Notation \"x ∊ l\" (at level 70, no associativity, format \"x  ∊  l\").\nReserved Notation \"x ≤ y\" (at level 70, no associativity, format \"x  ≤  y\").\nReserved Notation \"l ≲ m\" (at level 70, no associativity, format \"l  ≲  m\").\n\n(** Une librairie pour réaliser des inductions basées sur une mesure entière,\n    par exemple la longueur d'une liste, ou encore la longueur combinée de \n    deux listes. *)\n\nSection measure_rect.\n\n  Variables (X : Type) (m : X -> nat)\n            (P : X -> Type) (HP: forall x, (forall x', m x' < m x -> P x') -> P x).\n\n  Definition measure_rect x : P x.\n  Proof.\n    refine ((fix loop x (a : Acc (fun u v => m u < m v) x) : P x := _) x _).\n    + apply HP.\n      intros; now apply loop, Acc_inv with (1 := a).\n    + apply wf_inverse_image, lt_wf.\n  Defined.\n\nEnd measure_rect.\n\nSection measure_rect2.\n\n  Variables (X Y : Type) (m : X -> Y -> nat)\n            (P : X -> Y -> Type) (HP: forall x y, (forall x' y', m x' y' < m x y -> P x' y') -> P x y).\n\n  Definition measure2_rect x y : P x y.\n  Proof.\n    refine ((fix loop x y (a : Acc (fun u v => m (fst u) (snd u) < m (fst v) (snd v)) (x,y)) : P x y := _) x y _).\n    + apply HP.\n      intros; now apply loop, Acc_inv with (1 := a).\n    + apply wf_inverse_image, lt_wf.\n  Defined.\n\nEnd measure_rect2.\n\nTactic Notation \"induction\" \"on\" hyp(x) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n  pattern x; revert x; apply measure_rect with (m := fun x => f); intros x IH.\n\nTactic Notation \"induction\" \"on\" hyp(x) hyp(y) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n  pattern x, y; revert x y; apply measure2_rect with (m := fun x y => f); intros x y IH.\n\nExtraction Inline measure_rect measure2_rect.\n\n(** Toute petite extension de la libraire standard sur les listes (List) *)\n\nRequire Import List.\n\nImport ListNotations.\n\n(* On note \"In x l\" de manière infixe avec \"x ∊ l\" *)\nInfix \"∊\" := In.\nNotation \"⌊ l ⌋\" := (length l).\n\nPrint Notation  \"_ ∊ _\".\nAbout \"_ ∊ _\".\nPrint In.\n\nPrint Notation \"⌊ _ ⌋\".\nAbout \"⌊ _ ⌋\".\nPrint length.\n\nPrint Notation \"_ ++ _\".\nAbout \"_ ++ _\".\nPrint app.\n\nFact list_cons_inj X (x y : X) l m : x::l = y::m -> x = y /\\ l = m.\nProof. intros H; inversion H; split; trivial. Qed.\n\n#[local] Hint Resolve in_eq in_cons : core.\n\nCheck in_eq.\nCheck in_cons.\n\n(** On importe une partie de la librairie sur les permutations.\n    Seuls sont listés les résultats utiles aux algorithmes de tri. *)\n\nRequire Permutation.\nInfix \"~p\" := Permutation.Permutation.\n\nSection perm.\n\n  Variable (X : Type).\n\n  Implicit Types (l : list X).\n\n  Fact perm_refl l : l ~p l.\n  Proof. apply Permutation.Permutation_refl. Qed.\n\n  Fact perm_cons x y l m : x = y -> l ~p m -> x::l ~p y::m.\n  Proof. intros ->; apply Permutation.Permutation_cons; trivial. Qed.\n\n  Fact perm_swap x y l : x::y::l ~p y::x::l.\n  Proof. apply Permutation.perm_swap. Qed.\n\n  Fact perm_trans l m k : l ~p m -> m ~p k -> l ~p k.\n  Proof. apply Permutation.perm_trans. Qed.\n\n  Fact perm_sym l m : l ~p m -> m ~p l.\n  Proof. apply Permutation.Permutation_sym. Qed.\n\n  Fact perm_middle x l m : x::l++m ~p l++x::m.\n  Proof. apply Permutation.Permutation_middle. Qed.\n\n  Fact perm_app l l' m m' : l ~p l' -> m ~p m' -> l++m ~p l'++m'.\n  Proof. apply Permutation.Permutation_app. Qed.\n\n  Fact perm_app_comm l m : l++m ~p m++l.\n  Proof. apply Permutation.Permutation_app_comm. Qed.\n\n  Fact perm_nil l : [] ~p l -> l = [].\n  Proof. apply Permutation.Permutation_nil. Qed.\n\n  Fact perm_length l m : l ~p m -> ⌊l⌋ = ⌊m⌋.\n  Proof. apply Permutation.Permutation_length. Qed.\n\n  Fact perm_in l m x : l ~p m -> x ∊ l -> x ∊ m.\n  Proof. apply Permutation.Permutation_in. Qed.\n\n  Fact perm_cons_inv x l m : x::l ~p x::m -> l ~p m.\n  Proof. apply Permutation.Permutation_cons_inv. Qed.\n\nEnd perm.\n\n(** On va trier les listes en utilisant un ordre total \n    et calculable, c'est à dire, une relation binaire \n\n         R : X -> X -> Prop \n\n    notée \"x ≤ y\" à la place de \"R x y\" pour plus de lisibilité. \n    On suppose que R/≤ est\n     - réflexive, antisymétrique et transitive\n     - calculable, càd dotée du'une fonction R_cmp \n       qui calcule un Booléen b de sorte que\n       * si b est true alors on a une preuve de x ≤ y \n       * si b est false alors on a une preuve de y ≤ x. \n     - voir ci-dessous pour quelques détails supplémentaire\n       sur R_cmp. *)\n\nParameter (X : Type) (R : X -> X -> Prop).\nInfix \"≤\" := R.\n\nParameter (R_refl  : forall x, x ≤ x)\n          (R_anti  : forall x y, x ≤ y -> y ≤ x -> x = y)\n          (R_trans : forall x y z, x ≤ y -> y ≤ z -> x ≤ z)\n          (R_cmp   : forall x y, { b : bool | if b then x ≤ y else y ≤ x }).\n\n(* R_cmp x y est de type { b : bool | if b then x ≤ y else y ≤ x }, càd\n   une paire dépendante (b,Hb) où\n      - b est de type bool; \n      - Hb est de type (if b then x ≤ y else y ≤ x).\n   Donc le type de Hb dépend de la valeur de b. Plus précisément, b est true\n   alors Hb : x ≤ y, et si b est false alors Hb : y ≤ x. *)\n\n#[local] Hint Resolve R_refl : core.\n\n(** Une librairie pour la comparaison de deux listes \n    en utilisant R/≤. On défini une relation binaire\n\n        list_le : list X -> list X -> Prop\n\n    notée \"l ≲ r\" à la place de \"list_le l r\" pour\n    plus de lisibilité. \"l ≲ r\" signifie que tous les\n    éléments de l sont plus petits que tous les éléments\n    de r. *)\n\nDefinition list_le l r := forall x y, x ∊ l -> y ∊ r -> x ≤ y.\nInfix \"≲\" := list_le.\n\n(* Astuce: \"Print In\" vous dit que x ∊ [] est False *) \nFact list_le_nil_l r : [] ≲ r.  Proof. admit. Admitted.\nFact list_le_nil_r l : l ≲ [].  Proof. admit. Admitted.\n\n#[local] Hint Resolve list_le_nil_l list_le_nil_r : core.\n\n(* Astuce: utiliser R_trans *)\nFact list_le_trans l x r : l ≲ [x] -> [x] ≲ r -> l ≲ r.\nProof.\n  intros H1 H2 u v Hu Hv.\n  admit.\nAdmitted.\n\n(* Astuce: perm_in dit que si l ~p m alors l et m\n   ont les mêmes éléments *)\nFact list_le_perm_l l m r : l ~p m -> m ≲ r -> l ≲ r.\nProof.\n  intros H1 H2 u v Hu Hv.\n  admit.\nAdmitted.\n\nFact list_le_perm_r l m r : r ~p m -> l ≲ m -> l ≲ r.\nProof.\n  admit.\nAdmitted.\n\n(* Astuce: Check in_app_iff. *)\nFact list_le_app_l l r m : l++r ≲ m <-> l ≲ m /\\ r ≲ m.\nProof.\n  admit.\nAdmitted.\n\nFact list_le_app_r m l r : m ≲ l++r <-> m ≲ l /\\ m ≲ r.\nProof.\n  admit.\nAdmitted.\n\n(* Astuce:\n    - utiliser list_le_app_l\n    - et l'identité x::l = [x]++l *)\nFact list_le_cons_l x l r : [x] ≲ r -> l ≲ r -> x::l ≲ r.\nProof.\n  admit.\nAdmitted.\n\nFact list_le_cons_r x l r : l ≲ [x] -> l ≲ r -> l ≲ x::r.\nProof.\n  admit.\nAdmitted.\n\nFact list_le_singleton x y : x ≤ y -> [x] ≲ [y].\nProof.\n  admit.\nAdmitted.\n\n#[local] Hint Resolve list_le_singleton : core.\n\nFact list_le_singleton_iff x y : [x] ≲ [y] <-> x ≤ y.\nProof. split; auto. Qed.\n\n(** Notion de liste triée par rapport à R/≤ *)\n\n(* Si on découpe une liste triée m en deux \"m = l++r\", alors\n   la partie gauche \"l\" contient des éléments tous inférieurs \n   à eux de la partie droite \"r\".\n\n   C'est ainsi qu'on choisit de définir ce qu'est une liste\n   triée. D'autres choix de définitions équivalentes sont \n   possibles. *)\n\nDefinition sorted m := forall l r, m = l++r -> l ≲ r.\n\n(** Astuce:\n    - seul [] = []++[] est possible\n    - puis utiliser list_le_nil_* *)\nFact sorted_nil : sorted [].\nProof.\n  admit.\nAdmitted.\n\n(* Astuce:\n   - analyse par cas sur l, première variable\n     quantifiée dans la déf. de sorted.\n   - utiliser list_consj_inj ensuite. *)\nFact sorted_cons x m : [x] ≲ m -> sorted m -> sorted (x::m).\nProof.\n  intros H1 H2 [ | y k ] r E; simpl in *.\n  + admit.\n  + admit.\nAdmitted.\n\n#[local] Hint Resolve sorted_nil sorted_cons : core.\n\nFact sorted_singleton x : sorted [x].\nProof. auto. Qed.\n\n(* Astuce:\n   - si m = l++r alors x::m = (x::l)++r \n   - aussi, x::m = [x]++m *)\nFact sorted_cons_inv x m : sorted (x::m) -> sorted m /\\ [x] ≲ m.\nProof.\n  admit.\nAdmitted.\n\n(* Astuce:\n   - par induction sur l\n   - utiliser sorted_cons & sorted_cons_inv *)\nFact sorted_app l r : l ≲ r -> sorted l -> sorted r -> sorted (l++r).\nProof.\n  induction l as [ | x l IHl ] in r |- *; simpl; trivial.\n  admit.\nAdmitted.\n\n(** Il y a une seul résultat possible au tri d'une liste \n    même s'il y a plusieurs manières de procéder à ce tri *)\n\n(* Une fonction de tri est une fonction qui renvoie\n   une liste permutable et triée *)\nDefinition sorting_function (s : list X -> list X) :=\n  forall l, sorted (s l) /\\ s l ~p l.\n\n(* Astuce:\n   - par induction sur l puis analyse par cas sur r\n   - utiliser perm_*\n   - utiliser sorted_cons_inv \n   - aussi, R est antisymétrique *)\nLemma perm_sorted_eq l r : l ~p r -> sorted l -> sorted r -> l = r.\nProof.\n  induction l as [ | x l IHl ] in r |- *.\n  + intros E _ _.\n    apply perm_nil in E.\n    subst.\n    trivial.\n  + destruct r as [ | y r ].\n    * admit.\n    * admit.\nAdmitted.\n\n(* Toutes les fonctions de tri renvoient la même valeur *)\nCorollary sorting_deterministic s1 s2 : \n           sorting_function s1 \n        -> sorting_function s2 \n        -> forall l, s1 l = s2 l.\nProof.\n  intros H1 H2 l.\n  destruct (H1 l) as (G1 & G2).\n  destruct (H2 l) as (G3 & G4).\n  revert G1 G3; apply perm_sorted_eq.\n  now apply perm_trans with (1 := G2), perm_sym.\nQed. \n\nSection insertion_sort.\n\n  (** Le tri par insertion *)\n\n  (* On insère x dans l à sa place *)\n  Fixpoint insert x l :=\n    match l with\n    | []   => [x]\n    | y::m => if proj1_sig (R_cmp x y) then x::l else y::insert x m\n    end.\n\n  (* A permutation près, on ne fait que rajouter un élément à l *)\n  (* Astuce: perm_[refl,trans,cons,swap] *)\n  Fact insert_perm x l : insert x l ~p x::l.\n  Proof.\n    induction l as [ | y m IH ]; simpl.\n    + admit.\n    + admit.\n  Admitted.\n\n  (* Si l est déjà triée, l'insertion maintien cette propriété *)\n  (* Astuce: sorted_cons_inv, list_le_cons, list_le_trans *)\n  Fact insert_sorted x l : sorted l -> sorted (insert x l).\n  Proof.\n    induction l as [ | y m IH ]; simpl.\n    + intros _; apply sorted_singleton.\n    + intros H.\n      destruct (R_cmp x y) as ([] & Hb); simpl.\n      * admit.\n      * admit.\n  Admitted.\n\n  (* Le tri par insertion *)\n  Fixpoint insertion_sort l :=\n    match l with\n    | []   => []\n    | x::l => insert x (insertion_sort l)\n    end.\n\n  (* Astuce:\n     - insert_perm & perm_*\n     - insert_sorted *)\n  Theorem insert_sort_sorting : sorting_function insertion_sort.\n  Proof.\n    intros l.\n    induction l as [ | x l IH ]; simpl.\n  Admitted.\n\nEnd insertion_sort.\n\nSection quick_sort.\n\n  (** Le tri rapide *)\n\n  Implicit Type m : list X.\n\n  (* On sépare la liste m avec le pivot x:\n     - l qui contient les éléments plus petits que x\n     - r qui contient ceux plus grands que x *)\n  Fixpoint pivot_split x m :=\n    match m with\n    | []   => ([],[])\n    | y::m => let (l,r) := pivot_split x m in\n              if proj1_sig (R_cmp x y) then (l,y::r) else (y::l,r)\n    end.\n\n  (* Propriétés du pivot_split *)\n  (* Astuce:\n     - induction sur m = [] ou m = y::m'\n     - analyse du pivot_split x m' dans\n       le cas récursif \n     - comparaison de x et y *)\n  Lemma pivot_split_spec x m : \n    let (l,r) := pivot_split x m \n    in  l++r ~p m /\\ l ≲ [x] /\\ [x] ≲ r. \n  Proof.\n    induction m as [ | y m' IH ]; simpl.\n    + repeat split; auto; tauto.\n    + destruct (pivot_split x m') as (l,r).\n      destruct IH as (H1 & H2 & H3).\n      destruct (R_cmp x y) as ([] & Hxy); simpl.\n      * admit.\n      * admit.\n  Admitted.\n\n  (* pivot_split et sa spécification dans un seul type enrichi *)\n  Definition pivot_split_full x m : { '(l,r) | l++r ~p m /\\ l ≲ [x] /\\ [x] ≲ r }.\n  Proof. exists (pivot_split x m); apply pivot_split_spec. Defined.\n\n  (* Argument de terminaison pour le quick_sort *)\n  Lemma perm_length_cons l r x m : l++r ~p m -> ⌊l⌋ < ⌊x::m⌋ /\\ ⌊r⌋ < ⌊x::m⌋.\n  Proof.\n    intros H%perm_length.\n    rewrite app_length in H.\n    simpl; lia.\n  Qed.\n\n  (* Astuce:\n     - sorted_app, list_le_cons, list_le_trans *)\n  Lemma sorted_quick_sort l x r :\n        l ≲ [x] \n     -> [x] ≲ r\n     -> sorted l\n     -> sorted r\n     -> sorted (l++x::r).\n  Proof.\n    admit.\n  Admitted.\n\n  (* Argument de correction du quick_sort *)\n  (* Astuce: perm_[trans,cons,sym_middle] *)\n  Lemma perm_quick_sort l r x m : l++r ~p m -> l++x::r ~p x::m.\n  Proof.\n    admit.\n  Admitted.\n\n  (* quick_sort construit avec sa spécification:\n     la sortie s est une liste triée permutable\n      avec l'entré m. *)\n  (* Astuce:\n     - induction sur la longueur de m\n     - analyse par cas sur m = [] ou m = x::m'\n     - on utilise x comme pivot:\n        ((l,r),H) := pivot_split_full x m'\n     - on applique l'hypothèse d'induction à l et r *)\n  Lemma quick_sort_full m : { s | sorted s /\\ s ~p m }.\n  Proof.\n    induction on m as IH with measure ⌊m⌋.\n    destruct m as [ | x m' ].\n    + exists [].\n      admit.\n    + destruct (pivot_split_full x m') as ((l,r) & H1 & H2 & H3).\n      destruct (IH l) as (l' & G1 & G2); [ apply perm_length_cons with (1 := H1) | ].\n      destruct (IH r) as (r' & G3 & G4); [ apply perm_length_cons with (1 := H1) | ].\n      exists (l'++x::r'); split.\n      * admit.\n      * admit.\n  Admitted.\n\n  (* Puis on obtient le quick_sort en séparant\n     le résultat et sa spécification *)\n\n  Definition quick_sort m := proj1_sig (quick_sort_full m).\n\n  Theorem quick_sort_sorting : sorting_function quick_sort.\n  Proof. intros m; apply (proj2_sig (quick_sort_full m)). Qed.\n\nEnd quick_sort.\n\nSection merge_sort.\n\n  (** Le tri fusion *)\n\n  Implicit Type m : list X.\n\n  (* merge_split [x1,x2,x3,..] = ([x1,x3,x5,...],[x2,x4,...] *)\n  Fixpoint merge_split m :=\n    match m with\n    | []   => ([],[])\n    | x::m => let (l,r) := merge_split m in (x::r,l)\n    end.\n\n  (* Spécification de \"(l,r) := merge_split m\" :\n     - l&r contiennent les mêmes éléments que m à \n       permutation près\n     - les listes l et r ont presque la même longueur *)\n  (* Astuce:\n     - induction sur m = [] ou m = x::m'\n     - analyse de merge_split m'\n     - perm_[cons,trans,app_comm] *)\n  Lemma merge_split_spec m : \n    let (l,r) := merge_split m \n    in  l++r ~p m /\\ ⌊r⌋ <= ⌊l⌋ <= 1+⌊r⌋.\n  Proof.\n    induction m as [ | y m' IH ]; simpl.\n    + repeat split; auto; lia.\n    + revert IH.\n      destruct (merge_split m') as (l,r); simpl.\n      intros (H1 & H2 & H3).\n      split; [ | lia ].\n      admit.\n  Admitted.\n\n  Definition merge_split_full m : { '(l,r) | l++r ~p m /\\ ⌊r⌋ <= ⌊l⌋ <= 1+⌊r⌋ }.\n  Proof. exists (merge_split m); apply merge_split_spec. Defined.\n\n  (* fusion de deux listes triées l et r avec la spécification *)\n  (* Astuce:\n     - induction sur la longueur combinée ⌊l⌋+⌊r⌋\n     - analyse par cas sur l puis sur r \n     - dans le cas où l = x::l' et r = y::r'\n       comparaison de x et y avec R_dec *)\n  Lemma merge l r : sorted l -> sorted r -> { m | m ~p l++r /\\ sorted m }.\n  Proof.\n    induction on l r as IH with measure (⌊l⌋+⌊r⌋).\n    intros Hl Hr.\n    destruct l as [ | x l' ].\n    + exists r; auto.\n    + destruct r as [ | y r' ].\n      * exists (x::l'); split; auto.\n        now rewrite <- app_nil_end.\n      * apply sorted_cons_inv in Hl as (H1 & H2).\n        apply sorted_cons_inv in Hr as (H3 & H4).\n        destruct (R_cmp x y) as ([] & Hxy); simpl.\n        - destruct (IH l' (y::r')) as (m & G1 & G2); auto.\n          exists (x::m); simpl.\n          admit.\n        - admit.\n  Admitted.\n\n  (* tri fusion de m avec sa spécification *)\n  (* Astuce:\n     - par induction sur la longueur ⌊m⌋\n     - analyse par cas sur m\n       * m = []\n       * m = [x]\n       * m = _::_::_ (longueur > 1)\n         dans ce cas, on divise m en\n         deux parts de longueur presque identique,\n         que l'on trie récursivement, puis qu'on\n         fusionne. *)\n  Lemma merge_sort_full m : { s | sorted s /\\ s ~p m }.\n  Proof.\n    induction on m as IH with measure ⌊m⌋.\n    revert IH.\n    case_eq m.\n    + intros Hm IH.\n      exists []; auto.\n    + intros x [ | y m' ] Hm IH.\n      * exists [x]; auto.\n      * destruct (merge_split_full m) as ((l,r) & H1 & H2 & H3).\n        subst m.\n        generalize (perm_length H1); rewrite app_length; simpl; intros H4.\n        destruct (IH l) as (l' & G1 & G2); [ simpl; lia | ].\n        destruct (IH r) as (r' & G3 & G4); [ simpl; lia | ].\n        admit.\n  Admitted.\n\n  Definition merge_sort m := proj1_sig (merge_sort_full m).\n\n  Theorem meger_sort_sorting : sorting_function merge_sort.\n  Proof. intros m; apply (proj2_sig (merge_sort_full m)). Qed.\n\nEnd merge_sort.\n\n(** Pour information, on peut extraire les algorithmes\n    certifiés corrects vers le langage OCaml par exemple *)\n\nExtraction Inline pivot_split_full quick_sort_full.\nExtraction Inline merge_split_full merge_sort_full.\n\nExtract Inductive prod => \"( * )\" [ \"( , )\" ].\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\nExtract Inductive list => \"list\" [ \"[]\" \"(::)\" ].\n\nRecursive Extraction insertion_sort quick_sort merge_sort.\n", "meta": {"author": "DmxLarchey", "repo": "Introduction-to-Coq", "sha": "c2924b5284ef87143def1850520a25984dc0e724", "save_path": "github-repos/coq/DmxLarchey-Introduction-to-Coq", "path": "github-repos/coq/DmxLarchey-Introduction-to-Coq/Introduction-to-Coq-c2924b5284ef87143def1850520a25984dc0e724/sorting_algorithms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7240008112455437}}
{"text": "Require Export RTopology SeparatednessAxioms.\nRequire Import RFuncContinuity UniformTopology ContinuousFactorization.\nFrom Coq Require Import Description Max Psatz ClassicalChoice.\nFrom ZornsLemma Require Import Proj1SigInjective.\nRequire Import UrysohnsLemma.\n\n(* This proof of the Tietze extension theorem is heavily based on\n   the proof described on planetmath.org. *)\n\nSection Tietze_extension_construction.\n\nVariable X:TopologicalSpace.\nVariable F:Ensemble X.\nHypothesis F_closed: closed F.\nVariable f:SubspaceTopology F -> RTop.\nHypothesis f_continuous: continuous f.\nHypothesis f_bound: forall x:SubspaceTopology F,\n  -1 <= f x <= 1.\nHypothesis X_nonempty: inhabited X.\n\nVariable Urysohns_lemma_function:\n  forall F G:Ensemble X,\n  closed F -> closed G -> Intersection F G = Empty_set ->\n  { f:X -> RTop |\n  continuous f /\\ (forall x:X, 0 <= f x <= 1) /\\\n  (forall x:X, In F x -> f x = 0) /\\\n  (forall x:X, In G x -> f x = 1) }.\n\nLemma Rle_order: order Rle.\nProof.\nconstructor;\n  red; intros.\n- apply Rle_refl.\n- eapply Rle_trans;\n    eassumption.\n- now apply Rle_antisym.\nQed.\n\nSection extension_approximation.\n\nVariable f0:SubspaceTopology F -> RTop.\nHypothesis f0_cont: continuous f0.\nHypothesis f0_bound: forall x:SubspaceTopology F,\n                     -1 <= f0 x <= 1.\n\nDefinition extension_approximation: X -> RTop.\nrefine (\n  let F0:=Im [ x:SubspaceTopology F | f0 x <= -1/3 ]\n             (subspace_inc F) in\n  let G0:=Im [ x:SubspaceTopology F | f0 x >= 1/3 ]\n             (subspace_inc F) in\n  let g:=proj1_sig (Urysohns_lemma_function F0 G0 _ _ _) in\n  fun x:X => -1/3 + 2/3 * g x).\n- apply subspace_inc_takes_closed_to_closed; [assumption|].\n  replace ([ x:SubspaceTopology F | f0 x <= -1/3 ]) with\n    (inverse_image f0 [ y:RTop | y <= -1/3 ]).\n  + red.\n    rewrite <- inverse_image_complement.\n    apply f0_cont.\n    apply lower_closed_interval_closed.\n    * apply Rle_order.\n    * intros.\n      destruct (total_order_T x y) as [[|]|];\n        auto with real.\n  + extensionality_ensembles.\n    * now constructor.\n    * constructor.\n      now constructor.\n- apply subspace_inc_takes_closed_to_closed; [assumption|].\n  replace ([ x:SubspaceTopology F | f0 x >= 1/3 ]) with\n    (inverse_image f0 [ y:RTop | 1/3 <= y ]).\n  + red.\n    rewrite <- inverse_image_complement.\n    apply f0_cont.\n    apply upper_closed_interval_closed.\n    * apply Rle_order.\n    * intros.\n      destruct (total_order_T x y) as [[|]|];\n        auto with real.\n  + extensionality_ensembles.\n    * constructor. lra.\n    * constructor. constructor. lra.\n- extensionality_ensembles.\n  destruct x, x0.\n  simpl in *.\n  subst.\n  destruct (proof_irrelevance _ i i0).\n  lra.\nDefined.\n\nLemma extension_approximation_bound: forall x:X,\n  -1/3 <= extension_approximation x <= 1/3.\nProof.\nintros.\nunfold extension_approximation.\ndestruct Urysohns_lemma_function as [g].\nsimpl.\ndestruct a as [? [? []]].\ndestruct (H0 x).\nlra.\nQed.\n\nLemma extension_approximation_diff_bound:\n  forall x:SubspaceTopology F,\n  -2/3 <= f0 x - extension_approximation (subspace_inc F x) <= 2/3.\nProof.\nintros.\nunfold extension_approximation.\ndestruct Urysohns_lemma_function as [g [? [? []]]].\nsimpl.\ndestruct (f0_bound x).\ndestruct (Rle_or_lt (f0 x) (-1/3)).\n- replace (g (subspace_inc F x)) with 0.\n  { lra. }\n  symmetry. apply e.\n  econstructor; trivial.\n  now constructor.\n- destruct (Rle_or_lt (1/3) (f0 x)).\n  + replace (g (subspace_inc F x)) with 1.\n    { lra. }\n    symmetry. apply e0.\n    econstructor; trivial.\n    constructor.\n    lra.\n  + destruct (a (subspace_inc F x)).\n    lra.\nQed.\n\nLemma extension_approximation_continuous:\n  continuous extension_approximation.\nProof.\nunfold extension_approximation.\ndestruct Urysohns_lemma_function as [g [? [? []]]].\nsimpl.\napply pointwise_continuity.\nintros.\napply sum_continuous.\n- apply continuous_func_continuous_everywhere,\n        continuous_constant.\n- now apply const_multiple_continuous,\n            continuous_func_continuous_everywhere.\nQed.\n\nEnd extension_approximation.\n\nLemma missing_pow_mult: forall (x y:R) (n:nat),\n  (x*y)^n = x^n * y^n.\nProof.\ninduction n.\n- lra.\n- simpl.\n  rewrite IHn.\n  lra.\nQed.\n\nDefinition extension_approximation_seq: forall n:nat,\n  { g0:X -> RTop |\n    continuous g0 /\\\n    (forall x:X, -1 + (2/3)^n <= g0 x <= 1 - (2/3)^n) /\\\n    (forall x:SubspaceTopology F,\n      -(2/3)^n <= f x - g0 (subspace_inc F x) <= (2/3)^n) }.\nsimple refine (fix g (n:nat) {struct n} := match n return\n  { g0:X -> RTop |\n    continuous g0 /\\\n    (forall x:X, -1 + (2/3)^n <= g0 x <= 1 - (2/3)^n) /\\\n    (forall x:SubspaceTopology F,\n      -(2/3)^n <= f x - g0 (subspace_inc F x) <= (2/3)^n) } with\n| O => exist _ (fun _ => 0) _\n| S m => match g m with\n         | exist gm y =>\n         let H := _ in\n         let approx := extension_approximation\n                       (fun x:SubspaceTopology F =>\n                       (3/2)^m * (f x - gm (subspace_inc F x))) H in\n         exist _ (fun x:X => gm x + (2/3)^m * approx x) _\n         end\nend); clear g; [ | | clearbody H ].\n- simpl.\n  split.\n  + apply continuous_constant.\n  + split; intros.\n    * lra.\n    * destruct (f_bound x).\n      lra.\n- apply pointwise_continuity.\n  intros.\n  apply const_multiple_continuous.\n  apply diff_continuous.\n  + now apply continuous_func_continuous_everywhere.\n  + apply continuous_composition_at.\n    * destruct y.\n      now apply continuous_func_continuous_everywhere.\n    * apply continuous_func_continuous_everywhere,\n            subspace_inc_continuous.\n- assert (H023m: 0 <= (2/3)^m).\n  {\n    apply pow_le. lra.\n  }\n  assert (H032m: 0 <= (3/2)^m).\n  {\n    apply pow_le. lra.\n  }\n  assert (forall x,\n             -1 <= (3/2)^m * (f x - gm (subspace_inc F x)) <= 1).\n  {\n    intros.\n    destruct y as [? []].\n    destruct (H2 x).\n    assert ((3/2)^m * (2/3)^m = 1).\n    {\n      rewrite <- missing_pow_mult.\n      replace (3/2*(2/3)) with 1 by field.\n      apply pow1.\n    }\n    replace (-1) with ((3/2)^m * (- (2/3)^m)) by lra.\n    replace 1 with ((3/2)^m * (2/3)^m) by lra.\n    auto with real.\n  }\n  assert (forall x, -1/3 <= approx x <= 1/3) by\n    apply extension_approximation_bound.\n  assert (forall x,\n             -2/3 <= (3/2)^m * (f x - gm (subspace_inc F x)) -\n                           approx (subspace_inc F x) <= 2/3) by\n    now apply extension_approximation_diff_bound.\n  destruct y as [? []].\n  split.\n  + apply pointwise_continuity.\n    intros.\n    apply sum_continuous.\n    * now apply continuous_func_continuous_everywhere.\n    * apply const_multiple_continuous.\n      apply continuous_func_continuous_everywhere.\n      apply extension_approximation_continuous.\n  + split; intros.\n    * destruct (H4 x), (H1 x).\n      assert (0 <= (2/3)^m) by\n        auto with real.\n      assert ((2/3)^m * (-1/3) <= (2/3)^m * approx x <= (2/3)^m * (1/3)) by\n        auto with real.\n      simpl.\n      lra.\n    * simpl.\n      replace (-(2/3*(2/3)^m)) with ((2/3)^m * (-2/3)) by field.\n      replace (2/3*(2/3)^m) with ((2/3)^m * (2/3)) by ring.\n      replace (f x - (gm (subspace_inc F x) + (2/3)^m * approx (subspace_inc F x)))\n        with ((2/3)^m * ((3/2)^m * (f x - gm (subspace_inc F x)) -\n                               approx (subspace_inc F x))).\n      ** destruct (H2 x).\n         auto with real.\n      ** ring_simplify.\n         replace ((2/3)^m*(3/2)^m) with 1.\n         { ring. }\n         rewrite <- missing_pow_mult.\n         replace (2/3*(3/2)) with 1 by field.\n         now rewrite pow1.\nDefined.\n\nLemma extension_approximation_seq_diff: forall (n:nat) (x:X),\n  -(1/3 * (2/3)^n) <= proj1_sig (extension_approximation_seq (S n)) x -\n                      proj1_sig (extension_approximation_seq n) x\n                   <= 1/3*(2/3)^n.\nProof.\nintros.\nsimpl extension_approximation_seq.\ndestruct extension_approximation_seq.\nsimpl.\nmatch goal with |- context [extension_approximation ?A ?B x] =>\n  cut (-1/3 <= extension_approximation A B x <= 1/3);\n  [ generalize (extension_approximation A B x) |\n    apply extension_approximation_bound ] end.\nintros.\nassert (0 <= (2/3)^n).\n{ apply pow_le. lra. }\nreplace (-(1/3*(2/3)^n)) with ((2/3)^n*(-1/3)) by field.\nreplace (1/3*(2/3)^n) with ((2/3)^n*(1/3)) by ring.\nreplace (x0 x + (2/3)^n*p - x0 x) with ((2/3)^n*p) by ring.\ndestruct H.\nsplit;\n  now apply Rmult_le_compat_l.\nQed.\n\n(* now we've gotten what we need from the concrete definition, make\n   it opaque so it doesn't slow down searches in the future *)\nGlobal Opaque extension_approximation_seq.\nOpaque extension_approximation_seq.\n\nLemma Rle_R1_pow: forall (x:R) (m n:nat), 0 <= x <= 1 -> (m <= n)%nat ->\n  x^n <= x^m.\nProof.\ninduction 2;\n  auto with real.\nsimpl.\nreplace (x^m) with (1*x^m) by\n  auto with real.\ndestruct H.\napply Rmult_le_compat; trivial.\nnow apply pow_le.\nQed.\n\nLemma extension_approximation_seq_cauchy_aux:\n  forall (m n:nat) (x:X),\n  Rabs (proj1_sig (extension_approximation_seq m) x -\n        proj1_sig (extension_approximation_seq n) x) <=\n  Rabs ((2/3)^m - (2/3)^n).\nProof.\ncut (forall (m n:nat) (x:X), (m <= n)%nat ->\n  Rabs (proj1_sig (extension_approximation_seq m) x -\n        proj1_sig (extension_approximation_seq n) x) <=\n  (2/3)^m - (2/3)^n).\n- intros.\n  destruct (le_or_lt m n).\n  + rewrite (Rabs_right ((2/3)^m - (2/3)^n)).\n    { now apply H. }\n    apply Rge_minus.\n    cut ((2/3)^n <= (2/3)^m); auto with real.\n    apply Rle_R1_pow; trivial.\n    lra.\n  + apply lt_le_weak in H0.\n    rewrite (Rabs_left1 ((2/3)^m - (2/3)^n)).\n    * replace (- ((2/3)^m - (2/3)^n)) with ((2/3)^n - (2/3)^m) by ring.\n      rewrite Rabs_minus_sym.\n      now apply H.\n    * apply Rle_minus.\n      apply Rle_R1_pow; trivial.\n      lra.\n- induction 1.\n  + repeat match goal with |- context [ ?y - ?y ] =>\n      replace (y-y) with 0 by ring end.\n    rewrite Rabs_R0. lra.\n  + simpl pow.\n    apply Rle_trans with\n      (Rabs (proj1_sig (extension_approximation_seq m) x -\n             proj1_sig (extension_approximation_seq m0) x) +\n       Rabs (proj1_sig (extension_approximation_seq m0) x -\n             proj1_sig (extension_approximation_seq (S m0)) x)).\n    * rewrite Rplus_comm.\n      apply R_metric_is_metric.\n    * pose proof (extension_approximation_seq_diff m0 x).\n      cut (Rabs (proj1_sig (extension_approximation_seq m0) x -\n                    proj1_sig (extension_approximation_seq (S m0)) x) <=\n              1/3 * (2/3)^m0).\n      { lra. }\n      destruct H0.\n      unfold Rabs.\n      destruct Rcase_abs; lra.\nQed.\n\nDefinition convert_approx_to_uniform_space:\n  nat -> uniform_space R_metric (fun _:X => 0).\nrefine (fun n:nat => exist _ (proj1_sig (extension_approximation_seq n)) _).\ndestruct extension_approximation_seq as [g [? []]].\nsimpl.\nunfold R_metric.\nexists (1 - (2/3)^n).\nred. intros.\ndestruct H.\nrewrite H0. clear y H0.\ndestruct (a x).\nunfold Rabs.\ndestruct Rcase_abs; lra.\nDefined.\n\nLemma extension_approximation_seq_cauchy:\n  cauchy (uniform_metric R_metric (fun _:X => 0)\n          R_metric_is_metric X_nonempty)\n    convert_approx_to_uniform_space.\nProof.\nred. intros.\nassert (Rabs (2/3) < 1).\n{ rewrite Rabs_right; lra. }\nassert (0 < eps/2) by lra.\ndestruct (pow_lt_1_zero (2/3) H0 (eps/2) H1) as [N].\nexists N.\nintros.\napply Rle_lt_trans with (Rabs ((2/3)^m - (2/3)^n)).\n- unfold uniform_metric, convert_approx_to_uniform_space.\n  destruct sup.\n  simpl.\n  apply i.\n  red. intros.\n  destruct H5.\n  rewrite H6. clear y H6.\n  rewrite metric_sym.\n  + apply extension_approximation_seq_cauchy_aux.\n  + exact R_metric_is_metric.\n- apply Rle_lt_trans with (Rabs ((2/3)^m) + Rabs((2/3)^n)).\n  + rewrite <- (Rabs_Ropp ((2/3)^n)).\n    unfold Rminus.\n    apply Rabs_triang.\n  + replace eps with (eps/2 + eps/2) by field.\n    apply Rplus_lt_compat;\n      now apply H2.\nQed.\n\nDefinition Tietze_extension_func : X -> RTop.\nrefine (proj1_sig (proj1_sig (constructive_definite_description\n  (fun f:(UniformTopology R_metric (fun _:X => 0)\n                    R_metric_is_metric X_nonempty) =>\n  net_limit convert_approx_to_uniform_space f\n    (I:=nat_DS) (X:=UniformTopology R_metric (fun _:X => 0)\n                    R_metric_is_metric X_nonempty)) _))).\napply -> unique_existence.\nsplit.\n- assert (complete (uniform_metric R_metric (fun _:X => 0)\n                      R_metric_is_metric X_nonempty)\n            (uniform_metric_is_metric _ _ _ _ _ _)).\n  { apply uniform_metric_complete.\n    exact R_metric_complete. }\n  apply H.\n  exact extension_approximation_seq_cauchy.\n- apply Hausdorff_impl_net_limit_unique.\n  apply T3_sep_impl_Hausdorff.\n  apply normal_sep_impl_T3_sep.\n  apply metrizable_impl_normal_sep.\n  exists (uniform_metric R_metric (fun _:X => 0)\n            R_metric_is_metric X_nonempty).\n  + apply (uniform_metric_is_metric _ _ R_metric (fun _:X => 0)\n              R_metric_is_metric X_nonempty).\n  + apply MetricTopology_metrized.\nDefined.\n\nLemma Tietze_extension_func_bound: forall x:X,\n  -1 <= Tietze_extension_func x <= 1.\nProof.\nintros.\ncut (Rabs (Tietze_extension_func x) <= 1).\n{ intros.\n  unfold Rabs in H.\n  destruct Rcase_abs in H; lra. }\nunfold Tietze_extension_func.\ndestruct constructive_definite_description as [[g]].\nsimpl.\nassert (bound (Im Full_set (fun x:X => R_metric 0 0))).\n{ exists 0.\n  red. intros.\n  destruct H.\n  right.\n  rewrite H0.\n  apply R_metric_is_metric. }\napply Rle_trans with (uniform_metric _ _ R_metric_is_metric X_nonempty\n                    (exist _ (fun _:X => 0) H)\n                    (exist _ g b)).\n- unfold uniform_metric.\n  simpl.\n  destruct sup.\n  simpl.\n  apply i.\n  exists x.\n  + constructor.\n  + unfold R_metric.\n    f_equal.\n    auto with real.\n- apply lt_plus_epsilon_le.\n  intros.\n  unshelve refine (let H1:=metric_space_net_limit_converse _ _ _ _ _ _ n eps H0 in _); [ | | clearbody H1 ]; shelve_unifiable.\n  { apply MetricTopology_metrized. }\n  destruct H1 as [N].\n  refine (Rle_lt_trans _ _ _\n    (triangle_inequality _ _ _ _ (convert_approx_to_uniform_space N) _) _).\n  { apply uniform_metric_is_metric. }\n  apply Rplus_lt_compat.\n  + apply Rle_lt_trans with (1 - (2/3)^N).\n    * unfold uniform_metric. simpl. destruct sup. simpl.\n      apply i.\n      red. intros.\n      destruct H2.\n      rewrite H3. clear y H3.\n      unfold R_metric.\n      destruct extension_approximation_seq as [h [? []]].\n      destruct (a x1).\n      simpl.\n      unfold Rabs. destruct Rcase_abs; lra.\n    * assert ((2/3)^N > 0).\n      { apply pow_lt; lra. }\n      lra.\n  + rewrite metric_sym.\n    * apply H1.\n      constructor.\n    * apply uniform_metric_is_metric.\nQed.\n\nLemma Tietze_extension_func_is_extension:\n  forall x:SubspaceTopology F,\n  Tietze_extension_func (subspace_inc F x) = f x.\nProof.\nintros.\napply R_metric_is_metric.\napply Rle_antisym.\n2: {\n  apply Rge_le, metric_nonneg, R_metric_is_metric.\n}\napply lt_plus_epsilon_le; intros.\nunfold Tietze_extension_func;\n  destruct constructive_definite_description as [[g]]; simpl.\nassert (eps/2 > 0) by lra.\nunshelve refine (let H1:=metric_space_net_limit_converse _ _ _ _ _ _ n (eps/2) H0\n          in _); [ | | clearbody H1 ]; shelve_unifiable.\n{ apply MetricTopology_metrized. }\ndestruct H1 as [N1].\nassert (Rabs (2/3) < 1).\n{ rewrite Rabs_right; lra. }\ndestruct (pow_lt_1_zero (2/3) H2 (eps/2) H0) as [N2].\npose (N := max N1 N2).\napply Rle_lt_trans with (R_metric (g (subspace_inc F x))\n          (proj1_sig (extension_approximation_seq N) (subspace_inc F x)) +\n  R_metric (proj1_sig (extension_approximation_seq N) (subspace_inc F x))\n    (f x)).\n{ apply triangle_inequality, R_metric_is_metric. }\nreplace (0+eps) with (eps/2+eps/2) by field.\napply Rplus_lt_compat.\n- rewrite metric_sym; try apply R_metric_is_metric.\n  assert (DS_ord N1 N) by apply le_max_l.\n  apply Rle_lt_trans with (2:=H1 N H4).\n  unfold uniform_metric; simpl; destruct sup; simpl.\n  apply i.\n  exists (subspace_inc F x).\n  { constructor. }\n  apply R_metric_is_metric.\n- assert ((N >= N2)%nat) by apply le_max_r.\n  apply Rle_lt_trans with (2:=H3 N H4).\n  rewrite Rabs_right.\n  + destruct extension_approximation_seq as [h [? []]]; simpl.\n    unfold R_metric.\n    destruct (a0 x).\n    unfold Rabs; destruct Rcase_abs; lra.\n  + apply Rle_ge, pow_le; lra.\nQed.\n\nLet convert_continuity: forall h:X -> R,\n  continuous h (Y:=RTop) <-> continuous h (Y:=MetricTopology R_metric\n                                           R_metric_is_metric).\nProof.\nassert (continuous (fun x:R => x)\n  (X:=RTop) (Y:=MetricTopology R_metric R_metric_is_metric)).\n{ apply pointwise_continuity.\n  intros.\n  apply metric_space_fun_continuity with R_metric R_metric;\n    intros.\n  - apply RTop_metrization.\n  - apply MetricTopology_metrized.\n  - now exists eps. }\nassert (continuous (fun x:R => x)\n  (X:=MetricTopology R_metric R_metric_is_metric) (Y:=RTop)).\n{ apply pointwise_continuity.\n  intros.\n  apply metric_space_fun_continuity with R_metric R_metric;\n    intros.\n  - apply MetricTopology_metrized.\n  - apply RTop_metrization.\n  - now exists eps. }\nintros.\nsplit; intros.\n- apply continuous_composition with (1:=H) (2:=H1).\n- apply continuous_composition with (1:=H0) (2:=H1).\nQed.\n\nLemma Tietze_extension_func_continuous: continuous Tietze_extension_func.\nProof.\nunfold Tietze_extension_func;\n  destruct constructive_definite_description as [g];\n  simpl.\napply net_limit_in_closure with\n  (S:=fun h:UniformTopology R_metric (fun _:X => 0)\n                          R_metric_is_metric X_nonempty =>\n     continuous (proj1_sig h)\n     (Y:=MetricTopology R_metric R_metric_is_metric)) in n.\n- rewrite closure_fixes_closed in n.\n  + unfold In in n.\n    now apply <- convert_continuity.\n  + apply continuous_functions_closed_in_uniform_metric.\n- red. intros.\n  exists i.\n  split.\n  + constructor.\n  + red.\n    unfold convert_approx_to_uniform_space. simpl.\n    destruct extension_approximation_seq as [h [? []]]. simpl.\n    now apply -> convert_continuity.\nQed.\n\nEnd Tietze_extension_construction.\n\nLemma bounded_Tietze_extension_theorem: forall (X:TopologicalSpace)\n  (F:Ensemble X) (f:SubspaceTopology F -> RTop),\n  normal_sep X -> closed F -> continuous f ->\n  (forall x:SubspaceTopology F, -1 <= f x <= 1) ->\n  exists g:X -> RTop,\n    continuous g /\\ (forall x:SubspaceTopology F,\n                     g (subspace_inc F x) = f x) /\\\n    (forall x:X, -1 <= g x <= 1).\nProof.\nintros.\ndestruct (classic (inhabited X)) as [Hinh|Hempty].\n- destruct (choice (fun\n    (FG:{FG:Ensemble X * Ensemble X | let (F,G):=FG in\n                      closed F /\\ closed G /\\ Intersection F G = Empty_set})\n    (phi:X -> RTop) =>\n     let (F,G):=proj1_sig FG in\n     continuous phi /\\ (forall x:X, 0 <= phi x <= 1) /\\\n     (forall x:X, In F x -> phi x = 0) /\\\n     (forall x:X, In G x -> phi x = 1))) as [choice_fun].\n  + intros.\n    destruct x as [[F' G] [? []]].\n    now apply UrysohnsLemma.\n  + pose (Urysohns_lemma_function := fun (F G:Ensemble X)\n      (HF:closed F) (HG:closed G) (Hdisj:Intersection F G = Empty_set) =>\n      exist (fun (f:X -> RTop) =>\n               continuous f /\\ (forall x:X, 0 <= f x <= 1) /\\\n               (forall x:X, In F x -> f x = 0) /\\\n               (forall x:X, In G x -> f x = 1))\n        (choice_fun (exist _ (F,G) (conj HF (conj HG Hdisj))))\n        (H3 (exist _ (F,G) (conj HF (conj HG Hdisj))))).\n    clearbody Urysohns_lemma_function. clear choice_fun H3.\n    exists (Tietze_extension_func X F H0 f H1 H2 Hinh\n      Urysohns_lemma_function).\n    split.\n    * apply Tietze_extension_func_continuous.\n    * split; intros.\n      ** apply Tietze_extension_func_is_extension.\n      ** apply Tietze_extension_func_bound.\n- exists (fun x:X => False_rect _ (Hempty (inhabits x))).\n  split.\n  + apply pointwise_continuity.\n    intros.\n    destruct (Hempty (inhabits x)).\n  + split;\n      intros.\n    * destruct x.\n      destruct (Hempty (inhabits x)).\n    * destruct (Hempty (inhabits x)).\nQed.\n\nLemma open_bounded_Tietze_extension_theorem: forall (X:TopologicalSpace)\n  (F:Ensemble X) (f:SubspaceTopology F -> RTop),\n  normal_sep X -> closed F -> continuous f ->\n  (forall x:SubspaceTopology F, -1 < f x < 1) ->\n  exists g:X -> RTop,\n    continuous g /\\ (forall x:SubspaceTopology F,\n                     g (subspace_inc F x) = f x) /\\\n    (forall x:X, -1 < g x < 1).\nProof.\nintros.\ndestruct (bounded_Tietze_extension_theorem _ F f) as [g0 [? []]]; trivial.\n{ intros. split; left; apply H2. }\npose (G := characteristic_function_to_ensemble (fun x:X =>\n  g0 x = 1 \\/ g0 x = -1)).\ndestruct (UrysohnsLemma _ H G F) as [phi [? [? []]]]; trivial.\n- replace G with (inverse_image g0 (Union (Singleton 1) (Singleton (-1)))).\n  + red. rewrite <- inverse_image_complement.\n    apply H3.\n    apply (closed_union2 (X:=RTop)); apply Hausdorff_impl_T1_sep;\n      apply T3_sep_impl_Hausdorff; apply normal_sep_impl_T3_sep;\n      apply metrizable_impl_normal_sep; exists R_metric;\n      (apply R_metric_is_metric || apply RTop_metrization).\n  + extensionality_ensembles_inv;\n      constructor.\n    * now left.\n    * now right.\n    * destruct H7;\n        [left | right ];\n        now rewrite H6.\n- extensionality_ensembles.\n  assert (-1 < g0 x < 1).\n  { change x with (subspace_inc F (exist _ x H7)).\n    now rewrite H4. }\n  lra.\n- exists (fun x => phi x * g0 x).\n  split.\n  { apply pointwise_continuity.\n    intros.\n    apply product_continuous;\n      now apply continuous_func_continuous_everywhere.\n  }\n  split.\n  { intros.\n    rewrite H9.\n    - replace (1*g0 (subspace_inc F x)) with (g0 (subspace_inc F x)) by\n        auto with real.\n      apply H4.\n    - now destruct x.\n  }\n  intros.\n  apply and_comm, Rabs_def2.\n  rewrite Rabs_mult.\n  rewrite (Rabs_right (phi x));\n    [ | apply Rle_ge; apply H7 ].\n  destruct (classic (In G x)).\n  { rewrite H8; trivial. lra. }\n  assert (Rabs (g0 x) < 1).\n  { assert (Rabs (g0 x) <= 1).\n    { destruct (H5 x).\n      unfold Rabs; destruct Rcase_abs; lra. }\n    destruct H11; trivial.\n    contradiction H10.\n    unfold Rabs in H11.\n    destruct Rcase_abs in H11;\n      constructor.\n    - lra.\n    - now left. }\n  destruct (H7 x).\n  apply Rle_lt_trans with (Rabs (g0 x)); trivial.\n  pattern (Rabs (g0 x)) at 2.\n  replace (Rabs (g0 x)) with (1*Rabs (g0 x)) by\n    auto with real.\n  apply Rmult_le_compat_r; trivial.\n  apply Rabs_pos.\nQed.\n\nTheorem Tietze_extension_theorem: forall (X:TopologicalSpace)\n  (F:Ensemble X) (f:SubspaceTopology F -> RTop),\n  normal_sep X -> closed F -> continuous f ->\n  exists g:X -> RTop,\n    continuous g /\\ (forall x:SubspaceTopology F,\n                     g (subspace_inc F x) = f x).\nProof.\nintros.\npose (U := characteristic_function_to_ensemble\n      (fun x:RTop => -1 < x < 1)).\npose proof (open_interval_homeomorphic_to_real_line).\nfold U in H2.\nsimpl in H2.\ndestruct H2 as [a [b]].\npose (f0 := fun x:SubspaceTopology F => subspace_inc U (a (f x))).\ndestruct (open_bounded_Tietze_extension_theorem X F f0) as [g0 [? []]];\n  trivial.\n- unfold f0.\n  apply continuous_composition.\n  + apply subspace_inc_continuous.\n  + now apply continuous_composition.\n- intros.\n  unfold f0.\n  destruct (a (f x)).\n  now destruct i.\n- assert (forall x:X, In U (g0 x)).\n  { intros.\n    constructor.\n    apply H8. }\n  pose (g0_U := continuous_factorization g0 U H9).\n  assert (continuous g0_U) by\n    now apply factorization_is_continuous.\n  exists (fun x:X => b (g0_U x)).\n  split.\n  { now apply continuous_composition. }\n  intros.\n  unfold g0_U, continuous_factorization.\n  generalize (H9 (subspace_inc F x)).\n  rewrite H7.\n  intros.\n  replace (exist _ (f0 x) i) with (a (f x)) by\n    now apply (proj1_sig_injective (In U)).\n  apply H4.\nQed.\n", "meta": {"author": "coq-community", "repo": "topology", "sha": "f784257d0b9c316601440e4f02256bd6068e4f94", "save_path": "github-repos/coq/coq-community-topology", "path": "github-repos/coq/coq-community-topology/topology-f784257d0b9c316601440e4f02256bd6068e4f94/theories/Topology/TietzeExtension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7239931341364512}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp.analysis Require Import reals classical_sets boolp.\nFrom mathcomp Require Import zify algebra_tactics.ring.\nRequire Import tactics mathcomp_extras.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory Num.Theory.\nOpen Scope classical_set_scope.\nOpen Scope real_scope.\n\n(* Topological facts about sets of points in R^d, \n * in a more elementary way than mathcomp.analysis.topology. *)\n\nSection PointTopo.\n\nVariables (R : realType) (d : nat).\nNotation point := 'M[R]_(1, d).\n\nSection EuclidNorm.\nImplicit Types (x y : point) (s t : R).\nOpen Scope ring_scope.\n\nDefinition norm (x : point) : R := Num.sqrt ((x *m x^T) ord0 ord0). \n\nLemma norm_scalel x (s : R) : norm (s *: x) = `|s| * norm x.\nProof. \n  rewrite /norm trmx_scale scale_mulmx mxE -expr2 sqrtrM.\n  by rewrite sqrtr_sqr.\n  by rewrite sqr_ge0.\nQed.\n\nLemma norm_scaler x (s : R) : norm (s *: x) = norm x * `|s|.\nProof. by rewrite norm_scalel mulrC. Qed.\n\nLemma norm_ge0if x : (0 <= norm x ?= iff (x == 0))%R.\nProof. \n  split ; first by rewrite sqrtr_ge0.\n  apply /idP ; case: ifP => [/eqP ->|].\n    by rewrite /norm mul0mx mxE sqrtr0.\n  move /negbT => H ; apply /idP ; move: H ; apply contra.\n  rewrite eq_sym /norm sqrtr_eq0 => xxT_le0.\n  apply /eqP ; apply matrixP => i j ; rewrite mxE.\n  have: i = 0 by case: i => [i Hi] ; apply val_inj => /= ; lia. move->.\n  have xxT_ge0 : (x *m x^T) ord0 ord0 >= 0.\n    by rewrite mxE ; apply sumr_ge0if => k _ ; rewrite mxE -expr2 sqr_ge0.\n  have xxT_eq0 : (x *m x^T) ord0 ord0 == 0.\n    by rewrite Order.POrderTheory.eq_le xxT_le0 xxT_ge0.\n  clear xxT_ge0 xxT_le0 ; move: xxT_eq0.\n  rewrite mxE eq_sym sumr_ge0if /= ; last first => [k _ | /forallP /(_ j)].\n    by rewrite mxE -expr2 sqr_ge0.\n  by rewrite mxE -expr2 sqrf_eq0 => /eqP ->. \nQed.\n\nLemma norm0 : norm 0 = 0.\nProof. \n  move: (eqxx (GRing.zero (matrix_zmodType R 1 d))). \n  by rewrite -norm_ge0if eq_sym => /eqP.\nQed. \n\nLemma normN x : norm (-x) = norm x.\nProof. by rewrite -scaleN1r norm_scalel normrN1 mul1r. Qed.\n\nEnd EuclidNorm.\n\nSection OpenSets.\nImplicit Types (S : set point) (x : point).\n\n(* A simple (i.e. without filters) definition of an open set of points *)\nDefinition openS_near S x :=\n  exists2 eps : R, (eps > 0)%R & forall y, (norm (x - y) <= eps)%R -> S y.\nDefinition openS S := {in S, forall x, openS_near S x }.\n\nLemma openS_near_scale S x u : \n  openS_near S x -> exists2 l, (l > 0)%R & S (x + l%:M *m u)%R.\nProof. \n  rewrite /openS_near /= => [[eps eps_gt0 Heps]].\n  case: (u =P 0)%R => [->|neq_u0].\n    exists (GRing.one (Num.NumDomain.ringType R)) => //.\n    rewrite mulmx0 addr0 ; apply Heps.\n    by rewrite subrr norm0 ; apply Order.POrderTheory.ltW.\n  have l_gt0 : (0 < eps / norm u)%R.\n    apply mulr_gt0 ; rewrite ?invr_gt0 //.\n    move: neq_u0=> /eqP ; apply contraR ; rewrite -Order.TotalTheory.leNgt => H.\n    by rewrite -norm_ge0if Order.POrderTheory.eq_le H norm_ge0if.\n  exists (eps / norm u)%R => //.\n  apply Heps ; rewrite opprD addrA subrr sub0r normN mul_scalar_mx norm_scalel.\n  rewrite gtr0_norm // -mulrA mulVr ?mulr1 //.\n  by rewrite unitfE eq_sym norm_ge0if ; apply /eqP.\nQed.\n\nLemma openS_setT : openS (@setT point).\nProof. \n  rewrite /openS /openS_near /= => x _.\n  by exists (GRing.one (Num.NumDomain.ringType R)).\nQed.\n\nLemma le_min (x y z : R) : (x <= Num.min y z)%R <-> (x <= y)%R && (x <= z)%R.\nProof. Admitted.\n  (*case: (Num.Theory.ltrP y z) => [/Order.POrderTheory.ltW|] Oyz ;\n  apply is_true_inj ; apply propext ; split.\n  - move=> le_xy. apply /andP ; split => //. Search transitive. apply Order.MeetJoinMixin.le_trans.*)\n\nLemma openS_near_cap m (P : set 'I_m) F x :\n  (forall i, P i -> openS_near (F i) x) -> \n  openS_near (\\bigcap_(i in P) F i) x.\nProof.\n  elim: m F P => [|m IH] F1 P1 Oi.\n    exists (GRing.one (Num.NumDomain.ringType R)) => // y _ i.\n    by rewrite (set_ord0 P1) /=.\n  pose F0 := (fun i : 'I_m => F1 (widen_ord (leqnSn m) i)).\n  pose P0 := [set i | P1 (widen_ord (leqnSn m) i)].\n  have Oi' : forall i : 'I_m, P0 i -> openS_near (F0 i) x => [i|].\n    by rewrite /P0 /F0 /= ; apply Oi.\n  move: (Oi ord_max) (IH F0 P0 Oi') ; rewrite /openS_near /= => Om {}IH.\n  case: (asboolP (P1 ord_max)) IH => P1om [e1 lt_0e1 IH] ;\n  [move: P1om=> /Om [e2 lt_0e2 {}Om]|pose e2 := e1] ;\n  exists (Num.min e1 e2) ; (try by case: (Num.Theory.ltrP e1 e2)) ;\n  rewrite /bigcap /= => y /le_min/andP[le_De1 le_De2] i P1i ;\n  move: (IH y le_De1) ; rewrite /bigcap /= => {}IH ;\n  case: (widen_ordP i) P1i => [ |j] P1i.\n  - by apply Om.\n  - by apply IH ; rewrite /P0 //=.\n  - by intuition.\n  - by apply IH ; rewrite /P0 //=. \nQed.\n\nLemma openS_cap m (P : set 'I_m) F :\n  (forall i, P i -> openS (F i)) -> openS (\\bigcap_(i in P) F i).\nProof. \n  rewrite /bigcap /openS /= => Oi x ; rewrite in_setE /= => Fx.\n  apply openS_near_cap => /= i Pi ; apply Oi => //. \n  by rewrite in_setE ; apply Fx.\nQed.\n\n\nEnd OpenSets.\n\nEnd PointTopo.", "meta": {"author": "MathisBD", "repo": "coq-arrangements", "sha": "fd13e9d1fa366aab85e560bc92197702a96fd74c", "save_path": "github-repos/coq/MathisBD-coq-arrangements", "path": "github-repos/coq/MathisBD-coq-arrangements/coq-arrangements-fd13e9d1fa366aab85e560bc92197702a96fd74c/theories/point_topo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7239748840672942}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) : natural := mult lf2 (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj93_coqofml_XhgD8b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7239748796583864}}
{"text": "(** This file contains definitions of and lemmas about the real \nfunctional model **)\n\n\nFrom Coq Require Import ZArith Reals Psatz.\nFrom Coq Require Import Arith.Arith.\nFrom Coquelicot Require Import Coquelicot.\nFrom mathcomp.analysis Require Import Rstruct.\nFrom mathcomp Require Import matrix all_ssreflect all_algebra ssralg ssrnum bigop.\n\nSet Bullet Behavior \"Strict Subproofs\". \n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFrom Iterative Require Import lemmas.\nImport List ListNotations.\n\nOpen Scope R_scope.\nOpen Scope ring_scope.\n\nDelimit Scope ring_scope with Ri.\nDelimit Scope R_scope with Re.\n\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\n\n(*** Functional model for the iterative solution ***)\n\n(** Specialized to the Jacobi iterate for the symmetric tridiagonal\n    matrix:\n    (1'h^2) [2 -1 0; -1 2 -1; 0 -1 2]\n**)\n(** define a tridiagonal system **)\nDefinition A (n:nat) (h:R) := \\matrix_(i<n, j<n)\n   if (i==j :> nat) then (2 / h^2) %Re else\n      (if ((i-j)%N==1%N :>nat) then (-1 / h^2)%Re else\n            (if ((j-i)%N==1%N :>nat) then (-1/ h^2)%Re else 0)).\n\nDefinition A1 (n:nat) (h:R) := \\matrix_(i < n, j < n)\n      if (i == j :> nat) then (A n h) i j else 0.\n\nDefinition A2 (n:nat) (h:R) := \\matrix_(i < n, j < n)\n  ((A n h) i j - (A1 n h) i j).\n  \nDefinition inv_A1 (n:nat) (h:R) := \\matrix_(i < n, j < n)\n      if (i == j :> nat) then (1/ (A1 n h) i j) else 0.\n\n\nDefinition S_mat (n:nat) (h:R) := -(inv_A1 n h) *m (A2 n h).\n\nDefinition b_real : list R := [1;1;1].\n\n\nFixpoint X_m_real (m n:nat) (x0 b: 'cV[R]_n) (h:R) : 'cV[R]_n:=\n  match m with\n  | O => x0\n  | S p => S_mat n h *m (X_m_real p x0 b h) + inv_A1 n h *m b\n  end.\n\nLemma X_m_real_iter {n:nat} (k: nat) (x0 b: 'cV[R]_n) (h:R) :\n    let xkr := X_m_real k x0 b h in\n    X_m_real k.+1 x0 b h = X_m_real 1 xkr b h.\nProof. simpl; auto. Qed.\n\n\nClose Scope R_scope. \n", "meta": {"author": "VeriNum", "repo": "iterative_methods", "sha": "7507d713cceaf91d9493dab620d3583438b8bc8a", "save_path": "github-repos/coq/VeriNum-iterative_methods", "path": "github-repos/coq/VeriNum-iterative_methods/iterative_methods-7507d713cceaf91d9493dab620d3583438b8bc8a/SC_workshop/real_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7239748752494783}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREER SOFTWARE LICENSE AGREEMENT         *)\n(**************************************************************)\n\nRequire Import List Arith Wellfounded.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nSection measure_rect.\n\n  Variable (X : Type) (m : X -> nat) (P : X -> Type).\n\n  Hypothesis F : forall x, (forall y, m y < m x -> P y) -> P x.\n\n  Definition measure_rect x : P x.\n  Proof.\n    cut (Acc (fun x y => m x < m y) x); [ revert x | ].\n    + refine (\n        fix loop x Dx := @F x (fun y Dy => loop y _)\n      ).\n      apply (Acc_inv Dx), Dy.\n    + apply wf_inverse_image with (f := m), lt_wf.\n  Qed.\n\nEnd measure_rect.\n\nTactic Notation \"induction\" \"on\" hyp(x) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n  pattern x; revert x; apply measure_rect with (m := fun x => f); intros x IH.\n\nSection less_than_wf.\n\n  Variable (X : Type) (R : X -> X -> Prop) (Rwf : well_founded R).\n\n  Reserved Notation \"l '<lex' m\" (at level 70).  (* for lexicographic product *)\n  Reserved Notation \"l '<<' m\" (at level 70).    (* for less than *)\n\n  Inductive lex : list X -> list X -> Prop :=\n    | lex_skip x l m : l <lex m -> x::l <lex x::m\n    | lex_cons x y l m : length l = length m -> R x y -> x::l <lex y::m\n  where \"l <lex m\" := (lex l m).\n\n  Fact lex_length l m : l <lex m -> length l = length m.\n  Proof. induction 1; simpl; auto. Qed.\n\n  Fact lex_cons_inv l m : \n          l <lex m \n       -> match m with\n            | [] => False\n            | y::m =>\n            match l with\n              | [] => False\n              | x::l => x = y /\\ lex l m \n                     \\/ R x y /\\ length l = length m\n            end\n          end.\n  Proof. inversion 1; auto. Qed.\n\n  (* Proof of Acc lex m by nested induction on:\n       - induction the length of m (IHm)\n       - if m = [] then finished (no l exists st l <lex [])\n       - if m = x::m' then  \n         * we know Acc lex m' (by IHm)\n         * induction on x using Rfw\n         * induction on (Acc lex m')\n  *) \n\n  Theorem lex_wf : well_founded lex.\n  Proof.\n    intros m; induction on m as IHm with measure (length m).\n    destruct m as [ | y m ].\n    + constructor; intros l Hl; apply lex_cons_inv in Hl; easy.\n    + revert m IHm.\n      induction y as [ y IHy' ] using (well_founded_induction Rwf).\n      intros m IHm.\n      assert (Acc lex m) as Hm.\n      1: apply IHm; simpl; auto.\n      assert (forall x l, R x y -> length l = length m -> Acc lex (x::l)) as IHy.\n      1: { intros x l Hx Hl; apply IHy'; auto.\n           intros; apply IHm.\n           simpl in *; rewrite <- Hl; auto. }\n      clear IHy' IHm.\n      revert Hm IHy.\n      induction 1 as [ m Hm IHm ]; intros IHy.\n      constructor; intros l Hl; apply lex_cons_inv in Hl.\n      destruct l as [ | x l ]; try tauto.\n      destruct Hl as [ (-> & Hl) | (Hx & Hl) ].\n      * apply IHm; auto.\n        apply lex_length in Hl as ->; auto.\n      * apply IHy; auto.\n  Qed.\n\n  Inductive less_than : list X -> list X -> Prop :=\n    | less_than_lt l m : length l < length m -> l << m\n    | less_than_eq l m : lex l m -> l << m\n  where \"l << m\" := (less_than l m).\n\n  Fact less_than_inv l m : l << m -> length l < length m \\/ lex l m.\n  Proof. inversion 1; auto. Qed.\n\n  Theorem less_than_wf : well_founded less_than.\n  Proof.\n    intros m.\n    induction on m as IHm with measure (length m).\n    revert IHm; generalize (lex_wf m).\n    induction 1 as [ m Hm IHm ]; intros H.\n    constructor; intros l Hl.\n    apply less_than_inv in Hl as [ Hl | Hl ].\n    + apply H; auto.\n    + apply IHm; auto.\n      intros; apply H.\n      now apply lex_length in Hl as <-.\n  Qed.\n\n  Section less_than_rect.\n\n    Variable (P : list X -> Type)\n             (HP : forall m, (forall l, length l < length m -> P l)\n                          -> (forall l, lex l m -> P l)\n                          -> P m).\n\n    Corollary less_than_rect m : P m.\n    Proof.\n      induction m as [ m IHm ] using (well_founded_induction_type less_than_wf).\n      apply HP; intros; apply IHm.\n      + now constructor 1.\n      + now constructor 2.\n    Qed.\n  \n  End less_than_rect.\n\nEnd less_than_wf.", "meta": {"author": "ianshil", "repo": "CE_GL4ip", "sha": "199cde58e85cafe738a7085192a185aaeb164833", "save_path": "github-repos/coq/ianshil-CE_GL4ip", "path": "github-repos/coq/ianshil-CE_GL4ip/CE_GL4ip-199cde58e85cafe738a7085192a185aaeb164833/GL4ip/DLW_WO_list_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.723974871622357}}
{"text": "Require Import Lia.\nRequire Import NArith. Open Scope N_scope.\n\n(* Type class definition *)\nModule Type Bound.\n  (* Type *)\n  Parameter t : Type.\n\n  (* Constants *)\n  Parameter MIN : t.\n  Parameter MAX : t.\n\n  (* Computational functions *)\n  Parameter pred : t -> t.\n  Parameter succ : t -> t.\n\n  (* Comparison operators *)\n  Parameter eq : t -> t -> Prop.\n  Parameter le : t -> t -> Prop.\n  Parameter lt : t -> t -> Prop.\n\n  (* Prove decidability of operators *)\n  Axiom eq_dec : forall x y, {eq x y} + {~ eq x y}.\n  Axiom le_dec : forall x y, {le x y} + {~ le x y}.\n  Axiom lt_dec : forall x y, {lt x y} + {~ lt x y}.\n\n  (* Properties of eq for use in proofs *)\n  Axiom eq_refl : forall x, eq x x.\n\n  (* Properties of le for use in proofs *)\n  Axiom le_refl : forall x, le x x.\n  Axiom le_antisymm : forall x y, le x y -> le y x -> x = y.\n  Axiom le_trans : forall x y z, le x y -> le y z -> le x z.\n\n  (* Properties of lt for use in proofs *)\n  Axiom lt_irrefl : forall x, ~ lt x x.\n  Axiom lt_asymm : forall x y, lt x y -> ~ lt y x.\n  Axiom lt_trans : forall x y z, lt x y -> lt y z -> lt x z.\n\n  (* Properties of bounds, relating constants, operators, and functions *)\n  Axiom le_succ_r : forall x y, le x y -> le x (succ y).\n  Axiom le_pred_l : forall x y, le x y -> le (pred x) y.\n  Axiom le_pred_lt : forall x y, lt MIN x -> le x (pred y) -> lt x y.\n  Axiom lt_succ_le : forall x y, lt x MAX -> le (succ x) y -> lt x y.\nEnd Bound.\n\n(* Type class instance *)\nModule Byte <: Bound.\n\nRecord byte := mkbyte {\n  val : N;\n  range : val < 256;\n}.\n\nDefinition t := byte.\n\nDefinition MIN : byte := mkbyte 0 eq_refl.\nDefinition MAX : byte := mkbyte 255 eq_refl.\n\nDefinition eq (x y : byte) : Prop := N.eq x.(val) y.(val).\nDefinition le (x y : byte) : Prop := N.le x.(val) y.(val).\nDefinition lt (x y : byte) : Prop := N.lt x.(val) y.(val).\n\nTheorem eq_dec : forall x y, {eq x y} + {~ eq x y}.\nProof.\n  unfold eq. destruct x, y. intros. cbn.\n  destruct (N.eqb val0 val1) eqn:?.\n  - left. now apply N.eqb_eq.\n  - right. now apply N.eqb_neq.\nQed.\n\nTheorem le_dec : forall x y, {le x y} + {~ le x y}.\nProof.\n  unfold le. destruct x, y. intros. cbn.\n  destruct (N.leb val0 val1) eqn:?.\n  - left. now apply N.leb_le.\n  - right. now apply N.leb_nle.\nQed.\n\nTheorem lt_dec : forall x y, {lt x y} + {~ lt x y}.\nProof.\n  unfold lt. destruct x, y. intros. cbn.\n  destruct (N.ltb val0 val1) eqn:?.\n  - left. now apply N.ltb_lt.\n  - right. now apply N.ltb_nlt.\nQed.\n\nLemma N_succ_range : forall x, ~ eq x MAX -> N.succ x.(val) < 256.\nProof. unfold eq, N.eq. destruct x. cbn. lia. Qed.\n\nDefinition succ (x : byte) : byte :=\n  match eq_dec x MAX with\n  | left _ => x\n  | right pf => mkbyte (N.succ x.(val)) (N_succ_range _ pf)\n  end.\n\nDefinition pred (x : byte) : byte :=\n  match eq_dec x MIN with\n  | left _ => mkbyte (N.pred x.(val)) (N.lt_lt_pred _ _ x.(range))\n  | right _ => x\n  end.\n\nTheorem eq_refl : forall x, eq x x. Admitted.\n\nTheorem le_refl : forall x, le x x. Admitted.\nTheorem le_antisymm : forall x y, le x y -> le y x -> x = y. Admitted.\nTheorem le_trans : forall x y z, le x y -> le y z -> le x z. Admitted.\n\nTheorem lt_irrefl : forall x, ~ lt x x. Admitted.\nTheorem lt_asymm : forall x y, lt x y -> ~ lt y x. Admitted.\nTheorem lt_trans : forall x y z, lt x y -> lt y z -> lt x z. Admitted.\n\nTheorem le_succ_r : forall x y, le x y -> le x (succ y). Admitted.\nTheorem le_pred_l : forall x y, le x y -> le (pred x) y. Admitted.\nTheorem le_pred_lt : forall x y, lt MIN x -> le x (pred y) -> lt x y. Admitted.\nTheorem lt_succ_le : forall x y, lt x MAX -> le (succ x) y -> lt x y. Admitted.\n\nEnd Byte.\n", "meta": {"author": "thaliaarchi", "repo": "pl-papers", "sha": "587ecb9ce7e8db554c2a06129eadcaea8b0aae07", "save_path": "github-repos/coq/thaliaarchi-pl-papers", "path": "github-repos/coq/thaliaarchi-pl-papers/pl-papers-587ecb9ce7e8db554c2a06129eadcaea8b0aae07/ahp/module_type_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7239748672134491}}
{"text": "Require Import ssreflect Arith.\nRequire Import Arith.EqNat.\nRequire Import Arith.Compare_dec.\nRequire Import List.\nRequire Import Omega.\n\nDefinition var := nat.\n\nInductive term :=\n| Var : var -> term\n| Lambda: term -> term\n| App: term -> term -> term.\n\nLemma lambda_equivalence: forall t u: term, t = u <-> (Lambda t = Lambda u).\nProof.\n  move => t u.\n  split;(move => h0).\n  rewrite h0.\n  done.\n  inversion h0.\n  trivial.\nQed.\n\nLemma app_equivalence: forall t u v w: term, App t u = App v w <-> (t = v) /\\ (u = w).\nProof.\n  move => t u v w.\n  split.\n  move => h0.\n  split.\n  inversion h0.\n  done.\n  inversion h0.\n  done.\n  move => [h0 h1].\n  rewrite h0.\n  rewrite h1.\n  done.\nQed.\n\nFixpoint C (i: nat) (t: term): Prop :=\n  match t with\n    | Var v => (v < i) \n    | App t1 t2 => (C i t1) /\\ (C i t2)\n    | Lambda t1 => C (i+1) t1\n  end.\n\n(*Question 1.2*)\nLemma ind_C_pred: forall t: term, forall n: nat, C n t -> C (n+1) t.\nProof.\n  induction t.\n  move => n.\n  simpl.\n  move => h0.\n  Search _ (_<_).\n  apply Plus.lt_plus_trans.\n  done.\n  move => n.\n  simpl.\n  move => h0.\n  apply IHt.\n  done.\n  simpl.\n  move => n.\n  move => [h0 h1].\n  split.\n  apply IHt1.\n  done.\n  apply IHt2.\n  done.  \nQed.\n  \n(*\n ^ k\n |\n | n\n *)\n(*Lifting used to do substitutions*)\n\nFixpoint lifting (n: nat) (k: nat) (t: term): term :=\n  match t with\n    | Var i => if leb k i then Var (i+n) else Var i\n    | App t1 t2 => App (lifting n k t1) (lifting n k t2)\n    | Lambda t1 => Lambda (lifting n (k+1) t1)\n  end.\n\nFixpoint substitution (i: nat) (t1: term) (t2: term): term :=\n  match t1 with\n    | Var v => if beq_nat i v then t2 else Var v\n    | App t3 t4 => App (substitution i t3 t2) (substitution i t4 t2)\n    | Lambda t3 => Lambda (substitution (i+1) t3 (lifting 1 0 t2))\n  end.\n\n(*Same as lifting, only we do it in a list - equivalent to map (lifting n k) l*)\nFixpoint lift_all (n: nat) (k: nat) (l: list term): list term :=\n  match l with\n    | nil => nil\n    | x :: xs => (lifting n k x) :: (lift_all n k xs)\n  end.\n\nFixpoint multiple_substitution (i: nat) (t: term) (lu: list term): term :=\n  match t with\n    | Var v => if (leb i v) && (leb v (i+(length lu)-1)) then substitution v (Var v) (nth (v - i) lu (Var 0))  else Var v\n    | App t1 t2 => App (multiple_substitution i t1 lu) (multiple_substitution i t2 lu)\n    | Lambda t1 => Lambda (multiple_substitution (i+1) t1 (lift_all 1 0 lu))\n  end.\n\n", "meta": {"author": "pedrohaa", "repo": "untypedCoq", "sha": "89ba50c6c306a4e8b2a9d2114ccf1e944bacf8cf", "save_path": "github-repos/coq/pedrohaa-untypedCoq", "path": "github-repos/coq/pedrohaa-untypedCoq/untypedCoq-89ba50c6c306a4e8b2a9d2114ccf1e944bacf8cf/untypedLambda.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7239748652695903}}
{"text": "Set Implicit Arguments.\n\nInductive mylist (a : Set) : nat -> Set :=\n  MyNull : mylist a 0\n| MyCons : forall n, a -> mylist a n -> mylist a (S n).\n\n(* Require Import Coq.Program.Tactics Coq.Logic.JMeq. *)\n(* Program  *)\n\nFixpoint append (a : Set) (k k' : nat) (x : mylist a k) \n                (y : mylist a k') : mylist a (k+k') :=\n  match x with\n    MyNull _ => y\n  | @MyCons _ p hd tl =>\n      @MyCons _ _ hd (@append _ _ _ tl y)\nend.\n\nPrint append.\nPrint mylist.\n\nFixpoint length a k (x : mylist a k) : nat :=\n  match x with\n | MyNull _ => 0\n | MyCons hd tl => 1 + length tl\nend.\n\nPrint length.\n\nDefinition bool_len n (x : mylist bool n) :=\n  @length bool n x.\n\nPrint bool_len.\n\nLtac ByDefinition ident := \n  unfold ident; fold ident.\n\nRequire Import Omega.\n\nLtac ByLawsOfArithmetic' :=\ntry apply gt_Sn_n;\ntry apply eq_S.\n\nLtac ByLawsOfArithmetic :=\nByLawsOfArithmetic';\nauto.\n\nTheorem LowHanging : forall a k (x : mylist a k),\n  @length a k x = k.\n\nintros a k x.\ninduction x as [|n hd tl IH];\nByDefinition length;\nByLawsOfArithmetic.\n\n\n  exact IH.\n\nQed.\n\n(* Theorem LowHanging' : forall a k (x : mylist a k),\n  @length a k x = k.\n\nrefine (fun a k x => _).\nrefine (match x with \n          MyNull _ => _\n        | @MyCons _ p hd tl => _\n        end).\nrefine (ltac:(unfold length)).\nrefine (eq_refl 0).\nrefine (ltac:(unfold length)).\nrefine (ltac:(fold length)).\nPrint LowHanging.\n *)\n\n\n", "meta": {"author": "rinderknecht", "repo": "Coq", "sha": "8c25f60c8aad69f7c7ff0c9b3289f1824cf65543", "save_path": "github-repos/coq/rinderknecht-Coq", "path": "github-repos/coq/rinderknecht-Coq/Coq-8c25f60c8aad69f7c7ff0c9b3289f1824cf65543/mylist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338729, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7238663101506023}}
{"text": "Load \"10_map_rev.v\".\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p).\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z f x y.\n  unfold prod_uncurry.\n  unfold prod_curry.\n  simpl.\n  reflexivity.\nQed.\n\n\nLemma wat : forall (X Y : Type) (p : X * Y), (fst p, snd p) = p.\nProof.\n  intros X Y p.\n  destruct p. (* destructure *)\n  simpl.\n  reflexivity.\nQed.\n\nLemma wat' : forall (X Y : Type) (p : X * Y), (fst p, snd p) = p.\nProof.\n  intros X Y p.\n  case p. (* case analysis on the p : prod *)\n  (* the only case is that it's a pair since it's the only constructor for prod *)\n  intros proof_x proof_y.\n  simpl.\n  reflexivity.\nQed.\n\nPrint pair.\nPrint prod.\n\nCheck wat.\nSearch (forall (X Y : Type) (p : X * Y), (fst p, snd p) = p).\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  unfold prod_uncurry.\n  unfold prod_curry.\n  rewrite wat.\n  reflexivity.\nQed.\n", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/4_Poly/16_currying.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.843895098628499, "lm_q1q2_score": 0.7238662995610041}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  mult y (plus lf2 Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj205_coqofml_5iSD3V.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480244025281, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7236992414230998}}
{"text": "Definition pierce := forall (p q : Prop),\n  ((p -> q) -> p) -> p.\n\nDefinition lem := forall p, p\\/ ~ p.\n\nTheorem pierce_equiv_lem: pierce <-> lem.\n\nProof.\n  unfold pierce, lem.\n  firstorder.\n  apply H with (q := ~ (p \\/ ~p)).\n  firstorder.\n  destruct (H p).\n  assumption.\n  tauto.\nQed.", "meta": {"author": "sguzman", "repo": "CoqRepo", "sha": "e802df1540b7cff7dad5731c6abfcbf8e669f44e", "save_path": "github-repos/coq/sguzman-CoqRepo", "path": "github-repos/coq/sguzman-CoqRepo/CoqRepo-e802df1540b7cff7dad5731c6abfcbf8e669f44e/pierce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7236992298163712}}
{"text": "Require Export Init.Notations.\nRequire Import Init.Logic.\nRequire Import Init.Classical.\nRequire Import Init.Axiom.\n\n(* Operators *)\nDefinition subset (A B: J) := (∀ x, x ∈ A → x ∈ B).\nNotation   \"x ⊆ y\"         := (subset x y).\n\nDefinition proper_subset (A B: J) := ((subset A B) ∧ A ≠ B).\nNotation   \"x ⊂ y\"                := (proper_subset x y).\n\nDefinition empty_c := (ex_outl ax_empty).\nNotation   \"∅\"     := (empty_c).\n\nDefinition pair_c (A B: J) := (ex_outl (ax_pair A B)).\nNotation   \"`{ x , y }\"    := (pair_c x y).\n\nDefinition singleton (A: J) := (pair_c A A).\nNotation   \"`{ x }\"         := (singleton x).\n\nDefinition union_c (A: J) := (ex_outl (ax_union A)).\nNotation   \"∪ A \"         := (union_c A).\n\nDefinition union2_c (A B: J) := (∪(`{A, B})).\nNotation   \"A ∪ B\"           := (union2_c A B).\n\nDefinition power_c (A: J) := (ex_outl (ax_power A)).\nNotation   \"𝒫( x )\"       := (power_c x).\n\nDefinition sub_c (P: J → Prop) (x: J) := (ex_outl (ax_subset P x)).\nNotation   \"{ x : A | P }\"            := (sub_c (λ x, P) A).\n\nDefinition inter_c (A: J) := ({x: ∪A| ∀ a, a ∈ A → x ∈ a}).\nNotation   \"∩ A\"          := (inter_c A).\n\nDefinition inter2_c (A B: J) := ({x: A| x ∈ B}).\nNotation   \"A ∩ B\"           := (inter2_c A B).\n\nDefinition complement (A B : J) := ({x: A| x ∉ B}).\nNotation   \"A \\ B\"              := (complement A B).\n\nDefinition opair (A B: J) := `{`{A}, `{A, B}}.\nNotation  \"⟨ A , B ⟩\"     := (opair A B).\n\nDefinition in_cp (x A B: J) := ∃ a, ∃ b, a ∈ A ∧ b ∈ B ∧ x = ⟨a, b⟩.\nDefinition cp (A B: J)      := {x: 𝒫(𝒫(A ∪ B))| in_cp x A B}.\nNotation   \"A ⨉ B\"          := (cp A B).\n(*----------------------------------------------------------------------------*)\n\n(* Basic Properties *)\n\n(* Subset *)\nLemma sub_a: ∀ A, ∀ B, A ⊆ B ∧ B ⊆ A → A = B.\nProof.\n  intros A B [P1 P2].\n  apply ax_exten.\n  intro x.\n  split.\n  + apply (P1 x).\n  + apply (P2 x).\nQed.\n\nLemma sub_r: ∀ A, A ⊆ A.\nProof.\n  intros A x P.\n  apply P.\nQed.\n\nLemma sub_t: ∀ A, ∀ B, ∀ C, A ⊆ B → B ⊆ C → A ⊆ C.\nProof.\n  intros A B C P1 P2 x P3.\n  apply ((P2 x) ((P1 x) P3)).\nQed.\n\nLemma sub_i_eq: ∀ A, ∀ B, A = B → A ⊆ B.\nProof.\n  intros A B P1.\n  apply (eq_cl _ P1).\n  apply sub_r.\nQed.\n\nLemma ax_exten_reverse: ∀ A, ∀ B, A = B → (∀ x, x ∈  A ↔ x ∈  B).\nProof.\n  intros A B P1 x.\n  apply (eq_cl (λ s, x ∈ A ↔ x ∈ s) P1).\n  apply iff_r.\nQed.\n\nLemma sub_reduce: ∀ₚ P, ∀ A, (∀ x, (P x) → x ∈ A) → (∃ B, ∀ y, y ∈ B ↔ (P y)).\nProof.\n  intros P A P1.\n  exists {x : A | P x}.\n  intros x.\n  destruct (ex_outr (ax_subset P A) x) as [P2 P3].\n  split.\n  + apply P2.\n  + intros P4.\n    apply P3.\n    apply (and_i (P1 x P4) P4).\nQed.\n\nLemma sub_i: ∀ₚ P, ∀ A, ∀ x, x ∈ A → (P x) → x ∈ {y: A| P y}.\nProof.\n  intros P A x P1 P2.\n  destruct (ex_outr (ax_subset P A) x) as [_ P3].\n  apply P3.\n  apply (and_i P1 P2).\nQed.\n\nLemma sub_e: ∀ₚ P, ∀ A, ∀ x, x ∈  {y: A| P y} → x ∈ A ∧ (P x).\nProof.\n  intros P A x P1.\n  destruct (ex_outr (ax_subset P A) x) as [P2 _].\n  apply (P2 P1).\nQed.\n\nLemma sub_e1: ∀ₚ P, ∀ A, {y: A| P y} ⊆ A.\nProof.\n  intros P A x P1.\n  destruct (sub_e _ _ _ P1) as [P2 _].\n  apply P2.\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Non Equality *)\nLemma neq_e: ∀ A, ∀ B, A ≠ B → ∃ x, (x ∈ A ∧ x ∉  B) ∨ (x ∈ B ∧ x ∉  A).\nProof.\n  intros A B.\n  apply contraposition2.\n  intros P1.\n  apply sub_a.\n  split.\n  + intros x P2. \n    destruct (not_or_and (not_ex_all_not _ P1 x)) as [P3 _].\n    destruct (not_and_or P3) as [P4 | P4].\n    - apply (bot_e _ (P4 P2)).\n    - apply (nn_e P4). \n  + intros x P2.\n    destruct (not_or_and (not_ex_all_not _ P1 x)) as [_ P3].\n    destruct (not_and_or P3) as [P4 | P4].\n    - apply (bot_e _ (P4 P2)).\n    - apply (nn_e P4). \nQed.\n\nLemma neq_i: ∀ A, ∀ B, ∀ x, x ∈ A → x ∉  B → A ≠ B.\nProof.\n  intros A B x P1 P2 P3.\n  apply (P2 (eq_cl _ P3 P1)).\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Proper Subset *)\nLemma psub_i: ∀ A, ∀ B, A ⊆ B → A ≠ B → A ⊂ B.\nProof.\n  intros A B P1 P2.\n  apply (and_i P1 P2).\nQed.\n\nLemma psub_i1: ∀ A, ∀ B, (∀ x, x ∈ A → x ∈ B) → (∃ y, y ∈ A ∧ y ∉  B) → A ⊂ B.\nProof.\n  intros A B P1 [y [P2 P3]].\n  split.\n  + intros x P4.\n    apply (P1 _ P4).\n  + apply (neq_i _ _ _ P2 P3).\nQed.\n\nLemma psub_e: ∀ A, ∀ B, A ⊂ B → A ⊆ B.\nProof.\n  intros A B [P1 _].\n  apply P1.\nQed.\n\nLemma psub_e1: ∀ A, ∀ B, A ⊂ B → A ≠ B.\nProof.\n  intros A B [_ P1].\n  apply P1.\nQed.\n\nLemma psub_e2: ∀ A, ∀ B, A ⊂ B → ∃ x, x ∉ A ∧ x ∈ B.\nProof.\n  intros A B [P1 P2].\n  destruct (neq_e _ _ P2) as [x [[P3 P4] | [P3 P4]]].\n  + apply bot_e.\n    apply P4.\n    apply (P1 _ P3).\n  + exists x.\n    apply (and_i P4 P3).\nQed.\n\nLemma psub_ir: ∀ A, ~ A ⊂ A.\nProof.\n  intros A P1.\n  apply (psub_e1 _ _ P1).\n  apply eq_r.\nQed.\n\nLemma sub_e2: ∀ A, ∀ B, A ⊆ B → A ⊂ B ∨ A = B.\nProof.\n  intros A B P1.\n  destruct (LEM (A = B)) as [P2 | P2].\n  + right.\n    apply P2.\n  + left.\n    apply (psub_i _ _ P1 P2).\nQed.\n\nLemma psub_t: ∀ A, ∀ B, ∀ C, A ⊂ B → B ⊂ C → A ⊂ C.\nProof.\n  intros A B C P1 P2.\n  apply psub_i.\n  + intros x P3.\n    pose (psub_e _ _ P1 _ P3) as P4.\n    apply (psub_e _ _ P2 _ P4).\n  + destruct (psub_e2 _ _ P1) as [x [P3 P4]].\n    apply neq_s.\n    apply (neq_i _ _ x).\n    - apply (psub_e _ _ P2 _ P4).\n    - apply P3.\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Empty Set *)\nLemma empty_i: ∀ A, A ∉  ∅.\nProof.\n  intro A.\n  apply (ex_outr ax_empty A).\nQed.\n\nLemma empty_i1: ∀ A, ∅ ⊆ A.\nProof.\n  intros A x P1.\n  apply (bot_e _ (empty_i _ P1)).\nQed.\n\nLemma empty_unique: ∀ A, (∀ B, B ∉ A) → A = ∅ .\nProof.\n  intros A P1.\n  apply ax_exten.\n  intro x.\n  split.\n  + intro P3. \n    apply (bot_e _ (P1 _ P3)).\n  + intro P3.\n    apply (bot_e _ (empty_i _ P3)).\nQed.\n\nLemma nempty_ex: ∀ A, A ≠ ∅  → (∃ x, x ∈ A).\nProof.\n  intros A.\n  apply contraposition2.\n  intro P1.\n  apply empty_unique.\n  apply not_ex_all_not.\n  apply P1. \nQed.\n\nLemma ex_nempty: ∀ A, (∃ x, x ∈ A) → A ≠ ∅.\nProof.\n  intros A [x P1] P2.\n  apply (empty_i x).\n  apply (eq_cl _ P2 P1).\nQed.\n\nLemma sub_empty: ∀ₚ P, ∀ A, ∀ t, {y: A| P y} = ∅ → t ∈ A → ~(P t).\nProof.\n  intros P A t P1 P2 P3.\n  apply (empty_i t).\n  apply (eq_cl _ P1).\n  apply (sub_i _ _ _ P2 P3).\nQed.\n\nLemma sub_empty_empty: ∀ S, S ⊆ ∅ → S = ∅.\nProof.\n  intros S P1.\n  apply sub_a.\n  split.\n  + intros x P2.\n    apply (P1 _ P2).\n  + intros x P2.\n    apply bot_e.\n    apply (empty_i _ P2).\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Power set *)\nLemma power_e: ∀ A, ∀ x, x ∈ 𝒫(A) → x ⊆ A.\nProof.\n  intros A x P1 y P2.\n  destruct (ex_outr (ax_power A) x) as [P3 _].\n  apply (P3 P1 _ P2).\nQed.\n\nLemma power_i: ∀ A, ∀ x, x ⊆ A → x ∈ 𝒫(A).\nProof.\n  intros A x P1.\n  destruct (ex_outr (ax_power A) x) as [_ P2].\n  apply (P2 P1).\nQed.\n\nLemma in_power: ∀ A, A ∈ 𝒫(A).\nProof.\n  intros A.\n  apply power_i.\n  apply sub_r.\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Union *)\nLemma union_e: ∀ A, ∀ x, x ∈ ∪(A) → (∃ y, y ∈ A ∧ x ∈ y).\nProof.\n  intros A x P1.\n  destruct (ex_outr (ax_union A) x) as [P2 _].\n  apply (P2 P1).\nQed.\n\nLemma union_i: ∀ A, ∀ x, (∃ y, y ∈ A ∧ x ∈ y) → x ∈ ∪(A).\nProof.\n  intros A x P1.\n  destruct (ex_outr (ax_union A) x) as [_ P2].\n  apply (P2 P1).\nQed.\n\nLemma union_i2: ∀ A, ∀ x, x ∈ A → x ⊆ ∪A.\nProof.\n  intros A x P1 s P2.\n  apply union_i.\n  exists x.\n  apply (and_i P1 P2).\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Pair and Singleton *)\nLemma pair_e: ∀ A, ∀ B, ∀ x, x ∈ `{A, B} → x = A ∨ x = B.\nProof.\n  intros A B x P1.\n  destruct (ex_outr (ax_pair A B) x) as [P2 _].\n  apply (P2 P1).\nQed.\n\nLemma pair_il: ∀ A, ∀ B, A ∈ `{A, B}.\nProof.\n  intros A B.\n  destruct (ex_outr (ax_pair A B) A) as [_ P2].\n  apply P2.\n  left.\n  apply eq_r.\nQed.\n\nLemma pair_ir: ∀ A, ∀ B, B ∈ `{A, B}.\nProof.\n  intros A B.\n  destruct (ex_outr (ax_pair A B) B) as [_ P2].\n  apply P2.\n  right.\n  apply eq_r.\nQed.\n\nLemma pair_s: ∀ A, ∀ B, `{A, B} = `{B, A}.\nProof.\n  intros A B.\n  apply sub_a.\n  split.\n  + intros x P1.\n    destruct (pair_e _ _ _ P1) as [P2 | P2].\n    - apply (eq_cr (λ y, y ∈ `{B, A}) P2).\n      apply pair_ir.\n    - apply (eq_cr (λ y, y ∈ `{B, A}) P2).\n      apply pair_il.\n  + intros x P1.\n    destruct (pair_e _ _ _ P1) as [P2 | P2].\n    - apply (eq_cr (λ y, y ∈ `{A, B}) P2).\n      apply pair_ir.\n    - apply (eq_cr (λ y, y ∈ `{A, B}) P2).\n      apply pair_il.\nQed.\n\nLemma pair_eql: ∀ A, ∀ B, ∀ C, ∀ D, `{A, B} = `{C, D} → A = C ∨ A = D.\nProof.\n  intros A B C D P1.\n  pose (pair_il A B) as P2.\n  pose (eq_cl _ P1 P2) as P3.\n  apply (pair_e _ _ _ P3). \nQed.\n\nLemma pair_eqr: ∀ A, ∀ B, ∀ C, ∀ D, `{A, B} = `{C, D} → B = C ∨ B = D.\nProof.\n  intros A B C D P1.\n  pose (pair_ir A B) as P2.\n  pose (eq_cl _ P1 P2) as P3.\n  apply (pair_e _ _ _ P3). \nQed.\n\nLemma sing_i: ∀ A, A ∈ `{A}.\nProof.\n  intros A.\n  destruct (ex_outr (ax_pair A A) A) as [_ P1].\n  apply P1.\n  left.\n  apply eq_r.\nQed.\n\nLemma sing_i2: ∀ A, ∀ B, A = B → A ∈ `{B}.\nProof.\n  intros A B P1.\n  apply (eq_cl (λ x, A ∈ `{x}) P1).\n  apply sing_i.\nQed.\n\nLemma sing_e: ∀ A, ∀ B, B ∈ `{A} → A = B.\nProof.\n  intros A B P1.\n  destruct (ex_outr (ax_pair A A) B) as [P2 _].\n  destruct (P2 P1) as [P3 | P3].\n  + apply eq_s.\n    apply P3.\n  + apply eq_s.\n    apply P3.\nQed.\n\nLemma nsing_i: ∀ A, ∀ B, A ≠ B → B ∉ `{A}.\nProof.\n  intros A B.\n  apply contraposition1.\n  apply sing_e.\nQed.\n\nLemma nsing_e: ∀ A, ∀ B, B ∉ `{A} → A ≠ B.\nProof.\n  intros A B.\n  apply contraposition1.\n  intros P1.\n  generalize (eq_s P1).\n  apply sing_i2.\nQed.\n  \nLemma sing_sub_i: ∀ A, ∀ B, A ∈ B → `{A} ⊆ B.\nProof.\n  intros A B P1 x P2.\n  apply (eq_cl (λ x, x ∈ B) (sing_e _ _ P2)).\n  apply P1.\nQed.\n\nLemma sing_sub_e: ∀ A, ∀ B, `{A} ⊆ B → A ∈ B.\nProof.\n  intros A B P1.\n  apply P1.\n  apply sing_i.\nQed.\n\nLemma sing_nempty: ∀ A, `{A} ≠ ∅.\nProof.\n  intros A.\n  apply ex_nempty.\n  exists A.\n  apply sing_i.\nQed.\n\nLemma sing_pair_eq1: ∀ A, ∀ B, ∀ C, `{A} = `{B, C} → A = B.\nProof.\n  intros A B C P1.\n  apply sing_e.\n  apply (eq_cr _ P1).\n  apply pair_il.\nQed.\n\nLemma sing_pair_eq2: ∀ A, ∀ B, ∀ C, `{A} = `{B, C} → A = C.\nProof.\n  intros A B C P1.\n  pose (eq_t P1 (pair_s B C)) as P2.\n  apply (sing_pair_eq1 _ _ _ P2).\nQed.\n\nLemma sing_pair_eq3: ∀ A, ∀ B, ∀ C, `{A} = `{B, C} → B = C.\nProof.\n  intros A B C P1.\n  pose (eq_s (sing_pair_eq1 _ _ _ P1)) as P2.\n  pose (sing_pair_eq2 _ _ _ P1) as P3.\n  apply (eq_t P2 P3).\nQed.\n\nLemma sing_eq: ∀ A, ∀ B, `{A} = `{B} → A = B.\nProof.\n  intros A B P1.\n  apply sing_e.\n  apply (eq_cr _ P1).\n  apply sing_i.\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Union of Two *)\nLemma union2_e: ∀ A, ∀ B, ∀ x, x ∈ A ∪ B → x ∈ A ∨ x ∈ B.\nProof.\n  intros A B x P1.\n  destruct (union_e _ _ P1) as [a [P2 P3]].\n  destruct (pair_e _ _ _ P2) as [P4 | P4].\n  + left.\n    apply (eq_cl (λ y, x ∈ y) P4).\n    apply P3.\n  + right.\n    apply (eq_cl (λ y, x ∈ y) P4).\n    apply P3.\nQed.\n\nLemma union2_il: ∀ A, ∀ B, ∀ x, x ∈ A → x ∈ A ∪ B.\nProof.\n  intros A B x P1.\n  apply union_i.\n  exists A.\n  split.\n  + apply pair_il.\n  + apply P1.\nQed.\n\nLemma union2_ir: ∀ A, ∀ B, ∀ x, x ∈ B → x ∈ A ∪ B.\nProof.\n  intros A B x P1.\n  apply union_i.\n  exists B.\n  split.\n  + apply pair_ir.\n  + apply P1.\nQed.\n\nLemma union2_en: ∀ A, ∀ B, ∀ x, x ∉ A ∪ B → x ∉ A ∧ x ∉ B.\nProof.\n  intros A B x P1.\n  split.\n  + intros P2.\n    apply P1.\n    apply (union2_il _ _ _ P2).\n  + intros P2.\n    apply P1.\n    apply (union2_ir _ _ _ P2).\nQed.\n\nLemma union2_s: ∀ A, ∀ B, A ∪ B = B ∪ A.\nProof.\n  intros A B.\n  apply sub_a.\n  split.\n  + intros x P1.\n    destruct (union2_e _ _ _ P1) as [P2 | P2].\n    - apply (union2_ir _ _ _ P2).\n    - apply (union2_il _ _ _ P2).\n  + intros x P1.\n    destruct (union2_e _ _ _ P1) as [P2 | P2].\n    - apply (union2_ir _ _ _ P2).\n    - apply (union2_il _ _ _ P2).\nQed.\n\nLemma union2_sub: ∀ A, ∀ B, ∀ C, A ⊆ C → B ⊆ C → A ∪ B ⊆ C.\nProof.\n  intros A B C P1 P2 x P3.\n  destruct (union2_e _ _ _ P3) as [P4 | P4].\n  + apply (P1 _ P4).\n  + apply (P2 _ P4).\nQed.\n\nLemma union2_sub_l: ∀ A, ∀ B, A ⊆ A ∪ B.\nProof.\n  intros A B x P1.\n  apply union2_il.\n  apply P1.\nQed.\n\nLemma union2_sub_r: ∀ A, ∀ B, B ⊆ A ∪ B.\nProof.\n  intros A B x P1.\n  apply union2_ir.\n  apply P1.\nQed.\n\nLemma union2_sub_absorb_l: ∀ A, ∀ B, A ⊆ B → A ∪ B = B.\nProof.\n  intros A B P1.\n  apply sub_a.\n  split.\n  + intros x P2.\n    destruct (union2_e _ _ _ P2) as [P3 | P3].\n    - apply (P1 _ P3).\n    - apply P3.\n  + intros x P2.\n    apply (union2_ir _ _ _ P2).\nQed.\n\nLemma union2_sub_absorb_r: ∀ A, ∀ B, A ⊆ B → B ∪ A = B.\nProof.\n  intros A B P1.\n  apply (eq_t (union2_s B A)).\n  apply (union2_sub_absorb_l _ _ P1).\nQed.\n\nLemma union2_empty_absorb_l: ∀ A, ∅ ∪ A = A.\nProof.\n  intros A.\n  apply sub_a.\n  split.\n  + intros x P1.\n    destruct (union2_e _ _ _ P1) as [P2 | P2].\n    - apply bot_e. \n      apply (empty_i _ P2).\n    - apply P2.\n  + intros x P1.\n    apply (union2_ir _ _ _ P1).\nQed.\n\nLemma union2_empty_absorb_r: ∀ A, A ∪ ∅ = A.\nProof.\n  intros A.\n  apply (eq_t (union2_s A ∅)).\n  apply union2_empty_absorb_l.\nQed.\n\nLemma union2_sub_weak_l: ∀ A, ∀ B, ∀ C, C ⊆ A → C ⊆ (A ∪ B).\nProof.\n  intros A B C P1 x P2.\n  apply union2_il.\n  apply (P1 _ P2).\nQed.\n\nLemma union2_sub_weak_r: ∀ A, ∀ B, ∀ C, C ⊆ B → C ⊆ (A ∪ B).\nProof.\n  intros A B C P1 x P2.\n  apply union2_ir.\n  apply (P1 _ P2).\nQed.\n\nLemma union2_sub_preserve_l: ∀ A, ∀ A', ∀ B, A ⊆ A' → A ∪ B ⊆ A' ∪ B.\nProof.\n  intros A A' B P1 x P2.\n  destruct (union2_e _ _ _ P2) as [P3 | P3].\n  + apply (union2_il _ _ _ (P1 _ P3)).\n  + apply (union2_ir _ _ _ P3).\nQed.\n\nLemma union2_sub_preserve_r: ∀ A, ∀ B, ∀ B', B ⊆ B' → A ∪ B ⊆ A ∪ B'.\n  intros A A' B P1 x P2.\n  destruct (union2_e _ _ _ P2) as [P3 | P3].\n  + apply (union2_il _ _ _ P3).\n  + apply (union2_ir _ _ _ (P1 _ P3)).\nQed.\n\nLemma union2_sing_e: ∀ A, ∀ a, ∀ x, x ∈ A ∪ `{a} → x ∈ A ∨ x = a.\nProof.\n  intros A a x P1.\n  destruct (union2_e _ _ _ P1) as [P2 | P2].\n  + left.\n    apply P2.\n  + right.\n    apply (eq_s (sing_e _ _ P2)).\nQed.\n\nLemma union2_sing_il: ∀ A, ∀ a, ∀ x, x ∈ A → x ∈ A ∪ `{a}.\nProof.\n  intros A a x.\n  apply union2_il.\nQed.\n\nLemma union2_sing_ir: ∀ A, ∀ a, a ∈ A ∪ `{a}.\nProof.\n  intros A a.\n  apply union2_ir.\n  apply sing_i.\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Intersection *)\nLemma inter_e: ∀ A, ∀ x, x ∈ ∩A → (∀ a, a ∈ A → x ∈ a).\nProof.\n  intros A x P1 a P2.\n  destruct (sub_e _ _ _ P1) as [_ P3].\n  apply (P3 _ P2).\nQed.\n\nLemma inter_i: ∀ A, ∀ x, A ≠ ∅ → (∀ a, a ∈ A → x ∈ a) → x ∈ ∩A.\nProof.\n  intros A x P1 P2.\n  apply sub_i.\n  + apply union_i.\n    destruct (nempty_ex _ P1) as [a P3].\n    exists a.\n    split.\n    - apply P3.\n    - apply (P2 _ P3).\n  + apply P2.\nQed.\n\nLemma inter_sub: ∀ A, ∀ a, a ∈ A → ∩A ⊆ a.\nProof.\n  intros A a P1 x P2.\n  apply (inter_e _ _ P2 _ P1).\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Intersection of Two *)\nLemma inter2_e: ∀ A, ∀ B, ∀ x, x ∈ A ∩ B → x ∈ A ∧ x ∈ B.\nProof.\n  intros A B.\n  apply sub_e.\nQed.\n\nLemma inter2_i: ∀ A, ∀ B, ∀ x, x ∈ A → x ∈ B → x ∈ A ∩ B.\nProof.\n  intros A B.\n  apply sub_i.\nQed.\n\nLemma inter2_s: ∀ A, ∀ B, A ∩ B = B ∩ A.\nProof.\n  intros A B.\n  apply sub_a.\n  split.\n  + intros x P1.\n    destruct (inter2_e _ _ _ P1) as [P2 P3].\n    apply (inter2_i _ _ _ P3 P2).\n  + intros x P1.\n    destruct (inter2_e _ _ _ P1) as [P2 P3].\n    apply (inter2_i _ _ _ P3 P2).\nQed.\n  \nLemma inter2_sub_l: ∀ A, ∀ B, A ∩ B ⊆ A.\nProof.\n  intros A B x P1.\n  destruct (inter2_e _ _ _ P1) as [P2 _].\n  apply P2.\nQed.\n\nLemma inter2_sub_r: ∀ A, ∀ B, A ∩ B ⊆ B.\nProof.\n  intros A B.\n  apply (eq_cl (λ x, x ⊆ B) (inter2_s B A)).\n  apply inter2_sub_l.\nQed.\n\nLemma inter2_absorb_l: ∀ A, ∀ B, A ⊆ B → A ∩ B = A.\nProof.\n  intros A B P1.\n  apply sub_a.\n  split.\n  + intros x P2.\n    destruct (inter2_e _ _ _ P2) as [P3 _].\n    apply P3.\n  + intros x P2.\n    apply inter2_i.\n    - apply P2.\n    - apply (P1 _ P2).\nQed.\n\nLemma inter2_absorb_r: ∀ A, ∀ B, B ⊆ A → A ∩ B = B.\nProof.\n  intros A B P1.\n  apply (eq_cr (λ x, x = B) (inter2_s _ _)).\n  apply (inter2_absorb_l _ _ P1).\nQed.\n\nLemma inter2_eq_sub_l: ∀ A, ∀ B, A ∩ B = A → A ⊆ B.\nProof.\n  intros A B P1 x P2.\n  pose (eq_cr (λ y, x ∈ y) P1 P2) as P3.\n  destruct (inter2_e _ _ _ P3) as [_ P4].\n  apply P4.\nQed.\n\nLemma inter2_eq_sub_r: ∀ A, ∀ B, A ∩ B = B → B ⊆ A.\nProof.\n  intros A B P1.\n  apply inter2_eq_sub_l.\n  apply (eq_cr (λ x, x = B) (inter2_s _ _)).\n  apply P1.\nQed.\n\nLemma inter2_empty: ∀ A, ∀ B, (∀ x, x ∈ A → x ∉ B) → A ∩ B = ∅.\nProof.\n  intros A B P1.\n  apply sub_a.\n  split.\n  + intros x P2.\n    destruct (inter2_e _ _ _ P2) as [P3 P4].\n    apply bot_e.\n    apply (P1 _ P3 P4).\n  + intros x P2.\n    apply bot_e.\n    apply (empty_i _ P2).\nQed.\n\nLemma sub_inter2: ∀ A, ∀ B, ∀ C, C ⊆ A → C ⊆ B → C ⊆ A ∩ B.\nProof.\n  intros A B C P1 P2 x P3.\n  apply inter2_i.\n  + apply (P1 x P3).\n  + apply (P2 x P3).\nQed.\n\nLemma sub_inter2_el: ∀ A, ∀ B, ∀ C, C ⊆ A ∩ B → C ⊆ A.\nProof.\n  intros A B C P1 x P2.\n  destruct (inter2_e _ _ _ (P1 x P2)) as [P3 _].\n  apply P3.\nQed.\n \nLemma sub_inter2_er: ∀ A, ∀ B, ∀ C, C ⊆ A ∩ B → C ⊆ B.\nProof.\n  intros A B C.\n  apply (eq_cl (λ x, C ⊆ x → C ⊆ B) (inter2_s B A)).\n  apply sub_inter2_el.\nQed.\n\nLemma disjoint_selection: ∀ A, ∀ B, ∀ x, A ∩ B = ∅ → x ∈ A ∪ B → \n  (x ∈ A ∧ x ∉  B) ∨ (x ∈ B ∧ x ∉  A).\nProof.\n  intros A B x P1 P2.\n  destruct (union2_e _ _ _ P2) as [P3 | P3].\n  + left.\n    split.\n    - apply P3.\n    - intros P4.\n      apply bot_e.\n      apply (empty_i x).\n      apply (eq_cl _ P1).\n      apply (inter2_i _ _ _ P3 P4).\n  + right.\n    split.\n    - apply P3.\n    - intros P4.\n      apply bot_e.\n      apply (empty_i x).\n      apply (eq_cl _ P1).\n      apply (inter2_i _ _ _ P4 P3).\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Complement *)\nLemma compl_i: ∀ A, ∀ B, ∀ x, x ∈ A → x ∉  B → x ∈ A \\ B.\nProof.\n  intros A B x P1 P2.\n  apply (sub_i _ _ _ P1 P2).\nQed.\n\nLemma compl_e: ∀ A, ∀ B, ∀ x, x ∈ A \\ B → x ∈ A ∧ x ∉  B.\nProof.\n  intros A B x P1.\n  apply (sub_e _ _ _ P1).\nQed.\n\nLemma compl_exchange: ∀ A, ∀ B, ∀ C, A \\ B \\ C = A \\ C \\ B.\nProof.\n  intros A B C.\n  apply sub_a.\n  split.\n  + intros x P1.\n    destruct (compl_e _ _ _ P1) as [P2 P3].\n    destruct (compl_e _ _ _ P2) as [P4 P5].\n    apply compl_i.\n    - apply compl_i.\n      * apply P4.\n      * apply P3.\n    - apply P5.\n  + intros x P1.\n    destruct (compl_e _ _ _ P1) as [P2 P3].\n    destruct (compl_e _ _ _ P2) as [P4 P5].\n    apply compl_i.\n    - apply compl_i.\n      * apply P4.\n      * apply P3.\n    - apply P5.\nQed.\n\nLemma compl_inter2: ∀ A, ∀ B, A ∩ (B \\ A) = ∅.\nProof.\n  intros A B.\n  apply sub_a.\n  split.\n  + intros x P1.\n    destruct (inter2_e _ _ _ P1) as [P2 P3].\n    destruct (compl_e _ _ _ P3) as [_ P4].\n    apply (bot_e _ (P4 P2)).\n  + intros x P1.\n    apply (bot_e _ (empty_i _ P1)). \nQed.\n\nLemma compl_inter2_2: ∀ A, ∀ B, A ∩ (A \\ B)= A \\ B.\nProof.\n  intros A B.\n  apply sub_a.\n  split.\n  + intros x P1.\n    destruct (inter2_e _ _ _ P1) as [_ P2].\n    apply P2.\n  + intros x P1.\n    destruct (compl_e _ _ _ P1) as [P2 _].\n    apply inter2_i.\n    - apply P2.\n    - apply P1.\nQed.\n\nLemma compl_dilemma: ∀ A, ∀ B, ∀ x, x ∈ A → x ∈ A ∩ B ∨ x ∈ A \\ B.\nProof.\n  intros A B x P1.\n  destruct (LEM (x ∈ B)) as [P2 | P2].\n  + left.\n    apply (inter2_i _ _ _ P1 P2).\n  + right.\n    apply (compl_i _ _ _ P1 P2).\nQed.\n\nLemma compl_union2: ∀ A, ∀ B, A ∪ (B \\ A) = A ∪ B.\nProof.\n  intros A B.\n  apply sub_a.\n  split.\n  + intros x P1.\n    destruct (union2_e _ _ _ P1) as [P2 | P2].\n    - apply (union2_il _ _ _ P2).\n    - destruct (compl_e _ _ _ P2) as [P3 _].\n      apply (union2_ir _ _ _ P3).\n  + intros x P1.\n    destruct (union2_e _ _ _ P1) as [P2 | P2].\n    - apply (union2_il _ _ _ P2).\n    - destruct (LEM (x ∈ A)) as [P3 | P3].\n      * apply (union2_il _ _ _ P3).\n      * apply (union2_ir _ _ _ (compl_i _ _ _ P2 P3)).\nQed.\n\nLemma compl_sub: ∀ A, ∀ B, (A \\ B) ⊆ A.\nProof.\n  intros A B x P1.\n  destruct (compl_e _ _ _ P1) as [P2 _].\n  apply P2.\nQed.\n\nLemma compl_psub: ∀ A, ∀ B, B ⊆ A → B ≠ ∅ → A \\ B ⊂ A.\nProof.\n  intros A B P1 P2.\n  apply psub_i.\n  + apply compl_sub.\n  + intros P3.\n    destruct (nempty_ex _ P2) as [x P4].\n    pose (eq_cr (λ y, x ∈ y) P3 (P1 _ P4)) as P5.\n    destruct (compl_e _ _ _ P5) as [_ P6].\n    apply (P6 P4).\nQed.\n\nLemma compl_sub_reverse: ∀ A, ∀ B1, ∀ B2, B1 ⊆ B2 → A \\ B2 ⊆ A \\ B1.\nProof.\n  intros A B1 B2 P1 x P2.\n  destruct (compl_e _ _ _ P2) as [P3 P4].\n  apply compl_i.\n  + apply P3.\n  + intros P5.\n    apply P4.\n    apply (P1 _ P5).\nQed.\n\nLemma compl_psub_ex: ∀ A, ∀ B, A ⊂ B → ∃ x, x ∈ B \\ A.\nProof.\n  intros A B [P1 P2].\n  destruct (neq_e _ _ P2) as [x P3].\n  exists x.\n  destruct P3 as [[P3 P4] | [P3 P4]].\n  + apply (bot_e _ (P4 (P1 _ P3))).\n  + apply (compl_i _ _ _ P3 P4).\nQed.\n\nLemma compl_psub_nempty: ∀ A, ∀ B, A ⊂ B → B \\ A ≠ ∅.\nProof.\n  intros A B P1.\n  apply ex_nempty.\n  apply (compl_psub_ex _ _ P1).\nQed.\n\nLemma compl_empty: ∀ A, ∀ B, A \\ B = ∅ → A ⊆ B.\nProof.\n  intros A B P1 x P2.\n  apply nn_e.\n  intros P3.\n  apply (empty_i x).\n  apply (eq_cl (λ s, x ∈ s) P1).\n  apply (compl_i _ _ _ P2 P3).\nQed.\n\nLemma compl_union2_annihilate: ∀ A, ∀ B, B ⊆ A → (A \\ B) ∪ B = A.\nProof.\n  intros A B P1.\n  apply sub_a.\n  split.\n  + intros x P2.\n    destruct (union2_e _ _ _ P2) as [P3 | P3].\n    - destruct (compl_e _ _ _ P3) as [P4 _].\n      apply P4.\n    - apply (P1 _ P3).\n  + intros x P2.\n    destruct (LEM (x ∈ B)) as [P3 | P3].\n    - apply union2_ir.\n      apply P3.\n    - apply union2_il.\n      apply compl_i.\n      * apply P2.\n      * apply P3.\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Order Pairs *)\nLemma opair_e: ∀ A, ∀ B, ∀ x, x ∈ ⟨A, B⟩ → x = `{A} ∨ x = `{A, B}.\nProof.\n  intros A B x P1.\n  apply (pair_e _ _ _ P1).\nQed.\n\n(* 3A *)\nTheorem opair_eq_i: ∀ A, ∀ B, ∀ C, ∀ D, (A = C) → (B = D) → ⟨A, B⟩ = ⟨C, D⟩.\nProof.\n  intros A B C D P1 P2.\n  apply (eq_cl (λ x, ⟨A, B⟩ = ⟨x, D⟩) P1).\n  apply (eq_cl (λ x, ⟨A, B⟩ = ⟨A, x⟩) P2).\n  apply eq_r.\nQed.\n\nTheorem opair_eq_e: ∀ A, ∀ B, ∀ C, ∀ D, ⟨A, B⟩ = ⟨C, D⟩ → (A = C) ∧ (B = D).\nProof.\n  intros A B C D P1.\n  destruct (pair_eql _ _ _ _ P1) as [P2 | P2].\n  + destruct (pair_eqr _ _ _ _ (eq_s P1)) as [P3 | P3].\n    - split.\n      * apply (sing_eq _ _ P2).\n      * destruct (pair_eqr _ _ _ _ P1) as [P4 | P4].\n        ++apply (eq_cl _ (sing_pair_eq2 _ _ _ (eq_s P3))).\n          apply (eq_s (sing_pair_eq3 _ _ _ (eq_s P4))).\n        ++destruct (pair_eqr _ _ _ _ P4) as [P5 | P5].\n          --apply (eq_t P5). \n            apply (sing_pair_eq3 _ _ _ (eq_s P3)).\n          --apply P5.\n    - split.\n      * apply (sing_eq _ _ P2).\n      * destruct (pair_eqr _ _ _ _ P3) as [P4 | P4].\n        ++destruct (pair_eqr _ _ _ _ (eq_s P3)) as [P5 | P5].\n          --apply (eq_t P5).\n            apply (eq_t (sing_eq _ _ (eq_s P2))).\n            apply (eq_s P4).\n          --apply P5.\n        ++apply (eq_s P4).\n  + split.\n    - apply (sing_pair_eq1 _ _ _ P2).\n    - destruct (pair_eqr _ _ _ _ P1) as [P3 | P3].\n      * apply (eq_t (eq_s (sing_pair_eq3 _ _ _ (eq_s P3)))).\n        apply (sing_pair_eq2 _ _ _ P2).\n      * destruct (pair_eqr _ _ _ _ P3) as [P4 | P4].\n        ++apply(eq_t P4).\n          apply (sing_pair_eq3 _ _ _ P2).\n        ++apply P4.\nQed.\n\nTheorem opair_eq_el: ∀ A, ∀ B, ∀ C, ∀ D, ⟨A, B⟩ = ⟨C, D⟩ → A = C.\nProof.\n  intros A B C D P1.\n  destruct (opair_eq_e _ _ _ _ P1) as [P2 _].\n  apply P2.\nQed.\n\nTheorem opair_eq_er: ∀ A, ∀ B, ∀ C, ∀ D, ⟨A, B⟩ = ⟨C, D⟩ → B = D.\nProof.\n  intros A B C D P1.\n  destruct (opair_eq_e _ _ _ _ P1) as [_ P2].\n  apply P2.\nQed.\n\nLemma opair_superset: ∀ A, ∀ B, ∀ C, A ∈ C → B ∈ C → ⟨A, B⟩ ∈ 𝒫(𝒫(C)).\nProof.\n  intros A B C P1 P2.\n  apply power_i.\n  intros x P3.\n  apply power_i.\n  intros y P4.\n  destruct (pair_e _ _ _ P3) as [P5 | P5].\n  + apply (eq_cl (λ x, x ∈ C) (sing_e _ _ (eq_cl _ P5 P4))).\n    apply P1.\n  + destruct (pair_e _ _ _ (eq_cl (λ x, y ∈ x) P5 P4)) as [P6 | P6].\n    - apply (eq_cr (λ x, x ∈ C) P6).\n      apply P1.\n    - apply (eq_cr (λ x, x ∈ C) P6).\n      apply P2.\nQed.\n\nLemma opair_eq_swap: ∀ a, ∀ b, ∀ c, ∀ d, ⟨a, b⟩ = ⟨c, d⟩ → ⟨b, a⟩ = ⟨d, c⟩.\nProof.\n  intros a b c d P1.\n  apply (eq_cl (λ x, ⟨b, a⟩ = ⟨d, x⟩) (opair_eq_el _ _ _ _ P1)).\n  apply (eq_cl (λ x, ⟨b, a⟩ = ⟨x, a⟩) (opair_eq_er _ _ _ _ P1)).\n  apply eq_r.\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Cartesion Product *)\nLemma cp_i: ∀ A, ∀ B, ∀ x, ∀ y, x ∈ A → y ∈ B → ⟨x, y⟩ ∈ A ⨉ B.\nProof.\n  intros A B x y P1 P2.\n  apply sub_i.\n  + apply opair_superset.\n    - apply (union2_il _ _ _ P1).\n    - apply (union2_ir _ _ _ P2).\n  + exists x.\n    exists y.\n    repeat split.\n    - apply P1.\n    - apply P2.\nQed.\n\nLemma cp_e: ∀ A, ∀ B, ∀ x, x ∈ A ⨉ B → in_cp x A B.\n  intros A B x P1.\n  apply (sub_e _ _ _ P1).\nQed.\n\nLemma cp_e2: ∀ x, ∀ y, ∀ A, ∀ B, ⟨x, y⟩ ∈ A ⨉ B → x ∈ A ∧ y ∈ B.\nProof.\n  intros x y A B P1.\n  destruct (cp_e _ _ _ P1) as [a [b [P2 [P3 P4]]]].\n  split.\n  + apply (eq_cr (λ x, x ∈ A) (opair_eq_el _ _ _ _ P4)).\n    apply P2.\n  + apply (eq_cr (λ x, x ∈ B) (opair_eq_er _ _ _ _ P4)).\n    apply P3.\nQed.\n\nLemma cp_swap: ∀ A, ∀ B, ∀ x, ∀ y, ⟨x, y⟩ ∈ cp A B → ⟨y, x⟩ ∈ B ⨉ A.\nProof.\n  intros A B x y P1.\n  destruct (cp_e2 _ _ _ _ P1) as [P2 P3]. \n  apply (cp_i _ _ _ _ P3 P2).\nQed.\n\nLemma cp_sub: ∀ A, ∀ B, ∀ C, ∀ D, A ⊆ C → B ⊆ D → A ⨉ B ⊆ C ⨉ D.\nProof.\n  intros A B C D P1 P2 r P3.\n  destruct (cp_e _ _ _ P3) as [x [y [P4 [P5 P6]]]].\n  apply (eq_cr (λ r, r ∈ C ⨉ D) P6).\n  apply cp_i.\n  + apply (P1 _ P4).\n  + apply (P2 _ P5).\nQed.\n(*----------------------------------------------------------------------------*)\n\n(* Russell *)\nLemma no_universe: ~(∃ A, ∀ x, x ∈ A).\nProof.\n  intros [A P1].\n  pose ({x: A| x ∉ x}) as R.\n  assert (R ∉ R) as P2.\n  { intros P2.\n    destruct (sub_e _ _ _ P2) as [_ P3].\n    apply bot_e.\n    apply (P3 P2). }\n  assert (R ∈ R) as P3.\n  { apply sub_i.\n    + apply P1.\n    + apply P2. }\n  apply bot_e.\n  apply (P2 P3).\nQed.\n\nLemma ex_extra: ∀ A, ∃ x, x ∉ A.\nProof.\n  intros A.\n  apply not_all_ex_not.\n  apply (@not_ex_all_not (λ A, ∀ x, x ∈ A) no_universe).\nQed.\n\n(* Axiom of Regularity *)\nLemma nin_self: ∀ A, A ∉ A.\nProof.\n  intros A P1.\n  assert (∃ x, x ∈ `{A}) as P2.\n  { exists A.\n    apply sing_i. }\n  destruct (ax_regular `{A}) as [m P3].\n  destruct (P3 P2) as [P4 P5].\n  apply P5.\n  exists A.\n  split.\n  + apply sing_i.\n  + apply (eq_cl (λ x, A ∈ x) (sing_e _ _ P4)).\n    apply P1.\nQed.\n\nLemma no_mutual_in: ∀ A, ∀ B, ~(A ∈ B ∧ B ∈ A).\nProof.\n  intros A B [P1 P2].\n  assert (∃ x, x ∈ `{A, B}) as P3.\n  { exists A.\n    apply pair_il. }\n  destruct (ax_regular `{A, B}) as [m P4].\n  destruct (P4 P3) as [P5 P6].\n  apply P6.\n  destruct (pair_e _ _ _ P5) as [P7 | P7].\n  + exists B.\n    split.\n    - apply pair_ir.\n    - apply (eq_cr (λ x, B ∈ x) P7).\n      apply P2.\n  + exists A.\n    split.\n    - apply pair_il.\n    - apply (eq_cr (λ x, A ∈ x) P7).\n      apply P1.\nQed.\n(*----------------------------------------------------------------------------*)\n\n", "meta": {"author": "xuanlutw", "repo": "set_theory", "sha": "38bffe680ffbe242caeb33a474b99f385eba3251", "save_path": "github-repos/coq/xuanlutw-set_theory", "path": "github-repos/coq/xuanlutw-set_theory/set_theory-38bffe680ffbe242caeb33a474b99f385eba3251/Init/Operator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7236910928264124}}
{"text": "(** * MoreCoq: More About Coq *)\n\nRequire Export Poly.\n\n(* ###################################################### *)\n(** * More About Coq *)\n     \n(* ###################################################### *)\n(** ** The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n \nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n,o] = [n,p] ->\n     [n,o] = [m,p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  (* At this point, we could finish with \"[rewrite -> eq2. reflexivity.]\"\n     as we have done several times above. But we can achieve the \n     same effect in a single step by using the [apply] tactic instead: *)\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q,o] = [r,p]) ->\n     [n,o] = [m,p].\nProof.\n  intros n m o p eq1 eq2. \n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex) *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex : \n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\nintros eq1 eq2.\napply eq1. apply eq2.\nQed.\n\n\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal _exactly_ -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros eq1 eq2.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAdmitted.\n\n(** In this case we can use the [symmetry] tactic, which\n    switches the left and right sides of an equality in the goal. *)\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  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since \n            [apply] will do a [simpl] step first. *)  \n  apply H.  Qed.         \n\n(** **** Exercise: 3 stars (apply_exercise1) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* Hint: you can use [apply] with previously defined lemmas, not\n     just hypotheses in the context.  Remember that [SearchAbout] is\n     your friend. *)\n intros l l' eq1.\n rewrite -> eq1.\n symmetry.\n apply rev_involutive.\n Qed.\n  (* FILL IN HERE *) \n(** [] *)\n\n(** **** Exercise: 1 star (apply_rewrite) *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  Are there situations where both can usefully be\n    applied?\n\n  (* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ###################################################### *)\n(** ** Inversion *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is clear from this definition that every number has one of two\n    forms: either it is the constructor [O] or it is built by applying\n    the constructor [S] to another number.  But there is more here than\n    meets the eye: implicit in the definition (and in our informal\n    understanding of how datatype declarations work in other\n    programming languages) are two other facts:\n\n    - The constructor [S] is _injective_.  That is, the only way we can\n      have [S n = S m] is if [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor is\n    injective and [nil] is different from every non-empty list.  For\n    booleans, [true] and [false] are unequal.  (Since neither [true]\n    nor [false] take any arguments, their injectivity is not an issue.) *)\n\n(** Coq provides a tactic, called [inversion], that allows us to\n    exploit these principles in making proofs.\n \n    The [inversion] tactic is used like this.  Suppose [H] is a\n    hypothesis in the context (or a previously proven lemma) of the\n    form\n      c a1 a2 ... an = d b1 b2 ... bm\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] instructs Coq to \"invert\" this\n    equality to extract the information it contains about these terms:\n\n    - If [c] and [d] are the same constructor, then we know, by the\n      injectivity of this constructor, that [a1 = b1], [a2 = b2],\n      etc.; [inversion H] adds these facts to the context, and tries\n      to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory.  That is, a false assumption has crept\n      into the context, and this means that any goal whatsoever is\n      provable!  In this case, [inversion H] marks the current goal as\n      completed and pops it off the goal stack. *)\n\n(** The [inversion] tactic is probably easier to understand by\n    seeing it in action than from general descriptions like the above.\n    Below you will find example theorems that demonstrate the use of\n    [inversion] and exercises to test your understanding. *)\n\nTheorem eq_add_S : forall (n m : nat),\n     S n = S m ->\n     n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.  Qed.\n\nTheorem silly4 : forall (n m : nat),\n     [n] = [m] ->\n     n = m.\nProof.\n  intros n o eq. inversion eq. reflexivity.  Qed.\n\n(** As a convenience, the [inversion] tactic can also\n    destruct equalities between complex values, binding\n    multiple variables as it goes. *)\n\nTheorem silly5 : forall (n m o : nat),\n     [n,m] = [o,o] ->\n     [n] = [m].\nProof.\n  intros n m o eq. inversion eq. reflexivity. Qed.\n\n(** **** Exercise: 1 star (sillyex1) *) \nExample sillyex1 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof.\nintros X x y z l j eq.\ninversion eq.\nintros eq2.\ninversion eq2.\nreflexivity.\nQed.\n\n\n(** [] *)\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n  intros n m contra. inversion contra.  Qed.\n\n(** **** Exercise: 1 star (sillyex2) *)\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = [] ->\n     y :: l = z :: j ->\n     x = z.\nProof.\nintros X x y z l j contra.\ninversion contra.\nQed.\n\n  (* FILL IN HERE *) \n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    [forall (n m : nat), S n = S m -> n = m], the reverse direction of\n    the implication, provable by standard equational reasoning, is a\n    useful fact to record for cases we will see several times. *)\n\nLemma eq_remove_S : forall n m,\n  n = m -> S n = S m.\nProof. intros n m eq. rewrite -> eq. reflexivity. Qed.\n\n(** Here's another illustration of [inversion].  This is a slightly\n    roundabout way of stating a fact that we have already proved\n    above.  The extra equalities force us to do a little more\n    equational reasoning and exercise some of the tactics we've seen\n    recently. *)\n\nTheorem length_snoc' : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l. induction l as [| v' l'].\n  Case \"l = []\". intros n eq. rewrite <- eq. reflexivity.\n  Case \"l = v' :: l'\". intros n eq. simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply eq_remove_S. apply IHl'. inversion eq. reflexivity. Qed.\n\n(* ###################################################### *)\n(** ** Varying the Induction Hypothesis *)\n\n(** Here is a more realistic use of inversion to prove a\n    property that is useful in many places later on... *)\n\nTheorem beq_nat_eq_FAILED : forall n m,\n  true = beq_nat n m -> n = m.\nProof.\n  intros n m H. induction n as [| n']. \n  Case \"n = 0\".\n    destruct m as [| m'].\n    SCase \"m = 0\". reflexivity.  \n    SCase \"m = S m'\". simpl in H. inversion H. \n  Case \"n = S n'\".\n    destruct m as [| m'].\n    SCase \"m = 0\". simpl in H. inversion H.\n    SCase \"m = S m'\".\n      apply eq_remove_S. \n      (* stuck here because the induction hypothesis\n         talks about an extremely specific m *)\n      Admitted.\n\n(** The inductive proof above fails because we've set up things so\n    that the induction hypothesis (in the second subgoal generated by\n    the [induction] tactic) is\n\n       [ true = beq_nat n' m -> n' = m ].\n\n     This hypothesis makes a statement about [n'] together with the\n     _particular_ natural number [m] -- that is, the number [m], which\n     was introduced into the context by the [intros] at the top of the\n     proof, is \"held constant\" in the induction hypothesis.  This\n     induction hypothesis is not strong enough to make the induction\n     step of the proof go through.\n\n     If we set up the proof slightly differently by introducing just\n     [n] into the context at the top, then we get an induction\n     hypothesis that makes a stronger claim:\n\n      [ forall m : nat, true = beq_nat n' m -> n' = m ]\n\n     Setting up the induction hypothesis this way makes the proof of\n     [beq_nat_eq] go through: *)\n\nTheorem beq_nat_eq : forall n m,\n  true = beq_nat n m -> n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". \n    intros m. destruct m as [| m'].\n    SCase \"m = 0\". reflexivity.  \n    SCase \"m = S m'\". simpl. intros contra. inversion contra. \n  Case \"n = S n'\".\n    intros m. destruct m as [| m'].\n    SCase \"m = 0\". simpl. intros contra. inversion contra.\n    SCase \"m = S m'\". simpl. intros H.\n      apply eq_remove_S. apply IHn'. apply H. Qed.\n\n(** Similar issues will come up in _many_ of the proofs below.  If you\n    ever find yourself in a situation where the induction hypothesis\n    is insufficient to establish the goal, consider going back and\n    doing fewer [intros] to make the IH stronger. *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_eq_informal) *)\n(** Give an informal proof of [beq_nat_eq]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars (beq_nat_eq') *)\n(** We can also prove beq_nat_eq by induction on [m], though we have\n    to be a little careful about which order we introduce the\n    variables, so that we get a general enough induction hypothesis --\n    this is done for you below.  Finish the following proof.  To get\n    maximum benefit from the exercise, try first to do it without\n    looking back at the one above. *)\n\nTheorem beq_nat_eq' : forall m n,\n  beq_nat n m = true -> n = m.\nProof.\n  intros m. induction m as [| m']. \n  Case \"m = 0\".\n  intros n. destruct n.\n    SCase \"n = 0\". intros eq1. reflexivity.\n    SCase \"n = S n'\". intros contra1. inversion contra1.\n  Case \"m = S m'\".\n  intros n.  destruct n.\n    SCase \"n = 0\". intros contra2. inversion contra2.\n    SCase \"n = S n'\".  simpl. intros eq2. apply eq_remove_S. \n    apply IHm'. apply eq2. Qed.\n  (* FILL IN HERE *)\n(** [] *)\n\n\n(* ###################################################### *)\n(** *** Practice Session *)\n\n(** **** Exercise: 2 stars, optional (practice) *)\n(** Some nontrivial but not-too-complicated proofs to work together in\n    class, and some for you to work as exercises.  Some of the\n    exercises may involve applying lemmas from earlier lectures or\n    homeworks. *)\n \n\nTheorem beq_nat_0_l : forall n,\n  true = beq_nat 0 n -> 0 = n.\nProof.\n  intros n eq1. destruct n.\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". inversion eq1.\n  Qed.\n  (* FILL IN HERE *) \n\nTheorem beq_nat_0_r : forall n,\n  true = beq_nat 0 n -> 0 = n.\nProof.\n  intros n eq1. destruct n.\n  Case \"n = 0\". reflexivity.\n  Case \"n = S n'\". inversion eq1. \n  Qed.  \n  (* FILL IN HERE *) \n(** [] *)\n\n(** **** Exercise: 3 stars (apply_exercise2) *)\n(** In the following proof opening, notice that we don't introduce [m]\n    before performing induction.  This leaves it general, so that the\n    IH doesn't specify a particular [m], but lets us pick.  Finish the\n    proof. *)\n\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\". destruct m as [| m'].\n     SCase \"m = 0\". reflexivity.\n     SCase \"m = S m'\". reflexivity.\n  Case \"n = S n'\". destruct m as [| m'].\n     SCase \"m = 0\". reflexivity.\n     SCase \"m = S m'\". simpl. apply IHn'. Qed.\n  (* FILL IN HERE *) \n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (beq_nat_sym_informal) *)\n(** Provide an informal proof of this lemma that corresponds\n    to your formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(* ###################################################### *)\n(** ** Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b. \nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, the tactic [apply L in H] matches some\n    conditional statement [L] (of the form [L1 -> L2], say) against a\n    hypothesis [H] in the context.  However, unlike ordinary\n    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),\n    [apply L in H] matches [H] against [L1] and, if successful,\n    replaces it with [L2].\n \n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\" -- from [L1 -> L2] and a hypothesis matching [L1], it\n    gives us a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\" -- it says that if we know [L1->L2] and we\n    are trying to prove [L2], it suffices to prove [L1].  \n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\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  symmetry in H. apply eq in H. symmetry in H. \n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, Coq tends to favor backward reasoning, but in some\n    situations the forward style can be easier to use or to think\n    about.  *)\n\n(** **** Exercise: 3 stars (plus_n_n_injective) *)\n(** You can practice using the \"in\" variants in this exercise. *)\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  Case \"n = 0\". intros m eq1. destruct m.\n     SCase \"m = 0\". reflexivity.\n     SCase \"m = S m'\". inversion eq1.\n  Case \"n = S n'\". intros m eq2. destruct m as [| m'].\n     SCase \"m = 0\". \n\n    (* Hint: use the plus_n_Sm lemma *)\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where the [destruct] tactic is\n    used to perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun. \n  destruct (beq_nat n 3).\n    Case \"beq_nat n 3 = true\". reflexivity.\n    Case \"beq_nat n 3 = false\". destruct (beq_nat n 5).\n      SCase \"beq_nat n 5 = true\". reflexivity.\n      SCase \"beq_nat n 5 = false\". reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,\n    either [n] is equal to [3] or it isn't, so we use [destruct\n    (beq_nat n 3)] to let us reason about the two cases. *)\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(** **** Exercise: 3 stars (combine_split) *)\n(* \nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l. induction l as [| [x y] l'].\n  (* FILL IN HERE *) Admitted.\n*)\n(** [] *)\n\n(** **** Exercise: 3 stars (split_combine) *)\n(** Thought exercise: We have just proven that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you state the\n    theorem showing that [split] is the inverse of [combine]?\n \n    Hint: what property do you need of [l1] and [l2] for [split]\n    [combine l1 l2 = (l1,l2)] to be true?\n\n    State this theorem in Coq, and prove it. (Be sure to leave your\n    induction hypothesis general by not doing [intros] on more things\n    than necessary.) *)\n\n(* FILL IN HERE *) \n(** [] *)\n\n(* ###################################################### *)\n(** ** The [remember] Tactic *)\n\n(** (Note: the [remember] tactic is not strictly needed until a\n    bit later, so if necessary this section can be skipped and\n    returned to when needed.) *)\n\n(** We have seen how the [destruct] tactic can be used to\n    perform case analysis of the results of arbitrary computations.\n    If [e] is an expression whose type is some inductively defined\n    type [T], then, for each constructor [c] of [T], [destruct e]\n    generates a subgoal in which all occurrences of [e] (in the goal\n    and in the context) are replaced by [c].\n\n    Sometimes, however, this substitution process loses information\n    that we need in order to complete the proof.  For example, suppose\n    we define a function [sillyfun1] like this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** And suppose that we want to convince Coq of the rather\n    obvious observation that [sillyfun1 n] yields [true] only when [n]\n    is odd.  By analogy with the proofs we did with [sillyfun] above,\n    it is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAdmitted.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution peformed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep at\n    least one of these because we need to be able to reason that\n    since, in this branch of the case analysis, [beq_nat n 3 = true],\n    it must be that [n = 3], from which it follows that [n] is odd.\n\n    What we would really like is not to use [destruct] directly on\n    [beq_nat n 3] and substitute away all occurrences of this\n    expression, but rather to use [destruct] on something else that is\n    _equal_ to [beq_nat n 3].  For example, if we had a variable that\n    we knew was equal to [beq_nat n 3], we could [destruct] this\n    variable instead.\n\n    The [remember] tactic allows us to introduce such a variable. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n   remember (beq_nat n 3) as e3.\n   (* At this point, the context has been enriched with a new\n      variable [e3] and an assumption that [e3 = beq_nat n 3].\n      Now if we do [destruct e3]... *)\n   destruct e3.\n   (* ... the variable [e3] gets substituted away (it\n     disappears completely) and we are left with the same\n      state as at the point where we got stuck above, except\n      that the context still contains the extra equality\n      assumption -- now with [true] substituted for [e3] --\n      which is exactly what we need to make progress. *)\n     Case \"e3 = true\". apply beq_nat_eq in Heqe3.\n       rewrite -> Heqe3. reflexivity.\n     Case \"e3 = false\".\n      (* When we come to the second equality test in the\n        body of the function we are reasoning about, we can\n         use [remember] again in the same way, allowing us\n         to finish the proof. *)\n       remember (beq_nat n 5) as e5. destruct e5.\n         SCase \"e5 = true\".\n           apply beq_nat_eq in Heqe5.\n           rewrite -> Heqe5. reflexivity.\n         SCase \"e5 = false\". inversion eq.  Qed.\n\n(** **** Exercise: 2 stars *)\nTheorem bool_fn_applied_thrice : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (override_same) *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise) *)\n(** This one is a bit challenging.  Be sure your initial [intros] go\n    only up through the parameter on which you want to do\n    induction! *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** ** The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a,b] = [c,d] ->\n     [c,d] = [e,f] ->\n     [a,b] = [e,f].\nProof.\n  intros a b c d e f eq1 eq2. \n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might\n    abstract it out as a lemma recording once and for all\n    the fact that equality is transitive. *)\n\nTheorem trans_eq : forall {X:Type} (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. \n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to\n    prove the above example.  However, to do this we need\n    a slight refinement of the [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a,b] = [c,d] ->\n     [c,d] = [e,f] ->\n     [a,b] = [e,f].\nProof.\n  intros a b c d e f eq1 eq2. \n  (* If we simply tell Coq [apply trans_eq] at this point,\n     it can tell (by matching the goal against the\n     conclusion of the lemma) that it should instantiate [X]\n     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].\n     However, the matching process doesn't determine an\n     instantiation for [m]: we have to supply one explicitly\n     by adding [with (m:=[c,d])] to the invocation of\n     [apply]. *)\n  apply trans_eq with (m:=[c,d]). apply eq1. apply eq2.   Qed.\n\n(**  Actually, we usually don't have to include the name [m]\n    in the [with] clause; Coq is often smart enough to\n    figure out which instantiation we're giving. We could\n    instead write: apply trans_eq with [c,d]. *)\n\n(** **** Exercise: 3 stars (apply_exercises) *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o). \nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem beq_nat_trans : forall n m p,\n  true = beq_nat n m ->\n  true = beq_nat m p ->\n  true = beq_nat n p.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem override_permute : forall {X:Type} x1 x2 k1 k2 k3 (f : nat->X),\n  false = beq_nat k2 k1 ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen a bunch of Coq's fundamental tactics -- enough to\n    do pretty much everything we'll want for a while.  We'll introduce\n    one or two more as we go along through the next few lectures, and\n    later in the course we'll introduce some more powerful\n    _automation_ tactics that make Coq do more of the low-level work\n    in many cases.  But basically we've got what we need to get work\n    done.\n\n    Here are the ones we've seen:\n\n      - [intros]: \n        move hypotheses/variables from goal to context \n\n      - [reflexivity]:\n        finish the proof (when the goal looks like [e = e])\n\n      - [apply]:\n        prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: \n        apply a hypothesis, lemma, or constructor to a hypothesis in\n        the context (forward reasoning)\n\n      - [apply... with...]:\n        explicitly specify values for variables that cannot be\n        determined by pattern matching\n\n      - [simpl]:\n        simplify computations in the goal \n\n      - [simpl in H]:\n        ... or a hypothesis \n\n      - [rewrite]:\n        use an equality hypothesis (or lemma) to rewrite the goal \n\n      - [rewrite ... in H]:\n        ... or a hypothesis \n\n      - [symmetry]:\n        changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]:\n        changes a hypothesis of the form [t=u] into [u=t]\n\n      - [unfold]:\n        replace a defined constant by its right-hand side in the goal \n\n      - [unfold... in H]:\n        ... or a hypothesis  \n\n      - [destruct... as...]:\n        case analysis on values of inductively defined types \n\n      - [induction... as...]:\n        induction on values of inductively defined types \n\n      - [inversion]:\n        reason by injectivity and distinctness of constructors\n\n      - [remember (e) as x]:\n        give a name ([x]) to an expression ([e]) so that we can\n        destruct [x] without \"losing\" [e]\n\n      - [assert (e) as H]:\n        introduce a \"local lemma\" [e] and call it [H] \n*)\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 4 stars (forall_exists_challenge) *)\n(** Challenge problem: Define two recursive [Fixpoints],\n    [forallb] and [existsb].  The first checks whether every\n    element in a list satisfies a given predicate:\n      forallb oddb [1,3,5,7,9] = true\n\n      forallb negb [false,false] = true\n  \n      forallb evenb [0,2,4,5] = false\n  \n      forallb (beq_nat 5) [] = true\n    The function [existsb] checks whether there exists an element in\n    the list that satisfies a given predicate:\n      existsb (beq_nat 5) [0,2,3,6] = false\n \n      existsb (andb true) [true,true,false] = true\n \n      existsb oddb [1,0,0,0,0,3] = true\n \n      existsb evenb [] = false\n    Next, create a _nonrecursive_ [Definition], [existsb'], using\n    [forallb] and [negb].\n \n    Prove that [existsb'] and [existsb] have the same behavior.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* $Date: 2013-01-22 11:34:02 -0500 (Tue, 22 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/MoreCoq1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.8902942312159383, "lm_q1q2_score": 0.7236910918867978}}
{"text": "(*|\n##########################################################\nWhat does ``Proof. simpl. reflexivity. Qed.`` mean in Coq?\n##########################################################\n\n:Link: https://stackoverflow.com/q/64246592\n|*)\n\n(*|\nQuestion\n********\n\nI'm reading the book Software Foundations and got stuck at the very\nbeginning.\n\nThe author defined a boolean type and common operations:\n|*)\n\nInductive bool: Type :=\n| true\n| false.\n\nDefinition orb (b1: bool) (b2: bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\n(*|\nSo let's say we want to prove the correctness of the ``or`` function.\nThe author wrote a test followed by a proof:\n|*)\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\n(*|\nCould someone explain to me what ``simpl. reflexivity.`` mean? Is\nthere any other way we can prove this simple test?\n|*)\n\n(*|\nAnswer\n******\n\n``simpl`` is a tactic evaluating the goal. In your case, after\nexecuting it, the goal will be left to ``true = true``.\n``reflexivity`` is a tactic discharging goals of the shape ``x = x``\n(in its simplest incarnation). What it does under the hood is to\nprovide the proof term ``eq_refl : x = x`` as a solution to the\ncurrent proof obligation.\n\nNow, there are many ways to achieve this thing that ultimately will\nproduce the same (rather trivial) proof ``eq_refl`` (try doing ``Print\ntest_orb1.``). First, the ``simpl`` operation is not needed because\nCoq will do some computations when applying a term (in particular when\ncalling ``reflexivity``). Second, you could obtain the same effect as\n``reflexivity`` by calling ``constructor``, ``apply eq_refl`` or\n``refine eq_refl``. These are tactics with different goals but that\nhappen to coincide here.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/what-does-proof-simpl-reflexivity-qed-mean-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.8902942181173145, "lm_q1q2_score": 0.7236910812393544}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. You may distribute   *)\n(* under the terms of either the CeCILL-B License or the CeCILL        *)\n(* version 2 License, as specified in the README file.                 *)\nRequire Import ssreflect.\n\n(****************************************************************************)\n(* This file contains the basic definitions and notations for working with  *)\n(* functions. The definitions concern:                                      *)\n(*                                                                          *)\n(*  Pair projections                                                        *)\n(*    p.1  == first element of a pair                                       *)\n(*    p.2  == second element of a pair                                      *)\n(*                                                                          *)\n(*  Simplifying functions, beta-reduced by simpl and /= :                   *)\n(*           [fun : T => E] == constant function from type T that returns E *)\n(*             [fun x => E] == unary function                               *)\n(*         [fun x : T => E] == unary function with explicit domain type     *)\n(*           [fun x y => E] == binary function                              *)\n(*       [fun x y : T => E] == binary function with explicit domain type    *)\n(*     [fun (x : T) y => E] == binary function with explicit domain type    *)\n(*     [fun x (y : T) => E] == binary function with explicit domain type    *)\n(*    [fun (x : xT) (y : yT) => E]                                          *)\n(*                                                                          *)\n(* - partial functions using option type,                                   *)\n(*     oapp f d ox == if ox is Some x returns f x,        d otherwise       *)\n(*      odflt d ox == if ox is Some x returns x,          d otherwise       *)\n(*      obind f ox == if ox is Some x returns f x,        None otherwise    *)\n(*       omap f ox == if ox is Some x returns Some (f x), None otherwise    *)\n(*                                                                          *)\n(* - extensional equality for functions and relations (i.e. functions of 2  *)\n(*   arguments),                                                            *)\n(*    f1 =1 f2      ==  f1 x is equal to f2 x forall x                      *)\n(*    f1 =1 f2 :>A  ==    ... and f2 is explicitly typed                    *)\n(*    f1 =2 f2      ==  f1 x y is equal to f2 x y forall x y                *)\n(*    f1 =2 f2 :> A ==    ... and f2 is explicitly typed                    *)\n(*                                                                          *)\n(* - composition for total and partial functions,                           *)\n(*             f^~y == function f with y as second argument y               *)\n(*        f1 \\o f2  == composition of f1 and f2                             *)\n(*      pcomp f1 f2 == composition of partial functions f1 and f2           *)\n(*                                                                          *)\n(* - properties of functions                                                *)\n(*        injective f == f is injective                                     *)\n(*         cancel f g == g is the inverse of f                              *)\n(*        pcancel f g == g is the inverse of f where g is partial           *)\n(*        ocancel f g == g is the inverse of f where f is partial           *)\n(*        bijective f == f is bijective                                     *)\n(*       involutive f == f is involutive                                    *)\n(*                                                                          *)\n(* - properties for operations                                              *)\n(*                left_id e op == e is a left identity for op               *)\n(*               right_id e op == e is a right identity for op              *)\n(*         left_inverse e i op == i is a left inverse for op with unit e    *)\n(*        right_inverse e i op == i is a right inverse for op with unit e   *)\n(*         self_inverse x e op == x is its own inverse for op               *)\n(*             idempotent x op == x is idempotent                           *)\n(*                associate op == op is associative                         *)\n(*              commutative op == op is commutative                         *)\n(*         left_commutative op == op is left commutative                    *)\n(*        right_commutative op == op is right commutative                   *)\n(*              left_zero z op == z is a right zero for op                  *)\n(*             right_zero z op == z is a right zero for op                  *)\n(*   left_distributive op1 op2 == op1 is left distributive for op2          *)\n(*  right_distributive op1 op2 == op1 is right distributive for op2         *)\n(*                                                                          *)\n(* - morphisms for functions and relations,                                 *)\n(*  {morph f : x / a >-> r } == f is a morphism with respect to functions   *)\n(*                                 (fun x => a) and (fun x => r)            *)\n(*  {morph f : x / a } == f is a morphism with respect to (fun x => a)      *)\n(*  {morph f : x y / a >-> r } == f is a morphism with respect to functions *)\n(*                                 (fun x y => a) and (fun x y => r)        *)\n(*  {morph f : x / a } == f is a morphism with respect to (fun x y => a)    *)\n(*                                                                          *)\n(* The file also contains some basic lemmas for the above concepts.         *)\n(****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nDelimit Scope fun_scope with FUN.\nOpen Scope fun_scope.\n\nNotation \"f ^~ y\" := (fun x => f x y)\n  (at level 10, y at level 8, no associativity, format \"f ^~  y\") : fun_scope.\n\nDelimit Scope pair_scope with PAIR.\nOpen Scope pair_scope.\n\n(* Notations for pair projections *)\nNotation \"p .1\" := (fst p)\n  (at level 2, left associativity, format \"p .1\") : pair_scope.\nNotation \"p .2\" := (snd p)\n  (at level 2, left associativity, format \"p .2\") : pair_scope.\n\n(* Reserved notations for evaluation *)\nReserved Notation \"e .[ x ]\"\n  (at level 2, left associativity, format \"e .[ x ]\").\n\nReserved Notation \"e .[ x1 , x2 , .. , xn ]\"\n  (at level 2, left associativity,\n   format \"e '[ ' .[ x1 , '/'  x2 , '/'  .. , '/'  xn ] ']'\").\n\n(* Reserved notations for subscripting and superscripting *)\nReserved Notation \"x ^-1\"\n  (at level 3, left associativity, format \"x ^-1\").\n\nReserved Notation \"x *+ n\" (at level 40, left associativity).\nReserved Notation \"x *- n\" (at level 40, left associativity).\nReserved Notation \"x ^+ n\" (at level 29, left associativity).\nReserved Notation \"x ^- n\" (at level 29, left associativity).\n\nReserved Notation \"s `_ i\"\n  (at level 3, i at level 2, left associativity, format \"s `_ i\").\n\n(* Complements on the option type constructor, used below to  *)\n(* encode partial functions.                                  *)\n\nModule Option.\n\nDefinition apply aT rT (f : aT -> rT) x u := if u is Some y then f y else x.\n\nDefinition default T := apply (fun x : T => x).\n\nDefinition bind aT rT (f : aT -> option rT) := apply f None.\n\nDefinition map aT rT (f : aT -> rT) := bind (fun x => Some (f x)).\n\nEnd Option.\n\nNotation oapp := Option.apply.\nNotation odflt := Option.default.\nNotation obind := Option.bind.\nNotation omap := Option.map.\nNotation some := (@Some _) (only parsing).\n\n(* Syntax for defining auxiliary recursive function.          *)\n(*  Usage:                                                    *)\n(* Section FooDefinition.                                     *)\n(* Variables (g1 : T1) (g2 : T2).  (globals)                  *)\n(* Fixoint foo_auxiliary (a3 : T3) ... :=                     *)\n(*        body, using [rec e3, ...] for recursive calls       *)\n(* where \"[ 'rec' a3 , a4 , ... ]\" := foo_auxiliary.          *)\n(* Definition foo x y .. := [rec e1, ...].                    *)\n(* + proofs about foo                                         *)\n(* End FooDefinition.                                         *)\n\nReserved Notation \"[ 'rec' a0 ]\"\n  (at level 0).\nReserved Notation \"[ 'rec' a0 , a1 ]\"\n  (at level 0).\nReserved Notation \"[ 'rec' a0 , a1 , a2 ]\"\n  (at level 0).\nReserved Notation \"[ 'rec' a0 , a1 , a2 , a3 ]\"\n  (at level 0).\nReserved Notation \"[ 'rec' a0 , a1 , a2 , a3 , a4 ]\"\n  (at level 0).\nReserved Notation \"[ 'rec' a0 , a1 , a2 , a3 , a4 , a5 ]\"\n  (at level 0).\nReserved Notation \"[ 'rec' a0 , a1 , a2 , a3 , a4 , a5 , a6 , a7 ]\"\n  (at level 0).\nReserved Notation \"[ 'rec' a0 , a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 ]\"\n  (at level 0).\nReserved Notation \"[ 'rec' a0 , a1 , a2 , a3 , a4 , a5 , a6 , a7 , a8 , a9 ]\"\n  (at level 0).\n\n(* Definitions and notation for explicit functions with simplification,     *)\n(* i.e., which simpl and /= beta expand (this is complementary to nosimpl). *)\n\nSection SimplFun.\n\nVariables aT rT : Type.\n\nCoInductive simpl_fun : Type := SimplFun of aT -> rT.\n\nDefinition fun_of_simpl := fun f x => let: SimplFun lam := f in lam x.\n\nCoercion fun_of_simpl : simpl_fun >-> Funclass.\n\nEnd SimplFun.\n\nNotation \"[ 'fun' : T => E ]\" := (SimplFun (fun _ : T => E))\n  (at level 0,\n   format \"'[hv' [ 'fun' :  T  => '/ '  E ] ']'\") : fun_scope.\n\nNotation \"[ 'fun' x => E ]\" := (SimplFun (fun x => E))\n  (at level 0, x ident,\n   format \"'[hv' [ 'fun'  x  => '/ '  E ] ']'\") : fun_scope.\n\nNotation \"[ 'fun' x : T => E ]\" := (SimplFun (fun x : T => E))\n  (at level 0, x ident, only parsing) : fun_scope.\n\nNotation \"[ 'fun' x y => E ]\" := (fun x => [fun y => E])\n  (at level 0, x ident, y ident,\n   format \"'[hv' [ 'fun'  x  y  => '/ '  E ] ']'\") : fun_scope.\n\nNotation \"[ 'fun' x y : T => E ]\" := (fun x : T => [fun y : T => E])\n  (at level 0, x ident, y ident, only parsing) : fun_scope.\n\nNotation \"[ 'fun' ( x : T ) y => E ]\" := (fun x : T => [fun y => E])\n  (at level 0, x ident, y ident, only parsing) : fun_scope.\n\nNotation \"[ 'fun' x ( y : T ) => E ]\" := (fun x => [fun y : T => E])\n  (at level 0, x ident, y ident, only parsing) : fun_scope.\n\nNotation \"[ 'fun' ( x : xT ) ( y : yT ) => E ]\" :=\n    (fun x : xT => [fun y : yT => E])\n  (at level 0, x ident, y ident, only parsing) : fun_scope.\n\n(* For delta functions in eqtype.v. *)\nDefinition SimplFunDelta aT rT (f : aT -> aT -> rT) := [fun z => f z z].\n\n(* Shorthand for some basic equality lemmas. *)\n\nDefinition erefl := refl_equal.\nDefinition esym := sym_eq.\nDefinition nesym := sym_not_eq.\nDefinition etrans := trans_eq.\nDefinition congr1 := f_equal.\nDefinition congr2 := f_equal2.\n(* Force at least one implicit when used as a view. *)\nPrenex Implicits esym nesym.\n\n(* Extensional equality, for unary and binary functions, including syntactic *)\n(* sugar.                                                                    *)\n\nSection ExtensionalEquality.\n\nVariables A B C : Type.\n\nDefinition eqfun (f g : B -> A) : Prop := forall x, f x = g x.\n\nDefinition eqrel (r s : C -> B -> A) : Prop := forall x y, r x y = s x y.\n\nLemma frefl : forall f, eqfun f f. Proof. by []. Qed.\nLemma fsym : forall f g, eqfun f g -> eqfun g f. Proof. by move=> f g E x. Qed.\n\nLemma ftrans : forall f g h, eqfun f g -> eqfun g h -> eqfun f h.\nProof. by move=> f g h eqfg eqgh x; rewrite eqfg. Qed.\n\nLemma rrefl : forall r, eqrel r r. Proof. by []. Qed.\n\nEnd ExtensionalEquality.\n\nHint Resolve frefl rrefl.\n\nNotation \"f1 =1 f2\" := (eqfun f1 f2)\n  (at level 70, no associativity) : fun_scope.\nNotation \"f1 =1 f2 :> A\" := (f1 =1 (f2 : A))\n  (at level 70, f2 at next level, A at level 90) : fun_scope.\nNotation \"f1 =2 f2\" := (eqrel f1 f2)\n  (at level 70, no associativity) : fun_scope.\nNotation \"f1 =2 f2 :> A\" := (f1 =2 (f2 : A))\n  (at level 70, f2 at next level, A, B at level 90) : fun_scope.\n\nSection Composition.\n\nVariables A B C : Type.\n\nDefinition comp (f : B -> A) (g : C -> B) := [fun x => f (g x)].\n\nDefinition pcomp (f : B -> option A) (g : C -> option B) x := obind f (g x).\n\nLemma eq_comp : forall f f' g g', f =1 f' -> g =1 g' -> comp f g =1 comp f' g'.\nProof. by move=> f f' g g' Ef Eg x; rewrite /= Eg Ef. Qed.\n\nEnd Composition.\n\nNotation \"[ 'eta' f ]\" := (fun x => f x)\n  (at level 0, format \"[ 'eta'  f ]\") : fun_scope.\n\nNotation id := (fun x => x).\nNotation \"@ 'id' T \" := (fun x : T => x)\n  (at level 10, T at level 8, only parsing) : fun_scope.\n\nNotation \"f1 \\o f2\" := (comp f1 f2) (at level 50) : fun_scope.\n\nDefinition idfun T := @id T.\nPrenex Implicits idfun.\n\nSection OperationProperties.\n\nVariable T : Type.\nVariables zero one: T.\nVariable inv : T -> T.\nVariables mul add : T -> T -> T.\n\nNotation Local \"1\" := one.\nNotation Local \"0\" := zero.\nNotation Local \"x ^-1\" := (inv x).\nNotation Local \"x * y\"  := (mul x y).\nNotation Local \"x + y\"  := (add x y).\n\nDefinition left_id          := forall x,     1 * x = x.\nDefinition right_id         := forall x,     x * 1 = x.\nDefinition left_inverse       := forall x,     x^-1 * x = 1.\nDefinition right_inverse      := forall x,     x * x^-1 = 1.\nDefinition self_inverse       := forall x,     x * x = 1.\nDefinition idempotent         := forall x,     x * x = x.\nDefinition associative        := forall x y z, x * (y * z) = x * y * z.\nDefinition commutative        := forall x y,   x * y = y * x.\nDefinition left_commutative   := forall x y z, x * (y * z) = y * (x * z).\nDefinition right_commutative  := forall x y z, x * y * z = x * z * y.\nDefinition left_zero          := forall x,     0 * x = 0.\nDefinition right_zero         := forall x,     x * 0 = 0.\nDefinition left_distributive  := forall x y z, (x + y) * z = x * z + y * z.\nDefinition right_distributive := forall x y z, x * (y + z) = x * y + x * z.\n\nEnd OperationProperties.\n\nSection Morphism.\n\nVariables (aT rT sT : Type) (f : aT -> rT).\n\nDefinition morphism_1 aF rF := forall x, f (aF x) = rF (f x).\nDefinition morphism_2 aOp rOp := forall x y, f (aOp x y) = rOp (f x) (f y).\n\nEnd Morphism.\n\nNotation \"{ 'morph' f : x / a >-> r }\" :=\n  (morphism_1 f (fun x => a) (fun x => r))\n  (at level 0, f at level 99, x ident,\n   format \"{ 'morph'  f  :  x  /  a  >->  r }\") : type_scope.\n\nNotation \"{ 'morph' f : x / a }\" :=\n  (morphism_1 f (fun x => a) (fun x => a))\n  (at level 0, f at level 99, x ident,\n   format \"{ 'morph'  f  :  x  /  a }\") : type_scope.\n\nNotation \"{ 'morph' f : x y / a >-> r }\" :=\n  (morphism_2 f (fun x y => a) (fun x y => r))\n  (at level 0, f at level 99, x ident, y ident,\n   format \"{ 'morph'  f  :  x  y  /  a  >->  r }\") : type_scope.\n\nNotation \"{ 'morph' f : x y / a }\" :=\n  (morphism_2 f (fun x y => a) (fun x y => a))\n  (at level 0, f at level 99, x ident, y ident,\n   format \"{ 'morph'  f  :  x  y  /  a }\") : type_scope.\n\n(* In an intuitionistic setting, we have two degrees of injectivity. The     *)\n(* weaker one gives only simplification, and the strong one provides a left  *)\n(* inverse (we show in `fintype' that they coincide for finite types).       *)\n(* We also define an intermediate version where the left inverse is only a   *)\n(* partial function.                                                         *)\n\nSection Injections.\n\n(* rT must come first so we can use @ to mitigate the Coq 1st order   *)\n(* unification bug (e..g., Coq can't infer rT from a \"cancel\" lemma). *)\nVariables (rT aT : Type) (f : aT -> rT).\n\nDefinition injective := forall x1 x2, f x1 = f x2 -> x1 = x2.\n\nDefinition cancel g := forall x, g (f x) = x.\n\nDefinition pcancel g := forall x, g (f x) = Some x.\n\nDefinition ocancel (g : aT -> option rT) h := forall x, oapp h x (g x) = x.\n\nLemma can_pcan : forall g, cancel g -> pcancel (fun y => Some (g y)).\nProof. by move=> g fK x; congr (Some _). Qed.\n\nLemma pcan_inj : forall g, pcancel g -> injective.\nProof. by move=> g fK x y; move/(congr1 g); rewrite !fK => [[]]. Qed.\n\nLemma can_inj : forall g, cancel g -> injective.\nProof. by move=> g; move/can_pcan; exact: pcan_inj. Qed.\n\nLemma canLR : forall g x y, cancel g -> x = f y -> g x = y.\nProof. by move=> g x y fK ->. Qed.\n\nLemma canRL : forall g x y, cancel g -> f x = y -> x = g y.\nProof. by move=> g x y fK <-. Qed.\n\nEnd Injections.\n\nSection InjectionsTheory.\n\nVariables (A B C : Type) (f g : B -> A) (h : C -> B).\n\nLemma inj_id : injective (@id A).\nProof. by []. Qed.\n\nLemma inj_can_sym : forall f', cancel f f' -> injective f' -> cancel f' f.\nProof. move=> f' fK injf' x; exact: injf'. Qed.\n\nLemma inj_comp : injective f -> injective h -> injective (f \\o h).\nProof. move=> injf injh x y; move/injf; exact: injh. Qed.\n\nLemma can_comp : forall f' h',\n  cancel f f' -> cancel h h' -> cancel (f \\o h) (h' \\o f').\nProof. by move=> f' h' fK hK x; rewrite /= fK hK. Qed.\n\nLemma pcan_pcomp : forall f' h',\n  pcancel f f' -> pcancel h h' -> pcancel (f \\o h) (pcomp h' f').\nProof. by move=> f' h' fK hK x; rewrite /pcomp fK /= hK. Qed.\n\nLemma eq_inj : injective f -> f =1 g -> injective g.\nProof. by move=> injf eqfg x y; rewrite -2!eqfg; exact: injf. Qed.\n\nLemma eq_can : forall f' g', cancel f f' -> f =1 g -> f' =1 g' -> cancel g g'.\nProof. by move=> f' g' fK eqfg eqfg' x; rewrite -eqfg -eqfg'. Qed.\n\nLemma inj_can_eq : forall f',\n  cancel f f' -> injective f' -> cancel g f' -> f =1 g.\nProof. by move=> f' fK injf' gK x; apply: injf'; rewrite fK. Qed.\n\nEnd InjectionsTheory.\n\nSection Bijections.\n\nVariables (A B : Type) (f : B -> A).\n\nDefinition bijective : Prop := exists2 g, cancel f g & cancel g f.\n\nHypothesis bijf : bijective.\n\nLemma bij_inj : injective f.\nProof. by case: bijf => [h fK _]; apply: can_inj fK. Qed.\n\nLemma bij_can_sym : forall f', cancel f' f <-> cancel f f'.\nProof.\nmove=> f'; split=> fK; first exact: inj_can_sym fK bij_inj.\nby case: bijf => [h _ hK] x; rewrite -[x]hK fK.\nQed.\n\nLemma bij_can_eq : forall f' f'', cancel f f' -> cancel f f'' -> f' =1 f''.\nProof.\nby move=> f' f'' fK fK'; apply: (inj_can_eq _ bij_inj); apply/bij_can_sym.\nQed.\n\nEnd Bijections.\n\nSection BijectionsTheory.\n\nVariables (A B C : Type) (f : B -> A) (h : C -> B).\n\nLemma eq_bij : bijective f -> forall g, f =1 g -> bijective g.\nProof. by move=> [f' fK f'K] g eqfg; exists f'; eapply eq_can; eauto. Qed.\n\nLemma bij_comp : bijective f -> bijective h -> bijective (f \\o h).\nProof.\nmove=> [f' fK f'K] [h' hK h'K].\nby exists (h' \\o f' : _ -> _); apply can_comp; auto.\nQed.\n\nLemma bij_can_bij : bijective f -> forall f', cancel f f' -> bijective f'.\nProof. by move=> bijf; exists f; first by apply/(bij_can_sym bijf). Qed.\n\nEnd BijectionsTheory.\n\nSection Involutions.\n\nVariables (A : Type) (f : A -> A).\n\nDefinition involutive := cancel f f.\n\nHypothesis Hf : involutive.\n\nLemma inv_inj : injective f. Proof. exact: can_inj Hf. Qed.\nLemma inv_bij : bijective f. Proof. by exists f. Qed.\n\nEnd Involutions.\n\n\n\n\n\n\n\n\n", "meta": {"author": "Wassasin", "repo": "ssreflect", "sha": "45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4", "save_path": "github-repos/coq/Wassasin-ssreflect", "path": "github-repos/coq/Wassasin-ssreflect/ssreflect-45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4/theories/ssrfun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7236870045546531}}
{"text": "Require Import ssreflect.\n\nDefinition one : nat := 1.\n\n(* Definition one := 1. *)\n\nDefinition one' := 1.\nPrint one'.\n\nDefinition double x := x + x.\nPrint double.\n\nEval compute in double 2.\n\nDefinition double' := fun x => x + x.\nPrint double'.\n\nDefinition quad x := let y := double x in 2 * y.\nEval compute in quad 2.\n\nDefinition quad' x := double (double x).\nEval compute in quad' 2.\n\nDefinition triple x :=\n    let double x := x + x in\n    double x + x.\nEval compute in triple 3.\n\nInductive janken : Set :=\n| gu\n| choki\n| pa.\n\nDefinition weakness t :=\n    match t with\n    | gu => pa\n    | choki => gu\n    | pa => choki\n    end.\nEval compute in weakness pa.\n\nPrint bool.\nPrint janken.\n\nDefinition wins t1 t2 :=\n    match t1, t2 with\n    | gu, choki => true\n    | choki, pa => true\n    | pa, gu => true\n    | _, _ => false\n    end.\n\nCheck wins.\nEval compute in wins gu pa.\n\nLemma weakness_wins t1 t2 :\n    wins t1 t2 = true <-> weakness t2 = t1.\nProof.\n    split.\n    - by case: t1; case: t2.\n    - move => <-; by case: t2.\nQed.\n\nModule MyNat. (* nat を新しく定義 *)\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\n(*\nFixpoint plus (m n : nat) {struct m} : nat := (* 帰納法の対象を明示する 減らないとエラー *)\n    match m with\n    | O => n\n    | S m' => S (plus m n)\n    end.\n*)\n\nFixpoint plus (m n : nat) {struct m} : nat := (* 同じ型の引数をまとめる *)\n    match m with\n    | O => n\n    | S m' => S (plus m' n)\n    end.\n\nPrint plus.\nCheck plus (S (S O)) (S O).\nEval compute in plus (S (S O)) (S O).\n\nFixpoint mult (m n : nat) {struct m} : nat :=\n    match m with\n    | O => O\n    | S m' => plus n (mult m' n)\n    end.\nEval compute in mult (S (S O)) (S O).\nEval compute in mult (S (S (S O))) (S (S O)).\nEnd MyNat.\n\nCheck nat_ind.\n\nLemma plusnS m n : m + S n = S (m + n).\nProof.\n    elim: m => /=.\n    - done.\n    - move => m IH.\n      by rewrite IH.\nRestart.\n    elim: m => /=.\n    - done.\n    - move => m -> //.\nRestart.\n    elim: m => /= [|m ->] //.\nQed.\n\nLemma plusSn m n : S m + n = S (m + n).\nProof.\n    rewrite /=. done.\n    Show Proof.\nQed.\n\nLemma plusn0 n : n + 0 = n.\nProof.\n    by rewrite /=.\nQed.\nLemma plusC m n : m + n = n + m.\nProof.\n    elim n => /= [|o <-] //.\nQed.\nLemma plusA m n p : m + (n + p) = (m + n) + p.\nProof.\n    elim m => /= [|q <-] //.\nQed.\n\nLemma multnS m n : m * S n = m + m * n.\nProof.\n    elim: m => /= [|m ->] //.\n    by rewrite !plusA [n + m]plusC.\nQed.\n\nLemma multn0 n : n * 0 = 0.\nProof.\n    elim n.\n    - done.\n    - move => m //.\nRestart.\n    elim: n => [|m] //.\nQed.\nLemma multC m n : m * n = n * m.\nProof.\n    elim m.\n    - done.\n    - move => o /= ->.\n      by rewrite multnS.\nRestart.\n    elim: m => /= [|o ->] //.\n    by rewrite multnS.\nQed.\nLemma multnDr m n p : (m + n) * p = m * p + n * p.\nProof.\n    elim m.\n    - done.\n    - move => o /= ->.\n      by rewrite plusA.\nRestart.\n    elim: m => /= [|o ->] //.\n    by rewrite plusA.\nQed.\nLemma multA m n p : m * (n * p) = (m * n) * p.\nProof.\n    elim m.\n    - done.\n    - move => /= q ->.\n      by rewrite multnDr.\nRestart.\n    elim: m => /= [|q ->] //.\n    by rewrite multnDr.\nQed.\n\nFixpoint sum n :=\n    if n is S m then n + sum m else 0.\nPrint sum.\n\nLemma double_sum n : 2 * sum n = n * (n + 1).\nProof.\n    elim n.\n    - done.\n    - move => m.\n      rewrite plusSn multnS [S m * (m + 1)]multC multnS [(m + 1) * m]multC.\n      move => <- //=.\n      rewrite -plusnS -plusnS plusn0 plusnS.\n      rewrite [m + 1 + (sum m + sum m)]plusC.\n      rewrite -!plusA.\n      rewrite [sum m + (m + 1)]plusA.\n      by rewrite [sum m + m]plusC -plusA.\nQed.\nLemma square_eq a b : (a + b) * (a + b) = a * a + 2 * a * b + b * b.\nProof.\n    by rewrite /= !multnDr ![_ * (a + b)]multC !multnDr [b * a]multC [0 * b]multC multn0 plusn0 !plusA.\nQed.", "meta": {"author": "yak1ex", "repo": "ssreflect_study", "sha": "a28ac45bba327df674ceedf45564d91e3fe6dc77", "save_path": "github-repos/coq/yak1ex-ssreflect_study", "path": "github-repos/coq/yak1ex-ssreflect_study/ssreflect_study-a28ac45bba327df674ceedf45564d91e3fe6dc77/ssreflect03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7236869784173556}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (lf1 : natural) : natural :=\n  plus y (plus lf1 lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj201_coqofml_a1HQrw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.723658555642878}}
{"text": "(*\n  Exercises for <Software Foundations> V2 CH8.\n  Author : Brethland, Early 2020.\n*)\n\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Import Strings.String.\nRequire Import Coq.Logic.FunctionalExtensionality. \nAdd LoadPath \"C:\\Users\\ycy12\\Documents\\Workspace\\LEARNING-STUFF\\Coq\".\nLoad Coq31.\n\nModule STLCProp.\nImport STLC.\n\nLemma canonical_forms_bool : ∀t,\n  empty ⊢ t ∈ Bool →\n  value t →\n  (t = tru) ∨ (t = fls).\nProof.\n  intros t HT HVal.\n  inversion HVal; intros; subst; try inversion HT; auto.\nQed.\n\nLemma canonical_forms_fun : ∀t T1 T2,\n  empty ⊢ t ∈ (Arrow T1 T2) →\n  value t →\n  exists x u, t = abs x T1 u.\nProof.\n  intros t T1 T2 HT HVal.\n  inversion HVal; intros; subst; try inversion HT; subst; auto.\n  exists x0, t0. auto.\nQed.\n\nTheorem progress : ∀t T,\n  empty ⊢ t ∈ T →\n  value t ∨ ∃t', t -->> t'.\nProof with eauto.\n  intros t T Ht.\n  remember (@empty ty) as Gamma.\n  induction Ht; subst Gamma...\n  - (* T_Var *)\n    (* contradictory: variables cannot be typed in an\n       empty context *)\n    inversion H.\n  - (* T_App *)\n    (* t = t1 t2.  Proceed by cases on whether t1 is a\n       value or steps... *)\n    right. destruct IHHt1...\n    + (* t1 is a value *)\n      destruct IHHt2...\n      * (* t2 is also a value *)\n        assert (∃x0 t0, t1 = abs x0 T11 t0).\n        eapply canonical_forms_fun; eauto.\n        destruct H1 as [x0 [t0 Heq]]. subst.\n        exists ([x0:=t2]t0)...\n      * (* t2 steps *)\n        inversion H0 as [t2' Hstp]. exists (app t1 t2')...\n    + (* t1 steps *)\n      inversion H as [t1' Hstp]. exists (app t1' t2)...\n  - (* T_Test *)\n    right. destruct IHHt1...\n    + (* t1 is a value *)\n      destruct (canonical_forms_bool t1); subst; eauto.\n    + (* t1 also steps *)\n      inversion H as [t1' Hstp]. exists (test t1' t2 t3)...\nQed.\n\nTheorem progress' : ∀t T,\n     empty ⊢ t ∈ T →\n     value t ∨ ∃t', t -->> t'.\nProof with eauto.\n  intros t.\n  induction t; intros T Ht; auto.\n  - inversion Ht;subst. inversion H1.\n  - inversion Ht;subst. right. destruct (IHt1 (Arrow T11 T))...\n    destruct (IHt2 T11)... assert(exists x0 t0, t1 = abs x0 T11 t0). \n    eapply canonical_forms_fun; eauto. destruct H1 as [x0 [t0 H1]];subst.\n    exists ([x0:=t2]t0)...\n    destruct H0. exists (app t1 x0)... destruct H. exists (app x0 t2)...\n  - right. inversion Ht;subst. destruct (IHt1 Bool)... \n    destruct (canonical_forms_bool t1); subst; eauto. destruct H. exists (test x0 t2 t3)...\nQed.\n\nInductive appears_free_in : string → tm → Prop :=\n  | afi_var : ∀x,\n      appears_free_in x (var x)\n  | afi_app1 : ∀x t1 t2,\n      appears_free_in x t1 →\n      appears_free_in x (app t1 t2)\n  | afi_app2 : ∀x t1 t2,\n      appears_free_in x t2 →\n      appears_free_in x (app t1 t2)\n  | afi_abs : ∀x y T11 t12,\n      y ≠ x →\n      appears_free_in x t12 →\n      appears_free_in x (abs y T11 t12)\n  | afi_test1 : ∀x t1 t2 t3,\n      appears_free_in x t1 →\n      appears_free_in x (test t1 t2 t3)\n  | afi_test2 : ∀x t1 t2 t3,\n      appears_free_in x t2 →\n      appears_free_in x (test t1 t2 t3)\n  | afi_test3 : ∀x t1 t2 t3,\n      appears_free_in x t3 →\n      appears_free_in x (test t1 t2 t3).\nHint Constructors appears_free_in.\n\nDefinition closed (t:tm) :=\n  ∀x, ¬appears_free_in x t.\n\nLemma free_in_context : ∀x t T Gamma,\n   appears_free_in x t →\n   Gamma ⊢ t ∈ T →\n   ∃T', Gamma x = Some T'.\nProof.\n  intros x t T Gamma H H0. generalize dependent Gamma.\n  generalize dependent T.\n  induction H;\n         intros; try solve [inversion H0; eauto].\n  - (* afi_abs *)\n    inversion H1; subst.\n    apply IHappears_free_in in H7. unfold update in H7.\n    rewrite t_update_neq in H7; assumption.\nQed.\n\nCorollary typable_empty__closed : ∀t T,\n    empty ⊢ t ∈ T →\n    closed t.\nProof.\n  intros. inversion H;subst;unfold closed in *.\n  1 : inversion H0.\n  all : intros x contra.\n  1 : apply (free_in_context _ _ (Arrow T11 T12) empty) in contra;auto.\n  3 - 4 : apply (free_in_context _ _ Bool empty) in contra;inversion contra;inversion H0;auto.\n  2 - 3 : apply (free_in_context _ _ T empty) in contra;auto.\n  all : destruct contra as [m H']; inversion H'.\nQed.\n\nLemma context_invariance : ∀Gamma Gamma' t T,\n     Gamma ⊢ t ∈ T →\n     (∀x, appears_free_in x t → Gamma x = Gamma' x) →\n     Gamma' ⊢ t ∈ T.\nProof with eauto.\n  intros.\n  generalize dependent Gamma'.\n  induction H; intros; auto.\n  - apply T_Var. rewrite <- H0...\n  - apply T_Abs.\n    apply IHhas_type. intros x1 Hafi.\n    unfold update. unfold t_update. destruct (beq_string x0 x1) eqn: Hx0x1...\n    rewrite beq_string_false_iff in Hx0x1. auto.\n  - apply T_App with T11...\nQed.\n\nLemma t_update_shadow : ∀(A : Type) (m : total_map A) x v1 v2,\n    (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\n  intros.\n  apply functional_extensionality.\n  intros. unfold t_update.\n  destruct (beq_string x0 x1) eqn:HE.\n  - auto.\n  - auto.\nQed.\n\nTheorem beq_string_refl : ∀ s, true = beq_string s s. \nProof. \n  intros s. unfold beq_string. destruct (string_dec s s) as [|Hs]. \n  - reflexivity.   \n  - destruct Hs. reflexivity. \nQed.\n\nTheorem beq_string_true_iff : ∀ x y : string,   beq_string x y = true ↔ x = y. \nProof. \n  intros x y. \n  unfold beq_string. \n  destruct (string_dec x y) as [|Hs]. \n  - subst. split. auto. auto.\n  - split. \n    + intros contra. inversion contra.\n    + intros H. destruct Hs. auto.\nQed.\n\nTheorem beq_string_false_iff : ∀ x y : string,   beq_string x y = false   ↔ x ≠ y. \nProof. \n  intros x y. rewrite <- beq_string_true_iff. \n  rewrite not_true_iff_false. reflexivity. \nQed.\n\nLemma substitution_preserves_typing : ∀Gamma x U t v T,\n  (x ⊢> U ; Gamma) ⊢ t ∈ T →\n  empty ⊢ v ∈ U →\n  Gamma ⊢ [x:=v]t ∈ T.\nProof with eauto.\n  intros Gamma x U t v T Ht Ht'.\n  generalize dependent Gamma. generalize dependent T.\n  induction t; intros T Gamma H;\n    (* in each case, we'll want to get at the derivation of H *)\n    inversion H; subst; simpl...\n  - (* var *)\n    rename s into y. destruct (eqb_spec x y) as [Hxy|Hxy].\n    + (* x=y *)\n      subst. unfold update in H2.\n      rewrite t_update_eq in H2.\n      inversion H2; subst.\n      eapply context_invariance. eassumption.\n      apply typable_empty__closed in Ht'. unfold closed in Ht'.\n      intros. apply (Ht' x0) in H0. inversion H0.\n    + (* x<>y *)\n      apply T_Var. unfold update in H2. rewrite t_update_neq in H2...\n  - (* abs *)\n    rename s into y. rename t into T. apply T_Abs.\n    destruct (eqb_spec x y) as [Hxy | Hxy].\n    + (* x=y *)\n      subst. unfold update in H5. rewrite t_update_shadow in H5. apply H5.\n    + (* x<>y *)\n      apply IHt. eapply context_invariance...\n      intros z Hafi. unfold update, t_update.\n      destruct (eqb_spec y z) as [Hyz | Hyz]; subst; trivial.\n      rewrite <- beq_string_false_iff in Hxy.\n      rewrite Hxy... rewrite <- beq_string_false_iff in *. rewrite Hyz...\nQed.\n\nTheorem preservation : ∀t t' T,\n  empty ⊢ t ∈ T →\n  t -->> t' →\n  empty ⊢ t' ∈ T.\nProof with eauto.\n  remember (@empty ty) as Gamma.\n  intros t t' T HT. generalize dependent t'.\n  induction HT;\n       intros t' HE; subst Gamma; subst;\n       try solve [inversion HE; subst; auto].\n  - (* T_App *)\n    inversion HE; subst...\n    (* Most of the cases are immediate by induction,\n       and eauto takes care of them *)\n    + (* ST_AppAbs *)\n      apply substitution_preserves_typing with T11...\n      inversion HT1...\nQed.\n\nDefinition stuck (t:tm) : Prop :=\n  (normal_form step) t ∧ ¬value t.\nCorollary soundness : ∀t t' T,\n  empty ⊢ t ∈ T →\n  t -->* t' →\n  ~(stuck t').\nProof.\n  intros t t' T Hhas_type Hmulti. unfold stuck.\n  intros [Hnf Hnot_val]. unfold normal_form in Hnf.\n  induction Hmulti.\n  - eapply progress in Hhas_type. destruct Hhas_type;auto.\n  - eapply IHHmulti;auto. eapply preservation. apply Hhas_type. auto.\nQed.\n\nTheorem unique_types : ∀Gamma e T T',\n  Gamma ⊢ e ∈ T →\n  Gamma ⊢ e ∈ T' →\n  T = T'.\nProof.\n  intros Gamma e. generalize dependent Gamma. \n  induction e;intros;inversion H;subst;inversion H0;subst;auto.\n  - rewrite H3 in H4. inversion H4;auto.\n  - specialize (IHe2 _ _ _ H6 H8);subst. specialize (IHe1 _ _ _ H4 H5). inversion IHe1. auto.\n  - specialize (IHe _ _ _ H6 H7);subst;auto.\n  - specialize (IHe2 _ _ _ H7 H10);auto. \nQed.\n\nModule STLCArith.\nImport STLC.\n\nInductive ty : Type :=\n  | Arrow : ty → ty → ty\n  | Nat : ty.\n\nInductive tm : Type :=\n  | var : string → tm\n  | app : tm → tm → tm\n  | abs : string → ty → tm → tm\n  | const : nat → tm\n  | scc : tm → tm\n  | prd : tm → tm\n  | mlt : tm → tm → tm\n  | test0 : tm → tm → tm → tm.\n\n(* Leaving STLCArith *)", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/Coq32.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8244619350028205, "lm_q1q2_score": 0.7234462127689838}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import Omega.\n(*\n(* https://github.com/affeldt-aist/seplog/blob/master/lib/ssrnat_ext.v *)\nRequire Import ssrnat_ext.                  (* ssromega *)\n*)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* Set Print All. *)\n\nLtac ssromega :=\n  (repeat ssrnat2coqnat_hypo ;\n   ssrnat2coqnat_goal ;\n   omega)\nwith ssrnat2coqnat_hypo :=\n  match goal with\n    | H : context [?L < ?R] |- _ => move/ltP: H => H\n    | H : context [?L <= ?R] |- _ => move/leP: H => H\n    | H : context [?L < ?M < ?R] |- _ => let H1 := fresh in case/andP: H => H H1\n    | H : context [?L <= ?M < ?R] |- _ => let H1 := fresh in case/andP: H => H H1\n    | H : context [?L <= ?M <= ?R] |- _ => let H1 := fresh in case/andP: H => H H1\n    | H : context [addn ?L ?R] |- _ => rewrite <- plusE in H\n    | H : context [muln ?L ?R] |- _ => rewrite <- multE in H\n    | H : context [subn ?L ?R] |- _ => rewrite <- minusE in H\n    | H : ?x == _ |- _ => match type of x with nat => move/eqP in H end; idtac x\n    | H : _ == ?x |- _ => match type of x with nat => move/eqP in H end; idtac x\n    | H : _ != ?x |- _ => match type of x with nat => move/eqP in H end\n  end\nwith ssrnat2coqnat_goal :=\n  rewrite -?plusE -?minusE -?multE;\n  match goal with\n    | |- is_true (_ < _)%nat => apply/ltP\n    | |- is_true (_ <= _)%nat => apply/leP\n    | |- is_true (_ && _) => apply/andP; split; ssromega\n    | |- is_true (?x != _) => match type of x with nat => apply/eqP end\n    | |- is_true (_ != ?x) => match type of x with nat => apply/eqP end\n    | |- is_true (?x == _) => match type of x with nat => apply/eqP end\n    | |- is_true (_ == ?x) => match type of x with nat => apply/eqP end\n    | |- _ /\\ _ => split; ssromega\n    | |- _ \\/ _ => (left; ssromega) || (right; ssromega)\n    | |- _ => idtac\n  end.\n\nGoal forall x y : nat, x + 4 - 2 > y + 4 -> (x + 2) + 2 >= y + 6.\nProof.\n  intros.\n  ssromega.\nQed.\n\n\n(* どちらも、m < n での場合分けで良い。 *)\nPrint maxn.            (* = fun m n : nat => if m < n then n else m *)\nPrint minn.            (* = fun m n : nat => if m < n then m else n *)\n\nLtac linear_arithmetic' :=\n  intros;\n  repeat match goal with\n         | [ |- context[maxn ?a ?b] ] =>\n           rewrite {1}/maxn; case: (leqP b a); intros\n\n         | [ H : context[maxn ?a ?b] |- _ ] =>\n           let H' := fresh in\n           rewrite {1}/maxn in H; case: (leqP b a) => H'; try rewrite H' in H\n\n         | [ |- context[minn ?a ?b] ] =>\n           rewrite {1}/minn; case: (leqP b a); intros\n\n         | [ H : context[minn ?a ?b] |- _ ] =>\n           let H' := fresh in\n           rewrite {1}/minn in H; case: (leqP b a) => H';\n           try (rewrite leqNgt in H'; move/Bool.negb_true_iff in H'; rewrite H' in H)\n\n         | _ => idtac\n         end.\n(* case H' : (a < b) の H' が展開できないため、それを使うのを避ける。 *)\n(* destruct (a < b) eqn:H' としてもよい。 *)\n(*\n           let H' := fresh in\n           rewrite {1}/maxn; destruct (a < b) eqn: H'; intros\n*)\n\nLtac linear_arithmetic :=\n  linear_arithmetic';\n  try ssromega;\n  rewrite //=.\n\n(* sample *)\n\nGoal forall n m, maxn n m = n <-> m <= n.\nProof.\n  split.\n  - move=> H.\n    rewrite {1}/maxn in H.\n    case: (leqP m n) => H'.\n    + done.\n    + rewrite H' in H.\n      by ssromega.\n  - move=> H.\n    rewrite {1}/maxn.\n    case: (leqP m n) => H'.\n    + done.\n    + ssromega.\n\n  Restart.\n  \n  split.\n  - by linear_arithmetic.\n  - by linear_arithmetic.\nQed.\n\nLemma leq_ltF m n : m <= n <-> (n < m) = false.\nProof.\n  rewrite leqNgt.\n  split.\n  - by move/Bool.negb_true_iff.\n  - by move=> H; apply/Bool.negb_true_iff.\nQed.\n\nGoal forall n m, minn n m = n <-> n <= m.\nProof.\n  split.\n  - move=> H.\n    rewrite {1}/minn in H.\n    case: (leqP m n) => H'.\n    + move/leq_ltF in H'.\n      rewrite H' in H.\n      by ssromega.\n    + by ssromega.\n\n  - move=> H.\n    rewrite {1}/minn.\n    case: (leqP m n) => H'.\n    + by ssromega.\n    + done.\n    \n  Restart.\n    \n  split.\n  - by linear_arithmetic.\n  - by linear_arithmetic.\nQed.\n\nGoal forall m1 n1 m2 n2, m1 <= m2 -> n1 <= n2 -> maxn m1 n1 <= m2 + n2.\nProof.\n  linear_arithmetic'.\n  - ssromega.\n  - ssromega.\n\n  Restart.\n    \n  move=> m1 n1 m2 n2.\n  rewrite /maxn.\n  Check leqP n1 m1.\n  case: (leqP n1 m1) => H1 H2 H'.\n  - ssromega.\n  - ssromega.\nQed.\n\n(* ***** *)\n\nLtac simplify := intros;\n                 try autorewrite with core in *;\n                 simpl in *.\n\nLtac equality := intuition congruence.\n\nLtac cases E := let Heq := fresh \"Heq\" in\n                destruct E eqn: Heq. (* eqn: のスペースが要る。 *)\n\n(* ***** *)\n\nRequire Import Ascii.\nRequire Import String.\nOpen Scope string_scope.\n\nSection SSRAscii.\n\n  Definition eqAscii (a b : ascii) : bool :=\n    match ascii_dec a b with\n    | left _ => true\n    | right _ => false\n    end.\n\n  Compute eqAscii \"a\" \"a\".                  (* true *)\n  Compute eqAscii \"a\" \"b\".                  (* false *)\n  \n  Lemma ascii_eqP (a b : ascii) : reflect (a = b) (eqAscii a b).\n  Proof.\n    rewrite /eqAscii.\n    (* reflect (a = b) (if ascii_dec a b then true else false) *)\n    apply: (iffP idP); by case: (ascii_dec a b).\n  Qed.\n  \n  Fail Canonical ascii_eqType := [eqType of ascii].\n\n  Definition ascii_eqMixin := @EqMixin ascii eqAscii ascii_eqP.\n  Canonical ascii_eqType := @EqType ascii ascii_eqMixin.\n\n  Canonical ascii_eqType' := [eqType of ascii].\nEnd SSRAscii.\n\nCheck ascii_eqType : eqType.\nCheck \"a\"%char : ascii.\nCheck \"a\"%char : ascii_eqType.\n\nCheck true : bool.\nCheck true : bool_eqType.\n\nCheck 1 : nat.\nCheck 1 : nat_eqType.\n  \nSection SSRString.\n  \n  Definition eqString (s t : string) : bool :=\n    match string_dec s t with\n    | left _ => true\n    | right _ => false\n    end.\n  \n  Compute eqString \"aaaa\" \"aaaa\".             (* true *)\n  Compute eqString \"aaaa\" \"aa\".               (* false *)\n  \n  Lemma string_eqP (x y : string) : reflect (x = y) (eqString x y).\n  Proof.\n    rewrite /eqString.\n    apply: (iffP idP); by case: (string_dec x y).\n  Qed.        \n  \n  Definition string_eqMixin := @EqMixin string eqString string_eqP.\n  Canonical string_eqType := @EqType string string_eqMixin.\n\nEnd SSRString.\n\nCheck \"aaa\" = \"aaa\" : Prop.\nCheck \"aaa\" == \"aaa\" : bool.\nCheck \"aaa\" == \"aaa\" : Prop.\n\n(* Notation var := string. *)\n\n(* END *)\n\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/frap/ssr_frap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7234462078412963}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import Program.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Print All.\n\n(* **** *)\n(* perm *) (* seq.v *)\n(* **** *)\n\nVariable T : eqType.\n\nCheck perm_eq : seq T -> seq T -> bool.\nSearch _ perm_eq.\nCompute perm_eq [:: 1; 2] [:: 1; 2].        (* true *)\n\nCheck perm_eq_refl : forall (T : eqType) (s : seq T), perm_eq s s.\nCheck perm_eq_sym : forall T : eqType, symmetric perm_eq.\nCheck perm_eq_trans : forall T : eqType, transitive perm_eq.\nCheck perm_cons : forall (T : eqType) (x : T) (s1 s2 : seq T),\n    perm_eq (x :: s1) (x :: s2) = perm_eq s1 s2.\n\nLemma perm_cons' : forall (n : T) (l l' : seq T), \n    perm_eq l l' -> perm_eq (n :: l) (n :: l').\nProof.\n  move=> n l l' H.\n  by rewrite perm_cons.\nQed.\n\n(*\nLemma perm_cons'2 :  forall (T : eqType) (n1 n2 : T) (s1 s2 : seq T),\n    perm_eq [:: n1, n2 & s1] [:: n2, n1 & s2] = perm_eq (n1 :: s1) (n1 :: s2).\nProof.\nAdmitted.\n *)\n\nLemma perm_iff : forall (m n : seq T),\n                   (forall l, perm_eq m l = perm_eq n l) <-> perm_eq m n.\nProof.\n  move=> m n.\n  split=> H.\n  - by rewrite H.\n  - by apply/perm_eqlP.\nQed.\n\nLemma perm_swap : forall (l l' : seq T) (x a : T),\n                    perm_eq [:: x, a & l] l' = perm_eq [:: a, x & l] l'.\nProof.\n  move=> l l' x a.\n  apply perm_iff.\n  Check cat1s.\n  rewrite -[[:: x, a & l]]cat1s.\n  rewrite -[[:: a & l]]cat1s.\n  rewrite -[[:: a, x & l]]cat1s.\n  rewrite -[[:: x & l]]cat1s.\n  apply/perm_eqlP.\n  by apply (perm_catCA [:: x] [:: a] l).\nQed.\n\nLemma perm_swap_cat : forall (l l' l'' : seq T),\n    perm_eq (l ++ l') l'' = perm_eq (l' ++ l) l''.\nProof.\n  move=> l l' l''.\n  apply perm_iff.\n  by rewrite perm_catC.\nQed.\n\n(* :: と ++ は左結合で、同じ優先順位である。 *)\nLemma perm_swap_cons_cat : forall (x : T) (l l' l'' : seq T),\n    perm_eq (x :: l ++ l') l'' = perm_eq (l ++ x :: l') l''.\nProof.\n  move=> x l l' l''.\n  apply perm_iff.\n  rewrite -[x :: l ++ l']cat1s.\n  rewrite -[x :: l']cat1s.\n  by rewrite -perm_catCA.\nQed.\n\nHint Resolve perm_cons perm_eq_refl perm_eq_sym perm_eq_trans : perm.\nHint Rewrite perm_iff perm_swap perm_swap_cat : perm.\n\n(* **** *)\n(* sort *) (* path.v *)\n(* **** *)\n\nVariable leT : rel T.\nHypothesis leT_tr : transitive leT.\nHypothesis leT_false : forall x y, leT x y = false -> leT y x. (* ???? *)\n\nCheck sorted leT : seq T -> bool.\nSearch _ sorted.\n\nLemma sorted_nil : sorted leT [::].\nProof.\n    by [].\nQed.\n\nLemma sorted_cons1 n : sorted leT [:: n].\nProof.\n    by [].\nQed.\n\nLemma sorted_consn m n l :\n  sorted leT (n :: l) -> leT m n -> sorted leT [:: m, n & l].\nProof.\n  move=> /= H R.\n    by apply/andP.                            (* path の定義のまま。 *)\nQed.\n\nHint Resolve sorted_nil sorted_cons1 sorted_consn : sort.\n\nLemma sorted_cons_inv h l : sorted leT (h :: l) -> sorted leT l.\nProof.\n  apply: subseq_sorted.\n  - by apply: leT_tr.\n  - by apply: subseq_cons.\nQed.\n\nLemma sorted_inv m n l :\n  sorted leT [:: m, n & l] -> (leT m n /\\ sorted leT (n :: l)).\nProof.\n  by move/andP.                             (* path の定義のまま。 *)\nQed.\n\nLemma cat__sorted l l' :\n  sorted leT (l ++ l') -> (sorted leT l /\\ sorted leT l').\nProof.\n  elim: l.\n  - by [].\n  - move=> a l IHl H.\nAdmitted.                                   (* XXXX *)\n  \n(*\nLemma sorted_cons_inv2 m n l :\n  sorted leT [:: m, n & l] -> sorted leT (m :: l).\nProof.\n  apply: subseq_sorted.\n  - by apply: leT_tr.\n  - rewrite -[(m :: l)]cat1s.\n    rewrite -[[:: m, _ & _]]cat1s.\n    apply: cat_subseq.\n    + by apply: subseq_refl.\n    + by apply: subseq_cons.\nQed.\n\nLemma subseq_cons2 (n : T) (l l' : seq T) :\n  subseq l l' -> subseq (n :: l) (n :: l').\nProof.\n  rewrite -[(n :: l)]cat1s.\n  rewrite -[(n :: l')]cat1s.\n  by apply: cat_subseq.\nQed.\n\nLemma perm__subseq l l' :\n  (exists l'', perm_eq (l' ++ l'') l) ->\n  (sorted leT l -> sorted leT l') -> subseq l' l.\nProof.\nAdmitted.\n\nLemma perm__sorted n l l' :\n  (exists l'', perm_eq (l' ++ l'') l) ->    (* perm__subseq *)\n  (sorted leT l -> sorted leT l') ->        (* perm__subseq *)\n  sorted leT (n :: l) -> sorted leT (n :: l').\nProof.\n  move=> He Hs H.\n  Check (@subseq_sorted T leT leT_tr (n :: l') (n :: l)).\n  apply (@subseq_sorted T leT leT_tr (n :: l') (n :: l)).\n  - apply subseq_cons2.\n    apply perm__subseq; by [].\n  - by [].\nAdmitted.\n\nLemma perm_app : forall (n : nat) (l'' l l' : seq nat),\n    perm_eq l'' (l ++ l') -> perm_eq (n :: l'') (l ++ n :: l').\nAdmitted.\n *)\n\nLemma sorted__sorted' (x : T) (l : seq T) :\n  (forall y, y \\in l -> leT x y) -> sorted leT l -> sorted leT (x :: l).\nProof.\n  move=> Hxy.\n  Check @path_min_sorted T leT x l.\n  rewrite -(@path_min_sorted T leT x l).\n  - by [].\n  - (* Goal : {in l, forall y0 : T, leT x y0}, ssrbool.v l.222, l.1571 *)\n    (*             {in A, P1} <-> forall x, x \\in A -> Qx.             *)\n    move=> y Hyl.\n      by apply: (Hxy y).\nQed.\n(* 別証明 *)\n(* (forall y0 : T, y0 \\in x' -> leT x y0) <-> {in x', forall y : T, leT x y} *)\n(* であることにも。 *)\nLemma sorted__sorted (x : T) (l : seq T) :\n  {in l, forall y : T, leT x y} -> sorted leT l -> sorted leT (x :: l).\nProof.\n  move=> H Hs.\n  rewrite /sorted.\n  by rewrite path_min_sorted.\nQed.\n\nLemma sorted__in (n n' : T) (l l' : seq T) :\n  perm_eq (n :: l') l ->\n  (sorted leT l' -> sorted leT l) ->\n(*  head n l = n \\/ head n l = head n l' *)\n  leT n' n -> path leT n' l' ->\n  {in l, forall y : T, leT n' y}.\nProof.\nAdmitted.                                   (* XXX *)\n\nCheck path_min_sorted : forall (T : eqType) (leT : rel T) (x : T) (s : seq_predType T),\n    {in s, forall y : T, leT x y} -> path leT x s = sorted leT s.\n\nProgram Fixpoint merge (ls1 ls2 : seq T)\n  {measure (size ls1 + size ls2)} :\n  {l' : seq T | perm_eq (ls1 ++ ls2) l' /\\\n                (sorted leT ls1 -> sorted leT ls2 -> sorted leT l')} :=\n  (* match (ls1, ls2) とすると、ペアどうしの代入の前提が解けない。 *)\n  (* 「'」をつけてもだめのよう。 *)\n  match ls1 with\n  | [::] => ls2\n  | x :: ls1' => match ls2 with\n                 | [::] => ls1\n                 | y :: ls2' => if (leT x y) then\n                                  x :: (merge ls1' ls2)\n                                else\n                                  y :: (merge ls1 ls2')\n                 end\n  end.\nObligations.\nNext Obligation.\n  split.\n  - by rewrite [ls1' ++ []%list]List.app_nil_r.\n  - by [].\nDefined.\nNext Obligation.\n  apply PeanoNat.Nat.add_le_lt_mono.\n  - by [].\n  - by [].\nDefined.\nNext Obligation.\n  split.\n  - remember (merge ls1' (y :: ls2') _).\n    case Hx : s => /= [x' [Hxp Hxs]].\n    remember (merge (x :: ls1') ls2' _).\n    case Hy : s0 => /= [y' [Hyp Hys]].\n    case H : (leT x y); subst.\n    + by rewrite perm_cons.\n    + rewrite -cat_cons.\n      rewrite perm_swap_cat.\n      rewrite cat_cons.\n      rewrite perm_cons.\n        by rewrite perm_swap_cat.\n  - remember (merge ls1' (y :: ls2') _).\n    case Hx : s => /= [x' [Hxp Hxs]].\n    (* x' は ls1 ++ ls2 = x::ls1' ++ y::ls2' から x を抜いたもの。 *)\n    \n    remember (merge (x :: ls1') ls2' _).\n    case Hy : s0 => /= [y' [Hyp Hys]].\n    (* y' は ls1 ++ ls2 = x::ls1' ++ y::ls2' から y を抜いたもの。 *)\n\n    case H : (leT x y); subst.\n    + move=> H1 H2.\n      apply sorted__sorted.\n      * Check (@sorted__in y x x' (ls1' ++ ls2')).\n        apply (@sorted__in y x x' (ls1' ++ ls2')).\n        ** by rewrite perm_swap_cons_cat.\n        ** move=> H'.\n           apply cat__sorted in H'.\n           case: H' => H'1 H'2.\n           by apply Hxs.\n        ** by [].\n        ** admit.                           (* XXXX *)\n      * apply Hxs.\n        eapply path_sorted.\n        apply H1.\n        by apply H2.\n    + move=> H1 H2.\n      apply sorted__sorted.\n      * Check (@sorted__in x y y' (ls1' ++ ls2')).\n        apply (@sorted__in x y y' (ls1' ++ ls2')).\n        ** by [].\n        ** move=> H'.\n           apply cat__sorted in H'.\n           case: H' => H'1 H'2.\n           by apply Hys.\n        ** by apply leT_false.              (* ???? *)\n        ** admit.                           (* XXXX *)\n      * apply Hys.\n        apply H1.\n        eapply path_sorted.\n        by apply H2.\nDefined.\n\n(* ******************* *)\n(* insert を使う merge *)\n(* ******************* *)\nProgram Fixpoint insert n l {struct l} : \n  {l' : seq T | perm_eq (n :: l) l' /\\\n                (sorted leT l -> sorted leT l') /\\ \n                (head n l' = n \\/ head n l' = head n l)} := \n  match l with\n  | [::] => [:: n]\n  | n' :: l' => \n    if leT n n' then\n      n :: n' :: l'\n    else\n      n' :: insert n l'\n  end.\nObligations.\nNext Obligation.\n  case Hnn' : (leT n n').\n  - by auto with sort.\n  - split.\n    + erewrite perm_swap.\n      by rewrite perm_cons.\n    + split.\n      * move=> H.\n        apply sorted__sorted.\n(*\n        have H1 : sorted leT l' by apply: (@sorted_cons_inv n' l'). l', x : seq T\n        have H2 : sorted leT x by auto.\n*)\n        ** apply (@sorted__in n n' x l').\n           *** by apply i.\n           *** by apply i0.\n           *** by apply leT_false.          (* ????? *)\n           *** by apply H.\n        ** apply i0.\n           eapply path_sorted.\n             by apply H.\n      * by auto.\nDefined.\n\nHint Resolve sorted_cons_inv : sort.\nHint Resolve perm_cons' : perm.\n\nProgram Fixpoint merge' (ls1 ls2 : seq T) :\n  {l' : seq T | perm_eq (ls1 ++ ls2) l' /\\\n                (sorted leT ls1 /\\ sorted leT ls2 -> sorted leT l')} :=\n  match ls1 with\n  | nil => ls2\n  | h :: ls' => insert h (merge' ls' ls2)\n  end.\nObligations.\nNext Obligation.\n  split.\n  - by [].\n  - by case.\nDefined.\nNext Obligation.\n  remember (insert h x) as s.\n  case H : s => /= {Heqs}; subst.\n  intuition.                          (* ゴールの /\\ をsplit する。 *)\n  - Check @perm_eq_trans T (h :: x) (h :: ls' ++ ls2) _.\n    eapply (@perm_eq_trans T (h :: x) (h :: ls' ++ ls2) _). (* _ は _x_ *)\n    + by rewrite perm_cons.\n    + by [].\n  - apply H1, H2.\n    + by apply path_sorted with (x := h).\n    + by [].\n  - eapply (@perm_eq_trans T (h :: x) (h :: ls' ++ ls2) _). (* _ は _x_ *)\n    + by rewrite perm_cons.\n    + by [].\n  - apply H1, H2.\n    + by apply path_sorted with (x := h).\n    + by [].\nDefined.\n\n(* 証明のないinsertを呼ぶと、ゴールにinsertが残り、証明できない。 *)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/prog/ssr_msort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7234462037010233}}
{"text": "Require Import Qnn.\n\nLocal Open Scope Qnn.\n\nRequire Import FunctionalExtensionality.\n\n(** Nonnegative lower reals *)\n(** The nonnegative lower real numbers are encoded here\n    by lower Dedekind cuts. That is, they are predicates\n    on non-negative rational numbers, and can be viewed\n    essentially as subsets of rational numbers. They\n    are downward-closed ([dclosed]) and upward-open ([uopen]),\n    which means that if the predicate holds for some rational\n    number [q], it holds for all rationals which are less, and\n    some rational which is greater.\n\n    We show that [LPReal] forms a semiring, and then we can use\n    the [ring] tactic with them.\n\n    These guys are interesting because we can have proofy\n    bits in them. For example, we can create a real number\n    which is 0 if P = NP and 1 if P /= NP. [LPRindicator]\n    allows us, for any proposition, to create a real number \n    which is 1 iff the proposition is true, and 0 iff it\n    is false.\n\n    We also have a definition of suprema ([LPRsup]) over an\n    arbitrary indexing type.\n\n    The lower real numbers are closed under addition, multiplication,\n    min, max, supremum, but not (necessarily) under subtraction\n    or infima.\n\n    If LEM is admitted, the lower reals are simply the real numbers\n    as Dedekind cuts.\n\n *)\nRecord LPReal :=\n  { lbound :> Qnn -> Prop\n  ; dclosed : forall q, lbound q -> forall q', q' <= q -> lbound q'\n  ; uopen   : forall q, lbound q -> exists q', q < q' /\\ lbound q'\n  }.\n\nDefinition LPRle (r s : LPReal) : Prop :=\n  forall q, r q -> s q.\n\nDefinition LPRge (r s : LPReal) : Prop := LPRle s r.\n\nDefinition LPRlt (r s : LPReal) : Prop :=\n  exists q, ~ r q /\\ s q.\n\nDefinition LPRgt (r s : LPReal) : Prop := LPRlt s r.\n\nDefinition LPReq (r s : LPReal) : Prop :=\n  LPRle r s /\\ LPRle s r.\n\nDefinition LPRQnn (q : Qnn) : LPReal.\nProof.\nrefine (\n  {| lbound := fun q' => (q' < q)%Qnn |}\n).\n- abstract (intros; subst; eapply Qnnle_lt_trans; eassumption).\n- abstract (intros q0 H; destruct (Qnnbetween q0 q H) as [x xbetween];\n  eexists; eassumption).\nDefined.\n\nInductive LPRplusT {x y : LPReal} : Qnn -> Prop :=\n  | LPRplusL : forall q, x q -> LPRplusT q\n  | LPRplusR : forall q, y q -> LPRplusT q\n  | LPRplusB : forall q q' sum , x q -> y q' -> sum <= q + q' -> LPRplusT sum.\n\nArguments LPRplusT : clear implicits.\n\nLemma LPRplus_dclosed : forall x y q, \n  LPRplusT x y q -> forall q', q' <= q -> LPRplusT x y q'.\nProof.\nintros.\ninversion H; subst; \n[apply LPRplusL | apply LPRplusR | eapply LPRplusB].\neapply dclosed; eassumption.\neapply dclosed; eassumption.\neassumption. eassumption. \neapply Qnnle_trans; eassumption.\nQed.\n\nLemma LPRplus_uopen : forall x y q, \n  LPRplusT x y q -> exists q', q < q' /\\ LPRplusT x y q'.\nProof.\nintros. destruct H.\n  + pose proof (uopen _ _ H). destruct H0.\n    exists x0. intuition. apply LPRplusL. assumption.\n  + pose proof (uopen _ _ H). destruct H0.\n    exists x0. intuition. apply LPRplusR. assumption.\n  + pose proof (uopen _ _ H). destruct H2. \n    exists (x0 + q'). intuition. eapply Qnnle_lt_trans. eassumption.\n    rewrite (SRadd_comm Qnnsrt).\n    rewrite (SRadd_comm Qnnsrt x0).\n    apply Qnnplus_le_lt_compat. apply Qnnle_refl. assumption. \n    eapply LPRplusB. eassumption. eassumption. apply Qnnle_refl.\nQed.\n\nDefinition LPRplus (x y : LPReal) : LPReal :=\n  {| lbound := LPRplusT x y\n   ; dclosed := LPRplus_dclosed x y\n   ; uopen := LPRplus_uopen x y\n  |}.\n\nInductive LPRmultT {x y : LPReal} {q : Qnn} : Prop :=\n  MkLPRmultT : forall a b, lbound x a -> lbound y b -> (q <= a * b) -> LPRmultT.\n\nArguments LPRmultT : clear implicits.\n\nLemma LPRmult_dclosed : forall x y q, \n  LPRmultT x y q -> forall q', q' <= q -> LPRmultT x y q'.\nProof.\nintros.\ndestruct H.\neconstructor; try eassumption. \neapply Qnnle_trans; eassumption.\nQed.\n\nLemma LPRmult_uopen : forall x y q, \n  LPRmultT x y q -> exists q', q < q' /\\ LPRmultT x y q'.\nProof.\nintros. destruct H as [a b pa pb prod].\n  pose proof (uopen _ _ pa). destruct H as [a' [pa' xa']].\n  pose proof (uopen _ _ pb). destruct H as [b' [pb' yb']].\n  exists (a' * b'). split. eapply Qnnle_lt_trans. eassumption.\n  apply Qnnle_lt_trans with (a * b').\n  rewrite pb'. reflexivity. \n  apply Qnnmult_lt_compat_r.\n  eapply Qnnle_lt_trans. apply (nonneg b). assumption. assumption.\n  constructor 1 with a' b'; intuition.\nQed.\n\nDefinition LPRmult (x y : LPReal) : LPReal :=\n  {| lbound := LPRmultT x y\n  ;  uopen := LPRmult_uopen x y\n  ;  dclosed := LPRmult_dclosed x y\n  |}.\n\nLemma LPReq_prop : forall r s, LPReq r s ->\n  forall q, lbound r q <-> lbound s q.\nProof.\nintros. destruct H. split. apply H. apply H0.\nQed.\n\n(** Import the Ensemble Extensionality Axiom *)\nRequire Import Coq.Sets.Ensembles.\n\n(** Import the Proof Irrelevance Axiom *)\nRequire Import Coq.Logic.ProofIrrelevance.\n\nLemma LPReq_compat : forall r s, LPReq r s -> r = s. \nProof.\nintros. pose proof H as eq. destruct H.\nunfold LPRle in *.\nassert (lbound r = lbound s).\napply Extensionality_Ensembles. intuition.\ndestruct r, s.\nsimpl in *. induction H1.\nf_equal; apply proof_irrelevance.\nQed.\n\nLtac LPRsrttac := \nrepeat match goal with\n| [ |- _ /\\ _ ] => split\n| [ |- forall _, _] => intros\n| [ H : lbound (LPRQnn _) _ |- _ ] => simpl in H\n| [ H : lbound (LPRplus _ _) _ |- _ ] => destruct H\n| [ H : lbound (LPRmult _ _) _ |- _ ] => destruct H\n| [ H : exists x, _ |- _ ] => destruct H\n| [ H : _ /\\ _ |- _ ] => destruct H\n| [ H : _ < 0 |- _ ] => apply Qnnlt_not_le in H; unfold not in H;\n  apply False_rect; apply H; apply nonneg\n| [ |- lbound (LPRplus (LPRQnn 0) _) _ ] => apply LPRplusR\n| [ |- lbound (LPRplus _ (LPRQnn 0)) _ ] => apply LPRplusL\n| [ Hm : lbound ?m _, Hn : lbound ?n _ |- lbound (LPRplus ?m ?n) _ ]\n   => eapply LPRplusB; [ eassumption | eassumption | ]\n| [ Hm : lbound ?m ?q |- lbound (LPRplus ?m _) ?q ]\n   => apply LPRplusL\n| [ Hn : lbound ?n ?q |- lbound (LPRplus _ ?n) ?q ]\n   => apply LPRplusR\n| [ |- _ ] => assumption\nend.\n\n\n\nTheorem LPRsrt : semi_ring_theory (LPRQnn 0) (LPRQnn 1)\n  LPRplus LPRmult eq.\nProof.\nconstructor; intros; apply LPReq_compat; unfold LPReq, LPRle;\nLPRsrttac.\n- rewrite H1. ring_simplify. reflexivity.\n- rewrite H1. ring_simplify. reflexivity.\n- apply LPRplusL. LPRsrttac. \n- apply LPRplusL. LPRsrttac.\n- eapply LPRplusB; try eassumption. LPRsrttac.\n- apply LPRplusL. LPRsrttac.\n- eapply LPRplusB; try eassumption. LPRsrttac.\n- eapply LPRplusB with (q + q0) (q'). eapply LPRplusB with q q0.\n  eassumption. eassumption. reflexivity. assumption.\n  rewrite H1, H3. ring_simplify. reflexivity.\n- apply LPRplusR. LPRsrttac.\n- eapply LPRplusB; try eassumption. LPRsrttac.\n- eapply LPRplusR. LPRsrttac.\n- eapply LPRplusB; try eassumption. LPRsrttac.\n- apply LPRplusR. LPRsrttac.\n- eapply LPRplusB with q (q'0 + q'). assumption. \n  eapply LPRplusB with q'0 q'; try assumption.\n  reflexivity. rewrite H1, H3. ring_simplify.\n  reflexivity.\n- eapply dclosed. eassumption. rewrite H1.\n  replace b with (1 * b) at 2 by ring.\n  apply Qnnmult_le_compat. rewrite H. reflexivity.\n  reflexivity.\n- simpl. pose proof (uopen _ _ H). destruct H0 as [q' [qq' nq']].\n  constructor 1 with (q / q') q'. apply Qnndiv_lt. assumption. intuition.\n  unfold Qnndiv. rewrite <- (SRmul_assoc Qnnsrt).\n  replace (Qnninv q' * q') with 1. replace (q * 1) with q by ring.\n  reflexivity. symmetry. rewrite (SRmul_comm Qnnsrt). \n  apply Qnnmult_inv_r. eapply Qnnle_lt_trans. apply (nonneg q).\n  assumption.\n- simpl. constructor 1 with b a; intuition.\n  rewrite (SRmul_comm Qnnsrt).\n  assumption.\n- simpl. constructor 1 with b a; intuition.\n  rewrite (SRmul_comm Qnnsrt).\n  assumption.\n- simpl. constructor 1 with (a * a0) b0.\n  constructor 1 with a a0; intuition.\n  intuition. rewrite H1, H3. ring_simplify.\n  reflexivity. \n- simpl. constructor 1 with a0 (b0 * b); intuition.\n  constructor 1 with b0 b; intuition.\n  rewrite H1, H3. ring_simplify. reflexivity.\n- apply LPRplusL. simpl. econstructor; eauto.\n- apply LPRplusR. simpl. econstructor; eauto.\n- eapply LPRplusB. constructor 1 with q0 b; intuition. apply Qnnle_refl.\n  constructor 1 with q' b; intuition.\n  apply Qnnle_refl. rewrite H1, H3. ring_simplify.\n  reflexivity.\n- constructor 1 with a b; try (apply LPRplusL); assumption.\n- constructor 1 with a b; try (apply LPRplusR); assumption.\n- constructor 1 with (a0 + a) (Qnnmax b0 b); intuition.\n  eapply LPRplusB; try eassumption. reflexivity.\n  pattern b0, b, (Qnnmax b0 b). apply Qnnmax_induction; intros; assumption.\n  rewrite H1, H3, H5.\n  pattern b0, b, (Qnnmax b0 b). apply Qnnmax_induction; intros.\n  rewrite H6. ring_simplify. reflexivity.\n  rewrite H6. ring_simplify. reflexivity.\nQed.\n\nAdd Ring LPR_Ring : LPRsrt.\n\nInfix \"<=\" := LPRle : LPR_scope.\nInfix \"==\" := LPReq : LPR_scope.\nInfix \">=\" := LPRge : LPR_scope.\nInfix \">\"  := LPRgt : LPR_scope.\nInfix \"<\"  := LPRlt : LPR_scope.\nInfix \"+\"  := LPRplus : LPR_scope.\nInfix \"*\"  := LPRmult : LPR_scope.\n\nNotation \"'0'\" := (LPRQnn 0) : LPR_scope.\nNotation \"'1'\" := (LPRQnn 1) : LPR_scope.\n\nDelimit Scope LPR_scope with LPR.\n\nLocal Open Scope LPR.\n\nDefinition LPRle_refl (r : LPReal) : r <= r :=\n  fun _ p => p.\n\nDefinition LPRle_trans {r s t : LPReal} \n  (rs : r <= s) (st : s <= t) : r <= t :=\n  fun q prf => (st q (rs q prf)).\n\nRequire Import RelationClasses.\nInstance LPRle_preorder : PreOrder LPRle.\nProof.\nconstructor. \n- unfold Reflexive. apply LPRle_refl.\n- unfold Transitive. apply @LPRle_trans.\nQed.\n\nLemma LPReq_refl (x : LPReal) : x == x.\nProof. split; reflexivity. Qed.\n\nLemma LPReq_compat_backwards (x y : LPReal) : x = y -> x == y.\nProof. intros H; induction H; apply LPReq_refl. Qed.\n\nLemma LPReq_trans (x y z : LPReal) \n  : x == y -> y == z -> x == z.\nProof. intros. destruct H; destruct H0; split;\n  eapply LPRle_trans; eassumption.\nQed.\n\nTheorem LPRle_antisym {x y : LPReal}\n  : x <= y -> y <= x -> x = y.\nProof.\nintros. apply LPReq_compat. split; assumption.\nQed.\n\nTheorem LPRplus_le_compat {x y z t : LPReal}\n  : (x <= y) -> (z <= t) -> (x + z <= y + t).\nProof. intros. unfold LPRle in *. intros.\nsimpl in *. destruct H1;\n  [apply LPRplusL | apply LPRplusR | eapply LPRplusB ]; try intuition.\napply H. eassumption. apply H0. eassumption. assumption.\nQed.\n\nRequire Import Morphisms.\nInstance LPRplus_le_compatI : Proper (LPRle ==> LPRle ==> LPRle) LPRplus.\nProof.\nunfold Proper, respectful. intros. \napply LPRplus_le_compat; assumption.\nQed.\n\nTheorem LPRmult_le_compat {x x' y y' : LPReal}\n  : x <= x' -> y <= y' -> x * y <= x' * y'.\nProof.\nintros. unfold LPRle in *. intros.\nsimpl in *. destruct H1 as [a b H1 H2 H3].\neconstructor. apply H. eassumption.\napply H0. eassumption. assumption.\nQed.\n\nInstance LPRmult_le_compatI : Proper (LPRle ==> LPRle ==> LPRle) LPRmult.\nProof.\nunfold Proper, respectful. intros.\napply LPRmult_le_compat; assumption.\nQed.\n\nTheorem LPRzero_min (r : LPReal) : 0 <= r.\nProof.\nunfold LPRle. intros q Hq. simpl in *.\napply False_rect. eapply Qnnlt_zero_prop.\neassumption.\nQed.\n\nLemma LPRlt_not_le {x y : LPReal}\n  : x < y -> ~ (y <= x).\nProof. intros. unfold LPRlt, LPRle, not in *.\nintros. destruct H as [q [notxq yq]].\napply notxq. apply H0. assumption.\nQed.\n\n\nLemma LPRQnn_le {x y : Qnn} : LPRQnn x <= LPRQnn y <-> (x <= y)%Qnn.\nProof.\nsplit; intros.\n- unfold LPRle in H. simpl in *. destruct (Qnn_dec x y).\n  destruct s. apply Qnnlt_le_weak. assumption.\n  pose proof (H _ q). apply Qnnlt_not_le in H0.\n  apply False_rect. apply H0. reflexivity.\n  induction e. reflexivity.\n- unfold LPRle. simpl in *. intros.\n  eapply Qnnlt_le_trans. eassumption. assumption.\nQed.\n\nRequire Import Qcanon.\nLocal Close Scope Qc.\n\n\nLemma LPRQnn_plus {x y : Qnn} \n  : LPRQnn x + LPRQnn y = LPRQnn (x + y)%Qnn.\nProof.\napply LPReq_compat. unfold LPReq.\nsplit; unfold LPRle; intros; simpl in *.\n- destruct H; simpl in *.\n  + replace q with (0 + q)%Qnn by ring. \n    replace (x + y)%Qnn with (y + x)%Qnn by ring.\n    apply Qnnplus_le_lt_compat. apply nonneg. assumption. \n  + replace q with (0 + q)%Qnn by ring. \n    apply Qnnplus_le_lt_compat. apply nonneg. assumption.\n  + eapply Qnnle_lt_trans. eassumption.\n    eapply Qnnplus_le_lt_compat. apply Qnnlt_le_weak. \n    assumption. assumption.\n- destruct (Qnn_dec x 0%Qnn) as [[H0 | H0] | H0].\n  + apply Qnnlt_zero_prop in H0. contradiction.\n  + destruct (Qnn_dec y 0%Qnn) as [[H1 | H1] | H1].\n    * apply Qnnlt_zero_prop in H1. contradiction.\n    * pose proof (Qnnplus_open H H0 H1).\n      destruct H2 as [x' [y' [x'x [y'y sum]]]].\n      eapply LPRplusB. apply x'x. apply y'y. eassumption.\n    * apply LPRplusL. simpl.\n      eapply Qnnlt_le_trans. eassumption.\n      subst. replace (x + 0)%Qnn with x by ring.\n      apply Qnnle_refl.\n  + apply LPRplusR. simpl. eapply Qnnlt_le_trans.\n    eassumption. subst. replace (0 + y)%Qnn with y by ring.\n    apply Qnnle_refl.\nQed.\n\nDefinition LPRsup {A : Type} (f : A -> LPReal)\n  : LPReal.\nProof.\nrefine (\n  {| lbound := fun q => exists (idx : A), f idx q |}\n).\n- intros. destruct H. exists x. apply dclosed with q. assumption. assumption.\n- intros. destruct H. pose proof (uopen _ _ H).\n  destruct H0 as [q' [qq' fq']]. \n  exists q'. split. assumption. exists x. assumption.\nDefined.\n\nDefinition LPRinfinity : LPReal.\nProof. refine (\n  {| lbound := fun q => True |}\n); trivial.\nintros. exists (q + 1)%Qnn. intuition.\nreplace q with (q + 0)%Qnn at 1 by ring.\napply Qnnplus_le_lt_compat.\napply Qnnle_refl. apply Qnnlt_alt. reflexivity. \nDefined.\n\nTheorem LPRinfinity_max (r : LPReal) : r <= LPRinfinity.\nProof.\nunfold LPRle. intros. simpl. constructor.\nQed.\n\nLemma LPRsup_ge {A : Type} {f : A -> LPReal} {a : A} \n  : f a <= LPRsup f.\nProof. unfold LPRle. simpl. intros. eexists. eassumption.\nQed.\n\nLemma LPRsup_le {A : Type} {f : A -> LPReal} {x : LPReal} \n  : (forall (a : A), (f a <= x)) -> LPRsup f <= x.\nProof. intros. unfold LPRle in *. simpl. intros. destruct H0.\nsubst. apply H with x0.\nassumption.\nQed.\n\nLemma LPRsup_ge2 {A : Type} {f : A -> LPReal} {x : LPReal} \n  : (exists a, x <= f a) -> x <= LPRsup f.\nProof. intros. destruct H. rewrite H. apply LPRsup_ge.\nQed.\n\nLemma LPRsup_prop {A : Type} {f : A -> LPReal} {x : LPReal}\n  : (forall (a : A), (f a <= x))\n  -> (exists (a : A), x <= f a)\n  -> LPRsup f = x.\nProof. intros. apply LPReq_compat. split. apply LPRsup_le.\nassumption. eapply LPRsup_ge2. eassumption.\nQed.\n\nLemma LPRsup_monotonic_gen {A B : Type} (f : A -> LPReal) (g : B -> LPReal)\n  : (forall (a : A), exists (b : B), f a <= g b) -> LPRsup f <= LPRsup g.\nProof.\nintros mono. unfold LPRle in *.\nintros. simpl in *. destruct H. \ndestruct (mono x).\nexists x0. apply H0.  assumption.\nQed.\n\nLemma LPRsup_monotonic {A : Type} (f g : A -> LPReal)\n  : (forall (a : A), f a <= g a) -> LPRsup f <= LPRsup g.\nProof. \nintros. apply LPRsup_monotonic_gen. intros. exists a. auto.\nQed.\n\nLemma LPRsup_eq_pointwise {A : Type} (f g : A -> LPReal)\n  : (forall (a : A), f a = g a) -> LPRsup f = LPRsup g.\nProof.\nintros mono.\napply LPReq_compat. split; apply LPRsup_monotonic;\nintros; rewrite mono; apply LPRle_refl.\nQed.\n\nLemma LPRsup_sum {A : Type} (f g : A -> LPReal)\n  : LPRsup (fun x => f x + g x) <= LPRsup f + LPRsup g.\nProof. apply LPRsup_le. intros a.\napply LPRplus_le_compat; apply LPRsup_ge.\nQed.\n\nLemma LPRsup_iterated {A B : Type} : forall (f : A -> B -> LPReal),\n   LPRsup (fun a => LPRsup (fun b => f a b))\n = LPRsup (fun b => LPRsup (fun a => f a b)).\nProof.\nintros. apply LPRle_antisym; unfold LPRle; simpl; intros.\n- destruct H as [a [b fab]]. exists b. exists a. assumption.\n- destruct H as [b [a fab]]. exists a. exists b. assumption.\nQed.\n\nLemma LPRsup_sum_lattice {A : Type} (f g : A -> LPReal)\n  (le : A -> A -> Prop)\n  (max : A -> A -> A)\n  (maxL  : forall (a b : A), le a (max a b))\n  (maxR  : forall (a b : A), le b (max a b))\n  (monof : forall n m, le n m -> f n <= f m)\n  (monog : forall n m, le n m -> g n <= g m)\n  : LPRsup (fun x => f x + g x) = LPRsup f + LPRsup g.\nProof.\napply LPReq_compat. split; [apply LPRsup_sum | ].\nunfold LPRle. intros. simpl in *.\ndestruct H; simpl in *.\n- destruct H. exists x. apply LPRplusL. assumption.\n- destruct H. exists x. apply LPRplusR. assumption.\n- destruct H. destruct H0. exists (max x x0). eapply LPRplusB.\n  eapply monof. apply maxL. eassumption.\n  eapply monog. apply maxR. eassumption. assumption.\nQed.\n\nLemma LPRsup_nat_ord (f g : nat -> LPReal)\n  : (forall n m, (n <= m)%nat -> f n <= f m)\n  -> (forall n m, (n <= m)%nat -> g n <= g m)\n  -> LPRsup (fun x => f x + g x) = LPRsup f + LPRsup g.\nProof. intros. eapply LPRsup_sum_lattice; try eassumption.\napply Max.le_max_l.  apply Max.le_max_r.\nQed.\n\nDefinition LPRmax (x y : LPReal) : LPReal.\nProof. refine (\n  {| lbound := fun q => x q \\/ y q |}\n).\n- intros. destruct H; [left | right]; eapply dclosed; eassumption.\n- intros. destruct H; \n  pose proof (uopen _ _ H) as H'; \n  destruct H' as [q' [qq' pq']]; exists q'; intuition.\nDefined.\n\nLemma LPRmax_le_and {x y z : LPReal} \n  : x <= z -> y <= z -> LPRmax x y <= z.\nProof. intros.\nunfold LPRle; simpl in *; intros; intuition.\nQed.\n\nLemma LPRmax_le_or {x y z : LPReal} \n  : z <= x \\/ z <= y -> z <= LPRmax x y.\nProof. intros.\nunfold LPRle; simpl in *; intros; intuition.\nQed.\n\nLemma LPRmax_le {x y x' y' : LPReal} \n  : x <= x' -> y <= y' -> LPRmax x y <= LPRmax x' y'.\nProof.\nintros. unfold LPRle. intros q Hmax. simpl in *.\ndestruct Hmax; [left | right].\n- apply H. assumption.\n- apply H0. assumption.\nQed.\n\nLemma LPRmax_plus {x x' y y' : LPReal}\n  : LPRmax (x + x') (y + y') <= LPRmax x y + LPRmax x' y'.\nProof.\napply LPRmax_le_and; apply LPRplus_le_compat; apply LPRmax_le_or;\n  (left; apply LPRle_refl) || (right; apply LPRle_refl).\nQed.\n\nDefinition LPRmin (x y : LPReal) : LPReal.\nProof. refine (\n  {| lbound := fun q => x q /\\ y q |}\n).\n- intros. destruct H; split; eapply dclosed; eassumption.\n- intros. destruct H. \n  destruct (uopen _ _ H) as [q'x [qq'x pq'x]].\n  destruct (uopen _ _ H0) as [q'y [qq'y pq'y]].\n  exists (Qnnmin q'x q'y). split. eapply Qnnmin_lt_both; assumption.\n  split; eapply dclosed; try eassumption. apply Qnnmin_l.\n  apply Qnnmin_r.\nDefined.\n\n(* An real number which is an indicator for a logical proposition.\n   It is 0 if P is false and 1 if P is true. Without a proof or\n   refutation of P, you will not know which! *)\nDefinition LPRindicator (P : Prop) : LPReal.\nProof. refine \n( {| lbound := fun q => P /\\ (q < 1)%Qnn |}).\n- intros. intuition. eapply Qnnle_lt_trans; eassumption. \n- intros. destruct H. pose proof (Qnnbetween q 1%Qnn H0).\n  destruct H1. exists x. intuition.\nDefined.\n\nLemma LPRind_bounded (P : Prop) : LPRindicator P <= 1.\nProof.\nunfold LPRle; intros; simpl in *; intuition.\nQed.\n\nLemma LPRind_imp (P Q : Prop) (f : P -> Q)\n  : LPRindicator P <= LPRindicator Q.\nProof.\nunfold LPRle; intros; simpl in *. intuition.\nQed.\n\nLemma LPRind_iff (P Q : Prop) (equiv : P <-> Q)\n  : LPRindicator P = LPRindicator Q.\nProof.\napply LPReq_compat; split;\nunfold LPRle; intros; simpl in *; intuition.\nQed.\n\nLemma LPRind_true (P : Prop) : P -> LPRindicator P = 1.\nProof. intros. apply LPReq_compat.\nsplit.\n- apply LPRind_bounded.\n- unfold LPRle; intros; simpl in *. intuition.\nQed.\n\nLemma LPRind_false (P : Prop) : ~ P -> LPRindicator P = 0.\nProof. intros. apply LPReq_compat. \nsplit.\n- unfold LPRle; intros; simpl in *. intuition.\n- apply LPRzero_min.\nQed.\n\nHint Resolve Qnnle_refl.\n\nLemma LPRind_scale_le {P : Prop} {x y : LPReal}\n  : (P -> x <= y) -> LPRindicator P * x <= y.\nProof.\nintros. unfold LPRle; simpl in *; intros.\ndestruct H0 as [a b pa pb ab].\ndestruct pa. apply H in H0. apply H0. eapply dclosed. \neassumption. eapply Qnnle_trans. eassumption.\nreplace b with (1 * b)%Qnn at 2 by ring.\napply Qnnmult_le_compat. apply Qnnlt_le_weak. assumption.\napply Qnnle_refl.\nQed.\n\nLemma LPRind_mult {U V : Prop}\n  : LPRindicator (U /\\ V) = LPRindicator U * LPRindicator V.\nProof.\napply LPReq_compat. \nsplit; unfold LPRle; simpl in *; intros.\n- intuition. \n  assert (1 <= 1 * 1).\n  ring_simplify. apply LPRle_refl.\n  unfold LPRle in H0. \n  specialize (H0 q H1). simpl in H0.\n  destruct H0 as [a b pa pb pab].\n  constructor 1 with a b; simpl; intuition.\n- destruct H as [a b pa pb ab]. simpl in *. intuition.\n  eapply Qnnle_lt_trans. eassumption.\n  apply Qnnle_lt_trans with (a * 1)%Qnn.\n  apply Qnnmult_le_compat. apply Qnnle_refl.\n  apply Qnnlt_le_weak. assumption. \n  replace 1%Qnn with (1 * 1)%Qnn at 2 by ring. \n  apply Qnnmult_lt_compat_r. apply Qnnlt_alt. reflexivity.\n  assumption.\nQed.\n\nLemma LPRind_max {U V : Prop}\n  : LPRindicator (U \\/ V) = LPRmax (LPRindicator U) (LPRindicator V).\nProof.\napply LPReq_compat.\nsplit; unfold LPRle; simpl in *; intros; intuition.\nQed.\n\nLemma LPRind_exists : forall (A : Type) (f : A -> Prop),\n  LPRindicator (exists a, f a) = LPRsup (fun a => LPRindicator (f a)).\nProof.\nintros. apply LPRle_antisym; unfold LPRle; simpl; intros.\n- destruct H as [[a fa] q1]. exists a. intuition.\n- destruct H as [a [fa q1]]. split. exists a. assumption. assumption.\nQed.\n\nLemma LPRind_min {U V : Prop}\n  : LPRindicator (U /\\ V) = LPRmin (LPRindicator U) (LPRindicator V).\nProof.\napply LPReq_compat.\nsplit; unfold LPRle; simpl in *; intros; intuition.\nQed.\n\nLemma LPRind_modular {U V : Prop} :\n   LPRindicator U + LPRindicator V =\n   LPRindicator (U /\\ V) + LPRindicator (U \\/ V).\nProof.\napply LPReq_compat; split; unfold LPRle; intros q H.\n- destruct H.\n  + apply LPRplusR. rewrite LPRind_max. left. assumption.\n  + apply LPRplusR. rewrite LPRind_max. right. assumption.\n  +  simpl in *. intuition. eapply LPRplusB. rewrite LPRind_min.\n     simpl in *. intuition.  apply H3. apply H3. rewrite LPRind_max.\n     simpl. right. split. apply H. apply H4. assumption.\n- destruct H.\n  + eapply LPRplusB; simpl in *; intuition. eassumption. eassumption.\n    replace q with (q + 0)%Qnn at 1 by ring.\n    apply Qnnplus_le_compat. apply Qnnle_refl. apply nonneg.\n  + simpl in *. destruct H. destruct H. \n    * apply LPRplusL. simpl. intuition.\n    * apply LPRplusR. simpl. intuition.\n  + simpl in *. eapply LPRplusB; simpl in *; intuition.\n    eapply H3. assumption. eapply H4. assumption. assumption.\n    assumption.\nQed.\n\nLemma LPRplus_eq_compat : forall x y x' y',\n  x = x' -> y = y' -> x + y = x' + y'.\nProof. intros. subst. reflexivity. Qed.\n\nLemma LPRmult_eq_compat : forall x y x' y',\n  x = x' -> y = y' -> x * y = x' * y'.\nProof. intros. subst. reflexivity. Qed.\n\nLemma LPRQnn_eq {x y : Qnn} : x = y -> LPRQnn x = LPRQnn y.\nProof. intros; subst; reflexivity. Qed.\n\nLemma LPRmax_scales {c x y : LPReal} \n  : LPRmax (c * x) (c * y) = c * LPRmax x y.\nProof. \napply LPReq_compat. split.\n- apply LPRmax_le_and; (apply LPRmult_le_compat;\n  [ apply LPRle_refl \n  | apply LPRmax_le_or; auto using LPRle_refl]).\n- unfold LPRle; simpl; intros. \n  destruct H as [a b ca xyb qab].\n  destruct xyb; [left | right];\n  constructor 1 with a b; auto.\nQed.\n\nLemma LPRsup_scales {A : Type} {f : A -> LPReal}\n  {c : LPReal}\n  : c * LPRsup f = LPRsup (fun x => c * f x).\nProof.\napply LPReq_compat; split.\n- unfold LPRle; simpl; intros.\n  destruct H as [a b ca sup qab].\n  destruct sup. exists x. constructor 1 with a b; intuition.\n- apply LPRsup_le. intros. apply LPRmult_le_compat.\n  apply LPRle_refl. apply LPRsup_ge.\nQed.\n\nLemma LPRsup_constant {A : Type} (x : LPReal) :\n  A -> LPRsup (fun _ : A => x) = x.\nProof.\nintros. apply LPReq_compat; split; unfold LPRsup, LPRle; simpl; intros.\ndestruct H. assumption. exists X. assumption. \nQed.\n\nLemma Qnnpowsup {p : Qnn} (plt1 : (p < 1)%Qnn)\n  : LPRsup (fun n => LPRQnn (1 - (p ^ n)))%Qnn = 1.\nProof.\napply LPReq_compat. split.\n- replace 1 with (LPRsup (fun _ : nat => 1)).\n  apply LPRsup_monotonic. intros n.\n  induction n; simpl.\n   + unfold LPRle. simpl. intros. \n     apply Qnnminus_lt_r in H; [|apply Qnnle_refl].\n     eapply Qnnle_lt_trans; [| eassumption].\n     replace q with (0 + q)%Qnn at 1 by ring. apply Qnnplus_le_compat.\n     apply nonneg. apply Qnnle_refl. \n   + unfold LPRle. simpl. intros. \n     apply LPRQnn_le in IHn. apply Qnnminus_lt_r in H.\n     eapply Qnnle_lt_trans. Focus 2. apply H.\n     replace q with (0 + q)%Qnn at 1 by ring.\n     apply Qnnplus_le_compat. apply nonneg. apply Qnnle_refl.\n     pose proof (Qnnpow_le (Qnnlt_le_weak plt1) (n := S n)) as pn1.\n     apply pn1.\n   + apply LPRsup_constant. exact 0%nat.\n- unfold LPRle; simpl; intros.\n  pose proof (Qnnlt_le_weak H) as Hle.\n  pose proof (smallPowers plt1 (1 - q)%Qnn).\n  destruct (Qnn_dec q 0%Qnn).\n  destruct s. apply Qnnlt_zero_prop in q0. contradiction.\n  assert (1 - q > 0)%Qnn.\n  apply Qnnminus_lt_r. assumption. \n  replace (q + 0)%Qnn with q by ring. assumption. \n  apply H0 in H1. destruct H1. exists x. apply Qnnminus_lt_r.\n  apply Qnnpow_le. apply Qnnlt_le_weak. assumption.\n  apply Qnnminus_lt_r in H1. rewrite (SRadd_comm Qnnsrt).\n  assumption. assumption. subst. exists 1%nat. simpl. apply Qnnminus_lt_r.\n  replace (p * 1)%Qnn with p by ring. apply Qnnlt_le_weak.\n  assumption.\n  replace (p * 1 + 0)%Qnn with p by ring. assumption.\nQed.\n\nLemma LPRQnn_mult {x y : Qnn} : LPRQnn x * LPRQnn y = LPRQnn (x * y)%Qnn.\nProof. \napply LPRle_antisym; unfold LPRle; simpl; intros.\n- destruct H as [a b pa pb pab]. simpl in *.\n  eapply Qnnle_lt_trans. eassumption.\n  eapply Qnnle_lt_trans. Focus 2.\n  eapply Qnnmult_lt_compat_r. eapply Qnnle_lt_trans. 3:eassumption.\n  apply nonneg. eassumption.\n  rewrite pb. reflexivity.\n- destruct (Qnnmult_open H) as [a [b pab]]. \n  constructor 1 with a b; intuition.\nQed.", "meta": {"author": "bmsherman", "repo": "numbers", "sha": "412568157cfc9c3be0c6212a7c6692a8bfc802c1", "save_path": "github-repos/coq/bmsherman-numbers", "path": "github-repos/coq/bmsherman-numbers/numbers-412568157cfc9c3be0c6212a7c6692a8bfc802c1/LPReal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7234461961316893}}
{"text": "Require Import ZArith.\n\nOpen Scope Z_scope.\n\nFixpoint div_bin (n m:positive) : Z*Z :=\n  match n with\n    | 1%positive    =>  match m with\n                          | 1%positive    => (1,0)\n                          | v             => (0,1)\n                        end\n    | xO n'         =>  let (q',r') := div_bin n' m in\n                        match Z_lt_ge_dec (2*r')(Zpos m) with\n                          | left _    => (2*q', 2*r')\n                          | right _   => (2*q'+1, 2*r' - (Zpos m))\n                        end\n    | xI n'         =>  let (q',r') := div_bin n' m in \n                        match Z_lt_ge_dec (2*r'+1)(Zpos m) with\n                          | left _    => (2*q', 2*r' + 1)\n                          | right _   => (2*q' + 1, (2*r'+1)-(Zpos m))\n                        end\n  end.\n\n\nLemma rem_1_1_interval : 0 <= 0 < 1.\nProof.\n  auto with zarith. (* omega also works *)\nQed.\n\n\nLemma rem_1_even_interval : forall m: positive, \n  0 <= 1 < Zpos (xO m).\nProof.\n  intros m. split. \n  auto with zarith.\n(*\nNothing comes up\nSearchPattern (1 < Zpos _).\n*)\n(*\nLocate \"_ < _\".\n  Notation            Scope     \n  \"x < y\" := Pos.lt x y          : positive_scope\n                        \n  \"x < y\" := lt x y    : nat_scope\n                        \n  \"x < y\" := Z.lt x y  : Z_scope (default interpretation)\n  \"x < y\" := N.lt x y  : N_scope\n*)\n(*\nPrint Z.lt.\nZ.lt = fun x y : Z => (x ?= y) = Lt\n     : Z -> Z -> Prop\n*)\ncompute. (* trick !!!! simpl fails but compute works !!! *)\nreflexivity.\nQed.\n\nLemma rem_1_odd_interval : forall m:positive,\n  0 <= 1 < Zpos(xI m).\nProof.\n  intros m. split.\n  auto with zarith.\n  compute. reflexivity.\nQed.\n\nLemma rem_even_ge_interval : forall m r:Z,\n  0 <= r < m -> m <= 2*r -> 0 <= 2*r - m < m.\nProof.\n  intros. omega.\nQed.\n\nLemma rem_even_lt_interval: forall m r:Z,\n  0 <= r < m -> 2*r < m -> 0 <= 2*r < m.\nProof.\n  intros. omega.\nQed.\n\n\nLemma rem_odd_ge_interval: forall m r:Z,\n  0 <= r < m -> m <= 2*r + 1 -> 0 <= 2*r + 1 - m < m.\nProof.\n  intros. omega.\nQed.\n\nLemma rem_odd_lt_interval: forall m r:Z,\n  0 <= r < m -> 2*r + 1 < m -> 0 <= 2*r + 1 < m.\nProof.\n  intros. omega.\nQed.\n\nLtac div_bin_tac arg1 arg2 :=\n  elim arg1;\n    [intros p; lazy beta iota delta [div_bin]; fold div_bin;\n      case (div_bin p arg2); unfold snd; intros q' r' Hrec;\n      case (Z_lt_ge_dec (2*r' + 1)(Zpos arg2)); intros H\n    | intros p; lazy beta iota delta [div_bin]; fold div_bin;\n      case (div_bin p arg2); unfold snd; intros q' r' Hrec;\n      case (Z_lt_ge_dec (2*r')(Zpos arg2)); intros H\n    | case arg2; lazy beta iota delta [div_bin]; intros].\n\nHint Resolve rem_odd_ge_interval rem_even_ge_interval\nrem_odd_lt_interval rem_even_lt_interval rem_1_odd_interval\nrem_1_even_interval rem_1_1_interval.\n\nTheorem div_bin_rem_lt:\n  forall n m:positive, 0 <= snd (div_bin n m) < Zpos m.\nProof.\n  intros n m. div_bin_tac n m; unfold snd; auto; omega.\nQed.\n\n(* fails...\nSearchRewrite (Zpos (xI _)).\n*)\n\n(*\nCheck Zpos_xI.\n  Pos2Z.inj_xI\n       : forall p : positive, Z.pos p~1 = 2 * Z.pos p + 1\n*)\n\n(*\nCheck Zpos_xO.\n  Pos2Z.inj_xO\n       : forall p : positive, Z.pos p~0 = 2 * Z.pos p\n*)\n\nTheorem div_bin_eq:\n  forall n m:positive, Zpos n = (fst (div_bin n m))*(Zpos m) + snd (div_bin n m).\nProof.\n  intros n m. div_bin_tac n m;\n  rewrite Zpos_xI || (try rewrite Zpos_xO);\n  try rewrite Hrec; unfold fst, snd; ring.\nQed.\n\nInductive div_data (n m:positive) : Set :=\n  | div_data_def : forall q r:Z, \n    Zpos n = q*(Zpos m)+r -> 0 <= r < Zpos m -> div_data n m.\n\n\nDefinition div_bin2 : forall n m:positive, div_data n m.\n  intros n m. elim n.\n  intros n' [q r H_eq H_int].\n  case (Z_lt_ge_dec (2*r + 1)(Zpos m)).\n  exists (2*q)(2*r + 1).\n  rewrite Zpos_xI; rewrite H_eq; ring.\n  auto.\n  exists (2*q+1)(2*r + 1 - (Zpos m)).\n  rewrite Zpos_xI; rewrite H_eq; ring.\n  omega.\nAbort.\n\nDefinition div_bin3 : forall n m:positive, div_data n m.\n  refine\n    ((fix div_bin3 (n:positive) : forall m:positive, div_data n m :=\n      fun m =>\n        match n return div_data n m with\n          | 1%positive  =>\n            match m return div_data 1 m with\n              | 1%positive => div_data_def 1 1 1 0 _ _\n              | xO p => div_data_def 1 (xO p) 0 1 _ _\n              | xI p => div_data_def 1 (xI p) 0 1 _ _\n            end\n          | xO p  =>\n            match div_bin3 p m with\n              | div_data_def q r H_eq H_int =>\n                  match Z_lt_ge_dec (Zmult 2 r)(Zpos m) with\n                    | left hlt =>\n                        div_data_def (xO p) m (Zmult 2 q)\n                                     (Zmult 2 r) _ _\n                    | right hge =>\n                        div_data_def (xO p) m (Zplus (Zmult 2 q) 1)\n                                     (Zminus (Zmult 2 r)(Zpos m)) _ _\n                  end\n            end\n          | xI p =>\n            match div_bin3 p m with\n              | div_data_def q r H_eq H_int =>\n                  match Z_lt_ge_dec (Zplus (Zmult 2 r) 1)(Zpos m) with\n                    | left hlt =>\n                        div_data_def (xI p) m (Zmult 2 q)\n                                     (Zplus (Zmult 2 r) 1) _ _\n                    | right hge =>\n                        div_data_def (xI p) m (Zplus (Zmult 2 q) 1)\n                        (Zminus (Zplus (Zmult 2 r) 1)(Zpos m)) _ _\n                  end\n              end\n            end));\n  clear div_bin3; try rewrite Zpos_xI; try rewrite Zpos_xO;\n  try rewrite H_eq; auto with zarith; try (ring; fail).\n  split;[auto with zarith | compute; auto].\n  split;[auto with zarith | compute; auto].\nDefined.\n\n\n\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/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7232911340487076}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) : natural :=\n  mult (Succ y) (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj232_coqofml_us00i2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.723291121187931}}
{"text": "Require Import Arith.\nRequire Import ZArith.\nRequire Import List.\n\nParameters (prime_divisor : nat -> nat)\n           (prime : nat -> Prop)\n           (divides : nat -> nat -> Prop).\n\nOpen Scope nat_scope.\n\nCheck (prime (prime_divisor 220)).\n\nCheck (divides (prime_divisor 220) 220).\n\nCheck (divides 3).\n\nParameter binary_word : nat -> Set.\n\nDefinition short : Set := binary_word 32.\n\nDefinition long : Set := binary_word 64.\n\nCheck ((nat -> nat) -> Prop).\nCheck ((nat -> nat) -> (nat -> nat) -> Prop).\nCheck (nat -> nat -> Set).\n\nCheck (not (divides 3 81)).\nCheck (let d := prime_divisor 220 in prime d /\\ divides d 220).\n\n\nParameters (decomp : nat -> list nat) (decomp2 : nat -> nat * nat).\n\nCheck (decomp 220).\nCheck (decomp2 284).\n\nCheck @cons.\nCheck @pair.\nCheck (forall A B : Set, A -> B -> A*B).\nCheck @fst.\n\nCheck @le_n.\nCheck @le_S.\nCheck (le_n 36).\n\nDefinition le_36_37 := le_S 36 36 (le_n 36).\nCheck le_36_37.\n\nDefinition le_36_38 := le_S 36 37 le_36_37.\nCheck le_36_38.\n\nCheck (le_S _ _ (le_S _ _ (le_n 36))).\n\nDefinition twice : forall A : Set, (A -> A) -> A -> A :=\n  fun A f a => f (f a).\n\nCheck (twice Z).\nCheck (twice Z (fun z => (z*z)%Z)).\nCheck (twice _ S 56).\nCheck (twice (nat -> nat) (fun f x => f (f x)) (mult 3)).\n\nEval compute in (twice (nat -> nat) (fun f x => f (f x)) (mult 3) 1).\n\nTheorem le_i_SSi : forall i : nat, i <= S (S i).\nProof (fun i : nat => le_S _ _ (le_S _ _ (le_n i))).\n\nDefinition compose :\n  forall A B C : Set, (A -> B) -> (B -> C) -> A -> C :=\n    fun A B C f g x => g (f x).\n\nPrint compose.\n\nCheck (fun (A : Set) (f : Z -> A) => compose _ _ _ Z_of_nat f).\n\nImplicit Arguments compose [A B C].\nImplicit Arguments le_S [n m].\n\nCheck (le_S (le_i_SSi 1515)).\n\nCheck (compose (C := Z) S).\n\nCheck (le_S (n := 45)).\n\nReset compose.\nSet Implicit Arguments.\n\nDefinition compose (A B C : Set) (f : A -> B) (g : B -> C) (a : A) :=\n  g (f a).\n\nDefinition thrice (A : Set) (f : A -> A) := compose f (compose f f).\n\nUnset Implicit Arguments.\n\nPrint compose.\nPrint thrice.\n\nEval cbv beta delta in (thrice (thrice (A := nat)) S O).\n\n(* Exercise: 4.3 *)\nSection A_declared.\n  Variables (A : Set) (P Q : A -> Prop) (R : A -> A -> Prop).\n\n  Theorem all_perm : (forall a b : A, R a b) -> forall a b : A, R b a.\n  Proof (fun (H : forall a b : A, R a b) (a b : A) => H b a).\n\n  Theorem all_imp_dist :\n    (forall a : A, P a -> Q a) -> (forall a : A, P a) ->\n      (forall a : A, Q a).\n  Proof\n    (fun (H : forall a : A, P a -> Q a) (H' : forall a : A, P a) (a : A) =>\n      H a (H' a)).\n\n  Theorem all_delta : (forall a b : A, R a b) -> forall a : A, R a a.\n  Proof (fun (H : forall a b : A, R a b) (a : A) => H a a).\n\nEnd A_declared.\n\nCheck (forall n : nat, 0 < n -> nat).\n\nTheorem id : forall A : Set, A -> A.\nProof (fun (A : Set) (a : A) => a).\n\nTheorem diag : forall A B : Set, (A -> A -> B) -> A -> B.\nProof (fun (A B : Set) (f : A -> A -> B) (a : A) => f a a).\n\nTheorem permute : forall A B C : Set, (A -> B -> C) -> B -> A -> C.\nProof (fun (A B C : Set) (f : A -> B -> C) (b : B) (a : A) => f a b).\n\nTheorem f_nat_Z : forall A : Set, (nat -> A) -> Z -> A.\nProof (fun (A : Set) (f : nat -> A) (z : Z) => f (Z.to_nat z)).\n", "meta": {"author": "vishallama", "repo": "interactive_theorem_proving_and_program_development", "sha": "147498230e5f2d1791f41c37b8b6c37c8ec4aa37", "save_path": "github-repos/coq/vishallama-interactive_theorem_proving_and_program_development", "path": "github-repos/coq/vishallama-interactive_theorem_proving_and_program_development/interactive_theorem_proving_and_program_development-147498230e5f2d1791f41c37b8b6c37c8ec4aa37/src/chap04-dependent-products/Exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874624, "lm_q2_score": 0.8031737987125613, "lm_q1q2_score": 0.7232819313142467}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus x (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj208_coqofml_EfTF6y.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7232604510163612}}
{"text": "From Coq Require Import Init.Nat Lia.\nFrom QuickChick Require Import QuickChick.\nFrom mathcomp Require Import ssreflect ssreflect.eqtype.\nImport QcNotation. Import QcDefaultNotation.\n\nRequire Import ExtLib.Structures.Monads.\nOpen Scope monad_scope.\nOpen Scope qc_scope.\nOpen Scope nat_scope.\n\n\nFrom Ltac2 Require Import Ltac2.\n\n\n(* Some small examples for checker proof derivation *)\n\nInductive wf_list : list nat -> Prop :=\n| lnil : wf_list nil\n| lcons :\n    forall l,\n      wf_list l -> wf_list l.\n\nDerive DecOpt for (wf_list l).\n\nInductive wf_list2 : list nat -> Prop :=\n| lcons2 :\n    forall l,\n      wf_list2 l -> wf_list2 l.\n\nDerive DecOpt for (wf_list2 l).\n\n(* For each DecOpt instance we should be able to derive the following *) \n\nInstance DecOptwf_listSizeMonotonic l : DecOptSizeMonotonic (wf_list l).\nProof. derive_mon (). Qed. \n\nInstance DecOptwf_list_sound l : DecOptSoundPos (wf_list l).\nProof. derive_sound (). Qed.\n\nInstance DecOptwf_list_complete l : DecOptCompletePos (wf_list l).\nProof. derive_complete (). Qed.\n\n\n(* Counter-example for completess *) \nGoal (forall l, ~ wf_list2 l).\nProof.\n  intros l Hwf. induction Hwf; eauto.\nQed. \n\nInductive list_len : nat -> list nat -> Prop :=\n| nil_len : list_len 0 nil\n| cons_len :\n    forall n x l,\n      list_len n l ->\n      wf_list l -> (* silly; just to test proofs *) \n      list_len (S n) (x :: l). \n\nDerive DecOpt for (list_len n l).\n\n\nInstance DecOptlist_lenSizeMonotonic n l : DecOptSizeMonotonic (list_len n l).\nProof. derive_mon (). Qed. \n\nInstance DecOptlist_len_sound n l : DecOptSoundPos (list_len n l).\nProof. derive_sound (). Qed.\n\nInstance DecOptlist_len_complete n l : DecOptCompletePos (list_len n l).\nProof. derive_complete (). Qed.\n\n\nInductive tree :=\n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\nDerive Show for tree.\nDerive Arbitrary for tree.\n\nDerive ArbitrarySizedSuchThat for (fun n => le n n').\nDerive ArbitrarySizedSuchThat for (fun n' => le n n').\n\nInductive bst : nat -> nat -> tree -> Prop :=\n| BstLeaf : forall n1 n2, bst n1 n2 Leaf\n| BstNode : forall min max n t1 t2,\n    le min max -> le min n -> le n max ->\n    bst min n t1 -> bst n max t2 ->\n    bst min max (Node n t1 t2).\n\nDerive DecOpt for (le n m).\nDerive DecOpt for (bst min max t).\n\n(* For each DecOpt instance we should be able to derive the following *) \nInstance decOptbstSizeMonotonic m n t : DecOptSizeMonotonic (bst m n t).\nProof. derive_mon (). Qed.\n                       \nInstance DecOptbst_sound m n t : DecOptSoundPos (bst m n t).\nProof. derive_sound (). Qed.\n\nInstance DecOptbst_complete m n t : DecOptCompletePos (bst m n t).\nProof. derive_complete (). Qed.\n\nDerive ArbitrarySizedSuchThat for (fun b => bst min max b).\n\n\nConjecture expand_range : forall t,\n    bst 0 30 t ->\n    bst 0 40 t.\nQuickChick expand_range.\nConjecture contract_range : forall t,\n    bst 0 30 t ->\n    bst 0 1 t.\nQuickChick expand_range.\n(* this shouldn't work *)\n\nFixpoint insert t x :=\n  match t with\n  | Leaf => Node x Leaf Leaf\n  | Node a l r =>\n    if a <= x ? then\n      Node x (insert l x) r\n    else\n      Node x r (insert r x)\n  end.\n\n\nInductive inrange : nat -> nat -> tree -> nat -> Prop :=\n| InRange : forall t n max x,\n    le n max ->\n    bst 0 max t ->\n    le x max ->\n    inrange n max t x.\nDerive DecOpt for (inrange n m t x).\nDerive ArbitrarySizedSuchThat for (fun n => inrange n m t x).\n\n\n(* Testing here doesn't work *)\n(* Conjecture insert_invariant : *)\n(*   forall t, *)\n(*     inrange 30 30 t 30 -> *)\n(*     bst 0 30 t. *)\n(* QuickChick insert_invariant. *)\n\n\n", "meta": {"author": "mpstepan", "repo": "QC-631-Final", "sha": "4cbf25da5bd57252767e13c43cb20acb324178ee", "save_path": "github-repos/coq/mpstepan-QC-631-Final", "path": "github-repos/coq/mpstepan-QC-631-Final/QC-631-Final-4cbf25da5bd57252767e13c43cb20acb324178ee/examples/decderive_bst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7232604470380493}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL B FREE SOFTWARE LICENSE AGREEMENT           *)\n(**************************************************************)\n\n(* Following a discussion on Coq-Zulip\n\n    https://coq.zulipchat.com/#narrow/stream/237977-Coq-users/topic/Problem.20with.20nested.20fixpoints/near/309498019\n\n   we implement the nested short lex(icographic) order on list based rose-trees\n   and show that it is a (strongly) total strict order on those trees, but\n   however it is NOT well-founded as we expose a strictly decreasing sequence *)\n\nFrom Coq\n  Require Import Arith List Lia Wellfounded Utf8.\n\nFrom KruskalTrees\n  Require Import notations tactics list_utils rtree.\n\nImport ListNotations rtree_notations.\n\nSet Implicit Arguments.\n\n#[local] Reserved Notation \"l '<lex' m \" (at level 70, no associativity, format \"l  <lex  m\").\n#[local] Reserved Notation \"l '<slex' m \" (at level 70, no associativity, format \"l  <slex  m\").\n#[local] Reserved Notation \"l '<rlex' m \" (at level 70, no associativity, format \"l  <rlex  m\").\n\nSection measure_rect.\n\n  Variable (X : Type) (m : X → nat) (P : X → Type).\n\n  Hypothesis F : ∀x, (∀y, m y < m x → P y) → P x.\n\n  Definition measure_rect x : P x.\n  Proof.\n    cut (Acc (fun x y => m x < m y) x); [ revert x | ].\n    + refine (\n        fix loop x Dx := @F x (fun y Dy => loop y _)\n      ).\n      apply (Acc_inv Dx), Dy.\n    + apply wf_inverse_image with (f := m), lt_wf.\n  Qed.\n\nEnd measure_rect.\n\nTactic Notation \"induction\" \"on\" hyp(x) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n  pattern x; revert x; apply measure_rect with (m := fun x => f); intros x IH.\n\nDefinition order_stotal {X} (R : X → X → Prop) :=\n     (∀ x y, { R x y } + { x = y } + { R y x }).\n\nSection order.\n\n  Context {X : Type}.\n\n  Implicit Type (l m : list X).\n\n  Definition list_shorter l m := ⌊l⌋ < ⌊m⌋.\n\n  Fact list_shorter_wf : well_founded list_shorter.\n  Proof. unfold list_shorter; apply wf_inverse_image, lt_wf. Qed.\n\n  Variable (R : X → X → Prop).\n\n  Inductive list_lex : list X -> list X -> Prop :=\n    | list_lex_init x y l m : R x y → ⌊l⌋ = ⌊m⌋ → x::l <lex y::m\n    | list_lex_cons x l m : l <lex m → x::l <lex x::m\n  where \"l <lex m\" := (list_lex l m).\n\n  Fact list_lex_length l m : l <lex m → ⌊l⌋ = ⌊m⌋.\n  Proof. induction 1; simpl; f_equal; auto. Qed.\n\n  Fact list_lex_inv l m :\n        l <lex m \n      → match m with \n        | []   => False\n        | y::m =>\n          match l with\n          | []   => False\n          | x::l => R x y ∧ ⌊l⌋ = ⌊m⌋ \n                  ∨ x = y ∧ l <lex m\n          end\n        end.\n  Proof. destruct 1; eauto. Qed.\n\n  Section list_lex_irrefl.\n\n    Let list_lex_irrefl_rec l m : l <lex m → l = m → ∃x, x ∈ l ∧ R x x.\n    Proof.\n      induction 1 as [ x y l m H1 H2 | x l m H IH ].\n      + inversion 1; subst; simpl; eauto.\n      + inversion 1; subst.\n        destruct IH as (? & ? & ?); simpl; eauto.\n    Qed.\n\n    Fact list_lex_irrefl l : l <lex l → ∃x, x ∈ l ∧ R x x.\n    Proof. intros H; apply list_lex_irrefl_rec with (1 := H); auto. Qed.\n\n  End list_lex_irrefl.\n\n  Lemma list_lex_trans l m k :\n          (∀ x y z, x ∈ l → y ∈ m → z ∈ k → R x y → R y z → R x z)\n        → l <lex m → m <lex k → l <lex k.\n  Proof.\n    intros H1 H2; revert H2 k H1.\n    induction 1 as [ x y l m H1 H2 | x l m H IH ]; intros k HR Hk.\n    + apply list_lex_inv in Hk.\n      destruct k as [ | z k ]; try easy.\n      destruct Hk as [ [H3 H4] | [[] H4]].\n      * constructor 1; eauto; try lia.\n        revert H1 H3; apply HR; simpl; auto.\n      * constructor 1; auto.\n        apply list_lex_length in H4; lia.\n    + apply list_lex_inv in Hk.\n      destruct k as [ | z k ]; try easy.\n      destruct Hk as [ [H3 H4] | [[] H4]].\n      * constructor 1; auto.\n        apply list_lex_length in H; lia.\n      * constructor 2.\n        apply IH; auto.\n        intros ? ? ? ? ? ?; apply HR; simpl; auto.\n  Qed.\n\n  Lemma list_lex_stotal l m : \n          ⌊l⌋ = ⌊m⌋\n        → (∀ x y, x ∈ l → y ∈ m → { R x y } + { x = y } + { R y x })\n        → { l <lex m } + { l = m } + { m <lex l }.\n  Proof.\n    revert m; induction l as [ | x l IHl ]; intros [ | y m ]; try discriminate; simpl; intros E H; auto.\n    apply f_equal with (f := pred) in E; simpl in E.\n    destruct (H x y) as [ [ Hxy | <- ] | Hxy ]; auto.\n    + do 2 left; constructor 1; auto.\n    + destruct (IHl _ E) as [ [ H1 | <- ] | H1 ].\n      * intros; apply H; auto.\n      * do 2 left; constructor 2; auto.\n      * left; right; auto.\n      * right; constructor 2; auto.\n    + right; constructor 1; auto.\n  Qed.\n\n  Hypothesis (Rwf : well_founded R). \n\n  Lemma list_lex_wf : well_founded list_lex.\n  Proof.\n    intros m; induction on m as IHm with measure (length m).\n    destruct m as [ | y m ].\n    + constructor; intros l Hl; apply list_lex_inv  in Hl; easy.\n    + induction y as [ y IHy' ] using (well_founded_induction Rwf) in m, IHm |- *.\n      assert (Acc list_lex m) as Hm by (apply IHm; simpl; auto).\n      assert (forall x l, R x y -> length l = length m -> Acc list_lex (x::l)) as IHy.\n      1: { intros x l Hx Hl; apply IHy'; auto.\n           intros; apply IHm.\n           simpl in *; rewrite <- Hl; auto. }\n      clear IHy' IHm.\n      induction Hm as [ m Hm IHm ] in IHy |- *.\n      constructor; intros l Hl. \n      apply list_lex_inv in Hl; destruct l as [ | x l ]; try tauto.\n      destruct Hl as [ (Hx & Hlm) | (-> & Hl) ].\n      * apply IHy; auto.\n      * apply IHm; auto.\n        apply list_lex_length in Hl as ->; auto.\n  Qed.\n\n  Definition list_short_lex l m := ⌊l⌋ < ⌊m⌋ ∨ l <lex m.\n\n  Infix \"<slex\" := list_short_lex.\n\n  Lemma list_short_lex_irrefl l : l <slex l → ∃x, x ∈ l ∧ R x x.\n  Proof.\n    intros [ H | H ]; try lia.\n    revert H; apply list_lex_irrefl.\n  Qed.\n\n  Lemma list_short_lex_trans l m k : \n        (∀ x y z, x ∈ l → y ∈ m → z ∈ k → R x y → R y z → R x z)\n      → l <slex m -> m <slex k -> l <slex k.\n  Proof.\n    intros H0 [H1|H1] [H2|H2].\n    + constructor 1; lia.\n    + apply list_lex_length in H2; constructor 1; lia.\n    + apply list_lex_length in H1; constructor 1; lia.\n    + constructor 2; eapply list_lex_trans; eauto.\n  Qed.\n\n  Lemma list_short_lex_stotal l m :\n       (∀ x y, x ∈ l → y ∈ m → { R x y } + { x = y } + { R y x })\n     → { list_short_lex l m } + { l = m } + { list_short_lex m l }.\n  Proof.\n    intros Hlm.\n    destruct (lt_eq_lt_dec (length l) (length m)) as [ [| E] |].\n    + do 2 left; constructor 1; auto.\n    + destruct list_lex_stotal with (1 := E) as [[|[]]|]; auto.\n      * do 2 left; constructor 2; auto.\n      * right; constructor 2; auto.\n    + right; constructor 1; auto.\n  Qed.\n\n  Lemma list_short_lex_wf : well_founded list_short_lex.\n  Proof.\n    intros m.\n    induction on m as IH with measure (length m).\n    induction m as [ m IHm ] using (well_founded_induction list_lex_wf).\n    constructor; intros l [ Hl | Hl ]; auto.\n    apply IHm; auto.\n    apply list_lex_length in Hl as ->; eauto.\n  Qed.\n\nEnd order.\n\n#[local] Hint Constructors list_lex : core.\n\n(** This is the nested list short lex order *)\n\nUnset Elimination Schemes.\n\nInductive rtree_slex : rtree → rtree → Prop :=\n  | rtree_slex_intro l m : l <slex m → ⟨l⟩ᵣ <rlex ⟨m⟩ᵣ\nwhere \"r <rlex s\" := (rtree_slex r s)\nand \"l <slex m\" := (list_short_lex rtree_slex l m).\n\nSet Elimination Schemes.\n\n#[local] Hint Constructors rtree_slex : core.\n\n(** A versatile non-dependent induction principle for rtree_slex \n    but we do ot use it below *)\n\nSection rtree_slex_ind.\n\n  Variables (P : rtree → rtree → Prop)\n            (HP : ∀ l m, l <slex m → list_short_lex P l m → P ⟨l⟩ᵣ ⟨m⟩ᵣ).\n\n  Fixpoint rtree_slex_ind l m (H : l <rlex m) { struct H } : P l m.\n  Proof.\n    destruct H as [ l m H ]; apply HP; destruct H as [ H | H ].\n    + constructor 1; trivial.\n    + right; induction H; eauto.\n    + constructor 1; trivial.\n    + constructor 2; induction H.\n      * constructor 1; trivial. \n        apply rtree_slex_ind, H.\n      * constructor 2; trivial.\n  Qed.\n\nEnd rtree_slex_ind.\n\n(* However we use the inversion lemma below *)\nFact rtree_slex_inv r t : \n        rtree_slex r t\n      → match r, t with\n          | ⟨l⟩ᵣ, ⟨m⟩ᵣ => l <slex m\n        end.\nProof. now destruct 1. Qed.\n\n(** rtree_slex is a strongly total strict order:\n     - it is irreflexive and transitive\n     - one can computationally decide r <rlex t or r = t or t <rlex r *)\n\nTheorem rtree_slex_irrefl t : ¬ t <rlex t.\nProof. red; induction t; intros (? & ? & ?)%rtree_slex_inv%list_short_lex_irrefl; eauto. Qed.\n\nTheorem rtree_slex_trans r s t : r <rlex s → s <rlex t → r <rlex t.\nProof.\n  revert s t; induction r as [ l IHl ]; intros [m] [p] H1%rtree_slex_inv H2%rtree_slex_inv.\n  constructor.\n  revert H1 H2; apply list_short_lex_trans; eauto.\nQed.\n\nTheorem rtree_slex_stotal : order_stotal rtree_slex.\nProof.\n  intros r.\n  induction r as [ l IH ]; intros [ m ].\n  destruct (list_short_lex_stotal rtree_slex l m) as [ [|[]] | ];auto.\nQed.\n\n(** However rtree_slex is NOT well-founded because [x,y] > [[x,y]] > [[[x,y]] ... *)\n\nFixpoint rtree_decr_seq n :=\n  match n with\n    | 0 => ⟨[⟨[]⟩ᵣ;⟨[]⟩ᵣ]⟩ᵣ\n    | S n => ⟨[rtree_decr_seq n]⟩ᵣ\n  end.\n\nFact rtree_decr_seq_spec n : rtree_decr_seq (S n) <rlex rtree_decr_seq n.\nProof.\n  induction n as [ | n IHn ]; simpl.\n  + simpl; constructor; constructor 1; simpl; auto.\n  + simpl; constructor; constructor 2; auto.\nQed.\n", "meta": {"author": "DmxLarchey", "repo": "Kruskal-Trees", "sha": "3118293d44b79655eea068a77ea5ea010211f8b4", "save_path": "github-repos/coq/DmxLarchey-Kruskal-Trees", "path": "github-repos/coq/DmxLarchey-Kruskal-Trees/Kruskal-Trees-3118293d44b79655eea068a77ea5ea010211f8b4/theories/examples/rtree_lex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.723256942655301}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (y : natural) (lf2 : natural) : natural :=\n  plus y (plus lf2 lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj183_coqofml_P3I7Yn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7905303087996142, "lm_q1q2_score": 0.7232569363059497}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Omega List.\n\nRequire Import notations acc_utils list_utils finite.\n\nSet Implicit Arguments.\n\nSection trees.\n\n  Variable (X : Type).\n\n  (* we do not want the too weak Coq generated induction principles *)\n\n  Unset Elimination Schemes.\n\n  Inductive tree : Type := in_tree : X -> list tree -> tree.\n\n  Set Elimination Schemes.\n\n  Definition tree_root t := match t with in_tree x _ => x end.\n  Definition tree_sons t := match t with in_tree _ l => l end.\n\n  Fact tree_root_sons_eq t : t = in_tree (tree_root t) (tree_sons t).\n  Proof. destruct t; auto. Qed.\n  \n  (* the immediate subtree relation *)\n  \n  Definition imsub_tree s t := match t with in_tree _ ll => In s ll end.\n  \n  Infix \"<ist\" := imsub_tree (at level 70).\n  \n  Fact imsub_tree_fix s t :  s <ist t <-> exists x ll, In s ll /\\ t = in_tree x ll.\n  Proof.\n    split.\n    destruct t as [ x ll ]; exists x, ll; auto.\n    intros (x & ll & H1 & ?); subst; auto.\n  Qed.\n  \n  (* The immediate subtree relation is well founded *)\n  \n  Fixpoint imsub_tree_wf t : Acc imsub_tree t.\n  Proof.\n    refine (\n      match t with\n        | in_tree x ll => Acc_intro _ _\n      end); simpl; clear x t.\n    induction ll as [ | x ll IH ].\n    intros _ [].\n    intros ? [ [] | ].\n    apply imsub_tree_wf.\n    apply IH; auto.\n  Qed.\n\n  (* let us define our own induction principles *)\n\n  Section tree_rect.\n\n    Variable P : tree -> Type.\n    Hypothesis f : forall a ll, (forall x, In x ll -> P x) -> P (in_tree a ll).\n\n    Let f' : forall t, (forall x, x <ist t -> P x) -> P t.\n    Proof.\n      intros []; apply f.\n    Defined.\n\n    Definition tree_rect t : P t.\n    Proof.\n      apply Fix with (1 := imsub_tree_wf), f'.\n    Defined.\n\n    Section tree_rect_fix.\n    \n      Variable E : forall t, P t -> P t -> Prop.\n\n      Hypothesis f_ext : forall a ll f1 f2, (forall x Hx, E (f1 x Hx) (f2 x Hx)) -> E (f a ll f1) (f a ll f2).\n\n      (* Coq recursive type-checking does not allow such a definition \n         but it is possible to prove this identity\n      *)\n\n      Fact tree_rect_fix a ll : E (tree_rect (in_tree a ll)) (f a ll (fun t _ => tree_rect t)).\n      Proof.\n        unfold tree_rect, Fix.\n        rewrite <- Fix_F_eq; unfold f'.\n        apply f_ext; intros; apply Fix_F_ext.\n        intros [] ? ?; apply f_ext.\n      Qed.\n      \n    End tree_rect_fix.\n    \n    Section tree_rect_fix_eq.\n\n      Hypothesis f_ext : forall a ll f1 f2, (forall x Hx, f1 x Hx = f2 x Hx) -> f a ll f1 = f a ll f2.\n      \n      Fact tree_rect_fix_eq a ll : tree_rect (in_tree a ll) = f a ll (fun t _ => tree_rect t).\n      Proof.\n        apply tree_rect_fix with (E := fun _ => @eq _); simpl; auto.\n      Qed.\n      \n    End tree_rect_fix_eq.\n\n  End tree_rect.\n  \n  Definition tree_rec (P : tree -> Set)  := tree_rect P.\n  Definition tree_ind (P : tree -> Prop) := tree_rect P.\n\n  Section tree_recursion.\n\n    (* the particular case when the output type does not depend on the tree *)\n\n    Variables (Y : Type) (f : X -> list tree -> list Y -> Y).    \n  \n    Definition tree_recursion : tree -> Y.\n    Proof.\n      apply tree_rect.\n      intros x ll IH.\n      apply (f x ll (list_In_map _ IH)).\n    Defined.\n    \n    (* In that case, extensionnality is for free *)\n\n    Fact tree_recursion_fix x ll : tree_recursion (in_tree x ll) = f x ll (map tree_recursion ll).\n    Proof.\n      unfold tree_recursion at 1.\n      rewrite tree_rect_fix with (E := fun _ => eq).\n      f_equal; apply list_In_map_eq_map.\n      clear x ll; intros x ll g h H; simpl.\n      f_equal; apply list_In_map_ext, H.\n    Qed.\n  \n  End tree_recursion.\n\n  (* finite quantification over the nodes of trees *)\n\n  Section tree_fall_exst.\n\n    Variable P : X -> list tree -> Prop.\n\n    Definition tree_fall (t : tree) : Prop.\n    Proof.\n      induction t as [ a ll IH ].\n      exact (P a ll /\\ forall x Hx, IH x Hx).\n    Defined.\n\n   (* this is how we would like tree_fall to be recursively defined but this would\n       not be well-formed in Coq\n    *)\n\n    Fact tree_fall_fix x ll : tree_fall (in_tree x ll) <-> P x ll /\\ forall t, In t ll -> tree_fall t. \n    Proof.\n      unfold tree_fall at 1.\n      rewrite tree_rect_fix \n        with (E := fun _ A B => A <-> B);\n        firstorder.\n    Qed.\n \n    Section tree_fall_rect.\n  \n      Variable (Q : tree -> Type).\n  \n      Hypothesis HQ : forall x ll, tree_fall (in_tree x ll) -> (forall t, In t ll -> Q t) -> Q (in_tree x ll).\n  \n      Theorem tree_fall_rect t : tree_fall t -> Q t.\n      Proof.\n        induction t as [ x ll IH ]; intros H.\n        apply HQ; auto.\n        rewrite tree_fall_fix in H; destruct H; auto.\n      Qed.\n\n    End tree_fall_rect.\n    \n    Definition tree_fall_rec (Q : tree -> Set) := @tree_fall_rect Q.\n    Definition tree_fall_ind (Q : tree -> Prop) := @tree_fall_rect Q.\n\n    Definition tree_exst (t : tree) : Prop.\n    Proof.\n      induction t as [ a ll IH ].\n      exact (P a ll \\/ exists x Hx, IH x Hx).\n    Defined.\n\n    Let disj_eq_prop (A B B' : Prop) : (B <-> B') -> (A \\/ B <-> A \\/ B').\n    Proof. tauto. Qed.\n\n    Fact tree_exst_fix x ll : tree_exst (in_tree x ll) <-> P x ll \\/ exists t, In t ll /\\ tree_exst t. \n    Proof.\n      unfold tree_exst at 1.\n      rewrite tree_rect_fix \n        with (E := fun _ A B => A <-> B).\n      apply disj_eq_prop.\n      split; intros (y & ? & ?); exists y; split; auto.\n      intros; apply disj_eq_prop.\n      split; intros (y & Hy & ?); exists y, Hy; apply H; auto.\n    Qed.\n\n  End tree_fall_exst.\n\n  Fact tree_fall_inc (P Q : _ -> _ -> Prop) : P inc2 Q -> tree_fall P inc1 tree_fall Q.\n  Proof.\n    intros H t; induction t as [ x ll IH ].\n    repeat rewrite tree_fall_fix.\n    intros []; split; auto.\n  Qed.\n\n  Fact tree_exst_inc (P Q : _ -> _ -> Prop) : P inc2 Q -> tree_exst P inc1 tree_exst Q.\n  Proof.\n    intros H t; induction t as [ x ll IH ].\n    repeat rewrite tree_exst_fix.\n    intros [| (t & ? & ?)]; [ left | right ]; auto; exists t; auto.\n  Qed. \n  \n  Section tree_fall_exst_dec.\n\n    Variable (P Q : X -> list tree -> Prop).\n\n    Hypothesis PQ_incomp : forall x ll, P x ll -> Q x ll -> False.\n    \n    Fact tree_fall_exst_incomp t : tree_fall P t -> tree_exst Q t -> False.\n    Proof.\n      induction t as [ x ll IH ].\n      rewrite tree_fall_fix, tree_exst_fix.\n      intros [ H1 H2 ] [ H3 | (t & H3 & H4) ].\n      \n      apply PQ_incomp with (1 := H1); auto.\n      apply IH with (1 := H3); auto.\n    Qed.      \n\n    Hypothesis PQ_dec : forall x ll, { P x ll } + { Q x ll }.    \n    \n    Fact tree_fall_exst_dec t : { tree_fall P t } + { tree_exst Q t }.\n    Proof.\n      induction t as [ x ll IH ].\n      destruct (list_choose_rec (tree_exst Q) (tree_fall P) ll) as [ (t & H1 & H2) | H1 ].\n      intros z Hz; specialize (IH _ Hz); tauto.\n      \n      right.\n      apply tree_exst_fix.\n      right; exists t; auto.\n      \n      destruct (PQ_dec x ll) as [ | H2 ].\n      \n      left; apply tree_fall_fix; auto.\n      \n      right.\n      apply tree_exst_fix.\n      left; auto.\n    Qed.\n    \n  End tree_fall_exst_dec.\n\n  Section tree_fall_dec.\n  \n    Variable (P : X -> list tree -> Prop).\n\n    Hypothesis PQ_dec : forall x ll, { P x ll } + { ~ P x ll }.\n    \n    Fact tree_fall_dec t : { tree_fall P t } + { ~ tree_fall P t }.\n    Proof.\n      destruct (tree_fall_exst_dec _ _ PQ_dec t) as [ | C ].\n      tauto.\n      right; intros H.\n      apply tree_fall_exst_incomp with (2 := H) (3 := C).\n      intros; tauto.\n    Qed.\n    \n    Fact tree_exst_dec t : { tree_exst P t } + { ~ tree_exst P t }.\n    Proof.\n      destruct (tree_fall_exst_dec (fun x ll => ~ P x ll) P) with (t := t) as [ C | ].\n      intros x ll; specialize (PQ_dec x ll); tauto.\n      right; intros H.\n      apply tree_fall_exst_incomp with (2 := C) (3 := H).\n      intros; tauto.\n      left; auto.\n    Qed.\n\n  End tree_fall_dec.\n\nEnd trees.\n\nSection tree_map.\n\n  Variables (X Y : Type) (f : X -> Y).\n  \n  Definition tree_map : tree X -> tree Y.\n  Proof.\n    induction 1 as [ x ts IH ] using tree_recursion.\n    apply (in_tree (f x)), IH.\n  Defined.\n\n  Fact tree_map_fix x ts : tree_map (in_tree x ts) = in_tree (f x) (map tree_map ts).\n  Proof.\n    apply tree_recursion_fix.\n  Qed.\n\nEnd tree_map.\n\nSection weighted_tree.\n\n  Variable (X : Type) (w : X -> nat).\n  \n  (* We assume that there are only finitely many terms \n     for a given weight *)\n  \n  Hypothesis Hf : forall n, finite_t (fun x => w x = n).\n  \n  (* We define a weight for trees which is strictly positive *)\n\n  Definition tree_weight : tree X -> nat.\n  Proof.\n    induction 1 as [ c _ ll ] using tree_recursion.\n    exact (1+w c+lsum ll).\n  Defined.\n  \n  Fact tree_weight_fix c ll : tree_weight (in_tree c ll) = 1 + w c + lsum (map tree_weight ll).\n  Proof. apply tree_recursion_fix. Qed.\n  \n  Fact tree_weight_gt_O t : 0 < tree_weight t.\n  Proof. destruct t; rewrite tree_weight_fix; omega. Qed.\n  \n  (* Hence there are only finitely many trees of a given weight *)\n  \n  Fact finite_t_weighted_tree n : finite_t (fun t => tree_weight t = n).\n  Proof.\n    induction n as [ [ | n ] IHn ] using (well_founded_induction_type lt_wf).\n    \n    exists nil.\n    intros x; split.\n    intros [].\n    generalize (tree_weight_gt_O x); omega.\n    \n    set (Q ln := match ln with \n                   | nil  => fun _ => False \n                   | n::l => fun t => w (tree_root t) = n\n                                   /\\ map tree_weight (tree_sons t) = l end).\n                                   \n    destruct finite_t_map with (Q := Q) (1 := finite_t_part n) as (ll & Hll); \n      unfold Q in * |- *; clear Q.\n    \n    intros [ | x ln ].\n    intros [].\n    simpl; intros (H1 & H3).\n    \n    generalize (Hf x); intros Hx.\n    destruct (@finite_t_Forall _ _ (fun i t => tree_weight t = i) ln) as (lt & Hlt).\n    intros u Hu; apply IHn. \n    apply lsum_le in Hu; omega.\n    destruct Hx as (lx & Hlx).\n    exists (list_prod (@in_tree _) lx lt).\n    intros t.    \n    rewrite list_prod_spec; split.\n    \n    intros (c & ll & ? & H4 & H5); subst t; simpl.\n    rewrite <- Hlx; split; auto.\n    apply Hlt in H5.\n    symmetry.\n    clear H1 H3 Hlx lt Hlt c H4.\n    induction H5; simpl; f_equal; auto.\n    \n    intros (? & ?); subst.\n    destruct t as (c & l); exists c, l; split; auto.\n    split.\n    apply Hlx; auto.\n    apply Hlt; simpl.\n    clear H1 lx Hlx lt Hlt IHn.\n    induction l; simpl; constructor; auto.\n    \n    exists ll.\n    intros (c,l); rewrite Hll; simpl; split.\n    intros ([ | x ln] & H1 & H2).\n    destruct H2.\n    rewrite tree_weight_fix.\n    simpl in H2, H1.\n    destruct H2 as (H3 & H4).\n    destruct H1 as (H1 & H2).\n    apply f_equal with (f := lsum) in H4.\n    omega.\n    \n    rewrite tree_weight_fix.\n    intros H.\n    exists (w c::map tree_weight l); split.\n    split.\n    rewrite Forall_forall.\n    intros t Ht.\n    rewrite in_map_iff in Ht.\n    destruct Ht as (x & ? & Hx); subst.\n    apply tree_weight_gt_O.\n    omega.\n    simpl; split; auto.\n  Qed.\n  \nEnd weighted_tree.\n\n", "meta": {"author": "DmxLarchey", "repo": "Coq-is-total", "sha": "0f3facc9cf06e0b41194fdb0cc952816fb09c39a", "save_path": "github-repos/coq/DmxLarchey-Coq-is-total", "path": "github-repos/coq/DmxLarchey-Coq-is-total/Coq-is-total-0f3facc9cf06e0b41194fdb0cc952816fb09c39a/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7232450716289114}}
{"text": "\nSection FirstOrder.\n  Require Import Coq.Lists.List.\n  Require Import Coq.Bool.Bool.\n  Require Import Setoid.\n  Require Import Coq.Arith.Peano_dec.\n\n\n  (************************************************************************************)\n  (*                           The first-order model.                                 *)\n  (************************************************************************************)\n\nRecord fo_model : Type := {\n                           D : Set;\n                           d_Eq:  relation D; (* Equivalence of domain elements *)\n                           R: nat -> (list D -> Prop); (* An ordered set of relations *)\n                           F: nat -> (list D -> D); (* An ordered set of funnctions *)\n                           m : nat -> nat; (* arity function for R; a list of (m n) length is given to (R n) *)\n                           n : nat -> nat (* arity function for F *)\n                         }.\n  (************************************************************************************)\n  (*                        Equiv is an equivalence relation.                         *)\n (************************************************************************************)\n\n  (* Reflexivity of equiv *)\n  Axiom equiv_refl : forall (M : fo_model) (d: D M), \n                       d_Eq M d d. \n\n  (* Symmetry of equiv *)\n  Axiom equiv_symm : forall (M : fo_model) (d d' : D M), \n                       d_Eq M d d' -> d_Eq M d' d. \n\n  (* Transitivity of equiv *)\n  Axiom equiv_trans : forall (M : fo_model) (d d' d'' : D M), \n                        d_Eq M d d' -> d_Eq M d' d'' -> d_Eq M d d''.\n\n\n\n\n\n  (************************************************************************************)\n  (*                   Equivalence of a list of domain elements.                      *)\n  (************************************************************************************)\n\n  Definition equiv_listD : forall (M : fo_model), relation (list (D M)).\n    exact (fix el M ds ds' :  Prop := match ds with\n      | nil => match ds' with\n                 | x :: ds'' => False (* Length differs. *)\n                 | nil => True (* Base case. *)\n               end\n      | x :: ds'' => match ds' with\n                       | y :: ds''' => (d_Eq M x y) /\\ el M ds'' ds'''\n                       | _ => False (* Length differs. *)\n                     end\n    end).\n  Defined.\n\n\n\n  (************************************************************************************)\n  (*                        Indistiguishability under Equiv                           *)\n  (************************************************************************************)\n\n  (* Indistinguishability for relations *)\n  Axiom ind_R : forall (M : fo_model) (ds : list (D M)) (ds' : list (D M)) (i : nat),\n                  equiv_listD M ds ds' (* if two lists are equivalent *)\n                  -> (R M i ds) = (R M i ds'). (* then they are either both related by R i or not *)\n\n  (* Indisitinguishability for functions *)\n  Axiom ind_F : forall (M : fo_model) (ds :list (D M)) (ds' : list (D M)) (i : nat),\n                  equiv_listD M ds ds' (* if two lists are equivalent *)\n                  -> d_Eq M (F M i ds) (F M i ds'). (* then they both produce the same result from a function F *)\n\nEnd FirstOrder.\n\n  Add Parametric Relation (M : fo_model) : (D M) (@d_Eq M)\n    reflexivity proved by (equiv_refl M)    \n    symmetry proved by (equiv_symm M)    \n    transitivity proved by (equiv_trans M)\n  as DE_rel.\n", "meta": {"author": "focal-research", "repo": "focal", "sha": "464f505060609f292ab14349daf2d9144b2edefa", "save_path": "github-repos/coq/focal-research-focal", "path": "github-repos/coq/focal-research-focal/focal-464f505060609f292ab14349daf2d9144b2edefa/FirstOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443461, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7232122275182679}}
{"text": "Require Export Relation_Definitions.\nRequire Import Relation_Definitions_Implicit.\nRequire Import Classical.\nRequire Import Arith.\n\nLocal Unset Standard Proposition Elimination Names.\n\nRecord DirectedSet := {\n  DS_set : Type;\n  DS_ord : relation DS_set;\n  DS_ord_cond : preorder DS_ord;\n  DS_join_cond : forall i j:DS_set, exists k:DS_set,\n    DS_ord i k /\\ DS_ord j k\n}.\n\nArguments DS_ord [d].\nArguments DS_ord_cond [d].\nArguments DS_join_cond [d].\n\nSection for_large.\n\nVariable I : DirectedSet.\n\nDefinition eventually (P : DS_set I -> Prop) : Prop :=\n  exists i:DS_set I, forall j:DS_set I,\n  DS_ord i j -> P j.\n\nLemma eventually_and: forall (P Q: DS_set I -> Prop),\n  eventually P -> eventually Q ->\n  eventually (fun i:DS_set I => P i /\\ Q i).\nProof.\nintros.\ndestruct H.\ndestruct H0.\ndestruct (DS_join_cond x x0) as [? [? ?]].\nexists x1.\nintros; split.\napply H.\napply preord_trans with x1; trivial.\napply DS_ord_cond.\napply H0.\napply preord_trans with x1; trivial.\napply DS_ord_cond.\nQed.\n\nLemma eventually_impl_base: forall (P Q: DS_set I -> Prop),\n  (forall i:DS_set I, P i -> Q i) ->\n  eventually P -> eventually Q.\nProof.\nintros.\ndestruct H0.\nexists x.\nintros.\nauto.\nQed.\n\nLemma eventually_impl: forall (P Q: DS_set I -> Prop),\n  eventually P -> eventually (fun i:DS_set I => P i -> Q i) ->\n  eventually Q.\nProof.\nintros.\napply eventually_impl_base with (P := fun (i:DS_set I) =>\n  P i /\\ (P i -> Q i)).\ntauto.\napply eventually_and; assumption.\nQed.\n\nDefinition exists_arbitrarily_large (P: DS_set I -> Prop) :=\n  forall i:DS_set I, exists j:DS_set I,\n  DS_ord i j /\\ P j.\n\nLemma not_eal_eventually_not: forall (P: DS_set I -> Prop),\n  ~ exists_arbitrarily_large P ->\n  eventually (fun i:DS_set I => ~ P i).\nProof.\nintros.\napply not_all_ex_not in H.\ndestruct H as [i].\nexists i.\nintros.\nintro.\ncontradiction H.\nexists j; split; trivial.\nQed.\n\nLemma not_eventually_eal_not: forall (P: DS_set I -> Prop),\n  ~ eventually P ->\n  exists_arbitrarily_large (fun i:DS_set I => ~ P i).\nProof.\nintros.\nred; intros.\napply NNPP; intro.\ncontradiction H.\nexists i.\nintros.\napply NNPP; intro.\ncontradiction H0.\nexists j; split; trivial.\nQed.\n\nEnd for_large.\n\nArguments eventually [I].\nArguments eventually_and [I].\nArguments eventually_impl_base [I].\nArguments eventually_impl [I].\nArguments exists_arbitrarily_large [I].\nArguments not_eal_eventually_not [I].\nArguments not_eventually_eal_not [I].\n\nNotation \"'for' 'large' i : I , p\" :=\n  (eventually (fun i:I => p))\n  (at level 200, i ident, right associativity).\n\nNotation \"'exists' 'arbitrarily' 'large' i : I , p\" :=\n  (exists_arbitrarily_large (fun i:I => p))\n  (at level 200, i ident, right associativity).\n\nSection nat_DS.\n\nDefinition nat_DS : DirectedSet.\nrefine (Build_DirectedSet nat le _ _).\nconstructor; red; intros; auto with arith.\napply le_trans with y; assumption.\nintros.\ncase (lt_eq_lt_dec i j).\nexists j.\ndestruct s; auto with arith.\ndestruct e; auto with arith.\nexists i; auto with arith.\nDefined.\n\nEnd nat_DS.\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/DirectedSets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7232122167139359}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural :=\n  plus y (plus Zero lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj232_coqofml_litFSl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.723212214619292}}
{"text": "Require Import Coq.Unicode.Utf8 Coq.Setoids.Setoid Coq.Lists.List.\n\nSection pair_rel.\n\n  Context {A B} (Ra: relation A) (Rb: relation B) `{!Equivalence Ra} `{!Equivalence Rb}.\n\n  Definition pair_rel: relation (A * B) :=\n    fun a b => Ra (fst a) (fst b) /\\ Rb (snd a) (snd b).\n\n  Global Instance: Equivalence pair_rel.\n  Proof. firstorder. Qed.\n\nEnd pair_rel.\n\nDefinition first {A B C} (f: A → B) (p: A * C): B * C := (f (fst p), snd p).\nDefinition second {A B C} (f: A → B) (p: C * A): C * B := (fst p, f (snd p)).\n\nLemma map_fst_map_first {A B C} (l: list (A * B)) (f: A -> C): map (@fst _ _) (map (first f) l) = map f (map (@fst _ _) l).\nProof. induction l; simpl; congruence. Qed.\n\nDefinition curry {A B C} (f: A * B → C) (a: A) (b: B): C := f (a, b).\nDefinition uncurry {A B C} (f: A → B → C) (p: A * B): C := f (fst p) (snd p).\n\nDefinition map_pair {X Y A B} (f: X → Y) (g: A → B) (xa: X * A): Y * B := (f (fst xa), g (snd xa)).\n\nLemma map_map_comp {A B C} (f: A → B) (g: B → C) (l: list A): map g (map f l) = map (Basics.compose g f) l.\nProof. apply (map_map f g). Qed.\n\nDefinition diagonal {X} (x: X): X * X := (x, x).\n", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/stdlib_omissions/Pair.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7231940622155917}}
{"text": "Require Import Arith.\nRequire Import FunctionalExtensionality.\nRequire Import Program.\nRequire Import Omega.\n\nSet Implicit Arguments.\n\nDefinition Behavior (A : Type) := nat -> A.\n\nSection shift.\n\n  Variable A : Type.\n\n  Implicit Types s : Behavior A.\n\n  Definition shift s n : Behavior A :=\n    fun t => s (t + n).\n\n  Lemma unshift : forall s n i, shift s n i = s (i+n).\n  Proof. unfold shift. auto. Qed.\n\n  Lemma shift_0 : forall s, shift s 0 = s.\n  Proof.\n    intros s; extensionality x; replace (s x) with (s (x + 0)) by auto; apply unshift.\n  Qed.\n\n  Lemma contraction : forall s n m, shift (shift s n) m = shift s (m + n).\n  Proof.\n    unfold shift; intros s n m; extensionality x; rewrite plus_assoc; auto.\n  Qed.\n\nEnd shift.\n\nDelimit Scope behavior_scope with behavior.\n\nNotation \"s @ n\" :=\n  (shift s n)\n    (at level 1, no associativity) : behavior_scope.\n\nDefinition stutter_relation {A : Type} (R : Behavior A -> Behavior A -> Prop) :=\n  (forall s s', R s s' -> s 0 = s' 0) /\\\n  (forall s s', R s s' -> exists m, R (shift s 1) (shift s' m) /\\ forall k, k < m -> s' 0 = s' k) /\\\n  (forall s s', R s s' -> exists m, R (shift s m) (shift s' 1) /\\ forall k, k < m -> s 0 = s k).\n\nDefinition stutter_equiv {A : Type} (s s' : Behavior A) : Prop :=\n  exists R, R s s' /\\ stutter_relation R.\n\nLemma stutter_equiv_stuttering_relation : forall A, stutter_relation (stutter_equiv : Behavior A -> Behavior A -> Prop).\nProof.\n  intros A.\n  repeat split; intros s s' H; destruct H as (R,(H,(H0,(H1,H2)))); auto.\n  apply H1 in H. destruct H as (m,(H,H3)); exists m; split; auto; exists R; repeat split; auto.\n  apply H2 in H. destruct H as (m,(H,H3)); exists m; split; auto; exists R; repeat split; auto.\nQed.\n\nLemma stutter_relation_univ : forall A (R : Behavior A -> Behavior A -> Prop),\n                           stutter_relation R ->\n                           forall s s',\n                             R s s' ->\n                             forall n, exists m, R (shift s n) (shift s' m).\nProof.\n  intros A R H s s' H0 n.\n  generalize dependent s. generalize dependent s'.\n  induction n.\n  intros s' s H0. exists 0. do 2 rewrite shift_0. auto.\n  intros s' s H0. destruct H as (H,(H1,H2)).\n  apply H1 in H0. destruct H0 as (m,(H0,H3)).\n  apply IHn in H0. destruct H0 as (m0,H0).\n  do 2 rewrite contraction in H0.\n  exists (m0 + m). replace (S n) with (n + 1) by omega. auto.\nQed.\n\nTheorem stutter_equiv_univ : forall A (s s' : Behavior A), stutter_equiv s s' ->\n                                                          forall n, exists m,\n                                                            stutter_equiv (shift s n) (shift s' m).\nProof.\n  intros A s s' H n.\n  apply stutter_relation_univ; trivial.\n  apply stutter_equiv_stuttering_relation.\nQed.  \n\nLemma id_stutter_prop : forall A, stutter_relation (fun (s s': Behavior A) => s = s').\nProof.\n  intros A.\n  repeat split; intros s s' H; rewrite H; auto; exists 1; split; auto;\n  intros k H0; replace k with 0 by omega; auto.\nQed.\n\nTheorem refl_stutter_equiv : forall A (s : Behavior A), stutter_equiv s s.\nProof.\n  intros A s.\n  exists (fun s s' => s = s'). split; trivial.\n  apply id_stutter_prop.\nQed.\n\nLemma flip_stutter_relation : forall A (R : Behavior A -> Behavior A -> Prop),\n                            stutter_relation R ->\n                            stutter_relation (fun s s' => R s' s).\nProof.\n  intros A R H.\n  destruct H as (H,(H0,H1)).\n  repeat split; auto.\n  intros s s' H2. symmetry. auto.\nQed.\n\nTheorem sym_stutter_equiv : forall A (s s' : Behavior A),\n                              stutter_equiv s s'\n                              -> stutter_equiv s' s.\nProof.\n  intros A s s' H.\n  destruct H as (R,(H,RS)).\n  exists (fun s s' => R s' s).\n  split; trivial.\n  apply flip_stutter_relation; trivial.\nQed.\n\nLemma le_difference : forall n m, n <= m -> exists r, m = n + r.\nProof.\n  intros n m H.\n  generalize dependent n.\n  induction m.\n  intros n H. inversion H. exists 0; omega.\n  intros n H.\n  inversion H.\n  exists 0; omega.\n  assert (T : exists r, m = n + r). apply IHm; auto.\n  destruct T as (r, T). exists (S r). omega.\nQed.\n\nLemma stutter_relation_univ_small : forall A R (s s' : Behavior A) n,\n                                      stutter_relation R ->\n                                      R s s' ->\n                                      (forall k, k < n -> s 0 = s k) ->\n                                      exists m, R (shift s n) (shift s' m) /\\\n                                                (forall k, k < m -> s' 0 = s' k).\nProof.\n  intros A R s s' n H H0 H1.\n  generalize dependent s. generalize dependent s'.\n  induction n.\n  intros s' s H0 H1. exists 0. split. do 2 rewrite shift_0. auto.\n  intros k H2. exfalso. omega.\n  intros s' s H0 H1.\n  destruct H as (R_zero,(R_left,R_right)).\n  assert (H2 : exists m, R (shift s n) (shift s' m) /\\ (forall k, k < m -> s' 0 = s' k)).\n  apply IHn; auto.\n  destruct H2 as (m,(H2,H3)).\n  assert (H4 : exists m0,\n                 R (shift (shift s n) 1) (shift (shift s' m) m0)\n                 /\\ forall k, k < m0 -> (shift s' m) 0 = (shift s' m) k).\n  apply R_left; auto.\n  destruct H4 as (m0,(H4,H5)).\n  unfold shift in H5. simpl in H5.\n  assert (H6 : s 0 = (shift s' m) 0). transitivity ((shift s n) 0). unfold shift. simpl. apply H1.\n  omega. apply R_zero; auto.\n  unfold shift in H6. simpl in H6.\n  exists (m0 + m). split.\n  do 2 rewrite contraction in H4. simpl in H4. auto.\n  intros k H.\n  assert (H7 : k < m \\/ m <= k). omega.\n  destruct H7 as [H7|H7]. apply H3; auto.\n  apply le_difference in H7.\n  destruct H7 as (r,H7).\n  assert (H8 : k = r + m). omega. clear H7.\n  rewrite H8 in *.\n  transitivity (s' m). transitivity (s 0); auto. symmetry. apply R_zero; auto.\n  apply H5. omega.\nQed.\n  \nLemma comp_stutter_prop : forall A (R1 R2 : Behavior A -> Behavior A -> Prop),\n                            stutter_relation R1 ->\n                            stutter_relation R2 ->\n                            stutter_relation (fun s s' => exists s'', R1 s s'' /\\ R2 s'' s').\nProof.\n  intros A R1 R2 H H0.\n  repeat split; intros s s' H1; destruct H1 as (t,(H1,H2)).\n  destruct H as (H,_). destruct H0 as (H0,_). transitivity (t 0); auto.\n  destruct H as (R1_zero,(R1_right,R1_left)).\n  apply R1_right in H1. destruct H1 as (m,(H1,H3)).\n  assert (H4 : exists m0, R2 (shift t m) (shift s' m0) /\\ forall k, k < m0 -> s' 0 = s' k).\n  apply stutter_relation_univ_small; auto.\n  destruct H4 as (m0,(H4,H5)). exists m0. split; auto. exists (shift t m). split; auto.\n  destruct H0 as (R2_zero,(R2_right,R2_left)).\n  assert (H3 : exists m : nat,\n              R2 (shift t m) (shift s' 1) /\\\n              (forall k : nat, k < m -> t 0 = t k)). apply R2_left; auto.\n  destruct H3 as (m,(H3,H4)).\n  set (R1_flip := fun a b => R1 b a).\n  assert (H5 : exists m0, R1_flip (shift t m) (shift s m0) /\\\n                          (forall k, k < m0 -> s 0 = s k)).\n  apply stutter_relation_univ_small; auto.\n  unfold R1_flip.\n  apply flip_stutter_relation. auto.\n  unfold R1_flip in *. clear R1_flip.\n  destruct H5 as (m0,(H5,H6)).\n  exists m0. split; auto. exists (shift t m); split; auto.\nQed.\n\nTheorem trans_stutter_equiv : forall A (s t s' : Behavior A),\n                                stutter_equiv s t ->\n                                stutter_equiv t s' ->\n                                stutter_equiv s s'.\nProof.\n  intros A s t s' H H0.\n  destruct H as (R1,(H,R1_rel)).\n  destruct H0 as (R2,(H0,R2_rel)).\n  exists (fun a b => exists c, R1 a c /\\ R2 c b).\n  split. exists t. split; auto.\n  apply comp_stutter_prop; auto.\nQed.\n  \nDefinition prop_extension {A} (R : Behavior A -> Behavior A -> Prop) :=\n  fun s s' => R s s' \\/ (s 0 = s' 0 /\\ R (shift s 1) (shift s' 1)).\n\nLemma extend_stutter_relation : forall A (R : Behavior A -> Behavior A -> Prop),\n                                  stutter_relation R ->\n                                  stutter_relation (prop_extension R).\nProof.\n  intros A R H.\n  destruct H as (H,(H0,H1)).\n  repeat split; intros s s' H2; destruct H2 as [H2|(H2,H3)]; auto.\n  apply H0 in H2. destruct H2 as (m,(H2,H3)). exists m. split; auto. left; auto.\n  exists 1. split. left. auto. intros k H4. replace k with 0 by omega; auto.\n  apply H1 in H2. destruct H2 as (m,(H2,H3)). exists m. split; auto. left; auto.\n  exists 1. split. left. auto. intros k H4. replace k with 0 by omega; auto.\nQed.\n  \nTheorem extend_stutter_equiv : forall A (s s' : Behavior A), s 0 = s' 0 ->\n                                            stutter_equiv (shift s 1) (shift s' 1) ->\n                                            stutter_equiv s s'.\nProof.\n  intros A s s' H H0.\n  destruct H0 as (R,(H0,H1)).\n  exists (prop_extension R). split.\n  right; split; auto.\n  apply extend_stutter_relation; auto.\nQed.  \n\nDefinition front_relation {A} (s s' : Behavior A) := exists m n, s 0 = s' 0 /\\\n                                                                 (forall k, k <= m -> s 0 = s k) /\\\n                                                                 (forall k, k <= n -> s' 0 = s' k) /\\\n                                                                 shift s m = shift s' n.\n\nLemma front_relation_refl : forall A (s : Behavior A), front_relation s s.\nProof.\n  intros A s.\n  exists 0. exists 0. repeat split; auto; intros k H; replace k with 0 by omega; auto.\nQed.\n\nLemma front_relation_step : forall A  (s s' : Behavior A),  front_relation s s' ->\n   exists m : nat,\n     front_relation s @ 1%behavior s' @ m%behavior /\\\n     (forall k : nat, k < m -> s' 0 = s' k).\nProof.\n  intros A s s' H.\n  destruct H as (m,(n,(same_zero,(lt_m,(lt_n,same_tail))))).\n  destruct m. exists (S n). split. rewrite shift_0 in same_tail.\n  rewrite same_tail. rewrite contraction. simpl. apply front_relation_refl.\n  intros k H. apply lt_n; omega.\n  exists n. split. exists m. exists 0.\n  assert (same_one : s 0 = s 1). apply lt_m; omega.\n  repeat split.\n  unfold shift. simpl. transitivity (s 0). auto. \n  transitivity (s' 0); auto.\n  intros k H. unfold shift. simpl. transitivity (s 0); auto.\n  apply lt_m; omega.\n  intros k H. replace k with 0 by omega. auto.\n  do 2 rewrite contraction. simpl. replace (m + 1) with (S m) by omega. auto.\n  intros k H. apply lt_n; omega.\nQed.\n\nLemma front_relation_sym : forall A (s s' : Behavior A), front_relation s s' ->\n                                                         front_relation s' s.\nProof.\n  intros A s s' H.\n  destruct H as (m,(n,(same_refl,(lt_m,(lt_n,same_tail))))).\n  exists n. exists m. repeat split; auto.\nQed.\n  \nLemma front_stutter_relation : forall A, stutter_relation (front_relation : Behavior A -> Behavior A -> Prop).\nProof.\n  intros A.\n  repeat split; intros s s' H.\n  destruct H as (m,(n,(same_zero,(lt_m,(lt_n,same_tail))))); auto.\n  apply front_relation_step; auto.\n  apply front_relation_sym in H. apply front_relation_step in H.\n  destruct H as (m,(H,H0)).\n  exists m. split; auto. apply front_relation_sym; auto.\nQed.\n\nLemma front_relation_shift_1 : forall A (s : Behavior A), s 0 = s 1 ->\n                                                          front_relation (shift s 1) s.\nProof.\n  intros A s H.\n  exists 0. exists 1. repeat split; auto.\n  intros k H0. replace k with 0 by omega; auto.\n  intros k H0. assert (H1 : k = 0 \\/ k = 1). omega. destruct H1 as [H1|H1]; rewrite H1; auto.\n  rewrite contraction. auto.\nQed.\n\nTheorem stutter_equiv_shift_1 : forall A (s : Behavior A), s 0 = s 1 ->\n                                                         stutter_equiv (shift s 1) s.\nProof.\n  intros A s H.\n  exists front_relation. split.\n  apply front_relation_shift_1; auto.\n  apply front_stutter_relation; auto.\nQed.\n\nTheorem stutter_equiv_induct_next : forall A (s s' : Behavior A) R,\n                                      stutter_equiv s s' ->\n                                      (forall n, R (s n) (s (S n)) \\/ s n = s (S n)) ->\n                                      (forall n, R (s' n) (s' (S n)) \\/ s' n = s' (S n)).\nProof.\n  intros A s s' R H H0 n.\n  assert (H1 : exists m, stutter_equiv (shift s' n) (shift s m)).\n  apply stutter_equiv_univ. apply sym_stutter_equiv; auto.\n  destruct H1 as (m,H1).\n  assert (H2 : stutter_relation (stutter_equiv : Behavior A -> Behavior A -> Prop)).\n  apply stutter_equiv_stuttering_relation.\n  destruct H2 as (same_zero,(step_left,step_right)).\n  assert (H2 : (shift s' n) 0 = (shift s m) 0). apply same_zero.  auto.\n  unfold shift in H2. simpl in H2.\n  rewrite H2.\n  apply step_left in H1.\n  destruct H1 as (m0,(H1,H3)).\n  destruct m0.\n  assert (H4 : (shift (shift s' n) 1) 0 = (shift (shift s m) 0) 0). apply same_zero; auto.\n  unfold shift in H4. simpl in H4.\n  rewrite H4. right; auto.\n  assert (H4 : (shift s m) 0 = (shift s m) m0). apply H3; omega.\n  unfold shift in H4. simpl in H4.\n  assert (H5 : (shift (shift s' n) 1) 0 = (shift (shift s m) (S m0)) 0). apply same_zero; auto.\n  unfold shift in H5. simpl in H5.\n  rewrite H4. rewrite H5.\n  apply H0.\nQed.\n\nTheorem stutter_equiv_same_first : forall A (s s' : Behavior A),\n                                     stutter_equiv s s' ->\n                                     s 0 = s' 0.\nProof.\n  intros A s s' H.\n  destruct H as (r,(H,(same_zero,_))).\n  auto.\nQed.\n\nTheorem stutter_equiv_induct_next'_base\n     : forall (A : Type) (s s' : Behavior A) (R : A -> A -> Prop),\n       stutter_equiv s s' ->\n       R (s 0) (s 1) -> s 0 <> s 1 ->\n       exists n : nat, R (s' n) (s' (S n)).\nProof.\n  intros A s s' R H H1 H2.\n  pose (H3 := stutter_equiv_stuttering_relation A).\n  destruct H3 as (H3,(H4,H5)).\n  assert (H6 : exists m, stutter_equiv s @ 1%behavior s' @ m%behavior /\\\n       (forall k : nat, k < m -> s' 0 = s' k)). apply H4; auto.\n  destruct H6 as (m,(H6,H7)).\n  assert (H0 : s 0 = s' 0). apply H3; auto.\n  destruct m.\n  apply H3 in H6. unfold shift in H6. simpl in H6.\n  rewrite H0 in H2. rewrite H6 in H2. exfalso. apply H2; auto.\n  exists m.\n  apply H3 in H6. unfold shift in H6. simpl in H6.\n  rewrite <- H6.\n  specialize H7 with m. rewrite <- H7; auto.\n  rewrite <- H0.\n  auto.\nQed.\n\nTheorem stutter_equiv_induct_next'\n     : forall (A : Type) (s s' : Behavior A) (R : A -> A -> Prop),\n       stutter_equiv s s' ->\n       (exists n : nat, R (s n) (s (S n)) /\\ s n <> s (S n)) ->\n       exists n : nat, R (s' n) (s' (S n)).\nProof.\n  intros A s s' R H H1.\n  destruct H1 as (n,(H1,H2)).\n  assert (H3 : exists m, stutter_equiv (shift s n) (shift s' m)). apply stutter_equiv_univ; auto.\n  destruct H3 as (m,H3). \n  assert (H4 : exists n0, R ((s' @ m%behavior) n0) ((s' @ m%behavior) (S n0))).\n  apply stutter_equiv_induct_next'_base with (s @ n%behavior); auto.\n  destruct H4 as (n0,H4).\n  unfold shift in H4. simpl in H4.\n  exists (n0 + m); auto.\nQed.\n\nTheorem stutter_equiv_induct_next''\n     : forall (A : Type) (s s' : Behavior A) (R : A -> A -> Prop) (B : Type) (f : A -> B),\n       stutter_equiv s s' ->\n       (exists n : nat, R (s n) (s (S n)) /\\ f (s n) <> f (s (S n))) ->\n       exists n : nat, R (s' n) (s' (S n)) /\\ f (s' n) <> f (s' (S n)).\nProof.\n  intros A s s' R B f H H1.\n  destruct H1 as (n,(H1,H2)).\n  set (M := fun x y => R x y /\\ f x <> f y).\n  assert (H3 : exists m, M (s' m) (s' (S m))).\n  apply stutter_equiv_induct_next' with s; auto.\n  exists n. unfold M. repeat split; auto. intros N. apply H2; rewrite N; auto.\n  auto.\nQed.\n\n\nRequire Import Relations.\nRequire Import Setoid.\nRequire Import Morphisms.\nImport RelationClasses.\n\nAdd Parametric Relation A : (Behavior A) (@stutter_equiv A)\n    reflexivity proved by (fun s => refl_stutter_equiv s)\n    symmetry proved by (fun s s' H => sym_stutter_equiv H)\n    transitivity proved by (fun s t s' H0 H1 => trans_stutter_equiv H0 H1)\n      as stutter_equiv_rel.\n", "meta": {"author": "philipjf", "repo": "AWG-AVOCS-2016", "sha": "c6bf5fd38813bac1a4d34f78c11e13398031dcff", "save_path": "github-repos/coq/philipjf-AWG-AVOCS-2016", "path": "github-repos/coq/philipjf-AWG-AVOCS-2016/AWG-AVOCS-2016-c6bf5fd38813bac1a4d34f78c11e13398031dcff/src/Behavior.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7231491081476357}}
{"text": "(* The language and semantics in this file is mainly copied from software foundation. Benjamin C. Pierce, Arthur Azevedo de Amorim, Chris Casinghino, Marco Gaboardi, Michael Greenberg, Catalin Hritcu, Vilhelm Sjöberg, and Brent Yorgey. http://www.cis.upenn.edu/ bcpierce/sf. *)\n\nRequire Import Coq.ZArith.ZArith.\n\nSection Imp.\n\nContext {Var: Type}.\n\nDefinition state := Var -> Z.\n\nDefinition update (st : state) (x : Var) (n : Z) (st': state): Prop :=\n  st' x = n /\\\n  (forall x0, x0 <> x -> st x0 = st' x0).\n\nInductive aexp : Type :=\n  | AVar : Var -> aexp\n  | ANum : Z -> aexp\n  | APlus : aexp -> aexp -> aexp\n  | AMinus : aexp -> aexp -> aexp\n  | AMult : aexp -> aexp -> aexp.\n\nInductive bexp : Type :=\n  | BTrue : bexp\n  | BFalse : bexp\n  | BEq : aexp -> aexp -> bexp\n  | BLe : aexp -> aexp -> bexp\n  | BNot : bexp -> bexp\n  | BAnd : bexp -> bexp -> bexp.\n\nFixpoint aeval (st : state) (a : aexp) : Z :=\n  match a with\n  | AVar x => st x\n  | ANum n => n\n  | APlus a1 a2 => (aeval st a1) + (aeval st a2)\n  | AMinus a1 a2  => (aeval st a1) - (aeval st a2)\n  | AMult a1 a2 => (aeval st a1) * (aeval st a2)\n  end.\n\nFixpoint beval (st : state) (b : bexp) : bool :=\n  match b with\n  | BTrue       => true\n  | BFalse      => false\n  | BEq a1 a2   => Zeq_bool (aeval st a1) (aeval st a2)\n  | BLe a1 a2   => Zle_bool (aeval st a1) (aeval st a2)\n  | BNot b1     => negb (beval st b1)\n  | BAnd b1 b2  => andb (beval st b1) (beval st b2)\n  end.\n\nInductive cmd : Type :=\n  | CSkip : cmd\n  | CAss : Var -> aexp -> cmd\n  | CSeq : cmd -> cmd -> cmd\n  | CIf : bexp -> cmd -> cmd -> cmd\n  | CWhile : bexp -> cmd -> cmd.\n\nNotation \"'SKIP'\" :=\n  CSkip.\nNotation \"x '::=' a\" :=\n  (CAss x a) (at level 60).\nNotation \"c1 ;; c2\" :=\n  (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity).\nNotation \"'IFB' c1 'THEN' c2 'ELSE' c3 'FI'\" :=\n  (CIf c1 c2 c3) (at level 80, right associativity).\n\nReserved Notation \" t '/' st '==>' t' '/' st' \" \n                  (at level 40, st at level 39, t' at level 39).\n\nInductive cstep : (cmd * state) -> (cmd * state) -> Prop :=\n  | CS_Ass : forall st st' i n a,\n      aeval st a = n ->\n      update st i n st' ->\n      (i ::= a) / st ==> SKIP / st'\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      c1 / st ==> c1' / st' ->\n      (c1 ;; c2) / st ==> (c1' ;; c2) / st'\n  | CS_SeqFinish : forall st c2,\n      (SKIP ;; c2) / st ==> c2 / st\n  | CS_IfTrue : forall st b c1 c2,\n      beval st b = true ->\n      IFB b THEN c1 ELSE c2 FI / st ==> c1 / st\n  | CS_IfFalse : forall st b c1 c2,\n      beval st b = false ->\n      IFB b THEN c1 ELSE c2 FI / st ==> c2 / st\n  | CS_WhileTrue : forall st b c1,\n      beval st b = true ->\n      (WHILE b DO c1 END) / st ==> (c1;; (WHILE b DO c1 END)) / st\n  | CS_WhileFalse : forall st b c1,\n      beval st b = false ->\n      (WHILE b DO c1 END) / st ==> SKIP / st\n\n  where \" t '/' st '==>' t' '/' st' \" := (cstep (t,st) (t',st')).\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/examples/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7231491036496247}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) : natural := plus (mult z y) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj286_coqofml_XqF2dE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7231490997461285}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural := plus (Succ y) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj181_coqofml_ck4xWV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.723149095099489}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (lf2 : natural) : natural :=\n  plus lf1 lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj33_coqofml_O3m8Es.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7231490907501068}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural := plus (Succ lf1) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj234_coqofml_fnOKpW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7231490888726729}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus y (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj196_coqofml_N85k3T.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989810230102, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7231490872924959}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) (y : natural) : natural :=\n  mult y x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj2411_coqofml_L4edKf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7231490807684227}}
{"text": "(* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% *) \n(* Mainly borrowed from Sofware Foundations, v.4 \n   $Date: 2015-12-11 17:17:29 -0500 (Fri, 11 Dec 2015) $\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% *) \n\n\n(* ***************************************************************** *)\n(** * Identifiers as wrappers of nats *)\n(* ***************************************************************** *)\n(* ***************************************************************** *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\n\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.Structures.OrdersAlt.\nRequire Import Coq.Structures.Equalities.\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import Coq.MSets.MSets.\nRequire Import Coq.FSets.FMapAVL.\n\n\n(* ################################################################# *)\n(** ** Identifier Definitions  *)\n(* ################################################################# *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id id1 id2 :=\n  match id1,id2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\n(* ================================================================= *)\n(** *** Properties of Identifiers *)\n(* ================================================================= *)\n\nTheorem beq_id_refl : forall id, true = beq_id id id.\nProof.\n  intros [n]. simpl. rewrite <- beq_nat_refl.\n  reflexivity.\nQed.\n\nTheorem beq_id_true_iff : forall id1 id2 : id,\n  beq_id id1 id2 = true <-> id1 = id2.\nProof.\n   intros [n1] [n2].\n   unfold beq_id. \n   rewrite beq_nat_true_iff.\n   split.\n   - (* -> *) intros H. rewrite H. reflexivity.\n   - (* <- *) intros H. inversion H. reflexivity.\nQed.\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity.\nQed.\n\nTheorem false_beq_id : forall x y : id,\n   x <> y\n   -> beq_id x y = false.\nProof.\n  intros x y. rewrite beq_id_false_iff.\n  intros H. apply H.\nQed.\n\n(* ----------------------------------------------------------------- *)\n(** **** Reflecting Equality of Identifiers *)\n(* ----------------------------------------------------------------- *)\n\n(** It's convenient to use the reflection idioms.  \n    We begin by proving a fundamental _reflection lemma_ relating \n    the equality proposition on [id]s \n    with the boolean function [beq_id]. *)\n\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma beq_idP : forall x y, reflect (x = y) (beq_id x y).\nProof.\n  intros x y. \n  apply iff_reflect. symmetry. apply beq_id_true_iff.\nQed.\n\n(* ----------------------------------------------------------------- *)\n(** **** Propositional Equality of Identifiers *)\n(* ----------------------------------------------------------------- *)\n\nDefinition eq_id x y : Prop :=\n  match x, y with\n    Id n, Id m => eq_nat n m\n  end.\n\nLemma eq_id_iff_eq_nat : forall n m,\n    eq_id (Id n) (Id m) <-> eq_nat n m.\nProof.\n  tauto.\nQed. \n\nTheorem eq_id_decide : forall x y, {eq_id x y} + {~ eq_id x y}.\nProof.\n  intros [n] [m]. simpl.\n  apply eq_nat_decide.\nQed.\n\nTheorem eq_id_dec : forall (x y : id), {x = y} + {x <> y}.\nProof.\n  intros [x] [y]. destruct (eq_nat_dec x y) as [H|H].\n  - subst. left. reflexivity.\n  - right. intros contra. inversion contra as [contra'].\n    apply H in contra'. assumption.\nQed.\n", "meta": {"author": "julbinb", "repo": "ftfjp-2019", "sha": "2346bd5529a03a24efbea770adffe31d568c6499", "save_path": "github-repos/coq/julbinb-ftfjp-2019", "path": "github-repos/coq/julbinb-ftfjp-2019/ftfjp-2019-2346bd5529a03a24efbea770adffe31d568c6499/Mechanization/Aux/Identifier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7231225959590779}}
{"text": "Require Import Coq.QArith.QArith_base.\nRequire Import Coq.QArith.QArith.\nRequire Import Coq.QArith.Qfield.\nRequire Import Coq.PArith.BinPos.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Lists.List.\nRequire Import NPeano.\n\nRequire Import Shorthand.\nRequire Import Prefix.\nRequire Import Combi.\n\nLocal Open Scope nat.\n\nFixpoint e2 (x : nat) : positive :=\n  match x with\n      | 0 => xH\n      | S m => xO (e2 m)\n  end.\n\nLocal Open Scope positive_scope.\n\nTheorem e2_mul : forall (a : nat) (b : nat), (e2 a) * (e2 b) = e2 (a + b).\nProof.\n  intros.\n  induction a.\n  replace (e2 0) with BinNums.xH.\n  replace (0 + b)%nat with b.\n  apply Pos.mul_1_l.\n  auto.\n  auto.\n  replace (S a + b)%nat with (S (a + b))%nat.\n  replace (e2 (S a)) with (BinPos.Pos.mul 2 (e2 (a))).\n  replace (e2 (S (a + b))) with (BinPos.Pos.mul 2 (e2 (a + b))).\n  apply eq_sym.\n  replace (e2 (a + b)) with (BinPos.Pos.mul (e2 a) (e2 b)).\n  apply BinPos.Pos.mul_assoc.\n  auto.\n  auto.\n  auto.\nDefined.\n\n(* todo: gibts vmtl woanders *)\nDefinition kraft_f_1 : forall (m n : nat), (m - n = 0 -> m <= n)%nat.\nProof.\n  intros.\n  omega.\nDefined.\n\nLocal Open Scope Q_scope.\n\nFunction kraft_list (l : list LB) : Q :=\n  foldlist 0 (fun x y => Qplus (1 # (e2 (ll x))) y) l.\n\nLemma kraft_pflist_split : forall l, pflist l -> (In Bnil l +\n  (kraft_list (splitlist true l) + kraft_list (splitlist false l) ==\n  (2 # 1) * kraft_list l))%type.\nProof.\n  intros l pfl.\n  induction l.\n  apply inr.\n  reflexivity.\n  induction a.\n  apply inl.\n  apply in_eq.\n  assert (H:In Bnil l + (kraft_list (splitlist true l) + kraft_list (splitlist false l) ==\n                       (2 # 1) * kraft_list l)).\n  apply IHl.\n  unfold pflist.\n  intros x y z t u.\n  apply pfl.\n  apply in_cons.\n  auto.\n  apply in_cons.\n  auto.\n  auto.\n  elim H.\n  intros innil.\n  apply inl.\n  apply in_cons.\n  auto.\n  intros kraftind.\n  apply inr.\n  induction a.\n  assert(tmp1:kraft_list (splitlist true ((true :: a0) :: l)) =\n              (1 # (e2 (ll a0))) + kraft_list (splitlist true l)).\n  reflexivity.\n  rewrite -> tmp1.\n  assert(tmp2: splitlist false ((true :: a0) :: l) = splitlist false l).\n  reflexivity.\n  rewrite -> tmp2.\n  assert(tmp3:kraft_list ((true :: a0) :: l)=(1 # (e2 (ll (true :: a0))))+kraft_list l).\n  reflexivity.\n  rewrite -> tmp3.\n  assert(tmp4:(2 # 1) * ((1 # e2 (ll (true :: a0))) + kraft_list l) ==\n              (2 # 1) * (1 # e2 (ll (true :: a0))) + (2 # 1) * (kraft_list l)).\n  ring.\n  rewrite -> tmp4.\n  assert (tmp5:(1 # e2 (ll a0)) + kraft_list (splitlist true l) +\n               kraft_list (splitlist false l) ==\n               (1 # e2 (ll a0)) + (kraft_list (splitlist true l) +\n                                   kraft_list (splitlist false l))).\n  ring.\n  rewrite -> tmp5.\n  rewrite -> kraftind.\n  assert (tmp1337:(1 # e2 (ll (true :: a0))) = (1#2)*(1#e2(ll(a0)))).\n  reflexivity.\n  rewrite -> tmp1337.\n  ring.\n  assert(tmp1:kraft_list (splitlist false ((false :: a0) :: l)) =\n              (1 # (e2 (ll a0))) + kraft_list (splitlist false l)).\n  reflexivity.\n  rewrite -> tmp1.\n  assert(tmp2: splitlist true ((false :: a0) :: l) = splitlist true l).\n  reflexivity.\n  rewrite -> tmp2.\n  assert(tmp3:kraft_list ((false :: a0) :: l)=(1 # (e2 (ll (false :: a0))))+kraft_list l).\n  reflexivity.\n  rewrite -> tmp3.\n  assert(tmp4:(2 # 1) * ((1 # e2 (ll (false :: a0))) + kraft_list l) ==\n              (2 # 1) * (1 # e2 (ll (false :: a0))) + (2 # 1) * (kraft_list l)).\n  ring.\n  rewrite -> tmp4.\n  assert (tmp5:kraft_list (splitlist true l) + ((1 # e2 (ll a0)) + \n               kraft_list (splitlist false l)) ==\n               (1 # e2 (ll a0)) + (kraft_list (splitlist true l) +\n                                   kraft_list (splitlist false l))).\n  ring.\n  rewrite -> tmp5.\n  rewrite -> kraftind.\n  assert (tmp1337:(1 # e2 (ll (false :: a0))) = (1#2)*(1#e2(ll(a0)))).\n  reflexivity.\n  rewrite -> tmp1337.\n  ring.\nDefined.\n\nLemma kraft_pflist : forall l, dflist l -> pflist l -> kraft_list l <= 1.\nProof.\n  intros lq dfq pfq.\n  refine ((fix f n l df pf (eq0 : (list_maxlen l <= n)%nat) :=\n             match n as m return ((m = n) -> _) with\n               | 0%nat => (fun eq => _)\n               | (S n') => (fun eq => _)\n             end eq_refl) (S (list_maxlen lq)) lq dfq pfq _).\n  rewrite <- eq in eq0.\n  inversion eq0.\n  induction l.\n  compute.\n  intros Q.\n  inversion Q.\n  inversion H0.\n  destruct a.\n  destruct l.  \n  apply Qle_refl.\n  destruct l.\n  inversion df.\n  contradict H4.\n  apply in_eq.\n  assert (H2:max (ll Bnil) (list_maxlen ((b :: l) :: l0))=(list_maxlen ((b :: l) :: l0))).\n  apply Max.max_0_l.\n  rewrite -> H2 in H1.\n  inversion H1.\n  destruct (list_maxlen l0).\n  inversion H3.\n  inversion H3.\n  inversion H1.\n  destruct (list_maxlen l).\n  inversion H2.\n  inversion H2.\n\n  elim (kraft_pflist_split l pf).\n  intros innil.\n  destruct l.\n  inversion innil.\n  destruct l.\n  destruct l0.\n  compute.\n  intros Q.\n  inversion Q.\n  assert (q1 : In l (Bnil :: l :: l0)).\n  apply in_cons.\n  apply in_eq.\n  assert (q2 : Bnil <> l).\n  inversion df.\n  contradict H2.\n  rewrite <- H2.\n  apply in_eq.\n  assert (ispref : prefix Bnil l).\n  exists l.\n  apply app_nil_l.\n  contradict ispref.\n  apply pf.\n  apply innil.\n  apply q1.\n  apply q2.\n  assert(q1:In(b :: l)((b :: l) :: l0)).\n  apply in_eq.\n  assert (ispref : prefix Bnil (b :: l)).\n  exists (b :: l).\n  apply app_nil_l.\n  contradict ispref.\n  apply pf.\n  apply innil.\n  apply q1.\n  intros Q.\n  inversion Q.\n  intros rc.\n  assert(tmp1:(1#2)*(kraft_list (splitlist true l)) + (1#2)*kraft_list (splitlist false l) ==\n              kraft_list l).\n  assert(tmp2:(1#2)*(kraft_list (splitlist true l)) + (1#2)*(kraft_list (splitlist false l)) ==\n              (1#2)*(kraft_list (splitlist true l) + kraft_list (splitlist false l))).\n  ring.\n  rewrite -> tmp2.\n  rewrite -> rc.\n  ring.\n  rewrite <- tmp1.\n  assert (tmp2 : 1 == (1 # 2) + (1 # 2)).\n  ring.\n  rewrite -> tmp2.\n  assert (rec : forall b, kraft_list (splitlist b l) <= 1).\n  intros b.\n  apply (f n').\n  apply dflist_splittable.\n  auto.\n  apply pflist_splittable.\n  auto.\n  elim (eq_nat_dec (list_maxlen (splitlist b l)) 0).\n  intros iseq.\n  rewrite -> iseq.\n  apply le_0_n.\n  intros isneq.\n  apply lt_n_Sm_le.\n  rewrite -> eq.\n  apply (lt_le_trans _ (list_maxlen l)).\n  apply maxlen_split.\n  contradict isneq.\n  apply maxlen_split_3.\n  apply isneq.\n  auto.\n  apply Qplus_le_compat.\n  assert (tmp3 : 1 # 2 == (1 # 2) * 1).\n  ring.\n  rewrite -> tmp3.\n  apply Qmult_le_l.\n  reflexivity.\n  apply rec.\n  assert (tmp3 : 1 # 2 == (1 # 2) * 1).\n  ring.\n  rewrite -> tmp3.\n  apply Qmult_le_l.\n  reflexivity.\n  apply rec.\n  auto.\nDefined.\n\nLemma kraft_pflist_sharp_2 : forall l, 0 <= kraft_list l.\nProof.\n  induction l.\n  compute.\n  intros Q.\n  inversion Q.\n  assert (l' : kraft_list (a :: l) == (1 # (e2 (ll a))) + kraft_list l).\n  reflexivity.\n  rewrite -> l'.\n  assert (l'' : 0 == 0 + 0).\n  ring.\n  rewrite l''.\n  apply Qplus_le_compat.\n  compute.\n  intros Q.\n  inversion Q.\n  apply IHl.\nDefined.\n\nLemma kraft_pflist_sharp_1 : forall l, dflist l -> pflist l ->\n                                       (forall m, dflist (m :: l) -> pflist (m :: l) -> False)\n                                       -> kraft_list l <> 0.\nProof.\n  intros l H H0 H1 k0.\n  destruct l.\n  apply (H1 nil).\n  apply dflist_cons.\n  auto.\n  auto.\n  intros a b ina inb anb pf.\n  inversion ina.\n  inversion inb.\n  contradict anb.\n  rewrite <- H2.\n  apply H3.\n  inversion H3.\n  inversion H2.\n  destruct l.\n  destruct l0.\n  inversion k0.\n  destruct l.\n  inversion H.\n  contradict H5.\n  apply in_eq.\n  assert (pref : prefix Bnil (b :: l)).\n  exists (b :: l).\n  apply app_nil_l.\n  contradict pref.\n  apply H0.\n  apply in_eq.\n  apply in_cons.\n  apply in_eq.\n  intros Q.\n  inversion Q.\n  assert (k1 : 0 == kraft_list ((b :: l) :: l0)).\n  rewrite -> k0.\n  reflexivity.\n  contradict k1.\n  apply Qlt_not_eq.\n  assert (kg' : kraft_list ((b :: l) :: l0) == (1 # (e2 (S (ll l)))) + kraft_list l0).\n  reflexivity.\n  rewrite -> kg'.\n  assert (kg'' : 0 == 0 + 0).\n  ring.\n  rewrite -> kg''.\n  apply Qplus_lt_le_compat.\n  reflexivity.\n  apply kraft_pflist_sharp_2.\nDefined.\n\nLemma kraft_pflist_sharp : forall l, dflist l -> pflist l ->\n                                     (forall m, dflist (m :: l) -> pflist (m :: l) -> False)\n                                     -> kraft_list l == 1.\nProof.\n  intros lq dfq pfq fmq.\n  refine ((fix f n l (le : (list_maxlen l <= n)%nat) df pf fm :=\n             match n as m return (n = m -> _) with\n               | 0%nat => fun eq => _\n               | S n' => fun eq => _\n             end eq_refl)\n            (list_maxlen lq) lq (le_refl (list_maxlen lq)) dfq pfq fmq).\n  rewrite -> eq in le.\n  induction l.\n  assert (Q:False).\n  apply (fm nil).\n  apply dflist_cons.\n  auto.\n  auto.\n  unfold pflist.\n  intros a b ina inb aneqb.\n  inversion ina.\n  inversion inb.\n  contradict aneqb.\n  rewrite <- H.\n  auto.\n  inversion H0.\n  inversion H.\n  contradict Q.\n  destruct a.\n  destruct l.\n  reflexivity.\n  destruct l.\n  inversion df.\n  match goal with E : _ |- _ => contradict E; apply in_eq end.\n  assert (ispf : prefix Bnil (b :: l)).\n  exists (b :: l).\n  apply app_nil_l.\n  contradict ispf.\n  apply pf.\n  apply in_eq.\n  apply in_cons.\n  apply in_eq.\n  intros Q.\n  inversion Q.\n\n  inversion le.\n  destruct (list_maxlen l).\n  match goal with E : _ |- _ => inversion E end.\n  match goal with E : _ |- _ => inversion E end.\n\n  assert(indec : {In nil l}+{~ In nil l}).\n  apply in_dec.\n  apply list_eq_dec.\n  apply bool_dec.\n  elim indec.\n  intros innil.\n  destruct l.\n  inversion innil.\n  destruct l.\n  destruct l0.\n  reflexivity.\n  destruct l.\n  inversion df.\n  contradict H2.\n  apply in_eq.\n  assert (pref : prefix Bnil (b :: l)).\n  exists (b :: l).\n  auto.\n  contradict pref.\n  apply pf.\n  apply in_eq.\n  apply in_cons.\n  apply in_eq.\n  intros Q.\n  inversion Q.\n  assert (pref : prefix Bnil (b :: l)).\n  exists (b :: l).\n  auto.\n  contradict pref.\n  apply pf.\n  apply innil.\n  apply in_eq.\n  intros Q.\n  inversion Q.\n  intros nin.\n  elim (kraft_pflist_split l pf).\n  intros isin.\n  contradict nin.\n  auto.\n  intros kl.\n  apply (Qmult_inj_l _ _ (2 # 1)).\n  compute.\n  intros Q.\n  inversion Q.\n  rewrite <- kl.\n\n  assert (H_bl : forall bl, kraft_list (splitlist bl l) == 1).\n  intros bl.\n  apply (f n').\n  apply le_S_n.\n  apply (le_trans _ (list_maxlen l)).\n  apply maxlen_split.\n  destruct l.\n  intros _.\n  apply (fm nil).\n  apply dflist_cons.\n  apply dflist_nil.\n  apply nin.\n  intros a b ina inb anb.\n  inversion ina.\n  inversion inb.\n  contradict anb.\n  rewrite <- H.\n  apply H0.\n  inversion H0.\n  inversion H.\n\n  destruct l.\n  contradict nin.\n  apply in_eq.\n  intros Q.\n  inversion Q.\n  destruct(list_maxlen l0).\n  inversion H0.\n  inversion H0.\n  rewrite <- eq.\n  auto.\n  apply dflist_splittable.\n  auto.\n  apply pflist_splittable.\n  auto.\n  intros m d p.\n  apply (fm (bl :: m)).\n  inversion d.\n  apply dflist_cons.\n  apply df.\n  contradict H2.\n  apply pflist_splittable_3.\n  apply H2.\n  intros a b ina inb anb.\n\n  elim (list_eq_dec bool_dec a (bl :: m)).\n\n  intros a_eq.\n  rewrite a_eq.\n  inversion inb.\n  contradict H.\n  rewrite <- a_eq.\n  apply anb.\n  destruct b.\n  auto.\n  intros ispref.\n  inversion ispref.\n  inversion H0.\n  assert (ispref2 : prefix m b0).\n  exists x.\n  apply H3.\n  contradict ispref2.\n  apply p.\n  apply in_eq.\n  apply in_cons.\n  apply pflist_splittable_3.\n  rewrite -> H2.\n  auto.\n  rewrite -> a_eq in anb.\n  rewrite <- H2 in anb.\n  intros q.\n  contradict anb.\n  rewrite <- q.\n  reflexivity.\n  intros a_neq.\n  destruct a.\n  contradict nin.\n  assert (ininv : (bl :: m) = Bnil \\/ In Bnil l).\n  apply in_inv.\n  auto.\n  elim ininv.\n  intros Q.\n  inversion Q.\n  trivial.\n  elim (list_eq_dec bool_dec b (bl :: m)).\n  intros beq.\n  rewrite -> beq.\n  intros pref.\n  inversion pref.\n  inversion H.\n  assert (pref2 : prefix a m).\n  exists x.\n  apply H2.\n  contradict pref2.\n  apply p.\n  rewrite -> H1 in ina.\n  inversion ina.\n  contradict a_neq.\n  rewrite -> H1.\n  auto.\n  apply in_cons.\n  apply pflist_splittable_3.\n  apply H0.\n  apply in_eq.\n  rewrite -> H1 in a_neq.\n  contradict a_neq.\n  rewrite <- a_neq.\n  reflexivity.\n  intros b_neq.\n  assert (ininv : (bl :: m) = (b0 :: a) \\/ In (b0 :: a) l).\n  apply in_inv.\n  auto.\n  elim ininv.\n  intros iseq.\n  contradict a_neq.\n  auto.\n  intros isinl.\n  assert (ininv2 : (bl :: m) = b \\/ In b l).\n  apply in_inv.\n  auto.\n  elim ininv2.\n  intros iseq.\n  contradict b_neq.\n  auto.\n  intros isinl2.\n  apply pf.\n  auto.\n  auto.\n  auto.\n\n  rewrite -> H_bl.\n  rewrite -> H_bl.\n  reflexivity.\nDefined.\n", "meta": {"author": "dasuxullebt", "repo": "DampFnudeL", "sha": "6b0496d0ed5af23199bf0a03e04dbb9bb0373873", "save_path": "github-repos/coq/dasuxullebt-DampFnudeL", "path": "github-repos/coq/dasuxullebt-DampFnudeL/DampFnudeL-6b0496d0ed5af23199bf0a03e04dbb9bb0373873/KraftList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896737173119, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7231040319630441}}
{"text": "(* Zhiwei Wu, Wenrui Meng 1 hour for each *)\n(** * MoreInd: More on Induction *)\n\nRequire Export Logic. \n\n(* ##################################################### *)\n(** * Induction Principles *)\n\n(** This is a good point to pause and take a deeper look at induction\n    principles. \n\n    Every time we declare a new [Inductive] datatype, Coq\n    automatically generates an _induction principle_ for this type.\n\n    The induction principle for a type [t] is called [t_ind].  Here is\n    the one for natural numbers: *)\n\nCheck nat_ind.\n(*  ===> nat_ind : \n           forall P : nat -> Prop,\n              P 0  ->\n              (forall n : nat, P n -> P (S n))  ->\n              forall n : nat, P n  *)\n\n(** The [induction] tactic is a straightforward wrapper that, at\n    its core, simply performs [apply t_ind].  To see this more\n    clearly, let's experiment a little with using [apply nat_ind]\n    directly, instead of the [induction] tactic, to carry out some\n    proofs.  Here, for example, is an alternate proof of a theorem\n    that we saw in the [Basics] chapter. *)\n\nTheorem mult_0_r' : forall n:nat, \n  n * 0 = 0.\nProof.\n  apply nat_ind. \n  Case \"O\". reflexivity.\n  Case \"S\". simpl. intros n IHn. rewrite -> IHn. \n    reflexivity.  Qed.\n\n(** This proof is basically the same as the earlier one, but a\n    few minor differences are worth noting.  First, in the induction\n    step of the proof (the [\"S\"] case), we have to do a little\n    bookkeeping manually (the [intros]) that [induction] does\n    automatically.\n\n    Second, we do not introduce [n] into the context before applying\n    [nat_ind] -- the conclusion of [nat_ind] is a quantified formula,\n    and [apply] needs this conclusion to exactly match the shape of\n    the goal state, including the quantifier.  The [induction] tactic\n    works either with a variable in the context or a quantified\n    variable in the goal.\n\n    Third, the [apply] tactic automatically chooses variable names for\n    us (in the second subgoal, here), whereas [induction] lets us\n    specify (with the [as...]  clause) what names should be used.  The\n    automatic choice is actually a little unfortunate, since it\n    re-uses the name [n] for a variable that is different from the [n]\n    in the original theorem.  This is why the [Case] annotation is\n    just [S] -- if we tried to write it out in the more explicit form\n    that we've been using for most proofs, we'd have to write [n = S\n    n], which doesn't make a lot of sense!  All of these conveniences\n    make [induction] nicer to use in practice than applying induction\n    principles like [nat_ind] directly.  But it is important to\n    realize that, modulo this little bit of bookkeeping, applying\n    [nat_ind] is what we are really doing. *)\n\n(** **** Exercise: 2 stars, optional (plus_one_r') *)\n(** Complete this proof as we did [mult_0_r'] above, without using\n    the [induction] tactic. *)\n\nTheorem plus_one_r' : forall n:nat, \n  n + 1 = S n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The induction principles that Coq generates for other datatypes\n    defined with [Inductive] follow a similar pattern. If we define a\n    type [t] with constructors [c1] ... [cn], Coq generates a theorem\n    with this shape:\n    t_ind :\n       forall P : t -> Prop,\n            ... case for c1 ... ->\n            ... case for c2 ... ->\n            ...                \n            ... case for cn ... ->\n            forall n : t, P n\n    The specific shape of each case depends on the arguments to the\n    corresponding constructor.  Before trying to write down a general\n    rule, let's look at some more examples. First, an example where\n    the constructors take no arguments: *)\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind. \n(* ===> yesno_ind : forall P : yesno -> Prop, \n                      P yes  ->\n                      P no  ->\n                      forall y : yesno, P y *)\n\n(** **** Exercise: 1 star, optional (rgb) *)\n(** Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\nCheck rgb_ind.\n(** [] *)\n\n(** Here's another example, this time with one of the constructors\n    taking some arguments. *)\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n(* ===> (modulo a little tidying)\n   natlist_ind :\n      forall P : natlist -> Prop,\n         P nnil  ->\n         (forall (n : nat) (l : natlist), P l -> P (ncons n l)) ->\n         forall n : natlist, P n *)\n\n(** **** Exercise: 1 star, optional (natlist1) *)\n(** Suppose we had written the above definition a little\n   differently: *)\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\n\n(** Now what will the induction principle look like? *)\n(** [] *)\n\n(** From these examples, we can extract this general rule:\n\n    - The type declaration gives several constructors; each\n      corresponds to one clause of the induction principle.\n    - Each constructor [c] takes argument types [a1]...[an].\n    - Each [ai] can be either [t] (the datatype we are defining) or\n      some other type [s].\n    - The corresponding case of the induction principle\n      says (in English):\n        - \"for all values [x1]...[xn] of types [a1]...[an], if [P]\n           holds for each of the inductive arguments (each [xi] of\n           type [t]), then [P] holds for [c x1 ... xn]\". \n\n*)\n\n(** **** Exercise: 1 star, optional (False_ind_principle) *)\n(** Can you predict the induction principle for falsehood? *)\n\n(* Check False_ind. *)\n(** [] *)\n\n\n(** **** Exercise: 1 star, optional (byntree_ind) *)\n(** Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive byntree : Type :=\n | bempty : byntree  \n | bleaf  : yesno -> byntree\n | nbranch : yesno -> byntree -> byntree -> byntree.\n(** [] *)\n\n\n(** **** Exercise: 1 star, optional (ex_set) *)\n(** Here is an induction principle for an inductively defined\n    set.\n      ExSet_ind :\n         forall P : ExSet -> Prop,\n             (forall b : bool, P (con1 b)) ->\n             (forall (n : nat) (e : ExSet), P e -> P (con2 n e)) ->\n             forall e : ExSet, P e\n    Give an [Inductive] definition of [ExSet]: *)\n\nInductive ExSet : Type :=\n  (* FILL IN HERE *)\n.\n(** [] *)\n\n(** What about polymorphic datatypes?\n\n    The inductive definition of polymorphic lists\n      Inductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\n    is very similar to that of [natlist].  The main difference is\n    that, here, the whole definition is _parameterized_ on a set [X]:\n    that is, we are defining a _family_ of inductive types [list X],\n    one for each [X].  (Note that, wherever [list] appears in the body\n    of the declaration, it is always applied to the parameter [X].)\n    The induction principle is likewise parameterized on [X]:\n     list_ind :\n       forall (X : Type) (P : list X -> Prop),\n          P [] ->\n          (forall (x : X) (l : list X), P l -> P (x :: l)) ->\n          forall l : list X, P l\n   Note the wording here (and, accordingly, the form of [list_ind]):\n   The _whole_ induction principle is parameterized on [X].  That is,\n   [list_ind] can be thought of as a polymorphic function that, when\n   applied to a type [X], gives us back an induction principle\n   specialized to the type [list X]. *)\n\n(** **** Exercise: 1 star, optional (tree) *)\n(** Write out the induction principle that Coq will generate for\n   the following datatype.  Compare your answer with what Coq\n   prints. *)\n\nInductive tree (X:Type) : Type :=\n  | leaf : X -> tree X\n  | node : tree X -> tree X -> tree X.\nCheck tree_ind.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (mytype) *)\n(** Find an inductive definition that gives rise to the\n    following induction principle:\n      mytype_ind :\n        forall (X : Type) (P : mytype X -> Prop),\n            (forall x : X, P (constr1 X x)) ->\n            (forall n : nat, P (constr2 X n)) ->\n            (forall m : mytype X, P m -> \n               forall n : nat, P (constr3 X m n)) ->\n            forall m : mytype X, P m                   \n*) \n(** [] *)\n\n(** **** Exercise: 1 star, optional (foo) *)\n(** Find an inductive definition that gives rise to the\n    following induction principle:\n      foo_ind :\n        forall (X Y : Type) (P : foo X Y -> Prop),\n             (forall x : X, P (bar X Y x)) ->\n             (forall y : Y, P (baz X Y y)) ->\n             (forall f1 : nat -> foo X Y,\n               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n             forall f2 : foo X Y, P f2       \n*) \n(** [] *)\n\n(** **** Exercise: 1 star, optional (foo') *)\n(** Consider the following inductive definition: *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 : list X -> foo' X -> foo' X\n  | C2 : foo' X.\n\n(** What induction principle will Coq generate for [foo']?  Fill\n   in the blanks, then check your answer with Coq.)\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    _______________________ -> \n                    _______________________   ) ->\n             ___________________________________________ ->\n             forall f : foo' X, ________________________\n*)\n\n(** [] *)\n\n(* ##################################################### *)\n(** ** Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?\n\n    The induction principle for numbers\n       forall P : nat -> Prop,\n            P 0  ->\n            (forall n : nat, P n -> P (S n))  ->\n            forall n : nat, P n\n   is a generic statement that holds for all propositions\n   [P] (strictly speaking, for all families of propositions [P]\n   indexed by a number [n]).  Each time we use this principle, we\n   are choosing [P] to be a particular expression of type\n   [nat->Prop].\n\n   We can make the proof more explicit by giving this expression a\n   name.  For example, instead of stating the theorem [mult_0_r] as\n   \"[forall n, n * 0 = 0],\" we can write it as \"[forall n, P_m0r\n   n]\", where [P_m0r] is defined as... *)\n\nDefinition P_m0r (n:nat) : Prop := \n  n * 0 = 0.\n\n(** ... or equivalently... *)\n\nDefinition P_m0r' : nat->Prop := \n  fun n => n * 0 = 0.\n\n(** Now when we do the proof it is easier to see where [P_m0r]\n    appears. *)\n\nTheorem mult_0_r'' : forall n:nat, \n  P_m0r n.\nProof.\n  apply nat_ind.\n  Case \"n = O\". reflexivity.\n  Case \"n = S n'\". \n    (* Note the proof state at this point! *)\n    unfold P_m0r. simpl. intros n' IHn'. \n    apply IHn'.  Qed.\n\n(** This extra naming step isn't something that we'll do in\n    normal proofs, but it is useful to do it explicitly for an example\n    or two, because it allows us to see exactly what the induction\n    hypothesis is.  If we prove [forall n, P_m0r n] by induction on\n    [n] (using either [induction] or [apply nat_ind]), we see that the\n    first subgoal requires us to prove [P_m0r 0] (\"[P] holds for\n    zero\"), while the second subgoal requires us to prove [forall n',\n    P_m0r n' -> P_m0r n' (S n')] (that is \"[P] holds of [S n'] if it\n    holds of [n']\" or, more elegantly, \"[P] is preserved by [S]\").\n    The _induction hypothesis_ is the premise of this latter\n    implication -- the assumption that [P] holds of [n'], which we are\n    allowed to use in proving that [P] holds for [S n']. *)\n\n(* ####################################################### *)\n(** * Informal Proofs (Advanced) *)\n\n(** Q: What is the relation between a formal proof of a proposition\n       [P] and an informal proof of the same proposition [P]?\n\n    A: The latter should _teach_ the reader how to produce the\n       former.\n\n    Q: How much detail is needed??\n\n    Unfortunately, There is no single right answer; rather, there is a\n    range of choices.\n\n    At one end of the spectrum, we can essentially give the reader the\n    whole formal proof (i.e., the informal proof amounts to just\n    transcribing the formal one into words).  This gives the reader\n    the _ability_ to reproduce the formal one for themselves, but it\n    doesn't _teach_ them anything.\n\n   At the other end of the spectrum, we can say \"The theorem is true\n   and you can figure out why for yourself if you think about it hard\n   enough.\"  This is also not a good teaching strategy, because\n   usually writing the proof requires some deep insights into the\n   thing we're proving, and most readers will give up before they\n   rediscover all the same insights as we did.\n\n   In the middle is the golden mean -- a proof that includes all of\n   the essential insights (saving the reader the hard part of work\n   that we went through to find the proof in the first place) and\n   clear high-level suggestions for the more routine parts to save the\n   reader from spending too much time reconstructing these\n   parts (e.g., what the IH says and what must be shown in each case\n   of an inductive proof), but not so much detail that the main ideas\n   are obscured.\n\n   Another key point: if we're comparing a formal proof of a\n   proposition [P] and an informal proof of [P], the proposition [P]\n   doesn't change.  That is, formal and informal proofs are _talking\n   about the same world_ and they _must play by the same rules_. *)\n(** ** Informal Proofs by Induction *)\n\n(** Since we've spent much of this chapter looking \"under the hood\" at\n    formal proofs by induction, now is a good moment to talk a little\n    about _informal_ proofs by induction.\n\n    In the real world of mathematical communication, written proofs\n    range from extremely longwinded and pedantic to extremely brief\n    and telegraphic.  The ideal is somewhere in between, of course,\n    but while you are getting used to the style it is better to start\n    out at the pedantic end.  Also, during the learning phase, it is\n    probably helpful to have a clear standard to compare against.\n    With this in mind, we offer two templates below -- one for proofs\n    by induction over _data_ (i.e., where the thing we're doing\n    induction on lives in [Type]) and one for proofs by induction over\n    _evidence_ (i.e., where the inductively defined thing lives in\n    [Prop]).  In the rest of this course, please follow one of the two\n    for _all_ of your inductive proofs. *)\n\n(** *** Induction Over an Inductively Defined Set *)\n \n(** _Template_: \n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n \n    _Example_:\n \n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if length [[] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of index.\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n            length l = length (x::l') = S (length l'),\n          it suffices to show that \n            index (S (length l')) l' = None.\n]]  \n          But this follows directly from the induction hypothesis,\n          picking [n'] to be length [l'].  [] *)\n \n(** *** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_. \n\n    _Template_:\n \n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n \n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(** This section offers some additional details on how induction works\n    in Coq and the process of building proof trees.  It can safely be\n    skimmed on a first reading.  (We recommend skimming rather than\n    skipping over it outright: it answers some questions that occur to\n    many Coq users at some point, so it is useful to have a rough idea\n    of what's here.) *)\n\n(* ##################################################### *)\n(** * Induction Principles for [=] and [<=] *)\n\n\n(** In [Logic] we have defined [eq] as: *)\n\n(* Inductive eq (X:Type) : X -> X -> Prop :=\n       refl_equal : forall x, eq X x x. *)\n\n(** In the Coq standard library, the definition of equality is \n    slightly different: *)\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\n(** The advantage of this definition is that the induction\n    principle that Coq derives for it is precisely the familiar\n    principle of _Leibniz equality_: what we mean when we say \"[x] and\n    [y] are equal\" is that every property on [P] that is true of [x]\n    is also true of [y].  *)\n\nCheck eq'_ind.\n(* ===> \n     forall (X : Type) (x : X) (P : X -> Prop),\n       P x -> forall y : X, x =' y -> P y \n\n   ===>  (i.e., after a little reorganization)\n     forall (X : Type) (x : X) forall y : X, \n       x =' y -> \n       forall P : X -> Prop, P x -> P y *)\n\n\n(** Similarly, we have defined [<=] as: *)\n\n(* Inductive 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\n(** This definition can be streamlined a little by observing that the \n    left-hand argument [n] is the same everywhere in the definition, \n    so we can actually make it a \"general parameter\" to the whole \n    definition, rather than an argument to each constructor. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. \n    (The same was true of our second version of [eq].) *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(** By contrast, the induction principle that Coq calculates for the\n    first definition has a lot of extra quantifiers, which makes it\n    messier to work with when proving things by induction.  Here is\n    the induction principle for the first [le]: *)\n\n(* le_ind : \n     forall P : nat -> nat -> Prop,\n     (forall n : nat, P n n) ->\n     (forall n m : nat, le n m -> P n m -> P n (S m)) ->\n     forall n n0 : nat, le n n0 -> P n n0 *)\n\n(* ##################################################### *)\n(** ** Induction Principles in [Prop] *)\n\n(** Earlier, we looked in detail at the induction principles that Coq\n    generates for inductively defined _sets_.  The induction\n    principles for inductively defined _propositions_ like [gorgeous]\n    are a tiny bit more complicated.  As with all induction\n    principles, we want to use the induction principle on [gorgeous]\n    to prove things by inductively considering the possible shapes\n    that something in [gorgeous] can have -- either it is evidence\n    that [0] is gorgeous, or it is evidence that, for some [n], [3+n]\n    is gorgeous, or it is evidence that, for some [n], [5+n] is\n    gorgeous and it includes evidence that [n] itself is.  Intuitively\n    speaking, however, what we want to prove are not statements about\n    _evidence_ but statements about _numbers_.  So we want an\n    induction principle that lets us prove properties of numbers by\n    induction on evidence.\n\n    For example, from what we've said so far, you might expect the\n    inductive definition of [gorgeous]...\n    Inductive gorgeous : nat -> Prop :=\n         g_0 : gorgeous 0\n       | g_plus3 : forall n, gorgeous n -> gorgeous (3+m)\n       | g_plus5 : forall n, gorgeous n -> gorgeous (5+m).\n    ...to give rise to an induction principle that looks like this...\n    gorgeous_ind_max :\n       forall P : (forall n : nat, gorgeous n -> Prop),\n            P O g_0 ->\n            (forall (m : nat) (e : gorgeous m), \n               P m e -> P (3+m) (g_plus3 m e) ->\n            (forall (m : nat) (e : gorgeous m), \n               P m e -> P (5+m) (g_plus5 m e) ->\n            forall (n : nat) (e : gorgeous n), P n e\n    ... because:\n\n     - Since [gorgeous] is indexed by a number [n] (every [gorgeous]\n       object [e] is a piece of evidence that some particular number\n       [n] is gorgeous), the proposition [P] is parameterized by both\n       [n] and [e] -- that is, the induction principle can be used to\n       prove assertions involving both a gorgeous number and the\n       evidence that it is gorgeous.\n\n     - Since there are three ways of giving evidence of gorgeousness\n       ([gorgeous] has three constructors), applying the induction\n       principle generates three subgoals:\n\n         - We must prove that [P] holds for [O] and [b_0].\n\n         - We must prove that, whenever [n] is a gorgeous\n           number and [e] is an evidence of its gorgeousness,\n           if [P] holds of [n] and [e],\n           then it also holds of [3+m] and [g_plus3 n e].\n\n         - We must prove that, whenever [n] is a gorgeous\n           number and [e] is an evidence of its gorgeousness,\n           if [P] holds of [n] and [e],\n           then it also holds of [5+m] and [g_plus5 n e].\n\n     - If these subgoals can be proved, then the induction principle\n       tells us that [P] is true for _all_ gorgeous numbers [n] and\n       evidence [e] of their gorgeousness.\n\n    But this is a little more flexibility than we actually need or\n    want: it is giving us a way to prove logical assertions where the\n    assertion involves properties of some piece of _evidence_ of\n    gorgeousness, while all we really care about is proving\n    properties of _numbers_ that are gorgeous -- we are interested in\n    assertions about numbers, not about evidence.  It would therefore\n    be more convenient to have an induction principle for proving\n    propositions [P] that are parameterized just by [n] and whose\n    conclusion establishes [P] for all gorgeous numbers [n]:\n       forall P : nat -> Prop,\n          ... ->\n             forall n : nat, gorgeous n -> P n\n    For this reason, Coq actually generates the following simplified\n    induction principle for [gorgeous]: *)\n\nCheck gorgeous_ind.\n(* ===>  gorgeous_ind\n     : forall P : nat -> Prop,\n       P 0 ->\n       (forall n : nat, gorgeous n -> P n -> P (3 + n)) ->\n       (forall n : nat, gorgeous n -> P n -> P (5 + n)) ->\n       forall n : nat, gorgeous n -> P n *)\n\n(** In particular, Coq has dropped the evidence term [e] as a\n    parameter of the the proposition [P], and consequently has\n    rewritten the assumption [forall (n : nat) (e: gorgeous n), ...]\n    to be [forall (n : nat), gorgeous n -> ...]; i.e., we no longer\n    require explicit evidence of the provability of [gorgeous n]. *)\n\n(** In English, [gorgeous_ind] says:\n\n    - Suppose, [P] is a property of natural numbers (that is, [P n] is\n      a [Prop] for every [n]).  To show that [P n] holds whenever [n]\n      is gorgeous, it suffices to show:\n  \n      - [P] holds for [0],\n  \n      - for any [n], if [n] is gorgeous and [P] holds for\n        [n], then [P] holds for [3+n],\n\n      - for any [n], if [n] is gorgeous and [P] holds for\n        [n], then [P] holds for [5+n]. *)\n\n(** We can apply [gorgeous_ind] directly instead of using [induction]. *)\n\nTheorem gorgeous__beautiful' : forall n, gorgeous n -> beautiful n.\nProof.\n   intros.\n   apply gorgeous_ind.\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\".\n       intros.\n       apply b_sum. apply b_3.\n       apply H1.\n   Case \"g_plus5\".\n       intros.\n       apply b_sum. apply b_5.\n       apply H1.\n   apply H.\nQed.\n\nModule P.\n\n(** **** Exercise: 3 stars, optional (p_provability) *)\n(** Consider the following inductively defined proposition: *)\n\nInductive p : (tree nat) -> nat -> Prop :=\n   | c1 : forall n, p (leaf _ n) 1\n   | c2 : forall t1 t2 n1 n2,\n            p t1 n1 -> p t2 n2 -> p (node _ t1 t2) (n1 + n2)\n   | c3 : forall t n, p t n -> p t (S n).\n\n(** Describe, in English, the conditions under which the\n   proposition [p t n] is provable. \n\n   (* FILL IN HERE *)\n*)\n(** [] *)\n\nEnd P.\n\n(* ##################################################### *)\n(** ** More on the [induction] Tactic *)\n\n(** The [induction] tactic actually does even more low-level\n    bookkeeping for us than we discussed above.\n\n    Recall the informal statement of the induction principle for\n    natural numbers:\n      - If [P n] is some proposition involving a natural number n, and\n        we want to show that P holds for _all_ numbers n, we can\n        reason like this:\n          - show that [P O] holds\n          - show that, if [P n'] holds, then so does [P (S n')]\n          - conclude that [P n] holds for all n.\n    So, when we begin a proof with [intros n] and then [induction n],\n    we are first telling Coq to consider a _particular_ [n] (by\n    introducing it into the context) and then telling it to prove\n    something about _all_ numbers (by using induction).\n\n    What Coq actually does in this situation, internally, is to\n    \"re-generalize\" the variable we perform induction on.  For\n    example, in the proof above that [plus] is associative...\n*)\n\nTheorem plus_assoc' : forall n m p : nat, \n  n + (m + p) = (n + m) + p.   \nProof.\n  (* ...we first introduce all 3 variables into the context,\n     which amounts to saying \"Consider an arbitrary [n], [m], and\n     [p]...\" *)\n  intros n m p. \n  (* ...We now use the [induction] tactic to prove [P n] (that\n     is, [n + (m + p) = (n + m) + p]) for _all_ [n],\n     and hence also for the particular [n] that is in the context\n     at the moment. *)\n  induction n as [| n'].\n  Case \"n = O\". reflexivity.\n  Case \"n = S n'\". \n    (* In the second subgoal generated by [induction] -- the\n       \"inductive step\" -- we must prove that [P n'] implies \n       [P (S n')] for all [n'].  The [induction] tactic \n       automatically introduces [n'] and [P n'] into the context\n       for us, leaving just [P (S n')] as the goal. *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** It also works to apply [induction] to a variable that is\n   quantified in the goal. *)\n\nTheorem plus_comm' : forall n m : nat, \n  n + m = m + n.\nProof.\n  induction n as [| n']. \n  Case \"n = O\". intros m. rewrite -> plus_0_r. reflexivity.\n  Case \"n = S n'\". intros m. simpl. rewrite -> IHn'. \n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** Note that [induction n] leaves [m] still bound in the goal --\n    i.e., what we are proving inductively is a statement beginning\n    with [forall m].\n\n    If we do [induction] on a variable that is quantified in the goal\n    _after_ some other quantifiers, the [induction] tactic will\n    automatically introduce the variables bound by these quantifiers\n    into the context. *)\n\nTheorem plus_comm'' : forall n m : nat, \n  n + m = m + n.\nProof.\n  (* Let's do induction on [m] this time, instead of [n]... *)\n  induction m as [| m']. \n  Case \"m = O\". simpl. rewrite -> plus_0_r. reflexivity.\n  Case \"m = S m'\". simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, optional (plus_explicit_prop) *)\n(** Rewrite both [plus_assoc'] and [plus_comm'] and their proofs in\n    the same style as [mult_0_r''] above -- that is, for each theorem,\n    give an explicit [Definition] of the proposition being proved by\n    induction, and state the theorem and proof in terms of this\n    defined proposition.  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(* ##################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 2 stars, optional (foo_ind_principle) *)\n(** Suppose we make the following inductive definition:\n   Inductive foo (X : Set) (Y : Set) : Set :=\n     | foo1 : X -> foo X Y\n     | foo2 : Y -> foo X Y\n     | foo3 : foo X Y -> foo X Y.\n   Fill in the blanks to complete the induction principle that will be\n   generated by Coq. \n   foo_ind\n        : forall (X Y : Set) (P : foo X Y -> Prop),   \n          (forall x : X, __________________________________) ->\n          (forall y : Y, __________________________________) ->\n          (________________________________________________) ->\n           ________________________________________________\n\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (bar_ind_principle) *)\n(** Consider the following induction principle:\n   bar_ind\n        : forall P : bar -> Prop,\n          (forall n : nat, P (bar1 n)) ->\n          (forall b : bar, P b -> P (bar2 b)) ->\n          (forall (b : bool) (b0 : bar), P b0 -> P (bar3 b b0)) ->\n          forall b : bar, P b\n   Write out the corresponding inductive set definition.\n   Inductive bar : Set :=\n     | bar1 : ________________________________________\n     | bar2 : ________________________________________\n     | bar3 : ________________________________________.\n\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (no_longer_than_ind) *)\n(** Given the following inductively defined proposition:\n  Inductive no_longer_than (X : Set) : (list X) -> nat -> Prop :=\n    | nlt_nil  : forall n, no_longer_than X [] n\n    | nlt_cons : forall x l n, no_longer_than X l n -> \n                               no_longer_than X (x::l) (S n)\n    | nlt_succ : forall l n, no_longer_than X l n -> \n                             no_longer_than X l (S n).\n  write the induction principle generated by Coq.\n  no_longer_than_ind\n       : forall (X : Set) (P : list X -> nat -> Prop),\n         (forall n : nat, ____________________) ->\n         (forall (x : X) (l : list X) (n : nat),\n          no_longer_than X l n -> ____________________ -> \n                                  _____________________________ ->\n         (forall (l : list X) (n : nat),\n          no_longer_than X l n -> ____________________ -> \n                                  _____________________________ ->\n         forall (l : list X) (n : nat), no_longer_than X l n -> \n           ____________________\n\n*)\n(** [] *)\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(* ################################################### *)\n(** ** Induction Principles for [/\\] and [\\/] *)\n\n(** The induction principles for conjunction and disjunction are a\n    good illustration of Coq's way of generating simplified induction\n    principles for [Inductive]ly defined propositions, which we\n    discussed in the last chapter.  You try first: *)\n\n(** **** Exercise: 1 star, optional (and_ind_principle) *)\n(** See if you can predict the induction principle for conjunction. *)\n\n(* Check and_ind. *)\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_ind_principle) *)\n(** See if you can predict the induction principle for disjunction. *)\n\n(* Check or_ind. *)\n(** [] *)\n\nCheck and_ind.\n\n(** From the inductive definition of the proposition [and P Q]\n     Inductive and (P Q : Prop) : Prop :=\n       conj : P -> Q -> (and P Q).\n    we might expect Coq to generate this induction principle\n     and_ind_max :\n       forall (P Q : Prop) (P0 : P /\\ Q -> Prop),\n            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->\n            forall a : P /\\ Q, P0 a\n    but actually it generates this simpler and more useful one:\n     and_ind :\n       forall P Q P0 : Prop,\n            (P -> Q -> P0) ->\n            P /\\ Q -> P0\n    In the same way, when given the inductive definition of [or P Q]\n     Inductive or (P Q : Prop) : Prop :=\n       | or_introl : P -> or P Q\n       | or_intror : Q -> or P Q.\n    instead of the \"maximal induction principle\"\n     or_ind_max :\n       forall (P Q : Prop) (P0 : P \\/ Q -> Prop),\n            (forall a : P, P0 (or_introl P Q a)) ->\n            (forall b : Q, P0 (or_intror P Q b)) ->\n            forall o : P \\/ Q, P0 o\n    what Coq actually generates is this:\n     or_ind :\n       forall P Q P0 : Prop,\n            (P -> P0) ->\n            (Q -> P0) ->\n            P \\/ Q -> P0\n]] \n*)\n\n(* ######################################################### *)\n(** ** Explicit Proof Objects for Induction *)\n\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n    \n(** Recall the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\n(* Check nat_ind. *)\n(* ===> \n   nat_ind : forall P : nat -> Prop,\n      P 0%nat -> \n      (forall n : nat, P n -> P (S n)) -> \n      forall n : nat, P n  *)\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n \nPrint nat_ind.  \n(* ===> (after some manual tidying)\n   nat_ind =\n    fun (P : nat -> Type) \n        (f : P 0) \n        (f0 : forall n : nat, P n -> P (S n)) =>\n          fix F (n : nat) : P n :=\n             match n as n0 return (P n0) with\n            | 0 => f\n            | S n0 => f0 n0 (F n0)\n            end.\n*)\n\n(** We can read this as follows: \n     Suppose we have evidence [f] that [P] holds on 0,  and \n     evidence [f0] that [forall n:nat, P n -> P (S n)].  \n     Then we can prove that [P] holds of an arbitrary nat [n] via \n     a recursive function [F] (here defined using the expression \n     form [Fix] rather than by a top-level [Fixpoint] \n     declaration).  [F] pattern matches on [n]: \n      - If it finds 0, [F] uses [f] to show that [P n] holds.\n      - If it finds [S n0], [F] applies itself recursively on [n0] \n         to obtain evidence that [P n0] holds; then it applies [f0] \n         on that evidence to show that [P (S n)] holds. \n    [F] is just an ordinary recursive function that happens to \n    operate on evidence in [Prop] rather than on terms in [Set].\n \n    Aside to those interested in functional programming: You may\n    notice that the [match] in [F] requires an annotation [as n0\n    return (P n0)] to help Coq's typechecker realize that the two arms\n    of the [match] actually return the same type (namely [P n]).  This\n    is essentially like matching over a GADT (generalized algebraic\n    datatype) in Haskell.  In fact, [F] has a _dependent_ type: its\n    result type depends on its argument; GADT's can be used to\n    describe simple dependent types like this.\n \n    We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  Recall our desire to\n    prove that\n\n    [forall n : nat, even n -> ev n].\n \n    Attempts to do this by standard induction on [n] fail, because the\n    induction principle only lets us proceed when we can prove that\n    [even n -> even (S n)] -- which is of course never provable.  What\n    we did earlier in this chapter was a bit of a hack:\n \n    [Theorem even__ev : forall n : nat,\n     (even n -> ev n) /\\ (even (S n) -> ev (S n))].\n \n    We can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n \n *)\n \n Definition nat_ind2 : \n    forall (P : nat -> Prop), \n    P 0 -> \n    P 1 -> \n    (forall n : nat, P n -> P (S(S n))) -> \n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS => \n          fix f (n:nat) := match n return P n with \n                             0 => P0 \n                           | 1 => P1 \n                           | S (S n') => PSS n' (f n') \n                          end.\n \n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive (try\n     it!).\n\n     The [induction ... using] tactic gives a convenient way to\n     specify a non-standard induction principle like this. *)\n \nLemma even__ev' : forall n, even n -> ev n.\nProof. \n intros.  \n induction n as [ | |n'] using nat_ind2. \n  Case \"even 0\". \n    apply ev_0.  \n  Case \"even 1\". \n    inversion H.\n  Case \"even (S(S n'))\". \n    apply ev_SS. \n    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H. \nQed. \n\n(* ######################################################### *)\n(** ** The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is \"why\n    trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on.\n\n    There are a few additional wrinkles:\n\n    - Since Coq types can themselves be expressions, the checker must\n      normalize these (by using the conversion rules) before\n      comparing them.\n\n    - The checker must make sure that [match] expressions are\n      _exhaustive_.  That is, there must be an arm for every possible\n      constructor.  To see why, consider the following alleged proof\n      object:\n      Definition or_bogus : forall P Q, P \\/ Q -> P :=\n        fun (P Q : Prop) (A : P \\/ Q) =>\n           match A with\n           | or_introl H => H\n           end. \n      All the types here match correctly, but the [match] only\n      considers one of the possible constructors for [or].  Coq's\n      exhaustiveness check will reject this definition.\n\n    - The checker must make sure that each [fix] expression\n      terminates.  It does this using a syntactic check to make sure\n      that each recursive call is on a subexpression of the original\n      argument.  To see why this is essential, consider this alleged\n      proof:\n          Definition nat_false : forall (n:nat), False :=\n             fix f (n:nat) : False := f n. \n      Again, this is perfectly well-typed, but (fortunately) Coq will\n      reject it. *)\n\n(** Note that the soundness of Coq depends only on the correctness of\n    this typechecking engine, not on the tactic machinery.  If there\n    is a bug in a tactic implementation (and this certainly does\n    happen!), that tactic might construct an invalid proof term.  But\n    when you type [Qed], Coq checks the term for validity from\n    scratch.  Only lemmas whose proofs pass the type-checker can be\n    used in further proof developments.  *)\n\n(* $Date: 2013-02-06 20:55:20 -0500 (Wed, 06 Feb 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/For_wenrui/MoreInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.8947894745194283, "lm_q1q2_score": 0.7230500415271327}}
{"text": "(** Ordering functions (after Schutte) *)\n\n\n(**   Pierre Casteran, LaBRI, University of Bordeaux  \n\nEvery subset [A] of [Ord] can be enumerated in an unique way \n by a segment of [Ord].\n\nThus it makes sense to consider the [alpha]-th element of [A] \n\nThis module shows the construction of the _ordering function_  of [A], following\nSchutte's definitions.\n\n*)\n\n\nFrom hydras Require Export Schutte_basics.\nImport Ensembles  Well_Orders  Countable  PartialFun.\nImport Classical  MoreEpsilonIota  Epsilon.\n\nSet Implicit Arguments.\n\n\n\n (** ** Main definitions *)\n\n(* begin snippet segmentDef *)\n\nDefinition segment (A: Ensemble Ord) :=\n  forall alpha beta, In A alpha -> beta < alpha -> In A  beta.\n\nDefinition proper_segment (A: Ensemble Ord) :=\n  segment A /\\  ~ Same_set A ordinal.\n\n(* end snippet segmentDef *)\n\n(* begin snippet orderingFunctionDef *)\n\nClass ordering_function (f : Ord -> Ord)\n           (A B : Ensemble Ord) : Prop :=\n  Build_OF {\n      OF_segment : segment A;\n      OF_total : forall a, In A a -> In B (f a);\n      OF_onto : forall b, In B b -> exists a, In A a /\\ f a = b;\n      OF_mono : forall a b, In A a -> In A b -> a < b -> f a < f b\n    }. \n\nDefinition ordering_segment (A B : Ensemble Ord) :=\n  exists f : Ord -> Ord, ordering_function f A B.\n\n(* end snippet orderingFunctionDef *)\n\n(* begin snippet ordDef *)\n\nDefinition the_ordering_segment (B : Ensemble Ord) :=\n  the  (fun x => ordering_segment x B).\n\nDefinition ord   (B : Ensemble Ord) := \n  some (fun f => ordering_function f (the_ordering_segment B) B).\n(* end snippet ordDef *)\n\nDefinition proper_segment_of (B : Ensemble Ord)(beta : Ord): Ensemble Ord  :=\n  fun alpha => In B alpha /\\ alpha < beta /\\ In B beta.\n\nDefinition  normal (f : Ord -> Ord)(B : Ensemble Ord): Prop :=\n ordering_function f ordinal B /\\ continuous f ordinal B.\n\nDefinition fun_equiv (f g : Ord -> Ord)(A B : Ensemble Ord) :=\n  Same_set A B /\\ forall a, In A a -> f a = g a. \n\n(**  **  Properties of  segments *)\n\nLemma ordinal_segment : segment ordinal.\nProof.\n split; eauto with schutte. \nQed.\n\n\nLemma members_proper (alpha : Ord) :\n  proper_segment (members alpha).\nProof with eauto with schutte.\n  split.\n -  intros a b H H0; apply lt_trans with a ...\n -  intros [H0 H1]; destruct (@le_not_gt alpha (succ alpha)) ...\n   + apply  (H1 (succ alpha)) ...\nQed.\n\n\nLemma proper_members (A: Ensemble Ord) (H :  proper_segment A) :\n   exists a: Ord,  Same_set A (members a).\nProof with eauto with schutte.\n  case (not_all_not_ex _ (fun b => ordinal b /\\ ~ A b)).\n  - intro H1;  apply H;split.\n    +  unfold Included; split; auto.\n    +  intros x H2; apply NNPP; intro H3.\n       apply (H1 x); split;auto.\n  -  intros x H1; case (@well_order _  lt AX1 (fun x => ordinal x /\\ ~ A x) x). \n     + auto.\n     +  intros y Hy.\n        case Hy;intros H2 H3; destruct H2.\n        exists y;split...\n        * intros a H6; tricho a y T ...\n          case H;auto.\n          subst a; contradiction.\n          red in Hy.\n          destruct Hy.\n          destruct H.\n          red in H.\n          specialize (H a y H6 T).\n          contradiction.\n        *  red; unfold In;intros; apply NNPP.\n          case Hy;  intros H7 H8 H10.  \n          case (H8 x0 ).\n          { red; split ... }\n          { intro; subst. destruct (lt_irrefl H4). }\n          intro; case (@lt_irrefl x0); apply lt_trans with y ...\nQed.\n\n\nLemma countable_segment_proper : forall A : Ensemble Ord,\n           segment A -> countable A -> proper_segment A.\nProof.\n intros A H H0; split;[auto|idtac].\n intro H1; generalize (Extensionality_Ensembles _ _ _ H1).\n intros; subst A ; now case Non_denum.\nQed.\n\n\nLemma ordering_function_In f A B a :\n   ordering_function f A B -> In A a -> In B (f a).\nProof. destruct 1; auto. Qed.\n\n  \nLemma ordering_function_mono (f : Ord -> Ord) (A B: Ensemble Ord) :\n  ordering_function f A B ->\n  forall alpha beta,\n    In A alpha -> In A beta -> alpha < beta -> f alpha < f beta.\nProof.  now destruct 1. Qed.\n\n#[global] Hint Resolve ordering_function_mono : schutte.\n\nLemma  ordering_function_mono_weak (f : Ord -> Ord) (A B: Ensemble Ord) : \n ordering_function f A B ->\n   forall a b, In A a -> In A b -> a <= b -> f a <= f b.\nProof.\n destruct 1 as [H H0 H1 H2].\n destruct 3.\n -  subst b; left; auto with schutte.\n -  right;auto.\nQed.\n\n#[global] Hint Resolve ordering_function_mono_weak : schutte.\n\nLemma ordering_function_monoR : forall f A B, ordering_function f A B ->\n   forall a b, In A a -> In A b -> f a < f b -> a < b.\nProof.\n  destruct 1 as [H H0 H1 H2];\n    intros a b H3 H4 H5; tricho a b Ht; auto.\n  - subst b; now destruct (@lt_irrefl (f a)).\n  - destruct (@lt_irrefl (f a)); apply lt_trans with (f b); auto.\nQed.\n\n#[global] Hint Resolve ordering_function_monoR : schutte.\n\n\nLemma Ordering_bijection : forall f A B, ordering_function f A B ->\n                                         fun_bijection A B f.\nProof.\n  destruct 1 as [H H0 H1 H2].\n  split;red;auto; intros.\n  tricho a a' H7; trivial.\n  -  specialize  (H2 _ _ H3 H4 H7); rewrite H5 in H2;\n     destruct (lt_irrefl H2).\n  - specialize  (H2 _ _ H4 H3 H7);  rewrite H5 in H2;\n    destruct (lt_irrefl H2).\nQed.\n\n\nLemma  ordering_function_mono_weakR : \n  forall f A B, ordering_function f A B ->\n                forall a b, In A a -> In A b ->  f a <= f b -> a <= b.\nProof with auto with schutte.\n  intros f A B H a b H0 H1 H2.\n  case H; intros H3 H4 H5 H6.\n  destruct H2 as [H2 | H2].\n  case (Ordering_bijection H).\n  intros H10 H11 H12 ; specialize (H12 a b H0 H1 )...\n  -  right; eapply ordering_function_monoR; eauto.\nQed.\n\n#[global] Hint Resolve ordering_function_mono_weakR : schutte.\n\n\nLemma ordering_function_seg : forall A B, ordering_segment A B ->\n                                          segment A.\nProof. now destruct 1 as [f [H _]]. Qed.\n\nLemma empty_ordering : forall B, (forall b, ~ B b) ->\n                                 ordering_function (fun o => o)\n                                                   (members zero)\n                                                   B.\nProof.\n  intros B H; split.\n  -  intros a b H0 H1;  destruct (not_lt_zero H0);auto.\n  - intros b H0 ; now destruct (not_lt_zero H0).\n  -  intros x Hx; now destruct (H x). \n  -  intros a b Hb; case (@not_lt_zero a); assumption. \nQed.\n\n\nLemma segment_lt : forall A a b, segment A -> A a -> b < a -> A b.\nProof.\n intros A a b H0  H1 H2; now apply H0 with a.\nQed.\n\nTheorem segment_unbounded : forall A:Ensemble Ord, segment A -> \n                                        Unbounded A ->\n                                        A = ordinal.\nProof with eauto with schutte.\n intros A H H0; red in H0; apply Extensionality_Ensembles; split.\n - intros; split. \n -  intros x Hx; destruct (H0 x) as [x0 H1]...\n    destruct H1; now apply H with x0. \nQed.\n\n(* begin snippet orderingLe *)\n\n(*  Theorem 13.3 of Schutte's book *)\n\nTheorem ordering_le : forall f A B,\n    ordering_function f A B ->\n    forall alpha, In A alpha -> alpha <= f alpha. (* .no-out *)\n(*| .. coq:: none |*)\nProof with auto with schutte.\n  intros f A B H alpha H0; generalize H0;\n    pattern alpha; apply transfinite_induction.\n  - clear alpha H0; destruct H as [H1 H2 H3 H4].  \n    unfold progressive;   intros alpha H6 H7 .\n    tricho alpha (f alpha) H' ...\n    +   assert (f (f alpha) < f alpha).\n      {    apply H4.\n           - eapply segment_lt;eauto with schutte.\n           - unfold In;auto.\n           - unfold In;auto.\n      }\n      case (le_not_gt (a:= f alpha)(b:=f (f alpha)));auto.\n      apply H6;  eauto with schutte.\nQed.\n(*||*)\n(* end snippet orderingLe *)\n\n(* begin hide *)  \nSection ordering_function_unicity_1.\n  \n Variables B A1 A2 : Ensemble Ord.\n Variables f1 f2 : Ord -> Ord.\n Hypothesis O1 : ordering_function f1 A1 B.\n Hypothesis O2 : ordering_function f2 A2 B.\n\n \n Remark SA1 : segment A1.\n Proof.   case O1;intuition.  Qed.\n\n Remark SA2 : segment A2.\n Proof.  case O2;intuition.  Qed.\n \n #[local] Hint Resolve SA2 SA1 : schutte.\n\n  Lemma A1_A2 :forall a, In A1 a -> A2 a /\\ f1 a = f2 a.\n Proof with eauto with schutte.\n   intros a Ha;  generalize Ha;pattern a; apply transfinite_induction.\n   {\n     clear a Ha ; intros a  H0 Ha ;   assert (A2 a).\n     {\n       assert (forall khi, khi < a -> A2 khi /\\ f1 khi = f2 khi).\n       {  intros;  apply H0...\n       }\n       apply NNPP; intro H2.\n       assert (forall y, A2 y -> y < a).\n       { intros y H3;  tricho y a H4 ...\n         subst y; now case H2.\n         destruct H2;  apply segment_lt with y;auto with schutte.\n       }\n\n       assert (forall y, A2 y -> f1 y < f1 a).\n       {   intros y H4;  case O1;intros H5 H6 H7 H8.  \n           apply H8 ... \n       }  \n\n       case O2;intros H5 H6 H7 H8;  case (H7 (f1 a)).\n       - case O1;intros H9 H10 H11 H12. \n         apply H10;  auto.\n       -  destruct 1.   generalize (H3 x H4).\n          intro;  case (H0 x)...\n           + intros H13 H14. specialize (H6 _ H4).   rewrite <- H9 in H10.\n            rewrite H14 in H10.\n            case (@lt_irrefl (f2 x));auto.\n     }\n     {   split; trivial.\n         assert (H01 : least_member  lt\n                                        (fun x => B x /\\ \n                                                  forall y, y < a ->\n                                                            f1 y <> x)\n                                        (f1 a)).\n\n         {  split.\n            +  case O1;intros;  unfold In; intuition.\n               apply OF_total0; auto.\n               specialize (OF_mono0  y a ).\n               assert (In A1 y) by (eapply OF_segment0 with a ; auto). \n               specialize (OF_mono0 H3  Ha H1).\n               rewrite H2 in OF_mono0; now apply (@lt_irrefl (f1 a)).\n            + destruct 1;   destruct O1 as [H3 H4 H5 H6].\n              destruct (H5 x H1).\n              destruct H7; subst x;  tricho a x0 H9.\n              *  right.   apply H6;auto.\n              *  subst x0; now left.\n              * now destruct  (H2  _ H9). \n         } \n\n         assert (H02 : least_member  lt\n                                     (fun x => B x /\\ forall y, y < a ->\n                                                                f2 y <> x)\n                                     (f2 a)).\n         {\n           split.\n           +  case O2;intros  H2 H3 H4 H5.   unfold In; intuition.\n              apply H3; auto.\n              specialize (H5 y a ).\n              assert (In A2 y)  by ( eapply H2 with a ; auto). \n              specialize (H5 H7 H H1).\n              rewrite H6 in H5; now apply (@lt_irrefl (f2 a)).\n           + destruct 1; case O2; intros  H3 H4 H5 H6.  \n            destruct (H5 x H1).\n             destruct H7; subst x; tricho a x0 H9.\n             *  right;   apply H6;auto.\n             *  subst x0; now left.\n             * specialize (H2 _ H9); now destruct H2.\n         } \n         refine (least_member_of_eq AX1 _ _ H01 H02).\n\n         - intros x Hx; split.\n           + red in Hx; tauto.\n           + intros y H1; destruct (H0 _ H1).\n             * case O1; intros  H2 H3 H4 H5.    apply H2 with a; auto.\n             * rewrite <- H3;  destruct Hx;  auto.\n         - intros x Hx;  split.\n           + red in Hx; tauto.\n           + intros y H1;   destruct (H0 _ H1).\n             case O1;intros H2 H3 H4 H5.   apply H2 with a; auto.\n             rewrite  H3;    destruct Hx;  auto.\n     }\n   }\n Qed.\n\nEnd ordering_function_unicity_1.\n\n(* end hide *)\n \n\nSection ordering_function_unicity.\n  \n Variables B A1 A2 : Ensemble Ord.\n\n Variables f1 f2 : Ord -> Ord.\n Hypothesis O1 : ordering_function f1 A1 B.\n Hypothesis O2 : ordering_function f2 A2 B.\n\n (* begin hide *)\n \n Lemma A2_A1 :forall a, A2 a -> A1 a /\\ f2 a = f1 a.\n Proof.\n  intros; eapply A1_A2.   \n  - eapply O2.\n  - apply O1.\n  - auto.\n Qed.\n\n (* end hide *)\n \nTheorem ordering_function_unicity  : fun_equiv f1 f2 A1 A2.\nProof.\n split.\n - split.\n   +  intros x Hx; case (A1_A2 O1 O2 _ Hx);auto.\n   +  intros x Hx; destruct (A2_A1 Hx);auto.\n -  intros a Ha; destruct (A1_A2 O1 O2 a Ha);auto.\nQed.\n\nEnd ordering_function_unicity.\n\nLemma ordering_function_seg_unicity : forall A1 A2 B, \n           ordering_segment A1 B ->\n           ordering_segment A2 B -> A1 = A2.\nProof.\n destruct 1 as [f1 Hf1];  destruct 1 as [f2 Hf2]; \n apply Extensionality_Ensembles.\n assert (H : fun_equiv f1 f2 A1 A2)\n   by (eapply ordering_function_unicity;eauto); now destruct H.\nQed.\n\n\n\n(** Let us build now an ordering function, and the associated ordering segment\n of any subset B composed of ordinals *)\n    \n\nLemma proper_of_proper : forall B beta beta',\n                           ordinal beta -> In B beta ->\n                           In (proper_segment_of B beta) beta' ->\n                           proper_segment_of B beta' =\n                           proper_segment_of (proper_segment_of B beta) beta'.\nProof with  eauto with schutte.\n intros; apply Extensionality_Ensembles; split.\n - red; destruct 1; split. \n   + split;auto.\n     destruct H3; split.\n     * apply lt_trans with beta'...\n       case H1;tauto.\n     * auto.\n   + decompose [and] H3;  split;auto.\n - red; destruct 1;auto.\n   split.\n   +  case H2;auto.\n   +  split.\n    * tauto.  \n    * destruct  H3, H4 ...\nQed.\n\nSection building_ordering_function_1.\n Variable B : Ensemble Ord.\n\n Hypothesis H_B : forall beta, In B beta ->\n                               exists! A : Ensemble Ord,\n                                    ordering_segment A\n                                             (proper_segment_of B beta).\n  \n Section beta_fixed.\n\n Variable beta : Ord.\n Hypothesis beta_B : In B beta.\n\n (** Let us build an ordering function for (proper_segment_of B beta) *)\n  \n Definition _A := the  (fun E =>\n                          ordering_segment E  (proper_segment_of B beta)).\n \n \n Definition _f := some  (fun f => \n                           ordering_function f _A\n\t\t\t                     (proper_segment_of B beta)).\n\n\n Lemma of_beta' : ordering_function _f _A (proper_segment_of B beta).\n Proof.\n   pattern _f; unfold _f; apply epsilon_spec;\n     destruct (H_B  beta_B) as [x [H1 H2]].\n   case H1; intros x0 H;  exists x0;auto.\n   unfold _A; apply iota_ind.\n   - exists x; split; auto.\n   - intros a H0;  destruct H0;  replace a with x; auto.\n Qed.\n\n\n\n Remark Bbeta_denum : countable (proper_segment_of B beta).\n Proof.\n  apply AX2; exists beta;  destruct 1;tauto.\n Qed.\n\n #[local] Hint Resolve of_beta': schutte.\n\nRemark A_denum : countable _A.\nProof.\n eapply countable_bij_funR.\n - eapply Ordering_bijection;   eauto with schutte.\n - apply Bbeta_denum;eauto.\nQed.\n\nLemma Proper_A : proper_segment _A.\nProof.\n apply countable_segment_proper.\n - eapply SA1; eauto with schutte.\n - eapply A_denum.\nQed.\n\nLemma g_def1  : exists g_beta: Ord,  ordinal g_beta /\\ _A = members g_beta.\nProof.\n generalize (proper_members Proper_A); intros (a,Ha);exists a;split.\n - now destruct Ha. \n - eapply Extensionality_Ensembles; tauto.\nQed.\n\n\nLemma g_unic : forall g_beta g_beta', ordinal g_beta ->\n                                      ordinal g_beta' ->\n                                      _A = members g_beta ->\n                                      _A = members g_beta' ->\n                                      g_beta = g_beta'.\nProof.\n  intros g_beta g_beta' H H0 H1 H2;  rewrite H2 in H1;clear H2.\n  assert (Same_set  (members g_beta') (members g_beta)).\n  { rewrite H1; split;auto with schutte. }\n  case H2; unfold Included, members; intros; apply le_antisym.\n - apply not_gt_le; auto with schutte.\n   intro H5; generalize (H4 g_beta'); intros H6; unfold In in H6.\n   case (@lt_irrefl g_beta');  now apply H6. \n - apply not_gt_le; auto with schutte.\n   intro H5;  generalize (H3 g_beta);intros H6;\n     destruct  (@lt_irrefl g_beta);  now apply H6.   \nQed.\n\nDefinition g := iota inh_Ord (fun o => ordinal o /\\ _A = members o).\n\nEnd beta_fixed.\n\nLemma g_def : forall beta, In  B beta ->  _A beta = members (g beta ).\nProof.\n  intros.\n  pattern (g beta); unfold g; apply iota_ind.\n  - case (g_def1 H);  intros a' [Ha' Ha'']; exists a'; split;auto.\n    intros x (Hx,H'x);  eapply g_unic;eauto.\n  -  now intros x ((Hx,H'x),U).\nQed.\n\n\nLemma g_lemma : \n  forall beta, In B beta ->\n       ordering_function (_f beta) (members (g beta))\n                                       (proper_segment_of B beta).\nProof.\n intros beta H; rewrite <- g_def.\n - now   apply of_beta'.\n - assumption.\nQed.\n\nLemma g_mono : forall beta1 beta2, In B beta1 -> In B  beta2 ->\n                                   beta1 < beta2 ->\n                                   g beta1 < g beta2.\nProof with eauto with schutte.\n intros beta1 beta2 H H0 H1.\n assert( B2 : fun_bijection (members (g beta2))\n                            (proper_segment_of B beta2)\n                            (_f beta2)) .\n { apply Ordering_bijection, g_lemma ... }\n assert (B3 : In (proper_segment_of B beta2) beta1).\n { split.  apply H. split; assumption. }\n  assert (B4 : exists alpha,  alpha < g beta2 /\\ _f beta2 alpha= beta1).\n { destruct B2; case (H3 beta1) ... }\n\n case B4; intros alpha (Ha2,Ha3).\n assert (B5 : ordering_function (_f beta2) (members alpha) \n                                (proper_segment_of B beta1)).\n { repeat split ...\n   - red;  intros;   apply lt_trans with alpha0;eauto.\n   -  case B2;intros;  clear H4 H5; red in H3.\n      + generalize (H3 a); intros H4;  clear H3;  case H4.\n        * red; apply lt_trans with alpha; auto.\n        *  auto.\n   -  case (g_lemma H0). \n      intros H3 H4; decompose [and] H4; clear H4.\n      replace beta1 with (_f beta2 alpha).\n      intros.\n      apply OF_mono0; auto.\n      +   red;  apply lt_trans with alpha;auto.\n   -  destruct 1;  case (g_lemma H0).\n      intros H4 H5;  decompose [and] H4;  clear H4;  decompose [and] H5.\n       intros. case (OF_onto0 b). \n      + split;auto.\n        split;auto.\n        eapply lt_trans;eauto.\n        case H3;auto.\n       +  intros a (Ha,Ha');exists a;split;auto.\n          red;  tricho  a alpha X.\n         *  auto.\n         * subst a; rewrite Ha3 in Ha'.\n           subst b; case H3;intros H33 _.\n           case (@lt_irrefl _ H33).\n         *  assert (beta1 < b).\n           { rewrite <- Ha3; rewrite <- Ha'.\n             case (g_lemma H0); intros.   \n             apply OF_mono1; auto.\n           }\n           case (@lt_irrefl beta1);  apply lt_trans with b;auto.\n           case H3;auto.\n   - intros; case (g_lemma H0); intros.   \n     apply OF_mono0; auto.\n     red;  apply lt_trans with alpha;auto.\n    red;  red; apply lt_trans with alpha;auto.\n }\n generalize (g_lemma H);intro.\n generalize (ordering_function_unicity B5 H2). \n destruct 1.\n generalize (Extensionality_Ensembles _ _ _ H3).\n intros;  generalize (members_eq   H5).\n intro; subst alpha;auto.\nQed.\n\n\nLemma L3a : segment (image B g).\nProof.\n  intros gbeta alpha  (beta,(H1,H2)) H3;  subst gbeta. \n     generalize (g_lemma H1);intro.\n     case H; intros  H2 H4 H5 H6. \n     assert (exists beta0, In (proper_segment_of B beta) beta0 \n                      /\\ _f beta alpha=beta0).\n     {  exists (_f beta alpha); split;auto.\n     }\n     case H0;intros beta0 (H9,H10); clear H0.\n     assert (B5 : ordering_function (_f beta) (members alpha) \n                 (proper_segment_of B beta0)).\n     { \n       repeat split;  auto with schutte. \n       - red;  red; intros.  apply lt_trans with alpha0;eauto.\n       - assert( B2 : fun_bijection (members (g beta))\n                                  (proper_segment_of B beta) (_f beta)) .\n        { apply Ordering_bijection ;   apply g_lemma; auto. }\n         case B2;intros H77 H11 H12;  generalize (H77 a).\n         intros H13;  clear H77;  case H13.\n         2:auto.\n        red;  apply lt_trans with alpha; auto.\n \n       -  case (g_lemma H1); intros.  \n          replace beta0 with (_f beta alpha).\n        apply OF_mono0; auto.\n        red;  red;  apply lt_trans with alpha;auto.\n       -  case H9;  auto.\n       - destruct 1; case (g_lemma H1); intros.  \n          case (OF_onto0 b).\n         split;auto.\n         split;auto.\n         apply lt_trans with beta0;auto.\n         case H7;auto.\n         case H9;auto.\n         destruct 2; auto.\n         intros a (Ha,Ha');exists a;split;auto.\n         red; tricho  a alpha X.\n         + auto.\n        + subst a; rewrite H10 in Ha'.\n          subst b. case H7; intros H77 _.\n          case (@lt_irrefl _ H77).\n        + assert (beta0 < b) by (rewrite <- H10; rewrite <- Ha'; auto).\n          case (@lt_irrefl beta0).\n          apply lt_trans with b;auto.\n          case H7;auto.\n        - intros; case (g_lemma H1); intros.  \n          apply OF_mono0; auto.\n          red;  apply lt_trans with alpha;auto.\n          red; red;  apply lt_trans with alpha;auto.\n       }\n     generalize (g_lemma (beta:=beta0));intros.\n     case H9;intros H7 H8.   generalize (H0 H7).\n     intros H12; generalize (ordering_function_unicity B5 H12). \n     destruct 1;  generalize (Extensionality_Ensembles _ _ _ H11).\n     intros H14; generalize (members_eq (alpha:=alpha)(beta:=g beta0)   H14 ).\n     exists beta0;split;auto.\nQed.\n\n Lemma g_bij : fun_bijection B (image B g) g.\n Proof.\n split.\n -  intros a H ; exists a;split;auto.\n -  red; destruct 1;  exists x;split;auto.\n   +  case H;auto.\n   +  case H;auto.\n - red;intros a b; tricho a b Hab; trivial.\n   intros H H0 ; generalize (g_mono H H0 Hab); auto.\n   + intros H1 H2.   rewrite H2 in H1;  case (@lt_irrefl _ H1); auto.\n   + intros H H0 H1; generalize (g_mono H0 H Hab); intro; rewrite H1 in H2; \n      case (@lt_irrefl _ H2).\n Qed.\n\n #[local] Hint Resolve g_bij : schutte.\n\n\nLet g_1 := inv_fun inh_Ord B (image B g) g.\n\nLemma g_1_bij : fun_bijection (image B g) B g_1.\nProof.\n unfold  g_1; apply inv_fun_bij; auto with schutte.\nQed.\n\n#[local] Hint Resolve g_1_bij : schutte.\n\n\nLemma g_1_of : ordering_function g_1 (image B g) B.\nProof.\n split.\n -  apply L3a.\n - \n   destruct 1 as [x [H0 H1]]. rewrite <- H1.\n      replace (g_1 (g x)) with x;  auto.\n      symmetry;unfold g_1;eapply inv_compose;eauto.\n      auto with schutte.\n - intros b H;  exists (g b);  split;auto.\n   +  exists b;  split;auto.\n   +  unfold g_1;eapply inv_compose;eauto.\n      auto with schutte.\n  -  intros;  tricho (g_1 a) (g_1 b) Hab; auto with schutte.\n    + case g_1_bij; intros.\n      generalize (H2 a H).\n      case g_1_bij; intros.\n      generalize (H2 b H0).\n      replace a with (g (g_1 a)) in H1.\n      replace b with (g (g_1 b)) in H1.\n      rewrite Hab in H1.\n      case (@lt_irrefl _ H1).\n      unfold g_1;  apply inv_composeR;  auto with schutte.\n      unfold g_1;  apply inv_composeR;  auto with schutte.\n    +  case (le_not_gt (a:=a)(b:= b));  auto with schutte.\n       replace a with (g (g_1 a));\n         replace b with (g (g_1 b)) .\n       apply g_mono;auto with schutte.\n       case g_1_bij;auto with schutte.\n       case g_1_bij;auto with schutte.\n     all :  unfold g_1;  apply inv_composeR;  auto with schutte.\nQed.\n\nLemma image_B_g_seg  : ordering_segment (image B g) B.\nProof.\n exists g_1;  apply g_1_of.\nQed.\n\n(** Corresponds to Lemma 3 of Schutte's chapter :\n    It is used twice in the building of ordering function for any subset B of ordinal *)\n\n\nLemma L3_u : exists! S, ordering_segment S B.\nProof.\n exists (image B g);  split.\n - apply image_B_g_seg.\n - intros ;eapply ordering_function_seg_unicity;eauto.\n   apply image_B_g_seg.\nQed.\n\n \nEnd building_ordering_function_1.\n\n(** For any set [B], we build by transfinite induction the ordering segment of \n  [B] and the (unique upto extensionnality) ordering function of B \n *)\n\n\nSection building_ordering_function_by_induction.\n\n Variable B : Ensemble Ord.\n\n Lemma ordering_segments_of_B (beta : Ord) :\n  In B beta ->\n  exists! A : Ensemble Ord,\n    ordering_segment A  (proper_segment_of B beta).\n  Proof with eauto with schutte.\n    intros  Hbeta; pattern beta; apply transfinite_induction.\n    -  intros a  H0;  apply L3_u.\n    +   intros beta0 H1;\n      rewrite <- (proper_of_proper (B:=B) (beta:=a) (beta':=beta0))...\n      apply H0...\n        *  destruct H1 ; tauto.\n        *  destruct H1; tauto.  \nQed.\n\n\n \n Theorem ordering_segment_ex_unique : exists! S, ordering_segment S B.\n Proof.\n   apply L3_u,  ordering_segments_of_B.\n Qed.\n\n\nTheorem ordering_function_ex : exists ! S, exists f, ordering_function f S B.\nProof with eauto.\n case ordering_segment_ex_unique;intros S (f,pi); exists S.\n  split.\n  -  case f;intros x H;  exists x;auto.\n  -  intros x' H;  case H; intros;case f;intros.\n     eapply ordering_function_seg_unicity...\nQed.\n\n \nLemma ord_ok :\n  ordering_function (ord  B) (the_ordering_segment B) B.\nProof.\n  pattern (ord  B);  apply epsilon_spec. \n  pattern (the_ordering_segment B);\n    apply iota_spec,  ordering_segment_ex_unique.\nQed.\n\nLemma segment_the_ordering_segment  :\n  segment (the_ordering_segment B).\n  unfold the_ordering_segment.\n  apply iota_ind.\n  apply ordering_segment_ex_unique.\n  destruct 1.\n  destruct H.\n  now  destruct H.\nQed.\n\n\n\n\nLemma ord_eq (A : Ensemble Ord) (f : Ord -> Ord) :\n  ordering_function f A B ->\n  fun_equiv f (ord B) A (the_ordering_segment B).\n Proof with eauto with schutte.\n   intros;eapply ordering_function_unicity...\n   apply ord_ok.\n Qed.\n\n\nEnd building_ordering_function_by_induction.\n\n(* begin snippet orderingFunctionEx *)\n\nAbout ordering_function_ex.\nAbout ordering_function_unicity.\n\n(* end snippet orderingFunctionEx *)\n\nLemma of_image : forall f A B, ordering_function f A B ->\n                               ordering_function f A (image A f).\nProof.\n intros f A B O; case O; intros H H0;  decompose [and] H0.\n repeat split;auto.\n intros; exists a; auto. \nQed.\n\n\nSection Th13_5.\n Variables (A B : Ensemble Ord).\n Variable f : Ord -> Ord.\n Hypothesis f_ord : ordering_function f A B.\n\n Section recto.\n\n Hypothesis f_cont : continuous f A B.\n (* begin hide *)\n \n Section M_fixed.\n Variable M : Ensemble Ord.\n Hypothesis inc : Included M B.\n Hypothesis ne : Inhabited _ M.\n Hypothesis den : countable M.\n\n Let U := fun u => In A u /\\ In M ( f u).\n\n Remark fbij : fun_bijection A B f.\n  apply Ordering_bijection; auto.\n Qed.\n\n \n Remark restrict : fun_bijection U M f.\n Proof.\n   split.\n   -  destruct 1;auto.\n   - red; case fbij.\n     intros  H H0 H1 b H2; case (H0 b).\n     +   apply inc;auto.\n     +  intros x (Hx,H'x); exists x;split;auto.\n        red;unfold U; split;auto.\n        subst b;auto.\n   -  red; destruct 1.\n      destruct 1.\n      intros H3; case fbij;intros; now  apply H6.\nQed.\n \n Remark Inc_U_A : Included U A.\n Proof. now destruct 1. Qed.\n \n Remark den_U : countable U.\n eapply countable_bij_funR with Ord M f;auto.\n apply restrict.\n Qed.\n\n\n Remark inh_U : Inhabited _ U.\n Proof.  \n   case ne;intros.\n   exists (inv_fun inh_Ord A B f x).\n   red; unfold U; rewrite inv_composeR.\n   -  split;auto.\n      generalize (Ordering_bijection f_ord); \n      intros;    generalize (inv_fun_bij inh_Ord H0).\n      intros;  destruct H1.\n      apply H1.\n      apply inc;auto.\n   -  apply fbij.\n   -   apply inc;auto.\n Qed.\n\n \n Remark im_U_f : (image U f : Ensemble Ord)  = M.\n Proof.\n   eapply Extensionality_Ensembles;    split.\n   red;destruct 1;  unfold U in H;  case H.\n   intros;   case H0;intros.\n   subst x;auto.\n   red;  intros.\n   exists (inv_fun inh_Ord A B f x);  split.\n   red;red;  generalize (Ordering_bijection f_ord).\n   intros;   split.\n   case (inv_fun_bij inh_Ord H0).  \n   auto.\n   intros;   destruct H0.\n   rewrite inv_composeR; auto with schutte.\n   apply fbij.\n   apply inc;auto.\n   rewrite inv_composeR; auto with schutte.\n   apply fbij.\n   apply inc;auto.\n Qed.\n\n \n Lemma sup_M_in_B : In B (|_| M).\n Proof.\n  rewrite <- im_U_f.   case f_cont.  intros H [H0 H1].\n  rewrite H1; auto.\n  -  apply H.\n     apply H0.\n     + apply Inc_U_A.\n     + apply inh_U.\n     + apply den_U.\n  -  apply Inc_U_A.\n  -  apply inh_U.\n  - apply den_U.\nQed.\n\nEnd M_fixed.\n\n (* end hide *)\n \n Lemma Th_13_5_1 : Closed B.\n Proof.\n    red.\n   intros;    apply sup_M_in_B; auto.\n Qed.\n\n\nEnd recto.\n\nSection verso.\n Hypothesis B_closed : Closed B.\n\n (* begin hide *)\n \n Section U_fixed.\n Variable U : Ensemble Ord.\n Hypothesis U_non_empty : Inhabited _ U. \n Hypothesis U_den : countable U.\n Hypothesis U_inc_A : Included U A.\n\n (* apply Virgile's technique ? *)\n\n Remark R1_aux : countable (image U f).\n Proof.\n apply countable_bij_fun with Ord U f.\n - case (Ordering_bijection f_ord); intros H H0 H1;  split.\n  + intros u u_In_U;  exists u; auto.\n  +  intros u u_In_img; case u_In_img;  intros x Hx.\n      exists x; assumption.\n  +  intros u1 u2 u1_In_U u2_In_U Heq; apply H1;\n       try apply U_inc_A; assumption.\n -  assumption.\n Qed.\n\n Definition R1 := let foo := U_den in R1_aux.\n Opaque R1.\n\n\n Remark R2 : In B (|_| (image U f)). \n Proof.\n   apply  B_closed.\n   -  red;red;  destruct 1.\n      case f_ord. intros H0 H1 H2 H3. \n      case H;intros; subst x; destruct f_ord.\n      decompose [and] H3.\n      apply OF_total0. apply U_inc_A;auto. \n   -  case U_non_empty;intros x H;  exists (f x);auto.\n      exists x;auto.\n   - apply R1_aux.\n Qed.\n\nRemark R3: exists alpha, In A alpha /\\ f alpha = |_|  (image U f).\nProof.\n case f_ord; intros H H0 H1 H2.\n  case (H1 (|_|image U f)).\n  -  apply R2.\n  -  intros x; exists x;auto.\nQed.\n\nLet alpha_ : Ord :=\n  (epsilon inh_Ord (fun alpha =>  In A alpha /\\ f alpha = sup(image U f))).\n\n\nLemma alpha_A :   In A alpha_.\nProof.\n  unfold alpha_;  apply epsilon_ind.\n  - apply R3. \n  -  tauto.\nQed.\n\nLemma alpha_sup : f alpha_ = |_| (image U f). \nProof.\n pattern alpha_; epsilon_elim.\n - apply R3.\n - tauto.\nQed.\n\nRemark R5 : forall khi, In U khi -> f khi <= f alpha_.\nProof.\n intros; rewrite alpha_sup;  apply sup_upper_bound.\n -  apply R1.\n -  exists khi; tauto. \nQed.\n\n\nRemark R6 : forall khi, In U khi ->  khi <=  alpha_ .\nProof with eauto with schutte.\n intros khi H; case (R5 H).\n -  left.  \n   +  case (Ordering_bijection f_ord). \n      intros H1 H2 H3; apply H3.\n    *  apply U_inc_A;auto.\n    * apply alpha_A.\n    *  case H0;auto.\n -  right; case f_ord; intros _ H1 H2 H3.\n    tricho khi alpha_ H7; auto.\n   +    subst khi; case (@lt_irrefl _ H0).\n   + case (@lt_irrefl (f alpha_));auto.\n     apply lt_trans with (f khi); auto.\n     * apply H3; auto.\n      apply alpha_A;  auto.\nQed.\n\n\n#[local] Hint Resolve  alpha_A : schutte.\n \nRemark R7 : |_| U <= alpha_ .\nProof. \n apply sup_least_upper_bound; trivial.\n - intros;now apply R6.\nQed.\n \n \nRemark R4 : forall khi, In U khi -> khi <= sup U.\nProof.\n intros;  apply sup_upper_bound;auto.\nQed.\n\n (* Schutte's remark \"hence A is closed \" is out of this section *)\n\n\nLemma A_closed : In A (sup U).\nProof.\n  assert (H: segment A) by (eapply SA2;  eauto).\n  case R7.\n  - intros  H3; rewrite H3; apply alpha_A.\n  - intros;red.  eapply H with alpha_ ;auto with schutte.\nQed.\n\n\nRemark R4' : forall khi, In U khi -> f khi <= f (sup U).\nProof.\n intros khi H ; case f_ord;intros H0 H1 H2 H3 . \n case (R4 H).\n - intro;  subst khi;left;auto with schutte.\n -  right;auto.\n    apply H3;auto with schutte.\n    apply A_closed;auto.\nQed.\n\nRemark R4'' : |_| (image U f) <= f (sup U).\nProof.\n apply sup_least_upper_bound.\n -  apply R1.\n - intros y H; destruct H; destruct H;subst y;\n     apply ordering_function_mono_weak with A B; auto.\n   +  apply  A_closed.\n   +  apply sup_upper_bound;auto.\nQed.\n\n\nRemark R42 : f (sup U) <= |_| (image U f).\nProof.\n apply le_trans with (f alpha_).\n -  case f_ord;intros H H0 H1 H2.\n    case R7.\n    +  intro H5; rewrite H5;auto with schutte.\n    +  right;auto.\n       apply H2;auto with schutte.\n       apply A_closed;auto with schutte.\n -  unfold alpha_; apply epsilon_ind.\n    + apply R3.\n    + destruct 1; left;   auto.\nQed.\n\nLemma f_sup_commutes : f (|_| U) = |_| (image U f).\nProof.\n apply le_antisym.\n -  apply R42.\n -  apply R4''. \nQed.\n\nEnd U_fixed.\n\n (* end hide *)\n\n Lemma Th_13_5_2 : continuous f A B.\n Proof.\n   split.\n   - red.\n     case f_ord;tauto.\n   - split. red. intros. \n     eapply A_closed;auto.\n     intros;symmetry;apply f_sup_commutes;auto.\n Qed.\n\n\nEnd verso.\n\nEnd Th13_5.\n\n\nTheorem TH_13_6 (B : Ensemble Ord)(f : Ord -> Ord) :\n  normal f B ->   Closed B /\\ Unbounded B.\nProof with eauto with schutte.\n destruct 1.\n split.\n -  eapply Th_13_5_1;eauto.\n -  intros x;  generalize (Ordering_bijection H).\n    destruct 1 as [H3 H4 H5].\n    exists (f (succ x));  split.\n    +  apply H3 ... \n    +  apply le_lt_trans with (f x).\n       * eapply ordering_le ... \n       *  eapply ordering_function_mono ...\nQed.\n\n\nLemma ordering_unbounded_unbounded : \n  forall A B f,  ordering_function f A B ->\n                 (Unbounded B <-> Unbounded A).\nProof with auto with schutte.\n  intros A B f  H0;split.\n  - intro; apply not_countable_unbounded.\n    intro H2;  assert (H3 : countable B).\n    {  apply countable_bij_fun with Ord A  f ... \n       apply Ordering_bijection;auto.\n    }\n    case (countable_not_Unbounded  H3);auto.\n  - intro H1;  apply not_countable_unbounded ...\n    intro H2;  assert (H3 : countable A).\n    { apply countable_bij_funR with Ord   B  f;auto.\n      apply Ordering_bijection;auto.\n    }\n case (countable_not_Unbounded (X:= A));auto.\nQed.\n\n\nTheorem TH_13_6R (A B : Ensemble Ord) (f : Ord -> Ord) : \n  ordering_function f A B ->\n  Closed B ->    Unbounded B ->   normal f B.\nProof with auto with schutte.\n  intros  H0 H1 H2; assert (A = ordinal).\n    {   apply segment_unbounded.\n        - eapply SA1;  apply H0.\n        - destruct (ordering_unbounded_unbounded H0); auto.\n    }\n    subst A; split; [trivial | now apply Th_13_5_2].\nQed.\n\n(** If [f] is the ordering function of [B], then [f 0] is the least element of\n   [B] *)\n\nLemma ordering_function_least_least : \n forall B f  , ordering_function f ordinal B ->\n     least_member  lt B (f zero).\nProof with auto with schutte.\n intros b f H; case H; intros H0 H2 H3 H4 .\n split.\n -  apply H2 ...\n -  intros x  H55.\n   case (H3 _ H55); intros x0 (Hx0,H'x0); subst x.\n   generalize (ordering_function_mono_weak H (a:=zero) (b:=x0)).\n   intro H6;  apply H6 ...\nQed.\n\nLemma segment_lt_closed : forall A a b, segment A -> \n                                          In A b -> \n                                          a < b -> \n                                          In A a. \nProof.\n intros A a b H H0 H1; apply H with b;  auto. \nQed.\n\nLemma th_In A  alpha : In (the_ordering_segment A) alpha ->\n                             In A (ord A alpha). \nProof.\n  unfold ord;  intro H;   red;  unfold some;  apply epsilon_ind.\n  - destruct   (ordering_function_ex A) as [X [[f Hf] H0]];  exists f. \n   rewrite <-  (H0 (the_ordering_segment A) );  auto.\n   exists (ord A); apply ord_ok.\n  -   intros beta H0;  eapply ordering_function_In; [ eexact H0 | trivial].\nQed. \n\n(* begin snippet Th1352 *)\n\n(* Theorem 13.5.2 by Schutte *)\n\nAbout Th_13_5_2.\n\n(* end snippet Th1352 *)\n\nArguments ord  : clear implicits.\nArguments the_ordering_segment : clear implicits.\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/Schutte/Ordering_Functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7230500367936616}}
{"text": "Theorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1 as [| h1 t1 IH1].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IH1. rewrite <- app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l as [| h t IH].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr.\n    simpl. rewrite -> IH.\n    reflexivity.\nQed.", "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/Chapter4/rev_app_distr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7230500328569827}}
{"text": "Require Export Bool.\nRequire Export ZArith.\n\nOpen Scope Z_scope.\n\nInductive Z_inf_branch_tree : Set :=\n  Z_inf_leaf : Z_inf_branch_tree\n| Z_inf_node : Z->(nat->Z_inf_branch_tree)->Z_inf_branch_tree.\n\nFixpoint any_true (n:nat)(f:nat->bool){struct n}:bool :=\n match n with\n   0%nat => f 0%nat\n | S p => orb (f (S p)) (any_true p f)\n end.\n\nFixpoint izero_present (n:nat)(t:Z_inf_branch_tree) {struct t} :bool :=\n match t with\n | Z_inf_leaf => false\n | Z_inf_node v f =>\n   match v with\n     0 => true\n   | _ => any_true n (fun p => izero_present n (f p))\n   end\n end.\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/structinduct/SRC/izero_present.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7230200019022117}}
{"text": "Require Export Pullback Limits.\nRequire Import Common.\n\nSet Implicit Arguments.\n\nGeneralizable All Variables.\n\nSet Asymmetric Patterns.\n\nSet Universe Polymorphism.\n\nSection subobject_classifier.\n  (** Quoting Wikipedia:\n\n    For the general definition, we start with a category [C] that has\n    a terminal object, which we denote by [1]. The object [Ω] of [C]\n    is a subobject classifier for [C] if there exists a morphism [m :\n    1 → Ω] with the following property: for each monomorphism [j : U →\n    X] there is a unique morphism [χj : X → Ω] such that the following\n    commutative diagram:\n\n    [[\n        U ----> 1\n        |       |\n      j |       | m\n        ↓       ↓\n        X ----> Ω\n           χj\n    ]]\n\n    is a pullback diagram — that is, [U] is the limit of the diagram:\n\n    [[\n                1\n                |\n                | m\n                ↓\n        X ----> Ω\n           χj\n    ]]\n\n    The morphism [χj] is then called the classifying morphism for the\n    subobject represented by [j].\n   *)\n\n  (** Quoting nCatLab:\n\n   Definition 1. In a category [C] with finite limits, a subobject\n   classifier is a monomorphism [true : * → Ω] out of the terminal\n   object, such that for every monomorphism [U → X] in [C] there is a unique\n   morphism [χU : X → Ω] such that there is a pullback diagram\n\n   [[\n        U ----> *\n        |       |\n        |       | true\n        ↓       ↓\n        X ----> Ω\n           χU\n   ]]\n\n   See for instance (MacLane-Moerdijk, p. 22).\n   *)\n\n  Context `(C : @SpecializedCategory objC).\n\n  Local Reserved Notation \"'Ω'\".\n\n  Record SubobjectClassifier :=\n    {\n      SubobjectClassifierOne : TerminalObject C where \"1\" := (TerminalObject_Object SubobjectClassifierOne);\n      ObjectOfTruthValues : C where \"'Ω'\" := ObjectOfTruthValues;\n      TrueValue : C.(Morphism) 1 Ω;\n      TrueIsMonomorphism : IsMonomorphism TrueValue;\n      SubobjectClassifyingMap : forall U X (j : C.(Morphism) U X),\n                                  IsMonomorphism j\n                                  -> { χj : Morphism C X Ω &\n                                                     { H : Compose χj j =\n                                                           Compose TrueValue (TerminalObject_Morphism SubobjectClassifierOne U)\n                                                                   & IsPullbackGivenMorphisms\n                                                                   X 1 Ω\n                                                                   χj TrueValue\n                                                                   U j\n                                                                   (TerminalObject_Morphism SubobjectClassifierOne U)\n                                                                   H } }\n    }.\nEnd subobject_classifier.\n", "meta": {"author": "CategoricalData", "repo": "catdb", "sha": "ce74dd70c52116a29f4589fd8d12c6439181254e", "save_path": "github-repos/coq/CategoricalData-catdb", "path": "github-repos/coq/CategoricalData-catdb/catdb-ce74dd70c52116a29f4589fd8d12c6439181254e/SubobjectClassifier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7229491924556392}}
{"text": "Require Import Crypto.Util.Relations Crypto.Util.Notations.\nRequire Import Crypto.Util.Tactics.UniquePose.\nRequire Import Crypto.Util.Tactics.DebugPrint.\nRequire Import Coq.Classes.RelationClasses Coq.Classes.Morphisms.\nRequire Import Crypto.Algebra.Hierarchy Crypto.Algebra.Ring Crypto.Algebra.IntegralDomain.\nRequire Coq.setoid_ring.Field_theory.\n\nSection Field.\n  Context {T eq zero one opp add mul sub inv div} `{@field T eq zero one opp add sub mul inv div}.\n  Local Infix \"=\" := eq : type_scope. Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n  Local Notation \"0\" := zero. Local Notation \"1\" := one.\n  Local Infix \"+\" := add. Local Infix \"*\" := mul.\n\n  Lemma right_multiplicative_inverse : forall x : T, ~ eq x zero -> eq (mul x (inv x)) one.\n  Proof using Type*.\n    intros. rewrite commutative. auto using left_multiplicative_inverse.\n  Qed.\n\n  Lemma left_inv_unique x ix : ix * x = one -> ix = inv x.\n  Proof using Type*.\n    intro Hix.\n    assert (H0 : ix*x*inv x = inv x).\n    - rewrite Hix, left_identity; reflexivity.\n    - rewrite <-associative, right_multiplicative_inverse, right_identity in H0; trivial.\n      intro eq_x_0. rewrite eq_x_0, Ring.mul_0_r in Hix.\n      apply (zero_neq_one(eq:=eq)). assumption.\n  Qed.\n  Definition inv_unique := left_inv_unique.\n\n  Lemma right_inv_unique x ix : x * ix = one -> ix = inv x.\n  Proof using Type*. rewrite commutative. apply left_inv_unique. Qed.\n\n  Lemma div_one x : div x one = x.\n  Proof using Type*.\n    rewrite field_div_definition.\n    rewrite <-(inv_unique 1 1); apply monoid_is_right_identity.\n  Qed.\n\n  Lemma mul_cancel_l_iff : forall x y, y <> 0 ->\n                                       (x * y = y <-> x = one).\n  Proof using Type*.\n    intros x y H0.\n    split; intros H1.\n    + rewrite <-(right_multiplicative_inverse y) by assumption.\n      rewrite <-H1 at 1; rewrite <-associative.\n      rewrite right_multiplicative_inverse by assumption.\n      rewrite right_identity.\n      reflexivity.\n    + rewrite H1; apply left_identity.\n  Qed.\n\n  Lemma field_theory_for_stdlib_tactic : Field_theory.field_theory 0 1 add mul sub opp div inv eq.\n  Proof using Type*.\n    constructor.\n    { apply Ring.ring_theory_for_stdlib_tactic. }\n    { intro H01. symmetry in H01. auto using (zero_neq_one(eq:=eq)). }\n    { apply field_div_definition. }\n    { apply left_multiplicative_inverse. }\n  Qed.\n\n  Context {eq_dec:DecidableRel eq}.\n\n  Global Instance is_mul_nonzero_nonzero : @is_zero_product_zero_factor T eq 0 mul.\n  Proof using Type*.\n    split. intros x y Hxy.\n    eapply not_not; try typeclasses eauto; []; intuition idtac; eapply (zero_neq_one(eq:=eq)).\n    transitivity ((inv y * (inv x * x)) * y).\n    - rewrite <-!associative, Hxy, !Ring.mul_0_r; reflexivity.\n    - rewrite left_multiplicative_inverse, right_identity, left_multiplicative_inverse by trivial.\n      reflexivity.\n  Qed.\n\n  Global Instance integral_domain : @integral_domain T eq zero one opp add sub mul.\n  Proof using Type*.\n    split; auto using field_commutative_ring, field_is_zero_neq_one, is_mul_nonzero_nonzero.\n  Qed.\nEnd Field.\n\nSection Homomorphism.\n  Context {F EQ ZERO ONE OPP ADD MUL SUB INV DIV} `{@field F EQ ZERO ONE OPP ADD SUB MUL INV DIV}.\n  Context {K eq zero one opp add mul sub inv div} `{@field K eq zero one opp add sub mul inv div}.\n  Context {phi:F->K}.\n  Local Infix \"=\" := eq. Local Infix \"=\" := eq : type_scope.\n  Context `{@Ring.is_homomorphism F EQ ONE ADD MUL K eq one add mul phi}.\n\n  Lemma homomorphism_multiplicative_inverse\n    : forall x, not (EQ x ZERO)\n                -> phi (INV x) = inv (phi x).\n  Proof using Type*.\n    intros.\n    eapply inv_unique.\n    rewrite <-Ring.homomorphism_mul.\n    rewrite left_multiplicative_inverse; auto using Ring.homomorphism_one.\n  Qed.\n\n  Lemma homomorphism_multiplicative_inverse_complete\n        { EQ_dec : DecidableRel EQ }\n    : forall x, (EQ x ZERO -> phi (INV x) = inv (phi x))\n                -> phi (INV x) = inv (phi x).\n  Proof using Type*.\n    intros x ?; destruct (dec (EQ x ZERO)); auto using homomorphism_multiplicative_inverse.\n  Qed.\n\n  Lemma homomorphism_div\n    : forall x y, not (EQ y ZERO)\n                  -> phi (DIV x y) = div (phi x) (phi y).\n  Proof using Type*.\n    intros. rewrite !field_div_definition.\n    rewrite Ring.homomorphism_mul, homomorphism_multiplicative_inverse;\n      (eauto || reflexivity).\n  Qed.\n\n  Lemma homomorphism_div_complete\n        { EQ_dec : DecidableRel EQ }\n    : forall x y, (EQ y ZERO -> phi (INV y) = inv (phi y))\n                  -> phi (DIV x y) = div (phi x) (phi y).\n  Proof using Type*.\n    intros. rewrite !field_div_definition.\n    rewrite Ring.homomorphism_mul, homomorphism_multiplicative_inverse_complete;\n      (eauto || reflexivity).\n  Qed.\nEnd Homomorphism.\n\nSection Homomorphism_rev.\n  Context {F EQ ZERO ONE OPP ADD SUB MUL INV DIV} {fieldF:@field F EQ ZERO ONE OPP ADD SUB MUL INV DIV}.\n  Context {H} {eq : H -> H -> Prop} {zero one : H} {opp : H -> H} {add sub mul : H -> H -> H} {inv : H -> H} {div : H -> H -> H}.\n  Context {phi:F->H} {phi':H->F}.\n  Local Infix \"=\" := EQ. Local Infix \"=\" := EQ : type_scope.\n  Context (phi'_phi_id : forall A, phi' (phi A) = A)\n          (phi'_eq : forall a b, EQ (phi' a) (phi' b) <-> eq a b)\n          {phi'_zero : phi' zero = ZERO}\n          {phi'_one : phi' one = ONE}\n          {phi'_opp : forall a, phi' (opp a) = OPP (phi' a)}\n          (phi'_add : forall a b, phi' (add a b) = ADD (phi' a) (phi' b))\n          (phi'_sub : forall a b, phi' (sub a b) = SUB (phi' a) (phi' b))\n          (phi'_mul : forall a b, phi' (mul a b) = MUL (phi' a) (phi' b))\n          {phi'_inv : forall a, phi' (inv a) = INV (phi' a)}\n          (phi'_div : forall a b, phi' (div a b) = DIV (phi' a) (phi' b)).\n\n  Lemma field_and_homomorphism_from_redundant_representation\n    : @field H eq zero one opp add sub mul inv div\n      /\\ @Ring.is_homomorphism F EQ ONE ADD MUL H eq one add mul phi\n      /\\ @Ring.is_homomorphism H eq one add mul F EQ ONE ADD MUL phi'.\n  Proof using Type*.\n    repeat match goal with\n           | [ H : field |- _ ] => destruct H; try clear H\n           | [ H : commutative_ring |- _ ] => destruct H; try clear H\n           | [ H : ring |- _ ] => destruct H; try clear H\n           | [ H : commutative_group |- _ ] => destruct H; try clear H\n           | [ H : group |- _ ] => destruct H; try clear H\n           | [ H : monoid |- _ ] => destruct H; try clear H\n           | [ H : is_commutative |- _ ] => destruct H; try clear H\n           | [ H : is_left_multiplicative_inverse |- _ ] => destruct H; try clear H\n           | [ H : is_left_distributive |- _ ] => destruct H; try clear H\n           | [ H : is_right_distributive |- _ ] => destruct H; try clear H\n           | [ H : is_zero_neq_one |- _ ] => destruct H; try clear H\n           | [ H : is_associative |- _ ] => destruct H; try clear H\n           | [ H : is_left_identity |- _ ] => destruct H; try clear H\n           | [ H : is_right_identity |- _ ] => destruct H; try clear H\n           | [ H : Equivalence _ |- _ ] => destruct H; try clear H\n           | [ H : is_left_inverse |- _ ] => destruct H; try clear H\n           | [ H : is_right_inverse |- _ ] => destruct H; try clear H\n           | _ => intro\n           | _ => split\n           | [ H : eq _ _ |- _ ] => apply phi'_eq in H\n           | [ |- eq _ _ ] => apply phi'_eq\n           | [ H : (~eq _ _)%type |- _ ] => pose proof (fun pf => H (proj1 (@phi'_eq _ _) pf)); clear H\n           | [ H : EQ _ _ |- _ ] => rewrite H\n           | _ => progress erewrite ?phi'_zero, ?phi'_one, ?phi'_opp, ?phi'_add, ?phi'_sub, ?phi'_mul, ?phi'_inv, ?phi'_div, ?phi'_phi_id by reflexivity\n           | [ H : _ |- _ ] => progress erewrite ?phi'_zero, ?phi'_one, ?phi'_opp, ?phi'_add, ?phi'_sub, ?phi'_mul, ?phi'_inv, ?phi'_div, ?phi'_phi_id in H by reflexivity\n           | _ => solve [ eauto ]\n           end.\n  Qed.\nEnd Homomorphism_rev.\n\nLtac guess_field :=\n  match goal with\n  | |- ?eq _ _ =>  constr:(_:Hierarchy.field (eq:=eq))\n  | |- not (?eq _ _) =>  constr:(_:Hierarchy.field (eq:=eq))\n  | [H: ?eq _ _ |- _ ] =>  constr:(_:Hierarchy.field (eq:=eq))\n  | [H: not (?eq _ _) |- _] =>  constr:(_:Hierarchy.field (eq:=eq))\n  end.\n\nLtac goal_to_field_equality fld :=\n  let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in\n  match goal with\n  | [ |- eq _ _] => idtac\n  | [ |- not (eq ?x ?y) ] => apply not_exfalso; intro; goal_to_field_equality fld\n  | _ => exfalso;\n         match goal with\n         | H: not (eq _ _) |- _ => apply not_exfalso in H; apply H\n         | _ => apply (field_is_zero_neq_one(field:=fld))\n         end\n  end.\n\nLtac inequalities_to_inverse_equations fld :=\n  let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in\n  let zero := match type of fld with Hierarchy.field(zero:=?zero) => zero end in\n  let div := match type of fld with Hierarchy.field(div:=?div) => div end in\n  let sub := match type of fld with Hierarchy.field(sub:=?sub) => sub end in\n  repeat match goal with\n         | [H: not (eq _ _) |- _ ] =>\n           lazymatch type of H with\n           | not (eq ?d zero) =>\n             unique pose proof (right_multiplicative_inverse(H:=fld) _ H)\n           | not (eq zero ?d) =>\n             unique pose proof (right_multiplicative_inverse(H:=fld) _ (symmetry(R:=fun a b => not (eq a b)) H))\n           | not (eq ?x ?y) =>\n             unique pose proof (right_multiplicative_inverse(H:=fld) _ (Ring.neq_sub_neq_zero _ _ H))\n           end\n         end.\n\nLtac unique_pose_implication pf :=\n  let B := match type of pf with ?A -> ?B => B end in\n  match goal with\n             | [H:B|-_] => fail 1\n             | _ => unique pose proof pf\n  end.\n\nLtac inverses_to_conditional_equations fld :=\n  let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in\n  let inv := match type of fld with Hierarchy.field(inv:=?inv) => inv end in\n  repeat match goal with\n         | |- context[inv ?d] =>\n           unique_pose_implication constr:(right_multiplicative_inverse(H:=fld) d)\n         | H: context[inv ?d] |- _ =>\n           unique_pose_implication constr:(right_multiplicative_inverse(H:=fld) d)\n         end.\n\nLtac clear_hypotheses_with_nonzero_requirements fld :=\n  let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in\n  let zero := match type of fld with Hierarchy.field(zero:=?zero) => zero end in\n  repeat match goal with\n           [H: not (eq _ zero) -> _ |- _ ] => clear H\n         end.\n\nLtac forward_nonzero fld solver_tac :=\n  let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in\n  let zero := match type of fld with Hierarchy.field(zero:=?zero) => zero end in\n  repeat match goal with\n         | [H: not (eq ?x zero) -> _ |- _ ]\n           => let H' := fresh in\n              assert (H' : not (eq x zero)) by (clear_hypotheses_with_nonzero_requirements; solver_tac); specialize (H H')\n         | [H: not (eq ?x zero) -> _ |- _ ]\n           => let H' := fresh in\n              assert (H' : not (eq x zero)) by (clear H; solver_tac); specialize (H H')\n         end.\n\nLtac divisions_to_inverses fld :=\n  rewrite ?(field_div_definition(field:=fld)) in *.\n\nLtac fsatz_solve_on fld :=\n  goal_to_field_equality fld;\n  forward_nonzero fld ltac:(fsatz_solve_on fld);\n  nsatz;\n  solve_debugfail ltac:(IntegralDomain.solve_constant_nonzero).\n\nLtac fsatz_solve :=\n  let fld := guess_field in\n  fsatz_solve_on fld.\n\nLtac fsatz_prepare_hyps_on fld :=\n  divisions_to_inverses fld;\n  inequalities_to_inverse_equations fld;\n  inverses_to_conditional_equations fld;\n  forward_nonzero fld ltac:(fsatz_solve_on fld).\n\nLtac fsatz_prepare_hyps :=\n  let fld := guess_field in\n  fsatz_prepare_hyps_on fld.\n\nLtac fsatz :=\n  let fld := guess_field in\n  fsatz_prepare_hyps_on fld;\n  fsatz_solve_on fld.\n\n\nSection FieldSquareRoot.\n  Context {T eq zero one opp add mul sub inv div} `{@field T eq zero one opp add sub mul inv div} {eq_dec:DecidableRel eq}.\n  Local Infix \"=\" := eq : type_scope. Local Notation \"a <> b\" := (not (a = b)) : type_scope.\n  Local Infix \"+\" := add. Local Infix \"*\" := mul.\n  Lemma only_two_square_roots_choice x y z : x * x = z -> y * y = z -> x = y \\/ x = opp y.\n  Proof using Type*.\n    intros.\n    setoid_rewrite <-sub_zero_iff.\n    eapply zero_product_zero_factor.\n    fsatz.\n  Qed.\nEnd FieldSquareRoot.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Algebra/Field.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7229491890920494}}
{"text": "Require Export Props.\n\nSet Asymmetric Patterns. (* compatibility for Coq 8.4 pattern match *)\n\nDefinition funny_prop1 := forall n, forall (E : ev n), ev (n+4).\n\nDefinition funny_prop1' := forall n, forall (_ : ev n), ev (n+4).\n\nDefinition funny_prop1'' := forall n, ev n -> ev (n+4).\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\nCheck conj.\n\nTheorem and_example :\n  (ev 0) /\\ (ev 4).\nProof.\n  apply conj.\n  apply ev_0.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nPrint and_example.\n\nTheorem and_example' :\n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n    Case \"left\".  apply ev_0.\n    Case \"right\". apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem proj1 : forall P Q : Prop,\n                  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HP. Qed.\n\n\n(* 練習問題: ★, optional (proj2) *)\n\nTheorem proj2 : forall P Q : Prop,\n                  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HQ. Qed.\n(* ☐ *)\n\n\nTheorem and_commut : forall P Q : Prop,\n                       P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  split.\n  apply HQ.\n  apply HP. Qed.\n\nPrint and_commut.\n\n(*\n練習問題: ★★ (and_assoc)\n\n次の証明では、inversionが、入れ子構造になった命題H : P ∧ (Q ∧ R)をどのようにHP:\nP, HQ : Q, HR : R に分解するか、という点に注意しなががら証明を完成させなさい。\n *)\n\nTheorem and_assoc : forall P Q R : Prop,\n                      P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n  split. split.\n  apply HP. apply HQ. apply HR.\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★★, recommended (even_ev)\n\n今度は、前の章で棚上げしていた even と ev の等価性をが別の\n方向から証明してみましょう。ここで左側のandは我々が実際に注\n目すべきものです。右のandは帰納法の仮定となって帰納法による\n証明に結びついていくことになるでしょう。なぜこれが必要とな\nるかは、左側のandをそれ自身で証明しようとして、行き詰まって\nみるとかるでしょう。\n *)\n\nTheorem even_ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  intro n.\n  unfold even.\n  induction n as [| n'].\n  (* n = 0 *)\n    simpl. split.\n    intros eq. apply ev_0.\n    intros eq. discriminate eq.\n  (* n = S n' *)\n    inversion IHn' as [Hn' HSn'].\n    split.\n    apply HSn'.\n    simpl.\n    intros eeqH.\n    apply ev_SS.\n    apply (Hn' eeqH).\nQed.\n(* ☐ *)\n\n\n(*\n練習問題: ★★\n\n次の命題の証明を示すオブジェクトを作成しなさい。\n *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun (P Q R : Prop) H0 H1 =>\n    match H0 with\n      | conj HP0 HQ0 =>\n        match H1 with\n          | conj HQ1 HR1 => conj P R HP0 HR1\n        end\n    end.\n(* ☐ *)\n\n(* Iff （両含意） *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity) : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n  (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA]. apply HAB. Qed.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB. Qed.\n\n(* 練習問題: ★ (iff_properties)\n\n上の、 ↔ が対称であることを示す証明 (iff_sym) を使い、それが反射的であること、推移的であることを証明しなさい\n。\n *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intro P.\n  split.\n  intro P0. apply P0.\n  intro P0. apply P0.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R H0 H1.\n  inversion H0 as [ HPQ HQP ].\n  inversion H1 as [ HQR HRQ ].\n  split.\n  intro p. apply (HQR (HPQ p)).\n  intro r. apply (HQP (HRQ r)).\nQed.\n\n(*\nヒント: もしコンテキストに iff を含む仮定があれば、 inversion を使ってそれを二つの含意の式に分割することがで\nきます。 (なぜそうできるのか考えてみましょう。)\n *)\n(* ☐ *)\n\n(*\n練習問題: ★★ (MyProp_iff_ev)\n\nここまで、MyProp や ev がこれらの命題がある種の数値を特徴づける（偶数、などの）ことを見てきました。次の\nMyProp n ↔ ev n が任意の nで成り立つことを証明しなさい。お遊びのつもりでかまわないので、その証明を、単純明快\nな証明、タクティックを使わないにような証明に書き換えてください。（ヒント：以前に使用した定理をうまく使えば、\n１行だけでかけるはずです！）\n *)\nDefinition MyProp_iff_ev : forall n, MyProp n <-> ev n :=\n  fun (n : nat) => conj (MyProp n -> ev n) (ev n -> MyProp n) (ev_MyProp n) (MyProp_ev n).\n(* ☐ *)\n\n(*\nCoqのいくつかのタクティックは、証明の際に低レベルな操作を避けるため iff を特別扱いします。特に rewrite を iff\nに使うと、単なる等式以上のものとして扱ってくれます。\n *)\n\n(* 論理和、選言（Disjunction、OR） *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\nCheck or_introl.\n\nCheck or_intror.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"right\". apply or_intror. apply HP.\n    Case \"left\". apply or_introl. apply HQ. Qed.\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"right\". right. apply HP.\n    Case \"left\". left. apply HQ. Qed.\n\n\n(*\n練習問題: ★★ optional (or_commut'')\n\nor_commut の証明オブジェクトがどのようになるか、書き出してみてください。（ただし、定義済みの証明オブジェクト\nを Print を使って見てみたりしないこと。）\n *)\nDefinition or_commut'' : forall P Q : Prop, P \\/ Q -> Q \\/ P :=\n  fun (P Q : Prop) H =>\n    match H with\n      | or_introl HP => or_intror Q P HP\n      | or_intror HQ => or_introl Q P HQ\n    end.\n(* ☐ *)\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. inversion H as [HP | [HQ HR]].\n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR. Qed.\n\n(*\n練習問題: ★★, recommended (or_distributes_over_and_2)\n *)\n\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros P Q R H.\n  inversion H as [ [PH0 | QH] [PH1 | RH] ].\n  left. apply PH0.\n  left. apply PH0.\n  left. apply PH1.\n  right. split. apply QH. apply RH.\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★ (or_distributes_over_and)\n *)\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n  (* -> *)\n    intro H.\n    inversion H as [ PH | [ QH RH ] ].\n    (* P *)\n      split.\n      left. apply PH.\n      left. apply PH.\n    (* Q /\\ R*)\n      split.\n      right. apply QH.\n      right. apply RH.\n  (* <- *)\n    intro H.\n    inversion H as [ [PH0 | QH] [PH1 | RH] ].\n    left. apply PH0.\n    left. apply PH0.\n    left. apply PH1.\n    right. split. apply QH. apply RH.\nQed.\n(* ☐ *)\n\n\n(* ∧ 、 ∨ のandb 、orb への関連付け *)\n\nTheorem andb_true__and : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H. Qed.\n\nTheorem and__andb_true : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\n(*\n練習問題: ★ (bool_prop)\n *)\n\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  intros b c H.\n  destruct b.\n    destruct c.\n    (* b = true, c = true *)\n      simpl in H.\n      inversion H.\n\n    (* b = true, c = false *)\n      right. reflexivity.\n\n  (* b = false *)\n    left. reflexivity.\nQed.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H.\n  destruct b.\n    left. reflexivity.\n\n    destruct c.\n      right. reflexivity.\n\n      simpl in H.\n      inversion H.\nQed.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H.\n  destruct b.\n    destruct c.\n      simpl in H. inversion H.\n\n      simpl in H. inversion H.\n\n    destruct c.\n      simpl in H. inversion H.\n\n      split. reflexivity. reflexivity.\nQed.\n(* ☐ *)\n\n(* 偽であるということ *)\n\n(* Inductive False : Prop := . *)\nCheck False_ind.\n\n(*\n練習問題: ★ (False_ind_principle)\n\n「偽」に関する帰納的な公理を何か思いつくことができますか？\n *)\n\n(* 帰納的な命題は無い? *)\n\n(* ☐ *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof.\n  intros contra.\n  inversion contra. Qed.\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra. Qed.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P contra.\n  inversion contra. Qed.\n\n\n(* 真であるということ *)\n\n(*\n練習問題: ★★ (True_induction)\n\nTrue を、帰納的な命題として定義しなさい。あなたの定義に対してCoqはどのような帰納的原理を生成してくれるでしょ\nうか。（直観的には True はただ当たり前のように根拠を示される命題であるべきです。代わりに、帰納的原理から帰納\n的な定義を逆にたどっていくほうが近道だと気づくかもしれません。）\n *)\n\nInductive MyTrue : Prop :=\n| T : MyTrue.\n\nCheck MyTrue_ind.\nCheck True_ind.\n\n(* ☐ *)\n\n\n(* 否定 *)\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. inversion H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~ P) -> Q.\nProof.\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.\n  apply HNA in HP. inversion HP. Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~ P.\nProof.\n  intros P H. unfold not. intros G. apply G. apply H. Qed.\n\n(*\n練習問題: ★★, recommended (double_neg_inf)\n\ndouble_neg の非形式的な証明を書きなさい。:\n\nTheorem: P implies ~~P, for any proposition P.\n *)\n\n(* Proof: ☐ *)\n\n(*\n練習問題: ★★, recommended (contrapositive)\n *)\n\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~ Q -> ~ P).\nProof.\n  intros P Q f nq p.\n  apply (nq (f p)).\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★ (not_both_true_and_false)\n *)\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~ P).\nProof.\n  intros P H.\n  inversion H as [ p np ].\n  apply (np p).\nQed.\n(* ☐ *)\n\nTheorem five_not_even :\n  ~ ev 5.\nProof.\n  unfold not. intros Hev5. inversion Hev5 as [|n Hev3 Heqn].\n  inversion Hev3 as [|n' Hev1 Heqn']. inversion Hev1. Qed.\n\n(*\n練習問題: ★ ev_not_ev_S\n\n定理 five_not_even は、「５は偶数ではない」というようなとても当たり前の事実を確認するものです。今度はもう少し\n面白い例です。\n *)\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof.\n  unfold not. intros n H. induction H.\n  (* ev_0 *)  intro H. inversion H.\n  (* ev_SS *)\n    intro H2.\n    inversion H2 as [| n' evH ].\n    apply (IHev evH).\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★ (informal_not_PNP)\n\n命題 ∀ P : Prop, ~(P ∧ ~P) の形式的でない証明を（英語で）書きなさい。\n *)\n\n(* ☐ *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~ P -> P.\nProof.\n  intros P H. unfold not in H.\n  Admitted.\n\n(*\n練習問題: ★★★★★, optional (classical_axioms)\n\nさらなる挑戦を求める人のために、 Coq'Art book (p. 123) から一つ練習問題を取り上げてみます。次の五つの文は、よ\nく「古典論理の特性」と考えられているもの（Coqにビルトインされている構成的論理の対極にあるもの）です。これらを\nCoqで証明することはできませんが、古典論理を使うことが必要なら、矛盾なく「証明されていない公理」として道具に加\nえることができます。これら五つの命題が等価であることを証明しなさい。\n *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop,\n  ~~ P -> P.\nDefinition excluded_middle := 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\n(* ☐ *)\n\n\n(* 不等であるということ *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity. Qed.\n\n(*\n練習問題: ★★, recommended (not_eq_beq_false)\n *)\n\nLemma eq_nat_dec :\n  forall n m : nat, S n <> S m -> n <> m.\nProof.\n  intros n m H eq. apply H.\n  rewrite <- eq. reflexivity.\nQed.\n\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m as [| m' ].\n  (* m = 0 *)\n    destruct n as [| n' ].\n    (* n = 0 *)\n      intros H.\n      apply ex_falso_quodlibet. apply H.\n      reflexivity.\n    (* n = S n' *)\n      intros H. reflexivity.\n  (* m = S m' *)\n    destruct n as [| n' ].\n    (* n = 0 *) intros H. reflexivity.\n    (* n = S n' *)\n      intros H. simpl.\n      apply IHm'.\n      apply eq_nat_dec.\n      exact H.\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★★, optional (beq_false_not_eq)\n *)\n\nLemma eq_nat_inc :\n  forall n m : nat, n <> m -> S n <> S m.\nProof.\n  intros n m H eq. apply H.\n  inversion eq as [ eq' ]. reflexivity.\nQed.\n\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m as [| m' ].\n  (* m = 0 *)\n    destruct n as [| n' ].\n    (* n = 0 *) simpl. intros eqH eq. discriminate eqH.\n    (* n = S n' *) simpl. intros eqH eq. discriminate eq.\n  (* m = S m' *)\n    destruct n as [| n' ].\n    (* n = 0 *)\n      simpl. intros eqH eq. discriminate eq.\n    (* n = S n' *)\n      simpl. intros eqH. apply eq_nat_inc.\n      apply IHm'. exact eqH.\nQed.\n(* ☐ *)\n\n\n(* 存在量化子 *)\n\nInductive ex (X:Type) (P : X -> Prop) : Prop :=\n  ex_intro : forall (witness:X), P witness -> ex X P.\n\nDefinition some_nat_is_even : Prop :=\n  ex nat ev.\n\nDefinition sine : some_nat_is_even :=\n  ex_intro _ ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\nNotation \"'exists' x , p\" :=\n  (ex _ (fun x => p)) (at level 200, x ident, right associativity) : type_scope.\nNotation \"'exists' x : X , p\" :=\n  (ex _ (fun x:X => p)) (at level 200, x ident, right associativity) : type_scope.\n\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2).\n  reflexivity. Qed.\n\nExample exists_example_1' : exists n, n + (n * n) = 6.\nProof.\n  exists 2.\n  reflexivity. Qed.\n\nTheorem exists_example_2 :\n  forall n, (exists m, n = 4 + m) -> (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練習問題: ★ (english_exists)\n\n英語では、以下の命題は何を意味しているでしょうか？\n      ex nat (fun n => ev (S n))\n\n次の証明オブジェクトの定義を完成させなさい\n *)\n\nDefinition p : ex nat (fun n => ev (S n)) :=\n  ex_intro _ (fun n => ev (S n)) 1 (ev_SS 0 ev_0).\n(* ☐ *)\n\n(*\n練習問題: ★ (dist_not_exists)\n\n\"全ての x についてP が成り立つ\" ということと \" P を満たさない x は存在しない\" というこ\nとが等価であることを証明しなさい。\n *)\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 PH NH.\n  inversion NH as [x NP].\n  apply NP. apply PH.\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★★★, optional (not_exists_dist)\n\n一方、古典論理の「排中律（law of the excluded middle）」が必要とされる場合もあります。\n *)\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  intros em X P NNP x.\n  destruct (em (P x)) as [XP | NXP].\n  (* P x *) exact XP.\n  (* ~ P x *)\n    apply ex_falso_quodlibet.\n    apply NNP. exists x. exact NXP.\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★★ (dist_exists_or)\n\n存在量化子が論理和において分配法則を満たすことを証明しなさい。\n *)\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  intros X P Q.\n  split.\n\n  (* -> *)\n  intros ePorQ. inversion ePorQ as [ x orH ].\n  destruct orH as [ PX | QX ].\n  (* P x *) left.  exists x. exact PX.\n  (* Q x *) right. exists x. exact QX.\n\n  (* <- *)\n  intros EPorEQ.\n  destruct EPorEQ as [ EP | EQ ].\n\n  (* P x *)\n  inversion EP as [ x PX ].\n  exists x. left.  exact PX.\n\n  (* Q x *)\n  inversion EQ as [ x QX ].\n  exists x. right. exact QX.\nQed.\n(* ☐ *)\n\n\n(* 等しいということ（同値性） *)\n\nModule MyEquality.\n\nInductive eq (X:Type) : X -> X -> Prop :=\n  refl_equal : forall x, eq X x x.\n\nNotation \"x = y\" :=\n  (eq _ x y) (at level 70, no associativity) : type_scope.\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n  refl_equal' : eq' X x x.\n\nNotation \"x =' y\" :=\n  (eq' _ x y) (at level 70, no associativity) : type_scope.\n\n(*\n練習問題: ★★★, optional (two_defs_of_eq_coincide)\n\nこれら二つの定義が等価であることを確認しなさい。\n *)\n\nTheorem two_defs_of_eq_coincide : forall (X:Type) (x y : X),\n  x = y <-> x =' y.\nProof.\n  intros X x y.\n  split.\n\n  (* -> *)\n  intros eqH.\n  inversion eqH as [ x' y' eqT ].\n  apply refl_equal'.\n\n  (* <- *)\n  intros eqH.\n  inversion eqH as [ eqT ].\n  apply refl_equal.\nQed.\n(* ☐ *)\n\nCheck eq'_ind.\n\nDefinition four : 2 + 2 = 1 + 3 :=\n  refl_equal nat 4.\nDefinition singleton :\n  forall (X:Set) (x:X), [] ++ [x] = x::[] :=\n  fun (X:Set) (x:X) => refl_equal (list X) [x].\n\nEnd MyEquality.\n\n\n(* Inversion 再び *)\n\n(* 命題としての関係 *)\n\nModule LeFirstTry.\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\nEnd LeFirstTry.\n\nInductive le (n:nat) : nat -> Prop :=\n| le_n : le n n\n| le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nCheck le_ind.\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. Qed.\n\nTheorem test_le3 :\n  ~ (2 <= 1).\nProof.\n  intros H. inversion H. inversion H1. Qed.\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 (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\n(*\n練習問題: ★★, recommended (total_relation)\n\n二つの自然数のペア同士の間に成り立つ帰納的な関係 total_relation を定義しなさ\nい。\n *)\n\nLemma le_dec_R :\n  forall {n m}, n <= S m -> n <= m \\/ n = S m.\n(* -> *)\nProof.\n  intros n m H0.\n  inversion H0 as [ eq | m' H1 eq ].\n  (* le_n *) right. reflexivity.\n  (* le_S *) left.  exact H1.\nQed.\n\nLemma le_dec_L :\n  forall {n m}, n <= m \\/ n = S m -> n <= S m.\n(* <- *)\nProof.\n  intros n m H.\n  destruct H as [LE | EQ].\n  (* le *) apply (le_S n m LE).\n  (* eq *) rewrite <- EQ. apply le_n.\nQed.\n\nLemma le_dec :\n  forall {n m}, n <= S m <-> n <= m \\/ n = S m.\nProof.\n  split. apply le_dec_R. apply le_dec_L.\nQed.\n\nLemma inc_le_trans :\n  forall n m, n <= m <-> S n <= S m.\nProof.\n  split.\n\n  (* -> *)\n  intros H.\n  induction H as [ EQ | m' LE ].\n  (* EQ *) apply le_n.\n  (* LE *) apply le_S. apply IHLE.\n\n  (* <- *)\n    generalize dependent n.\n    induction m as [| m'].\n    (* m = 0 *)\n      intros n H.\n      inversion H as [eq | m' L].\n      (* le_n *) apply le_n.\n      (* le_S *) inversion L.\n\n    (* m = S m' *)\n      intros n H.\n      destruct (le_dec_R H) as [ LE | EQ ].\n      (* S n <= S m' *) apply le_S. apply IHm'. exact LE.\n      (* S n = S (S m') *) inversion EQ as [ EQ1 ]. apply le_n.\nQed.\n\nLemma inc_le_trans_LR :\n  forall n m, n <= m -> S n <= S m.\nProof.\n  intros n m.\n  destruct (inc_le_trans n m) as [ LR RL ].\n  exact LR.\nQed.\n\nLemma inc_le_trans_RL :\n  forall n m,  S n <= S m -> n <= m.\nProof.\n  intros n m.\n  destruct (inc_le_trans n m) as [ LR RL ].\n  exact RL.\nQed.\n\nLemma logic_O_le_n :\n  forall n, 0 <= n.\nProof.\n  induction n as [| n'].\n  apply le_n.\n  apply le_S.\n  apply IHn'.\nQed.\n\nInductive total_relation (R : nat -> nat -> Prop) (a b:nat) : Prop :=\n  total_order : R a b \\/ R b a -> total_relation R a b.\n\nTheorem total_order_le :\n  forall a b, total_relation le a b.\nProof.\n  intros a b.\n  apply total_order.\n  generalize dependent b.\n  induction a as [| a' IHa ].\n  (* a = 0 *)\n    intro b. left. induction b as [| b' IHb].\n      (* b = 0 *)    apply le_n.\n      (* b = S b' *) apply le_S. apply IHb.\n  (* a = S a' *)\n    intro b.\n    destruct b as [| b'].\n      (* b = 0 *)    right. apply logic_O_le_n.\n      (* b = S b' *)\n        destruct (IHa b') as [ ABH | BAH ]\n        ; [ left | right ]\n        ; apply inc_le_trans_LR\n        ; [ (* a' <= b' *) exact ABH\n          | (* b' <= a' *) exact BAH\n          ].\nQed.\n(* ☐ *)\n\n(*\n練習問題: ★★ (empty_relation)\n\n自然数の間では決して成り立たない関係 empty_relation を帰納的に定義しなさい。\n *)\n\nInductive empty_relation (a b:nat) : Prop :=\n  empty_relation_0 : S a = b /\\ S b = a -> empty_relation a b.\n\n(* ☐ *)\n\n(*\n練習問題: ★★★, recommended (R_provability)\n *)\n\nModule R.\n\n(*\n次は三つや四つの値の間に成り立つ関係を同じように定義してみましょう。例えば、\n次のような数値の三項関係が考えられます。\n\nInductive R : nat → nat → nat → Prop :=\n   | c1 : R 0 0 0\n   | c2 : ∀ m n o, R m n o → R (S m) n (S o)\n   | c3 : ∀ m n o, R m n o → R m (S n) (S o)\n   | c4 : ∀ m n o, R (S m) (S n) (S (S o)) → R m n o\n   | c5 : ∀ m n o, R m n o → R n m o.\n*)\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      + R 1 1 2\n      + R 2 2 6\n *)\n\n(* R 1 1 2 *)\n(* R 2 2 6 *)\n\n(*\n  * この関係 R の定義からコンストラクタ c5 を取り除くと、証明可能な命題の範囲\n    はどのように変わるでしょうか？端的に（１文で）説明しなさい。\n *)\n(*\n  * この関係 R の定義からコンストラクタ c4 を取り除くと、証明可能な命題の範囲\n    はどのように変わるでしょうか？端的に（１文で）説明しなさい。\n *)\n\n(* ☐ *)\n\n(*\n練習問題: ★★★, optional (R_fact)\n\n関係 R の、等値性に関する特性をあげ、それを証明しなさい。それは、もし R m n o\nが true なら m についてどんなことが言えるでしょうか？ n や o についてはどうで\nしょうか？その逆は？\n *)\n\nTheorem m_plus_n_eq_o_left :\n  forall m n o, R m n o -> m + n = o.\nProof.\n  intros m n o H.\n  induction H as [| m' n' o' H101 |  m' n' o' H011 |  m' n' o' H112 |  m' n' o' Hswap ].\n  (* c1 *) reflexivity.\n  (* c2 *) simpl. rewrite -> IHH101. reflexivity.\n  (* c3 *) rewrite <- (plus_n_Sm m' n'). rewrite -> IHH011. reflexivity.\n  (* c4 *)\n    simpl in IHH112. rewrite <- (plus_n_Sm m' n') in IHH112.\n    inversion IHH112. reflexivity.\n  (* c5 *) rewrite -> plus_comm. apply IHHswap.\nQed.\n\nLemma m_plus_n_O' :\n  forall m n, m + n = 0 -> m = 0.\nProof.\n  destruct m as [| m'].\n  (* m = 0 *) reflexivity.\n  (* m = S m' *)\n    intros n H.\n    simpl in H. inversion H.\nQed.\n\nLemma m_plus_n_O :\n  forall m n, m + n = 0 -> m = 0 /\\ n = 0.\nProof.\n  split.\n\n  (* m = 0 *)\n  apply (m_plus_n_O' m n).\n  exact H.\n\n  (* n = 0 *)\n  rewrite -> (plus_comm m n) in H.\n  apply (m_plus_n_O' n m).\n  exact H.\nQed.\n\nTheorem m_plus_n_eq_o_right :\n  forall m n o, m + n = o -> R m n o.\nProof.\n  intros m n o H.\n  generalize dependent m.\n  generalize dependent n.\n\n  induction o as [| o'].\n  (* o = 0 *)\n    intros n m H.\n    apply m_plus_n_O in H. inversion H.\n    rewrite -> H0. rewrite -> H1.\n    apply c1.\n\n  (* o = S o' *)\n    intros n m H.\n\n    (* c2 *)\n      destruct m as [| m'].\n      (* m = 0*)\n        destruct n as [| n'].\n        (* n = 0 *) inversion H.\n        (* n = S n'*)\n        simpl in H. apply c3. apply (IHo' n' 0). inversion H. reflexivity.\n\n      (* m = S m' *)\n        apply c2. apply IHo'. simpl in H. inversion H. reflexivity.\nQed.\n\n\n(* true なら -> 真なら *)\n\n(* ☐ *)\n\nEnd R.\n\n(*\n練習問題: ★★★, recommended (all_forallb)\n\nリストに関する属性 all を定義しなさい。それは、型 X と属性 P : X → Prop をパ\nラメータとし、 all X P l が「リスト l の全ての要素が属性 P} を満たす」とする\nものです。\n *)\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n| all_nil  : all X P []\n| all_cons : forall x xs, P x -> all X P xs -> all X P (x :: xs)\n.\n\n(*\nPoly.v の練習問題 forall_exists_challenge に出てきた関数 forallb を思い出して\nみましょう。\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\n(*\n属性 all を使って関数 forallb の仕様を書き、それを満たすことを証明しなさい。\nできるだけその仕様が厳格になるようにすること。\n\n関数 forallb の重要な性質が、あなたの仕様から洩れている、ということはありませ\nんか？\n *)\n\nTheorem all_forallb :\n  forall {X} (test : X -> bool) (xs : list X),\n    forallb test xs = true <-> all X (fun x => test x = true) xs.\nProof.\n  intros X test xs. split.\n\n  (* -> *)\n  induction xs as [| x xs'].\n  (* [] *)  intros EQ. apply all_nil.\n  (* x :: xs' *)\n    simpl.\n    intros EQ.\n    destruct (test x) as [] eqn: TxH.\n    (* true *)\n      apply all_cons. apply TxH.\n      apply IHxs'. apply EQ.\n    (* false *) inversion EQ.\n\n  (* <- *)\n  induction xs as [| x xs'].\n  (* [] *) reflexivity.\n  (* x :: xs' *)\n    intros H.\n    inversion H as [| x0 xs0 P AP].\n    simpl. rewrite -> P.\n    apply IHxs'. apply AP.\nQed.\n\n(* ☐ *)\n\n(*\n練習問題: ★★★★, optional (filter_challenge)\n\nCoq の主な目的の一つは、プログラムが特定の仕様を満たしていることを証明するこ\nとです。それがどういうことか、filter 関数の定義が仕様を満たすか証明してみまし\nょう。まず、その関数の仕様を非形式的に書き出してみます。\n\n集合 X と関数 test: X→bool、リストl とその型 list X を想定する。さらに、l が\n二つのリスト l1 と l2 が順序を維持したままマージされたもので、リスト l1 の要\n素はすべて test を満たし、 l2 の要素はすべて満たさないとすると、filter test l\n= l1 が成り立つ。\n\nリスト l が l1 と l2 を順序を維持したままマージしたものである、とは、それが\nl1 と l2 の要素をすべて含んでいて、しかも互いに入り組んではいても l1 、 l2 の\n要素が同じ順序になっている、ということです。例えば、\n\n    [1,4,6,2,3]\n\nは、以下の二つを順序を維持したままマージしたものです。\n    [1,6,2]\n\nと、\n    [4,3]\n\n課題は、この仕様をCoq の定理の形に書き直し、それを証明することです。（ヒント\n：まず、一つのりすとが二つのリストをマージしたものとなっている、ということを\n示す定義を書く必要がありますが、これは帰納的な関係であって、 Fixpoint で書く\nようなものではありません。）\n *)\n\nInductive in_order_merge {X:Type} : list X -> list X -> list X -> Prop :=\n| merge_nil : in_order_merge [] [] []\n| merge_cons_L : forall (x:X) (l1 l2 l : list X),\n                 in_order_merge l1 l2 l -> in_order_merge (x::l1) l2 (x::l)\n| merge_cons_R : forall (x:X) (l1 l2 l : list X),\n                 in_order_merge l1 l2 l -> in_order_merge l1 (x::l2) (x::l)\n.\n\n(*\n集合 X と関数 test: X→bool、リストl とその型 list X を想定する。さらに、l が\n二つのリスト l1 と l2 が順序を維持したままマージされたもので、リスト l1 の要\n素はすべて test を満たし、 l2 の要素はすべて満たさないとすると、filter test l\n= l1 が成り立つ。\n *)\n\nTheorem filter_challenge :\n  forall {X:Type} (test : X -> bool) (l l1 l2 : list X),\n    in_order_merge l1 l2 l ->\n    all X (fun x => test x = true) l1 ->\n    all X (fun x => test x = false) l2 ->\n    filter test l = l1.\nProof.\n  intros X test.\n  induction l as [| x xs] eqn: LEQ.\n  (* [] *) intros l1 l2 M. inversion M. reflexivity.\n  (* x :: xs*)\n    intros l1 l2 M T F.\n    inversion M as [| x0 xsL xsR xs0 ML E0 E1 E2 | x0 xsL xsR xs0 MR E0 E1 E2].\n    (* L *)\n\n    (* R *)\nAdmitted.\n(* ☐ *)\n\n(*\n練習問題: ★★★★★, optional (filter_challenge_2)\n\nfilter の振る舞いに関する特性を別の切り口で表すとこうなります。「test の結果\nが true なる要素だけでできた、リスト l のすべての部分リストの中で、filter\ntest l が最も長いリストである。」これを形式的に記述し、それを証明しなさい。\n *)\n(* ☐ *)\n\n(*\n練習問題: ★★★★, optional (no_repeats)\n\n次の、帰納的に定義された命題は、\n\nInductive appears_in {X:Type} (a:X) : list X → Prop :=\n  | ai_here : ∀ l, appears_in a (a::l)\n  | ai_later : ∀ b l, appears_in a l → appears_in a (b::l).\n\n値 a がリスト l の要素として少なくとも一度は現れるということを言うための、精\n確な方法を与えてくれます。\n\n次の二つはappears_in に関するウォームアップ問題です。\n *)\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\nLemma appears_in_app :\n  forall {X:Type} (xs ys : list X) (x:X),\n     appears_in x (xs ++ ys) -> appears_in x xs \\/ appears_in x ys.\nProof.\nAdmitted.\n\nLemma app_appears_in :\n  forall {X:Type} (xs ys : list X) (x:X),\n    appears_in x xs \\/ appears_in x ys -> appears_in x (xs ++ ys).\nProof.\nAdmitted.\n\n(*\nでは、 appears_in を使って命題 disjoint X l1 l2 を定義してください。これは、\n型 X の二つのリスト l1 、 l2 が共通の要素を持たない場合にのみ証明可能な命題で\nす。\n\n次は、 appears_in を使って帰納的な命題 no_repeats X l を定義してください。こ\nれは, 型 X のリスト l の中のどの要素も、他の要素と異なっている場合のみ証明で\nきるような命題です。例えば、 no_repeats nat [1,2,3,4] や no_repeats bool []\nは証明可能ですが、 no_repeats nat [1,2,1] や no_repeats bool [true,true] は証\n明できないようなものです。\n\n最後に、disjoint、 no_repeats、 ++ （リストの結合）の三つを使った、何か面白い\n定理を考えて、それを証明してください。\n *)\n\n(* ☐ *)\n\n(* 少し脱線: <= と < についてのさらなる事実 *)\n\n(* 練習問題: ★★, optional (le_exercises) *)\n\nTheorem O_le_n :\n  forall 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 :\n  forall n m, n <= m -> S n <= S m.\nProof.\n  intros n m H.\n  induction H as [EQ | m' LE].\n  (* EQ *) apply le_n.\n  (* LE *) apply le_S. apply IHLE.\nQed.\n\nTheorem Sn_le_Sm__n_le_m :\n  forall n m, S n <= S m -> n <= m.\nProof.\n  intros n m. generalize dependent n.\n  induction m as [| m'].\n  (* m = 0 *)\n    intros n H.\n    inversion H as [eq | m' L].\n    (* le_n *) apply le_n.\n    (* le_S *) inversion L.\n\n  (* m = S m' *)\n    intros n H.\n    destruct (le_dec_R H) as [LE | EQ].\n    (* S n <= S m' *) apply le_S. apply IHm'. apply LE.\n    (* S n = S (S m') *) inversion EQ as [ EQ1 ]. apply le_n.\nQed.\n\nTheorem le_plus_l :\n  forall a b, a <= a + b.\nProof.\n  induction a as [| a'].\n  (* a = 0 *) apply O_le_n.\n  intro b.\n  rewrite <- (plus_1_l a').\n  rewrite <- (plus_assoc 1 a' b).\n  simpl.\n  apply n_le_m__Sn_le_Sm.\n  apply IHa'.\nQed.\n\nTheorem plus_lt :\n  forall n1 n2 m,\n    n1 + n2 < m -> n1 < m /\\ n2 < m.\nProof.\n  intros n1 n2 m.\n  generalize dependent n2.\n  generalize dependent n1.\n  induction m as [| m'].\n  (* m = 0 *) intros n1 n2 H. inversion H.\n  (* m = S m' *)\n    intros n1 n2 H.\n    apply le_dec_R in H.\n    destruct H as [LE | EQ].\n    (* LE *)\n    apply IHm' in LE.\n    inversion LE as [n1H n2H].\n    split.\n      apply le_S. apply n1H.\n      apply le_S. apply n2H.\n\n    (* EQ *)\n    rewrite <- EQ.\n    split.\n      apply n_le_m__Sn_le_Sm. apply le_plus_l.\n      apply n_le_m__Sn_le_Sm. rewrite plus_comm. apply le_plus_l.\nQed.\n\nTheorem lt_S :\n  forall n m, n < m -> n < S m.\nProof.\n  intros n m H. apply le_S. apply H.\nQed.\n\nTheorem ble_nat_true :\n  forall n m, ble_nat n m = true -> n <= m.\nProof.\n  induction n as [| n'].\n  (* n = 0 *) intros m H. apply O_le_n.\n  (* n = S n' *)\n    destruct m as [| m'].\n    (* m = 0 *) intros H. inversion H.\n    (* m = S m' *)\n      simpl. intros H.\n      apply n_le_m__Sn_le_Sm. apply IHn'.  apply H.\nQed.\n\nTheorem ble_nat_n_Sn_false :\n  forall n m,\n    ble_nat n (S m) = false ->\n    ble_nat n m = false.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m as [| m'].\n  (* m = 0 *)\n    destruct n as [| n'].\n    (* n = 0 *) simpl. intro H. inversion H.\n    (* n = S n' *) simpl. intro H. reflexivity.\n\n  (* m = S m' *)\n    intros n H.\n    destruct n as [| n'].\n    (* n = 0 *) simpl in H. inversion H.\n    (* n = S n' *)\n      simpl. apply IHm'.\n      simpl in H. apply H.\nQed.\n\nTheorem ble_nat_false :\n  forall n m,\n    ble_nat n m = false -> ~(n <= m).\nProof.\n  induction n as [| n'].\n  (* n = 0 *)\n    destruct m as [| m'].\n    (* 0 *)   simpl. intro H. inversion H.\n    (* S m'*) simpl. intro H. inversion H.\n  (* n = S n' *)\n    intros m H.\n    destruct m as [| m'].\n    (* 0 *) intro LE. inversion LE.\n    (* S m' *)\n      simpl in H.\n      intro LE.\n      apply Sn_le_Sm__n_le_m in LE.\n      apply (IHn' m').\n      apply H. apply LE.\nQed.\n(* ☐ *)\n\n\n(* 練習問題: ★★★, recommended (nostutter) *)\n\n(*\n述語の帰納的な定義を定式化できるようになるというのは、これから先の学習に必要なスキ\nルになってきます。\n\nこの練習問題は、何の力も借りず自力で解いてください。もし誰かの力を借りてしまった場\n合は、そのことをコメントに書いておいてください。\n\n同じ数値が連続して現れるリストを \"stutters\" （どもったリスト）と呼ぶことにします。\n述語 \"nostutter mylist\" は、 mylist が「どもったリスト」でないことを意味しています\n。nostutter の帰納的な定義を記述しなさい。（これは以前の練習問題に出てきた\nno_repeats という述語とは異なるものです。リスト 1,4,1 は repeats ではありますが\nstutter ではありません。）\n *)\n\nInductive nostutter: list nat -> Prop :=\n\n.\n\n(*\nできた定義が、以下のテストを通過することを確認してください。通過できないものがあっ\nたら、定義を修正してもかまいません。あなたの書いた定義が、正しくはあるけれど私の用\n意した模範解答と異なっているかもしれません。その場合、このテストを通過するために別\nの証明を用意する必要があります。\n\n以下の Example にコメントとして提示された証明には、色々な種類の nostutter の定義に\n対応できるようにするため、まだ説明していないタクティックがいくつか使用されています\n。まずこれらのコメントをはずしただけの状態で確認できればいいのですが、もしそうした\nいなら、これらの証明をもっと基本的なタクティックで書き換えて証明してもかまいません\n。\n *)\n\nExample test_nostutter_1: nostutter [3,1,4,1,5,6].\nAdmitted.\n\nExample test_nostutter_2: nostutter [].\nAdmitted.\n\nExample test_nostutter_3: nostutter [5].\nAdmitted.\n\nExample test_nostutter_4: not (nostutter [3,1,1,4]).\nAdmitted.\n(* ☐ *)\n\n(* 練習問題: ★★★★, optional (pigeonhole principle) *)\n\n(*\n「鳩の巣定理（ \"pigeonhole principle\" ）」は、「数えるあげる」ということについての\n基本的な事実を提示しています。「もし n 個の鳩の巣に n 個より多い数のものを入れよう\nとするなら、どのような入れ方をしてもいくつかの鳩の巣には必ず一つ以上のものが入るこ\nとになる。」というもので、この、数値に関する見るからに自明な事実を証明するにも、な\nかなか自明とは言えない手段が必要になります。我々は既にそれを知っているのですが...\n\nまず、補題を二つほど証明しておきます。（既に数値のリストについては証明済みのもので\nすが、任意のリストについてはのものはまだないので）\n *)\n\nLemma app_length :\n  forall {X:Type} (l1 l2 : list X),\n    length (l1 ++ l2) = length l1 + length l2.\nProof.\nAdmitted.\n\nLemma appears_in_app_split :\n  forall {X:Type} (x:X) (l:list X),\n    appears_in x l ->\n    exists l1, exists l2, l = l1 ++ (x::l2).\nProof.\nAdmitted.\n\n(*\nそして、述語 repeats の定義をします（以前の練習問題 no_repeats に類似したものです\n）。それは repeats X l が、「 l の中に少なくとも一組の同じ要素（型 X の）を含む」\nという主張となるようなものです。\n *)\n\nInductive repeats {X:Type} : list X -> Prop :=\n\n.\n\n(*\nこの「鳩の巣定理」を定式化する方法を一つ挙げておきましょう。リスト l2 が鳩の巣に貼\nられたラベルの一覧を、リスト l1 はそのラベルの、アイテムへの割り当ての一覧を表して\nいるとします。もしラベルよりも沢山のアイテムがあったならば、少なくとも二つのアイテ\nムに同じラベルが貼られていることになります。おそらくこの証明には「排中律（\nexcluded_middle ）」が必要になるでしょう。\n *)\n\nTheorem pigeonhole_principle:\n  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. intros X l1. induction l1.\nAdmitted.\n(* ☐ *)\n\n(* 選択課題 *)\n\n(* ∧ や ∨ のための帰納法の原理 *)\n\n(* 練習問題: ★ (and_ind_principle) *)\n\n(*\n連言（ conjunction ）についての帰納法の原理を予想して、確認しなさい。\n *)\n\n(* ☐ *)\n\n(* 練習問題: ★ (or_ind_principle) *)\n\n(*\n選言（ disjunction ）についての帰納法の原理を予想して、確認しなさい。\n *)\n\n(* ☐ *)\n\nCheck and_ind.\n\n\nInductive or' (P Q : Prop) : Prop :=\n| or'_introl : P -> or' P Q\n| or'_intror : Q -> or' P Q\n.\n\nCheck or'_ind.\n\nDefinition nrect :=\nfun (P : nat -> Type) (f : P 0)\n    (f0 : forall n : nat, P n -> P(S n)) =>\n  fix F (n : nat) : P n :=\n  match n return (P n) with\n    | 0 => f\n    | S n0 => f0 n0 (F n0)\n  end.\n\n(* 帰納法のための明白な証明オブジェクト *)\n", "meta": {"author": "khibino", "repo": "sfja-code", "sha": "2b9f6c561b56652aa67bbc0971db90a211c66373", "save_path": "github-repos/coq/khibino-sfja-code", "path": "github-repos/coq/khibino-sfja-code/sfja-code-2b9f6c561b56652aa67bbc0971db90a211c66373/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7228804646436389}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(************************************************************************\n\n    Definition of the Euler Totient function\n\n*************************************************************************)\nRequire Import ZArith.\nRequire Export Znumtheory.\nRequire Import Tactic.\nRequire Export ZSum.\n\nOpen Scope Z_scope.\n\nDefinition phi n := Zsum 1 (n - 1) (fun x => if rel_prime_dec x n then 1 else 0).\n\nTheorem phi_def_with_0:\n  forall n, 1< n -> phi n = Zsum 0 (n - 1) (fun x => if rel_prime_dec x n then 1 else 0).\nintros n H; rewrite Zsum_S_left; auto with zarith.\ncase (rel_prime_dec 0 n); intros H2.\ncontradict H2; apply not_rel_prime_0; auto.\nrewrite Zplus_0_l; auto.\nQed.\n\nTheorem phi_pos: forall n, 1 < n -> 0 < phi n.\nintros n H; unfold phi.\ncase (Zle_lt_or_eq 2 n); auto with zarith; intros H1; subst.\nrewrite Zsum_S_left; simpl; auto with zarith.\ncase (rel_prime_dec 1 n); intros H2.\napply Z.lt_le_trans with (1 + 0); auto with zarith.\napply Zplus_le_compat_l.\npattern 0 at 1; replace 0 with  ((1 + (n - 1) - 2) * 0); auto with zarith.\nrewrite <- Zsum_c; auto with zarith.\napply Zsum_le; auto with zarith.\nintros x H3;  case (rel_prime_dec x n); auto with zarith.\ncase H2; apply rel_prime_1; auto with zarith.\nrewrite Zsum_nn.\ncase (rel_prime_dec (2 - 1) 2); auto with zarith.\nintros H1; contradict H1; apply rel_prime_1; auto with zarith.\nQed.\n\nTheorem phi_le_n_minus_1: forall n, 1 < n -> phi n <= n - 1.\nintros n H; replace (n-1) with ((1 +  (n - 1) - 1) * 1); auto with zarith.\nrewrite <- Zsum_c; auto with zarith.\nunfold phi; apply Zsum_le; auto with zarith.\nintros x H1; case (rel_prime_dec x n); auto with zarith.\nQed.\n\nTheorem prime_phi_n_minus_1: forall n, prime n -> phi n = n - 1.\nintros n H; replace (n-1) with ((1 +  (n - 1) - 1) * 1); auto with zarith.\nassert (Hu: 1 <= n - 1).\nassert (2 <= n); auto with zarith.\napply prime_ge_2; auto.\nrewrite <- Zsum_c; auto with zarith; unfold phi; apply Zsum_ext; auto.\nintros x  (H2, H3); case H; clear H; intros H H1.\ngeneralize (H1 x); case (rel_prime_dec x n); auto with zarith.\nintros H6 H7; contradict H6; apply H7; split; auto with zarith.\nQed.\n\nTheorem phi_n_minus_1_prime: forall n, 1 < n -> phi n = n - 1 -> prime n.\nintros n H H1; case (prime_dec n); auto; intros H2.\nassert (H3: phi n < n - 1); auto with zarith.\nreplace (n-1) with ((1 +  (n - 1) - 1) * 1); auto with zarith.\nassert (Hu: 1 <= n - 1); auto with zarith.\nrewrite <- Zsum_c; auto with zarith; unfold phi; apply Zsum_lt; auto.\nintros x _; case (rel_prime_dec x n); auto with zarith.\ncase not_prime_divide with n; auto.\nintros x (H3, H4); exists x; repeat split; auto with zarith.\ncase (rel_prime_dec x n); auto with zarith.\nintros H5; absurd (x = 1 \\/ x = -1); auto with zarith.\ncase (Zis_gcd_unique  x n x 1); auto.\napply Zis_gcd_intro; auto; exists 1; auto with zarith.\ncontradict H3; rewrite H1; auto with zarith.\nQed.\n\nTheorem phi_divide_prime: forall n, 1 < n -> (n - 1 | phi n) -> prime n.\nintros n H1 H2; apply  phi_n_minus_1_prime; auto.\napply Zle_antisym.\napply phi_le_n_minus_1; auto.\napply Zdivide_le; auto; auto with zarith.\napply phi_pos; auto.\nQed.\n", "meta": {"author": "thery", "repo": "coqprime", "sha": "431d7a66877cbe8688fc8864ef892369401440e1", "save_path": "github-repos/coq/thery-coqprime", "path": "github-repos/coq/thery-coqprime/coqprime-431d7a66877cbe8688fc8864ef892369401440e1/src/Coqprime/PrimalityTest/Euler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7228249118612511}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nInductive binop : Set := Plus | Times.\nInductive exp : Type :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp.\n\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n  match b with\n  | Plus => plus\n  | Times => mult\n  end.\n\nFixpoint expDenote (e : exp): nat :=\n  match e with\n  | Const n => n\n  | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n  end.\n\nEval simpl in expDenote (Const 42).\nEval simpl in expDenote (Binop Times (Const 5) (Binop Plus (Const 2) (Const 3))).\n\nInductive instr : Set :=\n| iConst : nat -> instr\n| iBinop : binop -> instr.\n\nDefinition prog := list instr.\nDefinition stack := list nat.\n\nDefinition instrDenote (i : instr) (s : stack) : option stack :=\n  match i with\n  | iConst n => Some (n :: s)\n  | iBinop b =>\n    match s with\n    | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')\n    | _ => None\n    end\n  end.\n\nFixpoint progDenote (p : prog) (s : stack) : option stack :=\n  match p with\n  | nil => Some s\n  | i :: p' =>\n    match instrDenote i s with\n      | None => None\n      | Some s' => progDenote p' s'\n    end\n  end.\n\nFixpoint compile (e : exp) : prog :=\n  match e with\n  | Const n => iConst n :: nil\n  | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil\n  end.\n\nEval simpl in progDenote (compile (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7))) nil.\n\nTheorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).\nAbort.\n\nLemma compile_correct' : forall e p s,\n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n  induction e.\n  intros.\n  unfold expDenote.\n  unfold progDenote at 1.\n  simpl.\n  fold progDenote.\n  reflexivity.\n  intros.\n  unfold compile.\n  fold compile.\n  unfold expDenote.\n  fold expDenote.\n  Check app_assoc_reverse.\n  rewrite app_assoc_reverse.\n  rewrite IHe2.\n  rewrite app_assoc_reverse.\n  rewrite IHe1.\n  unfold progDenote at 1.\n  simpl.\n  fold progDenote.\n  reflexivity.\nQed.\n\nLemma compile_crush : forall e p s,\n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n  induction e; crush.\nQed.\n\nTheorem compile_correct : forall e, progDenote (compile e) nil = Some (expDenote e :: nil).\n  intros.\n  Check app_nil_end.\n  rewrite (app_nil_end (compile e)).\n  rewrite compile_correct'.\n  reflexivity.\nQed.\n\nInductive type : Set := Nat | Bool.\n\nInductive tbinop : type -> type -> type -> Set :=\n| TPlus : tbinop Nat Nat Nat\n| TTimes : tbinop Nat Nat Nat\n| TEq : forall t, tbinop t t Bool\n| TLt: tbinop Nat Nat Bool.\n\nInductive texp : type -> Set :=\n| TNConst : nat -> texp Nat\n| TBConst : bool -> texp Bool\n| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\nDefinition typeDenote (t : type) : Set :=\n  match t with\n  | Nat => nat\n  | Bool => bool\n  end.\n\nDefinition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b with\n  | TPlus => plus\n  | TTimes => mult\n  | TEq Nat => beq_nat\n  | TEq Bool => eqb\n  | TLt => leb\n  end.\n\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n  | TNConst n => n\n  | TBConst b => b\n  | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nEval simpl in texpDenote (TNConst 42).\n\nDefinition tstack := list type.\n\nInductive tinstr : tstack -> tstack -> Set :=\n| TiNConst : forall s, nat -> tinstr s (Nat :: s)\n| TiBConst : forall s, bool -> tinstr s (Bool :: s)\n| TiBinop : forall arg1 arg2 res s,\n    tbinop arg1 arg2 res -> tinstr (arg1 :: arg2 :: s)(res :: s).\n\nInductive tprog : tstack -> tstack -> Set :=\n| TNil : forall s, tprog s s\n| TCons : forall s1 s2 s3,\n    tinstr s1 s2\n    -> tprog s2 s3\n    -> tprog s1 s3.\n\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n  | nil => unit\n  | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\n(*\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n  | TiNConst _ n => fun s => (n, s)\n  | TiBConst _ b => fun s => (b, s)\n  | TiBinop _ _ _ _ b => fun s => let '(arg1, (arg2, s')) := s in\n                                  ((tbinopDenote b) arg1, arg2, s')\n  end.\n *)\n\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n    | TiNConst _ n => fun s => (n, s)\n    | TiBConst _ b => fun s => (b, s)\n    | TiBinop _ _ _ _ b => fun s =>\n      let '(arg1, (arg2, s')) := s in\n        ((tbinopDenote b) arg1 arg2, s')\n  end.\n\nFixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n  | TNil _ => fun s => s\n  | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\nFixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n  | TNil _ => fun p' => p'\n  | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=\n  match e with\n  | TNConst n => TCons (TiNConst _ n) (TNil _)\n  | TBConst b => TCons (TiBConst _ b) (TNil _)\n  | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)\n                                    (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\nEval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.\n", "meta": {"author": "artagnon", "repo": "proofsauce", "sha": "9465e197d95c1dfb22ff8f52bd74e66b0ce2f48e", "save_path": "github-repos/coq/artagnon-proofsauce", "path": "github-repos/coq/artagnon-proofsauce/proofsauce-9465e197d95c1dfb22ff8f52bd74e66b0ce2f48e/theories/cpdt/cpdt01.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8221891218080991, "lm_q1q2_score": 0.7228249061156854}}
{"text": "Require Import Arith Bool.\n\nSet Implicit Arguments.\n\n\n(** * Easy reflection example: evenness of [nat]s *)\n\nInductive isEven : nat -> Prop :=\n  | Even_O : isEven O\n  | Even_SS : forall n, isEven n -> isEven (S (S n)).\n\nLtac prove_even :=\n  repeat (apply Even_O || apply Even_SS).\n\nTheorem even_256 : isEven 256.\n  prove_even.\nQed.\n\nPrint even_256.\n\nFixpoint check_even (n : nat) : bool :=\n  match n with\n    | 0 => true\n    | 1 => false\n    | S (S n') => check_even n'\n  end.\n\nHint Constructors isEven.\n\nLemma check_even_sound' : forall n, (check_even n = true -> isEven n)\n  /\\ (check_even (S n) = true -> isEven (S n)).\n  induction n; simpl; intuition; discriminate.\nQed.\n\nTheorem check_even_sound : forall n, check_even n = true -> isEven n.\n  intros.\n  generalize (check_even_sound' n); tauto.\nQed.\n\nLtac prove_even_reflective :=\n  apply check_even_sound; reflexivity.\n\nTheorem even_256' : isEven 256.\n  prove_even_reflective.\nQed.\n\nPrint even_256'.\n\n\n(** * Some support code: lists at sort Type *)\n\nSection listT.\n  Variable A : Type.\n  \n  Inductive listT : Type :=\n    | nilT : listT\n    | consT : A -> listT -> listT.\nEnd listT.\n\nImplicit Arguments nilT [A].\n\n\n(** * A reflective tautology solver *)\n\nInductive formula : Set :=\n  | Atomic : nat -> formula\n  | Truth : formula\n  | Falsehood : formula\n  | And : formula -> formula -> formula\n  | Or : formula -> formula -> formula\n  | Imp : formula -> formula -> formula.\n\nSection interp_formula.\n  Variable atomics : nat -> Prop.\n\n  Fixpoint interp_formula (f : formula) : Prop :=\n    match f with\n      | Atomic n => atomics n\n      | Truth => True\n      | Falsehood => False\n      | And f1 f2 => interp_formula f1 /\\ interp_formula f2\n      | Or f1 f2 => interp_formula f1 \\/ interp_formula f2\n      | Imp f1 f2 => interp_formula f1 -> interp_formula f2\n    end.\nEnd interp_formula.\n\nDefinition asgn := nat -> bool.\n\nDefinition add (f : asgn) (n : nat) :=\n  fun n' =>\n    if eq_nat_dec n' n\n      then true\n      else f n'.\n\nFixpoint forward (hyps : asgn) (hyp : formula) (cont : asgn -> bool) {struct hyp} : bool :=\n  match hyp with\n    | Atomic n => cont (add hyps n)\n    | Truth => cont hyps\n    | Falsehood => true\n    | And hyp1 hyp2 => forward hyps hyp1 (fun hyps' => forward hyps' hyp2 cont)\n    | Or hyp1 hyp2 => forward hyps hyp1 cont && forward hyps hyp2 cont\n    | Imp _ _ => cont hyps\n  end.\n\nFixpoint backward (hyps : asgn) (goal : formula) {struct goal} : bool :=\n  match goal with\n    | Atomic n => hyps n\n    | Truth => true\n    | Falsehood => false\n    | And goal1 goal2 => backward hyps goal1 && backward hyps goal2\n    | Or goal1 goal2 => backward hyps goal1 || backward hyps goal2\n    | Imp hyp goal' => forward hyps hyp (fun hyps' => backward hyps' goal')\n  end.\n\nLtac bool_simpl :=\n  repeat (match goal with\n\t    | [ H : _ |- _ ] =>\n\t      (generalize (andb_prop _ _ H)\n\t\t|| generalize (orb_prop _ _ H));\n\t      clear H; intro H\n\t  end\n  || apply andb_true_intro\n    || apply orb_true_intro).\n\nLtac simplify := repeat progress (simpl; intuition eauto; bool_simpl).\n\nHint Extern 1 False => discriminate.\n\nSection prove_sound.\n  Variable atomics : nat -> Prop.\n\n  Lemma add_sound : forall (hyps : asgn) (n : nat),\n    (forall n' : nat, hyps n' = true -> atomics n')\n    -> atomics n\n    -> forall n'', add hyps n n'' = true\n      -> atomics n''.\n    intuition.\n    unfold add in H1.\n    destruct (eq_nat_dec n'' n); subst; intuition.\n  Qed.\n\n  Hint Resolve add_sound.\n\n  Theorem forward_sound : forall (hyp : formula)\n    (hyps : nat -> bool)\n    (cont : (nat -> bool) -> bool),\n    (forall n, hyps n = true -> atomics n)\n    -> interp_formula atomics hyp\n    -> forward hyps hyp cont = true\n    -> exists hyps' : nat -> bool,\n      (forall n, hyps' n = true -> atomics n)\n      /\\ cont hyps' = true.\n    induction hyp; simplify; firstorder.\n  Qed.\n\n  Theorem backward_sound : forall (goal : formula)\n    (hyps : nat -> bool),\n    (forall n, hyps n = true -> atomics n)\n    -> backward hyps goal = true\n    -> interp_formula atomics goal.\n    induction goal; simplify;\n      generalize forward_sound; firstorder.\n  Qed.\n\n  Theorem prover : forall (goal : formula),\n    backward (fun _ => false) goal = true\n    -> interp_formula atomics goal.\n    intros.\n    apply (backward_sound goal (fun _ => false));\n      simpl; intuition; discriminate.\n  Qed.\nEnd prove_sound.\n\nFixpoint listT_atomics (ps : listT Prop) : nat -> Prop :=\n  match ps with\n    | nilT => fun _ => True\n    | consT P ps' => fun n =>\n      match n with\n\t| O => P\n\t| S n' => listT_atomics ps' n'\n      end\n  end.\n\nTheorem test1 : True.\n  apply (prover (listT_atomics nilT) Truth).\n  reflexivity.\nQed.\n\nTheorem test2 : forall (P : Prop), P -> P.\n  intro.\n  apply (prover (listT_atomics (consT P nilT)) (Imp (Atomic 0) (Atomic 0))).\n  reflexivity.\nQed.\n\nLtac add_atomic atomics P :=\n  match atomics with\n    | nilT => constr:(consT P nilT)\n    | consT P _ => atomics\n    | consT ?Q ?atomics' =>\n      let atomics'' := add_atomic atomics' P in\n\tconstr:(consT Q atomics'')\n  end.\n\nLtac enum_atomics' atomics P :=\n  match P with\n    | True => atomics\n    | False => atomics\n    | ?Q1 /\\ ?Q2 => enum_atomics' ltac:(enum_atomics' atomics Q1) Q2\n    | ?Q1 \\/ ?Q2 => enum_atomics' ltac:(enum_atomics' atomics Q1) Q2\n    | ?Q1 -> ?Q2 => enum_atomics' ltac:(enum_atomics' atomics Q1) Q2\n    | _ => add_atomic atomics P\n  end.\n\nLtac enum_atomics := enum_atomics' (@nilT Prop).\n\nLtac find_atomic atomics P :=\n  match atomics with\n    | consT P _ => constr:O\n    | consT _ ?atomics' =>\n      let n := find_atomic atomics' P in\n\tconstr:(S n)\n  end.\n\nLtac formulaify atomics P :=\n  match P with\n    | True => constr:Truth\n    | False => constr:Falsehood\n    | ?Q1 /\\ ?Q2 =>\n      let f1 := formulaify atomics Q1\n\twith f2 := formulaify atomics Q2 in\n\tconstr:(And f1 f2)\n    | ?Q1 \\/ ?Q2 =>\n      let f1 := formulaify atomics Q1\n\twith f2 := formulaify atomics Q2 in\n\tconstr:(Or f1 f2)\n    | ?Q1 -> ?Q2 =>\n      let f1 := formulaify atomics Q1\n\twith f2 := formulaify atomics Q2 in\n\tconstr:(Imp f1 f2)\n    | _ => let n := find_atomic atomics P in\n      constr:(Atomic n)\n  end.\n\nLtac prover :=\n  match goal with\n    | [ |- ?P ] =>\n      let atomics := enum_atomics P in\n\tlet f := formulaify atomics P in\n\t  apply (prover (listT_atomics atomics) f);\n\t    reflexivity\n  end.\n\nTheorem t1 : True.\n  prover.\nQed.\n\nPrint t1.\n\nTheorem t2 : 1 = 1 -> 1 = 1.\n  prover.\nQed.\n\nPrint t2.\n\nTheorem t3 : False -> 1 + 1 = 2.\n  prover.\nQed.\n\nPrint t3.\n\nTheorem t4 : forall x y, x > y -> x > y \\/ y > x.\n  do 2 intro; prover.\nQed.\n\nTheorem t5 : forall x y z, x > y \\/ x > z -> x > z \\/ x > y.\n  do 3 intro; prover.\nQed.\n\n\n(** * A quick example using the 'quote' tactic *)\n\nRequire Import Quote.\n\nInductive formula' : Set :=\n  | Atomic' : index -> formula'\n  | Truth' : formula'\n  | Falsehood' : formula'\n  | And' : formula' -> formula' -> formula'\n  | Or' : formula' -> formula' -> formula'\n  | Imp' : formula' -> formula' -> formula'.\n\nFixpoint interp_formula' (atomics : varmap Prop) (f : formula') {struct f} : Prop :=\n  match f with\n    | Atomic' v => varmap_find True v atomics\n    | Truth' => True\n    | Falsehood' => False\n    | And' f1 f2 => interp_formula' atomics f1 /\\ interp_formula' atomics f2\n    | Or' f1 f2 => interp_formula' atomics f1 \\/ interp_formula' atomics f2\n    | Imp' f1 f2 => interp_formula' atomics f1 -> interp_formula' atomics f2\n  end.\n\nTheorem t1' : True.\n  quote interp_formula'.\nAdmitted.\n\nTheorem t2' : True /\\ True.\n  quote interp_formula'.\nAdmitted.\n\nTheorem t3' : forall x y, x > y \\/ x <= y.\n  do 2 intro.\n  quote interp_formula'.\nAdmitted.\n\nTheorem t4' : True -> True.\n  quote interp_formula'.\nAdmitted.\n", "meta": {"author": "SatyendraBanjare", "repo": "itp", "sha": "80831ac497c7e000e964587eb0233adb7382ee88", "save_path": "github-repos/coq/SatyendraBanjare-itp", "path": "github-repos/coq/SatyendraBanjare-itp/itp-80831ac497c7e000e964587eb0233adb7382ee88/lecture_codes/Lect11/lecture11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7228249028240666}}
{"text": "Require Import Nijn.Prelude.\n\nDeclare Scope signature.\nOpen Scope signature.\n\n(** * Definition of simple types in an AFS *)\n\n(** Notational convention: we use [B] for the collection of base types, and simple types are named [A, A1, ...] *)\n\nInductive ty (B : Type) : Type :=\n| Base : B -> ty B\n| Fun : ty B -> ty B -> ty B.\n\nArguments Base {_} _.\nArguments Fun {_} _ _.\nNotation \"A ⟶ B\" := (Fun A B) (at level 70, right associativity) : signature.\n\n(** ** Decidable equality of types *)\n\n(** Lemmata on equality of the constructors *)\nProposition Base_nequal\n            {B : Type}\n            {b1 b2 : B}\n            (p : b1 <> b2)\n  : Base b1 <> Base b2.\nProof.\n  intro q.\n  inversion q.\n  contradiction.\nQed.\n\nProposition Base_not_Fun\n            {B : Type}\n            {A1 A2 : ty B}\n            {b : B}\n  : Base b <> (A1 ⟶ A2).\nProof.\n  discriminate.\nQed.\n\nProposition Fun_not_Base\n            {B : Type}\n            {A1 A2 : ty B}\n            {b : B}\n  : (A1 ⟶ A2) <> Base b.\nProof.\n  discriminate.\nQed.\n\nProposition eq_Fun\n            {B : Type}\n            {A1 A2 A3 A4 : ty B}\n            (p : A1 = A3)\n            (q : A2 = A4)\n  : (A1 ⟶ A2) = (A3 ⟶ A4).\nProof.\n  subst.\n  reflexivity.\nQed.\n\nProposition neq_Fun₁\n            {B : Type}\n            {A1 A2 A3 A4 : ty B}\n            (p : A1 <> A3)\n  : (A1 ⟶ A2) <> (A3 ⟶ A4).\nProof.\n  intro q.\n  inversion q.\n  contradiction.\nQed.\n\nProposition neq_Fun₂\n            {B : Type}\n            {A1 A2 A3 A4 : ty B}\n            (p : A2 <> A4)\n  : (A1 ⟶ A2) <> (A3 ⟶ A4).\nProof.\n  intro q.\n  inversion q.\n  contradiction.\nQed.\n\n(** The function that decides equality *)\nFixpoint dec_eq_Ty\n         {B : Type}\n         `{decEq B}\n         (A1 A2 : ty B)\n  : dec (A1 = A2)\n  := match A1 , A2 with\n     | Base b1 , Base b2 =>\n       match dec_eq b1 b2 with\n       | Yes p => Yes (f_equal Base p)\n       | No p => No (Base_nequal p)\n       end\n     | A1 ⟶ A2 , A3 ⟶ A4 =>\n       match dec_eq_Ty A1 A3 with\n       | Yes p =>\n         match dec_eq_Ty A2 A4 with\n         | Yes q => Yes (eq_Fun p q)\n         | No q => No (neq_Fun₂ q)\n         end\n       | No p => No (neq_Fun₁ p)\n       end\n     | _ ⟶ _ , Base _ => No Fun_not_Base\n     | Base _ , _ ⟶ _ => No Base_not_Fun\n     end.\n\nGlobal Instance decEq_Ty\n       {B : Type}\n       `{decEq B}\n  : decEq (ty B)\n  := {| dec_eq := dec_eq_Ty |}.\n", "meta": {"author": "nmvdw", "repo": "Nijn", "sha": "9bd88a93cdf0ab521536249fe628e9e63341f473", "save_path": "github-repos/coq/nmvdw-Nijn", "path": "github-repos/coq/nmvdw-Nijn/Nijn-9bd88a93cdf0ab521536249fe628e9e63341f473/Code/Syntax/Signature/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7227940454664249}}
{"text": "Require Export projective_plane_inst.\n\nModule Export uniq := (uniqueness_axioms AbstractProjectivePlane).\n \nLemma Incid_property : \nforall A B C D : Point,\nA <> B ->\nforall L1 L2: Line, \n  Incid A L1 -> Incid B L1 -> Incid C L1 ->\n  Incid A L2 -> Incid B L2 -> Incid D L2 ->\n  exists L3 : Line, \n    (Incid A L3)/\\(Incid B L3)/\\(Incid C L3)/\\(Incid D L3).\nintros A B C D.\nintros Hdistincts.\nintros D1 D2.\nintros HAD1 HBD1 HCD1 HAD2 HBD2 HDD2.\nintuition.\nelim (a1_exist A B).\nintros L1 HL1.\ncut ((D1=L1)/\\(D2=L1)).\nintros (HD1,HD2).\nexists L1.\npattern L1 at 1 2 3; rewrite <-HD1.\nrewrite <- HD2.\nintuition.\nsplit.\napply (a1_unique A B);intuition.\napply (a1_unique A B);intuition.\nQed.\n\nTheorem c :\n  (exists A:Point,exists B:Point,exists C:Point,exists D:Point, dist4 A B C D) ->\n  (exists M:Point,exists N:Point,exists P:Point,exists l:Line,\n    dist3 M N P/\\Incid M l/\\Incid N l/\\Incid P l).\nintros.\nelim H;clear H.\nintros A.\nintros Ha.\nelim Ha;clear Ha.\nintros B.\nintros Hb.\nelim Hb;clear Hb.\nintros C.\nintros Hc.\nelim Hc;clear Hc.\nintros D.\nintros H.\n\ngeneralize(a1_exist A B).\nintros Hl1;elim Hl1; clear Hl1.\nintros l1 Hl1.\nassert(A <> B).\nunfold dist4 in H.\ntauto.\nelim (incid_dec C l1).\nintros HCl1.\nexists A.\nexists B.\nexists C.\nexists l1.\nunfold dist3.\nunfold dist4 in H.\ntauto.\nintros HCl1.\nelim (incid_dec D l1).\nintros HDl1.\nexists A.\nexists B.\nexists D.\nexists l1.\nunfold dist3.\nunfold dist4 in H.\ntauto.\nintros HDl1.\n\ngeneralize(a1_exist C D).\nintros Hl2;elim Hl2; clear Hl2.\nintros l2 Hl2.\nintros.\nassert(C <> D).\nunfold dist4 in H.\ntauto.\nelim (incid_dec A l2).\nintros HAl2.\nexists C.\nexists D.\nexists A.\nexists l2.\nunfold dist3.\nunfold dist4 in *.\nintuition. (* tauto failed ??? *)\nintros HAl2.\nelim (incid_dec B l2).\nintros HBl2.\nexists C.\nexists D.\nexists B.\nexists l2.\nunfold dist3.\nunfold dist4 in *.\nsolve [intuition].\nintros HBl2. \ngeneralize (a2_exist l1 l2).\nintros HI.\nassert (l1 <> l2).\nintros Hl1l2.\nsubst l1.\napply HAl2.\ntauto.\nelim HI; clear HI; intros I HI.\nexists I.\nexists C.\nexists D.\nexists l2.\nunfold dist3.\nunfold dist4 in H.\nsplit.\nsplit.\nintros HIC.\nsubst I.\ntauto.\nsplit.\nintros HID.\nsubst I.\ntauto.\ntauto.\ntauto.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "projective-geometry", "sha": "bd3b5d752d323ee26033d07f4cc5f9ef1b96f40e", "save_path": "github-repos/coq/coq-contribs-projective-geometry", "path": "github-repos/coq/coq-contribs-projective-geometry/projective-geometry-bd3b5d752d323ee26033d07f4cc5f9ef1b96f40e/Plane/examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7227940361444573}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) (y : natural)\n  : natural := mult x y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj297_coqofml_teayJc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7227713800551475}}
{"text": "Require Import init.\n\nRequire Export topology_base.\nRequire Import topology_basis.\nRequire Import topology_axioms.\nRequire Import topology_subspace.\nRequire Import nat.\n\n(* begin hide *)\nSection ClosureInterior.\n\nLocal Open Scope set_scope.\n(* end hide *)\nDefinition closure {U} `{Topology U} A := ⋂ (λ S, closed S ∧ A ⊆ S).\nDefinition interior {U} `{Topology U} A := ⋃ (λ S, open S ∧ S ⊆ A).\n\n(* begin hide *)\nContext {U} `{Topology U}.\n(* end hide *)\nTheorem closure_closed : ∀ A, closed (closure A).\nProof.\n    intros A.\n    apply inter_closed.\n    intros S [S_closed sub].\n    exact S_closed.\nQed.\n\nTheorem interior_open : ∀ A, open (interior A).\nProof.\n    intros A.\n    apply union_open.\n    intros S [S_open sub].\n    exact S_open.\nQed.\n\nTheorem closure_sub : ∀ A, A ⊆ closure A.\nProof.\n    intros A x Ax S [S_closed sub].\n    apply sub.\n    exact Ax.\nQed.\n\nTheorem interior_sub : ∀ A, interior A ⊆ A.\nProof.\n    intros A x [S [[S_open sub] Sx]].\n    apply sub.\n    exact Sx.\nQed.\n\nTheorem in_closure : ∀ x A,\n    (closure A) x ↔ (∀ S, open S → S x → intersects A S).\nProof.\n    intros x A.\n    split.\n    -   intros A'x S S_open Sx eq.\n        apply (A'x (𝐂 S)); try exact Sx.\n        split.\n        +   unfold closed.\n            rewrite compl_compl.\n            exact S_open.\n        +   intros y Ay.\n            classic_contradiction Sy.\n            assert ((A ∩ S) y) as contr.\n            {\n                split; try exact Ay.\n                unfold 𝐂 in Sy.\n                rewrite not_not in Sy.\n                exact Sy.\n            }\n            rewrite eq in contr.\n            exact contr.\n    -   intros all_S.\n        intros B [B_closed sub].\n        classic_contradiction Bx.\n        assert (open (𝐂 B)) as B'_open by exact B_closed.\n        specialize (all_S (𝐂 B) B_closed Bx).\n        unfold intersects in all_S.\n        apply all_S.\n        apply empty_eq.\n        intros y [Ay B'y].\n        apply sub in Ay.\n        contradiction.\nQed.\n\nTheorem closed_if_closure : ∀ A, closed A ↔ A = closure A.\nProof.\n    intros A.\n    split.\n    -   intros A_closed.\n        apply predicate_ext; intros x; split.\n        +   intros Ax.\n            apply closure_sub.\n            exact Ax.\n        +   intros Ax.\n            specialize (Ax A (make_and A_closed (refl _))).\n            exact Ax.\n    -   intros eq; rewrite eq.\n        apply closure_closed.\nQed.\n\nTheorem open_if_interior : ∀ A, open A ↔ A = interior A.\nProof.\n    intros A.\n    split.\n    -   intros A_open.\n        apply predicate_ext; intros x; split.\n        +   intros Ax.\n            exists A.\n            repeat split.\n            *   exact A_open.\n            *   apply refl.\n            *   exact Ax.\n        +   intros [S [[S_open sub] Sx]].\n            apply sub.\n            exact Sx.\n    -   intros eq; rewrite eq.\n        apply interior_open.\nQed.\n\nTheorem closure_eq_if_closed : ∀ A, closed A → A = closure A.\nProof.\n    intros A.\n    apply closed_if_closure.\nQed.\n\nTheorem closure_sub_closure : ∀ A B, A ⊆ B → closure A ⊆ closure B.\nProof.\n    intros A B AB x Ax.\n    intros C [C_closed BC].\n    exact (Ax C (make_and C_closed (trans AB BC))).\nQed.\n\n(* begin hide *)\nEnd ClosureInterior.\n\nSection SubspaceClosure.\n\nContext {U} `{Topology U}.\n\nExisting Instance subspace_topology.\n(* end hide *)\nTheorem subspace_closure : ∀ X A, A ⊆ X →\n    closure (to_set_type X A) = to_set_type X (closure A).\nProof.\n    intros X A sub.\n    apply antisym.\n    -   assert (closed (to_set_type X (closure A))) as AX_closed.\n        {\n            rewrite to_set_type_inter.\n            apply (subspace_inter_closed _ _ (closure A)).\n            -   apply closure_closed.\n            -   reflexivity.\n        }\n        assert (to_set_type X A ⊆ to_set_type X (closure A)) as sub2.\n        {\n            apply to_set_type_sub.\n            apply closure_sub.\n        }\n        intros x Ax.\n        apply Ax; cbn.\n        split; assumption.\n    -   pose proof (closure_closed (to_set_type X A)) as A'_closed.\n        pose proof (from_set_type_sub_X X (closure (to_set_type X A)))\n            as A_sub.\n        rewrite <- to_from_set_type in A'_closed.\n        apply (subspace_closed_inter _ _ A_sub) in A'_closed.\n        destruct A'_closed as [B [B_closed A_eq]].\n        assert (A ⊆ B) as sub2.\n        {\n            assert (A ⊆ (from_set_type (closure (to_set_type X A)))) as sub2.\n            {\n                apply to_from_set_type_sub.\n                -   exact sub.\n                -   apply closure_sub.\n            }\n            apply (trans sub2).\n            rewrite A_eq.\n            apply inter_lsub.\n        }\n        assert (closure A ⊆ B) as sub3.\n        {\n            intros x Ax.\n            apply Ax.\n            split.\n            -   exact B_closed.\n            -   exact sub2.\n        }\n        rewrite <- to_from_set_type.\n        rewrite A_eq.\n        intros [x Xx] Ax.\n        split.\n        +   apply sub3.\n            exact Ax.\n        +   exact Xx.\nQed.\n\n(* begin hide *)\nEnd SubspaceClosure.\n\nSection ClosureBasis.\n\nContext {U} `{TopologyBasis U}.\n(* end hide *)\nTheorem basis_in_closure : ∀ x A,\n    (closure A) x ↔ ∀ B, top_basis B → B x → intersects A B.\nProof.\n    intros x A.\n    split.\n    -   intros Ax B B_basis Bx.\n        rewrite in_closure in Ax.\n        exact (Ax B (basis_open _ B_basis) Bx).\n    -   intros all_B A' [A'_closed sub].\n        classic_contradiction Ax.\n        unfold closed in A'_closed.\n        rewrite <- (compl_compl A') in Ax.\n        unfold 𝐂 in Ax at 1.\n        rewrite not_not in Ax.\n        unfold open in A'_closed; cbn in A'_closed.\n        specialize (A'_closed x Ax) as [B [B_basis [Bx B_sub]]].\n        specialize (all_B B B_basis Bx).\n        apply all_B.\n        apply empty_eq.\n        intros y [Ay By].\n        apply B_sub in By.\n        apply sub in Ay.\n        contradiction.\nQed.\n\n(* begin hide *)\nEnd ClosureBasis.\n\n(* end hide *)\nSection ClosureHausdorff.\n\n(* begin hide *)\nLocal Open Scope card_scope.\nLocal Open Scope set_scope.\n(* end hide *)\nContext {U} `{HausdorffSpace U}.\n\nTheorem point_closed : ∀ x, closed ❴x❵.\nProof.\n    intros x.\n    rewrite closed_if_closure.\n    apply (antisym (op := subset)).\n    -   apply closure_sub.\n    -   intros y y_closure.\n        apply singleton_eq.\n        classic_contradiction contr.\n        pose proof (hausdorff_space x y contr)\n            as [S1 [S2 [S1_open [S2_open [S1x [S2y S1S2]]]]]].\n        rewrite in_closure in y_closure.\n        specialize (y_closure S2 S2_open S2y).\n        assert ((S1 ∩ S2) x) as x_in.\n        {\n            split; try exact S1x.\n            apply empty_neq in y_closure.\n            destruct y_closure as [x' [x'_eq S2x']].\n            rewrite singleton_eq in x'_eq; subst.\n            exact S2x'.\n        }\n        unfold disjoint in S1S2.\n        rewrite S1S2 in x_in.\n        contradiction x_in.\nQed.\n\nTheorem finite_point_closed : ∀ A, finite (|set_type A|) → closed A.\nProof.\n    intros A A_fin.\n    apply fin_nat_ex in A_fin as [n A_fin].\n    revert A A_fin.\n    nat_induction n.\n    -   intros.\n        apply zero_is_empty in A_fin.\n        rewrite A_fin.\n        apply empty_closed.\n    -   intros A A_fin.\n        assert (set_type A) as [x Ax].\n        {\n            clear - A_fin.\n            classic_contradiction contr.\n            rewrite <- card_0_false in contr.\n            rewrite contr in A_fin.\n            apply nat_to_card_eq in A_fin.\n            inversion A_fin.\n        }\n        symmetry in A_fin.\n        pose proof (card_plus_one_nat A n [x|Ax] A_fin) as A'_fin; cbn in *.\n        remember (A - ❴x❵) as A'.\n        assert (A = A' ∪ ❴x❵) as eq.\n        {\n            apply predicate_ext; intros y; split.\n            -   intros Ay.\n                classic_case (x = y) as [eq|neq].\n                +   rewrite eq.\n                    right; reflexivity.\n                +   left.\n                    rewrite HeqA'; split.\n                    *   exact Ay.\n                    *   exact neq.\n            -   intros [A'y|xy].\n                +   rewrite HeqA' in A'y.\n                    apply A'y.\n                +   rewrite singleton_eq in xy; rewrite <- xy.\n                    exact Ax.\n        }\n        rewrite eq.\n        apply union_closed2.\n        +   apply IHn.\n            symmetry; exact A'_fin.\n        +   apply point_closed.\nQed.\n\nEnd ClosureHausdorff.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Topology/topology_closure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7226620534665602}}
{"text": "\nRequire Import List.\nRequire Import NPeano EqNat Compare_dec.\n\n\n(* determine whether given list of numbers is in decreasing order *)\nFixpoint decreasing_order (ns : list nat) : bool :=\n  match ns with\n      | nil => true\n      | a :: ns' => andb (match ns' with\n                            | nil => true\n                            | b :: _ => ltb b a\n                          end)\n                         (decreasing_order ns')\n  end.\n\nFixpoint last_is_1 (ns : list nat) : bool :=\n  match ns with\n    | nil => false\n    | 1 :: nil => true\n    | _ :: nil => false\n    | n :: ns' => last_is_1 ns'\n  end.\n\nDefinition coinlist := list nat.\nDefinition repr := list nat.\n\nDefinition N := 4.\nDefinition C : coinlist := 25 :: 6 :: 5 :: 1 :: nil.\n\nEval compute in decreasing_order C.\n\n(* this should follow from decreasing_order and last_is_1\nDefinition no_zeroes (C:coinlist) := forallb (fun c:nat => ltb 0 c) C.\n*)\n\nFixpoint repr_value (C : coinlist) (V : repr) : nat :=  (* inner product V . C *)\n  match C, V with\n      | nil, nil => 0\n      | c :: C', v :: V' => (c*v) + repr_value C' V'\n      | _, _ => 0\n  end. \n\nEval compute in (beq_nat 38 (repr_value (25 :: 10 :: 5 :: 1 :: nil) (1 :: 1 :: 0 :: 3 :: nil))).\n\nFixpoint repr_size (A : repr) : nat :=\n  match A with\n      | nil => 0\n      | a :: A' => a + repr_size A'\n  end.\n\nEval compute in (beq_nat 5 (repr_size (1 :: 1 :: 0 :: 3 :: nil))).\n\nFixpoint repr_lt (U V : repr) : bool :=\n  match U, V with\n    | nil, nil => false\n    | u :: U', v :: V' => \n      orb (ltb u v) (andb (beq_nat u v) (repr_lt U' V'))\n    | nil, _ => true\n    | _, nil => false\n  end.\n\nFixpoint repr_le (U V : repr) : bool :=\n  match U, V with\n    | nil, nil => true\n    | u :: U', v :: V' => \n      orb (ltb u v) (andb (beq_nat u v) (repr_le U' V'))\n    | nil, _ => true\n    | _, nil => false\n  end.\n\nDefinition repr_gt (U V : repr) : bool := repr_lt V U.\nDefinition repr_ge (U V : repr) : bool := repr_le V U.\n\nEval compute in (repr_lt (1 :: 1 :: 0 ::  3 :: nil) (1 :: 3 :: 0 :: 0 :: nil)).\nEval compute in (repr_lt (1 :: 1 :: 0 ::  3 :: nil) (1 :: 1 :: 0 :: 3 :: nil)).\nEval compute in (repr_le (1 :: 1 :: 0 ::  3 :: nil) (1 :: 1 :: 0 :: 3 :: nil)).\nEval compute in (repr_le (1 :: 1 :: 0 ::  3 :: nil) (1 :: 3 :: 0 :: 0 :: nil)).\nEval compute in negb (repr_lt (1 :: 1 :: nil) (1 :: 1 :: nil)).\nEval compute in negb (repr_lt (3 :: 1 :: nil) (1 :: 1 :: nil)).\n\nFixpoint make_list (k:nat) (v:nat) :=\n  match k with\n    | 0 => nil\n    | S k' => v :: make_list k' v\n  end.\n\n(* comp : is the first better than the second *)\nFixpoint best_of (comp : repr -> repr -> bool) (candidate : repr) (Rs : list repr) : repr :=\n  match Rs with\n      | nil => candidate\n      | r :: Rs' => best_of comp (if (comp r candidate) then r else candidate) Rs'\n  end.\n\nEval compute in 11 / 3.\nEval compute in 11 mod 3.\n\nFixpoint range (n:nat) : list nat :=\n  match n with\n    | 0 => nil\n    | S n' => n' :: range n'\n  end.\n\nFixpoint range_from (start num : nat) : list nat :=\n  match num with\n    | 0 => nil\n    | S m => start :: range_from (S start) m\n  end.\n\nEval compute in (range 5).\nEval compute in (range_from 10 5).\n\nFixpoint cons_each (x:nat) (V:list repr) :=\n  match V with\n    | nil => nil\n    | v :: V' => (cons x v) :: cons_each x V'\n  end.\n\nFixpoint all_reprs_iterate\n         (all_reprs : coinlist -> nat -> list repr) (C':coinlist) (c:nat) (v:nat) (X : list nat) : list repr :=\n  match X with\n    | nil => nil\n    | x :: X' =>\n      (* x .. c *)\n      app\n        (cons_each x (all_reprs C' (v - (x * c))))\n        (all_reprs_iterate all_reprs C' c v X')\n  end.\n\nFixpoint all_reprs (C : coinlist) (v : nat) {struct C} : list repr :=\n  match C with\n      | nil => nil\n      | c :: nil => (v :: nil) :: nil\n      | c :: C' => let max_of_c := v / c in\n                   let count_of_c_opts := range (S max_of_c) in\n                   (* all_reprs_iterate all_reprs C' c v *)\n                   (fix all_reprs_iterate (X : list nat) : list repr :=\n                      match X with\n                        | nil => nil\n                        | x :: X' =>\n                          (* x .. c *)\n                          app\n                            (cons_each x (all_reprs C' (v - (c * x))))\n                            (all_reprs_iterate X')\n                      end)\n                     count_of_c_opts\n  end.\n\nEval compute in (all_reprs C 17).\n\n(* new is \"more [or equally] minimal\" than cur if:\n     - size(new) < size(cur), or\n     - size(new)=size(cur) and cur <= new  [lexic. less than] *)\nDefinition more_minimal (new : repr) (cur : repr) : bool :=\n  orb (ltb (repr_size new) (repr_size cur))\n      (andb (beq_nat (repr_size new) (repr_size cur))\n            (repr_le cur new)).\n\nFixpoint make_repr_all_ones (n:nat) (v:nat) : repr :=\n  match n with\n    | 0 => nil\n    | 1 => v :: nil\n    | S n' => 0 :: make_repr_all_ones n' v\n  end.\n\n(* brute force computations of the minimal and greedy representations *)\nDefinition minimal_bf C v := best_of more_minimal (make_repr_all_ones (length C) v) (all_reprs C v).\nDefinition greedy_bf C v :=  best_of repr_ge (make_repr_all_ones (length C) v) (all_reprs C v).\n\nFixpoint greedy (C:coinlist) (v:nat) : repr :=\n  match C with\n    | nil => nil\n    | c :: C' => let q := v / c in\n                 let r := v mod c in\n                 q :: greedy C' r\n  end.\n\n\nEval compute in (make_repr_all_ones 4 17).\nEval compute in (more_minimal  (0 :: 1 :: 1 :: 2 :: nil) (0 :: 0 :: 1 :: 12 :: nil)).\nEval compute in (more_minimal  (1 :: 2 :: 1 :: 0 :: nil) (0 :: 1 :: 1 :: 2 :: nil) ).\n\nEval compute in \n    let v := 83 in\n    (minimal_bf C v , \n     greedy_bf C v, \n     greedy C v).\n\n\n\n(* =================================================== *)\n(* Pearson's algorithm to find smallest counterexample *)\n\nDefinition targetCvals (C:coinlist) : coinlist :=\n  map (fun c => c - 1) C.\n\nEval compute in targetCvals (25 :: 10 :: 5 :: 1 :: nil).\n\nDefinition greedy_multi (C:coinlist) (V : list nat) : list repr :=\n  map (greedy C) V.\n\nEval compute in (greedy_multi C (targetCvals C)).\n\nDefinition zero_out : repr -> repr :=\n  map (fun x => 0).\n\nFixpoint generate_possible_ce (R : repr) (i : nat) : repr :=\n  match R, i with\n    | x :: R', 0 => x+1 :: zero_out R'\n    | x :: R', S i' => x :: generate_possible_ce R' i'\n    | _, _ => R\n  end.\n\nDefinition generate_possible_ces_from (R : repr) (i j : nat) : list repr :=\n  map (generate_possible_ce R) (range_from i (j - i)).\n\nEval compute in generate_possible_ce (2 :: 1 :: 3 :: 1 :: 2 :: 7 :: nil) 3.\nEval compute in generate_possible_ces_from (2 :: 1 :: 3 :: 1 :: 2 :: 7 :: nil) 1 4.\n\nFixpoint app_all (Rs : list (list repr)) : list repr :=\n  match Rs with\n    | nil => nil\n    | x :: Rs' => app x (app_all Rs')\n  end.\n\nDefinition generate_min_reprs_to_check (Gs : list repr) : list repr :=\n  app_all (map (fun G => generate_possible_ces_from G 1 N) Gs).\n\nEval compute in generate_min_reprs_to_check  (greedy_multi C (targetCvals C)).\n\nDefinition is_min_lt_greedy_repr (R : repr) : bool :=\n  ltb (repr_size R) (repr_size (greedy C (repr_value C R))).\n\n\nFixpoint findp (A:Type) (f: A -> bool) (As : list A) : option A :=\n  match As with\n    | nil => None\n    | a :: As' => if (f a) then Some a else findp A f As'\n  end.\n\nDefinition find_counterexample (C:coinlist) : option nat :=\n  match \n    findp _ is_min_lt_greedy_repr (generate_min_reprs_to_check  (greedy_multi C (targetCvals C)))\n  with\n    | None => None\n    | Some R => Some (repr_value C R)\n  end.\n\n\nEval compute in (find_counterexample C).\n\nEval compute in \n    let v := 10 in\n    (minimal_bf C v , \n     greedy_bf C v, \n     greedy C v).", "meta": {"author": "nadeemabdulhamid", "repo": "make-change", "sha": "2b8667e4a0db00b6988f249c29bb4452ea254f3a", "save_path": "github-repos/coq/nadeemabdulhamid-make-change", "path": "github-repos/coq/nadeemabdulhamid-make-change/make-change-2b8667e4a0db00b6988f249c29bb4452ea254f3a/coq/coinsystem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7226620496635402}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Program.Basics.\nRequire Import DschingisKhan.Prelude.PreludeInit.\nRequire Import DschingisKhan.Prelude.PreludeUtil.\n\nModule BinaryTrees.\n\n  Import ListNotations.\n\n  Inductive direction : Set := LeftDir | RightDir.\n\n  Definition encode (ds : list direction) : nat := fold_left (fun i : nat => direction_rect (fun _ : direction => nat) (2 * i + 1) (2 * i + 2)) ds 0.\n\n  Lemma encode_inj (ds1 : list direction) (ds2 : list direction)\n    (ENCODE_EQ : encode ds1 = encode ds2)\n    : ds1 = ds2.\n  Proof with lia || eauto.\n    revert ENCODE_EQ. unfold encode; do 2 rewrite <- fold_left_rev_right.\n    intros ENCODE_EQ; eapply rev_inj; revert ENCODE_EQ.\n    generalize (rev ds2) as xs2. generalize (rev ds1) as xs1. clear ds1 ds2.\n    set (myF := fold_right (fun d : direction => fun i : nat => direction_rect (fun _ : direction => nat) (2 * i + 1) (2 * i + 2) d) 0).\n    induction xs1 as [ | x1 xs1 IH], xs2 as [ | x2 xs2]; simpl...\n    - destruct x2; simpl direction_rect...\n    - destruct x1; simpl direction_rect...\n    - destruct x1; destruct x2; simpl direction_rect...\n      all: intros ?; assert (claim1 : myF xs1 = myF xs2)...\n      all: eapply eq_congruence...\n  Qed.\n\n  Lemma encode_last (ds : list direction) (d : direction) :\n    encode (ds ++ [d]) =\n    match d with\n    | LeftDir => 2 * encode ds + 1\n    | RightDir => 2 * encode ds + 2\n    end.\n  Proof.\n    unfold encode at 1. rewrite <- fold_left_rev_right, rev_unit.\n    unfold fold_right, encode. rewrite <- fold_left_rev_right.\n    now destruct d as [ | ].\n  Qed.\n\n  Lemma decodable (idx : nat)\n    : {ds : list direction | encode ds = idx}.\n  Proof with lia || eauto.\n    induction idx as [[ | i'] IH] using NotherianRecursion.\n    - exists ([])...\n    - set (i := S i'). destruct (i mod 2) as [ | [ | i_mod_2]] eqn: H_obs.\n      + assert (claim1 : i = 2 * ((i - 2) / 2) + 2).\n        { eapply positive_even with (n := (i - 2) / 2)... }\n        assert (claim2 : (i - 2) / 2 < i)...\n        pose proof (IH ((i - 2) / 2) claim2) as [ds H_ds].\n        exists (ds ++ [RightDir]).\n        unfold encode. rewrite fold_left_last. unfold direction_rect at 1.\n        unfold encode in H_ds. rewrite H_ds...\n      + assert (claim1 : i = 2 * ((i - 1) / 2) + 1).\n        { eapply positive_odd with (n := (i - 1) / 2)... }\n        assert (claim2 : (i - 1) / 2 < i)...\n        pose proof (IH ((i - 1) / 2) claim2) as [ds H_ds].\n        exists (ds ++ [LeftDir]).\n        unfold encode. rewrite fold_left_last. unfold direction_rect at 1.\n        unfold encode in H_ds. rewrite H_ds...\n      + pose proof (Nat.mod_bound_pos i 2)...\n  Defined.\n\n  Definition decode (idx : nat) : list direction := proj1_sig (decodable idx).\n\n  Section BINARY_TREE.\n\n  Context {A : Type}.\n\n  Inductive bintree : Type := BTnull | BTnode (t_l : bintree) (x : A) (t_r : bintree).\n\n  Fixpoint getHeight (t : bintree) {struct t} : nat :=\n    match t with\n    | BTnull => 0\n    | BTnode t_l x t_r => 1 + max (getHeight t_l) (getHeight t_r)\n    end\n  .\n\n  Fixpoint getSize (t : bintree) {struct t} : nat :=\n    match t with\n    | BTnull => 0\n    | BTnode t_l x t_r => 1 + (getSize t_l + getSize t_r)\n    end\n  .\n\n  Definition getLeftChild (t : bintree) : option bintree :=\n    match t with\n    | BTnull => None\n    | BTnode t_l x t_r => Some t_l\n    end\n  .\n\n  Definition getRightChild (t : bintree) : option bintree :=\n    match t with\n    | BTnull => None\n    | BTnode t_l x t_r => Some t_r\n    end\n  .\n\n  Definition getKey (t : bintree) : option A :=\n    match t with\n    | BTnull => None\n    | BTnode t_l x t_r => Some x\n    end\n  .\n\n  Definition goto : list direction -> bintree -> option bintree :=\n    let k_step := @direction_rect _ (fun k : bintree -> option bintree => k <=< getLeftChild) (fun k : bintree -> option bintree => k <=< getRightChild) in\n    let k_base := @Some _ in\n    fold_right (A := bintree -> option bintree) (B := direction) k_step k_base\n  .\n\n  Lemma goto_unfold (ds : list direction) (t : bintree) :\n    goto ds t =\n    match ds with\n    | [] => Some t\n    | LeftDir :: ds' =>\n      match t with\n      | BTnull => None\n      | BTnode t_l x t_r => goto ds' t_l\n      end\n    | RightDir :: ds' =>\n      match t with\n      | BTnull => None\n      | BTnode t_l x t_r => goto ds' t_r\n      end\n    end.\n  Proof with try reflexivity.\n    destruct ds as [ | [ | ] ds']...\n    all: destruct t as [ | t_l x t_r]...\n  Qed.\n\n  Definition lookup (t : bintree) (ds : list direction) : option A :=\n    (getKey <=< goto ds) t\n  .\n\n  Definition toList (t : bintree) : list A :=\n    map (lookup t ∘ decode) (seq 0 (2 ^ getHeight t)) >>= maybe [] pure\n  .\n\n  Section COMPLETE_TREE.\n\n  Definition isComplete (t : bintree) : Prop :=\n    forall idx : nat, idx < getSize t -> lookup t (decode idx) <> None\n  .\n\n  End COMPLETE_TREE.\n\n  Section BREADTH_FIRST_SEARCH.\n\n  Fixpoint rk_bt (t : bintree) {struct t} : nat :=\n    match t with\n    | BTnull => 1\n    | BTnode t_l x t_r => 1 + rk_bt t_l + rk_bt t_r\n    end\n  .\n\n  Definition rk_queue (ts : list bintree) : nat := list_sum (map rk_bt ts).\n\n  Inductive bfsAux_spec : list bintree -> list A -> Prop :=\n  | bfsAux_nil\n    : bfsAux_spec [] []\n  | bfsAux_cons_null (ts : list bintree) (xs : list A)\n    (IH_SPEC : bfsAux_spec ts xs)\n    : bfsAux_spec (BTnull :: ts) xs\n  | bfsAux_cons_node (t_l : bintree) (x : A) (t_r : bintree) (ts : list bintree) (xs : list A)\n    (IH_SPEC : bfsAux_spec ([t_l; t_r] ++ ts) xs)\n    : bfsAux_spec (BTnode t_l x t_r :: ts) (x :: xs)\n  .\n\n  Definition bfsAux_withSpec (ts : list bintree)\n    : {xs : list A | forall xs' : list A, bfsAux_spec ts xs' <-> xs = xs'}.\n  Proof.\n    assert (WF_REC : forall ts : list bintree, Acc (fun lhs : list bintree => fun rhs : list bintree => rk_queue lhs < rk_queue rhs) ts).\n    { exact (well_founded_relation_on_image rk_queue Nat.lt (@lt_strong_ind (@Acc nat Nat.lt) (@Acc_intro nat Nat.lt))). }\n    induction (WF_REC ts) as [ts H_acc_inv IH]. clear H_acc_inv WF_REC. destruct ts as [ | [ | t_l x t_r] ts].\n    - exists ([]). intros xs'. split.\n      + intros SPEC. inversion SPEC; subst. reflexivity.\n      + intros ?; subst xs'. econstructor 1.\n    - assert (IH_rk : rk_queue ts < rk_queue (BTnull :: ts)).\n      { cbn. eapply le_intro_S_n_le_S_m. reflexivity. }\n      pose proof (IH ts IH_rk) as [xs IH_xs].\n      exists (xs). intros xs'. split.\n      + intros SPEC. inversion SPEC; subst. eapply IH_xs. exact (IH_SPEC).\n      + intros ?; subst xs'. econstructor 2. eapply IH_xs. reflexivity.\n    - assert (IH_rk : rk_queue ([t_l; t_r] ++ ts) < rk_queue (BTnode t_l x t_r :: ts)).\n      { cbn. eapply le_intro_S_n_le_S_m. rewrite Nat.add_assoc. reflexivity. }\n      pose proof (IH ([t_l; t_r] ++ ts) IH_rk) as [xs IH_xs].\n      exists (x :: xs). intros xs'. split.\n      + intros SPEC. inversion SPEC; subst. eapply eq_congruence. eapply IH_xs. exact (IH_SPEC).\n      + intros ?; subst xs'. econstructor 3. eapply IH_xs. reflexivity.\n  Defined.\n\n  Definition bfsAux (ts : list bintree) : list A := proj1_sig (bfsAux_withSpec ts).\n\n  Lemma bfsAux_spec_iff (ts : list bintree) (xs : list A)\n    : bfsAux_spec ts xs <-> bfsAux ts = xs.\n  Proof. revert xs. exact (proj2_sig (bfsAux_withSpec ts)). Qed.\n\n  Theorem bfsAux_unfold (ts : list bintree) :\n    bfsAux ts =\n    match ts with\n    | [] => []\n    | BTnull :: ts' => bfsAux ts'\n    | BTnode t_l x t_r :: ts' => x :: bfsAux ([t_l; t_r] ++ ts')\n    end.\n  Proof.\n    destruct ts as [ | [ | t_l x t_r] ts']; eapply bfsAux_spec_iff; econstructor.\n    all: eapply bfsAux_spec_iff; reflexivity.\n  Qed.\n\n  Definition bfs (t : bintree) : list A := bfsAux [t].\n\n  End BREADTH_FIRST_SEARCH.\n\n  End BINARY_TREE.\n\n  Global Arguments bintree : clear implicits.\n\nEnd BinaryTrees.\n", "meta": {"author": "KiJeong-Lim", "repo": "DschingisKhan", "sha": "b2d663f5c705f9732d44adc2faf49709b6ddec07", "save_path": "github-repos/coq/KiJeong-Lim-DschingisKhan", "path": "github-repos/coq/KiJeong-Lim-DschingisKhan/DschingisKhan-b2d663f5c705f9732d44adc2faf49709b6ddec07/theories/Data/BinTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7226620426418796}}
{"text": "Require Import QArith Qminmax Qabs QOrderedType.\nRequire Import Nsatz.\n\nDefinition Q_of_nat : nat -> Q := (fun n => inject_Z (Z_of_nat n)).\n\nSection Distance.\n\n  Definition qDistance (x y : Q) : Q :=\n    Qabs (x-y).\n\n  Lemma qDistance_Uniq : \n    forall x y, qDistance x y == 0 <-> x == y.\n  Proof.\n    intros. unfold qDistance.\n    apply Qabs_case.\n    - split; intros; nsatz.\n    - split; intros; nsatz.\n  Qed.\n\n  Lemma qDistance_symm : \n    forall x y,\n      qDistance x y == qDistance y x.\n  Proof.\n    intros. unfold qDistance.\n    rewrite Qabs_Qminus. reflexivity.\n  Qed.\n\n  Add Parametric Morphism : qDistance with\n    signature Qeq ==> Qeq ==> Qeq as qDistance_mor.\n  Proof. intros. unfold qDistance. rewrite H, H0. reflexivity. Qed.\n\n  Lemma qDistance_or : forall x y, \n    (x == y + (qDistance x y)) \\/ (x == y - (qDistance x y)).\n  Proof.\n    unfold qDistance.\n    intros. apply Qabs_case;\n    intros; [left | right]; nsatz.\n  Qed.\n\nEnd Distance.\n\nSection QInterval.\n\nRecord QInterval : Type :=\n  mkInterval {\n    upperBound : Q;\n    lowerBound : Q;\n\n    orderPf : lowerBound <= upperBound\n  }.\n\nInductive inQInterval : Q -> QInterval -> Prop :=\n| mkInQInterval :\n    forall q QI,\n      q <= (upperBound QI) ->\n      (lowerBound QI) <= q ->\n  inQInterval q QI.\n\nDefinition boundriesOfIntervalIntersection QInt1 QInt2 : Q * Q :=\n    let UB := Qmin (upperBound QInt1) (lowerBound QInt2) in\n    let LB := Qmax (lowerBound QInt1) (lowerBound QInt2) in\n  (UB, LB).\n\n  Definition intervalIntersection QInt1 QInt2 : option QInterval :=\n    let boundries := boundriesOfIntervalIntersection QInt1 QInt2 in\n    match Qlt_le_dec (fst boundries) (snd boundries) with\n    | left _ => None\n    | right pf => Some (mkInterval (fst boundries) (snd boundries) pf)\n    end.\n\nEnd QInterval.  ", "meta": {"author": "OUPL", "repo": "DPSS", "sha": "b888f594a66648969febe312ea0d83c27573d3ed", "save_path": "github-repos/coq/OUPL-DPSS", "path": "github-repos/coq/OUPL-DPSS/DPSS-b888f594a66648969febe312ea0d83c27573d3ed/DPSS_Numerics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7226620400989242}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Functions                                                               *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic LibBag LibSet.\nGeneralizable Variables A.\n\n\n(* ********************************************************************** *)\n(** ** Indentity function *)\n\nDefinition id {A} (x : A) :=\n  x.\n\n\n(* ********************************************************************** *)\n(** Constant functions *)\n\nDefinition const {A B} (v : B) : A -> B :=\n  fun _ => v.\nDefinition const1 :=\n  @const.\nDefinition const2 {A1 A2 B} (v:B) : A1->A2->B :=\n  fun _ _ => v.\nDefinition const3 {A1 A2 A3 B} (v:B) : A1->A2->A3->B :=\n  fun _ _ _ => v.\nDefinition const4 {A1 A2 A3 A4 B} (v:B) : A1->A2->A3->A4->B :=\n  fun _ _ _ _ => v.\nDefinition const5 {A1 A2 A3 A4 A5 B} (v:B) : A1->A2->A3->A4->A5->B :=\n  fun _ _ _ _ _ => v.\n\n(* ********************************************************************** *)\n(** Function application *)\n\nDefinition apply {A B} (f : A -> B) (x : A) :=\n  f x.\n\nDefinition apply_to (A : Type) (x : A) (B : Type) (f : A -> B) :=\n  f x.\n\n\n(* ********************************************************************** *)\n(** Function composition *)\n\nDefinition compose {A B C} (g : B -> C) (f : A -> B) :=\n  fun x => g (f x).\n\nNotation \"f1 \\o f2\" := (compose f1 f2)\n  (at level 49, right associativity) : func_scope.\n\nSection Combinators.\nOpen Scope func_scope.\nVariables (A B C D : Type).\n\nLemma compose_id_l : forall (f:A->B),\n  id \\o f = f.\nProof using. intros. apply~ func_ext_1. Qed.\n\nLemma compose_id_r : forall (f:A->B),\n  f \\o id = f.\nProof using. intros. apply~ func_ext_1. Qed.\n\nLemma compose_assoc : forall (f:C->D) (g:B->C) (h:A->B),\n  (f \\o g) \\o h = f \\o (g \\o h).\nProof using. intros. apply~ func_ext_1. Qed.\n\nLemma compose_eq_l : forall (f:B->C) (g1 g2:A->B),\n  g1 = g2 -> f \\o g1 = f \\o g2.\nProof using. intros. subst~. Qed.\n\nLemma compose_eq_r : forall (f:A->B) (g1 g2:B->C),\n  g1 = g2 -> g1 \\o f = g2 \\o f.\nProof using. intros. subst~. Qed.\n\n(** Composition of [LibList.map] behaves well. **)\n(* Could not be put in [LibList] because of circular dependencies. *)\nRequire Import LibList.\nLemma list_map_compose : forall A B C (f : A -> B) (g : B -> C) l,\n  LibList.map g (LibList.map f l) = LibList.map (g \\o f) l.\nProof.\n  introv. induction l.\n   reflexivity.\n   rew_list. fequals~.\nQed.\n\nEnd Combinators.\n\n(** Tactic for simplifying function compositions *)\n(* TODO: not used; might become deprecated *)\n\nHint Rewrite compose_id_l compose_id_r compose_assoc : rew_compose.\nTactic Notation \"rew_compose\" :=\n  autorewrite with rew_compose.\nTactic Notation \"rew_compose\" \"in\" \"*\" :=\n  autorewrite with rew_compose in *.\nTactic Notation \"rew_compose\" \"in\" hyp(H) :=\n  autorewrite with rew_compose in H.\n\n\n(* ********************************************************************** *)\n(** ** Function update *)\n\n(** [fupdate f a b x] is like [f] except that it returns [b] for input [a] *)\n\nDefinition fupdate A B (f : A -> B) (a : A) (b : B) : A -> B :=\n  fun x => If (x = a) then b else f x.\n\nLemma fupdate_def : forall A B (f:A->B) a b x,\n  fupdate f a b x = If (x = a) then b else f x.\nProof. auto. Qed.\n\nLemma fupdate_eq : forall A B (f:A->B) a b x,\n  x = a ->\n  fupdate f a b x = b.\nProof using. intros. unfold fupdate. case_if*. Qed.\n\nLemma fupdate_neq : forall A B (f:A->B) a b x,\n  x <> a ->\n  fupdate f a b x = f x.\nProof using. intros. unfold fupdate. case_if*. Qed.\n\n(* Opaque fupdate. -- could be added in the future *)\n\n\n(* ********************************************************************** *)\n(** ** Function image *)\n\nSection FunctionImage.\nOpen Scope set_scope.\nRequire Import LibList.\n\nDefinition image A B (f : A -> B) (E : set A) : set B :=\n  \\set{ y | exists_ x \\in E, y = f x }.\n\nLemma in_image_prove_eq : forall A B x (f : A -> B) (E : set A),\n  x \\in E -> f x \\in image f E.\nProof using. introv N. unfold image. rew_set. exists* x. Qed.\n\nLemma in_image_prove : forall A B x y (f : A -> B) (E : set A),\n  x \\in E -> y = f x -> y \\in image f E.\nProof using. intros. subst. applys* in_image_prove_eq. Qed.\n\nLemma in_image_inv : forall A B y (f : A -> B) (E : set A),\n  y \\in image f E -> exists x, x \\in E /\\ y = f x.\nProof using. introv N. unfolds image. rew_set in N. auto. Qed.\n\nLemma finite_image : forall A B (f : A -> B) (E : set A),\n  finite E ->\n  finite (image f E).\nProof using.\n  introv M. lets (L&H): finite_covers_basic M.\n  applys finite_prove_covers (LibList.map f L). introv N.\n  lets (y&Hy&Ey): in_image_inv (rm N). subst x. applys* Mem_map.\nQed.\n\nLemma image_covariant : forall A B (f : A -> B) (E F : set A),\n  E \\c F ->\n  image f E \\c image f F.\nProof using.\n  introv. do 2 rewrite incl_in_eq. introv M N.\n  lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\nQed.\n\nLemma image_union : forall A B (f : A -> B) (E F : set A),\n  image f (E \\u F) = image f E \\u image f F.\nProof using.\n  Hint Resolve in_image_prove.\n  introv. apply in_extens. intros x. iff N.\n    lets (y&Hy&Ey): in_image_inv (rm N). rewrite in_union_eq in Hy.\n     rewrite in_union_eq. destruct* Hy.\n    rewrite in_union_eq in N. destruct N as [N|N].\n      lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\n       rewrite in_union_eq. eauto.\n      lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\n       rewrite in_union_eq. eauto.\nQed.\n\nLemma image_singleton : forall A B (f : A -> B) (x : A),\n  image f \\{x} = \\{f x}.\nProof using.\n  intros. apply in_extens. intros z. iff N.\n    lets (y&Hy&Ey): in_image_inv (rm N). rewrite in_single_eq in Hy. subst~.\n    rewrite in_single_eq in N. applys* in_image_prove.\nQed.\n\nEnd FunctionImage.\n\nHint Resolve finite_image : finite.\n\n(* ********************************************************************** *)\n(** ** Function preimage *)\n\nSection FunctionPreimage.\nOpen Scope set_scope.\n\nDefinition preimage A B (f : A -> B) (E : set B) : set A :=\n  \\set{ x | exists_ y \\in E, y = f x }.\n\nEnd FunctionPreimage.\n\n\n\n(* ********************************************************************** *)\n(** ** Function iteration *)\n\nFixpoint applyn A n (f : A -> A) x :=\n  match n with\n  | O => x\n  | S n' =>\n    f (applyn n' f x)\n  end.\n\nLemma applyn_fix : forall A n f (x : A),\n  applyn (S n) f x = applyn n f (f x).\nProof. introv. induction~ n. simpls. rewrite~ IHn. Qed.\n\nLemma applyn_comp : forall A n m f (x : A),\n  applyn n f (applyn m f x) = applyn (n + m) f x.\nProof.\n  introv. gen m; induction n; introv; simpls~.\n  rewrite~ IHn.\nQed.\n\nLemma applyn_nested : forall A n m f (x : A),\n  applyn n (applyn m f) x = applyn (n * m) f x.\nProof.\n  introv. gen m. induction n; introv; simpls~.\n  rewrite IHn. rewrite~ applyn_comp.\nQed.\n\nLemma applyn_altern : forall A B (f : A -> B) (g : B -> A) x n,\n  applyn n (fun x => f (g x)) (f x) =\n    f (applyn n (fun x => g (f x)) x).\nProof. introv. gen x. induction~ n. introv. repeat rewrite applyn_fix. autos~. Qed.\n\nLemma applyn_ind : forall A (P : A -> Prop) (f : A -> A) x n,\n  (forall x, P x -> P (f x)) ->\n  P x ->\n  P (applyn n f x).\nProof. introv I. induction n; introv Hx; autos*. Qed.\n\n", "meta": {"author": "zhiyuanshi", "repo": "intersection", "sha": "825f69cf7f70db7d0b829875f590fa38468bfad1", "save_path": "github-repos/coq/zhiyuanshi-intersection", "path": "github-repos/coq/zhiyuanshi-intersection/intersection-825f69cf7f70db7d0b829875f590fa38468bfad1/workinprogress/semantics/tlc/src/LibFunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.722609962971322}}
{"text": "(*|\n################################\nCoq: automate repeated rewriting\n################################\n\n:Link: https://stackoverflow.com/q/48139738\n|*)\n\n(*|\nQuestion\n********\n|*)\n\nExample test : forall f (n : nat), f n = n -> f (f n) = n.\nProof.\n  intros f n H. repeat rewrite H. reflexivity.\nQed.\n\n(*|\nWhat would be a good way to further automate this? In particular, I\nwould like to not have to mention the name of the hypothesis anywhere.\n\n----\n\n**A:** ``repeat rewrite H.`` can be replaced with ``rewrite ?H.``\n(rewrite zero or more times) or ``rewrite !H.`` (rewrite one or more\ntimes)\n\n**A:** There is also ``autorewrite`` tactics.\n\n**Q:** Is there a way to make ``autorewrite`` consider local\nhypotheses?\n\n**A:** You can use this new `strat_rewrite tactic\n<https://github.com/coq/coq/blob/2d6e395dead61a49ede6208bc40e16b4b8e68ce4/CHANGES#L1028>`__:\n``Require Import Setoid. Hint Rewrite my_hint : my_db. <...>\nrewrite_strat topdown <local_term>; topdown (hints my_db).``\n|*)\n\n(*|\nAnswer\n******\n\nIf the goal can be solved with some sequence of rewrites, then the\n`congruence <https://coq.inria.fr/refman/tactics.html#congruence>`__\ntactic can handle it.\n\n    The tactic ``congruence``, by Pierre Corbineau, implements the\n    standard Nelson and Oppen congruence closure algorithm, which is a\n    decision procedure for ground equalities with uninterpreted\n    symbols. It also include the constructor theory (see 8.5.7 and\n    8.5.6). If the goal is a non-quantified equality, ``congruence``\n    tries to prove it with non-quantified equalities in the context.\n    Otherwise it tries to infer a discriminable equality from those in\n    the context. Alternatively, ``congruence`` tries to prove that a\n    hypothesis is equal to the goal or to the negation of another\n    hypothesis.\n\n    ``congruence`` is also able to take advantage of hypotheses\n    stating quantified equalities, you have to provide a bound for the\n    number of extra equalities generated that way. Please note that\n    one of the members of the equality must contain all the quantified\n    variables in order for ``congruence`` to match against it.\n\nThe above basically means that ``congruence`` can solve your goal if\nit can be solved using ``rewrite`` and ``discriminate`` tactics. But\nsometimes ``congruence`` can't help you because it does not unfold\ndefinitions for you -- in that case you'll have to help it.\n|*)\n\nReset Initial. (* .none *)\nExample test : forall f (n : nat), f n = n -> f (f n) = n.\nProof. congruence. Qed.\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/coq-automate-repeated-rewriting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.7226099599112126}}
{"text": "Inductive eList (a:Set) : Set :=\n| Nil   : eList a\n| ECons : a -> oList a -> eList a\nwith oList (a:Set) : Set :=\n| OCons : a -> eList a -> oList a\n.\n\nArguments Nil {a}.\nArguments ECons {a} _ _.\nArguments OCons {a} _ _.\n\nFixpoint eLength (a:Set) (xs:eList a) : nat :=\n    match xs with\n    | Nil           => O\n    | ECons _ xs    => S (oLength a xs)\n    end\nwith oLength (a:Set) (xs:oList a) : nat :=\n    match xs with \n    | OCons _ xs    => S (eLength a xs)\n    end\n.\n\nArguments eLength {a} _.\nArguments oLength {a} _.\n\nFixpoint eeAppend (a:Set) (xs ys:eList a) : eList a :=\n    match xs with\n    | Nil           => ys\n    | ECons x xs    => ECons x (oeAppend a xs ys)\n    end\nwith oeAppend (a:Set) (xs : oList a) (ys:eList a) : oList a :=\n    match xs with\n    | OCons x xs => OCons x (eeAppend a xs ys)\n    end\n.    \n\nFixpoint ooAppend (a:Set) (xs ys:oList a) : eList a :=\n    match xs with\n    | OCons x xs    => ECons x (eoAppend a xs ys)\n    end\nwith eoAppend (a:Set) (xs:eList a) (ys:oList a) : oList a :=\n    match xs with \n    | Nil           => ys\n    | ECons x xs    => OCons x (ooAppend a xs ys)\n    end\n.\n\nArguments eeAppend {a} _ _.\nArguments eoAppend {a} _ _.\nArguments oeAppend {a} _ _.\nArguments ooAppend {a} _ _.\n\n(* generate mutual induction scheme *)\nScheme eList_mut := Induction for eList Sort Prop\nwith oList_mut := Induction for oList Sort Prop.\n\n(*\nCheck eList_mut.\n\neList_mut : \n    forall (a : Set) (P : eList a -> Prop) (Q : oList a -> Prop),\n    P Nil ->\n    (forall (x : a) (xs : oList a), Q xs -> P (ECons x xs)) ->\n    (forall (x : a) (xs : eList a), P xs -> Q (OCons x xs)) ->\n    forall (xs : eList a), P xs\n*)\n\n(*\nCheck oList_mut.\n\noList_mut : \n    forall (a : Set) (P : eList a -> Prop) (Q : oList a -> Prop),\n    P Nil ->\n    (forall (x : a) (xs : oList a), Q xs -> P (ECons x xs)) ->\n    (forall (x : a) (xs : eList a), P xs -> Q (OCons x xs)) ->\n    forall (xs : oList a), Q xs\n*)\n\nLemma plus_n_O': forall (n:nat), plus n 0 = n.\nProof. \n    apply nat_ind; simpl.\n    - reflexivity.\n    - intros n IH. rewrite IH. reflexivity.\nQed.\n\nLemma plus_n_O'': forall (n:nat), plus n 0 = n.\nProof.\n    apply (nat_ind (fun n => plus n 0 = n)); simpl.\n    - reflexivity.\n    - intros n IH. rewrite IH. reflexivity.\nQed.\n    \nLemma length_eeAppend : forall (a:Set) (xs ys:eList a),\n    eLength (eeAppend xs ys) = plus (eLength xs) (eLength ys).\nProof.\n    intros a. \n    apply (eList_mut a \n        (fun (xs:eList a) => forall (ys:eList a), \n            eLength (eeAppend xs ys) = plus (eLength xs) (eLength ys))\n        (fun (xs:oList a) => forall (ys:eList a),\n            oLength (oeAppend xs ys) = plus (oLength xs) (eLength ys))).\n    - reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\nQed.\n\nLemma length_eoAppend : forall (a:Set) (xs:eList a) (ys:oList a),\n    oLength (eoAppend xs ys) = plus (eLength xs) (oLength ys).\nProof.\n    intros a.\n    apply (eList_mut a \n        (fun (xs:eList a) => forall (ys:oList a), \n            oLength (eoAppend xs ys) = plus (eLength xs) (oLength ys))\n        (fun (xs:oList a) => forall (ys:oList a),\n            eLength (ooAppend xs ys) = plus (oLength xs) (oLength ys))).\n    - reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\nQed.\n\nLemma length_oeAppend : forall (a:Set) (xs:oList a) (ys:eList a),\n    oLength(oeAppend xs ys) = plus (oLength xs) (eLength ys).\nProof.\n    intros a.\n    apply (oList_mut a \n        (fun (xs:eList a) => forall (ys:eList a), \n            eLength (eeAppend xs ys) = plus (eLength xs) (eLength ys))\n        (fun (xs:oList a) => forall (ys:eList a),\n            oLength (oeAppend xs ys) = plus (oLength xs) (eLength ys))).\n    - reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\nQed.\n\n\n\nLemma length_ooAppend : forall (a:Set) (xs:oList a) (ys:oList a),\n    eLength(ooAppend xs ys) = plus (oLength xs) (oLength ys).\nProof.\n    intros a.\n    apply (oList_mut a \n        (fun (xs:eList a) => forall (ys:oList a), \n            oLength (eoAppend xs ys) = plus (eLength xs) (oLength ys))\n        (fun (xs:oList a) => forall (ys:oList a),\n            eLength (ooAppend xs ys) = plus (oLength xs) (oLength ys))).\n    - reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity. \nQed.\n\nFixpoint test0 (n:nat) : nat := \n    match n with\n    | 0     => 0\n    | S n   => test1 n\n    end\nwith test1 (n:nat) : nat := \n    match n with\n    | 0     => 0\n    | S n   => test2 n\n    end\nwith test2 (n:nat) : nat :=\n    match n with \n    | 0     => 0\n    | S n   => test3 n\n    end\nwith test3 (n:nat) : nat :=\n    match n with\n    | 0     => 0\n    | S n   => test0 n\n    end.\n\nLemma test_all : test0 7 = 0.\nProof. reflexivity. Qed.\n\n\n\n(*\nCheck eList_mut.\n\neList_mut : \n    forall (a : Set) (P : eList a -> Prop) (Q : oList a -> Prop),\n    P Nil ->\n    (forall (x : a) (xs : oList a), Q xs -> P (ECons x xs)) ->\n    (forall (x : a) (xs : eList a), P xs -> Q (OCons x xs)) ->\n    forall (xs : eList a), P xs\n*)\n\n(*\nCheck oList_mut.\n\noList_mut : \n    forall (a : Set) (P : eList a -> Prop) (Q : oList a -> Prop),\n    P Nil ->\n    (forall (x : a) (xs : oList a), Q xs -> P (ECons x xs)) ->\n    (forall (x : a) (xs : eList a), P xs -> Q (OCons x xs)) ->\n    forall (xs : oList a), Q xs\n*)\n\n(* We can build these induction principle manually *)\n(* First we define the general recursion principle *)\nFixpoint eList_mut_rect (a:Set)(P:eList a -> Type)(Q:oList a -> Type)\n    (pnil : P Nil)\n    (p:forall (x:a)(xs:oList a), Q xs -> P (ECons x xs))\n    (q:forall (x:a)(xs:eList a), P xs -> Q (OCons x xs))\n    (xs:eList a)\n    : P xs :=\n        match xs with\n        | Nil           => pnil\n        | ECons x xs    => p x xs (oList_mut_rect a P Q pnil p q xs)\n        end\nwith oList_mut_rect (a:Set)(P:eList a -> Type)(Q:oList a -> Type)\n    (pnil : P Nil)\n    (p:forall (x:a)(xs:oList a), Q xs -> P (ECons x xs))\n    (q:forall (x:a)(xs:eList a), P xs -> Q (OCons x xs))\n    (xs:oList a)\n    : Q xs :=\n        match xs with\n        | OCons x xs    => q x xs (eList_mut_rect a P Q pnil p q xs)\n        end\n.\n\n(* We can specialize this recursion principle to Prop *) \n\nDefinition eList_mut_ind (a:Set)(P:eList a -> Prop)(Q:oList a -> Prop)\n    (pnil: P Nil)\n    (p:forall (x:a)(xs:oList a), Q xs -> P (ECons x xs))\n    (q:forall (x:a)(xs:eList a), P xs -> Q (OCons x xs))\n    (xs:eList a)\n    : P xs := eList_mut_rect a P Q pnil p q xs.\n\nDefinition oList_mut_ind (a:Set)(P:eList a -> Prop)(Q:oList a -> Prop)\n    (pnil: P Nil)\n    (p:forall (x:a)(xs:oList a), Q xs -> P (ECons x xs))\n    (q:forall (x:a)(xs:eList a), P xs -> Q (OCons x xs))\n    (xs:oList a)\n    : Q xs := oList_mut_rect a P Q pnil p q xs.\n\n(* we can now prove all four concatenation lemmas using those *)\n\nLemma length_eeAppend' : forall (a:Set) (xs ys:eList a),\n    eLength (eeAppend xs ys) = plus (eLength xs) (eLength ys).\nProof.\n    intros a. \n    apply (eList_mut_ind a \n        (fun (xs:eList a) => forall (ys:eList a), \n            eLength (eeAppend xs ys) = plus (eLength xs) (eLength ys))\n        (fun (xs:oList a) => forall (ys:eList a),\n            oLength (oeAppend xs ys) = plus (oLength xs) (eLength ys))).\n    - reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\nQed.\n\n\nLemma length_eoAppend' : forall (a:Set) (xs:eList a) (ys:oList a),\n    oLength (eoAppend xs ys) = plus (eLength xs) (oLength ys).\nProof.\n    intros a.\n    apply (eList_mut_ind a \n        (fun (xs:eList a) => forall (ys:oList a), \n            oLength (eoAppend xs ys) = plus (eLength xs) (oLength ys))\n        (fun (xs:oList a) => forall (ys:oList a),\n            eLength (ooAppend xs ys) = plus (oLength xs) (oLength ys))).\n    - reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\nQed.\n\nLemma length_oeAppend' : forall (a:Set) (xs:oList a) (ys:eList a),\n    oLength(oeAppend xs ys) = plus (oLength xs) (eLength ys).\nProof.\n    intros a.\n    apply (oList_mut_ind a \n        (fun (xs:eList a) => forall (ys:eList a), \n            eLength (eeAppend xs ys) = plus (eLength xs) (eLength ys))\n        (fun (xs:oList a) => forall (ys:eList a),\n            oLength (oeAppend xs ys) = plus (oLength xs) (eLength ys))).\n    - reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\nQed.\n\n\n\nLemma length_ooAppend' : forall (a:Set) (xs:oList a) (ys:oList a),\n    eLength(ooAppend xs ys) = plus (oLength xs) (oLength ys).\nProof.\n    intros a.\n    apply (oList_mut_ind a \n        (fun (xs:eList a) => forall (ys:oList a), \n            oLength (eoAppend xs ys) = plus (eLength xs) (oLength ys))\n        (fun (xs:oList a) => forall (ys:oList a),\n            eLength (ooAppend xs ys) = plus (oLength xs) (oLength ys))).\n    - reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity.\n    - intros x xs IH ys. simpl. rewrite IH. reflexivity. \nQed.\n\nFixpoint factorial (n:nat) : nat :=\n    match n with\n    | 0     => 1\n    | S n   => mult (S n) (factorial n)\n    end.\n\nLemma factorial_test : factorial 5 = 120.\nProof. reflexivity. Qed.\n\nDefinition factorial' : nat -> nat := \n    fix f (n:nat) : nat := \n        match n with\n        | 0     => 1\n        | S n   => mult (S n) (f n)\n        end.\n\nLemma factorial_test' : factorial' 5 = 120.\nProof. reflexivity. Qed.\n\nLemma factorial_same : forall (n:nat), factorial n = factorial' n.\nProof.\n    induction n as [|n IH]; simpl.\n    - reflexivity.\n    - rewrite IH. reflexivity.\nQed.\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/cpdt/mutual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7226099463521927}}
{"text": "From Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nRequire Export Coq.Strings.String.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\n\nDefinition eqb_string (x y : string) : bool :=\n  if string_dec x y then true else false.\n\nCheck string_dec.\n(*string_dec 的类型并不是bool，而是一个形如{x=y}+{x\\neq y}的类型，叫做sumbool\n一个sumbool类型的元素要么是x和y相等的证明，要么是x和y不等证明，目前可当做bool来考虑*)\n\n(** Now we need a few basic properties of string equality... *)\nTheorem eqb_string_refl : forall s : string, true = eqb_string s s.\nProof.\n  intros s. unfold eqb_string. destruct (string_dec s s) as [|Hs].\n  - reflexivity.\n  - destruct Hs. reflexivity.\nQed.\n(*两个字符创在eqb_string意义上相等，当且仅当在=意义上相等,建立了互映的关系*)\n\n(** The following useful property follows from an analogous\n    lemma about strings: *)\nTheorem eqb_string_true_iff : forall x y : string,\n    eqb_string x y =true <-> x=y.\nProof.\n  intros x y.\n  unfold eqb_string.\n  destruct (string_dec x y) as [|Hs].\n  - subst. split. reflexivity. reflexivity.\n  - split.\n    + intros H. inversion H.\n    + intros. rewrite H in Hs. destruct Hs. reflexivity.\nQed. \n(** Similarly: *)\nTheorem eqb_string_false_iff : forall x y :string,\n    eqb_string x y= false <-> x <> y.\nProof.\n  intros x y. rewrite <- eqb_string_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This handy variant follows just by rewriting: *)\n\nTheorem false_eqb_string : forall x y : string,\n   x <> y -> eqb_string x y = false.\nProof.\n  intros x y. rewrite eqb_string_false_iff.\n  intros H. apply H. Qed.\n\n(* ################################################################# *)\n(** * Total Maps *)\n\nDefinition total_map (A : Type) := string -> A.\n\n(*t_empty 在应用到任何字符串时都会返回默认元素*)\nDefinition t_empty {A : Type} (v : A) : total_map A :=\n  (fun _ => v).\n\nDefinition t_update {A : Type} (m : total_map A)\n                    (x : string) (v : A) :=\n  fun x' => if eqb_string x x' then v else m x'.\n\n(*由t_update可构造高阶函数，逐个修改键值，下面就构造出string到bool的映射，其中\"foo\"和\"bar\"映射到true\n其他映射到false*)\nDefinition examplemap :=\n  t_update (t_update (t_empty false) \"foo\" true)\n           \"bar\" true.\n\nNotation \"'_' '!->' v\" := (t_empty v)\n  (at level 100, right associativity).\n\nExample example_empty := (_ !-> false).\n\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n                              (at level 100, v at next level, right associativity).\n\n(** The [examplemap] above can now be defined as follows: *)\n\nDefinition examplemap' :=\n  ( \"bar\" !-> true;\n    \"foo\" !-> true;\n     _ !-> false\n  ).\n\nExample update_example1 : examplemap' \"baz\" = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap' \"foo\" = true.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap' \"quux\" = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap' \"bar\" = true.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (t_apply_empty) *)\n\nLemma t_apply_empty : forall (A : Type) (x : string) (v : A),\n    (_ !-> v) x = v.\nProof.\n  intros. reflexivity. Qed.\n(** [] *)\n(** **** Exercise: 2 stars, standard, optional (t_update_eq) *)\n\nLemma t_update_eq : forall (A : Type) (m : total_map A) x v,\n    (x !-> v ; m) x = v.\nProof.\n  intros.\n  unfold t_update.\n  assert(H: eqb_string x x =true). {rewrite eqb_string_true_iff. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_neq) *)\n\nTheorem t_update_neq : forall (A : Type) (m : total_map A) x1 x2 v,\n    x1 <> x2 ->\n    (x1 !-> v ; m) x2 = m x2.\nProof.\n  intros.\n  unfold t_update.\n  assert(H1: eqb_string x1 x2 =false). { apply false_eqb_string. apply H. }\n  rewrite H1.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_shadow)  *)\n\nLemma t_update_shadow : forall (A : Type) (m : total_map A) x v1 v2,\n    (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\n  intros.\n  unfold t_update.\n  apply functional_extensionality.\n  intros.\n  destruct (eqb_string x x0).\n  -reflexivity.\n  -reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard, optional (eqb_stringP)*)\n\nLemma eqb_stringP : forall x y : string,\n    reflect (x = y) (eqb_string x y).\nProof.\n  intros.\n  apply iff_reflect.\n  rewrite eqb_string_true_iff.\n  reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard (t_update_same) *)\n\nTheorem t_update_same : forall (A : Type) (m : total_map A) x,\n    (x !-> m x ; m) = m.\nProof.\n  intros.\n  unfold t_update.\n  apply functional_extensionality.\n  intros.\n  destruct (eqb_string x x0) eqn: H1.\n  -apply eqb_string_true_iff in H1. rewrite H1. reflexivity.\n  -reflexivity.\nQed.\n(** **** Exercise: 3 stars, standard, recommended (t_update_permute) *)\n\nTheorem t_update_permute : forall (A : Type) (m : total_map A)\n                                  v1 v2 x1 x2,\n    x2 <> x1 ->\n    (x1 !-> v1 ; x2 !-> v2 ; m)\n    =\n    (x2 !-> v2 ; x1 !-> v1 ; m).\nProof.\n  intros.\n  unfold t_update.\n  apply functional_extensionality.\n  intros.\n  destruct (eqb_string x1 x) eqn: H1.\n  - destruct (eqb_string x2 x) eqn: H2.\n    + apply eqb_string_true_iff in H1. apply eqb_string_true_iff in H2.\n      rewrite<-H1 in H2. rewrite H2 in H. destruct H. reflexivity.\n    + reflexivity.\n  - destruct (eqb_string x2 x) eqn: H2.\n    + reflexivity.\n    + reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\nDefinition partial_map (A : Type) := total_map (option A).\n\nDefinition empty {A : Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A : Type} (m : partial_map A)\n           (x : string) (v : A) :=\n  (x !-> Some v ; m).\n\n(** We introduce a similar notation for partial maps: *)\nNotation \"x '|->' v ';' m\" := (update m x v)\n  (at level 100, v at next level, right associativity).\n\n(** We can also hide the last case when it is empty. *)\nNotation \"x '|->' v\" := (update empty x v)\n  (at level 100).\n\nExample examplepmap :=\n  (\"Church\" |-> true ; \"Turing\" |-> false).\n\n(** We now straightforwardly lift all of the basic lemmas about total\n    maps to partial maps.  *)\n\nLemma apply_empty : forall (A : Type) (x : string),\n    @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall (A : Type) (m : partial_map A) x v,\n    (x |-> v ; m) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (A : Type) (m : partial_map A) x1 x2 v,\n    x2 <> x1 ->\n    (x2 |-> v ; m) x1 = m x1.\nProof.\n  intros A m x1 x2 v H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall (A : Type) (m : partial_map A) x v1 v2,\n    (x |-> v2 ; x |-> v1 ; m) = (x |-> v2 ; m).\nProof.\n  intros A m x v1 v2. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall (A : Type) (m : partial_map A) x v,\n    m x = Some v ->\n    (x |-> v ; m) = m.\nProof.\n  intros A m x v H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (A : Type) (m : partial_map A)\n                                x1 x2 v1 v2,\n    x2 <> x1 ->\n    (x1 |-> v1 ; x2 |-> v2 ; m) = (x2 |-> v2 ; x1 |-> v1 ; m).\nProof.\n  intros A m x1 x2 v1 v2. unfold update.\n  apply t_update_permute.\nQed.\n", "meta": {"author": "sjxer723", "repo": "Software-fundations", "sha": "8d18a6e695ac7c897d8b717a7870f91ed2794fee", "save_path": "github-repos/coq/sjxer723-Software-fundations", "path": "github-repos/coq/sjxer723-Software-fundations/Software-fundations-8d18a6e695ac7c897d8b717a7870f91ed2794fee/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.867035771827307, "lm_q1q2_score": 0.7225222265010484}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf2 : natural) : natural :=\n  plus (mult z (Succ y)) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_assoc/goal33conj193_coqofml_MPtPe3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.722510333084885}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (lf2 : natural) : natural :=\n  plus z (plus (mult z y) lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj122_coqofml_ckQYOn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7225103299577412}}
{"text": "Require Import ZArith Arith Bool Lia.\n\nInductive poly : Type :=\n| Cst : Z -> poly\n| Poly : poly -> nat -> poly -> poly .\n\nInductive valid_pol : poly -> Prop := \n|cst : forall (z:Z), valid_pol (Cst z)  \n|compose_cst : \n\tforall (i :nat), \n\tforall (x y :Z), y <> 0%Z ->  \n\tvalid_pol (Poly (Cst x) i (Cst y)) \n|compose_l : \n\tforall (i j :nat), i < j ->\n\tforall (x :Z),  x <> 0%Z -> \n\tforall (p q : poly), valid_pol (Poly p j q) -> \n\tvalid_pol (Poly (Poly p j q) i (Cst x)) \n|compose_r : \n\tforall (i j :nat), i <= j ->\n\tforall (x :Z),  \n\tforall (p q : poly), valid_pol (Poly p j q) -> \n\tvalid_pol (Poly (Cst x) i (Poly p j q)) \n|compose_lr : \n\tforall (i j j':nat), i < j /\\ i <= j' ->\n\tforall (p q p' q': poly), valid_pol (Poly p j q) /\\ valid_pol (Poly p' j' q') -> \n\tvalid_pol (Poly (Poly p j q) i (Poly p' j' q'))\n.\n\nFixpoint valid_b (pol:poly) : bool := \nmatch pol with \n|Cst _ => true\n|Poly p i q => \n  match p,q with \n  | _, Cst 0 => false \n  |Cst _, Cst _ => true \n  |Poly _ j1 _, Cst _ => (i <? j1) && valid_b p \n  |Cst _,  (Poly p2 j2 q2) => (i <=? j2) && valid_b q \n  |(Poly p1 j1 q1),  (Poly p2 j2 q2) => \n  (i <? j1) && (i <=? j2) \n  && valid_b p && valid_b q\n  end \nend.\n\n\nRecord valid_poly : Type :=\n{ VP_value : poly ;\nVP_prop : valid_b VP_value = true }.\n\n\nRequire Import FMapList.\nRequire Import Coq.FSets.FMapList.\nRequire Import Coq.Structures.OrderedTypeEx.\nModule Import NatMap := FMapList.Make(Nat_as_OT).\nRequire Import Coq.FSets.FMapFacts.\nModule P := WProperties_fun Nat_as_OT NatMap.\nModule F := P.F.\n\nDefinition monoid : Type := NatMap.t nat.\n\n(* We could make a single definition [get_coefficient] with a dependent match to keep the polynomials proofs of validity at each recursive call, but it would makes the proofs harder. Instead we use the following definitions, with the lemma [valid_b_more] to propagate the polynomials validity proofs at each recursive call *)\nFixpoint get_coefficient_ (pol: poly) (m:monoid) := \n  match pol with \n  | Cst z => if (P.for_all (fun (k:nat) (v:nat) => v =? 0%nat ) m) then z else 0%Z \n  | Poly p i q => \n    match NatMap.find i m with \n      |None | Some 0 => get_coefficient_ p m\n      |Some n => Z.add (get_coefficient_ p m) (get_coefficient_ q (add i (n-1) m))\n      end\nend.\n\nDefinition get_coefficient (pol: valid_poly) (m:monoid) := get_coefficient_ (VP_value pol) m.\n\nLemma option_dec {A}: \n  forall (el: option A),\n    el = None \\/ exists w: A, el = Some w.\nProof.\n  intros.\n  destruct el.\n  right; exists a; trivial.\n  left; trivial.\nQed.\n\n\nFixpoint poly_val_ (pol:poly) (f : nat -> Z) := \n  match pol with \n  | Cst z => z\n  | Poly p i q => \n    Z.add (poly_val_ p f) (Z.mul (f i) (poly_val_ q f))\nend.\n\nDefinition poly_val (pol:valid_poly) (f : nat -> Z) := \n poly_val_ (VP_value pol) f \n.", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/PA/project/src/PolyDefs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7225103299344494}}
{"text": "Require Import EQ ANY.\nRequire Import Alist.\n\nRequire Import Relations.\nRequire Import Operators_Properties.\n\nDeclare Module Name : EQ.\n\nDefinition name := Name.t.\nDefinition name_eq_dec := Name.t_eq_dec.\n\nInductive type : Type :=\n| TBool : type\n| TArrow : type -> type -> type.\n\nInductive term : Type :=\n| TConst : bool -> term\n| TVar : name -> term\n| TIf : term -> term -> term -> term \n| TAbs : name -> type -> term -> term\n| TApp : term -> term -> term.\n\nModule TypeAny.\n  Definition t := type.\nEnd TypeAny.\n\nModule TypingContext := alist Name TypeAny.\n\nDefinition typing_context := TypingContext.t.\n\nInductive has_type : typing_context -> term -> type -> Prop := \n| HTConst : forall Gamma b, has_type Gamma (TConst b) TBool\n| HTVar : forall Gamma x tau, \n    TypingContext.get x Gamma = Some tau -> \n    has_type Gamma (TVar x) tau\n| HTIf : forall Gamma e1 e2 e3 tau, \n    has_type Gamma e1 TBool -> \n    has_type Gamma e2 tau -> \n    has_type Gamma e3 tau -> \n    has_type Gamma (TIf e1 e2 e3) tau\n| HTAbs : forall Gamma x tyx e tau, \n    has_type (TypingContext.shadow x tyx Gamma) e tau -> \n    has_type Gamma (TAbs x tyx e) (TArrow tyx tau)\n| HTApp : forall Gamma e1 e2 ty2 tau, \n    has_type Gamma e1 (TArrow ty2 tau) -> \n    has_type Gamma e2 ty2 -> \n    has_type Gamma (TApp e1 e2) tau.\n\nFixpoint subs (from : name) (to : term) (e : term) : term :=\n  match e with \n  | TConst _ => e\n  | TVar y => if name_eq_dec from y then to else e\n  | TIf e1 e2 e3 => TIf (subs from to e1)\n                       (subs from to e2)\n                       (subs from to e3)\n  | TAbs y tau e' => if name_eq_dec from y then e else TAbs y tau (subs from to e')\n  | TApp e1 e2 => TApp (subs from to e1) (subs from to e2)\n  end.\n\nDefinition is_value (e : term) : Prop := \n  match e with \n  | TConst _ => True\n  | TAbs _ _ _ => True\n  | _ => False\n  end.\n\nInductive step : term -> term -> Prop := \n| step_if_true : \n    forall e2 e3, \n      step (TIf (TConst true) e2 e3) e2\n| step_if_false : \n    forall e2 e3, \n      step (TIf (TConst false) e2 e3) e3\n| step_if_step : \n    forall e1 e1' e2 e3, \n      step e1 e1' -> \n      step (TIf e1 e2 e3) (TIf e1' e2 e3)\n| step_beta : \n    forall x tau e1 e2, \n      is_value e2 -> \n      step (TApp (TAbs x tau e1) e2) (subs x e2 e1)\n| step_app1 : \n    forall e1 e1' e2, \n      step e1 e1' -> \n      step (TApp e1 e2) (TApp e1' e2)\n| step_app2 : \n    forall e1 e2 e2', \n      is_value e1 -> \n      step e2 e2' -> \n      step (TApp e1 e2) (TApp e1 e2').\n\nDefinition step_star := clos_refl_trans_n1 term step.\nDefinition irreducible (e : term) : Prop := forall e', step e e' -> False.\nDefinition terminates (e : term) : Prop := exists v, irreducible v /\\ step_star e v.", "meta": {"author": "wilcoxjay", "repo": "mechanized-metatheory", "sha": "b5210d1be7a4cd6d3d8c7d6db0881a5bbefcaf2b", "save_path": "github-repos/coq/wilcoxjay-mechanized-metatheory", "path": "github-repos/coq/wilcoxjay-mechanized-metatheory/mechanized-metatheory-b5210d1be7a4cd6d3d8c7d6db0881a5bbefcaf2b/explicit-names/STLC/SyntaxAndSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7224539029305851}}
{"text": "Require Import List. \nNotation \"[]\" := nil.\nNotation \"[ a ]\" := (cons a nil).\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..). \nInfix \"::\" := cons.\n\nRequire Import Arith. \nInfix \"===\" := eq_nat_dec (at level 50). \n\nInductive term : Set := \n| var : nat -> term\n| Pi : term -> term -> term\n| abs : term -> term -> term\n| app : term -> term -> term\n| star : term\n| box : term.\nCoercion var : nat >-> term.\n\nFixpoint open_rec (k:nat) (t:term) (u:term) : term := \n  match t with \n    | var n => match (k === n) with \n                 | left Hr => u \n                 | right Hr => t\n               end\n    | Pi A B => Pi (open_rec k A u) (open_rec (S k) B u)\n    | abs A B => abs (open_rec k A u) (open_rec (S k) B u)\n    | app A B => app (open_rec k A u) (open_rec k B u) \n    | star => star \n    | box => box\n  end.\nDefinition open := open_rec 0.\n\nInductive beta_eq : term -> term -> Prop := \n| beta_eq_base : forall A B C, beta_eq (app (abs A B) C) (open B C)\n| beta_eq_refl : forall A, beta_eq A A\n| beta_eq_sym : forall A B, beta_eq A B -> beta_eq B A \n| beta_eq_trans : forall A B C, beta_eq A B -> beta_eq B C -> beta_eq A C. \nInfix \"=b=\" := beta_eq (at level 50).\n\nInductive cube : term -> term -> Prop := \n| cube_s_s : cube star star \n| cube_b_b : cube box box \n| cube_s_b : cube box star.\nInfix \"~>\" := cube (at level 50).\n\nFixpoint reduce (t:term) : term := \n  match t with \n    | var n => var n\n    | Pi A B => Pi A B\n    | abs A B => abs A B\n    | app (abs A B) C => (open B C)\n    | app A B => app (reduce A) B\n    | star => star \n    | box => box\n  end.      \n\nDefinition context := list (nat * term).\n\nReserved Notation \"G |- x ;; T\" (at level 55).\nInductive turnstile : context -> term -> term -> Set := \n| star_intro : [] |- star ;; box\n| var_intro : forall x T G, \n  In (x,T) G -> \n  G |- x ;; T\n| app_intro : forall f a A A' B G, \n  G |- f ;; (Pi A B) -> \n    G |- a ;; A' ->\n      A =b= A' -> \n      G |- (app f a) ;; (open B a)\n| lam_intro : forall x b A B G t, \n  ([(x,A)] ++ G) |- b ;; B -> \n    G |- (Pi A B) ;; t -> \n      G |- (abs A b) ;; (Pi A B)\n| pi_intro : forall x A B t s, \n  G |- A ;; s -> \n    ([(x,A)] ++ G) |- B ;; t -> \n      s ~> t -> \n      G |- (Pi A B) ;; t      \n  where \"G |- x ;; T\" := (turnstile G x T).\n\n\n\n\nDefinition varin (n:nat) (c:context) : {t | In (n,t) c} + {forall t, ~ In (n,t) c}.\nProof.\n  intros. induction c.\n  (*nil*)\n  right ; intros ; simpl ; auto.\n  (*cons*)\n  destruct a. simpl. \n  case_eq (n0 === n). \n    (* n0 = n *)\n    intros e He. rewrite e in *. \n    left. exists t. auto.\n    (* n0 <> n *)\n    intros ne Hne.\n    case_eq IHc.\n      (* In next *)  \n      intros e He.  left. inversion e. exists x. auto.\n      (* not In next *)\n      intros Hni Hnew. right. \n      intros. unfold not. intros. inversion H.\n        (* left *) \n        inversion H0. congruence.    \n        (* right *) \n        unfold not in * ; eapply Hni. eauto.\nDefined.\nInfix \"@\" := varin (at level 55).\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/poitin-coq/LangTestPTS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7224538970910643}}
{"text": "Check true.\n\nInductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\n\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 => saturday\n  | saturday => sunday\n  | sunday => monday\n  end.\n\n\nCompute next_weekday monday.\n\nExample test_next_weekday :\n  (next_weekday (next_weekday sunday)) = tuesday.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nInductive bool : Type :=\n  | true\n  | false.\n\n\nDefinition negb (b : bool) : bool :=\n  match b with\n    | true => false\n    | false => true\n  end.\n\n\nDefinition andb (b1 b2 : bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => false\n  end.\n\n\nDefinition orb (b1 b2 : bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\n\n\nExample test_orb_true_false :\n  (orb true false) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb_true_true :\n  (orb true true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb_false_false :\n  (orb false false) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_orb_false_true :\n  (orb false true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_negb_false :\n  (negb false) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_negb_true :\n  (negb true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample andb_true_true :\n  (andb true true) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample andb_true_false :\n  (andb true false) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample andb_false_true :\n  (andb false true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample andb_false_false :\n  (andb false false) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\n\nCompute (true || false).\nCompute (true && false).\n\n\nDefinition negb' (b : bool) : bool :=\n  if b then false\n  else true.\n\n\nDefinition orb' (b1 b2 : bool) : bool :=\n  if b1 then true\n  else b2.\n\n\nDefinition nandb (b1 b2 : bool) : bool :=\n  negb (andb b1 b2).\n\n\nDefinition nandb' (b1 b2 : bool) : bool :=\n  match b1 with\n  | false => true\n  | true =>\n    match b2 with\n    | true => false\n    | false => true\n    end\n  end.\n\n\n\nExample nanb_true_true :\n  (nandb true true) = false.\nProof.\n  (* compute. *)\n  reflexivity.\nQed.\n\nExample andb_true_true' :\n  (nandb' true true) = false.\nProof.\n  simpl.\n  reflexivity.\nQed.\n  \n\nCheck true : bool.\nCheck negb : bool -> bool.\n\n\n(* ------------ *)\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p: rgb).\n\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\n\n\nDefinition is_red (c : color) : bool :=\n  match c with\n  | white => false\n  | black => false\n  | primary red => true\n  | primary _ => false\n  end.\n\n\nModule Playground.\n  Definition b : rgb := blue.\nEnd Playground.\n\n  Definition b : bool := true.\n\nCheck b : bool.\nCheck Playground.b : rgb.\n  \n\nModule NatNumber.\n  Inductive nat : Type :=\n    | O\n    | S (n : nat).\n  \n  Definition pred (n : nat) : nat :=\n    match n with\n    | O => O\n    | S n' => n'\n    end.\nEnd NatNumber.\n\nCheck (S (S (S (S (S O))))).\n\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\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\nFixpoint odd (n : nat) : bool :=\n  match n with\n  | O => false\n  | S O => true\n  | S (S n') => odd n'\n  end.\n\nCompute even 4.\nCompute odd 3.\n\nExample test_even_4 :\n  (even 4) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_odd_3 :\n  (odd 3) = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\n\nModule NatNumber2.\n  Fixpoint plus (n1 n2 : nat) : nat :=\n    match n1 with\n    | O => n2\n    | S n1' => S (plus n1' n2)\n    end.\n\n  Compute (plus 3 4).\n\n  Fixpoint mult (n1 n2 : nat) : nat :=\n    match n1 with\n    | O => O\n    | S n1' => plus n2 (mult n1'  n2)\n    end.\n  \n  Example test_mult_3_3 :\n    (mult 3 3) = 9.\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Fixpoint minus (n1 n2 : nat) : nat :=\n    match n1, n2 with\n    | O, _ => O\n    | n1', O => n1'\n    | S n1', S n2' => minus n1' n2'\n    end.\n\n  Example test_minus_4_2 :\n    (minus 4 2) = 2.\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\n  (* Notation \"x + y\" := (plus x y)\n    (at level 50, left associativity) : nat_scope.\n  Notation \"x * y\" := (mult x y)\n    (at level 40, left associativity) : nat_scope.\n  Notation \"x - y\" := (minus x y)\n    (at level 50, left associativity) : nat_scope. *)\n\n  Check ((0 + 1) + 1) : nat.\n\n  Fixpoint eqb(n1 n2 : nat) : bool :=\n    match n1 with\n    | O =>\n      match n2 with\n      | O => true\n      | _ => false\n      end\n    | S n1' =>\n      match n2 with\n      | O => false\n      | S n2' => eqb n1' n2'\n      end\n    end.\n\n  Fixpoint eqb' (n1 n2 : nat) : bool :=\n    match n1, n2 with\n    | O, O => true\n    | O, _ => false\n    | _, O => false\n    | S n1', S n2' => eqb' n1' n2'\n    end.\n\n  Fixpoint leb (n1 n2 : nat) : bool :=\n    match n1, n2 with\n    | O, O => true\n    | O, _ => true\n    | _, O => false\n    | S n1', S n2' => leb n1' n2'\n    end.\n  \n  Fixpoint geb (n1 n2 : nat) : bool :=\n    match n1, n2 with\n    | O, O => true\n    | _, O => true\n    | O, _ => false\n    | S n1', S n2' => geb n1' n2'\n    end.\n  \n  Notation \"x =? y\" := (eqb x y)\n    (at level 70) : nat_scope.\n  Notation \"x <=? y\" := (leb x y)\n    (at level 70) : nat_scope.\n  Notation \"x >=? y\" := (geb x y)\n    (at level 70) : nat_scope.\n  \n  Example test_leb_3_4 :\n    (3 <=? 4) = true.\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\nEnd NatNumber2.\n\n\nFixpoint eqb(n1 n2 : nat) : bool :=\n  match n1 with\n  | O =>\n    match n2 with\n    | O => true\n    | _ => false\n    end\n  | S n1' =>\n    match n2 with\n    | O => false\n    | S n2' => eqb n1' n2'\n    end\n  end.\n\n\nFixpoint leb (n1 n2 : nat) : bool :=\n  match n1, n2 with\n  | O, O => true\n  | O, _ => true\n  | _, O => false\n  | S n1', S n2' => leb n1' n2'\n  end.\n\nFixpoint geb (n1 n2 : nat) : bool :=\n  match n1, n2 with\n  | O, O => true\n  | _, O => true\n  | O, _ => false\n  | S n1', S n2' => geb n1' n2'\n  end.\n\nNotation \"x =? y\" := (eqb x y)\n  (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y)\n  (at level 70) : nat_scope.\nNotation \"x >=? y\" := (geb x y)\n  (at level 70) : nat_scope.\n\n\nTheorem plus_O_n :\n  forall (n : nat), plus O n = n.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem plus_n_O :\n  forall (n: nat), plus n O = n.\nProof.\n  induction n.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nTheorem mult_O_n :\n  forall (n : nat), mult O n = O.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\n\nTheorem mult_n_O :\n  forall (n : nat), mult n O = O.\nProof.\n  induction n.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHn.\n    reflexivity.\nQed.\n\nTheorem plus_id :\n  forall (n m : nat), n = m -> plus n n = plus m m.\nProof.\n  intros.\n  rewrite <- H.\n    (* rewrite -> H. *)\n  reflexivity.\nQed.\n\nCheck mult_n_O.\n\n\nTheorem mult_n_o_m_o :\n  forall (p q : nat), (p * O) + (q * O) = O.\nProof.\n  intros.\n  rewrite -> mult_n_O.\n  rewrite -> mult_n_O.\n  simpl.\n  reflexivity.\n  (* induction p.\n  - simpl.\n    apply mult_n_O.\n  - intros.\n    simpl.\n    rewrite IHp.\n    reflexivity. *)\nQed.\n\n\nTheorem plus_n_S_eqb_O :\n  forall (n : nat), ((plus n (S O)) =? O) = false.\nProof.\n  intros.\n  destruct n as [| n'] eqn : E.\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\n\nTheorem negb_involutive :\n  forall (b : bool), negb (negb b) = b.\nProof.\n  intros b.\n  destruct b eqn : E.\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\n\nTheorem andb_commutative :\n  forall (a b : bool), andb a b = andb b a.\nProof.\n  intros a b;\n  destruct a, b;\n  simpl;\n  reflexivity.\nQed.\n\n\nTheorem plus_1_neq_O :\n  forall (n : nat), (plus n (S O)) =? O = false.\nProof.\n  (* intros n. destruct n. *)\n  intros [|n].\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\n\nTheorem andb_commutative' :\n  forall (a b : bool), andb a b = andb b a.\nProof.\n  intros [] [];\n  simpl;\n  reflexivity.\nQed.\n\n\n\n\n", "meta": {"author": "tor4z", "repo": "SoftwareFoundations", "sha": "ad0d3d65d0deb4c0f1ea76b54cfb5ce2d8fcdef6", "save_path": "github-repos/coq/tor4z-SoftwareFoundations", "path": "github-repos/coq/tor4z-SoftwareFoundations/SoftwareFoundations-ad0d3d65d0deb4c0f1ea76b54cfb5ce2d8fcdef6/lf/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7224510075242904}}
{"text": "From Coq Require Import Nat Reals List Arith Lia Lra.\nFrom Coquelicot Require Import Coquelicot.\n\nImport ListNotations.\n\nSection StandardLibraryLemmas.\n\nLemma nat_pred_le_lt:\n    forall n m, (n <= Nat.pred m)%nat -> (m >= 1)%nat -> (n < m)%nat.\nProof.\n    intros n m Hn Hn_ge_1.\n    compute.\n    induction m.\n    - simpl in Hn.\n      apply le_n_S in Hn.\n      apply (Nat.le_trans (S n) 1).\n      apply Hn. apply Hn_ge_1.\n    - rewrite Nat.pred_succ in Hn.\n      apply le_n_S.\n      apply Hn.\nQed.\n\nLemma f_equal2_plus_R:\n    forall x1 y1 x2 y2 : R,\n    x1 = y1 -> x2 = y2 -> x1 + x2 = y1 + y2.\nProof.\n    intros x1 y1 x2 y2.\n    lra.\nQed.\n\nLemma list_prod_empty:\n    forall A B l,\n        list_prod (A:=A) (B:=B) l [] = [].\nProof.\n    intros A B l.\n    induction l.\n    * compute. reflexivity.\n    * unfold list_prod.\n      simpl. apply IHl.\nQed.\n\nEnd StandardLibraryLemmas.\n\nSection CoquelicotGeneralLemmas.\n\nLemma coeff_Tn_default:\n    forall n T (it: Tn n T) d i,\n        (i >= n)%nat ->\n        coeff_Tn d it i = d.\nProof.\n    intros n T it d.\n    induction n. reflexivity.\n    intros i Hi.\n    unfold coeff_Tn.\n    assert (Hi2: i = S (pred i)). {\n        apply S_pred_pos. lia.\n    }\n    rewrite Hi2.\n    induction it.\n    fold (coeff_Tn (T:=T) (n:=n)). simpl.\n    specialize (IHn b (pred i)).\n    apply IHn.\n    lia.\nQed.\n\nLemma zero_is_0:\n    zero = 0.\nProof.\n    reflexivity.\nQed.\n\nLemma sum_n_m_shift:\n    forall (f: nat -> R) n m shift,\n    sum_n_m f n m = sum_n_m (fun l => f (l - shift)%nat) (n + shift) (m + shift).\nProof.\n    intros f n m shift.\n    induction shift.\n    * repeat rewrite Nat.add_0_r.\n      apply sum_n_m_ext.\n      intros n0.\n      rewrite Nat.sub_0_r.\n      reflexivity.\n    * repeat rewrite Nat.add_succ_r.\n      rewrite <- sum_n_m_S.\n      apply IHshift.\nQed.\n\nLemma floor1_tech:\n    forall r n,\n       IZR n < r -> r <= IZR n + 1 -> floor1 r = n.\nProof.\n    intros r n H1 H2.\n    unfold floor1.\n    destruct floor1_ex as [x Hx]. simpl.\n    apply Z.le_antisymm.\n    - apply Zlt_succ_le. simpl.\n      apply lt_IZR.\n      apply (Rlt_le_trans _ r).\n      * destruct Hx as [H H0].\n        apply H.\n      * destruct Hx as [H H0].\n        rewrite succ_IZR.\n        apply H2.\n    - apply Zlt_succ_le.\n      apply lt_IZR.\n      rewrite succ_IZR.\n      apply (Rlt_le_trans _ r).\n      * apply H1.\n      * destruct Hx as [H H0].\n        apply H0.\nQed. \n\nLemma floor1_plus_IZR:\n    forall r n,\n        floor1 (r + IZR n) = (floor1 r + n)%Z.\nProof.\n    intros r n.\n    apply floor1_tech.\n    * rewrite plus_IZR.\n      apply Rplus_lt_compat_r.\n      unfold floor1.\n      destruct floor1_ex.\n      simpl.\n      apply a.\n    * rewrite plus_IZR.\n      rewrite Rplus_assoc.\n      rewrite (Rplus_comm (IZR n) 1).\n      rewrite <- Rplus_assoc.\n      apply Rplus_le_compat_r.\n      unfold floor1. destruct floor1_ex. simpl.\n      destruct a. apply H0.\nQed.\n          \nEnd CoquelicotGeneralLemmas.\n\n(*---------------------------------------------------------------------------*)\n\nSection CoquelicotMatrix.\n\nLemma coeff_mat_default:\n    forall A d m n (M: matrix (T:=A) m n) i j,\n        ((i >= m)%nat \\/ (j >= n)%nat) ->\n        coeff_mat d M i j = d.\nProof.\n    intros A d m n M i j Hij.\n    destruct Hij as [Hi|Hj].\n    - unfold coeff_mat. \n      rewrite (coeff_Tn_default _ _ _ _ i); try lia.\n      destruct (lt_dec j n).\n      * apply coeff_Tn_bij; try lia.\n      * rewrite coeff_Tn_default; try lia. reflexivity.\n    - unfold coeff_mat. rewrite coeff_Tn_default; try lia. reflexivity. \nQed.\n\nDefinition transpose {m n: nat} (M: matrix m n) :=\n    mk_matrix n m (fun i j => coeff_mat 0 M j i).\n\nTheorem transpose_transpose:\n    forall m n (M: matrix m n),\n    transpose (transpose M) = M.\nProof.\n    intros m n M.\n    unfold transpose.\n    unfold transpose.\n    rewrite <- (mk_matrix_bij 0).\n    apply mk_matrix_ext.\n    intros i j Hi Hj.\n    repeat (rewrite coeff_mat_bij; try lia).\n    reflexivity.\nQed.  \n\nTheorem Mmult_Mzero: \n    forall n m (M: matrix (T:=R) m n), Mmult (n:=m) Mzero M = (Mzero (n:=n)).\nProof.\n    intros n m M.\n    unfold Mmult.\n    unfold Mzero.\n    apply mk_matrix_ext.\n    intros i j Hi Hj.\n    unfold sum_n.\n    rewrite <- (sum_n_m_const_zero 0 (Init.Nat.pred m)) at 1.\n    apply sum_n_m_ext_loc.\n    intros k Hk.\n    rewrite coeff_mat_bij; try lia.\n    rewrite Rmult_0_l.\n    reflexivity.\nQed.\n\nDefinition scalar_mult {m n: nat} (c:R) (v: matrix m n) :=\n    mk_matrix m n (fun i j => c * coeff_mat 0 v i j).\n\nEnd CoquelicotMatrix.\n\n(*---------------------------------------------------------------------------*)\n\n(** * Theory of column vectors\n\nBasic theory of column vectors, wrapper for Coquelicot matricies\n\nOperations:\n- Contruction via mk_colvec\n- Coefficients retrieval via coeff_colvec\n- Special cases: dimesion zero vectors, null vectors\n- Conversions to n*1 and 1*n matricies\n- Dot product\n*)\n\nSection ColumnVectors.\n\n(* Column vector is a 1d matrix *)\nDefinition colvec m := matrix (T:=R) m 1.\n\n(* There is only a single colvec of dimension zero *)\nLemma unique_colvec_0:\n    forall (v1: colvec 0) (v2: colvec 0),\n        v1 = v2.\nProof.\n    intros v1 v2.\n    rewrite <- (mk_matrix_bij 0 v1).\n    rewrite <- (mk_matrix_bij 0 v2).\n    apply mk_matrix_ext.\n    intros i j Hi Hj.\n    rewrite coeff_mat_default; try lia.\nQed.\n\n(* Coeficient of a colvec V[i] with x0 as default value*)\nDefinition coeff_colvec {m: nat} (x0: R) (V:colvec m) (i:nat) :=\n  coeff_mat x0 V i 0.\n\n(* Construction of a colvec *)\nDefinition mk_colvec m (f: nat -> R) : colvec m := \n    mk_matrix m 1 (fun i j => (f i)).\n\n(* Dot product *)\nDefinition dot {n:nat} (c1: colvec n) (c2: colvec n) : R :=\n    coeff_mat 0 (Mmult (transpose c1) c2) 0 0.\n\n(* Null vector *)\nDefinition null_vector m := mk_colvec m (fun i => 0).\n\n(* Associativity of multiplication with constant and dot product *)\nTheorem dot_scalar_mult:\n    forall dim c (v1: colvec dim) (v2: colvec dim),\n    dot (scalar_mult c v1) v2 = Rmult c (dot v1 v2).\nProof.\n    intros dim c v1 v2.\n    unfold dot.\n    unfold Mmult.\n    repeat rewrite (coeff_mat_bij _ _ 0 0 Nat.lt_0_1 Nat.lt_0_1).\n    rewrite <- (sum_n_mult_l c).\n    apply sum_n_ext_loc.\n    intros n Hloc.\n    induction dim.\n    * compute. lra.\n    * assert (Hdim: (S dim >= 1)%nat). lia.\n      pose proof (nat_pred_le_lt n (S dim) Hloc Hdim) as Hndim.\n      unfold scalar_mult.\n      unfold transpose.\n      rewrite (coeff_mat_bij _ _ 0 n Nat.lt_0_1 Hndim).\n      unfold mk_colvec.\n      rewrite (coeff_mat_bij _ _ 0 n Nat.lt_0_1 Hndim).\n      unfold coeff_colvec.\n      rewrite (coeff_mat_bij _ _ n 0 Hndim Nat.lt_0_1).\n      rewrite Rmult_assoc.\n      reflexivity.\nQed.\n\n(* 0 dot v1 = 0 *)\nTheorem dot_null_vector:\n    forall dim x, dot (null_vector dim) x = 0.\nProof.\n    intros dim x.\n    unfold dot.\n    unfold Mmult.\n    rewrite (coeff_mat_bij _ _ 0 0 Nat.lt_0_1 Nat.lt_0_1).\n    unfold sum_n.\n    unfold coeff_colvec.\n    unfold null_vector.\n    unfold mk_colvec.\n    rewrite <- zero_is_0.\n    rewrite <- (sum_n_m_const_zero (G:=R_AbelianGroup) 0 (Nat.pred dim)) at 1.\n    apply sum_n_m_ext_loc.\n    intros n Hn.\n    destruct Hn.\n    induction dim.\n    * compute. lra.\n    * assert (Hdim: (S dim >= 1)%nat). lia. \n      pose proof (nat_pred_le_lt n (S dim) H0 Hdim) as Hndim.\n      unfold transpose.\n      rewrite (coeff_mat_bij _ _ 0 n Nat.lt_0_1 Hndim). \n      rewrite (coeff_mat_bij _ _ n 0 Hndim Nat.lt_0_1).\n      rewrite Rmult_0_l.\n      reflexivity.\nQed.\n\n(* v1 + 0 = v1 *)\nTheorem Mplus_null_vector: \n    forall dim v, Mplus v (null_vector dim) = v.\nProof. \n    intros dim v.\n    unfold Mplus. unfold colvec in v. unfold null_vector. unfold mk_colvec.\n    rewrite <- (mk_matrix_bij 0 v) at 1.\n    apply mk_matrix_ext.\n    intros i j Hi Hj.\n    unfold coeff_colvec.\n    rewrite (coeff_mat_bij 0 (fun _ _ => 0) i j).\n    rewrite Rplus_0_r. \n    induction j. reflexivity. lia.\n    apply Hi. lia. \nQed.\n\n(* For a matrix M and a vector v, M*v can be split into multiple\n   dot products over matrix rows *)\nTheorem Mmult_dot_split:\n    forall n m M v, Mmult M v = mk_colvec n (\n        fun i => \n            dot (mk_colvec m (fun j => coeff_mat 0 M i j)) v\n    ).\nProof.\n    intros n m M V.\n    unfold Mmult. \n    unfold mk_colvec. unfold dot. unfold Mmult. \n    apply mk_matrix_ext.\n    intros i j Hi Hj.\n    rewrite coeff_mat_bij.\n    apply sum_n_ext_loc.\n    intros n0 Hn0.\n    induction m.\n    * compute. lra.\n    * unfold transpose.\n      rewrite coeff_mat_bij.\n      unfold coeff_colvec.\n      rewrite coeff_mat_bij.\n      induction j. reflexivity. lia.\n      apply nat_pred_le_lt. apply Hn0. lia. lia. lia.\n      apply nat_pred_le_lt. apply Hn0. lia. lia. lia.\nQed.\n\n(* v1 * (v2 + v3) = v1 * v2 + v1 * v3 *)\nTheorem dot_Mplus_distr:\n    forall dim (v1: colvec dim) v2 v3,\n        dot v1 (Mplus v2 v3) = (dot v1 v2) + (dot v1 v3).\nProof.\n    intros dim v1 v2 c3.\n    unfold dot.\n    unfold Mplus.\n    unfold Mmult.\n    repeat (rewrite coeff_mat_bij; try lia).\n    assert (Hplus: forall a b, a + b = plus a b). { reflexivity. }\n    rewrite Hplus.\n    rewrite <- sum_n_plus.\n    apply sum_n_ext_loc.\n    intros n Hn.\n    unfold mk_colvec. unfold coeff_colvec.\n    induction dim.\n    * compute. lra.\n    * repeat (rewrite coeff_mat_bij; try lia).\n      rewrite Rmult_plus_distr_l. reflexivity.\nQed. \n\n(* Associativity of dot and matrix multiplication via transposition.\n   For matrix M and vectors v1 v2: v1 * (M * v2) = (v1^T * M)^T * v2 *)\nTheorem dot_Mmult:\n    forall m n v1 (M: matrix m n) v2,\n        dot v1 (Mmult M v2) = dot (transpose (Mmult (transpose v1) M)) v2.\nProof.\n    intros m n v1 M v2.\n    unfold dot.\n    repeat rewrite colvec2matrix_spec.\n    rewrite Mmult_assoc.\n    rewrite transpose_transpose.\n    reflexivity.\nQed.    \n\nEnd ColumnVectors.\n\n(*---------------------------------------------------------------------------*)\n\nSection ReshapeOperations.\n\nDefinition block_diag_matrix \n    {in_dim1 in_dim2 out_dim1 out_dim2: nat}  \n    (M1: matrix (T:=R) out_dim1 in_dim1)\n    (M2: matrix (T:=R) out_dim2 in_dim2): \n    matrix (out_dim1 + out_dim2) (in_dim1 + in_dim2) :=\n    mk_matrix (out_dim1 + out_dim2) (in_dim1 + in_dim2) \n        (fun i j => \n            if (ltb i out_dim1) then \n                (if (ltb j in_dim1) then\n                    coeff_mat 0 M1 i j\n                else\n                    0)\n            else \n                (if (ltb j in_dim1) then\n                    0\n                else \n                    coeff_mat 0 M2 (i - out_dim1) (j - in_dim1))\n        ).\n\nDefinition extend_colvec_at_bottom {n: nat} (v: colvec n) (new_dim: nat) :=\n    mk_colvec new_dim (\n        fun i =>\n        match i <? n with\n        | true => coeff_colvec 0 v i\n        | false => 0\n        end \n    ).\n\nLemma extend_colvec_at_bottom_same_dim:\n    forall d (v: colvec d),\n        extend_colvec_at_bottom v d = v.\nProof.\n    intros d v.\n    unfold colvec in v.\n    unfold extend_colvec_at_bottom.\n    rewrite <- (mk_matrix_bij 0 v) at 1.\n    unfold mk_colvec.\n    destruct d.\n    * apply unique_colvec_0.\n    * apply mk_matrix_ext.\n      intros i j Hi Hj.\n      rewrite <- Nat.ltb_lt in Hi.\n      rewrite Hi.\n      unfold coeff_colvec.\n      induction j.\n      - reflexivity.\n      - lia.\nQed.\n\nLemma extend_colvec_at_bottom_preserves_equality:\n    forall d1 d2 (v1: colvec d1) v2,\n      v1 = v2 <->\n      extend_colvec_at_bottom v1 (d1 + d2) = extend_colvec_at_bottom v2 (d1 + d2).\nProof.  \n    intros d1 d2 v1 v2.\n    rewrite <- (mk_matrix_bij 0 v1).\n    rewrite <- (mk_matrix_bij 0 v2).\n    split.\n    {\n      intros Hequal.\n      unfold colvec in v1. unfold colvec in v2.\n      unfold extend_colvec_at_bottom.\n      unfold mk_colvec.\n      apply mk_matrix_ext.\n      intros i j Hi Hj.\n      remember (i <? d1) as r.\n      destruct r; try reflexivity.\n      symmetry in Heqr. rewrite Nat.ltb_lt in Heqr.\n      pose proof (mk_matrix_ext (T:=R)) as Hext.\n      specialize (Hext d1 1%nat (coeff_mat 0 v1) (coeff_mat 0 v2)).\n      unfold coeff_colvec.\n      repeat (rewrite coeff_mat_bij; try lia).\n      apply Hext; try lia.\n      apply Hequal.\n    }\n    {\n      intros Hequal.\n      apply mk_matrix_ext.\n      intros i j Hi Hj.\n      unfold extend_colvec_at_bottom in Hequal.\n      unfold mk_colvec in Hequal.\n      pose proof (mk_matrix_ext (T:=R)) as Hext.\n      specialize (Hext (d1 + d2)%nat 1%nat).\n      specialize (Hext (fun i _ : nat => \n                          if i <? d1 then \n                            coeff_colvec 0 (mk_matrix d1 1 (coeff_mat 0 v1)) i\n                          else \n                            0)).\n      specialize (Hext (fun i _ : nat => \n                          if i <? d1 then \n                            coeff_colvec 0 (mk_matrix d1 1 (coeff_mat 0 v2)) i\n                          else \n                            0)).\n      destruct Hext as [Hext1 Hext2].               \n      specialize (Hext2 Hequal).\n      specialize (Hext2 i j).\n      pose proof Hi as Hi_cp.\n      rewrite <- Nat.ltb_lt in Hi.\n      rewrite Hi in Hext2.\n      unfold coeff_colvec in Hext2.\n      repeat (rewrite coeff_mat_bij in Hext2; try lia).\n      induction j.\n      * apply Hext2; try lia.\n      * lia.\n    }\nQed.\n\nDefinition extend_colvec_on_top {n: nat} (v: colvec n) (new_dim: nat) :=\n    mk_colvec new_dim (\n        fun i => \n        match i <? (new_dim - n) with\n        | true => 0\n        | false => coeff_colvec 0 v (i - (new_dim - n))\n        end\n    ).\n\nLemma extend_colvec_on_top_same_dim:\n    forall d (v: colvec d),\n      extend_colvec_on_top v d = v.    \nProof.\n    intros d v.\n    unfold colvec in v.\n    unfold extend_colvec_on_top.\n    rewrite <- (mk_matrix_bij 0 v) at 1.\n    unfold mk_colvec.\n    destruct d.\n    * apply unique_colvec_0.\n    * apply mk_matrix_ext.\n      intros i j Hi Hj.\n      rewrite Nat.sub_diag. \n      simpl.\n      unfold coeff_colvec.\n      rewrite Nat.sub_0_r.\n      induction j.\n      - reflexivity.\n      - lia.\nQed.    \n\nLemma extend_colvec_on_top_preserves_equality:\n    forall d1 d2 (v1: colvec d2) v2,\n      v1 = v2 <->\n      extend_colvec_on_top v1 (d1 + d2) = extend_colvec_on_top v2 (d1 + d2).\nProof.  \n    intros d1 d2 v1 v2.\n    rewrite <- (mk_matrix_bij 0 v1).\n    rewrite <- (mk_matrix_bij 0 v2).\n    split.\n    {\n      intros Hequal.\n      unfold colvec in v1. unfold colvec in v2.\n      unfold extend_colvec_on_top.\n      unfold mk_colvec.\n      apply mk_matrix_ext.\n      intros i j Hi Hj.\n      rewrite Nat.add_sub.\n      remember (i <? d1) as r.\n      destruct r; try reflexivity.\n      symmetry in Heqr. rewrite Nat.ltb_ge in Heqr.\n      pose proof (mk_matrix_ext (T:=R)) as Hext.\n      specialize (Hext d2 1%nat (coeff_mat 0 v1) (coeff_mat 0 v2)).\n      unfold coeff_colvec.\n      repeat (rewrite coeff_mat_bij; try lia).\n      apply Hext; try lia.\n      apply Hequal.\n    }\n    {\n      intros Hequal.\n      apply mk_matrix_ext.\n      intros i j Hi Hj.\n      unfold extend_colvec_on_top in Hequal.\n      unfold mk_colvec in Hequal.\n      rewrite Nat.add_sub in Hequal.\n      pose proof (mk_matrix_ext (T:=R)) as Hext.\n      specialize (Hext (d1 + d2)%nat 1%nat).\n      specialize (Hext (fun i _ : nat => \n                          if i <? d1 then \n                            0\n                          else \n                            coeff_colvec 0 (mk_matrix d2 1 (coeff_mat 0 v1)) (i - d1))).\n      specialize (Hext (fun i _ : nat => \n                          if i <? d1 then \n                            0\n                          else \n                            coeff_colvec 0 (mk_matrix d2 1 (coeff_mat 0 v2)) (i - d1))).\n      destruct Hext as [Hext1 Hext2].               \n      specialize (Hext2 Hequal).\n      specialize (Hext2 (i + d1)%nat j).\n      assert (Hi2: (d1 <= i + d1)%nat). lia.\n      rewrite <- Nat.ltb_ge in Hi2.\n      rewrite Hi2 in Hext2.\n      rewrite Nat.add_sub in Hext2.\n      unfold coeff_colvec in Hext2.\n      repeat (rewrite coeff_mat_bij in Hext2; try lia).\n      induction j.\n      * apply Hext2; try lia.\n      * lia.\n    }\nQed.\n\nDefinition colvec_concat {n m: nat} (v1: colvec n) (v2: colvec m) :=\n    Mplus (extend_colvec_at_bottom v1 (n + m)) (extend_colvec_on_top v2 (n + m)).\n\nLemma dot_extend_at_bottom:\n    forall d1 d2 (v: colvec d1) x1 x2,\n        dot (extend_colvec_at_bottom v (d1 + d2)) (colvec_concat x1 x2) =\n        dot v x1.\nProof.\n    intros d1 d2 v x1 x2.\n    destruct d1.\n    * destruct d2.\n      - rewrite (unique_colvec_0 (extend_colvec_at_bottom v (0 + 0)) v).\n        rewrite (unique_colvec_0 (colvec_concat x1 x2) x1).\n        reflexivity.\n      - unfold dot.\n        unfold Mmult.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite sum_O.\n        rewrite coeff_mat_default; try lia.\n        rewrite Rmult_0_l. rewrite Nat.add_0_l at 1.\n        rewrite <- zero_is_0.\n        rewrite <- (sum_n_m_const_zero (G:=R_AbelianGroup) 0 (d2)).\n        apply sum_n_ext_loc.\n        intros n Hn.\n        unfold transpose.\n        unfold extend_colvec_at_bottom.\n        unfold mk_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        simpl.\n        apply Rmult_0_l.\n    * destruct d2.\n      - unfold dot.\n        unfold Mmult.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.add_0_r at 1.\n        apply sum_n_ext_loc.\n        intros n Hn.\n        unfold transpose.\n        unfold extend_colvec_at_bottom. unfold mk_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        simpl in Hn.\n        unfold colvec_concat.\n        unfold Mplus.\n        unfold extend_colvec_at_bottom.\n        unfold extend_colvec_on_top.\n        unfold mk_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.add_sub.\n        apply le_lt_n_Sm in Hn.\n        rewrite <- Nat.ltb_lt in Hn.\n        rewrite Hn.\n        unfold coeff_colvec.\n        rewrite Rplus_0_r.\n        reflexivity.\n      - unfold extend_colvec_at_bottom.\n        unfold colvec_concat.\n        unfold dot. unfold Mmult.\n        repeat (rewrite coeff_mat_bij; try lia).\n        unfold sum_n. simpl.\n        rewrite <- (Rplus_0_r (sum_n_m _ 0 (d1))).\n        rewrite (sum_n_m_Chasles _ _ d1 (d1 + S d2)); try lia.\n        apply f_equal2_plus_R.\n        * apply sum_n_ext_loc.\n          intros n Hn.\n          unfold transpose.\n          unfold Mplus.\n          unfold extend_colvec_at_bottom.\n          unfold extend_colvec_on_top.\n          unfold mk_colvec.\n          repeat (rewrite coeff_mat_bij; try lia).\n          rewrite <- Nat.add_succ_l.\n          rewrite Nat.add_sub.\n          apply le_lt_n_Sm in Hn.\n          rewrite <- Nat.ltb_lt in Hn.\n          rewrite Hn.\n          unfold coeff_colvec.\n          rewrite Rplus_0_r.\n          reflexivity.\n        * simpl.\n          rewrite <- zero_is_0.\n          rewrite <- (sum_n_m_const_zero (G:=R_AbelianGroup) (S d1) (d1 + S d2)) at 1.\n          apply sum_n_m_ext_loc.\n          intros k Hk.\n          unfold transpose.\n          unfold Mplus.\n          unfold extend_colvec_at_bottom.\n          unfold extend_colvec_on_top.\n          unfold mk_colvec.\n          repeat (rewrite coeff_mat_bij; try lia).\n          destruct Hk.\n          rewrite <- Nat.ltb_ge in H.\n          rewrite H.\n          rewrite Rmult_0_l.\n          reflexivity.\nQed.\n\nLemma dot_extend_on_top:\n    forall d1 d2 (v: colvec d2) x1 x2,\n        dot (extend_colvec_on_top v (d1 + d2)) (colvec_concat x1 x2) =\n        dot v x2.\nProof.\n    intros d1 d2 v x1 x2.\n    destruct d1.\n    * destruct d2.\n      - rewrite (unique_colvec_0 (extend_colvec_on_top v (0 + 0)) v).\n        rewrite (unique_colvec_0 (colvec_concat x1 x2) x1).\n        reflexivity.\n      - unfold dot.\n        unfold Mmult.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.add_0_l at 1.\n        apply sum_n_ext_loc.\n        intros n Hn.\n        unfold transpose.\n        unfold extend_colvec_at_bottom. unfold mk_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        simpl in Hn.\n        unfold colvec_concat.\n        unfold Mplus.\n        unfold extend_colvec_at_bottom.\n        unfold extend_colvec_on_top.\n        unfold mk_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.add_sub. simpl.\n        unfold coeff_colvec.\n        rewrite Rplus_0_l.\n        rewrite Nat.sub_0_r.\n        reflexivity.\n    * destruct d2.\n      - unfold dot.\n        unfold Mmult.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite sum_O.\n        rewrite coeff_mat_default; try lia.\n        rewrite Rmult_0_l. rewrite Nat.add_0_r at 1.\n        rewrite <- zero_is_0.\n        rewrite <- (sum_n_m_const_zero (G:=R_AbelianGroup) 0 (d1)).\n        apply sum_n_ext_loc.\n        intros n Hn.\n        unfold transpose.\n        unfold extend_colvec_on_top.\n        unfold mk_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.add_sub.\n        apply le_lt_n_Sm in Hn.\n        rewrite <- Nat.ltb_lt in Hn.\n        rewrite Hn.\n        apply Rmult_0_l.\n      - unfold extend_colvec_on_top.\n        unfold colvec_concat.\n        unfold dot. unfold Mmult.\n        repeat (rewrite coeff_mat_bij; try lia).\n        unfold sum_n. simpl.\n        rewrite <- (Rplus_0_l (sum_n_m _ 0 (d2))).\n        rewrite (sum_n_m_Chasles _ _ d1 (d1 + S d2)); try lia.\n        apply f_equal2_plus_R.\n        * simpl.\n          rewrite <- zero_is_0.\n          rewrite <- (sum_n_m_const_zero (G:=R_AbelianGroup) 0 d1) at 1.\n          apply sum_n_m_ext_loc.\n          intros k Hk.\n          unfold transpose.\n          unfold Mplus.\n          unfold extend_colvec_at_bottom.\n          unfold extend_colvec_on_top.\n          unfold mk_colvec.\n          repeat (rewrite coeff_mat_bij; try lia).\n          simpl.\n          rewrite Nat.add_succ_r.\n          rewrite <- Nat.add_succ_l.\n          rewrite Nat.add_sub.\n          destruct Hk.\n          apply le_lt_n_Sm in H0.\n          rewrite <- Nat.ltb_lt in H0.\n          rewrite H0.\n          rewrite Rmult_0_l.\n          reflexivity.\n        * rewrite (sum_n_m_shift _ 0 d2 (S d1)).\n          rewrite Nat.add_0_l.\n          rewrite Nat.add_succ_r at 1.\n          rewrite (Nat.add_succ_r d2 d1).\n          rewrite (Nat.add_comm d1 d2).\n          apply sum_n_m_ext_loc.\n          intros n Hn.\n          unfold transpose.\n          unfold Mplus.\n          unfold extend_colvec_at_bottom.\n          unfold extend_colvec_on_top.\n          unfold mk_colvec.\n          repeat (rewrite coeff_mat_bij; try lia).\n          rewrite Nat.add_succ_r at 1.\n          do 2 rewrite <- Nat.add_succ_l.\n          do 2 rewrite Nat.add_sub.\n          destruct Hn.\n          rewrite <- Nat.ltb_ge in H.\n          rewrite H.\n          unfold coeff_colvec.\n          rewrite Nat.add_succ_r.\n          rewrite <- Nat.add_succ_l.\n          rewrite Nat.add_sub.\n          rewrite Rplus_0_l.\n          reflexivity.\nQed.\n\nLemma colvec_concat_eq:\n    forall d1 d2 (v1: colvec d1) (v2: colvec d2) v3 v4,\n        v1 = v3 -> v2 = v4 ->\n        colvec_concat v1 v2 = colvec_concat v3 v4.\nProof.\n    intros d1 d2 v1 v2 v3 v4 Hv13 Hv24.\n    unfold colvec_concat.\n    rewrite Hv13. rewrite Hv24.\n    reflexivity.\nQed.\n\nLemma Mplus_colvec_concat:\n    forall d1 d2 (v1: colvec d1) (v2: colvec d2) v3 v4,\n        Mplus (colvec_concat v1 v2) (colvec_concat v3 v4) =\n        colvec_concat (Mplus v1 v3) (Mplus v2 v4).\nProof.\n    intros d1 d2 v1 v2 v3 v4.\n    unfold colvec_concat.\n    rewrite (Mplus_assoc _ (extend_colvec_at_bottom v3 _) _).\n    rewrite <- (Mplus_assoc (extend_colvec_at_bottom v1 _) _ _).\n    rewrite (Mplus_comm (extend_colvec_on_top v2 _) (extend_colvec_at_bottom v3 _)).\n    rewrite (Mplus_assoc (extend_colvec_at_bottom v1 _) _ _).\n    rewrite <- (Mplus_assoc _ (extend_colvec_on_top v2 _) _).\n    unfold Mplus.\n    apply mk_matrix_ext.\n    intros i j Hi Hj.\n    destruct d1.\n    - destruct d2.\n      * lia.\n      * unfold extend_colvec_at_bottom.\n        unfold extend_colvec_on_top.\n        unfold mk_colvec. unfold coeff_colvec.\n        do 7 (rewrite coeff_mat_bij; try lia).\n        simpl. rewrite Nat.sub_diag. simpl.\n        repeat rewrite Rplus_0_l.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.sub_0_r.\n        reflexivity.\n    - destruct d2.\n      * unfold extend_colvec_at_bottom.\n        unfold extend_colvec_on_top.\n        unfold mk_colvec. unfold coeff_colvec.\n        do 9 (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.add_sub. \n        rewrite Nat.add_0_r in Hi.\n        rewrite <- Nat.ltb_lt in Hi.\n        rewrite Hi. rewrite Rplus_0_l. reflexivity.\n      * unfold extend_colvec_at_bottom.\n        unfold extend_colvec_on_top.\n        unfold mk_colvec. unfold coeff_colvec.\n        do 7 (rewrite coeff_mat_bij; try lia).\n        rewrite (coeff_mat_bij (m:=(S d1 + S d2))); try lia.\n        rewrite Nat.add_sub.\n        remember (i <? S d1) as r.\n        destruct r.\n        - repeat rewrite Rplus_0_r.\n          symmetry in Heqr. rewrite Nat.ltb_lt in Heqr.\n          rewrite coeff_mat_bij; try lia.\n          reflexivity.\n        - repeat rewrite Rplus_0_l.\n          symmetry in Heqr. rewrite Nat.ltb_ge in Heqr. \n          rewrite coeff_mat_bij; try lia.\n          reflexivity.\nQed.   \n\nLemma MMmult_block_diag_matrix:\n    forall m1 n1 m2 n2 (A1: matrix m1 n1) (A2: matrix m2 n2)\n        (v1: colvec n1) (v2: colvec n2),\n        Mmult (block_diag_matrix A1 A2) (colvec_concat v1 v2) = \n        colvec_concat (Mmult A1 v1) (Mmult A2 v2).\nProof.\n    intros m1 n1 m2 n2 A1 A2 v1 v2.\n    unfold colvec_concat.\n    rewrite (Mmult_distr_l (block_diag_matrix A1 A2) _ _).\n    unfold Mplus.\n    apply mk_matrix_ext.\n    intros i j Hi Hj.\n    induction j; try lia.\n    destruct (lt_dec i m1) as [Hile|Helt].\n    - destruct m1. lia. simpl in Hile.\n      assert (H1: coeff_mat zero \n        (Mmult (block_diag_matrix A1 A2) (extend_colvec_on_top v2 _)) i 0 = 0). { \n        unfold Mmult.\n        rewrite coeff_mat_bij; try lia.\n        unfold sum_n.\n        rewrite <- zero_is_0.\n        rewrite <- (sum_n_m_const_zero (G:=R_AbelianGroup) 0 (pred (n1 + n2))).\n        destruct (le_gt_dec (n1 + n2) 0).\n        - apply le_n_0_eq in l.\n          repeat rewrite <- l at 1. simpl. \n          repeat rewrite sum_n_n.\n          rewrite (coeff_mat_default _ _ _ _ _ 0 0); try lia.\n          apply Rmult_0_r.\n        - apply sum_n_m_ext_loc.\n          intros n Hn.\n          unfold extend_colvec_on_top.\n          unfold mk_colvec. unfold coeff_colvec.\n          rewrite coeff_mat_bij; try lia.\n          rewrite Nat.add_sub.\n          remember (n <? n1) as r.\n          induction r.\n          * apply Rmult_0_r.\n          * unfold block_diag_matrix.\n            rewrite coeff_mat_bij; try lia.\n            apply Nat.ltb_lt in Hile.\n            rewrite Hile. rewrite <- Heqr.\n            apply Rmult_0_l.\n      }\n      rewrite H1. rewrite Rplus_0_r.\n      assert (H2: coeff_mat zero (\n        extend_colvec_on_top (Mmult A2 v2) (S m1 + m2)) i 0 = 0). {\n        unfold extend_colvec_on_top. unfold mk_colvec.\n        rewrite coeff_mat_bij; try lia.\n        rewrite Nat.add_sub.\n        apply Nat.ltb_lt in Hile.\n        rewrite Hile. reflexivity.\n      }\n      rewrite H2. rewrite Rplus_0_r.\n      unfold Mmult at 1. \n      repeat rewrite coeff_mat_bij; try lia.\n      unfold sum_n. rewrite (sum_n_m_Chasles _ _ (pred n1) _); try lia.\n      rewrite <- (Rplus_0_r (coeff_mat zero \n        (extend_colvec_at_bottom (Mmult A1 v1) (S m1 + m2)) i 0)).\n      apply f_equal2_plus_R.\n      * unfold extend_colvec_at_bottom.\n        unfold mk_colvec. unfold coeff_colvec.\n        rewrite coeff_mat_bij; try lia.\n        rewrite <- Nat.ltb_lt in Hile. rewrite Hile.\n        unfold Mmult. rewrite Nat.ltb_lt in Hile.\n        rewrite coeff_mat_bij; try lia.\n        unfold sum_n. apply sum_n_m_ext_loc.\n        intros k Hk.\n        induction n1.\n        * simpl in Hk.\n          destruct Hk as [Hk1 Hk2].\n          apply le_n_0_eq in Hk2.\n          rewrite <- Hk2. simpl.\n          induction n2.\n          * rewrite coeff_mat_default; try lia.\n            rewrite (coeff_mat_default _ _ _ _ v1); try lia.\n            rewrite Rmult_0_l. rewrite Rmult_0_r. reflexivity.\n          * rewrite coeff_mat_bij; try lia.\n            rewrite (coeff_mat_default _ _ _ _ v1); try lia.\n            repeat rewrite Rmult_0_r. reflexivity.\n        * rewrite coeff_mat_bij; try lia.\n          unfold block_diag_matrix.\n          rewrite coeff_mat_bij; try lia.\n          rewrite <- Nat.ltb_lt in Hile. rewrite Hile.\n          remember (k <? S n1) as r.\n          induction r.\n          - reflexivity.\n          - symmetry in Heqr. rewrite Nat.ltb_ge in Heqr. lia.\n      * unfold extend_colvec_at_bottom.\n        unfold mk_colvec. unfold coeff_colvec.\n        rewrite <- zero_is_0.\n        rewrite <- (sum_n_m_const_zero \n            (G:=R_AbelianGroup) (S (pred n1)) (pred (n1 + n2))).\n        apply sum_n_m_ext_loc.\n        intros k Hk.\n        rewrite coeff_mat_bij; try lia.\n        rewrite sum_n_m_const_zero.\n        destruct Hk.\n        remember (k <? n1) as r.\n        induction r.\n        * symmetry in Heqr. rewrite Nat.ltb_lt in Heqr. lia.\n        * apply Rmult_0_r.  \n    - apply not_lt in Helt.\n      assert (Hib: i <? m1 = false). {\n         rewrite Nat.ltb_ge.\n         lia.\n      }\n      apply f_equal2_plus_R.\n      * assert (H1: coeff_mat zero \n        (Mmult (block_diag_matrix A1 A2) (extend_colvec_at_bottom v1 _)) i 0 = 0). \n        { \n            unfold Mmult.\n            rewrite coeff_mat_bij; try lia.\n            unfold sum_n.\n            rewrite <- zero_is_0.\n            rewrite <- (sum_n_m_const_zero (G:=R_AbelianGroup) 0 (pred (n1 + n2))).\n            apply sum_n_m_ext_loc.\n            intros n Hn.\n            destruct (le_gt_dec (n1 + n2) 0).\n            - apply le_n_0_eq in l.\n              rewrite (coeff_mat_default _ _ _ _ _ n 0); try lia.\n              apply Rmult_0_r.\n            - unfold extend_colvec_at_bottom.\n              unfold mk_colvec. unfold coeff_colvec.\n              rewrite coeff_mat_bij; try lia.\n              unfold block_diag_matrix.\n              rewrite coeff_mat_bij; try lia.\n              rewrite Hib.\n              destruct (n <? n1).\n              - apply Rmult_0_l.\n              - apply Rmult_0_r.\n        }\n        rewrite H1.\n        assert (H2: coeff_mat zero (\n            extend_colvec_at_bottom (Mmult A1 v1) (m1 + m2)) i 0 = 0). {\n            unfold extend_colvec_at_bottom. unfold mk_colvec.\n            rewrite coeff_mat_bij; try lia.\n            rewrite Hib.\n            reflexivity.\n        }\n        rewrite H2.\n        reflexivity.\n      * unfold extend_colvec_on_top. unfold block_diag_matrix.\n        unfold Mmult. unfold mk_colvec. unfold coeff_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        repeat rewrite Nat.add_sub.\n        rewrite Hib.\n        destruct n1.\n        * destruct n2.\n          * repeat rewrite sum_n_n.\n            repeat rewrite coeff_mat_default; try lia.\n            reflexivity.\n          * apply sum_n_ext_loc.\n            intros n Hn. simpl.\n            repeat rewrite coeff_mat_bij; try lia.\n            rewrite Hib. rewrite <- zero_is_0.\n            rewrite Nat.sub_0_r. reflexivity.\n        * rewrite <- (Rplus_0_l (sum_n _ (pred n2))).\n          unfold sum_n. \n          rewrite (sum_n_m_Chasles _ _ (pred (S n1)) _); try lia.\n          apply f_equal2_plus_R.\n          - rewrite <- zero_is_0.\n            rewrite <- (sum_n_m_const_zero \n              (G:=R_AbelianGroup) 0 (pred (S n1))).\n            apply sum_n_m_ext_loc.\n            intros k Hk.\n            rewrite coeff_mat_bij; try lia.\n            rewrite Hib.\n            destruct Hk.\n            simpl in H0.\n            apply le_lt_n_Sm in H0.\n            rewrite <- Nat.ltb_lt in H0.\n            rewrite H0.\n            rewrite sum_n_m_const_zero.\n            rewrite Rmult_0_l. apply zero_is_0.\n        - destruct n2.\n          * rewrite sum_n_m_zero; try lia.\n            rewrite sum_n_n.\n            rewrite (coeff_mat_default _ _ _ _ v2); try lia.\n            rewrite Rmult_0_r. apply zero_is_0.\n          * rewrite (sum_n_m_shift _ 0 _ (S (pred (S n1)))). simpl.\n            rewrite <- Nat.add_succ_comm.\n            rewrite (Nat.add_comm n2 _).\n            apply sum_n_m_ext_loc.\n            intros k Hk.\n            repeat (rewrite coeff_mat_bij; try lia).\n            rewrite Hib.\n            remember (k <? S n1) as r.\n            induction r.\n            * symmetry in Heqr. rewrite Nat.ltb_lt in Heqr. lia.\n            * rewrite <- zero_is_0. reflexivity.  \nQed.\n\nLemma dot_concat:\n    forall d1 d2 (v1: colvec d1) (v2:colvec d2) v3 v4,\n      dot (colvec_concat v1 v2) (colvec_concat v3 v4) =\n      dot v1 v3 + dot v2 v4.\nProof.\n    intros d1 d2 v1 v2 v3 v4.\n    unfold dot.\n    unfold Mmult.\n    repeat (rewrite coeff_mat_bij; try lia).\n    unfold sum_n.\n    destruct d1.\n    * destruct d2.\n      - simpl. repeat rewrite sum_n_n.\n        repeat rewrite coeff_mat_default; try lia.\n        rewrite Rmult_0_l. rewrite Rplus_0_l. reflexivity.\n      - simpl.\n        rewrite sum_n_n.\n        rewrite coeff_mat_default; try lia.\n        rewrite Rmult_0_l. rewrite Rplus_0_l.\n        apply sum_n_ext_loc.\n        intros n Hn.\n        unfold transpose.\n        unfold colvec_concat.\n        unfold Mplus.\n        unfold extend_colvec_at_bottom.\n        unfold mk_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        repeat rewrite extend_colvec_on_top_same_dim.\n        simpl. repeat rewrite Rplus_0_l.\n        reflexivity.\n    * destruct d2.\n      - simpl.\n        rewrite Nat.add_0_r at 1.\n        rewrite sum_n_n.\n        rewrite coeff_mat_default; try lia.\n        rewrite Rmult_0_l. rewrite Rplus_0_r.\n        apply sum_n_m_ext_loc.\n        intros k Hk. \n        unfold transpose.\n        unfold colvec_concat.\n        unfold Mplus.\n        unfold extend_colvec_on_top.\n        unfold extend_colvec_at_bottom.\n        unfold mk_colvec.\n        repeat (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.add_sub.\n        destruct Hk as [Hk1 Hk2].\n        apply le_lt_n_Sm in Hk2.\n        rewrite <- Nat.ltb_lt in Hk2.\n        rewrite Hk2. repeat rewrite Rplus_0_r.\n        reflexivity.\n      - rewrite (sum_n_m_Chasles _ _ (d1) (pred (S d1 + S d2))); try lia.\n        apply f_equal2_plus_R.\n        * simpl.\n          apply sum_n_ext_loc.\n          intros n Hn.\n          unfold transpose.\n          unfold colvec_concat.\n          unfold Mplus.\n          unfold extend_colvec_at_bottom.\n          unfold extend_colvec_on_top.\n          unfold mk_colvec.\n          repeat (rewrite coeff_mat_bij; try lia).\n          rewrite Nat.add_sub.\n          apply le_lt_n_Sm in Hn.\n          rewrite <- Nat.ltb_lt in Hn.\n          rewrite Hn.\n          repeat rewrite Rplus_0_r. \n          unfold coeff_colvec.\n          reflexivity.\n        * rewrite (sum_n_m_shift _ 0 (pred (S d2)) (S d1)).\n          rewrite Nat.add_pred_l; try lia.\n          rewrite (Nat.add_comm (S d2) (S d1)).\n          rewrite Nat.add_0_l.\n          apply sum_n_m_ext_loc.\n          intros k Hk.\n          unfold transpose.\n          unfold colvec_concat.\n          unfold Mplus.\n          unfold extend_colvec_at_bottom.\n          unfold extend_colvec_on_top.\n          unfold mk_colvec.\n          repeat (rewrite coeff_mat_bij; try lia).\n          destruct Hk as [H1 H2].\n          rewrite Nat.add_sub.\n          rewrite <- Nat.ltb_ge in H1. rewrite H1.\n          repeat rewrite Rplus_0_l.\n          unfold coeff_colvec.\n          reflexivity.\nQed.\n\nLemma colvec_split:\n    forall dim1 dim2 v,\n        exists v1 v2,\n            v1 = (mk_colvec dim1 (fun i => coeff_colvec 0 v i)) /\\\n            v2 = (mk_colvec dim2 (fun i => coeff_colvec 0 v (i + dim1))) /\\\n            v = colvec_concat v1 v2.\nProof.\n    intros dim1 dim2 v.\n    exists (mk_colvec dim1 (fun i => coeff_colvec 0 v i)).\n    exists (mk_colvec dim2 (fun i => coeff_colvec 0 v (i + dim1))).\n    repeat (split; try reflexivity).\n    unfold colvec_concat.\n    unfold extend_colvec_at_bottom.\n    unfold extend_colvec_on_top.\n    unfold mk_colvec. unfold coeff_colvec.\n    unfold Mplus.\n    induction dim1.\n    - induction dim2.\n      * apply unique_colvec_0.\n    all: (\n        rewrite <- (mk_matrix_bij 0 v);\n        apply mk_matrix_ext;\n        intros i j Hi Hj\n    ).\n      * rewrite coeff_mat_bij; try lia.\n        rewrite Rplus_0_l.\n        rewrite coeff_mat_bij; try lia.\n        rewrite Nat.sub_diag. \n        rewrite coeff_mat_bij; try lia.\n        rewrite coeff_mat_bij; try lia.\n        rewrite Nat.add_0_r. rewrite Nat.sub_0_r.\n        induction j.\n        * reflexivity.\n        * lia.\n    - induction j; try lia.\n      rewrite coeff_mat_bij; try lia.\n      remember (i <? S dim1) as r. \n      destruct r.\n      * symmetry in Heqr. apply Nat.ltb_lt in Heqr.\n        do 3 (rewrite coeff_mat_bij; try lia).\n        rewrite Nat.add_sub.\n        apply Nat.ltb_lt in Heqr. rewrite Heqr.\n        rewrite Rplus_0_r. reflexivity.\n      * rewrite Rplus_0_l.\n        rewrite coeff_mat_bij; try lia.\n        rewrite Nat.add_sub.\n        symmetry in Heqr.\n        rewrite Heqr. apply Nat.ltb_ge in Heqr.\n        rewrite coeff_mat_bij; try lia.\n        rewrite coeff_mat_bij; try lia.\n        rewrite Nat.sub_add; try lia.\n        reflexivity.\nQed.\n\nEnd ReshapeOperations.\n\nModule MatrixNotations.\n\nDeclare Scope colvec_scope.\nDelimit Scope colvec_scope with v.\nBind Scope colvec_scope with colvec.\n\nNotation \"A * B\" := (dot A B) : colvec_scope.\n\nDeclare Scope matrix_scope.\nDelimit Scope matrix_scope with M.\n\nNotation \"A * B\" := (Mmult A B) : matrix_scope.\nNotation \"A + B\" := (Mplus A B) : matrix_scope.\n\nDeclare Scope scalar_scope.\nDelimit Scope scalar_scope with scalar.\n\nNotation \"c * M\" := (scalar_mult c M) : scalar_scope.\n\nEnd MatrixNotations.\n", "meta": {"author": "verinncoq", "repo": "formalizing-pwa", "sha": "0181d9fcc798f209c9a227c9662660e4acadbb7e", "save_path": "github-repos/coq/verinncoq-formalizing-pwa", "path": "github-repos/coq/verinncoq-formalizing-pwa/formalizing-pwa-0181d9fcc798f209c9a227c9662660e4acadbb7e/matrix_extensions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7224429734028114}}
{"text": "Load \"5_bag_more_functions.v\".\n\nTheorem count_member_nonzero : forall (s : bag), Nat.leb 1 (count 1 (cons 1 s)) = true.\nProof.\n  simpl. intros proof_bag. reflexivity.\nQed.\n\nTheorem ble_n_Sn : forall n, Nat.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.\nQed.\n\nTheorem remove_decreases_count: forall (s : bag), Nat.leb (count 0 (remove_one 0 s)) (count 0 s) = true.\nProof.\n  intros.\n  induction s.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. case (Nat.eqb n 0) eqn:Hn.\n    + (* n == 0 *) simpl. rewrite ble_n_Sn. reflexivity.\n    + (* n != 0 *) simpl. rewrite Hn. rewrite IHs. reflexivity.\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/10_bag_proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7224429715000699}}
{"text": "(** * 3. Coq でのプログラミング *)\n(** 3.2 再帰的な型と関数 *)\nModule Section3_2.\n\n(** 自然数 nat について *)\nPrint nat.\n(* Inductive nat : Set :=  \n   O : nat \n | S : nat -> nat \n*)\n\nEval compute in (S (S (S O))).\n\n(** 自然数の加法 *)\nFixpoint add(n m:nat):nat :=\nmatch n with\n| O => m\n| S n' => S (add n' m)\nend.\n\nEval compute in (add (S (S O)) (S (S (S O)))).\n\n(** 自然数の比較 *)\nFixpoint eq_nat(n m:nat):bool :=\nmatch n,m with\n| O,O => true\n| S n', S m' => eq_nat n' m'\n| _,_ => false\nend.\n\nEval compute in (eq_nat 3 3).\nEval compute in (eq_nat 3 2).\n\nFixpoint le_nat(n m:nat):bool :=\nmatch n,m with\n| O,_ => true\n| S n,O => false\n| S n',S m' => le_nat n' m'\nend.\n\nEval compute in (le_nat 2 3).  (* = true *) \nEval compute in (le_nat 3 3).  (* = true *)\nEval compute in (le_nat 4 3).  (* = false *)\n\n(** 再帰関数の停止性 *)\nFixpoint add'(n m:nat){struct n}:nat :=\nmatch n with\n| O => m\n| S n' => S (add n' m)\nend.\n\n(** 課題２：自然数の関数 *)\n(* 1. 掛け算を行う関数 mul を add を参考に定義せよ。 *)\nFixpoint mul(n m:nat) :=\nmatch n with\n| O => O\n| S n' => add m (mult n' m)\nend.\n\nEval compute in (mul 2 3). (* = 6 *)\n\n(* 2. mul を用いて階乗を計算する関数 fact を定義せよ。*)\nFixpoint fact(n:nat) :=\nmatch n with\n| O => 1\n| S n' => mult n (fact n')\nend.\n\nEval compute in (fact 4). (* = 24 *)\n\n(* 3. 引き算を行う関数 sub を定義してみよ。但し n = 0 の場合は sub 0 m = 0と定義する。*)\nFixpoint sub(n m:nat):nat :=\nmatch n,m with\n| O,_ => O\n| _,O => n\n| S n',S m' => sub n' m'\nend.\n\nEval compute in (sub 5 2). (* = 3 *)\nEval compute in (sub 4 4). (* = 0 *)\nEval compute in (sub 2 5). (* = 0 *)\n\n(* 4. 次の関数 div3 は何を計算する関数か考えよ。また Eval を用いて 動作を確認してみよ。*)\nFixpoint div3(n:nat) :=\nmatch n with\n| S (S (S n')) => S (div3 n')\n| _ => O\nend.\n\nEval compute in (div3 2).\nEval compute in (div3 6).\nEval compute in (div3 7).\n\nEnd Section3_2.\n\n(** 3.3 多相型 *)\nModule Section3_3. \n\n(** 多相型とは *)\nDefinition cond{A:Set}(c:bool)(vt vf:A) : A :=\nmatch c with\n| true => vt\n| false => vf\nend.\n\nEval compute in (cond true 2 3).\nEval compute in (cond false false true).\nEval compute in (@cond nat false 2 3).\n\n(** option型 *)\nPrint option.\n(* Inductive option (A : Type) : Type :=  Some : A -> option A | None : option A *)\n\nDefinition option_map {A B:Type}(f:A->B)(o:option A) :=\nmatch o with\n| Some a => Some (f a)\n| None => None\nend.\n\nEval compute in (option_map (fun x => x+1) (Some 1)).\nEval compute in (option_map (fun x => x+1) None).\n\n(** prod型とsum型 *)\n\nPrint prod.\n(* Inductive prod (A B : Type) : Type :=  pair : A -> B -> A * B *)\n\nPrint sum.\n(* Inductive sum (A B : Type) : Type :=  inl : A -> A + B | inr : B -> A + B *)\n\nCheck (2,true,3).\n\nDefinition test_sum(s:sum nat bool) :=\nmatch s with\n| inl n => n\n| inr true => 1\n| inr false => 0\nend.\n\n(** List型 *)\nRequire Import List.\nPrint list.\n(* Inductive list (A : Type) : Type :=\n    nil : list A \n  | cons : A -> list A -> list A\n*)\n\nCheck (1::2::nil).\n\n(** List に対する再帰関数 *)\n(* Listの連結 *)\nFixpoint append{A:Type}(xs ys:list A):=\nmatch xs with\n| nil => ys\n| x::xs' => x::(append xs' ys)\nend.\nEval compute in (append (1::2::nil) (3::4::nil)).\n\n(* Listの最後の要素 *)\nFixpoint olast{A:Type}(xs:list A):option A :=\nmatch xs with\n| nil => None\n| a::nil => Some a\n| _::xs' => olast xs'\nend.\nEval compute in (olast (1::2::3::nil)).\nEval compute in (olast (1::nil)).\nEval compute in (olast (@nil nat)).\n\n(** 課題３：Listへの関数 *)\n(* 1. リストの長さを与える関数 len{A:Type}(xs:list A):nat を定義 せよ。*)\nFixpoint len{A:Type}(xs:list A):nat :=\nmatch xs with\n| nil => O\n| _::xs' => S (len xs')\nend.\n\nEval compute in (len (1::2::3::nil)). (* = 3 *)\n\n(* 2. list bool の入力を受け取り、全要素が true の時 true を返す関数\n all_true(xs:list bool):bool を定義せよ。\n但し nil に対し ては true を返すとせよ。*)\nFixpoint all_true(xs:list bool):bool :=\nmatch xs with\n| nil => true\n| x::xs' => andb x (all_true xs')\nend.\nEval compute in (all_true (@nil bool)).  (* = true *)\nEval compute in (all_true (true::true::nil)).  (* = true *)\nEval compute in (all_true (true::true::false::nil)).  (* = false *)\n\n(* 3. リストの先頭要素 x があれば Some x を、空リストに対しては \nNone を返す、関数 ohead{A:Type}(xs:list A):option A を\n定義せよ。*)\nDefinition ohead{A:Type}(xs:list A):option A :=\nmatch xs with\n| nil => None\n| a::_ => Some a\nend.\n\nEval compute in (ohead (@nil nat)).  (* = None *)\nEval compute in (ohead (1::nil)).  (* = Some 1 *)\nEval compute in (ohead (1::2::nil)).  (* = Some 1 *)\n\n(* 4. 自然数s,nに対してs :: s+1 :: ... :: (s+n-1) :: nilを\n 返す関数 nat_list(s n:nat):list nat を定義せよ。*)\nFixpoint nat_list(s n:nat):list nat :=\nmatch n with\n| O => nil\n| S n' => s::(nat_list (S s) n')\nend.\n\nEval compute in (nat_list 3 5).  (* = 3::4::5::6::7::nil *)\n\n(* 5. リストを反転する関数 reverse{A:Type}(xs:list A):list A を\n 定義せよ。必要なら append を使え。*)\nFixpoint reverse{A:Type}(xs:list A):list A :=\nmatch xs with\n| nil => nil\n| x::xs' => append (reverse xs') (x::nil)\nend.\n\nEval compute in (reverse (1::2::3::nil)). (* =  3::2::1::nil *)\n\nEnd Section3_3.\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/tutorial20120202/tutorial2_ans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.722428507900372}}
{"text": "(* CS 499 - Mechanized Reasoning about Programs *)\n(* Copyright Northern Arizona University        *)\n(* All rights reserved                          *)\n\nRequire Import Arith ZArith List String Project2.\nImport ListNotations.\n(** * Arithmetic Expressions *)\n\nModule Aexp.\n\n  (** * The type of arithmetic expressions *) \n\n  Inductive binary_op : Type :=\n    Add | Mul | Sub.\n\n  Inductive t : Type :=\n  | Int: Z -> t\n  | Var: Id.t -> t\n  | Binop : binary_op -> t -> t -> t.\n\n  Definition get_op (op: binary_op): Z->Z->Z :=\n    match op with\n    | Add => Z.add\n    | Mul => Z.mul\n    | Sub => Z.sub\n    end.\n  \n  (** ** Evaluation of expressions *)\n  Fixpoint A (a:Aexp.t) (s:Id.t -> Z) : Z :=\n    match a with\n    | Aexp.Int z => z\n    | Aexp.Var id => s id\n    | Aexp.Binop op a1 a2 => (Aexp.get_op op) (A a1 s) (A a2 s)  \n    end.\n\nModule Notations.\n  \n    (* Coercions *)\n    Coercion Int : Z >-> t.\n    Coercion Var : Id.t >-> t.\n    \n    (* Notations *)\n    Notation \"a0 + a1\" := (Binop Add a0 a1).\n    Notation \"a0 - a1\" := (Binop Sub a0 a1).\n    Notation \"a0 * a1\" := (Binop Mul a0 a1).\n\nEnd Notations.\n    \n  (* Examples of expressions *)\nModule Ex_t.\n    Import Notations.\n    \n    Definition x : Id.t := Id.Id 0. \n    Definition y : Id.t := Id.Id 1.\n    Definition z : Id.t := Id.Id 2.\n\n    (* Warning: scope Z is not opened! *)\n    Definition a0 : t := Binop Add x 1%Z.\n    Definition a1 : t := Binop Add x 1.\n    Print a0. (* 1%Z is considered as a numerical constant *)\n    Print a1. (* 1 is considered as an identifier! *)\n\n    Definition a2 : t := z - (x * (y + 1)).\n  End Ex_t.\n    \n  (* Examples of evaluation *)\n  Module Ex_A.\n    Import Ex_t.\n    \n    Definition s :=\n      fun z =>\n        if Id.beq z x then 42%Z else\n          if Id.beq z y then 0%Z else 0%Z.\n    \n    Example ex0 : A a0 s = 43%Z.\n    Proof. simpl. trivial. Qed.\n\n    Example ex1 : A a1 s = 42%Z.\n    Proof. simpl. trivial. Qed.\n\n    Example ex2 : A a2 s = 0%Z.\n    Proof. simpl. trivial. Qed.\n\n  End Ex_A.\n\n  (** ** Free variables *) \n\n  (* Instead of using a set of variables, we will use lists, and allow\n     a variable to be present several times in the list. *)\n  Fixpoint FV (a:t) : list Id.t :=\n    match a with\n    | Int z   => []     \n    | Var id  => [id]      \n    | Binop op a1 a2 => List.app (FV a1) (FV a2)\n    end.\n\n  Lemma lemma_1_12:\n    forall (s s':State.t) (a:t),\n      (forall x, In x (FV a) -> s x = s' x) ->\n      A a s = A a s'.\n  Proof.\n    intros s s' a H.\n    induction a as [ z | x | op a1 IH1 a2 IH2].\n    - simpl. trivial.\n    - simpl. apply H.\n      simpl. left. reflexivity.\n    - assert(A a1 s = A a1 s') as H1.\n      {\n        apply IH1.\n        intros x Hx.\n        apply H. simpl.\n        apply in_or_app.\n        left. assumption.\n      }\n      assert(A a2 s = A a2 s') as H2.\n      {\n        apply IH2.\n        intros x Hx.\n        apply H. simpl.\n        apply in_or_app.\n        right. assumption.\n      }\n      simpl.\n      rewrite H1, H2.\n      trivial.\n  Qed.\n\n  (** ** Substitution *)\n  Fixpoint subst (a:t) (y:Id.t) (a0:t) : t :=\n    match a with\n    | Int z  =>  Int z\n    | Var id =>  if Id.beq id y\n                then a0\n                else Var id\n    | Binop op a1 a2 =>\n      Binop op (subst a1 y a0) (subst a2 y a0)\n    end.\n\n  (** Lemma (Exercice) 1.14 (page 18) of Semantics with Applications\n      is written as follows: A[a[y →a0]]s = A[a](s[y →A[a0]s]) for all\n      states s.\n\n      A direct ``translation'' one could think of in would be: forall\n      s a a0 y, A (subst a y a0) s = A a (State.update s y (A a0 s)).\n\n      However (A a0 s) has type option Z, whereas function\n      State.update expect its third argument to be of type Z.\n\n      Therefore the correct statement in Coq is as follows: *)\n  Lemma lemma_1_14:\n    forall (s:State.t)(a a0:t)(y:Id.t),\n      A (subst a y a0) s = A a (State.update s y (A a0 s)). \n  Proof.\n    intros s a a0 y.\n    induction a as [ z | x | op a1 IH1 a2 IH2 ].\n    - trivial.\n    - unfold State.update. simpl.\n      destruct (Id.beq x y).\n      + trivial.\n      + trivial.\n    - simpl.\n      now rewrite IH1, IH2.\n  Qed.\n  \nEnd Aexp.\n\n(** * Boolean expressions *)\n\nModule Bexp.\n\n  (** ** Definition of boolean expressions *)\n  Inductive cmp_op : Type :=\n    Equal | LowerEq.\n\n  Definition get_cmp (cmp: cmp_op) : Z -> Z -> bool :=\n    match cmp with\n    | Equal => Z.eqb\n    | LowerEq => Z.leb\n    end.\n  \n  Inductive t : Type :=\n  | Bool: bool -> t      (* Constant: true or false *)\n  | Neg: t -> t       (* negation of an expression *)\n  | And: t -> t -> t   (* conjunction of two boolean expressions *)\n  | Cmp: cmp_op -> Aexp.t -> Aexp.t -> t\n                     (* comparison of two arithmetic expressions *)\n  .\n\n  (** ** Notations *)\n  Module Notations.\n  \n    Coercion Bool : bool >-> t.\n    Notation \"! b\":=(Neg b)(at level 70).\n    Infix \"&&\" := And.\n    Notation \"a1 == a2\" := (Cmp Equal a1 a2)(at level 70).\n    Notation \"a1 <= a2\" := (Cmp LowerEq a1 a2)(at level 70).\n\n  End Notations.\n\n  (** ** Examples *)\n  Module Ex_t.\n    Import Aexp.Notations Notations Aexp.Ex_t.\n    \n    Definition b1 : t := true.\n    Definition b2 : t := !(a1 == 0%Z).\n    Definition b3 : t := (0%Z <= x) && (x <= y).\n\n  End Ex_t.\n\n  Fixpoint B (b:Bexp.t) (s:Id.t -> Z) : bool :=\n  match b with\n  | Bexp.Bool b => b\n  | Bexp.Neg b  => negb(B b s)\n  | Bexp.And b1 b2 => andb (B b1 s) (B b2 s)\n  | Bexp.Cmp cmp a1 a2 => (Bexp.get_cmp  cmp) (Aexp.A a1 s) (Aexp.A a2 s)\n  end.", "meta": {"author": "chrisswhitneyy", "repo": "CS499_MechanicalReasoning", "sha": "ba1182cabc755bee52a432a24067a43f5bf093ce", "save_path": "github-repos/coq/chrisswhitneyy-CS499_MechanicalReasoning", "path": "github-repos/coq/chrisswhitneyy-CS499_MechanicalReasoning/CS499_MechanicalReasoning-ba1182cabc755bee52a432a24067a43f5bf093ce/Project3/Expressions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.8479677506936879, "lm_q1q2_score": 0.7224284916198634}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (lf1 : natural) : natural :=\n  mult lf2 (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj201_coqofml_l0uNQR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7224281318119584}}
{"text": "Require Import Coq.Classes.Morphisms\n  Coq.micromega.Lia Sigma.Algebra.Hierarchy\n  Sigma.Algebra.Monoid Sigma.Algebra.Group\n  Sigma.Algebra.Ring.\nRequire Coq.setoid_ring.Integral_domain\n  Coq.setoid_ring.Ncring Coq.setoid_ring.Cring.\n\n(* https://github.com/coq/coq/blob/master/theories/setoid_ring/Integral_domain.v *)\nSection IntegralDomain.\n\n  Context \n    {T eq zero one opp add sub mul}\n    {Hi:@integral_domain T eq zero one opp add sub mul}.\n\n  Lemma nonzero_product_iff_nonzero_factors :\n      forall x y : T, \n      ~eq (mul x y) zero <-> ~eq x zero /\\ ~eq y zero.\n  Proof.\n    setoid_rewrite ring_zero_product_iff_zero_factor.\n    intuition.\n  Qed.\n\n  \n  (* This is from the Coq library *)\n  Global Instance Intdom :\n    @Integral_domain.Integral_domain \n      T zero one add mul sub opp eq _ _ _. \n  Proof.\n    split. \n    apply zero_product_zero_factor.\n    apply one_neq_zero.\n  Defined.\n\nEnd IntegralDomain.\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "mukeshtiwari", "repo": "Dlog-zkp", "sha": "c291925d28609f57eab069bd8479d868e7e7f66c", "save_path": "github-repos/coq/mukeshtiwari-Dlog-zkp", "path": "github-repos/coq/mukeshtiwari-Dlog-zkp/Dlog-zkp-c291925d28609f57eab069bd8479d868e7e7f66c/src/Algebra/Integral_domain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210673, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7224281221617657}}
{"text": "Require Import Coq.FSets.FSetInterface.\nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import Graph.\nRequire Import Forest.\nRequire Import Path.\nRequire Import Coq.Init.Nat.\n\nModule Type DFSBase (O: UsualOrderedType)(S: FSetInterface.Sfun O)(G: Graph O S)(F: Forest O S).\n\n  Module P := (Path.PathTheories O S G).\n\n  Definition times_function := G.vertex -> nat.\n  \n  Parameter dfs : option G.vertex -> G.graph -> (F.forest *  times_function * times_function).\n\n  Parameter state : option G.vertex -> G.graph -> Type.\n\n  Definition d_time o g := match (dfs o g) with\n                           | (_, f, _) => f\n                           end.\n\n  Definition f_time o g := match (dfs o g) with\n                           | (_, _, f) => f\n                           end.\n\n  Definition dfs_forest o g := match (dfs o g) with\n                           | (f, _, _) => f\n                           end.\n\n  (*\n\n  Parameter f_time : G.graph -> G.vertex -> nat.\n\n  Parameter d_time : G.graph -> G.vertex -> nat.*)\n\n  Parameter time_of_state: forall o g, state o g -> nat. \n\n  (* States must exist*)\n  Parameter discovery_exists: forall o g v,\n    G.contains_vertex g v = true ->\n    exists (s: state o g), time_of_state o g s = d_time o g v.\n\n  Parameter finish_exists: forall o g v,\n    G.contains_vertex g v = true ->\n    exists (s: state o g), time_of_state o g s = f_time o g v.\n\n  Parameter white: forall (o : option G.vertex) (g : G.graph), state o g -> G.vertex -> bool.\n\n  Parameter white_def: forall o g s v,\n    white o g s v = true <-> ltb (time_of_state o g s) (d_time o g v) = true.\n\n  Parameter gray: forall (o : option G.vertex) (g : G.graph), state o g -> G.vertex -> bool.\n\n  Parameter gray_def: forall o g s v,\n    gray o g s v = true <-> ltb (time_of_state o g s) (f_time o g v) && leb (d_time o g v) (time_of_state o g s) = true.\n\n  Parameter black:forall (o : option G.vertex) (g : G.graph), state o g -> G.vertex -> bool.\n\n  Parameter black_def: forall o g s v,\n    black o g s v = true <-> leb (f_time o g v) (time_of_state o g s) = true.\n\n  Parameter state_time_unique: forall g o (s s': state o g),\n    time_of_state o g s = time_of_state o g s' <-> s = s'.\n\n  (* Some needed results about uniqueness of times *)\n  Parameter d_times_unique: forall o g u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    d_time o g u = d_time o g v <-> u = v.\n\n  Parameter f_times_unique: forall o g u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    f_time o g u = f_time o g v <-> u = v.\n\n  Parameter all_times_unique:\n    forall o g u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    f_time o g u <> d_time o g v.\n\n  (*Major Results*)\n  Parameter parentheses_theorem: forall o g u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    u <> v ->\n    (d_time o g u < d_time o g v /\\ d_time o g v < f_time o g v /\\ f_time o g v < f_time o g u) \\/\n    (d_time o g v < d_time o g u /\\ d_time o g u < f_time o g u /\\ f_time o g u < f_time o g v) \\/\n    (d_time o g u < f_time o g u /\\ f_time o g u < d_time o g v /\\ d_time o g v < f_time o g v) \\/\n    (d_time o g v < f_time o g v /\\ f_time o g v < d_time o g u /\\ d_time o g u < f_time o g u).\n\n  Parameter descendant_iff_interval: forall o g u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    F.desc (dfs_forest o g) u v <->\n     (d_time o g u < d_time o g v /\\ d_time o g v < f_time o g v /\\ f_time o g v < f_time o g u).\n\n  Parameter white_path_theorem: forall o g u v,\n    G.contains_vertex g u = true ->\n    F.desc (dfs_forest o g) u v <-> (forall s, time_of_state o g s = d_time o g u ->\n    exists l, P.path_list_ind g u v (fun x => white o g s x) l).\n\n  (* Basic results about vertices and edges *)\n  Parameter same_vertices: forall o g v,\n    G.contains_vertex g v = true <-> F.contains_vertex (dfs_forest o g) v = true.\n\n  Parameter same_edges: forall o g u v,\n    F.is_child (dfs_forest o g) u v = true -> G.contains_edge g u v = true.\n\n  (*Why we care about starting from a specific vertex*)\n  Parameter start_vertex: forall g v u,\n    G.contains_vertex g v = true ->\n    G.contains_vertex g u = true ->\n    v <> u ->\n    d_time (Some v) g v < d_time (Some v) g u.\n\n  (*Definitions for applications of DFS*)\n\n  Parameter back_edge : G.graph -> G.vertex -> G.vertex -> option G.vertex -> Prop.\n\n  (*Gets around declaring definition in interface: see if better way*)\n  Parameter back_edge_def: forall g u v o,\n    back_edge g u v o <-> (G.contains_edge g u v = true /\\ F.desc (dfs_forest o g) v u).\n\n  Parameter rev_f_time: option G.vertex -> G.graph -> G.vertex -> G.vertex -> Prop.\n\n  Parameter rev_f_time_def: forall o g u v,\n    rev_f_time o g u v <-> f_time o g u > f_time o g v.\n\n  (*(*The point of using an OrderedType*)\n  Parameter root_smallest: forall v g s,\n    time_of_state None g s = d_time None g v ->\n    F.is_root (dfs_forest None g) v = true ->\n    (forall u, G.contains_vertex g u = true -> white None g s u = true -> O.lt v u).*)\n\nEnd DFSBase.\n \n\nModule Type DFSWithCycleDetect(O: UsualOrderedType)(S: FSetInterface.Sfun O)(G: Graph O S)(F: Forest O S).\n  Include (DFSBase O S G F).\n\n  Parameter cycle_detect: option G.vertex -> G.graph -> bool.\n\n  Parameter cycle_detect_back_edge: forall g o,\n    cycle_detect o g = true <-> exists u v, back_edge g u v o.\n\nEnd DFSWithCycleDetect.\n\nModule Type DFSWithTopologicalSort(O: UsualOrderedType)(S: FSetInterface.Sfun O)(G: Graph O S)(F: Forest O S).\n  Include (DFSBase O S G F).\n\n  (*We have an additional function that produces a list of vertices reverse sorted by finish time*)\n  Parameter rev_f_time_list: G.graph -> option G.vertex  -> list (G.vertex).\n\n  Parameter topological_sort_condition: forall g o,\n    (forall v, G.contains_vertex g v = true <-> In v (rev_f_time_list g o)) /\\\n    StronglySorted (rev_f_time o g) (rev_f_time_list g o).\n\nEnd DFSWithTopologicalSort.\n\nModule Type DFSCustomOrder (O: UsualOrderedType)(S: FSetInterface.Sfun O)(G: Graph O S)(F: Forest O S).\n\n  Module P := (Path.PathTheories O S G).\n  Module G' := (Graph.GraphOrder O S G).\n  Section Whole.\n    Context (g: G.graph) (lt' : O.t -> O.t -> bool) (Ho : G'.GraphOrdering g lt').\n\n  Definition times_function := G.vertex -> nat.\n  \n  Parameter dfs:\n       G'.GraphOrdering g lt' -> option G.vertex -> F.forest * times_function * times_function.\n\n\n  Parameter state : G'.GraphOrdering g lt' ->\n   option G.vertex -> Type.\n\n  Definition d_time o := match (dfs Ho o) with\n                           | (_, f, _) => f\n                           end.\n\n  Definition f_time o := match (dfs Ho o) with\n                           | (_, _, f) => f\n                           end.\n\n  Definition dfs_forest o := match (dfs Ho o) with\n                           | (f, _, _) => f\n                           end.\n\n  (*\n\n  Parameter f_time : G.graph -> G.vertex -> nat.\n\n  Parameter d_time : G.graph -> G.vertex -> nat.*)\n\n  Parameter time_of_state: forall o, state Ho o  -> nat.\n\n  (* States must exist*)\n  Parameter discovery_exists: forall o v,\n    G.contains_vertex g v = true ->\n    exists (s: state Ho o), time_of_state o s = d_time o v.\n\n  Parameter finish_exists: forall o v,\n    G.contains_vertex g v = true ->\n    exists (s: state Ho o), time_of_state o s = f_time o v.\n\n  Parameter white: forall (o : option G.vertex), state Ho o -> G.vertex -> bool.\n\n  Parameter white_def: forall o s v,\n    white o s v = true <-> ltb (time_of_state o s) (d_time o v) = true.\n\n  Parameter gray: forall (o : option G.vertex), state Ho o -> G.vertex -> bool.\n\n  Parameter gray_def: forall o s v,\n    gray o s v = true <-> ltb (time_of_state o s) (f_time o v) && leb (d_time o v) (time_of_state o s) = true.\n\n  Parameter black:forall (o : option G.vertex), state Ho o -> G.vertex -> bool.\n\n  Parameter black_def: forall o s v,\n    black o s v = true <-> leb (f_time o v) (time_of_state o s) = true.\n\n  Parameter state_time_unique: forall o (s s': state Ho o),\n    time_of_state o s = time_of_state o s' <-> s = s'.\n\n  (* Some needed results about uniqueness of times *)\n  Parameter d_times_unique: forall o u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    d_time o u = d_time o v <-> u = v.\n\n  Parameter f_times_unique: forall o u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    f_time o u = f_time o v <-> u = v.\n\n  Parameter all_times_unique:\n    forall o u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    f_time o u <> d_time o v.\n\n  (*Major Results*)\n  Parameter parentheses_theorem: forall o u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    u <> v ->\n    (d_time o u < d_time o v /\\ d_time o v < f_time o v /\\ f_time o v < f_time o u) \\/\n    (d_time o v < d_time o u /\\ d_time o u < f_time o u /\\ f_time o u < f_time o v) \\/\n    (d_time o u < f_time o u /\\ f_time o u < d_time o v /\\ d_time o v < f_time o v) \\/\n    (d_time o v < f_time o v /\\ f_time o v < d_time o u /\\ d_time o u < f_time o u).\n\n  Parameter descendant_iff_interval: forall o u v,\n    G.contains_vertex g u = true ->\n    G.contains_vertex g v = true ->\n    F.desc (dfs_forest o) u v <->\n     (d_time o u < d_time o v /\\ d_time o v < f_time o v /\\ f_time o v < f_time o u).\n\n  Parameter white_path_theorem: forall o u v,\n    G.contains_vertex g u = true ->\n    F.desc (dfs_forest o) u v <-> (forall s, time_of_state o s = d_time o u ->\n    exists l, P.path_list_ind g u v (fun x => white o s x) l).\n\n  (* Basic results about vertices and edges *)\n  Parameter same_vertices: forall o v,\n    G.contains_vertex g v = true <-> F.contains_vertex (dfs_forest o) v = true.\n\n  Parameter same_edges: forall o u v,\n    F.is_child (dfs_forest o) u v = true -> G.contains_edge g u v = true.\n\n  (*Why we care about starting from a specific vertex*)\n  Parameter start_vertex: forall v u,\n    G.contains_vertex g v = true ->\n    G.contains_vertex g u = true ->\n    v <> u ->\n    d_time (Some v) v < d_time (Some v) u.\n\n (* (*Definitions for applications of DFS*)\n\n  Parameter back_edge : G.graph -> G.vertex -> G.vertex -> option G.vertex -> Prop.\n\n  (*Gets around declaring definition in interface: see if better way*)\n  Parameter back_edge_def: forall u v o,\n    back_edge g u v o <-> (G.contains_edge g u v = true /\\ F.desc (dfs_forest o) v u).\n\n  Parameter rev_f_time: option G.vertex -> G.graph -> G.vertex -> G.vertex -> Prop.\n\n  Parameter rev_f_time_def: forall o u v,\n    rev_f_time o g u v <-> f_time o u > f_time o v.*)\n\n  (*The point of using a GraphOrdering*)\n  Parameter root_smallest: forall v s,\n    time_of_state None s = d_time None v ->\n    F.is_root (dfs_forest None) v = true ->\n    (forall u (H2: G.contains_vertex g u = true), white None s u = true -> lt' v u = true).\n  End Whole.\nEnd DFSCustomOrder.\n\n\n\n\n\n", "meta": {"author": "joscoh", "repo": "graph-proofs", "sha": "88128ac6e07d184940520ef3fed91008ec01a745", "save_path": "github-repos/coq/joscoh-graph-proofs", "path": "github-repos/coq/joscoh-graph-proofs/graph-proofs-88128ac6e07d184940520ef3fed91008ec01a745/DFSSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7222628390625787}}
{"text": "(** * Rel: Properties of Relations *)\n\n(** This short (and optional) chapter develops some basic definitions\n    and a few theorems about binary relations in Coq.  The key\n    definitions are repeated where they are actually used (in the\n    [Smallstep] chapter of _Programming Language Foundations_),\n    so readers who are already comfortable with these ideas can safely\n    skim or skip this chapter.  However, relations are also a good\n    source of exercises for developing facility with Coq's basic\n    reasoning facilities, so it may be useful to look at this material\n    just after the [IndProp] chapter. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\nFrom Coq Require Import omega.Omega.\n\n(* ################################################################# *)\n(** * Relations *)\n\n(** A binary _relation_ on a set [X] is a family of propositions\n    parameterized by two elements of [X] -- i.e., a proposition about\n    pairs of elements of [X].  *)\n\nDefinition relation (X: Type) := X -> X -> Prop.\n\n(** Confusingly, the Coq standard library hijacks the generic term\n    \"relation\" for this specific instance of the idea. To maintain\n    consistency with the library, we will do the same.  So, henceforth\n    the Coq identifier [relation] will always refer to a binary\n    relation between some set and itself, whereas the English word\n    \"relation\" can refer either to the specific Coq concept or the\n    more general concept of a relation between any number of possibly\n    different sets.  The context of the discussion should always make\n    clear which is meant. *)\n\n(** An example relation on [nat] is [le], the less-than-or-equal-to\n    relation, which we usually write [n1 <= n2]. *)\n\nPrint le.\n(* ====> Inductive le (n : nat) : nat -> Prop :=\n             le_n : n <= n\n           | le_S : forall m : nat, n <= m -> n <= S m *)\nCheck le : nat -> nat -> Prop.\nCheck le : relation nat.\n(** (Why did we write it this way instead of starting with [Inductive\n    le : relation nat...]?  Because we wanted to put the first [nat]\n    to the left of the [:], which makes Coq generate a somewhat nicer\n    induction principle for reasoning about [<=].) *)\n\n(* ################################################################# *)\n(** * Basic Properties *)\n\n(** As anyone knows who has taken an undergraduate discrete math\n    course, there is a lot to be said about relations in general,\n    including ways of classifying relations (as reflexive, transitive,\n    etc.), theorems that can be proved generically about certain sorts\n    of relations, constructions that build one relation from another,\n    etc.  For example... *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Partial Functions *)\n\n(** A relation [R] on a set [X] is a _partial function_ if, for every\n    [x], there is at most one [y] such that [R x y] -- i.e., [R x y1]\n    and [R x y2] together imply [y1 = y2]. *)\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2. \n\n(** For example, the [next_nat] relation defined earlier is a partial\n    function. *)\n\nPrint next_nat.\n(* ====> Inductive next_nat (n : nat) : nat -> Prop :=\n           nn : next_nat n (S n) *)\nCheck next_nat : relation nat.\n\nTheorem next_nat_partial_function :\n   partial_function next_nat.\nProof.\n  unfold partial_function.\n  intros x y1 y2 H1 H2.\n  inversion H1. inversion H2.\n  reflexivity.  Qed.\n\n(** However, the [<=] relation on numbers is not a partial\n    function.  (Assume, for a contradiction, that [<=] is a partial\n    function.  But then, since [0 <= 0] and [0 <= 1], it follows that\n    [0 = 1].  This is nonsense, so our assumption was\n    contradictory.) *)\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply Hc with (x := 0).\n    - apply le_n.\n    - apply le_S. apply le_n. }\n  discriminate Nonsense.   Qed.\n\n(** **** Exercise: 2 stars, standard, optional (total_relation_not_partial)  \n\n    Show that the [total_relation] defined in (an exercise in)\n    [IndProp] is not a partial function. *)\n\nTheorem total_relation_not_pf :\n  ~ (partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply (Hc 0 0 1); apply tr.\n  }\n  congruence. Qed.\n\n(** **** Exercise: 2 stars, standard, optional (empty_relation_partial)  \n\n    Show that the [empty_relation] defined in (an exercise in)\n    [IndProp] is a partial function. *)\n\nTheorem empty_relation_pf :\n  (partial_function empty_relation).\nProof.\n  unfold not. unfold partial_function. intros.\n  inversion H. inversion H1. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Reflexive Relations *)\n\n(** A _reflexive_ relation on a set [X] is one for which every element\n    of [X] is related to itself. *)\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive :\n  reflexive le.\nProof.\n  unfold reflexive. intros n. apply le_n.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Transitive Relations *)\n\n(** A relation [R] is _transitive_ if [R a c] holds whenever [R a b]\n    and [R b c] do. *)\n\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  - (* le_n *) apply Hnm.\n  - (* le_S *) apply le_S. apply IHHmo.  Qed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  apply le_S in Hnm.\n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. Qed.\n\n(** **** Exercise: 2 stars, standard, optional (le_trans_hard_way)  \n\n    We can also prove [lt_trans] more laboriously by induction,\n    without using [le_trans].  Do this. *)\n\nTheorem lt_trans' :\n  transitive lt.\nProof.\n  (* Prove this by induction on evidence that [m] is less than [o]. *)\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [| m' Hm'o].\n  - apply le_S. apply Hnm.\n  - apply le_S. apply IHHm'o.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (lt_trans'')  \n\n    Prove the same thing again by induction on [o]. *)\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  - inversion Hmo.\n  - inversion Hmo.\n    + apply le_S in Hnm.\n      rewrite <- H0.\n      apply Hnm.\n    + apply le_S.\n      apply IHo'.\n      apply H0.\nQed.\n\n(** [] *)\n\n(** The transitivity of [le], in turn, can be used to prove some facts\n    that will be useful later (e.g., for the proof of antisymmetry\n    below)... *)\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof.\n  intros n m H. apply le_trans with (S n).\n  - apply le_S. apply le_n.\n  - apply H.\nQed.\n\n(** **** Exercise: 1 star, standard, optional (le_S_n)  *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros.\n  inversion H.\n  - apply le_n.\n  - apply le_Sn_le in H1. apply H1.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (le_Sn_n_inf)  \n\n    Provide an informal proof of the following theorem:\n\n    Theorem: For every [n], [~ (S n <= n)]\n\n    A formal proof of this is an optional exercise below, but try\n    writing an informal proof without doing the formal proof first.\n\n    Proof: *)\n    (* FILL IN HERE \n\n    [] *)\n\n(** **** Exercise: 1 star, standard, optional (le_Sn_n)  *)\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n  unfold not. intros.\n  induction n.\n  - inversion H.\n  - apply IHn, le_S_n, H.\nQed.\n\n(** [] *)\n\n(** Reflexivity and transitivity are the main concepts we'll need for\n    later chapters, but, for a bit of additional practice working with\n    relations in Coq, let's look at a few other common ones... *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Symmetric and Antisymmetric Relations *)\n\n(** A relation [R] is _symmetric_ if [R a b] implies [R b a]. *)\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\n(** **** Exercise: 2 stars, standard, optional (le_not_symmetric)  *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  unfold symmetric. unfold not. intros.\n  assert (Nonsense: 1 <= 0). {\n    apply H. apply le_S. apply le_n.\n  }\n  apply le_Sn_n in Nonsense. congruence.\nQed.\n  \n(** [] *)\n\n(** A relation [R] is _antisymmetric_ if [R a b] and [R b a] together\n    imply [a = b] -- that is, if the only \"cycles\" in [R] are trivial\n    ones. *)\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\n(** **** Exercise: 2 stars, standard, optional (le_antisymmetric)  *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  unfold antisymmetric. intros.\n  inversion H.\n  - reflexivity.\n  - omega.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (le_step)  *)\nTheorem le_step : forall n m p,\n  n < m ->\n  m <= S p ->\n  n <= p.\nProof.\n  intros. unfold lt in H.\n  apply le_S_n.\n  apply le_trans with m.\n  - apply H.\n  - apply H0.\nQed.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Equivalence Relations *)\n\n(** A relation is an _equivalence_ if it's reflexive, symmetric, and\n    transitive.  *)\n\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(* ----------------------------------------------------------------- *)\n(** *** Partial Orders and Preorders *)\n\n(** A relation is a _partial order_ when it's reflexive,\n    _anti_-symmetric, and transitive.  In the Coq standard library\n    it's called just \"order\" for short. *)\n\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\n(** A preorder is almost like a partial order, but doesn't have to be\n    antisymmetric. *)\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split.\n    - (* refl *) apply le_reflexive.\n    - split.\n      + (* antisym *) apply le_antisymmetric.\n      + (* transitive. *) apply le_trans.  Qed.\n\n(* ################################################################# *)\n(** * Reflexive, Transitive Closure *)\n\n(** The _reflexive, transitive closure_ of a relation [R] is the\n    smallest relation that contains [R] and that is both reflexive and\n    transitive.  Formally, it is defined like this in the Relations\n    module of the Coq standard library: *)\n\nInductive clos_refl_trans {A: Type} (R: relation A) : relation A :=\n    | rt_step x y (H : R x y) : clos_refl_trans R x y\n    | rt_refl x : clos_refl_trans R x x\n    | rt_trans x y z\n          (Hxy : clos_refl_trans R x y)\n          (Hyz : clos_refl_trans R y z) :\n          clos_refl_trans R x z.\n\n(** For example, the reflexive and transitive closure of the\n    [next_nat] relation coincides with the [le] relation. *)\n\nTheorem next_nat_closure_is_le : forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m. split.\n  - (* -> *)\n    intro H. induction H.\n    + (* le_n *) apply rt_refl.\n    + (* le_S *)\n      apply rt_trans with m. apply IHle. apply rt_step.\n      apply nn.\n  - (* <- *)\n    intro H. induction H.\n    + (* rt_step *) inversion H. apply le_S. apply le_n.\n    + (* rt_refl *) apply le_n.\n    + (* rt_trans *)\n      apply le_trans with y.\n      apply IHclos_refl_trans1.\n      apply IHclos_refl_trans2. Qed.\n\n(** The above definition of reflexive, transitive closure is natural:\n    it says, explicitly, that the reflexive and transitive closure of\n    [R] is the least relation that includes [R] and that is closed\n    under rules of reflexivity and transitivity.  But it turns out\n    that this definition is not very convenient for doing proofs,\n    since the \"nondeterminism\" of the [rt_trans] rule can sometimes\n    lead to tricky inductions.  Here is a more useful definition: *)\n\nInductive clos_refl_trans_1n {A : Type}\n                             (R : relation A) (x : A)\n                             : A -> Prop :=\n  | rt1n_refl : clos_refl_trans_1n R x x\n  | rt1n_trans (y z : A)\n      (Hxy : R x y) (Hrest : clos_refl_trans_1n R y z) :\n      clos_refl_trans_1n R x z.\n\n(** Our new definition of reflexive, transitive closure \"bundles\"\n    the [rt_step] and [rt_trans] rules into the single rule step.\n    The left-hand premise of this step is a single use of [R],\n    leading to a much simpler induction principle.\n\n    Before we go on, we should check that the two definitions do\n    indeed define the same relation...\n\n    First, we prove two lemmas showing that [clos_refl_trans_1n] mimics\n    the behavior of the two \"missing\" [clos_refl_trans]\n    constructors.  *)\n\nLemma rsc_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> clos_refl_trans_1n R x y.\nProof.\n  intros X R x y H.\n  apply rt1n_trans with y. apply H. apply rt1n_refl.   Qed.\n\n(** **** Exercise: 2 stars, standard, optional (rsc_trans)  *)\nLemma rsc_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      clos_refl_trans_1n R x y  ->\n      clos_refl_trans_1n R y z ->\n      clos_refl_trans_1n R x z.\nProof.\n  intros. induction H.\n  - apply H0.\n  - apply (rt1n_trans R x y z).\n    + apply Hxy.\n    + apply IHclos_refl_trans_1n, H0.\nQed.\n(** [] *)\n\n(** Then we use these facts to prove that the two definitions of\n    reflexive, transitive closure do indeed define the same\n    relation. *)\n\n(** **** Exercise: 3 stars, standard, optional (rtc_rsc_coincide)  *)\nTheorem rtc_rsc_coincide :\n         forall (X:Type) (R: relation X) (x y : X),\n  clos_refl_trans R x y <-> clos_refl_trans_1n R x y.\nProof.\n  intros. split.\n  + intros. induction H.\n    - apply rsc_R, H.\n    - apply rt1n_refl.\n    - apply (rsc_trans X R x y z).\n      * apply IHclos_refl_trans1.\n      * apply IHclos_refl_trans2.\n  + intros. induction H.\n    - apply rt_refl.\n    - apply (rt_trans R x y z).\n      * apply rt_step, Hxy.\n      * apply IHclos_refl_trans_1n.\nQed.\n(** [] *)\n\n(* Wed Jan 9 12:02:46 EST 2019 *)\n", "meta": {"author": "nerrons", "repo": "lf-works", "sha": "057c08597c7e8502fb3366d4dbcb2e40d2b90945", "save_path": "github-repos/coq/nerrons-lf-works", "path": "github-repos/coq/nerrons-lf-works/lf-works-057c08597c7e8502fb3366d4dbcb2e40d2b90945/lf/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7222485867872201}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import FunInd.\nRequire Import Znumtheory.\n\nOpen Scope Z.\n\nFixpoint product (L: list Z): Z :=\n  match L with\n  | [] => 1\n  | x :: t => x * product t\n  end.\n\nTheorem product_app (L1 L2: list Z): product (L1 ++ L2) = product L1 * product L2.\nProof.\n  induction L1; simpl; lia.\nQed.\n\nTheorem prime_divisor_existence (n: Z) (H: 2 <= n):\n  exists p, prime p /\\ Z.divide p n.\nProof.\n  assert (0 <= n) by lia. revert H. pattern n. apply Z_lt_induction; auto. clear n H0. intros.\n  destruct (prime_dec x).\n  + exists x. split; auto. exists 1. lia.\n  + apply not_prime_divide in n; try lia. destruct n as [n [H1 H2]]. destruct H2.\n    subst. assert (0 <= x0 < x0 * n) by nia. assert (2 <= x0) by nia. pose proof (H _ H2 H3).\n    destruct H4 as [p [H4 H5]]. exists p. split; auto. destruct H5. subst. exists (x * n). lia.\nQed.\n\nTheorem fta_existence (n: Z) (H: 1 <= n): exists (L: list Z), Forall prime L /\\ product L = n.\nProof.\n  assert (0 <= n) by lia. revert H. pattern n. apply Z_lt_induction; auto. intros. clear n H0.\n  assert (x = 1 \\/ 1 < x) by lia. destruct H0.\n  + subst. exists nil. simpl. repeat try split. constructor.\n  + assert (2 <= x) by lia. destruct (prime_divisor_existence x H2) as [p [H3 H4]].\n    destruct H4. assert (1 < p) by (inversion H3; auto).\n    assert (0 <= x0 < x) by nia. assert (1 <= x0) by nia.\n    assert (x0 = 1 \\/ 1 < x0) by lia. destruct H8.\n    - assert (x = p) by lia. exists [x]. split.\n      * constructor; auto. congruence.\n      * simpl. lia.\n    - assert (0 <= p < x) by nia. assert (1 <= p) by nia.\n      pose proof (H _ H6 H7). pose proof (H _ H9 H10). destruct H11 as [L1 H11], H12 as [L2 H12].\n      exists (L1 ++ L2). destruct H11, H12. split.\n      * apply Forall_app. auto.\n      * rewrite product_app. lia.\nQed.\n\nTheorem prime_divisor_of_prime_product (p: Z) (H: prime p) (L: list Z) (H0: Forall prime L):\n  Z.divide p (product L) -> In p L.\nProof.\n  induction L.\n  + simpl in *. intros. destruct H1. assert (1 < p) by (inversion H; auto).\n    symmetry in H1. rewrite Zmult_comm in H1. assert (p >= 0) by lia. pose proof (Zmult_one _ _ H3 H1).\n    lia.\n  + simpl in *. inversion H0; subst; clear H0. intros. apply prime_mult in H0; auto. destruct H0.\n    - apply prime_div_prime in H0; auto.\n    - auto.\nQed.\n\nTheorem prime_product_one_empty_list (L: list Z): Forall prime L -> product L = 1 -> L = [].\nProof.\n  intros. destruct L; auto. simpl in *. inversion H; subst; clear H. exfalso.\n  assert (1 < z) by (inversion H3; auto). assert (z >= 0) by lia. pose proof (Zmult_one _ _ H1 H0).\n  lia.\nQed.\n\nTheorem Forall_elt2 A (L1 L2: list A) (x: A) (P: A -> Prop):\n  Forall P (L1 ++ x :: L2) -> Forall P (L1 ++ L2).\nProof.\n  induction L1.\n  + simpl. intros. inversion H; subst; clear H. auto.\n  + simpl. intros. inversion H; subst; clear H. apply IHL1 in H3. constructor; auto.\nQed.\n\nTheorem prime_product_ge_one (L: list Z): Forall prime L -> product L >= 1.\nProof.\n  induction L; intros.\n  + simpl. lia.\n  + simpl. inversion H; subst; clear H. inversion H2. pose proof (IHL H3). nia.\nQed.\n\nTheorem product_split (L1 L2: list Z) (x: Z): x * product (L1 ++ L2) = product (L1 ++ x :: L2).\nProof.\n  induction L1.\n  + simpl. auto.\n  + simpl. lia.\nQed.\n\nTheorem fta_unique (n: Z) (H: 1 <= n) (L1 L2: list Z):\n  Forall prime L1 -> product L1 = n ->\n  Forall prime L2 -> product L2 = n ->\n  Permutation L1 L2.\nProof.\n  assert (0 <= n) by lia. revert H L1 L2. pattern n. apply Z_lt_induction; auto. intros. clear n H0.\n  assert (x = 1 \\/ 2 <= x) by lia. destruct H0.\n  + subst. assert (L1 = []).\n    { apply prime_product_one_empty_list; auto. }\n    assert (L2 = []).\n    { rewrite H0 in H5. apply prime_product_one_empty_list; auto. }\n    subst. constructor.\n  + pose proof (prime_divisor_existence _ H0). destruct H6. destruct H6.\n    assert (Z.divide x0 (product L1)) by congruence.\n    assert (Z.divide x0 (product L2)) by congruence.\n    apply prime_divisor_of_prime_product in H8; auto.\n    apply prime_divisor_of_prime_product in H9; auto.\n    apply in_split in H8. apply in_split in H9.\n    destruct H8 as [l1 [l2 H8]]. destruct H9 as [l3 [l4 H9]].\n    rewrite H8, H9. apply Permutation_elt. destruct H7. rewrite H7 in *.\n    assert (product (l1 ++ l2) = x1).\n    { pose proof (product_split l1 l2 x0). rewrite <- H8 in H10. rewrite H3 in H10.\n      assert (0 < x0) by (inversion H6; lia). nia. }\n    assert (product (l3 ++ l4) = x1).\n    { pose proof (product_split l3 l4 x0). rewrite <- H9 in H11. rewrite H5 in H11.\n      assert (0 < x0) by (inversion H6; lia). nia. }\n    assert (Forall prime (l1 ++ l2)) by (apply Forall_elt2 with (x:=x0); congruence).\n    assert (Forall prime (l3 ++ l4)) by (apply Forall_elt2 with (x:=x0); congruence).\n    assert (1 <= x1).\n    { rewrite <- H10. pose proof (prime_product_ge_one (l1 ++ l2) H12). lia. }\n    assert (1 < x0) by (inversion H6; lia).\n    assert (0 <= x1 < x1 * x0) by nia.\n    apply (H x1); auto.\nQed.\n\n", "meta": {"author": "LessnessRandomness", "repo": "PE", "sha": "211a7c68eb1b914193c96163c4f394b1b0bada27", "save_path": "github-repos/coq/LessnessRandomness-PE", "path": "github-repos/coq/LessnessRandomness-PE/PE-211a7c68eb1b914193c96163c4f394b1b0bada27/Verif_EulerProject3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284992, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7222485849784909}}
{"text": "Require Export Tactics.\n\nCheck 3 = 3.\n\n\nCheck forall n m : nat, n + m = m + n.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nCheck injective.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B.\n  intros HA.\n  intros HB.\n  split.\n  - apply HA.\n  - apply HB.\nQed.\n\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m.\n  destruct n.\n  - simpl.\n    intros H.\n    apply and_intro.\n    + reflexivity.\n    + apply H.\n  - intros H.\n    simpl in H.\n    inversion H.\nQed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m.\n  intros H.\n  destruct H as [Hn Hm].\n  rewrite -> Hn.\n  rewrite -> Hm.\n  reflexivity.\nQed.\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m.\n  intros [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q.\n  intros H.\n  destruct H as [HP HQ].\n  apply HP.\nQed.\n\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  destruct H as [HP HQ].\n  apply HQ.\nQed.\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R.\n  intros [HP [HQ HR]].\n  split.\n  - split.\n    + apply HP.\n    + apply HQ.\n  - apply HR.\nQed.\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m [Hn | Hm].\n  - rewrite -> Hn.\n    reflexivity.\n  - rewrite -> Hm.\n    rewrite <- mult_n_O.\n    reflexivity.\nQed.\n\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B.\n  intros HA.\n  left.\n  apply HA.\nQed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intros n.\n  destruct n.\n  - left.\n    reflexivity.\n  - right.\n    simpl.\n    reflexivity.\nQed.\n\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m.\n  intros H.\n  destruct n.\n  - left. reflexivity.\n  - simpl in H.\n    apply and_exercise in H.\n    destruct H as [Hm Hnm].\n    right.\n    apply Hm.\nQed.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q.\n  intros H.\n  destruct H.\n  - right.\n    apply H.\n  - left.\n    apply H.\nQed.\n\nModule MyNot.\n\nDefinition not (P:Prop) := P -> False.\n\n(* Notation \"¬ x\" := (not x) : type_scope. *)\n\n\nCheck not.\n(* ===> Prop -> Prop *)\n\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros P cont.\n  destruct cont.\nQed.\n\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros P.\n  unfold not.\n  intros np.\n  intros Q.\n  intros H.\n  apply np in H.\n  inversion H.\nQed.\n\nTheorem zero_not_one : ~(0 = 1).\nProof.\n  intros contra.\n  inversion contra.\nQed.\n\nCheck (0 <> 1).\n\nEval compute in (0 <> 1).\nEval compute in (0 <> 0).\n\nTheorem zero_not_one' : 0 <> 1.\nProof.\n  unfold not.\n  intros H.\n  inversion H.\nQed.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not.\n  intros H.\n  inversion H.\nQed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  intros P Q.\n  intros [HP1 HP2].\n  unfold not in HP2.\n  apply HP2 in HP1.\n  inversion HP1.\nQed.\n\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q.\n  intros H.\n  intros nQ.\n  unfold not in nQ.\n  unfold not.\n  intros HP.\n  apply H in HP.\n  apply nQ in HP.\n  inversion HP.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P.\n  unfold not.\n  intros [H1 H2].\n  apply H2 in H1.\n  inversion H1.\nQed.\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H.\n    reflexivity.\n  - reflexivity.\nQed.\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = false *)\n    unfold not in H.\n    exfalso. (* <=== *)\n    apply H. reflexivity.\n  - (* b = true *) reflexivity.\nQed.\n\nLemma True_is_true : True.\nProof.\n  apply I.\nQed.\n\nModule MyIff.\n\nRequire Import  Coq.Setoids.Setoid.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q.\n  intros leq.\n  unfold iff in leq.\n  unfold iff.\n  rewrite -> and_comm.\n  apply leq.\nQed.\n\nTheorem iff_sym_1 : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q.\n  intros [HAB HBA].\n  split.\n  - apply HBA.\n  - apply HAB.\nQed.\n\nLemma not_true_iff_false : forall b,\n  b <> true <-> b = false.\nProof.\n  intros b.\n  split.\n  - apply not_true_is_false.\n  - intros H1.\n    rewrite -> H1.\n    unfold not.\n    intros H2.\n    inversion H2.\nQed.\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros P.\n  split.\n  - intros H.\n    apply H.\n  - intros H.\n    apply H.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R.\n  intros [HPQ HQP].\n  intros [HQR HRQ].\n  split.\n  - intros P1.\n    apply HPQ in P1.\n    apply HQR in P1.\n    apply P1.\n  - intros P1.\n    apply HRQ in P1.\n    apply HQP in P1.\n    apply P1.\nQed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  unfold iff.\n  split.\n  - intros H1.\n    destruct H1.\n    + split.\n      * apply or_intro.\n        apply H.\n      * apply or_intro.\n        apply H.\n    + split.\n      * apply or_commut.\n        apply or_intro.\n        apply H.\n      * apply or_commut.\n        apply or_intro.\n        apply H.\n  - intros [H1 H2].\n    destruct H1.\n    + apply or_intro.\n      apply H.\n    + destruct H2.\n      * apply or_intro.\n        apply H0.\n      * apply or_commut.\n        apply or_intro.\n        split. apply H. apply H0.\nQed.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.        \n  intros n m.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R.\n  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 mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n intros n m p.\n rewrite mult_0.\n rewrite mult_0.\n rewrite -> or_assoc.\n reflexivity.\nQed.\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m.\n  apply mult_0.\nQed.\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\n  exists 2.\n  reflexivity.\nQed.\n\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) ->\n  (exists o, n = 2 + o).\nProof.\n  intros n.\n  intros [m Hm].\n  exists (2 + m).\n  apply Hm.\nQed.\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.\n  intros H.\n  unfold not.\n  intro E.\n  inversion E as [ x Hx ].\n  apply Hx.\n  apply H.\nQed.\n\nTheorem dist_not_exists_2 : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros X P.\n  intros H.\n  unfold not.\n  intros E.\n  destruct E.\n  apply H0.\n  apply H.\nQed.\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  intros X P Q.\n  split.\n  - intros H.\n    destruct H.\n    + destruct H.\n      * left.\n        exists x.\n        apply H.\n      * right.\n        exists x.\n        apply H.\n  - intros H.\n    destruct H.\n    + destruct H.\n      exists x.\n      left.\n      apply H.\n    + destruct H.\n      exists x.\n      right.\n      apply H.\nQed.\n\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n    | [] => False\n    | x' :: l' => x' = x \\/ In x l'\n  end.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  simpl.\n  right.\n  right.\n  right.\n  left.\n  reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n : nat, In n [2; 4] -> exists n': nat, n = 2 * n'.\nProof.\n  simpl.\n  intros n.\n  intros [H | [H | []]].\n  - exists 1.\n    simpl. rewrite <- H.\n    reflexivity.\n  - exists 2.\n    simpl.\n    rewrite <- H.\n    reflexivity.\nQed.\n\nLemma In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l -> In (f x) (map f l).\nProof.\n  intros A B f l x.\n  induction l as [| x' l' IHl'].\n  - simpl.\n    intros [].\n  - simpl. intros [H | H].\n    left. rewrite -> H. reflexivity.\n    apply IHl' in H.\n    right. apply H.\nQed.\n    \nLemma 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.\n  split.\n  - induction l as [| x' l' IHl'].\n    + simpl.\n      intros H.\n      inversion H.\n    + simpl.\n      intros H.\n      destruct H as [H1 | H2].\n      * exists x'.\n        split. apply H1.\n        rewrite <- H1 in IHl'.\n        left.\n        reflexivity.\n      * apply IHl' in H2.\n        destruct H2.\n        exists x.\n        split. apply H.\n        right.\n        apply H.\n  - intros H.\n    destruct H.\n    destruct H as [H1 H2].\n    apply In_map with (f := f) in H2.\n    rewrite -> H1 in H2.\n    apply H2.\nQed.\n\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a.\n  split.\n  - generalize dependent l'.\n    induction l as [| x l'' IHl].\n    + simpl.\n      intros l' H.\n      right.\n      apply H.\n    + simpl.\n      intros l' H.\n      destruct H as [H1 | H2].\n      * left. left. apply H1.\n      * apply IHl in H2.\n        destruct H2 as [H3 | H4].\n        left. right. apply H3.\n        right. apply H4.\n  - generalize dependent l'.\n    induction l as [| x l'' IHl'].\n    + intros l' [H1 | H2].\n      simpl in H1.\n      inversion H1.\n      simpl. apply H2.\n    + simpl.\n      intros l' [[H1 | H2] | H3].\n      left. apply H1.\n      specialize IHl' with l'.\n      right.\n      apply IHl'.\n      left.\n      apply H2.\n      specialize IHl' with l'.\n      right.\n      apply IHl'.\n      right.\n      apply H3.\nQed.\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 All_In :\n  forall T (P : T -> Prop) (l : list T), \n  (forall x, In x l -> P x) <-> All P l.\nProof.\n  intros T P l.\n  split.\n  - induction l as [| x l' IHl'].\n    + simpl.\n      intros H.\n      apply I.\n    + simpl.\n      intros H.\n      pose proof (H x) as HS.\n      split.\n      * apply HS.\n        left.\n        reflexivity.\n      * apply IHl'.\n        intros.\n        pose proof (H x0) as HS2.\n        apply HS2.\n        right.\n        apply H0.\n  - intros H.\n    induction l as [| x l' IHl'].\n    + simpl.\n      intros x.\n      intros y.\n      inversion y.\n    + intros x0.\n      simpl.\n      simpl in H.\n      intros.\n      destruct H0.\n      * destruct H as [H1 H2].\n        specialize (IHl' H2).\nAbort.        \n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=\nfun n => Podd n \\/ Peven 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\nDefinition oddb (n:nat) : bool := negb (evenb n).\n\nEval compute in oddb 0.\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  intros n.\n  intros H1 H2.\n  induction n as [|n' IHn'].\n  - unfold combine_odd_even.\n    unfold oddb in H2.\n    simpl in H2.\n    assert (H3: false = false).\n    reflexivity.\n    apply H2 in H3.\n    right.\n    apply H3.\n  - unfold combine_odd_even.\nAbort.\n\nRequire Import Coq.Arith.Plus.\n\nLemma plus_comm3_take3 :\n  forall n m p, n + (m + p) = (p + m) + n.\nProof.\n  intros n m p.\n  rewrite plus_comm.\n  rewrite (plus_comm m).\n  reflexivity.\nQed.\n\nRequire Import Coq.Arith.Mult.\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H).\n  destruct H0.\n  rewrite mult_0_r in H0.\n  symmetry.\n  apply H0.\nQed.\n\n\n\n\n\n\n\n", "meta": {"author": "psibi", "repo": "sf", "sha": "36d1f95b4d4ed894ecc2c55c81095c822f3e9c69", "save_path": "github-repos/coq/psibi-sf", "path": "github-repos/coq/psibi-sf/sf-36d1f95b4d4ed894ecc2c55c81095c822f3e9c69/chapter6-logic/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7222485829124109}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  Faux                                                   \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  *****************************************************************************\n  Auxillary properties about natural numbers, relative numbers and reals *)\nRequire Export Min.\nRequire Export Arith.\nRequire Export Reals.\nRequire Export Zpower.\nRequire Export ZArith.\nRequire Export Zcomplements.\nRequire Export sTactic.\nHint Resolve R1_neq_R0: real.\n(*Missing rule for nat *)\n \nTheorem minus_minus : forall a b : nat, a <= b -> b - (b - a) = a.\nintros a b H'.\napply sym_equal.\napply plus_minus; auto.\nrewrite plus_comm; apply le_plus_minus; auto.\nQed.\n \nTheorem lte_comp_mult :\n forall p q r t : nat, p <= q -> r <= t -> p * r <= q * t.\nintros p q r t H'; elim H'; simpl in |- *; auto with arith.\nelim p; simpl in |- *; auto with arith.\nintros n H m H0 H1 H2; apply plus_le_compat; auto with arith.\napply le_trans with (m := r + n * r); auto with arith.\nQed.\nHint Resolve lte_comp_mult: arith.\n \nTheorem le_refl_eq : forall n m : nat, n = m -> n <= m.\nintros n m H'; rewrite H'; auto.\nQed.\n \nTheorem lt_le_pred : forall n m : nat, n < m -> n <= pred m.\nintros n m H'; inversion H'; simpl in |- *; auto.\napply le_trans with (S n); auto.\nQed.\n \nTheorem lt_comp_mult_l : forall p q r : nat, 0 < p -> q < r -> p * q < p * r.\nintros p; elim p; simpl in |- *.\nauto with arith.\nintros n0; case n0.\nsimpl in |- *; auto with arith.\nintros n1 H' q r H'0 H'1.\napply lt_trans with (m := q + S n1 * r); auto with arith.\nQed.\nHint Resolve lt_comp_mult_l: arith.\n \nTheorem lt_comp_mult_r : forall p q r : nat, 0 < p -> q < r -> q * p < r * p.\nintros; repeat rewrite (fun x : nat => mult_comm x p); auto with arith.\nQed.\nHint Resolve lt_comp_mult_r: arith.\n \nTheorem lt_comp_mult : forall p q r s : nat, p < q -> r < s -> p * r < q * s.\nintros p q r s; case q.\nintros H'; inversion H'.\nintros q'; case p.\nintros H' H'0; simpl in |- *; apply le_lt_trans with (m := r);\n auto with arith.\nintros p' H' H'0; apply le_lt_trans with (m := S q' * r); auto with arith.\nQed.\nHint Resolve lt_comp_mult: arith.\n \nTheorem mult_eq_inv : forall n m p : nat, 0 < n -> n * m = n * p -> m = p.\nintros n m p H' H'0.\napply le_antisym; auto.\ncase (le_or_lt m p); intros H'1; auto with arith.\nabsurd (n * p < n * m); auto with arith.\nrewrite H'0; auto with arith.\ncase (le_or_lt p m); intros H'1; auto with arith.\nabsurd (n * m < n * p); auto with arith.\nrewrite H'0; auto with arith.\nQed.\n \nDefinition natEq : forall n m : nat, {n = m} + {n <> m}.\nintros n; elim n.\nintros m; case m; auto with arith.\nintros n0 H' m; case m; auto with arith.\nDefined.\n \nTheorem notEqLt : forall n : nat, 0 < n -> n <> 0.\nintros n H'; Contradict H'; auto.\nrewrite H'; auto with arith.\nQed.\nHint Resolve notEqLt: arith.\n \nTheorem lt_next : forall n m : nat, n < m -> m = S n \\/ S n < m.\nintros n m H'; elim H'; auto with arith.\nQed.\n \nTheorem le_next : forall n m : nat, n <= m -> m = n \\/ S n <= m.\nintros n m H'; case (le_lt_or_eq _ _ H'); auto with arith.\nQed.\n \nTheorem min_or :\n forall n m : nat, min n m = n /\\ n <= m \\/ min n m = m /\\ m < n.\nintros n; elim n; simpl in |- *; auto with arith.\nintros n' Rec m; case m; simpl in |- *; auto with arith.\nintros m'; elim (Rec m'); intros H'0; case H'0; clear H'0; intros H'0 H'1;\n rewrite H'0; auto with arith.\nQed.\n \nTheorem minus_inv_lt_aux : forall n m : nat, n - m = 0 -> n - S m = 0.\nintros n; elim n; simpl in |- *; auto with arith.\nintros n0 H' m; case m; auto with arith.\nintros H'0; discriminate.\nQed.\n \nTheorem minus_inv_lt : forall n m : nat, m <= n -> m - n = 0.\nintros n m H'; elim H'; simpl in |- *; auto with arith.\nintros m0 H'0 H'1; apply minus_inv_lt_aux; auto.\nQed.\n \nTheorem minus_le : forall m n p q : nat, m <= n -> p <= q -> m - q <= n - p.\nintros m n p q H' H'0.\ncase (le_or_lt m q); intros H'1.\nrewrite minus_inv_lt with (1 := H'1); auto with arith.\napply (fun p n m : nat => plus_le_reg_l n m p) with (p := q).\nrewrite le_plus_minus_r; auto with arith.\nrewrite (le_plus_minus p q); auto.\nrewrite (plus_comm p).\nrewrite plus_assoc_reverse.\nrewrite le_plus_minus_r; auto with arith.\napply le_trans with (1 := H'); auto with arith.\napply le_trans with (1 := H'0); auto with arith.\napply le_trans with (2 := H'); auto with arith.\nQed.\n \nTheorem lt_minus_inv : forall n m p : nat, n <= p -> m < n -> p - n < p - m.\nintros n m p H'; generalize m; clear m; elim H'.\nintros m H'0; rewrite <- minus_n_n; elim H'0.\nrewrite <- minus_Sn_m; auto with arith.\nintros m0 H'1 H'2; rewrite <- minus_Sn_m; auto with arith.\nintros m H'0 H'1 m0 H'2; repeat rewrite <- minus_Sn_m; auto with arith.\napply le_trans with n; auto with arith.\nQed.\n \nTheorem lt_mult_anti_compatibility :\n forall n n1 n2 : nat, 0 < n -> n * n1 < n * n2 -> n1 < n2.\nintros n n1 n2 H' H'0; case (le_or_lt n2 n1); auto.\nintros H'1; Contradict H'0; auto.\napply le_not_lt; auto with arith.\nQed.\n \nTheorem le_mult_anti_compatibility :\n forall n n1 n2 : nat, 0 < n -> n * n1 <= n * n2 -> n1 <= n2.\nintros n n1 n2 H' H'0; case (le_or_lt n1 n2); auto.\nintros H'1; Contradict H'0; auto.\napply lt_not_le; auto with arith.\nQed.\n \nTheorem min_n_0 : forall n : nat, min n 0 = 0.\nintros n; case n; simpl in |- *; auto.\nQed.\n(*Simplification rules missing in R *)\nHint Resolve Rabs_pos: real.\n \nTheorem Rlt_Rminus_ZERO : forall r1 r2 : R, (r2 < r1)%R -> (0 < r1 - r2)%R.\nintros r1 r2 H; replace 0%R with (r1 - r1)%R; unfold Rminus in |- *;\n auto with real.\nQed.\nHint Resolve Rlt_Rminus_ZERO: real.\n \nTheorem Rabsolu_left1 : forall a : R, (a <= 0)%R -> Rabs a = (- a)%R.\nintros a H; case H; intros H1.\napply Rabs_left; auto.\nrewrite H1; simpl in |- *; rewrite Rabs_right; auto with real.\nQed.\n \nTheorem RmaxLess1 : forall r1 r2 : R, (r1 <= Rmax r1 r2)%R.\nintros r1 r2; unfold Rmax in |- *; case (Rle_dec r1 r2); auto with real.\nQed.\n \nTheorem RmaxLess2 : forall r1 r2 : R, (r2 <= Rmax r1 r2)%R.\nintros r1 r2; unfold Rmax in |- *; case (Rle_dec r1 r2); auto with real;\n intros; apply Ropp_le_cancel; auto with real.\nQed.\n \nTheorem RmaxSym : forall p q : R, Rmax p q = Rmax q p.\nintros p q; unfold Rmax in |- *.\ncase (Rle_dec p q); case (Rle_dec q p); auto; intros H1 H2; apply Rle_antisym;\n auto.\ncase (Rle_or_lt p q); auto; intros H'0; Contradict H1; apply Rlt_le; auto.\ncase (Rle_or_lt q p); auto; intros H'0; Contradict H2; apply Rlt_le; auto.\nQed.\n \nTheorem RmaxAbs :\n forall p q r : R,\n (p <= q)%R -> (q <= r)%R -> (Rabs q <= Rmax (Rabs p) (Rabs r))%R.\nintros p q r H' H'0; case (Rle_or_lt 0 p); intros H'1.\nrepeat rewrite Rabs_right; auto with real.\napply Rle_trans with r; auto with real.\napply RmaxLess2; auto.\napply Rge_trans with p; auto with real; apply Rge_trans with q;\n auto with real.\napply Rge_trans with p; auto with real.\nrewrite (Rabs_left p); auto.\ncase (Rle_or_lt 0 q); intros H'2.\nrepeat rewrite Rabs_right; auto with real.\napply Rle_trans with r; auto.\napply RmaxLess2; auto.\napply Rge_trans with q; auto with real.\nrewrite (Rabs_left q); auto.\ncase (Rle_or_lt 0 r); intros H'3.\nrepeat rewrite Rabs_right; auto with real.\napply Rle_trans with (- p)%R; auto with real.\napply RmaxLess1; auto.\nrewrite (Rabs_left r); auto.\napply Rle_trans with (- p)%R; auto with real.\napply RmaxLess1; auto.\nQed.\n \nTheorem Rabsolu_Zabs : forall z : Z, Rabs (IZR z) = IZR (Zabs z).\nintros z; case z; simpl in |- *; auto with real.\napply Rabs_right; auto with real.\nintros p0; apply Rabs_right; auto with real zarith.\nintros p0; unfold IZR; rewrite <- INR_IPR; rewrite Rabs_Ropp.\napply Rabs_right; auto with real zarith.\nQed.\n \nTheorem RmaxRmult :\n forall p q r : R, (0 <= r)%R -> Rmax (r * p) (r * q) = (r * Rmax p q)%R.\nintros p q r H; unfold Rmax in |- *.\ncase (Rle_dec p q); case (Rle_dec (r * p) (r * q)); auto; intros H1 H2; auto.\ncase H; intros E1.\ncase H1; auto with real.\nrewrite <- E1; repeat rewrite Rmult_0_l; auto.\ncase H; intros E1.\ncase H2; auto with real.\napply Rmult_le_reg_l with (r := r); auto.\nrewrite <- E1; repeat rewrite Rmult_0_l; auto.\nQed.\n \nTheorem Rle_R0_Ropp : forall p : R, (p <= 0)%R -> (0 <= - p)%R.\nintros p H; rewrite <- Ropp_0; auto with real.\nQed.\n \nTheorem Rlt_R0_Ropp : forall p : R, (p < 0)%R -> (0 < - p)%R.\nintros p H; rewrite <- Ropp_0; auto with real.\nQed.\nHint Resolve Rle_R0_Ropp Rlt_R0_Ropp: real.\n(* Properties of Z *)\n \nTheorem convert_not_O : forall p : positive, nat_of_P p <> 0.\nintros p; elim p.\nintros p0 H'; unfold nat_of_P in |- *; simpl in |- *; rewrite ZL6.\ngeneralize H'; case (nat_of_P p0); auto.\nintros p0 H'; unfold nat_of_P in |- *; simpl in |- *; rewrite ZL6.\ngeneralize H'; case (nat_of_P p0); simpl in |- *; auto.\nunfold nat_of_P in |- *; simpl in |- *; auto with arith.\nQed.\nHint Resolve convert_not_O: zarith arith.\nHint Resolve Zlt_le_weak Zle_not_gt Zgt_irrefl Zlt_irrefl Zle_not_lt\n  Zlt_not_le Zlt_asym inj_lt inj_le: zarith.\n \nTheorem inj_abs :\n forall x : Z, (0 <= x)%Z -> Z_of_nat (Zabs_nat x) = x.\nintros x; elim x; auto.\nunfold Zabs_nat in |- *.\nintros p.\npattern p at 1 3 in |- *;\n rewrite <- (pred_o_P_of_succ_nat_o_nat_of_P_eq_id p).\ngeneralize (convert_not_O p); case (nat_of_P p); simpl in |- *;\n auto with arith.\nintros H'; case H'; auto.\nintros n H' H'0; rewrite Ppred_succ; auto.\nintros p H'; Contradict H'; auto.\nQed.\n \nTheorem inject_nat_convert :\n forall (p : Z) (q : positive),\n p = Zpos q -> Z_of_nat (nat_of_P q) = p.\nintros p q H'; rewrite H'.\nCaseEq (nat_of_P q); simpl in |- *.\nelim q; unfold nat_of_P in |- *; simpl in |- *; intros;\n try discriminate.\nabsurd (0%Z = Zpos p0); auto.\nred in |- *; intros H'0; try discriminate.\napply H; auto.\nchange (nat_of_P p0 = 0) in |- *.\ngeneralize H0; rewrite ZL6; case (nat_of_P p0); simpl in |- *;\n auto; intros; try discriminate.\nintros n; rewrite <- nat_of_P_o_P_of_succ_nat_eq_succ.\nintros H'0; apply f_equal with (f := Zpos).\napply nat_of_P_inj; auto.\nQed.\nHint Resolve inj_le inj_lt: zarith.\n \nTheorem ZleLe : forall x y : nat, (Z_of_nat x <= Z_of_nat y)%Z -> x <= y.\nintros x y H'.\ncase (le_or_lt x y); auto with arith.\nintros H'0; Contradict H'; auto with zarith.\nQed.\n \nTheorem inject_nat_eq : forall x y : nat, Z_of_nat x = Z_of_nat y -> x = y.\nintros x y H'; apply le_antisym.\napply ZleLe; auto.\nidtac; rewrite H'; auto with zarith.\napply ZleLe; auto.\nidtac; rewrite H'; auto with zarith.\nQed.\n \nTheorem Zcompare_EGAL :\n forall p q : Z, (p ?= q)%Z = Datatypes.Eq -> p = q.\nintros p q; case p; case q; simpl in |- *; auto with arith;\n try (intros; discriminate); intros q1 p1.\nintros H1; rewrite (Pcompare_Eq_eq p1 q1); auto.\nunfold Pos.compare.\ngeneralize (Pcompare_Eq_eq p1 q1);\n case (Pcompare p1 q1 Datatypes.Eq); simpl in |- *; \n intros H H1; try discriminate; rewrite H; auto.\nQed.\n \nTheorem Zlt_Zopp : forall x y : Z, (x < y)%Z -> (- y < - x)%Z.\nintros x y; case x; case y; simpl in |- *; auto with zarith; intros p p0;\n unfold Zlt in |- *; simpl in |- *; unfold Pos.compare; rewrite <- ZC4;\n auto.\nQed.\nHint Resolve Zlt_Zopp: zarith.\n \nTheorem Zle_Zopp : forall x y : Z, (x <= y)%Z -> (- y <= - x)%Z.\nintros x y H'; case (Zle_lt_or_eq _ _ H'); auto with zarith.\nQed.\nHint Resolve Zle_Zopp: zarith.\n \nTheorem absolu_INR : forall n : nat, Zabs_nat (Z_of_nat n) = n.\nintros n; case n; simpl in |- *; auto with arith.\nintros n0; rewrite nat_of_P_o_P_of_succ_nat_eq_succ; auto with arith.\nQed.\n \nTheorem absolu_Zopp : forall p : Z, Zabs_nat (- p) = Zabs_nat p.\nintros p; case p; simpl in |- *; auto.\nQed.\n \nTheorem Zabs_absolu : forall z : Z, Zabs z = Z_of_nat (Zabs_nat z).\nintros z; case z; simpl in |- *; auto; intros p; apply sym_equal;\n apply inject_nat_convert; auto.\nQed.\n \nTheorem absolu_comp_mult :\n forall p q : Z, Zabs_nat (p * q) = Zabs_nat p * Zabs_nat q.\nintros p q; case p; case q; simpl in |- *; auto; intros p0 p1;\n apply\n  ((fun (x y : positive) (_ : positive -> positive) =>\n    nat_of_P_mult_morphism x y) p1 p0 (fun x => x)).\nQed.\n \nTheorem Zmin_sym : forall m n : Z, Zmin n m = Zmin m n.\nintros m n; unfold Zmin in |- *.\ncase n; case m; simpl in |- *; auto; unfold Pos.compare.\nintros p p0; rewrite (ZC4 p p0).\ngeneralize (Pcompare_Eq_eq p0 p).\ncase (Pcompare p0 p Datatypes.Eq); simpl in |- *; auto.\nintros H'; rewrite H'; auto.\nintros p p0; rewrite (ZC4 p p0).\ngeneralize (Pcompare_Eq_eq p0 p).\ncase (Pcompare p0 p Datatypes.Eq); simpl in |- *; auto.\nintros H'; rewrite H'; auto.\nQed.\n \nTheorem Zpower_nat_O : forall z : Z, Zpower_nat z 0 = Z_of_nat 1.\nintros z; unfold Zpower_nat in |- *; simpl in |- *; auto.\nQed.\n \nTheorem Zpower_nat_1 : forall z : Z, Zpower_nat z 1 = z.\nintros z; unfold Zpower_nat in |- *; simpl in |- *; rewrite Zmult_1_r; auto.\nQed.\n \nTheorem Zmin_le1 : forall z1 z2 : Z, (z1 <= z2)%Z -> Zmin z1 z2 = z1.\nintros z1 z2; unfold Zle, Zmin in |- *; case (z1 ?= z2)%Z; auto; intros H;\n Contradict H; auto.\nQed.\n \nTheorem Zmin_le2 : forall z1 z2 : Z, (z2 <= z1)%Z -> Zmin z1 z2 = z2.\nintros z1 z2 H; rewrite Zmin_sym; apply Zmin_le1; auto.\nQed.\n \nTheorem Zmin_Zle :\n forall z1 z2 z3 : Z,\n (z1 <= z2)%Z -> (z1 <= z3)%Z -> (z1 <= Zmin z2 z3)%Z.\nintros z1 z2 z3 H' H'0; unfold Zmin in |- *.\ncase (z2 ?= z3)%Z; auto.\nQed.\n \nTheorem Zminus_n_predm :\n forall n m : Z, Zsucc (n - m) = (n - Zpred m)%Z.\nintros n m.\nunfold Zpred in |- *; unfold Zsucc in |- *; ring.\nQed.\n \nTheorem Zopp_Zpred_Zs : forall z : Z, (- Zpred z)%Z = Zsucc (- z).\nintros z; unfold Zpred, Zsucc in |- *; ring.\nQed.\n \nTheorem Zle_mult_gen :\n forall x y : Z, (0 <= x)%Z -> (0 <= y)%Z -> (0 <= x * y)%Z.\nintros x y H' H'0; case (Zle_lt_or_eq _ _ H').\nintros H'1; rewrite Zmult_comm; apply Zmult_gt_0_le_0_compat; auto;\n apply Zlt_gt; auto.\nintros H'1; rewrite <- H'1; simpl in |- *; auto with zarith.\nQed.\nHint Resolve Zle_mult_gen: zarith.\n \nDefinition Zmax : forall x_ x_ : Z, Z :=\n  fun n m : Z =>\n  match (n ?= m)%Z with\n  | Datatypes.Eq => m\n  | Datatypes.Lt => m\n  | Datatypes.Gt => n\n  end.\n \nTheorem ZmaxLe1 : forall z1 z2 : Z, (z1 <= Zmax z1 z2)%Z.\nintros z1 z2; unfold Zmax in |- *; CaseEq (z1 ?= z2)%Z; simpl in |- *;\n auto with zarith.\nunfold Zle in |- *; intros H; rewrite H; red in |- *; intros; discriminate.\nQed.\n \nTheorem ZmaxSym : forall z1 z2 : Z, Zmax z1 z2 = Zmax z2 z1.\nintros z1 z2; unfold Zmax in |- *; CaseEq (z1 ?= z2)%Z; CaseEq (z2 ?= z1)%Z;\n intros H1 H2; try case (Zcompare_EGAL _ _ H1); auto;\n try case (Zcompare_EGAL _ _ H2); auto; Contradict H1.\ncase (Zcompare.Zcompare_Gt_Lt_antisym z2 z1); auto.\nintros H' H'0; rewrite H'0; auto; red in |- *; intros; discriminate.\ncase (Zcompare.Zcompare_Gt_Lt_antisym z1 z2); auto.\nintros H'; rewrite H'; auto; intros; red in |- *; intros; discriminate.\nQed.\n \nTheorem Zmax_le2 : forall z1 z2 : Z, (z1 <= z2)%Z -> Zmax z1 z2 = z2.\nintros z1 z2; unfold Zle, Zmax in |- *; case (z1 ?= z2)%Z; auto.\nintros H'; case H'; auto.\nQed.\n \nTheorem Zmax_le1 : forall z1 z2 : Z, (z2 <= z1)%Z -> Zmax z1 z2 = z1.\nintros z1 z2 H'; rewrite ZmaxSym; apply Zmax_le2; auto.\nQed.\n \nTheorem ZmaxLe2 : forall z1 z2 : Z, (z2 <= Zmax z1 z2)%Z.\nintros z1 z2; rewrite ZmaxSym; apply ZmaxLe1.\nQed.\nHint Resolve ZmaxLe1 ZmaxLe2: zarith.\n \nTheorem Zeq_Zs :\n forall p q : Z, (p <= q)%Z -> (q < Zsucc p)%Z -> p = q.\nintros p q H' H'0; apply Zle_antisym; auto.\napply Zlt_succ_le; auto.\nQed.\n \nTheorem Zmin_Zmax : forall z1 z2 : Z, (Zmin z1 z2 <= Zmax z1 z2)%Z.\nintros z1 z2; case (Zle_or_lt z1 z2); unfold Zle, Zlt, Zmin, Zmax in |- *;\n CaseEq (z1 ?= z2)%Z; auto; intros H1 H2; try rewrite H1; \n try rewrite H2; red in |- *; intros; discriminate.\nQed.\n \nTheorem Zabs_Zmult :\n forall z1 z2 : Z, Zabs (z1 * z2) = (Zabs z1 * Zabs z2)%Z.\nintros z1 z2; case z1; case z2; simpl in |- *; auto with zarith.\nQed.\n \nTheorem Zle_Zmult_comp_r :\n forall x y z : Z, (0 <= z)%Z -> (x <= y)%Z -> (x * z <= y * z)%Z.\nintros x y z H' H'0; case (Zle_lt_or_eq _ _ H'); intros Zlt1.\napply Zmult_gt_0_le_compat_r; auto.\napply Zlt_gt; auto.\nrewrite <- Zlt1; repeat rewrite <- Zmult_0_r_reverse; auto with zarith.\nQed.\n \nTheorem Zle_Zmult_comp_l :\n forall x y z : Z, (0 <= z)%Z -> (x <= y)%Z -> (z * x <= z * y)%Z.\nintros x y z H' H'0; repeat rewrite (Zmult_comm z);\n apply Zle_Zmult_comp_r; auto.\nQed.\n \nTheorem NotZmultZero :\n forall z1 z2 : Z, z1 <> 0%Z -> z2 <> 0%Z -> (z1 * z2)%Z <> 0%Z.\nintros z1 z2; case z1; case z2; simpl in |- *; intros; auto; try discriminate.\nQed.\nHint Resolve NotZmultZero: zarith.\n(* Conversions from R <-> Z  <-> N *)\n \nTheorem IZR_zero : forall p : Z, p = 0%Z -> IZR p = 0%R.\nintros p H'; rewrite H'; auto.\nQed.\nHint Resolve not_O_INR: real.\n \nTheorem IZR_zero_r : forall p : Z, IZR p = 0%R -> p = 0%Z.\nintros p; case p; simpl in |- *; auto.\nintros p1 H'; Contradict H'; auto with real zarith.\nintros p1 H'; absurd (INR (nat_of_P p1) = 0%R); auto with real zarith.\nrewrite <- (Ropp_involutive (INR (nat_of_P p1))).\nunfold IZR in H'; rewrite <- INR_IPR in H'.\nrewrite H'; auto with real.\nQed.\n \nTheorem INR_lt_nm : forall n m : nat, n < m -> (INR n < INR m)%R.\nintros n m H'; elim H'; auto.\nreplace (INR n) with (INR n + 0)%R; auto with real; rewrite S_INR;\n auto with real.\nintros m0 H'0 H'1.\nreplace (INR n) with (INR n + 0)%R; auto with real; rewrite S_INR;\n auto with real.\nQed.\nHint Resolve INR_lt_nm: real.\n \nTheorem Rlt_INR1 : forall n : nat, 1 < n -> (1 < INR n)%R.\nreplace 1%R with (INR 1); auto with real.\nQed.\nHint Resolve Rlt_INR1: real.\n \nTheorem NEq_INR : forall n m : nat, n <> m -> INR n <> INR m.\nintros n m H'; (case (le_or_lt n m); intros H'1).\ncase (le_lt_or_eq _ _ H'1); intros H'2.\napply Rlt_dichotomy_converse; auto with real.\nContradict H'; auto.\napply Compare.not_eq_sym; apply Rlt_dichotomy_converse; auto with real.\nQed.\nHint Resolve NEq_INR: real.\n \nTheorem NEq_INRO : forall n : nat, n <> 0 -> INR n <> 0%R.\nreplace 0%R with (INR 0); auto with real.\nQed.\nHint Resolve NEq_INRO: real.\n \nTheorem NEq_INR1 : forall n : nat, n <> 1 -> INR n <> 1%R.\nreplace 1%R with (INR 1); auto with real.\nQed.\nHint Resolve NEq_INR1: real.\n \nTheorem not_O_lt : forall n : nat, n <> 0 -> 0 < n.\nintros n; elim n; simpl in |- *; auto with arith.\nQed.\nHint Resolve not_O_lt: arith.\n \nTheorem NEq_IZRO : forall n : Z, n <> 0%Z -> IZR n <> 0%R.\nintros n H; Contradict H.\napply IZR_zero_r; auto.\nQed.\nHint Resolve NEq_IZRO: real.\n \nTheorem Rlt_IZR : forall p q : Z, (p < q)%Z -> (IZR p < IZR q)%R.\nintros p q H; case (Rle_or_lt (IZR q) (IZR p)); auto.\nintros H1; Contradict H; apply Zle_not_lt.\napply le_IZR; auto.\nQed.\nHint Resolve Rlt_IZR: real.\n \nTheorem Rle_IZR : forall x y : Z, (x <= y)%Z -> (IZR x <= IZR y)%R.\nintros x y H'.\ncase (Zle_lt_or_eq _ _ H'); clear H'; intros H'.\napply Rlt_le; auto with real.\nrewrite <- H'; auto with real.\nQed.\nHint Resolve Rle_IZR: real.\n \nTheorem Rlt_IZRO : forall p : Z, (0 < p)%Z -> (0 < IZR p)%R.\nintros p H; replace 0%R with (IZR 0); auto with real.\nQed.\nHint Resolve Rlt_IZRO: real.\n \nTheorem Rle_IZRO : forall x y : Z, (0 <= y)%Z -> (0 <= IZR y)%R.\nintros; replace 0%R with (IZR 0); auto with real.\nQed.\nHint Resolve Rle_IZRO: real.\n \nTheorem Rlt_IZR1 : forall p q : Z, (1 < q)%Z -> (1 < IZR q)%R.\nintros; replace 1%R with (IZR 1); auto with real.\nQed.\nHint Resolve Rlt_IZR1: real.\n \nTheorem Rle_IZR1 : forall x y : Z, (1 <= y)%Z -> (1 <= IZR y)%R.\nintros; replace 1%R with (IZR 1); auto with real.\nQed.\nHint Resolve Rle_IZR1: real.\n \nTheorem lt_Rlt : forall n m : nat, (INR n < INR m)%R -> n < m.\nintros n m H'; case (le_or_lt m n); auto; intros H0; Contradict H';\n auto with real.\ncase (le_lt_or_eq _ _ H0); intros H1; auto with real.\nrewrite H1; apply Rlt_irrefl.\nQed.\n \nTheorem INR_inv : forall n m : nat, INR n = INR m -> n = m.\nintros n; elim n; auto; try rewrite S_INR.\nintros m; case m; auto.\nintros m' H1; Contradict H1; auto.\nrewrite S_INR.\napply Rlt_dichotomy_converse; left.\napply Rle_lt_0_plus_1.\napply pos_INR.\nintros n' H' m; case m.\nintros H'0; Contradict H'0; auto.\nrewrite S_INR.\napply Rlt_dichotomy_converse; right.\nred in |- *; apply Rle_lt_0_plus_1.\napply pos_INR.\nintros m' H'0.\nrewrite (H' m'); auto.\nrepeat rewrite S_INR in H'0.\napply Rplus_eq_reg_l with (r := 1%R); repeat rewrite (Rplus_comm 1);\n auto with real.\nQed.\n \nTheorem Rle_INR : forall x y : nat, x <= y -> (INR x <= INR y)%R.\nintros x y H; repeat rewrite INR_IZR_INZ.\napply Rle_IZR; auto with zarith.\nQed.\nHint Resolve Rle_INR: real.\n \nTheorem le_Rle : forall n m : nat, (INR n <= INR m)%R -> n <= m.\nintros n m H'; case H'; auto.\nintros H'0; apply lt_le_weak; apply lt_Rlt; auto.\nintros H'0; rewrite <- (INR_inv _ _ H'0); auto with arith.\nQed.\n \nTheorem Rmult_IZR : forall z t : Z, IZR (z * t) = (IZR z * IZR t)%R.\nintros z t; case z; case t; simpl in |- *; auto with real; unfold IZR; intros t1 z1; repeat rewrite <- INR_IPR.\n- rewrite nat_of_P_mult_morphism; auto with real.\n- rewrite nat_of_P_mult_morphism; auto with real.\n  rewrite Rmult_comm.\n  rewrite Ropp_mult_distr_l_reverse; auto with real.\n  apply Ropp_eq_compat; rewrite mult_comm; auto with real.\n- rewrite nat_of_P_mult_morphism; auto with real.\n  rewrite Ropp_mult_distr_l_reverse; auto with real.\n- rewrite nat_of_P_mult_morphism; auto with real.\n  rewrite Rmult_opp_opp; auto with real.\nQed.\n \nTheorem absolu_Zs :\n forall z : Z, (0 <= z)%Z -> Zabs_nat (Zsucc z) = S (Zabs_nat z).\nintros z; case z.\n3: intros p H'; Contradict H'; auto with zarith.\nreplace (Zsucc 0) with (Z_of_nat 1).\nintros H'; rewrite absolu_INR; simpl in |- *; auto.\nsimpl in |- *; auto.\nintros p H'; rewrite <- Zpos_succ_morphism; simpl in |- *; auto with zarith.\nunfold nat_of_P in |- *; rewrite Pmult_nat_succ_morphism; auto.\nQed.\nHint Resolve Zlt_le_succ: zarith.\n \nTheorem Zlt_next :\n forall n m : Z, (n < m)%Z -> m = Zsucc n \\/ (Zsucc n < m)%Z.\nintros n m H'; case (Zle_lt_or_eq (Zsucc n) m); auto with zarith.\nQed.\n \nTheorem Zle_next :\n forall n m : Z, (n <= m)%Z -> m = n \\/ (Zsucc n <= m)%Z.\nintros n m H'; case (Zle_lt_or_eq _ _ H'); auto with zarith.\nQed.\n \nTheorem Zlt_Zopp_Inv : forall p q : Z, (- p < - q)%Z -> (q < p)%Z.\nintros x y H'; case (Zle_or_lt x y); auto with zarith.\nQed.\n \nTheorem Zle_Zopp_Inv : forall p q : Z, (- p <= - q)%Z -> (q <= p)%Z.\nintros p q H'; case (Zle_lt_or_eq _ _ H'); auto with zarith.\nQed.\n \nTheorem absolu_Zs_neg :\n forall z : Z, (z < 0)%Z -> S (Zabs_nat (Zsucc z)) = Zabs_nat z.\nintros z H'; apply inject_nat_eq.\nrewrite inj_S.\nrepeat rewrite <- (absolu_Zopp (Zsucc z)).\nrepeat rewrite <- (absolu_Zopp z).\nrepeat rewrite inj_abs; replace 0%Z with (- (0))%Z; auto with zarith.\nQed.\n \nTheorem Zlt_absolu :\n forall (x : Z) (n : nat), Zabs_nat x < n -> (x < Z_of_nat n)%Z.\nintros x n; case x; simpl in |- *; auto with zarith.\nreplace 0%Z with (Z_of_nat 0); auto with zarith.\nintros p; rewrite <- (inject_nat_convert (Zpos p) p); auto with zarith.\ncase n; simpl in |- *; intros; red in |- *; simpl in |- *; auto.\nQed.\n \nTheorem inj_pred :\n forall n : nat, n <> 0 -> Z_of_nat (pred n) = Zpred (Z_of_nat n).\nintros n; case n; auto.\nintros H'; Contradict H'; auto.\nintros n0 H'; rewrite inj_S; rewrite <- Zpred_succ; auto.\nQed.\n \nTheorem Zle_abs : forall p : Z, (p <= Z_of_nat (Zabs_nat p))%Z.\nintros p; case p; simpl in |- *; auto with zarith; intros q;\n rewrite inject_nat_convert with (p := Zpos q); \n auto with zarith.\nunfold Zle in |- *; red in |- *; intros H'2; discriminate.\nQed.\nHint Resolve Zle_abs: zarith.\n \nTheorem ZleAbs :\n forall (z : Z) (n : nat),\n (- Z_of_nat n <= z)%Z -> (z <= Z_of_nat n)%Z -> Zabs_nat z <= n.\nintros z n H' H'0; case (le_or_lt (Zabs_nat z) n); auto; intros lt.\ncase (Zle_or_lt 0 z); intros Zle0.\nContradict H'0.\napply Zlt_not_le; auto.\nrewrite <- (inj_abs z); auto with zarith.\nContradict H'.\napply Zlt_not_le; auto.\nreplace z with (- Z_of_nat (Zabs_nat z))%Z.\napply Zlt_Zopp; auto with zarith.\nrewrite <- absolu_Zopp.\nrewrite inj_abs; auto with zarith.\nQed.\n \nTheorem lt_Zlt_inv : forall n m : nat, (Z_of_nat n < Z_of_nat m)%Z -> n < m.\nintros n m H'; case (le_or_lt n m); auto.\nintros H'0.\ncase (le_lt_or_eq _ _ H'0); auto with zarith.\nintros H'1.\nContradict H'.\napply Zle_not_lt; auto with zarith.\nQed.\n \nTheorem NconvertO : forall p : positive, nat_of_P p <> 0.\nintros p; elim p; unfold nat_of_P in |- *; simpl in |- *.\nintros p0 H'; red in |- *; intros H'0; discriminate.\nintros p0; rewrite ZL6; unfold nat_of_P in |- *.\ncase (Pmult_nat p0 1); simpl in |- *; auto.\nred in |- *; intros H'; discriminate.\nQed.\nHint Resolve NconvertO: zarith.\n \nTheorem absolu_lt_nz : forall z : Z, z <> 0%Z -> 0 < Zabs_nat z.\nintros z; case z; simpl in |- *; auto; try (intros H'; case H'; auto; fail);\n intros p; generalize (NconvertO p); auto with arith.\nQed.\n \nTheorem Rlt2 : (0 < INR 2)%R.\nreplace 0%R with (INR 0); auto with real arith.\nQed.\nHint Resolve Rlt2: real.\n \nTheorem RlIt2 : (0 < / INR 2)%R.\napply Rmult_lt_reg_l with (r := INR 2); auto with real.\nQed.\nHint Resolve RlIt2: real.\n \nTheorem Rledouble : forall r : R, (0 <= r)%R -> (r <= INR 2 * r)%R.\nintros r H'.\nreplace (INR 2 * r)%R with (r + r)%R; [ idtac | simpl in |- *; ring ].\npattern r at 1 in |- *; replace r with (r + 0)%R; [ idtac | ring ].\napply Rplus_le_compat_l; auto.\nQed.\n \nTheorem Rltdouble : forall r : R, (0 < r)%R -> (r < INR 2 * r)%R.\nintros r H'.\npattern r at 1 in |- *; replace r with (r + 0)%R; try ring.\nreplace (INR 2 * r)%R with (r + r)%R; simpl in |- *; try ring; auto with real.\nQed.\n \nTheorem Rlt_RinvDouble : forall r : R, (0 < r)%R -> (/ INR 2 * r < r)%R.\nintros r H'.\napply Rmult_lt_reg_l with (r := INR 2); auto with real.\nrewrite <- Rmult_assoc; rewrite Rinv_r.\napply Rmult_lt_compat_r; replace 1%R with (INR 1); auto with real arith.\nreplace 0%R with (INR 0); auto with real arith.\nQed.\nHint Resolve Rledouble: real.\n \nTheorem Rle_Rinv : forall x y : R, (0 < x)%R -> (x <= y)%R -> (/ y <= / x)%R.\nintros x y H H1; case H1; intros H2.\nleft; apply Rinv_lt_contravar; auto.\napply Rmult_lt_0_compat; auto.\napply Rlt_trans with (2 := H2); auto.\nrewrite H2; auto with real.\nQed.\n \nTheorem Int_part_INR : forall n : nat, Int_part (INR n) = Z_of_nat n.\nintros n; unfold Int_part in |- *.\ncut (up (INR n) = (Z_of_nat n + Z_of_nat 1)%Z).\nintros H'; rewrite H'; simpl in |- *; ring.\napply sym_equal; apply tech_up; auto.\nreplace (Z_of_nat n + Z_of_nat 1)%Z with (Z_of_nat (S n)).\nrepeat rewrite <- INR_IZR_INZ.\napply INR_lt_nm; auto.\nrewrite Zplus_comm; rewrite <- inj_plus; simpl in |- *; auto.\nrewrite plus_IZR; simpl in |- *; auto with real.\nrepeat rewrite <- INR_IZR_INZ; auto with real.\nQed.\n \nTheorem Int_part_IZR : forall z : Z, Int_part (IZR z) = z.\nintros z; unfold Int_part in |- *.\ncut (up (IZR z) = (z + 1)%Z).\nintros Z1; rewrite Z1; rewrite Zplus_comm; apply Zminus_plus;\n auto with zarith.\napply sym_equal; apply tech_up; simpl in |- *; auto with real zarith.\nreplace (IZR z) with (IZR z + IZR 0)%R; try rewrite plus_IZR;\n auto with real zarith.\nQed.\n \nTheorem Zlt_Rlt : forall z1 z2 : Z, (IZR z1 < IZR z2)%R -> (z1 < z2)%Z.\nintros z1 z2 H; case (Zle_or_lt z2 z1); auto.\nintros H1; Contradict H; auto with real zarith.\napply Rle_not_lt; auto with real zarith.\nQed.\n \nTheorem Zle_Rle :\n forall z1 z2 : Z, (IZR z1 <= IZR z2)%R -> (z1 <= z2)%Z.\nintros z1 z2 H; case (Zle_or_lt z1 z2); auto.\nintros H1; Contradict H; auto with real zarith.\napply Rlt_not_le; auto with real zarith.\nQed.\n \nTheorem IZR_inv : forall z1 z2 : Z, IZR z1 = IZR z2 :>R -> z1 = z2.\nintros z1 z2 H; apply Zle_antisym; apply Zle_Rle; rewrite H; auto with real.\nQed.\n \nTheorem Zabs_eq_opp : forall x, (x <= 0)%Z -> Zabs x = (- x)%Z.\nintros x; case x; simpl in |- *; auto.\nintros p H; Contradict H; auto with zarith.\nQed.\n \nTheorem Zabs_Zs : forall z : Z, (Zabs (Zsucc z) <= Zsucc (Zabs z))%Z.\nintros z; case z; auto.\nsimpl in |- *; auto with zarith.\nrepeat rewrite Zabs_eq; auto with zarith.\nintros p; rewrite Zabs_eq_opp; auto with zarith.\n2: unfold Zsucc in |- *; replace 0%Z with (-1 + 1)%Z; auto with zarith.\n2: case p; simpl in |- *; intros; red in |- *; simpl in |- *; intros;\n    red in |- *; intros; discriminate.\nreplace (- Zsucc (Zneg p))%Z with (Zpos p - 1)%Z.\nreplace (Zsucc (Zabs (Zneg p))) with (Zpos p + 1)%Z;\n auto with zarith.\nunfold Zsucc in |- *; rewrite Zopp_plus_distr.\nauto with zarith.\nQed.\nHint Resolve Zabs_Zs: zarith.\n \nTheorem Zle_Zpred : forall x y : Z, (x < y)%Z -> (x <= Zpred y)%Z.\nintros x y H; apply Zlt_succ_le.\nrewrite <- Zsucc_pred; auto.\nQed.\nHint Resolve Zle_Zpred: zarith.\n \nTheorem Zabs_Zopp : forall z : Z, Zabs (- z) = Zabs z.\nintros z; case z; simpl in |- *; auto.\nQed.\n \nTheorem Zle_Zabs : forall z : Z, (z <= Zabs z)%Z.\nintros z; case z; simpl in |- *; red in |- *; simpl in |- *; auto;\n try (red in |- *; intros; discriminate; fail).\nintros p; elim p; simpl in |- *; auto;\n try (red in |- *; intros; discriminate; fail).\nQed.\nHint Resolve Zle_Zabs: zarith.\n \nTheorem Zlt_mult_simpl_l :\n forall a b c : Z, (0 < c)%Z -> (c * a < c * b)%Z -> (a < b)%Z.\nintros a b0 c H H0; apply Zgt_lt.\napply Zmult_gt_reg_r with (p := c); try apply Zlt_gt; auto with zarith.\nrepeat rewrite (fun x => Zmult_comm x c); auto with zarith.\nQed.\n(* An equality function on Z that return a bool *)\n \nFixpoint pos_eq_bool (a b : positive) {struct b} : bool :=\n  match a, b with\n  | xH, xH => true\n  | xI a', xI b' => pos_eq_bool a' b'\n  | xO a', xO b' => pos_eq_bool a' b'\n  | _, _ => false\n  end.\n \nTheorem pos_eq_bool_correct :\n forall p q : positive,\n match pos_eq_bool p q with\n | true => p = q\n | false => p <> q\n end.\nintros p q; generalize p; elim q; simpl in |- *; auto; clear p q.\nintros p Rec q; case q; simpl in |- *;\n try (intros; red in |- *; intros; discriminate; fail).\nintros q'; generalize (Rec q'); case (pos_eq_bool q' p); simpl in |- *; auto.\nintros H1; rewrite H1; auto.\nintros H1; Contradict H1; injection H1; auto.\nintros p Rec q; case q; simpl in |- *;\n try (intros; red in |- *; intros; discriminate; fail).\nintros q'; generalize (Rec q'); case (pos_eq_bool q' p); simpl in |- *; auto.\nintros H1; rewrite H1; auto.\nintros H1; Contradict H1; injection H1; auto.\nintros q; case q; simpl in |- *;\n try (intros; red in |- *; intros; discriminate; fail); \n auto.\nQed.\n \nTheorem Z_O_1 : (0 < 1)%Z.\nred in |- *; simpl in |- *; auto; intros; red in |- *; intros; discriminate.\nQed.\nHint Resolve Z_O_1: zarith.\n \nDefinition Z_eq_bool a b :=\n  match a, b with\n  | Z0, Z0 => true\n  | Zpos a', Zpos b' => pos_eq_bool a' b'\n  | Zneg a', Zneg b' => pos_eq_bool a' b'\n  | _, _ => false\n  end.\n \nTheorem Z_eq_bool_correct :\n forall p q : Z,\n match Z_eq_bool p q with\n | true => p = q\n | false => p <> q\n end.\nintros p q; case p; case q; simpl in |- *; auto;\n try (intros; red in |- *; intros; discriminate; fail).\nintros p' q'; generalize (pos_eq_bool_correct q' p');\n case (pos_eq_bool q' p'); simpl in |- *; auto.\nintros H1; rewrite H1; auto.\nintros H1; Contradict H1; injection H1; auto.\nintros p' q'; generalize (pos_eq_bool_correct q' p');\n case (pos_eq_bool q' p'); simpl in |- *; auto.\nintros H1; rewrite H1; auto.\nintros H1; Contradict H1; injection H1; auto.\nQed.\n \nTheorem Zlt_mult_ZERO :\n forall x y : Z, (0 < x)%Z -> (0 < y)%Z -> (0 < x * y)%Z.\nintros x y; case x; case y; unfold Zlt in |- *; simpl in |- *; auto.\nQed.\nHint Resolve Zlt_mult_ZERO: zarith.\n \nTheorem Zlt_Zminus_ZERO :\n forall z1 z2 : Z, (z2 < z1)%Z -> (0 < z1 - z2)%Z.\nintros z1 z2; rewrite (Zminus_diag_reverse z2); auto with zarith.\nQed.\n \nTheorem Zle_Zminus_ZERO :\n forall z1 z2 : Z, (z2 <= z1)%Z -> (0 <= z1 - z2)%Z.\nintros z1 z2; rewrite (Zminus_diag_reverse z2); auto with zarith.\nQed.\nHint Resolve Zle_Zminus_ZERO Zlt_Zminus_ZERO: zarith.\n \nTheorem Zle_Zpred_Zpred :\n forall z1 z2 : Z, (z1 <= z2)%Z -> (Zpred z1 <= Zpred z2)%Z.\nintros z1 z2 H; apply Zsucc_le_reg.\nrepeat rewrite <- Zsucc_pred; auto.\nQed.\nHint Resolve Zle_Zpred_Zpred: zarith.\n \nTheorem Zle_ZERO_Zabs : forall z : Z, (0 <= Zabs z)%Z.\nintros z; case z; simpl in |- *; auto with zarith.\nQed.\nHint Resolve Zle_ZERO_Zabs: zarith.\n \nTheorem Zlt_Zabs_inv1 :\n forall z1 z2 : Z, (Zabs z1 < z2)%Z -> (- z2 < z1)%Z.\nintros z1 z2 H; case (Zle_or_lt 0 z1); intros H1.\napply Zlt_le_trans with (- (0))%Z; auto with zarith.\napply Zlt_Zopp; apply Zle_lt_trans with (2 := H); auto with zarith.\nrewrite <- (Zopp_involutive z1); rewrite <- (Zabs_eq_opp z1);\n auto with zarith.\nQed.\n \nTheorem Zlt_Zabs_inv2 :\n forall z1 z2 : Z, (Zabs z1 < Zabs z2)%Z -> (z1 < Zabs z2)%Z.\nintros z1 z2; case z1; case z2; simpl in |- *; auto with zarith.\nQed.\n \nTheorem Zle_Zabs_inv1 :\n forall z1 z2 : Z, (Zabs z1 <= z2)%Z -> (- z2 <= z1)%Z.\nintros z1 z2 H; case (Zle_or_lt 0 z1); intros H1.\napply Zle_trans with (- (0))%Z; auto with zarith.\napply Zle_Zopp; apply Zle_trans with (2 := H); auto with zarith.\nrewrite <- (Zopp_involutive z1); rewrite <- (Zabs_eq_opp z1);\n auto with zarith.\nQed.\n \nTheorem Zle_Zabs_inv2 :\n forall z1 z2 : Z, (Zabs z1 <= z2)%Z -> (z1 <= z2)%Z.\nintros z1 z2 H; case (Zle_or_lt 0 z1); intros H1.\nrewrite <- (Zabs_eq z1); auto.\napply Zle_trans with (Zabs z1); auto with zarith.\nQed.\n \nTheorem Zlt_Zabs_Zpred :\n forall z1 z2 : Z,\n (Zabs z1 < z2)%Z -> z1 <> Zpred z2 -> (Zabs (Zsucc z1) < z2)%Z.\nintros z1 z2 H H0; case (Zle_or_lt 0 z1); intros H1.\nrewrite Zabs_eq; auto with zarith.\nrewrite Zabs_eq in H; auto with zarith.\napply Zlt_trans with (2 := H).\nrepeat rewrite Zabs_eq_opp; auto with zarith.\nQed.\n \nTheorem Zle_n_Zpred :\n forall z1 z2 : Z, (Zpred z1 <= Zpred z2)%Z -> (z1 <= z2)%Z.\nintros z1 z2 H; rewrite (Zsucc_pred z1); rewrite (Zsucc_pred z2);\n auto with zarith.\nQed.\n \nTheorem Zpred_Zopp_Zs : forall z : Z, Zpred (- z) = (- Zsucc z)%Z.\nintros z; unfold Zpred, Zsucc in |- *; ring.\nQed.\n \nTheorem Zlt_1_O : forall z : Z, (1 <= z)%Z -> (0 < z)%Z.\nintros z H; apply Zsucc_lt_reg; simpl in |- *; auto with zarith.\nQed.\nHint Resolve Zlt_succ Zsucc_lt_compat Zle_lt_succ: zarith.\n \nTheorem Zlt_not_eq : forall p q : Z, (p < q)%Z -> p <> q.\nintros p q H; Contradict H; rewrite H; auto with zarith.\nQed.\n \nTheorem Zlt_not_eq_rev : forall p q : Z, (q < p)%Z -> p <> q.\nintros p q H; Contradict H; rewrite H; auto with zarith.\nQed.\nHint Resolve Zlt_not_eq Zlt_not_eq_rev: zarith.\n \nTheorem Zle_Zpred_Zlt :\n forall z1 z2 : Z, (z1 <= z2)%Z -> (Zpred z1 < z2)%Z.\nintros z1 z2 H; apply Zsucc_lt_reg; rewrite <- Zsucc_pred; auto with zarith.\nQed.\nHint Resolve Zle_Zpred_Zlt: zarith.\n \nTheorem Zle_Zpred_inv :\n forall z1 z2 : Z, (z1 <= Zpred z2)%Z -> (z1 < z2)%Z.\nintros z1 z2 H; rewrite (Zsucc_pred z2); auto with zarith.\nQed.\n \nTheorem Zabs_intro :\n forall (P : Z -> Prop) (z : Z), P (- z)%Z -> P z -> P (Zabs z).\nintros P z; case z; simpl in |- *; auto.\nQed.\n \nTheorem Zpred_Zle_Zabs_intro :\n forall z1 z2 : Z,\n (- Zpred z2 <= z1)%Z -> (z1 <= Zpred z2)%Z -> (Zabs z1 < z2)%Z.\nintros z1 z2 H H0; apply Zle_Zpred_inv.\napply Zabs_intro with (P := fun x => (x <= Zpred z2)%Z); auto with zarith.\nQed.\n \nTheorem Zlt_ZERO_Zle_ONE : forall z : Z, (0 < z)%Z -> (1 <= z)%Z.\nintros z H; replace 1%Z with (Zsucc 0); auto with zarith; simpl in |- *; auto.\nQed.\nHint Resolve Zlt_ZERO_Zle_ONE: zarith.\n \nTheorem ptonat_def1 : forall p q, 1 < Pmult_nat p (S (S q)).\nintros p; elim p; simpl in |- *; auto with arith.\nQed.\nHint Resolve ptonat_def1: arith.\n \nTheorem lt_S_le : forall p q, p < q -> S p <= q.\nintros p q; unfold lt in |- *; simpl in |- *; auto.\nQed.\nHint Resolve lt_S_le: arith.\n \nTheorem Zlt_Zabs_intro :\n forall z1 z2 : Z, (- z2 < z1)%Z -> (z1 < z2)%Z -> (Zabs z1 < z2)%Z.\nintros z1 z2; case z1; case z2; simpl in |- *; auto with zarith.\nintros p p0 H H0; change (- Zneg p0 < - Zneg p)%Z in |- *;\n auto with zarith.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/Faux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7222031687858906}}
{"text": "From GameTheory Require Import ImpartialGame.\nRequire Import Coq.Init.Wf.\nRequire Import Coq.Wellfounded.Lexicographic_Product.\nRequire Import Coq.Relations.Relation_Operators.\nImport Relation_Definitions.\n\n(** The definition of a sum of games is adapted from *)\n(** #<a href=\"https://github.com/arthuraa/poleiro/blob/master/theories/CGT2.v\">http://poleiro.info/posts/2013-09-08-an-introduction-to-combinatorial-game-theory.html</a>#  *)\nDefinition cg_pair_order {cg1 cg2} :=\n  symprod _ _ (valid_move cg1) (valid_move cg2).\nDefinition cg_pair_order_wf {cg1 cg2} : well_founded cg_pair_order :=\n  wf_symprod _ _ _ _ (finite_game cg1) (finite_game cg2).\n\nDefinition sum_game (a b : impartial_game) : impartial_game.\n  refine {|\n      position := position a * position b;\n      start := (start a, start b);\n      moves pos := map (fun s => (s, snd pos)) (moves a (fst pos)) ++\n                   map (fun s => (fst pos, s)) (moves b (snd pos));\n    |}.\n  match goal with\n  | |- well_founded ?R =>\n      assert (EQ : RelationClasses.relation_equivalence R cg_pair_order)\n  end.\n  { intros [pos1' pos2'] [pos1 pos2]. split.\n    - intros H.\n      apply in_app_or in H.\n      repeat rewrite in_map_iff in H.\n      destruct H as [(pos1'' & H1 & H2) | (pos2'' & H1 & H2)];\n        simpl in *; inversion H1; subst; clear H1;\n        constructor; auto.\n    - intros H.\n      inversion H as [? ? H' ?|? ? H']; subst; clear H;\n        rewrite in_app_iff; repeat rewrite in_map_iff;\n        simpl; eauto. }\n  rewrite EQ.\n  apply cg_pair_order_wf.\nDefined.\n\nNotation \"a ~+~ b\" := (sum_game a b) (at level 31, left associativity).\n\n(** This lemma describes what valid moves look like in a sum of games. *)\n(** We make use of both directions of the implication. *)\nLemma moves_in_game_sum : forall a b (s s' : position (a ~+~ b)),\n    valid_move (a ~+~ b) s' s <->\n      (valid_move a (fst s') (fst s) /\\ snd s' = snd s) \\/\n      (valid_move b (snd s') (snd s) /\\ fst s' = fst s).\nProof.\n  intros.\n  split; intros; destruct s, s'.\n  - unfold valid_move in H. simpl in H.\n    apply in_app_or in H.\n    destruct H; rewrite in_map_iff in H; destruct H as [x [H1 H2]];\n    [ left | right ]; inversion H1; subst; auto.\n  - simpl in *.\n    unfold valid_move. simpl.\n    apply in_or_app.\n    destruct H as [[H1 H2] | [H1 H2]]; subst;\n      [ left | right ]; apply in_map_iff; [ exists p1 | exists p2 ]; auto.\nQed.\n\nLtac valid_move_sum_left :=\n  apply moves_in_game_sum; left; simpl; intuition.\nLtac valid_move_sum_right :=\n  apply moves_in_game_sum; right; simpl; intuition.\n\n(** Transitive closure of relation: adapted from https://madiot.fr/pso/tp6.html *)\nInductive trans {A} (R : relation A) : relation A :=\n  | rel_same : forall x y, R x y -> trans R x y\n  | rel_trans : forall x y z, R x y -> R y z -> trans R x z.\n\nLemma Acc_trans (A : Type) (R : relation A) :\n  forall x, Acc R x -> Acc (trans R) x.\nProof.\n  intros.\n  induction H.\n  constructor. intros.\n  destruct H1; auto.\n  apply Acc_inv with y; auto.\n  constructor. auto.\nQed.\n\nTheorem wf_trans : forall (A : Type) (R : relation A),\n  well_founded R -> well_founded (trans R).\nProof.\n  intros A R W x. apply Acc_trans, W.\nQed.\n\n(** In this proof, we need to go back two steps, not just one. *)\n(** Therefore inducting on the Wf relation of a + b does not give us a strong enough induction principle. *)\n(** Instead we define the transitive closure of this relation, and then prove it is well-founded. *)\n(** Then we use this as our induction principle. *)\nLemma sum_losing_is_losing : forall a b x y,\n    losing_state a x ->\n    losing_state b y ->\n    losing_state (a ~+~ b) (x, y).\nProof.\n  intros a b.\n  enough (forall s, losing_state a (fst s) ->\n                    losing_state b (snd s) ->\n                    losing_state (a ~+~ b) s) by auto.\n  refine (well_founded_induction (wf_trans _ _ (finite_game (a ~+~ b))) _ _); intros [x y] IH ? ?; simpl in *.\n  constructor; intros.\n  apply moves_in_game_sum in H1 as [[? ?] | [? ?]]; destruct s'; simpl in *; subst.\n  - inversion H; subst. specialize H2 with p.\n    destruct H2; auto.\n    apply trans_to_losing with (s', y).\n    valid_move_sum_left.\n    apply IH; auto.\n    apply rel_trans with (s, y); valid_move_sum_left.\n  - inversion H0; subst. specialize H2 with p0.\n    destruct H2; auto.\n    apply trans_to_losing with (x, s').\n    valid_move_sum_right.\n    apply IH; auto.\n    apply rel_trans with (x, s); valid_move_sum_right.\nQed.\n\nLemma z_plus_z_is_losing : forall z, losing_state (z ~+~ z) (start z, start z).\nProof.\n  intros z.\n  enough (forall s, losing_state (z ~+~ z) (s, s)) by easy.\n  refine (well_founded_induction (finite_game z) _ _); intros a IH.\n  constructor; intros.\n  destruct s'.\n  apply moves_in_game_sum in H as [[? ?] | [? ?]]; simpl in *; subst.\n  - apply trans_to_losing with (p, p).\n    valid_move_sum_right.\n    apply IH; auto.\n  - apply trans_to_losing with (p0, p0).\n    valid_move_sum_left.\n    apply IH; auto.\nQed.\n\nLemma sum_losing_then_losing : forall x y,\n    losing_state (x ~+~ y) (start x, start y) ->\n    losing_state x (start x) ->\n    losing_state y (start y).\nProof.\n  intros.\n  destruct (winning_or_losing y (start y)); auto.\n  destruct w.\n  pose proof (sum_losing_is_losing _ _ (start x) s').\n  exfalso; apply (not_both_winning_losing (x ~+~ y) (start x, s')).\n  intuition.\n  inversion H; subst.\n  apply (H4 (start x, s')).\n  valid_move_sum_right.\nQed.\n", "meta": {"author": "tmoux", "repo": "game-theory", "sha": "c40a8dffe9ed60d512f09f4f1afbf9d1d0e95be2", "save_path": "github-repos/coq/tmoux-game-theory", "path": "github-repos/coq/tmoux-game-theory/game-theory-c40a8dffe9ed60d512f09f4f1afbf9d1d0e95be2/theories/SumGames.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7221606828781937}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus y (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj196_coqofml_WIoh0c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7221606785886739}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ListUtil.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma base_pow_neg b n : n < 0 -> b^n = 0.\n  Proof.\n    destruct n; intro H; try reflexivity; compute in H; congruence.\n  Qed.\n  Hint Rewrite base_pow_neg using zutil_arith : zsimplify.\n\n  Lemma nonneg_pow_pos a b : 0 < a -> 0 < a^b -> 0 <= b.\n  Proof.\n    destruct (Z_lt_le_dec b 0); intros; auto.\n    erewrite Z.pow_neg_r in * by eassumption.\n    lia.\n  Qed.\n  Hint Resolve nonneg_pow_pos (fun n => nonneg_pow_pos 2 n Z.lt_0_2) : zarith.\n  Lemma nonneg_pow_pos_helper a b dummy : 0 < a -> 0 <= dummy < a^b -> 0 <= b.\n  Proof. eauto with zarith lia. Qed.\n  Hint Resolve nonneg_pow_pos_helper (fun n dummy => nonneg_pow_pos_helper 2 n dummy Z.lt_0_2) : zarith.\n\n  Lemma div_pow2succ : forall n x, (0 <= x) ->\n    n / 2 ^ Z.succ x = Z.div2 (n / 2 ^ x).\n  Proof.\n    intros.\n    rewrite Z.pow_succ_r, Z.mul_comm by auto.\n    rewrite <- Z.div_div by (try apply Z.pow_nonzero; lia).\n    rewrite Zdiv2_div.\n    reflexivity.\n  Qed.\n\n  Definition pow_sub_r'\n    := fun a b c y H0 H1 => @Logic.eq_trans _ _ _ y (@Z.pow_sub_r a b c H0 H1).\n  Definition pow_sub_r'_sym\n    := fun a b c y p H0 H1 => Logic.eq_sym (@Logic.eq_trans _ y _ _ (Logic.eq_sym p) (@Z.pow_sub_r a b c H0 H1)).\n  Hint Resolve pow_sub_r' pow_sub_r'_sym Z.eq_le_incl : zarith.\n  Hint Resolve (fun b => f_equal (fun e => b ^ e)) (fun e => f_equal (fun b => b ^ e)) : zarith.\n\n  Lemma two_p_two_eq_four : 2^(2) = 4.\n  Proof. reflexivity. Qed.\n  Hint Rewrite <- two_p_two_eq_four : push_Zpow.\n\n  Lemma pow_pos_le a b : 0 < a -> 0 < b -> a <= a ^ b.\n  Proof.\n    intros; transitivity (a ^ 1).\n    { rewrite Z.pow_1_r; reflexivity. }\n    { apply Z.pow_le_mono; auto with zarith. }\n  Qed.\n  Hint Resolve pow_pos_le : zarith.\n\n  Lemma pow_pos_lt a b : 1 < a -> 1 < b -> a < a ^ b.\n  Proof.\n    intros; eapply Z.le_lt_trans with (m:=a ^ 1).\n    { rewrite Z.pow_1_r; reflexivity. }\n    { apply Z.pow_lt_mono_r; auto with zarith. }\n  Qed.\n  Hint Resolve pow_pos_lt : zarith.\n\n  Lemma pow_div_base a b : a <> 0 -> 0 < b -> a ^ b / a = a ^ (b - 1).\n  Proof. intros; rewrite Z.pow_sub_r, Z.pow_1_r; lia. Qed.\n  Hint Rewrite pow_div_base using zutil_arith : pull_Zpow.\n\n  Lemma pow_mul_base a b : 0 <= b -> a * a ^ b = a ^ (b + 1).\n  Proof. intros; rewrite <-Z.pow_succ_r, <-Z.add_1_r by lia; reflexivity. Qed.\n  Hint Rewrite pow_mul_base using zutil_arith : pull_Zpow.\nEnd Z.\n", "meta": {"author": "dip-proto", "repo": "fiat-crypto", "sha": "fc3a9280c51f413943c167cc9292e953b8e42c02", "save_path": "github-repos/coq/dip-proto-fiat-crypto", "path": "github-repos/coq/dip-proto-fiat-crypto/fiat-crypto-fc3a9280c51f413943c167cc9292e953b8e42c02/src/Util/ZUtil/Pow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7221606743330445}}
{"text": "Require Import Logic.Class.Eq.\nRequire Import Logic.Fol.Syntax.\n\n\n(* If equality on v is decidable, then so is equality on P v                    *) \nLemma eqDecidable : forall (v:Type) (e:Eq v),\n    forall (s t:P v), {s = t} + {s <> t}.\nProof.\n    intros v e s t. revert s t.\n    induction s as [|x y|s1 IH1 s2 IH2|x s1 IH1];\n    destruct t as [|x' y'|t1 t2|x' t1].\n    - left. reflexivity.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - destruct (eqDec x x') as [Ex|Ex], (eqDec y y') as [Ey|Ey].\n        + subst. left. reflexivity.\n        + right. intros H. inversion H. subst. apply Ey. reflexivity.\n        + right. intros H. inversion H. subst. apply Ex. reflexivity.\n        + right. intros H. inversion H. subst. apply Ex. reflexivity.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - destruct (IH1 t1) as [E1|E1], (IH2 t2) as [E2|E2].\n        + subst. left. reflexivity.\n        + right. intros H. inversion H. subst. apply E2. reflexivity.\n        + right. intros H. inversion H. subst. apply E1. reflexivity.\n        + right. intros H. inversion H. subst. apply E1. reflexivity.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - destruct (eqDec x x') as [E|E], (IH1 t1) as [E1|E1].\n        + subst. left. reflexivity.\n        + right. intros H. inversion H. subst. apply E1. reflexivity.\n        + right. intros H. inversion H. subst. apply E.  reflexivity.\n        + right. intros H. inversion H. subst. apply E.  reflexivity.\nDefined.\n\nArguments eqDecidable {v} {e}.\n\nInstance EqP (v:Type) (e:Eq v) : Eq (P v) := { eqDec := eqDecidable }.\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/Logic/Fol/Eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7221606594891765}}
{"text": "Require Import FSets.\nRequire Import S_as_OT.\n\nInductive accessRight : Set :=\n| weak : accessRight\n| read : accessRight\n| write : accessRight\n| send : accessRight.\n\n(* This defines a stepwise ordering on accessRights *)\n\n  Inductive accessRight_succ : accessRight -> accessRight -> Prop :=\n  | succ_weak_read : accessRight_succ weak read\n  | succ_read_write : accessRight_succ read write\n  | succ_write_send : accessRight_succ write send.\n\n  Hint Constructors accessRight_succ: caps.\n\n  Hint Resolve (f_equal accessRight_succ) : caps.\n\n(* The successor of n is not equal to n *)\n\n  Theorem accessRight_succ_neq : forall n Sn, accessRight_succ n Sn -> n <> Sn. \n  Proof.\n    intros n Sn H.\n    destruct H; discriminate.\n  Qed.\n\n  Hint Immediate accessRight_succ_neq : caps.\n\n(* Weak is not the successor of anything *)\n\n  Theorem accessRight_succ_weak : forall n, ~ accessRight_succ n weak.\n  Proof.\n    intros n H.\n    inversion H.\n  Qed.\n\n  Hint Resolve accessRight_succ_weak : caps.\n\n(* Nothing is the successor of send *)\n\n  Theorem accessRight_succ_send : forall n, ~ accessRight_succ send n.\n  Proof.\n    intros n H.\n    inversion H.\n  Qed.\n\n  Hint Resolve accessRight_succ_send : caps.\n\n(* Successor is not reflexive *)\n\n  Theorem accessRight_succ_n_n : forall n, ~ accessRight_succ n n.\n  Proof.\n    intros n H.\n    destruct n;\n      inversion H.\n  Qed.\n\n  Hint Resolve accessRight_succ_n_n : caps.\n\n(* Successor is not symmetric *)\n\n  Theorem accessRight_succ_neq_succ : forall a b, accessRight_succ a b -> ~ accessRight_succ b a.\n  Proof.\n    intros a b S H.\n    inversion S; subst; inversion H.\n  Qed.\n\n(* Define an order using successor *)\n\n  Inductive accessRight_le : accessRight -> accessRight -> Prop :=\n  | le_base : forall x, accessRight_le x x\n  | le_trans : forall x y z, accessRight_le x y -> accessRight_succ y z -> accessRight_le x z.\n\n  Hint Constructors accessRight_le : caps.\n\n  Hint Resolve (f_equal accessRight_le) : caps.\n\n(* accessRight_le is transitive *)\n\n  Theorem accessRight_le_trans : forall x y z, accessRight_le x y -> accessRight_le y z -> accessRight_le x z.\n  Proof.\n    intros.\n    induction H0; firstorder.  apply (le_trans x y z); assumption.\n  Qed.\n\n  Hint Resolve accessRight_le_trans: caps.\n\n(* accessRight_le is reflexive *)\n\n  Theorem accessRight_le_refl : forall x, accessRight_le x x.\n  Proof.\n    auto with caps.\n\n(*\n    intros. exact (le_base x).\n*)\n  Qed.\n\n(** modeled from Coq.Arith.Le **)\n\n(* Weak is less than everything *)\n\n  Theorem accessRight_le_weak_n : forall n, accessRight_le weak n.\n  Proof.\n    induction n;\n      eauto with caps.\n(*    \n    apply le_trans with weak; constructor.\n    apply le_trans with read; try constructor.\n    apply le_trans with weak; constructor.\n    apply le_trans with write; try constructor.\n    apply le_trans with read; try constructor.\n    apply le_trans with weak; constructor.\n    constructor.\n*)\n  Qed.\n\n  Hint Resolve accessRight_le_weak_n : caps.\n\n(* The successor of anything is not less than weak *)\n\n  Theorem accessRight_le_Sn_weak : forall n Sn, accessRight_succ n Sn -> ~ accessRight_le Sn weak.\n  Proof.\n    intros n Sn S.\n    red.\n    intro H.\n    change ((fun r =>\n      match r with\n        | weak => False\n        | read => True\n        | write => True\n        | send => True\n      end) weak).\n    induction H.\n    destruct S; trivial.\n    destruct H0; trivial.\n  Qed.\n\n  Hint Resolve accessRight_le_Sn_weak : caps.\n\n(* Only weak is less than weak *)\n\n  Theorem accessRight_le_n_weak_eq : forall n, accessRight_le n weak -> weak = n .\n  Proof.\n    intros n H.\n    inversion H; \n      [trivial\n        | absurd (accessRight_succ y weak); eauto with caps] .\n  Qed.\n\n  Hint Immediate accessRight_le_n_weak_eq : caps.\n\n(* The successor of n is not less than n *)\n\n  Theorem accessRight_le_Sn_n : forall n Sn, accessRight_succ n Sn -> ~ accessRight_le Sn n.\n  Proof.\n    intros n p S.\n    induction S; eauto with caps; intro ; inversion H ; subst;\n      inversion H1 ; subst ; inversion H0 ; subst.\n    absurd (accessRight_succ y weak); eauto with caps.\n    inversion H3; subst.  inversion H2; subst.\n    absurd (accessRight_succ y weak); eauto with caps.\n  Qed.\n  Hint Resolve accessRight_le_Sn_n : caps.\n\n  Theorem accessRight_le_n_S : forall n m Sn Sm, \n    accessRight_succ n Sn -> accessRight_succ m Sm -> accessRight_le n m -> accessRight_le Sn Sm.\n  Proof.\n    intros.\n    inversion H; subst; inversion H0; subst; firstorder; eauto with caps.\n    absurd (accessRight_le read weak); eauto with caps.\n    absurd (accessRight_le write weak); eauto with caps.\n    absurd (accessRight_le write read); eauto with caps.\n  Qed.\n\n  Theorem accessRight_le_Sn_le : forall n m Sn Sm, \n    accessRight_succ n Sn -> accessRight_succ m Sm -> accessRight_le Sn Sm -> accessRight_le n m.\n  Proof.\n    intros n m Sn Sm S S1 H.\n    inversion S; inversion S1; subst; eauto with caps.\n    inversion H; subst.  inversion H1; subst.  inversion H0; subst; contradiction accessRight_succ_weak with y.\n    inversion H; subst.  inversion H1; subst.  inversion H0; subst. contradiction accessRight_succ_weak with y.\n    inversion H; subst.  inversion H1; subst.  inversion H0; subst.\n    inversion H3; subst.  inversion H2; subst.  contradiction accessRight_succ_weak with y.\n  Qed.\n\n  Hint Resolve accessRight_le_Sn_le : caps.\n\n  Theorem accessRight_le_n_Sn : forall n p, accessRight_succ n p -> accessRight_le n p.\n  Proof.\n    eauto with caps.\n  Qed.\n\n  Hint Resolve accessRight_le_n_Sn : caps.\n\n  Theorem accessRight_le_pred_n : forall n Sn m,\n    accessRight_succ n Sn -> accessRight_le Sn m -> accessRight_le n m.\n  Proof.\n    intros n Sn m H. apply accessRight_le_trans. eauto with caps.\n  Qed.\n\n  Hint Immediate accessRight_le_pred_n: caps.\n\n  Theorem accessRight_le_not_Sn : forall n Sn m,\n    accessRight_succ n Sn -> ~ accessRight_le n m -> ~ accessRight_le Sn m.\n  Proof.\n    intros n Sn m S H.\n    inversion S; subst; eauto with caps.\n  Qed.\n\n  Hint Resolve accessRight_le_not_Sn : caps.\n\n  Theorem accessRight_le_not_n_Sn : forall n Sn m,\n    accessRight_succ n Sn -> ~ accessRight_le m Sn -> ~ accessRight_le m n.\n  Proof.\n    intros n Sn m S H.\n    eauto with caps.\n  Qed.\n\n  Hint Resolve accessRight_le_not_n_Sn : caps.\n\n(* If n is less than m, m is not the successor of n *)\n\n  Theorem accessRight_le_succ : forall n m,\n    accessRight_le n m -> ~ accessRight_succ m n.\n  Proof.\n    intros n m H.\n    inversion H as [| x pred_m z H0 H1]; subst; eauto with caps.\n    inversion H1; subst.\n    inversion H0; subst;  intro NOT;  inversion NOT; subst.  contradiction accessRight_succ_weak with y.\n    inversion H0; subst.  intro NOT; inversion NOT.  inversion H3; subst.  inversion H2; subst.  intro NOT.  inversion NOT.\n    contradiction accessRight_succ_weak with y.\n    inversion H0; subst.  intro NOT; inversion NOT; subst.  inversion H3; subst.  inversion H2; subst.  intro NOT.  inversion NOT.\n    inversion H5; subst.  inversion H4; subst.  intro NOT; inversion NOT.  contradiction accessRight_succ_weak with y.  \n  Qed.\n\n  Hint Resolve accessRight_le_succ : caps.\n\n  Theorem accessRight_le_antisym : forall x y, accessRight_le x y -> accessRight_le y x -> x = y.\n  Proof.\n    intros x y H H0.\n    inversion H as [| x' pred_y z H1 H2]; subst; eauto with caps.\n    absurd (accessRight_le y x); eauto with caps.\n    apply accessRight_le_Sn_n in H2.\n    eauto with caps.\n  Qed.\n\n  Hint Resolve accessRight_le_antisym : caps.\n\n  Theorem accessRight_succ_neq_trans : forall n Sn SSn,\n    accessRight_succ n Sn -> accessRight_succ Sn SSn -> n <> SSn.\n  Proof.\n    intros n Sn SSn S S1.\n    inversion S; subst; inversion S1; subst; discriminate.\n  Qed.\n\n  Hint Resolve accessRight_succ_neq_trans : caps.\n\n  Inductive accessRight_lt (n m :accessRight) : Prop :=\n  | accessRight_lt_le : forall Sn, accessRight_succ n Sn -> accessRight_le Sn m -> accessRight_lt n m.\n\n  Hint Constructors accessRight_lt : caps.\n\n  Theorem accessRight_lt_trans : forall n m p,\n    accessRight_lt n m -> accessRight_lt m p -> accessRight_lt n p.\n  Proof.\n    intros n m p H H0; inversion H0 as [Sm]; subst; inversion H as [Sn]; subst; constructor 1 with Sn; eauto with caps.\n  Qed.\n\n  Hint Resolve accessRight_lt_trans : caps.\n\n  Theorem accessRight_lt_irrefl : forall n,  ~ accessRight_lt n n.\n  Proof.\n    intros n H.\n    destruct H.\n    contradiction accessRight_le_Sn_n with n Sn.\n  Qed.\n\n  Hint Resolve accessRight_lt_irrefl : caps.\n\n  Theorem accessRight_lt_not_eq: forall n m,\n    accessRight_lt n m -> n <> m.\n    intros n m Hlt.\n    destruct Hlt as [Sn S Hle].\n    destruct S. \n    destruct m ; try discriminate ; inversion Hle; subst; contradiction accessRight_succ_weak with y . \n    destruct m ; try discriminate ; inversion Hle; subst; inversion H0; subst; inversion H; subst; contradiction accessRight_succ_weak with y . \n    destruct m ; try discriminate ; inversion Hle; subst. inversion H0; subst. inversion H; subst.  inversion H2; subst.     inversion H1; subst. contradiction accessRight_succ_weak with y . \n  Qed.\n\n  Hint Resolve accessRight_lt_not_eq : caps.\n\n  Theorem accessRight_lt_eq_lt_dec n m :\n    {accessRight_lt n m} + {n = m} + {accessRight_lt m n}.\n  Proof.\n    intros.\n    destruct n; destruct m; eauto with caps. \n  Qed.\n\n  Theorem accessRight_eq_dec: forall n m:accessRight, {n = m} + {n <> m}.\n  Proof.\n    intros.\n    induction n; destruct m; auto;\n    (* all that remains are the <> cases *)\n      right; simplify_eq.\n  Qed.    \n\nModule AccessRight_as_UOT <: UsualOrderedType.\n  \n  Definition t := accessRight.\n\n  Definition eq := @eq accessRight.\n  Definition eq_refl := @refl_equal t.\n  Definition eq_sym := @sym_eq t.\n  Definition eq_trans := @trans_eq t.\n  Definition eq_dec := accessRight_eq_dec.\n\n  Definition lt := accessRight_lt.\n\n  Definition lt_trans := accessRight_lt_trans.\n\n  Definition lt_not_eq := accessRight_lt_not_eq.\n\n  Theorem compare : forall x y : t, Compare lt eq x y. \n  Proof.\n    unfold t, lt.\n    intros.\n    case (accessRight_lt_eq_lt_dec x y).\n    intro s.  destruct s as [a|a].\n    exact (LT eq a).\n    exact (EQ accessRight_lt a).\n    intro a.\n    exact (GT eq a).\n  Qed.\n\nHint Unfold eq : caps.\nHint Unfold lt : caps.\n\nEnd AccessRight_as_UOT.\n\nModule AccessRightOT <: OrderedType := AccessRight_as_UOT.\n\nModule AccessRightFSetList := FSetList.Make AccessRightOT.\n\nModule Type AccessRightFSetType := FSetInterface.S with Module E := AccessRightOT.\n\nModule AccessRightFSet : AccessRightFSetType := AccessRightFSetList.\n\nDefinition accessRightSet := AccessRightFSet.t.\n\nHint Immediate AccessRightFSet.eq_sym : caps.\nHint Resolve AccessRightFSet.eq_refl AccessRightFSet.eq_trans AccessRightFSet.lt_not_eq AccessRightFSet.lt_trans : caps.\n\nRequire FSetAddEq.\nRequire FSetListUOT.\nRequire FoldEqual.\n\nModule ARSetProps := FSetProperties.Properties AccessRightFSet.\nModule ARSetFacts := FSetFacts.Facts AccessRightFSet.\nModule ARSetfDep := FSetBridge.DepOfNodep AccessRightFSet.\nModule ARSetEqProps := FSetEqProperties.EqProperties AccessRightFSet.\nModule ARSetAddEq := FSetAddEq.Make AccessRightFSet.\nModule ARSetFold := FoldEqual.Make AccessRightFSet.\n\n\nDefinition all_rights := AccessRightFSet.add read\n        (AccessRightFSet.add write\n          (AccessRightFSet.add weak\n            (AccessRightFSet.singleton send))).\n", "meta": {"author": "doerrie", "repo": "confinement-proof", "sha": "db7bfb3522990d0820de64f13baa97b67e694c44", "save_path": "github-repos/coq/doerrie-confinement-proof", "path": "github-repos/coq/doerrie-confinement-proof/confinement-proof-db7bfb3522990d0820de64f13baa97b67e694c44/AccessRights-old.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7221596577750842}}
{"text": "Require Export Basics.\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\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\nTheorem minus_help : forall (x y : nat),\n  ble_nat x y = true -> x + (minus y x) = y.\nProof.\n  intros x y. intros H.\n  induction x as [ | x'].\n  simpl. admit.\n  simpl. admit.\n\nTheorem ble_nat1 : forall (x y : nat),\n  ble_nat (S x) y = true -> ble_nat x y = true.\nProof.\n  intros x y. intros H.\n  induction y as [ | y'].\n  inversion H.\n\nTheorem ble_nat2 : forall (x : nat),\n  ble_nat x (S x).\n\n\nTheorem ble_nat_alt : forall (x y : nat),\n  ble_nat x y = true -> exists (z : nat), x + z = y.\nProof.\n  intros x y.\n  intros H.\n  assert (Lemma1 : x + (minus y x) = y).\n  \n", "meta": {"author": "mfount", "repo": "chicken", "sha": "83bb022522499272b4c246432188cfd5cce89c64", "save_path": "github-repos/coq/mfount-chicken", "path": "github-repos/coq/mfount-chicken/chicken-83bb022522499272b4c246432188cfd5cce89c64/coq/SF/alex-temp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.722159654526181}}
{"text": "Require Import HoTT.\nLoad pType_basics.\n\nSection Wedge.\n  (*Define the wedge as a pushout.*)\n  Definition wedge (A B : pType) := pushout (unit_name (point A)) (unit_name (point B) ).\n\n  (*Give the basepoint of the wedge. It could just as well have been pushr tt.*)\n  Global Instance ispointed_wedge {A B:pType} : IsPointed (wedge A B) := pushl tt.\n  Definition pWedge (A B : pType) := Build_pType (wedge A B) _.\n\n  (*The projection from sum to wedge:*)\n  Definition sum_to_wedge {A B:pType} : (A+B)->(wedge A B) := push.\n  \n  (*The path between the two basepoints in the wedge:*)\n  Definition pw {A B:pType} : \n    sum_to_wedge (inl (point A)) = sum_to_wedge (inr (point B)) \n    := pp tt.\n  \n  (*Wedge induction: You need compatible products over A and B.*)\n  Definition wedge_ind {A B:pType} \n\t     (P : (wedge A B)->Type) \n\t     (f: forall a : A, P (sum_to_wedge (inl a)))\n         (g : forall b : B, P (sum_to_wedge (inr b)))\n\t     (pw' : transport P pw (f (point A)) = g (point B) )\n  : forall w : wedge A B, P w.\n  Proof.\n    rapply (@pushout_ind Unit A B).\n    - intros [a | b].\n      exact (f a).\n      exact (g b).\n    - intros [].\n      exact pw'.\n  Defined.\n  \n  (*Wedge recursion: You need compatible maps from A and B.*)\n  Definition wedge_rec {A B: pType}\n             (P : Type) (f : A -> P) (g : B -> P) (pw' : f (point A) = g (point B) ) : (wedge A B) -> P.\n    Proof.\n      rapply (@pushout_rec Unit A B).\n      - intros [a | b].\n        exact (f a). exact (g b).\n      - intros []. exact pw'.\n    Defined.\n    (*Could also do this:\n  := wedge_ind (fun _ : wedge A B => P) f g (transport_const pw (f (point A)) @ pw').\n\n     But then it would be less convenient to use pushout_rec_beta_pp. . .*)\n\n  (*Pointed recursion*)\n  Definition wedge_pRec {A B : pType}\n             (P : pType) (f : A ->* P) (g : B ->* P)  : (pWedge A B) ->* P.\n    Proof.\n      refine (Build_pMap _ _ _ _).\n      - rapply (wedge_rec P f g).\n        refine (concat _ _).\n        + exact (point P).\n        + exact (point_eq f).\n        + exact (point_eq g)^.\n     - exact (point_eq f).\n    Defined.\n    \n  (*Wedge is a functor.*)\n  Definition wedge_functor {A B C D:pType} (f:A->*C) (g:B->*D) : \n    (wedge A B) -> (wedge C D) :=\n    wedge_rec\n      (wedge C D)\n      (sum_to_wedge o functor_sum f g o inl)\n      (sum_to_wedge o functor_sum f g o inr)\n      (ap (sum_to_wedge o inl) (point_eq f) @ pw @ (ap (sum_to_wedge o inr) (point_eq g))^).\n  (*Todo:\tShow that the result is a pMap*)\n\n  (*wedge_rec takes the path pw to what it should.*)\n  Lemma wedge_rec_beta_pw {A B : pType}\n        (P : Type) (f : A -> P) (g : B -> P) (pw' : f (point A) = g (point B) ) :\n    ap (wedge_rec P f g pw') pw = pw'.\n  Proof.\n    refine (pushout_rec_beta_pp P _ _ _).\n  Defined.\n    \n  (*For instance, wedge_functor takes pw to pw (more or less).*)\n  Lemma ap_wedge_functor {A B C D: pType} (f:A->*C) (g:B->*D) : \n    ap (wedge_functor f g) (pw) =\n    ap (sum_to_wedge o inl) (point_eq f) @ pw @ (ap (sum_to_wedge o inr) (point_eq g))^.\n  Proof.\n    apply wedge_rec_beta_pw.\n  Defined.\nEnd Wedge.\n\nSection Smash.\n  (*First some simple maps used to define the smash product.*)\n  Definition sum_pr1 {A B:pType} (x:A+B) : A :=\n    match x with\n      |inl a => a\n      |inr b => point A\n    end.\n  Definition sum_pr2 {A B:pType} (x:A+B) : B :=\n    match x with\n      |inl a => point B\n      |inr b => b\n    end.\n  Definition sum_to_product {A B:pType} (x : A+B) : A*B:= (sum_pr1 x, sum_pr2 x).\n\n  (*The inclusion of the wedge into the product.*)\n  Definition wedge_in_prod {A B:pType} : wedge A B -> A*B :=\n    wedge_rec (A*B) (sum_to_product o inl) (sum_to_product o inr) idpath.\n  (*This projects the path pw to idpath.*)\n  Lemma ap_wedge_in_prod {A B:pType} : ap (@wedge_in_prod A B) pw = idpath.\n    refine (pushout_rec_beta_pp _ _ _ _).\n  Defined.\n\n  (*This is just used to make the next proof more readable. . .*)\n  Definition pair' {A B : Type}  : A -> B -> B*A := fun a b => (b,a).\n\n  (*The inclusion of the wedge in the product is natural.*)\n  Definition natural_wedge_in_prod {A B C D: pType} (f:A->*C) (g:B->*D) : \n    forall w : wedge A B, \n      functor_prod f g (wedge_in_prod w) = wedge_in_prod (wedge_functor f g w).\n    rapply (@wedge_ind A B).\n    - intro a. exact (ap (pair (f a)) (point_eq g) ).\n    - intro b. exact (ap (pair' (g b)) (point_eq f) ).\n    -rewrite transport_paths_FlFr.\n     rewrite concat_pp_p.\n     rewrite (ap_compose wedge_in_prod (functor_prod f g)).\n     rewrite (ap_compose (wedge_functor f g) wedge_in_prod).\n     rewrite (@ap_wedge_in_prod A B). hott_simpl.\n     rewrite (@ap_wedge_functor A B C D f g).\n     rewrite (ap_compose inr sum_to_wedge).\n     rewrite (ap_compose inl sum_to_wedge).\n     rewrite ap_pp. rewrite ap_pp. \n     rewrite (@ap_wedge_in_prod C D). hott_simpl.\n     rewrite <- (ap_compose sum_to_wedge wedge_in_prod).     \n     rewrite <- (ap_compose sum_to_wedge wedge_in_prod).\n     pointed_reduce.\n     exact idpath.\n  Qed.\n\n  (*Define the smash as a pushout.*)\n  Definition smash (A B : pType) :=\n    pushout (@const (wedge A B) Unit tt) (wedge_in_prod).\n\n  (*The projection from the product to smash.*)\n  Definition prod_to_smash {A B:pType} (pair:A*B) : smash A B\n    := push (inr pair).\n\n  (*Define the base point of smash.*)\n  Global Instance ispointed_smash {A B:pType} : IsPointed (smash A B) := push (inl tt).\n  Definition pSmash (A B: pType) := Build_pType (smash A B) _.\n\n  (*The wedge collapses to a point in smash.*)\n  Definition ps {A B : pType} :\n    forall w : wedge A B, ispointed_smash = pushr w\n    := pp.\n\n  (*These are nice if you want to use smash without refering to wedge.*)\n  Definition psA {A B : pType} :\n    forall a : A, ispointed_smash = prod_to_smash (a, point B).\n    intro a.\n    exact (ps (sum_to_wedge (inl a))).\n  Defined.\n  \n  Definition psB {A B : pType} :\n    forall b : B, ispointed_smash = prod_to_smash (point A, b).\n    intro b.\n    exact (ps (sum_to_wedge (inr b))).\n  Defined.\n\n  (*Smash recursion : You need a map from A*B that is constant on the wedge.*)\n  Definition smash_rec {A B : pType}\n             (P:Type)\n\t         (f:A*B->P)\n             (const_w : forall w : wedge A B, f (point A, point B) = f (wedge_in_prod w))\n  : smash A B -> P.\n  Proof.\n    refine (pushout_rec _ _ _).\n    - intros [ [] | pair].\n      + (*What the basepoint of smash A B should be mapped to*)\n        exact (f (point A, point B)).\n      + (*What a general element of smash A B should be mapped to*)\n        exact (f pair).\n    - exact const_w.\n  Defined.\n\n  (*Variant of the recursion that doesn't use wedge.*)\n  Definition smash_rec' {A B:pType} \n\t     (P:Type)\n\t     (f:A*B->P)\n         (const_w_1 : forall a : A, f (point A, point B) = f (a, point B))\n         (const_w_2 : forall b : B, f (point A, point B) = f (point A, b))\n         (const_w_12 : const_w_1 (point A) = const_w_2 (point B))\n  : smash A B -> P.\n  Proof.\n    apply (smash_rec P f).\n    -(*Now we show that f is constant on the wedge*)\n      rapply (@wedge_ind A B).\n      + exact const_w_1.\n      + exact const_w_2.\n      + simpl.\n        path_via (const_w_1 (point A)).\n        * path_via ((const_w_1 (point A)) @ ap (f o wedge_in_prod) pw).\n            refine (transport_paths_Fr _ _).\n            path_via (const_w_1 (point A) @ 1).\n            { apply whiskerL.\n              path_via (ap f (ap wedge_in_prod pw)).\n              { apply ap_compose. }\n              refine (concat _ _).\n              exact (ap f idpath).\n               apply ap.\n               apply ap_wedge_in_prod.\n              apply ap_1.\n              }\n            apply concat_p1.\n        * exact const_w_12.\n  Defined.\n  \n  Definition smash_pRec {A B : pType}\n             (P : pType)\n             (f : Build_pType (A*B) _ ->* P)\n             (const_w : forall w: wedge A B, point P = f (wedge_in_prod w))\n  : pSmash A B ->* P.\n    Proof.\n      refine (Build_pMap _ _ _ _).\n      - apply (smash_rec P f ).\n        intro w.\n        exact ((point_eq f) @ (const_w w)).\n      - exact (point_eq f).\n    Defined.\n        \n\n  (*TODO: smash_rec_beta?*)\n  (*TODO: smash_ind*)\n  (*TODO : Smash and wedge are pointed. Functors map to pointed maps.*)\n  (*TODO: Smash and wedge are product and coproduct in pType*)\n  (*TODO: Comment better.*)\n  \n  Definition smash_functor {A B C D:pType} (f:A->*C) (g:B ->* D) :\n    smash A B -> smash C D.\n  Proof.\n    rapply (@smash_rec A B).\n    - (*First give the map A*B -> smash C D *)\n      exact (prod_to_smash o (functor_prod f g)). (* : A*B -> smash C D*)\n    - (*Then show it is well defined.*)\n      intro w.\n      (*Show that everything contracts to the basepoint: *)\n      path_via (@ispointed_smash C D).\n      path_via (prod_to_smash (B:=D) (wedge_in_prod (sum_to_wedge (inl (f (point A)))))).\n      + apply (ap prod_to_smash). \n        apply (ap (fun d : D => (f (point A), d))).\n        apply point_eq. \n      + apply (ps _)^. \n      + path_via (prod_to_smash (wedge_in_prod (wedge_functor f g w))).\n        { apply ps. }\n        apply (ap prod_to_smash).\n        apply (natural_wedge_in_prod f g w)^.\n  Defined.\n              \n(*      rewrite (natural_wedge_in_prod).\n      path_via (prod_to_smash (B:=D) (wedge_in_prod (sum_to_wedge (inl a)))).\n      \n      path_via (prod_to_smash (f a, point D)).\n      path_via (prod_to_smash (f (point A), point D)).\n      { apply (ap prod_to_smash).\n        apply (ap (fun d:D => (f (point A), d))).\n        apply point_eq. }\n      { apply ((psA (f (point A)))^ @ (psA (f a))). }\n      apply (ap prod_to_smash). \n      apply (ap (fun d:D => (f a, d))).\n      apply (point_eq g)^.\n    - intro b.\n      path_via (prod_to_smash (point C, g b)).\n      path_via (prod_to_smash (point C, g (point B))).\n      { apply (ap prod_to_smash).\n        apply (ap (fun c : C => (c, g (point B)))).\n        apply point_eq. }\n      { apply ((psB (g (point B)))^ @ (psB (g b))). }\n      { apply (ap prod_to_smash).\n        apply (ap (fun c : C => (c, g b))).\n        apply (point_eq _)^. }\n    - simpl. hott_simpl.\n      rewrite <- ap_pp.\n      rewrite <- ap_pp.\n      apply (ap (ap prod_to_smash)).\n      rewrite ap_V. rewrite ap_V. rewrite concat_pV. rewrite concat_pV.\n      reflexivity.\n  Qed.\n      \n  *)\nEnd Smash.\n\n\n\n(*Results on the relation between smash product and spheres.*)\nSection Smash_and_Spheres.\n\n  Definition sph0xA_to_A {A:pType} : A*(Sphere 0) -> A.\n    intros [a].\n    exact (Susp_rec (point A) (a) (Empty_rec)).\n  Defined.\n  \n  (* \n\tDefinition smashpush' {A:pType} : A*(pSphere 0) + pUnit -> A.\n\t\tintro x; elim x.\n\t\t\t-exact sph0xA_to_A.\n\t\t\t-exact (pconst _ _).\n\tDefined. *)\n  \n  Definition f {A:pType} (a : A+pSphere 0) : A := \n    sph0xA_to_A (wedge_in_prod (@sum_to_wedge A (pSphere 0) a)).\n  Definition g {A:pType} (_ : A+pSphere 0) : A := point A.\n  \n  Definition welldefined {A:pType} : forall w : A + pSphere 0, \n\t\t                       f w = g w.\n    \n    apply sum_ind.\n    -intro a. exact idpath.\n    -apply (@Susp_ind Empty _ idpath idpath); apply Empty_ind.\n  Defined.\n  \n  \n  Definition smash_A_to_A  {A:pType} : smash A (pSphere 0)  -> A.\n    refine (smash_rec' A  _ _ _ _).\n    - apply (prod_curry ).\n      intro a.\n      apply (Susp_rec (point A) a  ). apply Empty_ind. (*Basepoint goes to basepoint.*)\n    - intro a. exact idpath.\n    - rapply (@Susp_ind Empty).\n      + exact idpath.\n      + exact idpath.\n      + apply Empty_ind.\n    - exact idpath.\n  Defined.  \n  \n  Definition A_to_smash_A {A:pType} : A->smash A (pSphere 0) :=\n    fun a:A => @prod_to_smash A (pSphere 0) (a,South).\n    \n  Definition ispointed_A_to_smash_A {A:pType} : \n    A_to_smash_A (point A) = ispointed_smash\n    :=\n      (pp (@sum_to_wedge A (pSphere 0) (inr South)))^.\n\t                                            \n  Lemma isretr_AtoSm {A:pType} : Sect (@A_to_smash_A A) (@smash_A_to_A A).\n    intro a.\n    exact idpath.\n  Defined.\n  \n  Lemma issect_AtoSm {A:pType} : Sect (@smash_A_to_A A) (@A_to_smash_A A).\n    intro a.\n    unfold A_to_smash_A.\n    unfold prod_to_smash.\n    unfold smash_A_to_A.\n    unfold smash_rec'.\n    unfold smash_rec.\n    simpl.\n    unfold prod_curry.\n    simpl.\n    unfold wedge_ind.\n    simpl.\n    unfold Susp_rec.\n    unfold wedge_in_prod.\n    simpl.\n    unfold wedge_rec.\n    simpl.\n    unfold pushout_rec.\n    simpl.\n    unfold pushout_ind.\n    simpl.\n    unfold pushout.\n    simpl.\n    unfold Susp_ind.\n    unfold ap_wedge_in_prod.\n    simpl.\n    unfold pushout_rec_beta_pp.\n    unfold pushout_ind_beta_pp.\n    unfold pushout.\n    \n    refine (pp _)^.\n\n    \n  Admitted.\n  \n  Lemma isequiv_A_to_smash_A {A:pType} : IsEquiv (@A_to_smash_A A).\n    refine (BuildIsEquiv _ _ A_to_smash_A smash_A_to_A issect_AtoSm isretr_AtoSm _).\n  Admitted.\n(*\n  Lemma is_pequiv_A_smash_A (A:pType) : A <~>* p (smash A (pSphere 0)).\n    refine (Build_pEquiv A (p (smash A (pSphere 0))) _ _).\n    -exact (Build_pMap A (p (smash A (pSphere 0))) (@A_to_smash_A A) ispointed_A_to_smash_A).\n    -exact isequiv_A_to_smash_A.\n  Qed.\n  \n  Lemma commute_smash_susp {A B:pType} : p (smash (psusp A) B) <~>* psusp p (smash A B).\n  Admitted.\n  *)\n  \nEnd Smash_and_Spheres.\n\n\n\n\n\n\n(* \t\t\n\t\t\n\t\t\tAlternative wedge_functor\n\t\t\n\t\t\trapply (@functor_coeq Unit (A+B)).\n\t\t\t\t-exact idmap.\n\t\t\t\t-intros [a|b].\n\t\t\t\t\t+exact (inl (f a)).\n\t\t\t\t\t+exact (inr (g b)).\n\t\t\t\t-intros [].\n\t\t\t\tapply (ap inl).\n\t\t\t\texact (point_eq f).\n\t\t\t\t-intros [].\n\t\t\t\tapply (ap inr).\n\t\t\t\texact (point_eq g).\n\t\t\t\t\n *)\n(* Alternative smash_functor\n\n\t\t\trapply (@functor_coeq (wedge A B) (Unit+(A*B))).\n\t\t\t\t-exact (wedge_functor f g).\n\t\t\t\t-intros [[]|ab].\n\t\t\t\t\t+exact (inl tt).\n\t\t\t\t\t+exact (inr (functor_prod f g ab)).\n\t\t\t\t-apply ap10. exact idpath.\n\t\t\t\t-intro w.\n\t\t\t\tapply (ap inr).\n\t\t\t\texact (natural_wedge_in_prod f g w). *)*)", "meta": {"author": "kalfsvag", "repo": "misc_coq", "sha": "9886ed4eb3dfc077afd1d769c910a729475fa173", "save_path": "github-repos/coq/kalfsvag-misc_coq", "path": "github-repos/coq/kalfsvag-misc_coq/misc_coq-9886ed4eb3dfc077afd1d769c910a729475fa173/wedge_and_smash.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.722159649395202}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\nSet Implicit Arguments.\n\nRequire Import fcf.FCF.\nRequire Import fcf.CompFold.\nRequire Import fcf.RndListElem.\nRequire Import Permutation.\n\nLocal Open Scope list_scope.\n\nTheorem removeFirst_In_length : \n  forall (A : Set)(eqd : EqDec A)(ls : list A)(a : A),\n    In a ls ->\n    length (removeFirst (EqDec_dec _ ) ls a) = pred (length ls).\n  \n  induction ls; intuition; simpl in *.\n  intuition; subst.\n  destruct (EqDec_dec eqd a0 a0); intuition.\n  \n  destruct (EqDec_dec eqd a0 a); subst.\n  trivial.\n  simpl.\n  rewrite IHls.\n  destruct ls; simpl in *; intuition.\n\n  trivial.\nQed.\n\nFixpoint addInAllLocations(A : Type)(a : A)(ls : list A) :=\n  match ls with\n    | nil =>  (a :: nil) :: nil\n    | a' :: ls' => \n      (a :: ls) :: map (fun x => a' :: x) (addInAllLocations a ls')\n  end.\n\nFixpoint getAllPermutations(A : Type)(ls : list A) :=\n  match ls with\n    | nil => nil :: nil\n    | a :: ls' =>\n      let perms' := getAllPermutations ls' in\n        flatten (map (addInAllLocations a) perms')\n  end.\n\nTheorem addInAllLocations_not_nil : \n  forall (A : Type) l (a : A),\n    addInAllLocations a l = nil -> False.\n\n  induction l; intuition; unfold addInAllLocations in *; simpl in *.\n  inversion H.\n  inversion H.\n\nQed.\n\nTheorem getAllPermutations_not_nil : \n  forall (A : Type)(ls : list A),\n    getAllPermutations ls = nil -> False.\n\n  induction ls; intuition; simpl in *.\n  inversion H.\n\n  case_eq (getAllPermutations ls); intuition.\n  rewrite H0 in H.\n  simpl in *.\n  apply app_eq_nil in H.\n  intuition.\n  eapply addInAllLocations_not_nil; eauto.\nQed.\n  \n\nTheorem addInAllLocations_perm : \n  forall (A : Type) x0 (a : A) ls2,\n    In ls2 (addInAllLocations a x0) ->\n    Permutation ls2 (a :: x0).\n\n  induction x0; intuition; simpl in *.\n  intuition; subst.\n  eapply Permutation_refl.\n  \n  intuition; subst.\n  eapply Permutation_refl.\n\n  eapply in_map_iff in H0.\n  destruct H0.\n  intuition; subst.\n  eapply perm_trans.\n  Focus 2.\n  eapply perm_swap.\n  eapply perm_skip.\n  eapply IHx0.\n  trivial.\n\nQed.\n\nTheorem getAllPermutations_perms : \n  forall (A : Set)(ls1 ls2 : list A),\n    In ls2 (getAllPermutations ls1) ->\n    Permutation ls1 ls2.\n\n  induction ls1; intuition; simpl in *.\n  intuition.\n  subst.\n  econstructor.\n\n  eapply in_flatten in H.\n  destruct H.\n  intuition.\n  eapply in_map_iff in H0.\n  destruct H0.\n  intuition.\n  subst.\n  eapply addInAllLocations_perm in H1.\n  eapply perm_trans.\n  Focus 2.\n  eapply Permutation_sym.\n  eauto.\n  eapply perm_skip.\n  eapply IHls1.\n  trivial.\n  \nQed.\n\nSection ShuffleList.\n\n  Variable A : Set.\n  Hypothesis A_EqDec : EqDec A.\n\n  Definition shuffle(ls : list A) :=\n    o <-$ rndListElem _ (getAllPermutations ls);\n    ret \n    match o with\n      | None => nil\n      | Some x => x\n    end.\n      \n  Theorem shuffle_perm : \n    forall (ls1 ls2 : list A),\n      In ls2 (getSupport (shuffle ls1)) ->\n      Permutation ls2 ls1.\n\n    intuition.\n    unfold shuffle in *.\n    repeat simp_in_support.\n    destruct x.\n    eapply Permutation_sym.\n    eapply getAllPermutations_perms.    \n    apply rndListElem_support in H0.\n    trivial.\n\n    apply rndListElem_support_None in H0.\n    exfalso.\n    eapply getAllPermutations_not_nil.\n    eauto.\n\n  Qed.\n\n   Fixpoint permute(ls : list A)(sigma : list nat) : list A :=\n    match sigma with\n      | nil => nil\n      | n :: sigma' => \n        match (nth_error ls n) with\n          | None => nil\n          | Some a => a :: (permute ls sigma')\n        end\n  end.\n\n   Theorem permute_length_eq : \n     forall (sigma : list nat)(ls : list A),\n       (forall n, In n sigma -> n < length ls) ->\n       length (permute ls sigma) = length sigma.\n     \n     induction sigma; intuition; simpl in *.\n     case_eq (nth_error ls a); intuition.\n     simpl.\n     f_equal.\n     eapply IHsigma; intuition.\n     \n     Theorem nth_error_not_None : \n       forall (ls : list A)(n : nat),\n         n < length ls ->\n         nth_error ls n = None -> \n         False.\n\n       induction ls; destruct n; intuition; simpl in *.\n       omega.\n       omega.\n       inversion H0.\n       eapply IHls; eauto.\n       omega.\n     Qed.\n\n     exfalso.\n     eapply nth_error_not_None.\n     eapply H.\n     intuition.\n     trivial.\n   Qed.\n   \n   Theorem shuffle_Permutation : \n     forall (ls1 ls2 : list A),\n       In ls2 (getSupport (shuffle ls1)) ->\n       Permutation ls1 ls2.\n     \n     intuition.\n\n     unfold shuffle in *.\n     repeat simp_in_support.\n     destruct x.\n     eapply rndListElem_support in H0.\n     eapply getAllPermutations_perms.\n     trivial.\n\n     eapply rndListElem_support_None in H0.\n     exfalso.\n     eapply getAllPermutations_not_nil.\n     eauto.\n\n    Qed.\n  \n    Theorem shuffle_wf : \n      forall ls,\n        well_formed_comp (shuffle ls).\n\n      intuition.\n      unfold shuffle.\n      wftac.\n      eapply rndListElem_wf.\n\n    Qed.\n\nEnd ShuffleList.\n\nDefinition RndPerm(n : nat) :=\n  shuffle _ (allNatsLt n).\n\nTheorem list_pred_map_both':\n  forall (A B C D : Set) (lsa : list A) (lsb : list B) \n    (P : C -> D -> Prop) (f : A -> C)(g : B -> D),\n  list_pred (fun (a : A) (b : B) => P (f a) (g b)) lsa lsb ->\n  list_pred P (map f lsa) (map g lsb).\n\n  intuition.\n  eapply list_pred_impl.\n  eapply list_pred_map_both.\n  eauto.\n  intuition.\n  destruct H0.\n  destruct H0.\n  intuition; subst.\n  trivial.\n\nQed.\n\nTheorem addInAllLocations_pred : \n  forall (A B : Set) (R : A -> B -> Prop) (a : list A) (b : list B),\n    list_pred R a b ->\n    forall a1 a2,\n      R a1 a2 ->\n  list_pred (list_pred R) (addInAllLocations a1 a) (addInAllLocations a2 b).\n  \n  induction 1; intuition; simpl in *.\n  \n  econstructor.\n  econstructor.\n  trivial.\n  econstructor.\n  econstructor.\n  \n\n  econstructor.\n  repeat econstructor;assumption.\n\n  eapply list_pred_map_both'.\n  eapply list_pred_impl.\n  eauto.\n  intuition.\n  econstructor; assumption.\n\nQed.\n\nTheorem getAllPermutations_pred :\n  forall (A B : Set)(R : A -> B -> Prop)(lsa : list A)(lsb : list B),\n  list_pred R lsa lsb ->\n     list_pred (list_pred R) (getAllPermutations lsa) (getAllPermutations lsb).\n\n  induction 1; intuition; simpl in *.\n  econstructor.\n  econstructor.\n  econstructor.\n\n  eapply list_pred_flatten_both.\n  eapply list_pred_map_both'.\n  eapply list_pred_impl.\n  eauto.\n  intuition.\n  \n  eapply addInAllLocations_pred; intuition.\nQed.\n\nTheorem allNats_nth_pred : \n  forall (A : Set)(ls : list A),\n   list_pred (fun (a : A) (b : nat) => nth_error ls b = Some a) ls\n     (allNatsLt (length ls)).\n\n  induction ls using rev_ind; intuition; simpl in *.\n  econstructor.\n \n  rewrite app_length.\n  simpl.\n  rewrite plus_comm.\n  simpl.\n\n  eapply list_pred_app_both.\n  eapply list_pred_impl.\n  eapply IHls.\n  intuition.\n\n  Theorem nth_error_app_Some : \n    forall (A : Set)(ls : list A) n (a a' : A),\n      nth_error ls n = Some a ->\n      nth_error (ls ++ (a' :: nil)) n = Some a.\n\n    induction ls; destruct n; intuition; simpl in *.\n    inversion H.\n    inversion H.\n\n    eapply IHls.\n    trivial.\n\n  Qed.\n\n  eapply nth_error_app_Some; intuition.\n\n  econstructor.\n\n  Theorem nth_error_app_length : \n    forall (A : Set)(ls : list A) (a : A),\n      nth_error (ls ++ (a :: nil)) (length ls) = Some a.\n\n    induction ls; intuition; simpl in *.\n    \n  Qed.\n\n  eapply  nth_error_app_length .\n\n  econstructor.\n  \nQed.\n\nTheorem permute_nth_equiv : \n  forall (A : Set)(ls : list A) a b,\n  list_pred (fun (a0 : A) (b0 : nat) => nth_error ls b0 = Some a0) a b ->\n  a = permute ls b.\n\n  induction a; inversion 1; intuition; simpl in *.\n  subst.\n  \n  rewrite H2.\n  f_equal.\n  eapply IHa.\n  trivial.\nQed.\n\nTheorem getAllPerms_permute_eq :\n  forall (A : Set)(ls : list A),\n  list_pred (fun (a : list A) (b : list nat) => a = permute ls b)\n     (getAllPermutations ls) (getAllPermutations (allNatsLt (length ls))).\n\n  intuition.\n\n  generalize (@getAllPermutations_pred _ _ (fun a b => nth_error ls b = Some a) ls (allNatsLt (length ls))) ; intros.\n  eapply list_pred_impl.\n  eapply H.\n\n  eapply allNats_nth_pred.\n\n  intuition.\n\n  eapply permute_nth_equiv.\n  trivial.\n  \nQed.\n\nTheorem rndListElem_pred : \n  forall (A B : Set)(eqda : EqDec A)(eqdb : EqDec B)(P : A -> B -> Prop)(lsa : list A)(lsb : list B),\n    list_pred P lsa lsb ->\n    comp_spec (fun a b => \n      match a with\n        | None => b = None\n        | Some a' => exists b', b = Some b' /\\ P a' b'\n      end) (rndListElem _ lsa) (rndListElem _ lsb).\n\n\n  intuition.\n  unfold rndListElem in *.\n  case_eq (length lsa); intuition.\n  erewrite <- list_pred_length_eq; eauto.\n  rewrite H0.\n  eapply comp_spec_ret; intuition.\n  \n  erewrite <- list_pred_length_eq; eauto.\n  rewrite H0.\n  comp_skip.\n  apply None.\n  apply None.\n  eapply comp_spec_ret; intuition.\n\n  case_eq (nth_option lsa b); intuition.\n\n  Theorem list_pred_nth_exists : \n    forall (A B : Set)(P : A -> B -> Prop) lsa lsb,\n      list_pred P lsa lsb ->\n      forall n a, \n        nth_option lsa n = Some a -> exists b, nth_option lsb n = Some b /\\ P a b.\n\n    induction 1; intuition; simpl in *.\n    discriminate.\n\n    destruct n.\n    inversion H1; clear H1; subst.\n    econstructor; intuition.\n\n    edestruct IHlist_pred; eauto.\n\n  Qed.\n\n  edestruct list_pred_nth_exists; eauto.\n\n  exfalso.\n  eapply nth_option_not_None; eauto.\n  apply RndNat_support_lt in H1.\n  omega.\nQed.\n\nTheorem shuffle_RndPerm_spec : \n  forall (A : Set)(eqd : EqDec A)(ls : list A),\n    comp_spec (fun a b => a = permute ls b)\n    (shuffle eqd ls)\n    (shuffle _ (allNatsLt (length ls))).\n\n  intuition.\n  unfold shuffle in *.\n  \n  comp_skip.\n  eapply rndListElem_pred.\n  eapply getAllPerms_permute_eq.\n  \n  simpl in H1.\n  eapply comp_spec_ret; intuition.\n  destruct a.\n  destruct H1.\n  intuition.\n  subst.\n  trivial.\n\n  subst.\n  simpl.\n  intuition.\nQed.\n\nTheorem shuffle_RndPerm_spec_eq : \n  forall (A : Set)(eqd : EqDec A)(ls : list A),\n    comp_spec eq\n    (shuffle eqd ls)\n    (x <-$ RndPerm (length ls); ret permute ls x).\n\n  intuition.\n  eapply comp_spec_eq_trans.\n  eapply comp_spec_eq_symm.\n  eapply comp_spec_right_ident.\n  comp_skip.\n  eapply shuffle_RndPerm_spec.\n  eapply comp_spec_ret; intuition.\n\nQed.\n\nTheorem RndPerm_In_support : \n  forall n ls, \n    In ls (getSupport (RndPerm n)) ->\n    Permutation (allNatsLt n) ls.\n  \n  intuition.\n  eapply shuffle_Permutation.\n  eapply H.\nQed.\n\n\nTheorem RndPerm_In_support_length :\n  forall n ls,\n    In ls (getSupport (RndPerm n)) ->\n    length ls = n.\n\n  intuition.\n  erewrite Permutation_length.\n  Focus 2.\n  eapply Permutation_sym.\n  eapply RndPerm_In_support.\n  eauto.\n  eapply allNatsLt_length.\nQed.\n\nTheorem RndPerm_wf : \n  forall n,\n    well_formed_comp (RndPerm n).\n\n  intuition.\n  unfold RndPerm.\n  eapply shuffle_wf.\n\nQed.", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/fcf/RndPerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488296, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7221596442081675}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) : natural :=\n  plus Zero (plus lf2 y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj134_coqofml_Fr4SdC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7221507257314983}}
{"text": "Require Import List.\nOpen Scope list_scope.\n\nLemma list_Forall_map : forall X Y (P : Y -> Prop) (f : X -> Y) l,\n  Forall P (map f l) <-> Forall (fun x => P (f x)) l.\nProof.\n  induction l.\n  - now split; constructor.\n  - split; simpl; intro H.\n    + inversion H.\n      rewrite IHl in H3.\n      now constructor.\n    + inversion H.\n      rewrite <- IHl in H3.\n      now constructor.\nQed.\n\nLemma list_Exists_map : forall X Y (P : Y -> Prop) (f : X -> Y) l,\n  Exists P (map f l) <-> Exists (fun x => P (f x)) l.\nProof.\n  induction l.\n  - now split.\n  - simpl. split; intro H.\n    + inversion H.\n      * now apply Exists_cons_hd.\n      * now apply Exists_cons_tl, IHl.\n    + inversion H.\n      * now apply Exists_cons_hd.\n      * now apply Exists_cons_tl, IHl.\nQed.\n\nLemma list_Exists_Forall_and : forall X (P Q: X -> Prop) l,\n    Exists P l ->\n    Forall Q l ->\n    Exists (fun x => P x /\\ Q x) l.\nProof.\n  intros X P Q l ex all.\n  rewrite (Exists_exists P l) in ex. destruct ex as [x [x_in px]].\n  rewrite Exists_exists. exists x.\n  rewrite Forall_forall in all.\n  split; [|split]; now auto.\nQed.\n", "meta": {"author": "yoshihiro503", "repo": "cbc-casper-coq", "sha": "2e384d6295ac9ae1c5d27444eba8dff0a1dfec7f", "save_path": "github-repos/coq/yoshihiro503-cbc-casper-coq", "path": "github-repos/coq/yoshihiro503-cbc-casper-coq/cbc-casper-coq-2e384d6295ac9ae1c5d27444eba8dff0a1dfec7f/src/Util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7221507191651764}}
{"text": "Require Export D.\n\n\n\n(** **** Problem : 3 stars (mult_comm) *)\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.  \n  intros. induction n. simpl. reflexivity.\n  simpl. rewrite -> IHn.\n  Lemma plus_assoc : forall a b c : nat, a + (b + c) = (a + b) + c.\n  Proof. \n      intros. induction a. reflexivity.\n      simpl. rewrite -> IHa. reflexivity. Qed.\n  rewrite -> plus_assoc. reflexivity.\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/02/P07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7221507128111041}}
{"text": "(** by Evelyne Contejean, LRI *)\n\n(** * Some additional properties for the Coq lists. *)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import List Arith.\n\n\n(** ** Relations between length, map, append, In and nth. *)\n\nLemma map_map :\n  forall (A B C : Set) (l : (list A)) (f : B -> C) (g : A ->B),\n  map f (map g l) = map (fun x => f (g x)) l.\nProof.\nintros A B C l f g; induction l as [ | x l].\ntrivial.\nsimpl; rewrite IHl; trivial.\nQed.\n\nLemma list_app_length :\n forall A, forall l1 l2 : list A, length (l1 ++ l2) = length l1 + length l2.\nProof.\ninduction l1 as [ | a1 l1 ]; trivial.\nintros; simpl; rewrite IHl1; trivial.\nQed.\n\nLemma length_map :\n forall (A B : Set) (f : A -> B) (l : list A), length (map f l) = length l.\nProof.\nintros; induction l as [ | a l ]; trivial.\nsimpl; rewrite IHl; trivial.\nQed.\n\nLemma map_app :\n forall (A B : Set) (f : A -> B) l1 l2, map f (l1 ++ l2) = (map f l1) ++ (map f l2).\nProof.\ninduction l1 as [ | a1 l1 ]; trivial.\nintros; simpl; rewrite IHl1; trivial.\nQed.\n\n\nLemma in_in_map :\n  forall (A B : Set) (f : A -> B) a l, In a l -> In (f a) (map f l).\nProof.\nintros A B f a l; induction l as [ | b l ]; trivial.\nintro In_a; elim In_a; clear In_a; intro In_a.\nsubst; left; trivial.\nright; apply IHl; trivial.\nQed.\n\nLemma in_map_in :\n  forall (A B : Set) (f : A -> B) b l, In b (map f l) ->\n  exists a, In a l /\\ f a = b.\nProof.\nintros A B f b l; induction l as [ | a l ].\ncontradiction.\nintro In_b; elim In_b; clear In_b; intro In_b.\nexists a; split; trivial; left; trivial.\nelim (IHl In_b); intros a' [H1 H2]; exists a'; split; trivial; right; trivial.\nQed.\n\nLemma nth_error_map :\n  forall (A B : Set) (f : A -> B) (l : list A) i,\n  match nth_error (map f l) i with\n  | Some f_li => \n           match nth_error l i with\n            | Some li => f_li = f li\n            | None => False\n            end\n  | None =>\n            match nth_error l i with\n            | Some li => False\n            | None => True\n            end\nend.\nProof.\ninduction l as [ | a l ]; \nintro i; destruct i as [ | i ]; simpl; trivial.\napply IHl; trivial.\nQed.\n\n(** ** A measure on lists based on a measure on elements. *)\n\nFixpoint list_size (A : Set) (size : A -> nat) (l : list A) {struct l} : nat :=\n  match l with\n  | nil => 0\n  | h :: tl => size h + list_size size tl\n  end.\n\nLemma list_size_tl_compat :\n  forall (A : Set) (size : A -> nat) a b l, size a < size b -> \n    list_size size (a :: l) < list_size size (b :: l).\nProof.\nintros A size a b l H; simpl; apply Nat.add_lt_mono_r; trivial.\nQed.\n\nLemma list_size_app:\n forall (A : Set) (size : A -> nat) l1 l2,\n list_size size (l1 ++ l2) = list_size size l1 + list_size size l2.  \nProof. \ninduction l1 as [ | a1 l1 ]; trivial.\nintros; simpl; rewrite IHl1; auto with arith.\nQed.\n\nLemma list_size_fold :\n  forall (A : Set) (size : A -> nat) l n,\n  fold_left (fun (size_acc : nat) (a : A) => size_acc + size a) l n =\n  n + list_size size l.\nProof.\nintros A size l; induction l; trivial.\nintro n; simpl; rewrite Nat.add_assoc; apply IHl.\nQed.\n\nLemma list_size_size_eq :\n  forall (A : Set) (size1 : A -> nat) (size2 : A -> nat) l,\n (forall a, In a l -> size1 a = size2 a) -> list_size size1 l = list_size size2 l.\nProof.\nintros A size1 size2 l; induction l as [ | a l]; simpl; trivial.\nintros size1_eq_size2.\nrewrite (size1_eq_size2 a (or_introl _ (refl_equal _))).\napply (f_equal (fun n => size2 a + n)); apply IHl;\nintros; apply size1_eq_size2; right; trivial.\nQed.\n\n(** ** Induction principles for list. \n Induction on the length. *)\nDefinition list_rec2 :\n  forall A, forall P : list A -> Type,\n    (forall (n:nat) (l : list A), length l <= n -> P l) -> \n    forall l : list A, P l.\nProof.\nintros A P H l; apply (H (length l) l); apply le_n.\nDefined.\n\nDefinition o_length (A : Set) (l1 l2 : list A) : Prop := length l1 < length l2.\n\nTheorem well_founded_length : forall A, well_founded (o_length (A := A)).\nProof.\nintro A; assert (Acc_nil : Acc (o_length (A:=A)) (@nil A)).\napply Acc_intro; intros l H; absurd (o_length l nil); trivial; \nunfold o_length; simpl; auto with arith.\n\nunfold well_founded, o_length; \nintros l; pattern l; apply list_rec2; clear l;\ninduction n; intro l; destruct l; intros H; trivial.\nsimpl in H; absurd (S (length l) <= 0); trivial; auto with arith.\napply Acc_intro; intros l' H'; apply IHn;\napply Nat.le_trans with (length l);\nsimpl in H; simpl in H'; auto with arith.\nDefined.\n\n(** Induction on the the size. *)\nDefinition list_rec3 (A : Set) (size : A -> nat) :\n  forall P : list A -> Type,\n    (forall (n:nat) (l : list A), list_size size l <= n -> P l) -> \n    forall l : list A, P l.\nProof.\nintros P H l; apply (H (list_size size l) l); apply le_n.\nDefined.\n\n(** ** How to remove an element in a list, whenever it is present. *)\nFixpoint split_list (A : Set)\n  (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (l : list A) (t : A) {struct l} : list A * list A :=\n  match l with\n  | nil => (nil, nil)\n  | a :: l' =>\n      if eqA t a\n      then (nil, l')\n      else let (l1,l2) := split_list eqA l' t in (a :: l1, l2)\n  end.\n\nLemma split_list_app_cons :\n forall (A : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) t l,\n   In t l -> let (l1, l2) := split_list eqA l t in l = l1 ++ t :: l2.\nProof.\ninduction l as [ | a l ].\ncontradiction.\nsimpl; elim (eqA t a); intro eq_t_a.\nintros _; subst; trivial.\nintros [eq_t_a' | In_t].\nabsurd (t = a); auto.\ngeneralize (IHl In_t); destruct (split_list eqA l t); intro; subst; auto.\nDefined.\n\nFixpoint remove (A : Set) (eqA : forall a1 a2 : A, {a1=a2}+{a1<>a2}) \n  (a : A) (l : list A) {struct l} : (option (list A)) :=\n  match l with\n  | nil => None \n  | h :: tl =>\n    if eqA a h\n    then Some tl\n    else \n      match remove eqA a tl with\n      | Some rmv => Some (h :: rmv)\n      | None => None \n      end\n  end.\n\nLemma in_remove :\n  forall (A : Set) (eqA : forall a1 a2 : A, {a1=a2}+{a1<>a2}) a l,  \n  match remove eqA a l with\n  | None => ~In a l\n  | Some l' => In a l /\\ let (l1, l2) := split_list eqA l a in l' = l1 ++ l2\n  end.\nProof.\ninduction l as [ | a1 l]; simpl; auto;\nelim (eqA a a1); intro eq_a_a1; intuition.\ndestruct (remove eqA a l) as [ rmv |  ]; intuition; \ndestruct (split_list eqA l a); subst; auto.\nQed.\n\nFixpoint remove_list (A : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n(la l : list A) {struct l} : option (list A) :=\n  match la with\n  | nil => Some l\n  | a :: la' => \n\tmatch l with \n\t| nil => None\n\t| b :: l' => \n\t   if eqA a b\n\t   then remove_list eqA la' l'\n\t   else \n\t     match remove_list eqA la l' with\n\t     | None => None\n\t     | Some rmv => Some (b :: rmv)\n\t     end\n        end\n  end.\n\n\n(** ** Iterators. *) \nFixpoint fold_left2 (A B C : Set) (f : A -> B -> C -> A) (a : A) (l1 : list B) (l2 : list C)  \n  {struct l1} : option A :=\n  match l1, l2 with\n  | nil, nil => Some a\n  | b :: t1, c :: t2 => fold_left2 f (f a b c) t1 t2\n  | _, _ => None\n  end.\n\n(** ** more properties on the nth element. *)\nLemma nth_error_ok_in :\n  forall (A : Set) n (l : list A) (a : A),\n  nth_error l n = Some a -> In a l.\nProof.\nintros A n l; generalize n; clear n; induction l as [ | a' l].\nintros [ | n] a; simpl; discriminate.\nintros [ | n] a; simpl.\nintro H; injection H; subst; left; trivial.\nintro; right; apply IHl with n; trivial.\nQed.\n\n(** ** Association lists. \n*** find. *)\nFixpoint find (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n(a : A) (l : list (A * B)) {struct l} : option (B) :=\n match l with\n | nil => None\n | (a1,b1) :: l =>\n     if eqA a a1\n     then Some b1\n     else find eqA a l\n  end.\n\nLemma find_not_mem :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  (a : A) (b : B) (l : list (A * B)) (dom : list A),\n  ~In a dom -> (forall a', In a' dom -> find eqA a' ((a,b) :: l) = find eqA a' l).\nProof.\nintros A B eqA a b l dom a_not_in_dom a' a'_in_dom; simpl;\ndestruct (eqA a' a) as [a'_eq_a | a'_diff_a].\nsubst a'; absurd (In a dom); trivial.\ntrivial.\nQed.\n\n(** *** number of occurences of the first element of a pair. *)\nFixpoint nb_occ (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  (a : A) (l : list (A * B)) {struct l} : nat :=\n  match l with\n  | nil => 0\n  | (a',_) :: tl =>\n     if (eqA a a') then S (nb_occ eqA a tl) else nb_occ eqA a tl\n  end.\n\nLemma none_nb_occ_O :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  (a : A) (l : list (A * B)),\n  find eqA a l = None -> nb_occ eqA a l = 0.\nProof.\nintros A B eqA a l; induction l as [ | [a1 b1] l]; trivial; simpl.\ndestruct (eqA a a1) as [a_eq_a1 | a_diff_a1]; intros.\ndiscriminate.\napply IHl; trivial.\nQed.\n\nLemma some_nb_occ_Sn :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  (a : A) (l : list (A * B)) b,\n  find eqA a l = Some b -> 1 <= nb_occ eqA a l.\nProof.\nintros A B eqA a l; induction l as [ | [a1 b1] l].\nintros; discriminate.\nintro b; simpl; destruct (eqA a a1) as [_ | _].\nauto with arith.\nintros; apply IHl with b; trivial.\nQed.\n\nLemma nb_occ_app :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  a (l1 l2 : list (A * B)), \n  nb_occ eqA a (l1++l2) = nb_occ eqA a l1 + nb_occ eqA a l2.\nProof.\nintros A B eqA a l1; induction l1 as [ | [a1 b1] l1]; simpl; trivial.\nintro l2; rewrite IHl1; destruct (eqA a a1) as [_ | _]; trivial.\nQed.\n\nLemma reduce_assoc_list :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}),\n  forall (l : list (A * B)), exists l', \n (forall a, nb_occ eqA a l' <= 1) /\\ (forall a, find eqA a l = find eqA a l').\nProof.\nintros A B eqA l; induction l as [ | [a1 b1] l].\nexists (nil : list (A * B)); split; trivial; auto.\nelim IHl; intros l' [H1 H2].\nassert (In_a1 : forall a, a = a1 -> find eqA a l' = find eqA a1 l').\nintros; subst; trivial.\ndestruct (find eqA a1 l') as [ b | ]; \ngeneralize (In_a1 _ (refl_equal _)); clear In_a1; intro In_a1.\nassert (In_a1' : exists l1, exists  l2, l' = l1 ++ (a1,b) :: l2).\nclear H1 H2; induction l' as [ | [a' b'] l'].\ndiscriminate.\nsimpl in In_a1; destruct (eqA a1 a') as [a1_eq_a' | _].\nsubst; inversion In_a1; exists (nil : list (A * B)); exists l'; simpl; trivial.\nelim (IHl' In_a1); intros l1 [l2 H]; \nexists ((a',b') :: l1); exists l2; subst; trivial.\nelim In_a1'; intros l1 [l2 H]; exists ((a1,b1) :: l1 ++ l2); split.\nintro a; generalize (H1 a); subst l'; rewrite nb_occ_app; \nsimpl; destruct (eqA a a1) as [a_eq_a1 | _]; subst; rewrite nb_occ_app;\n[ rewrite Nat.add_comm; simpl; rewrite Nat.add_comm | idtac ]; trivial.\nintro a; simpl; destruct (eqA a a1) as [a_eq_a1 | a_diff_a1]; trivial.\nrewrite H2; subst l'; clear H1 H2 In_a1 In_a1'; \ninduction l1 as [ | [a1' b1'] l1]; simpl.\ndestruct (eqA a a1); trivial; absurd (a = a1); trivial.\nrewrite IHl1; trivial.\nexists ((a1,b1) :: l'); split; trivial; intro a; simpl.\ndestruct (eqA a a1) as [a_eq_a1 | a_diff_a1]; trivial.\nrewrite none_nb_occ_O; subst; trivial.\nrewrite (H2 a); trivial.\nQed.\n\n(** map_without_repetition applies a function to the elements of a list,\nbut only a single time when there are several consecutive occurences of the\nsame element. Moreover, the function is supposed to return an option as a result,\nin order to simulate exceptions, and the abnormal results are discarted.\n *)\n\nFixpoint map_without_repetition (A B : Set) \n  (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (f : A -> option B) (l : list A) {struct l} : list B :=\n    match l with\n    | nil => (nil : list B)\n    | h :: nil => \n      match f h with\n      | None => nil\n      | Some f_h => f_h :: nil\n      end\n    | h1 :: ((h2 :: tl) as l1) =>\n    if (eqA h1 h2)\n    then map_without_repetition eqA f l1\n    else \n      match f h1 with\n      | None => map_without_repetition eqA f l1\n      | Some f_h1 => f_h1 :: (map_without_repetition eqA f l1)\n      end\nend.\n\nLemma prop_map_without_repetition :\n forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (P : B -> Prop) f l,\n  (forall a, In a l -> \n   match f a with \n   | None => True \n   | Some f_a => P f_a\n   end) ->\n   (forall b, In b (map_without_repetition eqA f l) -> P b).\nProof.\ninduction l as [ | a1 l].\ncontradiction.\nassert (In_a1 : In a1 (a1 :: l)).\nleft; trivial.\nintros H; generalize (H a1 In_a1); simpl; destruct l as [ | a2 l].\ndestruct (f a1) as [ f_a1 |  ]; simpl; intuition; subst; trivial.\nelim (eqA a1 a2); intro eq_a1_a2.\nintros; apply IHl; trivial; intros; apply H; right; trivial.\ndestruct (f a1) as [ f_a1 |  ].\nintros P_f_a1 b [eq_f_a1_b | In_b].\nsubst; apply P_f_a1; left; trivial.\napply IHl; trivial; intros; apply H; right; trivial.\nintros; apply IHl; trivial; intros; apply H; right; trivial.\nQed.\n\nLemma exists_map_without_repetition :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (P : B -> Prop) f l,\n  (exists a,  In a l /\\ match f a with \n                        | None => False\n                        | Some f_a => P f_a\n                        end) ->\n  (exists b, In b (map_without_repetition eqA f l) /\\ P b).\nProof.\nintros A B eqA P f.\nassert (In_map_right : forall b a l, \nIn b (map_without_repetition eqA f l) ->\nIn b (map_without_repetition eqA f (a :: l))).\nintros b a1 l In_b; simpl; destruct l as [ | a2 l].\ncontradiction.\nelim (eqA a1 a2); trivial;\ndestruct (f a1) as [ b1 | ]; trivial; intros _; right; trivial.\ninduction l as [ | a1 l].\nintros [a [In_a _]]; contradiction.\nintros [a [[Eq_a_a1 | In_a] P_f_a]].\nsimpl; subst a1; destruct l as [ | a2 l]; intuition.\ndestruct (f a) as [b | ]; [ exists b; intuition | contradiction ].\nelim (eqA a a2).\nintro; subst a; apply IHl; exists a2; intuition.\nintros _; \ndestruct (f a) as [ b | ]; [exists b; intuition | contradiction].\nassert (H: exists b : B, In b (map_without_repetition eqA f l) /\\ P b).\napply IHl; exists a; intuition.\ngeneralize H; intros [b H_b]; exists b; intuition.\nQed.\n\n(** map12_without_repetition is similar to map_without_repetition, but the \napplied function returns two optional results instead of one.\n*)\n\nFixpoint map12_without_repetition (A B : Set) \n  (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (f : A -> option B * option B) (l : list A) {struct l} : list B :=\n    match l with\n    | nil => (nil : list B)\n    | h :: nil => \n      match f h with\n      | (None, None) => nil\n      | (Some f_h1, None) => f_h1 :: nil\n      | (None, Some f_h1) => f_h1 :: nil\n      | (Some f_h1, Some f_h2) => f_h1 :: f_h2 :: nil\n      end\n    | h :: ((h' :: tl) as l1) =>\n    if (eqA h h')\n    then map12_without_repetition eqA f l1\n    else \n      match f h with\n      | (None, None) => map12_without_repetition eqA f l1\n      | (Some f_h1, None) => f_h1 :: (map12_without_repetition eqA f l1)\n      | (None, Some f_h1) => f_h1 :: (map12_without_repetition eqA f l1)\n      | (Some f_h1, Some f_h2) => f_h2 :: f_h1 :: (map12_without_repetition eqA f l1)\n      end\nend.\n\nLemma prop_map12_without_repetition :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (P : B -> Prop) f l,\n  (forall a, In a l -> \n   match f a with \n   | (None, None) => True \n   | (Some f1_a, None) => P f1_a\n   | (None, Some f2_a) => P f2_a\n   | (Some f1_a, Some f2_a) => P f1_a /\\ P f2_a\n   end) ->\n (forall b, In b (map12_without_repetition eqA f l) -> P b).\nProof.\nintros A B eqA P f; induction l as [ | a1 l].\ncontradiction.\nassert (In_a1 : In a1 (a1 :: l)).\nleft; trivial.\nintros H b; \nassert (Hrec : \nforall b : B, In b (map12_without_repetition eqA f l) -> P b).\nintros; apply IHl; trivial; intros; apply H; right; trivial.\nclear IHl; simpl; generalize (H a1 In_a1).\ndestruct l as [ | a2 l].\ndestruct (f a1) as [o1 o2]; \ndestruct o1 as [ f1_a1 | ];\ndestruct o2 as [ f2_a1 | ];\n[ intros [P_f1_a1 P_f2_a1] | intros P_f1_a1 | intros P_f2_a1 | idtac].\nintros [Eq_b_f1_a1 | [Eq_b_f2_a1 | In_b]]; subst; trivial; contradiction.\nintros [Eq_b_f1_a1 | In_b]; subst; trivial; contradiction.\nintros [Eq_b_f2_a1 | In_b]; subst; trivial; contradiction.\ncontradiction.\nelim (eqA a1 a2).\nintros; apply Hrec; trivial.\ndestruct (f a1) as [o1 o2]; \ndestruct o1 as [ f1_a1 | ];\ndestruct o2 as [ f2_a1 | ];\n[ intros _ [P_f1_a1 P_f2_a1] \n| intros _ P_f1_a1 | intros _ P_f2_a1 | intros _].\nintros [Eq_b_f1_a1 | [Eq_b_f2_a1 | In_b]]; \nsubst; trivial; apply Hrec; trivial.\nintros [Eq_b_f1_a1 | In_b]; subst; trivial; apply Hrec; trivial.\nintros [Eq_b_f2_a1 | In_b]; subst; trivial; apply Hrec; trivial.\nintros; apply Hrec; trivial.\nQed.\n\nLemma exists_map12_without_repetition :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (P : B -> Prop) f l,\n  ((exists a, In a l /\\ match f a with \n                        | (None, None) => False\n                        | (None, Some f2_a) => P f2_a\n                        | (Some f1_a, None) => P f1_a\n                        | (Some f1_a, Some f2_a) => P f1_a \\/ P f2_a\n                        end) ->\n  (exists b, In b (map12_without_repetition eqA f l) /\\ P b)).\nProof.\nintros A B eqA P f; induction l as [ | a1 l].\nintros [a [In_a _]]; contradiction.\ndestruct l as [ | a2 l].\nintros [a [[Eq_a_a1 | In_a] P_f_a]]; simpl.\nsubst a; destruct (f a1) as [o1 o2];\ndestruct o1 as [f1_a1 | ];\ndestruct o2 as [f2_a1 | ].\ngeneralize P_f_a; clear P_f_a; intros [P_f1_a1 | P_f2_a1].\nexists f1_a1; intuition.\nexists f2_a1; intuition.\nexists f1_a1; intuition.\nexists f2_a1; intuition.\ncontradiction.\ncontradiction.\nintros [a [[Eq_a_a1 | In_a] P_f_a]].\nsubst a; simpl; elim (eqA a1 a2).\nintro; subst a1; apply IHl; exists a2; intuition.\ndestruct (f a1) as [o1 o2];\ndestruct o1 as [f1_a1 | ];\ndestruct o2 as [f2_a1 | ].\ngeneralize P_f_a; clear P_f_a; intros [P_f1_a1 | P_f2_a1].\nexists f1_a1; intuition.\nexists f2_a1; intuition.\nexists f1_a1; intuition.\nexists f2_a1; intuition.\ncontradiction.\nassert (Hrec : exists b : B, \nIn b (map12_without_repetition eqA f (a2 :: l)) /\\ P b).\napply IHl; exists a; split; trivial.\ngeneralize Hrec; intros [b [In_b P_b]]; exists b; split; trivial.\nsimpl; elim (eqA a1 a2).\nintro; subst a1; trivial.\nintros _; destruct (f a1) as [o1 o2];\ndestruct o1 as [P_f1_a1 | ];\ndestruct o2 as [P_f2_a1 | ].\nright; right; trivial.\nright; trivial.\nright; trivial.\ntrivial.\nQed.\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/rpo/more_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7221193312295782}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Import Le Lt Gt Decidable PeanoNat.\n\nLocal Open Scope nat_scope.\n\nImplicit Types m n x y : nat.\n\nDefinition zerop n : {n = 0} + {0 < n}.\nProof.\n  destruct n; auto with arith.\nDefined.\n\nDefinition lt_eq_lt_dec n m : {n < m} + {n = m} + {m < n}.\nProof.\n  induction n in m |- *; destruct m; auto with arith.\n  destruct (IHn m) as [H|H]; auto with arith.\n  destruct H; auto with arith.\nDefined.\n\nDefinition gt_eq_gt_dec n m : {m > n} + {n = m} + {n > m}.\nProof.\n  now apply lt_eq_lt_dec.\nDefined.\n\nDefinition le_lt_dec n m : {n <= m} + {m < n}.\nProof.\n  induction n in m |- *.\n  - left; auto with arith.\n  - destruct m.\n    + right; auto with arith.\n    + elim (IHn m); [left|right]; auto with arith.\nDefined.\n\nDefinition le_le_S_dec n m : {n <= m} + {S m <= n}.\nProof.\n  exact (le_lt_dec n m).\nDefined.\n\nDefinition le_ge_dec n m : {n <= m} + {n >= m}.\nProof.\n  elim (le_lt_dec n m); auto with arith.\nDefined.\n\nDefinition le_gt_dec n m : {n <= m} + {n > m}.\nProof.\n  exact (le_lt_dec n m).\nDefined.\n\nDefinition le_lt_eq_dec n m : n <= m -> {n < m} + {n = m}.\nProof.\n  intros; destruct (lt_eq_lt_dec n m); auto with arith.\n  intros; absurd (m < n); auto with arith.\nDefined.\n\nTheorem le_dec n m : {n <= m} + {~ n <= m}.\nProof.\n  destruct (le_gt_dec n m).\n  - now left.\n  - right. now apply gt_not_le.\nDefined.\n\nTheorem lt_dec n m : {n < m} + {~ n < m}.\nProof.\n  apply le_dec.\nDefined.\n\nTheorem gt_dec n m : {n > m} + {~ n > m}.\nProof.\n  apply lt_dec.\nDefined.\n\nTheorem ge_dec n m : {n >= m} + {~ n >= m}.\nProof.\n  apply le_dec.\nDefined.\n\n(** Proofs of decidability *)\n\nTheorem dec_le n m : decidable (n <= m).\nProof.\n  apply Nat.le_decidable.\nQed.\n\nTheorem dec_lt n m : decidable (n < m).\nProof.\n  apply Nat.lt_decidable.\nQed.\n\nTheorem dec_gt n m : decidable (n > m).\nProof.\n  apply Nat.lt_decidable.\nQed.\n\nTheorem dec_ge n m : decidable (n >= m).\nProof.\n  apply Nat.le_decidable.\nQed.\n\nTheorem not_eq n m : n <> m -> n < m \\/ m < n.\nProof.\n  apply Nat.lt_gt_cases.\nQed.\n\nTheorem not_le n m : ~ n <= m -> n > m.\nProof.\n  apply Nat.nle_gt.\nQed.\n\nTheorem not_gt n m : ~ n > m -> n <= m.\nProof.\n  apply Nat.nlt_ge.\nQed.\n\nTheorem not_ge n m : ~ n >= m -> n < m.\nProof.\n  apply Nat.nle_gt.\nQed.\n\nTheorem not_lt n m : ~ n < m -> n >= m.\nProof.\n  apply Nat.nlt_ge.\nQed.\n\n\n(** A ternary comparison function in the spirit of [Z.compare].\n    See now [Nat.compare] and its properties.\n    In scope [nat_scope], the notation for [Nat.compare] is \"?=\" *)\n\nNotation nat_compare := Nat.compare (compat \"8.6\").\n\nNotation nat_compare_spec := Nat.compare_spec (compat \"8.6\").\nNotation nat_compare_eq_iff := Nat.compare_eq_iff (compat \"8.6\").\nNotation nat_compare_S := Nat.compare_succ (only parsing).\n\nLemma nat_compare_lt n m : n<m <-> (n ?= m) = Lt.\nProof.\n symmetry. apply Nat.compare_lt_iff.\nQed.\n\nLemma nat_compare_gt n m : n>m <-> (n ?= m) = Gt.\nProof.\n symmetry. apply Nat.compare_gt_iff.\nQed.\n\nLemma nat_compare_le n m : n<=m <-> (n ?= m) <> Gt.\nProof.\n symmetry. apply Nat.compare_le_iff.\nQed.\n\nLemma nat_compare_ge n m : n>=m <-> (n ?= m) <> Lt.\nProof.\n symmetry. apply Nat.compare_ge_iff.\nQed.\n\n(** Some projections of the above equivalences. *)\n\nLemma nat_compare_eq n m : (n ?= m) = Eq -> n = m.\nProof.\n  apply Nat.compare_eq_iff.\nQed.\n\nLemma nat_compare_Lt_lt n m : (n ?= m) = Lt -> n<m.\nProof.\n  apply Nat.compare_lt_iff.\nQed.\n\nLemma nat_compare_Gt_gt n m : (n ?= m) = Gt -> n>m.\nProof.\n  apply Nat.compare_gt_iff.\nQed.\n\n(** A previous definition of [nat_compare] in terms of [lt_eq_lt_dec].\n    The new version avoids the creation of proof parts. *)\n\nDefinition nat_compare_alt (n m:nat) :=\n  match lt_eq_lt_dec n m with\n    | inleft (left _) => Lt\n    | inleft (right _) => Eq\n    | inright _ => Gt\n  end.\n\nLemma nat_compare_equiv n m : (n ?= m) = nat_compare_alt n m.\nProof.\n  unfold nat_compare_alt; destruct lt_eq_lt_dec as [[|]|].\n  - now apply Nat.compare_lt_iff.\n  - now apply Nat.compare_eq_iff.\n  - now apply Nat.compare_gt_iff.\nQed.\n\n(** A boolean version of [le] over [nat].\n    See now [Nat.leb] and its properties.\n    In scope [nat_scope], the notation for [Nat.leb] is \"<=?\" *)\n\nNotation leb := Nat.leb (only parsing).\n\nNotation leb_iff := Nat.leb_le (only parsing).\n\nLemma leb_iff_conv m n : (n <=? m) = false <-> m < n.\nProof.\n rewrite Nat.leb_nle. apply Nat.nle_gt.\nQed.\n\nLemma leb_correct m n : m <= n -> (m <=? n) = true.\nProof.\n apply Nat.leb_le.\nQed.\n\nLemma leb_complete m n : (m <=? n) = true -> m <= n.\nProof.\n apply Nat.leb_le.\nQed.\n\nLemma leb_correct_conv m n : m < n -> (n <=? m) = false.\nProof.\n apply leb_iff_conv.\nQed.\n\nLemma leb_complete_conv m n : (n <=? m) = false -> m < n.\nProof.\n apply leb_iff_conv.\nQed.\n\nLemma leb_compare n m : (n <=? m) = true <-> (n ?= m) <> Gt.\nProof.\n rewrite Nat.compare_le_iff. apply Nat.leb_le.\nQed.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Arith/Compare_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7220911911908374}}
{"text": "Require Import XR_posreal.\nRequire Import XR_Rmin.\nRequire Import XR_Rmin_Rgt_r.\n\nLocal Open Scope R_scope.\n\nLemma Rmin_stable_in_posreal : forall x y:posreal, R0 < Rmin x y.\nProof.\n  intros x y.\n  destruct x as [ x hx ].\n  destruct y as [ y hy ].\n  simpl.\n  apply Rmin_Rgt_r.\n  split.\n  { exact hx. }\n  { exact hy. }\nQed.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rmin_stable_in_posreal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7220801062108095}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural := plus y (Succ lf1).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj231_coqofml_i2MT4i.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7220800977640801}}
{"text": "(************************************************************************)\n(* Copyright 2007 Milad Niqui                                           *)\n(* This file is distributed under the terms of the                      *)\n(* GNU Lesser General Public License Version 2.1                        *)\n(* A copy of the license can be found at                                *)\n(*                  <http://www.gnu.org/licenses>                       *)\n(************************************************************************)\n\nRequire Import Recdef.\nRequire Import digits.\n\n\n(** We prove the LNP (Least Number Principle) for a decidable property\non [nat*Digits] *)\n\nSection LNP_for_nat_digits.\n\nVariable P:nat -> Digit -> Prop.\n\nVariable P_is_decidable:forall n (d:Digit), {P n d}+{~(P n d)}.\n\nVariable there_is_a_bound:{n:nat& {d:Digit |P n d}}.\n\nLet n_bound:= projS1 there_is_a_bound.\n\nLet n_bound_has_d:= projS2 there_is_a_bound.\n\nLet d_of_n_bound_has_d:= proj1_sig n_bound_has_d.\n\n(**\n<<\n-- the smallest k<=m<=n that has a property p\nlnp_next n k p = if k==n || p k then k\n                 else lnp_next n (k+1) p\n-- the smallest k<=n that has a property p\nlnp_all n p = lnp_next n 0 p\n>>\n*)\n\nLemma le_neq_S:forall m n, le m n-> ~ n=m -> le (S m) n.\nProof.\n intros; omega.\nQed.\n\nFunction f_LNP_dec_next (m:nat) (Hm:le m n_bound) {measure (fun (x:nat)=>(minus n_bound x)) m} : nat * Digit :=\n         match Peano_dec.eq_nat_dec n_bound m with\n         | left _ =>  (n_bound, d_of_n_bound_has_d)\n         | right Hneq => if P_is_decidable m LL then (m, LL)\n                         else if P_is_decidable m RR then (m, RR)\n                              else if P_is_decidable m MM then (m, MM) \n                              else f_LNP_dec_next (S m) (le_neq_S _ _ Hm Hneq)\n         end.\nProof.\n intros; omega.\nQed.\n\n\nDefinition f_LNP_dec_all : (nat*Digit) := f_LNP_dec_next O (le_O_n _).\n\nLemma result_f_LNP_dec_next_has_property:forall m (Hm:le m n_bound), let (n,d):=f_LNP_dec_next m Hm  in P n d.\nProof.\n intros m Hm.\n remember (f_LNP_dec_next m Hm) as nd; destruct nd.\n functional induction (f_LNP_dec_next m Hm); [ | | | |apply IHp; assumption];\n  assert (H_eq:=f_equal (@fst nat Digit) Heqnd); simpl in H_eq; rewrite H_eq; clear H_eq;\n  assert (H_eq:=f_equal (@snd nat Digit) Heqnd); simpl in H_eq; rewrite H_eq; trivial.\n  exact (proj2_sig n_bound_has_d)...\nQed.\n\nLemma result_f_LNP_dec_all_has_property: P (fst f_LNP_dec_all) (snd f_LNP_dec_all).\nProof.\n unfold f_LNP_dec_all. \n generalize (result_f_LNP_dec_next_has_property O (le_O_n n_bound)).\n destruct (f_LNP_dec_next 0 (le_O_n n_bound)).\n trivial.\nQed.   \n\nLemma result_f_LNP_le_bound: forall m (Hm:le m n_bound), (fst (f_LNP_dec_next m Hm) <= n_bound)%nat.\nProof.\n intros m Hm.\n functional induction (f_LNP_dec_next m Hm); simpl; trivial.\nQed.\n\nLemma result_f_LNP_dec_next_minimal_property: forall m p (Hm:le m n_bound) (d : Digit), \n  (m<=p)%nat -> (p< fst (f_LNP_dec_next m Hm))%nat -> ~ P p d.\nProof.\n intros m p Hm d Hp1 Hp2.\n assert (Hnbound:=le_not_lt _ _ (result_f_LNP_le_bound m Hm)).\n functional induction (f_LNP_dec_next m Hm); simpl.\n  intros _; apply Hnbound; apply le_lt_trans with p; trivial; rewrite <- _x; assumption...\n  intros _; simpl in Hp2; apply (lt_irrefl m); apply le_lt_trans with p; assumption...\n  intros _; simpl in Hp2; apply (lt_irrefl m); apply le_lt_trans with p; assumption...\n  intros _; simpl in Hp2; apply (lt_irrefl m); apply le_lt_trans with p; assumption...\n  destruct (le_lt_eq_dec _ _ Hp1) as [Hp3|Hp3]. \n   assert (Hp4:=lt_le_S _ _ Hp3); apply (IHp0 Hp4 Hp2 Hnbound).\n   rewrite <- Hp3; destruct d; assumption.\nQed.\n\nLemma result_f_LNP_dec_all_minimal_property: forall (p : nat) (d : Digit), (p < fst f_LNP_dec_all)%nat -> ~ P p d.\nProof.\n unfold f_LNP_dec_all. \n intros p d Hp.\n apply (result_f_LNP_dec_next_minimal_property O) with (le_O_n n_bound); trivial; apply le_O_n.  \nQed.\n\nLemma LNP_sigS_nat_Digit: {n:nat& {d:Digit | P n d/\\ forall m d, (lt m n) -> ~(P m d)}}.\nProof.\n remember f_LNP_dec_all as nd.\n exists (fst nd); exists (snd nd); split. \n   subst nd; apply result_f_LNP_dec_all_has_property...\n   intros m d Hm; subst nd; apply result_f_LNP_dec_all_minimal_property; assumption...\nQed.\n\nEnd LNP_for_nat_digits.\n", "meta": {"author": "coq-contribs", "repo": "coinductive-reals", "sha": "e1b67f1c3a4d23b2819e9977492728d3743abeec", "save_path": "github-repos/coq/coq-contribs-coinductive-reals", "path": "github-repos/coq/coq-contribs-coinductive-reals/coinductive-reals-e1b67f1c3a4d23b2819e9977492728d3743abeec/LNP_Digit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7220800955926038}}
{"text": "From Coq Require Import Arith ZArith Lia.\n\nInductive BoolSpecSet (P Q : Prop) : bool -> Set :=\n    BoolSpecT : P -> BoolSpecSet P Q true | BoolSpecF : Q -> BoolSpecSet P Q false.\n\nLemma leb_spec_Set : forall x y : nat, BoolSpecSet (x <= y) (y < x) (x <=? y).\nProof.\n  intros.\n  destruct (Nat.leb_spec0 x y).\n  now constructor.\n  constructor. now lia.\nQed.\n\nLemma nat_rev_ind (max : nat) :\n  forall (P : nat -> Prop),\n    (forall n, n >= max -> P n) ->\n    (forall n, n < max -> P (S n) -> P n) ->\n    forall n, P n.\nProof.\n  intros P hmax hS.\n  assert (h : forall n, P (max - n)).\n  { intros n. induction n.\n    - apply hmax. lia.\n    - destruct (Nat.leb_spec0 max n).\n      + replace (max - S n) with 0 by lia.\n        replace (max - n) with 0 in IHn by lia.\n        assumption.\n      + replace (max - n) with (S (max - S n)) in IHn by lia.\n        apply hS.\n        * lia.\n        * assumption.\n  }\n  intro n.\n  destruct (Nat.leb_spec0 max n).\n  - apply hmax. lia.\n  - replace n with (max - (max - n)) by lia. apply h.\nQed.\n\nLemma strong_nat_ind :\n  forall (P : nat -> Prop),\n    (forall n, (forall m, m < n -> P m) -> P n) ->\n    forall n, P n.\nProof.\n  intros P h n.\n  assert (forall m, m < n -> P m).\n  { induction n ; intros m hh.\n    - lia.\n    - destruct (Nat.eqb_spec n m).\n      + subst. eapply h. assumption.\n      + eapply IHn. lia.\n  }\n  eapply h. assumption.\nQed.\n\nLemma Z_of_pos_alt p : Z.of_nat (Pos.to_nat p) = Z.pos p.\nProof.\n  induction p using Pos.peano_ind.\n  rewrite Pos2Nat.inj_1. reflexivity.\n  rewrite Pos2Nat.inj_succ. cbn. f_equal. lia.\nQed.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/utils/theories/MCArith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7220530382483733}}
{"text": "Add LoadPath \"Tools\" as Tools.\n\nFrom mathcomp Require Import ssreflect.\nRequire Import Tools.MySum.\n\nInductive Parity :=\n  | ON : Parity\n  | OFF : Parity.\n\nDefinition ParityXOR (x y : Parity) := match x with\n  | ON => match y with\n    | ON => OFF\n    | OFF => ON\n  end\n  | OFF => match y with\n    | ON => ON\n    | OFF => OFF\n  end\nend.\n\nLemma ParityXOR_comm : forall (x y : Parity), ParityXOR x y = ParityXOR y x.\nProof.\nelim.\nelim.\nreflexivity.\nreflexivity.\nelim.\nreflexivity.\nreflexivity.\nQed.\n\nLemma ParityXOR_O_r : forall (x : Parity), ParityXOR x OFF = x.\nProof.\nelim.\nreflexivity.\nreflexivity.\nQed.\n\nLemma ParityXOR_assoc : forall (x y z : Parity), ParityXOR (ParityXOR x y) z = ParityXOR x (ParityXOR y z).\nProof.\nelim.\nelim.\nelim.\nreflexivity.\nreflexivity.\nelim.\nreflexivity.\nreflexivity.\nelim.\nelim.\nreflexivity.\nreflexivity.\nelim.\nreflexivity.\nreflexivity.\nQed.\n\nDefinition ParityXORCM := mkCommutativeMonoid Parity OFF ParityXOR ParityXOR_comm ParityXOR_O_r ParityXOR_assoc.\n", "meta": {"author": "itleigns", "repo": "CoqLibrary", "sha": "de210b755ab010e835e3777b9b47351972bbb577", "save_path": "github-repos/coq/itleigns-CoqLibrary", "path": "github-repos/coq/itleigns-CoqLibrary/CoqLibrary-de210b755ab010e835e3777b9b47351972bbb577/BasicNotation/Parity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7220530374641408}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** The type [nat] of Peano natural numbers (built from [O] and [S])\n    is defined in [Datatypes.v] *)\n\n(** This module defines the following operations on natural numbers :\n    - predecessor [pred]\n    - addition [plus]\n    - multiplication [mult]\n    - less or equal order [le]\n    - less [lt]\n    - greater or equal [ge]\n    - greater [gt]\n\n   It states various lemmas and theorems about natural numbers,\n   including Peano's axioms of arithmetic (in Coq, these are provable).\n   Case analysis on [nat] and induction on [nat * nat] are provided too\n *)\n\nRequire Import Notations.\nRequire Import Datatypes.\nRequire Import Logic.\nRequire Coq.Init.Nat.\n\nOpen Scope nat_scope.\n\nDefinition eq_S := f_equal S.\nDefinition f_equal_nat := f_equal (A:=nat).\n\nHint Resolve f_equal_nat: core.\n\n(** The predecessor function *)\n\nNotation pred := Nat.pred (only parsing).\n\nDefinition f_equal_pred := f_equal pred.\n\nTheorem pred_Sn : forall n:nat, n = pred (S n).\nProof.\n  simpl; reflexivity.\nQed.\n\n(** Injectivity of successor *)\n\nDefinition eq_add_S n m (H: S n = S m): n = m := f_equal pred H.\nHint Immediate eq_add_S: core.\n\nTheorem not_eq_S : forall n m:nat, n <> m -> S n <> S m.\nProof.\n  red; auto.\nQed.\nHint Resolve not_eq_S: core.\n\nDefinition IsSucc (n:nat) : Prop :=\n  match n with\n  | O => False\n  | S p => True\n  end.\n\n(** Zero is not the successor of a number *)\n\nTheorem O_S : forall n:nat, 0 <> S n.\nProof.\n  discriminate.\nQed.\nHint Resolve O_S: core.\n\nTheorem n_Sn : forall n:nat, n <> S n.\nProof.\n  induction n; auto.\nQed.\nHint Resolve n_Sn: core.\n\n(** Addition *)\n\nNotation plus := Nat.add (only parsing).\nInfix \"+\" := Nat.add : nat_scope.\n\nDefinition f_equal2_plus := f_equal2 plus.\nDefinition f_equal2_nat := f_equal2 (A1:=nat) (A2:=nat). \nHint Resolve f_equal2_nat: core.\n\nLemma plus_n_O : forall n:nat, n = n + 0.\nProof.\n  induction n; simpl; auto.\nQed.\n\nRemove Hints eq_refl : core.\nHint Resolve plus_n_O eq_refl: core.  (* We want eq_refl to have higher priority than plus_n_O *)\n\nLemma plus_O_n : forall n:nat, 0 + n = n.\nProof.\n  reflexivity.\nQed.\n\nLemma plus_n_Sm : forall n m:nat, S (n + m) = n + S m.\nProof.\n  intros n m; induction n; simpl; auto.\nQed.\nHint Resolve plus_n_Sm: core.\n\nLemma plus_Sn_m : forall n m:nat, S n + m = S (n + m).\nProof.\n  reflexivity.\nQed.\n\n(** Standard associated names *)\n\nNotation plus_0_r_reverse := plus_n_O (only parsing).\nNotation plus_succ_r_reverse := plus_n_Sm (only parsing).\n\n(** Multiplication *)\n\nNotation mult := Nat.mul (only parsing).\nInfix \"*\" := Nat.mul : nat_scope.\n\nDefinition f_equal2_mult := f_equal2 mult.\nHint Resolve f_equal2_mult: core.\n\nLemma mult_n_O : forall n:nat, 0 = n * 0.\nProof.\n  induction n; simpl; auto.\nQed.\nHint Resolve mult_n_O: core.\n\nLemma mult_n_Sm : forall n m:nat, n * m + n = n * S m.\nProof.\n  intros; induction n as [| p H]; simpl; auto.\n  destruct H; rewrite <- plus_n_Sm; apply eq_S.\n  pattern m at 1 3; elim m; simpl; auto.\nQed.\nHint Resolve mult_n_Sm: core.\n\n(** Standard associated names *)\n\nNotation mult_0_r_reverse := mult_n_O (only parsing).\nNotation mult_succ_r_reverse := mult_n_Sm (only parsing).\n\n(** Truncated subtraction: [m-n] is [0] if [n>=m] *)\n\nNotation minus := Nat.sub (only parsing).\nInfix \"-\" := Nat.sub : nat_scope.\n\n(** Definition of the usual orders, the basic properties of [le] and [lt]\n    can be found in files Le and Lt *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : n <= n\n  | le_S : forall m:nat, n <= m -> n <= S m\n\nwhere \"n <= m\" := (le n m) : nat_scope.\n\nHint Constructors le: core.\n(*i equivalent to : \"Hints Resolve le_n le_S : core.\" i*)\n\nDefinition lt (n m:nat) := S n <= m.\nHint Unfold lt: core.\n\nInfix \"<\" := lt : nat_scope.\n\nDefinition ge (n m:nat) := m <= n.\nHint Unfold ge: core.\n\nInfix \">=\" := ge : nat_scope.\n\nDefinition gt (n m:nat) := m < n.\nHint Unfold gt: core.\n\nInfix \">\" := gt : nat_scope.\n\nNotation \"x <= y <= z\" := (x <= y /\\ y <= z) : nat_scope.\nNotation \"x <= y < z\" := (x <= y /\\ y < z) : nat_scope.\nNotation \"x < y < z\" := (x < y /\\ y < z) : nat_scope.\nNotation \"x < y <= z\" := (x < y /\\ y <= z) : nat_scope.\n\nTheorem le_pred : forall n m, n <= m -> pred n <= pred m.\nProof.\ninduction 1; auto. destruct m; simpl; auto.\nQed.\n\nTheorem le_S_n : forall n m, S n <= S m -> n <= m.\nProof.\nintros n m. exact (le_pred (S n) (S m)).\nQed.\n\nTheorem le_0_n : forall n, 0 <= n.\nProof.\n induction n; constructor; trivial.\nQed.\n\nTheorem le_n_S : forall n m, n <= m -> S n <= S m.\nProof.\n induction 1; constructor; trivial.\nQed.\n\n(** Case analysis *)\n\nTheorem nat_case :\n forall (n:nat) (P:nat -> Prop), P 0 -> (forall m:nat, P (S m)) -> P n.\nProof.\n  induction n; auto.\nQed.\n\n(** Principle of double induction *)\n\nTheorem nat_double_ind :\n forall R:nat -> nat -> Prop,\n   (forall n:nat, R 0 n) ->\n   (forall n:nat, R (S n) 0) ->\n   (forall n m:nat, R n m -> R (S n) (S m)) -> forall n m:nat, R n m.\nProof.\n  induction n; auto.\n  destruct m; auto.\nQed.\n\n(** Maximum and minimum : definitions and specifications *)\n\nNotation max := Nat.max (only parsing).\nNotation min := Nat.min (only parsing).\n\nLemma max_l n m : m <= n -> Nat.max n m = n.\nProof.\n revert m; induction n; destruct m; simpl; trivial.\n - inversion 1.\n - intros. apply f_equal, IHn, le_S_n; trivial.\nQed.\n\nLemma max_r n m : n <= m -> Nat.max n m = m.\nProof.\n revert m; induction n; destruct m; simpl; trivial.\n - inversion 1.\n - intros. apply f_equal, IHn, le_S_n; trivial.\nQed.\n\nLemma min_l n m : n <= m -> Nat.min n m = n.\nProof.\n revert m; induction n; destruct m; simpl; trivial.\n - inversion 1.\n - intros. apply f_equal, IHn, le_S_n; trivial.\nQed.\n\nLemma min_r n m : m <= n -> Nat.min n m = m.\nProof.\n revert m; induction n; destruct m; simpl; trivial.\n - inversion 1.\n - intros. apply f_equal, IHn, le_S_n; trivial.\nQed.\n\n\nLemma nat_rect_succ_r {A} (f: A -> A) (x:A) n :\n  nat_rect (fun _ => A) x (fun _ => f) (S n) = nat_rect (fun _ => A) (f x) (fun _ => f) n.\nProof.\n  induction n; intros; simpl; rewrite <- ?IHn; trivial.\nQed.\n\nTheorem nat_rect_plus :\n  forall (n m:nat) {A} (f:A -> A) (x:A),\n    nat_rect (fun _ => A) x (fun _ => f) (n + m) =\n      nat_rect (fun _ => A) (nat_rect (fun _ => A) x (fun _ => f) m) (fun _ => f) n.\nProof.\n  induction n; intros; simpl; rewrite ?IHn; trivial.\nQed.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Init/Peano.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8244619350028205, "lm_q1q2_score": 0.722053035111443}}
{"text": "(* Copyright (c) 2008-2012, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n *   http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import List.\n\nRequire Import CpdtTactics MoreSpecif.\n\nSet Implicit Arguments.\n(* end hide *)\n\n\n(** %\\chapter{Proof by Reflection}% *)\n\n(** The last chapter highlighted a very heuristic approach to proving.  In this chapter, we will study an alternative technique,%\\index{proof by reflection}% _proof by reflection_ %\\cite{reflection}%.  We will write, in Gallina, decision procedures with proofs of correctness, and we will appeal to these procedures in writing very short proofs.  Such a proof is checked by running the decision procedure.  The term _reflection_ applies because we will need to translate Gallina propositions into values of inductive types representing syntax, so that Gallina programs may analyze them, and translating such a term back to the original form is called _reflecting_ it. *)\n\n\n(** * Proving Evenness *)\n\n(** Proving that particular natural number constants are even is certainly something we would rather have happen automatically.  The Ltac-programming techniques that we learned in the last chapter make it easy to implement such a procedure. *)\n\nInductive isEven : nat -> Prop :=\n| Even_O : isEven O\n| Even_SS : forall n, isEven n -> isEven (S (S n)).\n\n(* begin thide *)\nLtac prove_even := repeat constructor.\n(* end thide *)\n\nTheorem even_256 : isEven 256.\n  prove_even.\nQed.\n\nPrint even_256.\n(** %\\vspace{-.15in}% [[\neven_256 = \nEven_SS\n  (Even_SS\n     (Even_SS\n        (Even_SS\n    ]]\n\n    %\\noindent%...and so on.  This procedure always works (at least on machines with infinite resources), but it has a serious drawback, which we see when we print the proof it generates that 256 is even.  The final proof term has length super-linear in the input value.  Coq's implicit arguments mechanism is hiding the values given for parameter [n] of [Even_SS], which is why the proof term only appears linear here.  Also, proof terms are represented internally as syntax trees, with opportunity for sharing of node representations, but in this chapter we will measure proof term size as simple textual length or as the number of nodes in the term's syntax tree, two measures that are approximately equivalent.  Sometimes apparently large proof terms have enough internal sharing that they take up less memory than we expect, but one avoids having to reason about such sharing by ensuring that the size of a sharing-free version of a term is low enough.\n\n    Superlinear evenness proof terms seem like a shame, since we could write a trivial and trustworthy program to verify evenness of constants.  The proof checker could simply call our program where needed.\n\n    It is also unfortunate not to have static typing guarantees that our tactic always behaves appropriately.  Other invocations of similar tactics might fail with dynamic type errors, and we would not know about the bugs behind these errors until we happened to attempt to prove complex enough goals.\n\n    The techniques of proof by reflection address both complaints.  We will be able to write proofs like in the example above with constant size overhead beyond the size of the input, and we will do it with verified decision procedures written in Gallina.\n\n    For this example, we begin by using a type from the [MoreSpecif] module (included in the book source) to write a certified evenness checker. *)\n\n(* begin hide *)\n(* begin thide *)\nDefinition paartial := partial.\n(* end thide *)\n(* end hide *)\n\nPrint partial.\n(** %\\vspace{-.15in}% [[\nInductive partial (P : Prop) : Set :=  Proved : P -> [P] | Uncertain : [P]\n    ]]\n\n    A [partial P] value is an optional proof of [P]. The notation [[P]] stands for [partial P]. *)\n\nLocal Open Scope partial_scope.\n\n(** We bring into scope some notations for the [partial] type.  These overlap with some of the notations we have seen previously for specification types, so they were placed in a separate scope that needs separate opening. *)\n\n(* begin thide *)\nDefinition check_even : forall n : nat, [isEven n].\n  Hint Constructors isEven.\n\n  refine (fix F (n : nat) : [isEven n] :=\n    match n with\n      | 0 => Yes\n      | 1 => No\n      | S (S n') => Reduce (F n')\n    end); auto.\nDefined.\n\n(** The function [check_even] may be viewed as a _verified decision procedure_, because its type guarantees that it never returns %\\coqdocnotation{%#<tt>#Yes#</tt>#%}% for inputs that are not even.\n\n   Now we can use dependent pattern-matching to write a function that performs a surprising feat.  When given a [partial P], this function [partialOut] returns a proof of [P] if the [partial] value contains a proof, and it returns a (useless) proof of [True] otherwise.  From the standpoint of ML and Haskell programming, it seems impossible to write such a type, but it is trivial with a [return] annotation. *)\n\nDefinition partialOut (P : Prop) (x : [P]) :=\n  match x return (match x with\n                    | Proved _ => P\n                    | Uncertain => True\n                  end) with\n    | Proved pf => pf\n    | Uncertain => I\n  end.\n\n(** It may seem strange to define a function like this.  However, it turns out to be very useful in writing a reflective version of our earlier [prove_even] tactic: *)\n\nLtac prove_even_reflective :=\n  match goal with\n    | [ |- isEven ?N] => exact (partialOut (check_even N))\n  end.\n(* end thide *)\n\n(** We identify which natural number we are considering, and we \"prove\" its evenness by pulling the proof out of the appropriate [check_even] call.  Recall that the %\\index{tactics!exact}%[exact] tactic proves a proposition [P] when given a proof term of precisely type [P]. *)\n\nTheorem even_256' : isEven 256.\n  prove_even_reflective.\nQed.\n\nPrint even_256'.\n(** %\\vspace{-.15in}% [[\neven_256' = partialOut (check_even 256)\n     : isEven 256\n    ]]\n\n    We can see a constant wrapper around the object of the proof.  For any even number, this form of proof will suffice.  The size of the proof term is now linear in the number being checked, containing two repetitions of the unary form of that number, one of which is hidden above within the implicit argument to [partialOut].\n\n    What happens if we try the tactic with an odd number? *)\n\nTheorem even_255 : isEven 255.\n  (** %\\vspace{-.275in}%[[\n  prove_even_reflective.\n]]\n\n<<\nUser error: No matching clauses for match goal\n>>\n\n  Thankfully, the tactic fails.  To see more precisely what goes wrong, we can run manually the body of the [match].\n\n  %\\vspace{-.15in}%[[\n  exact (partialOut (check_even 255)).\n]]\n\n<<\n  Error: The term \"partialOut (check_even 255)\" has type\n \"match check_even 255 with\n  | Yes => isEven 255\n  | No => True\n  end\" while it is expected to have type \"isEven 255\"\n>>\n\n  As usual, the type checker performs no reductions to simplify error messages.  If we reduced the first term ourselves, we would see that [check_even 255] reduces to a %\\coqdocnotation{%#<tt>#No#</tt>#%}%, so that the first term is equivalent to [True], which certainly does not unify with [isEven 255]. *)\n\nAbort.\n\n(** Our tactic [prove_even_reflective] is reflective because it performs a proof search process (a trivial one, in this case) wholly within Gallina, where the only use of Ltac is to translate a goal into an appropriate use of [check_even]. *)\n\n\n(** * Reifying the Syntax of a Trivial Tautology Language *)\n\n(** We might also like to have reflective proofs of trivial tautologies like this one: *)\n\nTheorem true_galore : (True /\\ True) -> (True \\/ (True /\\ (True -> True))).\n  tauto.\nQed.\n\n(* begin hide *)\n(* begin thide *)\nDefinition tg := (and_ind, or_introl).\n(* end thide *)\n(* end hide *)\n\nPrint true_galore.\n(** %\\vspace{-.15in}% [[\ntrue_galore = \nfun H : True /\\ True =>\nand_ind (fun _ _ : True => or_introl (True /\\ (True -> True)) I) H\n     : True /\\ True -> True \\/ True /\\ (True -> True)\n    ]]\n\n    As we might expect, the proof that [tauto] builds contains explicit applications of natural deduction rules.  For large formulas, this can add a linear amount of proof size overhead, beyond the size of the input.\n\n   To write a reflective procedure for this class of goals, we will need to get into the actual \"reflection\" part of \"proof by reflection.\"  It is impossible to case-analyze a [Prop] in any way in Gallina.  We must%\\index{reification}% _reify_ [Prop] into some type that we _can_ analyze.  This inductive type is a good candidate: *)\n\n(* begin thide *)\nInductive taut : Set :=\n| TautTrue : taut\n| TautAnd : taut -> taut -> taut\n| TautOr : taut -> taut -> taut\n| TautImp : taut -> taut -> taut.\n\n(** We write a recursive function to _reflect_ this syntax back to [Prop].  Such functions are also called%\\index{interpretation function}% _interpretation functions_, and we have used them in previous examples to give semantics to small programming languages. *)\n\nFixpoint tautDenote (t : taut) : Prop :=\n  match t with\n    | TautTrue => True\n    | TautAnd t1 t2 => tautDenote t1 /\\ tautDenote t2\n    | TautOr t1 t2 => tautDenote t1 \\/ tautDenote t2\n    | TautImp t1 t2 => tautDenote t1 -> tautDenote t2\n  end.\n\n(** It is easy to prove that every formula in the range of [tautDenote] is true. *)\n\nTheorem tautTrue : forall t, tautDenote t.\n  induction t; crush.\nQed.\n\n(** To use [tautTrue] to prove particular formulas, we need to implement the syntax reification process.  A recursive Ltac function does the job. *)\n\nLtac tautReify P :=\n  match P with\n    | True => TautTrue\n    | ?P1 /\\ ?P2 =>\n      let t1 := tautReify P1 in\n      let t2 := tautReify P2 in\n        constr:(TautAnd t1 t2)\n    | ?P1 \\/ ?P2 =>\n      let t1 := tautReify P1 in\n      let t2 := tautReify P2 in\n        constr:(TautOr t1 t2)\n    | ?P1 -> ?P2 =>\n      let t1 := tautReify P1 in\n      let t2 := tautReify P2 in\n        constr:(TautImp t1 t2)\n  end.\n\n(** With [tautReify] available, it is easy to finish our reflective tactic.  We look at the goal formula, reify it, and apply [tautTrue] to the reified formula. *)\n\nLtac obvious :=\n  match goal with\n    | [ |- ?P ] =>\n      let t := tautReify P in\n        exact (tautTrue t)\n  end.\n\n(** We can verify that [obvious] solves our original example, with a proof term that does not mention details of the proof. *)\n(* end thide *)\n\nTheorem true_galore' : (True /\\ True) -> (True \\/ (True /\\ (True -> True))).\n  obvious.\nQed.\n\nPrint true_galore'.\n(** %\\vspace{-.15in}% [[\ntrue_galore' = \ntautTrue\n  (TautImp (TautAnd TautTrue TautTrue)\n     (TautOr TautTrue (TautAnd TautTrue (TautImp TautTrue TautTrue))))\n     : True /\\ True -> True \\/ True /\\ (True -> True)\n    ]]\n\n    It is worth considering how the reflective tactic improves on a pure-Ltac implementation.  The formula reification process is just as ad-hoc as before, so we gain little there.  In general, proofs will be more complicated than formula translation, and the \"generic proof rule\" that we apply here _is_ on much better formal footing than a recursive Ltac function.  The dependent type of the proof guarantees that it \"works\" on any input formula.  This benefit is in addition to the proof-size improvement that we have already seen.\n\n    It may also be worth pointing out that our previous example of evenness testing used a function [partialOut] for sound handling of input goals that the verified decision procedure fails to prove.  Here, we prove that our procedure [tautTrue] (recall that an inductive proof may be viewed as a recursive procedure) is able to prove any goal representable in [taut], so no extra step is necessary. *)\n\n\n(** * A Monoid Expression Simplifier *)\n\n(** Proof by reflection does not require encoding of all of the syntax in a goal.  We can insert \"variables\" in our syntax types to allow injection of arbitrary pieces, even if we cannot apply specialized reasoning to them.  In this section, we explore that possibility by writing a tactic for normalizing monoid equations. *)\n\nSection monoid.\n  Variable A : Set.\n  Variable e : A.\n  Variable f : A -> A -> A.\n\n  Infix \"+\" := f.\n\n  Hypothesis assoc : forall a b c, (a + b) + c = a + (b + c).\n  Hypothesis identl : forall a, e + a = a.\n  Hypothesis identr : forall a, a + e = a.\n\n  (** We add variables and hypotheses characterizing an arbitrary instance of the algebraic structure of monoids.  We have an associative binary operator and an identity element for it.\n\n     It is easy to define an expression tree type for monoid expressions.  A [Var] constructor is a \"catch-all\" case for subexpressions that we cannot model.  These subexpressions could be actual Gallina variables, or they could just use functions that our tactic is unable to understand. *)\n\n(* begin thide *)\n  Inductive mexp : Set :=\n  | Ident : mexp\n  | Var : A -> mexp\n  | Op : mexp -> mexp -> mexp.\n\n  (** Next, we write an interpretation function. *)\n\n  Fixpoint mdenote (me : mexp) : A :=\n    match me with\n      | Ident => e\n      | Var v => v\n      | Op me1 me2 => mdenote me1 + mdenote me2\n    end.\n\n  (** We will normalize expressions by flattening them into lists, via associativity, so it is helpful to have a denotation function for lists of monoid values. *)\n\n  Fixpoint mldenote (ls : list A) : A :=\n    match ls with\n      | nil => e\n      | x :: ls' => x + mldenote ls'\n    end.\n\n  (** The flattening function itself is easy to implement. *)\n\n  Fixpoint flatten (me : mexp) : list A :=\n    match me with\n      | Ident => nil\n      | Var x => x :: nil\n      | Op me1 me2 => flatten me1 ++ flatten me2\n    end.\n\n  (** This function has a straightforward correctness proof in terms of our [denote] functions. *)\n\n  Lemma flatten_correct' : forall ml2 ml1,\n    mldenote ml1 + mldenote ml2 = mldenote (ml1 ++ ml2).\n    induction ml1; crush.\n  Qed.\n\n  Theorem flatten_correct : forall me, mdenote me = mldenote (flatten me).\n    Hint Resolve flatten_correct'.\n\n    induction me; crush.\n  Qed.\n\n  (** Now it is easy to prove a theorem that will be the main tool behind our simplification tactic. *)\n\n  Theorem monoid_reflect : forall me1 me2,\n    mldenote (flatten me1) = mldenote (flatten me2)\n    -> mdenote me1 = mdenote me2.\n    intros; repeat rewrite flatten_correct; assumption.\n  Qed.\n\n  (** We implement reification into the [mexp] type. *)\n\n  Ltac reify me :=\n    match me with\n      | e => Ident\n      | ?me1 + ?me2 =>\n        let r1 := reify me1 in\n        let r2 := reify me2 in\n          constr:(Op r1 r2)\n      | _ => constr:(Var me)\n    end.\n\n  (** The final [monoid] tactic works on goals that equate two monoid terms.  We reify each and change the goal to refer to the reified versions, finishing off by applying [monoid_reflect] and simplifying uses of [mldenote].  Recall that the %\\index{tactics!change}%[change] tactic replaces a conclusion formula with another that is definitionally equal to it. *)\n\n  Ltac monoid :=\n    match goal with\n      | [ |- ?me1 = ?me2 ] =>\n        let r1 := reify me1 in\n        let r2 := reify me2 in\n          change (mdenote r1 = mdenote r2);\n            apply monoid_reflect; simpl\n    end.\n\n  (** We can make short work of theorems like this one: *)\n\n(* end thide *)\n\n  Theorem t1 : forall a b c d, a + b + c + d = a + (b + c) + d.\n    intros; monoid.\n    (** [[\n  ============================\n   a + (b + (c + (d + e))) = a + (b + (c + (d + e)))\n \n        ]]\n\n        Our tactic has canonicalized both sides of the equality, such that we can finish the proof by reflexivity. *)\n\n    reflexivity.\n  Qed.\n\n  (** It is interesting to look at the form of the proof. *)\n\n  Print t1.\n  (** %\\vspace{-.15in}% [[\nt1 = \nfun a b c d : A =>\nmonoid_reflect (Op (Op (Op (Var a) (Var b)) (Var c)) (Var d))\n  (Op (Op (Var a) (Op (Var b) (Var c))) (Var d))\n  (eq_refl (a + (b + (c + (d + e)))))\n     : forall a b c d : A, a + b + c + d = a + (b + c) + d\n      ]]\n\n      The proof term contains only restatements of the equality operands in reified form, followed by a use of reflexivity on the shared canonical form. *)\n\nEnd monoid.\n\n(** Extensions of this basic approach are used in the implementations of the %\\index{tactics!ring}%[ring] and %\\index{tactics!field}%[field] tactics that come packaged with Coq. *)\n\n\n(** * A Smarter Tautology Solver *)\n\n(** Now we are ready to revisit our earlier tautology solver example.  We want to broaden the scope of the tactic to include formulas whose truth is not syntactically apparent.  We will want to allow injection of arbitrary formulas, like we allowed arbitrary monoid expressions in the last example.  Since we are working in a richer theory, it is important to be able to use equalities between different injected formulas.  For instance, we cannot prove [P -> P] by translating the formula into a value like [Imp (Var P) (Var P)], because a Gallina function has no way of comparing the two [P]s for equality.\n\n   To arrive at a nice implementation satisfying these criteria, we introduce the %\\index{tactics!quote}%[quote] tactic and its associated library. *)\n\nRequire Import Quote.\n\n(* begin thide *)\nInductive formula : Set :=\n| Atomic : index -> formula\n| Truth : formula\n| Falsehood : formula\n| And : formula -> formula -> formula\n| Or : formula -> formula -> formula\n| Imp : formula -> formula -> formula.\n(* end thide *)\n\n(** The type %\\index{Gallina terms!index}%[index] comes from the [Quote] library and represents a countable variable type.  The rest of [formula]'s definition should be old hat by now.\n\n   The [quote] tactic will implement injection from [Prop] into [formula] for us, but it is not quite as smart as we might like.  In particular, it wants to treat function types specially, so it gets confused if function types are part of the structure we want to encode syntactically.  To trick [quote] into not noticing our uses of function types to express logical implication, we will need to declare a wrapper definition for implication, as we did in the last chapter. *)\n\nDefinition imp (P1 P2 : Prop) := P1 -> P2.\nInfix \"-->\" := imp (no associativity, at level 95).\n\n(** Now we can define our denotation function. *)\n\nDefinition asgn := varmap Prop.\n\n(* begin thide *)\nFixpoint formulaDenote (atomics : asgn) (f : formula) : Prop :=\n  match f with\n    | Atomic v => varmap_find False v atomics\n    | Truth => True\n    | Falsehood => False\n    | And f1 f2 => formulaDenote atomics f1 /\\ formulaDenote atomics f2\n    | Or f1 f2 => formulaDenote atomics f1 \\/ formulaDenote atomics f2\n    | Imp f1 f2 => formulaDenote atomics f1 --> formulaDenote atomics f2\n  end.\n(* end thide *)\n\n(** The %\\index{Gallina terms!varmap}%[varmap] type family implements maps from [index] values.  In this case, we define an assignment as a map from variables to [Prop]s.  Our interpretation function [formulaDenote] works with an assignment, and we use the [varmap_find] function to consult the assignment in the [Atomic] case.  The first argument to [varmap_find] is a default value, in case the variable is not found. *)\n\nSection my_tauto.\n  Variable atomics : asgn.\n\n  Definition holds (v : index) := varmap_find False v atomics.\n\n  (** We define some shorthand for a particular variable being true, and now we are ready to define some helpful functions based on the [ListSet] module of the standard library, which (unsurprisingly) presents a view of lists as sets. *)\n\n  Require Import ListSet.\n\n  Definition index_eq : forall x y : index, {x = y} + {x <> y}.\n    decide equality.\n  Defined.\n\n  Definition add (s : set index) (v : index) := set_add index_eq v s.\n\n  Definition In_dec : forall v (s : set index), {In v s} + {~ In v s}.\n    Local Open Scope specif_scope.\n\n    intro; refine (fix F (s : set index) : {In v s} + {~ In v s} :=\n      match s with\n        | nil => No\n        | v' :: s' => index_eq v' v || F s'\n      end); crush.\n  Defined.\n\n  (** We define what it means for all members of an index set to represent true propositions, and we prove some lemmas about this notion. *)\n\n  Fixpoint allTrue (s : set index) : Prop :=\n    match s with\n      | nil => True\n      | v :: s' => holds v /\\ allTrue s'\n    end.\n\n  Theorem allTrue_add : forall v s,\n    allTrue s\n    -> holds v\n    -> allTrue (add s v).\n    induction s; crush;\n      match goal with\n        | [ |- context[if ?E then _ else _] ] => destruct E\n      end; crush.\n  Qed.\n\n  Theorem allTrue_In : forall v s,\n    allTrue s\n    -> set_In v s\n    -> varmap_find False v atomics.\n    induction s; crush.\n  Qed.\n\n  Hint Resolve allTrue_add allTrue_In.\n\n  Local Open Scope partial_scope.\n\n  (** Now we can write a function [forward] that implements deconstruction of hypotheses, expanding a compound formula into a set of sets of atomic formulas covering all possible cases introduced with use of [Or].  To handle consideration of multiple cases, the function takes in a continuation argument, which will be called once for each case.\n\n     The [forward] function has a dependent type, in the style of Chapter 6, guaranteeing correctness.  The arguments to [forward] are a goal formula [f], a set [known] of atomic formulas that we may assume are true, a hypothesis formula [hyp], and a success continuation [cont] that we call when we have extended [known] to hold new truths implied by [hyp]. *)\n\n  Definition forward : forall (f : formula) (known : set index) (hyp : formula)\n    (cont : forall known', [allTrue known' -> formulaDenote atomics f]),\n    [allTrue known -> formulaDenote atomics hyp -> formulaDenote atomics f].\n    refine (fix F (f : formula) (known : set index) (hyp : formula)\n      (cont : forall known', [allTrue known' -> formulaDenote atomics f])\n      : [allTrue known -> formulaDenote atomics hyp -> formulaDenote atomics f] :=\n      match hyp with\n        | Atomic v => Reduce (cont (add known v))\n        | Truth => Reduce (cont known)\n        | Falsehood => Yes\n        | And h1 h2 =>\n          Reduce (F (Imp h2 f) known h1 (fun known' =>\n            Reduce (F f known' h2 cont)))\n        | Or h1 h2 => F f known h1 cont && F f known h2 cont\n        | Imp _ _ => Reduce (cont known)\n      end); crush.\n  Defined.\n\n  (** A [backward] function implements analysis of the final goal.  It calls [forward] to handle implications. *)\n\n(* begin thide *)\n  Definition backward : forall (known : set index) (f : formula),\n    [allTrue known -> formulaDenote atomics f].\n    refine (fix F (known : set index) (f : formula)\n      : [allTrue known -> formulaDenote atomics f] :=\n      match f with\n        | Atomic v => Reduce (In_dec v known)\n        | Truth => Yes\n        | Falsehood => No\n        | And f1 f2 => F known f1 && F known f2\n        | Or f1 f2 => F known f1 || F known f2\n        | Imp f1 f2 => forward f2 known f1 (fun known' => F known' f2)\n      end); crush; eauto.\n  Defined.\n(* end thide *)\n\n  (** A simple wrapper around [backward] gives us the usual type of a partial decision procedure. *)\n\n  Definition my_tauto : forall f : formula, [formulaDenote atomics f].\n(* begin thide *)\n    intro; refine (Reduce (backward nil f)); crush.\n  Defined.\n(* end thide *)\nEnd my_tauto.\n\n(** Our final tactic implementation is now fairly straightforward.  First, we [intro] all quantifiers that do not bind [Prop]s.  Then we call the [quote] tactic, which implements the reification for us.  Finally, we are able to construct an exact proof via [partialOut] and the [my_tauto] Gallina function. *)\n\nLtac my_tauto :=\n  repeat match goal with\n           | [ |- forall x : ?P, _ ] =>\n             match type of P with\n               | Prop => fail 1\n               | _ => intro\n             end\n         end;\n  quote formulaDenote;\n  match goal with\n    | [ |- formulaDenote ?m ?f ] => exact (partialOut (my_tauto m f))\n  end.\n(* end thide *)\n\n(** A few examples demonstrate how the tactic works. *)\n\nTheorem mt1 : True.\n  my_tauto.\nQed.\n\nPrint mt1.\n(** %\\vspace{-.15in}% [[\nmt1 = partialOut (my_tauto (Empty_vm Prop) Truth)\n     : True\n    ]]\n\n    We see [my_tauto] applied with an empty [varmap], since every subformula is handled by [formulaDenote]. *)\n\nTheorem mt2 : forall x y : nat, x = y --> x = y.\n  my_tauto.\nQed.\n\n(* begin hide *)\n(* begin thide *)\nDefinition nvm := (Node_vm, Empty_vm, End_idx, Left_idx, Right_idx).\n(* end thide *)\n(* end hide *)\n\nPrint mt2.\n(** %\\vspace{-.15in}% [[\nmt2 = \nfun x y : nat =>\npartialOut\n  (my_tauto (Node_vm (x = y) (Empty_vm Prop) (Empty_vm Prop))\n     (Imp (Atomic End_idx) (Atomic End_idx)))\n     : forall x y : nat, x = y --> x = y\n    ]]\n\n    Crucially, both instances of [x = y] are represented with the same index, [End_idx].  The value of this index only needs to appear once in the [varmap], whose form reveals that [varmap]s are represented as binary trees, where [index] values denote paths from tree roots to leaves. *)\n\nTheorem mt3 : forall x y z,\n  (x < y /\\ y > z) \\/ (y > z /\\ x < S y)\n  --> y > z /\\ (x < y \\/ x < S y).\n  my_tauto.\nQed.\n\nPrint mt3.\n(** %\\vspace{-.15in}% [[\nfun x y z : nat =>\npartialOut\n  (my_tauto\n     (Node_vm (x < S y) (Node_vm (x < y) (Empty_vm Prop) (Empty_vm Prop))\n        (Node_vm (y > z) (Empty_vm Prop) (Empty_vm Prop)))\n     (Imp\n        (Or (And (Atomic (Left_idx End_idx)) (Atomic (Right_idx End_idx)))\n           (And (Atomic (Right_idx End_idx)) (Atomic End_idx)))\n        (And (Atomic (Right_idx End_idx))\n           (Or (Atomic (Left_idx End_idx)) (Atomic End_idx)))))\n     : forall x y z : nat,\n       x < y /\\ y > z \\/ y > z /\\ x < S y --> y > z /\\ (x < y \\/ x < S y)\n    ]]\n\n    Our goal contained three distinct atomic formulas, and we see that a three-element [varmap] is generated.\n\n    It can be interesting to observe differences between the level of repetition in proof terms generated by [my_tauto] and [tauto] for especially trivial theorems. *)\n\nTheorem mt4 : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False --> False.\n  my_tauto.\nQed.\n\nPrint mt4.\n(** %\\vspace{-.15in}% [[\nmt4 = \npartialOut\n  (my_tauto (Empty_vm Prop)\n     (Imp\n        (And Truth\n           (And Truth\n              (And Truth (And Truth (And Truth (And Truth Falsehood))))))\n        Falsehood))\n     : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False --> False\n    ]]\n    *)\n\nTheorem mt4' : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False -> False.\n  tauto.\nQed.\n\n(* begin hide *)\n(* begin thide *)\nDefinition fi := False_ind.\n(* end thide *)\n(* end hide *)\n\nPrint mt4'.\n(** %\\vspace{-.15in}% [[\nmt4' = \nfun H : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False =>\nand_ind\n  (fun (_ : True) (H1 : True /\\ True /\\ True /\\ True /\\ True /\\ False) =>\n   and_ind\n     (fun (_ : True) (H3 : True /\\ True /\\ True /\\ True /\\ False) =>\n      and_ind\n        (fun (_ : True) (H5 : True /\\ True /\\ True /\\ False) =>\n         and_ind\n           (fun (_ : True) (H7 : True /\\ True /\\ False) =>\n            and_ind\n              (fun (_ : True) (H9 : True /\\ False) =>\n               and_ind (fun (_ : True) (H11 : False) => False_ind False H11)\n                 H9) H7) H5) H3) H1) H\n     : True /\\ True /\\ True /\\ True /\\ True /\\ True /\\ False -> False\n    ]]\n\nThe traditional [tauto] tactic introduces a quadratic blow-up in the size of the proof term, whereas proofs produced by [my_tauto] always have linear size. *)\n\n(** ** Manual Reification of Terms with Variables *)\n\n(* begin thide *)\n(** The action of the [quote] tactic above may seem like magic.  Somehow it performs equality comparison between subterms of arbitrary types, so that these subterms may be represented with the same reified variable.  While [quote] is implemented in OCaml, we can code the reification process completely in Ltac, as well.  To make our job simpler, we will represent variables as [nat]s, indexing into a simple list of variable values that may be referenced.\n\n   Step one of the process is to crawl over a term, building a duplicate-free list of all values that appear in positions we will encode as variables.  A useful helper function adds an element to a list, preventing duplicates.  Note how we use Ltac pattern matching to implement an equality test on Gallina terms; this is simple syntactic equality, not even the richer definitional equality.  We also represent lists as nested tuples, to allow different list elements to have different Gallina types. *)\n\nLtac inList x xs :=\n  match xs with\n    | tt => false\n    | (x, _) => true\n    | (_, ?xs') => inList x xs'\n  end.\n\nLtac addToList x xs :=\n  let b := inList x xs in\n    match b with\n      | true => xs\n      | false => constr:(x, xs)\n    end.\n\n(** Now we can write our recursive function to calculate the list of variable values we will want to use to represent a term. *)\n\nLtac allVars xs e :=\n  match e with\n    | True => xs\n    | False => xs\n    | ?e1 /\\ ?e2 =>\n      let xs := allVars xs e1 in\n        allVars xs e2\n    | ?e1 \\/ ?e2 =>\n      let xs := allVars xs e1 in\n        allVars xs e2\n    | ?e1 -> ?e2 =>\n      let xs := allVars xs e1 in\n        allVars xs e2\n    | _ => addToList e xs\n  end.\n\n(** We will also need a way to map a value to its position in a list. *)\n\nLtac lookup x xs :=\n  match xs with\n    | (x, _) => O\n    | (_, ?xs') =>\n      let n := lookup x xs' in\n        constr:(S n)\n  end.\n\n(** The next building block is a procedure for reifying a term, given a list of all allowed variable values.  We are free to make this procedure partial, where tactic failure may be triggered upon attempting to reify a term containing subterms not included in the list of variables.  The type of the output term is a copy of [formula] where [index] is replaced by [nat], in the type of the constructor for atomic formulas. *)\n\nInductive formula' : Set :=\n| Atomic' : nat -> formula'\n| Truth' : formula'\n| Falsehood' : formula'\n| And' : formula' -> formula' -> formula'\n| Or' : formula' -> formula' -> formula'\n| Imp' : formula' -> formula' -> formula'.\n\n(** Note that, when we write our own Ltac procedure, we can work directly with the normal [->] operator, rather than needing to introduce a wrapper for it. *)\n\nLtac reifyTerm xs e :=\n  match e with\n    | True => constr:Truth'\n    | False => constr:Falsehood'\n    | ?e1 /\\ ?e2 =>\n      let p1 := reifyTerm xs e1 in\n      let p2 := reifyTerm xs e2 in\n        constr:(And' p1 p2)\n    | ?e1 \\/ ?e2 =>\n      let p1 := reifyTerm xs e1 in\n      let p2 := reifyTerm xs e2 in\n        constr:(Or' p1 p2)\n    | ?e1 -> ?e2 =>\n      let p1 := reifyTerm xs e1 in\n      let p2 := reifyTerm xs e2 in\n        constr:(Imp' p1 p2)\n    | _ =>\n      let n := lookup e xs in\n        constr:(Atomic' n)\n  end.\n\n(** Finally, we bring all the pieces together. *)\n\nLtac reify :=\n  match goal with\n    | [ |- ?G ] => let xs := allVars tt G in\n      let p := reifyTerm xs G in\n        pose p\n  end.\n\n(** A quick test verifies that we are doing reification correctly. *)\n\nTheorem mt3' : forall x y z,\n  (x < y /\\ y > z) \\/ (y > z /\\ x < S y)\n  -> y > z /\\ (x < y \\/ x < S y).\n  do 3 intro; reify.\n\n(** Our simple tactic adds the translated term as a new variable:\n[[\nf := Imp'\n         (Or' (And' (Atomic' 2) (Atomic' 1)) (And' (Atomic' 1) (Atomic' 0)))\n         (And' (Atomic' 1) (Or' (Atomic' 2) (Atomic' 0))) : formula'\n]]\n*)\nAbort.\n\n(** More work would be needed to complete the reflective tactic, as we must connect our new syntax type with the real meanings of formulas, but the details are the same as in our prior implementation with [quote]. *)\n(* end thide *)\n\n\n(** * Building a Reification Tactic that Recurses Under Binders *)\n\n(** All of our examples so far have stayed away from reifying the syntax of terms that use such features as quantifiers and [fun] function abstractions.  Such cases are complicated by the fact that different subterms may be allowed to reference different sets of free variables.  Some cleverness is needed to clear this hurdle, but a few simple patterns will suffice.  Consider this example of a simple dependently typed term language, where a function abstraction body is represented conveniently with a Coq function. *)\n\nInductive type : Type :=\n| Nat : type\n| NatFunc : type -> type.\n\nInductive term : type -> Type :=\n| Const : nat -> term Nat\n| Plus : term Nat -> term Nat -> term Nat\n| Abs : forall t, (nat -> term t) -> term (NatFunc t).\n\nFixpoint typeDenote (t : type) : Type :=\n  match t with\n    | Nat => nat\n    | NatFunc t => nat -> typeDenote t\n  end.\n\nFixpoint termDenote t (e : term t) : typeDenote t :=\n  match e with\n    | Const n => n\n    | Plus e1 e2 => termDenote e1 + termDenote e2\n    | Abs _ e1 => fun x => termDenote (e1 x)\n  end.\n\n(** Here is a %\\%naive%{}% first attempt at a reification tactic. *)\n\nLtac refl' e :=\n  match e with\n    | ?E1 + ?E2 =>\n      let r1 := refl' E1 in\n      let r2 := refl' E2 in\n        constr:(Plus r1 r2)\n\n    | fun x : nat => ?E1 =>\n      let r1 := refl' E1 in\n        constr:(Abs (fun x => r1 x))\n\n    | _ => constr:(Const e)\n  end.\n\n(** Recall that a regular Ltac pattern variable [?X] only matches terms that _do not mention new variables introduced within the pattern_.  In our %\\%naive%{}% implementation, the case for matching function abstractions matches the function body in a way that prevents it from mentioning the function argument!  Our code above plays fast and loose with the function body in a way that leads to independent problems, but we could change the code so that it indeed handles function abstractions that ignore their arguments.\n\n   To handle functions in general, we will use the pattern variable form [@?X], which allows [X] to mention newly introduced variables that are declared explicitly.  A use of [@?X] must be followed by a list of the local variables that may be mentioned.  The variable [X] then comes to stand for a Gallina function over the values of those variables.  For instance: *)\n\nReset refl'.\nLtac refl' e :=\n  match e with\n    | ?E1 + ?E2 =>\n      let r1 := refl' E1 in\n      let r2 := refl' E2 in\n        constr:(Plus r1 r2)\n\n    | fun x : nat => @?E1 x =>\n      let r1 := refl' E1 in\n        constr:(Abs r1)\n\n    | _ => constr:(Const e)\n  end.\n\n(** Now, in the abstraction case, we bind [E1] as a function from an [x] value to the value of the abstraction body.  Unfortunately, our recursive call there is not destined for success.  It will match the same abstraction pattern and trigger another recursive call, and so on through infinite recursion.  One last refactoring yields a working procedure.  The key idea is to consider every input to [refl'] as _a function over the values of variables introduced during recursion_. *)\n\nReset refl'.\nLtac refl' e :=\n  match eval simpl in e with\n    | fun x : ?T => @?E1 x + @?E2 x =>\n      let r1 := refl' E1 in\n      let r2 := refl' E2 in\n        constr:(fun x => Plus (r1 x) (r2 x))\n\n    | fun (x : ?T) (y : nat) => @?E1 x y =>\n      let r1 := refl' (fun p : T * nat => E1 (fst p) (snd p)) in\n        constr:(fun x => Abs (fun y => r1 (x, y)))\n\n    | _ => constr:(fun x => Const (e x))\n  end.\n\n(** Note how now even the addition case works in terms of functions, with [@?X] patterns.  The abstraction case introduces a new variable by extending the type used to represent the free variables.  In particular, the argument to [refl'] used type [T] to represent all free variables.  We extend the type to [T * nat] for the type representing free variable values within the abstraction body.  A bit of bookkeeping with pairs and their projections produces an appropriate version of the abstraction body to pass in a recursive call.  To ensure that all this repackaging of terms does not interfere with pattern matching, we add an extra [simpl] reduction on the function argument, in the first line of the body of [refl'].\n\n   Now one more tactic provides an example of how to apply reification.  Let us consider goals that are equalities between terms that can be reified.  We want to change such goals into equalities between appropriate calls to [termDenote]. *)\n\nLtac refl :=\n  match goal with\n    | [ |- ?E1 = ?E2 ] =>\n      let E1' := refl' (fun _ : unit => E1) in\n      let E2' := refl' (fun _ : unit => E2) in\n        change (termDenote (E1' tt) = termDenote (E2' tt));\n          cbv beta iota delta [fst snd]\n  end.\n\nGoal (fun (x y : nat) => x + y + 13) = (fun (_ z : nat) => z).\n  refl.\n(** %\\vspace{-.15in}%[[\n  ============================\n   termDenote\n     (Abs\n        (fun y : nat =>\n         Abs (fun y0 : nat => Plus (Plus (Const y) (Const y0)) (Const 13)))) =\n   termDenote (Abs (fun _ : nat => Abs (fun y0 : nat => Const y0)))\n]]\n*)\n\nAbort.\n\n(** Our encoding here uses Coq functions to represent binding within the terms we reify, which makes it difficult to implement certain functions over reified terms.  An alternative would be to represent variables with numbers.  This can be done by writing a slightly smarter reification function that identifies variable references by detecting when term arguments are just compositions of [fst] and [snd]; from the order of the compositions we may read off the variable number.  We leave the details as an exercise (though not a trivial one!) for the reader. *)\n", "meta": {"author": "jcnm", "repo": "cpdt", "sha": "f490857c85e92be67a66e0523b31b951a173036c", "save_path": "github-repos/coq/jcnm-cpdt", "path": "github-repos/coq/jcnm-cpdt/cpdt-f490857c85e92be67a66e0523b31b951a173036c/src/Reflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.7220530344709944}}
{"text": "Require Import init.\n\nRequire Export relation.\nRequire Export set_base.\nRequire Export set_type.\n\nDefinition is_least {U} (op : U → U → Prop) (S : U → Prop) (x : U)\n    := S x ∧ ∀ y, S y → op x y.\nDefinition is_greatest {U} (op : U → U → Prop) (S : U → Prop) (x : U)\n    := S x ∧ ∀ y, S y → op y x.\nDefinition is_minimal {U} (op : U → U → Prop) (S : U → Prop) (x : U)\n    := S x ∧ ∀ y, S y → y ≠ x → ¬(op y x).\nDefinition is_maximal {U} (op : U → U → Prop) (S : U → Prop) (x : U)\n    := S x ∧ ∀ y, S y → y ≠ x → ¬(op x y).\nDefinition has_least {U} (op : U → U → Prop) (S : U → Prop)\n    := ∃ x, is_least op S x.\nDefinition has_greatest {U} (op : U → U → Prop) (S : U → Prop)\n    := ∃ x, is_greatest op S x.\nDefinition has_minimal {U} (op : U → U → Prop) (S : U → Prop)\n    := ∃ x, is_minimal op S x.\nDefinition has_maximal {U} (op : U → U → Prop) (S : U → Prop)\n    := ∃ x, is_maximal op S x.\n\nDefinition open_interval {U} `{Order U} a b := λ x, a < x ∧ x < b.\nDefinition open_closed_interval {U} `{Order U} a b := λ x, a < x ∧ x ≤ b.\nDefinition closed_open_interval {U} `{Order U} a b := λ x, a ≤ x ∧ x < b.\nDefinition closed_interval {U} `{Order U} a b := λ x, a ≤ x ∧ x ≤ b.\nDefinition open_inf_interval {U} `{Order U} a := λ x, a < x.\nDefinition closed_inf_interval {U} `{Order U} a := λ x, a ≤ x.\nDefinition inf_open_interval {U} `{Order U} a := λ x, x < a.\nDefinition inf_closed_interval {U} `{Order U} a := λ x, x ≤ a.\n\nDefinition is_chain {U} (op : U → U → Prop) (S : U → Prop)\n    := ∀ a b : U, S a → S b → op a b ∨ op b a.\n\nDefinition well_orders {U} (op : U → U → Prop) (S : U → Prop)\n    := ∀ A : U → Prop, A ⊆ S → (∃ x, A x) → ∃ a, is_least op A a.\n\nDefinition initial_segment {U} `{Order U} x := λ a, a < x.\n\nSection SetOrder.\n\nContext {U} `{\n    op : U → U → Prop,\n    Reflexive U op,\n    Antisymmetric U op,\n    Transitive U op\n}.\n\nTheorem chain_subset : ∀ S, is_chain op S → ∀ T, T ⊆ S → is_chain op T.\nProof.\n    intros S S_chain T sub a b Ta Tb.\n    apply S_chain.\n    all: apply sub; assumption.\nQed.\n\nTheorem well_orders_subset :\n    ∀ S, well_orders op S → ∀ T, T ⊆ S → well_orders op T.\nProof.\n    intros S S_wo T sub A A_sub A_ex.\n    apply S_wo.\n    -   exact (trans A_sub sub).\n    -   exact A_ex.\nQed.\n\nTheorem well_orders_chain : ∀ S, well_orders op S → is_chain op S.\nProof.\n    intros S S_wo a b Sa Sb.\n    specialize (S_wo ❴a, b❵).\n    prove_parts S_wo.\n    -   intros x [|]; subst x; assumption.\n    -   exists a.\n        left; reflexivity.\n    -   destruct S_wo as [x [x_in x_least]].\n        destruct x_in as [|]; subst x.\n        +   left.\n            apply x_least.\n            right; reflexivity.\n        +   right.\n            apply x_least.\n            left; reflexivity.\nQed.\n\nEnd SetOrder.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Set/set_order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7220489426436519}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  zNil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : lst) (qreva_arg1 : lst) : lst\n           := match qreva_arg0, qreva_arg1 with\n              | Nil, x => x\n              | Cons z x, y => qreva x (Cons z y)\n              end.\n\nTheorem plus_comm: forall (n m: natural), plus n m = plus m n.\nProof.\n  induction n; induction m.\n  { simpl. rewrite IHn. rewrite <- IHm. simpl. rewrite IHn. reflexivity. }\n  { simpl. rewrite IHn. simpl. reflexivity. }\n  { simpl. rewrite <- IHm. simpl. reflexivity. }\n  { reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (len (qreva x y)) (plus (len x) (len y)).\nProof.\n  induction x; induction y; simpl; try reflexivity.\n  + \n    rewrite plus_comm. simpl.\n    rewrite IHx. simpl. rewrite plus_comm.\n    simpl. reflexivity. \n  + \n    rewrite plus_comm. simpl. rewrite IHx. \n    rewrite plus_comm.\n    simpl. reflexivity. \nQed.\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7219955590006198}}
{"text": "   Theorem t75_5: forall (P Q : Set -> Prop),\n                   (forall x : Set, P x <-> Q x)\n                     -> ((forall x : Set, P x) <-> (forall x : Set, Q x)).\n   Proof.\n      intros. split. intros. cut(P x <-> Q x). intros.\n      apply H1. apply H0. apply H.\n      intros. cut(P x <-> Q x). intros.\n      apply H1. apply H0. apply H.\n    Qed.\n\n   Theorem t75_6: forall (P Q : Set -> Prop),\n                   (forall x : Set, P x <-> Q x)\n                     -> ((exists x : Set, P x) <-> (exists x : Set, Q x)).\n   Proof.\n      intros. split. intros. elim H0. intros. exists x.\n      cut(P x <-> Q x). intros. apply H2. assumption. apply H.\n      intros. elim H0. intros. exists x.\n      cut(P x <-> Q x). intros. apply H2. assumption. apply H.\n    Qed.\n\n   Theorem t76: forall (A : Set -> Prop) (b : Set),\n                   (forall x : Set, A x) -> (exists x : Set, A x).\n   Proof.\n      intros. exists b. apply H.\n    Qed.\n\n   Theorem t77: forall (A : Set -> Set -> Prop),\n                   (exists x : Set, forall y : Set, A y x) \n                   -> (forall x : Set, exists y : Set, A x y).\n   Proof.\n      intros. elim H. intros. exists x0. apply H0.\n    Qed.\n\n   Theorem t78: forall (A B : Set -> Prop),\n                   (exists x : Set, A x /\\ B x) \n                   -> ((exists x : Set, A x) /\\ (exists x : Set, B x)).\n   Proof.\n      intros. elim H. intros. split.\n      exists x. apply H0.\n      exists x. apply H0.\n    Qed.\n\n   Theorem t78_1: forall (P Q : Set -> Prop),\n                   (exists x : Set, P x /\\ ~(Q x)) \n               <-> ~(forall x : Set, P x -> Q x).\n   Proof.\n      intros. split. intros. elim H. intros. intro. elim H0. intros.\n      cut(P x -> Q x). intros. apply H3. apply H4. apply H0. apply H1.\n      Require Import Classical.\n      intros. apply NNPP. intro. apply H. intros. apply NNPP. intro.\n      apply H0. exists x. split. assumption. assumption.\n    Qed.\n\n   Theorem t78_2: forall (P Q : Set -> Prop) (E : Prop),\n                   (exists x : Set, Q x /\\ P x /\\ E) \n               <-> E /\\ (exists x : Set, Q x /\\ P x).\n   Proof.\n      intros. split. intros. elim H. intros. split.\n      apply H0. exists x. split. apply H0. apply H0.\n      intros. elim H. intros. elim H1. intros. exists x. split.\n      apply H2. split. apply H2. apply H0.\n    Qed.\n\n   Theorem t79: forall (A B : Set -> Prop),\n                   ((forall x : Set, A x) \\/ (forall x : Set, B x))\n                      -> (forall x : Set, A x \\/ B x).\n   Proof.\n      intros. elim H. intros. left. apply H0.\n      intros. right. apply H0.\n    Qed.\n\n   Theorem t80: forall (A B : Set -> Prop),\n                   ((exists x : Set, A x) -> (forall x : Set, B x))\n                      -> (forall x : Set, A x -> B x).\n   Proof.\n      intros. apply H. exists x. assumption.\n    Qed.\n\n   Theorem t80_1: forall (A B : Set -> Prop) (b : Set),\n                   ((exists x : Set, A x) -> (exists x : Set, B x))\n                      -> (exists x : Set, A x -> B x).\n   Proof.\n      Require Import Classical.\n      intros. apply NNPP. intro. apply H0. exists b. intros.\n      elim H. intros. apply NNPP.  intro.  apply H0. exists x. intro. assumption.\n      exists b. assumption.\n    Qed.\n\n   Theorem t81: forall (A : Set -> Set -> Prop),\n                   (forall x y : Set, A x y)\n                      -> (forall x : Set, A x x ).\n   Proof.\n      intros. apply H. \n    Qed.\n\n   Theorem t82: forall (A : Set -> Set -> Prop) (b : Set),\n                   (exists x : Set, A x x)\n                      -> (exists x : Set, exists y : Set, A x y).\n   Proof.\n      intros. elim H.  intros. exists x. exists x. assumption. \n    Qed.\n\n   Theorem t83: forall (A : Set -> Prop)\n                       (t : Set), \n                   (forall x : Set, A x) -> A t.\n   Proof.\n      intros. apply H.\n   Qed.\n\n   Theorem t84: forall (A : Set -> Prop)\n                       (t : Set), \n                   A t -> (exists x : Set, A x).\n   Proof.\n      intros. exists t. assumption.\n   Qed.\n\n   Theorem t85: forall (A : Set -> Prop)\n                       (t : Set), \n                   (exists x : Set, A x) \\/ (exists x : Set, ~(A x)).\n   Proof.\n      Require Import Classical.\n      intros. generalize(classic(A t)). intros. elim H.\n      intros. left. exists t. assumption.\n      intros. right. exists t. assumption.\n   Qed.\n\n   Theorem t86: forall (P Q : Set -> Prop)\n                       (R : Set -> Set -> Prop)\n                       (b : Set), \n                   (exists x : Set, (P x /\\ (exists y : Set, Q y /\\ R x y))) \n               <-> (exists y : Set, (Q y /\\ (exists x : Set, P x /\\ R x y))).\n   Proof.\n      intros. split. intros. elim H. intros. elim H0. intros. elim H2. intros.\n      elim H3. intros.\n      exists x0. split. assumption. exists x. split. assumption. assumption.\n      intros. elim H. intros. elim H0. intros. elim H2. intros.\n      elim H3. intros.\n      exists x0. split. assumption. exists x. split. assumption. assumption.\n   Qed.\n\n   Theorem t87: forall (P Q : Set -> Prop)\n                       (R : Set -> Set -> Prop)\n                       (b : Set), \n                   (exists x : Set, (P x /\\ (forall y : Set, Q y -> R x y))) \n                -> (forall y : Set, (Q y -> (exists x : Set, P x /\\ R x y))).\n   Proof.\n      intros. elim H. intros. elim H1. intros.\n      exists x. split. assumption. apply H3. assumption.\n   Qed.\n\n", "meta": {"author": "ko-petrov", "repo": "lessons", "sha": "3524fd9f0a98923f3ef471114bba52d6bbbfcf2f", "save_path": "github-repos/coq/ko-petrov-lessons", "path": "github-repos/coq/ko-petrov-lessons/lessons-3524fd9f0a98923f3ef471114bba52d6bbbfcf2f/coq/Lab2/PetrovPrPrLab2-t75_5-t87.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7219955485883975}}
{"text": "Require Export D.\n\n\n\n(** **** Exercise: 3 stars (swap_if_branches)  *)\n(** Show that we can swap the branches of an IF by negating its\n    condition *)\n\nLemma bool_negb : forall b1 b2,\n  negb b1 = b2 -> b1 = negb b2.\nProof. intros. destruct b1; destruct b2; try inversion H; try reflexivity. Qed.\n\n\nTheorem swap_if_branches: forall b e1 e2,\n  cequiv\n    (IFB b THEN e1 ELSE e2 FI)\n    (IFB BNot b THEN e2 ELSE e1 FI).\nProof.\n  split; intros.\n  Case \"->\". inversion H; subst. \n    SCase \"True\". apply E_IfFalse. simpl. rewrite H5. reflexivity. assumption.\n    SCase \"False\". apply E_IfTrue. simpl. rewrite H5. reflexivity.  assumption.\n  Case \"<-\".  inversion H; subst. inversion H5. \n    SCase \"False\". apply E_IfFalse. simpl. apply bool_negb in H1;simpl in H1. assumption. assumption.\n    SCase \"True\". apply E_IfTrue. simpl in H5. apply bool_negb in H5. simpl in H5. assumption. assumption.\n  Qed.\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/08/P08.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7219955476422982}}
{"text": "Require Import  Coq.Lists.List. \n\n\nDefinition insert (n:nat) (lst: list nat) :list nat := n::lst. \n\nDefinition remove (lst: list nat) : ((option nat) * list nat) :=\nmatch rev(lst) with\n| nil => (None, nil)\n| l::lst' => (Some l,lst')\nend. \n\n\n\n\nDefinition listProd: Set := (list nat * list nat) %type. \n\nDefinition insert' (n:nat) (lst: listProd) :listProd := \nmatch lst with\n| (bs,fs) => (n::bs,fs)\nend. \n\nDefinition remove' (lst:listProd): ((option nat) * listProd) :=\nmatch lst with\n| (bs , nil) => match rev(bs) with \n                    | nil => (None,lst)\n                    | i::bs' => (Some i, (nil,bs'))\n                    end\n| (bs, f::fs') => (Some f, (bs,fs'))\nend.\n\nDefinition R (lst: list nat) (lstProd:listProd) : Prop :=\nlet (bs,fs):=lstProd in\nlst = app (bs) (rev(fs)).\n\nLemma emptyR: \nR nil (nil,nil).\nProof.  simpl. auto. Qed.\n\n\n\nLemma insertR:\nforall lst lstProd d, R lst lstProd -> R (insert d lst) (insert' d lstProd).\nProof.\nintros.  unfold R. \nunfold insert. destruct lstProd. \nsimpl. inversion H. auto.  \nQed. \n\nLemma removeR:\nforall lst lstProd, \nR lst lstProd -> \n(lst = nil /\\ lstProd = (nil,nil) \n\\/ (exists d d' lst' lstProd',  remove lst = (Some d,lst') -> remove' lstProd =(Some d', lstProd') -> R lst' lstProd')).\nProof.\nintros. destruct lstProd.\ndestruct l0. destruct l. inversion H. left. split; simpl; auto.\ninversion H. simpl in H0. right.\nexists n. exists n. exists l.   exists ((nil,rev l)).\nintros. unfold R. simpl. rewrite rev_involutive.   auto.\ninversion H. right.\nexists n.  exists n. exists (l++ rev l0). \nexists ((l,l0)).\nintros. unfold R. auto.\nQed.       \n\n\n\n\n\n\n", "meta": {"author": "plclub", "repo": "cis670-16fa", "sha": "e123c26d06a883b599c9bbf2474610ad84975a8c", "save_path": "github-repos/coq/plclub-cis670-16fa", "path": "github-repos/coq/plclub-cis670-16fa/cis670-16fa-e123c26d06a883b599c9bbf2474610ad84975a8c/code/abstractTypeExample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7219955431935795}}
{"text": "Require Export Basics_J.\n\nModule NatList.\nInductive natprod : Type :=\n pair : nat -> nat -> natprod.\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\n\nNotation \"( x , y )\" := (pair x y).\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\nTheorem surjective_pairing' : forall (n m : nat), (n,m) = (fst (n,m), snd (n,m)).\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\nTheorem surjective_pairing : forall (p : natprod), p = (fst p, snd p).\nProof.\nintros p.\ndestruct p as (n,m).\nsimpl.\nreflexivity.\nQed.\n\nTheorem snd_fst_is_swap : forall (p : natprod), (snd p, fst p) = swap_pair p.\nProof.\nintros.\ndestruct p as (n,m).\nsimpl.\nreflexivity.\nQed.\n\nInductive natlist : Type :=\n | nil : natlist\n | cons : nat -> natlist -> natlist.\n\nDefinition l_123 := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l)(at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\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 length (l : natlist) : nat :=\n match l with\n  | nil => O\n  | h :: t => S (length t)\n end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n end.\n\nNotation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\nExample test_app1: [1,2,3] ++ [4,5] = [1,2,3,4,5].\nProof.\nsimpl.\nreflexivity.\nQed.\n\nExample test_app2: nil ++ [4,5] = [4,5].\nProof.\nsimpl.\nreflexivity.\nQed.\n\nExample test_app3: [1,2,3] ++ nil = [1,2,3].\nProof.\nsimpl.\nreflexivity.\nQed.\n\nDefinition hd (default : nat)(l : natlist) : nat :=\n match l with\n  | nil => default\n  | h :: t => h\n end.\n\n\nDefinition tail (l : natlist) : natlist :=\n match l with\n  | nil => nil\n  | h :: t => t\n end.\n\n\nExample test_hd1 : hd O [1,2,3] = 1.\nProof.\nsimpl.\nreflexivity.\nQed.\n\nExample test_hd2 : hd O [] = 0.\nProof.\nsimpl.\nreflexivity.\nQed.\n\nExample test_tail : tail [1,2,3] = [2,3].\nProof.\nsimpl.\nreflexivity.\nQed.\n\nDefinition bag := natlist.\n\n\n\n(*-----<<< Inference about the lists >>>------*)\nTheorem nil_app : forall (l : natlist), [] ++ l = l.\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\nTheorem tl_lentgh_pred : forall (l : natlist), pred (length l) = length (tail l).\nProof.\nintros.\ndestruct l.\nsimpl.\nreflexivity.\nsimpl.\nreflexivity.\nQed.\n\nEnd NatList.\n\n(*---------<<< start Dictionary >>>-----------*)\n", "meta": {"author": "masakiishii", "repo": "coq", "sha": "79aa006aabb42eeb44474dd8154108ed2af6f428", "save_path": "github-repos/coq/masakiishii-coq", "path": "github-repos/coq/masakiishii-coq/coq-79aa006aabb42eeb44474dd8154108ed2af6f428/Lists_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.8856314647623016, "lm_q1q2_score": 0.7219955357152907}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia Extraction Utf8. (* → λ ∀ ∃ ↔ ∧ ∨ *)\n\nRequire Import induction.\n\nRequire Import dfs_graph_def dfs_fun dfs_fix dfs_partial_corr.\n\nSet Implicit Arguments.\n\nSection dfs_domain_characterization.\n\n  (* Hence dfs v l cannot terminate unless such a finite invariant exists\n     (because that is what it computes ...) \n     Let us show that this condition is also sufficient *)\n\n  Theorem 𝔻dfs_domain v l : 𝔻dfs v l ↔ ∃i, dfs_invariant_t v l i.\n  Proof.\n    split.\n    + (* The direct implication is trivially derived from partial correctness *)\n\n      intros D; exists (dfs D); apply dfs_invariant.\n    + (* The reverse implication is more complicated, much more ...\n         We proceed by lexicographic product \n           a) strict reverse inclusion bounded by i for v\n           b) structural induction for l *)\n\n      unfold dfs_invariant_t, incl.\n      intros (i & H1 & H2 & H3).\n      revert v H1 l H2 H3.\n    \n      (** Induction on v using upper-bounded strict reverse inclusion as well-founded relation *)\n    \n      induction v as [ v IHv ] using (well_founded_induction (wf_sincl_maj i)); intros Hv.\n    \n      (** Structural induction on l *)\n    \n      induction l as [ | x l IHl ]; intros Hl H.\n      1: apply 𝔻dfs_1.\n      case_eq (mem x v); \n        [ rewrite mem_true_iff \n        | rewrite mem_false_iff ]; intros Hx.\n      * (* dfs v (x::_) where x ∈ v *) \n        clear IHv.\n        apply 𝔻dfs_2; auto.\n        apply IHl; auto.                (* Induction on l *)\n        intros; apply Hl; right; auto.\n      * (* dfs v (x::_) where x ∉ v *) \n        clear IHl.\n        apply 𝔻dfs_3; auto.\n        assert (Hx' : In x i) \n          by (apply Hl; left; auto).\n        apply IHv.                     (* Induction on v *)\n        - split;\n          [ right; auto\n          | exists x; repeat split; auto; left; auto ].\n        - intros y [ ? | ? ]; subst; auto.\n        - intros y Hy.\n          apply in_app_or in Hy.\n          destruct Hy as [ Hy | Hy ].\n          ++ apply H in Hx'.\n             destruct Hx' as [ Hx' | Hx' ].\n             ** tauto.\n             ** apply Hx'; auto.\n          ++ apply Hl; right; auto.\n        - intros y Hy; apply H in Hy; simpl; tauto.\n  Qed.\n\n  (* Using the domain characterized by invariants, \n     monotonicity properties are easy to establish ... \n     it is much harder with d_dfs based induction. *)\n\n  Fact 𝔻dfs_mono v v' l l' : v ⊆ v' → l' ⊆ v'++l → 𝔻dfs v l → 𝔻dfs v' l'.\n  Proof.\n    intros H1 H2.\n    do 2 rewrite 𝔻dfs_domain.\n    intros (lP & H3 & H4 & H5).\n    exists (v'++lP); repeat split; auto.\n    + intros ? ?; apply in_or_app; left; auto.\n    + intros x Hx; apply in_or_app.\n      apply H2, in_app_or in Hx.\n      destruct Hx; auto.\n    + intros x Hx.\n      apply in_app_or in Hx.\n      destruct Hx as [ Hx | Hx ]; auto.\n      apply H5 in Hx.\n      destruct Hx as [ Hx | Hx ].\n      * left; apply H1; auto.\n      * right; intros ? ?; apply in_or_app; right; auto.\n  Qed.\n  \n  (* dfs is usually called as dfs nil l. \n     In that case, the invariant is simpler \n\n     It is list containing l and closed under succs\n   *)\n\n  (* → λ ∀ ∃ ↔ ∧ ∨ *)\n\n  Definition dfs_nil_invariant_t l i := l ⊆ i ∧ ∀x, x ∈ i → succs x ⊆ i.\n\n  (* Partial correctness of dfs nil: it computes the minimal invariant *)\n\n  Corollary dfs_nil_invariant l D : dfs_nil_invariant_t l (@dfs nil l D)\n                              ∧ ∀i, dfs_nil_invariant_t l i → dfs D ⊆ i.\n  Proof.\n    generalize (dfs_invariant D); intros ((_ & H2 & H3) & H4).\n    repeat split; auto.\n    + intros x Hx.\n      destruct (H3 _ Hx) as [ [] | ]; auto.\n    + intros i (G1 & G2); apply H4.\n      repeat split; auto.\n      intros _ []. \n  Qed.\n\n  (* \"Total\" correctedness: dfs terminates provided an invariant exists *)\n\n  Corollary 𝔻dfs_nil_domain l : 𝔻dfs nil l ↔ ex (dfs_nil_invariant_t l). \n  Proof.\n    split.\n    + intros D; exists (dfs D); apply dfs_nil_invariant.\n    + rewrite 𝔻dfs_domain.\n      intros (inv & H1 & H2).\n      exists inv; split; auto.\n      intros _ [].\n  Qed.\n\nEnd dfs_domain_characterization.\n\nSection finite_domain.\n\n  (* In particular, if 𝓔 is finite then dfs terminate *)\n \n  Hypothesis (H𝓥 : ∃l𝓥, ∀x:𝓥, x ∈ l𝓥).\n\n  Fact 𝔻dfs_total v l : 𝔻dfs v l.\n  Proof. \n    apply 𝔻dfs_domain.\n    destruct H𝓥 as (l𝓥 & ?).\n    unfold dfs_invariant_t, incl.\n    exists l𝓥; auto.\n  Qed.\n\nEnd finite_domain.\n\nSection non_termination.\n\n  (* We assume as an example that 𝓔 is isomorphic to nat\n     and succs x = [S x] *)\n\n  Hypothesis (f : nat -> 𝓥) (g : 𝓥 -> nat) \n             (Hfg : forall x, f (g x) = x)\n             (Hgf : forall n, g (f n) = n)\n             (Hsuccs : forall x, succs x = f (S (g x)) :: nil).\n\n  Fact max_list l : { m | m ∈ l ∧ ∀k, k ∈ l → k <= m } + { l = nil }.\n  Proof.\n    induction l as [ | n l IHl ].\n    + right; auto.\n    + left; destruct IHl as [ (m & H1 & H2) | H ].\n      * destruct (le_lt_dec m n) as [ H | H ].\n        - exists n; simpl; split; auto.\n          intros k [ <- | H3 ]; auto.\n          apply H2 in H3; lia.\n        - exists m; simpl; split; auto.\n          intros k [ <- | H3 ]; auto; lia.\n      * exists n; subst; split; simpl; auto.\n        intros ? [ <- | [] ]; auto.\n  Qed. \n\n  Fact unbounded_list_absurd l : (∀n, n ∈ l → S n ∈ l) → l = nil.\n  Proof.\n    intros H.\n    destruct (max_list l) as [ (m & H1 & H2) | -> ]; auto.\n    apply H, H2 in H1; lia.\n  Qed.\n\n  Fact dfs_non_termination l : 𝔻dfs nil l ↔ l = nil. \n  Proof.\n    split.\n    * rewrite 𝔻dfs_nil_domain.\n      intros (i & H1 & H2).\n      assert (map g l ⊆ map g i) as H3.\n      { intro n; rewrite !in_map_iff.\n        intros (x & <- & ?); exists x; auto. } \n      rewrite (unbounded_list_absurd (map g i)) in H3.\n      + destruct l as [ | x ]; auto; exfalso; apply (H3 (g x)); simpl; auto.\n      + intros n; rewrite !in_map_iff.\n        intros (x & <- & Hx). \n        exists (f (S (g x))).\n        rewrite Hgf; split; auto.\n        apply (H2 x); auto.\n        rewrite Hsuccs; left; auto. \n    * intros ->; apply 𝔻dfs_nil_domain.\n      exists nil; repeat split; unfold incl; firstorder.\n  Qed.\n\nEnd non_termination.\n\nCheck 𝔻dfs.\nPrint Assumptions 𝔻dfs.\n\nCheck dfs.\nPrint Assumptions dfs.\n\nCheck 𝔻dfs_total.\nPrint Assumptions 𝔻dfs_total.\n\nCheck dfs_non_termination.\nPrint Assumptions dfs_non_termination.\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\nExtract Inductive list => \"list\" [ \"[]\" \"(::)\" ].\n(* Extract Inlined Constant app => \"(@)\". *)\n\nRecursive Extraction dfs.\n\n\n\n", "meta": {"author": "DmxLarchey", "repo": "The-Braga-Method", "sha": "e4f51add22a73681103454ad94a05aeeda332c50", "save_path": "github-repos/coq/DmxLarchey-The-Braga-Method", "path": "github-repos/coq/DmxLarchey-The-Braga-Method/The-Braga-Method-e4f51add22a73681103454ad94a05aeeda332c50/theories/dfs/dfs_term.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7219103142235922}}
{"text": "Require Import Coq.Bool.Bvector.\nRequire Import Coq.ZArith.BinInt.\nRequire Import Coq.ZArith.Zdigits.\n\nModule Bits.\n\n(* An 8-bit binary number. *)\nDefinition B8 := Bvector 8.\n\n(* A 64-bit binary number. *)\nDefinition B64 := Bvector 64.\n\n(* Map a natural number to an 8-bit binary number. *)\nDefinition nat_to_B8 (n: nat) : B8 := Z_to_binary 8 (Z.of_nat n).\n\n(* Map a natural number to a 64-bit binary number. *)\nDefinition nat_to_B64 (n: nat) : B64 := Z_to_binary 64 (Z.of_nat n).\n\n(* Map an 8-bit number to an integer. *)\nDefinition B8_to_Z (bv : B8) : Z := binary_value 8 bv.\n\n(* Map a 64-bit number to an integer. *)\nDefinition B64_to_Z (bv : B64) : Z := binary_value 64 bv.\n\n(* Map an integer to a  64-bit number. *)\nDefinition Z_to_B64 (z : Z) : B64 := Z_to_binary 64 z.\n\n(* Perform an AND operation on two BV64 values. *)\nDefinition B64_and (x y : B64) : B64 := BVand 64 x y.\n\n(* Perform an OR operation on two BV64 values. *)\nDefinition B64_or (x y : B64) : B64 := BVor 64 x y.\n\n(* Perform an XOR operation on two BV64 values. *)\nDefinition B64_xor (x y : B64) : B64 := BVxor 64 x y.\n\nModule ZStuff.\n\n    Local Open Scope Z_scope.\n\n    (* Do a left shift of a B64 value. *)\n    Definition B64_shl (bv : B64) := Z_to_B64 ((B64_to_Z bv) * 2).\n\n    (* Do an iterative left shift of a B64 value. *)\n    Definition B64_shl_iter (n : nat) (bv : B64) :=\n        Z_to_B64 ((B64_to_Z bv) * (two_power_nat n)).\n\n    (* Do a right shift of a B64 value. *)\n    Definition B64_shr (bv : B64) := Z_to_B64 ((B64_to_Z bv) / 2).\n\n    (* Do an iterative right shift of a B64 value. *)\n    Definition B64_shr_iter (n : nat) (bv : B64) :=\n        Z_to_B64 ((B64_to_Z bv) / (two_power_nat n)).\n\n    (* Determine if x equals y. *)\n    Definition B64_eql (x y : B64) :=\n        match (B64_to_Z x) ?= (B64_to_Z y) with\n            | Eq => nat_to_B64 1\n            | _ => nat_to_B64 0\n        end.\n\n    (* Determine if x < y. *)\n    Definition B64_lt (x y : B64) :=\n        match (B64_to_Z x) ?= (B64_to_Z y) with\n            | Lt => nat_to_B64 1\n            | _ => nat_to_B64 0\n        end.\n\n    (* Determine if x > y. *)\n    Definition B64_gt (x y : B64) :=\n        match (B64_to_Z x) ?= (B64_to_Z y) with\n            | Gt => nat_to_B64 1\n            | _ => nat_to_B64 0\n        end.\n\n    (* Determine if x <= y. *)\n    Definition B64_le (x y : B64) :=\n        match (B64_to_Z x) ?= (B64_to_Z y) with\n            | Eq => nat_to_B64 1\n            | Lt => nat_to_B64 1\n            | _ => nat_to_B64 0\n        end.\n\n    (* Determine if x >= y. *)\n    Definition B64_ge (x y : B64) :=\n        match (B64_to_Z x) ?= (B64_to_Z y) with\n            | Eq => nat_to_B64 1\n            | Gt => nat_to_B64 1\n            | _ => nat_to_B64 0\n        end.\n\n    (* Determine if x != y. *)\n    Definition B64_neq (x y : B64) :=\n        match (B64_to_Z x) ?= (B64_to_Z y) with\n            | Eq => nat_to_B64 0\n            | _ => nat_to_B64 1\n        end.\n\n    (* Add two numbers. *)\n    Definition B64_add (x y : B64) :=\n        (Z_to_B64 ((B64_to_Z x) + (B64_to_Z y))).\n\n    (* Subtract two numbers. *)\n    Definition B64_sub (x y : B64) :=\n        (Z_to_B64 ((B64_to_Z x) - (B64_to_Z y))).\n\n    (* Multiply two numbers. *)\n    Definition B64_mul (x y : B64) :=\n        (Z_to_B64 ((B64_to_Z x) * (B64_to_Z y))).\n\n    (* Divide two numbers. *)\n    Definition B64_div (x y : B64) :=\n        (Z_to_B64 ((B64_to_Z x) / (B64_to_Z y))).\n\n    (* Compute x modulo y. *)\n    Definition B64_mod (x y : B64) :=\n        (Z_to_B64 ((B64_to_Z x) mod (B64_to_Z y))).\n\nEnd ZStuff.\n\nExport ZStuff.\n\nEnd Bits.\n", "meta": {"author": "nanolith", "repo": "cpidgin", "sha": "ff70b5a2bf47d81a63164645bf52cc0496ad7c63", "save_path": "github-repos/coq/nanolith-cpidgin", "path": "github-repos/coq/nanolith-cpidgin/cpidgin-ff70b5a2bf47d81a63164645bf52cc0496ad7c63/src/coq/Data/Bits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7219103098272571}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  Fop                                                     \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  ******************************************************************************)\nRequire Export Fcomp.\nSection operations.\nVariable radix : Z.\n\nLet FtoRradix := FtoR radix.\nLocal Coercion FtoRradix : float >-> R.\n\nHypothesis radixNotZero : (0 < radix)%Z.\n \nDefinition Fplus (x y : float) :=\n  Float\n    (Fnum x * Zpower_nat radix (Zabs_nat (Fexp x - Zmin (Fexp x) (Fexp y))) +\n     Fnum y * Zpower_nat radix (Zabs_nat (Fexp y - Zmin (Fexp x) (Fexp y))))\n    (Zmin (Fexp x) (Fexp y)).\n \nTheorem Fplus_correct : forall x y : float, Fplus x y = (x + y)%R :>R.\nintros x y; unfold Fplus, Fshift, FtoRradix, FtoR in |- *; simpl in |- *.\nrewrite plus_IZR.\nrewrite Rmult_comm; rewrite Rmult_plus_distr_l; auto.\nrepeat rewrite Rmult_IZR.\nrepeat rewrite (Rmult_comm (Fnum x)); repeat rewrite (Rmult_comm (Fnum y)).\nrepeat rewrite Zpower_nat_Z_powerRZ; auto.\nrepeat rewrite <- Rmult_assoc.\nrepeat rewrite <- powerRZ_add; auto with real zarith arith.\nrepeat rewrite inj_abs; auto with real zarith.\nrepeat rewrite Zplus_minus; auto.\nQed.\n \nDefinition Fopp (x : float) := Float (- Fnum x) (Fexp x).\n \nTheorem Fopp_correct : forall x : float, Fopp x = (- x)%R :>R.\nunfold FtoRradix, FtoR, Fopp in |- *; simpl in |- *.\nintros x.\nrewrite Ropp_Ropp_IZR; auto with real.\nQed.\n \nTheorem Fopp_Fopp : forall p : float, Fopp (Fopp p) = p.\nintros p; case p; unfold Fopp in |- *; simpl in |- *; auto.\nintros; rewrite Zopp_involutive; auto.\nQed.\n \nTheorem Fzero_opp : forall f : float, ~ is_Fzero f -> ~ is_Fzero (Fopp f).\nintros f; case f; intros n e; case n; unfold is_Fzero in |- *; simpl in |- *;\n auto with zarith; intros; red in |- *; intros; discriminate.\nQed.\n \nTheorem Fdigit_opp : forall x : float, Fdigit radix (Fopp x) = Fdigit radix x.\nintros x; unfold Fopp, Fdigit in |- *; simpl in |- *.\nrewrite <- (digit_abs radix (- Fnum x)).\nrewrite <- (digit_abs radix (Fnum x)).\ncase (Fnum x); simpl in |- *; auto.\nQed.\n \nDefinition Fabs (x : float) := Float (Zabs (Fnum x)) (Fexp x).\n \nTheorem Fabs_correct1 :\n forall x : float, (0 <= FtoR radix x)%R -> Fabs x = x :>R.\nintros x; case x; unfold FtoRradix, FtoR in |- *; simpl in |- *.\nintros Fnum1 Fexp1 H'.\nrepeat rewrite <- (Rmult_comm (powerRZ radix Fexp1)); apply Rmult_eq_compat_l;\n auto.\ncut (0 <= Fnum1)%Z.\nunfold Zabs, Zle in |- *.\ncase Fnum1; simpl in |- *; auto.\nintros p H'0; case H'0; auto.\napply Znot_gt_le; auto.\nContradict H'.\napply Rgt_not_le; auto.\nrewrite Rmult_comm.\nreplace 0%R with (powerRZ radix Fexp1 * 0)%R; auto with real.\nred in |- *; apply Rmult_lt_compat_l; auto with real zarith.\nQed.\n \nTheorem Fabs_correct2 :\n forall x : float, (FtoR radix x <= 0)%R -> Fabs x = (- x)%R :>R.\nintros x; case x; unfold FtoRradix, FtoR in |- *; simpl in |- *.\nintros Fnum1 Fexp1 H'.\nrewrite <- Ropp_mult_distr_l_reverse;\n repeat rewrite <- (Rmult_comm (powerRZ radix Fexp1));\n apply Rmult_eq_compat_l; auto.\ncut (Fnum1 <= 0)%Z.\nunfold Zabs, Zle in |- *.\ncase Fnum1; unfold IZR; auto with real.\nintros p H'0; case H'0; auto.\napply Znot_gt_le.\nContradict H'.\napply Rgt_not_le; auto.\nrewrite Rmult_comm.\nreplace 0%R with (powerRZ radix Fexp1 * 0)%R; auto with real.\nred in |- *; apply Rmult_lt_compat_l; auto with real arith.\nreplace 0%R with (IZR 0); auto with real zarith arith.\nQed.\n \nTheorem Fabs_correct : forall x : float, Fabs x = Rabs x :>R.\nintros x; unfold Rabs in |- *.\ncase (Rcase_abs x); intros H1.\nunfold FtoRradix in |- *; apply Fabs_correct2; auto with arith.\napply Rlt_le; auto.\nunfold FtoRradix in |- *; apply Fabs_correct1; auto with arith.\napply Rge_le; auto.\nQed.\n \nTheorem RleFexpFabs :\n forall p : float, p <> 0%R :>R -> (Float 1%nat (Fexp p) <= Fabs p)%R.\nintros p H'.\nunfold FtoRradix, FtoR, Fabs in |- *; simpl in |- *.\napply Rmult_le_compat_r; auto with real arith.\nrewrite Zabs_absolu.\nreplace 1%R with (INR 1); auto with real.\nrepeat rewrite <- INR_IZR_INZ; apply Rle_INR; auto.\ncut (Zabs_nat (Fnum p) <> 0); auto with zarith.\nContradict H'.\nunfold FtoRradix, FtoR in |- *; simpl in |- *.\nreplace (Fnum p) with 0%Z; try (simpl;ring).\ngeneralize H'; case (Fnum p); simpl in |- *; auto with zarith arith;\n intros p0 H'3; Contradict H'3; auto with zarith arith.\nQed.\n \nTheorem Fabs_Fzero : forall x : float, ~ is_Fzero x -> ~ is_Fzero (Fabs x).\nintros x; case x; unfold is_Fzero in |- *; simpl in |- *.\nintros n m; case n; simpl in |- *; auto with zarith; intros; red in |- *;\n discriminate.\nQed.\nHint Resolve Fabs_Fzero: float.\n \nTheorem Fdigit_abs : forall x : float, Fdigit radix (Fabs x) = Fdigit radix x.\nintros x; unfold Fabs, Fdigit in |- *; simpl in |- *.\ncase (Fnum x); auto.\nQed.\n \nDefinition Fminus (x y : float) := Fplus x (Fopp y).\n \nTheorem Fminus_correct : forall x y : float, Fminus x y = (x - y)%R :>R.\nintros x y; unfold Fminus in |- *.\nrewrite Fplus_correct.\nrewrite Fopp_correct; auto.\nQed.\n \nTheorem Fopp_Fminus : forall p q : float, Fopp (Fminus p q) = Fminus q p.\nintros p q; case p; case q; unfold Fopp, Fminus, Fplus in |- *; simpl in |- *;\n auto.\nintros; apply floatEq; simpl in |- *; repeat rewrite (Zmin_sym Fexp0 Fexp);\n repeat rewrite Zopp_mult_distr_l_reverse; auto with zarith.\nQed.\n \nTheorem Fopp_Fminus_dist :\n forall p q : float, Fopp (Fminus p q) = Fminus (Fopp p) (Fopp q).\nintros p q; case p; case q; unfold Fopp, Fminus, Fplus in |- *; simpl in |- *;\n auto.\nintros; apply floatEq; simpl in |- *; repeat rewrite (Zmin_sym Fexp0 Fexp);\n repeat rewrite Zopp_mult_distr_l_reverse; auto with zarith.\nQed.\n \nTheorem minusSameExp :\n forall x y : float,\n Fexp x = Fexp y -> Fminus x y = Float (Fnum x - Fnum y) (Fexp x).\nintros x y; case x; case y; unfold Fminus, Fplus, Fopp in |- *; simpl in |- *.\nintros Fnum1 Fexp1 Fnum2 Fexp2 H'; rewrite <- H'.\nrepeat rewrite Zmin_n_n.\napply floatEq; simpl in |- *; auto.\nreplace (Zabs_nat (Fexp2 - Fexp2)) with 0; auto with zarith arith.\nreplace (Zpower_nat radix 0) with (Z_of_nat 1); simpl in |- *;\n auto with zarith arith.\nreplace (Fexp2 - Fexp2)%Z with 0%Z; simpl in |- *; auto with zarith arith.\nQed.\n \nDefinition Fmult (x y : float) := Float (Fnum x * Fnum y) (Fexp x + Fexp y).\n \nDefinition Fmult_correct : forall x y : float, Fmult x y = (x * y)%R :>R.\nintros x y; unfold FtoRradix, FtoR, Fmult in |- *; simpl in |- *; auto.\nrewrite powerRZ_add; auto with real zarith.\nrepeat rewrite Rmult_IZR.\nrepeat rewrite Rmult_assoc.\nrepeat rewrite (Rmult_comm (Fnum y)).\nrepeat rewrite <- Rmult_assoc.\nrepeat rewrite Zmult_assoc_reverse; auto.\nQed.\n \nTheorem oneZplus :\n forall x y : Z,\n Float 1%nat (x + y) = Fmult (Float 1%nat x) (Float 1%nat y).\nintros x y; unfold Fmult in |- *; auto.\nQed.\nEnd operations.\nHint Resolve Fabs_Fzero: float.\nHint Resolve Fzero_opp: float.", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/Fop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7219103096232304}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* This is a scratch pad for dealing with Chapter 2 of Using Z: Specification, Refinement, Proof *)\nTheorem and_comm : forall P Q : Prop, P /\\ Q -> Q /\\ P.\nProof.\n  (* TYLER: Ok, I'm doing this in CoqIDE, like a god-damn Caveman... \n            I switched to vim a while ago, and I just really dont want\n            to jack with anything.\n\n            So before I critique (hmm, no spelling... just bare with me)\n            let's just write this out by hand:\n       Assuming I know P and Q, can I show Q and P?\n         to show Q and P, I must first show Q, then P\n         I know Q\n         I know P\n         QED.\n\n      What does this look like in Coq?*)\n  intros P Q [HP HQ].\n  split.\n  - apply HQ.\n  - apply HP.\nQed.\n\n\n(* Here's an attempt to redo it using SSReflect *)\nTheorem and_comm' : forall P Q : Prop, P /\\ Q -> Q /\\ P.\nProof.\n  (* TYLER: Yeah, I've... literally never used ssreflect before, so\n            reading up really quick...\n  *)\n  move => P Q [HP HQ].\n  by split.\nQed.\n\nTheorem disj_comm : forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q H.\n  destruct H. right. apply H.\n  left. apply H.\nQed.\n\n(* and here's disj_comm in ssreflect *)\nTheorem disj_comm' : forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof. move => P Q. by case; [right | left]. Qed.\n\n(* Here's another proof from Using Z *)\nTheorem paqir_implies_piqir : forall P Q R : Prop, (P /\\ Q -> R) -> (P -> (Q -> R)).\nProof.\n  intros P Q R H HP HQ.\n  assert (HPQ: P /\\ Q).\n  split. exact HP. exact HQ.\n  pose (HR := H HPQ).\n  exact HR.\n  (* I worry this is on the ugly side for what I'm trying to do. *)\nQed.\n\n(* TYLER: Yeah, that was ugly. Let me try: *)\nTheorem paqir_implies_piqir' : forall P Q R : Prop, (P /\\ Q -> R) -> (P -> (Q -> R)).\nProof.\n  intros P Q R H HP HQ.\n  assert (HPQ: P /\\ Q). split. exact HP. exact HQ.\n  apply H. exact HPQ.\nQed.\n(* TYLER: So I have never used pose before. Seems fine. So bassically the same *)\n\n(* These two were stolen from a tutorial *)\n\nTheorem backward_small : (forall A B : Prop,  A -> (A -> B) -> B).\nProof.\n  intros A B.\n  intros proof_of_A A_implies_B.\n  refine (A_implies_B _).\n  exact proof_of_A.\nQed.\n\nTheorem forward_small : forall A B : Prop, A -> (A -> B) -> B.\nProof.\n  intros A B proof_of_A A_implies_B.\n  pose (proof_of_B := A_implies_B proof_of_A).\n  exact proof_of_B.\nQed.\n\nLemma p_and_q_implies_p A B : A /\\ B -> A.\nProof.\n  move => [HA _].\n    by [].\nQed.\n\n(* This is Example 2.9 from _Using Z_ *)\n\nTheorem p_stronger_q : forall P Q : Prop, (P -> Q) -> (P /\\ Q) <-> P.\nProof.\n  intros P Q H.\n  split.\n  - (* P /\\ Q -> P *) intros [HP HQ].\n    apply HP.\n  - (* P -> P /\\ Q *) intros HP.\n    pose (H2 := conj HP (H HP)).\n    apply H2.\n    (* alternate approach, instead of 'pose...': \n    apply H in HP as HQ.\n    apply conj. apply HP. apply HQ. *)\nQed.\n\nLemma my_demorgan1 P Q : ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\n  intros H.\n  split.\n  - (* ~ (P \\/ Q) -> ~P *) intro HP. apply H. left. exact HP.\n  - (* ~ (P \\/ Q) -> ~Q *) intro HQ. apply H. right. exact HQ.\nQed.\n", "meta": {"author": "fusiongyro", "repo": "ztools", "sha": "a34d5ef567fdc8d1ec7535d2671541aeb388ca42", "save_path": "github-repos/coq/fusiongyro-ztools", "path": "github-repos/coq/fusiongyro-ztools/ztools-a34d5ef567fdc8d1ec7535d2671541aeb388ca42/Z.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7218888460413122}}
{"text": "(* \n  Author(s):\n    Dominique Larchey-Wendling (1)\n    Andrej Dudenhefner (2)\n    Johannes Hostert (2)\n  Affiliation(s):\n    (1) LORIA -- CNRS\n    (2) Saarland University, Saarbrücken, Germany\n*)\n\n(** * Satisfiability of elementary, square, and uniform Diophantine constraints H10C_SAT, H10SQC_SAT, and H10UC_SAT *)\n\n(* \n  Problems(s):\n    Diophantine Constraint Solvability (H10C_SAT)\n    Square Diophantine Constraint Solvability (H10SQC_SAT)\n    Uniform Diophantine Constraint Solvability (H10UC_SAT)\n    Uniform Diophantine Pair Constraint Solvability (H10UPC_SAT)\n*)\n\nRequire Import List.\n\n(* Diophantine constraints (h10c) are of three shapes:\n      x = 1 | x + y = z | x * y = z  with x, y, z in nat \n*)\n\nInductive h10c : Set :=\n  | h10c_one : nat -> h10c\n  | h10c_plus : nat -> nat -> nat -> h10c\n  | h10c_mult : nat -> nat -> nat -> h10c.\n  \nDefinition h10c_sem c φ :=\n  match c with\n    | h10c_one x      => φ x = 1\n    | h10c_plus x y z => φ x + φ y = φ z\n    | h10c_mult x y z => φ x * φ y = φ z\n  end.\n\n(*\n  Diophantine Constraint Solvability:\n    given a list of Diophantine constraints, is there a valuation that satisfies each constraint?\n*)\nDefinition H10C_SAT (cs: list h10c) := exists (φ: nat -> nat), forall c, In c cs -> h10c_sem c φ.\n\n(* Square Diophantine constraints are of three shapes:\n      x = 1 | x + y = z | x * x = y  with x, y, z in nat \n*)\n\nInductive h10sqc : Set :=\n  | h10sqc_one : nat -> h10sqc\n  | h10sqc_plus : nat -> nat -> nat -> h10sqc\n  | h10sqc_sq : nat -> nat -> h10sqc.\n\nDefinition h10sqc_sem φ c :=\n  match c with\n    | h10sqc_one x      => φ x = 1\n    | h10sqc_plus x y z => φ x + φ y = φ z\n    | h10sqc_sq x y => φ x * φ x = φ y\n  end.\n\n(*\n  Square Diophantine Constraint Solvability:\n    given a list of Diophantine constraints, is there a valuation that satisfies each constraint?\n*)\nDefinition H10SQC_SAT (cs: list h10sqc) := exists (φ: nat -> nat), forall c, In c cs -> h10sqc_sem φ c.\n\n(* Uniform Diophantine constraints (h10uc) are of shape:  \n      1 + x + y * y = z\n*)\nDefinition h10uc := (nat * nat * nat)%type.\n\nDefinition h10uc_sem φ (c : h10uc) :=\n  match c with \n    | (x, y, z) => 1 + φ x + φ y * φ y = φ z\n  end.\n\n(*\n  Uniform Diophantine Constraint Solvability:\n    given a list of uniform Diophantine constraints, is there a valuation that satisfies each constraint?\n*)\nDefinition H10UC_SAT (cs: list h10uc) := exists (φ: nat -> nat), forall c, In c cs -> h10uc_sem φ c.\n\n\n(* Uniform Diophantine pairs constraints (h10upc) are of shape:  \n    (x, y) # (1 + x + y, y * (1 + y) / 2)\n*)\nDefinition h10upc := ((nat * nat) * (nat * nat))%type.\n\n\n(** Direct semantics of h10upc_sem *)\nDefinition h10upc_sem_direct (c : h10upc) :=\n  match c with \n    | ((x, y), (z1, z2)) => \n        1 + x + y = z1 /\\ y * (1 + y) = z2 + z2\n  end.\n\nDefinition h10upc_sem φ (c : h10upc) :=\n  match c with \n    | ((x, y), (z1, z2)) => h10upc_sem_direct (φ x, φ y, (φ z1, φ z2))\n  end.\n\n(*\n  Uniform Diophantine Pair Constraint Solvability:\n    given a list of uniform Diophantine pair constraints, \n    is there a valuation that satisfies each constraint?\n*)\nDefinition H10UPC_SAT (cs: list h10upc) := \n  exists (φ: nat -> nat), forall c, In c cs -> h10upc_sem φ c.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/DiophantineConstraints/H10C.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7218540531441103}}
{"text": "Require Export TopologicalSpaces.\nRequire Export InverseImage.\nRequire Export Continuity.\n\nSection StrongTopology.\n\nVariable A:Type.\nVariable X:forall a:A, TopologicalSpace.\nVariable Y:Type.\nVariable f:forall a:A, point_set (X a) -> Y.\n\nDefinition strong_open (S:Ensemble Y) : Prop :=\n  forall a:A, open (inverse_image (f a) S).\n\nDefinition StrongTopology : TopologicalSpace.\nrefine (Build_TopologicalSpace Y strong_open _ _ _).\nintros.\nred; intro.\nassert (inverse_image (f a) (FamilyUnion F) =\n  IndexedUnion (fun U:{ U:Ensemble Y | In F U } =>\n                 inverse_image (f a) (proj1_sig U))).\napply Extensionality_Ensembles; red; split; red; intros.\ndestruct H0.\ninversion H0.\nexists (exist _ S H1).\nconstructor.\nexact H2.\n\ndestruct H0.\ndestruct H0.\ndestruct a0 as [U].\nconstructor.\nexists U; trivial.\n\nrewrite H0.\napply open_indexed_union.\nintros.\ndestruct a0 as [U].\nsimpl.\napply H; trivial.\n\nintros.\nred; intro.\nrewrite inverse_image_intersection.\napply open_intersection2; (apply H || apply H0).\n\nred; intro.\nrewrite inverse_image_full.\napply open_full.\nDefined.\n\nLemma strong_topology_makes_continuous_funcs:\n  forall a:A, continuous (f a) (Y:=StrongTopology).\nProof.\nintros.\nred.\nintros.\nauto.\nQed.\n\nLemma strong_topology_strongest: forall (T':Ensemble Y->Prop)\n  (H1:_) (H2:_) (H3:_),\n  (forall a:A, continuous (f a)\n          (Y:=Build_TopologicalSpace Y T' H1 H2 H3)) ->\n  forall V:Ensemble Y, T' V -> strong_open V.\nProof.\nintros.\nunfold continuous in H.\nsimpl in H.\nred; intros; apply H; trivial.\nQed.\n\nEnd StrongTopology.\n\nImplicit Arguments StrongTopology [[A] [X] [Y]].\n", "meta": {"author": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/StrongTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7218540428215205}}
{"text": "Require Import init.\n\nRequire Import order_mult.\n\nDefinition min {U} `{Order U} x y :=\n    If (x ≤ y) then x else y.\nDefinition max {U} `{Order U} x y :=\n    If (x ≤ y) then y else x.\n\n(* begin hide *)\nSection MinMax.\n\nContext {U} `{OrderedField U}.\n(* end hide *)\nTheorem min_leq : ∀ a b, a ≤ b → min a b = a.\nProof.\n    intros a b leq.\n    unfold min; case_if [leq'|leq'].\n    -   reflexivity.\n    -   contradiction.\nQed.\nTheorem min_req : ∀ a b, b ≤ a → min a b = b.\nProof.\n    intros a b leq.\n    unfold min; case_if [leq'|leq'].\n    -   exact (antisym leq' leq).\n    -   reflexivity.\nQed.\nTheorem max_leq : ∀ a b, b ≤ a → max a b = a.\nProof.\n    intros a b leq.\n    unfold max; case_if [leq'|leq'].\n    -   exact (antisym leq leq').\n    -   reflexivity.\nQed.\nTheorem max_req : ∀ a b, a ≤ b → max a b = b.\nProof.\n    intros a b leq.\n    unfold max; case_if [leq'|leq'].\n    -   reflexivity.\n    -   contradiction.\nQed.\n\nTheorem min_comm : ∀ a b, min a b = min b a.\nProof.\n    intros a b.\n    destruct (connex a b) as [leq|leq].\n    -   rewrite min_leq, min_req by exact leq.\n        reflexivity.\n    -   rewrite min_req, min_leq by exact leq.\n        reflexivity.\nQed.\n\nTheorem max_comm : ∀ a b, max a b = max b a.\nProof.\n    intros a b.\n    destruct (connex a b) as [leq|leq].\n    -   rewrite max_req, max_leq by exact leq.\n        reflexivity.\n    -   rewrite max_leq, max_req by exact leq.\n        reflexivity.\nQed.\n\nTheorem min_assoc : ∀ a b c, min a (min b c) = min (min a b) c.\nProof.\n    intros a b c.\n    destruct (connex a b) as [ab|ab].\n    -   rewrite (min_leq a b ab).\n        destruct (connex b c) as [bc|bc].\n        +   rewrite (min_leq b c bc).\n            rewrite (min_leq a b ab).\n            rewrite (min_leq a c (trans ab bc)).\n            reflexivity.\n        +   rewrite (min_req b c bc).\n            reflexivity.\n    -   rewrite (min_req a b ab).\n        destruct (connex b c) as [bc|bc].\n        +   rewrite (min_leq b c bc).\n            exact (min_req a b ab).\n        +   rewrite (min_req b c bc).\n            exact (min_req a c (trans bc ab)).\nQed.\n\nTheorem max_assoc : ∀ a b c, max a (max b c) = max (max a b) c.\nProof.\n    intros a b c.\n    destruct (connex a b) as [ab|ab].\n    -   rewrite (max_req a b ab).\n        destruct (connex b c) as [bc|bc].\n        +   rewrite (max_req b c bc).\n            exact (max_req a c (trans ab bc)).\n        +   rewrite (max_leq b c bc).\n            exact (max_req a b ab).\n    -   rewrite (max_leq a b ab).\n        destruct (connex b c) as [bc|bc].\n        +   rewrite (max_req b c bc).\n            reflexivity.\n        +   rewrite (max_leq b c bc).\n            rewrite (max_leq a c (trans bc ab)).\n            exact (max_leq a b ab).\nQed.\n\nTheorem rmin : ∀ a b, min a b ≤ b.\nProof.\n    intros a b.\n    destruct (connex a b) as [ab|ab].\n    -   rewrite (min_leq a b ab).\n        exact ab.\n    -   rewrite (min_req a b ab).\n        apply refl.\nQed.\nTheorem lmin : ∀ a b, min a b ≤ a.\nProof.\n    intros a b.\n    rewrite min_comm.\n    apply rmin.\nQed.\n\nTheorem lmax : ∀ a b, a ≤ max a b.\nProof.\n    intros a b.\n    destruct (connex a b) as [ab|ab].\n    -   rewrite (max_req a b ab).\n        exact ab.\n    -   rewrite (max_leq a b ab).\n        apply refl.\nQed.\nTheorem rmax : ∀ a b, b ≤ max a b.\nProof.\n    intros a b.\n    rewrite max_comm.\n    apply lmax.\nQed.\n\nTheorem min_max_plus : ∀ a b, min a b + max a b = a + b.\nProof.\n    intros a b.\n    destruct (connex a b) as [ab|ab].\n    -   rewrite (min_leq a b ab), (max_req a b ab).\n        reflexivity.\n    -   rewrite (min_req a b ab), (max_leq a b ab).\n        apply plus_comm.\nQed.\n(* begin hide *)\nEnd MinMax.\n(* end hide *)\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Algebra/Relation/order_minmax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7218313468856029}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus z (mult z x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj214_coqofml_MkgxA6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7216727946030592}}
{"text": "Require Import Classical.\n\nLemma ex1 : forall a b:Prop, a \\/ (a -> b).\nProof.\n  intros a b.\n  classical_right.\n  intro H0.\n  contradiction. (* temos ~a  e a *)\nQed.\n\nLemma ex2 : forall a b:Prop, ((a -> b) /\\ ~b) -> ~a.\nProof.\n  intros a b H.\n  destruct H as [H1 H2].\n  intro H0.\n  absurd b.\n  - exact H2.\n\n  - cut a.\n    exact H1. exact H0.\nQed.\n\nLemma ex3 : forall A:Set, forall P Q:(A -> Prop), \nforall x:A,(forall x:A, (P x) -> (Q x)) -> ((forall x:A,(P x)) -> (exists x:A,(Q x))).\nProof.\n  intros A P Q X H H0.\n  exists X.\n  cut (P X).\n  apply H. apply H0.\nQed.\n", "meta": {"author": "dario-santos", "repo": "deductive-verification", "sha": "8a8147baa714a0df3d36014e4f7d795a0e3d0930", "save_path": "github-repos/coq/dario-santos-deductive-verification", "path": "github-repos/coq/dario-santos-deductive-verification/deductive-verification-8a8147baa714a0df3d36014e4f7d795a0e3d0930/TP2/ex1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7216727944179647}}
{"text": "Local Set Warnings \"-notation-overridden\".\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice fintype tuple.\nFrom mathcomp Require Import fingroup.\nLocal Set Warnings \"all\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Def.\n  Variable K M C : finType.\n\n  Record impl := Impl {enc : K -> M -> C; dec : K -> C -> M}.\n\n  Definition correct (i : impl)\n    := forall k, cancel (enc i k) (dec i k).\n  Definition secure (i : impl)\n    := exists n, forall c m, #|[pred k | enc i k m == c]| = n.\n\nEnd Def.\n\n\nSection Theory.\n  Variable K M C : finType.\n  Variable i : impl K M C.\n  Hypothesis correct_i : correct i.\n  Hypothesis secure_i : secure i.\n  Variable (k0 : K) (m0 : M).\n\n  Theorem card_ciphertext_ge : #|M| <= #|C|.\n  Proof.\n    rewrite -(cardC (mem_seq (image (enc i k0) M))).\n    apply/(leq_trans _ (leq_addr _ _)).\n    rewrite card_image => //.\n    by apply (can_inj (correct_i k0)).\n  Qed.\n\n  Theorem card_key_ge : #|C| <= #|K|.\n  Proof.\n    have find_k : forall c m, exists k, enc i k m == c.\n    {\n      move=> c m.\n      move: secure_i => [n Hsecuren].\n      have Hgtn : 0 < n.\n      {\n        rewrite -(Hsecuren (enc i k0 m0) m0).\n        by apply/card_gt0P; exists k0; rewrite inE.\n      }\n      move: Hgtn; rewrite -(Hsecuren c m).\n      by move/card_gt0P => [k Hk]; exists k.\n    }\n    pose fun_c2k c := xchoose (find_k c m0).\n    rewrite -(cardC (mem_seq (image fun_c2k C))).\n    apply/(leq_trans _ (leq_addr _ _)).\n    rewrite card_image => //.\n    apply (can_inj (g:=(enc i)^~ m0)).\n    move=> c; rewrite /fun_c2k.\n    by apply (eqP (xchooseP (find_k _ _))).\n  Qed.\nEnd Theory.\n\n\nSection OneTimePad.\n  Variable T : finGroupType.\n\n  Definition one_time_pad : impl T T T\n    := Impl mulg (mulg \\o invg).\n\n  Theorem correct_otp : correct one_time_pad.\n  Proof.\n    move=> k m /=. by rewrite mulgA mulVg mul1g.\n  Qed.\n\n  Theorem secure_otp : secure one_time_pad.\n  Proof.\n    exists 1.\n    move=> c m /=.\n    apply (eq_card1 (x:=(c * m^-1)%g)).\n    move=> k.\n    rewrite !inE.\n    rewrite -(inj_eq (mulIg (invg m))).\n    by rewrite -mulgA mulgV mulg1.\n  Qed.\nEnd OneTimePad.\n\n\nSection Pair.\n  Variable K1 M1 C1 : finType.\n  Variable i1 : impl K1 M1 C1.\n  Hypothesis correct_i1 : correct i1.\n  Hypothesis secure_i1 : secure i1.\n\n  Variable K2 M2 C2 : finType.\n  Variable i2 : impl K2 M2 C2.\n  Hypothesis correct_i2 : correct i2.\n  Hypothesis secure_i2 : secure i2.\n\n  Local Notation K := [finType of (K1 * K2)].\n  Local Notation M := [finType of (M1 * M2)].\n  Local Notation C := [finType of (C1 * C2)].\n\n  Definition compose_pair : impl K M C\n    := Impl\n         (fun '(k1, k2) '(m1, m2) => (enc i1 k1 m1, enc i2 k2 m2))\n         (fun '(k1, k2) '(c1, c2) => (dec i1 k1 c1, dec i2 k2 c2)).\n\n  Theorem correct_compose_pair : correct compose_pair.\n  Proof.\n    by move=> [k1 k2] [m1 m2] /=; rewrite correct_i1 correct_i2.\n  Qed.\n\n  Theorem secure_compose_pair : secure compose_pair.\n  Proof.\n    move: secure_i1 => [n1 Hsecure1].\n    move: secure_i2 => [n2 Hsecure2].\n    exists (n1 * n2) => [[c1 c2] [m1 m2]].\n    rewrite -(Hsecure1 c1 m1) -(Hsecure2 c2 m2) -cardX.\n    apply eq_card => [[k1 k2]].\n    by rewrite !inE /=.\n  Qed.\nEnd Pair.\n\n\nSection BijectTuplePair.\n  Variable T : Type.\n  Variable n : nat.\n\n  Definition pair_to_tuple_cons (p : (T * n.-tuple T)) := [tuple of p.1 :: p.2].\n  Definition tuple_cons_to_pair (t : n.+1.-tuple T) := (thead t, behead_tuple t).\n\n  Theorem can_pttc_tctp : cancel pair_to_tuple_cons tuple_cons_to_pair.\n  Proof.\n    move=> [h t].\n    rewrite /pair_to_tuple_cons /tuple_cons_to_pair /= theadE.\n    set ht := tuple _.\n    suff H : t = behead_tuple ht by rewrite H.\n    rewrite {}/ht.\n    apply/eq_from_tnth => i.\n    by rewrite tnth_behead !(tnth_nth h) /= inordK // ltnS.\n  Qed.\n\n  Theorem can_tctp_pttc : cancel tuple_cons_to_pair pair_to_tuple_cons.\n  Proof.\n    move=> t.\n    rewrite /pair_to_tuple_cons /tuple_cons_to_pair /=.\n    by symmetry; apply tuple_eta.\n  Qed.\n\n  Theorem bij_tctp : bijective tuple_cons_to_pair.\n  Proof. exact (Bijective can_tctp_pttc can_pttc_tctp). Qed.\nEnd BijectTuplePair.\n\nArguments bij_tctp {T n}.\n\n\nSection Tuple.\n  Variable K0 M0 C0 : finType.\n  Variable i0 : impl K0 M0 C0.\n  Hypothesis correct_i0 : correct i0.\n  Hypothesis secure_i0 : secure i0.\n  Variable n : nat.\n  Local Notation K := [finType of (n.-tuple K0)].\n  Local Notation M := [finType of (n.-tuple M0)].\n  Local Notation C := [finType of (n.-tuple C0)].\n\n  Definition lift_tuple2 {A B C} (f : A -> B -> C) (a : n.-tuple A) (b : n.-tuple B)\n    := map_tuple (prod_curry f) (zip_tuple a b).\n\n  Definition compose : impl K M C\n    := Impl (lift_tuple2 (enc i0)) (lift_tuple2 (dec i0)).\n\n  Lemma tnth_zip {A B} n' (a : n'.-tuple A) (b : n'.-tuple B) j\n    : tnth (zip_tuple a b) j = (tnth a j, tnth b j).\n  Proof.\n    rewrite /tnth nth_zip_cond size_zip !size_tuple minnn ltn_ord.\n    by apply injective_projections; apply set_nth_default; rewrite size_tuple ltn_ord.\n  Qed.\n\n  Theorem correct_compose : correct compose.\n  Proof.\n    move=> k m /=; apply eq_from_tnth => j /=.\n    by rewrite tnth_map tnth_zip tnth_map tnth_zip /prod_curry correct_i0.\n  Qed.\n\n  Theorem secure_compose : secure compose.\n  Proof.\n    move: secure_i0 => [l Hsecure]; exists (l^n) => c m.\n    rewrite /compose /lift_tuple2 /=.\n    have cHsecure cm := Hsecure cm.1 cm.2.\n    elim: n c m => [|n' IHn] c m.\n    {\n      rewrite expn0.\n      rewrite (eq_card1 (x:=[tuple])) // => k.\n      rewrite !inE.\n      by rewrite [k]tuple0 [c]tuple0 [map_tuple _ _]tuple0.\n    }\n    {\n      rewrite expnS.\n      rewrite -(IHn (behead_tuple c) (behead_tuple m)).\n      rewrite -(Hsecure (thead c) (thead m)).\n      rewrite -cardX.\n      rewrite !cardE -(size_map (@tuple_cons_to_pair _ _)).\n      apply perm_size.\n      apply uniq_perm;\n        [by rewrite (map_inj_uniq (bij_inj bij_tctp)); apply enum_uniq|exact: enum_uniq|]\n        => [[headk tailk]].\n      rewrite -{1}[(headk, tailk)]can_pttc_tctp (mem_map (bij_inj bij_tctp)) !mem_enum !inE.\n      apply/(sameP idP)/(iffP idP).\n      {\n        move=> /andP [Hheadk Htailk].\n        apply/eqP/eq_from_tnth => j.\n        rewrite [m]tuple_eta [c]tuple_eta.\n        rewrite tnth_map tnth_zip /prod_curry.\n        move: j => [[|j] Hj].\n        {\n          rewrite (_:Hj=ltn0Sn n'); last by apply bool_irrelevance.\n          by rewrite !tnth0; apply/eqP.\n        }\n        {\n          rewrite (tnth_nth (headk)) (tnth_nth (thead m)) (tnth_nth (thead c)) /=.\n          rewrite (_ : behead c = behead_tuple c) //.\n          rewrite ltnS in Hj.\n          pose oj := Ordinal Hj.\n          rewrite (_:j=oj) //.\n          rewrite -!tnth_nth.\n          rewrite -(eqP Htailk).\n          by rewrite tnth_map tnth_zip /prod_curry.\n        }\n      }\n      {\n        move=> /eqP <- /=.\n        apply/andP; split.\n        { by rewrite /thead tnth_map tnth_zip. }\n        {\n          apply/eqP/eq_from_tnth => j.\n          rewrite tnth_behead !tnth_map !tnth_zip /=.\n          rewrite {2}[m]tuple_eta.\n          rewrite [tnth _ (inord _)](tnth_nth headk).\n          rewrite [tnth _ (inord _)](tnth_nth (thead m)).\n          rewrite inordK /=; last by rewrite ltnS.\n          by rewrite -!tnth_nth.\n        }\n      }\n    }\n  Qed.\nEnd Tuple.\n", "meta": {"author": "HMPerson1", "repo": "formal-crypto", "sha": "046ca80169b26aa1b37fff244d5406a5ded97e65", "save_path": "github-repos/coq/HMPerson1-formal-crypto", "path": "github-repos/coq/HMPerson1-formal-crypto/formal-crypto-046ca80169b26aa1b37fff244d5406a5ded97e65/SymKeyEnc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7216718696557233}}
{"text": "Section tbool.\n\n  (*\n   *    I Logique à trois valeurs\n   *)\n  \n  Variable T: Set.\n  \n  (* V, F et P en Coq *)\n  Definition tbool := T -> T -> T -> T.\n  Definition tv : tbool := fun x y z => x.\n  Definition tf : tbool := fun x y z => y.\n  Definition tp : tbool := fun x y z => z.\n\n  (* CONDITION *)\n  (* Les tbool sont des fonctions a 3 paramètres qui renvoient l'un de ces paramètre(le premier pour vrai, le second pour faux et le troisième pour peut-être), le if s'obtient en appliquant un tbool à trois arguments*)\n  Definition tif : tbool -> T -> T -> T -> T := fun tb x y z=> tb x y z.\n  \n  Variable m n o : T.\n  Fact tif_v : tif tv m n o = m.\n  Proof.\n    cbv delta [tif].\n    cbv beta.\n    cbv delta [tv].\n    cbv beta.\n    reflexivity.\n  Qed.\n  Fact tif_f : tif tf m n o = n. Proof. reflexivity. Qed.\n  Fact tif_p : tif tp m n o = o. Proof. reflexivity. Qed.\n\n  (* NEGATION *)\n  (* V -> F\n     F -> V\n     P -> P\n     On peut donc traduire la négation du tbool b de la forme 'Lambda x y z . r' ou r est soit x, soit y, soit z\n     Par:\n       SI b vaut tv (b renvoie le 1er argument ie. r=x) ALORS ON DOIT RENVOYER y\n       SINON si b vaut tf (b renvoie le 2nd argument ie. r=y) ALORS ON DOIT RENVOYER x\n       SINON (b renvoie le 3eme argument ie. r=z) ON DOIT RENVOYER z \n   *)\n  Definition tnot : tbool -> tbool := fun tb => fun x y z => tb y x z. \n    \n  Fact tnot_v : tnot tv = tf.\n  Proof.\n    cbv delta [tnot].\n    cbv beta.\n    cbv delta [tif].\n    cbv beta.\n    cbv delta [tv].\n    cbv delta [tf].\n    cbv beta.\n    reflexivity.\n  Qed.\n  Fact tnot_f : tnot tf = tv. Proof. reflexivity. Qed.\n  Fact tnot_p : tnot tp = tp. Proof. reflexivity. Qed.\n\n  (* CONJONCTION *)\n  (* \n    Soit deux tbool a et b. La conjonction de ces deux tbool sera un tbool c de la forme 'Lambda x y z . r'. \n    Que vaut r?\n    On distingue plusieurs cas:\n    -a vaut tv:\n        -c sera égal à b, donc r vaut b x y z\n    -a vaut tf:\n        -c sera égal à tf, donc r vaut y\n    -a vaut tp:\n        -si b vaut tv: r vaut z\n        -si b vaut tf: r vaut y\n        -si b vaut tp: r vaut z\n   *)\n  Definition tand : tbool -> tbool -> tbool := fun a b => fun x y z => a (b x y z) y (b z y z).\n\n  Fact tand_vv : tand tv tv = tv. Proof. reflexivity. Qed.\n  Fact tand_vf : tand tv tf = tf. Proof. reflexivity. Qed.\n  Fact tand_vp : tand tv tp = tp. Proof. reflexivity. Qed.\n  Fact tand_fv : tand tf tv = tf. Proof. reflexivity. Qed.\n  Fact tand_ff : tand tf tf = tf. Proof. reflexivity. Qed.\n  Fact tand_fp : tand tf tp = tf. Proof. reflexivity. Qed.\n  Fact tand_pv : tand tp tv = tp. Proof. reflexivity. Qed.\n  Fact tand_pf : tand tp tf = tf. Proof. reflexivity. Qed.\n  Fact tand_pp : tand tp tp = tp. Proof. reflexivity. Qed.\n\n  (* DISJONCTION *)\n  (* \n    Soit deux tbool a et b. La disjonction de ces deux tbool sera un tbool c de la forme 'Lambda x y z . r'. \n    Que vaut r?\n    On distingue plusieurs cas:\n    -a vaut tv:\n        -c sera égal à tv, donc r vaut x\n    -a vaut tf:\n        -c sera égal à b, donc r vaut b x y z\n    -a vaut tp:\n        -si b vaut tv: r vaut x\n        -si b vaut tf: r vaut z\n        -si b vaut tp: r vaut z\n   *)\n  Definition tor : tbool -> tbool -> tbool := fun a b => fun x y z => a x (b x y z) (b x z z).\n\n  Fact tor_vv : tor tv tv = tv. Proof. reflexivity. Qed.\n  Fact tor_vf : tor tv tf = tv. Proof. reflexivity. Qed.\n  Fact tor_vp : tor tv tp = tv. Proof. reflexivity. Qed.\n  Fact tor_fv : tor tf tv = tv. Proof. reflexivity. Qed.\n  Fact tor_ff : tor tf tf = tf. Proof. reflexivity. Qed.\n  Fact tor_fp : tor tf tp = tp. Proof. reflexivity. Qed.\n  Fact tor_pv : tor tp tv = tv. Proof. reflexivity. Qed.\n  Fact tor_pf : tor tp tf = tp. Proof. reflexivity. Qed.\n  Fact tor_pp : tor tp tp = tp. Proof. reflexivity. Qed.\n  \nEnd tbool.\n\n(*\n *    II Programmation en Lambda-calcul polymorphe\n *)\n\n(* 2.1 Type de l'identite polymorphe *)\n(* 1. *)\nDefinition tid : Set := forall T: Set, T -> T.\nDefinition id : tid := fun T:Set => fun x:T => x.\n\n(*Exemple :*)\nCompute id nat 3 .\nCompute id nat 0.\nCompute id bool true.\nCompute id bool false.\n\n(* 2. *)\nDefinition nbtrue1 := fun b =>\n                        match b with true => 1 | false => 0 end.\nDefinition nbfalse1 := fun b =>\n                         match b with false => 1 | true => 0 end.\nCompute id (bool->nat) nbtrue1.\nCompute id (bool->nat) nbfalse1.\n\n(* 3. *)\nCompute id (tid) id.\n\n(* 4. *)\nTheorem th_id : forall T: Set, forall x: T, id T x = x.\nProof.\n  intros.\n  cbv delta [id].\n  cbv beta.\n  reflexivity.\nQed.\n\n(* 2.2 Booléens avec typage polymorphe *)\n(* 1. *)\nDefinition pbool : Set := forall T:Set, T -> T -> T.\nDefinition ptr : pbool := fun T:Set => fun x y => x.\nDefinition pfa : pbool := fun T:Set => fun x y => y.\n\n(* 2 *)\nDefinition pneg : pbool -> pbool := fun b:pbool => fun T => fun x y => b T y x.\nCompute pneg ptr.\nCompute pneg pfa.\n\nDefinition pif : forall T:Set, pbool -> T -> T -> T := fun T => fun b:pbool => fun x y => b T x y.\nCompute pif nat ptr 1 2.\nCompute pif nat pfa 1 2.\n\nDefinition pneg2 : pbool -> pbool := fun b:pbool => pif pbool b ptr pfa.\nCompute pneg2 ptr.\nCompute pneg2 pfa.\n\n(* 3. *)\n(* CONJONCTION *)\nDefinition pand : pbool -> pbool -> pbool := fun a b : pbool => a pbool b pfa.\nFact pand_vv: pand ptr ptr = ptr. Proof. reflexivity. Qed.\nFact pand_vf: pand ptr pfa = pfa. Proof. reflexivity. Qed.\nFact pand_fv: pand pfa ptr = pfa. Proof. reflexivity. Qed.\nFact pand_ff: pand pfa pfa = pfa. Proof. reflexivity. Qed.\n\n(* DISJONCTION *)\nDefinition por : pbool -> pbool -> pbool := fun a b : pbool => a pbool ptr b.\nFact por_vv: por ptr ptr = ptr. Proof. reflexivity. Qed.\nFact por_vf: por ptr pfa = ptr. Proof. reflexivity. Qed.\nFact por_fv: por pfa ptr = ptr. Proof. reflexivity. Qed.\nFact por_ff: por pfa pfa = pfa. Proof. reflexivity. Qed.\n\n(* 4. *)\nDefinition f4 : pbool -> nat := fun b:pbool => b nat 3 5.\nCompute f4 ptr.\nCompute f4 pfa.\n\n(* 5. *)\nDefinition f5 : pbool -> (pbool -> pbool):= fun b:pbool => b pbool b.\n\nCheck f5.\n(* f5 est une fonction pbool -> pbool -> pbool *)\n(* On teste f5 pour les différentes valeurs possible: *)\nCompute f5 ptr ptr. (*ptr ptr -> ptr*)\nCompute f5 ptr pfa. (*ptr pfa -> ptr*)\nCompute f5 pfa ptr. (*pfa ptr -> ptr*)\nCompute f5 pfa pfa. (*pfa pfa -> pfa*)\n(* On remarque que f5 a la même table de vérité que por *)\n\n(* Prouvons l'égalité entre f5 et por à l'aide d'un type énuméré *)\n(* Definition d’un type enumerant les numeros *)\nInductive pbool_num : Set := bnt | bnf.\n\n(* Fonction d’association entre numero et booleen *)\nDefinition cbool_of := fun n =>\nmatch n with\n| bnt => ptr\n| bnf => pfa\nend.\n\nLemma f5_por: forall a b: pbool_num, f5 (cbool_of a) (cbool_of b) = por (cbool_of a) (cbool_of b). \nProof.\n  intros a b.\n  -destruct a.\n   + unfold cbool_of. reflexivity.\n   + reflexivity.\nQed.\n\n(* 2.3 Logique à trois valeurs *)\n\n(* V, F et P en typage polymorphe *)\nDefinition ptbool : Set := forall T:Set, T -> T -> T -> T.\nDefinition ptv : ptbool := fun T:Set => fun x y z => x.\nDefinition ptf : ptbool := fun T:Set => fun x y z => y.\nDefinition ptp : ptbool := fun T:Set => fun x y z => z.\n\n(* CONDITION *)\nDefinition ptif : forall T:Set, ptbool -> T -> T -> T -> T := fun T => fun b x y z=> b T x y z.\n\nFact ptif_v : ptif nat ptv 1 2 3 = 1.\nProof.\n  cbv delta [ptif].\n  cbv beta.\n  cbv delta [ptv].\n  cbv beta.\n  reflexivity.\nQed.\nFact ptif_f : ptif nat ptf 1 2 3 = 2. Proof. reflexivity. Qed.\nFact ptif_p : ptif nat ptp 1 2 3 = 3. Proof. reflexivity. Qed.\n\n(* NEGATION *)\nDefinition ptnot : ptbool -> ptbool := fun b => fun T => fun x y z => b T y x z. \n\nFact ptnot_v : ptnot ptv = ptf.\nProof.\n  cbv delta [ptnot].\n  cbv beta.\n  cbv delta [ptif].\n  cbv beta.\n  cbv delta [ptv].\n  cbv delta [ptf].\n  cbv beta.\n  reflexivity.\nQed.\nFact ptnot_f : ptnot ptf = ptv. Proof. reflexivity. Qed.\nFact ptnot_p : ptnot ptp = ptp. Proof. reflexivity. Qed.\n\n(* CONJONCTION *)\nDefinition ptand : ptbool -> ptbool -> ptbool := fun a b => fun T => fun x y z => a T (b T x y z) y (b T z y z).\n\nFact ptand_vv : ptand tv tv = tv. Proof. reflexivity. Qed.\nFact ptand_vf : ptand tv tf = tf. Proof. reflexivity. Qed.\nFact ptand_vp : ptand tv tp = tp. Proof. reflexivity. Qed.\nFact ptand_fv : ptand tf tv = tf. Proof. reflexivity. Qed.\nFact ptand_ff : ptand tf tf = tf. Proof. reflexivity. Qed.\nFact ptand_fp : ptand tf tp = tf. Proof. reflexivity. Qed.\nFact ptand_pv : ptand tp tv = tp. Proof. reflexivity. Qed.\nFact ptand_pf : ptand tp tf = tf. Proof. reflexivity. Qed.\nFact ptand_pp : ptand tp tp = tp. Proof. reflexivity. Qed.\n\n(* DISJONCTION *)\nDefinition ptor : ptbool -> ptbool -> ptbool := fun a b => fun T => fun x y z => a T x (b T x y z) (b T x z z).\n\nFact ptor_vv : ptor tv tv = tv. Proof. reflexivity. Qed.\nFact ptor_vf : ptor tv tf = tv. Proof. reflexivity. Qed.\nFact ptor_vp : ptor tv tp = tv. Proof. reflexivity. Qed.\nFact ptor_fv : ptor tf tv = tv. Proof. reflexivity. Qed.\nFact ptor_ff : ptor tf tf = tf. Proof. reflexivity. Qed.\nFact ptor_fp : ptor tf tp = tp. Proof. reflexivity. Qed.\nFact ptor_pv : ptor tp tv = tv. Proof. reflexivity. Qed.\nFact ptor_pf : ptor tp tf = tp. Proof. reflexivity. Qed.\nFact ptor_pp : ptor tp tp = tp. Proof. reflexivity. Qed.\n\n(* 2.4 Produits et sommes avec typage polymorphe *)\n(* 2.4.1 Produits *)\n(* 1. *)\n(* type produit d'un nat et d'un bool *)\nDefinition pprod_nb := forall T:Set, (nat -> bool -> T) -> T.\n\n(* constructeur d’un couple d'un nat et d'un bool *)\nDefinition ppair_nb: nat -> bool -> pprod_nb :=\n  fun a b => fun T => fun k => k a b  .\n\n(* 2. *)\n(* type produit d'un nat et d'un bool *)\nDefinition pprod_bn := forall T:Set, (bool -> nat -> T) -> T.\n\n(* constructeur d’un couple d'un nat et d'un bool *)\nDefinition ppair_bn: bool -> nat -> pprod_bn :=\n  fun a b => fun T => fun k => k a b  .\n\n(* 3. *)\nDefinition echange_nb_bn: pprod_nb -> pprod_bn := fun nb => ppair_bn (nb bool (fun a b => b)) (nb nat (fun a b => a)).\n\n(* exemples *)\nCompute ppair_nb 5 true.\nCompute echange_nb_bn (ppair_nb 5 true).\n\n(* preuve *)\nFact p_echange_nb_bn: forall a:nat, forall b:bool, echange_nb_bn (ppair_nb a b) = ppair_bn b a.\nProof.\n  reflexivity.\nQed.\n\n(* 4. *)\nDefinition pprod : Set -> Set -> Set := fun U V => forall T:Set, (U -> V -> T) -> T.\nDefinition ppair : forall A B:Set, A -> B -> pprod A B := fun A B:Set => fun (a:A) (b:B) => fun T:Set => fun k:(A -> B -> T) => k a b.\n\nCompute ppair nat bool 5 true.\nCompute ppair nat nat 5 7.\nCompute ppair bool nat false 2.\nCompute ppair bool bool true false.\n\n(* 5. *)\nDefinition pprod_nb2 := pprod nat bool.\nDefinition ppair_nb2 := ppair nat bool.  \nFact pprod_nb_pprod : pprod_nb2 = pprod_nb. Proof. reflexivity. Qed.\n\nDefinition pprod_bn2 := pprod bool nat.\nDefinition ppair_bn2 := ppair bool nat. \nFact pprod_bn_pprod : pprod_bn2 = pprod_bn. Proof. reflexivity. Qed.\n\n(* 6. *)\nCompute ppair nat bool 5 true.\nCompute ppair nat bool 7 false.\nCompute ppair bool nat true 5.\nCompute ppair bool nat false 7.\n\n(* 7. *)\nDefinition echange : forall A B:Set, pprod A B -> pprod B A := fun A B => fun c => ppair B A (c B (fun a b =>  b)) (c A (fun a b => a)).\n\n(* 8. *)\nLemma p_echange : forall A B:Set, forall (a:A) (b:B), forall c:pprod A B, c = ppair A B a b -> c = echange B A (echange A B c).\nProof.\n  intros.\n  replace c.\n  cbv delta [echange].\n  cbv delta [ppair].\n  cbv beta.\n  reflexivity.\nQed.\n\n(* 2.4.2 Sommes *)\n(* 1. *)\nDefinition psom (U V : Set) : Set := forall T:Set, (U -> T) -> (V -> T) -> T.\nDefinition C1 (U V: Set) : U -> psom U V := fun u => fun T:Set => fun k1:U->T => fun k2:V->T => k1 u.\nDefinition C2 (U V: Set) : V -> psom U V := fun v => fun T:Set => fun k1:U->T => fun k2:V->T => k2 v.\n\nCompute C1 nat bool 5.\nCompute C2 nat bool true.\n\nVariable t1:psom nat bool .\n\nCompute t1 nat (fun a =>1) (fun b => 2).\n\n(* 2. *)\n(* Section 2 TD 4 *)\nSection S2TD4.\n  (* 1. *)\n  Definition f1 : psom nat bool -> nat := fun c => c nat (fun a => 2*a) (fun b => match b with true => 1 | false => 0 end).\n  Compute f1 (C1 nat bool 5).\n  Compute f1 (C2 nat bool true).\n  Compute f1 (C2 nat bool false).\n\n  (* 2. 3. 4.*)\n  (* On utilise ici les types polymorphes, on n'a donc plus besoin de définir des types destinés à renvoyer un unique type*)\n  Definition f3 : psom nat bool -> pprod bool nat:= fun c => c (pprod bool nat) (fun n => ppair bool nat true n) (fun b => match b with\n                                                                                                            |true => ppair bool nat false 1\n                                                                                                            |false => ppair bool nat false 0 end).\n  Compute f3 (C1 nat bool 5).\n  Compute f3 (C2 nat bool true).\n  Compute f3 (C2 nat bool false).\n  \nEnd S2TD4.\n\n(* 2.5 Entier de Church avec typage polymorphe *)\n(* 1. (Section 2 du TD3) *)\nDefinition pnat := forall T:Set, (T -> T) -> (T -> T).\nDefinition pO:pnat  := fun T:Set => fun (f:T->T) (x:T) => x.\nDefinition pS:pnat->pnat := fun n:pnat => fun T => fun (f:T->T) (x:T) => f (n T f x).\n\nCompute pO.\nCompute pS pO.\n\n(*Redefinition de la notation pour faciliter les tests:*)\nFixpoint iter (n:nat) :=\n  match n with\n    | 0 => pO\n    | S p => pS (iter p)\n  end.\n\nDefinition pnat_of_nat : nat -> pnat := fun n => iter n.\n\nNotation \"[ X ]N\" := (pnat_of_nat X) (at level 5).\nCompute [3]N.\nCompute [0]N.\nCompute [10]N.\n(*On peut désormais utiliser [X]N pour écrire le pnat X.*)\n\nDefinition padd:pnat->pnat->pnat := fun n m :pnat => fun T:Set => fun f x => n T f (m T f x).\n\nCompute padd [1]N [2]N. (* 1 + 2 = 3 *)\nCompute padd [0]N [0]N. (* 0 + 0 = 0 *)\n\nLemma padd_associativite : forall a b c :pnat, padd (padd a b) c = padd a (padd b c).\nProof.\n  intros.\n  cbv delta [padd].\n  cbv beta.\n  reflexivity.\nQed.\n\nDefinition pmul:pnat->pnat->pnat := fun n m :pnat => fun T:Set => fun f =>  n T (m T f).\n\nCompute pmul [2]N [3]N. (* 2 * 3 = 6 *)\n\nDefinition ptz:pnat->pbool := fun n:pnat => fun T:Set =>  fun x y =>  n T (fun z => y) x.\n\nCompute ptz [O]N.\nCompute ptz [1]N.\n\n(* Preuve que ptz renvoie ptr pour l'entier de Church 0. *)\nLemma p_ptz_ptr : (forall c:pnat, c=pO -> ptz c = ptr).\nProof.\n  intros.\n  cbv delta [ptr].\n  cbv delta [ptz].\n  cbv beta.\n  replace c.\n  cbv delta [pO].\n  cbv beta.\n  reflexivity.\nQed.\n\n(* Preuve que ptz renvoie pfa pour tout entier de Church différent de 0 en utilisant un type inductif. *)\nInductive pnat_num :Set :=\n|O :pnat_num\n|S :pnat_num -> pnat_num.\n\nFixpoint pnat_of n :=\n  match n with\n    | O => pO\n    | S n => pS (pnat_of n)\n  end.\n\nLemma p_ptz_pfa : (forall c:pnat_num, pnat_of(c)<>pO -> ptz (pnat_of c) = pfa).\nProof.\n  intros.\n  induction c ; tauto.\nQed.\n\n\n(* 2. *)\nDefinition pplus : pnat -> pnat -> pnat := fun n m : pnat => n pnat pS m.\n(*\nOn peut voir cette version de l'addition n+m comme une application de n fois la fonction successeur pS à m.\n *)\nCompute pplus [4]N [3]N.\nCompute pplus [3]N [0]N.\n\n(* 3. *)\n(* Définition d'une fonction couple_successeur qui pour un couple (x,y) rend le couple (y,S y) ie. renvoie y et son successeur *)\nDefinition couple_successeur : pprod pnat pnat -> pprod pnat pnat := fun c => ppair pnat pnat (c pnat (fun a b => b)) (c pnat (fun a b => pS b)).\nCompute ppair pnat pnat [1]N [2]N.\nCompute couple_successeur (ppair pnat pnat [1]N [2]N).\n\n(* Définition d'une fonction couple_successeur_n qui pour un couple (x,y) lui applique n fois la fonction couple_successeur *)\nDefinition couple_successeur_n : pprod pnat pnat -> pnat -> pprod pnat pnat := fun c n => n (pprod pnat pnat) (couple_successeur) c.\nCompute couple_successeur_n (ppair pnat pnat [0]N [0]N) [5]N.\n\n(* Définition d'une fonction pour un pnat n calcule le prédecesseur:\nL'idée est d'utiliser la fonction couple_successeur avec en argument le couple (0,0) et l'entier n pour ainsi obtenir le couple (n-1,n). On a ainsi facilement accès au prédecceseur de n*)\nDefinition predecesseur : pnat -> pnat := fun n => couple_successeur_n (ppair pnat pnat [0]N [0]N) n pnat (fun a b => a).\nCompute predecesseur [5]N.\nCompute predecesseur [1]N.\n\n(* 4. *)\n", "meta": {"author": "ThomasVandendorpe", "repo": "projetLC", "sha": "d2f6b80b5714beb4ef2e6b63f8850de7fa03498c", "save_path": "github-repos/coq/ThomasVandendorpe-projetLC", "path": "github-repos/coq/ThomasVandendorpe-projetLC/projetLC-d2f6b80b5714beb4ef2e6b63f8850de7fa03498c/lc-projet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7216718686645334}}
{"text": "\n\n\n\n\n(** * Basics: Functional Programming in Coq *)\n\n(* REMINDER:\n\n          #####################################################\n          ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n          #####################################################\n\n   (See the [Preface] for why.)\n*)\n\n(* ################################################################# *)\n(** * Introduction *)\n\n(** The functional programming style is founded on simple, everyday\n    mathematical intuition: If a procedure or method has no side\n    effects, then (ignoring efficiency) all we need to understand\n    about it is how it maps inputs to outputs -- that is, we can think\n    of it as just a concrete method for computing a mathematical\n    function.  This is one sense of the word \"functional\" in\n    \"functional programming.\"  The direct connection between programs\n    and simple mathematical objects supports both formal correctness\n    proofs and sound informal reasoning about program behavior.\n\n    The other sense in which functional programming is \"functional\" is\n    that it emphasizes the use of functions (or methods) as\n    _first-class_ values -- i.e., values that can be passed as\n    arguments to other functions, returned as results, included in\n    data structures, etc.  The recognition that functions can be\n    treated as data gives rise to a host of useful and powerful\n    programming idioms.\n\n    Other common features of functional languages include _algebraic\n    data types_ and _pattern matching_, which make it easy to\n    construct and manipulate rich data structures, and sophisticated\n    _polymorphic type systems_ supporting abstraction and code reuse.\n    Coq offers all of these features.\n\n    The first half of this chapter introduces the most essential\n    elements of Coq's functional programming language, called\n    _Gallina_.  The second half introduces some basic _tactics_ that\n    can be used to prove properties of Coq programs. *)\n\n(* ################################################################# *)\n(** * Data and Functions *)\n(* ================================================================= *)\n(** ** Enumerated Types *)\n\n(** One notable aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers a powerful mechanism for defining new\n    data types from scratch, with all these familiar types as\n    instances.\n\n    Naturally, the Coq distribution comes preloaded with an extensive\n    standard library providing definitions of booleans, numbers, and\n    many common data structures like lists and hash tables.  But there\n    is nothing magic or primitive about these library definitions.  To\n    illustrate this, we will explicitly recapitulate all the\n    definitions we need in this course, rather than just getting them\n    implicitly from the library. *)\n\n(* ================================================================= *)\n(** ** Days of the Week *)\n\n(** To see how this definition mechanism works, let's start with\n    a very simple example.  The following declaration tells Coq that\n    we are defining a new set of data values -- a _type_. *)\n\nInductive day : Type :=\n  | monday \n  | tuesday\n  | wednesday\n  | thursday \n  | friday\n  | saturday\n  | sunday.\n\n(** The type is called [day], and its members are [monday],\n    [tuesday], etc.  \n\n    Having defined [day], we can write functions that operate on\n    days. *)\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\n(** One thing to note is that the argument and return types of\n    this function are explicitly declared.  Like most functional\n    programming languages, Coq can often figure out these types for\n    itself when they are not given explicitly -- i.e., it can do _type\n    inference_ -- but we'll generally include them to make reading\n    easier. *)\n\n(** Having defined a function, we should check that it works on\n    some examples.  There are actually three different ways to do this\n    in Coq.  First, we can use the command [Compute] to evaluate a\n    compound expression involving [next_weekday]. *)\n\nCompute (next_weekday friday).\n(* ==> monday : day *)\n\nCompute (next_weekday (next_weekday saturday)).\n(* ==> tuesday : day *)\n\n(** (We show Coq's responses in comments, but, if you have a\n    computer handy, this would be an excellent moment to fire up the\n    Coq interpreter under your favorite IDE -- either CoqIde or Proof\n    General -- and try this for yourself.  Load this file, [Basics.v],\n    from the book's Coq sources, find the above example, submit it to\n    Coq, and observe the result.) *)\n\n(** Second, we can record what we _expect_ the result to be in the\n    form of a Coq example: *)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n(** This declaration does two things: it makes an\n    assertion (that the second weekday after [saturday] is [tuesday]),\n    and it gives the assertion a name that can be used to refer to it\n    later.  Having made the assertion, we can also ask Coq to verify\n    it, like this: *)\n\nProof. simpl. reflexivity.  Qed.\n\n(** The details are not important for now (we'll come back to\n    them in a bit), but essentially this can be read as \"The assertion\n    we've just made can be proved by observing that both sides of the\n    equality evaluate to the same thing, after some simplification.\"\n\n    Third, we can ask Coq to _extract_, from our [Definition], a\n    program in some other, more conventional, programming\n    language (OCaml, Scheme, or Haskell) with a high-performance\n    compiler.  This facility is very interesting, since it gives us a\n    way to go from proved-correct algorithms written in Gallina to\n    efficient machine code.  (Of course, we are trusting the\n    correctness of the OCaml/Haskell/Scheme compiler, and of Coq's\n    extraction facility itself, but this is still a big step forward\n    from the way most software is developed today.) Indeed, this is\n    one of the main uses for which Coq was developed.  We'll come back\n    to this topic in later chapters. *)\n\n(* ================================================================= *)\n(** ** Homework Submission Guidelines *)\n\n(** If you are using _Software Foundations_ in a course, your\n    instructor may use automatic scripts to help grade your homework\n    assignments.  In order for these scripts to work correctly (so\n    that you get full credit for your work!), please be careful to\n    follow these rules:\n      - The grading scripts work by extracting marked regions of the\n        [.v] files that you submit.  It is therefore important that\n        you do not alter the \"markup\" that delimits exercises: the\n        Exercise header, the name of the exercise, the \"empty square\n        bracket\" marker at the end, etc.  Please leave this markup\n        exactly as you find it.\n      - Do not delete exercises.  If you skip an exercise (e.g.,\n        because it is marked Optional, or because you can't solve it),\n        it is OK to leave a partial proof in your [.v] file, but in\n        this case please make sure it ends with [Admitted] (not, for\n        example [Abort]).\n      - It is fine to use additional definitions (of helper functions,\n        useful lemmas, etc.) in your solutions.  You can put these\n        between the exercise header and the theorem you are asked to\n        prove.\n\n    You will also notice that each chapter (like [Basics.v]) is\n    accompanied by a _test script_ ([BasicsTest.v]) that automatically\n    calculates points for the finished homework problems in the\n    chapter.  These scripts are mostly for the auto-grading\n    infrastructure that your instructor may use to help process\n    assignments, but you may also like to use them to double-check\n    that your file is well formatted before handing it in.  In a\n    terminal window either type [make BasicsTest.vo] or do the\n    following:\n\n       coqc -Q . LF Basics.v \n       coqc -Q . LF BasicsTest.v\n\n    There is no need to hand in [BasicsTest.v] itself (or [Preface.v]).\n*)\n\n(* ================================================================= *)\n(** ** Booleans *)\n\n(** In a similar way, we can define the standard type [bool] of\n    booleans, with members [true] and [false]. *)\n\nInductive bool : Type :=\n  | true \n  | false.\n\n(** Although we are rolling our own booleans here for the sake\n    of building up everything from scratch, Coq does, of course,\n    provide a default implementation of the booleans, together with a\n    multitude of useful functions and lemmas.  (Take a look at\n    [Coq.Init.Datatypes] in the Coq library documentation if you're\n    interested.)  Whenever possible, we'll name our own definitions\n    and theorems so that they exactly coincide with the ones in the\n    standard library.\n\n    Functions over booleans can be defined in the same way as\n    above: *)\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(** The last two of these illustrate Coq's syntax for\n    multi-argument function definitions.  The corresponding\n    multi-argument application syntax is illustrated by the following\n    \"unit tests,\" which constitute a complete specification -- a truth\n    table -- for the [orb] function: *)\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(** We can also introduce some familiar syntax for the boolean\n    operations we have just defined. The [Notation] command defines a new\n    symbolic notation for an existing definition. *)\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5:  false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(** _A note on notation_: In [.v] files, we use square brackets\n    to delimit fragments of Coq code within comments; this convention,\n    also used by the [coqdoc] documentation tool, keeps them visually\n    separate from the surrounding text.  In the HTML version of the\n    files, these pieces of text appear in a [different font].\n\n    The command [Admitted] can be used as a placeholder for an\n    incomplete proof.  We'll use it in exercises, to indicate the\n    parts that we're leaving for you -- i.e., your job is to replace\n    [Admitted]s with real proofs. *)\n\n(** **** Exercise: 1 star (nandb)  *)\n(** Remove \"[Admitted.]\" and complete the definition of the following\n    function; then make sure that the [Example] assertions below can\n    each be verified by Coq.  (I.e., fill in each proof, following the\n    model of the [orb] tests above.) The function should return [true]\n    if either or both of its inputs are [false]. *)\n\nDefinition nandb (b1:bool) (b2:bool) : bool:=\n  match b2 with\n  |true => negb(b1)\n  |false=> true\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(** [] *)\n\n(** **** Exercise: 1 star (andb3)  *)\n(** Do the same for the [andb3] function below. This function should\n    return [true] when all of its inputs are [true], and [false]\n    otherwise. *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool:=\n  match b1 with\n  |false => false\n  |true=> (b2 && b3)\n  end.\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(** [] *)\n\n(* ================================================================= *)\n(** ** Types *)\n\n(** Every expression in Coq has a type, describing what sort of\n    thing it computes. The [Check] command asks Coq to print the type\n    of an expression. *)\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\n\n(** Functions like [negb] itself are also data values, just like\n    [true] and [false].  Their types are called _function types_, and\n    they are written with arrows. *)\n\nCheck negb.\n(* ===> negb : bool -> bool *)\n\n(** The type of [negb], written [bool -> bool] and pronounced\n    \"[bool] arrow [bool],\" can be read, \"Given an input of type\n    [bool], this function produces an output of type [bool].\"\n    Similarly, the type of [andb], written [bool -> bool -> bool], can\n    be read, \"Given two inputs, both of type [bool], this function\n    produces an output of type [bool].\" *)\n\n(* ================================================================= *)\n(** ** New Types from Old *)\n\n(** The types we have defined so far are examples of \"enumerated\n    types\": their definitions explicitly enumerate a finite set of\n    elements, each of which is just a bare constructor.  Here is a\n    more interesting type definition, where one of the constructors\n    takes an argument: *)\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\n(** Let's look at this in a little more detail.\n\n    Every inductively defined type ([day], [bool], [rgb], [color],\n    etc.) contains a set of _constructor expressions_ built from\n    _constructors_ like [red], [primary], [true], [false], [monday],\n    etc. *)\n(** The definitions of [rgb] and [color] say how expressions in the\n    sets [rgb] and [color] can be built:\n\n    - [red], [green], and [blue] are the constructors of [rgb];\n    - [black], [white], and [primary] are the constructors of [color];\n    - the expression [red] belongs to the set [rgb], as do the\n      expressions [green] and [blue];\n    - the expressions [black] and [white] belong to the set [color];\n    - if [p] is an expression belonging to the set [rgb], then\n      [primary p] (pronounced \"the constructor [primary] applied to\n      the argument [p]\") is an expression belonging to the set\n      [color]; and\n    - expressions formed in these ways are the _only_ ones belonging\n      to the sets [rgb] and [color]. *)\n\n(** We can define functions on colors using pattern matching just as\n    we have done for [day] and [bool]. *)\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary p => false\n  end.\n\n(** Since the [primary] constructor takes an argument, a pattern\n    matching [primary] should include either a variable (as above) or\n    a constant of appropriate type (as below). *)\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\n(** The pattern [primary _] here is shorthand for \"[primary] applied\n    to any [rgb] constructor except [red].\"  (The wildcard pattern [_]\n    has the same effect as the dummy pattern variable [p] in the\n    definition of [monochrome].) *)\n\n(* ================================================================= *)\n(** ** Tuples *)\n\n(** A single constructor with multiple parameters can be used\n    to create a tuple type. As an example, consider representing\n    the four bits in a nybble (half a byte). We first define\n    a datatype [bit] that resembles [bool] (using the\n    constructors [B0] and [B1] for the two possible bit values),\n    and then define the datatype [nybble], which is essentially\n    a tuple of four bits.*)\n\nInductive bit : Type :=\n  | B0\n  | B1.\n\nInductive nybble : Type :=\n  | bits (b0 b1 b2 b3 : bit).\n\nCheck (bits B1 B0 B1 B0).\n(* ==> bits B1 B0 B1 B0 : nybble *)\n\n(** The [bits] constructor acts as a wrapper for its contents.\n    Unwrapping can be done by pattern-matching, as in the [all_zero]\n    function which tests a nybble to see if all its bits are O.\n    Note that we are using underscore (_) as a _wildcard pattern_ to\n    avoid inventing variable names that will not be used.*)\n\n\nDefinition all_zero (nb : nybble) : bool :=\n  match nb with\n    | (bits B0 B0 B0 B0) => true\n    | (bits _ _ _ _) => false\n  end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\n(* ===> false : bool *)\nCompute (all_zero (bits B0 B0 B0 B0)).\n(* ===> true : bool *)\n\n(* ================================================================= *)\n(** ** Modules *)\n\n(** Coq provides a _module system_, to aid in organizing large\n    developments.  In this course we won't need most of its features,\n    but one is useful: If we enclose a collection of declarations\n    between [Module X] and [End X] markers, then, in the remainder of\n    the file after the [End], these definitions are referred to by\n    names like [X.foo] instead of just [foo].  We will use this\n    feature to introduce the definition of the type [nat] in an inner\n    module so that it does not interfere with the one from the\n    standard library (which we want to use in the rest because it\n    comes with a tiny bit of convenient special notation).  *)\n\nModule NatPlayground.\n\n(* ================================================================= *)\n(** ** Numbers *)\n\n(** The types we have defined so far, \"enumerated types\" such as\n    [day], [bool], and [bit], and tuple types such as [nybble] built\n    from them, share the property that each type has a finite set of\n    values. The natural numbers are an infinite set, and we need to\n    represent all of them in a datatype with a finite number of\n    constructors. There are many representations of numbers to choose\n    from. We are most familiar with decimal notation (base 10), using\n    the digits 0 through 9, for example, to form the number 123.  You\n    may have encountered hexadecimal notation (base 16), in which the\n    same number is represented as 7B, or octal (base 8), where it is\n    173, or binary (base 2), where it is 1111011. Using an enumerated\n    type to represent digits, we could use any of these to represent\n    natural numbers. There are circumstances where each of these\n    choices can be useful.\n\n    Binary is valuable in computer hardware because it can in turn be\n    represented with two voltage levels, resulting in simple\n    circuitry. Analogously, we wish here to choose a representation\n    that makes _proofs_ simpler.\n\n    Indeed, there is a representation of numbers that is even simpler\n    than binary, namely unary (base 1), in which only a single digit\n    is used (as one might do while counting days in prison by scratching\n    on the walls). To represent unary with a Coq datatype, we use\n    two constructors. The capital-letter [O] constructor represents zero.\n    When the [S] constructor is applied to the representation of the\n    natural number _n_, the result is the representation of _n+1_.\n    ([S] stands for \"successor\", or \"scratch\" if one is in prison.) \n    Here is the complete datatype definition. *)\n\nInductive nat : Type :=\n  | O \n  | S (n : nat).\n\n(** With this definition, 0 is represented by [O], 1 by [S O],\n    2 by [S (S O)], and so on. *)\n\n(** The clauses of this definition can be read:\n      - [O] is a natural number (note that this is the letter \"[O],\"\n        not the numeral \"[0]\").\n      - [S] can be put in front of a natural number to yield another\n        one -- if [n] is a natural number, then [S n] is too. *)\n\n(** Again, let's look at this in a little more detail.  The definition\n    of [nat] says how expressions in the set [nat] can be built:\n\n    - [O] and [S] are constructors;\n    - the expression [O] belongs to the set [nat];\n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat]. *)\n\n(** The same rules apply for our definitions of [day], [bool],\n    [color], etc.\n\n    The above conditions are the precise force of the [Inductive]\n    declaration.  They imply that the expression [O], the expression\n    [S O], the expression [S (S O)], the expression [S (S (S O))], and\n    so on all belong to the set [nat], while other expressions built\n    from data constructors, like [true], [andb true false], [S (S\n    false)], and [O (O (O S))] do not.\n\n    A critical point here is that what we've done so far is just to\n    define a _representation_ of numbers: a way of writing them down.\n    The names [O] and [S] are arbitrary, and at this point they have\n    no special meaning -- they are just two different marks that we\n    can use to write down numbers (together with a rule that says any\n    [nat] will be written as some string of [S] marks followed by an\n    [O]).  If we like, we can write essentially the same definition\n    this way: *)\n\n\nInductive nat' : Type :=\n  | stop\n  | tick (foo : nat').\n\n(** The _interpretation_ of these marks comes from how we use them to\n    compute. *)\n\n(** We can do this by writing functions that pattern match on\n    representations of natural numbers just as we did above with\n    booleans and days -- for example, here is the predecessor\n    function: *)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\n(** The second branch can be read: \"if [n] has the form [S n']\n    for some [n'], then return [n'].\"  *)\n\nEnd NatPlayground.\n\n(** Because natural numbers are such a pervasive form of data,\n    Coq provides a tiny bit of built-in magic for parsing and printing\n    them: ordinary decimal numerals can be used as an alternative to\n    the \"unary\" notation defined by the constructors [S] and [O].  Coq\n    prints numbers in decimal form by default: *)\n\nCheck (S (S (S (S O)))).\n  (* ===> 4 : 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).\n  (* ===> 2 : nat *)\n\n(** The constructor [S] has the type [nat -> nat], just like\n    [pred] and functions like [minustwo]: *)\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\n(** These are all things that can be applied to a number to yield a\n    number.  However, there is a fundamental difference between the\n    first one and the other two: functions like [pred] and [minustwo]\n    come with _computation rules_ -- e.g., the definition of [pred]\n    says that [pred 2] can be simplified to [1] -- while the\n    definition of [S] has no such behavior attached.  Although it is\n    like a function in the sense that it can be applied to an\n    argument, it does not _do_ anything at all!  It is just a way of\n    writing down numbers.  (Think about standard decimal numerals: the\n    numeral [1] is not a computation; it's a piece of data.  When we\n    write [111] to mean the number one hundred and eleven, we are\n    using [1], three times, to write down a concrete representation of\n    a number.)\n\n    For most function definitions over numbers, just pattern matching\n    is not enough: we also need recursion.  For example, to check that\n    a number [n] is even, we may need to recursively check whether\n    [n-2] is even.  To write such functions, we use the keyword\n    [Fixpoint]. *)\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(** We can define [oddb] by a similar [Fixpoint] declaration, but here\n    is a simpler definition: *)\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(** (You will notice if you step through these proofs that\n    [simpl] actually has no effect on the goal -- all of the work is\n    done by [reflexivity].  We'll see more about why that is shortly.)\n\n    Naturally, we can also define multi-argument functions by\n    recursion.  *)\n\nModule NatPlayground2.\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\n(** Adding three to two now gives us five, as we'd expect. *)\n\nCompute (plus 3 2).\n\n(** The simplification that Coq performs to reach this conclusion can\n    be visualized as follows: *)\n\n(*  [plus (S (S (S O))) (S (S O))]\n==> [S (plus (S (S O)) (S (S O)))]\n      by the second clause of the [match]\n==> [S (S (plus (S O) (S (S O))))]\n      by the second clause of the [match]\n==> [S (S (S (plus O (S (S O)))))]\n      by the second clause of the [match]\n==> [S (S (S (S (S O))))]\n      by the first clause of the [match]\n*)\n\n(** As a notational convenience, if two or more arguments have\n    the same type, they can be written together.  In the following\n    definition, [(n m : nat)] means just the same as if we had written\n    [(n : nat) (m : nat)]. *)\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(** You can match two expressions at once by putting a comma\n    between them: *)\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 NatPlayground2.\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\n(** **** Exercise: 1 star (factorial)  *)\n(** Recall the standard mathematical factorial function:\n\n       factorial(0)  =  1\n       factorial(n)  =  n * factorial(n-1)     (if n>0)\n\n    Translate this into Coq. *)\n\nFixpoint factorial (n:nat) : nat := \n  match n with\n  | O => S O\n  | S n => mult (S n) (factorial n)\n  end.\nExample test_factorial1:          (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n\nExample test_factorial2:          (factorial 5) = (mult 10 12).\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** Again, we can make numerical expressions easier to read and write\n    by introducing notations for addition, multiplication, and\n    subtraction. *)\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\n(** (The [level], [associativity], and [nat_scope] annotations\n    control how these notations are treated by Coq's parser.  The\n    details are not important for our purposes, but interested readers\n    can refer to the \"More on Notation\" section at the end of this\n    chapter.)\n\n    Note that these do not change the definitions we've already made:\n    they are simply instructions to the Coq parser to accept [x + y]\n    in place of [plus x y] and, conversely, to the Coq pretty-printer\n    to display [plus x y] as [x + y]. *)\n\n(** When we say that Coq comes with almost nothing built-in, we really\n    mean it: even equality testing is a user-defined operation!\n\n    Here is a function [eqb], which tests natural numbers for\n    [eq]uality, yielding a [b]oolean.  Note the use of nested\n    [match]es (we could also have used a simultaneous match, as we did\n    in [minus].) *)\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\n(** Similarly, the [leb] function tests whether its first argument is\n    less than or equal to its second argument, yielding a boolean. *)\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\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(** Since we'll be using these (especially [eqb]) a lot, let's give\n    them infix notations. *)\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nExample test_leb3':             (4 <=? 2) = false.\nProof. simpl. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (ltb)  *)\n(** The [ltb] function tests natural numbers for [l]ess-[t]han,\n    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for\n    this one, define it in terms of a previously defined\n    function.  (It can be done with just one previously defined\n    function, but you can use two if you need to.) *)\n\nDefinition ltb (n m : nat) : bool:=\n  (andb (n <=? m) (negb (n =? m))).\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1:             (ltb 2 2) = false.\nProof. compute. reflexivity. Qed.\nExample test_ltb2:             (ltb 2 4) = true.\nProof. compute. reflexivity. Qed.\nExample test_ltb3:             (ltb 4 2) = false.\nProof. compute. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Simplification *)\n\n(** Now that we've defined a few datatypes and functions, let's\n    turn to stating and proving properties of their behavior.\n    Actually, we've already started doing this: each [Example] in the\n    previous sections makes a precise claim about the behavior of some\n    function on some particular inputs.  The proofs of these claims\n    were always the same: use [simpl] to simplify both sides of the\n    equation, then use [reflexivity] to check that both sides contain\n    identical values.\n\n    The same sort of \"proof by simplification\" can be used to prove\n    more interesting properties as well.  For example, the fact that\n    [0] is a \"neutral element\" for [+] on the left can be proved just\n    by observing that [0 + n] reduces to [n] no matter what [n] is, a\n    fact that can be read directly off the definition of [plus].*)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity.  Qed.\n\n(** (You may notice that the above statement looks different in\n    the [.v] file in your IDE than it does in the HTML rendition in\n    your browser, if you are viewing both. In [.v] files, we write the\n    [forall] universal quantifier using the reserved identifier\n    \"forall.\"  When the [.v] files are converted to HTML, this gets\n    transformed into an upside-down-A symbol.)\n\n    This is a good place to mention that [reflexivity] is a bit\n    more powerful than we have admitted. In the examples we have seen,\n    the calls to [simpl] were actually not needed, because\n    [reflexivity] can perform some simplification automatically when\n    checking that two sides are equal; [simpl] was just added so that\n    we could see the intermediate state -- after simplification but\n    before finishing the proof.  Here is a shorter proof of the\n    theorem: *)\n\nTheorem plus_O_n' : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\n(** Moreover, it will be useful later to know that [reflexivity]\n    does somewhat _more_ simplification than [simpl] does -- for\n    example, it tries \"unfolding\" defined terms, replacing them with\n    their right-hand sides.  The reason for this difference is that,\n    if reflexivity succeeds, the whole goal is finished and we don't\n    need to look at whatever expanded expressions [reflexivity] has\n    created by all this simplification and unfolding; by contrast,\n    [simpl] is used in situations where we may have to read and\n    understand the new goal that it creates, so we would not want it\n    blindly expanding definitions and leaving the goal in a messy\n    state.\n\n    The form of the theorem we just stated and its proof are almost\n    exactly the same as the simpler examples we saw earlier; there are\n    just a few differences.\n\n    First, we've used the keyword [Theorem] instead of [Example].\n    This difference is mostly a matter of style; the keywords\n    [Example] and [Theorem] (and a few others, including [Lemma],\n    [Fact], and [Remark]) mean pretty much the same thing to Coq.\n\n    Second, we've added the quantifier [forall n:nat], so that our\n    theorem talks about _all_ natural numbers [n].  Informally, to\n    prove theorems of this form, we generally start by saying \"Suppose\n    [n] is some number...\"  Formally, this is achieved in the proof by\n    [intros n], which moves [n] from the quantifier in the goal to a\n    _context_ of current assumptions.\n\n    The keywords [intros], [simpl], and [reflexivity] are examples of\n    _tactics_.  A tactic is a command that is used between [Proof] and\n    [Qed] to guide the process of checking some claim we are making.\n    We will see several more tactics in the rest of this chapter and\n    yet more in future chapters. *)\n\n(** Other similar theorems can be proved with the same pattern. *)\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(** The [_l] suffix in the names of these theorems is\n    pronounced \"on the left.\" *)\n\n(** It is worth stepping through these proofs to observe how the\n    context and the goal change.  You may want to add calls to [simpl]\n    before [reflexivity] to see the simplifications that Coq performs\n    on the terms before checking that they are equal. *)\n\n(* ################################################################# *)\n(** * Proof by Rewriting *)\n\n(** This theorem is a bit more interesting than the others we've\n    seen: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\n(** Instead of making a universal claim about all numbers [n] and [m],\n    it talks about a more specialized property that only holds when [n\n    = m].  The arrow symbol is pronounced \"implies.\"\n\n    As before, we need to be able to reason by assuming we are given such\n    numbers [n] and [m].  We also need to assume the hypothesis\n    [n = m]. The [intros] tactic will serve to move all three of these\n    from the goal into assumptions in the current context.\n\n    Since [n] and [m] are arbitrary numbers, we can't just use\n    simplification to prove this theorem.  Instead, we prove it by\n    observing that, if we are assuming [n = m], then we can replace\n    [n] with [m] in the goal statement and obtain an equality with the\n    same expression on both sides.  The tactic that tells Coq to\n    perform this replacement is called [rewrite]. *)\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 using the hypothesis: *)\n  rewrite -> H.\n  reflexivity.  Qed.\n\n(** The first line of the proof moves the universally quantified\n    variables [n] and [m] into the context.  The second moves the\n    hypothesis [n = m] into the context and gives it the name [H].\n    The third tells Coq to rewrite the current goal ([n + n = m + m])\n    by replacing the left side of the equality hypothesis [H] with the\n    right side.\n\n    (The arrow symbol in the [rewrite] has nothing to do with\n    implication: it tells Coq to apply the rewrite from left to right.\n    To rewrite from right to left, you can use [rewrite <-].  Try\n    making this change in the above proof and see what difference it\n    makes.) *)\n\n(** **** Exercise: 1 star (plus_id_exercise)  *)\n(** Remove \"[Admitted.]\" and fill in the proof. *)\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\nintros n m o.\n   intros n_m m_o.\n  rewrite -> n_m.\n  rewrite <- m_o.\n  reflexivity.\nQed.\n(** [] *)\n\n(** The [Admitted] command tells Coq that we want to skip trying\n    to prove this theorem and just accept it as a given.  This can be\n    useful for developing longer proofs, since we can state subsidiary\n    lemmas that we believe will be useful for making some larger\n    argument, use [Admitted] to accept them on faith for the moment,\n    and continue working on the main argument until we are sure it\n    makes sense; then we can go back and fill in the proofs we\n    skipped.  Be careful, though: every time you say [Admitted] you\n    are leaving a door open for total nonsense to enter Coq's nice,\n    rigorous, formally checked world! *)\n\n(** We can also use the [rewrite] tactic with a previously proved\n    theorem instead of a hypothesis from the context. If the statement\n    of the previously proved theorem involves quantified variables,\n    as in the example below, Coq tries to instantiate them\n    by matching with the current goal. *)\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\n(** **** Exercise: 2 stars (mult_S_1)  *)\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 -> plus_1_l. Check plus_1_l.\n   rewrite-> H.\n   reflexivity.  Qed.\n\n  (* (N.b. This proof can actually be completed with tactics other than\n     [rewrite], but please do use [rewrite] for the sake of the exercise.) *)\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Case Analysis *)\n\n(** Of course, not everything can be proved by simple\n    calculation and rewriting: In general, unknown, hypothetical\n    values (arbitrary numbers, booleans, lists, etc.) can block\n    simplification.  For example, if we try to prove the following\n    fact using the [simpl] tactic as above, we get stuck.  (We then\n    use the [Abort] command to give up on it for the moment.)*)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n  simpl.  (* does nothing! *)\nAbort.\n\n(** The reason for this is that the definitions of both\n    [eqb] and [+] begin by performing a [match] on their first\n    argument.  But here, the first argument to [+] is the unknown\n    number [n] and the argument to [eqb] is the compound\n    expression [n + 1]; neither can be simplified.\n\n    To make progress, we need to consider the possible forms of [n]\n    separately.  If [n] is [O], then we can calculate the final result\n    of [(n + 1) =? 0] and check that it is, indeed, [false].  And\n    if [n = S n'] for some [n'], then, although we don't know exactly\n    what number [n + 1] yields, we can calculate that, at least, it\n    will begin with one [S], and this is enough to calculate that,\n    again, [(n + 1) =? 0] will yield [false].\n\n    The tactic that tells Coq to consider, separately, the cases where\n    [n = O] and where [n = S n'] is called [destruct]. *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n. destruct n as [| n'] eqn:E.\n  - reflexivity.\n  - reflexivity.   Qed.\n\n(** The [destruct] generates _two_ subgoals, which we must then\n    prove, separately, in order to get Coq to accept the theorem.\n\n    The annotation \"[as [| n']]\" is called an _intro pattern_.  It\n    tells Coq what variable names to introduce in each subgoal.  In\n    general, what goes between the square brackets is a _list of\n    lists_ of names, separated by [|].  In this case, the first\n    component is empty, since the [O] constructor is nullary (it\n    doesn't have any arguments).  The second component gives a single\n    name, [n'], since [S] is a unary constructor.\n\n    In each subgoal, Coq remembers the assumption about [n] that is\n    relevant for this subgoal -- either [n = 0] or [n = S n'] for some\n    n'.  The [eqn:E] annotation tells [destruct] to give the name [E] to\n    this equation.  (Leaving off the [eqn:E] annotation causes Coq to\n    elide these assumptions in the subgoals.  This slightly\n    streamlines proofs where the assumptions are not explicitly used,\n    but it is better practice to keep them for the sake of\n    documentation, as they can help keep you oriented when working\n    with the subgoals.)\n\n    The [-] signs on the second and third lines are called _bullets_,\n    and they mark the parts of the proof that correspond to each\n    generated subgoal.  The proof script that comes after a bullet is\n    the entire proof for a subgoal.  In this example, each of the\n    subgoals is easily proved by a single use of [reflexivity], which\n    itself performs some simplification -- e.g., the second one\n    simplifies [(S n' + 1) =? 0] to [false] by first rewriting [(S n'\n    + 1)] to [S (n' + 1)], then unfolding [eqb], and then simplifying\n    the [match].\n\n    Marking cases with bullets is entirely optional: if bullets are\n    not present, Coq simply asks you to prove each subgoal in\n    sequence, one at a time. But it is a good idea to use bullets.\n    For one thing, they make the structure of a proof apparent, making\n    it more readable. Also, bullets instruct Coq to ensure that a\n    subgoal is complete before trying to verify the next one,\n    preventing proofs for different subgoals from getting mixed\n    up. These issues become especially important in large\n    developments, where fragile proofs lead to long debugging\n    sessions.\n\n    There are no hard and fast rules for how proofs should be\n    formatted in Coq -- in particular, where lines should be broken\n    and how sections of the proof should be indented to indicate their\n    nested structure.  However, if the places where multiple subgoals\n    are generated are marked with explicit bullets at the beginning of\n    lines, then the proof will be readable almost no matter what\n    choices are made about other aspects of layout.\n\n    This is also a good place to mention one other piece of somewhat\n    obvious advice about line lengths.  Beginning Coq users sometimes\n    tend to the extremes, either writing each tactic on its own line\n    or writing entire proofs on one line.  Good style lies somewhere\n    in the middle.  One reasonable convention is to limit yourself to\n    80-character lines.\n\n    The [destruct] tactic can be used with any inductively defined\n    datatype.  For example, we use it next to prove that boolean\n    negation is involutive -- i.e., that negation is its own\n    inverse. *)\n\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** Note that the [destruct] here has no [as] clause because\n    none of the subcases of the [destruct] need to bind any variables,\n    so there is no need to specify any names.  (We could also have\n    written [as [|]], or [as []].)  In fact, we can omit the [as]\n    clause from _any_ [destruct] and Coq will fill in variable names\n    automatically.  This is generally considered bad style, since Coq\n    often makes confusing choices of names when left to its own\n    devices.\n\n    It is sometimes useful to invoke [destruct] inside a subgoal,\n    generating yet more proof obligations. In this case, we use\n    different kinds of bullets to mark goals on different \"levels.\"\n    For example: *)\n\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\n(** Each pair of calls to [reflexivity] corresponds to the\n    subgoals that were generated after the execution of the [destruct c]\n    line right above it. *)\n\n(** Besides [-] and [+], we can use [*] (asterisk) as a third kind of\n    bullet.  We can also enclose sub-proofs in curly braces, which is\n    useful in case we ever encounter a proof that generates more than\n    three levels of subgoals: *)\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\n(** Since curly braces mark both the beginning and the end of a\n    proof, they can be used for multiple subgoal levels, as this\n    example shows. Furthermore, curly braces allow us to reuse the\n    same bullet shapes at multiple levels in a proof: *)\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\n(** Before closing the chapter, let's mention one final\n    convenience.  As you may have noticed, many proofs perform case\n    analysis on a variable right after introducing it:\n\n       intros x y. destruct y as [|y].\n\n    This pattern is so common that Coq provides a shorthand for it: we\n    can perform case analysis on a variable when introducing it by\n    using an intro pattern instead of a variable name. For instance,\n    here is a shorter proof of the [plus_1_neq_0] theorem\n    above.  (You'll also note one downside of this shorthand: we lose\n    the equation recording the assumption we are making in each\n    subgoal, which we previously got from the [eqn:E] annotation.) *)\n\nTheorem plus_1_neq_0' : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n. destruct n.\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** If there are no arguments to name, we can just write [[]]. *)\n\nTheorem andb_commutative'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(** **** Exercise: 2 stars (andb_true_elim2)  *)\n(** Prove the following claim, marking cases (and subcases) with\n    bullets when you use [destruct]. *)\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  \n  intros b.\n   intros c.\n   destruct b as [].\n    + destruct c as [].\n      - intros Hbc. \n        reflexivity.\n      - intros Hbc. \n         simpl andb in Hbc. \n          rewrite Hbc. \n        reflexivity.\n    + destruct c as [].\n      - intros Hbc. \n        reflexivity.\n      - intros Hbc. \n       simpl andb in Hbc. \n        rewrite Hbc. \n        reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (zero_nbeq_plus_1)  *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  intros [|n'].\n  - reflexivity.\n  - reflexivity.  Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** More on Notation (Optional) *)\n\n(** (In general, sections marked Optional are not needed to follow the\n    rest of the book, except possibly other Optional sections.  On a\n    first reading, you might want to skim these sections so that you\n    know what's there for future reference.)\n\n    Recall the notation definitions for infix plus and times: *)\n\nNotation \"x + y\" := (plus 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(** For each notation symbol in Coq, we can specify its _precedence\n    level_ and its _associativity_.  The precedence level [n] is\n    specified by writing [at level n]; this helps Coq parse compound\n    expressions.  The associativity setting helps to disambiguate\n    expressions containing multiple occurrences of the same\n    symbol. For example, the parameters specified above for [+] and\n    [*] say that the expression [1+2*3*4] is shorthand for\n    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and\n    _left_, _right_, or _no_ associativity.  We will see more examples\n    of this later, e.g., in the [Lists]\n    chapter.\n\n    Each notation symbol is also associated with a _notation scope_.\n    Coq tries to guess what scope is meant from context, so when it\n    sees [S(O*O)] it guesses [nat_scope], but when it sees the\n    cartesian product (tuple) type [bool*bool] (which we'll see in\n    later chapters) it guesses [type_scope].  Occasionally, it is\n    necessary to help it out with percent-notation by writing\n    [(x*y)%nat], and sometimes in what Coq prints it will use [%nat]\n    to indicate what scope a notation is in.\n\n    Notation scopes also apply to numeral notation ([3], [4], [5],\n    etc.), so you may sometimes see [0%nat], which means [O] (the\n    natural number [0] that we're using in this chapter), or [0%Z],\n    which means the Integer zero (which comes from a different part of\n    the standard library).\n\n    Pro tip: Coq's notation mechanism is not especially powerful.\n    Don't expect too much from it! *)\n\n(* ================================================================= *)\n(** ** Fixpoints and Structural Recursion (Optional) *)\n\n(** Here is a copy of the definition of addition: *)\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\n(** When Coq checks this definition, it notes that [plus'] is\n    \"decreasing on 1st argument.\"  What this means is that we are\n    performing a _structural recursion_ over the argument [n] -- i.e.,\n    that we make recursive calls only on strictly smaller values of\n    [n].  This implies that all calls to [plus'] will eventually\n    terminate.  Coq demands that some argument of _every_ [Fixpoint]\n    definition is \"decreasing.\"\n\n    This requirement is a fundamental feature of Coq's design: In\n    particular, it guarantees that every function that can be defined\n    in Coq will terminate on all inputs.  However, because Coq's\n    \"decreasing analysis\" is not very sophisticated, it is sometimes\n    necessary to write functions in slightly unnatural ways. *)\n\n(** **** Exercise: 2 stars, optional (decreasing)  *)\n(** To get a concrete sense of this, find a way to write a sensible\n    [Fixpoint] definition (of a simple function on numbers, say) that\n    _does_ terminate on all inputs, but that Coq will reject because\n    of this restriction.  (If you choose to turn in this optional\n    exercise as part of a homework assignment, make sure you comment\n    out your solution so that it doesn't cause Coq to reject the whole\n    file!) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** Each SF chapter comes with a tester file (e.g.  [BasicsTest.v]),\n    containing scripts that check most of the exercises. You can run\n    [make BasicsTest.vo] in a terminal and check its output to make\n    sure you didn't miss anything. *)\n\n(** **** Exercise: 2 stars (boolean_functions)  *)\n(** Use the tactics you have learned so far to prove the following\n    theorem about boolean functions. *)\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 f.\nintros H.\nintros b.\n\nrewrite H.\nrewrite H.\n\nreflexivity.\nQed.\n\n(** Now state and prove a theorem [negation_fn_applied_twice] similar\n    to the previous one but where the second hypothesis says that the\n    function [f] has the property that [f x = negb x].*)\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 f.\nintros H.\nintros b.\n\nrewrite H.\nrewrite H.\n\ndestruct b.\n-reflexivity.\n-reflexivity.\nQed.\n(* FILL IN HERE *)\n(* The [Import] statement on the next line tells Coq to use the\n   standard library String module.  We'll use strings more in later\n   chapters, but for the moment we just need syntax for literal\n   strings for the grader comments. *)\nFrom Coq Require Export String.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_negation_fn_applied_twice : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (andb_eq_orb)  *)\n(** Prove the following theorem.  (Hint: This one can be a bit tricky,\n    depending on how you approach it.  You will probably need both\n    [destruct] and [rewrite], but destructing everything in sight is\n    not the best way.) *)\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (binary)  *)\n(** We can generalize our unary representation of natural numbers to\n    the more efficient binary representation by treating a binary\n    number as a sequence of constructors [A] and [B] (representing 0s\n    and 1s), terminated by a [Z]. For comparison, in the unary\n    representation, a number is a sequence of [S]s terminated by an\n    [O].\n\n    For example:\n\n        decimal            binary                           unary\n           0                   Z                              O\n           1                 B Z                            S O\n           2              A (B Z)                        S (S O)\n           3              B (B Z)                     S (S (S O))\n           4           A (A (B Z))                 S (S (S (S O)))\n           5           B (A (B Z))              S (S (S (S (S O))))\n           6           A (B (B Z))           S (S (S (S (S (S O)))))\n           7           B (B (B Z))        S (S (S (S (S (S (S O))))))\n           8        A (A (A (B Z)))    S (S (S (S (S (S (S (S O)))))))\n\n    Note that the low-order bit is on the left and the high-order bit\n    is on the right -- the opposite of the way binary numbers are\n    usually written.  This choice makes them easier to manipulate. *)\n\nInductive bin : Type :=\n  | Z \n  | A (n : bin)\n  | B (n : bin).\n\n(** (a) Complete the definitions below of an increment function [incr]\n        for binary numbers, and a function [bin_to_nat] to convert\n        binary numbers to unary numbers. *)\n\nFixpoint incr (m:bin) : bin\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nFixpoint bin_to_nat (m:bin) : nat \n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(**    (b) Write five unit tests [test_bin_incr1], [test_bin_incr2], etc.\n        for your increment and binary-to-unary functions.  (A \"unit\n        test\" in Coq is a specific [Example] that can be proved with\n        just [reflexivity], as we've done for several of our\n        definitions.)  Notice that incrementing a binary number and\n        then converting it to unary should yield the same result as\n        first converting it to unary and then incrementing. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary : option (prod nat string) := None.\n(** [] *)\n\n\n(** * Induction: Proof by Induction *)\n\n(** Before getting started, we need to import all of our\n    definitions from the previous chapter: *)\n\n\n\n(** For the [Require Export] to work, Coq needs to be able to\n    find a compiled version of [Basics.v], called [Basics.vo], in a directory\n    associated with the prefix [LF].  This file is analogous to the [.class]\n    files compiled from [.java] source files and the [.o] files compiled from\n    [.c] files.\n\n    First create a file named [_CoqProject] containing the following line\n    (if you obtained the whole volume \"Logical Foundations\" as a single\n    archive, a [_CoqProject] should already exist and you can skip this step):\n\n      [-Q . LF]\n\n    This maps the current directory (\"[.]\", which contains [Basics.v],\n    [Induction.v], etc.) to the prefix (or \"logical directory\") \"[LF]\".\n    PG and CoqIDE read [_CoqProject] automatically, so they know to where to\n    look for the file [Basics.vo] corresponding to the library [LF.Basics].\n\n    Once [_CoqProject] is thus created, there are various ways to build\n    [Basics.vo]:\n\n     - In Proof General: The compilation can be made to happen automatically\n       when you submit the [Require] line above to PG, by setting the emacs\n       variable [coq-compile-before-require] to [t].\n\n     - In CoqIDE: Open [Basics.v]; then, in the \"Compile\" menu, click\n       on \"Compile Buffer\".\n\n     - From the command line: Generate a [Makefile] using the [coq_makefile]\n       utility, that comes installed with Coq (if you obtained the whole\n       volume as a single archive, a [Makefile] should already exist\n       and you can skip this step):\n\n         [coq_makefile -f _CoqProject *.v -o Makefile]\n\n       Note: You should rerun that command whenever you add or remove Coq files\n       to the directory.\n\n       Then you can compile [Basics.v] by running [make] with the corresponding\n       [.vo] file as a target:\n\n         [make Basics.vo]\n\n       All files in the directory can be compiled by giving no arguments:\n\n         [make]\n\n       Under the hood, [make] uses the Coq compiler, [coqc].  You can also\n       run [coqc] directly:\n\n         [coqc -Q . LF Basics.v]\n\n       But [make] also calculates dependencies between source files to compile\n       them in the right order, so [make] should generally be prefered over\n       explicit [coqc].\n\n    If you have trouble (e.g., if you get complaints about missing\n    identifiers later in the file), it may be because the \"load path\"\n    for Coq is not set up correctly.  The [Print LoadPath.] command\n    may be helpful in sorting out such issues.\n\n    In particular, if you see a message like\n\n        [Compiled library Foo makes inconsistent assumptions over\n        library Bar]\n\n    - Check whether you have multiple installations of Coq on your machine.\n      It may be that commands (like [coqc]) that you execute in a terminal\n      window are getting a different version of Coq than commands executed by\n      Proof General or CoqIDE.\n\n    - Another common reason is that the library [Bar] was modified and\n      recompiled without also recompiling [Foo] which depends on it.  Recompile\n      [Foo], or everything if too many files are affected.  (Using the third\n      solution above: [make clean; make].)\n\n    One more tip for CoqIDE users: If you see messages like [Error:\n    Unable to locate library Basics], a likely reason is\n    inconsistencies between compiling things _within CoqIDE_ vs _using\n    [coqc] from the command line_.  This typically happens when there\n    are two incompatible versions of [coqc] installed on your\n    system (one associated with CoqIDE, and one associated with [coqc]\n    from the terminal).  The workaround for this situation is\n    compiling using CoqIDE only (i.e. choosing \"make\" from the menu),\n    and avoiding using [coqc] directly at all. *)\n\n(* ################################################################# *)\n(** * Proof by Induction *)\n\n(** We proved in the last chapter that [0] is a neutral element\n    for [+] on the left, using an easy argument based on\n    simplification.  We also observed that proving the fact that it is\n    also a neutral element on the _right_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\n\n(** ... can't be done in the same simple way.  Just applying\n  [reflexivity] doesn't work, since the [n] in [n + 0] is an arbitrary\n  unknown number, so the [match] in the definition of [+] can't be\n  simplified.  *)\n\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** And reasoning by cases using [destruct n] doesn't get us much\n    further: the branch of the case analysis where we assume [n = 0]\n    goes through fine, but in the branch where [n = S n'] for some [n'] we\n    get stuck in exactly the same way. *)\n\nTheorem plus_n_O_secondtry : forall n:nat,\n  n = n + 0.\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(** We could use [destruct n'] to get one step further, but,\n    since [n] can be arbitrarily large, if we just go on like this\n    we'll never finish. *)\n\n(** To prove interesting facts about numbers, lists, and other\n    inductively defined sets, we usually need a more powerful\n    reasoning principle: _induction_.\n\n    Recall (from high school, a discrete math course, etc.) the\n    _principle of induction over natural numbers_: If [P(n)] is some\n    proposition involving a natural number [n] and we want to show\n    that [P] holds for all numbers [n], we can reason like this:\n         - show that [P(O)] holds;\n         - show that, for any [n'], if [P(n')] holds, then so does\n           [P(S n')];\n         - conclude that [P(n)] holds for all [n].\n\n    In Coq, the steps are the same: we begin with the goal of proving\n    [P(n)] for all [n] and break it down (by applying the [induction]\n    tactic) into two separate subgoals: one where we must show [P(O)]\n    and another where we must show [P(n') -> P(S n')].  Here's how\n    this works for the theorem at hand: *)\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\n(** Like [destruct], the [induction] tactic takes an [as...]\n    clause that specifies the names of the variables to be introduced\n    in the subgoals.  Since there are two subgoals, the [as...] clause\n    has two parts, separated by [|].  (Strictly speaking, we can omit\n    the [as...] clause and Coq will choose names for us.  In practice,\n    this is a bad idea, as Coq's automatic choices tend to be\n    confusing.)\n\n    In the first subgoal, [n] is replaced by [0].  No new variables\n    are introduced (so the first part of the [as...] is empty), and\n    the goal becomes [0 = 0 + 0], which follows by simplification.\n\n    In the second subgoal, [n] is replaced by [S n'], and the\n    assumption [n' + 0 = n'] is added to the context with the name\n    [IHn'] (i.e., the Induction Hypothesis for [n']).  These two names\n    are specified in the second part of the [as...] clause.  The goal\n    in this case becomes [S n' = (S n') + 0], which simplifies to\n    [S n' = S (n' + 0)], which in turn follows from [IHn']. *)\n\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(** (The use of the [intros] tactic in these proofs is actually\n    redundant.  When applied to a goal that contains quantified\n    variables, the [induction] tactic will automatically move them\n    into the context as needed.) *)\n\n(** **** Exercise: 2 stars, recommended (basic_induction)  *)\n(** Prove the following using induction. You might need previously\n    proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\nintros n. induction n as [|n' IHn'].\n- simpl. reflexivity.\n-simpl. rewrite->IHn'. reflexivity.\n   Qed.\n\nTheorem plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\nintros n m. induction n as [|n' IHn']. \n- simpl. reflexivity.\n- simpl. rewrite-> IHn'. reflexivity.\n   Qed.\n\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\nintros n m. induction n as [|n' IHn'].\n-simpl. rewrite <-plus_n_O. reflexivity.\n-simpl. rewrite <-plus_n_Sm. rewrite<- IHn'. reflexivity.\n  Qed.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\nintros n m p. induction n as [|n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite <-IHn'. reflexivity.\n   Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (double_plus)  *)\n(** Consider the following function, which doubles its argument: *)\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. \nintros n. induction n as [|n' IHn'].\n- simpl. reflexivity.\n-simpl.  rewrite IHn'. rewrite ->plus_n_Sm. reflexivity.\n  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (evenb_S)  *)\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.\nintros n. induction n as [|n' IHn'].\n- reflexivity.\n-  rewrite->IHn'. simpl. rewrite negb_involutive. reflexivity.\n   Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (destruct_induction)  *)\n(** Briefly explain the difference between the tactics [destruct]\n    and [induction].\n\n(* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_destruct_induction : option (prod nat string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proofs Within Proofs *)\n\n(** In Coq, as in informal mathematics, large proofs are often\n    broken into a sequence of theorems, with later proofs referring to\n    earlier theorems.  But sometimes a proof will require some\n    miscellaneous fact that is too trivial and of too little general\n    interest to bother giving it its own top-level name.  In such\n    cases, it is convenient to be able to simply state and prove the\n    needed \"sub-theorem\" right at the point where it is used.  The\n    [assert] tactic allows us to do this.  For example, our earlier\n    proof of the [mult_0_plus] theorem referred to a previous theorem\n    named [plus_O_n].  We could instead use [assert] to state and\n    prove [plus_O_n] in-line: *)\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.  Qed.\n\n(** The [assert] tactic introduces two sub-goals.  The first is\n    the assertion itself; by prefixing it with [H:] we name the\n    assertion [H].  (We can also name the assertion with [as] just as\n    we did above with [destruct] and [induction], i.e., [assert (0 + n\n    = n) as H].)  Note that we surround the proof of this assertion\n    with curly braces [{ ... }], both for readability and so that,\n    when using Coq interactively, we can see more easily when we have\n    finished this sub-proof.  The second goal is the same as the one\n    at the point where we invoke [assert] except that, in the context,\n    we now have the assumption [H] that [0 + n = n].  That is,\n    [assert] generates one subgoal where we must prove the asserted\n    fact and a second subgoal where we can use the asserted fact to\n    make progress on whatever we were trying to prove in the first\n    place. *)\n\n(** Another example of [assert]... *)\n\n(** For example, suppose we want to prove that [(n + m) + (p + q)\n    = (m + n) + (p + q)]. The only difference between the two sides of\n    the [=] is that the arguments [m] and [n] to the first inner [+]\n    are swapped, so it seems we should be able to use the\n    commutativity of addition ([plus_comm]) to rewrite one into the\n    other.  However, the [rewrite] tactic is not very smart about\n    _where_ it applies the rewrite.  There are three uses of [+] here,\n    and it turns out that doing [rewrite -> plus_comm] will affect\n    only the _outer_ one... *)\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 rewrites the wrong plus! *)\nAbort.\n\n(** To use [plus_comm] at the point where we need it, we can introduce\n    a local lemma stating that [n + m = m + n] (for the particular [m]\n    and [n] that we are talking about here), prove this lemma using\n    [plus_comm], and then use it to do the desired rewrite. *)\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\n(* ################################################################# *)\n(** * Formal vs. Informal Proof *)\n\n(** \"_Informal proofs are algorithms; formal proofs are code_.\" *)\n\n(** What constitutes a successful proof of a mathematical claim?\n    The question has challenged philosophers for millennia, but a\n    rough and ready definition could be this: A proof of a\n    mathematical proposition [P] is a written (or spoken) text that\n    instills in the reader or hearer the certainty that [P] is true --\n    an unassailable argument for the truth of [P].  That is, a proof\n    is an act of communication.\n\n    Acts of communication may involve different sorts of readers.  On\n    one hand, the \"reader\" can be a program like Coq, in which case\n    the \"belief\" that is instilled is that [P] can be mechanically\n    derived from a certain set of formal logical rules, and the proof\n    is a recipe that guides the program in checking this fact.  Such\n    recipes are _formal_ proofs.\n\n    Alternatively, the reader can be a human being, in which case the\n    proof will be written in English or some other natural language,\n    and will thus necessarily be _informal_.  Here, the criteria for\n    success are less clearly specified.  A \"valid\" proof is one that\n    makes the reader believe [P].  But the same proof may be read by\n    many different readers, some of whom may be convinced by a\n    particular way of phrasing the argument, while others may not be.\n    Some readers may be particularly pedantic, inexperienced, or just\n    plain thick-headed; the only way to convince them will be to make\n    the argument in painstaking detail.  But other readers, more\n    familiar in the area, may find all this detail so overwhelming\n    that they lose the overall thread; all they want is to be told the\n    main ideas, since it is easier for them to fill in the details for\n    themselves than to wade through a written presentation of them.\n    Ultimately, there is no universal standard, because there is no\n    single way of writing an informal proof that is guaranteed to\n    convince every conceivable reader.\n\n    In practice, however, mathematicians have developed a rich set of\n    conventions and idioms for writing about complex mathematical\n    objects that -- at least within a certain community -- make\n    communication fairly reliable.  The conventions of this stylized\n    form of communication give a fairly clear standard for judging\n    proofs good or bad.\n\n    Because we are using Coq in this course, we will be working\n    heavily with formal proofs.  But this doesn't mean we can\n    completely forget about informal ones!  Formal proofs are useful\n    in many ways, but they are _not_ very efficient ways of\n    communicating ideas between human beings. *)\n\n(** For example, here is a proof that addition is associative: *)\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\n(** Coq is perfectly happy with this.  For a human, however, it\n    is difficult to make much sense of it.  We can use comments and\n    bullets to show the structure a little more clearly... *)\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(** ... and if you're used to Coq you may be able to step\n    through the tactics one after the other in your mind and imagine\n    the state of the context and goal stack at each point, but if the\n    proof were even a little bit more complicated this would be next\n    to impossible.\n\n    A (pedantic) mathematician might write the proof something like\n    this: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n      n + (m + p) = (n + m) + p.\n\n    _Proof_: By induction on [n].\n\n    - First, suppose [n = 0].  We must show\n\n        0 + (m + p) = (0 + m) + p.\n\n      This follows directly from the definition of [+].\n\n    - Next, suppose [n = S n'], where\n\n        n' + (m + p) = (n' + m) + p.\n\n      We must show\n\n        (S n') + (m + p) = ((S n') + m) + p.\n\n      By the definition of [+], this follows from\n\n        S (n' + (m + p)) = S ((n' + m) + p),\n\n      which is immediate from the induction hypothesis.  _Qed_. *)\n\n(** The overall form of the proof is basically similar, and of\n    course this is no accident: Coq has been designed so that its\n    [induction] tactic generates the same sub-goals, in the same\n    order, as the bullet points that a mathematician would write.  But\n    there are significant differences of detail: the formal proof is\n    much more explicit in some ways (e.g., the use of [reflexivity])\n    but much less explicit in others (in particular, the \"proof state\"\n    at any given point in the Coq proof is completely implicit,\n    whereas the informal proof reminds the reader several times where\n    things stand). *)\n\n(** **** Exercise: 2 stars, advanced, recommended (plus_comm_informal)  *)\n(** Translate your solution for [plus_comm] into an informal proof:\n\n    Theorem: Addition is commutative.\n\n    Proof: (* FILL IN HERE *)\n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_plus_comm_informal : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (eqb_refl_informal)  *)\n(** Write an informal proof of the following theorem, using the\n    informal proof of [plus_assoc] as a model.  Don't just\n    paraphrase the Coq tactics into English!\n\n    Theorem: [true = n =? n] for any [n].\n\n    Proof: (* FILL IN HERE *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 3 stars, recommended (mult_comm)  *)\n(** Use [assert] to help prove this theorem.  You shouldn't need to\n    use induction on [plus_swap]. *)\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros n m p. rewrite plus_assoc'. rewrite plus_assoc'.\nassert (H: n + m = m + n).\n- rewrite-> plus_comm. reflexivity. \n- rewrite H. reflexivity. \nQed.\n\n\n(** Now 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.) *)\nTheorem mult_plus : forall n m : nat, n * S m = n + (n * m).\nProof.\n  intros n m.\n  induction n as [| n'].\n  \n    reflexivity.\n  \n    simpl. rewrite IHn'. rewrite plus_swap. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof. intros m n. induction m as [| m'].\n- simpl. rewrite mult_0_r. reflexivity.\n- simpl. rewrite mult_plus. rewrite IHm'.\nreflexivity.\nQed.\n  \n(** [] *)\n\n(** **** Exercise: 3 stars, optional (more_exercises)  *)\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 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. destruct n as [| n'] eqn:E.\n- reflexivity.\n- reflexivity.\n  Qed.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof. \nintros b. destruct b.\n- reflexivity.\n- reflexivity.\nQed.\n  \n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  n <=? m = true -> (p + n) <=? (p + m) = true.\nProof.\nintros n m p H. induction p as [|p'  IHp'].\n- simpl. rewrite H. reflexivity.\n- simpl. rewrite IHp'. reflexivity.\nQed.\n\n\nTheorem S_nbeq_0 : forall n:nat,\n  (S n) =? 0 = false.\nProof.\nintros n. destruct n.\n- reflexivity.\n- reflexivity.\nQed.\n\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\nintros n. induction n as [|n' IHn'].\n- reflexivity.\n- simpl. rewrite<-plus_n_O. 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.\nintros b c. destruct b.\n- destruct c.\n+ reflexivity.\n+ reflexivity.\n- destruct c.\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.\nintros n m p. induction n as [|n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite ->IHn'. rewrite plus_assoc''. reflexivity.\nQed.\n\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\nintros n m p. induction n as [|n' IHn'].\n- simpl. reflexivity.\n- simpl.  rewrite IHn'. rewrite mult_plus_distr_r. reflexivity.\nQed.\n  \n(** [] *)\n\n(** **** Exercise: 2 stars, optional (eqb_refl)  *)\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.) *)\n\nTheorem eqb_refl : forall n : nat,\n  true = (n =? n).\nProof.\nintros n. induction n as [|n' IHn'].\n- simpl. reflexivity.\n- simpl. rewrite IHn'. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (plus_swap')  *)\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)]. *)\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (binary_commute)  *)\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! *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_commute : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 5 stars, advanced (binary_inverse)  *)\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  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\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  (* FILL IN HERE *) Admitted.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_a : option (prod nat string) := None.\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(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_b : option (prod nat string) := None.\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.) *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_binary_inverse_c : option (prod nat string) := None.\n(** [] *)\n\n\n(** * Lists: Working with Structured Data *)\n\n(* From 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 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    that worked 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. intros p. destruct p as [n m]. 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.\nintros p. destruct p as [n m]. simpl. reflexivity.\nQed.\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 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=> nil\n      |O::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     |O::t=> (oddmembers t)\n     |h::t=>match evenb 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\nDefinition countoddmembers (l:natlist) : nat:=\n  length(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(** 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, l2 with\n    nil,nil=>nil\n    |nil,l2=> l2\n    |l1,nil=>l1\n    |h1::t1,h2::t2=>h1::h2:: (alternate t1 t2)\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, 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   |nil=>O\n   |h::t=> match eqb h v with\n            |false=> count v t\n            |true=> S(count v t)\n    end\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.\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 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  \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  v::s.\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    |O => false\n    |_=>true\nend.\n    \n\nExample test_member1:             member 1 [1;4;1] = true.\n Proof. 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. *)\n\nFixpoint remove_one (v:nat) (s:bag) : bag:=\n   match s with\n    |nil=> nil\n    |h::t=> match eqb v h with\n             |true=> t\n             |false=> h::(remove_one v t)\nend\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 eqb v h 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.\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, s2 with\n    |nil,nil=> true\n    |nil,s2 => true\n    |s1,nil=> false\n    |h1::t1,h2::t2=> match member h1 s2 with\n                      | true=>subset t1 (remove_one h1 s2) \n                      | false=> false\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(* 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\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 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.\nintros l. induction l as [| n l' 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 l1 l2. induction l1 as [| n l1' 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  intros l1 . induction l1 as [| n l1' IHl1'].\n- simpl. reflexivity.\n- simpl. rewrite rev_app_distr. simpl. rewrite IHl1'. 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.\nintros l1 l2 l3 l4. induction l1 as [| n l1' IHl1'].\n- simpl. rewrite app_assoc. reflexivity.\n- simpl. 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.\nintros l1 l2. induction l1 as [| n l1' IHl1'].\n- simpl. reflexivity.\n- destruct n.\n+ simpl. rewrite IHl1'. reflexivity.\n+ simpl. rewrite IHl1'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (eqblist)  *)\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    |nil,nil=> true\n    |nil,l2=>false\n    |l1,nil=>false\n    |h1::t1,h2::t2=> match eqb h1 h2 with\n                       |true=> eqblist t1 t2\n                       |false=> false\n     end\nend. \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.\nProof. reflexivity. Qed.\n\nExample test_eqblist3 :\n  eqblist [1;2;3] [1;2;4] = false.\n Proof. reflexivity. Qed.\n\nTheorem eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\nintros l. induction l as [| n l1' IHl1'].\n- simpl. reflexivity.\n- destruct n.\n+ simpl. rewrite IHl1'. reflexivity.\n+ simpl. rewrite <-eqb_refl. rewrite IHl1'. 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 (count_member_nonzero)  *)\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  intros l. induction l as [| n l1' IHl1'].\n- simpl. reflexivity.\n- simpl. 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  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  (* 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: *)\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 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\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\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     |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. induction l as [| n l1' IHl1'].\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).\nCheck 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 => n1 =? n2\n  end.\nCheck beq_id.\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 as [n].\n- simpl. induction n as [|n' IHn'].\n+ simpl. reflexivity.\n+ simpl. rewrite IHn'. 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 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. \nintros x d v. induction x as [|x' v' d' IHx'].\n- simpl. rewrite <-beq_id_refl. reflexivity.\n- simpl. rewrite <-beq_id_refl.  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.\nintros d x y o.  intros H. \nsimpl. rewrite H. 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 (x : baz)\n  | Baz2 (y : baz) (b : bool).\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(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil \n  | bool_cons (b : bool) (l : boollist).\nCheck boollist.\nCheck @boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\nCheck list.\nCheck @list.\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.)\n\n    What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list.\n\n(* ===> list : Type -> Type *)\n\n(** The parameter [X] in the definition of [list] becomes a parameter\n    to the constructors [nil] and [cons] -- that is, [nil] and [cons]\n    are now polymorphic constructors, that need to be supplied with\n    the type of the list they are building. As an example, [nil nat]\n    constructs the empty list of type [nat]. *)\n\nCheck (nil nat).\n(* ===> nil nat : list nat *)\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3.*)\n\nCheck (cons nat 3 (nil nat)).\n(* ===> cons nat 3 (nil nat) : list nat *)\n\n(** What might the type of [nil] be? We can read off the type [list X]\n    from the definition, but this omits the binding for [X] which is\n    the parameter to [list]. [Type -> list X] does not explain the\n    meaning of [X]. [(X : Type) -> list X] comes closer. Coq's\n    notation for this situation is [forall X : Type, list X]. *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier\n    is spelled out in letters.  In the generated HTML files and in the\n    way various IDEs show .v files (with certain settings of their\n    display controls), [forall] is usually typeset as the usual\n    mathematical \"upside down A,\" but you'll still see the spelled-out\n    \"forall\" in a few places.  This is just a quirk of typesetting:\n    there is no difference in meaning.) *)\n\n(** Having to supply a type argument for each use of a list\n    constructor may seem an awkward burden, but we will soon see\n    ways of reducing that burden. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've written [nil] and [cons] explicitly here because we haven't\n    yet defined the [ [] ] and [::] notations for the new version of\n    lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\nCheck repeat.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n\n\n(** **** Exercise: 2 stars (mumble_grumble)  *)\n(** Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a \n  | b (x : mumble) (y : nat)\n  | c.\nCheck mumble.\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\nCheck grumble.\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]  *)\n(*1.error occured because no type mentioned \n2.d mumble (b a 5)\n 3.d bool (b a 5)\n4.e bool true\n5.e mumble (b c 0)\n6.error occured because b c 0 is a mumble type.\n7.c*)\nCheck (d mumble (b a 5)). (*grumble mumble*)\nCheck (d bool (b a 5)). (*grumble bool*)\nCheck (e bool true). (*grumble bool*)\nCheck (e mumble (b c 0)). (*grumble mumble*)\nCheck (c). (*mumble*)\nEnd MumbleGrumble.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_mumble_grumble : option (prod nat string) := None.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** It has exactly the same type as [repeat].  Coq was able\n    to use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks, so we will continue to use them most of the time.  You\n    should try to find a balance in your own code between too many\n    type annotations (which can clutter and distract) and too\n    few (which forces readers to perform type inference in their heads\n    in order to understand your code). *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write the \"implicit argument\"\n    [_], which can be read as \"Please try to figure out for yourself\n    what belongs here.\"  More precisely, when Coq encounters a [_], it\n    will attempt to _unify_ all locally available information -- the\n    type of the function being applied, the types of the other\n    arguments, and the type expected by the context in which the\n    application appears -- to determine what concrete type should\n    replace the [_].\n\n    This may sound similar to type annotation inference -- indeed, the\n    two procedures rely on the same underlying mechanisms.  Instead of\n    simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with [_]\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using implicit arguments, the [repeat] function can be written like\n    this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\nCheck repeat'.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use argument synthesis to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** We can go further and even avoid writing [_]'s in most cases by\n    telling Coq _always_ to infer the type argument(s) of a given\n    function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists its argument names, with curly braces\n    around any arguments to be treated as implicit.  (If some\n    arguments of a definition don't have a name, as is often the case\n    for constructors, they can be marked with a wildcard pattern\n    [_].) *)\nCheck nil.\nCheck cons.\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\nCheck nil.\nCheck @nil.\nCheck cons.\nCheck @cons.\nCheck repeat.\nCheck @repeat.\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\nCheck list123''.\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\nCheck repeat'''.\nCheck @repeat'''.\nCheck nil.\nCheck @nil.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat''']; indeed, it would be invalid to\n    provide one!)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil' \n  | cons' (x : X) (l : list').\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\nCheck app.\nCheck @app.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\nCheck rev.\nCheck @rev.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\nCheck length.\nCheck @length.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity.  Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\nCheck @mynil.\n\nDefinition mynil' := @nil nat.\nCheck @mynil'.\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, optional (poly_exercises)  *)\n(** Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n intros X l. induction l as [| n l1' IHl1'].\n- simpl. reflexivity.\n- simpl. rewrite IHl1'. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n intros  X l m n. induction l as [| x l1' IHl1'].\n- simpl. reflexivity.\n- simpl. rewrite IHl1'. reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\nintros X l1 l2. induction l1 as [| n l1' IHl1'].\n- simpl. reflexivity.\n- simpl. rewrite IHl1'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (more_poly_exercises)  *)\n(** Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2. induction l1 as [| n l1' IHl1'].\n- simpl. rewrite app_nil_r. reflexivity.\n- simpl. rewrite-> app_assoc. rewrite IHl1'. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof. intros X l. induction l as [| n l1' IHl1'].\n- simpl. reflexivity.\n- simpl. rewrite rev_app_distr. rewrite IHl1'. simpl. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\nCheck prod.\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types.  This avoids a clash with\n    the multiplication symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\nCheck fst.\nCheck @fst.\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\nCheck snd.\nCheck @snd.\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, optional (combine_checks)  *)\n(** Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print? *)\n(** [] *)\nCheck combine.\nCheck @combine.\nCompute (combine [1;2] [false;false;true;true]).\n(** **** Exercise: 2 stars, recommended (split)  *)\n(** The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y):=\n   match l with\n    |[]=>([],[])\n    |(x,y)::t=>(x :: fst (split t), y :: snd (split t))\nend.\nCheck split.\nCheck @split.\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity.  Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_,\n    which generalize [natoption] from the previous chapter.  (We put\n    the definition inside a module because the standard library\n    already defines [option] and it's this one that we want to use\n    below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X) \n  | None.\nCheck Some.\nCheck @Some.\nCheck option.\nCheck None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | h1 :: t1 => if n =? O then Some h1 else nth_error t1 (pred n)\n  end.\nCheck nth_error.\nCheck @nth_error.\nExample test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\nProof. reflexivity. Qed.\nExample test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (hd_error_poly)  *)\n(** Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n        match l with\n         |[]=>None\n         |h1::t1=> Some h1\nend.\nCheck hd_error.\nCheck @hd_error.\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\n Proof. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\n Proof. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like many other modern programming languages -- including\n    all functional languages (ML, Haskell, Scheme, Scala, Clojure,\n    etc.) -- Coq treats functions as first-class citizens, allowing\n    them to be passed as arguments to other functions, returned as\n    results, stored in data structures, etc.*)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\nCheck @filter.\nCheck filter.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\nCheck length_is_1.\nCheck @length_is_1.\nCompute (length_is_1 [1;2;3]).\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\nCheck countoddmembers'.\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7)  *)\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat:=\n   filter (fun n => leb 7 n) (filter evenb l).\n\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n Proof. reflexivity.  Qed.\n\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n Proof. reflexivity.  Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars (partition)  *)\n(** Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\n(* FILL IN HERE *) Admitted.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y: Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\nCheck (map andb).\nCheck (map negb).\nCheck (map orb).\nCheck map.\nCheck @map.\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars (map_rev)  *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (flat_map)  *)\n(** The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : (list Y):=\n  match l with\n  | []     => []\n  | h :: t => (f h) ++ (flat_map f t)\n  end.\n\nCheck flat_map.\nCheck @flat_map.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\n Proof. reflexivity.  Qed.\n(** [] *)\n\n(** Lists are not the only inductive type that we can write a\n    [map] function for.  Here is the definition of [map] for the\n    [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, optional (implicit_args)  *)\n(** The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n*)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y: Type} (f: X->Y->Y) (l: list X) (b: Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb).\nCheck (fold orb).\n(* ===> fold andb : list bool -> bool -> bool *)\nExample fold_example0 :\n  fold mult [1;2;3;4] 2 = 48.\nProof. reflexivity. Qed.\n\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different)  *)\n(** Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* FILL IN HERE *)\nCheck andb.\nCheck plus.\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_types_different : option (prod nat string) := None.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars (fold_length)  *)\n(** Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n\nintros X l. induction l as [|n' l' IHl'].\n- reflexivity.\n- simpl. rewrite <-IHl'. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (fold_map)  *)\n(** We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y:=\n   fold (fun h lt => f h :: lt) l [].\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  *)\n(** In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)\n(** Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X n l, length l = n -> @nth_error X l n = None\n*)\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (prod nat string) := None.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (church_numerals)  *)\n(** This exercise explores an alternative way of defining natural\n    numbers, using the so-called _Church numerals_, named after\n    mathematician Alonzo Church.  We can represent a natural number\n    [n] as a function that takes a function [f] as a parameter and\n    returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : nat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** Successor of a natural number: *)\n\nDefinition succ (n : nat) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample succ_1 : succ zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_2 : succ one = two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample succ_3 : succ two = three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Addition of two natural numbers: *)\n\nDefinition plus (n m : nat) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample plus_1 : plus zero one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_2 : plus two three = plus three two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* FILL IN HERE *) Admitted.\n\n(** Multiplication: *)\n\nDefinition mult (n m : nat) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample mult_1 : mult one one = one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* FILL IN HERE *) Admitted.\n\nExample mult_3 : mult two three = plus three three.\nProof. (* FILL IN HERE *) Admitted.\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type: [nat] itself is usually problematic.) *)\n\nDefinition exp (n m : nat) : nat\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample exp_1 : exp two two = plus two two.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. (* FILL IN HERE *) Admitted.\n\nExample exp_3 : exp three zero = one.\nProof. (* FILL IN HERE *) Admitted.\n\nEnd Church.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_succ_plus_mult_exp : option (prod nat string) := None.\n(** [] *)\n\nEnd Exercises.\n\n\n(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to strengthen an induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\n\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can achieve the same effect in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex :\n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     oddb 3 = true ->\n     evenb 4 = true.\nProof.\nintros eq1 eq2.\n  apply eq2.\n  Qed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = (n =? 5)  ->\n     (S (S n)) =? 7 = true.\nProof.\n  intros n H.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (** (This [simpl] is optional, since [apply] will perform\n             simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [Search] is\n    your friend.) *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros l l' H.\nrewrite H.\nsymmetry.\napply  rev_involutive. Check rev_involutive.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied? *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply with] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\nintros n m o p H1 H2.\napply trans_eq with m.\napply H2.\napply H1. \n\n  Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [injection] and [discriminate] Tactics *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n].\n\n    Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not\n    interesting.)  And so on. *)\n\n(** We can prove the injectivity of [S] directly by using the [pred]\n    function defined in [Basics.v]. *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H1.\n  assert (H2: n = pred (S n)). { reflexivity. }\n  rewrite H2. rewrite H1. reflexivity.\nQed.\n\n(** This technique can be generalized to any constructor by\n    writing the equivalent of [pred] for that constructor, namely a\n    function that \"undoes\" one application. As a more convenient\n    alternative, Coq provides a tactic called [injection] that allow\n    us to exploit the injectivity of any constructor.  To see how to\n    use [injection], we give an alternate proof of the above theorem: *)\n\nTheorem S_injective' : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [injection H] at this point, we are asking Coq to\n    generate all equations that it can infer from [H] using the\n    injectivity of constructors. Each such equation is added as a\n    premise to the goal. In the present example, this\n    amounts to adding the premise [n = m]. *)\n\n  injection H. intro Hnm. apply Hnm.\nQed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem injection_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. \n  injection H. intros H1 H2.\n  rewrite H1. rewrite H2. reflexivity.\nQed.\n\n(** The \"as\" variant of [injection] introduces each equation\n    as a hypothesis in the context, allowing us to specify as\n    many names as there are equations. *)\n\nTheorem injection_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. \n  injection H as Hnm. rewrite Hnm.\n  reflexivity. Qed.\n\n(** **** Exercise: 1 star (injection_ex3)  *)\nExample injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\nintros X x y z. intros l j. intros H1. intros H2.\ninjection H1 as Hxz. injection H2 as Hyx. symmetry. apply Hyx.\n\nQed.\n(** [] *)\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [discriminate] solves the\n    goal immediately.  Consider the following proof: *)\n\nTheorem eqb_0_l : forall n,\n   0 =? n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [0 =? (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [0 =? (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [discriminate] on this hypothesis, Coq confirms that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. discriminate H.\nQed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything, even false things! *)\n\nTheorem discriminate_ex1 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. discriminate contra. Qed. \n\nTheorem discriminate_ex2 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. discriminate contra. Qed. \n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that, if the\n    nonsensical situation described by the premise did somehow arise,\n    then the nonsensical conclusion would follow.  We'll explore the\n    principle of explosion of more detail in the next chapter. *)\n\n(** **** Exercise: 1 star (discriminate_ex3)  *)\nExample discriminate_ex3 :\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] ->\n    y :: l = z :: j ->\n    x = z.\nProof.\nintros X x y z. intros l j. intros H1. intros H2. discriminate H1.\nQed.\n(** [] *)\n\n(** In general, suppose [H] is a hypothesis in the context\n    of the form [e1 = e2]. Then:\n\n    - If [e1 = c a1 a2 ... an] and [e2 = c b1 b2 ... bn],\n      then by the injectivity of the constructor [c], \n      we know that [a1 = b1], [a2 = b2], etc.\n      [injection H] works recursively on these.\n\n    - If one of [ai] and [bi] does not have an outermost constructor\n      (e.g, it is a variable or function application), then the\n      equality [ai = bi] is added as a premise to the goal,\n      or to the context if an intro pattern is used with [injection H].\n\n    - If [e1] and [e2] have different outer constructors\n      (or [ai] and [bi], or two deeper subexpressions found recursively\n      in equivalent positions), then [injection H] will fail. \n      But in this case, the hypothesis [H] is contradictory,\n      and the current goal doesn't have to be considered at all.\n      [discriminate H] marks the current goal as completed and \n      pops it off the goal stack. *)\n\n\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find convenient in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     (S n) =? (S m) = b  ->\n     n =? m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [L1 -> L2] and a hypothesis matching [L1], it\n    produces a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [L1->L2] and we are\n    trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\nTheorem silly3' : forall (n : nat),\n  (n =? 5 = true -> (S (S n)) =? 7 = true) ->\n  true = (n =? 5)  ->\n  true = ((S (S n)) =? 7).\nProof.\n  intros n eq H.\n  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this proof.  (Hint: use\n    [plus_n_Sm].) *)\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- intros m eq. simpl in eq. destruct m as [| m'].\n+ reflexivity.\n+ simpl in eq. discriminate eq.\n- intros m eq. destruct m as [|m'].\n+ simpl in eq. discriminate eq.\n+ apply f_equal. apply IHn'. Check f_equal.\nsimpl in eq. rewrite<- plus_n_Sm in eq.\nrewrite <- plus_n_Sm in eq.\n\ninjection eq as H. apply H. Qed.   (* FILL IN HERE *) \n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it maps different arguments to different results:\n\n    Theorem double_injective: forall n m,\n      double n = double m -> n = m.\n\n    The way we _start_ this proof is a bit delicate: if we begin with\n\n      intros n. induction n.\n\n    all is well.  But if we begin it with\n\n      intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) discriminate eq. \n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) discriminate eq.\n    + (* m = S m' *) apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a relation involving _every_ [n] but just a _single_ [m]. *)\n\n(** The successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) discriminate eq. \n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      discriminate eq. \n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. injection eq as goal. apply goal. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: To prove a property of [n] and [m] by induction on [n],\n    it is sometimes important to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (eqb_true)  *)\nTheorem eqb_true : forall n m,\n    n =? m = true -> n = m.\nProof.\n intros n. induction n as [| n'].\n- intros m eq. destruct m as [| m'].\n+ reflexivity.\n+ discriminate eq. \n- intros m eq.  destruct m as [| m'].\n+  discriminate eq.\n+ apply f_equal. apply IHn'. apply eq. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (eqb_true_informal)  *)\n(** Give a careful informal proof of [eqb_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (prod nat string) := None.\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq. \n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) discriminate eq. \n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m.\n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) discriminate eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) discriminate eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. injection eq as goal. apply goal. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by injectivity that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises,\n    let's digress briefly and use [eqb_true] to prove a similar\n    property of identifiers that we'll need in later chapters: *)\n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply eqb_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros  n X l.  generalize dependent n.  induction l as [| l' ].\n- simpl. reflexivity. \n- intros n H. destruct n as [|n'].\n+ simpl. discriminate H.\n+ simpl. apply IHl. simpl in H. injection H as goal. apply goal.  \nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a Definition\n    so that we can manipulate its right-hand side.  For example, if we\n    define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we get stuck: [simpl] doesn't simplify anything at this point,\n    and since we haven't proved any other facts about [square], there\n    is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these facts it is not\n    hard to finish the proof. *)\n\n  rewrite mult_assoc. Check mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  { rewrite mult_comm. apply mult_assoc. } Check mult_comm. Check mult_assoc.\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, a deeper discussion of unfolding and simplification\n    is in order.\n\n    You may already have observed that tactics like [simpl],\n    [reflexivity], and [apply] will often unfold the definitions of\n    functions automatically when this allows them to make progress.  For\n    example, if we define [foo m] to be the constant [5]... *)\n\nDefinition foo (x: nat) := 5.\n\n(** then the [simpl] in the following proof (or the [reflexivity], if\n    we omit the [simpl]) will unfold [foo m] to [(fun x => 5) m] and\n    then further simplify this expression to just [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is rather conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  It is not smart enough to notice that the\n    two branches of the [match] are identical, so it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that, itself, cannot be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone. *)\n\n(** At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress. *)\n\n(** A more straightforward way to make progress is to explicitly tell\n    Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if n =? 3 then false\n  else if n =? 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (n =? 3).\n    - (* n =? 3 = true *) reflexivity.\n    - (*  3 =? = false *) destruct (n =? 5).\n      + (* n =? 5 = true *) reflexivity.\n      + (* n =? 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (n =? 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (eqb\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\n(** Here is an implementation of the [split] function mentioned in\n    chapter [Poly]: *)\n\nFixpoint split1 {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (x, y) :: t =>\n      match split t with\n      | (lx, ly) => (x :: lx, y :: ly)\n      end\n  end.\n\n(** Prove that [split] and [combine] are inverses in the following\n    sense: *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\nAdmitted.\n\n\n(** [] *)\n\n(** However, [destruct]ing compound expressions requires a bit of\n    care, as such [destruct]s can sometimes erase information we need\n    to complete a proof. *)\n(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if n =? 3 then true\n  else if n =? 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution performed by [destruct] is too brutal -- it threw\n    away every occurrence of [n =? 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that, since [n =? 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [n =? 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (n =? 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply eqb_true in Heqe3. Check eqb_true.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (n =? 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply eqb_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) discriminate eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f . intros b. destruct ( f b) eqn:H1.\n- destruct b as[|b']. \n+ rewrite H1. apply H1.\n+ destruct (f true) eqn:H2.\n{ rewrite H2. reflexivity. }\n{ rewrite H1. reflexivity. }\n- destruct b as[|b']. \n+ destruct (f false) eqn:H3. \n{ rewrite H1. reflexivity.  }\n{ rewrite H3. reflexivity. }\n+ rewrite H1.  apply H1. \nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [injection]: reason by injectivity on equalities \n        between values of inductively defined types\n\n      - [discriminate]: reason by disjointness of constructors on\n        equalities between values of inductively defined types\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n  \n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (eqb_sym)  *)\nTheorem eqb_sym : forall (n m : nat),\n  (n =? m) = (m =? n).\nProof.\nintros n. induction n as [| n'].\n- induction m as [| m'].\n+ reflexivity.\n+ simpl. reflexivity.\n- induction m as [| m'].\n+ simpl. reflexivity.\n+ simpl. apply IHn'.\nQed. \n  (* FILL IN HERE *) \n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (eqb_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [eqb n m = eqb m n].\n\n   Proof: *)\n   (* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (eqb_trans)  *)\nTheorem eqb_trans : forall n m p,\n  eqb n m = true ->\n  eqb m p = true ->\n  eqb n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split (combine l1 l2) = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop:=\n  (* (\"[: Prop]\" means that we are giving a name to a\n     logical proposition here.) *)\n  forall X Y (l : list (X * Y)) l1 l2,\n  (length l1) = (length l2) ->\n  combine l1 l2 = l ->  \n  split l = (l1, l2).\n\nTheorem split_combine : split_combine_statement.\nProof.\nunfold split_combine_statement.\n  intros X Y.\n  intros l l1 l2.\n  generalize dependent l.\n  generalize dependent l2.\n  induction l1 as [|h t].\n\n-  simpl.\n  intros l2.\n  destruct l2 as [|h2 t2].\n  intros l e1 e2.\n  rewrite <- e2.\n  reflexivity.\n  intros l e1 e2.\n  inversion e1.\n\n-  intros l2 l e1 e2.\n  destruct l2 as [|h2 t2].\n  inversion e1.\n  destruct l as [|p q].\n  inversion e2.\n  simpl.\n  simpl in e1.\n  inversion e1.\n  inversion e2.\n  simpl.\n\n  assert (G : (split (combine t t2)) = (t, t2)).\n  rewrite combine_split with (l:=q).\n  rewrite IHt with (l:=q) (l2:=t2).\n  reflexivity.\n  apply H0.\n  apply H2.\n  rewrite IHt with (l:=q) (l2:=t2).\n  reflexivity.\n  apply H0.\n  apply H2.\n  rewrite G.\n  simpl.\n  reflexivity.\nQed.\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_split_combine : option (prod nat string) := None.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (eqb 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (eqb 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  fold (fun x ans => (andb (test x) ans)) l true.\n\nExample forallb1 :\n      forallb oddb [1;3;5;7;9] = true.\nProof. reflexivity. Qed.\nExample forallb2 :\n      forallb negb [false;false] = true.\nProof. reflexivity. Qed. \nExample forallb3 :\n      forallb evenb [0;2;4;5] = false.\nProof. reflexivity. Qed.\nExample forallb4 :\n      forallb (eqb 5) [] = true.\nProof. reflexivity. Qed.\n\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  fold (fun x ans => (orb (test x) ans)) l false.\n\nExample existsb1 :\n      existsb (eqb 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\nExample existsb2 :\n      existsb (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\nExample existsb3 :\n      existsb oddb [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\nExample existsb4 : \n      existsb evenb [] = false.\nProof. reflexivity. Qed.\n\nFixpoint existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=\n  negb (forallb (fun x => negb (test x)) l).\n\nTheorem existsb_same : forall (X : Type) (test : X -> bool) (l : list X),\n  (existsb test l) = (existsb' test l).\nProof.\n intros X test l.\n induction l as [|h t].\n - simpl. reflexivity.\n - simpl. (* intros test. *)\n  destruct (test h) eqn : T.\n  simpl. reflexivity.\nAbort.\n\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_forall_exists_challenge : option (prod nat string) := None.\n(** [] *)\n\n\n", "meta": {"author": "arn1992", "repo": "Software-Foundations-", "sha": "a94d06a4b3eb97d2731304a502617a133d2098e6", "save_path": "github-repos/coq/arn1992-Software-Foundations-", "path": "github-repos/coq/arn1992-Software-Foundations-/Software-Foundations--a94d06a4b3eb97d2731304a502617a133d2098e6/a4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509007, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7216718520609808}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia Coq.ZArith.Znumtheory Coq.ZArith.Zpow_facts.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.ZSimplify.Core.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma elim_mod : forall a b m, a = b -> a mod m = b mod m.\n  Proof. intros; subst; auto. Qed.\n  Hint Resolve elim_mod : zarith.\n\n  Lemma mod_add_full : forall a b c, (a + b * c) mod c = a mod c.\n  Proof. intros a b c; destruct (Z_zerop c); try subst; autorewrite with zsimplify; reflexivity. Qed.\n  Hint Rewrite mod_add_full : zsimplify.\n\n  Lemma mod_add_l_full : forall a b c, (a * b + c) mod b = c mod b.\n  Proof. intros a b c; rewrite (Z.add_comm _ c); autorewrite with zsimplify; reflexivity. Qed.\n  Hint Rewrite mod_add_l_full : zsimplify.\n\n  Lemma mod_add'_full : forall a b c, (a + b * c) mod b = a mod b.\n  Proof. intros a b c; rewrite (Z.mul_comm _ c); autorewrite with zsimplify; reflexivity. Qed.\n  Lemma mod_add_l'_full : forall a b c, (a * b + c) mod a = c mod a.\n  Proof. intros a b c; rewrite (Z.mul_comm _ b); autorewrite with zsimplify; reflexivity. Qed.\n  Hint Rewrite mod_add'_full mod_add_l'_full : zsimplify.\n\n  Lemma mod_add_l : forall a b c, b <> 0 -> (a * b + c) mod b = c mod b.\n  Proof. intros a b c H; rewrite (Z.add_comm _ c); autorewrite with zsimplify; reflexivity. Qed.\n\n  Lemma mod_add' : forall a b c, b <> 0 -> (a + b * c) mod b = a mod b.\n  Proof. intros a b c H; rewrite (Z.mul_comm _ c); autorewrite with zsimplify; reflexivity. Qed.\n  Lemma mod_add_l' : forall a b c, a <> 0 -> (a * b + c) mod a = c mod a.\n  Proof. intros a b c H; rewrite (Z.mul_comm _ b); autorewrite with zsimplify; reflexivity. Qed.\n\n  Lemma add_pow_mod_l : forall a b c, a <> 0 -> 0 < b ->\n                                      ((a ^ b) + c) mod a = c mod a.\n  Proof.\n    intros a b c H H0; replace b with (b - 1 + 1) by ring;\n      rewrite Z.pow_add_r, Z.pow_1_r by omega; auto using Z.mod_add_l.\n  Qed.\n\n  Lemma mod_exp_0 : forall a x m, x > 0 -> m > 1 -> a mod m = 0 ->\n    a ^ x mod m = 0.\n  Proof.\n    intros a x m H H0 H1.\n    replace x with (Z.of_nat (Z.to_nat x)) in * by (apply Z2Nat.id; omega).\n    induction (Z.to_nat x). {\n      simpl in *; omega.\n    } {\n      rewrite Nat2Z.inj_succ in *.\n      rewrite Z.pow_succ_r by omega.\n      rewrite Z.mul_mod by omega.\n      case_eq n; intros. {\n        subst. simpl.\n        rewrite Zmod_1_l by omega.\n        rewrite H1.\n        apply Zmod_0_l.\n      } {\n        subst.\n        rewrite IHn by (rewrite Nat2Z.inj_succ in *; omega).\n        rewrite H1.\n        auto.\n      }\n    }\n  Qed.\n\n  Lemma mod_pow : forall (a m b : Z), (0 <= b) -> (m <> 0) ->\n      a ^ b mod m = (a mod m) ^ b mod m.\n  Proof.\n    intros a m b H H0; rewrite <- (Z2Nat.id b) by auto.\n    induction (Z.to_nat b) as [|n IHn]; auto.\n    rewrite Nat2Z.inj_succ.\n    do 2 rewrite Z.pow_succ_r by apply Nat2Z.is_nonneg.\n    rewrite Z.mul_mod by auto.\n    rewrite (Z.mul_mod (a mod m) ((a mod m) ^ Z.of_nat n) m) by auto.\n    rewrite <- IHn by auto.\n    rewrite Z.mod_mod by auto.\n    reflexivity.\n  Qed.\n\n  Lemma mod_to_nat x m (Hm:(0 < m)%Z) (Hx:(0 <= x)%Z) : (Z.to_nat x mod Z.to_nat m = Z.to_nat (x mod m))%nat.\n    pose proof Zdiv.mod_Zmod (Z.to_nat x) (Z.to_nat m) as H;\n      rewrite !Z2Nat.id in H by omega.\n    rewrite <-H by (change 0%nat with (Z.to_nat 0); rewrite Z2Nat.inj_iff; omega).\n    rewrite !Nat2Z.id; reflexivity.\n  Qed.\n\n  Lemma mul_div_eq_full : forall a m, m <> 0 -> m * (a / m) = (a - a mod m).\n  Proof.\n    intros a m H. rewrite (Z_div_mod_eq_full a m) at 2 by auto. ring.\n  Qed.\n\n  Hint Rewrite mul_div_eq_full using zutil_arith : zdiv_to_mod.\n  Hint Rewrite <-mul_div_eq_full using zutil_arith : zmod_to_div.\n\n  Lemma f_equal_mul_mod x y x' y' m : x mod m = x' mod m -> y mod m = y' mod m -> (x * y) mod m = (x' * y') mod m.\n  Proof.\n    intros H0 H1; rewrite Zmult_mod, H0, H1, <- Zmult_mod; reflexivity.\n  Qed.\n  Hint Resolve f_equal_mul_mod : zarith.\n\n  Lemma f_equal_add_mod x y x' y' m : x mod m = x' mod m -> y mod m = y' mod m -> (x + y) mod m = (x' + y') mod m.\n  Proof.\n    intros H0 H1; rewrite Zplus_mod, H0, H1, <- Zplus_mod; reflexivity.\n  Qed.\n  Hint Resolve f_equal_add_mod : zarith.\n\n  Lemma f_equal_opp_mod x x' m : x mod m = x' mod m -> (-x) mod m = (-x') mod m.\n  Proof.\n    intro H.\n    destruct (Z_zerop (x mod m)) as [H'|H'], (Z_zerop (x' mod m)) as [H''|H''];\n      try congruence.\n    { rewrite !Z_mod_zero_opp_full by assumption; reflexivity. }\n    { rewrite Z_mod_nz_opp_full, H, <- Z_mod_nz_opp_full by assumption; reflexivity. }\n  Qed.\n  Hint Resolve f_equal_opp_mod : zarith.\n\n  Lemma f_equal_sub_mod x y x' y' m : x mod m = x' mod m -> y mod m = y' mod m -> (x - y) mod m = (x' - y') mod m.\n  Proof.\n    rewrite <- !Z.add_opp_r; auto with zarith.\n  Qed.\n  Hint Resolve f_equal_sub_mod : zarith.\n\n  Lemma mul_div_eq : forall a m, m > 0 -> m * (a / m) = (a - a mod m).\n  Proof.\n    intros a m H.\n    rewrite (Z_div_mod_eq a m) at 2 by auto.\n    ring.\n  Qed.\n\n  Lemma mul_div_eq' : (forall a m, m > 0 -> (a / m) * m = (a - a mod m))%Z.\n  Proof.\n    intros a m H.\n    rewrite (Z_div_mod_eq a m) at 2 by auto.\n    ring.\n  Qed.\n\n  Hint Rewrite mul_div_eq mul_div_eq' using zutil_arith : zdiv_to_mod.\n  Hint Rewrite <- mul_div_eq' using zutil_arith : zmod_to_div.\n\n  Lemma mod_div_eq0 : forall a b, 0 < b -> (a mod b) / b = 0.\n  Proof.\n    intros.\n    apply Z.div_small.\n    auto using Z.mod_pos_bound.\n  Qed.\n  Hint Rewrite mod_div_eq0 using zutil_arith : zsimplify.\n\n  Local Lemma mod_pull_div_helper a b c X\n        (HX : forall a b c d e f g,\n            X a b c d e f g = if a =? 0 then c else 0)\n    : 0 <> b\n      -> 0 <> c\n      -> (a / b) mod c\n         = (a mod (c * b)) / b\n           + if c <? 0 then - X ((a / b) mod c) (a mod (c * b)) ((a mod (c * b)) / b) a b c (a / b) else 0.\n  Proof.\n    intros; break_match; Z.ltb_to_lt; rewrite ?Z.sub_0_r, ?Z.add_0_r;\n      assert (0 <> c * b) by nia; Z.div_mod_to_quot_rem; subst;\n        destruct_head'_or; destruct_head'_and;\n          try assert (b < 0) by omega;\n          try assert (c < 0) by omega;\n          Z.replace_all_neg_with_pos;\n          try match goal with\n              | [ H : ?c * ?b * ?q1 + ?r1 = ?b * (?c * ?q2 + _) + _ |- _ ]\n                => assert (q1 = q2) by nia; progress subst\n              end;\n          rewrite ?HX; clear HX X;\n          try nia;\n          repeat match goal with\n                 | [ |- - ?x = ?y ] => is_var y; assert (y <= 0) by nia; Z.replace_all_neg_with_pos\n                 | [ |- - ?x = ?y + -_ ] => is_var y; assert (y <= 0) by nia; Z.replace_all_neg_with_pos\n                 | [ H : -?x + (-?y + ?z) = -?w + ?v |- _ ]\n                   => assert (x + (y + -z) = w + -v) by omega; clear H\n                 | [ H : ?c * ?b * ?q1 + (?b * ?q2 + ?r) = ?b * (?c * ?q1' + ?q2') + ?r' |- _ ]\n                   => assert (c * q1 + q2 = c * q1' + q2') by nia;\n                        assert (r = r') by nia;\n                        clear H\n                 | [ H : -?x < -?y + ?z |- _ ] => assert (y + -z < x) by omega; clear H\n                 | [ H : -?x + ?y <= 0 |- _ ] => assert (0 <= x + -y) by omega; clear H\n                 | _ => progress Z.clean_neg\n                 | _ => progress subst\n                 end.\n    all:match goal with\n        | [ H : ?c * ?q + ?r = ?c * ?q' + ?r' |- _ ]\n          => first [ constr_eq q q'; assert (r = r') by nia; clear H\n                   | assert (q = q') by nia; assert (r = r') by nia; clear H\n                   | lazymatch goal with\n                     | [ H' : r' < c |- _ ]\n                       => destruct (Z_dec' r c) as [[?|?]|?]\n                     | [ H' : r < c |- _ ]\n                       => destruct (Z_dec' r' c) as [[?|?]|?]\n                     end;\n                     subst;\n                     [ assert (q = q') by nia; assert (r = r') by nia; clear H\n                     | nia\n                     | first [ assert (1 + q = q') by nia | assert (q = 1 + q') by nia ];\n                       first [ assert (r' = 0) by nia | assert (r = 0) by nia ] ] ]\n        end.\n    all:try omega.\n    all:break_match; Z.ltb_to_lt; omega.\n  Qed.\n\n  Lemma mod_pull_div_full a b c\n    : (a / b) mod c\n      = if ((c <? 0) && ((a / b) mod c =? 0))%bool\n        then 0\n        else (a mod (c * b)) / b.\n  Proof.\n    destruct (Z_zerop b), (Z_zerop c); subst;\n      autorewrite with zsimplify; try reflexivity.\n    { break_match; Z.ltb_to_lt; omega. }\n    { erewrite mod_pull_div_helper at 1 by (omega || reflexivity); cbv beta.\n      destruct (c <? 0) eqn:?; simpl; [ | omega ].\n      break_innermost_match; omega. }\n  Qed.\n\n  Lemma mod_pull_div a b c\n    : 0 <= c -> (a / b) mod c = a mod (c * b) / b.\n  Proof. rewrite mod_pull_div_full; destruct (c <? 0) eqn:?; Z.ltb_to_lt; simpl; omega. Qed.\n\n  Lemma small_mod_eq a b n: a mod n = b mod n -> 0 <= a < n -> a = b mod n.\n  Proof. intros; rewrite <-(Z.mod_small a n); auto. Qed.\n\n  Lemma mod_pow_full p q n : (p^q) mod n = ((p mod n)^q) mod n.\n  Proof.\n    destruct (Z_dec' n 0) as [ [H|H] | H]; subst;\n      [\n      | apply Zpower_mod; assumption\n      | rewrite !Zmod_0_r; reflexivity ].\n    { revert H.\n      rewrite <- (Z.opp_involutive (p^q)),\n      <- (Z.opp_involutive ((p mod n)^q)),\n      <- (Z.opp_involutive p),\n      <- (Z.opp_involutive n).\n      generalize (-n); clear n; intros n H.\n      rewrite !Zmod_opp_opp.\n      rewrite !Z.opp_involutive.\n      apply f_equal.\n      destruct (Z.Even_or_Odd q).\n      { rewrite !Z.pow_opp_even by (assumption || omega).\n        destruct (Z.eq_dec (p^q mod n) 0) as [H'|H'], (Z.eq_dec ((-p mod n)^q mod n) 0) as [H''|H''];\n          repeat first [ rewrite Z_mod_zero_opp_full by assumption\n                       | rewrite Z_mod_nz_opp_full by assumption\n                       | reflexivity\n                       | rewrite <- Zpower_mod, Z.pow_opp_even in H'' by (assumption || omega); omega\n                       | rewrite <- Zpower_mod, Z.pow_opp_even in H'' |- * by (assumption || omega); omega ]. }\n      { rewrite Z.pow_opp_odd, !Z.opp_involutive, <- Zpower_mod, Z.pow_opp_odd, ?Z.opp_involutive by (assumption || omega).\n        reflexivity. } }\n  Qed.\n\n  Lemma mod_bound_min_max l x u d (H : l <= x <= u)\n    : (if l / d =? u / d then Z.min (l mod d) (u mod d) else Z.min 0 (d + 1))\n      <= x mod d\n      <= if l / d =? u / d then Z.max (l mod d) (u mod d) else Z.max 0 (d - 1).\n  Proof.\n    destruct (Z_dec d 0) as [ [?|?] | ? ];\n      try solve [ subst; autorewrite with zsimplify; simpl; split; reflexivity\n                | repeat first [ progress Z.div_mod_to_quot_rem\n                               | progress subst\n                               | progress break_innermost_match\n                               | progress Z.ltb_to_lt\n                               | progress destruct_head'_or\n                               | progress destruct_head'_and\n                               | progress apply Z.min_case_strong\n                               | progress apply Z.max_case_strong\n                               | progress intros\n                               | omega\n                               | match goal with\n                                 | [ H : ?x <= ?y, H' : ?y <= ?x |- _ ] => assert (x = y) by omega; clear H H'\n                                 | _ => progress subst\n                                 | [ H : ?d * ?q0 + ?r0 = ?d * ?q1 + ?r1 |- _ ]\n                                   => assert (q0 = q1) by nia; subst q0\n                                 | [ H : ?d * ?q0 + ?r0 <= ?d * ?q1 + ?r1 |- _ ]\n                                   => assert (q0 = q1) by nia; subst q0\n                                 end ] ].\n  Qed.\nEnd Z.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Util/ZUtil/Modulo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7216526723498266}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) (lf1 : natural)\n  : natural := mult (Succ y) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj194_coqofml_4HOO1K.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7216520396541123}}
{"text": "Require Import List.\nImport ListNotations.\n\nInductive Forall3 {A B C : Type} (R : A -> B -> C -> Prop) : list A -> list B -> list C -> Prop :=\n| Forall3_nil : Forall3 R [] [] []\n| Forall3_cons : forall x y z xs ys zs,\n        R x y z ->\n        Forall3 R xs ys zs ->\n        Forall3 R (x :: xs) (y :: ys) (z :: zs).\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/Forall3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7216520331543403}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Hints.ZArith.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma mod_mod_small a n m\n        (Hnm : (m mod n = 0)%Z)\n        (Hnm_le : (0 < n <= m)%Z)\n        (H : (a mod m < n)%Z)\n    : ((a mod n) mod m = a mod m)%Z.\n  Proof.\n    assert ((a mod n) < m)%Z\n      by (eapply Z.lt_le_trans; [ apply Z.mod_pos_bound | ]; lia).\n    rewrite (Z.mod_small _ m) by auto with zarith.\n    apply Z.mod_divide in Hnm; [ | lia ].\n    destruct Hnm as [x ?]; subst.\n    repeat match goal with\n           | [ H : context[(_ mod _)%Z] |- _ ]\n             => revert H\n           end.\n    Z.div_mod_to_quot_rem_in_goal.\n    lazymatch goal with\n    | [ H : a = (?x * ?n * ?q) + _, H' : a = (?n * ?q') + _ |- _ ]\n      => assert (q' = x * q) by nia; subst q'; nia\n    end.\n  Qed.\n\n  (** [rewrite_mod_small] is a better version of [rewrite Z.mod_small\n      by rewrite_mod_small_solver]; it backtracks across occurences\n      that the solver fails to solve the side-conditions on. *)\n  Ltac rewrite_mod_small_solver :=\n    zutil_arith_more_inequalities.\n  Ltac rewrite_mod_small :=\n    repeat match goal with\n           | [ |- context[?x mod ?y] ]\n             => rewrite (Z.mod_small x y) by rewrite_mod_small_solver\n           end.\n  Ltac rewrite_mod_mod_small :=\n    repeat match goal with\n           | [ |- context[(?a mod ?n) mod ?m] ]\n             => rewrite (mod_mod_small a n m) by rewrite_mod_small_solver\n           end.\n  Ltac rewrite_mod_small_more :=\n    repeat (rewrite_mod_small || rewrite_mod_mod_small).\n  Ltac rewrite_mod_small_in_hyps :=\n    repeat match goal with\n           | [ H : context[?x mod ?y] |- _ ]\n             => rewrite (Z.mod_small x y) in H by rewrite_mod_small_solver\n           end.\n  Ltac rewrite_mod_mod_small_in_hyps :=\n    repeat match goal with\n           | [ H : context[(?a mod ?n) mod ?m] |- _ ]\n             => rewrite (mod_mod_small a n m) in H by rewrite_mod_small_solver\n           end.\n  Ltac rewrite_mod_small_more_in_hyps :=\n    repeat (rewrite_mod_small_in_hyps || rewrite_mod_mod_small_in_hyps).\n  Ltac rewrite_mod_small_in_all := repeat (rewrite_mod_small || rewrite_mod_small_in_hyps).\n  Ltac rewrite_mod_mod_small_in_all := repeat (rewrite_mod_mod_small || rewrite_mod_mod_small_in_hyps).\n  Ltac rewrite_mod_small_more_in_all := repeat (rewrite_mod_small_more || rewrite_mod_small_more_in_hyps).\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/Tactics/RewriteModSmall.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7216416118129764}}
{"text": "Definition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\n  f (fst p) (snd p).\n\nTheorem uncurry_curry : forall(X Y Z : Type) (f : X -> Y -> Z) x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros.\n  unfold prod_curry, prod_uncurry.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry : forall(X Y Z : Type)\n  (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros.\n  unfold prod_curry, prod_uncurry.\n  destruct p as [a b].\n  simpl.\n  reflexivity.\nQed.\n", "meta": {"author": "yurrriq", "repo": "learning-coq", "sha": "0a14a550497bef6c0a50b531fea6911b73ec212e", "save_path": "github-repos/coq/yurrriq-learning-coq", "path": "github-repos/coq/yurrriq-learning-coq/learning-coq-0a14a550497bef6c0a50b531fea6911b73ec212e/prod_curry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.721641593228605}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #4 : 2 stars (filter_even_gt7) *)\n\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nFixpoint greater_than (a b:nat) : bool :=\nmatch a with\n| O => false\n| S n => match b with\n        | O => true\n        | S m => greater_than n m\n        end\nend.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => andb (evenb n) (greater_than n 7)) l\n.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\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/04/P05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7216415927142052}}
{"text": "Require Import ssreflect Nat PeanoNat Le Logic Lia.\n\nOpen Scope nat_scope.\n\nTheorem nat_strong_ind : forall P : nat -> Prop,\nP 0 -> (forall n, (forall k, k <= n -> P k) -> P (S n)) -> forall n, P n.\nProof.\n  move=> P P0 SI n.\n  assert (exists k, n <= k); first by exists n.\n  case: H => k.\n  move: n.\n  induction k.\n  - move=> n Le.\n    destruct n.\n    + exact P0.\n    + lia.\n  - move=> n H.\n    apply Nat.lt_eq_cases in H.\n    case: H => H.\n    + apply IHk.\n      lia.\n    + rewrite H.\n      apply SI => x.\n      apply IHk.\nQed.\n\nTheorem nat_strong2_ind : forall P : nat -> Prop,\n(forall n, (forall k, k < n -> P k) -> P n) -> forall n, P n.\nProof.\n  move=> P SI n.\n  refine (nat_strong_ind P _ _ n).\n  - apply: SI.\n    move=> k Lt.\n    inversion Lt.\n  - move=> m OSI.\n    apply: SI.\n    move=> k Lt.\n    apply: OSI.\n    lia.\nQed.\n\nTheorem nat_even_odd_ind : forall P : nat -> Prop,\nP 0 -> P 1 -> (forall n , P n -> P (2 + n)) -> forall n, P n.\nProof.\n  move=> P P0 P1 IH.\n  fix H 1.\n  case=> [|[|n]]; [exact: P0|exact: P1| ].\n  apply: IH.\n  apply: H.\n  Show Proof.\nQed.\n\nTheorem nat_my_ind : forall P : nat -> Prop,\nP 0 -> (forall n , P n -> P (S n)) -> forall n, P n.\nProof.\n  move=> P P0 IH.\n  fix H 1.\n  case=> [|n]; [exact: P0| ].\n  apply: IH.\n  apply: H.\nQed.\n\nFixpoint nat_my_def_ind (P : nat -> Prop)\n    (p0 : P 0) (ih : (forall n, P n -> P (S n))) (n : nat) : P n :=\n  match n with\n    | 0 => p0\n    | (S m) => ih m (nat_my_def_ind P p0 ih m)\n  end.\n\n\nTheorem even_odd_dec n: exists m, n = m * 2 \\/ n = 1 + m * 2.\nProof.\n  elim/nat_even_odd_ind: n => [ | | n H]; try exists 0; lia.\n  case: H => [m [-> | ->]]; by exists (m + 1); lia.\nQed.\n\nTheorem name : forall A B C : Prop, ((A -> B) /\\ (A -> C)) <-> (A -> B /\\ C).\nProof.\n  move=> A B C.\n  split.\n  - move=> [ab ac] a.\n    split.\n    + exact (ab a).\n    + exact (ac a).\n  - move=> abc.\n    split.\n    + move=> a.\n      move: (abc a) => [b c].\n      exact b.\n    + move=> a.\n      move: (abc a) => [b c].\n      exact c.\nQed.\n\nTheorem nat_doubling_ind : forall P : nat -> Prop,\n  P 0 -> (forall a : nat, P a -> (P (a * 2) /\\ P (1 + a * 2))) -> forall n, P n .\nProof.\n  move=> P P0 IH n.\n  move: (IH 0 P0) => [_ P1] /=.\n  simpl in P1.\n  elim/nat_strong_ind: n => [| n SIH] //.\n  case: (even_odd_dec n) => [m [E | E]];\n  rewrite E.\n  - case/name: (IH m) => m2m m2sm.\n    apply: m2sm.\n    apply: SIH.\n    lia.\n  - case/name: (IH (S m)) => m2m m2sm.\n    apply: m2m.\n    apply: SIH.\n    lia.\nQed.\n\nTheorem nat_doube_ind : forall R : nat -> nat -> Prop,\n  (forall n, R 0 n) -> (forall n, R (S n) 0) ->\n  (forall n m, R n m -> R (S n) (S m)) ->\n  forall n m, R n m.\nProof.\n  move=> R R0n Rn0 RS.\n  fix IH 1 => n m.\n  case: n => [| n0]; first exact: R0n.\n  case: m => [| m0]; first exact: Rn0.\n  apply: RS.\n  exact: IH.\nQed.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/strind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7215646839890598}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) : natural :=\n  mult lf2 (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj43_coqofml_eiXYhF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7215536380157339}}
{"text": " \nDefinition pred_partial: forall (n : nat), n <> 0 ->  nat.\nProof.\n refine (fun n:nat => match n return n <> 0 -> nat \n                      with 0 => fun h  => False_rec _ _\n                         | S p => fun h => p\n                      end).\n -  now destruct h.\nDefined.\n \nScheme\nle_ind_max := Induction for le Sort Prop.\n \nTheorem le_2_n_not_zero: forall (n : nat), 2 <= n ->  n <> 0.\nProof.\nintros n Hle; elim Hle; intros; discriminate.\nQed.\n \nTheorem le_2_n_pred:\n forall (n : nat) (h : 2 <= n),  pred_partial n (le_2_n_not_zero n h) <> 0.\nProof.\n intros n h; induction h  using le_ind_max.\n - discriminate.\n - cbn; inversion h; auto.\nQed.\n\n(** \n\nExtraction pred_partial.\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/ch14_fundations_of_inductive_types/SRC/use_le_ind_max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7215536273528547}}
{"text": "Require Import group.\nRequire Import Basics.\n\nOpen Scope program_scope.\n\nStructure action {M : Type} (G : group M) (X : Type) := {\n  phi :> M -> X -> X;\n  phi_low1 : forall x, phi (id G) x = x;\n  phi_low2 : forall g h x, phi g (phi h x) = phi (bin G g h) x;\n}.\n\nExample action_has_inverse {M : Type} (G : group M) (X : Type) (φ : action G X) : forall g, g \\in G -> exists φ',\n  (forall x, ((φ g) ∘ (φ' g)) x = x) /\\ (forall x, ((φ' g) ∘ (φ g)) x = x).\nProof.\n  intros.\n  exists (fun g => fun x => (φ (inverse G g)) x).\n  unfold compose.\n  split.\n  - (* left *)\n    intros.\n    rewrite phi_low2.\n    rewrite invR.\n    rewrite phi_low1.\n    reflexivity.\n  - (* right *)\n    intros.\n    rewrite phi_low2.\n    rewrite invL.\n    rewrite phi_low1.\n    reflexivity.\nQed.\n", "meta": {"author": "ryuta-ito", "repo": "algebra_1", "sha": "dc268e65e3338ef2c2be393b57acf3fa58453309", "save_path": "github-repos/coq/ryuta-ito-algebra_1", "path": "github-repos/coq/ryuta-ito-algebra_1/algebra_1-dc268e65e3338ef2c2be393b57acf3fa58453309/action.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7214953857169861}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** ** Single Diophantine equations *)\n\nRequire Import List Arith Omega Nat.\n\nRequire Import utils_tac utils_list sums pos vec. \nRequire Import dio_logic dio_elem.\n\nSet Implicit Arguments.\n\nLocal Notation \"∑\" := (msum plus 0).\n\nSection convexity.\n\n  Let convex_1 x p : 2*(x*(x+p)) <= x*x+(x+p)*(x+p).\n  Proof.\n    rewrite mult_assoc.\n    repeat rewrite Nat.mul_add_distr_r.\n    repeat rewrite Nat.mul_add_distr_l.\n    rewrite (mult_comm p x).\n    repeat rewrite <- mult_assoc.\n    generalize (x*x) (x*p) (p*p); intros; omega.\n  Qed.\n\n  Let convex_2 x p : 2*(x*(x+p)) = x*x+(x+p)*(x+p) -> p = 0.\n  Proof.\n    rewrite mult_assoc.\n    intros H.\n    cut (p*p = 0).\n    { destruct p; simpl; auto; discriminate. }\n    revert H.\n    repeat rewrite Nat.mul_add_distr_r.\n    repeat rewrite Nat.mul_add_distr_l.\n    rewrite (mult_comm p x).\n    repeat rewrite <- mult_assoc.\n    generalize (x*x) (x*p) (p*p); intros; omega.\n  Qed.\n\n  Fact convex_le x y : 2*(x*y) <= x*x+y*y.\n  Proof.\n    destruct (le_lt_dec x y).\n    + replace y with (x+(y-x)) by omega.\n      apply convex_1.\n    + rewrite (mult_comm x y), plus_comm.\n      replace x with (y+(x-y)) by omega.\n      apply convex_1.\n  Qed.\n\n  Fact convex_eq x y : 2*(x*y) = x*x+y*y -> x = y.\n  Proof.\n    destruct (le_lt_dec x y).\n    + replace y with (x+(y-x)) by omega.\n      intros H; apply convex_2 in H; omega.\n    + rewrite (mult_comm x y), plus_comm.\n      replace x with (y+(x-y)) by omega.\n      intros H; apply convex_2 in H; omega.\n  Qed.\n\n  Let convex_3 a t x y : 0 < t -> a*x+(a+t)*y = a*y+(a+t)*x -> x = y.\n  Proof.\n    intros H.\n    repeat rewrite Nat.mul_add_distr_r.\n    intros H1.\n    apply Nat.mul_cancel_l with t; omega.\n  Qed.\n   \n  Fact convex_neq a b x y : a < b -> a*x+b*y = a*y+b*x -> x = y.\n  Proof.\n    intros H.\n    replace b with (a+(b-a)) by omega.\n    apply convex_3; omega.\n  Qed.\n\n  Hint Resolve convex_le.\n\n  Fact convex_n_le n (f g : nat -> nat) :  ∑ n (fun i => 2*(f i*g i)) \n                                        <= ∑ n (fun i => f i*f i + g i*g i).\n  Proof.\n    revert f g; induction n as [ | n IHn ]; intros f g.\n    + rewrite msum_0; auto.\n    + do 2 rewrite msum_S.\n      apply plus_le_compat; auto.\n  Qed.\n\n  Hint Resolve convex_n_le.\n\n  Let nat_le_sum a b c d : a <= b -> c <= d -> a+c = b+d -> a = b /\\ c = d.\n  Proof. intros; omega. Qed.\n\n\n  (* This one can be used to encode a list of equations\n     x1 = y1 ... xn = yn into a single equation of size\n     linear in n if all the xi, yi have a bounded size \n\n     Hence one can transform a system elementary diophantine\n     equations into a single polynomial equation of linear\n     size !! *)\n\n  Fact convex_n_eq n (f g : nat -> nat) : ∑ n (fun i => 2*(f i*g i)) \n                                        = ∑ n (fun i => f i*f i + g i*g i)\n                                    <-> forall i, i < n -> f i = g i.\n  Proof.\n    split.\n    + revert f g; induction n as [ | n IHn ]; intros f g.\n      * intros; omega.\n      * do 2 rewrite msum_S; intros H.\n        apply nat_le_sum in H; auto.\n        destruct H as (H1 & H2).\n        apply convex_eq in H1.\n        specialize (IHn _ _ H2).\n        intros [ | ] ?; auto; apply IHn; omega.\n    + intros Hfg.\n      apply msum_ext.\n      intros i Hi; rewrite Hfg; auto; ring.\n  Qed.\n\nEnd convexity.\n\nSection diophantine_polynomial.\n\n  Variable (V P : Set).\n\n  Inductive dio_polynomial : Set :=\n    | dp_nat : nat -> dio_polynomial                  (* natural number constant *)\n    | dp_var : V   -> dio_polynomial                  (* existentially quantified variable *)\n    | dp_par : P   -> dio_polynomial                  (* parameter *)\n    | dp_comp : dio_op -> dio_polynomial -> dio_polynomial -> dio_polynomial.\n\n  Notation dp_add := (dp_comp do_add).\n  Notation dp_mul := (dp_comp do_mul).\n\n  Fixpoint dp_var_list p :=\n    match p with\n      | dp_nat _      => nil\n      | dp_var v      => v::nil\n      | dp_par _      => nil\n      | dp_comp _ p q => dp_var_list p ++ dp_var_list q\n    end.\n\n  Fixpoint dp_par_list p :=\n    match p with\n      | dp_nat _      => nil\n      | dp_var _      => nil\n      | dp_par x      => x::nil\n      | dp_comp _ p q => dp_par_list p ++ dp_par_list q\n    end.\n\n  (* ρ σ ν φ *)\n\n  Fixpoint dp_eval φ ν p := \n    match p with\n      | dp_nat n => n\n      | dp_var v => φ v\n      | dp_par i => ν i\n      | dp_comp do_add p q => dp_eval φ ν p + dp_eval φ ν q \n      | dp_comp do_mul p q => dp_eval φ ν p * dp_eval φ ν q \n    end.\n\n  Fact dp_eval_ext φ ν φ' ν' p :\n        (forall v, In v (dp_var_list p) -> φ v = φ' v) \n     -> (forall i, In i (dp_par_list p) -> ν i = ν' i) \n     -> dp_eval φ ν p = dp_eval φ' ν' p.\n  Proof.\n    induction p as [ | | | [] p Hp q Hq ]; simpl; intros H1 H2; f_equal; auto;\n      ((apply Hp || apply Hq); intros; [ apply H1 | apply H2 ]; apply in_or_app; auto).\n  Qed.\n\n  Fact dp_eval_fix_add φ ν p q : dp_eval φ ν (dp_add p q) = dp_eval φ ν p + dp_eval φ ν q.\n  Proof. trivial. Qed.\n\n  Fact dp_eval_fix_mul φ ν p q : dp_eval φ ν (dp_mul p q) = dp_eval φ ν p * dp_eval φ ν q.\n  Proof. trivial. Qed.\n\n  Fixpoint dp_size p :=\n    match p with\n      | dp_nat n => 1\n      | dp_var v => 1\n      | dp_par i => 1\n      | dp_comp _ p q => 1 + dp_size p + dp_size q \n    end.\n\n  Fact dp_size_fix_comp o p q : dp_size (dp_comp o p q) = 1 + dp_size p + dp_size q.\n  Proof. auto. Qed.\n\n  Definition dio_single := (dio_polynomial * dio_polynomial)%type.\n  Definition dio_single_size (e : dio_single) := dp_size (fst e) + dp_size (snd e).\n\n  Definition dio_single_pred e ν := exists φ, dp_eval φ ν (fst e) = dp_eval φ ν (snd e).\n\nEnd diophantine_polynomial.\n\nArguments dp_nat {V P}.\nArguments dp_var {V P}.\nArguments dp_par {V P}.\nArguments dp_comp {V P}.\n\nNotation dp_add := (dp_comp do_add).\nNotation dp_mul := (dp_comp do_mul).\n\nSection dio_elem_dio_poly.\n\n  Let dp_2xy u v : dio_polynomial nat nat := dp_mul (dp_nat 2) (dp_mul u v).\n  Let dp_x2y2 u v : dio_polynomial nat nat := dp_add (dp_mul u u) (dp_mul v v).\n\n  Let dp_2xy_size u v : dp_size (dp_2xy u v) = 3+dp_size u+dp_size v.\n  Proof. auto. Qed.\n\n  Let dp_x2y2_size u v : dp_size (dp_x2y2 u v) = 3+2*dp_size u+2*dp_size v.\n  Proof. simpl; omega. Qed.\n\n  Let dp_common e : dio_polynomial nat nat :=\n    match e with\n      | dee_nat c      => dp_nat c\n      | dee_var v      => dp_var v\n      | dee_par p      => dp_par p\n      | dee_comp o v w => dp_comp o (dp_var v) (dp_var w)\n    end.\n\n  Let dp_common_size e : dp_size (dp_common e) <= 3.\n  Proof. destruct e as [ | | | [] ]; simpl; auto. Qed.\n\n  Let dp_eval_common φ ν e : dp_eval φ ν (dp_common e) = dee_eval φ ν e.\n  Proof. destruct e as [ | | | [] ]; auto. Qed.  \n\n  Let dp_left (c : dio_constraint) := dp_2xy (dp_var (fst c)) (dp_common (snd c)).\n  Let dp_right (c : dio_constraint) := dp_x2y2 (dp_var (fst c)) (dp_common (snd c)).\n \n  Let dee2dp_1 l := fold_right dp_add (dp_nat 0) (map dp_left l).\n  Let dee2dp_2 l := fold_right dp_add (dp_nat 0) (map dp_right l).\n\n  Let dee2dp_1_size l : dp_size (dee2dp_1 l) <= 1+8*length l.\n  Proof.\n    induction l as [ | (x,e) l IHl ].\n    + simpl; auto.\n    + unfold dee2dp_1; simpl fold_right; fold (dee2dp_1 l).\n      rewrite dp_size_fix_comp.\n      unfold dp_left; rewrite dp_2xy_size.\n      unfold fst, snd.\n      generalize (dp_common_size e); intros.\n      simpl dp_size at 1; simpl length.\n      rewrite Nat.mul_succ_r; omega.\n  Qed.\n\n  Let dee2dp_2_size l : dp_size (dee2dp_2 l) <= 1+12*length l.\n  Proof.\n    induction l as [ | (x,e) l IHl ].\n    + simpl; auto.\n    + unfold dee2dp_2; simpl fold_right; fold (dee2dp_2 l).\n      rewrite dp_size_fix_comp.\n      unfold dp_right; rewrite dp_x2y2_size.\n      unfold fst, snd.\n      generalize (dp_common_size e); intros.\n      simpl dp_size at 1; simpl length.\n      rewrite Nat.mul_succ_r; omega.\n  Qed.\n\n  Let dc_value_1 φ ν (c : dio_constraint) := 2*(φ (fst c)*dee_eval φ ν (snd c)).\n  Let dc_value_2 φ ν (c : dio_constraint) := (φ (fst c)*φ (fst c)) + (dee_eval φ ν (snd c)*dee_eval φ ν (snd c)).\n\n  Let dee2dp_1_eval φ ν l : dp_eval φ ν (dee2dp_1 l) = fold_right plus 0 (map (dc_value_1 φ ν) l).\n  Proof.\n    induction l as [ | (u,e) l IHl ].\n    + simpl; auto.\n    + simpl fold_right; rewrite <- IHl.\n      unfold dee2dp_1; simpl fold_right.\n      rewrite dp_eval_fix_add; f_equal; auto.\n      unfold dc_value_1, dp_left, dp_2xy.\n      repeat rewrite dp_eval_fix_mul.\n      unfold fst, snd; do 2 f_equal.\n      apply dp_eval_common.\n  Qed.\n\n  Let dee2dp_2_eval φ ν l : dp_eval φ ν (dee2dp_2 l) = fold_right plus 0 (map (dc_value_2 φ ν) l).\n  Proof.\n    induction l as [ | (u,e) l IHl ].\n    + simpl; auto.\n    + simpl fold_right; rewrite <- IHl.\n      unfold dee2dp_2; simpl fold_right.\n      rewrite dp_eval_fix_add; f_equal; auto.\n      unfold dc_value_2, dp_right, dp_x2y2.\n      rewrite dp_eval_fix_add.\n      repeat rewrite dp_eval_fix_mul.\n      unfold fst, snd; do 2 f_equal;\n      apply dp_eval_common.\n  Qed.\n\n  Let dee2dp_spec φ ν l : dp_eval φ ν (dee2dp_1 l) = dp_eval φ ν (dee2dp_2 l)\n                      <-> Forall (dc_eval φ ν) l.\n  Proof.\n    rewrite dee2dp_1_eval, dee2dp_2_eval.\n    destruct (list_fun_inv l (0,dee_nat 0)) as (f & Hf).\n    rewrite Hf at 1 2.\n    do 2 rewrite map_map.\n    do 2 rewrite <- sum_fold_map.\n    unfold dc_value_1, dc_value_2.\n    rewrite convex_n_eq.\n    unfold dc_eval.\n    apply Forall_forall_map with (P := fun i =>  φ (fst i) = dee_eval φ ν (snd i)); auto.\n  Qed.\n\n  Theorem dio_elem_single l : { E : dio_single nat nat | dio_single_size E <= 2+20*length l\n              /\\ forall ν φ, dp_eval φ ν (fst E) = dp_eval φ ν (snd E) <-> Forall (dc_eval φ ν) l }.\n  Proof.\n    exists (dee2dp_1 l,dee2dp_2 l); split.\n    + unfold dio_single_size, fst, snd.\n      generalize (dee2dp_1_size l) (dee2dp_2_size l); intros; omega.\n    + unfold dio_single_pred, fst, snd; split; apply dee2dp_spec.\n  Defined.\n\n  Theorem dio_elem_equation l : { E : dio_single nat nat | dio_single_size E <= 2+20*length l\n                                            /\\ forall ν, dio_single_pred E ν <-> exists φ, Forall (dc_eval φ ν) l }.\n  Proof.\n    destruct (dio_elem_single l) as (p & H1 & H2); exists p; split; auto.\n    split; intros (phi & H); exists phi; revert H; apply H2.\n  Defined.\n\nEnd dio_elem_dio_poly.\n\nCorollary dio_rel_single R : \n      𝔻R R -> { E : dio_single nat nat | forall ν, R ν <-> dio_single_pred E ν}.\nProof.\n  intros (A & HA).\n  destruct dio_formula_elem with (f := A) as (l & _ & _ & Hl).\n  destruct dio_elem_equation with (l := l) as (E & _ & HE).\n  exists E; intro; rewrite HE, <- Hl, HA; tauto.\nQed.\n\nSection dio_poly_pos.\n\n  Variable P : Set.\n\n  Implicit Type (p : dio_polynomial nat P).\n\n  Definition dio_poly_pos m p : (forall x, In x (dp_var_list p) -> x < m) -> { q | forall φ ν, dp_eval φ ν p = dp_eval (vec_pos (fun2vec 0 m φ)) ν q }.\n  Proof.\n    induction p as [ n | v | i | o p Hp q Hq ]; intros H.\n    + exists (dp_nat n); auto.\n    + specialize (H v); spec in H; simpl; auto.\n      exists (dp_var (nat2pos H)); intros phi psi; simpl.\n      rewrite vec_pos_fun2vec, pos2nat_nat2pos; auto.\n    + exists (dp_par i); auto.\n    + simpl in H.\n      destruct Hp as (p1 & H1). { intros; apply H, in_or_app; auto. }\n      destruct Hq as (q1 & H2). { intros; apply H, in_or_app; auto. }\n      exists (dp_comp o p1 q1); intros phi psi; simpl.\n      destruct o; f_equal; auto.\n  Qed.\n\n  Theorem dio_poly_eq_pos (e : dio_single nat P) : { m : nat \n                                                 & { p' : dio_polynomial (pos m) P \n                                                 & { q' | forall ν, dio_single_pred e ν <-> dio_single_pred (p',q') ν } } }.\n  Proof.\n    destruct e as (p,q).\n    destruct (list_upper_bound (dp_var_list p++dp_var_list q)) as (m & Hm).\n    destruct (@dio_poly_pos m p) as (p1 & H1). { intros; apply Hm, in_or_app; auto. }\n    destruct (@dio_poly_pos m q) as (q1 & H2). { intros; apply Hm, in_or_app; auto. }\n    exists m, p1, q1; intros psi; unfold dio_single_pred.\n    split; intros (phi & Hphi).\n    + exists (vec_pos (fun2vec 0 m phi)); simpl.\n      rewrite <- H1, <- H2; auto.\n    + exists (vec2fun (vec_set_pos phi) 0).\n      rewrite H1, H2.\n      rewrite fun2vec_vec2fun.\n      eq goal Hphi; f_equal; \n      apply dp_eval_ext; auto; intros j _; rewrite vec_pos_set; auto. \n  Qed.\n\n  Fact dio_poly_eq_pos_equiv n (p q : dio_polynomial (pos n) P) ν : dio_single_pred (p,q) ν <-> exists w, dp_eval (vec_pos w) ν p = dp_eval (vec_pos w) ν q.\n  Proof.\n    split. \n    + intros (w & Hw); exists (vec_set_pos w); eq goal Hw; f_equal; simpl; apply dp_eval_ext; auto;\n        intros; rewrite vec_pos_set; auto.\n    + intros (w & Hw); exists (vec_pos w); auto.\n  Qed.\n\nEnd dio_poly_pos.\n\nCheck dio_poly_eq_pos.\n\nSection dio_poly_inst_par.\n\n  Variable (V P : Set) (σ : P -> nat).\n\n  Fixpoint dp_inst_par (p : dio_polynomial V P) : dio_polynomial V Empty_set :=\n    match p with\n      | dp_nat c       => dp_nat c\n      | dp_var v       => dp_var v\n      | dp_par p       => dp_nat (σ p)\n      | dp_comp o p q  => dp_comp o (dp_inst_par p) (dp_inst_par q)\n    end.\n\n  Fact dp_inst_par_eval φ ν p : \n    dp_eval φ ν (dp_inst_par p) = dp_eval φ σ p.\n  Proof. induction p as [ | | | [] ]; simpl; f_equal; auto. Qed.\n\nEnd dio_poly_inst_par.\n\nSection dio_poly_ren_par.\n\n  Variable (V P Q : Set) (f : P -> Q).\n\n  Fixpoint dp_ren_par p : dio_polynomial V Q :=\n    match p with\n      | dp_nat c       => dp_nat c\n      | dp_var v       => dp_var v\n      | dp_par p       => dp_par (f p)\n      | dp_comp o p q  => dp_comp o (dp_ren_par p) (dp_ren_par q)\n    end.\n\n  Fact dp_ren_par_eval φ ν p : \n    dp_eval φ ν (dp_ren_par p) = dp_eval φ (fun i => ν (f i)) p.\n  Proof. induction p as [ | | | [] ]; simpl; f_equal; auto. Qed.\n\nEnd dio_poly_ren_par.\n\nSection dio_poly_proj_par.\n\n  Variable (V : Set) (n : nat).\n\n  Fixpoint dp_proj_par p : dio_polynomial V (pos n) :=\n    match p with\n      | dp_nat c       => dp_nat c\n      | dp_var v       => dp_var v\n      | dp_par p       => match le_lt_dec n p with left _ => dp_nat 0 | right H => dp_par (nat2pos H) end\n      | dp_comp o p q  => dp_comp o (dp_proj_par p) (dp_proj_par q)\n    end.\n\n  Fact dp_proj_par_eval φ ν p : \n    dp_eval φ ν (dp_proj_par p) = dp_eval φ (fun i => match le_lt_dec n i with left _ => 0 | right H => ν (nat2pos H) end) p.\n  Proof. \n    induction p as [ | | p | [] ]; simpl; f_equal; auto.\n    destruct (le_lt_dec n p); auto.\n  Qed.\n      \nEnd dio_poly_proj_par.\n\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/H10/Dio/dio_single.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538936, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7214881276663689}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\n(* This file contains the definition of the base 2 logarithm function (rounded down) over natural numbers. *)\n\n(* Some of the definitions and theory in this file were added to Coq 8.4, so we should refactor this at some point. *)\n\nSet Implicit Arguments.\n\nRequire Import ZArith.\n\n(* log2 is like log_inf except it returns nat, so I don't have to reason about an unnecessary conversion. This function is only used to implement lognat below.*)\nFixpoint log2(n : positive) : nat :=\n  match n with \n    | xH => 0\n    | xO n' | xI n' => (S (log2 n'))\n  end.\n\nLemma log2_prod_sum : forall(a : positive),\n  (S (log2 a)) = (log2 (Pmult 2 a)).\n  \n  intros. auto.\nQed.\n\n\nLemma le_s : forall a b,\n  (a <= b) -> S a <= S b.\n\n  intros. omega.\nQed.\n\n\n\nLemma log2_monotonic_b : forall(a : positive),\n  (log2 a) <= (log2 (Psucc a)).\n\n  induction a; \n  simpl in *; try apply le_s; auto.\nQed.\n\nLemma log2_ge_monotonic : forall(a : positive),\n  (log2 (Psucc a)) >= (log2 a).\n\n  induction a; \n  simpl in *; try apply le_s; auto.\nQed.\n\n\nDefinition nat_to_pos (n : nat) : (n <> 0) -> positive :=\n  fun _ => (P_of_succ_nat (pred n)).\n\nLemma double_nat_nz : forall(a : nat)(pf : a <> 0),\n  ((2 * a) <> 0).\n  intros. omega.\nQed.\nLemma s_nat_nz : forall(a : nat)(pf : a <> 0),\n  ((S a) <> 0).\n  intros. omega.\nQed.\n\nLemma factor_s_conv : forall(a : nat)(pf1 : (a <> 0))(pf2 : (S a) <> 0),\n  (nat_to_pos (pf2)) = (Psucc (nat_to_pos pf1)).\n  \n  intros. \n  destruct a.\n  congruence.\n\n  unfold nat_to_pos in *.\n  simpl in *.\n  intros. auto.\nQed.\n\nLemma add_s_r : forall a b,\n  a + (S b) = S (a + b).\n  intros. omega.\nQed.\n\nLemma factor_double_s : forall a,\n  (2 * (S a)) = (S (S (2 * a))).\n\n  intros. omega.\nQed.\n\nLemma factor_double_conv : forall(a : nat)(pf1 : (a <> 0))(pf2 : (2 * a) <> 0),\n  (nat_to_pos pf2) = (Pmult 2 (nat_to_pos pf1)).\n\n  induction a; intros; simpl in *.\n  congruence.\n\n  destruct (eq_nat_dec a 0).\n  subst. \n  unfold nat_to_pos.\n  auto.\n\n  assert (a + S (a + 0) <> 0) by omega.\n  specialize (factor_s_conv H). intros. \n  unfold nat_to_pos in *.\n\n  rewrite (H0 pf2). clear H0.  clear pf2.\n  assert (a + S (a + 0) = S (a + (a + 0))) by omega.\n  rewrite H0.  \n  assert (a + (a + 0) <> 0) by omega.\n  specialize (factor_s_conv H1). intros. \n  \n  unfold nat_to_pos in H2.\n  rewrite <- H0 in H2.\n  rewrite <- H0.\n  rewrite (H2 H). clear H. clear H2.\n  \n  rewrite (IHa n). clear IHa.\n  simpl.\n  destruct a. intros. destruct n. auto.\n\n  auto.\n  omega. \nQed.\n\nDefinition lognat(n : nat) : (n <> 0) -> nat := \n  fun pf => (log2 (nat_to_pos pf)).\n\n\nTheorem lognat_prod_sum : forall(a : nat)(pf1 : (a <> 0))(pf2: (2 * a) <> 0),\n  (S (lognat pf1)) = (lognat pf2).\n  \n  intros. \n  unfold lognat in *.\n  rewrite (factor_double_conv pf1 pf2).\n  eapply log2_prod_sum.\nQed.  \n\nTheorem lognat_monotonic_b : forall(a : nat)(pf1 : (a <> 0))(pf2: (S a) <> 0),\n  (lognat pf1) <= (lognat pf2).\n  \n  induction a.\n  intros. \n  destruct pf1. auto.\n\n  intros. \n  unfold lognat in *.\n  rewrite (factor_s_conv pf1).\n  apply log2_monotonic_b.\nQed.\n\n(* for good measure, we will define exponentiation for nat and prove that lognat is correct *)\nFixpoint expnat(a e : nat) : nat :=\n  match e with\n    | 0 => 1\n    | (S e') => a * (expnat a e')\n  end.\n\nLemma mult_ne : forall a b,\n  a <> 0 -> b <> 0 -> a * b <> 0.\n\n  intros. \n  destruct a. omega. \n  destruct b. omega. \n  simpl. \n  remember (b + a * (S b)) as c.\n  omega. \nQed.\n  \n\nTheorem expnat_nz : forall a e,\n  (a <> 0) -> (expnat a e) <> 0.\n\n  induction e.\n  simpl. auto.\n\n  simpl. \n  intros. \n  eapply mult_ne; eauto.\nQed.\n\nLemma nz_2 : 2 <> 0.\n  omega.\nQed.\n\nTheorem expnat_2_nz: forall e,\n  (expnat 2 e) <> 0.\n  \n  intros. \n  apply (expnat_nz e nz_2).\nQed.\n\nTheorem expnat_2_monotonic : forall e1 e2,\n  e1 <= e2 ->\n  (expnat 2 e1 <= expnat 2 e2).\n  \n  induction e1.\n  intros.\n  simpl.\n  specialize (expnat_2_nz e2). intros.\n  omega.\n\n  induction e2;\n  intros.\n  omega.\n\n  simpl. \n  specialize (IHe1 e2).\n  omega.\nQed.\n\nTheorem lognat_correct_eq : forall(b : nat)(pf : (expnat 2 b) <> 0),\n  (lognat pf) = b.\n\n  induction b.\n  intros. simpl in *. auto.\n  \n  intros. \n  specialize (lognat_prod_sum (expnat_2_nz b)). intros. \n  specialize (IHb (expnat_2_nz b)). \n  rewrite IHb in H.\n  symmetry in H.\n  simpl in *.\n  apply H.\nQed.\n\n\nLemma fold_add : forall a,\n  a + (a + 0) = 2*a.\n  intros. omega.\nQed.\n\nTheorem lognat_ge_monotonic_b : forall(a : nat)(pf1 : (a <> 0))(pf2: (S a) <> 0),\n  (lognat pf2) >= (lognat pf1).\n  \n  induction a.\n  intros. \n  destruct pf1. auto.\n\n  intros. \n  unfold lognat in *.\n  rewrite (factor_s_conv pf1).\n  apply log2_monotonic_b.\nQed.\n\nLemma ge_trans : forall a b c,\n  a >= b -> b >= c -> a >= c.\n  intuition.\nQed.\n\nLemma lognat_ge_monotonic_h : forall (c a b : nat)(pfa : a <> 0)(pfb : b <> 0), \n    a >= b -> c = (a - b) -> (lognat pfa) >= (lognat pfb).\n\n  induction c.\n  intros. \n  assert (a = b) by intuition.\n  subst. auto.\n\n  intros. \n  assert (a >= (S b)) by omega. \n  assert (c = a - (S b)) by omega.\n  eapply ge_trans.\n  apply (IHc a (S b) pfa (s_nat_nz pfb)).\n  apply H1.\n  apply H2.\n  apply lognat_ge_monotonic_b.\nQed.\n\nLemma lognat_ge_monotonic : forall (a b : nat)(pfa : a <> 0)(pfb : b <> 0), \n    a >= b -> (lognat pfa) >= (lognat pfb).\n\n  intros.\n  remember (a - b) as c.\n  apply (@lognat_ge_monotonic_h c); auto.\nQed.\n\nLemma lognat_monotonic : forall (a b : nat)(pfa : a <> 0)(pfb : b <> 0), \n    a <= b -> (lognat pfa) <= (lognat pfb).\n\n  intros.\n  remember (b - a) as c.\n  apply (@lognat_ge_monotonic_h c); auto.\nQed.\n\nTheorem mt : forall P Q: Prop, (P -> Q) -> (~Q -> ~P).\n  unfold not in *.\n  intros. \n  apply H0.\n  apply H.\n  apply H1.\nQed.\n\nLemma ge_not : forall a b,\n  ~(a >= b) -> a < b.\n  intuition.\nQed.\n\nLemma lognat_ge_monotonic_mt : forall (a b : nat)(pfa : a <> 0)(pfb : b <> 0), \n    (lognat pfa) < (lognat pfb) -> a < b.\n\n  intros. \n  specialize (lognat_ge_monotonic pfa pfb).\n  intros. \n  specialize (mt H0).\n  intros. \n  apply ge_not. omega.\nQed.\n\nLemma lognat_correct2 : forall(a : nat)(pf : a <> 0),\n  a < (expnat 2 (S (lognat pf))).\n  \n  intros. \n\n  simpl.\n  rewrite fold_add.\n  assert (expnat 2 (lognat pf) <> 0). apply expnat_nz. auto.\n  assert (2 * (expnat 2 (lognat pf)) <> 0). omega. \n  eapply (lognat_ge_monotonic_mt pf H0). \n  rewrite <- (lognat_prod_sum H).\n  rewrite lognat_correct_eq.\n  omega.\nQed.\n\nLemma lognat_odd : forall(a : nat)(pf1 : (2 * a) <> 0)(pf2 : (S (2 * a)) <> 0),\n  ((lognat pf2) = (lognat pf1)).\n\n  intros. \n  unfold lognat in *.\n  rewrite (factor_s_conv pf1 pf2).\n  assert (a <> 0). omega.\n  rewrite (factor_double_conv H pf1).\n  simpl. \n  auto.\nQed.\n\nLemma double_s : forall a, (S (S (2 * a))) = 2 * (S a).\n  intros. omega.\nQed.\n\n\nLemma lognat_double_eq : forall a b (pf1: 2 * a <> 0)(pf2: 2 * b <> 0)(pf3 : a <> 0) (pf4: b <> 0),\n  lognat pf3 = lognat pf4 -> \n  lognat pf1 = lognat pf2.\n\n  intros. \n  rewrite <- (lognat_prod_sum pf3).\n  rewrite <- (lognat_prod_sum pf4).\n  omega.\nQed.\n\nLemma nat_comp : forall(a : nat),\n  exists x : nat,\n  (a = (2 * x) \\/ a = (S (2 * x))).\n\n  induction a.\n  exists 0. simpl.  auto.\n\n  elim IHa. clear IHa.\n  intros. \n  destruct H.\n  subst. simpl.\n  exists x.\n  right. auto.\n\n  subst. simpl. \n  exists (S x).\n  left.\n  simpl. \n  omega. \nQed.\n\nLemma lognat_correct1 : forall(b a : nat)(pf : a <> 0),\n  (lognat pf) = b -> \n  (expnat 2 b) <= a.\n\n  induction b.\n\n  intros. simpl in *. omega.\n\n  intros. \n  elim (nat_comp a). intros. \n  destruct H0.\n  subst. \n  destruct (eq_nat_dec x 0).\n  subst. omega. \n  rewrite <- (lognat_prod_sum n pf) in H.\n  inversion H. clear H.\n  rewrite H1.\n  apply IHb in H1.\n  simpl in *. omega. \n\n  subst. \n  destruct (eq_nat_dec x 0).\n  subst. unfold lognat in H. simpl in *. omega. \n  assert ((2 * x) <> 0). omega.\n  rewrite (lognat_odd x H0 pf) in H.\n  \n  rewrite <- (lognat_prod_sum n H0) in H.\n  inversion H.\n  rewrite H2.\n  apply IHb in H2.\n  simpl. \n  omega.\nQed.  \n  \n  \nTheorem lognat_correct : forall(a : nat)(pf : a <> 0),\n  (expnat 2 (lognat pf)) <= a < (expnat 2 (S (lognat pf))).\n\n  intros.\n  split.\n  remember (lognat pf) as b.\n  apply (lognat_correct1 pf). auto.\n  apply lognat_correct2.\nQed.\n\nLemma lognat_prod_sum_gen_h : forall (a' a b: nat)(pf1 : (a <> 0))(pf2 : (b <> 0))(pf3 : a * b <> 0), \n  lognat pf1 = a' ->\n  a' + lognat pf2 <= lognat pf3.\n \n  induction a'; intros. \n  simpl. \n  eapply lognat_monotonic. \n  induction a.\n  congruence.\n  simpl. \n  intuition.\n\n  destruct (nat_comp a).\n  destruct H0.\n  subst.\n  assert (x <> 0). omega.\n  assert (x * b <> 0). destruct x; destruct b; simpl; congruence.\n  rewrite <- (lognat_prod_sum H0) in H.\n  assert (lognat pf3 = S (lognat H1)). \n  generalize pf3.\n  rewrite mult_assoc_reverse.\n  intros. \n  rewrite (lognat_prod_sum _ pf0).\n  trivial.\n\n  rewrite H2.\n  inversion H.\n  specialize (IHa' x b H0 pf2 H1 H4).\n  subst.\n  omega. \n\n  destruct (eq_nat_dec x 0).\n  subst.\n  unfold lognat in *.\n  simpl in *.\n  discriminate.\n\n  assert (2 * x <> 0). omega. \n  assert (x * b <> 0). destruct x; destruct b; simpl; congruence.\n  assert (2 * x * b <> 0). rewrite mult_assoc_reverse. omega.\n  subst.\n  rewrite (lognat_odd _ H1) in H.\n  rewrite <- (lognat_prod_sum n) in H.\n  inversion H.\n  subst. \n  assert (lognat n = lognat n). trivial.\n  specialize (IHa' x b n pf2 H2 H0).\n\n  generalize pf3.\n  assert (S (2 * x) * b = b + 2 * x * b). intuition.\n  rewrite H4.\n  intros. \n  eapply le_trans.\n  Focus 2.\n  eapply (lognat_monotonic H3). intuition.\n  generalize H3.\n  rewrite mult_assoc_reverse.\n  intros. \n  rewrite <- (lognat_prod_sum H2).\n  omega.\nQed.\n\nTheorem lognat_prod_sum_gen : forall (a b: nat)(pf1 : (a <> 0))(pf2 : (b <> 0))(pf3 : a * b <> 0), \n  lognat pf1 + lognat pf2 <= lognat pf3.\n\n  intros.\n  eapply lognat_prod_sum_gen_h.\n  eauto.\nQed.\n\nLemma lognat_0_1 : forall n (pf : n <> 0),\n  lognat pf = 0 -> n = 1.\n\n  intros. \n  destruct n.\n  omega.\n  \n  destruct n.\n  trivial.\n\n  assert (2 <> 0). omega.\n  assert (lognat pf >= lognat H0).\n  eapply lognat_ge_monotonic.\n  omega. \n\n  unfold lognat in *.\n  simpl in *.\n  omega.\nQed.\n\nLemma lognat_succ_h : forall a n (pf1 : n <> 0)(pf2: (S n) <> 0),\n  a = lognat pf1 -> \n    lognat pf2 = a \\/\n    lognat pf2 = S (a).\n\n  induction a; intros. \n  assert (n = 1). \n  apply (lognat_0_1 pf1).\n  auto.\n  subst. \n  unfold lognat.\n  simpl. \n  auto.\n\n  destruct (nat_comp n).\n  destruct H0.\n  subst. \n  assert (x <> 0). omega.\n  rewrite <- (lognat_prod_sum H0) in H.\n  inversion H.\n  subst. \n  rewrite (lognat_odd _ pf1).\n  rewrite <- (lognat_prod_sum H0).\n  auto.\n\n  subst.\n  destruct (eq_nat_dec x 0).\n  subst. \n  unfold lognat in *.\n  simpl in *.\n  omega. \n\n  generalize pf2.\n  assert (S (S (2 * x)) = 2 * (S x)). omega.\n  rewrite H0.\n  intros. \n  assert (S x <> 0). omega. \n  assert (2 * x <> 0). omega.\n  rewrite (lognat_odd _ H2) in H.\n  rewrite <- (lognat_prod_sum n) in H.\n  inversion H.\n  rewrite <- (lognat_prod_sum H1).\n  specialize (IHa x n H1 H4). \n  destruct IHa.\n  subst. \n  rewrite H4.\n  auto.\n  subst. \n  right.\n  rewrite H3.\n  auto.\n\nQed.\n\nLemma lognat_succ : forall n (pf1 : n <> 0)(pf2: (S n) <> 0),\n  lognat pf2 = lognat pf1 \\/\n  lognat pf2 = S (lognat pf1).\n\n  intros.\n  eapply lognat_succ_h.\n  eauto.\nQed.\n\nLemma logn_ge_1 : forall n (pf : n <> 0),\n  n > 1 -> lognat pf >= 1.\n\n  intros. \n  destruct n.\n  congruence.\n  \n  destruct n.\n  omega.\n\n  assert (2 <> 0).\n  omega.\n\n  assert (forall n (pf1 : S (S n) <> 0)(pf2 : 2 <> 0), lognat pf1 >= lognat pf2).\n  intros.\n  eapply lognat_ge_monotonic.\n  omega.\n\n  assert (forall (pf : 2 <> 0), 1 = lognat pf).\n  intros. \n  unfold lognat. \n  auto.\n\n  rewrite (H2 H0).\n  eauto.\n\nQed.", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/fcf/Lognat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8175744761936438, "lm_q1q2_score": 0.7214505082789252}}
{"text": "Section ExistsUnique.\n\n  Variables (A : Type) (P : A -> Prop).\n  \n  (*                \nExample 3.6.1\n\n1. ∃x(P(x) ∧ ∀y(P(y) → y = x))                (= ∃!x P(x))\n2. ∃x∀y(P(y) ↔ y = x).\n3. ∃x P(x) ∧ ∀y∀z((P(y) ∧ P(z)) → y = z).\n   *)\n  \n  (* 1 -> 2 *)\n  Goal (exists ! x, P x) -> (exists x, forall y, P y <-> x = y).\n  Proof.\n    unfold unique.\n    intros.\n    destruct H as [x0].\n    destruct H as [H1 H2].\n    (* Givens and Goal p.147 *)\n    exists x0.\n    intros.\n    split.\n    - now apply H2.\n    - intros Hx0y.\n      now rewrite <- Hx0y.\n  Qed.\n  \n  (* 2 -> 3 *)\n  Goal (exists x, forall y, P y <-> x = y) ->\n  (exists x, P x /\\ (forall y z, P y /\\ P z -> y = z)).\n  Proof.\n    intros.\n    destruct H as [x0].\n    exists x0.\n    split.\n    - destruct (H x0).\n      now apply H1.\n    - intros y z [H1 H2].\n      (* Givens and Goal p.148 *)\n      destruct (H y) as [H3 H4].\n      destruct (H z) as [H5 H6].\n      now rewrite <- H3, <- H5.\n  Qed.\n  \n  (* 3 -> 1 *)\n  Goal (exists x, P x /\\ (forall y z, P y /\\ P z -> y = z)) ->\n  (exists ! x, P x).\n  Proof.\n    unfold unique.\n    intros H.\n    destruct H as [x0].\n    destruct H as [H1 H2].\n    exists x0.\n    (* Givens and Goal p.148 *)\n    split.\n    - easy.\n    - intros y H3.\n      now apply (H2 x0 y).\n  Qed.\n  \nEnd ExistsUnique.\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/htpl/htpi_existence_uniqueness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7213494638591919}}
{"text": "Require Import ZArith.\n\nDefinition INC : Z := 2.\n\nModule hddivsteps.\n\nRecord State : Set :=\n { delta : Z\n ; f : Z\n ; g : Z\n ; d : Z\n ; e : Z\n ; modulus : Z\n }.\n\nDefinition init f g := \n{| delta := 1\n ; f := f\n ; g := g\n ; d := 0\n ; e := 1\n ; modulus := f\n |}.\n\nSection Step.\n\nLet div2M (M x : Z) : Z :=\n (if Z.odd x then x + M else x) / 2.\n\nDefinition step (st : State) : State :=\nif Z.even (g st)\n  then {| delta := INC + delta st\n        ; f := f st\n        ; g := g st / 2\n        ; d := d st\n        ; e := div2M (modulus st) (e st)\n        ; modulus := modulus st\n        |}\n  else if (0 <? delta st)%Z\n         then {| delta := INC - delta st\n               ; f := g st\n               ; g := (g st - f st) / 2\n               ; d := e st\n               ; e := div2M (modulus st) (e st - d st)\n               ; modulus := modulus st\n               |}\n         else {| delta := INC + delta st\n               ; f := f st\n               ; g := (g st + f st) / 2\n               ; d := d st\n               ; e := div2M (modulus st) (e st + d st)\n               ; modulus := modulus st\n               |}.\n\nLemma modulus_step : forall st, modulus (step st) = modulus st.\nProof.\nintros [delta f g d e modulus].\nunfold step.\ncbn -[Z.ltb Z.add Z.sub] in *.\ncase (Z.even g) eqn:Hg;[|case (0 <? delta)%Z];auto.\nQed.\n\nLemma odd_step : forall st, Z.Odd (f st) ->\n   Z.Odd (f (step st)).\nProof.\nintros [delta f g] Hf.\nunfold step.\ncbn -[Z.ltb Z.add Z.sub] in *.\ncase (Z.even g) eqn:Hg;[|case (0 <? delta)%Z];auto.\nsimpl.\nrewrite <- Z.odd_spec, Zodd_even_bool, Hg.\nreflexivity.\nQed.\n\nLemma zero_step : forall st, g st = 0%Z ->\n   g (step st) = 0%Z.\nProof.\nintros [delta f g]; simpl.\nintros ->.\nreflexivity.\nQed.\n\nLemma d_zero_spec : forall (n:nat) st,\n  g st = 0%Z ->\n  d (Nat.iter n step st) = d st.\nProof.\nintros n [delta f g d e M]; simpl.\nset (st := Build_State _ _ _ _ _ _).\nintros ->.\ncut (hddivsteps.g (Nat.iter n step st) = 0%Z /\\ hddivsteps.d (Nat.iter n step st) = d).\n tauto.\ninduction n; auto.\nsimpl.\ndestruct IHn as [IHn1 IHn2].\nsplit;auto using zero_step.\nunfold step at 1.\nrewrite IHn1.\nassumption.\nQed.\n\nDefinition gcd (st : State) : Z := \n  Z.gcd (f st) (g st).\n\nLemma gcd_step : forall st, Z.Odd (f st) ->\n  gcd (step st) = gcd st.\nProof.\nassert (Hgcd : forall f g, Z.Odd f -> Z.Even g -> Z.gcd f (g / 2) = Z.gcd f g).\n  intros f g Hf Hg.\n  rewrite <- Zdiv2_div.\n  replace g with (2 * Z.div2 g)%Z at 2 by\n   (symmetry;\n    apply Zeven_div2;\n    rewrite Zeven_equiv;\n    assumption).\n  generalize (Z.div2 g); intros g'.\n  symmetry.\n  apply Znumtheory.Zis_gcd_gcd;[apply Z.gcd_nonneg|].\n  constructor;[apply Z.gcd_divide_l|apply Z.divide_mul_r; apply Z.gcd_divide_r|].\n  intros x Hxf Hxg'.\n  apply Z.gcd_greatest; auto.\n  apply Znumtheory.Gauss with 2%Z; auto.\n  apply Znumtheory.rel_prime_sym.\n  apply Znumtheory.prime_rel_prime;[apply Znumtheory.prime_2|].\n  intros H2x.\n  apply Z.Even_Odd_False with f; auto.\n  rewrite <-Zeven_equiv, Zeven_ex_iff.\n  exists (f / 2)%Z.\n  apply Znumtheory.Zdivide_Zdiv_eq; auto with *.\n  apply Z.divide_transitive with x; auto.\nintros [delta f g] Hf.\nunfold step, gcd.\ncbn -[Z.ltb Z.add Z.sub] in *.\ncase (Z.even g) eqn:Hg;[|case (0 <? delta)%Z];cbn -[Z.add Z.sub].\n* rewrite Z.even_spec in Hg.\n  apply Hgcd; auto.\n* rewrite (Z.gcd_comm f g), <- (Z.gcd_sub_diag_r g f).\n  replace (f - g)%Z with (-(g - f))%Z by ring.\n  rewrite Z.gcd_opp_r.\n  apply Hgcd;\n  [ rewrite <- Z.odd_spec, <- Z.negb_even, Hg; reflexivity\n  | rewrite <- Z.odd_spec in Hf;\n    rewrite <- Z.even_spec, Z.even_sub, Hg, Zeven.Zeven_odd_bool, Hf\n  ]; reflexivity.\n* rewrite <- (Z.gcd_add_diag_r f g).\n  apply Hgcd; auto.\n  rewrite <- Z.odd_spec in Hf.\n  rewrite <- Z.even_spec, Z.even_add, Hg, Zeven.Zeven_odd_bool, Hf.\n  reflexivity.\nQed.\n\nLemma gcd_spec : forall (n:nat) st,\n  Z.Odd (f st) ->\n  g (Nat.iter n step st) = 0%Z ->\n  Znumtheory.Zis_gcd (f st) (g st) (f (Nat.iter n step st)).\nProof.\nintros n [delta f g] Hf Hg; simpl in *.\nset (d := hddivsteps.f _).\ncut (Znumtheory.Zis_gcd f g (Z.abs d) /\\ Z.Odd d).\n  destruct (Z.abs_eq_or_opp d) as [-> | ->];intros [H _];[auto|].\n  replace d with (- - d)%Z by ring.\n  auto using Znumtheory.Zis_gcd_sym, Znumtheory.Zis_gcd_opp.\nrewrite <- Z.gcd_0_r, <- Hg.\nclear Hg.\ninduction n;[auto using Znumtheory.Zgcd_is_gcd|].\ndestruct IHn as [IHn1 IHn2].\nsplit;[|apply odd_step; auto].\nunfold d; simpl.\nset (st' := (Nat.iter n _ _ )) in *.\nfold (gcd (step st')).\nrewrite (gcd_step st'); auto.\nQed.\n\nLet modulo_invariant (x : Z) (st : State) :=\n eqm (modulus st) (f st) (d st * x) /\\ \n eqm (modulus st) (g st) (e st * x).\n\nDefinition inv2M (M : Z) : Z := \n let 'Znumtheory.Euclid_intro _ _ u _ d _ _ := Znumtheory.euclid 2 M in (d*u).\n\nLemma mul_inv2M : forall M, Z.Odd M -> eqm M (inv2M M * 2) 1.\nProof.\nintros M HM.\nunfold inv2M.\ndestruct (Znumtheory.euclid 2 M) as [u v d Hd Hgcd].\nassert (H : Znumtheory.rel_prime 2 M).\n apply Znumtheory.prime_rel_prime.\n  apply Znumtheory.prime_2.\n intros Heven.\n apply (Zeven_not_Zodd M).\n rewrite Znumtheory.Zdivide_Zdiv_eq with 2%Z M; auto with *.\n  apply Zeven_2p.\n apply Zodd_equiv; auto.\ndestruct (Znumtheory.Zis_gcd_uniqueness_apart_sign _ _ _ _ Hgcd H) as [Heq|Heq];\n rewrite Heq in *;\n[|apply (f_equal Z.opp) in Hd;rewrite Z.opp_involutive in Hd;\n  replace (- (u * 2 + v * M))%Z with (- u*2 + (-v) * M)%Z in Hd by ring];\n rewrite <- Hd at 2;\n unfold eqm;\n rewrite <- Zplus_mod_idemp_r, <- (Zmult_mod_idemp_r M), Z_mod_same_full,\n         Z.mul_0_r, Z.add_0_r;\n f_equal.\nring.\nQed.\n\nLemma mul_inv2M_even : forall M x, Z.Odd M -> Z.Even x ->\n eqm M (x / 2) (inv2M M * x).\nProof.\nintros M x HM Hx.\nrewrite <- Z.div2_div.\nrewrite (Zeven_div2 x) at 2; [|apply Zeven_equiv;auto].\nrewrite Zmult_assoc.\nreplace (Z.div2 x) with (1*Z.div2 x)%Z at 1 by ring.\napply Zmult_eqm;try reflexivity.\nauto using eqm_sym, mul_inv2M.\nQed.\n\nLemma eqm_div2M : forall M x, Z.Odd M -> eqm M (div2M M x) (inv2M M * x).\nProof.\nintros M x HM.\nrewrite <- (Z.mul_1_l (div2M M x)).\napply eqm_trans with ((inv2M M * 2) * div2M M x)%Z.\n apply Zmult_eqm; try reflexivity.\n apply eqm_sym.\n apply mul_inv2M; auto.\nrewrite <- Zmult_assoc.\napply Zmult_eqm; try reflexivity.\nunfold div2M.\ncase (Z.odd x) eqn:Hx.\n* apply Zodd_bool_iff in Hx.\n  apply Zodd_equiv in HM.\n  rewrite <- Zdiv2_div, <- Zeven_div2; auto using Zodd_plus_Zodd.\n  unfold eqm; rewrite Zplus_mod. \n  rewrite <- (Zmod_eqm M M), Z_mod_same_full, Z.add_0_r.\n  apply Zmod_mod.\n* apply (f_equal negb) in Hx.\n  rewrite Z.negb_odd in Hx.\n  apply Zeven_bool_iff in Hx.\n  rewrite <- Zdiv2_div, <- Zeven_div2; auto.\n  reflexivity.\nQed.\n\nLemma eqm_div2M' : forall M x y, Z.Odd M -> \n eqm M (inv2M M * (x * y)) (div2M M x * y).\nProof.\nintros M x y HM.\nrewrite Zmult_assoc.\napply Zmult_eqm;try reflexivity.\nauto using eqm_div2M, eqm_sym.\nQed.\n\nLemma modulo_step : forall x st, Z.Odd (modulus st) -> Z.Odd (f st) ->\n  modulo_invariant x st ->\n  modulo_invariant x (step st).\nProof.\nintros x [delta f g d e M] HM Hf [Heqf Heqg].\nunfold modulo_invariant.\nrewrite modulus_step.\nsimpl in *.\ndestruct (Z.eq_dec M 1%Z) as [->|HM1].\n unfold eqm.\n rewrite !Z.mod_1_r; auto with *.\ndestruct (Z.eq_dec M (-1)%Z) as [->|HM1'].\n unfold eqm.\n rewrite !(Z_mod_zero_opp_r _ _ (Z.mod_1_r _)); auto with *.\nassert (HM0 : M <> 0%Z).\n rewrite <- Z.odd_spec in HM.\n intros HM0.\n rewrite HM0 in HM.\n discriminate.\nassert (HM2 : (2 mod M)%Z <> 0%Z).\n rewrite <- Z.odd_spec in HM.\n intros H.\n apply Znumtheory.Zmod_divide in H; auto with *.\n apply Znumtheory.prime_divisors in H; auto using Znumtheory.prime_2.\n destruct H as [H|[H|[H|H]]]; try contradiction; rewrite H in HM; discriminate.\nunfold step.\ncbn -[Z.ltb Z.add Z.sub] in *.\ncase (Z.even g) eqn:Hg;[|case (0 <? delta)%Z];simpl;split;auto.\n* apply Zeven_bool_iff in Hg.\n  apply Zeven_equiv in Hg.\n  eapply eqm_trans;[apply mul_inv2M_even;auto|].\n  eapply eqm_trans;[|apply eqm_div2M';auto].\n  apply Zmult_eqm;try reflexivity.\n  assumption.\n* apply (f_equal negb) in Hg.\n  rewrite Z.negb_even in Hg.\n  rewrite Zodd_bool_iff in Hg.\n  apply Zodd_equiv in Hg.\n  eapply eqm_trans;[apply mul_inv2M_even;auto|].\n   apply Zeven_equiv.\n   apply Zodd_plus_Zodd; apply Zodd_equiv; auto.\n   apply Z.odd_spec.\n   rewrite Z.odd_opp.\n   apply Z.odd_spec.\n   assumption.\n  eapply eqm_trans;[|apply eqm_div2M';auto].\n  apply Zmult_eqm;try reflexivity.\n  replace ((e - d)*x)%Z with (e * x - d * x)%Z by ring.\n  apply Zminus_eqm; auto.\n* apply (f_equal negb) in Hg.\n  rewrite Z.negb_even in Hg.\n  rewrite Zodd_bool_iff in Hg.\n  apply Zodd_equiv in Hg.\n  eapply eqm_trans;[apply mul_inv2M_even;auto|].\n   apply Zeven_equiv.\n   apply Zodd_plus_Zodd; apply Zodd_equiv; auto.\n  eapply eqm_trans;[|apply eqm_div2M';auto].\n  apply Zmult_eqm;try reflexivity.\n  replace ((e + d)*x)%Z with (e * x + d * x)%Z by ring.\n  apply Zplus_eqm; auto.\nQed.\n\nLemma modulo_spec : forall (n:nat) st x,\n  Z.Odd (modulus st) ->\n  Z.Odd (f st) ->\n  modulo_invariant x st ->\n  Znumtheory.rel_prime (f st) (g st) ->\n  let st' := (Nat.iter n step st) in\n  g st' = 0%Z ->\n  Z.abs (f st') = 1%Z /\\\n  eqm (modulus st) ((d st' * f st') * x) 1.\nProof.\nintros n st x HM Hf Hinv Hprime st' Hg.\nassert (HMeq : modulus st = modulus st').\n clear.\n induction n;try reflexivity.\n unfold st'.\n rewrite IHn.\n simpl.\n rewrite modulus_step.\n reflexivity.\nassert (Hinv' : modulo_invariant x st').\n clear -HM Hf Hinv.\n cut (Z.Odd (modulus st') /\\ (Z.Odd (f st') /\\ modulo_invariant x st'));[tauto|].\n induction n; auto.\n destruct IHn as [IHn1 [IHn2 IHn3]].\n unfold st'.\n simpl.\n split;[rewrite modulus_step;auto|].\n split;[apply odd_step;auto|].\n apply modulo_step; auto.\ndestruct Hinv' as [Hinv' _].\nrewrite (Zmult_comm (d st') _), <- Zmult_assoc.\nrewrite <- HMeq in Hinv'.\nassert (Hgcd := gcd_spec n st Hf Hg).\nfold st' in Hgcd.\nassert (H1 : Z.abs (f st') = 1%Z).\ndestruct (Znumtheory.Zis_gcd_uniqueness_apart_sign _ _ _ _ Hgcd Hprime) as [->| ->];\n auto.\nsplit; auto.\nchange 1%Z with (1 * 1)%Z.\nrewrite <- H1.\nrewrite Z.abs_square.\napply eqm_sym.\napply Zmult_eqm; auto; reflexivity.\nQed.\n\nLemma modulo_init : forall f g, modulo_invariant g (init f g).\nProof.\nintros f g.\nsplit; unfold init; cbn -[Zmult]; unfold eqm.\n* rewrite Z_mod_same_full, Z.mul_0_l, Zmod_0_l; reflexivity.\n* rewrite Z.mul_1_l; reflexivity.\nQed.\n\nEnd Step.\nEnd hddivsteps.\n", "meta": {"author": "sipa", "repo": "safegcd-bounds", "sha": "afab8eda5b7e526b0069c4b132609e9fd09404bf", "save_path": "github-repos/coq/sipa-safegcd-bounds", "path": "github-repos/coq/sipa-safegcd-bounds/safegcd-bounds-afab8eda5b7e526b0069c4b132609e9fd09404bf/coq/hddivsteps/hddivsteps_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.72130845583104}}
{"text": "Inductive mynat : Set := Zero : mynat | Succ : mynat -> mynat.\n\nFixpoint myplus n m : mynat :=\nmatch n with\n  | Zero => m\n  | Succ p => Succ (myplus p m)\nend.\n\nLemma plus_n_0 : forall n : mynat, myplus n Zero = n.\nProof.\ninduction n.\n(*simpl.*)\nreflexivity.\n\nsimpl.\nrewrite -> IHn.\nreflexivity.\nQed.", "meta": {"author": "mklinik", "repo": "radboud", "sha": "1b79730dbf7979221ca0de97fc369db82c405331", "save_path": "github-repos/coq/mklinik-radboud", "path": "github-repos/coq/mklinik-radboud/radboud-1b79730dbf7979221ca0de97fc369db82c405331/type-theory-IMC010/mynat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7212904042741475}}
{"text": "Definition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => negb b2\n  | false => true\n  end.\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\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  andb (andb b1 b2) b3.\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\nFixpoint factorial (n:nat) : nat :=\n  match n with\n  | O => 1\n  | S n => S n * factorial n\n  end.\nExample test_factorial1: (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\nExample test_factorial2: (factorial 5) = (mult 10 12).\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\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nDefinition ltb (n m : nat) : bool :=\n  negb (leb m n).\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\nExample test_ltb1: (ltb 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_ltb2: (ltb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ltb3: (ltb 4 2) = false.\nProof. simpl. 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 H.\n  rewrite <- H.\n  intros H'.\n  rewrite -> H'.\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 H.\n  rewrite -> H.\n  reflexivity.\n  Qed.\n\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c = true -> c = true.\nProof.\n  intros [] [].\n  reflexivity.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\n  Qed.\n\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n  intros [].\n  - reflexivity.\n  - reflexivity.\n  Qed.\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.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\n  Qed.\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.\n  rewrite -> H.\n  rewrite -> H.\n  destruct b.\n  reflexivity.\n  reflexivity.\n  Qed.\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros [] [].\n  reflexivity.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\n  simpl.\n  intros H.\n  rewrite -> H.\n  reflexivity.\n  reflexivity.\n  Qed.\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 decr (m:bin) : bin :=\n  match m with\n  | Z => Z\n  | A n => B (decr n)\n  | B n => match n with\n           | Z => Z\n           | _ => A n\n           end\n  end.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n  match m with\n  | Z => O\n  | A n => 2 * bin_to_nat n\n  | B n => 1 + 2 * bin_to_nat n\n  end.\n", "meta": {"author": "akemimadoka", "repo": "software-foundations-exercises", "sha": "5acc814e7f0653de0d2e7bddaa7b8d34046821ec", "save_path": "github-repos/coq/akemimadoka-software-foundations-exercises", "path": "github-repos/coq/akemimadoka-software-foundations-exercises/software-foundations-exercises-5acc814e7f0653de0d2e7bddaa7b8d34046821ec/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156295, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7211798667980704}}
{"text": "Require Import A1_Plan A2_Orientation .\nRequire Import C1_Distance .\nRequire Import D1_IntersectionCirclesProp .\nRequire Import F5_Tactics .\nRequire Import G1_Angles.\n\nSection ANGLE_PROPERTIES.\n\nLemma  EqAngleUniquePointSide1 : forall A B C D : Point, \n\tCongruentAngle C A B D A B ->\n\tDistance A C = Distance A D ->\n\t~Clockwise A C B ->\n\t~Clockwise A D B ->\n\tC = D.\nProof.\n\tintros.\n\tapply (EqThirdPoint A B).\n\t apply (CongruentAngleDistinctBC C A B D A B H) .\n\t immediate5.\n\t apply (CongruentSAS A B C A B D).\n\t  immediate5.\n\t  immediate5.\n\t  apply CongruentAngleRev; immediate5.\n\t immediate5.\n\t immediate5.\nQed.\n\nLemma  EqAngleUniquePointSide2 : forall A B C D : Point,\n\tCongruentAngle B A C B A D  ->\n\tDistance A C = Distance A D ->\n\t~Clockwise A B C ->\n\t~Clockwise A B D ->\n\tC = D.\nProof.\n\tintros.\n\tapply (EqThirdPoint B A).\n\t apply sym_not_eq; apply (CongruentAngleDistinctBA B A C B A D H).\n\t apply (CongruentSAS A B C A B D); immediate5.\n\t immediate5.\n\t immediate5.\n\t immediate5.\nQed.\n\nLemma  EqAngleOpenRay1 : forall A B C D : Point, \n\tCongruentAngle C A B D A B ->\n\t~Clockwise A C B ->\n\t~Clockwise A D B ->\n\tOpenRay A C D.\nProof.\n\tintros.\n\tsetMarkSegmentPoint5 A D A C ipattern:(E).\n\t apply (CongruentAngleDistinctED C A B D A B H).\n\t since5 (C = E).\n\t  apply (EqAngleUniquePointSide1 A B C E).\n\t   apply (CongruentAngleTrans C A B D A B E A B).\n\t    immediate5.\n\t    apply CongruentAngleSide1.\n\t     immediate5.\n\t     apply (CongruentAngleDistinctBC C A B D A B H).\n\t     step5 H4.\n\t       step5 H3.\n\t       apply (CongruentAngleDistinctBA C A B D A B H).\n\t   immediate5.\n\t   immediate5.\n\t   intro; elim H1; step5 H4.\n\t  rewrite H5; immediate5.\nQed.\n\nLemma  EqAngleOpenRay2 : forall A B C D : Point, \n\tCongruentAngle B A C B A D ->\n\t~Clockwise A B C ->\n\t~Clockwise A B D ->\n\tOpenRay A C D.\nProof.\n\tintros.\n\tsetMarkSegmentPoint5 A D A C ipattern:(E).\n\t apply (CongruentAngleDistinctEF B A C B A D H).\n\t since5 (C = E).\n\t  apply (EqAngleUniquePointSide2 A B C E).\n\t   apply (CongruentAngleTrans B A C B A D B A E).\n\t    immediate5.\n\t    apply CongruentAngleSide2.\n\t     apply (CongruentAngleDistinctBA B A C B A D H).\n\t     immediate5.\n\t     step5 H4.\n\t       step5 H3.\n\t       apply (CongruentAngleDistinctBC B A C B A D H).\n\t   immediate5.\n\t   immediate5.\n\t   intro; elim H1; step5 H4.\n\t  rewrite H5; immediate5.\nQed.\n\nEnd ANGLE_PROPERTIES.\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/G2_AngleProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7211798614102853}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, partition *)\n\nInductive list(X: Type): Type :=\n|nil: list X\n|cons: X -> list X -> list X.\n\nArguments nil {X}.\nArguments cons {X} _ _.\n\nNotation \"[]\" := nil.\nNotation \"x :: y\" := (cons x y)(at level 60, right associativity).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint filter{X:Type}(f: X -> bool)(l: list X): list X:=\n    match l with\n    |[]   => []\n    |h::t => if f h then h::(filter f t) else (filter f t)\n    end.\n\nInductive prod(X Y: Type): Type :=\n|pair: X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\nNotation \"X * Y\" := (prod X Y): type_scope.\n\nDefinition fst{X Y: Type}(p: X*Y):= match p with (x,_) => x end.\nDefinition snd{X Y: Type}(p: X*Y):= match p with (_,y) => y end.\n\nDefinition notb(b: bool): bool:=\n    match b with\n    |true  => false\n    |false => true\n    end.\n\nDefinition partition{X: Type}(test: X -> bool)(l: list X): list X * list X :=\n    (filter test l, filter (fun x => notb (test x)) l).\n\nExample test_partition1: partition Nat.odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\n\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter6_Library_Poly/partition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7211798558236032}}
{"text": "(*\nZ_3 háromelemű (véges) típus, Z_3={0, 1, 2} ill. {n, a, b}\n*)\n\nInductive Z_3 : Set :=\n  | n : Z_3 \n  | a : Z_3\n  | b : Z_3.\n\n(*\nLegyen belőle csoport, ami egy olyan algebrai struktúra, ahol van \n\nop: G->G->G művelet, \n\nahol op asszociatív,\n\nvan z neutrális elem: op z x = x = op x z\n\nvan inv: inverz : op x (inv) x = z = op (inv x) x\n\nZ_3-ban ez az összeadás:\n\n*)\n\nDefinition ope (x:Z_3) (y:Z_3) :=\n  match x , y with\n  | n , y => y\n  | x , n => x\n  | a , b => n\n  | b , a => n \n  | a , a => b\n  | b , b => a\n  end.\n\nDefinition inve (x:Z_3) :=\n  match x with\n  | n => n\n  | a => b\n  | b => a\n  end.\n\n(*Absztrakt csoport definíciója Structure vagy Record környezettel: *)\n\nStructure Group : Type := const_kozos\n{\n  A :> Set;\n\n  op : A -> A -> A ;\n  inv : A -> A ;\n  z : A ;\n\n  op_assoc : forall a b c, op a (op b c) = op (op a b) c;\n  op_z : forall a, op a z = a /\\ op z a = a ;\n  op_inverse : forall a, op a (inv a) = z /\\ op (inv a) a = z\n}.\n\n\n(*Z_3 a műveletekkel valóban csoport, amit\n a Group típus Z_3_group jelölésű eleme mutat, aminek a definíciója: *)\n\nTheorem Z_3_group : Group.\nProof.\n  apply (const_kozos Z_3 ope inve n).\n  induction a0, b0, c; compute; auto.\n  induction a0; auto.\n  induction a0; auto.\nDefined.\n\n(*Minden véges típus algoritmikusan eldönthető, így Z_3 is: *)\n\nTheorem Z_3_eq_dec : forall (x y: Z_3), x = y \\/ x <> y.\nProof. \n  induction x, y; auto; right; discriminate.\n  Show Proof.\nDefined.\n\n(*A morfizmusok őshonos állatfajok a típuselméletben, \nígy a csoportok közötti G->H művelettartó leképezések is *)\n\nDefinition GroupMorphism (G:Group) (H:Group) (f:G->H) : Prop :=  \n    f(z G)=z H /\\\n    forall a:G, f(inv G a)=inv H (f(a)) /\\\n    forall a b : G, f(op G a b) = op H (f(a)) (f(b)).\n\n(*Pl. a Z_1->Z_3, e|--->n leképezés is egy csoportmorfizmus *)\n\n\nInductive Z_1 : Set :=\n  | e : Z_1.\n\nDefinition ope_1 (x:Z_1) (y:Z_1) :=\n  match x , y with\n  | e , e => e\n  end.\n\nDefinition inve_1 x:Z_1 :=\n  match x with\n  | e => e\n  end.\n\nTheorem Z_1_group : Group.\nProof.\n  apply (const_kozos Z_1 ope_1 inve_1 e).\n  induction a0, b0, c; compute; auto.\n  induction a0; auto. \n  induction a0; auto.\nDefined.\n\nDefinition f_Z_1_Z_3 : Z_1->Z_3 := fun (x:Z_1) => match x with e => n end.\n\nTheorem f_Z_1_Z_3_csoportmorfizmus : GroupMorphism (Z_1_group) (Z_3_group) f_Z_1_Z_3.\nProof.\n  unfold GroupMorphism.\n  split.\n  compute; auto.\n  split.\n  induction a0.\n  compute; auto.\n  induction a0, b0.\n  induction a0.\n  compute; auto.\nQed.\n\n\n\n\n\n", "meta": {"author": "mozow01", "repo": "bizcoq2021", "sha": "f98f22ba3ce80899bc88605ce3193d8972102c92", "save_path": "github-repos/coq/mozow01-bizcoq2021", "path": "github-repos/coq/mozow01-bizcoq2021/bizcoq2021-f98f22ba3ce80899bc88605ce3193d8972102c92/eloadas/2_bonyolultabb/bizcoq_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.721179628165167}}
{"text": "(*\nGuido Salazar\nTaller 3 Logica Computacional\n*)\n\nSection LP1.\nVariables P Q R S T : Prop.\n\n(* 1 *)\nLemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\nProof.\nintro.\napply H.\nintro.\napply H0.\nintro.\napply H.\nintro.\nassumption.\nQed.\n\n(* 2 *)\nLemma then_bsc : (P -> Q) -> (Q -> R) -> P -> R.\nProof.\nintros.\napply H0.\napply H.\nassumption.\nQed.\n\n(* 3 *)\nLemma contraposition : ((P -> Q) -> (~Q -> ~P)).\nProof.\nintros.\nintro.\ndestruct H0.\napply H.\nassumption.\nQed.\n\n(* 4 *)\nLemma contraposition' : (~P -> ~Q) <-> (~~Q -> ~~P).\nProof.\nsplit.\nintros.\nintro.\napply H.\nassumption.\ndestruct H0.\napply H.\nassumption.\nintros.\nintro.\napply H.\nintro.\ndestruct H2.\nassumption.\nassumption.\nQed.\n\n(* 5 *)\nLemma impl_cmpl : (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\nintros.\ndestruct H.\ndestruct H0.\nsplit.\nintro.\napply H0.\napply H.\nassumption.\nintro.\napply H1.\napply H2.\nassumption.\nQed.\n\n(* 6 *)\nLemma then_ext : (P -> Q) -> (P -> R) -> (Q -> R -> S) -> P -> S.\nProof.\nintros.\napply H1.\napply H.\nassumption.\napply H0.\nassumption.\nQed.\n\nEnd LP1.\n\nSection LP2.\nVariables P Q R S T : Prop.\n\n(* 7 *)\nLemma and_assoc : P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\nintro.\ndestruct H.\ndestruct H0.\nsplit.\nsplit.\nassumption.\nassumption.\nassumption.\nQed.\n\n(* 8 *)\nLemma and_imp_dist : (P -> Q) /\\ (R -> S) -> P /\\ R -> Q /\\ S.\nProof.\nintro.\ndestruct H.\nintro.\ndestruct H1.\nsplit.\napply H.\nassumption.\napply H0.\nassumption.\nQed.\n\n(* 9 - Resolver usando Contradicction *)\nLemma not_contrad : ~(P /\\ ~P).\nProof.\nintro.\ndestruct H.\ncontradiction.\nQed.\n\n(* 10 *)\nLemma or_and_not : (P \\/ Q) /\\ ~P -> Q.\nProof.\nintro.\ndestruct H.\ndestruct H.\ncontradiction.\nassumption.\nQed.\n\n(* 11 *)\nLemma de_morgan_1 : ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\nintro.\nsplit.\nintro.\ndestruct H.\nleft.\nassumption.\nintro.\ndestruct H.\nright.\nassumption.\nQed.\n\n(* 12 *)\nLemma de_morgan_2 : ~P /\\ ~Q -> ~(P \\/ Q).\nintro.\ndestruct H.\nintro.\ndestruct H1.\ncontradiction.\ncontradiction.\nQed.\n\n(* 13 *)\nLemma de_morgan_3 : ~P \\/ ~Q -> ~(P /\\ Q).\nProof.\nintro.\nintro.\ndestruct H0.\ndestruct H.\ncontradiction.\ndestruct H.\nassumption.\nQed.\n\n(* 14 *)\nLemma b_mx : P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\nsplit.\nintro.\ndestruct H.\nsplit.\nleft.\nassumption.\nleft.\nassumption.\ndestruct H.\nsplit.\nright.\nassumption.\nright.\nassumption.\nintro.\ndestruct H.\ndestruct H.\nleft.\nassumption.\ndestruct H0.\nleft.\nassumption.\nright.\nsplit.\nassumption.\nassumption.\nQed.\n\nEnd LP2.\n\n(* 15 *)\nSection S0.\nVariables P Q : Prop.\nHypothesis H0 : P -> Q.\nHypothesis H1 : ~P -> Q.\nLemma weak_exm : ~~Q.\nProof.\nunfold not.\nintro.\napply H.\napply H1.\nintro.\napply H.\napply H0.\nassumption.\nQed.\n\nEnd S0.\n\n(* 16 *)\n(*\nP : Aprobare Lógica\nQ : Dios Quiere/ Dios quiere que apruebe.\nR : Estudie\nS : Hice todo los ejercicios\n*)\n\n(* Sección con Q : Dios quiere que apruebe*)\nSection S1.\nVariables P Q R S: Prop.\nHypothesis H : Q -> P.\nHypothesis H0 : P <-> (R /\\ S). \nLemma weak_exm2 : ~S -> (~Q->~P).\nProof.\nintros.\ndestruct H0.\nintro.\ndestruct H1.\napply H3.\nassumption.\nQed.\n\nEnd S1.\n\n(* Sección con Q : Dios quiere*)\nSection S2.\n\nVariables P Q R S: Prop.\nHypothesis H : Q -> P.\nHypothesis H0 : P <-> (R /\\ S). \nLemma weak_exm1 : ~S -> ~Q.\nProof.\nintro.\ndestruct H0.\nintro.\ndestruct H1.\napply H2.\napply H.\nassumption.\nQed.\n\nEnd S2.\n\n\n\n\n", "meta": {"author": "GAOV13", "repo": "Logica-Computacional", "sha": "384ef4fac3f9a02a16f0655f95e16215c41e6cc3", "save_path": "github-repos/coq/GAOV13-Logica-Computacional", "path": "github-repos/coq/GAOV13-Logica-Computacional/Logica-Computacional-384ef4fac3f9a02a16f0655f95e16215c41e6cc3/Taller 3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7210470038181341}}
{"text": "Require Import Omega.\nRequire Import Nat.\nRequire Export Arith_base.\nRequire Import Arith.Even.\nRequire Import BinPos BinInt BinNat Pnat Nnat.\nRequire Import PeanoNat.\nRequire Import ZArith_base.\nRequire Import ZArithRing.\nRequire Import Zcomplements.\nRequire Import Zdiv.\nRequire Import Wf_nat.\n\nLemma even_exists : forall x : nat,\nNat.even x = true -> exists k, 2*k = x.\nProof.\nintros.\napply Nat.even_spec in H.\nunfold Nat.Even in H.\ndestruct H.\nexists x0.\nauto.\nQed.\n\nLemma even_minus_even_is_even : forall x a : nat,\n    Nat.even(x + 2*a) = true -> Nat.even(x) = true.\nProof.\nintros.\napply Nat.even_spec in H.\nunfold Nat.Even in H.\napply Nat.even_spec.\nunfold Nat.Even.\ndestruct H.\napply f_equal with (f := fun t => t- 2*a) in H.\nreplace (x + 2*a - 2*a) with (x) in H.\nreplace (2*x0 - 2*a) with (2*(x0-a)) in H.\nexists (x0-a).\nassumption.\nomega.\nomega.\nQed.\n\n\n\nTheorem two_times_x_even : forall x : nat, Nat.even(2 * x) = true.\nProof.\n  simpl.\n  induction x.\n  auto.\n  rewrite Nat.add_0_r.\n  rewrite Nat.add_0_r in IHx.\n  replace (S x + S x) with (S (S (x + x))).\n  simpl.\n  apply IHx.\n  simpl.\n  auto.\nQed.\n\n\nAxiom trivial : forall x : nat, 2*(x-1) +1 = 2*x - 1.\n\n\n\n\n  Lemma even_plus_one_is_odd : forall x : nat, Nat.even(x+1) = true -> Nat.odd(x) = true.\nProof.\nintros.\napply Nat.even_spec in H.\napply Nat.odd_spec.\nunfold Nat.Odd.\nunfold Nat.Even in H.\ndestruct H.\napply f_equal with (f := fun t => t-1) in H.\nreplace (x +1-1) with (x) in H.\nreplace (2*x0 -1) with (2*(x0-1) + 1) in H.\nexists (x0-1).\nassumption.\napply trivial.\nomega.\nQed.\n\n  \n  Theorem easy : forall p q : Prop, (p->q) -> (~q->~p).\nProof.\nintros.\nintro.\napply H0.\napply H.\nassumption.\nQed.\n\nLemma not_even_not_odd : forall n, even n -> odd n -> False.\nProof.\ninduction n.\nintros even_0 odd_0.\ninversion odd_0.\nintros even_Sn odd_Sn.\ninversion even_Sn.\ninversion  odd_Sn.\nauto with arith.\nQed.\n\nAxiom not_even_implies_odd: forall x : nat, Nat.even(x) <> true -> Nat.odd(x) = true.\nTheorem square_even_is_even : forall x : nat, Nat.even(x * x) = true <->  Nat.even(x) = true.\nProof.\nintros.\ninduction x.\nsimpl.  \nsplit.\nauto.\nauto.\nsplit.\nintros.\nreplace (S x  * S x) with ((x*x + 1) + 2*x) in H.\nassert (forall p q : nat, Nat.even(p+2*q) = true -> Nat.even(p) = true).\napply even_minus_even_is_even.\nassert (Nat.even(x*x+1) = true).\ndestruct (H0 (x*x+1) (x)).\nassumption.\nauto.\nassert (Nat.odd(x*x) = true).\napply even_plus_one_is_odd.\nassumption.\ndestruct IHx.\nassert (Nat.odd x = true).\nassert (~Nat.even(x*x) = true -> ~Nat.even(x) = true).     \napply easy.\nassumption.\nassert (Nat.even(x*x) <> true).\nunfold not.\nintros.\nassert (forall n : nat, (Nat.Even(n) -> Nat.Odd(n) -> False)).\nintros.\napply even_equiv in H7.\napply odd_equiv in H8.\ncut (odd n).\ncut (even n).\napply not_even_not_odd.\nassumption.\nassumption.\ndestruct (H7 (x*x)).\ncut (Nat.even(x*x) = true).\napply Nat.even_spec.\nassumption.\ncut (Nat.odd(x*x) = true).\napply Nat.odd_spec.\nassumption.\nassert (Nat.even x <> true).\napply H5.\nassumption.\ncut (Nat.even x <> true).\napply not_even_implies_odd.\nassumption.\nreplace (S x) with (x+1).\ncut (Nat.odd(1)= true).\ncut (Nat.odd(x) = true).\nrewrite Nat.even_spec.\nrepeat rewrite Nat.odd_spec.\nrewrite <-  even_equiv.\nrepeat rewrite <- odd_equiv.\napply odd_even_plus. \nassumption.\nauto.\nomega.\nsimpl.\nreplace (S x) with (x+1).\nrewrite Nat.mul_add_distr_l.\nrepeat omega.\nomega.\nintros.\nrewrite Nat.even_spec in H.\nrewrite Nat.even_spec.\nunfold Nat.Even in H.\nunfold Nat.Even.\ndestruct H.\nreplace (S x) with (2*x0).\nexists (2*x0*x0).\nrewrite <- Nat.mul_assoc.\napply f_equal.\nrewrite Nat.mul_assoc.\nreplace (x0*2) with (2*x0).\nauto.\nomega.\nQed.\n\n\nTheorem root_2_irr : forall p q : nat,p * p <> 2 * q * q.\n  Proof.\n  intros.\n  unfold not.\n  intros eq.\n  assert (Nat.even(p*p) = true).\n  rewrite eq.\n  replace (2*q*q) with (2*(q*q)).\n  apply two_times_x_even.\n  symmetry.\n  apply mult_assoc_reverse.\n  assert (Nat.even(p)= true).\n  apply square_even_is_even.\n  assumption.\n\n\n  (* The proof is incomplete, still need a way to define relatively prime numbers (that's readily available from coq) and a few lemmas need to be proved which are listed as axioms *)\n", "meta": {"author": "pointoflight", "repo": "coq_proofs", "sha": "dfde183d9e65ceb5533cea2bdbaf58606923b86c", "save_path": "github-repos/coq/pointoflight-coq_proofs", "path": "github-repos/coq/pointoflight-coq_proofs/coq_proofs-dfde183d9e65ceb5533cea2bdbaf58606923b86c/root2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.721046997405625}}
{"text": "Require Import GraphBasics.Graphs.\nRequire Import GraphBasics.Connected.\nRequire Import Coq.Logic.Classical_Prop.\n\n(* Require FunInd. *)\n\n\nSection Help.\n\n(* Our terminology for members of a network (graph). *)\nDefinition Component := Vertex.\n\n(* Unequalness is symmetric. *)\nLemma neq_symm: forall (X : Type) {p q: X}, p <> q -> q <> p.\nProof.\n  intros X p q pq.\n  unfold not.\n  intros.\n  apply pq.\n  symmetry.\n  apply H.\nQed.\n\n(* A natural number can't be even and odd at the same time. *)\nLemma not_even_and_odd: forall (n : nat),\n  Nat.even n = Nat.odd n -> False.\nProof.\n  intros n H.\n  induction n.\n  simpl in H.\n  rewrite Nat.odd_0 in H.\n  inversion H.\n  apply IHn.\n  rewrite Nat.even_succ in H.\n  rewrite Nat.odd_succ in H.\n  symmetry.\n  apply H.\nQed.\n\n(* A natural number is either odd or even. *)\nLemma even_or_odd: forall(n : nat),\n  Nat.even n = true \\/ Nat.odd n = true.\nProof.\n  intros n.\n  induction n.\n  left.\n  reflexivity.\n  destruct IHn.\n  right.\n  rewrite Nat.odd_succ.\n  apply H.\n  left.\n  rewrite Nat.even_succ.\n  apply H.\nQed.\n\n(* The definition of Connected doesn't allow loops (edges from some vertex to itself). *)\nLemma Connected_no_loops: forall (v: V_set) (a: A_set) (c : Connected v a) (x y : Vertex),\n  a (A_ends x y) -> x <> y.\nProof.\n  intros v a c x y arc.\n  assert (g:= c).\n  apply Connected_Isa_Graph in g.\n  assert (v x). \n  apply (G_ina_inv1 v a g) in arc.\n  apply arc.\n  rename H into vx.\n  assert (v y).\n  apply (G_ina_inv2 v a g) in arc.\n  apply arc.\n  rename H into vy.\n  induction c.\n\n  inversion arc.\n\n  assert (x0 <> y0).\n  unfold not. intros.\n  rewrite H in v0. intuition.\n\n  inversion arc.\n  inversion H0.\n  rewrite H3 in H. rewrite H4 in H. apply H.\n  rewrite H3 in H. rewrite H4 in H. intuition.\n  apply IHc.\n  apply H0.\n  apply Connected_Isa_Graph in c. apply c.\n  destruct vx.\n  inversion H2.\n  rewrite <- H3 in H0.\n  apply (G_ina_inv1 v a) in H0.\n  intuition.\n  apply Connected_Isa_Graph in c. apply c.\n  apply H2.\n  destruct vy.\n  inversion H2.\n  rewrite <- H3 in H0.\n  apply (G_ina_inv2 v a) in H0.\n  intuition.\n  apply Connected_Isa_Graph in c. apply c.\n  apply H2.\n\n  inversion arc.\n  inversion H.\n  rewrite H2 in n. rewrite H3 in n. apply n.\n  rewrite H2 in n. rewrite H3 in n. intuition.\n  apply (IHc H).\n  apply Connected_Isa_Graph in c. apply c.\n  apply vx. apply vy.\n\n  apply IHc.\n  rewrite <- e0 in arc.\n  apply arc.\n  rewrite <- e0 in g. rewrite <- e in g.\n  apply g.\n  rewrite <- e in vx.\n  apply vx.\n  rewrite <- e in vy.\n  apply vy.\nQed.\n\n(* the starting vertex of a walk is in the graph itself *)\nLemma W_endx_inv :\n forall (v: V_set) (a: A_set) (x y : Component) (vl : V_list) (el : E_list), Walk v a x y vl el -> v x.\nProof.\n        intros. inversion H. apply H0. apply H1.\nQed.\n\n(* the ending vertex of a walk is in the graph itself *)\nLemma W_endy_inv :\n forall (v: V_set) (a: A_set) (x y : Component) (vl : V_list) (el : E_list), Walk v a x y vl el -> v y.\nProof.\n        intros. elim H. intros. apply v0. intros. apply H0.\nQed.\n\n(* Lenghts of lists don't change by reversing. *)\nLemma E_rev_len: forall(el:E_list),\n  length (E_reverse el) = length el.\nProof.\n  intros el.\n  induction el.\n  reflexivity.\n  destruct a.\n  simpl.\n  rewrite app_length.\n  simpl.\n  rewrite IHel.\n  apply plus_comm.\nQed.\n\n(* All Connected have at least one component (therefore root exists). *)\nLemma v_not_empty : forall (v:V_set) (a:A_set) (c:Connected v a),\n  exists (x:Component), v x.\nProof.\n  intros v a c.\n  assert (c':=c).\n  induction c.\n  exists x.\n  unfold V_single.\n  intuition.\n\n  exists x.\n  apply V_in_right.\n  apply v0.\n  \n\n  exists x.\n  apply v0.\n  \n  rewrite <- e.\n  apply IHc.\n  apply c.\nQed.\n\nEnd Help.", "meta": {"author": "voellinger", "repo": "verified-certifying-distributed-algorithms", "sha": "35b2a4dc5c0aec6228ded6b10bbe4d086692dadb", "save_path": "github-repos/coq/voellinger-verified-certifying-distributed-algorithms", "path": "github-repos/coq/voellinger-verified-certifying-distributed-algorithms/verified-certifying-distributed-algorithms-35b2a4dc5c0aec6228ded6b10bbe4d086692dadb/bipartition/proofs/Help_Lemmata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8006920020959543, "lm_q1q2_score": 0.7210469952562741}}
{"text": "Require Import Arith.\nImport Nat.\n\n\nLoad hoare.\n\n(*\npower(x, n):\n  a := 1;\n  while n > 0 do    { x0 ^ n0 = a * x ^ n }\n    y := n mod 2;\n    n := n div 2;\n\n    if y then a := a * x else skip;\n    if n then x := x * x else skip\n *)\n\nDefinition gt01 n m := if gt_dec n m then 1 else 0.\n\nNotation \"[ e1 `*` e2 ]\" := (expr_op e1 mul e2).\nNotation \"[ e1 `/` e2 ]\" := (expr_op e1 div e2).\nNotation \"[ e1 `%` e2 ]\" := (expr_op e1 modulo e2).\nNotation \"[ e1 `>` e2 ]\" := (expr_op e1 gt01 e2).\n\nDefinition power_cmd :=\n  seq (assign a (expr_num 1))\n      (while [expr_var n `>` expr_num 0]\n             (seq (assign y [expr_var n `%` expr_num 2])\n                  (seq (assign n [expr_var n `/` expr_num 2])\n                       (seq (if_then_else (expr_var y)\n                                          (assign a [expr_var a `*` expr_var x])\n                                          skip)\n                            (if_then_else (expr_var n)\n                                          (assign x [expr_var x `*` expr_var x])\n                                          skip)\n                       )\n                  )\n             )\n      ).\n\n\n\nModule MainProof.\n\n  Definition c :=\n    (seq (assign y [expr_var n `%` expr_num 2])\n         (seq (assign n [expr_var n `/` expr_num 2])\n              (seq (if_then_else (expr_var y)\n                                 (assign a [expr_var a `*` expr_var x])\n                                 skip)\n                   (if_then_else (expr_var n)\n                                 (assign x [expr_var x `*` expr_var x])\n                                 skip)\n              )\n         )\n    ).\n\n  Definition linv x0 n0 := fun s => x0 ^ n0 = s a * (s x ^ s n).\n\n  (* Control the behavior of `simpl` to allow more unfoldings. *)\n  Arguments subst P v e /.\n  Arguments set s v / z.\n  Arguments var_eq_dec !v1 !v2.\n  Arguments div !x !y.\n  Arguments modulo !x !y.\n  Arguments gt01 n m / : simpl nomatch.\n\n  Lemma div_mod_n n k : k > 0 -> n = (n / k) * k + (n mod k).\n  Admitted.\n\n  Definition c1 := \n    (seq (assign y [expr_var n `%` expr_num 2])\n         (assign n [expr_var n `/` expr_num 2])).\n\n  \n  \n  Definition c2 :=\n    (seq (if_then_else (expr_var y)\n                       (assign a [expr_var a `*` expr_var x])\n                       skip)\n         (if_then_else (expr_var n)\n                       (assign x [expr_var x `*` expr_var x])\n                       skip)\n    ).\n\n  Lemma linv_advance x0 n0 : hoare (fun s => linv x0 n0 s /\\ s n > 0)\n                                   c1\n                                   (fun s => x0 ^ n0 = s a * (s x * s x) ^ s n * s x ^ s y\n                                          /\\ s y <= 1).\n  Proof.\n    econstructor.\n    2: constructor.\n    eapply hoare_weaken_l.\n    2: constructor.\n    unfold linv; simpl.\n    intros s [H1 H2].\n    split.\n    - rewrite H1.\n      rewrite div_mod with (x:=s n) (y:=2) at 1; [|firstorder].\n      rewrite pow_add_r.\n      rewrite pow_mul_r. simpl. rewrite mul_assoc. firstorder.\n    - apply lt_n_Sm_le. apply mod_upper_bound. firstorder.\n  Qed.    \n\n  Inductive hoare_two : assertion -> cmd -> cmd -> assertion -> Prop :=\n    hoare_two_seq : forall c1 c2 P M Q,\n      hoare P c1 M -> hoare M c2 Q -> hoare_two P c1 c2 Q\n  | hoare_two_weaken : forall (P' P : assertion) c1 c2 (Q Q' : assertion),\n      (forall s, P' s -> P s) ->\n      hoare_two P c1 c2 Q ->\n      (forall s, Q s -> Q' s) ->\n      hoare_two P' c1 c2 Q'.\n\n  Lemma hss' P c1 c2 Q c12 : c12 = seq c1 c2 ->\n                             hoare P c12 Q -> hoare_two P c1 c2 Q.\n  Proof.\n    intros.\n    induction H0; inversion H.\n    - eapply hoare_two_seq. subst. eassumption. subst. eassumption.\n    - eapply hoare_two_weaken. eassumption. subst; firstorder. eassumption.\n  Qed.\n\n  Lemma hss P c1 c2 Q : hoare P (seq c1 c2) Q -> hoare_two P c1 c2 Q.\n  Proof.\n    apply hss'. reflexivity.\n  Qed.\n\n  Lemma hoare_middle_ground' P c1 c2 Q : hoare_two P c1 c2 Q ->\n                                         exists M, hoare P c1 M /\\ hoare M c2 Q.\n  Proof.\n    induction 1.\n    - exists M; firstorder.\n    - destruct IHhoare_two as [M].\n      exists M. firstorder.\n      + eapply hoare_weaken_l; eassumption.\n      + eapply hoare_weaken_r; eassumption.\n  Qed.\n\n  Lemma hoare_middle_ground P c1 c2 Q : hoare P (seq c1 c2) Q ->\n                                        exists M, hoare P c1 M /\\ hoare M c2 Q.\n  Proof.\n    intro; apply hoare_middle_ground'. apply hss. assumption.\n  Qed.\n  \n  Lemma hoare_seq_assoc P Q c1 c2 c3 :\n    hoare P (seq c1 (seq c2 c3)) Q <-> hoare P (seq (seq c1 c2) c3) Q.\n  Proof.\n    split.\n    - intro H. apply hoare_middle_ground in H.\n      destruct H as [M1 [H1 H23]].\n      apply hoare_middle_ground in H23.\n      destruct H23 as [M2 [H2 H3]].\n      econstructor.\n      + econstructor; eassumption.\n      + assumption.\n    - intro H. apply hoare_middle_ground in H.\n      destruct H as [M2 [H12 H3]].\n      apply hoare_middle_ground in H12.\n      destruct H12 as [M1 [H1 H2]].\n      econstructor.\n      + eassumption.\n      + econstructor; eassumption.\n  Qed.\n    (* -- this went terribly bad --\n    split.\n    intro H. apply hss in H. inversion H.\n    - apply hss in H1. subst. induction H1.\n      + econstructor.\n        econstructor.\n        eassumption. eassumption. eassumption.\n      + eapply hoare_weaken_r.\n        2: apply IHhoare_seq_seq.\n        * firstorder.\n        * eapply hoare_seq_weaken.\n          2: eassumption.\n       *)   \n\n\n  Require Omega.\n  \n  Lemma linv_inv x0 n0 : hoare (fun s => linv x0 n0 s /\\ s n > 0)\n                               c\n                               (linv x0 n0).\n  Proof.\n    apply hoare_seq_assoc.\n    econstructor.\n    - apply linv_advance.\n    - econstructor.\n      Focus 2.\n      {\n        econstructor.\n        - eapply hoare_weaken_l.\n          2: constructor.\n          unfold linv; simpl.\n          intros. destruct H.\n          exact H.\n        - eapply hoare_weaken_l.\n          2: constructor.\n          unfold linv; simpl.\n          intros s [H1 H2].\n          rewrite H1, H2. reflexivity.\n      }\n      Unfocus.\n      econstructor.\n      + eapply hoare_weaken_l. 2: constructor.\n        simpl.\n        intros s [[H1 H2] H3].\n        assert (s y = 1) by firstorder.\n        rewrite H1, H, pow_1_r.\n        rewrite <- mul_assoc.\n        rewrite mul_comm with (n:=_ ^ s n).\n        rewrite mul_assoc.\n        reflexivity.\n      + eapply hoare_weaken_l. 2: constructor.\n        simpl.\n        intros s [[H1 H2] H3].\n        rewrite H1, H3. firstorder.\n  Qed.\n      \n        \nEnd MainProof.\n", "meta": {"author": "corwin-of-amber", "repo": "various-proofs", "sha": "e7c19549f1d573487f9fb3ebd5d6b80b2c52184b", "save_path": "github-repos/coq/corwin-of-amber-various-proofs", "path": "github-repos/coq/corwin-of-amber-various-proofs/various-proofs-e7c19549f1d573487f9fb3ebd5d6b80b2c52184b/ssar-class/hoare-pow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.721012515365116}}
{"text": "From iVM Require Import Init.\n\nUnset Suggest Proof Using.\n\nLocal Open Scope Z.\nLocal Open Scope vector.\n\nNotation Bits := Bvector.\n\nArguments Bsign {_} _.\n\n\n(** ** Helpers *)\n\nProposition mul_nonneg (x y : Z) : 0 <= x -> 0 <= y -> 0 <= x * y.\nProof.\n  intros Hx Hy.\n  rewrite <- (Z2N.id _ Hx).\n  rewrite <- (Z2N.id _ Hy).\n  rewrite <- N2Z.inj_mul.\n  apply N2Z.is_nonneg.\nQed.\n\nLemma div_neg z x (Hx: 0 < x) : z / x < 0 <-> z < 0.\nProof.\n  split.\n  - intros H. apply Znot_ge_lt. intros Hz. contradict H.\n    apply Zle_not_lt, Z.ge_le, Z_div_ge0; lia.\n  - intros Hz. apply Znot_ge_lt. intros H.\n    set (H1 := Z.mul_div_le z x Hx).\n    set (H2 := mul_nonneg x (z/ x)).\n    lia.\nQed.\n\n\n(** *** Powers of two\n\nWe focus on [2^n] for natural numbers n. Using [Z.shiftl] would be more\nefficient, but we mainly use [2^n] for specification purposes (not\ncomputations). *)\n\nLemma pow2_equation_0 : 2^0 = 1.\nProof. reflexivity. Qed.\n\nLemma pow2_equation_1 : 2 ^ 0%nat = 1.\nProof. simpl. exact pow2_equation_0. Qed.\n\nLemma pow2_equation_2 n : 2^(S n) = 2 * (2^n).\nProof.\n  rewrite nat_N_Z, nat_N_Z, Nat2Z.inj_succ, Z.pow_succ_r.\n  - reflexivity.\n  - apply Nat2Z.is_nonneg.\nQed.\n\nHint Rewrite\n     pow2_equation_0\n     pow2_equation_1\n     pow2_equation_2 : pow2.\n\nLemma pow2_pos (n: nat) : 0 < 2^n.\nProof.\n  rewrite nat_N_Z.\n  apply Z.pow_pos_nonneg, Nat2Z.is_nonneg; lia.\nQed.\n\nCorollary pow2_nonneg (n: nat) : 0 <= 2^n.\nProof. apply Z.lt_le_incl, pow2_pos. Qed.\n\nCorollary pow2_nonzero (n: nat) : 2^n <> 0.\nProof. apply Z.neq_sym, Z.lt_neq, pow2_pos. Qed.\n\nCorollary pow2_div_zero (z: Z) (n: nat) : z / 2^n = 0 <-> 0 <= z < 2^n.\nProof.\n  transitivity (0 <= z < 2 ^ n \\/ 2 ^ n < z <= 0).\n  - apply Z.div_small_iff, pow2_nonzero.\n  - set (H := pow2_nonneg n). lia.\nQed.\n\nProposition pow2_action (m n: nat) : 2%Z^(m + n)%nat = 2%Z^m * 2%Z^n.\nProof.\n  repeat rewrite nat_N_Z.\n  rewrite Nat2Z.inj_add.\n  apply Zpower_exp; apply Z.le_ge; apply Nat2Z.is_nonneg.\nQed.\n\n\n(** *** Congruence modulo [2^n] *)\n\nSection cong_section.\n\n  Context (n: nat).\n\n  Definition cong := irel (fun (z:Z) => z mod 2^n) eq.\n\n  #[global] Instance cong_equivalence : Equivalence cong.\n  Proof.\n    apply irel_equivalence.\n    typeclasses eauto.\n  Qed.\n\n  Proposition eq_cong z z' : z = z' -> cong z z'.\n  Proof. apply eq_subrelation. Qed.\n\n  #[global] Instance cong_add_proper : Proper (cong ==> cong ==> cong) Z.add.\n  Proof.\n    intros x x' Hx y y' Hy. unfold cong, irel in *.\n    setoid_rewrite Z.add_mod; [ | apply pow2_nonzero ..].\n    f_equal. f_equal; assumption.\n  Qed.\n\n  Corollary cong_eq x y : cong x y <-> cong (x - y) 0.\n  Proof.\n    split; intros H.\n    - transitivity (x + (-y)).\n      + apply eq_cong. lia.\n      + setoid_rewrite H. apply eq_cong. lia.\n    - transitivity ((x - y) + y).\n      + apply eq_cong. lia.\n      + setoid_rewrite H.  apply eq_cong. lia.\n  Qed.\n\n  #[global] Instance cong_mul_proper : Proper (cong ==> cong ==> cong) Z.mul.\n  Proof.\n    intros x x' Hx y y' Hy. unfold cong, irel in *.\n    setoid_rewrite Z.mul_mod; [ | apply pow2_nonzero ..].\n    f_equal. f_equal; assumption.\n  Qed.\n\n  (** Essentially just transitivity and symmetry. *)\n  #[global] Instance cong_cong_proper : Proper (cong ==> cong ==> iff) cong.\n  Proof. typeclasses eauto. Qed.\n\n  Proposition cong_mod (z: Z) (m: nat) (Hm: m >= n) : cong (z mod 2^m) z.\n  Proof.\n    unfold cong, irel.\n    by_lia (m = n + (m - n))%nat as H.\n    rewrite H at 1.\n    rewrite pow2_action.\n    rewrite <- Znumtheory.Zmod_div_mod.\n    - reflexivity.\n    - apply pow2_pos.\n    - apply Z.mul_pos_pos; apply pow2_pos.\n    - auto with zarith.\n  Qed.\n\n  Corollary cong_zero k : cong (k * 2^n) 0.\n  Proof.\n    transitivity ((k * 2^n) mod 2^n).\n    - symmetry. apply cong_mod. lia.\n    - apply eq_cong. apply Z_mod_mult.\n  Qed.\n\nEnd cong_section.\n\n\n(** *** Double and div2\n\nConverting to/from bits we use [Z.double] and [Z.div2] for efficiency. *)\n\nProposition div2_double z : Z.div2 (Z.double z) = z.\nProof.\n  rewrite Z.div2_div, Z.double_spec, Z.mul_comm, Z_div_mult;\n    auto with zarith.\nQed.\n\nProposition div2_double1 z : Z.div2 (Z.double z + 1) = z.\nProof.\n  rewrite Z.div2_div, Z.double_spec, Z.mul_comm, Z_div_plus_full_l;\n    auto with zarith.\nQed.\n\nCorollary div2_double2 z b : Z.div2 (Z.double z + Z.b2z b) = z.\nProof.\n  destruct b; simpl.\n  - apply div2_double1.\n  - rewrite Z.add_0_r. apply div2_double.\nQed.\n\nLemma odd_double {z b} : Z.odd (Z.double z + Z.b2z b) = b.\nProof.\n  rewrite Z.add_comm, Z.odd_add_mul_2.\n  destruct b; reflexivity.\nQed.\n\nProposition double_neg z h : Z.double z + Z.b2z h < 0 <-> z < 0.\nProof.\n  rewrite Z.double_spec.\n  destruct h; simpl Z.b2z; lia.\nQed.\n\nProposition div2_odd (z: Z) : z = Z.double (Z.div2 z) + Z.b2z (Z.odd z).\nProof.\n  rewrite Z.double_spec.\n  apply Z.div2_odd.\nQed.\n\nProposition div2_reflects_lt x y : Z.div2 x < Z.div2 y -> x < y.\nProof.\n  intros H.\n  setoid_rewrite Z.div2_odd.\n  do 2 destruct (Z.odd _); simpl Z.b2z; lia.\nQed.\n\nLemma div2_double_connection x y (Hx: 0 <= x) (Hy: 0 <= y) : Z.div2 x < y <-> x < Z.double y.\nProof.\n  setoid_rewrite (div2_odd x) at 2.\n  split.\n  - intros H. apply div2_reflects_lt. rewrite div2_double2, div2_double. exact H.\n  - setoid_rewrite Z.double_spec.\n    rewrite Z.div2_div.\n    destruct (Z.odd x); simpl Z.b2z; lia.\nQed.\n\n\n(** ** To bits and back *)\n\n(** *** Cleave *)\n\nEquations cleave n (z: Z) : (Bits n) * Z :=\n  cleave 0 z := ([], z);\n  cleave (S n) z :=\n    let (u, z') := cleave n (Z.div2 z) in\n    (Z.odd z :: u, z').\n\nProposition cleave_action m n z :\n  cleave (m + n) z = let (u, z') := cleave m z in\n                     let (v, z'') := cleave n z' in\n                     (u ++ v, z'').\nProof.\n  revert z. induction m; intros z; cbn; simp cleave; cbn.\n  - destruct (cleave n z); reflexivity.\n  - rewrite IHm. clear IHm.\n    destruct (cleave m (Z.div2 z)).\n    destruct (cleave n z0).\n    reflexivity.\nQed.\n\nLemma snd_cleave n z : snd (cleave n z) = z / 2^n.\nProof.\n  revert z; induction n; intros z; simp cleave.\n  - cbn. symmetry. apply Z.div_1_r.\n  - specialize (IHn (Z.div2 z)).\n    destruct (cleave n (Z.div2 z)) as [u z'].\n    simpl snd in *.\n    simp pow2.\n    rewrite Z.div2_div, Z.div_div in IHn.\n    + exact IHn.\n    + lia.\n    + apply pow2_pos.\nQed.\n\nCorollary snd_cleave_neg n z : snd (cleave n z) < 0 <-> z < 0.\nProof.\n  rewrite snd_cleave.\n  apply div_neg, pow2_pos.\nQed.\n\n\n(** *** Join *)\n\nEquations join {n} (u: Bits n) (z: Z) : Z :=\n  join [] z := z;\n  join (h :: u) z := Z.double (join u z) + Z.b2z h.\n\nProposition join_action {m} (u: Bits m) {n} (v: Bits n) z :\n  join u (join v z) = join (u ++ v) z.\nProof.\n  induction m.\n  - dependent elimination u. reflexivity.\n  - dependent elimination u. cbn. simp join. rewrite IHm. reflexivity.\nQed.\n\nProposition join_diff {n} (u: Bits n) z1 z2 :\n  join u z1 - join u z2 = 2^n * (z1 - z2).\nProof.\n  induction n; simp pow2.\n  - dependent elimination u. simp join.\n    lia.\n  - dependent elimination u as [Vector.cons (n:=n) h u].\n    simp join.\n    specialize (IHn u).\n    rewrite <- Z.mul_assoc.\n    rewrite <- IHn.\n    clear IHn.\n    setoid_rewrite Z.double_spec.\n    destruct h; repeat simpl Z.b2z; lia.\nQed.\n\nCorollary join_via_zero {n} (u: Bits n) z : join u z = 2^n * z + join u 0.\nProof.\n  enough (join u z - join u 0 = 2^n * (z - 0)); [lia |].\n  apply join_diff.\nQed.\n\nProposition join_neg {n} (u: Bits n) z : join u z < 0 <-> z < 0.\nProof.\n  induction n.\n  - dependent elimination u. tauto.\n  - dependent elimination u as [Vector.cons (n:=n) h u].\n    simp join.\n    transitivity (join u z < 0).\n    apply double_neg.\n    exact (IHn u).\nQed.\n\nProposition join_zero {n} (u: Bits n) : 0 <= join u 0 < 2^n.\nProof.\n  induction n.\n  - dependent elimination u. simp join. cbn. lia.\n  - dependent elimination u as [Vector.cons (n:=n) h u].\n    simp join.\n    specialize (IHn u).\n    destruct IHn as [H1 H2].\n    split.\n    + rewrite Z.double_spec. destruct h; simpl Z.b2z; lia.\n    + simp pow2. apply div2_reflects_lt.\n      rewrite div2_double2, <- Z.double_spec, div2_double.\n      exact H2.\nQed.\n\nCorollary join_mod {n} (u: Bits n) z : join u z mod 2^n = join u 0.\nProof.\n  symmetry.\n  apply (Z.mod_unique_pos _ _ z).\n  - apply join_zero.\n  - apply join_via_zero.\nQed.\n\n\n(** *** Bijection *)\n\nLemma join_cleave n z : uncurry join (cleave n z) = z.\nProof.\n  unfold uncurry. revert z.\n  induction n; intros z; simp cleave.\n  - simp join. reflexivity.\n  - specialize (IHn (Z.div2 z)).\n    destruct (cleave n (Z.div2 z)).\n    simp join. rewrite IHn.\n    symmetry.\n    apply div2_odd.\nQed.\n\nLemma cleave_join {n} (u: Bits n) z : cleave n (join u z) = (u, z).\nProof.\n  revert z. induction n; intros z.\n  - dependent elimination u. simp cleave join. reflexivity.\n  - dependent elimination u as [Vector.cons (n:=n) h u].\n    simp join cleave.\n    rewrite div2_double2.\n    rewrite IHn. clear IHn.\n    f_equal.\n    f_equal.\n    apply odd_double.\nQed.\n\n\n(** *** fromBits and toBits *)\n\nDefinition toBits n z := fst (cleave n z).\n\nDefinition fromBits {n} (u: Bits n) := join u 0.\n\nProposition toBits_fromBits {n} (u: Bits n) : toBits n (fromBits u) = u.\nProof.\n  unfold fromBits, toBits.\n  rewrite cleave_join.\n  reflexivity.\nQed.\n\n(* TODO: Standard property of sections. *)\nCorollary fromBits_injective {n} (u u': Bits n) :\n  fromBits u = fromBits u' -> u = u'.\nProof.\n  intros H. setoid_rewrite <- toBits_fromBits.\n  f_equal. exact H.\nQed.\n\nProposition fromBits_toBits_mod {n} z : fromBits (toBits n z) = z mod 2^n.\nProof.\n  unfold fromBits, toBits.\n  given (join_cleave n z) as Hj.\n  destruct (cleave n z) as [u z'] eqn:Hz.\n  cbn.\n  symmetry.\n  rewrite <- Hj.\n  apply join_mod.\nQed.\n\nCorollary toBits_congruence (n: nat) z z' :\n  toBits n z = toBits n z' <-> z mod 2^n = z' mod 2^n.\nProof.\n  split; intro H.\n  - setoid_rewrite <- fromBits_toBits_mod.\n    f_equal.\n    exact H.\n  - apply fromBits_injective.\n    setoid_rewrite fromBits_toBits_mod.\n    exact H.\nQed.\n\nCorollary fromBits_toBits (n: nat) z : 0 <= z < 2^n <-> fromBits (toBits n z) = z.\nProof.\n  rewrite fromBits_toBits_mod.\n  setoid_rewrite Z.mod_small_iff; [| apply pow2_nonzero].\n  split; [ tauto |].\n  intros [H|H]; [exact H |].\n  exfalso.\n  given (pow2_pos n) as HH.\n  lia.\nQed.\n\n(* TODO: Remove? *)\nProposition join_spec {n} (u: Bits n) z : join u z = fromBits u + 2^n * z.\nProof.\n  unfold fromBits.\n  enough (join u z - join u 0 = 2 ^ n * (z - 0)); [lia|].\n  apply join_diff.\nQed.\n\n\n(** *** Via [N] *)\n\nDefinition bitsToN {n} (u: Bits n) : N := Z.to_N (fromBits u).\n\nProposition ofN_bitsToN {n} (u: Bits n) : Z.of_N (bitsToN u) = fromBits u.\nProof.\n  unfold bitsToN. rewrite Z2N.id.\n  - reflexivity.\n  - unfold fromBits. apply join_zero.\nQed.\n\nCorollary toBits_ofN_bitsToN {n} (u: Bits n) : toBits n (Z.of_N (bitsToN u)) = u.\nProof.\n  rewrite <- (toBits_fromBits u) at 2.\n  f_equal.\n  apply ofN_bitsToN.\nQed.\n\n\n(** *** Signed integers *)\n\nLocal Notation signOffset u := (if Bsign u then -1 else 0).\n\nDefinition bitsToZ {n} (u: Bits (S n)) : Z := join u (signOffset u).\n\nDefinition butSign {n} (u: Bits (S n)) : Bits n.\nProof.\n  induction n.\n  - exact [].\n  - dependent elimination u as [h :: u].\n    exact (h :: (IHn u)).\nDefined.\n\nProposition butSign_equation_1 s : butSign [s] = [].\nProof. reflexivity. Qed.\n\nProposition butSign_equation_2 {n} (u: Bits (S n)) h :\n  butSign (h :: u) = h :: butSign u.\nProof. reflexivity. Qed.\n\nHint Rewrite butSign_equation_1 : butSign.\nHint Rewrite @butSign_equation_2 : butSign.\n#[global] Opaque butSign.\n\nProposition bitsToZ_split {n} (u: Bits (S n)) :\n  bitsToZ u = join (butSign u) (signOffset u).\nProof.\n  unfold bitsToZ.\n  induction n.\n  - dependent elimination u as [h :: u].\n    dependent elimination u.\n    destruct h; reflexivity.\n  - dependent elimination u as [h :: u].\n    specialize (IHn u).\n    simp butSign join.\n    cbn.\n    f_equal.\n    f_equal.\n    exact IHn.\nQed.\n\nCorollary bitsToZ_range {n} (u: Bits (S n)):\n  -2^n <= bitsToZ u < 2^(S n).\nProof.\n  rewrite bitsToZ_split.\n  set (H := join_zero (butSign u)).\n  simp pow2.\n  destruct (Bsign u); [rewrite join_via_zero |]; lia.\nQed.\n\n\n(** *** Multiplication and addition *)\n\nLocal Proposition inj_0 : N.of_nat 0 = 0%N.\nProof. reflexivity. Qed.\n\nLocal Proposition inj_1 : N.of_nat 1 = 1%N.\nProof. reflexivity. Qed.\n\nLocal Proposition Ninj_1 : Z.of_N 1 = 1%Z.\nProof. reflexivity. Qed.\n\nHint Rewrite <- N.add_1_l Z.add_1_l : ZZ.\n\nHint Rewrite\n     inj_0 inj_1\n     Nnat.Nat2N.inj_add\n     Nnat.Nat2N.inj_mul\n\n     N2Z.inj_0 Ninj_1\n     N2Z.inj_add\n     N2Z.inj_mul\n\n     Z.add_assoc\n     Z.add_0_l Z.add_0_r\n     Z.add_opp_l Z.add_opp_r\n\n     Z.sub_0_l\n     Z.sub_opp_l Z.sub_opp_r\n     Z.sub_0_l Z.sub_0_r\n\n     Z.opp_0\n     Z.opp_involutive\n\n     Z.mul_assoc\n     Z.mul_0_l Z.mul_0_r\n     Z.mul_1_l Z.mul_1_r\n     Z.mul_opp_l Z.mul_opp_r\n\n     Z.mul_add_distr_l Z.mul_add_distr_r\n     Z.mul_sub_distr_l Z.mul_sub_distr_r\n\n     Z.double_spec\n     Z.div2_div\n\n     pow2_equation_0\n     pow2_equation_1\n     pow2_equation_2\n  : ZZ.\n\n\n(** More congruence **)\n\nProposition toBits_cong n z z' : cong n z z' <-> toBits n z = toBits n z'.\nProof.\n  unfold cong, irel.\n  rewrite toBits_congruence.\n  reflexivity.\nQed.\n\nInstance toBits_proper n : Proper (cong n ==> eq) (toBits n).\nProof.\n  intros z z' Hz.\n  apply toBits_cong.\n  exact Hz.\nQed.\n\nProposition fromBits_toBits_cong n z : cong n (fromBits (toBits n z)) z.\nProof.\n  rewrite fromBits_toBits_mod.\n  setoid_rewrite cong_mod.\n  - reflexivity.\n  - lia.\nQed.\n\nCorollary ofN_bitsToN_toBits_cong n z : cong n (Z.of_N (bitsToN (toBits n z))) z.\nProof.\n  rewrite ofN_bitsToN.\n  apply fromBits_toBits_cong.\nQed.\n\n\n(** ** Bytes *)\n\nNotation B8 := (Bits 8).\nNotation B16 := (Bits 16).\nNotation B32 := (Bits 32).\nNotation B64 := (Bits 64).\n\nDefinition Bytes n := vector B8 n.\n\n(* It seems Equations is not able to handle these definitions yet,\n   even though [dependent elimination] works as expected. *)\n\nDefinition bitsToBytes {n} (u: Bits (n * 8)) : Bytes n.\nProof.\n  induction n.\n  - exact [].\n  - simpl in u.\n    dependent elimination u as [b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: u].\n    exact ([b0; b1; b2; b3; b4; b5; b6; b7] :: IHn u).\nDefined.\n\nProposition bitsToBytes_equation_1 : @bitsToBytes (0 * 8) [] = [].\nProof. reflexivity. Qed.\n\nProposition bitsToBytes_equation_2 {n} b0 b1 b2 b3 b4 b5 b6 b7 (u: Bits (n * 8)) :\n  @bitsToBytes (S n) (b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: u) =\n  [b0; b1; b2; b3; b4; b5; b6; b7] :: bitsToBytes u.\nProof. reflexivity. Qed.\n\nHint Rewrite bitsToBytes_equation_1 @bitsToBytes_equation_2 : bitsToBytes.\n#[global] Opaque bitsToBytes.\n\nDefinition bytesToBits {n} (u: Bytes n) : Bits (n * 8).\nProof.\n  induction n.\n  - exact [].\n  - dependent elimination u as [ [b0; b1; b2; b3; b4; b5; b6; b7] :: u].\n    exact (b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: IHn u).\nDefined.\n\nProposition bytesToBits_equation_1 : bytesToBits [] = [].\nProof. reflexivity. Qed.\n\nProposition bytesToBits_equation_2 n b0 b1 b2 b3 b4 b5 b6 b7 (u: Bytes n) :\n  @bytesToBits (S n) ([b0; b1; b2; b3; b4; b5; b6; b7] :: u) =\n  b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: bytesToBits u.\nProof. reflexivity. Qed.\n\nProposition bytesToBits_equation_3 (u: Bits 8) : bytesToBits [u] = u.\nProof.\n  dependent elimination u as [b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: []].\n  reflexivity.\nQed.\n\nHint Rewrite bytesToBits_equation_1 @bytesToBits_equation_2 @bytesToBits_equation_3 : bytesToBits.\n#[global] Opaque bytesToBits.\n\nLemma bitsToBytes_bytesToBits {n} (u: Bytes n) : bitsToBytes (bytesToBits u) = u.\nProof.\n  induction n.\n  - dependent elimination u; reflexivity.\n  - dependent elimination u as [ [b0; b1; b2; b3; b4; b5; b6; b7] :: u].\n    simp bytesToBits bitsToBytes. rewrite IHn. reflexivity.\nQed.\n\nLemma bytesToBits_bitsToBytes {n} (u: Bits (n * 8)) : bytesToBits (bitsToBytes u) = u.\nProof.\n  induction n.\n  - dependent elimination u; reflexivity.\n  - dependent elimination u as [b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: u].\n    simp bitsToBytes bytesToBits. rewrite IHn. reflexivity.\nQed.\n\n(***)\n\nCorollary toBits_cong' n z : cong n (Z.of_N (bitsToN (toBits n z))) z.\nProof.\n  rewrite ofN_bitsToN, fromBits_toBits_mod.\n  apply cong_mod.\n  lia.\nQed.\n\n#[export] Hint Opaque cong : rewrite.\n\nLtac cong_tac :=\n  apply toBits_cong;\n  rewrite toBits_cong';\n  apply eq_cong;\n  lia.\n\nInstance cong_toBits_proper n : Proper (cong n ==> eq) (toBits n).\nProof. intros z z' Hz. apply toBits_cong. exact Hz. Qed.\n\nCorollary fromBits_toBits' n (u: Bits n) : toBits n (Z.of_N (bitsToN u)) = u.\nProof. rewrite ofN_bitsToN. apply toBits_fromBits. Qed.\n\n(***)\n\nCorollary bytesToBits_injective {n} {u v: Bytes n} (H: bytesToBits u = bytesToBits v) : u = v.\nProof.\n  apply (f_equal bitsToBytes) in H.\n  setoid_rewrite bitsToBytes_bytesToBits in H.\n  exact H.\nQed.\n\nCorollary bitsToN_injective {n} {u v: Bits n} (H: bitsToN u = bitsToN v) : u = v.\nProof.\n  apply (f_equal Z.of_N) in H.\n  apply (f_equal (toBits n)) in H.\n  setoid_rewrite toBits_ofN_bitsToN in H.\n  exact H.\nQed.\n\nProposition bitsToN_bound {n} (u: Bits n) : (bitsToN u < 2 ^ n)%N.\nProof.\n  assert ((2^n)%N = 2^n :> Z) as H; [ now rewrite N2Z.inj_pow | ].\n  unfold bitsToN, fromBits.\n  apply N2Z.inj_lt.\n  rewrite N2Z.inj_pow.\n  destruct (join_zero u) as [H0 H64].\n  lia.\nQed.\n\n\n(** ** Bytes to longs *)\n\n(** Cf. [bitsToBytes] *)\nDefinition bytesToLongs {n} (u: Bytes (n * 8)) : vector B64 n.\nProof.\n  induction n.\n  - exact [].\n  - simpl in u.\n    dependent elimination u as [b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: u].\n    exact ((b0 ++ b1 ++ b2 ++ b3 ++ b4 ++ b5 ++ b6 ++ b7) :: IHn u).\nDefined.\n\nProposition bytesToLongs_equation_1 : @bytesToLongs (0 * 8) [] = [].\nProof. reflexivity. Qed.\n\nProposition bytesToLongs_equation_2 {n} b0 b1 b2 b3 b4 b5 b6 b7 (u: Bytes (n * 8)) :\n  @bytesToLongs (S n) (b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: u) =\n  (b0 ++ b1 ++ b2 ++ b3 ++ b4 ++ b5 ++ b6 ++ b7) :: bytesToLongs u.\nProof. reflexivity. Qed.\n\nHint Rewrite bytesToLongs_equation_1 @bytesToLongs_equation_2 : bytesToLongs.\n#[global] Opaque bytesToLongs.\n\nProposition bytesToBits_equation_2' {n} b (u: Bytes n) :\n  @bytesToBits (S n) (b :: u) = b ++ bytesToBits u.\nProof.\n  dependent elimination b as [b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: []].\n  simp bytesToBits.\n  reflexivity.\nQed.\n\nProposition bytesToLongs_equation_2' {n} b0 b1 b2 b3 b4 b5 b6 b7 (u: Bytes (n * 8)) :\n  @bytesToLongs (S n) (b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: u) =\n  (bytesToBits ([b0; b1; b2; b3; b4; b5; b6; b7] : Bytes 8)) :: bytesToLongs u.\nProof.\n  (* TODO: Can this be done more elegantly? *)\n  simp bytesToLongs.\n  repeat rewrite bytesToBits_equation_2'.\n  repeat f_equal.\n  dependent elimination b7 as [c0 :: c1 :: c2 :: c3 :: c4 :: c5 :: c6 :: c7 :: []].\n  reflexivity.\nQed.\n", "meta": {"author": "immortalvm", "repo": "ivm-formal-proofs", "sha": "102f767333237f8a486d8b6338a7773938f46004", "save_path": "github-repos/coq/immortalvm-ivm-formal-proofs", "path": "github-repos/coq/immortalvm-ivm-formal-proofs/ivm-formal-proofs-102f767333237f8a486d8b6338a7773938f46004/Binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7210125080478856}}
{"text": "(*** Introduction to Computational Logic, Coq part of Assignment 9 ***)\n\nRequire Import Arith Lia.\n\n\n\n(*** Exercise 9.1 ***)\n\n(* The first 5 exercises are stated for the explicit definition of x <= y. *)\n\nSection LE.\n\nDefinition le (x y : nat) : Prop :=\n  exists k, x + k = y.\n\nNotation \"x <= y\" := (le x y).\nNotation \"x < y\" := (le (S x) y).\n\nDefinition dec (X : Prop) :=\n  {X} + {~ X}.\n\nLemma origin x :\n  0 <= x.\nProof.\n  now exists x.\nQed.\n\nLemma refl x :\n  x <= x.\nProof.\n  now exists 0.\nQed.\n\nLemma trans x y z :\n  x <= y -> y <= z -> x <= z.\nProof.\n  intros [k H1] [l H2].\n  exists (k + l). now rewrite plus_assoc, H1.\nQed.\n\nLemma antisym x y :\n  x <= y -> y <= x -> x = y.\nProof.\n  intros [k H1] [l H2].\n  assert (H: forall m n, m + n = m -> n = 0).\n  { intros m n. induction m as [|m IH].\n    - now cbn.\n    - cbn. intros H%Nat.succ_inj. apply IH, H.\n  }\n  rewrite <- H1 in H2. rewrite <- plus_assoc in H2. apply H, plus_is_O in H2 as [H2 _].\n  now rewrite H2, Nat.add_0_r in H1.\nQed.\n\nLemma shift x y :\n  S x <= S y <-> x <= y.\nProof.\n  split.\n  - intros [k H]. exists k. cbn. now apply Nat.succ_inj.\n  - intros [k H]. exists k. cbn. now rewrite H.\nQed.\n\nLemma strict x :\n  ~ x < x.\nProof.\n  intros [k H]. destruct k.\n  - cbn in H. rewrite Nat.add_0_r in H. now apply Nat.neq_succ_diag_l in H.\nAbort.\n\nLemma minimum x :\n  ~ x < 0.\nProof.\n  intros H. destruct H as [k H]. lia.\nQed.\n\n(*** Exercise 9.2 ***)\n\nLemma add_sub_eq x y :\n  x + y - x = y.\nProof.\n  induction x as [|x IH]; cbn.\n  - apply Nat.sub_0_r.\n  - exact IH.\nQed.\n\nLemma le_add_sub x y :\n  x <= y -> x + (y - x) = y.\nProof.\n  intros [k H].\n  Abort.\n\n\n(*** Exercise 9.3 ***)\n\nLemma linearity :\n  forall n m, n <= m \\/ m <= n.\nProof.\n  intros n m. induction n as [|n IH] in m |-*.\n  - left. apply origin.\n  - destruct m.\n    + right. now exists (S n).\n    + destruct (IH m) as [[k H1]|[l H2]].\n      * left. exists k. cbn. now rewrite H1.\n      * right. exists l. cbn. now rewrite H2.\nQed.\n\nLemma trichotomy : \n  forall n m, n < m \\/ n = m \\/ m < n.\nProof.\n  intros n m. specialize (linearity n m) as [[k H1]|[l H2]].\n  - left. exists (k - 1). rewrite <- H1.\n    Abort.\n\nLemma not_lt_le x y :\n  ~ (y < x) -> x <= y.\nProof.\n  (*...*)\nAdmitted.\n\nLemma not_lt_eq x y :\n  ~ (x < y) -> ~ (y < x) -> x = y.\nProof.\n  (*...*)\nAdmitted.\n\n\n\n(*** Exercise 9.4 ***)\n\nLemma le_iff x y :\n  x <= y <-> x - y = 0.\nProof.\n  split.\n  - intros [k <-]. lia.\n  - intros H. exists (y - x). lia.\nQed.\n\nLemma le_dec x y :\n  dec (x <= y).\nProof.\n  induction x as [|x IH] in y |-*.\n  - left. apply origin.\n  - destruct y.\n    + right. apply minimum.\n    + specialize (IH y) as [H|H].\n      * left. destruct H as [k H]. exists k. cbn. now rewrite H.\n      * right. contradict H. destruct H as [k H]. cbn in H.\n        exists k. now apply Nat.succ_inj.\nQed.\n\nLemma le_dec' x y :\n  dec (x <= y).\nProof.\n  destruct (x - y) eqn:H.\n  - left. now apply le_iff.\n  - right. intros H2. apply le_iff in H2. congruence.\nQed.\n\nFixpoint le_bool (x y : nat) : bool :=\n  match x, y with\n  | O, y => true\n  | S _, O => false\n  | S x, S y => le_bool x y\n  end.\n\nLemma le_bool_spec x y :\n  x <= y <-> le_bool x y = true.\nProof.\n  split.\n  - intros H. destruct (le_bool x y) eqn:H2.\n    + reflexivity.\n    + rewrite <- H2. destruct x, y.\n      * reflexivity.\n      * reflexivity.\n      * exfalso. now apply (minimum x).\n      * destruct H as [k H]. \n        Abort.\n\n(*** Exercise 9.5 ***)\n\nLemma nat_dec (x y : nat) :\n  dec (x = y).\nProof.\n  (*...*)\nAdmitted.\n\nEnd LE.\n\n\n\n(*** Exercise 9.6 ***)\n\n(* We now switch to the pre-defined x <= y and fully rely on lia. *)\n\nLemma size_induction X (f : X -> nat) (p : X -> Type) :\n  (forall x, (forall y, f y < f x -> p y) -> p x) -> forall x, p x.\nProof.\n  (* intros H x. specialize (H x). apply H. *)\n  (* intros y H2. induction (f x) as [|fx IH]. *)\n  (* - destruct (f y). *)\n  (*   +  *)\nAdmitted.\n\nLemma complete_induction (p : nat -> Type) :\n  (forall x, (forall y, y < x -> p y) -> p x) -> forall x, p x.\nProof.\n  apply (size_induction _ (fun x => x)).\nQed.\n\n\n(*** Exercise 9.7 ***)\n\nLemma div_mod_unique y a b a' b' :\n  b <= y -> b' <= y -> a * S y + b = a' * S y + b' -> a = a' /\\ b = b'.\nProof.\n  intros H1 H2. \n  induction a as [|a IH] in a' |-*; destruct a'; cbn.\n  - lia.\n  - lia.\n  - lia.\n  - specialize (IH a'). lia.\nQed.\n\nLemma le_lt_dec x y :\n  {x <= y} + {y < x}.\nProof.\n  induction x as [|x IH] in y |-*.\n  - left. lia.\n  - destruct y as [|y].\n    + right. lia.\n    + specialize (IH y) as [IH|IH].\n      * left. lia.\n      * right. lia.\nQed.\n\nTheorem div_mod x y :\n  { a & { b & x = a * S y + b /\\ b <= y}}.\nProof.\n  (*...*)\nAdmitted.\n\nDefinition D (x y : nat) := (*...*) 0.\nDefinition M (x y : nat) := (*...*) 0.\n\nLemma DM_spec1 x y :\n  x = D x y * S y + M x y.\nProof.\n  (*...*)\nAdmitted.\n\nLemma DM_spec2 x y :\n  M x y <= y.\nProof.\n  (*...*)\nAdmitted.\n\n\n\n(*** Exercise 9.8 ***)\n\nDefinition divides x y :=\n  x <> 0 /\\ exists k, y = k * x.\n\nLemma divides_dec x y :\n  dec (divides x y).\nProof.\n (*...*)\nAdmitted.\n\nDefinition cong x y k :=\n  (x <= y /\\ divides k (y - x)) \\/ (y < x /\\ divides k (x - y)).\n\nLemma cong_dec x y k :\n  dec (cong x y k).\nProof.\n  (*...*)\nAdmitted.\n\n\n\n(*** Exercise 9.10 ***)\n\nDefinition spec_exp mu :=\n  forall f n, (f (mu f n) = true -> mu f n <= n /\\ forall k, k < mu f n -> f k = false)\n         /\\ (f (mu f n) = false -> mu f n = n /\\ forall k, k <= n -> f k = false).\n\nDefinition wf X (R : X -> X -> Prop) :=\n  forall f, (exists x, f x = true) -> exists x, f x = true /\\ forall y, f y = true -> R x y.\n\nLemma nat_wf mu :\n  spec_exp mu -> wf nat (fun x y => x <= y).\nProof.\n  (*...*)\nAdmitted.\n\n\n\n(*** Exercise 9.11 ***)\n\nSection S1.\n  Variables (f: nat -> bool)\n            (mu: nat -> nat)\n            (R1: mu 0 = 0)\n            (R2: forall n, mu (S n) = if f (mu n) then mu n else S n).\n\n  Goal forall n, if f (mu n)\n            then mu n <= n /\\ forall k, k < mu n -> f k = false\n            else mu n = n /\\ forall k, k <= n -> f k = false.\n  Proof.\n    (*...*)\n  Admitted.\n  \n  Variables (mu': nat -> nat)\n            (R1': mu' 0 = 0)\n            (R2': forall n, mu' (S n) = if f (mu' n) then mu' n else S n).\n\n  Goal forall n, mu n = mu' n.\n  Proof.\n    (*...*)\n  Admitted.\nEnd S1.\n\nSection S2.\n  Variables (f: nat -> bool) (mu: nat -> nat).\n  Variable (R: forall n, if f (mu n)\n                    then mu n <= n /\\ forall k, k < mu n -> f k = false\n                    else mu n = n /\\ forall k, k <= n -> f k = false ).\n  \n  Goal forall n, mu n <= n.\n  Proof.\n    (*...*)\n  Admitted.\n\n  Goal forall n k, k < mu n -> f k = false.\n  Proof.\n    (*...*)\n  Admitted.\n\n  Goal forall n, mu n < n -> f (mu n) = true.\n  Proof.\n     (*...*)\n  Admitted.\nEnd S2.\n\nSection S3.\n    Variables (f: nat -> bool) (mu: nat -> nat).\n    Variables (R1: forall n, mu n <= n)\n              (R2: forall n k, k < mu n -> f k = false)\n              (R3: forall n, mu n < n -> f (mu n) = true).\n\n    Goal mu 0 = 0.\n    Proof.\n      (*...*)\n    Admitted.\n\n    Goal forall n, mu (S n) = if f (mu n) then mu n else S n.\n    Proof.\n      (*...*)\n    Admitted.\nEnd S3.\n\n\n\n(*** Exercise 9.12 ***)\n  \nSection Challenge.\n\n  Variable D M : nat -> nat -> nat.\n  Hypothesis DM1 : forall x y, x = D x y * S y + M x y.\n  Hypothesis DM2 : forall x y, M x y <= y.\n\n  Goal forall x y, y < x -> D x y = S (D (x - S y) y).\n  Proof.\n    (*...*)\n  Admitted.\n\n  Goal forall x y, x <= y -> D x y = 0.\n  Proof.\n    (*...*)\n  Admitted.\n\nEnd Challenge.\n", "meta": {"author": "archbung", "repo": "icl-ss19", "sha": "fa2ba5d7d4d9ac61c9488c5f58b5233720e5914e", "save_path": "github-repos/coq/archbung-icl-ss19", "path": "github-repos/coq/archbung-icl-ss19/icl-ss19-fa2ba5d7d4d9ac61c9488c5f58b5233720e5914e/assignment/9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.7210125019901911}}
{"text": "(************************************************************************)\n(* Copyright 2006 Milad Niqui                                           *)\n(* This file is distributed under the terms of the                      *)\n(* GNU Lesser General Public License Version 2.1                        *)\n(* A copy of the license can be found at                                *)\n(*                  <http://www.gnu.org/licenses>                       *)\n(************************************************************************)\n\nRequire Import digits.\n\n\nClose Scope Z_scope.\n\n(** We define a function [lb] that returns the #<em>#upper bound#</em># of the\ninterval obtained by applying the initial segment of length [n] of\n[alpha] to the base interval #&#91;#-1,+1#&#93;#.*)\n\nFixpoint lb (alpha:Reals) (n:nat) {struct n} : Q :=\n  match n with\n  |   O => (Qopp 1) (* this is because of base interval, and that d(-1)=-1 *)\n  | S p => let (d,alpha'):= alpha in let q := lb alpha' p in\n           as_Moebius_Q d q\n  end.\n\nLemma lb_S_n:forall n alpha, lb alpha (S n) = as_Moebius_Q (hd alpha) (lb (tl alpha) n).\nProof.\n intros n [d alpha']; trivial.\nDefined.\n\nLemma lb_is_in_base_interval:forall k alpha,  - Qone <= lb alpha k /\\ lb alpha k <= Qone.\nProof.\n intro k; induction k; intro alpha.\n (* 0 *)\n split; unfold lb; natq_one; try rewrite <- Z_to_Qopp; apply Z_to_Qle; auto with zarith.\n (* S k *)\n destruct alpha as [[ | | ] alpha']; generalize (IHk alpha'); clear IHk;\n rewrite lb_S_n; unfold hd, tl; set (l':=lb alpha' k); intros [IHk_1 IHk_2].\n\n\n  (* L *)\n  (* TP: Zero <= l'+ 1 *)\n  assert (H_l'_one_nonneg: Zero <= l'+1).\n  stepr (l'-(Qopp 1)); try ring; apply Qle_Qminus_Zero; auto. \n  (* TP: Zero < l'+3 *)\n  assert (H_l'_three_pos: Zero < l'+3).\n  apply Qle_lt_trans with (l'+1); auto;\n  apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n  (* TP: Zero <= 2*l'+ 2 *)\n  assert (H_2l'_two_nonneg: Zero <= 2*l'+2).\n  stepr (2*(l'+1)); [|qZ_numerals; ring]; apply Qle_mult_nonneg_nonneg; auto.\n  (* TP: Zero <= l'+ 2 *)\n  assert (H_l'_two_nonneg: Zero <= l'+2).\n  apply Qle_trans with (l'+1); auto;\n  apply Qle_plus_plus; try apply Qle_reflexive; apply Z_to_Qle; apply inj_le; auto.\n\n  rewrite as_Moebius_Q_L; trivial; natZ_numerals.\n\n  split; apply Qmult_resp_Qle_pos_r with (l'+3); auto.\n   stepr (l'-1).\n    apply Qle_Zero_Qminus;\n    stepr (2*l'+2); auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n    generalize (l'-1) (l'+3) H_l'_three_pos; intros; field; auto.\n  \n   stepl (l'-1).\n    apply Qle_Zero_Qminus;\n    stepr 4; auto; qnat_S 3; qnat_S 2; qnat_S 1; qnat_one; ring.\n    generalize (l'-1) (l'+3) H_l'_three_pos; intros; field; auto.\n  \n  (* R *)\n  (* TP: Zero <= -l'+ 1 *)\n  assert (H_min_l'_one_nonneg: Zero <= -l'+1).\n  stepr (1-l'); try ring; apply Qle_Qminus_Zero; auto. \n  (* TP: Zero < -l'+3 *)\n  assert (H_min_l'_three_pos: Zero < -l'+3).\n  apply Qle_lt_trans with ((-l')+1); auto.\n  apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n  (* TP: Zero <= 2*(-l')+ 2 *)\n  assert (H_2_min_l'_two_nonneg: Zero <= 2*(-l')+2).\n  stepr (2*(-l'+1)); [|qZ_numerals; ring]; apply Qle_mult_nonneg_nonneg; auto.\n\n  rewrite as_Moebius_Q_R; trivial; natZ_numerals.\n  \n  split; apply Qmult_resp_Qle_pos_r with (-l'+3); auto.\n   stepr (l'+1).\n    apply Qle_Zero_Qminus;\n    stepr 4; auto; qnat_S 3; qnat_S 2; qnat_S 1; qnat_one; ring.\n    generalize (l'+1) (-l'+3) H_min_l'_three_pos; intros; field; auto.\n\n   stepl (l'+1).\n    apply Qle_Zero_Qminus;\n    stepr (2*(-l')+2); auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n    generalize (l'+1) (-l'+3) H_min_l'_three_pos; intros; field; auto.\n\n  (* M *)\n  rewrite as_Moebius_Q_M; natZ_numerals.\n\n  split; apply Qmult_resp_Qle_pos_r with 3; auto;\n  [ stepr l' | stepl l'].\n  apply Qle_trans with (-Qone); auto; apply Qlt_le_weak; apply Qlt_Zero_Qminus; stepr 2; auto.  \n  generalize l'; intro; field; auto.\n  apply Qle_trans with Qone; auto; apply Qlt_le_weak; apply Qlt_Zero_Qminus; stepr 2; auto.  \n  generalize l'; intro; field; auto.\nDefined.\n\n\nLemma lb_is_in_base_interval_low:forall k alpha, - Qone <= lb alpha k.\nProof.\n intros k alpha; elim (lb_is_in_base_interval k alpha); trivial.\nDefined.\n\nLemma lb_is_in_base_interval_up:forall k alpha, lb alpha k <= Qone.\nProof.\n intros k alpha; elim (lb_is_in_base_interval k alpha); trivial.\nDefined.\n\n(** This is similar to Lemma 5.7.2.i in the thesis. *)\nLemma thesis_5_7_2i_l:forall (k:nat) alpha, ~(lb alpha k = Qopp 1) -> (-k)/(k+2) <= lb alpha k.\nProof.\n intro k; induction k; intros alpha H_nonzero.\n\n  (* 0 *)\n  apply False_ind; apply H_nonzero; trivial.\n  (* S k *)\n  rewrite lb_S_n;\n  rewrite lb_S_n in H_nonzero.\n  (* TP: Zero < k + Qone *) \n  assert (H_k_one_pos: Zero < k + Qone ).\n  natq_S k; natq_zero; apply Z_to_Qlt; apply inj_lt; apply lt_O_Sn.\n  (* TP: Zero < k + 2 *) \n  assert (H_k_two_pos: Zero < k + 2 ).\n  stepr ((k+Qone)+Qone);\n  [ natq_S k; natq_S (S k); natq_zero; auto\n  | qnat_S 1; qnat_one; ring].\n  (* TP: O <= k  *) \n  assert (H_k_nonneg:  0 <= k).\n  apply Z_to_Qle; apply inj_le; auto with arith.\n  (* TP: Qone <= 2 * k + 3*)\n  assert (H_2k_3_nonneg:  Qone <= 2 * k + 3).\n  apply Qle_Zero_Qminus; stepr (2*(k+1));\n  [ apply Qle_mult_nonneg_nonneg; auto\n  | qnat_S 2; qnat_S 1; qnat_one; ring\n  ].\n\n  destruct alpha as [[ | | ] alpha']; unfold hd,tl; unfold hd,tl in H_nonzero; qnat_one; qnat_S k; set (l':=lb alpha' k).\n   (* L *)\n   fold l' in H_nonzero.\n   case (Q_eq_dec l' (Qopp 1)); intro H_l'.\n    (* l' = -1 *)\n    apply False_ind; apply H_nonzero; rewrite H_l'; rewrite as_Moebius_Q_L; qZ_numerals; auto.\n    (* l' <> -1 *)\n    generalize (IHk alpha' H_l'); fold l'; clear IHk; intro IHk.\n    (* TP: Zero <= l'+ 1 *)\n    assert (H_l'_one_nonneg: Zero <= l'+1).\n    stepr (l'-(Qopp 1)); try ring; apply Qle_Qminus_Zero;  unfold l'; apply lb_is_in_base_interval_low. \n    (* TP: Zero < l'+3 *)\n    assert (H_l'_three_pos: Zero < l'+3).\n    apply Qle_lt_trans with (l'+1); auto;\n    apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n \n    generalize H_nonzero; clear H_nonzero; rewrite as_Moebius_Q_L; trivial; natZ_numerals; intros H_nonzero.\n\n    apply Qmult_Qdiv_pos_Qle; auto;\n    apply Qle_Zero_Qminus;\n    stepr (2*(l'*(k+2)-(-k))).\n     apply Qle_mult_nonneg_nonneg; auto;\n     apply Qle_Qminus_Zero;\n     apply Qmult_resp_Qle_pos_r with (Qinv (k+2)).\n      apply Qinv_pos; auto.\n      rewrite <- Qmult_assoc; rewrite Qmult_Qinv_r; auto.\n      stepr l'; trivial; try ring.\n\n     qnat_S 2; qnat_S 1; qnat_one; ring.\n\n   (* R *)\n    (* TP: Zero <= -l'+ 1 *)\n    assert (H_min_l'_one_nonneg: Zero <= -l'+1).\n    stepr (1-l'); try ring; apply Qle_Qminus_Zero; subst l'; apply lb_is_in_base_interval_up.\n    (* TP: Zero < -l'+3 *)\n    assert (H_min_l'_three_pos: Zero < -l'+3).\n    apply Qle_lt_trans with ((-l')+1); auto;\n    apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n    (* TP: Zero <= l'+ 1 *)\n    assert (H_l'_one_nonneg: Zero <= l'+1).\n    stepr (l'-(Qopp 1)); try ring; apply Qle_Qminus_Zero; subst l'; apply lb_is_in_base_interval_low. \n    (* TP: Zero <= l'+3 *)\n    assert (H_l'_three_pos: Zero <= l'+3).\n    apply Qlt_le_weak; apply Qle_lt_trans with (l'+1); auto;\n    apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n\n    rewrite as_Moebius_Q_R; trivial; natZ_numerals.\n\n \n    apply Qmult_Qdiv_pos_Qle; auto;\n    apply Qle_Zero_Qminus;\n    stepr (2*((l'+3)+2*k)).\n     apply Qle_mult_nonneg_nonneg; auto.\n\n     qnat_S 2; qnat_S 1; qnat_one; ring.\n\n   (* M *)\n   rewrite as_Moebius_Q_M; natZ_numerals;\n    (* TP: Zero <= l'+ 1 *)\n    assert (H_l'_one_nonneg: Zero <= l'+1).\n    stepr (l'-(Qopp 1)); try ring; apply Qle_Qminus_Zero; subst l'; apply lb_is_in_base_interval_low. \n   \n   apply Qle_trans with ((-Qone)/3).\n    apply Qmult_Qdiv_pos_Qle; auto;\n    apply Qle_Zero_Qminus;\n    stepr (2*k); auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n\n    apply Qmult_Qdiv_pos_Qle; auto;\n    apply Qle_Zero_Qminus;\n    stepr (3*(l'+1)).\n     apply Qle_mult_nonneg_nonneg; auto.\n     qnat_S 2; qnat_S 1; qnat_one; ring.\nDefined.\n\n\nLemma thesis_5_7_2ii_l:forall (k:nat) alpha, lb alpha k <= (k-1)/(k+1).\nProof.\n intro k; induction k; intros alpha.\n  (* 0 *)\n  simpl; apply Qle_reflexive.\n  (* S k *)\n  (* TP: O <= k  *) \n  assert (H_k_nonneg:  0 <= k).\n  apply Z_to_Qle; apply inj_le; auto with arith.\n  (* TP: Zero < 1 + k *) \n  assert (H_k_one_pos: Zero < 1 + k ).\n  rewrite Qplus_sym; natq_zero; qnat_one; natq_S k; natq_S (S k); auto.\n  (* TP: Zero < k + 2 *) \n  assert (H_k_two_pos: Zero < k + 2 ).\n  natq_zero; qnat_S 1; qnat_one; rewrite Qplus_assoc; natq_S k; natq_S (S k); auto.\n\n  rewrite lb_S_n;\n  destruct alpha as [d alpha'];\n  destruct d; unfold hd,tl;\n  generalize (IHk alpha'); clear IHk; intros IHk;\n  qnat_one; qnat_S k; set (l':=lb alpha' k);\n  fold l' in IHk.\n   (* L *)\n   (* TP: Zero <= -l'+ 1 *)\n   assert (H_min_l'_one_nonneg: Zero <= -l'+1).\n   stepr (1-l'); try ring; apply Qle_Qminus_Zero; unfold l'; apply lb_is_in_base_interval_up.\n   (* TP: Zero <= l'+ 1 *)\n   assert (H_l'_one_nonneg: Zero <= l'+1).\n   stepr (l'-(Qopp 1)); try ring; apply Qle_Qminus_Zero; unfold l'; apply lb_is_in_base_interval_low. \n   (* TP: Zero < l'+3 *)\n   assert (H_l'_three_pos: Zero < l'+3).\n   apply Qle_lt_trans with (l'+1); auto;\n   apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n   \n   rewrite as_Moebius_Q_L; trivial; natZ_numerals.\n\n   apply Qmult_Qdiv_pos_Qle; auto;\n   apply Qle_Zero_Qminus;\n   stepr (2*((-l'+1)+2*k)).\n    apply Qle_mult_nonneg_nonneg; auto;\n    apply Qle_plus_pos_pos; auto.  \n\n    qnat_S 2; qnat_S 1; qnat_one; ring.\n\n   (* R *)\n   (* TP: Zero <= -l'+ 1 *)\n   assert (H_min_l'_one_nonneg: Zero <= -l'+1).\n   stepr (1-l'); try ring; apply Qle_Qminus_Zero; unfold l'; apply lb_is_in_base_interval_up.\n   (* TP: Zero < -l'+3 *)\n   assert (H_min_l'_three_pos: Zero < -l'+3).\n   apply Qle_lt_trans with ((-l')+1); auto;\n   apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n   (* TP: Zero <= l'+ 1 *)\n   assert (H_l'_one_nonneg: Zero <= l'+1).\n   stepr (l'-(Qopp 1)); try ring; apply Qle_Qminus_Zero; unfold l'; apply lb_is_in_base_interval_low. \n\n   rewrite as_Moebius_Q_R; trivial; natZ_numerals.\n\n   apply Qmult_Qdiv_pos_Qle; auto;\n   apply Qle_Zero_Qminus;\n   stepr (2*((k-1)-l'*(k+1))).\n    apply Qle_mult_nonneg_nonneg; auto;\n    apply Qle_Qminus_Zero;\n    apply Qmult_resp_Qle_pos_r with (Qinv (k+1)).\n      apply Qinv_pos; auto.\n      rewrite <- Qmult_assoc; rewrite Qmult_Qinv_r; auto;\n      stepl l'; trivial; try ring.\n\n    qnat_S k; qnat_S 2; qnat_S 1; qnat_one; ring.\n\n   (* M *)\n   generalize IHk; clear IHk; subst l'.\n      destruct k; rewrite as_Moebius_Q_M; natZ_numerals; intro IHk.\n   (* k := 0 *)\n   unfold lb; stepr Zero; auto.\n   (* k := S k *)\n   set (l':=lb alpha' (S k));\n   fold l' in IHk.\n   (* TP: O <= k  *) \n   assert (H_pk_nonneg:  0 <= k).\n   apply Z_to_Qle; apply inj_le; auto with arith.\n   (* TP: Zero <= -l'+ 1 *)\n   assert (H_min_l'_one_nonneg: Zero <= -l'+1).\n   stepr (1-l'); try ring; apply Qle_Qminus_Zero; unfold l'; apply lb_is_in_base_interval_up.\n   (* TP: Zero < -l'+3 *)\n   assert (H_min_l'_three_pos: Zero <= -l'+3).\n   apply Qle_trans with (-l'+1); auto;\n   apply Qle_plus_plus; try apply Qle_reflexive; apply Z_to_Qle; apply inj_le; auto.\n\n   apply Qmult_Qdiv_pos_Qle; auto;\n   apply Qle_Zero_Qminus.\n   stepr (k*(-l'+3)+3*(-l'+1)).\n    apply Qle_plus_pos_pos; apply Qle_mult_nonneg_nonneg; auto.\n       \n    qnat_S (S k); qnat_S k; qnat_S 2; qnat_S 1; qnat_one;\n    [ ring | natq_S k; natq_S (S k); auto].\nDefined.\n\n\nLemma lb_nondecreasing_step:forall k alpha, lb alpha k <= lb alpha (S k).\nProof.\n intro k; induction k.\n (* 0 *)\n intro alpha; stepl (Qopp 1); trivial; apply lb_is_in_base_interval_low.\n (* S n *)\n intros [d alpha'];\n rewrite lb_S_n;\n rewrite (lb_S_n (S k) (Cons d alpha')); unfold hd, tl.\n destruct d as [ | | ]; set (l':=lb alpha' (S k)); set (l'':=lb alpha' k); \n generalize (IHk alpha'); clear IHk; intros IHk; fold l' l'' in IHk.\n\n  (* L *)\n  (* TP: Zero <= l'+ 1 *)\n  assert (H_l'_one_nonneg: Zero <= l'+1).\n  stepr (l'-(Qopp 1)); try ring; apply Qle_Qminus_Zero; subst l'; apply lb_is_in_base_interval_low. \n  (* TP: Zero < l'+3 *)\n  assert (H_l'_three_pos: Zero < l'+3).\n  apply Qle_lt_trans with (l'+1); auto;\n  apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n  (* TP: Zero <= l''+ 1 *)\n  assert (H_l''_one_nonneg: Zero <= l''+1).\n  stepr (l''-(Qopp 1)); try ring; apply Qle_Qminus_Zero; subst l''; apply lb_is_in_base_interval_low. \n  (* TP: Zero < l''+3 *)\n  assert (H_l''_three_pos: Zero < l''+3).\n  apply Qle_lt_trans with (l''+1); auto;\n  apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n\n  repeat rewrite as_Moebius_Q_L; trivial; natZ_numerals.\n  (* NB: conjug_Q_L is nondecreasing for -3<= x*)\n  apply Qmult_Qdiv_pos_Qle; auto.\n  apply Qle_Zero_Qminus.\n  stepr (4*(l'-l'')).\n   apply Qle_mult_nonneg_nonneg; auto.\n   apply Qle_Qminus_Zero; assumption.\n   qnat_S 3; qnat_S 2; qnat_S 1; qnat_one; ring.\n\n  (* R *)\n  (* TP: Zero <= -l'+ 1 *)\n  assert (H_min_l'_one_nonneg: Zero <= -l'+1).\n  stepr (1-l'); try ring; apply Qle_Qminus_Zero; subst l'; apply lb_is_in_base_interval_up.\n  (* TP: Zero < -l'+3 *)\n  assert (H_min_l'_three_pos: Zero < -l'+3).\n  apply Qle_lt_trans with ((-l')+1); auto;\n  apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n  (* TP: Zero <= -l'''+ 1 *)\n  assert (H_min_l''_one_nonneg: Zero <= -l''+1).\n  stepr (1-l''); try ring; apply Qle_Qminus_Zero; subst l''; apply lb_is_in_base_interval_up.\n  (* TP: Zero < -l''+3 *)\n  assert (H_min_l''_three_pos: Zero < -l''+3).\n  apply Qle_lt_trans with ((-l'')+1); auto;\n  apply Qlt_Zero_Qminus; stepr 2; auto; qnat_S 2; qnat_S 1; qnat_one; ring.\n\n  repeat rewrite as_Moebius_Q_R; trivial; natZ_numerals.\n  (* NB: conjug_Q_R is nondecreasing for x<=3*)\n  apply Qmult_Qdiv_pos_Qle; auto.\n  apply Qle_Zero_Qminus.\n  stepr (4*(l'-l'')).\n   apply Qle_mult_nonneg_nonneg; auto.\n   apply Qle_Qminus_Zero; assumption.\n   qnat_S 3; qnat_S 2; qnat_S 1; qnat_one; ring.\n\n  (* M *)\n  do 2 rewrite as_Moebius_Q_M; natZ_numerals.\n  (* NB: conjug_Q_M is nondecreasing*)\n  apply Qmult_Qdiv_pos_Qle; auto.\n  apply Qle_Zero_Qminus.\n  stepr (3*(l'-l'')).\n   apply Qle_mult_nonneg_nonneg; auto.\n   apply Qle_Qminus_Zero; assumption.\n   qnat_S 2; qnat_S 1; qnat_one; ring.\nDefined.\n\n\nLemma lb_nondecreasing_steps:forall n k alpha, lb alpha n <= lb alpha (k+n).\nProof.\n intros [|n] k. \n  (* n:=0 *)\n  intros; replace (k+0)%nat with k; trivial; apply lb_is_in_base_interval_low.\n  (* n:=S n*)\n  induction k.\n   (* k:=0 *)\n   intro alpha; apply Qle_reflexive. \n   (* k:=S k *)\n   replace (S k +S n)%nat with (S (k+S n))%nat; trivial;\n   intros [d alpha'];\n   rewrite (lb_S_n n (Cons d alpha')); rewrite lb_S_n;  unfold hd, tl.\n   destruct d.\n    apply as_Moebius_Q_L_nondecreasing;\n    [ apply lb_is_in_base_interval_low\n    | apply lb_is_in_base_interval_up\n    | apply Qle_trans with (lb alpha' (S n)); trivial; apply lb_nondecreasing_step].\n    apply as_Moebius_Q_R_nondecreasing;\n    [ apply lb_is_in_base_interval_low\n    | apply lb_is_in_base_interval_up\n    | apply Qle_trans with (lb alpha' (S n)); trivial; apply lb_nondecreasing_step].\n    apply as_Moebius_Q_M_nondecreasing;\n    [ apply lb_is_in_base_interval_low\n    | apply lb_is_in_base_interval_up\n    | apply Qle_trans with (lb alpha' (S n)); trivial; apply lb_nondecreasing_step].\nDefined.\n\nLemma lb_nondecreasing:forall m n alpha, (m<=n)%nat -> lb alpha m <= lb alpha n.\nProof.\n intros m n alpha Hmn.\n replace n with ((n-m)+m)%nat; try omega; apply lb_nondecreasing_steps.\nDefined.\n", "meta": {"author": "coq-contribs", "repo": "coinductive-reals", "sha": "e1b67f1c3a4d23b2819e9977492728d3743abeec", "save_path": "github-repos/coq/coq-contribs-coinductive-reals", "path": "github-repos/coq/coq-contribs-coinductive-reals/coinductive-reals-e1b67f1c3a4d23b2819e9977492728d3743abeec/lb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7210053422448122}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (z : natural) : natural :=\n  plus Zero (plus lf3 z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj146_coqofml_7SzXyD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7210053293895815}}
{"text": "Require Import Peano_dec.\n\nRequire Import Logic.Class.Eq.\n\nLemma not_eq_s_n : forall (n:nat), ~ S n = n.\nProof.\n    induction n as [|n IH]; intros H.\n    - inversion H.\n    - injection H. intros H'. apply IH. assumption.\nDefined.\n\n(* TODO: issue already has an Eq instance from Ord                              *)\nInstance EqNat : Eq nat := { eqDec := eq_nat_dec }.\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/Logic/Nat/Eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7210053228783445}}
{"text": "Require Import ssreflect ssrbool ssrfun ssrnat eqtype seq fintype finfun fingraph  finset.\nRequire Import automata regexp misc.\n\nSet Implicit Arguments.\n\nSection RE_FA.\n  Variable char: finType.\n  Definition word:= misc.word char.\n\n  Fixpoint re_to_dfa (r: regular_expression char): dfa char :=\n    match r with\n    | Void => dfa_void char\n    | Eps => dfa_eps char\n    | Dot => dfa_dot char\n    | Atom a => dfa_char char a\n    | Star s => nfa_star (dfa_to_nfa (re_to_dfa s))\n    | Plus s t => dfa_disj (re_to_dfa s) (re_to_dfa t)\n    | And s t => dfa_conj (re_to_dfa s) (re_to_dfa t)\n    | Conc s t => nfa_to_dfa (nfa_conc (dfa_to_nfa (re_to_dfa s)) (dfa_to_nfa (re_to_dfa t)))\n    | Not s => dfa_compl (re_to_dfa s)\n    end.\n\n  Lemma re_to_dfa_correct r: dfa_lang (re_to_dfa r) =i r.\n  Proof.\n    elim: r => [].\n\n    move => w. apply/idP/idP. exact: dfa_void_correct.\n\n    exact: dfa_eps_correct.\n    \n    move => w.\n    rewrite -topredE /= /dot.\n    exact: dfa_dot_correct.\n\n    move => a. \n    move => w. exact: dfa_char_correct.\n\n    (* Star *)\n    move => s IHs.\n    move => w.\n    rewrite nfa_star_correct.\n    apply/starP/starP.\n      move => [] vv.\n      move => H0 H1.\n      exists vv.\n      erewrite (eq_all).\n          eexact H0.\n        move => x /=.\n        apply/andP/andP; move => [] H2 H3; split => //.\n          rewrite -dfa_to_nfa_correct.\n          move: H3. by rewrite -IHs.\n        move: H3. \n        rewrite -dfa_to_nfa_correct.\n        by rewrite -IHs.\n      exact H1.\n    move => [] vv H1 H2. exists vv => //.\n    erewrite eq_all. eexact H1.\n    move => x /=.\n    apply/andb_id2l => H3.\n    by rewrite -IHs -dfa_to_nfa_correct.\n     \n        \n    move => s Hs t Ht.\n    move => w. rewrite -dfa_disj_correct in_simpl /=.\n    by rewrite Ht Hs /=.\n\n    move => s Hs t Ht.\n    move => w. rewrite -dfa_conj_correct in_simpl /=.\n    by rewrite Hs Ht /=.\n\n    move => s Hs t Ht.\n    move => w. rewrite -nfa_to_dfa_correct. \n    apply/idP/idP.\n    move/nfa_conc_aux1 => [] w1 [] w2 /andP [] /andP [] /eqP H0 H1 H2.\n    rewrite -topredE /=.\n    apply/concP.\n    exists w1. by rewrite -Hs -topredE /= dfa_to_nfa_correct' /nfa_lang /= H1.\n    exists w2. rewrite /= in H2. by rewrite -Ht dfa_to_nfa_correct in_simpl H2.\n    exact H0.\n    move/concP => [] w1. rewrite -Hs => H1 [] w2. rewrite -Ht => H2 ->.\n    apply/nfa_conc_aux2.\n      move: H1. by rewrite  dfa_to_nfa_correct /nfa_lang /=.\n    move: H2. by rewrite dfa_to_nfa_correct /nfa_lang /=.\n                 \n    move => s H.\n    move => w. by rewrite -dfa_compl_correct -topredE /= H.\n  Qed.\n\n  Definition re_equiv r s := dfa_equiv (re_to_dfa r) (re_to_dfa s).\n  \n  Lemma re_equiv_correct r s: re_equiv r s <-> r =i s.\n  Proof.\n    rewrite dfa_equiv_correct.\n    split => H w. \n      move/H: (w). by rewrite !re_to_dfa_correct.\n    by rewrite !re_to_dfa_correct.\n  Qed.\n\nEnd RE_FA.\n\n", "meta": {"author": "Janno", "repo": "Bachelor-Thesis", "sha": "3ba23a0803ffa6d2cb69dcd10ec3533e367d9294", "save_path": "github-repos/coq/Janno-Bachelor-Thesis", "path": "github-repos/coq/Janno-Bachelor-Thesis/Bachelor-Thesis-3ba23a0803ffa6d2cb69dcd10ec3533e367d9294/src/re_fa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7209975027701454}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural := mult lf2 lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj15_coqofml_xw8I7n.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7209974963557481}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  mult y x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj264_coqofml_ukSmNG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7209974945485857}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint half (half_arg0 : Nat) : Nat\n           := match half_arg0 with\n              | zero => zero\n              | succ zero => zero\n              | succ (succ n) => succ (half n)\n              end.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : Lst) : Nat\n           := match len_arg0 with\n              | nil => zero\n              | cons x y => succ (len y)\n              end.\n\nLemma lem3: forall l, append l nil = l.\nProof.\ninduction l.\n  - simpl. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem2: forall l1 l2 n, succ (len (append l1 l2)) = len (append l1 (cons n l2)).\nProof.\ninduction l1.\n- intros. simpl. rewrite <- IHl1. reflexivity.\n- intros. reflexivity.\nQed.\n\nLemma lem: forall l1 l2, len (append l1 l2) = len (append l2 l1).\ninduction l1.\n  - intros. simpl. rewrite IHl1. rewrite <- lem2. reflexivity.\n  - intros. simpl. rewrite lem3. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (half (len (append x y))) (half (len (append y x))).\nProof.\nintros. f_equal. apply lem.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal23.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7209974920193065}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) : natural := plus z (mult y z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj286_coqofml_btoIIW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7209974898510858}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural := plus lf1 (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj231_coqofml_SP8Tvd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7209974815392618}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus y (Succ (plus lf1 x)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj201_coqofml_nrfrQC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7208790083682753}}
{"text": "(* Exercise 3.2: Using the basic tactics 'assumption', 'intros', and 'apply',\n * prove the following lemmas:\n *)\n\nVariables P Q R T : Prop.\n\nLemma id_P : P -> P.\nProof.\n  intros p.\n  assumption.\nQed.\n\nLemma id_PP : (P -> P) -> (P -> P).\nProof.\n  intros H p.\n  apply H.\n  assumption.\nQed.\n\nLemma imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros H H' p.\n  apply H'.\n  apply H.\n  assumption.\nQed.\n\nLemma imp_perm : (P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros H q p.\n  apply H.\n  apply p.\n  apply q.\nQed.\n\nLemma ignore_Q : (P -> R) -> P -> Q -> R.\nProof.\n  intros H p q.\n  apply H.\n  apply p.\nQed.\n\nLemma delta_imp : (P -> P -> Q) -> P -> Q.\nProof.\n  intros H p.\n  apply H.\n  apply p.\n  apply p.\nQed.\n\nLemma delta_impR : (P -> Q) -> (P -> P -> Q).\nProof.\n  intros H p.\n  apply H.\nQed.\n\nLemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> T) -> P -> T.\nProof.\n  intros H H' H'' p.\n  apply H''.\n  apply H.\n  apply p.\n  apply H'.\n  apply p.\nQed.\n\nLemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\nProof.\n  intros H.\n  apply H.\n  intros H'.\n  apply H'.\n  intros H''.\n  apply H.\n  intros H'''.\n  apply H''.\nQed.", "meta": {"author": "dogonthehorizon", "repo": "coq_practice", "sha": "df0b3b0ddb6475a01ad227fbffad7db09e0fda4f", "save_path": "github-repos/coq/dogonthehorizon-coq_practice", "path": "github-repos/coq/dogonthehorizon-coq_practice/coq_practice-df0b3b0ddb6475a01ad227fbffad7db09e0fda4f/coqart/ch3/ex_3_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.720871195736236}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(*i $Id: Znumtheory.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\nRequire Import ZArith_base.\nRequire Import ZArithRing.\nRequire Import Zcomplements.\nRequire Import Zdiv.\nRequire Import Wf_nat.\nOpen Local Scope Z_scope.\n\n(** This file contains some notions of number theory upon Z numbers:\n     - a divisibility predicate [Zdivide]\n     - a gcd predicate [gcd]\n     - Euclid algorithm [euclid]\n     - a relatively prime predicate [rel_prime]\n     - a prime predicate [prime]\n     - an efficient [Zgcd] function\n*)\n\n(** * Divisibility *)\n\nInductive Zdivide (a b:Z) : Prop :=\n    Zdivide_intro : forall q:Z, b = q * a -> Zdivide a b.\n\n(** Syntax for divisibility *)\n\nNotation \"( a | b )\" := (Zdivide a b) (at level 0) : Z_scope.\n\n(** Results concerning divisibility*)\n\nLemma Zdivide_refl : forall a:Z, (a | a).\nProof.\n  intros; apply Zdivide_intro with 1; ring.\nQed.\n\nLemma Zone_divide : forall a:Z, (1 | a).\nProof.\n  intros; apply Zdivide_intro with a; ring.\nQed.\n\nLemma Zdivide_0 : forall a:Z, (a | 0).\nProof.\n  intros; apply Zdivide_intro with 0; ring.\nQed.\n\nHint Resolve Zdivide_refl Zone_divide Zdivide_0: zarith.\n\nLemma Zmult_divide_compat_l : forall a b c:Z, (a | b) -> (c * a | c * b).\nProof.\n  simple induction 1; intros; apply Zdivide_intro with q.\n  rewrite H0; ring.\nQed.\n\nLemma Zmult_divide_compat_r : forall a b c:Z, (a | b) -> (a * c | b * c).\nProof.\n  intros a b c; rewrite (Zmult_comm a c); rewrite (Zmult_comm b c).\n  apply Zmult_divide_compat_l; trivial.\nQed.\n\nHint Resolve Zmult_divide_compat_l Zmult_divide_compat_r: zarith.\n\nLemma Zdivide_plus_r : forall a b c:Z, (a | b) -> (a | c) -> (a | b + c).\nProof.\n  simple induction 1; intros q Hq; simple induction 1; intros q' Hq'.\n  apply Zdivide_intro with (q + q').\n  rewrite Hq; rewrite Hq'; ring.\nQed.\n\nLemma Zdivide_opp_r : forall a b:Z, (a | b) -> (a | - b).\nProof.\n  simple induction 1; intros; apply Zdivide_intro with (- q).\n  rewrite H0; ring.\nQed.\n\nLemma Zdivide_opp_r_rev : forall a b:Z, (a | - b) -> (a | b).\nProof.\n  intros; replace b with (- - b). apply Zdivide_opp_r; trivial. ring.\nQed.\n\nLemma Zdivide_opp_l : forall a b:Z, (a | b) -> (- a | b).\nProof.\n  simple induction 1; intros; apply Zdivide_intro with (- q).\n  rewrite H0; ring.\nQed.\n\nLemma Zdivide_opp_l_rev : forall a b:Z, (- a | b) -> (a | b).\nProof.\n  intros; replace a with (- - a). apply Zdivide_opp_l; trivial. ring.\nQed.\n\nLemma Zdivide_minus_l : forall a b c:Z, (a | b) -> (a | c) -> (a | b - c).\nProof.\n  simple induction 1; intros q Hq; simple induction 1; intros q' Hq'.\n  apply Zdivide_intro with (q - q').\n  rewrite Hq; rewrite Hq'; ring.\nQed.\n\nLemma Zdivide_mult_l : forall a b c:Z, (a | b) -> (a | b * c).\nProof.\n  simple induction 1; intros q Hq; apply Zdivide_intro with (q * c).\n  rewrite Hq; ring.\nQed.\n\nLemma Zdivide_mult_r : forall a b c:Z, (a | c) -> (a | b * c).\nProof.\n  simple induction 1; intros q Hq; apply Zdivide_intro with (q * b).\n  rewrite Hq; ring.\nQed.\n\nLemma Zdivide_factor_r : forall a b:Z, (a | a * b).\nProof.\n  intros; apply Zdivide_intro with b; ring.\nQed.\n\nLemma Zdivide_factor_l : forall a b:Z, (a | b * a).\nProof.\n  intros; apply Zdivide_intro with b; ring.\nQed.\n\nHint Resolve Zdivide_plus_r Zdivide_opp_r Zdivide_opp_r_rev Zdivide_opp_l\n  Zdivide_opp_l_rev Zdivide_minus_l Zdivide_mult_l Zdivide_mult_r\n  Zdivide_factor_r Zdivide_factor_l: zarith.\n\n(** Auxiliary result. *)\n\nLemma Zmult_one : forall x y:Z, x >= 0 -> x * y = 1 -> x = 1.\nProof.\n  intros x y H H0; destruct (Zmult_1_inversion_l _ _ H0) as [Hpos| Hneg].\n  assumption.\n  rewrite Hneg in H; simpl in H.\n  contradiction (Zle_not_lt 0 (-1)).\n    apply Zge_le; assumption.\n    apply Zorder.Zlt_neg_0.\nQed.\n\n(** Only [1] and [-1] divide [1]. *)\n\nLemma Zdivide_1 : forall x:Z, (x | 1) -> x = 1 \\/ x = -1.\nProof.\n  simple induction 1; intros.\n  elim (Z_lt_ge_dec 0 x); [ left | right ].\n  apply Zmult_one with q; auto with zarith; rewrite H0; ring.\n  assert (- x = 1); auto with zarith.\n  apply Zmult_one with (- q); auto with zarith; rewrite H0; ring.\nQed.\n\n(** If [a] divides [b] and [b] divides [a] then [a] is [b] or [-b]. *)\n\nLemma Zdivide_antisym : forall a b:Z, (a | b) -> (b | a) -> a = b \\/ a = - b.\nProof.\n  simple induction 1; intros.\n  inversion H1.\n  rewrite H0 in H2; clear H H1.\n  case (Z_zerop a); intro.\n  left; rewrite H0; rewrite e; ring.\n  assert (Hqq0 : q0 * q = 1).\n  apply Zmult_reg_l with a.\n  assumption.\n  ring_simplify.\n  pattern a at 2 in |- *; rewrite H2; ring.\n  assert (q | 1).\n  rewrite <- Hqq0; auto with zarith.\n  elim (Zdivide_1 q H); intros.\n  rewrite H1 in H0; left; omega.\n  rewrite H1 in H0; right; omega.\nQed.\n\nTheorem Zdivide_trans: forall a b c, (a | b) -> (b | c) ->  (a | c).\nProof.\n  intros a b c [d H1] [e H2]; exists (d * e); auto with zarith.\n  rewrite H2; rewrite H1; ring.\nQed.\n\n(** If [a] divides [b] and [b<>0] then [|a| <= |b|]. *)\n\nLemma Zdivide_bounds : forall a b:Z, (a | b) -> b <> 0 -> Zabs a <= Zabs b.\nProof.\n  simple induction 1; intros.\n  assert (Zabs b = Zabs q * Zabs a).\n  subst; apply Zabs_Zmult.\n  rewrite H2.\n  assert (H3 := Zabs_pos q).\n  assert (H4 := Zabs_pos a).\n  assert (Zabs q * Zabs a >= 1 * Zabs a); auto with zarith.\n  apply Zmult_ge_compat; auto with zarith.\n  elim (Z_lt_ge_dec (Zabs q) 1); [ intros | auto with zarith ].\n  assert (Zabs q = 0).\n  omega.\n  assert (q = 0).\n  rewrite <- (Zabs_Zsgn q).\n  rewrite H5; auto with zarith.\n  subst q; omega.\nQed.\n\n(** [Zdivide] can be expressed using [Zmod]. *)\n\nLemma Zmod_divide : forall a b, b<>0 -> a mod b = 0 -> (b | a).\nProof.\n intros a b NZ EQ.\n apply Zdivide_intro with (a/b).\n rewrite (Z_div_mod_eq_full a b NZ) at 1.\n rewrite EQ; ring.\nQed.\n\nLemma Zdivide_mod : forall a b, (b | a) -> a mod b = 0.\nProof.\n  intros a b (c,->); apply Z_mod_mult.\nQed.\n\n(** [Zdivide] is hence decidable *)\n\nLemma Zdivide_dec : forall a b:Z, {(a | b)} + {~ (a | b)}.\nProof.\n  intros a b; elim (Ztrichotomy_inf a 0).\n  (* a<0 *)\n  intros H; elim H; intros.\n  case (Z_eq_dec (b mod - a) 0).\n  left; apply Zdivide_opp_l_rev; apply Zmod_divide; auto with zarith.\n  intro H1; right; intro; elim H1; apply Zdivide_mod; auto with zarith.\n  (* a=0 *)\n  case (Z_eq_dec b 0); intro.\n  left; subst; auto with zarith.\n  right; subst; intro H0; inversion H0; omega.\n  (* a>0 *)\n  intro H; case (Z_eq_dec (b mod a) 0).\n  left; apply Zmod_divide; auto with zarith.\n  intro H1; right; intro; elim H1; apply Zdivide_mod; auto with zarith.\nQed.\n\nTheorem Zdivide_Zdiv_eq: forall a b : Z,\n 0 < a -> (a | b) ->  b = a * (b / a).\nProof.\n  intros a b Hb Hc.\n  pattern b at 1; rewrite (Z_div_mod_eq b a); auto with zarith.\n  rewrite (Zdivide_mod b a); auto with zarith.\nQed.\n\nTheorem Zdivide_Zdiv_eq_2: forall a b c : Z,\n 0 < a -> (a | b) -> (c * b)/a = c * (b / a).\nProof.\n  intros a b c H1 H2.\n  inversion H2 as [z Hz].\n  rewrite Hz; rewrite Zmult_assoc.\n  repeat rewrite Z_div_mult; auto with zarith.\nQed.\n\nTheorem Zdivide_Zabs_l: forall a b, (Zabs a | b) ->  (a | b).\nProof.\n  intros a b [x H]; subst b.\n  pattern (Zabs a); apply Zabs_intro.\n  exists (- x); ring.\n  exists x; ring.\nQed.\n\nTheorem Zdivide_Zabs_inv_l: forall a b, (a | b) ->  (Zabs a | b).\nProof.\n  intros a b [x H]; subst b.\n  pattern (Zabs a); apply Zabs_intro.\n  exists (- x);  ring.\n  exists x; ring.\nQed.\n\nTheorem Zdivide_le: forall a b : Z,\n 0 <= a -> 0 < b -> (a | b) ->  a <= b.\nProof.\n  intros a b H1 H2 [q H3]; subst b.\n  case (Zle_lt_or_eq 0 a); auto with zarith; intros H3.\n  case (Zle_lt_or_eq 0 q); auto with zarith.\n  apply (Zmult_le_0_reg_r a); auto with zarith.\n  intros H4; apply Zle_trans with (1 * a); auto with zarith.\n  intros H4; subst q; omega.\nQed.\n\nTheorem Zdivide_Zdiv_lt_pos: forall a b : Z,\n 1 < a -> 0 < b -> (a | b) ->  0 < b / a < b .\nProof.\n  intros a b H1 H2 H3; split.\n  apply Zmult_lt_reg_r with a; auto with zarith.\n  rewrite (Zmult_comm (Zdiv b a)); rewrite <- Zdivide_Zdiv_eq; auto with zarith.\n  apply Zmult_lt_reg_r with a; auto with zarith.\n  repeat rewrite (fun x => Zmult_comm x a); auto with zarith.\n  rewrite <- Zdivide_Zdiv_eq; auto with zarith.\n  pattern b at 1; replace b with (1 * b); auto with zarith.\n  apply Zmult_lt_compat_r; auto with zarith.\nQed.\n\nLemma Zmod_div_mod: forall n m a, 0 < n -> 0 < m ->\n (n | m) -> a mod n = (a mod m) mod n.\nProof.\n  intros n m a H1 H2 H3.\n  pattern a at 1; rewrite (Z_div_mod_eq a m); auto with zarith.\n  case H3; intros q Hq; pattern m at 1; rewrite Hq.\n  rewrite (Zmult_comm q).\n  rewrite Zplus_mod; auto with zarith.\n  rewrite <- Zmult_assoc; rewrite Zmult_mod; auto with zarith.\n  rewrite Z_mod_same; try rewrite Zmult_0_l; auto with zarith.\n  rewrite (Zmod_small 0); auto with zarith.\n  rewrite Zplus_0_l; rewrite Zmod_mod; auto with zarith.\nQed.\n\nLemma Zmod_divide_minus: forall a b c : Z, 0 < b ->\n a mod b = c -> (b | a - c).\nProof.\n  intros a b c H H1; apply Zmod_divide; auto with zarith.\n  rewrite Zminus_mod; auto with zarith.\n  rewrite H1; pattern c at 1; rewrite <- (Zmod_small c b); auto with zarith.\n  rewrite Zminus_diag; apply Zmod_small; auto with zarith.\n  subst; apply Z_mod_lt; auto with zarith.\nQed.\n\nLemma Zdivide_mod_minus: forall a b c : Z, 0 <= c < b ->\n (b | a - c) -> a mod b = c.\nProof.\n  intros a b c (H1, H2) H3; assert (0 < b); try apply Zle_lt_trans with c; auto.\n  replace a with ((a - c) + c); auto with zarith.\n  rewrite Zplus_mod; auto with zarith.\n  rewrite (Zdivide_mod (a -c) b); try rewrite Zplus_0_l; auto with zarith.\n  rewrite Zmod_mod; try apply Zmod_small; auto with zarith.\nQed.\n\n(** * Greatest common divisor (gcd). *)\n\n(** There is no unicity of the gcd; hence we define the predicate [gcd a b d]\n     expressing that [d] is a gcd of [a] and [b].\n     (We show later that the [gcd] is actually unique if we discard its sign.) *)\n\nInductive Zis_gcd (a b d:Z) : Prop :=\n  Zis_gcd_intro :\n  (d | a) ->\n  (d | b) -> (forall x:Z, (x | a) -> (x | b) -> (x | d)) -> Zis_gcd a b d.\n\n(** Trivial properties of [gcd] *)\n\nLemma Zis_gcd_sym : forall a b d:Z, Zis_gcd a b d -> Zis_gcd b a d.\nProof.\n  simple induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_0 : forall a:Z, Zis_gcd a 0 a.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_1 : forall a, Zis_gcd a 1 1.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_refl : forall a, Zis_gcd a a a.\nProof.\n  constructor; auto with zarith.\nQed.\n\nLemma Zis_gcd_minus : forall a b d:Z, Zis_gcd a (- b) d -> Zis_gcd b a d.\nProof.\n  simple induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_opp : forall a b d:Z, Zis_gcd a b d -> Zis_gcd b a (- d).\nProof.\n  simple induction 1; constructor; intuition.\nQed.\n\nLemma Zis_gcd_0_abs : forall a:Z, Zis_gcd 0 a (Zabs a).\nProof.\n  intros a.\n  apply Zabs_ind.\n  intros; apply Zis_gcd_sym; apply Zis_gcd_0; auto.\n  intros; apply Zis_gcd_opp; apply Zis_gcd_0; auto.\nQed.\n\nHint Resolve Zis_gcd_sym Zis_gcd_0 Zis_gcd_minus Zis_gcd_opp: zarith.\n\nTheorem Zis_gcd_unique: forall a b c d : Z,\n Zis_gcd a b c -> Zis_gcd a b d ->  c = d \\/ c = (- d).\nProof.\nintros a b c d H1 H2.\ninversion_clear H1 as [Hc1 Hc2 Hc3].\ninversion_clear H2 as [Hd1 Hd2 Hd3].\nassert (H3: Zdivide c d); auto.\nassert (H4: Zdivide d c); auto.\napply Zdivide_antisym; auto.\nQed.\n\n\n(** * Extended Euclid algorithm. *)\n\n(** Euclid's algorithm to compute the [gcd] mainly relies on\n    the following property. *)\n\nLemma Zis_gcd_for_euclid :\n  forall a b d q:Z, Zis_gcd b (a - q * b) d -> Zis_gcd a b d.\nProof.\n  simple induction 1; constructor; intuition.\n  replace a with (a - q * b + q * b). auto with zarith. ring.\nQed.\n\nLemma Zis_gcd_for_euclid2 :\n  forall b d q r:Z, Zis_gcd r b d -> Zis_gcd b (b * q + r) d.\nProof.\n  simple induction 1; constructor; intuition.\n  apply H2; auto.\n  replace r with (b * q + r - b * q). auto with zarith. ring.\nQed.\n\n(** We implement the extended version of Euclid's algorithm,\n    i.e. the one computing Bezout's coefficients as it computes\n    the [gcd]. We follow the algorithm given in Knuth's\n    \"Art of Computer Programming\", vol 2, page 325. *)\n\nSection extended_euclid_algorithm.\n\n  Variables a b : Z.\n\n  (** The specification of Euclid's algorithm is the existence of\n      [u], [v] and [d] such that [ua+vb=d] and [(gcd a b d)]. *)\n\n  Inductive Euclid : Set :=\n    Euclid_intro :\n    forall u v d:Z, u * a + v * b = d -> Zis_gcd a b d -> Euclid.\n\n  (** The recursive part of Euclid's algorithm uses well-founded\n      recursion of non-negative integers. It maintains 6 integers\n      [u1,u2,u3,v1,v2,v3] such that the following invariant holds:\n      [u1*a+u2*b=u3] and [v1*a+v2*b=v3] and [gcd(u2,v3)=gcd(a,b)].\n      *)\n\n  Lemma euclid_rec :\n    forall v3:Z,\n      0 <= v3 ->\n      forall u1 u2 u3 v1 v2:Z,\n\tu1 * a + u2 * b = u3 ->\n\tv1 * a + v2 * b = v3 ->\n\t(forall d:Z, Zis_gcd u3 v3 d -> Zis_gcd a b d) -> Euclid.\n  Proof.\n    intros v3 Hv3; generalize Hv3; pattern v3 in |- *.\n    apply Zlt_0_rec.\n    clear v3 Hv3; intros.\n    elim (Z_zerop x); intro.\n    apply Euclid_intro with (u := u1) (v := u2) (d := u3).\n    assumption.\n    apply H3.\n    rewrite a0; auto with zarith.\n    set (q := u3 / x) in *.\n    assert (Hq : 0 <= u3 - q * x < x).\n    replace (u3 - q * x) with (u3 mod x).\n    apply Z_mod_lt; omega.\n    assert (xpos : x > 0). omega.\n    generalize (Z_div_mod_eq u3 x xpos).\n    unfold q in |- *.\n    intro eq; pattern u3 at 2 in |- *; rewrite eq; ring.\n    apply (H (u3 - q * x) Hq (proj1 Hq) v1 v2 x (u1 - q * v1) (u2 - q * v2)).\n    tauto.\n    replace ((u1 - q * v1) * a + (u2 - q * v2) * b) with\n      (u1 * a + u2 * b - q * (v1 * a + v2 * b)).\n    rewrite H1; rewrite H2; trivial.\n    ring.\n    intros; apply H3.\n    apply Zis_gcd_for_euclid with q; assumption.\n    assumption.\n  Qed.\n\n  (** We get Euclid's algorithm by applying [euclid_rec] on\n      [1,0,a,0,1,b] when [b>=0] and [1,0,a,0,-1,-b] when [b<0]. *)\n\n  Lemma euclid : Euclid.\n  Proof.\n    case (Z_le_gt_dec 0 b); intro.\n    intros;\n      apply euclid_rec with\n\t(u1 := 1) (u2 := 0) (u3 := a) (v1 := 0) (v2 := 1) (v3 := b);\n\tauto with zarith; ring.\n    intros;\n      apply euclid_rec with\n\t(u1 := 1) (u2 := 0) (u3 := a) (v1 := 0) (v2 := -1) (v3 := - b);\n\tauto with zarith; try ring.\n  Qed.\n\nEnd extended_euclid_algorithm.\n\nTheorem Zis_gcd_uniqueness_apart_sign :\n  forall a b d d':Z, Zis_gcd a b d -> Zis_gcd a b d' -> d = d' \\/ d = - d'.\nProof.\n  simple induction 1.\n  intros H1 H2 H3; simple induction 1; intros.\n  generalize (H3 d' H4 H5); intro Hd'd.\n  generalize (H6 d H1 H2); intro Hdd'.\n  exact (Zdivide_antisym d d' Hdd' Hd'd).\nQed.\n\n(** * Bezout's coefficients *)\n\nInductive Bezout (a b d:Z) : Prop :=\n  Bezout_intro : forall u v:Z, u * a + v * b = d -> Bezout a b d.\n\n(** Existence of Bezout's coefficients for the [gcd] of [a] and [b] *)\n\nLemma Zis_gcd_bezout : forall a b d:Z, Zis_gcd a b d -> Bezout a b d.\nProof.\n  intros a b d Hgcd.\n  elim (euclid a b); intros u v d0 e g.\n  generalize (Zis_gcd_uniqueness_apart_sign a b d d0 Hgcd g).\n  intro H; elim H; clear H; intros.\n  apply Bezout_intro with u v.\n  rewrite H; assumption.\n  apply Bezout_intro with (- u) (- v).\n  rewrite H; rewrite <- e; ring.\nQed.\n\n(** gcd of [ca] and [cb] is [c gcd(a,b)]. *)\n\nLemma Zis_gcd_mult :\n  forall a b c d:Z, Zis_gcd a b d -> Zis_gcd (c * a) (c * b) (c * d).\nProof.\n  intros a b c d; simple induction 1; constructor; intuition.\n  elim (Zis_gcd_bezout a b d H). intros.\n  elim H3; intros.\n  elim H4; intros.\n  apply Zdivide_intro with (u * q + v * q0).\n  rewrite <- H5.\n  replace (c * (u * a + v * b)) with (u * (c * a) + v * (c * b)).\n  rewrite H6; rewrite H7; ring.\n  ring.\nQed.\n\n\n(** * Relative primality *)\n\nDefinition rel_prime (a b:Z) : Prop := Zis_gcd a b 1.\n\n(** Bezout's theorem: [a] and [b] are relatively prime if and\n    only if there exist [u] and [v] such that [ua+vb = 1]. *)\n\nLemma rel_prime_bezout : forall a b:Z, rel_prime a b -> Bezout a b 1.\nProof.\n  intros a b; exact (Zis_gcd_bezout a b 1).\nQed.\n\nLemma bezout_rel_prime : forall a b:Z, Bezout a b 1 -> rel_prime a b.\nProof.\n  simple induction 1; constructor; auto with zarith.\n  intros. rewrite <- H0; auto with zarith.\nQed.\n\n(** Gauss's theorem: if [a] divides [bc] and if [a] and [b] are\n    relatively prime, then [a] divides [c]. *)\n\nTheorem Gauss : forall a b c:Z, (a | b * c) -> rel_prime a b -> (a | c).\nProof.\n  intros. elim (rel_prime_bezout a b H0); intros.\n  replace c with (c * 1); [ idtac | ring ].\n  rewrite <- H1.\n  replace (c * (u * a + v * b)) with (c * u * a + v * (b * c));\n    [ eauto with zarith | ring ].\nQed.\n\n(** If [a] is relatively prime to [b] and [c], then it is to [bc] *)\n\nLemma rel_prime_mult :\n  forall a b c:Z, rel_prime a b -> rel_prime a c -> rel_prime a (b * c).\nProof.\n  intros a b c Hb Hc.\n  elim (rel_prime_bezout a b Hb); intros.\n  elim (rel_prime_bezout a c Hc); intros.\n  apply bezout_rel_prime.\n  apply Bezout_intro with\n    (u := u * u0 * a + v0 * c * u + u0 * v * b) (v := v * v0).\n  rewrite <- H.\n  replace (u * a + v * b) with ((u * a + v * b) * 1); [ idtac | ring ].\n  rewrite <- H0.\n  ring.\nQed.\n\nLemma rel_prime_cross_prod :\n  forall a b c d:Z,\n    rel_prime a b ->\n    rel_prime c d -> b > 0 -> d > 0 -> a * d = b * c -> a = c /\\ b = d.\nProof.\n  intros a b c d; intros.\n  elim (Zdivide_antisym b d).\n  split; auto with zarith.\n  rewrite H4 in H3.\n  rewrite Zmult_comm in H3.\n  apply Zmult_reg_l with d; auto with zarith.\n  intros; omega.\n  apply Gauss with a.\n  rewrite H3.\n  auto with zarith.\n  red in |- *; auto with zarith.\n  apply Gauss with c.\n  rewrite Zmult_comm.\n  rewrite <- H3.\n  auto with zarith.\n  red in |- *; auto with zarith.\nQed.\n\n(** After factorization by a gcd, the original numbers are relatively prime. *)\n\nLemma Zis_gcd_rel_prime :\n  forall a b g:Z,\n    b > 0 -> g >= 0 -> Zis_gcd a b g -> rel_prime (a / g) (b / g).\nProof.\n  intros a b g; intros.\n  assert (g <> 0).\n  intro.\n  elim H1; intros.\n  elim H4; intros.\n  rewrite H2 in H6; subst b; omega.\n  unfold rel_prime in |- *.\n  destruct H1.\n  destruct H1 as (a',H1).\n  destruct H3 as (b',H3).\n  replace (a/g) with a';\n    [|rewrite H1; rewrite Z_div_mult; auto with zarith].\n  replace (b/g) with b';\n    [|rewrite H3; rewrite Z_div_mult; auto with zarith].\n  constructor.\n  exists a'; auto with zarith.\n  exists b'; auto with zarith.\n  intros x (xa,H5) (xb,H6).\n  destruct (H4 (x*g)).\n  exists xa; rewrite Zmult_assoc; rewrite <- H5; auto.\n  exists xb; rewrite Zmult_assoc; rewrite <- H6; auto.\n  replace g with (1*g) in H7; auto with zarith.\n  do 2 rewrite Zmult_assoc in H7.\n  generalize (Zmult_reg_r _ _ _ H2 H7); clear H7; intros.\n  rewrite Zmult_1_r in H7.\n  exists q; auto with zarith.\nQed.\n\nTheorem rel_prime_sym: forall a b, rel_prime a b -> rel_prime b a.\nProof.\n  intros a b H; auto with zarith.\n  red; apply Zis_gcd_sym; auto with zarith.\nQed.\n\nTheorem rel_prime_div: forall p q r,\n rel_prime p q -> (r | p) -> rel_prime r q.\nProof.\n  intros p q r H (u, H1); subst.\n  inversion_clear H as [H1 H2 H3].\n  red; apply Zis_gcd_intro; try apply Zone_divide.\n  intros x H4 H5; apply H3; auto.\n  apply Zdivide_mult_r; auto.\nQed.\n\nTheorem rel_prime_1: forall n, rel_prime 1 n.\nProof.\n  intros n; red; apply Zis_gcd_intro; auto.\n  exists 1; auto with zarith.\n  exists n; auto with zarith.\nQed.\n\nTheorem not_rel_prime_0: forall n, 1 < n -> ~ rel_prime 0 n.\nProof.\n  intros n H H1; absurd (n = 1 \\/ n = -1).\n  intros [H2 | H2]; subst; contradict H; auto with zarith.\n  case (Zis_gcd_unique  0 n n 1); auto.\n  apply Zis_gcd_intro; auto.\n  exists 0; auto with zarith.\n  exists 1; auto with zarith.\nQed.\n\nTheorem rel_prime_mod: forall p q, 0 < q ->\n rel_prime p q -> rel_prime (p mod q) q.\nProof.\n  intros p q H H0.\n  assert (H1: Bezout p q 1).\n  apply rel_prime_bezout; auto.\n  inversion_clear H1 as [q1 r1 H2].\n  apply bezout_rel_prime.\n  apply Bezout_intro with q1  (r1 + q1 * (p / q)).\n  rewrite <- H2.\n  pattern p at 3; rewrite (Z_div_mod_eq p q); try ring; auto with zarith.\nQed.\n\nTheorem rel_prime_mod_rev: forall p q, 0 < q ->\n rel_prime (p mod q) q -> rel_prime p q.\nProof.\n  intros p q H H0.\n  rewrite (Z_div_mod_eq p q); auto with zarith; red.\n  apply Zis_gcd_sym; apply Zis_gcd_for_euclid2; auto with zarith.\nQed.\n\nTheorem Zrel_prime_neq_mod_0: forall a b, 1 < b -> rel_prime a b -> a mod b <> 0.\nProof.\n  intros a b H H1 H2.\n  case (not_rel_prime_0 _ H).\n  rewrite <- H2.\n  apply rel_prime_mod; auto with zarith.\nQed.\n\n(** * Primality *)\n\nInductive prime (p:Z) : Prop :=\n  prime_intro :\n    1 < p -> (forall n:Z, 1 <= n < p -> rel_prime n p) -> prime p.\n\n(** The sole divisors of a prime number [p] are [-1], [1], [p] and [-p]. *)\n\nLemma prime_divisors :\n  forall p:Z,\n    prime p -> forall a:Z, (a | p) -> a = -1 \\/ a = 1 \\/ a = p \\/ a = - p.\nProof.\n  simple induction 1; intros.\n  assert\n    (a = - p \\/ - p < a < -1 \\/ a = -1 \\/ a = 0 \\/ a = 1 \\/ 1 < a < p \\/ a = p).\n  assert (Zabs a <= Zabs p). apply Zdivide_bounds; [ assumption | omega ].\n  generalize H3.\n  pattern (Zabs a) in |- *; apply Zabs_ind; pattern (Zabs p) in |- *;\n    apply Zabs_ind; intros; omega.\n  intuition idtac.\n  (* -p < a < -1 *)\n  absurd (rel_prime (- a) p); intuition.\n  inversion H3.\n  assert (- a | - a); auto with zarith.\n  assert (- a | p); auto with zarith.\n  generalize (H8 (- a) H9 H10); intuition idtac.\n  generalize (Zdivide_1 (- a) H11); intuition.\n  (* a = 0 *)\n  inversion H2. subst a; omega.\n  (* 1 < a < p *)\n  absurd (rel_prime a p); intuition.\n  inversion H3.\n  assert (a | a); auto with zarith.\n  assert (a | p); auto with zarith.\n  generalize (H8 a H9 H10); intuition idtac.\n  generalize (Zdivide_1 a H11); intuition.\nQed.\n\n(** A prime number is relatively prime with any number it does not divide *)\n\nLemma prime_rel_prime :\n  forall p:Z, prime p -> forall a:Z, ~ (p | a) -> rel_prime p a.\nProof.\n  simple induction 1; intros.\n  constructor; intuition.\n  elim (prime_divisors p H x H3); intuition; subst; auto with zarith.\n  absurd (p | a); auto with zarith.\n  absurd (p | a); intuition.\nQed.\n\nHint Resolve prime_rel_prime: zarith.\n\n(** As a consequence, a prime number is relatively prime with smaller numbers *)\n\nTheorem rel_prime_le_prime:\n forall a p, prime p -> 1 <=  a < p -> rel_prime a p.\nProof.\n  intros a p Hp [H1 H2].\n  apply rel_prime_sym; apply prime_rel_prime; auto.\n  intros [q Hq]; subst a.\n  case (Zle_or_lt q 0); intros Hl.\n  absurd (q * p <= 0 * p); auto with zarith.\n  absurd (1 * p <= q * p); auto with zarith.\nQed.\n\n\n(** If a prime [p] divides [ab] then it divides either [a] or [b] *)\n\nLemma prime_mult :\n  forall p:Z, prime p -> forall a b:Z, (p | a * b) -> (p | a) \\/ (p | b).\nProof.\n  intro p; simple induction 1; intros.\n  case (Zdivide_dec p a); intuition.\n  right; apply Gauss with a; auto with zarith.\nQed.\n\nLemma not_prime_0: ~ prime 0.\nProof.\n  intros H1; case (prime_divisors _ H1 2); auto with zarith.\nQed.\n\nLemma not_prime_1: ~ prime 1.\nProof.\n  intros H1; absurd (1 < 1); auto with zarith.\n  inversion H1; auto.\nQed.\n\nLemma prime_2: prime 2.\nProof.\n  apply prime_intro; auto with zarith.\n  intros n [H1 H2]; case Zle_lt_or_eq with ( 1 := H1 ); auto with zarith;\n   clear H1; intros H1.\n  contradict H2; auto with zarith.\n  subst n; red; auto with zarith.\n  apply Zis_gcd_intro; auto with zarith.\nQed.\n\nTheorem prime_3: prime 3.\nProof.\n  apply prime_intro; auto with zarith.\n  intros n [H1 H2]; case Zle_lt_or_eq with ( 1 := H1 ); auto with zarith;\n   clear H1; intros H1.\n  case (Zle_lt_or_eq 2 n); auto with zarith; clear H1; intros H1.\n  contradict H2; auto with zarith.\n  subst n; red; auto with zarith.\n  apply Zis_gcd_intro; auto with zarith.\n  intros x [q1 Hq1] [q2 Hq2].\n  exists (q2 - q1).\n  apply trans_equal with (3 - 2); auto with zarith.\n  rewrite Hq1; rewrite Hq2; ring.\n  subst n; red; auto with zarith.\n  apply Zis_gcd_intro; auto with zarith.\nQed.\n\nTheorem prime_ge_2: forall p, prime p ->  2 <= p.\nProof.\n  intros p Hp; inversion Hp; auto with zarith.\nQed.\n\nDefinition prime' p := 1<p /\\ (forall n, 1<n<p -> ~ (n|p)).\n\nTheorem prime_alt:\n forall p, prime' p <-> prime p.\nProof.\n  split; destruct 1; intros.\n  (* prime -> prime' *)\n  constructor; auto; intros.\n  red; apply Zis_gcd_intro; auto with zarith; intros.\n  case (Zle_lt_or_eq 0 (Zabs x)); auto with zarith; intros H6.\n  case (Zle_lt_or_eq 1 (Zabs x)); auto with zarith; intros H7.\n  case (Zle_lt_or_eq (Zabs x) p); auto with zarith.\n  apply Zdivide_le; auto with zarith.\n  apply Zdivide_Zabs_inv_l; auto.\n  intros H8; case (H0 (Zabs x)); auto.\n  apply Zdivide_Zabs_inv_l; auto.\n  intros H8; subst p; absurd (Zabs x <= n); auto with zarith.\n  apply Zdivide_le; auto with zarith.\n  apply Zdivide_Zabs_inv_l; auto.\n  rewrite H7; pattern (Zabs x); apply Zabs_intro; auto with zarith.\n  absurd (0%Z = p); auto with zarith.\n  assert (x=0) by (destruct x; simpl in *; now auto).\n  subst x; elim H3; intro q; rewrite Zmult_0_r; auto.\n  (* prime' -> prime *)\n  split; auto; intros.\n  intros H2.\n  case (Zis_gcd_unique n p n 1); auto with zarith.\n  apply Zis_gcd_intro; auto with zarith.\n  apply H0; auto with zarith.\nQed.\n\nTheorem square_not_prime: forall a, ~ prime (a * a).\nProof.\n  intros a Ha.\n  rewrite <- (Zabs_square a) in Ha.\n  assert (0 <= Zabs a) by auto with zarith.\n  set (b:=Zabs a) in *; clearbody b.\n  rewrite <- prime_alt in Ha; destruct Ha.\n  case (Zle_lt_or_eq 0 b); auto with zarith; intros Hza1; [ | subst; omega].\n  case (Zle_lt_or_eq 1 b); auto with zarith; intros Hza2; [ | subst; omega].\n  assert (Hza3 := Zmult_lt_compat_r 1 b b Hza1 Hza2).\n  rewrite Zmult_1_l in Hza3.\n  elim (H1 _ (conj Hza2 Hza3)).\n  exists b; auto.\nQed.\n\nTheorem prime_div_prime: forall p q,\n prime p -> prime q -> (p | q) -> p = q.\nProof.\n  intros p q H H1 H2;\n  assert (Hp: 0 < p); try apply Zlt_le_trans with 2; try apply prime_ge_2; auto with zarith.\n  assert (Hq: 0 < q); try apply Zlt_le_trans with 2; try apply prime_ge_2; auto with zarith.\n  case prime_divisors with (2 := H2); auto.\n  intros H4; contradict Hp; subst; auto with zarith.\n  intros [H4| [H4 | H4]]; subst; auto.\n  contradict H; auto; apply not_prime_1.\n  contradict Hp; auto with zarith.\nQed.\n\n\n(** We could obtain a [Zgcd] function via Euclid algorithm. But we propose\n  here a binary version of [Zgcd], faster and executable within Coq.\n\n   Algorithm:\n\n   gcd 0 b = b\n   gcd a 0 = a\n   gcd (2a) (2b) = 2(gcd a b)\n   gcd (2a+1) (2b) = gcd (2a+1) b\n   gcd (2a) (2b+1) = gcd a (2b+1)\n   gcd (2a+1) (2b+1) = gcd (b-a) (2*a+1)\n                    or gcd (a-b) (2*b+1), depending on whether a<b\n*)\n\nOpen Scope positive_scope.\n\nFixpoint Pgcdn (n: nat) (a b : positive) : positive :=\n  match n with\n    | O => 1\n    | S n =>\n      match a,b with\n\t| xH, _ => 1\n\t| _, xH => 1\n\t| xO a, xO b => xO (Pgcdn n a b)\n\t| a, xO b => Pgcdn n a b\n\t| xO a, b => Pgcdn n a b\n\t| xI a', xI b' =>\n          match Pcompare a' b' Eq with\n\t    | Eq => a\n\t    | Lt => Pgcdn  n (b'-a') a\n\t    | Gt => Pgcdn n (a'-b') b\n          end\n      end\n  end.\n\nDefinition Pgcd (a b: positive) := Pgcdn (Psize a + Psize b)%nat a b.\n\nClose Scope positive_scope.\n\nDefinition Zgcd (a b : Z) : Z :=\n  match a,b with\n    | Z0, _ => Zabs b\n    | _, Z0 => Zabs a\n    | Zpos a, Zpos b => Zpos (Pgcd a b)\n    | Zpos a, Zneg b => Zpos (Pgcd a b)\n    | Zneg a, Zpos b => Zpos (Pgcd a b)\n    | Zneg a, Zneg b => Zpos (Pgcd a b)\n  end.\n\nLemma Zgcd_is_pos : forall a b, 0 <= Zgcd a b.\nProof.\n  unfold Zgcd; destruct a; destruct b; auto with zarith.\nQed.\n\nLemma Zis_gcd_even_odd : forall a b g, Zis_gcd (Zpos a) (Zpos (xI b)) g ->\n  Zis_gcd (Zpos (xO a)) (Zpos (xI b)) g.\nProof.\n  intros.\n  destruct H.\n  constructor; auto.\n  destruct H as (e,H2); exists (2*e); auto with zarith.\n  rewrite Zpos_xO; rewrite H2; ring.\n  intros.\n  apply H1; auto.\n  rewrite Zpos_xO in H2.\n  rewrite Zpos_xI in H3.\n  apply Gauss with 2; auto.\n  apply bezout_rel_prime.\n  destruct H3 as (bb, H3).\n  apply Bezout_intro with bb (-Zpos b).\n  omega.\nQed.\n\nLemma Pgcdn_correct : forall n a b, (Psize a + Psize b<=n)%nat ->\n  Zis_gcd (Zpos a) (Zpos b) (Zpos (Pgcdn n a b)).\nProof.\n  intro n; pattern n; apply lt_wf_ind; clear n; intros.\n  destruct n.\n  simpl.\n  destruct a; simpl in *; try inversion H0.\n  destruct a.\n  destruct b; simpl.\n  case_eq (Pcompare a b Eq); intros.\n  (* a = xI, b = xI, compare = Eq *)\n  rewrite (Pcompare_Eq_eq _ _ H1); apply Zis_gcd_refl.\n  (* a = xI, b = xI, compare = Lt *)\n  apply Zis_gcd_sym.\n  apply Zis_gcd_for_euclid with 1.\n  apply Zis_gcd_sym.\n  replace (Zpos (xI b) - 1 * Zpos (xI a)) with (Zpos(xO (b - a))).\n  apply Zis_gcd_even_odd.\n  apply H; auto.\n  simpl in *.\n  assert (Psize (b-a) <= Psize b)%nat.\n  apply Psize_monotone.\n  change (Zpos (b-a) < Zpos b).\n  rewrite (Zpos_minus_morphism _ _ H1).\n  assert (0 < Zpos a) by (compute; auto).\n  omega.\n  omega.\n  rewrite Zpos_xO; do 2 rewrite Zpos_xI.\n  rewrite Zpos_minus_morphism; auto.\n  omega.\n  (* a = xI, b = xI, compare = Gt *)\n  apply Zis_gcd_for_euclid with 1.\n  replace (Zpos (xI a) - 1 * Zpos (xI b)) with (Zpos(xO (a - b))).\n  apply Zis_gcd_sym.\n  apply Zis_gcd_even_odd.\n  apply H; auto.\n  simpl in *.\n  assert (Psize (a-b) <= Psize a)%nat.\n  apply Psize_monotone.\n  change (Zpos (a-b) < Zpos a).\n  rewrite (Zpos_minus_morphism b a).\n  assert (0 < Zpos b) by (compute; auto).\n  omega.\n  rewrite ZC4; rewrite H1; auto.\n  omega.\n  rewrite Zpos_xO; do 2 rewrite Zpos_xI.\n  rewrite Zpos_minus_morphism; auto.\n  omega.\n  rewrite ZC4; rewrite H1; auto.\n  (* a = xI, b = xO *)\n  apply Zis_gcd_sym.\n  apply Zis_gcd_even_odd.\n  apply Zis_gcd_sym.\n  apply H; auto.\n  simpl in *; omega.\n  (* a = xI, b = xH *)\n  apply Zis_gcd_1.\n  destruct b; simpl.\n  (* a = xO, b = xI *)\n  apply Zis_gcd_even_odd.\n  apply H; auto.\n  simpl in *; omega.\n  (* a = xO, b = xO *)\n  rewrite (Zpos_xO a); rewrite (Zpos_xO b); rewrite (Zpos_xO (Pgcdn n a b)).\n  apply Zis_gcd_mult.\n  apply H; auto.\n  simpl in *; omega.\n  (* a = xO, b = xH *)\n  apply Zis_gcd_1.\n  (* a = xH *)\n  simpl; apply Zis_gcd_sym; apply Zis_gcd_1.\nQed.\n\nLemma Pgcd_correct : forall a b, Zis_gcd (Zpos a) (Zpos b) (Zpos (Pgcd a b)).\nProof.\n  unfold Pgcd; intros.\n  apply Pgcdn_correct; auto.\nQed.\n\nLemma Zgcd_is_gcd : forall a b, Zis_gcd a b (Zgcd a b).\nProof.\n  destruct a.\n  intros.\n  simpl.\n  apply Zis_gcd_0_abs.\n  destruct b; simpl.\n  apply Zis_gcd_0.\n  apply Pgcd_correct.\n  apply Zis_gcd_sym.\n  apply Zis_gcd_minus; simpl.\n  apply Pgcd_correct.\n  destruct b; simpl.\n  apply Zis_gcd_minus; simpl.\n  apply Zis_gcd_sym.\n  apply Zis_gcd_0.\n  apply Zis_gcd_minus; simpl.\n  apply Zis_gcd_sym.\n  apply Pgcd_correct.\n  apply Zis_gcd_sym.\n  apply Zis_gcd_minus; simpl.\n  apply Zis_gcd_minus; simpl.\n  apply Zis_gcd_sym.\n  apply Pgcd_correct.\nQed.\n\nTheorem Zgcd_spec : forall x y : Z, {z : Z | Zis_gcd x y z /\\ 0 <= z}.\nProof.\n  intros x y; exists (Zgcd x y).\n  split; [apply Zgcd_is_gcd  | apply Zgcd_is_pos].\nQed.\n\nTheorem Zdivide_Zgcd: forall p q r : Z,\n (p | q) -> (p | r) -> (p | Zgcd q r).\nProof.\n  intros p q r H1 H2.\n  assert (H3: (Zis_gcd q r (Zgcd q r))).\n  apply Zgcd_is_gcd.\n  inversion_clear H3; auto.\nQed.\n\nTheorem Zis_gcd_gcd: forall a b c : Z,\n 0 <= c ->  Zis_gcd a b c -> Zgcd a b = c.\nProof.\n  intros a b c H1 H2.\n  case (Zis_gcd_uniqueness_apart_sign a b c (Zgcd a b)); auto.\n  apply Zgcd_is_gcd; auto.\n  case Zle_lt_or_eq with (1 := H1); clear H1; intros H1; subst; auto.\n  intros H3; subst.\n  generalize (Zgcd_is_pos a b); auto with zarith.\n  case (Zgcd a b); simpl; auto; intros; discriminate.\nQed.\n\nTheorem Zgcd_inv_0_l: forall x y, Zgcd x y = 0 -> x = 0.\nProof.\n  intros x y H.\n  assert (F1: Zdivide 0 x).\n   rewrite <- H.\n   generalize (Zgcd_is_gcd x y); intros HH; inversion HH; auto.\n  inversion F1 as [z H1].\n  rewrite H1; ring.\nQed.\n\nTheorem Zgcd_inv_0_r: forall x y, Zgcd x y = 0 -> y = 0.\nProof.\n  intros x y H.\n  assert (F1: Zdivide 0 y).\n   rewrite <- H.\n   generalize (Zgcd_is_gcd x y); intros HH; inversion HH; auto.\n  inversion F1 as [z H1].\n  rewrite H1; ring.\nQed.\n\nTheorem Zgcd_div_swap0 : forall a b : Z,\n 0 < Zgcd a b ->\n 0 < b ->\n (a / Zgcd a b) * b = a * (b/Zgcd a b).\nProof.\n  intros a b Hg Hb.\n  assert (F := Zgcd_is_gcd a b); inversion F as [F1 F2 F3].\n  pattern b at 2; rewrite (Zdivide_Zdiv_eq (Zgcd a b) b); auto.\n  repeat rewrite Zmult_assoc; f_equal.\n  rewrite Zmult_comm.\n  rewrite <- Zdivide_Zdiv_eq; auto.\nQed.\n\nTheorem Zgcd_div_swap : forall a b c : Z,\n 0 < Zgcd a b ->\n 0 < b ->\n (c * a) / Zgcd a b * b = c * a * (b/Zgcd a b).\nProof.\n  intros a b c Hg Hb.\n  assert (F := Zgcd_is_gcd a b); inversion F as [F1 F2 F3].\n  pattern b at 2; rewrite (Zdivide_Zdiv_eq (Zgcd a b) b); auto.\n  repeat rewrite Zmult_assoc; f_equal.\n  rewrite Zdivide_Zdiv_eq_2; auto.\n  repeat rewrite <- Zmult_assoc; f_equal.\n  rewrite Zmult_comm.\n  rewrite <- Zdivide_Zdiv_eq; auto.\nQed.\n\nLemma Zgcd_comm : forall a b, Zgcd a b = Zgcd b a.\nProof.\n  intros.\n  apply Zis_gcd_gcd.\n  apply Zgcd_is_pos.\n  apply Zis_gcd_sym.\n  apply Zgcd_is_gcd.\nQed.\n\nLemma Zgcd_ass : forall a b c, Zgcd (Zgcd a b) c = Zgcd a (Zgcd b c).\nProof.\n  intros.\n  apply Zis_gcd_gcd.\n  apply Zgcd_is_pos.\n  destruct (Zgcd_is_gcd a b).\n  destruct (Zgcd_is_gcd b c).\n  destruct (Zgcd_is_gcd a (Zgcd b c)).\n  constructor; eauto using Zdivide_trans.\nQed.\n\nLemma Zgcd_Zabs : forall a b, Zgcd (Zabs a) b = Zgcd a b.\nProof.\n  destruct a; simpl; auto.\nQed.\n\nLemma Zgcd_0 : forall a, Zgcd a 0 = Zabs a.\nProof.\n  destruct a; simpl; auto.\nQed.\n\nLemma Zgcd_1 : forall a, Zgcd a 1 = 1.\nProof.\n  intros; apply Zis_gcd_gcd; auto with zarith; apply Zis_gcd_1.\nQed.\nHint Resolve Zgcd_0 Zgcd_1 : zarith.\n\nTheorem Zgcd_1_rel_prime : forall a b,\n Zgcd a b = 1 <-> rel_prime a b.\nProof.\n  unfold rel_prime; split; intro H.\n  rewrite <- H; apply Zgcd_is_gcd.\n  case (Zis_gcd_unique a b (Zgcd a b) 1); auto.\n  apply Zgcd_is_gcd.\n  intros H2; absurd (0 <= Zgcd a b); auto with zarith.\n  generalize (Zgcd_is_pos a b); auto with zarith.\nQed.\n\nDefinition rel_prime_dec: forall a b,\n { rel_prime a b }+{ ~ rel_prime a b }.\nProof.\n  intros a b; case (Z_eq_dec (Zgcd a b) 1); intros H1.\n  left; apply -> Zgcd_1_rel_prime; auto.\n  right; contradict H1; apply <- Zgcd_1_rel_prime; auto.\nDefined.\n\nDefinition prime_dec_aux:\n forall p m,\n  { forall n, 1 < n < m -> rel_prime n p } +\n  { exists n, 1 < n < m  /\\ ~ rel_prime n p }.\nProof.\n  intros p m.\n  case (Z_lt_dec 1 m); intros H1;\n   [ | left; intros; exfalso; omega ].\n  pattern m; apply natlike_rec; auto with zarith.\n  left; intros; exfalso; omega.\n  intros x Hx IH; destruct IH as [F|E].\n  destruct (rel_prime_dec x p) as [Y|N].\n  left; intros n [HH1 HH2].\n  case (Zgt_succ_gt_or_eq x n); auto with zarith.\n  intros HH3; subst x; auto.\n  case (Z_lt_dec 1 x); intros HH1.\n  right; exists x; split; auto with zarith.\n  left; intros n [HHH1 HHH2]; contradict HHH1; auto with zarith.\n  right; destruct E as (n,((H0,H2),H3)); exists n; auto with zarith.\nDefined.\n\nDefinition prime_dec: forall p, { prime p }+{ ~ prime p }.\nProof.\n  intros p; case (Z_lt_dec 1 p); intros H1.\n  case (prime_dec_aux p p); intros H2.\n  left; apply prime_intro; auto.\n  intros n [Hn1 Hn2]; case Zle_lt_or_eq with ( 1 := Hn1 ); auto.\n  intros HH; subst n.\n  red; apply Zis_gcd_intro; auto with zarith.\n  right; intros H3; inversion_clear H3 as [Hp1 Hp2].\n  case H2; intros n [Hn1 Hn2]; case Hn2; auto with zarith.\n  right; intros H3; inversion_clear H3 as [Hp1 Hp2]; case H1; auto.\nDefined.\n\nTheorem not_prime_divide:\n forall p, 1 < p -> ~ prime p -> exists n, 1 < n < p  /\\ (n | p).\nProof.\n  intros p Hp Hp1.\n  case (prime_dec_aux p p); intros H1.\n  elim Hp1; constructor; auto.\n  intros n [Hn1 Hn2].\n  case Zle_lt_or_eq with ( 1 := Hn1 ); auto with zarith.\n  intros H2; subst n; red; apply Zis_gcd_intro; auto with zarith.\n  case H1; intros n [Hn1 Hn2].\n  generalize (Zgcd_is_pos n p); intros Hpos.\n  case (Zle_lt_or_eq 0 (Zgcd n p)); auto with zarith; intros H3.\n  case (Zle_lt_or_eq 1 (Zgcd n p)); auto with zarith; intros H4.\n  exists (Zgcd n p); split; auto.\n  split; auto.\n  apply Zle_lt_trans with n; auto with zarith.\n  generalize (Zgcd_is_gcd n p); intros tmp; inversion_clear tmp as [Hr1 Hr2 Hr3].\n  case Hr1; intros q Hq.\n  case (Zle_or_lt q 0); auto with zarith; intros Ht.\n  absurd (n <= 0 * Zgcd n p) ; auto with zarith.\n  pattern n at 1; rewrite Hq; auto with zarith.\n  apply Zle_trans with (1 * Zgcd n p); auto with zarith.\n  pattern n at 2; rewrite Hq; auto with zarith.\n  generalize (Zgcd_is_gcd n p); intros Ht; inversion Ht; auto.\n  case Hn2; red.\n  rewrite H4; apply Zgcd_is_gcd.\n  generalize (Zgcd_is_gcd n p); rewrite <- H3; intros tmp;\n  inversion_clear tmp as [Hr1 Hr2 Hr3].\n  absurd (n = 0); auto with zarith.\n  case Hr1; auto with zarith.\nQed.\n\n(** A Generalized Gcd that also computes Bezout coefficients.\n   The algorithm is the same as for Zgcd. *)\n\nOpen Scope positive_scope.\n\nFixpoint Pggcdn (n: nat) (a b : positive) : (positive*(positive*positive)) :=\n  match n with\n    | O => (1,(a,b))\n    | S n =>\n      match a,b with\n\t| xH, b => (1,(1,b))\n\t| a, xH => (1,(a,1))\n\t| xO a, xO b =>\n           let (g,p) := Pggcdn n a b in\n           (xO g,p)\n\t| a, xO b =>\n           let (g,p) := Pggcdn n a b in\n           let (aa,bb) := p in\n           (g,(aa, xO bb))\n\t| xO a, b =>\n           let (g,p) := Pggcdn n a b in\n           let (aa,bb) := p in\n           (g,(xO aa, bb))\n\t| xI a', xI b' =>\n           match Pcompare a' b' Eq with\n\t     | Eq => (a,(1,1))\n\t     | Lt =>\n\t        let (g,p) := Pggcdn n (b'-a') a in\n\t        let (ba,aa) := p in\n\t        (g,(aa, aa + xO ba))\n\t     | Gt =>\n\t\tlet (g,p) := Pggcdn n (a'-b') b in\n\t\tlet (ab,bb) := p in\n\t\t(g,(bb+xO ab, bb))\n\t   end\n      end\n  end.\n\nDefinition Pggcd (a b: positive) := Pggcdn (Psize a + Psize b)%nat a b.\n\nOpen Scope Z_scope.\n\nDefinition Zggcd (a b : Z) : Z*(Z*Z) :=\n  match a,b with\n    | Z0, _ => (Zabs b,(0, Zsgn b))\n    | _, Z0 => (Zabs a,(Zsgn a, 0))\n    | Zpos a, Zpos b =>\n       let (g,p) := Pggcd a b in\n       let (aa,bb) := p in\n       (Zpos g, (Zpos aa, Zpos bb))\n    | Zpos a, Zneg b =>\n       let (g,p) := Pggcd a b in\n       let (aa,bb) := p in\n       (Zpos g, (Zpos aa, Zneg bb))\n    | Zneg a, Zpos b =>\n       let (g,p) := Pggcd a b in\n       let (aa,bb) := p in\n       (Zpos g, (Zneg aa, Zpos bb))\n    | Zneg a, Zneg b =>\n       let (g,p) := Pggcd a b in\n       let (aa,bb) := p in\n       (Zpos g, (Zneg aa, Zneg bb))\n  end.\n\n\nLemma Pggcdn_gcdn : forall n a b,\n  fst (Pggcdn n a b) = Pgcdn n a b.\nProof.\n  induction n.\n  simpl; auto.\n  destruct a; destruct b; simpl; auto.\n  destruct (Pcompare a b Eq); simpl; auto.\n  rewrite <- IHn; destruct (Pggcdn n (b-a) (xI a)) as (g,(aa,bb)); simpl; auto.\n  rewrite <- IHn; destruct (Pggcdn n (a-b) (xI b)) as (g,(aa,bb)); simpl; auto.\n  rewrite <- IHn; destruct (Pggcdn n (xI a) b) as (g,(aa,bb)); simpl; auto.\n  rewrite <- IHn; destruct (Pggcdn n a (xI b)) as (g,(aa,bb)); simpl; auto.\n  rewrite <- IHn; destruct (Pggcdn n a b) as (g,(aa,bb)); simpl; auto.\nQed.\n\nLemma Pggcd_gcd : forall a b, fst (Pggcd a b) = Pgcd a b.\nProof.\n  intros; exact (Pggcdn_gcdn (Psize a+Psize b)%nat a b).\nQed.\n\nLemma Zggcd_gcd : forall a b, fst (Zggcd a b) = Zgcd a b.\nProof.\n  destruct a; destruct b; simpl; auto; rewrite <- Pggcd_gcd;\n    destruct (Pggcd p p0) as (g,(aa,bb)); simpl; auto.\nQed.\n\nOpen Scope positive_scope.\n\nLemma Pggcdn_correct_divisors : forall n a b,\n  let (g,p) := Pggcdn n a b in\n  let (aa,bb):=p in\n  (a=g*aa) /\\ (b=g*bb).\nProof.\n  induction n.\n  simpl; auto.\n  destruct a; destruct b; simpl; auto.\n  case_eq (Pcompare a b Eq); intros.\n  (* Eq *)\n  rewrite Pmult_comm; simpl; auto.\n  rewrite (Pcompare_Eq_eq _ _ H); auto.\n  (* Lt *)\n  generalize (IHn (b-a) (xI a)); destruct (Pggcdn n (b-a) (xI a)) as (g,(ba,aa)); simpl.\n  intros (H0,H1); split; auto.\n  rewrite Pmult_plus_distr_l.\n  rewrite Pmult_xO_permute_r.\n  rewrite <- H1; rewrite <- H0.\n  simpl; f_equal; symmetry.\n  apply Pplus_minus; auto.\n  rewrite ZC4; rewrite H; auto.\n  (* Gt *)\n  generalize (IHn (a-b) (xI b)); destruct (Pggcdn n (a-b) (xI b)) as (g,(ab,bb)); simpl.\n  intros (H0,H1); split; auto.\n  rewrite Pmult_plus_distr_l.\n  rewrite Pmult_xO_permute_r.\n  rewrite <- H1; rewrite <- H0.\n  simpl; f_equal; symmetry.\n  apply Pplus_minus; auto.\n  (* Then... *)\n  generalize (IHn (xI a) b); destruct (Pggcdn n (xI a) b) as (g,(ab,bb)); simpl.\n  intros (H0,H1); split; auto.\n  rewrite Pmult_xO_permute_r; rewrite H1; auto.\n  generalize (IHn a (xI b)); destruct (Pggcdn n a (xI b)) as (g,(ab,bb)); simpl.\n  intros (H0,H1); split; auto.\n  rewrite Pmult_xO_permute_r; rewrite H0; auto.\n  generalize (IHn a b); destruct (Pggcdn n a b) as (g,(ab,bb)); simpl.\n  intros (H0,H1); split; subst; auto.\nQed.\n\nLemma Pggcd_correct_divisors : forall a b,\n  let (g,p) := Pggcd a b in\n  let (aa,bb):=p in\n  (a=g*aa) /\\ (b=g*bb).\nProof.\n  intros a b; exact (Pggcdn_correct_divisors (Psize a + Psize b)%nat a b).\nQed.\n\nClose Scope positive_scope.\n\nLemma Zggcd_correct_divisors : forall a b,\n  let (g,p) := Zggcd a b in\n  let (aa,bb):=p in\n  (a=g*aa) /\\ (b=g*bb).\nProof.\n  destruct a; destruct b; simpl; auto; try solve [rewrite Pmult_comm; simpl; auto];\n    generalize (Pggcd_correct_divisors p p0); destruct (Pggcd p p0) as (g,(aa,bb));\n      destruct 1; subst; auto.\nQed.\n\nTheorem Zggcd_opp: forall x y,\n  Zggcd (-x) y = let (p1,p) := Zggcd x y in\n                 let (p2,p3) := p in\n                 (p1,(-p2,p3)).\nProof.\nintros [|x|x] [|y|y]; unfold Zggcd, Zopp; auto.\ncase Pggcd; intros p1 (p2, p3); auto.\ncase Pggcd; intros p1 (p2, p3); auto.\ncase Pggcd; intros p1 (p2, p3); auto.\ncase Pggcd; intros p1 (p2, p3); auto.\nQed.\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/theories/ZArith/Znumtheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7208711830366132}}
{"text": "Require Omega.   \nRequire Export Bool.\nRequire Export List.\nExport ListNotations.\nRequire Export Arith.\nRequire Export Arith.EqNat.\n\nInductive tree : Set :=\n  leaf : tree\n| node : forall (n : nat) (left right : tree), tree.\n\nInductive lt_tree : nat -> tree -> Prop :=\n  lt_leaf : forall (n   : nat), lt_tree n leaf\n| lt_node : forall (n m : nat) (l r : tree), \n   m < n -> lt_tree n l -> lt_tree n r -> lt_tree n (node m l r).\n\nInductive gt_tree : nat -> tree -> Prop :=\n  gt_leaf : forall (n   : nat), gt_tree n leaf\n| gt_node : forall (n m : nat) (l r : tree), \n   m > n -> gt_tree n l -> gt_tree n r -> gt_tree n (node m l r).\n\nInductive is_search_tree : tree -> Prop :=\n  st_leaf : is_search_tree leaf\n| st_node : forall (n : nat) (l r : tree), \n   lt_tree n l -> gt_tree n r -> is_search_tree l -> is_search_tree r -> \n   is_search_tree (node n l r).\n\nInductive contains : nat -> tree -> Prop :=\n  root_contains : forall (n : nat) (l r : tree), contains n (node n l r)\n| left_contains : forall (n m : nat) (l r : tree), \n   contains n l -> contains n (node m l r)\n| right_contains : forall (n m : nat) (l r : tree), \n   contains n r -> contains n (node m l r).\n\nHint Constructors lt_tree gt_tree is_search_tree contains.\n\nLemma rt_contains: forall (n m : nat), contains m (node n leaf leaf) -> m = n.\nProof. intros. inversion H; try omega; inversion H2. Qed.\n\nLemma gt_contains : forall (t : tree) (n : nat), \n  (forall m, contains m t -> m > n) -> gt_tree n t.\nProof. intros. induction t; auto. Qed.\n\nLemma lt_contains : forall (t : tree) (n : nat),\n  (forall m, contains m t -> m < n) -> lt_tree n t.\nProof. intros. induction t; auto. Qed.\n\nLemma left_lt : forall (n m : nat) (l r : tree), \n  is_search_tree (node n l r) -> contains m l -> m < n.\nProof.\n  intros. induction l. inversion H0. \n    inversion H. inversion H0. inversion H4. omega.\n      apply IHl1. apply st_node. \n       inversion H4. assumption. assumption.\n       inversion H6. assumption. assumption. assumption.\n      apply IHl2. apply st_node. \n       inversion H4. assumption. assumption.\n       inversion H6. assumption. assumption. assumption.\nQed.\n\nLemma right_gt : forall (n m : nat) (l r : tree), \n  is_search_tree (node n l r) -> contains m r -> m > n.\nProof. \n  intros. induction r. inversion H0. \n    inversion H. inversion H0. inversion H5. omega.\n      apply IHr1. apply st_node. assumption.\n       inversion H5. assumption. assumption. \n       inversion H7. assumption. assumption. \n      apply IHr2. apply st_node. assumption.\n       inversion H5. assumption. assumption.\n       inversion H7. assumption. assumption.\nQed.\n\nDefinition add_in_search_tree : forall (t : tree) (n : nat),\n  is_search_tree t -> \n  {t' | is_search_tree t' & \n        (forall (m : nat), contains m t' <-> m = n \\/ contains m t)\n  }.\nProof.\n  intros. induction t. \n    exists (node n leaf leaf). \n       auto. intros. split. intros. left. \n       apply rt_contains in H0. assumption. \n       intros. inversion H0. rewrite H1. auto. inversion H1.    \n    assert (L: is_search_tree t1). inversion H. auto.\n    assert (LT: lt_tree n0 t1). inversion H. auto.\n    assert (R: is_search_tree t2). inversion H. auto.\n    assert (GT: gt_tree n0 t2). inversion H. auto.\n    remember (lt_eq_lt_dec n n0) as B. \n      inversion B. inversion H0. \n        apply IHt1 in L. inversion L. \n          exists (node n0 x t2).\n            apply st_node. apply lt_contains. intros. apply H3 in H4. \n                inversion H4. omega. apply (left_lt n0 m t1 t2); assumption.\n              assumption. assumption. assumption.\n            intros. split. intros. \n              inversion H4. right. auto. \n                apply H3 in H7. inversion H7. left. assumption. right. auto. right. auto.\n            intros. inversion H4. rewrite H5.\n              apply left_contains. apply H3. left. reflexivity.\n              inversion H5. auto. apply left_contains. apply H3. right. assumption.\n                apply right_contains. assumption.\n        exists (node n0 t1 t2). assumption. \n          intros. split. intros. right. assumption. intros. inversion H2.\n            rewrite <- H1. rewrite H3. auto. assumption.\n        apply IHt2 in R. inversion R.\n          exists (node n0 t1 x).\n            apply st_node. assumption. apply gt_contains. intros. apply H2 in H3.\n                inversion H3. omega. apply (right_gt n0 m t1 t2); assumption.  \n              assumption. assumption.\n            intros. split. intros. \n              inversion H3. right. auto.\n                right. apply left_contains. assumption. \n                apply H2 in H6. inversion H6. left. assumption. right. \n                apply right_contains. assumption.\n            intros. inversion H3. apply right_contains. apply H2. left. assumption.\n                inversion H4. auto. apply left_contains. assumption.\n                apply right_contains. apply H2. right. assumption.\nQed.\n\nLemma contains_in_lt n t : lt_tree n t -> forall x, contains x t -> n > x.\nProof. intros H; induction H; intros x Hi; inversion Hi; auto. Qed.\n\nLemma lt_insert x n (t : tree) (t' : tree) :\n     n < x -> lt_tree x t ->\n     (forall m, contains m t' -> m = n \\/ contains m t) ->\n     is_search_tree t' -> lt_tree x t'.\nProof.\n  intros. apply lt_contains. intros.\n    apply H1 in H3; destruct H3.\n      rewrite H3; auto.\n        apply (contains_in_lt x t); auto.\nQed.\n\nLemma contains_in_gt n t : gt_tree n t -> forall x, contains x t -> n < x.\nProof. intros H; induction H; intros x Hi; inversion Hi; auto. Qed.\n\nLemma gt_insert x n (t : tree) (t' : tree) :\n     n > x -> gt_tree x t ->\n     (forall m, contains m t' -> m = n \\/ contains m t) ->\n     is_search_tree t' -> gt_tree x t'.\nProof.\n  intros. apply gt_contains. intros.\n    apply H1 in H3; destruct H3.\n      rewrite H3; auto.\n        apply (contains_in_gt x t); auto.\nQed.\n\nProgram Fixpoint add_in_search_tree_prog (t : tree) (n : nat) :\n    is_search_tree t ->\n    {t' | is_search_tree t' /\\\n          (forall (m : nat), contains m t' <-> m = n \\/ contains m t)\n    } := fun H => \n  match t with\n  | leaf       => node n leaf leaf\n  | node x l r => match (lt_eq_lt_dec n x) with\n                  | inleft LE => \n                    if LE\n                    then let: nl := add_in_search_tree_prog l n _ in\n                         node x nl r\n                    else t\n                  | inright GT =>\n                         let: nr := add_in_search_tree_prog r n _ in\n                         node x l nr\n                  end\n  end.\nNext Obligation.\nsplit; auto.\n  intros m; clear H.\n    split; intros H; inversion H; auto.\n      rewrite H0; auto.\nQed.\nNext Obligation. inversion H; auto. Qed.\nNext Obligation.\n  clear LE Heq_anonymous.\n    split.\n      apply st_node; inversion H; auto.\n        apply (lt_insert x n l x0); auto.\n          apply i0.\n      intros m; split.\n        intros X; inversion X; auto.\n          apply (proj1 (i0 m)) in H3.\n            inversion H3; auto.\n        intros X; destruct X.\n          assert (m = n \\/ contains m l) as H2; auto.\n            apply (i0 m) in H2; auto.\n          inversion H1; auto.\n            apply left_contains.\n              apply i0; auto.\nDefined.\nNext Obligation.\nclear LE Heq_anonymous.\n  split; auto.\n    intros m; split; intros X; inversion X; auto.\n      rewrite H0; auto.      \nQed.      \nNext Obligation. inversion H; auto. Qed.              \nNext Obligation.        \n  clear Heq_anonymous.\n    split.\n      apply st_node; inversion H; auto.    \n        apply (gt_insert x n r x0); auto.\n          apply i0.\n      intros m; split.\n        intros X; inversion X; auto.\n          apply (proj1 (i0 m)) in H2.\n            inversion H2; auto.\n        intros X; destruct X.\n          assert (m = n \\/ contains m r) as H2; auto.\n            apply (i0 m) in H2; auto.\n          inversion H0; auto.\n            apply right_contains.\n              apply i0; auto.\nDefined.  \n\nFixpoint height (t: tree) : nat := \n  match t with\n  | leaf => 0\n  | node _ l r => 1 + max (height l) (height r)\n  end.\n\nFixpoint add_in_search_tree_fun t n :=\n  match t with\n  | leaf       => node n leaf leaf\n  | node x l r => match (lt_eq_lt_dec n x) with\n                  | inleft LE => \n                    if LE\n                    then let: nl := add_in_search_tree_fun l n in\n                         node x nl r\n                    else t\n                  | inright _ =>\n                         let: nr := add_in_search_tree_fun r n in\n                         node x l nr\n                  end\n  end.\n\nLemma add_fun_contains : forall t m x,\n  contains m (add_in_search_tree_fun t x) <-> m = x \\/ contains m t.\nProof.\ninduction t.\n  intros m x; split; intros H; simpl in H; simpl.\n    left. inversion H; auto; inversion H2.\n    destruct H. rewrite H; auto.\n      inversion H.    \n  intros m x; unfold add_in_search_tree_fun; split; destruct (lt_eq_lt_dec x n); intros H.\n    destruct s; fold add_in_search_tree_fun in H; auto.\n      inversion H. right; auto. \n        apply IHt1 in H2. destruct H2. left; auto.\n          right. constructor; auto.\n        right; apply right_contains; auto.\n    fold add_in_search_tree_fun in H.\n      inversion H. right; auto.\n        right; constructor; auto.\n        apply IHt2 in H2; destruct H2; auto.\n    destruct s; fold add_in_search_tree_fun; destruct H; auto;\n        specialize (IHt1 m x); destruct IHt1; auto.\n      inversion H; auto. rewrite <- e, H; auto. \n    fold add_in_search_tree_fun; destruct H.\n      apply right_contains; apply IHt2; auto.\n      inversion H; auto.    \n        apply right_contains; apply IHt2; auto.\nQed.\n\nTheorem add_in_search_tree_fun_correct : forall (t : tree) (n : nat),\n  is_search_tree t -> \n  is_search_tree (add_in_search_tree_fun t n) /\\ \n  (forall (m : nat), contains m (add_in_search_tree_fun t n) <-> m = n \\/ contains m t).\nProof.\ninduction t.\n  intros n _; split. constructor; auto. \n    intros m; split. apply add_fun_contains.\n      intros H; destruct H; simpl. rewrite H; auto.\n        inversion H; auto.\n  intros x H; split.\n    unfold add_in_search_tree_fun. destruct (lt_eq_lt_dec x n).\n      destruct s; fold add_in_search_tree_fun; auto. constructor; inversion H; auto.\n        apply lt_contains. intros m HcontM.  \n          apply add_fun_contains in HcontM. destruct HcontM.\n            rewrite H7; auto.\n            apply (left_lt _ _ _ _ H H7). \n        apply (IHt1 x) in H5. destruct H5; auto.\n      fold add_in_search_tree_fun. constructor; inversion H; auto.\n        apply gt_contains. intros m HcontM.\n            apply add_fun_contains in HcontM. destruct HcontM.\n              rewrite H7; auto.\n              apply (right_gt _ _ _ _ H H7). \n          apply (IHt2 x) in H6. destruct H6; auto.\n    intros m. apply add_fun_contains.\nQed.", "meta": {"author": "dboulytchev", "repo": "direct-curry-howard", "sha": "3e73befad8ccd701eabe3469468b4857f4ea6890", "save_path": "github-repos/coq/dboulytchev-direct-curry-howard", "path": "github-repos/coq/dboulytchev-direct-curry-howard/direct-curry-howard-3e73befad8ccd701eabe3469468b4857f4ea6890/Bitree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7208637031507755}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (x : natural) : natural := plus (mult x z) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj236_coqofml_56LHkW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.720858143202124}}
{"text": "Variable A B C : Prop.\n\nTheorem syll : (A -> B) -> (B -> C) -> A -> C. \nProof.\n  intros.\n  apply H0.\n  apply H.\n  assumption.\nQed.\n\nAxiom classic : forall P : Prop, (P \\/ ~P).\n\nTheorem doubleng : ~~A -> A.\nProof.\n  intro.\n  elim (classic A).\n  intro. assumption.\n  intro.\n  contradict H.\n  assumption.\nQed.\n\nTheorem ex4: forall A : Prop, A -> ~ ~ A.\nProof.\n  intro.\n  intro.\n  contradict H.\n  assumption.\nQed.\n\nTheorem ex7: forall (a b : Type) (p : Type -> Prop), p a \\/ p b -> exists x : Type, p x.\nProof.\n  intro.\n  intro.\n  intro.\n  intro.\n  elim H.\n  intro.\n  exists a. assumption.\n  intro.\n  exists b. assumption.\nQed.\n\nTheorem ex3: forall A B C D: Prop, (A -> C) /\\ (B -> D) -> A /\\ B -> C /\\ D.\nProof.\n  intros.\n  elim H.\n  elim H0.\n  intros.\n  split.\n  apply H3.\n  exact H1.\n  apply H4.\n  exact H2.\nQed.\n\nTheorem ex8: forall (A : Set) (R : A -> A -> Prop),\n    (forall x y z : A, R x y /\\ R y z -> R x z) ->\n    (forall x y : A, R x y -> R y x) -> forall x : A, (exists y : A, R x y) -> R x x.\nProof.\n  intros.\n  elim H1. intros.\n  apply H0.\n  apply H with x0.  \n  split.\n  exact H2.\n  apply H0.      \n  exact H2.  \nQed.\n\nPrint ex8.\n\n\n", "meta": {"author": "polywind", "repo": "MsuCoqTasks", "sha": "100ee40df7ffb26f1bcf81ebc7ac750563852c7e", "save_path": "github-repos/coq/polywind-MsuCoqTasks", "path": "github-repos/coq/polywind-MsuCoqTasks/MsuCoqTasks-100ee40df7ffb26f1bcf81ebc7ac750563852c7e/1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7208581388121965}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult (Succ x) (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj203_coqofml_4GvgKl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7208240633001476}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (x : natural) : natural :=\n  mult (Succ y) (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_succ/goal33conj142_coqofml_wQ1Q2c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7208240489588521}}
{"text": "(* \n    This file covers definitions and \n    proofs regarding boolean values\n*)\n\nInductive bool : Type :=\n| true\n| false.\n\nDefinition eqb (b_1 b_2 : bool) : bool :=\n    match b_1 with\n    | true => match b_2 with\n        | true => true\n        | false => false\n        end\n    | false => match b_2 with\n        | true => false\n        | false => true\n        end\n    end.\n\nExample eqb_f_f: eqb false false = true.\nProof. reflexivity. Qed.\nExample eqb_t_f: eqb true false = false.\nProof. reflexivity. Qed.\nExample eqb_f_t: eqb false true = false.\nProof. reflexivity. Qed.\nExample eqb_t_t: eqb true true = true.\nProof. reflexivity. Qed.\n\nDefinition notb (b : bool) : bool :=\n    match b with \n    | true => false\n    | false => true\n    end.\n\nExample notb_f: notb false = true.\nProof. reflexivity. Qed.\nExample notb_t: notb true = false.\nProof. reflexivity. Qed.\n\nDefinition andb (b_1 b_2 : bool) : bool :=\n    match b_1 with\n    | true => match b_2 with \n        | true => true\n        | false => false\n        end\n    | false => false\n    end.\n\nNotation \"x && y\" := (andb x y).\n\nExample andb_f_f: andb false false = false.\nProof. reflexivity. Qed.\nExample andb_t_f: andb true false = false.\nProof. reflexivity. Qed.\nExample andb_f_t: andb false true = false.\nProof. reflexivity. Qed.\nExample andb_t_t: andb true true = true.\nProof. reflexivity. Qed.\n\nTheorem b_and_b_is_b : forall (b : bool),\n    b && b = b.\nProof.\n    intros b. destruct b.\n    - reflexivity.\n    - reflexivity.\nQed.\n\nDefinition orb (b_1 b_2 : bool) : bool := \n    match b_1 with \n    | true => true\n    | false => b_2\n    end.\n\nExample orb_f_f: orb false false = false.\nProof. reflexivity. Qed.\nExample orb_t_f: orb true false = true.\nProof. reflexivity. Qed.\nExample orb_f_t: orb false true = true.\nProof. reflexivity. Qed.\nExample orb_t_t: orb true true = true.\nProof. reflexivity. Qed.\n\nNotation \"x || y\" := (orb x y).\n\nDefinition xorb (b_1 b_2 : bool) : bool :=\n    match b_1 with \n    | true => match b_2 with\n        | true => false\n        | false => true\n        end\n    | false => match b_2 with\n        | true => true\n        | false => false\n        end\n    end.\n\nExample xorb_f_f: xorb false false = false.\nProof. reflexivity. Qed.\nExample xorb_t_f: xorb true false = true.\nProof. reflexivity. Qed.\nExample xorb_f_t: xorb false true = true.\nProof. reflexivity. Qed.\nExample xorb_t_t: xorb true true = false.\nProof. reflexivity. Qed.\n\nTheorem A_implies_A : forall A : Prop, \n    A -> A.\nProof.\n    intros A. intros H. exact H.\nQed.\n", "meta": {"author": "CharlesAverill", "repo": "CoqPhysicsExperiments", "sha": "0ae3eb452ef465d5e07dbfb2c4c0c6b1d51f194b", "save_path": "github-repos/coq/CharlesAverill-CoqPhysicsExperiments", "path": "github-repos/coq/CharlesAverill-CoqPhysicsExperiments/CoqPhysicsExperiments-0ae3eb452ef465d5e07dbfb2c4c0c6b1d51f194b/Scalars/Booleans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7208065856938914}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Category.Composable_Chain.\nRequire Import Functor.Functor.\n\n\n(** The image of a functor is not simply the image of its object and arrow maps as\nthose may not form a category. Consider the following example.\n\n  category C:\n#\n<pre>\n             f\n       x1 ——————–> y1\n\n       x2 ——————–> y2\n             g\n</pre>\n#\n   category D:\n#\n<pre>\n             h1        h2  \n       x ——————–> y ————————> z\n\n       u ——————–> v\n            m\n</pre>\n#\n    functor F where:\n#\n<pre>\n       F _o x1 = x\n       F _o y1 = y\n       F _o x2 = y\n       F _o y2 = z\n\n       F _a f = h1\n       F _a g = h2\n</pre>\n#\n\nHere we have not drawn identity arrows and compositions of arrows in categories and\ntheir mappings by the functor as these are trivial details.\n\nIn this case, the simple image of arrow map of F has only h1 and h2 but not their\ncomposition and is hence not a category.\n\nWe define the image of a functor to be a sum category of the codomain category with\nobjects the image of object map of the functor and as morphisms image of the arrow\nmap of the functor closed under composition. That is, each morphism in the image\ncategory is a morphism that corresponds to a composable chain of morohisms in the\nimage of the arrow map of the functor.\n\n*)\nSection Functor_Image.\n  Context {C D : Category}\n          (F : (C –≻ D)%functor).\n\n  Local Open Scope morphism_scope.\n\n  Program Definition Functor_Image :=\n    SubCategory D\n                (fun a => ∃ x, (F _o x)%object = a)\n                (\n                  fun a b f =>\n                    ∃ (ch : Composable_Chain D a b),\n                      (Compose_of ch) = f\n                      ∧\n                      Forall_Links ch (\n                                     fun x y g =>\n                                     ∃ (c d : Obj) (h : c –≻ d)\n                                       (Fca : (F _o c)%object = x)\n                                       (Fdb : (F _o d)%object = y),\n                                       match Fca in (_ = Z) return Z –≻ _ with\n                                         eq_refl =>\n                                         match Fdb in (_ = Y) return _ –≻ Y with\n                                           eq_refl => (F _a h)%morphism\n                                         end\n                                       end = g)\n                )\n                _ _.\n\n  Ltac destr_exists :=\n    progress\n    (repeat\n       match goal with\n         [H : ∃ x, _ |- _] =>\n         let x := fresh \"x\" in\n         let Hx := fresh \"H\" x in\n         destruct H as [x Hx]\n       end).\n  \n  Next Obligation. (* Hom_Cri_id *)\n  Proof.\n    destr_exists.\n    ElimEq.\n    exists (Single (F _a id)); simpl; split; auto.\n    do 3 eexists; do 2 exists eq_refl; reflexivity.\n  Qed.\n\n  Next Obligation. (* Hom_Cri_compose *)\n  Proof.\n    destr_exists.\n    intuition.\n    ElimEq.\n    match goal with\n        [ch1 : Composable_Chain _ ?a ?b, ch2 : Composable_Chain _ ?b ?c|- _] =>\n        exists (Chain_Compose ch1 ch2); split\n    end.\n    rewrite <- Compose_of_Chain_Compose; trivial.\n    apply Forall_Links_Chain_Compose; auto.\n  Qed.\n\nEnd Functor_Image.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Functor/Functor_Image.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7208065824361231}}
{"text": "Require Import HoTT.Basics HoTT.Types UnivalenceImpliesFunext.\nRequire Import Truncations.\nRequire Import HIT.Coeq.\nRequire Import Algebra.Group.\nRequire Import Algebra.Subgroup.\nRequire Import Cubical.\nImport TrM.\n\nLocal Open Scope mc_mult_scope.\n\n(** * Abelian groups *)\n\n(** Definition of an abelian group *)\n\nClass AbGroup := {\n  abgroup_type : Type;\n  abgroup_sgop :> SgOp abgroup_type;\n  abgroup_unit :> MonUnit abgroup_type;\n  abgroup_inverse :> Negate abgroup_type;\n  abgroup_isabgroup :> IsAbGroup abgroup_type;\n}.\n\n(** We want abelian groups to be coerced to the underlying type. *)\nCoercion abgroup_type : AbGroup >-> Sortclass.\n\n(** The underlying group of an abelian group. *)\nDefinition group_abgroup : AbGroup -> Group.\nProof.\n  intros [G ? ? ? [l ?]].\n  ntc_rapply (Build_Group G _ _ _ l).\nDefined.\n\n(** We also want abelian groups to be coerced to the underlying group. *)\nCoercion group_abgroup : AbGroup >-> Group.\n\n(** Definition of Abelianization.\n\n  Given a map F that turns any group into an abelian group, and a unit homomorphism eta_X : X -> F X. This data is considered an Abelianization if and only if for all maps X -> A, there exists a unique g such that h == g o eta X. *)\nDefinition IsAbelianization {G : Group} (G_ab : AbGroup)\n  (eta : GroupHomomorphism G G_ab)\n  := forall (A : AbGroup) (h : GroupHomomorphism G A),\n    Contr (exists (g : GroupHomomorphism G_ab A), h == g o eta).\n\nExisting Class IsAbelianization.\n\n(** Here we define abelianization as a HIT. Specifically as a set-coequalizer of the following to maps: (a, b, c) |-> a (b c) and (a, b, c) |-> a (c b).\n\nFrom this we can show that Abel G is an abelian group.\n\nIn fact this models the following HIT:\n\nHIT Abel (G : Group) := \n | ab : G -> Abel G\n | ab_comm : forall x y z, ab (x * (y * z)) = ab (x * (z * y)).\n\nWe also derive ab and ab_comm from our coequalizer definition, and even prove the induction and computation rules for this HIT.\n\nThis HIT was suggested by Dan Christensen.\n*)\n\nSection Abel.\n\n  (** Let G be a group. *)\n  Context (G : Group).\n\n  (** We locally define a map uncurry2 that lets us uncurry A * B * C -> D twice. *)\n  Local Definition uncurry2 {A B C D : Type}\n    : (A -> B -> C -> D) -> A * B * C -> D.\n  Proof.\n    intros f [[a b] c].\n    by apply f.\n  Defined.\n\n  (** The type Abel is defined to be the set coequalizer of the following maps G^3 -> G. *)\n  Definition Abel\n    := Tr 0 (Coeq\n      (uncurry2 (fun a b c => a * (b * c)))\n      (uncurry2 (fun a b c => a * (c * b)))).\n\n  (** We have a natural map from G to Abel G *)\n  Definition ab : G -> Abel.\n  Proof.\n    intro g.\n    apply tr, coeq, g.\n  Defined.\n\n  (** This map has to satisfy the condition ab_comm *)\n  Definition ab_comm a b c\n    : ab (a * (b * c)) = ab (a * (c * b)).\n  Proof.\n    apply (ap tr).\n    exact (cglue (a, b, c)).\n  Defined.\n\n  (** It is clear that Abel is a set. *)\n  Global Instance istrunc_abel : IsHSet Abel := _.\n\n  (** We can derive the induction principle from the ones for truncation and the coequalizer. *)\n  Definition Abel_ind (P : Abel -> Type) `{forall x, IsHSet (P x)} \n    (a : forall x, P (ab x)) (c : forall x y z, DPath P (ab_comm x y z)\n      (a (x * (y * z))) (a (x * (z * y))))\n    : forall (x : Abel), P x.\n  Proof.\n    serapply Trunc_ind.\n    serapply Coeq_ind.\n    1: apply a.\n    intros [[x y] z].\n    refine (transport_compose _ _ _ _ @ _).\n    serapply dp_path_transport^-1.\n    apply c.\n  Defined.\n\n  (** The computation rule can also be prove. *)\n  Definition Abel_ind_beta_ab_comm (P : Abel -> Type)\n    `{forall x, IsHSet (P x)}(a : forall x, P (ab x))\n    (c : forall x y z, DPath P (ab_comm x y z)\n      (a (x * (y * z))) (a (x * (z * y))))\n    (x y z : G) : dp_apD (Abel_ind P a c) (ab_comm x y z) = c x y z.\n  Proof.\n    unfold ab_comm.\n    apply dp_apD_path_transport.\n    rewrite (apD_compose' tr).\n    rewrite (Coeq_ind_beta_cglue _ _ _ (x, y, z)).\n    unfold Abel_ind.\n    refine (_ @ concat_1p _).\n    refine (concat_p_pp _ _ _ @ _).\n    apply whiskerR.\n    apply concat_Vp.\n  Defined.\n\n  (** We also have a recursion princple. *)\n  Definition Abel_rec (P : Type) `{IsHSet P} (a : G -> P)\n    (c : forall x y z, a (x * (y * z)) = a (x * (z * y)))\n    : Abel -> P.\n  Proof.\n    apply (Abel_ind _ a).\n    intros; apply dp_const, c.\n  Defined.\n\n  (** Here is a simpler version of Abel_ind when our target is a HProp. This lets us discard all the higher paths. *)\n  Definition Abel_ind_hprop (P : Abel -> Type) `{forall x, IsHProp (P x)} \n    (a : forall x, P (ab x)) : forall (x : Abel), P x.\n  Proof.\n    serapply (Abel_ind _ a).\n    intros; apply dp_path_transport.\n    apply path_ishprop.\n  Defined.\n\n  (** And its recursion version. *)\n  Definition Abel_rec_hprop (P : Type) `{IsHProp P}\n    (a : G -> P) : Abel -> P.\n  Proof.\n    apply (Abel_rec _ a).\n    intros; apply path_ishprop.\n  Defined.\n\nEnd Abel.\n\n(** We make sure that G is implicit in the arguments of ab and ab_comm. *)\nArguments ab {_}.\nArguments ab_comm {_}.\n\n(** Now we can show that Abel G is infact an abelian group. *)\n\nSection AbelGroup.\n\n  Context `{Funext} (G : Group).\n\n  (** Firstly we derive the operation on Abel G. This is defined as follows:\n        ab x + ab y := ab (x y)\n      But we need to also check that it preserves ab_comm in the appropriate way. *)\n  Global Instance abel_sgop : SgOp (Abel G).\n  Proof.\n    serapply Abel_rec.\n    { intro a.\n      serapply Abel_rec.\n      { intro b.\n        exact (ab (a * b)). }\n      intros b c d; cbn.\n      refine (ab_comm _ _ _ @ _).\n      refine (ap _ _ @ _).\n      { refine (ap _ (associativity _ _ _)^ @ _).\n        refine (associativity _ _ _). }\n      refine (ab_comm _ _ _ @ _).\n      refine (ap _ (associativity _ _ _)^ @ _).\n      refine (ab_comm _ _ _ @ _).\n      refine (ap _ (ap _ (associativity _ _ _)^)). }\n    intros a b c.\n    apply path_forall.\n    serapply Abel_ind_hprop.\n    cbn; intro d.\n    refine (ap _ (associativity _ _ _)^ @ _).\n    refine (ap _ (ap _ (associativity _ _ _)^) @ _).\n    refine (ab_comm _ _ _ @ _).\n    refine (ap _ (ap _ (associativity _ _ _)^) @ _).\n    refine (ap _ (associativity _ _ _) @ _).\n    refine (ab_comm _ _ _ @ _).\n    refine (ap _ (associativity _ _ _)^ @ _).\n    refine (ap _ (ap _ (associativity _ _ _)) @ _).\n    refine (ap _ (associativity _ _ _)).\n  Defined.\n\n  (** We can now easily show that this operation is associative by associativity in G and the fact that being associative is a proposition. *)\n  Global Instance abel_sgop_associative : Associative abel_sgop.\n  Proof.\n    serapply Abel_ind_hprop; intro x.\n    serapply Abel_ind_hprop; intro y.\n    serapply Abel_ind_hprop; intro z.\n    cbn; apply ap, associativity.\n  Defined.\n\n  (** From this we know that Abel G is a semigroup. *)\n  Global Instance abel_issemigroup : IsSemiGroup (Abel G) := {}.\n\n  (** We define the unit as ab of the unit of G *)\n  Global Instance abel_mon_unit : MonUnit (Abel G) := ab mon_unit.\n\n  (** By using Abel_ind_hprop we can prove the left and right identity laws. *)\n  Global Instance abel_leftidentity : LeftIdentity abel_sgop abel_mon_unit.\n  Proof.\n    serapply Abel_ind_hprop; intro x.\n    cbn; apply ap, left_identity.\n  Defined.\n\n  Global Instance abel_rightidentity : RightIdentity abel_sgop abel_mon_unit.\n  Proof.\n    serapply Abel_ind_hprop; intro x.\n    cbn; apply ap, right_identity.\n  Defined.\n\n  (** Hence Abel G is a monoid *)\n  Global Instance ismonoid_abel : IsMonoid (Abel G) := {}.\n\n  (** We can also prove that the operation is commutative! This will come in handy later. *)\n  Global Instance abel_commutative : Commutative abel_sgop.\n  Proof.\n    serapply Abel_ind_hprop; intro x.\n    serapply Abel_ind_hprop; intro y.\n    cbn.\n    rewrite <- (left_identity (x * y)).\n    rewrite <- (left_identity (y * x)).\n    apply ab_comm.\n  Defined.\n\n  (** Now we can define the negation. This is just\n        - (ab g) := (ab (g^-1) \n      However when checking that it respects ab_comm we have to show the following:\n        ab (- z * - y * - x) = ab (- y * - z * - x)\n      there is no obvious way to do this, but we note that ab (x * y) is exactly the definition of ab x + ab y! Hence by commutativity we can show this. *)\n  Global Instance abel_negate : Negate (Abel G).\n  Proof.\n    serapply Abel_rec.\n    { intro g.\n      exact (ab (-g)). }\n    intros x y z; cbn.\n    rewrite ?negate_sg_op.\n    change (ab(- z) * ab(- y) * ab (- x) = ab (- y) * ab (- z) * ab(- x)).\n    by rewrite (commutativity (ab (-z)) (ab (-y))).\n  Defined.\n\n  (** Again by Abel_ind_hprop and the corresponding laws for G we can prove the left and right inverse laws. *)\n  Global Instance abel_leftinverse : LeftInverse abel_sgop abel_negate abel_mon_unit.\n  Proof.\n    serapply Abel_ind_hprop; intro x.\n    cbn; apply ap; apply left_inverse.\n  Defined.\n\n  Instance abel_rightinverse : RightInverse abel_sgop abel_negate abel_mon_unit.\n  Proof.\n    serapply Abel_ind_hprop; intro x.\n    cbn; apply ap; apply right_inverse.\n  Defined.\n\n  (** Thus Abel G is a group *)\n  Global Instance isgroup_abel : IsGroup (Abel G) := {}.\n\n  (** And since the operation is commutative and abelian group. *)\n  Global Instance isabgroup_abel : IsAbGroup (Abel G) := {}.\n\n  (** By definition, the map ab is also a group homomorphism. *)\n  Global Instance issemigrouppreserving_ab : IsSemiGroupPreserving ab.\n  Proof.\n    by unfold IsSemiGroupPreserving.\n  Defined.\n\nEnd AbelGroup.\n\n(** We can easily prove that ab is a surjection. *)\nGlobal Instance issurj_ab `{Funext} {G : Group} : IsSurjection ab.\nProof.\n  serapply Abel_ind_hprop.\n  intro x; cbn.\n  exists (tr (x; @idpath _ (ab x))).\n  apply path_ishprop.\nDefined.\n\n(** Now we finally check that our definition of abelianization satisfies the universal property of being an abelianization. *)\nSection Abelianization.\n\n  Context `{Funext}.\n\n  (** We define abel to be the abelianization of a group. This is a map from Group to AbGroup. *)\n  Definition abel : Group -> AbGroup.\n  Proof.\n    intro G.\n    serapply (Build_AbGroup (Abel G)).\n  Defined.\n\n  (** The unit of this map is the map ab which typeclasses can pick up to be a homomorphism. We write it out explicitly here. *)\n  Definition abel_unit (X : Group)\n    : GroupHomomorphism X (abel X).\n  Proof.\n    simple notypeclasses refine (Build_GroupHomomorphism _).\n    + exact ab.\n    + exact _.\n  Defined.\n\n  (** Finally we can prove that our construction abel is an abelianization. *)\n  Global Instance isabelianization_abel {G : Group}\n    : IsAbelianization (abel G) (abel_unit G).\n  Proof.\n    intros A h.\n    serapply Build_Contr.\n    { srefine (_;_).\n      { simple notypeclasses refine (Build_GroupHomomorphism _).\n        { serapply (Abel_rec _ _ h).\n          intros x y z.\n          refine (grp_homo_op _ _ _ @ _ @ (grp_homo_op _ _ _)^).\n          apply (ap (_ *.)).\n          refine (grp_homo_op _ _ _ @ _ @ (grp_homo_op _ _ _)^).\n          apply commutativity. }\n        serapply Abel_ind_hprop; intro x.\n        serapply Abel_ind_hprop; intro y.\n        apply grp_homo_op. }\n      cbn; reflexivity. }\n    intros [g p].\n    apply path_sigma_hprop; cbn.\n    apply equiv_path_grouphomomorphism.\n    serapply Abel_ind_hprop.\n    exact p.\n  Defined.\n\nEnd Abelianization.\n\nTheorem groupiso_isabelianization {G : Group}\n  (A B : AbGroup)\n  (eta1 : GroupHomomorphism G A)\n  (eta2 : GroupHomomorphism G B)\n  {x : IsAbelianization A eta1}\n  {y : IsAbelianization B eta2}\n  : GroupIsomorphism A B.\nProof.\n  unfold IsAbelianization in x, y.\n  destruct (x B eta2) as [[a ah] ac].\n  destruct (y A eta1) as [[b bh] bc].\n  destruct (x A eta1) as [[c ch] cc].\n  destruct (y B eta2) as [[d dh] dc].\n  serapply (Build_GroupIsomorphism _ _ a).\n  serapply (isequiv_adjointify _ b).\n  { apply ap10.\n    change (@grp_homo_map _ _ (grp_homo_compose a b)\n      = @grp_homo_map _ _ grp_homo_id).\n    refine (ap (@grp_homo_map _ _) _).\n    refine (ap pr1 ((dc (_; _))^ @ dc (grp_homo_id; _))).\n    1: exact (fun i => ah i @ ap a (bh i)).\n    reflexivity. }\n  { apply ap10.\n    change (@grp_homo_map _ _ (grp_homo_compose b a)\n      = @grp_homo_map _ _ grp_homo_id).\n    refine (ap (@grp_homo_map _ _) _).\n    refine (ap pr1 ((cc (_; _))^ @ cc (grp_homo_id; _))).\n    1: exact (fun i => bh i @ ap b (ah i)).\n    reflexivity. }\nDefined.\n\nTheorem homotopic_isabelianization {G : Group} (A B : AbGroup)\n  (eta1 : GroupHomomorphism G A) (eta2 : GroupHomomorphism G B)\n  {x : IsAbelianization A eta1} {y : IsAbelianization B eta2}\n  : eta2 == grp_homo_compose (groupiso_isabelianization A B eta1 eta2) eta1.\nProof.\n  unfold IsAbelianization in x, y.\n  destruct (x B eta2) as [[a ah] ac].\n  destruct (y A eta1) as [[b bh] bc].\n  refine (transport (fun e : GroupHomomorphism A B\n    => _ == (fun x : G => e (eta1 x))) (ap pr1 (ac _)) ah).\nDefined.\n\n(** Hence any abelianization is surjective. *)\nGlobal Instance issurj_isabelianization `{Funext} {G : Group}\n  (A : AbGroup) (eta : GroupHomomorphism G A)\n  : IsAbelianization A eta -> IsSurjection eta.\nProof.\n  intros k.\n  pose (homotopic_isabelianization A (abel G) eta (abel_unit G)) as p.\n  refine (@cancelR_isequiv_conn_map _ _ _ _ _ _ _\n    (conn_map_homotopic _ _ _ p _)).\nQed.\n\nGlobal Instance isequiv_abgroup_abelianization `{U : Univalence}\n  (A B : AbGroup) (eta : GroupHomomorphism A B) {H : IsAbelianization B eta}\n  : IsEquiv eta.\nProof.\n  destruct (H A grp_homo_id) as [[a ah] ac].\n  serapply (isequiv_adjointify eta a).\n  + simpl.\n    Require HIT.epi.\n    apply ap10.\n    pose (epi.issurj_isepi eta _) as i.\n    refine (i _ _ idmap _).\n    apply path_forall.\n    intro x.\n    apply ap.\n    symmetry.\n    apply ah.\n  + change (a o eta == idmap); symmetry.\n    apply ah.\nDefined.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Algebra/AbelianGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7207030410920077}}
{"text": "(********************************************************************************)\n(* Quicksort *)\n\nFrom sortalgs Require Import sorted.\n\nOpen Scope list_scope.\nImport List.ListNotations.\n\nRequire Import Recdef.\n\nLemma lem_partition `{DecTotalOrder} :\n  forall x l1 l2, Sorted l1 -> Sorted l2 -> GeLst x l1 -> LeLst x l2 ->\n                        Sorted (l1 ++ x :: l2).\nProof.\n  induction l1.\n  - inversion 4; sauto lq: on.\n  - inversion 1; inversion 2; hauto use: lem_sorted_tail ctrs: Sorted.\nQed.\n\nFunction partition {A} {dto : DecTotalOrder A} (x : A) (l : list A)\n  {measure length l} : list A * list A :=\n  match l with\n  | [] => ([], [])\n  | h :: t =>\n    match partition x t with\n    | (t1, t2) =>\n      if leb h x then\n        (h :: t1, t2)\n      else\n        (t1, h :: t2)\n    end\n  end.\nProof.\n  sauto.\nDefined.\n\nArguments partition {_ _}.\n\nLemma lem_partition_perm `{DecTotalOrder} :\n  forall l l1 l2 x, partition x l = (l1, l2) -> Permutation l (l1 ++ l2).\nProof.\n  induction l.\n  - sauto.\n  - intros *.\n    rewrite partition_equation.\n    hauto use: Permutation_middle, @leb_total.\nQed.\n\nLemma lem_partition_parted `{DecTotalOrder} :\n  forall l l1 l2 x, partition x l = (l1, l2) -> GeLst x l1 /\\ LeLst x l2.\nProof.\n  induction l.\n  - sauto.\n  - intros *.\n    rewrite partition_equation.\n    hauto use: lem_neg_leb.\nQed.\n\nFunction qsort {A} {dto : DecTotalOrder A} (l : list A) {measure length l}\n  : list A :=\n  match l with\n  | [] => []\n  | h :: t =>\n    match partition h t with\n    | (t1, t2) => qsort t1 ++ [h] ++ qsort t2\n    end\n  end.\nProof.\n  all: intros; hauto use: lem_partition_perm, Permutation_length db: list.\nDefined.\n\nArguments qsort {_ _}.\n\nLemma lem_qsort_perm `{DecTotalOrder} :\n  forall l, Permutation l (qsort l).\nProof.\n  intro l.\n  functional induction (qsort l).\n  - sauto.\n  - hauto lq: on use: lem_partition_perm, perm_trans, perm_skip, Permutation_middle, Permutation_app.\nQed.\n\nLemma lem_qsort_sorted `{DecTotalOrder} :\n  forall l, Sorted (qsort l).\nProof.\n  intro l.\n  functional induction (qsort l).\n  - sauto.\n  - hauto lq: on use: lem_partition_parted, lem_qsort_perm, lem_gelst_perm, lem_lelst_perm, lem_partition.\nQed.\n", "meta": {"author": "lukaszcz", "repo": "sortalgs", "sha": "6e03cf693b6ed23565db0949d647efb96410ae09", "save_path": "github-repos/coq/lukaszcz-sortalgs", "path": "github-repos/coq/lukaszcz-sortalgs/sortalgs-6e03cf693b6ed23565db0949d647efb96410ae09/qsort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7207030281144186}}
{"text": "(*Require Import notations.\nRequire Import option.\nRequire Import String.*)\n\nRequire Import String.\nRequire Import List.\nImport ListNotations.\nRequire Import Datatypes.\nRequire Import Ascii.\n\nLocal Open Scope list_scope.\n\nSection list_prob.\n(* Variable A:Type.  a changer / modifier *)\n\n(* 1.01 Find the last element of a list. *)\nFixpoint last {A:Type}(l:list A): option A :=\n    match l with\n    | nil => None\n    | x :: nil => Some x\n    | _ :: y => last y\n    end. \n\nLocal Open Scope string_scope.\nExample test_last: last [\"a\";\"b\";\"c\";\"d\"] = Some \"d\".\nProof. reflexivity. Qed.\nClose Scope string_scope.\n\nTheorem last_append {A:Type}: forall (x:A) (l:list A), last(l++[x]) = Some x.\nProof.\n    intros x l.\n    induction l. \n    - reflexivity.\n    - simpl. rewrite IHl. destruct (l++[x]).\n        * (* last [] = Some x impossible *) inversion IHl.\n        * reflexivity.\nQed.\n\n\nTheorem last_rev {A:Type}: forall (x:A) (l:list A), last (List.rev (x::l)) = Some x .\nProof.\n    intros x l.\n    simpl. apply last_append.\nQed.\n\n(* 1.02 Find the last but one element of a list. *)\nFixpoint last_but_one {A:Type}(l:list A): option A :=\n    match l with\n    | nil => None\n    | x :: y :: nil => Some x\n    | _ :: y => last_but_one y\n    end.\n\nLocal Open Scope string_scope.\nExample test_last_but_one: last_but_one [\"a\";\"b\";\"c\";\"d\"] = Some \"c\".\nProof. reflexivity. Qed.\nClose Scope string_scope.\n\nTheorem last_but_one_append {A:Type}: forall (l:list A) (x:A) (y:A),\n    last_but_one (l ++ [x;y]) = Some x.\n  Proof.\n    intros l x y.\n    induction l.\n    - reflexivity.\n    - simpl. destruct (l ++ [x;y]).\n        * (* last_but_one [] = Some x impossible *) inversion IHl.\n        * rewrite IHl. destruct l0.\n            ** (* Some a = Some x impossible *) inversion IHl.\n            ** reflexivity.\n  Qed.\n\n(* 1.03 Find the K'th element of a list. *) \n(* en commencant la notation à 0 *)\nFixpoint element_at {A:Type}(l:list A)(n: nat): option A :=\n    match n, l with\n    | _, nil => None\n    | O, x :: _ => Some x\n    | S n', _ :: y => element_at y n'\n    end.\n\n(* en commencant la notation à 1 *)\nFixpoint element_at_bis {A:Type}(l:list A)(n: nat): option A :=\n    match n, l with\n    | _, nil => None\n    | O, _ => None\n    | S O, x :: _ => Some x\n    | S n', _ :: y => element_at_bis y n'\n    end.\n\nLocal Open Scope string_scope.\nExample test_element_at: element_at [\"a\";\"b\";\"c\";\"d\"] 3 = Some \"d\".\nProof. reflexivity. Qed.\n\nExample test_element_at_bis: element_at_bis [\"a\";\"b\";\"c\";\"d\"] 3 = Some \"c\".\nProof. reflexivity. Qed.\nClose Scope string_scope.\n\nTheorem element_at_bis_0 {A:Type}: forall (l:list A), element_at_bis l 0 = None.\nProof.\n    intro l. \n    case l. \n    - reflexivity.\n    - intros x l'. reflexivity.\nQed.\n\nTheorem element_at_bis_append {A:Type}: forall (l:list A) (x:A),\n    element_at_bis (l ++ [x]) (length l + 1) = Some x.\n  Proof.\n    intros l x.\n    induction l.\n    - reflexivity.\n    - simpl. destruct (length l + 1).\n        * rewrite element_at_bis_0 in IHl. (* None = Some x impossible *) inversion IHl.\n        * apply IHl.\n  Qed.\n\n(* 1.04 Find the number of elements of a list. *) \nFixpoint length2 {A:Type}(l:list A): nat :=\n    match l with\n    | nil => O\n    | _ :: y => S (length2 y)\n    end.\n\nLocal Open Scope string_scope.\nExample test_length2: length2 [\"a\";\"b\";\"c\";\"d\"] = 4.\nProof. reflexivity. Qed.\nClose Scope string_scope.\n\nTheorem length2_append {A:Type}: forall (l1 l2:list A),\n    length2 l1 + length2 l2 = length2 (l1 ++ l2).\n  Proof.\n    intros l1 l2.\n    induction l1.\n    - (* length l2 = length l2 *) reflexivity.\n    - simpl. rewrite IHl1. reflexivity.\n  Qed.\n\nTheorem length2_eq_length {A:Type}: forall (l:list A),\n  length2 l = length l.\nProof.\n  intro l.\n  induction l.\n  - (* 0=0 *) reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\n(* 1.05 Reverse a list. *) \nFixpoint rev_list {A:Type}(l:list A): list A :=\n    match l with\n    | nil => nil\n    | x :: y =>  rev_list y ++ [ x ]\n    end.\n\n(* sans utiliser ++ *)\nFixpoint rev_list_bis {A:Type}(l:list A): list A :=\n    (fix sub(l l':list A): list A :=\n    match l with\n    | nil => l'\n    | x :: y =>  sub y (x :: l')\n    end) l nil.\n\nLocal Open Scope string_scope.\nExample test_rev_list: rev_list [\"a\";\"b\";\"c\";\"d\"] = [\"d\";\"c\";\"b\";\"a\"].\nProof. reflexivity. Qed.\n\nExample test_rev_list_bis: rev_list_bis [\"a\";\"b\";\"c\";\"d\"] = [\"d\";\"c\";\"b\";\"a\"].\nProof. reflexivity. Qed.\nClose Scope string_scope.\n\nTheorem rev_list_append {A:Type}: forall (l:list A)(x:A), \nrev_list (l++[x]) = x::(rev_list l).\nProof.\n    intros l x.\n    induction l.\n    - reflexivity.\n    - simpl. rewrite IHl. reflexivity.    \nQed.\n\nTheorem rev_cons {A:Type}: forall (l:list A)(x:A), \nrev_list (x::l) = (rev_list l)++[x].\nProof.\n    intros l x.\n    case l.\n    - reflexivity.\n    - simpl. reflexivity.    \nQed.\n\nTheorem rev_list_involutive {A:Type}: forall (l:list A), \n    rev_list (rev_list l) = l.\nProof.\n    intro l.\n    induction l. \n    - reflexivity.\n    - simpl. rewrite rev_list_append. rewrite IHl. reflexivity.    \nQed.\n\nTheorem rev_eq_rev_list {A:Type}: forall (l:list A), \n    rev_list l = rev l.\nProof.\n    intro l.\n    induction l.\n    - reflexivity.\n    - simpl. rewrite IHl. reflexivity.    \nQed.\n\n(* 1.06 Find out whether a list is a palindrome. *) \nSection pal_A_dec.\nVariable A:Type. (* on crée une variable pour pouvoir indiquer que A doit être décidable *)\nHypothesis A_dec : forall x y:A, {x = y} + {x <> y}.\n\nTheorem not_x_x: forall (x:A), x <> x -> false = true.\nProof.\n    intros. pose (Bool.absurd_eq_true) as X. apply X. apply H. apply (eq_refl x).\nQed.\n\nTheorem not_x_x_bis: forall (x:A)(P:Prop), x <> x -> P.\nProof.\n    intros.\n    apply not_x_x in H. discriminate.\nQed.\n\n\nFixpoint equal_lists (l l':list A): bool :=\nmatch l, l' with\n| nil, nil => true\n| x :: y, x' :: y' => match A_dec x x' with\n                      | left _ => equal_lists y y'\n                      | right _ => false\n                      end\n| _, _ => false \nend.\n\n(* en utilisant list_eq_dec *)\nFixpoint equal_lists_bis (l l':list A): bool :=\nmatch list_eq_dec A_dec l l' with\n| left _ => true\n| right _ => false\nend.\n\nTheorem equal_lists_l_l: forall (l:list A), equal_lists l l = true .\nProof.\n    intro l. induction l. \n    - reflexivity. \n    - simpl. case (A_dec a a). \n        * intro h. apply IHl.\n        * apply not_x_x.\nQed.\n\nDefinition is_palindrome (l:list A): bool :=\n    equal_lists l (rev_list l).\n\n(* Alternativement on peut définir un type inductif *)\nInductive palindrome : list A -> Prop :=\n|Empty : palindrome nil\n|Single : forall n, palindrome [n]\n|Rcons : forall (n : A)(l : list A), palindrome l -> palindrome (n :: l ++ [n]).\nPrint is_palindrome.\n\nTheorem is_palindrome_nil: is_palindrome [] = true.\nProof.\n    unfold is_palindrome.\n    simpl. reflexivity.\nQed.\n\nTheorem equal_lists_cons: forall (x:A)(l l':list A), \n    equal_lists (x::l) (x::l') = equal_lists l l'.\nProof.\n    intros. destruct (A_dec x x).\n    - simpl. destruct (A_dec x x).\n        * reflexivity.\n        * absurd (x=x). apply n. apply e.\n    -  pose (Bool.absurd_eq_bool) as X. apply X. apply n. apply (eq_refl x). \nQed.\n\nLemma nil_cons (x:A)(l:list A)\n: not (nil=cons x l).\nintro.\ndiscriminate.\nQed.\n\nLemma nil_app (x:A)(l:list A)\n: not (nil= l++[x]).\ndestruct l. simpl. discriminate.\ndiscriminate.\nQed.\n\nTheorem palindrome_self_rev : forall (l: list A),\n  palindrome (l ++ rev l). \nProof.\n  intros. induction l.\n  - simpl. apply Empty. \n  - simpl. rewrite app_assoc. apply Rcons. apply IHl.\nQed.\n\nTheorem palindrome_rev: forall (l:list A), palindrome l -> l = rev l.\n  intros. induction H.\n  - reflexivity.\n  - reflexivity.\n  - simpl. rewrite rev_unit. rewrite <- IHpalindrome. reflexivity.\nQed.\n\n(* ############ Demo l = rev l -> palindrome l ############## *)\n\nLemma fib_ind :\n forall P:nat -> Prop,\n   P 0 ->\n   P 1 -> \n  (forall n:nat, P n -> P (S n) -> P (S (S n))) -> \n  forall n:nat, P n.\nProof.\n intros P H0 H1 HSSn n. cut (P n /\\ P (S n)).\n - intro H. inversion H. apply H2.\n - induction n.\n    * split.\n        ** apply H0.\n        ** apply H1.\n    * split.\n        ** inversion IHn. apply H2.\n        ** apply HSSn.\n            *** inversion IHn. apply H.\n            *** inversion IHn. apply H2.\nQed.\n\nDefinition lfirst {X} (l: list X) : list X :=\n  match l with\n  | [] => []\n  | x :: l => [x]\nend.\n\nDefinition init {X} (l: list X) : list X := rev (tail (rev l)).\n\nDefinition llast {X} (l: list X) : list X := rev (lfirst (rev l)).\n\nTheorem app_r_nil : forall X (l: list X),\n  l ++ [] = l.\nProof. intros. induction l. reflexivity. simpl. rewrite IHl. reflexivity.\nQed.\n\nLemma rev_app_rev : forall X (a b:list X),\n  rev a ++ rev b = rev (b ++ a).\nProof. intros X a. induction a; intros.\n  rewrite app_r_nil. reflexivity.\n  simpl. rewrite <- app_assoc.\n  remember ([a] ++ rev b) as xrb.\n  rewrite <- rev_involutive with X xrb. rewrite IHa.\n  simpl in Heqxrb. rewrite Heqxrb. simpl. \n  rewrite rev_involutive. rewrite <- app_assoc. simpl. reflexivity.\nQed.\n\nTheorem rev_bij : forall X (l1 l2: list X),\n  l1 = l2 <-> rev l1 = rev l2.\nProof. intros. split. intro H. rewrite H. reflexivity.\n  intro H. rewrite <- rev_involutive. rewrite <- rev_involutive at 1.\n  rewrite H. rewrite ? rev_involutive. reflexivity.\nQed.\n\n\nTheorem first_app_tail : forall X (l: list X),\n  l = lfirst l ++ tail l.\nProof. intros.\n  destruct l. reflexivity.\n  simpl. reflexivity.\nQed.\n\nTheorem init_app_last : forall X (l: list X),\n  l = init l ++ llast l.\nProof. intros.\n  unfold init. unfold llast. rewrite rev_app_rev.\n  rewrite <- rev_involutive at 1. rewrite <- rev_bij.\n  apply first_app_tail.\nQed.\n\nTheorem snoc_tail_almost_comm : forall X (x: X) (l: list X),\n  l <> [] -> tail (l ++ [x]) = (tail l) ++ [x].\nProof. intros. destruct l. \n    - exfalso. apply H. reflexivity. \n    - reflexivity.\nQed.\n\nLemma lfirst_almost_init_inv : forall X (x y: X) (l: list X),\n  lfirst (init (x::y::l)) = lfirst (x::y::l).\nProof. intros. unfold init. remember (y::l) as yl. simpl.\n  rewrite snoc_tail_almost_comm.\n  rewrite rev_unit. reflexivity.\n  rewrite Heqyl. rewrite rev_bij. rewrite rev_involutive. simpl. \n  discriminate.\nQed.\n\nTheorem split_ends : forall X (l: list X) (x y: X),\n (x::y::l) = lfirst (x::y::l) ++ tail (init (x::y::l)) ++ llast (x::y::l).\nProof. intros.  \n  rewrite init_app_last at 1.\n  rewrite first_app_tail with (l := init (x::y::l)) at 1.\n  rewrite lfirst_almost_init_inv. reflexivity.\nQed.\n\nTheorem first_single : forall X (x y:X) (l: list X), l <> [] -> exists k, lfirst (l) = [k].\nProof. intros. induction l. unfold not in H. exfalso. apply H. reflexivity.\n  exists a. reflexivity.\nQed.\n\nTheorem last_single : forall X (x y:X) (l: list X), l <> [] -> exists k, llast (l) = [k].\nProof. intros. induction l. unfold not in H.  exfalso. apply H. reflexivity.\nunfold llast. assert (exists z, lfirst (rev (a :: l)) =  [z]).\n  apply first_single. assumption. assumption. rewrite rev_bij. rewrite rev_involutive. simpl. discriminate.\n  inversion H0. rewrite H1. exists x0. reflexivity.\nQed.\n\nLemma length_app :\n forall X (l l':list X), length (l ++ l') = length l + length l'.\nProof.\n  intros X l; elim l; simpl; auto.\nQed.\n\nRequire Import Arith.\n\nTheorem list_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 : list X, P l.\nProof. \n intros.\n cut (forall (n:nat) (l:list X), length l = n -> P l).\n - (* Case \"Proof of assertion\" *) intros. eapply H2. reflexivity.\n - intro n. pattern n. apply fib_ind.\n    * (* Case \"length is 0\". *) intros. apply length_zero_iff_nil in H2. rewrite H2. apply H.\n    * (* Case \"length is 1\". *) intros. destruct l0.\n        ** simpl in H2. inversion H2.\n        ** simpl in H2. inversion H2. apply length_zero_iff_nil in H4. rewrite H4. apply H0.\n    * (*  Case \"length is S S n\". *) intros. destruct l0.\n        ** simpl in H4. inversion H4.\n        ** destruct l0.\n            *** simpl in H4. inversion H4.\n            *** rewrite split_ends. simpl. rewrite split_ends in H4. simpl in H4. inversion H4. \n                assert(x::x0::l0 <> []).\n                + unfold not. intro contra. inversion contra.\n                + apply last_single in H5.\n                    ++ inversion H5. rewrite H7.  apply H1. apply H2. rewrite H7 in H6. \n                       rewrite length_app in H6. simpl in H6. rewrite plus_comm in H6. \n                      inversion H6. reflexivity.\n                    ++ assumption.\n                    ++ assumption.\nQed.\n\nTheorem app_l_eq : forall X (l1 l2 m: list X), m ++ l1 = m ++ l2 -> l1 = l2.\nProof. intros. induction m. simpl in H. apply H.\n inversion H. apply IHm in H1. apply H1.\nQed.\n\nTheorem app_r_eq : forall X (l1 l2 m: list X), l1 ++ m = l2 ++ m -> l1 = l2.\nProof. intros. rewrite rev_bij in H. rewrite <- 2? rev_app_rev in H.\n apply app_l_eq in H. rewrite <- rev_bij in H. apply H.\nQed. \n\nTheorem rev_pal : forall (l: list A),\n  l = rev l -> palindrome l.\nintros l. pattern l. apply list_induction; intros. Print palindrome.\n apply Empty.  apply Single. simpl in H0.\n rewrite rev_unit in H0.\n simpl in H0. inversion H0.\n apply Rcons.\n apply H.\n apply app_r_eq in H3. apply H3.\nQed.\n\n(* ############ Fin Demo l = rev l -> palindrome l ############## *)\n\n(*Lemma palindromic_rev : forall l:list A, palindrome l -> rev_list l = l.\nProof.\n    intros l H.\n    induction l. reflexivity.\n    simpl. generalize IHl. inversion H. simpl. reflexivity.\n    simpl. intros. rewrite rev_list_append. simpl.\n    elim H. destruct l. discriminate.\n    elim H. reflexivity.\n    reflexivity.\n    intros. simpl. rewrite rev_list_append. simpl.\n\nintros l H. elim H. simpl. auto with datatypes.\nintros a l0 m H0 H1 H2.\ngeneralize H1; inversion_clear H2.\nsimpl; auto.\nrewrite (remove_last_inv H3).\nsimpl.\nrepeat (rewrite rev_app; simpl).\nintro eg; rewrite eg.\nsimpl; auto.\nQed. *)\n\n\nTheorem equal_lists_append: forall (x:A)(l1 l2:list A), \n    equal_lists (l1 ++ [x]) (l2 ++ [x]) = equal_lists l1 l2.\nProof.\n    intros.\n    Admitted.\n\nTheorem is_palindrome_append: forall (l:list A)(x:A),\n    is_palindrome l = is_palindrome (x :: (l ++ [x])).\nProof.\n    intros l x.\n    unfold is_palindrome.\n    rewrite rev_cons. rewrite rev_list_append. rewrite <- app_comm_cons. \n    rewrite (equal_lists_cons x). rewrite (equal_lists_append x). reflexivity.\nQed.\n\nTheorem palindrome_nil: forall (l:list A), l=[] -> palindrome l.\nProof.\n    intros.\n    subst.\n    constructor.\nQed.\n\nTheorem cons_app_pal: forall (l:list A)(a:A), \n    is_palindrome l = true -> is_palindrome (a :: l ++ [a]) = true.\nProof.\n    intros.\n    induction l.\n    - simpl. unfold is_palindrome. simpl. case (A_dec a a).\n        * reflexivity.\n        * apply not_x_x.\n    - simpl. unfold is_palindrome in *. Admitted.\n\n\nTheorem pal_self_rev : forall (l: list A),\n  is_palindrome (l ++ rev l) = true.\nintros. induction l.\n    - reflexivity.\n    - simpl. assert (P: a :: (l ++ rev l) ++ [a] = a :: l ++ rev l ++ [a]). \n        * rewrite app_assoc. reflexivity. \n        * rewrite <- P. apply (cons_app_pal (l ++ rev l) a). apply IHl.\nQed. \nEnd pal_A_dec.\n\nExample test_palindrome: is_palindrome nat PeanoNat.Nat.eq_dec [2;3;3;2] = true.\nProof. reflexivity. Qed.\n\n(* Theorem rev_eq_pal_length: forall (n: nat) (l: list A), \n    length l <= n -> l = rev l -> palindrome l.\nProof.\n(* by induction on [n], not [l] *)\n    intros.\n    induction n. \n    - destruct l as [|a l'].\n        * constructor.\n        * simpl in H. inversion H.\n    - destruct l as [|a l'].\n        * constructor.\n        * inversion H0. destruct (rev l').\n            ** simpl in H2. inversion H2. constructor.\n            ** rewrite H2. induction l.\n                *** simpl. simpl in H2. inversion H2. subst. assert (P:[a0;a0]=a0::[]++[a0]). reflexivity. rewrite P. constructor.\n                *** inversion H2. subst. \n             subst. simpl in H. inversion H. subst. simpl in IHn.\nQed. *)\n\n(*    simpl.\n    destruct l.\n    - simpl. case (A_dec x x). \n        * reflexivity.\n        * intro n. pose (Bool.absurd_eq_true) as X. apply eq_sym. apply X. apply n. apply (eq_refl x).\n    - apply f_equal. simpl.\n\n\n    - intro. destruct l. simpl. apply e. reflexivity. \n    \n    rewrite <- (equal_lists_eq l (rev_list l)). case (A_dec x x).\n    intro n.\n\n\n\n    induction l.\n    - unfold is_palindrome. simpl. case (A_dec x x). \n        * reflexivity.\n        * unfold not. intro n. pose (Bool.absurd_eq_true) as X. apply eq_sym. apply X. apply n. apply (eq_refl x).\n    - unfold is_palindrome. rewrite rev_cons. inversion IHl.\n     simpl. case rev_list l ++ [a].\n        \n        \n        apply (not(eq_refl x)). intro t. Print eq_refl. apply (eq_refl x) in t. intro test. rewrite test in t. Print absurd. rewrite test. intro t. \n        simpl.  Locate \"<>\". inversion n.   *)\n\n\n(*\n\n\n\nVariable B : Type.\nVariable F : B -> Type.\n\nInductive hlist : list B -> Type :=\n| Hnil : hlist nil\n| Hcons : forall (x:B)(ls:list B), F x -> hlist ls -> hlist (x::ls).\n\n(* DefinBion hlist_hd {T Ts} (h : hlist (T :: Ts)) : F T :=\n  match h wBh\n  | Hcons x _ => x\n  | Hnil => tt\n  end. *)\n  \nVariable elm: B.\n\nInductive member : list B -> Type :=\n| HFirst : forall ls, member (elm :: ls)\n| HNext : forall x ls, member ls -> member (x :: ls).\nPrint Hnil.\nImplicit Arguments Hnil [B F].\nImplicit Arguments Hcons [ B F x ls ].\n\nEval compute in Hcons 2 (Hcons [3,4] (Hnil)). \n\nTODO: implementer les listes heterogenes *)\n\n\n(* 1.07 Flatten a nested list structure. *)\n\n(* probleme pour le cas [1;[1;2];3] => concatenation de listes mais pas d'imbrication *)\nInductive nlist (A:Type): Type :=\n| n0 : nlist A\n| ucons : A -> nlist A -> nlist A\n| lcons : nlist A -> nlist A -> nlist A.\n\nImplicit Arguments n0 [A].\nImplicit Arguments ucons [A].\nImplicit Arguments lcons [A].\n\n(*\nNotation \"x :: l\" := (ucons x l)(at level 60, right associativity) : nlist_scope.\nNotation \"[ ]\" := n0 : nlist_scope.\nNotation \"[ x ]\" := (ucons x n0) : nlist_scope.\nNotation \"[ x ; .. ; y ]\" := (ucons x .. (ucons y n0) ..) : nlist_scope.\nNotation \"[ x , .. , y , z ]\" := (lcons x .. (lcons y z) ..) : nlist_scope. \nLocal Open Scope nlist_scope. *)\n\nEval compute in lcons (ucons 1 n0) (ucons 1 (ucons 1 n0)).\nEval compute in ucons 1 (ucons  2 n0).\nEval compute in lcons (ucons 1  (ucons 2 (ucons 3 n0))) (ucons 1 (ucons 2 n0)).\n (* Eval compute in lcons [ 1 ; 2 ; 3 ] [1;2].\nEval compute in lcons [ 1 ; 2 ; 3 ] (lcons [1;2] [1;2;3;4]) . *)\n\nFixpoint nlength {A:Type} (l:nlist A): nat :=\nmatch l with\n| n0 => 0\n| ucons h t => S (nlength t)\n| lcons l1 l2 => 2            \nend.\n\nFixpoint my_flatten {A:Type} (l:nlist A): list A :=\nmatch l with\n| n0 => nil\n| ucons h t => h :: my_flatten t\n| lcons l1 l2 => my_flatten l1 ++ my_flatten l2            \nend.\n\nExample test_my_flatten: \nmy_flatten (lcons (ucons 1  (ucons 2 (ucons 3 n0))) (ucons 1 (ucons 2 n0))) = [1;2;3;1;2].\nProof. reflexivity. Qed.\n\n(* Eval compute in my_flatten (lcons [ 1 ; 2 ; 3 ] (lcons [1;2] [1;2;3;4])).\nLocal Close Scope nlist_scope.\nLocal Open Scope list_scope. *)\n\n\n(* 1.08 Eliminate consecutive duplicates of list elements. *) \nSection compress_A_dec.\nVariable A:Type.\nHypothesis A_dec : forall x y:A, {x = y} + {x <> y}.\n\nFixpoint compress (l:list A): list A :=\nmatch l with\n| nil => nil\n| h :: t => match t with\n            | h' :: t' => match A_dec h h' with\n                          | left _ => compress t\n                          | right _ => h :: compress t\n                          end\n            | nil => l\n            end\nend.\n\nFixpoint compress_bis (l:list A): list A :=\nmatch l with\n|nil => nil\n| h :: t => h :: (fix sub (l:list A) (last:A): list A :=\n                match l with\n                |nil => nil\n                | h :: t => match A_dec h last with\n                            | left _ => sub t last\n                            | right _ => h :: (sub t h)\n                            end\n                end) l h\nend.\n\nTheorem compress_append: forall (x:A)(l:list A), \n    compress ([x;x] ++ l) = compress (x::l) .\nProof.\n    intros. simpl. case (A_dec x x).\n    - intro. destruct l.\n        * reflexivity.\n        * reflexivity.\n    - simpl. apply not_x_x_bis. \nQed.\n\nTheorem compress_cons: forall (x:A)(l:list A), \n    compress (x::l) = x::(compress l) \\/ compress (x::l) = compress l.\nProof.\n    intros x l. destruct l.\n    - simpl. left. reflexivity.\n    - simpl. case (A_dec x a).\n        * right. reflexivity.\n        * left. reflexivity.    \nQed.\nEnd compress_A_dec.\n\nExample test_compress: \ncompress nat PeanoNat.Nat.eq_dec [2;3;3;2;2;1;1;1] = [2;3;2;1].\nProof. reflexivity. Qed.\n\nExample test_compress_bis: \ncompress_bis nat PeanoNat.Nat.eq_dec [2;3;3;2;2;1;1;1] = [2;3;2;1].\nProof. reflexivity. Qed.\n\n(* 1.09 Pack consecutive duplicates of list elements into sublists. *)\nSection pack_A_dec.\nVariable A:Type.\nHypothesis A_dec : forall x y:A, {x = y} + {x <> y}.\n\nFixpoint pack (l:list A): list (list A) :=\nmatch l with\n| nil => nil\n| h :: t => \n    (fix sub (l:list A) (last:A) (current:list A): list (list A) :=\n        match l with\n        | nil => [current]\n        | h :: t => match A_dec h last with\n                    | left _ => sub t h (h :: current)\n                    | right _ => [current] ++ (sub t h [h])\n                    end\n        end) t h [h]\nend.\n\nEnd pack_A_dec.\n\nExample test_pack: \npack nat Nat.eq_dec [1;1;1;2;2;2;3;4;4;4] = [[1;1;1];[2;2;2];[3];[4;4;4]].\nProof. reflexivity. Qed.\n\n(* Fixpoint pack (l:list A): nlist A :=\nmatch l with\n| nil => n0\n| h :: t => lcons (\n    (fix sub (l:list A) (last:A) (current:nlist A): nlist A :=\n        match l with\n        | nil => n0\n        | h :: t => match A_dec h last with\n                    | left _ => sub t h (ucons h current)\n                    | right _ => lcons current (sub t h n0)\n                    end\n        end) l h (ucons h n0)) n0\nend. *)\n\n\n(* 1.10 Run-length encoding of a list. *)\nSection encode_A_dec.\nVariable A:Type.\nHypothesis A_dec : forall x y:A, {x = y} + {x <> y}.\n\nPrint hd.\n(* Avec option *)\nFixpoint encode (l:list A): list (nat * option A) :=\nlet lpack:=pack A A_dec l in (\n    (fix sub (l:list (list A)): list (nat * option A) :=\n        match l with\n        | nil => nil\n        | l1 :: l2 => (length l1, hd_error l1) :: (sub l2)\n        end )) lpack.\n\n(* Sans option *)\nFixpoint encode_bis (l:list A): list (nat * A) :=\nlet lpack:=pack A A_dec l in (\n    (fix sub (l:list (list A)): list (nat * A) :=\n        match l with\n        | nil => nil\n        | l1 :: l2 => match l1 with\n                           | nil => (sub l2)\n                           | h :: t => (length l1, h) :: (sub l2)\n                           end\n        end )) lpack.\n\nEnd encode_A_dec.        \n\nEval compute in pack nat Nat.eq_dec ([1;1;1;2;2;4;5;5;4]).\n\nExample test_encode: \nencode nat Nat.eq_dec ([1;1;1;2;2;4;5;5;4]) = [(3, Some 1); (2, Some 2); (1, Some 4); (2, Some 5); (1, Some 4)].\nProof. reflexivity. Qed.\n\nExample test_encode_bis: \nencode_bis nat Nat.eq_dec ([1;1;1;2;2;4;5;5;4]) = [(3, 1); (2, 2); (1, 4); (2, 5); (1, 4)].\nProof. reflexivity. Qed.\n\n(* 1.11 Modified run-length encoding. *)\n(* Implementer une liste heterogene *)\nSection hlist.\nVariable iT : Type.\nVariable F : iT -> Type.\n\nInductive hlist : list iT -> Type :=\n| Hnil : hlist nil\n| Hcons : forall {T Ts}, F T -> hlist Ts -> hlist (T :: Ts).\n\nDefinition hlist_hd {T Ts} (h : hlist (T :: Ts)) : F T :=\nmatch h with\n  | Hcons x _ => x\n  | Hnil => tt\nend.\n\nDefinition hlist_tl {T Ts} (h : hlist (T :: Ts)) : hlist Ts :=\nmatch h with\n  | Hcons _ t => t\n  | Hnil => tt\nend.\n\nPrint hlist_tl.\nEnd hlist.\n\n\nSection encode2_A_dec.\nVariable A:Type.\nHypothesis A_dec : forall x y:A, {x = y} + {x <> y}.\n\nInductive dlist (A:Type): Type :=\n| Dn0 : dlist A\n| Dcons : A -> dlist A -> dlist A\n| DLcons : (nat*A) -> dlist A -> dlist A.\n\nImplicit Arguments Dn0 [A].\nImplicit Arguments Dcons [A].\nImplicit Arguments DLcons [A].\n\nCheck Dn0.\nCheck (Dcons 1 (Dcons 2 Dn0)).\nCheck DLcons (2,1) (Dcons 1 (Dcons 2 Dn0)).\n\n\n(* Notation \"x :: l\" := (Dcons x l)(at level 60, right associativity) : dlist_scope.\nNotation \"[ ]\" := Dn0 : dlist_scope.\nNotation \"[ x ]\" := (Dcons x n0) : dlist_scope.\nNotation \"[ x ; .. ; y ]\" := (Dcons x .. (Dcons y Dn0) ..) : dlist_scope.\nNotation \"[ x , .. , y , z ]\" := (DLcons x .. (DLcons y z) ..) : dlist_scope. \nLocal Open Scope dlist_scope. *)\n\n\nFixpoint encode_modified (l:list A): dlist A :=\nmatch l with\n| nil => Dn0\n| h :: t => \n    (fix sub (l:list A) (last:A) (count:nat): dlist A :=\n        match l with\n        | nil => if count =? 1 then \n                    Dcons last Dn0\n                else\n                    DLcons (count, last) Dn0\n        | h :: t => match A_dec h last with\n                    | left _ => sub t h (S count)\n                    | right _ => if count =? 1 then \n                                    Dcons last (sub t h 1)\n                                 else\n                                    DLcons (count, last) (sub t h 1)\n                    end\n        end) t h 1\nend.\n\n(* 1.12 Decode a run-length encoded list. *)\nFixpoint decode {A:Type} (l:list (nat * A)): list A :=\nmatch l with\n| nil => nil\n| (l,r) :: t => (fix dup (x:A)(n:nat): list A :=\n                match n with\n                | O => nil\n                | S n' => x :: dup x n'\n                end) r l ++ decode t\nend.\n\n(* 1.13 Run-length encoding of a list (direct solution). *)\nFixpoint encode_direct (l:list A): list (nat * A) :=\nmatch l with\n| nil => nil\n| h :: t => \n    (fix sub (l:list A) (last:A) (count:nat): list (nat * A) :=\n        match l with\n        | nil => (count, last) :: nil\n        | h :: t => match A_dec h last with\n                    | left _ => sub t h (S count)\n                    | right _ => (count, last) :: (sub t h 1)\n                    end\n        end) t h 1\nend.\n\nTheorem decode_inv_encode: forall(l:list A), decode (encode_direct l) = l.\nProof.\n    Admitted.\n       \nEnd encode2_A_dec.\n\nEval compute in encode nat Nat.eq_dec [1;1;1;2;2;4;5;5;4].\n\nExample test_encode_modified: \nencode_modified nat Nat.eq_dec ([1;1;1;2;3;3;4]) = \nDLcons nat (3, 1) (Dcons nat 2 (DLcons nat (2, 3) (Dcons nat 4 (Dn0 nat)))).\nProof. reflexivity. Qed.\n\nExample test_decode: \ndecode [(3,1); (2,2); (1,4); (2,5); (1,4)] = \n[1; 1; 1; 2; 2; 4; 5; 5; 4].\nProof. reflexivity. Qed.\n\n(* Theorem compress_cons2: forall (a:A)(l:list A), exists (l':list A), compress (a::l) = a::l'.\nProof.\n    Admitted.   \n\nTheorem list_neq_cons: forall (a:A)(l:list A), a::l <> l.\nProof.\n    intros. Admitted.\n\n\nTheorem compress_cons_not: forall (x a:A)(l:list A), \n    x::compress(a::l) <> compress(a::l).\nProof.\n    intros. apply list_neq_cons.\nQed.\n\nTheorem compress_cons_right: forall (x:A)(l:list A), \n    compress (x::l) = compress l -> exists (a:A)(l':list A), l = a::l' /\\ a = x.\nProof.\n    intros x l.\n    simpl.\n    destruct l as [| a l2]. \n    - discriminate.\n    - case (A_dec x a).\n        * intros. exists a. exists l2. split. reflexivity. apply eq_sym in e. apply e.\n        * intros e. simpl. destruct l2. \n            ** discriminate.\n            ** simpl. Admitted. *)\n\n\n(* Fixpoint pack (l:list A):list A. implementer listlist... *)\n\n(* 1.14 Duplicate the elements of a list. *) \nFixpoint dupli {A:Type}(l:list A): list A :=\nmatch l with\n| nil => nil\n| h :: t => h :: h :: dupli t\nend.\n\nEval compute in dupli [\"a\";\"b\";\"b\";\"c\";\"d\"]%string.\n\nLocal Open Scope string_scope.\nExample test_dupli: \ndupli [\"a\";\"b\";\"b\";\"c\";\"d\"] = [\"a\";\"a\";\"b\";\"b\";\"b\";\"b\";\"c\";\"c\";\"d\";\"d\"].\nProof. reflexivity. Qed.\nClose Scope string_scope. \n\nTheorem dupli_cons {A:Type}: forall (x:A)(l:list A), dupli (x::l) = [x;x] ++ dupli l.\nProof.\n    intros x l.\n    eauto.  \nQed.\n\n(*\nTheorem dupli_compress {A:Type}: forall(l:list A), compress (dupli l) = compress l.\nProof.\n    intro l. induction l.\n    - reflexivity.\n    - rewrite dupli_cons. rewrite compress_append. pose compress_cons as C.\n        elim (C a l). intro H. rewrite <- IHl in H. rewrite H.\n        elim (C a (dupli l)). trivial.\n        intros. rewrite H0. rewrite IHl in H. \n        pose (list_neq_cons a (compress (dupli l))) as X. unfold not in X. elim X. \nAdmitted. *)\n  (*    destruct (C a (dupli l)). rewrite H. rewrite IHl. apply eq_sym. destruct (C a l).\n      rewrite H0. reflexivity.\n      simpl.\n      rewrite H0. simpl. \n      simpl. destruct l. discriminate. \n        simpl.\n      rewrite <- H0 in IHl. rewrite IHl in H. rewrite H0 in H.\n\n      \n      rewrite H. rewrite H0. rewrite IHl. reflexivity.\n      rewrite H0. rewrite IHl. rewrite H. \n      rewrite H. rewrite H0. rewrite IHl.\n       split. rewrite (C a l). \nQed. *)\n\n(* 1.15 Duplicate the elements of a list a given number of times. *) \nFixpoint dupli_elm {A:Type}(x:A)(n:nat) : list A :=\nmatch n with\n| O => nil\n| S n' => x :: dupli_elm x n'\nend.\n\nFixpoint dupli_nth {A:Type}(l:list A)(n:nat) : list A :=\nmatch l with\n| nil => nil\n| h :: t => (dupli_elm h n) ++ (dupli_nth t n)\nend.\n\nLocal Open Scope string_scope.\nExample test_dupli_nth: \ndupli_nth [\"a\";\"b\";\"c\"] 3 = [\"a\"; \"a\"; \"a\"; \"b\"; \"b\"; \"b\"; \"c\"; \"c\"; \"c\"].\nProof. reflexivity. Qed.\nClose Scope string_scope. \n\n(* 1.16 Drop every N'th element from a list. *) \nFixpoint scroll_drop_list {A:Type}(l:list A)(n:nat) : list A :=\nmatch n, l with\n| _, nil => nil\n| O, h :: t => t\n| S n', h :: t => h :: scroll_drop_list t n'\nend.\n\n(* En commencant à O *)\nFixpoint drop {A:Type}(l:list A)(n:nat) : list A :=\n(fix sub (l:list A)(n cpt:nat) : list A :=\nmatch l, cpt with\n| nil, _ => nil\n| h :: t, O => sub t n n\n| h :: t, S n' => h :: sub t n n'\nend) l n n.\n\n(* En commencant à 1 *)\nFixpoint drop_bis {A:Type}(l:list A)(n:nat) : list A :=\nlet pn := pred n in \n(fix sub (l:list A)(n cpt:nat) : list A :=\nmatch l, cpt with\n| nil, _ => nil\n| h :: t, O => sub t n n\n| h :: t, S n' => h :: sub t n n'\nend) l pn pn.\n\n\nLocal Open Scope string_scope.\nExample test_drop: \ndrop [\"a\";\"b\";\"c\";\"a\";\"b\";\"c\";\"a\";\"b\";\"c\"] 3 = \n[\"a\"; \"b\"; \"c\"; \"b\"; \"c\"; \"a\"; \"c\"].\nProof. reflexivity. Qed.\n\nExample test_drop_bis: \ndrop_bis [\"a\";\"b\";\"c\";\"a\";\"b\";\"c\";\"a\";\"b\";\"c\"] 3 = \n[\"a\"; \"b\"; \"a\"; \"b\"; \"a\"; \"b\"].\nProof. reflexivity. Qed.\nClose Scope string_scope. \n\n(*\nFixpoint drop {A:Type}(l:list A)(n:nat) : list A :=\nmatch l with\n| nil => nil\n| h :: t => drop (scroll_drop_list l n) n\nend.\n\n\nFixpoint drop_bis {A:Type}(l:list A)(n:nat) : list A :=\n(fix sub (l:list A)(n cpt:nat) : list A :=\nmatch \n\n) l n n\n\n*)\n(* 1.17 Split a list into two parts; the length of the first part is given. *) \nLocate split.\n\nFixpoint split {A : Type} (l : list A) (n : nat) : (list A) * (list A) :=\nmatch l, n with\n    | [], _ => ([], [])\n    | h::t, S n' => let (l1, l2) := split t n' in (h::l1, l2)\n    | _, O => (nil, l)\nend.\n\nExample test_split: \nsplit [1;2;3;4;5;6;7;8;9;10] 4 = ([1;2;3;4],[5;6;7;8;9;10]). \nProof. reflexivity. Qed.\n\n\n(* 1.18 Extract a slice from a list. *) \n(* en partant de 0 *)\nFixpoint slice {A:Type}(l:list A)(m n:nat) : list A :=\nmatch l, m, n with\n| nil, _, _ => nil \n| h::t, _, O => h :: nil\n| h::t, O, S n' => h :: slice t m n'\n| h::t, S m', S n' => slice t m' n' \nend.\n\n(* en partant de 1 *)\nFixpoint slice_bis {A:Type}(l:list A)(m n:nat) : list A :=\nmatch l, m, n with\n| nil, _, _ => nil \n| _, _, O => nil\n| h::t, O, S n' => h :: slice_bis t m n'\n| h::t, S O, S n' => h :: slice_bis t O n'\n| h::t, S m', S n' => slice_bis t m' n' \nend.\n\nLocal Open Scope string_scope.\nExample test_slice: \nslice [\"a\";\"b\";\"c\";\"d\"; \"e\"; \"f\"] 3 5 = [\"d\"; \"e\"; \"f\"].\nProof. reflexivity. Qed.\n\nExample test_slice_bis: \nslice_bis [\"a\";\"b\";\"c\";\"d\"; \"e\"; \"f\"] 3 5 = [\"c\"; \"d\"; \"e\"].\nProof. reflexivity. Qed.\nClose Scope string_scope. \n\n(* 1.19 Rotate a list N places to the left. *) \nFixpoint rotate {A:Type}(l:list A)(n:nat) : list A :=\nlet lth := List.length l in \nlet modn := Nat.modulo n lth in\nlet (l1, l2) := split l modn in\nl2 ++ l1.\n\n(* sans split *)\nFixpoint rotate_bis {A:Type}(l:list A)(n:nat) : list A :=\nlet lth := List.length l in \nlet modn := Nat.modulo n lth in\n(fix sub (l s:list A)(n:nat) : list A :=\nmatch l, n with\n| nil, _ => nil \n| _, O => l ++ s\n| h::t, S n' => sub t (s ++ [h]) n'\nend) l nil modn.\n\nLocal Open Scope string_scope.\nExample test_rotate: \nrotate [\"a\";\"b\";\"c\";\"d\"; \"e\"; \"f\"] 4 = [\"e\"; \"f\"; \"a\"; \"b\"; \"c\"; \"d\"].\nProof. reflexivity. Qed.\n\nExample test_rotate_bis: \nrotate_bis [\"a\";\"b\";\"c\";\"d\"; \"e\"; \"f\"] 4 = [\"e\"; \"f\"; \"a\"; \"b\"; \"c\"; \"d\"].\nProof. reflexivity. Qed.\nClose Scope string_scope. \n\n(* 1.20 Remove the K'th element from a list. *) \n(* en renvoyant un couple et en partant de 1 *)\nFixpoint remove_kth {A:Type}(l:list A)(n:nat) : (option A) * (list A) :=\nmatch l, n with\n| nil, _ => (None, nil)\n| h::t, O => (Some h, t)\n| h::t, S O => (Some h, t)\n| h::t, S n' => let (elm, ls) := remove_kth t n' in (elm, h :: ls)\nend.\n\n(* en renvoyant seulement la liste et en partant de 1 *)\nFixpoint remove_kth_bis {A:Type}(l:list A)(n:nat) : list A :=\nmatch l, n with\n| nil, _ => nil\n| h::t, O => t\n| h::t, S O => t\n| h::t, S n' => h :: remove_kth_bis t n'\nend.\n\nLocal Open Scope string_scope.\nExample test_remove_kth: \nremove_kth [\"a\";\"b\";\"c\";\"d\"; \"e\"; \"f\"] 2 = (Some \"b\", [\"a\"; \"c\"; \"d\"; \"e\"; \"f\"]).\nProof. reflexivity. Qed.\n\nExample test_remove_kth_bis: \nremove_kth_bis [\"a\";\"b\";\"c\";\"d\"; \"e\"; \"f\"] 2 = [\"a\"; \"c\"; \"d\"; \"e\"; \"f\"].\nProof. reflexivity. Qed.\nClose Scope string_scope. \n\n\n(* 1.21 Insert an element at a given position into a list. *) \n(* en partant de 1 *)\nFixpoint insert_at {A:Type}(e:A)(l:list A)(n:nat) : list A :=\nmatch l, n with\n| nil, _ | _, O | _, S O => e :: l\n| h::t, S n' => h :: insert_at e t n'\nend.\n\nLocal Open Scope string_scope.\nExample test_insert_at: \ninsert_at \"c\" [\"a\";\"b\";\"d\"] 2 = [\"a\"; \"c\"; \"b\"; \"d\"].\nProof. reflexivity. Qed.\nClose Scope string_scope. \n\n(* 1.22 Create a list containing all integers within a given range. *) \nFixpoint range (a b:nat) : list nat :=\nlet diff := b - a in \n    (fix sub (b diff:nat) : list nat :=\n    match diff with\n    | O => [b]\n    | S d' => (b-diff) :: sub b d'\n    end) b diff.\n\n(* En utilisant le_lt_dec := {n <= m} + {m < n} *)\nFixpoint range_bis (a b:nat) : list nat :=\nif Arith.Compare_dec.le_lt_dec a b then  \n    match b with\n    | O => [O]\n    | S b' => (range a b') ++ [b]\n    end\nelse nil.\n\nExample test_range: \nrange 5 8 = [5; 6; 7; 8].\nProof. reflexivity. Qed.\n\nExample test_range_bis: \nrange_bis 5 8 = [5; 6; 7; 8].\nProof. reflexivity. Qed.\n\n(* 1.23 Extract a given number of randomly selected elements from a list. *)\n(* utiliser seed pour générer des nombres aléatoires ? *)\nRequire Import Streams.\nCoFixpoint rand (seed n1 n2 : nat) : Stream nat :=\n    let seed' := Nat.modulo seed n2 in Cons seed' (rand (seed' * n1) n1 n2).\n\n(* 1.24 Lotto: Draw N different random numbers from the set 1..M. *)\n\n(* 1.25 Generate a random permutation of the elements of a list. *)\n\n(* 1.26 Generate the combinations of K distinct objects chosen from the N elements of a list *)\nFixpoint combination {A:Type} (n:nat) (l:list A) : list (list A) :=\n(fix sub (n:nat) (l rem:list A): list (list A) := \nmatch n, l with\n| O, _ => [rem]\n| _, nil => [nil]\n| S n', h::t => if n <=? length t  then \n                    (sub n' t (h::rem)) ++ (sub n t rem)\n                else \n                    (sub n' t (h::rem))\nend) n l nil.\n\nExample test_combination: \ncombination 2 [1;2;3;4] = [[2; 1]; [3; 1]; [4; 1]; [3; 2]; [4; 2]; [4; 3]].\nProof. reflexivity. Qed.\n\nExample test_combination2: \ncombination 3 [1;2;3;4] = [[3; 2; 1]; [4; 2; 1]; [4; 3; 1]; [4; 3; 2]].\nProof. reflexivity. Qed.\n\nTheorem card_combination {A:Type}: forall (l:list A)(n:nat), let cardl := length l in \n    (length (combination n l) = fact cardl / (fact n * fact (cardl - n))).\nProof.\n    Admitted.   \nPrint prod.\n(* 1.27 Group the elements of a set into disjoint subsets. *)\n(* renvoie egalement la liste restant pour chaque combinaison *)\nFixpoint comb_bis {A:Type} (n:nat) (l:list A) : list (list A * list A) :=\n(fix sub (n:nat) (l rem remL:list A): list (list A * list A) := \nmatch n, l with\n| O, _ => [(rem, remL++l)]\n| _, nil => [(nil, remL)]\n| S n', h::t => if n <=? length t  then \n                    (sub n' t (h::rem) remL) ++ (sub n t rem (h::remL))\n                else \n                    (sub n' t (h::rem) remL)\nend) n l nil nil.\n\nEval compute in comb_bis 3 [1;2;3;4;5].\n\n(* ####### *)\n\n(* Fixpoint group3 {A:Type} (n m p:nat) (l:list A) : list (list A * list A * list A) :=\nlet comb1 := comb_bis n l in ( \n    match comb1 with\n    | nil => nil\n    | (cn, reml1)::t => let comb2 := comb_bis m reml1 in (\n                        match comb2 with\n                        | nil => nil\n                        | (cm, reml2) => let comb3 := comb_bis p reml2 in (\n                                            match comb2 with\n                                            | nil => nil\n                                            | (cp, _) => (cn, cm, cp))    \n    )\n )\n(fix sub (n m p:nat) (l remL remM remP:list A): list (list A * list A * list A) := \nmatch n, l with\n| O, _ =>  match \n| _, nil => [(remL, remM, remP)]\n| S n', h::t => if (n+m+p) <=? length t  then \n                    (sub n' t (h::remL)) ++ (sub n t remL)\n                else \n                    (sub n' t (h::remL))\nend) n m p l nil nil nil. *)\n\n(* ############ *)\n(* 1.28 Sorting a list of lists according to length of sublists  *)\nPrint Arith.Compare_dec.le_lt_dec.\n(* insertion d'une liste de taille lenL dans une liste de listes de taille variable *)\nFixpoint sub_lsort {A:Type} (l:list A)(m:list (list A))(lenL:nat) : list (list A) :=\nmatch m with\n| nil => [l]\n| l1::l2 => if Arith.Compare_dec.le_lt_dec lenL (length l1) then \n                [l] ++ m\n            else [l1] ++ (sub_lsort l l2 lenL)\nend. \n\n(* insertion de [1;2;2] dans [[1];[1;2;3;4]] *)\nExample test_sub_lsort: \nsub_lsort [1;2;2] [[1];[1;2;3;4]] 3 = [[1]; [1; 2; 2]; [1; 2; 3; 4]].\nProof. reflexivity. Qed.\n\nFixpoint lsort {A:Type}(l:list (list A)) : list (list A) :=\nmatch l with\n| nil => nil\n| h::t => sub_lsort h (lsort t) (length h)\nend.\n\nFixpoint lsort_bis {A:Type}(l:list (list A)) : list (list A) :=\n(fix sub (m res:list (list A)) : list (list A) :=\nmatch m with\n| nil => res\n| h::t => sub t (sub_lsort h res (length h))\nend) l nil.\n\n\nEval compute in lsort [[1];[1;2;3;4];[1;2];[1;4;5]].\nEval compute in lsort_bis [[1];[1;2;3;4];[1;2];[1;4;5]].\n\nExample test_lsort: \nlsort [[1];[1;2;3;4];[1;2];[1;4;5]] = [[1]; [1; 2]; [1; 4; 5]; [1; 2; 3; 4]].\nProof. reflexivity. Qed.\n\nExample test_lsort_bis: \nlsort_bis [[1];[1;2;3;4];[1;2];[1;4;5]] = [[1]; [1; 2]; [1; 4; 5]; [1; 2; 3; 4]].\nProof. reflexivity. Qed.\n\nEnd list_prob.", "meta": {"author": "ArthurWenger", "repo": "Coq", "sha": "b782f5f14f8e6d7f4e7a174385c7d2c5434bafb5", "save_path": "github-repos/coq/ArthurWenger-Coq", "path": "github-repos/coq/ArthurWenger-Coq/Coq-b782f5f14f8e6d7f4e7a174385c7d2c5434bafb5/TER M1/prob_lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7207030217547182}}
{"text": "(*|\n########################\nRewrite under ``exists``\n########################\n\n:Link: https://stackoverflow.com/q/47635697\n|*)\n\n(*|\nQuestion\n********\n\nSay I have the following relation:\n|*)\n\nInductive my_relation: nat -> Prop :=\n  constr n : my_relation n.\n\n(*| and I want to prove the following: |*)\n\nLemma example:\n  (forall n, my_relation n -> my_relation (S n)) ->\n  (exists n, my_relation n) -> exists n, my_relation (S n).\nProof.\n  intros.\n\n(*| After introducing, I have the following environment: |*)\n\n  Show. (* .unfold .messages *)\n\n(*|\nMy question is: is there a possibility to rewrite ``H`` under the\n``exists`` quantifier? If not, is there a strategy to solve this kind\nof problem (this particular one is not really relevant, but problems\nwhere you have to prove an ``exists`` using another ``exists``, and\nwhere, informally, you can \"deduce\" a way to rewrite the ``exists`` in\nthe hypothesis into the ``exists`` in the goal)?\n\nFor instance, if I try ``rewrite H in H0.`` I have, an error\n|*)\n\n  Fail rewrite H in H0. (* .unfold .messages *)\n\n(*|\nAnswer (eponier)\n****************\n\nThe standard way to manipulate an existential quantification in an\nhypothesis is to get a witness of the property using ``inversion`` or,\nbetter and simpler, ``destruct``.\n\nYou can give a name to the variable using one of the following\nsyntaxes:\n|*)\n\n  destruct H0 as (n, H0). Undo 1. (* .none *)\n\n  destruct H0 as [n H0]. Undo 1. (* .none *)\n\n  destruct H0 as (n & H0).\n\n(*|\nNote that you can also destruct an hypothesis using `intro-patterns\n<https://coq.inria.fr/refman/tactics.html#sec364>`__.\n|*)\n\n  Restart. (* .none *)\n  intros H (n & H0).\n\n(*| And you can even directly apply ``H`` in ``H0``. |*)\n\n  Restart. (* .none *)\n  intros H (n & H0%H). exists n. assumption.\n\n(*|\n`Software Foundations\n<https://softwarefoundations.cis.upenn.edu/lf-current/Logic.html#lab175>`__\nexplains this in a clear way.\n|*)\n\n(*|\nAnswer (Arthur Azevedo De Amorim)\n*********************************\n\nI found a way, I post it here for any similar questions in the future.\n\nIt is possible to inverse the ``exists`` hypothesis, in order to\n\"instantiate\" the quantified variable, for instance, here, the proof\ncan be finished by:\n|*)\n\n  Restart. (* .none *) intros. (* .none *)\n  inversion H0. apply H in H1.\n  exists x. apply H1.\n\n(*| After ``inversion H0``, we have in the environment: |*)\n\n  Restart. (* .none *) intros. (* .none *) inversion H0. (* .none *)\n  Show. (* .unfold .messages *)\n\n(*| and we can now work with ``x``. |*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/rewrite-under-exists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.720703018574868}}
{"text": "Require Import List.\nRequire Import ZArith.\nRequire Import Classical.\nRequire Import FinFun.\n\nFrom mathcomp\nRequire Import ssreflect.\n\nImport ListNotations.\n\nSection Utility.\n  Open Scope Z_scope.\n  Open Scope list_scope.\n\n  Definition succ (i : Z) : Z :=\n    (i + 1) mod 5.\n\n  Definition pred (i : Z) : Z :=\n    (i - 1) mod 5.\n\n  Definition Mat2 := list (list Z).\n\n  Definition mat_mul (m : Mat2) (p : Z * Z) : (Z * Z) :=\n    let row0 := nth 0 m [] in\n    let row1 := nth 1 m [] in\n    let (a, b) := (nth 0 row0 0, nth 1 row0 0) in\n    let (c, d) := (nth 0 row1 0, nth 1 row1 0) in\n    (a * (fst p) + b * (snd p), (c * (fst p) + d * (snd p))).\n    \n  Notation \"m * p\" := (mat_mul m p).\n\n  Definition mat2_pi_over_2 : Mat2 := [ [ 0; 1 ]; [ -1; 0 ] ].\n\n  Definition mat2_pi_over_2' : Mat2 := [ [ 0; -1 ]; [ 1; 0 ] ].\n\n  Lemma lt_imply_false (x : Z) : (x < 0 -> False) -> 0 <= x.\n  Proof. omega. Qed.\n\n  Lemma gt_imply_false (x : Z) : (0 < x -> False) -> x <= 0.\n  Proof. omega. Qed.\n\n  Lemma abs_eq_gt (x : Z) : 0 < x -> Z.abs x = x.\n  Proof.\n    have x_gt_imply_ge: 0 < x -> 0 <= x. omega.\n    move /x_gt_imply_ge.\n    apply: Z.abs_eq.\n  Qed.\n\n  Lemma abs_eq_lt (x : Z) : x < 0 -> Z.abs x = -x.\n  Proof.\n    have x_lt_imply_le: x < 0 -> x <= 0. omega.\n    move /x_lt_imply_le.\n    apply Z.abs_neq.\n  Qed.\n\n  Lemma pair_eq_and (a b c d : Z) : (a, b) = (c, d) <-> a = c /\\ b = d.\n  Proof.\n    split.\n    -move=> s0.\n      inversion s0.\n      split.\n      +by [].\n      +by [].\n    -move=> s0.\n      case: s0 => s0 s1.\n      by rewrite s0 s1.\n  Qed.\n\n  Lemma eqp_neq (a b c d : Z) :\n    (a, b) <> (c, d) <-> a =? c = false \\/ b =? d = false.\n  Proof.\n    split.\n    -move=> s0.\n      unfold not in s0.\n      move /pair_eq_and in s0.\n      apply not_and_or in s0.\n      case: s0 => s0.\n      +left. by apply Z.eqb_neq.\n      +right. by apply Z.eqb_neq.\n    -move=> s0.\n      move=> s1.\n      inversion s1.\n      case: s0 => s0.\n      +by apply Z.eqb_neq in s0.\n      +by apply Z.eqb_neq in s0.\n  Qed.\n\n  Close Scope list_scope.\n  Close Scope Z_scope.\n\nEnd Utility.\n", "meta": {"author": "cathesis", "repo": "verification-ca", "sha": "ba4e7128591d98832caa34f0d6863d6fb77dc90e", "save_path": "github-repos/coq/cathesis-verification-ca", "path": "github-repos/coq/cathesis-verification-ca/verification-ca-ba4e7128591d98832caa34f0d6863d6fb77dc90e/Utility.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7206975503368813}}
{"text": "Require Export D.\n\n\n\n(** **** Problem #19 : 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n. induction n. intros. destruct m. reflexivity.\n  inversion H.\n  intros. \n  destruct m. inversion H. \n  Lemma nm_SnSm_eq : forall (n m:nat),\n    n=m -> S n=S m.\n  Proof. intros.  rewrite ->H. reflexivity. Qed.\n  apply nm_SnSm_eq. apply IHn. inversion H. reflexivity.\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/04/P20.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7206975433299789}}
{"text": "From Coq Require Import Arith ZArith micromega.Lia.\n\nLemma strong_induction P : (forall n, (forall m, (m < n) -> P m) -> P n) -> forall k, P k.\nProof.\n  intros; generalize (Nat.le_refl k); generalize k at -2.\n  induction k; intros. apply X. lia. destruct k0. apply X. lia. apply X. intros. apply IHk. lia. Qed.\n\nLemma induction2 P : P 0%nat -> P 1%nat -> (forall n, P n -> P (S n) -> P (S (S n))) -> forall k, P k.\nProof.\n  intros; induction k using strong_induction; [destruct k as [|k]; [assumption|destruct k]; [assumption|]].\n  apply X1; apply X2; lia. Qed.\n\nLemma induction_at n (P : nat -> Prop) : P n -> (forall m, (n <= m)%nat -> (P m -> P (S m))) -> (forall m, (n <= m)%nat -> P m).\nProof.\n  intros; induction m.\n  - apply le_n_0_eq in H1; subst; assumption.\n  - destruct (Nat.eq_dec (S m) n).\n    + subst; assumption.\n    + apply H0; [|apply IHm]; lia. Qed.\n\nLemma rev_1_ind m (P : nat -> Prop) : P m -> (forall k, (0 < k <= m)%nat -> P k -> P (Nat.pred k)) -> forall k, (k <= m)%nat -> P k.\nProof.\n  intros.\n  assert { l : nat | (m - k)%nat = l }. eexists. reflexivity. destruct H2. generalize dependent k.\n  induction x; intros.\n  replace k with m by lia. assumption.\n  destruct (S k =? m)%nat eqn:E2. apply Nat.eqb_eq in E2. replace k with (Nat.pred m) by lia. apply H0. lia. assumption.\n  apply Nat.eqb_neq in E2.\n  replace k with (Nat.pred (S k)) by lia. apply H0. lia.\n  apply IHx. lia. lia. Qed.\n\nLemma rev_2_ind P m : P (S m) -> P m -> (forall k, (0 < k <= S m)%nat -> P k -> P (Nat.pred k) -> P (Nat.pred (Nat.pred k))) -> (forall k, (k <= (S m))%nat -> P k).\nProof.\n  intros.\n\n  assert { l : nat | ((S m) - k)%nat = l }. eexists. reflexivity. destruct H0. generalize dependent k.\n  induction x using induction2; intros.\n  - assert (k = S m) by lia. congruence.\n  - assert (k = m) by lia. congruence.\n  - destruct (Nat.eq_dec (S (S k)) (S m)).\n    replace k with (Nat.pred (Nat.pred (S (S k)))) by lia. rewrite e0. apply X1. lia.\n    assumption. assumption.\n\n    replace k with (Nat.pred (Nat.pred (S (S k)))) by lia.\n    apply X1. lia. apply IHx. lia. lia. apply IHx0. lia. lia. Qed.\n\nLocal Open Scope Z.\n\nLemma strong_natlike_ind (P : Z -> Prop) : (forall x, (forall y, 0 <= y < x -> P y) -> P x) -> forall x : Z, 0 <= x -> P x.\nProof.\n  intros Hind x. remember (Z.abs_nat x). revert x Heqn Hind.\n  induction n using strong_induction; intros.\n  apply Hind. intros; apply H with (m := Z.abs_nat y); try assumption; lia. Qed.\n\nLemma rev_1_natlike_ind (P : Z -> Prop) x : P x -> (forall y, (0 < y <= x) -> P y -> P (Z.pred y)) -> (forall y, (0 <= y) -> (y <= x) -> P y).\nProof.\n  intros Px Hind y. remember (Z.abs_nat (x - y)). revert y x Heqn Hind Px.\n  induction n; intros.\n  - assert (x = y) by lia; subst; assumption.\n  - destruct (Z.eq_dec x y); [subst; assumption|].\n    replace y with (Z.pred (Z.succ y)) by lia.\n    apply Hind; [lia|]; apply IHn with (x:=x); try assumption; lia. Qed.\n", "meta": {"author": "bshvass", "repo": "by-inversion", "sha": "281c10e6435a86e39b2c6e1829aa874e45147140", "save_path": "github-repos/coq/bshvass-by-inversion", "path": "github-repos/coq/bshvass-by-inversion/by-inversion-281c10e6435a86e39b2c6e1829aa874e45147140/src/InductionPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7206975403742509}}
{"text": "Require Import Program Omega Ring ArithRing List.\n\nProgram Fixpoint sum_to (n: nat): {r: nat | 2 * r = n * (n+1) } :=\n  match n with\n  | 0 => 0\n  | S n' => n + sum_to n'\n  end.\n\nCheck sum_to_obligation_1.\nObligation 2 of sum_to.\n  simpl.\n  assert (S (n' + x + S (n' + x + 0)) = n' + (x + (x + 0)) + n' + 2) by omega.\n  rewrite H. clear H.\n  rewrite e. clear e.\n  ring.\nDefined sum_to.\n\n\n\n\nLocate \"|\".\nCheck sig.\nPrint sig.\n(* Look here https://coq.inria.fr/library/Coq.Init.Specif.html *)\nCheck exist.\nCheck existT.\n\n\nProgram Fixpoint my_reverse (A: Type) (l: list A): {l': list A | length l = length l'} :=\n  match l with\n  | nil => nil\n  | cons head tail => (my_reverse A tail) ++ [head]\n  end.\nObligation 2 of my_reverse.\n  Search (length (_ ++ _) = length _ + length _).\n  rewrite app_length.\n  simpl.\n  omega.\nDefined my_reverse.", "meta": {"author": "KinanBab", "repo": "CS591K1-Labs", "sha": "d4569bf99d20c22cd56721024688cda247d1447f", "save_path": "github-repos/coq/KinanBab-CS591K1-Labs", "path": "github-repos/coq/KinanBab-CS591K1-Labs/CS591K1-Labs-d4569bf99d20c22cd56721024688cda247d1447f/lab3/code/certified_programming.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7206975348865385}}
{"text": "(* Code for Coq'Art, Chapter 3: Propositions and Proofs. *)\n\nSection PropositionsAndProofs.\n\nVariable P Q R S T : Prop.\n\n(* Examples *)\nSection Examples.\n\nSection MinimalPropositionalLogic.\n\nTheorem imp_trans_theorem : (P -> Q) -> (Q -> R) -> P -> R.\n(* Detailed proof *)\nProof.\n  intros h1 h2 h3.\n  apply h2.\n  apply h1.\n  apply h3. (* assumption. *)\nQed.\nPrint imp_trans_theorem.\n\nTheorem imp_trans' : (P -> Q) -> (Q -> R) -> P -> R.\n(* Auto Proof. *)\nProof.\n  auto.\nQed.\nPrint imp_trans'.\n\nHypothesis hypo1 : P -> Q -> R.\n\nLemma l1 : P -> Q -> R.\nProof.\n  apply hypo1.\nQed.\nPrint l1.\n\nTheorem delta : (P -> P -> Q) -> P -> Q.\nProof.\n  (* detailed proof:\n    intros h1 h2.\n    apply h1.\n    apply h2.\n    apply h2. *)\n  exact (fun (h1 : P -> P -> Q)(h2 : P) => h1 h2 h2).\nQed.\nPrint delta.\n\n(* Theorem delta : (P -> P -> Q) -> P -> Q.\nProof (fun (h1 : P -> P -> Q)(h2 : P) => h1 h2 h2).\nPrint delta. *)\n\nTheorem apply_example : (Q -> R -> T) -> (P -> Q) -> P -> R -> T.\nProof.\n  intros h1 h2 h3.\n  apply h1.\n  apply h2.\n  apply h3.\nQed.\nPrint apply_example.\n\nTheorem imp_dist : (P -> Q -> R) -> (P -> Q) -> (P -> R).\nProof.\n  intros h1 h2 h3.\n  apply h1.\n  apply h3.\n  apply h2.\n  apply h3.\nQed.\nPrint imp_dist.\n\nTheorem k : P -> Q -> P.\nProof.\n  intros h1 h2.\n  apply h1.\nQed.\nPrint k.\n\nSection ProofOfTripleImpl.\n\nHypothesis hypo2 : P.\nHypothesis hypo3 : ((P -> Q) -> Q) -> Q.\n\nLemma l2 : (P -> Q) -> Q.\nProof (fun (h1 : P -> Q) => h1 hypo2).\n\nTheorem triple_impl : Q.\nProof (hypo3 l2).\n\nEnd ProofOfTripleImpl.\n\nPrint triple_impl.\nPrint l2.\n\nTheorem then_example : P -> Q -> (P -> Q -> R) -> R.\nProof.\n  intros h1 h2 h3.\n  apply h3; assumption.\nQed.\n\nTheorem triple_impl_one_shot : (((P -> Q) -> Q) -> Q) -> P -> Q.\nProof.\n  intros h1 h2.\n  apply h1; intro h3; apply h3; apply h2.\nQed.\n\nTheorem compose_example : (P -> Q -> R) -> (P -> Q) -> (P -> R).\nProof.\n  intros h1 h2 h3.\n  apply h1; [assumption | apply h2; assumption].\nQed.\n\nTheorem orelse_example : (P -> Q) -> R -> ((P -> Q) -> R -> (T -> Q) -> T) -> T.\nProof.\n  intros h1 h2 h3.\n  apply h3; (assumption || intros h4).\nAbort. (* can't be proved. *)\n\nLemma idtac_example : (P -> Q) -> (P -> R) -> (P -> Q -> R -> T) -> P -> T.\nProof.\n  intros h1 h2 h3 h4.\n  apply h3; [idtac | apply h1 | apply h2]; assumption.\nQed.\n\nLemma then_fail_example : (P -> Q) -> (P -> Q).\nProof.\n  intros h1; apply h1; fail.\nQed.\n\nLemma try_example : (P -> Q -> R -> T) -> (P -> Q) -> (P -> R -> T).\nProof.\n  intros h1 h2 h3 h4.\n  apply h1; try assumption.\n  apply h2; assumption.\nQed.\n\nSection CutTacticExample.\n\n(* cut tactic: for goal Q, impose these two subgoals:\n  + P\n  + P -> Q\n  base on MP(Modus Ponens) rules, the goal can be proved by these two subgoals. *)\n\nHypothesis\n  (h1 : P -> Q)\n  (h2 : Q -> R)\n  (h3 : (P -> R) -> T -> Q)\n  (h4 : (P -> R) -> T).\n\nTheorem cut_example : Q.\nProof.\n  cut (P -> R).\n  intros h5.\n  apply h3;\n    [ apply h5\n    | apply h4; apply h5\n    ].\n  intros h6; apply h2; apply h1; apply h6.\nQed.\nPrint cut_example.\n\nEnd CutTacticExample.\n\nEnd MinimalPropositionalLogic.\n\nEnd Examples.\n\n(* Exercises. *)\nSection Exercises.\n\n(* Exercise 3.1 *)\nCheck ((P -> Q) -> (Q -> R) -> P -> R).\n\n(* Exercise 3.2 and 3.3 *)\nLemma id_P : P -> P.\nProof.\n  intros h1.\n  apply h1.\nQed.\nPrint id_P.\n\nLemma id_PP : (P -> P) -> (P -> P).\nProof.\n  intro h1.\n  apply h1.\nQed.\n\nLemma imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  intros h1 h2 h3.\n  apply h2.\n  apply h1.\n  apply h3.\nQed.\n\nLemma imp_perm : (P -> Q -> R) -> (Q -> P -> R).\nProof.\n  intros h1.\n  intros h2 h3.\n  apply h1.\n  apply h3.\n  apply h2.\nQed.\n\nLemma ignore_Q : (P -> R) -> P -> Q -> R.\nProof.\n  intros h1 h2 h3.\n  apply h1.\n  apply h2.\nQed.\n\nLemma delta_imp : (P -> P -> Q) -> P -> Q.\nProof.\n  intros h1 h2.\n  apply h1.\n  apply h2.\n  apply h2.\nQed.\n\nLemma delta_impR : (P -> Q) -> (P -> P -> Q).\nProof.\n  intros h1 h2.\n  apply h1.\nQed.\n\nLemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> T) -> P -> T.\nProof.\n  intros h1 h2 h3 h4.\n  apply h3.\n  apply h1.\n  apply h4.\n  apply h2.\n  apply h4.\nQed.\nPrint diamond.\n\nLemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\n(* Perice formula: ((P -> Q) -> P) -> P. can't be proved by Coq (Calculus of\n  Constructions), it uses normalization properties in typed lambda-calculi. *)\nProof.\n  intros h1.\n  apply h1.\n  intros h2.\n  apply h2.\n  intros h3.\n  apply h1.\n  intros h4.\n  apply h3.\nQed.\nPrint weak_peirce.\n\n(* Exercise 3.4 *)\n\n(** Typing rules used in minimum propositional logic is: Prod, Lam, App* and Var.\n  for a formula q:\n  + if q is a variable, it can be solved by assumption tactic.\n  + if q is an abstraction, it can be simplified by intro tactic.\n  + if q is an application, it can be solved by apply tactic. **)\n\n(* Exercise 3.5 *)\n\nSection Example_3_5.\n\nHypothesis\n  (h1 : P -> Q)\n  (h2 : Q -> R)\n  (h3 : (P -> R) -> T -> Q)\n  (h4 : (P -> R) -> T).\n\nLemma cut_example' : Q.\nProof.\n  apply h3.\n  intros h5.\n  apply h2; apply h1; apply h5.\n  apply h4.\n  intros h6.\n  apply h2; apply h1; apply h6.\nQed.\nEnd Example_3_5.\nPrint cut_example.\nPrint cut_example'.\n\n(* Exercise 3.6 *)\n\nSection AutoExample.\n\n(** Pattern: according to law of transfer, it's easy to construct a theorem/lemma\n  need to be proved at least arbitrary n steps. **)\n\nVariables P0 P1 P2 P3 P4 P5 : Prop.\nLemma auto_example :\n  (P0 -> P1) ->\n  (P1 -> P2) ->\n  (P2 -> P3) ->\n  (P3 -> P4) ->\n  (P4 -> P5) ->\n  P0 -> P5.\nProof.\n  auto 6.\nQed.\nPrint auto_example.\n\nEnd AutoExample.\n\nEnd Exercises.\n\nEnd PropositionsAndProofs.\n\n(* Abstraction (with universal quatification). *)\nPrint imp_dist.\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/coq-art/PropostionsAndProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7206975264430979}}
{"text": "Theorem rewrite_example_1: forall (a b c d : nat),\n  a = b + c -> b = c + d -> d = 1 -> c = 2 -> a = 5.\nProof.\n  intros a b c d H0 H1 H2 H3.\n  rewrite H0.\n  rewrite H1.\n  rewrite H2.\n  rewrite H3.\n  reflexivity.\nQed.\n\n\n\n", "meta": {"author": "d-krylov", "repo": "coq_examples", "sha": "c8556e538ff62eb46ba1dcd5e5bcf273b45935be", "save_path": "github-repos/coq/d-krylov-coq_examples", "path": "github-repos/coq/d-krylov-coq_examples/coq_examples-c8556e538ff62eb46ba1dcd5e5bcf273b45935be/Rewrite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7206675417999634}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := plus y (plus x Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj275_coqofml_fa6GyZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7206675315924937}}
{"text": "Require Export A_3_5.\n\nModule A4_1.\n\n(* 4.1 连续性的概念 *)\n(* 定义1：函数在一点的连续性 *)\nDefinition Continuous (f : Fun) (x0 : R) :=\n  x0 ∈ dom[f] /\\ limit f x0 f[x0].\n\n(* 左连续 *)\nDefinition ContinuousLeft (f : Fun) (x0 : R) :=\n  x0 ∈ dom[f] /\\ limit_neg f x0 f[x0].\n\n(* 右连续 *)\nDefinition ContinuousRight (f : Fun) (x0 : R) :=\n  x0 ∈ dom[f] /\\ limit_pos f x0 f[x0].\n\n(* 定义：函数在开区间上的连续 *)\nDefinition ContinuousOpen (f : Fun) (a b : R) :=\n  ∀ x, a < x < b -> Continuous f x.\n\n(* 定义：函数在闭区间上的连续 *)\nDefinition ContinuousClose (f : Fun) (a b : R) :=\n  ContinuousOpen f a b /\\ ContinuousRight f a\n  /\\ ContinuousLeft f b.\n\nEnd A4_1.\n\nExport A4_1.", "meta": {"author": "zhaobaoq", "repo": "MathAnalysis", "sha": "f51d41fc9ddfcbe4ac2560e4bda43540b1be2f6a", "save_path": "github-repos/coq/zhaobaoq-MathAnalysis", "path": "github-repos/coq/zhaobaoq-MathAnalysis/MathAnalysis-f51d41fc9ddfcbe4ac2560e4bda43540b1be2f6a/A_4_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7206675286258579}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf2 : natural) : natural :=\n  plus lf2 (mult z (Succ y)).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_assoc/goal33conj193_coqofml_IM03y2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7206675273604669}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\nRequire Turing.Util.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\n(* ---------------------------------------------------------------------------*)\n\n\n\n\n(**\n\nStudy the definition of [Turing.Util.pow] and [Turing.Util.pow1]\nand then show that [Turing.Util.pow1] can be formulated in terms of\n[Turing.Util.pow].\nMaterial: https://gitlab.com/umb-svl/turing/blob/main/src/Util.v\n\n\n *)\nTheorem ex1:\n  forall (A:Type) (x:A) n, Util.pow [x] n = Util.pow1 x n.\nProof.\n  intros.\n  induction n as [|n' IH].\n  - simpl. reflexivity.\n  - simpl.\n    rewrite IH.\n    reflexivity.\nQed.\n\n(**\n\nStudy recursive definition of [List.In] and the inductive definition of\n[List.Exists]. Then show that [List.In] can be formulated in terms\nof [List.Exists].\n\nMaterial: https://coq.inria.fr/library/Coq.Lists.List.html\n\n\n *)\nTheorem ex2:\n  forall (A:Type) (x:A) l, List.Exists (eq x) l <-> List.In x l.\nProof.\n  intros.\n  split.\n  \n  * intros.\n    induction l.\n    - simpl.\n      inversion H.\n    - inversion H.\n      simpl.\n      left.\n      subst.\n      reflexivity.\n      simpl.\n      right.\n      apply IHl in H1.\n      assumption.\n  * intros H.\n    induction l as [|y l' IH].\n    - inversion H.\n    - simpl.\n      destruct H as [H|H].\n      subst.\n      left.\n      reflexivity.\n      right.\n      apply IH.\n      assumption.\nQed.\n\n(**\n\nCreate an inductive relation that holds if, and only if, element 'x'\nappears before element 'y' in the given list.\nWe can define `succ` inductively as follows:\n\n                                (x, y) succ l\n-----------------------R1     ------------------R2\n(x, y) succ x :: y :: l       (x, y) succ z :: l\n\nRule R1 says that x succeeds y in the list that starts with [x, y].\n\nRule R2 says that if x succeeds y in list l then x succeeds y in a list\nthe list that results from adding z to list l.\n\n\n *)\n\nInductive succ {X : Type} (x : X) (y : X) : list X -> Prop :=\n  | r1 : forall (l: list X), succ x y (x :: y :: l)\n  | r2 : forall (z: X) (l: list X), succ x y l -> succ x y (z :: l).\n\n\nTheorem succ1:\n    (* Only one of the following propositions is provable.\n       Replace 'False' by the only provable proposition and then prove it:\n     1) succ 2 3 [1;2;3;4]\n     2) ~ succ 2 3 [1;2;3;4]\n     *)\n    succ 2 3 [1;2;3;4].\nProof.\n  apply r2.\n  apply r1.\nQed.\n\nTheorem succ2:\n    (* Only one of the following propositions is provable.\n       Replace 'False' by the only provable proposition and then prove it:\n     1) succ 2 3 []\n     2) ~ succ 2 3 []\n     *)\n    ~ succ 2 3 [].\nProof.\n  intros h1.\n  inversion h1.\nQed.\n\n\nTheorem succ3:\n    (* Only one of the following propositions is provable.\n       Replace 'False' by the only provable proposition and then prove it:\n     1) succ 2 4 [1;2;3;4]\n     2) ~ succ 2 4 [1;2;3;4]\n     *)\n    ~ succ 2 4 [1;2;3;4].\nProof.\n  intros h1.\n  inversion h1.\n  inversion H0.\n  inversion H3.\n  inversion H6.\n  inversion H9.\nQed.\n\n\nTheorem succ4:\n  forall (X:Type) (x y : Type), succ x y [x;y].\nProof.\n  intros.\n  apply r1.\nQed.\n\n\nTheorem ex3:\n  forall (X:Type) (l1 l2:list X) (x y:X), succ x y (l1 ++ (x :: y :: l2)).\nProof.\n  intros.\n  induction l1, l2.\n  - simpl.\n    apply r1.\n  - simpl.\n    apply r1.\n  - simpl.\n    inversion IHl1.\n    apply r2.\n    apply r1.\n    apply r2.\n    apply r2.\n    assumption.\n  - simpl.\n    inversion IHl1.\n    apply r2.\n    apply r1.\n    apply r2.\n    apply r2.\n    assumption.\nQed.\n\n\nTheorem ex4:\n  forall (X:Type) (x y:X) (l:list X), succ x y l -> exists l1 l2, l1 ++ (x:: y:: l2) = l.\nProof.\n\nAdmitted.\n\n\n\n", "meta": {"author": "javidan1", "repo": "cs420", "sha": "03edcef80b43dc84ed6a0beebd6ad3e201fa8834", "save_path": "github-repos/coq/javidan1-cs420", "path": "github-repos/coq/javidan1-cs420/cs420-03edcef80b43dc84ed6a0beebd6ad3e201fa8834/hw2/hw2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.7206432775953862}}
{"text": "Require Import Rbase Reals ZArith QArith micromega.Lia micromega.Lqa micromega.Lra Qreals.\n\nFrom BY Require Import Rlemmas IZR.\n\nLocal Open Scope Z.\nLocal Open Scope R.\nLocal Coercion IZR : Z >-> R.\n\nDefinition floor a := ((up a) - 1)%Z.\n\nLtac lira :=\n  lra +\n  (autorewrite with push_izr; try apply lt_IZR; lra) +\n  (autorewrite with push_izr; try apply le_IZR; lra) +\n  (autorewrite with pull_izr;\n       match goal with\n       | [ |- IZR _ < IZR _ ] => try apply IZR_lt\n       | [ |- IZR _ <= IZR _ ] => try apply IZR_le\n       end; lia).\n\nLemma floor_upper_bound a b : a <= b -> IZR (floor a) <= b.\nProof. unfold floor; pose proof archimed a; rewrite minus_IZR; lra. Qed.\n\nLemma floor_lower_bound a b : b <= a - 1 -> b < IZR (floor a).\nProof. unfold floor; pose proof archimed a; rewrite minus_IZR; lra. Qed.\n\nLemma floor_spec a : IZR (floor a) <= a /\\ (a - 1 < IZR (floor a)).\nProof. split; [apply floor_upper_bound| apply floor_lower_bound]; reflexivity. Qed.\n\nLemma up0 : up 0 = 1%Z.\nProof. symmetry; apply tech_up; lra. Qed.\n\nLemma floor0 : floor 0 = 0%Z.\nProof. unfold floor; rewrite up0; lia. Qed.\n\nLemma floor_eq (r : R) (z : Z) : z <= r -> r < z + 1 -> z = floor r.\nProof. intros. unfold floor. epose proof tech_up r (z + 1) _ _; lia.\n       Unshelve. rewrite plus_IZR; lra. rewrite plus_IZR; lra. Qed.\n\nLemma floor_inc a b : a <= b -> (floor a <= floor b)%Z.\nProof.\n  intros; pose proof floor_spec a as [? ?]; pose proof floor_spec b as [? ?].\n  apply le_IZR; destruct (Rlt_dec b (floor a + 1)).\n  - assert (eq : floor a = floor b) by (apply floor_eq; lra); rewrite eq; lra.\n  - lra. Qed.\n\nLemma floor_inv_inc a b : floor a <= floor b -> a < b + 1.\nProof. pose proof floor_spec a as [? ?]; pose proof floor_spec b as [? ?]; lra. Qed.\n\nLemma floor_pos a : 0 <= a -> (0 <= floor a)%Z.\nProof. replace 0%Z with (floor 0) at 2 by apply floor0; apply floor_inc. Qed.\n\nLemma floor_div a b : floor (IZR a / IZR b)%R = (a / b)%Z.\nProof.\n  destruct (Z.eq_dec b 0); [subst; rewrite div_0_r, Zdiv.Zdiv_0_r; apply floor0|].\n  assert (IZR b <> 0) by (apply IZR_neq; assumption).\n\n  destruct (Znumtheory.Zdivide_dec b a).\n  - symmetry; apply floor_eq; rewrite div_IZR; try lra; assumption.\n  - unfold floor. enough (((a / b) + 1)%Z = up (a / b)) by lia.\n    apply tech_up.\n    + apply Rlt_le_trans with (r2 := (a / b) + ((b - a mod b) / b)).\n      assert (0 < ((b - a mod b) / b)).\n      { destruct (Z_le_dec 0 b).\n        { pose proof Z.mod_pos_bound a b ltac:(lia) as [].\n          apply div_pos_nonneg; lira. }\n        { pose proof Z.mod_neg_bound a b ltac:(lia) as [].\n          apply div_neg_nonneg; lira. } }\n      lra.\n      rewrite <- Rdiv_plus_distr.\n      autorewrite with pull_izr. rewrite <- div_IZR.\n      rewrite Zdiv.Zmod_eq_full by lia.\n      replace (a + (b - (a - a / b * b)))%Z with (b + a / b * b)%Z by lia.\n      rewrite Z.div_add, Zdiv.Z_div_same_full by lia. lira.\n\n      rewrite Zdiv.Zmod_eq_full.\n      replace (a + (b - (a - a / b * b)))%Z with (b * (1 + a / b))%Z by lia. apply Z.divide_factor_l. lia.\n    + pose proof Rdiv_div a b. lira. Qed.\n", "meta": {"author": "bshvass", "repo": "by-inversion", "sha": "281c10e6435a86e39b2c6e1829aa874e45147140", "save_path": "github-repos/coq/bshvass-by-inversion", "path": "github-repos/coq/bshvass-by-inversion/by-inversion-281c10e6435a86e39b2c6e1829aa874e45147140/src/Floor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7206432729482719}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Bool.Bool.\nRequire Import vecs_new.\n\nDefinition bool_le (x y : bool) : Prop :=\n  match x with\n    false => True\n  | true => match y with \n      false => False \n    | true => True\n    end\n  end.\n\nFixpoint vec_le (n : nat) : vec bool n -> vec bool n -> Prop :=\n  match n as n return vec bool n -> vec bool n -> Prop with\n    0   => fun _ _ => True\n  | S m => fun v w => bool_le (vhead v) (vhead w) /\\ vec_le m (vtail v) (vtail w)\n  end.\n\nLemma vec_le_correct (n : nat)(v w : vec bool n) :\n  vec_le n v w -> forall i : fin n,\n    bool_le (item_at bool n i v) (item_at bool n i w).\nProof.\n  intros.\n  induction n.\n  destruct i.\n  destruct v,w,i.\n  destruct b,b0,u.\n  simpl.\n  reflexivity.\n  simpl in H.\n  destruct H.\n  contradiction.\n  simpl.\n  reflexivity.\n  simpl.\n  reflexivity.\n  simpl.\n  simpl in H.\n  apply IHn.\n  apply H.\nQed.   \n\nFixpoint index_eqb (n : nat) : fin n -> fin n -> bool :=\n  match n as n return fin n -> fin n -> bool with\n    0   => fun e e' => emptyf bool e\n  | S n => fun i j =>\n    match i , j with\n      inl tt , inl tt => true\n    | inl tt , inr l  => false\n    | inr k  , inl tt => false\n    | inr k  , inr l  => index_eqb n k l\n    end\n  end.\n\nDefinition conn (k : nat) :=\n  vec bool k -> bool.\n\nDefinition conn_ext_eq (n : nat) (f g : conn n) :=\n  forall v , f v = g v.\n\nNotation \"f [=] g\" := (conn_ext_eq f g) (at level 38, right associativity).\n\nDefinition comp (n k : nat) (f : conn n) (gs : vec (conn k) n) : conn k :=\n  fun xs => f (vec_ap bool n gs xs).\n(*\nDefinition remove_component (n m : nat) (f : conn (n + m)) : conn (n + S m) :=\n  fun x => f (rm_nth_vec Bool n m x).\n*)\nDefinition ID  : conn 1 :=\n  fun v => match v with\n           |[ b ] => b\n           end.\n\nDefinition NOT : conn 1 :=\n  fun v => match v with\n           |[ b ] => negb b\n           end.\n\nDefinition AND : conn 2 :=\n  fun v => match v with\n           |[ b1 , b2 ] => andb b1 b2\n           end.\n\nDefinition OR : conn 2 :=\n  fun v => match v with\n           |[ b1 , b2 ] => orb b1 b2\n           end.\n\nDefinition IMPL : conn 2 :=\n  fun v => match v with\n           |[ b1 , b2 ] => implb b1 b2\n           end.\n\nDefinition rIMPL : conn 2 :=\n  fun v => match v with\n           |[ b1 , b2 ] => match b1,b2 with\n                           |false , false => true\n                           |false , true  => false\n                           |true  , false => true\n                           |true  , true  => true\n                           end\n           end.\n\nDefinition const (k : nat)(x : bool) : conn k :=\n  fun v => x.\n\nDefinition proj (n : nat) (i : fin n) : conn n :=\n  fun v : vec bool n => item_at bool n i v .\n\nDefinition p1 : conn 2 := \n  proj 2 (inl tt).\n\nDefinition p2 : conn 2 := \n  proj 2 (inr (inl tt)).\n\n(* Definition of definable from a set X of connectives *)\nInductive Definable(X : forall n:nat, conn n -> Prop) : forall k, conn k -> Prop :=\n  | atom_def : forall (n : nat)(f : conn n), X n f -> Definable X f\n  | null_def : forall x : bool, Definable X (const 1 x) -> Definable X (const 0 x)\n  | project  : forall (n : nat) (i : fin n), Definable X (proj n i)\n  | compose  : forall (n k : nat) (f : conn n) (gs : vec (conn k) n),\n               Definable X f -> (forall i : fin n, Definable X (item_at (conn k) n i gs)) -> Definable X (comp k f gs)\n  | def_ext  : forall (n : nat) (f g : conn n), Definable X f -> f [=] g -> Definable X g.\n\n(*functionally complete*)\nDefinition FC(X : forall n:nat, conn n -> Prop) :=\n  (forall (n : nat)(f : conn n), Definable X f).\n\nDefinition DeM_or := \n  comp 2 NOT [ comp 2 AND [ comp 2 NOT [ p1 ] , comp 2 NOT [ p2 ] ] ].\n\nLemma or_def : DeM_or [=] OR.\nProof.\n  unfold DeM_or.\n  unfold comp.\n  intros v.\n  destruct v as [b1 [b2 u]].\n  destruct b1, b2, u; simpl; reflexivity.\nQed.\n\n(* two lemmas which make the compose rule easier to use *)\nLemma unit_comp_def(X : forall n:nat, conn n -> Prop) : forall k, forall f : conn 1, forall g : conn k,\n  Definable X f -> Definable X g -> Definable X (comp k f [ g ]).\nProof.\n  intros.\n  apply compose.\n  exact H.\n  intro.\n  destruct i.\n  destruct u.\n  simpl.\n  exact H0.\n  destruct f0.\nQed.\n\nLemma bin_comp_def(X : forall n:nat, conn n -> Prop) : forall k, forall f : conn 2 , forall g1 g2 : conn k,\n  Definable X f -> Definable X g1 -> Definable X g2 -> Definable X (comp k f [g1 , g2]).\nProof.\n  intros.\n  apply compose.\n  exact H.\n  destruct i.\n  destruct u.\n  simpl.\n  exact H0.\n  destruct f0.\n  destruct u.\n  simpl.\n  exact H1.\n  destruct f0.\nQed.\n\nLemma id_proj : proj 1 (inl tt) [=] ID.\nProof.\n  unfold ID, proj.\n  intro v.\n  destruct v as [b u].\n  destruct b,u; simpl; reflexivity.\nQed.\n\nLemma id_def(X : forall n:nat, conn n -> Prop) : Definable X ID.\nProof.\n  assert (Definable X (proj 1 (inl tt))).\n  apply project.\n  apply (def_ext H).\n  exact id_proj.\nQed.\n\nLemma or_from_and_not(X : forall n:nat, conn n -> Prop) : Definable X AND -> Definable X NOT -> Definable X OR.\nProof.\n  intros.\n  assert (Definable X DeM_or).\n  apply unit_comp_def.\n  exact H0.\n  apply bin_comp_def.\n  exact H.\n  apply unit_comp_def.\n  exact H0.\n  apply project.\n  apply unit_comp_def.\n  exact H0.\n  apply project.\n  apply (def_ext H1).\n  apply or_def.\nQed.\n\nDefinition DeM_and := \n  comp 2 NOT [ comp 2 OR [ comp 2 NOT [ p1 ] , comp 2 NOT [ p2 ] ] ].\n\nLemma and_DeM_def : DeM_and [=] AND.\nProof.\n  unfold DeM_and.\n  unfold comp.\n  intros v.\n  destruct v as [b1 [b2 u]].\n  destruct b1, b2, u; simpl; reflexivity.\nQed.  \n\nLemma and_from_or_not(X : forall n:nat, conn n -> Prop) : Definable X OR -> Definable X NOT -> Definable X AND.\nProof.\n  intros.\n  assert (Definable X DeM_and).\n  apply unit_comp_def.\n  exact H0.\n  apply bin_comp_def.\n  exact H.\n  apply unit_comp_def.\n  exact H0.\n  apply project.\n  apply unit_comp_def.\n  exact H0.\n  apply project.\n  apply (def_ext H1).\n  apply and_DeM_def.\nQed.\n\nDefinition DS_or :=\n  comp 2 IMPL [comp 2 NOT [ p1 ] , p2].\n\nLemma or_DS_def : DS_or [=] OR.\nProof.\n  unfold DS_or.\n  unfold comp.\n  intros v.\n  destruct v as [b1 [b2 u]].\n  destruct b1, b2, u; simpl; reflexivity.\nQed.\n\nLemma or_from_impl_not(X : forall n:nat, conn n -> Prop) : Definable X IMPL -> Definable X NOT -> Definable X OR.\nProof.\n  intros.\n  assert (Definable X DS_or).\n  apply bin_comp_def.\n  exact H.\n  apply unit_comp_def.\n  exact H0.\n  apply project.\n  apply project.\n  apply (def_ext H1).\n  apply or_DS_def.\nQed.\n\nDefinition rDS_or :=\n  comp 2 rIMPL [p1 , comp 2 NOT [ p2 ]].\n\nLemma or_rDS_def : rDS_or [=] OR.\nProof.\n  unfold rDS_or.\n  unfold comp.\n  intros v.\n  destruct v as [b1 [b2 u]].\n  destruct b1, b2, u; simpl; reflexivity.\nQed.\n\nLemma or_from_rimpl_not(X : forall n:nat, conn n -> Prop) : Definable X rIMPL -> Definable X NOT -> Definable X OR.\nProof.\n  intros.\n  assert (Definable X rDS_or).\n  apply bin_comp_def.\n  exact H.\n  apply project.\n  apply unit_comp_def.\n  exact H0.\n  apply project.\n  apply (def_ext H1).\n  apply or_rDS_def.\nQed.\n\nDefinition NonCon_F := comp 1 AND [ ID , NOT ].\n\nLemma f_def : NonCon_F [=] (const 1 false).\nProof.\n  unfold NonCon_F.\n  unfold comp.\n  intro v.\n  destruct v as [b u].\n  destruct b, u; simpl; reflexivity.  \nQed.\n\nLemma f_from_and_not(X : forall n:nat, conn n -> Prop) : Definable X AND -> Definable X NOT -> Definable X (const 1 false).\nProof.\n  intros.\n  assert (Definable X NonCon_F).\n  apply bin_comp_def.\n  exact H.\n  apply id_def.\n  exact H0.\n  apply (def_ext H1).\n  apply f_def.\nQed.\n\nDefinition LEM_T := comp 1 OR [ID , NOT].\n\nLemma t_def : LEM_T [=] (const 1 true).\nProof.\n  unfold LEM_T.\n  unfold comp.\n  intro v.\n  destruct v as [b u].\n  destruct b,u; simpl; reflexivity.\nQed.\n\nLemma t_from_and_not(X : forall n:nat, conn n -> Prop) : Definable X AND -> Definable X NOT -> Definable X (const 1 true).\nProof.\n  intros.\n  assert (Definable X LEM_T).\n  apply bin_comp_def.\n  apply or_from_and_not.\n  exact H.\n  exact H0.\n  apply id_def.\n  exact H0.\n  apply (def_ext H1).\n  apply t_def.\nQed.\n\nLemma nullconn_is_constant : forall f : conn 0, (const 0 false) [=] f \\/ (const 0 true) [=] f.\nProof.\n  intro f.\n  assert (f tt = false \\/ f tt = true).\n  destruct (f tt).\n  right; reflexivity.\n  left; reflexivity.\n  destruct H.\n  left.\n  intro.\n  destruct v.\n  rewrite H; simpl; reflexivity.\n  right.\n  intro.\n  destruct v.\n  rewrite H; simpl; reflexivity.\nQed.\n\nLemma all_nullconn_from_and_not(X : forall n:nat, conn n -> Prop) : Definable X AND -> Definable X NOT -> \n  (forall f:conn 0, Definable X f).\nProof.\n  intros.\n  destruct (nullconn_is_constant f).\n  assert (Definable X (const 0 false)).\n  apply null_def.\n  apply f_from_and_not.\n  exact H.\n  exact H0.\n  apply (def_ext H2).\n  exact H1.\n  assert (Definable X (const 0 true)).\n  apply null_def.\n  apply t_from_and_not.\n  exact H.\n  exact H0.\n  apply (def_ext H2).\n  exact H1.\nQed.\n\nLemma ext_unit_subst : forall (n : nat)(f : conn 1)(g h : conn n),\n  g [=] h -> comp n f [ g ] [=] comp n f [ h ].\nProof.\n  intros.\n  intro v.\n  unfold comp.\n  simpl.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma ext_bin_subst : forall (n : nat)(f : conn 2)(g1 g2 h1 h2 : conn n),\n  g1 [=] h1 -> g2 [=] h2 -> comp n f [ g1 , g2 ] [=] comp n f [ h1 , h2 ].\nProof.\n  intros.\n  intro v.\n  unfold comp.\n  simpl.\n  rewrite H, H0.\n  reflexivity.\nQed.\n\n(* some lemmas for simplifying expressions with AND and OR *)\n\nLemma and_left_f : forall (n:nat)(g h : conn n)(v : vec bool n),\n  g v = false -> comp n AND [g , h] v = false.\nProof.\n  intros.\n  unfold comp.\n  simpl.\n  rewrite H.\n  apply andb_false_l.\nQed.\n\nLemma and_left_t : forall (n:nat)(g h : conn n)(v : vec bool n),\n  g v = true -> comp n AND [g , h] v = h v.\nProof.\n  intros.\n  unfold comp.\n  simpl.\n  rewrite H.\n  apply andb_true_l.\nQed.\n\nLemma or_left_f : forall (n:nat)(g h : conn n)(v : vec bool n),\n  g v = false -> comp n OR [g , h] v = h v.\nProof.\n  intros.\n  unfold comp.\n  simpl.\n  rewrite H.\n  apply orb_false_l.\nQed.\n\nLemma or_left_t : forall (n:nat)(g h : conn n)(v : vec bool n),\n  g v = true -> comp n OR [g , h] v = true.\nProof.\n  intros.\n  unfold comp.\n  simpl.\n  rewrite H.\n  apply orb_true_l.\nQed.\n\nLemma or_right_f : forall (n:nat)(g h : conn n)(v : vec bool n),\n  h v = false -> comp n OR [g , h] v = g v.\nProof.\n  intros.\n  unfold comp.\n  simpl.\n  rewrite H.\n  apply orb_false_r.\nQed.\n\nLemma or_right_t : forall (n:nat)(g h : conn n)(v : vec bool n),\n  h v = true -> comp n OR [g , h] v = true.\nProof.\n  intros.\n  unfold comp.\n  simpl.\n  rewrite H.\n  apply orb_true_r.\nQed.\n\nDefinition change_first_arg (n : nat) (f : conn (S n)) (x : bool) : conn (S n) :=\n  fun v => f (x,(vtail v)).\n\n(*\nLemma remove_eq (n : nat)(f : conn (S n))(x : bool) : \n  remove_component 0 n (fun v => f (x,v)) [=] (remove_first_arg f x).\nProof.\n  intro v.\n  simpl v; destruct v.\n  simpl.\n  unfold remove_component.\n  unfold remove_first_arg.\n  simpl.\n  unfold vcons; reflexivity.\nQed.\n*)\n(* the idea: fun x,ybar => (x /\\ (f T,ybar)) \\/ (~x /\\ (f F,ybar)) *) \n\nDefinition and_or_not_form (n : nat) (f : conn (S n)) : conn (S n) :=\n  comp (S n) OR \n    [ \n      (comp (S n) AND [ (proj (S n) (inl tt)) , (change_first_arg f true) ] ) , \n      (comp (S n) AND [ comp (S n) NOT [ proj (S n) (inl tt)] , change_first_arg f false ] )\n    ].\n\nLemma first_proj_lemma : forall (n : nat)(x : bool)(v : vec bool n), proj (S n) (inl tt) (x,v) = x.\nProof.\n  intros.\n  unfold proj.\n  simpl.\n  reflexivity.\nQed.\n\nLemma un_comp_lemma : forall (n : nat)(f : conn 1)(g : conn (S n))(v : vec bool (S n)),\n  comp (S n) f [ g ] v = f ( [ g v ] ).\nProof.\n  intros.\n  unfold comp.\n  simpl.\n  reflexivity.\nQed.\n\nLemma and_or_not_eq : forall (n : nat)(f : conn (S n)), and_or_not_form f [=] f.\nProof.\n  intros n f v.\n  destruct v.\n  unfold and_or_not_form.\n  unfold comp.\n  unfold change_first_arg.\n  destruct b.\n  simpl.\n  apply orb_false_r.\n  simpl.\n  reflexivity.\nQed.\n\nDefinition proj_vec(n : nat) : vec (conn n) n := to_vec n (fun i => proj n i).\n\nLemma proj_vec_correct : forall (n : nat)(v : vec bool n), vec_ap bool n (proj_vec n) v = v.\nProof.\n  intros.\n  unfold proj_vec.\n  apply vec_ext.\n  intro i.\n  rewrite vec_ap_lemma.\n  rewrite to_vec_correct.\n  unfold proj.\n  reflexivity.\nQed.\n\nLemma ignore_first_proj_def : forall (n : nat)(g : conn n),\n  comp (S n) g (vtail (proj_vec (S n))) [=] (fun v => g (vtail v)).\nProof.\n  intros.\n  intro v.\n  unfold comp.\n  f_equal.\n  rewrite vec_ap_vtail_comm.\n  f_equal.\n  apply proj_vec_correct.\nQed.\n\nLemma ignore_first_definable(X : forall n:nat, conn n -> Prop) :  forall (n : nat)(f : conn (S n)),\n  (exists g : conn n, Definable X g /\\  (fun v => g (vtail v)) [=] f) -> Definable X f.\nProof.\n  intros.\n  destruct H as [g [gDef Hfg]].\n  assert (Definable X (fun v => g (vtail v))).\n  assert (Definable X (comp (S n) g (vtail (proj_vec (S n))))).\n  apply compose.\n  exact gDef.\n  intro i.\n  simpl.\n  rewrite to_vec_correct.\n  apply project.\n  apply (def_ext H).\n  intro v.\n  apply ignore_first_proj_def.\n  apply (def_ext H).\n  exact Hfg.\nQed.  \n\nLemma and_not_func_complete(X : forall n:nat, conn n -> Prop) : Definable X AND -> Definable X NOT ->\n  FC X.\nProof.\n  intros.\n  induction n.\n  apply all_nullconn_from_and_not.\n  exact H.\n  exact H0.\n  intro f.\n  assert (Definable X (and_or_not_form f)).\n  apply bin_comp_def.\n  apply or_from_and_not.\n  exact H.\n  exact H0.\n  apply bin_comp_def.\n  exact H.\n  apply project.\n  apply ignore_first_definable.\n  exists (fun v => f (true,v)).\n  split.\n  apply IHn.\n  intro v.\n  unfold change_first_arg.\n  reflexivity.\n  apply compose.\n  exact H.\n  intro i; destruct i.\n  destruct u.\n  simpl.\n  apply compose.\n  exact H0.\n  intro i; destruct i.\n  destruct u.\n  simpl.\n  apply project.\n  destruct f0.\n  destruct f0.\n  destruct u.\n  simpl.\n  apply ignore_first_definable.\n  exists (fun v => f (false,v)).\n  split.\n  apply IHn.\n  intro v.\n  unfold change_first_arg; reflexivity.\n  destruct f0.\n  apply (def_ext H1).\n  apply and_or_not_eq.\nQed.", "meta": {"author": "emarzion", "repo": "coq-project", "sha": "837dcb84a857718c5fbfe72ac196e3a4d886c8c5", "save_path": "github-repos/coq/emarzion-coq-project", "path": "github-repos/coq/emarzion-coq-project/coq-project-837dcb84a857718c5fbfe72ac196e3a4d886c8c5/andnot_new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7206432716747224}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nLocal Open Scope Z_scope.\n\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.Saturated.Core.\nRequire Import Crypto.Util.ZUtil.\nRequire Import Crypto.Util.LetIn Crypto.Util.Tuple.\nLocal Notation \"A ^ n\" := (tuple A n) : type_scope.\n\nSection UniformWeight.\n  Context (bound : Z) {bound_pos : bound > 0}.\n\n  Definition uweight : nat -> Z := fun i => bound ^ Z.of_nat i.\n  Lemma uweight_0 : uweight 0%nat = 1. Proof. reflexivity. Qed.\n  Lemma uweight_positive i : uweight i > 0.\n  Proof. apply Z.lt_gt, Z.pow_pos_nonneg; omega. Qed.\n  Lemma uweight_nonzero i : uweight i <> 0.\n  Proof. auto using Z.positive_is_nonzero, uweight_positive. Qed.\n  Lemma uweight_multiples i : uweight (S i) mod uweight i = 0.\n  Proof. apply Z.mod_same_pow; rewrite Nat2Z.inj_succ; omega. Qed.\n  Lemma uweight_divides i : uweight (S i) / uweight i > 0.\n  Proof.\n    cbv [uweight]. rewrite <-Z.pow_sub_r by (rewrite ?Nat2Z.inj_succ; omega).\n    apply Z.lt_gt, Z.pow_pos_nonneg; rewrite ?Nat2Z.inj_succ; omega.\n  Qed.\n\n  (* TODO : move to Positional *)\n  Lemma eval_from_eq {n} (p:Z^n) wt offset :\n    (forall i, wt i = uweight (i + offset)) ->\n    B.Positional.eval wt p = B.Positional.eval_from uweight offset p.\n  Proof. cbv [B.Positional.eval_from]. auto using B.Positional.eval_wt_equiv. Qed.\n\n  Lemma uweight_eval_from {n} (p:Z^n): forall offset,\n    B.Positional.eval_from uweight offset p = uweight offset * B.Positional.eval uweight p.\n  Proof.\n    induction n; intros; cbv [B.Positional.eval_from];\n      [|rewrite (subst_append p)];\n    repeat match goal with\n           | _ => destruct p\n           | _ => rewrite B.Positional.eval_unit; [ ]\n           | _ => rewrite B.Positional.eval_step; [ ]\n           | _ => rewrite IHn; [ ]\n           | _ => rewrite eval_from_eq with (offset0:=S offset)\n               by (intros; f_equal; omega)\n           | _ => rewrite eval_from_eq with\n                  (wt:=fun i => uweight (S i)) (offset0:=1%nat)\n               by (intros; f_equal; omega)\n           | _ => ring\n           end.\n    repeat match goal with\n           | _ => cbv [uweight]; progress autorewrite with natsimplify\n           | _ => progress (rewrite ?Nat2Z.inj_succ, ?Nat2Z.inj_0, ?Z.pow_0_r)\n           | _ => rewrite !Z.pow_succ_r by (try apply Nat2Z.is_nonneg; omega)\n           | _ => ring\n           end.\n  Qed.\n\n  Lemma uweight_eval_step {n} (p:Z^S n):\n    B.Positional.eval uweight p = hd p + bound * B.Positional.eval uweight (tl p).\n  Proof.\n    rewrite (subst_append p) at 1; rewrite B.Positional.eval_step.\n    rewrite eval_from_eq with (offset := 1%nat) by (intros; f_equal; omega).\n    rewrite uweight_eval_from. cbv [uweight]; rewrite Z.pow_0_r, Z.pow_1_r.\n    ring.\n  Qed.\n\n  Lemma uweight_le_mono n m : (n <= m)%nat ->\n    uweight n <= uweight m.\n  Proof.\n    unfold uweight; intro; Z.peel_le; omega.\n  Qed.\n\n  Lemma uweight_lt_mono (bound_gt_1 : bound > 1) n m : (n < m)%nat ->\n    uweight n < uweight m.\n  Proof.\n    clear bound_pos.\n    unfold uweight; intro; apply Z.pow_lt_mono_r; omega.\n  Qed.\n\n  Lemma uweight_succ n : uweight (S n) = bound * uweight n.\n  Proof.\n    unfold uweight.\n    rewrite Nat2Z.inj_succ, Z.pow_succ_r by auto using Nat2Z.is_nonneg; reflexivity.\n  Qed.\n\n\n  Definition small {n} (p : Z^n) : Prop :=\n    forall x, In x (to_list _ p) -> 0 <= x < bound.\n\nEnd UniformWeight.", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Arithmetic/Saturated/UniformWeight.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7206432659776003}}
{"text": "(******************************************************************************)\nFrom Coq Require Import Wf_nat Arith Lists.List Peano_dec. \n\nRequire Import ListExt. (* todo: use stdlib? *)\nRequire Export fol.\n\nSection Fol_Properties.\n\nVariable L : Language.\n\nNotation Formula := (Formula L) (only parsing).\nNotation Formulas := (Formulas L) (only parsing).\nNotation System := (System L) (only parsing).\nNotation Term := (Term L) (only parsing).\nNotation Terms := (Terms L) (only parsing).\n  \nLet lt_depth := lt_depth L.\n\nSection Free_Variables.\n\nFixpoint freeVarTerm (s : fol.Term L) : list nat :=\n  match s with\n  | var v => v :: nil\n  | apply f ts => freeVarTerms (arityF L f) ts\n  end\nwith freeVarTerms (n : nat) (ss : fol.Terms L n) {struct ss} : list nat :=\n       match ss with\n       | Tnil => nil (A:=nat)\n       | Tcons m t ts => freeVarTerm t ++ freeVarTerms m ts\n       end.\n\nLemma freeVarTermApply :\n  forall (f : Functions L) (ts : fol.Terms L _),\n    freeVarTerm (apply f ts) = freeVarTerms _ ts.\nProof. reflexivity. Qed.\n\nFixpoint freeVarFormula (A : fol.Formula L) : list nat :=\n  match A with\n  | equal t s => freeVarTerm t ++ freeVarTerm s\n  | atomic r ts => freeVarTerms _ ts\n  | impH A B => freeVarFormula A ++ freeVarFormula B\n  | notH A => freeVarFormula A\n  | forallH v A => List.remove  eq_nat_dec v (freeVarFormula A)\n  end.\n\nDefinition ClosedSystem (T : fol.System L) :=\n  forall (v : nat) (f : fol.Formula L),\n    mem _ T f -> ~ In v (freeVarFormula f).\n\nFixpoint closeList (l: list nat)(a : fol.Formula L) :=\n match l with\n   nil => a\n|  cons v l =>  (forallH v (closeList l a))\nend.\n\n(* Todo : use stdlib's nodup *)\n\nDefinition close (x : fol.Formula L) : fol.Formula L :=\n  closeList (List.nodup eq_nat_dec (freeVarFormula x)) x.\n\nLemma freeVarClosedList1 :\n  forall (l : list nat) (v : nat) (x : fol.Formula L),\n    In v l -> ~ In v (freeVarFormula (closeList l x)).\nProof.\n  intro l; induction l as [| a l Hrecl].\n  - intros v x H; elim H.\n  - intros v x H; induction H as [H| H].\n    + simpl in |- *; rewrite H.\n      unfold not in |- *; intros H0;\n        elim (in_remove_neq _ _ _ _ _ H0); reflexivity.\n    + simpl in |- *.  intro H0. \n      assert (H1: In v (freeVarFormula (closeList l x))).\n      { eapply in_remove.   apply H0. }\n      apply (Hrecl _ _ H H1).\nQed.\n\nLemma freeVarClosedList2 :\n  forall (l : list nat) (v : nat) (x : fol.Formula L),\n    In v (freeVarFormula (closeList l x)) ->\n    In v (freeVarFormula x).\nProof.\n  intro l; induction l as [| a l Hrecl].\n  - simpl; intros v x H; apply H.\n  - simpl; intros v x H; apply Hrecl; eapply in_remove;  apply H.\nQed.\n\nLemma freeVarClosed :\n  forall (x : fol.Formula L) (v : nat), ~ In v (freeVarFormula (close x)).\nProof.\n  intros x v; unfold close;\n  destruct (In_dec eq_nat_dec v (List.nodup eq_nat_dec (freeVarFormula x)))\n    as [i | n]. \n  - apply freeVarClosedList1; assumption.\n  - intro H; elim n. rewrite nodup_In.  \n    eapply freeVarClosedList2; apply H.\nQed.\n\nFixpoint freeVarListFormula (l : fol.Formulas L) : list nat :=\n  match l with\n  | nil => nil (A:=nat)\n  | f :: l => freeVarFormula f ++ freeVarListFormula l\n  end.\n\nLemma freeVarListFormulaApp :\n  forall a b : fol.Formulas L,\n    freeVarListFormula (a ++ b) =\n      freeVarListFormula a ++ freeVarListFormula b.\nProof.\n  intros a b; induction a as [| a a0 Hreca].\n  - reflexivity.\n  - simpl in |- *; rewrite Hreca; now rewrite List.app_assoc. \nQed.\n\nLemma In_freeVarListFormula :\n  forall (v : nat) (f : fol.Formula L) (F : fol.Formulas L),\n    In v (freeVarFormula f) -> In f F -> In v (freeVarListFormula F).\nProof.\n  intros v f F H H0; induction F as [| a F HrecF].\n  - elim H0.\n  - destruct H0 as [H0| H0]; simpl in |- *.\n    + apply in_or_app; left; now rewrite H0.\n    + apply in_or_app; auto.\nQed.\n\nLemma In_freeVarListFormulaE :\n  forall (v : nat) (F : fol.Formulas L),\n    In v (freeVarListFormula F) ->\n    exists f : fol.Formula L, In v (freeVarFormula f) /\\ In f F.\nProof.\n  intros v F H; induction F as [| a F HrecF].\n  - destruct H.\n  - destruct (in_app_or _ _ _ H) as [H0 | H0].\n    + exists a; simpl in |- *; auto.\n    + destruct (HrecF H0) as [x Hx]; exists x; cbn; tauto.\nQed.\n\nDefinition In_freeVarSys (v : nat) (T : fol.System L) :=\n  exists f : fol.Formula L, List.In v (freeVarFormula f) /\\ mem _ T f.\n\nLemma notInFreeVarSys :\n  forall x, ~ In_freeVarSys x (Ensembles.Empty_set (fol.Formula L)).\nProof.\n  intros x; unfold In_freeVarSys in |- *.\n  intros [? [? H0]]; destruct H0. \nQed.\n\nEnd Free_Variables.\n\nSection Substitution.\n\nFixpoint substituteTerm (s : fol.Term L) (x : nat) \n  (t : fol.Term L) {struct s} : fol.Term L :=\n  match s with\n  | var v =>\n      match eq_nat_dec x v with\n      | left _ => t\n      | right _ => var v\n      end\n  | apply f ts => apply f (substituteTerms _ ts x t)\n  end\nwith substituteTerms (n : nat) (ss : fol.Terms L n) \n       (x : nat) (t : fol.Term L) {struct ss} : fol.Terms L n :=\n       match ss in (fol.Terms _ n0) return (fol.Terms L n0) with\n       | Tnil => Tnil\n       | Tcons m s ts =>\n           Tcons  (substituteTerm s x t) \n             (substituteTerms m ts x t)\n       end.\n\nLemma subTermVar1 :\n  forall (v : nat) (s : fol.Term L), substituteTerm (var v) v s = s.\nProof.\n  intros v s;  unfold substituteTerm in |- *.\n  destruct  (eq_nat_dec v v) as [e | b].\n  - reflexivity.\n  - now destruct b.\nQed.\n\nLemma subTermVar2 :\n  forall (v x : nat) (s : fol.Term L),\n    v <> x -> substituteTerm (var x) v s = var x.\nProof.\n  intros v x s H; unfold substituteTerm in |- *.\n  destruct (eq_nat_dec v x).\n  - contradiction. \n  - reflexivity.\nQed.\n\nLemma subTermFunction :\n  forall (f : Functions L) (ts : fol.Terms L (arityF L f)) \n         (v : nat) (s : fol.Term L),\n    substituteTerm (apply f ts) v s = apply f (substituteTerms _ ts v s).\nProof. reflexivity. Qed.\n\nDefinition newVar (l : list nat) : nat := fold_right Nat.max 0 (map S l).\n\nLemma newVar2 : forall (l : list nat) (n : nat), In n l -> n < newVar l.\nProof.\n  induction l as [| a l Hrecl].\n  - destruct 1.\n  - destruct 1 as [H| H].\n    + rewrite H; unfold newVar in |- *; simpl in |- *.\n      induction (fold_right Nat.max 0 (map S l)).\n      * apply Nat.lt_succ_diag_r .\n      * apply Nat.lt_succ_r;  apply Nat.le_max_l.\n    + unfold newVar in Hrecl |- *; simpl. \n      assert\n        (H0: fold_right Nat.max 0 (map S l) = 0 \\/\n               (exists n : nat, fold_right Nat.max 0 (map S l) = S n)).\n      { induction (fold_right Nat.max 0 (map S l)) as [| n0 IHn0].\n        - auto.\n        - right; now exists n0.\n      }\n      destruct H0 as [H0| [x0 H0]].\n      * rewrite H0; rewrite H0 in Hrecl.\n        elim (Nat.nlt_0_r n (Hrecl _ H)).\n      * rewrite H0; rewrite H0 in Hrecl.\n        -- apply Nat.lt_le_trans with (S x0).\n           ++ now apply Hrecl.\n           ++ apply le_n_S, Nat.le_max_r.\nQed.\n\nLemma newVar1 : forall l : list nat, ~ In (newVar l) l.\nProof.\n  intros l ?; elim (Nat.lt_irrefl (newVar l)); now apply newVar2.\nQed.\n\nDefinition substituteFormulaImp (f : fol.Formula L)\n  (frec : nat * fol.Term L -> {y : fol.Formula L | depth L y = depth L f})\n  (g : fol.Formula L)\n  (grec : nat * fol.Term L -> {y : fol.Formula L | depth L y = depth L g})\n  (p : nat * fol.Term L) :\n  {y : fol.Formula L | depth L y = depth L (impH f g)} :=\n  match frec p with\n  | exist f' prf1 =>\n      match grec p with\n      | exist g' prf2 =>\n          exist\n            (fun y : fol.Formula L =>\n               depth L y = S (Nat.max (depth L f) (depth L g))) \n            (impH f' g')\n            (eq_ind_r\n               (fun n : nat =>\n                  S (Nat.max n (depth L g')) =\n                    S (Nat.max (depth L f) (depth L g)))\n               (eq_ind_r\n                  (fun n : nat =>\n                     S (Nat.max (depth L f) n) =\n                       S (Nat.max (depth L f) (depth L g)))\n                  (refl_equal (S (Nat.max  (depth L f) (depth L g))))\n                  prf2) prf1)\n      end\n  end.\n\nRemark substituteFormulaImpNice :\n  forall (f g : fol.Formula L)\n         (z1 z2 : nat * fol.Term L ->\n                  {y : fol.Formula L | depth L y = depth L f}),\n    (forall q : nat * fol.Term L, z1 q = z2 q) ->\n    forall\n      z3 z4 : nat * fol.Term L ->\n              {y : fol.Formula L | depth L y = depth L g},\n      (forall q : nat * fol.Term L, z3 q = z4 q) ->\n      forall q : nat * fol.Term L,\n        substituteFormulaImp f z1 g z3 q =\n          substituteFormulaImp f z2 g z4 q.\nProof.\n  intros f g z1 z2 H z3 z4 H0 q; unfold substituteFormulaImp in |- *.\n  rewrite H, H0; reflexivity. \nQed.\n\nDefinition substituteFormulaNot (f : fol.Formula L)\n  (frec : nat * fol.Term L ->\n          {y : fol.Formula L | depth L y = depth L f})\n  (p : nat * fol.Term L) :\n  {y : fol.Formula L | depth L y = depth L (notH f)} :=\n  match frec p with\n  | exist f' prf1 =>\n      exist (fun y : fol.Formula L => depth L y = S (depth L f)) \n        (notH f')\n        (eq_ind_r (fun n : nat => S n = S (depth L f))\n           (refl_equal (S (depth L f))) prf1)\n  end.\n\nRemark substituteFormulaNotNice :\n  forall (f : fol.Formula L)\n         (z1 z2 : nat * fol.Term L ->\n                  {y : fol.Formula L | depth L y = depth L f}),\n    (forall q : nat * fol.Term L, z1 q = z2 q) ->\n    forall q : nat * fol.Term L,\n      substituteFormulaNot f z1 q = substituteFormulaNot f z2 q.\nProof.\n  intros ? ? ? H ?; unfold substituteFormulaNot in |- *;\n    now rewrite H.\nQed.\n    \nDefinition substituteFormulaForall (n : nat) (f : fol.Formula L)\n  (frec : forall b : fol.Formula L,\n      lt_depth b (forallH n f) ->\n      nat * fol.Term L -> {y : fol.Formula L | depth L y = depth L b})\n  (p : nat * fol.Term L) :\n  {y : fol.Formula L | depth L y = depth L (forallH n f)} :=\n  match p with\n  | (v, s) =>\n      match eq_nat_dec n v with\n      | left _ =>\n          exist (fun y : fol.Formula L => depth L y = S (depth L f))\n            (forallH n f) (refl_equal (depth L (forallH n f)))\n      | right _ =>\n          match In_dec eq_nat_dec n (freeVarTerm s) with\n          | left _ =>\n              let nv := newVar (v :: freeVarTerm s ++ freeVarFormula f) in\n              match frec f (depthForall L f n) (n, var nv) with\n              | exist f' prf1 =>\n                  match\n                    frec f'\n                      (eqDepth L f' f (forallH n f) \n                         (sym_eq prf1) (depthForall L f n)) p\n                  with\n                  | exist f'' prf2 =>\n                      exist\n                        (fun y : fol.Formula L => depth L y = S (depth L f))\n                        (forallH nv f'')\n                        (eq_ind_r (fun n : nat => S n = S (depth L f))\n                           (refl_equal (S (depth L f))) \n                           (trans_eq prf2 prf1))\n                  end\n              end\n          | right _ =>\n              match frec f (depthForall L f n) p with\n              | exist f' prf1 =>\n                  exist (fun y : fol.Formula L => depth L y = S (depth L f))\n                    (forallH n f')\n                    (eq_ind_r (fun n : nat => S n = S (depth L f))\n                       (refl_equal (S (depth L f))) prf1)\n              end\n          end\n      end\n  end.\n\nRemark substituteFormulaForallNice :\n  forall (v : nat) (a : fol.Formula L)\n         (z1 z2 : forall b : fol.Formula L,\n             lt_depth b (forallH v a) ->\n             nat * fol.Term L -> {y : fol.Formula L | depth L y = depth L b}),\n    (forall (b : fol.Formula L) (q : lt_depth b (forallH v a))\n            (r : nat * fol.Term L), z1 b q r = z2 b q r) ->\n    forall q : nat * fol.Term L,\n      substituteFormulaForall v a z1 q = substituteFormulaForall v a z2 q.\nProof.\n  intros v a z1 z2 H [a0 b]; unfold substituteFormulaForall in |- *.\n  destruct (eq_nat_dec v a0) as [e | n] ; simpl in |- *.\n  - reflexivity.\n  - induction (In_dec eq_nat_dec v (freeVarTerm b)); simpl in |- *.\n    + rewrite H;\n        destruct\n          (z2 a (depthForall L a v)\n             (v, var (newVar\n                        (a0 :: freeVarTerm b ++ freeVarFormula a)))). \n         now rewrite H.  \n    + now rewrite H.\nQed.\n\nDefinition substituteFormulaHelp (f : fol.Formula L) \n  (v : nat) (s : fol.Term L) : {y : fol.Formula L | depth L y = depth L f}.\nProof.\n  apply\n    (Formula_depth_rec2 L\n       (fun f : fol.Formula L =>\n          nat * fol.Term L -> {y : fol.Formula L | depth L y = depth L f})).\n  - intros t t0 H; induction H as (a, b).\n    exists (equal (substituteTerm t a b) (substituteTerm t0 a b)); auto.\n  - intros r t H; induction H as (a, b).\n    exists (atomic r (substituteTerms _ t a b)); auto.\n  - exact substituteFormulaImp.\n  - exact substituteFormulaNot.\n  - exact substituteFormulaForall.\n  - exact (v, s).\nDefined.\n\nDefinition substituteFormula (f : fol.Formula L) (v : nat) (s : fol.Term L) :\n  fol.Formula L := proj1_sig (substituteFormulaHelp f v s).\n\nLemma subFormulaEqual :\n  forall (t1 t2 : fol.Term L) (v : nat) (s : fol.Term L),\n    substituteFormula (equal t1 t2) v s =\n      equal (substituteTerm t1 v s) (substituteTerm t2 v s).\nProof. reflexivity. Qed.\n\nLemma subFormulaRelation :\n  forall (r : Relations L) (ts : fol.Terms L (arityR L r)) \n         (v : nat) (s : fol.Term L),\n    substituteFormula (atomic r ts) v s =\n      atomic r (substituteTerms (arityR L r) ts v s).\nProof. reflexivity. Qed.\n\n\nLemma subFormulaImp :\n  forall (f1 f2 : fol.Formula L) (v : nat) (s : fol.Term L),\n    substituteFormula (impH f1 f2) v s =\n      impH (substituteFormula f1 v s) (substituteFormula f2 v s).\nProof.\n  intros f1 f2 v s. \n  unfold substituteFormula, substituteFormulaHelp in |- *.\n  rewrite\n    (Formula_depth_rec2_imp L)\n    with\n    (Q := \n       fun _ : fol.Formula L =>\n         (nat * fol.Term L)%type)\n    (P := \n       fun x : fol.Formula L =>\n         {y : fol.Formula L | depth L y = depth L x}).\n  unfold substituteFormulaImp at 1 in |- *.\n  - induction\n      (Formula_depth_rec2 L\n         (fun x : fol.Formula L =>\n            nat * fol.Term L -> {y : fol.Formula L | depth L y = depth L x})\n         (fun (t t0 : fol.Term L) (H : nat * fol.Term L) =>\n            prod_rec\n              (fun _ : nat * fol.Term L =>\n                 {y : fol.Formula L | depth L y = depth L (equal  t t0)})\n              (fun (a : nat) (b : fol.Term L) =>\n                 exist\n                   (fun y : fol.Formula L => \n                      depth L y = depth L (equal t t0))\n                   (equal (substituteTerm t a b) (substituteTerm t0 a b))\n                   (refl_equal (depth L (equal t t0)))) H)\n         (fun (r : Relations L) \n              (t : fol.Terms L (arityR L r))\n              (H : nat * fol.Term L) =>\n            prod_rec\n              (fun _ : nat * fol.Term L =>\n                 {y : fol.Formula L | depth L y = depth L (atomic r t)})\n              (fun (a : nat) (b : fol.Term L) =>\n                 exist\n                   (fun y : fol.Formula L => depth L y = \n                                               depth L (atomic r t))\n                   (atomic r (substituteTerms (arityR L r) \n                                t a b))\n                   (refl_equal (depth L (atomic r t)))) H)\n         substituteFormulaImp\n         substituteFormulaNot substituteFormulaForall f1 \n         (v, s)).\n    induction\n      (Formula_depth_rec2 L\n         (fun x0 : fol.Formula L =>\n            nat * fol.Term L -> {y : fol.Formula L | depth L y = depth L x0})\n         (fun (t t0 : fol.Term L) (H : nat * fol.Term L) =>\n            prod_rec\n              (fun _ : nat * fol.Term L =>\n                 {y : fol.Formula L | depth L y = depth L (equal t t0)})\n              (fun (a : nat) (b : fol.Term L) =>\n                 exist\n                   (fun y : fol.Formula L => \n                      depth L y = depth L (equal t t0))\n                   (equal (substituteTerm t a b) (substituteTerm t0 a b))\n                   (refl_equal (depth L (equal t t0)))) H)\n         (fun (r : Relations L) \n              (t : fol.Terms L (arityR L r))\n              (H : nat * fol.Term L) =>\n            prod_rec\n              (fun _ : nat * fol.Term L =>\n                 {y : fol.Formula L | depth L y = depth L (atomic r t)})\n              (fun (a : nat) (b : fol.Term L) =>\n                 exist\n                   (fun y : fol.Formula L => \n                      depth L y = depth L (atomic r t))\n                   (atomic r (substituteTerms (arityR L r) \n                                t a b))\n                   (refl_equal (depth L (atomic r t)))) H) \n         substituteFormulaImp\n         substituteFormulaNot substituteFormulaForall f2 \n         (v, s)).\n    reflexivity.\n  - apply substituteFormulaImpNice.\n  - apply substituteFormulaNotNice.\n  - apply substituteFormulaForallNice.\nQed.\n\nLemma subFormulaNot :\n  forall (f : fol.Formula L) (v : nat) (s : fol.Term L),\n    substituteFormula (notH f) v s = notH (substituteFormula f v s).\nProof.\n  intros f v s; \n  unfold substituteFormula, substituteFormulaHelp.\n  rewrite (Formula_depth_rec2_not L) with\n    (Q := fun _ : fol.Formula L => (nat * fol.Term L)%type)\n    (P := fun x : fol.Formula L =>\n         {y : fol.Formula L | depth L y = depth L x}).\n  - unfold substituteFormulaNot at 1 in |- *.\n    induction\n      (Formula_depth_rec2 L\n         (fun x : fol.Formula L =>\n            nat * fol.Term L -> {y : fol.Formula L | depth L y = depth L x})\n         (fun (t t0 : fol.Term L) (H : nat * fol.Term L) =>\n            prod_rec\n              (fun _ : nat * fol.Term L =>\n                 {y : fol.Formula L | depth L y = depth L (equal t t0)})\n              (fun (a : nat) (b : fol.Term L) =>\n                 exist\n                   (fun y : fol.Formula L => depth L y = \n                                               depth L (equal t t0))\n                   (equal (substituteTerm t a b) (substituteTerm t0 a b))\n                   (refl_equal (depth L (equal t t0)))) H)\n         (fun (r : Relations L) \n              (t : fol.Terms L (arityR L r))\n              (H : nat * fol.Term L) =>\n            prod_rec\n              (fun _ : nat * fol.Term L =>\n                 {y : fol.Formula L | depth L y = depth L (atomic r t)})\n              (fun (a : nat) (b : fol.Term L) =>\n                 exist\n                   (fun y : fol.Formula L =>\n                      depth L y = depth L (atomic r t))\n                   (atomic r\n                      (substituteTerms (arityR L r) t a b))\n                   (refl_equal (depth L (atomic r t)))) H)\n         substituteFormulaImp\n         substituteFormulaNot substituteFormulaForall f \n         (v, s)); reflexivity.\n  - apply substituteFormulaImpNice.\n  - apply substituteFormulaNotNice.\n  - apply substituteFormulaForallNice.\nQed.\n    \n\nLemma subFormulaForall :\n  forall (f : fol.Formula L) (x v : nat) (s : fol.Term L),\n    let nv := newVar (v :: freeVarTerm s ++ freeVarFormula f) in\n    substituteFormula (forallH x f) v s =\n      match eq_nat_dec x v with\n      | left _ => forallH x f\n      | right _ =>\n          match In_dec eq_nat_dec x (freeVarTerm s) with\n          | right _ => forallH x (substituteFormula f v s)\n          | left _ =>\n              forallH nv (substituteFormula \n                            (substituteFormula f x (var nv)) v s)\n          end\n      end.\nProof.\n  intros f x v s nv.\n  unfold substituteFormula at 1 in |- *.\n  unfold substituteFormulaHelp in |- *.\n  rewrite (Formula_depth_rec2_forall L)\n    with\n    (Q := \n       fun _ : fol.Formula L =>\n         (nat * fol.Term L)%type)\n    (P := \n       fun x : fol.Formula L =>\n         {y : fol.Formula L | depth L y = depth L x}).\n  - simpl in |- *; induction (eq_nat_dec x v); simpl in |- *.\n    + reflexivity.\n    + induction (In_dec eq_nat_dec x (freeVarTerm s)); simpl in |- *.\n      fold nv in |- *.\n      unfold substituteFormula at 2 in |- *; \n        unfold substituteFormulaHelp in |- *;\n        simpl in |- *.\n      * induction\n          (Formula_depth_rec2 L\n             (fun x0 : fol.Formula L =>\n                nat * fol.Term L -> \n                {y : fol.Formula L | depth L y = depth L x0})\n             (fun (t t0 : fol.Term L) (H : nat * fol.Term L) =>\n                prod_rec\n                  (fun _ : nat * fol.Term L => \n                     {y : fol.Formula L | depth L y = 0})\n                  (fun (a0 : nat) (b0 : fol.Term L) =>\n                     exist (fun y : fol.Formula L => depth L y = 0)\n                       (equal (substituteTerm t a0 b0) \n                          (substituteTerm t0 a0 b0))\n                       (refl_equal 0)) H)\n             (fun (r : Relations L) \n                  (t : fol.Terms L (arityR L r))\n                  (H : nat * fol.Term L) =>\n                prod_rec\n                  (fun _ : nat * fol.Term L => \n                     {y : fol.Formula L | depth L y = 0})\n                  (fun (a0 : nat) (b0 : fol.Term L) =>\n                     exist (fun y : fol.Formula L => depth L y = 0)\n                       (atomic r (substituteTerms\n                                    (arityR L r) t a0 b0))\n                       (refl_equal 0)) H) substituteFormulaImp\n             substituteFormulaNot\n             substituteFormulaForall f (x, var nv)).\n        unfold substituteFormula in |- *; unfold substituteFormulaHelp in |- *;\n          simpl in |- *.\n        induction\n          (Formula_depth_rec2 L\n             (fun x1 : fol.Formula L =>\n                nat * fol.Term L -> \n                {y : fol.Formula L | depth L y = depth L x1})\n             (fun (t t0 : fol.Term L) (H : nat * fol.Term L) =>\n                prod_rec\n                  (fun _ : nat * fol.Term L => \n                     {y : fol.Formula L | depth L y = 0})\n                  (fun (a0 : nat) (b0 : fol.Term L) =>\n                     exist (fun y : fol.Formula L => depth L y = 0)\n                       (equal (substituteTerm t a0 b0) \n                          (substituteTerm t0 a0 b0))\n                       (refl_equal 0)) H)\n             (fun (r : Relations L) \n                  (t : fol.Terms L (arityR L r))\n                  (H : nat * fol.Term L) =>\n                prod_rec\n                  (fun _ : nat * fol.Term L => \n                     {y : fol.Formula L | depth L y = 0})\n                  (fun (a0 : nat) (b0 : fol.Term L) =>\n                     exist (fun y : fol.Formula L => depth L y = 0)\n                       (atomic r (substituteTerms \n                                    (arityR L r) t a0 b0))\n                       (refl_equal 0)) H) substituteFormulaImp \n             substituteFormulaNot\n             substituteFormulaForall x0 (v, s)).\n        simpl in |- *; reflexivity.\n      * unfold substituteFormula in |- *; unfold substituteFormulaHelp in |- *;\n          simpl in |- *.\n        induction\n          (Formula_depth_rec2 L\n             (fun x0 : fol.Formula L =>\n                nat * fol.Term L -> \n                {y : fol.Formula L | depth L y = depth L x0})\n             (fun (t t0 : fol.Term L) (H : nat * fol.Term L) =>\n                prod_rec\n                  (fun _ : nat * fol.Term L => \n                     {y : fol.Formula L | depth L y = 0})\n                  (fun (a : nat) (b1 : fol.Term L) =>\n                     exist (fun y : fol.Formula L => depth L y = 0)\n                       (equal (substituteTerm t a b1) (substituteTerm t0 a b1))\n                       (refl_equal 0)) H)\n             (fun (r : Relations L) \n                  (t : fol.Terms L (arityR L r))\n                  (H : nat * fol.Term L) =>\n                prod_rec\n                  (fun _ : nat * fol.Term L => \n                     {y : fol.Formula L | depth L y = 0})\n                  (fun (a : nat) (b1 : fol.Term L) =>\n                     exist (fun y : fol.Formula L => depth L y = 0)\n                       (atomic r (substituteTerms\n                                    (arityR L r) t a b1))\n                       (refl_equal 0)) H) substituteFormulaImp\n             substituteFormulaNot\n             substituteFormulaForall f (v, s)).\n        simpl in |- *; reflexivity.\n  - apply substituteFormulaImpNice.\n  - apply substituteFormulaNotNice.\n  - apply substituteFormulaForallNice.\nQed.\n\nSection Extensions.\n\n\nLemma subFormulaOr :\n  forall (f1 f2 : fol.Formula L) (v : nat) (s : fol.Term L),\n    substituteFormula (orH f1 f2) v s =\n      orH (substituteFormula f1 v s) (substituteFormula f2 v s).\nProof.\n  intros f1 f2 v s; unfold orH;\n    now rewrite subFormulaImp, subFormulaNot.\nQed.\n\nLemma subFormulaAnd :\n  forall (f1 f2 : fol.Formula L) (v : nat) (s : fol.Term L),\n    substituteFormula (andH f1 f2) v s =\n      andH (substituteFormula f1 v s) (substituteFormula f2 v s).\nProof.\n  intros ? ? ? ?; unfold andH in |- *.\n  rewrite subFormulaNot, subFormulaOr; now repeat rewrite subFormulaNot.\nQed.\n\nLemma subFormulaExist :\n  forall (f : fol.Formula L) (x v : nat) (s : fol.Term L),\n    let nv := newVar (v :: freeVarTerm s ++ freeVarFormula f) in\n    substituteFormula (existH x f) v s =\n      match eq_nat_dec x v with\n      | left _ => existH x f\n      | right _ =>\n          match In_dec eq_nat_dec x (freeVarTerm s) with\n          | right _ => existH x (substituteFormula f v s)\n          | left _ =>\n              existH nv (substituteFormula \n                           (substituteFormula f x (var nv)) v s)\n          end\n      end.\nProof.\n  intros ? ? ? ? nv; unfold existH.\n  rewrite subFormulaNot, subFormulaForall.\n  destruct (eq_nat_dec x v).\n  - reflexivity.\n  - induction (In_dec eq_nat_dec x (freeVarTerm s));\n      now repeat rewrite subFormulaNot.\nQed.\n\nLemma subFormulaIff :\n  forall (f1 f2 : fol.Formula L) (v : nat) (s : fol.Term L),\n    substituteFormula (iffH f1 f2) v s =\n      iffH (substituteFormula f1 v s) (substituteFormula f2 v s).\nProof.\n  intros ? ? v s; unfold iffH in |- *.\n  rewrite subFormulaAnd; now repeat rewrite subFormulaImp.\nQed.\n\nLemma subFormulaIfThenElse :\n  forall (f1 f2 f3 : fol.Formula L) (v : nat) (s : fol.Term L),\n    substituteFormula (ifThenElseH f1 f2 f3) v s =\n      ifThenElseH (substituteFormula f1 v s) (substituteFormula f2 v s)\n        (substituteFormula f3 v s).\nProof.\n  intros ? ? ? ? ?; unfold ifThenElseH.\n  now rewrite subFormulaAnd, !subFormulaImp,  subFormulaNot.\nQed.\n\nEnd Extensions.\n\nLemma subFormulaDepth :\n  forall (f : fol.Formula L) (v : nat) (s : fol.Term L),\n    depth L (substituteFormula f v s) = depth L f.\nProof.\n  intros f v s; unfold substituteFormula in |- *.\n  induction (substituteFormulaHelp f v s) as [x p]; now simpl. \nQed.\n\nSection Substitution_Properties.\n\nLemma subTermId :\n  forall (t : fol.Term L) (v : nat), substituteTerm t v (var v) = t.\nProof.\n  intros ? ?; \n    elim t using Term_Terms_ind\n    with\n    (P0 := fun (n : nat) (ts : fol.Terms L n) =>\n             substituteTerms n ts v (var v) = ts).\n  - simpl in |- *; intros n.\n    induction (eq_nat_dec v n) as [a | b].\n    + now rewrite a.\n    + reflexivity.\n  -  intros f t0 H; simpl in |- *; now rewrite H.\n  -  reflexivity.\n  -  intros ? ? H t1 H0; simpl in |- *; now rewrite H, H0. \nQed.\n\nLemma subTermsId :\n  forall (n : nat) (ts : fol.Terms L n) (v : nat),\n    substituteTerms n ts v (var v) = ts.\nProof.\n  intros n ts v; induction ts as [| n t ts Hrects].\n  - reflexivity. \n  - simpl in |- *;  now rewrite Hrects,  subTermId.\nQed.\n\nLemma subFormulaId :\n  forall (f : fol.Formula L) (v : nat), substituteFormula f v (var v) = f.\nProof.\n  intros f v.\n  induction f as [t t0| r t| f1 Hrecf1 f0 Hrecf0| f Hrecf| n f Hrecf].\n  - now rewrite subFormulaEqual, !subTermId.\n  - now rewrite subFormulaRelation, subTermsId.\n  - now rewrite subFormulaImp, Hrecf1,  Hrecf0.\n  - now rewrite subFormulaNot, Hrecf.\n  - rewrite subFormulaForall; destruct  (eq_nat_dec n v) as [e|ne].\n    + reflexivity.\n    + induction (In_dec eq_nat_dec n (freeVarTerm (var v))) as [a|b].\n      * elim ne; destruct a as [H| H].\n        -- now subst.\n        -- destruct H.\n      * now rewrite Hrecf.\nQed.\n\nLemma subFormulaForall2 :\n  forall (f : fol.Formula L) (x v : nat) (s : fol.Term L),\n  exists nv : nat,\n    ~ In nv (freeVarTerm s) /\\\n      nv <> v /\\\n      ~ In nv (List.remove  eq_nat_dec x (freeVarFormula f)) /\\\n      substituteFormula (forallH x f) v s =\n        match eq_nat_dec x v with\n        | left _ => forallH x f\n        | right _ =>\n            forallH nv (substituteFormula (substituteFormula f x (var nv)) v s)\n        end.\nProof.\n  intros f x v s; rewrite subFormulaForall.\n  induction (eq_nat_dec x v) as [a | b].\n  - set\n      (A1 :=\n         v :: freeVarTerm s ++ List.remove eq_nat_dec x (freeVarFormula f)) \n      in *.\n    exists (newVar A1); repeat split.\n    + unfold not in |- *; intros; elim (newVar1 A1).\n      unfold A1 in |- *; right.\n      apply in_or_app; auto.\n    + unfold not in |- *; intros; elim (newVar1 A1).\n      rewrite H; left; auto.\n    + unfold not in |- *; intros; elim (newVar1 A1).\n      right; apply in_or_app; auto.\n  - induction (In_dec eq_nat_dec x (freeVarTerm s)) as [a | b0].\n    + set (A1 := v :: freeVarTerm s ++ freeVarFormula f) in *.\n      exists (newVar A1); repeat split.\n      * unfold not in |- *; intros; elim (newVar1 A1); right.\n        apply in_or_app; auto.\n      * unfold not in |- *; intros; elim (newVar1 A1); rewrite H; left; auto.\n      * unfold not in |- *; intros; elim (newVar1 A1); right;  apply in_or_app.\n        right; eapply in_remove; apply H.\n    + exists x; repeat split; auto.\n      intro H; eapply (in_remove_neq _ _ _ _ _ H).\n      * reflexivity.\n      * now rewrite subFormulaId.\nQed.\n\n\nLemma subFormulaExist2 :\n  forall (f : fol.Formula L) (x v : nat) (s : fol.Term L),\n  exists nv : nat,\n    ~ In nv (freeVarTerm s) /\\\n      nv <> v /\\\n      ~ In nv (List.remove eq_nat_dec x (freeVarFormula f)) /\\\n      substituteFormula (existH x f) v s =\n        match eq_nat_dec x v with\n        | left _ => existH x f\n        | right _ =>\n            existH nv (substituteFormula (substituteFormula f x (var nv)) v s)\n        end.\nProof.\n  intros f x v s; rewrite subFormulaExist.\n  induction (eq_nat_dec x v) as [a | b].\n  - set\n      (A1 :=\n         v :: freeVarTerm s ++ List.remove eq_nat_dec x (freeVarFormula f)) \n      in *.\n    exists (newVar A1); repeat split.\n    + unfold not in |- *; intros; elim (newVar1 A1).\n      unfold A1 in |- *; right; apply in_or_app; auto.\n    + unfold not in |- *; intros; elim (newVar1 A1); rewrite H; now left.\n    + unfold not in |- *; intros; elim (newVar1 A1); right; apply in_or_app; \n        auto.\n  - induction (In_dec eq_nat_dec x (freeVarTerm s)) as [a | b0].\n    + set (A1 := v :: freeVarTerm s ++ freeVarFormula f) in *.\n      exists (newVar A1);  repeat split.\n      * unfold not in |- *; intros; elim (newVar1 A1); right; apply in_or_app; auto.\n      * unfold not in |- *; intros; elim (newVar1 A1); rewrite H; left; auto.\n      * unfold not in |- *; intros; elim (newVar1 A1); right;  apply in_or_app.\n        right; eapply in_remove; apply H.\n    + exists x; repeat split; auto.\n      intros H; eapply (in_remove_neq _ _ _ _ _ H).\n      * reflexivity.\n      * rewrite subFormulaId; auto.\nQed.\n\nEnd Substitution_Properties.\n\nEnd Substitution.\n  \nDefinition Sentence (f:Formula) := (forall v : nat, ~ In v (freeVarFormula f)).\n\nEnd Fol_Properties.\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/Ackermann/folProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7206432577333797}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n   Require Export Lists.\n\n   (* ################################################################# *)\n   (** * Polymorphism *)\n   \n   (** In this chapter we continue our development of basic\n       concepts of functional programming.  The critical new ideas are\n       _polymorphism_ (abstracting functions over the types of the data\n       they manipulate) and _higher-order functions_ (treating functions\n       as data).  We begin with polymorphism. *)\n   \n   (* ================================================================= *)\n   (** ** Polymorphic Lists *)\n   \n   (** For the last couple of chapters, we've been working just\n       with lists of numbers.  Obviously, interesting programs also need\n       to be able to manipulate lists with elements from other types --\n       lists of strings, lists of booleans, lists of lists, etc.  We\n       _could_ just define a new inductive datatype for each of these,\n       for example... *)\n   \n   Inductive boollist : Type :=\n     | bool_nil : boollist\n     | bool_cons : bool -> boollist -> boollist.\n   \n   (** ... but this would quickly become tedious, partly because we\n       have to make up different constructor names for each datatype, but\n       mostly because we would also need to define new versions of all\n       our list manipulating functions ([length], [rev], etc.) for each\n       new datatype definition. *)\n   \n   (** To avoid all this repetition, Coq supports _polymorphic_\n       inductive type definitions.  For example, here is a _polymorphic\n       list_ datatype. *)\n   \n   Inductive list (X:Type) : Type :=\n     | nil : list X\n     | cons : X -> list X -> list X.\n   \n   (** This is exactly like the definition of [natlist] from the\n       previous chapter, except that the [nat] argument to the [cons]\n       constructor has been replaced by an arbitrary type [X], a binding\n       for [X] has been added to the header, and the occurrences of\n       [natlist] in the types of the constructors have been replaced by\n       [list X].  (We can re-use the constructor names [nil] and [cons]\n       because the earlier definition of [natlist] was inside of a\n       [Module] definition that is now out of scope.)\n   \n       What sort of thing is [list] itself?  One good way to think\n       about it is that [list] is a _function_ from [Type]s to\n       [Inductive] definitions; or, to put it another way, [list] is a\n       function from [Type]s to [Type]s.  For any particular type [X],\n       the type [list X] is an [Inductive]ly defined set of lists whose\n       elements are of type [X]. *)\n   \n   (** With this definition, when we use the constructors [nil] and\n       [cons] to build lists, we need to tell Coq the type of the\n       elements in the lists we are building -- that is, [nil] and [cons]\n       are now _polymorphic constructors_.  Observe the types of these\n       constructors: *)\n   \n   Check nil.\n   (* ===> nil : forall X : Type, list X *)\n   Check cons.\n   (* ===> cons : forall X : Type, X -> list X -> list X *)\n   \n   (** (Side note on notation: In .v files, the \"forall\" quantifier\n       is spelled out in letters.  In the generated HTML files and in the\n       way various IDEs show .v files (with certain settings of their\n       display controls), [forall] is usually typeset as the usual\n       mathematical \"upside down A,\" but you'll still see the spelled-out\n       \"forall\" in a few places.  This is just a quirk of typesetting:\n       there is no difference in meaning.) *)\n   \n   (** The \"[forall X]\" in these types can be read as an additional\n       argument to the constructors that determines the expected types of\n       the arguments that follow.  When [nil] and [cons] are used, these\n       arguments are supplied in the same way as the others.  For\n       example, the list containing [2] and [1] is written like this: *)\n   \n   Check (cons nat 2 (cons nat 1 (nil nat))).\n   \n   (** (We've written [nil] and [cons] explicitly here because we haven't\n       yet defined the [ [] ] and [::] notations for the new version of\n       lists.  We'll do that in a bit.) *)\n   \n   (** We can now go back and make polymorphic versions of all the\n       list-processing functions that we wrote before.  Here is [repeat],\n       for example: *)\n   \n   Fixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n     match count with\n     | 0 => nil X\n     | S count' => cons X x (repeat X x count')\n     end.\n   \n   (** As with [nil] and [cons], we can use [repeat] by applying it\n       first to a type and then to its list argument: *)\n   \n   Example test_repeat1 :\n     repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\n   Proof. reflexivity.  Qed.\n   \n   (** To use [repeat] to build other kinds of lists, we simply\n       instantiate it with an appropriate type parameter: *)\n   \n   Example test_repeat2 :\n     repeat bool false 1 = cons bool false (nil bool).\n   Proof. reflexivity.  Qed.\n   \n   \n   Module MumbleGrumble.\n   \n   (** **** Exercise: 2 starsM (mumble_grumble)  *)\n   (** Consider the following two inductively defined types. *)\n   \n   Inductive mumble : Type :=\n     | a : mumble\n     | b : mumble -> nat -> mumble\n     | c : mumble.\n   \n   Inductive grumble (X:Type) : Type :=\n     | d : mumble -> grumble X\n     | e : X -> grumble X.\n\n  Check (d mumble (b a 5)).\n  Check (d bool (b a 5)).\n  Check (e bool true).\n  Check (e mumble (b c 0)).\n  Check c.\n   \n   (** Which of the following are well-typed elements of [grumble X] for\n       some type [X]?\n         - [d (b a 5)]\n         - [d mumble (b a 5)]\n         - [d bool (b a 5)]\n         - [e bool true]\n         - [e mumble (b c 0)]\n         - [e bool (b c 0)]\n         - [c]\n   (* FILL IN HERE *)\n   *)\n   (** [] *)\n   \n   End MumbleGrumble.\n   \n   (* ----------------------------------------------------------------- *)\n   (** *** Type Annotation Inference *)\n   \n   (** Let's write the definition of [repeat] again, but this time we\n       won't specify the types of any of the arguments.  Will Coq still\n       accept it? *)\n   \n   Fixpoint repeat' X x count : list X :=\n     match count with\n     | 0        => nil X\n     | S count' => cons X x (repeat' X x count')\n     end.\n   \n   (** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n   \n   Check repeat'.\n   (* ===> forall X : Type, X -> nat -> list X *)\n   Check repeat.\n   (* ===> forall X : Type, X -> nat -> list X *)\n   \n   (** It has exactly the same type type as [repeat].  Coq was able\n       to use _type inference_ to deduce what the types of [X], [x], and\n       [count] must be, based on how they are used.  For example, since\n       [X] is used as an argument to [cons], it must be a [Type], since\n       [cons] expects a [Type] as its first argument; matching [count]\n       with [0] and [S] means it must be a [nat]; and so on.\n   \n       This powerful facility means we don't always have to write\n       explicit type annotations everywhere, although explicit type\n       annotations are still quite useful as documentation and sanity\n       checks, so we will continue to use them most of the time.  You\n       should try to find a balance in your own code between too many\n       type annotations (which can clutter and distract) and too\n       few (which forces readers to perform type inference in their heads\n       in order to understand your code). *)\n   \n   (* ----------------------------------------------------------------- *)\n   (** *** Type Argument Synthesis *)\n   \n   (** To use a polymorphic function, we need to pass it one or\n       more types in addition to its other arguments.  For example, the\n       recursive call in the body of the [repeat] function above must\n       pass along the type [X].  But since the second argument to\n       [repeat] is an element of [X], it seems entirely obvious that the\n       first argument can only be [X] -- why should we have to write it\n       explicitly?\n   \n       Fortunately, Coq permits us to avoid this kind of redundancy.  In\n       place of any type argument we can write the \"implicit argument\"\n       [_], which can be read as \"Please try to figure out for yourself\n       what belongs here.\"  More precisely, when Coq encounters a [_], it\n       will attempt to _unify_ all locally available information -- the\n       type of the function being applied, the types of the other\n       arguments, and the type expected by the context in which the\n       application appears -- to determine what concrete type should\n       replace the [_].\n   \n       This may sound similar to type annotation inference -- indeed, the\n       two procedures rely on the same underlying mechanisms.  Instead of\n       simply omitting the types of some arguments to a function, like\n   \n         repeat' X x count : list X :=\n   \n       we can also replace the types with [_]\n   \n         repeat' (X : _) (x : _) (count : _) : list X :=\n   \n       to tell Coq to attempt to infer the missing information.\n   \n       Using implicit arguments, the [count] function can be written like\n       this: *)\n   \n   Fixpoint repeat'' X x count : list X :=\n     match count with\n     | 0        => nil _\n     | S count' => cons _ x (repeat'' _ x count')\n     end.\n   \n   (** In this instance, we don't save much by writing [_] instead of\n       [X].  But in many cases the difference in both keystrokes and\n       readability is nontrivial.  For example, suppose we want to write\n       down a list containing the numbers [1], [2], and [3].  Instead of\n       writing this... *)\n   \n   Definition list123 :=\n     cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n   \n   (** ...we can use argument synthesis to write this: *)\n   \n   Definition list123' :=\n     cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n   \n   (* ----------------------------------------------------------------- *)\n   (** *** Implicit Arguments *)\n   \n   (** We can go further and even avoid writing [_]'s in most cases by\n       telling Coq _always_ to infer the type argument(s) of a given\n       function.  The [Arguments] directive specifies the name of the\n       function (or constructor) and then lists its argument names, with\n       curly braces around any arguments to be treated as implicit.  (If\n       some arguments of a definition don't have a name, as is often the\n       case for constructors, they can be marked with a wildcard pattern\n       [_].) *)\n   \n   Arguments nil {X}.\n   Arguments cons {X} _ _.\n   Arguments repeat {X} x count.\n   \n   (** Now, we don't have to supply type arguments at all: *)\n   \n   Definition list123'' := cons 1 (cons 2 (cons 3 nil)).\n   \n   (** Alternatively, we can declare an argument to be implicit\n       when defining the function itself, by surrounding it in curly\n       braces instead of parens.  For example: *)\n   \n   Fixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n     match count with\n     | 0        => nil\n     | S count' => cons x (repeat''' x count')\n     end.\n   \n   (** (Note that we didn't even have to provide a type argument to the\n       recursive call to [repeat''']; indeed, it would be invalid to\n       provide one!)\n   \n       We will use the latter style whenever possible, but we will\n       continue to use use explicit [Argument] declarations for\n       [Inductive] constructors.  The reason for this is that marking the\n       parameter of an inductive type as implicit causes it to become\n       implicit for the type itself, not just for its constructors.  For\n       instance, consider the following alternative definition of the\n       [list] type: *)\n   \n   Inductive list' {X:Type} : Type :=\n     | nil' : list'\n     | cons' : X -> list' -> list'.\n   \n   (** Because [X] is declared as implicit for the _entire_ inductive\n       definition including [list'] itself, we now have to write just\n       [list'] whether we are talking about lists of numbers or booleans\n       or anything else, rather than [list' nat] or [list' bool] or\n       whatever; this is a step too far. *)\n   \n   (** Let's finish by re-implementing a few other standard list\n       functions on our new polymorphic lists... *)\n   \n   Fixpoint app {X : Type} (l1 l2 : list X)\n                : (list X) :=\n     match l1 with\n     | nil      => l2\n     | cons h t => cons h (app t l2)\n     end.\n   \n   Fixpoint rev {X:Type} (l:list X) : list X :=\n     match l with\n     | nil      => nil\n     | cons h t => app (rev t) (cons h nil)\n     end.\n   \n   Fixpoint length {X : Type} (l : list X) : nat :=\n     match l with\n     | nil => 0\n     | cons _ l' => S (length l')\n     end.\n   \n   Example test_rev1 :\n     rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\n   Proof. reflexivity.  Qed.\n   \n   Example test_rev2:\n     rev (cons true nil) = cons true nil.\n   Proof. reflexivity.  Qed.\n   \n   Example test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\n   Proof. reflexivity.  Qed.\n   \n   (* ----------------------------------------------------------------- *)\n   (** *** Supplying Type Arguments Explicitly *)\n   \n   (** One small problem with declaring arguments [Implicit] is\n       that, occasionally, Coq does not have enough local information to\n       determine a type argument; in such cases, we need to tell Coq that\n       we want to give the argument explicitly just this time.  For\n       example, suppose we write this: *)\n   \n   Fail Definition mynil := nil.\n   \n   (** (The [Fail] qualifier that appears before [Definition] can be\n       used with _any_ command, and is used to ensure that that command\n       indeed fails when executed. If the command does fail, Coq prints\n       the corresponding error message, but continues processing the rest\n       of the file.)\n   \n       Here, Coq gives us an error because it doesn't know what type\n       argument to supply to [nil].  We can help it by providing an\n       explicit type declaration (so that Coq has more information\n       available when it gets to the \"application\" of [nil]): *)\n   \n   Definition mynil : list nat := nil.\n   \n   (** Alternatively, we can force the implicit arguments to be explicit by\n      prefixing the function name with [@]. *)\n   \n   Check @nil.\n   \n   Definition mynil' := @nil nat.\n   \n   (** Using argument synthesis and implicit arguments, we can\n       define convenient notation for lists, as before.  Since we have\n       made the constructor type arguments implicit, Coq will know to\n       automatically infer these when we use the notations. *)\n   \n   Notation \"x :: y\" := (cons x y)\n                        (at level 60, right associativity).\n   Notation \"[ ]\" := nil.\n   Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\n   Notation \"x ++ y\" := (app x y)\n                        (at level 60, right associativity).\n   \n   (** Now lists can be written just the way we'd hope: *)\n   \n   Definition list123''' := [1; 2; 3].\n   \n   (* ----------------------------------------------------------------- *)\n   (** *** Exercises *)\n   \n   (** **** Exercise: 2 stars, optional (poly_exercises)  *)\n   (** Here are a few simple exercises, just like ones in the [Lists]\n       chapter, for practice with polymorphism.  Complete the proofs below. *)\n   \n   Theorem app_nil_r : forall (X:Type), forall l:list X,\n     l ++ [] = l.\n   Proof.\n     intros X l.\n     induction l as [| h t IHl'].\n     - simpl. reflexivity.\n     - simpl.  rewrite -> IHl'. reflexivity.\n    Qed.\n   \n   Theorem app_assoc : forall A (l m n:list A),\n     l ++ m ++ n = (l ++ m) ++ n.\n   Proof.\n     intros A l m n.\n     induction l as [| h t IHl].\n     - simpl. reflexivity.\n     - simpl. rewrite <- IHl. reflexivity.\n    Qed.\n   \n   Lemma app_length : forall (X:Type) (l1 l2 : list X),\n     length (l1 ++ l2) = length l1 + length l2.\n   Proof.\n     intros X l1 l2.\n     induction l1 as [| h t IHl'].\n     - simpl. reflexivity.\n     - simpl. rewrite <- IHl'. reflexivity.\n    Qed.\n   (** [] *)\n   \n   (** **** Exercise: 2 stars, optional (more_poly_exercises)  *)\n   (** Here are some slightly more interesting ones... *)\n   \n   Theorem rev_app_distr: forall X (l1 l2 : list X),\n     rev (l1 ++ l2) = rev l2 ++ rev l1.\n   Proof.\n     intros X l1 l2.\n     induction l1 as [| h t IHl].\n     - simpl. rewrite -> app_nil_r. reflexivity.\n     - simpl. rewrite -> IHl. rewrite -> app_assoc. reflexivity.\n    Qed.\n   \n   Theorem rev_involutive : forall X : Type, forall l : list X,\n     rev (rev l) = l.\n   Proof.\n     intros X l.\n     induction l as [| h t IHl].\n     - simpl. reflexivity.\n     - simpl. rewrite -> rev_app_distr. rewrite -> IHl. simpl. reflexivity.\n    Qed.\n   (** [] *)\n   \n   (* ================================================================= *)\n   (** ** Polymorphic Pairs *)\n   \n   (** Following the same pattern, the type definition we gave in\n       the last chapter for pairs of numbers can be generalized to\n       _polymorphic pairs_, often called _products_: *)\n   \n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> prod X Y.\n   \n   Arguments pair {X} {Y} _ _.\n   \n   (** As with lists, we make the type arguments implicit and define the\n       familiar concrete notation. *)\n   \n   Notation \"( x , y )\" := (pair x y).\n   \n   (** We can also use the [Notation] mechanism to define the standard\n       notation for product _types_: *)\n   \n   Notation \"X * Y\" := (prod X Y) : type_scope.\n   \n   (** (The annotation [: type_scope] tells Coq that this abbreviation\n       should only be used when parsing types.  This avoids a clash with\n       the multiplication symbol.) *)\n   \n   (** It is easy at first to get [(x,y)] and [X*Y] confused.\n       Remember that [(x,y)] is a _value_ built from two other values,\n       while [X*Y] is a _type_ built from two other types.  If [x] has\n       type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n   \n   (** The first and second projection functions now look pretty\n       much as they would in any functional programming language. *)\n   \n   Definition fst {X Y : Type} (p : X * Y) : X :=\n     match p with\n     | (x, y) => x\n     end.\n   \n   Definition snd {X Y : Type} (p : X * Y) : Y :=\n     match p with\n     | (x, y) => y\n     end.\n   \n   (** The following function takes two lists and combines them\n       into a list of pairs.  In other functional languages, it is often\n       called [zip]; we call it [combine] for consistency with Coq's\n       standard library. *)\n   \n   Fixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n              : list (X*Y) :=\n     match lx, ly with\n     | [], _ => []\n     | _, [] => []\n     | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n     end.\n   \n   (** **** Exercise: 1 star, optionalM (combine_checks)  *)\n   (** Try answering the following questions on paper and\n       checking your answers in coq:\n       - What is the type of [combine] (i.e., what does [Check\n         @combine] print?)\n       - What does\n   \n           Compute (combine [1;2] [false;false;true;true]).\n   \n         print? *)\n   (** combine :: forall X Y : type, list X->list Y->list (X * Y) *)\n   Check combine.\n   (** [(1,false),(2,false)] *)\n   Compute (combine [1;2] [false;false;true;true]).\n   (** **** Exercise: 2 stars, recommended (split)  *)\n   (** The function [split] is the right inverse of [combine]: it takes a\n       list of pairs and returns a pair of lists.  In many functional\n       languages, it is called [unzip].\n   \n       Fill in the definition of [split] below.  Make sure it passes the\n       given unit test. *)\n   \n   Fixpoint split {X Y : Type} (l : list (X*Y))\n                  : (list X) * (list Y) :=\n      match l with\n      | nil => (nil, nil)\n      | h :: t => ((fst h) :: fst (split t), (snd h) :: snd (split t))\n      end.\n\n   \n   Example test_split:\n     split [(1,false);(2,false)] = ([1;2],[false;false]).\n   Proof.\n    simpl.\n    reflexivity.\n  Qed.\n   (** [] *)\n   \n   (* ================================================================= *)\n   (** ** Polymorphic Options *)\n   \n   (** One last polymorphic type for now: _polymorphic options_,\n       which generalize [natoption] from the previous chapter: *)\n   \n   Inductive option (X:Type) : Type :=\n     | Some : X -> option X\n     | None : option X.\n   \n   Arguments Some {X} _.\n   Arguments None {X}.\n   \n   (** We can now rewrite the [nth_error] function so that it works\n       with any type of lists. *)\n   \n   Fixpoint nth_error {X : Type} (l : list X) (n : nat)\n                      : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n     end.\n   \n   Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.\n   Proof. reflexivity. Qed.\n   Example test_nth_error2 : nth_error [[1];[2]] 1 = Some [2].\n   Proof. reflexivity. Qed.\n   Example test_nth_error3 : nth_error [true] 2 = None.\n   Proof. reflexivity. Qed.\n   \n   (** **** Exercise: 1 star, optional (hd_error_poly)  *)\n   (** Complete the definition of a polymorphic version of the\n       [hd_error] function from the last chapter. Be sure that it\n       passes the unit tests below. *)\n   \n   Definition hd_error {X : Type} (l : list X) : option X :=\n     match l with\n     | nil => None\n     | h :: t => Some h\n    end.\n   \n   (** Once again, to force the implicit arguments to be explicit,\n       we can use [@] before the name of the function. *)\n   \n   Check @hd_error.\n   \n   Example test_hd_error1 : hd_error [1;2] = Some 1.\n   Proof.\n     simpl.\n     reflexivity.\n    Qed.\n   Example test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\n   Proof.\n     simpl.\n     reflexivity.\n    Qed.\n   (** [] *)\n   \n   (* ################################################################# *)\n   (** * Functions as Data *)\n   \n   (** Like many other modern programming languages -- including\n       all functional languages (ML, Haskell, Scheme, Scala, Clojure,\n       etc.) -- Coq treats functions as first-class citizens, allowing\n       them to be passed as arguments to other functions, returned as\n       results, stored in data structures, etc.*)\n   \n   (* ================================================================= *)\n   (** ** Higher-Order Functions *)\n   \n   (** Functions that manipulate other functions are often called\n       _higher-order_ functions.  Here's a simple one: *)\n   \n   Definition doit3times {X:Type} (f:X->X) (n:X) : X :=\n     f (f (f n)).\n   \n   (** The argument [f] here is itself a function (from [X] to\n       [X]); the body of [doit3times] applies [f] three times to some\n       value [n]. *)\n   \n   Check @doit3times.\n   (* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n   \n   Example test_doit3times: doit3times minustwo 9 = 3.\n   Proof. reflexivity.  Qed.\n   \n   Example test_doit3times': doit3times negb true = false.\n   Proof. reflexivity.  Qed.\n   \n   (* ================================================================= *)\n   (** ** Filter *)\n   \n   (** Here is a more useful higher-order function, taking a list\n       of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n       and \"filtering\" the list, returning a new list containing just\n       those elements for which the predicate returns [true]. *)\n   \n   Fixpoint filter {X:Type} (test: X->bool) (l:list X)\n                   : (list X) :=\n     match l with\n     | []     => []\n     | h :: t => if test h then h :: (filter test t)\n                           else       filter test t\n     end.\n   \n   (** For example, if we apply [filter] to the predicate [evenb]\n       and a list of numbers [l], it returns a list containing just the\n       even members of [l]. *)\n   \n   Example test_filter1: filter evenb [1;2;3;4] = [2;4].\n   Proof. reflexivity.  Qed.\n   \n   Definition length_is_1 {X : Type} (l : list X) : bool :=\n     beq_nat (length l) 1.\n   \n   Example test_filter2:\n       filter length_is_1\n              [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n     = [ [3]; [4]; [8] ].\n   Proof. reflexivity.  Qed.\n   \n   (** We can use [filter] to give a concise version of the\n       [countoddmembers] function from the [Lists] chapter. *)\n   \n   Definition countoddmembers' (l:list nat) : nat :=\n     length (filter oddb l).\n   \n   Example test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\n   Proof. reflexivity.  Qed.\n   Example test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\n   Proof. reflexivity.  Qed.\n   Example test_countoddmembers'3:   countoddmembers' nil = 0.\n   Proof. reflexivity.  Qed.\n   \n   (* ================================================================= *)\n   (** ** Anonymous Functions *)\n   \n   (** It is arguably a little sad, in the example just above, to\n       be forced to define the function [length_is_1] and give it a name\n       just to be able to pass it as an argument to [filter], since we\n       will probably never use it again.  Moreover, this is not an\n       isolated example: when using higher-order functions, we often want\n       to pass as arguments \"one-off\" functions that we will never use\n       again; having to give each of these functions a name would be\n       tedious.\n   \n       Fortunately, there is a better way.  We can construct a function\n       \"on the fly\" without declaring it at the top level or giving it a\n       name. *)\n   \n   Example test_anon_fun':\n     doit3times (fun n => n * n) 2 = 256.\n   Proof. reflexivity.  Qed.\n   \n   (** The expression [(fun n => n * n)] can be read as \"the function\n       that, given a number [n], yields [n * n].\" *)\n   \n   (** Here is the [filter] example, rewritten to use an anonymous\n       function. *)\n   \n   Example test_filter2':\n       filter (fun l => beq_nat (length l) 1)\n              [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n     = [ [3]; [4]; [8] ].\n   Proof. reflexivity.  Qed.\n   \n   (** **** Exercise: 2 stars (filter_even_gt7)  *)\n   (** Use [filter] (instead of [Fixpoint]) to write a Coq function\n       [filter_even_gt7] that takes a list of natural numbers as input\n       and returns a list of just those that are even and greater than\n       7. *)\n   \n   Definition filter_even_gt7 (l : list nat) : list nat :=\n     filter (fun n => (negb (oddb n) && (leb 8 n))) l.\n\n   Example test_filter_even_gt7_1 :\n     filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n   Proof.\n     reflexivity.\n   Qed.\n   \n   Example test_filter_even_gt7_2 :\n     filter_even_gt7 [5;2;6;19;129] = [].\n  Proof.\n    reflexivity.\n  Qed.\n   (** [] *)\n   \n   (** **** Exercise: 3 stars (partition)  *)\n   (** Use [filter] to write a Coq function [partition]:\n   \n         partition : forall X : Type,\n                     (X -> bool) -> list X -> list X * list X\n   \n      Given a set [X], a test function of type [X -> bool] and a [list\n      X], [partition] should return a pair of lists.  The first member of\n      the pair is the sublist of the original list containing the\n      elements that satisfy the test, and the second is the sublist\n      containing those that fail the test.  The order of elements in the\n      two sublists should be the same as their order in the original\n      list. *)\n   \n   Definition partition {X : Type}\n                        (test : X -> bool)\n                        (l : list X)\n                      : list X * list X :=\n   (filter test l, filter (fun x => negb (test x)) l).\n   \n   Example test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\n   Proof. reflexivity. Qed.\n   Example test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\n   Proof. reflexivity. Qed.\n   (** [] *)\n   \n   (* ================================================================= *)\n   (** ** Map *)\n   \n   (** Another handy higher-order function is called [map]. *)\n   \n   Fixpoint map {X Y:Type} (f:X->Y) (l:list X) : (list Y) :=\n     match l with\n     | []     => []\n     | h :: t => (f h) :: (map f t)\n     end.\n   \n   (** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n       and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n       been applied to each element of [l] in turn.  For example: *)\n   \n   Example test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\n   Proof. reflexivity.  Qed.\n   \n   (** The element types of the input and output lists need not be\n       the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n       can thus be applied to a list of numbers and a function from\n       numbers to booleans to yield a list of booleans: *)\n   \n   Example test_map2:\n     map oddb [2;1;2;5] = [false;true;false;true].\n   Proof. reflexivity.  Qed.\n   \n   (** It can even be applied to a list of numbers and\n       a function from numbers to _lists_ of booleans to\n       yield a _list of lists_ of booleans: *)\n   \n   Example test_map3:\n       map (fun n => [evenb n;oddb n]) [2;1;2;5]\n     = [[true;false];[false;true];[true;false];[false;true]].\n   Proof. reflexivity.  Qed.\n   \n   (* ----------------------------------------------------------------- *)\n   (** *** Exercises *)\n   \n   (** **** Exercise: 3 stars (map_rev)  *)\n   (** Show that [map] and [rev] commute.  You may need to define an\n       auxiliary lemma. *)\n   \n   Lemma map_dis : forall (X Y : Type) (f : X -> Y) (l : list X) (x : X),\n    map f (l ++ [x]) = map f l ++ [f x].\n   Proof.\n     intros X Y f l x.\n     induction l as [| h t IHl].\n     - simpl. reflexivity.\n     - simpl. rewrite -> IHl. reflexivity.\n   Qed.\n\n   Theorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n     map f (rev l) = rev (map f l).\n   Proof.\n     intros X Y f l.\n     induction l as [| h t IHl].\n     - simpl. reflexivity.\n     - simpl. rewrite <- IHl. rewrite <- map_dis. reflexivity.\n    Qed.  \n     \n   (** [] *)\n   \n   (** **** Exercise: 2 stars, recommended (flat_map)  *)\n   (** The function [map] maps a [list X] to a [list Y] using a function\n       of type [X -> Y].  We can define a similar function, [flat_map],\n       which maps a [list X] to a [list Y] using a function [f] of type\n       [X -> list Y].  Your definition should work by 'flattening' the\n       results of [f], like so:\n   \n           flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n         = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n   *)\n   \n   Fixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                      : (list Y) :=\n    match l with\n    | [] => []\n    | h :: t => (f h) ++ (flat_map f t)\n    end.\n   \n   Example test_flat_map1:\n     flat_map (fun n => [n;n;n]) [1;5;4]\n     = [1; 1; 1; 5; 5; 5; 4; 4; 4].\n   Proof.\n    simpl.\n    reflexivity.\n   Qed.\n   (** [] *)\n   \n   (** Lists are not the only inductive type that we can write a\n       [map] function for.  Here is the definition of [map] for the\n       [option] type: *)\n   \n   Definition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                         : option Y :=\n     match xo with\n       | None => None\n       | Some x => Some (f x)\n     end.\n   \n   (** **** Exercise: 2 stars, optional (implicit_args)  *)\n   (** The definitions and uses of [filter] and [map] use implicit\n       arguments in many places.  Replace the curly braces around the\n       implicit arguments with parentheses, and then fill in explicit\n       type parameters where necessary and use Coq to check that you've\n       done so correctly.  (This exercise is not to be turned in; it is\n       probably easiest to do it on a _copy_ of this file that you can\n       throw away afterwards.)  [] *)\n   \n   (* ================================================================= *)\n   (** ** Fold *)\n   \n   (** An even more powerful higher-order function is called\n       [fold].  This function is the inspiration for the \"[reduce]\"\n       operation that lies at the heart of Google's map/reduce\n       distributed programming framework. *)\n   \n   Fixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y)\n                            : Y :=\n     match l with\n     | nil => b\n     | h :: t => f h (fold f t b)\n     end.\n   \n   (** Intuitively, the behavior of the [fold] operation is to\n       insert a given binary operator [f] between every pair of elements\n       in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n       means [1+2+3+4].  To make this precise, we also need a \"starting\n       element\" that serves as the initial second input to [f].  So, for\n       example,\n   \n          fold plus [1;2;3;4] 0\n   \n       yields\n   \n          1 + (2 + (3 + (4 + 0))).\n   \n       Some more examples: *)\n   \n   Check (fold andb).\n   (* ===> fold andb : list bool -> bool -> bool *)\n   \n   Example fold_example1 :\n     fold mult [1;2;3;4] 1 = 24.\n   Proof. reflexivity. Qed.\n   \n   Example fold_example2 :\n     fold andb [true;true;false;true] true = false.\n   Proof. reflexivity. Qed.\n   \n   Example fold_example3 :\n     fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\n   Proof. reflexivity. Qed.\n   \n   (** **** Exercise: 1 star, advancedM (fold_types_different)  *)\n   (** Observe that the type of [fold] is parameterized by _two_ type\n       variables, [X] and [Y], and the parameter [f] is a binary operator\n       that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n       situation where it would be useful for [X] and [Y] to be\n       different? *)\n   \n   (* FILL IN HERE *)\n   (** [] *)\n   \n   (* ================================================================= *)\n   (** ** Functions That Construct Functions *)\n   \n   (** Most of the higher-order functions we have talked about so\n       far take functions as arguments.  Let's look at some examples that\n       involve _returning_ functions as the results of other functions.\n       To begin, here is a function that takes a value [x] (drawn from\n       some type [X]) and returns a function from [nat] to [X] that\n       yields [x] whenever it is called, ignoring its [nat] argument. *)\n   \n   Definition constfun {X: Type} (x: X) : nat->X :=\n     fun (k:nat) => x.\n   \n   Definition ftrue := constfun true.\n   \n   Example constfun_example1 : ftrue 0 = true.\n   Proof. reflexivity. Qed.\n   \n   Example constfun_example2 : (constfun 5) 99 = 5.\n   Proof. reflexivity. Qed.\n   \n   (** In fact, the multiple-argument functions we have already\n       seen are also examples of passing functions as data.  To see why,\n       recall the type of [plus]. *)\n   \n   Check plus.\n   (* ==> nat -> nat -> nat *)\n   \n   (** Each [->] in this expression is actually a _binary_ operator\n       on types.  This operator is _right-associative_, so the type of\n       [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n       can be read as saying that \"[plus] is a one-argument function that\n       takes a [nat] and returns a one-argument function that takes\n       another [nat] and returns a [nat].\"  In the examples above, we\n       have always applied [plus] to both of its arguments at once, but\n       if we like we can supply just the first.  This is called _partial\n       application_. *)\n   \n   Definition plus3 := plus 3.\n   Check plus3.\n   \n   Example test_plus3 :    plus3 4 = 7.\n   Proof. reflexivity.  Qed.\n   Example test_plus3' :   doit3times plus3 0 = 9.\n   Proof. reflexivity.  Qed.\n   Example test_plus3'' :  doit3times (plus 3) 0 = 9.\n   Proof. reflexivity.  Qed.\n   \n   (* ################################################################# *)\n   (** * Additional Exercises *)\n   \n   Module Exercises.\n   \n   (** **** Exercise: 2 stars (fold_length)  *)\n   (** Many common functions on lists can be implemented in terms of\n      [fold].  For example, here is an alternative definition of [length]: *)\n   \n   Definition fold_length {X : Type} (l : list X) : nat :=\n     fold (fun _ n => S n) l 0.\n   \n   Example test_fold_length1 : fold_length [4;7;0] = 3.\n   Proof. reflexivity. Qed.\n   \n   (** Prove the correctness of [fold_length]. *)\n   \n   Theorem fold_length_correct : forall X (l : list X),\n     fold_length l = length l.\n   Proof.\n     intros X l.\n     induction l as [| h t IHl].\n     - simpl. reflexivity.\n     - simpl. rewrite <- IHl. reflexivity.\n    Qed.\n       \n   (** [] *)\n   \n   (** **** Exercise: 3 starsM (fold_map)  *)\n   (** We can also define [map] in terms of [fold].  Finish [fold_map]\n       below. *)\n   \n   Definition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=\n     fold (fun n p => ((f n) :: p)) l [].\n   \n   (** Write down a theorem [fold_map_correct] in Coq stating that\n      [fold_map] is correct, and prove it. *)\n   \n   (* FILL IN HERE *)\n   Theorem fold_map_correct : forall (X Y : Type) (f : X -> Y) (l : list X),\n    fold_map f l = map f l.\n   Proof.\n     intros X Y f l.\n     induction l as [| h t IHl].\n     - simpl. reflexivity.\n     - simpl. rewrite <- IHl. reflexivity.\n   Qed.\n   \n   (** **** Exercise: 2 stars, advanced (currying)  *)\n   (** In Coq, a function [f : A -> B -> C] really has the type [A\n       -> (B -> C)].  That is, if you give [f] a value of type [A], it\n       will give you function [f' : B -> C].  If you then give [f'] a\n       value of type [B], it will return a value of type [C].  This\n       allows for partial application, as in [plus3].  Processing a list\n       of arguments with functions that return functions is called\n       _currying_, in honor of the logician Haskell Curry.\n   \n       Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n       B) -> C].  This is called _uncurrying_.  With an uncurried binary\n       function, both arguments must be given at once as a pair; there is\n       no partial application. *)\n   \n   (** We can define currying as follows: *)\n   \n   Definition prod_curry {X Y Z : Type}\n     (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n   \n   (** As an exercise, define its inverse, [prod_uncurry].  Then prove\n       the theorems below to show that the two are inverses. *)\n   \n   Definition prod_uncurry {X Y Z : Type}\n     (f : X -> Y -> Z) (p : X * Y) : Z :=\n     f (fst p) (snd p).\n   \n   (** As a (trivial) example of the usefulness of currying, we can use it\n       to shorten one of the examples that we saw above: *)\n   \n   Example test_map2: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\n   Proof. reflexivity.  Qed.\n   \n   (** Thought exercise: before running the following commands, can you\n       calculate the types of [prod_curry] and [prod_uncurry]? *)\n   \n   Check @prod_curry.\n   Check @prod_uncurry.\n   \n   Theorem uncurry_curry : forall (X Y Z : Type)\n                           (f : X -> Y -> Z)\n                           x y,\n     prod_curry (prod_uncurry f) x y = f x y.\n   Proof.\n     intros X Y Z f x y.\n     reflexivity.\n    Qed.\n   \n   Theorem curry_uncurry : forall (X Y Z : Type)\n                           (f : (X * Y) -> Z) (p : X * Y),\n     prod_uncurry (prod_curry f) p = f p.\n   Proof.\n     intros X Y Z f p.\n     destruct p.\n     - reflexivity.\n    Qed.\n   \n   (** **** Exercise: 2 stars, advancedM (nth_error_informal)  *)\n   (** Recall the definition of the [nth_error] function:\n   \n      Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n        match l with\n        | [] => None\n        | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n        end.\n   \n      Write an informal proof of the following theorem:\n   \n      forall X n l, length l = n -> @nth_error X l n = None\n   \n   (* FILL IN HERE *)\n   *)\n   \n   (** Informal Proof: length l = n means that there are only n elements in the list\n      so the nth element will be None. The valid element index is from 0 to n - 1 *)\n\n   (** [] *)\n   \n   (** **** Exercise: 4 stars, advanced (church_numerals)  *)\n   (** This exercise explores an alternative way of defining natural\n       numbers, using the so-called _Church numerals_, named after\n       mathematician Alonzo Church.  We can represent a natural number\n       [n] as a function that takes a function [f] as a parameter and\n       returns [f] iterated [n] times. *)\n   \n   Module Church.\n   Definition nat := forall X : Type, (X -> X) -> X -> X.\n   \n   (** Let's see how to write some numbers with this notation. Iterating\n       a function once should be the same as just applying it.  Thus: *)\n   \n   Definition one : nat :=\n     fun (X : Type) (f : X -> X) (x : X) => f x.\n   \n   (** Similarly, [two] should apply [f] twice to its argument: *)\n   \n   Definition two : nat :=\n     fun (X : Type) (f : X -> X) (x : X) => f (f x).\n   \n   (** Defining [zero] is somewhat trickier: how can we \"apply a function\n       zero times\"?  The answer is actually simple: just return the\n       argument untouched. *)\n   \n   Definition zero : nat :=\n     fun (X : Type) (f : X -> X) (x : X) => x.\n   \n   (** More generally, a number [n] can be written as [fun X f x => f (f\n       ... (f x) ...)], with [n] occurrences of [f].  Notice in\n       particular how the [doit3times] function we've defined previously\n       is actually just the Church representation of [3]. *)\n   \n   Definition three : nat := @doit3times.\n   \n   (** Complete the definitions of the following functions. Make sure\n       that the corresponding unit tests pass by proving them with\n       [reflexivity]. *)\n   \n   (** Successor of a natural number: *)\n\n   Definition succ (n : nat) : nat :=\n    fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\n  \n   Example succ_1 : succ zero = one.\n   Proof.\n     reflexivity.\n   Qed.\n\n   Example succ_2 : succ one = two.\n   Proof.\n     reflexivity.\n   Qed. \n   \n   Example succ_3 : succ two = three.\n   Proof.\n     reflexivity.\n   Qed. \n\n   \n   (** Addition of two natural numbers: *)\n   \n   Definition plus (n m : nat) : nat :=\n     fun (X : Type) (f : X -> X) (x : X) => n X f (m X f x).\n   \n   Example plus_1 : plus zero one = one.\n   Proof. \n     reflexivity.\n   Qed.\n   \n   Example plus_2 : plus two three = plus three two.\n   Proof.\n     reflexivity.\n   Qed.\n   \n   Example plus_3 :\n     plus (plus two two) three = plus one (plus three three).\n   Proof. \n     reflexivity.\n   Qed.\n   \n   (** Multiplication: *)\n   \n   Definition mult (n m : nat) : nat :=\n     fun (X : Type) (f : X -> X) (x : X) => n X (m X f) x.\n   \n   Example mult_1 : mult one one = one.\n   Proof.\n     reflexivity.\n   Qed.\n   \n   Example mult_2 : mult zero (plus three three) = zero.\n   Proof. \n     reflexivity.\n   Qed.\n   \n   Example mult_3 : mult two three = plus three three.\n   Proof.\n     reflexivity.\n   Qed.\n   \n   (** Exponentiation: *)\n   \n   (** (_Hint_: Polymorphism plays a crucial role here.  However,\n       choosing the right type to iterate over can be tricky.  If you hit\n       a \"Universe inconsistency\" error, try iterating over a different\n       type: [nat] itself is usually problematic.) *)\n   \n   Definition exp (n m : nat) : nat :=\n     fun (X : Type) (f : X -> X) (x : X) => \n        m (X -> X) (n X) f x.\n   \n   Example exp_1 : exp two two = plus two two.\n   Proof. \n     reflexivity.\n    Qed.\n   \n   Example exp_2 : exp three two = plus (mult two (mult two two)) one.\n   Proof. \n     reflexivity.\n    Qed.\n   \n   Example exp_3 : exp three zero = one.\n   Proof. \n     reflexivity.\n    Qed.\n   \n   End Church.\n   (** [] *)\n   \n   End Exercises.\n   \n   (** $Date: 2016-10-07 15:11:04 -0400 (Fri, 07 Oct 2016) $ *)\n   ", "meta": {"author": "SugarSBN", "repo": "Software-Foundations-CIS500", "sha": "3e413e4443ea197a3bc096e35bd992b75c83329e", "save_path": "github-repos/coq/SugarSBN-Software-Foundations-CIS500", "path": "github-repos/coq/SugarSBN-Software-Foundations-CIS500/Software-Foundations-CIS500-3e413e4443ea197a3bc096e35bd992b75c83329e/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430604060731, "lm_q2_score": 0.867035763237924, "lm_q1q2_score": 0.7206307577390836}}
{"text": "From CReal.MetricSpace Require Export M_pack.\nTheorem PNP : forall p : Prop, ~(p /\\ ~p) .\nProof.\n  unfold not. intros. destruct H. apply H0 in H. apply H.\nQed.\n\nLemma le_one : forall (m n : nat), (m <= n)%nat \\/ (n <= m)%nat.\nProof.\n  intro m. induction m.\n  -intros. left. induction n. apply le_n. apply le_S. apply IHn.\n  -intros. destruct n. +right. apply le_0_n. +destruct IHm with (n := n).\n  {left. apply le_n_S. auto. } {right. apply le_n_S. auto. }\nQed.\n\nLemma le_equ : forall (m n : nat), (m <= n)%nat -> (n <= m)%nat -> m = n.\nProof.\n  intro m. induction m as [| m' IH]. -intros. destruct n. auto. inversion H0.\n  -intros. destruct n. +inversion H. +apply le_S_n in H. apply le_S_n in H0.\n    assert (m' = n). apply IH. apply H. apply H0. auto.\nQed.\n\n\nLemma always_greater : forall (m n : nat), exists N, (m < N)%nat /\\ (n < N)%nat.\nProof.\n    intro m. induction m. -intros. exists (S n).\n    split. apply neq_0_lt. unfold not. intros. inversion H. unfold lt. apply le_n.\n    -intros. destruct IHm with (n :=n) as [N']. destruct H. exists (S N').\n    split. apply lt_n_S. auto. unfold lt. unfold lt in H0. apply (le_trans (S n) N' (S N')).\n    auto. apply le_S. apply le_n.\nQed. ", "meta": {"author": "QinxiangCao", "repo": "ClassicalReal", "sha": "60860e58d1ca98251ce7fdd01a7175bb8c560dd8", "save_path": "github-repos/coq/QinxiangCao-ClassicalReal", "path": "github-repos/coq/QinxiangCao-ClassicalReal/ClassicalReal-60860e58d1ca98251ce7fdd01a7175bb8c560dd8/MetricSpace/M_pre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7206307343949429}}
{"text": "Module NatList.\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\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\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, l2' => l2'\n  | l1', nil => l1'\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].\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.", "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/Chapter3/alternate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.7206307195037134}}
{"text": "(** Calculation of an abstract machine for arithmetic expressions. *)\n\nRequire Import List.\nRequire Import ListIndex.\nRequire Import Tactics.\n\n(** * Syntax *)\n\nInductive Expr : Set := \n| Val (n : nat) : Expr \n| Add (x y: Expr) : Expr.\n\n(** * Semantics *)\n\nFixpoint eval (e: Expr) : nat :=\n  match e with\n    | Val n => n\n    | Add x y => eval x + eval y\n  end.\n\n(** * Abstract machine *)\n\nInductive CONT : Set :=\n| NEXT : Expr -> CONT -> CONT\n| ADD : nat -> CONT -> CONT\n| HALT : CONT\n.\n\nInductive Conf : Set := \n| eval'' : Expr -> CONT -> Conf\n| apply : CONT -> nat -> Conf.\n\nNotation \"⟨ x , c ⟩\" := (eval'' x c).\nNotation \"⟪ c , v ⟫\" := (apply c v).\n\n\n\nReserved Notation \"x ==> y\" (at level 80, no associativity).\nInductive AM : Conf -> Conf -> Prop :=\n| am_val n c : ⟨Val n, c⟩ ==> ⟪c, n⟫\n| am_add x y c : ⟨Add x y, c⟩ ==> ⟨x, NEXT y c⟩\n| am_NEXT y c n : ⟪NEXT y c, n⟫ ==> ⟨y, ADD n c⟩\n| am_ADD c n m : ⟪ADD n c, m⟫ ==> ⟪c, n+m⟫\nwhere \"x ==> y\" := (AM x y).\n\n\n(** * Calculation *)\n\n(** Boilerplate to import calculation tactics *)\n\nModule AM <: Preorder.\nDefinition Conf := Conf.\nDefinition VM := AM.\nEnd AM.\nModule AMCalc := Calculation AM.\nImport AMCalc.\n\n(** Specification of the abstract machine *)\n\nTheorem spec x c : ⟨x, c⟩ =>> ⟪c, eval x⟫.\n\n(** Setup the induction proof *)\n\nProof.\n  intros.\n  generalize dependent c.\n  induction x;intros.\n\n(** Calculation of the abstract machine *)\n\n  begin\n  ⟪c, eval (Val n)⟫.\n  =   {reflexivity}\n  ⟪c, n⟫.\n  <== { apply am_val }\n  ⟨Val n, c⟩.\n  [].\n\n  begin\n    ⟪c, eval (Add x1 x2) ⟫.\n  =   {reflexivity}\n    ⟪c, eval x1 + eval x2 ⟫.\n  <== { apply am_ADD }\n      ⟪ADD (eval x1) c, eval x2⟫.\n  <<= { apply IHx2 }\n      ⟨x2, ADD (eval x1) c⟩.\n  <== { apply am_NEXT }\n      ⟪NEXT x2 c, eval x1⟫.\n  <<= { apply IHx1 }\n      ⟨x1, NEXT x2 c⟩.\n  <== {apply am_add}\n      ⟨Add x1 x2, c ⟩.\n  [].\n\nQed.\n  \n", "meta": {"author": "pa-ba", "repo": "cps-defun", "sha": "2f2c9d3e45f4a7fb12dadbff41579d0fa5a085bf", "save_path": "github-repos/coq/pa-ba-cps-defun", "path": "github-repos/coq/pa-ba-cps-defun/cps-defun-2f2c9d3e45f4a7fb12dadbff41579d0fa5a085bf/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.720630263372382}}
{"text": "Require Import Bool List Arith Nat Coq.Arith.Div2.\nImport ListNotations.\n\n\n\nFixpoint bit_n (l : list bool) : nat :=\n  match l with\n    | [] => 0\n    | a :: tl => 2 * bit_n tl + Nat.b2n a\n  end.\n\n\nFixpoint n_bit (n : nat) (k : nat) : option (list bool) :=\n    match n with\n      | 0 => match k with\n             | 0 => Some []\n             | S _ => None\n             end\n      | S n' => match n_bit n' (Nat.div2 k) with\n                  | None => None\n                  | Some l => Some (Nat.odd k :: l)\n                end\n    end.\n\nCompute pow 2 8.\nCheck leb 2 3.\n\nLemma n_bit_dont_fail : forall (n k : nat),\n    k < pow 2 n -> exists (l : list bool), n_bit n k = Some l.\nProof.\n  induction n.\n  -destruct k.\n   +simpl.\n    exists [].\n    reflexivity.\n   +simpl.\n    Search (_ < 0).\n    Search (S _ < S _).\n    exists [].\n    apply lt_S_n in H.\n    Search (_ < 0).\n    apply Nat.nlt_0_r in H.\n    inversion H.    \n  -intros.\n   simpl.\n   specialize (IHn (Nat.div2 k)).\n   edestruct IHn.\n   +Search Nat.div2.\n    admit.\n   +rewrite H0.\n    eauto.\nAdmitted.   \n\n\nSearchAbout (_ mod _).\n\nLemma size_n_bit : forall (n k: nat) (l : list bool),\n    n_bit n k = Some l -> length l = n.\nProof.\n  induction n.\n  -intros k l.\n   induction k.\n   +intros.\n    inversion H.\n    reflexivity.\n   +simpl.\n    discriminate.\n  -intros k l.\n   simpl.\n   case_eq (n_bit n (Nat.div2 k)).  \n   +intros.\n    inversion H0.\n    assert (help1: forall (l' : list bool) (b : bool), length l' = n -> length(b :: l') = S n).\n    {\n      induction l'.\n      -intros b.\n       simpl.\n       intros.\n       rewrite H1.\n       reflexivity.\n      -intros b.\n       simpl.\n       intros.\n       rewrite H1.\n       reflexivity.\n    }    \n    apply help1.\n    specialize (IHn (Nat.div2 k)).\n    apply IHn.\n    exact H.\n   +intros.\n    discriminate.\nQed.\n     \n\n(* first proof that we need on binary representation *)\nTheorem n_bit_n : forall (l : list bool) (n k : nat),\n                    n_bit n k = Some l -> bit_n l = k.\nProof.\n  assert (I : forall (l : list bool) (n k : nat), n_bit n k = Some l -> bit_n l = k).\n  {\n    intros l; induction l; intros n k.\n    simpl.\n    assert (I_1 : n_bit n k = Some [] -> bit_n [] = k).\n    {\n      induction k.\n      - reflexivity.\n       (* the hypothesis is false so we will need to find how to demonstrate this *)\n      - assert (I_1_1 : n_bit n (S k) = Some [] -> bit_n [] = S k).\n       {\n         induction n.\n         - discriminate.\n         - unfold n_bit; fold n_bit.\n           destruct (n_bit n (Nat.div2 (S k))); discriminate.\n       }\n       exact I_1_1.\n    }\n    exact I_1.\n    assert (I_2 : n_bit n k = Some (a :: l) -> bit_n (a :: l) = k).\n    {\n      intros H.\n      simpl.\n      About Nat.div2_odd.\n      rewrite (Nat.div2_odd k).\n      simpl.\n      destruct n; simpl in H.\n      - destruct k; discriminate.\n      - destruct (n_bit n (Nat.div2 k)) eqn:Hl; try discriminate.\n        inversion H; subst.\n        erewrite IHl; eauto.\n    }\n    assumption.\n  }\n  assumption.\nQed.\n\n\n(* second proof *)\nTheorem bit_n_bit : forall (l : list bool) (n : nat),\n                      n = length l -> (n_bit n (bit_n l)) = Some l.\nProof.\n  assert (I : forall (l : list bool) (n : nat), n = length l -> n_bit n (bit_n l) = Some l).\n  {\n    induction l.\n    assert (I_1 : forall n : nat, n = length ([] : list bool) -> n_bit n (bit_n []) = Some []).\n    {\n      simpl.\n      intros n H.\n      rewrite H.\n      reflexivity.\n    }\n    exact I_1.\n    assert (I_2 : forall n : nat, n = length (a :: l) -> n_bit n (bit_n (a :: l)) = Some (a :: l)).\n    {\n      intros n.\n      simpl.\n      destruct a.\n      assert (I_2_1 : n = length (true :: l) -> n_bit n (bit_n (true :: l)) = Some (true :: l)).\n      {\n        simpl.\n        Search (_ + 0).\n        rewrite <- plus_n_O.\n        intros H.\n        rewrite H.\n        simpl.\n        assert (I_2_1_1 : forall l' : (list bool), bit_n l' + bit_n l' = 2 * bit_n l').\n        {\n          induction l'.\n          -reflexivity.\n          -simpl.\n           rewrite <- plus_n_O.\n           rewrite <- plus_n_O.\n           reflexivity.\n        }        \n        rewrite I_2_1_1.\n        Search (_ + 1 = S _).\n        Search (Nat.div2 _).\n        rewrite Nat.add_1_r.\n        Check even_div2.\n        rewrite <- even_div2.\n        -Search (Nat.div2 (2 * _)).\n         rewrite div2_double.\n         rewrite IHl.\n         +assert (I_2_1_2 : forall (n' : nat), Nat.odd (S (2 * n')) = true).\n          {\n            intros n'.\n            induction n'.\n            -reflexivity.\n            -simpl.\n             rewrite <- plus_n_Sm.\n             simpl in IHn'.\n             rewrite <- IHn'.\n             Search (Nat.odd (S (S _))).\n             rewrite Nat.odd_succ_succ. reflexivity.\n          }\n          rewrite I_2_1_2.\n          reflexivity.\n         +reflexivity.\n        -assert (I_2_1_3 : Even.even (2 * bit_n l)).\n         {\n           (* this is supposed to be trivial -_-_-_-_-_-_-_-_-_-_-_-_- *)\n           Check Nat.even_add_mul_2.\n           Search (0 + _).\n           rewrite <- Nat.add_0_l.\n           SearchAbout (even (_ + _)).\n           specialize (Nat.even_add_mul_2 0 (bit_n l)).\n           intros.\n           Check Even.even_equiv.\n           apply Even.even_equiv.\n           (* even spec *)\n           Check Nat.even_spec.\n           simpl in H0.\n           Search (_ + _ = 2 * _).\n           Check I_2_1_1.\n           rewrite <- I_2_1_1.\n           assert (0 + (bit_n l + bit_n l) = bit_n l + (bit_n l + 0)).\n           { simpl. Search (_ + 0). rewrite <- plus_n_O. reflexivity. }\n           rewrite H1. \n           rewrite Nat.even_spec in H0.\n           exact H0.\n         }\n         exact I_2_1_3.\n      }\n      exact I_2_1.\n      assert (I_2_2 : n = S (length l) -> n_bit n (bit_n l + (bit_n l + 0) + Nat.b2n false) = Some (false :: l)).\n      {\n        simpl.\n        Search (_ + 0).\n        rewrite <- plus_n_O.\n        rewrite <- plus_n_O.\n        intros H.\n        rewrite H.\n        simpl.\n        Search (2 * _ = _).\n        assert (I_2_2_0 : forall (n' : nat), 2 * n' = n' + n').\n        {\n          intros n'. simpl. rewrite <- plus_n_O. reflexivity.\n        }\n        rewrite <- I_2_2_0.\n        rewrite div2_double.\n        rewrite IHl.\n        -assert (I_2_2_1 : forall (n' : nat), Nat.odd (2 * n') = false).\n         {\n           induction n'.\n           -simpl. Search (Nat.odd 0).\n            rewrite Nat.odd_0. reflexivity.\n           -simpl.\n            Search (_ + 0).\n            rewrite <- plus_n_O.\n            Search (_ + _ = _ + _).\n            rewrite <- plus_Snm_nSm.\n            Search (S _ + _).\n            rewrite plus_Sn_m.\n            Search (Nat.odd (S (S _))).\n            rewrite Nat.odd_succ_succ.\n            simpl in IHn'.\n            rewrite <- plus_n_O in IHn'.\n            rewrite IHn'.\n            reflexivity.            \n         }\n         rewrite I_2_2_1.\n         reflexivity.\n        -reflexivity.\n      }\n      exact I_2_2.\n    }\n    exact I_2.\n  }\n  exact I.\nQed.", "meta": {"author": "romisfrag", "repo": "little_mmx_encode-decode", "sha": "9f5a583fc2376f271bac30ec82c8800614a5fdd6", "save_path": "github-repos/coq/romisfrag-little_mmx_encode-decode", "path": "github-repos/coq/romisfrag-little_mmx_encode-decode/little_mmx_encode-decode-9f5a583fc2376f271bac30ec82c8800614a5fdd6/oldsrc/binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7206302510787764}}
{"text": "Require Export D.\n\n\n(********** Existential Quantification **********)\n\nPrint ex.\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n ex_intro : forall (witness:X), P witness -> ex X P.\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\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof. apply ex_intro with (witness:=2). constructor.  Qed.\n\nExample exists_example_22 : exists n, n + (n * n) = 6.\nProof. exists 2. constructor.  Qed.\n\nTheorem exists_example_2 : forall n,\n  (exists m, n = 4 + m) -> (exists o, n = 2 + o).\nProof. intros. inversion H as [m Hm]. exists (2+m).\n  assumption. Qed.\n\nLemma exists_example_3 : exists (n:nat), even n /\\ beautiful n.\nProof. exists 8. split.\n  Case \"even\". unfold even. reflexivity.\n  Case \"beautiful\". apply b_sum with (n:=3) (m:=5). apply b_3. apply b_5. Qed.\n\nDefinition Eng_e : Prop := ex nat (fun n => beautiful (S n)).\nExample eng : Eng_e.\nProof. exists 2. apply b_3. Qed. \n\nTheorem dist_not_exists : forall (X:Type) (P: X -> Prop),\n    (forall x, P x) -> ~(exists x, ~(P x)).\nProof. intros.  unfold not. intro Hcontra.\n  inversion Hcontra. apply H0 in H. inversion H. Qed.\n\n\n\nPrint ex_falso_quodlibet.\n\nTheorem not_exists_dist :\n  excluded_middle ->\n    forall (X:Type) (P:X -> Prop), ~(exists x, ~(P x)) -> \n      (forall x, P x).\nProof.\n unfold excluded_middle. unfold not.\n  intros H X P H2 x. destruct H with (P:=P x).\n  Case \"P\". apply H0.\n  Case \"~P\". apply ex_falso_quodlibet. apply H2. exists x. assumption.\nQed.\n\nTheorem dist_exsits_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  Case \"->\". intros. destruct H as [x]. inversion H.\n    SCase \"P x\". left. exists x. assumption.     \n    SCase \"Q x\". right. exists x. assumption.\n  Case \"<-\". intros. destruct H.\n    SCase \"P x\". destruct H as [x]. exists x. left. assumption.\n    SCase \"Q x\". destruct H as [x]. exists x. right. assumption.\nQed.\n\n\n(********** Evidence_Carrying Booleans **********)\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\nTheorem eq_nat_dec : forall n m: nat, \n  {n = m} + {~(n = m)}.\nProof. intros n.\n  induction n as [|n'].\n  Case \"O\".\n    intro m. destruct m as [|m'].\n    SCase \"O\". left. reflexivity.\n    SCase \"S m\". right. intros contra. inversion contra.\n  Case \"S n\".\n    intro m. destruct m as [|m'].\n    SCase \"O\". right. intros contra. inversion contra.  \n    SCase \"S m\". destruct IHn' with (m:=m').\n      SSCase \"left\". left. rewrite e. reflexivity.\n      SSCase \"right\". right. intros contra. inversion contra. apply n in H0. inversion H0.\nQed.\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 -> (override' f k1 x1) k2 = f k2.\nProof. intros. unfold override'. destruct (eq_nat_dec k1 k2) eqn:Heq.\n  Case \"left\".  rewrite<-e. symmetry. assumption. \n  Case \"right\". reflexivity. Qed.\n\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. intros. unfold override'. destruct (eq_nat_dec k1 k2) eqn:Heq.\n  Case \"left\". reflexivity.\n  Case \"right\". reflexivity.\nQed.\n\n\n(********** Additional Exercises **********) \n\nInductive all (X:Type) (P: X -> Prop) : list X -> Prop :=\n|all_nil : all X P []\n|all_cons :  forall hd tl, P hd -> all X P tl -> all X P (hd::tl)\n.\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool := \nmatch l with\n| [] => true\n| hd::tl => andb (test hd) (forallb test tl)\nend.\n\nTheorem all_forallb : forall (X : Type) (test : X -> bool) (l : list X),\n  all X (fun x => test x = true) l <-> forallb test l = true.\nProof.\n  intros.  (*remember (fun x : X => test x = true) as P.*) split. \n  Case \"->\".\n  {\n     intro H. induction l as [|hd tl].\n    SCase \"[]\". reflexivity. \n    SCase \"hd::tl\". simpl. unfold andb. destruct (forallb test tl) eqn:Htl. destruct (test hd) eqn:Hhd. reflexivity.\n      inversion H. rewrite H2 in Hhd. inversion Hhd. \n      destruct (test hd) eqn:Hhd. inversion H. apply IHtl in H3. inversion H3.\n      inversion H. rewrite H2 in Hhd. inversion Hhd.\n  }\n  Case \"<-\".\n  {\n    intro H. induction l as [|hd tl].\n    SCase \"[]\". apply all_nil.   \n    SCase \"hd::tl\". apply all_cons. inversion H.\n      destruct (test hd) eqn:Hhd. symmetry. assumption. reflexivity.\n     apply IHtl. inversion H. destruct (forallb test tl) eqn:Htl.\n      symmetry. assumption. destruct (test hd) eqn:Hhd. reflexivity. reflexivity.\n  }\n Qed.\n\n\n(*********************************************************)\nInductive inorder_merge {X : Type} : list X -> list X -> list X -> Prop :=\n| inorder_nil : inorder_merge [] [] []\n| inorder_l1 : forall hd tl l2 l3,\n  inorder_merge tl l2 l3 -> inorder_merge (hd::tl) l2 (hd::l3)\n| inorder_l2 : forall l1 hd tl l3,\n  inorder_merge l1 tl l3 -> inorder_merge l1 (hd::tl) (hd::l3)\n.\n\nLemma same_tail : forall (X:Type) (x:X) t1 t2, x::t1 = x::t2 -> t1 = t2.\nProof. intros. inversion H. reflexivity. Qed.\n\n\nTheorem filter_challenge : forall (X:Type) (l1 l2 l:list X) (test:X->bool),\n  (filter test l1 = l1) -> (filter test l2 = []) -> inorder_merge l1 l2 l -> (filter test l = l1).\nProof.\n intros. induction H1.\n  Case \"inorder_nil\". assumption.\n  Case \"inorder_l1\". simpl. destruct (test hd) eqn:Hhd.\n    SCase \"true\".  assert (Htl : filter test tl = tl).\n    Proof. inversion H. rewrite Hhd in H3. apply same_tail in H3. assumption.\n  apply IHinorder_merge in Htl. rewrite Htl. reflexivity. assumption.\n    SCase \"false\". simpl in H. rewrite Hhd in H. inversion H.  inversion H. \nAbort.\n(*************************************************************)\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\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. intros X xs. induction xs as [|hd tl].\n  Case \"[]\". intros. replace ([]++ys) with ys in H. right. assumption. reflexivity. \n  Case \"hd::tl\". intros. inversion H.\n    SCase \"ai_here\". left. apply ai_here.\n    SCase \"ai_later\". apply IHtl in H1. destruct H1. left. apply ai_later. assumption. right. assumption. Qed.\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. intros. destruct H.\n  Case \"left\". induction xs as [|hd tl].\n    SCase \"[]\". inversion H.\n    SCase \"hd::tl\". replace ((hd::tl)++ys) with (hd::(tl++ys)).\n      inversion H. apply ai_here. apply ai_later. apply IHtl. assumption. reflexivity.\n  Case \"right\". induction xs as [|hd tl].\n    SCase \"[]\". simpl. assumption.\n    SCase \"hd::tl\". replace ((hd::tl)++ys) with (hd::(tl++ys)). \n      apply ai_later. assumption. reflexivity. Qed.\n\nDefinition disjoint (X:Type) (l1 l2:list X) : Prop :=\n  forall (x:X), appears_in x (l1 ++ l2) -> (appears_in x l1 -> ~(appears_in x l2)) /\\ (appears_in x l2 -> ~(appears_in x l1)).\n\nExample dis_ex : disjoint nat [1;2] [4;5].\nProof. unfold disjoint. intros. split.\n  Case \"left\". intro H2. inversion H2. \n    SCase \"ai_here\". unfold not. intro contra. inversion contra. inversion H4. inversion H7. \n    SCase \"ai_later\". unfold not. intro contra. inversion H1. rewrite H5 in contra. inversion contra as [|n l' contra2]. inversion contra2. inversion H9.\n      inversion H5.\n  Case \"right\".  intro H2. inversion H2. \n    SCase \"ai_here\". unfold not. intro contra. inversion contra. inversion H4. inversion H7. \n    SCase \"ai_later\". unfold not. intro contra. inversion H1. rewrite H5 in contra. inversion contra as [|n l' contra2]. inversion contra2. inversion H9.\n      inversion H5. Qed.\n\nInductive no_repeats (X:Type) : list X ->  Prop :=\n| nr_nil : no_repeats X []\n| nr_cons : forall hd tl, no_repeats X tl -> ~(appears_in hd tl) -> no_repeats X (hd::tl)\n.\n\nInductive nostutter: list nat -> Prop :=\n| ns_nil : nostutter []\n| ns_single : forall n, nostutter [n]\n| ns_cons : forall x1 x2 tl, (x1<>x2) -> nostutter tl -> nostutter (x1::x2::tl)\n.\nExample nostutter_example_1 : nostutter [1;4;1].\nProof. apply ns_cons. intros contra. inversion contra. apply ns_single. Qed.\n\n\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/practice/MoreLogic_practice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7204774605783469}}
{"text": "Parameter G : Set.\nParameter mult : G -> G -> G.\nNotation \"x * y\" := (mult x y).\nParameter one : G.\nNotation \"1\" := one.\nParameter inv : G -> G.\nNotation \"/ x\" := (inv x).\n\nAxiom mult_assoc : forall x y z, x * (y * z) = (x * y) * z.\nAxiom one_unit_l : forall x, 1 * x = x.\nAxiom inv_l : forall x, /x * x = 1.\n\nLemma inv_r : forall x, x * / x = 1.\nProof.\n  intros.\n  rewrite <- (one_unit_l  x).\n  rewrite <- (inv_l (/ x)).\n  rewrite <- (mult_assoc (/ / x) (/ x) x).\n  rewrite inv_l.\n  rewrite <- (mult_assoc (/ / x) 1 (/ (/ / x * 1))).\n  rewrite one_unit_l.\n  rewrite inv_l.\n  rewrite <- (inv_l x).\n  rewrite (mult_assoc (/ / x) (/ x) x).\n  rewrite inv_l.\n  rewrite one_unit_l.\n  rewrite inv_l.\n  rewrite inv_l.\n  reflexivity.\nQed.\n\nLemma one_unit_r : forall x, x * / x = 1.\nProof.\n  intros.\n  rewrite inv_r.\n  reflexivity.\nQed.", "meta": {"author": "KeenS", "repo": "coqex", "sha": "325a48569d54a8925e41f757cbb4c3c74443c5a3", "save_path": "github-repos/coq/KeenS-coqex", "path": "github-repos/coq/KeenS-coqex/coqex-325a48569d54a8925e41f757cbb4c3c74443c5a3/2/10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7204625001355948}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import Multiset.\n\nRequire Import Relations.\nRequire Import Arith.\nRequire Import Omega.\n\nSet Implicit Arguments.\n\nSection defs.\n\n(* TODO:\n   - finish soundness -- Done\n   - think / read about completeness \n   - make proofs independent of list order, either by reformulating proof rules, \n     or by using multisets -- Done*)\n\nInductive Formula :=\n  var : nat -> Formula (* p_n *)\n| neg : Formula -> Formula\n| con : Formula -> Formula -> Formula.\n\nDefinition Sequent := multiset Formula.\n\nLemma eqA_dec : forall x y: Formula, {x = y} + {~ (x = y)}.\nintros; decide equality.\nauto with arith.\nQed.\n\n  Let emptyBag := EmptyBag Formula.\n  Let singletonBag := SingletonBag _ eqA_dec.\n\nFixpoint list_contents (l:list Formula) : multiset Formula :=\n    match l with\n      | nil => emptyBag\n      | a :: [] => (singletonBag a)\n      | a :: l => munion (singletonBag a) (list_contents l)\n    end.\n\nLemma sumpos (n m: nat) : n + m > 0 <-> ((n > 0) \\/ (m > 0)).\nProof.\n  omega.\nQed.\n\nDefinition InMSet (a : Formula) (m : multiset Formula): Prop  := multiplicity m a > 0.\n\nLemma multiSInversion: forall (x: Formula) (m n : multiset Formula), (InMSet x (munion m n) <-> ((InMSet x m) \\/ (InMSet x n))).\nProof.\n  intros x m n.\n  split.\n  intros H.\n  unfold InMSet; unfold InMSet in H; simpl in H.\n  destruct multiplicity; simpl in H.\n  right; assumption.\n  auto with arith.\n  intros H.\n  unfold InMSet; unfold InMSet in H; simpl.\n  destruct multiplicity.\n  destruct H.\n  auto with arith.\n  auto with arith.\n  auto with arith.\nQed.\n\nLemma SingletonEquality:\n  forall (x y: Formula) , InMSet x (singletonBag y) <-> (x = y).\nProof.\n  split.\n  -intros H. unfold InMSet in H. simpl in H .  destruct eqA_dec.\n  rewrite e. reflexivity. assert (Zero: ~(0 > 0)).\n  auto with arith. contradiction.\n  \n  -intros H. unfold InMSet. simpl. rewrite H. destruct eqA_dec.\n  auto with arith. contradiction.\n  Qed. \n\n\n(* proofs of validity of a sequent *)\nInductive Proof : Sequent -> Type :=\n  ax : forall (n: nat) (Gamma: Sequent),  \n    Proof (  munion  (list_contents [ var n ; neg (var n)] ) Gamma )\n| ci : forall (A B : Formula) (Gamma: Sequent),\n    Proof (munion (list_contents [A]) Gamma) -> Proof (munion (list_contents [B]) Gamma) -> Proof (munion (list_contents [con A B])  Gamma)\n| di : forall (A B : Formula) (Gamma: Sequent), \n    Proof (munion (list_contents [ neg A; neg B]) Gamma) -> Proof (munion (list_contents [neg (con A B) ]) Gamma).\n\n\n(* todo: think about list order or use multisets, and define truth *)\n\n(* negb: bool -> bool is boolean negation library function *)\n(* andb: bool -> bool -> bool is conjunction library function *)\nCheck negb.\nCheck andb.\n\nDefinition Valuation := nat -> bool.\n\nFixpoint ev (A: Formula) (v: Valuation) : bool :=\n  match A with\n  | var n => (v n)\n  | neg B => negb (ev B v)\n  | con A B => andb (ev A v) (ev B v)\n  end.\n\n(* counterexample to validity *)\nDefinition counterexample (v: Valuation) (Gamma: Sequent) :=\n  forall (A: Formula), InMSet A Gamma -> ev A v = false.\n\nCheck true.\n\nDefinition validF (A : Formula) := forall (v: Valuation),  ev A v = true.\nDefinition validS (Gamma : Sequent) := forall (v: Valuation), exists (A: Formula),\n       InMSet A Gamma /\\ ev A v = true.\n\n(* Theorem conversion: forall (a b : bool), negb (a && b) = neg b *)\n\n(* soundness *)\nTheorem sound : forall (Gamma : Sequent) (p: Proof Gamma),  validS Gamma.\nProof.\n  intros Gamma p.\n  induction p.\n  unfold validS.\n  intro v.\n  (* case distinction on v n = true or false *)\n\n  (* probably use a library function or proof? *)\n  assert (H: (v n = true) \\/ (v n = false) ).\n  destruct (v n).\n  left.  reflexivity.\n  right. reflexivity.\n\n  destruct H as [HL | HR].\n  (* case v n = true *)\n  exists (var n).\n  split.\n  unfold InMSet.\n  simpl.\n  destruct eqA_dec.\n  auto with arith.\n  contradiction. \n  assumption.\n  \n\n(*   case v n is false *)\n  exists (neg (var n)).\n  split.\n  unfold InMSet.\n  simpl.\n  destruct eqA_dec.\n  auto with arith.\n  destruct eqA_dec.\n  auto with arith.\n  contradiction.\n  simpl.\n  rewrite HR.\n  reflexivity.\n  \n(* case of conjunction *)\n  unfold validS.\n  intro v.\n  destruct IHp1 with (v:= v); destruct IHp2 with (v:= v).\n  firstorder.\n  simpl in H0; simpl in H.\n  \n  rewrite multiSInversion in H0; rewrite multiSInversion in H.\n  destruct H0.\n  destruct H.\n  exists (con x x0).\n  split.\n  simpl.\n  rewrite multiSInversion.\n  left.\n  rewrite  SingletonEquality in H0; rewrite SingletonEquality in H.\n rewrite H0; rewrite H.\n  rewrite SingletonEquality; reflexivity.\n  simpl. rewrite H1; rewrite H2. reflexivity.\n\n  exists x. \n  split. \n  simpl.\n  rewrite multiSInversion.\n  right; assumption.\n  assumption.\n\n  exists x0.\n  split. \n  simpl.\n  rewrite multiSInversion.\n  right; assumption.\n  assumption.\n\n  (* case of disjunction *)\n  intro v.\n  destruct IHp with (v := v).\n  firstorder.\n  simpl in H.\n  rewrite multiSInversion in H.\n  destruct H.\n  rewrite multiSInversion in H.\n  destruct H.\n\n  - rewrite SingletonEquality in H.\n  exists (neg(con A B)).\n  split. simpl. rewrite multiSInversion. left. rewrite SingletonEquality.\n  reflexivity.\n  rewrite H in H0. simpl in H0.\n  apply Bool.negb_false_iff in H0;\n  rewrite <- Bool.negb_involutive_reverse in H0.\n  simpl.\n  destruct(ev B v).\n  rewrite H0; reflexivity.\n  rewrite H0; reflexivity.\n\n  - rewrite SingletonEquality in H.\n  exists (neg(con A B)).\n  split. simpl. rewrite multiSInversion. left. rewrite SingletonEquality.\n  reflexivity.\n  rewrite H in H0. simpl in H0.\n  apply Bool.negb_false_iff in H0;\n  rewrite <- Bool.negb_involutive_reverse in H0.\n  simpl.\n  destruct(ev A v).\n  rewrite H0; reflexivity.\n  rewrite H0; reflexivity.\n\n  -exists x.\n  split.\n  simpl. rewrite multiSInversion. right. assumption.\n  assumption.\nQed.\n\n\n(* completeness: every valid sequent is provable *)\n    Theorem complete: forall (Gamma: Sequent),  validS Gamma -> exists (p: Proof Gamma), True.\nProof.\n\nintros Gamma HG.\nunfold Sequent in Gamma.\nunfold validS in HG.\nspecialize (HG (fun _ => true)). destruct HG as [A [H1 H2]].\ndestruct A. exists. simpl in H2. pose ax. simpl in p. apply (Proof v). \n\n\n\nPrint validS.\nintros G. induction G.\nintros H1.  unfold validS in H1.\n\nintuition.\n\n      admit.\n\n(* decidable with counterexample *)\n      Theorem decidable : forall (Gamma: Sequent),  (exists p: Proof Gamma, True) \\/ (exists v: Valuation, counterexample v Gamma).\n        admit.", "meta": {"author": "rahulghangas", "repo": "Prop-Logic-coq", "sha": "70dfa5fd4e006a246eaca04998086758f8440947", "save_path": "github-repos/coq/rahulghangas-Prop-Logic-coq", "path": "github-repos/coq/rahulghangas-Prop-Logic-coq/Prop-Logic-coq-70dfa5fd4e006a246eaca04998086758f8440947/f.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389113, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7203202533062225}}
{"text": "(* Bibliotecas importadas *)\n\nRequire Import Arith.\n\n\n(* Definição indutiva dos termos de L0 *)\n\nInductive term :=\n | zero   : term\n | succ   : term -> term\n | true   : term\n | false  : term\n | iszero : term -> term\n | pred   : term -> term\n | ifte   : term -> term -> term -> term \n.\n\n(* Definição indutiva da propriedade de ser um número *)\n\nInductive nv : term -> Prop :=\n | zeroNum : nv zero\n | succNum : forall n, (nv n) -> (nv (succ n))\n.\n\n(* Definição indutiva de valor : números OU booleanos *)\n\nInductive value : term -> Prop :=\n | trueVal  : value true\n | falseVal : value false\n | numVal   : forall n, (nv n) -> (value n)\n.\n\n(* Testando termos *)\nCheck ifte false zero (succ zero).\n\n(* Testando valores do tipo termo *)\nCheck value (iszero true).\n\n(* Provando uma propriedade *)\nTheorem teste1 : value (succ zero).\nProof.\nconstructor 3.\nconstructor 2.\nconstructor 1.\nQed.\n\n(* Provando uma propriedade 2 *)\nTheorem teste2 : value (succ zero).\nProof.\napply numVal.\napply succNum.\napply zeroNum.\nQed.\n\n\n(* Provando uma propriedade negada *)\nLemma teste : ~ value (iszero true).\nProof.\nunfold not.\nintro H.\ninversion H.\nsubst.\ninversion H0.\nQed.\n\n\n\n\n\n\n\n(*****************************************************************)\n\n\n\n\n\n\n(* Definição da semântica operacional *)\nInductive step : term -> term -> Prop :=\n | e_iftrue     : forall t2 t3,        step (ifte true  t2 t3) t2\n | e_iffalse    : forall t2 t3,        step (ifte false t2 t3) t3\n | e_if         : forall t1 t2 t3 t1', (step t1 t1') -> step (ifte t1 t2 t3) (ifte t1' t2 t3)\n | e_succ       : forall t t',         step t t' -> step (succ t) (succ t')\n | e_predzero   :                      step (pred zero) zero\n | e_predsucc   : forall t,  (nv t) -> step (pred (succ t)) t\n | e_pred       : forall t t',         step t t' -> step (pred t) (pred t')\n | e_iszerozero :                      step (iszero zero) true\n | e_iszerosucc : forall t,  (nv t) -> step (iszero (succ t)) false\n | e_iszero     : forall t t',         step t t' -> step (iszero t) (iszero t')\n.\n\n(* Definição de forma normal *)\n\nDefinition NF (t:term) : Prop := forall t', not (step t t').\n\n\n\n\n\n(*****************************************************************)\n\n\n\n(* Exercício : TODO NV É FORMA NORMAL *)\nTheorem nvNF : forall (t:term), nv t -> NF t.\nProof.\ninduction t.\nintro. unfold NF. intro. unfold not. intro. inversion H0. (* zero *)  \nintro. inversion H. subst. apply IHt in H1. unfold NF in H1.  intro. unfold not. intro. inversion H0. subst. unfold not in H1. apply (H1 t'0) in H3. assumption. (* succ *) \nintro. unfold NF. intro. intro. inversion H0. (* true *) \nintro. unfold NF. intro. intro. inversion H0. (* false *)\nintro. inversion H. (* iszero *)\nintro. inversion H. (* pred *)\nintro. inversion H. (* ifte *)\nQed.\n\n\n\n(* Exercício : TODO VALOR É FORMA NORMAL *)\n\nTheorem valueNF : forall (t:term), value t -> NF t.\nProof.\nintro. \nintro. \ninduction H.\n  (* H=true *)\n  unfold NF.\n  intro.\n  unfold not.\n  intro.\n  inversion H.\n  (* H=false *)\n  unfold NF.\n  intro.\n  unfold not.\n  intro.\n  inversion H.\n  (* H=nv *)\n  apply nvNF.\n  assumption.\nQed.\n\n\n\n(* DETERMINISMO *)\n\nTheorem determinismo : forall t t' t'', (step t t') -> (step t t'') -> (t' = t'').\nProof.\ninduction t.\n(* zero *)\nintros. inversion H.\n(* succ *) \nintros.  inversion H. inversion H0. subst. assert (t'0 = t'1). apply (IHt t'0 t'1 H2 H5). apply f_equal. assumption.\n(* true *)\nintros. inversion H.\n(* false *)\nintros. inversion H.\n(* iszero *)\n\nintros. inversion H. subst. inversion H0. reflexivity. inversion H2. \ninversion H0.  subst. discriminate H5. reflexivity. subst. \napply succNum in H2. apply nvNF in H2. unfold NF in H2. unfold not in H2. apply H2 in H5. exfalso. assumption.\ninversion H0.  subst.  inversion H2. subst. apply succNum in H5. apply nvNF in H5. unfold NF in H5. unfold not in H5. exfalso. apply (H5 t'0 H2). subst. apply f_equal. apply (IHt t'0 t'1 H2 H5).\n\n\nintros. inversion H. subst. inversion H0. reflexivity. inversion H2. \ninversion H0.  subst. discriminate H5. subst. injection H4. intro. symmetry.  assumption.  \nsubst. \napply succNum in H2. apply nvNF in H2. unfold NF in H2. unfold not in H2. apply H2 in H5. exfalso. assumption.\ninversion H0.  subst.  inversion H2. subst. apply succNum in H5. apply nvNF in H5. unfold NF in H5. unfold not in H5. exfalso. apply (H5 t'0 H2). subst. apply f_equal. apply (IHt t'0 t'1 H2 H5).\n\n\nintros. \ninversion H. subst. inversion H0. subst. reflexivity. inversion H5.\n\ninversion H0. subst. discriminate. subst. assumption. subst. inversion H9. subst. inversion H0. subst. inversion H5. subst. inversion H5. subst. assert (t1'=t1'0). apply IHt1. assumption. assumption. rewrite H1. reflexivity.\n\nQed.\n\nInductive type :=\n | tBool : type\n | tNat  : type\n.\n\nInductive hasType : term -> type -> Prop :=\n | t_true   :                                         hasType true       tBool\n | t_false  :                                         hasType false      tBool\n | t_zero   :                                         hasType zero       tNat\n | t_succ   : forall t,           hasType t tNat   -> hasType (succ t)   tNat\n | t_pred   : forall t,           hasType t tNat   -> hasType (pred t)   tNat\n | t_iszero : forall t,           hasType t tNat   -> hasType (iszero t) tBool\n | t_ifte   : forall t1 t2 t3 ty, hasType t1 tBool -> \n                                  hasType t2 ty    ->\n                                  hasType t3 ty    -> hasType (ifte t1 t2 t3) ty\n.\n\nTheorem questao2a : hasType (ifte (iszero (succ (succ zero))) (succ zero) zero) tNat.\nProof.\napply t_ifte.\napply t_iszero.\napply t_succ.\napply t_succ.\napply t_zero.\napply t_succ.\napply t_zero.\napply t_zero.\nQed.\n\nTheorem questao2b : step (ifte (iszero (succ (succ zero))) (succ zero) zero)\n                       (ifte false (succ zero) zero).\nProof.\napply e_if.\napply e_iszerosucc.\napply succNum.\napply zeroNum.\nQed.\n\nTheorem questao2c : ~ (step (ifte (iszero (succ (succ zero))) (succ zero) zero) zero).\nProof.\nunfold not.\nintro.\ninversion H.\nQed.\n\nTheorem questao2d : ~ forall t : term, value t.\nProof.\nunfold not.\nintros.\nAdmitted.\n\nTheorem questao2e : forall t : term, (value t) \\/ ~(value t).\nProof.\nintros.\nunfold not.\ninduction t.\n  (* zero *)\n  left. apply numVal. apply zeroNum.\n  (* succ t *)\n  inversion IHt.\n  inversion H.\n  (* value t*)\n    (* succ true *)  \n    subst. right. intro. inversion H0. subst. inversion H1. subst. inversion H3.\n    (* succ false *)\n    subst. right. intro. inversion H0. subst. inversion H1. subst. inversion H3.\n    (* succ nv *)\n    subst. left. apply numVal. apply succNum. assumption.\n  (* value t -> False *)\n  right. intro. apply H. apply numVal. inversion H0. subst. inversion H1. subst. assumption.\n  (* true *)\n  left. apply trueVal.\n  (* false *)\n  left. apply falseVal.\n  (* iszero t *)\n  right. intro. inversion H. inversion H0.\n  (* pred t *)\n  right. intro. inversion H. inversion H0.\n  (* ifte t1 t2 t3 *)\n  right. intro. inversion H. inversion H0.\nQed.\n\nTheorem unicidade_de_tipos : forall t, forall T1 T2 : type, (hasType t T1) -> (hasType t T2) -> T1 = T2.\nProof.\nintros.\ninduction H.\n  (* true *)\n  inversion H0.\n  reflexivity.\n  (* false *)\n  inversion H0.\n  reflexivity.\n  (* zero *)\n  inversion H0.\n  reflexivity.\n  (* succ t *)\n  inversion H0.\n  reflexivity.\n  (* pred t *)\n  inversion H0.\n  reflexivity.\n  (* iszero t *)\n  inversion H0.\n  reflexivity.\n  (* ifte t1 t2 t3 *)\n  inversion H0.\n  subst.\n  apply IHhasType2.\n  assumption.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "prlanzarin", "repo": "coq-test", "sha": "6b87a143b1e48ed6c5058eba74e140471efcd6e3", "save_path": "github-repos/coq/prlanzarin-coq-test", "path": "github-repos/coq/prlanzarin-coq-test/coq-test-6b87a143b1e48ed6c5058eba74e140471efcd6e3/typesystem/marcos_linguagem-de-termos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7203202518910466}}
{"text": "Parameter A : Type.\nParameter eq_bool : A -> A -> bool.\nAxiom eq_bool_true : forall (x y:A), eq_bool x y = true  -> x = y.\nAxiom eq_bool_false: forall (x y:A), eq_bool x y = false -> x <> y.\n\n\n(* convoy pattern *)\nDefinition test (x y:A) : {x = y} + {x <> y} :=\n    match eq_bool x y as b return eq_bool x y = b -> {x = y} + {x <> y} with\n    | true  => fun p    => left  (eq_bool_true  x y p)\n    | false => fun p    => right (eq_bool_false x y p)\n    end (eq_refl (eq_bool x y)).\n\n(* we do not need to use the convoy pattern *) \n\nDefinition test_bool (b:bool) : {b = true} + {b = false} :=\n    match b with\n    | true  => left  (eq_refl true)\n    | false => right (eq_refl false)\n    end.\n\n(* now do not pattern match on boolean values, but on proofs instead *)\n\nDefinition test' (x y:A) : {x = y} + {x <> y} :=\n    match test_bool (eq_bool x y) with\n    | left  p   => left  (eq_bool_true  x y p)\n    | right p   => right (eq_bool_false x y p)\n    end.\n\n\n(* functions such as test and test' are always 'correct' *)\nDefinition correct (f:forall (x y:A), {x = y} + {x <> y}) : Prop := \n    forall (x y:A),\n        ( (exists p, f x y = left p ) <-> x = y ) /\\\n        ( (exists p, f x y = right p) <-> x <> y) . \n\nLemma always_correct : forall (f:forall (x y:A), {x = y} + {x <> y}), correct f.\nProof.\n    intros f. unfold correct. intros x y. split.\n    - split.\n        + intros [H _]. exact H.\n        + intros H. destruct (f x y) as [H'|H']. \n            { exists H'. reflexivity. }\n            { exfalso. apply H'. exact H. }\n    - split.\n        + intros [H _]. exact H.\n        + intros H. destruct (f x y) as [H'|H'].\n            { exfalso. apply H. exact H'. }\n            { exists H'. reflexivity. }\nQed.\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/cat/ConvoyPattern3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.81047890180374, "lm_q1q2_score": 0.7203202485301444}}
{"text": "Require Import Setoid. \n\n(** Results about lexicographic order *)\n\nNotation lex x y := \n  (match x with \n    | Eq => y\n    | c => c\n  end). \n\nSection t. \n  Variable A B: Type. \n  Variable f : A -> A -> comparison.\n  Variable g : B -> B -> comparison.\n  Hypothesis Hf_sym: forall x y,  f x y = CompOpp (f y x). \n  Hypothesis Hf_trans:forall c x y z,  f x y = c -> f y z = c -> f x z = c. \n  Hypothesis Hg_sym: forall x y,  g x y = CompOpp (g y x). \n  Hypothesis Hg_trans:forall c x y z,  g x y = c -> g y z = c -> g x z = c. \n\n  Hint Resolve Hf_sym Hf_trans Hg_sym Hg_trans : lex. \n  Lemma lex_sym x1 x2 y1 y2: lex (f x1 x2) (g y1 y2) = CompOpp (lex (f x2 x1) (g y2 y1)).\n  Proof. \n    repeat match goal with \n               |- context [f ?x ?y] => case_eq (f x y); intros ?\n             | |- context [f ?x ?y] => case_eq (g x y); intros ?\n             | H : f ?x ?y = _, H' : f ?y ?x = _ |- _ => \n               rewrite Hf_sym, H' in H; simpl in H; clear H'; try discriminate\n           end; simpl; try eauto with lex. \n  Qed.\n\n  Lemma CompOpp_move x y : CompOpp x = y <-> x = CompOpp y. \n    destruct x; destruct y; simpl; intuition discriminate.  \n  Qed. \n  \n  Lemma Hf_sym' c x y : f x y = CompOpp c -> f y x = c. \n  Proof.   \n    intros. rewrite Hf_sym. rewrite CompOpp_move. assumption.\n  Qed. \n\n  Hint Resolve Hf_sym' : lex. \n\n  Lemma lex_trans c x1 x2 x3 y1 y2 y3: \n    lex (f x1 x2) (g y1 y2) = c -> \n    lex (f x2 x3) (g y2 y3) = c -> \n    lex (f x1 x3) (g y1 y3) = c.\n  Proof. \n    Ltac finish :=\n      repeat match goal with \n               | H : ?x = ?y, H' : ?x = ?z |- _ => constr_eq y z; clear H'\n               | H : ?x = ?y, H' : ?x = ?z |- _ => \n                 rewrite H in H'; discriminate\n             end; simpl; try eauto with lex. \n\n    repeat match goal with \n               |- context [f ?x ?y] => case_eq (f x y); intros ?\n             | |- context [f ?x ?y] => case_eq (g x y); intros ?\n             | H : f ?x ?y = _, H' : f ?y ?x = _ |- _ => \n               rewrite Hf_sym, H' in H; simpl in H; clear H'; try discriminate\n             | H : f ?x ?y = _, H' : f ?y ?z = _ |- _ => \n               pose proof (Hf_trans _ _ _ _ H H'); clear H H'\n           end; finish. \n\n    assert (f x2 x3 = Eq) by eauto with lex; finish. \n    assert (f x1 x2 = Gt) by eauto with lex; finish. \n    assert (f x2 x3 = Eq) by eauto with lex; finish. \n    assert (f x1 x2 = Lt) by eauto with lex; finish. \n    assert (f x1 x2 = Eq) by eauto with lex; finish. \n    assert (f x2 x3 = Gt) by eauto with lex; finish. \n    congruence. \n    assert (f x1 x2 = Eq) by eauto with lex; finish. \n    assert (f x2 x3 = Lt) by eauto with lex; finish. \n    congruence. \n  Qed. \nEnd t. \n", "meta": {"author": "braibant", "repo": "Synthesis", "sha": "922982aaddb8a7a16101ff304c45d24a6265dc2e", "save_path": "github-repos/coq/braibant-Synthesis", "path": "github-repos/coq/braibant-Synthesis/Synthesis-922982aaddb8a7a16101ff304c45d24a6265dc2e/src/Compare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.720315182707565}}
{"text": "Require Export VST.floyd.sublist.\nRequire Export Integers.\nRequire Export Coqlib.\nRequire Export List. Import ListNotations.\nRequire Export aes.sbox.\n\n(* substitute b for its counterpart in the sbox *)\nDefinition look_sbox (b: int) : int :=\n  (* All possible values of b are covered in the sbox so the default should never be returned *)\n  Int.repr (Znth (Int.unsigned b) sbox 0).\n\n(* substitute b for its counterpart in the inverse sbox *)\nDefinition look_inv_sbox (b: int) : int :=\n  Int.repr (Znth (Int.unsigned b) inv_sbox 0).\n\n(********************* GF(256) arithmetic *******************)\n\n(* xtime operation from section 4.2.1. Corresponds to multiplying by 2 in GF(256) *)\nDefinition xtime (b: int) : int :=\n  let b' := Int.modu (Int.shl b (Int.one)) (Int.repr 256) in (* shift left by one, mod 256 *)\n  let c_1b := Int.repr 27 in (* 0x1b *)\n  let c_80 := Int.repr 128 in (* 0x80 *)\n  (* test if highest bit of b is one. If so, then XOR b' with 0x1b, otherwise return b' *)\n  if Int.eq (Int.and b c_80) Int.zero then b'\n  else Int.xor b' c_1b.\n\n(* Finite field multiplication using xtime operation and xor for finite field addition\n * (Russian peasant multiplication), not described directly but suggested in section 4.2.1. *)\n\n(* Repeatedly double b using xtime as per Russian peasant multiplication. Add b to accumulator\n * if there is a \"remainder,\" i.e., the tested bit of a is 1 *)\nDefinition ff_checkbit (a b : int) (acc : int) : int :=\n  (* if lowest bit of a is one, add (xor) b to acc. Otherwise do nothing *)\n  if Int.eq (Int.and a Int.one) Int.zero then acc\n  else Int.xor acc b.\n\nFixpoint xtime_test (a b : int) (acc : int) (shifts : nat) : int :=\n  if Int.eq a Int.zero then acc (* if a or b are zero, nothing to do *)\n  else if Int.eq b Int.zero then acc\n  else\n    (* check lowest bit of a, add b to acc if it is positive. Shift a\n     * right for next iteration unless we're finished *)\n    match shifts with\n    | S n =>\n      let acc' := ff_checkbit a b acc in\n      (* shift a right and double b *)\n      let a' := Int.shru a Int.one in\n      let b' := xtime b in\n      xtime_test a' b' acc' n\n    | O => acc\n    end.\n\nDefinition ff_mult (a b : int) : int := xtime_test a b Int.zero 8%nat.\n\n(******************************************************************************************)\n\n\n(* Defining words and state as they are considered in the specification, using tuples\n * to enforce the length requirement -- a word is 4 bytes, while a state is 4 words,\n * illustrated as 4 rows of 4 bytes *)\nDefinition word := (int * int * int * int) % type.\nDefinition state := (word * word * word * word) % type.\nDefinition block := state%type. (* Used synonymously with state in the spec, aliased here for readability *)\n\n(* SubBytes() transformation described in section 5.1.1 *)\nDefinition sub_word (w: word) : word :=\n  match w with (b1, b2, b3, b4) => (look_sbox b1, look_sbox b2, look_sbox b3, look_sbox b4) end.\nDefinition SubBytes (s: state) : state :=\n  match s with (w1, w2, w3, w4) => (sub_word w1, sub_word w2, sub_word w3, sub_word w4) end.\n\n(* ShiftRows() transformation described in section 5.1.2 *)\nDefinition ShiftRows (s : state) : state :=\n  match s with\n  ((b11, b12, b13, b14),\n   (b21, b22, b23, b24),\n   (b31, b32, b33, b34),\n   (b41, b42, b43, b44)) =>\n\n  ((b11, b12, b13, b14),\n   (b22, b23, b24, b21),\n   (b33, b34, b31, b32),\n   (b44, b41, b42, b43))\n  end.\n\n(* MixColumns() transformation described in section 5.1.3 *)\n\nDefinition transform_column (col: word) : word :=\n  match col with (b1, b2, b3, b4) =>\n    let two := Int.repr 2 in\n    let three := Int.repr 3 in\n    (* (2*b1)^(3*b2)^b3^b4 *)\n    let c0 := Int.xor (Int.xor (ff_mult two b1) (ff_mult three b2)) (Int.xor b3 b4) in\n    (* b1^(2*b2)^(3*b3)^b4 *)\n    let c1 := Int.xor (Int.xor b1 (ff_mult two b2)) (Int.xor (ff_mult three b3) b4) in\n    (* b1^b2^(2*b3)^(3*b4)*)\n    let c2 := Int.xor (Int.xor b1 b2) (Int.xor (ff_mult two b3) (ff_mult three b4)) in\n    (* (3*b1)^b2^b3^(2*b4)*)\n    let c3 := Int.xor (Int.xor (ff_mult three b1) b2) (Int.xor b3 (ff_mult two b4)) in\n    (c0, c1, c2, c3)\n  end.\n\n(* lets us treat state by columns rather than rows *)\nDefinition transpose (s: state) : state :=\n  match s with\n   ((b11, b12, b13, b14),\n    (b21, b22, b23, b24),\n    (b31, b32, b33, b34),\n    (b41, b42, b43, b44)) =>\n\n   ((b11, b21, b31, b41),\n    (b12, b22, b32, b42),\n    (b13, b23, b33, b43),\n    (b14, b24, b34, b44))\nend.\n\n(* apply column transformation to each column in the state *)\nDefinition MixColumns (s: state) : state :=\n  let cols := transpose s in\n  match cols with (c1, c2, c3, c4) =>\n    transpose (transform_column c1, transform_column c2, transform_column c3, transform_column c4)\n  end.\n\n(* Key expansion functions, section 5.2 *)\n\n(* SubWord function from section 5.2: apply S-box to each byte in a word *)\nDefinition SubWord (w: word) : word :=\n  match w with (b1, b2, b3, b4) => (look_sbox b1, look_sbox b2, look_sbox b3, look_sbox b4) end.\n\n(* RotWord function from section 5.2: rotate bytes left, wrapping around *)\nDefinition RotWord (w: word) : word :=\n  match w with (b1, b2, b3, b4) => (b2, b3, b4, b1) end.\n\n(* round constant (RCon) array, described in section 5.2 and explicitly written\n * out in appendix A.3 (256-bit key expansion example) *)\nDefinition RCon : list word := [\n  (* 0x01000000 *) (Int.repr 1, Int.zero, Int.zero, Int.zero);\n  (* 0x02000000 *) (Int.repr 2, Int.zero, Int.zero, Int.zero);\n  (* 0x04000000 *) (Int.repr 4, Int.zero, Int.zero, Int.zero);\n  (* 0x08000000 *) (Int.repr 8, Int.zero, Int.zero, Int.zero);\n  (* 0x10000000 *) (Int.repr 16, Int.zero, Int.zero, Int.zero);\n  (* 0x20000000 *) (Int.repr 32, Int.zero, Int.zero, Int.zero);\n  (* 0x40000000 *) (Int.repr 64, Int.zero, Int.zero, Int.zero)\n].\n\n(* For AES-256, figure 4 fixes the key length in words at 8 and the number\n * of rounds at 14 *)\nDefinition Nk := 8. (* number of words in key *)\nDefinition Nr := 14. (* number of cipher rounds *)\nDefinition Nb := 4. (* number of words in a block (state) *)\n\n(* xor two words together, i.e., apply xor byte by byte *)\nDefinition xor_word (w1 w2 : word) : word :=\n  match w1, w2 with (b1, b2, b3, b4), (b1', b2', b3', b4') =>\n    (Int.xor b1 b1', Int.xor b2 b2', Int.xor b3 b3', Int.xor b4 b4')\n  end.\n\n(* Expanded key is Nb*(Nr+1) words, or Nr+1 blocks *)\nDefinition extended_key_blocks := Nr+1.\n\n(* Based on Figure 11 and diagram in appendex A.3 *)\n\n(* Note that \"even\" and \"odd\" are if you start counting blocks at 1, rather than 0 *)\n(* b1 and b2 are the two blocks generated before this round. *)\nDefinition odd_round (b1 b2 : block) (rcon: word) : block :=\n  match b1, b2 with (w1, w2, w3, w4), (_, _, _, w8) =>\n    let w1' := xor_word w1 (xor_word (SubWord (RotWord w8)) rcon) in\n    let w2' := xor_word w2 w1' in\n    let w3' := xor_word w3 w2' in\n    let w4' := xor_word w4 w3' in\n    (w1', w2', w3', w4')\n  end.\nDefinition even_round (b1 b2: block) : block :=\n  match b1, b2 with (w1, w2, w3, w4), (_, _, _, w8) =>\n    let w1' := xor_word w1 (SubWord w8) in\n    let w2' := xor_word w2 w1' in\n    let w3' := xor_word w3 w2' in\n    let w4' := xor_word w4 w3' in\n    (w1', w2', w3', w4')\n  end.\n\nFixpoint grow_key (b1 b2: block) (rcs: list word) : list block :=\n  match rcs with\n  | rc :: [] =>\n    (* for the last round constant, only apply an odd round *)\n    (odd_round b1 b2 rc) :: []\n  | rc :: tl =>\n    (* generate a block with an odd round, use it in the next even round and keep going *)\n    let b3 := odd_round b1 b2 rc in\n\tlet b4 := even_round b2 b3 in\n\tb3 :: b4 :: (grow_key b3 b4 tl)\n  | [] => [] (* should not happen *)\n  end.\n\n(* Note that RCon list (round constants) is described in section 5.2 and its values are given in A.3.\n * k should be a list of words of length Nk. Returns a list of blocks of length Nr+1 *)\nDefinition KeyExpansion (k : list word) : list block :=\n  match k with\n  | [w1; w2; w3; w4; w5; w6; w7; w8] =>\n    let b1 := (w1, w2, w3, w4) in\n\tlet b2 := (w5, w6, w7, w8) in\n\tb1 :: b2 :: (grow_key b1 b2 RCon)\n  | l => [] (* should not happen *)\n  end.\n\n(* AddRoundKey() described in section 5.1.4: it uses a block from the expanded key, xoring\n * each word from the expanded key block with a column from the state *)\nDefinition AddRoundKey (s : state) (kb : block) : state :=\n  let cols := transpose s in\n  match cols, kb with (c1,c2,c3,c4), (k1,k2,k3,k4) =>\n    transpose (xor_word c1 k1, xor_word c2 k2, xor_word c3 k3, xor_word c4 k4)\n  end.\n\n(* Based on figure 5, description of the cipher *)\nDefinition round (s : state) (kb: block) : state :=\n  AddRoundKey (MixColumns (ShiftRows (SubBytes s))) kb.\n(* omits mix columns step *)\nDefinition last_round (s : state) (kb : block) : state :=\n  AddRoundKey (ShiftRows (SubBytes s)) kb.\n\n(* Applies cipher rounds given an expanded key *)\nFixpoint apply_rounds (s : state) (ek: list block) : state :=\n  match ek with\n  | rk :: [] => last_round s rk (* last round *)\n  | rk :: tl => apply_rounds (round s rk) tl\n  | [] => s (* should not happen *)\n  end.\n\n(* exp_key should be length Nr+1 blocks, produced by applying KeyExpansion on a valid key. *)\nDefinition Cipher (exp_key : list block) (init : state) : state :=\n  match exp_key with\n  | k1 :: tl =>\n    let r1 := AddRoundKey init k1 in\n\tapply_rounds r1 tl\n  | [] => init (* should not happen *)\n  end.\n\n(* Inverse cipher and inverse operations -- section 5.3 *)\n\n(* InvShiftRows in section 5.3.1 *)\nDefinition InvShiftRows (s: state) : state :=\n  match s with\n    ((b11, b12, b13, b14),\n     (b21, b22, b23, b24),\n\t (b31, b32, b33, b34),\n\t (b41, b42, b43, b44)) =>\n\t\n\t((b11, b12, b13, b14),\n\t (b24, b21, b22, b23),\n\t (b33, b34, b31, b32),\n\t (b42, b43, b44, b41))\n  end.\n\n(* InvSubBytes in section 5.3.2 *)\nDefinition inv_sub_word (w: word) : word :=\n  match w with (b1, b2, b3, b4) =>\n    (look_inv_sbox b1, look_inv_sbox b2, look_inv_sbox b3, look_inv_sbox b4)\n  end.\n\nDefinition InvSubBytes (s : state) : state :=\n  match s with (w1, w2, w3, w4) =>\n    (inv_sub_word w1, inv_sub_word w2, inv_sub_word w3, inv_sub_word w4)\n  end.\n\n(* InvMixColumns in 5.3.3 *)\nDefinition inv_transform_column (w: word) : word :=\n  let c_e := Int.repr 14 in (* 0x0e *)\n  let c_b := Int.repr 11 in (* 0x0b *)\n  let c_d := Int.repr 13 in (* 0x0d *)\n  let c_9 := Int.repr 9 in (* 0x09 *)\n  match w with (b1, b2, b3, b4) =>\n    (* (0x0e * b1) ^ (0x0b * b2) ^ (0x0d * b3) ^ (0x09 * b4) *)\n    let b1' := Int.xor (Int.xor (ff_mult c_e b1) (ff_mult c_b b2)) (Int.xor (ff_mult c_d b3) (ff_mult c_9 b4)) in\n    (* (0x09 * b1) ^ (0x0e * b2) ^ (0x0b * b3) ^ (0x0d * b4) *)\n    let b2' := Int.xor (Int.xor (ff_mult c_9 b1) (ff_mult c_e b2)) (Int.xor (ff_mult c_b b3) (ff_mult c_d b4)) in\n    (* (0x0d * b1) ^ (0x09 * b2) ^ (0x0e * b3) ^ (0x0b * b4) *)\n    let b3' := Int.xor (Int.xor (ff_mult c_d b1) (ff_mult c_9 b2)) (Int.xor (ff_mult c_e b3) (ff_mult c_b b4)) in\n    (* (0x0b * b1) ^ (0x0d * b2) ^ (0x09 * b3) ^ (0x0e * b4) *)\n    let b4' := Int.xor (Int.xor (ff_mult c_b b1) (ff_mult c_d b2)) (Int.xor (ff_mult c_9 b3) (ff_mult c_e b4)) in\n    (b1', b2', b3', b4')\n  end.\n\nDefinition InvMixColumns (s : state) : state :=\n  let cols := transpose s in\n  match cols with (c1, c2, c3, c4) =>\n    transpose (inv_transform_column c1, inv_transform_column c2, inv_transform_column c3, inv_transform_column c4)\n  end.\n\n(* applies InvMixColumns to all members of expanded key but the last *)\nFixpoint grow_inv_key (ek : list block) : list block :=\n  match ek with\n  | rk :: [] => rk :: [] (* don't do anything to last one *)\n  | rk :: tl => InvMixColumns rk :: grow_inv_key tl\n  | [] => [] (* should not happen *)\n  end.\n\n(* Inverse key expansion briefly described at end of figure 15. k should be of length Nk. *)\nDefinition InverseKeyExpansion (k : list word) : list block :=\n  let exp_key := KeyExpansion k in\n  match exp_key with\n  (* don't apply inv mix columns to first round key either *)\n  | k1 :: tl => k1 :: grow_inv_key tl\n  | ek => [] (* should not happen *)\n  end.\n\n(* Inverse cipher described in figure 15 *)\nDefinition inv_round (s : state) (kb : block) : state :=\n  AddRoundKey (InvMixColumns (InvShiftRows (InvSubBytes s))) kb.\n(* omits mix columns *)\nDefinition inv_last_round (s : state) (kb : block) : state :=\n  AddRoundKey (InvShiftRows (InvSubBytes s)) kb.\n\nFixpoint apply_inv_rounds (s: state) (ek: list block) : state :=\n  match ek with\n  | kb :: [] => inv_last_round s kb\n  | kb :: tl => apply_inv_rounds (inv_round s kb) tl\n  | [] => s (* should not happen *)\n  end.\n\n(* exp_key should be length Nr+1 blocks, produced by applying InverseKeyExpansion on a valid\n * key and reversing the result, since the round keys are supposed to be applied starting with\n * the last. (We pass the key in this way for simplifying verification, since the implementation's\n * key expansion process also reverses the key, whereas the specification reverses it during the\n * decryption process) *)\nDefinition EqInvCipher (exp_key: list block) (init: state) : state :=\n  match exp_key with\n  | kb :: tl => apply_inv_rounds (AddRoundKey init kb) tl\n  | l => init (* should not happen *)\n  end.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/aes/spec_AES256_HL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.72031518134101}}
{"text": "Require Import Coq.Arith.PeanoNat.\nOpen Scope nat_scope.\n\nRequire Import Monad.\nImport Notations.\nOpen Scope monad_scope.\n\n\nRequire Import List.\nImport ListNotations.\nOpen Scope list_scope.\n\nRequire Export Coq.Sets.Ensembles.\nRequire Import Setoid.\n\n\n(** * Decidable equality\n\nEquality is decidable for a type [A] if there is a procedure such that, for any\ntwo elements [a b : A], produces either (1) a proof that [a] equals [b], or (2)\na proof that [a] does not equal [b].\n\nEquality is not decidable for every type [A]; for example, the type of real\nnumbers is not decidable, but all finite types and most simple inductive types\nare decidable.\n\nTypes that are decidable can be given instances of the class [eq_dec A]. When\nsuch a type is decidable, the expression [a =? b] is a boolean that can be used\ne.g. in an [if] statement: [if a =? b then X else Y]. *)\nClass eq_dec A := { Dec : forall (a b : A), {a = b} + {a <> b} }.\nDefinition eqb {A} `{eq_dec A} (a b : A) : bool :=\n  if Dec a b then true else false.\nInfix \"=?\" := eqb.\n\n(** ** Some lemmas about decidable equality *)\nLemma eqb_eq : forall A `{eq_dec A} (a : A), a =? a = true.\nProof. intros. unfold eqb. destruct (Dec a a); auto. Qed.\nLemma eqb_eq' : forall A `{eq_dec A} (a b : A), a = b -> (a =? b) = true.\nProof. intros. unfold eqb. destruct (Dec a b); auto. Qed.\nLemma eqb_neq : forall A `{eq_dec A} (a b : A), a <> b -> a =? b = false.\nProof. intros. unfold eqb. destruct (Dec a b); auto. contradiction. Qed.\n\n(** ** Instances of decidable equality *)\nInstance eq_dec_bool : eq_dec bool.\nProof.\n  split. intros [ | ] [ | ]; try (right; inversion 1; fail); try (left; auto; fail).\nDefined.\n\nInstance nat_eq_dec : eq_dec nat.\nProof.\n  constructor.\n  intros x;\n  induction x as [ | x]; intros [ | y]; auto.\n  destruct (IHx y) as [IHxy | IHxy]; subst; auto.\nDefined.\n\nInstance prod_eq_dec {A B} `{eq_dec A} `{eq_dec B} : eq_dec (A*B).\nProof.\n  split. intros [a b] [a' b'].\n  destruct (Dec a a'); destruct (Dec b b');\n    subst; auto;\n    right; inversion 1; contradiction.\nDefined.\n\nInstance option_eq_dec {A} `{eq_dec A} : eq_dec (option A).\nProof.\n  constructor.\n  intros [a | ] [b | ];\n    try (left; reflexivity);\n    try (right; discriminate).\n  destruct (Dec a b); subst;\n    try (left; reflexivity);\n    try (right; inversion 1; contradiction).\nDefined.\n\n(** ** Decidable list inclusion\n\nIf a type [A] is decidable, then we can also decide whether an element [a] is an\nelement of a list [ls] of [A]s. This is written [a ∈? ls]. *)\n\nFixpoint in_list_dec {A} `{eq_dec A} (a : A) (ls : list A) : bool :=\n  match ls with\n  | [] => false\n  | b :: ls' => if a =? b then true else in_list_dec a ls'\n  end.\nNotation \"a ∈ ls\" := (in_list_dec a ls = true) (no associativity, at level 90).\nNotation \"a ∈? ls\" := (in_list_dec a ls) (no associativity, at level 90).\n\n\n(** * Snoc/tail lists\n\nA tail_list is just an ordinary list that is interpreted \"backward\". In this\ndevelopment we use it for traces where a trace [t ▶ e] consists of the trace [t]\nfollowed by the event [e].\n\n*)\n\nInductive tail_list (A : Type) :=\n| t_empty : tail_list A\n| t_next : tail_list A -> A -> tail_list A.\nArguments t_empty {A}.\nArguments t_next {A}.\nInfix \"▶\" := t_next (left associativity, at level 73).\n\n\n\n(** * Ensemble notation\n\nAn [Ensemble A] in Coq represents a mathematical set with elements of the type\n[A]. [Ensemble]s are defined in the Coq standard library but are not computable,\nso we introduce the standard unicode notations below, including [X == Y] to mean\nthat the sets [X] and [Y] have the same elements.\n\n\n *)\nModule EnsembleNotation.\n  Notation \"x ∈ X\" := (In _ X x) : ensemble_scope.\n  Notation \"X ∪ Y\" := (Union _ X Y) (at level 50) : ensemble_scope.\n  Notation \"X ∩ Y\" := (Intersection _ X Y) (at level 50) : ensemble_scope.\n  Notation \"X ⊥ Y\" := (Disjoint _ X Y) (at level 90) : ensemble_scope.\n  Notation \"X ∖ Y\" := (Setminus _ X Y) (at level 40) : ensemble_scope.\n  Notation \"X ⊆ Y\" := (Included _ X Y) (at level 80) : ensemble_scope.\n  Notation \"X == Y\" := (Same_set _ X Y) (at level 90) : ensemble_scope.\n  Notation \"∅\" := (Empty_set _) : ensemble_scope.\n  Notation \"⊤\" := (fun _ => True) : ensemble_scope.\n  Definition singleton {X} (x : X) : Ensemble X := Singleton X x.\n  Notation \"x ∉ X\" := (~(In _ X x)) (at level 70) : ensemble_scope.\n\n  (** ** Decidable set inclusion *)\n  Open Scope ensemble_scope.\n  Class in_dec {Z} (X : Ensemble Z) := {In_Dec : forall (x:Z), {x ∈ X} + {~(x ∈ X)}}.\n  Arguments In_Dec {Z} X {in_dec} : rename.\n  Notation \"x ∈? X\" := (In_Dec X x) : ensemble_scope.\n\n  Instance in_dec_singleton {X} `{eq_dec X} {x : X} : in_dec (singleton x).\n  Proof.\n    constructor.\n    intros y.\n    destruct (Dec x y).\n    - left. subst. constructor.\n    - right. inversion 1; contradiction.\n  Defined.\n  Instance in_dec_union : forall A (X Y : Ensemble A), in_dec X -> in_dec Y -> in_dec (X ∪ Y).\n  Proof.\n    intros A X Y HX HY.\n    constructor; intros z.\n    destruct (@In_Dec _ X HX z); [ left; auto with sets | ].\n    destruct (@In_Dec _ Y HY z); [ left; auto with sets | ].\n    right. intros Hz.\n    inversion Hz; contradiction.\n  Qed.\n  Instance in_dec_intersect : forall A (X Y : Ensemble A), in_dec X -> in_dec Y -> in_dec (X ∩ Y).\n  Proof.\n    intros A X Y HX HY.\n    constructor; intros z.\n    destruct (In_Dec X z); [ | right; inversion 1; contradiction].\n    destruct (In_Dec Y z); [ | right; inversion 1; contradiction].\n    left; auto with sets.\n  Qed.\n  Instance in_dec_setminus : forall A (X Y : Ensemble A), in_dec X -> in_dec Y -> in_dec (X ∖ Y).\n  Proof.\n    intros A X Y HX HY.\n    constructor; intros z.\n    destruct (In_Dec X z); [ | right; inversion 1; contradiction].\n    destruct (In_Dec Y z); [ right; inversion 1; contradiction |].\n    left; auto with sets.\n  Qed.\n  Instance in_dec_empty : forall A, in_dec (Empty_set A).\n  Proof.\n    intros A.\n    constructor; intros x.\n    right. inversion 1.\n  Qed.\n(*  Hint Resolve in_dec_singleton in_dec_union in_dec_intersect in_dec_setminus in_dec_singleton in_dec_empty : sets.*)\n\n  (** ** Ensembles as a setoid *)\n\n  Lemma Included_refl : forall A (X : Ensemble A), X ⊆ X.\n  Proof.\n    intros A X. intros x Hx; auto.\n  Qed.\n  Lemma Included_trans : forall A (X Y Z : Ensemble A), X ⊆ Y -> Y ⊆ Z -> X ⊆ Z.\n  Proof.\n    intros A X Y Z HXY HYZ x HX.\n    apply HYZ. apply HXY. auto.\n  Qed.\n\n  Add Parametric Relation A : (Ensemble A) (Included A)\n    reflexivity proved by (Included_refl A)\n    transitivity proved by (Included_trans A)\n    as subset_ensemble_rel.\n\n\n  Lemma Same_set_refl : forall A (X : Ensemble A), X == X.\n  Proof.\n    intros A X. split; reflexivity.\n  Qed.\n  Lemma Same_set_symm : forall A (X Y : Ensemble A), X == Y -> Y == X.\n  Proof.\n    intros A X Y [HXY HYX]. split.\n    * intros y Hy. apply HYX. auto.\n    * intros x Hx. apply HXY. auto.\n  Qed.\n  Lemma Same_set_trans : forall A (X Y Z : Ensemble A), X == Y -> Y == Z -> X == Z.\n  Proof.\n    intros A X Y Z [HXY HYX] [HYZ HZY].\n    split; transitivity Y; auto.\n  Qed.\n\n\n  Add Parametric Relation A : (Ensemble A) (Same_set A)\n    reflexivity proved by (Same_set_refl A)\n    symmetry proved by (Same_set_symm A)\n    transitivity proved by (Same_set_trans A)\n    as eq_ensemble_rel.\n\n  Add Parametric Morphism A : (Included A)\n    with signature (Same_set A) ==> (Same_set A) ==> iff as subset_mor.\n  Proof.\n    intros X Y [HXY HYX] X' Y' [HXY' HYX'].\n    split; intros H.\n    * intros y Hy. apply HXY'. apply H. apply HYX. assumption.\n    * intros x HX. apply HYX'. apply H. apply HXY. assumption.\n  Qed.\n\n  Add Parametric Morphism A : (In A)\n    with signature (Same_set A) ==> (@eq A) ==> iff as in_mor.\n  Proof.\n    intros X Y [HXY HYX] a.\n    split; intros Ha.\n    * apply HXY; auto.\n    * apply HYX; auto.\n  Qed.\n\n  Add Parametric Morphism A : (Union A)\n    with signature (Same_set A) ==> (Same_set A) ==> (Same_set A) as union_mor.\n  Proof.\n    intros X Y HXY X' Y' HXY'.\n    split.\n    * intros x Hx. inversion Hx; subst; clear Hx.\n      + left. rewrite <- HXY. auto.\n      + right. rewrite <- HXY'. auto.\n    * intros x Hx. inversion Hx; subst; clear Hx.\n      + left. rewrite HXY. auto.\n      + right. rewrite HXY'. auto.\n  Qed.\n\n  Add Parametric Morphism A : (Intersection A)\n    with signature (Same_set A) ==> (Same_set A) ==> (Same_set A) as intersection_mor.\n  Proof.\n    intros X Y HXY X' Y' HXY'.\n    split.\n    * intros x Hx. inversion Hx; subst; clear Hx.\n      split. \n      + rewrite <- HXY. auto.\n      + rewrite <- HXY'. auto.\n    * intros x Hx. inversion Hx; subst; clear Hx.\n      split.\n      + rewrite HXY. auto.\n      + rewrite HXY'. auto.\n  Qed.\n\n  Add Parametric Morphism A : (Disjoint A)\n    with signature (Same_set A) ==> (Same_set A) ==> iff as disjoint_mor.\n  Proof.\n    intros X Y HXY X' Y' HXY'.\n    split; intros [Hdisjoint]; constructor; intros x.\n    * rewrite <- HXY, <- HXY'. auto.\n    * rewrite HXY, HXY'. auto.\n  Qed.\n\n  Add Parametric Morphism A : (Setminus A)\n    with signature (Same_set A) ==> (Same_set A) ==> (Same_set A) as setminus_mor.\n  Proof.\n    intros X Y HXY X' Y' HXY'.\n    split; intros x [Hx Hx'].\n    * split; [rewrite <- HXY; auto | rewrite <- HXY'; auto].\n    * split; [rewrite HXY; auto | rewrite HXY'; auto].\n  Qed.\n\n\n\n  (** ** Helper lemmas *)\n  Lemma Setminus_in : forall {A} x (X Y : Ensemble A),\n      x ∈ X ∖ Y ->\n      x ∈ X.\n  Proof.\n    intros A x X Y H.\n    inversion H; auto.\n  Qed.\n  Lemma Setminus_not_in : forall {A} x (X Y : Ensemble A),\n      x ∈ X ∖ Y ->\n      ~(x ∈ Y).\n  Proof.\n    intros A x X Y H.\n    inversion H; auto.\n  Qed.\n  Hint Resolve Setminus_in Setminus_not_in : sets.\n\n  Lemma not_union_1 : forall {A} (x : A) X Y,\n      ~(x ∈ X ∪ Y) ->\n      ~(x ∈ X).\n  Proof.\n    intros A x X Y Hunion HX.\n    apply Hunion.\n    left.\n    assumption.\n  Qed.\n  Lemma not_union_2 : forall {A} (x : A) X Y,\n      ~(x ∈ X ∪ Y) ->\n      ~(x ∈ Y).\n  Proof.\n    intros A x X Y Hunion HX.\n    apply Hunion.\n    right.\n    assumption.\n  Qed.\n  Hint Resolve not_union_1 not_union_2 : sets.\n\n  Lemma not_in_singleton_neq : forall {A} (x y : A),\n      ~(x ∈ singleton y) <->\n      x <> y.\n  Proof.\n    intros x y. split. \n    * intros H_x_y x_y.\n      apply H_x_y.\n      subst.\n      auto with sets.\n    * intros x_neq_y.\n      inversion 1.\n      subst.\n      contradiction.\n  Qed.\n  Hint Resolve not_in_singleton_neq : sets.\n\n  Lemma not_in_setminus : forall {A} (x : A) (X Y : Ensemble A) `{in_dec _ Y},\n      x ∉ (X ∖ Y) ->\n      (x ∈ Y) \\/ x ∉ X.\n  Proof.\n    intros A x X Y decY Hin.\n    destruct (x ∈? Y).\n    - left. assumption.\n    - right. intro x_in_X.\n      apply Hin.\n      constructor; auto.\n  Qed.\n\n  Lemma in_Y_not_in_setminus_X_Y : forall {A} (x : A) (X Y : Ensemble A),\n      (x ∈ Y) ->\n      x ∉ (X ∖ Y).\n  Proof.\n    intros A x X Y HY Hsetminus.\n    inversion Hsetminus; contradiction.\n  Qed.\n\n  Lemma not_in_X_not_in_setminus_X_Y : forall {A} (x : A) (X Y : Ensemble A),\n      x ∉ X ->\n      x ∉ (X ∖ Y).\n  Proof.\n    intros A x X Y HX Hsetminus.\n    inversion Hsetminus; contradiction.\n  Qed.\n\n  Lemma not_in_union : forall {A} (x : A) X Y,\n      x ∉ X ∪ Y <->\n      x ∉ X /\\ x ∉ Y.\n  Proof.\n    intros A x X Y.\n    split.\n    - intros Hunion. split.\n      * intros HX. apply Hunion. left. assumption.\n      * intros HY. apply Hunion. right. assumption.\n    - intros [HX HY] Hunion.\n      inversion Hunion; subst; contradiction.\n  Qed.\n\n\n  (** ** Convert from lists to ensembles *)\n  Fixpoint from_list {A} (l : list A) : Ensemble A :=\n    match l with\n    | nil => ∅\n    | x :: l' => singleton x ∪ from_list l'\n    end.\n  Instance from_list_in_dec {A} `{eq_dec A} (l : list A) : in_dec (from_list l).\n  Proof.\n    constructor. intros a.\n    induction l.\n    * right. inversion 1.\n    * destruct (Dec a a0) as [Heq | Hneq].\n      + subst. left. constructor. constructor.\n      + destruct IHl as [IHl | IHl].\n        ++ left. right. auto.\n        ++ right. simpl.\n           apply not_in_union.\n           split; auto.\n           inversion 1; subst; contradiction.\n  Defined.\n\n  Lemma from_list_app : forall {X} (l1 l2 : list X),\n    from_list (l1 ++ l2) == from_list l1 ∪ from_list l2.\n  Proof.\n    induction l1; intros; simpl.\n    * split; intros x Hx.\n      { right; assumption. }\n      { inversion Hx; subst.\n        + inversion H.\n        + assumption.\n      }\n    * rewrite IHl1.\n      split; intros x Hx.\n      { inversion Hx as [? Hx' | ? Hx' ]; subst; clear Hx.\n        { inversion Hx'; subst. left. left. assumption. }\n        { inversion Hx' as [? Hx'' | ? Hx'']; subst; clear Hx'.\n          { left. right. assumption. }\n          { right. assumption. }\n        }\n      }\n      { inversion Hx as [? Hx' | ? Hx' ]; subst; clear Hx.\n        { inversion Hx'; subst.\n          { left. assumption. }\n          { right. left. assumption. }\n        }\n        { right. right. assumption. }\n      }\n  Qed.\n\n\n  Lemma setminus_union_equiv : forall {X} (A B : Ensemble X) `{in_dec X B},\n    (A ∖ B) ∪ B == A ∪ B.\n  Proof.\n    intros X A B Bdec. split; intros x Hx.\n    + inversion Hx as [? HA | HB]; subst.\n      { inversion HA as [HA' _].\n        left. auto.\n      }\n      { right. auto. }\n    \n    + destruct (In_Dec B x) as [HB | HB].\n      { right. auto. }\n      inversion Hx as [? HA | ? HB']; subst.\n      { left. constructor; auto. }\n      { right. auto. }\n  Qed.\n\n\n  (** The [all_disjoint ls] predicate asserts that every element of the list\n  [ls] is disjoint from every other elemenet of the list [ls]. *)\n  Inductive all_disjoint {A} : list A -> Prop :=\n  | nil_disjoint : all_disjoint []\n  | cons_disjoint x ls : \n      x ∉ from_list ls ->\n      all_disjoint ls ->\n      all_disjoint (x::ls).\n\n\n  Class enumerable {A} (X : Ensemble A) :=\n    { enumerate : list A\n    ; rewrite_enumerate : X == from_list enumerate\n    }.\n  Arguments enumerate {A} X {enumX} : rename.\n  Instance singleton_enumerable {X} : forall (x : X), enumerable (singleton x).\n  Proof. intros x. exists [x]. simpl.\n    split; intros y Hy.\n    * constructor; auto.\n    * inversion Hy; subst; auto.\n      inversion H.\n  Defined.\n  Instance from_list_enumerable {X} : forall (l : list X), enumerable (from_list l).\n  Proof.\n    intros l. exists l. reflexivity.\n  Defined.\n\n  Instance union_enumerable {A} (X Y : Ensemble A) :\n    enumerable X ->\n    enumerable Y ->\n    enumerable (X ∪ Y).\n  Proof.\n    intros [Xl HX] [Yl HY].\n    exists (Xl ++ Yl).\n    rewrite HX, HY.\n    rewrite from_list_app.\n    reflexivity.\n  Defined.\n\n  Instance enum_in_dec : forall {A} `{eq_dec A} (X : Ensemble A) `{enumerable _ X}, in_dec X.\n  Proof.\n    intros ? ? X [Xl Hl].\n    constructor; intros x.\n    destruct (x ∈? from_list Xl).\n    + left. rewrite Hl; auto.\n    + right. rewrite Hl; auto.\n  Defined.\n\n\nEnd EnsembleNotation.\n\n\n(** * Tactics *)\n\n\n(** ** Inversion *)\nLtac inversion_In :=\n  repeat match goal with\n  | [ H : In _ [ _ ] |- _ ] => inversion H; subst; clear H\n  | [ H : In _ [] |- _ ] => inversion H\n  | [ H : In _ (flat_map _ _) |- _ ] => apply in_flat_map in H; destruct H as [? ?]\n  | [ H : _ * _ |- _ ] => destruct H as [? ?]\n  | [ H : _ /\\ _ |- _ ] => destruct H as [? ?]\n  | [ H : (_ , _) = (_, _) |- _] => inversion H; subst; clear H\n  end.\n\nLtac case_In :=\n  match goal with\n  | [ H : In _ [ _ ] |- _ ] => inversion H as [ | H0]\n  | [ H : In _ [] |- _ ] => inversion H\n  | [ H : In _ (_ :: _) |- _ ] => destruct H as [? | ?]\n\n  | [ H : In _ (_ ++ _) |- _ ] => apply in_app_or in H; destruct H as [H | H]\n  end; inversion_In.\n\n\nImport EnsembleNotation.\n\n\n(** ** Contradictions *)\n\n(* First, we find contradictions of the form [all_disjoint ls] where [ls] has\nmore than one occurrence of the same variable. *)\n\nFixpoint count {A} `{eq_dec A} (a : A) (ls : list A) : nat :=\n  match ls with\n  | nil => 0\n  | cons b ls' => if a =? b then 1+count a ls'\n                       else count a ls'\n  end.\n\nLemma count_1_disjoint_contradiction : forall {A} `{eq_dec A} (a:A) ls,\n    count a ls > 0 ->\n    ~ all_disjoint (a::ls).\nProof.\n  induction ls as [ | b ls']; intros Hcount Hdisjoint; simpl in *.\n  * inversion Hcount.\n  * destruct (Dec a b); subst.\n    + inversion Hdisjoint as [ | ? ? Hcontra ]; subst.\n      apply Hcontra. left. auto with sets.\n    + inversion Hdisjoint as [ | ? ? Ha Hdisjoint']; subst.\n      inversion Hdisjoint'; subst.\n      apply IHls'; [rewrite eqb_neq in Hcount; auto | ].\n      constructor; auto.\n      intros Ha_ls'.\n      apply Ha.\n      right; auto.\nQed.\n\nLemma count_disjoint_contradiction : forall {A} `{eq_dec A} (a : A) ls,\n    count a ls > 1 ->\n    ~ all_disjoint ls.\nProof.\n  induction ls as [ | b ls']; intros Hcount.\n  * inversion Hcount.\n  * simpl in Hcount.\n    destruct (Dec a b); [subst; rewrite eqb_eq in Hcount | rewrite eqb_neq in Hcount]; auto.\n    + apply count_1_disjoint_contradiction.\n      apply Gt.gt_S_n; auto.\n    + inversion 1; subst.\n      apply IHls'; auto.\nQed.\n\n\nLtac find_occurrence x ls :=\n  match ls with\n  | x :: _ => idtac\n  | _ :: ?ls' => find_occurrence x ls'\n  end.\n\nLtac find_repetition ls :=\n  match ls with\n  | context[ ?x :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n  | context[ ?x :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: _  :: ?x :: _ ] => constr:(x)\n\n  end.\nLemma reduce_count_cons_eq : forall {A} `{eq_dec A} (x:A) ls n,\n    count x ls > n ->\n    count x (x :: ls) > S n.\nProof.\n    intros A Adec x ls.\n    induction ls as [ | a ls]; intros n Hn.\n    * simpl in Hn. inversion Hn.\n    * simpl in *.\n      unfold eqb in *.\n      destruct (Dec x x) as [Hx | Hx].\n      2:{ contradict Hx; auto. }\n      destruct (Dec x a) as [Ha | Ha].\n      { apply Gt.gt_n_S; auto. }\n      { apply IHls; auto. }\nQed.\nLemma reduce_count_cons_0 : forall  {A} `{eq_dec A} (x:A) ls,\n    count x (x :: ls) > 0.\nProof.\n  intros. simpl.\n  unfold eqb.\n  destruct (Dec x x) as [Hx | Hx].\n  { apply Gt.gt_Sn_O. }\n  { contradict Hx. auto. }\nQed.\nLemma reduce_count_cons_neq : forall  {A} `{eq_dec A} (x y : A) ls n,\n    count x ls > n ->\n    count x (y :: ls) > n.\nProof.\n  intros A Adec x y ls n Hn.\n  simpl. unfold eqb.\n  destruct (Dec x y) as [Hx | Hx]; [ | auto].\n  apply Gt.gt_trans with (m := (count x ls)); auto.\nQed.\nLtac reduce_count :=\n  repeat match goal with\n  | [ |- count ?x (?x :: _) > S ?n ] => apply reduce_count_cons_eq\n  | [ |- count ?x (?x :: _) > 0    ] => apply reduce_count_cons_0\n  | [ |- count ?x (?y :: _) > ?n   ] => apply reduce_count_cons_neq\n  end.\nLtac all_disjoint_contradiction :=\n  repeat match goal with\n  (* contradiction *)\n  | [ H : all_disjoint ?ls |- _ ] => let x := find_repetition ls in\n                                     contradict H;\n                                     apply (count_disjoint_contradiction x);\n                                     reduce_count\n  | [ H : all_disjoint ?ls, Heq : ?x = ?y |- _ ] =>\n    rewrite Heq in *;\n    clear Heq\n  end;\n  fail.\n\n(** ** [find_contradiction]\n\nUse when a hypothesis or collection of hypotheses leads to a simple\ncontradiction about equality, numbers, or set inclusion that can't be solved by\n[contradiction].\n\n*)\nLtac find_contradiction :=\n  try contradiction;\n  try discriminate;\n  try match goal with\n  | [ H : ?a = _, H' : ?a = _ |- _ ] => rewrite H in H'; discriminate\n  | [ H : ?a = _, H' : _ = ?a |- _ ] => rewrite H in H'; discriminate\n  | [ H : _ = ?a, H' : ?a = _ |- _ ] => rewrite <- H in H'; discriminate\n  | [ H : _ = ?a, H' : _ = ?a |- _ ] => rewrite H in H'; discriminate\n  | [ H : ?a = ?b, H' : ?a <> ?b |- _] => rewrite H in H'; contradiction\n  | [ H : ?a = ?b, H' : ?b <> ?a |- _] => rewrite H in H'; contradiction\n  | [ H : ?x < ?x |- _ ] => apply Nat.lt_irrefl in H; contradiction\n  | [ H : ?x > ?x |- _ ] => apply Nat.lt_irrefl in H; contradiction\n  | [ H : ~( ?x ∈ singleton ?x ) |- _ ] => contradict H; auto with sets\n  | [ H1 : ?x ∈ ?X1, H2 : ?x ∈ ?X2, H : ?X1 ⊥ ?X2 |- _] =>\n      absurd (x ∈ X1 ∩ X2); inversion H; auto with sets; fail\n  | [ H : all_disjoint ?ls |- _ ] => all_disjoint_contradiction\n  end.\n\n\n\n\n(** ** [decompose_set_structure] and [solve_set]\n\nUse [decompose_set_structure] to deconstruct hypotheses about set inclusion into\nsimpler hypotheses that can be used to automatically solve a goal.\n\nUse [solve_set] to solve goals of the form [?x ∈ ?X]. May need to combine these;\n[decompose_set_structure; solve_set].\n\n*)\n\nLtac my_subst :=\n  match goal with\n  | [ H : ?x = ?y |- _ ] => replace y with x in * by auto; clear H\n  end.\n\nLtac decompose_set_structure_1 :=\n  match goal with\n  | [ H : ?x ∉ ∅ |- _ ] => clear H\n  | [ H : ?x ∈ ∅ |- _ ] => inversion H\n  | [ H : ?x ∈ ?X ∖ ?Y |- _ ] => destruct H \n  | [ H : ?x ∈ ?X ∪ ?Y |- _ ] => inversion H; subst; clear H\n  | [ H : ?x ∈ ?X ∩ ?Y |- _ ] => inversion H; subst; clear H\n  | [ H : ~(?x ∈ ?X ∪ ?Y) |- _] => assert (~(x ∈ X)) by auto with sets;\n                                   assert (~(x ∈ Y)) by auto with sets;\n                                   clear H\n  | [ H : ?x ∉ ?X ∪ ?Y |- _ ] => apply not_in_union in H; destruct H\n  | [ H : ?x ∉ singleton ?y |- _ ] => apply not_in_singleton_neq in H\n  | [ H : ?x ∈ Couple _ ?y ?z |- _] => inversion H; try subst; clear H\n  | [ H : ?x ∈ singleton ?y |- _ ] => inversion H; my_subst; clear H\n  | [ H : _ /\\ _ |- _ ] => destruct H\n  | [ H : exists _, _ |- _ ] => destruct H\n\n(*\n  | [ H : all_disjoint [] |- _ ] => clear H\n  | [ H : all_disjoint (_ :: _) |- _] => let H' := fresh \"H\" in\n                                         inversion H as [ | ? ? H']; subst; \n                                         simpl in H'; clear H\n*)\n  | [ H : ?x ∈ from_list _ |- _ ] => simpl in H\n  | [ H : ?x ∉ ?X ∖ ?Y |- _ ] =>\n    apply not_in_setminus in H;\n    [destruct H | typeclasses eauto]\n  end.\nLtac decompose_set_structure :=\n  repeat (decompose_set_structure_1; try find_contradiction; auto with sets).\nLtac deep_decompose_set_structure :=\n  repeat (decompose_set_structure;\n          try match goal with\n          | [ H : _ ∈ _ |- _ ] => inversion H; subst; clear H\n          end).\n\n\nLtac try_solve_set :=\n  repeat (auto with sets;\n  match goal with\n  | [ |- ?x <> ?y ] => auto; fail\n  | [ |- ?x <> ?y ] => intro; my_subst; all_disjoint_contradiction\n  | [ |- ?x ∉ singleton ?y ] => apply not_in_singleton_neq; try congruence\n  | [ |- ?x ∈ ?X ∖ ?Y ] => constructor\n  | [ |- ?x ∈ ?X ∪ ?Y ] => left; try_solve_set; fail\n  | [ |- ?x ∈ ?X ∪ ?Y ] => right; try_solve_set; fail\n  | [ |- ?x ∈ ?X ∩ ?Y ] => constructor\n  | [ |- ?x ∉ ?X ∖ ?Y ] => apply in_Y_not_in_setminus_X_Y; try_solve_set; fail\n  | [ |- ?x ∉ ?X ∖ ?Y ] => apply not_in_X_not_in_setminus_X_Y; try_solve_set; fail\n  | [ |- ?x ∉ ?X ∪ ?Y ] => apply not_in_union; constructor\n  | [ |- ?x ∉ ?X ]      => intro; decompose_set_structure; fail\n  | [ |- ?X ⊥ ?Y ]      => constructor; intro\n  end).\n\nLtac solve_set :=\n  simpl; try_solve_set; fail.\n\n  Lemma intersection_emptyset : forall {X} (A : Ensemble X),\n    ∅ ∩ A == ∅.\n  Proof.\n    intros. split; intros x Hx; decompose_set_structure.\n  Qed.\n  Lemma union_emptyset : forall {X} (A : Ensemble X),\n    ∅ ∪ A == A.\n  Proof.\n    intros. split; intros x Hx; decompose_set_structure; solve_set.\n  Qed.\n  Lemma setminus_emptyset : forall {X} (A : Ensemble X),\n    ∅ ∖ A == ∅.\n  Proof.\n    intros. split; intros x Hx; decompose_set_structure; solve_set.\n  Qed.\n\n  Lemma union_symm : forall {X} (A B : Ensemble X),\n    A ∪ B == B ∪ A.\n  Proof.\n    intros. split; intros x Hx; decompose_set_structure; solve_set.\n  Qed.\n  Lemma intersection_symm : forall {X} (A B : Ensemble X),\n    A ∩ B == B ∩ A.\n  Proof.\n    intros. split; intros x Hx; decompose_set_structure; solve_set.\n  Qed.\n\n\n  Lemma union_emptyset_r : forall {X} (A : Ensemble X),\n    A ∪ ∅ == A.\n  Proof.\n    intros.\n    rewrite union_symm. apply union_emptyset.\n  Qed.\n  Lemma intersection_emptyset_r : forall {X} (A : Ensemble X),\n    A ∩ ∅ == ∅.\n  Proof.\n    intros. rewrite intersection_symm. apply intersection_emptyset.\n  Qed.\n  Lemma setminus_emptyset_r : forall {X} (A : Ensemble X),\n    A ∖ ∅ == A.\n  Proof.\n    intros. split; intros x Hx; decompose_set_structure; solve_set.\n  Qed.\n\n  Lemma union_intersect_distr : forall {X} (A B C : Ensemble X),\n    (A ∪ B) ∩ C == (A ∩ C) ∪ (B ∩ C).\n  Proof.\n    intros. split; intros x Hx; decompose_set_structure; solve_set.\n  Qed.\n\n  Lemma union_setminus_distr : forall {X} (A B C : Ensemble X),\n    (A ∪ B) ∖ C == (A ∖ C) ∪ (B ∖ C).\n  Proof.\n    intros; split; intros x Hx; decompose_set_structure; solve_set.\n  Qed.\n\n  Lemma singleton_intersection_in : forall {X} (A : Ensemble X) a,\n    a ∈ A ->\n    singleton a ∩ A == singleton a.\n  Proof.\n    intros X A a Ha; split; intros x Hx;\n    decompose_set_structure.\n  Qed.\n  Lemma singleton_intersection_not_in : forall {X} (A : Ensemble X) a,\n    a ∉ A ->\n    singleton a ∩ A == ∅.\n  Proof.\n    intros X A a Ha; split; intros x Hx;\n    decompose_set_structure.\n  Qed.\n  Lemma singleton_setminus_in : forall {X} (A : Ensemble X) a,\n      a ∈ A ->\n      singleton a ∖ A == ∅.\n    intros X A a Ha; split; intros x Hx;\n    decompose_set_structure.\n  Qed.\n  Lemma singleton_setminus_not_in : forall {X} (A : Ensemble X) a,\n      a ∉ A ->\n      singleton a ∖ A == singleton a.\n    intros X A a Ha; split; intros x Hx;\n    decompose_set_structure.\n  Qed.\n\n  Lemma not_in_intersection : forall {X} (x : X) A B, x ∉ A \\/ x ∉ B -> x ∉ (A ∩ B).\n  Proof.\n    intros X x A B [H | H]; intros Hx;\n    inversion Hx; subst;\n       contradiction.\n  Qed.\n\n\n  Lemma subset_union_r : forall {X} (A B : Ensemble X),\n    B ⊆ A ->\n    A ∪ B == A.\n  Proof.\n    intros X A B Hsubset.\n    split; intros x Hx.\n    2:{ left. auto. }\n    decompose_set_structure; auto.\n  Qed.\n\n\n\n\n\nLtac reduce_set_simpl := match goal with\n    | [ |- context[ ∅ ∩ ?A ] ] => rewrite (intersection_emptyset A)\n    | [ |- context[ ?A ∩ ∅ ] ] => rewrite (intersection_emptyset_r A)\n    | [ |- context[ ∅ ∖ ?A ] ] => rewrite (setminus_emptyset A)\n    | [ |- context[ ?A ∖ ∅ ] ] => rewrite (setminus_emptyset_r A)\n    | [ |- context[ ∅ ∪ ?A ] ] => rewrite (union_emptyset A)\n    | [ |- context[ ?A ∪ ∅ ] ] => rewrite (union_emptyset_r A)\n    end.\n\n\n(** ** Tactics for decidable equality \n\nUse [reduce_eqb] to reduce expressions of the form [x =? y] in both the hypotheses and the goal when you know either [x = y] or [x <> y].\n\nUse [compare e1 e2] to apply decidable equality to decide whether [e1] and [e2] are equal.\n\nUse [compare_next] to search for occurrences of [x =? y] in the context and apply [compare e1 e2].\n\n*)\nLtac reduce_eqb :=\n  repeat match goal with\n  | [ H : context[ ?x =? ?x ] |- _ ] => rewrite eqb_eq in H\n  | [ H : context[ ?x1 =? ?x2 ], H' : ?x1 <> ?x2 |- _] => rewrite (eqb_neq _ x1 x2) in H; [ | auto]\n  | [ H : context[ ?x1 =? ?x2 ], H' : ?x2 <> ?x1 |- _] => rewrite (eqb_neq _ x1 x2) in H; [ | auto]\n  | [ |- context[ ?x =? ?x ] ] => rewrite eqb_eq\n  | [ H' : ?x1 <> ?x2 |- context[ ?x1 =? ?x2 ] ] => rewrite (eqb_neq _ x1 x2); [ | auto]\n  | [ H' : ?x1 <> ?x2 |- context[ ?x2 =? ?x1 ] ] => rewrite (eqb_neq _ x2 x1); [ | auto]\n  | [ H' : ?x1 = ?x2 |- context[ ?x1 =? ?x2 ] ] => rewrite H'\n  | [ H' : ?x1 = ?x2 |- context[ ?x2 =? ?x1 ] ] => rewrite H'\n\n\n  | [ H1 : context[ ?x =? ?y ]\n    , H2 : ?x = ?y\n    |- _ ] => rewrite (eqb_eq' _ x y) in H1; auto\n  | [ H1 : context[ ?x =? ?y ]\n    , H2 : ?y = ?x\n    |- _ ] => rewrite (eqb_eq' _ x y) in H1; auto\n  | [ H2 : ?x = ?y\n    |- context[ ?x =? ?y] ] => rewrite (eqb_eq' _ x y); auto\n  | [ H2 : ?y = ?x\n    |- context[ ?x =? ?y] ] => rewrite (eqb_eq' _ x y); auto\n  end; find_contradiction.\n\nLtac compare e1 e2 :=\n  let Heq := fresh \"Heq\" in\n  let Hneq := fresh \"Hneq\" in\n  destruct (Dec e1 e2) as [Heq | Hneq]; [try subst; try (rewrite Heq) | ]; reduce_eqb.\n\nLtac compare_next :=\n    match goal with\n    | [ |- context[ eqb ?e1 ?e2 ] ] => let tp := type of e1 in\n                                       compare (e1 : tp) (e2 : tp)\n    | [ H : context[ eqb ?e1 ?e2 ] |- _ ] => let tp := type of e1 in compare (e1 : tp) (e2 : tp)\n    end.\n\n(** ** Convert between x ∈ X and in_list_dec x (enumerate X) *)\n\nLemma in_list_dec_t {A} `{A_dec : eq_dec A} : forall (x : A) (X : list A),\n    in_list_dec x X = true <-> x ∈ from_list X.\nProof.\n    induction X; split; simpl; intros H; try (inversion H; fail).\n    * compare_next; try solve_set.\n      right. apply IHX. auto.\n    * compare_next; auto.\n      apply IHX.\n      decompose_set_structure.\nQed.\nLemma in_list_dec_f {A} `{a_dec : eq_dec A} : forall (x : A) X,\n    in_list_dec x X = false <-> x ∉ from_list X.\nProof.\n    induction X; split; simpl; intros H; auto; try solve_set.\n    * compare_next.\n      apply IHX in H.\n      solve_set.\n    * decompose_set_structure.\n      compare_next.\n      apply IHX; auto.\nQed.\n\nLtac from_in_list_dec :=\n  repeat match goal with\n  | [ H : in_list_dec ?x ?X = true |- _] => apply in_list_dec_t in H\n  | [ |- in_list_dec ?x ?X = true ] => apply in_list_dec_t\n  | [ H : in_list_dec ?x ?X = false |- _] => apply in_list_dec_f in H\n  | [ |- in_list_dec ?x ?X = false ] => apply in_list_dec_f\n  end.\nLtac to_in_list_dec :=\n  repeat match goal with\n  | [ H : ?x ∈ ?X |- _] => apply in_list_dec_t in H\n  | [ |- ?x ∈ ?X ] => apply in_list_dec_t\n  | [ H : ?x ∉ ?X |- _] => apply in_list_dec_f in H\n  | [ |- ?x ∉ ?X ] => apply in_list_dec_f\n  end.\n\n  Ltac rewrite_in_list_dec :=\n    match goal with\n    | [ H : ?x ∈ from_list ?l |- context[ in_list_dec ?x ?l ] ] =>\n      replace (in_list_dec x l) with true in *\n      by (to_in_list_dec; rewrite H; auto)\n    | [ H : ?x ∈ from_list ?l, H' : context[ in_list_dec ?x ?l ] |- _ ] =>\n      replace (in_list_dec x l) with true in *\n      by (to_in_list_dec; rewrite H; auto)\n    | [ H : ?x ∈ ?X |- context[ in_list_dec ?x (enumerate ?X) ] ] =>\n      replace (in_list_dec x (enumerate X)) with true in *\n      by (rewrite (@rewrite_enumerate _ X) in H;\n          to_in_list_dec;\n          rewrite H;\n          auto)\n    | [ H : ?x ∈ ?X, H' : context[ in_list_dec ?x (enumerate ?X) ] |- _ ] =>\n      replace (in_list_dec x (enumerate X)) with true in *\n      by (rewrite (@rewrite_enumerate _ X) in H;\n          to_in_list_dec;\n          rewrite H;\n          auto)\n\n    | [ H : ?x ∉ from_list ?l |- context[ in_list_dec ?x ?l ] ] =>\n      replace (in_list_dec x l) with false in *\n      by (to_in_list_dec; rewrite H; auto)\n    | [ H : ?x ∉ from_list ?l, H' : context[ in_list_dec ?x ?l ] |- _ ] =>\n      replace (in_list_dec x l) with false in *\n      by (to_in_list_dec; rewrite H; auto)\n    | [ H : ?x ∉ ?X |- context[ in_list_dec ?x (enumerate ?X) ] ] =>\n      replace (in_list_dec x (enumerate X)) with false in *\n      by (rewrite (@rewrite_enumerate _ X) in H;\n          to_in_list_dec;\n          rewrite H;\n          auto)\n    | [ H : ?x ∉ ?X, H' : context[ in_list_dec ?x (enumerate ?X) ] |- _ ] =>\n      replace (in_list_dec x (enumerate X)) with false in *\n      by (rewrite (@rewrite_enumerate _ X) in H;\n          to_in_list_dec;\n          rewrite H;\n          auto)\n    end.\n\nLtac compare_next_in :=\n  match goal with\n  | [ |- context[ ?x ∈? ?X ] ] => destruct (x ∈? X)\n  | [ H : context[ ?x ∈? ?X ] |- _ ] => destruct (x ∈? X)\n  end.\nLtac compare_in_list :=\n  match goal with\n  | [ |- context[ in_list_dec ?x ?X ] ] =>\n    let Hx := fresh \"Hx\" in\n    destruct (in_list_dec x X) eqn:Hx\n  end.\n\n\n  Section IntersectionEnumerable.\n\n    Context {A : Type} `{A_dec : eq_dec A}.\n    Definition list_intersection (A B : list A) := filter (fun x => in_list_dec x B) A.\n\n    Lemma list_intersection_equiv : forall (l1 l2 : list A),\n      from_list (list_intersection l1 l2) == from_list l1 ∩ from_list l2.\n    Proof.\n      intros l1 l2.\n      unfold list_intersection.\n      simpl.\n      induction l1.\n      * simpl. rewrite intersection_emptyset.\n        reflexivity.\n      * simpl.\n        destruct (in_list_dec a l2) eqn:Ha.\n        + (* a ∈ l2 *) simpl; from_in_list_dec.\n          rewrite union_intersect_distr.\n          rewrite singleton_intersection_in; auto.\n          rewrite IHl1.\n          reflexivity.\n        + (* a ∉ l2 *)\n          from_in_list_dec.\n          rewrite union_intersect_distr.\n          rewrite singleton_intersection_not_in; auto.\n          rewrite union_emptyset.\n          rewrite IHl1; reflexivity.\n    Qed.\n\n\n    Variable X Y : Ensemble A.\n    Context `{enumX : enumerable _ X} `{enumY : enumerable _ Y}.\n\n    Lemma from_list_intersection :\n      X ∩ Y == from_list (list_intersection (enumerate X) (enumerate Y)).\n    Proof.\n      destruct enumX as [Xl HX]; destruct enumY as [Yl HY].\n      rewrite list_intersection_equiv.\n      repeat rewrite <- rewrite_enumerate.\n      reflexivity.\n    Qed.\n\n\n\n    Instance intersection_enumerable :\n      enumerable (X ∩ Y).\n    Proof.\n      exists (list_intersection (enumerate X) (enumerate Y)).\n      apply from_list_intersection.\n    Defined.\n  End IntersectionEnumerable.\n  Existing Instance intersection_enumerable.\n\n\n  Section SetminusEnumerable.\n    Context {name : Type} `{name_dec : eq_dec name}.\n\n    Fixpoint better_filter {A : Type} (f : A -> bool) (l : list A) :=\n      match l with\n      | nil => nil\n      | x :: l0 => (if f x then x::nil else nil) ++ better_filter f l0\n      end.\n    Lemma filter_false : forall {X} (l : list X),\n      better_filter (fun _ => false) l = nil.\n    Proof.\n      induction l; auto.\n    Qed.\n\n    Definition list_setminus (lX lY : list name) :=\n      better_filter (fun x => negb (in_list_dec x lY)) lX.\n\n    \n    Lemma list_setminus_equiv : forall l1 l2 : list name,\n      from_list (list_setminus l1 l2) == from_list l1 ∖ from_list l2.\n    Proof.\n      intros l1.\n      unfold list_setminus.\n      induction l1 as [ | a l1]; intros l2.\n      * simpl.\n        rewrite setminus_emptyset.\n        reflexivity.\n      * simpl.\n        rewrite union_setminus_distr.\n        rewrite <- IHl1.\n        destruct (in_list_dec a l2) eqn:Ha;\n          from_in_list_dec;\n          simpl.\n        + (* a ∈ Y *)\n          rewrite singleton_setminus_in; auto.\n          rewrite union_emptyset.\n          reflexivity.\n        + (* a ∉ Y *)\n          rewrite singleton_setminus_not_in; auto.\n          reflexivity.\n  Qed.\n\n\n\n    Variable X Y : Ensemble name.\n    Context `{enumX : enumerable _ X} `{enumY : enumerable _ Y}.\n\n    Lemma from_list_setminus :\n      X ∖ Y == from_list (list_setminus (enumerate X) (enumerate Y)).\n    Proof.\n      rewrite list_setminus_equiv.\n      destruct enumX as [Xl HX]; destruct enumY as [Yl HY].\n      repeat rewrite <- rewrite_enumerate.\n      reflexivity.\n  Qed.\n  Instance setminus_enumerable : enumerable (X ∖ Y).\n    exists (list_setminus (enumerate X) (enumerate Y)).\n    apply from_list_setminus.\n  Defined.\n  End SetminusEnumerable.\n\n  Instance empty_enumerable : forall {A}, @enumerable A ∅.\n  Proof.\n    intros A.\n    exists nil. simpl. reflexivity.\n  Defined.\n  Existing Instance union_enumerable.\n  Existing Instance setminus_enumerable.\n\n\n\n\n(** ** Utilities for making robust Ltac tactics *)\n\nLtac maybe_do flag tac :=\n  match flag with\n  | false => idtac\n  | true  => tac\n  end.\n\nLtac replace_with_in x y loc_flag :=\n  match loc_flag with\n  | false => (* only in conclusion *) replace x with y\n  | true  => (* everywhere *) replace x with y in *\n  | _ => replace x with y in loc_flag\n  end.\n", "meta": {"author": "GaloisInc", "repo": "Coq-Flow-Equivalence", "sha": "bbbc01aa3cc5887e615c75847fa0c9ac3beaaa45", "save_path": "github-repos/coq/GaloisInc-Coq-Flow-Equivalence", "path": "github-repos/coq/GaloisInc-Coq-Flow-Equivalence/Coq-Flow-Equivalence-bbbc01aa3cc5887e615c75847fa0c9ac3beaaa45/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.83973396967765, "lm_q1q2_score": 0.7202970128129906}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\n(** \"_Algorithms are the computational content of proofs_.\"\n    --Robert Harper *)\n\n(** We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types like [nat] or [list] and functions over\n    these types, and for _proving_ properties of these programs, using\n    inductive propositions (like [ev]), implication, universal\n    quantification, and the like.  So far, we have mostly treated\n    these mechanisms as if they were quite separate, and for many\n    purposes this is a good way to think.  But we have also seen hints\n    that Coq's programming and proving facilities are closely related.\n    For example, the keyword [Inductive] is used to declare both data\n    types and propositions, and [->] is used both to describe the type\n    of functions on data and logical implication.  This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are\n    almost the same thing.  In this chapter we will study how this\n    works.\n\n    We have already seen the fundamental idea: provability in Coq is\n    represented by concrete _evidence_.  When we construct the proof\n    of a basic proposition, we are actually building a tree of\n    evidence, which can be thought of as a data structure.\n\n    If the proposition is an implication like [A -> B], then its proof\n    will be an evidence _transformer_: a recipe for converting\n    evidence for A into evidence for B.  So at a fundamental level,\n    proofs are simply programs that manipulate evidence. *)\n\n(** Question: If evidence is data, what are propositions themselves?\n\n    Answer: They are types! *)\n\n(** Look again at the formal definition of the [ev] property.  *)\n\nPrint ev.\n(* ==>\n  Inductive ev : nat -> Prop :=\n    | ev_0 : ev 0\n    | ev_SS : forall n, ev n -> ev (S (S n)).\n*)\n\n(** Suppose we introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can say \"is a proof of.\"  For example,\n    the second line in the definition of [ev] declares that [ev_0 : ev\n    0].  Instead of \"[ev_0] has type [ev 0],\" we can say that \"[ev_0]\n    is a proof of [ev 0].\" *)\n\n(** This pun between types and propositions -- between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\" -- is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation:\n\n                 propositions  ~  types\n                 proofs        ~  data values\n\n    See [Wadler 2015] (in Bib.v) for a brief history and up-to-date\n    exposition. *)\n\n(** Many useful insights follow from this connection.  To begin with,\n    it gives us a natural interpretation of the type of the [ev_SS]\n    constructor: *)\n\nCheck ev_SS\n  : forall n,\n    ev n ->\n    ev (S (S n)).\n\n(** This can be read \"[ev_SS] is a constructor that takes two\n    arguments -- a number [n] and evidence for the proposition [ev\n    n] -- and yields evidence for the proposition [ev (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [ev]. *)\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** As with ordinary data values and functions, we can use the [Print]\n    command to see the _proof object_ that results from this proof\n    script. *)\n\nPrint ev_4.\n(* ===> ev_4 = ev_SS 2 (ev_SS 0 ev_0)\n     : ev 4  *)\n\n(** Indeed, we can also write down this proof object _directly_,\n    without the need for a separate proof script: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0))\n  : ev 4.\n\n(** The expression [ev_SS 2 (ev_SS 0 ev_0)] can be thought of as\n    instantiating the parameterized constructor [ev_SS] with the\n    specific arguments [2] and [0] plus the corresponding proof\n    objects for its premises [ev 2] and [ev 0].  Alternatively, we can\n    think of [ev_SS] as a primitive \"evidence constructor\" that, when\n    applied to a particular number, wants to be further applied to\n    evidence that this number is even; its type,\n\n      forall n, ev n -> ev (S (S n)),\n\n    expresses this functionality, in the same way that the polymorphic\n    type [forall X, list X] expresses the fact that the constructor\n    [nil] can be thought of as a function from types to empty lists\n    with elements of that type. *)\n\n(** We saw in the [Logic] chapter that we can use function\n    application syntax to instantiate universally quantified variables\n    in lemmas, as well as to supply evidence for assumptions that\n    these lemmas impose.  For instance: *)\n\nTheorem ev_4': ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(* ################################################################# *)\n(** * Proof Scripts *)\n\n(** The _proof objects_ we've been discussing lie at the core of how\n    Coq operates.  When Coq is following a proof script, what is\n    happening internally is that it is gradually constructing a proof\n    object -- a term whose type is the proposition being proved.  The\n    tactics between [Proof] and [Qed] tell it how to build up a term\n    of the required type.  To see this process in action, let's use\n    the [Show Proof] command to display the current state of the proof\n    tree at various points in the following tactic proof. *)\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with a\n    \"hole\" (indicated by [?Goal] here, and so on), and it knows what\n    type of evidence is needed to fill this hole.\n\n    Each hole corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    evidence we've built is stored in the global context under the name\n    given in the [Theorem] command. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand, as shown above. Then we can use [Definition]\n    (rather than [Theorem]) to give a global name directly to this\n    evidence. *)\n\nDefinition ev_4''' : ev 4 := ev_SS 2 (ev_SS 0 ev_0).\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint ev_4.\n(* ===> ev_4    =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\n\n(** **** Exercise: 2 stars, standard (eight_is_even)\n\n    Give a tactic proof and a proof object showing that [ev 8]. *)\n\nTheorem ev_8 : ev 8.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_SS. apply ev_SS. apply ev_0.\nQed.\n\nDefinition ev_8' : ev 8 := ev_SS _ (ev_SS _ (ev_SS _ (ev_SS _ ev_0))).\n\nPrint ev_8.\nPrint ev_8'.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Quantifiers, Implications, Functions *)\n\n(** In Coq's computational universe (where data structures and\n    programs live), there are two sorts of values that have arrows in\n    their types: _constructors_ introduced by [Inductive]ly defined\n    data types, and _functions_.\n\n    Similarly, in Coq's logical universe (where we carry out proofs),\n    there are two ways of giving evidence for an implication:\n    constructors introduced by [Inductive]ly defined propositions,\n    and... functions! *)\n\n(** For example, consider this statement: *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\nPrint ev_plus4.\n\n(** What is the proof object corresponding to [ev_plus4]?\n\n    We're looking for an expression whose _type_ is [forall n, ev n ->\n    ev (4 + n)] -- that is, a _function_ that takes two arguments (one\n    number and a piece of evidence) and returns a piece of evidence!\n\n    Here it is: *)\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah],\" and that Coq treats [4 + n] and [S (S (S (S n)))]\n    as synonyms. Another equivalent way to write this definition is: *)\n\nDefinition ev_plus4'' (n : nat) (H : ev n)\n                    : ev (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''\n  : forall n : nat,\n    ev n ->\n    ev (4 + n).\n\n(** When we view the proposition being proved by [ev_plus4] as a\n    function type, one interesting point becomes apparent: The second\n    argument's type, [ev n], mentions the _value_ of the first\n    argument, [n].\n\n    While such _dependent types_ are not found in conventional\n    programming languages, they can be useful in programming too, as\n    the recent flurry of activity in the functional programming\n    community demonstrates. *)\n\n(** Notice that both implication ([->]) and quantification ([forall])\n    correspond to functions on evidence.  In fact, they are really the\n    same thing: [->] is just a shorthand for a degenerate use of\n    [forall] where there is no dependency, i.e., no need to give a\n    name to the type on the left-hand side of the arrow:\n\n           forall (x:nat), nat\n        =  forall (_:nat), nat\n        =  nat -> nat\n*)\n\n(** For example, consider this proposition: *)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : ev n), ev (n + 2).\n\n(** A proof term inhabiting this proposition would be a function\n    with two arguments: a number [n] and some evidence [E] that [n] is\n    even.  But the name [E] for this evidence is not used in the rest\n    of the statement of [ev_plus2], so it's a bit silly to bother\n    making up a name for it.  We could write it like this instead,\n    using the dummy identifier [_] in place of a real name: *)\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : ev n), ev (n + 2).\n\n(** Or, equivalently, we can write it in a more familiar way: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, ev n -> ev (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\n(** If we can build proofs by giving explicit terms rather than\n    executing tactic scripts, you may be wondering whether we can\n    build _programs_ using _tactics_ rather than explicit terms.\n    Naturally, the answer is yes! *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n\nPrint add1.\n(* ==>\n    add1 = fun n : nat => S n\n         : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than\n    with [:=] followed by a term.  This tells Coq to enter _proof\n    scripting mode_ to build an object of type [nat -> nat].  Also, we\n    terminate the proof with [Defined] rather than [Qed]; this makes\n    the definition _transparent_ so that it can be used in computation\n    like a normally-defined function.  ([Qed]-defined objects are\n    opaque during computation.)\n\n    This feature is mainly useful for writing functions with dependent\n    types, which we won't explore much further in this book.  But it\n    does illustrate the uniformity and orthogonality of the basic\n    ideas in Coq. *)\n\n(* ################################################################# *)\n(** * Logical Connectives as Inductive Types *)\n\n(** Inductive definitions are powerful enough to express most of the\n    connectives we have seen so far.  Indeed, only universal\n    quantification (with implication as a special case) is built into\n    Coq; all the others are defined inductively.  We'll see these\n    definitions in this section. *)\n\nModule Props.\n\n(* ================================================================= *)\n(** ** Conjunction *)\n\n(** To prove that [P /\\ Q] holds, we must present evidence for both\n    [P] and [Q].  Thus, it makes sense to define a proof object for [P\n    /\\ Q] as consisting of a pair of two proofs: one for [P] and\n    another one for [Q]. This leads to the following definition. *)\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n| conj : P -> Q -> and P Q.\n\nArguments conj [P] [Q].\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** Notice the similarity with the definition of the [prod] type,\n    given in chapter [Poly]; the only difference is that [prod] takes\n    [Type] arguments, whereas [and] takes [Prop] arguments. *)\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\n\n(** This similarity should clarify why [destruct] and [intros]\n    patterns can be used on a conjunctive hypothesis.  Case analysis\n    allows us to consider all possible ways in which [P /\\ Q] was\n    proved -- here just one (the [conj] constructor). *)\n\nTheorem proj1' : forall P Q,\n    P /\\ Q -> P.\nProof.\n  intros P Q HPQ.\n  Show Proof.\n  destruct HPQ as [HP HQ].\n  Show Proof.\n  apply HP.\n  Show Proof.\nQed.\n\n(** Similarly, the [split] tactic actually works for any inductively\n    defined proposition with exactly one constructor.  In particular,\n    it works for [and]: *)\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  Show Proof.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HQ HP]. split.\n    + apply HP.\n    + apply HQ.\n  Show Proof.\n  Check Logic.conj.\nQed.\n\n(* The proof object looks like below.\n(fun P Q : Prop =>\n Logic.conj (fun H : P /\\ Q => match H with\n                               | conj HP HQ => conj HQ HP\n                               end)\n   (fun H : Q /\\ P => match H with\n                      | conj HQ HP => conj HP HQ\n                      end))\n\nNote that it was because the type of and_comm is actually\n  (P /\\ Q -> Q /\\ P) /\\ (Q /\\ P -> P /\\ Q)\n *)\n\n\nEnd And.\n\n(** This shows why the inductive definition of [and] can be\n    manipulated by tactics as we've been doing.  We can also use it to\n    build proofs directly, using pattern-matching.  For instance: *)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) : Q /\\ P :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, standard (conj_fact)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  (fun p q r H1 H2 => conj (proj1 _ _ H1) (proj2 _ _ H2)).\n\n(* full version *)\nDefinition conj_fact' : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  (fun p q r H1 H2 => conj (proj1 p q H1) (proj2 q r H2)).\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Disjunction *)\n\n(** The inductive definition of disjunction uses two constructors, one\n    for each side of the disjunct: *)\n\nModule Or.\n\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\n\nArguments or_introl [P] [Q].\nArguments or_intror [P] [Q].\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** This declaration explains the behavior of the [destruct] tactic on\n    a disjunctive hypothesis, since the generated subgoals match the\n    shape of the [or_introl] and [or_intror] constructors.\n\n    Once again, we can also directly write proof objects for theorems\n    involving [or], without resorting to tactics. *)\n\nDefinition inj_l : forall (P Q : Prop), P -> P \\/ Q :=\n  fun P Q HP => or_introl HP.\n\nTheorem inj_l' : forall (P Q : Prop), P -> P \\/ Q.\nProof.\n  intros P Q HP. left. apply HP.\nQed.\n\nPrint inj_l.\n\nDefinition or_elim : forall (P Q R : Prop), (P \\/ Q) -> (P -> R) -> (Q -> R) -> R :=\n  fun P Q R HPQ HPR HQR =>\n    match HPQ with\n    | or_introl HP => HPR HP\n    | or_intror HQ => HQR HQ\n    end.\n\nTheorem or_elim' : forall (P Q R : Prop), (P \\/ Q) -> (P -> R) -> (Q -> R) -> R.\nProof.\n  intros P Q R HPQ HPR HQR.\n  destruct HPQ as [HP | HQ].\n  - apply HPR. apply HP.\n  - apply HQR. apply HQ.\nQed.\n\nPrint or_elim'.\n\nEnd Or.\n\n(** **** Exercise: 2 stars, standard (or_commut')\n\n    Construct a proof object for the following proposition. *)\n\nDefinition or_commut' : forall P Q, P \\/ Q -> Q \\/ P :=\n  fun P Q HPQ => match HPQ with\n              | or_introl P => or_intror P\n              | or_intror Q => or_introl Q\n              end.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Existential Quantification *)\n\n(** To give evidence for an existential quantifier, we package a\n    witness [x] together with a proof that [x] satisfies the property\n    [P]: *)\n\nModule Ex.\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro : forall x : A, P x -> ex P.\n\nInductive ex' {A : Type} (P : A -> Prop) : Prop :=\n| ex_intro' (x : A) (H : P x) : ex' P.\n\nDefinition some_nat_is_even'' : @ex' nat ev :=\n  @ex_intro' nat ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\nCheck ex_intro'.\n\nNotation \"'exists' x , p\" :=\n  (ex (fun x => p))\n    (at level 200, right associativity) : type_scope.\n\nEnd Ex.\n\n(** This may benefit from a little unpacking.  The core definition is\n    for a type former [ex] that can be used to build propositions of\n    the form [ex P], where [P] itself is a _function_ from witness\n    values in the type [A] to propositions.  The [ex_intro]\n    constructor then offers a way of constructing evidence for [ex P],\n    given a witness [x] and a proof of [P x].\n\n    The notation in the standard library is a slight variant of\n    the above, enabling syntactic forms such as [exists x y, P x y]. *)\n\n(** The more familiar form [exists x, P x] desugars to an expression\n    involving [ex]: *)\n\nCheck ex (fun n => ev n) : Prop.\n\n(** Here's how to define an explicit proof object involving [ex]: *)\n\nDefinition some_nat_is_even : exists n, ev n :=\n  ex_intro ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\nCheck ex_intro.\n(* forall (A : Type) (P : A -> Prop) (x : A), P x -> exists y, P y *)\n\nCheck 4. (* nat *)\nCheck ev. (* nat -> Prop *)\nCheck (ev_SS 2 (ev_SS 0 ev_0)). (* ev 4 *)\n\n(* Note that (A: Type) is omitted because it was marked optional.\n   If we are to pass explicitly, we should put \"nat\" in there.\n *)\n\n(** **** Exercise: 2 stars, standard (ex_ev_Sn)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) :=\n  ex_intro (fun n => ev (S n)) 1 (ev_SS _ ev_0).\nPrint ex_ev_Sn.\n\n(* ex_ev_Sn =\nex_intro (fun n : nat => ev (S n)) 1 (ev_SS 0 ev_0)\n     : exists n : nat, ev (S n)\n *)\n\nDefinition ex_ev_Sn' : ex (fun n => ev (S n)).\nProof.\n  exists 1. apply ev_SS. apply ev_0.\nQed.\nPrint ex_ev_Sn'.\n\n(* ex_ev_Sn' =\nex_intro (fun n : nat => ev (S n)) 1 (ev_SS 0 ev_0)\n     : exists n : nat, ev (S n)\n *)\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** [True] and [False] *)\n\n(** The inductive definition of the [True] proposition is simple: *)\n\nInductive True : Prop :=\n  | I : True.\n\n(** It has one constructor (so every proof of [True] is the same, so\n    being given a proof of [True] is not informative.) *)\n\n(** **** Exercise: 1 star, standard (p_implies_true)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition p_implies_true : forall P, P -> True := (fun _P _HP => I).\nPrint p_implies_true.\n\n(* p_implies_true = fun (_P : Type) (_ : _P) => I\n     : forall P : Type, P -> True\n *)\n\nDefinition p_implies_true' : forall P, P -> True.\nProof.\n  intro P. intro HP. apply I.\nQed.\nPrint p_implies_true'.\n\n(* p_implies_true' = fun (P : Type) (_ : P) => I\n     : forall P : Type, P -> True\n *)\n\n(** [] *)\n\n(** [False] is equally simple -- indeed, so simple it may look\n    syntactically wrong at first glance! *)\n\nInductive False : Prop := .\n\n(** That is, [False] is an inductive type with _no_ constructors --\n    i.e., no way to build evidence for it. For example, there is\n    no way to complete the following definition such that it\n    succeeds (rather than fails). *)\n\nFail Definition contra : False :=\n  0 = 1.\n\n(** But it is possible to destruct [False] by pattern matching. There can\n    be no patterns that match it, since it has no constructors.  So\n    the pattern match also is so simple it may look syntactically\n    wrong at first glance. *)\n\nDefinition false_implies_zero_eq_one : False -> 0 = 1 :=\n  fun contra => match contra with end.\n\n(** Since there are no branches to evaluate, the [match] expression\n    can be considered to have any type we want, including [0 = 1].\n    Indeed, it's impossible to ever cause the [match] to be evaluated,\n    because we can never construct a value of type [False] to pass to\n    the function. *)\n\n(** **** Exercise: 1 star, standard (ex_falso_quodlibet')\n\n    Construct a proof object for the following proposition. *)\n\nDefinition ex_falso_quodlibet' : forall P, False -> P :=\n  fun p contra => match contra with end.\n\n(** [] *)\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  We can define\n    it ourselves: *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n| eq_refl : forall x, eq x x.\n\nNotation \"x == y\" := (eq x y)\n                       (at level 70, no associativity)\n                     : type_scope.\n\n(** The way to think about this definition (which is just a slight\n    variant of the standard library's) is that, given a set [X], it\n    defines a _family_ of propositions \"[x] is equal to [y],\" indexed\n    by pairs of values ([x] and [y]) from [X].  There is just one way\n    of constructing evidence for members of this family: applying the\n    constructor [eq_refl] to a type [X] and a single value [x : X],\n    which yields evidence that [x] is equal to [x].\n\n    Other types of the form [eq x y] where [x] and [y] are not the\n    same are thus uninhabited. *)\n\n(** We can use [eq_refl] to construct evidence that, for example, [2 =\n    2].  Can we also use it to construct evidence that [1 + 1 = 2]?\n    Yes, we can.  Indeed, it is the very same piece of evidence!\n\n    The reason is that Coq treats as \"the same\" any two terms that are\n    _convertible_ according to a simple set of computation rules.\n\n    These rules, which are similar to those used by [Compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.  *)\n\nLemma four: 2 + 2 == 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove\n    equalities up to now is essentially just shorthand for [apply\n    eq_refl].\n\n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).\n\n    But you can see them directly at work in the following explicit\n    proof objects: *)\n\nDefinition four' : 2 + 2 == 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), []++[x] == x::[]  :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\n(** **** Exercise: 2 stars, standard (equality__leibniz_equality)\n\n    The inductive definition of equality implies _Leibniz equality_:\n    what we mean when we say \"[x] and [y] are equal\" is that every\n    property on [P] that is true of [x] is also true of [y].  *)\n\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x == y -> forall P:X->Prop, P x -> P y.\nProof.\n  intros. destruct H. apply H0.\nQed.\n\n(* Trying to write a proof object for it *)\n\nFail Definition equality__leibniz_equality' : forall (X : Type) (x y: X),\n    x == y -> forall P:X->Prop, P x -> P y :=\n  fun X x y Heq HP HPx => match Heq with\n                       | eq_refl x => _ (* I'm stuck *)\n                       end.\n\nPrint equality__leibniz_equality.\n\n(*\nfun (X : Type) (x y : X) (H : x == y) (P : X -> Prop) (H0 : P x) =>\nmatch H in (y0 == y1) return (P y0 -> P y1) with\n| eq_refl x0 => fun H1 : P x0 => H1\nend H0\n\n *)\n\n(* So it seems like it's done using some intricate syntax that I\nhaven't learned yet. Let's move on anyway. *)\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (leibniz_equality__equality)\n\n    Show that, in fact, the inductive definition of equality is\n    _equivalent_ to Leibniz equality.  Hint: the proof is quite short;\n    about all you need to do is to invent a clever property [P] to\n    instantiate the antecedent.*)\n\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P:X->Prop, P x -> P y) -> x == y.\nProof.\n  intros.\n  assert (Himp: x == x -> x == y).\n  { apply H. }\n  apply Himp. apply eq_refl.\nQed.\n\n\nDefinition leibniz_equality__equality' : forall (X : Type) (x y: X),\n    (forall P:X->Prop, P x -> P y) -> x == y :=\n  (fun X (x y : X) (H : forall P: X -> Prop, P x -> P y) =>\n     (H (fun k => x == k)) (eq_refl x)\n  ).\n\nPrint leibniz_equality__equality.\n\n(** [] *)\n\nEnd MyEquality.\n\n(* ================================================================= *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves.\n\n    In general, the [inversion] tactic...\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n\n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are\n    two constructors, so two subgoals get generated.  The\n    conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [and], there is\n    only one constructor, so only one subgoal gets generated.  Again,\n    the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal.  The\n    constructor does have two arguments, though, and these can be seen\n    in the context in the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [eq], there is\n    again only one constructor, so only one subgoal gets generated.\n    Now, though, the form of the [eq_refl] constructor does give us\n    some extra information: it tells us that the two arguments to [eq]\n    must be the same!  The [inversion] tactic adds this fact to the\n    context. *)\n\n(* ################################################################# *)\n(** * The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is\n    \"why trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on. *)\n\n(** There are a few additional wrinkles:\n\n    First, since Coq types can themselves be expressions, the checker\n    must normalize these (by using the computation rules) before\n    comparing them.\n\n    Second, the checker must make sure that [match] expressions are\n    _exhaustive_.  That is, there must be an arm for every possible\n    constructor.  To see why, consider the following alleged proof\n    object: *)\n\nFail Definition or_bogus : forall P Q, P \\/ Q -> P :=\n  fun (P Q : Prop) (A : P \\/ Q) =>\n    match A with\n    | or_introl H => H\n    end.\n\n(** All the types here match correctly, but the [match] only\n    considers one of the possible constructors for [or].  Coq's\n    exhaustiveness check will reject this definition.\n\n    Third, the checker must make sure that each recursive function\n    terminates.  It does this using a syntactic check to make sure\n    that each recursive call is on a subexpression of the original\n    argument.  To see why this is essential, consider this alleged\n    proof: *)\n\nFail Fixpoint infinite_loop {X : Type} (n : nat) {struct n} : X :=\n  infinite_loop n.\nFail Definition falso : False := infinite_loop 0.\n\n(** Recursive function [infinite_loop] purports to return a\n    value of any type [X] that you would like.  (The [struct]\n    annotation on the function tells Coq that it recurses on argument\n    [n], not [X].)  Were Coq to allow [infinite_loop], then [falso]\n    would be definable, thus giving evidence for [False].  So Coq rejects\n    [infinite_loop]. *)\n\n(** Note that the soundness of Coq depends only on the\n    correctness of this typechecking engine, not on the tactic\n    machinery.  If there is a bug in a tactic implementation (and this\n    certainly does happen!), that tactic might construct an invalid\n    proof term.  But when you type [Qed], Coq checks the term for\n    validity from scratch.  Only theorems whose proofs pass the\n    type-checker can be used in further proof developments.  *)\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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7202970022983614}}
{"text": "(* chap 15.1 Proving Eveness *)\n\nRequire Import List.\nRequire Import Cpdt.CpdtTactics Cpdt.MoreSpecif.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n\nInductive isEven  : nat->Prop :=\n| Even_O: isEven O\n| Even_SS:forall n, isEven n->isEven (S (S n)).\n\nLtac prove_even:= repeat constructor.\nTheorem even_256 : isEven 256.\n  prove_even. Qed.\nTheorem lt_2_1024 : 2<256.  (* it will be very slow *)\n  prove_even. Qed.\n\nPrint lt_2_1024.\nPrint even_256.\n\nPrint partial.\nLocal Open Scope partial_scope.\nDefinition check_even: forall n:nat, [isEven n].\n  Hint Constructors isEven.\n  refine (fix F (n:nat):[isEven n]:=\n            match n with\n            | 0=>Yes\n            | 1=>No\n            | S (S n')=>Reduce (F n')\n            end); auto.\nDefined.\n\nDefinition partialOut (P:Prop) (x:[P]) :=\nmatch x return (match x with\n                | Proved _ =>P\n                | Uncertain =>True\n                end) with\n| Proved pf => pf\n| Uncertain => I\nend.\n\n\nLtac prove_even_reflective:=\n  match goal with\n  | [ |- isEven ?N ]=> exact (partialOut (check_even N))\n  end.\n\nTheorem even_256' : isEven 256.\n prove_even_reflective. Qed.\n\nPrint even_256'.\n\nTheorem even_255 : isEven 255.\nAbort.\n\n(* chap 15.2 *)\n\nTheorem true_galore : (True /\\ True) -> (True \\/ (True /\\ (True -> True))).\n  tauto. Qed.\nPrint true_galore.\n\nInductive taut : Set :=\n| TautTrue : taut\n| TautAnd : taut->taut->taut\n| TautOr: taut->taut->taut\n| TautImp: taut ->taut ->taut.\n\nFixpoint tautDenote (t:taut) : Prop :=\n  match t with\n  | TautTrue => True\n  | TautAnd t1 t2 => tautDenote t1 /\\ tautDenote t2\n  | TautOr t1 t2 => tautDenote t1 \\/ tautDenote t2\n  | TautImp t1 t2 => tautDenote t1 -> tautDenote t2\n  end.\n\nTheorem tautTrue : forall t, tautDenote t.\n  induction t; crush. Qed.\n\n\n\nLtac tautReify P :=\n  match P with\n  | True => TautTrue\n  | ?P1 /\\ ?P2 =>\n    let t1:= tautReify P1 in\n    let t2:=tautReify P2 in\n    constr:(TautAnd t1 t2)\n  | ?P1 \\/ ?P2 =>\n    let t1:= tautReify P1 in\n    let t2:= tautReify P2 in\n    constr:(TautOr t1 t2)\n  | ?P1 -> ?P2 =>\n    let t1:= tautReify P1 in\n    let t2:= tautReify P2 in\n    constr:(TautImp t1 t2)\n  end.\n\nLtac obvious :=\n  match goal with\n  | [ |- ?P ]=>\n    let t:=tautReify P in\n    exact (tautTrue t)\n  end.\n\nLemma true_test1: True.\n  exact (tautTrue TautTrue). Qed.\nPrint true_test1.\nTheorem true_galore' : (True /\\ True) -> (True \\/ (True /\\ (True -> True))).\n  obvious. Qed.\n\nPrint true_galore'.\n\n\n(* chap 15.3 *)\n\nSection monoid.\n  Variable A : Set.\n  Variable e : A.\n  Variable f : A->A->A.\n\n  Infix \"+\" := f.\n  Hypothesis assocc:forall a b c, (a+b)+c =a +(b+c).\n  Hypothesis identl :forall a, e+a= a.\n  Hypothesis identr: forall a, a+e=a.\n\n  Inductive mexp:Set:=\n  | Ident:mexp\n  |Var :A -> mexp\n  | Op : mexp ->mexp ->mexp.\n\n  Fixpoint mdenote (me:mexp) : A:=\n    match me with\n    | Ident => e\n    | Var v => v\n    | Op me1 me2 => mdenote me1 + mdenote me2\n    end.\n\n\n  Fixpoint mIdenote (ls :list A): A:=\n    match ls with\n    | nil => e\n    | x::ls'=> x+ mIdenote ls'\n    end.\n\n  Fixpoint flatten (me:mexp) :list A:=\n    match me with\n    | Ident => nil\n    | Var x => x::nil\n    | Op me1 me2 =>flatten me1++flatten me2\n    end.\n\n  Lemma flatten_correct': forall ml2 ml1,\n      mIdenote ml1 + mIdenote ml2 = mIdenote (ml1++ml2).\n    induction ml1; crush. Qed.\n\n  Theorem flatten_correct : forall me, mdenote me = mIdenote (flatten me).\n    Hint Resolve flatten_correct'.\n    induction me; crush. Qed.\n\n  Theorem monoid_reflect : forall me1 me2, mIdenote (flatten me1) =\n                                      mIdenote (flatten me2) ->\n                                      mdenote me1=mdenote me2.\n    intros; repeat rewrite flatten_correct; assumption. Qed.\n\n  Ltac reify me:=\n    match me with\n    | e => Ident\n    | ?me1 + ?me2 =>\n      let r1:= reify me1 in\n      let r2:= reify me2 in\n      constr:(Op r1 r2)\n    | _ => constr:(Var me)\n    end.\n\n  Ltac monoid :=\n    match goal with\n    | [ |- ?me1 = ?me2 ]=>\n      let r1:= reify me1 in\n      let r2:= reify me2 in\n      change (mdenote r1=mdenote r2);\n      apply monoid_reflect; simpl\n    end.\n\n  Theorem t1:forall a b c d, a+b+c +d = a+ (b+c) +d.\n    intros; monoid. reflexivity. Qed.\n\n  Print t1.\nEnd monoid.\n\nModule test1. (* This module is a test for keyword `return` *)\n  Inductive test:Type:=\n    test1 | test2.\n  Definition return_test (n:test) :=\n    match n return (match n with\n                    | test1 => Prop\n                    | test2 => Type\n                   end)  with\n    | test1 => (forall x:nat , x >=0)\n    | test2 => test\n    end.\n  Lemma test_test : return_test test1=(forall x:nat, x >= 0).\n    reflexivity. Qed. Print test_test.\nEnd test1.\n\n(* chap 15.4 *)\nRequire Import Quote.\n\nInductive formula: Set:=\n| Atomic :index->formula\n| Truth: formula\n| Falsehood : formula\n| And : formula -> formula -> formula\n| Or: formula -> formula -> formula\n| Imp : formula -> formula -> formula.\n\nDefinition imp (P1 P2:Prop)  := P1->P2.\nInfix \"->\" := imp (no associativity, at level 95).\n\nDefinition asgn := varmap Prop.\nFixpoint formulaDenote (atomics:asgn) (f:formula) :Prop:=\n  match f with\n  | Atomic v => varmap_find False v atomics\n  | Truth => True\n  | Falsehood => False\n  | And f1 f2 => formulaDenote atomics f1 /\\ formulaDenote atomics f2\n  | Or f1 f2 => formulaDenote atomics f1 \\/ formulaDenote atomics f2\n  | Imp f1 f2 => formulaDenote atomics f1 -> formulaDenote atomics f2\n  end.\n\nSection my_tauto.\n  Variable atomics : asgn.\n  Definition holds (v:index)  := varmap_find False v atomics.\n  Require Import ListSet.\n\n  Definition index_eq : forall x y:index, {x = y}+{ x<> y}.\n    decide equality.\n  Defined.\n\n  Definition add (s:set index) (v:index)  := set_add index_eq v s.\n  Definition In_dec:forall v (s :set index), {In v s}+{~ In v s} .\n    Local Open Scope specif_scope.\n\n    intro; refine (fix F (s:set index) : {In v s}+{~ In v s}:=\n                     match s with\n                     | nil => No\n                     | v'::s' => index_eq v' v || F s'\n                     end); crush.\n  Defined.\n\n  Fixpoint allTrue (s:set index) :Prop:=\n    match s with\n    | nil => True\n    | v::s' => holds v /\\ allTrue s'\n    end.\n\n  Theorem allTrue_add : forall v s, allTrue s->\n                               holds v->allTrue (add s v).\n    induction s; crush; match goal with\n                        | [ |- context[if ?E then _ else _]]=> destruct E\n                        end; crush. Qed.\n\n  Theorem allTrue_In : forall v s, allTrue s -> set_In v s ->\n                              varmap_find False v atomics.\n    induction s; crush. Qed.\n\n  Hint Resolve allTrue_add allTrue_In.\n  Local Open Scope partial_scope.\n\n  Definition forward: forall (f :formula) (known:set index) (hyp:formula)\n                        (cont: forall known', [allTrue known'->formulaDenote atomics f]),\n      [allTrue known ->formulaDenote atomics hyp -> formulaDenote atomics f].\n    refine (fix F (f:formula ) (known: set index) (hyp: formula)\n                (cont : forall known', [allTrue known' -> formulaDenote atomics f])\n            : [ allTrue known -> formulaDenote atomics hyp -> formulaDenote atomics f]:=\n              match hyp with\n              | Atomic v => Reduce (cont (add known v))\n              | Truth => Reduce (cont known)\n              | Falsehood  => Yes\n              | And h1 h2 =>\n                Reduce (F (Imp h2 f) known h1 (fun known' =>\n                                                 Reduce (F f known' h2 cont)))\n              | Or h1 h2 => F f known h1 cont && F f known h2 cont\n              | Imp _ _ => Reduce (cont known)\n              end); crush.\n  Defined.\n\n  Definition backward : forall (known : set index) (f : formula),\n[allTrue known -> formulaDenote atomics f ].\nrefine (fix F (known : set index) (f : formula)\n: [allTrue known -> formulaDenote atomics f ] :=\nmatch f with\n| Atomic v => Reduce (In_dec v known)\n| Truth => Yes\n| Falsehood => No\n| And f1 f2 => F known f1 && F known f2\n| Or f1 f2 => F known f1 || F known f2\n| Imp f1 f2 => forward f2 known f1 (fun known' => F known' f2 )\nend); crush; eauto.\n  Defined.\n\n  Definition my_tauto: forall f: formula, [formulaDenote atomics f].\n    intro; refine (Reduce (backward nil f)) ;crush. Defined.\n\nEnd my_tauto.\n\nLtac my_tauto:=\n  repeat match goal with\n         | [ |- forall x:?P, _ ]=>\n           match type of P with\n           | Prop => fail 1\n           | _ => intro\n           end\n         end;\n  quote formulaDenote;\n  match goal with\n  | [ |- formulaDenote ?m ?f] => exact (partialOut (my_tauto m f))\n  end.\n\nTheorem mt1 : True.\n  my_tauto. Qed.\n\nPrint mt1.\n\nTheorem mt2 : forall x y:nat, x= y -> x=y.\n  intros.  ", "meta": {"author": "shij-hsu", "repo": "coq", "sha": "335711e36628d93d5723d8617b250e90be578d83", "save_path": "github-repos/coq/shij-hsu-coq", "path": "github-repos/coq/shij-hsu-coq/coq-335711e36628d93d5723d8617b250e90be578d83/cpdt/ProofByReflection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7202970002129623}}
{"text": "From Coq Require Import\n  Lia\n  List\n  ZArith.\nFrom FunProofs.Lib Require Import\n  Arith\n  List\n  Tactics.\nFrom FunProofs.Lib Require Export\n  AltMap\n  Extrema\n  Sum.\n\n#[local] Open Scope Z.\n\nSection Geom.\n  Definition geom r n := map (fun x => Z.pow r (Z.of_nat x)) (seq 0 n).\n  Definition tens := geom 10.\n\n  Lemma geom_length r n : length (geom r n) = n.\n  Proof. unfold geom; rewrite map_length, seq_length; auto. Qed.\n\n  Lemma geom_mod r r' n b :\n    b <> 0 ->\n    r mod b = r' mod b ->\n    map (fun x => x mod b) (geom r n) = map (fun x => x mod b) (geom r' n).\n  Proof.\n    unfold geom; intros.\n    erewrite !map_map, map_ext; eauto.\n    intros; apply pow_mod; lia.\n  Qed.\n\n  Lemma geom_one n : geom 1 n = repeat 1 n.\n  Proof.\n    unfold geom; induction n; cbn; auto.\n    rewrite <- seq_shift, map_map, <- IHn.\n    erewrite map_ext; auto.\n    intros; rewrite !Z.pow_1_l; lia.\n  Qed.\n\n  Lemma geom_none n : geom (-1) n = altmap Z.opp (repeat 1 n).\n  Proof.\n    unfold geom; induction n; cbn; auto.\n    rewrite <- seq_shift, map_map.\n    erewrite map_ext with (g := fun x => _).\n    2: intros; rewrite Nat2Z.inj_succ, Z.pow_succ_r by lia.\n    2: rewrite Z.mul_comm, <- Z.opp_eq_mul_m1; eauto.\n    rewrite <- map_map, IHn.\n    clear IHn; induction n; cbn; auto.\n    rewrite <- IHn; cbn; auto.\n    rewrite map_map.\n    erewrite map_ext with (g := fun x => x), map_id; auto using Z.opp_involutive.\n  Qed.\n\n  Lemma geom_zero' n : tl (geom 0 n) = repeat 0 (n - 1).\n  Proof.\n    unfold geom; induction n; cbn; auto.\n    destruct n; auto; cbn -[Z.of_nat].\n    replace (S n - 1)%nat with n in IHn by lia.\n    rewrite <- seq_shift, map_map, <- IHn; cbn -[Z.of_nat].\n    f_equal; apply map_ext_in; intros * Hin.\n    apply in_seq in Hin; rewrite !Z.pow_0_l; lia.\n  Qed.\n\n  Corollary geom_zero n : (0 < n)%nat -> geom 0 n = 1 :: repeat 0 (n - 1).\n  Proof. intros; rewrite <- geom_zero'; now destruct n. Qed.\nEnd Geom.\n", "meta": {"author": "whonore", "repo": "FunProofs", "sha": "f87c0d56670af0903f2a50a52c5f1056703f31cc", "save_path": "github-repos/coq/whonore-FunProofs", "path": "github-repos/coq/whonore-FunProofs/FunProofs-f87c0d56670af0903f2a50a52c5f1056703f31cc/Lib/Series.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7202042371838964}}
{"text": "(** Solutions to exercise sheet for lecture 2: Fundamentals of Coq.\n\nNote that these are just suggestions for solutions and many of the\nproblems can have different solutions. Once you know how to prove\nthings in Coq you can try to prove that your solutions are equivalent\nto the ones in this file.\n\nWritten by Anders Mörtberg.\n\n*)\nRequire Import UniMath.Foundations.Preamble.\nRequire Import fundamentals_lecture.\n\nDefinition idfun : forall (A : UU), A -> A := fun (A : UU) (a : A) => a.\n\nDefinition const (A B : UU) (a : A) (b : B) : A := a.\n\n(** * Booleans *)\n\nDefinition ifbool (A : UU) (x y : A) : bool -> A :=\n  bool_rect (fun _ : bool => A) x y.\n\nDefinition negbool : bool -> bool :=\n  ifbool bool false true.\n\nDefinition andbool (b : bool) : bool -> bool :=\n  ifbool (bool -> bool) (idfun bool) (const bool bool false) b.\n\n(** Exercise: define boolean or: *)\n\nDefinition orbool (b : bool) : bool -> bool :=\n  ifbool (bool -> bool) (const bool bool true) (idfun bool) b.\n\nEval compute in orbool true true.     (* true *)\nEval compute in orbool true false.    (* true *)\nEval compute in orbool false true.    (* true *)\nEval compute in orbool false false.   (* false *)\n\n(** * Natural numbers *)\n\nDefinition nat_rec (A : UU) (a : A) (f : nat -> A -> A) : nat -> A :=\n  nat_rect (fun _ : nat => A) a f.\n\nDefinition even : nat -> bool := nat_rec bool true (fun _ b => negbool b).\n\n(** Exercise: define a function odd that tests if a number is odd *)\nDefinition odd : nat -> bool :=\n  nat_rec bool false (fun _ b => negbool b).\n\nEval compute in odd 24.   (* false *)\nEval compute in odd 19.   (* true *)\n\n\n(** Exercise: define a notation \"myif b then x else y\" for \"ifbool _ x y b\"\nand rewrite negbool and andbool using this notation. *)\n\nNotation \"'myif' b 'then' x 'else' y\" := (ifbool _ x y b) (at level 1).\n\nDefinition negbool' (b : bool) : bool := myif b then false else true.\n\n(* Check that negbool' uses ifbool by disabling printing of notations *)\nUnset Printing Notations.\nPrint negbool'.\nSet Printing Notations.\n\nEval compute in negbool' true.   (* false *)\nEval compute in negbool' false.  (* true *)\n\nDefinition andbool' (b1 b2 : bool) : bool :=\n  myif b1 then b2 else false.\n\nEval compute in andbool true true.    (* true *)\nEval compute in andbool true false.   (* false *)\nEval compute in andbool false true.   (* false *)\nEval compute in andbool false false.  (* false *)\n\n\nDefinition add (m : nat) : nat -> nat := nat_rec nat m (fun _ y => S y).\n\nDefinition iter (A : UU) (a : A) (f : A → A) : nat → A :=\n  nat_rec A a (λ _ y, f y).\n\nNotation \"f ̂ n\" := (λ x, iter _ x f n) (at level 10).\n\nDefinition sub (m n : nat) : nat := pred ̂ n m.\n\n(** Exercise: define addition using iter and S *)\nDefinition add' (m : nat) : nat → nat :=\n  iter nat m S.\n\nEval compute in add' 4 9.   (* 13 *)\n\nDefinition is_zero : nat -> bool := nat_rec bool true (fun _ _ => false).\n\nDefinition eqnat (m n : nat) : bool :=\n  andbool (is_zero (sub m n)) (is_zero (sub n m)).\n\nNotation \"m == n\" := (eqnat m n) (at level 50).\n\n(** Exercises: define <, >, ≤, ≥  *)\n\nDefinition ltnat (m n : nat) : bool := is_zero (sub (S m) n).\n\nNotation \"x < y\" := (ltnat x y).\n\nEval compute in (2 < 3). (* true *)\nEval compute in (3 < 3). (* false *)\nEval compute in (4 < 3). (* false *)\n\n\nDefinition gtnat (m n : nat) : bool := n < m.\n\nNotation \"x > y\" := (gtnat x y).\n\nEval compute in (2 > 3). (* false *)\nEval compute in (3 > 3). (* false *)\nEval compute in (4 > 3). (* true *)\n\n\nDefinition leqnat (m n : nat) : bool := orbool (m < n) (m == n).\n\nNotation \"x ≤ y\" := (leqnat x y) (at level 10).\n\nEval compute in (2 ≤ 3). (* true *)\nEval compute in (3 ≤ 3). (* true *)\nEval compute in (4 ≤ 3). (* false *)\n\n\nDefinition geqnat (m n : nat) : bool := orbool (m > n) (m == n).\n\nNotation \"x ≥ y\" := (geqnat x y) (at level 10).\n\nEval compute in (2 ≥ 3). (* false *)\nEval compute in (3 ≥ 3). (* true *)\nEval compute in (4 ≥ 3). (* true *)\n\n\nDefinition coprod_rec {A B C : UU} (f : A → C) (g : B → C) : A ⨿ B → C :=\n  @coprod_rect A B (λ _, C) f g.\n\n\nDefinition Z : UU := coprod nat nat.\n\nNotation \"⊹ x\" := (inl x) (at level 20).\nNotation \"─ x\" := (inr x) (at level 40).\n\nDefinition Z1 : Z := ⊹ 1.\nDefinition Z0 : Z := ⊹ 0.\nDefinition Zn3 : Z := ─ 2.\n\nDefinition Zcase (A : UU) (fpos : nat → A) (fneg : nat → A) : Z → A :=\n  coprod_rec fpos fneg.\n\nDefinition negate : Z → Z :=\n  Zcase Z (λ x, ifbool Z Z0 (─ pred x) (is_zero x)) (λ x, ⊹ S x).\n\n(* Exercise (harder): define addition for Z *)\n\nDefinition Zadd : Z -> Z -> Z :=\n  Zcase (Z → Z)\n        (λ posn : nat,\n           Zcase Z\n                 (λ posm : nat, ⊹ (posn + posm))\n                 (λ negm : nat,\n                    myif posn ≥ negm then ⊹ (posn - negm)\n                                      else (─ (negm - posn))))\n        (λ negn : nat,\n           Zcase Z\n                 (λ posm : nat,\n                    myif posm ≥ negn then ⊹ (posm - negn)\n                                      else (─ (negn - posm)))\n                 (λ negm : nat, ─ (S negn + negm))).\n\n(* This should satisfy *)\nEval compute in Zadd Z0 Z0.              (* ⊹ 0 *)\nEval compute in Zadd Z1 Z1.              (* ⊹ 2 *)\nEval compute in Zadd Z1 Zn3.             (* ─ 1 *) (* recall that negative numbers are off-by-one *)\nEval compute in Zadd Zn3 Z1.             (* ─ 1 *)\nEval compute in Zadd Zn3 Zn3.            (* ─ 5 *)\nEval compute in Zadd (Zadd Zn3 Zn3) Zn3. (* ─ 8 *)\nEval compute in Zadd Z0 (negate (Zn3)).  (* ⊹ 3 *)\n", "meta": {"author": "UniMath", "repo": "Schools", "sha": "ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b", "save_path": "github-repos/coq/UniMath-Schools", "path": "github-repos/coq/UniMath-Schools/Schools-ab62e1075171b5baf22da1bc1ec1dcb5d8f3ef2b/2019-04-Birmingham/Part2_Fundamentals_Coq/coq_solutions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7202042249423516}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_collinear_ABC_BCA.\nRequire Import ProofCheckingEuclid.lemma_collinear_ABC_BAC.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral}.\n\nLemma lemma_collinearorder :\n\tforall A B C,\n\tCol A B C ->\n\tCol B A C /\\ Col B C A /\\ Col C A B /\\ Col A C B /\\ Col C B A.\nProof.\n\tintros A B C.\n\tintros Col_A_B_C.\n\n\tpose proof (lemma_collinear_ABC_BCA _ _ _ Col_A_B_C) as Col_B_C_A.\n\tpose proof (lemma_collinear_ABC_BCA _ _ _ Col_B_C_A) as Col_C_A_B.\n\tpose proof (lemma_collinear_ABC_BAC _ _ _ Col_A_B_C) as Col_B_A_C.\n\tpose proof (lemma_collinear_ABC_BCA _ _ _ Col_B_A_C) as Col_A_C_B.\n\tpose proof (lemma_collinear_ABC_BCA _ _ _ Col_A_C_B) as Col_C_B_A.\n\n\trepeat split.\n\texact Col_B_A_C.\n\texact Col_B_C_A.\n\texact Col_C_A_B.\n\texact Col_A_C_B.\n\texact Col_C_B_A.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_collinearorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7200783018766542}}
{"text": "(* ************************************************************************** *)\n(*                                                                            *)\n(* Verified Flash Translation Layer                                           *)\n(*                                                                            *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\nRequire Import Lists.List.\nRequire Export Bnat.\n\n(* written by zhanghui *)\nFixpoint list_append {A: Set} (l: list A) (a: A) : list A :=\n  match l with\n    | nil => cons a nil\n    | cons x l' => cons x (list_append l' a)\n  end.\n\nFixpoint list_none {A: Set} (n: nat) : list (option A) :=\n  match n with \n    | O => nil\n    | S n => cons None (list_none n)\n  end.\n\n(* written by zhanghui *)\nFixpoint list_repeat {A: Set} (n : nat) (elem : A) : list A :=\n  match n with\n    | O => nil\n    | S n' => cons elem (list_repeat n' elem)\n  end.\n\nFixpoint list_get {A: Set} (l: list A) (i: nat) : option A :=\n  match i, l with \n    | O, cons a l' => Some a\n    | S i', cons a l' => list_get l' i'\n    | _, _ => None\n  end.\n\nFixpoint list_set {A: Set} (l: list A) (i: nat) (a: A): option (list A) :=\n  match i, l with\n    | O, cons a' l' => Some (cons a l')\n    | S i', cons a' l' => \n      match list_set l' i' a with\n        | None => None \n        | Some l'' => Some (cons a' l'')\n      end\n    | _, _ => None\n  end.\n\nFixpoint list_find_aux {A:Set} (beq_a: A->A->bool) (l:list A) (a: A) (i: nat) : option nat :=\n  match l with \n    | nil => None\n    | cons a' l' => match beq_a a a' with\n                      | true => Some i\n                      | false => list_find_aux beq_a l' a (S i) \n                    end\n  end.\n\nDefinition list_find {A:Set} (beq_a: A->A->bool) (l:list A) (a: A) : option nat :=\n  list_find_aux beq_a l a O.\n\nFixpoint list_find_rev_aux {A:Set} (beq_a: A->A->bool) (l:list A) (a: A) (i: nat) : option nat :=\n  match l with \n    | nil => None\n    | cons a' l' => match list_find_rev_aux beq_a l' a (S i) with \n                      | Some i' => Some i'\n                      | None => match beq_a a a' with\n                                  | true => Some i\n                                  | false => None \n                                end\n                    end\n  end.\n\nDefinition list_find_rev {A:Set} (beq_a: A->A->bool) (l:list A) (a: A): option nat :=\n  list_find_rev_aux beq_a l a O.\n\n(* Eval compute in (list_find beq_nat (0::1::99::3::4::5::99::7::nil) 99). *)\n(* Eval compute in (list_find_rev beq_nat (0::1::99::3::4::5::99::7::nil) 99). *)\n\nFixpoint list_find_min {A: Set} (l: list A) (pred: A -> A -> option bool) : option A :=\n  match l with\n    | nil => None\n    | cons x nil => Some x\n    | cons x l' =>\n      match list_find_min l' pred with\n        | None => None\n        | Some m =>\n          match pred x m with\n            | None => None\n            | Some b =>\n              match b with\n                | true => Some x\n                | false => Some m\n              end\n          end\n      end\n  end. \n\nDefinition blt_nat_opt (n1 n2 : nat) : option bool :=\n  Some (ble_nat n1 n2).\n\nDefinition test_list_1 := (11::22::33::44::55::88::66::77::88::9::nil).\nExample list_find_min_test1 : list_find_min test_list_1 blt_nat_opt = Some 9.\nProof. reflexivity. Qed.\n\nDefinition list_find_min_index {A: Set} (l: list A) (pred_min: A -> A -> option bool)\n           (pred_eq: A -> A -> bool): option nat :=\n  match list_find_min l pred_min with\n    | None => None\n    | Some a =>\n      list_find pred_eq l a\n  end.\n\nExample list_find_min_index_test1 : list_find_min_index test_list_1 blt_nat_opt beq_nat = Some 9.\nProof. reflexivity. Qed.\n\nFixpoint list_in {A: Set} (beq_a: A->A->bool) (l: list A) (a : A) : bool :=\n  match l with \n    | nil => false\n    | cons a' l' => match beq_a a a' with\n                      | true => true\n                      | false => list_in beq_a l' a \n                    end\n  end.\n\nLemma list_set_length_preserv: \n  forall {A: Set} (l:list A) i l' (a: A),\n    blt_nat i (length l) = true\n    -> list_set l i a = Some l'\n    -> length l' = length l.\nProof.\n  intro A.\n  induction l; destruct i; simpl; intros.\n    discriminate.\n    discriminate.\n  destruct l' as [ | a' l'].\n  discriminate.\n  inversion H0.\n  subst a0 l'.\n  simpl; trivial.\n  destruct l' as [ | a' l'].\n  destruct (list_set l i a0).\n    inversion H0.\n    discriminate.\n  simpl.\n  remember (list_set l i a0) as x.\n  destruct x.\n  inversion H0; subst.\n  assert (length l' = length l).\n    eapply IHl; eauto.\n  auto with arith.\n  discriminate.\nQed.                                    \n", "meta": {"author": "vittayang", "repo": "coqnand", "sha": "dd538809cf926e04d8de9912521d4e2dfc32189e", "save_path": "github-repos/coq/vittayang-coqnand", "path": "github-repos/coq/vittayang-coqnand/coqnand-dd538809cf926e04d8de9912521d4e2dfc32189e/new/ListEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619959279793, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.720071518708019}}
{"text": "(** Experimental !!!! *)\n(** This file is a draft !!! *)\n\n(*\nhttps://math-comp.github.io/htmldoc_1_14_0/mathcomp.ssreflect.choice.html\n\nhttps://github.com/math-comp/math-comp/blob/master/mathcomp/ssreflect/order.v\n *)\n\n\nFrom mathcomp Require Import all_ssreflect zify.\nFrom Coq Require Import Logic.Eqdep_dec.\nFrom hydras Require Import DecPreOrder ON_Generic  T1 E0.\nFrom gaia Require Export ssete9.\nRequire Import T1Bridge.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n\n(**  Type [T1] vs generic trees *)\n\nFixpoint T12Tree (a: T1): GenTree.tree nat :=\n  if a is cons b n c\n  then GenTree.Node n [:: T12Tree b; T12Tree c]\n  else GenTree.Leaf 0.                                        \n\nFixpoint Tree2T1 (t: GenTree.tree nat): option T1 :=\n  match t with\n  | GenTree.Leaf 0 => Some zero\n  | GenTree.Node n [:: t1; t2] =>\n      match Tree2T1 t1, Tree2T1 t2 with\n      | Some b, Some c => Some (cons b n c)\n      | _, _ => None\n      end\n  | _ => None\n  end.\n\nLemma TreeT1K : pcancel T12Tree Tree2T1. \nProof. \n  elim => // t Ht n t0 Ht0 /=; by rewrite Ht0 Ht. \nQed.                                              \n\n(** to remove (useless) *)\nLemma  T12Tree_inj: injective T12Tree.   \nProof.\n  move => t1 t2 Heq.\n  have H: Some t1 = Some t2 by rewrite -!TreeT1K Heq. \n  by injection H. \nQed.\n\nDefinition T1mixin :\n  Countable.mixin_of T1 := PcanCountMixin TreeT1K.\n\n\n\nCanonical T1Choice :=\n  Eval hnf in ChoiceType T1 (CountChoiceMixin T1mixin).\n\nExample ex_pos: exists alpha: T1, zero != alpha. \nProof. exists (cons zero 0 zero) => //. Qed. \n\nExample some_pos: T1 := xchoose ex_pos. \n\nExample some_pos' : T1 := choose (fun p : T1 => zero != p)\n                                 T1omega.\n\nGoal (zero: T1Choice) != some_pos'.\n  pose p a := (zero != a); move: (@chooseP _ p T1omega).\n  rewrite /p /some_pos' => H; by apply: H. \nQed.\n\nCompute  [eqType of T1].\n(**    = EqType T1 (EqMixin (@T1eqP))\n     : eqType *)\n\nCompute  [choiceType of T1]. \n\n(**\n   = Choice.Pack\n         {|\n           Choice.base := EqMixin (@T1eqP);\n           Choice.mixin := PcanChoiceMixin (pcan_pickleK TreeT1K)\n         |}\n     : choiceType\n\n*)\n\nDefinition T1_le_Mixin := leOrderMixin T1Choice.\n\nDefinition T1min a b := if T1lt a b then a else b. \nDefinition T1max a b := if T1lt a b then b else a. \n\nLemma T1ltE x y : T1lt x y = (y != x) && T1le x y.\nProof. by rewrite T1lt_neAle eq_sym. Qed. \n\nLemma T1minE x y : T1min x y = (if T1lt x y then x else y).\nProof. done. Qed. \n\nLemma T1maxE x y : T1max x y = (if T1lt x y then y else x).\nProof. done. Qed. \n\nLemma T1le_asym: ssrbool.antisymmetric T1le.\nProof. move => x y;  by rewrite -T1eq_le =>/eqP. Qed.\n\n\nDefinition T1leOrderMixin : leOrderMixin T1Choice :=\n  LeOrderMixin T1ltE T1minE T1maxE T1le_asym T1le_trans T1le_total.\n\nCanonical T1orderType :=\n  @OrderOfChoiceType tt T1Choice T1leOrderMixin.\n\nGoal @Order.le tt T1orderType T1omega T1omega.\nby rewrite Order.POrderTheory.lexx.\nQed.\n\nCheck T1omega: T1orderType. \n\nGoal ((T1omega:T1orderType) <= (T1omega:T1orderType))%O. \ndone.\nQed. \n\n\n\nNotation \"x <= y\" := (@Order.le _ T1orderType  x y).\n\nNotation \"x < y\" := (@Order.lt _ T1orderType  x y).\n\nAbout Order.le. \n\n\nGoal @Order.le tt T1orderType T1omega T1omega.\napply Order.POrderTheory.lexx. \nQed. \nImport Order.POrderTheory.\n\nGoal T1omega <= T1omega. \nSet Printing All.\napply lexx. \nQed.\n\nGoal T1omega < T1succ T1omega.\nby [].\nQed. \n\n\n\nFail Goal  ~~ (<%O T1omega T1omega).\n\nGoal  ~~ (<%O (T1omega:T1orderType) (T1omega:T1orderType)).\nby cbn. Qed.\n\n\nGoal ~~(T1omega < T1omega).\nby cbn.   \nQed. \n\n\nCompute Order.POrder.sort T1orderType. \nGoal ~~ @Order.lt tt (T1orderType) T1omega T1omega.\nby cbn. \nQed. \n\n\nGoal T1omega <= T1omega. \nby []. \nQed. \n\nFail Goal Order.max T1omega T1omega == T1omega.\n\n\nPrint E0.\n\n(* Check [subCountType of T1]. *)\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/gaia/T1Choice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.720071500165433}}
{"text": "Require Export vectors.\nRequire Import notations decidables Setoid Morphisms.\n\nDefinition matr A rows cols := fin rows -> fin cols -> A.\nDefinition matr_eq {A rows cols} (M1 M2: matr A rows cols) := forall i j, M1 i j = M2 i j.\n\nDefinition matr_row {A rows cols} (i: fin rows) (M: matr A rows cols): vect A cols := fun j => M i j.\nDefinition matr_col {A rows cols} (j: fin cols) (M: matr A rows cols): vect A rows := fun i => M i j.\n\nDefinition matr_transpose {A rows cols} (M: matr A rows cols): matr A cols rows := fun i j => M j i.\n\nDefinition remove_row {A rows cols} (num: fin (S rows)) (M: matr A (S rows) cols): matr A rows cols :=\n fun i j => if le_dec i.1 num.1 then M (le_to_fin (le_S _ _ i.2)) j else M (le_to_fin (Le.le_n_S _ _ i.2)) j.\nDefinition remove_col {A rows cols} (num: fin (S cols)) (M: matr A rows (S cols)): matr A rows cols :=\n fun i j => if le_dec j.1 num.1 then M i (le_to_fin (le_S _ _ j.2)) else M i (le_to_fin (Le.le_n_S _ _ j.2)).\n\n\nInstance matr_eq_Equiv A n: Equivalence (vect_eq (A:=A) (n:=n)).\n split; unfold Reflexive, Symmetric, Transitive, matr_eq; congruence.\nQed.\nInstance matr_row_Proper A rows cols i: Proper (matr_eq ==> vect_eq) (matr_row (A:=A) (rows:=rows) (cols:=cols) i).\n unfold Proper, respectful, matr_eq, vect_eq, matr_row; auto.\nQed.\nInstance matr_col_Proper A rows cols i: Proper (matr_eq ==> vect_eq) (matr_col (A:=A) (rows:=rows) (cols:=cols) i).\n unfold Proper, respectful, matr_eq, vect_eq, matr_col; auto.\nQed.\nInstance matr_transpose_Proper A rows cols: Proper (matr_eq ==> matr_eq) (matr_transpose (A:=A) (rows:=rows) (cols:=cols)).\n unfold Proper, respectful, matr_eq, matr_transpose; auto.\nQed.\nInstance remove_row_Proper A rows cols num: Proper (matr_eq ==> matr_eq) (remove_row (A:=A) (rows:=rows) (cols:=cols) num).\n unfold Proper, respectful, matr_eq, remove_row; intros; repeat destruct le_dec; auto.\nQed.\nInstance remove_col_Proper A rows cols num: Proper (matr_eq ==> matr_eq) (remove_col (A:=A) (rows:=rows) (cols:=cols) num).\n unfold Proper, respectful, matr_eq, remove_col; intros; repeat destruct le_dec; auto.\nQed.\n\n", "meta": {"author": "zaarcis", "repo": "linear_algebra_in_Coq", "sha": "9d091fbe61b6895f8e9e2b486e44827cd4c959dc", "save_path": "github-repos/coq/zaarcis-linear_algebra_in_Coq", "path": "github-repos/coq/zaarcis-linear_algebra_in_Coq/linear_algebra_in_Coq-9d091fbe61b6895f8e9e2b486e44827cd4c959dc/matrices.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7200625524244362}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** Implement an instance of equality type for the [seq] datatype *)\n\n\n\n(** Take apart the following proof: *)\nLemma size_eq0 (T : eqType) (s : seq T) :\n  (size s == 0) = (s == [::]).\nProof. exact: (sameP nilP eqP). Qed.\n\n\n\nLemma filter_all T (a : pred T) s :\n  all a (filter a s).\nAdmitted.\n\nLemma filter_id T (a : pred T) s :\n  filter a (filter a s) = filter a s.\nAdmitted.\n\nLemma all_count T (a : pred T) s :\n  all a s = (count a s == size s).\nAdmitted.\n\nLemma all_predI T (a1 a2 : pred T) s :\n  all (predI a1 a2) s = all a1 s && all a2 s.\nAdmitted.\n\nLemma allP (T : eqType) {a : pred T} {s : seq T} :\n  reflect {in s, forall x, a x} (all a s).\n(* Hint 1: *)\n(* rewrite /prop_in1. *)\n\n(* Hint 2a and 2b: *)\n(* Check erefl : 1 \\in [:: 3; 2; 1; 0] = true. *)\n(* Check erefl : 42 \\in [:: 3; 2; 1; 0] = false. *)\nAdmitted.\n\nLemma sub_find T (a1 a2 : pred T) s :\n  subpred a1 a2 ->\n  find a2 s <= find a1 s.\nAdmitted.\n\nLemma take_nseq T n m (x : T) : take n (nseq m x) = nseq (minn n m) x.\nAdmitted.\n\nLemma rev_nseq A n (x : A) : rev (nseq n x) = nseq n x.\nAdmitted.\n\n(* Hint: use mapP *)\nLemma mem_map (T1 T2 : eqType) (f : T1 -> T2) x s :\n  injective f ->\n  (f x \\in map f s) = (x \\in s).\nAdmitted.\n\n(* Double induction principle *)\nLemma seq_ind2 {S T} (P : seq S -> seq T -> Type) :\n    P [::] [::] ->\n    (forall x y s t, size s = size t -> P s t -> P (x :: s) (y :: t)) ->\n  forall s t, size s = size t -> P s t.\nAdmitted.\n\n(* Hint: use seq_ind2 to prove the following *)\nLemma rev_zip S T (s : seq S) (t : seq T) :\n  size s = size t -> rev (zip s t) = zip (rev s) (rev t).\nAdmitted.\n\nLemma last_ind T (P : seq T -> Prop) :\n  P [::] -> (forall s x, P s -> P (rcons s x)) -> forall s, P s.\nAdmitted.\n\n(* Hint: use last_ind to prove the following *)\nLemma nth_rev T (x0 : T) n (s : seq T) :\n  n < size s -> nth x0 (rev s) n = nth x0 s (size s - n.+1).\nAdmitted.\n\n\n", "meta": {"author": "anton-trunov", "repo": "coq-lecture-notes", "sha": "e012addae82da6d8d03f6e789e43f35140dcdfea", "save_path": "github-repos/coq/anton-trunov-coq-lecture-notes", "path": "github-repos/coq/anton-trunov-coq-lecture-notes/coq-lecture-notes-e012addae82da6d8d03f6e789e43f35140dcdfea/homework/hw06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218864, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7200625371887989}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (y : natural) (lf2 : natural) : natural :=\n  mult (Succ y) lf3.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj172_coqofml_gkqGXB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7199639853723752}}
{"text": "(** * 6.887 Formal Reasoning About Programs - Lab 4\n    * Abstract Interpretation *)\n\nRequire Import Frap Imp.\n\n(* Authors: Adam Chlipala (adamc@csail.mit.edu), Peng Wang (wangpeng@csail.mit.edu) *)\n\nSet Implicit Arguments.\n\n\n(* In lecture, we saw a very general abstract-interpretation framework, but it\n * had one important weakness (among others): it always ignores conditional\n * expressions, so we get significant imprecision in modeling \"if\" and \"while.\"\n * This lab is all about\n * (1) extending the framework to analyze conditionals;\n * (2) extending the example even-odd interpretation for the new framework; and\n * (3) verifying a particular program automatically, where the old framework\n *     would fail because of precision loss. *)\n\n(* FIRST, here's our old definition of an abstract interpretation.  In fact,\n * this fill is an already-compiling excerpt of the code from lecture, with some\n * comments indicating changes that we'd like you to make.  Your highly\n * strenuous first task is to uncomment the *two new record fields* below, which\n * provide the extra information for sound abstract interpretation of\n * conditionals. *)\nRecord absint := {\n  Domain :> Set;\n  (* We will represent concrete values (natural numbers) with this alternative,\n   * abstract set.  This [:>] notation lets us treat any [absint] as its\n   * [Domain], automatically.  See below for examples (e.g., return type of\n   * [absint_interp]). *)\n  Top : Domain;\n  (* A universal (least informative) element, describing *all* concrete\n   * values *)\n  Constant : nat -> Domain;\n  (* Most accurate representation of a constant *)\n  Add : Domain -> Domain -> Domain;\n  Subtract : Domain -> Domain -> Domain;\n  Multiply : Domain -> Domain -> Domain;\n  (* Abstract versions of arithmetic operators *)\n  Join : Domain -> Domain -> Domain;\n  (* Returns some new element that covers all cases of each of its inputs *)\n  Represents : nat -> Domain -> Prop\n  (* Which elements represent which numbers? *)\n\n  (* UNCOMMENT THIS PART TO START THE LAB! *)\n(*;\n  (* Given our knowledge of a value, could it possibly be zero or nonzero? *)\n  CouldBeZero : Domain -> bool;\n  CouldBeNonzero : Domain -> bool\n*)\n}.\n\n(* CHALLENGE #1: Add new algebraic laws to this soundness condition, sufficient\n * to enable you to prove the theorems from later challenges.  You may find\n * yourself returning here frequently as you work on those proofs, when you find\n * you need a new law! *)\nRecord absint_sound (a : absint) : Prop := {\n  TopSound : forall n, a.(Represents) n a.(Top);\n\n  ConstSound : forall n, a.(Represents) n (a.(Constant) n);\n\n  AddSound : forall n na m ma, a.(Represents) n na\n                               -> a.(Represents) m ma\n                               -> a.(Represents) (n + m) (a.(Add) na ma);\n  SubtractSound: forall n na m ma, a.(Represents) n na\n                                   -> a.(Represents) m ma\n                                   -> a.(Represents) (n - m) (a.(Subtract) na ma);\n  MultiplySound : forall n na m ma, a.(Represents) n na\n                                    -> a.(Represents) m ma\n                                    -> a.(Represents) (n * m) (a.(Multiply) na ma);\n\n  AddMonotone : forall na na' ma ma', (forall n, a.(Represents) n na -> a.(Represents) n na')\n                                      -> (forall n, a.(Represents) n ma -> a.(Represents) n ma')\n                                      -> (forall n, a.(Represents) n (a.(Add) na ma)\n                                                    -> a.(Represents) n (a.(Add) na' ma'));\n  SubtractMonotone : forall na na' ma ma', (forall n, a.(Represents) n na -> a.(Represents) n na')\n                                           -> (forall n, a.(Represents) n ma -> a.(Represents) n ma')\n                                           -> (forall n, a.(Represents) n (a.(Subtract) na ma)\n                                                         -> a.(Represents) n (a.(Subtract) na' ma'));\n  MultiplyMonotone : forall na na' ma ma', (forall n, a.(Represents) n na -> a.(Represents) n na')\n                                           -> (forall n, a.(Represents) n ma -> a.(Represents) n ma')\n                                           -> (forall n, a.(Represents) n (a.(Multiply) na ma)\n                                                         -> a.(Represents) n (a.(Multiply) na' ma'));\n\n  JoinSoundLeft : forall x y n, a.(Represents) n x\n                                -> a.(Represents) n (a.(Join) x y);\n  JoinSoundRight : forall x y n, a.(Represents) n y\n                                 -> a.(Represents) n (a.(Join) x y)\n}.\n\n(* Let's ask [eauto] to try all of the above soundness rules automatically. *)\nHint Resolve TopSound ConstSound AddSound SubtractSound MultiplySound\n     AddMonotone SubtractMonotone MultiplyMonotone\n     JoinSoundLeft JoinSoundRight.\n\n\n(** * Example: even-odd analysis *)\n\n(* CHALLENGE #2: Extend this even-odd section to work with the new definition.\n * That is, both fill in the new record fields and prove that the extended\n * record is a sound abstract interpretation, starting from the proofs already\n * in place for the old version. *)\n\nInductive parity := Even | Odd | Either.\n\nDefinition isEven (n : nat) := exists k, n = k * 2.\nDefinition isOdd (n : nat) := exists k, n = k * 2 + 1.\n\n(* BEGIN SPAN OF BORING THEOREMS ABOUT PARITY, WHICH WE WON'T EXPLAIN. *)\n\nTheorem decide_parity : forall n, isEven n \\/ isOdd n.\nProof.\n  induct n; simplify; propositional.\n\n  left; exists 0; linear_arithmetic.\n\n  invert H.\n  right.\n  exists x; linear_arithmetic.\n\n  invert H.\n  left.\n  exists (x + 1); linear_arithmetic.\nQed.\n\nTheorem notEven_odd : forall n, ~isEven n -> isOdd n.\nProof.\n  simplify.\n  assert (isEven n \\/ isOdd n).\n  apply decide_parity.\n  propositional.\nQed.\n\nTheorem odd_notEven : forall n, isOdd n -> ~isEven n.\nProof.\n  propositional.\n  invert H.\n  invert H0.\n  linear_arithmetic.\nQed.\n\nTheorem isEven_0 : isEven 0.\nProof.\n  exists 0; linear_arithmetic.\nQed.\n\nTheorem isEven_1 : ~isEven 1.\nProof.\n  propositional; invert H; linear_arithmetic.\nQed.\n\nTheorem isEven_S_Even : forall n, isEven n -> ~isEven (S n).\nProof.\n  propositional; invert H; invert H0; linear_arithmetic.\nQed.\n\nTheorem isEven_S_Odd : forall n, ~isEven n -> isEven (S n).\nProof.\n  propositional.\n  apply notEven_odd in H.\n  invert H.\n  exists (x + 1); linear_arithmetic.\nQed.\n\nHint Resolve isEven_0 isEven_1 isEven_S_Even isEven_S_Odd.  \n\n(* END SPAN OF BORING THEOREMS ABOUT PARITY. *)\n\n(* Next, we are ready to implement the operators of the abstract\n * interpretation. *)\n\nDefinition parity_flip (p : parity) :=\n  match p with\n  | Even => Odd\n  | Odd => Even\n  | Either => Either\n  end.\n\nFixpoint parity_const (n : nat) :=\n  match n with\n  | O => Even\n  | S n' => parity_flip (parity_const n')\n  end.\n\nDefinition parity_add (x y : parity) :=\n  match x, y with\n  | Even, Even => Even\n  | Odd, Odd => Even\n  | Even, Odd => Odd\n  | Odd, Even => Odd\n  | _, _ => Either\n  end.\n\nDefinition parity_subtract (x y : parity) :=\n  match x, y with\n  | Even, Even => Even\n  | _, _ => Either\n  end.\n(* Note subtleties with [Either]s above, to deal with underflow at zero! *)\n\nDefinition parity_multiply (x y : parity) :=\n  match x, y with\n  | Even, _ => Even\n  | Odd, Odd => Odd\n  | _, Even => Even\n  | _, _ => Either\n  end.\n\nDefinition parity_join (x y : parity) :=\n  match x, y with\n  | Even, Even => Even\n  | Odd, Odd => Odd\n  | _, _ => Either\n  end.\n\n(* What does it mean for a parity to classify a number correctly? *)\nInductive parity_rep : nat -> parity -> Prop :=\n| PrEven : forall n,\n  isEven n\n  -> parity_rep n Even\n| PrOdd : forall n,\n  ~isEven n\n  -> parity_rep n Odd\n| PrEither : forall n,\n  parity_rep n Either.\n\nHint Constructors parity_rep.\n\n(* Putting it all together: *)\nDefinition parity_absint := {|\n  Top := Either;\n  Constant := parity_const;\n  Add := parity_add;\n  Subtract := parity_subtract;\n  Multiply := parity_multiply;\n  Join := parity_join;\n  Represents := parity_rep\n|}.\n\n(* Now we prove soundness. *)\n\nLemma parity_const_sound : forall n,\n  parity_rep n (parity_const n).\nProof.\n  induct n; simplify; eauto.\n  cases (parity_const n); simplify; eauto.\n  invert IHn; eauto.\n  invert IHn; eauto.\nQed.\n\nHint Resolve parity_const_sound.\n\nLemma even_not_odd :\n  (forall n, parity_rep n Even -> parity_rep n Odd)\n  -> False.\nProof.\n  simplify.\n  specialize (H 0).\n  assert (parity_rep 0 Even) by eauto.\n  apply H in H0.\n  invert H0.\n  apply H1.\n  auto.\nQed.\n\nLemma odd_not_even :\n  (forall n, parity_rep n Odd -> parity_rep n Even)\n  -> False.\nProof.\n  simplify.\n  specialize (H 1).\n  assert (parity_rep 1 Odd) by eauto.\n  apply H in H0.\n  invert H0.\n  invert H1.\n  linear_arithmetic.\nQed.\n\nHint Resolve even_not_odd odd_not_even.\n\nLemma parity_join_complete : forall n x y,\n  parity_rep n (parity_join x y)\n  -> parity_rep n x \\/ parity_rep n y.\nProof.\n  simplify; cases x; cases y; simplify; propositional.\n  assert (isEven n \\/ isOdd n) by apply decide_parity.\n  propositional; eauto using odd_notEven.\n  assert (isEven n \\/ isOdd n) by apply decide_parity.\n  propositional; eauto using odd_notEven.\nQed.\n\nHint Resolve parity_join_complete.\n\n(* The final proof uses some automation that we won't explain, to descend down\n * to the hearts of the interesting cases. *)\n\nTheorem parity_sound : absint_sound parity_absint.\nProof.\n  constructor; simplify; eauto;\n  repeat match goal with\n         | [ H : parity_rep _ _ |- _ ] => invert H\n         | [ H : ~isEven _ |- _ ] => apply notEven_odd in H; invert H\n         | [ H : isEven _ |- _ ] => invert H\n         | [ p : parity |- _ ] => cases p; simplify; try equality\n         end; try solve [ exfalso; eauto ]; try (constructor; try apply odd_notEven).\n\n  (* We finish up by instantiating all those existential quantifiers in uses of\n   * [isEven] and [isOdd]. *)\n  exists (x0 + x); ring.\n  exists (x0 + x); ring.\n  exists (x0 + x); ring.\n  exists (x0 + x + 1); ring.\n  exists (x - x0); linear_arithmetic.\n  exists (x * x0 * 2); ring.\n  exists ((x * 2 + 1) * x0); ring.\n  exists (n * x); ring.\n  exists ((x * 2 + 1) * x0); ring.\n  exists (2 * x * x0 + x + x0); ring.\n  exists (x * m); ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x; ring.\n  exists x0; ring.\n  exists x0; ring.\nQed.\n\n\n(** * Interpreting expressions *)\n\n(* Now we're back to the general framework.  Here's an unchanged expression\n * abstract interpreter and its proof.  Feel free to skip ahead to\n * \"HERE NEXT.\" *)\n\nDefinition astate (a : absint) := fmap var a.\n\nFixpoint absint_interp (e : arith) a (s : astate a) : a :=\n  match e with\n  | Const n => a.(Constant) n\n  | Var x => match s $? x with\n             | None => a.(Top)\n             | Some xa => xa\n             end\n  | Plus e1 e2 => a.(Add) (absint_interp e1 s) (absint_interp e2 s)\n  | Minus e1 e2 => a.(Subtract) (absint_interp e1 s) (absint_interp e2 s)\n  | Times e1 e2 => a.(Multiply) (absint_interp e1 s) (absint_interp e2 s)\n  end.\n\nDefinition merge_astate a : astate a -> astate a -> astate a :=\n  merge (fun x y =>\n           match x with\n           | None => None\n           | Some x' =>\n             match y with\n             | None => None\n             | Some y' => Some (a.(Join) x' y')\n             end\n           end).\n\nDefinition subsumed a (s1 s2 : astate a) :=\n  forall x, match s1 $? x with\n            | None => s2 $? x = None\n            | Some xa1 =>\n              forall xa2, s2 $? x = Some xa2\n                          -> forall n, a.(Represents) n xa1\n                                       -> a.(Represents) n xa2\n            end.\n\nTheorem subsumed_refl : forall a (s : astate a),\n  subsumed s s.\nProof.\n  unfold subsumed; simplify.\n  cases (s $? x); equality.\nQed.\n\nHint Resolve subsumed_refl.\n\nLemma subsumed_use : forall a (s s' : astate a) x n t0 t,\n  s $? x = Some t0\n  -> subsumed s s'\n  -> s' $? x = Some t\n  -> Represents a n t0\n  -> Represents a n t.\nProof.\n  unfold subsumed; simplify.\n  specialize (H0 x).\n  rewrite H in H0.\n  eauto.\nQed.\n\nLemma subsumed_use_empty : forall a (s s' : astate a) x n t0 t,\n  s $? x = None\n  -> subsumed s s'\n  -> s' $? x = Some t\n  -> Represents a n t0\n  -> Represents a n t.\nProof.\n  unfold subsumed; simplify.\n  specialize (H0 x).\n  rewrite H in H0.\n  equality.\nQed.\n\nHint Resolve subsumed_use subsumed_use_empty.\n\nLemma subsumed_trans : forall a (s1 s2 s3 : astate a),\n  subsumed s1 s2\n  -> subsumed s2 s3\n  -> subsumed s1 s3.\nProof.\n  unfold subsumed; simplify.\n  specialize (H x); specialize (H0 x).\n  cases (s1 $? x); simplify.\n  cases (s2 $? x); eauto.\n  cases (s2 $? x); eauto.\n  equality.\nQed.\n\nLemma subsumed_merge_left : forall a, absint_sound a\n  -> forall s1 s2 : astate a,\n    subsumed s1 (merge_astate s1 s2).\nProof.\n  unfold subsumed, merge_astate; simplify.\n  cases (s1 $? x); trivial.\n  cases (s2 $? x); simplify; try equality.\n  invert H0; eauto.\nQed.\n\nHint Resolve subsumed_merge_left.\n\nLemma subsumed_add : forall a, absint_sound a\n  -> forall (s1 s2 : astate a) x v1 v2,\n  subsumed s1 s2\n  -> (forall n, a.(Represents) n v1 -> a.(Represents) n v2)\n  -> subsumed (s1 $+ (x, v1)) (s2 $+ (x, v2)).\nProof.\n  unfold subsumed; simplify.\n  cases (x ==v x0); subst; simplify; eauto.\n  invert H2; eauto.\n  specialize (H0 x0); eauto.\nQed.\n\nHint Resolve subsumed_add.\n\nDefinition compatible a (s : astate a) (v : valuation) : Prop :=\n  forall x xa, s $? x = Some xa\n               -> exists n, v $? x = Some n\n                            /\\ a.(Represents) n xa.\n\nLemma compatible_add : forall a (s : astate a) v x na n,\n  compatible s v\n  -> a.(Represents) n na\n  -> compatible (s $+ (x, na)) (v $+ (x, n)).\nProof.\n  unfold compatible; simplify.\n  cases (x ==v x0); simplify; eauto.\n  invert H1; eauto.\nQed.\n\nHint Resolve compatible_add.\n\nTheorem absint_interp_ok : forall a, absint_sound a\n  -> forall (s : astate a) v e,\n    compatible s v\n    -> a.(Represents) (interp e v) (absint_interp e s).\nProof.\n  induct e; simplify; eauto.\n  cases (s $? x); auto.\n  unfold compatible in H0.\n  apply H0 in Heq.\n  invert Heq.\n  propositional.\n  rewrite H2.\n  assumption.\nQed.\n\nHint Resolve absint_interp_ok.\n\n\n(** * Flow-sensitive analysis *)\n\nDefinition astates (a : absint) := fmap cmd (astate a).\n\n(* HERE NEXT!  CHALLENGE #2: Extend the old command stepper to model\n * conditionals more precisely. *)\n\nFixpoint absint_step a (s : astate a) (c : cmd) (wrap : cmd -> cmd) : option (astates a) :=\n  match c with\n  | Skip => None\n  | Assign x e => Some ($0 $+ (wrap Skip, s $+ (x, absint_interp e s)))\n  | Sequence c1 c2 =>\n    match absint_step s c1 (fun c => wrap (Sequence c c2)) with\n    | None => Some ($0 $+ (wrap c2, s))\n    | v => v\n    end\n  | If _ then_ else_ => Some ($0 $+ (wrap then_, s) $+ (wrap else_, s))\n  | While e body => Some ($0 $+ (wrap Skip, s) $+ (wrap (Sequence body (While e body)), s))\n  end.\n\n(* CHALLENGE #3: Update all of the theorems and lemmas below to work in the new\n * world.  Only their proofs, not their statements, will need changes; and only\n * a few of them need updating at all.  We suggest optimistically powering\n * through with the existing proofs, getting Coq to tell you when changes are\n * needed.\n * One tactic hint: you will face many goals of the form [subsumeds s s'], for\n * more specific values of [s] and [s'].  When the structures of the two sides\n * match up well, repeated application of [subsumeds_add] and [subsumeds_empty]\n * finishes the proof, and [eauto] will even do all that for you.  Sometimes the\n * structures of the two sides don't match up well, but you can rewrite the goal\n * so that the match is obvious.  For instance, if you're starting at this goal:\n *   [subsumeds ($0 $+ (a, n)) ($0 $+ (a, n) $+ (b, m))]\n * It will be helpful to run:\n *   [replace ($0 $+ (a, n) $+ (b, m)) with ($0 $+ (b, m) $+ (a, n)) by maps_equal.]\n * Afterward, [eauto] can finish the subgoal! *)\n\nLemma command_equal : forall c1 c2 : cmd, sumbool (c1 = c2) (c1 <> c2).\nProof.\n  repeat decide equality.\nQed.\n\nTheorem absint_step_ok : forall a, absint_sound a\n  -> forall (s : astate a) v, compatible s v\n  -> forall c v' c', step (v, c) (v', c')\n                     -> forall wrap, exists ss s', absint_step s c wrap = Some ss\n                                                   /\\ ss $? wrap c' = Some s'\n                                                   /\\ compatible s' v'.\nProof.\n  induct 2; simplify.\n\n  do 2 eexists; propositional.\n  simplify; equality.\n  eauto.\n\n  eapply IHstep in H0; auto.\n  invert H0.\n  invert H2.\n  propositional.\n  rewrite H2.\n  eauto.\n\n  do 2 eexists; propositional.\n  simplify; equality.\n  assumption.\n\n  do 2 eexists; propositional.\n  cases (command_equal (wrap c') (wrap else_)).\n  simplify; equality.\n  simplify; equality.\n  assumption.\n\n  do 2 eexists; propositional.\n  simplify; equality.\n  assumption.\n\n  do 2 eexists; propositional.\n  simplify; equality.\n  assumption.\n\n  do 2 eexists; propositional.\n  cases (command_equal (wrap Skip) (wrap (body;; while e loop body done))).\n  simplify; equality.\n  simplify; equality.\n  assumption.\nQed.\n\nInductive abs_step a : astate a * cmd -> astate a * cmd -> Prop :=\n| AbsStep : forall s c ss s' c',\n  absint_step s c (fun x => x) = Some ss\n  -> ss $? c' = Some s'\n  -> abs_step (s, c) (s', c').\n\nHint Constructors abs_step.\n\nDefinition absint_trsys a (c : cmd) := {|\n  Initial := {($0, c)};\n  Step := abs_step (a := a)\n|}.\n\nInductive Rabsint a : valuation * cmd -> astate a * cmd -> Prop :=\n| RAbsint : forall v s c,\n  compatible s v\n  -> Rabsint (v, c) (s, c).\n\nHint Constructors abs_step Rabsint.\n\nTheorem absint_simulates : forall a v c,\n  absint_sound a\n  -> simulates (Rabsint (a := a)) (trsys_of v c) (absint_trsys a c).\nProof.\n  simplify.\n  constructor; simplify.\n\n  exists ($0, c); propositional.\n  subst.\n  constructor.\n  unfold compatible.\n  simplify.\n  equality.\n\n  invert H0.\n  cases st1'.\n  eapply absint_step_ok in H1; eauto.\n  invert H1.\n  invert H0.\n  propositional.\n  eauto.\nQed.\n\nDefinition merge_astates a : astates a -> astates a -> astates a :=\n  merge (fun x y =>\n           match x with\n           | None => y\n           | Some x' =>\n             match y with\n             | None => Some x'\n             | Some y' => Some (merge_astate x' y')\n             end\n           end).\n\nInductive oneStepClosure a : astates a -> astates a -> Prop :=\n| OscNil :\n  oneStepClosure $0 $0\n| OscCons : forall ss c s ss' ss'',\n  oneStepClosure ss ss'\n  -> match absint_step s c (fun x => x) with\n     | None => ss'\n     | Some ss'' => merge_astates ss'' ss'\n     end = ss''\n  -> oneStepClosure (ss $+ (c, s)) ss''.\n\nDefinition subsumeds a (ss1 ss2 : astates a) :=\n  forall c s1, ss1 $? c = Some s1\n               -> exists s2, ss2 $? c = Some s2\n                             /\\ subsumed s1 s2.\n\nTheorem subsumeds_refl : forall a (ss : astates a),\n  subsumeds ss ss.\nProof.\n  unfold subsumeds; simplify; eauto.\nQed.\n\nHint Resolve subsumeds_refl.\n\nLemma subsumeds_add : forall a (ss1 ss2 : astates a) c s1 s2,\n  subsumeds ss1 ss2\n  -> subsumed s1 s2\n  -> subsumeds (ss1 $+ (c, s1)) (ss2 $+ (c, s2)).\nProof.\n  unfold subsumeds; simplify.\n  cases (command_equal c c0); subst; simplify; eauto.\n  invert H1; eauto.\nQed.\n\nHint Resolve subsumeds_add.\n\nLemma subsumeds_empty : forall a (ss : astates a),\n  subsumeds $0 ss.\nProof.\n  unfold subsumeds; simplify.\n  equality.\nQed.\n\nLemma subsumeds_add_left : forall a (ss1 ss2 : astates a) c s,\n  ss2 $? c = Some s\n  -> subsumeds ss1 ss2\n  -> subsumeds (ss1 $+ (c, s)) ss2.\nProof.\n  unfold subsumeds; simplify.\n  cases (command_equal c c0); subst; simplify; eauto.\n  invert H1; eauto.\nQed.\n\nInductive interpret a : astates a -> astates a -> astates a -> Prop :=\n| InterpretDone : forall ss1 any ss2,\n  oneStepClosure ss1 ss2\n  -> subsumeds ss2 ss1\n  -> interpret ss1 any ss1\n| InterpretStep : forall ss worklist ss' ss'',\n  oneStepClosure worklist ss'\n  -> interpret (merge_astates ss ss') ss' ss''\n  -> interpret ss worklist ss''.\n\nLemma oneStepClosure_sound : forall a, absint_sound a\n  -> forall ss ss' : astates a, oneStepClosure ss ss'\n  -> forall c s s' c', ss $? c = Some s\n                       -> abs_step (s, c) (s', c')\n                          -> exists s'', ss' $? c' = Some s''\n                                         /\\ subsumed s' s''.\nProof.\n  induct 2; simplify.\n\n  equality.\n\n  cases (command_equal c c0); subst; simplify.\n\n  invert H2.\n  invert H3.\n  rewrite H5.\n  unfold merge_astates; simplify.\n  rewrite H7.\n  cases (ss' $? c').\n  eexists; propositional.\n  unfold subsumed; simplify.\n  unfold merge_astate; simplify.\n  cases (s' $? x); try equality.\n  cases (a0 $? x); simplify; try equality.\n  invert H1; eauto.\n  eauto.\n\n  apply IHoneStepClosure in H3; auto.\n  invert H3; propositional.\n  cases (absint_step s c (fun x => x)); eauto.\n  unfold merge_astates; simplify.\n  rewrite H3.\n  cases (a0 $? c'); eauto.\n  eexists; propositional.\n  unfold subsumed; simplify.\n  unfold merge_astate; simplify.\n  specialize (H4 x0).\n  cases (s' $? x0).\n  cases (a1 $? x0); try equality.\n  cases (x $? x0); try equality.\n  invert 1.\n  eauto.\n\n  rewrite H4.\n  cases (a1 $? x0); equality.\nQed.\n\nLemma absint_step_monotone_None : forall a (s : astate a) c wrap,\n    absint_step s c wrap = None\n    -> forall s' : astate a, absint_step s' c wrap = None.\nProof.\n  induct c; simplify; try equality.\n  cases (absint_step s c1 (fun c => wrap (c;; c2))); equality.\nQed.\n\nLemma absint_interp_monotone : forall a, absint_sound a\n  -> forall (s : astate a) e s' n,\n    a.(Represents) n (absint_interp e s)\n    -> subsumed s s'\n    -> a.(Represents) n (absint_interp e s').\nProof.\n  induct e; simplify; eauto.\n\n  cases (s' $? x); eauto.\n  cases (s $? x); eauto.\nQed.\n\nHint Resolve absint_interp_monotone.\n\nHint Resolve subsumeds_empty.\n\nLemma absint_step_monotone : forall a, absint_sound a\n    -> forall (s : astate a) c wrap ss,\n      absint_step s c wrap = Some ss\n      -> forall s', subsumed s s'\n                    -> exists ss', absint_step s' c wrap = Some ss'\n                                   /\\ subsumeds ss ss'.\nProof.\n  induct c; simplify.\n\n  equality.\n\n  invert H0.\n  eexists; propositional.\n  eauto.\n  apply subsumeds_add; eauto.\n\n  cases (absint_step s c1 (fun c => wrap (c;; c2))).\n\n  invert H0.\n  eapply IHc1 in Heq; eauto.\n  invert Heq; propositional.\n  rewrite H2; eauto.\n\n  invert H0.\n  eapply absint_step_monotone_None in Heq; eauto.\n  rewrite Heq; eauto.\n\n  invert H0; eauto.\n\n  invert H0; eauto.\nQed.\n\nLemma abs_step_monotone : forall a, absint_sound a\n  -> forall (s : astate a) c s' c',\n    abs_step (s, c) (s', c')\n    -> forall s1, subsumed s s1\n                  -> exists s1', abs_step (s1, c) (s1', c')\n                                 /\\ subsumed s' s1'.\nProof.\n  invert 2; simplify.\n  eapply absint_step_monotone in H4; eauto.\n  invert H4; propositional.\n  apply H3 in H6.\n  invert H6; propositional; eauto.\nQed.\n\nLemma interpret_sound' : forall c a, absint_sound a\n  -> forall ss worklist ss' : astates a, interpret ss worklist ss'\n    -> ss $? c = Some $0\n    -> invariantFor (absint_trsys a c) (fun p => exists s, ss' $? snd p = Some s\n                                                           /\\ subsumed (fst p) s).\nProof.\n  induct 2; simplify; subst.\n\n  apply invariant_induction; simplify; propositional; subst; simplify; eauto.\n\n  invert H3; propositional.\n  cases s.\n  cases s'.\n  simplify.\n  eapply abs_step_monotone in H4; eauto.\n  invert H4; propositional.\n  eapply oneStepClosure_sound in H4; eauto.\n  invert H4; propositional.\n  eapply H1 in H4.\n  invert H4; propositional.\n  eauto using subsumed_trans.\n\n  apply IHinterpret.\n  unfold merge_astates; simplify.\n  rewrite H2.\n  cases (ss' $? c); trivial.\n  unfold merge_astate; simplify; equality.\nQed.\n\nTheorem interpret_sound : forall c a (ss : astates a),\n  absint_sound a\n  -> interpret ($0 $+ (c, $0)) ($0 $+ (c, $0)) ss\n  -> invariantFor (absint_trsys a c) (fun p => exists s, ss $? snd p = Some s\n                                                         /\\ subsumed (fst p) s).\nProof.\n  simplify.\n  eapply interpret_sound'; eauto.\n  simplify; equality.\nQed.\n\nLtac interpret_simpl := unfold merge_astates, merge_astate;\n                       simplify; repeat simplify_map.\nLtac oneStepClosure := apply OscNil\n                       || (eapply OscCons; [ oneStepClosure\n                                           | interpret_simpl; reflexivity ]).\nLtac interpret1 := eapply InterpretStep; [ oneStepClosure | interpret_simpl ].\nLtac interpret_done := eapply InterpretDone; [ oneStepClosure\n  | repeat (apply subsumeds_add_left || apply subsumeds_empty); (simplify; equality) ].\n\n\n(** * Now, let's see a conditional-aware analysis in action! *)\n\n(* CHALLENGE #4: Prove that this particular program only finishes in states\n * where [\"b\"] is even.  The old analysis wouldn't realize that one branch of\n * the final conditional is impossible. *)\nExample loopomatic :=\n  (\"a\" <- 1;;\n   while \"n\" loop\n     \"a\" <- \"a\" + 2 * \"n\";;\n     \"n\" <- \"n\" - 1\n   done;;\n   when \"a\" then\n     \"b\" <- 0\n   else\n     \"b\" <- 1\n   done).\n\n(* OK, so the main challenge here is waiting for Coq to finishing processing\n * proof scripts, since we've given you all the code. ;) *)\n\n(* Now two lemmas that we prove to help the [simplify] tactic reduce uses of\n * [merge_astates]. *)\n\nLemma merge_astates_fok_parity : forall x : option (astate parity_absint),\n  match x with Some x' => Some x' | None => None end = x.\nProof.\n  simplify; cases x; equality.\nQed.\n\nLemma merge_astates_fok2_parity : forall x (y : option (astate parity_absint)),\n    match y with\n    | Some y' => Some (merge_astate x y')\n    | None => Some x\n    end = None -> False.\nProof.\n  simplify; cases y; equality.\nQed.\n\nHint Resolve merge_astates_fok_parity merge_astates_fok2_parity.\n\n(* Here's a utility theorem we used in lecture, too. *)\nLemma final_even : forall (s s' : astate parity_absint) v x,\n  compatible s v\n  -> subsumed s s'\n  -> s' $? x = Some Even\n  -> exists n, v $? x = Some n /\\ isEven n.\nProof.\n  unfold compatible, subsumed; simplify.\n  specialize (H x); specialize (H0 x).\n  cases (s $? x); simplify.\n\n  rewrite Heq in *.\n  assert (Some d = Some d) by equality.\n  apply H in H2.\n  first_order.\n\n  eapply H0 in H1.\n  invert H1.\n  eauto.\n  assumption.\n\n  rewrite Heq in *.\n  equality.\nQed.\n\nTheorem loopomatic_even : forall v,\n  invariantFor (trsys_of v loopomatic)\n               (fun p => snd p = Skip\n                         -> exists n, fst p $? \"b\" = Some n /\\ isEven n).\nProof.\n  simplify.\n  eapply invariant_weaken.\n\n  unfold loopomatic.\n  eapply invariant_simulates.\n  apply absint_simulates with (a := parity_absint).\n  apply parity_sound.\n\n  apply interpret_sound.\n  apply parity_sound.\n\n  (* The rest of this depends on your new interpreter being plugged in.\n   * The exact number of iterations required below might vary, based on the\n   * exact changes you make to the original framework. *)\n(*\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret1.\n  interpret_done.\n\n  invert 1.\n  first_order.\n  invert H0; simplify.\n  invert H1.\n  eapply final_even; eauto; simplify; try equality.\nQed.\n*)\nAdmitted.\n", "meta": {"author": "wangpengmit", "repo": "6887psets", "sha": "36d2bf962ef4a7ec94754674cdfe25ba4e2e0c8d", "save_path": "github-repos/coq/wangpengmit-6887psets", "path": "github-repos/coq/wangpengmit-6887psets/6887psets-36d2bf962ef4a7ec94754674cdfe25ba4e2e0c8d/Lab5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7199192936079888}}
{"text": "(* Exercise 110 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* de Morgan's disjunction law inverse *)\n\nTheorem exercise_110 : (~A /\\ ~B) -> ~(A \\/ B).\nProof.\nimp_i a1.\nneg_i (1=1) a2.\ndis_e (A \\/ B) a3 a3.\nhyp a2.\nneg_e (A).\ncon_e1 (~B).\nhyp a1.\nhyp a3.\nneg_e B.\ncon_e2 (~A).\nhyp a1.\nhyp a3.\nlin_solve.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop110.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7199142295450823}}
{"text": "(** * Matrix.v *)\n(** This file is adapted from Robert Rand's \n    Verified Quantum Computing book\n    http://www.cs.umd.edu/~rrand/vqc/Matrix.html *)\n(** Some key differences / additions are:\n    * We use the type N of binary natural numbers rather\n      than the type nat of Peano natural numbers to parametrize\n      our matrices. This is intended to speed up computation of\n      matrix operations (especially between 2^n × 2^n matrices)\n    * We define tensor powers of matrices and vectors\n    * We take advantage of Coq's typeclasses system to define\n      and prove facts about various classes of matrices, e.g.,\n      Hermitian matrices, unitary matrices, orthogonal projectors,\n      the Loewner partial order, etc.\n*)\n\nRequire Import Psatz.\nRequire Import Setoid.\nRequire Import Arith.\nRequire Import Bool.\nRequire Import Program.\nRequire Export QuantumHoareLogic.Complex.\nRequire Import Omega.\nRequire Import NArith.\n\n(** * Matrix Definitions and Equivalence **)\n\nOpen Scope N_scope.\n    \nDefinition Matrix (m n : N) := N -> N -> C.\n\nNotation Vector n := (Matrix n 1).\nNotation Square n := (Matrix n n).\n\nDefinition mat_equiv {m n : N} (A B : Matrix m n) : Prop :=\n  forall i j, i < m -> j < n -> A i j = B i j.\n\nInfix \"==\" := mat_equiv (at level 80).\n\nLemma mat_equiv_refl : forall {m n} (A : Matrix m n), A == A.\nProof. split; eauto. Qed.\n\nLemma mat_equiv_sym : forall {m n} (A B : Matrix m n), A == B -> B == A.\nProof.\n  intros m n A B H i j Hi Hj. rewrite H; auto.\nQed.\n\nLemma mat_equiv_trans : forall {m n} (A B C : Matrix m n),\n    A == B -> B == C -> A == C.\nProof.\n  intros m n A B C H1 H2 i j Hi Hj. rewrite H1; [rewrite H2| |]; auto.\nQed.\n\nAdd Parametric Relation m n : (Matrix m n) (@mat_equiv m n)\n  reflexivity proved by mat_equiv_refl\n  symmetry proved by mat_equiv_sym\n  transitivity proved by mat_equiv_trans\n    as mat_equiv_rel.\n\nLemma mat_equiv_trans2 : forall {m n} (A B C : Matrix m n),\n    A == B -> A == C -> B == C.\nProof.\n  intros m n A B C HAB HAC.\n  rewrite <- HAB.\n  apply HAC.\nQed.\n\nLemma mat_equiv_entries_eq : forall {m n}(A B:Matrix m n), A == B ->\n  forall i j, (i<m)%N -> (j<n)%N -> A i j = B i j.\nProof. intros. apply H; auto. Qed.\n\nLtac meq := apply mat_equiv_entries_eq; try nomega.\n\n(* ################################################################# *)\n(** * Basic Matrices and Operations *)\n\nClose Scope N_scope.\nOpen Scope C_scope.\n\nNotation \"m =? n\" := (N.eqb m n) (at level 70) : matrix_scope.\nNotation \"m <? n\" := (N.ltb m n) (at level 70) : matrix_scope.\nNotation \"m <=? n\" := (N.leb m n) (at level 70) : matrix_scope.\n\nOpen Scope matrix_scope.\n\nDefinition I (n : N) : Matrix n n := fun i j => if (i =? j)%N then 1 else 0.\n\nDefinition Zero (m n : N) : Matrix m n := fun _ _ => 0. \n\nDefinition Mscale {m n : N} (c : C) (A : Matrix m n) : Matrix m n := \n  fun i j => c * A i j.\n\nDefinition Mplus {m n : N} (A B : Matrix m n) : Matrix m n :=\n  fun i j => A i j + B i j.\n\nDefinition Mneg {m n : N} (A : Matrix m n) : Matrix m n :=\n  fun i j => - A i j.\n\nDefinition Mminus {m n : N} (A B : Matrix m n) : Matrix m n :=\n  Mplus A (Mneg B).\n\nNotation \".- A\" := (Mneg A) (at level 45) : matrix_scope.\nInfix \".+\" := Mplus (at level 50, left associativity) : matrix_scope.\nInfix \".-\" := Mminus (at level 50, left associativity) : matrix_scope.\nInfix \".*\" := Mscale (at level 40, left associativity) : matrix_scope.\n\nLemma Mplus_assoc : forall {m n} (A B C : Matrix m n), (A .+ B) .+ C == A .+ (B .+ C).\nProof.\n  intros m n A B C i j Hi Hj.\n  unfold Mplus.\n  lca.\nQed.\n\nLemma Mplus_comm : forall {m n} (A B : Matrix m n), A .+ B == B .+ A.\nProof.\n  intros m n A B i j Hi Hj.\n  unfold Mplus.\n  lca.\nQed.\n  \nLemma Mplus_0_l : forall {m n} (A : Matrix m n), Zero m n .+ A == A. \nProof.\n  intros m n A i j Hi Hj.\n  unfold Zero, Mplus.\n  lca.\nQed.\n  \nLemma Mplus_0_r : forall {m n} (A : Matrix m n), A .+ Zero m n == A. \nProof.\n  intros m n A.\n  rewrite Mplus_comm.\n  apply Mplus_0_l.\nQed.\n\nLemma Mplus_compat : forall {m n} (A B A' B' : Matrix m n),\n    A == A' -> B == B' -> A .+ B == A' .+ B'.\nProof.\n  intros m n A B A' B' HA HB.\n  intros i j Hi Hj.\n  unfold Mplus.\n  rewrite HA by lia.\n  rewrite HB by lia.\n  reflexivity.\nQed.\n    \nAdd Parametric Morphism m n : (@Mplus m n)\n  with signature mat_equiv ==> mat_equiv ==> mat_equiv as Mplus_mor.\nProof.\n  intros A A' HA B B' HB.\n  apply Mplus_compat; easy.\nQed.\n\nAdd Parametric Morphism m n : (@Mneg m n)\n  with signature mat_equiv ==> mat_equiv as Mneg_mor.\nProof. intros. intros i j Hi Hj. unfold Mneg; rewrite H; auto. Qed.\n\nAdd Parametric Morphism m n : (@Mminus m n)\n  with signature mat_equiv ==> mat_equiv ==> mat_equiv as Mminus_mor.\nProof. intros. unfold Mminus. rewrite H; rewrite H0; easy. Qed.\n\n\n\n\nLemma Mplus3 : forall {m n} (A B C : Matrix m n), (B .+ A) .+ C == A .+ (B .+ C).\nProof.\n  intros m n A B C.\n  rewrite (Mplus_comm B A).\n  apply Mplus_assoc.\nQed.\n\nLemma Mscale_compat : forall {m n} (c c' : C) (A A' : Matrix m n),\n    c = c' -> A == A' -> c .* A == c' .* A'.\nProof.\n  intros m n c c' A A' Hc HA.\n  intros i j Hi Hj.\n  unfold Mscale.\n  rewrite Hc, HA; easy.\nQed.\n\nAdd Parametric Morphism m n : (@Mscale m n)\n  with signature eq ==> mat_equiv ==> mat_equiv as Mscale_mor.\nProof.\n  intros; apply Mscale_compat; easy.\nQed.\n\nDefinition trace {n : N} (A : Square n) : C := \n  Csum (fun x => A x x) n.\n\nDefinition Mmult {m n o : N} (A : Matrix m n) (B : Matrix n o) : Matrix m o := \n  fun x z => Csum (fun y => A x y * B y z) n.\n\nOpen Scope N_scope.\n\nDefinition kron {m n o p : N} (A : Matrix m n) (B : Matrix o p) : \n  Matrix (m*o) (n*p) :=\n  fun x y => Cmult (A (x / o) (y / p)) (B (x mod o) (y mod p)).\n\nDefinition transpose {m n} (A : Matrix m n) : Matrix n m := \n  fun x y => A y x.\n\nDefinition adjoint {m n} (A : Matrix m n) : Matrix n m := \n  fun x y => (A y x)^*.\n\nDefinition dot {n : N} (A : Vector n) (B : Vector n) : C :=\n  Mmult (transpose A) B 0 0.\n\nDefinition inner_product {n} (u v : Vector n) : C := \n  Mmult (adjoint u) (v) 0 0.\n\nDefinition outer_product {n} (u v : Vector n) : Square n := \n  Mmult u (adjoint v).\n\nClose Scope N_scope.\n\nInfix \"×\" := Mmult (at level 40, left associativity) : matrix_scope.\nInfix \"⊗\" := kron (at level 41, left associativity) : matrix_scope.\nNotation \"A ⊤\" := (transpose A) (at level 0) : matrix_scope. \nNotation \"A †\" := (adjoint A) (at level 0) : matrix_scope. \nInfix \"∘\" := dot (at level 40, left associativity) : matrix_scope.\nNotation \"⟨ A , B ⟩\" := (inner_product A B) : matrix_scope.\n\n(* ================================================================= *)\n(** ** Compatibility lemmas *)\n\nLtac nomega := zify; omega.\n\nLemma trace_compat : forall {n} (A A' : Square n),\n    A == A' -> trace A = trace A'.\nProof.\n  intros n A A' H.\n  apply Csum_eq.\n  intros x Hx.\n  rewrite H. easy. 1,2:nomega.\nQed.\n\nAdd Parametric Morphism n : (@trace n)\n  with signature mat_equiv ==> eq as trace_mor.\nProof. intros; apply trace_compat; easy. Qed.\n\nLemma Mmult_compat : forall {m n o} (A A' : Matrix m n) (B B' : Matrix n o),\n    A == A' -> B == B' -> A × B == A' × B'.\nProof.\n  intros m n o A A' B B' HA HB i j Hi Hj.\n  unfold Mmult.\n  apply Csum_eq; intros x Hx.\n  rewrite HA, HB; try auto; nomega.\nQed.\n\nAdd Parametric Morphism m n o : (@Mmult m n o)\n  with signature mat_equiv ==> mat_equiv ==> mat_equiv as Mmult_mor.\nProof. intros. apply Mmult_compat; easy. Qed.\n\nLemma kron_compat : forall {m n o p} (A A' : Matrix m n) (B B' : Matrix o p),\n    A == A' -> B == B' -> A ⊗ B == A' ⊗ B'.\nProof.\n  intros m n o p A A' B B' HA HB.\n  intros i j Hi Hj.\n  unfold kron.\n  assert (Ho : o <> 0%N). intros F. rewrite F in *. lia.\n  assert (Hp : p <> 0%N). intros F. rewrite F in *. lia.\n  rewrite HA, HB. easy.\n  - apply N.mod_upper_bound; easy.\n  - apply N.mod_upper_bound; easy.\n  - apply N.div_lt_upper_bound; lia.\n  - apply N.div_lt_upper_bound; lia.\nQed.\n\nAdd Parametric Morphism m n o p : (@kron m n o p)\n  with signature mat_equiv ==> mat_equiv ==> mat_equiv as kron_mor.\nProof. intros. apply kron_compat; easy. Qed.\n\nLemma transpose_compat : forall {m n} (A A' : Matrix m n),\n    A == A' -> A⊤ == A'⊤.\nProof.\n  intros m n A A' H.\n  intros i j Hi Hj.\n  unfold transpose.\n  rewrite H; easy.\nQed.\n\nAdd Parametric Morphism m n : (@transpose m n)\n  with signature mat_equiv ==> mat_equiv as transpose_mor.\nProof. intros. apply transpose_compat; easy. Qed.\n\nLemma adjoint_compat : forall {m n} (A A' : Matrix m n),\n    A == A' -> A† == A'†.\nProof.\n  intros m n A A' H.\n  intros i j Hi Hj.\n  unfold adjoint.\n  rewrite H; easy.\nQed.\n\nAdd Parametric Morphism m n : (@adjoint m n)\n  with signature mat_equiv ==> mat_equiv as adjoint_mor.\nProof. intros. apply adjoint_compat; easy. Qed.\n\nLemma innprod_compat : forall {n}(x x' y y' : Vector n),\n  x == x' -> y == y' -> ⟨x,y⟩ = ⟨x',y'⟩.\nProof. intros. unfold inner_product. apply Mmult_compat; try auto.\napply adjoint_compat; auto. 1,2:apply N.lt_0_1.\nQed.\n\nAdd Parametric Morphism n : (@inner_product n)\n  with signature mat_equiv ==> mat_equiv ==> eq as innprod_mor.\nProof. intros. apply innprod_compat; easy.\nQed.\n\n\n\n(* ################################################################# *)\n(** * Matrix Automation *)\n\nLtac solve_end :=\n  match goal with\n  | H : lt _ O |- _ => apply Nat.nlt_0_r in H; contradict H\n  end.\n                \nLtac by_cell := \n  intros i j Hi Hj;\n  repeat (destruct i as [|i]; simpl; [|apply lt_S_n in Hi]; try solve_end); clear Hi;\n  repeat (destruct j as [|j]; simpl; [|apply lt_S_n in Hj]; try solve_end); clear Hj.\n\nLtac lma := by_cell; lca.\n\nLemma scale0_concrete : 0 .* I 10 == Zero _ _.\nProof. lma. Qed.\n\n\nLtac mintros := intros i j Hi Hj.\n\n\n(* ################################################################# *)\n(** * Matrix Properties *)\n\nTheorem Mmult_assoc : forall {m n o p : N} (A : Matrix m n) (B : Matrix n o) \n  (C: Matrix o p), A × B × C == A × (B × C).\nProof.\n  intros m n o p.\n  unfold Mmult.\n  N.induct n; intros.\n  - simpl. intros i j Hi Hj.\n    apply Csum_0. intros. lca.\n  - intros i j Hi Hj. rewrite Csum_succ.\n    rewrite <- H; eauto.\n    rewrite Csum_mult_l. rewrite <- Csum_plus.\n    apply Csum_eq; intros. rewrite Csum_succ. rewrite Cmult_plus_distr_r.\n    rewrite Cmult_assoc. auto.\nQed.\n\nTheorem Mmult_plus_distr_l : forall {m n p}(A: Matrix m n)(B C: Matrix n p),\n  A × (B .+ C) == A×B .+ A×C.\nProof.\n  intros. unfold Mmult, Mplus. intros i j Hi Hj.\n  rewrite <- Csum_plus. apply Csum_eq; intros; field.\nQed.\n\nTheorem Mmult_plus_distr_r : forall {m n p}(A B: Matrix m n)(C: Matrix n p),\n  (A .+ B) × C  == A×C .+ B×C.\nProof.\n  intros. unfold Mmult, Mplus. intros i j Hi Hj.\n  rewrite <- Csum_plus. apply Csum_eq; intros; field.\nQed.\n\nLemma Mneg_mult_distr_l : forall {m n p}(A: Matrix m n)(B: Matrix n p),\n  .- A×B == (.-A)×B.\nProof. intros. unfold Mneg, Mmult; mintros. rewrite Csum_neg.\napply Csum_eq; intros; lca.\nQed.\n\nLemma Mmult_neg_cancel : forall {m n p}(A: Matrix m n)(B: Matrix n p),\n  (.-A)×(.-B) == A×B.\nProof. intros. unfold Mneg, Mmult; mintros. apply Csum_eq. intros; lca.\nQed.\n\nLemma Mmult_adjoint : forall {m n o : N} (A : Matrix m n) (B : Matrix n o),\n      (A × B)† == B† × A†.\nProof.\n  intros m n o A B i j Hi Hj.\n  unfold Mmult, adjoint.\n  rewrite Csum_conj_distr.\n  apply Csum_eq; intros.\n  rewrite Cconj_mult_distr.\n  rewrite Cmult_comm.\n  reflexivity.\nQed.\n\nLemma Mmult_1_l: forall (m n : N) (A : Matrix m n), \n  I m × A == A.\nProof.\n  intros m n A i j Hi Hj.\n  unfold Mmult.\n  apply Csum_unique with i. nomega.\n  unfold I. rewrite N.eqb_refl. lca.\n  intros x Hx.\n  unfold I.\n  apply N.eqb_neq in Hx. rewrite Hx.\n  lca.\nQed.\n\nLemma Mmult_1_r: forall (m n : N) (A : Matrix m n), \n  A × I n == A.\nProof.\n  intros m n A i j Hi Hj.\n  unfold Mmult.\n  eapply Csum_unique. apply Hj.\n  unfold I. rewrite N.eqb_refl. lca.\n  intros x Hx.\n  unfold I.\n  apply N.eqb_neq in Hx. rewrite N.eqb_sym. rewrite Hx.\n  lca.\nQed.\n\nLemma adjoint_sum : forall {m n} (A B: Matrix m n), (A .+ B)† == A† .+ B†.\nProof. intros; mintros; lca. Qed.\n\nLemma adjoint_involutive : forall {m n} (A : Matrix m n), A†† == A.\nProof.\n  (* WORKED IN CLASS *)\n  intros m n A i j _ _.\n  lca.\nQed.  \n  \nLemma kron_adjoint : forall {m n o p} (A : Matrix m n) (B : Matrix o p),\n  (A ⊗ B)† == A† ⊗ B†.\nProof. \n  (* WORKED IN CLASS *)\n  intros m n o p A B.\n  intros i j Hi Hj.\n  unfold adjoint, kron. \n  rewrite Cconj_mult_distr.\n  reflexivity.\nQed.\n\nLemma trace_mult : forall {m n}(A: Matrix m n)(B: Matrix n m),\n  trace (A×B) = trace (B×A).\nProof.\n  intros. unfold trace, Mmult. rewrite Csum_order.\n  apply Csum_eq; intros; apply Csum_eq; intros; field.\nQed.\n\nLemma trace_plus : forall {n}(A B: Square n),\n  trace (A .+ B) = trace A + trace B.\nProof. intros; unfold trace, Mplus; simpl. apply Csum_plus.\nQed.\n\nLemma trace_zero : forall {n}, trace (Zero n n) = 0.\nProof. unfold trace, Zero; intros. apply Csum_0; intros; field.\nQed.\n\nLemma trace_neg : forall {n}(A: Square n), - trace A = trace (.- A).\nProof. intros. unfold trace, Mneg. apply Csum_neg.\nQed.\n\nLemma Mmult_0_l : forall {m n p}(M: Matrix n p),\n  (Zero m n) × M == Zero m p.\nProof. intros. unfold Zero, Mmult; by_cell. apply Csum_0; intros; field.\nQed.\n\nLemma Mmult_0_r : forall {m n p}(M: Matrix m n),\n  M × (Zero n p) == Zero m p.\nProof. intros. unfold Zero, Mmult; by_cell. apply Csum_0; intros; field.\nQed.\n\nLemma Mscale_mult_comm : forall {m n p} c (A: Matrix m n)(B: Matrix n p),\n  c .* (A×B) == A × (c.*B).\nProof. intros. unfold Mmult, Mscale; mintros. rewrite Csum_mult_l.\n  apply Csum_eq; intros; field.\nQed.\n\nLemma innprod_distr_r : forall {n}(x y z: Vector n), ⟨x, y.+z⟩ = ⟨x, y⟩ + ⟨x, z⟩.\nProof. intros. unfold inner_product. rewrite Mmult_plus_distr_l. unfold Mplus. auto. 1,2:nomega.\nQed.\n\nLemma vectnorm_nonneg : forall {n}(v: Vector n), 0 <= ⟨v,v⟩.\nProof.\n  intros. unfold inner_product, Mmult, adjoint; simpl.\n  apply Csum_ge0. intros. split; [|split]. lca. lca. simpl. nra.\nQed.\n\nLemma Mminus_same : forall {m n}(A: Matrix m n), A .- A == Zero m n.\nProof. intros. lma. Qed.\n\nLemma Mneg_zero_zero : forall {m n}, .- Zero m n == Zero m n.\nProof. intros. lma. Qed.\n\nLemma innprod_zero : forall {n}(x: Vector n), ⟨x,x⟩ = 0 <-> x == Zero n 1.\nProof. unfold inner_product. split; intros.\n- mintros. unfold Mmult in H. assert (j=0)%N by nomega; subst.\n  epose proof (Csum_nonneg_0 _ _ _ H). specialize (H0 i Hi). simpl in H0.\n  unfold adjoint in H0. unfold Zero; simpl. apply Cnorm2_0_0.\n  apply RtoC_inj. rewrite <- Cconj_mult_norm2. rewrite Cmult_comm; auto.\n- apply Csum_0. intros. specialize (H x0 0%N). rewrite H. apply Cmult_0_r.\n  auto. nomega. Unshelve. intros. simpl. split. lca. split. lca. simpl. nra.\nQed.\n\n(** Tensor Product facts *)\n\n(*\nDefinition mat_equiv2 (m1 n1 m2 n2:N)(A B : N -> N -> C) :=\n  m1 = m2 /\\ n1 = n2 /\\ @mat_equiv m1 m2 A B.\n\nDefinition mat_equiv3 {m1 n1 m2 n2}(A: Matrix m1 n1)(B: Matrix m2 n2) :=\n  mat_equiv2 m1 n1 m2 n2 A B.\n\nInfix \"===\" := mat_equiv3 (at level 80).\n*)\n\n\n\n(* idea: define the original mat_equiv on (N->N->C), and try to set\n   so that implicit arguments are filled in when fed matrices  *)\n\n\n\n\n\n\n\n\n\n\n\nLemma kron_assoc : forall {m n o p q r} (A:Matrix m n)(B:Matrix o p)(C:Matrix q r),\n  A ⊗ B ⊗ C == A ⊗ (B ⊗ C).\nProof. intros. unfold kron. intros i j Hi Hj.\nrepeat rewrite N.div_div. repeat rewrite (N.mul_comm o). repeat rewrite (N.mul_comm p).\ndo 4 try rewrite N.mod_mul_r at 1. rewrite (N.mul_comm q (_ mod _)); rewrite (N.mul_comm r (_ mod _)).\nrepeat rewrite N.div_add. do 2 replace (_ mod _ / _)%N with N0. do 2 rewrite N.add_0_l.\nrepeat rewrite N.mod_add. repeat rewrite N.mod_mod. apply Cmult_assoc.\n5,7: symmetry; apply N.div_small_iff. 6,8: apply N.mod_upper_bound.\n9: auto.\nall: match goal with |[|- (?x <> 0)%N] => destruct x; try subst; try rewrite N.mul_0_r in *; try nomega\nend.\nQed.\n\n\nLemma kron_mult : forall {m n p m' n' p'} (A:Matrix m n)(B:Matrix m' n')(C:Matrix n p)(D:Matrix n' p'),\n  (A ⊗ B) × (C ⊗ D) == (A × C) ⊗ (B × D).\nProof.\nintros. unfold kron, Mmult. mintros. rewrite Csum_convolution.\napply Csum_eq. intros. lca.\nQed.\n\nLemma kron_1 : forall {m n}, (I m) ⊗ (I n) == I(m*n).\nProof. intros. mintros. unfold kron, I; simpl.\ndestruct (N.eq_dec i j). subst. repeat rewrite N.eqb_refl. lca.\nassert ((i =? j) = false) by (apply N.eqb_neq; auto). rewrite H.\nassert (n<>0)%N by (intro; subst; nomega).\npose proof (N.div_mod i n H0). pose proof (N.div_mod j n H0).\ndestruct (N.eq_dec (i/n)(j/n)).\n- replace (i mod n =? j mod n) with false. lca. symmetry; apply N.eqb_neq.\n  intro. rewrite H3 in H1. rewrite e in H1. apply n0. rewrite H1. rewrite H2 at 3. auto.\n- replace (i / n =? j / n) with false. lca. symmetry; apply N.eqb_neq. auto.\nQed.\n\nLemma kron_0_l : forall {m n o p}(A:Matrix o p), (Zero m n) ⊗ A == Zero _ _.\nProof. intros; unfold Zero, kron. mintros; lca.\nQed.\n\nLemma kron_0_r : forall {m n o p}(A:Matrix m n), A ⊗ (Zero o p) == Zero _ _.\nProof. intros; unfold Zero, kron. mintros; lca.\nQed.\n\nDefinition tensor {m k:N} (n:N) (f : N -> Matrix m k) :=\n  N.peano_rect (fun p => Matrix (m^p)(k^p)) (I 1) (fun i M => M ⊗ (f i)) n.\n\n(* Need to redo definition of tensor so that the type changes\nover the recursion *)\n\n(*\nAdd Parametric Morphism m k : (@tensor m k)\n  with signature N.eq ==> mat_equiv ==> mat_equiv as tensor_mor.\nProof. intros. apply innprod_compat; easy.\nQed.*)\n\nLemma tensor_succ : forall {m k:N} n f,\n  @tensor m k (N.succ n) f == (tensor n f) ⊗ (f n).\nProof. intros. unfold tensor. rewrite N.peano_rect_succ. reflexivity.\nQed.\n\nLemma tensor_succ_eq : forall {m k:N} n f,\n  @tensor m k (N.succ n) f = (tensor n f) ⊗ (f n).\nProof. intros. unfold tensor. rewrite N.peano_rect_succ. reflexivity.\nQed.\n\n(*\nTheorem change_dim_eq : forall m n m' n' (A B:Matrix m n),\n  m = m' -> n = n' -> @mat_equiv m n A B -> @mat_equiv m' n' A B.\nProof. intros. mintros; apply H1; nomega.\nQed.*)\n\nLemma tensor_mult : forall {m k o} n f g,\n  (@tensor m k n f) × (@tensor k o n g) == tensor n (fun i => (f i)×(g i)).\nProof.\nintros m k o n. N.induct n.\n- intros. simpl. mintros. unfold Mmult, I. simpl. assert (i=0)%N by nomega; assert (j=0)%N by nomega. subst. simpl. lca.\n- intros. repeat rewrite tensor_succ.\nmintros.\nrewrite N.pow_succ_r' in Hi,Hj. pose proof (kron_mult (tensor n f) (f n) (tensor n g) (g n)).\nunfold Mmult in*. rewrite N.pow_succ_r'. rewrite N.mul_comm.\nrewrite H0. unfold kron. rewrite H. auto. \n1,2:apply N.div_lt_upper_bound. 5,6:rewrite N.mul_comm. all:eauto.\nall: (intros contra; subst; nomega).\nQed.\n\n\nLemma tensor_idx : forall n (f:N -> Square 2) i j (Hi:(i<n)%N) (Hj:(j<n)%N),\n  (tensor n f) i j =\n    Cprod (fun k => f k (N.b2n (N.testbit i (n-k-1))) (N.b2n (N.testbit j (n-k-1)))) n.\nProof.\nintros n f. N.induct n; intros.\n- nomega.\n- rewrite tensor_succ. rewrite Cprod_succ. unfold kron at 1.\n\ndestruct (N.eq_dec n 0). assert (i=0/\\j=0)%N by nomega. induction H0; subst.\nsimpl. unfold I. rewrite N.eqb_refl. rewrite N.mod_0_l. auto. nomega.\n\n  rewrite H. apply f_equal2. apply Cprod_eq. intros.\n  repeat rewrite N.sub_succ_l. repeat rewrite N.testbit_succ_r_div2.\n  repeat rewrite N.div2_div. auto. 1,2,3,4:nomega.\n  do 2 rewrite <- N.bit0_mod. replace (N.succ n - n - 1)%N with 0%N by nomega.\n  auto. 1,2: apply N.div_lt_upper_bound. all:try nomega.\n  all:pose proof (N.log2_le_lin i); pose proof (N.log2_le_lin j);\n  apply N.log2_lt_cancel; rewrite N.log2_pow2; nomega.\nQed.\n\n(* ********* *)\n\n\n(** * Inverses *)\n\nDefinition mat_inverse {n} (A: Matrix n n) := {B | B × A == I n}.\n\nTheorem Minv_nullsp0 : forall {n} (A: Matrix n n),\n  mat_inverse A -> forall (x:Vector n), A × x == Zero n 1 -> x == Zero n 1.\nProof.\n  intros. destruct X as [B HB]. rewrite <- Mmult_1_l at 1. rewrite <- HB.\n  rewrite Mmult_assoc. rewrite H. unfold Mmult, Zero; by_cell; simpl; apply Csum_0; intros; lca.\nQed.\n\n\n\n\n(** * Eigenstuff *)\n\n(* need definition to include v != 0 *)\n(*\nRecord NonZero n := mknonzerovect {\n  nonzero :> Vector n;\n  cond_nonzero : 0 < ⟨nonzero, nonzero⟩\n}.\n\nDefinition eigenvalue {n}(A:Square n)(λ:C) := exists v:NonZero n, A×v == λ .* v.\n\nDefinition eigenvector {n}(A:Square n)(v:NonZero n) := exists λ:C, A×v == λ .* v.\n*)\n\n(** * Matrix Classes *)\n\n\nClass Hermitian {n} (A: Square n) := {\n  cond_hermitian : A == A†\n}.\nAdd Parametric Morphism n : (@Hermitian n)\n  with signature mat_equiv ==> iff as hermitian_mor.\nProof. repeat split; [rewrite <- H | rewrite H]; apply cond_hermitian. Qed.\n\nClass Unitary {n} (A: Square n) := {\n  cond_unitary : A† × A == I n\n}.\nAdd Parametric Morphism n : (@Unitary n)\n  with signature mat_equiv ==> iff as unitary_mor.\nProof. repeat split; [rewrite <- H | rewrite H]; apply cond_unitary. Qed.\n\nClass PositiveSemidef {n} (A: Square n) := {\n  psd_herm :> Hermitian A;\n  cond_psd : forall (v:Vector n), 0 <= ⟨ v, A × v⟩\n}.\nAdd Parametric Morphism n : (@PositiveSemidef n)\n  with signature mat_equiv ==> iff as psd_mor.\nProof. split; split; intros; first [rewrite <- H | rewrite H]; \nfirst [typeclasses eauto|apply cond_psd]. Qed.\n\nClass Projection {n} (A: Square n) := {\n  cond_projection : A × A == A\n}.\nAdd Parametric Morphism n : (@Projection n)\n  with signature mat_equiv ==> iff as projection_mor.\nProof. repeat split; [rewrite <- H | rewrite H]; apply cond_projection. Qed.\n\nClass OrthProjection {n} (A: Square n) := {\n  orthproj_proj :> Projection A;\n  orthproj_herm :> Hermitian A\n}.\nAdd Parametric Morphism n : (@OrthProjection n)\n  with signature mat_equiv ==> iff as orthproj_mor.\nProof. do 2 split; first [rewrite <- H | rewrite H]; typeclasses eauto. Qed.\n\nClass Density {n} (A: Square n) := {\n  density_psd :> PositiveSemidef A;\n  cond_density : trace A = 1\n}.\nAdd Parametric Morphism n : (@Density n)\n  with signature mat_equiv ==> iff as density_mor.\nProof. do 2 split; first [rewrite <- H | rewrite H];\nfirst [typeclasses eauto|apply cond_density]. Qed.\n\nClass PartialDensityMatrix {n} (A: Square n) := {\n  pdm_psd :> PositiveSemidef A;\n  cond_pdm : 0 <= trace A <= 1\n}.\nNotation PDM := PartialDensityMatrix.\nAdd Parametric Morphism n : (@PartialDensityMatrix n)\n  with signature mat_equiv ==> iff as pdm_mor.\nProof. do 2 split; first [rewrite <- H | rewrite H];\nfirst [typeclasses eauto|apply cond_pdm]. Qed.\n\nClass OrthProjPair {n} (A B: Square n) := {\n  oppair_op1 :> OrthProjection A;\n  oppair_op2 :> OrthProjection B;\n  cond_oppair : A .+ B == I n\n}.\nAdd Parametric Morphism n : (@OrthProjPair n)\n  with signature mat_equiv ==> mat_equiv ==> iff as oppair_mor.\nProof. do 2 split; first [rewrite<-H|rewrite H|rewrite<-H0|rewrite H0];\ntry typeclasses eauto; [rewrite<-H0|rewrite H0]; apply cond_oppair. Qed.\n\n(* Theorems on matrix classes *)\nTypeclasses eauto := 5.\n\n\nLemma herm_diag_real : forall {n} (H:Square n) {Hherm: Hermitian H} (i:N),\n  (i<n)%N -> (H i i) = (H i i)^*.\nProof. intros. apply cond_hermitian; eauto.\nQed.\n\nLemma herm_trace_real : forall {n} (H:Square n), Hermitian H ->\n  trace H = (trace H)^*.\nProof. unfold trace; intros; simpl.\nrewrite Csum_conj_distr. apply Csum_eq. apply herm_diag_real. auto.\nQed.\n\nInstance unitary_adjoint_unitary : forall {n} U `{Unitary n U},\n  Unitary U†.\nProof. Admitted.\n\nInstance herm_conj_herm : forall {n m}(H:Square n)(M:Matrix m n)`{Hermitian _ H},\n  Hermitian (M×H×M†).\nProof. intros. constructor. rewrite Mmult_assoc at 2. do 2 rewrite Mmult_adjoint.\nrewrite adjoint_involutive. rewrite cond_hermitian at 1. reflexivity.\nQed.\n\nInstance psd_conj_unitary_psd : forall {n}(A U:Square n)`{PositiveSemidef _ A}`{Unitary _ U},\n  PositiveSemidef (U×A×U†).\nProof. intros. constructor; [constructor|]. apply herm_conj_herm. apply psd_herm. intros.\nassert (v†×(U×A×U†×v) == (U†×v)†×(A×(U†×v))). do 2 rewrite Mmult_assoc at 1.\nrewrite <- Mmult_assoc at 1. rewrite Mmult_adjoint. rewrite adjoint_involutive. easy.\nunfold inner_product. rewrite H1; try auto. apply cond_psd. 1,2:nomega.\nQed.\n\nTheorem conj_preserves_trace : forall {n} M U `{Unitary n U},\n  trace (U×M×U†) = trace M.\nProof. intros. rewrite trace_mult. rewrite <- Mmult_assoc.\nrewrite cond_unitary. rewrite Mmult_1_l. auto.\nQed.\n\nInstance density_conj_unitary_density : forall {n}(rho U:Square n)`{Density _ rho}`{Unitary _ U},\n  Density (U×rho×U†).\nProof. intros. split; try typeclasses eauto. rewrite conj_preserves_trace. apply cond_density. eauto.\nQed.\n\nInstance pdm_conj_unitary_pdm : forall {n}(rho U:Square n)`{PDM rho}`{Unitary _ U},\n  PDM (U×rho×U†).\nProof. intros. split; try typeclasses eauto. rewrite conj_preserves_trace. apply cond_pdm. eauto.\nQed.\n\nLemma orthproj_pairs_prod0 : forall {n}(P1 P2: Square n)`{OrthProjPair _ P1 P2},\n  P1×P2 == Zero n n.\nProof.\n  intros. assert (P1 == I n .- P2). unfold Mminus, Mplus, Mneg in *.\n  intros i j Hi Hj. rewrite <- cond_oppair; [unfold Mplus; field|auto|auto].\n  rewrite H0. unfold Mminus; rewrite Mmult_plus_distr_r.\n  rewrite Mmult_1_l. intros i j Hi Hj; unfold Mmult, Mplus, Mneg, Zero.\n  rewrite <- cond_projection. unfold Mmult. rewrite <- Csum_plus.\n  apply Csum_0. intros; field. all: auto.\nQed.\n\nInstance oppair_sym : forall {n} P1 P2 `{OrthProjPair n P1 P2},\n  OrthProjPair P2 P1.\nProof. intros. split; try typeclasses eauto. rewrite Mplus_comm; apply cond_oppair.\nQed.\n\nLemma measure_output_preserves_trace : forall {n} (P1 P2 M: Square n) `{OrthProjPair n P1 P2},\n  trace (P1×M×P1 .+ P2×M×P2) = trace M.\nProof.\n  intros. symmetry. rewrite <- Mmult_1_l at 1. rewrite <- Mmult_1_r at 1.\n  rewrite <- cond_oppair. rewrite Mmult_plus_distr_l. repeat rewrite Mmult_plus_distr_r.\n  repeat rewrite trace_plus. rewrite (trace_mult (P2×_) P1). rewrite (trace_mult (P1×_) P2).\n  do 2 rewrite <- Mmult_assoc. rewrite (orthproj_pairs_prod0 P1 P2).\n  rewrite (orthproj_pairs_prod0 P2 P1). rewrite Mmult_0_l. rewrite trace_zero. field.\nQed.\n\nInstance herm_sum_herm : forall {n:N} A B `{Hermitian n A} `{Hermitian n B},\n  Hermitian (A .+ B).\nProof. intros. split. rewrite adjoint_sum. rewrite (@cond_hermitian _ A) at 1.\nrewrite (@cond_hermitian _ B) at 1. easy. all:auto.\nQed.\n\nInstance herm_neg_herm : forall {n:N} A `{Hermitian n A},\n  Hermitian (.- A).\nProof. split. unfold Mneg, adjoint. mintros. rewrite Cconj_opp. rewrite cond_hermitian; auto.\nQed.\n\nInstance herm_minus_herm : forall {n:N} A B `{Hermitian n A} `{Hermitian n B},\n  Hermitian (A .- B).\nProof. intros. typeclasses eauto.\nQed.\n\nInstance herm_bilinform_real_matform : forall {n} A (v: Vector n)`{Hermitian n A},\n  Hermitian (v†×(A×v)).\nProof. intros. split. rewrite <- Mmult_assoc. rewrite <- (adjoint_involutive v) at 2 4.\napply cond_hermitian.\nQed.\n\nLemma herm_bilinform_real : forall {n} A (v: Vector n)`{Hermitian n A},\n  ⟨v, A×v⟩  = ⟨v, A×v⟩^*.\nProof. intros. apply (@cond_hermitian _ _ (herm_bilinform_real_matform _ _)); nomega.\nQed.\n\nLemma herm_innprod : forall {n} A (v: Vector n)`{Hermitian n A},\n   ⟨v, A×v⟩  = ⟨A×v, v⟩.\nProof. intros. unfold inner_product. meq. rewrite Mmult_adjoint.\nrewrite <- cond_hermitian. symmetry. apply Mmult_assoc.\nQed.\n\nInstance psd_sum_psd : forall {n} A B `{PositiveSemidef n A}`{PositiveSemidef n B},\n  PositiveSemidef (A .+ B).\nProof. intros. split. typeclasses eauto 3. intro; simpl.\nrewrite (innprod_compat _ _ _ _ (reflexivity v) (Mmult_plus_distr_r A B v)).\nrewrite innprod_distr_r. repeat split; try lca. rewrite Cconj_plus_distr.\nrewrite (herm_bilinform_real A) at 1. rewrite (herm_bilinform_real B v) at 1. auto.\napply psd_herm.\napply Rplus_le_le_0_compat.\nassert (0 <= ⟨ v,A×v⟩).\n  autounfold; apply cond_psd.\ndestruct H1. destruct H2. auto.\nassert (0 <= ⟨ v,B×v⟩).\n  autounfold; apply cond_psd.\ndestruct H1. destruct H2. auto.\nQed.\n\nInstance herm_herm_herm : forall {n} A B `{Hermitian n A}`{Hermitian n B},\n  Hermitian (B×A×B).\nProof.\n  constructor. rewrite cond_hermitian at 2 4. apply herm_conj_herm; auto.\nQed.\n\nInstance astara_herm : forall {m n}(A: Matrix m n), Hermitian (A†×A).\nProof. split. rewrite Mmult_adjoint. rewrite adjoint_involutive; easy.\nQed.\n\nLemma innprod_norm_ge0 : forall {n}(v: Vector n), 0 <= ⟨v,v⟩.\nProof. intros. repeat split; try lca; unfold inner_product.\napply astara_herm; nomega. unfold adjoint, Mmult; simpl.\ngeneralize dependent v. N.induct n; intros. simpl. lra. rewrite Csum_succ. apply Rplus_le_le_0_compat. auto.\nunfold C; simpl. nra.\nQed.\n\nInstance astara_psd : forall {m n}(A: Matrix m n),\n  PositiveSemidef (A†×A).\nProof. split. typeclasses eauto.\nunfold inner_product. intros. assert (v†×(A†×A×v)==(A×v)†×(A×v)).\nrewrite Mmult_assoc at 1. rewrite <- Mmult_assoc at 1.\nrewrite Mmult_adjoint. easy. rewrite H; try nomega. apply innprod_norm_ge0.\nQed.\n\nInstance orthproj_psd : forall {n} A `{OrthProjection n A}, PositiveSemidef A.\nProof. split. typeclasses eauto. intros. unfold inner_product. assert (v†×(A×v) == (A×v)†×(A×v)).\nrewrite <- cond_projection at 1. rewrite cond_hermitian at 1.\nrewrite Mmult_assoc at 1. rewrite <- Mmult_assoc at 1. rewrite Mmult_adjoint. easy.\nrewrite H0; try nomega. apply innprod_norm_ge0.\nQed.\n\nInstance psd_multlr_psd_herm : forall {n} A B `{PositiveSemidef n A}`{Hermitian n B},\n  Hermitian (B×A×B).\nProof. split. do 2 rewrite Mmult_adjoint. rewrite <- cond_hermitian.\nrewrite <- (@cond_hermitian _ A). apply Mmult_assoc. typeclasses eauto.\nQed.\n\nInstance psd_multlr_psd_psd : forall {n} A B `{PositiveSemidef n A}`{Hermitian n B},\n  PositiveSemidef (B×A×B).\nProof. split. typeclasses eauto.\nunfold inner_product. intros. assert (v†×(B×A×B×v)==((B×v)†×(A×(B×v)))).\ndo 5 rewrite <- Mmult_assoc. rewrite cond_hermitian at 1. rewrite Mmult_adjoint; easy.\nrewrite H1; try nomega. generalize (B×v). autounfold. apply cond_psd.\nQed.\n\n\nInstance density_pdm : forall {n} A `{Density n A},\n  PDM A.\nProof. intros. split. typeclasses eauto. rewrite cond_density.\nrepeat split; try lca; try nra. apply Rle_0_1.\nQed.\n\n\n\n\nInstance I_herm : forall {n}, Hermitian (I n).\nProof. split. unfold I, adjoint; mintros.\nrewrite N.eqb_sym; destruct (j =? i); lca.\nQed.\n\nInstance I_psd : forall {n}, PositiveSemidef (I n).\nProof. split. typeclasses eauto. intros. erewrite innprod_compat.\napply (vectnorm_nonneg v). easy. apply Mmult_1_l.\nQed.\n\nInstance I_unitary : forall {n}, Unitary (I n).\nProof. split. rewrite <- cond_hermitian. apply Mmult_1_l.\nQed.\n\nInstance zero_herm : forall {n}, Hermitian (Zero n n).\nProof. split; unfold I, adjoint; intros; lma. Qed.\n\nInstance zero_psd : forall {n}, PositiveSemidef (Zero n n).\nProof. split; try typeclasses eauto; intros. erewrite innprod_compat. unfold inner_product.\nrewrite Mmult_0_r; try nomega. unfold Zero; simpl. repeat split; try lca; lra.\nreflexivity. apply Mmult_0_l.\nQed.\n\n\nLemma trace_herm_herm_real : forall {n} A B `{Hermitian n A}`{Hermitian n B},\n  trace (A×B) = (trace (A×B))^*.\nProof. intros. rewrite cond_hermitian at 1; rewrite (@cond_hermitian _ B) at 1 by auto;\nrewrite <- Mmult_adjoint; rewrite trace_mult; unfold trace, adjoint;\nrewrite Csum_conj_distr; auto.\nQed.\n\nInstance orthproj_haspair : forall {n} A `{OrthProjection n A},\n  OrthProjection (I n .- A).\nProof. split. split. unfold Mminus. rewrite Mmult_plus_distr_l.\ndo 2 rewrite Mmult_plus_distr_r. repeat rewrite Mmult_1_l. repeat rewrite Mmult_1_r.\nrewrite Mplus_assoc. apply Mplus_compat. easy. rewrite Mmult_neg_cancel.\nrewrite cond_projection. lma. typeclasses eauto.\nQed.\n\n\n(** *********)\n\n(* Loewner Order *)\n\n\nClass loewner_le {n} (A B: Square n) :=\n  cond_lle :> PositiveSemidef (B .- A).\nAdd Parametric Morphism n : (@loewner_le n)\n  with signature mat_equiv ==> mat_equiv ==> iff as lle_mor.\nProof. do 2 split; intros; first [rewrite<-H; rewrite<-H0|rewrite H;rewrite H0];\nfirst [typeclasses eauto|apply cond_psd]. Qed.\n\nInfix \"⊑\" := loewner_le (at level 70) : matrix_scope.\nHint Unfold loewner_le.\n\nTheorem lle_refl : forall {n}(A:Square n) ,\n  A ⊑ A.\nProof. repeat autounfold; intros; simpl. split; [split|intros].\nrewrite Mminus_same. apply cond_hermitian. rewrite Mminus_same.\nrewrite Mmult_0_l. unfold inner_product; rewrite Mmult_0_r;\nunfold Zero; try nomega. apply Cle_0_0.\nQed.\n\nTheorem lle_trans : forall {n}(A B C: Square n),\n  A ⊑ B -> B ⊑ C -> A ⊑ C.\nProof. repeat autounfold; intros; simpl in *.\nassert (C.-A == (C.-B).+(B.-A)). unfold Mminus.\n  rewrite Mplus_assoc. rewrite <- (Mplus_assoc (.-B)).\n  rewrite (Mplus_comm (.-B)). setoid_rewrite Mminus_same.\n  rewrite Mplus_0_l. easy.\nrewrite H1. split. typeclasses eauto. intros. rewrite Mmult_plus_distr_r.\nrewrite innprod_distr_r. apply Cplus_le_le_0_compat; apply cond_psd.\nQed.\n\nAdd Parametric Relation n : (Square n) (@loewner_le n)\n      reflexivity proved by lle_refl\n      transitivity proved by lle_trans\n    as lle_rel.\n\nTheorem lle_antisym : forall {n} A B `{PositiveSemidef n A}`{PositiveSemidef n B},\n  A ⊑ B -> B ⊑ A -> A == B.\nProof. intros. mintros. autounfold in *. pose proof (@cond_psd _ _ H1). pose proof cond_psd. \nAbort.\n\nLemma lle_trace : forall {n}(A B:Square n),\n  A ⊑ B <-> forall (rho:Square n), PDM rho -> trace (A×rho) <= trace (B×rho).\nProof.\n  split; intros. assert (0 <= trace ((B .- A)×rho)).\n    unfold trace; simpl. apply Csum_ge0; intros.\nAdmitted.\n(* to prove this, need theorem that PDMs are lin combs of outer products *)\n(* to prove that, need Spectral Theorem *)\n(* Spectral Theorem requires the fundamental theorem of algebra, which is\n  beyond the scope of this project unless we depend on another library \n  for definitions and facts regarding the complex numbers *)\n\nInstance zero_lle_psd : forall {n} A `{PositiveSemidef n A},\n  Zero n n ⊑ A.\nProof. intros. autounfold. unfold Mminus. rewrite Mneg_zero_zero. rewrite Mplus_0_r. auto.\nQed.\n\n\n\n\n\n(** **************)\n\n(* Predicates *)\n\nClass Predicate {n} (A: Square n) := {\n  predicate_psd :> PositiveSemidef A;\n  cond_predicate : A ⊑ I n\n}.\nAdd Parametric Morphism n : (@Predicate n)\n  with signature mat_equiv ==> iff as predicate_mor.\nProof. do 2 split; first [rewrite <- H | rewrite H];\nfirst [typeclasses eauto|apply cond_predicate]. Qed.\n\n\n\n\n\n\nInstance orthproj_pred : forall {n} A `{OrthProjection n A},\n  Predicate A.\nProof. split; autounfold; typeclasses eauto.\nQed.\n\nInstance pdm_multlr_orthproj_pdm : forall {n} A P `{PDM A}`{OrthProjection n P},\n  PDM (P×A×P).\nProof. split. typeclasses eauto. rewrite trace_mult. rewrite <- Mmult_assoc.\nrewrite cond_projection. split. rewrite <- (@trace_zero n). erewrite <- Mmult_0_l.\napply lle_trace; typeclasses eauto. eapply Cle_trans. apply lle_trace.\napply cond_predicate. auto. rewrite Mmult_1_l. apply cond_pdm.\nQed.\n\nInstance psd_prod_psd : forall {n} A B `{PositiveSemidef n A}`{PositiveSemidef n B}`{Hermitian n (A×B)},\n  PositiveSemidef (A×B).\nProof.\nintros. split; eauto. intro. assert (⟨v, B×v⟩ + ⟨B×v, A×B×v⟩ <= ⟨v, A×B×v⟩).\nAbort.\n\n\n(*\nTheorem unitary_inverse_opp : forall {n} U,\n  Unitary U -> U† × U == I n.\nProof. intros.\n  by_cell. pose proof unitary. unfold I; destruct (i =? j) eqn:H1.\n  pose proof (beq_nat_true _ _ H1). subst.\n  unfold adjoint, Mmult in *; simpl in *. specialize (H0 j j); simpl in *.\n*)\n\n(*\nTheorem hermitian_evals_real : forall {n} (M : Matrix n n),\n  Hermitian M -> forall (x : Vector n), im ⟨ x, M × x ⟩ = 0.\nProof.\n  intros. apply Creal_conj. unfold inner_product.\n  assert (Hermitian (x† × (M × x))).\n    unfold Hermitian. do 2 rewrite Mmult_adjoint.\n    rewrite adjoint_involutive. rewrite <- Mmult_assoc.\n    apply Mmult_compat. apply Mmult_compat.\n      easy. apply hermitian. easy.\n  rewrite H0 at 1; auto.\nQed.\n*)\n\n(*\n\nDefinition Lowner_le {n}(A B:Matrix n n) := \n  PositiveSemidef A /\\ PositiveSemidef B /\\ PositiveSemidef (B .- A).\n\n(* change this notation to unicode *)\nInfix \"⊑\" := Lowner_le (at level 70) : matrix_scope.\n\nTheorem Lowner_density_trace : forall {n}(A B: Matrix n n),\n  A =[ B <-> forall rho, PartialDensityMatrix rho -> trace (A×rho) <= trace (B×rho).\nProof.\n  split; intros. split.\n\n*)\nLemma Npow_succ : forall m n:N, (m ^ (N.succ n) = m^n * m)%N.\nProof. intros; rewrite N.pow_succ_r'; apply N.mul_comm.\nQed.\n\nLemma kron_prop_tensor_prop : forall (MatProp : forall k, Square k -> Prop),\n  (forall m n (A:Square m)(B:Square n), MatProp _ A -> MatProp _ B -> MatProp _ (A⊗B))\n    -> MatProp _ (I 1)\n    -> forall n m (f:N -> Square m),\n        (forall k, (k<n)%N -> MatProp _ (f k)) -> MatProp _ (tensor n f).\nProof. intros MatProp kron_prop HI n. N.induct n; intros.\n- simpl. auto.\n- rewrite tensor_succ_eq. rewrite Npow_succ. apply kron_prop.\napply H. intros. apply H0; nomega. apply H0; nomega.\nQed.\n\nInstance kron_unitary : forall {m n} (A:Square m)(B:Square n),\n  Unitary A -> Unitary B -> Unitary (A⊗B).\nProof. intros. split. rewrite kron_adjoint.\nrewrite kron_mult. do 2 rewrite cond_unitary. apply kron_1.\nQed.\n\nInstance tensor_unitary : forall n m (f:N -> Square m),\n  (forall k, (k<n)%N -> Unitary (f k)) -> Unitary (tensor n f).\nProof. intros. apply kron_prop_tensor_prop; typeclasses eauto.\nQed.\n\nInstance kron_herm : forall {m n} (A:Square m)(B:Square n),\n  Hermitian A -> Hermitian B -> Hermitian (A⊗B).\nProof. intros. split. rewrite kron_adjoint.\nrewrite cond_hermitian at 1; rewrite (@cond_hermitian _ B) at 1; [reflexivity|auto].\nQed.\n\nInstance tensor_herm : forall n m (f:N -> Square m),\n  (forall k, (k<n)%N -> Hermitian (f k)) -> Hermitian (tensor n f).\nProof. intros; apply kron_prop_tensor_prop; typeclasses eauto.\nQed.\n\nInstance kron_proj : forall {m n} (A:Square m)(B:Square n),\n  Projection A -> Projection B -> Projection (A⊗B).\nProof. intros. split. rewrite kron_mult.\nrepeat rewrite cond_projection. reflexivity.\nQed.\n\nInstance tensor_proj : forall n m (f:N -> Square m),\n  (forall k, (k<n)%N -> Unitary (f k)) -> Unitary (tensor n f).\nProof. apply kron_prop_tensor_prop; typeclasses eauto.\nQed.\n\n\n\nInstance kron_psd : forall {m n} (A:Square m)(B:Square n),\n  PositiveSemidef A -> PositiveSemidef B -> PositiveSemidef (A⊗B).\nProof. intros. split. typeclasses eauto.\nintros. unfold inner_product.\nAbort.\n\n\nDefinition psd_alt {n}(A:Square n) :=\n  forall λ (v:Vector n),  ~(v == Zero _ _) -> A×v == λ .* v -> 0 <= λ.\n\nTheorem psd_psd_alt : forall {n}(A:Square n), PositiveSemidef A <-> psd_alt A.\nProof. split; intros.\n- admit.\n- split. split. mintros. unfold adjoint. unfold psd_alt in H. Abort.\n\n\n(*\n split; intros. split. lca. split. pose proof (cond_psd v).\nrewrite H1 in H2. unfold inner_product in H2. rewrite <- Mscale_mult_comm in H2.\nunfold Mscale in H2. inversion H2. inversion H4. rewrite Cconj_mult_distr in H5.\nrewrite (@cond_hermitian _ _ _ 0%N 0%N) in H5 at 1. unfold adjoint in H5 at 1.\nassert ((v†×v) 0%N 0%N <> 0). intro.\nrewrite Mmult_adjoint in H5.*)\n\n\n\n\n\n\n\n\n\n\n(*\nDefinition change_dim {m n}(A:Matrix m n) o p : Matrix o p := A.\n\nLtac mat_eq_dim2 o p :=\n  match goal with\n  |[|- @mat_equiv ?m ?n ?A ?B] =>\n         unfold mat_equiv; replace m with o; replace n with p;\n           fold (@mat_equiv o p A B)\n  end.\n\nLtac mat_eq_dim p :=\n  match goal with\n  |[|- @mat_equiv ?m ?m ?A ?B] =>\n         unfold mat_equiv; replace m with p;\n           fold (@mat_equiv p p (change_dim A p p) (change_dim B p p))\n  end.\n\nTheorem mat_eq_stuff : forall m1 n1 m2 n2 (A B: N -> N -> C),\n  m1 = m2 -> n1 = n2 -> @mat_equiv m1 n1 A B -> @mat_equiv m2 n2 A B.\nProof. unfold mat_equiv. intros. apply H1; nomega.\nQed.\n*)\n  \n\n", "meta": {"author": "rcraigfiedorek", "repo": "QuantumHoareLogic", "sha": "0bd6fc9b32a67f910eee961a53ba0481b8179a21", "save_path": "github-repos/coq/rcraigfiedorek-QuantumHoareLogic", "path": "github-repos/coq/rcraigfiedorek-QuantumHoareLogic/QuantumHoareLogic-0bd6fc9b32a67f910eee961a53ba0481b8179a21/theories/Matrix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7199011629057002}}
{"text": "Require Export XR_pos_INR.\nRequire Export XR_Rle_lt_trans.\nRequire Export XR_Rplus_eq_compat_r.\n\nLocal Open Scope R_scope.\n\nLemma not_0_INR : forall n:nat,\n  n <> 0%nat ->\n  INR n <> R0.\nProof.\n  intros n h.\n  unfold not.\n  intro eq.\n  unfold not in h.\n  apply h.\n  destruct n as [ | n ].\n  { reflexivity. }\n  {\n    rewrite S_INR in eq.\n    clear h.\n    exfalso.\n    apply (Rplus_eq_compat_r (-R1) _  _ ) in eq.\n    rewrite Rplus_assoc in eq.\n    rewrite Rplus_opp_r in eq.\n    rewrite Rplus_0_r in eq.\n    rewrite Rplus_0_l in eq.\n    apply Rlt_irrefl with R0.\n    apply Rle_lt_trans with (INR n).\n    { apply pos_INR. }\n    {\n      rewrite eq.\n      clear eq n.\n      rewrite <- Ropp_0.\n      apply Ropp_lt_contravar.\n      exact Rlt_0_1.\n    }\n  }\nQed.\n\n\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_not_0_INR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.719901156410929}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nFrom mathcomp\nRequire Import finfun bigop prime binomial ssralg finset fingroup finalg.\nFrom mathcomp\nRequire Import perm zmodp matrix.\n\n(*****************************************************************************)\n(* In this file we develop the rank and row space theory of matrices, based  *)\n(* on an extended Gaussian elimination procedure similar to LUP              *)\n(* decomposition. This provides us with a concrete but generic model of      *)\n(* finite dimensional vector spaces and F-algebras, in which vectors, linear *)\n(* functions, families, bases, subspaces, ideals and subrings are all        *)\n(* represented using matrices. This model can be used as a foundation for    *)\n(* the usual theory of abstract linear algebra, but it can also be used to   *)\n(* develop directly substantial theories, such as the theory of finite group *)\n(* linear representation.                                                    *)\n(*   Here we define the following concepts and notations:                    *)\n(* Gaussian_elimination A == a permuted triangular decomposition (L, U, r)   *)\n(*                   of A, with L a column permutation of a lower triangular *)\n(*                   invertible matrix, U a row permutation of an upper      *)\n(*                   triangular invertible matrix, and r the rank of A, all  *)\n(*                   satisfying the identity L *m pid_mx r *m U = A.         *)\n(*        \\rank A == the rank of A.                                          *)\n(*    row_free A <=> the rows of A are linearly free (i.e., the rank and     *)\n(*                   height of A are equal).                                 *)\n(*    row_full A <=> the row-space of A spans all row-vectors (i.e., the     *)\n(*                   rank and width of A are equal).                         *)\n(*    col_ebase A == the extended column basis of A (the first matrix L      *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*    row_ebase A == the extended row base of A (the second matrix U         *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*     col_base A == a basis for the columns of A: a row-full matrix         *)\n(*                   consisting of the first \\rank A columns of col_ebase A. *)\n(*     row_base A == a basis for the rows of A: a row-free matrix consisting *)\n(*                   of the first \\rank A rows of row_ebase A.               *)\n(*       pinvmx A == a partial inverse for A in its row space (or on its     *)\n(*                   column space, equivalently). In particular, if u is a   *)\n(*                   row vector in the row_space of A, then u *m pinvmx A is *)\n(*                   the row vector of the coefficients of a decomposition   *)\n(*                   of u as a sub of rows of A.                             *)\n(*        kermx A == the row kernel of A : a square matrix whose row space   *)\n(*                   consists of all u such that u *m A = 0 (it consists of  *)\n(*                   the inverse of col_ebase A, with the top \\rank A rows   *)\n(*                   zeroed out). Also, kermx A is a partial right inverse   *)\n(*                   to col_ebase A, in the row space anihilated by A.       *)\n(*      cokermx A == the cokernel of A : a square matrix whose column space  *)\n(*                   consists of all v such that A *m v = 0 (it consists of  *)\n(*                   the inverse of row_ebase A, with the leftmost \\rank A   *)\n(*                   columns zeroed out).                                    *)\n(* eigenvalue g a <=> a is an eigenvalue of the square matrix g.             *)\n(* eigenspace g a == a square matrix whose row space is the eigenspace of    *)\n(*                   the eigenvalue a of g (or 0 if a is not an eigenvalue). *)\n(* We use a different scope %MS for matrix row-space set-like operations; to *)\n(* avoid confusion, this scope should not be opened globally. Note that the  *)\n(* the arguments of \\rank _ and the operations below have default scope %MS. *)\n(*    (A <= B)%MS <=> the row-space of A is included in the row-space of B.  *)\n(*                   We test for this by testing if cokermx B anihilates A.  *)\n(*     (A < B)%MS <=> the row-space of A is properly included in the         *)\n(*                   row-space of B.                                         *)\n(*  (A <= B <= C)%MS == (A <= B)%MS && (B <= C)%MS, and similarly for        *)\n(*                   (A < B <= C)%MS, (A < B <= C)%MS and (A < B < C)%MS.    *)\n(*    (A == B)%MS == (A <= B <= A)%MS (A and B have the same row-space).     *)\n(*   (A :=: B)%MS == A and B behave identically wrt. \\rank and <=. This      *)\n(*                   triple rewrite rule is the Prop version of (A == B)%MS. *)\n(*                   Note that :=: cannot be treated as a setoid-style       *)\n(*                   Equivalence because its arguments can have different    *)\n(*                   types: A and B need not have the same number of rows,   *)\n(*                   and often don't (e.g., in row_base A :=: A).            *)\n(*       <<A>>%MS == a square matrix with the same row-space as A; <<A>>%MS  *)\n(*                   is a canonical representation of the subspace generated *)\n(*                   by A, viewed as a list of row-vectors: if (A == B)%MS,  *)\n(*                   then <<A>>%MS = <<B>>%MS.                               *)\n(*     (A + B)%MS == a square matrix whose row-space is the sum of the       *)\n(*                   row-spaces of A and B; thus (A + B == col_mx A B)%MS.   *)\n(*  (\\sum_i <expr i>)%MS == the \"big\" version of (_ + _)%MS; as the latter   *)\n(*                   has a canonical abelian monoid structure, most generic  *)\n(*                   bigop lemmas apply (the other bigop indexing notations  *)\n(*                   are also defined).                                      *)\n(*   (A :&: B)%MS == a square matrix whose row-space is the intersection of  *)\n(*                   the row-spaces of A and B.                              *)\n(*  (\\bigcap_i <expr i>)%MS == the \"big\" version of (_ :&: _)%MS, which also *)\n(*                   has a canonical abelian monoid structure.               *)\n(*         A^C%MS == a square matrix whose row-space is a complement to the  *)\n(*                   the row-space of A (it consists of row_ebase A with the *)\n(*                   top \\rank A rows zeroed out).                           *)\n(*   (A :\\: B)%MS == a square matrix whose row-space is a complement of the  *)\n(*                   the row-space of (A :&: B)%MS in the row-space of A.    *)\n(*                   We have (A :\\: B := A :&: (capmx_gen A B)^C)%MS, where  *)\n(*                   capmx_gen A B is a rectangular matrix equivalent to     *)\n(*                   (A :&: B)%MS, i.e., (capmx_gen A B == A :&: B)%MS.      *)\n(*    proj_mx A B == a square matrix that projects (A + B)%MS onto A         *)\n(*                   parallel to B, when (A :&: B)%MS = 0 (A and B must also *)\n(*                   be square).                                             *)\n(*     mxdirect S == the sum expression S is a direct sum. This is a NON     *)\n(*                   EXTENSIONAL notation: the exact boolean expression is   *)\n(*                   inferred from the syntactic form of S (expanding        *)\n(*                   definitions, however); both (\\sum_(i | _) _)%MS and     *)\n(*                   (_ + _)%MS sums are recognized. This construct uses a   *)\n(*                   variant of the reflexive (\"quote\") canonical structure, *)\n(*                   mxsum_expr. The structure also recognizes sums of       *)\n(*                   matrix ranks, so that lemmas concerning the rank of     *)\n(*                   direct sums can be used bidirectionally.                *)\n(* The next set of definitions let us represent F-algebras using matrices:   *)\n(*   'A[F]_(m, n) == the type of matrices encoding (sub)algebras of square   *)\n(*                   n x n matrices, via mxvec; as in the matrix type        *)\n(*                   notation, m and F can be omitted (m defaults to n ^ 2). *)\n(*                := 'M[F]_(m, n ^ 2).                                       *)\n(*   (A \\in R)%MS <=> the square matrix A belongs to the linear set of       *)\n(*                    matrices (most often, a sub-algebra) encoded by the    *)\n(*                    row space of R. This is simply notation, so all the    *)\n(*                    lemmas and rewrite rules for (_ <= _)%MS can apply.    *)\n(*                := (mxvec A <= R)%MS.                                      *)\n(*     (R * S)%MS == a square n^2 x n^2 matrix whose row-space encodes the   *)\n(*                   linear set of n x n matrices generated by the pointwise *)\n(*                   product of the sets of matrices encoded by R and S.     *)\n(*       'C(R)%MS == a square matric encoding the centraliser of the set of  *)\n(*                   square matrices encoded by R.                           *)\n(*     'C_S(R)%MS := (S :&: 'C(R))%MS (the centraliser of R in S).           *)\n(*       'Z(R)%MS == the center of R (i.e., 'C_R(R)%MS).                     *)\n(*  left_mx_ideal R S <=> S is a left ideal for R (R * S <= S)%MS.           *)\n(* right_mx_ideal R S <=> S is a right ideal for R (S * R <= S)%MS.          *)\n(*       mx_ideal R S <=> S is a bilateral ideal for R.                      *)\n(*      mxring_id R e <-> e is an identity element for R (Prop predicate).   *)\n(*    has_mxring_id R <=> R has a nonzero identity element (bool predicate). *)\n(*           mxring R <=> R encodes a nontrivial subring.                    *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope.\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nReserved Notation \"\\rank A\" (at level 10, A at level 8, format \"\\rank  A\").\nReserved Notation \"A ^C\"    (at level 8, format \"A ^C\").\n\nNotation \"''A_' ( m , n )\" := 'M_(m, n ^ 2)\n  (at level 8, format \"''A_' ( m ,  n )\") : type_scope.\n\nNotation \"''A_' ( n )\" := 'A_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A_' n\" := 'A_(n)\n  (at level 8, n at next level, format \"''A_' n\") : type_scope.\n\nNotation \"''A' [ F ]_ ( m , n )\" := 'M[F]_(m, n ^ 2)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ ( n )\" := 'A[F]_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ n\" := 'A[F]_(n)\n  (at level 8, n at level 2, only parsing) : type_scope.\n\nDelimit Scope matrix_set_scope with MS.\n\nLocal Notation simp := (Monoid.Theory.simpm, oppr0).\n\n(*****************************************************************************)\n(******************** Rank and row-space theory ******************************)\n(*****************************************************************************)\n\nSection RowSpaceTheory.\n\nVariable F : fieldType.\nImplicit Types m n p r : nat.\n\nLocal Notation \"''M_' ( m , n )\" := 'M[F]_(m, n) : type_scope.\nLocal Notation \"''M_' n\" := 'M[F]_(n, n) : type_scope.\n\n(* Decomposition with double pivoting; computes the rank, row and column  *)\n(* images, kernels, and complements of a matrix.                          *)\n\nFixpoint Gaussian_elimination {m n} : 'M_(m, n) -> 'M_m * 'M_n * nat :=\n  match m, n with\n  | _.+1, _.+1 => fun A : 'M_(1 + _, 1 + _) =>\n    if [pick ij | A ij.1 ij.2 != 0] is Some (i, j) then\n      let a := A i j in let A1 := xrow i 0 (xcol j 0 A) in\n      let u := ursubmx A1 in let v := a^-1 *: dlsubmx A1 in\n      let: (L, U, r) := Gaussian_elimination (drsubmx A1 - v *m u) in\n      (xrow i 0 (block_mx 1 0 v L), xcol j 0 (block_mx a%:M u 0 U), r.+1)\n    else (1%:M, 1%:M, 0%N)\n  | _, _ => fun _ => (1%:M, 1%:M, 0%N)\n  end.\n\nSection Defs.\n\nVariables (m n : nat) (A : 'M_(m, n)).\n\nFact Gaussian_elimination_key : unit. Proof. by []. Qed.\n\nLet LUr := locked_with Gaussian_elimination_key (@Gaussian_elimination) m n A.\n\nDefinition col_ebase := LUr.1.1.\nDefinition row_ebase := LUr.1.2.\nDefinition mxrank := if [|| m == 0 | n == 0]%N then 0%N else LUr.2.\n\nDefinition row_free := mxrank == m.\nDefinition row_full := mxrank == n.\n\nDefinition row_base : 'M_(mxrank, n) := pid_mx mxrank *m row_ebase.\nDefinition col_base : 'M_(m, mxrank) := col_ebase *m pid_mx mxrank.\n\nDefinition complmx : 'M_n := copid_mx mxrank *m row_ebase.\nDefinition kermx : 'M_m := copid_mx mxrank *m invmx col_ebase.\nDefinition cokermx : 'M_n := invmx row_ebase *m copid_mx mxrank.\n\nDefinition pinvmx : 'M_(n, m) :=\n  invmx row_ebase *m pid_mx mxrank *m invmx col_ebase.\n\nEnd Defs.\n\nArguments mxrank {m%N n%N} A%MS.\nLocal Notation \"\\rank A\" := (mxrank A) : nat_scope.\nArguments complmx {m%N n%N} A%MS.\nLocal Notation \"A ^C\" := (complmx A) : matrix_set_scope.\n\nDefinition submx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  A *m cokermx B == 0).\nFact submx_key : unit. Proof. by []. Qed.\nDefinition submx := locked_with submx_key submx_def.\nCanonical submx_unlockable := [unlockable fun submx].\n\nArguments submx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A <= B\" := (submx A B) : matrix_set_scope.\nLocal Notation \"A <= B <= C\" := ((A <= B) && (B <= C))%MS : matrix_set_scope.\nLocal Notation \"A == B\" := (A <= B <= A)%MS : matrix_set_scope.\n\nDefinition ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  (A <= B)%MS && ~~ (B <= A)%MS.\nArguments ltmx {m1%N m2%N n%N} A%MS B%MS.\nLocal Notation \"A < B\" := (ltmx A B) : matrix_set_scope.\n\nDefinition eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  prod (\\rank A = \\rank B)\n       (forall m3 (C : 'M_(m3, n)),\n            ((A <= C) = (B <= C)) * ((C <= A) = (C <= B)))%MS.\nArguments eqmx {m1%N m2%N n%N} A%MS B%MS.\nLocal Notation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\n\nSection LtmxIdentities.\n\nVariables (m1 m2 n : nat) (A : 'M_(m1, n)) (B : 'M_(m2, n)).\n\nLemma ltmxE : (A < B)%MS = ((A <= B)%MS && ~~ (B <= A)%MS). Proof. by []. Qed.\n\nLemma ltmxW : (A < B)%MS -> (A <= B)%MS. Proof. by case/andP. Qed.\n\nLemma ltmxEneq : (A < B)%MS = (A <= B)%MS && ~~ (A == B)%MS.\nProof. by apply: andb_id2l => ->. Qed.\n\nLemma submxElt : (A <= B)%MS = (A == B)%MS || (A < B)%MS.\nProof. by rewrite -andb_orr orbN andbT. Qed.\n\nEnd LtmxIdentities.\n\n(* The definition of the row-space operator is rigged to return the identity  *)\n(* matrix for full matrices. To allow for further tweaks that will make the   *)\n(* row-space intersection operator strictly commutative and monoidal, we      *)\n(* slightly generalize some auxiliary definitions: we parametrize the         *)\n(* \"equivalent subspace and identity\" choice predicate equivmx by a boolean   *)\n(* determining whether the matrix should be the identity (so for genmx A its  *)\n(* value is row_full A), and introduce a \"quasi-identity\" predicate qidmx     *)\n(* that selects non-square full matrices along with the identity matrix 1%:M  *)\n(* (this does not affect genmx, which chooses a square matrix).               *)\n(*   The choice witness for genmx A is either 1%:M for a row-full A, or else  *)\n(* row_base A padded with null rows.                                          *)\nLet qidmx m n (A : 'M_(m, n)) :=\n  if m == n then A == pid_mx n else row_full A.\nLet equivmx m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  (B == A)%MS && (qidmx B == idA).\nLet equivmx_spec m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  prod (B :=: A)%MS (qidmx B = idA).\nDefinition genmx_witness m n (A : 'M_(m, n)) : 'M_n :=\n  if row_full A then 1%:M else pid_mx (\\rank A) *m row_ebase A.\nDefinition genmx_def := idfun (fun m n (A : 'M_(m, n)) =>\n   choose (equivmx A (row_full A)) (genmx_witness A) : 'M_n).\nFact genmx_key : unit. Proof. by []. Qed.\nDefinition genmx := locked_with genmx_key genmx_def.\nCanonical genmx_unlockable := [unlockable fun genmx].\nLocal Notation \"<< A >>\" := (genmx A) : matrix_set_scope.\n\n(* The setwise sum is tweaked so that 0 is a strict identity element for      *)\n(* square matrices, because this lets us use the bigop component. As a result *)\n(* setwise sum is not quite strictly extensional.                             *)\nLet addsmx_nop m n (A : 'M_(m, n)) := conform_mx <<A>>%MS A.\nDefinition addsmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if A == 0 then addsmx_nop B else if B == 0 then addsmx_nop A else\n  <<col_mx A B>>%MS : 'M_n).\nFact addsmx_key : unit. Proof. by []. Qed.\nDefinition addsmx := locked_with addsmx_key addsmx_def.\nCanonical addsmx_unlockable := [unlockable fun addsmx].\nArguments addsmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A + B\" := (addsmx A B) : matrix_set_scope.\nLocal Notation \"\\sum_ ( i | P ) B\" := (\\big[addsmx/0]_(i | P) B%MS)\n  : matrix_set_scope.\nLocal Notation \"\\sum_ ( i <- r | P ) B\" := (\\big[addsmx/0]_(i <- r | P) B%MS)\n  : matrix_set_scope.\n\n(* The set intersection is similarly biased so that the identity matrix is a  *)\n(* strict identity. This is somewhat more delicate than for the sum, because  *)\n(* the test for the identity is non-extensional. This forces us to actually   *)\n(* bias the choice operator so that it does not accidentally map an           *)\n(* intersection of non-identity matrices to 1%:M; this would spoil            *)\n(* associativity: if B :&: C = 1%:M but B and C are not identity, then for a  *)\n(* square matrix A we have A :&: (B :&: C) = A != (A :&: B) :&: C in general. *)\n(* To complicate matters there may not be a square non-singular matrix        *)\n(* different than 1%:M, since we could be dealing with 'M['F_2]_1. We         *)\n(* sidestep the issue by making all non-square row-full matrices identities,  *)\n(* and choosing a normal representative that preserves the qidmx property.    *)\n(* Thus A :&: B = 1%:M iff A and B are both identities, and this suffices for *)\n(* showing that associativity is strict.                                      *)\nLet capmx_witness m n (A : 'M_(m, n)) :=\n  if row_full A then conform_mx 1%:M A else <<A>>%MS.\nLet capmx_norm m n (A : 'M_(m, n)) :=\n  choose (equivmx A (qidmx A)) (capmx_witness A).\nLet capmx_nop m n (A : 'M_(m, n)) := conform_mx (capmx_norm A) A.\nDefinition capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  lsubmx (kermx (col_mx A B)) *m A.\nDefinition capmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if qidmx A then capmx_nop B else\n  if qidmx B then capmx_nop A else\n  if row_full B then capmx_norm A else capmx_norm (capmx_gen A B) : 'M_n).\nFact capmx_key : unit. Proof. by []. Qed.\nDefinition capmx := locked_with capmx_key capmx_def.\nCanonical capmx_unlockable := [unlockable fun capmx].\nArguments capmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nLocal Notation \"\\bigcap_ ( i | P ) B\" := (\\big[capmx/1%:M]_(i | P) B)\n  : matrix_set_scope.\n\nDefinition diffmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  <<capmx_gen A (capmx_gen A B)^C>>%MS : 'M_n).\nFact diffmx_key : unit. Proof. by []. Qed.\nDefinition diffmx := locked_with diffmx_key diffmx_def.\nCanonical diffmx_unlockable := [unlockable fun diffmx].\nArguments diffmx {m1%N m2%N n%N} A%MS B%MS : rename.\nLocal Notation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\n\nDefinition proj_mx n (U V : 'M_n) : 'M_n := pinvmx (col_mx U V) *m col_mx U 0.\n\nLocal Notation GaussE := Gaussian_elimination.\n\nFact mxrankE m n (A : 'M_(m, n)) : \\rank A = (GaussE A).2.\nProof. by rewrite /mxrank unlock /=; case: m n A => [|m] [|n]. Qed.\n\nLemma rank_leq_row m n (A : 'M_(m, n)) : \\rank A <= m.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma row_leq_rank m n (A : 'M_(m, n)) : (m <= \\rank A) = row_free A.\nProof. by rewrite /row_free eqn_leq rank_leq_row. Qed.\n\nLemma rank_leq_col m n (A : 'M_(m, n)) : \\rank A <= n.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma col_leq_rank m n (A : 'M_(m, n)) : (n <= \\rank A) = row_full A.\nProof. by rewrite /row_full eqn_leq rank_leq_col. Qed.\n\nLet unitmx1F := @unitmx1 F.\nLemma row_ebase_unit m n (A : 'M_(m, n)) : row_ebase A \\in unitmx.\nProof.\nrewrite /row_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] /= nzAij | //=]; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uU.\nrewrite unitmxE xcolE det_mulmx (@det_ublock _ 1) det_scalar1 !unitrM.\nby rewrite unitfE nzAij -!unitmxE uU unitmx_perm.\nQed.\n\nLemma col_ebase_unit m n (A : 'M_(m, n)) : col_ebase A \\in unitmx.\nProof.\nrewrite /col_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] _|] //=; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uL.\nrewrite unitmxE xrowE det_mulmx (@det_lblock _ 1) det1 mul1r unitrM.\nby rewrite -unitmxE unitmx_perm.\nQed.\nHint Resolve rank_leq_row rank_leq_col row_ebase_unit col_ebase_unit : core.\n\nLemma mulmx_ebase m n (A : 'M_(m, n)) :\n  col_ebase A *m pid_mx (\\rank A) *m row_ebase A = A.\nProof.\nrewrite mxrankE /col_ebase /row_ebase unlock.\nelim: m n A => [n A | m IHm]; first by rewrite [A]flatmx0 [_ *m _]flatmx0.\ncase=> [A | n]; first by rewrite [_ *m _]thinmx0 [A]thinmx0.\nrewrite -(add1n m) -?(add1n n) => A /=.\ncase: pickP => [[i0 j0] | A0] /=; last first.\n  apply/matrixP=> i j; rewrite pid_mx_0 mulmx0 mul0mx mxE.\n  by move/eqP: (A0 (i, j)).\nset a := A i0 j0 => nz_a; set A1 := xrow _ _ _.\nset u := ursubmx _; set v := _ *: _; set B : 'M_(m, n) := _ - _.\nmove: (rank_leq_col B) (rank_leq_row B) {IHm}(IHm n B); rewrite mxrankE.\ncase: (GaussE B) => [[L U] r] /= r_m r_n defB.\nhave ->: pid_mx (1 + r) = block_mx 1 0 0 (pid_mx r) :> 'M[F]_(1 + m, 1 + n).\n  rewrite -(subnKC r_m) -(subnKC r_n) pid_mx_block -col_mx0 -row_mx0.\n  by rewrite block_mxA castmx_id col_mx0 row_mx0 -scalar_mx_block -pid_mx_block.\nrewrite xcolE xrowE mulmxA -xcolE -!mulmxA.\nrewrite !(addr0, add0r, mulmx0, mul0mx, mulmx_block, mul1mx) mulmxA defB.\nrewrite addrC subrK mul_mx_scalar scalerA divff // scale1r.\nhave ->: a%:M = ulsubmx A1 by rewrite [_ A1]mx11_scalar !mxE !lshift0 !tpermR.\nrewrite submxK /A1 xrowE !xcolE -!mulmxA mulmxA -!perm_mxM !tperm2 !perm_mx1.\nby rewrite mulmx1 mul1mx.\nQed.\n\nLemma mulmx_base m n (A : 'M_(m, n)) : col_base A *m row_base A = A.\nProof. by rewrite mulmxA -[col_base A *m _]mulmxA pid_mx_id ?mulmx_ebase. Qed.\n\nLemma mulmx1_min_rank r m n (A : 'M_(m, n)) M N :\n  M *m A *m N = 1%:M :> 'M_r -> r <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) mulmxA -mulmxA; move/mulmx1_min. Qed.\nArguments mulmx1_min_rank [r m n A].\n\nLemma mulmx_max_rank r m n (M : 'M_(m, r)) (N : 'M_(r, n)) :\n  \\rank (M *m N) <= r.\nProof.\nset MN := M *m N; set rMN := \\rank _.\npose L : 'M_(rMN, m) := pid_mx rMN *m invmx (col_ebase MN).\npose U : 'M_(n, rMN) := invmx (row_ebase MN) *m pid_mx rMN.\nsuffices: L *m M *m (N *m U) = 1%:M by apply: mulmx1_min.\nrewrite mulmxA -(mulmxA L) -[M *m N]mulmx_ebase -/MN.\nby rewrite !mulmxA mulmxKV // mulmxK // !pid_mx_id /rMN ?pid_mx_1.\nQed.\nArguments mulmx_max_rank [r m n].\n\nLemma mxrank_tr m n (A : 'M_(m, n)) : \\rank A^T = \\rank A.\nProof.\napply/eqP; rewrite eqn_leq -{3}[A]trmxK -{1}(mulmx_base A) -{1}(mulmx_base A^T).\nby rewrite !trmx_mul !mulmx_max_rank.\nQed.\n\nLemma mxrank_add m n (A B : 'M_(m, n)) : \\rank (A + B)%R <= \\rank A + \\rank B.\nProof.\nby rewrite -{1}(mulmx_base A) -{1}(mulmx_base B) -mul_row_col mulmx_max_rank.\nQed.\n\nLemma mxrankM_maxl m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) -mulmxA mulmx_max_rank. Qed.\n\nLemma mxrankM_maxr m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank B.\nProof. by rewrite -mxrank_tr -(mxrank_tr B) trmx_mul mxrankM_maxl. Qed.\n\nLemma mxrank_scale m n a (A : 'M_(m, n)) : \\rank (a *: A) <= \\rank A.\nProof. by rewrite -mul_scalar_mx mxrankM_maxr. Qed.\n\nLemma mxrank_scale_nz m n a (A : 'M_(m, n)) :\n   a != 0 -> \\rank (a *: A) = \\rank A.\nProof.\nmove=> nza; apply/eqP; rewrite eqn_leq -{3}[A]scale1r -(mulVf nza).\nby rewrite -scalerA !mxrank_scale.\nQed.\n\nLemma mxrank_opp m n (A : 'M_(m, n)) : \\rank (- A) = \\rank A.\nProof. by rewrite -scaleN1r mxrank_scale_nz // oppr_eq0 oner_eq0. Qed.\n\nLemma mxrank0 m n : \\rank (0 : 'M_(m, n)) = 0%N.\nProof. by apply/eqP; rewrite -leqn0 -(@mulmx0 _ m 0 n 0) mulmx_max_rank. Qed.\n\nLemma mxrank_eq0 m n (A : 'M_(m, n)) : (\\rank A == 0%N) = (A == 0).\nProof.\napply/eqP/eqP=> [rA0 | ->{A}]; last exact: mxrank0.\nmove: (col_base A) (row_base A) (mulmx_base A); rewrite rA0 => Ac Ar <-.\nby rewrite [Ac]thinmx0 mul0mx.\nQed.\n\nLemma mulmx_coker m n (A : 'M_(m, n)) : A *m cokermx A = 0.\nProof.\nby rewrite -{1}[A]mulmx_ebase -!mulmxA mulKVmx // mul_pid_mx_copid ?mulmx0.\nQed.\n\nLemma submxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS = (A *m cokermx B == 0).\nProof. by rewrite unlock. Qed.\n\nLemma mulmxKpV m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> A *m pinvmx B *m B = A.\nProof.\nrewrite submxE !mulmxA mulmxBr mulmx1 subr_eq0 => /eqP defA.\nrewrite -{4}[B]mulmx_ebase -!mulmxA mulKmx //.\nby rewrite (mulmxA (pid_mx _)) pid_mx_id // !mulmxA -{}defA mulmxKV.\nQed.\n\nLemma submxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists D, A = D *m B) (A <= B)%MS.\nProof.\napply: (iffP idP) => [/mulmxKpV | [D ->]]; first by exists (A *m pinvmx B).\nby rewrite submxE -mulmxA mulmx_coker mulmx0.\nQed.\nArguments submxP {m1 m2 n A B}.\n\nLemma submx_refl m n (A : 'M_(m, n)) : (A <= A)%MS.\nProof. by rewrite submxE mulmx_coker. Qed.\nHint Resolve submx_refl : core.\n\nLemma submxMl m n p (D : 'M_(m, n)) (A : 'M_(n, p)) : (D *m A <= A)%MS.\nProof. by rewrite submxE -mulmxA mulmx_coker mulmx0. Qed.\n\nLemma submxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A <= B)%MS -> (A *m C <= B *m C)%MS.\nProof. by case/submxP=> D ->; rewrite -mulmxA submxMl. Qed.\n\nLemma mulmx_sub m n1 n2 p (C : 'M_(m, n1)) A (B : 'M_(n2, p)) :\n  (A <= B -> C *m A <= B)%MS.\nProof. by case/submxP=> D ->; rewrite mulmxA submxMl. Qed.\n\nLemma submx_trans m1 m2 m3 n\n                 (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B -> B <= C -> A <= C)%MS.\nProof. by case/submxP=> D ->{A}; apply: mulmx_sub. Qed.\n\nLemma ltmx_sub_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A < B)%MS -> (B <= C)%MS -> (A < C)%MS.\nProof.\ncase/andP=> sAB ltAB sBC; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltAB; apply: submx_trans.\nQed.\n\nLemma sub_ltmx_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B)%MS -> (B < C)%MS -> (A < C)%MS.\nProof.\nmove=> sAB /andP[sBC ltBC]; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltBC => sCA; apply: submx_trans sAB.\nQed.\n\nLemma ltmx_trans m n : transitive (@ltmx m m n).\nProof. by move=> A B C; move/ltmxW; apply: sub_ltmx_trans. Qed.\n\nLemma ltmx_irrefl m n : irreflexive (@ltmx m m n).\nProof. by move=> A; rewrite /ltmx submx_refl andbF. Qed.\n\nLemma sub0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) <= A)%MS.\nProof. by rewrite submxE mul0mx. Qed.\n\nLemma submx0null m1 m2 n (A : 'M[F]_(m1, n)) :\n  (A <= (0 : 'M_(m2, n)))%MS -> A = 0.\nProof. by case/submxP=> D; rewrite mulmx0. Qed.\n\nLemma submx0 m n (A : 'M_(m, n)) : (A <= (0 : 'M_n))%MS = (A == 0).\nProof. by apply/idP/eqP=> [|->]; [apply: submx0null | apply: sub0mx]. Qed.\n\nLemma lt0mx m n (A : 'M_(m, n)) : ((0 : 'M_n) < A)%MS = (A != 0).\nProof. by rewrite /ltmx sub0mx submx0. Qed.\n\nLemma ltmx0 m n (A : 'M[F]_(m, n)) : (A < (0 : 'M_n))%MS = false.\nProof. by rewrite /ltmx sub0mx andbF. Qed.\n\nLemma eqmx0P m n (A : 'M_(m, n)) : reflect (A = 0) (A == (0 : 'M_n))%MS.\nProof. by rewrite submx0 sub0mx andbT; apply: eqP. Qed.\n\nLemma eqmx_eq0 m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (A == 0) = (B == 0).\nProof. by move=> eqAB; rewrite -!submx0 eqAB. Qed.\n\nLemma addmx_sub m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= C)%MS -> (B <= C)%MS -> ((A + B)%R <= C)%MS.\nProof.\nby case/submxP=> A' ->; case/submxP=> B' ->; rewrite -mulmxDl submxMl.\nQed.\n\nLemma summx_sub m1 m2 n (B : 'M_(m2, n))\n                I (r : seq I) (P : pred I) (A_ : I -> 'M_(m1, n)) :\n  (forall i, P i -> A_ i <= B)%MS -> ((\\sum_(i <- r | P i) A_ i)%R <= B)%MS.\nProof.\nby move=> leAB; elim/big_ind: _ => // [|C D]; [apply/sub0mx | apply/addmx_sub].\nQed.\n\nLemma scalemx_sub m1 m2 n a (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> (a *: A <= B)%MS.\nProof. by case/submxP=> A' ->; rewrite scalemxAl submxMl. Qed.\n\nLemma row_sub m n i (A : 'M_(m, n)) : (row i A <= A)%MS.\nProof. by rewrite rowE submxMl. Qed.\n\nLemma eq_row_sub m n v (A : 'M_(m, n)) i : row i A = v -> (v <= A)%MS.\nProof. by move <-; rewrite row_sub. Qed.\n\nLemma nz_row_sub m n (A : 'M_(m, n)) : (nz_row A <= A)%MS.\nProof. by rewrite /nz_row; case: pickP => [i|] _; rewrite ?row_sub ?sub0mx. Qed.\n\nLemma row_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall i, row i A <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i|sAB].\n  by apply: submx_trans sAB; apply: row_sub.\nrewrite submxE; apply/eqP/row_matrixP=> i; apply/eqP.\nby rewrite row_mul row0 -submxE.\nQed.\nArguments row_subP {m1 m2 n A B}.\n\nLemma rV_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB v Av | sAB]; first exact: submx_trans sAB.\nby apply/row_subP=> i; rewrite sAB ?row_sub.\nQed.\nArguments rV_subP {m1 m2 n A B}.\n\nLemma row_subPn m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists i, ~~ (row i A <= B)%MS) (~~ (A <= B)%MS).\nProof. by rewrite (sameP row_subP forallP) negb_forall; apply: existsP. Qed.\n\nLemma sub_rVP n (u v : 'rV_n) : reflect (exists a, u = a *: v) (u <= v)%MS.\nProof.\napply: (iffP submxP) => [[w ->] | [a ->]].\n  by exists (w 0 0); rewrite -mul_scalar_mx -mx11_scalar.\nby exists a%:M; rewrite mul_scalar_mx.\nQed.\n\nLemma rank_rV n (v : 'rV_n) : \\rank v = (v != 0).\nProof.\ncase: eqP => [-> | nz_v]; first by rewrite mxrank0.\nby apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0; apply/eqP.\nQed.\n\nLemma rowV0Pn m n (A : 'M_(m, n)) :\n  reflect (exists2 v : 'rV_n, v <= A & v != 0)%MS (A != 0).\nProof.\nrewrite -submx0; apply: (iffP idP) => [| [v svA]]; last first.\n  by rewrite -submx0; apply: contra (submx_trans _).\nby case/row_subPn=> i; rewrite submx0; exists (row i A); rewrite ?row_sub.\nQed.\n\nLemma rowV0P m n (A : 'M_(m, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v = 0)%MS (A == 0).\nProof.\nrewrite -[A == 0]negbK; case: rowV0Pn => IH.\n  by right; case: IH => v svA nzv IH; case/eqP: nzv; apply: IH.\nby left=> v svA; apply/eqP; apply/idPn=> nzv; case: IH; exists v.\nQed.\n\nLemma submx_full m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A <= B)%MS.\nProof.\nby rewrite submxE /cokermx => /eqnP->; rewrite /copid_mx pid_mx_1 subrr !mulmx0.\nQed.\n\nLemma row_fullP m n (A : 'M_(m, n)) :\n  reflect (exists B, B *m A = 1%:M) (row_full A).\nProof.\napply: (iffP idP) => [Afull | [B kA]].\n  by exists (1%:M *m pinvmx A); apply: mulmxKpV (submx_full _ Afull).\nby rewrite [_ A]eqn_leq rank_leq_col (mulmx1_min_rank B 1%:M) ?mulmx1.\nQed.\nArguments row_fullP {m n A}.\n\nLemma row_full_inj m n p A : row_full A -> injective (@mulmx _ m n p A).\nProof.\ncase/row_fullP=> A' A'K; apply: can_inj (mulmx A') _ => B.\nby rewrite mulmxA A'K mul1mx.\nQed.\n\nLemma row_freeP m n (A : 'M_(m, n)) :\n  reflect (exists B, A *m B = 1%:M) (row_free A).\nProof.\nrewrite /row_free -mxrank_tr.\napply: (iffP row_fullP) => [] [B kA];\n  by exists B^T; rewrite -trmx1 -kA trmx_mul ?trmxK.\nQed.\n\nLemma row_free_inj m n p A : row_free A -> injective ((@mulmx _ m n p)^~ A).\nProof.\ncase/row_freeP=> A' AK; apply: can_inj (mulmx^~ A') _ => B.\nby rewrite -mulmxA AK mulmx1.\nQed.\n\nLemma row_free_unit n (A : 'M_n) : row_free A = (A \\in unitmx).\nProof.\napply/row_fullP/idP=> [[A'] | uA]; first by case/mulmx1_unit.\nby exists (invmx A); rewrite mulVmx.\nQed.\n\nLemma row_full_unit n (A : 'M_n) : row_full A = (A \\in unitmx).\nProof. exact: row_free_unit. Qed.\n  \nLemma mxrank_unit n (A : 'M_n) : A \\in unitmx -> \\rank A = n.\nProof. by rewrite -row_full_unit => /eqnP. Qed.\n\nLemma mxrank1 n : \\rank (1%:M : 'M_n) = n.\nProof. by apply: mxrank_unit; apply: unitmx1. Qed.\n\nLemma mxrank_delta m n i j : \\rank (delta_mx i j : 'M_(m, n)) = 1%N.\nProof.\napply/eqP; rewrite eqn_leq lt0n mxrank_eq0.\nrewrite -{1}(mul_delta_mx (0 : 'I_1)) mulmx_max_rank.\nby apply/eqP; move/matrixP; move/(_ i j); move/eqP; rewrite !mxE !eqxx oner_eq0.\nQed.\n\nLemma mxrankS m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B.\nProof. by case/submxP=> D ->; rewrite mxrankM_maxr. Qed.\n\nLemma submx1 m n (A : 'M_(m, n)) : (A <= 1%:M)%MS.\nProof. by rewrite submx_full // row_full_unit unitmx1. Qed.\n\nLemma sub1mx m n (A : 'M_(m, n)) : (1%:M <= A)%MS = row_full A.\nProof.\napply/idP/idP; last exact: submx_full.\nby move/mxrankS; rewrite mxrank1 col_leq_rank.\nQed.\n\nLemma ltmx1 m n (A : 'M_(m, n)) : (A < 1%:M)%MS = ~~ row_full A.\nProof. by rewrite /ltmx sub1mx submx1. Qed.\n\nLemma lt1mx m n (A : 'M_(m, n)) : (1%:M < A)%MS = false.\nProof. by rewrite /ltmx submx1 andbF. Qed.\n\nLemma eqmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :=: B)%MS (A == B)%MS.\nProof.\napply: (iffP andP) => [[sAB sBA] | eqAB]; last by rewrite !eqAB.\nsplit=> [|m3 C]; first by apply/eqP; rewrite eqn_leq !mxrankS.\nsplit; first by apply/idP/idP; apply: submx_trans.\nby apply/idP/idP=> sC; apply: submx_trans sC _.\nQed.\nArguments eqmxP {m1 m2 n A B}.\n\nLemma rV_eqP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall u : 'rV_n, (u <= A) = (u <= B))%MS (A == B)%MS.\nProof.\napply: (iffP idP) => [eqAB u | eqAB]; first by rewrite (eqmxP eqAB).\nby apply/andP; split; apply/rV_subP=> u; rewrite eqAB.\nQed.\n\nLemma eqmx_refl m1 n (A : 'M_(m1, n)) : (A :=: A)%MS.\nProof. by []. Qed.\n\nLemma eqmx_sym m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (B :=: A)%MS.\nProof. by move=> eqAB; split=> [|m3 C]; rewrite !eqAB. Qed.\n\nLemma eqmx_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :=: B)%MS -> (B :=: C)%MS -> (A :=: C)%MS.\nProof. by move=> eqAB eqBC; split=> [|m4 D]; rewrite !eqAB !eqBC. Qed.\n\nLemma eqmx_rank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A == B)%MS -> \\rank A = \\rank B.\nProof. by move/eqmxP->. Qed.\n\nLemma lt_eqmx m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n    (A :=: B)%MS ->\n  forall C : 'M_(m3, n), (((A < C) = (B < C))%MS * ((C < A) = (C < B))%MS)%type.\nProof. by move=> eqAB C; rewrite /ltmx !eqAB. Qed.\n\nLemma eqmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A :=: B)%MS -> (A *m C :=: B *m C)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !submxMr ?eqAB. Qed.\n\nLemma eqmxMfull m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_full A -> (A *m B :=: B)%MS.\nProof.\ncase/row_fullP=> A' A'A; apply/eqmxP; rewrite submxMl /=.\nby apply/submxP; exists A'; rewrite mulmxA A'A mul1mx.\nQed.\n\nLemma eqmx0 m n : ((0 : 'M[F]_(m, n)) :=: (0 : 'M_n))%MS.\nProof. by apply/eqmxP; rewrite !sub0mx. Qed.\n\nLemma eqmx_scale m n a (A : 'M_(m, n)) : a != 0 -> (a *: A :=: A)%MS.\nProof.\nmove=> nz_a; apply/eqmxP; rewrite scalemx_sub //.\nby rewrite -{1}[A]scale1r -(mulVf nz_a) -scalerA scalemx_sub.\nQed.\n\nLemma eqmx_opp m n (A : 'M_(m, n)) : (- A :=: A)%MS.\nProof.\nby rewrite -scaleN1r; apply: eqmx_scale => //; rewrite oppr_eq0 oner_eq0.\nQed.\n\nLemma submxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C <= B *m C)%MS = (A <= B)%MS.\nProof.\ncase/row_freeP=> C' C_C'_1; apply/idP/idP=> sAB; last exact: submxMr.\nby rewrite -[A]mulmx1 -[B]mulmx1 -C_C'_1 !mulmxA submxMr.\nQed.\n\nLemma eqmxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C :=: B *m C)%MS -> (A :=: B)%MS.\nProof.\nby move=> Cfree eqAB; apply/eqmxP; move/eqmxP: eqAB; rewrite !submxMfree.\nQed.\n\nLemma mxrankMfree m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_free B -> \\rank (A *m B) = \\rank A.\nProof.\nby move=> Bfree; rewrite -mxrank_tr trmx_mul eqmxMfull /row_full mxrank_tr.\nQed.\n\nLemma eq_row_base m n (A : 'M_(m, n)) : (row_base A :=: A)%MS.\nProof.\napply/eqmxP; apply/andP; split; apply/submxP.\n  exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n  by rewrite -{8}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\nexists (col_ebase A *m pid_mx (\\rank A)).\nby rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nQed.\n\nLet qidmx_eq1 n (A : 'M_n) : qidmx A = (A == 1%:M).\nProof. by rewrite /qidmx eqxx pid_mx_1. Qed.\n\nLet genmx_witnessP m n (A : 'M_(m, n)) :\n  equivmx A (row_full A) (genmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /genmx_witness.\ncase fullA: (row_full A); first by rewrite eqxx sub1mx submx1 fullA.\nset B := _ *m _; have defB : (B == A)%MS.\n  apply/andP; split; apply/submxP.\n    exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n    by rewrite -{3}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\n  exists (col_ebase A *m pid_mx (\\rank A)).\n  by rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nrewrite defB -negb_add addbF; case: eqP defB => // ->.\nby rewrite sub1mx fullA.\nQed.\n\nLemma genmxE m n (A : 'M_(m, n)) : (<<A>> :=: A)%MS.\nProof.\nby rewrite unlock; apply/eqmxP; case/andP: (chooseP (genmx_witnessP A)).\nQed.\n\nLemma eq_genmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B -> <<A>> = <<B>>)%MS.\nProof.\nmove=> eqAB; rewrite unlock.\nhave{eqAB} eqAB: equivmx A (row_full A) =1 equivmx B (row_full B).\n  by move=> C; rewrite /row_full /equivmx !eqAB.\nrewrite (eq_choose eqAB) (choose_id _ (genmx_witnessP B)) //.\nby rewrite -eqAB genmx_witnessP.\nQed.\n\nLemma genmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (<<A>> = <<B>>)%MS (A == B)%MS.\nProof.\napply: (iffP idP) => eqAB; first exact: eq_genmx (eqmxP _).\nby rewrite -!(genmxE A) eqAB !genmxE andbb.\nQed.\nArguments genmxP {m1 m2 n A B}.\n\nLemma genmx0 m n : <<0 : 'M_(m, n)>>%MS = 0.\nProof. by apply/eqP; rewrite -submx0 genmxE sub0mx. Qed.\n\nLemma genmx1 n : <<1%:M : 'M_n>>%MS = 1%:M.\nProof.\nrewrite unlock; case/andP: (chooseP (@genmx_witnessP n n 1%:M)) => _ /eqP.\nby rewrite qidmx_eq1 row_full_unit unitmx1 => /eqP.\nQed.\n\nLemma genmx_id m n (A : 'M_(m, n)) : (<<<<A>>>> = <<A>>)%MS.\nProof. by apply: eq_genmx; apply: genmxE. Qed.\n\nLemma row_base_free m n (A : 'M_(m, n)) : row_free (row_base A).\nProof. by apply/eqnP; rewrite eq_row_base. Qed.\n\nLemma mxrank_gen m n (A : 'M_(m, n)) : \\rank <<A>> = \\rank A.\nProof. by rewrite genmxE. Qed.\n\nLemma col_base_full m n (A : 'M_(m, n)) : row_full (col_base A).\nProof.\napply/row_fullP; exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\nby rewrite !mulmxA mulmxKV // pid_mx_id // pid_mx_1.\nQed.\nHint Resolve row_base_free col_base_full : core.\n\nLemma mxrank_leqif_sup m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (B <= A)%MS.\nProof.\nmove=> sAB; split; first by rewrite mxrankS.\napply/idP/idP=> [| sBA]; last by rewrite eqn_leq !mxrankS.\ncase/submxP: sAB => D ->; rewrite -{-2}(mulmx_base B) mulmxA.\nrewrite mxrankMfree // => /row_fullP[E kE].\nby rewrite -{1}[row_base B]mul1mx -kE -(mulmxA E) (mulmxA _ E) submxMl.\nQed.\n\nLemma mxrank_leqif_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (A == B)%MS.\nProof. by move=> sAB; rewrite sAB; apply: mxrank_leqif_sup. Qed.\n\nLemma ltmxErank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS = (A <= B)%MS && (\\rank A < \\rank B).\nProof.\nby apply: andb_id2l => sAB; rewrite (ltn_leqif (mxrank_leqif_sup sAB)).\nQed.\n\nLemma rank_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS -> \\rank A < \\rank B.\nProof. by rewrite ltmxErank => /andP[]. Qed.\n\nLemma eqmx_cast m1 m2 n (A : 'M_(m1, n)) e :\n  ((castmx e A : 'M_(m2, n)) :=: A)%MS.\nProof. by case: e A; case: m2 / => A e; rewrite castmx_id. Qed.\n\nLemma eqmx_conform m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (conform_mx A B :=: A \\/ conform_mx A B :=: B)%MS.\nProof.\ncase: (eqVneq m2 m1) => [-> | neqm12] in B *.\n  by right; rewrite conform_mx_id.\nby left; rewrite nonconform_mx ?neqm12.\nQed.\n\nLet eqmx_sum_nop m n (A : 'M_(m, n)) : (addsmx_nop A :=: A)%MS.\nProof.\ncase: (eqmx_conform <<A>>%MS A) => // eq_id_gen.\nexact: eqmx_trans (genmxE A).\nQed.\n\nSection AddsmxSub.\n\nVariable (m1 m2 n : nat) (A : 'M[F]_(m1, n)) (B : 'M[F]_(m2, n)).\n\nLemma col_mx_sub m3 (C : 'M_(m3, n)) :\n  (col_mx A B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof.\nrewrite !submxE mul_col_mx -col_mx0.\nby apply/eqP/andP; [case/eq_col_mx=> -> -> | case; do 2!move/eqP->].\nQed.\n\nLemma addsmxE : (A + B :=: col_mx A B)%MS.\nProof.\nhave:= submx_refl (col_mx A B); rewrite col_mx_sub; case/andP=> sAS sBS.\nrewrite unlock; do 2?case: eqP => [AB0 | _]; last exact: genmxE.\n  by apply/eqmxP; rewrite !eqmx_sum_nop sBS col_mx_sub AB0 sub0mx /=.\nby apply/eqmxP; rewrite !eqmx_sum_nop sAS col_mx_sub AB0 sub0mx andbT /=.\nQed.\n\nLemma addsmx_sub m3 (C : 'M_(m3, n)) :\n  (A + B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof. by rewrite addsmxE col_mx_sub. Qed.\n\nLemma addsmxSl : (A <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmxSr : (B <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmx_idPr : reflect (A + B :=: B)%MS (A <= B)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS B.\nby rewrite addsmxSr addsmx_sub submx_refl !andbT.\nQed.\n\nLemma addsmx_idPl : reflect (A + B :=: A)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS A.\nby rewrite addsmxSl addsmx_sub submx_refl !andbT.\nQed.\n\nEnd AddsmxSub.\n\nLemma adds0mx m1 m2 n (B : 'M_(m2, n)) : ((0 : 'M_(m1, n)) + B :=: B)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSr /= andbT. Qed.\n\nLemma addsmx0 m1 m2 n (A : 'M_(m1, n)) : (A + (0 : 'M_(m2, n)) :=: A)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSl /= !andbT. Qed.\n\nLet addsmx_nop_eq0 m n (A : 'M_(m, n)) : (addsmx_nop A == 0) = (A == 0).\nProof. by rewrite -!submx0 eqmx_sum_nop. Qed.\n\nLet addsmx_nop0 m n : addsmx_nop (0 : 'M_(m, n)) = 0.\nProof. by apply/eqP; rewrite addsmx_nop_eq0. Qed.\n\nLet addsmx_nop_id n (A : 'M_n) : addsmx_nop A = A.\nProof. exact: conform_mx_id. Qed.\n\nLemma addsmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A + B = B + A)%MS.\nProof.\nhave: (A + B == B + A)%MS.\n  by apply/andP; rewrite !addsmx_sub andbC -addsmx_sub andbC -addsmx_sub.\nmove/genmxP; rewrite [@addsmx]unlock -!submx0 !submx0.\nby do 2!case: eqP => [// -> | _]; rewrite ?genmx_id ?addsmx_nop0.\nQed.\n\nLemma adds0mx_id m1 n (B : 'M_n) : ((0 : 'M_(m1, n)) + B)%MS = B.\nProof. by rewrite unlock eqxx addsmx_nop_id. Qed.\n\nLemma addsmx0_id m2 n (A : 'M_n) : (A + (0 : 'M_(m2, n)))%MS = A.\nProof. by rewrite addsmxC adds0mx_id. Qed.\n\nLemma addsmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A + (B + C) = A + B + C)%MS.\nProof.\nhave: (A + (B + C) :=: A + B + C)%MS.\n  by apply/eqmxP/andP; rewrite !addsmx_sub -andbA andbA -!addsmx_sub.\nrewrite {1 3}[in @addsmx m1]unlock [in @addsmx n]unlock !addsmx_nop_id -!submx0.\nrewrite !addsmx_sub ![@addsmx]unlock -!submx0; move/eq_genmx.\nby do 3!case: (_ <= 0)%MS; rewrite //= !genmx_id.\nQed.\n\nCanonical addsmx_monoid n :=\n  Monoid.Law (@addsmxA n n n n) (@adds0mx_id n n) (@addsmx0_id n n).\nCanonical addsmx_comoid n := Monoid.ComLaw (@addsmxC n n n).\n\nLemma addsmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A + B)%MS *m C :=: A *m C + B *m C)%MS.\nProof. by apply/eqmxP; rewrite !addsmxE -!mul_col_mx !submxMr ?addsmxE. Qed.\n\nLemma addsmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                            (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A + B <= C + D)%MS.\nProof.\nmove=> sAC sBD.\nby rewrite addsmx_sub {1}addsmxC !(submx_trans _ (addsmxSr _ _)).\nQed.\n\nLemma addmx_sub_adds m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m, n))\n                               (C : 'M_(m1, n)) (D : 'M_(m2, n)) :\n  (A <= C -> B <= D -> (A + B)%R <= C + D)%MS.\nProof.\nmove=> sAC; move/(addsmxS sAC); apply: submx_trans.\nby rewrite addmx_sub ?addsmxSl ?addsmxSr.\nQed.\n\nLemma addsmx_addKl n m1 m2 (A : 'M_(m1, n)) (B C : 'M_(m2, n)) :\n  (B <= A)%MS -> (A + (B + C)%R :=: A + C)%MS.\nProof.\nmove=> sBA; apply/eqmxP; rewrite !addsmx_sub !addsmxSl.\nby rewrite -{3}[C](addKr B) !addmx_sub_adds ?eqmx_opp.\nQed.\n\nLemma addsmx_addKr n m1 m2 (A B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (B <= C)%MS -> ((A + B)%R + C :=: A + C)%MS.\nProof. by rewrite -!(addsmxC C) addrC; apply: addsmx_addKl. Qed.\n\nLemma adds_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                              (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A + B :=: C + D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !addsmxS ?eqAC ?eqBD. Qed.\n\nLemma genmx_adds m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<(A + B)%MS>> = <<A>> + <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (adds_eqmx (genmxE A) (genmxE B))).\nby rewrite [@addsmx]unlock !addsmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\nQed.\n\nLemma sub_addsmxP m1 m2 m3 n\n                  (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  reflect (exists u, A = u.1 *m B + u.2 *m C) (A <= B + C)%MS.\nProof.\napply: (iffP idP) => [|[u ->]]; last by rewrite addmx_sub_adds ?submxMl.\nrewrite addsmxE; case/submxP=> u ->; exists (lsubmx u, rsubmx u).\nby rewrite -mul_row_col hsubmxK.\nQed.\nArguments sub_addsmxP {m1 m2 m3 n A B C}.\n\nVariable I : finType.\nImplicit Type P : pred I.\n\nLemma genmx_sums P n (B_ : I -> 'M_n) :\n  <<(\\sum_(i | P i) B_ i)%MS>>%MS = (\\sum_(i | P i) <<B_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_adds n n n) (@genmx0 n n)). Qed.\n\nLemma sumsmx_sup i0 P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  P i0 -> (A <= B_ i0)%MS -> (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\nby move=> Pi0 sAB; apply: submx_trans sAB _; rewrite (bigD1 i0) // addsmxSl.\nQed.\nArguments sumsmx_sup i0 [P m n A B_].\n\nLemma sumsmx_subP P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  reflect (forall i, P i -> A_ i <= B)%MS (\\sum_(i | P i) A_ i <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: submx_trans sAB; apply: sumsmx_sup Pi _.\nby elim/big_rec: _ => [|i Ai Pi sAiB]; rewrite ?sub0mx // addsmx_sub sAB.\nQed.\n\nLemma summx_sub_sums P m n (A : I -> 'M[F]_(m, n)) B :\n    (forall i, P i -> A i <= B i)%MS ->\n  ((\\sum_(i | P i) A i)%R <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply: summx_sub => i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma sumsmxS P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i <= B i)%MS ->\n  (\\sum_(i | P i) A i <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply/sumsmx_subP=> i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma eqmx_sums P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i :=: B i)%MS ->\n  (\\sum_(i | P i) A i :=: \\sum_(i | P i) B i)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !sumsmxS // => i; move/eqAB->. Qed.\n\nLemma sub_sumsmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (exists u_, A = \\sum_(i | P i) u_ i *m B_ i)\n          (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [| [u_ ->]]; last first.\n  by apply: summx_sub_sums => i _; apply: submxMl.\nelim: {P}_.+1 {-2}P A (ltnSn #|P|) => // b IHb P A.\ncase: (pickP P) => [i Pi | P0 _]; last first.\n  rewrite big_pred0 //; move/submx0null->.\n  by exists (fun _ => 0); rewrite big_pred0.\nrewrite (cardD1x Pi) (bigD1 i) //= => /IHb{b IHb} /= IHi /sub_addsmxP[u ->].\nhave [u_ ->] := IHi _ (submxMl u.2 _).\nexists [eta u_ with i |-> u.1]; rewrite (bigD1 i Pi) /= eqxx; congr (_ + _).\nby apply: eq_bigr => j /andP[_ /negPf->].\nQed.\n\nLemma sumsmxMr_gen P m n A (B : 'M[F]_(m, n)) :\n  ((\\sum_(i | P i) A i)%MS *m B :=: \\sum_(i | P i) <<A i *m B>>)%MS.\nProof.\napply/eqmxP/andP; split; last first.\n  by apply/sumsmx_subP=> i Pi; rewrite genmxE submxMr ?(sumsmx_sup i).\nhave [u ->] := sub_sumsmxP _ _ _ (submx_refl (\\sum_(i | P i) A i)%MS).\nby rewrite mulmx_suml summx_sub_sums // => i _; rewrite genmxE -mulmxA submxMl.\nQed.\n\nLemma sumsmxMr P n (A_ : I -> 'M[F]_n) (B : 'M_n) :\n  ((\\sum_(i | P i) A_ i)%MS *m B :=: \\sum_(i | P i) (A_ i *m B))%MS.\nProof.\nby apply: eqmx_trans (sumsmxMr_gen _ _ _) (eqmx_sums _) => i _; apply: genmxE.\nQed.\n\nLemma rank_pid_mx m n r : r <= m -> r <= n -> \\rank (pid_mx r : 'M_(m, n)) = r.\nProof.\ndo 2!move/subnKC <-; rewrite pid_mx_block block_mxEv row_mx0 -addsmxE addsmx0.\nby rewrite -mxrank_tr tr_row_mx trmx0 trmx1 -addsmxE addsmx0 mxrank1.\nQed.\n\nLemma rank_copid_mx n r : r <= n -> \\rank (copid_mx r : 'M_n) = (n - r)%N.\nProof.\nmove/subnKC <-; rewrite /copid_mx pid_mx_block scalar_mx_block.\nrewrite opp_block_mx !oppr0 add_block_mx !addr0 subrr block_mxEv row_mx0.\nrewrite -addsmxE adds0mx -mxrank_tr tr_row_mx trmx0 trmx1.\nby rewrite -addsmxE adds0mx mxrank1 addKn.\nQed.\n\nLemma mxrank_compl m n (A : 'M_(m, n)) : \\rank A^C = (n - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?rank_copid_mx. Qed.\n\nLemma mxrank_ker m n (A : 'M_(m, n)) : \\rank (kermx A) = (m - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma kermx_eq0 n m (A : 'M_(m, n)) : (kermx A == 0) = row_free A.\nProof. by rewrite -mxrank_eq0 mxrank_ker subn_eq0 row_leq_rank. Qed.\n\nLemma mxrank_coker m n (A : 'M_(m, n)) : \\rank (cokermx A) = (n - \\rank A)%N.\nProof. by rewrite eqmxMfull ?row_full_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma cokermx_eq0 n m (A : 'M_(m, n)) : (cokermx A == 0) = row_full A.\nProof. by rewrite -mxrank_eq0 mxrank_coker subn_eq0 col_leq_rank. Qed.\n\nLemma mulmx_ker m n (A : 'M_(m, n)) : kermx A *m A = 0.\nProof.\nby rewrite -{2}[A]mulmx_ebase !mulmxA mulmxKV // mul_copid_mx_pid ?mul0mx.\nQed.\n\nLemma mulmxKV_ker m n p (A : 'M_(n, p)) (B : 'M_(m, n)) :\n  B *m A = 0 -> B *m col_ebase A *m kermx A = B.\nProof.\nrewrite mulmxA mulmxBr mulmx1 mulmxBl mulmxK //.\nrewrite -{1}[A]mulmx_ebase !mulmxA => /(canRL (mulmxK (row_ebase_unit A))).\nrewrite mul0mx // => BA0; apply: (canLR (addrK _)).\nby rewrite -(pid_mx_id _ _ n (rank_leq_col A)) mulmxA BA0 !mul0mx addr0.\nQed.\n\nLemma sub_kermxP p m n (A : 'M_(m, n)) (B : 'M_(p, m)) :\n  reflect (B *m A = 0) (B <= kermx A)%MS.\nProof.\napply: (iffP submxP) => [[D ->]|]; first by rewrite -mulmxA mulmx_ker mulmx0.\nby move/mulmxKV_ker; exists (B *m col_ebase A).\nQed.\n\nLemma mulmx0_rank_max m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  A *m B = 0 -> \\rank A + \\rank B <= n.\nProof.\nmove=> AB0; rewrite -{3}(subnK (rank_leq_row B)) leq_add2r.\nby rewrite -mxrank_ker mxrankS //; apply/sub_kermxP.\nQed.\n\nLemma mxrank_Frobenius m n p q (A : 'M_(m, n)) B (C : 'M_(p, q)) :\n  \\rank (A *m B) + \\rank (B *m C) <= \\rank B + \\rank (A *m B *m C).\nProof.\nrewrite -{2}(mulmx_base (A *m B)) -mulmxA (eqmxMfull _ (col_base_full _)).\nset C2 := row_base _ *m C.\nrewrite -{1}(subnK (rank_leq_row C2)) -(mxrank_ker C2) addnAC leq_add2r.\nrewrite addnC -{1}(mulmx_base B) -mulmxA eqmxMfull //.\nset C1 := _ *m C; rewrite -{2}(subnKC (rank_leq_row C1)) leq_add2l -mxrank_ker.\nrewrite -(mxrankMfree _ (row_base_free (A *m B))).\nhave: (row_base (A *m B) <= row_base B)%MS by rewrite !eq_row_base submxMl.\ncase/submxP=> D defD; rewrite defD mulmxA mxrankMfree ?mxrankS //.\nby apply/sub_kermxP; rewrite -mulmxA (mulmxA D) -defD -/C2 mulmx_ker.\nQed.\n\nLemma mxrank_mul_min m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank A + \\rank B - n <= \\rank (A *m B).\nProof.\nby have:= mxrank_Frobenius A 1%:M B; rewrite mulmx1 mul1mx mxrank1 leq_subLR.\nQed.\n\nLemma addsmx_compl_full m n (A : 'M_(m, n)) : row_full (A + A^C)%MS.\nProof.\nrewrite /row_full addsmxE; apply/row_fullP.\nexists (row_mx (pinvmx A) (cokermx A)); rewrite mul_row_col.\nrewrite -{2}[A]mulmx_ebase -!mulmxA mulKmx // -mulmxDr !mulmxA.\nby rewrite pid_mx_id ?copid_mx_id // -mulmxDl addrC subrK mul1mx mulVmx.\nQed.\n\nLemma sub_capmx_gen m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= capmx_gen B C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof.\napply/idP/andP=> [sAI | [/submxP[B' ->{A}] /submxP[C' eqBC']]].\n  rewrite !(submx_trans sAI) ?submxMl // /capmx_gen.\n   have:= mulmx_ker (col_mx B C); set K := kermx _.\n   rewrite -{1}[K]hsubmxK mul_row_col; move/(canRL (addrK _))->.\n   by rewrite add0r -mulNmx submxMl.\nhave: (row_mx B' (- C') <= kermx (col_mx B C))%MS.\n  by apply/sub_kermxP; rewrite mul_row_col eqBC' mulNmx subrr.\ncase/submxP=> D; rewrite -[kermx _]hsubmxK mul_mx_row.\nby case/eq_row_mx=> -> _; rewrite -mulmxA submxMl.\nQed.\n\nLet capmx_witnessP m n (A : 'M_(m, n)) : equivmx A (qidmx A) (capmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /qidmx /capmx_witness.\nrewrite -sub1mx; case s1A: (1%:M <= A)%MS => /=; last first.\n  rewrite !genmxE submx_refl /= -negb_add; apply: contra {s1A}(negbT s1A).\n  case: eqP => [<- _| _]; first by rewrite genmxE.\n  by case: eqP A => //= -> A; move/eqP->; rewrite pid_mx_1.\ncase: (m =P n) => [-> | ne_mn] in A s1A *.\n  by rewrite conform_mx_id submx_refl pid_mx_1 eqxx.\nby rewrite nonconform_mx ?submx1 ?s1A ?eqxx //; case: eqP.\nQed.\n\nLet capmx_normP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_norm A).\nProof. by case/andP: (chooseP (capmx_witnessP A)) => /eqmxP defN /eqP. Qed.\n\nLet capmx_norm_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A == B)%MS -> capmx_norm A = capmx_norm B.\nProof.\nmove=> eqABid /eqmxP eqAB.\nhave{eqABid eqAB} eqAB: equivmx A (qidmx A) =1 equivmx B (qidmx B).\n  by move=> C; rewrite /equivmx eqABid !eqAB.\nrewrite {1}/capmx_norm (eq_choose eqAB).\nby apply: choose_id; first rewrite -eqAB; apply: capmx_witnessP.\nQed.\n\nLet capmx_nopP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_nop A).\nProof.\nrewrite /capmx_nop; case: (eqVneq m n) => [-> | ne_mn] in A *.\n  by rewrite conform_mx_id.\nby rewrite nonconform_mx ?ne_mn //; apply: capmx_normP.\nQed.\n\nLet sub_qidmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx B -> (A <= B)%MS.\nProof.\nrewrite /qidmx => idB; apply: {A}submx_trans (submx1 A) _.\nby case: eqP B idB => [-> _ /eqP-> | _ B]; rewrite (=^~ sub1mx, pid_mx_1).\nQed.\n\nLet qidmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx (A :&: B)%MS = qidmx A && qidmx B.\nProof.\nrewrite unlock -sub1mx.\ncase idA: (qidmx A); case idB: (qidmx B); try by rewrite capmx_nopP.\ncase s1B: (_ <= B)%MS; first by rewrite capmx_normP.\napply/idP=> /(sub_qidmx 1%:M).\nby rewrite capmx_normP sub_capmx_gen s1B andbF.\nQed.\n\nLet capmx_eq_norm m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A :&: B)%MS = capmx_norm (A :&: B)%MS.\nProof.\nmove=> eqABid; rewrite unlock -sub1mx {}eqABid.\nhave norm_id m (C : 'M_(m, n)) (N := capmx_norm C) : capmx_norm N = N.\n  by apply: capmx_norm_eq; rewrite ?capmx_normP ?andbb.\ncase idB: (qidmx B); last by case: ifP; rewrite norm_id.\nrewrite /capmx_nop; case: (eqVneq m2 n) => [-> | neqm2n] in B idB *.\n  have idN := idB; rewrite -{1}capmx_normP !qidmx_eq1 in idN idB.\n  by rewrite conform_mx_id (eqP idN) (eqP idB).\nby rewrite nonconform_mx ?neqm2n ?norm_id.\nQed.\n\nLemma capmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B :=: capmx_gen A B)%MS.\nProof.\nrewrite unlock -sub1mx; apply/eqmxP.\nhave:= submx_refl (capmx_gen A B); rewrite !sub_capmx_gen => /andP[sIA sIB].\ncase idA: (qidmx A); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase idB: (qidmx B); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase s1B: (1%:M <= B)%MS; rewrite !capmx_normP ?sub_capmx_gen sIA ?sIB //=.\nby rewrite submx_refl (submx_trans (submx1 _)).\nQed.\n\nLemma capmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= A)%MS.\nProof. by rewrite capmxE submxMl. Qed.\n\nLemma sub_capmx m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= B :&: C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof. by rewrite capmxE sub_capmx_gen. Qed.\n\nLemma capmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B = B :&: A)%MS.\nProof.\nhave [eqAB|] := eqVneq (qidmx A) (qidmx B).\n  rewrite (capmx_eq_norm eqAB) (capmx_eq_norm (esym eqAB)).\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbC.\n  by apply/andP; split; rewrite !sub_capmx andbC -sub_capmx.\nby rewrite negb_eqb !unlock => /addbP <-; case: (qidmx A).\nQed.\n\nLemma capmxSr m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= B)%MS.\nProof. by rewrite capmxC capmxSl. Qed.\n\nLemma capmx_idPr n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: B)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A :&: B)%MS B.\nby rewrite capmxSr sub_capmx submx_refl !andbT.\nQed.\n\nLemma capmx_idPl n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: A)%MS (A <= B)%MS.\nProof. by rewrite capmxC; apply: capmx_idPr. Qed.\n\nLemma capmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                           (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A :&: B <= C :&: D)%MS.\nProof.\nby move=> sAC sBD; rewrite sub_capmx {1}capmxC !(submx_trans (capmxSr _ _)).\nQed.\n\nLemma cap_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                             (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A :&: B :=: C :&: D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !capmxS ?eqAC ?eqBD. Qed.\n\nLemma capmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A :&: B) *m C <= A *m C :&: B *m C)%MS.\nProof. by rewrite sub_capmx !submxMr ?capmxSl ?capmxSr. Qed.\n\nLemma cap0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) :&: A)%MS = 0.\nProof. exact: submx0null (capmxSl _ _). Qed.\n\nLemma capmx0 m1 m2 n (A : 'M_(m1, n)) : (A :&: (0 : 'M_(m2, n)))%MS = 0.\nProof. exact: submx0null (capmxSr _ _). Qed.\n\nLemma capmxT m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A :&: B :=: A)%MS.\nProof.\nrewrite -sub1mx => s1B; apply/eqmxP.\nby rewrite capmxSl sub_capmx submx_refl (submx_trans (submx1 A)).\nQed.\n\nLemma capTmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full A -> (A :&: B :=: B)%MS.\nProof. by move=> Afull; apply/eqmxP; rewrite capmxC !capmxT ?andbb. Qed.\n\nLet capmx_nop_id n (A : 'M_n) : capmx_nop A = A.\nProof. by rewrite /capmx_nop conform_mx_id. Qed.\n\nLemma cap1mx n (A : 'M_n) : (1%:M :&: A = A)%MS.\nProof. by rewrite unlock qidmx_eq1 eqxx capmx_nop_id. Qed.\n\nLemma capmx1 n (A : 'M_n) : (A :&: 1%:M = A)%MS.\nProof. by rewrite capmxC cap1mx. Qed.\n\nLemma genmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  <<A :&: B>>%MS = (<<A>> :&: <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (cap_eqmx (genmxE A) (genmxE B))).\ncase idAB: (qidmx <<A>> || qidmx <<B>>)%MS.\n  rewrite [@capmx]unlock !capmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\n  by case: (qidmx _) idAB => //= ->.\ncase idA: (qidmx _) idAB => //= idB; rewrite {2}capmx_eq_norm ?idA //.\nset C := (_ :&: _)%MS; have eq_idC: row_full C = qidmx C.\n  rewrite qidmx_cap idA -sub1mx sub_capmx genmxE; apply/andP=> [[s1A]].\n  by case/idP: idA; rewrite qidmx_eq1 -genmx1 (sameP eqP genmxP) submx1.\nrewrite unlock /capmx_norm eq_idC.\nby apply: choose_id (capmx_witnessP _); rewrite -eq_idC genmx_witnessP.\nQed.\n\nLemma capmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :&: (B :&: C) = A :&: B :&: C)%MS.\nProof.\nrewrite (capmxC A B) capmxC; wlog idA: m1 m3 A C / qidmx A.\n  move=> IH; case idA: (qidmx A); first exact: IH.\n  case idC: (qidmx C); first by rewrite -IH.\n  rewrite (@capmx_eq_norm n m3) ?qidmx_cap ?idA ?idC ?andbF //.\n  rewrite capmx_eq_norm ?qidmx_cap ?idA ?idC ?andbF //.\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbAC.\n  by apply/andP; split; rewrite !sub_capmx andbAC -!sub_capmx.\nrewrite -!(capmxC A) [in @capmx m1]unlock idA capmx_nop_id.\nhave [eqBC |] :=eqVneq (qidmx B) (qidmx C).\n  rewrite (@capmx_eq_norm n) ?capmx_nopP // capmx_eq_norm //.\n  by apply: capmx_norm_eq; rewrite ?qidmx_cap ?capmxS ?capmx_nopP.\nby rewrite !unlock capmx_nopP capmx_nop_id; do 2?case: (qidmx _) => //.\nQed.\n\nCanonical capmx_monoid n :=\n   Monoid.Law (@capmxA n n n n) (@cap1mx n) (@capmx1 n).\nCanonical capmx_comoid n := Monoid.ComLaw (@capmxC n n n).\n\nLemma bigcapmx_inf i0 P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  P i0 -> (A_ i0 <= B -> \\bigcap_(i | P i) A_ i <= B)%MS.\nProof. by move=> Pi0; apply: submx_trans; rewrite (bigD1 i0) // capmxSl. Qed.\n\nLemma sub_bigcapmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (forall i, P i -> A <= B_ i)%MS (A <= \\bigcap_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: (submx_trans sAB); rewrite (bigcapmx_inf Pi).\nby elim/big_rec: _ => [|i Pi C sAC]; rewrite ?submx1 // sub_capmx sAB.\nQed.\n\nLemma genmx_bigcap P n (A_ : I -> 'M_n) :\n  (<<\\bigcap_(i | P i) A_ i>> = \\bigcap_(i | P i) <<A_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_cap n n n) (@genmx1 n)). Qed.\n\nLemma matrix_modl m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= C -> A + (B :&: C) :=: (A + B) :&: C)%MS.\nProof.\nmove=> sAC; set D := ((A + B) :&: C)%MS; apply/eqmxP.\nrewrite sub_capmx addsmxS ?capmxSl // addsmx_sub sAC capmxSr /=.\nhave: (D <= B + A)%MS by rewrite addsmxC capmxSl.\ncase/sub_addsmxP=> u defD; rewrite defD addrC addmx_sub_adds ?submxMl //.\nrewrite sub_capmx submxMl -[_ *m B](addrK (u.2 *m A)) -defD.\nby rewrite addmx_sub ?capmxSr // eqmx_opp mulmx_sub.\nQed.\n\nLemma matrix_modr m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (C <= A -> (A :&: B) + C :=: A :&: (B + C))%MS.\nProof. by rewrite !(capmxC A) -!(addsmxC C); apply: matrix_modl. Qed.\n\nLemma capmx_compl m n (A : 'M_(m, n)) : (A :&: A^C)%MS = 0.\nProof.\nset D := (A :&: A^C)%MS; have: (D <= D)%MS by [].\nrewrite sub_capmx andbC => /andP[/submxP[B defB]].\nrewrite submxE => /eqP; rewrite defB -!mulmxA mulKVmx ?copid_mx_id //.\nby rewrite mulmxA => ->; rewrite mul0mx.\nQed.\n\nLemma mxrank_mul_ker m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  (\\rank (A *m B) + \\rank (A :&: kermx B))%N = \\rank A.\nProof.\napply/eqP; set K := kermx B; set C := (A :&: K)%MS.\nrewrite -(eqmxMr B (eq_row_base A)); set K' := _ *m B.\nrewrite -{2}(subnKC (rank_leq_row K')) -mxrank_ker eqn_add2l.\nrewrite -(mxrankMfree _ (row_base_free A)) mxrank_leqif_sup.\n  rewrite sub_capmx -(eq_row_base A) submxMl.\n  by apply/sub_kermxP; rewrite -mulmxA mulmx_ker.\nhave /submxP[C' defC]: (C <= row_base A)%MS by rewrite eq_row_base capmxSl.\nrewrite defC submxMr //; apply/sub_kermxP.\nby rewrite mulmxA -defC; apply/sub_kermxP; rewrite capmxSr.\nQed.\n\nLemma mxrank_injP m n p (A : 'M_(m, n)) (f : 'M_(n, p)) :\n  reflect (\\rank (A *m f) = \\rank A) ((A :&: kermx f)%MS == 0).\nProof.\nrewrite -mxrank_eq0 -(eqn_add2l (\\rank (A *m f))).\nby rewrite mxrank_mul_ker addn0 eq_sym; apply: eqP.\nQed.\n\nLemma mxrank_disjoint_sum m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B)%MS = 0 -> \\rank (A + B)%MS = (\\rank A + \\rank B)%N.\nProof.\nmove=> AB0; pose Ar := row_base A; pose Br := row_base B.\nhave [Afree Bfree]: row_free Ar /\\ row_free Br by rewrite !row_base_free.\nhave: (Ar :&: Br <= A :&: B)%MS by rewrite capmxS ?eq_row_base.\nrewrite {}AB0 submx0 -mxrank_eq0 capmxE mxrankMfree //.\nset Cr := col_mx Ar Br; set Crl := lsubmx _; rewrite mxrank_eq0 => /eqP Crl0.\nrewrite -(adds_eqmx (eq_row_base _) (eq_row_base _)) addsmxE -/Cr.\nsuffices K0: kermx Cr = 0.\n  by apply/eqP; rewrite eqn_leq rank_leq_row -subn_eq0 -mxrank_ker K0 mxrank0.\nmove/eqP: (mulmx_ker Cr); rewrite -[kermx Cr]hsubmxK mul_row_col -/Crl Crl0.\nrewrite mul0mx add0r -mxrank_eq0 mxrankMfree // mxrank_eq0 => /eqP->.\nexact: row_mx0.\nQed.\n\nLemma diffmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B :=: A :&: (capmx_gen A B)^C)%MS.\nProof. by rewrite unlock; apply/eqmxP; rewrite !genmxE !capmxE andbb. Qed.\n\nLemma genmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<A :\\: B>> = A :\\: B)%MS.\nProof. by rewrite [@diffmx]unlock genmx_id. Qed.\n \nLemma diffmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :\\: B <= A)%MS.\nProof. by rewrite diffmxE capmxSl. Qed.\n\nLemma capmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B) :&: B)%MS = 0.\nProof.\napply/eqP; pose C := capmx_gen A B; rewrite -submx0 -(capmx_compl C).\nby rewrite sub_capmx -capmxE sub_capmx andbAC -sub_capmx -diffmxE -sub_capmx.\nQed.\n\nLemma addsmx_diff_cap_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B + A :&: B :=: A)%MS.\nProof.\napply/eqmxP; rewrite addsmx_sub capmxSl diffmxSl /=.\nset C := (A :\\: B)%MS; set D := capmx_gen A B.\nsuffices sACD: (A <= C + D)%MS.\n  by rewrite (submx_trans sACD) ?addsmxS ?capmxE.\nhave:= addsmx_compl_full D; rewrite /row_full addsmxE.\ncase/row_fullP=> U /(congr1 (mulmx A)); rewrite mulmx1.\nrewrite -[U]hsubmxK mul_row_col mulmxDr addrC 2!mulmxA.\nset V := _ *m _ => defA; rewrite -defA; move/(canRL (addrK _)): defA => defV.\nsuffices /submxP[W ->]: (V <= C)%MS by rewrite -mul_row_col addsmxE submxMl.\nrewrite diffmxE sub_capmx {1}defV -mulNmx addmx_sub 1?mulmx_sub //.\nby rewrite -capmxE capmxSl.\nQed.\n\nLemma mxrank_cap_compl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A :&: B) + \\rank (A :\\: B))%N = \\rank A.\nProof.\nrewrite addnC -mxrank_disjoint_sum ?addsmx_diff_cap_eq //.\nby rewrite (capmxC A) capmxA capmx_diff cap0mx.\nQed.\n\nLemma mxrank_sum_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A + B) + \\rank (A :&: B) = \\rank A + \\rank B)%N.\nProof.\nset C := (A :&: B)%MS; set D := (A :\\: B)%MS.\nhave rDB: \\rank (A + B)%MS = \\rank (D + B)%MS.\n  apply/eqP; rewrite mxrank_leqif_sup; first by rewrite addsmxS ?diffmxSl.\n  by rewrite addsmx_sub addsmxSr -(addsmx_diff_cap_eq A B) addsmxS ?capmxSr.\nrewrite {1}rDB mxrank_disjoint_sum ?capmx_diff //.\nby rewrite addnC addnA mxrank_cap_compl.\nQed.\n\nLemma mxrank_adds_leqif m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  \\rank (A + B) <= \\rank A + \\rank B ?= iff (A :&: B <= (0 : 'M_n))%MS.\nProof.\nrewrite -mxrank_sum_cap; split; first exact: leq_addr.\nby rewrite addnC (@eqn_add2r _ 0) eq_sym mxrank_eq0 -submx0.\nQed.\n\n(* Subspace projection matrix *)\n\nLemma proj_mx_sub m n U V (W : 'M_(m, n)) : (W *m proj_mx U V <= U)%MS.\nProof. by rewrite !mulmx_sub // -addsmxE addsmx0. Qed.\n\nLemma proj_mx_compl_sub m n U V (W : 'M_(m, n)) :\n  (W <= U + V -> W - W *m proj_mx U V <= V)%MS.\nProof.\nrewrite addsmxE => sWUV; rewrite mulmxA -{1}(mulmxKpV sWUV) -mulmxBr.\nby rewrite mulmx_sub // opp_col_mx add_col_mx subrr subr0 -addsmxE adds0mx.\nQed.\n\nLemma proj_mx_id m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= U)%MS -> W *m proj_mx U V = W.\nProof.\nmove=> dxUV sWU; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?proj_mx_sub //= -eqmx_opp opprB.\nby rewrite proj_mx_compl_sub // (submx_trans sWU) ?addsmxSl.\nQed.\n\nLemma proj_mx_0 m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= V)%MS -> W *m proj_mx U V = 0.\nProof.\nmove=> dxUV sWV; apply/eqP; rewrite -submx0 -dxUV.\nrewrite sub_capmx proj_mx_sub /= -[_ *m _](subrK W) addmx_sub // -eqmx_opp.\nby rewrite opprB proj_mx_compl_sub // (submx_trans sWV) ?addsmxSr.\nQed.\n\nLemma add_proj_mx m n U V (W : 'M_(m, n)) :\n    (U :&: V = 0)%MS -> (W <= U + V)%MS ->\n  W *m proj_mx U V + W *m proj_mx V U = W.\nProof.\nmove=> dxUV sWUV; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite -addrA sub_capmx {2}addrCA -!(opprB W).\nby rewrite !{1}addmx_sub ?proj_mx_sub ?eqmx_opp ?proj_mx_compl_sub // addsmxC.\nQed.\n\nLemma proj_mx_proj n (U V : 'M_n) :\n  let P := proj_mx U V in (U :&: V = 0)%MS -> P *m P = P.\nProof. by move=> P dxUV; rewrite -{-2}[P]mul1mx proj_mx_id ?proj_mx_sub. Qed.\n\n(* Completing a partially injective matrix to get a unit matrix. *)\n\nLemma complete_unitmx m n (U : 'M_(m, n)) (f : 'M_n) :\n  \\rank (U *m f) = \\rank U -> {g : 'M_n | g \\in unitmx & U *m f = U *m g}.\nProof.\nmove=> injfU; pose V := <<U>>%MS; pose W := V *m f.\npose g := proj_mx V (V^C)%MS *m f + cokermx V *m row_ebase W.\nhave defW: V *m g = W.\n  rewrite mulmxDr mulmxA proj_mx_id ?genmxE ?capmx_compl //.\n  by rewrite mulmxA mulmx_coker mul0mx addr0.\nexists g; last first.\n  have /submxP[u ->]: (U <= V)%MS by rewrite genmxE.\n  by rewrite -!mulmxA defW.\nrewrite -row_full_unit -sub1mx; apply/submxP.\nhave: (invmx (col_ebase W) *m W <= V *m g)%MS by rewrite defW submxMl.\ncase/submxP=> v def_v; exists (invmx (row_ebase W) *m (v *m V + (V^C)%MS)).\nrewrite -mulmxA mulmxDl -mulmxA -def_v -{3}[W]mulmx_ebase -mulmxA.\nrewrite mulKmx ?col_ebase_unit // [_ *m g]mulmxDr mulmxA.\nrewrite (proj_mx_0 (capmx_compl _)) // mul0mx add0r 2!mulmxA.\nrewrite mulmxK ?row_ebase_unit // copid_mx_id ?rank_leq_row //.\nrewrite (eqmxMr _ (genmxE U)) injfU genmxE addrC -mulmxDl subrK.\nby rewrite mul1mx mulVmx ?row_ebase_unit.\nQed.\n\n(* Two matrices with the same shape represent the same subspace *)\n(* iff they differ only by a change of basis.                   *)\n\nLemma eqmxMunitP m n (U V : 'M_(m, n)) :\n  reflect (exists2 P, P \\in unitmx & U = P *m V) (U == V)%MS.\nProof.\napply: (iffP eqmxP) => [eqUV | [P Punit ->]]; last first.\n  by apply/eqmxMfull; rewrite row_full_unit.\nhave [D defU]: exists D, U = D *m V by apply/submxP; rewrite eqUV.\nhave{eqUV} [Pt Pt_unit defUt]: {Pt | Pt \\in unitmx & V^T *m D^T = V^T *m Pt}.\n  by apply/complete_unitmx; rewrite -trmx_mul -defU !mxrank_tr eqUV.\nby exists Pt^T; last apply/trmx_inj; rewrite ?unitmx_tr // defU !trmx_mul trmxK.\nQed.\n\n(* Mapping between two subspaces with the same dimension. *)\n\nLemma eq_rank_unitmx m1 m2 n (U : 'M_(m1, n)) (V : 'M_(m2, n)) :\n  \\rank U = \\rank V -> {f : 'M_n | f \\in unitmx & V :=: U *m f}%MS.\nProof.\nmove=> eqrUV; pose f := invmx (row_ebase <<U>>%MS) *m row_ebase <<V>>%MS.\nhave defUf: (<<U>> *m f :=: <<V>>)%MS.\n  rewrite -[<<U>>%MS]mulmx_ebase mulmxA mulmxK ?row_ebase_unit // -mulmxA.\n  rewrite genmxE eqrUV -genmxE -{3}[<<V>>%MS]mulmx_ebase -mulmxA.\n  move: (pid_mx _ *m _) => W; apply/eqmxP.\n  by rewrite !eqmxMfull ?andbb // row_full_unit col_ebase_unit.\nhave{defUf} defV: (V :=: U *m f)%MS.\n  by apply/eqmxP; rewrite -!(eqmxMr f (genmxE U)) !defUf !genmxE andbb.\nhave injfU: \\rank (U *m f) = \\rank U by rewrite -defV eqrUV.\nby have [g injg defUg] := complete_unitmx injfU; exists g; rewrite -?defUg.\nQed.\n\nSection SumExpr.\n\n(* This is the infrastructure to support the mxdirect predicate. We use a     *)\n(* bespoke canonical structure to decompose a matrix expression into binary   *)\n(* and n-ary products, using some of the \"quote\" technology. This lets us     *)\n(* characterize direct sums as set sums whose rank is equal to the sum of the *)\n(* ranks of the individual terms. The mxsum_expr/proper_mxsum_expr structures *)\n(* below supply both the decomposition and the calculation of the rank sum.   *)\n(* The mxsum_spec dependent predicate family expresses the consistency of     *)\n(* these two decompositions.                                                  *)\n(*   The main technical difficulty we need to overcome is the fact that       *)\n(* the \"catch-all\" case of canonical structures has a priority lower than     *)\n(* constant expansion. However, it is undesireable that local abbreviations   *)\n(* be opaque for the direct-sum predicate, e.g., not be able to handle        *)\n(* let S := (\\sum_(i | P i) LargeExpression i)%MS in mxdirect S -> ...).      *)\n(*   As in \"quote\", we use the interleaving of constant expansion and         *)\n(* canonical projection matching to achieve our goal: we use a \"wrapper\" type *)\n(* (indeed, the wrapped T type defined in ssrfun.v) with a self-inserting     *)\n(* non-primitive constructor to gain finer control over the type and          *)\n(* structure inference process. The innermost, primitive, constructor flags   *)\n(* trivial sums; it is initially hidden by an eta-expansion, which has been   *)\n(* made into a (default) canonical structure -- this lets type inference      *)\n(* automatically insert this outer tag.                                       *)\n(*   In detail, we define three types                                         *)\n(*  mxsum_spec S r <-> There exists a finite list of matrices A1, ..., Ak     *)\n(*                     such that S is the set sum of the Ai, and r is the sum *)\n(*                     of the ranks of the Ai, i.e., S = (A1 + ... + Ak)%MS   *)\n(*                     and r = \\rank A1 + ... + \\rank Ak. Note that           *)\n(*                     mxsum_spec is a recursive dependent predicate family   *)\n(*                     whose elimination rewrites simultaneaously S, r and    *)\n(*                     the height of S.                                       *)\n(*   proper_mxsum_expr n == The interface for proper sum expressions; this is *)\n(*                     a double-entry interface, keyed on both the matrix sum *)\n(*                     value and the rank sum. The matrix value is restricted *)\n(*                     to square matrices, as the \"+\"%MS operator always      *)\n(*                     returns a square matrix. This interface has two        *)\n(*                     canonical insances, for binary and n-ary sums.         *)\n(*   mxsum_expr m n == The interface for general sum expressions, comprising  *)\n(*                     both proper sums and trivial sums consisting of a      *)\n(*                     single matrix. The key values are WRAPPED as this lets *)\n(*                     us give priority to the \"proper sum\" interpretation    *)\n(*                     (see below). To allow for trivial sums, the matrix key *)\n(*                     can have any dimension. The mxsum_expr interface has   *)\n(*                     two canonical instances, for trivial and proper sums,  *)\n(*                     keyed to the Wrap and wrap constructors, respectively. *)\n(* The projections for the two interfaces above are                           *)\n(*   proper_mxsum_val, mxsum_val : these are respectively coercions to 'M_n   *)\n(*                     and wrapped 'M_(m, n); thus, the matrix sum for an     *)\n(*                     S : mxsum_expr m n can be written unwrap S.            *)\n(*   proper_mxsum_rank, mxsum_rank : projections to the nat and wrapped nat,  *)\n(*                     respectively; the rank sum for S : mxsum_expr m n is   *)\n(*                     thus written unwrap (mxsum_rank S).                    *)\n(* The mxdirect A predicate actually gets A in a phantom argument, which is   *)\n(* used to infer an (implicit) S : mxsum_expr such that unwrap S = A; the     *)\n(* actual definition is \\rank (unwrap S) == unwrap (mxsum_rank S).            *)\n(*   Note that the inference of S is inherently ambiguous: ANY matrix can be  *)\n(* viewed as a trivial sum, including one whose description is manifestly a   *)\n(* proper sum. We use the wrapped type and the interaction between delta      *)\n(* reduction and canonical structure inference to resolve this ambiguity in   *)\n(* favor of proper sums, as follows:                                          *)\n(*    - The phantom type sets up a unification problem of the form            *)\n(*         unwrap (mxsum_val ?S) = A                                          *)\n(*      with unknown evar ?S : mxsum_expr m n.                                *)\n(*    - As the constructor wrap is also a default Canonical instance for the  *)\n(*      wrapped type, so A is immediately replaced with unwrap (wrap A) and   *)\n(*      we get the residual unification problem                               *)\n(*         mxsum_val ?S = wrap A                                              *)\n(*    - Now Coq tries to apply the proper sum Canonical instance, which has   *)\n(*      key projection wrap (proper_mxsum_val ?PS) where ?PS is a fresh evar  *)\n(*      (of type proper_mxsum_expr n). This can only succeed if m = n, and if *)\n(*      a solution can be found to the recursive unification problem          *)\n(*         proper_mxsum_val ?PS = A                                           *)\n(*      This causes Coq to look for one of the two canonical constants for    *)\n(*      proper_mxsum_val (addsmx or bigop) at the head of A, delta-expanding  *)\n(*      A as needed, and then inferring recursively mxsum_expr structures for *)\n(*      the last argument(s) of that constant.                                *)\n(*    - If the above step fails then the wrap constant is expanded, revealing *)\n(*      the primitive Wrap constructor; the unification problem now becomes   *)\n(*         mxsum_val ?S = Wrap A                                              *)\n(*      which fits perfectly the trivial sum canonical structure, whose key   *)\n(*      projection is Wrap ?B where ?B is a fresh evar. Thus the inference    *)\n(*      succeeds, and returns the trivial sum.                                *)\n(* Note that the rank projections also register canonical values, so that the *)\n(* same process can be used to infer a sum structure from the rank sum. In    *)\n(* that case, however, there is no ambiguity and the inference can fail,      *)\n(* because the rank sum for a trivial sum is not an arbitrary integer -- it   *)\n(* must be of the form \\rank ?B. It is nevertheless necessary to use the      *)\n(* wrapped nat type for the rank sums, because in the non-trivial case the    *)\n(* head constant of the nat expression is determined by the proper_mxsum_expr *)\n(* canonical structure, so the mxsum_expr structure must use a generic        *)\n(* constant, namely wrap.                                                     *)\n\nInductive mxsum_spec n : forall m, 'M[F]_(m, n) -> nat -> Prop :=\n | TrivialMxsum m A\n    : @mxsum_spec n m A (\\rank A)\n | ProperMxsum m1 m2 T1 T2 r1 r2 of\n      @mxsum_spec n m1 T1 r1 & @mxsum_spec n m2 T2 r2\n    : mxsum_spec (T1 + T2)%MS (r1 + r2)%N.\nArguments mxsum_spec {n%N m%N} T%MS r%N.\n\nStructure mxsum_expr m n := Mxsum {\n  mxsum_val :> wrapped 'M_(m, n);\n  mxsum_rank : wrapped nat;\n  _ : mxsum_spec (unwrap mxsum_val) (unwrap mxsum_rank)\n}.\n\nCanonical trivial_mxsum m n A :=\n  @Mxsum m n (Wrap A) (Wrap (\\rank A)) (TrivialMxsum A).\n\nStructure proper_mxsum_expr n := ProperMxsumExpr {\n  proper_mxsum_val :> 'M_n;\n  proper_mxsum_rank : nat;\n  _ : mxsum_spec proper_mxsum_val proper_mxsum_rank\n}.\n\nDefinition proper_mxsumP n (S : proper_mxsum_expr n) :=\n  let: ProperMxsumExpr _ _ termS := S return mxsum_spec S (proper_mxsum_rank S)\n  in termS.\n\nCanonical sum_mxsum n (S : proper_mxsum_expr n) :=\n  @Mxsum n n (wrap (S : 'M_n)) (wrap (proper_mxsum_rank S)) (proper_mxsumP S).\n\nSection Binary.\nVariable (m1 m2 n : nat) (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n).\nFact binary_mxsum_proof :\n  mxsum_spec (unwrap S1 + unwrap S2)\n             (unwrap (mxsum_rank S1) + unwrap (mxsum_rank S2)).\nProof. by case: S1 S2 => [A1 r1 A1P] [A2 r2 A2P]; right. Qed.\nCanonical binary_mxsum_expr := ProperMxsumExpr binary_mxsum_proof.\nEnd Binary.\n\nSection Nary.\nContext J (r : seq J) (P : pred J) n (S_ : J -> mxsum_expr n n).\nFact nary_mxsum_proof :\n  mxsum_spec (\\sum_(j <- r | P j) unwrap (S_ j))\n             (\\sum_(j <- r | P j) unwrap (mxsum_rank (S_ j))).\nProof.\nelim/big_rec2: _ => [|j]; first by rewrite -(mxrank0 n n); left.\nby case: (S_ j); right.\nQed.\nCanonical nary_mxsum_expr := ProperMxsumExpr nary_mxsum_proof.\nEnd Nary.\n\nDefinition mxdirect_def m n T of phantom 'M_(m, n) (unwrap (mxsum_val T)) :=\n  \\rank (unwrap T) == unwrap (mxsum_rank T).\n\nEnd SumExpr.\n\nNotation mxdirect A := (mxdirect_def (Phantom 'M_(_,_) A%MS)).\n\nLemma mxdirectP n (S : proper_mxsum_expr n) :\n  reflect (\\rank S = proper_mxsum_rank S) (mxdirect S).\nProof. exact: eqnP. Qed.\nArguments mxdirectP {n S}.\n\nLemma mxdirect_trivial m n A : mxdirect (unwrap (@trivial_mxsum m n A)).\nProof. exact: eqxx. Qed.\n\nLemma mxrank_sum_leqif m n (S : mxsum_expr m n) :\n  \\rank (unwrap S) <= unwrap (mxsum_rank S) ?= iff mxdirect (unwrap S).\nProof.\nrewrite /mxdirect_def; case: S => [[A] [r] /= defAr]; split=> //=.\nelim: m A r / defAr => // m1 m2 A1 A2 r1 r2 _ leAr1 _ leAr2.\nby apply: leq_trans (leq_add leAr1 leAr2); rewrite mxrank_adds_leqif.\nQed.\n\nLemma mxdirectE m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) == unwrap (mxsum_rank S)).\nProof. by []. Qed.\n\nLemma mxdirectEgeq m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) >= unwrap (mxsum_rank S)).\nProof. by rewrite (geq_leqif (mxrank_sum_leqif S)). Qed.\n\nSection BinaryDirect.\n\nVariables m1 m2 n : nat.\n\nLemma mxdirect_addsE (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n) :\n   mxdirect (unwrap S1 + unwrap S2)\n    = [&& mxdirect (unwrap S1), mxdirect (unwrap S2)\n        & unwrap S1 :&: unwrap S2 == 0]%MS.\nProof.\nrewrite (@mxdirectE n) /=.\nhave:= leqif_add (mxrank_sum_leqif S1) (mxrank_sum_leqif S2).\nmove/(leqif_trans (mxrank_adds_leqif (unwrap S1) (unwrap S2)))=> ->.\nby rewrite andbC -andbA submx0.\nQed.\n\nLemma mxdirect_addsP (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B = 0)%MS (mxdirect (A + B)).\nProof. by rewrite mxdirect_addsE !mxdirect_trivial; apply: eqP. Qed.\n\nEnd BinaryDirect.\n\nSection NaryDirect.\n\nVariables (P : pred I) (n : nat).\n\nLet TIsum A_ i := (A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0 :> 'M_n)%MS.\n\nLet mxdirect_sums_recP (S_ : I -> mxsum_expr n n) :\n  reflect (forall i, P i -> mxdirect (unwrap (S_ i)) /\\ TIsum (unwrap \\o S_) i)\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\nrewrite /TIsum; apply: (iffP eqnP) => /= [dxS i Pi | dxS].\n  set Si' := (\\sum_(j | _) unwrap (S_ j))%MS.\n  have: mxdirect (unwrap (S_ i) + Si') by apply/eqnP; rewrite /= -!(bigD1 i).\n  by rewrite mxdirect_addsE => /and3P[-> _ /eqP].\nelim: _.+1 {-2 4}P (subxx P) (ltnSn #|P|) => // m IHm Q; move/subsetP=> sQP.\ncase: (pickP Q) => [i Qi | Q0]; last by rewrite !big_pred0 ?mxrank0.\nrewrite (cardD1x Qi) !((bigD1 i) Q) //=.\nmove/IHm=> <- {IHm}/=; last by apply/subsetP=> j /andP[/sQP].\ncase: (dxS i (sQP i Qi)) => /eqnP=> <- TiQ_0; rewrite mxrank_disjoint_sum //.\napply/eqP; rewrite -submx0 -{2}TiQ_0 capmxS //=.\nby apply/sumsmx_subP=> j /= /andP[Qj i'j]; rewrite (sumsmx_sup j) ?[P j]sQP.\nQed.\n\nLemma mxdirect_sumsP (A_ : I -> 'M_n) :\n  reflect (forall i, P i -> A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0)%MS\n          (mxdirect (\\sum_(i | P i) A_ i)).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => dxA i /dxA; first by case.\nby rewrite mxdirect_trivial.\nQed.\n\nLemma mxdirect_sumsE (S_ : I -> mxsum_expr n n) (xunwrap := unwrap) :\n  reflect (and (forall i, P i -> mxdirect (unwrap (S_ i)))\n               (mxdirect (\\sum_(i | P i) (xunwrap (S_ i)))))\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => [dxS | [dxS_ dxS] i Pi].\n  by do [split; last apply/mxdirect_sumsP] => i; case/dxS.\nby split; [apply: dxS_ | apply: mxdirect_sumsP Pi].\nQed.\n\nEnd NaryDirect.\n\nSection SubDaddsmx.\n\nVariables m m1 m2 n : nat.\nVariables (A : 'M[F]_(m, n)) (B1 : 'M[F]_(m1, n)) (B2 : 'M[F]_(m2, n)).\n\nVariant sub_daddsmx_spec : Prop :=\n  SubDaddsmxSpec A1 A2 of (A1 <= B1)%MS & (A2 <= B2)%MS & A = A1 + A2\n                        & forall C1 C2, (C1 <= B1)%MS -> (C2 <= B2)%MS ->\n                          A = C1 + C2 -> C1 = A1 /\\ C2 = A2.\n\nLemma sub_daddsmx : (B1 :&: B2 = 0)%MS -> (A <= B1 + B2)%MS -> sub_daddsmx_spec.\nProof.\nmove=> dxB /sub_addsmxP[u defA].\nexists (u.1 *m B1) (u.2 *m B2); rewrite ?submxMl // => C1 C2 sCB1 sCB2.\nmove/(canLR (addrK _)) => defC1.\nsuffices: (C2 - u.2 *m B2 <= B1 :&: B2)%MS.\n  by rewrite dxB submx0 subr_eq0 -defC1 defA; move/eqP->; rewrite addrK.\nrewrite sub_capmx -opprB -{1}(canLR (addKr _) defA) -addrA defC1.\nby rewrite !(eqmx_opp, addmx_sub) ?submxMl.\nQed.\n\nEnd SubDaddsmx.\n\nSection SubDsumsmx.\n\nVariables (P : pred I) (m n : nat) (A : 'M[F]_(m, n)) (B : I -> 'M[F]_n).\n\nVariant sub_dsumsmx_spec : Prop :=\n  SubDsumsmxSpec A_ of forall i, P i -> (A_ i <= B i)%MS\n                        & A = \\sum_(i | P i) A_ i\n                        & forall C, (forall i, P i -> C i <= B i)%MS ->\n                          A = \\sum_(i | P i) C i -> {in SimplPred P, C =1 A_}.\n\nLemma sub_dsumsmx :\n    mxdirect (\\sum_(i | P i) B i) -> (A <= \\sum_(i | P i) B i)%MS ->\n  sub_dsumsmx_spec.\nProof.\nmove/mxdirect_sumsP=> dxB /sub_sumsmxP[u defA].\npose A_ i := u i *m B i.\nexists A_ => //= [i _ | C sCB defAC i Pi]; first exact: submxMl.\napply/eqP; rewrite -subr_eq0 -submx0 -{dxB}(dxB i Pi) /=.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?submxMl ?sCB //=.\nrewrite -(subrK A (C i)) -addrA -opprB addmx_sub ?eqmx_opp //.\n  rewrite addrC defAC (bigD1 i) // addKr /= summx_sub // => j Pi'j.\n  by rewrite (sumsmx_sup j) ?sCB //; case/andP: Pi'j.\nrewrite addrC defA (bigD1 i) // addKr /= summx_sub // => j Pi'j.\nby rewrite (sumsmx_sup j) ?submxMl.\nQed.\n\nEnd SubDsumsmx.\n\nSection Eigenspace.\n\nVariables (n : nat) (g : 'M_n).\n\nDefinition eigenspace a := kermx (g - a%:M).\nDefinition eigenvalue : pred F := fun a => eigenspace a != 0.\n\nLemma eigenspaceP a m (W : 'M_(m, n)) :\n  reflect (W *m g = a *: W) (W <= eigenspace a)%MS.\nProof.\nrewrite (sameP (sub_kermxP _ _) eqP).\nby rewrite mulmxBr subr_eq0 mul_mx_scalar; apply: eqP.\nQed.\n\nLemma eigenvalueP a :\n  reflect (exists2 v : 'rV_n, v *m g = a *: v & v != 0) (eigenvalue a).\nProof. by apply: (iffP (rowV0Pn _)) => [] [v]; move/eigenspaceP; exists v. Qed.\n\nLemma mxdirect_sum_eigenspace (P : pred I) a_ :\n  {in P &, injective a_} -> mxdirect (\\sum_(i | P i) eigenspace (a_ i)).\nProof.\nelim: {P}_.+1 {-2}P (ltnSn #|P|) => // m IHm P lePm inj_a.\napply/mxdirect_sumsP=> i Pi; apply/eqP/rowV0P => v.\nrewrite sub_capmx => /andP[/eigenspaceP def_vg].\nset Vi' := (\\sum_(i | _) _)%MS => Vi'v.\nhave dxVi': mxdirect Vi'.\n  rewrite (cardD1x Pi) in lePm; apply: IHm => //.\n  by apply: sub_in2 inj_a => j /andP[].\ncase/sub_dsumsmx: Vi'v => // u Vi'u def_v _.\nrewrite def_v big1 // => j Pi'j; apply/eqP.\nhave nz_aij: a_ i - a_ j != 0.\n  by case/andP: Pi'j => Pj ne_ji; rewrite subr_eq0 eq_sym (inj_in_eq inj_a).\ncase: (sub_dsumsmx dxVi' (sub0mx 1 _)) => C _ _ uniqC.\nrewrite -(eqmx_eq0 (eqmx_scale _ nz_aij)).\nrewrite (uniqC (fun k => (a_ i - a_ k) *: u k)) => // [|k Pi'k|].\n- by rewrite -(uniqC (fun _ => 0)) ?big1 // => k Pi'k; apply: sub0mx.\n- by rewrite scalemx_sub ?Vi'u.\nrewrite -{1}(subrr (v *m g)) {1}def_vg def_v scaler_sumr mulmx_suml -sumrB.\nby apply: eq_bigr => k /Vi'u/eigenspaceP->; rewrite scalerBl.\nQed.\n\nEnd Eigenspace.\n\nEnd RowSpaceTheory.\n\nHint Resolve submx_refl : core.\nArguments submxP {F m1 m2 n A B}.\nArguments eq_row_sub [F m n v A].\nArguments row_subP {F m1 m2 n A B}.\nArguments rV_subP {F m1 m2 n A B}.\nArguments row_subPn {F m1 m2 n A B}.\nArguments sub_rVP {F n u v}.\nArguments rV_eqP {F m1 m2 n A B}.\nArguments rowV0Pn {F m n A}.\nArguments rowV0P {F m n A}.\nArguments eqmx0P {F m n A}.\nArguments row_fullP {F m n A}.\nArguments row_freeP {F m n A}.\nArguments eqmxP {F m1 m2 n A B}.\nArguments genmxP {F m1 m2 n A B}.\nArguments addsmx_idPr {F m1 m2 n A B}.\nArguments addsmx_idPl {F m1 m2 n A B}.\nArguments sub_addsmxP {F m1 m2 m3 n A B C}.\nArguments sumsmx_sup [F I] i0 [P m n A B_].\nArguments sumsmx_subP {F I P m n A_ B}.\nArguments sub_sumsmxP {F I P m n A B_}.\nArguments sub_kermxP {F p m n A B}.\nArguments capmx_idPr {F n m1 m2 A B}.\nArguments capmx_idPl {F n m1 m2 A B}.\nArguments bigcapmx_inf [F I] i0 [P m n A_ B].\nArguments sub_bigcapmxP {F I P m n A B_}.\nArguments mxrank_injP {F m n} p [A f].\nArguments mxdirectP {F n S}.\nArguments mxdirect_addsP {F m1 m2 n A B}.\nArguments mxdirect_sumsP {F I P n A_}.\nArguments mxdirect_sumsE {F I P n S_}.\nArguments eigenspaceP {F n g a m W}.\nArguments eigenvalueP {F n g a}.\n\nArguments mxrank {F m%N n%N} A%MS.\nArguments complmx {F m%N n%N} A%MS.\nArguments row_full {F m%N n%N} A%MS.\nArguments submx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments ltmx {F m1%N m2%N n%N} A%MS B%MS.\nArguments eqmx {F m1%N m2%N n%N} A%MS B%MS.\nArguments addsmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments capmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments diffmx {F m1%N m2%N n%N} A%MS B%MS : rename.\nArguments genmx {F m%N n%N} A%R : rename.\nNotation \"\\rank A\" := (mxrank A) : nat_scope.\nNotation \"<< A >>\" := (genmx A) : matrix_set_scope.\nNotation \"A ^C\" := (complmx A) : matrix_set_scope.\nNotation \"A <= B\" := (submx A B) : matrix_set_scope.\nNotation \"A < B\" := (ltmx A B) : matrix_set_scope.\nNotation \"A <= B <= C\" := ((submx A B) && (submx B C)) : matrix_set_scope.\nNotation \"A < B <= C\" := (ltmx A B && submx B C) : matrix_set_scope.\nNotation \"A <= B < C\" := (submx A B && ltmx B C) : matrix_set_scope.\nNotation \"A < B < C\" := (ltmx A B && ltmx B C) : matrix_set_scope.\nNotation \"A == B\" := ((submx A B) && (submx B A)) : matrix_set_scope.\nNotation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\nNotation \"A + B\" := (addsmx A B) : matrix_set_scope.\nNotation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nNotation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\nNotation mxdirect S := (mxdirect_def (Phantom 'M_(_,_) S%MS)).\n\nNotation \"\\sum_ ( i <- r | P ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i | P ) B\" :=\n  (\\big[addsmx/0%R]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ i B\" :=\n  (\\big[addsmx/0%R]_i B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i : t | P ) B\" :=\n  (\\big[addsmx/0%R]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i : t ) B\" :=\n  (\\big[addsmx/0%R]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i < n ) B\" :=\n  (\\big[addsmx/0%R]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A | P ) B\" :=\n  (\\big[addsmx/0%R]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A ) B\" :=\n  (\\big[addsmx/0%R]_(i in A) B%MS) : matrix_set_scope.\n\nNotation \"\\bigcap_ ( i <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i | P ) B\" :=\n  (\\big[capmx/1%:M]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ i B\" :=\n  (\\big[capmx/1%:M]_i B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t | P ) B\" :=\n  (\\big[capmx/1%:M]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t ) B\" :=\n  (\\big[capmx/1%:M]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n ) B\" :=\n  (\\big[capmx/1%:M]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A | P ) B\" :=\n  (\\big[capmx/1%:M]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A ) B\" :=\n  (\\big[capmx/1%:M]_(i in A) B%MS) : matrix_set_scope.\n\nSection DirectSums.\nVariables (F : fieldType) (I : finType) (P : pred I).\n\nLemma mxdirect_delta n f : {in P &, injective f} ->\n  mxdirect (\\sum_(i | P i) <<delta_mx 0 (f i) : 'rV[F]_n>>).\nProof.\npose fP := image f P => Uf; have UfP: uniq fP by apply/dinjectiveP.\nsuffices /mxdirectP : mxdirect (\\sum_i <<delta_mx 0 i : 'rV[F]_n>>).\n  rewrite /= !(bigID [mem fP] predT) -!big_uniq //= !big_map !big_filter.\n  by move/mxdirectP; rewrite mxdirect_addsE => /andP[].\napply/mxdirectP=> /=; transitivity (mxrank (1%:M : 'M[F]_n)).\n  apply/eqmx_rank; rewrite submx1 mx1_sum_delta summx_sub_sums // => i _.\n  by rewrite -(mul_delta_mx (0 : 'I_1)) genmxE submxMl.\nrewrite mxrank1 -[LHS]card_ord -sum1_card.\nby apply/eq_bigr=> i _; rewrite /= mxrank_gen mxrank_delta.\nQed.\n\nEnd DirectSums.\n\nSection CardGL.\n\nVariable F : finFieldType.\n\nLemma card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite big_nat_rev big_add1 -triangular_sum expn_sum -big_split /=.\npose fr m := [pred A : 'M[F]_(m, n) | \\rank A == m].\nset m := {-7}n; transitivity #|fr m|.\n  by rewrite cardsT /= card_sub; apply: eq_card => A; rewrite -row_free_unit.\nelim: m (leqnn m : m <= n) => [_|m IHm]; last move/ltnW=> le_mn.\n  rewrite (@eq_card1 _ (0 : 'M_(0, n))) ?big_geq //= => A.\n  by rewrite flatmx0 !inE !eqxx.\nrewrite big_nat_recr // -{}IHm //= !subSS mulnBr muln1 -expnD subnKC //.\nrewrite -sum_nat_const /= -sum1_card -add1n.\nrewrite (partition_big dsubmx (fr m)) /= => [|A]; last first.\n  rewrite !inE -{1}(vsubmxK A); move: {A}(_ A) (_ A) => Ad Au Afull.\n  rewrite eqn_leq rank_leq_row -(leq_add2l (\\rank Au)) -mxrank_sum_cap.\n  rewrite {1 3}[@mxrank]lock addsmxE (eqnP Afull) -lock -addnA.\n  by rewrite leq_add ?rank_leq_row ?leq_addr.\napply: eq_bigr => A rAm; rewrite (reindex (col_mx^~ A)) /=; last first.\n  exists usubmx => [v _ | vA]; first by rewrite col_mxKu.\n  by case/andP=> _ /eqP <-; rewrite vsubmxK.\ntransitivity #|~: [set v *m A | v in 'rV_m]|; last first.\n  rewrite cardsCs setCK card_imset ?card_matrix ?card_ord ?mul1n //.\n  have [B AB1] := row_freeP rAm; apply: can_inj (mulmx^~ B) _ => v.\n  by rewrite -mulmxA AB1 mulmx1.\nrewrite -sum1_card; apply: eq_bigl => v; rewrite !inE col_mxKd eqxx.\nrewrite andbT eqn_leq rank_leq_row /= -(leq_add2r (\\rank (v :&: A)%MS)).\nrewrite -addsmxE mxrank_sum_cap (eqnP rAm) addnAC leq_add2r.\nrewrite (ltn_leqif (mxrank_leqif_sup _)) ?capmxSl // sub_capmx submx_refl.\nby congr (~~ _); apply/submxP/imsetP=> [] [u]; exists u.\nQed.\n\n(* An alternate, somewhat more elementary proof, that does not rely on the *)\n(* row-space theory, but directly performs the LUP decomposition.          *)\nLemma LUP_card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite cardsT /= card_sub /GRing.unit /= big_add1 /= -triangular_sum -/n.\nelim: {n'}n => [|n IHn].\n  rewrite !big_geq // mul1n (@eq_card _ _ predT) ?card_matrix //= => M.\n  by rewrite {1}[M]flatmx0 -(flatmx0 1%:M) unitmx1.\nrewrite !big_nat_recr //= expnD mulnAC mulnA -{}IHn -mulnA mulnC.\nset LHS := #|_|; rewrite -[n.+1]muln1 -{2}[n]mul1n {}/LHS.\nrewrite -!card_matrix subn1 -(cardC1 0) -mulnA; set nzC := predC1 _.\nrewrite -sum1_card (partition_big lsubmx nzC) => [|A]; last first.\n  rewrite unitmxE unitfE; apply: contra; move/eqP=> v0.\n  rewrite -[A]hsubmxK v0 -[n.+1]/(1 + n)%N -col_mx0.\n  rewrite -[rsubmx _]vsubmxK -det_tr tr_row_mx !tr_col_mx !trmx0.\n  by rewrite det_lblock [0]mx11_scalar det_scalar1 mxE mul0r.\nrewrite -sum_nat_const; apply: eq_bigr; rewrite /= -[n.+1]/(1 + n)%N => v nzv.\ncase: (pickP (fun i => v i 0 != 0)) => [k nza | v0]; last first.\n  by case/eqP: nzv; apply/colP=> i; move/eqP: (v0 i); rewrite mxE.\nhave xrkK: involutive (@xrow F _ _ 0 k).\n  by move=> m A /=; rewrite /xrow -row_permM tperm2 row_perm1.\nrewrite (reindex_inj (inv_inj (xrkK (1 + n)%N))) /= -[n.+1]/(1 + n)%N.\nrewrite (partition_big ursubmx xpredT) //= -sum_nat_const.\napply: eq_bigr => u _; set a : F := v _ _ in nza.\nset v1 : 'cV_(1 + n) := xrow 0 k v.\nhave def_a: usubmx v1 = a%:M.\n  by rewrite [_ v1]mx11_scalar mxE lshift0 mxE tpermL.\npose Schur := dsubmx v1 *m (a^-1 *: u).\npose L : 'M_(1 + n) := block_mx a%:M 0 (dsubmx v1) 1%:M.\npose U B : 'M_(1 + n) := block_mx 1 (a^-1 *: u) 0 B.\nrewrite (reindex (fun B => L *m U B)); last first.\n  exists (fun A1 => drsubmx A1 - Schur) => [B _ | A1].\n    by rewrite mulmx_block block_mxKdr mul1mx addrC addKr.\n  rewrite !inE mulmx_block !mulmx0 mul0mx !mulmx1 !addr0 mul1mx addrC subrK.\n  rewrite mul_scalar_mx scalerA divff // scale1r andbC; case/and3P => /eqP <- _.\n  rewrite -{1}(hsubmxK A1) xrowE mul_mx_row row_mxKl -xrowE => /eqP def_v.\n  rewrite -def_a block_mxEh vsubmxK /v1 -def_v xrkK.\n  apply: trmx_inj; rewrite tr_row_mx tr_col_mx trmx_ursub trmx_drsub trmx_lsub.\n  by rewrite hsubmxK vsubmxK.\nrewrite -sum1_card; apply: eq_bigl => B; rewrite xrowE unitmxE.\nrewrite !det_mulmx unitrM -unitmxE unitmx_perm det_lblock det_ublock.\nrewrite !det_scalar1 det1 mulr1 mul1r unitrM unitfE nza -unitmxE.\nrewrite mulmx_block !mulmx0 mul0mx !addr0 !mulmx1 mul1mx block_mxKur.\nrewrite mul_scalar_mx scalerA divff // scale1r eqxx andbT.\nby rewrite block_mxEh mul_mx_row row_mxKl -def_a vsubmxK -xrowE xrkK eqxx andbT.\nQed.\n\nLemma card_GL_1 : #|'GL_1[F]| = #|F|.-1.\nProof. by rewrite card_GL // mul1n big_nat1 expn1 subn1. Qed.\n\nLemma card_GL_2 : #|'GL_2[F]| = (#|F| * #|F|.-1 ^ 2 * #|F|.+1)%N.\nProof.\nrewrite card_GL // big_ltn // big_nat1 expn1 -(addn1 #|F|) -subn1 -!mulnA.\nby rewrite -subn_sqr.\nQed.\n\nEnd CardGL.\n\nLemma logn_card_GL_p n p : prime p -> logn p #|'GL_n(p)| = 'C(n, 2).\nProof.\nmove=> p_pr; have p_gt1 := prime_gt1 p_pr.\nhave p_i_gt0: p ^ _ > 0 by move=> i; rewrite expn_gt0 ltnW.\nrewrite (card_GL _ (ltn0Sn n.-1)) card_ord Fp_cast // big_add1 /=.\npose p'gt0 m := m > 0 /\\ logn p m = 0%N.\nsuffices [Pgt0 p'P]: p'gt0 (\\prod_(0 <= i < n.-1.+1) (p ^ i.+1 - 1))%N.\n  by rewrite lognM // p'P pfactorK //; case n.\napply big_ind => [|m1 m2 [m10 p'm1] [m20]|i _]; rewrite {}/p'gt0 ?logn1 //.\n  by rewrite muln_gt0 m10 lognM ?p'm1.\nrewrite lognE -if_neg subn_gt0 p_pr /= -{1 2}(exp1n i.+1) ltn_exp2r // p_gt1.\nby rewrite dvdn_subr ?dvdn_exp // gtnNdvd.\nQed.\n\nSection MatrixAlgebra.\n\nVariables F : fieldType.\n\nLocal Notation \"A \\in R\" := (@submx F _ _ _ (mxvec A) R).\n\nLemma mem0mx m n (R : 'A_(m, n)) : 0 \\in R.\nProof. by rewrite linear0 sub0mx. Qed.\n\nLemma memmx0 n A : (A \\in (0 : 'A_n)) -> A = 0.\nProof. by rewrite submx0 mxvec_eq0; move/eqP. Qed.\n\nLemma memmx1 n (A : 'M_n) : (A \\in mxvec 1%:M) = is_scalar_mx A.\nProof.\napply/sub_rVP/is_scalar_mxP=> [[a] | [a ->]].\n  by rewrite -linearZ scale_scalar_mx mulr1 => /(can_inj mxvecK); exists a.\nby exists a; rewrite -linearZ scale_scalar_mx mulr1.\nQed.\n\nLemma memmx_subP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, A \\in R1 -> A \\in R2) (R1 <= R2)%MS.\nProof.\napply: (iffP idP) => [sR12 A R1_A | sR12]; first exact: submx_trans sR12.\nby apply/rV_subP=> vA; rewrite -(vec_mxK vA); apply: sR12.\nQed.\nArguments memmx_subP {m1 m2 n R1 R2}.\n\nLemma memmx_eqP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, (A \\in R1) = (A \\in R2)) (R1 == R2)%MS.\nProof.\napply: (iffP eqmxP) => [eqR12 A | eqR12]; first by rewrite eqR12.\nby apply/eqmxP; apply/rV_eqP=> vA; rewrite -(vec_mxK vA) eqR12.\nQed.\nArguments memmx_eqP {m1 m2 n R1 R2}.\n\nLemma memmx_addsP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists D, [/\\ D.1 \\in R1, D.2 \\in R2 & A = D.1 + D.2])\n          (A \\in R1 + R2)%MS.\nProof.\napply: (iffP sub_addsmxP) => [[u /(canRL mxvecK)->] | [D []]].\n  exists (vec_mx (u.1 *m R1), vec_mx (u.2 *m R2)).\n  by rewrite /= linearD !vec_mxK !submxMl.\ncase/submxP=> u1 defD1 /submxP[u2 defD2] ->.\nby exists (u1, u2); rewrite linearD /= defD1 defD2.\nQed.\nArguments memmx_addsP {m1 m2 n A R1 R2}.\n\nLemma memmx_sumsP (I : finType) (P : pred I) n (A : 'M_n) R_ :\n  reflect (exists2 A_, A = \\sum_(i | P i) A_ i & forall i, A_ i \\in R_ i)\n          (A \\in \\sum_(i | P i) R_ i)%MS.\nProof.\napply: (iffP sub_sumsmxP) => [[C defA] | [A_ -> R_A] {A}].\n  exists (fun i => vec_mx (C i *m R_ i)) => [|i].\n    by rewrite -linear_sum -defA /= mxvecK.\n  by rewrite vec_mxK submxMl.\nexists (fun i => mxvec (A_ i) *m pinvmx (R_ i)).\nby rewrite linear_sum; apply: eq_bigr => i _; rewrite mulmxKpV.\nQed.\nArguments memmx_sumsP {I P n A R_}.\n\nLemma has_non_scalar_mxP m n (R : 'A_(m, n)) : \n    (1%:M \\in R)%MS ->\n  reflect (exists2 A, A \\in R & ~~ is_scalar_mx A)%MS (1 < \\rank R).\nProof.\ncase: (posnP n) => [-> | n_gt0] in R *; set S := mxvec _ => sSR.\n  by rewrite [R]thinmx0 mxrank0; right; case; rewrite /is_scalar_mx ?insubF.\nhave rankS: \\rank S = 1%N.\n  apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0 mxvec_eq0.\n  by rewrite -mxrank_eq0 mxrank1 -lt0n.\nrewrite -{2}rankS (ltn_leqif (mxrank_leqif_sup sSR)).\napply: (iffP idP) => [/row_subPn[i] | [A sAR]].\n  rewrite -[row i R]vec_mxK memmx1; set A := vec_mx _ => nsA.\n  by exists A; rewrite // vec_mxK row_sub.\nby rewrite -memmx1; apply/contra/submx_trans.\nQed.\n\nDefinition mulsmx m1 m2 n (R1 : 'A[F]_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (\\sum_i <<R1 *m lin_mx (mulmxr (vec_mx (row i R2)))>>)%MS.\n\nArguments mulsmx {m1%N m2%N n%N} R1%MS R2%MS.\n\nLocal Notation \"R1 * R2\" := (mulsmx R1 R2) : matrix_set_scope.\n\nLemma genmx_muls m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  <<(R1 * R2)%MS>>%MS = (R1 * R2)%MS.\nProof. by rewrite genmx_sums; apply: eq_bigr => i; rewrite genmx_id. Qed.\n\nLemma mem_mulsmx m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) A1 A2 :\n  (A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R1 * R2)%MS.\nProof.\nmove=> R_A1 R_A2; rewrite -[A2]mxvecK; case/submxP: R_A2 => a ->{A2}.\nrewrite mulmx_sum_row !linear_sum summx_sub // => i _.\nrewrite !linearZ scalemx_sub {a}//= (sumsmx_sup i) // genmxE.\nrewrite -[A1]mxvecK; case/submxP: R_A1 => a ->{A1}.\nby apply/submxP; exists a; rewrite mulmxA mul_rV_lin.\nQed.\n\nLemma mulsmx_subP m1 m2 m n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R : 'A_(m, n)) :\n  reflect (forall A1 A2, A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R)\n          (R1 * R2 <= R)%MS.\nProof.\napply: (iffP memmx_subP) => [sR12R A1 A2 R_A1 R_A2 | sR12R A].\n  by rewrite sR12R ?mem_mulsmx.\ncase/memmx_sumsP=> A_ -> R_A; rewrite linear_sum summx_sub //= => j _.\nrewrite (submx_trans (R_A _)) // genmxE; apply/row_subP=> i.\nby rewrite row_mul mul_rV_lin sR12R ?vec_mxK ?row_sub.\nQed.\nArguments mulsmx_subP {m1 m2 m n R1 R2 R}.\n\nLemma mulsmxS m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                            (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 <= R3 -> R2 <= R4 -> R1 * R2 <= R3 * R4)%MS.\nProof.\nmove=> sR13 sR24; apply/mulsmx_subP=> A1 A2 R_A1 R_A2.\nby apply: mem_mulsmx; [apply: submx_trans sR13 | apply: submx_trans sR24].\nQed.\n\nLemma muls_eqmx m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                              (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 :=: R3 -> R2 :=: R4 -> R1 * R2 = R3 * R4)%MS.\nProof.\nmove=> eqR13 eqR24; rewrite -(genmx_muls R1 R2) -(genmx_muls R3 R4).\nby apply/genmxP; rewrite !mulsmxS ?eqR13 ?eqR24.\nQed.\n\nLemma mulsmxP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists2 A1, forall i, A1 i \\in R1\n            & exists2 A2, forall i, A2 i \\in R2\n           & A = \\sum_(i < n ^ 2) A1 i *m A2 i)\n          (A \\in R1 * R2)%MS.\nProof.\napply: (iffP idP) => [R_A|[A1 R_A1 [A2 R_A2 ->{A}]]]; last first.\n  by rewrite linear_sum summx_sub // => i _; rewrite mem_mulsmx.\nhave{R_A}: (A \\in R1 * <<R2>>)%MS.\n  by apply: memmx_subP R_A; rewrite mulsmxS ?genmxE.\ncase/memmx_sumsP=> A_ -> R_A; pose A2_ i := vec_mx (row i <<R2>>%MS).\npose A1_ i := mxvec (A_ i) *m pinvmx (R1 *m lin_mx (mulmxr (A2_ i))) *m R1.\nexists (vec_mx \\o A1_) => [i|]; first by rewrite vec_mxK submxMl.\nexists A2_ => [i|]; first by rewrite vec_mxK -(genmxE R2) row_sub.\napply: eq_bigr => i _; rewrite -[_ *m _](mx_rV_lin (mulmxr_linear _ _)).\nby rewrite -mulmxA mulmxKpV ?mxvecK // -(genmxE (_ *m _)) R_A.\nQed.\nArguments mulsmxP {m1 m2 n A R1 R2}.\n\nLemma mulsmxA m1 m2 m3 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 * R3) = R1 * R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls (_ * _)%MS) -genmx_muls; apply/genmxP; apply/andP; split.\n  apply/mulsmx_subP=> A1 A23 R_A1; case/mulsmxP=> A2 R_A2 [A3 R_A3 ->{A23}].\n  by rewrite !linear_sum summx_sub //= => i _; rewrite mulmxA !mem_mulsmx.\napply/mulsmx_subP=> _ A3 /mulsmxP[A1 R_A1 [A2 R_A2 ->]] R_A3.\nrewrite mulmx_suml linear_sum summx_sub //= => i _.\nby rewrite -mulmxA !mem_mulsmx.\nQed.\n\nLemma mulsmx_addl m1 m2 m3 n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  ((R1 + R2) * R3 = R1 * R3 + R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls R2 R3) -(genmx_muls R1 R3) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> _ A3 /memmx_addsP[A [R_A1 R_A2 ->]] R_A3.\nby rewrite mulmxDl linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx_addr m1 m2 m3 n\n                  (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 + R3) = R1 * R2 + R1 * R3)%MS.\nProof.\nrewrite -(genmx_muls R1 R3) -(genmx_muls R1 R2) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> A1 _ R_A1 /memmx_addsP[A [R_A2 R_A3 ->]].\nby rewrite mulmxDr linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx0 m1 m2 n (R1 : 'A_(m1, n)) : (R1 * (0 : 'A_(m2, n)) = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A1 A0 _.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mulmx0 mem0mx.\nQed.\n\nLemma muls0mx m1 m2 n (R2 : 'A_(m2, n)) : ((0 : 'A_(m1, n)) * R2 = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A0 A2.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mul0mx mem0mx.\nQed.\n\nDefinition left_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R1 * R2 <= R2)%MS.\n\nDefinition right_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R2 * R1 <= R2)%MS.\n\nDefinition mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  left_mx_ideal R1 R2 && right_mx_ideal R1 R2.\n\nDefinition mxring_id m n (R : 'A_(m, n)) e :=\n  [/\\ e != 0,\n      e \\in R,\n      forall A, A \\in R -> e *m A = A\n    & forall A, A \\in R -> A *m e = A]%MS.\n\nDefinition has_mxring_id m n (R : 'A[F]_(m , n)) :=\n  (R != 0) &&\n  (row_mx 0 (row_mx (mxvec R) (mxvec R))\n    <= row_mx (cokermx R) (row_mx (lin_mx (mulmx R \\o lin_mulmx))\n                                  (lin_mx (mulmx R \\o lin_mulmxr))))%MS.\n\nDefinition mxring m n (R : 'A_(m, n)) :=\n  left_mx_ideal R R && has_mxring_id R.\n\nLemma mxring_idP m n (R : 'A_(m, n)) :\n  reflect (exists e, mxring_id R e) (has_mxring_id R).\nProof.\napply: (iffP andP) => [[nzR] | [e [nz_e Re ideR idRe]]].\n  case/submxP=> v; rewrite -[v]vec_mxK; move/vec_mx: v => e.\n  rewrite !mul_mx_row; case/eq_row_mx => /eqP.\n  rewrite eq_sym -submxE => Re.\n  case/eq_row_mx; rewrite !{1}mul_rV_lin1 /= mxvecK.\n  set u := (_ *m _) => /(can_inj mxvecK) idRe /(can_inj mxvecK) ideR.\n  exists e; split=> // [ | A /submxP[a defA] | A /submxP[a defA]].\n  - by apply: contra nzR; rewrite ideR => /eqP->; rewrite !linear0.\n  - by rewrite -{2}[A]mxvecK defA idRe mulmxA mx_rV_lin -defA /= mxvecK.\n  by rewrite -{2}[A]mxvecK defA ideR mulmxA mx_rV_lin -defA /= mxvecK.\nsplit.\n  by apply: contraNneq nz_e => R0; rewrite R0 eqmx0 in Re; rewrite (memmx0 Re).\napply/submxP; exists (mxvec e); rewrite !mul_mx_row !{1}mul_rV_lin1.\nrewrite submxE in Re; rewrite {Re}(eqP Re).\ncongr (row_mx 0 (row_mx (mxvec _) (mxvec _))); apply/row_matrixP=> i.\n  by rewrite !row_mul !mul_rV_lin1 /= mxvecK ideR vec_mxK ?row_sub.\nby rewrite !row_mul !mul_rV_lin1 /= mxvecK idRe vec_mxK ?row_sub.\nQed.\nArguments mxring_idP {m n R}.\n\nSection CentMxDef.\n\nVariables (m n : nat) (R : 'A[F]_(m, n)).\n\nDefinition cent_mx_fun (B : 'M[F]_n) := R *m lin_mx (mulmxr B \\- mulmx B).\n\nLemma cent_mx_fun_is_linear : linear cent_mx_fun.\nProof.\nmove=> a A B; apply/row_matrixP=> i; rewrite linearP row_mul mul_rV_lin.\nrewrite /= {-3}[row]lock row_mul mul_rV_lin -lock row_mul mul_rV_lin.\nby rewrite -linearP -(linearP [linear of mulmx _ \\- mulmxr _]).\nQed.\nCanonical cent_mx_fun_additive := Additive cent_mx_fun_is_linear.\nCanonical cent_mx_fun_linear := Linear cent_mx_fun_is_linear.\n\nDefinition cent_mx := kermx (lin_mx cent_mx_fun).\n\nDefinition center_mx := (R :&: cent_mx)%MS.\n\nEnd CentMxDef.\n\nLocal Notation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nLocal Notation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nLemma cent_rowP m n B (R : 'A_(m, n)) :\n  reflect (forall i (A := vec_mx (row i R)), A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP sub_kermxP); rewrite mul_vec_lin => cBE.\n  move/(canRL mxvecK): cBE => cBE i A /=; move/(congr1 (row i)): cBE.\n  rewrite row_mul mul_rV_lin -/A; move/(canRL mxvecK).\n  by move/(canRL (subrK _)); rewrite !linear0 add0r.\napply: (canLR vec_mxK); apply/row_matrixP=> i.\nby rewrite row_mul mul_rV_lin /= cBE subrr !linear0.\nQed.\nArguments cent_rowP {m n B R}.\n\nLemma cent_mxP m n B (R : 'A_(m, n)) :\n  reflect (forall A, A \\in R -> A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP cent_rowP) => cEB => [A sAE | i A].\n  rewrite -[A]mxvecK -(mulmxKpV sAE); move: (mxvec A *m _) => u.\n  rewrite !mulmx_sum_row !linear_sum mulmx_suml; apply: eq_bigr => i _ /=.\n  by rewrite !linearZ -scalemxAl /= cEB.\nby rewrite cEB // vec_mxK row_sub.\nQed.\nArguments cent_mxP {m n B R}.\n\nLemma scalar_mx_cent m n a (R : 'A_(m, n)) : (a%:M \\in 'C(R))%MS.\nProof. by apply/cent_mxP=> A _; apply: scalar_mxC. Qed.\n\nLemma center_mx_sub m n (R : 'A_(m, n)) : ('Z(R) <= R)%MS.\nProof. exact: capmxSl. Qed.\n\nLemma center_mxP m n A (R : 'A_(m, n)) :\n  reflect (A \\in R /\\ forall B, B \\in R -> B *m A = A *m B)\n          (A \\in 'Z(R))%MS.\nProof.\nrewrite sub_capmx; case R_A: (A \\in R); last by right; case.\nby apply: (iffP cent_mxP) => [cAR | [_ cAR]].\nQed.\nArguments center_mxP {m n A R}.\n\nLemma mxring_id_uniq m n (R : 'A_(m, n)) e1 e2 :\n  mxring_id R e1 -> mxring_id R e2 -> e1 = e2.\nProof.\nby case=> [_ Re1 idRe1 _] [_ Re2 _ ide2R]; rewrite -(idRe1 _ Re2) ide2R.\nQed.\n\nLemma cent_mx_ideal m n (R : 'A_(m, n)) : left_mx_ideal 'C(R)%MS 'C(R)%MS.\nProof.\napply/mulsmx_subP=> A1 A2 C_A1 C_A2; apply/cent_mxP=> B R_B.\nby rewrite mulmxA (cent_mxP C_A1) // -!mulmxA (cent_mxP C_A2).\nQed.\n\nLemma cent_mx_ring m n (R : 'A_(m, n)) : n > 0 -> mxring 'C(R)%MS.\nProof.\nmove=> n_gt0; rewrite /mxring cent_mx_ideal; apply/mxring_idP.\nexists 1%:M; split=> [||A _|A _]; rewrite ?mulmx1 ?mul1mx ?scalar_mx_cent //.\nby rewrite -mxrank_eq0 mxrank1 -lt0n.\nQed.\n\nLemma mxdirect_adds_center m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n    mx_ideal (R1 + R2)%MS R1 -> mx_ideal (R1 + R2)%MS R2 ->\n    mxdirect (R1 + R2) ->\n  ('Z((R1 + R2)%MS) :=: 'Z(R1) + 'Z(R2))%MS.\nProof.\ncase/andP=> idlR1 idrR1 /andP[idlR2 idrR2] /mxdirect_addsP dxR12.\napply/eqmxP/andP; split.\n  apply/memmx_subP=> z0; rewrite sub_capmx => /andP[].\n  case/memmx_addsP=> z [R1z1 R2z2 ->{z0}] Cz.\n  rewrite linearD addmx_sub_adds //= ?sub_capmx ?R1z1 ?R2z2 /=.\n    apply/cent_mxP=> A R1_A; have R_A := submx_trans R1_A (addsmxSl R1 R2).\n    have Rz2 := submx_trans R2z2 (addsmxSr R1 R2).\n    rewrite -{1}[z.1](addrK z.2) mulmxBr (cent_mxP Cz) // mulmxDl.\n    rewrite [A *m z.2]memmx0 1?[z.2 *m A]memmx0 ?addrK //.\n      by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  apply/cent_mxP=> A R2_A; have R_A := submx_trans R2_A (addsmxSr R1 R2).\n  have Rz1 := submx_trans R1z1 (addsmxSl R1 R2).\n  rewrite -{1}[z.2](addKr z.1) mulmxDr (cent_mxP Cz) // mulmxDl.\n  rewrite mulmxN [A *m z.1]memmx0 1?[z.1 *m A]memmx0 ?addKr //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nrewrite addsmx_sub; apply/andP; split.\n  apply/memmx_subP=> z; rewrite sub_capmx => /andP[R1z cR1z].\n  have Rz := submx_trans R1z (addsmxSl R1 R2).\n  rewrite sub_capmx Rz; apply/cent_mxP=> A0.\n  case/memmx_addsP=> A [R1_A1 R2_A2] ->{A0}.\n  have R_A2 := submx_trans R2_A2 (addsmxSr R1 R2).\n  rewrite mulmxDl mulmxDr (cent_mxP cR1z) //; congr (_ + _).\n  rewrite [A.2 *m z]memmx0 1?[z *m A.2]memmx0 //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\napply/memmx_subP=> z; rewrite !sub_capmx => /andP[R2z cR2z].\nhave Rz := submx_trans R2z (addsmxSr R1 R2); rewrite Rz.\napply/cent_mxP=> _ /memmx_addsP[A [R1_A1 R2_A2 ->]].\nrewrite mulmxDl mulmxDr (cent_mxP cR2z _ R2_A2) //; congr (_ + _).\nhave R_A1 := submx_trans R1_A1 (addsmxSl R1 R2).\nrewrite [A.1 *m z]memmx0 1?[z *m A.1]memmx0 //.\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nby rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\nQed.\n\nLemma mxdirect_sums_center (I : finType) m n (R : 'A_(m, n)) R_ :\n    (\\sum_i R_ i :=: R)%MS -> mxdirect (\\sum_i R_ i) ->\n    (forall i : I, mx_ideal R (R_ i)) ->\n  ('Z(R) :=: \\sum_i 'Z(R_ i))%MS.\nProof.\nmove=> defR dxR idealR.\nhave sR_R: (R_ _ <= R)%MS by move=> i; rewrite -defR (sumsmx_sup i).\nhave anhR i j A B : i != j -> A \\in R_ i -> B \\in R_ j -> A *m B = 0.\n  move=> ne_ij RiA RjB; apply: memmx0.\n  have [[_ idRiR] [idRRj _]] := (andP (idealR i), andP (idealR j)).\n  rewrite -(mxdirect_sumsP dxR j) // sub_capmx (sumsmx_sup i) //.\n    by rewrite (mulsmx_subP idRRj) // (memmx_subP (sR_R i)).\n  by rewrite (mulsmx_subP idRiR) // (memmx_subP (sR_R j)).\napply/eqmxP/andP; split.\n  apply/memmx_subP=> Z; rewrite sub_capmx => /andP[].\n  rewrite -{1}defR => /memmx_sumsP[z ->{Z} Rz cRz].\n  apply/memmx_sumsP; exists z => // i; rewrite sub_capmx Rz.\n  apply/cent_mxP=> A RiA; have:= cent_mxP cRz A (memmx_subP (sR_R i) A RiA).\n  rewrite (bigD1 i) //= mulmxDl mulmxDr mulmx_suml mulmx_sumr.\n  by rewrite !big1 ?addr0 // => j; last rewrite eq_sym; move/anhR->.\napply/sumsmx_subP => i _; apply/memmx_subP=> z; rewrite sub_capmx.\ncase/andP=> Riz cRiz; rewrite sub_capmx (memmx_subP (sR_R i)) //=.\napply/cent_mxP=> A; rewrite -{1}defR; case/memmx_sumsP=> a -> R_a.\nrewrite (bigD1 i) // mulmxDl mulmxDr mulmx_suml mulmx_sumr.\nrewrite !big1 => [|j|j]; first by rewrite !addr0 (cent_mxP cRiz).\n  by rewrite eq_sym => /anhR->.\nby move/anhR->.\nQed.\n\nEnd MatrixAlgebra.\n\nArguments mulsmx {F m1%N m2%N n%N} R1%MS R2%MS.\nArguments left_mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments right_mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments mx_ideal {F m1%N m2%N n%N} R%MS S%MS : rename.\nArguments mxring_id {F m%N n%N} R%MS e%R.\nArguments has_mxring_id {F m%N n%N} R%MS.\nArguments mxring {F m%N n%N} R%MS.\nArguments cent_mx {F m%N n%N} R%MS.\nArguments center_mx {F m%N n%N} R%MS.\n\nNotation \"A \\in R\" := (submx (mxvec A) R) : matrix_set_scope.\nNotation \"R * S\" := (mulsmx R S) : matrix_set_scope.\nNotation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nNotation \"''C_' R ( S )\" := (R :&: 'C(S))%MS : matrix_set_scope.\nNotation \"''C_' ( R ) ( S )\" := ('C_R(S))%MS (only parsing) : matrix_set_scope.\nNotation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nArguments memmx_subP {F m1 m2 n R1 R2}.\nArguments memmx_eqP {F m1 m2 n R1 R2}.\nArguments memmx_addsP {F m1 m2 n} A [R1 R2].\nArguments memmx_sumsP {F I P n A R_}.\nArguments mulsmx_subP {F m1 m2 m n R1 R2 R}.\nArguments mulsmxP {F m1 m2 n A R1 R2}.\nArguments mxring_idP F {m n R}.\nArguments cent_rowP {F m n B R}.\nArguments cent_mxP {F m n B R}.\nArguments center_mxP {F m n A R}.\n\n(* Parametricity for the row-space/F-algebra theory.                         *)\nSection MapMatrixSpaces.\n\nVariables (aF rF : fieldType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nLemma Gaussian_elimination_map m n (A : 'M_(m, n)) :\n  Gaussian_elimination A^f = ((col_ebase A)^f, (row_ebase A)^f, \\rank A).\nProof.\nrewrite mxrankE /row_ebase /col_ebase unlock.\nelim: m n A => [|m IHm] [|n] A /=; rewrite ?map_mx1 //.\nset pAnz := [pred k | A k.1 k.2 != 0].\nrewrite (@eq_pick _ _ pAnz) => [|k]; last by rewrite /= mxE fmorph_eq0.\ncase: {+}(pick _) => [[i j]|]; last by rewrite !map_mx1.\nrewrite mxE -fmorphV  -map_xcol -map_xrow -map_dlsubmx -map_drsubmx.\nrewrite -map_ursubmx -map_mxZ -map_mxM -map_mx_sub {}IHm /=.\ncase: {+}(Gaussian_elimination _) => [[L U] r] /=; rewrite map_xrow map_xcol.\nby rewrite !(@map_block_mx _ _ f 1 _ 1) !map_mx0 ?map_mx1 ?map_scalar_mx.\nQed.\n\nLemma mxrank_map m n (A : 'M_(m, n)) : \\rank A^f = \\rank A.\nProof. by rewrite mxrankE Gaussian_elimination_map. Qed.\n\nLemma row_free_map m n (A : 'M_(m, n)) : row_free A^f = row_free A.\nProof. by rewrite /row_free mxrank_map. Qed.\n\nLemma row_full_map m n (A : 'M_(m, n)) : row_full A^f = row_full A.\nProof. by rewrite /row_full mxrank_map. Qed.\n\nLemma map_row_ebase m n (A : 'M_(m, n)) : (row_ebase A)^f = row_ebase A^f.\nProof. by rewrite {2}/row_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_col_ebase m n (A : 'M_(m, n)) : (col_ebase A)^f = col_ebase A^f.\nProof. by rewrite {2}/col_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_row_base m n (A : 'M_(m, n)) :\n  (row_base A)^f = castmx (mxrank_map A, erefl n) (row_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/row_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_row_ebase.\nQed.\n\nLemma map_col_base m n (A : 'M_(m, n)) :\n  (col_base A)^f = castmx (erefl m, mxrank_map A) (col_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/col_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_col_ebase.\nQed.\n\nLemma map_pinvmx m n (A : 'M_(m, n)) : (pinvmx A)^f = pinvmx A^f.\nProof.\nrewrite !map_mxM !map_invmx map_row_ebase map_col_ebase.\nby rewrite map_pid_mx -mxrank_map.\nQed.\n\nLemma map_kermx m n (A : 'M_(m, n)) : (kermx A)^f = kermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_col_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_cokermx m n (A : 'M_(m, n)) : (cokermx A)^f = cokermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_row_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_submx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f <= B^f)%MS = (A <= B)%MS.\nProof. by rewrite !submxE -map_cokermx -map_mxM map_mx_eq0. Qed.\n\nLemma map_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f < B^f)%MS = (A < B)%MS.\nProof. by rewrite /ltmx !map_submx. Qed.\n\nLemma map_eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f :=: B^f)%MS <-> (A :=: B)%MS.\nProof.\nsplit=> [/eqmxP|eqAB]; first by rewrite !map_submx => /eqmxP.\nby apply/eqmxP; rewrite !map_submx !eqAB !submx_refl.\nQed.\n\nLemma map_genmx m n (A : 'M_(m, n)) : (<<A>>^f :=: <<A^f>>)%MS.\nProof. by apply/eqmxP; rewrite !(genmxE, map_submx) andbb. Qed.\n\nLemma map_addsmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (((A + B)%MS)^f :=: A^f + B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !addsmxE -map_col_mx !map_submx !addsmxE andbb.\nQed.\n\nLemma map_capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (capmx_gen A B)^f = capmx_gen A^f B^f.\nProof. by rewrite map_mxM map_lsubmx map_kermx map_col_mx. Qed.\n\nLemma map_capmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :&: B)^f :=: A^f :&: B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !capmxE -map_capmx_gen !map_submx -!capmxE andbb.\nQed.\n\nLemma map_complmx m n (A : 'M_(m, n)) : (A^C^f = A^f^C)%MS.\nProof. by rewrite map_mxM map_row_ebase -mxrank_map map_copid_mx. Qed.\n\nLemma map_diffmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B)^f :=: A^f :\\: B^f)%MS.\nProof.\napply/eqmxP; rewrite !diffmxE -map_capmx_gen -map_complmx.\nby rewrite -!map_capmx !map_submx -!diffmxE andbb.\nQed.\n\nLemma map_eigenspace n (g : 'M_n) a : (eigenspace g a)^f = eigenspace g^f (f a).\nProof. by rewrite map_kermx map_mx_sub ?map_scalar_mx. Qed.\n\nLemma eigenvalue_map n (g : 'M_n) a : eigenvalue g^f (f a) = eigenvalue g a.\nProof. by rewrite /eigenvalue -map_eigenspace map_mx_eq0. Qed.\n\nLemma memmx_map m n A (E : 'A_(m, n)) : (A^f \\in E^f)%MS = (A \\in E)%MS.\nProof. by rewrite -map_mxvec map_submx. Qed.\n\nLemma map_mulsmx m1 m2 n (E1 : 'A_(m1, n)) (E2 : 'A_(m2, n)) :\n  ((E1 * E2)%MS^f :=: E1^f * E2^f)%MS.\nProof.\nrewrite /mulsmx; elim/big_rec2: _ => [|i A Af _ eqA]; first by rewrite map_mx0.\napply: (eqmx_trans (map_addsmx _ _)); apply: adds_eqmx {A Af}eqA.\napply/eqmxP; rewrite !map_genmx !genmxE map_mxM.\napply/rV_eqP=> u; congr (u <= _ *m _)%MS.\nby apply: map_lin_mx => //= A; rewrite map_mxM // map_vec_mx map_row.\nQed.\n\nLemma map_cent_mx m n (E : 'A_(m, n)) : ('C(E)%MS)^f = 'C(E^f)%MS.\nProof.\nrewrite map_kermx //; congr (kermx _); apply: map_lin_mx => // A.\nrewrite map_mxM //; congr (_ *m _); apply: map_lin_mx => //= B.\nby rewrite map_mx_sub ? map_mxM.\nQed.\n\nLemma map_center_mx m n (E : 'A_(m, n)) : (('Z(E))^f :=: 'Z(E^f))%MS.\nProof. by rewrite /center_mx -map_cent_mx; apply: map_capmx. Qed.\n\nEnd MapMatrixSpaces.\n\n\n", "meta": {"author": "palmskog", "repo": "mathcomp-experiment", "sha": "67a6e83c025784b1e6f646a30dde38e0f33060eb", "save_path": "github-repos/coq/palmskog-mathcomp-experiment", "path": "github-repos/coq/palmskog-mathcomp-experiment/mathcomp-experiment-67a6e83c025784b1e6f646a30dde38e0f33060eb/algebra/mxalgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.7981867729389245, "lm_q1q2_score": 0.7199011458289445}}
{"text": "Load FiniteSets.\nRequire Import Bool. \nRequire Import Arith. \nRequire Import List.\nRequire Import Notations.\n  \n(*A finite set is described using an inductive definition, using 2 constructors.*)\n\nDefinition El:=Fin. \n\n(*A word is a list of elements *)(*Variable Sigma : Alphabet. *) \n(*A word is a list of elements *)\nVariable a:Alphabet.\nDefinition Word := list (Fin a).\n\nDefinition Language := Word  -> Prop.\n(**empty word/string *)\nDefinition eps :Word :=nil.\n\n(**empty word/string *)\nDefinition lang_conc(l1:Language  )(l2:Language ):Language  :=\n    fun w:Word => exists w1:Word , exists w2:Word ,  w1 ++ w2=w /\\ l1 w1 /\\ l2 w2.\n\nDefinition lang_union (l1:Language )(l2:Language ):Language :=\n    fun w:Word =>  l1 w \\/ l2 w.\n\n(* empty language imply [False] *)\nDefinition empty_lang :Language := fun w:Word =>False.\nCheck empty_lang.\n\n(** A language included into another language *)\nDefinition Included (l1:Language )(l2:Language) :Prop := forall (w:Word ), l1 w -> l2 w.\nCheck Included.\n\n\nDefinition eps_lang1 :Language := fun w:Word => w=nil.\n  \nDefinition eps_lang :Language := fun w:Word => match w with \n   |nil => True\n  | _  => False\n   end.\n\n(* L1 conc empty = empty *)\nLemma empty_lr : forall (l1:Language )(w:Word ) ,  (lang_conc l1 (empty_lang ))w <->  empty_lang w.\n\nunfold iff.\nintros.\nsplit.\nsimpl.\nintro.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nsimpl.\nsimpl in H1.\nunfold empty_lang.\nunfold empty_lang in H1.\ndestruct H1.\nintro.\n\nunfold empty_lang in H.\ndestruct H.\nQed.\n\n\nLemma empty_rl: forall (l1:Language )(w:Word ) ,(lang_conc (empty_lang ) l1 )w <->  empty_lang w.\nintros.\nunfold iff.\nsplit.\nintros.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nunfold empty_lang in H0.\ndestruct H0.\nintros.\nunfold empty_lang in H.\ndestruct H.\nQed.\n\nTheorem app_l_nil :  forall (A : Set)(l : list A),\n  l ++ nil = l.\nintros A l.\ninduction l.\nreflexivity.\nsimpl.\nrewrite IHl.\nreflexivity.\nQed.\nLemma eps_lr :forall (l1:Language)(w:Word), (lang_conc l1 eps_lang1) w <-> l1 w.\nintros.\nunfold iff.\nsplit.\nintros.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nunfold eps_lang1 in H1.\nrewrite H1 in H.\nsimpl in H.\nrewrite app_l_nil in H.\nrewrite <-H.\nexact H0.\nintro.\nunfold lang_conc.\nexists w.\nexists nil.\nsplit.\napply app_l_nil.\nsplit.\nexact H.\nunfold eps_lang1.\nreflexivity.\nQed.\nDefinition In_lang(w:Word)(l:Language) := l w.\n(* use the properties of existence quantifier to attribute the right values\nto the words *)\n\n(** distributivity property *)\nLemma distrib : forall (l1 l2 l3 :Language) (w:Word), In_lang w (lang_conc l1 (lang_union l2 l3)) <-> In_lang w (lang_union (lang_conc l1 l2) (lang_conc l1 l3)).\n(** -> *)\n\nintros.\nunfold iff.\nsplit.\nintro.\nunfold In_lang.\nunfold In_lang in H.\nunfold lang_conc.\nunfold lang_union.\nunfold lang_conc in H.\nunfold lang_union in H.\ndestruct H.\ndestruct H.\ndestruct H.\n\n(* use the properties of existence quantifier to attribute the right values\nto the words *)\ndestruct H0.\ndestruct H1.\nleft.\nexists x.\nexists x0.\nsplit.\nassumption.\nsplit.\nassumption.\nassumption.\nright.\nexists x.\nexists x0.\nsplit.\nexact H.\nsplit.\nassumption.\nassumption.\n\n(**  <- *)\nintro.\nunfold In_lang in H.\nunfold lang_union in H.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nunfold In_lang.\nunfold lang_conc.\nunfold lang_union.\nexists x.\nexists x0.\nsplit.\nexact H.\nsplit.\nexact H0.\nleft.\nexact H1.\n\n\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nunfold In_lang.\nunfold lang_conc.\nexists x.\nexists x0.\nsplit.\nexact H.\nsplit.\nexact H0.\nunfold lang_union.\nright.\nexact H1.\nQed.\n\nVariable x:Word.\n\nLemma eps_implies_nil : forall (w:Word) , eps_lang w -> w=nil.\nintros.\ninduction w.\nreflexivity.\nunfold eps_lang in H.\ndestruct H.\nQed.\n(** Found in the List library *)\n\n\n(* L conc epsilon = L *)\n\nTheorem lang_conc_neutral_left : forall (l:Language)(w:Word), In_lang w (lang_conc l eps_lang) <-> In_lang w l.\nintros.\nunfold iff.\nsplit.\nintro.\nunfold In_lang.\nunfold In_lang in H.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\nrewrite <-H.\nassert (x1 = nil).\napply eps_implies_nil.\nexact H1.\nrewrite H2.\nsimpl.\nrewrite app_l_nil.\nexact H0.\n\nintro.\nunfold In_lang.\nunfold In_lang in H.\nunfold lang_conc.\nexists w. \nexists nil.\nsplit.\nrewrite app_l_nil.\nreflexivity.\nsplit.\nexact H.\nsplit.\nQed.\n\n\n(** epsilon language belongs to L*, if L belongs to the powerset of the word , L* bleongs to the\npowerset of the word (using concatenation) *)\n\nInductive Star(x:Language) : Language := \n  | nil0: (Star x) nil\n  | cons0 : forall (a: Word)(b:Word),Star x a /\\ x b -> Star x (app a b).\n\n\n(** the power of a language L : L^n = LLLL...L n times *)\nFixpoint lang_power (l:Language)(n:nat) : Language := \n     match n with \n     | 0 => eps_lang\n     | S n => lang_conc l (lang_power l n)\n     end.\n\n(** L1 conc(L2 conc L3) =(L1 conc L2) conc L3 \nassume w= v0++ v1, v0 in L1\nv1 in L2 conc L3\nv1 = v2++v3,\nv2 in L2 /\\ v3 in L3,\nw = v0++(v2++v3) = (v0++ v2)++v3 (associativity of lists) in L1 L2 L4\n*)\nAxiom app_ao : forall (A:Set)(l1 l2 l3 : list A) , l1 ++ app l2 l3 = (l1 ++ l2) ++ l3.\nLemma ab : forall (A:Set) (l1 l2 : list A) ,  app l1 l2 = l1 ++ l2.\nintros.\nreflexivity.\nQed.\nLemma abc : forall (A:Set) (l1 l2 l3: list A), app l1 l2 ++ l3 = l1 ++ (l2 ++l3).\nintros.\nsimpl.\nadmit.\nQed.\nLemma lang_assoc : forall (l1 l2 l3:Language)(w:Word), In_lang w (lang_conc l1 (lang_conc l2 l3)) <-> In_lang w (lang_conc (lang_conc l1 l2) l3).\n\n\nintros.\nunfold iff.\nsplit.\nintro.\nunfold In in H.\n\nunfold In_lang.\nunfold lang_conc.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\ndestruct H1.\ndestruct H1.\ndestruct H1.\ndestruct H2.\nassert( In_lang x1 (lang_conc l2 l3)).\nunfold In_lang.\nunfold lang_conc.\nexists x2.\nexists x3.\nsplit.\nexact H1.\nsplit.\nassumption.\nassumption.\nrewrite <-H1 in H.\n\n\nrewrite app_ao in H.\nexists (x0 ++ x2).\nexists x3.\nsplit.\n\nrewrite <-H.\nsimpl.\nadmit.\n(* Coq does not recognise app x0 x2 ++ x3 as (x0 ++ x2) ++ x3 ??*)\nsplit.\nexists x0.\nexists x2.\nsplit.\nreflexivity.\nsplit.\nassumption.\nassumption.\nexact H3.\n\nintro.\nunfold In.\nunfold In in H.\nunfold lang_conc.\nunfold lang_conc in H.\ndestruct H.\ndestruct H.\ndestruct H.\ndestruct H0.\ndestruct H0.\ndestruct H0.\ndestruct H0.\ndestruct H2.\n\nrewrite <-H0 in H.\nrewrite abc in H.\nexists x2.\nexists (x3++ x1).\nsplit. (* x2 ++ app x3 x1 *)\nadmit. \nsplit.\nexact H2.\n\nexists x3.\nexists x1.\nsplit.\nreflexivity.\nsplit.\nassumption.\nassumption.\nQed.\n\n(** Star (Star L) = Star l.  we will prove this by using *) \n Lemma kleene1 : forall (l:Language) (w:Word), In_lang w (Star l) ->In_lang w (Star (Star l)).\n\nunfold In_lang.\nintros.\nrewrite <- app_nil_l.\nassert (Star (Star l) nil).\napply (nil0 ).\nassert ((Star (Star l) nil) /\\ ((Star l) w)).\nsplit.\nassumption.\nassumption.\napply (cons0) in H1.\nexact H1.\nQed.\n\nAxiom nil_O_r : forall (A:Set)(l:list A), l++nil = l.\n(*Lemma star_help: forall (l:Language)(a: Word) , In_lang a (Star l) -> In_lang a l.\nintros.\nunfold In_lang in *.\ninduction a0.\nsimpl. *)\nLemma kleene2: forall (l:Language)(w:Word), In_lang w (Star(Star l)) -> In_lang w (Star l).\nunfold In_lang.\n\nPrint Star.\nintros.\ninduction H.\napply nil0.\n\nPrint Star.\nassert (Star (Star l) (a0 ++ b)).\napply cons0.\nexact H.\n\ndestruct H.\ndestruct H.\ntrivial.\ndestruct H.\napply cons0.\nintuition.\n\n\n\n\ninduction w.\nunfold In_lang in *.\nintro.\napply nil0.\n\nintro.\n\nunfold In_lang in *.\n\nset(xs := a0:: nil).\nassert (xs ++ w = a0::w).\nsimpl in *.\nreflexivity.\nrewrite <-H0.\n\napply cons0.\nrewrite <-H0 in H.\nassumption.\n\n\nintros.\nunfold In_lang in *.\ninduction H.\napply nil0.\ndestruct H.\napply cons0.\nsplit.\n\n\ninduction w.\napply nil0.\nassumption.\nQed.\ndestruct H.\n(** Not required\nLemma star_if: forall ( l:Language) (a b : Word) , In_lang a (Star l) /\\ In_lang b (Star l) -> In_lang (a ++ b) (Star l).\n\nintros.\nunfold In_lang.\nunfold In_lang in H.\ndestruct H.\ninduction H0.\nsimpl.\nrewrite nil_O_r.\nassumption.\nPrint Star.\nassert(Star l (a0 ++b )).\napply cons0.\ndestruct H0.\nsplit.\nassumption.\nassumption.\ndestruct H0.\n\n\n\nintros.\n\ndestruct H.\nadmit.\nadmit.\nQed. *)\n\n\nLemma kleene2: forall (l:Language)(w:Word), In_lang w (Star(Star l)) -> In_lang w (Star l).\nintros.\nunfold In_lang.\nunfold In_lang in H.\n\ninduction H.\napply nil0.\ndestruct H.\napply cons0.\nsplit.\ninduction H.\napply nil0.\napply cons0.\nsplit.\ninduction w.\napply nil0.\n\n\n\nPrint Star.\nset(xs := a0:: nil).\nassert (xs ++ w = a0::w).\nsimpl in *.\nreflexivity.\nrewrite <-H0.\napply star_if.\nsplit.\nunfold In_lang.\nPrint Star.\napply cons0.\nsplit.\nPrint Star.\ninduction xs.\napply nil0.\n\ninduction H.\napply nil0.\ndestruct H.\nPrint Star.\ninduction H0.\napply cons0.\nintuition.\n\ninduction w.\napply nil0.\n\ninduction H.\napply nil0.\n\napply cons0.\nsplit.\ndestruct H.\n\ninduction w.\napply nil0.\ndestruct H.\napply nil0.\napply cons0.\n\nPrint Star.\ninduction w.\napply nil0.\n\nassert (l(a0::w) -> Star l (a0::w)).\nintros.\nPrint Star.\n\nadmit.\n\napply H0.\n\napply nil0.\ndestruct H.\napply cons0.\ninduction H.\napply nil0.\ndestruct H.\nPrint Star.\napply cons0.\nsplit.\ninduction w.\nsimpl.\napply nil0.\n\n\ndestruct H.\napply nil0.\ndestruct H.\n\napply cons0.\nsplit.\n\n\ninduction H.\n\n\napply nil0.\ndestruct H.\n\n\n\n \nassert(Star (Star l) (a++b)).\napply cons0.\nsplit.\nassumption.\nassumption.\nassert(Star(Star l) b).\napply kleene1.\nunfold In_lang.\nexact H0.\ninduction H.\nsimpl.\nassumption.\ndestruct H.\nassert (Star l (b0 ++ b)).\napply lem.\nunfold In_lang.\nsplit.\nassumption.\nassumption.\n\n\n\ninduction a.\nsimpl.\nexact H4.\n\nPrint Star.\n\ndestruct H.\nsimpl.\nassumption.\ndestruct H.\n\n\n\ninduction H0.\nsimpl.\nassert(a++nil = a).\nadmit.\nrewrite H0.\n\ninduction H.\n\n\n\n\n\n\n\ninduction H.\nexact (nil0 l).\nassert(Star (Star l ) (a++b)).\napply cons0.\nassumption.\n\nPrint Star.\n\ndestruct H.\ninduction H.\nsimpl.\nassumption.\ndestruct H.\nassert(Star l (b0++b)).\napply lem.\nunfold In_lang.\nsplit.\nassumption.\nassumption.\nadmit.\n(*\ninduction H0.\nassert (a++ nil = a).\nadmit.\nrewrite H0.\ninduction H.\napply nil0.\napply cons0.\nsplit. *)\n\n\ninduction H.\nsimpl.\nexact H0.\nPrint Star.\n\nassert(Star l (a++b0)).\ndestruct H.\n\n\nassert (Star (Star l) (a ++ b0)).\napply cons0.\nexact H.\nPrint Star.\n\nassert (Star (Star l) b).\napply kleene1.\nunfold In_lang.\nexact H0.\nPrint Star.\n\n\n\ninduction H.\nsimpl.\nexact H0.\n\napply cons0.\n", "meta": {"author": "radu07", "repo": "dissertation1", "sha": "191837b0ec9cb5b890eba304f665586d05bff20a", "save_path": "github-repos/coq/radu07-dissertation1", "path": "github-repos/coq/radu07-dissertation1/dissertation1-191837b0ec9cb5b890eba304f665586d05bff20a/code/Language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7199008827225667}}
{"text": "(** * Индукция: Доказательство по Индукции *)\n\n(** Во первых, импортируем все наши определения из предыдущей главы. *)\n\nRequire Export Basics.\n\n(** Для того чтобы [Require Export] заработало, нам сначало необходимо\n    использовать [coqc] для компиляции [Basics.v] в [Basics.vo]. Это \n    похоже на то как делается .class файл из .java файла, или .o файл из .c\n    файла. Есть два способа это сделать:\n\n     - В CoqIDE:\n\n         Открыть [Basics.v].  В меню \"Compile\", кликнуть на \"Compile\n         Buffer\".\n\n     - Из командной строки:\n\n         Запустить [coqc Basics.v]\n\n    *)\n\n(* ###################################################################### *)\n(** * Доказательство по индукции *)\n\n(** В прошлой главе мы доказали что [0] есть нейтральный элемент \n    слева для [+], используя простой аргумент основанный на упрощении.\n    Факт того, что он также является нейтральным элементом _справа_... *)\n\nTheorem plus_n_O_firsttry : forall n:nat,\n  n = n + 0.\n\n(** ... не может быть доказан таким же простым способом. Простое\n  применение [reflexivity] не срабатывает, так как [n] в [n + 0] есть\n  произвольное неизвестное число, поэтому [match] в определении [+] не может\n  быть упрощен.  *)\n\nProof.\n  intros n.\n  simpl. (* Ничего не происходит! *)\nAbort.\n\n(** Рассужение с перебором случаев и использованием [destruct n] также не\n   продвигает нас далеко: ветвь анализа случаев, где мы предполагаем [n = 0]\n   доказывается хорошо, но ветвь [n = S n'] для некоторого [n'] останавливает\n   нас аналогично предыдущей попытке.  Мы можем использовать [destruct n']\n   для продвижения на еще один шаг, но, так как [n] произвольно большое, то\n   делая таким образом никогда не закончим. *)\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. (* пока хорошо... *)\n  - (* n = S n' *)\n    simpl.       (* ...но здесь мы застряли опять *)\nAbort.\n\n(** Для доказательства интересных фактов о числах, списках и \n    других индуктивно определенных множествахм нам нужен более\n    мощный принцип вывода: _индукция_.\n\n    Вспомните (из школы или курса дискретной математики) принцип\n    индукции на натуральных числах: Если [P(n)] есть некоторое\n    утверждение (пропозиция) включающая натуральное число [n] и\n    мы хотим показать, что [P] справедливо для _всех_ чисел [n], \n    мы можем рассуждать следующим образом:\n         - показать справедливость [P(O)];\n         - показать что, для любого [n'], если [P(n')] справесливо, \n           то также справедливо [P(S n')];\n         - заключить что [P(n)] справедливо для всех [n].\n\n    В Coq, шаги остаются теми же, но в противоположном порядке:\n    мы начинаем с цели [P(n)] для всех [n] и разбиваем \n    (используя тактику [induction]) на две подцели:\n    во первых показываем [P(O)] а затем показываем [P(n') -> P(S\n    n')].  Вот как это работает для нашей теоремы: *)\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\n(** Как и [destruct], тактика [induction] принимает условие [as...]\n    для определения имен переменных, которые надо ввести в подцели.\n    В первой ветке, [n] заменяется на [0] и целью становится\n    [0 + 0 = 0], что доказывается упрощением. Во второй, [n] заменяется\n    [S n'] и утверждение [n' + 0 = n'] добавляется в контекст (под именем [IHn'],\n    т.е., Индуктивная Гипотеза для [n'] -- заметьте, что это имя\n    явным образом выбрано [as...] условием вызова [induction]\n    вместо предоставления выбора Coq). Целью в данном случае становится\n    [(S n') + 0 = S n'], что упрощается до [S (n' + 0)\n    = S n'], которая в свою очередь следует из [IHn']. *)\n\nTheorem minus_diag : forall n,\n  minus n n = 0.\nProof.\n  (* СДЕЛАНО В КЛАССЕS *)\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(** (Использование тактики [intros] в данных доказательствах на самом\n     излишне. Когда применено к цели содежащей квантор всеобщности,\n     тактика [induction] автоматически переместит эти переменные \n     в контекст по мере необходимости.) *)\n\n(** **** Упражнение: 2 звездочки, рекомендовано (basic_induction)  *)\n(** Докажите следующее используя индукцию. Вам могут понадобиться\n    предыдуще доказанные результаты. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem plus_n_Sm : forall n m : nat, \n  S (n + m) = n + (S m).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem plus_assoc : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 2 звездочки (double_plus)  *)\n(** Рассмотрите следующую функцию, которая удваивает свой аргумент: *)\n\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\n(** Используя индукцию докажите следующий простой факт о [double]: *)\n\nLemma double_plus : forall n, double n = n + n .\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 2 звездочки, дополнительное (evenb_S)  *)\n(** Один неудобный аспект нашего определения [evenb n] состоит в том, что\n    оно требует реккурсивного вызова на [n - 2]. Это делает доказательства\n    связанные с [evenb n] труднее, когда используется индукция по [n], так как\n    нам может понадобиться индуктивная гипотеза о [n - 2]. Следующая лемма\n    предоставляет более удобную характеристику [evenb (S n)]: *)\n\nTheorem evenb_S : forall n : nat,\n  evenb (S n) = negb (evenb n).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 1 звездочка (destruct_induction)  *)\n(** Коротко изложите разницу между тактиками [destruct] \n    и [induction].\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n*)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Доказательства в Доказательствах *)\n\n(** В Coq, как и в обычной математике, большие доказательства часто\n    разбиваются на последовательность теорем, с последующими теоремами\n    ссылающимися на предыдущие теоремы. Но иногда доказательства требует\n    некоторый факт который слишком тривиалем и мал, чтобы представлять\n    интерес в виде формулировки в виде отдельной теоремы. В таких случая\n    было бы удобно иметь возможность просто сформулировать и доказать\n    необходимую \"подтеорему\" прямо на месте ее использования. Тактика\n    [assert] позволяет это сделать. Например, наше ранее доказательство\n    теоремы [mult_0_plus] обращалось к предыдущей теореме [plus_O_n].\n    Вместо этого мы могли бы использовать [assert] для формулировки\n    и доказательства [plus_O_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). { reflexivity. }\n  rewrite -> H.\n  reflexivity.  Qed.\n\n(** Тактика [assert] вводит две подцели. Первая подцель это само нужное\n    нам утверждение, используя [H:] мы задаем ему имя [H].  (Мы также\n    можем задать имя утверждения с помощью [as] как мы это делали\n    раньше в случае [destruct] и [induction], т.е., [assert (0 + n\n    = n) as H].)  Заметьте, как мы выделяем доказательство утверждения\n    фигурными скобками [{ ... }], как для читаемости, так и для того,\n    чтобы в интерактивной сессии Coq легче видеть когда мы закончили\n    под докозательство. Вторая цель такая же как и предыдущая в момент\n    до использования [assert] за исключением того, что теперь у нас\n    в контексте утверждение [H] о том что [0 + n = n].  Таким образомо,\n    [assert] генерирует одну подцель, в которой мы должны  доказать\n    нужный нам факт и вторую подцель где мы можем использовать\n    данный факт для дальнейшего прогресса в том что мы с самого\n    начала пытались доказать. *)\n\n(** Тактика [assert] пригождается во многих ситуациях. Например, предположим\n    что мы хотим доказать что [(n + m) + (p + q) = (m +\n    n) + (p + q)]. Единственная разница между обоими частями [=] состоит\n    в том, что аргументы [m] и [n] в первом внутреннем [+] переставлены\n    местами, и кажется что нам может помочь коммутативность сложения ([plus_comm])\n    для переписывания одной части в другую. Тем не менне, тактика [rewrite]\n    немного глупа в том _где_ она применяет переписывание. У нас есть\n    три использование [+], и оказывается, что [rewrite -> plus_comm] воздействует\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  (* Нам просто нужно переставить (n + m) на (m + n)...\n     кажется plus_comm должно это сделать! *)\n  rewrite -> plus_comm.\n  (* Не работает...Coq переписал неправильный плюс! *)\n\t\t     Abort.\n\n(** Чтобы [plus_comm] был применен в точке, которая нам нужна, мы можем ввести локальную\n    лемму, утверждающую [n + m = m + n] (для конкретного [m] и [n] с которыми мы работаем), \n    доказать данную лемму используя [plus_comm], а затем применить ее для требуемого\n    переписывания. *)\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\n(* ###################################################################### *)\n(** * Больше Упражнений *)\n\n(** **** Упражнение: 3 звездочки, рекомендованное (mult_comm)  *)\n(** Используйте [assert] как помощь в доказательстве теоремы. Нет необходимости\n   использовать индукцию в [plus_swap]. *)\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\n(** Теперь докажите коммутативность умножения.  (Вам наверное понадобится\n    определить и доказать отдельную вспомогательную лемму для использования\n    в основном доказательства. Вы можете найти [plus_swap] полезной.) *)\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 3 звездочки, дополнительное (больше упражнений)  *)\n(** Возьмите лист бумаги. Для каждой из следующих теорем, во первых\n    _подумайте_ о (a) может ли она быть доказана с использованием лишь\n    упрощением и переписыванием, (b) требует ли она также анализа случаев\n    ([destruct]), или (c) также потребуется индукция. Запишите ваше предсказание.\n    Затем заполните доказательство. (Нет необходимости приносить или показывать\n    ваш лист с предсказаниями. Это исключительно для тренировки мысли!) *)\n\nTheorem leb_refl : forall n:nat,\n  true = leb n n.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem zero_nbeq_S : forall n:nat,\n  beq_nat 0 (S n) = false.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem plus_ble_compat_l : forall n m p : nat,\n  leb n m = true -> leb (p + n) (p + m) = true.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem S_nbeq_0 : forall n:nat,\n  beq_nat (S n) 0 = false.\nProof.\n  (* ЗАПОЛОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem mult_1_l : forall n:nat, 1 * n = n.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\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  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem mult_plus_distr_r : forall n m p : nat,\n  (n + m) * p = (n * p) + (m * p).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 2 звездочки, дополнительное (beq_nat_refl)  *)\n(** Докажите следующую теорему.  (Ставить [true] в левую часть\n    равенства может показаться странным, но это так как данная теорема\n    определена в стандартной библиотеке Coq, так что мы просто следуем\n    их выбору. Переписывание работает одинакого хорошо в обоих направлениях,\n    так что мы не будем иметь проблем от нашего способа формулировки\n    данной теоремы.) *)\n\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 2 звездочки, дополнительное (plus_swap')  *)\n(** Тактика [replace] позволяет указать конкретный подтерм для переписывания\n   и на что именно он должен быть переписан: [replace (t) with (u)]\n   заменяет (все копии) выражения [t] в цели на выражения\n   [u], и генерирует [t = u] в качестве дополнительной подцели. Это часто полезно\n   когда просто [rewrite] воздействует на неправильную часть цели.\n\n   Используйте тактику [replace] чтобы доказать [plus_swap'], аналогичную\n   [plus_swap] но без использования [assert (n + m = m + n)]. *)\n\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  (* ЗАПОЛНИТЕ ЗДЕСЬ *) Admitted.\n(** [] *)\n\n(** **** Упражнение: 3 звездочки, рекомендовано (binary_commute)  *)\n(** Вспомните функции [incr] и [bin_to_nat], которые вы написали для\n    упражнения [binary] главы [Basics]. Докажите, что следующая\n    диаграмма коммутирует:\n\n               bin --------- incr -------> bin\n                |                           |\n            bin_to_nat                  bin_to_nat\n                |                           |\n                v                           v\n               nat ---------- S ---------> nat\n\n    А именно, инкрементируя бинарное число и конвертируя его в унарное\n    производит тот же результат, что и конвертация в натуральное число с\n    последующим инкрементированием. Назовите свою теорему [bin_to_nat_pres_incr] \n    (\"pres\" от \"preserves\").\n\n    Прежде чем начать работать над упражнением, скопируйте определения\n    из вашего решение упражнения [binary] так чтобы данный файл оценивался\n    самостоятельно. Если вы находите более удобным поменять оригинальные\n    определения для упрощения доказательства, то можете это сделать! *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(** **** Упражнение: 5 звездочек, продвинутое (binary_inverse)  *)\n(** Данное упражнение является продолжением предыдущего упражнения о\n    бинарных числах. Вам понадобятся ваши определения и теоремы оттуда\n    для завершения этого упражнения.\n\n    (a) Во первых, напишите функцию конвертирующую натуральные числа\n        в бинарные числа. Затем докажите что начиная с произвольного\n        натурального числа, конвертирую его в бинарное, а затем обратно\n        получается то же натуральное число, с которого мы начали.\n\n    (b) Вы можете естественно подумать, что можно доказать аналогичный\n        факт в обратном направлении: начав с бинарного числа, сконвертиров\n        его в натуральное, а затем обратно в бинарное, мы получим\n        то же число с которого начали. Там не менее, это не так!\n        Объясните в чем здесь состоит проблема.\n\n    (c) Определите функцию \"прямой\" нормализации -- т.е., функцию\n        [normalize] из бинарных чисел в бинарные числа, так чтобы для\n        любого бинарного числа b, конвертируя его в натуральное, а затем обратно\n        получилось бы [(normalize b)].  Докажите это.  (Предупреждение: данная\n        часть сложна!)\n\n    Опять же, совободно меняйте свои предыдущие определения, если это вам \n    здесь поможет. *)\n\n(* ЗАПОЛНИТЕ ЗДЕСЬ *)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Формальные и Неформальные Доказательства (Дополнительный Материал) *)\n\n(** \"_Неформальные доказательства есть алгоритмы; формальные доказательства есть код_.\" *)\n\n(** Вопрос что же состовляет доказательство математического утверждения\n    волновал философов тысячелетия. Готовое и грубое определение было\n    бы таким: доказательство математического утверждения [P] это \n    записаный (или сказанный) текст, который приводит читателя или\n    слушателя к твердому убеждению того что [P] справедливо. Таким образом,\n    доказательство это акт коммуникации.\n\n    Акты коммуникации могут включать в себя разные типы \"читателей\".\n    С одной стороны, \"читателем\" могут быть программы вроде Coq, и в этом\n    случае \"вера\" основывается на том что [P] может быть механистически\n    выведено из некоторог множества формальных логических правил, и \n    доказательство эт рецепт, который помогает программе проверить\n    заданный факт. Такие рецепты и есть _формальные доказательства_.\n\n    Альтернативно, читателем может быть человек, и в этом случае\n    доказательство будет записано на некотором естественном языке,\n    и таким образом будет _неформальным_. Здесь, критерии успеха\n    определены менее ясно. \"Валидное\" доказательством является то,\n    которое позволяет убедить читателя поверить в [P]. Однако, тоже\n    самое доказательство может быть прочитано разными читателями,\n    некоторые из которых могут быть убеждены данным конкретным\n    способом выразить агумент, в то время как другие могут и не быть.\n    Отдельные читатели могут быть педантичны, неопытны или просто\n    тугодумы. Единственный способ убедить таких это предоставить\n    все мучительно детально. Другие читатели, более знакомые с\n    конкретной областью могут найти такой обилие деталей неприемлемым,\n    так как теряется общая суть.  Все что они хотят, это услышать\n    главные идеи, так как для них легче заполнить детали самим, чем\n    пробираться через из запись. Итого, не существует универсального\n    стандарта, так как нет одного простого пути, которым неформальное\n    доказательство гарантировало бы убедить любого возможного читателя.\n\n    На практике, тем не менее, математики разработали богатый набор\n    конвенций и идиом для описания сложных математических объектов,\n    которые -- по крайней мере в рамках конкретных сообществ -- делают\n    коммуникацию вполне надежной. Конвенции данные конвенции такой\n    стилизованой формы коммуникации предоставляют вполне ясный\n    стандарт для разделения хороших и плохих доказательств.\n\n    Так как мы используем Coq в данном курсе, мы будем много работать\n    с формальными доказательствами. Но это не означает, что мы можем\n    полностью забыть о неформальных!  Формальные доказательства полезны\n    многими способами, но они _не_ очень эффективны для коммуникации идей\n    между людьми. *)\n\n(** Например, приведем доказательство того, что суммирование аддитивно: *)\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\n(** Coq вполне доволен этим. Для человека, тем не менее, достаточно\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  - (* n = 0 *)\n    reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.   Qed.\n\n(** ... и если вы привычны к Coq то сможете пройти через все тактики\n    в своем воображении и представить сосотяния текущих цели и контекста\n    в каждой точке. Хотя если доказательство станет немного более \n    сложным, то такое упражнение будет практически невозможным.\n\n    Математик (педантичный) мог бы записать ээто доказательство примерно так: *)\n\n(** - _Theorem_: For any [n], [m] and [p],\n\n      n + (m + p) = (n + m) + p.\n\n    _Proof_: Индукцией по [n].\n\n    - Во первых, предположим [n = 0].  Мы должны показать\n\n        0 + (m + p) = (0 + m) + p.\n\n      Это следует напрямую из определения [+].\n\n    - Далее, предположив [n = S n'], где\n\n        n' + (m + p) = (n' + m) + p.\n\n      Покажем\n\n        (S n') + (m + p) = ((S n') + m) + p.\n\n      По определению [+], это следует из\n\n        S (n' + (m + p)) = S ((n' + m) + p),\n\n      которое напрямую следует из гипотезы индукции.  _Qed_. *)\n\n\n(** Общая форма доказательства в целом таже самая, и конечно же \n    это не случайность: Coq был задуман так, чтобы тактика\n    [induction] генерировала бы теже подцели, в том же порядке,\n    что математик бы написал сам. Однако есть существенная разница\n    в степени детализации: формальное доказательство намного более\n    явно выписанно в отдельных моментах (например, использование [reflexivity])\n    но более неявное в других (в частности, \"состояние доказательства\"\n    в каждый момент в доказательстве Coq задано полностью неявно,\n    тогда как в неформальном доказательстве мы часто напоминаем читателю\n    что на данный момент у нас есть). *)\n\n(** **** Упражнение: 2 звездочки, продвинутое, рекомендованное (plus_comm_informal)  *)\n(** Переведите ваше доказательство для [plus_comm] в неформальное доказательство:\n\n    Теорема: Суммирование коммутативно.\n\n    Доказательство: (* ЗАПОЛНИТЕ ЗДЕСЬ *)\n*)\n(** [] *)\n\n(** **** Упражнение: 2 звездочки, дополнительное (beq_nat_refl_informal)  *)\n(** Запишите неформальное доказательство следующей теоремы, используя неформально\n    доказательство [plus_assoc] в качестве модели. Не надо просто перефразировать\n    названия тактик Coq на русском!\n\n    Теорема: [true = beq_nat n n] для любого [n].\n\n    Доказательство: (* ЗАПОЛНИТЕ ЗДЕСЬ *)\n[] *)\n\n(** $Date: 2016-05-26 16:17:19 -0400 (Thu, 26 May 2016) $ *)\n", "meta": {"author": "karsar", "repo": "SF_Russian", "sha": "653657985d4134973a512cc897bf1793c6ebd378", "save_path": "github-repos/coq/karsar-SF_Russian", "path": "github-repos/coq/karsar-SF_Russian/SF_Russian-653657985d4134973a512cc897bf1793c6ebd378/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.7199008702316247}}
{"text": "Require Import ssreflect.\nTheorem frobenius (A : Set) (P : A -> Prop) (Q : Prop) :\n  (exists x : A, Q /\\ P x) <-> (Q /\\ exists x : A, P x).\nProof.\n  split=> [[x [q px]]|[q [x px]]].\n  - split => //. by exists x.\n  - by exists x.\nQed.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/frob.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7198456246414586}}
{"text": "Require Import List PeanoNat FunInd Arith.Wf_nat Recdef.\nImport ListNotations.\nFrom mathcomp Require Import ssreflect.\n\nModule Sort.\n\nFixpoint sorted (xs: list nat): Prop :=\n  match xs with\n  | [] => True\n  | x1 :: xs1 => (forall x, In x xs1 -> x1 <= x) /\\ sorted xs1\n  end.\n\nExample sorted_example1:\n  sorted ([1; 2; 3]).\nProof.\nrewrite /=.\nsplit.\n  move=> x.\n  case.\n    move=> H; rewrite -H.\n    auto.\n  case=> //.\n    move=> H; rewrite -H.\n    auto.\nsplit.\n  move=> x.\n  case=> //.\n  move=> H; rewrite -H.\n  auto.\nsplit=> //.\nQed.\n\n(* 上のsortedの定義は少しややこしいので、もっとシンプルな定義と同値なことを証明しておきます *)\nFixpoint sorted_simple (xs: list nat): Prop :=\n  match xs with\n  | [] => True\n  | x1 :: [] => True\n  | x1 :: (x2 :: _) as xs' => x1 <= x2 /\\ sorted_simple xs'\n  end.\n\nDefinition length_sorted_simple(l: nat) :=\n  forall xs, l = length xs -> sorted_simple xs -> sorted xs.\n\nTheorem sorted_simple_iff: forall xs,\n  sorted xs <-> sorted_simple xs.\nProof.\nmove=> xs.\nsplit.\n- induction xs => //.\n  rename a into x1.\n  rewrite /=.\n  case.\n  move=> Hx1_le_xs Hxs_sorted.\n  case_eq xs => //.\n  move=> x2 xs2 Hxs.\n  rewrite -Hxs.\n  split.\n  + apply Hx1_le_xs.\n    rewrite Hxs /=.\n    by left.\n  + by apply IHxs.\n- apply: (lt_wf_ind (length xs) length_sorted_simple) => //.\n  clear xs.\n  move=> l.\n  rewrite /length_sorted_simple.\n  move=> Hlength_lt_sorted xs H Hsorted_simple.\n  subst.\n  case_eq xs => //=.\n  move=> x1 xs1 Hxs.\n  split.\n  + move: Hsorted_simple.\n    rewrite Hxs /=.\n    case_eq xs1 => //.\n    move=> x2 xs2 Hxs1.\n    case.\n    move=> Hx1_le_x2 Hsorted_simple_xs1 x.\n    rewrite /=.\n    case.\n      by move=> H; rewrite -H.\n    move=> Hx_in_xs2.\n    apply (Nat.le_trans x1 x2 x) => //.\n    suff: sorted xs1.\n      rewrite Hxs1 /=.\n      case.\n      move=> H _.\n      by apply H.\n    apply (Hlength_lt_sorted (length xs1)) => //.\n    * by rewrite Hxs /=.\n    * by rewrite Hxs1.\n  + apply (Hlength_lt_sorted (length xs1)) => //.\n    * by rewrite Hxs /=.\n    * move: Hsorted_simple.\n      rewrite Hxs /=.\n      case_eq xs1 => //.\n      move=> x2 xs2 Hxs1.\n      case.\n      by move=> _ H.\nQed.\n\nLemma filter_length {A: Type} : forall (xs: list A) f,\n  length (filter f xs) <= length xs.\nProof.\nmove=> xs f.\ninduction xs => //.\nrewrite /=.\ncase (f a).\n- suff: S (length (filter f xs)) <= S (length xs).\n    by rewrite /=.\n  by rewrite -Nat.succ_le_mono.\n- by apply Nat.le_le_succ_r.\nQed.\n\nFunction quick_sort (xs: list nat) {measure length}: list nat :=\n  match xs with\n  | [] => []\n  | pivot :: xs1 =>\n    let right := filter (fun x => x <? pivot) xs1 in\n    let left := filter (fun x => pivot <=? x) xs1 in\n      (quick_sort right) ++ pivot :: (quick_sort left)\n  end.\nProof.\n(* xs = pivot :: xs1 *)\nmove=> xs pivot xs1 Hxs.\nrewrite /=.\napply Nat.lt_succ_r.\nby apply filter_length.\n\nmove=> xs pivot xs1 Hxs.\nrewrite /=.\napply Nat.lt_succ_r.\nby apply filter_length.\nQed.\n\nExample quick_sort_example:\n  quick_sort [3; 4; 1; 4; 2] = [1; 2; 3; 4; 4].\nProof.\nrewrite quick_sort_equation /=.\nrewrite 2!quick_sort_equation /=.\nrewrite 2!quick_sort_equation /=.\nrewrite quick_sort_equation /=.\nrewrite 2!quick_sort_equation /=.\nby rewrite quick_sort_equation.\nQed.\n\nLemma quick_sort_nil:\n  quick_sort [] = [].\nProof.\nby rewrite quick_sort_equation.\nQed.\n\nLemma quick_sort_single: forall x1: nat,\n  quick_sort [x1] = [x1].\nProof.\nmove=> x1.\nrewrite quick_sort_equation /=.\nby rewrite quick_sort_equation.\nQed.\n\nLemma sorted_app: forall l r,\n  sorted l -> sorted r -> (forall lx rx, In lx l -> In rx r -> lx <= rx) ->\n  sorted (l ++ r).\nProof.\nmove=> l r Hsorted_l Hsorted_r Hlx_le_rx.\ninduction l.\n  by [].\nrename a into l1.\nsuff: sorted (l1 :: l ++ r).\n  by [].\nrewrite /=.\nsplit.\n- move=> x Hin_x.\n  have: In x l \\/ In x r.\n    by rewrite -in_app_iff.\n  case.\n  + move=> Hx_in.\n    move: Hsorted_l.\n    rewrite /=.\n    case.\n    move=> H _.\n    by apply H.\n  + apply Hlx_le_rx.\n    apply in_eq.\n- apply IHl.\n  + by apply Hsorted_l.\n  + move=> lx rx Hlx_in Hrx_in.\n    apply Hlx_le_rx.\n    * rewrite /=.\n      by right.\n    * by [].\nQed.\n\nLemma filter_negb_In {A: Type}: forall xs (x: A) f g,\n  In x xs ->\n  (forall x', g x' = negb (f x')) ->\n  In x (filter f xs) \\/ In x (filter g xs).\nProof.\nmove=> xs x f g Hxin.\ncase_eq (f x) => /=.\n- move=> Hfx.\n  left.\n  rewrite filter_In.\n  by split => //=.\n- move=> Hfx.\n  right.\n  rewrite filter_In.\n  split => //=.\n  rewrite (H x).\n  by rewrite Bool.negb_true_iff.\nQed.\n\nLemma quick_sort_In_ind: forall xs x,\n  (forall xs', length xs' < length xs -> (In x xs' <-> In x (quick_sort xs'))) ->\n  (In x xs <-> In x (quick_sort xs)).\nProof.\nmove=> xs x Hquick_sort_In_length.\nsplit.\n- move=> Hinx.\n  case_eq xs.\n    move=> H.\n    subst.\n    by rewrite quick_sort_nil.\n  move=> x1 xs1 Hxs.\n  rewrite quick_sort_equation.\n  remember (quick_sort (filter (fun x0 : nat => x0 <? x1) xs1)) as left.\n  remember (quick_sort (filter (fun x0 : nat => x1 <=? x0) xs1)) as right.\n  rewrite in_app_iff.\n  suff: x1 = x \\/ In x (left ++ right).\n    rewrite /=.\n    case.\n      by right; left.\n    rewrite in_app_iff.\n    case.\n      by left.\n    by right; right.\n  suff: In x xs -> x1 = x \\/ In x xs1.\n    case.\n    + by [].\n    + by left.\n    + right.\n      rewrite in_app_iff Heqleft Heqright.\n      rewrite -Hquick_sort_In_length.\n      * rewrite -Hquick_sort_In_length.\n        - apply (filter_negb_In xs1 x).\n          + by [].\n          + move=> x'.\n            by apply Nat.leb_antisym.\n        - rewrite Hxs /=.\n          by apply /Lt.le_lt_n_Sm /filter_length.\n      * rewrite Hxs /=.\n        by apply /Lt.le_lt_n_Sm /filter_length.\n  rewrite Hxs /=.\n  case.\n  + by left.\n  + by right.\n- case_eq xs.\n    by rewrite quick_sort_nil.\n  move=> x1 xs1 Hxs.\n  rewrite quick_sort_equation.\n  rewrite in_app_iff.\n  case.\n  + rewrite -Hquick_sort_In_length.\n    * rewrite filter_In /=.\n      case.\n      move=> H _.\n      by right.\n    * rewrite Hxs /=.\n      by apply /Lt.le_lt_n_Sm /filter_length.\n  + rewrite /=.\n    case.\n    * by left.\n    * rewrite -Hquick_sort_In_length.\n      - rewrite filter_In.\n        case.\n        move=> H _.\n        by right.\n      - rewrite Hxs /=.\n        by apply /Lt.le_lt_n_Sm /filter_length.\nQed.\n\nDefinition length_quick_sort_In(l: nat) :=\n  forall xs x, l = length xs -> In x xs <-> In x (quick_sort xs).\n\nLemma quick_sort_In: forall xs x,\n  In x xs <-> In x (quick_sort xs).\nProof.\nmove=> xs x.\napply (lt_wf_ind (length xs) length_quick_sort_In) => //.\nmove=> l.\nrewrite /length_quick_sort_In.\nmove=> Hlength_lt_In xs1 x1 Hxs1_length.\nsubst.\napply quick_sort_In_ind.\nmove=> xs2 Hxs2.\napply (Hlength_lt_In (length xs2)) => //.\nQed.\n\nLemma quick_sort_sorted_length_ind: forall xs,\n  (forall xs', length xs' < length xs -> sorted (quick_sort xs')) ->\n  sorted (quick_sort xs).\nProof.\nmove=> xs Hsorted_quick_sort.\ncase_eq xs. \n  by rewrite quick_sort_nil.\nmove=> x1 xs1 Hxs.\nrewrite quick_sort_equation.\nhave: length xs = S (length xs1).\n  by rewrite Hxs /=.\nmove=> Hxs_length.\nremember (quick_sort (filter (fun x : nat => x1 <=? x) xs1)) as right.\ncase_eq (quick_sort (filter (fun x : nat => x <? x1) xs1)).\n- rewrite /=.\n  split.\n  + rewrite Heqright.\n    move=> x.\n    rewrite -quick_sort_In.\n    rewrite filter_In.\n    case.\n    move=> _.\n    by rewrite Nat.leb_le.\n  + rewrite Heqright.\n    apply Hsorted_quick_sort.\n    rewrite Hxs_length.\n    by apply /Lt.le_lt_n_Sm /filter_length.\n(* (head :: left) ++ x1 :: right *)\n- move=> head left Heqleft.\n  rewrite /=.\n  split.\n  + move=> x.\n    rewrite in_app_iff.\n    case.\n    * move=> Hinx_left.\n      suff: sorted (head :: left).\n        rewrite /=.\n        case.\n        move=> H _.\n        by apply (H x).\n      rewrite -Heqleft.\n      apply Hsorted_quick_sort.\n      rewrite Hxs_length.\n      by apply /Nat.lt_succ_r /filter_length.\n    * move=> Hin_right.\n      have: x1 = x \\/ In x right.\n        move: Hin_right.\n        by rewrite /=.\n      clear Hin_right.\n      have: In head (head :: left) -> head <= x1.\n        rewrite -Heqleft.\n        rewrite -quick_sort_In.\n        rewrite filter_In.\n        case => _.\n        rewrite Nat.ltb_lt.\n        by apply Nat.lt_le_incl.\n      move=> Hhead_le_x1.\n      case.\n      - move=> H; rewrite -H; clear H.\n        apply Hhead_le_x1.\n        apply in_eq.\n      - rewrite Heqright.\n        rewrite -quick_sort_In.\n        rewrite filter_In.\n        case => _.\n        rewrite Nat.leb_le.\n        apply Nat.le_trans.\n        apply Hhead_le_x1.\n        by apply in_eq.\n  + apply sorted_app.\n    * suff: sorted (head :: left).\n        rewrite /=.\n        by case.\n      rewrite -Heqleft.\n      apply: Hsorted_quick_sort.\n      rewrite Hxs_length.\n      by apply /Nat.lt_succ_r /filter_length.\n    * rewrite Heqright.\n      rewrite /sorted -/sorted.\n      split.\n      - move=> x.\n        rewrite -quick_sort_In.\n        rewrite filter_In.\n        case.\n        by rewrite Nat.leb_le.\n      - apply: Hsorted_quick_sort.\n        rewrite Hxs_length.\n        by apply /Nat.lt_succ_r /filter_length.\n    * move=> lx rx Hlx Hrx.\n      move: Nat.le_trans => H.\n      apply (H _ x1 _); clear H.\n      - suff: In lx (head :: left) -> lx <= x1.\n          apply.\n          rewrite /=.\n          by right.\n        rewrite -Heqleft.\n        rewrite -quick_sort_In.\n        rewrite filter_In.\n        case.\n        move=> _.\n        rewrite Nat.ltb_lt.\n        by apply Nat.lt_le_incl.\n      - move: Hrx.\n        rewrite /=.\n        case.\n          move=> H; by rewrite H.\n        rewrite Heqright.\n        rewrite -quick_sort_In.\n        rewrite filter_In.\n        case.\n        move=> _.\n        by rewrite Nat.leb_le.\nQed.\n\nDefinition length_quick_sort_sorted(l: nat) :=\n  forall xs, l = length xs -> sorted (quick_sort xs).\n\nTheorem quick_sort_sorted: forall xs,\n  sorted (quick_sort xs).\nProof.\nmove=> xs.\napply (lt_wf_ind (length xs) length_quick_sort_sorted) => //.\nmove=> len.\nrewrite /length_quick_sort_sorted.\nmove=> Hlength_lt_sorted xs1 Hxs1_length.\nsubst.\napply quick_sort_sorted_length_ind.\nmove=> xs2 Hxs2_length.\napply (Hlength_lt_sorted (length xs2)) => //.\nQed.\n\n\n\nDefinition count_nat := count_occ Nat.eq_dec.\n\n(* count_occを気にせず使いたいので、置き換えるための補題 *)\nLemma count_nat_app: forall (l1 l2: list nat) (n: nat),\n  count_nat (l1 ++ l2) n = count_nat l1 n + count_nat l2 n.\nProof.\nmove=> l1 l2 n.\nby rewrite !/count_nat count_occ_app.\nQed.\nLemma count_nat_cons_eq: forall (l: list nat) (x n: nat),\n  x = n -> count_nat (x :: l) n = S (count_nat l n).\nProof.\nmove=> l x n Hx_eq_n.\nby rewrite !/count_nat count_occ_cons_eq.\nQed.\nLemma count_nat_cons_neq: forall (l: list nat) (x n: nat),\n  x <> n -> count_nat (x :: l) n = count_nat l n.\nProof.\nmove=> l x n Hx_neq_n.\nby rewrite !/count_nat count_occ_cons_neq.\nQed.\n\nLemma filter_negb_count_nat: forall xs f g,\n  (forall x, g x = negb (f x)) ->\n  (forall x, count_nat xs x = count_nat (filter f xs) x + count_nat (filter g xs) x).\nProof.\nmove=> xs f g Hgf n.\ninduction xs => //.\ncase_eq (f a).\n- move=> Hfa_true.\n  rewrite /= Hgf Hfa_true /=.\n  case (Nat.eq_dec a n) => _ //.\n  rewrite Nat.add_succ_l.\n  by apply eq_S.\n- move=> Hfa_false.\n  rewrite /= Hgf Hfa_false /=.\n  case (Nat.eq_dec a n) => _ //.\n  rewrite Nat.add_succ_r.\n  by apply eq_S.\nQed.\n\nLemma quick_sort_count_ind: forall xs,\n  (forall xs', length xs' < length xs ->\n    forall n, count_nat (quick_sort xs') n = count_nat xs' n) ->\n  forall n, count_nat (quick_sort xs) n = count_nat xs n.\nProof.\nmove=> xs Hsorted_count n.\ncase_eq xs.\n  by rewrite quick_sort_nil.\nmove=> x1 xs1 Hxs.\nrewrite quick_sort_equation.\nrewrite count_nat_app.\ncase_eq (x1 =? n).\n- rewrite Nat.eqb_eq => Hx1_eq_n.\n  rewrite count_nat_cons_eq => //.\n  rewrite count_nat_cons_eq => //.\n  rewrite Nat.add_succ_r.\n  apply eq_S.\n  have: forall fg, length (filter fg xs1) < length xs.\n    move=> fg.\n    rewrite Hxs /=.\n    rewrite Nat.lt_succ_r.\n    apply filter_length.\n  move=> Hfilter_length.\n  rewrite Hsorted_count => //.\n  rewrite Hsorted_count => //.\n  rewrite -filter_negb_count_nat => //.\n  move=> x.\n  by apply Nat.leb_antisym.\n- rewrite Nat.eqb_neq => Hx1_neq_n.\n  rewrite count_nat_cons_neq => //.\n  rewrite count_nat_cons_neq => //.\n  have: forall fg, length (filter fg xs1) < length xs.\n    move=> fg.\n    rewrite Hxs /=.\n    rewrite Nat.lt_succ_r.\n    apply filter_length.\n  move=> Hfilter_length.\n  rewrite Hsorted_count => //.\n  rewrite Hsorted_count => //.\n  rewrite -filter_negb_count_nat => //.\n  move=> x.\n  by apply Nat.leb_antisym.\nQed.\n\nDefinition length_quick_sort_count(l: nat) :=\n  forall xs, l = length xs -> forall n, count_nat (quick_sort xs) n = count_nat xs n.\n\nLemma quick_sort_count: forall xs,\n  forall n, count_nat (quick_sort xs) n = count_nat xs n.\nProof.\nmove=> xs n.\napply (lt_wf_ind (length xs) length_quick_sort_count) => // len.\nrewrite /length_quick_sort_count => Hlength_lt_sort_count xs1 Hxs1_length.\nsubst.\napply quick_sort_count_ind => xs2 Hxs2_length.\napply (Hlength_lt_sort_count (length xs2)) => //.\nQed.\n\nDefinition sort_algorithm (alg: list nat -> list nat) :=\n  forall xs, sorted (alg xs) /\\ forall n, count_nat (alg xs) n = count_nat xs n.\n\n(*\n  ということできちんとクイックソートがソートアルゴリズムであることが証明できました。\n  これで安心してクイックソートを使えます！\n*)\nTheorem quick_sort_is_sort_algorithm: sort_algorithm quick_sort.\nProof.\nrewrite /sort_algorithm => xs.\nsplit.\n- by apply quick_sort_sorted.\n- by apply quick_sort_count.\nQed.\n\nEnd Sort.\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "soukouki", "repo": "coq-quick_sort", "sha": "1032514af6516fa64756359a0c2bd90dd56f9cf4", "save_path": "github-repos/coq/soukouki-coq-quick_sort", "path": "github-repos/coq/soukouki-coq-quick_sort/coq-quick_sort-1032514af6516fa64756359a0c2bd90dd56f9cf4/sort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7198009982702783}}
{"text": "\n(* The Word module should use the same definitions as CompCert.\n   There is a functor that can be instantiated for the targeted word size.\n   https://github.com/artart78/coq-bits/blob/master/test/integers.v\n   See, e.g., the module Int64 defined in that file.\n   If more flexibility on the word size is needed, e.g., to make all\n   definitions parameteric in the word size, then let's discuss.\n   For the moment, I won't touch your current Word module. *)\n\n\nRequire Import Arith.PeanoNat.\nRequire Import Lia.\nRequire Import ProofIrrelevance.\n\nInductive word (size : nat) : Type :=\n| Word : forall n : nat, n < 2 ^ size -> word size.\n\nDefinition word_equality (s : nat) (w x : word s) : bool :=\n  match w, x with\n      | Word _ m _, Word _ n _ => EqNat.beq_nat m n\n  end.\n\nLemma word_eq_succ : forall (n0 n1 size : nat) (H0 : n0 < 2 ^ size) (H1 : n1 < 2 ^ size) (P0 : (S n0) < 2 ^ size) (P1 : (S n1) < 2 ^ size),\n    Word size n0 H0 = Word size n1 H1 -> Word size (S n0) P0 = Word size (S n1) P1.\nProof.\n  intros; generalize dependent P0; generalize dependent P1.\n  inversion H.\n  induction n0; destruct n1; try(inversion H3);intros;\n    assert (P0 = P1) as P by apply proof_irrelevance; rewrite P; reflexivity.  Qed.\n\nLemma word_neq_nat_neq : forall m n s P Q, Word s m P <> Word s n Q -> m <> n.\nProof.\n  induction m; destruct n; intros; try(discriminate).\n  - assert (P = Q) by (apply proof_irrelevance; assumption).\n    contradiction H. rewrite H0. reflexivity.\n  - intro Cont; destruct Cont.\n    assert (P = Q) by (apply proof_irrelevance; assumption). rewrite H0 in H. contradiction. Qed.\n\nLemma word_neq_succ : forall (n0 n1 size : nat) (H0 : n0 < 2 ^ size) (H1 : n1 < 2 ^ size) (P0 : (S n0) < 2 ^ size) (P1 : (S n1) < 2 ^ size),\n    Word size n0 H0 <> Word size n1 H1 -> Word size (S n0) P0 <> Word size (S n1) P1.\nProof.\n  induction n0; destruct n1; intros; try(discriminate).\n  assert (H': H0 = H1) by apply proof_irrelevance; rewrite H' in H. contradiction.\n  intros Con. inversion Con. apply word_neq_nat_neq in H.\n  apply H. apply f_equal. assumption.  Qed.\n\nTheorem word_eq_dec : forall (n : nat) (w1 w2 : word n), {w1 = w2} + {w1 <> w2}.\n  intros size [n0 P0].\n  induction n0; intros [n1 P1]; destruct n1; try(right; discriminate).\n    + left. assert (P0 = P1) by apply proof_irrelevance. rewrite H. reflexivity.\n    + assert (n0 < 2 ^ size) by (apply Nat.lt_succ_l;assumption).\n      assert (n1 < 2 ^ size) by (apply Nat.lt_succ_l;assumption).\n      assert ({Word size n0 H = Word size n1 H0} + {Word size n0 H <> Word size n1 H0}) by apply IHn0.\n      inversion H1.\n      * left. apply word_eq_succ with H H0. assumption.\n      * right. apply word_neq_succ with H H0. assumption.  Qed.\n\nLemma lem0 : forall (m n p: nat), m < 2^p -> n < 2^p -> (m + n) mod (2 ^ p) < (2 ^ p) .\nProof.\n  intros.\n  apply Nat.mod_upper_bound.\n  apply Nat.pow_nonzero.\n  discriminate.\nQed.\n\nDefinition word_add (size : nat) (w1 w2 : word size) : word size :=\n  match w1, w2 with\n  | Word _ n1 P1, Word _ n2 P2 => Word size ((n1 + n2) mod 2 ^ size)\n                                      (lem0 n1 n2 size P1 P2)\n  end.\n\nFixpoint nat_sub_underflow (under : nat) (n m : nat) :=\n  match n, m with\n  | _, 0 => n\n  | 0, S m' => nat_sub_underflow under under m'\n  | S n', S m' => nat_sub_underflow under n' m'\n  end.\n\nLemma lem4 : forall (m n p : nat), m < 2^p -> n < 2 ^ p ->\n    nat_sub_underflow (2^p - 1) m n < (2^p).\nProof.\n  intros m n p P Q.\n  generalize dependent m.\n  induction n; destruct m; auto; intros; simpl.\n  - apply IHn.\n    + apply (Nat.lt_trans n (S n) (2^p)) in Q.\n      * assumption.\n      * apply Nat.lt_succ_diag_r.\n    + rewrite Nat.sub_succ_r.\n      rewrite Nat.sub_0_r.\n      apply Lt.lt_pred_n_n.\n      assumption.\n  - intros.\n    apply IHn.\n    + apply (Nat.lt_trans n (S n) (2^p)) in Q.\n      * assumption.\n      * apply Nat.lt_succ_diag_r.\n    + apply (Nat.lt_trans m (S m) (2^p)) in P.\n      * assumption.\n      * apply Nat.lt_succ_diag_r.  Qed.\n\nDefinition word_sub (size : nat) (w1 w2 : word size) : word size :=\n  match w1, w2 with\n  | Word _ n1 P1, Word _ n2 P2 => Word size (nat_sub_underflow (2^size - 1) n1 n2)\n                                     (lem4 n1 n2 size P1 P2)\n  end.\n\nLemma bitwise_max_lem : forall (m n p : nat) (op : bool -> bool -> bool), m <= 2^p - 1 -> n <= 2^p - 1 ->\n    (Nat.bitwise op p m n) <= 2^p - 1.\nProof.\n  intros m n p. generalize dependent n.\n  generalize dependent m. induction p; intros; auto.\n  intros. simpl.\n    assert (forall x y, x <= 2 ^ S y - 1 -> Nat.div2 x <= 2 ^ y - 1). {\n      intros.\n      destruct (Nat.Even_or_Odd x).\n      * inversion H2. rewrite H3.\n        rewrite Nat.div2_double.\n        rewrite H3 in H1.\n        assert (0 < 2) by lia.\n        apply (Nat.mul_le_mono_pos_l _ _ 2 H4).\n        rewrite  Nat.mul_sub_distr_l.\n        rewrite <- H3.\n        simpl (2 * 1).\n        inversion H1.\n        lia.\n        lia.\n\n      * inversion H2. rewrite H3.\n        rewrite (Nat.add_comm).\n        rewrite Nat.div2_succ_double.\n        rewrite H3 in H1.\n        inversion H1.\n        lia.\n        lia.\n    }\n    apply H1 in H.\n    apply H1 in H0.\n    apply (IHp _ _ op H) in H0.\n    apply (Nat.mul_le_mono_pos_l _ _ 2) in H0.\n    rewrite  Nat.mul_sub_distr_l in H0.\n    simpl in *.\n    destruct (op (Nat.odd m) (Nat.odd n)).\n    simpl.\n    apply le_n_S in H0.\n    repeat rewrite (Nat.add_comm _ 0) in *.\n    simpl in *.\n    assert (forall x, S (2 ^ x + 2 ^ x - 2) = (2 ^ x + 2 ^ x - 1)). {\n      intros.\n      assert (2 <= 2 ^ x + 2 ^ x) by\n          (induction x; simpl; lia).\n      rewrite <- (Nat.sub_succ_l _ _ H2).\n      reflexivity.\n    }\n    rewrite H2 in H0.\n    apply H0.\n    simpl.\n    apply le_S in H0.\n    repeat rewrite (Nat.add_comm _ 0) in *.\n    simpl in *.\n    assert (forall x, S (2 ^ x + 2 ^ x - 2) = (2 ^ x + 2 ^ x - 1)). {\n      intros.\n      assert (2 <= 2 ^ x + 2 ^ x) by\n          (induction x; simpl; lia).\n      rewrite <- (Nat.sub_succ_l _ _ H2).\n      reflexivity.\n    }\n    rewrite H2 in H0.\n    apply H0. lia.\nQed.\n\nTheorem bitwise_max : forall (m n p : nat) (op : bool -> bool -> bool), m < 2^p -> n < 2^p ->\n    (Nat.bitwise op p m n) < 2^p.\n  intros.\n  assert (2 ^ p = S ( 2 ^ p - 1)) by lia.\n  rewrite H1 in *.\n  apply Lt.le_lt_n_Sm.\n  apply Lt.lt_n_Sm_le in H.\n  apply Lt.lt_n_Sm_le in H0.\n  apply bitwise_max_lem; assumption. Qed.\n\nDefinition word_and (size : nat) (w1 w2 : word size) : word size :=\n  match w1, w2 with\n  | Word _ n1 P1, Word _ n2 P2 => Word size (Nat.bitwise andb size n1 n2)\n                                      (bitwise_max n1 n2 size andb P1 P2)\n  end.\n\nDefinition word_or (size : nat) (w1 w2 : word size) : word size :=\n  match w1, w2 with\n  | Word _ n1 P1, Word _ n2 P2 => Word _ (Nat.bitwise orb size n1 n2)\n                                      (bitwise_max n1 n2 size orb P1 P2)\n  end.\n\nDefinition word_xor (size : nat) (w1 w2 : word size) : word size :=\n  match w1, w2 with\n  | Word _ n1 P1, Word _ n2 P2 => Word _ (Nat.bitwise xorb size n1 n2)\n                                      (bitwise_max n1 n2 size xorb P1 P2)\n  end.\n\nLemma Oneq : forall s n, n mod 2 ^ s < 2 ^ s.\nProof. intros. apply Nat.mod_upper_bound. apply Nat.pow_nonzero. discriminate.  Qed.\n\nDefinition word_to_nat (s : nat) (w : word s) : nat :=\n  match w with | Word _ n _ => n end.\n\nDefinition nat_to_word (s n : nat) : word s :=\n  Word s (n mod 2 ^ s) (Oneq s n).\n", "meta": {"author": "ku-sldg", "repo": "cakeml-coq", "sha": "46256bebe3e151a75956e379d236c44f58e255de", "save_path": "github-repos/coq/ku-sldg-cakeml-coq", "path": "github-repos/coq/ku-sldg-cakeml-coq/cakeml-coq-46256bebe3e151a75956e379d236c44f58e255de/cakeSemantics/Word.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7197925302165973}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nLemma lem: forall l n, cons n (rev l) = rev (append l (cons n nil)).\nProof.\nintros. induction l.\n  - simpl. rewrite <- IHl. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem2: forall l, rev (rev l) = l.\nProof.\ninduction l.\n  - simpl. rewrite <- lem. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Lst) (y : Lst), eq (append (rev (rev x)) y) (rev (rev (append x y))).\nProof.\n  intros. rewrite lem2. rewrite lem2. reflexivity.\nQed.\n\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal19.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7197925261258213}}
{"text": "Require Import Coq.Reals.Reals.\nRequire Import Coq.Logic.Classical_Prop.\nRequire Import Coq.omega.Omega.\nRequire Export LibTactics.\n\nInductive point : Type := Point (x y : R).\n\nDefinition region : Type := point -> Prop.\n\nDefinition map : Type := point -> region.\n\nInductive interval : Type := Interval (x y : R).\n\nInductive rectangle : Type := Rectangle (hspan vspan : interval).\n\nDefinition in_interval (s : interval) : R -> Prop :=\n  fun t => let ' Interval x y := s in (x < t)%R /\\ (t < y)%R.\n\nDefinition in_rectangle rr : region :=\n  fun z => let ' Rectangle hspan vspan := rr in let ' Point x y := z in\n  in_interval hspan x /\\ in_interval vspan y.\n\n(* Elementary set theory for the plane. *)\n\nDefinition union (r1 r2 : region) : region := fun z => r1 z \\/ r2 z.\n\nDefinition intersect (r1 r2 : region) : region := fun z => r1 z /\\ r2 z.\n\nDefinition nonempty (r : region) : Prop := exists z : point, r z.\n\nDefinition subregion (r1 r2 : region) : Prop := forall z : point, r1 z -> r2 z.\n\nLemma intersect_symm (r1 r2 : region) (z : point) :\n  intersect r1 r2 z <-> intersect r2 r1 z.\nProof. split; intros [? ?]; split; auto. Qed.\n\nLemma subregion_refl (r : region) :\n  subregion r r.\nProof. red. auto. Qed.\n\nLemma subregion_trans (r1 r2 r3 : region) :\n  subregion r1 r2 -> subregion r2 r3 -> subregion r1 r3.\nProof.\n  unfold subregion. intros. auto. Qed.\n\nDefinition meet (r1 r2 : region) : Prop := nonempty (intersect r1 r2).\n\nLemma meet_symm (r1 r2 : region) :\n  meet r1 r2 -> meet r2 r1.\nProof. intros [? [? ?]]. exists x; split; auto. Qed.\n\nLemma meet_subregion (u1 u2 r : region) :\n  meet u1 r -> subregion u1 u2 -> meet u2 r.\nProof.\n  unfold meet, nonempty, intersect. intros [? [? ?]] ?.\n  exists x. split; auto.\nQed.\n\nHint Resolve subregion_refl subregion_trans meet_subregion.\n\n(* Maps are represented as relations; proper map are partial equivalence  *)\n(* relations (PERs).                                                      *)\n\nRecord plain_map (m : map) : Prop := PlainMap {\n  map_symm z1 z2 : m z1 z2 -> m z2 z1;\n  map_trans z1 z2 z3 : m z1 z2 -> m z2 z3 -> m z1 z3\n}.\n\n(*\nAxiom plain_map_unique_point :\n  forall (m : map) (z1 z2 : point), plain_map m -> m z1 z2 -> z1 = z2.\n*)\n\nLemma map_symm_trans_ll (m : map) (z1 z2 z3 : point) :\n  plain_map m -> m z1 z2 -> m z1 z3 -> m z2 z3.\nProof. intros. apply map_trans with z1; auto. apply map_symm; auto. Qed.\n\nLemma map_symm_trans_rr (m : map) (z1 z2 z3 : point) :\n  plain_map m -> m z1 z2 -> m z3 z2 -> m z1 z3.\nProof. intros. apply map_trans with z2; auto. apply map_symm; auto. Qed.\n\nLemma map_covered_left (m : map) (z1 z2 : point) :\n  plain_map m -> m z1 z2 -> m z1 z1.\nProof.\n  intros. assert (m z2 z1) by (apply map_symm; auto).\n  apply map_trans with z2; auto. Qed.\n\nLemma map_covered_right (m : map) (z1 z2 : point) :\n  plain_map m -> m z1 z2 -> m z2 z2.\nProof.\n  intros. assert (m z2 z1) by (apply map_symm; auto).\n  apply map_trans with z1; auto. Qed.\n\n(* sum of all the regions in map (set of all the points defined on map) *)\nDefinition cover (m : map) : region := fun z => m z z.\n\nDefinition submap (m1 m2 : map) : Prop := forall z, subregion (m1 z) (m2 z).\n\nLemma submap_refl (m : map) :\n  submap m m.\nProof. unfold submap. auto. Qed.\n\nLemma submap_trans (m1 m2 m3 : map) :\n  submap m1 m2 -> submap m2 m3 -> submap m1 m3.\nProof.\n  unfold submap. intros.\n  eapply subregion_trans; auto.\nQed.\n\n(* There are at most n regions in m. *)\nDefinition at_most_regions (n : nat) (m : map) :=\n  exists f, forall z, cover m z -> exists2 i : nat, Peano.lt i n & m (f i) z.\n\n(* Elementary topology. *)\n\nDefinition open (r : region) : Prop :=\n  forall z, r z -> exists2 u, in_rectangle u z & subregion (in_rectangle u) r.\n\nDefinition closure (r : region) : region :=\n  fun z => forall u, open u -> u z -> meet r u.\n\nLemma closure_supregion (m : map) (z : point) :\n  m z z -> closure (m z) z.\nProof with auto.\n  red. intros. exists z... split...\nQed.\n\nLemma closure_preserves_subregion (r1 r2 : region) :\n  subregion r1 r2 -> subregion (closure r1) (closure r2).\nProof with auto.\n  unfold subregion, closure. intros. destruct (H0 u) as [x [? ?]]...\n  exists x. split...\nQed.\n\nDefinition connected (r : region) : Prop :=\n  forall u v, open u -> open v -> subregion r (union u v) ->\n  meet u r -> meet v r -> meet u v.\n\nRecord simple_map (m : map) : Prop := SimpleMap {\n  simple_map_plain : plain_map m;\n  simple_map_open z : open (m z);\n  simple_map_connected z : connected (m z)\n}.\n\nRecord finite_simple_map (m : map) : Prop := FiniteSimpleMap {\n  finite_simple_map_simple : simple_map m;\n  finite_simple_map_finite : exists n, at_most_regions n m\n}.\n\nHint Resolve simple_map_plain.\n\nLemma closure_map (m : map) (z z' : point) :\n  simple_map m -> closure (m z) z' -> m z z' \\/ ~ m z' z'.\nProof.\n  intros. repeat red in H0. destruct H.\n  assert (m z' z' -> exists z0 : point, intersect (m z) (m z') z0) by auto.\n  apply imply_to_or in H.\n  destruct H; auto.\n  left. inversion H; inversion H1.\n  apply map_trans with x; auto.\n  apply map_symm; auto.\nQed.\n\nLemma closure_map_trans (m : map) (z1 z2 z : point) :\n  plain_map m -> m z1 z2 -> closure (m z1) z -> closure (m z2) z.\nProof with auto.\n  unfold closure, meet. intros.\n  assert (nonempty (intersect (m z1) u)) by auto.\n  destruct H4. destruct H4. exists x. split; auto.\n  apply map_trans with z1... apply map_symm...\nQed.\n\n(* Borders, corners, adjacency and coloring. *)\n\nDefinition border (m : map) (z1 z2 : point) : region :=\n  intersect (closure (m z1)) (closure (m z2)).\n\nDefinition corner_map (m : map) (z : point) : map :=\n  fun z1 z2 => open (m z1) /\\ m z1 z2 /\\ closure (m z1) z.\n\n(* a point is not a corner of a map iff it doesn't belong to the closure of\n*  more than 2 regions. *)\nDefinition not_corner (m : map) : region :=\n  fun z => at_most_regions 2 (corner_map m z).\n\nLemma not_corner_correct (m : map) (z1 z2 z3 z : point) :\n  simple_map m -> not_corner m z ->\n  m z1 z1 /\\ closure (m z1) z ->\n  m z2 z2 /\\ closure (m z2) z ->\n  m z3 z3 /\\ closure (m z3) z ->\n  m z1 z2 \\/ m z2 z3 \\/ m z3 z1.\nProof with auto.\n  intros. repeat red in H0. destruct H0 as [f ?].\n  assert (open (m z1) /\\ m z1 z1 /\\ closure (m z1) z) by (split; auto; apply simple_map_open; auto).\n  assert (open (m z2) /\\ m z2 z2 /\\ closure (m z2) z) by (split; auto; apply simple_map_open; auto).\n  assert (open (m z3) /\\ m z3 z3 /\\ closure (m z3) z) by (split; auto; apply simple_map_open; auto).\n  clear H1 H2 H3; rename H4 into H1; rename H5 into H2; rename H6 into H3.\n  apply (H0 z1) in H1. destruct H1 as [i ?]. destruct H4 as [? [? ?]].\n  apply (H0 z2) in H2. destruct H2 as [j ?]. destruct H7 as [? [? ?]].\n  apply (H0 z3) in H3. destruct H3 as [k ?]. destruct H10 as [? [? ?]].\n  assert (i = 0 \\/ i = 1) by omega.\n  assert (j = 0 \\/ j = 1) by omega.\n  assert (k = 0 \\/ k = 1) by omega.\n  clear H1 H2 H3.\n  destruct H13; subst.\n  - destruct H14; subst.\n    + left. apply map_trans with (f 0)... apply map_symm...\n    + right. destruct H15; subst.\n      { right. apply map_symm_trans_ll with (f 0)... }\n      { left. apply map_symm_trans_ll with (f 1)... }\n  - destruct H14; subst.\n    + right. destruct H15; subst.\n      { left. apply map_symm_trans_ll with (f 0)... }\n      { right. apply map_symm_trans_ll with (f 1)... }\n    + left. apply map_symm_trans_ll with (f 1)...\nQed.\n\nRecord adjacent (m : map) (z1 z2 : point) : Prop := Adjacent {\n  adjacent_cover_left : m z1 z1;\n  adjacent_cover_right : m z2 z2;\n  adjacent_not_same_face : ~ m z1 z2;\n  adjacent_meet : meet (not_corner m) (border m z1 z2)\n}.\n\nDefinition inter_region (m : map) (z1 z2 : point) : region :=\n  fun z => ~ m z1 z2 /\\ intersect (not_corner m) (border m z1 z2) z.\n\nLemma border_symm (m : map) (z1 z2 z : point) :\n  border m z1 z2 z <-> border m z2 z1 z.\nProof. split; unfold border; apply intersect_symm. Qed.\n\nLemma inter_region_symm (m : map) (z1 z2 z : point) :\n  simple_map m ->\n  inter_region m z1 z2 z <-> inter_region m z2 z1 z.\nProof with auto.\n  split; unfold inter_region; intros [? [? ?]]; split.\n  - intros F; apply H0; apply map_symm...\n  - split... apply border_symm...\n  - intros F; apply H0; apply map_symm...\n  - split... apply border_symm...\nQed.\n\nHint Resolve border_symm inter_region_symm.\n\nLemma border_not_covered (m : map) (z1 z2 z : point) :\n  simple_map m -> ~ m z1 z2 -> border m z1 z2 z -> ~ m z z.\nProof with auto.\n  intros ? ? [? ?] ?.\n  apply H0. apply map_trans with z.\n  - inversion H...\n  - destruct (closure_map _ _ _ H H1)...\n    apply H4 in H3. inversion H3.\n  - destruct (closure_map _ _ _ H H2).\n    + apply map_symm...\n    + apply H4 in H3. inversion H3.\nQed.\n\nLemma inter_region_deterministic (m : map) (z z1 z2 z3 z4 : point) :\n  simple_map m ->\n  m z1 z1 -> m z2 z2 -> m z3 z3 -> m z4 z4 ->\n  inter_region m z1 z2 z -> inter_region m z3 z4 z ->\n  (m z1 z3 /\\ m z2 z4) \\/ (m z1 z4 /\\ m z2 z3).\nProof with auto.\n  unfold inter_region. intros ? ? ? ? ? [? [? [? ?]]] [? [_ [? ?]]].\n  assert (m z1 z2 \\/ m z2 z3 \\/ m z3 z1) by (apply not_corner_correct with z; auto).\n  destruct H11.\n  - contradiction.\n  - destruct H11.\n    + right; split...\n      assert (m z1 z3 \\/ m z3 z4 \\/ m z4 z1) by (apply not_corner_correct with z; auto).\n      destruct H12.\n      { exfalso. apply H4; apply map_symm_trans_rr with z3... }\n      { destruct H12. contradiction. apply map_symm... }\n    + left. split; apply map_symm...\n      assert (m z2 z3 \\/ m z3 z4 \\/ m z4 z2) by (apply not_corner_correct with z; auto).\n      destruct H12.\n      { exfalso. apply H4; apply map_trans with z3; auto; apply map_symm... }\n      { destruct H12. contradiction. auto. }\nQed.\n\nRecord coloring (m k : map) : Prop := Coloring {\n  coloring_plain : plain_map k;\n  coloring_cover : subregion (cover m) (cover k);\n  coloring_consistent : submap m k;\n  coloring_adjacent z1 z2 : adjacent m z1 z2 -> ~ k z1 z2\n}.\n\nDefinition colorable_with (n : nat) (m : map) : Prop :=\n  exists2 k, coloring m k & at_most_regions n k.\n\n(* TODO: add a restriction so that each region of m should be convex *)\nDefinition totalize (m : map) : map :=\n  fun z z' =>\n    (* もともとm上の点である *)\n    m z z' \\/\n    (* z1, z2を含むregionの間にある点 *)\n    (exists z1 z2 : point,\n      m z1 z1 /\\ m z2 z2 /\\ ~ m z1 z2 /\\\n      intersect (border m z1 z2) (not_corner m) z /\\\n      intersect (border m z1 z2) (not_corner m) z').\n\nLemma totalize_symm (m : map) (z1 z2 : point) :\n  simple_map m -> totalize m z1 z2 -> totalize m z2 z1.\nProof.\n  unfold totalize. intros. destruct H0.\n  - left. apply map_symm; auto.\n  - destruct H0 as [z3 [z4 [? [? [? [[? ?] [? ?]]]]]]].\n    right. exists z3, z4.\n    repeat (split; auto).\nQed.\n\nLemma totalize_trans (m : map) (z1 z2 z3 : point) :\n  simple_map m -> totalize m z1 z2 -> totalize m z2 z3 -> totalize m z1 z3.\nProof with auto.\n  intros. destruct H0.\n  - destruct H1.\n    + left. apply map_trans with z2...\n    + destruct H1 as [z4 [z5 [? [? [? [[? ?] [? ?]]]]]]].\n      apply border_not_covered in H4...\n      apply map_covered_right in H0... contradiction.\n  - destruct H0 as [z4 [z5 [? [? [? [[? ?] [? ?]]]]]]].\n    destruct H1.\n    + apply border_not_covered in H6...\n      apply map_covered_left in H1... contradiction.\n    + destruct H1 as [z6 [z7 [? [? [? [[? ?] [? ?]]]]]]].\n      assert (m z4 z6 /\\ m z5 z7 \\/ m z4 z7 /\\ m z5 z6).\n      { apply inter_region_deterministic with z2; auto; split; auto; split; auto. }\n      destruct H14; destruct H14.\n      { right. exists z4, z5. destruct H12. repeat (split; auto).\n        - apply closure_map_trans with z6... apply map_symm...\n        - apply closure_map_trans with z7... apply map_symm... }\n      { right. exists z4, z5. destruct H12. repeat (split; auto).\n        - apply closure_map_trans with z7... apply map_symm...\n        - apply closure_map_trans with z6... apply map_symm... }\nQed.\n\nLemma totalize_subregion (m : map) (z : point) :\n  subregion (m z) (totalize m z).\nProof.\n  red; intros; left; auto. Qed.\n\nLemma totalize_plain_map (m : map) :\n  simple_map m -> plain_map (totalize m).\nProof with auto.\n  intros. inversion H. split; intros.\n  - apply totalize_symm...\n  - red. intros. apply totalize_trans with z3...\n    apply totalize_trans with z2... apply totalize_trans with z2...\n    apply totalize_symm...\nQed.\n\nLemma plain_map_totalize (m : map) (z z' : point) :\n  simple_map m -> m z z' -> totalize m z z'.\nProof.\n  intros. red. auto.\nQed.\n\nLemma totalize_cover_subregion (m : map) :\n  simple_map m -> subregion (cover m) (cover (totalize m)).\nProof.\n  unfold subregion, cover. intros. apply plain_map_totalize; auto.\nQed.\n\nLemma totalize_open (m : map) (z1 z2 : point) :\n  simple_map m ->\n  totalize m z1 z2 -> open (totalize m z1) -> m z1 z2.\nProof with auto.\n  intros. inversion H0...\n  exfalso.\n  destruct H2 as [z3 [z4 [? [? [? [[? ?] [? ?]]]]]]].\n  destruct (H1 z2) as [u ?]...\n  assert (totalize m z1 z3).\n  { destruct H7.\n    assert (meet (m z3) (in_rectangle u)).\n    { apply H7... red. intros. exists u... }\n    destruct H12 as [z5 [? ?]].\n    assert (totalize m z1 z5)...\n    apply totalize_trans with z5... left. apply map_symm... }\n  assert (totalize m z1 z4).\n  { destruct H7.\n    assert (meet (m z4) (in_rectangle u)).\n    { apply H12... red. intros. exists u... }\n    destruct H13 as [z5 [? ?]].\n    assert (totalize m z1 z5)...\n    apply totalize_trans with z5... left; apply map_symm... }\n  assert (totalize m z3 z4).\n  { apply totalize_trans with z1... apply totalize_symm... }\n  destruct H13.\n  - contradiction.\n  - destruct H13 as [z5 [z6 [? [? [? [[? ?] _]]]]]].\n    apply border_not_covered in H16...\nQed.\n\nLemma totalize_preserves_corner_map (m : map) (x z1 z2 : point) :\n  simple_map m -> corner_map m x z1 z2 <-> corner_map (totalize m) x z1 z2.\nProof with auto.\n  split; unfold corner_map; intros [? [? ?]].\n  - splits.\n    + red. intros. destruct H3.\n      { destruct (H0 z)... exists x0...\n        apply subregion_trans with (m z1)...\n        apply totalize_subregion. }\n      { exfalso.\n        destruct H3 as [z3 [z4 [_ [_ [? [? ?]]]]]].\n        destruct H4.\n        apply border_not_covered in H4...\n        apply H4. apply map_covered_left in H1... }\n    + left...\n    + repeat red. intros.\n      repeat red in H2. destruct (H2 u) as [z ?]...\n      exists z. destruct H5. split... left...\n  - splits.\n    + red. intros. unfold open in H0. destruct (H0 z) as [u ?]... left...\n      exists u... unfold subregion in H5.\n      red; intros.\n      destruct (H5 z0)...\n      exfalso. destruct H7 as [z3 [z4 [_ [_ [? [[? ?] _]]]]]].\n      apply border_not_covered in H8...\n      apply H8. apply map_covered_left in H3...\n    + apply totalize_open...\n    + repeat red. intros.\n      destruct (H2 u) as [z ?]... exists z... destruct H5. split...\n      apply totalize_open...\nQed.\n\nLemma totalize_preserves_not_corner (m : map) (x : point) :\n  simple_map m -> not_corner m x -> not_corner (totalize m) x.\nProof.\n  unfold not_corner, at_most_regions. intros.\n  destruct H0 as [f ?]. exists f. intros.\n  assert (exists2 i : nat, i < 2 & corner_map m x (f i) z).\n  { apply H0. apply totalize_preserves_corner_map; auto. }\n  destruct H2 as [i ?].\n  exists i; auto. rewrite <- totalize_preserves_corner_map; auto.\nQed.\n\nRecord tcoloring (m k : map) : Prop := TColoring {\n  tcoloring_coloring : coloring (totalize m) k;\n  tcoloring_adjacent z :\n    forall z1 z2 : point,\n    adjacent (totalize m) z z1 -> adjacent (totalize m) z z2 -> ~ k z1 z2\n}.\n\nDefinition tcolorable_with (n : nat) (m : map) : Prop :=\n  exists2 k, tcoloring m k & at_most_regions n k.\n\nLemma tcoloring_is_coloring :\n  forall m k : map, simple_map m -> tcoloring m k -> coloring m k.\nProof with auto.\n  intros. destruct H0. destruct tcoloring_coloring0.\n  split...\n  - apply subregion_trans with (cover (totalize m))...\n    apply totalize_cover_subregion...\n  - apply submap_trans with (totalize m)...\n    repeat red...\n  - (* any adjacent two faces in m are colored differently *)\n    intros z1 z2 [? ? ? [? [? ?]]].\n    assert (~ m x x). { apply border_not_covered with z1 z2... }\n    apply tcoloring_adjacent0 with x.\n    + (* adjacent (totalize m) x z1 *)\n      split.\n      { right. exists z1, z2. repeat (split; auto). }\n      { left... }\n      { (* ~ totalize m x z1 *)\n        intros F. destruct F.\n        - (* m x z1 を仮定する場合 *)\n          apply map_covered_left in H3...\n        - (* z1が境界上にあることを仮定する場合 *)\n          destruct H3 as [z3 [z4 [? [? [? [? ?]]]]]].\n          destruct H7. apply border_not_covered in H7... }\n      { (* meet (not_corner (totalize m)) (border (totalize m) x z1) *)\n        exists x. split.\n        - apply totalize_preserves_not_corner...\n        - split.\n          + apply closure_supregion... right.\n            exists z1, z2... destruct H1. repeat split...\n          + destruct H1.\n            cut (subregion (closure (m z1)) (closure (totalize m z1)))...\n            apply closure_preserves_subregion. apply totalize_subregion. }\n    + (* same as previous one! *)\n      split.\n      { right. exists z1, z2. repeat (split; auto). }\n      { left... } { unfold totalize. intros F. destruct F.\n        - apply map_covered_left in H3...\n        - destruct H3 as [z3 [z4 [? [? [? [? ?]]]]]].\n          destruct H7. apply border_not_covered in H7... }\n      { exists x. split.\n        - apply totalize_preserves_not_corner...\n        - split.\n          + apply closure_supregion... right.\n            exists z1, z2... destruct H1. repeat split...\n          + destruct H1.\n            cut (subregion (closure (m z2)) (closure (totalize m z2)))...\n            apply closure_preserves_subregion. apply totalize_subregion. }\nQed.\n\nTheorem coloring_leq_tcoloring (m : map) (n : nat) :\n  simple_map m -> tcolorable_with n m -> colorable_with n m.\nProof with auto.\n  intros H [k H0 H1]. exists k... apply tcoloring_is_coloring...\nQed.\n\nRecord incident (m : map) (z1 z2 : point) : Prop := Incident {\n  incident_not_same_edge : ~ totalize m z1 z2;\n  incident_common_adjacent : exists z, adjacent (totalize m) z z1 /\\ adjacent (totalize m) z z2\n}.\n\nDefinition edge (m : map) : map :=\n  fun z z' =>\n    (* z1, z2を含むregionの間にある点 *)\n    (exists z1 z2 : point,\n      m z1 z1 /\\ m z2 z2 /\\ ~ m z1 z2 /\\\n      intersect (border m z1 z2) (not_corner m) z /\\\n      intersect (border m z1 z2) (not_corner m) z').\n\nRecord ecoloring (m k : map) : Prop := EColoring {\n  ecoloring_plain : plain_map k;\n  ecoloring_cover : subregion (cover (edge m)) (cover k);\n  ecoloring_consistent : submap (edge m) k;\n  ecoloring_incident z1 z2 :\n    incident m z1 z2 -> ~ k z1 z2\n}.\n\nDefinition ecolorable_with (n : nat) (m : map) : Prop :=\n  exists2 k, ecoloring m k & at_most_regions n k.\n\nTheorem tcoloring_is_ecoloring (m k : map) :\n  simple_map m -> tcoloring m k -> ecoloring m k.\nProof with auto.\n  intros. inversion H0. split.\n  - apply coloring_plain with m... apply tcoloring_is_coloring...\n  - destruct tcoloring_coloring0. apply subregion_trans with (cover (totalize m))...\n    red. intros. repeat red. right...\n  - destruct tcoloring_coloring0. apply submap_trans with (totalize m)...\n    repeat red. intros. right...\n  - intros. destruct H1. destruct incident_common_adjacent0 as [z [? ?]].\n    eapply tcoloring_adjacent0 with z...\nQed.\n\nTheorem ecoloring_leq_tcoloring (m : map) (n : nat) :\n  simple_map m -> tcolorable_with n m -> ecolorable_with n m.\nProof with auto.\n  intros ? [k ? ?]. exists k... apply tcoloring_is_ecoloring...\nQed.\n\nTheorem tcoloring_leq_coloring_and_ecoloring (m : map) (n n' : nat) :\n  colorable_with n m -> ecolorable_with n' m ->\n  tcolorable_with (n + n') m.\nProof.\n  intros [k ?] [k' ?].\n  red.\nAdmitted.\n\nDefinition num_of_regions (n : nat) (m : map) : Prop :=\n  ~ (at_most_regions (n - 1) m) /\\ at_most_regions n m.\n\n(* alias *)\nDefinition num_of_vertices := num_of_regions.\n\nDefinition num_of_edges (n : nat) (m : map) : Prop :=\n  ~ (at_most_regions (n - 1) (edge m)) /\\ at_most_regions n (edge m).\n\n(*\nDefinition num_of_faces (n : nat) (m : map) : Prop :=\n  ~ (at_most_regions (n - 1) (corner_map m)) /\\ at_most_regions n (corner_map m).\n*)\n", "meta": {"author": "momohatt", "repo": "plane-graph", "sha": "11336a94d812ea5cb7694b21d3b50a1d97c77a93", "save_path": "github-repos/coq/momohatt-plane-graph", "path": "github-repos/coq/momohatt-plane-graph/plane-graph-11336a94d812ea5cb7694b21d3b50a1d97c77a93/PlaneGraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7197925213033899}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) : natural := plus (mult y z) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj286_coqofml_CwVfci.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7197925134144999}}
{"text": "Inductive lst : Type :=\n  | Nil : lst\n  | Cons : nat -> lst -> lst.\n\nFixpoint append (l1 : lst) (l2 : lst) : lst :=\n  match l1 with\n  | Nil => l2\n  | Cons x y => Cons x (append y l2)\n  end.\n\nFixpoint rev2 (l : lst) (a : lst) : lst :=\n  match l with\n  | Nil => a\n  | Cons x t => rev2 t (Cons x a)\n  end.\n\nLemma rev2_append_aux : forall x a b : lst,\n  append (rev2 x Nil) (append a b) = append (rev2 x a) b.\nProof.\n  intro x.\n  induction x.\n  - reflexivity.\n  - intros. simpl.\n    rewrite <- (IHx (Cons n a)).\n    rewrite <- IHx.\n    reflexivity.\nQed.\n\nLemma append_single : forall (n : nat) (a : lst),\n  append (Cons n Nil) a = Cons n a.\nProof.\n  reflexivity.\nQed.\n\nTheorem rev2_append : forall x a : lst, rev2 x a = append (rev2 x Nil) a.\nProof.\n  intro x.\n  induction x.\n  - reflexivity.\n  - intros. simpl.\n    rewrite IHx.\n    rewrite <- append_single.\n    rewrite rev2_append_aux.\n    reflexivity.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/list_rev2_append.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7197330370886985}}
{"text": "Require Export lc.tactics.\nImport LCNotations.\nLocal Open Scope lc_scope.\n\n\n(*** Formalization of Barendregt's Chapter 3 (REDUCTION). *)\n\n\n(* ################################################################# *)\n(** * Section 3.1 Notions of reduction *)\n\n(** We start by defining *properties* of binary term relations.\n  \n    In our Ott generated definitions, a [relation] is defined as the type\n    [tm -> tm -> Prop]. \n\n    Below, we'll use the metavariable [R] for relations, and if terms [t] and \n    [u] are related by [R], then we will write that as [R t u].\n\n    Because we are working with a locally nameless representation, if we have \n    [R t u], we'll want to know that both [t] and [u] are locally closed. In \n    other words, we have satisfied the [lc R] constraint.\n\n *)\n\n(** ** Equivalence relation (and type classes) *)\n\n(** This is a standard mathematical definitions. An *equivalence* relation is\n    one that is reflexive, symmetric and transitive.  These definitions are\n    similar to those in the the Coq standard library\n    (https://coq.inria.fr/library/Coq.Classes.RelationClasses.html) but note\n    that reflexivity is only required for *locally closed* terms.\n\n    A type class is a form of record type that is determined by its parameter\n    [R]. We expect that there will only be one meaningful way that a relation\n    can be reflexive. Later on, we will create values of this record type for\n    specific relations by supplying appropriate proofs. By declaring these\n    records asw type classes, Coq can find these proofs automatically, just by\n    knowing what relation we are working with.  *)\n\nClass reflexive (R: relation) := {\n  reflexivity : forall t : tm, lc_tm t -> R t t\n}.\nClass transitive (R: relation) := {\n  transitivity : forall t1 t2 t3 : tm, R t1 t2 -> R t2 t3 -> R t1 t3\n}.\nClass symmetric (R: relation) := {\n  symmetry : forall t1 t2 : tm, R t1 t2 -> R t2 t1\n}.\n\nClass equivalence (R : relation) : Prop := {\n    equivalence_reflexive  :> reflexive R ;\n    equivalence_symmetric  :> symmetric R ;\n    equivalence_transitive :> transitive R \n}.\n\n(* ================================================================= *)\n\n(** ** Compatible relation *)\n\n(** Definition 3.1.1 (i)\n\n   A *compatible* relation is one that is preserved by the constructors of the\n   language definition. We might write this informally, using the three\n   conditions.\n\n       - (abs) R t u implies R \\x.t \\x.u\n\n       - (app1) R t t' implies R (t u) (t' u)\n\n       - (app2) R u u' implies R (t u) (t u')\n\n   Because of our use of the locally nameless representation, we'll need to \n   add lc_tm preconditions to `compatible_app1` and `compatible_app2`.\n\n   Also, compatibility for the `abs` constructor is stated in the \"exists-fresh\"\n   form. We need to be able to show that the relation holds for a single \n   variable that is sufficiently fresh.\n\n *)\n\nClass compatible (R: relation) := {\n\n    compatible_abs :  forall x t u,\n      x `notin` fv_tm t \\u fv_tm u ->\n      R (t ^ x)(u ^ x) -> R (abs t) (abs u) ;\n\n    compatible_app1 : forall t t' u, \n      R t t' -> lc_tm u -> R (app t u) (app t' u) ;\n\n    compatible_app2 : forall t u u', \n      lc_tm t -> R u u' -> R (app t u) (app t u')\n  }.\n\n(** In the case when the relation is reflexive and transitive, we can use the\n    two separate properties for application at once. The notation `{_} marks \n    type class arguments to this lemma. When we apply the lemma, Coq will \n    search for the values automatically. *)\n\nLemma compatible_app {R} `{lc R} `{reflexive R} `{transitive R} `{compatible R} :\n  forall t u t' u',\n  R t t' -> R u u' -> R (app t u) (app t' u').\nProof.\n  (* WORKINCLASS *)\n  intros. \n  eapply transitivity with (t2 := (app t' u)).\n  eapply compatible_app1; eauto with lngen.  \n  eapply compatible_app2; eauto with lngen.\nQed. (* /WORKINCLASS *)\n\n(* ================================================================= *)\n\n(** Definition 3.1.1 (ii) a *congruence* relation (also called an equality) is \n   a compatible equivalence relation. *)\nClass congruence R := {\n  congruence_equivalence :> equivalence R ;\n  congruence_compatible  :> compatible R \n}.\n\n(** Definition 3.1.1 (iii) a *reduction* relation is reflexive, transitive and \n  compatible. *)\nClass reduction R := {\n  reduction_reflexive  :> reflexive R ;\n  reduction_transitive :> transitive R ;\n  reduction_compatible :> compatible R\n}.\n\n\n(** We'll jump ahead a bit in the chapter and also define the following three\n    substitution properties for binary term relations.\n\n    In general, we expect the first property to always hold for any binary\n    term relation. If two terms are related, then they should still be \n    related after substitution.\n\n    However, the second and third may or may not be true.  (For example, the\n    second is not true for primitive \"beta\" reduction.)  *)\n\n(** Definition 3.1.14 *)\nDefinition subst1 (R : relation) := \n  forall t t' x u, lc_tm u ->\n    R t t' -> R (t [ x ~> u ]) (t' [ x ~> u ]) .\nDefinition subst2 (R : relation) :=\n  forall x t u u', lc_tm t -> \n    R u u' -> R (t [ x ~> u ]) (t [ x ~> u' ]).\nDefinition subst3 (R : relation) :=\n  forall x t t' u u', \n    R t t' -> R u u' -> R (t [ x ~> u ]) ( t' [ x ~> u' ]).\n\n(** We'll also make a class for relations that satisfy the first substitution\n    property. *)\nClass substitutive (R : relation) := {\n    subst : subst1 R\n}.\n\n(** Finally, we'll say that a relation S is a closure of relation R if it \n    includes everything that is related by R (and possibly more things.\n *)\nClass closure (R S : relation) := { \n    embed : forall t u, R t u -> S t u\n  }.\n\n\n(* ================================================================= *)\n\n(** ** Definition 3.1.4 and 3.1.5\n    \n   Next, We will diverge slightly from Barendregt and use a general definition\n   for reflexive-transitive closure and symmetric-transitive closure instead\n   of layering them on top of compatible closure.\n\n   Take a moment to look at the following inductive definitions that appear in\n   the Ott file. These definitions are a way of taking a relation and forcing\n   it to be compatible, reflexive, and transitive.  *)\n\nPrint compatible_closure.\nPrint refl_trans_closure.\nPrint sym_trans_closure.\n \n(** Below are some names for specific closures of R. Below, we will call an\n    arbitrary [R] a \"reduction\" and imagine it as a step or transition\n    rule. i.e. if we have [R t u] then we say \"[t] reduces to [u] via [R]\".  *)\n\n(** Allow exactly one R-reduction, anywhere inside the term. *)\nDefinition one_step_R_reduction (R : relation) := compatible_closure R.\n\n(** Allow a sequence of arbitrarily many one step R-reductions *)\nDefinition R_reduction (R : relation) := refl_trans_closure (compatible_closure R).\n\n(** Generate congruence relation from R-reduction, by forcing it \n    to also be symmetric. *)\nDefinition R_convertibility (R : relation) := sym_trans_closure (R_reduction R).\n\n(** We will also specialize the latter definitions to the [beta] relation *)\n\nDefinition beta_reduction := R_reduction beta.\nDefinition beta_convertibility := R_convertibility beta.\n\n(** Note: beta_convertibility is almost the same as beta_equivalence. However,\n    beta_equivalence is defined directly as the reflexive, symmtric,\n    transitive, compatible closure of beta_reduction, which is not quite the\n    same as the above proof. Both definitions do relate the same terms, but\n    beta_equivalence derivations are less structured than beta_conversion.\n\n    If each of the \\ and / below are beta_reductions, then a\n    beta_convertibility proof looks like:\n\n            t t1 t2 ...  t3 u \\ / \\ / \\ / \\ / t' t1' ...  u' *)\n\n\n(* ================================================================= *)\n\n(** We'll want to show that beta_reduction and beta_convertibility have the\n    properties listed above. We can do so by proving those properties about\n    the closure operations and asking Coq to glue these results together \n    via type class resolution. \n\n *)\n\n(** ** Properties of the compatible closure operation *)\n\n#[local]\nInstance lc_compatible_closure {R} `{lc R} : lc (compatible_closure R).\nProof.\n  split.\n  - intros a b CC. induction CC; eauto using lc1.\n  - intros a b CC. induction CC; eauto using lc2.\nQed. \n\n#[local]\nInstance closure_compatible_closure {R} : closure R (compatible_closure R).\nProof. constructor. intros; eauto using cc_rel. Qed.\n\n(** *** Exercise [subst1_compatible closure] *)\n\n(** This is a standard substitution lemma *)\n#[local]\nInstance subst1_compatible_closure R { SR : substitutive R } : substitutive (compatible_closure R).\nProof. \n(* ADMITTED *)\n  constructor. intros t t' x u LCu CC. \n  induction CC.\n  - eapply cc_rel; eauto. apply subst; eauto.\n  - pick fresh y and apply cc_abs. fold subst_tm. \n    spec y.\n    autorewrite with lngen in H0; auto.\n  - eapply cc_app1; eauto with lngen.\n  - eapply cc_app2; eauto with lngen.\nQed. (* /ADMITTED *)\n\n(** Due to the use of co-finite quantification in our definition of\n    compatible_closure (in the Ott file), we need the underlying relation to\n    be substitutive.  Showing this result is similiar to proving an\n    \"exists-fresh\" lemma *)\n\n#[local]\nInstance compatible_compatible_closure {R} `{substitutive R} : compatible (compatible_closure R).\nProof.\n    (* WORKINCLASS *)\n  split;  intros; eauto.\n  have SS: substitutive (compatible_closure R) by typeclasses eauto.\n  pick fresh y and apply cc_abs.\n  rewrite (subst_tm_intro x t); auto.\n  rewrite (subst_tm_intro x u); auto.\n  eapply subst; eauto.\nQed. (* /WORKINCLASS *)\n\n(** ** Properties of refl_trans_closure operation **)\n\n(** *** Exercise [lc_refl_trans_closure] *)\n\n#[local]\nInstance lc_refl_trans_closure {R} `{lc R} : lc (refl_trans_closure R).\nProof. (* ADMITTED *)\n  split.\n  - induction 1; eauto using lc1.\n  - induction 1; eauto using lc2.\nQed. (* /ADMITTED *)\n\n#[local]\nInstance closure_refl_trans_closure {R} : closure R (refl_trans_closure R).\nProof. constructor. intros; eauto using rt_rel. Qed.\n\n#[local]\nInstance reflexive_refl_trans_closure {R}: reflexive (refl_trans_closure R).\nProof. constructor. intros. eauto using rt_refl with lngen. Qed.\n\n#[local]\nInstance transitive_refl_trans_closure {R} : transitive (refl_trans_closure R).\nProof. constructor. intros. eauto using rt_trans with lngen. Qed.\n\n#[local]\nInstance subst1_refl_trans_closure {R} `{substitutive R} : substitutive (refl_trans_closure R).\nProof.\n  constructor. unfold subst1.\n  intros t t' x u LC RTC.\n  induction RTC; eauto using subst with lngen.\nQed.\n\n#[local]\nInstance compatible_refl_trans_closure {R} `{compatible R} : \n  compatible (refl_trans_closure R).\nProof.\n  (* WORKINCLASS *)\n  split;  intros x t u H1 H0; eauto.\n  + dependent induction H0. \n    - (* rt_rel *)\n      eapply rt_rel. \n      eapply (compatible_abs x); eauto.\n    - (* rt_refl *)\n      autorewrite with lngen in x. subst. \n      eapply reflexivity; eauto with lngen.\n    - (* rt_trans *) \n      eapply transitivity with (t2 := abs (close x t2)).\n      eapply IHrefl_trans_closure1 with (x := x); auto;\n      autorewrite with lngen; auto.\n      eapply IHrefl_trans_closure2 with (x:= x); auto;\n      autorewrite with lngen; auto.\n  + dependent induction H1; eauto using compatible_app1.\n  + dependent induction H0; eauto using compatible_app2.\nQed. (* /WORKINCLASS *)\n\n\n(** ** Properties of sym_trans_closure: it preserves local closure,\nsubstitutivity and compatibility *)\n\n(** *** Exercise [lc_sym_trans_closure] *)\n#[local]\nInstance lc_sym_trans_closure {R} `{lc R} : lc (sym_trans_closure R).\nProof.  (* ADMITTED *)\n  have LC:forall a b, sym_trans_closure R a b -> lc_tm a /\\ lc_tm b.\n  { intros a b STC. induction STC; split.\n    all: try destruct IHSTC. \n    all: try destruct IHSTC1.\n    all: try destruct IHSTC2.    \n    all: eauto with lngen.\n  } \n  split.\n  intros; edestruct LC; eauto.\n  intros; edestruct LC; eauto.\nQed. (* /ADMITTED *)\n\n#[local]\nInstance closure_sym_trans_closure {R} : closure R (sym_trans_closure R).\nProof. constructor. intros; eauto using st_rel. Qed.\n\n#[local]\nInstance symmetric_sym_trans_closure {R} : symmetric (sym_trans_closure R).\nProof. constructor. intros. eauto using st_sym with lngen. Qed.\n\n#[local]\nInstance transitive_sym_trans_closure {R} : transitive (sym_trans_closure R).\nProof. constructor. intros. eauto using st_trans with lngen. Qed.\n\n#[local]\nInstance reflexive_sym_trans_closure {R} `{reflexive R} : \n  reflexive (sym_trans_closure R).\nProof. constructor. intros. apply embed. apply reflexivity. auto. Qed.\n\n#[local]\nInstance subst1_sym_trans_closure {R} {SR : substitutive R} : substitutive (sym_trans_closure R).\nProof.\n  constructor. unfold subst1. intros t t' x u LCu STC.\n  induction STC.\n  - eapply embed; eauto using subst. \n  - eapply symmetry; eauto.\n  - eapply transitivity with (t2 := t2 [x ~> u]); eauto.\nQed.\n\n(** *** Exercise [compatible_sym_trans_closure] *)\n\n#[local]\nInstance compatible_sym_trans_closure {R} {CR: compatible R} : compatible (sym_trans_closure R).\nProof.\n  (* ADMITTED *)\n  constructor.\n  + intros.\n    dependent induction H0.\n    - eapply embed; eauto.\n      eapply compatible_abs; eauto.\n    - eapply symmetry; eauto.\n    - eapply transitivity with (t2 := (abs (close x t2))).\n      eapply IHsym_trans_closure1; eauto.\n      autorewrite with lngen; auto.\n      autorewrite with lngen; auto.\n      eapply IHsym_trans_closure2; eauto.\n      autorewrite with lngen; auto.\n      autorewrite with lngen; auto.\n + intros.\n   dependent induction H.\n   - eapply embed; eauto. \n     eapply compatible_app1; eauto.\n   - eapply symmetry; eauto.\n   - eapply transitivity with (t2 := app t2 u); eauto.\n + intros. dependent induction H0.\n   - eapply embed; eauto. \n     eapply compatible_app2; eauto.      \n   - eapply symmetry; eauto.\n   - eapply transitivity with (t2 := app t t2); eauto.\nQed. (* /ADMITTED *)\n\n(* ================================================================= *)\n\n(** Now let's put everything together and show properties of R-reduction and R-convertibility. *)\n\n(** ** Lemma 3.1.6  \n\n   Our definition of the R_reduction operation produces a reduction relation\n   and R_convertibility produces a congruence relation. \n   \n*)\n\n#[local]\nInstance reduction_R_reduction R `{substitutive R} : reduction (R_reduction R).\nProof.\n  split; typeclasses eauto.\nQed.\n\n#[local]\nInstance congruence_R_convertibility {R} `{substitutive R}: congruence (R_convertibility R).\nProof.\n  split.\n  - split; typeclasses eauto.\n  - typeclasses eauto. \nQed.\n\n\n(** ** Remark 3.1.7 *)\n\nLemma subst2_R_reduction R `{lc R}`{substitutive R}: subst2 (R_reduction R).\nProof.\n  (* WORKINCLASS *)\n  unfold subst2. \n  intros x t u u' LCt Red.\n  have LC: lc (refl_trans_closure (compatible_closure R)). { typeclasses eauto. }\n  have CC: compatible (refl_trans_closure (compatible_closure R)). { typeclasses eauto. }\n  (* induction on the \"syntax\" of the term *)\n  induction LCt; simpl; eauto.\n  + (* var *)\n    destruct_var_eq.\n    auto.\n    eapply reflexivity; auto.\n  + (* abs *) \n    pick fresh y. spec y.\n    eapply compatible_abs with (x:=y).\n    autorewrite with lngen. auto.\n    rewrite_subst_open_hyp; eauto with lngen.    \n  + (* app *)\n    eapply compatible_app; eauto.\nQed. (* /WORKINCLASS *)\n\n(* ================================================================= *)\n\n(** The next part defines what it means for a term to be a normal\n    form [nf] according to some reduction relation R. \n  *)\n\n(** ** Definition 3.1.8 *)\n\n(** (i) A term t is a R-redex if there exists u, such that R t u *)\nPrint redex.\n\n(** (ii) A term t is R-normal-form if no subterm contains an R-redex *)\nPrint nf.\n\n(** (iii) A term u is a R-nf-of t if u is an R-nf and t is R-convertible to u. *)\nDefinition R_nf_of R u t := nf R u /\\ R_convertibility R t u.\n\n(** ** Lemma 3.1.10  (i) *)\n\n(** Normal forms do not single-step *)\n\nLemma nf_normal R : forall t,\n  nf R t -> not (redex (compatible_closure R) t).\nProof.\n  intros t nft.\n  induction nft.\n  all: intros h; inversion h; subst.\n  all: match goal with [H0 : compatible_closure ?R ?x ?u |- _ ] => inversion H0; subst end; eauto. \n  pick fresh x. spec x. eauto.\nQed.\n\n(** ** Lemma 3.1.10  (ii) *)\n\n(** Normal forms only reduce to themselves *)\n\nLemma nf_noreduction {R} : forall t,  nf R t -> forall u, R_reduction R t u -> t = u /\\ nf R u.\nProof.\n  intros.\n  unfold R_reduction in H0. \n  dependent induction H0.\n  - apply nf_normal in H.\n    apply False_ind. apply H.\n    exists u. auto.\n  - auto.\n  - destruct (IHrefl_trans_closure1 R); auto. subst.\n    destruct (IHrefl_trans_closure2 R); auto.\nQed.\n\n(* ================================================================= *)\n\n(** ** Definition 3.1.11 *) \n\nDefinition diamond_property (R : relation) := \n  forall t t1 t2, R t t1 -> R t t2 -> exists t3, R t1 t3 /\\ R t2 t3.\n\nDefinition church_rosser (R : relation) := diamond_property (R_reduction R).  \n\n(** ** Theorem 3.1.12 *)\n\n(** R-compatible terms R-reduce to a common term *)\n\nTheorem convertibility_reduction_diamond {R} `{lc R} (CR: church_rosser R) :\n  forall t u, R_convertibility R t u -> exists z, R_reduction R t z /\\ R_reduction R u z.\nProof. \n  intros t u Rconv.\n  have lcRR: lc (R_reduction R). { typeclasses eauto. }\n  unfold R_convertibility in *.\n  dependent induction Rconv.\n  - exists u. split; unfold R_reduction. auto. eapply reflexivity. eapply lc2; eauto.\n  - edestruct (IHRconv R) as [z [Ruz Rtz]]; eauto.\n  - edestruct (IHRconv1 R) as [z1 [Rt1z1 Rt2z1]]; eauto.\n    edestruct (IHRconv2 R) as [z2 [Rt2z2 Rt3z2]]; eauto.\n    unfold church_rosser, diamond_property in CR.\n    destruct (CR _ _ _ Rt2z1 Rt2z2) as [z3 [Rz1z3 Rz2z3]]; eauto.\n    (*      t1     t2    t3\n               z1     z2\n                   z3           *)\n    exists z3. split. \n    eapply transitivity with (t2:= z1); eauto.\n    eapply transitivity with (t2:= z2); eauto.\nQed.\n\n\n(** ** Corollary 3.1.13 *)\nLemma nf_reduce R `{lc R} (CR: church_rosser R) : forall u t, R_nf_of R u t -> R_reduction R t u.\nProof.\n  intros u t.\n  unfold R_nf_of.\n  intros [NF RC].\n  destruct (convertibility_reduction_diamond CR _ _ RC) as [z[Rtz Rzu]].\n  edestruct (nf_noreduction _ NF _ Rzu). subst.\n  auto.\nQed.\n  \n(** ** Proposition 3.1.15 *)\n\n#[local]\nInstance subst1_R_reduction {R} `{substitutive R} : substitutive (R_reduction R).\nProof.\n  typeclasses eauto.\nQed.\n\n#[local]\nLemma subst1_R_convertibility {R} `{substitutive R} : substitutive (R_convertibility R).\nProof.\n  typeclasses eauto.\nQed.\n\n(** ** Proposition 3.1.16 *)\n\n(** *** Exercise [subst1_beta] *)\n\n#[local]\nInstance subst1_beta : substitutive beta.\nProof. (* ADMITTED *)\n  constructor. intros t t' x u LCu Beta.\n  inversion Beta. subst.\n  simpl.\n  autorewrite with lngen; auto.\n  eapply beta_reduct; eauto with lngen.\n  pick fresh y. eapply (lc_abs_exists y). \n  inversion H. spec y.\n  apply subst_tm_lc_tm with (t2 := u) (x1 := x) in H2; auto.\n  autorewrite with lngen in H2; auto.\nQed. (* /ADMITTED *)\n\n#[local]\nInstance lc_beta : lc beta.\nProof. \n  econstructor.\n  - intros. inversion H; auto.\n  - intros. inversion H; subst; auto.\n    eauto with lngen.\nQed.\n\n(* ################################################################# *)\n(** * Section 3.2 Beta reduction *)\n\n(** This section studies the relation [beta_reduction] more closely and shows \n    that it is Church-Rosser using a proof that Barendregt attributes to \n    Tait and Martin-Lof. \n\n   We won't show that beta_reduction satisfies the diamond property directly. Instead \n   we will define another relation, called \"parallel reduction\", and derive this \n   property from the lemma below and the following two facts:\n\n      - parallel reduction satisfies the diamond property\n\n      - beta_reduction is the transitive closure of parallel reduction\n      \n   *)\n\n(** ** Lemma 3.2.2 *)\n(** If a relation has the diamond property, then so does its transitive closure. \n\nBarendregt's proof is \"A simple diagram chase suggested by figure 3.4\". See \nif you can figure out how to translate that figure to a (nested) induction.\n*)\n\n(** *** Exercise [diamond_property_trans_closure] *)\n\nLemma diamond_property_trans_closure {R} : diamond_property R -> diamond_property (trans_closure R). \nProof. \n  intros DR.\n  unfold diamond_property in *.\n  intros t t1 t2 TC1.\n  move: t2.\n  (* ADMITTED *)\n  induction TC1; intros t2' TC2.\n  - have lemma: forall u,  R t u -> exists t3, trans_closure R u t3 /\\ R t2' t3.\n    { clear u H.\n    induction TC2; intros u0 H1.\n    + edestruct (DR t u u0) as [u1 [R1 R2]]; eauto.\n    + destruct (IHTC2_1 DR _ H1) as [u2 [R1 R2]].\n      edestruct (IHTC2_2 DR) as [e3 [R3 R4]]. eauto. eauto.\n    } \n    edestruct lemma; eauto.\n    exists x. split_hyp. split; eauto.\n  - destruct (IHTC1_1 DR ltac:(eauto)) as [u2 [R1 R2]]; eauto.\n    edestruct (IHTC1_2 DR) as [u3 [R3 R4]]. eauto.\n    exists u3. split. eauto. eapply t_trans with (t2 := u2); eauto.\nQed. (* /ADMITTED *)\n\n(* ================================================================= *)\n\n(** ** Definition 3.2.3 is often called parallel reduction. *)\n\nPrint parallel.\n\n(** Properties of parallel reduction *)\n\n#[local]\nInstance lc_parallel : lc parallel.\nProof.\n  have: forall a b, parallel a b -> lc_tm a /\\ lc_tm b.\n  { intros a b P. induction P; split; split_hyp; eauto.\n  eapply lc_abs_open; eauto.\n  pick fresh x. repeat spec x. split_hyp. eapply lc_abs_exists; eauto.\n  pick fresh x. repeat spec x. split_hyp. eapply lc_abs_exists; eauto. }\n  intros h.\n  split;  intros a b h1; edestruct h; eauto.\nQed.\n\n#[local]\nInstance parallel_reflexive : reflexive parallel.\nProof.\n  constructor. intros t LC.\n  induction LC; eauto.\n   Unshelve. exact empty.\nQed.\n\n#[local]\nInstance subst1_parallel : substitutive parallel.\nProof.\n  constructor. unfold subst1.\n  intros t t' x u LCu Ptt'. \n  induction Ptt'; simpl.\n  - (* beta *)\n    autorewrite with lngen; auto.\n  - (* var *)\n    destruct_var_eq;\n    eauto using reflexivity.\n  - (* abs *)\n    pick fresh y and apply p_abs.\n    spec y.\n    rewrite_subst_open_hyp.\n  - (* app *)\n    eauto.\nQed.  \n\n#[local]\nInstance compatible_parallel : compatible parallel.\nProof.\n  split. \n  + intros x t u Fr P.\n    pick fresh y and apply p_abs.\n    rewrite (subst_tm_intro x t); auto.\n    rewrite (subst_tm_intro x u); auto.\n    eapply subst; eauto.\n  + intros. eauto using reflexivity.\n  + intros. eauto using reflexivity.\nQed.\n\n(** ** Lemma 3.2.4  \n\n   Parallel reduction satisfies the second and third substitution properties.\n   This is a key part of the Church-Rosser proof.\n *)\n\n(** This is done inline. But we have already identified this property for \n   relations, so we'll prove it separately first. *)\nLemma subst2_parallel : subst2 parallel.\nProof.\n  unfold subst2.\n  intros x t u u' LC P.\n  induction LC; simpl.\n  - (* var *)\n    destruct_var_eq; auto. \n  - (* abs *)\n    pick fresh y and apply p_abs.\n    spec y.\n    rewrite_subst_open_hyp.\n    eapply lc1; eauto.\n    eapply lc2; eauto. \n  - (* app *)\n    eauto.\nQed.\n\n(** Parallel reduction is *not* transitive. So we need to prove this by induction. *)\nLemma subst3_parallel : subst3 parallel.\nProof.\n  unfold subst3.\n  intros x t t' u u' Ptt' Puu'.\n  have LCu : lc_tm u. { eapply lc1; eauto. }\n  have LCu' : lc_tm u'. { eapply lc2; eauto. }\n  induction Ptt'; simpl.\n  - (* beta *)\n    autorewrite with lngen; auto.\n  - (* var *)\n    destruct_var_eq; auto.\n  - (* abs *)\n    pick fresh y and apply p_abs.\n    spec y.\n    rewrite_subst_open_hyp.\n  - (* app *)\n    eauto.\nQed.\n\n(** A corollary of the above lets us reason about parallel reduction for opened terms. *)\nCorollary parallel_open : forall x t t' u u',\n  x `notin` fv_tm t \n  -> x `notin` fv_tm t'\n  -> parallel (t ^ x) (t' ^ x) \n  -> parallel u u' \n  -> parallel (open t u) (open t' u').\nProof.  \n  intros x t t' u u' F1 F2 H0 P41.\n  move: (subst3_parallel x _ _ _ _ H0 P41) => h.\n  repeat rewrite subst_tm_open_tm_wrt_tm in h; eauto.\n  eapply lc1; eauto with lngen.\n  eapply lc2; eauto with lngen.\n  repeat rewrite subst_eq_var in h.\n  repeat rewrite subst_tm_fresh_eq in h; auto.\nQed.\n\n\n\n(* ================================================================= *)\n\n(** ** Lemma 3.2.6 *)\n\n(** The first of our two key lemmas: parallel reduction satisfies \nthe diamond property. *)\n\nLemma diamond_property_parallel : diamond_property parallel.\nProof.\n  (* WORKINCLASS *)\n  unfold diamond_property.\n  intros t t1 t2 H1 H2.\n  move: t2 H2. (* make IH stronger *)\n  induction H1; \n    intros t2 H2; inversion H2; subst.\n  - (* beta / beta *)\n    destruct (IHparallel1 _ H1) as [t3' [P31 P32]].\n    inversion P31. subst.\n    inversion P32. subst.\n    destruct (IHparallel2 _ H4) as [t4' [P41 P42]].\n    pick fresh x. spec x.\n    exists (open t'1 t4'). \n    split; eauto using parallel_open. \n  - (* beta / app *)\n    destruct (IHparallel1 _ H1) as [t2 [P1 P2]].\n    inversion P1. subst.\n    destruct (IHparallel2 _ H4) as [t3 [P3 P4]].\n    pick fresh x. spec x.\n    exists (open t'1 t3).\n    split; eauto using parallel_open.\n  - (* var / var *)\n    exists (var_f x). split; auto.\n  - (* abs / abs *)\n    pick fresh x. repeat spec x.\n    destruct (H0 _ H3) as [t3 [P1 P2]].\n    exists (abs (close x t3)).\n    split.\n    eapply (compatible_abs x);\n    autorewrite with lngen; auto.\n    eapply (compatible_abs x);\n    autorewrite with lngen; auto.\n  - (* app / beta *)\n    destruct (IHparallel1 _ H1) as [t2 [P1 P2]].\n    inversion P2. subst.\n    destruct (IHparallel2 _ H4) as [t3 [P3 P4]].\n    pick fresh x. spec x.\n    exists (open t'1 t3).\n    split; eauto using parallel_open. \n  - (* app / app *)\n    destruct (IHparallel1 _ H1) as [t2 [P1 P2]].\n    destruct (IHparallel2 _ H4) as [t3 [P3 P4]].\n    exists (app t2 t3).\n    split; auto.\nQed. (* /WORKINCLASS *)\n\n(* ================================================================= *)\n\n(** This next part talks about relations between relations. To make this \n    a bit easier to work with, we'll introduce some notation for when \n    one relation implies another and when one relation is equivalent to \n    another\n*)\n\nModule RelationNotation.\n  Notation \"R1 [<=] R2\" := (forall t u, R1 t u -> R2 t u).\n  Notation \"R1 [=] R2\" := (forall t u, R1 t u <-> R2 t u).\nEnd RelationNotation.\nImport RelationNotation.\n\n(** ** Lemma 3.2.7 *)\n\n(** Lemma 3.2.7 states that \n\n               beta_reduction = trans_closure parallel\n\n   To prove this lemma, Barendregt notes that \n\n           refl_closure (compatible_closure beta) [<=] parallel [<=] beta_reduction\n\n   He then says: \n\n      Since beta_reduction is the transitive closure of the first, then it is also \n      the transitive closure of parallel reduction.\n\n  This proof is captured in then next four lemmas.\n\n*)\n\n\n\nLemma refl_compatible_sub_parallel : refl_closure (compatible_closure beta) [<=] parallel.\nProof.\n  intros t u H. dependent induction H.\n  - dependent induction H.\n    + inversion H. eapply p_beta; eauto using reflexivity.\n    + pick fresh x. spec x. eapply (compatible_abs x); eauto.\n    + eapply compatible_app1; eauto using reflexivity.\n    + eapply compatible_app2; eauto using reflexivity.      \n  - eapply reflexivity; auto.\nQed.\n\n(** *** Exercise [parallel_sub_beta_reduction] *)\n\nLemma parallel_sub_beta_reduction : parallel [<=] beta_reduction.\nProof. (* ADMITTED *)\n  intros.\n  induction H; unfold beta_reduction in *; unfold R_reduction in *.\n  - apply transitivity with (t2:= app (abs t') u').\n    eapply compatible_app; eauto.\n    eapply embed.\n    eapply embed.\n    eapply beta_reduct; eauto using lc1, lc2.\n  - eauto.\n  - pick fresh x. spec x.\n    eapply (compatible_abs x); eauto.\n  - eapply compatible_app; eauto.\nQed. (* /ADMITTED *)\n\nLemma beta_reduction_trans_refl_cc : beta_reduction [=] trans_closure (refl_closure (compatible_closure beta)).\nProof.\n  unfold beta_reduction, R_reduction in *. \n  split; intros h; dependent induction h; eauto.\n  inversion H. eauto. eapply reflexivity. auto.\nQed.\n\nLemma  beta_reduction_is_trans_closure_parallel : \n   beta_reduction [=] trans_closure parallel.\nProof. \n  intros.\n  split.\n  - rewrite beta_reduction_trans_refl_cc.\n    (* relies on R1 [<=] R2 implies trans_closure R1 [<=] trans_closure R2\n       where R1 is refl_closure (cc beta) and R2 is parallel reduction \n     *)\n    intros h.\n    dependent induction h.\n    eapply t_rel. \n    eapply refl_compatible_sub_parallel. auto.\n    eapply t_trans; eauto.\n  - intros h.\n    (* relies on R1 [<=] R2 implies trans_closure R1 [<=] trans_closure R2\n       where R1 is parallel reduction and R2 is beta_reduction. \n       Also observe: trans_closure (beta_reduction) [=] beta_reduction *)\n    dependent induction h.\n    eapply parallel_sub_beta_reduction; auto. \n    eapply transitivity; eauto.\nQed.\n\n(** To use this result, we also need to show that the diamond\n    property respects relational equivalence. This is mostly a matter \n    of unfolding definitions. *)\n\nLemma diamond_respects : forall R1 R2,\n  R1 [=] R2 ->\n  diamond_property R1 ->\n  diamond_property R2.\nProof.\n  intros R1 R2 rr.\n  unfold diamond_property. \n  intros db t1 t2 t3 T1 T2.\n  rewrite <- rr in T1.\n  rewrite <- rr in T2.\n  destruct (db t1 t2 t3 T1 T2) as [t4 [b1 b2]].\n  exists t4.\n  rewrite -> rr in b1.\n  rewrite -> rr in b2.\n  split; auto.\nQed.\n\n(* ================================================================= *)\n\n(** * Lemma 3.2.8 (Church-Rosser Theorem) *)\n\nLemma church_rosser_beta : church_rosser beta.\nProof.\n  unfold church_rosser.\n  fold beta_reduction.\n  eapply diamond_respects.\n  symmetry.\n  eapply beta_reduction_is_trans_closure_parallel.\n  apply diamond_property_trans_closure.\n  apply diamond_property_parallel.\nQed.\n\n(* ================================================================= *)\n\n(** ** Corollary 3.2.9 (i) *)\n\nLemma nf_reduce_beta : forall u t, R_nf_of beta u t -> beta_reduction t u.\nProof.\n  intros. eapply nf_reduce; eauto.\n  typeclasses eauto.\n  eapply church_rosser_beta.\nQed.\n\n(** ** Corollary 3.2.9 (ii) *)\n\nLemma nf_unique_beta : forall u1 u2 t, R_nf_of beta u1 t -> R_nf_of beta u2 t -> u1 = u2.\nProof.\n  intros u1 u2 t h1 h2. \n  move: (nf_reduce_beta _ _ h1) => r1.\n  move: (nf_reduce_beta _ _ h2) => r2.\n  destruct h1 as [h1 h1'].\n  destruct h2 as [h2 h2'].\n  move: (church_rosser_beta _ _ _ r1 r2) => [v [r1' r2']].\n  apply nf_noreduction in r1'; auto. destruct r1' as [eq nfv1]. subst.\n  apply nf_noreduction in r2'; auto. destruct r2' as [eq nfv2]. subst.\n  auto.\nQed.\n\nLemma joinability t u (H : beta_convertibility t u) :\n  exists v, beta_reduction t v /\\ beta_reduction u v.\nProof.\n  apply convertibility_reduction_diamond.\n  apply church_rosser_beta.\n  auto.\nQed.\n\n(** ** Main result: different normal forms are not beta convertible. *)\n\nLemma consistency : forall t u, nf beta t -> nf beta u -> t <> u -> not (beta_convertibility t u).\nProof.\n  intros.\n  intros h.\n  move: (joinability _ _ h) => [v [rtv ruv]].\n  move: (nf_noreduction _ H _ rtv) => [EQ nfv].\n  move: (nf_noreduction _ H0 _ ruv) => [EQ' nfv'].\n  rewrite <- EQ' in EQ.\n  contradiction.\nQed.\n\n\n(** For completness, we will exhibit two different normal forms. *)\n\n(* \" \\x. \\y. x\" *)\nDefinition church_true := abs (abs (var_b 1)).\n\n(* \" \\x. \\y. y\" *)\nDefinition church_false := abs (abs (var_b 0)).\n\nLemma nf_true : nf beta church_true.\nProof.\n  pick fresh x and apply nf_abs.\n  pick fresh y and apply nf_abs.\n  apply nf_var.\n  intro h; inversion h; inversion H.\n  intro h; inversion h; inversion H.\n  intro h; inversion h; inversion H.\nQed.\n\nLemma nf_false : nf beta church_false.\nProof.\n  pick fresh x and apply nf_abs.\n  pick fresh y and apply nf_abs.\n  apply nf_var.\n  intro h; inversion h; inversion H.\n  intro h; inversion h; inversion H.\n  intro h; inversion h; inversion H.\nQed.\n\nLemma not_convertible_true_false : not (beta_convertibility church_true church_false).\nProof.\n  apply consistency.\n  apply nf_true.\n  apply nf_false.\n  intro h. inversion h.\nQed.\n", "meta": {"author": "sweirich", "repo": "lambda-calculus", "sha": "76f0e970d345db824448a52e263aed79f7c271d5", "save_path": "github-repos/coq/sweirich-lambda-calculus", "path": "github-repos/coq/sweirich-lambda-calculus/lambda-calculus-76f0e970d345db824448a52e263aed79f7c271d5/coq/relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7197330241034294}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_collinearorder.\nRequire Import ProofCheckingEuclid.lemma_s_n_col_ncol.\nRequire Import ProofCheckingEuclid.lemma_s_ncol_n_col.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_NCorder :\n\tforall A B C,\n\tnCol A B C ->\n\tnCol B A C /\\ nCol B C A /\\ nCol C A B /\\ nCol A C B /\\ nCol C B A.\nProof.\n\tintros A B C.\n\tintros nCol_A_B_C.\n\n\tpose proof (lemma_s_ncol_n_col _ _ _ nCol_A_B_C) as n_Col_A_B_C.\n\n\tassert (~ Col B A C) as n_Col_B_A_C.\n\t{\n\t\tintros Col_B_A_C.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_B_A_C) as (Col_A_B_C & _).\n\t\tcontradict Col_A_B_C.\n\t\texact n_Col_A_B_C.\n\t}\n\tpose proof (lemma_s_n_col_ncol _ _ _ n_Col_B_A_C) as nCol_B_A_C.\n\n\tassert (~ Col B C A) as n_Col_B_C_A.\n\t{\n\t\tintros Col_B_C_A.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_B_C_A) as (_ & _ & Col_A_B_C & _).\n\t\tcontradict Col_A_B_C.\n\t\texact n_Col_A_B_C.\n\t}\n\tpose proof (lemma_s_n_col_ncol _ _ _ n_Col_B_C_A) as nCol_B_C_A.\n\n\tassert (~ Col C A B) as n_Col_C_A_B.\n\t{\n\t\tintros Col_C_A_B.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_C_A_B) as (_ & Col_A_B_C & _ ).\n\t\tcontradict Col_A_B_C.\n\t\texact n_Col_A_B_C.\n\t}\n\tpose proof (lemma_s_n_col_ncol _ _ _ n_Col_C_A_B) as nCol_C_A_B.\n\n\tassert (~ Col A C B) as n_Col_A_C_B.\n\t{\n\t\tintros Col_A_C_B.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_A_C_B) as (_ & _ & _ & Col_A_B_C & _).\n\t\tcontradict Col_A_B_C.\n\t\texact n_Col_A_B_C.\n\t}\n\tpose proof (lemma_s_n_col_ncol _ _ _ n_Col_A_C_B) as nCol_A_C_B.\n\n\tassert (~ Col C B A) as n_Col_C_B_A.\n\t{\n\t\tintros Col_C_B_A.\n\t\tpose proof (lemma_collinearorder _ _ _ Col_C_B_A) as (_ & _ & _ & _ & Col_A_B_C).\n\t\tcontradict Col_A_B_C.\n\t\texact n_Col_A_B_C.\n\t}\n\tpose proof (lemma_s_n_col_ncol _ _ _ n_Col_C_B_A) as nCol_C_B_A.\n\n\tsplit.\n\texact nCol_B_A_C.\n\tsplit.\n\texact nCol_B_C_A.\n\tsplit.\n\texact nCol_C_A_B.\n\tsplit.\n\texact nCol_A_C_B.\n\texact nCol_C_B_A.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_NCorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.826711787666479, "lm_q1q2_score": 0.7197330130008218}}
{"text": "(** * POrderNat.v : Partial order of nat *)\n\n\nFrom Babel Require Import TerminalDogma \n                          ExtraDogma.Extensionality.\n\n\nFrom Coq Require Import Relations Classical Arith.\n\nFrom Babel Require Export NaiveSet POrderFacility.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\nModule NatLePoset.\n\nLemma poset_mixin : Poset.class_of nat.\nProof.\n    refine (@Poset.Mixin _ le _).\n    constructor.\n    move => x. by apply Nat.le_refl.\n    move => x y z. by apply Nat.le_trans.\n    move => x y. by apply Nat.le_antisymm.\nDefined.\n\nCanonical poset_type := Poset nat poset_mixin.\n\nLemma nat_subset_chainMixin (A : 𝒫(nat)) :\n    Chain.mixin_of A.\nProof.\n    rewrite /Chain.mixin_of => x Hx y Hy //=.\n    by apply Nat.le_ge_cases.\nDefined.\n\n(** every subset of nat is a chain *)\nCanonical nat_subset_chain (A : 𝒫(nat)) := Chain _ (@nat_subset_chainMixin A).\n\n\nModule CanonicalStruct.\n\nCanonical poset_type.\nCanonical nat_subset_chain.\n\nEnd CanonicalStruct.\n\nEnd NatLePoset.\n", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/Babel/POrderInstances/POrderNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7197080185886855}}
{"text": "From Coq Require Import Reals List Arith Lia Lra.\nFrom Coquelicot Require Import Coquelicot.\nFrom CoqE2EAI Require Import matrix_extensions.\nImport ListNotations.\nImport MatrixNotations.\n\nOpen Scope colvec_scope.\nOpen Scope matrix_scope.\nOpen Scope R_scope.\nOpen Scope list_scope.\n\nSection Polehydra.\n\n(** * Basic convex polyhedra theory\n\nConvex polyhedron is a set that arises from a series of\nlinear constraints and describes set of solutions to\na linear inequalities system. We allow only non-strict\ninequalities\n*)\n\n(** A linear constraint c * _ <= b *)\nInductive LinearConstraint (dim: nat) : Type :=\n| Constraint (c: colvec dim) (b:R).\n\n(** \nA predicate that a certain point x satisfies a\nlinear constraint, meaning c*x <= b, where c and b\nare from the definition of linear constraint\n*)\nDefinition satisfies_lc {dim: nat} (x: colvec dim) (l: LinearConstraint dim): Prop :=\nmatch l with\n| Constraint c b => (c * x)%v <= b\nend.    \n\n(* Direct evaluation of linear constraint as a function *)\nDefinition lc_eval {dim: nat} (x: colvec dim) (l: LinearConstraint dim): bool :=\nmatch l with\n| Constraint c b => if Rle_dec (dot c x) b then true else false\nend.    \n\nTheorem lc_eval_correct:\n    forall dim (x: colvec dim) l,\n        (lc_eval x l = true <-> satisfies_lc x l).\nProof.\n    intros dim x l.\n    induction l.\n    unfold lc_eval.\n    unfold satisfies_lc.\n    destruct Rle_dec.\n    split.\n    - intros Htaut. apply r.\n    - intros Hdot. reflexivity.\n    split.\n    - discriminate.\n    - intros Hwrong. contradiction.\nQed.  \n\n(** A convex polyhedron is described by a set of linear constraints *)\nInductive ConvexPolyhedron (dim: nat) : Type :=\n| Polyhedron (constraints: list (LinearConstraint dim)).\n\n(**\nA predicate for membership inside of convex polyhedra\nx is in the polyhedron <=> x satisfies all linear constraints of the polyherdron\n*)\nDefinition in_convex_polyhedron {dim: nat} (x: colvec dim) (p: ConvexPolyhedron dim) :=\nmatch p with\n| Polyhedron lcs =>\n    forall constraint, In constraint lcs ->\n    satisfies_lc x constraint\nend.\n\nFixpoint polyhedron_eval_helper {dim: nat} (l: list (LinearConstraint dim)) (x: colvec dim): bool :=\nmatch l with\n| nil => true\n| lc :: next => andb (lc_eval x lc) (polyhedron_eval_helper next x)\nend.\n\n(**\nDirect evaluation of polyhedron membership as a function into bool\n*)\nDefinition polyhedron_eval {dim: nat} (x: colvec dim) (p: ConvexPolyhedron dim): bool :=\nmatch p with\n| Polyhedron constraints => polyhedron_eval_helper constraints x\nend.\n\nTheorem polyhedron_eval_correct:\n    forall dim (x: colvec dim) p,\n        polyhedron_eval x p = true <-> in_convex_polyhedron x p.\nProof.\n    intros dim x p.\n    induction p.\n    unfold polyhedron_eval.\n    induction constraints.\n    * simpl. split. contradiction. reflexivity.\n    split. unfold polyhedron_eval_helper. unfold in_convex_polyhedron.\n    {\n        intros H constraint HIn.\n        unfold In in HIn.\n        apply andb_prop in H. destruct H.\n        destruct HIn.\n        * rewrite <- H1. \n          apply lc_eval_correct in H.\n          apply H.\n        * unfold in_convex_polyhedron in IHconstraints.\n          apply IHconstraints.\n          apply H0. apply H1.   \n    }\n    {\n        intros H.\n        unfold polyhedron_eval_helper.\n        apply andb_true_intro.\n        split.\n        * apply lc_eval_correct.\n          unfold in_convex_polyhedron in H.\n          apply H. compute. left. reflexivity.\n        * apply IHconstraints.\n          unfold in_convex_polyhedron.\n          intros constraint HIn.\n          unfold in_convex_polyhedron in H.\n          apply H. unfold In. right. apply HIn.\n    }\nQed.\n\n(**\nConstruction of intersection of two polyhedra\n*)\nDefinition polyhedra_intersect {dim: nat} (p1 p2: ConvexPolyhedron dim) :=\n    match p1 with\n    | Polyhedron l1 =>\n        match p2 with \n        | Polyhedron l2 => \n            Polyhedron dim (l1 ++ l2)\n        end\n    end.\n\nTheorem polyhedra_intersect_correct:\n    forall dim (x: colvec dim) p1 p2,\n        in_convex_polyhedron x p1 /\\ in_convex_polyhedron x p2 ->\n        in_convex_polyhedron x (polyhedra_intersect p1 p2).\nProof.\n    intros dim x p1 p2 Hinboth.\n    induction p1. induction p2.\n    unfold in_convex_polyhedron.\n    unfold polyhedra_intersect.\n    intros constraint Hin.\n    unfold in_convex_polyhedron in Hinboth.\n    destruct Hinboth.\n    specialize (H constraint).\n    specialize (H0 constraint).\n    apply in_app_or in Hin.\n    destruct Hin.\n    - apply (H H1).\n    - apply (H0 H1).\nQed. \n\nEnd Polehydra.\n\n(** * Constructive piecewise affine functions *)\nSection PiecewiseLinear.\n\n(**\nPWAF Axiom\n\nFor all polehydra pairs (p1 p2) \\in body of PWAF f\nholds that if p1 and p2 intersect, the corresponding\naffine functions are the same, formally: for all\nx, such that x \\in p1 and x\\in p2 holds that\n\nA_1 * x + b_1 = A_2 * x + b_2\n\nwhere A_i, b_i are affine function parameters\nassociated with p_i\n\nThis guarantees that the output of PWAF is unique\n*)\nDefinition pwaf_univalence \n    {in_dim out_dim: nat}\n    (l: list (ConvexPolyhedron in_dim * ((matrix out_dim in_dim) * colvec out_dim)))\n    :=\n    ForallPairs (\n        fun e1 e2 =>\n            let p1 := fst e1 in\n            let p2 := fst e2 in\n                forall x,\n                    in_convex_polyhedron x p1 /\\ in_convex_polyhedron x p2 ->\n                    let M1 := fst (snd e1) in\n                    let b1 := snd (snd e1) in\n                    let M2 := fst (snd e2) in\n                    let b2 := snd (snd e2) in\n                    ((M1 * x) + b1 = (M2 * x) + b2)%M\n    ) l. \n\n(**\nPiecewise affine function (PWAF)\n\nA function is affine if it can be expressed as\nf(x) = A*x + b \nwhere A is a matrix and b is a vector.\n\nPWAF is defined by multiple polyhedra with an affine\nfunction attached to them. To compute f(x), the value of\nPWAF f on input x, one needs to find\na polyhedron to which x belongs and compute f(x)\nusing affine function.\n\nMembers:\n- body: list of polyhedra with an associated linear function\n- prop: PWAF univalence property\n\nHypothesis: this is a class of functions that can be\ndefined using a SMT solver.\n*)\nRecord PWAF (in_dim out_dim: nat): Type := mkPLF {\n    body: list (ConvexPolyhedron in_dim * ((matrix out_dim in_dim) * colvec out_dim));\n    prop: pwaf_univalence body;\n}.\n\n(**\nUseful invariant of pwaf_univalence: \nif pwaf_univalence holds for a list, it holds for tail of that list as well\n*)\nLemma pwaf_univalence_inv:\n    forall in_dim out_dim h t,\n    pwaf_univalence (in_dim:=in_dim) (out_dim:=out_dim) (h :: t) -> pwaf_univalence t.\nProof.\n    intros in_dim out_dim h t Hax.\n    unfold pwaf_univalence.\n    unfold ForallPairs.\n    intros a b HaIn HbIn x Hinpolyh.\n    unfold pwaf_univalence in Hax.\n    assert (ax1 := Hax).\n    unfold ForallPairs in ax1.\n    specialize (ax1 a b).\n    specialize (ax1 (in_cons h a t HaIn)).\n    specialize (ax1 (in_cons h b t HbIn)).\n    specialize (ax1 x Hinpolyh).\n    apply ax1.\nQed.\n\n(**\nA point x is in domain of PWAF f, if it has \na polehydron in body of f\n\nNote that PWAF is not total, it is not required\nfor polyhedra to cover entire R^n\n*)\nDefinition in_pwaf_domain {in_dim out_dim: nat}\n    (f: PWAF in_dim out_dim)\n    (x: colvec in_dim) :=  \n        exists body_el, \n            (In body_el (body in_dim out_dim f)) \n                /\\ in_convex_polyhedron x (fst body_el).\n\n(** \nA predicate that describes the value of TCPLF-SO f\nf(x) = f_x for a TCPLF-SO f\n*)\nDefinition is_pwaf_value {in_dim out_dim: nat} \n    (f: PWAF in_dim out_dim) \n    (x: colvec in_dim) \n    (f_x: colvec out_dim) :=\n    in_pwaf_domain f x ->\n    exists body_el,\n        In body_el (body in_dim out_dim f) /\\\n            let p := fst body_el in\n            let c := fst (snd body_el) in\n            let b := snd (snd body_el) in\n            in_convex_polyhedron x p /\\ Mplus (Mmult c x) b = f_x.\n\nFixpoint pwaf_eval_helper \n    {in_dim out_dim: nat}\n    (body: list (ConvexPolyhedron in_dim * ((matrix (T:=R) out_dim in_dim) * colvec out_dim)))\n    (x: colvec in_dim) \n    :=\n    match body with\n    | nil => None\n    | body_el :: next => \n        match body_el with\n        | (polyh, affine_f) =>\n            match polyhedron_eval x polyh with\n            | true => Some affine_f\n            | false => pwaf_eval_helper next x\n            end\n        end\n    end.\n\nLemma pwaf_eval_helper_some_in_domain:\n    forall in_dim out_dim (f: PWAF in_dim out_dim) x,\n        in_pwaf_domain f x ->\n        exists (body_el: (ConvexPolyhedron in_dim * _)),\n            pwaf_eval_helper (body in_dim out_dim f) x = Some (snd body_el).\nProof.\n    intros in_dim out_dim f x Hdomain.\n    induction f.\n    induction body0.\n    * destruct Hdomain.\n      simpl in H. destruct H. contradiction.\n    * simpl. induction a. induction b.\n      remember (polyhedron_eval x a) as polyh_eval.\n      induction polyh_eval.\n      - exists ((a, (a0, b))). reflexivity.\n      - specialize (IHbody0 (pwaf_univalence_inv in_dim out_dim (a,(a0,b)) body0 prop0)).\n        apply IHbody0.\n        unfold in_pwaf_domain.\n        destruct Hdomain.\n        exists (x0).\n        destruct H.\n        pose proof (in_inv H) as Hinv.\n        destruct Hinv.\n        - induction x0. induction b0.\n          simpl in H0.\n          apply polyhedron_eval_correct in H0.\n          apply pair_equal_spec in H1.\n          destruct H1.\n          apply pair_equal_spec in H2.\n          destruct H2.\n          rewrite H1 in Heqpolyh_eval.\n          rewrite H0 in Heqpolyh_eval.\n          discriminate.\n        - split.\n          * apply H1.\n          * apply H0.\nQed.\n\n(**\nFunction that directly computes the value of\nPWAF or outputs None if x is not in the domain\n*)\nDefinition pwaf_eval {in_dim out_dim: nat}\n    (f: PWAF in_dim out_dim)\n    (x: colvec in_dim) : option (colvec out_dim)\n    :=\n    match pwaf_eval_helper (body in_dim out_dim f) x with\n    | None => None\n    | Some (M,b) => Some (Mplus (Mmult M x) b)\n    end.\n\nTheorem pwaf_eval_correct :\n    forall in_dim out_dim (f: PWAF in_dim out_dim) x f_x,\n        pwaf_eval f x = Some f_x <-> \n        (in_pwaf_domain f x /\\ is_pwaf_value f x f_x).\nProof.\n    intros in_dim out_dim f x f_x.\n    unfold pwaf_eval.\n    unfold is_pwaf_value.\n    induction f.\n    induction body0.\n    * split.\n      - intros Hhelper.\n        unfold pwaf_eval_helper in Hhelper.\n        simpl in Hhelper. discriminate.\n      - intros Hvalue.\n        destruct Hvalue as [Hdomain Hvalue].\n        unfold in_pwaf_domain in Hdomain.\n        destruct Hdomain.\n        unfold In in H. simpl in H. destruct H. contradiction H.\n    * induction a. induction b.\n      remember (polyhedron_eval x a) as p_eval.\n      induction p_eval.\n      {\n        split.\n        - intros Hhelper.\n          split.\n          - unfold in_pwaf_domain.\n            exists (a, (a0, b)).\n            split.\n            * apply in_eq.\n            * symmetry in Heqp_eval.\n              rewrite polyhedron_eval_correct in Heqp_eval. \n              simpl. apply Heqp_eval.\n          - exists (a, (a0, b)).\n            split.\n            * simpl. left. reflexivity.\n            split.\n            * symmetry in Heqp_eval.\n                rewrite polyhedron_eval_correct in Heqp_eval. \n                simpl. apply Heqp_eval.\n            * simpl. unfold pwaf_eval_helper in Hhelper.\n                simpl in Hhelper.\n                rewrite <- Heqp_eval in Hhelper.\n                inversion Hhelper. reflexivity.\n        - intros Hinpwafdom.\n          destruct Hinpwafdom as [Hdomain Hinpwafdom].\n          specialize (Hinpwafdom Hdomain).\n          unfold pwaf_eval_helper. simpl.\n          rewrite <- Heqp_eval.\n          destruct Hinpwafdom.\n          destruct H. destruct H0.\n          rewrite <- H1. simpl.\n          unfold pwaf_univalence in prop0.\n          unfold ForallPairs in prop0.\n          assert (ax0_1 := prop0).\n          specialize (ax0_1 (a, (a0, b)) x0 (in_eq _ _) H x).\n          simpl in ax0_1. f_equal.\n          apply ax0_1.\n          split.\n          * symmetry in Heqp_eval.\n            apply polyhedron_eval_correct in Heqp_eval.\n            apply Heqp_eval.\n          * apply H0.               \n      }\n      {\n        assert (ax0_1:=prop0).\n        apply pwaf_univalence_inv in ax0_1.\n        specialize (IHbody0 ax0_1).\n        unfold pwaf_eval_helper. simpl.\n        rewrite <- Heqp_eval.\n        fold (pwaf_eval_helper body0 x).\n        destruct IHbody0. \n        split.\n        - intros Heval.\n          specialize (H Heval).\n          destruct H.\n          specialize (H1 H).\n          destruct H1.\n          split.\n          * exists x0. \n            split. \n            right. apply H1. apply H1.\n          * exists x0.\n            split. \n            right. apply H1. apply H1.\n        - intros Hexists.\n          destruct Hexists as [Hdomain Hexists].\n          specialize (Hexists Hdomain).\n          destruct Hexists.\n          destruct H1. destruct H2.\n          destruct H1.\n          * rewrite <- H1 in H2.\n            apply polyhedron_eval_correct in H2.\n            simpl in H2.\n            rewrite H2 in Heqp_eval. discriminate.\n          * apply H0.\n            split.\n            * unfold in_pwaf_domain.\n              exists x0. split.\n              - apply H1.\n              - apply H2. \n            * intros Hdomain2.\n              unfold in_pwaf_domain in Hdomain2.\n              destruct Hdomain2.\n              exists x1.\n              split. apply H4.\n              split. apply H4.\n              rewrite <- H3.\n              unfold pwaf_univalence in ax0_1.\n              unfold ForallPairs in ax0_1.\n              apply ax0_1.\n              apply H4.\n              apply H1.\n              split.\n              apply H4.\n              apply H2.\n      }\nQed.\n        \n(**\nA PWAF representation g of a real function f is a PWAF\nthat is equal to f everywhwere: for all x f(x) = g(x)\n*)\nDefinition pwaf_representation {in_dim out_dim: nat} \n    (f: colvec in_dim -> colvec out_dim) \n    (g: PWAF in_dim out_dim) :=\n    forall x, is_pwaf_value g x (f x).\n    \n(**\nA function is piecewise linear if there is a PWAF representations\n*)\nDefinition is_piecewise_linear {in_dim out_dim: nat} (f: colvec in_dim -> colvec out_dim) :=\n    exists pwaf,\n        pwaf_representation f pwaf.\n\n(**\nPWAF is total if the function is defined on all inputs in R^n\n*)\nDefinition is_total {in_dim out_dim: nat} (f: PWAF in_dim out_dim) :=\n    forall (x: colvec in_dim), in_pwaf_domain f x.\n\n(**\nA TPWAF is a total PWAF\n*)\nDefinition TPWAF (in_dim out_dim: nat) := \n    { f: PWAF in_dim out_dim | is_total f }.\n\nEnd PiecewiseLinear.\n\n(** * Example proof of piecewise linearity via construction\n\nWe prove that a simple ReLU function f([x1, x2]) = [ReLU(2 * x1 + x2), x2] is\npiecewise linear by constructing a corresponding TCPLF-SO \nusing definition from section PiecewiseLinear\n*)\n\nSection PiecewiseLinearExample.\n\n(**\nNaive/direct defintion of the example simple ReLU function\n\nf([x1, x2]) = [ReLU(2*x1 + x2), x2]\n*)\nDefinition simpleReLU (x: colvec 2) :=\n    let c := mk_colvec 2 (\n        fun i => \n            match i with\n            | 0 => 2\n            | 1 => 1\n            | _ => 0\n            end\n        ) in\n    let sum := dot c x in\n    let relu_result := if Rle_dec sum 0 then 0 else sum in\n    mk_colvec 2 (\n        fun i =>\n            match i with\n            | 0 => relu_result\n            | 1 => coeff_colvec 0 x 1\n            | _ => 0\n            end\n    ).\n\n(**\nConstruction of TCPLF for simple ReLU finction example\n\nTCPLF consists of:\n- A polyhedron for 2 * x1 + x2 <= 0\n- A polyhedron for 2 * x1 + x2 >= 0\n- Proofs of axioms\n*)\n\nDefinition c_vector := mk_colvec 2 (\n    fun i => \n        match i with\n        | 0 => 2\n        | 1 => 1\n        | _ => 0\n        end\n).\nDefinition minus_c_vector := scalar_mult (Ropp 1) c_vector.\n\nDefinition lincon1 := Constraint 2 c_vector 0.\nDefinition lincon2 := Constraint 2 minus_c_vector 0.\n\n(** Polyhedron for 2 * x1 + x2 <= 0 *)\nDefinition polyhedra1 := Polyhedron 2 [lincon1].\n\n(** Polyhedron for 2 * x1 + x2 >= 0 which is equivalent to\n    - 2 * x1 - x2 <= 0 *)\nDefinition polyhedra2 := Polyhedron 2 [lincon2].\nDefinition polyhedra_simpleReLU := [polyhedra1; polyhedra2].\n\n(** \nFunction body for TCPLF-SO of simple ReLU\n\nPolyhedron 1 -> [0, x2]     \nPolyhedron 2 -> [2 * x1 + x2, x2]\n*)\nDefinition matrix1 :=\n    mk_matrix 2 2 (\n        fun i j =>\n            match i, j with\n            | 0, 0 => 0\n            | 0, 1 => 0\n            | 1, 0 => 0\n            | 1, 1 => 1\n            | _, _ => 0\n            end\n    ).\n\nDefinition matrix2 :=\n    mk_matrix 2 2 (\n        fun i j =>\n            match i, j with\n            | 0, 0 => 2\n            | 0, 1 => 1\n            | 1, 0 => 0\n            | 1, 1 => 1\n            | _, _ => 0\n            end\n    ).\n\nDefinition simpleReLU_body := [\n    (polyhedra1, (matrix1, null_vector 2)); (polyhedra2, (matrix2, null_vector 2))\n].\n\n(**\nLemma: two polyhedra intersect at exactly 2*x1 + x2 = 0\n\nProof requires inference in hypothesis of intersection to\narrive at 2 * x1 + x2 <= 0 and 2 * x1 + x2 >= 0 which is then\nproven using Rle_anitsym\n*)\nLemma simpleReLU_polyhedra_intersection:\n    forall x, \n        in_convex_polyhedron x polyhedra1 /\\ in_convex_polyhedron x polyhedra2 ->\n        dot c_vector x = 0.\nProof.\n    intros x. simpl. \n    unfold satisfies_lc.\n    intros H. destruct H.\n    specialize (H lincon1). specialize (H0 lincon2).\n    unfold lincon1 in H. unfold lincon2 in H0.\n    assert (forall dim (c: LinearConstraint dim), c = c \\/ False). {\n        intros dim c. left. reflexivity.\n    }\n    specialize (H1 2%nat lincon1) as H11.\n    specialize (H1 2%nat lincon2) as H12.\n    apply H in H11. apply H0 in H12.\n    unfold minus_c_vector in H12.\n    rewrite dot_scalar_mult in H12.\n    apply Ropp_le_ge_contravar in H12.\n    rewrite Ropp_0 in H12.\n    rewrite Ropp_mult_distr_l in H12.\n    rewrite Ropp_involutive in H12.\n    rewrite Rmult_1_l in H12.\n    apply Rge_le in H12.\n    apply (Rle_antisym _ _ H11) in H12.\n    apply H12.\nQed.\n\n(**\nTheorem: univalence holds for simple ReLU. This means\nthat for two polyhedra of simple ReLU, the function is uniquely\ndefined at their intersection\n\nProof: we first destruct the goal sufficiently to create a proof\ngoal for each polyhedra pair and then show for each pair that\nthe function is the same using simple_ReLU_polyhedra_intersection\nlemma\n*)\nTheorem simpleReLU_prop:\n    pwaf_univalence simpleReLU_body.\nProof.\n    unfold pwaf_univalence.\n    unfold ForallPairs.\n    intros a b.\n    unfold In. simpl.\n    intros Ha Hb x Hintersect.\n    assert (Hmain: \n        in_convex_polyhedron x polyhedra1 /\\ in_convex_polyhedron x polyhedra2 ->\n            Mplus (Mmult matrix1 x) (null_vector 2) = \n            Mplus (Mmult matrix2 x) (null_vector 2)). {\n        intros Hinboth.   \n        repeat rewrite Mplus_null_vector.\n        repeat rewrite Mmult_dot_split.\n        unfold mk_colvec.\n        apply mk_matrix_ext.\n        intros i j Hi Hj.\n        induction i.\n        * assert (Hequal: mk_matrix 2 1 (fun i _ : nat => coeff_mat 0 matrix2 0 i) = c_vector). {\n            unfold c_vector. unfold mk_colvec.\n            unfold matrix2. reflexivity.\n            }\n            rewrite Hequal.\n            rewrite simpleReLU_polyhedra_intersection.\n            unfold dot. unfold Mmult.\n            rewrite coeff_mat_bij. unfold sum_n.\n            assert (Hzero: forall n m, sum_n_m (fun _ => zero) n m = 0). {\n            intros n m.\n            rewrite (sum_n_m_const_zero n m).\n            reflexivity.\n            }\n            rewrite <- (Hzero 0%nat 1%nat) at 1.\n            apply sum_n_m_ext_loc. \n            intros n Hn.\n            unfold transpose.\n            rewrite coeff_mat_bij.\n            unfold coeff_colvec.\n            rewrite coeff_mat_bij.\n            unfold matrix1.\n            rewrite coeff_mat_bij.\n            induction n.\n            - rewrite Rmult_0_l. reflexivity.\n            - induction n. rewrite Rmult_0_l. reflexivity.\n            rewrite Rmult_0_l. reflexivity. \n            lia. lia. lia. lia. lia. lia. lia. lia.\n            apply Hinboth.\n        * unfold matrix1. unfold matrix2. compute. reflexivity.\n    } \n    destruct Ha. destruct Hb.\n    * unfold Mplus. unfold mk_colvec. apply mk_matrix_ext.\n      intros i j Hi Hj.\n      rewrite <- H. rewrite <- H0. simpl. reflexivity.\n    * destruct H0.\n      - rewrite <- H. rewrite <- H0. simpl.\n        apply Hmain.\n        rewrite <- H in Hintersect.\n        rewrite <- H0 in Hintersect.\n        simpl in Hintersect.\n        apply Hintersect.\n      - contradiction.\n    * destruct H. destruct Hb.\n      { \n        rewrite <- H. rewrite <- H0. simpl.\n        symmetry. apply Hmain.\n        rewrite <- H in Hintersect.\n        rewrite <- H0 in Hintersect.\n        destruct Hintersect. split. apply H2. apply H1. \n      }\n      destruct H0.\n      {\n        rewrite <- H. rewrite <- H0. simpl.\n        reflexivity.\n      }\n      - contradiction.\n    - contradiction.\nQed.\n\n(**\nPWAF for simple ReLU\n*)\nDefinition simpleReLU_PWAF := mkPLF 2 2 simpleReLU_body simpleReLU_prop.\n\n(**\nTheorem: naive definition of simple ReLU example, simpleReLU, \nis represented by PWAF and hence piecewise linear\n\nProof: mostly utilizes Rle_dec (x <= y) \\/ ~ (x <= y) to \narrive at four cases for each possible polyhedra and if-statement result\nof the naive definition where we then show either contradiction or \nequality of function values\n*)\nTheorem simpleReLU_piecewise_linear:\n    is_piecewise_linear simpleReLU.\nProof.\n    unfold is_piecewise_linear.\n    exists simpleReLU_PWAF.\n    unfold pwaf_representation.\n    intros x.\n    unfold is_pwaf_value.\n    destruct (Rle_dec (dot c_vector x) 0).\n    * exists (polyhedra1, (matrix1, null_vector 2)).\n      split.\n      * simpl. left. reflexivity.  \n      * split.\n        - unfold in_convex_polyhedron.\n          simpl.  \n          intros constraint Hconstraint.\n          destruct Hconstraint.\n          rewrite <- H0.\n          unfold satisfies_lc. simpl.\n          apply r. contradiction.\n        - rewrite Mplus_null_vector. \n          rewrite Mmult_dot_split.\n          unfold simpleReLU.\n          fold c_vector.\n          destruct (Rle_dec (dot c_vector x) 0).\n          unfold mk_colvec. \n          apply mk_matrix_ext.\n          intros i j Hi Hj.\n          induction i.\n          rewrite dot_null_vector. reflexivity.\n          induction i.\n          * unfold dot.\n            unfold Mmult.\n            rewrite coeff_mat_bij.\n            unfold sum_n. unfold sum_n_m.\n            unfold Iter.iter_nat. simpl.\n            unfold transpose. unfold coeff_colvec.\n            unfold matrix1.\n            repeat rewrite coeff_mat_bij.\n            rewrite Rmult_0_l. rewrite Rplus_0_l.\n            rewrite Rmult_1_l. rewrite Rplus_0_r.\n            unfold coeff_colvec.\n            reflexivity.\n            lia. lia. lia. lia. lia. lia. lia. lia.\n            lia. lia. lia. lia. lia. lia. lia. contradiction. \n    * exists (polyhedra2, (matrix2, null_vector 2)).\n      split.\n      * simpl. right. left. reflexivity. \n      * apply Rnot_le_gt in n. \n        split.\n        - unfold in_convex_polyhedron.\n          intros constraint Hconstraint.\n          destruct Hconstraint.\n          rewrite <- H0.\n          unfold satisfies_lc. unfold lincon2.\n          unfold minus_c_vector.\n          rewrite dot_scalar_mult.\n          rewrite <- Ropp_mult_distr_l.\n          rewrite Rmult_1_l.\n          rewrite <- Ropp_0.\n          apply Ropp_le_contravar.\n          apply Rlt_le. apply n. \n          contradiction.\n        - rewrite Mplus_null_vector. \n          rewrite Mmult_dot_split.\n          unfold simpleReLU.\n          fold c_vector.\n          destruct (Rle_dec (dot c_vector x) 0).\n          apply Rle_not_gt in r. contradiction.\n          unfold mk_colvec. apply mk_matrix_ext.\n          intros i j Hi Hj.\n          induction i.\n          reflexivity.\n          induction i.\n          * unfold dot. unfold Mmult.\n          rewrite coeff_mat_bij.\n          unfold sum_n. unfold sum_n_m. unfold Iter.iter_nat.\n          simpl.\n          unfold transpose. unfold coeff_colvec.\n          unfold matrix1.\n          repeat rewrite coeff_mat_bij.\n          rewrite Rmult_0_l. rewrite Rplus_0_l.\n          rewrite Rmult_1_l. rewrite Rplus_0_r.\n          unfold coeff_colvec.\n          reflexivity.\n          lia. lia. lia. lia. lia. lia.\n          lia. lia. lia. lia. lia.\nQed.\n\n(**\nLemma: for all [x1, x2], 2 * x1 + x2 <= 0 or 2 * x1 + x2 >= 0\n\nProof: By specializing Rle_or_lt that tells that for real numbers\nholds (x <= y) or (y < x), we arrive that either 2 * x1 + x2 <= 0 or\n0 <= 2 * x1 + x2 that correspond to constraints of simple ReLU polyhedra\n*)\nLemma simpleReLU_full_R_split:\n    forall x,\n        satisfies_lc x lincon1 \\/ satisfies_lc x lincon2.\nProof.\n    intros x.\n    unfold satisfies_lc.\n    simpl.\n    unfold minus_c_vector.\n    rewrite dot_scalar_mult.\n    rewrite <- Ropp_0 at 2.\n    rewrite <- Ropp_mult_distr_l.\n    rewrite Rmult_1_l.\n    pose proof (Rle_or_lt (dot c_vector x) 0) as H.\n    destruct H.\n    * left. apply H.\n    * right. apply Ropp_ge_le_contravar. apply Rle_ge. apply Rlt_le. apply H.\nQed.\n\n(**\nTheorem: simple ReLU is a total function\n\nProof: follows mostly from the simple_ReLU_full_R_split lemma,\nwe just need to show what polyhedron contains constraint needed\n*)\nTheorem simpleReLU_total:\n    is_total simpleReLU_PWAF.\nProof.\n    unfold is_total.\n    unfold in_pwaf_domain.\n    intros x.\n    pose proof (simpleReLU_full_R_split x).\n    destruct H.\n    - exists (polyhedra1, (matrix1, null_vector 2)). split.\n      * simpl. left. reflexivity.\n      * unfold in_convex_polyhedron. simpl.\n        intros constraint Hconstraint.\n        destruct Hconstraint.\n        rewrite <- H0. apply H.\n        contradiction.\n    - exists (polyhedra2, (matrix2, null_vector 2)). split.\n      * simpl. right. left. reflexivity.\n      * unfold in_convex_polyhedron. simpl.\n        intros constraint Hconstraint.\n        destruct Hconstraint.\n        rewrite <- H0. apply H.\n        contradiction.\nQed.\n\nDefinition simpleReLU_TPWAF: TPWAF 2 2 := \n    exist _ simpleReLU_PWAF simpleReLU_total.\n\nEnd PiecewiseLinearExample. \n\n", "meta": {"author": "verinncoq", "repo": "formalizing-pwa", "sha": "0181d9fcc798f209c9a227c9662660e4acadbb7e", "save_path": "github-repos/coq/verinncoq-formalizing-pwa", "path": "github-repos/coq/verinncoq-formalizing-pwa/formalizing-pwa-0181d9fcc798f209c9a227c9662660e4acadbb7e/piecewise_affine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291502, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7197080142422645}}
{"text": "Require Import Logic.Eqdep.\nRequire Export Relations.Relation_Definitions.\nRequire Export Wellfounded.\nRequire Import Lists.SetoidList.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import Utf8.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection relations.\n\nVariable A : Type.\n\n(* Inverse relation *)\nDefinition inv (R : relation A) : relation A := fun x y => R y x.\n\n(* Strict subrelation *)\nDefinition strict (R : relation A) : relation A :=\n  fun x y => R x y /\\ x <> y.\n\nDefinition ascending_chain (R : relation A)\n  := well_founded (strict (inv R)).\n\nEnd relations.\n\nSection SymProduct.\n\nVariable A : Type.\nVariable B : Type.\nVariable leA : relation A.\nVariable leB : relation B.\n\nInductive symprod : relation (A * B) :=\n  | left_sym :\n    forall x x', leA x x' ->\n                 forall y, symprod (x, y) (x', y)\n  | right_sym :\n    forall y y', leB y y' ->\n                 forall x, symprod (x, y) (x, y').\n\nVariable leA_wf : well_founded leA.\nVariable leB_wf : well_founded leB.\n\nLemma symprod_wf : well_founded symprod.\nProof.\nintros [a b].\nrevert b.\napply Acc_ind with (R:=leA) (x:=a); auto; clear a.\nintros a _ Ha b.\napply Acc_ind with (R:=leB) (x:=b); auto; clear b.\nintros b _ Hb.\napply Acc_intro; intros [x y] Hxy.\ninversion Hxy; subst; now firstorder.\nQed.\n\nEnd SymProduct.\n\nSection LexProduct.\n\nVariable A : Type.\nVariable B : Type.\nVariable leA : relation A.\nVariable leB : relation B.\n\nInductive lexprod : relation (A * B) :=\n  | left_lex :\n    forall x x' y y',\n      leA x x' -> lexprod (x,y) (x',y')\n  | right_lex :\n    forall x y y',\n      leB y y' -> lexprod (x,y) (x,y').\n\nVariable leA_wf : well_founded leA.\nVariable leB_wf : well_founded leB.\n\nLemma lexprod_wf : well_founded lexprod.\nProof.\nintros [a b].\nassert (Ha : Acc leA a) by auto.\nrevert b.\napply Acc_ind with (R:=leA) (x:=a); auto; clear dependent a.\nintros a _ Ha b.\napply Acc_ind with (R:=leB) (x:=b); auto; clear b.\nintros b _ Hb.\napply Acc_intro; intros [x y] Hxy.\ninversion Hxy; subst; now firstorder.\nQed.\n\nEnd LexProduct.\n\nSection vector_defs.\n\nVariable A : Type.\n\nInductive vector : nat -> Type :=\n| vec_nil : vector 0\n| vec_cons : forall n, A -> vector n -> vector (S n).\n\nDefinition eq_vec := eq_dep nat vector.\n\nFixpoint vector_of (l : list A) : {n : nat & vector n} :=\n  match l with\n    | nil => existT _ 0 vec_nil\n    | cons h t =>\n        let (n,l) := vector_of t in\n          existT _ (S n) (vec_cons h l)\n  end.\n\nFixpoint list_of n (v : vector n) : list A :=\n  match v with\n    | vec_nil => nil\n    | vec_cons _ h t => cons h (list_of t)\n  end.\n\nLemma len_vector_of (l : list A) :\n  projT1 (vector_of l) = length l.\nProof.\ninduction l as [| h t IH]; auto.\nsimpl. destruct (vector_of t) as [n v]; simpl; simpl in IH.\nnow rewrite IH.\nQed.\n\nDefinition head' n (v : vector n) :=\n  match v in vector x return lt 0 x -> A with\n    | vec_nil =>\n        fun H : lt O O => (False_rect A (lt_irrefl O H))\n    | vec_cons n' h _ =>\n        fun H : lt 0 (S n') => h\n  end.\n\nDefinition head n (v : vector (S n)) :=\n  head' (n:=S n) v (lt_O_Sn n).\n\nDefinition tail n (v : vector n) :=\n  match v in vector x return vector (pred x) with\n    | vec_nil => vec_nil\n    | vec_cons _ _ v' => v'\n  end.\n\nFixpoint nth_aux n (v : vector n) i :\n  lt i n -> A :=\n  match v, i with\n    | vec_nil, _ => fun (H : i < 0) => False_rect A (lt_n_0 i H)\n    | vec_cons n' h _, 0 => fun (H : 0 < S n') => h\n    | vec_cons n' _ t, S i' =>\n        fun (H : S i' < S n') => @nth_aux n' t i' (lt_S_n _ _ H)\n  end.\n\nDefinition nth n (v : vector n) (i : {i | i < n}) :=\n  nth_aux v (proj2_sig i).\n\n\nLemma empty_dep n (v : vector n) :\n  n = O -> @eq_vec n v 0 vec_nil.\nProof.\nintros e.\ndependent inversion v.\n- easy.\n- now subst.\nQed.\nHint Resolve empty_dep.\n\nLemma empty (v : vector O) : v = vec_nil.\nProof.\napply (eq_dep_eq nat vector O).\nnow apply empty_dep.\nQed.\nHint Resolve empty.\n\nLemma non_empty_dep n (v : vector (S n)) :\n  {h : A & {t : vector n |\n            @eq_vec (S n) v (S n) (vec_cons h t)}}.\nProof.\ndependent inversion_clear v with\n  (fun n' (v: vector n') =>\n     {a : A & {v' : vector n |\n               @eq_vec n' v (S n) (vec_cons a v')}}).\nnow exists a, v0.\nQed.\n\nLemma non_empty n (v :vector (S n)) :\n  {a : A & {t : vector n | v = vec_cons a t}}.\nProof.\nassert (H := non_empty_dep v).\ndestruct H as [h [t H]].\nexists h, t. now apply eq_dep_eq.\nQed.\n\nLemma split_vec n (v : vector (S n)) :\n  v = vec_cons (head v) (tail v).\nProof.\ndestruct (non_empty v) as [h [t H]].\nnow subst.\nQed.\n\nLemma nth_0_is_head n (v : vector (S n)) :\n  head v = nth v (exist _ 0 (lt_0_Sn n)).\nProof.\nnow rewrite (split_vec v).\nQed.\n\nLemma nth_irrel n (v : vector n) i (H H' : i < n) :\n  nth_aux v H = nth_aux v H'.\nProof.\nrevert i H H'.\ninduction n as [| n IHn].\n- easy.\n- rewrite (split_vec v).\n  destruct i as [| i]; auto.\n  intros H H'.\n  now simpl.\nQed.\n\nLemma nth_cons n (v : vector n) a i H (Hi : i > 0) :\n  exists H',\n    @nth_aux _ (vec_cons a v) i H = @nth_aux _ v (i-1) H'.\nProof.\ndestruct i; [easy |].\nsimpl in H. simpl.\nrevert H. rewrite <- minus_n_O.\nintros H.\nassert (H' : i < n) by omega.\nexists H'. now apply nth_irrel.\nQed.\n\nEnd vector_defs.\n\nSection search.\n\nVariable A : Type.\n\nFixpoint has n (v : vector A n) a : Prop :=\n  match v with\n    | vec_nil => False\n    | vec_cons n' h t => h = a \\/ has t a\n  end.\n\nLemma has_nil a : ~ has (vec_nil A) a.\nProof.\neasy.\nQed.\n\nLemma has_cons a n h (t : vector A n) :\n  a <> h -> has (vec_cons h t) a -> has t a.\nProof.\nsimpl. intros ne H. now destruct H; try congruence.\nQed.\n\nLemma InA_has l a :\n  InA eq a l ->\n  let (_, v) := vector_of l in has v a.\nProof.\ninduction l as [| h t IH].\n- easy.\n- intros H.\n  inversion H; subst.\n  + simpl.\n    destruct (vector_of t) as [nt vt].\n    now left.\n  + simpl.\n    destruct (vector_of t) as [nt vt].\n    now right; auto.\nQed.\n\nVariable eq_dec : forall a a' : A, {a = a'} + {a <> a'}.\n\nFixpoint find'_aux n (v : vector A n) a count :=\n  match v return has v a -> nat with\n    | vec_nil =>\n        fun H : has (vec_nil A) a => False_rect nat (has_nil H)\n    | vec_cons n' h t =>\n        fun H : has (vec_cons h t) a =>\n          match eq_dec a h with\n            | left _ => count\n            | right ne =>\n                @find'_aux n' t a (S count) (has_cons ne H)\n          end\n  end.\n\nDefinition find' n (v : vector A n) a := @find'_aux n v a 0.\n\nLemma find'_aux_irrel n (v : vector A n) a c (H1 H2 : has v a) :\n  find'_aux c H1 = find'_aux c H2.\nProof.\nrevert c H1 H2.\ninduction v as [| n' h t IH].\n- intros c H1 H2. now elim (has_nil H1).\n- intros c H1 H2.\n  unfold find'. unfold find' in IH.\n  simpl.\n  now destruct (eq_dec a h).\nQed.\n\nLemma find'_aux_shift n (v : vector A n) a c (H : has v a) :\n  find'_aux c H = find'_aux 0 H + c.\nProof.\nrevert c.\ninduction v as [| n' h t IH].\n- now elim (has_nil H).\n- intros c. simpl.\n  destruct (eq_dec a h); auto.\n  rewrite IH with (c:=S c).\n  rewrite IH with (c:=1).\n  omega.\nQed.\n\nLemma find'_irrel n (v : vector A n) a (H1 H2 : has v a) :\n  find' H1 = find' H2.\nProof.\nunfold find'.\nnow apply find'_aux_irrel.\nQed.\n\nLemma find'_cons_0 n (v : vector A n) a H :\n  @find' _ (vec_cons a v) a H = 0.\nProof.\nunfold find', find'_aux. simpl.\nnow destruct (eq_dec a a); congruence.\nQed.\n\nLemma find'_cons_1 n (v : vector A n) h a Hcons H (Ha : a <> h) :\n  @find' _ (vec_cons h v) a Hcons = S (@find' _ v a H).\nProof.\nunfold find'. simpl.\ndestruct (eq_dec a h) as [e | ne]; [easy |].\nrewrite find'_aux_shift.\nrewrite find'_aux_irrel with (H2:=H).\nomega.\nQed.\n\nLemma find'_cons_1_bis n (v : vector A n) h a H (Ha : a <> h) :\n  exists H', @find' _ (vec_cons h v) a H = @find' _ v a H' + 1.\nProof.\nunfold find'. simpl.\ndestruct (eq_dec a h) as [e | ne]; [easy |].\nrewrite find'_aux_shift.\nnow eauto.\nQed.\n\nLemma find'_cons_2 n (v : vector A n) h a H (Ha : a <> h) :\n  @find' _ (vec_cons h v) a H > 0.\nProof.\ndestruct (find'_cons_1_bis H Ha) as [H' e].\nrewrite e; now auto with arith.\nQed.\n\nLemma find'_aux_le n (v : vector A n) a (H : has v a) c :\n  find'_aux c H < n + c.\nProof.\nrevert c.\ninduction v as [| n' h t IH].\n- now elim (has_nil H).\n- simpl.\n  destruct (eq_dec a h).\n  + now auto with arith.\n  + simpl. intros c.\n    now rewrite plus_n_Sm.\nQed.\n\nLemma find'_le n (v : vector A n) a (H : has v a) : find' H < n.\nProof.\nunfold find.\nrewrite <- (plus_0_r n).\nnow apply find'_aux_le.\nQed.\n\nDefinition find n (v : vector A n) a (H : has v a) : {i | i < n}.\nexists (find' H).\nnow apply find'_le.\nDefined.\n\nLemma nth_aux_find n (v : vector A n) a (Ha : has v a) H :\n    @nth_aux A _ v (find' Ha) H = a.\nProof.\ninduction v as [| n' h t IH].\n- now elim (has_nil Ha).\n- destruct (eq_dec a h) as [e | ne] eqn:E; [subst h |].\n  + destruct (@find' _ (@vec_cons A _ a t) a Ha) eqn:Habs; auto.\n    now rewrite find'_cons_0 in Habs.\n  + destruct (@find' (S n') (@vec_cons A n' h t) a Ha) eqn:Hcons.\n    * assert (Htmp := find'_cons_2 Ha ne).\n      now rewrite Hcons in Htmp.\n    * destruct (nth_cons t h H) as [H' e]; auto with arith.\n      rewrite e; clear e.\n      revert H'. simpl. rewrite <- (minus_n_O n).\n      intros H'.\n      assert (Htmp := find'_cons_1 Ha (has_cons ne Ha) ne).\n      rewrite Htmp in Hcons; clear Htmp.\n      inversion Hcons as [H0]; clear Hcons.\n      now subst n.\nQed.\n\nLemma nth_find n (v : vector A n) a (Ha : has v a) :\n    @nth A _ v (find Ha) = a.\nProof.\nunfold nth, find. simpl.\nnow apply nth_aux_find.\nQed.\n\nEnd search.\n\nSection map.\n\nVariables A B : Type.\n\nFixpoint map n (v : vector A n) (f : A -> B) : vector B n :=\n  match v with\n    | vec_nil => vec_nil B\n    | vec_cons n' h t => vec_cons (f h) (map t f)\n  end.\n\nLemma nth_map n (v : vector A n) (f : A -> B) :\n  forall i : {i | i < n},\n    nth (map v f) i = f (nth v i).\nProof.\nintros i.\ninduction v.\n- now elim i.\n- destruct i as [i Hi].\n  revert Hi. destruct i as [| i]; auto.\n  intros Hi.\n  simpl.\n  apply (IHv (exist _ i (lt_S_n _ _ Hi))).\nQed.\n\nLemma map_nth n (va : vector A n) (vb : vector B n) (f : A -> B) :\n  (forall i : {i | i < n}, f (nth va i) = nth vb i) ->\n  map va f = vb.\nProof.\ninduction va.\n- now rewrite (empty vb).\n- intros H.\n  rewrite (split_vec vb).\n  simpl.\n  f_equal.\n  + specialize H with (exist _ 0 (lt_0_Sn _)).\n    unfold nth in H. simpl in H.\n    now rewrite nth_0_is_head.\n  + eapply IHva.\n    intros [i Hi].\n    rewrite (split_vec vb) in H.\n    specialize H with (exist _ (S i) (lt_n_S _ _ Hi)).\n    unfold nth in H. simpl in H.\n    unfold nth. simpl.\n    rewrite (nth_irrel va)\n            with (H':=lt_S_n i n (lt_n_S i n Hi)).\n    now rewrite (nth_irrel (tail vb))\n            with (H':=lt_S_n i n (lt_n_S i n Hi)).\nQed.\n\nEnd map.\n\nSection orderings.\n\nVariable A : Type.\nVariable eq_dec : forall x y : A, {x = y} + {x <> y}.\n\nVariable leA : relation A.\nVariable leA_wf : well_founded leA.\n\n(* Pointwise ordering on vectors *)\nInductive lp_vector : forall n, relation (vector A n) :=\n| lp_nil : @lp_vector 0 (vec_nil A) (vec_nil A)\n| lp_cons :\n    forall a a' n v v',\n      leA a a' ->\n      @lp_vector n v v' ->\n      @lp_vector (S n) (vec_cons a v) (vec_cons a' v').\n\nLemma lp_vector_nth n (v w : vector A n) :\n  (forall i : {i | i < n}, leA (nth v i) (nth w i)) ->\n  lp_vector v w.\nProof.\ninduction v.\n- intros _. rewrite (empty w).\n  now apply lp_nil.\n- intros H.\n  rewrite (split_vec w).\n  apply lp_cons.\n  + specialize H with (exist _ 0 (lt_0_Sn _)).\n    unfold nth in H. simpl in H.\n    now rewrite nth_0_is_head.\n  + apply IHv.\n    intros [i Hi].\n    rewrite (split_vec w) in H.\n    specialize H with (exist _ (S i) (lt_n_S _ _ Hi)).\n    unfold nth in H. simpl in H.\n    unfold nth. simpl.\n    rewrite (nth_irrel v)\n            with (H':=lt_S_n i n (lt_n_S i n Hi)).\n    now rewrite (nth_irrel (tail w))\n            with (H':=lt_S_n i n (lt_n_S i n Hi)).\nQed.\n\n(* Lexicographical ordering on vectors *)\nInductive lex_vector : forall n, relation (vector A n) :=\n| lex_vector_left :\n    forall a a' n v v',\n      leA a a' ->\n      @lex_vector (S n) (vec_cons a v) (vec_cons a' v')\n| lex_vector_right :\n    forall a n v v',\n      @lex_vector n v v' ->\n      @lex_vector (S n) (vec_cons a v) (vec_cons a v').\n\nLemma lex_vector_Acc_step n :\n  (forall v, Acc (@lex_vector n) v) ->\n  forall a v,\n    Acc (@lex_vector (S n)) (vec_cons a v).\nProof.\nintros Hn a.\napply Acc_ind with (R := leA) (x:=a); auto; clear a.\nintros a _ Ha.\nintros v.\napply Acc_ind with (R := lex_vector (n:=n)) (x:=v); auto; clear v.\nintros v _ Hv.\nconstructor.\nintros w Hw. inversion Hw; subst.\n- apply inj_pair2 in H0.\n  apply inj_pair2 in H3.\n  now subst; auto.\n- apply inj_pair2 in H0.\n  apply inj_pair2 in H3.\n  now subst; auto.\nQed.\n\nLemma lex_vector_0_wf : well_founded (@lex_vector 0).\nProof.\nintros v.\ndependent inversion v.\nconstructor.\nintros w Hw.\nnow inversion Hw.\nQed.\n\nLemma lex_vector_wf_step n :\n  well_founded (@lex_vector n) ->\n  well_founded (@lex_vector (S n)).\nProof.\nintros H.\nintros v.\ndependent inversion v as [| ? a v']; subst.\nconstructor.\nintros w Hw.\ndependent inversion w as [| ? b w']; subst.\nnow apply lex_vector_Acc_step.\nQed.\n\nTheorem lex_vector_wf n : well_founded (@lex_vector n).\nProof.\ninduction n as [| n IHn].\n- now apply lex_vector_0_wf.\n- now apply lex_vector_wf_step.\nQed.\n\nEnd orderings.\n\nSection lp_ascending.\n\nVariable A : Type.\nVariable eq_dec : forall x y : A, {x = y} + {x <> y}.\n\nVariable leA : relation A.\n\nLemma lp_vector_to_lex_vector_inv n (v v' : vector A n) :\n  strict (inv (lp_vector leA (n:=n))) v v' ->\n  lex_vector (strict (inv leA)) v v'.\nProof.\ninduction v.\n- rewrite (empty v').\n  intros H. inversion H. now firstorder.\n- rewrite (split_vec v').\n  intros H.\n  destruct H as [H Hconsv].\n  case (eq_dec a (head v')) as [e | ne].\n  + rewrite <- e.\n    apply lex_vector_right.\n    apply IHv; clear IHv.\n    rewrite <- e in Hconsv.\n    unfold inv in *.\n    split.\n    * inversion H; subst.\n      apply inj_pair2 in H2.\n      apply inj_pair2 in H5.\n      now subst.\n    * intros Hv. now subst; auto.\n  + apply lex_vector_left.\n    split; auto.\n    unfold inv in *.\n    now inversion H; subst.\nQed.\n\nLemma asc_lp_vector n :\n  ascending_chain leA ->\n  ascending_chain (lp_vector leA (n:=n)).\nProof.\nunfold ascending_chain.\nintros H.\napply wf_incl with (@lex_vector A (strict (inv leA)) n).\n- unfold inclusion. now apply lp_vector_to_lex_vector_inv.\n- now apply lex_vector_wf.\nQed.\n\nEnd lp_ascending.\n", "meta": {"author": "karbyshev", "repo": "solvers", "sha": "db663eb55f7b75b72801058ad37be9e76220de41", "save_path": "github-repos/coq/karbyshev-solvers", "path": "github-repos/coq/karbyshev-solvers/solvers-db663eb55f7b75b72801058ad37be9e76220de41/Rels.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7196788055760789}}
{"text": "Require Export Lci.\nRequire Export misc.\nRequire Export Arith.\nRequire Export groups.\nRequire Export rings.\nRequire Export ZArith.\nRequire Import Omega.\n\n(* Addition on Z, (Z, +) is a group *)\n\nDefinition IdZ (x : Z) := True.\n\nTheorem Z_group : is_group Z IdZ Zplus 0%Z Zopp.\nProof.\nsplit.\nred in |- *; trivial.\nsplit.\nred in |- *; auto with zarith.\nsplit; red in |- *.\nsplit; auto with zarith.\nunfold IdZ in |- *; trivial.\nsplit; auto with zarith.\nQed.\n\n(* Multiplication on Z, (Z, +, *, 0, 1) is a unitary commutative ring *)\n\nTheorem Z_ring : is_ring Z IdZ Zplus Zmult 0%Z Zopp.\nProof.\nunfold is_ring in |- *.\nsplit.\nred in |- *; auto with zarith.\nsplit. exact Z_group.\nsplit. unfold intern in |- *. intros. exact I.\nsplit; red in |- *; auto with zarith.\nQed.\n\nTheorem Z_unitary_commutative_ring :\n is_unitary_commutative_ring Z IdZ Zplus Zmult 0%Z 1%Z Zopp.\nProof.\nunfold is_unitary_commutative_ring in |- *.\nsplit. exact Z_ring.\nsplit.\nred in |- *; auto with zarith.\nsplit.\nunfold IdZ in |- *; trivial.\nsplit; auto with zarith.\nQed.\n\n(* Z is an integral domain *)\n\nTheorem integrityZ : integrity Z Zmult 0%Z.\nProof.\nunfold integrity in |- *.\nintros a b; elim a.\n(* OZ *)\nintros; left; reflexivity.\n(* pos n *)\nintros; right.\ngeneralize H; clear H; simpl in |- *; case b; intros; inversion H; trivial.\n(* neg n *)\nintros; right.\ngeneralize H; clear H; simpl in |- *; case b; intros; inversion H; trivial.\nQed.\n\nLemma inversibleZ :\n forall x : Z, inversible Z Zmult 1%Z x -> x = 1%Z \\/ x = (-1)%Z.\nProof.\nunfold inversible in |- *.\nintros.\ninversion_clear H.\ninversion_clear H0.\nclear H1.\ngeneralize H; clear H.\n(* [x>0] *)\nelim (Z_lt_ge_dec 0 x); intros. \nleft.\nelim (Z_le_lt_eq_dec 1 x); auto with zarith; intros.\ncut (1 > x0)%Z; intros.\nabsurd (0 < x0)%Z; intros; auto with zarith.\napply Zgt_lt.\napply Zmult_gt_0_reg_l with x; auto with zarith.\napply Zmult_gt_reg_r with x; auto with zarith.\nrewrite Zmult_1_l; rewrite Zmult_comm; auto with zarith.\n(*[x<0] *)\nelim (Z_le_lt_eq_dec x 0); auto with zarith; intros.\nclear b.\nright.\nelim (Z_le_lt_eq_dec 1 (- x)); auto with zarith; intros.\ncut (1 > - x0)%Z; intros.\nabsurd (0 < - x0)%Z; intros; auto with zarith.\napply Zgt_lt.\napply Zmult_gt_0_reg_l with (- x)%Z; auto with zarith.\nrewrite Zopp_mult_distr_l_reverse; rewrite <- Zopp_mult_distr_r;\n auto with zarith.\napply Zmult_gt_reg_r with (- x)%Z; auto with zarith.\nrewrite Zmult_1_l; rewrite Zmult_comm.\nrewrite Zopp_mult_distr_l_reverse; rewrite <- Zopp_mult_distr_r;\n auto with zarith.\n(* [x=0] *)\nrewrite b0 in H; simpl in H; inversion H.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "zchinese", "sha": "dcf20f2c95bcd026b1c49d658cd6ae5283b43655", "save_path": "github-repos/coq/coq-contribs-zchinese", "path": "github-repos/coq/coq-contribs-zchinese/zchinese-dcf20f2c95bcd026b1c49d658cd6ae5283b43655/Zstruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7196788055760789}}
{"text": "Require Import Arith Omega Coq.Logic.Classical List.\n\nSection minExists.\n  Context {P : nat -> Prop}.\n  Lemma leastOrNone x :\n    (exists x, P x /\\ forall y, y < x -> ~ P y) \\/\n                                                forall y, y <= x -> ~ P y.\n  Proof.\n    induction x.\n    destruct (classic (P 0)) as [P0 | notP0].\n    left; exists 0; constructor; [intuition | intros; omega].\n    right; intros y le; assert (yEq0: y = 0) by omega; rewrite yEq0 in *; intuition.\n    destruct IHx as [ex | notEx].\n    left; assumption.\n    destruct (classic (P (S x))) as [PSx | notPSx].\n    left; exists (S x); constructor; [assumption | intros y lt; assert (y <= x) by omega; firstorder].\n    right; intros; assert (opts: y <= x \\/ y = S x) by omega. destruct opts; [firstorder | congruence].\n  Qed.\n\n  Theorem minExists (ex: exists x, P x) : (exists x, P x /\\ forall y, y < x -> ~ P y).\n  Proof.\n    destruct ex as [x Px].\n    pose proof (leastOrNone x) as exOrNot.\n    destruct exOrNot.\n    assumption.\n    assert (eq: x <= x) by omega.\n    firstorder.\n  Qed.\n\n  Theorem minExistsPower {x} (Px: P x): (exists y, y <= x /\\ P y /\\ forall z, z < y -> ~ P z).\n  Proof.\n    assert (ex: exists x, P x) by firstorder.\n    pose proof (minExists ex) as exMin.\n    clear ex.\n    destruct exMin as [t rest].\n    destruct rest as [Pt notBelow].\n    exists t.\n    intuition.\n    destruct (classic (t <= x)).\n    assumption.\n    assert (x < t) by omega.\n    firstorder.\n  Qed.\nEnd minExists.\n\nSection maxExists.\n  Context {P: nat -> Prop}.\n  Theorem maxExists {max} (exPx: exists x, x <= max /\\ P x): exists x, x <= max /\\ P x /\\ forall y, S x <= y <= max -> ~ P y.\n  Proof.\n    destruct exPx as [x rest].\n    destruct rest as [xLeMax Px].\n    pose (fun x => P (max - x)) as Q.\n    pose (max - x) as diff.\n    assert (xEq: max - (max - x) = x) by omega.\n    assert (Qdiff: Q diff) by (unfold Q; unfold diff; rewrite xEq in *; intuition).\n    assert (exQdiff: exists d, Q d) by (exists diff; intuition).\n    pose proof (minExists exQdiff) as qMin.\n    destruct qMin as [y rest].\n    destruct rest as [leDiff noLower].\n    exists (max - y).\n    constructor.\n    omega.\n    constructor.\n    auto.\n    intros y0 complx.\n    assert (lt: max - y0 < y) by omega.\n    unfold Q in noLower.\n    specialize (noLower (max - y0) lt).\n    assert (eq: max - (max - y0) = y0) by (assert (e: y0 <= max) by omega; generalize e; clear; intuition).\n    rewrite eq in noLower.\n    intuition.\n  Qed.\n\n  Theorem maxExists' {maxi} (exPx: exists x, x < maxi /\\ P x): exists x, x < maxi /\\ P x /\\ forall y, x < y < maxi -> ~ P y.\n  Proof.\n    destruct exPx as [x [contra Px]].\n    destruct maxi.\n    omega.\n    assert (exPx': exists x, x <= maxi /\\ P x) by (exists x; constructor; [omega | intuition]).\n    pose proof (maxExists exPx') as this.\n    destruct this as [x' [cond1 [Px' forally]]].\n    exists x'.\n    constructor.\n    omega.\n    constructor.\n    intuition.\n    intros y cond.\n    assert (S x' <= y <= maxi) by omega.\n    firstorder.\n  Qed.\n\n  Theorem maxExistsPower {max x} (xLeMax: x <= max) (Px: P x) : (exists y, x <= y <= max /\\ P y /\\ forall z, S y <= z <= max -> ~ P z).\n  Proof.\n    assert (exX: exists x, x <= max /\\ P x) by firstorder.\n    pose proof (maxExists exX) as maxExX.\n    destruct maxExX as [t rest].\n    destruct rest as [tLeMax rest].\n    destruct rest as [Pt noLower].\n    exists t.\n    destruct (classic (x <= t)) as [xLeT | xGtT].\n    firstorder.\n    assert (hyp: S t <= x <= max) by omega.\n    firstorder.\n  Qed.\nEnd maxExists.\n\nSection Induction.\n  Context {P: nat -> Type}.\n  Hypothesis case_0: P 0.\n  Hypothesis case_n: forall {t}, (forall ti, ti <= t -> P ti) -> P (S t).\n\n  Theorem ind t: P t.\n  Proof.\n    assert (q0: forall ti, ti <= 0 -> P ti) by \n        (intros ti ti_le_0; assert (rew: ti = 0) by omega; rewrite rew; assumption).\n    assert (qIHt: forall t, (forall ti, ti <= t -> P ti) -> (forall ti, ti <= S t -> P ti)).\n    intros t0 lt_t0.\n    specialize (case_n t0 lt_t0).\n    intros ti ti_le_S_t0.\n    pose proof (le_lt_eq_dec ti (S t0) ti_le_S_t0) as options.\n    destruct options as  [hyp|new].\n    firstorder.\n    rewrite new.\n    assumption.\n    assert (Hyp: forall t, (forall ti, ti <= t -> P ti)) by (\n                                                            induction t0; firstorder).\n    specialize (Hyp t t).\n    assert (fct: t <= t) by omega.\n    firstorder.\n  Qed.\nEnd Induction.\n\n\n    Theorem listNeq: forall {A} (x: A) l, x :: l <> l.\n      unfold not; intros A x l eq.\n      assert (H: length (x :: l) = length l) by (f_equal; assumption).\n      unfold length in *.\n      remember ((fix length (l : list A) : nat :=\n            match l with\n            | nil => 0\n            | _ :: l' => S (length l')\n            end) l) as y.\n      generalize H; clear.\n      intros neq.\n\n      assert (H: S y <> y) by auto.\n      firstorder.\n    Qed.\n\n    Theorem listCond1: forall {A} (l: list A), l <> nil -> length l = S (length (tl l)).\n    Proof.\n      intros A l lgd.\n      unfold tl.\n      destruct l.\n      firstorder.\n      unfold length.\n      reflexivity.\n    Qed.\n\n    Theorem listCond2: forall {A} (l: list A), l <> nil -> length l = S (length (removelast l)).\n    Proof.\n      intros A l lgd.\n      induction l.\n      firstorder.\n      destruct l.\n      unfold length.\n      reflexivity.\n      unfold length in *.\n      f_equal.\n      assert (H: removelast (a :: a0 :: l) = a :: removelast (a0 :: l)) by\n          (\n            unfold removelast;\n            reflexivity).\n      rewrite H; clear H.\n      assert (H: a0 :: l <> nil) by discriminate.\n      specialize (IHl H).\n      assumption.\n    Qed.\n\n    Theorem notInRemove: forall {A} (a: A) l, In a (removelast l) -> In a l.\n    Proof.\n      intros A a l inl.\n      induction l.\n      unfold removelast in *; simpl in *.\n      assumption.\n      unfold removelast in inl.\n      destruct l.\n      unfold In in *.\n      firstorder.\n      unfold In in inl.\n      destruct inl.\n      unfold In.\n      left.\n      assumption.\n      specialize (IHl H).\n      unfold In.\n      right.\n      assumption.\n    Qed.\n\n    Theorem notInTail: forall {A} (a: A) l, In a (tl l) -> In a l.\n    Proof.\n      intros A a l inl.\n      destruct l.\n      unfold tl in inl; assumption.\n      unfold tl in inl.\n      unfold In.\n      right.\n      assumption.\n    Qed.\n\n    Theorem eachProd: forall {A B} {a b: A} {c d: B}, (a, c) = (b, d) -> a = b /\\ c = d.\n    Proof.\n      intros A B a b c d eq.\n      injection eq.\n      auto.\n    Qed.\n\n    Theorem combNil: forall {A} B (l : list A), combine l (@nil B) = nil.\n    Proof.\n      intros A B l.\n      destruct l; unfold combine; reflexivity.\n    Qed.\n\n    Theorem removeCombine: forall {A B} (l1: list A) (l2: list B),\n                             removelast (combine l1 l2) = combine (removelast l1)\n                                                                  (removelast l2).\n    Proof.\n      intros A B l1.\n      induction l1.\n      intros l2.\n      reflexivity.\n      intros l2.\n      destruct l2.\n      simpl.\n      pose proof (combNil B match l1 with\n           | nil => nil\n           | _ :: _ => a :: removelast l1\n           end) as sth.\n      rewrite sth.\n      reflexivity.\n      unfold combine.\n      fold (combine l1 l2).\n      fold (combine (removelast (a::l1)) (removelast (b::l2))).\n      unfold removelast.\n      fold (removelast (a :: l1)).\n      fold (removelast (b :: l2)).\n      fold (removelast (combine l1 l2)).\n      destruct l1.\n      reflexivity.\n      destruct l2.\n      reflexivity.\n      assert (H: combine (a0::l1) (b0::l2) <> nil).\n      unfold not; intros.\n      unfold combine in H.\n      discriminate.\n      remember (combine (a0::l1) (b0::l2)) as  comb.\n      destruct comb.\n      firstorder.\n      rewrite Heqcomb.\n      clear Heqcomb p comb H.\n      specialize (IHl1 (b0::l2)).\n      rewrite IHl1.\n      reflexivity.\n    Qed.\n\n    Theorem lenEqLastCombine: forall {A B} (a: A) (la: list A) (da: A), la <> nil ->\n                                     a = last la da ->\n                                     forall (b: B) (lb: list B) (db: B),\n                                       length la = length lb -> b = last lb db ->\n                                       In (a, b) (combine la lb).\n    Proof.\n      intros A B a la da lanil lasta.\n      induction la.\n      firstorder.\n      intros b lb db lenEq lastb.\n      destruct lb.\n      unfold length in lenEq.\n      discriminate.\n      unfold length in lenEq.\n      injection lenEq.\n      clear lenEq; intros lenEq.\n      destruct la.\n      destruct lb.\n      unfold last in lasta.\n      unfold last in lastb.\n      rewrite lasta; rewrite lastb.\n      unfold In; unfold combine; simpl.\n      left; reflexivity.\n      discriminate.\n      destruct lb.\n      discriminate.\n      assert (H: a1 :: la <> nil) by discriminate.\n      specialize (IHla H lasta b (b1 :: lb) db lenEq lastb).\n      unfold combine; unfold In.\n      right.\n      apply IHla.\n    Qed.\n\n    Theorem eqLen: forall {A B} (la: list A) (lb: list B), length la = length lb ->\n                                                           length (removelast la) =\n                                                           length (removelast lb).\n    Proof.\n      intros A B la.\n      induction la.\n      intros lb cond.\n      destruct lb.\n      reflexivity.\n      unfold length in cond.\n      discriminate.\n      intros lb cond.\n      destruct la.\n      destruct lb.\n      unfold removelast.\n      reflexivity.\n      unfold length in cond.\n      assert (sim: 1 = S (length lb)) by (apply cond).\n      injection sim.\n      clear sim cond; intros sim.\n      destruct lb.\n      reflexivity.\n      unfold length in sim.\n      discriminate.\n      destruct lb.\n      simpl in cond.\n      discriminate.\n      injection cond as cond2.\n      specialize (IHla lb cond2).\n      destruct lb.\n      unfold length in cond2.\n      discriminate.\n      unfold removelast.\n      unfold length.\n      f_equal.\n      assumption.\n    Qed.\n\n    Theorem listShift: forall {A l n} (a dmy: A),\n                         nth n l dmy = nth (S n) (a :: l) dmy.\n    Proof.\n      intros A l n a dmy.\n      unfold nth.\n      reflexivity.\n    Qed.\n\n    Theorem inComb: forall {A B a b} {la: list A} {lb: list B}, In (a, b) (combine la lb)\n                                                                -> In b lb.\n    Proof.\n      intros A B a b la.\n      induction la.\n      intros lb inComb.\n      simpl in inComb.\n      firstorder.\n      intros lb inComb.\n      destruct lb.\n      pose proof (combNil B (a0::la)) as stf.\n      rewrite stf in inComb.\n      simpl in inComb.\n      firstorder.\n      simpl in inComb.\n      simpl.\n      destruct inComb.\n      left.\n      injection H; firstorder.\n      right.\n      specialize (IHla lb H).\n      firstorder.\n    Qed.\n\n    Theorem listEq: forall {A} {l: list A} dmy {n},\n                      n < length (removelast l) -> nth n (removelast l) dmy =\n                                                   nth n l dmy.\n    Proof.\n      intros A l dmy.\n      induction l.\n      intros n n_lt.\n      simpl in n_lt.\n      assert False by omega; firstorder.\n      intros n n_lt.\n      destruct l.\n      simpl in n_lt.\n      assert False by omega; firstorder.\n      destruct n.\n      reflexivity.\n      assert (H: n < length (removelast (a0 :: l))).\n      unfold removelast in n_lt.\n      unfold length in n_lt.\n      fold (removelast (a0 :: l)) in n_lt.\n      fold (length (removelast (a0 :: l))) in n_lt.\n      omega.\n      unfold removelast.\n      fold (removelast (a0 :: l)).\n      unfold nth.\n      fold (nth n (removelast (a0 :: l)) dmy).\n      fold (nth n (a0 :: l) dmy).\n      firstorder.\n    Qed.\n      \n    Theorem listNoShift: forall {l},\n                           (forall n, n < length l -> forall i, i < n -> nth n l 0 <\n                                                                         nth i l 0) ->\n                           forall {n}, n < length (removelast l) ->\n                                       forall {i}, i < n -> nth n (removelast l) 0 <\n                                                            nth i (removelast l) 0.\n    Proof.\n      intros l cond n n_lt i i_lt.\n      pose proof (listEq 0 n_lt) as n1.\n      assert (i_lt': i < length (removelast l)) by omega.\n      pose proof (listEq 0 i_lt') as i1.\n      rewrite n1; rewrite i1.\n      destruct l.\n      simpl in n_lt.\n      assert False by omega; firstorder.\n      assert (n0 :: l <> nil) by discriminate.\n      pose proof (listCond2 (n0::l) H).\n      assert (n < length (n0 :: l)) by omega.\n      specialize (cond n H1 i i_lt).\n      assumption.\n    Qed.\n\n    Theorem lastCombine: forall {A B} {la: list A} da {lb: list B} db,\n                           length la = length lb -> last la da = fst (last (combine la lb) (da, db)).\n    Proof.\n      intros A B la da.\n      induction la.\n      intros lb db eqLen.\n      reflexivity.\n      intros lb db eqLen.\n      destruct lb.\n      unfold length in eqLen.\n      discriminate.\n      simpl.\n      destruct la.\n      reflexivity.\n      destruct lb.\n      simpl in *.\n      assert False by omega; firstorder.\n      simpl.\n      unfold length in eqLen.\n      fold (length (a0 :: la)) in eqLen.\n      fold (length (b0 :: lb)) in eqLen.\n      assert (H: length (a0 :: la) = length (b0 :: lb)) by auto.\n      specialize (IHla (b0 :: lb) db H).\n      assumption.\n    Qed.\n\n    Theorem lastIn: forall {A} {la: list A} da, la <> nil -> In (last la da) la.\n    Proof.\n      intros A la da notNil.\n      induction la.\n      firstorder.\n      destruct la.\n      unfold last.\n      simpl.\n      left.\n      reflexivity.\n      unfold In.\n      fold (In (last (a :: a0 :: la) da) (a0 :: la)).\n      right.\n      assert (a0 :: la <> nil) by discriminate.\n      specialize (IHla H).\n      assumption.\n    Qed.\n\n    Theorem last_nth: forall {A} (la: list A) da, nth (length la - 1) la da =\n                                                  last la da.\n    Proof.\n      intros A la da.\n      induction la.\n      reflexivity.\n      simpl.\n      destruct la.\n      reflexivity.\n      unfold length.\n      fold (length la).\n      remember (S (length la) - 0) as contra.\n      destruct contra.\n      omega.\n      assert (S (length la) - 0 = length (a0 :: la)) by (unfold length; omega).\n      assert (length (a0 :: la) - 1 = contra) by omega.\n      rewrite <- H0.\n      assumption.\n    Qed.\n\n    Theorem in_nth: forall {A} {la: list A} {a} da, In a la -> exists i, i < length la /\\\n                                                                         nth i la da = a.\n    Proof.\n      intros A la a da ina.\n      induction la.\n      unfold In in ina.\n      firstorder.\n      unfold In in ina.\n      destruct ina.\n      exists 0.\n      constructor.\n      unfold length.\n      omega.\n      unfold nth.\n      assumption.\n      specialize (IHla H).\n      destruct IHla as [i [i_lt nth_a]].\n      exists (S i).\n      constructor.\n      simpl.\n      omega.\n      simpl.\n      assumption.\n    Qed.\n\n    Theorem lastInRemove: forall {A} {la: list A} {da}, In (last la da) (removelast la) ->\n                                                        exists i, i < length la - 1 /\\\n                                                                  nth i la da = last la da.\n    Proof.\n      intros A la da isIn.\n      induction la.\n      simpl in isIn.\n      firstorder.\n      destruct la.\n      simpl in isIn.\n      firstorder.\n      simpl in isIn.\n      destruct isIn.\n      destruct la.\n      exists 0.\n      constructor.\n      simpl.\n      omega.\n      simpl.\n      assumption.\n      exists 0.\n      constructor.\n      simpl.\n      omega.\n      simpl.\n      assumption.\n      specialize (IHla H).\n      destruct IHla as [i [c1 c2]].\n      exists (S i).\n      constructor.\n      simpl in c1.\n      simpl.\n      omega.\n      simpl.\n      assumption.\n    Qed.\n\n    Theorem eqComb: forall {A B} {la: list A} da {lb: list B} db i,\n                      length la = length lb -> nth i (combine la lb) (da, db) =\n                                               (nth i la da, nth i lb db).\n    Proof.\n      intros A B la da.\n      induction la.\n      intros lb db i eq_len.\n      destruct lb.\n      simpl.\n      destruct i; reflexivity.\n      unfold length in eq_len; discriminate.\n      intros lb db i eq_len.\n      destruct lb.\n      unfold length in eq_len; discriminate.\n      unfold length in eq_len.\n      injection eq_len as gd1; clear eq_len; fold (length la) in gd1. fold (length lb) in gd1.\n      unfold combine.\n      fold (combine la lb).\n      destruct i.\n      reflexivity.\n      unfold nth.\n      fold (nth i (combine la lb) (da, db)).\n      fold (nth i la da).\n      fold (nth i lb db).\n      apply (IHla lb db i gd1).\n    Qed.\n\n    Theorem combLength: forall {A B} {la: list A} {lb: list B},\n                          length la = length lb -> length la = length (combine la lb).\n    Proof.\n      intros A B la.\n      induction la.\n      intros lb.\n      intros len.\n      reflexivity.\n      destruct lb.\n      intros len.\n      simpl in len.\n      discriminate.\n      intros len.\n      simpl in len.\n      injection len as len'.\n      simpl.\n      specialize (IHla lb len').\n      f_equal; assumption.\n    Qed.\n    \n\nTheorem lastCombineDist: forall {A B} (la : list A) da (lb : list B) db,\n                           length la = length lb ->\n                           last (combine la lb) (da, db) = (last la da, last lb db).\nProof.\n  intros A B la da.\n  induction la.\n  intros lb db lenEq.\n  destruct lb.\n  reflexivity.\n  unfold length in lenEq.\n  discriminate.\n  intros lb db lenEq.\n  destruct lb.\n  unfold length in lenEq; discriminate.\n  simpl in lenEq.\n  injection lenEq as l'.\n  clear lenEq.\n  specialize (IHla lb db l').\n  simpl.\n  destruct la.\n  simpl.\n  destruct lb.\n  reflexivity.\n  unfold length in l'; discriminate.\n  destruct lb.\n  unfold length in l'; discriminate.\n  simpl.\n  assumption.\nQed.\n\nTheorem inNotInRemove: forall {A} {a} {la: list A} da , In a la -> ~ In a (removelast la) ->\n                                                        last la da = a.\nProof.\n  intros A a la da isIn notIn.\n  induction la.\n  simpl in isIn.\n  intuition.\n  destruct la.\n  simpl in *.\n  destruct isIn; intuition.\n  simpl in *.\n  destruct isIn.\n  firstorder.\n  specialize (IHla H).\n  assert (notIn': ~ In a match la with\n                         | nil => nil\n                         | _ :: _ => a1 :: removelast la\n                       end) by firstorder.\n  apply (IHla notIn').\nQed.", "meta": {"author": "vmurali", "repo": "CacheProof", "sha": "bf59c12575808dcec5abe0b67a81e042cd5b1bf5", "save_path": "github-repos/coq/vmurali-CacheProof", "path": "github-repos/coq/vmurali-CacheProof/CacheProof-bf59c12575808dcec5abe0b67a81e042cd5b1bf5/Useful.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7194854616927008}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Auxiliary lemmas for lists.\n*)\n\nRequire Import List.\nImport ListNotations.\nRequire Import Psatz.\nRequire Import ssreflect ssrbool ssrfun. \n\nSection Facts.\n\n(* induction principle wrt. a decreasing measure f *)\n(* example: elim /(measure_ind length) : l. *)\nLemma measure_ind {X : Type} (f : X -> nat) (P : X -> Prop) : \n  (forall x, (forall y, f y < f x -> P y) -> P x) -> forall (x : X), P x.\nProof.\n  apply : well_founded_ind.\n  apply : Wf_nat.well_founded_lt_compat. move => *. by eassumption.\nQed.\nArguments measure_ind {X}.\n\nEnd Facts.\n\nSection ForallNorm.\n\nVariable T : Type.\nVariable P : T -> Prop.\n\nLemma Forall_nilP : Forall P [] <-> True.\nProof. by constructor. Qed.\n\nLemma Forall_consP {a A} : Forall P (a :: A) <-> P a /\\ Forall P A.\nProof.\n  constructor. \n    move=> H. by inversion H.\n  move=> [? ?]. by constructor.\nQed.\n\nLemma Forall_singletonP {a} : Forall P [a] <-> P a.\nProof. rewrite Forall_consP Forall_nilP. by tauto. Qed.\n\nLemma Forall_appP {A B}: Forall P (A ++ B) <-> Forall P A /\\ Forall P B.\nProof.\n  elim: A.\n    constructor; by [|case].\n  move=> ? ? IH /=. rewrite ? Forall_consP ? IH.\n  by tauto.\nQed.\n\n(* usage rewrite ? Forall_norm *)\nDefinition Forall_norm := (@Forall_appP, @Forall_singletonP, @Forall_consP, @Forall_nilP).\n\nEnd ForallNorm.\n\nSection ListFacts.\n\n(* any list is empty or has a last element *)\nLemma nil_or_ex_last {T: Type} (A: list T) : A = [] \\/ exists B a, A = B ++ [a].\nProof.\n  elim: A.\n    by left.\n  move=> a A. case.\n    move=> ->. right. by exists [], a.\n  move=> [B [b ->]]. right. by exists (a :: B), b.\nQed.\n\n(* induction wrt the last element of a list *)\nLemma list_last_ind (X: Type) (P : list X -> Prop) : \n  P [] ->\n  (forall a A, P A -> P (A ++ [a])) ->\n  forall (A : list X), P A.\nProof.\n  move=> H1 H2. elim /(measure_ind (@length X)).\n  move=> A IH. case: (nil_or_ex_last A).\n    by move=> ->.\n  move=> [B [a ?]]. subst A. apply: H2. apply: IH.\n  rewrite app_length /length. by lia.\nQed.\n\nArguments list_last_ind [X].\n\nLemma incl_consP {X: Type} {a: X} {A B} : incl (a :: A) B <-> (In a B /\\ incl A B).\nProof.\n  by rewrite /incl - ? Forall_forall ?Forall_norm.\nQed.\n\nEnd ListFacts.", "meta": {"author": "uds-psl", "repo": "2020-types-propositional-calculi", "sha": "87d61951f216881ccb45984349031915b2f842ee", "save_path": "github-repos/coq/uds-psl-2020-types-propositional-calculi", "path": "github-repos/coq/uds-psl-2020-types-propositional-calculi/2020-types-propositional-calculi-87d61951f216881ccb45984349031915b2f842ee/HSC/HSC/HSC_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7194854589386851}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(*i $Id: Rsigma.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\nRequire Import Rbase.\nRequire Import Rfunctions.\nRequire Import Rseries.\nRequire Import PartSum.\nOpen Local Scope R_scope.\n\nSet Implicit Arguments.\n\nSection Sigma.\n\n  Variable f : nat -> R.\n\n  Definition sigma (low high:nat) : R :=\n    sum_f_R0 (fun k:nat => f (low + k)) (high - low).\n\n  Theorem sigma_split :\n    forall low high k:nat,\n      (low <= k)%nat ->\n      (k < high)%nat -> sigma low high = sigma low k + sigma (S k) high.\n  Proof.\n    intros; induction  k as [| k Hreck].\n    cut (low = 0%nat).\n    intro; rewrite H1; unfold sigma in |- *; rewrite <- minus_n_n;\n      rewrite <- minus_n_O; simpl in |- *; replace (high - 1)%nat with (pred high).\n    apply (decomp_sum (fun k:nat => f k)).\n    assumption.\n    apply pred_of_minus.\n    inversion H; reflexivity.\n    cut ((low <= k)%nat \\/ low = S k).\n    intro; elim H1; intro.\n    replace (sigma low (S k)) with (sigma low k + f (S k)).\n    rewrite Rplus_assoc;\n      replace (f (S k) + sigma (S (S k)) high) with (sigma (S k) high).\n    apply Hreck.\n    assumption.\n    apply lt_trans with (S k); [ apply lt_n_Sn | assumption ].\n    unfold sigma in |- *; replace (high - S (S k))%nat with (pred (high - S k)).\n    pattern (S k) at 3 in |- *; replace (S k) with (S k + 0)%nat;\n      [ idtac | ring ].\n    replace (sum_f_R0 (fun k0:nat => f (S (S k) + k0)) (pred (high - S k))) with\n    (sum_f_R0 (fun k0:nat => f (S k + S k0)) (pred (high - S k))).\n    apply (decomp_sum (fun i:nat => f (S k + i))).\n    apply lt_minus_O_lt; assumption.\n    apply sum_eq; intros; replace (S k + S i)%nat with (S (S k) + i)%nat.\n    reflexivity.\n    ring.\n    replace (high - S (S k))%nat with (high - S k - 1)%nat.\n    apply pred_of_minus.\n    omega.\n    unfold sigma in |- *; replace (S k - low)%nat with (S (k - low)).\n    pattern (S k) at 1 in |- *; replace (S k) with (low + S (k - low))%nat.\n    symmetry  in |- *; apply (tech5 (fun i:nat => f (low + i))).\n    omega.\n    omega.\n    rewrite <- H2; unfold sigma in |- *; rewrite <- minus_n_n; simpl in |- *;\n      replace (high - S low)%nat with (pred (high - low)).\n    replace (sum_f_R0 (fun k0:nat => f (S (low + k0))) (pred (high - low))) with\n    (sum_f_R0 (fun k0:nat => f (low + S k0)) (pred (high - low))).\n    apply (decomp_sum (fun k0:nat => f (low + k0))).\n    apply lt_minus_O_lt.\n    apply le_lt_trans with (S k); [ rewrite H2; apply le_n | assumption ].\n    apply sum_eq; intros; replace (S (low + i)) with (low + S i)%nat.\n    reflexivity.\n    ring.\n    omega.\n    inversion H; [ right; reflexivity | left; assumption ].\n  Qed.\n\n  Theorem sigma_diff :\n    forall low high k:nat,\n      (low <= k)%nat ->\n      (k < high)%nat -> sigma low high - sigma low k = sigma (S k) high.\n  Proof.\n    intros low high k H1 H2; symmetry  in |- *; rewrite (sigma_split H1 H2); ring.\n  Qed.\n\n  Theorem sigma_diff_neg :\n    forall low high k:nat,\n      (low <= k)%nat ->\n      (k < high)%nat -> sigma low k - sigma low high = - sigma (S k) high.\n  Proof.\n    intros low high k H1 H2; rewrite (sigma_split H1 H2); ring.\n  Qed.\n\n  Theorem sigma_first :\n    forall low high:nat,\n      (low < high)%nat -> sigma low high = f low + sigma (S low) high.\n  Proof.\n    intros low high H1; generalize (lt_le_S low high H1); intro H2;\n      generalize (lt_le_weak low high H1); intro H3;\n        replace (f low) with (sigma low low).\n    apply sigma_split.\n    apply le_n.\n    assumption.\n    unfold sigma in |- *; rewrite <- minus_n_n.\n    simpl in |- *.\n    replace (low + 0)%nat with low; [ reflexivity | ring ].\n  Qed.\n\n  Theorem sigma_last :\n    forall low high:nat,\n      (low < high)%nat -> sigma low high = f high + sigma low (pred high).\n  Proof.\n    intros low high H1; generalize (lt_le_S low high H1); intro H2;\n      generalize (lt_le_weak low high H1); intro H3;\n        replace (f high) with (sigma high high).\n    rewrite Rplus_comm; cut (high = S (pred high)).\n    intro; pattern high at 3 in |- *; rewrite H.\n    apply sigma_split.\n    apply le_S_n; rewrite <- H; apply lt_le_S; assumption.\n    apply lt_pred_n_n; apply le_lt_trans with low; [ apply le_O_n | assumption ].\n    apply S_pred with 0%nat; apply le_lt_trans with low;\n      [ apply le_O_n | assumption ].\n    unfold sigma in |- *; rewrite <- minus_n_n; simpl in |- *;\n      replace (high + 0)%nat with high; [ reflexivity | ring ].\n  Qed.\n\n  Theorem sigma_eq_arg : forall low:nat, sigma low low = f low.\n  Proof.\n    intro; unfold sigma in |- *; rewrite <- minus_n_n.\n    simpl in |- *; replace (low + 0)%nat with low; [ reflexivity | ring ].\n  Qed.\n\nEnd Sigma.\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/theories/Reals/Rsigma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7194854534026318}}
{"text": "Add LoadPath \"C:/Coq/buffer\".\nRequire Export Poly.\n\nTheorem silly1 : forall (n m o p : nat),\n  n = m -> [n;o] = [n;p] -> [n;o] = [m;p].\nProof. intros n m o p eq1 eq2. rewrite <- eq1. apply eq2. Qed.\n\nTheorem silly2 : forall (n m o p : nat),\n  n = m -> (forall (q r : nat), q = r -> [q;o] = [r;p]) -> [n;o] = [m;p].\nProof. intros n m o p eq1 eq2. apply eq2. apply eq1. Qed.\n\nTheorem silly2a : forall (n m : nat),\n  (n,n) = (m,m) ->\n  (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) -> [n] = [m].\nProof. intros n m eq1 eq2. apply eq2. apply eq1. Qed.\n\n(* using apply before introducing hypotheses may simplify proof *)\nTheorem silly_ex :\n  (forall n, evenb n = true -> oddb (S n) = true) ->\n  evenb 3 = true ->\n  oddb 4 = true.\nProof. intros eq1. apply eq1. Qed.\n\n(* use symmetry tatic to swap equality, need to sometimes with apply *)\nTheorem silly3_firsttty : \n    forall (n : nat), true = beq_nat n 5 ->\n    beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H. simpl. symmetry. apply H. Qed.\n\nTheorem rev_excercise1 : forall (l l' : list nat),\n    l = rev l' ->\n    l' = rev l.\nProof. intros l l' H. symmetry. rewrite -> H. apply rev_involutive. Qed.\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity. Qed.\n\nExample trans_eq_example : forall(a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  apply trans_eq with (m := [c;d]). \n  apply eq1. apply eq2. Qed.\n\nExample trans_eq_excercise : forall (n m o p : nat),\n  m = (minustwo o) ->\n  (n + p) = m ->\n  (n + p) = (minustwo o).\nProof. intros n m o p eq1 eq2. apply trans_eq with m. apply eq2. apply eq1. Qed.\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n ; m] = [o ; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. inversion H as [Hnm]. reflexivity. Qed.\n\n\nTheorem inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros X x y z l j H1 H2. inversion H2. reflexivity. Qed. \n\nTheorem beq_nat_O_1 : forall n,\n  beq_nat 0 n = true -> n = 0.\nProof.\n  intros n. destruct n as [| n']. intros H. reflexivity. simpl. intros H. inversion H. Qed. \n\n(* principle of explosion *)\nTheorem inversion_ex6 : forall (X : Type) (x y z : X) (l j : list X), \n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof. intros X x y z l j H1 H2. inversion H1. Qed.\n\nTheorem f_equal : forall (A B : Type) (f:A->B) (x y : A),\n  x = y -> f x = f y.\nProof. intros A B f x y H. rewrite -> H. reflexivity. Qed.\n\n(* can use many tatics in the context instead of the goal\n  Usually by adding 'in <hypothesis_name>' after the tatic*)\nTheorem S_inj : forall (n m : nat) (b : bool),\n  beq_nat (S n) (S m) = b ->\n  beq_nat n m = b.\nProof. intros n m b H. simpl in H. apply H. Qed.\n\n(* apply and apply in are backwards and forwards reasoning resp \n  apply is modus ponens and apply in is like modus ponens but on hypotheses*)\n\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. intros n eq H. symmetry in H. apply eq in H. symmetry in H. apply H. Qed.\n\nTheorem plus_n_n_injective : forall n m,\n  n + n = m + m -> n = m. \nProof. intros n. induction n as [| n'].\n    - intros [| m']. reflexivity. inversion 1.\n    - intros [| m']. inversion 1.\n      + intros H. apply f_equal. apply IHn'. \n        rewrite <- plus_n_Sm in H. simpl in H.\n        rewrite <- plus_n_Sm in H. \n        inversion H. reflexivity.\nQed.\n\nTheorem double_injective: forall n m, \n  double n = double m -> n = m.\nProof. intros n. induction n as [| n'].\n  - simpl. intros m eq. destruct m as [| m'].\n    +reflexivity.\n    +inversion eq.\n  - simpl. intros m eq. destruct m as [| m'].\n    +simpl. inversion eq.\n    +apply f_equal. apply IHn'. inversion eq. reflexivity. \nQed.\n\nTheorem beq_nat_true : forall n m,\n  beq_nat n m = true -> n = m.\nProof. intros n. induction n as [| n' Hn'].\n    - intros [| m'].\n      +reflexivity.\n      +inversion 1.\n    - intros [| m'].\n      +inversion 1.\n      +intros H. simpl in H. apply Hn' in H. \n       rewrite -> H. reflexivity. \nQed.\n\nTheorem double_injective' : forall n m,\n  double n = double m -> n = m.\nProof. intros n m. induction m as [| m'].\n  - simpl. intros eq. destruct n as [| n'].\n    +reflexivity.\n    +inversion eq.\n  -intros eq. destruct n as [| n'].\n    +inversion eq.\n    +apply f_equal. simpl in eq. Abort.\n(*\n  The above fails because n must be introduced before m\n  so we cannot preform case analysis on n. \n  The induction hypothesis is not general enough\n \n  Solution to this problem is to use the \n  generalize dependent tactic\n*)\n\nTheorem double_injective_take2 : forall n m,\n  double n = double m -> n = m.\nProof.\n  intros n m. (* n and m in context *)\n  generalize dependent n. \n  induction m as [| m' Hm'].\n    - intros [| n']. reflexivity. inversion 1.\n    - intros [| n']. inversion 1. \n      + intros H. apply f_equal. apply Hm'. \n        inversion H. reflexivity.\nQed.\n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof. intros [n] [m]. simpl. intros H. \n       assert (H' : n = m). { apply beq_nat_true. apply H. }\n       rewrite H'. reflexivity.\nQed.\n\nTheorem nth_error_after_last : \n  forall (n : nat) (X : Type) (l : list X),\n    length l = n ->\n    nth_error l n = None.\nProof. intros n X l. generalize dependent n.\n       induction l as [| h t Ht].\n       -simpl. reflexivity.\n       -intros [| n']. \n        +inversion 1.\n        +simpl. intros H. apply Ht. \n         inversion H. reflexivity.\nQed.\n\nDefinition square n := n * n.\n\nLemma square_mult : forall n m, \n  square (n*m) = square n * square m.\nProof. intros n m. unfold square. rewrite mult_assoc.\n       assert (H : n * m * n = n * n * m).\n      { rewrite mult_comm. apply mult_assoc. }\n      rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(* using unfold *)\nDefinition bar x :=\n  match x with  \n  | 0 => 5\n  | S _ => 5\n  end.\n(* cannot progress without using destruct \n   but may not know that match is the problem*)\nFact silly_fact_FAILED : forall m,\n  bar m + 1 = bar (m + 1) + 1.\nProof. intros m. simpl. (* does nothing *)\nAbort. \n(* using unfold allows to see that we are getting\n   stuck at a match statement *)\nFact silly_fact : forall m,\n  bar m + 1 = bar (m + 1) + 1.\nProof. intros m. unfold bar. destruct m; reflexivity.\nQed.\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.\nQed.\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof. intros X Y. intros l. induction l as [| hl tl Htl].\n       -intros. inversion H. reflexivity.\n       -intros [| hl1 tl1] [| hl2 tl2]; intros; inversion H.\n        Abort.\n\n(* what goes wrong here? *)\nTheorem bool_fn_applied_thrice_FAIL :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f b. destruct (f b) eqn:H.\n  - destruct (f true) eqn:Hf.\n    + apply Hf.\n    + destruct (f false) eqn:Hff.\n      ++ reflexivity.\n      ++ (* false = true OH NO! *) Abort.\n\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof. intros f b. destruct b.\n      - destruct (f true) eqn:Hf.\n        { rewrite -> Hf. apply Hf. }\n        { destruct (f false) eqn:Hff.\n           + apply Hf.\n           + apply Hff. }\n      - destruct (f false) eqn:Hf.\n        { destruct (f true) eqn:Hff.\n           + apply Hff.\n           + apply Hf. }\n        { rewrite -> Hf.  apply Hf. }\nQed.\n\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat n m.\nProof. intros. destruct (beq_nat n m); reflexivity.\nQed.\n\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\n\nProof. intros n m p Hn Hp.\n      assert (beq_nat n m = true -> n = m) as Enm.\n      { apply beq_nat_true. }\n      assert (beq_nat m p = true -> m = p) as Emp.\n      { apply beq_nat_true. }\n      apply Enm in Hn. apply Emp in Hp. \n      rewrite Hn. rewrite Hp. rewrite <- beq_nat_refl. reflexivity.\nQed.\n\nTheorem filter_excercise : forall (X : Type) (test : X -> bool)\n  (x : X) (l lf : list X), filter test l = x :: lf -> test x = true.\nProof. intros X test x l lf. induction l as [| h t Ht].\n        - inversion 1.\n        - intros H. unfold filter in H. destruct (test h) eqn:Htest.\n          + inversion H. rewrite <- H1. apply Htest.\n          + apply Ht in H. apply H.\nQed.\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n  | nil => true\n  | h :: t => andb (test h) (forallb test t)\n  end.\n\nCompute forallb evenb [12;1;4;8].\nCompute forallb negb [false; false; false].\nCompute forallb oddb [1;3;5;7;9].\nCompute forallb negb [false;false].\nCompute forallb evenb [0;2;4;5].\nCompute forallb (beq_nat 5) [].\n(* could define this with orb but this way is faster *)\nFixpoint existsb {X : Type} (test : X -> bool) (l : list X) :=\n  match l with\n  | nil => false\n  | h :: t =>\n    match (test h) with\n    | true => true\n    | false => existsb test t\n  end.\n\nCompute existsb (beq_nat 5) [0;2;3;6].\nCompute existsb (andb true) [true;true;false].\nCompute existsb oddb [1;0;0;0;0;3].\nCompute existsb evenb [].\n\nDefinition existsb' {X : Type} (test : X -> bool) (l : list X) :=\n  negb (forallb (fun n => negb (test n)) l).\n\nTheorem existsb_existsb' : \n  forall (X : Type) (test : X -> bool) (l : list X),\n  existsb test l = existsb' test l.\nProof. intros X test l. induction l as [| h t Ht].\n      - reflexivity.\n      - simpl. destruct (test h) eqn:Htest; unfold existsb'; simpl; rewrite -> Htest; simpl.\n        + reflexivity.\n        + rewrite -> Ht. reflexivity.\nQed.\n\n\n\n\n\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/Tatics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8774767986961403, "lm_q1q2_score": 0.7194373873930082}}
{"text": "Add LoadPath \"somePath\".\n\nRequire Export propVar_relation.\n\n(*----------rel cons----------*)\nDefinition consistent_environment (theta : environment)(R:propVar_relation) := \n  forall x y: propVar, (R x y) -> (theta x -> theta y).\n\nLemma environment_union_consistent : forall R:propVar_relation, forall th1 th2:environment, \nconsistent_environment th1 R -> consistent_environment th2 R -> consistent_environment (environment_union th1 th2) R.\nProof.\nintros.\nintro;intros.\napply orb_true_iff in H2.\ndestruct H2.\napply orb_true_iff.\nleft.\napply (H x);auto.\napply orb_true_iff.\nright.\napply (H0 x);auto.\nQed.\n\nLemma full_environment_consistent : forall R:propVar_relation, consistent_environment full_environment R.\nProof.\nintros;intro;intros.\nunfold full_environment;auto.\nQed.\n\nLemma empty_environment_consistent : forall R:propVar_relation, consistent_environment empty_environment R.\nProof.\nintros;intro;intros.\ninversion H0.\nQed.\n\nDefinition rel_cons (R:propVar_relation)(f g:propForm):=\nforall theta:environment, consistent_environment theta R -> [[f]]theta -> [[g]]theta.\n\nLemma consistent_environment_rel_union : forall theta:environment, forall R1 R2:propVar_relation,\nconsistent_environment theta (R1 U R2)\n->\n(consistent_environment theta R1 /\\ consistent_environment theta R2).\nProof.\nintros.\nunfold consistent_environment in *.\nsplit.\nintros.\napply (H x y).\nleft;auto.\nassumption.\nintros.\napply (H x y).\nright;auto.\nassumption.\nQed.\n\nLemma rel_union_consistent_environment : forall theta:environment, forall R1 R2:propVar_relation,\n(consistent_environment theta R1 /\\ consistent_environment theta R2)\n->\nconsistent_environment theta (R1 U R2).\nProof.\nintros.\nunfold consistent_environment.\ndestruct H.\nintros.\ndestruct H1.\nexact (H x y H1 H2).\nexact (H0 x y H1 H2).\nQed.\n\n", "meta": {"author": "MECvDelft", "repo": "ConsequencesInCoq", "sha": "742ba2b35ebe13d37a41eb460f802346a8574d00", "save_path": "github-repos/coq/MECvDelft-ConsequencesInCoq", "path": "github-repos/coq/MECvDelft-ConsequencesInCoq/ConsequencesInCoq-742ba2b35ebe13d37a41eb460f802346a8574d00/rel_cons.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7194373751907379}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Generalizable All Variables. *)\nRequire Import Aw_0_Notations.\nRequire Import Aw_1_3_Categories.\nRequire Import Aw_1_5_Isomorphisms.\n\n(******************************************************************************)\n(* Chapter 2.1: Epic and Monic morphisms                                      *)\n(******************************************************************************)\n\n(* Definition 2.1a *)\nClass Monic `{C : Category} {a b : C} (f : a ~> b) : Prop :=\n  monic : forall c (g1 g2 : c ~> a), f \\\\o g1 === f \\\\o g2 -> g1 === g2.\n(* Implicit Arguments monic [ C a b Ob Hom ]. *)\n\n(* Definition 2.1b *)\nClass Epic `{C : Category} {a b : C} (f : a ~> b) : Prop := \n  epic : forall c (g1 g2 : b~>c), g1 \\\\o f === g2 \\\\o f -> g1 === g2.\n(* Implicit Arguments epic [ C a b Ob Hom ]. *)\n\n(* Proposition 2.6 *)\n(* すべての同型は、エピepiである。 *)\nInstance iso_epic `(i : Isomorphic) : Epic #i.\nProof.\n  Check #i : a ~> b.\n  Check iso_forward i : a ~> b.\n  \n  rewrite /Epic => c g1 g2 H.\n  rewrite -[g1]right_identity -[g2]right_identity.\n  rewrite -iso_comp2 -2!associativity.\n  rewrite H.\n  reflexivity.\nQed.\n\n(* Proposition 2.6 *)\n(* すべての同型は、モノmonicである。 *)\nInstance iso_monic `(i : Isomorphic) : Monic #i.\nProof.\n  rewrite /Monic => c g1 g2 H.\n  rewrite -[g1]left_identity -[g2]left_identity.\n  rewrite -iso_comp1 2!associativity.\n  rewrite H.\n  reflexivity.\nQed.\n\n(* a BiMorphism is an epic monic *)\nClass BiMorphism `{C : Category} {a b : C} (f : a ~> b) : Prop :=\n  {\n    bimorphism_epic  :> Epic  f;\n    bimorphism_monic :> Monic f\n  }.\nCoercion bimorphism_epic  : BiMorphism >-> Epic.\nCoercion bimorphism_monic : BiMorphism >-> Monic.\n\nClass EndoMorphism `{C : Category} (A : C) :=\n  endo : A ~> A.\n\nClass AutoMorphism `{C : Category} (A : C) : Type :=\n  {\n    auto_endo1 : EndoMorphism A;\n    auto_endo2 : EndoMorphism A;\n    auto_iso   : Isomorphism  (@endo _ _ _ _ auto_endo1) (@endo _ _ _ _ auto_endo2);\n  }.\n\n(*Class Balanced `{C:Category} : Prop :=\n  balanced : forall (a b:C)(f:a~>b), BiMorphism f -> Isomorphism f.*)\n\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/categories/Aw_2_1_EpicMinic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.719437365917346}}
{"text": "Require Export PropL.\n\n(* ((Existential Quantification)) *)\n\n(* Exercise: 1 star, optional (english_exists) *)\n\n(* ex nat (fun n => beautiful (S n)) means:\nThere exists such natural number n that the following number has property\n\"beautiful\" *)\n\n(* END english_exists. *)\n\n(* Exercise: 1 star (dist_not_exists) *)\n\nTheorem dist_not_exists : forall (X : Type) (P : X -> Prop),\n  (forall x, P x) -> not (exists x, not (P x)).\nProof.\n  unfold not.\n  intros X P H1 H2.\n  inversion H2.\n  apply H.\n  apply H1.\nQed.\n\n(* END dist_not_exists. *)\n\n(* Exercise: 3 stars, optional (not_exists_dist) *)\n\nTheorem not_exists_dist : excluded_middle -> forall (X : Type) (P : X -> Prop),\n  not (exists x, not (P x)) -> (forall x, P x).\nProof.\n  unfold not.\n  intros EM X P H x.\n  apply excluded_middle_implies_classic in EM.\n  unfold classic in EM.\n  unfold not in EM.\n  apply EM.\n  intros pxf.\n  apply H.\n  exists x.\n  apply pxf.\nQed.\n\n(* END not_exists_dist. *)\n\n(* Exercise: 2 stars (dist_exists_or) *)\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  intros X P Q.\n  split.\n  Case \"a -> b\".\n    intros H.\n    inversion H.\n    inversion H0.\n    left.\n    exists x.\n    apply H1.\n    right.\n    exists x.\n    apply H1.\n  Case \"a <- b\".\n    intros H.\n    inversion H.\n    inversion H0.\n    exists x.\n    left.\n    apply H1.\n    inversion H0.\n    exists x.\n    right.\n    apply H1.\nQed.\n\n(* END dist_exists_or. *)\n\n(* ((Evidence-Carrying Booleans)) *)\n\nTheorem eq_nat_dec : forall n m : nat, { n = m } + { n <> m }.\nProof.\n  induction n.\n  Case \"n = 0\".\n    destruct m.\n    SCase \"m = 0\".\n      left.\n      trivial.\n    SCase \"m = S m\".\n      right.\n      intros H.\n      inversion H.\n  Case \"n = S n\".\n    induction m.\n    SCase \"m = 0\".\n      right.\n      intros H.\n      inversion H.\n    SCase \"m = S m\".\n      destruct IHn with (m := m).\n      left. apply f_equal. apply e.\n      right. intros H. apply n0. inversion H. trivial.\nDefined.\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\n(* Exercise: 1 star (override_shadow') *)\n\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  intros X x1 x2 k1 k2 f.\n  unfold override'.\n  destruct (eq_nat_dec k1 k2).\n  trivial.\n  trivial.\nQed.\n\n(* ((Additional Exercises)) *)\n\n(* Exercise: 3 stars (all_forallb) *)\n\nInductive all {X : Type} (P : X -> Prop) : list X -> Prop :=\n  | all_nil  : all P nil\n  | all_cons : forall x l, P x -> all P l -> all P (cons x l).\n\nTheorem forallb_true_all: forall (X : Type) (test : X -> bool) (l : list X),\n  all (fun x => test x = true) l -> forallb test l = true.\nProof.\n  intros X test l.\n  induction l.\n    reflexivity.\n    intros H.\n    simpl.\n    inversion H.\n    rewrite -> H2.\n    simpl.\n    apply IHl.\n    apply H3.\nQed.\n\nTheorem forallb_false_not_all :\n  forall (X : Type) (test : X -> bool) (l : list X),\n  not (all (fun x => test x = true) l) -> forallb test l = false.\nProof.\n  intros X test l.\n  unfold not.\n  induction l.\n  Case \"l = nil\".\n    intros H.\n    apply ex_falso_quodlibet.\n    apply H.\n    apply all_nil.\n  Case \"l = a :: l\".\n    intros H.\n    simpl.\n    destruct (test a) eqn: Q.\n    SCase \"test a = true\".\n      simpl.\n      apply IHl.\n      intros H'.\n      apply H.\n      apply all_cons.\n      apply Q.\n      apply H'.\n    SCase \"test a = false\".\n      reflexivity.\nQed.\n\n(* END all_forallb. *)\n\n(* Exercise: 4 stars, advanced (filter_challenge) *)\n\nInductive merged {X : Type} : list X -> list X -> list X -> Prop :=\n  | merged_nil   : merged nil nil nil\n  | merged_left  : forall x l1 l2 l3,\n                     merged l1 l2 l3 -> merged (x :: l1) l2 (x :: l3)\n  | merged_right : forall x l1 l2 l3,\n                     merged l1 l2 l3 -> merged l1 (x :: l2) (x :: l3).\n\nTheorem filter_spec : forall (X : Type) (f : X -> bool) (l l1 l2 : list X),\n  (all (fun b => f b = true)  l1) ->\n  (all (fun b => f b = false) l2) ->\n  merged l1 l2 l ->\n  filter f l = l1.\nProof.\n  intros X f l.\n  induction l.\n  Case \"l = nil\".\n    intros l1 l2 H1 H2 H3.\n    inversion H3.\n    reflexivity.\n  Case \"l = a :: l\".\n    simpl.\n    intros l1 l2 H1 H2 H3.\n    inversion H3.\n    SCase \"merged_left\".\n      inversion H1.\n      SSCase \"l1 = nil\".\n        rewrite <- H7 in H0.\n        inversion H0.\n      SSCase \"x0 :: l5 = l1\".\n        rewrite <- H9 in H0.\n        inversion H0.\n        rewrite <- H11 in H7.\n        rewrite -> H in H7.\n        rewrite -> H7.\n        replace (filter f l) with l5.\n        trivial.\n        symmetry.\n        apply IHl with (l2 := l2).\n        apply H8.\n        apply H2.\n        rewrite <- H12.\n        apply H5.\n    SCase \"merged_right\".\n      inversion H2.\n      SSCase \"l2 = nil\".\n        rewrite <- H7 in H4.\n        inversion H4.\n      SSCase \"x0 :: l5 = l2\".\n        rewrite <- H9 in H4.\n        inversion H4.\n        rewrite <- H11 in H7.\n        rewrite -> H in H7.\n        rewrite -> H7.\n        apply IHl with (l2 := l3).\n        apply H1.\n        rewrite <- H12 in H8.\n        apply H8.\n        apply H5.\nQed.\n\n(* END filter_challenge. *)\n\n(* Exercise: 5 stars, advanced, optional (filter_challenge_2) *)\n\nTheorem filter_empty : forall (X : Type) (test : X -> bool) (l : list X),\n  filter test l = nil -> all (fun x => test x = false) l.\nProof.\n  intros X test l.\n  induction l.\n  Case \"l = nil\".\n    intros H.\n    apply all_nil.\n  Case \"l = a :: l\".\n    intros H.\n    simpl in H.\n    destruct (test a) eqn: TA.\n    SCase \"test a = true\".\n      inversion H.\n    SCase \"test a = false\".\n      apply all_cons.\n      apply TA.\n      apply IHl.\n      apply H.\nQed.\n\nTheorem subseq_all : forall (X : Type) (P : X -> Prop) (l1 l2 : list X),\n  all P l1 -> subseq l2 l1 -> all P l2.\nProof.\n  intros X P l1.\n  induction l1.\n  Case \"l1 = nil\".\n    intros.\n    inversion H0.\n    apply all_nil.\n  Case \"l1 = a :: l1\".\n    intros.\n    inversion H.\n    inversion H0.\n    apply all_nil.\n    generalize dependent H7.\n    generalize dependent H4.\n    apply IHl1.\n    apply all_cons.\n    apply H3.\n    generalize dependent H7.\n    generalize dependent H4.\n    apply IHl1.\nQed.\n\nTheorem filter_subseq :\n  forall (X : Type) (test : X -> bool) l,\n  subseq (filter test l) l.\nProof.\n  intros X test.\n  induction l.\n  Case \"l = nil\".\n    simpl.\n    apply subseq_nil.\n  Case \"l = a :: l\".\n    simpl.\n    destruct (test a).\n    SCase \"test a = true\".\n      apply subseq_cons'.\n      apply IHl.\n    SCase \"test a = false\".\n      apply subseq_cons.\n      apply IHl.\nQed.\n\nTheorem all_cons_inv : forall (X : Type) (P : X -> Prop) (x : X) (l : list X),\n  all P (x :: l) -> all P l.\nProof.\n  intros X P x l H.\n  inversion H.\n  apply H3.\nQed.\n\nTheorem filter_spec_2_helper :\n  forall (X : Type) (test : X -> bool) (n : nat) (l ls : list X),\n  length l <= n ->\n  subseq ls l -> (all (fun x => test x = true) ls) ->\n  length ls <= length (filter test l).\nProof.\n  intros X test n.\n  induction n.\n  Case \"n = 0\".\n    intros l ls Hn Hs.\n    inversion Hn.\n    apply length_nil_zero in H0.\n    rewrite -> H0 in Hs.\n    inversion Hs.\n    simpl.\n    intros.\n    apply O_le_n.\n  Case \"n = S n\".\n    destruct l.\n    SCase \"l = nil\".\n      intros ls Hn Hs.\n      inversion Hs.\n      simpl.\n      intros.\n      apply O_le_n.\n    SCase \"l = a :: l\".\n      intros ls Hn.\n      generalize dependent ls.\n      simpl in Hn.\n      apply Sn_le_Sm__n_le_m in Hn.\n      simpl.\n      destruct (test x) eqn : Htx.\n      SSCase \"test x = true\".\n        destruct ls.\n        SSSCase \"ls = nil\".\n          simpl.\n          intros.\n          apply O_le_n.\n        SSSCase \"ls = x0 :: ls\".\n          intros Hs Ht.\n          simpl.\n          apply n_le_m__Sn_le_Sm.\n          apply all_cons_inv in Ht.\n          inversion Hs.\n          SSSSCase \"cons\".\n            assert (subseq ls l).\n            apply subseq_cons_inv in H1.\n            apply H1.\n            apply IHn.\n            apply Hn.\n            apply H3.\n            apply Ht.\n          SSSSCase \"cons'\".\n            apply IHn.\n            apply Hn.\n            apply H0.\n            apply Ht.\n      SSCase \"test x = false\".\n        intros ls Hs Ht.\n        inversion Hs.\n        SSSCase \"ls = nil\".\n          simpl. apply O_le_n.\n        SSSCase \"cons\".\n          apply IHn.\n          apply Hn.\n          apply H1.\n          apply Ht.\n        SSSCase \"cons'\".\n          rewrite <- H0 in Ht.\n          inversion Ht.\n          rewrite -> H in H5.\n          rewrite -> H5 in Htx.\n          inversion Htx.\nQed.\n\nTheorem filter_spec_2 :\n  forall (X : Type) (test : X -> bool) (l ls : list X),\n  subseq ls l ->\n  (all (fun x => test x = true) ls) ->\n  length ls <= length (filter test l).\nProof.\n  intros.\n  apply filter_spec_2_helper with (n := length l).\n  apply le_n.\n  apply H.\n  apply H0.\nQed.\n\n(* END filter_challenge_2. *)\n\n(* Exercise: 4 stars, advanced (no_repeats) *)\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\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  intros X xs.\n  induction xs.\n  Case \"xs = nil\".\n    intros ys x H.\n    simpl in H.\n    right.\n    apply H.\n  Case \"xs = a :: xs\".\n    intros ys x H.\n    simpl in H.\n    inversion H.\n    left.\n    apply ai_here.\n    apply IHxs in H1.\n    inversion H1.\n    left.\n    apply ai_later.\n    apply H3.\n    right.\n    apply H3.\nQed.\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  intros X xs.\n  induction xs.\n  Case \"xs = nil\".\n    intros ys x H.\n    inversion H.\n    inversion H0.\n    simpl. apply H0.\n  Case \"xs = a :: xs\".\n    intros ys x H.\n    inversion H.\n    inversion H0.\n    apply ai_here.\n    simpl.\n    apply ai_later.\n    apply IHxs.\n    left.\n    apply H2.\n    simpl.\n    apply ai_later.\n    apply IHxs.\n    right.\n    apply H0.\nQed.\n\nInductive disjoint {X : Type} : list X -> list X -> Prop :=\n  | dis_nil  : forall l, disjoint nil l \n  | dis_cons : forall x l1 l2, disjoint l1 l2 -> not (appears_in x l2) ->\n                disjoint (x :: l1) l2.\n\nInductive no_repeats {X : Type} : list X -> Prop :=\n  | nr_nil  : no_repeats nil\n  | nr_cons : forall x l, no_repeats l -> not (appears_in x l) ->\n                no_repeats (x :: l).\n\nTheorem disjoint_app_no_repeats : forall (X : Type) (l1 l2 : list X),\n  disjoint l1 l2 -> no_repeats l1 -> no_repeats l2 -> no_repeats (l1 ++ l2).\nProof.\n  induction l1.\n  Case \"l1 = nil\".\n    intros. simpl. apply H1.\n  Case \"l1 = a :: l1\".\n    intros. simpl.\n    inversion H0.\n    inversion H.\n    apply nr_cons.\n    apply IHl1.\n    apply H8.\n    apply H4.\n    apply H1.\n    unfold not.\n    intros.\n    apply appears_in_app in H11.\n    inversion H11.\n    unfold not in H5.\n    apply H5.\n    apply H12.\n    unfold not in H10.\n    apply H10.\n    apply H12.\nQed.\n\n(* END no_repeats. *)\n\n(* Exercise: 3 stars (nostutter) *)\n\nInductive nostutter {X : Type} : list X -> Prop :=\n  | nost_nil  : nostutter nil\n  | nost_one  : forall a, nostutter (a :: nil)%list\n  | nost_cons : forall a b l, not (a = b) -> nostutter (b :: l)%list ->\n                  nostutter (a :: b :: l)%list.\n\nExample test_nostutter1 : nostutter (3 :: 1 :: 4 :: 1 :: 5 :: 6 :: nil)%list.\nProof. repeat constructor; auto. Qed.\n\nExample test_nostutter2 : forall (X : Type), nostutter (@nil X).\nProof. repeat constructor; auto. Qed.\n\nExample test_nostutter3 : nostutter (5 :: nil)%list.\nProof. repeat constructor; auto. Qed.\n\nExample test_nostutter4 : not (nostutter (3 :: 1 :: 1 :: 4 :: nil)%list).\nProof.\n  intro.\n  repeat match goal with\n    h : nostutter _ |- _ => inversion h; clear h; subst end.\n  contradiction H1; trivial.\nQed.\n\n(* END nostutter. *)\n\n(* Exercise: 4 stars, advanced (pigeonhole principle) *)\n\nLemma appears_in_app_split : forall (X : Type) (x : X) (l : list X),\n  appears_in x l -> exists l1, exists l2, (l = l1 ++ (x :: l2))%list.\nProof.\n  intros X x l H.\n  induction l.\n  Case \"l = nil\".\n    inversion H.\n  Case \"l = a :: l\".\n    inversion H.\n    SCase \"a = x\".\n      exists nil.\n      exists l.\n      reflexivity.\n    SCase \"appears_in x l\".\n      apply IHl in H1.\n      destruct H1.\n      destruct H1.\n      exists (a :: x0)%list.\n      exists x1.\n      rewrite -> H1.\n      reflexivity.\nQed.\n\nInductive repeats {X : Type} : list X -> Prop :=\n  | rep_n    : forall x l, appears_in x l -> repeats (x :: l)\n  | rep_cons : forall x l, repeats l -> repeats (x :: l).\n\nTheorem pure_functions : forall (X Y : Type) (f : X -> Y) (x1 x2 : X),\n  x1 = x2 -> f x1 = f x2.\nProof.\n  intros X Y f x1 x2 H.\n  rewrite -> H.\n  trivial.\nQed.\n\nTheorem appears_app_comm : forall (X : Type) (x : X) (l1 l2 : list X),\n  appears_in x (l1 ++ l2) -> appears_in x (l2 ++ l1).\nProof.\n  intros.\n  apply appears_in_app in H.\n  apply or_comm in H.\n  apply app_appears_in in H.\n  apply H.\nQed.\n\nTheorem length_app_comm : forall (X : Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length (l2 ++ l1).\nProof.\n  intros X l1 l2.\n  rewrite -> app_length.\n  rewrite -> app_length.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\n\nTheorem pigeonhole_principle :\n  excluded_middle ->\n  forall (X : Type) (l1 l2 : list X),\n  (forall x, appears_in x l1 -> appears_in x l2) ->\n  length l2 < length l1 ->\n  repeats l1.\nProof.\n  intros EM.\n  intros X l1. induction l1 as [|x l1'].\n  Case \"l1 = nil\".\n    intros. inversion H0.\n  Case \"l1 = x :: l1'\".\n    intros.\n    assert (appears_in x (x :: l1')).\n      apply ai_here.\n    apply H in H1.\n    apply appears_in_app_split in H1.\n    inversion H1.\n    inversion H2.\n    rewrite -> H3 in H0.\n    rewrite -> length_app_comm in H0.\n    unfold lt in H0.\n    simpl in H0.\n    apply Sn_le_Sm__n_le_m in H0.\n    rewrite -> H3 in H.\n    assert (forall z : X, appears_in z (x :: l1') ->\n        appears_in z (x :: (x1 ++ x0))%list).\n      intros z Hz.\n      apply H in Hz.\n      apply appears_app_comm in Hz.\n      simpl in Hz.\n      apply Hz.\n    (* Excluded middle *)\n    assert (appears_in x l1' \\/ not (appears_in x l1')).\n      apply EM.\n    destruct H5.\n    SCase \"x appears in l1'\".\n      apply rep_n.\n      apply H5.\n    SCase \"x does not appear in l1'\".\n      apply rep_cons.\n      apply IHl1' with (l2 := (x1 ++ x0)%list).\n      intros x2 Hh.\n      assert (x2 = x \\/ not (x2 = x)).\n        apply EM.\n      destruct H6.\n      SSCase \"x2 = x\".\n        rewrite -> H6 in Hh.\n        apply H5 in Hh.\n        inversion Hh.\n      SSCase \"x2 <> x\".\n        apply ai_later with (b := x) in Hh.\n        apply H4 in Hh.\n        inversion Hh.\n        apply H6 in H8.\n        inversion H8.\n        apply H8.\n        unfold lt.\n        apply H0.\nQed.\n\n(* END pigeonhole principle. *)\n", "meta": {"author": "rouanth", "repo": "learning", "sha": "b45a4cde6118a2ba756bf70f04c3b67fc01f6ac6", "save_path": "github-repos/coq/rouanth-learning", "path": "github-repos/coq/rouanth-learning/learning-b45a4cde6118a2ba756bf70f04c3b67fc01f6ac6/swotarfe_andufotions/src/MoreLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7194373638287946}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_30helper.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_crossimpliesopposite.\nRequire Export GeoCoq.Elements.OriginalProofs.proposition_30A.\n\nSection Euclid.\n\nContext `{Ax:euclidean_euclidean}.\n\nLemma parnotmeet: forall A B C D,\n Par A B C D -> ~ Meet A B C D.\nProof.\nintros.\nconclude_def Par.\nQed.\n\nLemma proposition_30 : \n   forall A B C D E F G H K, \n   Par A B E F -> Par C D E F -> BetS G H K -> Col A B G -> Col E F H -> Col C D K -> neq A G -> neq E H -> neq C K ->\n   Par A B C D.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists b, (BetS A G b /\\ Cong G b A G)) by (conclude lemma_extension);destruct Tf as [b];spliter.\nlet Tf:=fresh in\nassert (Tf:exists f, (BetS E H f /\\ Cong H f E H)) by (conclude lemma_extension);destruct Tf as [f];spliter.\nlet Tf:=fresh in\nassert (Tf:exists d, (BetS C K d /\\ Cong K d C K)) by (conclude lemma_extension);destruct Tf as [d];spliter.\nassert (nCol C D E) by (forward_using lemma_parallelNC).\nassert (neq C D) by (forward_using lemma_NCdistinct).\nassert (Col A G b) by (conclude_def Col ).\nassert (Col G A b) by (forward_using lemma_collinearorder).\nassert (Col G A B) by (forward_using lemma_collinearorder).\nassert (neq G A) by (conclude lemma_inequalitysymmetric).\nassert (Col A b B) by (conclude lemma_collinear4).\nassert (Col B A b) by (forward_using lemma_collinearorder).\nassert (Par E F A B) by (conclude lemma_parallelsymmetric).\nassert (Par E F B A) by (forward_using lemma_parallelflip).\nassert (neq A b) by (forward_using lemma_betweennotequal).\nassert (neq b A) by (conclude lemma_inequalitysymmetric).\nassert (Par E F b A) by (conclude lemma_collinearparallel).\nassert (Par E F A b) by (forward_using lemma_parallelflip).\nassert (Par A b E F) by (conclude lemma_parallelsymmetric).\nassert (Col E H f) by (conclude_def Col ).\nassert (Col H E f) by (forward_using lemma_collinearorder).\nassert (Col H E F) by (forward_using lemma_collinearorder).\nassert (neq H E) by (conclude lemma_inequalitysymmetric).\nassert (Col E f F) by (conclude lemma_collinear4).\nassert (Col F E f) by (forward_using lemma_collinearorder).\nassert (neq E f) by (forward_using lemma_betweennotequal).\nassert (neq f E) by (conclude lemma_inequalitysymmetric).\nassert (Par A b F E) by (forward_using lemma_parallelflip).\nassert (Par A b f E) by (conclude lemma_collinearparallel).\nassert (Par A b E f) by (forward_using lemma_parallelflip).\nassert (Col C K d) by (conclude_def Col ).\nassert (Col K C d) by (forward_using lemma_collinearorder).\nassert (Col K C D) by (forward_using lemma_collinearorder).\nassert (neq K C) by (conclude lemma_inequalitysymmetric).\nassert (Col C d D) by (conclude lemma_collinear4).\nassert (Col D C d) by (forward_using lemma_collinearorder).\nassert (Par E F C D) by (conclude lemma_parallelsymmetric).\nassert (Par E F D C) by (forward_using lemma_parallelflip).\nassert (neq C d) by (forward_using lemma_betweennotequal).\nassert (neq d C) by (conclude lemma_inequalitysymmetric).\nassert (Par E F d C) by (conclude lemma_collinearparallel).\nassert (Par E F C d) by (forward_using lemma_parallelflip).\nassert (Par C d E F) by (conclude lemma_parallelsymmetric).\nassert (Par C d F E) by (forward_using lemma_parallelflip).\nassert (Par C d f E) by (conclude lemma_collinearparallel).\nassert (Par C d E f) by (forward_using lemma_parallelflip).\nassert (eq H H) by (conclude cn_equalityreflexive).\nassert (Col E H H) by (conclude_def Col ).\nassert (Col A b G) by (forward_using lemma_collinearorder).\nassert (Col E f H) by (forward_using lemma_collinearorder).\nassert (Col f E H) by (forward_using lemma_collinearorder).\nassert (Par A b f E) by (forward_using lemma_parallelflip).\nassert (Par A b H E) by (conclude lemma_collinearparallel).\nassert (Par H E A b) by (conclude lemma_parallelsymmetric).\nassert (Par E H b A) by (forward_using lemma_parallelflip).\nassert (Col b A G) by (forward_using lemma_collinearorder).\nassert (Par E H G A) by (conclude lemma_collinearparallel).\nassert (Par E H A G) by (forward_using lemma_parallelflip).\nassert (Par A G E H) by (conclude lemma_parallelsymmetric).\nassert (Par C d f E) by (forward_using lemma_parallelflip).\nassert (Col f E H) by (forward_using lemma_collinearorder).\nassert (Par C d H E) by (conclude lemma_collinearparallel).\nassert (Par H E C d) by (conclude lemma_parallelsymmetric).\nassert (Par H E d C) by (forward_using lemma_parallelflip).\nassert (Col C K d) by (conclude_def Col ).\nassert (Col d C K) by (forward_using lemma_collinearorder).\nassert (neq C K) by (forward_using lemma_betweennotequal).\nassert (neq K C) by (conclude lemma_inequalitysymmetric).\nassert (Par H E K C) by (conclude lemma_collinearparallel).\nassert (Par E H C K) by (forward_using lemma_parallelflip).\nassert (TP E H C K) by (conclude lemma_paralleldef2B).\nassert (OS C K E H) by (conclude_def TP ).\nassert (nCol E H K) by (forward_using lemma_parallelNC).\nassert (BetS K H G) by (conclude axiom_betweennesssymmetry).\nassert (TS K E H G) by (conclude_def TS ).\nassert (TS C E H G) by (conclude lemma_planeseparation).\nlet Tf:=fresh in\nassert (Tf:exists Q, (BetS C Q G /\\ Col E H Q /\\ nCol E H C)) by (conclude_def TS );destruct Tf as [Q];spliter.\nassert (Par E f C d) by (conclude lemma_parallelsymmetric).\nassert (TP E f C d) by (conclude lemma_paralleldef2B).\nassert (OS C d E f) by (conclude_def TP ).\nassert (OS d C E f) by (forward_using lemma_samesidesymmetric).\nassert (Col E H f) by (conclude_def Col ).\nassert (Col H E f) by (forward_using lemma_collinearorder).\nassert (Col H E Q) by (forward_using lemma_collinearorder).\nassert (Col E f Q) by (conclude lemma_collinear4).\nassert (nCol C E f) by (forward_using lemma_parallelNC).\nassert (nCol E f C) by (forward_using lemma_NCorder).\nassert (TS C E f G) by (conclude_def TS ).\nassert (TS d E f G) by (conclude lemma_planeseparation).\nlet Tf:=fresh in\nassert (Tf:exists P, (BetS d P G /\\ Col E f P /\\ nCol E f d)) by (conclude_def TS );destruct Tf as [P];spliter.\nassert (~ ~ (CR A f G H \\/ CR A E G H)).\n {\n intro.\n assert (CR A E G H) by (conclude lemma_30helper).\n contradict.\n }\nassert (~ ~ (CR C f K H \\/ CR C E K H)).\n {\n intro.\n assert (CR C E K H) by (conclude lemma_30helper).\n contradict.\n }\nassert (Col F E H) by (forward_using lemma_collinearorder).\nassert (Col B A G) by (forward_using lemma_collinearorder).\nassert (Par A B F E) by (forward_using lemma_parallelflip).\nassert (Par A B H E) by (conclude lemma_collinearparallel).\nassert (Par A B E H) by (forward_using lemma_parallelflip).\nassert (Par E H A B) by (conclude lemma_parallelsymmetric).\nassert (Par E H B A) by (forward_using lemma_parallelflip).\nassert (Par E H G A) by (conclude lemma_collinearparallel).\nassert (Par E H A G) by (forward_using lemma_parallelflip).\nassert (Par A G E H) by (conclude lemma_parallelsymmetric).\nassert (nCol A G H) by (forward_using lemma_parallelNC).\nassert (Par C D F E) by (forward_using lemma_parallelflip).\nassert (Par C D H E) by (conclude lemma_collinearparallel).\nassert (Par C D E H) by (forward_using lemma_parallelflip).\nassert (Par E H C D) by (conclude lemma_parallelsymmetric).\nassert (Par E H D C) by (forward_using lemma_parallelflip).\nassert (Col D C K) by (forward_using lemma_collinearorder).\nassert (Par E H K C) by (conclude lemma_collinearparallel).\nassert (Par E H C K) by (forward_using lemma_parallelflip).\nassert (Par C K E H) by (conclude lemma_parallelsymmetric).\nassert (nCol C K H) by (forward_using lemma_parallelNC).\nassert (nCol K H C) by (forward_using lemma_NCorder).\nassert (nCol E H K) by (forward_using lemma_parallelNC).\nassert (Col E H f) by (conclude_def Col ).\nassert (neq H f) by (forward_using lemma_betweennotequal).\nassert (neq f H) by (conclude lemma_inequalitysymmetric).\nassert (eq H H) by (conclude cn_equalityreflexive).\nassert (Col E H H) by (conclude_def Col ).\nassert (nCol f H K) by (conclude lemma_NChelper).\nassert (nCol K H f) by (forward_using lemma_NCorder).\nassert (Col K H H) by (conclude_def Col ).\nassert (Par A b C d).\nby cases on (CR A f G H \\/ CR A E G H).\n{\n assert (TS A G H f) by (forward_using lemma_crossimpliesopposite).\n assert (Par A b C d).\n by cases on (CR C f K H \\/ CR C E K H).\n {\n  assert (TS f H K C) by (forward_using lemma_crossimpliesopposite).\n  assert (Par A b C d)\n   by (apply (proposition_30A _ _ _ _ E f G H K);assumption).\n  close.\n  }\n {\n  let Tf:=fresh in\n  assert (Tf:exists M, (BetS C M E /\\ BetS K M H)) by (conclude_def CR );destruct Tf as [M];spliter.\n  assert (Col K M H) by (conclude_def Col ).\n  assert (Col K H M) by (forward_using lemma_collinearorder).\n  assert (BetS f H E) by (conclude axiom_betweennesssymmetry).\n  assert (OS f C K H) by (conclude_def OS ).\n  assert (eq K K) by (conclude cn_equalityreflexive).\n  assert (Col K H K) by (conclude_def Col ).\n  assert (TS C K H d) by (conclude_def TS ).\n  assert (TS f K H d) by (conclude lemma_planeseparation).\n  let Tf:=fresh in\n  assert (Tf:exists m, (BetS f m d /\\ Col K H m /\\ nCol K H f)) by (conclude_def TS );destruct Tf as [m];spliter.\n  assert (Par f E C d) by (conclude lemma_parallelsymmetric).\n  assert (~ Meet f E C d) by (auto using parnotmeet).\n  assert (Col f H E) by (forward_using lemma_collinearorder).\n  assert (neq f E) by (forward_using lemma_betweennotequal).\n  assert (neq f H) by (conclude lemma_inequalitysymmetric).\n  assert (neq K d) by (forward_using lemma_betweennotequal).\n  assert (Col H K m) by (forward_using lemma_collinearorder).\n  assert (BetS H m K) by (conclude lemma_collinearbetween).\n  assert (BetS K m H) by (conclude axiom_betweennesssymmetry).\n  assert (BetS d m f) by (conclude axiom_betweennesssymmetry).\n  assert (CR d f K H) by (conclude_def CR ).\n  assert (nCol C K H) by (forward_using lemma_NCorder).\n  assert (Col C K d) by (conclude_def Col ).\n  assert (neq d K) by (conclude lemma_inequalitysymmetric).\n  assert (Col C K K) by (conclude_def Col ).\n  assert (nCol d K H) by (conclude lemma_NChelper).\n  assert (TS d H K f) by (forward_using lemma_crossimpliesopposite).\n  assert (Par d C E f) by (forward_using lemma_parallelflip).\n  assert (BetS d K C) by (conclude axiom_betweennesssymmetry).\n  assert (TS f H K d) by (conclude lemma_oppositesidesymmetric).\n  assert (Par A b d C).\n  { simple eapply proposition_30A.\n    exact H40.\n    exact H171.\n    exact H2.\n    exact H9.\n    exact H11.\n    exact H172.\n    exact H138.\n    exact H173.\n }\n  assert (Par A b C d) by (forward_using lemma_parallelflip).\n  close.\n  }\n(** cases *)\n close.\n }\n{\n assert (Par A b C d).\n by cases on (CR C f K H \\/ CR C E K H).\n {\n  let Tf:=fresh in\n  assert (Tf:exists M, (BetS C M f /\\ BetS K M H)) by (conclude_def CR );destruct Tf as [M];spliter.\n  assert (Col K M H) by (conclude_def Col ).\n  assert (Col K H M) by (forward_using lemma_collinearorder).\n  assert (nCol K H E) by (forward_using lemma_NCorder).\n  assert (nCol K H C) by (forward_using lemma_NCorder).\n  assert (OS E C K H) by (conclude_def OS ).\n  assert (eq K K) by (conclude cn_equalityreflexive).\n  assert (Col K H K) by (conclude_def Col ).\n  assert (TS C K H d) by (conclude_def TS ).\n  assert (TS E K H d) by (conclude lemma_planeseparation).\n  let Tf:=fresh in\n  assert (Tf:exists m, (BetS E m d /\\ Col K H m /\\ nCol K H E)) by (conclude_def TS );destruct Tf as [m];spliter.\n  assert (Par E f C d) by (conclude lemma_parallelsymmetric).\n  assert (~ Meet E f C d) by (auto using parnotmeet).\n  assert (Col E H f) by (forward_using lemma_collinearorder).\n  assert (neq E f) by (forward_using lemma_betweennotequal).\n  assert (neq E H) by (conclude lemma_inequalitysymmetric).\n  assert (neq K d) by (forward_using lemma_betweennotequal).\n  assert (Col H K m) by (forward_using lemma_collinearorder).\n  assert (BetS H m K) by (conclude lemma_collinearbetween).\n  assert (BetS K m H) by (conclude axiom_betweennesssymmetry).\n  assert (BetS d m E) by (conclude axiom_betweennesssymmetry).\n  assert (CR d E K H) by (conclude_def CR ).\n  assert (nCol C K H) by (forward_using lemma_NCorder).\n  assert (Col C K d) by (conclude_def Col ).\n  assert (neq d K) by (conclude lemma_inequalitysymmetric).\n  assert (Col C K K) by (conclude_def Col ).\n  assert (nCol d K H) by (conclude lemma_NChelper).\n  assert (TS d H K E) by (forward_using lemma_crossimpliesopposite).\n  assert (Par d C f E) by (forward_using lemma_parallelflip).\n  assert (BetS d K C) by (conclude axiom_betweennesssymmetry).\n  assert (TS E H K d) by (conclude lemma_oppositesidesymmetric).\n  assert (TS A G H E) by (forward_using lemma_crossimpliesopposite).\n  assert (BetS f H E) by (conclude axiom_betweennesssymmetry).\n  assert (Par A b d C) by (conclude proposition_30A).\n  assert (Par A b C d) by (forward_using lemma_parallelflip).\n  close.\n  }\n {\n  assert (TS C H K E) by (forward_using lemma_crossimpliesopposite).\n  assert (TS E H K C) by (conclude lemma_oppositesidesymmetric).\n  assert (TS A G H E) by (forward_using lemma_crossimpliesopposite).\n  assert (BetS f H E) by (conclude axiom_betweennesssymmetry).\n  assert (Par A b C d).\n   { \n  simple eapply proposition_30A.\n   exact H62.\n   exact H70.\n   exact H2.\n   exact H9.\n   exact H143.\n   exact H13.\n   exact H142.\n   exact H141.\n  }\n  close.\n  }\n(** cases *)\n close.\n }\n(** cases *)\nassert (Par A b d C) by (forward_using lemma_parallelflip).\nassert (Col d C D) by (forward_using lemma_collinearorder).\nassert (neq D C) by (conclude lemma_inequalitysymmetric).\nassert (Par A b D C) by (conclude lemma_collinearparallel).\nassert (Par A b C D) by (forward_using lemma_parallelflip).\nassert (Par C D A b) by (conclude lemma_parallelsymmetric).\nassert (Par C D b A) by (forward_using lemma_parallelflip).\nassert (Col b A B) by (forward_using lemma_collinearorder).\nassert (nCol A B E) by (forward_using lemma_parallelNC).\nassert (neq B A) by (forward_using lemma_NCdistinct).\nassert (Par C D B A) by (conclude lemma_collinearparallel).\nassert (Par C D A B) by (forward_using lemma_parallelflip).\nassert (Par A B C D) by (conclude lemma_parallelsymmetric).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_30.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7194373613595125}}
{"text": "Require Export Coq.ZArith.ZArith.\n\nOpen Scope Z.\n\nModule bounds.\n\nLemma lt_lt_trans: forall (b c a d x:Z),\n  b < x < c ->\n  a <= b ->\n  c <= d ->\n  a < x < d.\nProof. intros b c a d x [] ; split ; omega. Qed.\n\nLemma lt_impl_le: forall (a b x:Z),\n  a < x < b ->\n  a <= x <= b.\nProof. intros ; split ; omega. Qed.\n\nLemma le_le_trans: forall (a b c d x:Z),\n  b <= x <= c ->\n  a <= b ->\n  c <= d ->\n  a <= x <= d.\nProof. intros a b c d x [] ; split ; omega. Qed.\n\nLemma le_lt_trans: forall (b c a d x:Z),\n  b <= x <= c ->\n  a < b ->\n  c < d ->\n  a < x < d.\nProof. intros b c a d x [] ; split ; omega. Qed.\n\nLemma lelt_lt_trans: forall (b c a d x:Z),\n  b <= x < c ->\n  a < b ->\n  c < d ->\n  a < x < d.\nProof. intros b c a d x [] ; split ; omega. Qed.\n\nLemma lelteq_lt_trans: forall (b d a x:Z),\n  b <= x < d ->\n  a < b ->\n  a < x < d.\nProof. intros b a d x [] ; split ; omega. Qed.\n\nEnd bounds.\n\nClose Scope Z.\n\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/proofs/spec/Libs/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7194287515904498}}
{"text": "Theorem p_implies_nnp : forall (p : Prop), p -> ~~p.\nProof.\n  intros p.\n  intros Hp.\n  unfold not.\n  intros Hnp.\n  apply (Hnp Hp).\nQed.\n\nDefinition lem : Prop :=\nforall (p : Prop), p \\/ (~p).\n\nTheorem doubleneg_elim :\nlem -> forall (p : Prop), ~~ p -> p.\nProof.\n  intros Hlem p Hnnp.\n  unfold not in Hnnp.\n  destruct (Hlem p) as [Hp | Hnp].\n  - assumption.\n  - unfold not in Hnp. apply Hnnp in Hnp. contradiction.\nQed.\n", "meta": {"author": "jopefd", "repo": "fmc1-coq", "sha": "f503e5d06bf894cf56d3566d03c4e39f144b2651", "save_path": "github-repos/coq/jopefd-fmc1-coq", "path": "github-repos/coq/jopefd-fmc1-coq/fmc1-coq-f503e5d06bf894cf56d3566d03c4e39f144b2651/p_iff_nnp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605947, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7194287459815323}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (x : natural) (y : natural)\n  : natural := mult x y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj226_coqofml_mN48dh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7194287395797452}}
{"text": "Require Import Arith.\nRequire Import Fin.\nRequire Import Vector.\nRequire Import NatMisc.\nImport VectorNotations.\nRequire Import NotationsMisc.\nRequire Import SigmaMisc.\nFrom Equations Require Import Equations.\nSet Equations Transparent.\nUnset Equations WithK.\n\nDerive EqDec for Fin.t.\n\n(* any two elements in Fin.t (1) are equal *)\n\nEquations fin1IsProp (x y : Fin.t 1) : x = y :=\n  fin1IsProp F1 F1 := eq_refl.\n\n(* a vector v of elements of (Fin.t n) of length m describes \n   a map (Fin.t m) -> (Fin.t n)  *)\n\nDefinition mapOfVect {m n : nat} (v : Vector.t (Fin.t n) m) :\n                     (Fin.t m) -> (Fin.t n) := nth v.\n\n(* operation on vectors inducing composition on corresponding maps *)\n\nDefinition vectCompose {m n o : nat} \n                       (v : Vector.t (Fin.t o) n)\n                       (w : Vector.t (Fin.t n) m) :\n                        Vector.t (Fin.t o) m :=\n  map (nth v) w.\n\nEquations nthMapLemma {A B: Type} {n : nat} (f : A -> B) \n                      (w : Vector.t A n) (x : Fin.t n) :\n                      nth (map f w) x = f (nth w x) :=\nnthMapLemma f nil x                :=! x;\nnthMapLemma f (cons _ ws') F1      := eq_refl;\nnthMapLemma f (cons _ ws') (FS x') := nthMapLemma f ws' x'.\n\n(* in order to improve the readability of the elements of ER,\n   we interpret the \"new\" class in ERNew as the largest element\n   in Fin.t (S n).\n   For this it is convenient to introduce FL, the largest element\n   in a Fin.t, and a map FU that just \"shifts up\" Fin.t n to Fin.t (S n).\n   Under the involutive isomorphism invertFin, FL corresponds to F1\n   and FU to FS.\n*)\n\nEquations FL (n : nat) :\n             Fin.t (S n) :=\n  FL 0     := F1;\n  FL (S n) := FS (FL n).\n\nEquations FU {n : nat} (x : Fin.t n) :\n             Fin.t (S n) :=\n  FU F1     := F1;\n  FU (FS x) := FS (FU x).\n\nEquations invertFin {n : nat} (x : Fin.t n) : \n                    Fin.t n :=\n  invertFin  F1    := FL _;\n  invertFin (FS x) := FU (invertFin x).\n\nEquations invFULemma {n : nat} (x : Fin.t n) :\n                     invertFin (FU x) = FS (invertFin x) :=\n  invFULemma F1     := _;\n  invFULemma (FS x) := (f_equal _ (invFULemma x)).\n\nEquations invFLLemma (n : nat) :\n                     invertFin (FL n) = F1 :=\n  invFLLemma 0     := eq_refl;\n  invFLLemma (S n) := f_equal FU (invFLLemma n).\n\n(* invertFin is an involution *)\n\nEquations invertFinInv {n : nat} (x : Fin.t n) :\n                       invertFin (invertFin x) = x :=\n  invertFinInv {n:=0}      x     :=! x;\n  invertFinInv {n:=(S _)}  F1    := (invFLLemma _);\n  invertFinInv {n:=(S _)} (FS y) := (eq_trans\n                                     (invFULemma (invertFin y))\n                                     (f_equal _ (invertFinInv y))).\n\n(* in particular, it is injective *)\nEquations invertFinInjective {n : nat} (x y : Fin.t n)\n                             (invEq: invertFin x = invertFin y) :\n                              x = y :=\n  invertFinInjective x y eq := x\n                                 ={ eq_sym (invertFinInv _) }=\n                               invertFin (invertFin x)\n                                 ={ f_equal invertFin eq }=\n                               invertFin (invertFin y)\n                                 ={ invertFinInv _ }=\n                               y QED.\n\n(* to use invertFin for pattern matching, we have to keep\n   the association ... *)\n\nDefinition invFinViewType {n : nat} (x : (Fin.t n)) : Type :=\n  { y : Fin.t n & x = invertFin y }.\n\nDefinition invFinView {n : nat} (x : (Fin.t n)) : invFinViewType x :=\n  {| invertFin x ; eq_sym (invertFinInv x) |}.\n\n(* case splitting according to FU and FL *)\n\nEquations(noind) finFUOrFL {n : nat} (x : Fin.t (S n)) :\n                 { y : Fin.t n & x = FU y } + ( x = FL n ) :=\n  finFUOrFL  {n:=0}     F1                  := (inr eq_refl);\n  finFUOrFL  {n:=(S _)} x with invFinView x := {\n                        | {| F1  ; eq |} := (inr eq);\n                        | {| FS _; eq |} := (inl {| invertFin _ ; eq |})}.\n\n\nEquations shiftinLast {n : nat} {A : Type} (a : A) (v : Vector.t A n) :\n                      nth (shiftin a v) (FL n) = a :=\n  shiftinLast a  []         := eq_refl;\n  shiftinLast a (cons _ ws) := eq_trans _ (shiftinLast a ws).\n\nEquations shiftinPrevious {n : nat} {A : Type} (a : A)\n                          (v : Vector.t A n) (t : Fin.t n) :\n                          nth (shiftin a v) (FU t) = nth v t :=\n  shiftinPrevious a  nil         t      :=! t;\n  shiftinPrevious a (cons _ ws)  F1     := eq_refl;\n  shiftinPrevious a (cons _ ws) (FS t') := eq_trans _ (shiftinPrevious a ws _).\n\n\n(* these are NoConfusion principles for FL and FU ...\n   how to formulate properly ? *)\n\nLemma finNotFUAndFL {n : nat} (x : Fin.t n) \n                    (eq : FU x = FL n) : False.\nProof.\n  induction n.\n  - apply (Fin.case0 _ x).\n  - pose (f_equal invertFin eq) as eq'. simpl in eq'.\n    rewrite invFULemma in eq'.\n    rewrite invFLLemma in eq'.\n    simpl in eq'.\n    inversion eq'.\nDefined.\n\nLemma fuIsInjective {n : nat} (x y : Fin.t n)\n                    (eq : FU x = FU y) : x = y.\nProof.\n  induction n.\n  - apply Fin.case0.\n  - apply (f_equal invertFin) in eq.\n    repeat rewrite invFULemma in eq.\n    inversion eq.\n    apply sigmaNat in H0. \n    apply invertFinInjective.\n    exact H0.\nDefined.\n\n\n\n(* order relations on Fin.t *)\n\nEquations toNat {n : nat} (x : Fin.t n) : nat :=\n  toNat {n:=0}      x      :=! x;\n  toNat {n:=(S _)}  F1     := 0;\n  toNat {n:=(S _)} (FS x') := S (toNat x').\n\nDefinition leF : forall {m n : nat},\n                 Fin.t m -> Fin.t n -> Prop :=\n  fun m n x y => toNat x <= toNat y.\n\nDefinition ltF : forall {m n : nat},\n                 Fin.t m -> Fin.t n -> Prop :=\n  fun m n x y => toNat x < toNat y.\n\nNotation \"x <=~ y\" := (leF x y) (at level 70).\nNotation \"x <~ y\"  := (ltF x y) (at level 70).\nNotation \"x =~ y\"  := ((x <=~ y) /\\ (y <=~ x)) (at level 70).\n\nDefinition leFDecidable {m n : nat}\n                        (x : Fin.t m) (y : Fin.t n) :\n                        {x <=~ y} + {~ (x <=~ y)}.\nProof.\n  pose (toNat x) as x'.\n  pose (toNat y) as y'.\n  exact (le_dec x' y').\nDefined.\n\nDefinition ltFDecidable {m n : nat}\n                        (x : Fin.t m) (y : Fin.t n) :\n                        {x <~ y} + {~ (x <~ y)}.\nProof.\n  pose (toNat x) as x'.\n  pose (toNat y) as y'.\n  exact (lt_dec x' y').\nDefined.\n\nLemma ltTleF {m n : nat} (x : Fin.t m) (y : Fin.t n) :\n              x <~ y <-> (FS x) <=~ y.\nProof.\n  unfold \"<~\",\"<=~\",\"<\".\n  destruct m.\n  - inversion x.\n  - destruct n.\n    + inversion y.\n    + rewrite toNat_equation_3. intuition.\nDefined.\n\nLemma eqFLemma {m n : nat} (x : Fin.t m) (y : Fin.t n) :\n                x =~ y <-> (toNat x = toNat y).\nProof.\n  unfold \"<=~\"; split.\n  - apply leAntiSymmetric.\n  - intro eq; split; rewrite eq; trivial.\nDefined.\n\nLemma eqFToEq {m : nat} (x y : Fin.t m) :\n               x =~ y <-> x = y.\nProof.\n  rewrite eqFLemma.\n  induction m.\n  - apply Fin.case0. assumption.\n  - induction x; dependent induction y.\n    + intuition.\n    + split; intro; apply False_rec.\n      * program_simpl.\n      * inversion H.\n    + split; intro; apply False_rec.\n      * program_simpl.\n      * inversion H.\n    + split; intro; inversion H.\n      * rewrite (IHx y) in H1; congruence.\n      * rewrite H; reflexivity.\nDefined.\n\nLemma ltFTricho {m n : nat} (x : Fin.t m) (y : Fin.t n) :\n      (x =~ y) + (y <~ x) + (x <~ y).\nProof.\n  unfold \"<~\".\n  pose (ltTricho (toNat x) (toNat y)) as tnT.\n  destruct tnT as [[Eq | GT ]| LT]; intuition.\n  pose ((proj2 (eqFLemma x y)) (eq_sym Eq)); intuition.\nDefined.\n\nLemma ltFTricho' {m : nat} (x y : Fin.t m) :\n      (x = y) + (y <~ x) + (x <~ y).\nProof.\n  destruct (ltFTricho x y).\n  - left. destruct s.\n    + left. rewrite eqFToEq in a; assumption.\n    + right; assumption.\n  - right. assumption.\nDefined.\n\nLemma ltFFS {m n : nat} {x : Fin.t m} {y : Fin.t n} :\n      ((FS x) <~ (FS y)) <-> (x <~ y).\nProof.\n  unfold \"<~\".\n  repeat (rewrite toNat_equation_3).\n  split.\n  - apply leSN.\n  - apply leNS.\nDefined.\n\nLemma ltFFS1 {m n : nat} {x : Fin.t m} {y : Fin.t n} :\n      ((FS x) <~ (FS y)) -> (x <~ y).\nProof. rewrite ltFFS. intuition. Defined.\n\nLemma notLtF1 {m n : nat} {x : Fin.t m} : ~ (x <~ (@F1 n)).\nProof.\n  unfold \"<~\". rewrite toNat_equation_2. apply notLt0.\nDefined.\n\nLemma ltFIrrefl {m : nat} (x : Fin.t m) : ~ (x <~ x).\nProof.\n  apply lt_irrefl.\nDefined.\n\nLemma ltFAsymm {m n : nat} (x : Fin.t m) (y : Fin.t n) : x <~ y -> ~ (y <~ x).\nProof. apply Nat.lt_asymm. Defined.\n\n", "meta": {"author": "paola-giannini", "repo": "sharing", "sha": "1717b4f2cf887615b6d396a361ffd531e7f4238b", "save_path": "github-repos/coq/paola-giannini-sharing", "path": "github-repos/coq/paola-giannini-sharing/sharing-1717b4f2cf887615b6d396a361ffd531e7f4238b/FinVectorMisc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7194287323850884}}
{"text": "Require Import Reals.\nRequire Import Interval.Tactic.\n\nGoal\n  forall x, (-1/2 <= x <= 0)%R ->\n  True.\nProof.\nintros x Hx.\ninterval_intro (Rabs x + x)%R upper with (i_bisect x, i_autodiff x, i_depth 5).\nexact I.\nQed.\n", "meta": {"author": "validsdp", "repo": "coq-interval", "sha": "4035680e718ae256601e00454279f1770e5c15e8", "save_path": "github-repos/coq/validsdp-coq-interval", "path": "github-repos/coq/validsdp-coq-interval/coq-interval-4035680e718ae256601e00454279f1770e5c15e8/testsuite/bug-20120927.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012686491107, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.7194243574327269}}
{"text": "(** * Tactics: More Basic Tactics *)\n\n(** This chapter introduces several additional proof strategies\n    and tactics that allow us to begin proving more interesting\n    properties of functional programs.  We will see:\n\n    - how to use auxiliary lemmas in both \"forward-style\" and\n      \"backward-style\" proofs;\n    - how to reason about data constructors (in particular, how to use\n      the fact that they are injective and disjoint);\n    - how to strengthen an induction hypothesis (and when such\n      strengthening is required); and\n    - more details on how to reason by case analysis. *)\n\nRequire Export Poly.\n\n(* ################################################################# *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    _exactly_ the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n\n(** Here, we could finish with \"[rewrite -> eq2.  reflexivity.]\" as we\n    have done several times before.  We can achieve the same effect in\n    a single step by using the [apply] tactic instead: *)\n\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n(*I tried and it seems like there is no way. \n    to proof it using just rewrite. *) \n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] that binds some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nDefinition test := (forall n, evenb n = true -> oddb (S n) = true).\n\nCheck test.\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 eq1 eq2. apply eq1. apply eq2. Qed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal exactly -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n\n(** Here we cannot use [apply] directly, but we can use the [symmetry]\n    tactic, which switches the left and right sides of an equality in\n    the goal. *)\n\n  symmetry.\n  simpl. (* (This [simpl] is optional, since [apply] will perform\n            simplification first, if needed.) *)\n  apply H.  Qed.\n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** (_Hint_: You can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [Search] is\n    your friend.) *)\nSearchAbout rev.\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros l l' eq1. rewrite -> eq1. symmetry. apply rev_involutive.\n  (*Alternative: \n  rewrite -> eq1. \n  rewrite -> rev_involutive. reflexivity.\n  *)\nQed. \n(** [] *)\n\n(** **** Exercise: 1 star, optionalM (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  What are the situations where both can usefully be\n    applied?\n\n(* Rewrite allows us to choose the direction of rewriting with -> or <-. \nApply on the other hand requires the fact to match the goal exaclty before \nit can be applied. In particular the apply tactic is specifically for\nconditional hypotheses and lemmas as rewrite does not help in simplification.\nThus both are usefully applied when it is not conditional.\n *)\n*)\n(** [] *)\n\n(* ################################################################# *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might like to pull it out\n    as a lemma recording, once and for all, the fact that equality is\n    transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.\n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to prove the above\n    example.  However, to do this we need a slight refinement of the\n    [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n\n(** If we simply tell Coq [apply trans_eq] at this point, it can\n    tell (by matching the goal against the conclusion of the lemma)\n    that it should instantiate [X] with [[nat]], [n] with [[a,b]], and\n    [o] with [[e,f]].  However, the matching process doesn't determine\n    an instantiation for [m]: we have to supply one explicitly by\n    adding [with (m:=[c,d])] to the invocation of [apply]. *)\n\n  apply trans_eq with (m:=[c;d]).\n  apply eq1. apply eq2.   Qed.\n\n(** Actually, we usually don't have to include the name [m] in\n    the [with] clause; Coq is often smart enough to figure out which\n    instantiation we're giving. We could instead write: [apply\n    trans_eq with [c;d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o).\nProof.\n  intros n m o p eq1 eq2. apply trans_eq with m. apply eq2. apply eq1. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * The [inversion] Tactic *)\n\n(** Recall the definition of natural numbers:\n\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n\n    It is obvious from this definition that every number has one of\n    two forms: either it is the constructor [O] or it is built by\n    applying the constructor [S] to another number.  But there is more\n    here than meets the eye: implicit in the definition (and in our\n    informal understanding of how datatype declarations work in other\n    programming languages) are two more facts:\n\n    - The constructor [S] is _injective_.  That is, if [S n = S m], it\n      must be the case that [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n].\n\n    Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor\n    is injective and [nil] is different from every non-empty list.\n    For booleans, [true] and [false] are different.  (Since neither\n    [true] nor [false] take any arguments, their injectivity is not\n    interesting.)  And so on. *)\n\n(** Coq provides a tactic called [inversion] that allows us to\n    exploit these principles in proofs. To see how to use it, let's\n    show explicitly that the [S] constructor is injective: *)\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H.\n\n(** By writing [inversion H] at this point, we are asking Coq to\n    generate all equations that it can infer from [H] as additional\n    hypotheses, replacing variables in the goal as it goes. In the\n    present example, this amounts to adding a new hypothesis [H1 : n =\n    m] and replacing [n] by [m] in the goal. *)\n\n  inversion H.\n  reflexivity.\nQed.\n\n(** Here's a more interesting example that shows how multiple\n    equations can be derived at once. *)\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros n m o H. inversion H. reflexivity. Qed.\n\n(** We can name the equations that [inversion] generates with an\n    [as ...] clause: *)\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros n m H. inversion H as [Hnm]. reflexivity.  Qed.\n\n(** **** Exercise: 1 star (inversion_ex3)  *)\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros X x y z l j H1 H2. inversion H1. inversion H2. symmetry. apply H0.\n\n(** [] *)\n\n(** When used on a hypothesis involving an equality between\n    _different_ constructors (e.g., [S n = O]), [inversion] solves the\n    goal immediately.  Consider the following proof: *)\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros n.\n\n(** We can proceed by case analysis on [n]. The first case is\n    trivial. *)\n\n  destruct n as [| n'].\n  - (* n = 0 *)\n    intros H. reflexivity.\n\n(** However, the second one doesn't look so simple: assuming\n    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter\n    clearly contradictory!  The way forward lies in the assumption.\n    After simplifying the goal state, we see that [beq_nat 0 (S n') =\n    true] has become [false = true]: *)\n\n  - (* n = S n' *)\n    simpl.\n\n(** If we use [inversion] on this hypothesis, Coq notices that\n    the subgoal we are working on is impossible, and therefore removes\n    it from further consideration. *)\n\n    intros H. inversion H. Qed.\n\n(** This is an instance of a logical principle known as the _principle\n    of explosion_, which asserts that a contradictory hypothesis\n    entails anything, even false things! *)\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros n m contra. inversion contra. Qed.\n\n(** If you find the principle of explosion confusing, remember\n    that these proofs are not actually showing that the conclusion of\n    the statement holds.  Rather, they are arguing that, if the\n    nonsensical situation described by the premise did somehow arise,\n    then the nonsensical conclusion would follow.  We'll explore the\n    principle of explosion of more detail in the next chapter. *)\n\n(** **** Exercise: 1 star (inversion_ex6)  *)\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof. intros X x y z l j H1 H2. inversion H1.\nQed.\n\n(** [] *)\n\n(** To summarize this discussion, suppose [H] is a hypothesis in the\n    context or a previously proven lemma of the form\n\n        c a1 a2 ... an = d b1 b2 ... bm\n\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] has the following effect:\n\n    - If [c] and [d] are the same constructor, then, by the\n      injectivity of this constructor, we know that [a1 = b1], [a2 =\n      b2], etc.  The [inversion H] adds these facts to the context and\n      tries to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory, and the current goal doesn't have to be\n      considered at all.  In this case, [inversion H] marks the\n      current goal as completed and pops it off the goal stack. *)\n\n(** The injectivity of constructors allows us to reason that\n    [forall (n m : nat), S n = S m -> n = m].  The converse of this\n    implication is an instance of a more general fact about both\n    constructors and functions, which we will find useful in a few\n    places below: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b.\nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, [apply L in H] matches some conditional statement\n    [L] (of the form [L1 -> L2], say) against a hypothesis [H] in the\n    context.  However, unlike ordinary [apply] (which rewrites a goal\n    matching [L2] into a subgoal [L1]), [apply L in H] matches [H]\n    against [L1] and, if successful, replaces it with [L2].\n\n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\": from [L1 -> L2] and a hypothesis matching [L1], it\n    produces a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\": it says that if we know [L1->L2] and we are\n    trying to prove [L2], it suffices to prove [L1].\n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\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  symmetry in H. apply eq in H. symmetry in H.\n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, idiomatic use of Coq tends to favor backward reasoning,\n    but in some situations the forward style can be easier to think\n    about.  *)\n\n(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise.  (Hint: use\n    [plus_n_Sm].) *)\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  { intros m H0. simpl in H0. destruct m as [| m'].\n    { reflexivity. }\n    { inversion H0. } }\n  { intros m H1. destruct m as [| m'].\n    { inversion H1. }\n    { inversion H1.\n      apply f_equal. apply IHn'.\n      rewrite <- plus_n_Sm in H0. rewrite <- plus_n_Sm in H0.\n      apply S_injective in H0.\n      apply H0. } }\nQed.\n\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose\n    we want to show that the [double] function is injective -- i.e.,\n    that it maps different arguments to different results:\n\n    Theorem double_injective: forall n m,\n      double n = double m -> n = m.\n\n    The way we _start_ this proof is a bit delicate: if we begin with\n\n      intros n. induction n.\n\n    all is well.  But if we begin it with\n\n      intros n m. induction n.\n\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *) apply f_equal.\n\n(** At this point, the induction hypothesis, [IHn'], does _not_ give us\n    [n' = m'] -- there is an extra [S] in the way -- so the goal is\n    not provable. *)\n\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context --\n    intuitively, we have told Coq, \"Let's consider some particular [n]\n    and [m]...\" and we now have to prove that, if [double n = double\n    m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove, for\n    _all_ [n], that the proposition\n\n      - [P n] = \"if [double n = double m], then [n = m]\"\n\n    holds, by showing\n\n      - [P O]\n\n         (i.e., \"if [double O = double m] then [O = m]\") and\n\n      - [P n -> P (S n)]\n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help at all with proving\n    [R]!  (If we tried to prove [R] from [Q], we would start with\n    something like \"Suppose [double (S n) = 10]...\" but then we'd be\n    stuck: knowing that [double (S n)] is [10] tells us nothing about\n    whether [double n] is [10], so [Q] is useless.) *)\n\n(** Trying to carry out this proof by induction on [n] when [m] is\n    already in the context doesn't work because we are then trying to\n    prove a relation involving _every_ [n] but just a _single_ [m]. *)\n\n(** The successful proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq.\n\n  - (* n = S n' *) simpl.\n\n(** Notice that both the goal and the induction hypothesis are\n    different this time: the goal asks us to prove something more\n    general (i.e., to prove the statement for _every_ [m]), but the IH\n    is correspondingly more flexible, allowing us to choose any [m] we\n    like when we apply the IH. *)\n\n    intros m eq.\n\n(** Now we've chosen a particular [m] and introduced the assumption\n    that [double n = double m].  Since we are doing a case analysis on\n    [n], we also need a case analysis on [m] to keep the two \"in sync.\" *)\n\n    destruct m as [| m'].\n    + (* m = O *) simpl.\n\n(** The 0 case is trivial: *)\n\n      inversion eq.\n\n    + (* m = S m' *)\n      apply f_equal.\n\n(** At this point, since we are in the second branch of the [destruct\n    m], the [m'] mentioned in the context is the predecessor of the\n    [m] we started out talking about.  Since we are also in the [S]\n    branch of the induction, this is perfect: if we instantiate the\n    generic [m] in the IH with the current [m'] (this instantiation is\n    performed automatically by the [apply] in the next step), then\n    [IHn'] gives us exactly what we need to finish the proof. *)\n\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What you should take away from all this is that we need to be\n    careful about using induction to try to prove something too\n    specific: To prove a property of [n] and [m] by induction on [n],\n    it is sometimes important to leave [m] generic. *)\n\n(** The following exercise requires the same pattern. *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n. induction n as [| n'].\n  { intros m eq. destruct m as [| m'].\n    { reflexivity. }\n    { inversion eq. } }\n  { intros m eq. destruct m as [| m'].\n    { inversion eq. }\n    { apply f_equal. apply IHn'. simpl in eq. apply eq. }}\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advancedM (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** The strategy of doing fewer [intros] before an [induction] to\n    obtain a more general IH doesn't always work by itself; sometimes\n    some _rearrangement_ of quantified variables is needed.  Suppose,\n    for example, that we wanted to prove [double_injective] by\n    induction on [m] instead of [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce [n]\n    for us!)  *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    works, but it's not nice: We don't want to have to twist the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them!  Rather we want to state them in the clearest and\n    most natural way. *)\n\n(** What we can do instead is to first introduce all the quantified\n    variables and then _re-generalize_ one or more of them,\n    selectively taking variables out of the context and putting them\n    back at the beginning of the goal.  The [generalize dependent]\n    tactic does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. \n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n    _Theorem_: For any nats [n] and [m], if [double n = double m], then\n      [n = m].\n\n    _Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n      any [n], if [double n = double m] then [n = m].\n\n      - First, suppose [m = 0], and suppose [n] is a number such\n        that [double n = double m].  We must show that [n = 0].\n\n        Since [m = 0], by the definition of [double] we have [double n =\n        0].  There are two cases to consider for [n].  If [n = 0] we are\n        done, since [m = 0 = n], as required.  Otherwise, if [n = S n']\n        for some [n'], we derive a contradiction: by the definition of\n        [double], we can calculate [double n = S (S (double n'))], but\n        this contradicts the assumption that [double n = 0].\n\n      - Second, suppose [m = S m'] and that [n] is again a number such\n        that [double n = double m].  We must show that [n = S m'], with\n        the induction hypothesis that for every number [s], if [double s =\n        double m'] then [s = m'].\n\n        By the fact that [m = S m'] and the definition of [double], we\n        have [double n = S (S (double m'))].  There are two cases to\n        consider for [n].\n\n        If [n = 0], then by definition [double n = 0], a contradiction.\n\n        Thus, we may assume that [n = S n'] for some [n'], and again by\n        the definition of [double] we have [S (S (double n')) =\n        S (S (double m'))], which implies by inversion that [double n' =\n        double m'].  Instantiating the induction hypothesis with [n'] thus\n        allows us to conclude that [n' = m'], and it follows immediately\n        that [S n' = S m'].  Since [S n' = n] and [S m' = m], this is just\n        what we wanted to show. [] *)\n\n(** Before we close this section and move on to some exercises,\n    let's digress briefly and use [beq_nat_true] to prove a similar\n    property of identifiers that we'll need in later chapters: *)\n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n]. simpl. intros H.\n  assert (H' : m = n). { apply beq_nat_true. apply H. }\n  rewrite H'. reflexivity.\nQed.\n\n(** **** Exercise: 3 stars, recommended (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros n X l.\n  generalize dependent n.\n  induction l as [|h tl IH].\n  { simpl. intros n H. reflexivity. }\n  { intros n H. simpl. destruct n as [| n'].\n    { simpl. inversion H. }\n    { simpl. apply IH. simpl in H. apply S_injective. apply H. }}\nQed.\n\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Unfolding Definitions *)\n\n(** It sometimes happens that we need to manually unfold a Definition\n    so that we can manipulate its right-hand side.  For example, if we\n    define... *)\n\nDefinition square n := n * n.\n\n(** ... and try to prove a simple fact about [square]... *)\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros n m.\n  simpl.\n\n(** ... we get stuck: [simpl] doesn't simplify anything at this point,\n    and since we haven't proved any other facts about [square], there\n    is nothing we can [apply] or [rewrite] with.\n\n    To make progress, we can manually [unfold] the definition of\n    [square]: *)\n\n  unfold square.\n\n(** Now we have plenty to work with: both sides of the equality are\n    expressions involving multiplication, and we have lots of facts\n    about multiplication at our disposal.  In particular, we know that\n    it is commutative and associative, and from these facts it is not\n    hard to finish the proof. *)\n\n  rewrite mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  { rewrite mult_comm. apply mult_assoc. }\n  rewrite H. rewrite mult_assoc. reflexivity.\nQed.\n\n(** At this point, a deeper discussion of unfolding and simplification\n    is in order.\n\n    You may already have observed that tactics like [simpl],\n    [reflexivity], and [apply] will often unfold the definitions of\n    functions automatically when this allows them to make progress.  For\n    example, if we define [foo m] to be the constant [5]... *)\n\nDefinition foo (x: nat) := 5.\n\n(** then the [simpl] in the following proof (or the [reflexivity], if\n    we omit the [simpl]) will unfold [foo m] to [(fun x => 5) m] and\n    then further simplify this expression to just [5]. *)\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  simpl.\n  reflexivity.\nQed.\n\n(** However, this automatic unfolding is rather conservative.  For\n    example, if we define a slightly more complicated function\n    involving a pattern match... *)\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\n(** ...then the analogous proof will get stuck: *)\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  simpl. (* Does nothing! *)\nAbort.\n\n(** The reason that [simpl] doesn't make progress here is that it\n    notices that, after tentatively unfolding [bar m], it is left with\n    a match whose scrutinee, [m], is a variable, so the [match] cannot\n    be simplified further.  (It is not smart enough to notice that the\n    two branches of the [match] are identical.)  So it gives up on\n    unfolding [bar m] and leaves it alone.  Similarly, tentatively\n    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a\n    function application (that, itself, cannot be simplified, even\n    after unfolding the definition of [+]), so [simpl] leaves it\n    alone.\n\n    At this point, there are two ways to make progress.  One is to use\n    [destruct m] to break the proof into two cases, each focusing on a\n    more concrete choice of [m] ([O] vs [S _]).  In each case, the\n    [match] inside of [bar] can now make progress, and the proof is\n    easy to complete. *)\n\nFact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  destruct m.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\n(** This approach works, but it depends on our recognizing that the\n    [match] hidden inside [bar] is what was preventing us from making\n    progress.\n\n    A more straightforward way to make progress is to explicitly tell\n    Coq to unfold [bar]. *)\n\nFact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n\n(** Now it is apparent that we are stuck on the [match] expressions on\n    both sides of the [=], and we can use [destruct] to finish the\n    proof without thinking too hard. *)\n\n  destruct m.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where [destruct] is used to\n    perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun.\n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  But either\n    [n] is equal to [3] or it isn't, so we can use [destruct (beq_nat\n    n 3)] to let us reason about the two cases.\n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c]. *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y.\n  destruct l as [| h tl].\n  { simpl. intros l1 l2 eq. inversion eq. simpl. reflexivity. }\n  { intros l1 l2 eq. destruct combine.\n    { inversion eq. \n  \n  \n  destruct l1 as [| h tl].\n    { simpl. reflexivity. }\n    { simpl. inversion eq. } }\n  { intros l1 l2 eq. \n(* STUCK !!! *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** However, [destruct]ing compound expressions requires a bit of\n    care, as such [destruct]s can sometimes erase information we need\n    to complete a proof. *)\n(** For example, suppose we define a function [sillyfun1] like\n    this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** Now suppose that we want to convince Coq of the (rather\n    obvious) fact that [sillyfun1 n] yields [true] only when [n] is\n    odd.  By analogy with the proofs we did with [sillyfun] above, it\n    is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution performed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that, since [beq_nat n 3 = true] in this\n    branch of the case analysis, it must be that [n = 3], from which\n    it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation, giving it a\n    name that we choose. *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got\n     stuck above, except that the context contains an extra\n     equality assumption, which is exactly what we need to\n     make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body\n        of the function we are reasoning about, we can use\n        [eqn:] again in the same way, allow us to finish the\n        proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5.\n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros f b. apply f_equal. destruct b eqn:H.\n  { destruct f eqn:f1.\n    { reflexivity. }\n    { rewrite <- H. inversion H. rewrite <- H0.   }\n  }\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Review *)\n\n(** We've now seen many of Coq's most fundamental tactics.  We'll\n    introduce a few more in the coming chapters, and later on we'll\n    see some more powerful _automation_ tactics that make Coq help us\n    with low-level details.  But basically we've got what we need to\n    get work done.\n\n    Here are the ones we've seen:\n\n      - [intros]: move hypotheses/variables from goal to context\n\n      - [reflexivity]: finish the proof (when the goal looks like [e =\n        e])\n\n      - [apply]: prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: apply a hypothesis, lemma, or constructor to\n        a hypothesis in the context (forward reasoning)\n\n      - [apply... with...]: explicitly specify values for variables\n        that cannot be determined by pattern matching\n\n      - [simpl]: simplify computations in the goal\n\n      - [simpl in H]: ... or a hypothesis\n\n      - [rewrite]: use an equality hypothesis (or lemma) to rewrite\n        the goal\n\n      - [rewrite ... in H]: ... or a hypothesis\n\n      - [symmetry]: changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]: changes a hypothesis of the form [t=u] into\n        [u=t]\n\n      - [unfold]: replace a defined constant by its right-hand side in\n        the goal\n\n      - [unfold... in H]: ... or a hypothesis\n\n      - [destruct... as...]: case analysis on values of inductively\n        defined types\n\n      - [destruct... eqn:...]: specify the name of an equation to be\n        added to the context, recording the result of the case\n        analysis\n\n      - [induction... as...]: induction on values of inductively\n        defined types\n\n      - [inversion]: reason by injectivity and distinctness of\n        constructors\n\n      - [assert (H: e)] (or [assert (e) as H]): introduce a \"local\n        lemma\" [e] and call it [H]\n\n      - [generalize dependent x]: move the variable [x] (and anything\n        else that depends on it) from the context back to an explicit\n        hypothesis in the goal formula *)\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advancedM? (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advancedM (split_combine)  *)\n(** We proved, in an exercise above, that for all lists of pairs,\n    [combine] is the inverse of [split].  How would you formalize the\n    statement that [split] is the inverse of [combine]?  When is this\n    property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?) *)\n\nDefinition split_combine_statement : Prop\n  (* (\"[: Prop]\" means that we are giving a name to a\n     logical proposition here.) *)\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your\n    induction hypothesis. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced, recommended (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n\n      forallb evenb [0;2;4;5] = false\n\n      forallb (beq_nat 5) [] = true\n\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n\n      existsb (beq_nat 5) [0;2;3;6] = false\n\n      existsb (andb true) [true;true;false] = true\n\n      existsb oddb [1;0;0;0;0;3] = true\n\n      existsb evenb [] = false\n\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n\n    Finally, prove a theorem [existsb_existsb'] stating that\n    [existsb'] and [existsb] have the same behavior. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2016-10-08 18:36:21 -0400 (Sat, 08 Oct 2016) $ *)\n\n\n", "meta": {"author": "zunction", "repo": "Coqy", "sha": "a588f3b9000329eb1db25a4a81da8219bcb8f053", "save_path": "github-repos/coq/zunction-Coqy", "path": "github-repos/coq/zunction-Coqy/Coqy-a588f3b9000329eb1db25a4a81da8219bcb8f053/old version/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.8902942297605357, "lm_q1q2_score": 0.7194175857148981}}
{"text": "(*** Montgomery Multiplication *)\n(** This file implements the proofs for Montgomery Form, Montgomery\n    Reduction, and Montgomery Multiplication on [Z].  We follow\n    Wikipedia. *)\nRequire Import Coq.ZArith.ZArith Coq.micromega.Psatz Coq.Structures.Equalities.\nRequire Import Crypto.Arithmetic.MontgomeryReduction.Definition.\nRequire Import Crypto.Util.ZUtil.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SimplifyRepeatedIfs.\nRequire Import Crypto.Util.Notations.\n\nDeclare Module Nop : Nop.\nModule Import ImportEquivModuloInstances := Z.EquivModuloInstances Nop.\n\nLocal Existing Instance eq_Reflexive. (* speed up setoid_rewrite as per https://coq.inria.fr/bugs/show_bug.cgi?id=4978 *)\n\nLocal Open Scope Z_scope.\n\nSection montgomery.\n  Context (N : Z)\n          (N_reasonable : N <> 0)\n          (R : Z)\n          (R_good : Z.gcd N R = 1).\n  Local Notation \"x ≡ y\" := (Z.equiv_modulo N x y) : type_scope.\n  Local Notation \"x ≡ᵣ y\" := (Z.equiv_modulo R x y) : type_scope.\n  Context (R' : Z)\n          (R'_good : R * R' ≡ 1).\n\n  Lemma R'_good' : R' * R ≡ 1.\n  Proof using R'_good. rewrite <- R'_good; apply f_equal2; lia. Qed.\n\n  Local Notation to_montgomery_naive := (to_montgomery_naive R) (only parsing).\n  Local Notation from_montgomery_naive := (from_montgomery_naive R') (only parsing).\n\n  Lemma to_from_montgomery_naive x : to_montgomery_naive (from_montgomery_naive x) ≡ x.\n  Proof using R'_good.\n    unfold to_montgomery_naive, from_montgomery_naive.\n    rewrite <- Z.mul_assoc, R'_good'.\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n  Lemma from_to_montgomery_naive x : from_montgomery_naive (to_montgomery_naive x) ≡ x.\n  Proof using R'_good.\n    unfold to_montgomery_naive, from_montgomery_naive.\n    rewrite <- Z.mul_assoc, R'_good.\n    autorewrite with zsimplify; reflexivity.\n  Qed.\n\n  (** * Modular arithmetic and Montgomery form *)\n  Section general.\n    Local Infix \"+\" := add : montgomery_scope.\n    Local Infix \"-\" := sub : montgomery_scope.\n    Local Infix \"*\" := (mul_naive R') : montgomery_scope.\n\n    Lemma add_correct_naive x y : from_montgomery_naive (x + y) = from_montgomery_naive x + from_montgomery_naive y.\n    Proof using Type. unfold from_montgomery_naive, add; lia. Qed.\n    Lemma add_correct_naive_to x y : to_montgomery_naive (x + y) = (to_montgomery_naive x + to_montgomery_naive y)%montgomery.\n    Proof using Type. unfold to_montgomery_naive, add; autorewrite with push_Zmul; reflexivity. Qed.\n    Lemma sub_correct_naive x y : from_montgomery_naive (x - y) = from_montgomery_naive x - from_montgomery_naive y.\n    Proof using Type. unfold from_montgomery_naive, sub; lia. Qed.\n    Lemma sub_correct_naive_to x y : to_montgomery_naive (x - y) = (to_montgomery_naive x - to_montgomery_naive y)%montgomery.\n    Proof using Type. unfold to_montgomery_naive, sub; autorewrite with push_Zmul; reflexivity. Qed.\n\n    Theorem mul_correct_naive x y : from_montgomery_naive (x * y) = from_montgomery_naive x * from_montgomery_naive y.\n    Proof using Type. unfold from_montgomery_naive, mul_naive; lia. Qed.\n    Theorem mul_correct_naive_to x y : to_montgomery_naive (x * y) ≡ (to_montgomery_naive x * to_montgomery_naive y)%montgomery.\n    Proof using R'_good.\n      unfold to_montgomery_naive, mul_naive.\n      rewrite <- !Z.mul_assoc, R'_good.\n      autorewrite with zsimplify; apply (f_equal2 Z.modulo); lia.\n    Qed.\n  End general.\n\n  (** * The REDC algorithm *)\n  Section redc.\n    Context (N' : Z)\n            (N'_in_range : 0 <= N' < R)\n            (N'_good : N * N' ≡ᵣ -1).\n\n    Lemma N'_good' : N' * N ≡ᵣ -1.\n    Proof using N'_good. rewrite <- N'_good; apply f_equal2; lia. Qed.\n\n    Lemma N'_good'_alt x : (((x mod R) * (N' mod R)) mod R) * (N mod R) ≡ᵣ x * -1.\n    Proof using N'_good.\n      rewrite <- N'_good', Z.mul_assoc.\n      unfold Z.equiv_modulo; push_Zmod.\n      reflexivity.\n    Qed.\n\n    Section redc.\n      Context (T : Z).\n\n      Local Notation m := (((T mod R) * N') mod R).\n      Local Notation prereduce := (prereduce N R N').\n\n      Local Ltac t_fin_correct :=\n        unfold Z.equiv_modulo; push_Zmod; autorewrite with zsimplify; reflexivity.\n\n      Lemma prereduce_correct : prereduce T ≡ T * R'.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        transitivity ((T + m * N) * R').\n        { unfold prereduce.\n          autorewrite with zstrip_div; push_Zmod.\n          rewrite N'_good'_alt.\n          autorewrite with zsimplify pull_Zmod.\n          reflexivity. }\n        t_fin_correct.\n      Qed.\n\n      Lemma reduce_correct : reduce N R N' T ≡ T * R'.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold reduce.\n        break_match; rewrite prereduce_correct; t_fin_correct.\n      Qed.\n\n      Lemma partial_reduce_correct : partial_reduce N R N' T ≡ T * R'.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold partial_reduce.\n        break_match; rewrite prereduce_correct; t_fin_correct.\n      Qed.\n\n      Lemma reduce_via_partial_correct : reduce_via_partial N R N' T ≡ T * R'.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold reduce_via_partial.\n        break_match; rewrite partial_reduce_correct; t_fin_correct.\n      Qed.\n\n      Let m_small : 0 <= m < R. Proof. auto with zarith. Qed.\n\n      Section generic.\n        Lemma prereduce_in_range_gen B\n        : 0 <= N\n          -> 0 <= T <= R * B\n          -> 0 <= prereduce T < B + N.\n        Proof using N_reasonable m_small. unfold prereduce; auto with zarith nia. Qed.\n      End generic.\n\n      Section N_very_small.\n        Context (N_very_small : 0 <= 4 * N < R).\n\n        Lemma prereduce_in_range_very_small\n          : 0 <= T <= (2 * N - 1) * (2 * N - 1)\n            -> 0 <= prereduce T < 2 * N.\n        Proof using N_reasonable N_very_small m_small. pose proof (prereduce_in_range_gen N); nia. Qed.\n      End N_very_small.\n\n      Section N_small.\n        Context (N_small : 0 <= 2 * N < R).\n\n        Lemma prereduce_in_range_small\n          : 0 <= T <= (2 * N - 1) * (N - 1)\n            -> 0 <= prereduce T < 2 * N.\n        Proof using N_reasonable N_small m_small. pose proof (prereduce_in_range_gen N); nia. Qed.\n\n        Lemma prereduce_in_range_small_fully_reduced\n          : 0 <= T <= 2 * N\n            -> 0 <= prereduce T <= N.\n        Proof using N_reasonable N_small m_small. pose proof (prereduce_in_range_gen 1); nia. Qed.\n      End N_small.\n\n      Section N_small_enough.\n        Context (N_small_enough : 0 <= N < R).\n\n        Lemma prereduce_in_range_small_enough\n          : 0 <= T <= R * R\n            -> 0 <= prereduce T < R + N.\n        Proof using N_reasonable N_small_enough m_small. pose proof (prereduce_in_range_gen R); nia. Qed.\n\n        Lemma reduce_in_range_R\n          : 0 <= T <= R * R\n            -> 0 <= reduce N R N' T < R.\n        Proof using N_reasonable N_small_enough m_small.\n          intro H; pose proof (prereduce_in_range_small_enough H).\n          unfold reduce, prereduce in *; break_match; Z.ltb_to_lt; nia.\n        Qed.\n\n        Lemma partial_reduce_in_range_R\n          : 0 <= T <= R * R\n            -> 0 <= partial_reduce N R N' T < R.\n        Proof using N_reasonable N_small_enough m_small.\n          intro H; pose proof (prereduce_in_range_small_enough H).\n          unfold partial_reduce, prereduce in *; break_match; Z.ltb_to_lt; nia.\n        Qed.\n\n        Lemma reduce_via_partial_in_range_R\n          : 0 <= T <= R * R\n            -> 0 <= reduce_via_partial N R N' T < R.\n        Proof using N_reasonable N_small_enough m_small.\n          intro H; pose proof (prereduce_in_range_small_enough H).\n          unfold reduce_via_partial, partial_reduce, prereduce in *; break_match; Z.ltb_to_lt; nia.\n        Qed.\n      End N_small_enough.\n\n      Section unconstrained.\n        Lemma prereduce_in_range\n          : 0 <= T <= R * N\n            -> 0 <= prereduce T < 2 * N.\n        Proof using N_reasonable m_small. pose proof (prereduce_in_range_gen N); nia. Qed.\n\n        Lemma reduce_in_range\n        : 0 <= T <= R * N\n          -> 0 <= reduce N R N' T < N.\n        Proof using N_reasonable m_small.\n          intro H; pose proof (prereduce_in_range H).\n          unfold reduce, prereduce in *; break_match; Z.ltb_to_lt; nia.\n        Qed.\n\n        Lemma partial_reduce_in_range\n        : 0 <= T <= R * N\n          -> Z.min 0 (R - N) <= partial_reduce N R N' T < 2 * N.\n        Proof using N_reasonable m_small.\n          intro H; pose proof (prereduce_in_range H).\n          unfold partial_reduce, prereduce in *; break_match; Z.ltb_to_lt;\n            apply Z.min_case_strong; nia.\n        Qed.\n\n        Lemma reduce_via_partial_in_range\n        : 0 <= T <= R * N\n          -> Z.min 0 (R - N) <= reduce_via_partial N R N' T < N.\n        Proof using N_reasonable m_small.\n          intro H; pose proof (partial_reduce_in_range H).\n          unfold reduce_via_partial in *; break_match; Z.ltb_to_lt; lia.\n        Qed.\n      End unconstrained.\n\n      Section alt.\n        Context (N_in_range : 0 <= N < R)\n                (T_representable : 0 <= T < R * R).\n        Lemma partial_reduce_alt_eq : partial_reduce_alt N R N' T = partial_reduce N R N' T.\n        Proof using N_in_range N_reasonable T_representable m_small.\n          assert (0 <= T + m * N < 2 * (R * R)) by nia.\n          assert (0 <= T + m * N < R * (R + N)) by nia.\n          assert (0 <= (T + m * N) / R < R + N) by auto with zarith.\n          assert ((T + m * N) / R - N < R) by lia.\n          assert (R * R <= T + m * N -> R <= (T + m * N) / R) by auto with zarith.\n          assert (T + m * N < R * R -> (T + m * N) / R < R) by auto with zarith.\n          assert (H' : (T + m * N) mod (R * R) = if R * R <=? T + m * N then T + m * N - R * R else T + m * N)\n            by (break_match; Z.ltb_to_lt; autorewrite with zsimplify; lia).\n          unfold partial_reduce, partial_reduce_alt, prereduce.\n          rewrite H'; clear H'.\n          simplify_repeated_ifs.\n          set (m' := m) in *.\n          autorewrite with zsimplify; push_Zmod; autorewrite with zsimplify; pull_Zmod.\n          break_match; Z.ltb_to_lt; autorewrite with zsimplify; try reflexivity; lia.\n        Qed.\n\n        Lemma reduce_via_partial_alt_eq : reduce_via_partial_alt N R N' T = reduce_via_partial N R N' T.\n        Proof.\n            cbv [reduce_via_partial_alt reduce_via_partial].\n            rewrite partial_reduce_alt_eq by omega. reflexivity.\n        Qed.\n      End alt.\n    End redc.\n\n    (** * Arithmetic in Montgomery form *)\n    Section arithmetic.\n      Local Infix \"*\" := (mul N R N') : montgomery_scope.\n\n      Local Notation to_montgomery := (to_montgomery N R N').\n      Local Notation from_montgomery := (from_montgomery N R N').\n      Lemma to_from_montgomery a : to_montgomery (from_montgomery a) ≡ a.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold to_montgomery, from_montgomery.\n        transitivity ((a * 1) * 1); [ | apply f_equal2; lia ].\n        rewrite <- !R'_good, !reduce_correct.\n        unfold Z.equiv_modulo; push_Zmod; pull_Zmod.\n        apply f_equal2; lia.\n      Qed.\n      Lemma from_to_montgomery a : from_montgomery (to_montgomery a) ≡ a.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold to_montgomery, from_montgomery.\n        rewrite !reduce_correct.\n        transitivity (a * ((R * (R * R' mod N) * R') mod N)).\n        { unfold Z.equiv_modulo; push_Zmod; pull_Zmod.\n          apply f_equal2; lia. }\n        { repeat first [ rewrite R'_good\n                       | reflexivity\n                       | push_Zmod; pull_Zmod; progress autorewrite with zsimplify\n                       | progress unfold Z.equiv_modulo ]. }\n      Qed.\n\n      Theorem mul_correct x y : from_montgomery (x * y) ≡ from_montgomery x * from_montgomery y.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold from_montgomery, mul.\n        rewrite !reduce_correct; apply f_equal2; lia.\n      Qed.\n      Theorem mul_correct_to x y : to_montgomery (x * y) ≡ (to_montgomery x * to_montgomery y)%montgomery.\n      Proof using N'_good N'_in_range N_reasonable R'_good.\n        unfold to_montgomery, mul.\n        rewrite !reduce_correct.\n        transitivity (x * y * R * 1 * 1 * 1);\n          [ rewrite <- R'_good at 1\n          | rewrite <- R'_good at 1 2 3 ];\n          autorewrite with zsimplify;\n          unfold Z.equiv_modulo; push_Zmod; pull_Zmod.\n        { apply f_equal2; lia. }\n        { apply f_equal2; lia. }\n      Qed.\n    End arithmetic.\n  End redc.\nEnd montgomery.\n\nModule Import LocalizeEquivModuloInstances := Z.RemoveEquivModuloInstances Nop.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Arithmetic/MontgomeryReduction/Proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7194175789542178}}
{"text": "(* coq-robot (c) 2017 AIST and INRIA. License: LGPL-2.1-or-later. *)\nRequire Import NsatzTactic.\nFrom mathcomp Require Import all_ssreflect ssralg ssrint ssrnum rat poly.\nFrom mathcomp Require Import closed_field polyrcf matrix mxalgebra mxpoly zmodp.\nFrom mathcomp Require Import realalg complex fingroup perm.\nFrom mathcomp Require Import interval reals trigo.\nRequire Import ssr_ext euclidean vec_angle frame rot.\nFrom mathcomp.analysis Require Import forms.\nRequire Import extra_trigo.\n\n(******************************************************************************)\n(*                            Quaternions                                     *)\n(*                                                                            *)\n(* This file develops the theory of quaternions. It defines the type of       *)\n(* quaternions and the type of unit quaternions and show that quaternions     *)\n(* form a ZmodType, a RingType, a LmodType, a UnitRingType. It also defines   *)\n(* polar coordinates and dual quaternions.                                    *)\n(*                                                                            *)\n(*        quat R == type of quaternions over the ringType R                   *)\n(*          x%:q == quaternion with scalar part x and vector part 0           *)\n(*   x \\is realq == the quaternion x has no vector part                       *)\n(*          u%:v == pure quaternion (or vector quaternion) with scalar part 0 *)\n(*                  and vector part u                                         *)\n(*   x \\is pureq == the quaternion x has no scalar part                       *)\n(*    `i, `j, `k == basic quaternions                                         *)\n(*           x.1 == scalar part of the quaternion x                           *)\n(*           x.2 == vector part of the quaternion x                           *)\n(*          x^*q == conjugate of quaternion x                                 *)\n(*       normq x == norm of the quaternion x                                  *)\n(*       uquat R == type of unit quaternions, i.e., quaternions with norm 1   *)\n(* conjugation x == v |-> x v x^*                                             *)\n(*                                                                            *)\n(* Polar coordinates:                                                         *)\n(*     polar_of_quat a == polar coordinates of the quaternion a               *)\n(*   quat_of_polar a u == quaternion corresponding to the polar coordinates   *)\n(*                        angle a and vector u                                *)\n(*          quat_rot x == snd \\o conjugation x (rotation of angle 2a about    *)\n(*                        vector v where a,v are the polar coordinates of x,  *)\n(*                        a unit quaternion                                   *)\n(* Dual numbers:                                                              *)\n(*     dual R == the type of dual numbers over a ringType R                   *)\n(*        x.1 == left part of the dual number x                               *)\n(*        x.2 == right part of the dual number x                              *)\n(* Dual numbers are equipped with a structure of ZmodType, RingType, and of   *)\n(* LmodType when R is a ringType, of Com/UnitRingType when R is a             *)\n(* Com/UnitRingType.                                                          *)\n(*                                                                            *)\n(* Dual quaternions:                                                          *)\n(*     x +ɛ* y  == dual number formed by x and y                              *)\n(*        dquat == type of dual quaternions                                   *)\n(* x \\is puredq == the dual quaternion x is pure                              *)\n(*   a \\is dnum == a has no vector part                                       *)\n(*        x^*dq == conjugate of dual quaternion x                             *)\n(*                                                                            *)\n(******************************************************************************)\n\nReserved Notation \"x %:q\" (at level 2, format \"x %:q\").\nReserved Notation \"x %:v\" (at level 2, format \"x %:v\").\nReserved Notation \"x '_i'\" (at level 1, format \"x '_i'\").\nReserved Notation \"x '_j'\" (at level 1, format \"x '_j'\").\nReserved Notation \"x '_k'\" (at level 1, format \"x '_k'\").\nReserved Notation \"'`i'\".\nReserved Notation \"'`j'\".\nReserved Notation \"'`k'\".\nReserved Notation \"x '^*q'\" (at level 2, format \"x '^*q'\").\nReserved Notation \"r *`i\" (at level 3).\nReserved Notation \"r *`j\" (at level 3).\nReserved Notation \"r *`k\" (at level 3).\nReserved Notation \"x +ɛ* y\"\n  (at level 40, left associativity, format \"x  +ɛ*  y\").\nReserved Notation \"x -ɛ* y\"\n  (at level 40, left associativity, format \"x  -ɛ*  y\").\nReserved Notation \"x '^*d'\" (at level 2, format \"x '^*d'\").\n\nDeclare Scope quat_scope.\nDeclare Scope dual_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\n\nImport Order.TTheory GRing.Theory Num.Def Num.Theory.\n\nSection quaternion0.\nVariable R : ringType.\n\nRecord quat := mkQuat {quatl : R ; quatr : 'rV[R]_3 }.\nImplicit Types x y : quat.\n\nLocal Notation \"x %:q\" := (mkQuat x 0).\nLocal Notation \"x %:v\" := (mkQuat 0 x).\nLocal Notation \"'`i'\" := ('e_0)%:v.\nLocal Notation \"'`j'\" := ('e_1)%:v.\nLocal Notation \"'`k'\" := ('e_2%:R)%:v.\nLocal Notation \"x '_i'\" := ((x.2)``_0).\nLocal Notation \"x '_j'\" := ((x.2)``_1).\nLocal Notation \"x '_k'\" := ((x.2)``_(2%:R : 'I_3)).\n\nCoercion pair_of_quat x := let: mkQuat x1 x2 := x in (x1, x2).\nLet quat_of_pair (a : R * 'rV[R]_3) := let: (a1, a2) := a in mkQuat a1 a2.\n\nLemma quat_of_pairK : cancel pair_of_quat quat_of_pair.\nProof. by case. Qed.\n\nDefinition quat_eqMixin := CanEqMixin quat_of_pairK.\nCanonical Structure quat_eqType := EqType quat quat_eqMixin.\nDefinition quat_choiceMixin := CanChoiceMixin quat_of_pairK.\nCanonical Structure quat_choiceType := ChoiceType quat quat_choiceMixin.\n\nLemma eq_quat x y : (x == y) = (x.1 == y.1) && (x.2 == y.2).\nProof.\ncase: x y => [? ?] [? ?] /=.\napply/idP/idP => [/eqP [ -> ->]|/andP[/eqP -> /eqP -> //]]; by rewrite !eqxx.\nQed.\n\nDefinition addq x y := nosimpl (mkQuat (x.1 + y.1) (x.2 + y.2)).\n\nLemma addqC : commutative addq.\nProof. move=> *; congr mkQuat; by rewrite addrC. Qed.\n\nLemma addqA : associative addq.\nProof. move=> *; congr mkQuat; by rewrite addrA. Qed.\n\nLemma add0q : left_id 0%:q addq.\nProof. case=> *; by rewrite /addq /= 2!add0r. Qed.\n\nDefinition oppq x := nosimpl (mkQuat (- x.1) (- x.2)).\n\nLemma addNq : left_inverse 0%:q oppq addq.\nProof. move=> *; congr mkQuat; by rewrite addNr. Qed.\n\nDefinition quat_ZmodMixin := ZmodMixin addqA addqC add0q addNq.\nCanonical quat_ZmodType := ZmodType quat quat_ZmodMixin.\n\nLemma addqE x y : x + y = addq x y. Proof. by []. Qed.\n\nLemma oppqE x : - x = oppq x. Proof. by []. Qed.\n\nLocal Notation \"r *`i\" := (mkQuat 0 (r *: 'e_0)).\nLocal Notation \"r *`j\" := (mkQuat 0 (r *: 'e_1)).\nLocal Notation \"r *`k\" := (mkQuat 0 (r *: 'e_2%:R)).\n\nLemma quatE x : x = x.1%:q + x.2%:v.\nProof. by apply/eqP; rewrite eq_quat /=; Simp.r. Qed.\n\nLemma quatrE x : x.2%:v = x _i *`i + x _j *`j + x _k *`k.\nProof. by apply/eqP; rewrite eq_quat /=; Simp.r; rewrite -vec3E. Qed.\n\nLemma quat_scalarE (r s : R) : (r%:q == s%:q) = (r == s).\nProof. by apply/idP/idP => [/eqP[] ->|/eqP -> //]. Qed.\n\nLemma quat_realN (r : R) : (- r)%:q = - (r%:q).\nProof. by rewrite oppqE /oppq /= oppr0. Qed.\n\nLemma quat_vectN (u : 'rV[R]_3) : (- u)%:v = - (u%:v).\nProof. by rewrite oppqE /oppq /= oppr0. Qed.\n\nLemma quat_realD (r s : R) : (r + s)%:q = r%:q + s%:q.\nProof. by rewrite addqE /addq /= add0r. Qed.\n\nLemma quat_vectD (u v : 'rV[R]_3) : (u + v)%:v = u%:v + v%:v.\nProof. by rewrite addqE /addq /= addr0. Qed.\n\nLemma quat_realB (r s : R) : (r - s)%:q = r%:q - s%:q.\nProof. by rewrite quat_realD quat_realN. Qed.\n\nLemma quat_vectB (u v : 'rV[R]_3) : (u - v)%:v = u%:v - v%:v.\nProof. by rewrite quat_vectD quat_vectN. Qed.\n\nDefinition pureq := [qualify x : quat | x.1 == 0].\nFact pureq_key : pred_key pureq. Proof. by []. Qed.\nCanonical pureq_keyed := KeyedQualifier pureq_key.\n\nDefinition realq := [qualify x : quat | x.2 == 0].\nFact realq_key : pred_key realq. Proof. by []. Qed.\nCanonical realq_keyed := KeyedQualifier realq_key.\n\nEnd quaternion0.\n\nDelimit Scope quat_scope with quat.\nLocal Open Scope quat_scope.\n\nNotation \"r %:q\" := (mkQuat r 0) : quat_scope.\nNotation \"u %:v\" := (mkQuat 0 u) : quat_scope.\nNotation \"'`i'\" := ('e_0)%:v : quat_scope.\nNotation \"'`j'\" := ('e_1)%:v : quat_scope.\nNotation \"'`k'\" := ('e_2%:R)%:v : quat_scope.\nNotation \"x '_i'\" := ((x.2)``_0) : quat_scope.\nNotation \"x '_j'\" := ((x.2)``_1) : quat_scope.\nNotation \"x '_k'\" := ((x.2)``_(2%:R : 'I_3)) : quat_scope.\nNotation \"r *`i\" := (mkQuat 0 (r *: 'e_0)) : quat_scope.\nNotation \"r *`j\" := (mkQuat 0 (r *: 'e_1)) : quat_scope.\nNotation \"r *`k\" := (mkQuat 0 (r *: 'e_2%:R)) : quat_scope.\n\nArguments pureq {R}.\n\nImport rv3LieAlgebra.Exports.\n\nStructure Conjugate := { conjugate_type : Type ;\n                         conjugate_op : conjugate_type -> conjugate_type }.\n\nDefinition conjugate_op_nosimpl := nosimpl conjugate_op.\n\nNotation \"x '^*q'\" := (@conjugate_op_nosimpl _ x) : quat_scope.\n\nSection quaternion.\nVariable R : comRingType.\nImplicit Types x y : quat R.\n\nDefinition mulq x y := nosimpl\n  (mkQuat (x.1 * y.1 - x.2 *d y.2) (x.1 *: y.2 + y.1 *: x.2 + x.2 *v y.2)).\n\nLemma mulqA : associative mulq.\nProof.\nmove=> [a a'] [b b'] [c c']; congr mkQuat => /=.\n- rewrite mulrDr mulrDl mulrA -!addrA; congr (_ + _).\n  rewrite mulrN !dotmulDr !dotmulDl !opprD !addrA dot_crossmulC; congr (_ + _).\n  rewrite addrC addrA; congr (_ + _ + _).\n  by rewrite mulrC dotmulvZ mulrN.\n  by rewrite dotmulZv.\n  by rewrite dotmulvZ dotmulZv.\n- rewrite 2![in LHS]scalerDr 1![in RHS]scalerDl scalerA.\n  rewrite -4![in LHS]addrA -3![in RHS]addrA; congr (_ + _).\n  rewrite [in RHS]scalerDr [in RHS]addrCA\n         -[in RHS]addrA -[in LHS]addrA; congr (_ + _).\n    by rewrite scalerA mulrC -scalerA.\n  rewrite [in RHS]scalerDr [in LHS]scalerDl [in LHS]addrCA\n         -[in RHS]addrA -addrA; congr (_ + _).\n    by rewrite scalerA mulrC.\n  rewrite (addrC (a *: _)) linearD /= (addrC (a' *v _)) linearD /=.\n  rewrite -![in LHS]addrA ![in LHS]addrA (addrC (- _ *: a'))\n          -![in LHS]addrA; congr (_ + _).\n    by rewrite linearZ.\n  rewrite [in RHS]lieC /= linearD /= opprD [in RHS]addrCA\n         ![in LHS]addrA addrC -[in LHS]addrA.\n  congr (_ + _); first by rewrite linearZ /= lieC scalerN.\n  rewrite addrA addrC linearD /= opprD [in RHS]addrCA; congr (_ + _).\n    by rewrite !linearZ /= lieC.\n  rewrite 2!double_crossmul opprD opprK\n         [in RHS]addrC addrA; congr (_ + _); last first.\n    by rewrite scaleNr.\n  by rewrite dotmulC scaleNr; congr (_ + _); rewrite dotmulC.\nQed.\n\nLemma mul1q : left_id 1%:q mulq.\nProof.\ncase=> a a'; rewrite /mulq /=; congr mkQuat; Simp.r => /=.\n  by rewrite dotmul0v subr0.\nby rewrite linear0l addr0.\nQed.\n\nLemma mulq1 : right_id 1%:q mulq.\nProof.\ncase=> a a'; rewrite /mulq /=; congr mkQuat; Simp.r => /=.\n  by rewrite dotmulv0 subr0.\nby rewrite linear0r addr0.\nQed.\n\nLemma mulqDl : left_distributive mulq (@addq R).\nProof.\nmove=> [a a'] [b b'] [c c']; rewrite /mulq /=; congr mkQuat => /=.\n  by rewrite [in RHS]addrCA 2!addrA -mulrDl (addrC a) dotmulDl opprD addrA.\nrewrite scalerDl -!addrA; congr (_ + _).\nrewrite [in RHS](addrCA (a' *v c')) [in RHS](addrCA (c *: a')); congr (_ + _).\nrewrite scalerDr -addrA; congr (_ + _).\nrewrite addrCA; congr (_ + _).\nby rewrite lieC linearD /= lieC opprD opprK (lieC b').\nQed.\n\nLemma mulqDr : right_distributive mulq (@addq R).\nProof.\nmove=> [a a'] [b b'] [c c']; rewrite /mulq /=; congr mkQuat => /=.\n  rewrite mulrDr -!addrA; congr (_ + _).\n  rewrite addrCA; congr (_ + _).\n  by rewrite dotmulDr opprD.\nrewrite scalerDr -!addrA; congr (_ + _).\nrewrite [in RHS](addrCA (a' *v b')) [in RHS](addrCA (b *: a')); congr (_ + _).\nrewrite scalerDl -addrA; congr (_ + _).\nby rewrite addrCA linearD.\nQed.\n\nLemma oneq_neq0 : 1%:q != 0 :> quat R.\nProof. apply/eqP => -[]; apply/eqP. exact: oner_neq0. Qed.\n\nDefinition quat_RingMixin :=\n  RingMixin mulqA mul1q mulq1 mulqDl mulqDr oneq_neq0.\nCanonical Structure quat_Ring := Eval hnf in RingType (quat R) quat_RingMixin.\n\nLemma mulqE x y : x * y = mulq x y. Proof. by []. Qed.\n\nLemma realq_comm x y : x \\is realq R -> x * y = y * x.\nProof.\nrewrite qualifE; move: x y => [x1 x2] [y1 y2] /= /eqP->.\ncongr mkQuat => /=; first by rewrite dotmul0v dotmulv0 mulrC.\nby rewrite scaler0 !linear0 add0r addr0 -/(crossmulr _ _) linear0 addr0.\nQed.\n\nLemma realq_real (r : R) : r%:q \\is realq R.\nProof. by rewrite qualifE. Qed.\n\nLemma realqE x : x \\is realq R -> x = (x.1)%:q.\nProof. by rewrite qualifE; case: x => [x1 x2] /= /eqP->. Qed.\n\nLemma quat_realM (r s : R) : (r * s)%:q = r%:q * s%:q.\nProof. by congr mkQuat; rewrite /= (dotmul0v, linear0l); Simp.r. Qed.\n\nLemma iiN1 : `i * `i = -1.\nProof. by congr mkQuat; rewrite (dote2, liexx) /=; Simp.r. Qed.\n\nLemma ijk : `i * `j = `k.\nProof. by congr mkQuat; rewrite /= (dote2, vecij); Simp.r. Qed.\n\nLemma ikNj : `i * `k = - `j.\nProof. by congr mkQuat; rewrite /= (dote2, vecik); Simp.r. Qed.\n\nLemma jiNk : `j * `i = - `k.\nProof. by congr mkQuat; rewrite /= (dote2, vecji); Simp.r. Qed.\n\nLemma jjN1 : `j * `j = -1.\nProof. by congr mkQuat; rewrite /= (dote2, liexx); Simp.r. Qed.\n\nLemma jkNi : `j * `k = `i.\nProof. by congr mkQuat; rewrite /= ?(dote2, vecjk) //; Simp.r. Qed.\n\nLemma kij : `k * `i = `j.\nProof. by congr mkQuat; rewrite /= (dote2, vecki); Simp.r. Qed.\n\nLemma kjNi : `k * `j = - `i.\nProof. by congr mkQuat; rewrite /= (dote2, veckj); Simp.r. Qed.\n\nLemma kkN1 : `k * `k = -1.\nProof. by congr mkQuat; rewrite /= (dote2, liexx); Simp.r. Qed.\n\nDefinition scaleq k x := mkQuat (k * x.1) (k *: x.2).\n\nLemma scaleqA r s x : scaleq r (scaleq s x) = scaleq (r * s) x.\nProof.\nrewrite /scaleq /=; congr mkQuat; by [rewrite mulrA | rewrite scalerA].\nQed.\n\nLemma scaleq1 : left_id 1 scaleq.\nProof.\nby move=> q; rewrite /scaleq mul1r scale1r; apply/eqP; rewrite eq_quat /= !eqxx.\nQed.\n\nLemma scaleqDr : @right_distributive R (quat R) scaleq +%R.\nProof. move=> a b c; by rewrite /scaleq /= mulrDr scalerDr. Qed.\n\nLemma scaleqDl x : {morph (scaleq^~ x : R -> quat R) : r s / r + s}.\nProof. by move=> r s; rewrite /scaleq mulrDl /= scalerDl; congr mkQuat. Qed.\n\nDefinition quat_lmodMixin := LmodMixin scaleqA scaleq1 scaleqDr scaleqDl.\nCanonical quat_lmodType := Eval hnf in LmodType R (quat R) quat_lmodMixin.\n\nLemma scaleqE (k : R) x : k *: x = k *: x.1%:q + k *: x.2%:v.\nProof. by apply/eqP; rewrite eq_quat /=; Simp.r. Qed.\n\nLemma quat_realZ (k : R) (r : R) : (k * r)%:q = k *: r%:q.\nProof. by congr mkQuat; rewrite scaler0. Qed.\n\nLemma quat_vectZ (k : R) (u : 'rV[R]_3) : (k *: u)%:v = k *: u%:v.\nProof. by congr mkQuat; rewrite /= mulr0. Qed.\n\nLemma quatAl k x y : k *: (x * y) = k *: x * y.\nProof.\ncase: x y => [x1 x2] [y1 y2]; apply/eqP.\nrewrite !mulqE /mulq /= scaleqE /= eq_quat /=.\napply/andP; split; first by Simp.r; rewrite mulrBr mulrA dotmulZv.\napply/eqP; Simp.r; rewrite 2!scalerDr scalerA -2!addrA; congr (_ + _).\nby rewrite linearZl_LR /=; congr (_ + _); rewrite scalerA mulrC -scalerA.\nQed.\nCanonical quat_lAlgType := Eval hnf in LalgType _ (quat R) quatAl.\n\nLemma quatAr k x y : k *: (x * y) = x * (k *: y).\nProof.\ncase: x y => [x1 x2] [y1 y2]; apply/eqP.\nrewrite !mulqE /mulq /= scaleqE /= eq_quat /=.\napply/andP; split; first by Simp.r; rewrite /= mulrBr mulrCA mulrA dotmulvZ.\napply/eqP; Simp.r; rewrite 2!scalerDr scalerA mulrC -scalerA -!addrA.\nby congr (_ + _); rewrite linearZr_LR /= scalerA.\nQed.\nCanonical quat_algType := Eval hnf in AlgType _ (quat R) quatAr.\n\nLemma quat_algE r : r%:q = r%:A.\nProof. by apply/eqP; rewrite eq_quat //=; Simp.r. Qed.\n\nDefinition conjq x := nosimpl (mkQuat x.1 (- x.2)).\nCanonical Conjugate_quaternion := @Build_Conjugate (quat R) conjq.\n\nLemma conjq_def x : x^*q = mkQuat x.1 (- x.2).\nProof. by case: x. Qed.\n\nLemma conjq_linear : linear (@conjugate_op_nosimpl Conjugate_quaternion).\nProof.\nmove=> k /= x y; rewrite !conjq_def /= scaleqE addqE /addq /=; Simp.r.\nby rewrite linearN /= linearD.\nQed.\n\nCanonical conjq_is_additive := Additive conjq_linear.\nCanonical conjq_is_linear := AddLinear conjq_linear.\n\nLemma conjqI x : (x ^*q) ^*q = x.\nProof. by rewrite conjq_def; case: x => x1 x2 /=; rewrite opprK. Qed.\n\nLemma conjq0 : (0%:v)^*q = 0.\nProof. by rewrite conjq_def oppr0. Qed.\n\nLemma conjq_comm x : x^*q * x = x * x^*q.\nProof.\napply/eqP; rewrite eq_quat /=.\ndo ! rewrite (linearNl,linearNr,liexx,dotmulvN,dotmulNv,subr0,opprK,\n              scaleNr,scalerN,eqxx) /=.\nby rewrite addrC.\nQed.\n\nLemma conjq_addMC x y : x * y + (x * y)^*q  = y * x + (y * x) ^*q.\nProof.\ncase: x => x1 x2; case: y => y1 y2; congr mkQuat => /=.\n  by rewrite [y1 * _]mulrC [y2 *d _]dotmulC.\nrewrite !opprD !addrA [_ + x1 *:y2]addrC -!addrA; congr (_ + (_ + _)).\nby rewrite [LHS]addrC [RHS]addrC !addrA !subrK addrC.\nQed.\n\nLemma realq_conjD x : x + x^*q \\is realq R.\nProof.  by case: x => x1 x2; rewrite addqE /addq /= subrr qualifE. Qed.\n\nLemma realq_conjM x : x * x^*q \\is realq R.\nProof.\ncase: x => [x1 x2]; rewrite mulqE /mulq /= scalerN linearN /=.\nby rewrite liexx subr0 [- _ + _]addrC subrr qualifE.\nQed.\n\nLemma conjq_comm2 x y : y^*q * x + x^*q * y = x * y^*q + y * x^*q.\nProof.\napply: (addIr (x * x ^*q + y * y ^*q)).\nrewrite [RHS]addrAC !addrA -mulrDr -[RHS]addrA -mulrDr -mulrDl -linearD /=.\nrewrite addrC !addrA -conjq_comm -mulrDr -addrA -conjq_comm -mulrDr -mulrDl.\nby rewrite -linearD /= [y + x]addrC conjq_comm.\nQed.\n\nLemma conjqM x y : (x * y)^*q = y^*q * x^*q.\nProof.\ncase: x y => [x1 x2] [y1 y2] /=.\nrewrite 2!conjq_def /= mulqE /mulq /= mulrC dotmulC dotmulvN dotmulNv opprK;\n    congr mkQuat.\nby rewrite 2!opprD 2!scalerN linearN /= -(lieC x2) linearN\n           /= -2!scaleNr -addrA addrCA addrA.\nQed.\n\nLemma quat_realC (r : R) : (r%:q)^*q = r%:q.\nProof. by congr mkQuat; rewrite /= oppr0. Qed.\n\nLemma quat_vectC (u : 'rV_3) : (u%:v)^*q = -(u%:v).\nProof. by congr mkQuat; rewrite /= oppr0. Qed.\n\nEnd quaternion.\nArguments pureq {R}.\nArguments realq {R}.\n\nSection quaternion1.\nVariable R : realType.\nImplicit Types x y : quat R.\n\nDefinition sqrq x := x.1 ^+ 2 + norm (x.2) ^+ 2.\n\nLemma sqrq0 : sqrq 0 = 0. Proof. by rewrite /sqrq norm0 expr0n add0r. Qed.\n\nLemma sqrq_ge0 x : 0 <= sqrq x. Proof. by rewrite addr_ge0 // sqr_ge0. Qed.\n\nLemma sqrq_eq0 x : (sqrq x == 0) = (x == 0).\nProof.\nrewrite /sqrq paddr_eq0 ?sqr_ge0// !sqrf_eq0 norm_eq0 -xpair_eqE.\nby rewrite -surjective_pairing.\nQed.\n\nLemma sqrqN x : sqrq (- x) = sqrq x.\nProof. by rewrite /sqrq /= normN sqrrN. Qed.\n\nLemma sqrq_conj x : sqrq (x ^*q) = sqrq x.\nProof. by rewrite /sqrq normN. Qed.\n\nLemma conjqP x : x * x^*q = (sqrq x)%:q.\nProof.\nrewrite /mulq /=; congr mkQuat.\n  by rewrite /= dotmulvN dotmulvv opprK -expr2.\nby rewrite scalerN addNr add0r linearNr liexx oppr0.\nQed.\n\nLemma conjqZ k x : (k *: x) ^*q = k *: x ^*q.\nProof. by congr mkQuat; rewrite /= scalerN. Qed.\n\nLemma conjqN (u : 'rV[R]_3) : (- u%:v)^*q = - u%:v^*q.\nProof. by rewrite 2!conjq_def /= opprK oppr0 quat_vectN opprK. Qed.\n\nLemma pureq_conj x : (x \\is pureq) = (x + x^*q == 0).\nProof.\ncase: x => x1 x2; rewrite qualifE /=; apply/idP/idP=> [/eqP->{x1}|].\n  by rewrite conjq_def /= quat_vectN subrr.\nby rewrite conjq_def /= => /eqP[/eqP]; rewrite -mulr2n (mulrn_eq0 x1 2).\nQed.\n\nLemma conjqE x :\n  x^*q = - (1 / 2%:R) *: (x + `i * x * `i + `j * x * `j + `k * x * `k).\nProof.\napply/eqP; rewrite eq_quat; apply/andP; split; apply/eqP.\n  rewrite [in LHS]/= scaleqE /=.\n  rewrite !(mul0r,mulr0,addr0) scale0r !add0r !dotmulDl.\n  rewrite dotmulZv dotmulvv normeE expr1n mulr1 dotmulC\n          dot_crossmulC liexx dotmul0v addr0.\n  rewrite subrr add0r dotmulZv dotmulvv normeE expr1n mulr1\n          dotmulC dot_crossmulC liexx.\n  rewrite dotmul0v addr0 dotmulZv dotmulvv normeE expr1n mulr1\n          opprD addrA dotmulC dot_crossmulC.\n  rewrite liexx dotmul0v subr0 -opprD mulrN mulNr\n          opprK -mulr2n -(mulr_natl x.1) mulrA.\n  by rewrite div1r mulVr ?mul1r // unitfE pnatr_eq0.\nrewrite /= !(mul0r,scale0r,add0r,addr0).\nrewrite [_ *v 'e_0]lieC /= ['e_0 *v _]linearD /= ['e_0 *v _]linearZ /= liexx.\nrewrite scaler0 add0r double_crossmul dotmulvv normeE expr1n scale1r.\nrewrite [_ *v 'e_1]lieC /= ['e_1 *v _]linearD /= ['e_1 *v _]linearZ /= liexx.\nrewrite scaler0 add0r double_crossmul dotmulvv normeE expr1n scale1r.\nrewrite [_ *v 'e_2%:R]lieC /= ['e_2%:R *v _]linearD /=\n        ['e_2%:R *v _]linearZ /= liexx.\nrewrite scaler0 add0r double_crossmul dotmulvv normeE expr1n scale1r.\nrewrite [X in _ = - _ *: X](_ : _ = 2%:R *:x.2).\n  by rewrite scalerA mulNr div1r mulVr ?unitfE ?pnatr_eq0 // scaleN1r.\nrewrite !opprB (addrCA _ x.2) addrA -mulr2n scaler_nat -[RHS]addr0 -3!addrA;\n    congr (_ + _).\ndo 3 rewrite (addrCA _ x.2).\ndo 2 rewrite addrC -!addrA.\nrewrite -opprB (scaleNr _ 'e_0) opprK -mulr2n addrA -mulr2n.\nrewrite addrC addrA -opprB scaleNr opprK -mulr2n.\nrewrite opprD.\nrewrite (addrCA (- _ *: 'e_2%:R)).\nrewrite -opprB scaleNr opprK -mulr2n.\nrewrite -!mulNrn -3!mulrnDl -scaler_nat.\napply/eqP; rewrite scalemx_eq0 pnatr_eq0 /=.\nrewrite addrA addrC eq_sym -subr_eq add0r opprB opprD 2!opprK.\nrewrite !['e__ *d _]dotmulC !dotmul_delta_mx /=.\nby rewrite addrA addrAC -addrA addrC [X in _ == X]vec3E.\nQed.\n\nLemma conjq_scalar x : x.1%:q = (1 / 2%:R) *: (x + x^*q).\nProof.\ncase: x => x1 x2.\nrewrite /conjq /= addqE /addq /= subrr quat_realD scalerDr -scalerDl.\nby rewrite -mulr2n -mulr_natr div1r mulVr ?scale1r // unitfE pnatr_eq0.\nQed.\n\nLemma conjq_vector x : x.2%:v = (1 / 2%:R) *: (x - x^*q).\nProof.\ncase: x => x1 x2.\nrewrite /conjq /= addqE /addq /= subrr opprK quat_vectD scalerDr -scalerDl.\nby rewrite -mulr2n -mulr_natr div1r mulVr ?scale1r // unitfE pnatr_eq0.\nQed.\n\nDefinition invq a := (1 / sqrq a) *: (a ^*q).\n\nDefinition unitq : pred (quat R) := [pred a | a != 0%:q].\n\nLemma mulVq : {in unitq, left_inverse 1 invq (@mulq R)}.\nProof.\nmove=> a; rewrite inE /= => a0.\nrewrite /invq -mulqE -quatAl conjq_comm conjqP.\nby rewrite -quat_realZ mul1r mulVf // sqrq_eq0.\nQed.\n\nLemma mulqV : {in unitq, right_inverse 1 invq (@mulq R)}.\nProof.\nmove=> a; rewrite inE /= => a0.\nby rewrite /invq -mulqE -quatAr conjqP -quat_realZ mul1r mulVf // sqrq_eq0.\nQed.\n\nLemma quat_integral x y : (x * y == 0) = ((x == 0) || (y == 0)).\nProof.\ncase: (x =P 0) => [->|/eqP xNZ] /=; first by rewrite mul0r eqxx.\napply/eqP/eqP => [xyZ|->]; last by rewrite mulr0.\nby rewrite -[y]mul1r -(@mulVq x) // -mulrA xyZ mulr0.\nQed.\n\nLemma unitqP x y : y * x = 1 /\\ x * y = 1 -> unitq x.\nProof.\nmove=> [ba1 ab1]; rewrite /unitq inE; apply/eqP => x0.\nmove/esym: ab1; rewrite x0 mul0r.\napply/eqP; exact: oneq_neq0.\nQed.\n\nLemma invq0id : {in [predC unitq], invq =1 id}.\nProof.\nmove=> a; rewrite !inE negbK => /eqP ->.\nby rewrite /invq /= conjq0 scaler0.\nQed.\n\nDefinition quat_UnitRingMixin := UnitRingMixin mulVq mulqV unitqP invq0id.\nCanonical quat_unitRing := UnitRingType (quat R) quat_UnitRingMixin.\n\nLemma invqE x : x^-1 = invq x. Proof. by done. Qed.\n\nDefinition normq x := Num.sqrt (sqrq x).\n\nLemma normq0 : normq 0 = 0.\nProof. by rewrite /normq /sqrq expr0n /= norm0 add0r expr0n sqrtr0. Qed.\n\nLemma normqc x : normq x^*q = normq x.\nProof. by rewrite /normq /sqrq /= normN. Qed.\n\nLemma normqE x : (normq x ^+ 2)%:q = x^*q * x.\nProof.\nrewrite -normqc /normq sqr_sqrtr; last by rewrite /sqrq addr_ge0 // sqr_ge0.\nby rewrite -conjqP conjqI.\nQed.\n\nLemma normq_ge0 x : 0 <= normq x.\nProof. by apply sqrtr_ge0. Qed.\n\nLemma normq_eq0 x : (normq x == 0) = (x == 0).\nProof. by rewrite /normq -{1}sqrtr0 eqr_sqrt ?sqrq_ge0// sqrq_eq0. Qed.\n\nLemma normq_vector (u : 'rV[R]_3) : normq u%:v = norm u.\nProof.\nby rewrite /normq /sqrq /= expr0n add0r sqrtr_sqr ger0_norm ?norm_ge0.\nQed.\n\nLemma normqM x y : normq (x * y) = normq x * normq y.\nProof.\napply/eqP; rewrite -(@eqr_expn2 _ 2) // ?normq_ge0 //; last first.\n  by rewrite mulr_ge0 // normq_ge0.\nrewrite -quat_scalarE normqE conjqM -mulrA (mulrA x^*q) -normqE.\nrewrite quat_algE mulr_algl -scalerAr exprMn quat_realM.\nby rewrite (normqE y) -mulr_algl quat_algE.\nQed.\n\nLemma normqZ (k : R) x : normq (k *: x) = `|k| * normq x.\nProof.\nby rewrite /normq /sqrq /= normZ 2!exprMn sqr_normr -mulrDr sqrtrM ?sqr_ge0 //\n           sqrtr_sqr.\nQed.\n\nLemma normqV x : normq (x^-1) = normq x / sqrq x.\nProof.\nrewrite invqE /invq normqZ ger0_norm; last first.\n  by rewrite divr_ge0 // ?ler01 // /sqrq addr_ge0 // sqr_ge0.\nby rewrite normqc mulrC mul1r.\nQed.\n\nDefinition normQ x := (normq x)%:q.\n\nLemma normQ_eq0 x : (normQ x == 0) = (x == 0).\nProof. by rewrite /normQ quat_scalarE normq_eq0. Qed.\n\nDefinition normalizeq x : quat R := 1 / normq x *: x.\n\nLemma normalizeq1 x : x != 0 -> normq (normalizeq x) = 1.\nProof.\nmove=> x0; rewrite /normalizeq normqZ normrM normr1 mul1r normrV; last first.\n  by rewrite unitfE normq_eq0.\nby rewrite ger0_norm ?normq_ge0 // mulVr // unitfE normq_eq0.\nQed.\n\nDefinition lequat x y := (x.2 == y.2) && (x.1 <= y.1).\n\nLemma lequat_normD x y : lequat (normQ (x + y)) (normQ x + normQ y).\nProof.\nrewrite /lequat /= add0r eqxx andTb /normq /sqrq !sqr_norm !sum3E /= !mxE.\npose X := nth 0 [:: x.1; x _i; x _j; x _k].\npose Y := nth 0 [:: y.1; y _i; y _j; y _k].\nsuff: Num.sqrt (\\sum_(i < 4) (X i + Y i)^+2) <=\n      Num.sqrt (\\sum_(i < 4) (X i) ^+ 2) + Num.sqrt (\\sum_(i < 4) (Y i) ^+ 2).\n  by rewrite !sum4E /X /Y /= !addrA.\nhave sqr_normE (x1 : R) : `|x1| ^+2 = x1 ^+ 2.\n  by case: (ltrgt0P x1); rewrite ?sqrrN // => ->.\nhave ler_mul_norm (x1 y1 : R) : x1 * y1 <= `|x1| * `|y1|.\n  rewrite {1}(numEsign x1) {1}(numEsign y1) mulrAC mulrA -signr_addb.\n  rewrite -mulrA [_ * `|x1|]mulrC.\n  case: (_ (+) _); rewrite !(expr0, expr1, mulNr, mul1r) //.\n  rewrite -subr_gte0 opprK -mulr2n; apply: mulrn_wge0.\n  by apply: mulr_ge0; apply: normr_ge0.\napply: le_trans (_ : Num.sqrt (\\sum_(i < 4) (`|X i| + `|Y i|) ^+ 2) <= _).\n  rewrite -ler_sqr ?nnegrE; try by apply: sqrtr_ge0.\n  rewrite !sqr_sqrtr; try by apply: sumr_ge0 => i _; apply: sqr_ge0.\n  apply: ler_sum => i _; rewrite !sqrrD.\n  by rewrite !sqr_normE; do ! apply: ler_add => //.\nrewrite -ler_sqr ?nnegrE; last 2 first.\n- by apply: sqrtr_ge0.\n- by apply: addr_ge0; apply: sqrtr_ge0.\nrewrite [in X in _ <= X]sqrrD !sqr_sqrtr;\n    try by apply: sumr_ge0 => i ; rewrite sqr_ge0.\nunder eq_bigr do rewrite sqrrD.\nrewrite 2!big_split /= sumrMnl.\nunder [X in _ <= X + _ + _]eq_bigr do rewrite -sqr_normE.\nunder [X in _ <= _ + _ X * _ *+2  + _]eq_bigr do rewrite -sqr_normE.\nunder [X in _ <= _ + _ + X]eq_bigr do rewrite -sqr_normE.\nunder [X in _ <= _ + _ * _ X *+2  + _]eq_bigr do rewrite -sqr_normE.\ndo 2 (apply: ler_add => //); rewrite ler_muln2r /=.\nrewrite -ler_sqr ?nnegrE; last 2 first.\n- by apply: sumr_ge0 => i _; apply: mulr_ge0; apply: normr_ge0.\n- by apply: mulr_ge0; apply: sqrtr_ge0.\nrewrite exprMn !sqr_sqrtr; last 2 first.\n- by apply: sumr_ge0=> i _; apply: sqr_ge0.\n- by apply: sumr_ge0=> i _; apply: sqr_ge0.\n(* This is Cauchy Schwartz *)\nrewrite -[_ <= _]orFb -[false]/(2 == 0)%nat -ler_muln2r.\npose u := \\sum_(i < 4) \\sum_(j < 4) (`|X i| * `|Y j| - `|X j| * `|Y i|) ^+ 2.\nset z1 := \\sum_(i < _) _; set z2 := \\sum_(i < _) _; set z3 := \\sum_(i < _) _.\nsuff ->: z2 * z3 *+ 2 = z1 ^+ 2 *+ 2 + u.\n  rewrite -{1}(addr0 (_ *+ 2)).\n  apply: ler_add => //.\n  by apply: sumr_ge0 => i _; apply: sumr_ge0 => j _; apply: sqr_ge0.\nunder [X in _ = _ + X]eq_bigr do\n  (under eq_bigr do (rewrite sqrrB !exprMn); rewrite !(sumrN, big_split));\n  rewrite !(sumrN, big_split, addrA) /=.\nunder eq_bigr do rewrite -mulr_sumr; rewrite -mulr_suml -/z2 -/z3.\nhave mswap (a b c d : R) : a * b * (c * d) = (c * b) * (a * d).\n  by rewrite mulrC mulrAC [a * _]mulrC !mulrA.\nunder [X in _ = _ - (X + _) + _]eq_bigr do\n  (under eq_bigr do rewrite mswap; rewrite -mulr_suml);\n  rewrite -mulr_sumr -expr2 -/z1.\nunder [X in _ = _ - (_ + X) + _]eq_bigr do\n  (under eq_bigr do rewrite mswap; rewrite -mulr_suml);\n  rewrite -mulr_sumr -expr2 -/z1 -mulr2n.\nunder [X in _ = _ + X]eq_bigr do rewrite -mulr_suml;\n  rewrite -mulr_sumr -/z2 -/z3.\nby rewrite [_ *+ 2 + _]addrC addrK mulr2n.\nQed.\n\nDefinition ltquat x y := (x.2 == y.2) && (x.1 < y.1).\n\nLemma ltquat0_add x y : ltquat 0 x -> ltquat 0 y -> ltquat 0 (x + y).\nProof.\ncase: x => x0 x1; case: y => y0 y1; rewrite /ltquat /=.\nmove=> /andP[/eqP<- x0P] /andP[/eqP<- u0P] /=.\nby rewrite addr0 eqxx addr_gt0.\nQed.\n\nLemma ge0_lequat_total x y :\n  lequat 0 x -> lequat 0 y -> lequat x y || lequat y x.\nProof.\ncase: x => x0 x1; case: y => y0 y1; rewrite /lequat /=.\nmove=> /andP[/eqP<- x0P] /andP[/eqP<- y0P] /=.\ncase:  (lerP x0 y0); rewrite eqxx //=.\nby apply: ltW.\nQed.\n\nLemma normQM x y : normQ (x * y) = normQ x * normQ y.\nProof. by rewrite {1}/normQ normqM quat_realM. Qed.\n\nLemma lequat_def x y : lequat x y = (normQ (y - x) == y - x).\nProof.\ncase: x => x0 x1; case: y => y0 y1; rewrite /normQ /normq  /sqrq /=.\napply/idP/idP.\n  rewrite /lequat /=.\n  case/andP => /eqP<- x0Ly0.\n  apply/eqP; congr mkQuat; rewrite ?subrr ?expr0n ?addr0 //=.\n  rewrite norm0 expr0n addr0 sqrtr_sqr.\n  by apply/eqP; rewrite eqr_norm_id subr_ge0.\ncase/eqP => /eqP H H1.\nmove: (sym_equal H1) H => /subr0_eq->.\nrewrite /lequat /= eqxx /=.\nby rewrite subrr norm0 expr0n addr0 sqrtr_sqr eqr_norm_id subr_ge0.\nQed.\n\nLemma ltquat_def x y : ltquat x y = (y != x) && lequat x y.\nProof.\ncase: x => x0 x1; case: y => y0 y1 /=.\napply/andP/and3P => [[/eqP<- x0Ly0] | ].\n  split=> //.\n    by apply/negP; case/eqP => y0E; rewrite y0E // ltxx in x0Ly0.\n  by apply: ltW.\nrewrite eq_quat negb_and /= => [] [/orP[y0Dx0 | y1Dx1] x1Ey1 x0Ly0];\n  split => //.\n  by rewrite lt_neqAle eq_sym y0Dx0.\nby rewrite eq_sym x1Ey1 in y1Dx1.\nQed.\n\nFail Definition quat_POrderedMixin :=\n  NumMixin lequat_normD ltquat0_add eq0_normQ ge0_lequat_total\n           normQM lequat_def ltquat_def.\nFail Canonical Structure quat_numDomainType :=\n  NumDomainType _ quat_POrderedMixin.\n\nDefinition uquat := [qualify x : quat R | normq x == 1].\nFact uquat_key : pred_key uquat. Proof. by []. Qed.\nCanonical uquat_keyed := KeyedQualifier uquat_key.\n\nLemma uquatE x : (x \\is uquat) = (sqrq x == 1).\nProof. by rewrite qualifE /normq -{1}sqrtr1 eqr_sqrt // ?sqrq_ge0// ler01. Qed.\n\nLemma muluq_proof x y : x \\is uquat -> y \\is uquat -> x * y \\is uquat.\nProof. by rewrite 3!qualifE => /eqP Hq /eqP Hp; rewrite normqM Hq Hp mulr1. Qed.\n\nLemma invq_uquat x : x \\is uquat -> x^-1 = x^*q.\nProof.\nby rewrite uquatE => /eqP Hq; rewrite invqE /invq Hq invr1 mul1r scale1r.\nQed.\n\nLemma invuq_proof x : x \\is uquat -> normq (x^-1) == 1.\nProof. by move=> ux; rewrite invq_uquat // normqc. Qed.\n\nLemma cos_atan_uquat x : x \\is uquat -> x \\isn't pureq ->\n  let a := atan (norm x.2 / x.1) in cos a ^+ 2 = x.1 ^+ 2.\nProof.\nmove=> ux q00 a.\nrewrite cos_atan exprMn [x.1 ^-1 ^+2]exprVn.\nhave /divff <- : x.1 ^+ 2 !=0 by rewrite sqrf_eq0.\nrewrite -mulrDl.\nrewrite uquatE /sqrq in ux; rewrite (eqP ux) mul1r.\nby rewrite -exprVn sqrtr_sqr normfV invrK sqr_normr.\nQed.\n\nLemma sin_atan_uquat x : x \\is uquat -> x \\isn't pureq ->\n  let a := atan (norm x.2 / x.1) in sin a ^+ 2 = norm x.2 ^+ 2.\nProof.\nmove=> ux q00 a.\nrewrite /a sqr_sin_atan.\nhave /divrr <- : x.1 ^+ 2 \\in GRing.unit by rewrite unitfE sqrf_eq0.\nrewrite uquatE /sqrq in ux.\nrewrite expr_div_n -mulrDl.\nby rewrite (eqP ux) mul1r invrK -mulrA mulVr ?mulr1 // unitrX // unitfE.\nQed.\n\nEnd quaternion1.\nArguments uquat {R}.\n\nSection conjugation.\nVariable R : realType.\nImplicit Types (x : quat R) (u : 'rV[R]_3).\n\nDefinition conjugation x u : quat R := x * u%:v * x^*q.\n\nLemma conjugation_is_pure x u : conjugation x u \\is pureq.\nProof.\nrewrite pureq_conj /conjugation conjqM conjqI conjqM mulrA -mulrDl -mulrDr.\nby have := pureq_conj u%:v; rewrite qualifE /= eqxx => /esym/eqP ->; Simp.r.\nQed.\n\nLemma conjugationE x u : conjugation x u =\n  ((x.1 ^+ 2 - norm x.2 ^+ 2) *: u +\n   ((x.2 *d u) *: x.2) *+ 2 +\n   (x.1 *: (x.2 *v u)) *+ 2)%:v.\nProof.\ncase: x => x1 x2 /=; rewrite /conjugation /= /conjq /= mulqE /mulq /=.\nrewrite mulr0 scale0r addr0 add0r; congr mkQuat.\n  rewrite dotmulvN opprK dotmulDl (dotmulC (_ *v _) x2) dot_crossmulC.\n  by rewrite liexx dotmul0v addr0 dotmulZv mulNr mulrC dotmulC addrC subrr.\nrewrite scalerDr scalerA -expr2 addrCA scalerBl -!addrA; congr (_ + _).\nrewrite [in X in _ + X = _]linearN /= (lieC _ x2) linearD /= opprK.\nrewrite linearZ /= (addrA (x1 *: _ )) -mulr2n.\nrewrite [in LHS]addrCA 2![in RHS]addrA [in RHS]addrC; congr (_ + _).\nrewrite scalerN scaleNr opprK -addrA addrCA; congr (_ + _).\nby rewrite double_crossmul [in RHS]addrC dotmulvv.\nQed.\n\nLemma conjugation_uquat x : x \\is uquat -> conjugation x x.2 = (x.2)%:v.\nProof.\nrewrite uquatE /sqrq => /eqP xu.\nrewrite conjugationE liexx scaler0 mul0rn addr0 dotmulvv scalerBl mulr2n addrA.\nby rewrite subrK -scalerDl xu scale1r.\nQed.\n\nLemma conjugation_axis x k : x \\is uquat ->\n  conjugation x (k *: x.2) = (k *: x.2)%:v.\nProof.\nmove=> xu; rewrite /conjugation quat_vectZ -scalerAr -scalerAl.\nby rewrite -/(conjugation x x.2) conjugation_uquat.\nQed.\n\nLemma norm_conjugation x u : x \\is uquat -> normq (conjugation x u) = norm u.\nProof.\nrewrite qualifE => /eqP x1; rewrite /conjugation 2!normqM normqc x1; Simp.r.\nby rewrite normq_vector.\nQed.\n\nEnd conjugation.\n\nSection polar_coordinates.\nVariable R : realType.\nImplicit Types (x : quat R) (v : 'rV[R]_3) (a : R).\n\nDefinition quat_of_polar a v := mkQuat (cos a) (sin a *: v).\n\nLemma quat_of_polar01 : quat_of_polar 0 'e_1 = 1%:q.\nProof. by rewrite /quat_of_polar /= cos0 sin0 scale0r. Qed.\n\nLemma quat_of_polarpi1 : quat_of_polar pi 'e_1 = (-1)%:q.\nProof. by rewrite /quat_of_polar cospi sinpi scale0r. Qed.\n\nLemma quat_of_polarpihalf v : quat_of_polar (pi / 2%:R) v = v%:v.\nProof. by rewrite /quat_of_polar cos_pihalf sin_pihalf scale1r. Qed.\n\nLemma uquat_of_polar a v (v1 : norm v = 1) : quat_of_polar a v \\is uquat.\nProof.\nby rewrite uquatE /quat_of_polar /sqrq /= normZ v1 mulr1 sqr_normr cos2Dsin2.\nQed.\n\nDefinition quat_rot x v : 'rV[R]_3 := (conjugation x v).2.\n\nLemma conjugation_quat_of_polar_axis v a : norm v = 1 ->\n  quat_rot (quat_of_polar a v) v = v.\nProof.\nmove=> v1.\nrewrite /quat_rot conjugationE /= normZ exprMn v1 expr1n mulr1 sqr_normr.\nrewrite dotmulZv dotmulvv v1 expr1n mulr1 linearZl_LR liexx 2!scaler0 mul0rn.\nrewrite addr0 scalerA -expr2 mulr2n scalerBl addrA subrK -scalerDl cos2Dsin2.\nby rewrite scale1r.\nQed.\n\nLocal Open Scope frame_scope.\n\nLemma conjugation_quat_of_polar_frame_j (f : frame R) a :\n  quat_rot (quat_of_polar a f~i) f~j =\n  cos (a *+ 2) *: f~j + sin (a *+ 2) *: f~k.\nProof.\nrewrite /quat_rot conjugationE /= normZ noframe_norm mulr1 sqr_normr dotmulZv.\nhave v0 : f~i != 0 by rewrite -norm_eq0 noframe_norm oner_neq0.\nrewrite (noframe_idotj f) mulr0 scale0r mul0rn addr0 linearZl_LR /=.\nrewrite (frame_icrossj f) scalerA [in RHS]mulr2n cosD sinD -!expr2.\nby congr (_ + _); rewrite (mulrC (sin a)) -mulr2n -scalerMnl.\nQed.\n\nLemma conjugation_quat_of_polar_frame_k (f : frame R) a :\n  quat_rot (quat_of_polar a f~i) f~k =\n  - sin (a *+ 2) *: f~j + cos (a *+ 2) *: f~k.\nProof.\nrewrite /quat_rot conjugationE /= normZ noframe_norm mulr1 sqr_normr dotmulZv.\nhave v0 : f~i != 0 by rewrite -norm_eq0 noframe_norm oner_neq0.\nrewrite (noframe_idotk f) mulr0 scale0r mul0rn addr0 linearZl_LR /=.\nrewrite (frame_icrossk f) 2!scalerN scalerA sinD cosD -!expr2 addrC scaleNr.\nby congr (_ + _); rewrite (mulrC (sin a)) -mulr2n -scalerMnl mulNrn.\nQed.\n\nDefinition polar_of_quat x : (R * 'rV_3)%type :=\n  if x.2 == 0 then\n    if x.1 == 1 then (0, 'e_1) else (pi, 'e_1)\n  else if x.1 == 0 then (pi / 2%:R, x.2) else\n  let: u := normalize x.2 in\n  let: a := atan (norm x.2 / x.1) in\n  if 0 < x.1 then (a, u) else (a + pi, u).\n\nLemma polar_of_quat0 : polar_of_quat 0 = (pi, 'e_1).\nProof. by rewrite /polar_of_quat eqxx eq_sym oner_eq0. Qed.\n\nLemma norm_polar_of_quat x : x \\is uquat -> norm (polar_of_quat x).2 = 1.\nProof.\ncase: x => a0 a1; rewrite /= qualifE /polar_of_quat /normq /sqrq /=.\nhave [/eqP ->|a10] := ifPn; first by case: ifPn; rewrite norm_delta_mx.\ncase: (sgzP a0) => [-> /eqP| |]; try by rewrite norm_normalize.\nby rewrite expr0n add0r sqrtr_sqr ger0_norm // norm_ge0.\nQed.\n\nLemma polar_of_quatK x : x \\is uquat ->\n  quat_of_polar (polar_of_quat x).1 (polar_of_quat x).2 = x.\nProof.\ncase: x => a0 a1; rewrite /= qualifE /polar_of_quat /normq /sqrq /=.\nhave [->|/eqP a1N u1] := a1 =P 0.\n  rewrite norm0 expr0n addr0 sqrtr_sqr; have [?/eqP->|?|_] := ltrgt0P a0.\n  - by rewrite eqxx quat_of_polar01.\n  - by rewrite eqr_oppLR => /eqP ->; rewrite eqrNxx oner_eq0 quat_of_polarpi1.\n  - by rewrite eq_sym oner_eq0.\nmove: u1; have [-> _|a0P /eqP u1 |a0N /eqP u1] := sgzP a0.\n- by rewrite quat_of_polarpihalf.\n- congr mkQuat.\n    by rewrite cos_atan sqrtr_1sqr2 ?gt_eqF// gtr0_norm// invrK.\n  rewrite sin_atan sqrtr_1sqr2 ?gt_eqF// gtr0_norm// invrK -mulrA.\n  by rewrite mulVf ?gt_eqF// mulr1 norm_scale_normalize.\n- congr mkQuat.\n    rewrite cosDpi cos_atan sqrtr_1sqr2 ?lt_eqF// invrK ltr0_norm//.\n    by rewrite opprK.\n  rewrite sinDpi sin_atan sqrtr_1sqr2// ?lt_eqF// ltr0_norm// 2!invrN mulrN.\n  by rewrite invrK opprK -mulrA mulVf ?lt_eqF// mulr1 norm_scale_normalize.\nQed.\n\nLemma quat_rot_is_linear x : linear (quat_rot x).\nProof.\nmove=> k u v; rewrite /quat_rot !conjugationE.\nrewrite scalerDr scalerA (mulrC _ k) -scalerA.\nrewrite 2![in RHS]scalerDr -2![in LHS]addrA -3![in RHS]addrA; congr (_ + _).\nrewrite [in RHS]addrA [in RHS]addrCA -[in RHS]addrA; congr (_ + _).\nrewrite dotmulDr scalerDl mulrnDl -addrA addrCA; congr (_ + _).\nrewrite dotmulvZ -scalerA scalerMnr -addrA; congr (_ + _).\nrewrite linearD /= scalerDr mulrnDl; congr (_ + _).\nby rewrite linearZ /= scalerA mulrC -scalerA -scalerMnr.\nQed.\nCanonical quat_rot_linear x := Linear (quat_rot_is_linear x).\n\nLemma quat_rot_isRot_polar v a : norm v = 1 ->\n  isRot (a *+2) v [linear of quat_rot (quat_of_polar a v)].\nProof.\nmove=> v1 /=.\nhave vE : (Base.frame v)~i = v by rewrite Base.frame0E // ?normalizeI // norm1_neq0.\napply/isRotP; split => /=.\n- by rewrite conjugation_quat_of_polar_axis.\n- by rewrite -{1}vE conjugation_quat_of_polar_frame_j.\n- by rewrite -{1}vE conjugation_quat_of_polar_frame_k.\nQed.\n\nLemma quat_rot_isRot x : x \\is uquat ->\n  let: a := (polar_of_quat x).1 in\n  let: u := (polar_of_quat x).2 in\n  isRot (a *+ 2) u [linear of quat_rot x].\nProof.\nmove=> ux /=; set a := _.1; set u := _.2.\nby rewrite -(polar_of_quatK ux) quat_rot_isRot_polar // norm_polar_of_quat.\nQed.\n\nLocal Open Scope quat_scope.\n\n(* [bottema] p.150 (2.1) *)\n(* compared to cayleyij:\nthe Rodrigues' parameters a, b, c are \"normalized\" into r a, b r, c r with r != 0\nwe have the relation\n(1 + a^2 + b^2 + c^2) cayley_transform = cayley_matrix\n(r^2 + a^2 + b^2 + c^2) cayley_transform = hcayley_matrix\n*)\nDefinition hcayley00 (r a b c : R) := r ^+ 2 + a ^+ 2 - b ^+ 2 - c ^+ 2.\nDefinition hcayley01 (r a b c : R) := (a * b - r * c) *+ 2.\nDefinition hcayley02 (r a b c : R) := (a * c + r * b) *+ 2.\nDefinition hcayley10 (r a b c : R) := (a * b + r * c) *+ 2.\nDefinition hcayley11 (r a b c : R) := r ^+ 2 - a ^+ 2 + b ^+ 2 - c ^+ 2.\nDefinition hcayley12 (r a b c : R) := (b * c - r * a) *+ 2.\nDefinition hcayley20 (r a b c : R) := (a * c - r * b) *+ 2.\nDefinition hcayley21 (r a b c : R) := (b * c + r * a) *+ 2.\nDefinition hcayley22 (r a b c : R) := r ^+ 2 - a ^+ 2 - b ^+ 2 + c ^+ 2.\n\nLemma matrix_of_quat_rot (q : quat R) (u : 'rV[R]_3) :\n(*  q \\is uquat ->*)\n  let: r := q.1 in let: a := q _i in let: b := q _j in let: c := q _k in\n  quat_rot q u =\n    u *m (col_mx3\n    (row3 (hcayley00 r a b c) (hcayley01 r a b c) (hcayley02 r a b c))\n    (row3 (hcayley10 r a b c) (hcayley11 r a b c) (hcayley12 r a b c))\n    (row3 (hcayley20 r a b c) (hcayley21 r a b c) (hcayley22 r a b c)))^T.\nProof.\nhave F (e1 q1 u1 : 'rV[R]_3) : \\det (col_mx3 e1 q1 u1) =\n  e1``_0 * (q1``_1 * u1``_2%:R - u1``_1 * q1``_2%:R) +\n  e1``_1 * (u1``_0 * q1``_2%:R - q1``_0 * u1``_2%:R) +\n  e1``_2%:R * (q1``_0 * u1``_1 - u1``_0 * q1``_1).\n  by rewrite det_mx33 !mxE.\napply/row3P; apply/and3P; split; apply/eqP.\n(* ForAll[{u1, u2, u3, q1, q21, q22, q23},\n  q1^2 + q21^2 + q22^2 + q23^2 == 1,\n  ((q1^2 - q21^2 - q22^2 - q23^2) {u1, u2, u3} +\n      2 (Dot[{q21, q22, q23}, {u1, u2, u3}] {q21, q22, q23}) +\n      2 (q1 Cross[{q21, q22, q23}, {u1, u2, u3}]))[[1]] ==\n   u1 (q1^2 + q21^2 - q22^2 - q23^2) +\n    u2 (2 (q21*q22 - q1*q23)) +\n    u3 (2 (q21*q23 + q1*q22))] // Resolve*)\n- rewrite !(mxE, sum3E) /=.\n  rewrite /crossmul; unlock.\n  rewrite !(mxE, sum3E) /= !F !mxE /= !F !mxE /=.\n  rewrite !dotmulE sum3E /=.\n  rewrite /hcayley00 /hcayley01 /hcayley02 !expr2 !mulr2n.\n  nsatz.\n(* ForAll[{u1, u2, u3, q1, q21, q22, q23},\n  q1^2 + q21^2 + q22^2 + q23^2 == 1,\n  ((q1^2 - q21^2 - q22^2 - q23^2) {u1, u2, u3} +\n      2 (Dot[{q21, q22, q23}, {u1, u2, u3}] {q21, q22, q23}) +\n      2 (q1 Cross[{q21, q22, q23}, {u1, u2, u3}]))[[2]] ==\n   u1 (2 (q21*q22 + q1*q23)) +\n    u2 (q1^2 - q21^2 + q22^2 - q23^2) +\n    u3 (2 (q22*q23 - q1*q21))] // Resolve *)\n- rewrite !(mxE, sum3E) /=.\n  rewrite /crossmul; unlock.\n  rewrite !(mxE, sum3E) /= !F /= !mxE /= !F !mxE /=.\n  rewrite !dotmulE sum3E /=.\n  rewrite /hcayley10 /hcayley11 /hcayley12 !expr2 !mulr2n.\n  nsatz.\n(* ForAll[{u1, u2, u3, q1, q21, q22, q23},\n  q1^2 + q21^2 + q22^2 + q23^2 == 1,\n  ((q1^2 - q21^2 - q22^2 - q23^2) {u1, u2, u3} +\n      2 (Dot[{q21, q22, q23}, {u1, u2, u3}] {q21, q22, q23}) +\n      2 (q1 Cross[{q21, q22, q23}, {u1, u2, u3}]))[[3]] ==\n   u1 (2 (q21*q23 - q1*q22)) +\n    u2 (2 (q22*q23 + q1*q21)) +\n    u3 (q1^2 - q21^2 - q22^2 + q23^2)] // Resolve *)\nrewrite !(mxE, sum3E) /=.\nrewrite /crossmul; unlock.\nrewrite !(mxE, sum3E) /= !F /= !mxE /= !F !mxE /=.\nrewrite !dotmulE sum3E /=.\nrewrite /hcayley20 /hcayley21 /hcayley22 !expr2 !mulr2n.\nnsatz.\nQed.\n\nEnd polar_coordinates.\n\nSection dual_number.\nVariable R : ringType.\nImplicit Types r : R.\nRecord dual := mkDual {ldual : R ; rdual : R}.\nImplicit Types x y : dual.\n\nLocal Notation \"x +ɛ* y\" := (mkDual x y).\nLocal Notation \"x -ɛ* y\" := (mkDual x (- y)).\n\nDefinition dual0 : dual := 0 +ɛ* 0.\nDefinition dual1 : dual := 1 +ɛ* 0.\n\nCoercion pair_of_dual x : R * R := let: mkDual x1 x2 := x in (x1, x2).\n\nLet dual_of_pair (z : R * R) := let: (z1, z2) := z in z1 +ɛ* z2.\n\nLemma dual_of_pairK : cancel pair_of_dual dual_of_pair.\nProof. by case. Qed.\n\nDefinition dual_eqMixin := CanEqMixin dual_of_pairK.\nCanonical Structure dual_eqType := EqType dual dual_eqMixin.\nDefinition dual_choiceMixin := CanChoiceMixin dual_of_pairK.\nCanonical Structure dual_choiceType := ChoiceType dual dual_choiceMixin.\n\nDefinition oppd x := (- x.1) +ɛ* (- x.2).\n\nDefinition addd x y := (x.1 + y.1) +ɛ* (x.2 + y.2).\n\nDefinition muld x y := x.1 * y.1 +ɛ* (x.1 * y.2 + x.2 * y.1).\n\nDefinition deps : 'M[R]_2 :=\n  \\matrix_(i < 2, j < 2) ((i == 0) && (j == 1))%:R.\n\nLemma deps2 : deps ^+2 = 0.\nProof.\nrewrite expr2; apply/matrixP => i j.\nby rewrite !mxE sum2E !mxE /= mulr0 addr0 -ifnot01 eqxx andbF mul0r.\nQed.\n\nDefinition mat_of_dual x : 'M[R]_2 := x.1%:M + x.2 *: deps.\n\nDefinition dual_of_mat (M : 'M[R]_2) := (M 0 0) +ɛ* (M 0 1).\n\nLemma adddE x y : addd x y = dual_of_mat (mat_of_dual x + mat_of_dual y).\nProof.\nrewrite /addd /dual_of_mat /mat_of_dual /= !mxE; congr mkDual.\nby rewrite !eqxx !(mulr1n,andbF,mulr1,mulr0,addr0).\nby rewrite !mulr0n !eqxx !mulr1 !add0r.\nQed.\n\nLemma muldE x y : muld x y = dual_of_mat (mat_of_dual x * mat_of_dual y).\nProof.\nrewrite /muld /dual_of_mat /mat_of_dual /= !mxE !sum2E !mxE; congr mkDual.\nby rewrite !eqxx !(mulr0n,mulr1n,mulr0,mulr1,addr0).\nby rewrite !eqxx !(mulr0n,mulr1n,mulr0,add0r,addr0,mulr1).\nQed.\n\nLemma adddA : associative addd.\nProof. by move=> x y z; rewrite /addd 2!addrA. Qed.\n\nLemma adddC : commutative addd.\nProof. by move=> x y; rewrite /addd addrC [in X in _ +ɛ* X = _]addrC. Qed.\n\nLemma add0d : left_id dual0 addd.\nProof. by move=> x; rewrite /addd 2!add0r; case: x. Qed.\n\nLemma addNd : left_inverse dual0 oppd addd.\nProof. by move=> x; rewrite /addd 2!addNr. Qed.\n\nDefinition dual_ZmodMixin := ZmodMixin adddA adddC add0d addNd.\nCanonical dual_ZmodType := ZmodType dual dual_ZmodMixin.\n\nLemma addd_def x y : x + y = (x.1 + y.1) +ɛ* (x.2 + y.2).\nProof. by []. Qed.\n\nLemma muldA : associative muld.\nProof.\nmove=> x y z; rewrite /muld; congr mkDual; first by rewrite mulrA.\nby rewrite mulrDr mulrDl !mulrA addrA.\nQed.\n\nLemma mul1d : left_id dual1 muld.\nProof. by case=> x0 x1; rewrite /muld 2!mul1r mul0r addr0. Qed.\n\nLemma muld1 : right_id dual1 muld.\nProof. by case=> x0 x1; rewrite /muld 2!mulr1 mulr0 add0r. Qed.\n\nLemma muldDl : left_distributive muld addd.\nProof.\nmove=> x y z; rewrite /muld /addd mulrDl; congr mkDual.\nby rewrite mulrDl -!addrA; congr (_ + _); rewrite mulrDl addrCA.\nQed.\n\nLemma muldDr : right_distributive muld addd.\nProof.\nmove=> x y z; rewrite /muld /addd mulrDr; congr mkDual.\nby rewrite mulrDr -!addrA; congr (_ + _); rewrite mulrDr addrCA.\nQed.\n\nLemma oned_neq0 : dual1 != 0 :> dual.\nProof. by apply/eqP; case; apply/eqP; exact: oner_neq0. Qed.\n\nDefinition dual_RingMixin := RingMixin muldA mul1d muld1 muldDl muldDr oned_neq0.\nCanonical Structure dual_Ring := Eval hnf in RingType dual dual_RingMixin.\n\nLemma muld_def x y : x * y = x.1 * y.1 +ɛ* (x.1 * y.2 + x.2 * y.1).\nProof. by []. Qed.\n\nDefinition scaled r x := r * x.1 +ɛ* (r * x.2).\n\nLemma scaledA a b x : scaled a (scaled b x) = scaled (a * b) x.\nProof. by rewrite /scaled /=; congr mkDual; rewrite mulrA. Qed.\n\nLemma scaled1 : left_id 1 scaled.\nProof. by rewrite /left_id /scaled /=; case=> ? ? /=; rewrite !mul1r. Qed.\n\nLemma scaledDr : @right_distributive R dual scaled +%R.\nProof. by move=> r x y; rewrite /scaled /= !mulrDr. Qed.\n\nLemma scaledDl x : {morph (scaled^~ x : R -> dual) : a b / a + b}.\nProof. by move=> a b; rewrite /scaled !mulrDl. Qed.\n\nDefinition dual_lmodMixin := LmodMixin scaledA scaled1 scaledDr scaledDl.\nCanonical dual_lmodType := Eval hnf in LmodType R dual dual_lmodMixin.\n\nDefinition conjd x := x.1 -ɛ* x.2.\nLocal Notation \"x '^*d'\" := (conjd x).\n\nDefinition duall (r : R) := r +ɛ* 0.\n\nLocal Notation \"*%:dl\" := duall (at level 2).\nLocal Notation \"r %:dl\" := (duall r) (at level 2).\n\nFact duall_is_rmorphism : rmorphism *%:dl.\nProof.\nsplit => [p q|]; first by congr mkDual; rewrite /= subrr.\nsplit => [p q|] //; by congr mkDual; rewrite /=; Simp.r.\nQed.\nCanonical duall_rmorphism := RMorphism duall_is_rmorphism.\n\n(* Sanity check : Taylor series for polynomial *)\nLemma dual_deriv_poly (p : {poly R}) r :\n  (map_poly *%:dl p).[r +ɛ* 1] = p.[r] +ɛ* p^`().[r].\nProof.\nelim/poly_ind : p => [|p b IH]; first by rewrite map_poly0 deriv0 !horner0.\nrewrite !(rmorphD, rmorphM) /= map_polyX (map_polyC duall_rmorphism) /=.\nrewrite derivD derivC derivM derivX; Simp.r.\nrewrite !hornerMXaddC hornerD hornerMX IH; congr mkDual => /=.\nby Simp.r; rewrite addrC.\nQed.\n\nEnd dual_number.\n\nNotation \"a +ɛ* b\" := (mkDual a b) : dual_scope.\nNotation \"a -ɛ* b\" := (mkDual a (- b)) : dual_scope.\n\nSection dual_comm.\nVariable R : comRingType.\n\nFact muld_comm (p q : dual R) : p * q = q * p.\nProof.\ncase: p => p1 p2; case: q => q1 q2; rewrite !muld_def /=.\nby rewrite addrC mulrC [p2 * _]mulrC [q2 * _]mulrC.\nQed.\nCanonical dual_comRingType := Eval hnf in ComRingType (dual R) muld_comm.\n\nEnd dual_comm.\n\nSection dual_number_unit.\nVariable R : unitRingType.\nLocal Open Scope dual_scope.\nImplicit Types x y : dual R.\n\nDefinition unitd : pred (dual R) := [pred x : dual R | x.1 \\is a GRing.unit].\n\nDefinition invd x :=\n  if x \\in unitd then x.1^-1 -ɛ* (x.1^-1 * x.2 * x.1^-1) else x.\n\n(* NB: invd was previously written using matrices *)\nFact invdE x : x \\in unitd ->\n  invd x = dual_of_mat (x.1^-1%:M * (1 - deps R * x.2%:M * (x.1)^-1%:M)).\nProof.\nmove : x => [q r] /=; rewrite inE /= => qu; rewrite /invd inE /= qu.\nby rewrite /dual_of_mat !(mxE,sum2E) /=; Simp.r.\nQed.\n\nLemma mulVd : {in unitd, left_inverse 1 invd *%R}.\nProof.\nmove=> [q r]; rewrite inE /= => qu.\nby rewrite /invd inE qu muld_def /= mulNr -mulrA !mulVr// mulr1 subrr.\nQed.\n\nLemma muldV : {in unitd, right_inverse 1 invd *%R}.\nProof.\nmove=> [q r]; rewrite inE /= => qu; rewrite /invd inE qu /= muld_def /=.\nby rewrite mulrN 2!mulrA divrr// mul1r addrC subrr.\nQed.\n\nLemma unitdP x y : y * x = 1 /\\ x * y = 1 -> unitd x.\nProof. by rewrite 2!muld_def => -[[? _] [? _]]; apply/unitrP; exists y.1. Qed.\n\n(* The inverse of a non-unit x is constrained to be x itself *)\nLemma invd0id : {in [predC unitd], invd =1 id}.\nProof. by move=> x; rewrite inE /= /invd => /negbTE ->. Qed.\n\nDefinition dual_UnitRingMixin := UnitRingMixin mulVd muldV unitdP invd0id.\nCanonical dual_unitRing := UnitRingType (dual R) dual_UnitRingMixin.\n\nEnd dual_number_unit.\n\nSection dual_quaternion.\nVariable R : realType (*realType*).\nLocal Open Scope dual_scope.\n\nDefinition dquat := @dual (quat_unitRing R).\n\nImplicit Types x y : dquat.\n\nDefinition conjdq x : dquat := (x.1)^*q +ɛ* (x.2)^*q.\n\nCanonical Conjugate_dquaternion := @Build_Conjugate (@dual (quat_unitRing R)) conjdq.\n\nLemma conjdq_def x : x^*q = (x.1)^*q +ɛ* (x.2)^*q.\nProof. by case: x. Qed.\n\nLemma conjdqD x y : (x + y)^*q = x^*q + y^*q.\nProof. by rewrite conjdq_def /= 2!linearD. Qed.\n\nLemma conjdqI x : (x^*q)^*q = x.\nProof. by rewrite !conjdq_def /= !conjqI; case: x. Qed.\n\nLemma conjdq0 : (0 : dquat)^*q = 0.\nProof. by rewrite conjdq_def /= conjq0. Qed.\n\nLemma conjdqM x y : (x * y)^*q = y^*q * x^*q.\nProof.\nrewrite /= conjdq_def /= !muld_def /= !conjqM; congr mkDual.\nby rewrite linearD /= !conjqM addrC.\nQed.\n\nLemma conjdq_comm x : x^*q * x = x * x^*q.\nProof. by rewrite conjdq_def /= !muld_def /= conjq_comm conjq_comm2 addrC. Qed.\n\nLemma conjdq_unit x : (x^*q \\is a GRing.unit) = (x \\is a GRing.unit).\nProof.\ncase: x => [] [a0 av] [b0 bv].\nby rewrite !qualifE /= /unitd /= !qualifE /= /unitq /= !eq_quat /= oppr_eq0.\nQed.\n\nDefinition puredq := [qualify x : dquat | (x.1 \\is pureq) && (x.2 \\is pureq)].\nFact puredq_key : pred_key puredq. Proof. by []. Qed.\nCanonical puredq_keyed := KeyedQualifier puredq_key.\n\nDefinition dnum := [qualify x : dquat | x^*q == x].\nFact dnum_key : pred_key dnum. Proof. by []. Qed.\nCanonical dnum_keyed := KeyedQualifier dnum_key.\n\nLemma dnumE x : (x \\is dnum) = (x^*q == x).\nProof. by []. Qed.\n\nLemma dnumE' x : (x \\is dnum) = (x.1.2 == 0) && (x.2.2 == 0).\nProof.\ncase: x => [] [a1 a2] [b1 b2]; rewrite dnumE /conjdq /=.\nby rewrite -[a2 == 0]andTb -[b2 == 0]andTb;\n   congr ((_ && _) && (_ && _)); rewrite ?eqxx //= eq_sym\n     -subr_eq0 opprK -mulr2n -scaler_nat scalemx_eq0 (eqr_nat _ 2 0).\nQed.\n\nLemma dnumE'' x : (x \\is dnum) = (x == (x.1.1)%:q +ɛ* (x.2.1)%:q).\nProof.\ncase: x => [] [a1 a2] [b1 b2]; rewrite dnumE' /=.\nby rewrite -[a2 == 0]andTb -[b2 == 0]andTb;\n   congr ((_ && _) && (_ && _)); rewrite /= !eqxx.\nQed.\n\nLemma dnumD x y : x \\is dnum -> y \\is dnum -> x + y \\is dnum.\nProof. by rewrite 3!dnumE conjdqD => /eqP-> /eqP->. Qed.\n\nLemma dnum0 : 0 \\is dnum.\nProof. by rewrite dnumE' eqxx. Qed.\n\nLemma dnum1 : 1 \\is dnum.\nProof. by rewrite dnumE' eqxx. Qed.\n\nLemma dnum_nat n : n%:R \\is dnum.\nProof.\nelim: n => [|n IH]; first by rewrite dnum0.\nby rewrite -add1n natrD dnumD // dnum1.\nQed.\n\nLemma dnumM x y : x \\is dnum -> y \\is dnum -> x * y \\is dnum.\nProof.\nrewrite 3!dnumE' muld_def /= => /andP[/eqP-> /eqP->] /andP[/eqP-> /eqP->].\nby rewrite !linear0r !scaler0 !add0r eqxx.\nQed.\n\nLemma dnumM_comm x y : x \\is dnum -> y * x = x * y.\nProof.\ncase: y => done1 y2; rewrite dnumE'' => /eqP->.\nby rewrite !muld_def /= !quat_algE -!quatAr -!quatAl !mulr1 !mul1r addrC.\nQed.\n\n(* squared norm *)\nDefinition sqrdq x : dquat := x * x^*q.\n\nLemma dnum_sqrdq x : sqrdq x \\in dnum.\nProof. by rewrite dnumE conjdqM conjdqI. Qed.\n\n(* inverse *)\nDefinition invdq x : dquat := x^-1.\n\nLemma invdqEl x : x.1 != 0 -> invdq x = (sqrdq x)^-1 * (x^*q).\nProof.\nmove=> aD; rewrite /sqrdq -conjdq_comm invrM  ?conjdq_unit //.\nby rewrite divrK ?conjdq_unit.\nQed.\n\nLemma invdqEr x : x.1 != 0 -> invdq x = (x^*q) * (sqrdq x)^-1.\nProof.\nmove=> aD; rewrite /sqrdq invrM  ?conjdq_unit // mulrA.\nby rewrite mulrV ?mul1r // ?conjdq_unit.\nQed.\n\n(* unit dual quaternions *)\nDefinition udquat := [qualify x : dquat | sqrdq x == 1].\nFact udquat_key : pred_key udquat. Proof. by []. Qed.\nCanonical udquat_keyed := KeyedQualifier udquat_key.\n\nLemma udquatE x : (x \\is udquat) = (sqrdq x == 1).\nProof. by []. Qed.\n\nLemma invdq_udquat x : x \\is udquat -> x^-1 = x^*q.\nProof.\nrewrite udquatE => /eqP sqE.\nsuff x1NZ : x.1 != 0 by rewrite [x^-1]invdqEl // sqE invr1 mul1r.\napply/eqP=> x1Z.\nmove/eqP: sqE; rewrite [sqrdq _]muld_def x1Z !mul0r => /andP[] /=.\nby rewrite eq_sym oner_eq0.\nQed.\n\nEnd dual_quaternion.\n\n(* WIP: dual quaternions and rigid body transformations *)\nSection dquat_rbt.\nVariable R : realType (*realType*).\nLocal Open Scope dual_scope.\nImplicit Types u x : dquat R.\n\nDefinition dconjugation (u : dquat R)(*unit dual quaternion*)\n                        (x : dquat R)(*dual vector quaternion*) := u * x * u ^*q.\n\nDefinition dquat_from_rot_trans (r t : quat R)\n  (_ : r \\is uquat) (_ : r \\isn't pureq) (_ : (polar_of_quat r).1 != 0)\n  (* i.e., rotation around (polar_of_quat r).1 of angle (polar_of_quat r).2 *+ 2 *)\n  (_ : t \\is pureq)\n  : dquat R := r +ɛ* t.\n\nDefinition rot_trans_from_dquat x := (x.1, 2%:R *: (x.2 * x.1^*q)).\n\nEnd dquat_rbt.\n", "meta": {"author": "affeldt-aist", "repo": "coq-robot", "sha": "5c7b536dc17748f3a397995f04cec7f99bca402b", "save_path": "github-repos/coq/affeldt-aist-coq-robot", "path": "github-repos/coq/affeldt-aist-coq-robot/coq-robot-5c7b536dc17748f3a397995f04cec7f99bca402b/quaternion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7194175786596412}}
{"text": "Require Import VST.floyd.proofauto.\n\n(*Model-level definitions and associated lemmas.*)\n\nDefinition sumlist : list Z -> Z := fold_right Z.add Z0.\n\nFixpoint decreasing (n: nat) :=\n match n with\n | O => nil\n | S n' => Z.of_nat n :: decreasing n'\n end.\n\nFixpoint triang (n: nat) :=\n match n with\n | O => 0\n | S n' => Z.of_nat n + triang n'\n end.\n\nLemma triangular_number:\n  forall n, 0 <= n -> \n     sumlist (decreasing (Z.to_nat n)) = n*(n+1)/2.\nProof.\nintros.\nassert (2* sumlist (decreasing (Z.to_nat n)) = n * (n + 1))%Z.\n2: rewrite <- H0, Z.mul_comm, Z.div_mul by lia; auto.\nrewrite <- (Z2Nat.id n) at 2 3 by lia.\nclear H.\ninduction (Z.to_nat n).\nreflexivity.\nrewrite inj_S.\nunfold decreasing; fold decreasing.\nchange (sumlist (Z.of_nat (S n0) :: decreasing n0))\n  with (Z.of_nat (S n0) + sumlist (decreasing n0)).\nrewrite Z.mul_add_distr_l.\nrewrite IHn0.\nclear.\nrewrite inj_S.\nforget (Z.of_nat n0) as n.\nunfold Z.succ.\nrewrite !Z.mul_add_distr_l.\nrewrite !Z.mul_add_distr_r.\nlia.\nQed.\n\nLemma sumlist_decreasing_bound:\n  forall n, 0 <= n < 1000 ->\n  0 <= sumlist (decreasing (Z.to_nat n)) <= Int.max_signed.\nProof.\nintros.\nrewrite triangular_number by lia.\nsplit.\napply Z.div_pos; try lia.\n(*apply Z.mul_nonneg_nonneg; lia.*)\napply Z.div_le_upper_bound; try lia.\neapply Z.le_trans.\napply Z.mul_le_mono_nonneg; try lia.\ninstantiate (1:=1001); lia.\ninstantiate (1:=1001); lia.\ncomputable.\nQed.\n\nLemma sumlist_nonneg: forall sigma, \n  Forall (Z.le 0) sigma -> 0 <= sumlist sigma.\nProof.\nintros.\ninduction sigma; simpl. lia. inv H.\napply IHsigma in H3; lia.\nQed.\n\nLemma decreasing_inc i (I:0 <= i):\n  i + 1 :: decreasing (Z.to_nat i) = decreasing (Z.to_nat (i + 1)).\nProof. \n    replace (Z.to_nat (i+1)) with (S (Z.to_nat i)).\n    unfold decreasing; fold decreasing.\n    + f_equal. rewrite inj_S. rewrite Z2Nat.id by lia. lia.\n    + rewrite <- Z2Nat.inj_succ by lia. f_equal; lia.\nQed.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/VSUpile/PileModel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.719383873805265}}
{"text": "(* NOMBRE COMPLETO: Agustín Mista *)\n\nSection Problema1.\n\n  Require Export List.\n  Require Export Arith.\n  Print beq_nat.\n\n  Set Implicit Arguments.\n\n  (* 1.a *)\n  Fixpoint eliminar (z : nat) (l : list nat) : list nat :=\n    match l with\n    | nil => nil\n    | cons x xs =>\n      if beq_nat x z\n      then xs\n      else cons x (eliminar z xs)\n    end.\n\n  (* 1.b *)\n  Fixpoint pertenece (z : nat) (l : list nat) : bool :=\n    match l with\n    | nil => false\n    | cons x xs =>\n      if beq_nat x z\n      then true\n      else pertenece z xs\n    end.\n\n  (* 1.c *)\n  Fixpoint concatenar (A : Set) (l1 l2 : list A) : list A :=\n    match l1 with\n    | nil => l2\n    | cons x l1' => cons x (concatenar l1' l2)\n    end.\n\n  (* 1.d.1 *)\n  Lemma L1_1 : forall (A : Set) (l : list A) (x : A), l <> x::l.\n  Proof. \n    intros. induction l; unfold not; intros.\n    - discriminate.\n    - injection H. intros.\n      apply IHl. rewrite <- H1. auto.\n  Qed.\n\n  (* 1.d.2 *)\n  Lemma L1_2 : forall (l1 l2 : list nat) (x : nat), \n      pertenece x (concatenar l1 l2) = true -> \n      pertenece x l1 = true \\/ pertenece x l2 = true.\n  Proof.\n    intros. induction l1.\n    - simpl in H. right. auto.\n    - simpl in H. case (a =? x) eqn:eq1.\n      + simpl. rewrite eq1. left. auto.\n      + apply IHl1 in H. elim H; intros.\n        * left. simpl. rewrite eq1. auto.\n        * right. auto.\n  Qed.\n  \n  (* 1.d.3 *)\n  Lemma L1_3 : forall (l : list nat) (x : nat), \n      pertenece x l = true -> eliminar x l <> l.\n  Proof. \n    intros. induction l.\n    - inversion H.\n    - simpl. case (a =? x) eqn:eq1.\n      + apply L1_1.\n      + simpl in H. rewrite eq1 in H.\n        apply IHl in H. injection.\n        contradiction.\n  Qed.\n\nEnd Problema1.\n\n\nSection Problema2.\n\n  Require Import Coq.Bool.Bool.\n\n  (* 2.a *)\n  Inductive distintas (A:Set) : list A -> list A -> Prop :=\n  | distintas_nil : distintas nil nil\n  | distintas_cons : forall l1 l2 x y,\n      x <> y -> distintas l1 l2 -> distintas (cons x l1) (cons y l2).\n\n  Hint Constructors distintas.\n\n  (* 2.b *)\n  Lemma L2 : forall (l1 : list bool), { l2 : list bool | distintas l1 l2 }.\n  Proof. \n    intros. induction l1.\n    - exists nil. auto.\n    - elim IHl1. intros. exists (cons (negb a) x). constructor; auto.\n      case a eqn:eq1; simpl; unfold not; intros; discriminate.\n  Qed.\n\nEnd Problema2.\n\n(* 2.3 *)\nExtraction Language Haskell.\nExtract Inductive bool => \"Bool\" [ \"true\" \"false\" ].\nExtraction \"L2\" L2.\n\nSection Problema3.\n \n  Definition Var := nat.\n  Definition Valor := nat.\n\n  Definition Memoria := Var -> Valor.\n\n  (* 3.a *)\n  Inductive Instr : Set :=\n  | IVar : Var -> Valor -> Instr\n  | ISeq : Instr -> Instr -> Instr\n  | IIf  : Var -> Valor -> Instr -> Instr -> Instr.\n\n  (* 3.b *)\n  Definition lookup (m : Memoria) (v : Var) : Valor := m v.\n\n  Definition update (m : Memoria) (v : Var) (w : Valor) : Memoria := \n    fun v' => if beq_nat v v'\n              then w\n              else m v'.\n  \n  (* 3.c *)\n  Inductive Execute : Memoria -> Instr -> Memoria -> Prop :=\n  | XAss : forall var val mem,\n      Execute mem (IVar var val) (update mem var val)\n  | XSeq : forall ins1 ins2 mem1 mem2 mem3,\n      Execute mem1 ins1 mem2\n      -> Execute mem2 ins2 mem3\n      -> Execute mem1 (ISeq ins1 ins2) mem3\n  | XIfT : forall var val ins1 ins2 mem1 mem2,\n      lookup mem1 var = val\n      -> Execute mem1 ins1 mem2\n      -> Execute mem1 (IIf var val ins1 ins2) mem2 \n  | XIfF : forall var val ins1 ins2 mem1 mem2,\n      lookup mem1 var <> val\n      -> Execute mem1 ins2 mem2\n      -> Execute mem1 (IIf var val ins1 ins2) mem2. \n\n  Hint Constructors Execute.\n\n  (* 3.d *)\n  Lemma L3_1 : forall (m1 m2 : Memoria) (var : Var) (val : Valor), \n      Execute m1 (IVar var val) m2 -> lookup m2 var = val.\n  Proof.\n    intros. inversion H. unfold update, lookup.\n    rewrite <- beq_nat_refl. auto.\n  Qed.\n\n  Lemma L3_2 : forall (m1 m2 : Memoria) (v : Var) (val : Valor) (i1 i2 : Instr), \n      lookup m1 v <> val\n      -> Execute m1 (IIf v val i1 i2) m2\n      -> Execute m1 i2 m2.\n  Proof.\n    intros. unfold not in H.\n    inversion_clear H0; auto.\n    contradiction.\n  Qed.\n\n  Require Import Omega.\n\n  Lemma L3_3: forall (m1 m2 m3 : Memoria) (v1 v2 : Var) (val : Valor) (i1 i2 : Instr),\n      v2 <> v1\n      -> Execute m1 (ISeq (IVar v1 val) (IVar v2 (val + 1))) m2\n      -> Execute m2 i2 m3\n      -> Execute m2 (IIf v2 (lookup m2 v1) i1 i2) m3.\n  Proof.\n    intros. apply XIfF.\n    - inversion H0. inversion H5. rewrite <- H9 in H7. inversion H7.\n      unfold lookup, update. rewrite <- beq_nat_refl. rewrite <- beq_nat_refl.\n      elim (beq_nat_false_iff v2 v1). intros. rewrite (H17 H). omega.\n    - inversion H0. auto.\n  Qed.\n \nEnd Problema3.\n", "meta": {"author": "agustinmista", "repo": "coq", "sha": "b88431c1bed91cf0d9a69f5a058504edd19482ce", "save_path": "github-repos/coq/agustinmista-coq", "path": "github-repos/coq/agustinmista-coq/coq-b88431c1bed91cf0d9a69f5a058504edd19482ce/parcial/parcial2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7193838723646421}}
{"text": "Require Import ZArith Bool.\n\nInductive Z_btree : Set :=\n | Z_leaf : Z_btree \n | Z_bnode : Z->Z_btree->Z_btree->Z_btree.\n\nFixpoint value_present (z:Z)(t:Z_btree) : bool :=\n   match t with\n   | Z_leaf => false\n   | Z_bnode z1  t1 t2 => Zeq_bool z z1 || \n                          value_present z t1  || \n                          value_present z t2\n   end.\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/ch6_inductive_data/SRC/value_present.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7193565295915649}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import Arith.Max.\n\nRequire Import set.\nRequire Import order.\nRequire Import elements.\n\nLemma order_elements : forall (a x:set), In x (elements a) -> order x < order a.\nProof. intro a. elim a. (* induction on a*)\n  (* a = Empty *)\n  simpl. intro x. apply False_ind. \n  (* a = Singleton x *)\n  clear a. intro x. intro H. clear H. intro z. simpl. intro H. elim H. intro H'.\n  rewrite <- H'. unfold lt. apply le_n. apply False_ind. \n  (* a = Union x y *)\n  clear a. intros x Hx y Hy z. simpl. intro H. \n  cut(In z (elements x) \\/ In z (elements y)). intro H'. elim H'.\n\n  intro Hx'. unfold lt. apply le_S. apply le_trans with (m:= order x). \n  apply Hx. exact Hx'. apply le_max_l.\n\n  intro Hy'. unfold lt. apply le_S. apply le_trans with (m:= order y).\n  apply Hy. exact Hy'. apply le_max_r. \n\n  apply in_app_or. exact H.\nQed.\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/set2/order_elements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7191300433535273}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (lf2 : natural) : natural :=\n  plus (mult (Succ y) z) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj172_coqofml_uk701b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7191300354538072}}
{"text": "Print bool.\n\nPrint bool_rect.\nPrint bool_ind.\nPrint bool_rec.\n\n(* negate *)\nDefinition match_true := match true with true => false | false => true end.\n\nCheck match_true.\nEval compute in match_true.\n\nDefinition nat_of_bool := bool_rec (fun _ => nat) 1 0.\n\nCheck (nat_of_bool : bool -> nat).\n\nEval compute in (nat_of_bool false).\n\nDefinition dep_of_bool := bool_rec (fun b => match b with true => nat | false => bool end) 1 true.\n\nCheck (dep_of_bool : forall b, match b with true => nat | false => bool end).\n\nEval compute in (dep_of_bool false).\n\nDefinition dep_of_bool2 b : match b with true => nat | false => bool end :=\n  match b with\n      true => 1\n    | false => true\n  end.\n\nGoal dep_of_bool = dep_of_bool2.\nreflexivity.\nQed.\n\nCheck dep_of_bool2.\n\nFrom Ssreflect Require Import ssreflect ssrfun ssrbool.\n\nPrint andb.\nPrint negb.\nPrint orb.\n\nGoal forall a b : bool, ~~ (a && b) = (~~ a) || (~~ b).\nby case; case.\nQed.\n\nFrom Ssreflect Require Import eqtype ssrnat.\n\nLemma ifP_example : forall n : nat, odd (if odd n then n else n.+1).\nProof.\nmove=> n.\ncase: ifP.\n  done.\nmove=> Hn.\nrewrite -addn1.\nrewrite odd_add.\nby rewrite Hn.\nQed.\n\nCheck ifP.\n(* forall (A : Type) (b : bool) (vT vF : A),\n       if_spec b vT vF (b = false) b (if b then vT else vF) *)\nPrint if_spec.\n(* CoInductive if_spec (A : Type) (b : bool) (vT vF : A)\n            (not_b : Prop) : bool -> A -> Set :=\n    IfSpecTrue : b -> if_spec b vT vF not_b true vT\n  | IfSpecFalse : not_b -> if_spec b vT vF not_b false vF\n*)\n(* ifP is the proof that \"if ... is ... then ... else ...\" satifies the if_spec predicate *)\n(*\nupon case analysis, match (a subterm in) the goal with\n\"(if b then vT else vF)\" and generate to goals:\n1. b is replaced with true, b is pushed on the stack\n1. b is replaced with false, not_b is pushed on the stack\n*)\n\nLemma exo23 : forall n : nat, n * n - 1 < n ^ n.\nProof.\nmove=> n.\ncase: (boolP (n == O)).\n  admit.\nmove=> n0.\ncase: (boolP (n == 1)).\n  admit.\nmove=> n1.\nhave [m Hm] : exists m, n = m.+2.\n  admit.\nadmit.\nAbort.\n\nCheck boolP.\n(* forall b1 : bool, alt_spec b1 b1 b1 *)\nCheck (boolP (0 == 1)).\n(* alt_spec (0 == 1) (0 == 1) (0 == 1) *)\nCheck alt_spec.\nPrint alt_spec.\n(* two combinations possible:\n   P b true\n   P b false\n   upon case analysis, there are two branches:\n   - \"(0 == 1)\" is replaced by true and the hypothesis \"(0 == 1) (= true)\" is pushed\n   - \"(0 == 1)\" is replaced by false and the hypothesis \"~~ (0 == 1)\" = \"(0 != 1)\" is pushed\n*)\n", "meta": {"author": "affeldt", "repo": "ssrcoq-kyoto2015", "sha": "e7dbd84e60fd2c24e8b025d60ca663f091800907", "save_path": "github-repos/coq/affeldt-ssrcoq-kyoto2015", "path": "github-repos/coq/affeldt-ssrcoq-kyoto2015/ssrcoq-kyoto2015-e7dbd84e60fd2c24e8b025d60ca663f091800907/ssrbool_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7191249897388878}}
{"text": "Require Import Shared.Base Shared.FiniteTypes TM.Prelim.\nRequire Import Shared.Vectors.Vectors.\n\n(** * Relations *)\n\nDefinition Rel (X : Type) (Y : Type) := X -> Y -> Prop.\n\nDefinition rcomp X Y Z (R : Rel X Y) (S : Rel Y Z) : Rel X Z :=\n  fun x z => exists y, R x y /\\ S y z.\nNotation \"R1 '∘' R2\" := (rcomp R1 R2) (at level 40, left associativity).\nArguments rcomp {X Y Z} (R S) x y /.\n\nDefinition runion X Y (R : Rel X Y) (S : Rel X Y) : Rel X Y := fun x y => R x y \\/ S x y.\nNotation \"R '∪' S\" := (runion R S) (at level 42).\nArguments runion { X Y } ( R S ) x y /.\n\nDefinition rintersection X Y (R : Rel X Y) (S : Rel X Y) : Rel X Y := fun x y => R x y /\\ S x y.\nNotation \"R '∩' S\" := (rintersection R S) (at level 41).\nArguments rintersection { X Y } ( R S ) x y /.\n\n\nDefinition rimplication X Y (R : Rel X Y) (S : Rel X Y) : Rel X Y := fun x y => R x y -> S x y.\nNotation \"R '⊂' S\" := (rimplication R S) (at level 41).\nArguments rimplication { X Y } ( R S ) x y /.\n\nDefinition ignoreParam X Y Z (R : Rel X Z) : Rel X (Y * Z)  := fun x '(y,z) => R x z.\nArguments ignoreParam {X Y Z} ( R ) x y /.\n\nDefinition rUnion (X Y : Type) (F : Type) (R : F -> Rel X Y) : Rel X Y := \n  fun x y => exists f, R f x y.\nNotation \"'⋃_' f R\" := (rUnion (fun f => R)) (at level 50, f at level 9, R at next level, format \"'⋃_' f  R\"). (* Todo: This does not work if f is higher than 9. Why? *)\nArguments rUnion { X Y F } ( R ) x y /.\n\nDefinition rIntersection (X Y : Type) (F : Type) (R : F -> Rel X Y) : Rel X Y := \n  fun x y => forall f, R f x y.\nNotation \"'⋂_' f R\" := (rIntersection (fun f => R)) (at level 50, f at level 9, R at next level, format \"'⋂_' f  R\"). (* Todo: This does not work if f is higher than 9. Why? *)\nArguments rIntersection { X Y F } ( R ) x y /.\n\n\nDefinition surjective X Z (R : Rel X Z) :=\n  forall x, exists y, R x y.\n\nDefinition functional X Z (R : Rel X Z) :=\n  forall x z1 z2, R x z1 -> R x z2 -> z1 = z2.\n\nDefinition subrel X Y (R S: Rel X Y) := (forall x y, R x y -> S x y).\nNotation \"R1 <<=2 R2\" := (subrel R1 R2) (at level 60).\n\nInstance eqrel_pre X Y : PreOrder (subrel (X := X) (Y := Y)).\nProof. constructor; firstorder. Qed.\n\nFact subrel_and X Y (R1 R2 R3 : Rel X Y) :\n  R1 <<=2 R3 \\/ R2 <<=2 R3 -> R1 ∩ R2 <<=2 R3.\nProof. firstorder. Qed.\n\nFact subrel_or X Y (R1 R2 R3 : Rel X Y) :\n  R1 <<=2 R3 /\\ R2 <<=2 R3 -> R1 ∪ R2 <<=2 R3.\nProof. firstorder. Qed.\n\nFact subrel_and2 X Y (R1 R2 R3 R4 : Rel X Y) :\n  R1 <<=2 R3 /\\ R2 <<=2 R4 -> R1 ∩ R2 <<=2 R3 ∩ R4.\nProof. firstorder. Qed.\n\nFact subrel_or2 X Y (R1 R2 R3 R4 : Rel X Y) :\n  R1 <<=2 R3 /\\ R2 <<=2 R4 -> R1 ∪ R2 <<=2 R3 ∪ R4.\nProof. firstorder. Qed.\n\nDefinition eqrel X Y (R S: Rel X Y) := (R <<=2 S /\\ S <<=2 R) .\n\nNotation \"R '=2' S\"  := (eqrel R S) (at level 70).\n\nInstance eqrel_eq X Y : Equivalence (eqrel (X := X) (Y := Y)).\nProof. constructor; firstorder. Qed.\n\n(** ** Relational operators on labelled relations *)\n\n(** Restrict the label of a labelled relation and return an unlabelled relation *)\nDefinition restrict X Y Z (R : Rel X (Y * Z)) f : Rel X Z := (fun x1 x2 => R x1 (f, x2)).\nNotation \"R '|_' f\" := (restrict R f) (at level 30, format \"R '|_' f\").\nArguments restrict { X Y Z } ( R f ) x y /.\n\n(** Introduce a label that is fixed to a value *)\nDefinition rfix X Y Z (R : Rel X Z) (p : Y) : Rel X (Y*Z) := (fun x '(y, z) =>\ny = p /\\ R x z).\nNotation \"R '||_' f\" := (rfix R f) (at level 30, format \"R '||_' f\").\nArguments rfix { X Y Z } ( R p ) x y /.\n\n\n(** ** Relations over Vectors *)\n\nSection Fix_X2.\n  Variable X Y Z : Type.\n  Variable n : nat.\n\n  Local Notation \"'V' Z\" := (Vector.t Z n) (at level 10).\n\n  Definition Eq_in (f : Fin.t n -> Prop) : Rel (V X) (V X) :=\n    fun vx vy => forall i : Fin.t n, f i -> vy[@i] = vx[@i].\n\n  Instance Eq_in_equivalence X (f : Fin.t n -> Prop) :\n    Equivalence (@Eq_in X).\n  Proof.\n    econstructor.\n    - econstructor.\n    - hnf. intros. hnf in *. intros. rewrite <- H; eauto.\n    - hnf. intros. hnf in *. intros. rewrite <- H, <- H0; eauto.\n  Qed.\n\nEnd Fix_X2.\n\nArguments Eq_in { X n } P x y / : rename.\n\n\n(** ** Reflexive transitive closure and relational power *)\nSection Star_Pow.\n  Variable X : Type.\n  Variable R : Rel X X.\n\n  Inductive pow : nat -> Rel X X :=\n  | pow_0 x : pow 0 x x\n  | pow_S k x y z : R x y -> pow k y z -> pow (S k) x z.\n\n  Inductive star : Rel X X :=\n  | starR x : star x x\n  | starC x y z : R x y -> star y z -> star x z.\n\n  Lemma star_trans : transitive _ star.\n  Proof. induction 1; eauto using star. Qed.\n\n  Global Instance star_preorder : PreOrder star.\n  Proof. constructor. constructor. apply star_trans. Qed.\n\n  Lemma pow_plus k1 k2 x y z :\n    pow k1 x y -> pow k2 y z -> pow (k1 + k2) x z.\n  Proof. induction 1; cbn; eauto using pow. Qed.\n\n  Lemma star_pow x y :\n    star x y <-> exists n, pow n x y.\n  Proof.\n    split.\n    - induction 1; firstorder eauto using pow.\n    - intros (n&H). induction H; eauto using star.\n  Qed.\n\nEnd Star_Pow.", "meta": {"author": "uds-psl", "repo": "CoqTM", "sha": "f4d2aab2008e2158e2c7ca88ebb53b42808a0778", "save_path": "github-repos/coq/uds-psl-CoqTM", "path": "github-repos/coq/uds-psl-CoqTM/CoqTM-f4d2aab2008e2158e2c7ca88ebb53b42808a0778/theories/TM/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7191249886598621}}
{"text": "From Coq Require Import Arith.Arith.\n\nFail Fixpoint false_proof (p : nat) : False := false_proof p.\n\nFixpoint sum (n : nat) : nat :=\n  match n with\n  | 0 => 0\n  | S n' => n + (sum n')\n  end.\n\nTheorem summation :\n  forall n, sum n + sum n = n * (n + 1).\nProof.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. apply eq_S. rewrite <- plus_assoc. rewrite <- plus_assoc.\n    apply f_equal2_plus. reflexivity.\n    simpl. rewrite Nat.add_succ_r.\n    apply eq_S. rewrite plus_comm. rewrite <- plus_assoc.\n    rewrite IHn. rewrite Nat.mul_succ_r. rewrite plus_comm. reflexivity.\n  Qed.\n\nFrom Coq Require Import Omega.\n\nTheorem summation_ring :\n  forall n, sum n + sum n = n * (n + 1).\nProof.\n  induction n.\n  - simpl. reflexivity.\n  - simpl.\n    replace (n + sum n + S (n + sum n)) with ((sum n + sum n) + n + S n).\n    rewrite IHn. ring. ring. Qed.\n\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\nDefinition injective {A B} (f : A -> B) : Prop :=\n  forall a b, f a = f b -> a = b.\n\nDefinition FiniteType (A : Type) :=\n  exists f : A -> nat, injective f /\\ exists n, forall a, f a <= n.\n\nTheorem FiniteBool : FiniteType bool.\nProof.\n  unfold FiniteType. exists (fun b : bool => if b then 0 else 1).\n  split.\n  - unfold injective. intros.\n    destruct a; destruct b; auto.\n    + inversion H.\n    + inversion H.\n  - exists 1. intros. destruct a; omega.\n  Qed.\n\nDefinition InfiniteType (A : Type) : Prop :=\n  exists f : nat -> A, injective f.\n\nTheorem InfiniteNat : InfiniteType nat.\nProof.\n  exists (fun x => x). repeat intro. assumption. Qed.\n", "meta": {"author": "mekty2012", "repo": "Coq-Study", "sha": "d8d4d746bb2bbec41e4befbf1aace5ddf14a5b2a", "save_path": "github-repos/coq/mekty2012-Coq-Study", "path": "github-repos/coq/mekty2012-Coq-Study/Coq-Study-d8d4d746bb2bbec41e4befbf1aace5ddf14a5b2a/Intro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.8311430457670241, "lm_q1q2_score": 0.7191249763756}}
{"text": "Load basic.\n\nDefinition app {X} {Y} (f:X->Y) (x:option X) : option Y :=\n  match x with\n    None => None\n  | Some x => Some (f x)\n  end.\n\nFixpoint subst {Pi} (F G:@formula Pi) p :=\n  match F, p with\n    _, [] => Some G\n  | (Not F), 1::p => app Not (subst F G p)\n  | (And F1 F2), 1::p => app (fun f => And f F2) (subst F1 G p)\n  | (And F1 F2), 2::p => app (And F1) (subst F2 G p)\n  | (Or F1 F2), 1::p => app (fun f => Or f F2) (subst F1 G p)\n  | (Or F1 F2), 2::p => app (Or F1) (subst F2 G p)\n  | (To F1 F2), 1::p => app (fun f => To f F2) (subst F1 G p)\n  | (To F1 F2), 2::p => app (To F1) (subst F2 G p)\n  | (Equiv F1 F2), 1::p => app (fun f => Equiv f F2) (subst F1 G p)\n  | (Equiv F1 F2), 2::p => app (Equiv F1) (subst F2 G p)\n  | _, _ => None\n  end.\n\nDefinition negPol p :=\n  match p with\n    TT => FF\n  | FF => TT\n  | NN => NN\n  end.\n\nFixpoint pol {Pi} (F:@formula Pi) p :=\n  match F,p with\n    _, [] => Some TT\n  | (Not F), 1::p => app negPol (pol F p)\n  | (And F1 F2), 1::p => pol F1 p\n  | (And F1 F2), 2::p => pol F2 p\n  | (Or F1 F2), 1::p => pol F1 p\n  | (Or F1 F2), 2::p => pol F2 p\n  | (To F1 F2), 1::p => app negPol (pol F1 p)\n  | (To F1 F2), 2::p => pol F2 p\n  | (Equiv F1 F2), 1::p => Some NN\n  | (Equiv F1 F2), 2::p => Some NN\n  | _,_ => None\n  end.\n\nFixpoint eval {Pi} (A:Pi->bool) (F:@formula Pi) : nat :=\n  match F with\n    Bot => 0\n  | Top => 1\n  | V p => A p\n  | Not F => 1-eval A F\n  | And F G => min (eval A F) (eval A G)\n  | Or F G => max (eval A F) (eval A G)\n  | To F G => max (1-eval A F) (eval A G)\n  | Equiv F G => if eval A F =? eval A G then 1 else 0\n  end.\n\nDefinition sat {Pi} A (F:@formula Pi) : Prop := eval A F = 1.\n\nDefinition satisfiable {Pi} (F:@formula Pi) : Prop :=\n  exists A, sat A F.\n\n", "meta": {"author": "NeuralCoder3", "repo": "automatedreasoning", "sha": "f39c87008d47c8ee0c290e7ce45379a0c984e28e", "save_path": "github-repos/coq/NeuralCoder3-automatedreasoning", "path": "github-repos/coq/NeuralCoder3-automatedreasoning/automatedreasoning-f39c87008d47c8ee0c290e7ce45379a0c984e28e/functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098192, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7190924793880235}}
{"text": "\nDefinition leibniz (a:Type) (x y:a) : Prop :=\n    forall (P:a -> Prop), P x -> P y.\n\n\nArguments leibniz {a} _ _.\n\nNotation \"x == y\" := (leibniz x y) (at level 40).\n\n\nLemma equal_refl : forall (a:Type) (x:a), x == x.\nProof. intros a x. unfold leibniz. intros P H. exact H. Qed.\n\n\nLemma equal_sym : forall (a:Type) (x y:a), x == y -> y == x.\nProof.\n    intros a x y. unfold leibniz. intros H P Hy.\n    remember (fun (y:a) => P y -> P x) as Q eqn:H'.\n    assert (Q y) as Hq. { apply H. rewrite H'. intros Hx. exact Hx. }\n    rewrite H' in Hq. apply Hq. exact Hy. \nQed.\n\nLemma equal_trans : forall (a:Type) (x y z:a), x == y -> y == z -> x == z.\nProof.\n    intros a x y z. unfold leibniz. intros Exy Eyz P Hx.\n    apply Eyz, Exy. exact Hx.\nQed.\n\nLemma leibniz_is_eq : forall (a:Type) (x y:a), x = y <-> x == y.\nProof.\n    intros a x y. split.\n    - intros E. rewrite E. apply equal_refl.\n    - intros E. remember (fun (y:a) => x = y) as Q eqn:H.\n        unfold leibniz in E. apply E. rewrite H. reflexivity.\nQed.\n\n(* setoid paper *)\n\n\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/cat/Leibniz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7190606145580318}}
{"text": "Theorem ex47: forall a : Prop,\n              a <-> a.\nProof.\n  Require Import Coq.Program.Basics.\n  split. apply id. apply id.\nQed.\n\nTheorem ex48: forall a : Prop,\n              a \\/ ~a.\nProof.\n  Require Import Classical.\n  intros. apply (classic a).\nQed.\n\nTheorem ex48_1: forall a b : Prop,\n                (a -> b) \\/ (b -> a).\nProof.\n  intros. apply NNPP. intro. elim H.\n  left. intro. elim H. right. intro.\n  assumption.\nQed.\n\nTheorem ex49: forall a : Prop,\n              ~(a /\\ ~a).\nProof.\n  intros. intro. elim H. intros. contradiction.\nQed.\n\n", "meta": {"author": "limitedeternity", "repo": "PrPr-Labs", "sha": "0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62", "save_path": "github-repos/coq/limitedeternity-PrPr-Labs", "path": "github-repos/coq/limitedeternity-PrPr-Labs/PrPr-Labs-0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62/PrPr-01/Traditional.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8104789109591831, "lm_q1q2_score": 0.7190606032451486}}
{"text": "Require Export Poly.\n\nTheorem silly1:\n  forall (n m o p : nat),\n    n = m -> [n;o] = [n;p] -> [m;o] = [m;p].\nProof.\n  intros n m o p.\n  intros eq1.\n  intros eq2.\n  rewrite <- eq1.\n  apply eq2.\nQed.\n\nTheorem silly2:\n  forall (n m o p : nat),\n    n = m ->\n    (forall (q r :nat), q = r -> [q;o] = [r;p]) ->\n    [n;o] = [m;p].\nProof.\n  intros m n o p.\n  intros eq1.\n  intros eq2.\n  apply eq2.\n  apply eq1.\nQed.\n\nTheorem silly2a:\n  forall n m : nat,\n    (n,n) = (m,m) ->\n    (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n    [n] = [m].\nProof.\n  intros n m.\n  intros eq1 eq2.\n  apply eq2.\n  apply eq1.\nQed.\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 eq1.\n  intros eq2.\n  apply eq1.\n  apply eq2.\nQed.\n\nTheorem silly3_firsttry:\n  forall (n : nat),\n    true = beq_nat n 5 -> beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use apply directly *)\nAbort.\n\nTheorem silly3_firsttry:\n  forall (n : nat),\n    true = beq_nat n 5 -> beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  symmetry.\n  simpl.\n  apply H.\nQed.\n\nTheorem rev_exercise1:\n  forall l l' : list nat,\n    l = rev l' -> l' = rev l.\nProof.\n  intros l l'.\n  intros H.\n  rewrite -> H.\n  symmetry.\n  apply rev_involutive.\nQed.\n\nExample trans_eq_example:\n  forall (a b c d e f : nat),\n    [a;b] = [c;d] ->\n    [c;d] = [e;f] ->\n    [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2.\n  rewrite -> eq1.\n  rewrite -> eq2.\n  reflexivity.\nQed.\n\nTheorem trans_eq:\n  forall (X : Type) (n m o : X),\n    n = m -> m = o -> n = o.\nProof.\n  intros X n m o.\n  intros eq1 eq2.\n  rewrite -> eq1.\n  rewrite -> eq2.\n  reflexivity.\nQed.\n\nExample trans_eq_example':\n  forall (a b c d e f : nat),\n    [a;b] = [c;d] ->\n    [c;d] = [e;f] ->\n    [a;b] = [e;f].\nProof.\n  intros a b c d e f.\n  intros eq1 eq2.\n  apply trans_eq with (m := [c;d]).\n  apply eq1.\n  apply eq2.\nQed.\n\nExample trans_eq_exercise:\n  forall (m n o p : nat),\n    m = (minustwo o) ->\n    (n + p) = m ->\n    (n + p) = (minustwo o).\nProof.\n  intros m n o p.\n  intros eq1 eq2.\n  apply trans_eq with (m := (n + p)).\n  reflexivity.\n  rewrite -> eq2.\n  apply eq1.\nQed.\n\nTheorem eq_add_S:\n  forall n m : nat,\n    S n = S m -> n = m.\nProof.\n  intros n m.\n  intros eq.\n  inversion eq.\n  reflexivity.\nQed.\n\nTheorem silly4:\n  forall n m : nat,\n    [n] = [m] -> n = m.\nProof.\n  intros n m.\n  intros H.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem silly5:\n  forall n m o : nat,\n    [n;m] = [o;o] -> [n] = [m].\nProof.\n  intros n m o.\n  intros H.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem sillyex1:\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = z :: j ->\n    y :: l = x :: j ->\n    x = y.\nProof.\n  intros X x y z l j.\n  intros eq1 eq2.\n  inversion eq2.\n  reflexivity.\nQed.\n\nTheorem silly6:\n  forall n : nat,\n    S n = O -> 2 + 2 = 5.\nProof.\n  intros n H.\n  inversion H.\nQed.\n\nTheorem silly7:\n  forall n m : nat,\n    false = true -> [n] = [m].\nProof.\n  intros n m H.\n  inversion H.\nQed.\n\nExample sillyex2:\n  forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] ->\n    y :: l = z :: j ->\n    x = z.\nProof.\n  intros X x y z l j.\n  intros eq1 eq2.\n  inversion eq1.\nQed.\n\nTheorem f_equal:\n  forall (A B : Type) (f : A -> B) (x y : A),\n    x = y -> f x = f y.\nProof.\n  intros A B f x y.\n  intros H.\n  rewrite H.\n  reflexivity.\nQed.\n\nTheorem beq_nat_0_l:\n  forall n,\n    beq_nat 0 n = true -> n = 0.\nProof.\n  intros n H.\n  induction n as [| n'].\n  reflexivity.\n  inversion H.\nQed.\n\nTheorem beq_nat_0_r:\n  forall n,\n    beq_nat n 0 = true -> n = 0.\nProof.\n  intros n H.\n  induction n as [| n'].\n  reflexivity.\n  inversion H.\nQed.\n\nTheorem S_inj:\n  forall (n m : nat) (b : bool),\n    beq_nat (S n) (S m) = b -> beq_nat n m = b.\nProof.\n  intros n m b.\n  intros H.\n  simpl in H.\n  apply H.\nQed.\n\nTheorem silly3':\n  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.\n  intros eq1 eq2.\n  symmetry in eq2.\n  apply eq1 in eq2.\n  symmetry in eq2.\n  apply eq2.\nQed.\n\nTheorem plus_n_n_O:\n  forall n,\n    n + n = 0 -> n = 0.\nProof.\n  intros n.\n  induction n as [| n'].\n  simpl. reflexivity.\n  intros H.\n  inversion H.\nQed.\n\nTheorem plus_n_n_injective:\n  forall n m,\n    n + n = m + m -> n = m.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n' = O\".\n    simpl.\n    intros m H.\n    symmetry in H.\n    apply plus_n_n_O in H.\n    symmetry.\n    apply H.\n  Case \"n' = S n'\".\n    intros m.\n    destruct m.\n      SCase \"m = O\".\n      intros H.\n      inversion H.\n      SCase \"m = S m\".\n      simpl.\n      intros H.\n      inversion H.\n      rewrite <- plus_n_Sm in H1.\n      rewrite <- plus_n_Sm in H1.\n      inversion H1.\n      apply IHn' in H2.\n      rewrite -> H2.\n      reflexivity.\nQed.\n\nTheorem double_injective:\n  forall n m,\n    double n = double m -> n = m.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = O\".\n    simpl.\n    intros m H.\n    destruct m as [| m'].\n    SCase \"m = O\".\n      reflexivity.\n    SCase \"m = S m'\".\n      inversion H.\n  Case \"n = S n'\".\n    intros m H.\n    destruct m as [| m'].\n      SCase \"m = O\".\n        inversion H.\n      SCase \"m = S m'\".\n        apply f_equal.\n        apply IHn'.\n        inversion H.\n        reflexivity.\nQed.\n\nTheorem beq_nat_true:\n  forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = O\".\n    intros m H.\n    destruct m as [| m'].\n    SCase \"m = O\".\n      reflexivity.\n    SCase \"m = S m'\".\n      inversion H.\n  Case \"n = S n'\".\n    intros m H.\n    destruct m as [| m'].\n    SCase \"m = O\".\n      inversion H.\n    SCase \"m = S m'\".\n      apply f_equal.\n      apply IHn'.\n      inversion H.\n      reflexivity.\nQed.\n\nTheorem double_injective_take2_FAILED:\n  forall n m,\n     double n = double m -> n = m.\nProof.\n  intros n m. induction m as [| m'].\n  Case \"m = O\". simpl. intros eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq.\n  Case \"m = S m'\". intros eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\". apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\nTheorem double_injective_take2:\n  forall n m,\n    double n = double m -> n = m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m as [| m'].\n  Case \"m = O\".\n    intros n H.\n    destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion H.\n  Case \"m = S m'\".\n    intros n H.\n    destruct n as [| n'].\n    SCase \"n = O\". inversion H.\n    SCase \"n = S n'\".\n      apply f_equal.\n      apply IHm'.\n      inversion H.\n      reflexivity.\nQed.\n    \nTheorem length_snoc':\n  forall (X : Type) (v : X) (l : list X) (n : nat),\n    length l = n -> length (snoc l v) = S n.\nProof.\n  intros X v l.\n  induction l as [| v' l'].\n  Case \"l = []\".\n    intros n H.\n    rewrite <- H.\n    reflexivity.\n  Case \"l = v' :: l'\".\n    intros n H.\n    simpl.\n    destruct n as [| n'].\n    SCase \"n = O\".\n      inversion H.\n    SCase \"n = S n'\".\n      apply f_equal.\n      apply IHl'.\n      inversion H.\n      reflexivity.\nQed.\n\nTheorem index_after_last:\n  forall (n : nat) (X : Type) (l : list X),\n    length l = n -> index n l = None.\nProof.\n  intros n X l.\n  generalize dependent n.\n  induction l as [| v' l'].\n  Case \"l = []\".\n    intros n H.\n    simpl. reflexivity.\n  Case \"l = v' :: l'\".\n    intros n H.\n    destruct n.\n    SCase \"n = O\".\n      inversion H.\n    SCase \"n = S n\".\n      simpl.\n      apply IHl'.\n      inversion H.\n      reflexivity.\nQed.\n\nTheorem length_snoc''':\n  forall (n : nat) (X : Type) (v : X) (l : list X),\n    length l = n -> length (snoc l v) = S n.\nProof.\n  intros n X v l.\n  generalize dependent n.\n  induction l as [| v' l'].\n  Case \"l = []\".\n    intros n H.\n    simpl. \n    destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". \n      inversion H.\n  Case \"l = v' :: l'\".\n    intros n H.\n    simpl.\n    destruct n as [| n'].\n    SCase \"n = O\".\n      inversion H.\n    SCase \"n = S n'\".\n      apply f_equal.\n      apply IHl'.\n      inversion H.\n      reflexivity.\nQed.\n\nTheorem app_length_cons:\n  forall (X : Type) (l1 l2 : list X) (x : X) (n : nat),\n    length (l1 ++ (x :: l2)) = n ->\n    S (length (l1 ++ l2)) = n.\nProof.\n  intros X l1 l2 x.\n  induction l1 as [| v' l1'].\n  Case \"l1 = []\".\n    intros n H.\n    destruct n as [| n'].\n    SCase \"n' = O\".\n      inversion H.\n    SCase \"n' = S n'\".\n      simpl in H.\n      simpl.\n      apply H.\n  Case \"l1 = v' :: l1'\".\n    intros n H.\n    destruct n as [| n'].\n    SCase \"n' = O\".\n      inversion H.\n    SCase \"n' = S n'\".\n      simpl.\n      apply f_equal.\n      apply IHl1'.\n      inversion H.\n      reflexivity.\nQed.\n\nTheorem length_app:\n  forall (X : Type) (v : X) (l1 l2 : list X),\n    length (l1 ++ v :: l2) = S (length (l1 ++ l2)).\nProof.\n  intros X v l1 l2.\n  induction l1 as [| v' l1'].\n  Case \"l1 = []\".\n    simpl. reflexivity.\n  Case \"l1 = v' :: l1'\".\n    simpl.\n    apply f_equal.\n    apply IHl1'.\nQed.\n\nTheorem app_length_twice:\n  forall (X : Type) (n : nat) (l : list X),\n    length l = n -> length (l ++ l) = n + n.\nProof.\n  intros X n l.\n  generalize dependent n.\n  induction l as [| v' l'].\n  Case \"l = []\".\n    intros n H.\n    destruct n as [| n'].\n    SCase \"n = O\".\n      simpl. reflexivity.\n    SCase \"n = S n'\".\n      inversion H.\n  Case \"l = v' :: l'\".\n    intros n H.\n    destruct n as [| n'].\n    SCase \"n = O\".\n      inversion H.\n    SCase \"n = S n'\".\n      simpl.\n      rewrite -> length_app.\n      apply f_equal.\n      inversion H.\n      rewrite -> H1.\n      apply IHl' in H1.\n      rewrite -> H1.\n      rewrite -> plus_n_Sm.\n      reflexivity.\nQed.\n\nTheorem double_induction:\n  forall (P : nat -> nat -> Prop),\n    P 0 0 ->\n    (forall m, P m 0 -> P (S m) 0) ->\n    (forall n, P 0 n -> P 0 (S n)) ->\n    (forall m n, P m n -> P (S m) (S n)) ->\n    forall m n, P m n.\nProof.\n  intros P eq1 eq2 eq3 eq4 m.\n  induction m as [| m'].\n  Case \"m = O\".\n    intros n.\n    induction n as [| n'].\n    SCase \"n = O\".\n      apply eq1.\n    SCase \"n = S n'\".\n      apply eq3.\n      apply IHn'.\n  Case \"m = S m'\".\n    intros n.\n    induction n as [| n'].\n    SCase \"n = O\".\n      apply eq2.\n      apply IHm'.\n    SCase \"n = S n'\".\n      apply eq4.\n      apply IHm'.\nQed.\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n       else false.\n\nTheorem sillyfun_false:\n  forall n : nat,\n    sillyfun n = false.\nProof.\n  intros n.\n  unfold sillyfun.\n  destruct (beq_nat n 3).\n  Case \"beq_nat n 3 = true\".\n    reflexivity.\n  Case \"beq_nat n 3 = false\".\n    destruct (beq_nat n 5).\n      SCase \"beq_nat n 5 = true\".\n        reflexivity.\n      SCase \"beq_nat n 5 = false\".\n        reflexivity.\nQed.\n\nTheorem override_shadow:\n  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  intros X x1 x2 k1 k2 f.\n  unfold override.\n  destruct (beq_nat k1 k2).\n  Case \"beq_nat k1 k2 = true\".\n    reflexivity.\n  Case \"beq_nat k1 k2 = false\".\n    reflexivity.\nQed.\n\nTheorem combine_split:\n  forall X Y (l : list (X * Y)) l1 l2,\n    split l = (l1, l2) -> combine l1 l2 = l.\nProof.\n  intros X Y l.\n  induction l as [| [x y] l'].\n  Case \"l = []\".\n    intros l1 l2 H.\n    inversion H.\n    reflexivity.\n  Case \"l = v' :: l'\".\n    intros l1 l2 H.\n    simpl in H.\n    destruct (split l') as [lx ly].\n    SCase \"split l' = (lx,ly)\".\n      inversion H.\n      simpl.\n      rewrite -> IHl'.\n      reflexivity.\n      reflexivity.\nQed.\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n       else false.\n\nTheorem sillyfun1_odd_FAILED:\n  forall n : nat,\n    sillyfun1 n = true ->\n    oddb n = true.\nProof.\n  intros n H.\n  unfold sillyfun1 in H.\n  destruct (beq_nat n 3).\nAbort.\n\nTheorem sillyfun1_odd:\n  forall n : nat,\n    sillyfun1 n = true ->\n    oddb n = true.\nProof.\n  intros n eq.\n  unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n    Case \"e3 = true\".\n      apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3.\n      reflexivity.\n    Case \"e3 = false\".\n      destruct (beq_nat n 5) eqn:Heqe5.\n      SCase \"e5 = true\".\n        apply beq_nat_true in Heqe5.\n        rewrite -> Heqe5.\n        reflexivity.\n      SCase \"e5 = false\".\n        inversion eq.\nQed.\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 (f b) eqn:H.\n  Case \"f b = true\".\n    destruct b.\n    SCase \"b = true\".\n      rewrite -> H.\n      symmetry.\n      rewrite -> H.\n      reflexivity.\n    SCase \"b = false\".\n      destruct (f true) eqn:H'.\n        rewrite -> H'.\n        reflexivity.\n\n        rewrite -> H.\n        reflexivity.\n  Case \"f b = false\".\n    destruct b.\n    SCase \"b = true\".\n      destruct (f false) eqn:H'.\n        symmetry.\n        rewrite -> H.\n        reflexivity.\n\n        rewrite -> H'.\n        reflexivity.\n    SCase \"b = false\".\n      destruct (f false) eqn:H'.\n        inversion H.\n\n        rewrite -> H'.\n        reflexivity.\nQed.\n\nTheorem override_same:\n  forall (X : Type) x1 k1 k2 (f : nat -> X),\n    f k1 = x1 -> (override f k1 x1) k2 = f k2.\nProof.\n  intros X x1 k1 k2 f H.\n  unfold override.\n  destruct (beq_nat k1 k2) eqn:eq.\n    apply beq_nat_true in eq.\n    rewrite eq in H.\n    rewrite -> H.\n    reflexivity.\n    reflexivity.\nQed.\n\nTheorem beq_nat_sym:\n  forall n m : nat,\n    beq_nat n m = beq_nat m n.\nProof.\n  intros n m.\n  destruct (beq_nat n m) eqn:H.\n  Case \"beq_nat n m = true\".\n    inversion H.\n    apply beq_nat_true in H.\n    rewrite -> H.\n    reflexivity.\n  Case \"beq_nat n m = false\".\n    destruct n.\n    SCase \"n = O\".\n      destruct m.\n      SSCase \"m = O\".\n        inversion H.\n      SSCase \"m = S m\".\n        simpl. reflexivity.\n    SCase \"n = S n\".\n      destruct m.\n      SSCase \"m = O\".\n        simpl. reflexivity.\n      SSCase \"m = S m\".\nAbort.\n\nTheorem beq_nat_sym:\n  forall n m : nat,\n    beq_nat n m = beq_nat m n.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = O\".\n    intros m.\n    destruct m.\n      reflexivity.\n      reflexivity.\n  Case \"n = S n\".\n    intros m.\n    destruct m.\n      reflexivity.\n      simpl.\n      rewrite -> IHn'.\n      reflexivity.\nQed.\n", "meta": {"author": "abm", "repo": "software-foundations", "sha": "fcc4a39b688893ffd1744bff851590d28ddf8d68", "save_path": "github-repos/coq/abm-software-foundations", "path": "github-repos/coq/abm-software-foundations/software-foundations-fcc4a39b688893ffd1744bff851590d28ddf8d68/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7190493339090916}}
{"text": "(* Hand is defined inductively *)\nInductive Hand : Set := Gu | Tyoki | Pa.\n\n(* Check type of Hand *)\nCheck Hand.\n\n(* Show definitions *)\nPrint Hand.\nPrint Hand_ind.\n\n(* Function definition *)\nInductive win : Hand -> Hand -> Prop :=\n| gu_win_tyoki : win Gu Tyoki\n| tyoki_win_pa : win Tyoki Pa\n| pa_win_gu : win Pa Gu.\n\nHint Constructors win.\n(* Winning hand *)\nDefinition winning_hand(s:Hand) : { a | win a s }.\nProof.\ninduction s.\n exists Pa. apply pa_win_gu.\n exists Gu. auto.\n exists Tyoki; auto.\nDefined.\n\n(* Result = hand & proof *)\nEval compute in (winning_hand Gu).\n(* Hand *)\nEval compute in (proj1_sig (winning_hand Gu)).\n(* Proof *)\nEval compute in (proj2_sig (winning_hand Gu)).\n(* Extract as OCaml program *)\nExtraction winning_hand.\n\n(* Winning hand is unique *)\nTheorem winning_hand_unique : forall a b c, \n  win a c -> win b c -> a = b.\nProof.\nintros a b c Hac Hbc. induction c.\n inversion Hac. inversion Hbc. reflexivity.\n inversion Hac. inversion Hbc. auto.\n inversion Hac; inversion Hbc; auto.\nQed.\n\n(* Import List module *)\nRequire Import List.\n\n(* Show definition of list type *)\nPrint list.\n\n(* Sample of list *)\nCheck (1::2::nil).\n\nCheck list_ind.\n\n(* Define append function *)\nFixpoint append{A:Type}(xs ys:list A):=\nmatch xs with\n| nil => ys\n| x::xs' => x::(append xs' ys)\nend.\n\n(* Evaluation *)\nEval compute in (append (1::2::nil) (3::4::nil)).\n\n(* Definition of nat *)\nPrint nat.\nPrint plus.\n\n(* Write your length function *)\nFixpoint len{A:Type}(xs:list A):nat :=\nmatch xs with\n| nil => 0\n| _::xs' => S (len xs')\nend.\n\n(* Should be 3 *)\nEval compute in (len (1::2::3::nil)).\n\nTheorem len_append: forall (A:Type)(xs ys:list A),\n  len (append xs ys) = plus (len xs) (len ys).  \nProof.\nintro A.\ninduction xs.\n simpl.\n intro ys. auto.\n\n intro ys. simpl.\n erewrite IHxs.\n auto.\nQed.\n\nFixpoint reverse{A:Type}(xs:list A):list A :=\nmatch xs with\n| nil => nil\n| x::xs' => append (reverse xs') (x::nil)\nend.\n\n(* Evaluate *)\nEval compute in (reverse (1::2::3::nil)).\n(* reverse twice *)\nEval compute in (reverse (reverse (1::2::3::nil))).\n\nLemma append_right_nil: forall (A:Type)(xs:list A),\n  append xs nil = xs.\nProof.\ninduction xs.\n auto.\n simpl. erewrite IHxs. auto.\nQed.\n\nLemma append_append : forall (A:Type)(xs ys zs:list A),\n  append (append xs ys) zs = append xs (append ys zs).\nProof.\ninduction xs.\n simpl. intros; auto.\n\n simpl. intros. erewrite IHxs. auto.\nQed. \n\nLemma reverse_append : forall (A:Type)(xs ys:list A),\n  reverse (append xs ys) = append (reverse ys) (reverse xs).\nProof.\ninduction xs.\n simpl. intro.\n erewrite append_right_nil. auto.\n\n simpl. intro ys.\n erewrite IHxs.\n erewrite append_append.\n auto.\nQed.\n\nTheorem reverse_reverse: forall (A:Type)(xs:list A),\n  reverse (reverse xs) = xs.\nProof.\ninduction xs.\n simpl. auto.\n simpl. erewrite reverse_append. erewrite IHxs.\n simpl. auto.\nQed.\n\n\n\n\nFixpoint rev2{A:Type}(xs ys:list A):list A :=\nmatch xs with\n| nil => ys\n| x::xs' => rev2 xs' (x::ys)\nend.\n\nLemma app_r_head: forall (A: Type)(a: A)(xs ys: list A),\n  append xs (a :: ys) = append (append xs (a :: nil)) ys.\nProof.\n  intros A a.\n  induction xs.\n    intro ys.\n    simpl.\n    reflexivity.\n    \n    intro ys.\n    simpl.\n    rewrite IHxs.\n    reflexivity.\nQed.\n\nLemma rev2_app: forall (A: Type)(xs ys: list A),\n  append (rev2 xs nil) ys = rev2 xs ys.\nProof.\n  induction xs.\n    simpl.\n    intro ys.\n    reflexivity.\n    \n    intro ys.\n    simpl.\n    rewrite <- (IHxs (a::ys)).\n    rewrite <- (IHxs (a::nil)).\n    rewrite <- app_r_head.\n    reflexivity.\nQed.\n\nTheorem rev_eq_rev2: forall (A: Type)(xs: list A),\n  reverse xs = rev2 xs nil.\nProof.\n  intro A.\n  induction xs.\n    simpl.\n    reflexivity.\n    \n    simpl.\n    erewrite IHxs.\n    rewrite rev2_app.\n    reflexivity.\nQed.\n", "meta": {"author": "rf0444", "repo": "coq", "sha": "ea26e698cd68ccc051a309b856c7724181be6aae", "save_path": "github-repos/coq/rf0444-coq", "path": "github-repos/coq/rf0444-coq/coq-ea26e698cd68ccc051a309b856c7724181be6aae/coqart_20130817.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7190493192483145}}
{"text": "Require Import Bool Arith List CpdtTactics.\nSet Implicit Arguments.\n\n(*\nSet Asymetric Patterns. (* no impact before Coq version 8.5 *)\n*) \n\nInductive binop : Set := Plus | Times.\n\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp.\n\n(*\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n  match b with\n  | Plus => plus\n  | Times => mult\n  end.\n*)\n\n(*\nDefinition binopDenote : binop -> nat -> nat -> nat := fun (b : binop) =>\n  match b with\n  | Plus => plus\n  | Times => mult\n  end.\n*)\n\nDefinition binopDenote := fun b =>\n  match b with\n    | Plus => plus\n    | Times => mult\n  end.\n\nFixpoint expDenote (e : exp) : nat :=\n  match e with\n    | Const n => n\n    | Binop b e1 e2 => (binopDenote b) (expDenote e1 ) (expDenote e2 )\n  end.\n\nDefinition exp1 : exp := Const 42.\nDefinition exp2 : exp := Binop Plus (Const 2) (Const 2).\nDefinition exp3 : exp := Binop Times exp2 (Const 7).\n\n(*\nEval simpl in expDenote exp1.\nEval simpl in expDenote exp2.\nEval simpl in expDenote exp3.\n*)\n\n\n(*\nEval simpl in expDenote(Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n*)\n\nInductive instr : Set :=\n| iConst : nat -> instr\n| iBinop : binop -> instr.\n\nDefinition prog := list instr.\nDefinition stack := list nat.\n\nDefinition instrDenote (i : instr) (s : stack) : option stack :=\n  match i with\n    | iConst n => Some (n :: s)\n    | iBinop b =>\n      match s with\n        | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')\n        | _ => None\n      end\n  end.\n\nFixpoint progDenote (p : prog) (s : stack) : option stack :=\n  match p with\n    | nil     => Some s\n    | i :: p' =>\n      match instrDenote i s with\n        | None    => None\n        | Some s' => progDenote p' s'\n      end\n    end.\n\nFixpoint compile (e : exp) : prog :=\n  match e with\n    | Const n       => iConst n :: nil\n    | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil\n  end.\n\n(*\nEval simpl in compile exp1. (* Const 42 *)\nEval simpl in compile exp2. (* Binop Plus (Const 2) (Const 2) *)\nEval simpl in compile exp3. (* Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7) *)\n*)\n\nDefinition prog1 : prog := compile exp1.\nDefinition prog2 : prog := compile exp2.\nDefinition prog3 : prog := compile exp3.\n\n(*\nEval simpl in progDenote prog1 nil.\nEval simpl in progDenote prog2 nil.\nEval simpl in progDenote prog3 nil.\n*)\n\n\nTheorem compile_correct : forall e, \n  progDenote (compile e) nil = Some (expDenote e :: nil).\n\n\nAbort.\n\n\nLemma compile_correct' : forall e p s,\n  progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n\n  induction e.\n  intros.\n  unfold compile.\n  unfold expDenote.\n  unfold progDenote at 1.\n  simpl.\n  fold progDenote.\n  reflexivity.\n\n  intros.\n  unfold compile.\n  fold compile.\n  unfold expDenote.\n  fold expDenote.\n(*\nCheck app_assoc_reverse.\nCheck app_assoc.\nSearchRewrite((_++_)++_).\n*)\n  rewrite app_assoc_reverse.\n  rewrite IHe2.\n  rewrite app_assoc_reverse.\n  rewrite IHe1.\n  unfold progDenote at 1.\n  simpl.\n  fold progDenote. \n  reflexivity.\n\nAbort.\n\nLemma compile_correct' : forall e p s,\n  progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n\n  induction e; crush.\nQed.\n\nTheorem compile_correct : forall e, \n  progDenote (compile e) nil = Some (expDenote e :: nil).\n \n  intros.\n\n(*\nCheck app_nil_end.\n*)\n  rewrite (app_nil_end(compile e)).\n  rewrite compile_correct'.\n  unfold progDenote. (* actually this is optional, as reflexivity will check *)\n  reflexivity.\nQed.\n\nInductive type : Set := Nat | Bool.\n\nInductive tbinop : type -> type -> type -> Set :=\n| TPlus : tbinop Nat Nat Nat\n| TTimes : tbinop Nat Nat Nat\n| TEq : forall t, tbinop t t Bool\n| TLt : tbinop Nat Nat Bool.\n\nInductive texp : type -> Set :=\n| TNConst : nat -> texp Nat\n| TBConst : bool -> texp Bool\n| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\nDefinition typeDenote (t : type) : Set :=\n  match t with\n    | Nat => nat\n    | Bool => bool\n  end.\n\nDefinition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b with\n    | TPlus => plus\n    | TTimes => mult\n    | TEq Nat => beq_nat\n    | TEq Bool => eqb\n    | TLt => leb\n  end.\n\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n    | TNConst n => n\n    | TBConst b => b\n    | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\nDefinition texp1: texp Nat  := TNConst 42.\nDefinition texp2: texp Bool := TBConst false.\nDefinition texp3: texp Bool := TBConst true.\nDefinition texp_2p2         := TBinop TPlus (TNConst 2) (TNConst 2).\nDefinition texp_7           := TNConst 7.\nDefinition texp4: texp Nat  := TBinop TTimes texp_2p2 texp_7.\nDefinition texp5: texp Bool := TBinop (TEq Nat) texp_2p2 texp_7.\nDefinition texp6: texp Bool := TBinop TLt texp_2p2 texp_7.\n\n\n\n(*\nEval simpl in texpDenote texp1. \nEval simpl in texpDenote texp2. \nEval simpl in texpDenote texp3. \nEval simpl in texpDenote texp4. \nEval simpl in texpDenote texp5. \nEval simpl in texpDenote texp6. \n*)\n\nDefinition tstack := list type.\n\nInductive tinstr : tstack -> tstack -> Set :=\n| TiNConst : forall s, nat -> tinstr s (Nat :: s)\n| TiBConst : forall s, bool -> tinstr s (Bool :: s)\n| TiBinop : forall arg1 arg2 res s, tbinop arg1 arg2 res\n  -> tinstr (arg1 :: arg2 :: s) (res :: s).\n\nInductive tprog : tstack -> tstack -> Set :=\n| TNil : forall s, tprog s s\n| TCons : forall s1 s2 s3,\n  tinstr s1 s2 -> tprog s2 s3 -> tprog s1 s3.\n\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n    | nil => unit\n    | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n    | TiNConst _ n => fun s => (n, s)\n    | TiBConst _ b => fun s => (b, s)\n    | TiBinop _ _ _ _ b => fun s =>\n      let '(arg1, (arg2, s')) := s in\n        ((tbinopDenote b) arg1 arg2, s')\n  end.\n\nFixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n    | TNil _ => fun s => s\n    | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\n\nFixpoint tconcat ts ts' ts''(p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n    | TNil _ => fun p' => p'\n    | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=\n  match e with\n    | TNConst n => TCons (TiNConst _ n) (TNil _)\n    | TBConst b => TCons (TiBConst _ b) (TNil _)\n    | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)\n      (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\n(*\nPrint tcompile.\n\nEval simpl in tprogDenote (tcompile texp1 nil) tt.\nEval simpl in tprogDenote (tcompile texp2 nil) tt.\nEval simpl in tprogDenote (tcompile texp3 nil) tt.\nEval simpl in tprogDenote (tcompile texp4 nil) tt.\nEval simpl in tprogDenote (tcompile texp5 nil) tt.\nEval simpl in tprogDenote (tcompile texp6 nil) tt.\n*)\n\n\nTheorem tcompile_correct : forall t (e : texp t),\n  tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\n\nAbort.\n\nLemma tcompile_correct' : \n  forall (t : type) (e : texp t) (ts : tstack) (s : vstack ts),\n    tprogDenote (tcompile e ts) s = (texpDenote e, s).\n\n  induction e; crush.\n\nAbort.\n\nLemma tconcat_correct : \n  forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'') (s : vstack ts),\n  tprogDenote (tconcat p p') s = tprogDenote p' (tprogDenote p s).\n\n  induction p; crush.\nQed.\n\nHint Rewrite tconcat_correct.\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n  tprogDenote (tcompile e ts) s = (texpDenote e, s).\n\n  induction e; crush.\nQed. \n\nExtraction tcompile.\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/StackMachine-test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7190493176193391}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(*                                                                          *)\n(* Jean-Francois.Monin@lannion.cnet.fr                                      *)\n(* December 1994, Coq V5.10                                                 *)\n(*                                                                          *)\n(****************************************************************************)\n(*                                  tree.v                                  *)\n(****************************************************************************)\n\nInductive tree : Set :=\n  | leaf : nat -> tree\n  | node : tree -> tree -> tree.\n\nSection func_pred.\n\nVariable bin : nat -> nat -> nat.\n\nFixpoint ext_morph (t : tree) : nat :=\n  match t return nat with\n  | leaf n => n\n  | node t1 t2 => bin (ext_morph t1) (ext_morph t2)\n  end.\n\nInductive Pext_morph : tree -> nat -> Prop :=\n  | Pl : forall n : nat, Pext_morph (leaf n) n\n  | Pn :\n      forall (t1 t2 : tree) (n1 n2 : nat),\n      Pext_morph t1 n1 ->\n      Pext_morph t2 n2 -> Pext_morph (node t1 t2) (bin n1 n2).\nHint Resolve Pl Pn.\n\nTheorem Pem_em : forall t : tree, Pext_morph t (ext_morph t).\nsimple induction t; simpl in |- *; auto.\nQed.\n\nTheorem em_eq_Pem :\n forall (t : tree) (n : nat), n = ext_morph t -> Pext_morph t n.\nintros t n Heq; rewrite Heq; apply Pem_em.\nQed.\n\nTheorem Pem_em_eq :\n forall (t : tree) (n : nat), Pext_morph t n -> n = ext_morph t.\nsimple induction 1.\n   auto.\n   intros t1 t2 n1 n2 HPem1 Heq1 HPem2 Heq2.\n      rewrite Heq1; rewrite Heq2; auto.\nQed.\n\n\nEnd func_pred.\n\n(* ============================== *)\n", "meta": {"author": "coq-contribs", "repo": "continuations", "sha": "52115376f182175321b0d9fac9ad7d61db51ddb0", "save_path": "github-repos/coq/coq-contribs-continuations", "path": "github-repos/coq/coq-contribs-continuations/continuations-52115376f182175321b0d9fac9ad7d61db51ddb0/weight/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7190493062165123}}
{"text": "(***************************************************************************\n* Generic Variables for Programming Language Metatheory                    *\n* Brian Aydemir & Arthur Charguéraud, July 2007, Coq v8.1      é            *\n***************************************************************************)\n\nSet Implicit Arguments.\nRequire Import List Max Omega OrderedType OrderedTypeEx.\nRequire Import Lib_Tactic Lib_ListFacts Lib_FinSet Lib_FinSetImpl.\nRequire Export Lib_ListFactsMore.\n\n(* ********************************************************************** *)\n(** * Abstract Definition of Variables *)\n\nModule Type VARIABLES.\n\n(** We leave the type of variables abstract. *)\n\nParameter var : Set.\n\n(** This type is inhabited. *)\n\nParameter var_default : var.\n\n(** Variables are ordered. *)\n\nDeclare Module Var_as_OT : UsualOrderedType with Definition t := var.\n\n(** We can form sets of variables. *)\n\nDeclare Module Import VarSet : FinSet with Module E := Var_as_OT.\nLocal Open Scope set_scope.\n\nDefinition vars := VarSet.S.t.\n\n(** Finally, we have a means of generating fresh variables. *)\n\nParameter var_generate : vars -> var.\nParameter var_generate_spec : forall E, (var_generate E) \\notin E.\nParameter var_fresh : forall (L : vars), { x : var | x \\notin L }.\n\n(** Variables can be enumerated *)\n\nParameter var_of_Z : Z -> var.\nParameter Z_of_var : var -> Z.\n\nEnd VARIABLES.\n\n\n(* ********************************************************************** *)\n(** * Concrete Implementation of Variables *)\n\nModule Variables : VARIABLES.\n\nLocal Open Scope Z_scope.\n\nDefinition var := Z.\n\nDefinition var_default : var := 0.\n\nDefinition var_of_Z x : var := x.\nDefinition Z_of_var x : Z := x.\n\nModule Var_as_OT : UsualOrderedType with Definition t := var := Z_as_OT.\n\nModule Import VarSet : FinSet with Module E := Var_as_OT :=\n  Lib_FinSetImpl.Make Var_as_OT.\n\nLocal Open Scope set_scope.\n\nDefinition vars := VarSet.S.t.\n\nLemma max_lt_l :\n  forall (x y z : Z), x <= y -> x <= Z.max y z.\nProof.\n  intros.\n  apply (Z.le_trans _ _ _ H).\n  apply Z.le_max_l.\nQed.\n\nLemma finite_nat_list_max : forall (l : list Z),\n  { n : Z | forall x, In x l -> x <= n }.\nProof.\n  induction l as [ | l ls IHl ].\n  exists 0; intros x H; inversion H.\n  inversion IHl as [x H].\n  exists (Z.max x l); intros y J; simpl in J; inversion J.\n    subst; apply Z.le_max_r.\n    assert (y <= x); auto using max_lt_l.\nQed.\n\nLemma finite_nat_list_max' : forall (l : list Z),\n  { n : Z | ~ In n l }.\nProof.\n  intros l.\n  case (finite_nat_list_max l); intros x H.\n  exists (x+1).\n  intros J.\n  assert (K := H _ J); omega.\nQed.\n\nDefinition var_generate (L : vars) : var :=\n  proj1_sig (finite_nat_list_max' (S.elements L)).\n\nLemma var_generate_spec : forall E, (var_generate E) \\notin E.\nProof.\n  unfold var_generate. intros E.\n  destruct (finite_nat_list_max' (S.elements E)) as [n pf].\n  simpl. intros a.\n  assert (In n (S.elements E)). rewrite <- InA_iff_In.\n  auto using S.elements_1.\n  intuition.\nQed.\n\nLemma var_fresh : forall (L : vars), { x : var | x \\notin L }.\nProof.\n  intros L. exists (var_generate L). apply var_generate_spec.\nQed.\n\nEnd Variables.\n\n\n(* ********************************************************************** *)\n(** * Properties of variables *)\n\nExport Variables.\nExport Variables.VarSet.\nModule Export VarSetFacts := FinSetFacts VarSet.\n\nOpen Scope set_scope.\n\n(** Equality on variables is decidable. *)\n\nModule Import Var_as_OT_Facts := OrderedTypeFacts Variables.Var_as_OT.\n\nLemma eq_var_dec : forall x y : var, {x = y} + {x <> y}.\nProof.\n  exact Var_as_OT_Facts.eq_dec.\nQed.\n\n(* ********************************************************************** *)\n(** ** Dealing with list of variables *)\n\n(** Freshness of n variables from a set L and from one another. *)\n\nFixpoint fresh (L : vars) (n : nat) (xs : list var) {struct xs} : Prop :=\n  match xs, n with\n  | nil, O => True\n  | x::xs', S n' => x \\notin L /\\ fresh (L \\u {{x}}) n' xs'\n  | _,_ => False\n  end.\n\nHint Extern 1 (fresh _ _ _) => simpl : core.\n\n(** Triviality : If a list xs contains n fresh variables, then\n    the length of xs is n. *)\n\nLemma fresh_length : forall xs L n,\n  fresh L n xs -> n = length xs.\nProof.\n  induction xs; simpl; intros; destruct n; \n  try solve [ contradictions* | f_equal* ].\nQed.\n\n(* It is possible to build a list of n fresh variables. *)\n\nLemma var_freshes : forall L n, \n  { xs : list var | fresh L n xs }.\nProof.\n  intros. gen L. induction n; intros L.\n  exists* (nil : list var).\n  destruct (var_fresh L) as [x Fr].\n   destruct (IHn (L \\u {{x}})) as [xs Frs].\n   exists* (x::xs).\nQed.\n\n\n(* ********************************************************************** *)\n(** ** Tactics: Case Analysis on Variables *)\n\n(** We define notations for the equality of variables (our free variables)\n  and for the equality of naturals (our bound variables represented using\n  de Bruijn indices). *)\n\nNotation \"x == y\" := (eq_var_dec x y) (at level 67).\nNotation \"i === j\" := (Peano_dec.eq_nat_dec i j) (at level 70).\n\n(** Tactic for comparing two bound or free variables. *)\n\nLtac case_nat :=\n  let destr x y := destruct (x === y); [try subst x | idtac] in\n  match goal with\n  | H: context [?x === ?y] |- _ => destr x y\n  | |- context [?x === ?y]      => destr x y\n  end.\n\nTactic Notation \"case_nat\" \"*\" := case_nat; auto*.\n\nTactic Notation \"case_var\" :=\n  let destr x y := destruct (x == y); [try subst x | idtac] in\n  match goal with\n  | H: context [?x == ?y] |- _ => destr x y\n  | |- context [?x == ?y]      => destr x y\n  end.\n\nTactic Notation \"case_var\" \"*\" := case_var; auto*.\n\n\n(* ********************************************************************** *)\n(** ** Tactics: Picking Names Fresh from the Context *)\n\n(** [gather_vars_for_type T F] return the union of all the finite sets\n  of variables [F x] where [x] is a variable from the context such that\n  [F x] type checks. In other words [x] has to be of the type of the\n  argument of [F]. The resulting union of sets does not contain any\n  duplicated item. This tactic is an extreme piece of hacking necessary\n  because the tactic language does not support a \"fold\" operation on\n  the context. *)\n\nLtac gather_vars_with F :=\n  let rec gather V :=\n    match goal with\n    | H: ?S |- _ =>\n      let FH := constr:(F H) in\n      match V with\n      | {} => gather FH\n      | context [FH] => fail 1\n      | _ => gather (FH \\u V)\n      end\n    | _ => V\n    end in\n  let L := gather {} in eval simpl in L.\n\n(** [beautify_fset V] assumes that [V] is built as a union of finite\n  sets and return the same set cleaned up: empty sets are removed and\n  items are laid out in a nicely parenthesized way *)\n\nLtac beautify_fset V :=\n  let rec go Acc E :=\n     match E with\n     | ?E1 \\u ?E2 => let Acc1 := go Acc E1 in\n                     go Acc1 E2\n     | {}  => Acc\n     | ?E1 => match Acc with\n              | {} => E1\n              | _ => constr:(Acc \\u E1)\n              end\n     end\n  in go {} V.\n\n(** [pick_fresh_gen L Y] expects [L] to be a finite set of variables\n  and adds to the context a variable with name [Y] and a proof that\n  [Y] is fresh for [L]. *)\n\nLtac pick_fresh_gen L Y :=\n  let Fr := fresh \"Fr\" in\n  let L := beautify_fset L in\n  (destruct (var_fresh L) as [Y Fr]).\n\n(** [pick_fresh_gens L n Y] expects [L] to be a finite set of variables\n  and adds to the context a list of variables with name [Y] and a proof \n  that [Y] is of length [n] and contains variable fresh for [L] and\n  distinct from one another. *)\n\nLtac pick_freshes_gen L n Y :=\n  let Fr := fresh \"Fr\" in\n  let L := beautify_fset L in\n  (destruct (var_freshes L n) as [Y Fr]).\n\n(** Demo of pick_fresh_gen *)\n\nLtac test_pick_fresh_filter Y :=\n  let A := gather_vars_with (fun x : vars => x) in\n  let B := gather_vars_with (fun x : var => {{ x }}) in\n  let C := gather_vars_with (fun x : var => {}) in\n  pick_fresh_gen (A \\u B \\u C) Y.\n\nLemma test_pick_fresh : forall (x y z : var) (L1 L2 L3: vars), True.\nProof.\n  intros. test_pick_fresh_filter k. auto.\nQed.\n\n(** The above invokation of [pick_fresh] generates a\n  variable [k] and the hypothesis\n  [k \\notin L1 \\u L2 \\u L3 \\u {{x}} \\u {{y}} \\u {{z}}] *)\n\n\n(* ********************************************************************** *)\n(** ** Tactics: Applying Lemmas With Quantification Over Cofinite Sets *)\n\n(** [apply_fresh_base] tactic is a helper to build tactics that apply an\n  inductive constructor whose first argument should be instanciated\n  by the set of names already used in the context. Those names should\n  be returned by the [gather] tactic given in argument. For each premise\n  of the inductive rule starting with an universal quantification of names\n  outside the set of names instanciated, a subgoal with be generated by\n  the application of the rule, and in those subgoal we introduce the name\n  quantified as well as its proof of freshness. *)\n\nLtac apply_fresh_base_simple lemma gather :=\n  let L0 := gather in let L := beautify_fset L0 in\n  first [apply (@lemma L) | eapply (@lemma L)].\n\nLtac apply_fresh_base lemma gather var_name :=\n  apply_fresh_base_simple lemma gather;\n  try match goal with |- forall _, _ \\notin _ -> _ =>\n    let Fr := fresh \"Fr\" in intros var_name Fr end.\n\n\n(** [inst_notin H y as H'] expects [H] to be of the form\n  [forall x, x \\notin L, P x] and creates an hypothesis [H']\n  of type [P y]. It tries to prove the subgoal [y \\notin L]\n  by [auto]. This tactic is very useful to apply induction\n  hypotheses given in the cases with binders. *)\n\nTactic Notation \"inst_notin\" constr(lemma) constr(var)\n                \"as\" ident(hyp_name) :=\n  let go L := let Fr := fresh in assert (Fr : var \\notin L);\n     [ auto | poses hyp_name (@lemma var Fr); clear Fr ] in\n  match type of lemma with\n  | forall _, _ \\notin ?L -> _ => go L\n  | forall _, (_ \\in ?L -> False) -> _ => go L\n  end.\n\nTactic Notation \"inst_notin\" \"*\" constr(lemma) constr(var)\n                \"as\" ident(hyp_name) :=\n  inst_notin lemma var as hyp_name; auto*.\n", "meta": {"author": "garrigue", "repo": "certint", "sha": "ca94fba3e87f843ee1b7666e3bdbf7900029e0ec", "save_path": "github-repos/coq/garrigue-certint", "path": "github-repos/coq/garrigue-certint/certint-ca94fba3e87f843ee1b7666e3bdbf7900029e0ec/Metatheory_Var.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7189588037056354}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, list_design *)\n\nInductive natlist: Type:=\n|nil: natlist\n|cons: nat -> natlist -> natlist.\n\nNotation \"[]\" := nil.\nNotation \" x :: l\" := (cons x l).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint append(l1 l2: natlist): natlist :=\nmatch l1 with\n|nil        => l2\n|cons h1 t1 => h1 :: (append t1 l2)\nend.\n\nNotation \"l1 ++ l2\" := (append l1 l2).\n\nFixpoint snoc(l: natlist)(v:nat): natlist :=\nmatch l with\n|nil  => [v]\n|h::t => h::(snoc t v)\nend.\n\n(* Write down a non-trivial theorem involving cons (::), snoc, and app (++).\nProve it *)\n\nTheorem list_design: forall (l1 l2: natlist)(v: nat),\n  l1 ++ (cons v l2) = (snoc l1 v) ++ l2.\nProof.\n    intros. induction l1 as [|h1 t1].\n    simpl. reflexivity.\n    simpl. rewrite IHt1. reflexivity.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter5_Library_List/list_design.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7189588035329858}}
{"text": "Section Vector.\n  Variable A : Type.\n  Variable f : A -> bool.\n\n  Inductive Vec : nat -> Type :=\n  | nil : Vec 0\n  | cons : forall {n}, A -> Vec n -> Vec (S n).\n\n  Notation \"[]\" := nil.\n  Notation \"a :: l\" := (cons a l).\n\n  Fixpoint append {n m : nat} (v : Vec n) (v0 : Vec m) : Vec (n + m) :=\n    match v with\n      | [] => v0\n      | a::v' => a::(append v' v0)\n    end.\n\n  Fixpoint filter_length {n} (v : Vec n) : nat :=\n    match v with\n      | [] => O\n      | a::v' =>\n        if f a then S (filter_length v') else filter_length v'\n    end.\n\n  Fixpoint filter {n} (v : Vec n) : Vec (filter_length v) :=\n    match v as v0 return Vec (filter_length v0)\n    with\n      | [] => []\n      | a::v' =>\n        if f a as b return Vec (if b then S (filter_length v')\n                                else filter_length v')\n        then a::(filter v')\n        else filter v'\n    end.\nEnd Vector.\n", "meta": {"author": "OKU1987", "repo": "sandbox", "sha": "068de7623825da8b7d7da8c5b5eef8dfb5005cb9", "save_path": "github-repos/coq/OKU1987-sandbox", "path": "github-repos/coq/OKU1987-sandbox/sandbox-068de7623825da8b7d7da8c5b5eef8dfb5005cb9/coq/vector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7189432765471488}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (lf1 : natural) : natural :=\n  plus y (Succ lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj33_coqofml_DoHoik.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7189369065763405}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\n(* ** Reification for bounded quantification *)\n\nRequire Import Arith Lia.\n\nSet Implicit Arguments.\n\n(* A nat indexed finite number of conjunctions *) \n\nDefinition fmap_reifier_t X (Q : nat -> X -> Prop) k : \n             (forall i, i < k -> sig (Q i))\n          -> { f : forall i, i < k -> X | forall i Hi, Q i (f i Hi) }.\nProof.\n  revert Q; induction k as [ | k IHk ]; intros Q HQ.\n  + assert (f : forall i, i < 0 -> X) by (intros i Hi; exfalso; revert Hi; apply Nat.nlt_0_r).\n    exists f; intros i Hi; exfalso; revert Hi; apply Nat.nlt_0_r.\n  + destruct (HQ 0) as (f0 & H0).\n    * apply Nat.lt_0_succ.\n    * destruct (IHk (fun i => Q (S i))) as (f & Hf).\n      - intros; apply HQ, lt_n_S; trivial.\n      - set (f' :=\n        fun i => match i return i < S k -> X with \n                   | 0   => fun _  => f0\n                   | S j => fun Hj => f j (lt_S_n _ _ Hj)\n                 end).\n        exists f'; intros [ | i ] Hi; simpl; trivial.\nDefined.\n\nDefinition fmap_reifier_t_default X (Q : nat -> X -> Prop) k (x : X) : \n             (forall i, i < k -> sig (Q i))\n          -> { f : nat -> X | forall i, i < k -> Q i (f i) }.\nProof.\n  intros H.\n  apply fmap_reifier_t in H.\n  destruct H as (f & Hf).\n  exists (fun i => match le_lt_dec k i with \n                          | left _ => x \n                          | right Hi => f i Hi \n                        end).\n  intros i Hi.\n  destruct (le_lt_dec k i) as [ H1 | ]; auto.\n  exfalso; revert Hi H1; apply lt_not_le.\nDefined.\n\n(* Given predicate P : nat -> nat -> Prop such that\n      1/ P x is satisfiable for any x < n\n    \n    then there is a bound m such that for any x < n\n    P x y is satisfied for some y below m *)\n\nTheorem fmap_bound n P : \n           (forall x, x < n -> ex (P x)) \n        -> exists m, forall x, x < n -> exists y, y < m /\\ P x y.\nProof with try lia.\n  revert P; induction n as [ | n IHn ]; intros P HP.\n  + exists 0; intros...\n  + destruct (HP 0) as (m0 & H0)...\n    destruct (IHn (fun n => P (S n))) as (m1 & Hm1).\n    - intros; apply HP...\n    - exists (1+m0+m1); intros [ | x ] Hx.\n      * exists m0; split; auto...\n      * destruct (Hm1 x) as (y & H1 & H2)...\n        exists y; split; auto...\nQed.\n\nTheorem fmap_reifier_default X n (P : nat -> X -> Prop) : \n           inhabited X \n        -> (forall x, x < n -> ex (P x)) \n        -> exists f, forall x, x < n -> P x (f x).\nProof with try lia.\n  intros [ u ].\n  revert P; induction n as [ | n IHn ]; intros P HP.\n  + exists (fun _ => u); intros...\n  + destruct (IHn (fun i => P (S i))) as (f & Hf).\n    { intros; apply HP... }\n    destruct (HP 0) as (x & Hx)...\n    exists (fun i => match i with 0 => x | S i => f i end).\n    intros [|] ?; auto; apply Hf...\nQed. \n\nTheorem fmap_reifer_bound n P : \n           (forall x, x < n -> ex (P x)) \n        -> exists m f, forall x, x < n -> f x < m /\\ P x (f x).\nProof.\n  intros H.\n  apply fmap_bound in H.\n  destruct H as (m & Hm); exists m.\n  revert Hm; apply fmap_reifier_default; auto.\nQed.\n\n(* equal_upto m f g means f 0 = g 0, ... f (m-1) = g (m-1) *)\n\nLocal Notation equal_upto := (fun m (f g : nat -> nat) => forall n, n < m -> f n = g n).\n\n(* Given a predicate P over nat * (nat -> nat), which is supposed to be finitary \n\n  1/ for any x, P x only takes the first p values of its argument into acounts \n  2/ P x is satisfiable for any value of x lower than n\n\n  then there is a bound m such that for any x, there is always a solution f to\n  P x f which is uniformly bounded by m \n\n*)\n\nTheorem fmmap_bound p n (P : nat -> (nat -> nat) -> Prop) :\n             (forall x f g, equal_upto p f g -> P x f -> P x g)       \n          -> (forall x, x < n -> exists f, P x f) \n          -> exists m, forall x, x < n -> exists f, (forall i, i < p -> f i < m) /\\ P x f.\nProof.\n  revert P.\n  induction p as [ | p IHp ]; intros P HP H.\n  + exists 1; intros x Hx.\n    destruct (H _ Hx) as (f & Hf).\n    exists (fun _ => 0); split; auto.\n    apply (HP x f); auto.\n    intros ? ?; lia.\n  + set (Q x y := exists f, P x (fun i => match i with 0 => y | S i => f i end)).\n    destruct (@fmap_bound n Q) as (m1 & Hm1).\n    { intros x Hx.\n      destruct (H _ Hx) as (f & Hf).\n      exists (f 0); red.\n      exists (fun i => f (S i)).\n      revert Hf; apply HP.\n      intros [ | i ]; auto. }\n    set (R x f := exists y, y < m1 /\\ P x (fun i => match i with 0 => y | S i => f i end)).\n    destruct (IHp R) as (m2 & Hm2).\n    { intros x f g Hfg (y & H1 & H2); exists y; split; auto.\n      revert H2; apply HP; intros [ | ]; auto; intros; apply Hfg; lia. }\n    { intros x Hx. \n      destruct (Hm1 _ Hx) as (y & H1 & f & H2).\n      exists f, y; split; auto. }\n    exists (m1+m2).\n    intros x Hx.\n    destruct (Hm2 _ Hx) as (f & H1 & y & H2 & H3).\n    eexists; split; [ | exact H3 ].\n    intros [ | j ] Hj; try lia.\n    specialize (H1 j); intros; lia.\nQed.\n\nTheorem fmmap_reifer_bound p n (P : nat -> (nat -> nat) -> Prop) :\n             (forall x f g, equal_upto p f g -> P x f -> P x g)       \n          -> (forall x, x < n -> exists f, P x f) \n          -> exists m f, forall x, x < n -> (forall j, j < p -> f x j < m) /\\ P x (f x).\nProof.\n  intros H1 H2.\n  apply fmmap_bound with (1 := H1) in H2.\n  destruct H2 as (m & Hm).\n  apply fmap_reifier_default in Hm; auto.\n  destruct Hm as (f & Hf); exists m, f; auto.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/Shared/Libs/DLW/Utils/bounded_quantification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7187774472840242}}
{"text": "(* Lemma cons_inj  : \nforall x1 x2 :Type, forall l1 l2 : list Type,\n cons x1 l1 = cons x2 l2 -> x1=x2 /\\ l1=l2.\nProof.\n\tintros.\n\tinjection H.\n\tsplit.\n\tapply H1.\n\tapply H0.\nQed. *)\n\nParameter A:Type.\n\nDefinition tl (l: list A) : list A :=\n\tmatch l with \n\tnil => nil\n\t|cons _ t => t\n\tend\n.\n\nDefinition hd (v:A) (l: list A) : A :=\n\tmatch l with \n\tnil =>  v\n\t|cons h t => h\n\tend\n.\n\nLemma cons_inj  : \nforall x1 x2 :A, forall l1 l2 : list A,\n cons x1 l1 = cons x2 l2 -> x1=x2 /\\ l1=l2.\nProof.\n\tintros.\n\tsplit.\n\tapply f_equal with (f:= hd x1) in H.\n\t\n\tsimpl in H.\n\tapply H.\n\tapply f_equal with (f:= tl) in H.\n\tsimpl in H.\n\tapply H.\nQed.\n\nDefinition Nil (l: list A) := \n\tmatch l with \n\tnil => True\n\t|_ => False\n\tend\n.\n\n\nLemma cons_discr : \nforall x : A, forall l : list A, nil <> cons x l.\nProof.\n\tintros.\n\t\n\tunfold not.\n\tintro.\n\tapply f_equal with (f:=Nil) in H.\n\tunfold Nil in H.\n\trewrite <-  H.\n\texact I.\n\t\n", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/PA/2021/TP4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8175744673038221, "lm_q1q2_score": 0.7187679501284806}}
{"text": "(** * IndPrinciples: Induction Principles *)\n\n(** With the Curry-Howard correspondence and its realization in Coq in\n    mind, we can now take a deeper look at induction principles. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export ProofObjects.\n\n(* ################################################################# *)\n(** * Basics *)\n\n(** Every time we declare a new [Inductive] datatype, Coq\n    automatically generates an _induction principle_ for this type.\n    This induction principle is a theorem like any other: If [t] is\n    defined inductively, the corresponding induction principle is\n    called [t_ind].  Here is the one for natural numbers: *)\n\nCheck nat_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, P n -> P (S n)) ->\n    forall n : nat, P n.\n\n(** In English: Suppose [P] is a property of natural numbers (that is,\n      [P n] is a [Prop] for every [n]). To show that [P n] holds of all\n      [n], it suffices to show:\n\n      - [P] holds of [0]\n      - for any [n], if [P] holds of [n], then [P] holds of [S n]. *)\n\n(** The [induction] tactic is a straightforward wrapper that, at its\n    core, simply performs [apply t_ind].  To see this more clearly,\n    let's experiment with directly using [apply nat_ind], instead of\n    the [induction] tactic, to carry out some proofs.  Here, for\n    example, is an alternate proof of a theorem that we saw in the\n    [Induction] chapter. *)\n\nTheorem mult_0_r' : forall n:nat,\n  n * 0 = 0.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *) simpl. intros n' IHn'. rewrite -> IHn'.\n    reflexivity.  Qed.\n\n(** This proof is basically the same as the earlier one, but a\n    few minor differences are worth noting.\n\n    First, in the induction step of the proof (the [S] case), we\n    have to do a little bookkeeping manually (the [intros]) that\n    [induction] does automatically.\n\n    Second, we do not introduce [n] into the context before applying\n    [nat_ind] -- the conclusion of [nat_ind] is a quantified formula,\n    and [apply] needs this conclusion to exactly match the shape of\n    the goal state, including the quantifier.  By contrast, the\n    [induction] tactic works either with a variable in the context or\n    a quantified variable in the goal.\n\n    Third, we had to manually supply the name of the induction principle\n    with [apply], but [induction] figures that out itself.\n\n    These conveniences make [induction] nicer to use in practice than\n    applying induction principles like [nat_ind] directly.  But it is\n    important to realize that, modulo these bits of bookkeeping,\n    applying [nat_ind] is what we are really doing. *)\n\n(** **** Exercise: 2 stars, standard (plus_one_r') \n\n    Complete this proof without using the [induction] tactic. *)\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  - simpl. reflexivity.\n  - simpl. intros n' IHn. rewrite IHn. reflexivity.\nQed.\n(** [] *)\n\n(** Coq generates induction principles for every datatype\n    defined with [Inductive], including those that aren't recursive.\n    Although of course we don't need the proof technique of induction\n    to prove properties of non-recursive datatypes, the idea of an\n    induction principle still makes sense for them: it gives a way to\n    prove that a property holds for all values of the type. *)\n\n(** These generated principles follow a similar pattern. If we\n    define a type [t] with constructors [c1] ... [cn], Coq generates a\n    theorem with this shape:\n\n    t_ind : forall P : t -> Prop,\n              ... case for c1 ... ->\n              ... case for c2 ... -> ...\n              ... case for cn ... ->\n              forall n : t, P n\n\n    The specific shape of each case depends on the arguments to the\n    corresponding constructor. *)\n\n(** Before trying to write down a general rule, let's look at\n    some more examples. First, an example where the constructors take\n    no arguments: *)\n\nInductive time : Type :=\n  | day\n  | night.\n\nCheck time_ind :\n  forall P : time -> Prop,\n    P day ->\n    P night ->\n    forall t : time, P t.\n\n(** **** Exercise: 1 star, standard, optional (rgb) \n\n    Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\nCheck rgb_ind.\n(** [] *)\n\n(** Here's another example, this time with one of the constructors\n    taking some arguments. *)\n\nInductive natlist : Type :=\n  | nnil\n  | ncons (n : nat) (l : natlist).\n\nCheck natlist_ind :\n  forall P : natlist -> Prop,\n    P nnil  ->\n    (forall (n : nat) (l : natlist),\n        P l -> P (ncons n l)) ->\n    forall l : natlist, P l.\n\n(** In general, the automatically generated induction principle for\n    inductive type [t] is formed as follows:\n\n    - Each constructor [c] generates one case of the principle.\n    - If [c] takes no arguments, that case is:\n\n      \"P holds of c\"\n\n    - If [c] takes arguments [x1:a1] ... [xn:an], that case is:\n\n      \"For all x1:a1 ... xn:an,\n          if [P] holds of each of the arguments of type [t],\n          then [P] holds of [c x1 ... xn]\"\n\n      But that oversimplifies a little.  An assumption about [P]\n      holding of an argument [x] of type [t] actually occurs\n      immediately after the quantification of [x].\n*)\n\n(** For example, suppose we had written the definition of [natlist] a little\n    differently: *)\n\nInductive natlist' : Type :=\n  | nnil'\n  | nsnoc (l : natlist') (n : nat).\n\n(** Now the induction principle case for [nsnoc1] is a bit different\n    than the earlier case for [ncons]: *)\n\nCheck natlist'_ind :\n  forall P : natlist' -> Prop,\n    P nnil' ->\n    (forall l : natlist', P l -> forall n : nat, P (nsnoc l n)) ->\n    forall n : natlist', P n.\n\n(** **** Exercise: 1 star, standard (booltree_ind) \n\n    In the comment below, Write out the induction principle that Coq \n    will generate for the following datatype. *)\n\nInductive booltree : Type :=\n | bt_empty\n | bt_leaf (b : bool)\n | bt_branch (b : bool) (t1 t2 : booltree).\n\n\n(* FILL IN HERE:\n   forall P : booltree -> Prop,\n   P bt_empty ->\n   (forall (b : bool), P(bt_leaf)) ->\n   (forall (b : bool) (t1 : booltree), P t1 -> \n   forall t2 : booltree, P t2 -> P (bt_branch b t1 t2)) ->\n   forall bt : booltree, P bt \n*)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_booltree_ind : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (toy_ind) \n\n    Here is an induction principle for a toy type:\n\n  forall P : Toy -> Prop,\n    (forall b : bool, P (con1 b)) ->\n    (forall (n : nat) (t : Toy), P t -> P (con2 n t)) ->\n    forall t : Toy, P t\n\n    Give an [Inductive] definition of [Toy], such that the induction\n    principle Coq generates is that given above: *)\n\nInductive Toy : Type :=\n  | con1 (b : bool)\n  | con2 (n : nat) (t: Toy).\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_toy_ind : option (nat*string) := None.\n(** [] *)\n\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** What about polymorphic datatypes?\n\n    The inductive definition of polymorphic lists\n\n      Inductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\n\n    is very similar to that of [natlist].  The main difference is\n    that, here, the whole definition is _parameterized_ on a set [X]:\n    that is, we are defining a _family_ of inductive types [list X],\n    one for each [X].  (Note that, wherever [list] appears in the body\n    of the declaration, it is always applied to the parameter [X].)\n*)\n\n(**  The induction principle is likewise parameterized on [X]:\n\n      list_ind :\n        forall (X : Type) (P : list X -> Prop),\n           P [] ->\n           (forall (x : X) (l : list X), P l -> P (x :: l)) ->\n           forall l : list X, P l\n\n    Note that the _whole_ induction principle is parameterized on\n    [X].  That is, [list_ind] can be thought of as a polymorphic\n    function that, when applied to a type [X], gives us back an\n    induction principle specialized to the type [list X]. *)\n\n(** **** Exercise: 1 star, standard, optional (tree) \n\n    Write out the induction principle that Coq will generate for\n   the following datatype.  Compare your answer with what Coq\n   prints. *)\n\nInductive tree (X:Type) : Type :=\n  | leaf (x : X)\n  | node (t1 t2 : tree X).\nCheck tree_ind.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (mytype) \n\n    Find an inductive definition that gives rise to the\n    following induction principle:\n\n      mytype_ind :\n        forall (X : Type) (P : mytype X -> Prop),\n            (forall x : X, P (constr1 X x)) ->\n            (forall n : nat, P (constr2 X n)) ->\n            (forall m : mytype X, P m ->\n               forall n : nat, P (constr3 X m n)) ->\n            forall m : mytype X, P m\n*) \n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (foo) \n\n    Find an inductive definition that gives rise to the\n    following induction principle:\n\n      foo_ind :\n        forall (X Y : Type) (P : foo X Y -> Prop),\n             (forall x : X, P (bar X Y x)) ->\n             (forall y : Y, P (baz X Y y)) ->\n             (forall f1 : nat -> foo X Y,\n               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n             forall f2 : foo X Y, P f2\n*) \n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (foo') \n\n    Consider the following inductive definition: *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 (l : list X) (f : foo' X)\n  | C2.\n\n(** What induction principle will Coq generate for [foo']?  Fill\n   in the blanks, then check your answer with Coq.)\n\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    _______________________ ->\n                    _______________________   ) ->\n             ___________________________________________ ->\n             forall f : foo' X, ________________________\n*)\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?\n\n    The induction principle for numbers\n\n       forall P : nat -> Prop,\n            P 0  ->\n            (forall n : nat, P n -> P (S n))  ->\n            forall n : nat, P n\n\n   is a generic statement that holds for all propositions\n   [P] (or rather, strictly speaking, for all families of\n   propositions [P] indexed by a number [n]).  Each time we\n   use this principle, we are choosing [P] to be a particular\n   expression of type [nat->Prop].\n\n   We can make proofs by induction more explicit by giving\n   this expression a name.  For example, instead of stating\n   the theorem [mult_0_r] as \"[forall n, n * 0 = 0],\" we can\n   write it as \"[forall n, P_m0r n]\", where [P_m0r] is defined\n   as... *)\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\n\n(** ... or equivalently: *)\n\nDefinition P_m0r' : nat->Prop :=\n  fun n => n * 0 = 0.\n\n(** Now it is easier to see where [P_m0r] appears in the proof. *)\n\nTheorem mult_0_r'' : forall n:nat,\n  P_m0r n.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    (* Note the proof state at this point! *)\n    intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n(** This extra naming step isn't something that we do in\n    normal proofs, but it is useful to do it explicitly for an example\n    or two, because it allows us to see exactly what the induction\n    hypothesis is.  If we prove [forall n, P_m0r n] by induction on\n    [n] (using either [induction] or [apply nat_ind]), we see that the\n    first subgoal requires us to prove [P_m0r 0] (\"[P] holds for\n    zero\"), while the second subgoal requires us to prove [forall n',\n    P_m0r n' -> P_m0r (S n')] (that is \"[P] holds of [S n'] if it\n    holds of [n']\" or, more elegantly, \"[P] is preserved by [S]\").\n    The _induction hypothesis_ is the premise of this latter\n    implication -- the assumption that [P] holds of [n'], which we are\n    allowed to use in proving that [P] holds for [S n']. *)\n\n(* ################################################################# *)\n(** * More on the [induction] Tactic *)\n\n(** The [induction] tactic actually does even more low-level\n    bookkeeping for us than we discussed above.\n\n    Recall the informal statement of the induction principle for\n    natural numbers:\n      - If [P n] is some proposition involving a natural number n, and\n        we want to show that P holds for _all_ numbers n, we can\n        reason like this:\n          - show that [P O] holds\n          - show that, if [P n'] holds, then so does [P (S n')]\n          - conclude that [P n] holds for all n.\n    So, when we begin a proof with [intros n] and then [induction n],\n    we are first telling Coq to consider a _particular_ [n] (by\n    introducing it into the context) and then telling it to prove\n    something about _all_ numbers (by using induction).\n*)\n\n(**  What Coq actually does in this situation, internally, is to\n    \"re-generalize\" the variable we perform induction on.  For\n    example, in our original proof that [plus] is associative... *)\n\nTheorem plus_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  (* ...we first introduce all 3 variables into the context,\n     which amounts to saying \"Consider an arbitrary [n], [m], and\n     [p]...\" *)\n  intros n m p.\n  (* ...We now use the [induction] tactic to prove [P n] (that\n     is, [n + (m + p) = (n + m) + p]) for _all_ [n],\n     and hence also for the particular [n] that is in the context\n     at the moment. *)\n  induction n as [| n'].\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** It also works to apply [induction] to a variable that is\n    quantified in the goal. *)\n\nTheorem plus_comm' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [| n'].\n  - (* n = O *) intros m. rewrite <- plus_n_O. reflexivity.\n  - (* n = S n' *) intros m. simpl. rewrite -> IHn'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** Note that [induction n] leaves [m] still bound in the goal --\n    i.e., what we are proving inductively is a statement beginning\n    with [forall m].\n\n    If we do [induction] on a variable that is quantified in the goal\n    _after_ some other quantifiers, the [induction] tactic will\n    automatically introduce the variables bound by these quantifiers\n    into the context. *)\n\nTheorem plus_comm'' : forall n m : nat,\n  n + m = m + n.\nProof.\n  (* Let's do induction on [m] this time, instead of [n]... *)\n  induction m as [| m']. (* [n] is already introduced into the context *)\n  - (* m = O *) simpl. rewrite <- plus_n_O. reflexivity.\n  - (* m = S m' *) simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, standard, optional (plus_explicit_prop) \n\n    Rewrite both [plus_assoc'] and [plus_comm'] and their proofs in\n    the same style as [mult_0_r''] above -- that is, for each theorem,\n    give an explicit [Definition] of the proposition being proved by\n    induction, and state the theorem and proof in terms of this\n    defined proposition.  *)\n\n(* FILL IN HERE\n\n    [] *)\n\n(* ################################################################# *)\n(** * Induction Principles for Propositions *)\n\n(** Inductive definitions of propositions also cause Coq to generate\n    induction priniciples.  For example, recall our proposition [ev],\n    repeated here as [ev'']: *)\n\nInductive ev'' : nat -> Prop :=\n| ev_0 : ev'' 0\n| ev_SS (n : nat) : ev'' n -> ev'' (S (S n)).\n\nCheck ev''_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, ev'' n -> P n -> P (S (S n))) ->\n    forall n : nat, ev'' n -> P n.\n\n(** In English, [ev''_ind] says: Suppose [P] is a property of natural\n    numbers.  To show that [P n] holds whenever [n] is even, it suffices\n    to show:\n\n      - [P] holds for [0],\n\n      - for any [n], if [n] is even and [P] holds for [n], then [P]\n        holds for [S (S n)]. *)\n\n(** As expected, we can apply [ev''_ind] directly instead of using\n    [induction].  For example, we can use it to show that [ev'] (the\n    slightly awkward alternate definition of evenness that we saw in\n    an exercise in the \\chap{IndProp} chapter) is equivalent to the\n    cleaner inductive definition [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\nTheorem ev''_ev' : forall n, ev'' n -> ev' n.\nProof.\n  apply ev''_ind.\n  - (* ev_0 *)\n    apply ev'_0.\n  - (* ev_SS *)\n    intros m Hm IH.\n    apply (ev'_sum 2 m).\n    + apply ev'_2.\n    + apply IH.\nQed.\n\n(** The precise form of an [Inductive] definition can affect the\n    induction principle Coq generates. *)\n\nInductive le1 : nat -> nat -> Prop :=\n     | le1_n : forall n, le1 n n\n     | le1_S : forall n m, (le1 n m) -> (le1 n (S m)).\n\nNotation \"m <=1 n\" := (le1 m n) (at level 70).\n\n(** This definition can be streamlined a little by observing that the\n    left-hand argument [n] is the same everywhere in the definition,\n    so we can actually make it a \"general parameter\" to the whole\n    definition, rather than an argument to each constructor. *)\n\nInductive le2 (n:nat) : nat -> Prop :=\n  | le2_n : le2 n n\n  | le2_S m (H : le2 n m) : le2 n (S m).\n\nNotation \"m <=2 n\" := (le2 m n) (at level 70).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. *)\n\nCheck le1_ind :\n  forall P : nat -> nat -> Prop,\n    (forall n : nat, P n n) ->\n    (forall n m : nat, n <=1 m -> P n m -> P n (S m)) ->\n    forall n n0 : nat, n <=1 n0 -> P n n0.\n\nCheck le2_ind :\n  forall (n : nat) (P : nat -> Prop),\n    P n ->\n    (forall m : nat, n <=2 m -> P m -> P (S m)) ->\n    forall n0 : nat, n <=2 n0 -> P n0.\n\n(* ################################################################# *)\n(** * Another Form of Induction Principles on Propositions (Optional) *)\n\n(** The induction principle that Coq generated for [ev''] was parameterized\n    on a natural number [n].  It could have additionally been parameterized\n    on the evidence that [n] was even, which would have led to this\n    induction principle:\n\n    forall P : (forall n : nat, ev'' n -> Prop),\n      P O ev_0 ->\n      (forall (m : nat) (E : ev'' m),\n        P m E -> P (S (S m)) (ev_SS m E)) ->\n      forall (n : nat) (E : ev'' n), P n E\n*)\n\n(**   ... because:\n\n     - Since [ev''] is indexed by a number [n] (every [ev''] object [E] is\n       a piece of evidence that some particular number [n] is even),\n       the proposition [P] is parameterized by both [n] and [E] --\n       that is, the induction principle can be used to prove\n       assertions involving both an even number and the evidence that\n       it is even.\n\n     - Since there are two ways of giving evidence of evenness ([even]\n       has two constructors), applying the induction principle\n       generates two subgoals:\n\n         - We must prove that [P] holds for [O] and [ev_0].\n\n         - We must prove that, whenever [m] is an even number and [E]\n           is an evidence of its evenness, if [P] holds of [m] and\n           [E], then it also holds of [S (S m)] and [ev_SS m E].\n\n     - If these subgoals can be proved, then the induction principle\n       tells us that [P] is true for _all_ even numbers [n] and\n       evidence [E] of their evenness.\n\n    This is more flexibility than we normally need or want: it is\n    giving us a way to prove logical assertions where the assertion\n    involves properties of some piece of _evidence_ of evenness, while\n    all we really care about is proving properties of _numbers_ that\n    are even -- we are interested in assertions about numbers, not\n    about evidence.  It would therefore be more convenient to have an\n    induction principle for proving propositions [P] that are\n    parameterized just by [n] and whose conclusion establishes [P] for\n    all even numbers [n]:\n\n       forall P : nat -> Prop,\n         ... ->\n       forall n : nat,\n         even n -> P n\n\n    That is why Coq actually generates the induction principle\n    [ev''_ind] that we saw before. *)\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proofs by Induction *)\n\n(** Question: What is the relation between a formal proof of a\n    proposition [P] and an informal proof of the same proposition [P]?\n\n    Answer: The latter should _teach_ the reader how to produce the\n    former.\n\n    Question: How much detail is needed??\n\n    Unfortunately, there is no single right answer; rather, there is a\n    range of choices.\n\n    At one end of the spectrum, we can essentially give the reader the\n    whole formal proof (i.e., the \"informal\" proof will amount to just\n    transcribing the formal one into words).  This may give the reader\n    the ability to reproduce the formal one for themselves, but it\n    probably doesn't _teach_ them anything much.\n\n   At the other end of the spectrum, we can say \"The theorem is true\n   and you can figure out why for yourself if you think about it hard\n   enough.\"  This is also not a good teaching strategy, because often\n   writing the proof requires one or more significant insights into\n   the thing we're proving, and most readers will give up before they\n   rediscover all the same insights as we did.\n\n   In the middle is the golden mean -- a proof that includes all of\n   the essential insights (saving the reader the hard work that we\n   went through to find the proof in the first place) plus high-level\n   suggestions for the more routine parts to save the reader from\n   spending too much time reconstructing these (e.g., what the IH says\n   and what must be shown in each case of an inductive proof), but not\n   so much detail that the main ideas are obscured.\n\n   Since we've spent much of this chapter looking \"under the hood\" at\n   formal proofs by induction, now is a good moment to talk a little\n   about _informal_ proofs by induction.\n\n   In the real world of mathematical communication, written proofs\n   range from extremely longwinded and pedantic to extremely brief and\n   telegraphic.  Although the ideal is somewhere in between, while one\n   is getting used to the style it is better to start out at the\n   pedantic end.  Also, during the learning phase, it is probably\n   helpful to have a clear standard to compare against.  With this in\n   mind, we offer two templates -- one for proofs by induction over\n   _data_ (i.e., where the thing we're doing induction on lives in\n   [Type]) and one for proofs by induction over _evidence_ (i.e.,\n   where the inductively defined thing lives in [Prop]). *)\n\n(* ================================================================= *)\n(** ** Induction Over an Inductively Defined Set *)\n\n(** _Template_:\n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_:\n\n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if [length [] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of [index].\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n\n            length l = length (x::l') = S (length l'),\n\n          it suffices to show that\n\n            index (S (length l')) l' = None.\n\n          But this follows directly from the induction hypothesis,\n          picking [n'] to be [length l'].  [] *)\n\n(* ================================================================= *)\n(** ** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_.\n\n    _Template_:\n\n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n\n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n(* ################################################################# *)\n(** * Explicit Proof Objects for Induction (Optional) *)\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n\n(** Recall again the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\nCheck nat_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, P n -> P (S n)) ->\n    forall n : nat, P n.\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n\nPrint nat_ind.\n\n(** We can rewrite that more tidily as follows: *)\nFixpoint build_proof\n         (P : nat -> Prop)\n         (evPO : P 0)\n         (evPS : forall n : nat, P n -> P (S n))\n         (n : nat) : P n :=\n  match n with\n  | 0 => evPO\n  | S k => evPS k (build_proof P evPO evPS k)\n  end.\n\nDefinition nat_ind_tidy := build_proof.\n\n(** We can read [build_proof] as follows: Suppose we have\n    evidence [evPO] that [P] holds on 0, and evidence [evPS] that [forall\n    n:nat, P n -> P (S n)].  Then we can prove that [P] holds of an\n    arbitrary nat [n] using recursive function [build_proof], which\n    pattern matches on [n]:\n\n      - If [n] is 0, [build_proof] returns [evPO] to show that [P n]\n        holds.\n\n      - If [n] is [S k], [build_proof] applies itself recursively on\n        [k] to obtain evidence that [P k] holds; then it applies\n        [evPS] on that evidence to show that [P (S n)] holds. *)\n\n(** Recursive function [build_proof] thus pattern matches against\n    [n], recursing all the way down to 0, and building up a proof\n    as it returns. *)\n\n(** The actual [nat_ind] that Coq generates uses a recursive\n    function [F] defined with [fix] instead of [Fixpoint]. *)\n\n(**  We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  As a motivating example,\n    suppose that we want to prove the following lemma, directly\n    relating the [ev] predicate we defined in [IndProp]\n    to the [evenb] function defined in [Basics]. *)\n\nLemma evenb_ev : forall n: nat, evenb n = true -> ev'' n.\nProof.\n  induction n; intros.\n  - apply ev_0.\n  - destruct n.\n    + simpl in H. inversion H.\n    + simpl in H.\n      apply ev_SS.\nAbort.\n\n(** Attempts to prove this by standard induction on [n] fail in the case for\n    [S (S n)],  because the induction hypothesis only tells us something about\n    [S n], which is useless. There are various ways to hack around this problem;\n    for example, we _can_ use ordinary induction on [n] to prove this (try it!):\n\n    [Lemma evenb_ev' : forall n : nat,\n     (evenb n = true -> ev n) /\\ (evenb (S n) = true -> ev (S n))].\n\n    But we can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n *)\n\n Definition nat_ind2 :\n    forall (P : nat -> Prop),\n    P 0 ->\n    P 1 ->\n    (forall n : nat, P n -> P (S(S n))) ->\n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS =>\n          fix f (n:nat) := match n with\n                             0 => P0\n                           | 1 => P1\n                           | S (S n') => PSS n' (f n')\n                          end.\n\n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive.\n\n     The [induction ... using] tactic variant gives a convenient way to\n     utilize a non-standard induction principle like this. *)\n\nLemma evenb_ev : forall n, evenb n = true -> ev'' n.\nProof.\n intros.\n induction n as [ | |n'] using nat_ind2.\n - apply ev_0.\n - simpl in H.\n   inversion H.\n - simpl in H.\n   apply ev_SS.\n   apply IHn'.\n   apply H.\nQed.\n\n\n(* 04 Mar 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/a6src/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744717487329, "lm_q2_score": 0.8791467548438126, "lm_q1q2_score": 0.7187679436810428}}
{"text": "Require Import List.\nSection Last.\n\n  Variable A : Type.\n  Set Implicit Arguments.\n\n  Inductive last (a:A) : list A -> Prop :=\n  | last_hd : last a (a :: nil)\n  | last_tl : forall (b:A) (l:list A), last a l -> last a (b :: l).\n\n\n  #[local] Hint Constructors last : core.\n\n  Fixpoint last_fun (l:list A) : option A :=\n    match l with\n    | nil => None (A:=A)\n    | a :: nil => Some a\n    | a :: l' => last_fun l'\n    end.\n\n  Theorem last_fun_correct :\n    forall (a:A) (l:list A), last a l -> last_fun l = Some a.\n  Proof.\n    intros a l H; induction H as [| b l H IH].  \n    - reflexivity. \n    -   destruct l; simpl in *.\n        +  discriminate IH.\n        +  assumption. \n  Qed.\n\n  Theorem last_fun_correct_R :\n    forall (a:A) (l:list A), last_fun l = Some a -> last a l.\n  Proof.\n    intros a l ; induction l as [ |a0 l0 IHl0]; simpl.\n    - discriminate.\n    -  destruct l0.\n       + injection 1;intros;subst a0;auto.\n       +  intro e; simpl; auto. \n  Qed.\n\n  Lemma last_fun_of_cons : forall (l:list A) (a:A), last_fun (a :: l) <> None.\n  Proof.\n    intros l ; induction l as [| a l0].\n    -  discriminate.\n    - destruct l0;simpl;auto.   \n      + discriminate.\n  Qed.\n\n  Theorem last_fun_correct3 :\n    forall l:list A, last_fun l = None -> forall b:A, ~ last b l.\n  Proof.\n    intro l; case l.\n    - simpl; red; inversion 2.\n    -  intros a l0 H;  case (last_fun_of_cons l0 a H). \n  Qed.\n\nEnd Last.\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch8_inductive_predicates/SRC/last.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7187195990625574}}
{"text": "(** DEPRECATED?\n    \\o notation for composition is used in LibFixDemos\n*)\n\n(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Functions                                                               *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic LibContainer LibSet.\n(* This will be Import-ed only in the relevant sections *)\nFrom TLC Require LibList.\nGeneralizable Variables A.\n\n\n(* ********************************************************************** *)\n(** ** Indentity function *)\n\nDefinition id {A} (x : A) :=\n  x.\n\n\n(* ********************************************************************** *)\n(** Constant functions *)\n\nDefinition const {A B} (v : B) : A -> B :=\n  fun _ => v.\nDefinition const1 :=\n  @const.\nDefinition const2 {A1 A2 B} (v:B) : A1->A2->B :=\n  fun _ _ => v.\nDefinition const3 {A1 A2 A3 B} (v:B) : A1->A2->A3->B :=\n  fun _ _ _ => v.\nDefinition const4 {A1 A2 A3 A4 B} (v:B) : A1->A2->A3->A4->B :=\n  fun _ _ _ _ => v.\nDefinition const5 {A1 A2 A3 A4 A5 B} (v:B) : A1->A2->A3->A4->A5->B :=\n  fun _ _ _ _ _ => v.\n\n\n(* ********************************************************************** *)\n(** Function application *)\n\nDefinition apply {A B} (f : A -> B) (x : A) :=\n  f x.\n\nDefinition apply_to (A : Type) (x : A) (B : Type) (f : A -> B) :=\n  f x.\n\n\n(* ********************************************************************** *)\n(** Function composition *)\n\nDefinition compose {A B C} (g : B -> C) (f : A -> B) :=\n  fun x => g (f x).\n\nDeclare Scope fun_scope.\n\nNotation \"f1 \\o f2\" := (compose f1 f2)\n  (at level 49, right associativity) : fun_scope.\n\nSection Combinators.\nOpen Scope fun_scope.\nVariables (A B C D : Type).\n\nLemma compose_id_l : forall (f:A->B),\n  id \\o f = f.\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_id_r : forall (f:A->B),\n  f \\o id = f.\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_assoc : forall (f:C->D) (g:B->C) (h:A->B),\n  (f \\o g) \\o h = f \\o (g \\o h).\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_eq_l : forall (f:B->C) (g1 g2:A->B),\n  g1 = g2 ->\n  f \\o g1 = f \\o g2.\nProof using. intros. subst~. Qed.\n\nLemma compose_eq_r : forall (f:A->B) (g1 g2:B->C),\n  g1 = g2 ->\n  g1 \\o f = g2 \\o f.\nProof using. intros. subst~. Qed.\n\n(** Composition of [LibList.map] behaves well. **)\n(* Could not be put in [LibList] because of circular dependencies. *)\nImport LibList.\n\nLemma list_map_compose : forall A B C (f : A -> B) (g : B -> C) l,\n  LibList.map g (LibList.map f l) = LibList.map (g \\o f) l.\nProof using.\n  introv. induction l.\n   reflexivity.\n   rew_listx. fequals~.\nQed.\n\nEnd Combinators.\n\n(** Tactic for simplifying function compositions *)\n(* --TODO: not used; might become deprecated *)\n\n#[global]\nHint Rewrite compose_id_l compose_id_r compose_assoc : rew_compose.\nTactic Notation \"rew_compose\" :=\n  autorewrite with rew_compose.\nTactic Notation \"rew_compose\" \"in\" \"*\" :=\n  autorewrite with rew_compose in *.\nTactic Notation \"rew_compose\" \"in\" hyp(H) :=\n  autorewrite with rew_compose in H.\n\n\n(* ********************************************************************** *)\n(** ** Function update *)\n\n(** [fupdate f a b x] is like [f] except that it returns [b] for input [a] *)\n\nDefinition fupdate A B (f : A -> B) (a : A) (b : B) : A -> B :=\n  fun x => If (x = a) then b else f x.\n\nLemma fupdate_eq : forall A B (f:A->B) a b x,\n  fupdate f a b x = If (x = a) then b else f x.\nProof using. auto. Qed.\n\nLemma fupdate_same : forall A B (f:A->B) a b,\n  fupdate f a b a = b.\nProof using. intros. unfold fupdate. case_if*. Qed.\n\nLemma fupdate_neq : forall A B (f:A->B) a b x,\n  x <> a ->\n  fupdate f a b x = f x.\nProof using. intros. unfold fupdate. case_if*. Qed.\n\n(* Opaque fupdate. -- could be added in the future *)\n\n\n(* ********************************************************************** *)\n(** ** Function image *)\n\nSection FunctionImage.\nOpen Scope set_scope.\nImport LibList.\n\nDefinition image A B (f : A -> B) (E : set A) : set B :=\n  \\set{ y | exists_ x \\in E, y = f x }.\n\nLemma in_image_prove_eq : forall A B x (f : A -> B) (E : set A),\n  x \\in E -> f x \\in image f E.\nProof using. introv N. unfold image. rew_set. exists* x. Qed.\n\nLemma in_image_prove : forall A B x y (f : A -> B) (E : set A),\n  x \\in E -> y = f x -> y \\in image f E.\nProof using. intros. subst. applys* in_image_prove_eq. Qed.\n\nLemma in_image_inv : forall A B y (f : A -> B) (E : set A),\n  y \\in image f E -> exists x, x \\in E /\\ y = f x.\nProof using. introv N. unfolds image. rew_set in N. auto. Qed.\n\nLemma finite_image : forall A B (f : A -> B) (E : set A),\n  finite E ->\n  finite (image f E).\nProof using.\n  introv M. lets (L&H): finite_inv_list_covers M.\n  applys finite_of_list_covers (LibList.map f L). introv N.\n  lets (y&Hy&Ey): in_image_inv (rm N). subst x. applys* mem_map.\nQed.\n\nLemma image_covariant : forall A B (f : A -> B) (E F : set A),\n  E \\c F ->\n  image f E \\c image f F.\nProof using.\n  introv. do 2 rewrite incl_in_eq. introv M N.\n  lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\nQed.\n\nLemma image_union : forall A B (f : A -> B) (E F : set A),\n  image f (E \\u F) = image f E \\u image f F.\nProof using.\n  Hint Resolve in_image_prove.\n  introv. apply in_extens. intros x. iff N.\n    lets (y&Hy&Ey): in_image_inv (rm N). rewrite in_union_eq in Hy.\n     rewrite in_union_eq. destruct* Hy.\n    rewrite in_union_eq in N. destruct N as [N|N].\n      lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\n       rewrite in_union_eq. eauto.\n      lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\n       rewrite in_union_eq. eauto.\nQed.\n\nLemma image_singleton : forall A B (f : A -> B) (x : A),\n  image f \\{x} = \\{f x}.\nProof using.\n  intros. apply in_extens. intros z. rewrite in_single_eq. iff N.\n    lets (y&Hy&Ey): in_image_inv (rm N). rewrite in_single_eq in Hy. subst~.\n    applys* in_image_prove. rewrite~ @in_single_eq. typeclass.\nQed.\n\nEnd FunctionImage.\n\n#[global]\nHint Resolve finite_image : finite.\n\n\n(* ********************************************************************** *)\n(** ** Function preimage *)\n\nSection FunctionPreimage.\nOpen Scope set_scope.\n\nDefinition preimage A B (f : A -> B) (E : set B) : set A :=\n  \\set{ x | exists_ y \\in E, y = f x }.\n\nEnd FunctionPreimage.\n\n\n(* ********************************************************************** *)\n(** ** Function iteration *)\n\nFixpoint applyn A n (f : A -> A) x :=\n  match n with\n  | O => x\n  | S n' => f (applyn n' f x)\n  end.\n\nLemma applyn_fix : forall A n f (x : A),\n  applyn (S n) f x = applyn n f (f x).\nProof using. introv. induction~ n. simpls. rewrite~ IHn. Qed.\n\nLemma applyn_comp : forall A n m f (x : A),\n  applyn n f (applyn m f x) = applyn (n + m) f x.\nProof using.\n  introv. gen m; induction n; introv; simpls~.\n  rewrite~ IHn.\nQed.\n\nLemma applyn_nested : forall A n m f (x : A),\n  applyn n (applyn m f) x = applyn (n * m) f x.\nProof using.\n  introv. gen m. induction n; introv; simpls~.\n  rewrite IHn. rewrite~ applyn_comp.\nQed.\n\nLemma applyn_altern : forall A B (f : A -> B) (g : B -> A) x n,\n  applyn n (fun x => f (g x)) (f x) =\n    f (applyn n (fun x => g (f x)) x).\nProof using. introv. gen x. induction~ n. introv. repeat rewrite applyn_fix. autos~. Qed.\n\nLemma applyn_ind : forall A (P : A -> Prop) (f : A -> A) x n,\n  (forall x, P x -> P (f x)) ->\n  P x ->\n  P (applyn n f x).\nProof using. introv I. induction n; introv Hx; autos*. Qed.\n\n\n(* --TODO: rename applyn to iter *)\n(* --TODO: migrate iteration of functionals from LibFix to here *)\n", "meta": {"author": "charguer", "repo": "tlc", "sha": "590c8c8d80442376b8ac19198b7ed446cebc6934", "save_path": "github-repos/coq/charguer-tlc", "path": "github-repos/coq/charguer-tlc/tlc-590c8c8d80442376b8ac19198b7ed446cebc6934/src/LibFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.8670357735451835, "lm_q1q2_score": 0.7187195972305336}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrbool ssrfun ssrnat eqtype seq choice div fintype.\nFrom mathcomp\nRequire Import path bigop finset prime ssralg poly polydiv mxpoly.\nFrom mathcomp\nRequire Import generic_quotient countalg closed_field ssrnum ssrint rat intdiv.\nFrom mathcomp\nRequire Import algebraics_fundamentals.\n\n(******************************************************************************)\n(* This file provides an axiomatic construction of the algebraic numbers.     *)\n(* The construction only assumes the existence of an algebraically closed     *)\n(* filed with an automorphism of order 2; this amounts to the purely          *)\n(* algebraic contents of the Fundamenta Theorem of Algebra.                   *)\n(*       algC == the closed, countable field of algebraic numbers.            *)\n(*  algCeq, algCring, ..., algCnumField == structures for algC.               *)\n(* The ssrnum interfaces are implemented for algC as follows:                 *)\n(*     x <= y <=> (y - x) is a nonnegative real                               *)\n(*      x < y <=> (y - x) is a (strictly) positive real                       *)\n(*       `|z| == the complex norm of z, i.e., sqrtC (z * z^* ).               *)\n(*      Creal == the subset of real numbers (:= Num.real for algC).           *)\n(*         'i == the imaginary number (:= sqrtC (-1)).                        *)\n(*      'Re z == the real component of z.                                     *)\n(*      'Im z == the imaginary component of z.                                *)\n(*        z^* == the complex conjugate of z (:= conjC z).                     *)\n(*    sqrtC z == a nonnegative square root of z, i.e., 0 <= sqrt x if 0 <= x. *)\n(*  n.-root z == more generally, for n > 0, an nth root of z, chosen with a   *)\n(*               minimal non-negative argument for n > 1 (i.e., with a        *)\n(*               maximal real part subject to a nonnegative imaginary part).  *)\n(*               Note that n.-root (-1) is a primitive 2nth root of unity,    *)\n(*               an thus not equal to -1 for n odd > 1 (this will be shown in *)\n(*               file cyclotomic.v).                                          *)\n(* In addition, we provide:                                                   *)\n(*       Crat == the subset of rational numbers.                              *)\n(*       Cint == the subset of integers.                                      *)\n(*       Cnat == the subset of natural integers.                              *)\n(*  getCrat z == some a : rat such that ratr a = z, provided z \\in Crat.      *)\n(*   floorC z == for z \\in Creal, an m : int s.t. m%:~R <= z < (m + 1)%:~R.   *)\n(*   truncC z == for z >= 0, an n : nat s.t. n%:R <= z < n.+1%:R, else 0%N.   *)\n(* minCpoly z == the minimal (monic) polynomial over Crat with root z.        *)\n(* algC_invaut nu == an inverse of nu : {rmorphism algC -> algC}.             *)\n(*         (x %| y)%C <=> y is an integer (Cint) multiple of x; if x or y are *)\n(*        (x %| y)%Cx     of type nat or int they are coerced to algC here.   *)\n(*                        The (x %| y)%Cx display form is a workaround for    *)\n(*                        design limitations of the Coq Notation facilities.  *)\n(* (x == y %[mod z])%C <=> x and y differ by an integer (Cint) multiple of z; *)\n(*                as above, arguments of type nat or int are cast to algC.    *)\n(* (x != y %[mod z])%C <=> x and y do not differ by an integer multiple of z. *)\n(* Note that in file algnum we give an alternative definition of divisibility *)\n(* based on algebraic integers, overloading the notation in the %A scope.     *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n\n(* The Num mixin for an algebraically closed field with an automorphism of    *)\n(* order 2, making it into a field of complex numbers.                        *)\nLemma ComplexNumMixin (L : closedFieldType) (conj : {rmorphism L -> L}) :\n    involutive conj -> ~ conj =1 id ->\n  {numL | forall x : NumDomainType L numL, `|x| ^+ 2 = x * conj x}.\nProof.\nmove=> conjK conj_nt.\nhave nz2: 2%:R != 0 :> L.\n  apply/eqP=> char2; apply: conj_nt => e; apply/eqP/idPn=> eJ.\n  have opp_id x: - x = x :> L.\n    by apply/esym/eqP; rewrite -addr_eq0 -mulr2n -mulr_natl char2 mul0r.\n  have{char2} char2: 2 \\in [char L] by apply/eqP.\n  without loss{eJ} eJ: e / conj e = e + 1.\n    move/(_ (e / (e + conj e))); apply.\n    rewrite fmorph_div rmorphD conjK -{1}[conj e](addNKr e) mulrDl.\n    by rewrite opp_id (addrC e) divff // addr_eq0 opp_id.\n  pose a := e * conj e; have aJ: conj a = a by rewrite rmorphM conjK mulrC.\n  have [w Dw] := @solve_monicpoly _ 2 (nth 0 [:: e * a; - 1]) isT.\n  have{Dw} Dw: w ^+ 2 + w = e * a.\n    by rewrite Dw !big_ord_recl big_ord0 /= mulr1 mulN1r addr0 subrK.\n  pose b := w + conj w; have bJ: conj b = b by rewrite rmorphD conjK addrC.\n  have Db2: b ^+ 2 + b = a.\n    rewrite -Frobenius_autE // rmorphD addrACA Dw /= Frobenius_autE -rmorphX.\n    by rewrite -rmorphD Dw rmorphM aJ eJ -mulrDl -{1}[e]opp_id addKr mul1r.\n  have /eqP[] := oner_eq0 L; apply: (addrI b); rewrite addr0 -{2}bJ.\n  have: (b + e) * (b + conj e) == 0.\n    rewrite mulrDl 2!mulrDr -/a addrA addr_eq0 opp_id (mulrC e) -addrA.\n    by rewrite -mulrDr eJ addrAC -{2}[e]opp_id subrr add0r mulr1 Db2.\n  rewrite mulf_eq0 !addr_eq0 !opp_id => /pred2P[] -> //.\n  by rewrite {2}eJ rmorphD rmorph1.\nhave mul2I: injective (fun z : L => z *+ 2).\n  by move=> x y; rewrite /= -mulr_natl -(mulr_natl y) => /mulfI->.\npose sqrt x : L := sval (sig_eqW (@solve_monicpoly _ 2 (nth 0 [:: x]) isT)).\nhave sqrtK x: sqrt x ^+ 2 = x.\n  rewrite /sqrt; case: sig_eqW => /= y ->.\n  by rewrite !big_ord_recl big_ord0 /= mulr1 mul0r !addr0.\nhave sqrtE x y: y ^+ 2 = x -> {b : bool | y = (-1) ^+ b * sqrt x}.\n  move=> Dx; exists (y != sqrt x); apply/eqP; rewrite mulr_sign if_neg.\n  by case: ifPn => //; apply/implyP; rewrite implyNb -eqf_sqr Dx sqrtK.\npose i := sqrt (- 1).\nhave sqrMi x: (i * x) ^+ 2 = - x ^+ 2 by rewrite exprMn sqrtK mulN1r.\nhave iJ : conj i = - i.\n  have /sqrtE[b]: conj i ^+ 2 = - 1 by rewrite -rmorphX sqrtK rmorphN1.\n  rewrite mulr_sign -/i; case: b => // Ri.\n  case: conj_nt => z; wlog zJ: z / conj z = - z.\n    move/(_ (z - conj z)); rewrite !rmorphB conjK opprB => zJ.\n    by apply/mul2I/(canRL (subrK _)); rewrite -addrA zJ // addrC subrK.\n  have [-> | nz_z] := eqVneq z 0; first exact: rmorph0.\n  have [u Ru [v Rv Dz]]:\n    exists2 u, conj u = u & exists2 v, conj v = v & (u + z * v) ^+ 2 = z.\n  - pose y := sqrt z; exists ((y + conj y) / 2%:R).\n      by rewrite fmorph_div rmorphD conjK addrC rmorph_nat.\n    exists ((y - conj y) / (z *+ 2)).\n      rewrite fmorph_div rmorphMn zJ mulNrn invrN mulrN -mulNr rmorphB opprB.\n      by rewrite conjK.\n    rewrite -(mulr_natl z) invfM (mulrC z) !mulrA divfK // -mulrDl addrACA.\n    by rewrite subrr addr0 -mulr2n -mulr_natr mulfK ?Neq0 ?sqrtK.\n  suffices u0: u = 0 by rewrite -Dz u0 add0r rmorphX rmorphM Rv zJ mulNr sqrrN.\n  suffices [b Du]: exists b : bool, u = (-1) ^+ b * i * z * v.\n    apply: mul2I; rewrite mul0rn mulr2n -{2}Ru.\n    by rewrite Du !rmorphM rmorph_sign Rv Ri zJ !mulrN mulNr subrr.\n  have/eqP:= zJ; rewrite -addr_eq0 -{1 2}Dz rmorphX rmorphD rmorphM Ru Rv zJ.\n  rewrite mulNr sqrrB sqrrD addrACA (addrACA (u ^+ 2)) addNr addr0 -!mulr2n.\n  rewrite -mulrnDl -(mul0rn _ 2) (inj_eq mul2I) /= -[rhs in _ + rhs]opprK.\n  rewrite -sqrMi subr_eq0 eqf_sqr -mulNr !mulrA.\n  by case/pred2P=> ->; [exists false | exists true]; rewrite mulr_sign.\npose norm x := sqrt x * conj (sqrt x).\nhave normK x : norm x ^+ 2 = x * conj x by rewrite exprMn -rmorphX sqrtK.\nhave normE x y : y ^+ 2 = x -> norm x = y * conj y.\n  rewrite /norm => /sqrtE[b /(canLR (signrMK b)) <-].\n  by rewrite !rmorphM rmorph_sign mulrACA -mulrA signrMK.\nhave norm_eq0 x : norm x = 0 -> x = 0.\n  by move/eqP; rewrite mulf_eq0 fmorph_eq0 -mulf_eq0 -expr2 sqrtK => /eqP.\nhave normM x y : norm (x * y) = norm x * norm y.\n  by rewrite mulrACA -rmorphM; apply: normE; rewrite exprMn !sqrtK.\nhave normN x : norm (- x) = norm x.\n  by rewrite -mulN1r normM {1}/norm iJ mulrN -expr2 sqrtK opprK mul1r.\npose le x y := norm (y - x) == y - x; pose lt x y := (y != x) && le x y.\nhave posE x: le 0 x = (norm x == x) by rewrite /le subr0.\nhave leB x y: le x y = le 0 (y - x) by rewrite posE.\nhave posP x : reflect (exists y, x = y * conj y) (le 0 x).\n  rewrite posE; apply: (iffP eqP) => [Dx | [y {x}->]]; first by exists (sqrt x).\n  by rewrite (normE _ _ (normK y)) rmorphM conjK (mulrC (conj _)) -expr2 normK.\nhave posJ x : le 0 x -> conj x = x.\n  by case/posP=> {x}u ->; rewrite rmorphM conjK mulrC.\nhave pos_linear x y : le 0 x -> le 0 y -> le x y || le y x.\n  move=> pos_x pos_y; rewrite leB -opprB orbC leB !posE normN -eqf_sqr.\n  by rewrite normK rmorphB !posJ ?subrr.\nhave sposDl x y : lt 0 x -> le 0 y -> lt 0 (x + y).\n  have sqrtJ z : le 0 z -> conj (sqrt z) = sqrt z.\n    rewrite posE -{2}[z]sqrtK -subr_eq0 -mulrBr mulf_eq0 subr_eq0.\n    by case/pred2P=> ->; rewrite ?rmorph0.\n  case/andP=> nz_x /sqrtJ uJ /sqrtJ vJ.\n  set u := sqrt x in uJ; set v := sqrt y in vJ; pose w := u + i * v.\n  have ->: x + y = w * conj w.\n    rewrite rmorphD rmorphM iJ uJ vJ mulNr mulrC -subr_sqr sqrMi opprK.\n    by rewrite !sqrtK.\n  apply/andP; split; last by apply/posP; exists w.\n  rewrite -normK expf_eq0 //=; apply: contraNneq nz_x => /norm_eq0 w0.\n  rewrite -[x]sqrtK expf_eq0 /= -/u -(inj_eq mul2I) !mulr2n -{2}(rmorph0 conj).\n  by rewrite -w0 rmorphD rmorphM iJ uJ vJ mulNr addrACA subrr addr0.\nhave sposD x y : lt 0 x -> lt 0 y -> lt 0 (x + y).\n  by move=> x_gt0 /andP[_]; apply: sposDl.\nhave normD x y : le (norm (x + y)) (norm x + norm y).\n  have sposM u v: lt 0 u -> le 0 (u * v) -> le 0 v.\n    by rewrite /lt !posE normM andbC => /andP[/eqP-> /mulfI/inj_eq->].\n  have posD u v: le 0 u -> le 0 v -> le 0 (u + v).\n    have [-> | nz_u u_ge0 v_ge0] := eqVneq u 0; first by rewrite add0r.\n    by have /andP[]: lt 0 (u + v) by rewrite sposDl // /lt nz_u.\n  have le_sqr u v: conj u = u -> le 0 v -> le (u ^+ 2) (v ^+ 2) -> le u v.\n    move=> Ru v_ge0; have [-> // | nz_u] := eqVneq u 0.\n    have [u_gt0 | u_le0 _] := boolP (lt 0 u).\n      by rewrite leB (leB u) subr_sqr mulrC addrC; apply: sposM; apply: sposDl.\n    rewrite leB posD // posE normN -addr_eq0; apply/eqP.\n    rewrite /lt nz_u posE -subr_eq0 in u_le0; apply: (mulfI u_le0).\n    by rewrite mulr0 -subr_sqr normK Ru subrr.\n  have pos_norm z: le 0 (norm z) by apply/posP; exists (sqrt z).\n  rewrite le_sqr ?posJ ?posD // sqrrD !normK -normM rmorphD mulrDl !mulrDr.\n  rewrite addrA addrC !addrA -(addrC (y * conj y)) !addrA.\n  move: (y * _ + _) => u; rewrite -!addrA leB opprD addrACA {u}subrr add0r -leB.\n  rewrite {}le_sqr ?posD //.\n    by rewrite rmorphD !rmorphM !conjK addrC mulrC (mulrC y).\n  rewrite -mulr2n -mulr_natr exprMn normK -natrX mulr_natr sqrrD mulrACA.\n  rewrite -rmorphM (mulrC y x) addrAC leB mulrnA mulr2n opprD addrACA.\n  rewrite subrr addr0 {2}(mulrC x) rmorphM mulrACA -opprB addrAC -sqrrB -sqrMi.\n  apply/posP; exists (i * (x * conj y - y * conj x)); congr (_ * _).\n  rewrite !(rmorphM, rmorphB) iJ !conjK mulNr -mulrN opprB.\n  by rewrite (mulrC x) (mulrC y).\nby exists (Num.Mixin normD sposD norm_eq0 pos_linear normM (rrefl _) (rrefl _)).\nQed.\n\nModule Algebraics.\n\nModule Type Specification.\n\nParameter type : Type.\n\nParameter eqMixin : Equality.class_of type.\nCanonical eqType := EqType type eqMixin.\n\nParameter choiceMixin : Choice.mixin_of type.\nCanonical choiceType := ChoiceType type choiceMixin.\n\nParameter countMixin : Countable.mixin_of type.\nCanonical countType := CountType type countMixin.\n\nParameter zmodMixin : GRing.Zmodule.mixin_of type.\nCanonical zmodType := ZmodType type zmodMixin.\nCanonical countZmodType := [countZmodType of type].\n\nParameter ringMixin : GRing.Ring.mixin_of zmodType.\nCanonical ringType := RingType type ringMixin.\nCanonical countRingType := [countRingType of type].\n\nParameter unitRingMixin : GRing.UnitRing.mixin_of ringType.\nCanonical unitRingType := UnitRingType type unitRingMixin.\n\nAxiom mulC : @commutative ringType ringType *%R.\nCanonical comRingType := ComRingType type mulC.\nCanonical comUnitRingType := [comUnitRingType of type].\n\nAxiom idomainAxiom : GRing.IntegralDomain.axiom ringType.\nCanonical idomainType := IdomainType type idomainAxiom.\n\nAxiom fieldMixin : GRing.Field.mixin_of unitRingType.\nCanonical fieldType := FieldType type fieldMixin.\n\nParameter decFieldMixin : GRing.DecidableField.mixin_of unitRingType.\nCanonical decFieldType := DecFieldType type decFieldMixin.\n\nAxiom closedFieldAxiom : GRing.ClosedField.axiom ringType.\nCanonical closedFieldType := ClosedFieldType type closedFieldAxiom.\n\nParameter numMixin : Num.mixin_of ringType.\nCanonical numDomainType := NumDomainType type numMixin.\nCanonical numFieldType := [numFieldType of type].\n\nParameter conjMixin : Num.ClosedField.imaginary_mixin_of numDomainType.\nCanonical numClosedFieldType := NumClosedFieldType type conjMixin.\n\nAxiom algebraic : integralRange (@ratr unitRingType).\n\nEnd Specification.\n\nModule Implementation : Specification.\n\nDefinition L := tag Fundamental_Theorem_of_Algebraics.\n\nDefinition conjL : {rmorphism L -> L} :=\n  s2val (tagged Fundamental_Theorem_of_Algebraics).\n\nFact conjL_K : involutive conjL.\nProof. exact: s2valP (tagged Fundamental_Theorem_of_Algebraics). Qed.\n\nFact conjL_nt : ~ conjL =1 id.\nProof. exact: s2valP' (tagged Fundamental_Theorem_of_Algebraics). Qed.\n\nDefinition LnumMixin := ComplexNumMixin conjL_K conjL_nt.\nDefinition Lnum := NumDomainType L (sval LnumMixin).\n\nDefinition QtoL := [rmorphism of @ratr [numFieldType of Lnum]].\nNotation pQtoL := (map_poly QtoL).\n\nDefinition rootQtoL p_j :=\n  if p_j.1 == 0 then 0 else\n  (sval (closed_field_poly_normal (pQtoL p_j.1)))`_p_j.2.\n\nDefinition eq_root p_j q_k := rootQtoL p_j == rootQtoL q_k.\nFact eq_root_is_equiv : equiv_class_of eq_root.\nProof. by rewrite /eq_root; split=> [ ? | ? ? | ? ? ? ] // /eqP->. Qed.\nCanonical eq_root_equiv := EquivRelPack eq_root_is_equiv.\nDefinition type : Type := {eq_quot eq_root}%qT.\n\nDefinition eqMixin : Equality.class_of type := EquivQuot.eqMixin _.\nCanonical eqType := EqType type eqMixin.\n\nDefinition choiceMixin : Choice.mixin_of type := EquivQuot.choiceMixin _.\nCanonical choiceType := ChoiceType type choiceMixin.\n\nDefinition countMixin : Countable.mixin_of type := CanCountMixin reprK.\nCanonical countType := CountType type countMixin.\n\nDefinition CtoL (u : type) := rootQtoL (repr u).\n\nFact CtoL_inj : injective CtoL.\nProof. by move=> u v /eqP eq_uv; rewrite -[u]reprK -[v]reprK; apply/eqmodP. Qed.\n\nFact CtoL_P u : integralOver QtoL (CtoL u).\nProof.\nrewrite /CtoL /rootQtoL; case: (repr u) => p j /=.\ncase: (closed_field_poly_normal _) => r Dp /=.\ncase: ifPn => [_ | nz_p]; first exact: integral0.\nhave [/(nth_default 0)-> | lt_j_r] := leqP (size r) j; first exact: integral0.\napply/integral_algebraic; exists p; rewrite // Dp -mul_polyC rootM orbC.\nby rewrite root_prod_XsubC mem_nth.\nQed.\n\nFact LtoC_subproof z : integralOver QtoL z -> {u | CtoL u = z}.\nProof.\ncase/sig2_eqW=> p mon_p pz0; rewrite /CtoL.\npose j := index z (sval (closed_field_poly_normal (pQtoL p))).\npose u := \\pi_type%qT (p, j); exists u; have /eqmodP/eqP-> := reprK u.\nrewrite /rootQtoL -if_neg monic_neq0 //; apply: nth_index => /=.\ncase: (closed_field_poly_normal _) => r /= Dp.\nby rewrite Dp (monicP _) ?(monic_map QtoL) // scale1r root_prod_XsubC in pz0.\nQed.\n\nDefinition LtoC z Az := sval (@LtoC_subproof z Az).\nFact LtoC_K z Az : CtoL (@LtoC z Az) = z.\nProof. exact: (svalP (LtoC_subproof Az)). Qed.\n\nFact CtoL_K u : LtoC (CtoL_P u) = u.\nProof. by apply: CtoL_inj; rewrite LtoC_K. Qed.\n\nDefinition zero := LtoC (integral0 _).\nDefinition add u v := LtoC (integral_add (CtoL_P u) (CtoL_P v)).\nDefinition opp u := LtoC (integral_opp (CtoL_P u)).\n\nFact addA : associative add.\nProof. by move=> u v w; apply: CtoL_inj; rewrite !LtoC_K addrA. Qed.\n\nFact addC : commutative add.\nProof. by move=> u v; apply: CtoL_inj; rewrite !LtoC_K addrC. Qed.\n\nFact add0 : left_id zero add.\nProof. by move=> u; apply: CtoL_inj; rewrite !LtoC_K add0r. Qed.\n\nFact addN : left_inverse zero opp add.\nProof. by move=> u; apply: CtoL_inj; rewrite !LtoC_K addNr. Qed.\n\nDefinition zmodMixin := ZmodMixin addA addC add0 addN.\nCanonical zmodType := ZmodType type zmodMixin.\nCanonical countZmodType := [countZmodType of type].\n\nFact CtoL_is_additive : additive CtoL.\nProof. by move=> u v; rewrite !LtoC_K. Qed.\nCanonical CtoL_additive := Additive CtoL_is_additive.\n\nDefinition one := LtoC (integral1 _).\nDefinition mul u v := LtoC (integral_mul (CtoL_P u) (CtoL_P v)).\nDefinition inv u := LtoC (integral_inv (CtoL_P u)).\n\nFact mulA : associative mul.\nProof. by move=> u v w; apply: CtoL_inj; rewrite !LtoC_K mulrA. Qed.\n\nFact mulC : commutative mul.\nProof. by move=> u v; apply: CtoL_inj; rewrite !LtoC_K mulrC. Qed.\n\nFact mul1 : left_id one mul.\nProof. by move=> u; apply: CtoL_inj; rewrite !LtoC_K mul1r. Qed.\n\nFact mulD : left_distributive mul +%R.\nProof. by move=> u v w; apply: CtoL_inj; rewrite !LtoC_K mulrDl. Qed.\n\nFact one_nz : one != 0 :> type.\nProof. by rewrite -(inj_eq CtoL_inj) !LtoC_K oner_eq0. Qed.\n\nDefinition ringMixin := ComRingMixin mulA mulC mul1 mulD one_nz.\nCanonical ringType := RingType type ringMixin.\nCanonical comRingType := ComRingType type mulC.\nCanonical countRingType := [countRingType of type].\n\nFact CtoL_is_multiplicative : multiplicative CtoL.\nProof. by split=> [u v|]; rewrite !LtoC_K. Qed.\nCanonical CtoL_rmorphism := AddRMorphism CtoL_is_multiplicative.\n\nFact mulVf : GRing.Field.axiom inv.\nProof.\nmove=> u; rewrite -(inj_eq CtoL_inj) rmorph0 => nz_u.\nby apply: CtoL_inj; rewrite !LtoC_K mulVf.\nQed.\nFact inv0 : inv 0 = 0. Proof. by apply: CtoL_inj; rewrite !LtoC_K invr0. Qed.\n\nDefinition unitRingMixin := FieldUnitMixin mulVf inv0.\nCanonical unitRingType := UnitRingType type unitRingMixin.\nCanonical comUnitRingType := [comUnitRingType of type].\n\nDefinition fieldMixin := FieldMixin mulVf inv0.\nDefinition idomainAxiom := FieldIdomainMixin fieldMixin.\nCanonical idomainType := IdomainType type idomainAxiom.\nCanonical fieldType := FieldType type fieldMixin.\n\nFact closedFieldAxiom : GRing.ClosedField.axiom ringType.\nProof.\nmove=> n a n_gt0; pose p := 'X^n - \\poly_(i < n) CtoL (a i).\nhave Ap: {in p : seq L, integralRange QtoL}.\n  move=> _ /(nthP 0)[j _ <-]; rewrite coefB coefXn coef_poly.\n  apply: integral_sub; first exact: integral_nat.\n  by case: ifP => _; [apply: CtoL_P | apply: integral0].\nhave sz_p: size p = n.+1.\n  by rewrite size_addl size_polyXn // size_opp ltnS size_poly.\nhave [z pz0]: exists z, root p z by apply/closed_rootP; rewrite sz_p eqSS -lt0n.\nhave Az: integralOver ratr z.\n  by apply: integral_root Ap; rewrite // -size_poly_gt0 sz_p.\nexists (LtoC Az); apply/CtoL_inj; rewrite -[CtoL _]subr0 -(rootP pz0).\nrewrite rmorphX /= LtoC_K hornerD hornerXn hornerN opprD addNKr opprK.\nrewrite horner_poly rmorph_sum; apply: eq_bigr => k _.\nby rewrite rmorphM rmorphX /= LtoC_K.\nQed.\n\nDefinition decFieldMixin := closed_field_QEMixin closedFieldAxiom.\nCanonical decFieldType := DecFieldType type decFieldMixin.\nCanonical closedFieldType := ClosedFieldType type closedFieldAxiom.\n\nFact conj_subproof u : integralOver QtoL (conjL (CtoL u)).\nProof.\nhave [p mon_p pu0] := CtoL_P u; exists p => //.\nrewrite -(fmorph_root conjL) conjL_K map_poly_id // => _ /(nthP 0)[j _ <-].\nby rewrite coef_map fmorph_rat.\nQed.\nFact conj_is_rmorphism : rmorphism (fun u => LtoC (conj_subproof u)).\nProof.\ndo 2?split=> [u v|]; apply: CtoL_inj; last by rewrite !LtoC_K rmorph1.\n- by rewrite LtoC_K 3!{1}rmorphB /= !LtoC_K.\nby rewrite LtoC_K 3!{1}rmorphM /= !LtoC_K.\nQed.\nDefinition conj : {rmorphism type -> type} := RMorphism conj_is_rmorphism.\nLemma conjK : involutive conj.\nProof. by move=> u; apply: CtoL_inj; rewrite !LtoC_K conjL_K. Qed.\n\nFact conj_nt : ~ conj =1 id.\nProof.\nhave [i i2]: exists i : type, i ^+ 2 = -1.\n  have [i] := @solve_monicpoly _ 2 (nth 0 [:: -1 : type]) isT.\n  by rewrite !big_ord_recl big_ord0 /= mul0r mulr1 !addr0; exists i.\nmove/(_ i)/(congr1 CtoL); rewrite LtoC_K => iL_J.\nhave/ltr_geF/idP[] := @ltr01 Lnum; rewrite -oppr_ge0 -(rmorphN1 CtoL_rmorphism).\nrewrite -i2 rmorphX /= expr2 -{2}iL_J -(svalP LnumMixin).\nby rewrite exprn_ge0 ?normr_ge0.\nQed.\n\nDefinition numMixin := sval (ComplexNumMixin conjK conj_nt).\nCanonical numDomainType := NumDomainType type numMixin.\nCanonical numFieldType := [numFieldType of type].\n\nLemma normK u : `|u| ^+ 2 = u * conj u.\nProof. exact: svalP (ComplexNumMixin conjK conj_nt) u. Qed.\n\nLemma algebraic : integralRange (@ratr unitRingType).\nProof.\nmove=> u; have [p mon_p pu0] := CtoL_P u; exists p => {mon_p}//.\nrewrite -(fmorph_root CtoL_rmorphism) -map_poly_comp; congr (root _ _): pu0.\nby apply/esym/eq_map_poly; apply: fmorph_eq_rat.\nQed.\n\nDefinition conjMixin :=\n  ImaginaryMixin (svalP (imaginary_exists closedFieldType))\n                 (fun x => esym (normK x)).\nCanonical numClosedFieldType := NumClosedFieldType type conjMixin.\n\nEnd Implementation.\n\nDefinition divisor := Implementation.type.\n\nModule Internals.\n\nImport Implementation.\n\nLocal Notation algC := type.\nLocal Notation \"z ^*\" := (conj z) (at level 2, format \"z ^*\") : ring_scope.\nLocal Notation QtoC := (ratr : rat -> algC).\nLocal Notation QtoCm := [rmorphism of QtoC].\nLocal Notation pQtoC := (map_poly QtoC).\nLocal Notation ZtoQ := (intr : int -> rat).\nLocal Notation ZtoC := (intr : int -> algC).\nLocal Notation Creal := (Num.real : qualifier 0 algC).\n\nFact algCi_subproof : {i : algC | i ^+ 2 = -1}.\nProof. exact: GRing.imaginary_exists. Qed.\n\nVariant getCrat_spec : Type := GetCrat_spec CtoQ of cancel QtoC CtoQ.\n\nFact getCrat_subproof : getCrat_spec.\nProof.\nhave isQ := rat_algebraic_decidable algebraic.\nexists (fun z => if isQ z is left Qz then sval (sig_eqW Qz) else 0) => a.\ncase: (isQ _) => [Qa | []]; last by exists a.\nby case: (sig_eqW _) => b /= /fmorph_inj.\nQed.\n\nFact floorC_subproof x : {m | x \\is Creal -> ZtoC m <= x < ZtoC (m + 1)}.\nProof.\nhave [Rx | _] := boolP (x \\is Creal); last by exists 0.\nwithout loss x_ge0: x Rx / x >= 0.\n  have [x_ge0 | /ltrW x_le0] := real_ger0P Rx; first exact.\n  case/(_ (- x)) => [||m /(_ isT)]; rewrite ?rpredN ?oppr_ge0 //.\n  rewrite ler_oppr ltr_oppl -!rmorphN opprD /= ltr_neqAle ler_eqVlt.\n  case: eqP => [-> _ | _ /and3P[lt_x_m _ le_m_x]].\n    by exists (- m) => _; rewrite lerr rmorphD ltr_addl ltr01.\n  by exists (- m - 1); rewrite le_m_x subrK.\nhave /ex_minnP[n lt_x_n1 min_n]: exists n, x < n.+1%:R.\n  have [n le_x_n] := rat_algebraic_archimedean algebraic x.\n  by exists n; rewrite -(ger0_norm x_ge0) (ltr_trans le_x_n) ?ltr_nat.\nexists n%:Z => _; rewrite addrC -intS lt_x_n1 andbT.\ncase Dn: n => // [n1]; rewrite -Dn.\nhave [||//|] := @real_lerP _ n%:R x; rewrite ?rpred_nat //.\nby rewrite Dn => /min_n; rewrite Dn ltnn.\nQed.\n\nFact minCpoly_subproof (x : algC) :\n  {p | p \\is monic & forall q, root (pQtoC q) x = (p %| q)%R}.\nProof.\nhave isQ := rat_algebraic_decidable algebraic.\nhave [p [mon_p px0 irr_p]] := minPoly_decidable_closure isQ (algebraic x).\nexists p => // q; apply/idP/idP=> [qx0 | /dvdpP[r ->]]; last first.\n  by rewrite rmorphM rootM px0 orbT.\nsuffices /eqp_dvdl <-: gcdp p q %= p by apply: dvdp_gcdr.\nrewrite irr_p ?dvdp_gcdl ?gtn_eqF // -(size_map_poly QtoCm) gcdp_map /=.\nrewrite (@root_size_gt1 _ x) ?root_gcd ?px0 //.\nby rewrite gcdp_eq0 negb_and map_poly_eq0 monic_neq0.\nQed.\n\nDefinition algC_divisor (x : algC) := x : divisor.\nDefinition int_divisor m := m%:~R : divisor.\nDefinition nat_divisor n := n%:R : divisor.\n\nEnd Internals.\n\nModule Import Exports.\n\nImport Implementation Internals.\n\nNotation algC := type.\nDelimit Scope C_scope with C.\nDelimit Scope C_core_scope with Cc.\nDelimit Scope C_expanded_scope with Cx.\nOpen Scope C_core_scope.\n\nCanonical eqType.\nCanonical choiceType.\nCanonical countType.\nCanonical zmodType.\nCanonical countZmodType.\nCanonical ringType.\nCanonical countRingType.\nCanonical unitRingType.\nCanonical comRingType.\nCanonical comUnitRingType.\nCanonical idomainType.\nCanonical numDomainType.\nCanonical fieldType.\nCanonical numFieldType.\nCanonical decFieldType.\nCanonical closedFieldType.\nCanonical numClosedFieldType.\n\nNotation algCeq := eqType.\nNotation algCzmod := zmodType.\nNotation algCring := ringType.\nNotation algCuring := unitRingType.\nNotation algCnum := numDomainType.\nNotation algCfield := fieldType.\nNotation algCnumField := numFieldType.\nNotation algCnumClosedField := numClosedFieldType.\n\nNotation Creal := (@Num.Def.Rreal numDomainType).\n\nDefinition getCrat := let: GetCrat_spec CtoQ _ := getCrat_subproof in CtoQ.\nDefinition Crat : pred_class := fun x : algC => ratr (getCrat x) == x.\n\nDefinition floorC x := sval (floorC_subproof x).\nDefinition Cint : pred_class := fun x : algC => (floorC x)%:~R == x.\n\nDefinition truncC x := if x >= 0 then `|floorC x|%N else 0%N.\nDefinition Cnat : pred_class := fun x : algC => (truncC x)%:R == x.\n\nDefinition minCpoly x : {poly algC} :=\n  let: exist2 p _ _ := minCpoly_subproof x in map_poly ratr p.\n\nCoercion nat_divisor : nat >-> divisor.\nCoercion int_divisor : int >-> divisor.\nCoercion algC_divisor : algC >-> divisor.\n\nLemma nCdivE (p : nat) : p = p%:R :> divisor. Proof. by []. Qed.\nLemma zCdivE (p : int) : p = p%:~R :> divisor. Proof. by []. Qed.\nDefinition CdivE := (nCdivE, zCdivE).\n\nDefinition dvdC (x : divisor) : pred_class :=\n   fun y : algC => if x == 0 then y == 0 else y / x \\in Cint.\nNotation \"x %| y\" := (y \\in dvdC x) : C_expanded_scope.\nNotation \"x %| y\" := (@in_mem divisor y (mem (dvdC x))) : C_scope.\n\nDefinition eqCmod (e x y : divisor) := (e %| x - y)%C.\n\nNotation \"x == y %[mod e ]\" := (eqCmod e x y) : C_scope.\nNotation \"x != y %[mod e ]\" := (~~ (x == y %[mod e])%C) : C_scope.\n\nEnd Exports.\n\nEnd Algebraics.\n\nExport Algebraics.Exports.\n\nSection AlgebraicsTheory.\n\nImplicit Types (x y z : algC) (n : nat) (m : int) (b : bool).\nImport Algebraics.Internals.\n\nLocal Notation ZtoQ := (intr : int -> rat).\nLocal Notation ZtoC := (intr : int -> algC).\nLocal Notation QtoC := (ratr : rat -> algC).\nLocal Notation QtoCm := [rmorphism of QtoC].\nLocal Notation CtoQ := getCrat.\nLocal Notation intrp := (map_poly intr).\nLocal Notation pZtoQ := (map_poly ZtoQ).\nLocal Notation pZtoC := (map_poly ZtoC).\nLocal Notation pQtoC := (map_poly ratr).\n\nLocal Hint Resolve (intr_inj : injective ZtoC) : core.\n\n(* Specialization of a few basic ssrnum order lemmas. *)\n\nDefinition eqC_nat n p : (n%:R == p%:R :> algC) = (n == p) := eqr_nat _ n p.\nDefinition leC_nat n p : (n%:R <= p%:R :> algC) = (n <= p)%N := ler_nat _ n p.\nDefinition ltC_nat n p : (n%:R < p%:R :> algC) = (n < p)%N := ltr_nat _ n p.\nDefinition Cchar : [char algC] =i pred0 := @char_num _.\n\n(* This can be used in the converse direction to evaluate assertions over     *)\n(* manifest rationals, such as 3%:R^-1 + 7%:%^-1 < 2%:%^-1 :> algC.           *)\n(* Missing norm and integer exponent, due to gaps in ssrint and rat.          *)\nDefinition CratrE :=\n  let CnF := Algebraics.Implementation.numFieldType in\n  let QtoCm := ratr_rmorphism CnF in\n  ((rmorph0 QtoCm, rmorph1 QtoCm, rmorphMn QtoCm, rmorphN QtoCm, rmorphD QtoCm),\n   (rmorphM QtoCm, rmorphX QtoCm, fmorphV QtoCm),\n   (rmorphMz QtoCm, rmorphXz QtoCm, @ratr_norm CnF, @ratr_sg CnF),\n   =^~ (@ler_rat CnF, @ltr_rat CnF, (inj_eq (fmorph_inj QtoCm)))).\n\nDefinition CintrE :=\n  let CnF := Algebraics.Implementation.numFieldType in\n  let ZtoCm := intmul1_rmorphism CnF in\n  ((rmorph0 ZtoCm, rmorph1 ZtoCm, rmorphMn ZtoCm, rmorphN ZtoCm, rmorphD ZtoCm),\n   (rmorphM ZtoCm, rmorphX ZtoCm),\n   (rmorphMz ZtoCm, @intr_norm CnF, @intr_sg CnF),\n   =^~ (@ler_int CnF, @ltr_int CnF, (inj_eq (@intr_inj CnF)))).\n\nLet nz2 : 2%:R != 0 :> algC. Proof. by rewrite -!CintrE. Qed.\n\n(* Conjugation and norm. *)\n\nDefinition algC_algebraic x := Algebraics.Implementation.algebraic x.\n\n(* Real number subset. *)\n\nLemma Creal0 : 0 \\is Creal. Proof. exact: rpred0. Qed.\nLemma Creal1 : 1 \\is Creal. Proof. exact: rpred1. Qed.\n(* Trivial cannot resolve a general real0 hint. *)\nHint Resolve Creal0 Creal1 : core. \n\nLemma algCrect x : x = 'Re x + 'i * 'Im x.\nProof. by rewrite [LHS]Crect. Qed.\n\nLemma algCreal_Re x : 'Re x \\is Creal.\nProof. by rewrite Creal_Re. Qed.\n\nLemma algCreal_Im x : 'Im x \\is Creal.\nProof. by rewrite Creal_Im. Qed.\nHint Resolve algCreal_Re algCreal_Im : core.\n\n(* Integer subset. *)\n(* Not relying on the undocumented interval library, for now. *)\n\nLemma floorC_itv x : x \\is Creal -> (floorC x)%:~R <= x < (floorC x + 1)%:~R.\nProof. by rewrite /floorC => Rx; case: (floorC_subproof x) => //= m; apply. Qed.\n\nLemma floorC_def x m : m%:~R <= x < (m + 1)%:~R -> floorC x = m.\nProof.\ncase/andP=> lemx ltxm1; apply/eqP; rewrite eqr_le -!ltz_addr1.\nhave /floorC_itv/andP[lefx ltxf1]: x \\is Creal.\n  by rewrite -[x](subrK m%:~R) rpredD ?realz ?ler_sub_real.\nby rewrite -!(ltr_int [numFieldType of algC]) 2?(@ler_lt_trans _ x).\nQed.\n\nLemma intCK : cancel intr floorC.\nProof.\nby move=> m; apply: floorC_def; rewrite ler_int ltr_int ltz_addr1 lerr.\nQed.\n\nLemma floorCK : {in Cint, cancel floorC intr}. Proof. by move=> z /eqP. Qed.\n\nLemma floorC0 : floorC 0 = 0. Proof. exact: (intCK 0). Qed.\nLemma floorC1 : floorC 1 = 1. Proof. exact: (intCK 1). Qed.\nHint Resolve floorC0 floorC1 : core.\n\nLemma floorCpK (p : {poly algC}) :\n  p \\is a polyOver Cint -> map_poly intr (map_poly floorC p) = p.\nProof.\nmove/(all_nthP 0)=> Zp; apply/polyP=> i.\nrewrite coef_map coef_map_id0 //= -[p]coefK coef_poly.\nby case: ifP => [/Zp/floorCK // | _]; rewrite floorC0.\nQed.\n\nLemma floorCpP (p : {poly algC}) :\n  p \\is a polyOver Cint -> {q | p = map_poly intr q}.\nProof. by exists (map_poly floorC p); rewrite floorCpK. Qed.\n\nLemma Cint_int m : m%:~R \\in Cint.\nProof. by rewrite unfold_in intCK. Qed.\n\nLemma CintP x : reflect (exists m, x = m%:~R) (x \\in Cint).\nProof.\nby apply: (iffP idP) => [/eqP<-|[m ->]]; [exists (floorC x) | apply: Cint_int].\nQed.\n\nLemma floorCD : {in Cint & Creal, {morph floorC : x y / x + y}}.\nProof.\nmove=> _ y /CintP[m ->] Ry; apply: floorC_def.\nby rewrite -addrA 2!rmorphD /= intCK ler_add2l ltr_add2l floorC_itv.\nQed.\n\nLemma floorCN : {in Cint, {morph floorC : x / - x}}.\nProof. by move=> _ /CintP[m ->]; rewrite -rmorphN !intCK. Qed.\n\nLemma floorCM : {in Cint &, {morph floorC : x y / x * y}}.\nProof. by move=> _ _ /CintP[m1 ->] /CintP[m2 ->]; rewrite -rmorphM !intCK. Qed.\n\nLemma floorCX n : {in Cint, {morph floorC : x / x ^+ n}}.\nProof. by move=> _ /CintP[m ->]; rewrite -rmorphX !intCK. Qed.\n\nLemma rpred_Cint S (ringS : subringPred S) (kS : keyed_pred ringS) x :\n  x \\in Cint -> x \\in kS.\nProof. by case/CintP=> m ->; apply: rpred_int. Qed.\n\nLemma Cint0 : 0 \\in Cint. Proof. exact: (Cint_int 0). Qed.\nLemma Cint1 : 1 \\in Cint. Proof. exact: (Cint_int 1). Qed.\nHint Resolve Cint0 Cint1 : core.\n\nFact Cint_key : pred_key Cint. Proof. by []. Qed.\nFact Cint_subring : subring_closed Cint.\nProof.\nby split=> // _ _ /CintP[m ->] /CintP[p ->];\n    rewrite -(rmorphB, rmorphM) Cint_int.\nQed.\nCanonical Cint_keyed := KeyedPred Cint_key.\nCanonical Cint_opprPred := OpprPred Cint_subring.\nCanonical Cint_addrPred := AddrPred Cint_subring.\nCanonical Cint_mulrPred := MulrPred Cint_subring.\nCanonical Cint_zmodPred := ZmodPred Cint_subring.\nCanonical Cint_semiringPred := SemiringPred Cint_subring.\nCanonical Cint_smulrPred := SmulrPred Cint_subring.\nCanonical Cint_subringPred := SubringPred Cint_subring.\n\nLemma Creal_Cint : {subset Cint <= Creal}.\nProof. by move=> _ /CintP[m ->]; apply: realz. Qed.\n\nLemma conj_Cint x : x \\in Cint -> x^* = x.\nProof. by move/Creal_Cint/conj_Creal. Qed.\n\nLemma Cint_normK x : x \\in Cint -> `|x| ^+ 2 = x ^+ 2.\nProof. by move/Creal_Cint/real_normK. Qed.\n\nLemma CintEsign x : x \\in Cint -> x = (-1) ^+ (x < 0)%C * `|x|.\nProof. by move/Creal_Cint/realEsign. Qed.\n\n(* Natural integer subset. *)\n\nLemma truncC_itv x : 0 <= x -> (truncC x)%:R <= x < (truncC x).+1%:R.\nProof.\nmove=> x_ge0; have /andP[lemx ltxm1] := floorC_itv (ger0_real x_ge0).\nrewrite /truncC x_ge0 -addn1 !pmulrn PoszD gez0_abs ?lemx //.\nby rewrite -ltz_addr1 -(ltr_int [numFieldType of algC]) (ler_lt_trans x_ge0).\nQed.\n\nLemma truncC_def x n : n%:R <= x < n.+1%:R -> truncC x = n.\nProof.\nmove=> ivt_n_x; have /andP[lenx _] := ivt_n_x.\nby rewrite /truncC (ler_trans (ler0n _ n)) // (@floorC_def _ n) // addrC -intS.\nQed.\n\nLemma natCK n : truncC n%:R = n.\nProof. by apply: truncC_def; rewrite lerr ltr_nat /=. Qed.\n\nLemma CnatP x : reflect (exists n, x = n%:R) (x \\in Cnat).\nProof.\nby apply: (iffP eqP) => [<- | [n ->]]; [exists (truncC x) | rewrite natCK].\nQed.\n\nLemma truncCK : {in Cnat, cancel truncC (GRing.natmul 1)}.\nProof. by move=> x /eqP. Qed.\n\nLemma truncC_gt0 x : (0 < truncC x)%N = (1 <= x).\nProof.\napply/idP/idP=> [m_gt0 | x_ge1].\n  have /truncC_itv/andP[lemx _]: 0 <= x.\n    by move: m_gt0; rewrite /truncC; case: ifP.\n  by apply: ler_trans lemx; rewrite ler1n.\nhave /truncC_itv/andP[_ ltxm1]:= ler_trans ler01 x_ge1.\nby rewrite -ltnS -ltC_nat (ler_lt_trans x_ge1).\nQed.\n\nLemma truncC0Pn x : reflect (truncC x = 0%N) (~~ (1 <= x)).\nProof. by rewrite -truncC_gt0 -eqn0Ngt; apply: eqP. Qed.\n\nLemma truncC0 : truncC 0 = 0%N. Proof. exact: (natCK 0). Qed.\nLemma truncC1 : truncC 1 = 1%N. Proof. exact: (natCK 1). Qed.\n\nLemma truncCD :\n  {in Cnat & Num.nneg, {morph truncC : x y / x + y >-> (x + y)%N}}.\nProof.\nmove=> _ y /CnatP[n ->] y_ge0; apply: truncC_def.\nby rewrite -addnS !natrD !natCK ler_add2l ltr_add2l truncC_itv.\nQed.\n\nLemma truncCM : {in Cnat &, {morph truncC : x y / x * y >-> (x * y)%N}}.\nProof. by move=> _ _ /CnatP[n1 ->] /CnatP[n2 ->]; rewrite -natrM !natCK. Qed.\n\nLemma truncCX n : {in Cnat, {morph truncC : x / x ^+ n >-> (x ^ n)%N}}.\nProof. by move=> _ /CnatP[n1 ->]; rewrite -natrX !natCK. Qed.\n\nLemma rpred_Cnat S (ringS : semiringPred S) (kS : keyed_pred ringS) x :\n  x \\in Cnat -> x \\in kS.\nProof. by case/CnatP=> n ->; apply: rpred_nat. Qed.\n\nLemma Cnat_nat n : n%:R \\in Cnat. Proof. by apply/CnatP; exists n. Qed.\nLemma Cnat0 : 0 \\in Cnat. Proof. exact: (Cnat_nat 0). Qed.\nLemma Cnat1 : 1 \\in Cnat. Proof. exact: (Cnat_nat 1). Qed.\nHint Resolve Cnat_nat Cnat0 Cnat1 : core.\n\nFact Cnat_key : pred_key Cnat. Proof. by []. Qed.\nFact Cnat_semiring : semiring_closed Cnat.\nProof.\nby do 2![split] => //= _ _ /CnatP[n ->] /CnatP[m ->]; rewrite -(natrD, natrM).\nQed.\nCanonical Cnat_keyed := KeyedPred Cnat_key.\nCanonical Cnat_addrPred := AddrPred Cnat_semiring.\nCanonical Cnat_mulrPred := MulrPred Cnat_semiring.\nCanonical Cnat_semiringPred := SemiringPred Cnat_semiring.\n\nLemma Cnat_ge0 x : x \\in Cnat -> 0 <= x.\nProof. by case/CnatP=> n ->; apply: ler0n. Qed.\n\nLemma Cnat_gt0 x : x \\in Cnat -> (0 < x) = (x != 0).\nProof. by case/CnatP=> n ->; rewrite pnatr_eq0 ltr0n lt0n. Qed.\n\nLemma conj_Cnat x : x \\in Cnat -> x^* = x.\nProof. by case/CnatP=> n ->; apply: rmorph_nat. Qed.\n\nLemma norm_Cnat x : x \\in Cnat -> `|x| = x.\nProof. by move/Cnat_ge0/ger0_norm. Qed.\n\nLemma Creal_Cnat : {subset Cnat <= Creal}.\nProof. by move=> z /conj_Cnat/CrealP. Qed.\n\nLemma Cnat_sum_eq1 (I : finType) (P : pred I) (F : I -> algC) :\n     (forall i, P i -> F i \\in Cnat) -> \\sum_(i | P i) F i = 1 ->\n   {i : I | [/\\ P i, F i = 1 & forall j, j != i -> P j -> F j = 0]}.\nProof.\nmove=> natF sumF1; pose nF i := truncC (F i).\nhave{natF} defF i: P i -> F i = (nF i)%:R by move/natF/eqP.\nhave{sumF1} /eqP sumF1: (\\sum_(i | P i) nF i == 1)%N.\n  by rewrite -eqC_nat natr_sum -(eq_bigr _ defF) sumF1.\nhave [i Pi nZfi]: {i : I | P i & nF i != 0%N}.\n  by apply/sig2W/exists_inP; rewrite -negb_forall_in -sum_nat_eq0 sumF1.\nhave F'ge0 := (leq0n _, etrans (eq_sym _ _) (sum_nat_eq0 (predD1 P i) nF)).\nrewrite -lt0n in nZfi; have [_] := (leqif_add (leqif_eq nZfi) (F'ge0 _)).\nrewrite /= big_andbC -bigD1 // sumF1 => /esym/andP/=[/eqP Fi1 /forall_inP Fi'0].\nexists i; split=> // [|j neq_ji Pj]; first by rewrite defF // -Fi1.\nby rewrite defF // (eqP (Fi'0 j _)) // neq_ji.\nQed.\n\nLemma Cnat_mul_eq1 x y :\n  x \\in Cnat -> y \\in Cnat -> (x * y == 1) = (x == 1) && (y == 1).\nProof. by do 2!move/truncCK <-; rewrite -natrM !pnatr_eq1 muln_eq1. Qed.\n\nLemma Cnat_prod_eq1 (I : finType) (P : pred I) (F : I -> algC) :\n    (forall i, P i -> F i \\in Cnat) -> \\prod_(i | P i) F i = 1 ->\n  forall i, P i -> F i = 1.\nProof.\nmove=> natF prodF1; apply/eqfun_inP; rewrite -big_andE.\nmove: prodF1; elim/(big_load (fun x => x \\in Cnat)): _.\nelim/big_rec2: _ => // i all1x x /natF N_Fi [Nx x1all1].\nby split=> [|/eqP]; rewrite ?rpredM ?Cnat_mul_eq1 // => /andP[-> /eqP].\nQed.\n\n(* Relating Cint and Cnat. *)\n\nLemma Cint_Cnat : {subset Cnat <= Cint}.\nProof. by move=> _ /CnatP[n ->]; rewrite pmulrn Cint_int. Qed.\n\nLemma CintE x : (x \\in Cint) = (x \\in Cnat) || (- x \\in Cnat).\nProof.\napply/idP/idP=> [/CintP[[n | n] ->] | ]; first by rewrite Cnat_nat.\n  by rewrite NegzE opprK Cnat_nat orbT.\nby case/pred2P=> [<- | /(canLR opprK) <-]; rewrite ?rpredN rpred_nat.\nQed.\n\nLemma Cnat_norm_Cint x : x \\in Cint -> `|x| \\in Cnat.\nProof.\ncase/CintP=> [m ->]; rewrite [m]intEsign rmorphM rmorph_sign.\nby rewrite normrM normr_sign mul1r normr_nat rpred_nat.\nQed.\n\nLemma CnatEint x : (x \\in Cnat) = (x \\in Cint) && (0 <= x).\nProof.\napply/idP/andP=> [Nx | [Zx x_ge0]]; first by rewrite Cint_Cnat ?Cnat_ge0.\nby rewrite -(ger0_norm x_ge0) Cnat_norm_Cint.\nQed.\n\nLemma CintEge0 x : 0 <= x -> (x \\in Cint) = (x \\in Cnat).\nProof. by rewrite CnatEint andbC => ->. Qed.\n\nLemma Cnat_exp_even x n : ~~ odd n -> x \\in Cint -> x ^+ n \\in Cnat.\nProof.\nrewrite -dvdn2 => /dvdnP[m ->] Zx; rewrite mulnC exprM -Cint_normK ?rpredX //.\nexact: Cnat_norm_Cint.\nQed.\n\nLemma norm_Cint_ge1 x : x \\in Cint -> x != 0 -> 1 <= `|x|.\nProof.\nrewrite -normr_eq0 => /Cnat_norm_Cint/CnatP[n ->].\nby rewrite pnatr_eq0 ler1n lt0n.\nQed.\n\nLemma sqr_Cint_ge1 x : x \\in Cint -> x != 0 -> 1 <= x ^+ 2.\nProof.\nby move=> Zx nz_x; rewrite -Cint_normK // expr_ge1 ?normr_ge0 ?norm_Cint_ge1.\nQed.\n\nLemma Cint_ler_sqr x : x \\in Cint -> x <= x ^+ 2.\nProof.\nmove=> Zx; have [-> | nz_x] := eqVneq x 0; first by rewrite expr0n.\napply: ler_trans (_ : `|x| <= _); first by rewrite real_ler_norm ?Creal_Cint.\nby rewrite -Cint_normK // ler_eexpr // norm_Cint_ge1.\nQed.\n\n(* Integer divisibility. *)\n\nLemma dvdCP x y : reflect (exists2 z, z \\in Cint & y = z * x) (x %| y)%C.\nProof.\nrewrite unfold_in; have [-> | nz_x] := altP eqP.\n  by apply: (iffP eqP) => [-> | [z _ ->]]; first exists 0; rewrite ?mulr0.\napply: (iffP idP) => [Zyx | [z Zz ->]]; last by rewrite mulfK.\nby exists (y / x); rewrite ?divfK.\nQed.\n\nLemma dvdCP_nat x y : 0 <= x -> 0 <= y -> (x %| y)%C -> {n | y = n%:R * x}.\nProof.\nmove=> x_ge0 y_ge0 x_dv_y; apply: sig_eqW.\ncase/dvdCP: x_dv_y => z Zz -> in y_ge0 *; move: x_ge0 y_ge0 Zz.\nrewrite ler_eqVlt => /predU1P[<- | ]; first by exists 22; rewrite !mulr0.\nby move=> /pmulr_lge0-> /CintEge0-> /CnatP[n ->]; exists n.\nQed.\n\nLemma dvdC0 x : (x %| 0)%C.\nProof. by apply/dvdCP; exists 0; rewrite ?mul0r. Qed.\n\nLemma dvd0C x : (0 %| x)%C = (x == 0).\nProof. by rewrite unfold_in eqxx. Qed.\n\nLemma dvdC_mull x y z : y \\in Cint -> (x %| z)%C -> (x %| y * z)%C.\nProof.\nmove=> Zy /dvdCP[m Zm ->]; apply/dvdCP.\nby exists (y * m); rewrite ?mulrA ?rpredM.\nQed.\n\nLemma dvdC_mulr x y z : y \\in Cint -> (x %| z)%C -> (x %| z * y)%C.\nProof. by rewrite mulrC; apply: dvdC_mull. Qed.\n\nLemma dvdC_mul2r x y z : y != 0 -> (x * y %| z * y)%C = (x %| z)%C.\nProof.\nmove=> nz_y; rewrite !unfold_in !(mulIr_eq0 _ (mulIf nz_y)).\nby rewrite mulrAC invfM mulrA divfK.\nQed.\n\nLemma dvdC_mul2l x y z : y != 0 -> (y * x %| y * z)%C = (x %| z)%C.\nProof. by rewrite !(mulrC y); apply: dvdC_mul2r. Qed.\n\nLemma dvdC_trans x y z : (x %| y)%C -> (y %| z)%C -> (x %| z)%C.\nProof. by move=> x_dv_y /dvdCP[m Zm ->]; apply: dvdC_mull. Qed.\n\nLemma dvdC_refl x : (x %| x)%C.\nProof. by apply/dvdCP; exists 1; rewrite ?mul1r. Qed.\nHint Resolve dvdC_refl : core.\n\nFact dvdC_key x : pred_key (dvdC x). Proof. by []. Qed.\nLemma dvdC_zmod x : zmod_closed (dvdC x).\nProof.\nsplit=> [| _ _ /dvdCP[y Zy ->] /dvdCP[z Zz ->]]; first exact: dvdC0.\nby rewrite -mulrBl dvdC_mull ?rpredB.\nQed.\nCanonical dvdC_keyed x := KeyedPred (dvdC_key x).\nCanonical dvdC_opprPred x := OpprPred (dvdC_zmod x).\nCanonical dvdC_addrPred x := AddrPred (dvdC_zmod x).\nCanonical dvdC_zmodPred x := ZmodPred (dvdC_zmod x).\n\nLemma dvdC_nat (p n : nat) : (p %| n)%C = (p %| n)%N.\nProof.\nrewrite unfold_in CintEge0 ?divr_ge0 ?invr_ge0 ?ler0n // !pnatr_eq0.\nhave [-> | nz_p] := altP eqP; first by rewrite dvd0n.\napply/CnatP/dvdnP=> [[q def_q] | [q ->]]; exists q.\n  by apply/eqP; rewrite -eqC_nat natrM -def_q divfK ?pnatr_eq0.\nby rewrite [num in num / _]natrM mulfK ?pnatr_eq0.\nQed.\n\nLemma dvdC_int (p : nat) x : x \\in Cint -> (p %| x)%C = (p %| `|floorC x|)%N.\nProof.\nmove=> Zx; rewrite -{1}(floorCK Zx) {1}[floorC x]intEsign.\nby rewrite rmorphMsign rpredMsign dvdC_nat.\nQed.\n\n(* Elementary modular arithmetic. *)\n\nLemma eqCmod_refl e x : (x == x %[mod e])%C.\nProof. by rewrite /eqCmod subrr rpred0. Qed.\n\nLemma eqCmodm0 e : (e == 0 %[mod e])%C. Proof. by rewrite /eqCmod subr0. Qed.\nHint Resolve eqCmod_refl eqCmodm0 : core.\n\nLemma eqCmod0 e x : (x == 0 %[mod e])%C = (e %| x)%C.\nProof. by rewrite /eqCmod subr0. Qed.\n\nLemma eqCmod_sym e x y : ((x == y %[mod e]) = (y == x %[mod e]))%C.\nProof. by rewrite /eqCmod -opprB rpredN. Qed.\n\nLemma eqCmod_trans e y x z :\n  (x == y %[mod e] -> y == z %[mod e] -> x == z %[mod e])%C.\nProof. by move=> Exy Eyz; rewrite /eqCmod -[x](subrK y) -addrA rpredD. Qed.\n\nLemma eqCmod_transl e x y z :\n  (x == y %[mod e])%C -> (x == z %[mod e])%C = (y == z %[mod e])%C.\nProof. by move/(sym_left_transitive (eqCmod_sym e) (@eqCmod_trans e)). Qed.\n\nLemma eqCmod_transr e x y z :\n  (x == y %[mod e])%C -> (z == x %[mod e])%C = (z == y %[mod e])%C.\nProof. by move/(sym_right_transitive (eqCmod_sym e) (@eqCmod_trans e)). Qed.\n\nLemma eqCmodN e x y : (- x == y %[mod e])%C = (x == - y %[mod e])%C.\nProof. by rewrite eqCmod_sym /eqCmod !opprK addrC. Qed.\n\nLemma eqCmodDr e x y z : (y + x == z + x %[mod e])%C = (y == z %[mod e])%C.\nProof. by rewrite /eqCmod addrAC opprD !addrA subrK. Qed.\n\nLemma eqCmodDl e x y z : (x + y == x + z %[mod e])%C = (y == z %[mod e])%C.\nProof. by rewrite !(addrC x) eqCmodDr. Qed.\n\nLemma eqCmodD e x1 x2 y1 y2 :\n  (x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 + y1 == x2 + y2 %[mod e])%C.\nProof.\nby rewrite -(eqCmodDl e x2 y1) -(eqCmodDr e y1); apply: eqCmod_trans.\nQed.\n\nLemma eqCmod_nat (e m n : nat) : (m == n %[mod e])%C = (m == n %[mod e]).\nProof.\nwithout loss lenm: m n / (n <= m)%N.\n  by move=> IH; case/orP: (leq_total m n) => /IH //; rewrite eqCmod_sym eq_sym.\nby rewrite /eqCmod -natrB // dvdC_nat eqn_mod_dvd.\nQed.\n\nLemma eqCmod0_nat (e m : nat) : (m == 0 %[mod e])%C = (e %| m)%N.\nProof. by rewrite eqCmod0 dvdC_nat. Qed.\n\nLemma eqCmodMr e :\n  {in Cint, forall z x y, x == y %[mod e] -> x * z == y * z %[mod e]}%C.\nProof. by move=> z Zz x y; rewrite /eqCmod -mulrBl => /dvdC_mulr->. Qed.\n\nLemma eqCmodMl e :\n  {in Cint, forall z x y, x == y %[mod e] -> z * x == z * y %[mod e]}%C.\nProof. by move=> z Zz x y Exy; rewrite !(mulrC z) eqCmodMr. Qed.\n\nLemma eqCmodMl0 e : {in Cint, forall x, x * e == 0 %[mod e]}%C.\nProof. by move=> x Zx; rewrite -(mulr0 x) eqCmodMl. Qed.\n\nLemma eqCmodMr0 e : {in Cint, forall x, e * x == 0 %[mod e]}%C.\nProof. by move=> x Zx; rewrite /= mulrC eqCmodMl0. Qed.\n\nLemma eqCmod_addl_mul e : {in Cint, forall x y, x * e + y == y %[mod e]}%C.\nProof. by move=> x Zx y; rewrite -{2}[y]add0r eqCmodDr eqCmodMl0. Qed.\n\nLemma eqCmodM e : {in Cint & Cint, forall x1 y2 x2 y1,\n  x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 * y1 == x2 * y2 %[mod e]}%C.\nProof.\nmove=> x1 y2 Zx1 Zy2 x2 y1 eq_x /(eqCmodMl Zx1)/eqCmod_trans-> //.\nexact: eqCmodMr.\nQed.\n\n(* Rational number subset. *)\n\nLemma ratCK : cancel QtoC CtoQ.\nProof. by rewrite /getCrat; case: getCrat_subproof. Qed.\n\nLemma getCratK : {in Crat, cancel CtoQ QtoC}.\nProof. by move=> x /eqP. Qed.\n\nLemma Crat_rat (a : rat) : QtoC a \\in Crat.\nProof. by rewrite unfold_in ratCK. Qed.\n\nLemma CratP x : reflect (exists a, x = QtoC a) (x \\in Crat).\nProof.\nby apply: (iffP eqP) => [<- | [a ->]]; [exists (CtoQ x) | rewrite ratCK].\nQed.\n\nLemma Crat0 : 0 \\in Crat. Proof. by apply/CratP; exists 0; rewrite rmorph0. Qed.\nLemma Crat1 : 1 \\in Crat. Proof. by apply/CratP; exists 1; rewrite rmorph1. Qed.\nHint Resolve Crat0 Crat1 : core.\n\nFact Crat_key : pred_key Crat. Proof. by []. Qed.\nFact Crat_divring_closed : divring_closed Crat.\nProof.\nsplit=> // _ _ /CratP[x ->] /CratP[y ->].\n  by rewrite -rmorphB Crat_rat.\nby rewrite -fmorph_div Crat_rat.\nQed.\nCanonical Crat_keyed := KeyedPred Crat_key.\nCanonical Crat_opprPred := OpprPred Crat_divring_closed.\nCanonical Crat_addrPred := AddrPred Crat_divring_closed.\nCanonical Crat_mulrPred := MulrPred Crat_divring_closed.\nCanonical Crat_zmodPred := ZmodPred Crat_divring_closed.\nCanonical Crat_semiringPred := SemiringPred Crat_divring_closed.\nCanonical Crat_smulrPred := SmulrPred Crat_divring_closed.\nCanonical Crat_divrPred := DivrPred Crat_divring_closed.\nCanonical Crat_subringPred := SubringPred Crat_divring_closed.\nCanonical Crat_sdivrPred := SdivrPred Crat_divring_closed.\nCanonical Crat_divringPred := DivringPred Crat_divring_closed.\n\nLemma rpred_Crat S (ringS : divringPred S) (kS : keyed_pred ringS) :\n  {subset Crat <= kS}.\nProof. by move=> _ /CratP[a ->]; apply: rpred_rat. Qed.\n\nLemma conj_Crat z : z \\in Crat -> z^* = z.\nProof. by move/getCratK <-; rewrite fmorph_div !rmorph_int. Qed.\n\nLemma Creal_Crat : {subset Crat <= Creal}.\nProof. by move=> x /conj_Crat/CrealP. Qed.\n\nLemma Cint_rat a : (QtoC a \\in Cint) = (a \\in Qint).\nProof.\napply/idP/idP=> [Za | /numqK <-]; last by rewrite rmorph_int Cint_int.\napply/QintP; exists (floorC (QtoC a)); apply: (can_inj ratCK).\nby rewrite rmorph_int floorCK.\nQed.\n\nLemma minCpolyP x :\n   {p | minCpoly x = pQtoC p /\\ p \\is monic\n      & forall q, root (pQtoC q) x = (p %| q)%R}.\nProof. by rewrite /minCpoly; case: (minCpoly_subproof x) => p; exists p. Qed.\n\nLemma minCpoly_monic x : minCpoly x \\is monic.\nProof. by have [p [-> mon_p] _] := minCpolyP x; rewrite map_monic. Qed.\n\nLemma minCpoly_eq0 x : (minCpoly x == 0) = false.\nProof. exact/negbTE/monic_neq0/minCpoly_monic. Qed.\n\nLemma root_minCpoly x : root (minCpoly x) x.\nProof. by have [p [-> _] ->] := minCpolyP x. Qed.\n\nLemma size_minCpoly x : (1 < size (minCpoly x))%N.\nProof. by apply: root_size_gt1 (root_minCpoly x); rewrite ?minCpoly_eq0. Qed.\n\n(* Basic properties of automorphisms. *)\nSection AutC.\n\nImplicit Type nu : {rmorphism algC -> algC}.\n\nLemma aut_Cnat nu : {in Cnat, nu =1 id}.\nProof. by move=> _ /CnatP[n ->]; apply: rmorph_nat. Qed.\n\nLemma aut_Cint nu : {in Cint, nu =1 id}.\nProof. by move=> _ /CintP[m ->]; apply: rmorph_int. Qed.\n\nLemma aut_Crat nu : {in Crat, nu =1 id}.\nProof. by move=> _ /CratP[a ->]; apply: fmorph_rat. Qed.\n\nLemma Cnat_aut nu x : (nu x \\in Cnat) = (x \\in Cnat).\nProof.\nby do [apply/idP/idP=> Nx; have:= aut_Cnat nu Nx] => [/fmorph_inj <- | ->].\nQed.\n\nLemma Cint_aut nu x : (nu x \\in Cint) = (x \\in Cint).\nProof. by rewrite !CintE -rmorphN !Cnat_aut. Qed.\n\nLemma Crat_aut nu x : (nu x \\in Crat) = (x \\in Crat).\nProof.\napply/idP/idP=> /CratP[a] => [|->]; last by rewrite fmorph_rat Crat_rat.\nby rewrite -(fmorph_rat nu) => /fmorph_inj->; apply: Crat_rat.\nQed.\n\nLemma algC_invaut_subproof nu x : {y | nu y = x}.\nProof.\nhave [r Dp] := closed_field_poly_normal (minCpoly x).\nsuffices /mapP/sig2_eqW[y _ ->]: x \\in map nu r by exists y.\nrewrite -root_prod_XsubC; congr (root _ x): (root_minCpoly x).\nhave [q [Dq _] _] := minCpolyP x; rewrite Dq -(eq_map_poly (fmorph_rat nu)).\nrewrite (map_poly_comp nu) -{q}Dq Dp (monicP (minCpoly_monic x)) scale1r.\nrewrite rmorph_prod big_map; apply: eq_bigr => z _.\nby rewrite rmorphB /= map_polyX map_polyC.\nQed.\nDefinition algC_invaut nu x := sval (algC_invaut_subproof nu x).\n\nLemma algC_invautK nu : cancel (algC_invaut nu) nu.\nProof. by move=> x; rewrite /algC_invaut; case: algC_invaut_subproof. Qed.\n\nLemma algC_autK nu : cancel nu (algC_invaut nu).\nProof. exact: inj_can_sym (algC_invautK nu) (fmorph_inj nu). Qed.\n\nFact algC_invaut_is_rmorphism nu : rmorphism (algC_invaut nu).\nProof. exact: can2_rmorphism (algC_autK nu) (algC_invautK nu). Qed.\nCanonical algC_invaut_additive nu := Additive (algC_invaut_is_rmorphism nu).\nCanonical algC_invaut_rmorphism nu := RMorphism (algC_invaut_is_rmorphism nu).\n\nLemma minCpoly_aut nu x : minCpoly (nu x) = minCpoly x.\nProof.\nwlog suffices dvd_nu: nu x / (minCpoly x %| minCpoly (nu x))%R.\n  apply/eqP; rewrite -eqp_monic ?minCpoly_monic //; apply/andP; split=> //.\n  by rewrite -{2}(algC_autK nu x) dvd_nu.\nhave [[q [Dq _] min_q] [q1 [Dq1 _] _]] := (minCpolyP x, minCpolyP (nu x)).\nrewrite Dq Dq1 dvdp_map -min_q -(fmorph_root nu) -map_poly_comp.\nby rewrite (eq_map_poly (fmorph_rat nu)) -Dq1 root_minCpoly.\nQed.\n\nEnd AutC.\n\nSection AutLmodC.\n\nVariables (U V : lmodType algC) (f : {additive U -> V}).\n\nLemma raddfZ_Cnat a u : a \\in Cnat -> f (a *: u) = a *: f u.\nProof. by case/CnatP=> n ->; apply: raddfZnat. Qed.\n\nLemma raddfZ_Cint a u : a \\in Cint -> f (a *: u) = a *: f u.\nProof. by case/CintP=> m ->; rewrite !scaler_int raddfMz. Qed.\n\nEnd AutLmodC.\n\nSection PredCmod.\n\nVariable V : lmodType algC.\n\nLemma rpredZ_Cnat S (addS : @addrPred V S) (kS : keyed_pred addS) :\n  {in Cnat & kS, forall z u, z *: u \\in kS}.\nProof. by move=> _ u /CnatP[n ->]; apply: rpredZnat. Qed.\n\nLemma rpredZ_Cint S (subS : @zmodPred V S) (kS : keyed_pred subS) :\n  {in Cint & kS, forall z u, z *: u \\in kS}.\nProof. by move=> _ u /CintP[m ->]; apply: rpredZint. Qed.\n\nEnd PredCmod.\n\nEnd AlgebraicsTheory.\nHint Resolve Creal0 Creal1 Cnat_nat Cnat0 Cnat1 Cint0 Cint1 floorC0 Crat0 Crat1 : core.\nHint Resolve dvdC0 dvdC_refl eqCmod_refl eqCmodm0 : core.\n", "meta": {"author": "palmskog", "repo": "mathcomp-experiment", "sha": "67a6e83c025784b1e6f646a30dde38e0f33060eb", "save_path": "github-repos/coq/palmskog-mathcomp-experiment", "path": "github-repos/coq/palmskog-mathcomp-experiment/mathcomp-experiment-67a6e83c025784b1e6f646a30dde38e0f33060eb/field/algC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7187195884864589}}
{"text": "From mathcomp Require Import ssreflect ssrnat.\nFrom LCAC Require Import Relations_ext.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Definition 1.1: Lambda-terms *)\n\nInductive lcterm : Set :=\n  | lcbvar of nat\n  | lcubvar of nat\n  | lclam of lcterm\n  | lcapp of lcterm & lcterm.\n\nLemma eq_lcterm_dec (t1 t2 : lcterm) : {t1 = t2}+{t1 <> t2}.\nProof. do !decide equality. Qed.\n\nInfix \"@\" := lcapp (at level 20, left associativity).\n\n(* Example 1.2 *)\n\nCheck (lclam (lcapp (lcbvar 0) (lcubvar 0))).\nCheck (lclam (lcapp (lcbvar 0) (lcubvar 0))).\nCheck (lcapp (lcubvar 0) (lclam (lclam (lcbvar 0)))).\nCheck (lcapp (lclam (lcbvar 0)) (lclam (lcapp (lcbvar 0) (lcubvar 0)))).\nCheck (lclam (lcapp (lcubvar 0) (lcbvar 0))).\n\n(* Notation 1.3 *)\n\nFixpoint lclams (n : nat) (t : lcterm) :=\n  match n with\n    | 0 => t\n    | n.+1 => lclams n (lclam t)\n  end.\n\n(* Definition 1.6: Length of lambda-term *)\n\nFixpoint lc_length (t : lcterm) : nat :=\n  match t with\n    | lclam t' => (lc_length t').+1\n    | lcapp t1 t2 => lc_length t1 + lc_length t2\n    | _ => 1\n  end.\n\n(* Definition 1.7: Binary relation \"occurs in\" on lambda-terms *)\n\nInductive lc_occurs : relation lcterm :=\n  | lc_occurs_refl t         : lc_occurs t t\n  | lc_occurs_left t1 t2 t3  : lc_occurs t1 t2 -> lc_occurs t1 (t2 @ t3)\n  | lc_occurs_right t1 t2 t3 : lc_occurs t1 t3 -> lc_occurs t1 (t2 @ t3)\n  | lc_occurs_lam t1 t2      : lc_occurs t1 t2 -> lc_occurs t1 (lclam t2).\n\n(* Definition 1.12: Substitution *)\n", "meta": {"author": "pi8027", "repo": "lambda-calculus", "sha": "a5c58079b944ec8f98d8a3fabc2c829bb32a1de7", "save_path": "github-repos/coq/pi8027-lambda-calculus", "path": "github-repos/coq/pi8027-lambda-calculus/lambda-calculus-a5c58079b944ec8f98d8a3fabc2c829bb32a1de7/coq/Origin/Untyped.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664175, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7187195866544354}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus Zero (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj1910_coqofml_oFYGJN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7187133498815088}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := plus (mult x y) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj63_coqofml_E7GIbv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7187133480442559}}
{"text": "(*\n   generalize dependent m.\n   または、intro で「forall m」を残した状態で、\n   induction n をする例\n*)\n\n\nRequire Import Omega.\nRequire Import NArith.\nRequire Import Arith.\n\n\nFixpoint sum n :=\n  match n with\n    | O => O\n    | S n' => S n' + sum n'\n  end.\n\n\nTheorem Sum_of_nat : forall (n m: nat),\n  m = 2 * sum n -> m = n * (n + 1).\nProof.\n  intros n m.\n  induction n.\n  simpl.\n  auto.\n  (*\n     IHn : m = 2 * sum n -> m = n * (n + 1)\n     ============================\n     m = 2 * sum (S n) -> m = S n * (S n + 1)\n   *)\nAbort.\n\n\nTheorem Sum_of_nat : forall (n m: nat),\n  m = 2 * sum n -> m = n * (n + 1).\nProof.\n  intro n.\n  induction n.\n  simpl.\n  auto.\n  \n(*\n   n : nat\n   IHn : forall m : nat, m = 2 * sum n -> m = n * (n + 1)\n   ============================\n   forall m : nat, m = 2 * sum (S n) -> m = S n * (S n + 1)\n*)\n  intros.\n  \n  (* 代数的な式の変形をする *)\n  subst.\n  unfold sum.\n  fold sum.\n  ring_simplify.\n  cut (forall m n, m = n -> m + 2 = n + 2).\n  intros.\n  apply (H (2 * n + 2 * sum n) (n * n + 3 * n)).\n  cut (forall x y n, x = y + n -> 2 * n + x = y + 3 * n).\n  intros.\n  apply (H0 (2 * sum n) (n * n)).\n  cut (forall m n, m = n * (n + 1) -> m = n * n + n).\n  intros.\n  apply H1.\n  \n  apply IHn.                                (* ここで、上記の前提をつかう！ *)\n  reflexivity.                              (* 証明終了！ *)\n  \n  (* cutで導入した前提を片付ける *)\n  intros.\n  rewrite H1.\n  ring.\n  intros.\n  rewrite H0.\n  ring.\n  intros.\n  rewrite H.\n  reflexivity.\nQed.\n\n\nTheorem Sum_of_nat' : forall (m n : nat),\n  m = 2 * sum n -> m = n * (n + 1).\nProof.\n  intros m n.\n  generalize dependent m.\n  induction n.\n  simpl.\n  auto.\n\n\n(*\n   n : nat\n   IHn : forall m : nat, m = 2 * sum n -> m = n * (n + 1)\n   ============================\n   forall m : nat, m = 2 * sum (S n) -> m = S n * (S n + 1)\n   \n   Sum_of_nat と同じようにする。\n*)\nAbort.\n\n\n\n\n(* 1変数の場合 *)\n\n\nLemma Sample_of_unfold : forall n, 2 * sum n = n * (n + 1).\nProof.\n  induction n.\n  reflexivity.\n  (*\n     ここで、sum を unfold して、fold すると式が少し変形されます。\n     *)\n  unfold sum.\n  fold sum.\n  (*\n     ここでreplaceを使ってちょっと左辺を書き換えます。書き換えて良い証明はsubgoal 2と後回しです。\n     *)\n  replace (2 * (S n + sum n)) with (2 * S n + 2 * sum n).\n  (*\n     ここでIHnを用いて書き換えて式変形を ring で自動証明します。後回しにしたものもringで一発です。\n     *)\n  rewrite IHn.\n  ring.\n  ring.\nQed.\n\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/coq_generalize_dependent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7186714543919756}}
{"text": "Open Scope list.\nRequire Export List.\nRequire Import Omega.\n\nInductive is_perm : (list nat) -> (list nat) -> Prop :=\n| is_perm_refl :forall l : (list nat), is_perm l l\n| is_perm_sym : forall l1 l2 : (list nat), is_perm l1 l2 -> is_perm l2 l1\n| is_perm_transi : forall l1 l2 l3 : (list nat), is_perm l1 l2 -> is_perm l2 l3 -> is_perm l1 l3\n| is_perm_cons : forall (a : nat) (l1 l2 : (list nat)), is_perm l1 l2 -> is_perm (a::l1) (a::l2)\n| is_perm_a : forall (a : nat) (l : (list nat)), is_perm (a::l) (l++a::nil).\n\n\n\nDefinition l1 : (list nat) := 1::2::3::nil.\nDefinition l2 : (list nat) := 3::2::1::nil.\n\nLemma lemma1 : is_perm l1 l2.\nunfold l1.\nunfold l2.\napply (is_perm_transi (1::2::3::nil) ((2::3::nil)++1::nil) (3::2::1::nil)).\napply is_perm_a.\napply (is_perm_transi (2::3::1::nil) ((3::1::nil)++2::nil) (3::2::1::nil)).\napply is_perm_a.\napply is_perm_cons.\napply (is_perm_transi (1::2::nil) ((1::nil)++(2::nil)) (2::1::nil)).\napply is_perm_cons.\napply is_perm_refl.\napply is_perm_a.\nQed.\n\nInductive is_sorted : (list nat) -> Prop :=\n| is_sorted_nil : is_sorted nil\n| is_sorted_base : forall a : nat , is_sorted (a::nil)\n| is_sorted_rec : forall (a b : nat) (l : (list nat)), a <= b -> is_sorted (b::l) -> is_sorted (a::b::l).\n\n\nLemma lemma2 : is_sorted l1.\nunfold l1.\napply is_sorted_rec.\nomega.\napply is_sorted_rec.\nomega.\napply is_sorted_base.\nQed.\n\nFixpoint sorted_insert (n : nat) (l : (list nat)) : (list nat) :=\nmatch l with\n | (nil) => (n::nil)\n | (a::h)=> match le_dec n a with \n           | left _=> n::a::h\n           | right _=> a::(sorted_insert n h)\n           end\n end.\n\nFixpoint insert_sort (l : (list nat)) : (list nat):=\nmatch l with\n | (nil) => (nil)\n | a::h => (sorted_insert a (insert_sort h))\nend.\n\n(*\nLemma is_perm_refl_sort :\n      forall (l : list nat), is_perm l (insert_sort l).\nintro.\nelim l.\nsimpl.\napply is_perm_refl.\nintros.\n*)\n\n(*\nTheorem insert_sort_correction: \nforall (l1 : (list nat)) (l2 : (list nat)),(insert_sort l1) = l2 -> (is_perm l1 l2).\nintro.\ninduction l3.\nintros.\nrewrite <- H.\nsimpl.\n\napply is_perm_refl.\nintro.\nintro.\nrewrite <- H.\nis_per\n*)\n\n\n\n\n\nTheorem insert_sort_correction: \nforall (l1 : (list nat)) (l2 : (list nat)),(insert_sort l1) = l2 -> (is_perm l1 l2)  /\\ (is_sorted l2).\ninduction l3.\nintros.\nrewrite <- H.\nsplit.\nsimpl.\napply is_perm_refl.\nsimpl.\napply is_sorted_nil.\nintros.\nrewrite <- H.\nelim (IHl3 (insert_sort l3)).\nintros.\n\nsimpl.\nsplit.elim_perm_transi (is_perm (a::l3), a::(insert_sort(l3))) (a::(insert_sort l3)) (is_perm a::(insert_sort l3) (sorted_insert a l3))).\nintro.\ninduction l3.\n\n\n\nintros.\n\nrewrite <- H.\nsplit.\napply is_perm_refl.\napply is_sorted_nil.\nelim (IHl3 l3).\nintros.\nsplit.\nrewrite <- H1.\nsimpl.\n\n\nintro.\n\nrewrite <- H.\n\nelim (IHl3 l3).\nintros.\nsplit.\nsimpl.\n\napply \n\n(*\nFunctional Scheme even_ind := Induction for even Sort Prop.\n\nTheorem even_sound :\n forall (n : nat) (v : Prop) , (even n) = True -> is_even n.\nProof.\n  do 2 intro.\n  functional induction (even n) using even_ind; intros.\n  apply is_even_O.\n  elimtype False; rewrite H; auto.\n  apply is_even_S; apply IHP; assumption.\nQed.\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/sortproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7186714501763366}}
{"text": "Require Import Arith Omega.\n\nTheorem le_plus_minus : forall n m:nat, m <= n -> n = m+(n-m).\nProof.\nintros n m H.\n\ninduction n.\n\nrewrite <- le_n_0_eq with (1 := H); simpl; trivial.", "meta": {"author": "torebre", "repo": "coq_test", "sha": "869bfaa8154f988e1330dbc0bc5e682b3a2940e0", "save_path": "github-repos/coq/torebre-coq_test", "path": "github-repos/coq/torebre-coq_test/coq_test-869bfaa8154f988e1330dbc0bc5e682b3a2940e0/chapter7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951588871156, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.7186248552601803}}
{"text": "Require Import FiniteTypes Arith MyTactics MPiecewise  VNArith.  \n\n\n(* Top level definitions  of ellipsis functions using natural numbers *)\n\n Set Implicit Arguments.\n\n (** * Top level definitions *)\n\n\n\n  (** Linear function in n variables.   *)\n Inductive lfun (n : nat)  : Set :=\n   | adD :  lfun n -> lfun n -> lfun n\n   | suB :  lfun n -> lfun n -> lfun n\n   | vr :  Fin n -> lfun n\n   | cnst : nat ->  lfun n.\n\n (** interpretation  *) \n Fixpoint evl n (i : lfun n) (v : Vec nat n) :  nat :=\n   match i with \n   | cnst n =>  n\n   | vr j =>  vecfin v j\n   | adD l r => evl l v + evl r v\n   | suB l r  => evl l v - (evl r v )\n   end.\n\n (** composition *)\n Fixpoint cmp n (i j : lfun (S n)) : lfun (S n) :=\n   match i with\n   | adD  l r => adD (cmp l j) (cmp r j)\n   | suB  l r => suB (cmp l j) (cmp r j)\n   | vr  i  =>  match finEmtp i with\n                 | isTp  =>  j\n                 | isEmb l => vr (emb l)\n                 end\n   | cnst n => cnst _ n\n  end.\n\n  Fixpoint cmp' n (i : lfun 1) (j : lfun n) : lfun n :=\n   match i with\n   | adD  l r => adD (cmp' l j) (cmp' r j)\n   | suB  l r => suB (cmp' l j) (cmp' r j)\n   | vr  i  =>  j\n   | cnst n => cnst _ n\n  end.\n\n (* easy to see composition is correct *) \n Lemma cmp'_ok n (i : lfun 1) (j : lfun n) : \n   forall v,  evl (cmp' i j) v = evl i (vcons (evl j v) (vnil _)).\n Proof.\n   induction i; simpl; intros; FSimpl.\n Qed.\n\n (** fix the first n variables then treat it as a function in 1 variable *)\n Fixpoint plsn n (i : lfun (S n)) (v : Vec nat n) : lfun 1 :=\n    match i with \n    | cnst n   =>   cnst _ n \n    | vr j     =>   match finEmtp j with\n                    | isTp  =>  vr (fz _)\n                    | isEmb l => cnst _ (vecfin v l)\n                    end\n    | adD l r => adD (plsn l v) (plsn r v)\n    | suB l r => suB (plsn l v) (plsn r v)\n   end. \n \n  (** check we did the correct thing with  *)\n  Lemma plsn_ok n (a : lfun (S n)) : \n       forall v,  evl (plsn a (vfirst v)) (vcons (vlast v) (vnil nat)) = evl a (vSnoc (vlast v) (vfirst v)).\n  Proof.\n    induction a; simpl; intros; FSimpl; vSimp; simpl.\n     try (unfold vlast; unfold vfirst; unfold vhead; unfold vtail; simpl).   \n    rewrite vecfin_tp; vecRwt; trivial. rewrite vecfin_emb; vecRwt; trivial.\n  Qed.\n\n  (** compsition is correct *)\n  Lemma cmp_ok n (i j : lfun (S n)) : forall v, \n    evl (cmp i j) v = (* evl (cmp' (plsn i (vfirst v)) (plsn j (vfirst v))) (vcons (vlast v) (vnil _ )). *)\n                      evl (cmp (plsn i (vfirst v)) (plsn j (vfirst v)))  (vcons (vlast v) (vnil nat)).\n  Proof.\n    induction i; simpl; intros.\n    rewrite (IHi1 j v); rewrite (IHi2 j v); trivial.\n    rewrite (IHi1 j v); rewrite (IHi2 j v); trivial.\n    destruct ( finEmtp f); simpl.\n     (* *)\n    induction j; simpl; auto.\n    destruct ( finEmtp f); simpl. destruct (vCons v); simpl.\n    generalize a.\n    induction n; vSimp; simpl. unfold vlast; unfold vhead; simpl; trivial.\n    rewrite (IHn i a0). unfold vlast. unfold vhead; unfold vtail; simpl; trivial.\n    apply vecfin_emb.  apply vecfin_emb . trivial.\n Qed.\n\n\n  (** embedding a function in n variables into one with n+1 variables from .   *)\n    Fixpoint lemb n (i : lfun n) : lfun (S n) :=\n    match i with \n    | cnst n =>  cnst _ n \n    | vr j =>  vr (emb j)\n    | adD l r => adD (lemb l) (lemb r)\n    | suB l r  => suB (lemb l) (lemb r)\n   end.\n\n   (*_ embedding a function in n variables into one with n+1 variables - avoid the first  *)\n    Fixpoint lfs n (i : lfun n) : lfun (S n) :=\n    match i with \n    | cnst n =>  cnst _ n \n    | vr j =>  vr (fs j)\n    | adD l r => adD (lfs l) (lfs r)\n    | suB l r  => suB (lfs l) (lfs r)\n   end.\n\n  (** embedding is fine *)\n  Lemma lemb_ok : forall n (i : lfun n) v, evl i (vfirst v)  = evl (lemb i) v. \n  Proof.\n   induction i; simpl; intros; try  rewrite vecfin_emb;  auto.  \n  Qed.\n\n  (* skip first  is fine *)\n  Lemma lfs_ok : forall n (i : lfun n) v, evl i (vtail v)  = evl (lfs i) v. \n  Proof.\n   induction i; simpl; intros; vSimp;  auto.  \n  Qed.\n  \n   (**\n    post composing with bivariate function \n     -- Given f : N x N -> N and  v : N^n -> N,  want: \\lam (a : N^n) n =>  (f . (v n))  n *)\n   Fixpoint pl2n n (i : lfun 2) (j : lfun n) : lfun (S n) :=\n    match i with \n    | cnst n =>  cnst _ n \n    | vr i' =>   match finEmtp i' with\n                 | isTp  =>  vr (tp _)\n                 | isEmb l => lemb  j\n                 end\n    | adD l r => adD (pl2n l j) (pl2n r j)\n    | suB l r  => suB (pl2n l j) (pl2n r j)\n   end.\n\n  (** correctness of bivariate post compositions  *)\n   Lemma pl2n_ok n (l :  lfun 2) (ln :  lfun n) : forall vz,\n     evl (pl2n l ln) vz =  evl l (vcons (evl ln (vfirst vz)) (vcons (vlast vz) (vnil _))).\n   Proof.\n     induction l; intros; simpl; FSimpl. rewrite lemb_ok. trivial. clear.\n     induction n; vSimp; simpl. unfold vlast; unfold vhead; trivial.\n     generalize (IHn (vcons a0 i)); simpl. intro h; rewrite h.\n     unfold vlast; unfold vhead; unfold vtail; auto.\n  Qed.\n\n \n Section TLPiecewise.\n   (** * Now extend definitions and proofs to piecewise-linear functions  *)\n   Definition Plfun n := Piecewise (lfun n). \n   \n   Fixpoint pevl n  (i : Plfun n) v  :=\n   match i with \n   | lp a => evl a v\n   | pf l cl cr => if lt_le_dec 0 (pevl l v) then pevl cl v else pevl cr v\n   end. \n\n  \n   Section Composition.\n    \n    Fixpoint pcmp' n (l : lfun 1) (ln : Plfun n) :=\n     match ln with\n     | lp a => lp (cmp' l a)\n     | pf a b c => pf a  (pcmp' l b)  (pcmp' l c)\n     end.\n\n    Lemma pcmp'_ok n l (ln : Plfun n) v : pevl (pcmp' l ln) v = evl l (vcons (pevl ln v) (vnil _ )).\n    Proof.\n      induction ln; simpl; intros; try apply cmp'_ok.\n      rewrite (IHln2  v);  rewrite  (IHln3 v); destruct ( lt_le_dec 0 (pevl ln1 v)); trivial.\n   Qed.\n\n   (** post composing with a univariate piecewise-linear function  *)\n   Fixpoint pcmp1 n (i : Plfun 1) (j : Plfun n) :=\n    match i with\n    | lp l => pcmp' l j\n    | pf c l r => pf (pcmp1 c j) (pcmp1 l j) (pcmp1 r j)\n   end.\n\n  (** correctness of this composition  *)\n  Lemma pcmp1_ok n (i : Plfun 1) (j : Plfun n) : forall v, pevl (pcmp1 i j) v = pevl i (vcons (pevl j v) (vnil _ )).\n  Proof. \n    induction i; try apply pcmp'_ok; simpl.\n    intros j v; rewrite (IHi1 j v); rewrite (IHi2 j v); rewrite (IHi3 j v); trivial.\n  Qed.\n\n    (* piecewise case for plSn2n *)\n   Fixpoint pplsn n (i :  Plfun (S n)) (v : Vec nat n) : Piecewise (lfun 1) := \n     match i with\n     | lp l => lp (plsn l v)\n     | pf c l r => pf (pplsn c v)  (pplsn l v) (pplsn r v)\n     end.\n\n   (* correctness *)\n   Lemma pplsn_ok n (l :  Plfun (S n))  : forall v,\n       pevl (pplsn l (vfirst v)) (vcons (vlast v) (vnil _)) = pevl l (vSnoc (vlast v) (vfirst v)) .\n   Proof. \n     induction l; simpl; intros; try apply plsn_ok.\n     rewrite (IHl1 v); rewrite (IHl2 v); rewrite (IHl3 v); trivial.\n   Qed.\n\n   (** composition of two n+1-variate piecewise-linear functions, by fixing the \n    first n varaibles and treating them as a univariate function *)\n  Fixpoint pcmp_aux n (l : lfun (S n)) (i : Plfun (S n)) : Plfun (S n) :=\n    match i with\n    | lp ll => lp (cmp l ll)\n    | pf c ll rr => pf c (pcmp_aux l ll) (pcmp_aux l rr)\n    end.\n\n  Lemma cmp_cmp' (i j : lfun 1): forall v,  evl (cmp i j) v = evl (cmp' i j) v.\n  Proof.\n    induction i; simpl; intros; FSimpl.\n  Qed.\n\n (*  Lemma pcmp_cmp' (i : lfun 1) (j : Plfun 1) : forall v,  pevl (pcmp' i j) v = pevl (pcmp_aux i j) v. *)\n\n  (* correctness proof for pcompSn1*)\n  Lemma pcmp_aux_ok n (i : lfun (S n)) (j : Plfun (S n)) : forall v, \n    pevl (pcmp_aux i j) v = pevl (pcmp' (plsn i (vfirst v)) (pplsn j (vfirst v))) (vcons (vlast v) (vnil _ )).\n   Proof.\n     induction j; simpl; intros.  rewrite  (cmp_ok i a v); rewrite  cmp_cmp'.  trivial. \n     rewrite (IHj2 v);  rewrite (IHj3 v). \n     replace (pevl j1 v) with (pevl (pplsn j1 (vfirst v)) (vcons (vlast v) (vnil _))); trivial. \n     rewrite (pplsn_ok j1 v); rewrite <- (vVsnoc v); trivial.\n  Qed.\n\n  (** main function *) \n  Fixpoint pcmp n (i j : Plfun (S n)) :=\n   match i with\n   | lp l => pcmp_aux l j\n   | pf c l r => pf (pcmp c j) (pcmp l j) (pcmp r j)\n   end.\n\n  (** correctness proof for pcompSn*)\n  Lemma pcmp_ok n  (i j : Plfun (S n)) : forall v, \n    pevl (pcmp i j) v = pevl (pcmp1 (pplsn i (vfirst v)) (pplsn j (vfirst v))) (vcons (vlast v) (vnil _ )).\n  Proof. \n   induction i; simpl; intros;  try apply pcmp_aux_ok.\n   rewrite (IHi1 j v);  rewrite (IHi3 j v);  rewrite (IHi2 j v); trivial.\n  Qed.\n\n   (* push a piecewise-linear function in n variables into a functions in n + 1 variables\n      such that  f v = (polwk f) (tail v) *)\n  Fixpoint plfs n (i : Plfun n) :=\n    match i with\n    | lp l => lp (lfs l)\n    | pf a b c => pf (plfs a) (plfs b) (plfs c)\n    end.\n\n  Lemma plfs_ok n (i : Plfun n) : forall v, pevl (plfs i) v = pevl i (vtail v).\n  Proof.\n    induction i; simpl; intros; try rewrite lfs_ok; trivial.\n    rewrite (IHi1 v); rewrite (IHi2 v); rewrite (IHi3 v); trivial.\n  Qed.\n\n  (* push a piecewise-linear function in n variables into a functions in n + 1 variables\n      such that  f v = (polwk f) (first v) *)\n  Fixpoint pemb n (i : Plfun n) :=\n    match i with\n    | lp l => lp (lemb l)\n    | pf a b c => pf (pemb a) (pemb b) (pemb c)\n    end.\n\n  Lemma pemb_ok n (i : Plfun n) : forall v, pevl (pemb i) v = pevl i (vfirst v).\n  Proof.\n    induction i; intros; simpl; try rewrite lemb_ok; trivial.\n    rewrite (IHi1 v); rewrite (IHi2 v); rewrite (IHi3 v); trivial.\n  Qed.\n\n    (*\n    post composing with bivariate piecewise-linear function \n    Given f : N x N -> N and  v : N^n -> N, \\lambda (a : N^n) m =>  (f . (v a))  m *)\n  Fixpoint ppl2n_aux n (l : lfun 2) (i : Plfun  n)  :=\n    match i with\n    | lp ll => lp (pl2n l ll)\n    | pf c ll rr => pf (pemb c) (ppl2n_aux l ll) (ppl2n_aux l rr)\n    end.\n\n   Lemma ppl2n_aux_ok n (l :  lfun 2) (ln :  Plfun n) : forall vz,\n      pevl (ppl2n_aux l ln) vz =  evl l (vcons (pevl ln (vfirst vz)) (vcons (vlast vz) (vnil _))).\n   Proof.\n     induction ln; simpl; try apply pl2n_ok.\n     intros vz; rewrite (pemb_ok ln1 vz);  rewrite (IHln2 vz); rewrite (IHln3 vz).\n     destruct (lt_le_dec 0 (pevl ln1 (vfirst vz))); trivial.\n   Qed.\n\n  (* case : bothe piecewise *)\n   Fixpoint ppl2n n (l : Plfun 2) (i : Plfun  n)  :=\n    match l with\n    | lp ll => ppl2n_aux ll i\n    | pf c ll rr => pf (ppl2n c i) (ppl2n ll i) (ppl2n rr i)\n    end.\n\n    (* correctness *)\n    Lemma ppl2Sn_ok n (l : Plfun 2) (ln :  Plfun n) : forall vz,\n      pevl (ppl2n l ln) vz =  pevl l (vcons (pevl ln (vfirst vz)) (vcons (vlast vz) (vnil _))).\n    Proof.\n      induction l; simpl; intros;  try apply ppl2n_aux_ok.  \n      rewrite (IHl1 ln vz); rewrite (IHl2 ln vz); rewrite (IHl3 ln vz); trivial.\n    Qed.\n   \n    (* --------------------------------------------------*) \n    Fixpoint ppl2n_ax n (l : Plfun 2) (i : lfun n)  :=\n    match l with\n    | lp ll => lp (pl2n ll i)\n    | pf c ll rr => pf (ppl2n_ax c i) (ppl2n_ax ll i) (ppl2n_ax rr i)\n    end.\n\n  Lemma ppl2n_ax_ok n (l : Plfun 2) (i : lfun n) : \n      forall v, pevl (ppl2n_ax l i) v = pevl  l (vcons (evl i (vfirst v)) (vcons (vlast v) (vnil _))).\n  Proof.  \n    induction l; simpl; intros. apply pl2n_ok.\n    rewrite (IHl1 i v); rewrite (IHl2 i v);  rewrite (IHl3 i v). trivial.\n  Qed.\n    \n\n End Composition.\n  \n\n Section Representation.\n  \n   (** We can represent polymorphic functions whose shape maps are linear\n     as a pair, given by a linear function for the shapes and a piecewise-linear function \n    for the positions. This representaiton does not have a on-to-one correspondence with\n    container morphisms, but instead captures the operations inherent in the container representation\n    in an intuitive way, amenable to geometric interpretation   *) \n   \n    \n    (** liner shape maps only *) \n    Definition PCm n :=  prod (lfun  (S n)) (Plfun (S  (S n))).\n\n     (** piecewise-linear shape maps -- these are more general *)\n     Definition PPCm n :=  prod (Plfun  (S n)) (Plfun (S  (S n))).\n\n    (** Interpretation  *)\n    Definition PCm_int' n (X : Set) :   PCm  n -> Vec nat (S n) * (nat -> X) ->   nat * (nat -> X) :=\n       fun pl  vl => let (l , p) := pl in\n                                (evl l (fst vl) , fun v => snd vl (pevl p (vSnoc v (fst vl)))).\n     (* piecewise case *)\n     Definition PPCm_int' n (X : Set) :   PPCm  n -> Vec nat (S n) * (nat -> X) ->   nat * (nat -> X) :=\n       fun pl  vl => let (l , p) := pl in\n                                (pevl l (fst vl) , fun v => snd vl (pevl p (vSnoc v (fst vl)))).\n \n    (** unpacking  list of lists  *)\n    Fixpoint  nf2pvf1 n (X : Set) (v : Vec (nat * (nat -> X)) n) (F : nat -> X) (i : nat) :   X :=\n     match v with\n     | vnil => F i\n     | vcons _ x xs =>  if le_lt_dec (fst x ) i then  nf2pvf1 xs  (snd x) (i - (fst x)) else (snd x) i\n     end.\n\n  (*\n    Fixpoint  vf2pvf1 n (X : Set) (v : Vec (Z * (Z -> X)) n) (k : Z * (Z -> X)) (z : Z) :   X :=\n     match v with\n     | vnil => snd k z\n     | vcons _ x xs =>  if Z_lt_dec z (fst x) then  (snd x) z\n                                 else vf2pvf1 xs k (z - fst x)\n     end.\n   *)\n\n   Definition nf2pf n (X : Set) (v : Vec (nat * (nat -> X)) (S n)) :=\n                (vmap  (fst (A := nat) (B := nat -> X)) v, nf2pvf1 (vtail v) (snd (vhead v))) .\n  \n\n   Definition PCm_int n (X : Set) :   PCm  n -> Vec (prod nat (nat -> X)) (S n) ->   nat * (nat -> X) := \n        fun i nm => PCm_int' i (nf2pf nm).  \n\n   (* piecewise *)\n    Definition PPCm_int n (X : Set) :   PPCm  n -> Vec (nat * (nat -> X)) (S n) ->   nat * (nat -> X) := \n        fun i nm => PPCm_int' i (nf2pf nm).              \n\n\n (** Composition : we only postcompose with a univariete functions *)\n    Definition PComp n (l : PCm 0) (r : PCm n) := \n      let (v , G) := l in\n         let (u , F) := r in\n              (cmp' v u , pcmp F (ppl2n_ax G u)). \n   \n    (** composition of lmors commute with composition of functions*)\n    Lemma PCm_cmp_ok n (l : PCm 0)  (r : PCm n)  (X : Set) : \n       forall (k : Vec (prod nat (nat -> X)) (S n)),  PCm_int (PComp l r) k = PCm_int l (vcons (PCm_int r k) (vnil _)).\n       unfold PCm; unfold PComp; unfold PCm_int; unfold PCm_int'.\n       destruct l; destruct r; simpl. intros.\n       assert (forall (A B : Type) (a b : A * B), fst a = fst b -> snd a = snd b -> a = b); \n        try (destruct a;  destruct b0; simpl; repeat( intro h; destruct h); trivial). \n       apply H; simpl; try apply (cmp'_ok l l0 ). \n       apply extensionality;  intros;  \n       rewrite (pcmp_ok  p0 (ppl2n_ax p l0));  rewrite pcmp1_ok;\n       rewrite (pplsn_ok (ppl2n_ax p l0) ); rewrite ppl2n_ax_ok;\n       generalize (pplsn_ok p0 (vSnoc (pevl p (vcons (evl l0 (vmap (fst (A := nat) (B := nat -> X)) k)) (vcons a (vnil nat))))\n         (vmap (fst (A := nat) (B := nat -> X)) k))); repeat vecRwt ; try ( intro H0; rewrite H0; trivial).\n    Qed.\n\n   (* piecewise composition *) \n    Definition PPComp n (l : PPCm 0) (r : PPCm n) := \n      let (v , G) := l in\n         let (u , F) := r in\n              (pcmp1 v u , pcmp F (ppl2n G u)).\n\n    (** piecewise composition is correct *)\n    Lemma PPCm_cmp_ok n (l : PPCm 0)  (r : PPCm n)  (X : Set) : \n       forall (k : Vec (prod nat (nat -> X)) (S n)),  PPCm_int (PPComp l r) k = PPCm_int l (vcons (PPCm_int r k) (vnil _)).\n       unfold PPCm; unfold PPComp; unfold PPCm_int; unfold PPCm_int'.\n       destruct l; destruct r; simpl. intros.\n       assert (forall (A B : Type) (a b : A * B), fst a = fst b -> snd a = snd b -> a = b); \n        try (destruct a;  destruct b0; simpl; repeat( intro h; destruct h); trivial). \n       apply H; simpl. try apply (pcmp1_ok p p1 ). \n       apply extensionality;  intros.  \n       rewrite (pcmp_ok  p2 (ppl2n p0 p1)); rewrite pcmp1_ok;\n       rewrite (pplsn_ok (ppl2n p0 p1) ); rewrite ppl2Sn_ok;\n       generalize (pplsn_ok p2 (vSnoc (pevl p0 (vcons (pevl p1 (vmap (fst (A := nat) (B := nat -> X)) k)) (vcons a (vnil nat))))\n         (vmap (fst (A := nat) (B := nat -> X)) k))); repeat vecRwt ; try ( intro H0; rewrite H0; trivial).\n    Qed.\n  \n\n   Fixpoint pcmpm_aux (n : nat) (i : Plfun (S n)) (j : lfun (S n))  :=\n    match i with\n    | lp l => lp (cmp l  j) \n    | pf c l r => pf (pcmpm_aux c j) (pcmpm_aux l j) (pcmpm_aux r j)\n    end.\n\n   (* correctness *)\n   Lemma pcmpm_aux_ok n (i : Plfun (S n)) (l : lfun (S n)) : \n    forall v,   pevl (pcmpm_aux i l) v =\n       pevl (pcmp1 (pplsn i (vfirst v)) (pplsn (lp l) (vfirst v))) (vcons (vlast v) (vnil nat)). \n   Proof.\n    induction i; simpl; intros. rewrite <- cmp_cmp'. apply cmp_ok.\n    rewrite (IHi1 l v); rewrite (IHi2 l v); rewrite (IHi3 l v). trivial.\n   Qed.\n\n  Fixpoint pcmpm (n : nat) (i j : Plfun (S n))  :=\n    match j with\n    | lp l => pcmpm_aux i l\n    | pf c l r => pf c (pcmpm i l) (pcmpm i r)\n    end.\n \n\n  (* correctness *-)\n  Lemma pcmpm_ok n (i j : Plfun (S n)) : \n    forall v, *)\n\n  (* post compoing a piecewise-linear function along hte if *)\n  Fixpoint pmp m (l : PPCm 0) (r : PPCm m) :=\n       let (v , G) := l in\n         let (u , F) := r in\n              (pcmp1 v u , pcmpm F (ppl2n G u)).\n    \n    \n End Representation. \n  \n\n End TLPiecewise.\n\n  \n Section Normalizing.\n     (** Euqality for linear functions  *)\n     \n     (* push a number into a vector at positions determined by Fin n *)\n     Fixpoint push n (X : Set) (x0 : X) (i : Fin n) (z : X) : Vec X n :=\n     match i in Fin e return (Vec X e ) with\n     | fz m => vcons z (vec m x0)\n     | fs _ j => vcons x0 (push  x0 j z)\n     end. \n\n   (* in n variables, alpha is an array of length n *)\n   Fixpoint alps n (i : lfun n) :  Vec nat n :=\n    match i  with\n    | cnst _ =>  vec n 0\n    | vr j => push 0 j 1\n    | adD l r => vAdd (alps l) (alps r) \n    | suB l r => vSub (alps l) (alps r)\n   end.\n \n   (* beta is just a constant *)\n   Fixpoint bet n (i : lfun n)  :=\n   match i  with\n   | cnst n =>   n\n   | vr _   => 0\n   | adD l r => (bet l + bet r)\n   | suB l r => (bet l - bet r)\n   end.\n\n   Definition norm n (i : lfun n) := (alps i , bet i). \n   \n   (* decision procedure for Lfun n  *)\n   Definition lfunEq n (i j : lfun n) :=  \n     if (vecEqDec eq_nat_dec (alps i) (alps j)) then (if eq_nat_dec (bet i) (bet j) then true else false) else false.  \n\n End Normalizing.\n\n\nSection Equality. \n\n   Definition vlst n (v : Vec nat n) :=\n      match v with\n      | vnil  => 0\n      | xs    => vlast xs\n      end.\n \n   (** Equality:  *)   \n  Inductive pcmEQ n (i j : PPCm n) : Prop :=\n  | isEQ :  (* lfunEq  (fst i) (fst j) = true -> *)\n            (forall v, pevl (fst i) v = pevl (fst j) v) ->\n            (forall v, \n               vlast v < pevl (fst i) (vfirst v) -> \n               vlast v < pevl (fst j) (vfirst v) ->  pevl  (snd i) v = pevl (snd j) v) -> pcmEQ i j.\n   \n\n\n  (** Correctness of equality  *)\n Lemma pcmEQ_ok n (l r : PPCm n)  (X : Set) : \n       forall (k : Vec (prod nat (nat -> X)) (S n)),\n    pcmEQ l r -> (forall a, a <  pevl (fst l)  (vmap (fst (A := nat) (B := nat -> X)) k) /\\\n                            a <  pevl (fst r)  (vmap (fst (A := nat) (B := nat -> X)) k) ) -> PPCm_int  l k = PPCm_int r k.\n Proof.\n   unfold PPCm_int; unfold PPCm_int'; intros n l r X k H H0.\n   destruct l; destruct r; destruct H as [H1 H2]; simpl in *. \n   generalize H2; generalize H0. clear H0 ; clear H2.\n   rewrite (H1 (vmap (fst (A := nat) (B := nat -> X)) k) ).\n   intros H0 H2; \n   cut (forall (A B :Set) (a a1 : A) (b b1 : B), a = a1 /\\ b = b1 -> (a, b) = (a1 , b1)). \n  intros. apply H;split; clear H; trivial.\n   apply extensionality. intros.\n   generalize (H2 (vSnoc a (vmap (fst (A := nat) (B := nat -> X)) k)) ).\n   clear H2; vecRwt.\n   rewrite (vfirst_vSnoc  a (vmap (fst (A := nat) (B := nat -> X)) k)  ).\n   rewrite (H1 (vmap (fst (A := nat) (B := nat -> X)) k)).\n   intros. destruct (vCons k); unfold vhead; unfold vtail; simpl.\n   destruct a0; simpl in *. \n   rewrite (H (proj1 (H0 a)) (proj2 (H0 a))); trivial.\n   intros. destruct H as [L R]; destruct L; destruct R; trivial.\n  Qed.\n\n\n  End Equality. \n \n\n(** * Experiements with arithmetic representation *)\n\n (** first some basic tactics to introduce the assumptions, etc *)\n  Ltac remLtLe' :=\n     match goal with \n     | [|- context [lt_le_dec ?x ?y]] =>  destruct (lt_le_dec x y) \n  end.\n\n Ltac remLtLe := repeat remLtLe'. \n\n Ltac initialise_tac :=\n     apply isEQ; simpl; intros; vSimp; simpl in *; remLtLe.\n\n  (** main tactic *)\n  Ltac containers :=\n      initialise_tac; optimiseOmega;  omega.\n\n\n  Section Examples_and_Definitions.\n(** Definitions and Exmaples*)\n\n  (** reverse *)\n  Definition Rev1 :  Plfun 1 *  Plfun 2  :=\n   (  lp (vr (fz _ )) ,  \n   (lp (suB (suB (vr (fz _)) (vr (tp _))) (cnst _ 1))) ). (*pf (lp (suB (vr (fz _))  (vr (tp _)))) (lp (cnst _ 0))). *)\n \n  (** identity function  *)\n  Definition Id1 n :  lfun n :=\n    match n with\n    | O => cnst _ 0\n    | S n => vr (tp n)\n    end.\n\n  Definition Idf :  Plfun 1 *  Plfun 2  := (   lp (vr (fz _ )) , lp (Id1 2)).\n  \n  \n  (** rev is involutive  *)\n  Lemma rev_rev_idm  :  pcmEQ (PPComp Rev1 Rev1) Idf.\n     containers.\n   (*  currently takes 11 seconds *)\n  Qed.\n\n \n  (* Append = (n, f) where\n      n = \\lambda  n m. n + m\n      f = \\lambda n m i. if i < n + m then  \n                               if i < n then i else n - i\n                          else 0\n   *)\n  (** Append  *)\n  Definition appn1 : PPCm 1 :=\n     (lp (adD (vr (fz _ )) (vr (fs (fz _)))) , \n          (pf (lp (suB (vr (fz _)) (vr (tp _)))) (lp (vr (tp 2))) (lp (suB (vr (fz _)) (vr (tp 2))))) \n     ).\n\n \n   (**  app reverse *)\n  Lemma rev1_appn1 : pcmEQ (PPComp Rev1 appn1) (pmp Rev1 appn1).\n  Proof.  \n    containers.\n   (* apply isEQ; simpl; intros; vSimp; simpl in *; remLtLe; repeat remMinus_0; auto. *)\n  Qed.\n\n  \n\n (* tail = (f ,g ) where\n         f n = n - 1 \n         g n i =  i + 1   *)\n\n (** tail  *)\n Definition tail1 : PPCm 0 :=\n    ( lp (suB (vr (fz _)) (cnst _ 1)) , lp (adD (vr (tp 1)) (cnst _ 1)) ).\n\n (* butlast = (f , g)  where\n       (f , g) where\n       f n = n - 1\n       g n i =  i (or i - 1) *)\n\n (** But last *)\n Definition butlast1 : PPCm 0 :=\n     ( lp (suB (vr (fz _)) (cnst _ 1)) , lp (vr (tp _ ))) (*suB (vr (tp _)) (cnst _ 1)) *).\n\n(** last *)\n Definition last1 : PPCm 0 :=\n    ( lp (suB (vr (fz _)) (suB (vr (fz _)) (cnst _ 1))) ,\n      pf (lp (suB (suB (vr (fz _)) (suB (vr (fz _)) (cnst _ 1))) (vr (tp _ ))))\n         (lp (suB (vr (fz _)) (cnst _ 1))) (lp (cnst _ 0))).\n\n\n (** head  *)\n Definition head1 : PPCm 0 :=\n    (lp (suB (vr (fz _)) (suB (vr (fz _)) (cnst _ 1))),\n        pf (lp (suB (suB (vr (fz _)) (suB (vr (fz _)) (cnst _ 1))) (vr (tp _ ))))\n         (lp (cnst _ 0)) (lp (cnst _ 0))).\n\n \n (** Theorems:  \n -- 1.  Theorem crev_chead_clast :  (m_comp cHead crev) ==== clast.\n -- 2.  Theorem crev_cbut_last_ctail :  (m_comp ctail crev) ==== (m_comp crev cbut_lst).\n *)\n \n Lemma  rev_head_last : pcmEQ (PPComp head1 Rev1) last1.\n    containers. \n Qed.\n\n\n Lemma  crev_butlast_tail : pcmEQ (PPComp tail1 Rev1) (PPComp Rev1 butlast1).\n   containers. \n Qed.\n\n\n  (** Take               *)\n Definition take1 m : PPCm 0 :=\n    ( pf (lp (suB (cnst _ m) (vr (fz _)))) (lp (cnst _ m)) (lp (vr (fz 0)))  ,\n       (pf (lp (suB (cnst _ m) (vr (tp 1)))) (lp (cnst _ m)) (lp (vr (tp 1))))\n    ).\n   \n\n  (** drop m   *)\n  Definition drop1 m : PPCm 0 :=\n    ( lp (suB (vr (fz _)) (cnst _ m)) , lp (adD (vr (tp _)) (cnst _ m)) ).\n\n\n (**  drop n (drop m xs) = drop (n + m) xs  *)\n Lemma drop_drop n m : pcmEQ (PPComp (drop1 n) (drop1 m)) (drop1 (n + m)). \n Proof.\n   intros. containers.\n Qed.\n\n (* drop n (take m xs) = take (m - n) (drop n xs)  *)\n Lemma drop_take n m : pcmEQ (PPComp (drop1 n) (take1 m)) (PPComp (take1 (m - n)) (drop1 n)).\n Proof. \n   intros. containers.\n Qed.\n\n (**  take n (drop m xs) = drop m (take (n + m) xs) *)\n Lemma take_drop n m : pcmEQ (PPComp (take1 n) (drop1 m)) (PPComp (drop1 m) (take1 (n + m))).\n Proof.\n    intros. containers.\n Qed.\n\n\n  (* rot1 = (f ,g ) where\n        f = id\n        g = \\lambda n i.  if i < 1 then n- 1 else i -1\n                           *)\n   (** unrotate  - put last element at the front  *)\n  Definition unrot1 : PPCm 0 :=\n    (lp (Id1 1) ,\n     pf (lp (vr (tp _))) \n         (lp (suB (vr (tp _)) (cnst _ 1)))  (lp (suB (vr (fz _)) (cnst _ 1)))\n    ).\n\n  (* rotate - dual to unrotate *)\n  Definition rot1 : PPCm 0 :=\n    (lp (Id1 1) ,\n     pf (lp (suB (suB (vr (fz _))  (cnst _ 1)) (vr (tp _)))) \n         (lp (adD (vr (tp _)) (cnst _ 1)))\n        (* (lp (suB (vr (tp _)) (suB (vr (fz _))  (cnst _ 1)))) *)\n          (lp (cnst _ 0)) \n    ).\n\n  (** roatate (unrotate x) = xs *)\n Lemma rot_unrot : pcmEQ (PPComp rot1 unrot1)  Idf.\n Proof.\n     containers.\n  Qed.\n\n (** head  head (reverse ( rotate xs )) = head xs  *)\n Lemma head_rev_rot : pcmEQ (PPComp head1 (PPComp Rev1 rot1)) head1.\n Proof.\n    containers.\n Qed.\n  \n\n (**  last (rotate xs) = head xs *)\n Lemma last_rot_head : pcmEQ (PPComp last1 rot1) head1.\n Proof.\n   containers.\n Qed.\n\n (** head (unrotate xs) = last xs  *)\n Lemma head_unrot_last : pcmEQ (PPComp head1 unrot1) last1.\n Proof.\n   containers.\n Qed.\n\n (**   drop 1 (unrotate xs) =  butlast xs *)\n Lemma drop_unrot_but_last : pcmEQ (PPComp (drop1 1) unrot1) butlast1.\n Proof.\n   containers.\n Qed.\n\n (**  butlast (rotate xs) = tail xs*)\n Lemma butlast_rot_tail : pcmEQ (PPComp butlast1 rot1) tail1.\n Proof.\n   containers.\n Qed.\n   \nEnd Examples_and_Definitions.\n\n", "meta": {"author": "rawlep", "repo": "ArithmeticAnaysisOfPolymorphicPrograms", "sha": "1e7919ade56888a7134597e25d9fb1438e24a75b", "save_path": "github-repos/coq/rawlep-ArithmeticAnaysisOfPolymorphicPrograms", "path": "github-repos/coq/rawlep-ArithmeticAnaysisOfPolymorphicPrograms/ArithmeticAnaysisOfPolymorphicPrograms-1e7919ade56888a7134597e25d9fb1438e24a75b/DecidableFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7186066483108761}}
{"text": "Require Import Coq.Program.Program.\nRequire Import Coq.Arith.Compare_dec.\nNotation \"( x & y )\" := (existS _ x y) : core_scope.\n\nRequire Import Omega.\n\nProgram Fixpoint euclid (a : nat) (b : { b : nat | b <> O }) {wf lt a}  :\n  { q : nat & { r : nat | a = b * q + r /\\ r < b } } :=\n  if le_lt_dec b a then let (q', r) := euclid (a - b) b in\n  (S q' & r)\n  else (O & a).\n\nNext Obligation.\n  assert(b * S q' = b * q' + b) by auto with arith ; omega.\nDefined.\n\nProgram Definition test_euclid : (prod nat nat) := let (q, r) := euclid 4 2 in (q, q).\n\nEval lazy beta zeta delta iota in test_euclid.\n\nProgram Definition testsig (a : nat) : { x : nat & { y : nat | x < y } } :=\n  (a & S a).\n\nCheck testsig.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/plugins/subtac/test/euclid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542887603537, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.7184902131145319}}
{"text": "(**\n\nBasic facts about types not being equal. Includes some examples and\nsome more general theorems. The heart of the type inequality proof for\nfinite types is a fact about finite isomorphisms in finite_iso.v.\n\nExamples include some simple (small) finite types as well as\ninequality of sets and their powersets, via diagonalization.\n\n*)\n\nSet Implicit Arguments.\n\nRequire Import finite_iso.\n\n(* Some manual proofs of type inequalities, with techniques specific\nto the small cardinalities involved. *)\n\nTheorem empty_not_unit : Empty_set <> unit.\nProof.\n  intro.\n  pose proof tt.\n  rewrite <- H in H0.\n  inversion H0.\nQed.\n\nTheorem unit_not_bool : unit <> bool.\nProof.\n  intro.\n  assert (forall x y:unit, x = y).\n  destruct x, y; auto.\n  rewrite H in H0.\n  pose proof (H0 true false).\n  inversion H1.\nQed.\n\n(* unit can only be proven not equal to inhabited option types, hence\nthe extra premise of any a:A) *)\nTheorem unit_not_option : forall A (a:A),\n   (unit:Type) <> option A.\nProof.\n  unfold not; intros.\n  assert (forall x y:unit, x = y).\n  destruct x, y; auto.\n  rewrite H in H0.\n  pose proof (H0 (Some a) None).\n  inversion H1.\nQed.\n\nTheorem bool_not_nat : bool <> nat.\nProof.\n  intro.\n  assert (forall x y z:bool, x = y \\/ y = z \\/ x = z).\n  destruct x, y, z; eauto.\n  rewrite H in H0.\n  pose proof (H0 0 1 2).\n  intuition congruence.\nQed.\n\nRequire Import cardinality.\n\nTheorem no_iso_ineq : forall A B,\n  (Iso.T A B -> False) ->\n  A <> B.\nProof.\n  unfold not; intros; subst.\n  auto using Iso.Refl.\nQed.\n\nTheorem no_iso_ineq_set : forall (A B:Set),\n  (Iso.T A B -> False) ->\n  A <> B.\nProof.\n  unfold not; intros; subst.\n  auto using Iso.Refl.\nQed.\n\nCorollary nat_not_baire_space : nat <> (nat -> nat).\nProof.\n  apply no_iso_ineq_set.\n  apply Iso.Cantor.\nQed.\n\nTheorem one_cardinality : forall A n m\n  (iso_n: cardinality A n)\n  (iso_m: cardinality A m),\n  n = m.\nProof.\n  intros.\n  pose proof (Iso.Trans (Iso.Sym iso_n) iso_m).\n  apply fin_iso; assumption.\nQed.\n\nTheorem neq_cardinalities : forall (A B:Type) n m,\n  cardinality A n ->\n  cardinality B m ->\n  n <> m ->\n  A <> B.\nProof.\n  intros.\n  intro; subst.\n  eauto using one_cardinality.\nQed.\n\nExample unit_neq_bool : (unit:Type) <> bool.\nProof.\n  apply neq_cardinalities with (n := 1) (m := 2).\n  exact unit_1.\n  exact bool_2.\n  auto.\nQed.\n\n(** Diagonalization between a set and its powerset, defined\ncomputationally as boolean functions on the set. *)\nTheorem powerset_bigger : forall A, Iso.T A (A -> bool) -> False.\nProof.\n  (* this proof is modeled after Theorem 13.7 in\n  http://www.people.vcu.edu/~rhammack/BookOfProof/Cardinality.pdf,\n  though our formulation of isomorphisms is a bit different (rather\n  than requiring a single injective and surjective function we provide\n  both functions and both directions of inverse proofs) *)\n  destruct 1.\n  pose (f := fun x => if (to x x) then false else true).\n  assert (to (from f) (from f) = f (from f)) by\n    (rewrite to_from; reflexivity).\n  destruct (to (from f) (from f)) eqn:?.\n  unfold f in *.\n  rewrite Heqb in H.\n  congruence.\n\n  unfold f in *.\n  rewrite Heqb in H.\n  congruence.\n\n  (* the theorem is proven, but we provide an alternate proof that\n  looks a bit nicer and uses the same intuition as above. *)\nRestart.\n  destruct 1.\n  pose (f := fun x => negb (to x x)).\n  assert (f (from f) = negb (to (from f) (from f))).\n  unfold f.\n  rewrite to_from.\n  reflexivity.\n  rewrite to_from in H.\n  eapply Bool.no_fixpoint_negb; eauto.\nQed.\n\nCorollary type_not_powerset : forall A,\n  A <> (A -> bool).\nProof.\n  intros.\n  apply no_iso_ineq.\n  apply powerset_bigger.\nQed.\n", "meta": {"author": "tchajed", "repo": "cardinality", "sha": "9ba233ed1c0b927a19865e60abf65328def49405", "save_path": "github-repos/coq/tchajed-cardinality", "path": "github-repos/coq/tchajed-cardinality/cardinality-9ba233ed1c0b927a19865e60abf65328def49405/type_neq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7184836969112529}}
{"text": "Require Import UniMath.Foundations.All.\n\n(** When proving a negation, we may undo a double negation. *)\nLemma wma_dneg {X:Type} (P:Type) : ¬¬ P -> (P -> ¬ X) -> ¬ X.\nProof.\n  intros dnp p.\n  apply dnegnegtoneg.\n  assert (q := dnegf p); clear p.\n  apply q; clear q.\n  apply dnp.\nDefined.\n\n(** It's not false that a type is decidable. *)\nLemma dneg_decidable (P:Type) : ¬¬ decidable P.\nProof.\n  intros ndec.\n  unfold decidable in ndec.\n  assert (q := fromnegcoprod ndec); clear ndec.\n  contradicts (pr1 q) (pr2 q).\nDefined.\n\n(** When proving a negation, we may assume a type is decidable. *)\nLemma wma_decidable {X:Type} (P:Type) : (decidable P -> ¬ X) -> ¬ X.\nProof.\n  apply (wma_dneg (decidable P)).\n  apply dneg_decidable.\nDefined.\n\nLocal Open Scope logic.\n\n(** Compare with [negforall_to_existsneg], which uses LEM instead. *)\nLemma negforall_to_existsneg' {X:Type} (P:X->Type) : (¬ ∏ x, ¬¬ (P x)) -> ¬¬ (∃ x, ¬ (P x)).\nProof.\n  intros nf c. use nf; clear nf. intro x.\n  assert (q := neghexisttoforallneg _ c x); clear c; simpl in q.\n  exact q.\nDefined.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/MoreFoundations/DoubleNegation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7853085884247212, "lm_q1q2_score": 0.7184795793361376}}
{"text": "(* Exercise 5.7 *)\n(* Here are five statements that are often considered as characterizations\n   of classical logic. Prove that these five propositions are equivalent. *)\n\nDefinition peirce := forall P Q : Prop, ((P -> Q) -> P) -> P.\nDefinition classic := forall P : Prop, ~~P -> P.\nDefinition excluded_middle := forall P : Prop, P \\/ ~P.\nDefinition de_morgan_not_and_not := forall P Q : Prop, ~(~P /\\ ~Q) -> P \\/ Q.\nDefinition implies_to_or := forall P Q : Prop, (P -> Q) -> (~P \\/ Q).\n\nTheorem excluded_middle_peirce_with_elim : excluded_middle -> peirce.\nProof.\n  unfold excluded_middle, peirce.\n  intros excluded_middle P Q H.\n  elim (excluded_middle P).\n  apply id.\n  intro H0.\n  apply H.\n  intro p.\n  apply False_ind.\n  apply H0.\n  assumption.\nQed.\n\nTheorem excluded_middle_peirce_with_exact : excluded_middle -> peirce.\nProof.\n  unfold excluded_middle, peirce.\n  intros excluded_middle P Q H.\n  exact (or_ind (* (P:=P) *)\n                (fun p => p)\n                (fun H0 => (H (fun p => False_ind Q (H0 p))))\n                (excluded_middle P)).\nQed.\n\nTheorem excluded_middle_peirce : excluded_middle -> peirce.\nProof.\n  unfold excluded_middle, peirce.\n  intros excluded_middle P Q H.\n  cut (~P -> P).\n  intro H0.\n  apply (or_ind (fun p => p) H0).\n  apply excluded_middle.\n  intro H1.\n  apply H.\n  intro p.\n  apply False_ind.\n  apply H1.\n  assumption.\nQed.\n\n\nTheorem peirce_implies_classic : peirce -> classic.\nProof.\n  unfold peirce, classic.\n  intros peirce P H.\n  apply (peirce P False).\n  intro H0.\n  apply False_ind.\n  apply H.\n  intro p.\n  apply H0.\n  assumption.\nQed.\n\nTheorem classic_implies_excluded_middle : classic -> excluded_middle.\nProof.\n  unfold classic, excluded_middle.\n  intros classic P.\n  apply classic.\n  intro H.\n  apply H.\n  right.\n  intro p.\n  apply H.\n  left.\n  assumption.\nQed.\n\nTheorem excluded_middle_implies_to_or_with_exact :  excluded_middle -> implies_to_or.\nProof.\n  unfold excluded_middle, implies_to_or.\n  intros excluded_middle P Q H.\n  exact (or_ind (fun p : P => or_intror (H p))\n                (fun H0 : ~P => or_introl H0)\n        (excluded_middle P)).\nQed.\n\nTheorem excluded_middle_implies_to_or_with_elim :  excluded_middle -> implies_to_or.\nProof.\n  unfold excluded_middle, implies_to_or.\n  intros excluded_middle P Q H.\n  elim (excluded_middle P).\n  intro p.\n  right.\n  apply H.\n  assumption.\n  intro H0.\n  left.\n  assumption.\nQed.\n\nTheorem excluded_middle_implies_to_or :  excluded_middle -> implies_to_or.\nProof.\n  unfold excluded_middle, implies_to_or.\n  intros excluded_middle P Q H.\n  cut (P -> ~P \\/ Q).\n  intro H0.\n  cut (~P -> ~P \\/ Q).\n  intro H1.\n  apply (or_ind H0 H1).\n  apply excluded_middle.\n  apply or_introl.\n  intro p.\n  apply or_intror.\n  apply H.\n  assumption.\nQed.\n\nTheorem implies_to_or_excluded_middle : implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or, excluded_middle.\n  intros implies_to_or P.\n  apply or_comm.\n  apply (implies_to_or P P).\n  apply id.\nQed.\n\nTheorem implies_to_or_excluded_middle_with_exact : implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or, excluded_middle.\n  intros implies_to_or P.\n  exact (match (implies_to_or P P (fun p : P => p)) with\n         | or_introl H => or_intror H\n         | or_intror H => or_introl H\n        end).\nQed.\n\nTheorem implies_to_or_excluded_middle_with_elim : implies_to_or -> excluded_middle.\nProof.\n  unfold implies_to_or, excluded_middle.\n  intros implies_to_or P.\n  elim (implies_to_or P P).\n  intro H.\n  apply or_intror.\n  assumption.\n  intro p.\n  apply or_introl.\n  assumption.\n  apply id.\nQed.\n\n\nTheorem classic_de_morgan_not_and_not : classic -> de_morgan_not_and_not.\n  unfold classic, de_morgan_not_and_not.\n  intros classic P Q H.\n  apply classic.\n  intro H0.\n  apply H.\n  apply conj.\n  intro p.\n  apply H0.\n  apply or_introl.\n  assumption.\n  intro q.\n  apply H0.\n  apply or_intror.\n  assumption.\nQed.\n\nTheorem de_morgan_not_and_not_excluded_middle : de_morgan_not_and_not -> excluded_middle.\nProof.\n  unfold de_morgan_not_and_not, excluded_middle.\n  intros de_morgan_not_and_not P.\n  apply de_morgan_not_and_not.\n  intro H.\n  apply H.\n  intro p.\n  apply proj1 in H.\n  apply H.\n  assumption.\nQed.\n\nTheorem de_morgan_not_and_not_excluded_middle_with_assert : de_morgan_not_and_not -> excluded_middle.\nProof.\n  unfold de_morgan_not_and_not, excluded_middle.\n  intros de_morgan_not_and_not P.\n  apply de_morgan_not_and_not.\n  intro H.\n  apply H.\n  intro p.\n  assert (H0 : ~P).\n  apply H.\n  apply H0.\n  assumption.\nQed.\n", "meta": {"author": "aymanosman", "repo": "coq-art-exercises", "sha": "ff7e2aba35a5094d366be5b9f55dfdd13d38cd48", "save_path": "github-repos/coq/aymanosman-coq-art-exercises", "path": "github-repos/coq/aymanosman-coq-art-exercises/coq-art-exercises-ff7e2aba35a5094d366be5b9f55dfdd13d38cd48/05_everyday_logic/exercise_07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320035, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.7184795628533522}}
{"text": "Require Import init.\n\nRequire Export mult_ring.\nRequire Import relation.\n\nDefinition divides {U} `{Mult U} a b := ∃ c, c * a = b.\n(** Note that this is the unicode symbol '∣', not '|'!  It is the LaTeX \\mid.\nThe reason for this is that using the normal '|' causes issues with things like\npattern matching.\n*)\nInfix \"∣\" := divides (at level 50).\n\nDefinition unit {U} `{Mult U, One U} a := a ∣ 1.\nDefinition associates {U} `{Mult U} a b := a ∣ b ∧ b ∣ a.\nDefinition irreducible {U} `{Zero U, Mult U, One U} p\n    := 0 ≠ p ∧ ¬unit p ∧ ∀ a b, ¬unit a → ¬unit b → p ≠ a * b.\nDefinition prime {U} `{Zero U, Mult U, One U} p\n    := 0 ≠ p ∧ ¬unit p ∧ ∀ a b, p ∣ (a * b) → p ∣ a ∨ p ∣ b.\n\nDefinition even {U} `{Plus U, Mult U, One U} a := 2 ∣ a.\nDefinition odd {U} `{Plus U, Mult U, One U} a := ¬(2 ∣ a).\n\n(* begin hide *)\nSection Div.\n\nContext {U} `{Up : Plus U,\n                  @PlusAssoc U Up,\n                  @PlusComm U Up,\n              Uz : Zero U,\n                  @PlusLid U Up Uz,\n              Un : Neg U,\n                  @PlusLinv U Up Uz Un,\n              Um : Mult U,\n                  @MultAssoc U Um,\n                  @MultComm U Um,\n                  @Ldist U Up Um,\n                  @Rdist U Up Um,\n                  @MultLanni U Uz Um,\n                  @MultRanni U Uz Um,\n              Uo : One U,\n                  @MultLid U Um Uo,\n                  @MultRid U Um Uo,\n                  @MultLcancel U Uz Um,\n                  @MultRcancel U Uz Um,\n              Ul : Order U,\n                  @Connex U le,\n                  @Antisymmetric U le,\n                  @Transitive U le\n              }.\n\nLemma divides_refl : ∀ a, a ∣ a.\nProof.\n    intros a.\n    exists 1.\n    apply mult_lid.\nQed.\n(* end hide *)\nGlobal Instance divides_refl_class : Reflexive divides := {\n    refl := divides_refl\n}.\n\n(* begin hide *)\nLemma divides_trans : ∀ a b c, a ∣ b → b ∣ c → a ∣ c.\nProof.\n    intros a b c [d eq1] [e eq2].\n    exists (e * d).\n    rewrite <- mult_assoc.\n    rewrite eq1.\n    rewrite eq2.\n    reflexivity.\nQed.\n(* end hide *)\nGlobal Instance divides_trans_class : Transitive divides := {\n    trans := divides_trans\n}.\n\nTheorem one_divides : ∀ n, 1 ∣ n.\nProof.\n    intros n.\n    exists n.\n    apply mult_rid.\nQed.\n\nTheorem divides_zero : ∀ a, a ∣ 0.\nProof.\n    intros a.\n    exists 0.\n    apply mult_lanni.\nQed.\n\nTheorem divides_neg : ∀ a b, a ∣ b → a ∣ -b.\nProof.\n    intros a b [c eq].\n    exists (-c).\n    rewrite mult_lneg.\n    apply f_equal.\n    exact eq.\nQed.\n\nTheorem plus_stays_divides : ∀ p a b, p ∣ a → p ∣ b → p ∣ (a + b).\nProof.\n    intros p a b [c c_eq] [d d_eq].\n    exists (c + d).\n    rewrite <- c_eq, <- d_eq.\n    apply rdist.\nQed.\n\nTheorem plus_changes_divides : ∀ p a b,\n                               p ∣ a → ¬(p ∣ b) → ¬(p ∣ (a + b)).\nProof.\n    intros p a b [c c_eq] not [d d_eq].\n    rewrite <- c_eq in d_eq.\n    apply lplus with (-(c * p)) in d_eq.\n    rewrite plus_assoc, plus_linv, plus_lid in d_eq.\n    rewrite <- mult_lneg in d_eq.\n    rewrite <- rdist in d_eq.\n    unfold divides in not.\n    rewrite not_ex in not.\n    specialize (not (-c + d)).\n    contradiction.\nQed.\n\nTheorem mult_factors_extend : ∀ p a b, p ∣ a → p ∣ a * b.\nProof.\n    intros p a b [c eq].\n    exists (b * c).\n    rewrite (mult_comm a).\n    rewrite <- eq.\n    symmetry; apply mult_assoc.\nQed.\n\nTheorem mult_factors_back : ∀ a b c, a * b = c → a ∣ c ∧ b ∣ c.\nProof.\n    intros a b c eq.\n    split.\n    -   exists b.\n        rewrite mult_comm.\n        exact eq.\n    -   exists a.\n        exact eq.\nQed.\n\nTheorem mult_div_lself : ∀ a b, a ∣ a * b.\nProof.\n    intros a b.\n    exists b.\n    apply mult_comm.\nQed.\n\nTheorem mult_div_rself : ∀ a b, a ∣ b * a.\nProof.\n    intros a b.\n    exists b.\n    reflexivity.\nQed.\n\nTheorem div_rcancel : ∀ a b c, 0 ≠ c → a * c ∣ b * c → a ∣ b.\nProof.\n    intros a b c c_nz [x eq].\n    exists x.\n    rewrite mult_assoc in eq.\n    apply mult_rcancel in eq; [>|exact c_nz].\n    exact eq.\nQed.\n\nTheorem div_lcancel : ∀ a b c, 0 ≠ a → a * b ∣ a * c → b ∣ c.\nProof.\n    intros a b c a_nz.\n    do 2 rewrite (mult_comm a).\n    apply div_rcancel.\n    exact a_nz.\nQed.\n\nTheorem unit_mult : ∀ a b, unit a → unit b → unit (a * b).\nProof.\n    intros a b [a' a_eq] [b' b_eq].\n    exists (b' * a').\n    rewrite <- mult_assoc.\n    rewrite (mult_assoc a').\n    rewrite a_eq.\n    rewrite mult_lid.\n    apply b_eq.\nQed.\n\nTheorem div_mult_unit : ∀ a b, 0 ≠ a → a * b ∣ a → unit b.\nProof.\n    intros a b a_nz eq.\n    destruct eq as [c eq].\n    exists c.\n    rewrite (mult_comm a b) in eq.\n    rewrite mult_assoc in eq.\n    rewrite <- (mult_lid a) in eq at 2.\n    apply mult_rcancel in eq; [>|exact a_nz].\n    exact eq.\nQed.\n\nTheorem prime_irreducible : ∀ p, prime p → irreducible p.\nProof.\n    intros p [p_nz [p_nu p_prime]].\n    repeat split; [>exact p_nz|exact p_nu|].\n    intros a b a_nu b_nu.\n    intros contr.\n    subst p.\n    assert (0 ≠ a) as a_nz.\n    {\n        intros contr.\n        subst a.\n        rewrite mult_lanni in p_nz.\n        contradiction.\n    }\n    assert (0 ≠ b) as b_nz.\n    {\n        intros contr.\n        subst b.\n        rewrite mult_ranni in p_nz.\n        contradiction.\n    }\n    specialize (p_prime a b (refl (a * b))) as [d1|d2].\n    -   apply div_mult_unit in d1; [>|exact a_nz].\n        contradiction.\n    -   rewrite mult_comm in d2.\n        apply div_mult_unit in d2; [>|exact b_nz].\n        contradiction.\nQed.\n\nTheorem associates_refl : ∀ a, associates a a.\nProof.\n    intros a.\n    split.\n    all: exists 1.\n    all: apply mult_lid.\nQed.\n\nTheorem associates_sym : ∀ a b, associates a b → associates b a.\nProof.\n    intros a b [ab ba].\n    split; assumption.\nQed.\n\nTheorem associates_trans :\n    ∀ a b c, associates a b → associates b c → associates a c.\nProof.\n    intros a b c [ab ba] [bc cb].\n    split.\n    -   exact (divides_trans _ _ _ ab bc).\n    -   exact (divides_trans _ _ _ cb ba).\nQed.\n\n(* begin hide *)\nEnd Div.\n(* end hide *)\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/Algebra/Ring/Domain/mult_div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7184716784510793}}
{"text": "(***********************************************************************)\n(** * Definition of STLC *)\n(***********************************************************************)\n\n(** This file containes all of the definitions for a locally-nameless\n    representation of a Curry-Style simply-typed lambda calculus.\n\n    This file was generated via Ott from `stlc.ott` and then edited to\n    include explanation about the definitions. As a result, it is gathers\n    all of the STLC definitions in one place, but the associated\n    exercises are found elsewhere in the tutorial.  You'll want to refer\n    back to this file as you progress through the rest of the\n    material. *)\n\n\nRequire Import Metalib.Metatheory.\n\n(***********************************************************************)\n(** * Syntax of STLC *)\n(***********************************************************************)\n\n(** We use a locally nameless representation for the simply-typed lambda\n    calculus, where bound variables are represented as natural numbers\n    (de Bruijn indices) and free variables are represented as [atom]s.\n\n    The type [atom], defined in the Metatheory library, represents names.\n    Equality on names is decidable, and it is possible to generate an\n    atom fresh for any given finite set of atoms ([atom_fresh]).\n\n    Note: the type [var] is notation for [atom].  *)\n\nInductive typ : Set :=  (*r types *)\n | typ_base : typ\n | typ_arrow (T1:typ) (T2:typ).\n\nInductive exp : Set :=  (*r expressions *)\n | var_b (_:nat)\n | var_f (x:var)\n | abs (e:exp)\n | app (e1:exp) (e2:exp).\n\n\n(***********************************************************************)\n(** * Substitution *)\n(***********************************************************************)\n\n(** Substitution replaces a free variable with a term.  The definition\n    below is simple for two reasons:\n      - Because bound variables are represented using indices, there\n        is no need to worry about variable capture.\n      - We assume that the term being substituted in is locally\n        closed.  Thus, there is no need to shift indices when\n        passing under a binder.\n*)\n\n(** The [Fixpoint] keyword defines a Coq function.  As all functions in\n    Coq must be total.  The annotation [{struct e}] indicates the\n    termination metric---all recursive calls in this definition are made\n    to arguments that are structurally smaller than [e].\n\n    Note also that [subst_exp] uses [x == y] for decidable equality.\n    This operation is defined in the Metatheory library.  *)\n\nFixpoint subst_exp (u:exp) (y:var) (e:exp) {struct e} : exp :=\n  match e with\n  | (var_b n)   => var_b n\n  | (var_f x)   => (if x == y then u else (var_f x))\n  | (abs e1)    => abs (subst_exp u y e1)\n  | (app e1 e2) => app (subst_exp u y e1) (subst_exp u y e2)\nend.\n\n(***********************************************************************)\n(** * Free variables *)\n(***********************************************************************)\n\n(** The function [fv_exp], defined below, calculates the set of free\n    variables in an expression.  Because we are using a locally\n    nameless representation, where bound variables are represented as\n    indices, any name we see is a free variable of a term.  In\n    particular, this makes the [abs] case simple.\n*)\n\nFixpoint fv_exp (e_5:exp) : vars :=\n  match e_5 with\n  | (var_b nat)   => {}\n  | (var_f x)   => {{x}}\n  | (abs e)     => fv_exp e\n  | (app e1 e2) => fv_exp e1 `union` fv_exp e2\nend.\n\n(** The type [vars] represents a finite set of elements of type [atom].\n    The notations for the finite set definitions (empty set `{}`,\n    singleton `{{x}}` and union `\\u`) is also defined in the Metatheory\n    library.  *)\n\n\n\n(***********************************************************************)\n(** * Opening *)\n(***********************************************************************)\n\n(** Opening replaces an index with a term.  It corresponds to informal\n    substitution for a bound variable, such as in the rule for beta\n    reduction.  Note that only \"dangling\" indices (those that do not\n    refer to any abstraction) can be opened.  Opening has no effect for\n    terms that are locally closed.\n\n    Natural numbers are just an inductive datatype with two constructors:\n    [O] (as in the letter 'oh', not 'zero') and [S], defined in\n    Coq.Init.Datatypes.  Coq allows literal natural numbers to be written\n    using standard decimal notation, e.g., 0, 1, 2, etc.  The function\n    [lt_eq_lt_dec] compares its two arguments for ordering.\n\n    We do not assume that zero is the only unbound index in the term.\n    Consequently, we must substract one when we encounter other unbound\n    indices (i.e. the [inright] case).\n\n    However, we do assume that the argument [u] is locally closed.  This\n    assumption simplifies the implementation since we do not need to\n    shift indices in [u] when passing under a binder. *)\n\nFixpoint open_exp_wrt_exp_rec (k:nat) (u:exp) (e:exp) {struct e}: exp :=\n  match e with\n  | (var_b n) =>\n      match lt_eq_lt_dec n k with\n        | inleft (left _)  => var_b n\n        | inleft (right _) => u\n        | inright _        => var_b (n - 1)\n      end\n  | (var_f x)   => var_f x\n  | (abs e)     => abs (open_exp_wrt_exp_rec (S k) u e)\n  | (app e1 e2) => app (open_exp_wrt_exp_rec k u e1)\n                      (open_exp_wrt_exp_rec k u e2)\nend.\n\nDefinition open_exp_wrt_exp e u := open_exp_wrt_exp_rec 0 u e.\n\n\n(***********************************************************************)\n(** * Notations *)\n(***********************************************************************)\n\n\n(** Many common applications of opening replace index zero with an\n    expression or variable.  The following definition provides a\n    convenient shorthand for such uses.  Note that the order of\n    arguments is switched relative to the definition above.  For\n    example, [(open e x)] can be read as \"substitute the variable [x]\n    for index [0] in [e]\" and \"open [e] with the variable [x].\"\n*)\n\nModule StlcNotations.\nNotation \"[ z ~> u ] e\" := (subst_exp u z e) (at level 0) : exp_scope.\nNotation open e1 e2     := (open_exp_wrt_exp e1 e2).\nNotation \"e ^ x\"        := (open_exp_wrt_exp e (var_f x)) : exp_scope.\nEnd StlcNotations.\nImport StlcNotations.\nOpen Scope exp_scope.\n\n(***********************************************************************)\n(** * Local closure *)\n(***********************************************************************)\n\n(** Recall that [exp] admits terms that contain unbound indices.  We say\n    that a term is locally closed when no indices appearing in it are\n    unbound.  The proposition [lc_exp e] holds when an expression [e] is\n    locally closed.\n\n    The inductive definition below formalizes local closure such that the\n    resulting induction principle serves as the structural induction\n    principle over (locally closed) expressions.  In particular, unlike\n    induction for type [exp], there are no cases for bound variables.\n    Thus, the induction principle corresponds more closely to informal\n    practice than the one arising from the definition of pre-terms.  *)\n\n\nInductive lc_exp : exp -> Prop :=\n | lc_var_f : forall (x:var),\n     lc_exp (var_f x)\n | lc_abs : forall (e:exp),\n      (forall x , lc_exp (open e (var_f x)))  ->\n     lc_exp (abs e)\n | lc_app : forall (e1 e2:exp),\n     lc_exp e1 ->\n     lc_exp e2 ->\n     lc_exp (app e1 e2).\n\n\n(***********************************************************************)\n(** * Typing contexts *)\n(***********************************************************************)\n\n(** We represent typing contexts as association lists (lists of pairs of\n    keys and values) whose keys are [atom]s.\n*)\n\nDefinition ctx : Set := list (atom * typ).\n\n(** For STLC, contexts bind [atom]s to [typ]s.\n\n    Lists are defined in Coq's standard library, with the constructors\n    [nil] and [cons].  The list library includes the [::] notation for\n    cons as well as standard list operations such as append, map, and\n    fold. The infix operation [++] is list append.\n\n    The Metatheory library extends this reasoning by instantiating the\n    AssocList library to provide support for association lists whose keys\n    are [atom]s.  Everything in this library is polymorphic over the type\n    of objects bound in the environment.  Look in AssocList.v for\n    additional details about the functions and predicates that we mention\n    below.  *)\n\n\n(***********************************************************************)\n(** * Typing relation *)\n(***********************************************************************)\n\n(** The definition of the typing relation is straightforward.  In\n    order to ensure that the relation holds for only well-formed\n    environments, we check in the [typing_var] case that the\n    environment is [uniq].  The structure of typing derivations\n    implicitly ensures that the relation holds only for locally closed\n    expressions.\n\n    Finally, note the use of cofinite quantification in\n    the [typing_abs] case.\n*)\n\nInductive typing : ctx -> exp -> typ -> Prop :=\n | typing_var : forall (G:ctx) (x:var) (T:typ),\n     uniq G ->\n     binds x T G  ->\n     typing G (var_f x) T\n | typing_abs : forall (L:vars) (G:ctx) (T1:typ) (e:exp) (T2:typ),\n     (forall x , x `notin` L -> typing ([(x,T1)] ++ G) (e ^ x) T2)  ->\n     typing G (abs e) (typ_arrow T1 T2)\n | typing_app : forall (G:ctx) (e1 e2:exp) (T2 T1:typ),\n     typing G e1 (typ_arrow T1 T2) ->\n     typing G e2 T1 ->\n     typing G (app e1 e2) T2 .\n\n\n(***********************************************************************)\n(** * Values and Small-step Evaluation *)\n(***********************************************************************)\n\n(** Finally, we define values and a call-by-name small-step evaluation\n    relation. In STLC, abstractions are the only value. *)\n\nDefinition is_value (e : exp) : Prop :=\n  match e with\n  | abs _   => True\n  | _       => False\n  end.\n\n(** For [step_beta], note that we use [open_exp_wrt_exp] instead of\n    substitution --- no variable names are involved.\n\n    Note also the hypotheses in [step] that ensure that the relation holds\n    only for locally closed terms.  *)\n\nInductive step : exp -> exp -> Prop :=\n | step_beta : forall (e1 e2:exp),\n     lc_exp (abs e1) ->\n     lc_exp e2 ->\n     step (app  (abs e1) e2)  (open e1 e2)\n | step_app : forall (e1 e2 e1':exp),\n     lc_exp e2 ->\n     step e1 e1' ->\n     step (app e1 e2) (app e1' e2).\n\n\nHint Constructors typing step lc_exp.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/Stlc/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7184716784510793}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling    [*]              *)\n(*             Jean-François Monin           [+]              *)\n(*                                                            *)\n(*            [*] Affiliation LORIA -- CNRS                   *)\n(*            [+] Affiliation VERIMAG - Univ. Grenoble-Alpes  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** From verify.rwth-aachen.de/giesl/papers/ibn96-30.ps\n\n    orig. algo from https://arxiv.org/ftp/cs/papers/9301/9301103.pdf\n\n   type Ω = α | ω of Ω * Ω * Ω\n\n   let rec nm e = match e with\n     | α                => α\n     | ω (α,y,z)        => ω (α,nm y,nm z)\n     | ω (ω(a,b,c),y,z) => nm (ω (a,nm(ω(b,y,z)),nm(ω(c,y,z)))\n\n  We simulate the following Inductive/Recursive definition\n\n  Inductive 𝔻 : Ω -> Prop :=\n    | d_nm_0 : 𝔻 α\n    | d_nm_1 : forall y z, 𝔻 y -> 𝔻 z -> 𝔻 (ω α y z)\n    | d_nm_2 : forall a b c y z (Db : 𝔻 (ω b y z)) (Dc : 𝔻 (ω c y z)),\n\\                      𝔻 (ω a (nm (ω b y z) D1) (nm (ω c y z) D2))\n\\                   -> 𝔻 (ω (ω a b c) y z)\n  with Fixpoint nm e (De : 𝔻 e) : Ω :=\n    match De with\n      | d_nm_0 => α\n      | d_nm_1 y z Dy Dz => ω α (nm y Dy) (nm z Dz)\n      | d_nm_2 a b c y z Db Dc Da => nm (ω a (nm (ω b y z) Db) (nm (ω c y z) Dc)) Da\n    end.\n*)\n\nRequire Import Arith Lia Wellfounded Extraction.\n\nRequire Import measure_ind.\n\nTactic Notation \"eq\" \"goal\" \"with\" hyp(H) := \n  match goal with \n    |- ?b => match type of H with ?t => replace b with t; auto end \n  end.\n\nSet Implicit Arguments.\n\nInductive cexpr : Set := At : cexpr | If : cexpr -> cexpr -> cexpr -> cexpr.\n\nNotation α := At.\nNotation ω := If.\nNotation Ω := cexpr.\n\nSection nm_def.\n\n  Reserved Notation \"x '~~>' y\" (at level 70, no associativity).\n  \n  Inductive 𝔾 : Ω -> Ω -> Prop :=\n    | in_gnm_0 :           α ~~> α\n\n    | in_gnm_1 y ny z nz :\n                         y   ~~>     ny\n                  ->       z ~~>        nz\n                  -> ω α y z ~~> ω α ny nz\n\n    | in_gnm_2 : forall a b c y z nb nc na,\n                             ω b y z ~~> nb\n                  ->         ω c y z ~~> nc\n                  ->       ω a nb nc ~~> na\n                  -> ω (ω a b c) y z ~~> na\n  where \"x ~~> y\" := (𝔾 x y).\n\n  Ltac inv_ind := match goal with \n      | H: forall x : _, ?t ~~> x -> ?y = x, \n        G: ?t ~~> ?z                         \n       |- _ => apply H in G; subst \n    end.\n\n  Local Fact 𝔾_fun e n1 n2 : e ~~> n1 -> e ~~> n2 -> n1 = n2.\n  Proof.\n    intros H; revert H n2.\n    induction 1 as [ \n                   | y ny z nz H1 IH1 H2 IH2\n                   | u v w y z na nb nc H1 IH1 H2 IH2 H3 IH3 ]; inversion 1; subst; auto.\n    + f_equal; auto.\n    + repeat inv_ind; auto.\n  Qed.\n  \n  Unset Elimination Schemes.\n\n  Inductive d_nm : Ω -> Prop :=\n    | in_dnm_0 :                   d_nm α\n    | in_dnm_1 : forall y z,       d_nm y \n                                -> d_nm z \n                                -> d_nm (ω α y z)\n    | in_dnm_2 : forall a b c y z,\n                                   d_nm (ω b y z) \n                                -> d_nm (ω c y z) \n                 -> (forall nb nc, ω b y z ~~> nb  \n                                -> ω c y z ~~> nc \n                                -> d_nm (ω a nb nc))\n                                -> d_nm (ω (ω a b c) y z).\n  \n  Notation 𝔻 := d_nm.\n\n  Set Elimination Schemes.\n\n  Section nm_def.\n\n    Let nm_full : forall e, 𝔻 e -> { n | e ~~> n }.\n    Proof.\n      refine(fix loop e De := match e as e' return 𝔻 e' -> sig (𝔾 e') with\n        | α               => fun _ => \n                         exist _ α _\n\n        | ω α y z         => fun D => \n          let (ny,Dy) := loop y _ in\n          let (nz,Dz) := loop z _ in\n                         exist _ (ω α ny nz) _\n\n        | ω (ω a b c) y z => fun D =>\n          let (nb,Db) := loop (ω b y z)   _ in\n          let (nc,Dc) := loop (ω c y z)   _ in\n          let (na,Da) := loop (ω a nb nc) _ in\n                         exist _ na _\n      end De).\n      2-3,5-7: inversion D; auto.\n      + constructor 1.\n      + constructor 2; auto.\n      + constructor 3 with nb nc; auto.\n    Qed.\n\n    Definition nm e (D : 𝔻 e) := proj1_sig (@nm_full e D).\n    \n    Fact nm_spec e D : 𝔾 e (@nm e D). \n    Proof. apply (proj2_sig _). Qed.\n  \n  End nm_def.\n  \n  Arguments nm e D : clear implicits.\n  \n  Fact d_nm_0 : 𝔻 α.\n  Proof. constructor; auto. Qed.\n\n  Fact d_nm_1 y z : 𝔻 y -> 𝔻 z -> 𝔻 (ω α y z).\n  Proof. constructor; auto. Qed.\n\n  Fact d_nm_2 a b c y z Db Dc : 𝔻 (ω a (nm (ω b y z) Db) (nm (ω c y z) Dc)) \n                             -> 𝔻 (ω (ω a b c) y z).\n  Proof. \n    constructor 3; auto.\n    intros; eq goal with H; do 2 f_equal;\n    apply 𝔾_fun with (1 := nm_spec _); trivial.\n  Qed.\n\n  Hint Resolve nm_spec.\n\n  Section d_nm_rect.\n\n    Variables (P : forall e, 𝔻 e -> Type)\n              (HPi : forall e D1 D2, @P e D1 -> @P e D2)\n              (HP0 : P d_nm_0)\n              (HP1 : forall y z D1 (_ : P D1) D2 (_ : P D2), P (@d_nm_1 y z D1 D2))\n              (HP2 : forall a b c y z D1 (_ : P D1) D2 (_ : P D2) D3 (_ : P D3), P (@d_nm_2 a b c y z D1 D2 D3)).\n  \n    Fixpoint d_nm_rect e (De : 𝔻 e) : @P e De.\n    Proof.\n      destruct e as [ | [ | a b c ] y z ].\n      + apply HPi with (1 := HP0).\n      + refine (HPi _ (HP1 (d_nm_rect y _) \n                           (d_nm_rect z _))); \n          inversion De; trivial.\n      + assert (𝔻 (ω b y z)) as Db by (inversion De; trivial).\n        assert (𝔻 (ω c y z)) as Dc by (inversion De; trivial).\n        refine (HPi _ (HP2 (d_nm_rect (ω b y z) Db)\n                           (d_nm_rect (ω c y z) Dc) \n                           (d_nm_rect (ω a _ _) _))). (** dependancies here *)\n        inversion De; auto.\n    Qed.\n\n  End d_nm_rect.\n\n  Definition d_nm_ind (P : forall e, 𝔻 e -> Prop) := @d_nm_rect P. \n\n  Fact nm_pirr e D1 D2 : nm e D1 = nm e D2.\n  Proof. apply 𝔾_fun with e; auto. Qed.\n\n  Fact nm_fix_0 : nm α d_nm_0 = α.\n  Proof. apply 𝔾_fun with α; [ | constructor ]; auto. Qed.\n\n  Fact nm_fix_1 y z D1 D2 : nm (ω α y z) (d_nm_1 D1 D2) = ω α (nm y D1) (nm z D2).\n  Proof. apply 𝔾_fun with (ω α y z); [ | constructor ]; auto. Qed.\n\n  Fact nm_fix_2 u v w y z D1 D2 D3 : \n            nm (ω (ω u v w) y z) (d_nm_2 D1 D2 D3) \n          = nm (ω u (nm (ω v y z) D1) (nm (ω w y z) D2)) D3.\n  Proof. \n    apply 𝔾_fun with (ω (ω u v w) y z); auto.\n    constructor 3 with (nm _ D1) (nm _ D2); auto.\n  Qed.\n   \nEnd nm_def.\n\nArguments nm e D : clear implicits.\n\nCreate HintDb nm_fix_db.\nHint Rewrite nm_fix_0 nm_fix_1 nm_fix_2 : nm_fix_db.\n\nLtac nm_pirr := \n  match goal with \n    [ |- context f [nm ?e _] ] => \n    match goal with \n      _: context[nm e ?D] |- _ => rewrite (nm_pirr _ D) \n    end \n  end.\n\nLtac nm_rewrite := autorewrite with nm_fix_db.\n\nTactic Notation \"nm\" \"auto\" := try nm_pirr; nm_rewrite; auto.\n\nCheck nm_spec.\nPrint Assumptions nm_spec.\n\nRecursive Extraction nm.\n\n(* Now we show the partial correctness of nm, \n   independently of its termination *)\n\n(** normal forms only have atoms as boolean condition \n    ie. b in if b then _ else _ *)\n\nInductive normal : Ω -> Prop :=\n  | in_normal_0 :             normal α\n  | in_normal_1 : forall y z, normal y \n                           -> normal z \n                           -> normal (ω α y z).\n\nNotation ℕ := normal.\n\n(** nm produces normal forms *)\n\nTheorem nm_normal e D : ℕ (nm e D).\nProof.\n  induction D.\n  all: nm auto; constructor; auto.\nQed.\n\n(** equiv is the congruence generated by \n\n   ω (ω a b c) y z ~e ω a (ω b y z) (ω c y z) \n\n  *)\n\nReserved Notation \"x '~Ω' y\" (at level 70, no associativity).\n\nInductive equiv : Ω -> Ω -> Prop :=\n  | in_eq_0 : forall u v w y z, ω (ω u v w) y z ~Ω ω u (ω v y z) (ω w y z)\n  | in_eq_1 : forall x x' y y' z z', x ~Ω x' -> y ~Ω y' -> z ~Ω z'-> ω x y z ~Ω ω x' y' z'\n  | in_eq_2 : α ~Ω α\n  | in_eq_3 : forall x y z, x ~Ω y -> y ~Ω z -> x ~Ω z\nwhere \"x ~Ω y\" := (equiv x y).\n\nHint Constructors equiv.\n\nFact equiv_refl e : e ~Ω e.   Proof. induction e; auto. Qed.\n\nHint Resolve equiv_refl.\n\nNotation equiv_trans := in_eq_3.\n\n(** nm preserves equivalence *)\n\nFact nm_equiv e D : e ~Ω nm e D.\nProof.\n  induction D as [ e D1 D2 \n                 | \n                 | y z D1 ID1 D2 ID2 \n                 | u v w y z D1 ID1 D2 ID2 D3 ID3 ].\n  all: nm auto.\n  apply equiv_trans with (2 := ID3),\n        equiv_trans with (1 := in_eq_0 _ _ _ _ _); auto.\nQed.\n\n(** Using the simulated IR definition of \n\n            𝔻 : Ω -> Prop and nm : forall e, 𝔻 e -> Ω\n\n    we show totality of 𝔻: \n \n      a) we define a measure [.] : Ω -> nat by structural induction\n\n      b) we show that nm preserves the measure, ie\n\n           forall e (De : 𝔻 e), [nm e De] <= [e]\n\n         by dependent induction on De : 𝔻 e\n\n      c) we show that 𝔻 is total\n      \n           forall e, 𝔻 e \n           \n         by induction on [e] : nat\n*)\n\nSection ce_size.\n\n  Let c x y z := x * (1+y+z).\n\n  (* The next properties are sufficient for the measure *)\n\n  Let c_mono x x' y y' z z' : x <= x' -> y <= y' -> z <= z' -> c x y z <= c x' y' z'.\n  Proof. intros; simpl; apply mult_le_compat; lia. Qed.\n\n  Let c_smono_1 x x' y z : x < x' -> c x y z < c x' y z.\n  Proof. intro; simpl; apply mult_lt_compat_r; lia. Qed.\n\n  Let c_inc_1 x y z : x <= c x y z.\n  Proof. unfold c; rewrite <- Nat.mul_1_r at 1; apply mult_le_compat; lia. Qed.\n\n  Let c_sinc_1 x y z : 0 < x -> 0 < y + z -> x < c x y z.\n  Proof. intros ? ?; unfold c; rewrite <- Nat.mul_1_r at 1; apply mult_lt_compat_l; lia. Qed.\n\n  Let c_sinc_2 x y z : 0 < x -> y < c x y z.\n  Proof. intros ?; unfold c, lt; rewrite <- Nat.mul_1_l at 1; apply mult_le_compat; lia. Qed.\n\n  Let c_sinc_3 x y z : 0 < x -> z < c x y z.\n  Proof. intros ?; unfold c, lt; rewrite <- Nat.mul_1_l at 1; apply mult_le_compat; lia. Qed.\n\n  Let c_special a u v y z : 0 < a -> 0 < y + z -> c a (c u y z) (c v y z) < c (c a u v) y z.\n  Proof.\n    unfold c; intros ? ?.\n    rewrite <- mult_assoc.\n    apply mult_lt_compat_l; auto.\n    simpl.\n    generalize (S (y + z)); intros n.\n    rewrite mult_plus_distr_r; lia.\n  Qed.\n\n  Reserved Notation \"'[' e ']'\" (at level 0).\n\n  (** This is the decreasing measure *)\n\n  Fixpoint ce_size e :=\n    match e with\n      | α => 1\n      | ω x y z => c [x] [y] [z]\n    end\n  where \"[ e ]\" := (ce_size e).\n\n  (* Some elementary properties of the measure *)\n\n  Local Fact ce_size_mono x x' y y' z z' : \n     [x] <= [x'] -> [y] <= [y'] -> [z] <= [z'] -> [ω x y z] <= [ω x' y' z'].\n  Proof. apply c_mono. Qed.\n\n  Local Fact ce_size_smono_1 x x' y z : [x] < [x'] -> [ω x y z] < [ω x' y z].\n  Proof. apply c_smono_1. Qed.\n\n  Local Fact ce_size_ge_1 e : 1 <= [e].\n  Proof.\n    induction e as [ | x Hx y _  z _ ]; auto.\n    apply le_trans with (1 := Hx), c_inc_1.\n  Qed.\n\n  Hint Resolve ce_size_ge_1.\n\n  Local Fact ce_size_sub_1 x y z : [x] < [ω x y z].\n  Proof. simpl; apply c_sinc_1; auto; generalize (ce_size_ge_1 y); lia. Qed.\n\n  Local Fact ce_size_sub_2 x y z : [y] < [ω x y z].\n  Proof. simpl; apply c_sinc_2; auto. Qed.\n\n  Local Fact ce_size_sub_3 x y z : [z] < [ω x y z].\n  Proof. simpl; apply c_sinc_3; auto. Qed.\n\n  (* The special properties that makes it a suitable measure for induction *)\n\n  Local Fact ce_size_special a u v y z : [ω a (ω u y z) (ω v y z)] < [ω (ω a u v) y z].\n  Proof. simpl; apply c_special; auto; generalize (ce_size_ge_1 y); lia. Qed.\n\nEnd ce_size.\n\n(* No we finish with the termination/totality of nm *)\n\nSection d_nm_total.\n\n  Notation 𝔻 := d_nm.\n  Notation \"'[' e ']'\" := (ce_size e) (at level 0).\n\n  Hint Resolve ce_size_sub_2 ce_size_sub_3 ce_size_mono ce_size_smono_1.\n  \n  (** nm preserves the measure *)\n\n  Local Fact nm_dec e D : [nm e D] <= [e].\n  Proof.\n    induction D as [ e D1 D2 | | y z D1 ID1 D2 ID2 | u v w y z D1 ID1 D2 ID2 D3 ID3 ]; nm auto.\n    apply le_trans with (1 := ID3),\n          le_trans with (2 := ce_size_special _ _ _ _ _); auto.\n  Qed.\n\n  Hint Resolve nm_dec.\n\n  (** Termination/totality by induction on [e] *)\n\n  Theorem d_nm_total e : 𝔻 e.\n  Proof.\n    induction on e as IHe with measure [e].\n    destruct e as [ | [ | u v w ] y z ].\n    + apply d_nm_0.\n    + apply d_nm_1; apply IHe; simpl; lia.\n    + assert (D1 : 𝔻 (ω v y z)) by auto.\n      assert (D2 : 𝔻 (ω w y z)) by auto.\n      apply d_nm_2 with D1 D2.\n      apply IHe, le_lt_trans with (2 := ce_size_special _ _ _ _ _); auto.\n  Qed.\n  \nEnd d_nm_total.\n\n(** We can finish with a fully specified term defining a total function \n    which computes a normal form *)\n\nHint Resolve nm_equiv nm_normal.\n\nDefinition nm_total e : { ne | e ~Ω ne /\\ ℕ ne }.\nProof.\n  exists (nm _ (d_nm_total e)); auto.\nDefined.\n\nExtraction Inline nm.\n\nRecursive Extraction nm_total.\n\nPrint inhabited.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "PC19", "sha": "0481befc4f7b57679000a0d6ae29940532f55026", "save_path": "github-repos/coq/DmxLarchey-PC19", "path": "github-repos/coq/DmxLarchey-PC19/PC19-0481befc4f7b57679000a0d6ae29940532f55026/nm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7183353115188154}}
{"text": "Inductive pos : Set :=\n| S1 : pos\n| S : pos -> pos.\n\nFixpoint plus(n m:pos) : pos :=\n  match n with\n    | S1 => S m\n    | S l => S (plus l  m)\n  end.\n\nInfix \"+\" := plus.\n\nLemma succ_equal : forall n m : pos, (n = m) -> (S n = S m).\nProof.\n  intros.\n  induction n.\n  rewrite <- H.\n  auto.\n  rewrite H.\n  auto.\nQed.\n\nTheorem plus_assoc : forall n m p, n + (m + p) = (n + m) + p.\nProof.\n  intros.\n  induction n.\n  simpl.\n  auto.\n  simpl.\n  apply succ_equal.\n  auto.\nQed.", "meta": {"author": "KeenS", "repo": "coqex", "sha": "325a48569d54a8925e41f757cbb4c3c74443c5a3", "save_path": "github-repos/coq/KeenS-coqex", "path": "github-repos/coq/KeenS-coqex/coqex-325a48569d54a8925e41f757cbb4c3c74443c5a3/3/13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7183353101035415}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult (Succ y) (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj201_coqofml_cwYuLe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.718335308270862}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  mult (Succ x) (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj182_coqofml_yaZVEv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7183353052316123}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := mult (Succ y) x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj245_coqofml_ahf1G8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7183201904018034}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Lists.List.\nRequire Import Crypto.Util.ZUtil.Land.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nLocal Open Scope bool_scope. Local Open Scope Z_scope.\n\nModule Z.\n  Lemma fold_right_land_m1_cps v ls\n    : fold_right Z.land v ls\n      = Z.land (fold_right Z.land (-1) ls) v.\n  Proof.\n    induction ls as [|?? IH]; cbn [fold_right].\n    { now rewrite Z.land_m1'_l. }\n    { rewrite <- !Z.land_assoc, IH; reflexivity. }\n  Qed.\n\n  Lemma fold_right_land_ones_id sz ls\n    : Z.land (fold_right Z.land (Z.ones sz) ls) (Z.ones sz)\n      = Z.land (fold_right Z.land (-1) ls) (Z.ones sz).\n  Proof.\n    rewrite fold_right_land_m1_cps, <- Z.land_assoc, Z.land_diag.\n    reflexivity.\n  Qed.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/Land/Fold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7182899995236589}}
{"text": "Require Export P06.\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. induction H.\n  - split.\n    + apply le_n_S. induction n1.\n      * simpl. apply le_0_n.\n      * simpl. apply le_n_S. assumption.\n    + apply le_n_S. induction n1.\n      * simpl. apply le_n.\n      * simpl. apply le_S. assumption.\n  - destruct IHle. split.\n    + apply le_S. assumption.\n    + apply le_S. assumption.\nQed.      ", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/06/P07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7182899833024609}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Category.\n\n(**\nA sub category of C is a category whose objects are a subset (here we ues\nsubset types, i.e., sig) of objects of C and whose arrows are a subset of\narrows of C.\n\nHere, we define a subcategory using two functions Obj_Cri : Obj C -> Prop\nwhich defines the objects of subcategory and\nHom_Cri : ∀ (a b : Obj) -> Hom a b -> Prop\nwhich defines the arrows of subcategory.\nIn other words, Obj_Cri and Hom_Cri are respectively cirteria for objects and\narrows being in the sub category. We furthermore, require that the Hom_Cri\nprovides that identity arrows of all objects in the subcategory are part of\nthe arrows of the subcategory. Additionally, For ant two composable arrow that\nare in the subcategory, their composition must also be in the subcategory.\n*)\nSection SubCategory.\n  Context (C : Category)\n          (Obj_Cri : Obj → Type)\n          (Hom_Cri : ∀ a b, (a --> b)%morphism → Prop).\n\n  Arguments Hom_Cri {_ _} _.\n\n  Context (Hom_Cri_id : ∀ a, Obj_Cri a → Hom_Cri (id a))\n          (Hom_Cri_compose :\n             ∀ a b c (f : (a --> b)%morphism)\n               (g : (b --> c)%morphism),\n               Hom_Cri f → Hom_Cri g → Hom_Cri (g ∘ f)).\n\n  Arguments Hom_Cri_id {_} _.\n  Arguments Hom_Cri_compose {_ _ _ _ _} _ _.\n\n  Local Obligation Tactic := idtac.\n\n  Program Definition SubCategory : Category :=\n  {|\n    Obj := sigT Obj_Cri;\n\n    Hom :=\n      fun a b =>\n        sig (@Hom_Cri (projT1 a) (projT1 b));\n\n    compose :=\n      fun _ _ _ f g =>\n        exist _ _\n              (Hom_Cri_compose (proj2_sig f) (proj2_sig g));\n\n    id :=\n      fun a =>\n        exist _ _ (Hom_Cri_id (projT2 a))\n  |}.\n\n  Next Obligation.\n    intros.\n    apply sig_proof_irrelevance; simpl; abstract auto.\n  Qed.\n\n  Next Obligation.\n    symmetry.\n    apply SubCategory_obligation_1.\n  Qed.\n\n  Local Hint Extern 3 => simpl : core.\n\n  Local Obligation Tactic := basic_simpl; auto.\n\n  Solve Obligations.\n\nEnd SubCategory.\n\n\n(**\nA wide subcategory of C is a subcategory of C that has all the objects of C but\nnot necessarily all its arrows.\n*)\nNotation Wide_SubCategory C Hom_Cri := (SubCategory C (fun _ => True) Hom_Cri).\n\n(**\nA Full subcategory of C is a subcategory of C that for any pair of objects of\nthe category that it has, it has all the arrows between them. In practice, we\nconstruct a full subcategory by only expecting an object criterion and setting\nthe arrow criterrion to accept all arrows.\n*)\nNotation Full_SubCategory C Obj_Cri :=\n  (SubCategory C Obj_Cri (fun _ _ _ => True) (fun _ _ => I) (fun _ _ _ _ _ _ _ => I)).\n", "meta": {"author": "amintimany", "repo": "Categories", "sha": "1839108875df0107fa4f6061c654003decda2d49", "save_path": "github-repos/coq/amintimany-Categories", "path": "github-repos/coq/amintimany-Categories/Categories-1839108875df0107fa4f6061c654003decda2d49/Category/SubCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7182693476348042}}
{"text": "Require Export Logic.\n\nDefinition relation (X: Type) := X->X->Prop.\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\nTheorem next_nat_partial_function :\n   partial_function next_nat.\nProof.\n  unfold partial_function.\n  intros.\n  inversion H. inversion H0.\n  reflexivity.\nQed.\n\nTheorem total_relation_not_partial :\n  ~ partial_function total_relation.\nProof.\n  unfold not.\n  unfold partial_function.\n  intros.\n  assert (0 = 1) as Nonsense.\n  apply H with 0.\n  apply tl.\n  apply tl.\n  inversion Nonsense.\nQed.\n\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive :\n  reflexive le.\nProof.\n  unfold reflexive. intros n. apply le_n.  Qed.\n\n\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  Case \"le_n\". apply Hnm.\n  Case \"le_S\". apply le_S. apply IHHmo.  Qed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  apply le_S in Hnm.\n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. Qed.\n\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof.\n  intros n m H. apply le_trans with (S n).\n    apply le_S. apply le_n.\n    apply H.  Qed.\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\n\nInductive clos_refl_trans {A: Type} (R: relation A) : relation A :=\n    | rt_step : forall x y, R x y -> clos_refl_trans R x y\n    | rt_refl : forall x, clos_refl_trans R x x\n    | rt_trans : forall x y z,\n          clos_refl_trans R x y ->\n          clos_refl_trans R y z ->\n          clos_refl_trans R x z.\n\nTheorem next_nat_closure_is_le : forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m.\n  split.\n  (* -> *)\n  intros.\n  induction H.\n  apply rt_refl.\n  apply rt_trans with m.\n  apply IHle.\n  apply rt_step.\n  apply nn.\n\n  (* <- *)\n  intros.\n  induction H.\n  inversion H.\n  apply le_S. apply le_n.\n  apply le_n.\n  apply le_trans with y.\n  tauto. tauto.\nQed.\n\nInductive refl_step_closure {X:Type} (R: relation X) : relation X :=\n  | rsc_refl  : forall (x : X), refl_step_closure R x x\n  | rsc_step : forall (x y z : X),\n                    R x y ->\n                    refl_step_closure R y z ->\n                    refl_step_closure R x z.\n\nTactic Notation \"rt_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"rt_step\" | Case_aux c \"rt_refl\"\n  | Case_aux c \"rt_trans\" ].\n\nTactic Notation \"rsc_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"rsc_refl\" | Case_aux c \"rsc_step\" ].\n\nTheorem rsc_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> refl_step_closure R x y.\nProof.\n  intros.\n  apply rsc_step with y.\n  apply H.\n  apply rsc_refl.\nQed.\n\nTheorem rsc_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      refl_step_closure R x y  ->\n      refl_step_closure R y z ->\n      refl_step_closure R x z.\nProof.\n  intros.\n  induction H.\n  apply H0.\n  apply rsc_step with y.\n  apply H.\n  apply IHrefl_step_closure.\n  apply H0.\nQed.\n\nTheorem rtc_rsc_coincide :\n         forall (X:Type) (R: relation X) (x y : X),\n  clos_refl_trans R x y <-> refl_step_closure R x y.\nProof.\n  intros.\n  split.\n  (* -> *)\n  intros.\n  induction H.\n  apply rsc_step with y.\n  apply H.\n\n  apply rsc_refl.\n  apply rsc_refl.\n\n  apply rsc_trans with y.\n  auto. auto.\n\n  (* <- *)\n  intros.\n  induction H.\n  apply rt_refl.\n  apply rt_trans with y.\n  apply rt_step. apply H.\n  apply IHrefl_step_closure.\nQed.\n", "meta": {"author": "egejjespersen", "repo": "software_foundation_exercise", "sha": "e2f788ff88b4b6a6cefc3f413e646c8a733232b2", "save_path": "github-repos/coq/egejjespersen-software_foundation_exercise", "path": "github-repos/coq/egejjespersen-software_foundation_exercise/software_foundation_exercise-e2f788ff88b4b6a6cefc3f413e646c8a733232b2/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8267117983401364, "lm_q1q2_score": 0.7182693466299327}}
{"text": "\n(****************** One-step Reduction **************)\n\nInductive s1: Spec -> Tape -> State -> Tape -> State -> Prop :=\n\n(* RIGHT move *)\n\n | s1R: forall T:Spec, forall p q:State,\n        forall l r:HTape,\n        (tr T p (read (pair l r))) = (Some (q, R)) ->\n        (s1 T (pair l r) p\n              (pair (Cons (hd r) l) (tl r)) q)\n\n(* LEFT move *)\n\n | s1L: forall T:Spec, forall p q:State,\n        forall l r:HTape,\n        (tr T p (read (pair l r))) = (Some (q, L)) ->\n        (s1 T (pair l r) p\n              (pair (tl l) (Cons (hd l) r)) q)\n\n(* WRITE move *)\n\n | s1W: forall T:Spec, forall p q:State,\n        forall l r:HTape, forall a:Sym,\n        (tr T p (read (pair l r))) = (Some (q, (W a))) ->\n        (s1 T (pair l r) p\n              (pair l (Cons a (tl r))) q).\n\n(****************** Finite Reduction *********************)\n\nInductive sf: Spec -> Tape -> State -> Tape -> State -> Prop :=\n\n(* HALT move *)\n\n   sf0: forall T:Spec, forall q:State, forall t:Tape,\n        (sf T t q t q)\n\n(* inductive moves *)\n\n | sfI: forall T:Spec, forall p q i:State, forall s t u:Tape,\n        (s1 T s p u i) -> (sf T u i t q) ->\n        (sf T s p t q).\n\n(****************** Infinite Reduction *********************)\n\nCoInductive si: Spec -> Tape -> State -> Prop :=\n\n(* coinductive moves *)\n\n | siC: forall T:Spec, forall p q:State, forall s t:Tape,\n        (s1 T s p t q) -> (si T t q) ->\n        (si T s p).\n", "meta": {"author": "asr", "repo": "tm-coinduction", "sha": "599083b74ffdf0c1032c5c2495fef9bf23a4058c", "save_path": "github-repos/coq/asr-tm-coinduction", "path": "github-repos/coq/asr-tm-coinduction/tm-coinduction-599083b74ffdf0c1032c5c2495fef9bf23a4058c/metatheory/adequacy/smallstep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7182094101994677}}
{"text": "Require Import Arith.\n\nFixpoint sum_odd(n:nat) : nat :=\n  match n with\n    | 0 => 0\n    | S m => 1 + m + m + sum_odd m\n  end.\n\nGoal forall n, sum_odd n = n * n.\nProof.\n  intros.\n  induction n.\n  simpl.\n  ring.\n  simpl.\n  rewrite <- (eq_S (n + n + sum_odd n) (n + n * S n)).\n  ring.\n  rewrite IHn.\n  ring.\nQed.\n             ", "meta": {"author": "KeenS", "repo": "coqex", "sha": "325a48569d54a8925e41f757cbb4c3c74443c5a3", "save_path": "github-repos/coq/KeenS-coqex", "path": "github-repos/coq/KeenS-coqex/coqex-325a48569d54a8925e41f757cbb4c3c74443c5a3/3/11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107896491796, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7181786703397389}}
{"text": "(* assumption *)\nTheorem p_implies_p : forall P : Prop,\n  P -> P.\nProof.\n  intros P P_holds.\n  assumption.\nQed.\n\n(* apply *)\nTheorem modus_ponens : forall (P Q : Prop),\n  (P -> Q) -> P -> Q.\nProof.\n  intros P Q P_implies_Q P_holds.\n  apply P_implies_Q in P_holds.\n  assumption.\nQed.\n\n\n  ", "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/functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7181768489207645}}
{"text": "Require Import XR_Rmax.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rle_antisym.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rmax_right : forall x y, x <= y -> Rmax x y = y.\nProof.\n  intros x y h.\n  unfold Rmax.\n  destruct (Rle_dec x y) as [ hl | hr ].\n  { reflexivity. }\n  {\n    apply Rle_antisym.\n    { exact h. }\n    {\n      left.\n      apply Rnot_le_lt.\n      exact hr.\n    }\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rmax_right.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7181768376699631}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(*                 The Calculus of Inductive Constructions                  *)\n(*                                                                          *)\n(*                                Projet Coq                                *)\n(*                                                                          *)\n(*                     INRIA                        ENS-CNRS                *)\n(*              Rocquencourt                        Lyon                    *)\n(*                                                                          *)\n(*                                Coq V5.10                                 *)\n(*                              Nov 25th 1994                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                                 Zmult.v                                  *)\n(****************************************************************************)\nRequire Export Lci.\nRequire Export misc.\nRequire Export Arith.\nRequire Export Nat_complements.\nRequire Export groups.\nRequire Export rings.\nRequire Export Zbase.\nRequire Export Z_succ_pred.\nRequire Export Zadd.\n\n(* Multiplication on Z, (Z, +, *, 0, 1) is a unitary commutative ring *)\n\n(*Recursive Definition multZ : Z -> Z -> Z := \n        OZ      y  => OZ\n | (pos O)      y  => y\n | (pos (S n1)) y  => (addZ (multZ (pos n1) y) y)\n | (neg O)      y  => (oppZ y)\n | (neg (S n1)) y  => (addZ (multZ (neg n1) y) (oppZ y)).\n*)\n\n\nFixpoint multpos (x2 : Z) (n : nat) {struct n} : Z :=\n  match n with\n  | O => x2\n  | S n0 => addZ (multpos x2 n0) x2\n  end.\n\nFixpoint multneg (x2 : Z) (n : nat) {struct n} : Z :=\n  match n with\n  | O => oppZ x2\n  | S n0 => addZ (multneg x2 n0) (oppZ x2)\n  end. \n\nDefinition multZ (x1 x2 : Z) :=\n  match x1 with\n  | OZ => OZ\n  | pos n => multpos x2 n\n  | neg n => multneg x2 n\n  end.\n\n\nLemma multZ_eq1 : forall n : Z, multZ OZ n = OZ.\nProof.\n auto.\nQed.\n\nLemma multZ_eq2 : forall n : Z, multZ (pos 0) n = n.\nProof.\n auto.\nQed.\n\nLemma multZ_eq3 :\n forall (n1 : nat) (n : Z), multZ (pos (S n1)) n = addZ (multZ (pos n1) n) n.\nProof.\n auto.\nQed.\n\nLemma multZ_eq4 : forall n : Z, multZ (neg 0) n = oppZ n.\nProof.\n auto.\nQed.\n\nLemma multZ_eq5 :\n forall (n1 : nat) (n : Z),\n multZ (neg (S n1)) n = addZ (multZ (neg n1) n) (oppZ n).\nProof.\n auto.\nQed.\n\n(*******************)\nLemma tech_mult_posZ :\n forall (x : nat) (y : Z), multZ (pos (S x)) y = addZ (multZ (pos x) y) y.\n\nProof multZ_eq3.\n\n(*******************)\nLemma tech_mult_negZ :\n forall (x : nat) (y : Z),\n multZ (neg (S x)) y = addZ (multZ (neg x) y) (oppZ y).\n\nProof multZ_eq5.\n\n(*****************)\nLemma mult_succZ_l : forall x y : Z, multZ (succZ x) y = addZ (multZ x y) y.\n\nintros; elim x.\n(* OZ *)\nsimpl in |- *; reflexivity.\n(* pos n *)\nintros; simpl in |- *; reflexivity.\n(* neg n *)\nintros; elim n.\n(* neg O *)\nsimpl in |- *; symmetry  in |- *. \nelim (addZ_opposite y I); intros. elim H0; intros; elim H2; intros; exact H4.\n(* neg (S n0) *)\nintros; unfold succZ in |- *; rewrite (tech_mult_negZ n0 y).\nelim (addZ_associativity (multZ (neg n0) y) (oppZ y) y).\nelim (addZ_opposite y I); intros. elim H1; intros; elim H3; intros. rewrite H5.\nsymmetry  in |- *; exact (add_OZ (multZ (neg n0) y)).\nQed.\n\n(*****************)\nLemma mult_predZ_l :\n forall x y : Z, multZ (predZ x) y = addZ (multZ x y) (oppZ y).\n\nProof.\nintros; elim x.\n(* OZ *)\nsimpl in |- *; reflexivity.\n(* pos n *)\nintros; elim n.\n(* pos O *)\nsimpl in |- *; symmetry  in |- *.\nelim (addZ_opposite y I); intros. elim H0; intros; elim H2; intros; exact H3.\n(* pos (S n0) *)\nintros; unfold predZ in |- *; rewrite (tech_mult_posZ n0 y).\nelim (addZ_associativity (multZ (pos n0) y) y (oppZ y)).\nelim (addZ_opposite y I); intros. elim H1; intros; elim H3; intros; rewrite H4.\nrewrite (add_OZ (multZ (pos n0) y)); reflexivity.\n(* neg n *)\nintros; reflexivity.\nQed.\n\n(*****************)\nLemma mult_succZ_r : forall x y : Z, multZ x (succZ y) = addZ (multZ x y) x.\n\nintros; elim x.\n(* OZ *)\nreflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nsymmetry  in |- *; exact (add_IZ_succZ y).\n(* pos (S y0) *)\nintros y0 H; do 2 rewrite (tech_mult_posZ y0).\nrewrite H; elim (addZ_commutativity (pos y0) (multZ (pos y0) y)).\nelim (addZ_associativity (pos y0) (multZ (pos y0) y) (succZ y)).\nelim (addZ_commutativity (addZ (multZ (pos y0) y) (succZ y)) (pos y0)).\nrewrite (succ_addZ_r (multZ (pos y0) y) y).\nrewrite (succ_addZ_l (addZ (multZ (pos y0) y) y) (pos y0)).\nelim (succ_addZ_r (addZ (multZ (pos y0) y) y) (pos y0)).\nreflexivity.\n(* neg n *)\nsimple induction n.\n(* neg O *)\nsimpl in |- *; rewrite (add_mIZ_predZ (oppZ y)); exact (opp_succZ y).\n(* neg (S y0) *)\nintros y0 H; do 2 rewrite (tech_mult_negZ y0).\nelim H; elim (addZ_commutativity (oppZ y) (multZ (neg y0) y)).\nelim (addZ_associativity (oppZ y) (multZ (neg y0) y) (neg (S y0))).\nelim (addZ_commutativity (addZ (multZ (neg y0) y) (neg (S y0))) (oppZ y)).\nrewrite (opp_succZ y). \nrewrite (pred_addZ_r (multZ (neg y0) (succZ y)) (oppZ y)).\nrewrite H; elim (pred_addZ_l (addZ (multZ (neg y0) y) (neg y0)) (oppZ y)).\nelim (pred_addZ_r (multZ (neg y0) y) (neg y0)); unfold predZ in |- *;\n reflexivity.\nQed.\n\n(*****************)\nLemma mult_predZ_r :\n forall x y : Z, multZ x (predZ y) = addZ (multZ x y) (oppZ x).\n\nintros; elim x.\n(* OZ *)\nreflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nsimpl in |- *; symmetry  in |- *; exact (add_mIZ_predZ y).\n(* pos (S n0) *)\nintros n0 H; unfold oppZ in |- *; do 2 rewrite (tech_mult_posZ n0).\nrewrite (pred_addZ_r (multZ (pos n0) (predZ y)) y).\nelim (pred_addZ_l (multZ (pos n0) (predZ y)) y).\nelim (addZ_commutativity y (multZ (pos n0) y)).\nelim (addZ_associativity y (multZ (pos n0) y) (neg (S n0))).\nelim (addZ_commutativity (addZ (multZ (pos n0) y) (neg (S n0))) y).\nrewrite H; elim (pred_addZ_r (multZ (pos n0) y) (oppZ (pos n0))).\nreflexivity.\n(* neg n *)\nsimple induction n.\n(* neg O *)\nsimpl in |- *.\nreplace (pos 0) with IZ; auto.\nrewrite (add_IZ_succZ (oppZ y)).\nexact (opp_predZ y).\n(* neg (S n0) *)\nintros n0 H; do 2 rewrite (tech_mult_negZ n0).\nrewrite H; rewrite (opp_predZ y).\nelim (addZ_commutativity (oppZ (neg n0)) (multZ (neg n0) y)).\nelim (addZ_associativity (oppZ (neg n0)) (multZ (neg n0) y) (succZ (oppZ y))).\nelim\n (addZ_commutativity (addZ (multZ (neg n0) y) (succZ (oppZ y)))\n    (oppZ (neg n0))).\nrewrite (succ_addZ_r (multZ (neg n0) y) (oppZ y)).\nrewrite (succ_addZ_l (addZ (multZ (neg n0) y) (oppZ y)) (oppZ (neg n0))).\nelim (succ_addZ_r (addZ (multZ (neg n0) y) (oppZ y)) (oppZ (neg n0))).\nreflexivity.\nQed.\n\n(************)\nLemma mult_OZ : forall x : Z, multZ x OZ = OZ.\n\nsimple destruct x.\n(* OZ *)\nreflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nreflexivity.\n(* pos (S y) *)\nintros y H; rewrite (tech_mult_posZ y OZ); rewrite H; reflexivity.\n(* neg n *)\nsimple induction n.\n(* neg O *)\nreflexivity.\n(* neg (S y) *)\nintros y H; rewrite (tech_mult_negZ y OZ); rewrite H; reflexivity.\nQed.\n\n(************)\nLemma mult_IZ : forall x : Z, multZ x IZ = x.\n\nsimple destruct x.\n(* OZ *)\nreflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nreflexivity.\n(* pos (S y) *)\nintros y H; rewrite (tech_mult_posZ y IZ); rewrite H. \nrewrite (add_IZ_succZ (pos y)); reflexivity.\n(* neg n *)\nsimple induction n.\n(* neg O *)\nreflexivity.\n(* neg (S y) *)\nintros y H; rewrite (tech_mult_negZ y IZ); rewrite H; unfold IZ in |- *;\n unfold oppZ in |- *. \nrewrite (add_mIZ_predZ (neg y)); reflexivity.\nQed.\n\n(*************)\nLemma mult_mIZ : forall x : Z, multZ x (neg 0) = oppZ x.\n\nsimple destruct x.\n(* OZ *)\nreflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nreflexivity.\n(* pos (S y) *)\nintros y H; rewrite (tech_mult_posZ y (neg 0)); rewrite H. \nrewrite (add_mIZ_predZ (oppZ (pos y))); reflexivity.\n(* neg n *)\nsimple induction n.\n(* neg O *)\nreflexivity.\n(* neg (S y) *)\nintros y H; rewrite (tech_mult_negZ y (neg 0)); rewrite H.\nelim\n (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity (neg y) (neg 0) I I).\nrewrite (add_mIZ_predZ (neg y)); reflexivity.\nQed.\n\n(**************************)\nTheorem multZ_commutativity : commutativity Z multZ.\n\nunfold commutativity in |- *; intros; elim x.\n(* OZ *)\nrewrite (mult_OZ y); unfold multZ in |- *; reflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nsimpl in |- *; symmetry  in |- *; exact (mult_IZ y).\n(* pos (S y0) *)\nintros y0 H; rewrite (tech_mult_posZ y0 y); rewrite H. \nelim (mult_succZ_r y (pos y0)); unfold succZ in |- *; reflexivity.\n(* neg n *)\nintros; elim n.\n(* neg O *)\nsimpl in |- *; symmetry  in |- *; exact (mult_mIZ y).\n(* neg (S y0) *)\nintros y0 H; rewrite (tech_mult_negZ y0 y); rewrite H. \nelim (mult_predZ_r y (neg y0)); unfold predZ in |- *; reflexivity.\nQed.\n\n(********************)\nTheorem multZ_neutral : neutral Z IdZ multZ IZ.\n\nunfold neutral in |- *.\nsplit. exact I.\nintros. \nsplit.\n(* -> *)\nelim (multZ_commutativity IZ x); reflexivity.\n(* <- *)\nreflexivity.\nQed.\n\n(******************************)\nTheorem mult_add_distributivity : distributivity Z addZ multZ.\n\nunfold distributivity in |- *; intros; case x.\n(* OZ *)\nsplit; reflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nsplit.\nrewrite addZ_eq2; rewrite multZ_eq2.\nrewrite (mult_succZ_l y z); exact (addZ_commutativity (multZ y z) z). \nreflexivity.\n(* pos (S y0) *)\nintros y0 H.\nelim H; intros; split.\nrewrite addZ_eq3; rewrite multZ_eq3.\nrewrite mult_succZ_l; rewrite H0.\nelim (addZ_associativity (multZ (pos y0) z) (multZ y z) z).\nelim (addZ_commutativity z (multZ y z)).\napply addZ_associativity.\ndo 3 rewrite multZ_eq3.\nrewrite H1.\napply (add_add Z addZ addZ_commutativity addZ_associativity).\n(* neg n *)\nsimple induction n.\n(* neg O *)\nsplit.\nrewrite addZ_eq4; rewrite multZ_eq4; rewrite (mult_predZ_l y z). \nexact (addZ_commutativity (multZ y z) (oppZ z)).\nrewrite multZ_eq4.\napply (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity y z I I).\n(* neg (S y0) *)\nintros y0 H.\nsplit.\n(* -> *)\nrewrite (tech_add_neg_predZ y0 y); rewrite (mult_predZ_l (addZ (neg y0) y) z).\nelim H; intros. rewrite H0.\nelim (addZ_associativity (multZ (neg y0) z) (multZ y z) (oppZ z)).\nelim (addZ_commutativity (oppZ z) (multZ y z)).\nrewrite (addZ_associativity (multZ (neg y0) z) (oppZ z) (multZ y z)).\nelim (tech_mult_negZ y0 z); reflexivity.\n(* <- *)\nrewrite (tech_mult_negZ y0 (addZ y z)); rewrite (tech_mult_negZ y0 y).\nrewrite (tech_mult_negZ y0 z); elim H; intros; rewrite H1.\nelim\n (add_add Z addZ addZ_commutativity addZ_associativity \n    (multZ (neg y0) y) (multZ (neg y0) z) (oppZ y) \n    (oppZ z)).\nelim (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity y z I I).\nreflexivity.\nQed.\n\n(****************)\nLemma mult_oppZ_r : forall x y : Z, multZ x (oppZ y) = oppZ (multZ x y).\n\nintros; case x.\n(* OZ *)\nreflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nreflexivity.\n(* pos (S y0) *)\nintros y0 H; do 2 rewrite (tech_mult_posZ y0).\nrewrite\n (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity \n    (multZ (pos y0) y) y I I).\nelim H; reflexivity.\n(* neg n *)\nintros; elim n.\n(* neg O *)\nreflexivity.\n(* neg (S y0) *)\nintros y0 H; do 2 rewrite (tech_mult_negZ y0).\nrewrite\n (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity \n    (multZ (neg y0) y) (oppZ y) I I).\nelim H; reflexivity.\nQed.\n\n(****************)\nLemma mult_oppZ_l : forall x y : Z, multZ (oppZ x) y = oppZ (multZ x y).\n\nsimple destruct y.\n(* OZ *)\nrewrite (mult_OZ (oppZ x)); rewrite (mult_OZ x); reflexivity.\n(* pos n *)\nintros; elim (multZ_commutativity (pos n) (oppZ x)). \nelim (multZ_commutativity (pos n) x); elim n.\n(* pos O *)\nreflexivity.\n(* pos (S y0) *)\nintros y0 H; do 2 rewrite (tech_mult_posZ y0).\nrewrite H; symmetry  in |- *. \nexact\n (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity \n    (multZ (pos y0) x) x I I).\n(* neg n *)\nintros; elim (multZ_commutativity (neg n) (oppZ x)). \nelim (multZ_commutativity (neg n) x); elim n.\n(* neg O *)\nreflexivity.\n(* neg (S y0) *)\nintros y0 H; do 2 rewrite (tech_mult_negZ y0).\nrewrite H; symmetry  in |- *.\nexact\n (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity \n    (multZ (neg y0) x) (oppZ x) I I).\nQed.\n\n(********************)\nLemma tech_multZ_negO : forall x : Z, multZ (neg 0) x = oppZ x.\n\nProof multZ_eq4.\n\n(***********************)\nLemma tech_mult_pos_posZ :\n forall n m : nat, multZ (pos n) (pos m) = pos (n * m + (n + m)).\n\nintros; elim n.\n(* O *)\nreflexivity.\n(* S y *)\nintros y H; rewrite (tech_mult_posZ y (pos m)); rewrite H.\nrewrite (tech_add_pos_posZ (y * m + (y + m)) m).\nelim (technical_lemma y m); reflexivity.\nQed.\n\n(***********************)\nLemma tech_mult_neg_negZ :\n forall n m : nat, multZ (neg n) (neg m) = pos (n * m + (n + m)).\n\nintros; elim n.\n(* O *)\nreflexivity.\n(* S y *)\nintros y H; rewrite (tech_mult_negZ y (neg m)); rewrite H;\n unfold oppZ in |- *.\nrewrite (tech_add_pos_posZ (y * m + (y + m)) m).\nelim (technical_lemma y m); reflexivity.\nQed.\n\n(***********************)\nLemma tech_mult_pos_negZ :\n forall n m : nat, multZ (pos n) (neg m) = neg (n * m + (n + m)).\n\nintros; elim n.\n(* O *)\nsimpl in |- *; reflexivity.\n(* S y *)\nintros y H; rewrite (tech_mult_posZ y (neg m)); rewrite H.\nrewrite (tech_add_neg_negZ (y * m + (y + m)) m).\nelim (technical_lemma y m); reflexivity.\nQed.\n\n(***********************)\nLemma tech_mult_neg_posZ :\n forall n m : nat, multZ (neg n) (pos m) = neg (n * m + (n + m)).\n\nintros; elim n.\n(* O *)\nsimpl in |- *; reflexivity.\n(* S y *)\nintros y H; rewrite (tech_mult_negZ y (pos m)); unfold oppZ in |- *;\n rewrite H.\nrewrite (tech_add_neg_negZ (y * m + (y + m)) m).\nelim (technical_lemma y m); reflexivity.\nQed.\n\n(**************************)\nTheorem multZ_associativity : associativity Z multZ.\n\nunfold associativity in |- *; intros; elim x.\n(* OZ *)\nreflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nunfold multZ in |- *; reflexivity.\n(* pos (S y0) *)\nintros y0 H; do 2 rewrite (tech_mult_posZ y0).\nrewrite H; elim (mult_oppZ_l y z).\nelim (mult_add_distributivity (multZ (pos y0) y) y z); intros. elim H0.\nreflexivity.\n(* neg n *)\nsimple induction n.\n(* neg O *)\nsimpl in |- *; symmetry  in |- *; exact (mult_oppZ_l y z).\n(* neg (S y0) *)\nintros y0 H; do 2 rewrite (tech_mult_negZ y0).\nrewrite H; elim (mult_oppZ_l y z).\nelim (mult_add_distributivity (multZ (neg y0) y) (oppZ y) z); intros. elim H0.\nreflexivity.\nQed.\n\n(*************)\nTheorem Z_ring : is_ring Z IdZ addZ multZ OZ oppZ.\n\nunfold is_ring in |- *.\nsplit. exact addZ_commutativity.\nsplit. exact Z_group.\nsplit. unfold intern in |- *. intros. exact I.\nsplit. exact multZ_associativity. exact mult_add_distributivity.\nQed.\n\n(*********************************)\nTheorem Z_unitary_commutative_ring :\n is_unitary_commutative_ring Z IdZ addZ multZ OZ IZ oppZ.\n\nunfold is_unitary_commutative_ring in |- *.\nsplit. exact Z_ring.\nsplit. exact multZ_commutativity. exact multZ_neutral.\nQed.\n\n(* Z is an integral domain *)\n(********************)\nLemma tech_integ_posZ :\n forall (n : nat) (x : Z), multZ (pos n) x = OZ -> x = OZ.\n\nintros n x; elim x.\n(* OZ *)\nreflexivity.\n(* pos n0 *)\nintros n0; rewrite (tech_mult_pos_posZ n n0); intros.\nabsurd (pos (n * n0 + (n + n0)) = OZ). discriminate. exact H.\n(* neg n0 *)\nintros n0; rewrite (tech_mult_pos_negZ n n0); intros.\nabsurd (neg (n * n0 + (n + n0)) = OZ). discriminate. exact H.\nQed.\n\n(********************)\nLemma tech_integ_negZ :\n forall (n : nat) (x : Z), multZ (neg n) x = OZ -> x = OZ.\n\nintros n x; elim x.\n(* OZ *)\nreflexivity.\n(* pos n0 *)\nintros n0; rewrite (tech_mult_neg_posZ n n0); intros.\nabsurd (neg (n * n0 + (n + n0)) = OZ). discriminate. exact H.\n(* neg n0 *)\nintros n0; rewrite (tech_mult_neg_negZ n n0); intros.\nabsurd (pos (n * n0 + (n + n0)) = OZ). discriminate. exact H.\nQed.\n\n(*****************)\nTheorem integrityZ : integrity Z multZ OZ.\n\nunfold integrity in |- *; intros a b; elim a.\n(* OZ *)\nintros; left; reflexivity.\n(* pos n *)\nintros; right; apply (tech_integ_posZ n b); exact H.\n(* neg n *)\nintros; right; apply (tech_integ_negZ n b); exact H.\nQed.\n\n(************************)\nLemma tech_mult_pos_succZ :\n forall n m : nat, posOZ (S n * S m) = multZ (pos n) (pos m).\n\nintros; elim m.\n(* O *)\nelim multZ_neutral; intros; elim (H0 (pos n) I); intros. \nreplace (pos 0) with IZ; auto.\nrewrite H1.\nelim (mult_commut 1 (S n)). rewrite (mult_neutr (S n)). \nunfold posOZ in |- *; reflexivity.\n(* S y *)\nintros y H; elim (multZ_commutativity (pos (S y)) (pos n)).\nrewrite (tech_mult_posZ y (pos n));\n elim (multZ_commutativity (pos n) (pos y)).\nelim H; elim (mult_n_Sm (S n) (S y)); elim (plus_n_Sm (S n * S y) n).\nelim (mult_n_Sm (S n) y); elim (plus_n_Sm (S n * y) n).\nunfold posOZ in |- *; rewrite (tech_add_pos_posZ (S n * y + n) n).\nreflexivity.\nQed.\n\n(************************)\nLemma tech_mult_pos_succZ2 :\n forall n m : nat, multZ (pos n) (pos m) = pos (S n * m + n).\n\nintros; elim (tech_mult_pos_succZ n m).\nsimpl in |- *; elim (mult_n_Sm n m); elim (plus_assoc m (n * m) n);\n reflexivity. \nQed.\n\n(**************)\nLemma tech_div1 :\n forall n0 n q r : nat,\n S n0 = q * S n + r -> pos n0 = addZ (multZ (pos n) (posOZ q)) (posOZ r).\n\nintros n0 n q r; elim q.\n(* O O *)\nelim r.\nintros; absurd (S n0 = 0). discriminate. exact H.\n(* O (S y) *)\nintros y H; unfold posOZ in |- *; rewrite (mult_OZ (pos n)).\nsimpl in |- *; intros; elim (eq_add_S n0 y H0); reflexivity.\n(* (S n) O *)\nelim r.\nintros y H; unfold posOZ in |- *; elim (plus_n_O (S y * S n)).\nrewrite (add_OZ (multZ (pos n) (pos y))); elim (tech_mult_pos_succZ n y).\nelim (mult_commut (S n) (S y)); intros; elim H0; unfold posOZ in |- *;\n reflexivity.\n(* (S n) (S y) *)\nintros y H y0 H0; unfold posOZ in |- *; elim (plus_n_Sm (S y0 * S n) y).\nintros; rewrite (eq_add_S n0 (S y0 * S n + y) H1).\nrewrite (tech_mult_pos_succZ2 n y0).\nrewrite (tech_add_pos_posZ (S n * y0 + n) y).\nelim (plus_comm n (S n * y0)); elim (mult_commut y0 (S n)); simpl in |- *.\nreflexivity.\nQed.\n\n(**************)\nLemma tech_div2 :\n forall n0 n q : nat, S n0 = q * S n -> neg n0 = multZ (pos n) (negOZ q).\n\nintros n0 n q; elim q.\n(* O *)\nsimpl in |- *; intros; absurd (S n0 = 0). discriminate. exact H.\n(* S y *)\nintros y H; unfold negOZ in |- *. rewrite (tech_mult_pos_negZ n y); intros.\nsimpl in H0; rewrite (eq_add_S _ _ H0).\nelim (mult_commut (S n) y); simpl in |- *; elim (plus_comm (n + y) (n * y)).\nelim (plus_assoc n y (n * y)); reflexivity.\nQed.\n\n(***************)\nLemma tech_div31 :\n forall n q : nat,\n addZ (oppZ (multZ (pos n) (pos q))) (pos n) = oppZ (multZ (pos n) (posOZ q)).\n\nintros; elim q.\n(* O *)\nunfold posOZ in |- *; rewrite (mult_OZ (pos n)). \ncut (IZ = pos 0); intros. elim H. rewrite (mult_IZ (pos n)).\nelim (addZ_opposite (pos n) I); intros; elim H1; intros; elim H3; intros.\nrewrite H5; reflexivity. reflexivity.\n(* S y *)\nintros y H; unfold posOZ in |- *;\n elim (multZ_commutativity (pos (S y)) (pos n)).\nrewrite (tech_mult_posZ y (pos n)).\nrewrite\n (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity\n    (multZ (pos y) (pos n)) (pos n) I I).\nelim\n (addZ_associativity (oppZ (multZ (pos y) (pos n))) (oppZ (pos n)) (pos n)).\nelim (addZ_opposite (pos n) I); intros; elim H1; intros; elim H3; intros.\nrewrite H5; rewrite (add_OZ (oppZ (multZ (pos y) (pos n)))).\nelim (multZ_commutativity (pos y) (pos n)); reflexivity.\nQed.\n\n(***************)\nLemma tech_div32 :\n forall n q r : nat, S n > r -> pos (n - r) = addZ (pos n) (oppZ (posOZ r)).\n\nintros n q r; elim r.\n(* O *)\nunfold posOZ in |- *; unfold oppZ in |- *; rewrite (add_OZ (pos n));\n elim (minus_n_O n).\nreflexivity.\n(* S y *)\nintros y H; unfold posOZ in |- *; unfold oppZ in |- *; symmetry  in |- *. \nexact (tech_add_pos_neg_posZ n y (gt_S_n y n H0)).\nQed.\n\n(**************)\nLemma tech_div3 :\n forall n0 n q r : nat,\n S n0 = q * S n + r ->\n S n > r -> neg n0 = addZ (multZ (pos n) (neg q)) (pos (n - r)).\n\nintros.\nelim (tech_opp_pos_negZ q); intros; elim H1.\nrewrite (mult_oppZ_r (pos n) (pos q)); rewrite (tech_div32 n q r H0).\nrewrite\n (addZ_associativity (oppZ (multZ (pos n) (pos q))) (pos n) (oppZ (posOZ r)))\n .\nrewrite (tech_div31 n q).\nelim\n (opp_add Z IdZ addZ OZ oppZ Z_group addZ_commutativity\n    (multZ (pos n) (posOZ q)) (posOZ r) I I).\nelim (tech_div1 n0 n q r H); reflexivity.\nQed.\n\n(**************)\nLemma tech_div4 :\n forall n0 n q r : nat,\n S n0 = q * S n + r -> pos n0 = addZ (multZ (neg n) (negOZ q)) (posOZ r).\n\nintros; cut (multZ (neg n) (negOZ q) = multZ (pos n) (posOZ q)); intros.\nrewrite H0; intros; exact (tech_div1 n0 n q r H).\ncut (negOZ q = oppZ (posOZ q)); intros. rewrite H0.\nelim (tech_opp_pos_negZ n); intros; elim H1.\napply (mult_opp_opp Z IdZ addZ multZ OZ oppZ Z_ring (pos n) (posOZ q) I I).\nelim q; reflexivity.\nQed.\n\n(**************)\nLemma tech_div5 :\n forall n0 n q : nat, S n0 = q * S n -> neg n0 = multZ (neg n) (posOZ q).\n\nintros; cut (posOZ q = oppZ (negOZ q)); intros. rewrite H0.\nelim (tech_opp_pos_negZ n); intros; elim H1.\nrewrite (mult_opp_opp Z IdZ addZ multZ OZ oppZ Z_ring (pos n) (negOZ q) I I).\nexact (tech_div2 n0 n q H).\nelim q; reflexivity.\nQed.\n\n(**************)\nLemma tech_div6 :\n forall n0 n q r : nat,\n S n0 = q * S n + r ->\n S n > r -> neg n0 = addZ (multZ (neg n) (pos q)) (pos (n - r)).\n\nintros.\nelim (tech_opp_pos_negZ q); intros; elim H2.\nelim (tech_opp_pos_negZ n); intros; elim H3.\nrewrite (mult_opp_opp Z IdZ addZ multZ OZ oppZ Z_ring (pos n) (neg q) I I).\napply (tech_div3 n0 n q r H H0).\nQed.\n\n(****************)\nLemma inversibleZ :\n forall x : Z, inversible Z multZ IZ x -> x = IZ \\/ x = oppZ IZ.\n\nsimple destruct x.\n(* OZ *)\nintros; elim H; intros; elim H0; intros; elim H1.\nleft; reflexivity.\n(* pos n *)\nsimple induction n.\n(* pos O *)\nintros; left; reflexivity.\n(* pos (S y) *)\nintros y H H0; elim H0; intros; elim H1; intros.\nabsurd (multZ (pos (S y)) x0 = IZ). elim x0.\nrewrite (mult_OZ (pos (S y))). discriminate.\nintros; rewrite (tech_mult_pos_posZ (S y) n0).\nelim (plus_comm (S y + n0) (S y * n0)).\nelim (plus_assoc (S y) n0 (S y * n0)); simpl in |- *.\napply (tech_pos_not_posZ (S (y + (n0 + (n0 + y * n0)))) 0).\ndiscriminate.\nintros; rewrite (tech_mult_pos_negZ (S y) n0).\nelim (plus_comm (S y + n0) (S y * n0)).\nelim (plus_assoc (S y) n0 (S y * n0)); simpl in |- *; discriminate.\nexact H2.\n(* neg n *) \nsimple induction n.\n(* neg O *)\nright; reflexivity.\n(* neg (S y) *)\nintros y H H0; elim H0; intros; elim H1; intros.\nabsurd (multZ (neg (S y)) x0 = IZ). elim x0.\nrewrite (mult_OZ (neg (S y))). discriminate.\nintros; rewrite (tech_mult_neg_posZ (S y) n0).\nelim (plus_comm (S y + n0) (S y * n0)).\nelim (plus_assoc (S y) n0 (S y * n0)); simpl in |- *; discriminate.\nintros; rewrite (tech_mult_neg_negZ (S y) n0).\nelim (plus_comm (S y + n0) (S y * n0)).\nelim (plus_assoc (S y) n0 (S y * n0)); simpl in |- *.\napply (tech_pos_not_posZ (S (y + (n0 + (n0 + y * n0)))) 0).\ndiscriminate.\nexact H2.\nQed.\n\n(************)\nLemma sgn_abs : forall x : Z, multZ x (sgnZ x) = absZ x.\n\nsimple destruct x.\n(* OZ *)\nreflexivity.\n(* pos n *)\nintros; exact (mult_IZ (pos n)).\n(* neg n *)\nintros; exact (mult_mIZ (neg n)).\nQed.", "meta": {"author": "coq-contribs", "repo": "chinese", "sha": "8af6c42f817721f7ac0f8f6fa6e123a455f4713e", "save_path": "github-repos/coq/coq-contribs-chinese", "path": "github-repos/coq/coq-contribs-chinese/chinese-8af6c42f817721f7ac0f8f6fa6e123a455f4713e/Zmult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7181768346351658}}
{"text": "Require Import Coq.Init.Prelude.\n\n(** 点ごとに等しい *)\nDefinition pointwise_eq {A B : Type} (f g : A -> B) : Prop := forall x, f x = g x.\n\nNotation \"f == g\" := (pointwise_eq f g) (at level 70, no associativity) : type_scope.\n\n\n(** 恒等射 *)\nDefinition id {A : Type} : A -> A := fun x => x.\n\n(** 射の合成 *)\nDefinition compose {A B C : Type} (f : B -> C) (g : A -> B) : A -> C := fun x => f (g x).\n\nNotation \"g 'o' f\" := (compose g%function f%function) (at level 40, left associativity)\n : function_scope.\n\n\n(** [f] は単射である *)\nDefinition mono {A B : Type} (f : A -> B) : Prop\n := forall (Z : Type) (g₁ g₂ : Z -> A), f o g₁ == f o g₂ -> g₁ == g₂.\n\n(** [f] に対して [g] は左逆射である *)\nDefinition left_inv_rel {A B : Type} (f : A -> B) (g : B -> A) : Prop := g o f == id.\n\n(** [f] は左逆射を持つ *)\nDefinition left_inv {A B : Type} (f : A -> B) : Prop := ex (left_inv_rel f).\n\n(** [h] は分裂単射である *)\nDefinition split_mono {A B : Type} (h : A -> B) : Prop := left_inv h /\\ mono h.\n\n(** [f] は全射である *)\nDefinition epi {A B : Type} (f : A -> B) : Prop\n := forall (C : Type) (g₁ g₂ : B -> C), g₁ o f == g₂ o f -> g₁ == g₂.\n\n(** [f] に対して [g] は右逆射である *)\nDefinition right_inv_rel {A B : Type} (f : A -> B) (g : B -> A) : Prop := f o g == id.\n\n(** [f] は右逆射を持つ *)\nDefinition right_inv {A B : Type} (f : A -> B) : Prop := ex (right_inv_rel f).\n\n(** [f] は分裂全射である *)\nDefinition split_epi {A B : Type} (h : A -> B) : Prop := right_inv h /\\ epi h.\n\n(** [f] は全単射／双射である *)\nDefinition bi {A B : Type} (f : A -> B) : Prop := mono f /\\ epi f.\n\n(** [f] と [g] は逆射の関係である *)\nDefinition iso_rel {A B : Type} (f : A -> B) (g : B -> A) : Prop := g o f == id /\\ f o g == id.\n\n(** [f] は同型射である *)\nDefinition iso {A B : Type} (f : A -> B) : Prop := ex (iso_rel f).\n\n\n(** 左逆射を持つ [f] の、その左逆射／引き込みを得る *)\nDefinition retraction {A B : Type} (f : A -> B) (P : left_inv f) : B -> A.\nProof.\n (* destruct P as [ g P ]. *)\nAdmitted.\n\n(** 右逆射を持つ [f] の、その右逆射／断面を得る *)\nDefinition section {A B : Type} (f : A -> B) (P : right_inv f) : B -> A.\nProof.\n (* destruct P as [ g P ]. *)\nAdmitted.\n\n\n(** [f] が左逆射を持つならば [f] は単射である *)\nDefinition mono_left_inv {A B : Type} (f : A -> B) : left_inv f -> mono f.\nProof.\n intros P.\n unfold left_inv in P.\n destruct P as [ g P ].\n unfold left_inv_rel in P.\n unfold mono.\n intros Z g₁ g₂ Q.\n unfold pointwise_eq.\n intros x.\n change (id (g₁ x) = id (g₂ x)).\n unfold pointwise_eq in P.\n rewrite <- P with (g₁ x).\n rewrite <- P with (g₂ x).\n unfold compose.\n apply f_equal.\n unfold pointwise_eq in Q.\n unfold compose in Q.\n apply Q.\nDefined.\n\n(** [f] が右逆射を持つならば [f] は全射である *)\nDefinition epi_right_inv {A B : Type} (f : A -> B) : right_inv f -> epi f.\nProof.\n intros P.\n unfold right_inv in P.\n destruct P as [ g P ].\n unfold right_inv_rel in P.\n unfold epi.\n intros C g₁ g₂ Q.\n unfold pointwise_eq.\n intros x.\n change (g₁ (id x) = g₂ (id x)).\n unfold pointwise_eq in P.\n rewrite <- P with x.\n unfold compose.\n unfold pointwise_eq in Q.\n unfold compose in Q.\n apply Q.\nDefined.\n\n(** [f] が同型射であるのならば [f] は左逆射を持ち、右逆射を持つ *)\nDefinition left_right_inv_iso {A B : Type} (f : A -> B) : iso f -> left_inv f /\\ right_inv f.\nProof.\n intros P.\n unfold iso in P.\n destruct P as [ g P ].\n unfold iso_rel in P.\n destruct P as [ left_P right_P ].\n split.\n -\n  unfold left_inv.\n  exists g.\n  unfold left_inv_rel.\n  apply left_P.\n -\n  unfold right_inv.\n  exists g.\n  unfold right_inv_rel.\n  apply right_P.\nDefined.\n\n(** [f] が同型射であるのならば [f] は双射である *)\nDefinition bi_iso {A B : Type} (f : A -> B) : iso f -> bi f.\nProof.\n intros P.\n apply left_right_inv_iso in P.\n destruct P as [ left_P right_P ].\n unfold bi.\n split.\n -\n  apply mono_left_inv.\n  apply left_P.\n -\n  apply epi_right_inv.\n  apply right_P.\nDefined.\n", "meta": {"author": "Hexirp", "repo": "coq-gist", "sha": "ee215045eaf99febb40fca953c3d1ba75a4d1d36", "save_path": "github-repos/coq/Hexirp-coq-gist", "path": "github-repos/coq/Hexirp-coq-gist/coq-gist-ee215045eaf99febb40fca953c3d1ba75a4d1d36/inverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7181768332350287}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** A modular implementation of mergesort (the complexity is O(n.log n) in\n   the length of the list) *)\n\n(* Initial author: Hugo Herbelin, Oct 2009 *)\n\nRequire Import List Setoid Permutation Sorted Orders.\n\n(** Notations and conventions *)\n\nLocal Notation \"[ ]\" := nil.\nLocal Notation \"[ a ; .. ; b ]\" := (a :: .. (b :: []) ..).\n\nOpen Scope bool_scope.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\n(** The main module defining [mergesort] on a given boolean\n    order [<=?]. We require minimal hypotheses : this boolean\n    order should only be total: [forall x y, (x<=?y) \\/ (y<=?x)].\n    Transitivity is not mandatory, but without it one can\n    only prove [LocallySorted] and not [StronglySorted].\n*)\n\nModule Sort (Import X:Orders.TotalLeBool').\n\nFixpoint merge l1 l2 :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | a1::l1', a2::l2' =>\n      if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\n(** We implement mergesort using an explicit stack of pending mergings.\n    Pending merging are represented like a binary number where digits are\n    either None (denoting 0) or Some list to merge (denoting 1). The n-th\n    digit represents the pending list to be merged at level n, if any.\n    Merging a list to a stack is like adding 1 to the binary number\n    represented by the stack but the carry is propagated by merging the\n    lists. In practice, when used in mergesort, the n-th digit, if non 0,\n    carries a list of length 2^n. For instance, adding singleton list\n    [3] to the stack Some [4]::Some [2;6]::None::Some [1;3;5;5]\n    reduces to propagate the carry [3;4] (resulting of the merge of [3]\n    and [4]) to the list Some [2;6]::None::Some [1;3;5;5], which reduces\n    to propagating the carry [2;3;4;6] (resulting of the merge of [3;4] and\n    [2;6]) to the list None::Some [1;3;5;5], which locally produces\n    Some [2;3;4;6]::Some [1;3;5;5], i.e. which produces the final result\n    None::None::Some [2;3;4;6]::Some [1;3;5;5].\n\n    For instance, here is how [6;2;3;1;5] is sorted:\n\n<<\n       operation             stack                list\n       iter_merge            []                   [6;2;3;1;5]\n    =  append_list_to_stack  [ + [6]]             [2;3;1;5]\n    -> iter_merge            [[6]]                [2;3;1;5]\n    =  append_list_to_stack  [[6] + [2]]          [3;1;5]\n    =  append_list_to_stack  [ + [2;6];]          [3;1;5]\n    -> iter_merge            [[2;6];]             [3;1;5]\n    =  append_list_to_stack  [[2;6]; + [3]]       [1;5]\n    -> merge_list            [[2;6];[3]]          [1;5]\n    =  append_list_to_stack  [[2;6];[3] + [1]     [5]\n    =  append_list_to_stack  [[2;6] + [1;3];]     [5]\n    =  append_list_to_stack  [ + [1;2;3;6];;]     [5]\n    -> merge_list            [[1;2;3;6];;]        [5]\n    =  append_list_to_stack  [[1;2;3;6];; + [5]]  []\n    -> merge_stack           [[1;2;3;6];;[5]]\n    =                                             [1;2;3;5;6]\n>>\n    The complexity of the algorithm is n*log n, since there are\n    2^(p-1) mergings to do of length 2, 2^(p-2) of length 4, ..., 2^0\n    of length 2^p for a list of length 2^p. The algorithm does not need\n    explicitly cutting the list in 2 parts at each step since it the\n    successive accumulation of fragments on the stack which ensures\n    that lists are merged on a dichotomic basis.\n*)\n\nFixpoint merge_list_to_stack stack l :=\n  match stack with\n  | [] => [Some l]\n  | None :: stack' => Some l :: stack'\n  | Some l' :: stack' => None :: merge_list_to_stack stack' (merge l' l)\n  end.\n\nFixpoint merge_stack stack :=\n  match stack with\n  | [] => []\n  | None :: stack' => merge_stack stack'\n  | Some l :: stack' => merge l (merge_stack stack')\n  end.\n\nFixpoint iter_merge stack l :=\n  match l with\n  | [] => merge_stack stack\n  | a::l' => iter_merge (merge_list_to_stack stack [a]) l'\n  end.\n\nDefinition sort := iter_merge [].\n\n(** The proof of correctness *)\n\nLocal Notation Sorted := (LocallySorted leb) (only parsing).\n\nFixpoint SortedStack stack :=\n  match stack with\n  | [] => True\n  | None :: stack' => SortedStack stack'\n  | Some l :: stack' => Sorted l /\\ SortedStack stack'\n  end.\n\nLocal Ltac invert H := inversion H; subst; clear H.\n\nFixpoint flatten_stack (stack : list (option (list t))) :=\n  match stack with\n  | [] => []\n  | None :: stack' => flatten_stack stack'\n  | Some l :: stack' => l ++ flatten_stack stack'\n  end.\n\nTheorem Sorted_merge : forall l1 l2,\n  Sorted l1 -> Sorted l2 -> Sorted (merge l1 l2).\nProof.\ninduction l1; induction l2; intros; simpl; auto.\n  destruct (a <=? a0) eqn:Heq1.\n    invert H.\n      simpl. constructor; trivial; rewrite Heq1; constructor.\n      assert (Sorted (merge (b::l) (a0::l2))) by (apply IHl1; auto).\n      clear H0 H3 IHl1; simpl in *.\n      destruct (b <=? a0); constructor; auto || rewrite Heq1; constructor.\n    assert (a0 <=? a) by\n      (destruct (leb_total a0 a) as [H'|H']; trivial || (rewrite Heq1 in H'; inversion H')).\n    invert H0.\n      constructor; trivial.\n      assert (Sorted (merge (a::l1) (b::l))) by auto using IHl1.\n      clear IHl2; simpl in *.\n      destruct (a <=? b); constructor; auto.\nQed.\n\nTheorem Permuted_merge : forall l1 l2, Permutation (l1++l2) (merge l1 l2).\nProof.\n  induction l1; simpl merge; intro.\n    assert (forall l, (fix merge_aux (l0 : list t) : list t := l0) l = l)\n    as -> by (destruct l; trivial). (* Technical lemma *)\n    apply Permutation_refl.\n  induction l2.\n    rewrite app_nil_r. apply Permutation_refl.\n    destruct (a <=? a0).\n      constructor; apply IHl1.\n      apply Permutation_sym, Permutation_cons_app, Permutation_sym, IHl2.\nQed.\n\nTheorem Sorted_merge_list_to_stack : forall stack l,\n  SortedStack stack -> Sorted l -> SortedStack (merge_list_to_stack stack l).\nProof.\n  induction stack as [|[|]]; intros; simpl.\n    auto.\n    apply IHstack. destruct H as (_,H1). fold SortedStack in H1. auto.\n      apply Sorted_merge; auto; destruct H; auto.\n      auto.\nQed.\n\nTheorem Permuted_merge_list_to_stack : forall stack l,\n  Permutation (l ++ flatten_stack stack) (flatten_stack (merge_list_to_stack stack l)).\nProof.\n  induction stack as [|[]]; simpl; intros.\n    reflexivity.\n    rewrite app_assoc.\n    etransitivity.\n      apply Permutation_app_tail.\n      etransitivity.\n        apply Permutation_app_comm.\n      apply Permuted_merge.\n    apply IHstack.\n    reflexivity.\nQed.\n\nTheorem Sorted_merge_stack : forall stack,\n  SortedStack stack -> Sorted (merge_stack stack).\nProof.\ninduction stack as [|[|]]; simpl; intros.\n  constructor; auto.\n  apply Sorted_merge; tauto.\n  auto.\nQed.\n\nTheorem Permuted_merge_stack : forall stack,\n  Permutation (flatten_stack stack) (merge_stack stack).\nProof.\ninduction stack as [|[]]; simpl.\n  trivial.\n  transitivity (l ++ merge_stack stack).\n    apply Permutation_app_head; trivial.\n    apply Permuted_merge.\n  assumption.\nQed.\n\nTheorem Sorted_iter_merge : forall stack l,\n  SortedStack stack -> Sorted (iter_merge stack l).\nProof.\n  intros stack l H; induction l in stack, H |- *; simpl.\n    auto using Sorted_merge_stack.\n    assert (Sorted [a]) by constructor.\n    auto using Sorted_merge_list_to_stack.\nQed.\n\nTheorem Permuted_iter_merge : forall l stack,\n  Permutation (flatten_stack stack ++ l) (iter_merge stack l).\nProof.\n  induction l; simpl; intros.\n    rewrite app_nil_r. apply Permuted_merge_stack.\n    change (a::l) with ([a]++l).\n    rewrite app_assoc.\n    etransitivity.\n      apply Permutation_app_tail.\n    etransitivity.\n    apply Permutation_app_comm.\n    apply Permuted_merge_list_to_stack.\n    apply IHl.\nQed.\n\nTheorem Sorted_sort : forall l, Sorted (sort l).\nProof.\nintro; apply Sorted_iter_merge. constructor.\nQed.\n\nCorollary LocallySorted_sort : forall l, Sorted.Sorted leb (sort l).\nProof. intro; eapply Sorted_LocallySorted_iff, Sorted_sort; auto. Qed.\n\nTheorem Permuted_sort : forall l, Permutation l (sort l).\nProof.\nintro; apply (Permuted_iter_merge l []).\nQed.\n\nCorollary StronglySorted_sort : forall l,\n  Transitive leb -> StronglySorted leb (sort l).\nProof. auto using Sorted_StronglySorted, LocallySorted_sort. Qed.\n\nEnd Sort.\n\n(** An example *)\n\nModule NatOrder <: TotalLeBool.\n  Definition t := nat.\n  Fixpoint leb x y :=\n    match x, y with\n    | 0, _ => true\n    | _, 0 => false\n    | S x', S y' => leb x' y'\n    end.\n  Infix \"<=?\" := leb (at level 35).\n  Theorem leb_total : forall a1 a2, a1 <=? a2 \\/ a2 <=? a1.\n  Proof.\n    induction a1; destruct a2; simpl; auto.\n  Qed.\nEnd NatOrder.\n\nModule Import NatSort := Sort NatOrder.\n\nExample SimpleMergeExample := Eval compute in sort [5;3;6;1;8;6;0].\n\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Sorting/Mergesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7181768311810276}}
{"text": "Require Import FinTypes.\n(**  Proofs about DFA as a test for the finType library *)\nSet Implicit Arguments.\nUnset Printing Implicit Defensive.\nUnset Strict Implicit.\nSet Contextual Implicit.\n\n(** * Conversion between Props and bools *)\n\nCoercion toProp (b:bool) := if b then True else False.\n\nInstance toProp_dec b : dec (toProp b).\nProof.\n  destruct b; auto.\nQed.\n\nSection DFA.\n  (** * Definition of the alphabet, words and dfa*)\n  Variable Sig: finType.\n  Definition word := list Sig.\n  \nRecord dfa: Type :=\n  DFA {\n      S:> finType;\n      s: S;\n      F: decPred S;\n      delta_S: S -> Sig -> S\n    }.\n\nSection Reachability.\nVariable  A : dfa.\n(** transition function for whole words *)\nFixpoint delta_star (q: A) (w: word) :=\n  match w with \n  | nil => q\n  | x::w' => delta_star (delta_S q x) w'\n  end.\n\n(** Definition if acceptance *)\nDefinition accept (w:word) := F (@delta_star s w).\n\nInstance accept_dec w : dec (accept w).\nProof.\n  auto.\nQed.\n\n(** * Reachability \n- normal reachability\n- reachability with a specific word\n *)\n\nInductive reachable (q: A) :  A -> Prop :=\n| refl: reachable q q\n| step q' x: reachable (delta_S q x) q' -> reachable q q'.\n\nDefinition reachable_with q w q':= delta_star q w = q'.\n\nHint Constructors reachable.\n\nLemma reachable_with_reachable (q q': A): reachable q q' <-> exists w, reachable_with q w q'.\nProof.\n  split.\n  - intro R. induction R.\n    + now exists nil.\n    + destruct IHR as [w IHR]. exists (x::w). unfold reachable_with. cbn. congruence.\n  - intros [w H]. revert q H.  induction w; intros q H.\n    + now rewrite H.\n    + econstructor 2. apply IHw. apply H.\nQed.\n\nHint Resolve reachable_with_reachable.\n\nLemma reachable_transitive (q:A) q' q'': reachable q q' /\\ reachable q' q'' -> reachable q q''.\nProof.\n  intros [R R']. induction R; eauto.\nQed.\n(*\nLemma reachable_delta_star q w: reachable q (delta_star q w).\nProof.\n  apply reachable_with_reachable. now exists w.\nQed.\n*)\n(** * Reach (set of all reachable states)\n- defined using fixed-point iteration *)\n\n(* The predicate for the fixed-point iteration *)\nDefinition step_reach (set: list A) (q: A) := exists q' x, q' el set /\\ reachable_with q' [x] q.\n\nLemma step_reach_consistent: step_consistent step_reach.\nProof.\n  intros B q H B' sub. destruct H as [q' [x [E R]]]. exists q', x. auto.\nQed.    \n\nDefinition reach (q: A) := FCIter step_reach [q].\n\nLemma reach_least_fp q: least_fp_containing (FCStep step_reach) (reach q) [q]. \nProof.\n  apply step_consistent_least_fp. apply step_reach_consistent.\nQed.\n\nLemma reach_correct1 (q:A): inclp (reach q) (reachable q).\nProof.\n  apply FCIter_ind.\n  - intro x. cbn. now intros [[]|[]].\n  - intros set q' H [q'' [x [E  H1]]]. eapply reachable_transitive; split.\n    + apply (H _ E).\n    + apply reachable_with_reachable. eauto.\nQed.\n \nLemma reach_correct2' q q': q' el reach q -> forall q'', reachable q' q'' -> q'' el reach q.\nProof.\n intros E q'' R. induction R.\n  - exact E.\n  - apply IHR. apply Closure_FCIter. now  exists q0, x.\nQed.\n\nLemma reach_correct2 q: forall q', reachable q q' -> q' el reach q.\nProof.\napply reach_correct2'. now apply preservation_FCIter.\nQed.        \n\nLemma reach_correct q q': reachable q q' <-> q' el (reach q).\nProof.\n  split.\n  - apply reach_correct2.\n  - apply reach_correct1.\nQed.\n\nGlobal Instance reachable_dec q q': dec (reachable q q').\nProof.\n  eapply dec_prop_iff.\n  - symmetry. apply reach_correct.\n  - auto.\nQed.    \n\nGlobal Instance reachable_with_something_dec q q': dec (exists w, reachable_with q w q').\nProof.\n  eauto.\nQed.\n\nLemma reach_reachable_with q q': (exists w, reachable_with q w q') <-> q' el reach q.\nProof.\n rewrite <- reachable_with_reachable.  apply reach_correct.\nQed.\n\nLemma delta_star_reach w q: delta_star q w el (reach q).\nProof.\n  apply reach_reachable_with. now exists w.\nQed.\n\nNotation in_lang w := (accept w) (only parsing).\n\nLemma Sig_reach : (forall w, in_lang w) <-> forall (q: A), q el (reach s) -> F q.\nProof.\n  split.\n  - intros H q E. rewrite <- reach_reachable_with in E. destruct E as [w R].\n   rewrite <- R.  apply (H w).\n  - intros H w. apply (H (delta_star s w)). apply delta_star_reach.\nQed.    \n  \nGlobal Instance Sig_dec : dec (forall w, in_lang w).\nProof.\n  decide( forall q, q el reach s -> F q) as [H | H].\n  - left. now apply Sig_reach.\n  - right. now rewrite Sig_reach.\nQed.\n\nDefinition empty := forall w, ~ in_lang w.\n\nDefinition neg_F := DecPred (fun x => ~ (@F A  x)).\n\nDefinition complement := DFA s neg_F (@delta_S A).\n\nEnd Reachability.\nNotation in_lang A w := (accept A w) (only parsing).\nSection Operations.\nVariable  A : dfa.\n\nLemma complement_correct w: accept (complement A) w <-> ~ (accept A w).\nProof.\n  split; auto.\nQed.\n\nGlobal Instance empty_dec : dec (empty A).\nProof.\n  apply (dec_trans (@Sig_dec (complement A))). now setoid_rewrite complement_correct.\nQed.\n\nLemma empty_reach: empty A <-> forall (q:A), q el (reach s) -> ~ (F q).\nProof.\n  split.\n  - intros empt q E F . rewrite <- reach_reachable_with in E. destruct E as [w R].\n    specialize (empt w). apply empt. unfold accept. now rewrite R.\n  - intros H w acc. specialize (H (delta_star s w)). apply H.\n    + apply delta_star_reach.\n    + exact acc.\nQed.\n\nInstance exists_accept_dec: dec (exists w, accept A w).\nProof.\ndecide (empty A) as [H | H].\n- firstorder.\n- left. unfold empty in H.  rewrite empty_reach in H. rewrite DM_notAll in H.\n  + destruct H as [q H]. destruct (dec_DM_impl _ _ H) as [H' acc].\n     rewrite <- reach_reachable_with in H'. destruct H' as [w R]. exists w.  rewrite <- R in acc. \n    apply dec_DN; auto.     \n  + auto.\nQed.\n\nInstance exists_not_accept_dec : dec (exists w, ~ accept A w).\nProof.\n  decide (forall w, accept A w) as [H|H].\n  - right. firstorder.\n  - left. rewrite Sig_reach in H. rewrite DM_notAll in H.\n    + destruct H as [q H].  destruct (dec_DM_impl _ _ H) as [H' acc].\n       rewrite <- reach_reachable_with in H'. destruct H' as [w R]. exists w.  now rewrite <- R in acc. \n    + auto.\nQed.      \n    \nDefinition Epsilon_autom : dfa.\nProof.\n  refine (DFA (inl tt) (DecPred (fun q: unit + unit => if q then True else False)) (fun _ _ => inr tt)).\n  intros [[]|[]]; auto.\nDefined.\n\n\nLemma inr_fix_epsilon w : (@delta_star Epsilon_autom (inr tt) w) = inr tt.\nProof.\n  now induction w.\nQed.\n\nLemma Epsilon_autom_correct w: accept Epsilon_autom w <-> w = nil.\nProof.\n  split.\n  - cbn. destruct w.\n    + reflexivity.\n    + cbn. now rewrite inr_fix_epsilon.\n  - intros H. subst w. cbn. exact I.\nQed.\n\n\n\nDefinition predCons (A:dfa) (q: option A + unit) := match q with\n                                                        | inl None => False\n                                                        | inl (Some q) => F q\n                                                        | inr tt => False end.\n\nDefinition deltaCons x (A:dfa) (q: option A + unit) y  := match q with\n                                     | inl None => if decision (y = x) then inl (Some s) else inr tt\n                                     | inl (Some q) => inl (Some (delta_S q y))\n                                     | inr tt => inr tt end.\n\nInstance predCons_dec  (A:dfa) (q: option A + unit) : dec (predCons q).\nProof.\n  destruct q.\n  - destruct o; auto.\n  - destruct u; auto.\nQed.\n\n\nDefinition cons (A: dfa) (x:Sig) :=\n  DFA (inl None) (DecPred (@predCons A)) (@deltaCons x A).\n\n\nLemma inr_fix A' x w : (@delta_star (cons A' x) (inr tt) w) = inr tt.\nProof.\n  now induction w.\nQed.    \n\nLemma cons_correct  (A':dfa) x w : accept A' w <-> accept (cons A' x) (x::w).\nProof.\n  cbn in *. deq x. unfold accept. generalize (@s A').  induction w; firstorder.\nQed.\n\n\nFixpoint exactW (w: word)  := match w with\n                     | nil => Epsilon_autom\n                     | x::w' => cons (exactW w') x end.\n\nLemma exactW_correct w w': accept (exactW w) w' <-> w' = w.\nProof.\n  split.\n    - revert w'; induction w; intros w';  destruct w'.\n   + reflexivity.\n   + simpl. apply Epsilon_autom_correct.\n   + cbn. tauto.\n   + intros H. pose proof (@cons_correct (exactW w) a w') as nc; cbn in *. deq a.     \n    dec.\n    * subst e. rewrite <- nc in H. f_equal. now apply IHw.\n    * unfold predCons in *. now rewrite (@inr_fix (exactW w) _  w') in H.\n    - intros []. induction w'.\n      + exact I.\n      + simpl. now rewrite <- cons_correct.\nQed.\n    \nVariable A':dfa.\n\n\nSection Product_automaton.\n  Variable op: Prop -> Prop -> Prop.\n  Variable op_dec: forall P Q, dec P -> dec Q -> dec (op P Q).\n  \n  Definition prod_delta: A (x) A' -> Sig -> A (x) A' :=\n    fun P x  => match P with (q1,q2) => (delta_S q1 x, delta_S q2 x) end.\nDefinition prod_pred := (fun P => match P with (q1,q2) => op (@F A q1) (@F A' q2) end).\n\nGlobal Instance prod_pred_dec P: dec (prod_pred P).\nProof.\n  destruct P as [q1 q2]. auto.\nQed.\n\nDefinition prod_F  := DecPred prod_pred.\n\nDefinition prod := DFA (s,s) prod_F prod_delta.\n\nLemma prod_delta_star w q1 q2 : @delta_star prod (q1, q2) w = (delta_star q1 w, delta_star q2 w).\nProof.\n  revert q1 q2. induction w; now cbn.\nQed.\n\nLemma prod_correct w: accept prod w <-> op (accept A w) (accept A' w).\nProof.\n  cbn. now rewrite prod_delta_star.\nQed.\n\nEnd Product_automaton.\nArguments prod op {op_dec}.\n\nDefinition intersect := prod and.\n\nLemma intersect_correct w: accept intersect w <-> accept A w /\\ accept A' w.\nProof.\n  apply prod_correct.\nQed.\n\nDefinition U :=  prod or.\n\nLemma U_correct w: accept U w <-> accept A w \\/ accept A' w.\nProof.\n  apply prod_correct.\nQed.\n\nDefinition diff := prod (fun P Q => P /\\ ~ Q).\n\nLemma diff_correct w : accept diff w <-> accept A w /\\ ~ accept A' w.\nProof.\n  unfold diff. now rewrite prod_correct.\nQed.\n\nDefinition lang_incl := forall w, in_lang A w -> in_lang A' w.\n\nLemma lang_incl_iff : lang_incl <-> empty diff.\nProof.\n  unfold empty. setoid_rewrite diff_correct. split.\n  - firstorder.\n  - intros H w H'. specialize (H w). destruct (dec_DM_and _ H).\n    + tauto.\n    + apply dec_DN; auto.\nQed.\n\nEnd Operations.\n\nDefinition lang_equiv A A':= lang_incl A A' /\\ lang_incl A' A.\n\nInstance lang_sub_dec A A' : dec (lang_incl A A'). \nProof.\n  decide (empty (diff A A')) as [H|H]; unfold empty in H; setoid_rewrite diff_correct in H.\n  - left. intros w acc. specialize (H w). decide (accept A' w); tauto.\n  - right. firstorder.\nQed.    \n\nInstance equiv_eq_dec A A': dec (lang_equiv A A').\nProof.\n  auto.\nQed.\n\n(** * Nondeterministic finite automata (NFA)*)\n\nRecord nfa := NFA {\n                  Q :> finType;\n                  q0:Q;\n                  Q_acc: decPred Q;\n                  delta_Q: Q -> Sig -> decPred Q\n                }.\n\nImplicit Type B : nfa.\nImplicit Type A: dfa.\nFixpoint delta_Q_star B q w: B -> Prop  :=\n  match w with\n  | nil => fun q' => q' = q\n  |x::w' => fun q'' => exists q', delta_Q q x q' /\\ delta_Q_star q' w' q''\n  end.\nArguments delta_Q_star {B} q w q'.\n\nInstance delta_Q_star_dec B (q q': B) w: dec (delta_Q_star q w q').\nProof.\n revert q. induction w.\n  - cbn. auto.\n  - intros q. cbn. auto.\nQed.\n\nLemma delta_Q_star_trans B w w' (q q' q'': B) : delta_Q_star q w q' /\\ delta_Q_star q' w' q'' -> delta_Q_star q (w ++ w') q''.\nProof.\n  intros [H H']. revert q H. induction w; intros q H.\n  - cbn in *. congruence.\n  - cbn in *. destruct H as [q_m [D H]]. exists q_m. split.\n    + exact D.\n    + now apply IHw.\nQed.      \n    \nDefinition n_accept B w := exists (q:B), Q_acc q /\\ delta_Q_star q0 w q.\n\nDefinition toNFA A := @NFA (S A) s F (fun q x => DecPred (fun q' => delta_S q x = q')).\n\n\nLemma toNFA_delta_star_correct A q w q': q' = delta_star q w <-> @delta_Q_star (toNFA A) q w q'.\nProof.\n  revert q. induction w.\n  - reflexivity.\n  - intro q; cbn. rewrite IHw. split.\n    +eauto.\n    +now intros [q'' [[] H]].   \nQed.\n\nLemma toNFA_correct A : forall w, accept A w <-> n_accept (toNFA A) w.\nProof.\n  intros w. unfold accept, n_accept. split.\n  - intros H. exists (delta_star s w). now rewrite <- toNFA_delta_star_correct.\n  - intros [q [acc H]]. rewrite <- toNFA_delta_star_correct in H. now subst q.\nQed.\n\nDefinition toDFA_F B := fun f: B --> bool => exists q, f q /\\ Q_acc q.\n\nDefinition toDFA_delta B := fun (f: B --> bool) x => vectorise (fun q => toBool (exists q':B, f q' /\\ delta_Q q' x q)).\n\nLemma toDFA_delta_correct B f x q : toDFA_delta f x q -> exists q':B, f q' /\\ delta_Q q' x q.\nProof.\n  intros H.   unfold toDFA_delta in H. rewrite apply_vectorise_inverse in H. unfold toBool in H. dec.\n  - assumption.\n  - contradiction H.\nQed.\n\nDefinition onestate B q:= (vectorise (fun q':B => toBool (q' = q) )).\n\nLemma onestate_correct B q q' : @onestate B q q' <-> q = q'.\nProof.\n  unfold onestate. rewrite apply_vectorise_inverse. unfold toBool. dec; cbn.\n  - subst q. tauto.\n  - split; [>tauto | auto].\nQed.\n\nDefinition toDFA B := DFA (onestate q0) (DecPred (@toDFA_F B)) (@toDFA_delta B).\n\nLemma toDFA_delta_star_correct1 B q w q':\n  delta_Q_star q w q' -> forall f: B --> bool, f q -> applyVect (@delta_star (toDFA B) f w) q'.\nProof.\n  intros H f F. revert f q F H. induction w; intros f q F H; cbn in *.\n   -  now subst q'.\n   - destruct H as [q'' [H S]]. eapply IHw; eauto.\n      unfold toDFA_delta. rewrite apply_vectorise_inverse. unfold toBool. dec.\n     + exact I.\n     + apply n. now exists q.\n  Qed.\n\nLemma toDFA_delta_star_correct2 B (f: B --> bool) w q':\n  applyVect (@delta_star (toDFA B) f w) q' -> exists q, f q /\\ delta_Q_star q w q'.\nProof.\n  revert f. induction w.\n  - cbn. eauto.\n  - intros f. cbn. intros H. specialize (IHw _ H). destruct IHw as [q'' [E E']].\n    destruct (toDFA_delta_correct E). firstorder.\nQed.\n    \nLemma toDFA_correct B w: n_accept B w <-> accept (toDFA B) w.\nProof.\n  cbn. unfold n_accept, toDFA_F. split.\n  -  intros [q [acc G]]. exists q; split.\n     + apply (toDFA_delta_star_correct1 G). now apply onestate_correct.\n     + exact acc.       \n  -  intros [q [H acc]]. exists q; split.\n     + exact acc.\n     + destruct (toDFA_delta_star_correct2 H) as [q' [E D]]. rewrite onestate_correct in E. now subst q'.\nQed.\n\n(** * Concatenation of two regular languages *)\n\nDefinition concat_acc_pred B B' := fun (q: B + B') => match q with\n                                             | inl q => if decision (Q_acc (@q0 B')) then Q_acc q else False\n                                             | inr q => Q_acc q\n                                             end.\n\nInstance acc_dec B B' q: dec (@concat_acc_pred B B' q).\nProof.\n  destruct q as [q | q].\n  - cbn. dec; auto.\n  - auto.    \nQed.\n\nDefinition concat_acc_decPred B B':= DecPred (@concat_acc_pred B B').\n\nDefinition concat_delta B B' (q q': B + B') x:= match q with\n                                          | inl q => match q' with\n                                                    | inl q' => delta_Q q x q'\n                                                    | inr q' => if decision (@Q_acc B q) then delta_Q q0 x q' else False\n                                                    end\n                                          | inr q => match q' with\n                                                    | inl q' => False\n                                                    | inr q' => delta_Q q x q'\n                                                    end\n                                          end.\n\nInstance conact_delta_dec B B' (q: B + B') x q' : dec (concat_delta q q' x).\nProof.\n  destruct q, q'.\n  - auto.\n  - cbn. dec; auto.\n  - auto.\n  - auto.\nQed.\n\nDefinition concat_delta_Q B B':= fun (q: B + B') x => DecPred (fun q' => concat_delta q q' x).\n\nDefinition concat B B' := NFA (inl (@q0 B)) (@concat_acc_decPred B B') (@concat_delta_Q B B').\n\n\nLemma concat_delta_Q_star_correct1 B B' q q' w: @delta_Q_star (concat B B') (inr q) w (inl q') <-> False.\nProof.\n  split; try tauto. revert q; induction w; intro q.\n  - congruence.\n  - cbn. intros [[q''|q''] H]; firstorder.\nQed.      \n    \nLemma concat_delta_Q_star_correct2 B B' q q' w:  @delta_Q_star (concat B B') (inl q) w (inl q') <->   delta_Q_star q w q'.\nProof.\n  split; revert q; induction w; intro q; try congruence.\n  - intros [[q''|q''] [S H]].\n    + exists q''. firstorder.\n    + now rewrite concat_delta_Q_star_correct1 in H.\n  - intro H. firstorder.\nQed.\n\nLemma concat_delta_Q_star_correct3 B B' q q' w:  @delta_Q_star (concat B B') (inr q) w (inr q') <->   delta_Q_star q w q'.\nProof.\n  split; revert q; induction w; intro q; try congruence.\n  - intros [[q''|q''] [S H]].\n    + contradiction S. \n    + exists q''. firstorder. \n  - intro H. firstorder.\nQed.\n\nLemma concat_delta_Q_star_correct4 B B' q q' w:  @delta_Q_star (concat B B') (inl q) w (inr q') <->   exists w' q'', delta_Q_star q w' q'' /\\ Q_acc q'' /\\ exists w'', w = w' ++ w'' /\\ delta_Q_star q0 w'' q' /\\ (w'' = nil -> q0 <> q').\nProof.\n  split; revert q; induction w; intro q; try congruence.\n  -intros [[q''|q''] [S H]].\n    + specialize (IHw q'' H). destruct IHw as [w' [q_m [S' [acc [w'' [E [D IHw]]]]]]]. exists (a::w'), q_m. repeat split.\n      * cbn. now exists q''.\n      * exact acc.             \n      * subst w. exists w''. tauto.\n     +  exists nil, q. cbn in S. dec; repeat split; try tauto.\n         exists (a::w). cbn. repeat split; try congruence.\n           exists q''. split.\n           *  exact S.\n           *  eapply concat_delta_Q_star_correct3. exact H.             \n - intros [w' [_ [_ [_ [w'' [E [D H]]]]]]]. symmetry in E. pose proof ( app_eq_nil _ _ E) as [E1 E2].  subst w'' w'.\n   cbn in *. exfalso; now apply H.                       \n - intros [w' [q'' [H [ acc [w'' [E [D S]]]]]]]. cbn. destruct w'.\n    + cbn in *. subst q'' w''. destruct D as [q'' [D H]]. exists (inr q''). split.\n       * now dec.\n       * now apply concat_delta_Q_star_correct3.\n    +  cbn in *. inv E. destruct H as [q1 [D' H]].  exists (inl q1).  eauto 10.      \nQed.\n \nLemma concat_correct  B B' w : n_accept (concat B B') w <-> exists w' w'', n_accept B w' /\\ n_accept B' w'' /\\ w = w' ++ w''.\nProof.\n  split.\n  - intros acc. destruct acc as [q [acc H]]. destruct q as [q |q].\n    + cbn in H. rewrite concat_delta_Q_star_correct2 in H. exists w, nil. rewrite app_nil_r. cbn in acc. dec; firstorder.\n    + cbn in H.  rewrite concat_delta_Q_star_correct4 in H.  firstorder.\n  -  intros [w' [w'' [[q1 [acc1 D1]] [[q2 [acc2 D2]] eqn]]]]. destruct w''.\n     +  rewrite app_nil_r in eqn.  subst w'. exists (inl q1). cbn. dec.\n      * now rewrite concat_delta_Q_star_correct2.\n      * cbn in D2. subst q2. tauto.\n     + subst w. exists (inr q2). split; auto. cbn. rewrite concat_delta_Q_star_correct4.\n       exists w', q1. firstorder. exists (e::w''). firstorder. congruence.        \nQed.\n(** * Kleene Operator *)\n\nDefinition kleene_acc_pred B := fun q => match q with\n                                      | None => True\n                                      | Some q => @Q_acc B q end.\n\nInstance kleene_acc_dec B (q: option B): dec (kleene_acc_pred q).\nProof.\n  unfold kleene_acc_pred. destruct q; auto.\nQed.\n\nDefinition kleene_acc_decPred B:= DecPred (@kleene_acc_pred B).\n\nDefinition kleene_delta B (q: option B) x q':= match q' with\n                                                            | Some q' => match q with\n                                                                        | None => delta_Q q0 x q'\n                                                                        | Some q => delta_Q q x q' \\/ (Q_acc q /\\ delta_Q q0 x q')\n                                                                        end\n                                                            | _ => False end.\nInstance kleene_delta_dec B (q q': option B) x : dec (kleene_delta q x q').                                                        Proof.\ndestruct q, q'; auto.                                                                                                                                     Qed.\n\nDefinition kleene_star B := NFA (None) (@kleene_acc_decPred B) (fun (q: option B) x => DecPred (fun q' => kleene_delta q x q')).\n\nLemma nil_kleene B : n_accept (kleene_star B) nil.\nProof.\n  unfold n_accept.  now exists q0.\nQed.\n\nLemma kleene_delta_ok1 B (q q': B) w: delta_Q_star q w q' -> @delta_Q_star (kleene_star B) (Some q) w (Some q').\nProof.\n  revert q. induction w; intros q H.\n  - cbn in *. congruence.\n  - cbn in *.  firstorder.\nQed.\n\nLemma kleene_delta_ok2 B q q' x w:\n  Q_acc q -> @delta_Q_star (kleene_star B) None (x::w) q' -> @delta_Q_star (kleene_star B) q (x::w) q'.\nProof.\n  intros acc H. cbn in *. unfold kleene_acc_pred in acc. destruct q.\n  - destruct H as [q'' [D H]]. exists q''. split.\n    + unfold kleene_delta. destruct q''.\n      * tauto.\n      * contradiction D.\n    + exact H.\n  - exact H.    \nQed.\n\nLemma kleene_delta_ok_3 B w:  n_accept B w -> n_accept (kleene_star B) w.\n  destruct w.\n  - intros _. apply nil_kleene.\n  -  intros [q [acc H]]. exists (Some q). split.\n     + exact acc.\n     + destruct H as [q' [H' H]]. exists (Some q'). split.\n       * exact H'.\n       * now apply kleene_delta_ok1.\nQed.\n\n\nLemma kleene_delta_ok_4 B x w q': @delta_Q_star B q0  (x:: w) q' -> @delta_Q_star (kleene_star B) q0 (x::w) (Some q').\nProof.    \n  cbn. intros [q [H S]]. exists (Some q). split.\n  + exact H.\n  + now apply kleene_delta_ok1.\nQed.\n\nLemma kleene_delta_ok_5 B a w:\n  n_accept B a -> n_accept (kleene_star B) w -> n_accept (kleene_star B) (a++ w).\nProof.\n\n    (* If there is a rest (w is not empty), then the last state is the last state after reading w, otherwise it is the last state after reading a. we need to know which one it is because we have to commit to a  final state now *)\n  destruct w.\n  - rewrite app_nil_r. intros H _. now apply kleene_delta_ok_3.\n  -  destruct a.\n     + now cbn.       \n     + intros [q' [acc' H]] [q [acc H1]]. exists q. split.\n       * exact acc.\n       * eapply delta_Q_star_trans. split.\n         {\n           apply kleene_delta_ok_4. exact H.\n         }\n         {\n           now apply kleene_delta_ok2.\n         }\nQed.\n\nLemma kleene_star_correct1 B w: (forall w', w' el w -> n_accept B w') -> n_accept (kleene_star B) (List.concat w).\nProof.\n  induction w.\n  - cbn. intros _. apply nil_kleene.\n  - intros H.\n    assert (forall w', w' el w -> n_accept B w') as ass by firstorder. specialize (IHw ass); clear ass.\n    cbn. apply kleene_delta_ok_5.\n    + now apply H.\n    + exact IHw.\nQed.\n           \nLemma kleene_delta_ok6  B (q:B) w (q':B) :\n  @delta_Q_star (kleene_star B) (Some q) w (Some q') -> @delta_Q_star B q w q' \\/ exists w' w'' q'', w = w' ++ w'' /\\ Q_acc q'' /\\ @delta_Q_star B q w' q'' /\\ @delta_Q_star (kleene_star B) None w'' (Some q').\nProof.\n  revert q. induction w; intros q H.\n  - left. cbn in H. now inv H.\n  - destruct H as [q_m [H D]]. destruct q_m; try contradiction H. specialize (IHw _ D). destruct H as [H |acc H].\n    + destruct IHw as [IHw | [w' [w'' [q'' [E [acc IHw]]]]]]. \n      *  firstorder.        \n      *  right. exists (a::w'), w''. subst w. exists q''.  firstorder.\n    + right. exists nil, (a::w), q. cbn. firstorder.      \nQed.\n\nLemma kleene_delta_ok7 B q  w :\n  @delta_Q_star (kleene_star B) q w None <-> q= None /\\ w = nil.\nProof.\n  split.\n  - revert q. induction w; intros q H.\n    + cbn in H. now subst q.\n    + cbn in H. destruct H as [q' [D H]]. specialize (IHw _ H). destruct IHw as [E E']. subst q' w.\n      contradiction D.\n  - intros [E E']. now subst q w.\nQed.\n\n(* w must not be empty because kleene_star B accepts nil no matter what B does. *)\nLemma kleene_delta_ok8 B x w:\n  n_accept (kleene_star B) (x::w) -> n_accept B (x::w) \\/ exists w' w'', w = w' ++ w'' /\\ n_accept B (x::w') /\\ n_accept (kleene_star B) w''.\nProof.\n  intros [q  [acc [q' [H S]]]]. cbn in *. destruct q, q'.\n  - pose proof (kleene_delta_ok6 S) as [H'|H']; clear S.\n    + left. exists e. firstorder.\n    + right. destruct H' as [w' [w'' [q [E [acc' [S S']]]]]]. exists w', w''. firstorder.\n  - contradiction H.\n  - rewrite kleene_delta_ok7 in S. destruct S as [S _]. discriminate S.\n  - contradiction H.\nQed.\n\nLemma kleene_star_correct2 B w :\n  n_accept (kleene_star B) w -> exists w', List.concat w' = w /\\  (forall w'', w'' el w' -> n_accept B w'').\nProof.\n   intros H. induction w using (@size_induction _ (@length Sig)). destruct w.\n-  exists nil. firstorder.\n- destruct (kleene_delta_ok8 H) as [H' | H']; clear H.\n  + exists [(e::w)]. cbn. rewrite app_nil_r. split.\n    * reflexivity.\n    * now intros w' [[]|  []].\n  + destruct H' as [w' [w'' [E [acc1 acc2]]]].\n    assert (|w''| < | e::w|) as L.\n    {\n      subst w. cbn. rewrite app_length. omega. \n    }\n    specialize (H0 w'' L acc2); clear L. destruct H0 as [w1 [E' H]]. exists ((e::w')::w1). split.\n    * cbn. rewrite E'. now subst w.\n    * intros w2 [[]|H']; auto.\nQed.      \n \nLemma kleene_star_correct B w:  n_accept (kleene_star B) w <-> exists w', List.concat w' = w /\\  (forall w'', w'' el w' -> n_accept B w'').\nProof.\n  split.\n  - apply kleene_star_correct2.\n  - intros [w' [[] H]]. now apply kleene_star_correct1.\nQed.\n    \nEnd DFA.\n\n\n\n\n\n      \n    \n        \n                                                             \n", "meta": {"author": "uds-psl", "repo": "base-library", "sha": "d9f3b8abf379d4c12049dd25c8d1fdf1973dab48", "save_path": "github-repos/coq/uds-psl-base-library", "path": "github-repos/coq/uds-psl-base-library/base-library-d9f3b8abf379d4c12049dd25c8d1fdf1973dab48/FiniteTypes/Automata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7180543964708603}}
{"text": "(*\n    Exercise 1.\n*)\n\n(*a*)\nTheorem taut1: (True \\/ False) /\\ (False \\/ True).\n    split. left. constructor. right. constructor.\nQed.\n\n(*b*)\nTheorem taut2: forall P: Prop, P -> ~~P.\n    intros. unfold not. intro. destruct H0. assumption.\nQed.\n\n(*c*)\nTheorem taut3: forall P Q R,\n    P /\\ (Q \\/ R) -> (P /\\ Q) \\/ (P /\\ R).\n    intros.\n    destruct H. (* Split P /\\ (Q \\/ R) into P and Q \\/ R *)\n    destruct H0. (* Split Q \\/ R into Q and R *)\n    left. split. assumption. assumption. (* Prove the P /\\ Q case *)\n    right. split. assumption. assumption. (* Prove the P /\\ R case *)\nQed.", "meta": {"author": "awh44", "repo": "CoqExercises", "sha": "26899115fb86e36621e7954f2918d934ff3f8c64", "save_path": "github-repos/coq/awh44-CoqExercises", "path": "github-repos/coq/awh44-CoqExercises/CoqExercises-26899115fb86e36621e7954f2918d934ff3f8c64/src/inductive_predicates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7180543944938768}}
{"text": "Require Export XR_R.\nRequire Export XR_Rle.\nRequire Export XR_total_order_T.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rlt_le_dec : forall r1 r2, {r1 < r2} + {r2 <= r1}.\nProof.\n  intros x y.\n  destruct (total_order_T x y) as [ [ hxy | heq ] | hyx ].\n  {\n    left.\n    exact hxy.\n  }\n  {\n    subst y.\n    right.\n    unfold \"<=\".\n    right.\n    reflexivity.\n  }\n  {\n    right.\n    unfold \"<=\".\n    left.\n    exact hyx.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rlt_le_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7180543944938768}}
{"text": "(** * SetInterface.v : An abstract interface for sets\n   and an implementation using lists *)\n\nSet Implicit Arguments.\n\nRequire Export BoolEquality.\nRequire Export List.\n\n\n(** Abstract interface for sets of elements of a type equipped \n    with boolean equality *)\nModule Type SET.\n\n Declare Module E : EQDEC.\n Export E.\n\n Parameter t : Type. \n\n (** Boolean equality *)\n Parameter eqb : t -> t -> bool.\n Definition eq : t -> t -> Prop := eqb.\n\n (** The empty set *)\n Parameter empty : t.\n\n (** [mem x s] tests whether [x] belongs to the set [s] *) \n Parameter mem : E.t -> t -> bool.\n\n (** [add x s] returns a set containing all elements of [s], plus [x]. \n     If [x] was already in [s], [s] is returned unchanged. *)\n Parameter add : E.t -> t -> t.\n\n (** [singleton x] returns the one-element set containing only [x] *)\n Parameter singleton : E.t -> t.\n\n (** [remove x s] returns a set containing all elements of [s], except [x]. \n     If [x] was not in [s], [s] is returned unchanged *)\n Parameter remove : E.t -> t -> t.\n\n (** Set union *)\n Parameter union : t -> t -> t.\n\n (** Set intersection *)\n Parameter inter : t -> t -> t.\n\n (** Set difference *)\n Parameter diff : t -> t -> t.\n\n (** [subset s1 s2] tests whether the set [s1] is a subset of the set [s2] *)\n Parameter subsetb : t -> t -> bool.\n Definition subset: t -> t -> Prop := subsetb.\n\n (** Lists the elements of the set in some unspecified order *)\n Parameter elements : t -> list E.t.\n\n (** [fold f s] a computes (f xN ... (f x2 (f x1 a))...), \n     where [x1 ... xN] is the result of [elements s] *)\n Parameter fold : forall A : Type, (E.t -> A -> A) -> t -> A -> A.\n\n Parameter filter : (E.t -> bool) -> t -> t.\n\n Parameter forallb : (E.t -> bool) -> t -> bool.\n\n Notation \"s [=] t\" := (eq s t) (at level 70, no associativity).\n Notation \"s [<=] t\" := (subset s t) (at level 70, no associativity).\n Notation \"s '[=?]' t\" := (eqb s t) (at level 70, no associativity).\n Notation \"s '[<=?]' t\" := (subsetb s t) (at level 70, no associativity).\n\n Definition disjoint s1 s2 := eqb (inter s1 s2) empty.\n \n Hint Unfold disjoint.\n\n\n (** * Specification *)\n \n (** Specification of [subset] *)\n Parameter subset_correct : forall s1 s2, \n  s1 [<=] s2 -> (forall x, mem x s1 -> mem x s2).\n\n Parameter subset_complete : forall s1 s2, \n  (forall x, mem x s1 -> mem x s2) -> s1 [<=] s2.\n\n (** Specification of [eq] *)\n Parameter eq_correct_l : forall s1 s2,\n  s1 [=] s2 -> s1 [<=] s2.\n \n Parameter eq_correct_r : forall s1 s2,\n  s1 [=] s2 -> s2 [<=] s1.\n\n Parameter eq_complete : forall s1 s2,\n  s1 [<=] s2 -> s2 [<=] s1 -> s1 [=] s2.\n\n\n (** Specification of [empty] *)\n Parameter empty_spec : forall x, ~mem x empty.\n\n\n (** Specification of [mem] *)\n Parameter mem_correct : forall x y s,\n  E.eq x y -> mem x s -> mem y s.\n\n \n (** Specification of [add] *)\n Parameter add_correct : forall x y s,\n  E.eq x y -> mem y (add x s).\n \n Parameter add_complete : forall x y s,\n  mem y s -> mem y (add x s).\n\n Parameter add_inversion : forall x y s,\n  ~E.eq x y -> mem y (add x s) -> mem y s.\n\n\n (** Specification of [singleton] *)\n Parameter singleton_correct : forall x y,\n  E.eq x y -> mem y (singleton x).\n\n Parameter singleton_complete : forall x y,\n  mem y (singleton x) -> E.eq x y.\n\n\n (** Specification of [remove] *)\n Parameter remove_correct : forall x y s,\n  E.eq x y -> ~mem x (remove y s).\n\n Parameter remove_complete : forall x y s,\n  ~E.eq x y -> mem y s -> mem y (remove x s).\n\n Parameter remove_inversion : forall x y s,\n  mem y (remove x s) -> mem y s.\n\n\n (** Specification of [union] *)\n Parameter union_correct : forall s1 s2 x,\n  mem x (union s1 s2) -> (mem x s1 \\/ mem x s2).\n\n Parameter union_complete_l : forall s1 s2 x, \n  mem x s1 -> mem x (union s1 s2).\n\n Parameter union_complete_r : forall s1 s2 x, \n  mem x s2 -> mem x (union s1 s2).\n\n\n (** Specification of [inter] *)\n Parameter inter_correct_l : forall s1 s2 x,\n  mem x (inter s1 s2) -> mem x s1.\n\n Parameter inter_correct_r : forall s1 s2 x,\n  mem x (inter s1 s2) -> mem x s2.\n\n Parameter inter_complete : forall s1 s2 x,\n  mem x s1 -> mem x s2 -> mem x (inter s1 s2).\n\n\n (** Specification of [diff] *)\n Parameter diff_correct_l : forall s1 s2 x, \n  mem x (diff s1 s2) -> mem x s1.\n\n Parameter diff_correct_r : forall s1 s2 x, \n  mem x (diff s1 s2) -> ~mem x s2.\n\n Parameter diff_complete : forall s1 s2 x, \n  mem x s1 -> ~mem x s2 -> mem x (diff s1 s2).\n\n\n (** Specification of [fold] *)\n Parameter fold_spec : forall A (f:E.t -> A -> A) i s,\n  fold f s i = fold_left (fun a x => f x a) (elements s) i.\n\n (* Alternatively,\n Parameter fold_spec : forall A (f:E.t -> A -> A) i s,\n  fold f s i = fold_right f i (elements s). *)\n\n (** Specification of [forallb] *)\n Parameter forallb_correct : forall f, (forall x y, E.eq x y -> f x = f y) ->\n   forall s, forallb f s -> forall x, mem x s -> f x.\n \n Parameter forallb_complete : forall (f:E.t->bool),\n   (forall x y, E.eq x y -> f x = f y) ->\n   forall s, (forall x, mem x s -> f x) -> forallb f s.\n\n (** Specification of [elements] *)\n Parameter elements_correct : forall s x, \n  mem x s -> InA E.eq x (elements s).\n\n Parameter elements_complete : forall s x, \n  InA E.eq x (elements s) -> mem x s.\n\n (** Specification of filter *)\n Parameter filter_correct : forall (f:E.t->bool) x s,\n  (forall x y, E.eq x y -> f x = f y) -> mem x (filter f s) -> mem x s /\\ f x.\n \n Parameter filter_complete : forall (f:E.t->bool) x s,\n  (forall x y, E.eq x y -> f x = f y) ->\n  mem x s -> f x -> mem x (filter f s).\n\nEnd SET.\n\n\n(** Functor extending [SET] *)\nModule MkSet_Theory (S:SET).\n\n Export S.\n\n Module ET := MkEqDec_Theory E.\n\n\n Lemma subset_iff : forall s1 s2, \n  s1 [<=] s2 <-> (forall x, mem x s1 -> mem x s2).\n Proof.\n  split; [apply subset_correct | apply subset_complete].\n Qed.\n\n Lemma subset_refl : forall s, s [<=] s.\n Proof.\n  auto using subset_complete.\n Qed.\n\n Lemma subset_trans : forall s s0 s1, \n  s [<=] s0 -> s0 [<=] s1 -> s [<=] s1.\n Proof.\n  intros s s0 s1; repeat rewrite subset_iff; firstorder.\n Qed.\n\n Add Relation t subset \n   reflexivity proved by subset_refl\n   transitivity proved by subset_trans\n   as subset_relation.\n \n Lemma eq_refl : forall s, s [=] s. \n Proof. \n  auto using subset_refl, eq_complete.\n Qed.\n\n Lemma eq_sym : forall s1 s2, \n  s1 [=] s2 -> s2 [=] s1.\n Proof.\n  intros; apply eq_complete.\n  apply eq_correct_r; trivial.\n  apply eq_correct_l; trivial.\n Qed.\n\n Lemma eq_trans : forall s1 s2 s3,\n  s1 [=] s2 -> s2 [=] s3 -> s1 [=] s3.\n Proof.\n  intros; apply eq_complete.\n  apply subset_trans with s2; apply eq_correct_l; trivial.\n  apply subset_trans with s2; apply eq_correct_r; trivial.\n Qed.\n \n Add Relation t eq \n  reflexivity proved by eq_refl\n  symmetry proved by eq_sym\n  transitivity proved by eq_trans as eq_setoid.\n\n Add Morphism eqb \n  with signature eq ==> eq ==> (@Logic.eq bool)\n  as eqb_morphism.\n Proof.\n  intros s1 s2 H s3 s4 H0.\n  case_eq (s1 [=?] s3); intros.\n  change (s1 [=] s3) in H1.\n  symmetry; change (s2 [=] s4).\n  transitivity s1.\n  symmetry; trivial.\n  transitivity s3; auto.\n  case_eq (s2 [=?] s4); auto; intros.\n  rewrite <- H1; change (s2 [=] s4) in H2.\n  change (s1 [=] s3).\n  transitivity s2; auto.\n  transitivity s4; auto.\n  symmetry; trivial.\n Qed.\n  \n Add Morphism subsetb \n  with signature eq ==> eq ==> (@Logic.eq bool) \n  as subsetb_morphism.\n Proof. \n  intros s1 s2 H s3 s4 H0.\n  case_eq (s1 [<=?] s3); case_eq (s2 [<=?] s4); intros; trivial.\n\n  assert (L:=eq_correct_r H); assert (R:=eq_correct_l H0).\n  elim H1.\n  symmetry; apply fold_is_true.\n  eapply subset_trans; eauto.\n  eapply subset_trans; eauto.\n  trivialb.\n\n  assert (L:=eq_correct_r H0); assert (R:=eq_correct_l H).\n  elim H2.\n  apply fold_is_true.\n  eapply subset_trans; eauto.\n  eapply subset_trans; eauto.\n Qed.\n\n Add Morphism subset \n  with signature eq ==> eq ==> iff\n  as subset_morphism.\n Proof. \n  intros; unfold subset.\n  rewrite iff_eq.\n  apply subsetb_morphism; trivial.\n Qed.\n\n Lemma eq_spec : forall s1 s2, \n  s1 [=] s2 <-> (s1 [<=] s2 /\\ s2 [<=] s1).\n Proof.\n  split; intros.\n  auto using eq_correct_l, eq_correct_r.\n  apply eq_complete; autob.\n Qed.\n\n Lemma eqb_eq : forall s1 s2,\n  eqb s1 s2 -> s1 [=] s2.\n Proof.\n  trivial.\n Qed.\n\n Add Morphism mem \n  with signature E.eq ==> eq ==> (@Logic.eq bool)\n  as mem_morphism.\n Proof.\n  intros x y H s1 s2 H0.\n  destruct (eq_spec s1 s2).\n  destruct (H1 H0); clear H0 H1 H2.\n  rewrite <- iff_eq.\n  split; eauto using mem_correct, subset_correct.\n Qed.  \n\n Lemma mem_diff : forall s x y, ~mem x s -> mem y s -> ~E.eq x y.\n Proof.\n  intros s x y H H0.\n  case (ET.eq_dec x y); intro; trivial.\n  rewrite e in H; trivialb.\n Qed.\n\n Lemma mem_dec : forall x s, {mem x s} + {~mem x s}.\n Proof.\n  intros x s; case_eq (mem x s); intro; [left | right]; trivialb.\n Qed.\n\n  \n Add Morphism add \n  with signature E.eq ==> eq ==> eq\n  as add_morphism.  \n Proof.\n  intros x y H s1 s2 H0. \n  apply eq_complete; apply subset_complete; intros.\n  case (ET.eq_dec x0 y); intro.\n  apply add_correct; auto.\n  apply add_complete.\n  rewrite <- H0; rewrite <- H in n.\n  apply add_inversion with x; auto. \n  case (ET.eq_dec x0 x); intro.\n  apply add_correct; auto.\n  apply add_complete.\n  rewrite H0; rewrite H in n.\n  apply add_inversion with y; auto.\n Qed.\n \n Lemma add_spec : forall a s x, \n  mem x (add a s) <-> (E.eq a x \\/ mem x s).\n Proof. \n  split; intros.\n  case (ET.eq_dec a x); intro.\n  left; trivial.\n  right; apply (add_inversion n H).\n  destruct H; [apply add_correct | apply add_complete]; trivial.\n Qed.\n\n Lemma subset_empty : forall s, empty [<=] s.\n Proof.\n  intros; apply subset_complete.\n  intros; elim (empty_spec H). \n Qed.\n\n Lemma subset_add : forall a s, s [<=] (add a s).\n Proof.\n  intros; apply subset_complete. \n  intros; apply add_complete; auto.\n Qed.\n\n Lemma add_idem : forall x s,\n  mem x s -> (add x s) [=] s.\n Proof.\n  intros x s H; apply eq_complete.\n  apply subset_complete; intros y Hy.\n  case (ET.eq_dec x y); intro.\n  rewrite <- e; trivial.\n  apply add_inversion with x; trivial.\n  apply subset_add.\n Qed.\n\n Add Morphism singleton \n  with signature E.eq ==> eq \n  as singleton_morphism.\n Proof.\n  intros.\n  unfold eq; apply eq_complete; apply subset_complete; intros.\n  apply singleton_correct.\n  rewrite <- H.\n  apply singleton_complete; trivial.\n  apply singleton_correct.\n  rewrite H.\n  apply singleton_complete; trivial.\n Qed.\n\n Lemma singleton_mem_diff : forall x y, \n  ~E.eq x y -> ~mem y (singleton x).\n Proof.\n  intros x y H; case_eq (mem y (singleton x)); intros; autob.\n  elim H; apply singleton_complete; trivialb.\n Qed.\n\n Lemma mem_singleton_diff : forall x y, \n  ~mem y (singleton x) -> ~E.eq x y.\n Proof.\n  intros x y H H0. \n  rewrite H0 in H.\n  elim H; apply singleton_correct; trivial.\n Qed.\n\n Add Morphism remove \n  with signature E.eq ==> eq ==> eq \n  as remove_morphism.\n Proof.\n  intros x y H s1 s2 H0.\n  apply eq_complete; apply subset_complete; intros.\n  apply remove_complete.\n  rewrite <- H.\n  intro H2; elim (remove_correct (E.eq_sym H2) H1).\n  rewrite <- H0; apply remove_inversion with x; trivial.\n  apply remove_complete.\n  rewrite H.\n  intro H2; elim (remove_correct (E.eq_sym H2) H1).\n  rewrite H0; apply remove_inversion with y; trivial.\n Qed.\n\n Lemma remove_spec : forall x y s, \n  mem y (remove x s) <-> (mem y s /\\ ~E.eq x y).\n Proof. \n  repeat split; intros.\n  apply remove_inversion with x; trivial.\n  intro H0; elim (remove_correct (E.eq_sym H0) H).\n  apply remove_complete; destruct H; auto.\n Qed.\n\n Lemma subset_remove : forall x s, (remove x s) [<=] s.\n Proof.\n  intros; apply subset_complete; intros.\n  apply remove_inversion with x; trivial.\n Qed.\n\n Lemma remove_idem : forall x s,\n  ~mem x s -> (remove x s) [=] s.\n Proof.\n  intros x s H; apply eq_complete.\n  apply subset_remove.\n  apply subset_complete; intros y Hy.\n  case (ET.eq_dec x y); intro e.\n  rewrite e in H; trivialb.\n  apply remove_complete; trivial.\n Qed.\n\n Add Morphism union \n  with signature eq ==> eq ==> eq \n  as union_morphism.\n Proof.\n  intros; apply eq_complete; apply subset_complete; intros. \n  destruct (union_correct H1).\n  apply union_complete_l; rewrite <- H; trivial.\n  apply union_complete_r; rewrite <- H0; trivial.\n  destruct (union_correct H1).\n  apply union_complete_l; rewrite H; trivial.\n  apply union_complete_r; rewrite H0; trivial.\n Qed.\n\n Lemma union_spec : forall s1 s2 x, \n  mem x (union s1 s2) <-> (mem x s1 \\/ mem x s2).\n Proof. \n  split. \n  apply union_correct.\n  destruct 1; auto using union_complete_l, union_complete_r.\n Qed.\n\n Lemma union_sym : forall s1 s2, union s1 s2 [=] union s2 s1.\n Proof.\n  intros; rewrite eq_spec; split; apply subset_complete; intros x H;\n   rewrite union_spec in *; destruct H; auto.\n Qed.\n\n Lemma union_empty : forall s, union empty s [=] s.\n Proof.\n  intros; apply eq_complete; apply subset_complete; intros.\n  destruct (union_correct H); trivial.\n  elim (empty_spec H0).\n  apply union_complete_r; trivial.\n Qed.\n \n Lemma subset_union_l : forall s1 s2, s1 [<=] (union s1 s2).\n Proof.\n  intros; apply subset_complete; intros.\n  apply union_complete_l; auto.\n Qed.\n\n Lemma subset_union_r : forall s1 s2, s2 [<=] (union s1 s2).\n Proof.\n  intros; apply subset_complete; intros.\n  apply union_complete_r; auto.\n Qed.\n\n Lemma union_assoc : forall s1 s2 s3, union (union s1 s2) s3 [=] union s1 (union s2 s3).\n Proof.\n  intros; rewrite eq_spec; split; apply subset_complete; intro x;\n  repeat rewrite union_spec; tauto.\n Qed.\n\n Lemma subset_union : forall s1 s2, s1 [<=] s2 -> union s1 s2 [=] s2.\n Proof.\n  intros s1 s2; rewrite eq_spec; repeat rewrite subset_iff;\n  split; intros; rewrite union_spec in *; intuition.\n Qed.\n\n Lemma union_idem : forall s, union s s [=] s.\n Proof.\n  intros; apply eq_complete; rewrite subset_iff; intros;\n  rewrite union_spec in *; intuition.\n Qed.\n\n Lemma subset_union_ctxt : forall s1 s1' s2 s2', \n   s1 [<=] s1' -> s2 [<=] s2' -> union s1 s2 [<=] union s1' s2'.\n Proof.\n  intros s1 s1' s2 s2'; repeat rewrite subset_iff; intros.\n  rewrite union_spec in *; intuition.\n Qed.\n\n Lemma union_subset : forall s1 s2 s3,\n  s1 [<=] s3 ->\n  s2 [<=] s3 ->\n  union s1 s2 [<=] s3.   \n Proof.\n  intros; rewrite <- (union_idem s3).\n  apply subset_union_ctxt; trivial.\n Qed.\n\n Add Morphism inter \n  with signature eq ==> eq ==> eq\n  as inter_morphism.\n Proof.\n  intros s1 s2 H s3 s4 H0.\n  apply eq_complete; apply subset_complete; intros. \n  apply inter_complete.\n  rewrite <- H; apply inter_correct_l with s3; trivial.\n  rewrite <- H0; apply inter_correct_r with s1; trivial.\n  apply inter_complete.\n  rewrite H; apply inter_correct_l with s4; trivial.\n  rewrite H0; apply inter_correct_r with s2; trivial.\n Qed.\n\n Lemma inter_spec : forall s1 s2 x,\n  mem x (inter s1 s2) <-> (mem x s1 /\\ mem x s2).\n Proof. \n  repeat split; intros.\n  apply inter_correct_l with s2; trivial.\n  apply inter_correct_r with s1; trivial.\n  apply inter_complete; autob.\n Qed.\n \n Lemma inter_sym : forall s1 s2, inter s1 s2 [=] inter s2 s1.\n Proof.\n  intros s1 s2; apply eq_complete; apply subset_complete; \n   eauto using inter_complete, inter_correct_l, inter_correct_r.\n Qed.\n\n Lemma subset_inter_l : forall s1 s2, (inter s1 s2) [<=] s1.\n Proof.\n  intros; apply subset_complete; intros.\n  apply inter_correct_l with s2; trivial.\n Qed.\n\n Lemma subset_inter_r : forall s1 s2, (inter s1 s2) [<=] s2.\n Proof.\n  intros; apply subset_complete; intros.\n  apply inter_correct_r with s1; trivial.\n Qed.\n\n Lemma subset_inter : forall s1 s2, \n  s1 [<=] s2 -> inter s1 s2 [=] s1.\n Proof.\n  intros.\n  apply eq_complete; apply subset_complete; intros.\n  eauto using inter_correct_l.\n  eauto using inter_complete, subset_correct.\n Qed.\n\n Lemma inter_idem : forall s, inter s s [=] s.\n Proof.\n  intros; rewrite subset_inter.  \n  apply eq_refl.\n  apply subset_refl.\n Qed.\n \t \n Add Morphism diff \n  with signature eq ==> eq ==> eq\n  as diff_morphism.\n Proof.\n  intros s1 s2 H s3 s4 H0.\n  apply eq_complete; apply subset_complete; intros. \n  apply diff_complete.\n  rewrite <- H; apply diff_correct_l with s3; trivial.\n  rewrite <- H0; apply diff_correct_r with s1; trivial.\n  apply diff_complete.\n  rewrite H; apply diff_correct_l with s4; trivial.\n  rewrite H0; apply diff_correct_r with s2; trivial.\n Qed.\n\n Lemma diff_spec : forall s1 s2 x, \n  mem x (diff s1 s2) <-> (mem x s1 /\\ ~mem x s2).\n Proof. \n  repeat split; intros.\n  apply diff_correct_l with s2; trivial. \n  apply diff_correct_r with s1; trivial.\n  apply diff_complete; autob.\n Qed.\n\n Lemma subset_diff : forall s1 s2, (diff s1 s2) [<=] s1. \n Proof.\n  intros; apply subset_complete; intros.\n  apply diff_correct_l with s2; trivial.\n Qed.\n\n Lemma remove_diff : forall x s, \n  remove x s [=] diff s (singleton x).\n Proof.\n  intros; rewrite eq_spec; split; apply subset_complete; intros.\n  apply diff_complete.\n  eauto using remove_inversion.\n  intro H0.\n  assert (W:=singleton_complete H0).\n  exact (remove_correct (E.eq_sym W) H).\n  eauto using remove_complete, mem_singleton_diff, diff_correct_r, \n   diff_correct_l.\n Qed.\n\n Lemma union_diff_assoc : forall s1 s2 s3, union (diff s1 s3) (diff s2 s3) [=] diff (union s1 s2) s3.\n Proof.\n   intros; rewrite eq_spec; split; apply subset_complete; intros;\n   repeat (rewrite union_spec in * ||  rewrite diff_spec in * ); tauto.\n Qed.\n\n Lemma union_diff : forall s1 s2, union (diff s1 s2) s2 [=] union s1 s2.\n Proof.\n  intros; rewrite eq_spec; split; apply subset_complete; intros;\n   repeat (rewrite union_spec in * ||  rewrite diff_spec in * ); intuition.\n  destruct (mem x s2); auto.\n  left; split; auto.\n  intros; autob.\n Qed.\n\n (* To declare [elements] and [fold] as morphisms it is necessary to declare \n    equality on lists up to permutation as a relation first (as done in the \n    Coq standard library)*) \n\n Lemma elements_empty : elements empty = nil.\n Proof.\n  generalize (@elements_complete empty).\n  destruct (elements empty); trivial.\n  intros; assert (mem t0 empty) by auto.\n  elim (empty_spec H0).\n Qed.\n\n Lemma mem_fold_add_inversion : forall l s x, \n  mem x (fold_left (fun s y => add y s) l s) ->\n  InA E.eq x l \\/ mem x s.\n Proof.\n  induction l; simpl; intros.\n  auto.\n  case (ET.eq_dec a x); intro.\n  auto.\n  assert (InA E.eq x l \\/ mem x (add a s)).\n  apply IHl; trivial.\n  destruct H0; auto.\n  right; apply (add_inversion n H0).\n Qed.  \n\n Lemma mem_fold_add_r : forall l s x, \n  mem x s -> mem x (fold_left (fun s y => add y s) l s).\n Proof.\n  induction l; simpl; intros.\n  trivial.\n  auto using add_complete.\n Qed.  \n\n Lemma mem_fold_add_l : forall s1 s2 x, \n  mem x s1 -> mem x (fold add s1 s2).\n Proof.\n  intros s1 s2 x H; rewrite fold_spec; generalize s2; clear s2.\n  assert (W:=elements_correct H).\n  induction (elements s1); intros; simpl; inversion_clear W.\n  auto using mem_fold_add_r, add_correct.\n  auto.\n Qed.\n\n Lemma union_fold : forall s1 s2,\n  union s1 s2 [=] fold add s1 s2.\n Proof.\n  intros; apply eq_complete; apply subset_complete; intros.\n  destruct (union_correct H).\n  auto using mem_fold_add_l.\n  rewrite fold_spec; auto using mem_fold_add_r.\n  rewrite fold_spec in H.\n  destruct (mem_fold_add_inversion _ _ H);\n   auto using union_complete_l, union_complete_r, elements_complete.\n Qed.  \n\n Lemma diff_le_compat : forall s1 s2 s1' s2',\n     s1 [<=] s1' -> s2' [<=] s2 ->\n     diff s1 s2 [<=] diff s1' s2'.\n Proof.\n  intros s1 s2 s1' s2'; repeat rewrite subset_iff; intros H H0 x;\n  repeat rewrite diff_spec; intuition.\n Qed.\n\n Hint Resolve subset_complete eq_correct_l eq_correct_r\n  eq_complete add_correct add_complete\n  singleton_correct singleton_complete remove_correct remove_complete\n  union_complete_l union_complete_r inter_correct_l inter_correct_r \n  diff_correct_l diff_correct_r elements_correct\n  subset_refl subset_trans eq_refl eq_trans\n  subset_empty singleton_mem_diff mem_singleton_diff diff_le_compat: set.\n \n Hint Immediate subset_correct eq_complete mem_correct\n  empty_spec union_correct inter_complete diff_complete \n  elements_complete eq_sym subset_empty subset_add subset_remove \n  subset_union_l subset_union_r subset_inter_l subset_inter_r \n  subset_diff remove_diff : set.\n\n Lemma empty_union : forall s1 s2,\n   union s1 s2 [=] empty ->\n   s1 [=] empty /\\ s2 [=] empty.\n Proof.\n  intros; apply eq_spec in H; destruct H.\n  split; apply eq_spec; split; auto with set;\n  eapply subset_trans; eauto; auto with set.\n Qed.\n\n Lemma inter_remove_comm : forall x s1 s2, \n  inter (remove x s1) s2 [=] remove x (inter s1 s2).\n Proof.\n  intros; apply eq_complete; apply subset_complete; intro;\n   rewrite remove_spec; repeat rewrite inter_spec; \n   try rewrite remove_spec; tauto.\n Qed.\n  \n Lemma add_remove : forall x s, add x (remove x s) [=] add x s.\n Proof.\n  intros; apply eq_complete; apply subset_complete; intro;\n   repeat rewrite add_spec; rewrite remove_spec; try tauto.\n  assert (W:=E.eqb_spec x x0); destruct (E.eqb x x0); tauto.\n Qed.\n\n Lemma add_union_comm : forall x s1 s2, \n  add x (union s1 s2) [=] union (add x s1) s2.\n Proof.\n   intros; apply eq_complete; apply subset_complete; intro;\n    repeat (rewrite union_spec || rewrite add_spec); tauto.\n Qed.\n\n Lemma add_union_swap : forall x s1 s2, \n  union (add x s1) s2 [=] union s1 (add x s2).\n Proof.\n  intros x s1 s2; rewrite (union_sym s1); repeat rewrite <- add_union_comm;\n   rewrite union_sym; apply eq_refl.\n Qed.\n\n Lemma inter_union_comm : forall s1 s2 s3, \n  inter s1 (union s2 s3) [=] union (inter s1 s2) (inter s1 s3).\n Proof.\n  intros; apply eq_complete; apply subset_complete; intro;\n   repeat (rewrite union_spec || rewrite inter_spec); tauto.\n Qed.\n\n Lemma union_inter_comm : forall s1 s2 s3,\n  union (inter s1 s2) s3 [=] \n  inter (union s1 s3) (union s2 s3).\n Proof.\n  intros; apply eq_complete; apply subset_complete; intro;\n   repeat (rewrite union_spec || rewrite inter_spec); tauto.\n Qed.\n\n Lemma empty_dec : forall s, s[=] empty \\/ exists x, mem x s.\n Proof.\n  intros s; case_eq (elements s); intros.\n  left; apply eq_complete; auto with set.\n  apply subset_complete; intros.\n  assert (U:=elements_correct H0); rewrite H in U; inversion U.\n  right; exists t0; apply elements_complete. \n  rewrite H; constructor; trivial. \n Qed.\n\n Lemma subset_remove_ctxt : forall x s1 s2, \n  s1 [<=] s2 -> remove x s1 [<=] remove x s2.\n Proof.\n  intros x s1 s2; repeat rewrite subset_iff; intros.\n  rewrite remove_spec in *; intuition.\n Qed.\n\n Lemma subset_inter_ctxt : forall s1 s1' s2 s2', \n   s1 [<=] s1' -> s2 [<=] s2' -> inter s1 s2 [<=] inter s1' s2'.\n Proof.\n  intros s1 s1' s2 s2'; repeat rewrite subset_iff; intros.\n  rewrite inter_spec in *; intuition.\n Qed.\n\n Lemma subset_add_ctxt : forall x s1 s2,\n   s1 [<=] s2 -> (add x s1) [<=] (add x s2).\n Proof.\n  intros x s1 s2; repeat rewrite subset_iff; intros.\n  rewrite add_spec in *; intuition.\n Qed.\n\n Lemma disjoint_sym : forall s1 s2, disjoint s1 s2 -> disjoint s2 s1.\n Proof.\n  unfold disjoint; intros; rewrite inter_sym; trivial.\n Qed.\n\n Lemma disjoint_subset_l : forall X Y Z,\n  X [<=] Y ->\n  disjoint Y Z ->\n  disjoint X Z.\n Proof.\n  unfold disjoint; intros X Y Z Hsub Heq.\n  apply eq_complete; auto with set.\n  change (inter Y Z [=] empty) in Heq.\n  rewrite <- Heq.\n  apply subset_inter_ctxt; auto with set.\n Qed.\n \n Lemma disjoint_mem_not_mem : forall s1 s2,\n  disjoint s1 s2 -> forall x, mem x s1 -> ~mem x s2.\n Proof.\n  unfold disjoint; intros s1 s2 H x H1 H2.\n  assert (mem x (inter s1 s2)) by auto using inter_complete.\n  change (inter s1 s2 [=] empty) in H.\n  rewrite H in H0; elim (empty_spec H0).\n Qed.\n\n Lemma disjoint_complete : forall X1 X2, \n      (forall x, mem x X1 -> ~mem x X2) -> disjoint X1 X2.\n Proof.\n  unfold disjoint; intros.\n  change ((inter X1 X2) [=] empty).\n  apply eq_complete; apply subset_complete; intros.\n  rewrite inter_spec in H0; destruct H0.\n  elim (H _ H0 H1).\n  elim (empty_spec H0).\n Qed.\n\n Lemma filter_union : forall s f,\n  (forall x y, E.eq x y -> f x = f y) ->\n  s [=] union (filter f s) (filter (fun x => negb (f x)) s).\n Proof.\n  intros s f Hf.\n  assert (Hnf: forall x y, E.eq x y -> negb (f x) = negb (f y)) by\n   (intros y z Heq; rewrite (Hf _ _ Heq); trivial).\n  \n  apply eq_complete.\n  apply subset_complete; intros x Hx.\n  case_eq (f x); intro H.\n  apply union_complete_l; apply filter_complete; trivial.\n  apply union_complete_r; apply filter_complete; trivialb.\n\n  apply subset_complete; intros x Hx.\n  destruct (union_correct Hx). \n  destruct (filter_correct Hf H); trivial.\n  destruct (filter_correct Hnf H); trivial.\n Qed.\n\n Lemma filter_subset : forall s f,\n  (forall x y, E.eq x y -> f x = f y) ->\n  (filter f s) [<=] s.\n Proof.\n  intros s f Hf; apply subset_complete; intros x Hx.\n  generalize (filter_correct Hf Hx); intuition.\n Qed.\n\nEnd MkSet_Theory.\n\n\n(** A concrete implementation of [SET] using lists *)\nModule MkListSet (X:EQDEC) <: SET.\n\n Module E := X.\n Module ET := MkEqDec_Theory X.\n\n Definition t := list X.t.\n\n Definition empty : t := nil.\n\n Definition singleton (x:X.t) : t := x::nil.\n\n Fixpoint mem (x:X.t) (s:t) {struct s} : bool :=\n  match s with\n   | nil => false\n   | y :: s' => if X.eqb x y then true else mem x s'\n  end.\n \n Fixpoint add (x:X.t) (s:t) {struct s} : t :=\n  match s with\n   | nil => x::nil\n   | y :: s' => if X.eqb x y then y :: s' else y :: add x s'\n  end.\n \n Fixpoint remove (x:X.t) (s:t) {struct s} : t :=\n  match s with\n   | nil => nil\n   | y::s' => if X.eqb x y then remove x s' else y::remove x s'\n  end.\n\n Fixpoint inter (s1 s2:t) {struct s1} : t :=\n  match s1 with\n   | nil => nil\n   | y :: s1' => if mem y s2 then y :: inter s1' s2 else inter s1' s2\n  end.\n\n Fixpoint union (s1 s2:t) {struct s1} : t :=\n  match s1 with\n   | nil => s2\n   | y :: s1' =>  union s1' (add y s2)\n  end.\n\n Fixpoint diff (s1 s2:t) {struct s2} : t :=\n  match s2 with\n   | nil => s1\n   | x :: s2' => remove x (diff s1 s2')\n  end.\n\n Fixpoint subsetb (s1 s2:t) {struct s1} : bool :=\n  match s1 with\n   | nil => true\n   | x :: s1' => if mem x s2 then subsetb s1' s2 else false\n  end.\n\n Definition filter : (E.t -> bool) -> t -> t := @List.filter E.t.\n\n Definition eqb (s1 s2:t) : bool :=\n  if subsetb s1 s2 then subsetb s2 s1 else false.\n\n\n Definition subset : t -> t -> Prop := subsetb.\n\n Definition eq : t -> t -> Prop := eqb.\n\n Definition elements (s:t) : list E.t := s.\n\n Definition fold (A:Type) (f:X.t -> A -> A) (s:t) (i:A) := \n  fold_left (fun a x => f x a) s i. \n\n Definition forallb (f:X.t ->bool) := \n  Eval cbv beta delta [List.forallb andb ifb] in List.forallb f.\n\n Notation \"s [=] t\" := (eq s t) (at level 70, no associativity).\n Notation \"s [<=] t\" := (subset s t) (at level 70, no associativity).\n Notation \"s '[=?]' t\" := (eqb s t) (at level 70, no associativity).\n Notation \"s '[<=?]' t\" := (subsetb s t) (at level 70, no associativity).\n\n Definition disjoint s1 s2 := eqb (inter s1 s2) empty.\n\n\n (** * Specification *)\n\n (** Specification of [mem] *)\n Lemma mem_correct : forall x y s,\n  X.eq x y -> mem x s -> mem y s.\n Proof.\n  induction s; trivial. \n  simpl; intros.\n  case (ET.eq_dec x a); intro.\n  assert (X.eqb y a) by eauto.\n  trivialb.\n\n  rewrite H in n.\n  assert (~X.eqb x a) by eauto.\n  rewrite ET.neq_neqb in n.\n  autob.\n Qed.\n\n\n (** Specification of [subset] *)\n Lemma subset_correct : forall s1 s2, \n  s1 [<=] s2 -> (forall x, mem x s1 -> mem x s2).\n Proof.\n  unfold subset; induction s1; simpl; intros; autob.\n  case_eq (mem a s2); intro.\n  case_eq (X.eqb x a); intro.\n  apply mem_correct with a; auto. \n  rewrite H1 in H; rewrite H2 in H0; autob.\n  rewrite H1 in H; trivialb.\n Qed.\n\n Lemma subset_complete : forall s1 s2, \n  (forall x, mem x s1 -> mem x s2) -> s1 [<=] s2.\n Proof.\n  unfold subset; induction s1; simpl; intros; autob.\n  assert (W:=H a).\n  assert (X.eqb a a) by auto.\n  simplb.\n  apply IHs1; intros.\n  apply H; intros.\n  case (X.eqb x a); trivialb.\n Qed.  \n\n\n (** Specification of [eqb] *)\n Lemma eq_correct_l : forall s1 s2,\n  s1 [=] s2 -> s1 [<=] s2.\n Proof.\n  intros s1 s2; unfold eq, eqb, subset.\n  case (s1 [<=?] s2); trivial.\n Qed.\n \n Lemma eq_correct_r : forall s1 s2,\n  s1 [=] s2 -> s2 [<=] s1.\n Proof.\n  intros s1 s2; unfold eq, eqb, subset.\n  case (s2 [<=?] s1); case (s1 [<=?] s2); trivial.\n Qed.\n\n Lemma eq_complete : forall s1 s2,\n  s1 [<=] s2 -> s2 [<=] s1 -> s1 [=] s2.\n Proof.\n  unfold eq, eqb, subset; intros; trivialb.\n Qed.\n\n\n (** Specification of [empty] *)\n Lemma empty_spec : forall x, ~mem x empty.\n Proof.\n  intros x; unfold empty; trivialb.\n Qed.\n\n \n (** Specification of [add] *)\n Lemma add_correct : forall x y s,\n  X.eq x y -> mem y (add x s).\n Proof.\n  induction s; simpl; intros.\n  assert (X.eqb y x) by auto; trivialb.\n\n  case (ET.eq_dec x a); intro.\n  assert (X.eqb x a) by auto; assert (X.eqb y a) by eauto; trivialb; simpl; \n   trivialb.\n  assert (~X.eqb y a) by eauto; rewrite ET.eq_eqb in n.\n  rewrite (if_notb n); simpl.\n  rewrite (if_notb H0); auto.\n Qed.\n  \n \n Lemma add_complete : forall x y s,\n  mem y s -> mem y (add x s).\n Proof.\n  induction s; simpl; intros.\n  trivialb.\n  case (X.eqb x a); simpl; destruct (X.eqb y a); autob.\n Qed.\n\n Lemma add_inversion : forall x y s,\n  ~X.eq x y -> mem y (add x s) -> mem y s.\n Proof.\n  induction s; simpl; intros.\n  assert (~X.eqb y x) by auto.\n  rewrite (if_notb H1) in H0; trivialb.\n  destruct (X.eqb x a); simpl in H0; destruct (X.eqb y a); autob.\n Qed.\n\n\n (** Specification of [singleton] *)\n Lemma singleton_correct : forall x y,\n  X.eq x y -> mem y (singleton x).\n Proof.\n  intros; simpl.\n  assert (X.eqb y x) by auto; trivialb.\n Qed.\n\n Lemma singleton_complete : forall x y,\n  mem y (singleton x) -> X.eq x y.\n Proof.\n  simpl; intros.\n  symmetry.\n  apply ET.eq_eqb_r; destruct (X.eqb y x); trivial.\n Qed.\n\n\n (** Specification of [remove] *)\n Lemma remove_correct : forall x y s,\n  X.eq x y -> ~mem x (remove y s).\n Proof.\n  induction s; intros.\n  trivialb.\n  simpl; case (ET.eq_dec y a); intro.\n  assert (X.eqb y a) by auto.\n  autob.\n  assert (~X.eq x a) by eauto.\n  rewrite ET.eq_eqb in n; rewrite ET.eq_eqb in H0.\n  rewrite (if_notb n); simpl.\n  rewrite (if_notb H0); auto.\n Qed.\n\n Lemma remove_complete : forall x y s,\n  ~X.eq x y -> mem y s -> mem y (remove x s).\n Proof.\n  induction s; intros.\n  trivial.\n  simpl in H0 |- *.   \n  case (ET.eq_dec x a); intro.  \n  assert (~X.eqb y a) by eauto.\n  assert (X.eqb x a) by auto.\n  autob.\n\n  assert (~X.eqb x a) by auto.\n  simplb; destruct (X.eqb y a); auto.\n Qed.\n\n Lemma remove_inversion : forall x y s,\n  mem y (remove x s) -> mem y s.\n Proof.\n  induction s; intros.\n  trivial.\n  simpl in H |- *.\n  case (ET.eq_dec y a); intro.\n  assert (X.eqb y a) by auto.\n  trivialb.\n\n  assert (~X.eqb y a) by auto.\n  simplb.\n  case (ET.eq_dec x a); intro.\n  assert (X.eqb x a) by auto.\n  trivialb.\n\n  assert (~X.eqb x a) by auto.\n  simplb; simpl in H; trivialb.\n Qed.\n  \n\n (** Specification of [union] *)\n Lemma union_correct : forall s1 s2 x,\n  mem x (union s1 s2) -> (mem x s1 \\/ mem x s2).\n Proof.\n  induction s1; simpl; intros; auto.\n  destruct (IHs1 (add a s2) x H).\n  left; rewrite H0; destruct (X.eqb x a); trivial.\n  case (ET.eq_dec a x); intro.\n  assert (X.eqb x a) by auto; autob.\n  right; apply add_inversion with a; trivial.\n Qed.\n\n Lemma union_complete : forall s1 s2 x, \n  mem x s1 \\/ mem x s2 -> mem x (union s1 s2).\n Proof.\n  induction s1; simpl; intros s2 x H.\n  destruct H; autob.\n\n  apply IHs1; simpl.\n  case (ET.eq_dec x a); intro.\n  assert (X.eqb x a) by auto. \n  right; auto using add_correct.\n \n  destruct H; auto using add_complete.\n  assert (~X.eqb x a) by auto; trivialb.\n  auto.\n Qed.\n\n Lemma union_complete_l : forall s1 s2 x, \n  mem x s1 -> mem x (union s1 s2).\n Proof.\n  auto using union_complete.\n Qed.\n\n Lemma union_complete_r : forall s1 s2 x, \n  mem x s2 -> mem x (union s1 s2).\n Proof.\n  auto using union_complete.\n Qed.\n\n\n (** Specification of [inter] *)\n Lemma inter_correct_l : forall s1 s2 x,\n  mem x (inter s1 s2) -> mem x s1.\n Proof.\n  induction s1; intros.\n  trivial.\n\n  simpl in *.\n  case_eq (X.eqb x a); intro; trivial.\n  case_eq (mem a s2); intro; simplb.\n  simpl in H; eautob.\n  eauto.\n Qed.  \n  \n Lemma inter_correct_r : forall s1 s2 x,\n  mem x (inter s1 s2) -> mem x s2.\n Proof.\n  induction s1; simpl; intros.\n  trivialb.\n  case_eq (mem a s2); intro; simplb; simpl in H.\n  case (ET.eq_dec x a); intro.\n  apply mem_correct with a; auto.\n  assert (~X.eqb x a) by auto; simplb; auto.\n  auto.\n Qed.\n\n Lemma inter_complete : forall s1 s2 x,\n  mem x s1 -> mem x s2 -> mem x (inter s1 s2).\n Proof.\n  induction s1; simpl; intros.\n  trivialb.\n\n  case_eq (X.eqb x a); intro.\n  case_eq (mem a s2); intro; trivialb.\n  assert (~mem a s2) by autob.\n  assert (X.eq x a) by auto.\n  elim H; eauto using mem_correct.\n\n  case (mem a s2); autob.\n Qed.\n\n\n (** Specification of [diff] *)\n Lemma diff_correct_l : forall s1 s2 x, \n  mem x (diff s1 s2) -> mem x s1.\n Proof.\n  induction s2; simpl; intros.\n  trivial.\n  eauto using remove_inversion.\n Qed.\n\n Lemma diff_correct_r : forall s1 s2 x, \n  mem x (diff s1 s2) -> ~mem x s2.\n Proof.\n  induction s2; simpl; intros.\n  trivialb.\n\n  case (ET.eq_dec x a); intro; simplb.\n  assert (X.eqb x a) by auto; simplb.\n  elim (remove_correct (diff s1 s2) e); auto.\n  assert (~X.eqb x a) by auto; simplb.\n  eauto using remove_inversion.\n Qed.\n\n Lemma diff_complete : forall s1 s2 x, \n  mem x s1 -> ~mem x s2 -> mem x (diff s1 s2).\n Proof.\n  induction s2; simpl; intros.\n  trivial.\n  case (ET.eq_dec x a); intro.\n  assert (X.eqb x a) by auto; trivialb.\n  assert (~X.eqb x a) by auto; simplb.\n  apply remove_complete; auto.\n Qed.  \n\n\n (** Specification of [fold] *)\n Lemma fold_spec : forall A (f:X.t -> A -> A) i s,\n  fold f s i = fold_left (fun x a => f a x) (elements s) i.\n Proof.\n  trivial.\n Qed.\n\n (* Alternatively,\n Parameter fold_spec : forall A (f:E.t -> A -> A) i s,\n  fold f s i = fold_right f i (elements s). *)\n\n\n (** Specification of [elements] *)\n Lemma elements_correct : forall s x, \n  mem x s -> InA X.eq x (elements s).\n Proof.\n  induction s; unfold elements; simpl; intros.\n  trivialb.  \n  case (ET.eq_dec x a); intro.\n  constructor; trivial.\n  rewrite ET.eq_eqb in n; simplb.\n  constructor 2; auto.\n Qed.\n\n Lemma elements_complete : forall s x, \n  InA X.eq x (elements s) -> mem x s.\n Proof.\n  induction s; unfold elements; simpl; intros.\n  inversion H.  \n  inversion H.\n  rewrite ET.eq_eqb in H1; trivialb.\n  destruct (X.eqb x a); auto.\n Qed.\n\n Lemma filter_correct : forall (f:E.t->bool) x s, \n  (forall x y, E.eq x y -> f x = f y) -> mem x (filter f s) -> mem x s /\\ f x.\n Proof.\n  intros.\n  assert (W:=elements_correct _ _ H0).\n  rewrite InA_spec in W; destruct W as (y,(W1,W2)).\n  unfold filter, elements in W2; rewrite filter_In in W2.\n  destruct W2; rewrite (H _ _ W1); split; trivial.\n  apply elements_complete.\n  rewrite InA_spec.\n  exists y; auto.\n Qed.\n\n Lemma filter_complete : forall (f:E.t -> bool) x s, \n  (forall x y, E.eq x y -> f x = f y) ->\n  mem x s -> f x -> mem x (filter f s).\n Proof.\n  intros.\n  assert (W:=elements_correct _ _ H0).\n  rewrite InA_spec in W; destruct W as (y, (W1,W2)).\n  assert (In y s /\\ f y).\n  rewrite <- (H _ _ W1); auto.\n  unfold filter, is_true in H2; rewrite <- filter_In in H2.\n  apply elements_complete.\n  rewrite InA_spec; exists y; auto.\n Qed.\n\n Lemma forallb_correct : forall f, (forall x y, X.eq x y -> f x = f y) ->\n  forall s, forallb f s -> forall x, mem x s -> f x.\n Proof.\n  induction s; simpl; intros; autob.\n  assert (W:= X.eqb_spec x a); destruct (X.eqb x a).\n  rewrite (H x a W).\n  destruct (f a); trivialb.\n  destruct (f a); trivialb; auto.\n Qed. \n\n Lemma forallb_complete : forall (f:E.t -> bool), \n  (forall x y, X.eq x y -> f x = f y) ->\n  forall s, (forall x, mem x s -> f x) -> forallb f s.\n Proof.\n  induction s; simpl; intros; auto.\n  assert (W:= H0 a).\n  assert (Heq:= X.eqb_spec a a); destruct (X.eqb a a).\n  rewrite W; auto. \n  apply IHs; intros; apply H0.\n  destruct (X.eqb x a); auto.\n  elim Heq; apply X.eq_refl.\n Qed.\n\nEnd MkListSet.\n", "meta": {"author": "initc3", "repo": "certipriv", "sha": "95e089a46715ebb5931eb54e0828dd20e70dcd58", "save_path": "github-repos/coq/initc3-certipriv", "path": "github-repos/coq/initc3-certipriv/certipriv-95e089a46715ebb5931eb54e0828dd20e70dcd58/Lib/SetInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7180543944938768}}
{"text": "(* From coq-projects/circuits/ *)\nRequire Import Bool.\nRequire Import Nat.\nRequire Import Arith.\nRequire Import Lia.\n\nDefinition half_adder_sum (b1 : bool) (b2: bool) : bool:=\nmatch b1, b2 with\n| true, true => false\n| true, false => true\n| false, true => true\n| false, false => false\nend.\n\nDefinition half_adder_carry (b1 : bool) (b2: bool) : bool:= \nmatch b1 with\n| true => b2\n| false => false\nend.\n\n\nDefinition bool_to_nat (b : bool) :=\n  match b with\n  | true => 1\n  | false => 0\n  end.\n\nLemma half_adder_sum_sym:\n  forall a b: bool, half_adder_sum a b = half_adder_sum b a.\nProof.\n  induction a; induction b; auto.\nQed.\n\nLemma half_adder_carry_sym:\n  forall a b: bool, half_adder_carry a b = half_adder_carry b a.\nProof.\nsimple  induction a; induction b; auto.\nQed.\n\nLemma half_adder_sum_false : forall a : bool, half_adder_sum a false = a.\nProof.\nsimple induction a; auto.\nQed.\n\nLemma half_adder_carry_false :\n forall a : bool, half_adder_carry a false = false.\nProof.\n simple induction a; auto.\nQed.\n\nLemma half_adder_sum_true : forall a : bool, half_adder_sum a true = negb a.\nProof.\nauto.\nQed.\n\nLemma half_adder_carry_true : forall a : bool, half_adder_carry a true = a.\nProof.\nsimple induction a; auto.\nQed.\n\nTheorem half_adder_ok :\n forall a b : bool,\n bool_to_nat (half_adder_sum a b) +\n (bool_to_nat (half_adder_carry a b) + bool_to_nat (half_adder_carry a b)) =\n bool_to_nat a + bool_to_nat b.\nProof.\nsimple induction a; simple induction b; auto.\nQed.\n\n\nDefinition full_adder_sum (a b c : bool) :=\n  match true with\n  | true => half_adder_sum (half_adder_sum a b) c\n  | false => false\n  end.\n\nDefinition full_adder_carry (a b c : bool) :=\n  match half_adder_carry a b with\n  | true => true\n  | false => half_adder_carry (half_adder_sum a b) c\n  end.\n\nLemma full_adder_sum_sym1 :\n forall a b c : bool, full_adder_sum a b c = full_adder_sum b a c.\nProof.\nsimple induction a; simple induction b; auto.\nQed.\n\nLemma full_adder_sum_sym2 :\n forall a b c : bool, full_adder_sum a b c = full_adder_sum a c b.\nProof.\nsimple induction b.\nsimple induction c.\nauto.\nunfold full_adder_sum in |- *.\nrewrite half_adder_sum_false.\nrewrite half_adder_sum_false.\nauto.\nunfold full_adder_sum in |- *. intro.\nrewrite half_adder_sum_false.\nrewrite half_adder_sum_false.\nauto.\nQed.\n\nLemma full_adder_sum_false :\n forall a : bool, full_adder_sum a false false = a.\nProof.\n simple induction a; auto.\nQed.\n\nLemma full_adder_sum_true : forall a : bool, full_adder_sum a true true = a.\nProof.\nsimple induction a; auto.\nQed.\n\nLemma full_adder_carry_sym1 :\n forall a b c : bool, full_adder_carry a b c = full_adder_carry b a c.\nProof.\nsimple induction a; simple induction b; auto.\nQed.\n\nLemma full_adder_carry_sym2 :\n forall a b c : bool, full_adder_carry a b c = full_adder_carry a c b.\nProof.\nsimple induction b.\nsimple induction c.\nauto.\nunfold full_adder_carry in |- *.\nrewrite half_adder_sum_false.\nrewrite half_adder_carry_false.\nrewrite half_adder_carry_false.\nsimpl in |- *.\nelim (half_adder_carry a true); auto.\nintros.\nunfold full_adder_carry in |- *.\nrewrite half_adder_carry_false.\nrewrite half_adder_sum_false.\nrewrite half_adder_carry_false.\nsimpl in |- *.\nelim (half_adder_carry a c); auto.\nQed.\n\nLemma full_adder_carry_false :\n forall a : bool, full_adder_carry a false false = false.\nProof.\nsimple induction a; auto.\nQed.\n\nLemma full_adder_carry_true :\n forall a : bool, full_adder_carry a true true = true.\nProof.\nsimple induction a.\nunfold full_adder_carry in |- *.\nauto.\nunfold full_adder_carry in |- *.\nauto.\nQed.\n\nLemma full_adder_carry_true_false :\n forall a : bool, full_adder_carry a true false = a.\nProof.\nsimple induction a; auto.\nQed.\n\nLemma full_adder_carry_neg :\n forall a b : bool, full_adder_carry a (negb a) b = b.\nProof.\nsimple induction a; simple induction b; simpl in |- *.\nrewrite full_adder_carry_sym1. \nrewrite full_adder_carry_true. trivial.\nrewrite full_adder_carry_false. trivial.\nrewrite full_adder_carry_true. trivial.\nrewrite full_adder_carry_sym1. \nrewrite full_adder_carry_false. trivial.\nQed.\n\n(****************************************************************)\n\nTheorem full_adder_ok :\n forall a b c : bool,\n bool_to_nat (full_adder_sum a b c) +\n (bool_to_nat (full_adder_carry a b c) + bool_to_nat (full_adder_carry a b c)) =\n bool_to_nat a + bool_to_nat b + bool_to_nat c.\nProof.\nsimple induction a; simple induction b; simple induction c; auto.\nQed.\n\nLemma plus_permute2 : forall x y z : nat, x + y + z = x + z + y.\nProof.\nintros.\nrewrite (plus_comm x y).\nrewrite (plus_comm x z).\nrewrite plus_comm.\nsymmetry  in |- *.\nrewrite plus_comm.\nrewrite plus_permute.\nauto with arith.\nQed.\n\nInductive boolList : Type :=\n| Nil : boolList\n| Cons : bool -> boolList -> boolList.\n\n(* Infix \"::\" := Cons (at level 60, right associativity). *)\n\nDefinition length : boolList -> nat :=\n  fix length l :=\n  match l with\n   | Nil => O\n   | Cons _ l' => S (length l')\n  end.\n\nDefinition app : boolList -> boolList -> boolList :=\n  fix app l m :=\n  match l with\n   | Nil => m\n   | Cons a l1 => Cons a (app l1 m)\n  end.\n\n(* Infix \"++\" := app (right associativity, at level 60). *)\n\nLemma app_eq2 : forall (x : bool) (l l' : boolList), app (Cons x l) l' = Cons x  (app l l').\nProof.\nauto. \nQed.\n\nLemma length_eq2 :\n forall (x : bool) (l : boolList), length (Cons x l) = S (length l).\n Proof.\n auto with arith. Qed.\n\n Fixpoint bV_full_adder_sum_nil (l0: boolList) (b0: bool): boolList :=\n  match l0 with\n  | Nil => Nil\n  | Cons b l1 => Cons (half_adder_sum b b0)\n                      (bV_full_adder_sum_nil l1 (half_adder_carry b b0))\n  end.\n\nFixpoint bV_full_adder_sum (l m: boolList) (bb: bool): boolList :=\n  match l with\n  | Nil => bV_full_adder_sum_nil m bb\n  | Cons b l0 =>\n    match m with\n    | Nil =>\n      Cons (half_adder_sum b bb) (bV_full_adder_sum l0 Nil (half_adder_carry b bb))\n    | Cons b0 l1 =>\n      Cons (full_adder_sum b b0 bb)\n           (bV_full_adder_sum l0 l1 (full_adder_carry b b0 bb))\n    end\n  end.\n\n\nLemma BV_full_adder_sum_eq1 :\n forall b : bool, bV_full_adder_sum Nil Nil b = Nil.\nProof.\n auto.\nQed.\n\nLemma BV_full_adder_sum_eq2 :\n forall (vh : bool) (vt : boolList) (b : bool),\n bV_full_adder_sum Nil (Cons vh vt) b =\n Cons (half_adder_sum vh b)\n   (bV_full_adder_sum Nil vt (half_adder_carry vh b)).\nProof.\n auto.\nQed.\n\nLemma BV_full_adder_sum_eq3 :\n forall (vh : bool) (vt : boolList) (b : bool),\n bV_full_adder_sum (Cons vh vt) Nil b =\n Cons (half_adder_sum vh b)\n   (bV_full_adder_sum vt Nil (half_adder_carry vh b)).\nProof.\n auto.\nQed.\n\nLemma BV_full_adder_sum_eq4 :\n forall (vh : bool) (vt : boolList) (wh : bool) (wt : boolList) (b : bool),\n bV_full_adder_sum (Cons vh vt) (Cons wh wt) b =\n Cons (full_adder_sum vh wh b)\n   (bV_full_adder_sum vt wt (full_adder_carry vh wh b)).\nProof.\n auto.\nQed.\n\n\nFixpoint bV_full_adder_carry_nil (l0: boolList) (bb: bool): bool :=\n  match l0 with\n  | Nil => bb\n  | Cons b l1 => bV_full_adder_carry_nil l1 (half_adder_carry b bb)\n  end.\n\nFixpoint bV_full_adder_carry (l m: boolList) (bb: bool) :=\n  match l with\n  | Nil => bV_full_adder_carry_nil m bb\n  | Cons b l0 =>\n    match m with\n    | Nil => bV_full_adder_carry l0 Nil (half_adder_carry b bb)\n    | Cons b0 l1 => bV_full_adder_carry l0 l1 (full_adder_carry b b0 bb)\n    end\n  end.\n\n\nLemma BV_full_adder_carry_eq1 :\n forall b : bool, bV_full_adder_carry Nil Nil b = b.\nProof.\n auto.\nQed.\n\nLemma BV_full_adder_carry_eq2 :\n forall (vh : bool) (vt : boolList) (b : bool),\n bV_full_adder_carry Nil (Cons vh vt) b =\n bV_full_adder_carry Nil vt (half_adder_carry vh b).\nProof.\n auto.\nQed.\n\n\nLemma BV_full_adder_carry_eq3 :\n forall (vh : bool) (vt : boolList) (b : bool),\n bV_full_adder_carry (Cons vh vt) Nil b =\n bV_full_adder_carry vt Nil (half_adder_carry vh b).\n\nProof.\n auto.\nQed.\n\nLemma BV_full_adder_carry_eq4 :\n forall (vh : bool) (vt : boolList) (wh : bool) (wt : boolList) (b : bool),\n bV_full_adder_carry (Cons vh vt) (Cons wh wt) b =\n bV_full_adder_carry vt wt (full_adder_carry vh wh b).\n\nProof.\n auto.\nQed.\n\n\nDefinition bV_full_adder (v w : boolList) (cin : bool) : boolList :=\n  match true with\n  |true => \n  app (bV_full_adder_sum v w cin)\n    (Cons (bV_full_adder_carry v w cin) Nil)\n  | false => Nil\n  end.\n\n(****************************************************************)\n\nLemma BV_full_adder_sum_v_nil_false :\n forall v : boolList, bV_full_adder_sum v Nil false = v.\nProof.\nsimple induction v. trivial. intros.\nrewrite BV_full_adder_sum_eq3. \nrewrite half_adder_carry_false.\nrewrite half_adder_sum_false. \nrewrite H; auto.\nQed.\n\nLemma BV_full_adder_carry_v_nil_false :\n forall v : boolList, bV_full_adder_carry v Nil false = false.\nProof.\nsimple induction v. trivial. intros.\nrewrite BV_full_adder_carry_eq3. \nrewrite half_adder_carry_false.\ntrivial.\nQed.\n\nLemma BV_full_adder_sum_sym :\n forall (v w : boolList) (cin : bool),\n bV_full_adder_sum v w cin = bV_full_adder_sum w v cin.\nProof.\nsimple induction v. simple induction w. auto. intros.\nrewrite BV_full_adder_sum_eq2. \nrewrite BV_full_adder_sum_eq3.\nrewrite H. auto. simple induction w. intro.\nrewrite BV_full_adder_sum_eq2. \nrewrite BV_full_adder_sum_eq3. rewrite H.\nauto. intros. repeat rewrite BV_full_adder_sum_eq4. rewrite H.\ndo 2 rewrite full_adder_carry_sym1. \ndo 2 rewrite full_adder_sum_sym1. auto.\nQed.\n\nLemma length_BV_full_adder_sum :\n forall (v w : boolList) (cin : bool),\n length v = length w -> length (bV_full_adder_sum v w cin) = length v.\nProof.\nunfold length in |- *. simple induction v. simple induction w. intros. case cin. simpl in |- *. trivial.\nsimpl in |- *. trivial.\nintros. absurd (length (Nil:boolList) = length (Cons b b0)).\nsimpl in |- *. discriminate. exact H0. simple induction w. simpl in |- *. intros. discriminate H0.\nintros. simpl in |- *. rewrite H. trivial. generalize H1. simpl in |- *. auto.\nQed.\n\nLemma BV_full_adder_carry_sym :\n forall (v w : boolList) (cin : bool),\n bV_full_adder_carry v w cin = bV_full_adder_carry w v cin.\nProof.\nsimple induction v. simple induction w. auto. intros.\nrewrite BV_full_adder_carry_eq2. \nrewrite BV_full_adder_carry_eq3.\nrewrite H; auto. simple induction w. intros. \nrewrite BV_full_adder_carry_eq2.\nrewrite BV_full_adder_carry_eq3.\nrewrite H. auto. intros. \ndo 2 rewrite BV_full_adder_carry_eq4.\nrewrite H. rewrite full_adder_carry_sym1. auto.\nQed.\n\nLemma BV_full_adder_sym :\n forall (v w : boolList) (cin : bool),\n bV_full_adder v w cin = bV_full_adder w v cin.\nProof.\nunfold bV_full_adder in |- *.\nintros.\nrewrite BV_full_adder_sum_sym. \nrewrite BV_full_adder_carry_sym. auto.\nQed.\n\nFixpoint bV_to_nat (v : boolList) : nat :=\n  match v return nat with\n  | Nil => 0\n  | Cons b w => bool_to_nat b + (bV_to_nat w + bV_to_nat w)\n  end.\n\nFixpoint power2 (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S x => power2 x + power2 x\n  end.\n\nLemma BV_to_nat_app :\n forall (l n : boolList) (ll : nat),\n (******************)\n length l = ll -> bV_to_nat (app l n) = bV_to_nat l + power2 ll * bV_to_nat n.\nProof.\nsimple induction l. intros. inversion H. simpl in |- *. auto.\nintros. simpl.\ndestruct ll.\ninversion H0.\ninversion H0.\nrewrite (H n ll H2).\nrewrite <- (plus_assoc (bool_to_nat b) (bV_to_nat b0 + bV_to_nat b0)).\nf_equal.\nrewrite <- plus_assoc.\nrewrite <- (plus_assoc (bV_to_nat b0) (bV_to_nat b0)).\nf_equal.\nsimpl.\n\nrewrite mult_plus_distr_r. \nrepeat rewrite plus_assoc.\nsubst.\nrewrite <- plus_assoc.\nrewrite Nat.add_comm.\nreflexivity.\nQed.\n\nLemma BV_to_nat_app2 :\n forall l n : boolList,\n (*******************)\n bV_to_nat (app l n) = bV_to_nat l + power2 (length l) * bV_to_nat n.\nProof.\n intros. apply BV_to_nat_app. auto.\nQed.\n\nLemma BV_full_adder_nil_true_ok :\n forall v : boolList, bV_to_nat (bV_full_adder v Nil true) = S (bV_to_nat v).\nProof.\nsimple induction v; auto with arith. unfold bV_full_adder in |- *. intros.\nrewrite BV_full_adder_sum_eq3. \nrewrite BV_full_adder_carry_eq3.\nrewrite app_eq2. \nrewrite half_adder_carry_true.\nsimpl in |- *. elim b. rewrite H. simpl in |- *. auto with arith.\nrewrite BV_full_adder_sum_v_nil_false.\nrewrite BV_full_adder_carry_v_nil_false.\nrewrite BV_to_nat_app2.\nsimpl in |- *. elim mult_n_O. elim plus_n_O. trivial with arith.\nQed.\n\n\nLemma BV_full_adder_nil_ok :\n forall (v : boolList) (cin : bool),\n bV_to_nat (bV_full_adder v Nil cin) = bV_to_nat v + bool_to_nat cin.\n Proof.\nsimple induction v. simple induction cin; auto with arith.\nsimple induction cin. rewrite BV_full_adder_nil_true_ok. simpl in |- *. rewrite Nat.add_1_r. reflexivity.\nunfold bV_full_adder in |- *. rewrite BV_full_adder_sum_v_nil_false.\nrewrite BV_full_adder_carry_v_nil_false. \nrewrite BV_to_nat_app2.\nsimpl in |- *. elim mult_n_O. elim plus_n_O. trivial with arith.\nQed.\n\n(****************************************************************)\n\nTheorem BV_full_adder_ok :\n forall (v w : boolList) (cin : bool),\n bV_to_nat (bV_full_adder v w cin) =\n bV_to_nat v + bV_to_nat w + bool_to_nat cin.\nProof.\nsimple induction v.\nintros.\nrewrite BV_full_adder_sym.\nsimpl in |- *.\nrewrite BV_full_adder_nil_ok.\nauto with arith.\n\nunfold bV_full_adder in |- *.\nsimple induction w.\nrename b into a.\nrename b0 into l.\nsimpl in |- *.\nintro.\nrewrite H.\nsimpl in |- *.\nelim plus_n_O.\nelim plus_n_O.\nreplace\n (bV_to_nat l + bool_to_nat (half_adder_carry a cin) +\n  (bV_to_nat l + bool_to_nat (half_adder_carry a cin))) with\n (bool_to_nat (half_adder_carry a cin) + bool_to_nat (half_adder_carry a cin) +\n  (bV_to_nat l + bV_to_nat l)).\nrepeat rewrite plus_assoc.\nreplace\n (bool_to_nat (half_adder_sum a cin) + bool_to_nat (half_adder_carry a cin) +\n  bool_to_nat (half_adder_carry a cin)) with\n (bool_to_nat (half_adder_sum a cin) +\n  (bool_to_nat (half_adder_carry a cin) +\n   bool_to_nat (half_adder_carry a cin))).\nrewrite half_adder_ok.\nrewrite (plus_permute2 (bool_to_nat a) (bool_to_nat cin) (bV_to_nat l)).\nrewrite\n (plus_permute2 (bool_to_nat a + bV_to_nat l) (bool_to_nat cin) (bV_to_nat l))\n .\ntrivial with arith.\n\ntrivial with arith.\n\nrepeat rewrite plus_assoc.\nrewrite\n (plus_permute2 (bool_to_nat (half_adder_carry a cin))\n    (bool_to_nat (half_adder_carry a cin)) (bV_to_nat l))\n .\nrewrite (plus_comm (bool_to_nat (half_adder_carry a cin)) (bV_to_nat l)).\nrewrite\n (plus_permute2 (bV_to_nat l + bool_to_nat (half_adder_carry a cin))\n    (bool_to_nat (half_adder_carry a cin)) (bV_to_nat l))\n .\ntrivial with arith.\n\n rename b into a.\n rename b0 into l.\n intros a0 l0.\n intros.\nsimpl in |- *.\nrewrite H.\nclear H.\nelim cin; elim a.\nrewrite full_adder_carry_sym1.\nrewrite full_adder_carry_true.\nrewrite full_adder_sum_sym1.\nrewrite full_adder_sum_true.\nsimpl in |- *.\nrepeat rewrite plus_n_SO.\nelim plus_n_Sm.\nelim plus_n_Sm.\nsimpl in |- *.\nelim plus_n_Sm.\nrepeat rewrite plus_assoc.\nlia.\n(* rewrite *)\n(*  (plus_permute2 (bool_to_nat a0 + bV_to_nat l) (bV_to_nat l0) (bV_to_nat l)) *)\n(*  . *)\n(* rewrite (plus_comm (bool_to_nat a0) (bV_to_nat l)). *)\n(* rewrite (plus_permute2 (bV_to_nat l) (bool_to_nat a0) (bV_to_nat l)). *)\n(* trivial with arith. *)\n\nelim a0.\nsimpl in |- *.\nelim plus_n_Sm.\nsimpl in |- *.\nelim plus_n_O.\nelim plus_n_Sm.\nelim plus_n_Sm.\nelim plus_n_Sm.\nelim plus_n_O.\nrepeat rewrite plus_assoc.\nrewrite (plus_permute2 (bV_to_nat l) (bV_to_nat l0) (bV_to_nat l)).\ntrivial with arith.\n\nsimpl in |- *.\nrepeat rewrite <- plus_n_Sm.\nrepeat rewrite <- plus_n_O.\nrepeat rewrite plus_assoc.\ntry trivial with arith.\nrewrite (plus_permute2 (bV_to_nat l) (bV_to_nat l0) (bV_to_nat l)).\ntry trivial with arith.\n\nelim a0.\nsimpl in |- *.\nrepeat rewrite <- plus_n_Sm.\nrepeat rewrite <- plus_n_O.\nrepeat rewrite plus_assoc.\nsimpl in |- *.\nrewrite (plus_permute2 (bV_to_nat l) (bV_to_nat l0) (bV_to_nat l)).\ntrivial with arith.\n\nsimpl in |- *.\nrepeat rewrite <- plus_n_O.\nrepeat rewrite plus_assoc.\nrewrite (plus_permute2 (bV_to_nat l) (bV_to_nat l0) (bV_to_nat l)).\ntrivial with arith.\n\nelim a0; simpl in |- *; repeat rewrite <- plus_n_Sm;\n repeat rewrite <- plus_n_O; repeat rewrite plus_assoc;\n rewrite (plus_permute2 (bV_to_nat l) (bV_to_nat l0) (bV_to_nat l));\n trivial with arith.\n\nQed.", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/modifications/quickchick_fails/test246_fulladder/fulladder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7180543885629259}}
{"text": "Require Import List Arith Bool Decidable PeanoNat Coq.Arith.Peano_dec.\nImport ListNotations.\nRequire Extraction.\n\n(** * A. Reflet bool/Prop *)\n\nPrint eqb.\n\nLocate \"=?\".\n\nSearch((_ =? _ = false) -> ~(_ = _)).\nPrint beq_nat_false.\n\nSearch((_ =? _ = true) -> (_ = _)).\nPrint beq_nat_true.\n\n(** * B. Relations d'ordre *)\n\n(** * B.1 Supérieur ou égal dans Type *)\n\n(*\nn      m = n\n^       /\n|      /\n|     x \n|    /x\n|   / x   m >= n\n|  /  x\n| /   \n|-----------------------> m\n                          m >= S n \n------ [diagonale]        -------- [descenteVerticale]\nm >= m                    m >= n\n\n *)\n(* Sorte Type car utilisé dans des calculs. *)\n(* Paramétrisation par 'm : nat', indexation par un 'nat'. *)\nInductive SuperieurOuEgal(m : nat) : nat -> Prop :=\n| diagonale : SuperieurOuEgal m m\n| descenteVerticale : forall n, SuperieurOuEgal m (S n)  -> SuperieurOuEgal m n.\n\nProposition superieurOuEgal_Scroissante :\n  forall m n, SuperieurOuEgal m n -> SuperieurOuEgal (S m) (S n).\nProof.\nAdmitted.\n\nPrint le.\n(*\nInductive le (n : nat) : nat -> Prop :=\n    le_n : n <= n | le_S : forall m : nat, n <= m -> n <= S m.\nn\n^        m = n\n| m <= n /\n|   x   /\n|   x  /\n|   x / \n|   x/\n|   / \n|  /  \n| /   \n|-----------------------> m\n\n\n                          m <= n \n------ [diagonale]        -------- [montéeVerticale]\nm <= m                    m <= S n\n\n*)\n\nDefinition superieurOuEgal_adequation : forall m n, (SuperieurOuEgal m n) -> (n <= m).\nProof.\n  fix REC 3.\nAdmitted.\n  \nDefinition superieurOuEgal_completude : forall m n, m <= n -> (SuperieurOuEgal n m).\nProof.\n  fix REC 3.\nAdmitted.\n\n(** * B.2 Inférieur strict *)\nPrint lt.\n(*\nS n <= m\n--------\n  n <  m\n\n\nlt = fun n m : nat => S n <= m\n     : nat -> nat -> Prop\n*)\n\nLemma lt_inferieurStrict :\n  forall m n, m < n -> (m <= n) /\\ (m <> n).\nProof.\nAdmitted.\n\nLemma inferieurStrict_lt :\n  forall m n, ((m <= n) /\\ (m <> n)) -> (m < n).\nProof.\nAdmitted.\n\n(** * Division euclidienne *)\n\nFixpoint divisionEuclidienne(n d : nat) : nat * nat.\nProof.\n  case n as [ | pn].\nAdmitted.\n\nPrint divisionEuclidienne.\n\nExample divisionEuclidienne_13_5 : divisionEuclidienne 13 5 = (2, 3).\nAdmitted.\n\nExample divisionEuclidienne_14_5 : divisionEuclidienne 14 5 = (2, 4).\nAdmitted.\n\nExample divisionEuclidienne_15_5 : divisionEuclidienne 15 5 = (3, 0).\nAdmitted.\n\nExample divisionEuclidienne_13_0 : divisionEuclidienne 13 0 = (0, 13).\nAdmitted.\n\nDefinition quotient(n d : nat) : nat.\n  case (divisionEuclidienne n d) as [q _].\n  exact q.\nDefined.\n\nPrint quotient.\n\nDefinition reste(n d : nat) : nat.\nAdmitted.\n\nPrint reste.\n\nProposition divEuclidienne_decomposition :\n  forall n d, n = (quotient n d) * d + (reste n d).\nProof.\n  (* unfold quotient, reste.*)\n  fix HR 1.\n  (* Indication : utiiser ring.*)\nAdmitted.\n\nProposition divEuclidienne_resteDivParZero : forall n, (reste n 0 = n).\nProof.\nAdmitted.\n\nProposition divEuclidienne_quotientDivParZero : forall n, (quotient n 0 = 0).\nProof.\nAdmitted.\n\nProposition divEuclidienne_majorationReste :\n  forall n d, (0 < d) -> (reste n d) < d.\nProof.\nAdmitted.\n\nProposition divEuclidienne_caracterisation :\n  forall d, (0 < d) ->\n       forall n q r, (n = q * d + r) -> (r < d)\n                -> ((quotient n d = q) /\\ (reste n d = r)).\nProof.\n  (* compliqué ! *)\nAdmitted.\n\nProposition divEuclidienne_caracterisationReste :\n  forall d, (0 < d) ->\n       forall n q r, (n = q * d + r) -> (r < d)\n                -> (reste n d = r).\nProof.\nAdmitted.\n\nProposition reste_idempotence :\n  forall d n, reste (reste n d) d = reste n d.\nProof.\nAdmitted.\n \nProposition reste_preMorphismeAdditif :\n  forall d m n, reste (m + n) d = reste ((reste m d) + (reste n d)) d.\nProof.\nAdmitted.\n\nDefinition modulo_egalite(d m n: nat) : Prop.\n  exact (reste m d = reste n d).\nDefined.  \n\nProposition modulo_egalite_reflexivite : forall d n, modulo_egalite d n n.\nProof.\nAdmitted.\n\nProposition modulo_egalite_symetrie : forall d m n, modulo_egalite d m n -> modulo_egalite d n m.\nProof.\nAdmitted.\n\nProposition modulo_egalite_transitivite :\n  forall d n1 n2 m, modulo_egalite d n1 m -> modulo_egalite d m n2 -> modulo_egalite d n1 n2.\nProof.\nAdmitted.\n\nProposition modulo_egalite_compatibiliteAddition :\n  forall d, forall m1 n1 m2 n2,\n    modulo_egalite d m1 m2\n    -> modulo_egalite d n1 n2\n    -> modulo_egalite d (m1 + n1) (m2 + n2).\nProof.\nAdmitted.\n\n(** * Vers une représentation canonique ? question difficile.\n \nModulo d (pour représenter les classes de la relation modulo (S d)) : \n{(h : d, v : 0), ..., (h : 0, v : d)} formé de couples (h, v), avec  \nv la valeur et h le nombre de valeurs au-dessus. Invariant : h + v = d.\n\nConstruction en deux temps.\n\n1. ModuloBrut(d : nat) : nat -> Type - paramétrisation par 'd' et indexation par 'h'\n\n                          (ModuloBrut d (S h))\n-------------- [zeroMod]  -------------------- [succMod]\nModuloBrut d d              (ModuloBrut d h)\n\nInterprétation :\n- ModuloBrut d h est le type singleton {h, v}, avec h + v = d.\n\n2. Modulo (d : nat) : somme des singletons (ModuloBrut d h)\n\nModulo(d : nat) : Type.\n\n(h : nat) (ModuloBrut d h)\n-------------------------- [modulo]\n       Modulo d\n\n- Interprétation : Modulo d = {(d, 0), ..., (0, d)} - Nat modulo (S d)\n*)\n\nInductive ModuloBrut(d : nat) : nat -> Type :=\n| mb_zero : ModuloBrut d d\n| mb_succ : forall h, ModuloBrut d (S h) -> ModuloBrut d h.\n\nFixpoint moduloBrut_valeur(d h : nat)(mb : ModuloBrut d h) : nat.\nProof.\n  case mb as [ | h pmb].\n  - exact 0.\n  - exact (S (moduloBrut_valeur _ _ pmb)).\nDefined.\n\nProposition moduloBrut_majoration :\n  forall (d h : nat)(mb : ModuloBrut d h), SuperieurOuEgal d h.\nProof.\n  fix HR 3.\nAdmitted.\n\nProposition moduloBrut_invariant :\n  forall d h, forall (mb : ModuloBrut d h),\n    (moduloBrut_valeur d h mb) + h = d. \nProof.\nAdmitted.\n\nInductive Modulo(d : nat) : Type :=\n| modulo : forall h, ModuloBrut d h -> Modulo d.\n\nDefinition modulo_valeur(d : nat)(m : Modulo d) : nat.\nProof.\n  case m as [h mb].\n  exact (moduloBrut_valeur _ _ mb).\nDefined.\n\nDefinition modulo_hauteur(d : nat)(m : Modulo d) : nat.\nProof.\n  case m as [h mb].\n  exact h.\nDefined.\n\nProposition modulo_invariant :\n  forall d, forall (m : Modulo d),\n    (modulo_valeur d m) + (modulo_hauteur d m) = d. \nProof.\nAdmitted.\n\n(* Modulo d : algèbre sur la signature (0, S). *)\n\nDefinition modulo_zero(d : nat) : Modulo d := modulo _ _ (mb_zero d).\n\nDefinition modulo_succ(d : nat)(m : Modulo d) : Modulo d.\nProof.\n  case m as [h mb].\n  case h as [ | ph].\n  + exact (modulo_zero d).\n  + exact (modulo _ _ (mb_succ _ _ mb)).\nDefined.\n\nFixpoint modulo_morphismeNat(d n : nat) : Modulo d.\nProof.\n  case n as [ | pn].\n  - exact (modulo_zero d).\n  - exact (modulo_succ d (modulo_morphismeNat d pn)).\nDefined.\n\nLemma modulo_morphismeNat_valeur :\n  forall d, forall n,\n    modulo_valeur d (modulo_morphismeNat d n) = reste n (S d).\nProof.\n  fix HR 2.\n  (* compliqué ! *)\nAdmitted.\n\n(* compatibilité *)\nLemma modulo_morphismeNat_calculParReste :\n  forall d, forall n,\n    modulo_morphismeNat d n = modulo_morphismeNat d (reste n (S d)).\nProof.\n  fix HR 2.\n  (* compliqué ! *)\nAdmitted.\n\nProposition modulo_egalite_compatibiliteMorphismeNat :\n  forall d, forall m n,\n    modulo_egalite (S d) m n\n    -> modulo_morphismeNat d m = modulo_morphismeNat d n.\nProof.\n  intros d m n equiv_m_n.\n  unfold modulo_egalite.\n  rewrite (modulo_morphismeNat_calculParReste d m).\n  rewrite (modulo_morphismeNat_calculParReste d n).\n  rewrite equiv_m_n.\n  reflexivity.\nQed.  \n\nDefinition zeroMod3 := modulo_morphismeNat 2 3.\nPrint zeroMod3.\nCompute zeroMod3.\n\nDefinition unMod3 := modulo_morphismeNat 2 1.\nPrint unMod3.\nCompute unMod3.\n\nDefinition deuxMod3 := modulo_morphismeNat 2 2.\nPrint deuxMod3.\nCompute deuxMod3.\n\nExample identite_valeur_2_mod3 :\n  modulo_morphismeNat 2 (modulo_valeur _ deuxMod3) = deuxMod3.\nAdmitted.\n\n(* L'inversibilité antérieure entraîne la surjectivité. *)\nProposition moduloBrut_morphismeNat_inversibiliteAnterieure :\n  forall d h (mb : ModuloBrut d h),\n    modulo_morphismeNat d (moduloBrut_valeur _ _ mb) = modulo _ _ mb.\nProof.\nAdmitted.\n\nProposition modulo_morphismeNat_inversibiliteAnterieure :\n  forall d (m : Modulo d),\n    modulo_morphismeNat d (modulo_valeur _ m) = m.\nProof.\nAdmitted.\n\n(* L'inversibilité postérieure entraîne l'injectivité (modulo (S d)). *)\n\nProposition modulo_morphismeNat_inversibilitePosterieure :\n  forall d n,\n    modulo_egalite (S d) (modulo_valeur d (modulo_morphismeNat d n))\n                                  n.\nProof.\nAdmitted.\n\n(* Monoïde additif *)\n\nFixpoint sommeBrute(d h : nat)(mb : ModuloBrut d h)(n : Modulo d){struct mb} : Modulo d.\nProof.\nAdmitted.\n\nDefinition somme{d : nat}(m n : Modulo d) : Modulo d.\nProof.\nAdmitted.\n\nExample somme_12_13_mod25 :\n  somme (modulo_morphismeNat 24 12) (modulo_morphismeNat 24 13) = modulo_morphismeNat 24 0.\nAdmitted.\n\n(*\nFixpoint sommeBrute(d h k : nat)(m : ModuloBrut h d)(n : ModuloBrut k d){struct m} : Modulo d.\nProof.\n  case m as [ | d m].\n  - exact (modulo (S h) k n).\n  - case (sommeBrute _ _ _ m n) as [hr mbr].\n    case hr as [ | phr].\n    * exact (modulo _ d (zeroMod _)).\n    * exact (modulo _ phr (succMod _ _ mbr)).\nDefined.\n\nDefinition somme{d : nat}(m n : Modulo d) : Modulo d.\nProof.\n  case m as [h mb].\n  case n as [k nb].\n  exact (sommeBrute _ _ _ mb nb).\nDefined.  *)\n\n\nExample somme_1_2_mod3 : somme unMod3 deuxMod3 = zeroMod3.\nAdmitted.\n\nExample somme_2_2_mod3 : somme deuxMod3 deuxMod3 = unMod3.\nAdmitted.\n\n(* Complément : sur l'unicité de la représentation. *)\n\n(* Conversion : foncteur catégorique - voir egalite_preuves_singletonSiDecidable. *)\nDefinition conversion(d h1 h2 : nat)(eg : h1 = h2) : ModuloBrut d h1 -> ModuloBrut d h2. \n  case eg.\n  exact (fun mb => mb).\nDefined.\n\n(* Utilisation de l'unicité des preuves d'égalité sur nat :\n- apply UIP_nat. *)\nLemma moduloBrut_singleton_casZeroModuloConversion :\n  forall d h (mb : ModuloBrut d h)(eg : h = d), \n    conversion d h d eg mb = mb_zero d.   \nProof.\nAdmitted.\n\nLemma moduloBrut_singleton_casZero :  forall d (mb : ModuloBrut d d),\n    mb = mb_zero d.\nProof.\nAdmitted.\n\n(* Les types 'ModuloBrut'sont des types singletons. *)\nProposition moduloBrut_typesSingletons :\n  forall (d h : nat)(mb1 mb2 : ModuloBrut d h),\n    mb1 = mb2.\nProof.\n  fix HR 3.\nAdmitted.  \n", "meta": {"author": "dhiaZnaidi", "repo": "Coq-Proof-Assistant-Project", "sha": "35ad59373469f5db249fa87e3d5dcd91c48ec1a7", "save_path": "github-repos/coq/dhiaZnaidi-Coq-Proof-Assistant-Project", "path": "github-repos/coq/dhiaZnaidi-Coq-Proof-Assistant-Project/Coq-Proof-Assistant-Project-35ad59373469f5db249fa87e3d5dcd91c48ec1a7/dev/masque.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7180543874150822}}
{"text": "Add LoadPath \"F:\\sfsol\".\nRequire Export Chap5.\n\nDefinition funny_prop1 :=\n  forall n, forall (E : beautiful n), beautiful (n+3).\n\nDefinition funny_prop1' :=\n  forall n, forall (_ : beautiful n), beautiful (n+3).\n\nDefinition funny_prop1'' :=\n  forall n, beautiful n -> beautiful (n+3).\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\nCheck conj.\n\nTheorem and_example :\n  (beautiful 0) /\\ (beautiful 3).\nProof.\n  apply conj.\n  apply b_0.\n  apply b_3.\n  Qed.\n\nPrint and_example.\n\nTheorem and_example' :\n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n    Case \"left\". apply ev_0.\n    Case \"right\". apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nTheorem proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HP. Qed.\n\nTheorem proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HQ. Qed.\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros.\n  inversion H as [HP HQ].\n  split.\n  assumption.\n  assumption.\n  Qed.\n\nPrint and_commut.\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n  split.\n  split.\n  assumption.\n  assumption.\n  assumption.\n  Qed.\n  \nTheorem even__ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  intros.\n  induction n.\n  split.\n  intros. apply ev_0.\n  intros. inversion H.\n  inversion IHn as [IHn1 IHn2].\n  split.\n  apply IHn2.\n  intros.\n  apply ev_SS. unfold even in H. unfold evenb in H.\n  assert (even n). unfold even. apply H.\n  apply IHn1. apply H0.\n  Qed.\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun (P Q R : Prop) (H : P /\\ Q) =>\n    match H with\n    | conj HP HQ => (\n      fun (H2 : Q /\\ R) =>\n        match H2 with\n        | conj HQ HR => conj P R HP HR\n        end\n    )\n    end.\n\nPrint conj_fact.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity) : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n  (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA]. apply HAB. Qed.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB. Qed.\n\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  split.\n  intros. assumption.\n  intros. assumption.\n  Qed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros.\n  inversion H as [HPQ HQP].\n  inversion H0 as [HQR HRQ].\n  split.\n  intros. apply HQR. apply HPQ. apply H1.\n  intros. apply HQP. apply HRQ. apply H1.\n  Qed.\n\nSearchAbout gorgeous.\n\nDefinition beautiful_iff_gorgeous :\n  forall n, beautiful n <-> gorgeous n :=\n    fun (n:nat) => conj (beautiful n -> gorgeous n) (gorgeous n -> beautiful n) (beautiful__gorgeous n) (gorgeous__beautiful n).\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ. Qed.\n\nDefinition or_comm_defn : forall P Q : Prop, P \\/ Q -> Q \\/ P :=\n  fun (P Q : Prop) (H : P \\/ Q) =>\n    match H with\n    | or_introl P1 => or_intror Q P P1\n    | or_intror Q1 => or_introl Q P Q1\n    end.\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. inversion H as [HP | [HQ HR]].\n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR. Qed.\n\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros.\n  inversion H.\n  destruct H0.\n  apply or_introl.\n  apply H0.\n  destruct H1.\n  apply or_introl.\n  apply H1.\n  apply or_intror.\n  split.\n  assumption.\n  assumption.\n  Qed.\n\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros.\n  split.\n  apply or_distributes_over_and_1.\n  apply or_distributes_over_and_2.\n  Qed.\n\nTheorem andb_true__and : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H. Qed.\n\nTheorem and__andb_true : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  intros.\n  destruct b.\n  simpl in H.\n  apply or_intror.\n  apply H.\n  apply or_introl. reflexivity.\n  Qed.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros.\n  destruct b.\n  apply or_introl. reflexivity.\n  simpl in H.\n  apply or_intror. apply H.\n  Qed.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros.\n  destruct b.\n  inversion H.\n  simpl in H.\n  split.\n  reflexivity.\n  apply H.\n  Qed.\n\nInductive False : Prop := .\n\nCheck False_ind.\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof.\n  intros contra.\n  inversion contra. Qed.\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra. Qed.\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  intros.\n  inversion H.\n  Qed.\n\nInductive True : Prop := \n  | evidence : forall (P : Prop), P -> True.\n\nCheck True_ind.\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. inversion H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.\n  apply HNA in HP. inversion HP. Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  intros P H. unfold not. intros G. apply G. apply H. Qed.\n\nTheorem double_neg_inf : forall (P : Prop),\n  P -> ~~P.\nProof.\n  intros.\n  unfold not.\n  intros.\n  apply H0.\n  apply H.\n  Qed.\n\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros.\n  unfold not in H0.\n  unfold not.\n  intros.\n  apply H0. apply H. apply H1.\n  Qed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  unfold not.\n  intros.\n  inversion H.\n  apply H1. apply H0.\n  Qed.\n\nTheorem five_not_even :\n  ~ ev 5.\nProof.\n  unfold not. intros Hev5. inversion Hev5 as [|n Hev3 Heqn].\n  inversion Hev3 as [|n' Hev1 Heqn']. inversion Hev1. Qed.\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof.\n  unfold not. intros n H. induction H.\n  intros.\n  inversion H.\n  intros.\n  inversion H0.\n  apply IHev.\n  apply H2.\n  Qed.\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop,\n  ~~P -> P.\nDefinition excluded_middle := 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 peirce__classic : ( forall P Q: Prop,\n  ((P->Q)->P)->P ) -> ( forall P:Prop,\n  ~~P -> P ).\nProof.\n  intros.\n  unfold not in H0.\n  apply H with (Q := False).\n  intros.\n  assert(H2 : False).\n    apply H0.\n    apply H1.\n  inversion H2.\n  Qed.\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity. Qed.\n\nTheorem inv_inequal : forall n n' : nat,\n  S n <> S n' -> n <> n'.\nProof.\n  unfold not.\n  intros. apply H. rewrite -> H0.\n  reflexivity. Qed.\n\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof.\n  intros.\n  generalize dependent n'.\n  induction n.\n  intros. unfold not in H.\n  destruct n'. apply ex_falso_quodlibet.\n  apply H. reflexivity.\n  reflexivity.\n  destruct n'. reflexivity.\n  intros.\n  simpl. apply IHn.\n  apply inv_inequal. apply H.\n  Qed.\n\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  intros.\n  unfold not.\n  destruct n.\n  destruct m.\n  inversion H.\n  intros.\n  inversion H0.\n  intros.\n  destruct m.\n  inversion H0.\n  inversion H0.\n  simpl in H.\n  rewrite -> H2 in H.\n  rewrite <- beq_nat_refl in H.\n  inversion H.\n  Qed.\n\nInductive ex (X:Type) (P : X->Prop) : Prop :=\n  ex_intro : forall(witness:X), P witness -> ex X P.\n\nDefinition some_nat_is_even : Prop :=\n  ex nat ev.\n\nDefinition snie : some_nat_is_even :=\n  ex_intro _ ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\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\nExample exists_example_1 : exists n, n + (n * n) = 6.\nProof.\n  apply ex_intro with (witness:=2).\n  reflexivity. Qed.\n\nExample exists_example_1' : exists n,\n  n + (n * n) = 6.\nProof.\n  exists 2.\n  reflexivity. Qed.\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\nDefinition p : ex nat (fun n => beautiful (S n)) :=\n  ex_intro nat (fun n:nat => beautiful (S n)) 2 b_3.\n\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros.\n  unfold not.\n  intros.\n  inversion H0.\n  apply H1.\n  apply H.\n  Qed.\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  unfold excluded_middle.\n  intros.\n  unfold not in H.\n  assert((P x) \\/ (~ P x)).\n  apply H.\n  inversion H1.\n  apply H2.\n  assert(False).\n  apply H0.\n  apply ex_intro with (witness := x).\n  apply H2.\n  inversion H3.\n  Qed.\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  intros.\n  split.\n  intros.\n  inversion H.\n  inversion H0.\n  apply or_introl.\n  apply ex_intro with (witness := witness).\n  apply H1.\n  apply or_intror.\n  apply ex_intro with (witness := witness).\n  apply H1.\n  intros.\n  inversion H.\n  inversion H0.\n  apply ex_intro with (witness := witness).\n  apply or_introl. apply H1.\n  inversion H0.\n  apply ex_intro with (witness := witness).\n  apply or_intror. apply H1.\n  Qed.\n\nModule MyEquality.\n\nInductive eq (X:Type) : X -> X -> Prop :=\n  refl_equal : forall x, eq X x x.\n\nNotation \"x = y\" := (eq _ x y)\n                    (at level 70, no associativity) : type_scope.\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\nNotation \"x =' y\" := (eq' _ x y)\n                     (at level 70, no associativity) : type_scope.\n\nTheorem two_defs_of_eq_coincide : forall (X:Type) (x y : X),\n  x = y <-> x =' y.\nProof.\n  intros.\n  split.\n  intros.\n  inversion H.\n  apply refl_equal'.\n  intros.\n  inversion H.\n  apply refl_equal.\n  Qed.\n\nDefinition four : 2 + 2 = 1 + 3 :=\n  refl_equal nat 4.\n\nDefinition singleton : forall (X:Set) (x:X), []++[x] = x::[] :=\n  fun (X:Set) (x:X) => refl_equal (list X) [x].\n\nEnd MyEquality.\n\nModule LeFirstTry.\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\nEnd LeFirstTry.\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\nCheck le_ind.\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. Qed.\n\nTheorem test_le3 :\n  ~ (2 <= 1).\nProof.\n  intros H. inversion H. inversion H1. Qed.\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 (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\nInductive total_relation (n m:nat) : Prop :=\n  | tr_1 : total_relation n m.\n\nInductive empty_relation (n m:nat) : Prop :=\n  | er_1 : ~ (total_relation n m) -> (empty_relation n m).\n\nModule 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\nInductive R' : nat -> nat -> nat -> Prop :=\n   | d1 : R' 0 0 0\n   | d2 : forall m n o, R' m n o -> R' (S m) n (S o)\n   | d3 : forall m n o, R' m n o -> R' m (S n) (S o)\n   | d4 : forall m n o, R' m n o -> R' n m o.\n\nInductive R'' : nat -> nat -> nat -> Prop :=\n   | e1 : R'' 0 0 0\n   | e2 : forall m n o, R'' m n o -> R'' (S m) n (S o)\n   | e3 : forall m n o, R'' m n o -> R'' m (S n) (S o).\n\nTheorem e3_R'' : forall (m n o:nat),\n  (R'' m (S n) (S o)) <-> (R'' m n o).\nProof.\n  split.\n  generalize dependent n.\n  generalize dependent o.\n  induction m.\n  intros.\n  inversion H.\n  apply H3.\n  intros.\n  inversion H.\n  destruct o.\n  inversion H3.\n  apply e2.\n  apply IHm.\n  apply H3.\n  apply H3.\n  intros.\n  apply e3.\n  apply H.\n  Qed.\n\nTheorem e2_R'' : forall (m n o:nat),\n  (R'' (S m) n (S o)) <-> (R'' m n o).\nProof.\n  split.\n  generalize dependent m.\n  generalize dependent o.\n  induction n.\n  intros.\n  inversion H.\n  apply H3.\n  intros.\n  inversion H.\n  apply H3.\n  destruct o.\n  inversion H3.\n  apply e3.\n  apply IHn.\n  apply H3.\n  intros.\n  apply e2.\n  apply H.\n  Qed.\n\nTheorem e3_e2_R'' : forall (m n o:nat),\n  (R'' (S m) n o) <-> (R'' m (S n) o).\nProof.\n  split.\n  intros.\n  destruct o.\n  inversion H.\n  apply e3.\n  apply e2_R''.\n  apply H.\n  intros.\n  destruct o.\n  inversion H.\n  apply e2.\n  apply e3_R''.\n  apply H.\n  Qed.\n\nTheorem symm_R'' : forall (m n o:nat),\n  (R'' m n o) -> (R'' n m o).\nProof.\n  induction m.\n  induction n.\n  intros. apply H.\n  intros.\n  destruct o.\n  inversion H.\n  inversion H.\n  apply e2.\n  apply IHn.\n  apply H3.\n  intros.\n  apply e3_e2_R''.\n  apply IHm.\n  apply e3_e2_R''.\n  apply H.\n  Qed.\n\nTheorem eq_R_R'' : forall (m n o:nat),\n  (R m n o) <-> (R'' m n o).\nProof.\n  split.\n  apply R_ind.\n  apply e1.\n  intros.\n  apply e2.\n  apply H0.\n  intros.\n  apply e3.\n  apply H0.\n  intros.\n  apply e2_R''.\n  apply e3_R''.\n  apply H0.\n  intros.\n  apply symm_R''.\n  apply H0.\n  apply R''_ind.\n  apply c1.\n  intros.\n  apply c2.\n  apply H0.\n  intros.\n  apply c3.\n  apply H0.\n  Qed.\n\nDefinition sum_eq (m n o:nat) : Prop :=\n  m + n = o.\n\nTheorem eq_R : forall (m n o:nat),\n  (R m n o) <-> (sum_eq m n o).\nProof.\n  split.\n  assert ((R'' m n o) -> (sum_eq m n o)).\n  apply R''_ind.\n  unfold sum_eq. reflexivity.\n  intros.\n  unfold sum_eq in H0.\n  unfold sum_eq.\n  rewrite <- H0.\n  reflexivity.\n  intros.\n  unfold sum_eq in H0.\n  unfold sum_eq.\n  rewrite <- H0.\n  rewrite -> plus_n_Sm.\n  reflexivity.\n  intros.\n  apply H.\n  apply eq_R_R''.\n  apply H0.\n  unfold sum_eq.\n  generalize dependent o.\n  generalize dependent n.\n  induction m.\n  intros.\n  simpl in H.\n  rewrite -> H.\n  generalize dependent n.\n  induction o.\n  intros.\n  apply c1.\n  intros.\n  apply c3.\n  destruct n.\n  inversion H.\n  inversion H.\n  apply IHo with (n:=n).\n  apply H1.\n  intros.\n  destruct o.\n  inversion H.\n  apply c2.\n  inversion H.\n  apply IHm.\n  reflexivity.\n  Qed.\n\nEnd R.\n\nInductive all (X : Type) (P : X -> Prop) : list X -> Prop :=\n  | all1 : all X P []\n  | all2 : forall (x:X) (l:list X), (P x) -> (all X P l) -> (all X P (x::l)).\n\nTheorem all_forallb : forall (X:Type) (P: X ->bool) (l:list X),\n  all X (fun x:X => (P x)=true) l -> (forallb P l = true).\nProof.\n  intros.\n  induction l.\n  reflexivity.\n  simpl.\n  inversion H.\n  rewrite -> H2.\n  apply IHl.\n  apply H3.\n  Qed.\n\nInductive in_merge (X:Type) : list X->list X->list X->Prop :=\n  | in1 : in_merge X [] [] []\n  | in2 : forall (hx:X) (x y xy:list X) , in_merge X x y xy -> in_merge X (hx::x) y (hx::xy)\n  | in3 : forall (hy:X) (x y xy:list X) , in_merge X x y xy -> in_merge X x (hy::y) (hy::xy).\n\nTheorem filter_challenge : forall (X:Set) (l1 l2 l:list X) (test:X->bool),\n  (all X (fun x:X => (test x)=true) l1)->(all X (fun x:X => (test x)=false) l2)\n  ->(in_merge X l1 l2 l)\n  -> filter test l=l1.\nProof.\n  intros.\n  generalize dependent l.\n  generalize dependent l2.\n  induction l1.\n  induction l2.\n  intros.\n  inversion H1.\n  reflexivity.\n  intros.\n  inversion H1.\n  inversion H0.\n  unfold filter.\n  rewrite -> H9.\n  apply IHl2.\n  apply H10.\n  apply H6.\n  intros.\n  generalize dependent l.\n  generalize dependent l2.\n  induction l2.\n  intros.\n  inversion H1.\n  inversion H.\n  assert(filter test xy = l1).\n  apply IHl1 with (l2:=[]).\n  apply H10.\n  apply H0.\n  apply H6.\n  rewrite <- H11.\n  unfold filter.\n  rewrite -> H9.\n  reflexivity.\n  intros.\n  inversion H.\n  inversion H1.\n  assert(filter test xy = l1).\n  apply IHl1 with (l2:=(x0::l2)).\n  apply H5.\n  apply H0.\n  apply H10.\n  rewrite <- H11.\n  unfold filter.\n  rewrite -> H4.\n  reflexivity.\n  inversion H0.\n  assert(filter test (x0::xy) = filter test xy).\n  unfold filter.\n  rewrite -> H13.\n  reflexivity.\n  rewrite -> H15.\n  apply IHl2.\n  apply H14.\n  apply H10.\n  Qed.\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\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  intros X.\n  induction xs.\n  intros.\n  simpl in H.\n  apply or_intror.\n  apply H.\n  intros.\n  inversion H.\n  apply or_introl.\n  apply ai_here.\n  assert (appears_in x0 xs \\/ appears_in x0 ys).\n    apply IHxs.\n    apply H1.\n  inversion H3 as [ H4 | H5].\n    apply or_introl.\n    apply ai_later.\n    apply H4.\n    apply or_intror.\n    apply H5.\n  Qed.\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  intros.\n  inversion H as [H1 | H2].\n  induction xs.\n  inversion H1.\n  inversion H1.\n  apply ai_here.\n  apply ai_later.\n  apply IHxs.\n  apply or_introl.\n  apply H2.\n  apply H2.\n  induction xs.\n  apply H2.\n  apply ai_later.\n  apply IHxs.\n  apply or_intror.\n  apply H2.\n  Qed.\n\nDefinition disjoint (X:Type) (l1 l2:list X) :=\n  forall (x:X), ((appears_in x l1)/\\ ~(appears_in x l2))\\/(~(appears_in x l1)/\\ (appears_in x l2)).\n\nInductive no_repeats (X:Type) : list X->Prop :=\n  | nr1 : no_repeats X []\n  | nr2 : forall (x:X) (l:list X), ~ (appears_in x l) -> no_repeats X (x::l).\n\nTheorem O_le_n : forall n,\n  0 <= n.\nProof.\n  intros.\n  induction n.\n  apply le_n.\n  apply le_S.\n  apply IHn.\n  Qed.  \n\nTheorem n_le_m__Sn_le_Sm : forall n m,\n  n <= m -> S n <= S m.\nProof.\n  intros.\n  generalize dependent m.\n  induction n.\n  intros.\n  induction m.\n  apply le_n.\n  apply le_S.\n  apply IHm.\n  apply O_le_n.\n  induction m.\n  intros.\n  inversion H.\n  intros.\n  inversion H.\n  apply le_n.\n  apply le_S.\n  apply IHm.\n  apply H1.\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. generalize dependent n. induction m.\n  intros.\n  inversion H.\n  apply le_n.\n  inversion H1.\n  intros.\n  inversion H.\n  apply le_n.\n  apply le_S.\n  apply IHm.\n  apply H1.\n  Qed.\n\nTheorem le_plus_l : forall a b,\n  a <= a + b.\nProof.\n  intros a b.\n  induction b.\n  rewrite -> plus_0_r.\n  apply le_n.\n  rewrite <- plus_n_Sm.\n  apply le_S.\n  apply IHb.\n  Qed.\n\nTheorem plus_lt_l : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m .\nProof.\n  intros.\n  generalize dependent m.\n  induction n2.\n  intros.\n  rewrite -> plus_0_r in H.\n  apply H.\n  intros.\n  inversion H.\n  unfold lt.\n  apply n_le_m__Sn_le_Sm.\n  apply le_plus_l.\n  rewrite <- H1 in H.\n  unfold lt in H.\n  apply Sn_le_Sm__n_le_m in H.\n  rewrite <- plus_n_Sm in H.\n  apply le_S.\n  apply IHn2.\n  apply H.\n  Qed.\n\nTheorem plus_lt : forall n1 n2 m,\n  n1 + n2 < m ->\n  n1 < m /\\ n2 < m.\nProof.\n  intros.\n  apply conj.\n  apply plus_lt_l with (n2:=n2).\n  apply H.\n  rewrite -> plus_comm in H.\n  apply plus_lt_l with (n2:=n1).\n  apply H.\n  Qed.\n\nTheorem lt_S : forall n m,\n  n < m ->\n  n < S m.\nProof.\n  intros.\n  apply le_S.\n  apply H.\n  Qed.\n\nTheorem ble_nat_true : forall n m,\n  ble_nat n m = true -> n <= m.\nProof.\n  intros.\n  generalize dependent m.\n  induction n.\n  intros.\n  apply O_le_n.\n  intros.\n  inversion H.\n  destruct m.\n  inversion H1.\n  apply n_le_m__Sn_le_Sm.\n  apply IHn.\n  apply H1.\n  Qed.\n\nTheorem ble_nat_n_Sn_false : forall n m,\n  ble_nat n (S m) = false ->\n  ble_nat n m = false.\nProof.\n  intros.\n  generalize dependent m.\n  induction n.\n  intros.\n  inversion H.\n  intros.\n  inversion H.\n  destruct m.\n  rewrite -> H1.\n  unfold ble_nat.\n  reflexivity.\n  rewrite -> H1.\n  unfold ble_nat.\n  apply IHn.\n  apply H1.\n  Qed.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  intros.\n  generalize dependent n.\n  induction m.\n  intros.\n  unfold not.\n  intros.\n  inversion H0.\n  rewrite -> H1 in H.\n  inversion H.\n  induction n.\n  intros.\n  inversion H.\n  intros.\n  unfold not.\n  intros.\n  apply Sn_le_Sm__n_le_m in H0.\n  generalize H0.\n  apply IHm.\n  inversion H.\n  reflexivity.\n  Qed.\n\nInductive nostutter: list nat -> Prop :=\n  | ns1 : nostutter []\n  | ns2 : forall (x:nat), (nostutter [x])\n  | ns3 : forall (x y:nat) (l:list nat),~(x=y) -> (nostutter (y::l)) -> (nostutter (x::y::l)).\n\nExample test_nostutter_1: nostutter [3,1,4,1,5,6].\nProof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n\nExample test_nostutter_2: nostutter [].\nProof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n\nExample test_nostutter_3: nostutter [5].\nProof. repeat constructor; apply beq_false_not_eq; 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 H1; auto. Qed.\n\nLemma app_length : forall {X:Type} (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  generalize dependent l2.\n  induction l1.\n  auto.\n  intros.\n  simpl.\n  auto.\n  Qed.\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  intros.\n  induction l.\n  inversion H.\n  inversion H.\n  apply ex_intro with (witness:=[]).\n  apply ex_intro with (witness:=l).\n  reflexivity.\n  assert(exists l1 : list X, exists l2 : list X, l = l1 ++ x :: l2).\n  auto.\n  inversion H3.\n  inversion H4.\n  apply ex_intro with (witness:=(x0::witness)).\n  apply ex_intro with (witness:=witness0).\n  rewrite -> H5. reflexivity.\n  Qed.\n\nInductive repeats {X:Type} : list X -> Prop :=\n  | rp1 : forall (x:X) (l:list X),(appears_in x l)->(repeats (x::l))\n  | rp2 : forall (x:X) (l:list X),(repeats l)->(repeats (x::l)).\n\nTheorem remove_one: forall (X:Type) (x:X) (l l1 l2:list X),\n  (forall (x1:X), (appears_in x1 (x::l)) -> (appears_in x1 (l1++(x::l2)))) ->\n  (forall (x2:X), ~(x2=x) -> (appears_in x2 l) -> (appears_in x2 (l1++l2))).\nProof.\n  intros.\n  assert(appears_in x2 (l1++x::l2)).\n  apply H.\n  apply ai_later.\n  apply H1.\n  apply appears_in_app in H2.\n  inversion H2 as [H3 | H4].\n  apply app_appears_in.\n  apply or_introl.\n  apply H3.\n  inversion H4.\n  assert(False).\n  apply H0. apply H5.\n  inversion H3.\n  apply app_appears_in.\n  apply or_intror.\n  apply H5.\n  Qed.\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. intros X l1. induction l1.\n  intros.\n  inversion H1.\n  intros.\n  assert((appears_in x l1)\\/~(appears_in x l1)).\n  apply H.\n  inversion H2 as [H3 | H4].\n  apply rp1. apply H3.\n  apply rp2.\n  assert(appears_in x l2).\n  apply H0. apply ai_here.\n  apply appears_in_app_split in H3.\n  inversion H3.\n  inversion H5.\n  assert((forall x1 : X, (~x1=x) -> appears_in x1 l1 -> appears_in x1 (witness++witness0))).\n  apply remove_one.\n  rewrite <- H6.\n  apply H0.\n  assert(forall x1 : X, appears_in x1 l1 -> appears_in x1 (witness ++ witness0)).\n  intros.\n  apply H7.\n  assert(forall (y y1:X) (l:list X),~(appears_in y l)->(appears_in y1 l)->~(y=y1)).\n    induction l.\n    intros.\n    inversion H10.\n    intros.\n    inversion H10.\n    rewrite <- H12 in H9.\n    unfold not in H9.\n    unfold not. intros.\n    apply H9.\n    rewrite -> H12.\n    rewrite -> H11.\n    apply ai_here.\n    apply IHl.\n    unfold not.\n    intros.\n    apply H9.\n    apply ai_later.\n    apply H14.\n    apply H12.\n  assert(x<>x1).\n  apply H9 with (l:=l1).\n  auto.\n  auto.\n  unfold not.\n  auto.\n  apply H8.\n  apply IHl1 with (l2:=(witness ++ witness0)).\n  apply H.\n  assumption.\n  rewrite -> H6 in H1.\n  rewrite -> app_length.\n  rewrite -> app_length in H1.\n  unfold lt in H1.\n  unfold lt.\n  apply Sn_le_Sm__n_le_m.\n  assert(forall (l:list X), length(x::l)=S (length l)).\n    intros.\n    unfold length.\n    reflexivity.\n  rewrite -> H9 in H1.\n  rewrite -> H9 in H1.\n  rewrite <- plus_n_Sm in H1.\n  assumption.\n  Qed.", "meta": {"author": "mmalone", "repo": "sfsol", "sha": "5888f4532a1ec1ababa21bef39e25eb26279f0e4", "save_path": "github-repos/coq/mmalone-sfsol", "path": "github-repos/coq/mmalone-sfsol/sfsol-5888f4532a1ec1ababa21bef39e25eb26279f0e4/Chap6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7180519154738045}}
{"text": "\nRequire Export Iron.Language.SystemF.Ki.\n\n\n(* Type Expressions *)\nInductive ty  : Type :=\n | TCon    : nat -> ty            (* Data type constructor. *)\n | TVar    : nat -> ty            (* deBruijn index. *)\n | TForall : ty  -> ty            (* Type variable binding. *)\n | TFun    : ty  -> ty -> ty.     (* Function type constructor. *)\n\nHint Constructors ty.\n\n\n(********************************************************************)\n(* Well formed types are closed under the given kind environment *)\nFixpoint wfT (ke: kienv) (tt: ty) : Prop := \n match tt with\n | TCon _     => True\n | TVar i     => exists k, get i ke = Some k\n | TForall t  => wfT (ke :> KStar) t\n | TFun t1 t2 => wfT ke t1 /\\ wfT ke t2\n end.\nHint Unfold wfT.\n\n\n(* A closed type is well formed under an empty type environment. *)\nDefinition closedT (tt: ty) : Prop\n := wfT nil tt.\nHint Unfold closedT.\n\n\n(********************************************************************)\n(* Lifting of type indices in types.\n   When we push new elements on the environment stack, we need\n   to lift referenes to existing elements across the new ones. *)\nFixpoint liftTT (d: nat) (tt: ty) : ty :=\n  match tt with\n  | TCon _     => tt\n\n  |  TVar ix\n  => if le_gt_dec d ix\n      then TVar (S ix)\n      else tt\n\n  |  TForall t \n  => TForall (liftTT (S d) t)\n\n  |  TFun t1 t2\n  => TFun    (liftTT d t1) (liftTT d t2)\n  end.\nHint Unfold liftTT.\n\n\n(* Tactic to help deal with lifting functions. *)\nLtac lift_cases \n := match goal with \n     |  [ |- context [le_gt_dec ?n ?n'] ]\n     => case (le_gt_dec n n')\n    end.\n\n\n(********************************************************************)\n(* Substitution for the outer-most binder in a type. *)\nFixpoint substTT (d: nat) (u: ty) (tt: ty) : ty \n := match tt with\n    |  TCon _     \n    => tt\n \n    | TVar ix\n    => match nat_compare ix d with\n       | Eq => u\n       | Gt => TVar (ix - 1)\n       | _  => TVar  ix\n       end\n\n    |  TForall t  \n    => TForall (substTT (S d) (liftTT 0 u) t)\n\n    |  TFun t1 t2 \n    => TFun (substTT d u t1) (substTT d u t2)\n  end.\n\n\n(********************************************************************)\n(* Changing the order of lifting. *)\nLemma liftTT_liftTT\n :  forall n n' t\n ,  liftTT n              (liftTT (n + n') t) \n =  liftTT (1 + (n + n')) (liftTT n t).\nProof.\n intros. gen n n'.\n induction t; intros; auto.\n\n Case \"TVar\".\n  simpl.\n  repeat (unfold liftTT; lift_cases; intros); burn.\n\n Case \"TForall\".\n  simpl.\n  assert (S (n + n') = (S n) + n'). omega. rewrite H. \n  rewrite IHt. auto.\n\n Case \"TFun\".\n  simpl. apply f_equal2; auto.\nQed.  \n\n\n(* Lifting then substituting at the same index doesn't do anything.\n\n   When we lift indices in a type that are greater or equal to some\n   depth d, there will be no indices of value d in the result. The\n   lifting process increments indices greater than 'd', but then the\n   substitution process decrements them again, so we get back to \n   the type we started with. \n *)\nLemma substTT_liftTT\n :  forall d t1 t2\n ,  substTT d t2 (liftTT d t1) = t1.\nProof.\n intros. gen d t2.\n induction t1; intros; eauto.\n\n Case \"TVar\".\n  simpl; lift_cases; unfold substTT;\n   fbreak_nat_compare; intros;\n   burn.\n\n Case \"TForall\".\n  simpl. \n  rewrite IHt1. auto.\n\n Case \"TFun\".\n  simpl.\n  rewrite IHt1_1.\n  rewrite IHt1_2. auto.\nQed.\n\n\n(* Lifting after substitution *)\nLemma liftTT_substTT\n :  forall n n' t1 t2\n ,  liftTT n (substTT (n + n') t2 t1)\n =  substTT (1 + n + n') (liftTT n t2) (liftTT n t1).\nProof.\n intros. gen n n' t2.\n induction t1; intros; eauto.\n\n Case \"TVar\".\n  repeat (simpl; fbreak_nat_compare; \n          try lift_cases; try intros);\n   burn.\n\n Case \"TForall\".\n  simpl.\n  rewrite (IHt1 (S n) n'). simpl.\n  rewrite (liftTT_liftTT 0 n). auto.\n\n Case \"TFun\".\n  simpl.\n  rewrite IHt1_1. auto.\n  rewrite IHt1_2. auto.\nQed.\n\n\n(* Lifting after substitution, another way. *)\nLemma liftTT_substTT'\n :  forall n n' t1 t2\n ,  liftTT (n + n') (substTT n t2 t1)\n =  substTT n (liftTT (n + n') t2) (liftTT (1 + n + n') t1).\nProof.\n intros. gen n n' t2.\n induction t1; intros; auto.\n\n Case \"TVar\".\n  repeat ( unfold liftTT; unfold substTT; fold liftTT; fold substTT\n         ; try lift_cases; try fbreak_nat_compare\n         ; intros); burn.\n\n Case \"TForall\".\n  simpl. f_equal.\n  rewrite (IHt1 (S n) n'). f_equal.\n   simpl. rewrite (liftTT_liftTT 0 (n + n')). auto.\n\n Case \"TFun\".\n  simpl. f_equal.\n   apply IHt1_1.\n   apply IHt1_2.\nQed.\n\n\n(* Commuting substitutions. *)\nLemma substTT_substTT\n :  forall n m t1 t2 t3\n ,  substTT (n + m) t3 (substTT n t2 t1)\n =  substTT n (substTT (n + m) t3 t2)\n              (substTT (1 + n + m) (liftTT n t3) t1).\nProof.\n intros. gen n m t2 t3.\n induction t1; intros; auto.\n\n Case \"TVar\".\n  repeat (simpl; fbreak_nat_compare); try burn.\n  rewrite substTT_liftTT. auto.\n\n Case \"TForall\".\n  simpl. f_equal.\n  rewrite (IHt1 (S n) m). f_equal.\n   simpl. rewrite (liftTT_substTT 0 (n + m)). auto.\n   simpl. rewrite (liftTT_liftTT 0 n). auto.  \n\n Case \"TFun\".\n  simpl. f_equal.\n   apply IHt1_1.\n   apply IHt1_2.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/SystemF/Ty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218866, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7180519082304767}}
{"text": "From mathcomp Require Import ssreflect mini_ssrfun mini_ssrbool.\nFrom mathcomp Require Import mini_eqtype mini_ssrnat mini_seq.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition sum m n F := (foldr (fun i a => F i + a) 0 (iota m (n - m))).\n\nNotation \"\\sum_ ( m <= i < n ) F\" := (sum m n (fun i => F))\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\sum_ ( m  <=  i  <  n ) '/  '  F ']'\").\n\nLemma sum_geq m n F : n <= m -> \\sum_(m <= i < n) F i = 0.\nProof. by rewrite /sum => /eqP->. Qed.\n\nLemma sum_recr m n F : m <= n ->\n  \\sum_(m <= i < n.+1) F i = \\sum_(m <= i < n) F i + F n.\nProof.\nmove=> leq_mn; rewrite /sum subSn// -addn1 iota_add subnKC// foldr_cat/=.\nby elim: iota (F n) => [|x s IHs] k; rewrite -?addnA -?IHs ?addn0.\nQed.\n\nLemma sum_recl m n F : m <= n ->\n  \\sum_(m <= i < n.+1) F i = F m + \\sum_(m <= i < n) F (S i).\nProof.\nmove=> leq_mn; rewrite /sum subSn//=; congr (_ + _).\nby move: (n - m) => k {leq_mn}; elim: k m => //= k IHk m; rewrite IHk.\nQed.\n\nLemma muln_sumr (m n k : nat) F :\n  k * (\\sum_(m <= i < n) F i) = \\sum_(m <= i < n) k * F i.\nProof.\nby rewrite /sum; elim: iota => [|x s IHs]; rewrite (muln0, mulnDr) ?IHs.\nQed.\n\nLemma eqn_sum (m n : nat) G F : (forall i, F i = G i) ->\n  (\\sum_(m <= i < n) F i) = \\sum_(m <= i < n) G i.\nProof.\nby rewrite /sum; elim: iota => [|x s IHs]//= eqFG; rewrite IHs ?eqFG.\nQed.\nArguments eqn_sum {m n} G F eq_FG.\n\nLemma muln_suml (m n k : nat) F :\n  (\\sum_(m <= i < n) F i) * k = \\sum_(m <= i < n) F i * k.\nProof. by rewrite mulnC muln_sumr; apply: eqn_sum => i; rewrite mulnC. Qed.\n", "meta": {"author": "gares", "repo": "mathcomp", "sha": "f4ea1abac523107baf16e3cf528752b22ad8fdb5", "save_path": "github-repos/coq/gares-mathcomp", "path": "github-repos/coq/gares-mathcomp/mathcomp-f4ea1abac523107baf16e3cf528752b22ad8fdb5/mathcomp/ssreflect/mini_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7179469289623351}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Neighborhoods.\nFrom ZornsLemma Require Export InverseImage.\nRequire Export OpenBases.\nRequire Export NeighborhoodBases.\nRequire Export Subbases.\n\nSection continuity.\n\nVariable X Y:TopologicalSpace.\nVariable f:point_set X -> point_set Y.\n\nDefinition continuous : Prop :=\n  forall V:Ensemble (point_set Y), open V ->\n  open (inverse_image f V).\n\nDefinition continuous_at (x:point_set X) : Prop :=\n  forall V:Ensemble (point_set Y),\n  neighborhood V (f x) -> neighborhood (inverse_image f V) x.\n\nLemma continuous_at_open_neighborhoods:\n  forall x:point_set X,\n  (forall V:Ensemble (point_set Y),\n  open_neighborhood V (f x) -> neighborhood (inverse_image f V) x) ->\n  continuous_at x.\nProof.\nintros.\nred; intros.\ndestruct H0 as [V' [? ?]].\npose proof (H V' H0).\ndestruct H2 as [U' [? ?]].\nexists U'; split; trivial.\napply (inverse_image_increasing f) in H1; auto with sets.\nQed.\n\nLemma pointwise_continuity :\n  (forall x:point_set X, continuous_at x) -> continuous.\nProof.\nintros.\nred; intros.\nassert (interior (inverse_image f V) = inverse_image f V).\napply Extensionality_Ensembles; split.\napply interior_deflationary.\nred; intros.\ndestruct H1.\nassert (neighborhood V (f x)).\nexists V; repeat split; auto with sets.\npose proof (H x V H2).\ndestruct H3 as [U].\ndestruct H3.\ndestruct H3.\nassert (Included U (interior (inverse_image f V))).\napply interior_maximal; trivial.\nauto.\n\nrewrite <- H1; apply interior_open.\nQed.\n\nLemma continuous_func_continuous_everywhere:\n  continuous -> forall x:point_set X, continuous_at x.\nProof.\nintros.\napply continuous_at_open_neighborhoods.\nintros.\napply open_neighborhood_is_neighborhood.\ndestruct H0; split; try constructor; auto.\nQed.\n\nLemma continuous_at_neighborhood_basis:\n  forall (x:point_set X) (NB:Family (point_set Y)),\n  neighborhood_basis NB (f x) ->\n  (forall V:Ensemble (point_set Y),\n  In NB V -> neighborhood (inverse_image f V) x) ->\n  continuous_at x.\nProof.\nintros.\nred; intros.\ndestruct H.\napply neighborhood_basis_cond in H1.\ndestruct H1 as [N [? ?]].\npose proof (H0 N H).\ndestruct H2 as [U [? ?]].\nexists U; split; trivial.\nassert (Included (inverse_image f N) (inverse_image f V));\n  auto with sets.\nQed.\n\nLemma continuous_open_basis:\n  forall (B:Family (point_set Y)), open_basis B ->\n  (forall V:Ensemble (point_set Y),\n    In B V -> open (inverse_image f V)) -> continuous.\nProof.\nintros.\napply pointwise_continuity.\nintro.\npose proof (open_basis_to_open_neighborhood_basis B (f x) H).\napply open_neighborhood_basis_is_neighborhood_basis in H1.\napply (continuous_at_neighborhood_basis _ _ H1).\nintros.\ndestruct H2 as [[? ?]].\napply open_neighborhood_is_neighborhood.\nsplit; try constructor; auto.\nQed.\n\nLemma continuous_subbasis:\n  forall (SB:Family (point_set Y)), subbasis SB ->\n  (forall V:Ensemble (point_set Y),\n     In SB V -> open (inverse_image f V)) -> continuous.\nProof.\nintros.\napply (continuous_open_basis _\n  (finite_intersections_of_subbasis_form_open_basis _ _ H)).\nintros.\ndestruct H1.\ndestruct H1 as [A [? [V' []]]].\nrewrite H3.\nassert (inverse_image f (IndexedIntersection V') =\n  IndexedIntersection (fun a:A => inverse_image f (V' a))).\napply Extensionality_Ensembles; split; red; intros.\ndestruct H4.\ninversion_clear H4.\nconstructor; intros.\nconstructor.\napply H5.\ndestruct H4.\nconstructor.\nconstructor; intros.\ndestruct (H4 a).\nexact H5.\n\nrewrite H4.\napply open_finite_indexed_intersection; trivial.\nintros.\napply H0.\napply H2.\nQed.\n\nEnd continuity.\n\nArguments continuous {X} {Y}.\nArguments continuous_at {X} {Y}.\n\nLemma continuous_composition_at: forall {X Y Z:TopologicalSpace}\n  (f:point_set Y -> point_set Z) (g:point_set X -> point_set Y)\n  (x:point_set X),\n  continuous_at f (g x) -> continuous_at g x ->\n  continuous_at (fun x:point_set X => f (g x)) x.\nProof.\nintros.\nred; intros.\nrewrite inverse_image_composition.\nauto.\nQed.\n\nLemma continuous_composition: forall {X Y Z:TopologicalSpace}\n  (f:point_set Y -> point_set Z) (g:point_set X -> point_set Y),\n  continuous f -> continuous g ->\n  continuous (fun x:point_set X => f (g x)).\nProof.\nintros.\nred; intros.\nrewrite inverse_image_composition.\nauto.\nQed.\n\nLemma continuous_identity: forall (X:TopologicalSpace),\n  continuous (fun x:point_set X => x).\nProof.\nintros.\nred; intros.\napply eq_ind with (1:=H).\napply Extensionality_Ensembles; split; red; intros.\nconstructor; trivial.\ndestruct H0; trivial.\nQed.\n\nLemma continuous_constant: forall (X Y:TopologicalSpace)\n  (y0:point_set Y), continuous (fun x:point_set X => y0).\nProof.\nintros.\npose (f := fun _:point_set X => y0).\nfold f.\nred; intros.\ndestruct (classic (In V y0)).\nreplace (inverse_image f V) with (@Full_set (point_set X)).\napply open_full.\napply Extensionality_Ensembles; split; red; intros.\nconstructor; trivial.\nconstructor.\nreplace (inverse_image f V) with (@Empty_set (point_set X)).\napply open_empty.\napply Extensionality_Ensembles; split; auto with sets;\n  red; intros.\ndestruct H1.\ncontradiction H0.\nQed.\n\nLemma continuous_at_is_local: forall (X Y:TopologicalSpace)\n  (x0:point_set X) (f g:point_set X -> point_set Y)\n  (N:Ensemble (point_set X)),\n  neighborhood N x0 -> (forall x:point_set X, In N x -> f x = g x) ->\n  continuous_at f x0 -> continuous_at g x0.\nProof.\nintros.\nred; intros.\ndestruct H as [U1 [[]]].\nrewrite <- H0 in H2.\napply H1 in H2.\ndestruct H2 as [U2 [[]]].\nexists (Intersection U1 U2).\nrepeat split; trivial.\napply open_intersection2; trivial.\ndestruct H7.\nrewrite <- H0.\napply H6 in H8.\ndestruct H8; trivial.\nauto.\nauto.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/topology/Continuity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7179469179280036}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) (lf3 : natural) : natural :=\n  plus lf2 lf3.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj83_coqofml_02kCXG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7179469111217132}}
{"text": "Require Import List.\nRequire Import String.\nRequire Import ZArith.\n\nOpen Scope list_scope.\nOpen Scope string_scope.\nOpen Scope Z_scope.\n\nRequire Import Imp.ImpSyntax.\nRequire Import Imp.ImpCommon.\n\n(*\n * In this file, you will finish writing the interpreter for Imp.\n * You should use the semantics in ImpEval.v as a guide.\n *)\n\nDefinition interp_op1\n  (op : op1) (v : val) : option val :=\n  match op, v with\n  | Oneg, Vint i =>\n      Some (Vint (Z.opp i))\n  | Onot, Vbool b =>\n      Some (Vbool (negb b))\n  | _, _ =>\n      None\n  end.\n\n(*\n * Problem 1 [20 points, ~30 LOC]: Complete the rest of interp_op2.\n * The semantics for this are in eval_binop in ImpEval.v.\n *\n * Once you have written this, uncomment the proof of eval_op2_interp_op2 in \n * ImpInterpProof.v.\n *)\nDefinition interp_op2\n  (op : op2) (v1 v2 : val) : option val :=\n  match op, v1, v2 with\n  | Oadd, Vint i1, Vint i2 =>\n      Some (Vint (Z.add i1 i2))\n  | Odiv, Vint i1, Vint i2 =>\n      if Z.eq_dec i2 0 then\n        None\n      else\n        Some (Vint (Z.div i1 i2))\n  (* YOUR CODE HERE *)\n  | _, _, _ =>\n      None\n  end.\n\nFixpoint interp_e (s : store) (h : heap)\n  (e : expr) : option val :=\n  match e with\n  | Eval v => Some v\n  | Evar x => lkup s x\n  | Eop1 op e1 =>\n      match interp_e s h e1 with\n      | Some v1 => interp_op1 op v1\n      | _ => None\n      end\n  | Eop2 op e1 e2 =>\n      match interp_e s h e1, interp_e s h e2 with\n      | Some v1, Some v2 => interp_op2 op v1 v2\n      | _, _ => None\n      end\n  | Elen e1 =>\n      match interp_e s h e1 with\n      | Some (Vaddr a) =>\n          match read h a with\n          | Some (Vint l) => Some (Vint l)\n          | _ => None\n          end\n      | Some (Vstr cs) =>\n          Some (Vint (Z.of_nat (String.length cs)))\n      | _ => None\n      end\n  | Eidx e1 e2 =>\n      match interp_e s h e1, interp_e s h e2 with\n      | Some (Vaddr a), Some (Vint i) =>\n          match read h a with\n          | Some (Vint l) =>\n              if Z_le_dec 0 i then\n                if Z_lt_dec i l then\n                  read h (Z.succ (a + i))\n                else\n                  None\n              else\n                None\n          | _ => None\n          end\n      | Some (Vstr cs), Some (Vint i) =>\n          if Z_le_dec 0 i then\n            match String.get (Z.to_nat i) cs with\n            | Some c =>\n                Some (Vstr (String c EmptyString))\n            | None => None\n            end\n          else\n            None\n      | _, _ => None\n      end\n  end.\n\nFixpoint interps_e (s : store) (h : heap)\n  (es : list expr) : option (list val) :=\n  match es with\n  | nil => Some nil\n  | e :: t =>\n      match interp_e s h e, interps_e s h t with\n      | Some v, Some vs => Some (v :: vs)\n      | _, _ => None\n      end\n  end.\n\n(*\n * Problem 2 [25 points, ~70 LOC]: Complete the rest of interp_s. \n * The semantics for this are in eval_s in ImpEval.v.\n *\n * Hint: If you are lost, try walking through and understanding how one of the \n * cases that is already filled in (say, Salloc) relates to the corresponding\n * constructors of eval_s (eval_alloc). Also, note that it is OK to have\n * a single case that corresponds to multiple different constructors of eval_s, \n * much like the Scall case that is already filled in.\n *)\nFixpoint interp_s (fuel : nat) (env : env) (s : store) (h : heap)\n  (p : stmt) : option (store * heap) :=\n  match fuel with O => None | S n =>\n    match p with  \n    | Salloc x e1 e2 =>\n        match interp_e s h e1, interp_e s h e2 with\n        | Some (Vint i), Some v =>\n            if Z_le_dec 0 i then\n              Some (update s x (Vaddr (zlen h)), alloc h i v)\n            else\n              None\n        | _, _ => None\n        end\n    | Swrite x e1 e2 =>\n        match lkup s x\n            , interp_e s h e1\n            , interp_e s h e2 with\n        | Some (Vaddr a), Some (Vint i), Some v =>\n            match read h a with\n            | Some (Vint l) =>\n                if Z_le_dec 0 i then\n                  if Z_lt_dec i l then\n                    match write h (Z.succ (a + i)) v with\n                    | Some h' => Some (s, h')\n                    | None => None\n                    end\n                  else\n                    None\n                else\n                  None\n            | _ => None\n            end\n        | _, _, _ => None\n        end\n    | Scall x f es =>\n        match interps_e s h es with\n        | Some vs =>\n            match locate env f with\n            | Some (Func _ params body ret) =>\n                match updates store_0 params vs with\n                | Some sf =>\n                    match interp_s n env sf h body with\n                    | Some (s', h') =>\n                        match interp_e s' h' ret with\n                        | Some v' =>\n                            Some (update s x v', h')\n                        | None => None\n                        end\n                    | None =>\n                        None\n                    end\n                | None =>\n                    None\n                end\n            | None =>\n                if extcall_args_ok f vs h then\n                  let (v', h') := extcall f vs h in\n                  Some (update s x v', h')\n                else\n                  None\n            end\n        | None => None\n        end\n    (* YOUR CODE HERE *)\n    | _ => None\n    end\n  end.\n\nDefinition interp_p (fuel : nat) (p : prog) : option (heap * val) :=\n  match p with\n  | Prog funcs body ret =>\n      match interp_s fuel funcs store_0 heap_0 body with\n      | Some (s', h') =>\n          match interp_e s' h' ret with\n          | Some v' => Some (h', v')\n          | None => None\n          end\n      | None => None\n      end\n  end.\n", "meta": {"author": "abcdabcd987", "repo": "cse505", "sha": "4e12a263abb9423718b45fe7c031963715449f5d", "save_path": "github-repos/coq/abcdabcd987-cse505", "path": "github-repos/coq/abcdabcd987-cse505/cse505-4e12a263abb9423718b45fe7c031963715449f5d/homework/hw4/coq/ImpInterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7179469081163071}}
{"text": "(*\n   CPS\n   2010_10_29\n   *)\n\n\n(* 階乗の再帰版 *)\nFixpoint fact (n : nat) : nat :=\n  match n with\n    | 0 => 1\n    | (S n') => n * fact n'\n  end.\nEval cbv in fact 6.                         (* 720 *)\n\n\n(* CPS 版で書くとこうなる。*)\nFixpoint fact_cps (n : nat) (cont : nat -> nat) : nat :=\n  match n with\n    | 0 => cont 1\n    | (S n') => fact_cps n' (fun (a : nat) => cont (n * a))\n  end.\nEval cbv in fact_cps 6 (fun a => a).        (* 720 *)\n\n\nLemma fact_Sn :\n  forall n,\n    fact (S n) = (S n) * fact n.\nProof.\n  reflexivity.\nQed.\n\n\nLemma fact_cps_Sn :\n  forall n f,\n    fact_cps (S n) f =\n    fact_cps n (fun (r:nat) => (f (S n * r))).\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\n\n(* fact_cps_Sn の実験 *)\nEval cbv in fact_cps 6 (fun (r:nat) => r).  (* 720 *)\nEval cbv in fact_cps 5 (fun (r:nat) => (6 * r)). (* 720 *)\n\n\nLemma eq_fact_fact_cps_aux :\n  forall (n:nat),\n    (forall f, f (fact n) = fact_cps n f) /\\\n    (forall g, g (fact (S n)) = fact_cps (S n) g).\nProof.\n  intros.\n  induction n.\n  (* 再帰の底 *)\n  auto.\n  \n  destruct IHn.\n  split.\n  (* /\\の左 *)\n  apply H0.\n  \n  (* /\\の右 *)\n  intro g.\n  rewrite fact_cps_Sn.\n  rewrite <- H0.\n  rewrite fact_Sn.\n  reflexivity.\nQed.\n\n\nTheorem eq_fact_fact_cps :\n  forall n f, f (fact n) = fact_cps n f.\nProof.\n  intros.\n  destruct (eq_fact_fact_cps_aux n).\n  apply H.\nQed.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/coq_cps_fact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7179409812012486}}
{"text": "(** %\\chapter{Equality and Rewriting Principles}% *)\n\nFrom mathcomp.ssreflect\nRequire Import ssreflect ssrfun eqtype ssrnat ssrbool.\n\nModule Rewriting.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** * Propositional equality in Coq *)\n\nLocate \"_ = _\".\n\n(**\n[[\n\"x = y\" := eq x y    : type_scope\n]]\n*)\n\nPrint eq.\n\n(**\n[[\nInductive eq (A : Type) (x : A) : A -> Prop :=  eq_refl : eq x x\n]]\n\nThe type of its only constructor [eq_refl] is a bit misleading, as it\nlooks like it is applied to two arguments: [x] and ... [x]. To\ndisambiguate it, we shall put some parentheses, so, it fact, it should\nread as\n\n[[\nInductive eq (A : Type) (x : A) : A -> Prop :=  eq_refl : (eq x) x\n]]\n\nThat is, the constructor [eq_refl] delivers an element of type [(eq\nx)], whose _parameter_ is some [x] (and [eq] is directly applied to\nit), and its _index_ (which comes second) is constrained to be [x] as\nwell. That is, case-analysing on an instance of [eq x y] in the\nprocess of the proof construction will inevitably lead the side\ncondition implying that [x] and [y] actually correspond to the _same\nobject_. Coq will take advantage of this fact immediately, by\nperforming the _unification_ and substituting all occurrences of [y]\nin the subsequent goal with [x].  Let us see how it works in practice.\n\n** Case analysis on an equality witness\n\nTo demonstrate the actual proofs on the case analysis by equality, we\nwill have to perform an awkward twist: define _our own_ equality\npredicate. \n\n*)\n\nSet Implicit Arguments.\nInductive my_eq (A : Type) (x : A) : A -> Prop :=  my_eq_refl : my_eq x x.\nNotation \"x === y\" := (my_eq x y) (at level 70).\n\n(** \n\nAs we can see, this definition literally repeats the Coq's standard\ndefinition of propositional equality. The reason for the code\nduplication is that SSReflect provides a specific treatment of Coq's\nstandard equality predicate, so the case-analysis on its instances is\ncompletely superseded by the powerful [rewrite] tactics, which we will\nsee in %Section~\\ref{sec:rewriting}% of this chapter. Alas, this\nspecial treatment also leads to a non-standard behaviour of\ncase-analysis on equality. This is why, for didactical purposes, we\nwill have to stick with or own home-brewed definition until the end of\nthis section.\n\n*)\n\nLemma my_eq_sym A (x y: A) : x === y -> y === x.\n\ncase.\n\n(** \n\n[[\n  A : Type\n  x : A\n  y : A\n  ============================\n   x === x\n]]\n*)\n\ndone.\nQed.\n\n(**\n\nOur next exercise will be to show that the predicate we have just\ndefined implies Leibniz equality. The proof is accomplished in one\nline by first moving the assumption [P x]\nto the top and then case-analysing on the equality, which leads to the\nautomatic replacements of [y] by [x].\n\n*)\n\nLemma my_eq_Leibniz A (x y: A) (P: A -> Prop) : x === y -> P x -> P y. \nProof. by case. Qed.\n\n(** ** Implementing discrimination\n\nAnother important application of the equality predicate family and\nsimilar ones are _proofs by discrimination_, in which the\ncontradiction is reached (i.e., the falsehood is derived) out of the\nfact that two clearly non-equal elements are assumed to be equal. The\nnext lemma demonstrates the essens of the proof by discrimination\nusing the [my_eq] predicate.\n\n*)\n\nLemma disaster : 2 === 1 -> False.\nProof.\nmove=> H.\n\n(**\n\n[[\n  H : 2 === 1\n  ============================\n   False\n]]\n\n*)\n\npose D x := if x is 2 then False else True.\n\n(**\n\n[[\n  H : 2 === 1\n  D := fun x : nat =>\n       match x with\n       | 0 => True\n       | 1 => True\n       | 2 => False\n       | S (S (S _)) => True\n       end : nat -> Prop\n  ============================\n   False\n]]\n*)\n\nhave D1: D 1. \nby [].\n\n(**\n\n[[\n  H : 2 === 1\n  D := ...\n  D1 : D 1\n  ============================\n   False\n]]\n*)\n\ncase: H D1. \n\n(**\n\n[[\n  D := ...\n  ============================\n   D 2 -> False\n]]\n*)\n\nmove=>/=.\n\n(**\n\nThe tactical [/=], coming after [=>] runs all possible simplifications\non the result obtained by the tactics, preceding [=>], finishing the\nproof.\n\n*)\n\ndone.\nQed.\n\n(** \n\n** Reasoning with Coq's standard equality\n\nNow we know what drives the reasoning by equality and discrimination,\nso let us forget about the home-brewed predicate [my_eq] and use the\nstandard equality instead. Happily, the discrimination pattern we used\nto implement \"by hand\" now is handled by Coq/SSReflect automatically,\nso the trivially false equalities deliver the proofs right away by\nsimply typing [done]. \n\n*)\n\nLemma disaster3: 2 = 1 -> False.\nProof. done. Qed.\n\n(** \n\n* Proofs by rewriting \n\nThe vast majority of the steps when constructing real-life proofs in\nCoq are _rewriting_ steps. The general flow of the interactive proof\nis typically targeted on formulating and proving small auxiliary\nhypotheses about equalities in the forward-style reasoning and then\nexploiting the derived equalities by means of rewriting in the goal\nand, occasionally, other assumptions in the context. All rewriting\nmachinery is handled by SSReflect's enhanced [rewrite]%\\ssrt{rewrite}%\ntactics, and in this section we focus on its particular uses.\n\n** Unfolding definitions and in-place rewritings\n\nOne of the common uses of the [rewrite] tactic is to fold/unfold\ntransparent definitions. In general, Coq is capable to perform the\nunfoldings itself, whenever it's required. Nevertheless, manual\nunfolding of a definition might help to understand the details of the\nimplementation, as demonstrated by the following example.\n\n*)\n\nDefinition double A (f: A -> A) (x: A) := f (f x).\n\nFixpoint nat_iter (n : nat) {A} (f : A -> A) (x : A) : A :=\n  if n is S n' then f (nat_iter n' f x) else x.\n\nLemma double2 A (x: A) f t: \n  t = double f x -> double f t = nat_iter 4 f x.\nProof.\n\nmove=>Et; rewrite Et.\n\n(**\n\n[[\n  A : Type\n  x : A\n  f : A -> A\n  t : A\n  Et : t = double f x\n  ============================\n   double f (double f x) = nat_iter 4 f x\n]]\n\nEven though the remaining goal is simple enough to be completed by\n[done], let us unfold both definition to make sure that the two terms\nare indeed equal structurally. Such unfoldings can be _chained_, just\nas any other rewritings.\n\n*)\n\nrewrite /double /nat_iter.\n\n(**\n[[\n  x : A\n  f : A -> A\n  ============================\n   f (f (f (f x))) = f (f (f (f x)))\n]]\n\nAn alternative way to prove the same statement would be to use the\n[->] tactical, which is usually combined with\n[move] or [case], but instead of moving the assumption to the top, it\nmakes sure that the assumption is an equality and rewrites by it.\n\n *)\n\nRestart.\nby move=>->.\nQed.\n\n(** \n\nNotice that the tactical has a companion one [<-], which performs the\nrewriting by an equality assumption from right to left, in contrast to\n[->], which rewrites left to right.\n\nThe reverse operation to folding is done by using [rewrite -/...]\ninstead of [rewrite /...].\n\n** Proofs by congruence and rewritings by lemmas\n\n*)\n\nDefinition f x y :=  x + y.\n\nGoal forall x y, x + y + (y + x) = f y x + f y x.\nProof. \nmove=> x y.\n\nrewrite /f.\n\n(**\n\n[[\n  x : nat\n  y : nat\n  ============================\n   x + y + (y + x) = y + x + (y + x)\n]]\n*)\n\ncongr (_ + _).\n\n(** \n\n[[\n  x : nat\n  y : nat\n  ============================\n   x + y = y + x\n]]\n*)\n\nCheck addnC.\n\n(**\n[[\naddnC\n     : commutative addn\n]]\n*)\n\nPrint ssrfun.commutative.\n\n(** \n[[\nssrfun.commutative = \n  fun (S T : Type) (op : S -> S -> T) => forall x y : S, op x y = op y x\n       : forall S T : Type, (S -> S -> T) -> Prop\n]]\n\nSo, after specializing the definition appropriately, the type of\n[addnC] should be read as:\n\n[[\naddnC\n     : forall n m: nat, n + m = m + n\n]]\n\nNow, we can take advantage of this equality and rewrite by it a part\nof the goal. Notice that Coq will figure out how the\nuniversally-quantified variables should be instantiated (i.e., with\n[y] and [x], respectively):\n\n*)\n\nby rewrite [y + _]addnC.\nQed.\n\nGoal forall x y z, (x + (y + z)) = (z + y + x).\nProof.\nby move=>x y z; rewrite [y + _]addnC; rewrite [z + _ + _]addnC.\nQed.\n\n(** ** Naming in subgoals and optional rewritings\n\nWhen working with multiple cases, it is possible to \"chain\" the\nexecution of several tactics. Then, in the case of a script [tac1;\ntac2], if the goal is replaced by several after applying [tac1], then\n[tac2] will be applied to _all_ subgoals, generated by [tac1]. For\nexample, let us consider a proof of the following lemma from the\nstandrad [ssrnat] %\\ssrm{ssrnat}% module:\n\n*)\n\nLemma addnCA: forall m n p, m + (n + p) = n + (m + p).\nProof.\nmove=>m n. \n\n(** \n\n[[\n  m : nat\n  n : nat\n  ============================\n   forall p : nat, m + (n + p) = n + (m + p)\n]]\n\nThe proof will proceed by induction on [m]. We have already seen the\nuse of the [case] tactics, which just performs the case\nanalysis. Another SSReflect tactic [elim]  generalizes\n[case] by applying the default induction principle ([nat_ind] in this\ncase) with the respect to the remaining goal (that is, the predicate\n[[forall p : nat, m + (n + p) = n + (m + p)]]) is to be proven by\ninduction.  The following sequence of tactics proceeds by induction on\n[m] with the default induction principle. It also names some of the\ngenerated assumptions. \n\n*)\n\nelim: m=>[ | m Hm ] p. \n\n(**\n\nIn particular, the following steps are performed:\n\n- [m] is pushed as a top assumption of the goal;\n- [elim] is run, which leads to generation of the two goals;\n\n  - The first goal is of the shape\n[[\nforall p : nat, 0 + (n + p) = n + (0 + p)\n]]\n\n  - The second goal has the shape\n[[\nforall n0 : nat,\n (forall p : nat, n0 + (n + p) = n + (n0 + p)) ->\n forall p : nat, n0.+1 + (n + p) = n + (n0.+1 + p)\n]]\n\n- The subsequent structured naming [=> [ |m Hm ] p] names zero\n  assumptions in the first goal and the two top assumptions, [m] and\n  [Hm], in the second goal. It then next names the assumption [p] in\n  _both_ goals and moves it to the top.\n\nThe first goal can now be proved by multiple rewritings via the lemma\n[add0n], stating that [0] is the left unit with respect to the\naddition:\n\n*)\n\nby rewrite !add0n.\n\n(**\n\nThe second goal can be proved by a series of rewritings using the fact\nabout the [(_ + 1)] function:\n\n*)\n\n\nby rewrite !addSnnS -addnS.\n\n(**\n\nNotice that the conclusion of the [addnS] lemma is rewritten\nright-to-left.\n\nThe whole proof could be, however, accomplished in one line using the\n_optional_ rewritings. \n*)\n\nRestart.\n\nby move=>m n; elim: m=>[ | m Hm ] p; rewrite ?add0n ?addSnnS -?addnS.\nQed.\n\n(** \n\nNotice that the optional rewritings (e.g., [?addSnnS]) are\nperformed as many times as they can be.\n\n** Selective occurrence rewritings\n\nSometimes, instead of providing an r-pattern to specialize the\nrewriting, it is more convenient to specify, which particular\nsyntactic occurrences in the goal term should be rewritten. This is\ndemonstrated by the following alternative proof of commutativity of\naddition from the lemma [addnCA], which we have proved before:\n\n*)\n\nLemma addnC: forall m n, m + n = n + m.\nProof.\nmove=> m n. \nrewrite -{1}[n]addn0.\nby rewrite addnCA addn0. \nQed.\n\n(** \n\nThe first rewriting with [addn0] \"adds\" [0] to the first occurrence of\n[addn0], so the left-hand side of the equality becomes [m + (n +\n0)]. The next rewriting employs the lemma [addnCA], so we get [n + (m\n+ 0) = n + m] as the goal, and the last one \"removes\" zero, so the\nresult trivially follows.\n\n*)\n\n\n(** * Indexed datatype families as rewriting rules\n\nIn this chapter we have already seen how defining indexed datatype\nfamilies makes it possible for Coq to provide a convenient rewriting\nmachinery, which is implicitly invoked by case analysis on such\nfamilies' refined types, thanks to sophisticated Coq's unification\nprocedure.\n\nAlthough so far this approach has been demonstrated by only one\nindexed type family example---propositional equality, defined by means\nof the [eq] family, in this section, concluding the chapter, we will\nshow how to define other client-specific rewriting rules. Let us start\nfrom a motivating example in the form of an \"obvious\" lemma.\n\n*)\n\nLemma huh n m: (m <= n) /\\ (m > n) -> False.\n\n(**\n\nFrom now on, we will be consistently including yet another SSReflect\nmodules, [ssrbool] and [eqtype], %\\ssrm{ssrbool}\\ssrm{eqtype}% into\nour development. The need for them is due to the smooth combination of\nreasoning with [Prop]ositions and [bool]eans, which is a subject of\nthe next chapter. Even though in SSReflect's library, relations on\nnatural numbers, such as [<=] and [>], are defined as _boolean_\nfunctions, so far we recommend to the reader to think of them as of\npredicates defined in [Prop] and, therefore, valid arguments to the\n[/\\] connective.\n\nAlthough the statement is somewhat obvious, in the setting of Coq's\ninductive definition of natural numbers it should be no big surprise\nthat it is proved by induction. We present the proof here, leaving the\ndetails aside, so the reader could figure them out on his own, as a\nsimple exercise.%\\ssrt{elim}\\ssrt{suff:}\\ssrtl{//}%\n\n*)\n\nProof.\nsuff X: m <= n -> ~(m > n) by case=>/X. \nby elim: m n => [ | m IHm ] [ | n] //; exact: IHm n.\nQed.\n\nDefinition maxn m n := if m < n then n else m.\n\nLemma max_is_max m n: n <= maxn m n /\\ m <= maxn m n.\n\n(** \n\nThe stated lemma [max_is_max] can be, indeed, proved by induction on\n[m] and [n], which is a rather tedious exercise, so we will not be\nfollowing this path.\n*)\n\nAbort.\n\n(* ** Encoding custom rewriting rules *)\n\nInductive leq_xor_gtn m n : bool -> bool -> Set :=\n  | LeqNotGtn of m <= n : leq_xor_gtn m n true false\n  | GtnNotLeq of n < m  : leq_xor_gtn m n false true.\n\n\n(** \n\nHowever, this is not yet enough to enjoy the custom rewriting and case\nanalysis on these two variant. At this moment, the datatype family\n[leq_xor_gtn], whose constructors' indices encode a truth table's\n\"rows\", specifies two substitutions in the case when [m <= n] and [n <\nm], respectively and diagrammatically looks as follows:\n\n<<\n         |   C1  |   C2\n-------------------------\nm <= n   | true  | false\n-------------------------\nn < m    | false | true\n>>\n\nThe boolean values in the cells specify what the values of C1 and C2\nwill be substituted _with_ in each of the two cases. However, the\ntable does not capture, what to substitute them _for_.  Therefore, our\nnext task is to provide suitable variants for C1 and C2, so the table\nwould describe a real situation and capture exactly the \"case\nanalysis\" intuition. This values of the columns are captured by the\nfollowing lemma, which, informally speaking, states that the table\nwith this particular values of C1 and C2 \"makes sense\".\n*)\n\nLemma leqP m n : leq_xor_gtn m n (m <= n) (n < m).\nProof.\nrewrite ltnNge. \nby case X: (m <= n); constructor=>//; rewrite ltnNge X.\nQed.\n\n(*\nMoreover, the lemma [leqP], which we have just proved, delivers the\nnecessary instance of the \"truth\" table, which we can now case-analyse\nagainst.\n\n*)\n\n(** ** Using custom rewriting rules  *)\n\nLemma huh' n m: (m <= n) /\\ (m > n) -> False.\nProof.\n\nmove/andP.  \n\n(**\n\n[[\n  n : nat\n  m : nat\n  ============================\n   m <= n < m -> False\n]]\n\nThe top assumption [m <= n < m] of the goal is just a syntactic sugar\nfor [(m <= n) && (n < m)]. \n*)\n\ncase:leqP.\n\n(** \n\n[[\n  n : nat\n  m : nat\n  ============================\n   m <= n -> true && false -> False\n\nsubgoal 2 (ID 638) is:\n n < m -> false && true -> False\n]]\n\nNow, considering a boolean value [true && false] in a goal simply as a\nproposition [(true && false) = true], the proof is trivial by\nsimplification of the boolean conjunction.\n\n*)\n\ndone.\ndone.\nQed.\n\n(** \n\nThe proof of [huh'] is now indeed significantly shorter than the proof\nof its predecessor, [huh]. However, it might look like the definition\nof the rewriting rule [leq_xor_gtn] and its accompanying lemma [leqP]\nis quite narrowly-scoped, and it is not clear how useful it might be\nfor other proofs.\n*)\n\nLemma max_is_max m n: n <= maxn m n /\\ m <= maxn m n.\nProof.\n(** \n\nThe proof begins by unfolding the definition of [maxn].\n\n*)\nrewrite /maxn.\n\n(** \n[[\n  m : nat\n  n : nat\n  ============================\n   n <= (if m < n then n else m) /\\ m <= (if m < n then n else m)\n]]\n\nWe are now in the position to unleash our rewriting rule, which,\ntogether with simplifications by means of the [//] tactical\n%\\ssrtl{//}% does most of the job.\n\n*)\n\ncase: leqP=>//. \n\n(** \n\n[[\n  m : nat\n  n : nat\n  ============================\n   m < n -> n <= n /\\ m <= n\n]]\n\nThe res of the proof employs rewriting by some trivial lemmas from [ssrnat],\n%\\ssrm{ssrnat}% but conceptually is very easy.\n\n*)\n\nmove=>H; split.\n\nSearch _ (?X <= ?X).\n\nby apply: leqnn.\n\nSearch _ (?x < ?y) (?x <= ?y).\n\nby rewrite ltn_neqAle in H; case/andP: H.\nQed.\n\n(** \n\nThe key advantage we got out of using the custom rewriting rule,\ndefined as an indexed datatype family is lifting the need to prove _by\ninduction_ a statement, which one would intuitively prove by means of\n_case analysis_. In fact, all inductive reasoning was conveniently\n\"sealed\" by the proof of [leqP] and the lemmas it made use of, so just\nthe tailored \"truth table\"-like interface for case analysis was given\nto the client.\n*)\n\n\n(*******************************************************************)\n(**                     * Exercices *                              *)\n(*******************************************************************)\n\n(**\n---------------------------------------------------------------------\nExercise [Discriminating [===]]\n---------------------------------------------------------------------\nLet us change the statement of a lemma [disaster] for a little bit:\n*)\n\nLemma disaster2 : 1 === 2 -> False.\n\n(**\nNow, try to prove it using the same scheme. What goes wrong and how to\nfix it?\n*)\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(**\n---------------------------------------------------------------------\nExercise [Fun with rewritings]\n---------------------------------------------------------------------\nProve the following lemma by using the [rewrite] tactics.\n\n*)\n\nLemma rewrite_is_fun T (f : T -> T -> T) (a b c : T):\n  commutative f -> associative f ->\n  f (f b a) c = f a (f c b).     \nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\n(**\n---------------------------------------------------------------------\nExercise [Properties of maxn]\n---------------------------------------------------------------------\nProve the following lemmas about [maxn].\n*)\n\nLemma max_l m n: n <= m -> maxn m n = m.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma succ_max_distr_r n m : (maxn n m).+1 = maxn (n.+1) (m.+1).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma plus_max_distr_l m n p: maxn (p + n) (p + m) = p + maxn n m.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n\nHint: it might be useful to employ the lemmas [ltnNge], [leqNgt],\n[ltnS] and similar to them from SSReflect's [ssrnat] module. Use the\n[Search] command to find propositions that might help you to deal with\nthe goal.\n\nHint: Forward-style reasoning via [suff] and [have] might be more\nintuitive.\n\nHint: A hypothesis of the shape [H: n < m] is a syntactic sugar for\n[H: n < m = true], since [n < m] in fact has type [bool], as will be\nexplained in the next lecture.\n\n*)\n\n(**\n---------------------------------------------------------------------\nExercise [More custom rewriting rules]\n---------------------------------------------------------------------\n\nLet us consider an instance of a more sophisticated custom rewriting\nrule, which now encodes a three-variant truth table for the ordering\nrelations on natural numbers.\n\n*)\n\nInductive nat_rels m n : bool -> bool -> bool -> Set :=\n  | CompareNatLt of m < n : nat_rels m n true false false\n  | CompareNatGt of m > n : nat_rels m n false true false\n  | CompareNatEq of m = n : nat_rels m n false false true.\n\n(** \n\nThe following rewriting lemma establishes a truth table for\n[nat_rels]. Step through the proofs (splitting the combined tactics\nwhenever it's necessary) to see what's going on.\n\n*)\n\nLemma natrelP m n : nat_rels m n (m < n) (n < m) (m == n).\nProof.\nrewrite ltn_neqAle eqn_leq; case: ltnP; first by constructor.\nby rewrite leq_eqVlt orbC; case: leqP; constructor; first exact/eqnP.\nQed.\n\n\n(** \nLet us define the minimum function [minn] on natural numbers as\nfollows:\n*)\n\nDefinition minn m n := if m < n then m else n.\n\n(**\nProve the following lemma about [minm] and [maxn]:\n*)\n\nLemma addn_min_max m n : minn m n + maxn m n = m + n.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nEnd Rewriting.\n", "meta": {"author": "rodrigogribeiro", "repo": "program-proofs-coq", "sha": "d69fc3382392a4d569b8a77409fc96fd1fa176a7", "save_path": "github-repos/coq/rodrigogribeiro-program-proofs-coq", "path": "github-repos/coq/rodrigogribeiro-program-proofs-coq/program-proofs-coq-d69fc3382392a4d569b8a77409fc96fd1fa176a7/lectures/Rewriting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8333245973817159, "lm_q1q2_score": 0.717940978540511}}
{"text": "Require Import Arith.\nRequire Import Bool.\nRequire Import List.\n\nRequire Import Utils.nat.\n\nInductive type : Set := Nat | Bool.\n\nInductive tbinop : type -> type -> type -> Set :=\n| TPlus  : tbinop Nat Nat Nat\n| TTimes : tbinop Nat Nat Nat\n| TEq    : forall (t:type), tbinop t t Bool\n| TLt    : tbinop Nat Nat Bool\n.\n\nInductive texp : type -> Set :=\n| TNConst : nat  -> texp Nat\n| TBConst : bool -> texp Bool\n| TBinop  : forall (t1 t2 t:type), tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t\n.\n\nArguments TBinop {t1} {t2} {t} _ _ _.\n    \nDefinition typeDenote (t:type) : Set :=\n    match t with\n    | Nat   => nat\n    | Bool  => bool\n    end.\n\nDefinition tbinopDenote (t1 t2 t:type) (b:tbinop t1 t2 t) \n    : typeDenote t1 -> typeDenote t2 -> typeDenote t := \n        match b with \n        | TPlus    => plus\n        | TTimes   => mult\n        | TEq Nat  => beq_nat\n        | TEq Bool => eqb \n        | TLt      => blt_nat\n        end.\n\nArguments tbinopDenote {t1} {t2} {t} _ _ _.\n\nFixpoint texpDenote (t:type) (e:texp t) : typeDenote t :=\n    match e with\n    | TNConst n               => n\n    | TBConst b               => b\n    | @TBinop t1 t2 _ b e1 e2 => \n            tbinopDenote b (texpDenote t1 e1) (texpDenote t2 e2)\n    end.\n    \nArguments texpDenote {t} _.\n\nDefinition tstack := list type.\n\nInductive tinstr : tstack -> tstack -> Set :=\n| TiNConst : forall (s:tstack) (n:nat) , tinstr s (Nat :: s)\n| TiBConst : forall (s:tstack) (b:bool), tinstr s (Bool :: s)\n| TiBinop  : forall (t1 t2 t:type) (s:tstack), \n    tbinop t1 t2 t -> tinstr (t1 :: t2 :: s) (t :: s) \n.\n\nArguments TiBinop {t1} {t2} {t} _ _. \n\nInductive tprog : tstack -> tstack -> Set :=\n| TNil  : forall (s:tstack), tprog s s\n| TCons : forall (s1 s2 s3:tstack), tinstr s1 s2 -> tprog s2 s3 -> tprog s1 s3\n.\n\nArguments TCons {s1} {s2} {s3} _ _.\n\nFixpoint vstack (ts:tstack) : Set :=\n    match ts with \n    | nil       => unit\n    | t :: ts'  => prod (typeDenote t) (vstack ts')\n    end.\n\nDefinition tinstrDenote (s1 s2:tstack) (i:tinstr s1 s2) \n    : vstack s1 -> vstack s2 :=\n    match i with\n    | TiNConst _ n        => fun s => (n,s)\n    | TiBConst _ b        => fun s => (b,s)\n    | @TiBinop _ _ _ _ b  => fun s =>\n        let '(v1, (v2, s')) := s in \n            ((tbinopDenote b) v1 v2, s')\n    end.\n\nArguments tinstrDenote {s1} {s2} _ _.\n\nFixpoint tprogDenote (s1 s2:tstack) (p:tprog s1 s2) \n    : vstack s1 -> vstack s2 :=\n    match p with \n    | TNil _               => fun s => s\n    | @TCons s1 s2 s3 i p' => fun s => tprogDenote s2 s3 p' (tinstrDenote i s)  \n    end. \n\nArguments tprogDenote {s1} {s2} _ _.\n\nFixpoint tconcat (t1 t2 t3:tstack) (p:tprog t1 t2) \n    : tprog t2 t3 -> tprog t1 t3 :=\n    match p with\n    | TNil _               => fun q => q\n    | @TCons s1 s2 s3 i p' => fun q => TCons i (tconcat s2 s3 _ p' q)\n    end.    \n\nArguments tconcat {t1} {t2} {t3} _ _.\n\nFixpoint tcompile (t:type) (e:texp t) (ts:tstack) : tprog ts (t :: ts) :=\n    match e with\n    | TNConst n             => TCons (TiNConst _ n) (TNil _)\n    | TBConst b             => TCons (TiBConst _ b) (TNil _)\n    | @TBinop _ _ _ b e1 e2 => tconcat (tcompile _ e2 _) \n        (tconcat (tcompile _ e1 _) (TCons (TiBinop _ b) (TNil _)))\n    end. \n\nArguments tcompile {t} _ _.\n\n\nLemma tconcat_correct: \n    forall (t1 t2 t3:tstack) (p:tprog t1 t2) (q:tprog t2 t3) (s:vstack t1),\n    tprogDenote (tconcat p q) s = tprogDenote q (tprogDenote p s).\nProof.\n    intros t1 t2 t3 p q. induction p as [t|s1 s2 s3 i r IH]; intros s; simpl.\n    - reflexivity.\n    - rewrite IH. reflexivity.\nQed.\n\n\n\nLemma tcompile_correct': forall (t:type) (e:texp t)(ts:tstack)(s:vstack ts),\n    tprogDenote (tcompile e ts) s = (texpDenote e, s).\nProof.\n    intros t e. induction e as [n|b|t1 t2 t3 b e1 H1 e2 H2]; intros ts s; simpl.\n    - reflexivity.\n    - reflexivity.\n    - rewrite tconcat_correct. rewrite H2.\n      rewrite tconcat_correct. rewrite H1.\n      reflexivity.\nQed.\n\nTheorem tcompile_correct: forall (t:type) (e:texp t),\n    tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\nProof.\n    intros t e. apply tcompile_correct'.\nQed.\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/cpdt/typed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7179409761537245}}
{"text": "Require Import List.\n\n(** A type for triangular arrays *)\n\n\nInductive triangular (A B : Type) :=\n| base : B -> triangular A B\n| line : B -> triangular A (A * B) -> triangular A B. \n\nDefinition triangle (A: Type) := triangular A A.\n\nArguments base {A B} _.\nArguments line {A B} _ _.\n\nExample t1 : triangle  nat :=\nbase 6.\n\nExample t2 : triangle nat :=\n  line 5\n (base (1, 1)).\n\nExample t3 :triangle nat  :=\n line 6 \n(line (5, 3) \n(line (5, (7, 8)) \n(base (1, (2, (3, 4)))))).\n\n\n\nFixpoint height {A B : Type}(t : triangular A B) : nat :=\n  match t with base  _ => 1\n             | line  _ m' => 1 + height m'\n  end.\n\nExample test1 :  height t3 = 4.\nProof.  reflexivity. Qed.\n\n\n(** getting the vertical edge  of a triangle *)\n\nFixpoint left_edge_aux {A B : Type}(m : triangular A B): B * list A :=\nmatch m with base b => (b,nil)\n           | line b t' => match left_edge_aux t' with (x,y,l) => (b,(x::l)) end\nend.\n\n\nDefinition left_edge {A:Type} (m: triangle A) :=\n  match left_edge_aux m with (a,l)=> a::l end.\n\n\nExample test2 : left_edge t3 = 6::5::5::1::nil.\nProof. reflexivity. Qed.\n\n(* getting the lowest row *)\n\nFixpoint the_base_aux {A B : Type}(m : triangular A B)(f : B -> list A) :  list A :=\nmatch m with base b => f b\n           | line b t' => the_base_aux t' (fun p : A * B => fst p :: f (snd p))\nend.\n\nDefinition the_base {A:Type} (m: triangle  A) :=\n the_base_aux m (fun a:A => a::nil).\n\nExample test3 : the_base t3 = 1 :: 2 :: 3 :: 4 :: nil.\nProof. reflexivity. Qed.\n\n(** getting the diagonal *)\n\nFixpoint diagonal {A B : Type}(m : triangular A B) :  list B :=\nmatch m with base b =>  b :: nil\n           | line b t' => b :: map snd (diagonal  t')\nend.\n\n\nExample test4 : diagonal  t3 = 6 :: 3 :: 8 :: 4 :: nil.\nProof. reflexivity. Qed.\n\n\n(** flattening a triangle *)\n\n\nFixpoint flatten_aux {A}{B}(f: B -> list A) (m : triangular A B) : list A :=\n match m with base  b => f b\n            | line   b m' => f b ++ flatten_aux (fun x=> fst x :: (f (snd x))) m'\n end.\n\n\nDefinition flatten {A:Type} (m : triangle A) : list A :=\nflatten_aux (fun a => a::nil) m.\n\nExample test5 : flatten t3 =\n                6 :: 5 :: 3 :: 5 :: 7 :: 8 :: 1 :: 2 :: 3 :: 4 :: nil.\nProof. reflexivity. Qed.\n\n\n(** building a triangle with the same data everywhere *)\n\n\nFixpoint uniform_aux {A B : Type}(a:A)(b:B)(n:nat) : triangular A B :=\n  match n with 0 => base  b\n             | S p => line  b (uniform_aux a (a,b)  p)\n end.\n\nDefinition uniform {A:Type}(a:A)(n:nat) : triangle A :=\nuniform_aux a a n.\n\nExample test6 : uniform 41 3 =\n line 41\n(line (41, 41)\n(line (41, (41, 41)) \n(base (41, (41, (41, 41)))))).\nProof. reflexivity. Qed.\n\n\n(** what does this function compute ? *)\n\nFixpoint mystery_aux {A B : Type}(f:A->A)(a:A)(b:B)(n:nat) : triangular A B :=\n  match n with 0 => base  b\n             | S p => line  b (mystery_aux f (f a) (f a, b)   p)\n end.\n\nDefinition mystery {A:Type} (f : A -> A)(a:A) (n:nat) : triangle A :=\n mystery_aux f a a 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/ch14_fundations_of_inductive_types/SRC/triangular.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7177743047651324}}
{"text": "Require Coq.extraction.Extraction.\nExtraction Language OCaml.\n\nInductive term : Type :=\n| tru\n| fls\n| If (t1 t2 t3: term)\n| O\n| succ (t1: term)\n| pred (t1: term)\n| iszero (t1: term).\n\n\nFixpoint isnumericval (t: term): bool :=\n  match t with\n  | O => true\n  | succ t1 => isnumericval t1\n  | _ => false\n  end.\n\nDefinition isval (t: term) : bool :=\n  match t with\n  | tru => true\n  | fls => true\n  | _ => isnumericval t\n  end.\n\nInductive optiont : Type :=\n| Some (t: term)\n| None.\n\nFixpoint eval1 (t: term) : optiont :=\n  match t with\n  | If t1 t2 t3 =>\n    if (isval t1) then\n      match t1 with\n      | tru => Some t2\n      | fls => Some t3\n      | _ => None\n      end else\n      match (eval1 t1) with\n      | Some t1' => Some (If t1' t2 t3)\n      | _ => None\n      end\n  | succ t1 =>\n    if isnumericval t1 then\n      None else\n      match (eval1 t1) with\n      | Some t1' => Some (succ t1')\n      | _ => None\n      end\n  | pred t1 =>\n    if (isnumericval t1) then\n      match t1 with\n      | O => Some O\n      | succ nv1 => Some nv1\n      | _ => None\n      end else\n      match (eval1 t1) with\n      | Some t1' => Some (pred t1')\n      | _ => None\n      end\n  | iszero t1 =>\n    if (isnumericval t1) then\n      match t1 with\n      | O => Some tru\n      | succ _ => Some fls\n      | _ => None\n      end else\n      match (eval1 t1) with\n      | Some t1' => Some (iszero t1')\n      | _ => None\n      end\n  | _ => None\n  end.\n\n\nLtac solve_by_inverts n :=\n  match goal with | H : ?T |- _ =>\n  match type of T with Prop =>\n    solve [\n      inversion H;\n      match n with S (S (?n')) => subst; solve_by_inverts (S n') end ]\n  end end.\n\nLtac solve_by_invert :=\n  solve_by_inverts 1.\n\nTheorem eval1value : forall t1,\n    isval t1 = true -> eval1 t1 = None.\nProof.\n  intros. induction t1; try solve_by_inverts 2; try reflexivity.\n  inversion H. simpl. rewrite H1; auto.\nQed.\n\n\nExtraction \"ocaml/src/eval.ml\" eval1.\n\nInductive NatValue: term -> Prop :=\n| nv_O : NatValue O\n| nv_S : forall nv1, NatValue nv1 -> NatValue (succ nv1).\n\nInductive Pvalue: term -> Prop :=\n| v_tru : Pvalue tru\n| v_fls : Pvalue fls\n| v_nat : forall t1, NatValue t1 -> Pvalue t1.\n\nReserved Notation \" t '-->' t' \" (at level 40).\nInductive step: term -> term -> Prop :=\n| E_IfTrue : forall t2 t3,\n    If tru t2 t3 --> t2\n| E_IfFalse : forall t2 t3,\n    If fls t2 t3 --> t3\n| E_If : forall t1 t1' t2 t3,\n    t1 --> t1' ->\n    If t1 t2 t3 --> If t1' t2 t3\n| E_Succ : forall t1 t1',\n    t1 --> t1' -> succ t1 --> succ t1'\n| E_PredZero :\n    pred O --> O\n| E_PredSucc : forall nv1,\n    NatValue nv1 -> pred (succ nv1) --> nv1\n| E_Pred : forall t1 t1',\n    t1 --> t1' -> pred t1 --> pred t1'\n| E_IsZeroZero :\n    iszero O --> tru\n| E_IsZeroSucc : forall nv1,\n    NatValue nv1 -> iszero (succ nv1) --> fls\n| E_IsZero : forall t1 t1',\n    t1 --> t1' -> iszero t1 --> iszero t1'\n\n  where \" t '-->' t' \" := (step t t').\n\n\nLemma nat_value : forall t,\n    NatValue t <-> isnumericval t = true.\nProof.\n  split; intros.\n  -\n    induction H; auto.\n  -\n    induction t; try solve_by_invert.\n    apply nv_O. inversion H. apply IHt in H1. apply nv_S; auto.\nQed.\n\nLemma isval_Pvalue : forall t,\n    isval t = true <-> Pvalue t.\nProof.\n  split; intros.\n  -\n    induction t; try solve_by_invert.\n    apply v_tru. apply v_fls.\n    apply v_nat; apply nv_O.\n    inversion H. apply nat_value in H1. apply v_nat. apply nv_S; auto.\n  -\n    induction H; auto.\n    unfold isval. inversion H; auto.\n    simpl. apply nat_value; auto.\nQed.\n\nTheorem step_eval1_correct : forall t1 t1',\n    eval1 t1 = Some t1' <-> t1 --> t1'.\nProof.\n  split.\n  -\n    intros. generalize dependent t1'.\n    induction t1; intros; try solve_by_invert.\n    +\n      inversion H. \n      induction (isval t1_1).\n      destruct t1_1; try solve_by_invert.\n      inversion H1. apply E_IfTrue.\n      inversion H1. apply E_IfFalse.\n      induction (eval1 t1_1) eqn:IHt1; try solve_by_invert.\n      inversion H1. inversion H1. apply E_If. apply IHt1_1; auto.\n    +\n      inversion H.\n      destruct (isnumericval t1) eqn:IHnum. inversion H1.\n      destruct (eval1 t1) eqn:IH. inversion H1. apply E_Succ. apply IHt1; auto.\n      inversion H1.\n    +\n      inversion H. destruct (isnumericval t1) eqn:IHnum; try solve_by_invert.\n      destruct t1; try solve_by_invert. inversion H1. apply E_PredZero.\n      inversion H1. apply E_PredSucc. inversion IHnum. apply nat_value; subst; auto.\n      destruct (eval1 t1); try solve_by_invert.\n      inversion H1. apply E_Pred. apply IHt1; auto.\n    +\n      inversion H.\n      destruct (isnumericval t1) eqn:IHnum.\n      destruct t1; try solve_by_invert.\n      inversion H1. apply E_IsZeroZero.\n      inversion H1. apply E_IsZeroSucc. inversion IHnum. apply nat_value; auto.\n      destruct (eval1 t1); try solve_by_invert.\n      inversion H1. apply E_IsZero. apply IHt1; auto.\n  -\n    intros. induction H; try reflexivity.\n    +\n      simpl. destruct (isval t1) eqn:IHv.\n      destruct t1; try solve_by_invert. inversion H. inversion IHstep.\n      inversion IHv. rewrite H5 in H4. inversion H4.\n      rewrite IHstep; auto.\n    +\n      simpl. destruct (isnumericval t1) eqn:IHnum.\n      pose proof (eval1value t1).\n      rewrite H0 in IHstep.\n      inversion IHstep.\n      unfold isval. destruct t1; try solve_by_invert; auto.\n\n      destruct (eval1 t1); try solve_by_invert.\n      inversion IHstep; auto.\n    +\n      simpl. apply nat_value in H. rewrite H; auto.\n    +\n      simpl. destruct (isnumericval t1) eqn:IHnum.\n      destruct t1; try solve_by_invert.\n      pose proof (eval1value (succ t1)).\n      rewrite H0 in IHstep. inversion IHstep.\n      simpl. inversion IHnum; auto.\n      destruct (eval1 t1); try solve_by_invert.\n      inversion IHstep; auto.\n    +\n      simpl.\n      destruct (isnumericval nv1) eqn:IHnum; try solve_by_invert; auto.\n      apply nat_value in H. rewrite H in IHnum; inversion IHnum.\n    +\n      simpl.\n      destruct (isnumericval t1) eqn:IHnum.\n      pose proof (eval1value t1). rewrite H0 in IHstep. inversion IHstep.\n      unfold isval. destruct t1; try solve_by_invert; auto.\n      destruct (eval1 t1); try solve_by_invert. inversion IHstep; auto.\nQed.\n\n\n\nDefinition relation (X : Type) := X -> X -> Prop.\n\nInductive multi {X : Type} (R : relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nNotation multistep := (multi step).\nNotation \"t1 '-->*' t2\" := (multistep t1 t2) (at level 40).\n\n\n(*停止する保証がないのでbigstepは無理そう*)\n(*\nFixpoint bstep (t: term) : optiont :=\n  match t with\n  | tru => Some tru\n  | fls => Some fls\n  | O => Some t\n  | If t1 t2 t3 =>\n    match (eval1 t1) with\n    | Some t1' =>\n      if (isval t1') then\n        match t1' with\n        | tru => bstep t2\n        | fls => bstep t3\n        | _ => None\n        end else bstep (If t1' t2 t3)\n    | None => None\n    end\n  | succ t1 =>\n    match (eval1 t1) with\n    | Some t1' =>\n      if (isval t1') then\n        match t1' with\n        | O => Some (succ O)\n        | succ _ => Some (t1')\n        | _ => None\n        end else bstep (succ t1')\n    | None => None\n    end\n  | pred t1 =>\n    match (eval1 t1) with\n    | Some t1' =>\n      if (isval t1') then\n        match t1' with\n        | O => Some O\n        | succ nv1 => Some nv1\n        | _ => None\n        end else bstep (pred t1')\n    | _ => None\n    end\n  | iszero t1 =>\n    match (eval1 t1) with\n    | Some t1' =>\n      if (isval t1') then\n        match t1' with\n        | O => Some tru\n        | succ _ => Some fls\n        | _ => None\n        end else bstep (iszero t1')\n    | _ => None\n    end\n  end.\n*)\n", "meta": {"author": "NeM-T", "repo": "Formalizing-TaPL", "sha": "2a4dba29d0850a7494c7fd52c0daf4bbb3879691", "save_path": "github-repos/coq/NeM-T-Formalizing-TaPL", "path": "github-repos/coq/NeM-T-Formalizing-TaPL/Formalizing-TaPL-2a4dba29d0850a7494c7fd52c0daf4bbb3879691/arith/chap4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7177743010101374}}
{"text": "Require Export List Omega.\nImport ListNotations.\nFrom icl Require Import util assignments formulas number_of_models.\n\n(** * Algorithm 1 *)\n(* Algorithm 1 just computes all the possible assignments \n   and then filters all non-satisfying assignments. *)\nSection Algorithm1.\n\n  (* Generate all the possible assignments on a given set of variables. *)\n  Fixpoint all_assignments_on (vs : variables) : assignments :=\n    match vs with\n    | [] => [[]] | v::vs =>\n                  map (cons (v,false)) (all_assignments_on vs) ++\n                      map (cons (v,true)) (all_assignments_on vs)\n    end.\n\n  Lemma vars_of_assignment_in_all_assignments_on:\n    forall (vs : variables) (α : assignment),\n      α el all_assignments_on vs ->\n      equi (vars_in α) vs.\n  Proof.\n    induction vs; intros ? EL; simpl in EL.\n    - destruct EL as [EL|F]; [subst |exfalso]; auto.\n      split; intros x EL; destruct EL.\n    - apply in_app_iff in EL; destruct EL as [EL|EL].\n      + apply in_map_iff in EL; destruct EL as [α_tl [EQ EL]]; subst α.\n        specialize (IHvs _ EL); simpl; auto using equi_cons.\n      + apply in_map_iff in EL; destruct EL as [α_tl [EQ EL]]; subst α.\n        specialize (IHvs _ EL); simpl; auto using equi_cons.\n  Qed.\n  \n  Corollary assignment_in_all_assignments_on_sets_all_variables:\n    forall (ϕ : formula) (α : assignment),\n      α el all_assignments_on (formula_vars ϕ) ->\n      sets_all_variables α ϕ.\n  Proof.\n    intros ? ? EL.\n    apply vars_of_assignment_in_all_assignments_on in EL; rename EL into EQU. \n    intros v EL; apply EQU.\n    apply nodup_In; assumption.\n  Qed.\n  \n  Lemma size_of_list_of_all_assignments_on:\n    forall (vs : variables),\n      length (all_assignments_on vs) = Nat.pow 2 (length vs).\n  Proof.\n    induction vs; simpl; auto.\n    rewrite app_length, !map_length, <- plus_n_O, <- IHvs; auto.\n  Qed.\n \n  Lemma list_of_all_assignments_dupfree:\n    forall (vs : variables),\n      NoDup vs ->\n      dupfree vs (all_assignments_on vs). \n  Proof.\n    intros ? ND; split.\n    { induction vs.\n      - constructor; [intros C; easy | constructor ].\n      - apply NoDup_cons_iff in ND; destruct ND as [NEL ND].\n        feed IHvs; [assumption | ].\n        apply nodup_app_of_map_cons; easy.\n    } \n    { induction vs; intros α1 α2 EL1 EL2 NEQ EQ.\n      { inversion EL1; inversion EL2; subst; auto. }\n      { apply NoDup_cons_iff in ND; destruct ND as [NEL ND].\n        feed IHvs; auto.\n        simpl in EL1, EL2; apply in_app_iff in EL1; apply in_app_iff in EL2.\n        destruct EL1 as [EL1|EL1], EL2 as [EL2|EL2];\n          apply in_map_iff in EL1; apply in_map_iff in EL2;\n            destruct EL1 as [α1_tl [EQ1 EL1]], EL2 as [α2_tl [EQ2 EL2]].\n        { rewrite <-EQ1, <-EQ2 in EQ, NEQ; clear EQ1 EQ2 α1 α2.\n          rename α1_tl into α1, α2_tl into α2.\n          apply neq_cons in NEQ.\n          specialize (IHvs _ _ EL1 EL2 NEQ).\n          apply IHvs; clear IHvs.\n          eapply equiv_assignments_cancel_cons; eauto 2.\n        }\n        { rewrite <-EQ1, <-EQ2 in EQ, NEQ; clear EQ1 EQ2 NEQ.\n          apply non_equiv_assignments in EQ; assumption. }\n        { rewrite <-EQ1, <-EQ2 in EQ, NEQ; clear EQ1 EQ2 NEQ.\n          apply non_equiv_assignments in EQ; assumption. }\n        { rewrite <-EQ1, <-EQ2 in EQ, NEQ; clear EQ1 EQ2 α1 α2.\n          rename α1_tl into α1, α2_tl into α2.\n          apply neq_cons in NEQ.\n          specialize (IHvs _ _ EL1 EL2 NEQ).\n          apply IHvs; clear IHvs.\n          eapply equiv_assignments_cancel_cons; eauto 2.\n        } \n      }\n    }\n  Qed.\n\n  (* Any assignment that sets variables vs has an equivalen assignment \n     that belongs to the set with all assignments on variables vs. *)\n  Definition set_with_all_assignments_on (vs : variables) (αs : assignments) :=\n    set_with_all (equiv_assignments vs) (fun α => vs ⊆ vars_in α) αs.\n \n  Lemma all_assignments_in_all_assignments_on:\n    forall (vs : variables), \n      set_with_all_assignments_on vs (all_assignments_on vs).\n  Proof.\n    induction vs; intros α INCL.\n    { exists []; split.\n      - intros v EL; inversion EL.\n      - left; auto. }\n    { specialize (IHvs α); feed IHvs; auto.\n      { intros v EL; apply INCL; right; auto. }\n      destruct IHvs as [β [EQU IN]].\n      destruct (mapsto_total α a) as [[[EL MAP]|[NEL2 NMAP]]|[EL MAP]].\n      { exists ((a,true)::β); split.\n        { intros v EL2; destruct EL2 as [EQ|EL2]; subst; intros b; split; intros EV.\n          - apply (mapsto_injective _ _ _ _ MAP) in EV; subst; constructor.\n          - inversion EV; subst; [ |exfalso]; auto.\n          - decide (a = v) as [EQ|NEQ]; [subst | ].\n            apply EQU in MAP; apply EQU in EV; auto.\n            apply (mapsto_injective _ _ _ _ MAP) in EV; subst; constructor.\n            constructor; auto; apply EQU; auto.\n          - decide (a = v) as [EQ|NEQ]; [subst | ].\n            + inversion EV; subst; [ | exfalso]; auto.\n            + inversion EV; subst; [exfalso | apply EQU]; auto.\n        } \n        { simpl; apply in_app_iff; right.\n          apply in_map_iff; exists β; split; auto.\n        } \n      }\n      { exfalso; apply NEL2; apply INCL; left; auto. } \n      { exists ((a,false)::β); split.\n        { intros v EL2; destruct EL2 as [EQ|EL2]; subst; intros b; split; intros EV.\n          - apply (mapsto_injective _ _ _ _ MAP) in EV; subst; constructor.\n          - inversion EV; subst; [ |exfalso]; auto.\n          - decide (a = v) as [EQ|NEQ]; [subst | ].\n            apply EQU in MAP; apply EQU in EV; auto.\n            apply (mapsto_injective _ _ _ _ MAP) in EV; subst; constructor.\n            constructor; auto; apply EQU; auto.\n          - decide (a = v) as [EQ|NEQ]; [subst | ].\n            + inversion EV; subst; [ | exfalso]; auto.\n            + inversion EV; subst; [exfalso | apply EQU]; auto.\n        } \n        { simpl; apply in_app_iff; left.\n          apply in_map_iff; exists β; split; auto.\n        } \n      }      \n    }\n  Qed.\n\n  Definition compute_formula (ϕ : formula) (α : assignment) (SET : sets_all_variables α ϕ):\n    { b : bool | formula_eval ϕ α b }.\n  Proof.\n    induction ϕ.\n    - exists false; auto. \n    - exists true; auto.\n    - feed (SET v).\n      { left; auto. }\n      destruct (mapsto_dec α v SET) as [M|M]; [exists true| exists false]; auto. \n    - destruct IHϕ as [b EV].\n      simpl in SET; assumption.\n      exists (negb b); constructor; rewrite Bool.negb_involutive; auto.\n    - apply inclusion_app in SET; destruct SET.\n      destruct IHϕ1 as [b1 EV1]; destruct IHϕ2 as [b2 EV2]; auto.\n      exists (andb b1 b2).\n      destruct b1, b2; simpl in *; try(constructor; auto; fail). \n    - simpl in SET; apply inclusion_app in SET; destruct SET.\n      destruct IHϕ1 as [b1 EV1]; destruct IHϕ2 as [b2 EV2]; auto.\n      exists (orb b1 b2).\n      destruct b1, b2; simpl in *; try(constructor; auto; fail).\n  Defined.\n    \n  Definition formula_sat_filter (ϕ : formula) (α : assignment) : bool :=\n    match sets_all_variables_dec ϕ α with \n    | left _ SETS => let '(exist _ b _) := compute_formula ϕ α SETS in b\n    | right _ => false\n    end.\n  \n  (* Now for a function ϕ, the algorithm \n     1) Generates the list of all assignments on ϕ's variables\n     2) Keeps assignment such that ℇ ϕ α ≡ true. *)\n  Definition algorithm1 (ϕ : formula) : { n : nat | #sat ϕ ≃ n }.\n  Proof. \n    set (vars := formula_vars ϕ). \n    assert(EX: { αs | list_of_all_sat_assignments ϕ αs }).\n    { exists (filter (fun α => formula_sat_filter ϕ α) (all_assignments_on vars)).\n      split;[split | split].\n      { apply nodup_filter.\n        destruct(list_of_all_assignments_dupfree vars).\n        - apply NoDup_nodup.\n        - assumption.\n      }\n      { intros α1 α2 EL1 EL2 NEQ EQU.\n        apply filter_In in EL1; destruct EL1 as [EL1 SAT1].\n        apply filter_In in EL2; destruct EL2 as [EL2 SAT2].\n        apply equiv_assignments_nodup in EQU.\n        apply list_of_all_assignments_dupfree in EQU; try (apply NoDup_nodup || auto).\n      }\n      { intros α EL.  \n        apply filter_In in EL; destruct EL as [EL TR]. \n        unfold formula_sat_filter in *; destruct (sets_all_variables_dec ϕ α) as [D|D]; [ | easy].\n        destruct (compute_formula ϕ α D) as [b EV]; subst b.\n        split; assumption.\n      } \n      { intros α [SETS SAT].\n        assert(H := all_assignments_in_all_assignments_on vars α).\n        feed H; [eapply incl_tran; eauto; apply incl_nodup| ]. \n        destruct H as [β [EQ EL]].\n        exists β; split.\n        - clear EL; intros ? EL b; split; intros EV.\n          all: apply EQ; auto; apply nodup_In; auto.\n        - apply filter_In; split; auto.\n          unfold formula_sat_filter; destruct (sets_all_variables_dec ϕ β) as [S|S].\n          + apply equiv_assignments_nodup in EQ.\n            destruct (compute_formula ϕ β S) as [b EV].\n            apply formula_eval_assignment_transfer with (β := β) in SAT; auto.\n            eapply formula_eval_injective; eauto 2.\n          + exfalso; apply S.\n            auto using assignment_in_all_assignments_on_sets_all_variables. \n      }\n    }\n    destruct EX as [αs AS]; exists (length αs); exists αs; split; auto.\n  Defined.\n\n  Section Tests.\n\n    Let x1 := [|V 1|].\n    Let x2 := [|V 2|].\n    Let x3 := [|V 3|].\n    Let x4 := [|V 4|].\n    Let x5 := [|V 5|].\n    \n    Let or_n n := fold_left (fun ϕ x => ϕ ∨ [|V x|]) (range 1 n) F.\n    Let xor_n n := fold_left (fun ϕ x => ϕ ⊕ [|V x|]) (range 1 n) F.\n    \n    (* Compute (proj1_sig (algorithm1 x1)). => 1 : nat *)\n    (* Compute (proj1_sig (algorithm1 (x1 ∨ x2 ∨ x3 ∨ x4 ∨ x5))). => 31 : nat *)\n    (* Compute (proj1_sig (algorithm1 (x1 ⊕ x2 ⊕ x3 ⊕ x4 ⊕ x5))). => 16 : nat *)\n    (* Compute (proj1_sig (algorithm1 (or_n 8))). => 255 : nat *)\n    \n    (* It already takes a few seconds. *)\n    (* Compute (proj1_sig (algorithm1 (xor_n 8))). => 128 : nat *)\n                \n  End Tests.\n  \nEnd Algorithm1.\n\n(** * Algorithm 2: *)\n(** With transformation ϕ = (ϕ[x ↦ T] ∧ x) ∨ (ϕ[x ↦ F] ∧ ¬x). *)\nSection Algorithm2.\n  (* The main idea of the algorithm is the following: \n       #sat F = 0\n       #sat T = 1 \n       #sat ϕ = #sat (x ∧ ϕ[x ↦ T] ∨ ¬x ∧ ϕ[x ↦ F]) \n              = #sat (x ∧ ϕ[x ↦ T]) + #sat (¬x ∧ ϕ[x ↦ F])\n              = #sat (ϕ[x ↦ T]) + #sat (ϕ[x ↦ F]).                *)\n\n  (* We start from \"switch\"-lemma which claims that \n     ϕ is equivalent to (ϕ[x ↦ T] ∧ x) ∨ (ϕ[x ↦ F] ∧ ¬x).  *)\n  Section Switch.\n\n    (* For any formula ϕ and any assignments α which sets x to true \n       formulas ϕ and ϕ[x ↦ T] evaluates to the same value. *) \n    Lemma formula_eval_subst_T:\n      forall (ϕ : formula) (x : variable) (α : assignment) (b : bool),\n        x / α ↦ true ->\n        ℇ (ϕ) α ≡ b <-> ℇ (ϕ [x ↦ T]) α ≡ b.\n    Proof.\n      intros ϕ; induction ϕ; intros x α b M; split; intros EV.\n      all: try(inversion_clear EV; constructor; fail).\n      all: try(inversion_clear EV; simpl;\n               [ eapply ev_conj_t; [eapply IHϕ1|eapply IHϕ2]\n               | eapply ev_conj_fl; eapply IHϕ1\n               | eapply ev_conj_fr; eapply IHϕ2]; eauto).\n      all: try(inversion_clear EV; simpl;\n               [ eapply ev_disj_f; [eapply IHϕ1|eapply IHϕ2]\n               | eapply ev_disj_tl; eapply IHϕ1\n               | eapply ev_disj_tr; eapply IHϕ2]; eauto).\n      all: try(simpl; constructor; eapply IHϕ; [ | inversion_clear EV]; eauto).\n      - inversion_clear EV.\n        simpl in *; decide (x = v) as [EQ|NEQ];\n          [subst; apply (mapsto_injective _ _ _ _ H) in M; subst| ]; auto.\n      - simpl in *; decide (x = v) as [EQ|NEQ]; [subst; inversion_clear EV| ]; auto.\n    Qed. \n\n    (* Similarly for false. For any formula ϕ and any assignments α which\n       sets x to false formulas ϕ and ϕ[x ↦ F] evaluates to the same value. *) \n    Lemma formula_eval_subst_F:\n      forall (ϕ : formula) (x : variable) (α : assignment) (b : bool),\n        x / α ↦ false ->\n        ℇ (ϕ) α ≡ b <-> ℇ (ϕ [x ↦ F]) α ≡ b.\n    Proof.\n      intros ϕ; induction ϕ; intros x α b M; split; intros EV.\n      all: try(inversion_clear EV; constructor; fail).\n      all: try(inversion_clear EV; simpl;\n               [ eapply ev_conj_t; [eapply IHϕ1|eapply IHϕ2]\n               | eapply ev_conj_fl; eapply IHϕ1\n               | eapply ev_conj_fr; eapply IHϕ2]; eauto).\n      all: try(inversion_clear EV; simpl;\n               [ eapply ev_disj_f; [eapply IHϕ1|eapply IHϕ2]\n               | eapply ev_disj_tl; eapply IHϕ1\n               | eapply ev_disj_tr; eapply IHϕ2]; eauto).\n      all: try(simpl; constructor; eapply IHϕ; [ | inversion_clear EV]; eauto).\n      - inversion_clear EV.\n        simpl in *; decide (x = v) as [EQ|NEQ];\n          [subst; apply (mapsto_injective _ _ _ _ H) in M; subst| ]; auto.\n      - simpl in *; decide (x = v) as [EQ|NEQ]; [subst; inversion_clear EV| ]; auto.\n    Qed. \n\n    (* Proof by case analysis on [x / α ↦ b] and b. *)\n    Lemma switch:\n      forall (ϕ : formula) (x : variable) (α : assignment) (b : bool),\n        x el vars_in α ->\n        ℇ (ϕ) α ≡ b <-> ℇ ([|x|] ∧ ϕ[x ↦ T] ∨ ¬[|x|] ∧ ϕ[x ↦ F]) α ≡ b.\n    Proof.\n      intros ϕ ? ? ? SET.\n      destruct (mapsto_dec _ _ SET); destruct b; split; intros EV.\n      - apply ev_disj_tl; constructor; [ |apply formula_eval_subst_T]; auto.\n      - inversion_clear EV; inversion_clear H.\n        + apply <-formula_eval_subst_T; eauto.\n        + exfalso; clear H1.\n          inversion_clear H0; inversion_clear H.\n          apply (mapsto_injective _ _ _ _ m) in H0; inversion H0.\n      - eapply formula_eval_subst_T in EV; eauto; constructor;\n          [apply ev_conj_fr|apply ev_conj_fl]; auto.\n      - eapply formula_eval_subst_T; eauto.\n        inversion_clear EV; inversion_clear H0; inversion_clear H; try assumption.\n        + inversion_clear H1; apply (formula_eval_injective _ _ _ _ H) in H0; inversion H0.\n        + inversion_clear H0; apply (mapsto_injective _ _ _ _ H) in m; inversion m.\n      - apply ev_disj_tr; constructor; [ |apply formula_eval_subst_F]; auto.\n      - inversion_clear EV; inversion_clear H.\n        + exfalso; clear H1.\n          inversion_clear H0.\n          apply (mapsto_injective _ _ _ _ m) in H; inversion H.\n        + apply <-formula_eval_subst_F; eauto.\n      - eapply formula_eval_subst_F in EV; eauto. \n      - eapply formula_eval_subst_F; eauto.\n        inversion_clear EV; inversion_clear H0; inversion_clear H; try assumption.\n        + inversion_clear H1; apply (formula_eval_injective _ _ _ _ H) in H0; inversion H0.\n        + inversion_clear H1; inversion_clear H; apply (mapsto_injective _ _ _ _ H1) in m; inversion m.\n    Qed.\n\n  End Switch.\n\n  (* The algorithm proceeds by induction on formula size. *)\n\n  (* Any formula of size 0 is equivalent to either T or F. Moreover, we know that\n     T (of size 0) has one satisfying assignment and F has zero sat. assignments. *)\n  Section BaseCase.\n\n    Lemma formula_size_dec:\n      forall (ϕ : formula),\n        {formula_size ϕ = 0} + {formula_size ϕ > 0}.\n    Proof.\n      intros.\n      induction ϕ.\n      { left; easy. }\n      { left; easy. }\n      { right; unfold formula_size; simpl; omega. }\n      { destruct IHϕ as [IH|IH]. \n        - left; assumption.\n        - right; assumption.\n      }\n      { destruct IHϕ1 as [IH1|IH1].\n        - destruct IHϕ2 as [IH2|IH2].\n          + left; unfold formula_size in *; simpl.\n            rewrite app_length, IH1, IH2. easy.\n          + right; unfold formula_size in *; simpl.\n            rewrite app_length, IH1; easy.\n        - right; unfold formula_size in *; simpl.\n          rewrite app_length; omega.\n      }\n      { destruct IHϕ1 as [IH1|IH1].\n        - destruct IHϕ2 as [IH2|IH2].\n          + left; unfold formula_size in *; simpl.\n            rewrite app_length, IH1, IH2. easy.\n          + right; unfold formula_size in *; simpl.\n            rewrite app_length, IH1; easy.\n        - right; unfold formula_size in *; simpl.\n          rewrite app_length; omega.\n      }\n    Defined.\n\n    Lemma zero_size_formula_constant_dec:\n      forall (ϕ : formula),\n        formula_size ϕ = 0 -> \n        {equivalent ϕ T} + {equivalent ϕ F}.\n    Proof.\n      intros ? SIZE.\n      induction ϕ.\n      { right; intros ? ?; split; intros EV; auto. }\n      { left; intros ? ?; split; intros EV; auto. }\n      { exfalso; compute in SIZE; easy. }\n      { rewrite formula_size_neg in SIZE. \n        feed IHϕ; auto.\n        destruct IHϕ as [IH|IH]; [right | left].\n        { apply formula_equiv_neg_move.\n          apply formula_equiv_trans with T; auto.\n          apply formula_equiv_T_neg_F. }\n        { apply formula_equiv_neg_move.\n          apply formula_equiv_trans with F; auto.\n          apply formula_equiv_sym, formula_equiv_neg_move, formula_equiv_T_neg_F. } }\n      { rewrite formula_size_and in SIZE.\n        apply plus_is_O in SIZE.\n        destruct SIZE as [S1 S2].\n        feed IHϕ1; auto; feed IHϕ2; auto.\n        destruct IHϕ1 as [IH1|IH1].\n        - destruct IHϕ2 as [IH2|IH2].\n          + left; apply formula_equiv_and_compose_T; auto.\n          + right; clear IH1.\n            apply formula_equiv_trans with (ϕ2 ∧ ϕ1).\n            apply formula_equiv_and_comm. apply formula_equiv_and_compose_F; auto.\n        - right; clear IHϕ2.\n          apply formula_equiv_and_compose_F; auto.\n      }\n      { rewrite formula_size_or in SIZE.\n        apply plus_is_O in SIZE.\n        destruct SIZE as [S1 S2].\n        feed IHϕ1; auto; feed IHϕ2; auto.\n        destruct IHϕ1 as [IH1|IH1].\n        - clear IHϕ2; left. \n          apply formula_equiv_or_compose_T; auto.\n        - destruct IHϕ2 as [IH2|IH2].\n          + left. apply formula_equiv_trans with (ϕ2 ∨ ϕ1).\n            apply formula_equiv_or_comm. apply formula_equiv_or_compose_T; auto.\n          + right. apply formula_equiv_or_compose_F; auto; apply fo_eq_11.\n      }\n    Defined.\n\n    Lemma number_or_satisfying_assignments_of_eqT:\n      forall (ϕ : formula),\n        equivalent ϕ T ->\n        #sat ϕ ≃ (Nat.pow 2 (length (formula_vars ϕ))).\n    Proof.\n      intros ? EQ.\n      exists (all_assignments_on (formula_vars ϕ)).\n      split; [split; [split | split] | ].\n\n      - apply list_of_all_assignments_dupfree.\n        apply NoDup_nodup.\n      - assert(H := list_of_all_assignments_dupfree\n                      (formula_vars ϕ)).\n        feed H. apply NoDup_nodup. destruct H as [H1 H2].\n        intros ? ? EL1 EL2 NEQ EQU.\n        apply equiv_assignments_nodup in EQU.\n        apply H2 with (x1 := x1) (x2 := x2); auto.\n      - intros α EL; split.\n        auto using assignment_in_all_assignments_on_sets_all_variables.\n        apply EQ; constructor.\n      - intros α [SETS SAT].\n        assert(H := all_assignments_in_all_assignments_on (formula_vars ϕ) α).\n        feed H.\n        { apply incl_tran with (leaves ϕ); try apply incl_nodup; auto. }\n        destruct H as [β [EQU EL]].\n        exists β; split; [apply equiv_assignments_nodup| ]; auto.\n      - rewrite size_of_list_of_all_assignments_on; auto.\n    Qed.\n          \n    Corollary number_or_satisfying_assignments_of_T:\n      #sat T ≃ 1.\n    Proof.\n      apply number_or_satisfying_assignments_of_eqT, formula_equiv_refl.\n    Qed.      \n      \n    Lemma number_or_satisfying_assignments_of_eqF:\n      forall (ϕ : formula),\n        equivalent ϕ F ->\n        #sat ϕ ≃ 0.\n    Proof.\n      intros ? EQ.\n      exists []. split; [split; [split | split] | ]; auto.\n      - constructor.\n      - intros ? EL; destruct EL.\n      - intros α [_ SAT].\n        apply EQ in SAT.\n        inversion_clear SAT.\n    Qed.\n    \n    Corollary number_or_satisfying_assignments_of_F:\n      #sat F ≃ 0.\n    Proof.\n      apply number_or_satisfying_assignments_of_eqF, formula_equiv_refl.\n    Qed.\n    \n  End BaseCase.\n\n  (* For the induction step we assume that lists with satisfying \n     assignments are know for formulas ϕ[x ↦ T] and ϕ[x ↦ F]. *) \n  Section InductionStep.\n\n    (* Consider a formula ϕ. *)\n    Variable ϕ : formula.\n\n    (* And its leaf x. *)\n    Variable x : variable.\n    Hypothesis H_leaf : x el leaves ϕ.\n\n    (* Let αs1 and αs2 be lists of satisfying assignments for \n       formulas ϕ[x ↦ T] and ϕ[x ↦ F] respectively. *)\n    Variables αs1 αs2 : assignments.\n    \n    Lemma app_sat_assignments_is_dupfree:\n      dupfree (leaves (ϕ [x ↦ T])) αs1 ->\n      dupfree (leaves (ϕ [x ↦ F])) αs2 ->\n      dupfree (leaves ϕ) (map (cons (x, true)) αs1 ++ map (cons (x, false)) αs2).\n    Proof.\n      intros [ND1 NE1] [ND2 NE2]; split.\n      { apply nodup_app_of_map_cons; auto.\n        intros F; inversion_clear F.\n      }\n      { intros α1 α2 EL1 EL2 EQ NEQ. \n        apply in_app_iff in EL1; apply in_app_iff in EL2.\n        destruct EL1 as [EL1|EL1], EL2 as [EL2|EL2]. \n        { apply in_map_iff in EL1; destruct EL1 as [β1 [EQ1 EL1]].\n          apply in_map_iff in EL2; destruct EL2 as [β2 [EQ2 EL2]]; subst α1 α2.\n          specialize (NE1 _ _ EL1 EL2).\n          feed NE1; [intros C; apply EQ; rewrite C; auto | ].\n          apply NE1; clear NE1.\n          apply equiv_assignments_cancel_subset with (vs_sub := leaves (ϕ [x ↦ T])) in NEQ;\n            auto using leaves_subset_subst_T, leaves_nel_subst_T.\n        }\n        { apply in_map_iff in EL1; apply in_map_iff in EL2.\n          destruct EL1 as [α1_tl [EQ1 _]], EL2 as [α2_tl [EQ2 _]]; subst α1 α2.\n          specialize (NEQ x H_leaf true); destruct NEQ as [NEQ _]; feed NEQ; auto.\n          inversion_clear NEQ; auto.\n        }\n        { apply in_map_iff in EL1; apply in_map_iff in EL2.\n          destruct EL1 as [α1_tl [EQ1 _]], EL2 as [α2_tl [EQ2 _]]; subst α1 α2.\n          specialize (NEQ x H_leaf true); destruct NEQ as [_ NEQ]; feed NEQ; auto.\n          inversion_clear NEQ; auto.\n        }\n        { apply in_map_iff in EL1; destruct EL1 as [β1 [EQ1 EL1]].\n          apply in_map_iff in EL2; destruct EL2 as [β2 [EQ2 EL2]]; subst α1 α2.\n          specialize (NE2 _ _ EL1 EL2).\n          feed NE2; [intros C; apply EQ; rewrite C; auto | ].\n          apply NE2; clear NE2.\n          apply equiv_assignments_cancel_subset with (vs_sub := leaves (ϕ [x ↦ F])) in NEQ;\n            auto using leaves_subset_subst_F, leaves_nel_subst_F.\n        }\n      }\n    Qed.\n    \n    Lemma app_sat_assignments_is_set_with_sat_assignments:\n      set_with_sat_assignments (ϕ[x ↦ T]) αs1 -> \n      set_with_sat_assignments (ϕ[x ↦ F]) αs2 -> \n      set_with_sat_assignments\n        ϕ (map (cons (x, true)) αs1 ++ map (cons(x, false)) αs2).\n    Proof.\n      intros SAT1 SAT2; intros α ELt; split.\n      { apply in_app_iff in ELt; destruct ELt as [EL|EL]; apply in_map_iff in EL;\n          destruct EL as [α_tl [EQ EL]]; subst α.\n        - intros v IN.\n          decide (x = v) as [EQ|NEQ]; subst.\n          + left; auto.\n          + specialize (SAT1 α_tl EL); destruct SAT1 as [SET1 _].\n            right; apply SET1, leaves_el_neq_subst_T; auto.\n        - intros v IN.\n          decide (x = v) as [EQ|NEQ]; subst.\n          + left; auto.\n          + specialize (SAT2 α_tl EL); destruct SAT2 as [SET2 _].\n            right; apply SET2, leaves_el_neq_subst_F; auto.     \n      }\n      apply switch with x.\n      { apply in_app_iff in ELt; destruct ELt as [EL|EL]; apply in_map_iff in EL;\n          destruct EL as [α_tl [EQ EL]]; subst α; simpl; left; auto. }\n      apply in_app_or in ELt; destruct ELt as [EL|EL].\n      { apply ev_disj_tl, ev_conj_t.\n        { apply in_map_iff in EL.\n          destruct EL as [mα [EQ1 MEM1]]; subst α; auto.\n        } \n        { apply in_map_iff in EL.\n          destruct EL as [mα [EQ MEM]]; subst α.\n          apply formula_eval_nel_cons, SAT1; auto using leaves_nel_subst_T; auto.\n        }\n      }\n      { apply ev_disj_tr, ev_conj_t.\n        { apply in_map_iff in EL.\n          destruct EL as [mα [EQ MEM]]; subst α; auto.\n        }\n        { apply in_map_iff in EL.\n          destruct EL as [mα [EQ MEM]]; subst α.\n          apply formula_eval_nel_cons, SAT2; auto using leaves_nel_subst_F; auto.\n        }\n      }\n    Qed.\n    \n    Lemma app_sat_assignments_is_set_with_all_sat_assignments:\n      set_with_all_sat_assignments (ϕ [x ↦ T]) αs1 -> \n      set_with_all_sat_assignments (ϕ [x ↦ F]) αs2 -> \n      set_with_all_sat_assignments\n        ϕ (map (cons (x, true)) αs1 ++ map (cons (x, false)) αs2).\n    Proof.\n      intros SET1 SET2. \n      intros α [SETS SAT].\n      apply (switch _ x _ _ (SETS x H_leaf)) in SAT.\n      inversion_clear SAT; inversion_clear H.\n      { specialize (SET1 α); feed SET1.\n        { split; [apply sets_all_variables_subst_T| ]; auto. } \n        destruct SET1 as [β [EQ EL]].\n        inversion_clear H0. \n        exists ((x,true)::β); split.\n        { intros v ELl b.\n          decide (v = x) as [E|NEQ]; [subst | ]; split; intros EV.\n          - apply (mapsto_injective _ _ _ _ H) in EV; subst; constructor.\n          - inversion_clear EV; [ | exfalso]; auto.\n          - constructor; auto; apply EQ; auto using leaves_el_neq_subst_T.\n          - inversion_clear EV; auto; apply EQ; auto using leaves_el_neq_subst_T.\n        }\n        { apply in_app_iff; left.\n          apply in_map_iff; exists β; easy.\n        }\n      }\n      { specialize (SET2 α); feed SET2.\n        { split; [apply sets_all_variables_subst_F| ]; auto. }\n        destruct SET2 as [β [EQ EL]].\n        inversion_clear H0; inversion_clear H; simpl in H0.\n        exists ((x,false)::β); split.\n        { intros v ELl b.\n          decide (v = x) as [E|NEQ]; [subst | ]; split; intros EV.\n          - apply (mapsto_injective _ _ _ _ H0) in EV; subst; constructor.\n          - inversion_clear EV; [ | exfalso]; auto.\n          - constructor; auto; apply EQ; auto using leaves_el_neq_subst_F.\n          - inversion_clear EV; auto; apply EQ; auto using leaves_el_neq_subst_F.\n        }\n        { apply in_app_iff; right.\n          apply in_map_iff; exists β; easy.\n        }\n      } \n    Qed. \n\n    Lemma app_sat_assignments_sum_length:\n      forall (nl nr : nat),\n        length αs1 = nl ->\n        length αs2 = nr ->\n        length (map (cons (x, true)) αs1 ++ map (cons (x, false)) αs2) = nl + nr.\n    Proof.\n      intros nl nr LEN1 LEN2.\n      rewrite app_length, map_length, map_length, <- LEN1, <- LEN2; auto.\n    Qed.\n    \n  End InductionStep.\n  \n  Definition algorithm2 (ϕ : formula) : { n : nat | #sat ϕ ≃ n }.\n  Proof.\n    generalize dependent ϕ.\n    apply size_recursion with formula_size; intros ϕ IHϕ. \n    destruct (formula_size_dec ϕ) as [Zero|Pos].\n    { destruct (zero_size_formula_constant_dec ϕ Zero) as [Tr|Fl].\n      - exists 1.\n        assert(EQ := nodup_length_le _ (leaves ϕ)); unfold formula_size in Zero;\n          rewrite Zero in EQ; rewrite Nat.le_0_r in EQ.\n        assert(One := number_or_satisfying_assignments_of_eqT ϕ Tr); unfold formula_vars in One;\n          rewrite EQ in One; simpl in One.\n        assumption.\n      - exists 0; auto using number_or_satisfying_assignments_of_eqF. } \n    { assert (V := get_var _ Pos).\n      destruct V as [x IN]; clear Pos.\n      assert (IH1 := IHϕ (ϕ[x ↦ T])); assert(IH2 := IHϕ (ϕ[x ↦ F])); clear IHϕ.\n      specialize (IH1 (formula_size_subst_T_lt _ _ IN));\n        specialize (IH2 (formula_size_subst_F_lt _ _ IN)).\n      destruct IH1 as [nl EQ1], IH2 as [nr EQ2].\n      exists (nl + nr).\n      destruct EQ1 as [αs1 [LAA1 LEN1]], EQ2 as [αs2 [LAA2 LEN2]].\n      exists (map (fun α => (x, true)::α) αs1 ++ map (fun α => (x,false)::α) αs2).\n      destruct LAA1 as [ND1 [SAT1 SET1]], LAA2 as [ND2 [SAT2 SET2]].\n      split; [split; [ | split] | ];\n        auto using app_sat_assignments_is_dupfree,\n        app_sat_assignments_is_set_with_sat_assignments,\n        app_sat_assignments_is_set_with_all_sat_assignments,\n        app_sat_assignments_sum_length.\n    }\n  Defined.\n\n  Section Tests.\n\n    Let or_n n := fold_left (fun ϕ x => ϕ ∨ [|V x|]) (range 1 n) F.\n    Let xor_n n := fold_left (fun ϕ x => ϕ ⊕ [|V x|]) (range 1 n) F.\n\n    (* Compute (proj1_sig (algorithm1 (or_n 5))). => 31 : nat *)\n    (* Compute (proj1_sig (algorithm1 (or_n 8))). => 255 : nat *)\n    (* Compute (proj1_sig (algorithm1 (or_n 10))). => 1023 : nat *)\n    (* Compute (proj1_sig (algorithm1 (or_n 15))). => 32767 : nat *)\n    (* Compute (proj1_sig (algorithm1 (or_n 16))). => Stack overflow. *)\n    \n    (* Compute (proj1_sig (algorithm1 (xor_n 5))). => 16 : nat *)\n    (* Compute (proj1_sig (algorithm1 (xor_n 8))). => 128 : nat *)\n    \n  End Tests.\n\nEnd Algorithm2.\n\n(** * Bonus 1: A (failed) attempt to come up with a third algorithm. *)\n(* Algorithm\n   1) Transform ϕ to DNF form\n   2) Map each monomial into a certificate1\n   3) Make these certificates disjoint \n      (i.e. they set at least one variable to different values)\n   4) Calculate the number of sat. assignments. *)\nSection Algorithm3.\n  \n  Section Literal.\n\n    Inductive literal :=\n    | Positive: variable -> literal\n    | Negative: variable -> literal.\n\n    Inductive literal_eval: literal -> assignment -> bool -> Prop :=\n    | lit_ev_pos: forall (v : variable) (α : assignment) (b : bool),\n        (v / α ↦ b) -> literal_eval (Positive v) α b\n    | lit_ev_neg: forall (v : variable) (α : assignment) (b : bool),\n        (v / α ↦ (negb b)) -> literal_eval (Negative v) α b.\n  \n    Lemma literal_eval_injective:\n      forall (α : assignment) (l : literal) (b1 b2 : bool),\n        literal_eval l α b1 ->\n        literal_eval l α b2 ->\n        b1 = b2.\n    Proof.\n      intros ? ? ? ? M1 M2.\n      destruct b1, b2; auto; exfalso.\n      all: inversion M1; subst; inversion M2; subst.\n      all: eapply mapsto_injective_contr; eauto. \n    Qed.\n    \n    Corollary literal_eval_injective_contr:\n      forall (α : assignment) (l : literal),\n        literal_eval l α true ->\n        literal_eval l α false ->\n        False.\n    Proof.\n      intros ? ? EV1 EV2; assert (F := literal_eval_injective _ _ _ _ EV1 EV2); easy.\n    Qed.\n    \n  End Literal.\n  Hint Constructors literal_eval.\n\n  Section Monomial.\n    \n    Definition monomial := list literal.\n    \n    Inductive monomial_eval: monomial -> assignment -> bool -> Prop :=\n    | mon_ev_true: forall (m : monomial) (α : assignment),\n        (forall l, l el m -> literal_eval l α true) -> \n        monomial_eval m α true\n    | mon_ev_false: forall (m : monomial) (α : assignment),\n        (exists l, l el m /\\ literal_eval l α false) -> \n        monomial_eval m α false.\n\n\n    Definition monomial_sat_assignment (m : monomial) (α : assignment) :=\n      monomial_eval m α true.\n\n    Definition monomial_satisfiable (m : monomial) :=\n      exists (α : assignment), monomial_sat_assignment m α.\n\n    Definition monomial_unsat_assignment (m : monomial) (α : assignment) :=\n      monomial_eval m α false.\n\n    Definition monomial_unsatisfiable (m : monomial) :=\n      forall (α : assignment), monomial_unsat_assignment m α.\n\n\n    Lemma literal_eval_total:\n      forall (α : assignment) (m : monomial),\n        (forall l, l el m -> literal_eval l α true) \\/\n        ((exists l, l el m /\\ forall b, ~ literal_eval l α b)\n         /\\ (forall l, l el m -> (exists b, literal_eval l α b) -> literal_eval l α true)) \\/\n        (exists l, l el m /\\ literal_eval l α false).\n    Proof.\n      clear; intros; induction m.\n      left; intros l EL; inversion EL.      \n      destruct IHm as [IH|[IH|IH]].\n      { destruct a; destruct (mapsto_total α v) as [[[V H]|[V H]]|[V H]].\n        - left; intros l EL; destruct EL as [EQ|IN]; subst; auto.\n        - right; left; split. \n          + exists (Positive v); split; [left| ]; auto.\n            intros b EV; inversion_clear EV.\n            apply nel_mapsto in H0; auto.\n          + intros ? [EQ|EL] [b EV]; subst; apply IH; auto.\n            inversion_clear EV; specialize (H _ H0); destruct H.\n        - right; right; exists (Positive v); split; [left| ]; auto.\n        - right; right; exists (Negative v); split; [left| ]; auto.\n        - right; left; split.\n          + exists (Negative v); split; [left| ]; auto.\n            intros b EV; inversion_clear EV.\n            apply nel_mapsto in H0; auto.\n          + intros ? [EQ|EL] [b EV]; subst; apply IH; auto.\n            inversion_clear EV; specialize (H _ H0); destruct H.\n        - left; intros l EL; destruct EL as [EQ|IN]; subst; auto. \n      }     \n      { destruct IH as [[l [EL NE]] ALL], a, (mapsto_total α v) as [[[V H]|[V H]]|[V H]]; right.\n        - left; split.\n          + exists l; split; [right | ]; auto.\n          + intros l2 [EQ|EL2] [b EV]; subst; [constructor|apply ALL]; eauto.\n        - left; split.\n          + exists l; split; [right | ]; auto.\n          + intros l2 [EQ|EL2] [b EV]; subst.\n            exfalso; inversion_clear EV; eapply H; eauto.\n            apply ALL; eauto.\n        - right.\n          exists (Positive v); split; [left| ]; auto.\n        - right.\n          exists (Negative v); split; [left| ]; auto.      \n        - left; split.\n          + exists l; split; [right | ]; auto.\n          + intros l2 [EQ|EL2] [b EV]; subst.\n            exfalso; inversion_clear EV; eapply H; eauto.\n            apply ALL; eauto.\n        - left; split.\n          + exists l; split; [right | ]; auto.\n          + intros l2 [EQ|EL2] [b EV]; subst; [constructor|apply ALL]; eauto.\n      }\n      { destruct IH as [l [EL NE]].\n        right; right.\n        exists l; split; [right | ]; auto.  \n      }      \n    Qed.\n    \n  End Monomial.\n  \n  Section DNF.\n    \n    Definition dnf := list monomial.\n\n    Inductive dnf_eval: dnf -> assignment -> bool -> Prop :=\n    | dnf_ev_true: forall (d : dnf) (α : assignment),\n        (exists m, m el d /\\ monomial_eval m α true) -> \n        dnf_eval d α true\n    | dnf_ev_false: forall (d : dnf) (α : assignment),\n        (forall m, m el d -> monomial_eval m α false) -> \n        dnf_eval d α false.\n\n    Definition dnf_representation (ϕ : formula) (ψ : dnf) :=\n      forall (α : assignment) (b : bool),\n        formula_eval ϕ α b <-> dnf_eval ψ α b.\n    \n    Definition equivalent_dnf (ψ1 ψ2 : dnf) :=\n      forall (α : assignment) (b : bool),\n        dnf_eval ψ1 α b <-> dnf_eval ψ2 α b.\n    \n    \n    Lemma dnf_representation_formula_transfer:\n      forall (ϕ1 ϕ2 : formula) (ψ : dnf), \n        equivalent ϕ1 ϕ2 ->\n        dnf_representation ϕ2 ψ ->\n        dnf_representation ϕ1 ψ.\n    Proof.\n      intros ? ? ? EQU DNF1.\n      intros ? b; split; intros EV.\n      apply DNF1, EQU; assumption.\n      apply EQU, DNF1; assumption.\n    Qed.\n\n    Corollary dnf_representation_sigma_formula_transfer:\n      forall (ϕ1 ϕ2 : formula), \n        equivalent ϕ1 ϕ2 -> \n        {ψ : dnf | dnf_representation ϕ1 ψ} ->\n        {ψ : dnf | dnf_representation ϕ2 ψ}.\n    Proof.\n      intros ? ? EQ REP.\n      destruct REP as [ψ REP].\n      exists ψ; apply dnf_representation_formula_transfer with ϕ1; auto.\n      apply formula_equiv_sym; assumption.\n    Qed.\n\n    Lemma monomial_sat_total:\n      forall (α : assignment) (ψ : dnf),\n        (forall m, m el ψ -> monomial_unsat_assignment m α) \\/\n        (exists m, m el ψ /\\ forall b, ~ monomial_eval m α b) \\/\n        (exists m, m el ψ /\\ monomial_sat_assignment m α).\n    Proof.\n      intros.\n      induction ψ.\n      - left; intros; inversion_clear H.\n      - destruct IHψ as [IH|[IH|IH]].\n        + destruct (literal_eval_total α a) as [H|[H|H]].\n          * right; right.\n            exists a; split; [left|constructor]; auto.\n          * right; left; destruct H as [[l [EL NO]] ALL].\n            exists a; split; [left| ]; auto; intros [ | ] MON.\n            apply NO with (b := true); inversion_clear MON; auto.\n            inversion_clear MON; destruct H as [l2 [EL2 NO2]].\n            specialize (ALL l2 EL2 (@ex_intro _ (literal_eval l2 α) false NO2)).\n            eapply literal_eval_injective_contr; eauto.\n          * left.\n            destruct H as [l [EL ALL]].\n            intros m [EQ|EL2]; subst.\n            constructor; exists l; split; auto.\n            apply IH; auto.\n        + right; left.\n          destruct IH as [m [EL ALL]].\n          exists m; split; [right| ]; auto.\n        + right; right.\n          destruct IH as [m [EL ALL]].\n          exists m; split; [right| ]; auto.\n    Qed.\n        \n  End DNF.\n\n  Section FormulaToDNF.\n\n    Fixpoint bottom_negations (ϕ : formula) : Prop :=\n      match ϕ with\n      | T | F | [|_|] | ¬ [|_|]=> True\n      | ϕl ∧ ϕr => bottom_negations ϕl /\\ bottom_negations ϕr\n      | ϕl ∨ ϕr => bottom_negations ϕl /\\ bottom_negations ϕr\n      | ¬ _ => False\n      end.\n\n    (* By repetitive application of DeMorgan's laws, one \n       can move all negations to the bottom of a formula. *)\n    Definition move_negations (ϕ : formula):\n      {neg_ϕ : formula | equivalent ϕ neg_ϕ\n                         /\\ bottom_negations neg_ϕ }.\n    Proof.\n      generalize dependent ϕ. \n      apply size_recursion with number_of_nodes; intros ϕ IH.\n      destruct ϕ.\n      { (* move_negations F := F. *)\n        exists F; split.\n        - apply formula_equiv_refl.\n        - constructor.\n      }\n      { (* move_negations T := T. *)\n        exists T; split.\n        - apply formula_equiv_refl.\n        - constructor.\n      }\n      { (* move_negations [|v|] := [|v|]. *)\n        exists [|v|]; split.\n        - apply formula_equiv_refl.\n        - constructor.\n      }\n      { destruct ϕ.\n        { (* move_negations (¬F) := T. *)\n          exists T; split. \n          - apply formula_equiv_sym;\n              apply formula_equiv_T_neg_F.\n          - constructor.\n        }\n        { (* move_negations (¬T) := F. *)\n          exists F; split.\n          - apply formula_equiv_neg_move;\n              apply formula_equiv_T_neg_F.\n          - constructor.\n        }\n        { (* move_negations (¬[|v|]) := ¬ [|v|]. *)\n          exists (¬ [|v|]); split.\n          - apply formula_equiv_refl.\n          - constructor.\n        }\n        { (* move_negations (¬ ¬ ϕ) := move_negations ϕ. *)\n          assert (IH1 := IH ϕ); feed IH1; [simpl; omega| clear IH].\n          destruct IH1 as [neg_ϕ [EQ LIT]].\n          exists neg_ϕ; split.\n          - apply formula_equiv_neg_move.\n            apply ->formula_equiv_neg_compose; assumption.\n          - assumption.\n        }\n        { (* move_negations (¬(ϕl ∧ ϕr)) := move_negations ϕl ∨ move_negations ϕr. *)\n          assert (IH1 := IH (¬ ϕ1)); feed IH1; [simpl; omega| ].\n          assert (IH2 := IH (¬ ϕ2)); feed IH2; [simpl; omega| clear IH].\n          destruct IH1 as [neg_ϕ1 [EQ1 BOT1]], IH2 as [neg_ϕ2 [EQ2 BOT2]].\n          exists (neg_ϕ1 ∨ neg_ϕ2); split. \n          - apply formula_equiv_neg_move.\n            apply formula_equiv_trans with (¬(¬ϕ1 ∨ ¬ϕ2)).\n            apply formula_equiv_demorgan_and.\n            apply ->formula_equiv_neg_compose; apply formula_equiv_or_compose; auto.\n          - split; assumption.     \n        }\n        { (* move_negations (¬(ϕl ∨ ϕr)) := move_negations ϕl ∧ move_negations ϕr. *)\n          assert (IH1 := IH (¬ ϕ1)); feed IH1; [simpl; omega| ].\n          assert (IH2 := IH (¬ ϕ2)); feed IH2; [simpl; omega| ].\n          destruct IH1 as [neg_ϕ1 [EQ1 BOT1]], IH2 as [neg_ϕ2 [EQ2 BOT2]].\n          exists (neg_ϕ1 ∧ neg_ϕ2); split.\n          - apply formula_equiv_neg_move.\n            apply formula_equiv_trans with (¬(¬ϕ1 ∧ ¬ϕ2)).\n            apply formula_equiv_demorgan_or.\n            apply ->formula_equiv_neg_compose; apply formula_equiv_and_compose; auto. \n          - split; assumption.\n        }   \n      }\n      { (* move_negations (ϕl ∧ ϕr) := move_negations ϕl ∧ move_negations ϕr. *)\n        assert (IH1 := IH ϕ1); feed IH1; [simpl; omega| ].\n        assert (IH2 := IH ϕ2); feed IH2; [simpl; omega| ].\n        destruct IH1 as [neg_ϕ1 [EQ1 BOT1]], IH2 as [neg_ϕ2 [EQ2 BOT2]].\n        exists (neg_ϕ1 ∧ neg_ϕ2); split.\n        - apply formula_equiv_and_compose; assumption. \n        - split; assumption.\n      }\n      { (* move_negations (ϕl ∨ ϕr) := move_negations ϕl ∨ move_negations ϕr. *)\n        assert (IH1 := IH ϕ1); feed IH1; [simpl; omega| ].\n        assert (IH2 := IH ϕ2); feed IH2; [simpl; omega| ].\n        destruct IH1 as [neg_ϕ1 [EQ1 BOT1]], IH2 as [neg_ϕ2 [EQ2 BOT2]].\n        exists (neg_ϕ1 ∨ neg_ϕ2); split.\n        - apply formula_equiv_or_compose; auto.\n        - split; assumption.\n      }\n    Qed.\n\n    (* Next we inductively transform a formula into its DNF representation. *)\n\n    Lemma dnf_representation_of_T:\n      dnf_representation T [[]].   \n    Proof.\n      split; intros EV.\n      { inversion_clear EV.\n        constructor; intros.\n        exists []; split.\n        - left; auto.\n        - constructor.\n          intros; inversion_clear H.\n      }\n      { inversion_clear EV.\n        - constructor.\n        - exfalso.\n          specialize (H ([])); feed H; [left; auto | ].\n          inversion_clear H. \n          destruct H0 as [t  [IN EV]].\n          inversion_clear IN.\n      } \n    Qed.\n\n    Lemma dnf_representation_of_F:\n      dnf_representation F [].   \n    Proof.\n      split; intros EV.\n      { inversion_clear EV.\n        constructor; intros.\n        inversion_clear H.\n      }\n      { inversion_clear EV.\n        - destruct H as [m [IN EV]]; inversion_clear IN.\n        - constructor.\n      } \n    Qed.\n\n    Lemma dnf_representation_of_var:\n      forall (v : variable),\n        dnf_representation [|v|] [[Positive v]].   \n    Proof.\n      intros; split; intros EV.\n      { inversion_clear EV.\n        destruct b; constructor.\n        { exists [Positive v]; split.\n          - left; auto. \n          - constructor; intros lit EL.\n            apply singl_in in EL; subst; auto.\n        }\n        { intros m EL.\n          apply singl_in in EL; subst.\n          constructor; exists (Positive v); split; try left; auto.\n        }\n      } \n      { constructor.\n        inversion_clear EV.\n        { destruct H as [m [EL MON]].\n          apply singl_in in EL; subst.\n          inversion_clear MON.\n          specialize (H (Positive v)); feed H; [left; auto | ].\n          inversion_clear H; assumption.\n        }\n        { specialize (H ([Positive v])); feed H; [left; auto | ].\n          inversion_clear H; destruct H0 as [lit [EL F]]. \n          apply singl_in in EL; subst.\n          inversion_clear F; assumption.\n        }\n      }\n    Qed.\n\n    Lemma dnf_representation_of_neg_var:\n      forall (v : variable),\n        dnf_representation (¬[|v|]) [[Negative v]].   \n    Proof.\n      intros; split; intros EV.\n      { inversion_clear EV; inversion_clear H.\n        destruct b; constructor.\n        { exists [Negative v]; split.\n          - left; reflexivity.\n          - constructor; intros lit EL.\n            apply singl_in in EL; subst.\n            constructor; assumption.\n        }\n        { intros m EL.\n          apply singl_in in EL; subst.\n          constructor; exists (Negative v); split.\n          - left; reflexivity.\n          - constructor; assumption.\n        }\n      } \n      { constructor; constructor.\n        inversion_clear EV.\n        { destruct H as [m [EL MON]].\n          apply singl_in in EL; subst.\n          inversion_clear MON.\n          specialize (H (Negative v)); feed H; [left; auto | ].\n          inversion_clear H; assumption.\n        }\n        { specialize (H ([Negative v])); feed H; [left; auto | ].\n          inversion_clear H; destruct H0 as [lit [EL F]]. \n          apply singl_in in EL; subst.\n          inversion_clear F; assumption.\n        }\n      }\n    Qed.\n\n    Lemma dnf_representation_of_and:\n      forall (ϕl ϕr : formula) (ψl ψr : dnf),\n        dnf_representation ϕl ψl ->\n        dnf_representation ϕr ψr ->\n        dnf_representation (ϕl ∧ ϕr) (ψl ×× ψr).\n    Proof.\n      intros ? ? ? ? REP1 REP2; split; intros EV.\n      { inversion_clear EV.\n        { apply REP1 in H; apply REP2 in H0; clear REP1 REP2.\n          inversion_clear H; inversion_clear H0; rename H into MR, H1 into ML.\n          destruct ML as [ml [ELl Ml]], MR as [mr [ELr Mr]].\n          constructor; exists (ml ++ mr); split.\n          - apply app_in_flat_product; assumption.\n          - inversion_clear Ml; inversion_clear Mr; rename H into Ml, H0 into Mr.\n            constructor; intros lit EL; apply in_app_iff in EL; destruct EL as [EL|EL]; eauto. \n        }\n        { apply REP1 in H; clear REP1 REP2.\n          inversion_clear H; rename H0 into MF.\n          constructor; intros m EL.\n          apply flat_product_contains_only_apps in EL; destruct EL as [ml [mr [EQ [EL1 EL2]]]]; subst m.\n          specialize (MF ml EL1); inversion_clear MF; destruct H as [lit [EL EV]].\n          constructor; exists lit; split; [apply in_app_iff;left | ]; auto.\n        }\n        { apply REP2 in H; clear REP1 REP2.\n          inversion_clear H; rename H0 into MF.\n          constructor; intros m EL.\n          apply flat_product_contains_only_apps in EL; destruct EL as [ml [mr [EQ [EL1 EL2]]]]; subst m.\n          specialize (MF mr EL2); inversion_clear MF; destruct H as [lit [EL EV]].\n          constructor; exists lit; split; [apply in_app_iff;right | ]; auto.\n        }        \n      }\n      { inversion_clear EV.\n        { destruct H as [mon [FL EV]].\n          apply flat_product_contains_only_apps in FL; destruct FL as [ml [mr [EQ [ELl ELr]]]]; subst.\n          inversion_clear EV; rename H into EL.\n          constructor; [apply REP1|apply REP2]; constructor;\n            [exists ml|exists mr]; split; auto; constructor; intros lit ELlit;\n              apply EL; apply in_app_iff; [left|right]; auto.\n        }\n        { destruct (monomial_sat_total α ψl) as [EVl|[EVl|EVl]], (monomial_sat_total α ψr) as [EVr|[EVr|EVr]].\n          all: try(apply ev_conj_fl; apply REP1; constructor; assumption).\n          all: try(apply ev_conj_fr; apply REP2; constructor; assumption).\n          all: exfalso.\n          all: destruct EVl as [ml [ELl Fl]], EVr as [mr [ELr Fr]].\n          all: specialize (H _ (app_in_flat_product _ _ _ _ ELl ELr)).\n          all: inversion_clear H.\n          all: destruct H0 as [l [EL LIT]].\n          all: apply in_app_iff in EL; destruct EL as [EL|EL].\n          all: try(apply Fl with false; constructor; exists l; split; assumption).\n          all: try(apply Fr with false; constructor; exists l; split; assumption).\n          all: try(inversion_clear Fr; specialize (H _ EL); eauto using literal_eval_injective_contr). \n          all: try(inversion_clear Fl; specialize (H _ EL); eauto using literal_eval_injective_contr). \n        }\n      }\n    Qed.\n\n    Lemma dnf_representation_of_or:\n      forall (ϕl ϕr : formula) (ψl ψr : dnf),\n        dnf_representation ϕl ψl ->\n        dnf_representation ϕr ψr ->\n        dnf_representation (ϕl ∨ ϕr) (ψl ++ ψr).\n    Proof.\n      intros ? ? ? ? REP1 REP2; split; intros EV.\n      { inversion_clear EV.\n        { apply REP1 in H; apply REP2 in H0; clear REP1 REP2.\n          inversion_clear H; inversion_clear H0; rename H into MR, H1 into ML.\n          constructor; intros mon EL.\n          apply in_app_iff in EL; destruct EL as [EL|EL]; auto.\n        }\n        { apply REP1 in H; clear REP1 REP2.\n          inversion_clear H; destruct H0 as [m [EL MON]].\n          constructor; exists m; split.\n          - apply in_or_app; left; assumption.\n          - assumption. }\n        { apply REP2 in H; clear REP1 REP2.\n          inversion_clear H; destruct H0 as [m [EL MON]].\n          constructor; exists m; split.\n          - apply in_or_app; right; assumption.\n          - assumption. }\n      }\n      { inversion_clear EV.\n        destruct H as [m [EL MON]]; apply in_app_iff in EL; destruct EL as [EL|EL];\n          [apply ev_disj_tl; apply REP1 | apply ev_disj_tr; apply REP2];\n          constructor; exists m; split; auto.\n        constructor; (apply REP1 || apply REP2);\n          constructor; intros m EL;\n            apply H; apply in_app_iff; [left|right]; assumption.\n      }     \n    Qed.\n\n    (* Final algorithm works as follows: \n       1) Move all the negations to the leaves/bottom \n       2) Inductively build the DNF respesentation. *)\n    Definition to_dnf (ϕ : formula) : { ψ : dnf | dnf_representation ϕ ψ }.\n    Proof.\n      assert (NEG := move_negations ϕ).\n      destruct NEG as [neg_ϕ [EQ NEG]]. \n      apply dnf_representation_sigma_formula_transfer with neg_ϕ;\n        [apply formula_equiv_sym; auto| clear EQ ϕ].\n      induction neg_ϕ.\n      { (* to_dnf F := []. *)\n        exists []; apply dnf_representation_of_F.\n      }\n      { (* to_dnf T := [[]]. *)\n        exists [[]]; apply dnf_representation_of_T.\n      }\n      { (* to_dnf [|v|] := [[Positive v]]. *)\n        exists [[Positive v]]; apply dnf_representation_of_var.\n      }\n      { (* to_dnf (¬[|v|]) := [[Negative v]]. *)\n        assert (LIT : {v | neg_ϕ = [|v|]}).\n        { destruct neg_ϕ; try (exfalso; auto; fail).\n          exists v; reflexivity. }\n        destruct LIT as [v EQ]; subst neg_ϕ.\n        exists [[Negative v]].\n        apply dnf_representation_of_neg_var.\n      } \n      { (* to_dnf (ϕl ∧ ϕr) := (to_dnf ϕl) × (to_dnf ϕr). *)\n        destruct NEG as [NEG1 NEG2].\n        feed IHneg_ϕ1; auto; clear NEG1.\n        feed IHneg_ϕ2; auto; clear NEG2.\n        destruct IHneg_ϕ1 as [ψ1 REP1], IHneg_ϕ2 as [ψ2 REP2].\n        exists (flat_product ψ1 ψ2); apply dnf_representation_of_and; auto.\n      }\n      { (* to_dnf (ϕl ∨ ϕr) := (to_dnf ϕl) ++ (to_dnf ϕr). *)\n        destruct NEG as [NEG1 NEG2].\n        feed IHneg_ϕ1; auto; clear NEG1.\n        feed IHneg_ϕ2; auto; clear NEG2.\n        destruct IHneg_ϕ1 as [ψ1 REP1], IHneg_ϕ2 as [ψ2 REP2].\n        exists (ψ1 ++ ψ2); apply dnf_representation_of_or; auto.\n      }\n    Qed.\n\n  End FormulaToDNF.\n\n  Section Certificates.\n\n    Definition ext_assignment (vs : variables) (α ext_α : assignment) :=\n      vs ⊆ vars_in ext_α /\\\n      forall (v : variable) (b : bool),\n        v el vars_in α ->\n        v / α ↦ b ->\n        v / ext_α ↦ b.\n    \n    Definition certificate1 (ϕ : formula) (ξ : assignment) :=\n      forall ext_ξ, ext_assignment (leaves ϕ) ξ ext_ξ -> ℇ (ϕ) ext_ξ ≡ true.\n\n    Fixpoint monomial_to_certificate1 (m : monomial) : assignment :=\n      match m with\n      | [] => []\n      | Positive v :: m' => (v, true) :: monomial_to_certificate1 m'\n      | Negative v :: m' => (v, false) :: monomial_to_certificate1 m'\n      end.\n\n    (* Note that [monomial_to_certificate] can fail on an unsatisfiable monomial. *)\n    Example ex_unsat:\n      let var := V 0 in\n      let mon := [Negative var; Positive var] in\n      let α := monomial_to_certificate1 mon in \n      monomial_unsat_assignment mon α.\n    Proof.\n      intros; unfold monomial_unsat_assignment, mon in *; clear mon.\n      constructor; exists (Positive var); split.\n      - right; left; auto. \n      - simpl; constructor; constructor.\n    Qed.\n\n    Lemma sat_mon_contains_no_conflicting_literals:\n      forall (mon : monomial) (v : variable),\n        monomial_satisfiable mon -> \n        Positive v el mon ->\n        Negative v el mon ->\n        False.\n    Proof.\n      intros ? ? SAT N P.\n      inversion_clear SAT as [α SAT2].\n      inversion_clear SAT2.\n      assert(F1 := H _ P); assert(F2 := H _ N); clear H N P.\n      inversion_clear F1; inversion_clear F2.\n      destruct (mapsto_injective_contr _ _ H H0).\n    Qed.\n\n    Lemma mon_sat_cons:\n      forall (l : literal) (mon : monomial),\n        monomial_satisfiable (l :: mon) ->\n        monomial_satisfiable mon.\n    Proof.\n      intros ? ? SAT.\n      inversion_clear SAT as [α SAT2].\n      exists α; constructor; intros.\n      inversion_clear SAT2; apply H0; right; assumption.\n    Qed.\n    \n    Lemma pos_literal_in_cert_vars:\n      forall (mon : monomial) (v : variable),\n        Positive v el mon -> \n        v el vars_in (monomial_to_certificate1 mon).\n    Proof.\n      intros; induction mon.\n      - destruct H.\n      - destruct H as [EQ|EL]; [subst; clear IHmon | ].\n        + simpl; left; reflexivity.\n        + destruct a; simpl; right; auto.\n    Qed.\n\n    Lemma neg_literal_in_cert_vars:\n      forall (mon : monomial) (v : variable),\n        Negative v el mon -> \n        v el vars_in (monomial_to_certificate1 mon).\n    Proof.\n      intros; induction mon.\n      - destruct H.\n      - destruct H as [EQ|EL]; [subst; clear IHmon | ].\n        + simpl; left; reflexivity.\n        + destruct a; simpl; right; auto.\n    Qed.\n    \n    Lemma pos_literal_mapsto_true:\n      forall (mon : monomial) (v : variable),\n        Positive v el mon ->\n        monomial_satisfiable mon -> \n        v / monomial_to_certificate1 mon ↦ true.\n    Proof.\n      intros ? ? EL SAT; induction mon as [ |m mon]; [destruct EL| ].\n      destruct EL as [EQ|EL]; [subst; clear IHmon| ]. \n      - simpl; constructor.\n      - destruct m; decide (v = v0) as [ |NEQ]; subst.\n        + constructor.\n        + specialize (IHmon EL (mon_sat_cons _ _ SAT)).\n          simpl; constructor; auto.\n        + exfalso; apply sat_mon_contains_no_conflicting_literals with (v := v0) (mon := Negative v0 :: mon);\n            [ |right|left]; auto.\n        + simpl; constructor; auto.\n          eauto using IHmon, mon_sat_cons.\n    Qed.\n    \n    Lemma neg_literal_mapsto_false:\n      forall (mon : monomial) (v : variable),\n        Negative v el mon ->\n        monomial_satisfiable mon -> \n        v / monomial_to_certificate1 mon ↦ false.\n    Proof.\n      intros ? ? EL SAT; induction mon as [ |m mon]; [destruct EL| ].\n      destruct EL as [EQ|EL]; [subst; clear IHmon| ]. \n      - simpl; constructor.\n      - destruct m; decide (v = v0) as [ |NEQ]; subst.\n        + exfalso; apply sat_mon_contains_no_conflicting_literals with (v := v0) (mon := Positive v0 :: mon);\n            [ |left|right]; auto.\n        + simpl; constructor; auto.\n          eauto using IHmon, mon_sat_cons.\n        + constructor.\n        + constructor; eauto using mon_sat_cons.\n    Qed.\n    \n    \n    Lemma monomial_to_certificate1_correct:\n      forall (ϕ : formula) (ψ : dnf),\n        dnf_representation ϕ ψ -> \n        forall (mon : monomial),\n          mon el ψ ->\n          monomial_satisfiable mon ->\n          certificate1 ϕ (monomial_to_certificate1 mon).\n    Proof.\n      intros ? ? DNF ? MON SAT. intros ? [INC EXT].\n      apply DNF.\n      constructor; exists mon; split; auto.\n      constructor; intros [v|v] EL; constructor; simpl; apply EXT.\n      all: auto using pos_literal_in_cert_vars, neg_literal_in_cert_vars,\n           pos_literal_mapsto_true, neg_literal_mapsto_false.\n    Qed. \n\n    (* The final thing is to note that if two certificates are disjoint then the \n       sets of their extensions are also disjoint. So we can calculate:\n       num. of models of ϕ = \n         sum_{mon el dnf(ϕ)} 2^(num. of vars in ϕ - num. of vars in mon). *)\n\n    (* Problem: but it’s not always possible to make certificates disjoint. \n       For example [ϕ = x1 ∨ x2] is in DNF. So there are two certificates --\n       x1 and x2. They are not disjoint (and there is no clear way to make them \n       disjoint). Thus, an assignment (x1 ↦ true, x2 ↦ true) is an extension \n       of both certificates. Thus, we'll double-count this assignment. *)\n\n    (* But transformation to DNF looks beautiful, so I did not delete this part. *)\n    \n  End Certificates.\n\nEnd Algorithm3.\n\n(** * \"Bonus\" 2: Counting k-Cliques. *)\n(** This \"bonus\" gives nothing significant. The only reason I include this section is \n    to see the performance of the algorithms on real formulas (it is bad). *)\nSection kCliques.\n\n  (* Full proof of the correctness seems quite difficult. Loosely speaking, one has to:\n     0) define the notion of a graph\n     1) define the notion of a clique \n     2) define the notion of the number of k-cliques in a graph\n     3) construct a reduction k-Clique problem to formula satisfiability problem\n     4) show that this reduction respects the number of cliques!\n        (i.e., the standart reduction for decision problems doesn't work). *)\n  \n  (* Considering the foregoing, I won't prove any properties of the reduction.\n     I'll use the problem of counting the k-cliques as a \"generator\" of \n     nontrivial boolean formulas. *)\n\n  (* Mostly, the resulting formulas are very big (200+ leaves); so evaluation takes \n     a looong time. However, for small examples I was able to get some results.  *)\n\n  Record graph :=\n    { vtcs : list nat; \n      edges : nat -> nat -> bool;\n(*    arefl : rel_list_antirefl vtcs edges *)\n(*    sym : rel_list_sym vtcs edges        *)\n    }.\n\n  Definition cart_prod {X : Type} (xs ys : list X) : list (X * X) :=\n    flat_map (fun x => map (fun y => (x,y)) ys) xs.\n\n  Definition lt_pairs (xs : list nat) : list (nat * nat) :=\n    filter (fun '(x,y) => if lt_dec x y then true else false) (cart_prod xs xs).\n\n  Definition le_pairs (xs : list nat) : list (nat * nat) :=\n    filter (fun '(x,y) => if le_dec x y then true else false) (cart_prod xs xs).\n\n  Definition neq_pairs (xs : list nat) : list (nat * nat) :=\n    filter (fun '(x,y) => if nat_eq_dec x y then false else true) (cart_prod xs xs).\n\n  Definition transform (k : nat) (g : graph) : formula :=\n    (* Extract vertices and edges from the graph. *)\n    let '(Vs, Es) :=\n        match g with\n          {| vtcs := vtcs; edges := edges |} =>\n          (vtcs, edges)\n        end in\n\n    (* The transformation copies the graph k times.\n       Each copy corresponds to one vertex in a clique. *)\n\n    (* Pick at least one vertex from each group. *)\n    let r1 : formula :=\n        fold_left\n          Conj\n          (map (fun k =>\n                  fold_left\n                    Disj\n                    (map (fun v => [|V (100 * k + v)|]) Vs)\n                    F\n               )\n               (range 0 (k-1)))\n          T in\n\n    (* Pick at most one vertex from each group. *)\n    let r2 :=\n        fold_left\n          Conj \n          (flat_map\n             (fun k =>\n                map\n                  (fun '(v1,v2) => ¬[|V (100 * k + v1) |] ∨ ¬ [|V (100 * k + v2) |])\n                  (lt_pairs Vs)\n             )\n             (range 0 (k-1)))\n          T in\n\n    (* Can't pick the same vertex twice. *)\n    let r3 : formula :=\n        fold_left\n          Conj \n          (map\n             (fun '(k1,k2) =>\n                fold_left\n                  Conj \n                  (map (fun v => ¬ [|V (100 * k1 + v)|] ∨ ¬ [|V (100 * k2 + v)|]) Vs)\n                  T\n             )\n             (lt_pairs (range 0 (k-1))))\n          T in\n\n    (* Pick only adjacent vertices. *)\n    let r4 : formula :=\n        fold_left\n          Conj \n          (flat_map\n             (fun '(v1,v2) =>\n                if Es v1 v2\n                then []\n                else map\n                       (fun '(k1,k2) =>  ¬[|V (100 * k1 + v1)|] ∨ ¬[|V (100 * k2 + v2)|])\n                       (neq_pairs (range 0 (k-1))))\n             (lt_pairs Vs))\n          T in\n\n    (* In order to count each clique only once, we need \n       to introduce an ordering on the vertices. *) \n    let r5 : formula :=\n        fold_left\n          Conj \n          (map\n             (fun '(v1,v2) =>\n                fold_left\n                  Conj\n                  (map\n                     (fun '(k1,k2) => ¬[|V (100 * k1 + v2)|] ∨ ¬[|V (100 * k2 + v1)|])\n                     (lt_pairs (range 0 (k-1))))\n                    T\n             )\n             (lt_pairs Vs))\n          T in\n    r1 ∧ r2 ∧ r3 ∧ r4 ∧ r5.\n\n  (* To count the number of k-cligues in a graph g, the algorithm \n     first transforms the graph into a corresponding boolean formula, \n     and then runs algorithm2 on the obtained formula. *)\n  Definition counting_k_cliques (k : nat) (g : graph) :=\n    proj1_sig (algorithm2 (transform k g)).\n\n  Section Tests.\n    \n    Definition graph_3_clique :=\n      {| vtcs := [1;2;3];\n         edges v1 v2 :=\n           match v1, v2 with\n           | 1,2 | 2,1 => true\n           | 1,3 | 3,1 => true\n           | 2,3 | 3,2 => true\n           | _, _ => false\n           end;\n      |}.\n    \n    Definition graph_4_clique :=\n      {| vtcs := [1;2;3;4];\n         edges v1 v2 :=\n           match v1, v2 with\n           | 1,2 | 2,1 => true\n           | 1,3 | 3,1 => true\n           | 1,4 | 4,1 => true\n           | 2,3 | 3,2 => true\n           | 2,4 | 4,2 => true\n           | 3,4 | 4,3 => true\n           | _, _ => false\n           end;\n      |}.\n    \n    Definition graph_5_clique :=\n      {| vtcs := [1;2;3;4;5];\n         edges v1 v2 :=\n           match v1, v2 with\n           | 1,2 | 2,1 => true\n           | 1,3 | 3,1 => true\n           | 1,4 | 4,1 => true\n           | 1,5 | 5,1 => true\n\n           | 2,3 | 3,2 => true\n           | 2,4 | 4,2 => true\n           | 2,5 | 5,2 => true\n\n           | 3,4 | 4,3 => true\n           | 3,5 | 5,3 => true\n\n           | 4,5 | 5,4 => true\n                           \n           | _, _ => false\n           end;\n      |}.\n\n    (* Note that 1-clique is a vertex, 2-clique is an edge. *)\n\n    (* Take ~12 sec. *)\n    (* Compute (counting_k_cliques 1 graph_3_clique). => 3 : nat *)\n    (* Compute (counting_k_cliques 2 graph_3_clique). => 3 : nat *)\n    (* Compute (counting_k_cliques 3 graph_3_clique). => 1 : nat *)\n    (* Compute (counting_k_cliques 4 graph_3_clique). => 0 : nat *)\n\n    (* Take ~10 sec. *)\n    (* Compute (counting_k_cliques 1 graph_4_clique). => 4 : nat *)\n    (* Compute (counting_k_cliques 2 graph_4_clique). => 6 : nat *)\n    (* Compute (counting_k_cliques 3 graph_4_clique). => 4 : nat *)\n    (* Takes ~240 sec. *)\n    (* Compute (counting_k_cliques 4 graph_4_clique). => 1 : nat *)\n\n    (* Take ~4 sec. *)\n    (* Compute (counting_k_cliques 1 graph_5_clique). => 5 : nat *)\n    (* Compute (counting_k_cliques 2 graph_5_clique). => 10 : nat *)\n    (* Takes ~100 sec. *)\n    (* Basically it says that a pentagram contains 10 triangles.  *)\n    (* Compute (counting_k_cliques 3 graph_5_clique). => 10 : nat *)\n    (* No answer after ~2100 sec. *)\n    (* Compute (counting_k_cliques 4 graph_5_clique). *)\n    (* Compute (counting_k_cliques 5 graph_5_clique). *)\n\n  End Tests.\n\nEnd kCliques.", "meta": {"author": "GKerfImf", "repo": "Satisfiability-Theory-in-Coq", "sha": "170b4107c51e297f100de596c155a5d14d6913d6", "save_path": "github-repos/coq/GKerfImf-Satisfiability-Theory-in-Coq", "path": "github-repos/coq/GKerfImf-Satisfiability-Theory-in-Coq/Satisfiability-Theory-in-Coq-170b4107c51e297f100de596c155a5d14d6913d6/project3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7176667970763148}}
{"text": "From mathcomp Require Import ssreflect.all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Nested Proofs Allowed.\n\nModule SsrSyntax.\n\n(* this proof should not be considered correct, \n   due to the no elliptic curve being defined for \n   point g. Please see the report for more details *)\n\n(* Defines n as a prime *)\nDefinition valid_point_order (n: nat) :=\n  prime n.\n\n(* Defines the secret integer a as being less than n  *)\nDefinition valid_a_secret (a n: nat) :=\n  valid_point_order n\n  /\\\n  a < n.\n\n(* Defines the secret integer b as being less than n *)\nDefinition valid_b_secret (b n: nat) :=\n  valid_point_order n\n  /\\\n  b < n.\n\n(* Defines the theorrem to generate the key A *)\nDefinition key_a_generation (A G a: nat) :=\n  A = a * G.\n\n(* Defines the theorem to generate the key B *)\nDefinition key_b_generation (B G b: nat) :=\n  B = b * G.\n\n(* Checks that all of the variables are within\n   their set constraints *)\nDefinition valid_key_pair (A B G a b n: nat) :=\n  valid_a_secret a n\n  /\\\n  valid_b_secret b n\n  /\\\n  key_a_generation A G a\n  /\\\n  key_b_generation B G b \n  /\\\n  valid_point_order n.\n\n(* Defines the encryption fuunctions using A and B *)\nDefinition spec_of_enc_func_a \n          (encrypt: nat -> nat -> nat) :=\n  forall A b: nat,\n    encrypt A b = b * A.\n\nDefinition spec_of_enc_func_b\n          (encrypt: nat -> nat -> nat) :=\n  forall B a: nat,\n    encrypt B a = a * B.\n\nDefinition ECC_secret_a (A b: nat) :=\n  A * b.\n\nDefinition ECC_secret_b (B a: nat) :=\n  B * a.\n\n(* Assertion that encrypting using either keys will\n   result in the same outcome *)\nTheorem Prove_validity_of_ECC_DH:\n  forall encrypt_a encrypt_b: nat -> nat -> nat,\n    spec_of_enc_func_a encrypt_a ->\n    spec_of_enc_func_b encrypt_b ->\n    forall A B G a b n: nat,\n      valid_key_pair A B G a b n ->\n      encrypt_a A b = encrypt_b B a.\n\n(* Proof to validate the Elliptic Curve \n   Diffie-Hellman theorem *)\nProof.\n  intros encrypt_a encrypt_b h_encrypt_a h_encrypt_b A B G a b n h_valid_key_pair.\n  assert (h_temp := h_valid_key_pair).\n  unfold valid_key_pair in h_temp.\n  destruct h_temp as [h_valid_a_secret h_valid_b_secret].\n  destruct h_valid_b_secret as [h_valid_b_secret h_key_a_generation].\n  destruct h_key_a_generation as [h_key_a_generation h_key_b_generation].\n  destruct h_key_b_generation as [h_key_b_generation h_valid_point_order].\n \n  unfold spec_of_enc_func_a in h_encrypt_a.\n  unfold spec_of_enc_func_b in h_encrypt_b.\n  unfold key_a_generation in h_key_a_generation.\n  unfold key_b_generation in h_key_b_generation.\n  unfold valid_a_secret in h_valid_a_secret.\n  unfold valid_b_secret in h_valid_b_secret.\n  unfold valid_point_order in h_valid_point_order.\n\n  rewrite -> h_encrypt_a.\n  rewrite -> h_encrypt_b.\n\n  rewrite -> h_key_a_generation.\n  rewrite -> h_key_b_generation.\n  ring_simplify.\n  reflexivity.\nQed.\nPrint Prove_validity_of_ECC_DH.\n\n\n\n\n", "meta": {"author": "danmaddock265", "repo": "Final-Year-Project", "sha": "ad3c9acff35a9d807253901458985eaa13fe31ef", "save_path": "github-repos/coq/danmaddock265-Final-Year-Project", "path": "github-repos/coq/danmaddock265-Final-Year-Project/Final-Year-Project-ad3c9acff35a9d807253901458985eaa13fe31ef/EllipticCurveProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7176667927623006}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import all_rs_base rs_dscrt rs_usig rs_reals.\nRequire Import Qreals Reals Psatz ClassicalChoice.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection CAUCHYREALS.\nImport QArith.\nLocal Open Scope R_scope.\n\nDefinition rep_R : (Q -> Q) -> R -> Prop :=\n  fun phi x => forall eps, 0 < Q2R eps-> Rabs(x-Q2R(phi eps)) <= Q2R eps.\n(* This is close to the standard definition of the chauchy representation. Usually integers\nare prefered to avoid to many possible answers. I tried using integers, but it got very ugly\nso I gave up at some point. I feel like the above is the most natural formulation of the Cauchy\nrepresentation anyway. *)\n\nLemma rep_R_sing: rep_R \\is_single_valued.\nProof.\nmove => phi x x' phinx phinx'.\napply (cond_eq_f accf_Q2R_0) => q qg0.\nset r := Q2R (phi (q/(1 + 1))%Q); rewrite /R_dist.\nreplace (x-x') with ((x-r) + (r-x')) by field.\napply /triang /Rle_trans.\n\tapply /Rplus_le_compat; last rewrite Rabs_minus_sym; [apply phinx | apply phinx'];\n\t\trewrite Q2R_div; try lra; rewrite {2}/Q2R/=; lra.\nby rewrite Q2R_div; try lra; rewrite {2 4}/Q2R/=; lra.\nQed.\n\n(* Auxillary lemmas for the proof that the Cauchy representation is surjective. *)\nLemma approx : forall r, r - Int_part r <= 1.\nProof.\nmove => r; move: (base_Int_part r) => [bipl bipr]; lra.\nQed.\n\nLemma approx' : forall r, 0 <= r - Int_part r.\nProof.\nmove => r; move: (base_Int_part r) => [bipl bipr]; lra.\nQed.\n\n(* The notation is_representation is for being single_valued and surjective. *)\nLemma rep_R_is_rep: rep_R \\is_representation.\nProof.\nsplit => [ | x]; first exact: rep_R_sing.\nexists (fun eps => Qmult eps (Qmake(Int_part(x/(Q2R eps))) xH)) => epsr eg0.\nrewrite Q2R_mult.\nset eps := Q2R epsr.\nrewrite Rabs_pos_eq.\n\tset z := Int_part(x/eps).\n\treplace (x - eps * Q2R (z#1)) with (eps * (x / eps - z));first last.\n\t\trewrite /Q2R/=; field.\n\t\tby apply: Rlt_dichotomy_converse; right; rewrite /eps.\n\trewrite -{3}(Rmult_1_r eps).\n\tapply: Rmult_le_compat_l; first by left; rewrite /eps.\n\tapply: (approx (x * /eps)).\napply: (Rmult_le_reg_l (/eps)).\n\tby apply: Rinv_0_lt_compat; rewrite /eps.\nrewrite Rmult_0_r.\nset z := Int_part(x/eps).\nreplace (/eps*(x - eps * Q2R (z#1))) with (x/eps - z);last first.\n\trewrite /Q2R/=.\n\tfield.\n\tby apply: Rlt_dichotomy_converse; right; rewrite /eps.\nby apply (approx' (x * /eps)).\nQed.\n\nLemma rationals_countable: Q \\is_countable.\nProof.\nAdmitted.\n\nCanonical rep_space_R := @make_rep_space\n\tR\n\tQ\n\tQ\n\trep_R\n\t1%Q\n\t1%Q\n\trationals_countable\n\trationals_countable\n\trep_R_is_rep.\n\nLemma id_is_computable : (id : R -> R) \\is_computable_function.\nProof. by apply/ rec_fun_cmpt; exists (fun phi => phi). Qed.\n\nLemma Q_rec_elts q: (Q2R q) \\is_recursive_element.\nProof.\nexists (fun eps => q).\nby abstract by move => eps ineq; apply/ Rbasic_fun.Rabs_le; lra.\nDefined.\n\n\nSection addition.\nLemma Ropp_rec_fun:\n\tRopp \\is_recursive_function.\nProof.\nexists (fun phi q => Qopp (phi q)).\nby abstract by move => phi x phinx eps epsg0 /=; rewrite Q2R_opp; move: (phinx eps epsg0); split_Rabs; lra.\nDefined.\n\nLemma Ropp_cmpt_fun:\n\tRopp \\is_computable_function.\nProof. exact/rec_fun_cmpt/Ropp_rec_fun. Defined.\n\nDefinition Rplus_frlzr (phi: names (rep_space_prod rep_space_R rep_space_R)) (eps: questions rep_space_R) :=\n  (Qplus (phi (inl (Qdiv eps (1+1)))).1 (phi (inr (Qdiv eps (1+1)))).2).\n\nLemma Rplus_frlzr_crct:\n\tRplus_frlzr \\is_realizer_function_for (fun x => Rplus x.1 x.2).\nProof.\nmove => phi x phinx eps eg0.\nrewrite /Rplus_frlzr Q2R_plus.\nset phi0 := (fun q => (phi (inl q)).1).\nset phi1 := (fun q => (phi (inr q)).2).\nset r := Q2R (phi0 (Qdiv eps (1 + 1))).\nset q := Q2R (phi1 (Qdiv eps (1 + 1))).\nreplace (x.1 + x.2 - (r + q)) with (x.1 - r + (x.2 - q)); last first.\n\tfield.\napply: triang.\nrewrite -(eps2 (Q2R eps)).\nreplace ((Q2R eps)*/2) with (Q2R (eps/ (1 + 1))); last first.\n\trewrite Q2R_div; last by lra.\n\tby rewrite {2}/Q2R/=; lra.\napply: Rplus_le_compat; apply phinx.\n\trewrite Q2R_div /=; last by lra.\n\tby rewrite {2}/Q2R/=; lra.\nrewrite Q2R_div /=; last by lra.\nby rewrite {2}/Q2R/=; lra.\nQed.\n\nLemma Rplus_rec_fun : Rplus \\is_recursive_function.\nProof.\nexists Rplus_frlzr.\nexact: Rplus_frlzr_crct.\nDefined.\n\nLemma Rplus_cmpt_fun:\n\tRplus \\is_computable_function.\nProof.\nexact/rec_fun_cmpt/Rplus_rec_fun.\nDefined.\nEnd addition.\n\nSection multiplication.\n(* Multiplication is more involved as the precision of approximations that have to be used\ndepends on the size of the inputs *)\nLet trunc (eps: questions rep_space_R) := if Qlt_le_dec eps 1 then eps else (1%Q: questions rep_space_R).\nLet rab := (fun (phi : Q -> Q) => inject_Z(up(Rabs(Q2R(phi (1#2)))+1))).\nDefinition Rmult_frlzr (phi: names (rep_space_prod rep_space_R rep_space_R)) (eps: questions rep_space_R) :=\n  ((phi (inl (trunc eps / (1 + 1)/(rab (fun q => (phi(inr q)).2))))).1\n  *\n  (phi (inr (eps / (1 + 1)/(rab (fun q => (phi(inl q) ).1))))).2)%Q.\n\nLemma Rmult_frlzr_crct:\n\tRmult_frlzr \\is_realizer_function_for (fun x => Rmult x.1 x.2).\nProof.\nhave rab_pos: forall phi, Q2R (rab phi) >= 1.\n\tmove => phi; rewrite /Q2R/rab/=.\n\treplace (/ 1) with 1 by field; rewrite Rmult_1_r; apply Rle_ge.\n\tapply: Rle_trans; last by\tapply Rlt_le; apply archimed.\n\tby rewrite -{1}(Rplus_0_l 1); apply Rplus_le_compat_r; exact: Rabs_pos.\nhave ineq: forall eps, Q2R (trunc eps) <= (Q2R eps).\n\tby move => eps; rewrite /trunc; case: (Qlt_le_dec eps 1) => ass /=; [lra | apply Qle_Rle].\nmove => phipsi [x y] [phinx psiny] eps eg0 /=.\nrewrite Q2R_mult.\nset phi := (fun q:Q => (phipsi (inl q)).1:Q).\nrewrite -/phi/= in phinx.\nset psi := (fun q:Q => (phipsi (inr q)).2:Q).\nrewrite -/psi/= in psiny.\nset r := Q2R (phi (trunc eps / (1 + 1) / rab psi)%Q).\nset q := Q2R (psi (eps / (1 + 1) / rab phi)%Q).\nspecialize (ineq eps).\nhave truncI: 0 < Q2R (trunc eps) <= 1.\n\trewrite /trunc; case: (Qlt_le_dec eps 1) => /= ass; last by rewrite /Q2R/=; lra.\n\tsplit => //; apply Rlt_le; replace 1 with (Q2R 1) by by rewrite /Q2R/=; lra.\n\tby apply Qlt_Rlt.\nhave g0: 0 < Q2R (eps / (1 + 1)) by rewrite Q2R_div; first rewrite {2}/Q2R/=; lra.\nhave rabneq: forall phi', ~ rab phi' == 0.\n\tmove => phi' eq; move: (Qeq_eqR (rab phi') 0 eq).\n\tapply Rgt_not_eq; replace (Q2R 0) with 0 by by rewrite /Q2R/=; lra.\n\tspecialize (rab_pos phi'); lra.\nreplace (x * y - r * q) with ((x - r) * y + r * (y - q)) by field.\napply: triang.\nreplace (Q2R eps) with (Q2R (eps/ (1 + 1)) + Q2R (eps/ (1 + 1))); last first.\n\trewrite Q2R_div; first rewrite {2 4}/Q2R/=; lra.\napply: Rplus_le_compat.\n\tspecialize (rab_pos psi).\n\trewrite Rabs_mult.\n\tcase: (classic (y = 0)) => [eq | neq].\n\t\tby apply/ Rle_trans; last apply/ Rlt_le /g0; rewrite eq Rabs_R0; lra.\n\trewrite -(Rmult_1_r (Q2R (eps / (1 + 1)))) -(Rinv_l (Rabs y)); last by split_Rabs; lra.\n\trewrite -Rmult_assoc;\tapply: Rmult_le_compat; [ split_Rabs | split_Rabs | | ]; try lra.\n\tapply/ Rle_trans; first apply phinx; rewrite Q2R_div => //.\n\t\tapply Rmult_gt_0_compat; last by apply Rlt_gt; apply Rinv_0_lt_compat; lra.\n\t\tby apply Rlt_gt; rewrite Q2R_div; first rewrite {2}/Q2R/=; lra.\n\tapply Rmult_le_compat; [ | apply Rlt_le; apply Rinv_0_lt_compat; lra | | ].\n\t\t\trewrite Q2R_div; first rewrite {2}/Q2R/=; first apply Rlt_le; lra.\n\t\tby rewrite !Q2R_div; [ | lra | lra]; apply Rmult_le_compat_r; first by rewrite /Q2R/=; lra.\n\tapply: Rinv_le_contravar; first\texact: Rabs_pos_lt.\n\trewrite /rab {1}/Q2R/=; replace (/1) with 1 by lra; rewrite Rmult_1_r.\n\tapply/ Rle_trans; last apply/ Rlt_le; last apply: (archimed (Rabs (Q2R (psi (1#2)))+1)).1.\n\tsuffices: (Rabs y -Rabs (Q2R (psi (1#2))) <= 1) by lra.\n\tapply/ Rle_trans; first by apply: Rabs_triang_inv.\n\tapply: Rle_trans; first apply: psiny; rewrite /Q2R/=; lra.\nrewrite Rabs_mult.\ncase: (classic (r = 0)) => [eq | neq].\n\tby apply/ Rle_trans; [rewrite eq Rabs_R0 | apply/ Rlt_le/ g0]; lra.\nrewrite /Qdiv -(Rmult_1_l (Q2R (eps / (1 + 1)))).\nrewrite -(Rinv_r (Rabs r)); last by split_Rabs; lra.\nrewrite Rmult_assoc.\napply: Rmult_le_compat; [ split_Rabs | split_Rabs | | ]; try lra; rewrite Rmult_comm.\napply/ Rle_trans; first rewrite /q; first apply psiny.\n\trewrite Q2R_div => //; apply Rmult_gt_0_compat=>//; apply Rlt_gt.\n\tby apply Rinv_0_lt_compat; have:= rab_pos phi; lra.\nrewrite Q2R_div => //.\napply Rmult_le_compat_l => //; first by rewrite Q2R_div => //; apply Rlt_le; rewrite {2}/Q2R/=; lra.\napply Rle_Rinv; first exact: Rabs_pos_lt.\n\tspecialize (rab_pos phi); lra.\nrewrite /rab {1}/Q2R/=; replace (/1) with 1 by lra; rewrite Rmult_1_r.\napply/ Rle_trans; last apply/ Rlt_le; last apply: (archimed (Rabs (Q2R (phi (1#2)))+1)).1.\nsuffices: (Rabs r -Rabs (Q2R (phi (1#2))) <= 1) by lra.\napply/ Rle_trans; first apply: Rabs_triang_inv.\napply: Rle_trans.\n\treplace (r - Q2R (phi (1#2))) with ((r - x) - (Q2R (phi (1#2)) - x)) by field.\n\tapply /triang/ Rplus_le_compat; last by rewrite Ropp_minus_distr; apply phinx; rewrite /Q2R/=; lra.\n\trewrite Rabs_minus_sym; apply phinx.\n\tspecialize (rab_pos psi); rewrite !Q2R_div => //; rewrite {2}/Q2R/=.\n\tby apply Rmult_gt_0_compat; try lra; apply /Rlt_gt/ Rinv_0_lt_compat; lra.\nspecialize (rab_pos psi).\nrewrite !Q2R_div; [ | by lra | trivial].\nrewrite {4}/Q2R/= {1}/Rdiv.\nreplace (1 * / 2) with (/2 * 1) by lra.\nrewrite -(Rinv_r (Q2R (rab psi))); try lra.\nrewrite -Rmult_assoc -Rmult_plus_distr_r.\napply: Rmult_le_compat_r; first by apply Rlt_le; apply Rinv_0_lt_compat; lra.\nsuffices: Q2R (trunc eps) / Q2R (1 + 1) <= Q2R (rab psi)/2 by lra.\nby rewrite !/Rdiv {2}/Q2R/=; apply Rmult_le_compat; try lra.\nQed.\n\nLemma Rmult_rec_fun : Rmult \\is_recursive_function.\nProof.\nexists Rmult_frlzr; exact: Rmult_frlzr_crct.\nDefined.\n\nLemma Rmult_cmpt_fun:\n\tRmult \\is_computable_function.\nProof. exact/rec_fun_cmpt/Rmult_rec_fun. Defined.\nEnd multiplication.\n\nSection limit.\n(* The unrestricted limit function is discontinuous with respect to the Cauchy representation,\nand thus there is no hope to prove it computable *)\nLemma lim_not_cont: ~lim \\has_continuous_realizer.\nProof.\nmove => [/= F [/= rlzr cont]].\npose xn (n: nat):R := 0.\npose qn (p: (nat * Q)) := 0%Q.\nhave qnxn: @delta (rep_space_usig_prod rep_space_R) qn xn.\n\tmove => n eps ineq; rewrite /qn /xn {1}/Q2R/=; split_Rabs; lra.\nhave limxn0: lim xn 0.\n\tmove => eps ineq;\texists 0%nat.\n\tmove => n ineq'; rewrite /xn;\tsplit_Rabs; lra.\npose zn (eps:Q) := 0%Q.\nhave zn0: zn \\is_name_of 0.\n\tmove => eps ineq; rewrite {1}/Q2R/=; split_Rabs; lra.\nhave qnfdF: qn \\from_dom F.\n\thave qnfd: qn \\from_dom (lim o (delta (r:=rep_space_usig_prod rep_space_R))).\n\t\texists 0;\tsplit.\n\t\t\texists xn => //.\n\t\tmove => yn name.\n\t\trewrite -(rep_sing (rep_space_usig_prod rep_space_R) qn xn yn) => //.\n\t\tby exists 0.\n\thave [x [[phi [Fqnphi]]] _ _]:= (rlzr qn qnfd).1.\n\tby exists phi.\nhave [L [/=_ Lprop]]:= (cont qn qnfdF 1%Q).\nset fold := @List.fold_right nat nat.\nset m:= fold maxn 0%N (unzip1 L).\nhave mprop: forall n eps, List.In (n, eps) L -> (n <= m)%nat.\n\tmove: Lprop => _; rewrite /m; move: m => _.\n\telim: L => // a L ih n eps /= lstn.\n\tcase: lstn => ass.\n\t\tby apply/ leq_trans; last apply leq_maxl; rewrite ass.\n\tby apply/ leq_trans; last apply leq_maxr; apply (ih n eps).\npose yn n := if (n <= m)%nat then 0 else 3.\npose rn (p: nat * Q) := if (p.1 <= m)%nat then 0%Q else 3#1.\nhave rnyn: @delta (rep_space_usig_prod rep_space_R) rn yn.\n\tmove => n eps ineq; rewrite /rn /yn.\n\tcase: ifP => ineq'; rewrite {1}/Q2R/=; split_Rabs; lra.\nhave limyn3: lim yn 3.\n\tmove => eps ineq.\n\texists (S m) => n ineq'.\n\trewrite /yn.\n\tcase: ifP; last by split_Rabs; lra.\n\tmove  => ineq''.\n\thave: (n <= m)%coq_nat by apply /leP.\n\thave: (m < n)%coq_nat by apply /leP.\n\tlia.\nhave rnfdF: rn \\from_dom F.\n\thave rnfd: rn \\from_dom (lim o (delta (r:=rep_space_usig_prod rep_space_R))).\n\t\texists 3;\tsplit.\n\t\t\texists yn => //.\n\t\tmove => y'n name.\n\t\trewrite -(rep_sing (rep_space_usig_prod rep_space_R) rn yn y'n) => //.\n\t\tby exists 3.\n\thave [x [[phi [Fqnphi]]] _ _]:= (rlzr rn rnfd).1.\n\tby exists phi.\nhave coin: qn \\and rn \\coincide_on L.\n\tapply /coin_lstn => [[n eps] listin].\n\trewrite /qn /rn.\n\tcase: ifP => // /= ineq.\n\tspecialize (mprop n eps listin).\n\thave nineq: (~n <= m)%coq_nat by apply /leP; rewrite ineq.\n\thave ge:= not_le n m nineq.\n\thave fineq: (n <= m)%coq_nat by apply /leP.\n\tlia.\nhave [phi Frnphi ]:= rnfdF.\nhave [psi Fqnpsi]:= qnfdF.\nhave /=eq':= Lprop psi Fqnpsi rn coin phi Frnphi.\nhave eq: psi 1%Q == phi 1%Q by rewrite eq'.\nhave := Qeq_eqR (psi 1%Q) (phi 1%Q) eq.\nhave psin0: psi \\is_name_of 0 by apply/ rlzr_val_sing; [apply lim_sing | apply rlzr | | | ].\nhave phin3: phi \\is_name_of 3.\n\tby apply/ rlzr_val_sing; [apply lim_sing | apply rlzr | apply rnyn | | ].\nhave l01: 0 < Q2R 1 by rewrite /Q2R/=; lra.\nhave:= psin0 1%Q l01.\nhave:= phin3 1%Q l01.\nrewrite {2 4}/Q2R/=.\nsplit_Rabs; lra.\nQed.\n\nFixpoint Pos_size p := match p with\n\t| xH => 1%nat\n\t| xI p' => S (Pos_size p')\n\t| xO p' => S (Pos_size p')\nend.\n\nLemma Pos_size_gt0 p: (0 < Pos_size p)%nat.\nProof. by elim p. Qed.\n\nDefinition Z_size z:= match z with\n\t| Z0 => 0%nat\n\t| Z.pos p => Pos_size p\n\t| Z.neg p => Pos_size p\nend.\n\nLemma Z_size_eq0 z: Z_size z = 0%nat <-> z = 0%Z.\nProof.\nsplit; last by move => ->.\ncase z => // p /=; have := Pos_size_gt0 p => /leP ineq eq; rewrite eq in ineq; lia.\nQed.\n\nLemma Z_size_lt z: IZR z < 2 ^ (Z_size z).\nProof.\nrewrite pow_IZR; apply IZR_lt; rewrite -two_power_nat_equiv.\nelim: z => // p; elim: p => // p /= ih.\nrewrite !Pos2Z.inj_xI two_power_nat_S.\nhave ineq: (Z.pos p + 1 <= two_power_nat (Pos_size p))%Z by lia.\napply/ Z.lt_le_trans; last by apply Zmult_le_compat_l; last lia; apply ineq.\nby lia.\nQed.\n\nLemma size_Qden_leq eps: 0 < Q2R eps -> /2^(Pos_size (Qden eps)) <= Q2R eps.\nProof.\nmove => ineq; rewrite /Q2R/Rdiv /Qdiv -[/_]Rmult_1_l.\napply Rmult_le_compat; [ | apply Rlt_le; apply Rinv_0_lt_compat; apply pow_lt | | ]; try lra.\n\tapply IZR_le; suffices: (0 < Qnum eps)%Z by lia.\n\tby apply Qnum_gt; apply Rlt_Qlt; rewrite {1}/Q2R/=; try lra.\napply Rinv_le_contravar; first exact /IZR_lt/Pos2Z.is_pos.\nby have /=:= Z_size_lt (Z.pos (Qden eps)); lra.\nQed.\n\nDefinition lim_eff_frlzr (phin: names (rep_space_usig_prod rep_space_R)) :(names rep_space_R) :=\n\tfun eps =>\tphin (S (Pos_size (Qden eps))%nat, (Qmult eps (1#2))).\n\n(* The proof of this was done ages ago, it should be overhauled *)\nLemma lim_eff_frlzr_crct:\n\tlim_eff_frlzr \\is_rec_realizer_of lim_eff.\nProof.\nmove => psi xn psinxn [x limxnx].\nexists x; split => //.\nmove => eps epsg0.\n\tset N:= (Pos_size (Qden eps)).\n\thave ->: x - Q2R (lim_eff_frlzr psi eps) = x - (xn N.+1) + (xn N.+1 - Q2R (lim_eff_frlzr psi eps)) by lra.\n\trewrite /lim_eff_frlzr -/N.\n\tapply /triang /Rle_trans.\n\t\tapply /Rplus_le_compat; first by rewrite Rabs_minus_sym; apply/limxnx.\n\tby apply psinxn; rewrite Q2R_mult {2}/Q2R/=; lra.\nhave lt1:= pow_lt 2 (Pos_size (Qden eps)); have lt2:= size_Qden_leq epsg0; try lra.\nrewrite Q2R_mult {2}/Q2R /= /N Rinv_mult_distr; try lra.\nQed.\n\nLemma lim_eff_rec:\n\tlim_eff \\is_recursive.\nProof. by exists lim_eff_frlzr; apply lim_eff_frlzr_crct. Defined.\n\nLemma lim_eff_cmpt: lim_eff \\is_computable.\nProof. by apply /rec_cmpt /lim_eff_rec. Defined.\nEnd limit.\n\n(*\nLemma cont_rlzr_cont (f: R -> R):\n\t(F2MF f) \\has_continuous_realizer <-> continuity f.\nProof.\nsplit.\n\tmove => [F [Frf Fcont]] x e eg0.\n\thave [phi phinx]:= rep_sur rep_space_R x.\n\thave [eps [epsg0 epsle]]:= Q_accumulates_to_zero eg0.\n\thave phifd: phi \\from_dom F by apply/ rlzr_dom; [apply Frf |\tapply phinx | apply F2MF_tot].\n\thave [L Lprop]:= Fcont phi eps phifd.\n\tset fold := @List.fold_right R Q.\n\tset delta:= fold (fun q => Rmin (Q2R q)) (Q2R eps) L.\n\texists delta.\n\t\thave: delta <= e.\n\t\t\trewrite /delta/=.\n\t\t\telim: (L) => /=; try lra; move => a K ih.\n\t\t\tapply/ Rle_trans; [exact: Rmin_r | exact: ih].\n\tsplit.\n\nAdmitted.\n\n\nDefinition ps_eval an (x: I) y:=\n\tlim (fun m => eval (in_seg an m) (projT1 x)) y.\n\nDefinition geo_series n := 1/(two_power_nat n).\n\nLemma geo_series_comp_elt:\n\tgeo_series \\is_computable_element.\nProof.\nexists (fun p => 1/inject_Z (two_power_nat p.1))%Q.\nmove => n eps epsg0 /=.\nsuffices <-: geo_series n  = Q2R (1 / inject_Z (two_power_nat n)) by split_Rabs; lra.\nrewrite /geo_series.\nsuffices ->: (Q2R (1 / inject_Z (two_power_nat n))) = (1/ Q2R (inject_Z (two_power_nat n))).\n\tsuffices ->: IZR (two_power_nat n) = Q2R (inject_Z(two_power_nat n)) by trivial.\n\tby rewrite /Q2R/inject_Z /=; rewrite Rinv_1 Rmult_1_r.\nby rewrite /Q2R/= Rinv_1 Rmult_1_r/=.\nDefined.\n\nLemma geo_series_sum x:\n\tps_eval geo_series x (1/(1-(projT1 x)/2)).\nProof.\nAdmitted.\n\nLemma analytic (an: nat -> R):\n\teff_zero an -> (fun (x: I) (y: R) => ps_eval an x y) \\is_prec.\nProof.\nmove => ez.\nrewrite /eff_zero in ez.\nAdmitted.\n*)\nEnd CAUCHYREALS.", "meta": {"author": "FlorianSteinberg", "repo": "coqrep", "sha": "1e644da9bdb75ab8f91a7db46ffda3f2825b32b8", "save_path": "github-repos/coq/FlorianSteinberg-coqrep", "path": "github-repos/coq/FlorianSteinberg-coqrep/coqrep-1e644da9bdb75ab8f91a7db46ffda3f2825b32b8/rs_reals_creals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7176667906028988}}
{"text": "\nRequire Import Game.\nRequire Import BaseGame.\n\nInductive RPS_player : Type := | J1 | J2.\nInductive RPS_choice : Type := | Rock | Paper | Scissors.\nInductive RPS_state  : Type :=\n  | NoWinner : RPS_state\n  | Winner : RPS_player -> RPS_state.\n\n\n\nDefinition RPS_rules (s:RPS_state) (dec:RPS_player -> RPS_choice) :=\n  match s with\n  | Winner p => Winner p\n  | NoWinner =>\n    match (dec J1, dec J2) with\n    | (Rock    , Scissors)\n    | (Scissors, Paper)\n    | (Paper   , Rock) => Winner J1\n    | (Rock    , Rock)\n    | (Scissors, Scissors)\n    | (Paper   , Paper) => NoWinner\n    | _ => Winner J2\n    end\n  end.\n\nDefinition RPS : Game :=\n  mkGame\n    RPS_player\n    RPS_state\n    NoWinner\n    (fun s p => RPS_choice)\n    RPS_rules.\n\n(*\nIf the game is not done yet, forall J1 move there is a winning move for J2.\nRandom is not yet in this model.\nBasically this holds because J1 and J2 both have access to all random variables.\n*)\nLemma J2_may_always_win :\n  forall s:RPS_state,\n  forall d1:decision RPS NoWinner J1,\n  exists d2:decision RPS NoWinner J2,\n    rules RPS\n          NoWinner\n          (fun p => match p with | J1 => d1 | J2 => d2 end) = s.\nProof.\n  Check RPS_state_ind.\n  intros.\n  destruct s.\n  destruct d1.\n  exists Rock. compute. auto.\n  exists Paper. compute. auto.\n  exists Scissors. compute. auto.\n  destruct d1.\n  destruct r.\n  exists Scissors. compute. auto.\n  exists Paper. compute. auto.\n  destruct r.\n  exists Rock. compute. auto.\n  exists Scissors. compute. auto.\n  destruct r.\n  exists Paper. compute. auto.\n  exists Rock. compute. auto.\nQed.\n\n\n", "meta": {"author": "Gaspi", "repo": "BGonCoq", "sha": "1b212fffbf0fb40c3d73523bf18fb402b568543a", "save_path": "github-repos/coq/Gaspi-BGonCoq", "path": "github-repos/coq/Gaspi-BGonCoq/BGonCoq-1b212fffbf0fb40c3d73523bf18fb402b568543a/G_RockPaperScissors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7176667884458917}}
{"text": "(**\nComposition of lax functors and pseudo functors.\n\nAuthors: Dan Frumin, Niels van der Weide\n\nPorted from: https://github.com/nmvdw/groupoids\n *)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.PrecategoryBinProduct.\nRequire Import UniMath.Bicategories.Core.Bicat. Import Bicat.Notations.\nRequire Import UniMath.Bicategories.Core.BicategoryLaws.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\nRequire Import UniMath.Bicategories.PseudoFunctors.Display.PseudoFunctorBicat.\nRequire Import UniMath.Bicategories.PseudoFunctors.PseudoFunctor.\nImport PseudoFunctor.Notations.\nLocal Open Scope cat.\nLocal Open Scope bicategory_scope.\n\nSection FunctorComposition.\n  Context {C D E : bicat}.\n  Variable (G : psfunctor D E) (F : psfunctor C D).\n\n  Definition comp_psfunctor_data : psfunctor_data C E.\n  Proof.\n    use make_psfunctor_data.\n    - exact (λ X, G(F X)).\n    - exact (λ _ _ f, #G(#F f)).\n    - exact (λ _ _ _ _ α, ##G(##F α)).\n    - exact (λ a, psfunctor_id G (F a) • ##G (psfunctor_id F a)).\n    - exact (λ _ _ _ f g, psfunctor_comp G (#F f) (#F g) • ##G (psfunctor_comp F f g)).\n  Defined.\n\n  Definition comp_is_ps : psfunctor_laws comp_psfunctor_data.\n  Proof.\n    repeat split.\n    - intros a b f ; cbn in *.\n      rewrite !psfunctor_id2.\n      reflexivity.\n    - intros a b f g h α β ; cbn in *.\n      rewrite !psfunctor_vcomp.\n      reflexivity.\n    - intros a b f ; cbn in *.\n      rewrite !psfunctor_lunitor.\n      rewrite <- rwhisker_vcomp.\n      rewrite !vassocr.\n      rewrite !psfunctor_vcomp.\n      rewrite !vassocl.\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite <- psfunctor_rwhisker.\n      reflexivity.\n    - intros a b f ; cbn.\n      rewrite !psfunctor_runitor.\n      rewrite <- lwhisker_vcomp.\n      rewrite !psfunctor_vcomp.\n      rewrite !vassocl.\n      apply maponpaths.\n      rewrite !vassocr.\n      rewrite <- psfunctor_lwhisker.\n      reflexivity.\n    - intros a b c d f g h ; cbn.\n      rewrite <- !lwhisker_vcomp.\n      rewrite !vassocl.\n      rewrite <- psfunctor_vcomp.\n      rewrite !(maponpaths (λ z, _ • z) (vassocr _ _ _)).\n      rewrite <- psfunctor_lwhisker.\n      rewrite !vassocl.\n      rewrite <- !psfunctor_vcomp.\n      rewrite !vassocr.\n      pose @psfunctor_lassociator as p.\n      cbn in p.\n      rewrite p ; clear p.\n      rewrite !psfunctor_vcomp.\n      rewrite !vassocl.\n      rewrite !vassocr.\n      apply (maponpaths (λ z, z • _)).\n      rewrite psfunctor_lassociator.\n      rewrite !vassocl.\n      apply (maponpaths (λ z, _ • z)).\n      rewrite psfunctor_rwhisker.\n      rewrite <- !rwhisker_vcomp.\n      rewrite !vassocr.\n      reflexivity.\n    - intros a b c f g₁ g₂ α ; cbn.\n      rewrite !vassocl.\n      rewrite <- psfunctor_vcomp.\n      rewrite !psfunctor_lwhisker.\n      rewrite !vassocr.\n      pose (@psfunctor_lwhisker _ _ G) as p.\n      cbn in p ; rewrite <- p ; clear p.\n      rewrite psfunctor_vcomp.\n      rewrite !vassocr.\n      reflexivity.\n    - intros a b c f g₁ g₂ α ; cbn.\n      rewrite !vassocl.\n      rewrite <- psfunctor_vcomp.\n      rewrite !psfunctor_rwhisker.\n      rewrite !vassocr.\n      pose (@psfunctor_rwhisker _ _ G) as p.\n      cbn in p ; rewrite <- p ; clear p.\n      rewrite psfunctor_vcomp.\n      rewrite !vassocr.\n      reflexivity.\n  Qed.\n\n  Definition comp_psfunctor : psfunctor C E.\n  Proof.\n    use make_psfunctor.\n    - exact comp_psfunctor_data.\n    - exact comp_is_ps.\n    - split.\n      + intros a ; cbn.\n        is_iso.\n        * exact (psfunctor_id G (F a)).\n        * exact (psfunctor_is_iso G (psfunctor_id F a)).\n      + intros a b c f g ; cbn.\n        is_iso.\n        * exact (psfunctor_comp G (#F f) (#F g)).\n        * exact (psfunctor_is_iso G (psfunctor_comp F f g)).\n  Defined.\n\n  Definition comp_psfunctor_cell\n             {X Y : C}\n             {f g : X --> Y}\n             (α : f ==> g)\n    : ## comp_psfunctor α = ## G (## F α).\n  Proof.\n    apply idpath.\n  Qed.\n\n  Definition comp_psfunctor_psfunctor_id\n             (X : C)\n    : pr1 (psfunctor_id comp_psfunctor X)\n      =\n      psfunctor_id G (F X) • ##G (psfunctor_id F X).\n  Proof.\n    apply idpath.\n  Qed.\n\n  Definition comp_psfunctor_psfunctor_comp\n             {X Y Z : C}\n             (f : X --> Y) (g : Y --> Z)\n    : pr1 (psfunctor_comp comp_psfunctor f g)\n      =\n      psfunctor_comp G (#F f) (#F g) • ##G (psfunctor_comp F f g).\n  Proof.\n    apply idpath.\n  Qed.\nEnd FunctorComposition.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Bicategories/PseudoFunctors/Examples/Composition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7176213130797248}}
{"text": "Require Import ords ssreflect ssrfun ssrbool pg3x_spec pg33_ind.\nRequire Import wlog.\n\nModule PS : ProjectiveSpace.\n\n  Definition Point := Point.\n  Definition Line := Line.\n\n  Definition incid_lp := incid_lp. \n  Definition eqP := eqP.\n  Definition eqL := eqL.\n\n  (** a1_exists : existence of a line generated from 2 points *)\n\n  Check l_from_points.\n  \n  Ltac prove_a1_exists :=\n    let A:=fresh in\n    let B:=fresh in\n    intros A B;  pose (l:=(l_from_points A B));\n                   revert l;case A; case B; intros l; exists l; exact (erefl true).\n\n  Lemma a1_exists : forall A B : Point,\n      {l : Line | incid_lp A l && incid_lp B l}.\n  Proof.\n    idtac \"-> proving a1_exists\".\n    time (prove_a1_exists).\n    Time Qed.\n  Check a1_exists.\n\n  (** a3_1 : every line has at least three distinct points *)\n  \n  Ltac exists_p3 t u v :=\n    exact (existT _ t \n                  (existT _  u \n                          (exist _   v (erefl true)))).\n  \n  Ltac prove_a3_1 := let l := fresh \"l\" in\n                     let x := fresh \"x\" in\n                     intros l; pose (x:= points_from_line l); revert x;\n                     case l; intros x;\n                     exists_p3 (fst (fst (fst x))) (snd (fst (fst x))) (snd (fst x)).\n\n  Definition dist_3p  (A B C :Point) : bool := (negb (eqP A B)) && (negb (eqP A C)) && (negb (eqP B C)).\n\n  Lemma a3_1 : \n    forall l:Line,{A:Point &{B:Point &{ C:Point| \n            dist_3p A B C && (incid_lp A l && incid_lp B l && incid_lp C l)}}}.\n    Proof.\n    idtac \"-> proving a3_1\".\n    time (prove_a3_1).\n    Time Qed. \n\n    Check a3_1.\n\n  (** a1_unique : unicity of the line generated from 2 points *)\n  (** l_from_points is actually a1_exists *)\n  Check l_from_points.\n  Check a1_exists.\n\n  Lemma points_line : forall T Z:Point, forall x:Line,\n        incid_lp T x -> incid_lp Z x -> (T<>Z) -> x = (l_from_points T Z).\n  Proof.\n    idtac \"-> proving points_line\".\n    time (intros T Z x;\n          case x; case T; intros HTx;\n          first [ discriminate | \n                 case Z; intros HZx HTZ;\n                 solve  [ discriminate |  exact (@erefl Line _) | apply False_rect; auto ] ]).\n    Time Qed.\n\n  Check points_line.\n  \n  Ltac handle x :=\n    match goal with Ht  : is_true (incid_lp ?T x),\n                    Hz  : is_true (incid_lp ?Z x),\n                    Htz : (not (@eq Point ?T ?Z))  |- _ =>\n                    let HP := fresh in pose proof (points_line T Z x Ht Hz Htz) as HP;\n                                       clear Ht Hz; rewrite HP(*; subst*)  end.\n\n  Ltac prove_a1_unique :=\n    let A:=fresh in\n    let B:= fresh in\n    let HAB' := fresh in \n    let l1:=fresh in\n    let l2:=fresh in\n    let HAB:=fresh in\n    let HAl1:=fresh in\n    let HBl1:= fresh in\n    let HAl2 := fresh in\n    let HBl2 := fresh in\n    intros A B l1 l2 HAB HAl1 HBl1 HAl2 HBl2;\n    revert A B HAB l1 HAl1 HBl1 l2 HAl2 HBl2;\n    intros  X; case X;\n    intros Y;case Y; intros HAB;\n    solve [apply False_rect; auto\n          | discriminate\n          | intros l1 HAl1 HBl1; handle l1; intros l2 HAl2 HBl2; handle l2; exact (@erefl Line _)].\n  \n  Lemma a1_unique:forall (A B :Point)(l1 l2:Line),\n      ~A=B -> incid_lp A l1 -> incid_lp B l1  -> incid_lp A l2 -> incid_lp B l2 -> l1=l2.\n  Proof.\n    idtac \"-> proving a1_unique\".\n    time(prove_a1_unique).\n    Time Qed.\n  \n  Check a1_unique.\n\n  Lemma Point_dec : forall T U:Point, {T=U}+{~T=U}.\n  Proof.\n    intros T U; case T; case U;\n      solve [left; exact (@erefl Point _) | right; discriminate].\n  Qed. \n\n  Ltac prove_uniqueness :=\n    let P:= fresh in\n    let Q:= fresh in\n    let hypP := fresh in\n    let HPQdiff := fresh in \n    let hypQ := fresh in\n    let HPQ := fresh in \n    let l := fresh in\n    let m := fresh in\n    let Hl := fresh in\n    let Hl' := fresh in\n    let Hm := fresh in\n    let Hm' := fresh in\n    intros P Q l m Hl Hl' Hm Hm';\n    revert l Hl Hl' m Hm Hm';\n    destruct (Point_dec P Q) as [HPQdiff | HPQdiff];\n    [left; rewrite HPQdiff; exact (@erefl Point _) | idtac]; revert HPQdiff;\n    case P; case Q; intros HPQdiff;\n    solve [discriminate |  \n      intros  l Hl Hl';handle l; intros m Hm Hm'; handle m; right; exact (@erefl Line _)].\n\n  Lemma uniqueness : forall (A B :Point)(l1 l2:Line),\n      incid_lp A l1 -> incid_lp B l1  -> incid_lp A l2 -> incid_lp B l2 -> A = B \\/ l1 = l2.\n  Proof.\n    idtac \"-> proving uniqueness\".\n    time(prove_uniqueness).\n    Time Qed.\n  Check uniqueness.\n  \n  (** a3_2 : there exists 2 lines which do not intersect, i.e. dim >= 3  *)\n\n  Ltac solve_a3_2 := let p:= fresh in\n                     intros p; case p;\n                     let hypp:=fresh in let t := fresh in intros hypp t; discriminate.\n\n  (*Ltac prove_a3_2 := try_all_l ltac:(fun l1 => exists l1; try_all_l ltac:(fun l2 => exists l2; solve_a3_2)).*)\n  \n  Lemma a3_2 : exists l1:Line, exists l2:Line, forall p:Point, ~(incid_lp p l1 && incid_lp p l2). \n  Proof.\n    idtac \"-> proving a3_2\".\n    exists L0; exists L34;intros p; case p; \n      let hypp:=fresh in let t := fresh in intros t; discriminate.\n    (*Time (prove_a3_2).*) (* we could have chosen GKL and EHM for instance:  exists (o 35 0); exists (o 35 34)).*)\n    Time Qed.\n  Check a3_2.\n\n(* a3_3 : given 3 lines, there exists a line which intersects these 3 lines *)\n\n  Definition Intersect_In (l1 l2 :Line) (P:Point) := incid_lp P l1 && incid_lp P l2.\n \n  (** points_from_l is actually a3_1 *)\n  \n  Definition points_from_l (l:Line) := points_from_line l.\n\n  Ltac exists_lppp l t u v :=\n    exact (ex_intro _  l \n                 (ex_intro _  t\n                  (ex_intro _ u \n                          (ex_intro _  v  (erefl true))))).\n\n  Definition dist_3l (A B C :Line) : bool :=\n    (negb (eqL A B)) && (negb (eqL A C)) && (negb (eqL B C)).\n\n  Lemma a3_3_simple :\n    forall v1 v2 v3:Line,\n      leL v1 v2-> leL v2 v3 ->\n      dist_3l v1 v2 v3 ->\n      exists v4 :Line, exists T1:Point, exists T2:Point, exists T3:Point,\n              (Intersect_In v1 v4 T1) && (Intersect_In v2 v4 T2) && (Intersect_In v3 v4 T3).\n   Proof.\n     idtac \"-> proving a3_3_simple\".\n     unfold dist_3l; intros v1 v2 v3 Hv1v2 Hv2v3 Hd;\n       pose (t:=f_a3_3 v1 v2 v3) ;\npose(l:=fst t); pose (x:= fst (fst (snd t))); pose (y:= snd (fst (snd t))); pose (z:=snd (snd t));\n       revert Hv1v2 Hv2v3 Hd t l x y z.\n\n     case v1.\n\n(*case v2;\n                  intros hp1p2;try exact (degen_bool _ hp1p2) .\n\ncase v3;intros hp1p3 hdist l x y z.*)\n\n    par: abstract\n           (time (case v2;\n                  intros hp1p2;\n                  first [exact (degen_bool _ hp1p2) | \n                         (case v3;\n                          intros hp1p3 hdist t l x y z;\n                          solve [ (exact (degen_bool _ hp1p3))\n                                | (exact (degen_bool _ hdist))\n                                | exists_lppp l x y z ])])).\n\n      Time Qed.\n(*233s*)\n   Lemma eqL_sym : forall x y:Line, eqL x y = eqL y x.\n    Proof.\n      idtac \"proving eqL_sym\".\n      time (intros; apply PeanoNat.Nat.eqb_sym). \n    Time Qed.\n    Check eqL_sym.\n    \n    Lemma eqP_sym : forall x y:Point, eqP x y = eqP y x.\n    Proof. \n      idtac \"proving eqP_sym\".\n      time (intros;apply PeanoNat.Nat.eqb_sym).\n    Time Qed.\n    Check eqP_sym.\n    \n    Lemma exchL: forall x y B C, ~~eqL y x && B &&C-> ~~eqL x y && B && C.\n    Proof.\n      intros x y b c H.\n      apply ab_bool in H.      \n      destruct H as [Hx Hy].\n      apply ab_bool in Hx.\n      destruct Hx.\n      apply ab_bool; split.\n      apply ab_bool; split.\n      rewrite eqL_sym.\n      assumption.\n      assumption.\n      assumption.\n    Qed.\n    \n    Lemma exchP: forall x y B C D E F,\n        ~~eqP y x && B &&C &&D &&E &&F-> ~~eqP x y && B && C && D && E &&F.\n    Proof.\n      intros x y b c d e f H.\n      apply ab_bool in H.\n      destruct H as [Ha Hf]; apply ab_bool in Ha;\n        destruct Ha as [Ha He]; apply ab_bool in Ha;\n          destruct Ha as [Ha Hd]; apply ab_bool in Ha;\n            destruct Ha as [Ha Hc]; apply ab_bool in Ha;\n              destruct Ha as [Ha Hb].\n      apply ab_bool; split.\n      apply ab_bool; split.\n      apply ab_bool; split.\n      apply ab_bool; split.\n      apply ab_bool; split.\n      rewrite eqP_sym.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n    Qed.\n\n   Lemma a3_3 : forall v1 v2 v3:Line,\n      dist_3l v1 v2 v3 -> exists v4 :Line,  exists T1:Point, exists T2:Point, exists T3:Point,\n             (Intersect_In v1 v4 T1) && (Intersect_In v2 v4 T2) && (Intersect_In v3 v4 T3).\n  Proof.\n    idtac \"-> proving a3_3\".\n    intros v1 v2 v3.\n    wlog3 v1 v2 v3 leL leL_total idtac idtac.\n\n    intros; apply a3_3_simple.\n    destruct (ab_bool_lr _ _  H) as [Ha1 Ha2]; exact Ha1.\n    destruct (ab_bool_lr _ _  H) as [Ha1 Ha2]; exact Ha2.\n    assumption.\n\n    intros.\n    assert (Hd: dist_3l x z y).\n    unfold dist_3l in *;\n      apply circ3;apply circ3;apply exchL;apply circ3; apply comm12L; assumption.\n    destruct (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t1; exists t3; exists t2.\n    apply circ3; apply circ3; apply comm12L; assumption.\n    \n    intros.\n    assert (Hd: dist_3l y x z).\n    unfold dist_3l in *; apply exchL; apply circ3; apply circ3; apply comm12L; assumption.\n    destruct (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t2; exists t1; exists t3.\n    apply comm12L; assumption.\n    \n    intros.\n    assert (Hd: dist_3l y z x).\n    unfold dist_3l in *.\n    apply circ3; apply exchL; apply circ3; apply exchL; apply circ3; apply circ3; assumption.\n    destruct (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t3; exists t1; exists t2.\n    apply circ3; assumption.\n    \n    intros.\n    assert (Hd: dist_3l z x y).\n    unfold dist_3l in *.\n    apply exchL; apply circ3; apply exchL; apply circ3; assumption.\n    destruct (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t2; exists t3; exists t1.\n    apply circ3; apply circ3; assumption.\n    \n    intros.\n    assert (Hd: dist_3l z y x).\n    unfold dist_3l in *.\n    apply exchL; apply circ3; apply exchL; apply circ3; apply exchL;\n      apply circ3; apply circ3; apply comm12L; assumption.\n    destruct  (H Hd) as [v4 [t1 [t2 [t3 Hv4t1t2t3]]]].\n    exists v4; exists t3; exists t2; exists t1.\n    apply comm12L; apply circ3;apply circ3; assumption. \n    Time Qed.\n  \n  (** a2 : Pasch's axiom *)\n\n  Definition dist_4p  (A B C D:Point) : bool :=\n    (negb (eqP A B)) && (negb (eqP A C)) && (negb (eqP A D))\n                     && (negb (eqP B C)) && (negb (eqP B D)) && (negb (eqP C D)).\n\n  Ltac findp' := match goal with\n                  |-  (@ex Point (fun J:Point => \n                                       is_true (andb (incid_lp J ?m) \n                                                     (incid_lp J ?p))))\n                  /\\ (@ex Point (fun K:Point => \n                                       is_true (andb (incid_lp K ?q) \n                                                     (incid_lp K ?r))))=> \n                  exact (conj (ex_intro _  ((*pg33_ind.*)f_a2 m p) (erefl true))\n                              (ex_intro _  ((*pg33_ind.*)f_a2 q r) (erefl true)))\n                 end.\n  \n  Lemma a2_conj_specific :\n    forall A B C D:Point, leP A B -> leP C D ->\n        let lAB := l_from_points A B in\n        let lCD := l_from_points C D in\n        let lAC := l_from_points A C in\n        let lBD := l_from_points B D in\n        let lAD := l_from_points A D in\n        let lBC := l_from_points B C in \n        \n        dist_4p A B C D -> \n        incid_lp A lAB && incid_lp B lAB ->  \n        incid_lp C lCD && incid_lp D lCD -> \n        incid_lp A lAC && incid_lp C lAC -> \n        incid_lp B lBD && incid_lp D lBD ->\n        incid_lp A lAD && incid_lp D lAD ->\n        incid_lp B lBC && incid_lp C lBC ->\n        \n        (exists I:Point, incid_lp I lAB && incid_lp I lCD) ->\n        (exists J:Point, (incid_lp J lAC && incid_lp J lBD)) /\\\n        (exists K:Point, (incid_lp K lAD && incid_lp K lBC)).\n  Proof.\n  idtac \"-> proving a2_conj_specific\".\n     intros A B C D HleAB HleCD lAB lCD lAC lBD lAD lBC Hdist HlAB HlCD HlAC HlBD HlAD HlBC Hex;\n       destruct (ab_bool_lr _ _ Hdist) as [Hdist1 HCD]; clear Hdist;\n         destruct (ab_bool_lr _ _ Hdist1) as [Hdist2 HBD]; clear Hdist1;\n           destruct (ab_bool_lr _ _ Hdist2) as [Hdist3 HBC]; clear Hdist2;\n             destruct (ab_bool_lr _ _ Hdist3) as [Hdist4 HAD]; clear Hdist3;\n               destruct (ab_bool_lr _ _ Hdist4) as [HAB HAC]; clear Hdist4;\n        revert A B HleAB HAB lAB HlAB C HBC HAC lBC HlBC lAC HlAC D HleCD HAD HBD HCD lAD HlAD lBD HlBD lCD HlCD Hex.\n\n     time (intros A B; case A; case B; intros HlePAB HAB lAB HlAB). \n     par: abstract (time (first [exact (degen_bool _ HlePAB) |exact (degen_bool _ HAB) | exact (degen_bool _ HlAB)| \n\n\n\n      (intros C; case C; intros HBC HAC lBC HlBC lAC HlAC; \n           first [  exact (degen_bool _ HBC) | exact (degen_bool _ HAC)\n                        |\n           \n                        (intros D; case D; intros HleCD HAD HBD HCD lAD HlAD lBD HlBD lCD HlCD Hex;\n\n                         first [ exact (degen_bool _ HleCD) | exact (degen_bool _ HAD)\n                                 | exact (degen_bool _ HBD) | exact (degen_bool _ HCD)\n                                 \n                                 | case Hex; intros t; case t; intros Ht;\n                                 first [exact (degen_bool _ Ht) | findp'] ])])])).\n  Qed.\n  Check a2_conj_specific.\n  \n  Lemma l_from_points_sym : forall x y:Point, l_from_points x y = l_from_points y x.\n  Proof.\n    intros x y; case x; case y; reflexivity.\n  Qed.\n\nLemma a2_conj :\n    forall A B C D:Point, dist_4p A B C D -> \n         let lAB := l_from_points A B in\n         let lCD := l_from_points C D in\n         let lAC := l_from_points A C in\n         let lBD := l_from_points B D in\n         let lAD := l_from_points A D in\n         let lBC := l_from_points B C in \n         \n         incid_lp A lAB && incid_lp B lAB ->  \n         incid_lp C lCD && incid_lp D lCD -> \n         incid_lp A lAC && incid_lp C lAC -> \n         incid_lp B lBD && incid_lp D lBD ->\n         incid_lp A lAD && incid_lp D lAD ->\n         incid_lp B lBC && incid_lp C lBC ->\n         \n         (exists I:Point, incid_lp I lAB && incid_lp I lCD) ->\n         (exists J:Point, (incid_lp J lAC && incid_lp J lBD)) /\\\n         (exists J:Point, (incid_lp J lAD && incid_lp J lBC)).\n  Proof.\n    intros A B.\n    wlog2 A B leP leP_total idtac idtac.\n    intros A B HleAB.\n    intros C D.\n    wlog2 C D leP leP_total idtac ltac:(intros; apply a2_conj_specific; assumption || exact I).\n    (* other cases *)\n\n    intros C D Hr.\n\n    intros lAB lCD lAC lBD lAD lBC Hdist HlAB HlCD HlAC HlBD HlAD HlBC Hex.\n    assert (Hd' : dist_4p A B D C).\n    unfold dist_4p in *.\n    apply circ6; apply comm12P; apply circ6; apply circ6 ; apply comm12P; apply circ6;\n    apply circ6; apply exchP; apply circ6; assumption.\n\n    assert (HlDC:(incid_lp D (l_from_points D C) && incid_lp C (l_from_points D C))).\n    apply circ2; rewrite l_from_points_sym; assumption. \n    assert (Hex': (exists I : Point, incid_lp I (l_from_points A B) && incid_lp I (l_from_points D C))).\n    rewrite (l_from_points_sym D C); assumption.\n    generalize (Hr Hd' HlAB HlDC HlAD HlBC HlAC HlBD Hex').\n    solve [intuition].\n\n    intros A B Hr C D.\n    intros Hd lAB lCD lAC lBD lAD lBC HlAB HlCD HlAC HlBD HlAD HlBC Hex.\n    assert (Hd':  dist_4p B A C D).\n    unfold dist_4p in *.\n    apply exchP; apply circ6; apply circ6; apply comm12P; apply circ6; apply comm12P;\n      apply circ6; apply circ6; apply circ6; apply circ6; apply comm12P; apply circ6;\n        apply comm12P; apply circ6; apply circ6; apply circ6; apply circ6; assumption.\n\n    assert (HlBA:incid_lp B (l_from_points B A) && incid_lp A (l_from_points B A)).\n    apply circ2; rewrite l_from_points_sym; assumption.\n    assert (HlDB:(incid_lp D (l_from_points D B) && incid_lp B (l_from_points D B))).\n    apply circ2; rewrite l_from_points_sym; assumption.\n    assert (Hex':(exists I : Point, incid_lp I (l_from_points B A) && incid_lp I (l_from_points C D))).\n    rewrite (l_from_points_sym B A); assumption.\n\n    generalize (Hr C D Hd' HlBA HlCD HlBC HlAD HlBD HlAC Hex').\n    intros (He1,He2).\n    split.\n    destruct He2 as [e2 He2]; apply circ2 in He2; exists e2; assumption.\n    destruct He1 as [e1 He1]; apply circ2 in He1; exists e1; assumption.\n  Qed.\n\n  Check a2_conj.\n\n  \n  Lemma points_line' : forall T Z:Point, forall x:Line,\n        incid_lp T x -> incid_lp Z x -> ~~ eqP T Z -> x = (l_from_points T Z).\n  Proof.\n    idtac \"-> proving points_line\".\n    time (intros T Z x;\n           case x ; \n           case T; intros  HTx;\n           first [ discriminate | \n                   case Z; intros  HZx HTZ;\n                   solve [discriminate | apply False_rect; auto | exact (@erefl Line _)]]).\n    Time Qed.\n\n  Ltac handle' x :=\n    match goal with Ht  : is_true (incid_lp ?T x),\n                          Hz  : is_true (incid_lp ?Z x),\n                                Htz : is_true (negb (eqP ?T ?Z)) |- _ =>\n                    let HP := fresh in pose proof (points_line' T Z x Ht Hz Htz) as HP;\n                                       clear Ht Hz; rewrite HP(*; subst*)  end.\n\n  \n  Ltac handle_eff l P Q HlAB:= assert (l=l_from_points P Q);[\n                                 assert (incid_lp P l) by ( solve [intuition]);\n                                 assert (incid_lp Q l) by ( solve [intuition]);\n                                 handle' l; reflexivity | idtac].\n\n  Lemma incid_lp_l_from_point1 : forall x y, incid_lp x (l_from_points x y).\n  Proof.\n    intros x y; case x; case y; trivial.\n  Qed.\n\n  Lemma incid_lp_l_from_point2 : forall x y, incid_lp y (l_from_points x y).\n  Proof.\n    intros x y; case x; case y; trivial.\n  Qed.\n\n  Lemma a2 : forall A B C D:Point, forall lAB lCD lAC lBD :Line,\n        dist_4p A B C D -> \n        incid_lp A lAB && incid_lp B lAB ->\n        incid_lp C lCD && incid_lp D lCD ->\n        incid_lp A lAC && incid_lp C lAC ->\n        incid_lp B lBD && incid_lp D lBD ->\n        (exists I:Point, incid_lp I lAB && incid_lp I lCD) ->\n        exists J:Point, incid_lp J lAC && incid_lp J lBD.\n  Proof.\n    intros A B C D lAB lCD lAC lBD Hdist HlAB HlCD HlAC HlBD Hex.\n    destruct (ab_bool_lr _ _ HlAB) as [HlAB1 HlAB2]; \n      destruct (ab_bool_lr _ _ HlCD) as [HlCD1 HlCD2]; \n      destruct (ab_bool_lr _ _ HlAC) as [HlAC1 HlAC2]; \n      destruct (ab_bool_lr _ _ HlBD) as [HlBD1 HlBD2]; \n      destruct (ab_bool_lr _ _ Hdist) as [Hdist1 HCD]; \n      destruct (ab_bool_lr _ _ Hdist1) as [Hdist2 HBD]; \n      destruct (ab_bool_lr _ _ Hdist2) as [Hdist3 HBC]; \n      destruct (ab_bool_lr _ _ Hdist3) as [Hdist4 HAD]; \n      destruct (ab_bool_lr _ _ Hdist4) as [HAB HAC].\n    \n    handle_eff lAB A B HlAB.\n    handle_eff lCD C D HlCD.\n    handle_eff lAC A C HlAC.\n    handle_eff lBD B D HlBD.\n    rewrite H in HlAB.\n    rewrite H0 in HlCD.\n    rewrite H1 in HlAC.\n    rewrite H2 in HlBD.\n    rewrite H in Hex.\n    rewrite H0 in Hex.\n    assert (HlAD:(incid_lp A (l_from_points A D) && incid_lp D (l_from_points A D))).\n    apply Bool.andb_true_iff; split;\n      [apply incid_lp_l_from_point1 | apply incid_lp_l_from_point2].\n    \n    assert (HlBC: (incid_lp B (l_from_points B C) && incid_lp C (l_from_points B C))).\n    apply Bool.andb_true_iff; split;\n      [apply incid_lp_l_from_point1 | apply incid_lp_l_from_point2].\n    \n    rewrite H1.\n    rewrite H2.\n    elim (a2_conj A B C D Hdist HlAB HlCD HlAC HlBD HlAD HlBC Hex).\n    intros; assumption.\n  Qed.\n  Check a2.\n  \nEnd PS.\n\n(* Local Variables: *)\n(* coq-prog-name: \"/Users/magaud/.opam/4.07.0/bin/coqtop\" *)\n(* coq-load-path: ((\".\" \"Top\") ) *)\n(* suffixes: .v *)\n(* End: *)\n", "meta": {"author": "ProjectiveGeometry", "repo": "ProjectiveGeometry", "sha": "4f7f4e6c14580833c91fdef38d048259fb454b88", "save_path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry", "path": "github-repos/coq/ProjectiveGeometry-ProjectiveGeometry/ProjectiveGeometry-4f7f4e6c14580833c91fdef38d048259fb454b88/Finite/pg33_proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7176213085544559}}
{"text": "Require Import Coq.Program.Equality.\nRequire Import Coq.btauto.Btauto.\nFrom Coq.ssr Require Import ssreflect ssrfun ssrbool.\nFrom mathcomp.ssreflect Require Import seq eqtype.\n\nSet Boolean Equality Schemes.\nSet Decidable Equality Schemes.\n\n\nModule Syntax1.\nInductive syntax := Zero | One \n | Tensor (Left : syntax) (Right : syntax)\n | With (Left : syntax) (Right : syntax)\n | Implication (Left : syntax) (Right : syntax)\n | Bang (Right : syntax).\n\nDeclare Scope syntax_scope.\nDelimit Scope syntax_scope with syntax. (* allows writing foo%syntax to mean that foo is in syntax_scope *)\nBind Scope syntax_scope with syntax. (* means that functions taking variables of type syntax will\nautomatically parse those variables in syntax_scope *)\nPrint Grammar constr.\nNotation \"A * B\" := (Tensor A B) : syntax_scope.\nNotation \"A && B\" := (With A B) : syntax_scope.\nNotation \"A '-o' B\" := (Implication A B) (at level 99) : syntax_scope.\nNotation \"! A\" := (Bang A) (at level 9, format \"! A\") : syntax_scope.\nNotation \"0\" := Zero : syntax_scope.\nNotation \"1\" := One : syntax_scope.\nReserved Notation \"Ctx ||- A\" (at level 100, no associativity).\n\n(* ssreflect magic to use decidable membership *)\nLemma syntax_eqbP : Equality.axiom syntax_beq.\nProof.\n  intros A B; pose proof (internal_syntax_dec_bl A B); pose proof (internal_syntax_dec_lb A B).\n  destruct (syntax_beq A B); constructor.\n  all: intuition congruence.\nQed.\n\nCanonical syntax_eqMixin := EqMixin syntax_eqbP.\nCanonical syntax_eqType := Eval hnf in EqType syntax syntax_eqMixin.\nInductive provable : seq syntax -> syntax -> Type :=\n| idA A\n\n(*------------------------------*)\n:          [:: A] ||- A\n\n\n| permute_context Ctx1 Ctx2 P \n\n(a : perm_eq Ctx1 Ctx2)     (b : Ctx1 ||- P)\n(*---------------------------------------------*)\n:                  Ctx2 ||- P\n\n\n| tensor_left Ctx A B P\n\n    (a : A :: B :: Ctx ||- P)\n(*------------------------------*)\n:     A * B :: Ctx ||- P\n\n\n| tensor_right Ctx1 Ctx2 A B\n (a : Ctx1 ||- A)    (b : Ctx2 ||- B)\n(*------------------------------------*)\n:     Ctx1 ++ Ctx2 ||- A * B\n\n\n\n| with_left_1 Ctx A B P\n\n      (a : A :: Ctx ||- P)\n(*------------------------------*) \n:      A && B :: Ctx ||- P \n\n| with_left_2 Ctx A B P\n\n      (a : B :: Ctx ||- P)\n(*------------------------------*) \n:      A && B :: Ctx ||- P \n\n\n| with_right Ctx A B \n\n(a : Ctx ||- A)    (b : Ctx ||- B)\n(*------------------------------*)\n:       Ctx ||- A && B\n\n\n| one_left Ctx P\n\n          (a : Ctx ||- P)\n(*------------------------------*)\n:         1 :: Ctx ||- P\n\n\n| one_right\n\n\n(*------------------------------*)\n:           [::] ||- 1\n\n\n| zero_left Ctx P\n\n\n(*------------------------------*)\n:     0 :: Ctx ||- P\n\n\n| implication_left Ctx1 Ctx2 A B P\n\n      (a : Ctx1 ||- A)    (b : B :: Ctx2 ||- P)\n(*--------------------------------------------------*)\n:         (A -o B) :: Ctx1 ++ Ctx2 ||- P\n\n\n| implication_right Ctx A B\n\n     (a : A :: Ctx ||- B)\n(*------------------------------*)\n:      Ctx ||- (A -o B)\n\nwhere \"Ctx ||- A\" := (provable Ctx%syntax A).\n\nLemma catss0 : forall [T : Type] (s1 s2 : seq T),\n  s1 ++ s2 = [::] -> s1 = [::] /\\ s2 = [::].\nProof.\n  destruct s1.\n  {\n    simpl.\n    intros.\n    split.\n    {\n      reflexivity.\n    }\n    {\n      exact H.\n    }\n  }\n  {\n    simpl.\n    intros.\n    discriminate.\n  }\nQed.\n\n(** Previously, we were copy-pasting\n<<<\n    exfalso.\n    clear -x.\n    apply catss0 in x.\n    destruct x as [a b].\n    apply catss0 in b.\n    destruct b as [c d].\n    discriminate.\n>>>\nto prove goals like\n>>>\n1 subgoal\nCtx1, Ctx2 : seq syntax\nLeft, Right : syntax\nproof : Ctx1 ++ [:: Left; Right] ++ Ctx2 ||- False\nIHproof : Ctx1 ++ [:: Left; Right] ++ Ctx2 = [::] ->\n          False = False -> Logic.False\nx : Ctx1 ++ [:: (Left /\\ Right)%syntax] ++ Ctx2 = [::]\n______________________________________(1/1)\nLogic.False\n>>>\n\nNow we write a tactic to handle all goals which have a hypothesis which says that some concatenation of lists is empty.\n*)\nLtac absurd_from_empty_cat :=\n  repeat match goal with\n         | [ H : _ ++ _ = [::] |- _ ] => apply catss0 in H\n         | [ H : _ /\\ _        |- _ ] => destruct H\n         | [ H : _ :: _ = [::] |- _ ] => exfalso; discriminate\n         end.\n\nFixpoint truth_value (x : syntax) : bool\n  := match x with\n     | One => true\n     | Zero => false\n     | Tensor l r => truth_value l && truth_value r\n     | With l r => truth_value l && truth_value r\n     | Implication l r => if truth_value l then truth_value r else true\n     | Bang r => truth_value r\n     end.\n     \nDefinition truth_value_of_context (ctx : seq syntax) : bool\n  := foldr andb true (map truth_value ctx).\n  \nLemma truth_value_of_context_cons x ctx : truth_value_of_context (x :: ctx) = truth_value x && truth_value_of_context ctx.\nProof.\n  reflexivity.\nQed.\n\nLemma foldr_cat_assoc A (s1 s2 : seq A) (init : A) (op : A -> A -> A)\n  (init_idl : forall x, op init x = x) \n  (op_assoc : forall a b c, op a (op b c) = op (op a b) c)\n: foldr op init (s1 ++ s2) = op (foldr op init s1) (foldr op init s2).\nProof.\n  induction s1.\n  {\n    simpl.\n    rewrite init_idl.\n    reflexivity.\n  }\n  {\n    simpl.\n    rewrite IHs1.\n    rewrite op_assoc.\n    reflexivity.\n  }\nQed.\n\nSearch \"assoc\" andb.\n\nLemma truth_value_of_context_cat Ctx1 Ctx2\n: truth_value_of_context (Ctx1 ++ Ctx2) = truth_value_of_context Ctx1 && truth_value_of_context Ctx2.\nProof.\n  unfold truth_value_of_context.\n  Search map cat.\n  rewrite map_cat.\n  Search foldr cat.\n  Search foldr.\n  rewrite foldr_cat_assoc//.\n  apply Bool.andb_assoc.\nQed.\n\nLemma truth_value_of_context_nil \n: truth_value_of_context [::] = true.\nProof.\n  reflexivity.\nQed.\n\nSearch perm_eq.\nCheck catCA_perm_ind.\n\nLemma truth_value_of_context_perm Ctx1 Ctx2 : perm_eq Ctx1 Ctx2 -> truth_value_of_context Ctx1 = truth_value_of_context Ctx2.\nProof.\n  Search perm_eq.\n  Check catCA_perm_ind.\n  intros A.\n  pose proof (@catCA_perm_ind _ \n    (fun Ctx2 => truth_value_of_context Ctx1 = truth_value_of_context Ctx2)) as H.\n  cbv beta in H.\n  apply H with (s1 := Ctx1).\n  {\n    clear.\n    intros s1 s2 s3 A.\n    rewrite A.\n    clear.\n    rewrite !truth_value_of_context_cat.\n    Search (?A && ?B = ?B && ?A).\n    Search (_ && _ = _ && _).\n    rewrite !Bool.andb_assoc.\n    rewrite (Bool.andb_comm (truth_value_of_context s1) (truth_value_of_context s2)).\n    reflexivity.\n  }\n  {\n    exact A.\n  }\n  {\n    reflexivity.\n  }\nQed.\n\nTheorem boolean_consistency : forall Ctx P, (Ctx ||- P) ->  truth_value_of_context Ctx = true -> truth_value P = true.\nProof.\n  intros Ctx P H T.\n  induction H;\n  rewrite -> ?truth_value_of_context_cat, -> ?truth_value_of_context_cons, -> ?truth_value_of_context_nil, -> ?Bool.andb_true_r in *.\n  all: simpl in *; auto.  \n  all: rewrite -> ?truth_value_of_context_cat, -> ?truth_value_of_context_cons, -> ?truth_value_of_context_nil, -> ?Bool.andb_true_r in *.\n  all: simpl in *; auto.  \n  {\n    apply truth_value_of_context_perm in a.\n    rewrite -a // in T.\n  }\n  {\n    rewrite -> ?Bool.andb_assoc in *.    \n    assert (X : truth_value A = true) by auto.\n    rewrite -> X in *.\n    auto.\n  }\n  {\n    rewrite T in IHprovable.\n    Search (_ && true).\n    rewrite -> Bool.andb_true_r in *.\n    destruct (truth_value A); auto.\n  }\nQed.\n\nInductive extended_nat := negative_infinity | positive_infinity | non_negative (_:nat).\nCoercion non_negative : nat >-> extended_nat.\nDeclare Scope extended_nat_scope.\nDelimit Scope extended_nat_scope with extended_nat.\nBind Scope extended_nat_scope with extended_nat.\nNotation \"-oo\" := negative_infinity : extended_nat_scope.\nNotation \"+oo\" := positive_infinity : extended_nat_scope.\n\nDefinition extended_plus (A B : extended_nat) : extended_nat\n  := match A, B with \n     | -oo, -oo => -oo\n     | -oo, non_negative _ => -oo\n     | non_negative _, -oo => -oo\n     | non_negative A, non_negative B => non_negative (A + B)\n     end%extended_nat.\nInfix \"+\" := extended_plus : extended_nat_scope.\n\nDefinition extended_minus (A B : extended_nat) : extended_nat\n  := match A, B with \n     | -oo, -oo => -oo\n     | -oo, non_negative _ => -oo\n     | non_negative _, -oo => -oo\n     | non_negative A, non_negative B => non_negative (A + B)\n     end%extended_nat.\nInfix \"-\" := extended_minus : extended_nat_scope.\n\nFixpoint resource_count (x : syntax) : extended_nat\n  := match x with\n     | One => 0\n     | Zero => -oo\n     | Tensor l r => resource_count l + resource_count r\n     | With l _ =>  resource_count l\n     | Implication l r => resource_count r - resource_count a\n     | Bang r => truth_value r\n     end%extended_nat.\n     \nDefinition truth_value_of_context (ctx : seq syntax) : bool\n  := foldr andb true (map truth_value ctx).\n  \nLemma truth_value_of_context_cons x ctx : truth_value_of_context (x :: ctx) = truth_value x && truth_value_of_context ctx.\nProof.\n  reflexivity.\nQed.\n\nLemma foldr_cat_assoc A (s1 s2 : seq A) (init : A) (op : A -> A -> A)\n  (init_idl : forall x, op init x = x) \n  (op_assoc : forall a b c, op a (op b c) = op (op a b) c)\n: foldr op init (s1 ++ s2) = op (foldr op init s1) (foldr op init s2).\nProof.\n  induction s1.\n  {\n    simpl.\n    rewrite init_idl.\n    reflexivity.\n  }\n  {\n    simpl.\n    rewrite IHs1.\n    rewrite op_assoc.\n    reflexivity.\n  }\nQed.\n\nSearch \"assoc\" andb.\n\nLemma truth_value_of_context_cat Ctx1 Ctx2\n: truth_value_of_context (Ctx1 ++ Ctx2) = truth_value_of_context Ctx1 && truth_value_of_context Ctx2.\nProof.\n  unfold truth_value_of_context.\n  Search map cat.\n  rewrite map_cat.\n  Search foldr cat.\n  Search foldr.\n  rewrite foldr_cat_assoc//.\n  apply Bool.andb_assoc.\nQed.\n\nLemma truth_value_of_context_nil \n: truth_value_of_context [::] = true.\nProof.\n  reflexivity.\nQed.\n\nSearch perm_eq.\nCheck catCA_perm_ind.\n\nLemma truth_value_of_context_perm Ctx1 Ctx2 : perm_eq Ctx1 Ctx2 -> truth_value_of_context Ctx1 = truth_value_of_context Ctx2.\nProof.\n  Search perm_eq.\n  Check catCA_perm_ind.\n  intros A.\n  pose proof (@catCA_perm_ind _ \n    (fun Ctx2 => truth_value_of_context Ctx1 = truth_value_of_context Ctx2)) as H.\n  cbv beta in H.\n  apply H with (s1 := Ctx1).\n  {\n    clear.\n    intros s1 s2 s3 A.\n    rewrite A.\n    clear.\n    rewrite !truth_value_of_context_cat.\n    Search (?A && ?B = ?B && ?A).\n    Search (_ && _ = _ && _).\n    rewrite !Bool.andb_assoc.\n    rewrite (Bool.andb_comm (truth_value_of_context s1) (truth_value_of_context s2)).\n    reflexivity.\n  }\n  {\n    exact A.\n  }\n  {\n    reflexivity.\n  }\nQed.\n\nTheorem boolean_consistency : forall Ctx P, (Ctx ||- P) ->  truth_value_of_context Ctx = true -> truth_value P = true.\nProof.\n  intros Ctx P H T.\n  induction H;\n  rewrite -> ?truth_value_of_context_cat, -> ?truth_value_of_context_cons, -> ?truth_value_of_context_nil, -> ?Bool.andb_true_r in *.\n  all: simpl in *; auto.  \n  all: rewrite -> ?truth_value_of_context_cat, -> ?truth_value_of_context_cons, -> ?truth_value_of_context_nil, -> ?Bool.andb_true_r in *.\n  all: simpl in *; auto.  \n  {\n    apply truth_value_of_context_perm in a.\n    rewrite -a // in T.\n  }\n  {\n    rewrite -> ?Bool.andb_assoc in *.    \n    assert (X : truth_value A = true) by auto.\n    rewrite -> X in *.\n    auto.\n  }\n  {\n    rewrite T in IHprovable.\n    Search (_ && true).\n    rewrite -> Bool.andb_true_r in *.\n    destruct (truth_value A); auto.\n  }\nQed.\n\n\n", "meta": {"author": "harshikaaagrawal", "repo": "game-semantics-for-affine-logic", "sha": "6db365c92e9bff315d61d6262cb1b794100d69ad", "save_path": "github-repos/coq/harshikaaagrawal-game-semantics-for-affine-logic", "path": "github-repos/coq/harshikaaagrawal-game-semantics-for-affine-logic/game-semantics-for-affine-logic-6db365c92e9bff315d61d6262cb1b794100d69ad/Main/Affine_Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7176213085544559}}
{"text": "Require Import Reals.\nRequire Import Interval.Tactic.\n\nOpen Scope R_scope.\n\nGoal\n  forall x, -1 <= x <= 1 ->\n  sqrt (1 - x) <= 3/2.\nProof.\n  intros.\n  interval.\nQed.\n\nGoal\n  forall x, -1 <= x <= 1 ->\n  sqrt (1 - x) <= 141422/100000.\nProof.\n  intros.\n  interval.\nQed.\n\nGoal\n  forall x, -1 <= x <= 1 ->\n  sqrt (1 - x) <= 141422/100000.\nProof.\n  intros.\n  interval_intro (sqrt (1 - x)) upper as H'.\n  apply Rle_trans with (1 := H').\n  interval.\nQed.\n\nGoal\n  forall x, 3/2 <= x <= 2 ->\n  forall y, 1 <= y <= 33/32 ->\n  Rabs (sqrt(1 + x/sqrt(x+y)) - 144/1000*x - 118/100) <= 71/32768.\nProof.\n  intros.\n  interval with (i_prec 19, i_bisect x).\nQed.\n\nGoal\n  forall x, 1/2 <= x <= 2 ->\n  Rabs (sqrt x - (((((122 / 7397 * x + (-1733) / 13547) * x\n                   + 529 / 1274) * x + (-767) / 999) * x\n                   + 407 / 334) * x + 227 / 925))\n    <= 5/65536.\nProof.\n  intros.\n  interval with (i_bisect_taylor x 3).\nQed.\n\nGoal\n  forall x, -1 <= x ->\n  x < 1 + powerRZ x 3.\nProof.\n  intros.\n  interval with (i_bisect_diff x).\nQed.\n\nRequire Import Coquelicot.Coquelicot.\n\nGoal\n  Rabs (RInt (fun x => atan (sqrt (x*x + 2)) / (sqrt (x*x + 2) * (x*x + 1))) 0 1\n        - 5/96*PI*PI) <= 1/1000.\nProof.\n  interval with (i_integral_prec 9, i_integral_depth 1, i_integral_deg 5).\nQed.\n\nGoal\n  RInt_gen (fun x => 1 * (powerRZ x 3 * ln x^2))\n           (at_right 0) (at_point 1) = 1/32.\nProof.\n  refine ((fun H => Rle_antisym _ _ (proj2 H) (proj1 H)) _).\n  interval.\nQed.\n\nGoal\n  Rabs (RInt_gen (fun t => 1/sqrt t * exp (-(1*t)))\n                 (at_point 1) (Rbar_locally p_infty)\n        - 2788/10000) <= 1/1000.\nProof.\n  interval.\nQed.\n", "meta": {"author": "MSoegtropIMC", "repo": "interval", "sha": "2d7d7fe5d7e150372008924487186215774ba535", "save_path": "github-repos/coq/MSoegtropIMC-interval", "path": "github-repos/coq/MSoegtropIMC-interval/interval-2d7d7fe5d7e150372008924487186215774ba535/testsuite/example-20071016.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7176204898850762}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Export Fiat.Common.Coq__8_4__8_5__Compat.\n\n#[global]\nHint Rewrite <- nat_compare_lt : hints.\n#[global]\nHint Rewrite <- nat_compare_gt : hints.\n#[global]\nHint Rewrite Nat.compare_eq_iff : hints.\n#[global]\nHint Rewrite <- Nat.compare_eq_iff : hints.\n\nLtac autorewrite_nat_compare :=\n  autorewrite with hints.\n\nLemma nat_compare_eq_refl : forall x, Nat.compare x x = Eq.\n  intros; apply Nat.compare_eq_iff; trivial.\nQed.\n\nLemma nat_compare_consistent :\n  forall n0 n1,\n    { Nat.compare n0 n1 = Lt /\\ Nat.compare n1 n0 = Gt }\n    + { Nat.compare n0 n1 = Eq /\\ Nat.compare n1 n0 = Eq }\n    + { Nat.compare n0 n1 = Gt /\\ Nat.compare n1 n0 = Lt }.\nProof.\n  intros n0 n1;\n  destruct (lt_eq_lt_dec n0 n1) as [ [_lt | _eq] | _lt ];\n  [ constructor 1; constructor 1  | constructor 1; constructor 2 | constructor 2 ];\n  split;\n  autorewrite_nat_compare;\n  intuition.\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/QueryStructure/Implementation/DataStructures/Bags/NatCompare_Facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.717620487437451}}
{"text": "(** Celia Picard with contributions by Ralph Matthes, \n    I.R.I.T.,  University of Toulouse and CNRS*)\n\n(** provides the definition of various relations of permutation \n    on ilist with associated tools and lemmas *)\n\nRequire Import Fin.\nRequire Import Ilist. \nRequire Import Setoid.\nRequire Import Extroduce. \nRequire Import Utf8.\nRequire Import Basics.\nRequire Import Morphisms.\nRequire Import Tools.\n\nSet Implicit Arguments. \n\n(* this section corresponds to the developments around ilist_perm_occ in the paper (section 2.1) *)\nSection Ilist_Perm_occ.\n\n  Fixpoint count_occn (T: Set)(RelT: relation T)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(t: T)(n: nat)\n    (i: ilistn T n){struct n} : nat := \n    match n as m return (ilistn T m -> nat) with \n      0 => fun _: ilistn T 0 => 0 \n    | S m => fun i0: ilistn T (S m) =>  \n    if (R_dec t (i0 (first m))) then\n        S (count_occn RelT R_dec t (fun f => i0 (succ f)))\n        else (count_occn RelT R_dec t (fun f => i0 (succ f)))\n      end i.\n\n  (* Counts number of occurrences of t in i *)\n  (* called nb_occ in the paper - Definition 7 *)\n  Definition count_occ(T: Set)(RelT: relation T)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(t: T)(i: ilist T) : nat := \n     let (n, i') := i  in count_occn RelT R_dec t i'.\n\n  Add Parametric Morphism (T: Set)(RelT: relation T)(RelTEq: Equivalence RelT)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(t: T): \n    (count_occ RelT R_dec t)\n  with signature (ilist_rel RelT ==> @eq nat)\n  as count_occM1.\n  Proof.\n    intros [n1 i1] [n2 i2] [h H].\n    cbn in h, H.\n    assert (h' := h) ; revert i2 h H ; rewrite <- h' ; intros i2 h H ; clear h' n2.\n    fold (mkilist i1); fold (mkilist i2).\n    assert (e1: forall f, f = rewriteFins h f).\n    { intro f.\n      apply decode_Fin_unique, decode_Fin_match'. }\n    assert (H': forall f, RelT (i1 f) (i2 f)).\n    { intro f ; rewrite (e1 f) at 2 ; apply H. }\n    clear h H e1.\n    cbn.\n    induction n1 as [|n IH].\n    { reflexivity. }\n    cbn.\n    destruct RelTEq as [Rrefl Rsym Rtrans].\n    elim (R_dec t (i1 (first n))) ; intros a ;\n    elim (R_dec t (i2 (first n))) ; intros c ;\n    rewrite (IH _ (fun f : Fin n => i2 (succ f)));\n    try reflexivity ; \n    try (intro f ; apply H') ; \n    try assert (b := Rtrans _ _ _ a (H' (first n))) ; \n    try assert (b := Rtrans _ _ _ c (Rsym _ _ (H' (first n)))) ;\n    contradiction b.\n  Qed.\n\n  (* Indicates whether an ilist is a permutation of another using decidability *)\n  (* Called ilist_perm_occ in the paper - Definition 8 *)\n  Inductive IlistPerm (T: Set)(RelT: relation T)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(i1 i2: ilist T): Prop :=\n    is_IlistPerm: (forall t: T,\n      count_occ RelT R_dec t i1 = \n      count_occ RelT R_dec t i2) -> \n        IlistPerm RelT R_dec i1 i2.\n\n  Lemma count_occn_in (T: Set)(RelT: relation T)(Req: Equivalence RelT)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(n: nat)(l : ilistn T n)(i: Fin n) : \n     exists m, count_occn RelT R_dec (l i) l = S m.\n  Proof.\n    induction i.\n    - cbn.\n      elim (R_dec (l (first k)) (l (first k))) ; intros a.\n      + exists (count_occn RelT R_dec (l (first k)) (fun f : Fin k => l (succ f))).\n        reflexivity.\n      + unfold not in a.\n        contradiction a.\n        reflexivity.\n    - cbn.\n      elim (R_dec (l (succ i)) (l (first k))) ; intros a.\n      + exists (count_occn RelT R_dec (l (succ i)) (fun f : Fin k => l (succ f))).\n        reflexivity.\n      + destruct (IHi (fun f : Fin k => l (succ f))) as [m H].\n        exists m.\n        apply H.\n  Qed.\n\n  Lemma count_occn_not_exist (T: Set)(RelT: relation T)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(n: nat)(l : ilistn T n)(t: T): \n     not (exists i: Fin n, RelT t (l i)) -> count_occn RelT R_dec t l = 0.\n   Proof.\n     intros H.\n     induction n as [|n IH].\n     { reflexivity. }\n     cbn.\n     elim (R_dec t (l (first n))) ; intros a.\n     - destruct H.\n       exists (first n) ; assumption.\n     - apply IH.\n       intros [f H'].\n       destruct H.\n       exists (succ f) ; assumption.\n   Qed.\n\n  Lemma count_occn_exist (T: Set)(RelT: relation T)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(n: nat)(l : ilistn T n)(t: T)(m: nat): \n     count_occn RelT R_dec t l = S m -> exists i: Fin n, RelT t (l i).\n   Proof.\n     intro H.\n     induction n as [|n IH].\n     { inversion H. }\n     cbn in H.\n     revert H.\n     elim (R_dec t (l (first n))) ; cbn ; intros a H.\n     - exists (first n) ; assumption.\n     - destruct (IH (fun x => l (succ x)) H) as [f H'].\n       exists (succ f) ; assumption.\n   Qed.\n\n  Lemma IlistPerm_refl: forall (T: Set)(RelT: relation T)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(i1: ilist T), \n    IlistPerm RelT R_dec i1 i1.\n  Proof.\n    intros T RelT R_dec i1.\n    apply is_IlistPerm.\n    reflexivity.\n  Qed.\n\n  Lemma IlistPerm_sym: forall (T: Set)(RelT: relation T)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(i1 i2: ilist T),\n    IlistPerm RelT R_dec i1 i2 -> IlistPerm RelT R_dec i2 i1.\n  Proof.\n    intros T RelT Req i1 i2 [H].\n    apply is_IlistPerm.\n    intro t.\n    apply (sym_eq (H t)).\n  Qed.\n\n  Lemma IlistPerm_trans: forall (T: Set)(RelT: relation T)\n    (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(i1 i2 i3: ilist T),\n    IlistPerm RelT R_dec i1 i2 -> IlistPerm RelT R_dec i2 i3 -> \n    IlistPerm RelT R_dec i1 i3.\n  Proof.\n    intros T RelT R_dec i1 i2 i3 [H1] [H2].\n    apply is_IlistPerm.\n    intro t.\n    apply (trans_eq (H1 t) (H2 t)).\n  Qed.\n   \n    Add Parametric Relation(T: Set)(RelT: relation T)\n      (R_dec: forall x y, {RelT x y}+{not (RelT x y)}): \n      (ilist T) (@IlistPerm T RelT R_dec)\n      reflexivity proved by (@IlistPerm_refl T RelT R_dec)\n      symmetry proved by (@IlistPerm_sym T RelT R_dec)\n      transitivity proved by (@IlistPerm_trans T RelT R_dec)\n      as IlistPermRel.\n\n   Add Parametric Morphism (T: Set)(RelT: relation T)(REq: Equivalence RelT)\n      (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(i: ilist T): \n      (fun x => count_occ RelT R_dec x i)\n   with signature (RelT ==> @eq nat)\n   as count_occM2.\n   Proof.\n     intros t1 t2 H.\n     destruct i as [n i].\n     cbn.\n     induction n as [|n IH].\n     { reflexivity. }\n     cbn.\n     destruct REq as [Rrefl Rsym Rtrans].\n     elim (R_dec t1 (i (first n))) ; intros a ;\n     elim (R_dec t2 (i (first n))) ; intros b ;\n     try (rewrite IH ; reflexivity); \n     try assert (c := Rtrans _ _ _ (Rsym _ _ H) a) ;\n     try assert (c := Rtrans _ _ _ H b) ;\n     contradiction c.\n   Qed.\n\n   Lemma ilist_rel_finer_IlistPerm: \n     forall (T: Set)(RelT: relation T) (REq : Equivalence RelT)\n       (R_dec: forall x y, {RelT x y}+{not (RelT x y)})(i1 i2: ilist T), \n     ilist_rel RelT i1 i2 -> IlistPerm RelT R_dec i1 i2.\n   Proof.\n     intros T RelT [Rrefl Rsym Rtrans] R_dec [n i1] [n2 i2] [h H].\n     apply is_IlistPerm.\n     intros t.\n     cbn in *|-*.\n     assert (h' := h) ; revert i1 i2 h H ; rewrite <- h' ; intros i1 i2 h H ; clear h' n2.\n     assert (H1 : forall f, RelT (i1 f) (i2 f)).\n     { intro f.\n       rewrite (decode_Fin_unique _ _ (decode_Fin_match' f h)) at 2.\n       apply (H f). }\n     clear H h.\n     induction n as [|n IH].\n     { reflexivity. }\n     cbn.\n     elim (R_dec t (i1 (first n))) ; elim (R_dec t (i2 (first n))) ; intros a b.\n     - f_equal ; apply IH.\n       intro f ; apply (H1 (succ f)).\n     - contradiction (Rtrans _ _ _ b (H1 (first n))).\n     - contradiction (Rtrans _ _ _ a (Rsym _ _ (H1 (first n)))).\n     - apply IH.\n       intro f ; apply (H1 (succ f)).\n   Qed.\n   \nEnd Ilist_Perm_occ.\n\nSection IlistPerm_ind.\n\n   (* In the paper, iperm *)\n   Inductive IlistPerm3 (T: Set)(RelT: relation T)(i1 i2: ilist T): Prop :=\n     IlistPerm3_nil: lgti i1 = lgti i2 -> lgti i1 = 0 -> IlistPerm3 RelT i1 i2  \n   | IlistPerm3_cons: forall f1 f2, RelT (fcti i1 f1) (fcti i2 f2) -> \n        IlistPerm3 RelT (extroduce i1 f1) (extroduce i2 f2) -> \n        IlistPerm3 RelT i1 i2.\n\n   (* In the paper, iperm' *)\n   Inductive IlistPerm4 (T: Set)(RelT: relation T): ilist T-> ilist T-> Prop :=\n     is_IlistPerm4: forall (i1 i2: ilist T), lgti i1 = lgti i2 -> \n       (forall f1, exists f2, RelT (fcti i1 f1) (fcti i2 f2) /\\\n        IlistPerm4 RelT (extroduce i1 f1) (extroduce i2 f2)) -> \n        IlistPerm4 RelT i1 i2.\n\n   Scheme IlistPerm4_ind_rich := Induction for IlistPerm4 Sort Prop.\n\n   Lemma IlistPerm4_ind_better : forall (T : Set)(RelT : relation T)(P : ilist T -> ilist T -> Prop), \n     (forall i1 i2 : ilist T, lgti i1 = lgti i2 -> \n       (forall f1 : Fin (lgti i1), exists f2 : Fin (lgti i2),\n       RelT (fcti i1 f1) (fcti i2 f2) /\\ IlistPerm4 RelT (extroduce i1 f1) (extroduce i2 f2) /\\\n       P (extroduce i1 f1) (extroduce i2 f2)) -> P i1 i2)\n       -> (forall i i0 : ilist T, IlistPerm4 RelT i i0 -> P i i0).\n   Proof.\n     intros T RelT P H.\n     refine (fix Hr (i00 i0: ilist T)(h: IlistPerm4 RelT i00 i0){struct h} : P i00 i0 := \n       match h with is_IlistPerm4 i1 i2 h1 h2 => _ end).\n     clear i00 i0 h.\n     apply H.\n     { assumption. }\n     intro f1.\n     destruct (h2 f1) as [f2 [h3 h4]].\n     exists f2.\n     split ; try split ; try assumption.\n     apply (Hr _ _ h4).\n   Qed.\n   \n   Inductive IlistPerm5 (T: Set)(RelT: relation T): ilist T -> ilist T -> Prop :=\n     is_IlistPerm5: forall (i1 i2: ilist T), lgti i1 = lgti i2 -> \n       (forall f2, exists f1, RelT (fcti i1 f1) (fcti i2 f2) /\\\n        IlistPerm5 RelT (extroduce i1 f1) (extroduce i2 f2)) -> \n        IlistPerm5 RelT i1 i2.\n\n   Lemma IlistPerm5_ind_better : forall (T : Set)(RelT : relation T)(P : ilist T → ilist T → Prop), \n     (forall i1 i2 : ilist T, lgti i1 = lgti i2 -> \n       (forall f2 : Fin (lgti i2), exists f1 : Fin (lgti i1),\n       RelT (fcti i1 f1) (fcti i2 f2) /\\ IlistPerm5 RelT (extroduce i1 f1) (extroduce i2 f2) /\\\n       P (extroduce i1 f1) (extroduce i2 f2)) -> P i1 i2)\n       -> (forall i i0 : ilist T, IlistPerm5 RelT i i0 -> P i i0).\n   Proof.\n     intros T RelT P H.\n     refine (fix Hr (i00 i0: ilist T)(h: IlistPerm5 RelT i00 i0){struct h} : P i00 i0 := \n       match h with is_IlistPerm5 i1 i2 h1 h2 => _ end).\n     clear i00 i0 h.\n     apply H.\n     { assumption. }\n     intro f2.\n     destruct (h2 f2) as [f1 [h3 h4]].\n     exists f1.\n     split ; try split ; try assumption.\n     apply (Hr _ _ h4).\n   Qed.\n\n   Lemma IlistPerm3_lgti: forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     IlistPerm3 RelT i1 i2 -> lgti i1 = lgti i2.\n   Proof.\n     intros T RelT i1 i2 H.\n     induction H as [i1 i2 h1 h2 | i1 i2 f1 f2 h1 h2 IH].\n     { assumption. }\n     apply eq_S in IH.\n     do 2 rewrite <- extroduce_lgti in IH.\n     assumption.\n   Qed.\n\n   (* D2 => D1 *)\n   Lemma IlistPerm4_IlistPerm3_eq : forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     IlistPerm4 RelT i1 i2 -> IlistPerm3 RelT i1 i2.\n   Proof.\n     intros T RelT i1 i2 h.\n     induction h as [i1 i2 h1 h2] using IlistPerm4_ind_better.\n     destruct i1 as [n1 i1]; destruct i2 as [n2 i2].\n     simpl lgti in h1, h2 ; simpl fcti in h2.\n     fold (mkilist i1) in *|-*.\n     fold (mkilist i2) in *|-*.\n     destruct n1 as [|n1].\n     - apply IlistPerm3_nil.\n       + assumption.\n       + reflexivity.\n     - destruct (h2 (first n1)) as [f2 [h3 [h4 h5]]] ; clear h2.\n       clear h4.\n       apply (IlistPerm3_cons _ _ (first _: Fin (lgti (mkilist _))) \n         (f2: Fin (lgti (mkilist _)))) ; assumption.\n     Qed.\n     \n   Lemma IlistPerm5_IlistPerm3_eq : forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     IlistPerm5 RelT i1 i2 -> IlistPerm3 RelT i1 i2.\n   Proof.\n     intros T RelT i1 i2 h.\n     induction h as [i1 i2 h1 h2] using IlistPerm5_ind_better.\n     destruct i1 as [n1 i1]; destruct i2 as [n2 i2].\n     simpl lgti in h1, h2 ; simpl fcti in h2.\n     fold (mkilist i1) in *|-*.\n     fold (mkilist i2) in *|-*.\n     destruct n2 as [|n2].\n     - apply IlistPerm3_nil ; assumption.\n     - destruct (h2 (first n2)) as [f1 [h3 [h4 h5]]] ; clear h2.\n       clear h4.\n       apply (IlistPerm3_cons _ _ (f1 : Fin (lgti (mkilist _))) \n         (first _: Fin (lgti (mkilist _)))) ; assumption.\n    Qed.\n\n   Lemma IlistPerm4_refl_refl: forall (T: Set)(RelT: relation T)(Rrefl: Reflexive RelT)(i: ilist T),\n     IlistPerm4 RelT i i.\n   Proof.\n     intros T RelT Rrefl [n i].\n     induction n as [|n IH] ;\n     apply (is_IlistPerm4 _ _ (refl_equal _)) ;\n     simpl lgti ; simpl fcti ;\n     intro f ; exists f.\n     - inversion f.\n     - split.\n       + reflexivity.\n       + set (e := extroduce (existT (fun n0 : nat => ilistn T n0) (S n) i) f).\n         assert (h:= extroduce_lgti_S _ _ : n = lgti e).\n         destruct e as [n' e].\n         cbn in h ; revert e ; rewrite <- h ; intro e ; apply IH.\n   Qed.\n\n   Lemma IlistPerm4_refl: forall (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(i: ilist T),\n     IlistPerm4 RelT i i.\n   Proof.\n     intros T RelT [Rrefl _ _] [n i].\n     induction n as [|n IH] ;\n     apply (is_IlistPerm4 _ _ (refl_equal _)) ;\n     simpl lgti ; simpl fcti ;\n     intro f ; exists f.\n     - inversion f.\n     - split.\n       + apply Rrefl.\n       + set (e := extroduce (existT (fun n0 : nat => ilistn T n0) (S n) i) f).\n         assert (h: lgti e = n).\n         { apply eq_add_S.\n           unfold e.\n           rewrite <- extroduce_lgti.\n           reflexivity. }\n         destruct e as [n' e].\n         cbn in h ; revert e ; rewrite h ; intro e ; apply IH.\n   Qed.\n\n   (* Deduced from IlistPerm4_refl *)\n   Lemma IlistPerm3_refl_refl: forall (T: Set)(RelT: relation T)(Rrefl: Reflexive RelT)(i: ilist T),\n     IlistPerm3 RelT i i.\n   Proof.\n     intros T RelT Rrefl i.\n     apply IlistPerm4_IlistPerm3_eq.\n     apply (IlistPerm4_refl_refl Rrefl).\n   Qed.\n\n   (* Deduced from IlistPerm4_refl *)\n   Lemma IlistPerm3_refl: forall (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(i: ilist T),\n     IlistPerm3 RelT i i.\n   Proof.\n     intros T RelT EqT i.\n     apply IlistPerm4_IlistPerm3_eq.\n     apply (IlistPerm4_refl EqT).\n   Qed.\n\n   Lemma IlistPerm3nil: forall (T: Set)(RelT: relation T)(i1 i2: ilistn T 0), \n     IlistPerm3 RelT (mkilist (n:=0) i1) (mkilist (n:=0) i2).\n   Proof.\n     intros T RelT i1 i2.\n     apply IlistPerm3_nil ; reflexivity.\n   Qed.\n\n   Lemma IlistPerm4nil: forall (T: Set)(RelT: relation T)(i1 i2: ilistn T 0), \n     IlistPerm4 RelT (mkilist (n:=0) i1) (mkilist (n:=0) i2).\n   Proof.\n     intros T RelT i1 i2.\n     apply is_IlistPerm4.\n     - reflexivity.\n     - intro f1 ; inversion f1.\n   Qed.\n\n   Lemma IlistPerm4nil_gen: forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     lgti i1 = lgti i2 -> lgti i1 = 0 ->\n     IlistPerm4 RelT i1 i2.\n   Proof.\n     intros T RelT i1 i2 Hyp1 Hyp2.\n     apply is_IlistPerm4.\n     - exact Hyp1.\n     - intro f1.\n       apply False_rec.\n       rewrite Hyp2 in f1.\n       inversion f1.\n   Qed.\n\n   Lemma IlistPerm4_lgti: forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     IlistPerm4 RelT i1 i2 -> lgti i1 = lgti i2.\n   Proof.\n     intros T RelT _ _ [i1 i2 e1 _] ; assumption.\n   Qed.\n\n   Lemma IlistPerm3_flip: forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     IlistPerm3 RelT i1 i2 -> IlistPerm3 (flip RelT) i2 i1.\n   Proof.\n     intros T RelT i1 i2 ; intros h ;\n     induction h as [i1 i2 e1 e2 | i1 i2 f1 f2 h1 _ IH].\n     - apply (IlistPerm3_nil _ _ _ (sym_eq e1) (trans_eq (sym_eq e1) e2)).\n     - apply (IlistPerm3_cons _ _ f2 f1) ; assumption.\n   Qed.\n\n   Lemma IlistPerm3_flip': forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     IlistPerm3 (flip RelT) i1 i2 -> IlistPerm3 RelT i2 i1.\n   Proof.\n     intros T RelT i1 i2 ; intros h ;\n     induction h as [i1 i2 e1 e2 | i1 i2 f1 f2 h1 h2 IH].\n     - apply (IlistPerm3_nil _ _ _ (sym_eq e1) (trans_eq (sym_eq e1) e2)).\n     - apply (IlistPerm3_cons _ _ f2 f1); assumption.\n   Qed.\n\n   (* using IlistPerm3_flip *)\n   Lemma IlistPerm3_sym: forall (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(i1 i2: ilist T), \n     IlistPerm3 RelT i1 i2 -> IlistPerm3 RelT i2 i1.\n   Proof.\n     intros T RelT [_ Rsym _] i1 i2 h.\n     assert (h1 := IlistPerm3_flip h) ; clear h.\n     induction h1 as  [i2 i1 e1 e2 | i2 i1 f2 f1 h1 _ IH].\n     - apply (IlistPerm3_nil _ _ _ e1 e2).\n     - apply (IlistPerm3_cons _ _ f2 f1).\n       + apply (Rsym _ _ h1).\n       + assumption.\n   Qed.\n\n   Lemma IlistPerm3_sym_sym: forall (T: Set)(RelT: relation T)(Rsym: Symmetric RelT)(i1 i2: ilist T), \n     IlistPerm3 RelT i1 i2 -> IlistPerm3 RelT i2 i1.\n   Proof.\n     intros T RelT Rsym i1 i2 h.\n     assert (h1 := IlistPerm3_flip h) ; clear h.\n     induction h1 as  [i1 i2 e1 e2 | i1 i2 f1 f2 h1 h2 IH].\n     - apply (IlistPerm3_nil _ _ _ e1 e2).\n     - apply (IlistPerm3_cons _ _ f1 f2).\n       + apply (Rsym _ _ h1).\n       + assumption.\n   Qed.\n\n   Definition TransitiveAt (T: Type)(R: relation T)(t1: T): Prop :=\n     forall (t2 t3: T), R t1 t2 -> R t2 t3 -> R t1 t3.\n\n   Lemma IlistPerm4_trans_refined: \n     forall (T: Set)(RelT: relation T)(i1: ilist T), \n     (forall f1: Fin (lgti i1), TransitiveAt RelT (fcti i1 f1)) ->\n     TransitiveAt (IlistPerm4 RelT) i1.\n   Proof.\n    intros T RelT i1 Hyp i2 i3 h1 h2.\n    revert i1 h1 Hyp.\n    induction h2 as [i2 i3 e2 h2] using IlistPerm4_ind_better.\n    intros i1 h1 Hyp.\n    destruct h1 as [i1 i2 e1 h1].\n    apply is_IlistPerm4.\n    - apply (trans_eq e1 e2).\n    - intro f1.\n      destruct (h1 f1) as [f2 [h11 h12]] ; clear h1.\n      destruct (h2 f2) as [f3 [h21 [h22 h23]]] ; clear h2.\n      exists f3.\n      split.\n      + apply (Hyp _ _ _ h11 h21).\n      + apply (h23 _ h12).\n        intro f0.\n        destruct (extroduce_ok_cor i1 f1 f0).\n        rewrite H.\n        apply Hyp.\n   Qed.\n\n(* obviously, the following lemma is just a special case *)\n   Lemma IlistPerm4_trans: \n     forall (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(i1 i2 i3: ilist T), \n     IlistPerm4 RelT i1 i2 -> IlistPerm4 RelT i2 i3 -> IlistPerm4 RelT i1 i3.\n   Proof.\n     intros T RelT [_ _ Rtrans] i1.\n     change (TransitiveAt (IlistPerm4 RelT) i1).\n     apply IlistPerm4_trans_refined.\n     red.\n     intros.\n     transitivity t2; assumption.\n   Qed.\n\n   Lemma IlistPerm4_trans_trans: \n     forall (T: Set)(RelT: relation T)(Rtrans: Transitive RelT)(i1 i2 i3: ilist T), \n     IlistPerm4 RelT i1 i2 -> IlistPerm4 RelT i2 i3 -> IlistPerm4 RelT i1 i3.\n   Proof.\n     intros T RelT Rtrans i1.\n     change (TransitiveAt (IlistPerm4 RelT) i1).\n     apply IlistPerm4_trans_refined.\n     intros f1 t2 t3 H1 H2.\n     transitivity t2; assumption.\n   Qed.\n\n   Lemma IlistPerm4_flip_IlistPerm5 : forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     IlistPerm4 RelT i1 i2 -> IlistPerm5 (flip RelT) i2 i1.\n   Proof.\n     intros T RelT i1 i2 H.\n     induction H as [i1 i2 h1 h2] using IlistPerm4_ind_better.\n     apply (is_IlistPerm5 _ _ (sym_eq h1)).\n     intro f1.\n     destruct (h2 f1) as [f2 [h3 [_ h4]]].\n     exists f2.\n     split ; assumption.\n   Qed.\n\n   Lemma IlistPerm4_sym_IlistPerm5 : forall (T: Set)(RelT: relation T)(Rsym: symmetric _ RelT)\n     (i1 i2: ilist T), IlistPerm4 RelT i1 i2 -> IlistPerm5 RelT i2 i1.\n   Proof.\n     intros T RelT Rsym i1 i2 h.\n     assert (h1:= IlistPerm4_flip_IlistPerm5 h) ; clear h.\n     induction h1 as [i1 i2 h1 h2] using IlistPerm5_ind_better.\n     apply (is_IlistPerm5 _ _ h1).\n     intro f2.\n     destruct (h2 f2) as [f1 [h3 [_ h4]]].\n     exists f1.\n     split.\n     - apply (Rsym _ _ h3).\n     - assumption.\n   Qed.\n\n   Lemma IlistPerm5_flip_IlistPerm4 : forall (T: Set)(RelT: relation T)(i1 i2: ilist T), \n     IlistPerm5 RelT i1 i2 -> IlistPerm4 (flip RelT) i2 i1.\n   Proof.\n     intros T RelT i1 i2 H.\n     induction H as [i1 i2 h1 h2] using IlistPerm5_ind_better.\n     apply (is_IlistPerm4 _ _ (sym_eq h1)).\n     intro f1.\n     destruct (h2 f1) as [f2 [h3 [_ h4]]].\n     exists f2.\n     split ; assumption.\n   Qed.\n\n   Lemma IlistPerm5_sym_IlistPerm4 : forall (T: Set)(RelT: relation T)(Rsym: symmetric _ RelT)\n     (i1 i2: ilist T), IlistPerm5 RelT i1 i2 -> IlistPerm4 RelT i2 i1.\n   Proof.\n     intros T RelT Rsym i1 i2 h.\n     assert (h1:= IlistPerm5_flip_IlistPerm4 h) ; clear h.\n     induction h1 as [i1 i2 h1 h2] using IlistPerm4_ind_better.\n     apply (is_IlistPerm4 _ _ h1).\n     intro f2.\n     destruct (h2 f2) as [f1 [h3 [_ h4]]].\n     exists f1.\n     split.\n     - apply (Rsym _ _ h3).\n     - assumption.\n   Qed.\n\n   (* deduced from IlistPerm4_refl *)\n   Lemma IlistPerm5_refl: forall (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(i: ilist T),\n     IlistPerm5 RelT i i.\n   Proof.\n     intros T RelT EqT i.\n     apply IlistPerm4_sym_IlistPerm5.\n     - destruct EqT as [_ Rsym _] ; assumption.\n     - apply (IlistPerm4_refl EqT).\n   Qed.\n\n   (* Proof by induction on IlistPerm4 *)\n   Lemma IlistPerm4_ilist_rel: forall (T: Set)(RelT: relation T)(EqT: Equivalence RelT)\n     (i1 i1' i2 : ilist T), ilist_rel RelT i1 i1' -> IlistPerm4 RelT i1 i2 -> \n     IlistPerm4 RelT i1' i2.\n   Proof.\n     intros T RelT EqT i1 i1' i2 h1 h2.\n     apply (ilist_rel_sym _) in h1.\n     revert i1' h1.\n     induction h2 as [i1 i2 e2 h2] using IlistPerm4_ind_better ; intros i1' h1.\n     destruct h1 as [e1 h1'].\n     apply (is_IlistPerm4 _ _ (trans_eq e1 e2)).\n     intro f1.\n     destruct (h2 (rewriteFins e1 f1)) as [f3 [h3 [h4 IH]]].\n     exists f3.\n     split.\n     - destruct EqT as [_ _ Rtrans].\n       apply (Rtrans _ _ _ (h1' f1) h3).\n     - apply IH.\n       assert (h : lgti (extroduce i1' f1) = lgti (extroduce i1 (rewriteFins e1 f1))).\n       { evalLgtiExtro.\n         assumption. }\n       apply (is_ilist_rel _ _ _ h).\n       intro f.\n       elim (le_lt_dec (decode_Fin f1) (decode_Fin f)) ; intros a.\n       + rewrite extroduce_ok3' ; try assumption.\n         rewrite extroduce_ok3' by (treatFin a).\n         assert (h5: rewriteFins (sym_eq (extroduce_lgti i1 (rewriteFins e1 f1))) (succ (rewriteFins h f)) =\n                     rewriteFins e1 (rewriteFins (sym_eq (extroduce_lgti i1' f1)) (succ f))).\n         { treatFinPure. }\n         rewrite h5.\n         apply h1'.\n       + rewrite extroduce_ok2' ; try assumption.\n         rewrite extroduce_ok2' by (treatFin a).\n         assert (h5: rewriteFins (sym_eq (extroduce_lgti i1 (rewriteFins e1 f1)))\n            (weakFin (rewriteFins h f)) = rewriteFins e1\n            (rewriteFins (sym_eq (extroduce_lgti i1' f1)) (weakFin f))).\n         * treatFinPure.\n         * rewrite h5.\n           apply h1'.\n   Qed.\n\n   (* Proof with induction on IlistPerm3 *)\n   Lemma IlistPerm3_ilist_rel: forall (T: Set)(RelT: relation T)(EqT: Equivalence RelT)\n     (i1 i1' i2 : ilist T), ilist_rel RelT i1 i1' -> IlistPerm3 RelT i1 i2 -> \n     IlistPerm3 RelT i1' i2.\n   Proof.\n     intros T RelT EqT i1 i1' i2 h1 h2.\n     revert i1' h1 ; induction h2 as [i1 i2 e2 e3 | i1 i2 f1 f2 e2 h2 IH] ; intros i1' [e1 h1].\n     - apply (IlistPerm3_nil _ _ _ (trans_eq (sym_eq e1) e2) (trans_eq (sym_eq e1) e3)).\n     - apply (IlistPerm3_cons _ _ (rewriteFins e1 f1) f2).\n       + destruct EqT as [_ Rsym Rtrans].\n         apply (Rtrans _ _ _ (Rsym _ _ (h1 f1)) e2).\n       + apply IH.\n         assert (h3: lgti (extroduce i1 f1) = lgti (extroduce i1' (rewriteFins e1 f1))).\n         { evalLgtiExtro.\n           assumption. }\n         apply (is_ilist_rel _ _ _ h3).\n         intro f.\n         elim (le_lt_dec (decode_Fin f1) (decode_Fin f)) ; intros a.\n         (* continue as for IlistPerm4_ilist_rel (only variable names have changed) *)\n         * rewrite extroduce_ok3' ; try assumption.\n           rewrite extroduce_ok3' by (treatFin a).\n           assert (h4: rewriteFins (sym_eq (extroduce_lgti i1' (rewriteFins e1 f1))) (succ (rewriteFins h3 f)) =\n                       rewriteFins e1 (rewriteFins (sym_eq (extroduce_lgti i1 f1)) (succ f))).\n           { treatFinPure. }\n           rewrite h4.\n           apply h1.\n         * rewrite extroduce_ok2' ; try assumption.\n           rewrite extroduce_ok2' by (treatFin a).\n           assert (h5: rewriteFins (sym_eq (extroduce_lgti i1' (rewriteFins e1 f1)))\n              (weakFin (rewriteFins h3 f)) = rewriteFins e1\n              (rewriteFins (sym_eq (extroduce_lgti i1 f1)) (weakFin f))).\n           { treatFinPure. }\n           rewrite h5.\n           apply h1.\n   Qed.\n\n   Lemma IlistPerm3_ilist_rel_eq: forall (T: Set)(RelT: relation T)(l1 l1' l2 : ilist T)\n     (h: ilist_rel (@eq T) l1 l1'), IlistPerm3 RelT l1 l2 ->  IlistPerm3 RelT l1' l2.\n   Proof.\n     intros T RelT l1 l1' l2 h1 h2.\n     revert l1' h1 ; induction h2 as [l1 l2 e2 e3 | l1 l2 i1 i2 e2 h2 IH] ; intros l1' h1 ;\n     inversion h1 as [e1 h1'].\n     - apply (IlistPerm3_nil _ _ _ (trans_eq (sym_eq e1) e2) (trans_eq (sym_eq e1) e3)).\n     - apply (IlistPerm3_cons _ _ (rewriteFins e1 i1) i2).\n       + rewrite <- (h1' i1).\n         assumption.\n       + apply IH.\n         apply extroduce_ilist_rel_bis.\n         assumption.\n   Qed.\n\n(* just a dual proof for the changes in the second argument *)\n  Lemma IlistPerm3_ilist_rel_eq_snd: forall (T: Set)(RelT: relation T)(l1 l2 l2' : ilist T)\n     (h: ilist_rel (@eq T) l2 l2'), IlistPerm3 RelT l1 l2 ->  IlistPerm3 RelT l1 l2'.\n   Proof.\n     intros T RelT l1 l1' l2 h1 h2.\n     revert l2 h1 ; induction h2 as [l1 l2 e2 e3 | l1 l2 i1 i2 e2 h2 IH] ; intros l1' h1 ;\n     inversion h1 as [e1 h1'].\n     apply (IlistPerm3_nil _ _ _ (trans_eq e2 e1) e3).\n     apply (IlistPerm3_cons _ _ i1 (rewriteFins e1 i2)).\n     rewrite <- (h1' i2).\n     assumption.\n     apply IH.\n     apply extroduce_ilist_rel_bis.\n     assumption.\n   Qed.\n\n   Add Parametric Morphism (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(l: ilist T) : \n     (fun x => IlistPerm3 RelT x l)\n   with signature (ilist_rel RelT ==> impl) as IlistPerm3M1_Eq.\n   Proof.\n     intros l2 l2' H2 H3.\n     apply (IlistPerm3_ilist_rel EqT H2 H3).\n   Qed.\n     \n   Add Parametric Morphism (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(l: ilist T) : \n     (IlistPerm3 RelT l)\n   with signature (ilist_rel RelT ==> impl) as IlistPerm3M2_Eq.\n   Proof.\n     intros l1 l1' H2 H3.\n     apply (IlistPerm3_sym EqT).\n     apply (IlistPerm3_sym EqT) in H3.\n     apply (IlistPerm3_ilist_rel EqT H2 H3).\n   Qed.\n\n   Add Parametric Morphism (T: Set)(RelT: relation T)(EqT: Equivalence RelT): \n     (IlistPerm3 RelT)\n   with signature (ilist_rel RelT ==> ilist_rel RelT ==> impl) as IlistPerm3M_Eq.\n   Proof.\n     intros l1 l1' H1 l2 l2' H2 H3.\n     apply (IlistPerm3M2_Eq EqT H2).\n     apply (IlistPerm3M1_Eq EqT H1).\n     assumption.\n   Qed.\n\n   Lemma ilist_rel_finer_IlistPerm3: forall (T: Set)(RelT: relation T)\n     (i1 i2 : ilist T), ilist_rel RelT i1 i2 -> IlistPerm3 RelT i1 i2.\n   Proof.\n     intros T RelT [n l1] [n2 l2] H.\n     inversion H as [h2 _].\n     cbn in h2.\n     revert l2 H ; rewrite <- h2 ; intros l2 H ; clear n2 h2.\n     induction n as [|n IH].\n     - destruct H as [h H] ; cbn in *|-*.\n       apply IlistPerm3_nil ; reflexivity.\n     - assert (i := first n).\n       apply (IlistPerm3_cons _ _ (i: Fin (lgti (existT (fun n0 : nat => ilistn T n0) (S n) l1))) \n         (i: Fin (lgti (existT (fun n0 : nat => ilistn T n0) (S n) l2)))).\n       + destruct H as [h H].\n         assert (H1: forall i, RelT (l1 i) (l2 i)).\n         { intro i'. \n           assert (h' : i' = rewriteFins h i').\n           unfold rewriteFins; apply decode_Fin_unique, decode_Fin_match.\n           rewrite h' at 2 ; apply (H i'). }\n         clear h H.\n         apply H1.\n       + assert (H1 := extroduce_ilist_rel i H).\n         revert H1 ; unfold mkilist.\n         set (l1' := extroduce (existT (fun n0 : nat => ilistn T n0) (S n) l1) i).\n         set (l2' := extroduce (existT (fun n0 : nat => ilistn T n0) (S n) l2) i).\n         intro H1.\n         assert (h: lgti l1' = n).\n         { unfold l1' ; apply eq_add_S.\n           rewrite <- extroduce_lgti.\n           reflexivity. }\n         destruct l1' as [n' l1'] ; destruct l2' as [n2 l2'].\n         inversion H1 as [h1 _].\n         cbn in *|-*.\n         revert l1' l2' H1.\n         rewrite <- h1, h.\n         apply IH.\n   Qed.\n  \n   Lemma ilist_rel_finer_IlistPerm4: forall (T: Set)(RelT: relation T)\n     (l1 l2 : ilist T), ilist_rel RelT l1 l2 -> IlistPerm4 RelT l1 l2.\n   Proof.\n     intros T RelT [n l1] [n2 l2] h.\n     inversion h as [h2 _].\n     cbn in h2.\n     revert l2 h ; rewrite <- h2 ; intros l2 h ; clear n2 h2.\n     fold (mkilist l1) (mkilist l2).\n     induction n as [|n IH].\n     { apply IlistPerm4nil. }\n     apply (is_IlistPerm4 _ _ (refl_equal _ : lgti (mkilist l1) = lgti (mkilist l2))).\n     intro i.\n     inversion h as [e h'].\n     simpl lgti in *|-* ; simpl fcti in *|-*.\n     exists i.\n     split.\n     - rewrite (decode_Fin_unique _ _ (decode_Fin_match' i e)) at 2.\n       apply h'.\n     - assert (hex := extroduce_ilist_rel i h).\n       revert hex.\n       set (l1' := extroduce (mkilist l1) i) ; set (l2' := extroduce (mkilist l2) i) ; \n         assert (h1 := extroduce_lgti_S l1 i :n = lgti l1') ; assert (h2 := extroduce_lgti_S l2 i :n = lgti l2').\n       destruct l1' as [n1 l1'] ; destruct l2' as [n2 l2'].\n       cbn in h1, h2.\n       revert l1' l2' ; rewrite <- h1, <- h2 ; clear n1 n2 h1 h2.\n       apply IH.\n   Qed.\n\n   Lemma IlistPerm3_imap (T U: Set)(RelT: relation T)(RelU: relation U)\n     (f: T -> U)(fM: Proper (RelT ==> RelU) f) (l1 l2: ilist T): \n     IlistPerm3 RelT l1 l2 -> IlistPerm3 RelU (imap f l1) (imap f l2).\n   Proof.\n     intro H ; induction H as [[n1 l1] [n2 l2] e1 e2 | l1 l2 i1 i2 h2 H IH].\n     { apply IlistPerm3_nil ; assumption. }\n     apply (IlistPerm3_cons _ _ (i1 : Fin (lgti(imap f l1))) (i2: Fin (lgti (imap f l2)))).\n     - cbn.\n       apply fM, h2.\n     - apply (IlistPerm3_ilist_rel_eq (ilist_rel_sym _ (extroduce_imap f l1 i1))).\n       apply (IlistPerm3_ilist_rel_eq_snd (ilist_rel_sym _ (extroduce_imap f l2 i2))).\n       apply IH.\n   Qed.\n\n  Lemma IlistPerm3_imap_bis (A B: Set)(Rel: relation B)(f1 f2: A -> B)(l1 l2: ilist A):\n     IlistPerm3 (fun a1 a2 => Rel (f1 a1) (f2 a2)) l1 l2 -> IlistPerm3 Rel (imap f1 l1) (imap f2 l2).\n   Proof.\n     intro Hyp.\n     induction Hyp as [l1 l2 Hyp1 Hyp2 | l1 l2 i1 i2 H1 _ IH].\n     { apply IlistPerm3_nil ; assumption. }\n     apply (IlistPerm3_cons _ _ (i1 : Fin (lgti (imap f1 l1))) (i2 : Fin (lgti (imap f2 l2)))).\n     - assumption.\n     - assert (H7 := extroduce_imap f1 l1 i1).\n      apply ilist_rel_sym in H7 ; try apply eq_equivalence.\n      apply (IlistPerm3_ilist_rel_eq H7).\n      clear H7.\n      assert (H7 := extroduce_imap f2 l2 i2).\n      apply ilist_rel_sym in H7 ; try apply eq_equivalence.\n      apply (IlistPerm3_ilist_rel_eq_snd H7).\n      assumption.\n   Qed.\n\n   Lemma IlistPerm3_imap_back (A B: Set)(Rel: relation B)\n     (f1 f2: A -> B)(l1 l2: ilist A): IlistPerm3 Rel (imap f1 l1) (imap f2 l2) -> \n     IlistPerm3 (fun a1 a2 => Rel (f1 a1) (f2 a2)) l1 l2.\n   Proof.\n     remember (lgti l1) as n.\n     revert l1 l2 Heqn ; induction n as [|n IH] ; intros l1 l2 H H1. \n     - apply IlistPerm3_nil.\n       + apply (IlistPerm3_lgti H1).\n       + symmetry ; assumption.\n     - inversion_clear H1 as [H2 H3 | i1 i2 H2 H3].\n       + cbn in H3 ; rewrite <- H in H3.\n         inversion H3.\n       + cbn in i1, i2, H2.\n         apply (IlistPerm3_cons _ _ i1 i2).\n         * assumption.\n         * apply IH.\n           -- evalLgtiExtro.\n              apply H.\n           -- assert (H4 := extroduce_imap f1 l1 i1).\n              assert (H5 := extroduce_imap f2 l2 i2).\n              apply (IlistPerm3_ilist_rel_eq H4), (IlistPerm3_ilist_rel_eq_snd H5), H3.\n   Qed.\n\n  Lemma IlistPerm3_exists_rec: forall (T: Set)(RelT: relation T)\n     (i1 i2: ilist T), IlistPerm3 RelT i1 i2 -> forall f1, exists f2, RelT (fcti i1 f1) (fcti i2 f2) /\\ \n                           IlistPerm3 RelT (extroduce i1 f1) (extroduce i2 f2).\n   Proof.\n     intros T RelT l1 l2 H.\n     induction H as [l1 l2 _ e2 | l1 l2 i1 i2 h2 H IH].\n     - (* empty list *)\n       intros i1.\n       apply False_rec.\n       rewrite e2 in i1.\n       inversion i1.\n     - (* non-empty list *)\n       assert (h1:= eq_S _ _ (IlistPerm3_lgti H)).\n       do 2 rewrite <- extroduce_lgti in h1.\n       destruct l1 as [n l1] ; destruct l2 as [n2 l2];\n       cbn in i1, i2, h1, h2 ;\n       fold (mkilist l1) in *|-*;\n       fold (mkilist l2) in *|-*.\n       revert l2 i2 h2 H IH ; rewrite <- h1 ; intros l2 i2 h2 H IH ; clear n2 h1.\n       change (forall i1', exists i2', RelT (l1 i1') (l2 i2') /\\ \n                         IlistPerm3 RelT (extroduce (mkilist l1) i1') (extroduce (mkilist l2) i2')).\n       intros i1'. \n       (* is there something to do renaming? *)\n       elim (eq_nat_dec (decode_Fin i1) (decode_Fin i1')) ; intros a.\n       + (* f1 = f1' *)\n         rewrite <- (decode_Fin_unique _ _ a).\n         exists i2.\n         split; assumption.\n       + (* f1 <> f1' *)\n         destruct n as [|n].\n         * (* exclude zero case *)\n           inversion i1.\n     * (* main case *)    \n       set (i1'new := index_in_extroduce i1 i1' a).\n       destruct (IH (rewriteFins (extroduce_lgti_S _ i1) i1'new)) as [i2IH [IH1 IH2]].\n       set (i2IH' := rewriteFins (sym_eq (extroduce_lgti_S _ i2)) i2IH).\n       set (i2' := extroduce_Fin i2 i2IH').\n       exists i2'.\n       split.\n       -- assert (h3: l1 i1' = fcti (extroduce (mkilist l1) i1) (rewriteFins (extroduce_lgti_S l1 i1) i1'new)) by\n             apply index_in_extroduce_ok_cor.\n          assert (h4: l2 i2' = fcti (extroduce (mkilist l2) i2) i2IH).\n          { unfold i2', i2IH'.\n            rewrite extroduce_Fin_ok_cor.\n            f_equal.\n            treatFinPure. }\n          rewrite h3, h4.\n          assumption.\n       -- set (i1new := index_in_extroduce i1' i1 (not_eq_sym a)).\n          assert (a2:  decode_Fin i2' <> decode_Fin i2).\n          { unfold i2'.\n            intro Hyp.\n            apply decode_Fin_unique in Hyp.\n            apply (extroduce_Fin_not_fex _ Hyp). }\n          set (i2new := index_in_extroduce i2' i2 a2).\n          apply (IlistPerm3_cons _ _ (rewriteFins (extroduce_lgti_S l1 i1') i1new) \n                                         (rewriteFins (extroduce_lgti_S l2 i2') i2new)).\n          ++ unfold i1new.\n             rewrite <- index_in_extroduce_ok_cor.\n             unfold i2new.\n             rewrite <- index_in_extroduce_ok_cor.\n             exact h2.\n          ++ assert (H1:= extroduce_interchange_eq l1 i1' i1 (not_eq_sym a) a).\n             fold i1new i1'new in H1.\n             assert (H2:= extroduce_interchange_eq l2 i2' i2 a2 (not_eq_sym a2)).\n             fold i2new in H2.\n             apply ilist_rel_sym in H1 ; apply ilist_rel_sym in H2 ; try apply eq_equivalence.\n             apply (IlistPerm3_ilist_rel_eq H1), (IlistPerm3_ilist_rel_eq_snd H2).\n             assert (H3 : i2IH = rewriteFins (extroduce_lgti_S l2 i2) (index_in_extroduce i2 i2' (not_eq_sym a2))).\n             { unfold i2', i2IH'.\n               rewrite index_in_from_extroduce.\n               apply decode_Fin_unique.\n               do 2 rewrite <- decode_Fin_match'.\n               reflexivity. }\n             rewrite <- H3.\n             assumption.\n   Qed.\n\n   (* from the Coq tutorial at POPL'08 *)\n   Tactic Notation \"remember\" constr(c) \"as\" ident(x) \"in\" \"|-\" :=\n     let x := fresh x in\n     let H := fresh \"Heq\" x in\n     (set (x := c); assert (H : x = c) by reflexivity; clearbody x).\n\n   Lemma IlistPerm3_IlistPerm4_eq: forall (T: Set)(RelT: relation T)(i1 i2: ilist T),\n     IlistPerm3 RelT i1 i2 -> IlistPerm4 RelT i1 i2.\n   Proof.\n     intros T RelT l1 l2 H.\n     remember (lgti l1) as n in |-.\n     revert l1 l2 H Heqn ; induction n as [|n IH]; intros l1 l2 H Heqn ; cbn in *|-*.\n     - apply IlistPerm4nil_gen.\n       + apply (IlistPerm3_lgti H).\n       + symmetry; assumption.\n     - apply is_IlistPerm4.\n       + apply (IlistPerm3_lgti H).\n       + intro i1.\n         destruct (IlistPerm3_exists_rec H i1) as [i2 [Hyp1 Hyp2]].\n         exists i2.\n         split.\n         * exact Hyp1.\n         * apply IH.\n           -- apply Hyp2.\n           -- evalLgtiExtro.\n              apply Heqn.\n   Qed.\n\n   Lemma IlistPerm3_extroduce : forall (T: Set)(RelT: relation T)\n     (i1 i2: ilist T)(f1: Fin (lgti i1)) (f2 : Fin (lgti i2)), RelT (fcti i1 f1) (fcti i2 f2) -> \n     IlistPerm3 RelT (extroduce i1 f1) (extroduce i2 f2) -> IlistPerm3 RelT i1 i2.\n   Proof.\n     intros T RelT i1 i2 f1 f2.\n     apply IlistPerm3_cons.\n   Qed.\n\n   Lemma IlistPerm3_trans (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(l1 l2 l3 : ilist T) : \n     IlistPerm3 RelT l1 l2 -> IlistPerm3 RelT l2 l3 -> IlistPerm3 RelT l1 l3.\n   Proof.  \n     intros H1 H2.\n     apply IlistPerm4_IlistPerm3_eq.\n     apply IlistPerm3_IlistPerm4_eq in H1.\n     apply IlistPerm3_IlistPerm4_eq in H2.\n     apply (IlistPerm4_trans _ H1 H2).\n   Qed.\n\n   Lemma IlistPerm3_trans_trans (T: Set)(RelT: relation T)(Rtrans: Transitive RelT)(l1 l2 l3 : ilist T) : \n     IlistPerm3 RelT l1 l2 -> IlistPerm3 RelT l2 l3 -> IlistPerm3 RelT l1 l3.\n   Proof.  \n     intros H1 H2.\n     apply IlistPerm4_IlistPerm3_eq.\n     apply IlistPerm3_IlistPerm4_eq in H1.\n     apply IlistPerm3_IlistPerm4_eq in H2.\n     apply (IlistPerm4_trans_trans _ H1 H2).\n   Qed.\n\n   Add Parametric Relation (T: Set)(RelT: relation T)(EqT: Equivalence RelT) : (ilist T)(IlistPerm3 RelT) \n      reflexivity proved by (IlistPerm3_refl EqT)\n      symmetry proved by (IlistPerm3_sym EqT)\n      transitivity proved by (IlistPerm3_trans EqT)\n      as IlistPerm3Rel.\n\n   Lemma IlistPerm4_sym (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(l1 l2 : ilist T) : \n     IlistPerm4 RelT l1 l2 -> IlistPerm4 RelT l2 l1.\n   Proof.  \n     intros H1.\n     apply IlistPerm4_IlistPerm3_eq in H1.\n     apply IlistPerm3_IlistPerm4_eq.\n     apply (IlistPerm3_sym _ H1).\n   Qed.\n\n   Lemma IlistPerm4_sym_sym (T: Set)(RelT: relation T)(Rsym: Symmetric RelT)(l1 l2 : ilist T) : \n     IlistPerm4 RelT l1 l2 -> IlistPerm4 RelT l2 l1.\n   Proof.  \n     intros H1.\n     apply IlistPerm4_IlistPerm3_eq in H1.\n     apply IlistPerm3_IlistPerm4_eq.\n     apply (IlistPerm3_sym_sym _ H1).\n   Qed.\n\n   Add Parametric Relation (T: Set)(RelT: relation T)(EqT: Equivalence RelT) : (ilist T)(IlistPerm4 RelT) \n      reflexivity proved by (IlistPerm4_refl EqT)\n      symmetry proved by (IlistPerm4_sym EqT)\n      transitivity proved by (IlistPerm4_trans EqT)\n      as IlistPerm4Rel.\n\n   Lemma IlistPerm5_sym (T: Set)(RelT: relation T)(EqT: Equivalence RelT)(l1 l2 : ilist T) : \n     IlistPerm5 RelT l1 l2 -> IlistPerm5 RelT l2 l1.\n   Proof.  \n     intros H1.\n     inversion EqT as [_ Rsym _].\n     apply (IlistPerm5_sym_IlistPerm4 Rsym) in H1.\n     apply (IlistPerm4_sym_IlistPerm5 Rsym).\n     apply (IlistPerm4_sym _ H1).\n   Qed.\n     \n   Lemma IlistPerm4_trans_special (A: Set)(R1 R2: relation A)(i1 i2 i3: ilist A):\n     IlistPerm4 R1 i1 i2 -> IlistPerm4 R2 i2 i3 -> IlistPerm4 \n       (fun a1 a3 => exists a2, R1 a1 a2 /\\ R2 a2 a3) i1 i3.\n   Proof.\n     intro Hyp1.\n     revert i3.\n     induction Hyp1 as [l1 l2 H1 IH] using IlistPerm4_ind_better.\n     intros l3 Hyp.\n     inversion_clear Hyp as [x y H2 H3].\n     apply is_IlistPerm4.\n     - transitivity (lgti l2); assumption.\n     - intro i1.\n       destruct (IH i1) as [i2 [HypR1 [_ H5]]].\n       destruct (H3 i2) as [i3 [HypR2 H2']].\n       exists i3.\n       split.\n       + exists (fcti l2 i2).\n         split; assumption.\n       + apply H5, H2'.\n   Qed.\n \n   Corollary IlistPerm3_trans_special (A: Set)(R1 R2: relation A)(i1 i2 i3: ilist A):\n     IlistPerm3 R1 i1 i2 -> IlistPerm3 R2 i2 i3 -> \n     IlistPerm3 (fun a1 a3 => exists a2, R1 a1 a2 /\\ R2 a2 a3) i1 i3.\n   Proof.\n     intros.\n     apply IlistPerm4_IlistPerm3_eq.\n     apply (IlistPerm4_trans_special (i2:= i2));\n     apply IlistPerm3_IlistPerm4_eq; assumption.\n   Qed.\n   \n   Lemma IlistPerm3_mon :forall(U : Set) (l1 l2 : ilist U) R1 R2, \n     subrelation R1 R2 -> IlistPerm3 R1 l1 l2 -> IlistPerm3 R2 l1 l2.\n   Proof.\n     intros.\n     induction H0.\n     - apply IlistPerm3_nil; assumption.\n     - apply (IlistPerm3_cons _ _ f1 f2).\n       + apply H.\n         assumption.\n       + assumption.\n   Qed.\n\n  Section IlistPerm34_dec.\n    Section IlistPerm6. \n    \n      Inductive IlistPerm6 (T: Set)(RelT: relation T)(l1 l2: ilist T): Prop :=\n        IlistPerm6_nil: lgti l1 = lgti l2 -> lgti l1 = 0 -> IlistPerm6 RelT l1 l2  \n      | IlistPerm6_cons: (exists i1 , exists i2, RelT (fcti l1 i1) (fcti l2 i2) /\\\n        IlistPerm6 RelT (extroduce l1 i1) (extroduce l2 i2)) -> IlistPerm6 RelT l1 l2.\n       \n      Lemma IlistPerm6_ind_better (T: Set)(RelT : relation T)(P : ilist T → ilist T → Prop): \n        (forall l1 l2 : ilist T, lgti l1 = lgti l2 -> lgti l1 = 0 -> P l1 l2) -> \n        (forall l1 l2 : ilist T, forall i1 i2, RelT (fcti l1 i1) (fcti l2 i2) ->\n        IlistPerm6 RelT (extroduce l1 i1) (extroduce l2 i2) -> P (extroduce l1 i1) (extroduce l2 i2) -> \n        P l1 l2) -> (forall l1 l2 : ilist T, IlistPerm6 RelT l1 l2 -> P l1 l2).\n      Proof.\n        fix Hr 5.\n        intros H1 H2 l1 l2 H3.\n        destruct H3 as [H3 H4 | [i1 [i2 [H3 H4]]]].\n        - apply H1 ; assumption.\n        - apply (H2 l1 l2 i1 i2 H3 H4).\n          apply Hr ; try assumption.\n      Qed.\n\n      Lemma IlistPerm6_lgti (T: Set)(RelT: relation T)(l1 l2: ilist T): IlistPerm6 RelT l1 l2 -> \n        lgti l1 = lgti l2.\n      Proof.\n        revert l1 l2.\n        fix Hr 3.\n        intros l1 l2 [H1 H2 | [i1 [i2 [H1 H2]]]].\n        - assumption.\n        - assert (H3 := Hr _ _ H2).\n          apply eq_S in H3.\n          do 2 rewrite <- extroduce_lgti in H3.\n          assumption.\n      Qed.\n\n      Lemma IlistPerm3_IlistPerm6_eq (T: Set)(RelT: relation T)(l1 l2: ilist T): \n        IlistPerm3 RelT l1 l2 -> IlistPerm6 RelT l1 l2.\n      Proof.\n        intros H ; induction H as [l1 l2 H1 H2 | l1 l2 i1 i2 H1 H2 IH].\n        - apply IlistPerm6_nil; assumption.\n        - apply IlistPerm6_cons.\n          exists i1, i2 ; split; assumption.\n      Qed.\n\n      Lemma IlistPerm6_IlistPerm3_eq (T: Set)(RelT: relation T)(l1 l2: ilist T): \n        IlistPerm6 RelT l1 l2 -> IlistPerm3 RelT l1 l2.\n      Proof.\n        intros H.\n        induction H using IlistPerm6_ind_better.\n        - apply IlistPerm3_nil ; assumption.\n        - apply (IlistPerm3_cons _ _ i1 i2); assumption.\n      Qed.\n\n      Lemma IlistPerm4_IlistPerm6_eq (T: Set)(RelT: relation T)(l1 l2: ilist T): \n        IlistPerm4 RelT l1 l2 -> IlistPerm6 RelT l1 l2.\n      Proof.\n        intro H.\n        apply IlistPerm3_IlistPerm6_eq, IlistPerm4_IlistPerm3_eq.\n        assumption.\n      Qed.\n\n      Lemma IlistPerm6_IlistPerm4_eq (T: Set)(RelT: relation T)(l1 l2: ilist T): \n        IlistPerm6 RelT l1 l2 -> IlistPerm4 RelT l1 l2.\n      Proof.\n        intro H.\n        apply IlistPerm3_IlistPerm4_eq, IlistPerm6_IlistPerm3_eq.\n        assumption.\n      Qed.\n    End IlistPerm6. \n\n    Lemma extroduce_IlistPerm4 (T: Set)(RelT: relation T)(Req : Equivalence RelT)(l1 l2: ilist T): \n      forall i1 i2, IlistPerm4 RelT l1 l2 -> RelT (fcti l1 i1) (fcti l2 i2) -> \n      IlistPerm4 RelT (extroduce l1 i1) (extroduce l2 i2).\n    Proof.\n      intros i1 i2 H.\n      apply IlistPerm4_IlistPerm6_eq in H.\n      induction H  as [l1 l2 H1 H2| l1 l2 i1' i2' H1 H2 IH] using IlistPerm6_ind_better.\n      { apply False_rec; rewrite H2 in i1 ; inversion i1. }\n      destruct l1 as [n l1] ; destruct l2 as [n2 l2] ; assert (H4 := IlistPerm6_lgti H2) ; \n      cbn in H1, i1', i2'; fold (mkilist l1) (mkilist l2) in *|-*.\n      apply eq_S in H4 ; do 2 rewrite <- extroduce_lgti in H4 ; cbn in H4.\n      revert l2 i2' H1 H2 IH i2; rewrite <- H4 ; clear n2 H4 ; intros l2 i2' H1 H2 IH i2 H3 ; \n      cbn in i1, i2, H3.\n      destruct n as [|n].\n      { inversion i1. }\n      apply IlistPerm6_IlistPerm4_eq.\n      elim (eq_nat_dec (decode_Fin i1') (decode_Fin i1)) ; intros a ; \n      (* case i1 = i1'*) \n      try (revert H3 ; rewrite <- (decode_Fin_unique _ _ a) ; clear i1 a; intros H3) ; \n      elim (eq_nat_dec (decode_Fin i2') (decode_Fin i2)) ; intros b ;\n      (* case i2 = i2'*)\n      try (revert H3 ; rewrite <- (decode_Fin_unique _ _ b) ;  clear i2 b; intros H3 ) ; \n      (* case i1 = i1' /\\ i2 = i2'*)\n      try apply H2 ; \n      (* all other cases *)\n      apply IlistPerm6_cons ; apply IlistPerm6_IlistPerm4_eq in H2.\n      - (* case i1 = i1' /\\ i2 <> i2' *)\n        apply IlistPerm4_sym_IlistPerm5, (IlistPerm5_sym Req) in H2; try (destruct Req ; assumption).\n        inversion_clear H2 as [i3 i4 H9 H4 H10 H11] ; clear H9.\n        destruct (H4 (rewriteFins (extroduce_lgti_S _ _) (index_in_extroduce i2' i2 b))) as [i1 [H5 H6]].\n        exists i1, (rewriteFins (extroduce_lgti_S _ _) (index_in_extroduce i2 i2' (not_eq_sym b))).\n        split.\n        + rewrite H5, <- index_in_extroduce_ok_cor, <- index_in_extroduce_ok_cor, <- H3.\n          assumption.\n        + apply IlistPerm3_IlistPerm6_eq, (IlistPerm3_ilist_rel_eq_snd (extroduce_interchange_eq l2 _ _ b _)).\n          apply IlistPerm5_IlistPerm3_eq, H6.\n      - (* cas i1 <> i1' /\\ i2 = i2' *)\n        inversion_clear H2 as [i3 i4 H9 H4 H10 H11] ; clear H9.\n        destruct (H4 (rewriteFins (extroduce_lgti_S _ _) (index_in_extroduce i1' i1 a))) as [i2 [H5 H6]].\n        exists (rewriteFins (extroduce_lgti_S _ _) (index_in_extroduce i1 i1' (not_eq_sym a))), i2.\n        split.\n        + rewrite <- H5, <- index_in_extroduce_ok_cor, <- index_in_extroduce_ok_cor, H3.\n          assumption.\n        + apply IlistPerm3_IlistPerm6_eq, \n          (IlistPerm3_ilist_rel_eq (extroduce_interchange_eq l1 _ _ a (not_eq_sym a))).\n          apply IlistPerm4_IlistPerm3_eq, H6.\n      - (* cas i1 <> i1' /\\ i2 <> i2' *) \n        exists (rewriteFins (extroduce_lgti_S _ _) (index_in_extroduce _ _ (not_eq_sym a))), \n      (rewriteFins (extroduce_lgti_S _ _) (index_in_extroduce _ _ (not_eq_sym b))).\n        split.\n        + do 2 rewrite <- index_in_extroduce_ok_cor.\n          assumption.\n        + apply IlistPerm3_IlistPerm6_eq, (IlistPerm3_ilist_rel_eq (extroduce_interchange_eq l1 _ _ a _)).\n          apply (IlistPerm3_ilist_rel_eq_snd (extroduce_interchange_eq l2 _ _ b _)), IlistPerm4_IlistPerm3_eq.\n          apply IH.\n          do 2 rewrite <- index_in_extroduce_ok_cor.\n          assumption.\n    Qed.\n\n    Lemma exists_eq_Ilist (T: Set)(RelT: relation T)\n      (Rdec : forall t1 t2, {RelT t1 t2}+{not (RelT t1 t2)})(t: T)(n: nat) (l : ilistn T n): \n      { i | RelT t (l i)} + {not (exists i, RelT t (l i))}.\n    Proof.\n      induction n as [|n IH].\n      - right.\n        intros [i _] ; inversion i.\n      - elim (Rdec t (l (first n))) ; intros H.\n        + left.\n          exists (first n) ; assumption.\n        + destruct (IH (fun x => l (succ x))) as [[i H1] | H1].\n          * left.\n            exists (succ i) ; assumption.\n          * right.\n            intros [i H2].\n            elim (zerop (decode_Fin i)) ; intros a.\n            -- rewrite (decode_Fin_0_first _ a) in H2.\n               contradiction.\n            -- apply H1.\n               exists (get_cons _ a).\n               rewrite <- (decode_Fin_unique _ _ (decode_Fin_get_cons _ _ : \n                   decode_Fin i = decode_Fin (succ (get_cons i a)))).\n               assumption.\n    Qed.\n    \n    Lemma IlistPerm4_dec (T: Set)(RelT: relation T)(Req : Equivalence RelT)\n      (Rdec : forall t1 t2, {RelT t1 t2}+{not (RelT t1 t2)}): \n      forall l1 l2, {IlistPerm4 RelT l1 l2}+{not (IlistPerm4 RelT l1 l2)}.\n    Proof.\n      intros [n1 l1] [n2 l2].\n      (* comparison between n1 and n2 *)\n      elim (eq_nat_dec n1 n2) ; intros H.\n      - (* case n1 = n2 --> suppression of n2 *)\n        revert l2.\n        rewrite <- H.\n        intros l2 ; clear n2 H.\n        (* induction on n1 *)\n        induction n1 as [|n1 IH].\n        + (* case 0 *)\n          left.\n          apply IlistPerm4nil.\n        + (* case S n1 *)\n          (* Does an element in l2 \"equal\" to l1 (first n1) exists ? *)\n          elim (exists_eq_Ilist RelT Rdec (l1 (first n1)) l2) ; intros H1.\n          * (* yes : i *)\n            destruct H1 as [i H1].\n            (* trick to use IH *)\n            set (e1 := extroduce (mkilist l1) (first n1)).\n            set (e2 := extroduce (mkilist l2) i).\n            assert (H2 : n1 = lgti e1) by apply extroduce_lgti_S.\n            assert (H3 : n1 = lgti e2) by apply extroduce_lgti_S.\n            assert (H4 := refl_equal _ : e1 = extroduce (mkilist l1) (first n1)).\n            assert (H5 := refl_equal _ : e2 = extroduce (mkilist l2) i).\n            destruct e1 as [n1' e1] ; destruct e2 as [n2' e2] ; cbn in H2, H3.\n            revert e1 e2 H4 H5 ; rewrite <- H2, <- H3 ; clear n1' n2' H2 H3 ; intros e1 e2 H2 H3.\n            elim (IH e1 e2) ; clear IH ; intros H4 ; \n              rewrite H2, H3 in H4 ; clear e1 e2 H2 H3.\n            -- (* here we prove the ilists are equivalent *)\n              left.\n              apply IlistPerm3_IlistPerm4_eq.\n              apply (IlistPerm3_cons _ _ (first n1 : Fin (lgti (mkilist l1))) (i : Fin (lgti (mkilist l2))) H1).\n              apply (IlistPerm4_IlistPerm3_eq H4).\n            -- (* here we prove the ilists are not equivalent *)\n              right.\n              intros H5.\n              assert (H6 := extroduce_IlistPerm4 _ (first n1: Fin (lgti (mkilist l1))) \n                 (i: Fin (lgti (mkilist l2))) H5 H1).\n              contradiction.\n          * (* no *)\n            right.\n            intro H.\n            inversion H.\n            clear H0 H3 H4 i1 i2.\n            destruct (H2 (first n1)) as [i [H3 _]].\n            apply H1.\n            exists i ; assumption.\n      - (* cas n1 <> n2 *)\n        right.\n        intro H1.\n        apply IlistPerm4_lgti in H1.\n        contradiction.\n    Qed.\n      \n    Lemma IlistPerm4_dec_IlistPerm3_dec (T: Set)(RelT: relation T):\n      (forall l1 l2, {IlistPerm4 RelT l1 l2}+{not (IlistPerm4 RelT l1 l2)}) ->\n      forall l1 l2, {IlistPerm3 RelT l1 l2}+{not (IlistPerm3 RelT l1 l2)}.\n    Proof.\n      intros H l1 l2.\n      destruct (H l1 l2) as [H1 | H1].\n      - left ; apply IlistPerm4_IlistPerm3_eq, H1.\n      - right ; intro H2 ; apply H1, IlistPerm3_IlistPerm4_eq, H2.\n    Qed.\n  \n    Lemma IlistPerm3_dec (T: Set)(RelT: relation T)(Req : Equivalence RelT)\n      (Rdec : forall t1 t2, {RelT t1 t2}+{not (RelT t1 t2)}): \n    forall l1 l2, {IlistPerm3 RelT l1 l2}+{not (IlistPerm3 RelT l1 l2)}.\n    Proof.\n      apply IlistPerm4_dec_IlistPerm3_dec, IlistPerm4_dec ; assumption.\n    Qed.\n\n    End IlistPerm34_dec.\n\n    Section IlistPerm3_cert.\n\n    (* IlistPerm3Cert shall now be IlistPerm3 with a certificate for the chosen permutation *)\n    Fixpoint IlistPerm3Cert_list (n: nat) : Set :=\n      match n with \n        0 => unit\n      | S n' => prod (prod (Fin (S n')) (Fin (S n'))) (IlistPerm3Cert_list n') end.\n\n    Definition IlistPerm3Cert_aux2 (A: Set)(i1 i2: ilist A)(Hyp: lgti i1 = lgti i2) \n      (f1: Fin(lgti i1))(f2: Fin(lgti i2)): lgti (extroduce i1 f1) = lgti (extroduce i2 f2).\n    Proof.\n      apply eq_add_S.\n      do 2 rewrite <- extroduce_lgti.\n      assumption.\n    Defined.\n\n    Definition rewriteIlistPerm3Cert_list (n1 n2: nat)(H: n1 = n2)(f: IlistPerm3Cert_list n1): \n      IlistPerm3Cert_list n2.\n    Proof.\n      revert n2 H ; induction n1 as [|n1 IH] ; intros [|n2] H.\n      - exact tt.\n      - inversion H.\n      - inversion H.\n      - destruct f as [[i1 i2] f].\n        fold (IlistPerm3Cert_list n1) in f.\n        split.\n        + exact (rewriteFins H i1, rewriteFins H i2).\n        + apply (IH f).\n          apply eq_add_S, H.\n    Defined.\n\n    Definition IlistPerm3Cert_aux3 (A: Set)(l1 l2: ilist A)(Hyp : lgti l1 = lgti l2)(i1: Fin(lgti l1))\n      (i2 : Fin (lgti l2))(c: IlistPerm3Cert_list (lgti (extroduce l1 i1))): IlistPerm3Cert_list (lgti l1).\n    Proof.\n      destruct l1 as [[|n1] l1].\n      - inversion i1.\n      - exact (i1, (rewriteFins (sym_eq Hyp) i2), (rewriteIlistPerm3Cert_list (sym_eq (extroduce_lgti_S _ _)) c)).\n    Defined.\n\n    Lemma IlistPerm3Cert_list_eq (n: nat)(c: IlistPerm3Cert_list n)(H: n = n) : \n      c = rewriteIlistPerm3Cert_list H c.\n    Proof.\n      induction n as [|n IH]. \n      - destruct c; reflexivity.\n      - destruct c as [[i1 i2] c]. cbn.\n        f_equal ; try f_equal ; try treatFinPure.\n        apply IH.\n    Qed.\n\n    Lemma rewriteIlistPerm3Cert_list_proofirr: forall (n1 n2: nat)(e1 e2: n1 = n2)\n      (f: IlistPerm3Cert_list n1), rewriteIlistPerm3Cert_list e1 f = rewriteIlistPerm3Cert_list e2 f.\n    Proof.\n      induction n1 as [|n1 IH]; intros [|n2] e1 e2 f.\n      - reflexivity.\n      - inversion e1.\n      - inversion e1.\n      - destruct f as [[i1 i2] f].\n        cbn.\n        f_equal.\n        f_equal ; treatFinPure.\n        apply IH.\n    Qed.\n    \n    Lemma rewriteIlistPerm3Cert_list_sym: forall (n1 n2: nat)(e: n1 = n2)(f: IlistPerm3Cert_list n2),\n      rewriteIlistPerm3Cert_list e (rewriteIlistPerm3Cert_list (sym_eq e) f) = f.\n    Proof.\n      induction n1 as [|n1 IH]; intros [|n2] e f.\n      - destruct f.\n        reflexivity.\n      - inversion e.\n      - inversion e.\n      - destruct f as [[i1 i2] f].\n        simpl.\n        f_equal.\n        f_equal ; treatFinPure.\n        rewrite (rewriteIlistPerm3Cert_list_proofirr _ (eq_sym (eq_add_S _ _ e))).\n        apply IH.\n    Qed.\n\n    Lemma IlistPerm3Cert_aux3_ok1(A: Set)(n: nat)(l1 l2: ilistn A (S n))(Hyp : lgti (mkilist l1) = lgti (mkilist l2))\n      (i1: Fin (lgti (mkilist l1)))(i2 : Fin (lgti (mkilist l2)))\n      (c: IlistPerm3Cert_list (lgti (extroduce (mkilist l1) i1))):\n      IlistPerm3Cert_aux3 (mkilist l1) (mkilist l2) Hyp i1 i2 c = \n      (((i1, i2: Fin (lgti (mkilist l1))), rewriteIlistPerm3Cert_list (sym_eq (extroduce_lgti_S l1 i1)) c)).\n    Proof.\n      cbn.\n      repeat f_equal.\n      apply decode_Fin_unique, sym_eq, decode_Fin_match.\n    Qed.\n    \n    Lemma IlistPerm3Cert_aux3_proofirr(T: Set)(l1 l2: ilist T)(H1 H2: lgti l1 = lgti l2)\n      (i1 : Fin (lgti l1))(i2 : Fin (lgti l2)) (c: IlistPerm3Cert_list (lgti (extroduce l1 i1))): \n      IlistPerm3Cert_aux3 l1 l2 H1 i1 i2 c = IlistPerm3Cert_aux3 l1 l2 H2 i1 i2 c.\n    Proof.\n      destruct l1 as [n1 l1] ; destruct l2 as [n2 l2].\n      cbn in H1, H2, i1, i2.\n      revert l2 H2 i2 c ; rewrite <- H1 ; clear n2 H1 ; intros l2 H2 i2 c.\n      destruct n1 as [|n1].\n      - inversion i1.\n      - cbn.\n        do 2 f_equal.\n        treatFinPure.\n    Qed.\n\n    Inductive IlistPerm3Cert (A: Set)(RA: relation A)(l1 l2: ilist A)(Hyp: lgti l1 = lgti l2)\n      (c: IlistPerm3Cert_list(lgti l1)): Prop :=\n      IlistPerm3Cert_nil: lgti l1 = 0 -> IlistPerm3Cert RA l1 l2 Hyp c\n    | IlistPerm3Cert_cons: \n        forall (i1: Fin(lgti l1))(i2: Fin(lgti l2))(c': IlistPerm3Cert_list (lgti (extroduce l1 i1))), \n        RA (fcti l1 i1) (fcti l2 i2) -> \n        c = IlistPerm3Cert_aux3 l1 l2 Hyp i1 i2 c'->\n        IlistPerm3Cert  RA (extroduce l1 i1) (extroduce l2 i2) (IlistPerm3Cert_aux2 l1 l2 Hyp i1 i2) c'-> \n        IlistPerm3Cert  RA l1 l2 Hyp c.\n    \n    Lemma IlistPerm3Cert_IlistPerm3 (A: Set)(RA: relation A)(i1 i2: ilist A)(Hyp: lgti i1 = lgti i2)\n      (f: IlistPerm3Cert_list(lgti i1)): IlistPerm3Cert RA i1 i2 Hyp f -> IlistPerm3 RA i1 i2.\n    Proof.\n      intro H.\n      induction H.\n      - apply IlistPerm3_nil; assumption.\n      - apply (IlistPerm3_cons _ _ i1 i2); assumption.\n    Qed.\n\n    Lemma IlistPerm3_IlistPerm3Cert (A: Set)(RA: relation A)(i1 i2: ilist A)(Hyp: lgti i1 = lgti i2): \n      IlistPerm3 RA i1 i2 -> exists f: IlistPerm3Cert_list(lgti i1), IlistPerm3Cert RA i1 i2 Hyp f.\n    Proof.\n      intro H.\n      induction H as [l1 l2 H1 H2 |l1 l2 i1 i2 H1 H2 IH ].\n      - exists (rewriteIlistPerm3Cert_list (sym_eq H2) tt).\n        apply IlistPerm3Cert_nil.\n        assumption.\n      - destruct (IH (IlistPerm3Cert_aux2 l1 l2 Hyp i1 i2)) as [c Hypf].\n        exists (IlistPerm3Cert_aux3 l1 l2 Hyp i1 i2 c).\n        apply (@IlistPerm3Cert_cons _ _ _ _  _ _  _ i2 c H1 (refl_equal _) Hypf).\n    Qed.\n\n    Lemma IlistPerm3Cert_mon (A: Set)(RA1 RA2: relation A)(HypR: subrelation RA1 RA2)(i1 i2: ilist A)\n      (Hyp: lgti i1 = lgti i2)(f: IlistPerm3Cert_list(lgti i1)):\n      IlistPerm3Cert RA1 i1 i2 Hyp f -> IlistPerm3Cert RA2 i1 i2 Hyp f.\n    Proof.\n      intro H.\n      induction H.\n      - apply IlistPerm3Cert_nil, H.\n      - apply (@IlistPerm3Cert_cons _ _ _ _ _ _ _ i2 c') ; try assumption.\n        apply HypR, H.\n    Qed.\n\n    Lemma IlistPerm3Cert_proofirr(T: Set)(R: relation T)(l1 l2: ilist T)(H1 H2: lgti l1 = lgti l2)\n      (c: IlistPerm3Cert_list(lgti l1)): IlistPerm3Cert R l1 l2 H1 c -> IlistPerm3Cert R l1 l2 H2 c.\n    Proof.\n      intros H3.\n      induction H3 as [l1 l2 H1 c H3 |l1 l2 H1 c i1 i2 c' H3 H4 _ IH].\n      - apply IlistPerm3Cert_nil, H3.\n      - apply (@IlistPerm3Cert_cons _ _ _ _ _ _ i1 i2 c' H3).\n        + rewrite H4.\n          apply IlistPerm3Cert_aux3_proofirr.\n        + apply IH.\n    Qed.\n\n    Lemma IlistPerm3Cert_inter (A: Set)(l1 l2: ilist A)(Hyp: lgti l1 = lgti l2)\n      (c: IlistPerm3Cert_list(lgti l1))(I: Type)(R: I -> relation A)\n      (HypR: forall i:I, IlistPerm3Cert (R i) l1 l2 Hyp c):\n      IlistPerm3Cert (fun a1 a2 => forall i, R i a1 a2) l1 l2 Hyp c.\n    Proof.\n      destruct l1 as [n1 l1] ; destruct l2 as [n2 l2]. \n      cbn in Hyp.\n      revert l2 c HypR ; rewrite <- Hyp ; intros l2 c H1.\n      cbn in *|-*.\n      fold (mkilist l1) (mkilist l2) in *|-*.\n      clear Hyp n2.\n      induction n1 as [|n1 IH].\n      - apply IlistPerm3Cert_nil.\n        reflexivity.\n      - destruct c as [[i1 i2] c] ; fold (IlistPerm3Cert_list n1) in c.\n        apply (@IlistPerm3Cert_cons _ _ _ _ _ _ (i1: Fin (lgti (mkilist l1))) \n          (i2: Fin (lgti (mkilist l2))) (rewriteIlistPerm3Cert_list (extroduce_lgti_S _ _) c)).\n        + intros i.\n          destruct (H1 i) as [H | i1' i2' c'' H5 H6 H7].\n          * inversion H.\n          * cbn in H6.\n            inversion H6.\n            assumption.\n        + cbn.\n          rewrite (rewriteIlistPerm3Cert_list_proofirr _ (eq_sym (eq_sym (extroduce_lgti_S l1 i1)))), \n          rewriteIlistPerm3Cert_list_sym.\n          reflexivity.\n        + set (l1' := extroduce (mkilist l1) i1).\n          set (l2' := extroduce (mkilist l2) i2).\n          assert(H4 := extroduce_lgti_S l1 i1 : n1 = lgti l1').\n          rewrite (rewriteIlistPerm3Cert_list_proofirr _ H4).\n          assert (H5 := IlistPerm3Cert_aux2 (mkilist l1) (mkilist l2) (eq_refl (S n1)) i1 i2 : \n            lgti l1' = lgti l2').\n          apply (@IlistPerm3Cert_proofirr _ _ _ _ H5 _ (rewriteIlistPerm3Cert_list H4 c)).\n          assert (H2 := refl_equal _ : l1' = extroduce (mkilist l1) i1) ;\n            assert (H3 := refl_equal _ : l2' = extroduce (mkilist l2) i2).\n          destruct l1' as [n1' l1'] ; destruct l2' as [n2' l2'].\n          cbn in H4, H5.\n          revert l1' l2' H2 H3 ; rewrite <- H5, <- H4 ; clear n1' n2' H4 H5 ; intros l1' l2' H2 H3.\n          fold (mkilist l1') (mkilist l2') in *|-*.\n          apply IH ; clear IH.\n          rewrite <- IlistPerm3Cert_list_eq.\n          intros i.\n          destruct (H1 i) as [H4 | i1' i2' c'' _ H4 H5].\n          * inversion H4.\n          * cbn in H4.\n            inversion H4.\n            revert H2 H3 ; rewrite H0, H6 ; intros H2 H3 ; clear i1 i2 H1 H0 H4 H6 H7 c.\n            assert (H6 := eq_sym (extroduce_lgti_S l1 i1')).\n            rewrite (rewriteIlistPerm3Cert_list_proofirr _ H6).\n            assert (H7 := IlistPerm3Cert_aux2 (mkilist l1) (mkilist l2) (eq_refl (S n1)) i1' i2').\n            apply (IlistPerm3Cert_proofirr H7) in H5.\n            revert H5.\n            revert H6 H7 c''.\n            rewrite <- H2, <- H3.\n            simpl.\n            intros H6 H7 c''.\n            rewrite <- IlistPerm3Cert_list_eq.\n            apply IlistPerm3Cert_proofirr.\n    Qed.\n    \n    Definition IlistPerm3Cert_list_function (n: nat)(c: IlistPerm3Cert_list n) : Fin n -> Fin n.\n    Proof.\n      induction n as [|n IH] ; intro i.\n      - inversion i.\n      - destruct c as [[i1 i2] c].\n        fold (IlistPerm3Cert_list n) in c.\n        elim (eq_nat_dec (decode_Fin i1) (decode_Fin i)); intros a.\n        + exact i2.\n        + exact (extroduce_Fin i2 (IH c (index_in_extroduce _ _ a))).\n    Defined.\n\n    Definition IlistPerm3Cert_list_inv (n: nat)(c: IlistPerm3Cert_list n) : IlistPerm3Cert_list n.\n    Proof.\n      induction n as [|n IH].\n      - apply c.\n      - destruct c as [[i1 i2] c].\n        exact ((i2, i1), (IH c)).\n    Defined.\n\n    Definition IlistPerm3Cert_list_function_inv (n: nat)(c: IlistPerm3Cert_list n):= \n      IlistPerm3Cert_list_function (IlistPerm3Cert_list_inv _ c).\n      \n    Lemma IlistPerm3Cert_list_inv_inv_id (n: nat)(c: IlistPerm3Cert_list n) : \n      IlistPerm3Cert_list_inv _ (IlistPerm3Cert_list_inv _ c) = c.\n    Proof.\n      induction n as [|n IH].\n      - reflexivity.\n      - destruct c as [[i1 i2] c].\n        cbn.\n        rewrite IH ; reflexivity.\n    Qed.\n\n    Lemma IP3Cl_function_ok1 (n: nat)(i1 i2 : Fin (S n))(c: IlistPerm3Cert_list n)(i: Fin (S n)) : \n      decode_Fin i1 = decode_Fin i -> IlistPerm3Cert_list_function (((i1, i2), c): IlistPerm3Cert_list (S n)) i = i2.\n    Proof.\n      intros H.\n      rewrite (decode_Fin_unique _ _ H).\n      cbn.\n      unfold sumbool_rec, sumbool_rect.\n      elim (eq_nat_dec (decode_Fin i) (decode_Fin i)) ; intros a.\n      - reflexivity.\n      - apply False_rec, a, eq_refl.\n    Qed.\n\n    Lemma IP3Cl_function_ok2 (n: nat)(i1 i2 : Fin (S n))(c: IlistPerm3Cert_list n)(i: Fin (S n))\n      (h: decode_Fin i1 <> decode_Fin i) : \n      decode_Fin i2 <= decode_Fin (IlistPerm3Cert_list_function c (index_in_extroduce _ _ h)) -> \n      IlistPerm3Cert_list_function (((i1, i2), c): IlistPerm3Cert_list (S n)) i = \n      succ (IlistPerm3Cert_list_function c (index_in_extroduce _ _ h)).\n    Proof.\n      intros H.\n      cbn.\n      unfold sumbool_rec, sumbool_rect.\n      elim (eq_nat_dec (decode_Fin i1) (decode_Fin i)) ; intros a.\n      - contradiction a.\n      - rewrite (index_in_extroduce_proofirr _ _ a h).\n        apply extroduce_Fin_ok1.\n        assumption.\n    Qed.\n    \n    Lemma IP3Cl_function_ok3 (n: nat)(i1 i2 : Fin (S n))(c: IlistPerm3Cert_list n)(i: Fin (S n))\n      (h: decode_Fin i1 <> decode_Fin i) : \n      decode_Fin (IlistPerm3Cert_list_function c (index_in_extroduce _ _ h)) < decode_Fin i2 -> \n      IlistPerm3Cert_list_function (((i1, i2), c): IlistPerm3Cert_list (S n)) i = \n        weakFin (IlistPerm3Cert_list_function c (index_in_extroduce _ _ h)).\n    Proof.\n      intros H.\n      cbn.\n      unfold sumbool_rec, sumbool_rect.\n      elim (eq_nat_dec (decode_Fin i1) (decode_Fin i)) ; intros a.\n      - contradiction a.\n      - rewrite (index_in_extroduce_proofirr _ _ a h).\n        apply extroduce_Fin_ok2.\n        assumption.\n    Qed.\n\n    Lemma IP3Cl_function_ok4 (n: nat)(i1 i2 : Fin (S n))(c: IlistPerm3Cert_list n)(i: Fin (S n))\n      (h: decode_Fin i1 <> decode_Fin i) : \n      IlistPerm3Cert_list_function (((i1, i2), c): IlistPerm3Cert_list (S n)) i = \n      extroduce_Fin i2 (IlistPerm3Cert_list_function c (index_in_extroduce _ _ h)).\n    Proof.\n      cbn.\n      unfold sumbool_rec, sumbool_rect.\n      elim (eq_nat_dec (decode_Fin i1) (decode_Fin i)) ; intros a.\n      - contradiction a.\n      - rewrite (index_in_extroduce_proofirr _ _ a h).\n        reflexivity.\n    Qed.\n\n    Lemma IP3Cl_function_function_inv_inv (n: nat)(c: IlistPerm3Cert_list n) : \n      forall i, (IlistPerm3Cert_list_function c) (IlistPerm3Cert_list_function_inv c i) = i.\n    Proof.\n      intros i ; induction n as [|n IH].\n      { inversion i. }      \n      destruct c as [[i1 i2] c].\n      fold (IlistPerm3Cert_list n) in c.\n      unfold IlistPerm3Cert_list_function_inv.\n      change (IlistPerm3Cert_list_inv (S n) (i1, i2, c)) with ((i2, i1, (IlistPerm3Cert_list_inv n c))).\n      elim (eq_nat_dec (decode_Fin i2) (decode_Fin i)) ; intros a.\n      - rewrite (IP3Cl_function_ok1 i2 i1 _ i) ; try assumption.\n        rewrite IP3Cl_function_ok1 ; try reflexivity.\n        apply decode_Fin_unique, a.\n      - elim (le_lt_dec (decode_Fin i1) \n        (decode_Fin (IlistPerm3Cert_list_function (IlistPerm3Cert_list_inv n c) (index_in_extroduce i2 i a)))); intros b.\n        + rewrite (IP3Cl_function_ok2 _ _ _ _ a b).\n          assert (h : decode_Fin i1 <> (decode_Fin (succ\n          (IlistPerm3Cert_list_function (IlistPerm3Cert_list_inv n c) (index_in_extroduce i2 i a))))).\n          * intros h.\n            rewrite h in b.\n            apply (le_Sn_n _ b).\n          * apply le_lt_n_Sm in b.\n            change (S (decode_Fin _)) with (decode_Fin (succ  (IlistPerm3Cert_list_function (IlistPerm3Cert_list_inv n c)\n        (index_in_extroduce i2 i a)))) in b.\n            fold (IlistPerm3Cert_list_function_inv c) in *|-*.\n            elim (le_lt_dec (decode_Fin i2) (decode_Fin (IlistPerm3Cert_list_function c (index_in_extroduce _ _ h)))); \n      intros d.\n            -- rewrite (IP3Cl_function_ok2 _ _ _ _ h) ; try assumption.\n               revert d.\n               rewrite index_in_extroduce_succ2 ; try assumption.\n               rewrite IH.\n               intros d.\n               apply index_in_extroduce_succ ; try assumption.\n            -- rewrite (IP3Cl_function_ok3 _ _ _ _ h) ; try assumption.\n               revert d.\n               rewrite index_in_extroduce_succ2 ; try assumption.\n               rewrite IH.\n               intros d.\n               apply index_in_extroduce_weakFin2 ; try assumption.\n        + rewrite (IP3Cl_function_ok3 _ _ _ _ a b).\n          rewrite <- weakFin_ok in b.\n          assert (h : decode_Fin i1 <> (decode_Fin (weakFin\n            (IlistPerm3Cert_list_function (IlistPerm3Cert_list_inv n c) (index_in_extroduce i2 i a))))).\n          { intros h.\n            rewrite h in b.\n            apply (le_Sn_n _ b). }      \n          fold (IlistPerm3Cert_list_function_inv c) in *|-*.\n          elim (le_lt_dec (decode_Fin i2) (decode_Fin (IlistPerm3Cert_list_function c (index_in_extroduce _ _ h)))); \n      intros d.\n          * rewrite (IP3Cl_function_ok2 _ _ _ _ h) ; try assumption.\n            revert d.\n            rewrite index_in_extroduce_weakFin ; try assumption.\n            rewrite IH.\n            intros d.\n            apply index_in_extroduce_succ ; try assumption.\n          * rewrite (IP3Cl_function_ok3 _ _ _ _ h) ; try assumption.\n            revert d.\n            rewrite index_in_extroduce_weakFin ; try assumption.\n            rewrite IH.\n            intros d.\n            apply index_in_extroduce_weakFin2 ; try assumption.\n    Qed.\n\n    Lemma IP3Cl_function_inv_function_inv (n: nat)(c: IlistPerm3Cert_list n) : \n      forall i, (IlistPerm3Cert_list_function_inv c) (IlistPerm3Cert_list_function c i) = i.\n    Proof.\n      unfold IlistPerm3Cert_list_function_inv.\n      rewrite <- (IlistPerm3Cert_list_inv_inv_id _ c), IlistPerm3Cert_list_inv_inv_id.\n      apply IP3Cl_function_function_inv_inv.\n    Qed.\n\n\n    Lemma IlistPerm3Cert_list_function_ok_n (T: Set)(R: relation T)(n: nat)(l1 l2 : ilistn T n)\n      (c: IlistPerm3Cert_list n)(h: n = n): IlistPerm3Cert R (mkilist l1) (mkilist l2) h c -> \n      forall i, R (l1 i) (l2 (IlistPerm3Cert_list_function c i)).\n    Proof.\n      intros h1 i.\n      induction n as [|n IH].\n      {inversion i. }\n      destruct h1 as [h1 |i1 i2 c' h1 h2 h3].\n      - inversion h1.\n      - cbn in i1, i2, h1.\n        rewrite h2.\n        rewrite IlistPerm3Cert_aux3_ok1.\n        elim (eq_nat_dec (decode_Fin i1) (decode_Fin i)) ; intros a.\n        + rewrite IP3Cl_function_ok1 ; try assumption.\n          rewrite <- (decode_Fin_unique _ _ a).\n          assumption.\n        + rewrite (IP3Cl_function_ok4 _ _ _ _ a).\n          set (i2' := IlistPerm3Cert_list_function (rewriteIlistPerm3Cert_list (eq_sym (extroduce_lgti_S l1 i1)) c') \n            (index_in_extroduce _ _ a)).\n          change (R (l1 i) (l2 (extroduce_Fin i2 i2'))).\n          assert (h4 : decode_Fin i2 <> decode_Fin (extroduce_Fin i2 i2')).\n          { intro H.\n            apply decode_Fin_unique, sym_eq in H.\n            apply (extroduce_Fin_not_fex _ H). }\n          rewrite (index_in_extroduce_ok_cor l1 _ _ a), (index_in_extroduce_ok_cor l2 _ _ h4).\n          clear h2.\n          rewrite index_in_from_extroduce.\n          revert c' h3 i2' h4.\n          set (h3' := IlistPerm3Cert_aux2 (mkilist l1) (mkilist l2) h i1 i2).\n          set (h5 := extroduce_lgti_S l1 i1) ; set (h6 := extroduce_lgti_S l2 i2).\n          generalize h3' h5 h6 ; clear h3' h5 h6.\n          set (l1' := extroduce (mkilist l1) i1) ; set (l2' := extroduce (mkilist l2) i2) ;\n            assert (h7 := refl_equal _ : extroduce (mkilist l1) i1 = l1') ; \n            assert (h8 := refl_equal _ : l2' = extroduce (mkilist l2) i2).\n          destruct l1' as [n1' l1'] ; destruct l2' as [n2' l2'].\n          simpl lgti.\n          intros h3' h5 h6; revert h3' l1' l2' h7 h8.\n          rewrite <- h5, <- h6.\n          clear n1' n2' h5 h6.\n          intros h3' l1' l2' h5 h6 c' h3.\n          fold (mkilist l1') (mkilist l2') in *|-*.\n          rewrite <- IlistPerm3Cert_list_eq.\n          intros i2' h4.\n          do 2 rewrite <- (decode_Fin_unique _ _ (decode_Fin_match' _ _)).\n          apply (IH _ _ _ h3'), h3.\n    Qed.\n\n    Lemma IlistPerm3Cert_list_function_ok (T: Set)(R: relation T)(l1 l2 : ilist T)(c: IlistPerm3Cert_list (lgti l1)) \n      (h: lgti l1 = lgti l2): IlistPerm3Cert R l1 l2 h c -> \n      forall i, R (fcti l1 i) (fcti l2 (rewriteFins h (IlistPerm3Cert_list_function c i))).\n    Proof.\n      intros h1 i.\n      destruct l1 as [n l1] ; destruct l2 as [n2 l2] ; cbn in *|-*.\n      revert l2 h1 ; rewrite <- h ; intros l2 h1 ; clear n2 h.\n      rewrite <- (decode_Fin_unique _ _ (decode_Fin_match' _ _)).\n      apply (IlistPerm3Cert_list_function_ok_n h1).\n    Qed.\n \n    Lemma IlistPerm3Cert_list_function_ok_cor (T: Set)(R: relation T)(n: nat)(l1 l2 : ilistn T n) \n      (c: IlistPerm3Cert_list n): IlistPerm3Cert R (mkilist l1) (mkilist l2) (eq_refl n) c -> \n      forall i, R (l1 i) (l2 (IlistPerm3Cert_list_function c i)).\n    Proof.\n      intros h1 i.\n      assert (h3 : IlistPerm3Cert_list_function c i = rewriteFins \n        (eq_refl _ : lgti (mkilist l1) = lgti (mkilist l2)) (IlistPerm3Cert_list_function c i)).\n      { treatFinPure. }\n      rewrite h3.\n      apply (IlistPerm3Cert_list_function_ok h1).\n    Qed.\n\n    End IlistPerm3_cert.\n  \nEnd IlistPerm_ind.\n\nSection IlistPerm_bij.\n   Inductive IlistPerm7 (T: Set)(R: relation T)(l1 l2 : ilist T): Prop := \n     perm7 : forall f g, Bijective f g -> (forall i, R (fcti l1 i) (fcti l2 (f i))) -> IlistPerm7 R l1 l2.\n\n   Lemma IlistPerm7_refl (T: Set)(R: relation T)(Rrefl: Reflexive R)(l : ilist T) : IlistPerm7 R l l.\n   Proof.\n     apply (@perm7 _ R l l (fun x => x) (fun x => x)) ; try split ; reflexivity.\n   Qed.\n\n   Lemma IlistPerm7_sym (T: Set)(R: relation T)(Rsym: Symmetric R)(l1 l2 : ilist T) : \n     IlistPerm7 R l1 l2 -> IlistPerm7 R l2 l1.\n   Proof.\n     intros [f g h1 h2].\n     apply (perm7 R _ _ (Bij_sym h1)).\n     intro i.\n     assert (h3 := h2 (g i)).\n     destruct h1 as [h4 h5].\n     rewrite (h5 _) in h3.\n     apply Rsym, h3.\n   Qed.\n   \n   Lemma IlistPerm7_trans (T: Set)(R: relation T)(Rrefl: Transitive R)(l1 l2 l3: ilist T) : \n     IlistPerm7 R l1 l2 -> IlistPerm7 R l2 l3 -> IlistPerm7 R l1 l3.\n   Proof.\n     intros [f1 g1 h1 h2] [f2 g2 h3 h4].\n     apply (perm7  _ _ _ (Bij_trans h1 h3)).\n     intro i.\n     transitivity (fcti l2 (f1 i)).\n     - apply h2.\n     - apply h4.\n   Qed.\n\n   Add Parametric Relation (T: Set)(RelT: relation T)(EqT: Equivalence RelT) : (ilist T)(IlistPerm7 RelT) \n     reflexivity proved by (IlistPerm7_refl _)\n     symmetry proved by (IlistPerm7_sym _)\n     transitivity proved by (IlistPerm7_trans _)\n   as IlistPerm7Rel.\n\n   Lemma IlistPerm7_mon (U: Set)(l1 l2 : ilist U)(R1 R2 : relation U) :\n     subrelation R1 R2 -> IlistPerm7 R1 l1 l2 -> IlistPerm7 R2 l1 l2.\n   Proof.\n     intros h1 [f g h2 h3].\n     apply (perm7 R2 _ _ h2).\n     intros i.\n     apply (h1 _ _ (h3 i)).\n   Qed.\n\n   Lemma IlistPerm7_lgti (T: Set)(R: relation T)(l1 l2 : ilist T) : IlistPerm7 R l1 l2 -> lgti l1 = lgti l2.\n   Proof.\n     intros [f g h _].\n     apply (Fin_inj_aux h).\n   Qed.\n\n   Lemma Bijective_IP3Cl_function (n: nat)(c: IlistPerm3Cert_list n) : \n     Bijective (IlistPerm3Cert_list_function c) (IlistPerm3Cert_list_function_inv c).\n   Proof.\n     split.\n     - apply IP3Cl_function_inv_function_inv.\n     - apply IP3Cl_function_function_inv_inv.\n   Qed.\n\n   Lemma IlistPerm3_IlistPerm7 (T: Set)(R: relation T)(l1 l2 : ilist T) : \n     IlistPerm3 R l1 l2 -> IlistPerm7 R l1 l2.\n   Proof.\n     destruct l1 as [n l1] ; destruct l2 as [n2 l2].\n     intros h1 ; assert (h2 := IlistPerm3_lgti h1) ; cbn in *|-* ; revert l1 l2 h1 ; rewrite <- h2 ; clear n2 h2;\n     intros l1 l2 h1.\n     destruct (IlistPerm3_IlistPerm3Cert (refl_equal _ : lgti (existT _ _ l1) = lgti (existT _ _ l2)) h1) as [c h2].\n     fold (mkilist l1) (mkilist l2) in *|-*.\n     apply (perm7 R (mkilist l1) (mkilist l2) (Bijective_IP3Cl_function _ c)).\n     apply IlistPerm3Cert_list_function_ok_cor, h2.\n   Qed.\n   \n   Lemma IlistPerm7_IlistPerm3 (T: Set)(R: relation T)(l1 l2 : ilist T) : \n     IlistPerm7 R l1 l2 -> IlistPerm3 R l1 l2.\n   Proof.\n     intros h1 ; assert (h := IlistPerm7_lgti h1).\n     destruct l1 as [n l1] ; destruct l2 as [n2 l2] ; cbn in *|-* ; revert l1 l2 h1 ; rewrite <- h ;\n     intros l1 l2 [f g [h1 h2] h3]; clear n2 h ; cbn in *|-*.\n     induction n as [|n IH].\n     { apply IlistPerm3_nil ; reflexivity. }\n     apply (IlistPerm3_cons _ _ (first n : Fin (lgti (existT _ _ l1))) (f (first n) :  Fin (lgti (existT _ _ l2)))).\n     { apply h3. }     \n     assert (hex1_aux := extroduce_lgti (existT _ _ l1) (first n)).\n     assert (hex1 : forall i, fcti (extroduce (existT _ _ l1) (first n)) i = fcti (existT _ _ l1)\n         (rewriteFins (eq_sym hex1_aux) (succ i))).\n     { intro i.\n       rewrite extroduce_ok3'.\n       - f_equal.\n         treatFinPure.\n       - apply le_0_n.\n     }     \n     assert (hex2_aux := extroduce_lgti (existT _ _ l2) (f (first n))).\n     assert (hex21 : forall i, decode_Fin i < decode_Fin (f (first n)) -> \n         fcti (extroduce (existT _ _ l2) (f (first n))) i = \n         fcti (existT _ _ l2) (rewriteFins (eq_sym hex2_aux) (weakFin i))).\n     { intros i h4.\n       rewrite extroduce_ok2' ; try assumption.\n       f_equal.\n       treatFinPure. }     \n     assert (hex22 : forall i, decode_Fin (f (first n)) <=  decode_Fin i -> \n         fcti (extroduce (existT _ _ l2) (f (first n))) i = \n         fcti (existT _ _ l2) (rewriteFins (eq_sym hex2_aux) (succ i))).\n     { intros i h4.\n       rewrite extroduce_ok3' ; try assumption.\n       f_equal.\n       treatFinPure. }     \n     revert hex1_aux hex1 hex2_aux hex21 hex22.\n     set (l1' := extroduce (existT _ _ l1) (first n)) ; set (l2' := extroduce (existT _ _ l2) (f (first n))).\n     assert (h4 := refl_equal _ : l1' =  extroduce (existT _ _ l1) (first n)) ; \n       assert (h5 := refl_equal _ : l2' =  extroduce (existT _ _ l2) (f (first n))).\n     destruct l1' as [n' l1'] ; destruct l2' as [n2' l2'].\n     assert (h6 : n' = n2').\n     { change (lgti (existT (fun n : nat => ilistn T n) _ l1') = lgti (existT (fun n : nat => ilistn T n) _ l2')).\n       rewrite h4, h5.\n       apply extroduce_lgti_S. }\n     assert (h7 : n' = n).\n     { change (lgti (existT (fun n : nat => ilistn T n) _ l1') = n).\n       apply eq_add_S.\n       rewrite h4, <- extroduce_lgti.\n       reflexivity. }\n     revert l1' l2' h4 h5 ; rewrite <- h6, h7 ; intros l1' l2' h4 h5.\n     cbn.\n     intros hex1_aux hex1 hex2_aux hex21 hex22; \n       clear n' n2' h6 h7.\n     assert (hex1' : forall i, l1' i = l1 (succ i)).\n     { intro i.\n       assert (h6 : succ i = rewriteFins (eq_sym hex1_aux) (succ i)) by treatFinPure.\n       rewrite h6 ; apply hex1. }\n     assert (hex21' : forall i, decode_Fin i < decode_Fin (f (first n)) -> l2' i = l2 (weakFin i)).\n     { intros i h6.\n       assert (h7 : weakFin i = rewriteFins (eq_sym hex2_aux) (weakFin i)) by treatFinPure.\n       rewrite h7 ; apply hex21, h6. }\n     assert (hex22' : forall i, decode_Fin (f (first n)) <= decode_Fin i -> l2' i = l2 (succ i)).\n     { intros i h6.\n       assert (h7 : succ i = rewriteFins (eq_sym hex2_aux) (succ i)) by treatFinPure.\n       rewrite h7 ; apply hex22, h6. }\n     clear hex1_aux hex2_aux hex1 hex21 hex22.\n     fold (mkilist l1') (mkilist l2') in *|-*.\n     assert (h6 : forall i, decode_Fin (f (first n)) <> decode_Fin (f (@succ n i))).\n     { intros i h6.\n       apply decode_Fin_unique, (f_equal g) in h6.\n       do 2 rewrite h1 in h6.\n       inversion h6. }\n     set (f' := fun i => index_in_extroduce _ _ (h6 i)).\n     assert (h7 : forall i, decode_Fin (first n) <> decode_Fin (g (extroduce_Fin (f (first n)) i))).\n     { intro i.\n       unfold extroduce_Fin, sumbool_rec, sumbool_rect.\n       elim (le_lt_dec (decode_Fin (f (first n))) (decode_Fin i)) ; intros a h7 ;\n         apply decode_Fin_unique, (f_equal f) in h7 ; rewrite h2 in h7 ; rewrite h7 in a.\n       - apply (le_Sn_n _ a).\n       - rewrite weakFin_ok in a.\n         apply (lt_irrefl _ a).\n     }\n     set (g' := fun i => index_in_extroduce _ _ (h7 i)).\n     apply (IH _ _ f' g') ; intros i; unfold f', g' ; clear f' g'.\n     - assert (h8 : decode_Fin (first n) < decode_Fin (g (extroduce_Fin (f (first n))\n         (index_in_extroduce (f (first n)) (f (succ i)) (h6 i))))).\n       { rewrite (index_from_in_extroduce _ _ (h6 i)), h1. \n         apply lt_0_Sn. }\n       apply decode_Fin_unique, eq_add_S.\n       rewrite index_in_extroduce_decode1, (index_from_in_extroduce _ _ (h6 i)), h1 ; try assumption.\n       reflexivity.\n     - elim (lt_eq_lt_dec (decode_Fin (f (first n))) (decode_Fin (f (succ (index_in_extroduce (first n)\n           (g (extroduce_Fin (f (first n)) i)) (h7 i)))))) ; try intros [a|a] ; try intros a ; \n           apply decode_Fin_unique.\n       + apply eq_add_S.\n         rewrite index_in_extroduce_decode1 ; try assumption.\n         elim (lt_eq_lt_dec (decode_Fin (first n)) (decode_Fin (g (extroduce_Fin (f (first n)) i)))) ; \n           try intros [b|b] ; try intros b.\n         * rewrite (decode_Fin_unique _ _ (index_in_extroduce_decode1 _ _ (h7 _) b : decode_Fin (succ _) = _)), h2.\n           elim (le_lt_dec (decode_Fin (f (first n))) (decode_Fin i)) ; intros c.\n           -- rewrite extroduce_Fin_ok1 ; try assumption.\n              reflexivity.\n           -- apply False_rec.\n              rewrite (decode_Fin_unique _ _ (index_in_extroduce_decode1 _ _ (h7 _) b : decode_Fin (succ _) = _)), h2 in a.\n              rewrite extroduce_Fin_ok2, weakFin_ok in a ; try assumption.\n              apply (lt_irrefl _ (lt_trans _ _ _ a c)).\n         * contradiction (h7 i).\n         * inversion b.\n       + apply decode_Fin_unique, (f_equal g) in a.\n         do 2 rewrite h1 in a.\n         inversion a.\n       + rewrite index_in_extroduce_decode2 ; try assumption.\n         revert a ; set (h8 := h7 i) ; generalize h8 ; clear h8.\n         elim (le_lt_dec (decode_Fin (f (first n))) (decode_Fin i)) ; intros b.\n         * rewrite extroduce_Fin_ok1 ; try assumption.\n           intros h8 a.\n           elim (lt_eq_lt_dec (decode_Fin (first n)) (decode_Fin (g (succ i)))) ; try intros [c|c] ; try intros c.\n           -- rewrite (decode_Fin_unique _ _ (index_in_extroduce_decode1 _ _ h8 c : decode_Fin (succ _) = _)), h2 in a.\n              apply False_rec, (le_Sn_n _ (lt_le_weak _ _ (lt_le_trans _ _ _ a b))).\n           -- contradiction c.\n           -- inversion c.\n         * rewrite extroduce_Fin_ok2 ; try assumption.\n           intros h8 a.\n           elim (lt_eq_lt_dec (decode_Fin (first n)) (decode_Fin (g (weakFin i)))) ; try intros [c|c] ; try intros c.\n           -- rewrite (decode_Fin_unique _ _ (index_in_extroduce_decode1 _ _ h8 c : decode_Fin (succ _) = _)), h2.\n              apply weakFin_ok.\n           -- contradiction c.\n           -- inversion c.\n     - set (h8 := h6 i) ; generalize h8 ; clear h8 ; intros h8.\n       rewrite hex1'.\n       assert (h9 : l2' (index_in_extroduce (f (first n)) (f (succ i)) h8) = l2 (f (succ i))).\n       { rewrite (index_in_extroduce_ok_cor l2 _ _ h8).\n         set (h9 := extroduce_lgti_S l2 (f (first n))).\n         generalize h9 ; clear h9.\n         change (mkilist l2' = extroduce (mkilist l2) (f (first n))) in h5.\n         rewrite <- h5.\n         intros h9.\n         cbn.\n         f_equal.\n         treatFinPure.\n       }\n       rewrite h9.\n       apply h3.\n   Qed.\n     \n  End IlistPerm_bij.\n", "meta": {"author": "rmatthes", "repo": "coinductiverepofgraphsceliapicard", "sha": "9d9633d35a3c9b2c5999b86353bc6f98005e8126", "save_path": "github-repos/coq/rmatthes-coinductiverepofgraphsceliapicard", "path": "github-repos/coq/rmatthes-coinductiverepofgraphsceliapicard/coinductiverepofgraphsceliapicard-9d9633d35a3c9b2c5999b86353bc6f98005e8126/IlistPerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7176019515752787}}
{"text": "(**********************  TD n°6  ***************************)\n(* Ce TD porte sur la sémantique naturelle codée en Coq    *)\n(* du petit langage impératif WHILE déjà vu précédemment.  *)\n(* On va l'utiliser pour faire des dérivations, montrer    *)\n(* des propriétés, étudier des extensions.                 *)\n(***********************************************************)\n\n(* On importe les bibliothèques de Coq utiles pour le TD   *)\n\nRequire Import Bool Arith List.\nImport List.ListNotations.\n\n(** * On choisit de définir ici un état comme une liste d'entiers naturels.\n      On utilise ici le type list de la bibliothèque standard de Coq.\n      Ce type est polymorphe. On le spécialise pour des éléments de type nat. *)\n\nCheck list.\nCheck list nat.\n\nPrint list.\n\nCheck 0::1::3::nil.\n\n(* Ici on observe que la notation des listes façon ocaml est gérée par Coq. *)\n\nCheck [0;1;3].\n\nRemark List_Notation: [0;1;3] = 0::1::3::nil.\nProof.\n  reflexivity.\nQed.\n\n(** * On reprend ici les AST définis aux séances précédentes *)\n\n(** ** Syntaxe des expressions arithétiques *)\n\nInductive aexp :=\n| Aco : nat -> aexp (* constantes *)\n| Ava : nat -> aexp (* variables *)\n| Apl : aexp -> aexp -> aexp\n| Amu : aexp -> aexp -> aexp\n| Amo : aexp -> aexp -> aexp\n.\n\n(** ** Syntaxe des expressions booléennes *)\n\nInductive bexp :=\n| Btrue : bexp\n| Bfalse : bexp\n| Bnot : bexp -> bexp\n| Band : bexp -> bexp -> bexp\n| Bor : bexp -> bexp -> bexp\n| Beq : bexp -> bexp -> bexp (* test égalité de bexp *)\n| Beqnat : aexp -> aexp -> bexp (* test égalité d'aexp *)\n.\n\n(** ** Syntaxe du langage impératif WHILE *)\n\nInductive winstr :=\n| Skip   : winstr\n| Assign : nat -> aexp -> winstr\n| Seq    : winstr -> winstr -> winstr\n| If     : bexp -> winstr -> winstr -> winstr\n| While  : bexp -> winstr -> winstr\n.\n\n(** ** Quelques listes/états pour faire des tests *)\n(** Ci-dessous, S1 est un état dans lequel la variable numéro 0\n    vaut 1, la variable numéro 1 vaut 2, et toutes les autres\n    valent 0' (valeur par défaut).                                      *)\n(** Plus généralement, une variable (Ava i) étant représentée par le\n    numéro i, sa valeur dans un état S est la valeur en ieme position\n    de la liste qui représente cet état S. *)\n\nDefinition state := list nat.\n\nDefinition S1 := [1; 2].\nDefinition S2 := [0; 3].\nDefinition S3 := [0; 7; 5; 41].\n\n(** * Sémantique *)\n(** On reprend les sémantiques fonctionnelles\n    des expressions artihmétiques et booléennes      *)\n\n(** La fonction get x s rend la valeur de x dans s. *)\n(** Elle rend 0 par défaut, par exemple si la variable\n    n'est pas définie/initialisée    *)\n\nFixpoint get (x:nat) (s:state) : nat :=\nmatch x,s with\n| 0   , v::_      => v\n| S x1, _::l1 => get x1 l1\n| _   , _         => 0\nend.\n\n(** Exemples *)\n\nCompute (get 0 S3).\nCompute (get 1 S3).\nCompute (get 2 S3).\nCompute (get 3 S3).\nCompute (get 4 S3).\n\n(** La mise à jour d'une variable v par un nouvel entier n dans un état s\n    s'écrit 'update s v n'\n    Cette fonction n'échoue jamais et écrit la valeur à sa place même\n    si elle n'est pas encore définie dans l'état *)\n\nFixpoint update (s:state) (v:nat) (n:nat): state :=\n  match v,s with\n  | 0   , a :: l1 => n :: l1\n  | 0   , nil     => n :: nil\n  | S v1, a :: l1 => a :: (update l1 v1 n)\n  | S v1, nil     => 0 :: (update nil v1 n)\n  end.\n\nDefinition S4 := update (update (update (update (update S1 4 1) 3 2) 2 3) 1 4) 0 5.\n\nCompute S1.\nCompute S4.\n\n(** ** Sémantique fonctionnelle de aexp*)\nFixpoint evalA (a: aexp) (s: state) : nat :=\n  match a with\n  | Aco n => n\n  | Ava x => get x s\n  | Apl a1 a2 =>  evalA a1 s + evalA a2 s\n  | Amu a1 a2 =>  evalA a1 s * evalA a2 s\n  | Amo a1 a2 =>  evalA a1 s - evalA a2 s\n  end.\n\n\n(** ** Sémantique fonctionnelle de Baexp*)\n\nDefinition eqboolb b1 b2 : bool :=\n  match b1, b2  with\n  | true , true  => true\n  | false, false => true\n  | _    , _     => false\n  end.\n\nFixpoint eqnatb n1 n2 : bool :=\n  match n1, n2 with\n  | O    , O     => true\n  | S n1', S n2' => eqnatb n1' n2'\n  | _    , _     => false\n  end.\n\nFixpoint evalB (b : bexp) (s : state) : bool :=\n  match b with\n  | Btrue => true\n  | Bfalse => false\n  | Bnot b => negb (evalB b s)\n  | Band e1 e2 => (evalB e1 s) && (evalB e2 s)\n  | Bor e1 e2 => (evalB e1 s) || (evalB e2 s)\n  | Beq e1 e2 => eqboolb (evalB e1 s) (evalB e2 s)\n  | Beqnat n1 n2 => eqnatb (evalA n1 s) (evalA n2 s)\n  end.\n\n(** Pour définir plus facilement des expressions de test on prédéfinit\n    des constantes entières ... *)\n\nDefinition N0 := Aco 0.\nDefinition N1 := Aco 1.\nDefinition N2 := Aco 2.\nDefinition N3 := Aco 3.\nDefinition N4 := Aco 4.\n\n(** ...  et des variables *)\n\nDefinition X := Ava 1.\nDefinition Y := Ava 2.\nDefinition Z := Ava 3.\n\n\n(** Quelques expressions arithmétiques pour tester *)\n\n(** exp1 = x + 3 *)\nDefinition E1 := Apl X N3.\n\n(** exp2 = y - 1 *)\nDefinition E2 := Amo Y N1.\n\n(** exp3 = (x + y) * 2 *)\nDefinition E3 := Amu (Apl X Y) N2.\n\nCompute (evalA E1 S1).\nCompute (evalA E1 S2).\nCompute (evalA E2 S1).\nCompute (evalA E2 S2).\nCompute (evalA E3 S1).\nCompute (evalA E3 S2).\n\n(** Quelques expressions booléennes pour tester *)\n\n(** B1 :=  exp1 = 4 *)\nDefinition B1 := Beqnat E1 N4.\n\n(** B2 := not ( bexp1 /\\ (exp1 = 7) *)\nDefinition B2 := Bnot (Band B1 (Beqnat X N2)).\n\nCompute (evalB B1 S1).\nCompute (evalB B1 S2).\nCompute (evalB B2 S1).\nCompute (evalB B2 S2).\n\n(** Corrigé du travail effectué en TD5 *)\n\nFail Fixpoint evalW (i : winstr) (s : state) {struct i} : state :=\n  match i with\n  | Skip       => s\n  | Assign x e => update s x (evalA e s)\n  | Seq i1 i2  => let s1 := evalW i1 s in evalW i2 s1\n               (*   (evalW i2 (evalW i1 s) *)\n  | If e i1 i2 => match evalB e s with\n                  | true  => evalW i1 s\n                  | false => evalW i2 s\n                  end\n  | (While e i1) as i => match evalB e s with\n                  | true  =>\n                    let s1 := evalW i1 s in evalW (While e i1) s1\n               (*   let s1 := evalW i1 s in evalW i s1                *)\n                  | false => s\n                  end\n  end.\n\n\n\n(** ** Version relationnelle, appelée \"sémantique naturelle\" *)\n\n(** Vu dans le CM précédent.\n    La sémantique naturelle (ou sémantique opérationnelle à grands pas)\n    du langage WHILE est donnée sous la forme d'un prédicat inductif. *)\n\nInductive SN: winstr -> state -> state -> Prop :=\n| SN_Skip        : forall s,\n                   SN Skip s s\n| SN_Assign      : forall x a s,\n                   SN (Assign x a) s (update s x (evalA a s))\n| SN_Seq         : forall i1 i2 s s1 s2,\n                   SN i1 s s1 -> SN i2 s1 s2 -> SN (Seq i1 i2) s s2\n| SN_If_true     : forall b i1 i2 s s1,\n                   (evalB b s = true)  ->  SN i1 s s1 -> SN (If b i1 i2) s s1\n| SN_If_false    : forall b i1 i2 s s2,\n                   (evalB b s = false) ->  SN i2 s s2 -> SN (If b i1 i2) s s2\n| SN_While_false : forall b i s,\n                   (evalB b s = false) ->  SN (While b i) s s\n| SN_While_true  : forall b i s s1 s2,\n                   (evalB b s = true)  ->  SN i s s1 -> SN (While b i) s1 s2 ->\n                   SN (While b i) s s2\n.\n\n(** On code dans WHILE un programme P1 correspondant à\n    while not (i=0) do {i:=i-1;x:=1+x} *)\nDefinition Il := 0.\nDefinition Ir := Ava Il.\nDefinition Xl := 1.\nDefinition Xr := Ava Xl.\n\nDefinition corps_boucle := Seq (Assign Il (Amo Ir N1)) (Assign Xl (Apl N1 Xr)).\nDefinition P1 := While (Bnot (Beqnat Ir N0)) corps_boucle.\n\n(** On montre que P1 transforme l'état S1 en l'état S2  *)\n\nTheorem reduction1 : SN P1 S1 S2.\n(** Regarder les états courants tout au long de la preuve *)\nProof.\n  cbv [P1]. cbv [S1]. cbv [S2].\n  (** Ou de façon équivalente :\n  unfold P1. unfold S1. unfold S2. *)\n\n  (** Ce but devrait être prouvé par l'une des deux dernières règles de SN,\n      qui portent sur le cas While.\n      On peut deviner laquelle de tête, ou demander de l'aide ainsi : *)\n  Compute (evalB (Bnot (Beqnat Ir N0)) [1; 2]).\n  (** Ce sera donc avec SN_While_true.\n      On peut essayer d'avancer avec 'apply SN_While_true.'  ... mais ça échoue.\n      Ici Coq ne peut pas deviner ce que sera l'état intermédiaire s1. *)\n  Fail apply SN_While_true.\n  (** Une stratégie possible serait d'indiquer directement l'état\n      intermédiaire avec la variante 'apply ... with (s1:= ...)'.\n      Il faut deviner les paramètres corrects ce qui n'est pas toujours facile.\n      Dans notre cas cela serait : *)\n  apply SN_While_true with (s1:=[0;3]).\n  (** On va donc proposer une autre stratégie· *)\n  Undo 1.\n  (** Une première possibilité est avec refine, déjà connu :\n      ici on indique un joker '_' pour chacun des HUIT arguments ;\n      [b], [i], [s] et [s2] se trouvent déterminés par la forme du but,\n      [s1] sera déterminé par la preuve de [SN s i s s1] et ne donne donc\n      pas lieu à un sous-but. Il restera à prouver :\n      [evalB b s = true], [SN i s s1] et [SN (While b i) s1 s2].  *)\n  refine (SN_While_true _ _ _ _ _ _ _ _).\n  (** On obtient le même effet avec la tactique [eapply], plus commode. *)\n  Undo 1.\n  eapply SN_While_true.\n  - reflexivity.\n  - cbv [corps_boucle].\n    (** Un nouvel état intermédiaire est à deviner *)\n    eapply SN_Seq.\n    + apply SN_Assign.\n    (* En appliquant cette règle nous avons fixé la valeur de l'état d'arrivée *)\n    + (* L'état de départ vient du cas précédent ;\n         comme les états sont connus on peut simplifier. *)\n      cbn [evalA Ir Il N1 get minus update].\n      (** Ou, plus rapidement *)\n      Undo 1.\n      cbn.\n      apply SN_Assign.\n  - cbn.\n    (** SN_While_true ou SN_While_false ? *)\n    Compute (evalB (Bnot (Beqnat Ir N0)) [0; 3]).\n    apply SN_While_false.\n    cbn.\n    reflexivity.\nQed.\n\n(** À FAIRE (NIVEAU 1) : présenter reduction1 sous forme d'arbre *)\nDefinition AFAIRE_dessin_reduction1 : unit.\nAdmitted.\n\n(** Une autre présentation de ce script, structurée par accolades.\n    Cela permet de gérer l'indentation autrement\n    (surtout utile quand le corps de boucle s'exécute plusieurs fois. *)\nTheorem reduction1_accolades : SN P1 S1 S2.\nProof.\n  cbv [P1]. cbv [S1]. cbv [S2].\n  eapply SN_While_true.\n  { cbn. reflexivity. }\n  { cbv [corps_boucle].\n    eapply SN_Seq.\n    + apply SN_Assign.\n    + cbn. apply SN_Assign. }\n  cbn.\n  Compute (evalB (Bnot (Beqnat Ir N0)) [0; 3]).\n  apply SN_While_false.\n  cbn. reflexivity.\nQed.\n\n(** Exercice d'entraînement *)\n\nTheorem entrainement_P1 : SN P1 [2; 5] [0; 7].\nProof.\n  eapply SN_While_true.\n  - cbn [evalB]. cbv [Ir Il N0]. cbn [evalA negb eqnatb get]. reflexivity.\n  - eapply SN_Seq.\n    + eapply SN_Assign.\n    + eapply SN_Assign.\n  - cbv [Il Xl Ir N1 Xr]. cbn [update evalA get \"+\" \"-\"].\n    eapply SN_While_true.\n    + reflexivity.\n    + cbv [corps_boucle]. eapply SN_Seq.\n      * eapply SN_Assign.\n      * eapply SN_Assign.\n    + cbv [Il Xl Ir N1 Xr]. cbn [update evalA get \"+\" \"-\"].\n      eapply SN_While_false. reflexivity.\nQed.\n\n(** On veut montrer maintenant que P1 rend toujours un état où\n    i vaut 0 et x voit sa valeur augmenter de la valeur initiale de i. *)\n\n(** Rappel : En Coq les entiers naturels sont définis par un type inductif\n    comprenant les constructeurs O pour zéro et S pour le successeur. *)\n\nPrint nat.\n\n(** Les lemmes suivants de la bibliothèque Coq peuvent être utiles\n    - Lemma minus_n_O : forall n, n = n - 0.\n    - Lemma plus_n_Sm : forall n m, S (n + m) = n + S m. *)\n\nTheorem reduction2 : forall x y, SN P1 [x;y] [0;x+y].\nProof.\n  cbv[P1 Ir Il N1 Xr Xl]; intros x.\n  induction x as [ | x Hrec_x];\n    intros; cbn [evalA];cbn [evalB].\n    - eapply SN_While_false. reflexivity.\n    - eapply SN_While_true.\n      + reflexivity.\n      + eapply SN_Seq.\n        * eapply SN_Assign.\n        * eapply SN_Assign.\n      + cbv [Il Xl Ir N1 Xr]. cbn [evalA update get \"-\" \"+\"].\n        rewrite Nat.sub_0_r. rewrite plus_n_Sm. apply Hrec_x.\n  (** complétez ici NIVEAU 2 *)\nQed.\n\n(** *** Calcul du carré avec des additions *)\n(** On code dans While un programme Pcarre correspondant à\n    while not (i=n) do {i:= 1+i; x:= y+x ; y:= 2+y} *)\n(* (* *déjà définis *)\nDefinition Il := 0.\nDefinition Ir := Ava Il.\nDefinition Xl := 1.\nDefinition Xr := Ava Xl.*)\nDefinition Yl := 2.\nDefinition Yr := Ava Yl.\n\nDefinition incrI := Assign Il (Apl N1 Ir).\nDefinition incrX := Assign Xl (Apl Yr Xr).\nDefinition incrY := Assign Yl (Apl N2 Yr).\nDefinition corps_carre := Seq incrI (Seq incrX incrY).\nDefinition Pcarre_2 := While (Bnot (Beqnat Ir (Aco 2))) corps_carre.\nDefinition Pcarre n := While (Bnot (Beqnat Ir (Aco n))) corps_carre.\n\nTheorem reduction_Pcarre_2 : SN (Pcarre_2) [0;0;1] [2;4;5].\nProof.\n  eapply SN_While_true.\n  { reflexivity. }\n  { cbv [corps_carre]. eapply SN_Seq.\n    { cbv [incrI]. eapply SN_Assign. }\n    { cbv [incrX incrY]. eapply SN_Seq; eapply SN_Assign.\n    }\n  }\n  cbn. eapply SN_While_true.\n  { reflexivity. }\n  { cbv [corps_carre]. eapply SN_Seq.\n    { cbv [incrI]. eapply SN_Assign. }\n    { cbv [incrX incrY]. eapply SN_Seq; eapply SN_Assign. }\n  }\n  cbn.\n  eapply SN_While_false. reflexivity.\nQed.\n\n(** Énoncer et démontrer que Pcarre n permet de calculer le carré de n *)\n(* Complétez ici NIVEAU 4\n   (pas de technique nouvelle, mais demande de la créativité *)\nTheorem reduction_pcarre : forall n, SN (Pcarre n) [0; 0; 1] [n; n * n; 2 * n + 1].\nProof.\n  intro n.\n  induction n.\n  - eapply SN_While_false. cbn. reflexivity.\n  - eapply SN_While_true.\n    * cbn. reflexivity.\n    * cbv. eapply SN_Seq.\n      + eapply SN_Assign.\n      + eapply SN_Seq; cbn; eapply SN_Assign.\n    * cbn. eapply SN_While_true.\n      + \nQed.\n\n\n(** Sur le même modèle, trouver un programme Pcube n'utilisant que des\n    additions, énoncer et démontrer qu'il est correct. *)\n(* Complétez ici NIVEAU 6\n   (pas de technique nouvelle, mais demande de la créativité *)\n\n(* -------------------------------------------------------------------------- *)\n(** ** Preuve par récurrence structurelle dans un prédicat inductif *)\n\n\n(** Transformation simple de programme :\n   -  if true  then X else Y ---> X\n   -  if false then X else Y ---> Y  *)\nFixpoint simpl_test_Btrue_Bfalse (i: winstr) : winstr :=\n  match i with\n  | Skip => Skip\n  | Assign v a => i\n  | Seq w1 w2 => Seq (simpl_test_Btrue_Bfalse w1)\n                     (simpl_test_Btrue_Bfalse w2)\n  | If Btrue i1 i2 => simpl_test_Btrue_Bfalse i1\n  | If Bfalse i1 i2 => simpl_test_Btrue_Bfalse i2\n  | If cond i1 i2 => If cond (simpl_test_Btrue_Bfalse i1) (simpl_test_Btrue_Bfalse i2)\n  | While cond i1 => While cond (simpl_test_Btrue_Bfalse i1)\n  end.\n\n(** Comme indiqué ci-dessus on va procéder par récurrence structurelle sur\n     les arbres de preuve de [SN i s s'] *)\nTheorem simpl_test_Btrue_Bfalse_correct :\n  forall i s s', SN i s s' -> SN (simpl_test_Btrue_Bfalse i) s s'.\nProof.\n  (** On essaie d'abord une récurrence sur i.\n      Même avec prudence, de la façon la plus générale possible\n      (les états [s] et [s'], ainsi que l'hypothèse [SN i s s'] sont\n      introduits APRÈS [induction i]), on verra que les buts ne sont\n      pas comme souhaité *)\n  intro i.\n  induction i as [ | | | | ]; (** sans nommer les composantes pour alléger *)\n    intros s s' sn (** les introductions sont effectuées systématiquement\n                         sur chaque sous-but *).\n  (** On observe que l'hypothèse [sn] devrait entraîner [s = s'],\n      mais on ne l'a pas obtenu directement ;\n      tous les autres sous-buts souffrent de problèmes analogues. *)\n  Undo 2.\n  (** Il est bien plus opportun de raisonner par récurrence sur [sn] car\n      on aura naturellement non seulement la décomposition de [i] mais en plus\n      les contraintes dictées par la définition de SN *)\n  intros i s s' sn.\n  induction sn as  [ (* SN_Skip *) s\n                   | (* SN_Assign *) x s a\n                   | (* SN_Seq *) i1 i2 s s1 s' sn1 hrec_sn1 sn2 hrec_sn2\n                   | (* SN_If_true *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_If_false *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_While_false *) (* complétez ici NIVEAU 1 *)\n                   | (* SN_While_true *) (* complétez ici NIVEAU 1 *)\n                   ]; cbn [simpl_test_Btrue_Bfalse].\n\n (** La preuve qui suit est un peu fastidieuse, on verra plus tard\n     des moyens de la fabriquer plus intelligemment. *)\n (** Certains buts contiendront en une hypothèse se convertissant en\n     [false = true] (plus visible en utilisant [cbn in ...].\n     On pourra se souvenir d'une technique vue auparavant (égalités contagieuses).\n  *)\n(** complétez ici\n     - nombreux sous-buts NIVEAU 2\n     - quelques sous-buts NIVEAU 3, utiliser admit si besoin *)\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** Une autre transformation simple (facultatif, pour l'entraînement)\n  -  if (Bnot b) then X else Y ---> if b then Y else X  *)\n\nFixpoint simpl_test_echange (i: winstr) : winstr.\n  (** complétez ici NIVEAU 1 *)\nAdmitted.\n\nLemma negb_negb : forall b, b = negb (negb b).\nProof.\n  (** complétez ici NIVEAU 1 *)\nAdmitted.\n\nLemma Bnot_negb : forall {B s b}, evalB (Bnot B) s = b -> evalB B s = negb b.\nProof.\n (** complétez ici NIVEAU 1 *)\nAdmitted.\n\n(** Suivre le même principe que pour simpl_test_Btrue_Bfalse_correct. *)\nTheorem simpl_test_echange_correct :\n  forall i s s', SN i s s' -> SN (simpl_test_echange i) s s'.\nProof.\n  (** complétez ici\n     - nombreux sous-buts NIVEAU 2\n     - quelques sous-buts NIVEAU 3, utiliser admit si besoin *)\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** ** Interlude sur l'inversion *)\n\n(** Dans l'exercice qui suit, on aura un but comprenant\n    une hypothèse de la forme [SN i s s2],\n    où [i] est lui-même de la forme [Seq i1 i2]    (1).\n    Sans la condition (1), il serait naturel de procéder par\n    cas sur [i], ce qui donnerait lieu aux 7 cas ;\n    mais avec la condition (1), on voit que seul un cas\n    est pertinent, correpondant à SN_Seq.\n    Cette technique de preuve est dite \"par inversion\".\n    On va se ramener à une situation plus simple au moyen du\n    prédicat auxiliaire suivant, qui isole le cas intéressant de SN.\n *)\n\nInductive SN1_Seq i1 i2 s s2 : Prop :=\n| SN1_Seq_intro : forall s1,\n                  SN i1 s s1 -> SN i2 s1 s2 -> SN1_Seq i1 i2 s s2\n.\n\n(** On peut alors démontrer la conséquence suivante d'une hypothèse\n    respectant la condition (1) ci-dessus *)\n\nLemma inv_Seq' : forall {i1 i2 s s2}, SN (Seq i1 i2) s s2 -> SN1_Seq i1 i2 s s2.\nProof.\n  intros i1 i2 s s2 sn.\n  (** Ici in utilise une tactique magique de Coq. *)\n  inversion sn.\n  (** Puis une autre, pour nettoyer les égalités. *)\n  subst.\n  apply (SN1_Seq_intro _ _ _ _ _ H1 H4).\nQed.\n\n(** Mode d'emploi. Devant ce but :\n\n H18 : SN (Seq i1 i2) s s2\n =========================\n conclusion\n\nAu lieu d'un\n  destruct H18\nqui donne 7 cas, on observe que\n[inv_Seq' H18]   est de type   [SN1_Seq i1 i2 s s2]\net donc on peut de manière plus adéquate utiliser\n  destruct (inv_Seq' H18) as [s1 sn1 sn2]\nqui ne prévoit qu'un cas, celui qui est pertinent.\n*)\n\n(** Voici une preuve par \"petites inversions\" du même théorème,\n    qui n'utilise que les connaissances élémentaires déjà acquises,\n    en particulier un programme à la \"ouf_ouf\" (voir coq3_B_A_BA_ouf.v\n    dans les supports de CM).\n    Il n'est pas indispensable de la comprendre avant de l'utiliser.\n    EXERCICES FACULTATIFS :\n    1) expliquer le fonctionnement cette preuve.\n    2) dans les scripts à suivre, utiliser SN_inv\n       au lieu de inv_Seq\n       (intérêt : cela pourra être généralisé).\n *)\nInductive SN1_trivial (s s1 : state) : Prop := Triv : SN1_trivial s s1.\n\nDefinition dispatch (i: winstr) : state -> state -> Prop :=\n  match i with\n  | Seq i1 i2 => SN1_Seq i1 i2\n  | _ => SN1_trivial\n  end.\n\nDefinition SN_inv {i s s2} (sn : SN i s s2) : dispatch i s s2 :=\n  match sn with\n  | SN_Seq i1 i2 s s1 s2 sn1 sn2 =>\n    SN1_Seq_intro _ _ _ _ s1 sn1 sn2\n  | _ => Triv _ _\n  end.\n\nLemma inv_Seq : forall {i1 i2 s s2}, SN (Seq i1 i2) s s2 -> SN1_Seq i1 i2 s s2.\nProof.\n  intros * sn. apply (SN_inv sn).\nQed.\n\n(** *** Illustration *)\n(** Une autre manière d'exprimer la sémantique de WHILE ;\n    on prouvera que SN et SN' sont équivalentes. *)\nInductive SN': winstr -> state -> state -> Prop :=\n| SN'_Skip        : forall s,\n                    SN' Skip s s\n| SN'_Assign      : forall x a s,\n                    SN' (Assign x a) s (update s x (evalA a s))\n| SN'_Seq         : forall i1 i2 s s1 s2,\n                    SN' i1 s s1 -> SN' i2 s1 s2 -> SN' (Seq i1 i2) s s2\n| SN'_If_true     : forall b i1 i2 s s1,\n                    (evalB b s = true)  ->  SN' i1 s s1 -> SN' (If b i1 i2) s s1\n| SN'_If_false    : forall b i1 i2 s s2,\n                    (evalB b s = false) ->  SN' i2 s s2 -> SN' (If b i1 i2) s s2\n| SN'_While_false : forall b i s,\n                    (evalB b s = false) ->  SN' (While b i) s s\n| SN'_While_true  : forall b i s s1,\n                    (evalB b s = true)  ->  SN' (Seq i (While b i)) s s1 ->\n                    SN' (While b i) s s1\n.\n\n\n(** La direction suivante ne pose pas de nouvelle difficulté *)\nLemma SN_SN' : forall i s s1, SN i s s1 -> SN' i s s1.\nProof.\n  intros i s s1 sn.\n  induction sn as  [ (* SN_Skip *) s\n                   | (* SN_Assign *) x s a\n                   | (* SN_Seq *) i1 i2 s s1 s' sn1 hrec_sn1 sn2 hrec_sn2\n                   | (* SN_If_true *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_If_false *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_While_false *) (* complétez ici NIVEAU 1 *)\n                   | (* SN_While_true *)  (* complétez ici NIVEAU 1 *)\n                   ].\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - (** Le sous-but le plus intéressant, où les formulations diffèrent entre\n        SN' et SN *)\n    apply SN'_While_true.\n    + admit (** complétez ici NIVEAU 1 *).\n    + eapply SN'_Seq.\n      -- admit (** complétez ici NIVEAU 2 *).\n      -- admit (** complétez ici NIVEAU 2 *).\nAdmitted.\n\n(** Pour la réciproque le script est semblable SAUF au dernier sous-but,\n    qui précisément demande une inversion. *)\nLemma SN'_SN : forall i s s1, SN' i s s1 -> SN i s s1.\nProof.\n  intros i s s1 sn'.\n  induction sn' as [ (* SN_Skip *) s\n                   | (* SN_Assign *) x s a\n                   | (* SN_Seq *) i1 i2 s s1 s' sn1 hrec_sn1 sn2 hrec_sn2\n                   | (* SN_If_true *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_If_false *) cond i1 i2 s s' e sn hrec_sn\n                   | (* SN_While_false *) cond i s e\n                   | (* SN_While_true *)\n                     cond i s s' e sn hrec_sn\n                   ].\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - admit (** complétez ici NIVEAU 1 *).\n  - (** NIVEAU 4 *)\n    (** Ici il faut exploiter l'hypothèse\n        hrec_sn : SN (Seq i (While cond i)) s s'\n        On observe que cette hypothèse est de la forme SN (Seq i1 i2) s s'\n        qui est un cas particulier de SN i s s' ;\n        cependant un destruct de hrec_sn oublierait que l'on est\n        dans ce cas particulier *)\n    destruct hrec_sn as [ | | | | | | ].\n    + (** Le but obtenu ici correspond au cas où\n          [Seq i (While cond i)] serait en même temps [Skip]\n          un cas qui est hors propos. *)\n      Undo 1.\n    Undo 1.\n    (** Cela est résolu en utilisant\n        conséquence de hrec_sn indiquée par inv_Seq.\n        Voir le mode d'emploi indiqué ci-dessus.\n     *)\n    destruct (inv_Seq hrec_sn) as [s1 sn1 sn2].\n    (** On termine en utilisant ici SN_While_true *)\n    + eapply SN_While_true.\n      -- apply e.\n      -- apply sn1.\n      -- apply sn2.\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** ** Le langage REPEAT *)\n(** On considère maintenant un langage impératif sans la commande While,\n    mais comportant une autre instruction de boucle\n                       'repeat i until b\n    qui exécute i puis sort si b est vrai, et sinon recommence.\n *)\n\n(** Voici la syntaxe du langage REPEAT\n    (on redéfinit un nouveau type avec de nouveaux constructeurs.    *)\n\nInductive rinstr :=\n| RSkip   : rinstr\n| RAssign : nat -> aexp -> rinstr\n| RSeq    : rinstr -> rinstr -> rinstr\n| RIf     : bexp -> rinstr -> rinstr -> rinstr\n| Repeat  : rinstr -> bexp -> rinstr.\n\n(** Définir la sémantique naturelle du langage REPEAT *)\n\nInductive SNr: rinstr -> state -> state -> Prop :=\n| SNr_Skip        : forall s,\n                    SNr RSkip s s\n| SNr_Assign      : forall x e s,\n                    SNr (RAssign x e) s (update s x (evalA e s))\n| SNr_Seq         : forall i1 i2 s s1 s2,\n                    SNr i1 s s1 -> SNr i2 s1 s2 -> SNr (RSeq i1 i2) s s2\n| SNr_If_true     : forall b i1 i2 s s1,\n                    evalB b s = true -> SNr i1 s s1 -> SNr (RIf b i1 i2) s s1\n| SNr_If_false    : forall b i1 i2 s s2,\n                    evalB b s = false -> SNr i2 s s2 -> SNr (RIf b i1 i2) s s2\n| SNr_Repeat_true : (** complétez ici NIVEAU 2 *)\n| SNr_Repeat_false: (** complétez ici NIVEAU 2 *)\n.\n\n(** On code dans REPEAT un programme P2 correspondant à\n    repeat {i:=i-1;x:=1+x} until i=0 *)\n\nDefinition corps_boucleR : rinstr. Admitted.\nDefinition P2 := Repeat corps_boucleR (Beqnat Ir N0).\n\nLemma P2_test : SNr P2 [2; 5] [0; 7].\nProof.\nAdmitted.\n\n(** À FAIRE : présenter P2_test sous forme d'arbre *)\nDefinition AFAIRE_dessin_P2_test : unit.\nAdmitted.\n\n\n(** *** Preuves sur SNr *)\n(** On va maintenant montrer que : 'Repeat i until b'\n    peut être traduit  par       : 'i; while (not b) do i'     *)\n\n(** Ecrire une fonction qui traduit toute expression rinstr en winstr en\n    remplaçant les Repeat par l'expression équivalente ci-dessus\n *)\n\nFixpoint repeat_while (i:rinstr) : winstr :=\n    match i with\n    | RSkip        => Skip\n    | RAssign v a  => Assign v a\n    | RSeq i1 i2   =>\n      (** complétez ici NIVEAU 2 *)\n    end.\n\n(** Avant d'aborder la preuve suivante, il est recommandé de tester\n    sur un petit programme REPEAT qu'après transformation son exécution\n    à partir d'un état initial concret donne bien le même état final.\n*)\n\n(** Montrer que cette transformation préserve la sémantique c-a-d : *)\n\nTheorem repeat_while_correct : forall i s1 s2, SNr i s1 s2 -> SN (repeat_while i) s1 s2.\nProof.\n  intros i s1 s2 sn.\n            (* complétez ici NIVEAU 3 *)\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** Transformation inverse *)\nFixpoint while_repeat (i:winstr) : rinstr :=\n    match i with\n    | Skip        => RSkip\n    | Assign v a  => RAssign v a\n    | Seq i1 i2   =>\n      (* complétez ici NIVEAU 3 *)\n    end.\n\n(** Avant d'aborder la preuve suivante, il est recommandé de tester\n    sur un petit programme WHILE qu'après transformation son exécution\n    à partir d'un état initial concret donne bien le même état final.\n*)\n\n\n(** Montrer que cette transformation préserve la sémantique *)\n(** La preuve suivante requiert quelques techniques supplémentaires,\n    à considérer seulement après la semaine 7 *)\n\nTheorem while_repeat_correct :\n  forall i s1 s2, SN i s1 s2 -> SNr (while_repeat i) s1 s2.\nProof.\n  intros i s_1 s_2 sn.\n            (** complétez ici NIVEAU 4 *)\nAdmitted.\n\n(* -------------------------------------------------------------------------- *)\n(** ** Le langage WHILE-REPEAT *)\n(** Remarque : on pourrait également considérer un langage WHILE_REPEAT\n    comprenant à la fois l'instruction While et l'instruction Repeat\n *)\n", "meta": {"author": "elegaanz", "repo": "info4-ltpf", "sha": "1c2802dc05157ac781e07147763d35491f7995a6", "save_path": "github-repos/coq/elegaanz-info4-ltpf", "path": "github-repos/coq/elegaanz-info4-ltpf/info4-ltpf-1c2802dc05157ac781e07147763d35491f7995a6/TD06_SN_winstr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7176019301714417}}
{"text": "Require Import Logic.Axiom.Dec.\n\n(* A proposition is weakly decidable                                            *)\nDefinition Wec (A:Prop) : Prop := A \\/ ~A.\n\n\n(* a predicate is weakly decidable                                              *)\nDefinition pWec (a:Type) (p:a -> Prop) : Prop := forall (x:a), Wec (p x).\n\nArguments pWec {a}.\n\n(* Two-fold weakly decidable predicates                                         *)\nDefinition pWec2 (a b:Type) (p:a -> b -> Prop) := \n    forall (x:a) (y:b), Wec (p x y).\n\nArguments pWec2 {a} {b}.\n\nLemma pWec2Wec : forall (a b:Type) (p:a -> b -> Prop) (x:a),\n    pWec2 p -> pWec (p x).\nProof.\n    intros a b p x H1 y. apply H1.\nDefined.\n\nLemma DecWec : forall (A:Prop), Dec A -> Wec A.\nProof.\n    intros A [H1|H1]. \n    - left. assumption.\n    - right. assumption.\nDefined.\n\nLemma pDecWec : forall (a:Type) (p:a -> Prop), pDec p -> pWec p.\nProof.\n    intros a p H1 x. apply DecWec. apply H1.\nDefined.\n\nLemma andWec : forall (A B:Prop), Wec A -> Wec B -> Wec (A /\\ B).\nProof.\n    intros A B [H1|H1] [H2|H2].\n    - left. split; assumption.\n    - right. intros [H3 H4]. apply H2 in H4. contradiction.\n    - right. intros [H3 H4]. apply H1 in H3. contradiction.\n    - right. intros [H3 H4]. apply H1 in H3. contradiction.\nDefined.\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/Logic/Axiom/Wec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7175180241211406}}
{"text": "Require Import Coq.Reals.Reals.\n\nOpen Scope R.\n\nTheorem HamkinsQverheard9thGradeProblem : forall x:R, x > 0 -> (x + (1/x)) >= 2.\nintros.\nunfold Rdiv.\nrewrite Rmult_1_l.\nrewrite <- (Rmult_1_l (x + / x)).\nrewrite <- (Rmult_1_l 2).\nrewrite Rmult_plus_distr_l.\nrewrite <- (Rinv_r x).\nrewrite (Rmult_comm x (/ x)).\nrepeat rewrite (Rmult_assoc (/ x)).\nrewrite <- (Rmult_plus_distr_l (/ x)).\napply Rmult_ge_compat_l.\napply (Rgt_ge _ _ (Rlt_gt _ _ (Rinv_0_lt_compat x (Rlt_gt _ _ H)))).\nrepeat rewrite <- Rinv_r_sym.\nrepeat rewrite <- Rinv_l_sym.\nall: try apply (Rgt_not_eq _ _ H).\nfold (Rsqr x).\nrewrite (Rmult_comm x 2).\napply Rminus_ge.\nrewrite <- Rsqr_1.\nrewrite Rplus_comm.\nrewrite <- (Rmult_1_r x) at 2.\nrewrite (Rmult_comm x 1).\nrewrite <- (Rmult_assoc 2 1 x).\nrewrite <- Rsqr_minus.\napply Rle_ge.\napply Rle_0_sqr.\nOptimize Proof.\nDefined.\n\nPrint HamkinsQverheard9thGradeProblem.\n\n(*\nfun (x : R) (H : x > 0) =>\neq_ind_r (fun r : R => x + r >= 2)\n  (eq_ind (1 * (x + / x)) (fun r : R => r >= 2)\n     (eq_ind (1 * 2) (fun r : R => 1 * (x + / x) >= r)\n        (eq_ind_r (fun r : R => r >= 1 * 2)\n           (eq_ind (x * / x) (fun r : R => r * x + r * / x >= r * 2)\n              (eq_ind_r (fun r : R => r * x + r * / x >= r * 2)\n                 (eq_ind_r (fun r : R => r + / x * x * / x >= / x * x * 2)\n                    (eq_ind_r (fun r : R => / x * (x * x) + r >= / x * x * 2)\n                       (eq_ind_r (fun r : R => / x * (x * x) + / x * (x * / x) >= r)\n                          (eq_ind (/ x * (x * x + x * / x)) (fun r : R => r >= / x * (x * 2))\n                             (Rmult_ge_compat_l (/ x) (x * x + x * / x) \n                                (x * 2)\n                                (Rgt_ge (/ x) 0\n                                   (Rlt_gt 0 (/ x) (Rinv_0_lt_compat x (Rlt_gt 0 x H))))\n                                (eq_ind 1 (fun r : R => x * x + r >= x * 2)\n                                   (eq_ind_r (fun r : R => x² + 1 >= r)\n                                      (Rminus_ge (x² + 1) (2 * x)\n                                         (eq_ind 1² (fun r : R => x² + r - 2 * x >= 0)\n                                            (eq_ind_r (fun r : R => r - 2 * x >= 0)\n                                               ((fun lemma : x * 1 = x =>\n                                                 Morphisms.reflexive_proper Rge\n                                                   (1² + x² - 2 * x) \n                                                   (1² + x² - 2 * (x * 1))\n                                                   (Morphisms.Reflexive_partial_app_morphism\n                                                      (Morphisms.reflexive_proper Rminus)\n                                                      (Morphisms.eq_proper_proxy (1² + x²))\n                                                      (2 * x) (2 * (x * 1))\n                                                      (Morphisms.Reflexive_partial_app_morphism\n                                                         (Morphisms.reflexive_proper Rmult)\n                                                         (Morphisms.eq_proper_proxy 2) x\n                                                         (x * 1)\n                                                         (RelationClasses.symmetry lemma))) 0\n                                                   0 (Morphisms.eq_proper_proxy 0))\n                                                  (Rmult_1_r x)\n                                                  (eq_ind_r\n                                                     (fun r : R => 1² + x² - 2 * r >= 0)\n                                                     (eq_ind (2 * 1 * x)\n                                                        (fun r : R => 1² + x² - r >= 0)\n                                                        (eq_ind (1 - x)²\n                                                           (fun r : R => r >= 0)\n                                                           (Rle_ge 0 \n                                                              (1 - x)² \n                                                              (Rle_0_sqr (1 - x)))\n                                                           (1² + x² - 2 * 1 * x)\n                                                           (Rsqr_minus 1 x)) \n                                                        (2 * (1 * x)) \n                                                        (Rmult_assoc 2 1 x)) \n                                                     (Rmult_comm x 1))) \n                                               (Rplus_comm x² 1²)) 1 Rsqr_1))\n                                      (Rmult_comm x 2)) (x * / x)\n                                   (Rinv_r_sym x (Rgt_not_eq x 0 H))))\n                             (/ x * (x * x) + / x * (x * / x))\n                             (Rmult_plus_distr_l (/ x) (x * x) (x * / x)))\n                          (Rmult_assoc (/ x) x 2)) (Rmult_assoc (/ x) x (/ x)))\n                    (Rmult_assoc (/ x) x x)) (Rmult_comm x (/ x))) 1\n              (Rinv_r x (Rgt_not_eq x 0 H))) (Rmult_plus_distr_l 1 x (/ x))) 2 \n        (Rmult_1_l 2)) (x + / x) (Rmult_1_l (x + / x))) (Rmult_1_l (/ x))\n*)\n", "meta": {"author": "bowtochris", "repo": "CoqStuff", "sha": "80ffef00b18a23b85f66fcb5b198d2730a49a362", "save_path": "github-repos/coq/bowtochris-CoqStuff", "path": "github-repos/coq/bowtochris-CoqStuff/CoqStuff-80ffef00b18a23b85f66fcb5b198d2730a49a362/HamkinsQverheard9thGradeProblem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7174994638078708}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := mult x (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj208_coqofml_CdwqET.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7174837360559608}}
{"text": "From mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype.\nRequire Import prosa.util.tactics.\n\n(** This file introduces a function called [search_arg] that allows finding the\n    argument within a given range for which a function is minimal w.r.t. to a\n    given order while satisfying a given predicate, along with lemmas\n    establishing the basic properties of [search_arg].\n\n    Note that while this is quite similar to [arg min ...] / [arg max ...] in\n    [ssreflect] ([fintype]), this function is subtly different in that it possibly\n    returns None and that it does not require the last element in the given\n    range to satisfy the predicate. In contrast, [ssreflect]'s notion of\n    extremum in [fintype] uses the upper bound of the search space as the\n    default value, which is rather unnatural when searching through a schedule.\n*)\n\nSection ArgSearch.\n  \n  (* Given a function [f] that maps the naturals to elements of type [T]... *)\n  Context {T : Type}.\n  Variable f: nat -> T.\n\n  (* ... a predicate [P] on [T] ... *)\n  Variable P: pred T.\n\n  (* ... and an order [R] on [T] ... *)\n  Variable R: rel T.\n\n  (* ... we define the procedure [search_arg] to iterate a given search space\n     [a, b), while checking each element whether [f] satisfies [P] at that\n     point and returning the extremum as defined by [R]. *)\n  Fixpoint search_arg (a b : nat) : option nat :=\n    if a < b then\n      match b with\n      | 0 => None\n      | S b' => match search_arg a b' with\n                | None => if P (f b') then Some b' else None\n                | Some x => if P (f b') && R (f b') (f x) then Some b' else Some x\n                end\n      end\n    else None.\n\n  (** In the following, we establish basic properties of [search_arg]. *)\n\n  (* To begin, we observe that the search yields [None] iff predicate [P] does\n     not hold for any of the points in the search interval. *)\n  Lemma search_arg_none:\n    forall a b,\n      search_arg a b = None <-> forall x, a <= x < b -> ~~ P (f x).\n  Proof.\n    split.\n    { (* if *)\n      elim: b => [ _ | b' HYP]; first by move=> _ /andP [_ FALSE] //.\n      rewrite /search_arg  -/search_arg.\n      case: (boolP (a < b'.+1)) => [a_lt_b | not_a_lt_b' TRIV].\n      - move: HYP. case: (search_arg a b') => [y | HYP NIL x].\n        + case: (P (f b') && R (f b') (f y)) => //.\n        + move=> /andP[a_le_x x_lt_b'].\n          move: x_lt_b'.\n          rewrite ltnS leq_eqVlt => /orP [/eqP EQ|LT].\n          * rewrite EQ.\n            move: NIL. case: (P (f b')) => //.\n          * feed HYP => //.\n            apply: (HYP x).\n            by apply /andP; split.\n      - move=> x /andP [a_le_x b_lt_b'].\n        exfalso.\n        move: not_a_lt_b'. rewrite -leqNgt ltnNge => /negP b'_lt_a.\n        by move: (leq_ltn_trans a_le_x b_lt_b').\n    }\n    { (* only if *)\n      rewrite /search_arg.\n      elim: b  => [//|b'].\n      rewrite -/search_arg => IND  NOT_SAT.\n      have ->: search_arg a b' = None.\n      {\n        apply IND => x /andP [a_le_x x_lt_n].\n        apply: (NOT_SAT x).\n        apply /andP; split => //.\n        by rewrite ltnS; apply ltnW.\n      }\n      case: (boolP (a < b'.+1)) => [a_lt_b | //].\n      apply ifF.\n      apply negbTE.\n      apply (NOT_SAT b').\n        by apply /andP; split.\n    }\n  Qed.\n\n  (* Conversely, if we know that [f] satisfies [P] for at least one point in\n     the search space, then [search_arg] yields some point. *)\n  Lemma search_arg_not_none:\n    forall a b,\n      (exists x, (a <= x < b) /\\ P (f x)) ->\n      exists y, search_arg a b = Some y.\n  Proof.\n    move=> a b H_exists.\n    destruct (search_arg a b) eqn:SEARCH; first by exists n.\n    move: SEARCH. rewrite search_arg_none => NOT_exists.\n    exfalso.\n    move: H_exists => [x [RANGE Pfx]].\n    by move: (NOT_exists x RANGE) => /negP not_Pfx.\n  Qed.\n\n  (* Since [search_arg] considers only points at which [f] satisfies [P], if it\n     returns a point, then that point satisfies [P]. *)\n  Lemma search_arg_pred:\n    forall a b x,\n      search_arg a b = Some x -> P (f x).\n  Proof.\n    move=> a b x.\n    elim: b => [| n IND]; first by rewrite /search_arg // ifN.\n    rewrite /search_arg -/search_arg.\n    destruct (a < n.+1) eqn:a_lt_Sn; last by trivial.\n    move: a_lt_Sn. rewrite ltnS => a_lt_Sn.\n    destruct (search_arg a n) as [q|] eqn:REC;\n      destruct (P (f n)) eqn:Pfn => //=;\n      [elim: (R (f n) (f q)) => // |];\n      by move=> x_is; injection x_is => <-.\n  Qed.\n\n  (* Since [search_arg] considers only points within a given range, if it\n     returns a point, then that point lies within the given range. *)\n  Lemma search_arg_in_range:\n    forall a b x,\n      search_arg a b = Some x -> a <= x < b.\n  Proof.\n    move=> a b x.\n    elim: b => [| n IND]; first by rewrite /search_arg // ifN.\n    rewrite /search_arg -/search_arg.\n    destruct (a < n.+1) eqn:a_lt_Sn; last by trivial.\n    move: a_lt_Sn. rewrite ltnS => a_lt_Sn.\n    destruct (search_arg a n) as [q|] eqn:REC;\n      elim: (P (f n)) => //=.\n    - elim: (R (f n) (f q)) => //= x_is;\n        first by injection x_is => <-; apply /andP; split.\n      move: (IND x_is) => /andP [a_le_x x_lt_n].\n      apply /andP; split => //.\n      by rewrite ltnS ltnW.\n    - move => x_is.\n      move: (IND x_is) => /andP [a_le_x x_lt_n].\n      apply /andP; split => //.\n      by rewrite ltnS ltnW.\n    - move => x_is.\n      by injection x_is => <-; apply /andP; split.\n  Qed.\n\n  (* Let us assume that [R] is a reflexive and transitive total order... *)\n  Hypothesis R_reflexive: reflexive R.\n  Hypothesis R_transitive: transitive R.\n  Hypothesis R_total: total R.\n\n  (* ...then [search_arg] yields an extremum w.r.t. to [a, b), that is, if\n     [search_arg] yields a point x, then [R (f x) (f y)] holds for any [y] in the\n     search range [a, b) that satisfies [P]. *)\n  Lemma search_arg_extremum:\n    forall a b x,\n      search_arg a b = Some x ->\n      forall y,\n        a <= y < b ->\n        P (f y) ->\n        R (f x) (f y).\n  Proof.\n    move=> a b x SEARCH.\n    elim: b x SEARCH => n IND x; first by rewrite /search_arg.\n    rewrite /search_arg -/search_arg.\n    destruct (a < n.+1) eqn:a_lt_Sn; last by trivial.\n    move: a_lt_Sn. rewrite ltnS => a_lt_Sn.\n    destruct (search_arg a n) as [q|] eqn:REC;\n      destruct (P (f n)) eqn:Pfn => //=.\n    - rewrite <- REC in IND.\n      destruct (R (f n) (f q)) eqn:REL => some_x_is;\n        move=> y /andP [a_le_y y_lt_Sn] Pfy;\n        injection some_x_is => x_is; rewrite -{}x_is //;\n        move: y_lt_Sn; rewrite ltnS;\n        rewrite leq_eqVlt => /orP [/eqP EQ | y_lt_n].\n      + by rewrite EQ; apply (R_reflexive (f n)).\n      + apply (R_transitive (f q)) => //.\n        move: (IND q REC y) => HOLDS.\n        apply HOLDS => //.\n        by apply /andP; split.\n      + rewrite EQ.\n        move: (R_total (f q) (f n)) => /orP [R_qn | R_nq] //.\n        by move: REL => /negP.\n      + move: (IND q REC y) => HOLDS.\n        apply HOLDS => //.\n        by apply /andP; split.\n    - move=> some_q_is y /andP [a_le_y y_lt_Sn] Pfy.\n      move: y_lt_Sn. rewrite ltnS.\n      rewrite leq_eqVlt => /orP [/eqP EQ | y_lt_n].\n      + exfalso. move: Pfn => /negP Pfn. by subst.\n      + apply IND => //. by apply /andP; split.\n    - move=> some_n_is. injection some_n_is => n_is.\n      move=> y /andP [a_le_y y_lt_Sn] Pfy.\n      move: y_lt_Sn. rewrite ltnS.\n      rewrite leq_eqVlt => /orP [/eqP EQ | y_lt_n].\n      + by rewrite -n_is EQ; apply (R_reflexive (f n)).\n      + exfalso.\n        move: REC. rewrite search_arg_none => NONE.\n        move: (NONE y) => not_Pfy.\n        feed not_Pfy; first by apply /andP; split.\n        by move: not_Pfy => /negP.\n  Qed.\n\nEnd ArgSearch.\n\nSection ExMinn.\n\n  (* We show that the fact that the minimal satisfying argument [ex_minn ex] of \n     a predicate [pred] satisfies another predicate [P] implies the existence\n     of a minimal element that satisfies both [pred] and [P]. *) \n  Lemma prop_on_ex_minn:\n    forall (P : nat -> Prop) (pred : nat -> bool) (ex : exists n, pred n),\n      P (ex_minn ex) ->\n      exists n, P n /\\ pred n /\\ (forall n', pred n' -> n <= n').\n  Proof.\n    intros.\n    exists (ex_minn ex); repeat split; auto.\n    all: have MIN := ex_minnP ex; move: MIN => [n Pn MIN]; auto.\n  Qed.\n\n  (* As a corollary, we show that if there is a constant [c] such \n     that [P c], then the minimal satisfying argument [ex_minn ex] \n     of a predicate [P] is less than or equal to [c]. *)\n  Corollary ex_minn_le_ex:\n    forall (P : nat -> bool) (exP : exists n, P n) (c : nat),\n      P c -> \n      ex_minn exP <= c.\n  Proof. \n    intros ? ? ? EX.\n    rewrite leqNgt; apply/negP; intros GT.\n    pattern (ex_minn (P:=P) exP) in GT;\n      apply prop_on_ex_minn in GT; move: GT => [n [LT [Pn MIN]]].\n    specialize (MIN c EX).\n      by move: MIN; rewrite leqNgt; move => /negP MIN; apply: MIN.\n  Qed.\n  \nEnd ExMinn.\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/util/search_arg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7174837336708385}}
{"text": "(** * MoreInd: More on Induction *)\n\nRequire Export ProofObjects.\n\n(* ##################################################### *)\n(** * Induction Principles *)\n\n(** This is a good point to pause and take a deeper look at induction\n    principles. \n\n    Every time we declare a new [Inductive] datatype, Coq\n    automatically generates and proves an _induction principle_ \n    for this type.\n\n    The induction principle for a type [t] is called [t_ind].  Here is\n    the one for natural numbers: *)\n\nCheck nat_ind.\n(*  ===> nat_ind : \n           forall P : nat -> Prop,\n              P 0  ->\n              (forall n : nat, P n -> P (S n))  ->\n              forall n : nat, P n  *)\n\n\n(** The [induction] tactic is a straightforward wrapper that, at\n    its core, simply performs [apply t_ind].  To see this more\n    clearly, let's experiment a little with using [apply nat_ind]\n    directly, instead of the [induction] tactic, to carry out some\n    proofs.  Here, for example, is an alternate proof of a theorem\n    that we saw in the [Basics] chapter. *)\n\nTheorem mult_0_r' : forall n:nat, \n  n * 0 = 0.\nProof.\n  apply nat_ind. \n  Case \"O\". reflexivity.\n  Case \"S\". simpl. intros n IHn. rewrite -> IHn. \n    reflexivity.  Qed.\n\n\n(** This proof is basically the same as the earlier one, but a\n    few minor differences are worth noting.  First, in the induction\n    step of the proof (the [\"S\"] case), we have to do a little\n    bookkeeping manually (the [intros]) that [induction] does\n    automatically.\n\n    Second, we do not introduce [n] into the context before applying\n    [nat_ind] -- the conclusion of [nat_ind] is a quantified formula,\n    and [apply] needs this conclusion to exactly match the shape of\n    the goal state, including the quantifier.  The [induction] tactic\n    works either with a variable in the context or a quantified\n    variable in the goal.\n\n    Third, the [apply] tactic automatically chooses variable names for\n    us (in the second subgoal, here), whereas [induction] lets us\n    specify (with the [as...]  clause) what names should be used.  The\n    automatic choice is actually a little unfortunate, since it\n    re-uses the name [n] for a variable that is different from the [n]\n    in the original theorem.  This is why the [Case] annotation is\n    just [S] -- if we tried to write it out in the more explicit form\n    that we've been using for most proofs, we'd have to write [n = S\n    n], which doesn't make a lot of sense!  All of these conveniences\n    make [induction] nicer to use in practice than applying induction\n    principles like [nat_ind] directly.  But it is important to\n    realize that, modulo this little bit of bookkeeping, applying\n    [nat_ind] is what we are really doing. *)\n\n(** **** Exercise: 2 stars, optional (plus_one_r') *)\n(** Complete this proof as we did [mult_0_r'] above, without using\n    the [induction] tactic. *)\n\nTheorem plus_one_r' : forall n:nat, \n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  {reflexivity. }\n  {intros. simpl. rewrite -> plus_comm. reflexivity. }\n  Qed.\n   \n\n(** Coq generates induction principles for every datatype defined with\n    [Inductive], including those that aren't recursive. (Although \n    we don't need induction to prove properties of non-recursive \n    datatypes, the idea of an induction principle still makes sense\n    for them: it gives a way to prove that a property holds for all\n    values of the type.)\n    \n    These generated principles follow a similar pattern. If we define a\n    type [t] with constructors [c1] ... [cn], Coq generates a theorem\n    with this shape:\n    t_ind :\n       forall P : t -> Prop,\n            ... case for c1 ... ->\n            ... case for c2 ... ->\n            ...                \n            ... case for cn ... ->\n            forall n : t, P n\n    The specific shape of each case depends on the arguments to the\n    corresponding constructor.  Before trying to write down a general\n    rule, let's look at some more examples. First, an example where\n    the constructors take no arguments: *)\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind. \n(* ===> yesno_ind : forall P : yesno -> Prop, \n                      P yes  ->\n                      P no  ->\n                      forall y : yesno, P y *)\n\n(** **** Exercise: 1 star, optional (rgb) *)\n(** Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\nCheck rgb_ind.\n(** rgb_ind : forall P : rgb -> Prop,\n       P red -> P green -> P blue -> forall y : rgb, P y*)\n\n\n(** Here's another example, this time with one of the constructors\n    taking some arguments. *)\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n(* ===> (modulo a little variable renaming for clarity)\n   natlist_ind :\n      forall P : natlist -> Prop,\n         P nnil  ->\n         (forall (n : nat) (l : natlist), P l -> P (ncons n l)) ->\n         forall n : natlist, P n *)\n\n(** **** Exercise: 1 star, optional (natlist1) *)\n(** Suppose we had written the above definition a little\n   differently: *)\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\n\n(** Now what will the induction principle look like? *)\n(** natlist1_ind :\n      forall P : natlist1 -> Prop,\n        P nnil1 -> (forall (l : natlist1) (n : nat), P l -> P (nsnoc1 l n)) ->\n        forall n : natlist, P n*)\n\n(** From these examples, we can extract this general rule:\n\n    - The type declaration gives several constructors; each\n      corresponds to one clause of the induction principle.\n    - Each constructor [c] takes argument types [a1]...[an].\n    - Each [ai] can be either [t] (the datatype we are defining) or\n      some other type [s].\n    - The corresponding case of the induction principle\n      says (in English):\n        - \"for all values [x1]...[xn] of types [a1]...[an], if [P]\n           holds for each of the inductive arguments (each [xi] of\n           type [t]), then [P] holds for [c x1 ... xn]\". \n\n*)\n\n\n\n(** **** Exercise: 1 star, optional (byntree_ind) *)\n(** Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive byntree : Type :=\n | bempty : byntree  \n | bleaf  : yesno -> byntree\n | nbranch : yesno -> byntree -> byntree -> byntree.\n(** \n\nbyntree_ind : forall P : byntree -> Prop,\n                P bempty -> (forall y : yesno, P (bleaf y)) ->\n                (forall (y : yesno) (b1 b2 : byntree), P b1 -> P b2 -> P (nbranch y b1 b2)) ->\n                forall b : byntree, P b*)\n\n(** **** Exercise: 1 star, optional (ex_set) *)\n(** Here is an induction principle for an inductively defined\n    set.\n      ExSet_ind :\n         forall P : ExSet -> Prop,\n             (forall b : bool, P (con1 b)) ->\n             (forall (n : nat) (e : ExSet), P e -> P (con2 n e)) ->\n             forall e : ExSet, P e\n    Give an [Inductive] definition of [ExSet]: *)\n\nInductive ExSet : Type :=\n  |con1 : bool -> ExSet\n  |con2 : nat -> ExSet -> ExSet.\n\n(** What about polymorphic datatypes?\n\n    The inductive definition of polymorphic lists\n      Inductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\n    is very similar to that of [natlist].  The main difference is\n    that, here, the whole definition is _parameterized_ on a set [X]:\n    that is, we are defining a _family_ of inductive types [list X],\n    one for each [X].  (Note that, wherever [list] appears in the body\n    of the declaration, it is always applied to the parameter [X].)\n    The induction principle is likewise parameterized on [X]:\n     list_ind :\n       forall (X : Type) (P : list X -> Prop),\n          P [] ->\n          (forall (x : X) (l : list X), P l -> P (x :: l)) ->\n          forall l : list X, P l\n   Note the wording here (and, accordingly, the form of [list_ind]):\n   The _whole_ induction principle is parameterized on [X].  That is,\n   [list_ind] can be thought of as a polymorphic function that, when\n   applied to a type [X], gives us back an induction principle\n   specialized to the type [list X]. *)\n\n(** **** Exercise: 1 star, optional (tree) *)\n(** Write out the induction principle that Coq will generate for\n   the following datatype.  Compare your answer with what Coq\n   prints. *)\n\nInductive tree (X:Type) : Type :=\n  | leaf : X -> tree X\n  | node : tree X -> tree X -> tree X.\nCheck tree_ind.\n(** \ntree_ind : forall (X : Type) (P : tree X -> Prop),\n            (forall x : X, P (leaf x)) ->\n            (forall (t1 t2 : tree X), P t1 -> P t2 -> P (node t1 t2)) -> \n            forall t : tree X, P t*)\n\n(** **** Exercise: 1 star, optional (mytype) *)\n(** Find an inductive definition that gives rise to the\n    following induction principle:\n      mytype_ind :\n        forall (X : Type) (P : mytype X -> Prop),\n            (forall x : X, P (constr1 X x)) ->\n            (forall n : nat, P (constr2 X n)) ->\n            (forall m : mytype X, P m -> \n               forall n : nat, P (constr3 X m n)) ->\n            forall m : mytype X, P m                   \n*) \nInductive mytype (X : Type) : Type :=\n  |constr1 : X -> mytype X\n  |constr2 : nat -> mytype X\n  |constr3 : mytype X -> nat -> mytype X.\n\n(** **** Exercise: 1 star, optional (foo) *)\n(** Find an inductive definition that gives rise to the\n    following induction principle:\n      foo_ind :\n        forall (X Y : Type) (P : foo X Y -> Prop),\n             (forall x : X, P (bar X Y x)) ->\n             (forall y : Y, P (baz X Y y)) ->\n             (forall f1 : nat -> foo X Y,\n               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n             forall f2 : foo X Y, P f2       \n*) \nInductive foo (X Y : Type) : Type :=\n  |bar : X -> foo X Y\n  |baz : Y -> foo X Y\n  |quux : nat -> foo X Y -> nat -> foo X Y.\n\n(** **** Exercise: 1 star, optional (foo') *)\n(** Consider the following inductive definition: *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 : list X -> foo' X -> foo' X\n  | C2 : foo' X.\n\n(** What induction principle will Coq generate for [foo']?  Fill\n   in the blanks, then check your answer with Coq.)\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    (forall (l : list X) (f : foo' X), P f -> P (C1 l f)) -> \n             P C2 ->\n             forall f : foo' X, P f\n*)\n\n(** [] *)\n\n(* ##################################################### *)\n(** ** Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?\n\n    The induction principle for numbers\n       forall P : nat -> Prop,\n            P 0  ->\n            (forall n : nat, P n -> P (S n))  ->\n            forall n : nat, P n\n   is a generic statement that holds for all propositions\n   [P] (strictly speaking, for all families of propositions [P]\n   indexed by a number [n]).  Each time we use this principle, we\n   are choosing [P] to be a particular expression of type\n   [nat->Prop].\n\n   We can make the proof more explicit by giving this expression a\n   name.  For example, instead of stating the theorem [mult_0_r] as\n   \"[forall n, n * 0 = 0],\" we can write it as \"[forall n, P_m0r\n   n]\", where [P_m0r] is defined as... *)\n\nDefinition P_m0r (n:nat) : Prop := \n  n * 0 = 0.\n\n(** ... or equivalently... *)\n\nDefinition P_m0r' : nat->Prop := \n  fun n => n * 0 = 0.\n\n(** Now when we do the proof it is easier to see where [P_m0r]\n    appears. *)\n\nTheorem mult_0_r'' : forall n:nat, \n  P_m0r n.\nProof.  \n  apply nat_ind.\n  Case \"n = O\". reflexivity.\n  Case \"n = S n'\". \n    (* Note the proof state at this point! *)\n    intros n IHn. \n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n(** This extra naming step isn't something that we'll do in\n    normal proofs, but it is useful to do it explicitly for an example\n    or two, because it allows us to see exactly what the induction\n    hypothesis is.  If we prove [forall n, P_m0r n] by induction on\n    [n] (using either [induction] or [apply nat_ind]), we see that the\n    first subgoal requires us to prove [P_m0r 0] (\"[P] holds for\n    zero\"), while the second subgoal requires us to prove [forall n',\n    P_m0r n' -> P_m0r n' (S n')] (that is \"[P] holds of [S n'] if it\n    holds of [n']\" or, more elegantly, \"[P] is preserved by [S]\").\n    The _induction hypothesis_ is the premise of this latter\n    implication -- the assumption that [P] holds of [n'], which we are\n    allowed to use in proving that [P] holds for [S n']. *)\n\n(* ##################################################### *)\n(** ** More on the [induction] Tactic *)\n\n(** The [induction] tactic actually does even more low-level\n    bookkeeping for us than we discussed above.\n\n    Recall the informal statement of the induction principle for\n    natural numbers:\n      - If [P n] is some proposition involving a natural number n, and\n        we want to show that P holds for _all_ numbers n, we can\n        reason like this:\n          - show that [P O] holds\n          - show that, if [P n'] holds, then so does [P (S n')]\n          - conclude that [P n] holds for all n.\n    So, when we begin a proof with [intros n] and then [induction n],\n    we are first telling Coq to consider a _particular_ [n] (by\n    introducing it into the context) and then telling it to prove\n    something about _all_ numbers (by using induction).\n\n    What Coq actually does in this situation, internally, is to\n    \"re-generalize\" the variable we perform induction on.  For\n    example, in our original proof that [plus] is associative...\n*)\n\nTheorem plus_assoc' : forall n m p : nat, \n  n + (m + p) = (n + m) + p.   \nProof.\n  (* ...we first introduce all 3 variables into the context,\n     which amounts to saying \"Consider an arbitrary [n], [m], and\n     [p]...\" *)\n  intros n m p. \n  (* ...We now use the [induction] tactic to prove [P n] (that\n     is, [n + (m + p) = (n + m) + p]) for _all_ [n],\n     and hence also for the particular [n] that is in the context\n     at the moment. *)\n  induction n as [| n'].\n  Case \"n = O\". reflexivity.\n  Case \"n = S n'\". \n    (* In the second subgoal generated by [induction] -- the\n       \"inductive step\" -- we must prove that [P n'] implies \n       [P (S n')] for all [n'].  The [induction] tactic \n       automatically introduces [n'] and [P n'] into the context\n       for us, leaving just [P (S n')] as the goal. *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n\n(** It also works to apply [induction] to a variable that is\n   quantified in the goal. *)\n\nTheorem plus_comm' : forall n m : nat, \n  n + m = m + n.\nProof.\n  induction n as [| n']. \n  Case \"n = O\". intros m. rewrite -> plus_0_r. reflexivity.\n  Case \"n = S n'\". intros m. simpl. rewrite -> IHn'. \n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** Note that [induction n] leaves [m] still bound in the goal --\n    i.e., what we are proving inductively is a statement beginning\n    with [forall m].\n\n    If we do [induction] on a variable that is quantified in the goal\n    _after_ some other quantifiers, the [induction] tactic will\n    automatically introduce the variables bound by these quantifiers\n    into the context. *)\n\nTheorem plus_comm'' : forall n m : nat, \n  n + m = m + n.\nProof.\n  (* Let's do induction on [m] this time, instead of [n]... *)\n  induction m as [| m']. \n  Case \"m = O\". simpl. rewrite -> plus_0_r. reflexivity.\n  Case \"m = S m'\". simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, optional (plus_explicit_prop) *)\n(** Rewrite both [plus_assoc'] and [plus_comm'] and their proofs in\n    the same style as [mult_0_r''] above -- that is, for each theorem,\n    give an explicit [Definition] of the proposition being proved by\n    induction, and state the theorem and proof in terms of this\n    defined proposition.  *)\n\nTheorem plus_assoc'' : forall n m p, n + (m + p) = (n + m) + p.\nProof.\n  intros. apply nat_ind with (n := n).\n  {simpl. reflexivity. }\n  {intros. simpl. rewrite -> H. reflexivity. }\n  Qed.\n\nTheorem plus_comm''' : forall n m, n + m = m + n.\nProof.\n  intros. apply nat_ind with (n := n).\n  {simpl. rewrite -> plus_0_r. reflexivity. }\n  {intros. simpl. rewrite <- plus_n_Sm. rewrite -> H.\n   reflexivity. }\n  Qed.\n\n\n\n(** ** Generalizing Inductions. *)\n\n(** One potentially confusing feature of the [induction] tactic is\nthat it happily lets you try to set up an induction over a term\nthat isn't sufficiently general.  The net effect of this will be \ndo lose information (much as [destruct] can do), and leave\nyou unable to complete the proof. Here's an example: *)\n\nLemma one_not_beautiful_FAILED: ~ beautiful 1. \nProof.\n  intro H.\n  (* Just doing an [inversion] on [H] won't get us very far in the [b_sum]\n\n    case. (Try it!). So we'll need induction. A naive first attempt: *)\n  induction H. \n  (* But now, although we get four cases, as we would expect from\n     the definition of [beautiful], we lose all information about [H] ! *) \nAbort.\n\n(** The problem is that [induction] over a Prop only works properly over \n   completely general instances of the Prop, i.e. one in which all\n   the arguments are free (unconstrained) variables. \n   In this respect it behaves more\n   like [destruct] than like [inversion]. \n\n   When you're tempted to do use [induction] like this, it is generally\n   an indication that you need to be proving something more general.\n   But in some cases, it suffices to pull out any concrete arguments\n   into separate equations, like this: *)\n\nLemma one_not_beautiful: forall n, n = 1 -> ~ beautiful n. \nProof.\n intros n E H.\n  induction H  as [| | | p q Hp IHp Hq IHq]. \n    Case \"b_0\".\n      inversion E.\n    Case \"b_3\". \n      inversion E. \n    Case \"b_5\". \n      inversion E. \n    Case \"b_sum\". \n      (* the rest is a tedious case analysis *)\n      destruct p as [|p'].\n      SCase \"p = 0\".\n        destruct q as [|q'].\n        SSCase \"q = 0\". \n          inversion E.\n        SSCase \"q = S q'\".\n          apply IHq. apply E. \n      SCase \"p = S p'\". \n        destruct q as [|q'].\n        SSCase \"q = 0\". \n          apply IHp.  rewrite plus_0_r in E. apply E. \n        SSCase \"q = S q'\".\n          simpl in E. inversion E.  destruct p'.  inversion H0.  inversion H0. \nQed.\n\n(** There's a handy [remember] tactic that can generate the second\nproof state out of the original one. *)\n\nLemma one_not_beautiful': ~ beautiful 1. \nProof.\n  intros H.  \n  remember 1 as n eqn:E. \n  (* now carry on as above *)\n  induction H.   \n  {inversion E. }\n  {inversion E. }\n  {inversion E. }\n  {destruct n.\n   {destruct m.\n    {inversion E. }\n    {apply IHbeautiful2. simpl in E. inversion E. reflexivity. }\n   }\n   {destruct m.\n    {apply IHbeautiful1. rewrite -> plus_0_r in E. apply E. }\n    {simpl in E. inversion E. destruct n. \n     {simpl in *. inversion H2. }\n     {simpl in *. inversion H2. }\n    }\n   }\n   }\n  Qed.\n\n(* ####################################################### *)\n(** * Informal Proofs (Advanced) *)\n\n(** Q: What is the relation between a formal proof of a proposition\n       [P] and an informal proof of the same proposition [P]?\n\n    A: The latter should _teach_ the reader how to produce the\n       former.\n\n    Q: How much detail is needed??\n\n    Unfortunately, There is no single right answer; rather, there is a\n    range of choices.\n\n    At one end of the spectrum, we can essentially give the reader the\n    whole formal proof (i.e., the informal proof amounts to just\n    transcribing the formal one into words).  This gives the reader\n    the _ability_ to reproduce the formal one for themselves, but it\n    doesn't _teach_ them anything.\n\n   At the other end of the spectrum, we can say \"The theorem is true\n   and you can figure out why for yourself if you think about it hard\n   enough.\"  This is also not a good teaching strategy, because\n   usually writing the proof requires some deep insights into the\n   thing we're proving, and most readers will give up before they\n   rediscover all the same insights as we did.\n\n   In the middle is the golden mean -- a proof that includes all of\n   the essential insights (saving the reader the hard part of work\n   that we went through to find the proof in the first place) and\n   clear high-level suggestions for the more routine parts to save the\n   reader from spending too much time reconstructing these\n   parts (e.g., what the IH says and what must be shown in each case\n   of an inductive proof), but not so much detail that the main ideas\n   are obscured.\n\n   Another key point: if we're comparing a formal proof of a\n   proposition [P] and an informal proof of [P], the proposition [P]\n   doesn't change.  That is, formal and informal proofs are _talking\n   about the same world_ and they _must play by the same rules_. *)\n(** ** Informal Proofs by Induction *)\n\n(** Since we've spent much of this chapter looking \"under the hood\" at\n    formal proofs by induction, now is a good moment to talk a little\n    about _informal_ proofs by induction.\n\n    In the real world of mathematical communication, written proofs\n    range from extremely longwinded and pedantic to extremely brief\n    and telegraphic.  The ideal is somewhere in between, of course,\n    but while you are getting used to the style it is better to start\n    out at the pedantic end.  Also, during the learning phase, it is\n    probably helpful to have a clear standard to compare against.\n    With this in mind, we offer two templates below -- one for proofs\n    by induction over _data_ (i.e., where the thing we're doing\n    induction on lives in [Type]) and one for proofs by induction over\n    _evidence_ (i.e., where the inductively defined thing lives in\n    [Prop]).  In the rest of this course, please follow one of the two\n    for _all_ of your inductive proofs. *)\n\n(** *** Induction Over an Inductively Defined Set *)\n \n(** _Template_: \n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n \n    _Example_:\n \n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if length [[] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of index.\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n            length l = length (x::l') = S (length l'),\n          it suffices to show that \n            index (S (length l')) l' = None.\n]]  \n          But this follows directly from the induction hypothesis,\n          picking [n'] to be length [l'].  [] *)\n \n(** *** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_. \n\n    _Template_:\n \n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n \n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(** The remainder of this chapter offers some additional details on\n    how induction works in Coq, the process of building proof\n    trees, and the \"trusted computing base\" that underlies\n    Coq proofs.  It can safely be skimmed on a first reading.  (We\n    recommend skimming rather than skipping over it outright: it\n    answers some questions that occur to many Coq users at some point,\n    so it is useful to have a rough idea of what's here.) *)\n\n\n(* ##################################################### *)\n(** ** Induction Principles in [Prop] *)\n\n\n(** Earlier, we looked in detail at the induction principles that Coq\n    generates for inductively defined _sets_.  The induction\n    principles for inductively defined _propositions_ like [gorgeous]\n    are a tiny bit more complicated.  As with all induction\n    principles, we want to use the induction principle on [gorgeous]\n    to prove things by inductively considering the possible shapes\n    that something in [gorgeous] can have -- either it is evidence\n    that [0] is gorgeous, or it is evidence that, for some [n], [3+n]\n    is gorgeous, or it is evidence that, for some [n], [5+n] is\n    gorgeous and it includes evidence that [n] itself is.  Intuitively\n    speaking, however, what we want to prove are not statements about\n    _evidence_ but statements about _numbers_.  So we want an\n    induction principle that lets us prove properties of numbers by\n    induction on evidence.\n\n    For example, from what we've said so far, you might expect the\n    inductive definition of [gorgeous]...\n    Inductive gorgeous : nat -> Prop :=\n         g_0 : gorgeous 0\n       | g_plus3 : forall n, gorgeous n -> gorgeous (3+m)\n       | g_plus5 : forall n, gorgeous n -> gorgeous (5+m).\n    ...to give rise to an induction principle that looks like this...\n    gorgeous_ind_max :\n       forall P : (forall n : nat, gorgeous n -> Prop),\n            P O g_0 ->\n            (forall (m : nat) (e : gorgeous m), \n               P m e -> P (3+m) (g_plus3 m e) ->\n            (forall (m : nat) (e : gorgeous m), \n               P m e -> P (5+m) (g_plus5 m e) ->\n            forall (n : nat) (e : gorgeous n), P n e\n    ... because:\n\n     - Since [gorgeous] is indexed by a number [n] (every [gorgeous]\n       object [e] is a piece of evidence that some particular number\n       [n] is gorgeous), the proposition [P] is parameterized by both\n       [n] and [e] -- that is, the induction principle can be used to\n       prove assertions involving both a gorgeous number and the\n       evidence that it is gorgeous.\n\n     - Since there are three ways of giving evidence of gorgeousness\n       ([gorgeous] has three constructors), applying the induction\n       principle generates three subgoals:\n\n         - We must prove that [P] holds for [O] and [b_0].\n\n         - We must prove that, whenever [n] is a gorgeous\n           number and [e] is an evidence of its gorgeousness,\n           if [P] holds of [n] and [e],\n           then it also holds of [3+m] and [g_plus3 n e].\n\n         - We must prove that, whenever [n] is a gorgeous\n           number and [e] is an evidence of its gorgeousness,\n           if [P] holds of [n] and [e],\n           then it also holds of [5+m] and [g_plus5 n e].\n\n     - If these subgoals can be proved, then the induction principle\n       tells us that [P] is true for _all_ gorgeous numbers [n] and\n       evidence [e] of their gorgeousness.\n\n    But this is a little more flexibility than we actually need or\n    want: it is giving us a way to prove logical assertions where the\n    assertion involves properties of some piece of _evidence_ of\n    gorgeousness, while all we really care about is proving\n    properties of _numbers_ that are gorgeous -- we are interested in\n    assertions about numbers, not about evidence.  It would therefore\n    be more convenient to have an induction principle for proving\n    propositions [P] that are parameterized just by [n] and whose\n    conclusion establishes [P] for all gorgeous numbers [n]:\n       forall P : nat -> Prop,\n          ... ->\n             forall n : nat, gorgeous n -> P n\n    For this reason, Coq actually generates the following simplified\n    induction principle for [gorgeous]: *)\n\n\n\nCheck gorgeous_ind.\n(* ===>  gorgeous_ind\n     : forall P : nat -> Prop,\n       P 0 ->\n       (forall n : nat, gorgeous n -> P n -> P (3 + n)) ->\n       (forall n : nat, gorgeous n -> P n -> P (5 + n)) ->\n       forall n : nat, gorgeous n -> P n *)\n\n(** In particular, Coq has dropped the evidence term [e] as a\n    parameter of the the proposition [P], and consequently has\n    rewritten the assumption [forall (n : nat) (e: gorgeous n), ...]\n    to be [forall (n : nat), gorgeous n -> ...]; i.e., we no longer\n    require explicit evidence of the provability of [gorgeous n]. *)\n\n(** In English, [gorgeous_ind] says:\n\n    - Suppose, [P] is a property of natural numbers (that is, [P n] is\n      a [Prop] for every [n]).  To show that [P n] holds whenever [n]\n      is gorgeous, it suffices to show:\n  \n      - [P] holds for [0],\n  \n      - for any [n], if [n] is gorgeous and [P] holds for\n        [n], then [P] holds for [3+n],\n\n      - for any [n], if [n] is gorgeous and [P] holds for\n        [n], then [P] holds for [5+n]. *)\n\n(** As expected, we can apply [gorgeous_ind] directly instead of using [induction]. *)\n\nTheorem gorgeous__beautiful' : forall n, gorgeous n -> beautiful n.\nProof.\n   intros.\n   apply gorgeous_ind.\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\".\n       intros.\n       apply b_sum. apply b_3.\n       apply H1.\n   Case \"g_plus5\".\n       intros.\n       apply b_sum. apply b_5.\n       apply H1.\n   apply H.\nQed.\n\n\n\n(** The precise form of an Inductive definition can affect the\n    induction principle Coq generates.\n\nFor example, in [Logic], we have defined [<=] as: *)\n\n(* Inductive 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\n(** This definition can be streamlined a little by observing that the \n    left-hand argument [n] is the same everywhere in the definition, \n    so we can actually make it a \"general parameter\" to the whole \n    definition, rather than an argument to each constructor. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(** By contrast, the induction principle that Coq calculates for the\n    first definition has a lot of extra quantifiers, which makes it\n    messier to work with when proving things by induction.  Here is\n    the induction principle for the first [le]: *)\n\n(* le_ind : \n     forall P : nat -> nat -> Prop,\n     (forall n : nat, P n n) ->\n     (forall n m : nat, le n m -> P n m -> P n (S m)) ->\n     forall n n0 : nat, le n n0 -> P n n0 *)\n\n\n(* ##################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 2 stars, optional (foo_ind_principle) *)\n(** Suppose we make the following inductive definition:\n   Inductive foo (X : Set) (Y : Set) : Set :=\n     | foo1 : X -> foo X Y\n     | foo2 : Y -> foo X Y\n     | foo3 : foo X Y -> foo X Y.\n   Fill in the blanks to complete the induction principle that will be\n   generated by Coq. \n   foo_ind\n        : forall (X Y : Set) (P : foo X Y -> Prop),   \n          (forall x : X, __________________________________) ->\n          (forall y : Y, __________________________________) ->\n          (________________________________________________) ->\n           ________________________________________________\n\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (bar_ind_principle) *)\n(** Consider the following induction principle:\n   bar_ind\n        : forall P : bar -> Prop,\n          (forall n : nat, P (bar1 n)) ->\n          (forall b : bar, P b -> P (bar2 b)) ->\n          (forall (b : bool) (b0 : bar), P b0 -> P (bar3 b b0)) ->\n          forall b : bar, P b\n   Write out the corresponding inductive set definition.\n   Inductive bar : Set :=\n     | bar1 : ________________________________________\n     | bar2 : ________________________________________\n     | bar3 : ________________________________________.\n\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (no_longer_than_ind) *)\n(** Given the following inductively defined proposition:\n  Inductive no_longer_than (X : Set) : (list X) -> nat -> Prop :=\n    | nlt_nil  : forall n, no_longer_than X [] n\n    | nlt_cons : forall x l n, no_longer_than X l n -> \n                               no_longer_than X (x::l) (S n)\n    | nlt_succ : forall l n, no_longer_than X l n -> \n                             no_longer_than X l (S n).\n  write the induction principle generated by Coq.\n  no_longer_than_ind\n       : forall (X : Set) (P : list X -> nat -> Prop),\n         (forall n : nat, ____________________) ->\n         (forall (x : X) (l : list X) (n : nat),\n          no_longer_than X l n -> ____________________ -> \n                                  _____________________________ ->\n         (forall (l : list X) (n : nat),\n          no_longer_than X l n -> ____________________ -> \n                                  _____________________________ ->\n         forall (l : list X) (n : nat), no_longer_than X l n -> \n           ____________________\n\n*)\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Induction Principles for other Logical Propositions *)\n\n(** Similarly, in [Logic] we have defined [eq] as: *)\n\n(* Inductive eq (X:Type) : X -> X -> Prop :=\n       refl_equal : forall x, eq X x x. *)\n\n(** In the Coq standard library, the definition of equality is \n    slightly different: *)\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\n(** The advantage of this definition is that the induction\n    principle that Coq derives for it is precisely the familiar\n    principle of _Leibniz equality_: what we mean when we say \"[x] and\n    [y] are equal\" is that every property on [P] that is true of [x]\n    is also true of [y].  *)\n\nCheck eq'_ind.\n(* ===> \n     forall (X : Type) (x : X) (P : X -> Prop),\n       P x -> forall y : X, x =' y -> P y \n\n   ===>  (i.e., after a little reorganization)\n     forall (X : Type) (x : X) forall y : X, \n       x =' y -> \n       forall P : X -> Prop, P x -> P y *)\n\n\n\n(** The induction principles for conjunction and disjunction are a\n    good illustration of Coq's way of generating simplified induction\n    principles for [Inductive]ly defined propositions, which we\n    discussed above.  You try first: *)\n\n(** **** Exercise: 1 star, optional (and_ind_principle) *)\n(** See if you can predict the induction principle for conjunction. *)\n\n(* Check and_ind. *)\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_ind_principle) *)\n(** See if you can predict the induction principle for disjunction. *)\n\n(* Check or_ind. *)\n(** [] *)\n\nCheck and_ind.\n\n(** From the inductive definition of the proposition [and P Q]\n     Inductive and (P Q : Prop) : Prop :=\n       conj : P -> Q -> (and P Q).\n    we might expect Coq to generate this induction principle\n     and_ind_max :\n       forall (P Q : Prop) (P0 : P /\\ Q -> Prop),\n            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->\n            forall a : P /\\ Q, P0 a\n    but actually it generates this simpler and more useful one:\n     and_ind :\n       forall P Q P0 : Prop,\n            (P -> Q -> P0) ->\n            P /\\ Q -> P0\n    In the same way, when given the inductive definition of [or P Q]\n     Inductive or (P Q : Prop) : Prop :=\n       | or_introl : P -> or P Q\n       | or_intror : Q -> or P Q.\n    instead of the \"maximal induction principle\"\n     or_ind_max :\n       forall (P Q : Prop) (P0 : P \\/ Q -> Prop),\n            (forall a : P, P0 (or_introl P Q a)) ->\n            (forall b : Q, P0 (or_intror P Q b)) ->\n            forall o : P \\/ Q, P0 o\n    what Coq actually generates is this:\n     or_ind :\n       forall P Q P0 : Prop,\n            (P -> P0) ->\n            (Q -> P0) ->\n            P \\/ Q -> P0\n]] \n*)\n\n(** **** Exercise: 1 star, optional (False_ind_principle) *)\n(** Can you predict the induction principle for falsehood? *)\n\n(* Check False_ind. *)\n(** [] *)\n\n(** Here's the induction principle that Coq generates for existentials: *)\n\nCheck ex_ind.\n(* ===>  forall (X:Type) (P: X->Prop) (Q: Prop),\n         (forall witness:X, P witness -> Q) -> \n          ex X P -> \n           Q *)\n\n(** This induction principle can be understood as follows: If we have\n         a function [f] that can construct evidence for [Q] given _any_\n        witness of type [X] together with evidence that this witness has\n        property [P], then from a proof of [ex X P] we can extract the\n        witness and evidence that must have been supplied to the\n        constructor, give these to [f], and thus obtain a proof of [Q]. *)\n\n\n\n(* ######################################################### *)\n(** ** Explicit Proof Objects for Induction *)\n\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n    \n(** Recall the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\nCheck nat_ind.\n(* ===> \n   nat_ind : forall P : nat -> Prop,\n      P 0 -> \n      (forall n : nat, P n -> P (S n)) -> \n      forall n : nat, P n  *)\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n\nPrint nat_ind.\nPrint nat_rect.\n(* ===> (after some manual inlining and tidying)\n   nat_ind =\n    fun (P : nat -> Prop) \n        (f : P 0) \n        (f0 : forall n : nat, P n -> P (S n)) =>\n          fix F (n : nat) : P n :=\n             match n with\n            | 0 => f\n            | S n0 => f0 n0 (F n0)\n            end.\n*)\n\n(** We can read this as follows: \n     Suppose we have evidence [f] that [P] holds on 0,  and \n     evidence [f0] that [forall n:nat, P n -> P (S n)].  \n     Then we can prove that [P] holds of an arbitrary nat [n] via \n     a recursive function [F] (here defined using the expression \n     form [Fix] rather than by a top-level [Fixpoint] \n     declaration).  [F] pattern matches on [n]: \n      - If it finds 0, [F] uses [f] to show that [P n] holds.\n      - If it finds [S n0], [F] applies itself recursively on [n0] \n         to obtain evidence that [P n0] holds; then it applies [f0] \n         on that evidence to show that [P (S n)] holds. \n    [F] is just an ordinary recursive function that happens to \n    operate on evidence in [Prop] rather than on terms in [Set].\n \n*)\n\n \n(**  We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  Recall our desire to\n    prove that\n\n    [forall n : nat, even n -> ev n].\n \n    Attempts to do this by standard induction on [n] fail, because the\n    induction principle only lets us proceed when we can prove that\n    [even n -> even (S n)] -- which is of course never provable.  What\n    we did in [Logic] was a bit of a hack:\n \n    [Theorem even__ev : forall n : nat,\n     (even n -> ev n) /\\ (even (S n) -> ev (S n))].\n \n    We can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n \n *)\n \n Definition nat_ind2 : \n    forall (P : nat -> Prop), \n    P 0 -> \n    P 1 -> \n    (forall n : nat, P n -> P (S(S n))) -> \n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS => \n          fix f (n:nat) := match n with \n                             0 => P0 \n                           | 1 => P1 \n                           | S (S n') => PSS n' (f n') \n                          end.\n \n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive (try\n     it!).\n\n     The [induction ... using] tactic variant gives a convenient way to\n     specify a non-standard induction principle like this. *)\n \nLemma even__ev' : forall n, even n -> ev n.\nProof. \n intros.  \n induction n as [ | |n'] using nat_ind2. \n  Case \"even 0\". \n    apply ev_0.  \n  Case \"even 1\". \n    inversion H.\n  Case \"even (S(S n'))\". \n    apply ev_SS. \n    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H. \nQed. \n\n(* ######################################################### *)\n(** ** The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is \"why\n    trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on.\n\n    There are a few additional wrinkles:\n\n    - Since Coq types can themselves be expressions, the checker must\n      normalize these (by using the computation rules) before\n      comparing them.\n\n    - The checker must make sure that [match] expressions are\n      _exhaustive_.  That is, there must be an arm for every possible\n      constructor.  To see why, consider the following alleged proof\n      object:\n      Definition or_bogus : forall P Q, P \\/ Q -> P :=\n        fun (P Q : Prop) (A : P \\/ Q) =>\n           match A with\n           | or_introl H => H\n           end. \n      All the types here match correctly, but the [match] only\n      considers one of the possible constructors for [or].  Coq's\n      exhaustiveness check will reject this definition.\n\n    - The checker must make sure that each [fix] expression\n      terminates.  It does this using a syntactic check to make sure\n      that each recursive call is on a subexpression of the original\n      argument.  To see why this is essential, consider this alleged\n      proof:\n          Definition nat_false : forall (n:nat), False :=\n             fix f (n:nat) : False := f n. \n      Again, this is perfectly well-typed, but (fortunately) Coq will\n      reject it. *)\n\n(** Note that the soundness of Coq depends only on the correctness of\n    this typechecking engine, not on the tactic machinery.  If there\n    is a bug in a tactic implementation (and this certainly does\n    happen!), that tactic might construct an invalid proof term.  But\n    when you type [Qed], Coq checks the term for validity from\n    scratch.  Only lemmas whose proofs pass the type-checker can be\n    used in further proof developments.  *)\n\n(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 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/MoreInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059560743422, "lm_q2_score": 0.9046505325302033, "lm_q1q2_score": 0.7174837255155297}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Nombre.\n\n(* Convertir une liste d'entiers en un entier                                 *)\n\nDefinition l2nat l := foldl (fun v i => i + 10 * v) 0 l.\n\nLemma l2nat_rcons l n : l2nat (rcons l n) = l2nat l * 10 + n.\nProof.\nrewrite /l2nat -[rcons _ _]revK rev_rcons foldl_rev.\nby rewrite /= -foldl_rev revK addnC mulnC.\nQed.\n\nCompute l2nat [:: 1; 2; 3].\n\n\n(* Convertir un entier en une liste d'entiers                                 *)\n\nFixpoint nat2l2 m n := \n   if n < 10 then [:: n] else\n   if m is m1.+1 then rcons (nat2l2 m1 (n %/ 10)) (n %% 10) else [::n].\n\nCompute nat2l2 100 123.\n\nDefinition nat2l n := nat2l2 n n.\n\nCompute nat2l 123.\n\nLemma nat2l2K m n : n < 10 ^ m -> l2nat (nat2l2 m n) = n.\nProof.\nelim: m n => [[]|m IH n nLD] //=.\ncase: leqP => _ /=; last by rewrite /l2nat /= addnC.\nrewrite l2nat_rcons IH -1?divn_eq //.\nrewrite -(ltn_pmul2r (_ : 0 < 10)) // -expnSr (leq_ltn_trans _ nLD) //.\nby rewrite {2}(divn_eq n 10) leq_addr.\nQed.\n\nLemma nat2l2_eq m1 m2 n :\n  n < 10 ^ m1 ->  n < 10 ^ m2 -> nat2l2 m1 n = nat2l2 m2 n.\nProof.\nwlog : m1 m2 / m1 <= m2 => [H nLm1 nLm2|].\n  case: (leqP m1 m2)=> [m1Lm2|m2Lm1]; first by apply: H.\n  by apply: sym_equal; apply: H => //; apply: ltnW.\nelim: m1 m2 n => [[|m2] [] |] //= m1 IH [|m2] //= n.\nrewrite ltnS => m1Lm2 nLm1 nLm2.\ncase: leqP=> // _; congr rcons.\napply: IH => //.\n  rewrite -(ltn_pmul2r (_ : 0 < 10)) // -expnSr (leq_ltn_trans _ nLm1) //.\n  by rewrite {2}(divn_eq n 10) leq_addr.\nrewrite -(ltn_pmul2r (_ : 0 < 10)) // -expnSr (leq_ltn_trans _ nLm2) //.\nby rewrite {2}(divn_eq n 10) leq_addr.\nQed.\n\nLemma nat2lK n : l2nat (nat2l n) = n.\nProof. by apply: nat2l2K; apply: ltn_expl. Qed.\n\n(******************************************************************************)\n(*                                                                            *)\n(*              Modélisation des différentes propositions                     *)\n(*                                                                            *)\n(******************************************************************************)\n\n(* Chiffres décroissants                                                      *)\n\nDefinition prop1 l := (1 \\in l) == sorted (fun x y => x >= y) l.\n\nCompute prop1 [:: 4; 3; 2; 1; 1; 0].\nCompute prop1 [:: 7; 5; 2; 2; 1; 0].\n\n(* Au moins deux chiffres impairs                                             *)\n\nDefinition prop2 l := (2 \\in l) == (count odd l >= 2).\n\nCompute prop2 [:: 5; 2; 6; 1; 0].\nCompute prop2 [:: 1; 1; 3; 2].\n\n(* Tous les chiffres différents                                               *)\n\nDefinition prop3 l := (3 \\in l) == uniq l.\n\nCompute prop3 [:: 3; 1; 2].\nCompute prop3 [:: 4; 4; 3].\n\n(* Quatrième chiffre en partant de la gauche est pair                         *)\n\nDefinition prop4 l := (4 \\in l) == ~~ odd (nth 0 l 3).\n\nCompute prop4 [:: 4; 3; 1; 6; 0].\n\n(* Produit non divisible par 5                                                *)\n\nDefinition prop5 l := (5 \\in l) == ~~ (5 %| foldr muln 1 l).\n\nCompute prop5 [:: 4; 2].\nCompute prop5 [:: 3; 7].\n\n(* Trois chiffres impairs à la suite                                          *)\n\nFixpoint todd l := if l is a :: l1 then\n                     if l1 is b :: c :: l2 then \n                              [&& odd a, odd b & odd c] || todd l1\n                     else false\n                   else false.\n\nDefinition prop6 l := (6 \\in l) == todd l.\n\nCompute prop6 [:: 1; 3; 7; 6].\nCompute prop6 [:: 6; 2; 1; 1; 1; 3; 4].\n\n(* Est un nombre premier                                                      *)\n\nDefinition prop7 l := (7 \\in l) == prime (l2nat l).\n\nCompute prop7 [:: 7].\nCompute prop7 [:: 3; 7].\n\n(* Pas plus 2 nombres pairs à la suite                                        *)\n\nFixpoint teven l := if l is a :: l1 then\n                     if l1 is b :: c :: _ then \n                              [&& ~~ odd a, ~~ odd b & ~~ odd c] || teven l1\n                     else false\n                   else false.\n\nDefinition prop8 l := (8 \\in l) == ~~ teven l.\n\nCompute prop8 [:: 8; 2; 2].\nCompute prop8 [:: 4; 8; 2; 1].\n\n(* Produit des impairs est un carré parfait                                   *)\n\nDefinition perfect_square n :=\n   all (fun p => ~~ odd p.2) (prime_decomp n).\n\nCompute perfect_square 47.\n\nDefinition iprod l := foldr (fun i v => if odd i then i * v else v) 1 l.\n\nCompute iprod [:: 9; 2; 3].\n\nDefinition prop9 l := (9 \\in l) == perfect_square (iprod l).\n\n\n(* Un élément distinct est la somme des autres                                *)\n\nDefinition prop0 l := (0 \\in l) == \n                        (let sum := foldr addn 0 l in\n                         ~~ odd sum && (count (pred1 sum./2) l == 1)).\n\nCompute prop0 [:: 5; 7; 2; 0; 0].\nCompute prop0 [:: 1; 0; 1; 3; 1].\nCompute prop0 [:: 4; 4; 0].\n\n(* Toutes les propositions                                                    *)\n\nDefinition check_prop n :=\n  let l := nat2l n in\n  [&& prop1 l, prop2 l, prop3 l, prop4 l, prop5 l,\n      prop6 l, prop7 l, prop8 l, prop9 l& prop0 l].\n\n(* Une version plus rapide                                                    *)\nDefinition fcheck_prop n := \n  let l := nat2l n in\n  if prop9 l then if prop8 l then if prop0 l then if prop6 l then if prop5 l \n  then if prop4 l then if prop3 l then if prop2 l then if prop1 l then prop7 l \n  else false else false else false else false else false else false else false \n  else false else false.\n\nLemma Pfcheck_prop n : fcheck_prop n = check_prop n.\nProof.\nrewrite /check_prop /fcheck_prop.\ncase: prop9 => //; case prop8 => //; case: prop0; rewrite ?andbF //.\ncase: prop6 => //; case prop5 => //; case: prop4; rewrite ?andbF //.\ncase: prop3 => //; case prop2  => //; case: prop1 => //; case: prop7 => //.\nQed.\n\n(* Le résultat                                                                *)\n\nDefinition result := l2nat [:: 9; 4; 2; 2; 1; 0].\n\n(* Le résultat vérifie les 10 propositions                                    *)\n\nFact Presult : check_prop result.\nProof. by vm_compute. Qed.\n\n(******************************************************************************)\n(*                                                                            *)\n(*     Tester tous les nombres plus petits que 942210                         *)\n(*                                                                            *)\n(******************************************************************************)\n\n\n(* Test à zero sur une liste                                                  *)\n\nDefinition is_zero l := all (pred1 0) l.\n\nLemma is_zero_rcons l a : is_zero (rcons l a) = (is_zero l && (a == 0)).\nProof.\nelim: l a => [a| b l IH a] /=; first by rewrite andbT.\nby rewrite IH andbA.\nQed.\n\nLemma head_nat2l2_eq0 m n :\n   n < 10 ^ m -> (nth 1 (nat2l2 m n) 0  == 0) == (n == 0).\nProof.\nelim: m n => [[]|m IH n nLD] //.\nrewrite [nat2l2 _ _]/=.\ncase: leqP=> [DLn|nLN //].\nrewrite nth_rcons.\nhave->: 0 < size (nat2l2 m (n %/ 10)).\n  by case: (m) => /=; case: (_ < 10) => // s; rewrite size_rcons.\nrewrite (eqP (IH _ _)); last first.\n  rewrite -(ltn_pmul2r (_ : 0 < 10)) // -expnSr (leq_ltn_trans _ nLD) //.\n  by rewrite {2}(divn_eq n 10) leq_addr.\nby move: (DLn); rewrite -divn_gt0 //; case: (n) DLn => // n1; case: (_ %/ _).\nQed.\n\nLemma is_zero_nat2l2 m n : n < 10 ^ m -> is_zero (nat2l2 m n) == (n == 0).\nProof.\nelim: m n => [[]|m IH n nLD] //=.\ncase: leqP=> [DLn|nLN /=]; last by rewrite andbT.\nrewrite is_zero_rcons (eqP (IH _ _)); last first.\n  rewrite -(ltn_pmul2r (_ : 0 < 10)) // -expnSr (leq_ltn_trans _ nLD) //.\n  by rewrite {2}(divn_eq n 10) leq_addr.\nby rewrite {3}(divn_eq n 10) addn_eq0 muln_eq0 orbF.\nQed.\n\n(* Remplacer tous les chiffres par des 9                                    *)\n\nDefinition to_nine l := map (fun i : nat => 9) l.\n\n(* Décrémenter de 1 une liste                                               *)\n\nFixpoint decrr l := \n  if l is a :: l1 then\n     if is_zero l1 then\n        if a == 0 then to_nine l else a.-1 :: to_nine l1  \n     else a :: decrr l1\n  else [::].\n\nDefinition decr l := \n  if is_zero l then [:: 0] else\n  let l1 := decrr l in \n  if l1 is 0 :: a :: l2 then a :: l2 else l1.\n\nCompute decr [:: 1; 2; 3].\nCompute decr [:: 1].\n\nLemma decrr_rcons l a : \n  decrr (rcons l a) = \n     if (a == 0) then rcons (decrr l) 9 else rcons l a.-1.\nProof.\nelim: l => //= b l IH.\nrewrite is_zero_rcons; case: (boolP (is_zero l)) => [zZ|zNZ] /=; last first.\n  by rewrite {}IH; case: (a =P 0) => //.\ncase: (b =P 0) => [-> | bNZ] /=.\n  by rewrite /to_nine map_rcons {}IH; case: (_ == _).\nby rewrite /to_nine map_rcons {}IH; case: (_ == _).\nQed.\n\nLemma Pdecrr m n : n < 10 ^ m -> 0 < n ->\n  let l1 := decrr (nat2l2 m n) in \n  (if l1 is 0 :: a :: l2 then a :: l2 else l1)  = nat2l2 m n.-1.\nProof.\nelim: m n => [[]|m IH [|n] nLm _] //=.\ncase: (leqP 10  n.+1) => [DLm|] /= ; last first.\n  case: (n) nLm => // n1 nLm nLD.\n  by rewrite (leq_ltn_trans _ nLD).\nrewrite decrr_rcons.\ncase: (_ =P 0) => [modZ|modNZ] /=; last first.\n  have : n %% 10 < 10 by apply: ltn_pmod.\n  rewrite leq_eqVlt ltnS => /orP[/eqP nE10 | mL9].\n    by case: modNZ; rewrite -addn1 -modnDml addn1 nE10.\n  have /= := head_nat2l2_eq0 nLm.\n  rewrite ltnNge DLm /=.\n  move: DLm mL9; rewrite ltnS leq_eqVlt => /orP[/eqP<-|] //.\n  rewrite ltnNge -ltnS => /negPf-> mL9.\n  have [-> -> /=]: (n.+1 %/ 10) = (n %/ 10) /\\ (n.+1 %% 10) = (n %% 10).+1.\n    have ->: n.+1 = n %/ 10 * 10 + (n %% 10).+1.    \n      by rewrite addnS -divn_eq.\n    rewrite divnMDl // [_.+1 %/ _]divn_small ?addn0 //.\n    by rewrite modnMDl  // modn_small.\n  by case: nat2l2=> [|[|a] l] //=; case: modn.\nhave nLSD : n.+1 %/ 10 < 10 ^ m.\n  rewrite -(ltn_pmul2r (_ : 0 < 10)) // -expnSr (leq_ltn_trans _ nLm) //.\n  by rewrite {2}(divn_eq n.+1 10) leq_addr.\nmove: DLm modZ; rewrite ltnS leq_eqVlt => /orP[/eqP<-|DLm] //=.\n  by case: (m).\nrewrite leqNgt ltnS DLm /= => modD0.\nhave posD : 0 < n %/ 10 by rewrite divn_gt0.\nhave modD9 : n %% 10 = 9.\n  move: modD0.\n  have : n %% 10 < 10 by apply: ltn_pmod.\n  rewrite leq_eqVlt eqSS ltnS => /orP[/eqP-> //| DD].\n  by rewrite -addn1 -modnDml modn_small addnC.\nhave posSD : 0 < n.+1 %/ 10.\n  by rewrite divn_gt0 // (leq_trans DLm).\nrewrite modD9; move: (IH _ nLSD posSD).\nhave -> /=: (n.+1 %/ 10) = (n %/ 10).+1.\n  by rewrite {1}[n](divn_eq n 10) -addnS modD9 divnMDl ?addn1.\ncase: decrr => [|[[HH |a1 l1 <-]|a l <-]] //=.\n  by case: (m) => [|m1] //=; case: (_ < _) => //; case: nat2l2.\nhave nLD : n %/ 10 < 10 ^ m.\n  by apply/(leq_ltn_trans _ nLSD)/leq_div2r.\nhave := nat2l2K nLD; rewrite -HH /l2nat/= muln0.\nby case: (_ %/ _) posD.\nQed.\n\nLemma Pdecr n : decr (nat2l n) = nat2l n.-1.\nProof.\nsuff {n}H : forall m n, n < 10 ^ m -> decr (nat2l2 m n) = nat2l2 m n.-1.\n  suff->: nat2l n.-1 = nat2l2 n n.-1; first by apply/H/ltn_expl.\n  apply: nat2l2_eq; first by apply: ltn_expl.\n  by apply: leq_trans (leq_ltn_trans (leq_pred _) _) (ltn_expl _ _).\nmove=> [|m] [|n] // nLD.\nrewrite /decr (eqP (is_zero_nat2l2 _)) //=.\nby apply: (Pdecrr nLD).\nQed.\n\n(* Une version plus efficace pour vérifier les propositions                   *)\n\nDefinition check_propl l :=\n  if prop9 l then\n    if prop8 l then \n     if prop0 l then\n     if prop6 l then\n     if prop5 l then\n     if prop4 l then\n     if prop3 l then\n     if prop2 l then\n     if prop1 l then prop7 l else false\n     else false else false else false else false else false else false \n     else false else false.\n\nLemma Pcheck_propl n : check_prop n = check_propl (nat2l n).\nProof.\nrewrite /check_prop /check_propl.\ncase: prop9 => //; case prop8 => //; case: prop0; rewrite ?andbF //.\ncase: prop6 => //; case prop5 => //; case: prop4; rewrite ?andbF //.\ncase: prop3 => //; case prop2  => //; case: prop1 => //; case: prop7 => //.\nQed.\n\n(* Vérifier en décrémentant progressivement                                   *)\nFixpoint check_less l n := \n  let l1 := decr l in\n  if n is n1.+1 then check_propl l1 || check_less l1 n1 \n                         else false.\n\nLemma Pcheck_less n m :\n  check_less (nat2l n) m = false ->  forall k, n - m <= k < n -> ~ check_prop k.\nProof.\nelim: m n => [m _ k|m IH [|n]] //=.\n  by rewrite subn0 leqNgt; case: (_ <= _).\nrewrite Pdecr /= subSS -Pcheck_propl.\ncase: (boolP (check_prop _)) => //= /negP cP /IH H k.\nrewrite [k < _]leq_eqVlt eqSS ltnS; case: eqP=> [->|kDl] //=.\nby exact: H.\nQed.\n\n(* Tous les nombres plus petits ne vérifient pas les 10 propositions          *)\n\nFact Lresult : forall m, m < result -> ~ check_prop m.\nProof.\nmove=> m mLr.\nhave: result - result <= m < result by rewrite subnn leq0n.\nmove: {mLr}m.\nhave F : check_less (nat2l result) result = false\n  by vm_cast_no_check (refl_equal false).\napply: (Pcheck_less F).\nQed.\n\nEnd Nombre.\n", "meta": {"author": "thery", "repo": "lemonde", "sha": "a91665306424cfea8c4b9bdb0a1826666029b1a1", "save_path": "github-repos/coq/thery-lemonde", "path": "github-repos/coq/thery-lemonde/lemonde-a91665306424cfea8c4b9bdb0a1826666029b1a1/nombre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7174837248229394}}
{"text": "Require Import ssreflect ssrbool.\n\nGoal forall A B, A /\\ B -> B /\\ A.\nProof.\n    by move=> A B [].\nQed.\n\nGoal forall A B, A \\/ B -> B \\/ A.\nProof.\n    by move=> A B [a | b] ; [right | left].\nQed.\n\nGoal forall (A B : bool), A \\/ B -> B \\/ A.\nProof.\n    by move=> [] [] AoB; apply/orP; move/orP : AoB.\nQed.\n\nGoal forall A (a : A) (P : A -> Prop),  (forall P : Prop, P \\/ ~P) -> exists x, P x -> forall y, P y.\nProof.\n    move=> A a P EP.\n    case: (EP (exists u : A, ~P u)) => [[u nPu]| nenPu].\n    by exists u.\n    exists a => pa m.\n    case: (EP (P m)) => // npm.\n    by case: nenPu; exists m.\n    Show Proof.\nQed.\n\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/ssr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.7174837142825083}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import ZArith.\nRequire Import Rbase.\nParameter pow2: Z -> R.\n\n\nAxiom Power_0 : ((pow2 0%Z) = 1%R).\n\nAxiom Power_s : forall (n:Z), (0%Z <= n)%Z ->\n  ((pow2 (n + 1%Z)%Z) = (2%R * (pow2 n))%R).\n\nAxiom Power_p : forall (n:Z), (n <= 0%Z)%Z ->\n  ((pow2 (n - 1%Z)%Z) = ((05 / 10)%R * (pow2 n))%R).\n\nAxiom Power_s_all : forall (n:Z), ((pow2 (n + 1%Z)%Z) = (2%R * (pow2 n))%R).\n\nAxiom Power_p_all : forall (n:Z),\n  ((pow2 (n - 1%Z)%Z) = ((05 / 10)%R * (pow2 n))%R).\n\nAxiom Power_1 : ((pow2 1%Z) = 2%R).\n\nAxiom Power_neg1 : ((pow2 (-1%Z)%Z) = (05 / 10)%R).\n\n(* YOU MAY EDIT THE CONTEXT BELOW *)\nOpen Scope Z_scope.\n(* DO NOT EDIT BELOW *)\n\nTheorem Power_non_null : forall (n:Z), ~ ((pow2 n) = 0%R).\n(* YOU MAY EDIT THE PROOF BELOW *)\n\n\nintro n.\nassert (h:n>=0 \\/ n<=0) by omega.\ndestruct h.\ncut (0 <= n); auto with zarith.\napply Z_lt_induction with\n  (P:= fun n => \n       0 <= n -> pow2 n <> 0%R);auto with zarith.\nintros x Hind Hxpos.\nassert (hx:x = 0 \\/ x >0) by omega.\ndestruct hx.\nsubst x.\nrewrite Power_0;auto with *.\nreplace (x) with (x-1+1) by omega.\nrewrite Power_s;auto with *.\n\nrewrite Rmult_neq_0_reg with (r1:=2%R) (r2:=pow2 (x - 1)).\napply Hind.\n\nQed.\n(* DO NOT EDIT BELOW *)\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/tests/bitvector1/bitvector1_Pow2real_Power_non_null_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.717483710204854}}
{"text": "(**\n* Canonical finite types\n[FIN.t n] is a type with [n] members,\none member naturally corresponding to each [m < n].\n*)\n\nModule FIN.\n\n  (**\n  ** Definitions\n  *)\n\n  Inductive Singleton (n : nat) := lift : Singleton n.\n\n  (**\n  *** Canonical finite types\n  [t 0] is the empty type.\n  [t (S n)] is the sum of [t n] and the singleton of [n].\n  *)\n\n  Fixpoint t (n : nat) : Type :=\n  match n with\n  | O   => Empty_set\n  | S n => sum (t n) (Singleton n)\n  end.\n\n  Definition last {n} : t (S n) := inr (lift n).\n\n  (**\n  An element of\n  [FIN.t n]\n  is also an element of\n  [FIN.t (S n)].\n  More generally,\n  it is also an element of\n  [FIN.t (k + n)].\n  *)\n\n  Definition up {n} (x : t n) : t (S n) := inl x.\n  Local Notation \"++ x\" := (up x) (at level 6, right associativity).\n\n  Fixpoint up' {n k} (x : t n) : t (k + n) :=\n  match k with\n  | O   => x\n  | S k => ++(up' x)\n  end.\n\n  (**\n  *** To and from naturals\n  *)\n\n  Definition ofNat (n k : nat) : t (k + S n) := up' last.\n\n  Fixpoint toNat {n} : t (S n) -> nat :=\n  match n with\n  | O   => fun _ => 0\n  | S n => fun x => match x with\n                    | inl x => toNat x\n                    | inr x => n\n                    end\n  end.\n\n  (**\n  ** Notations\n  *)\n\n  Module NOTATIONS.\n\n    Delimit Scope FIN with FIN.\n\n    Notation \"++ x\" := ++x (at level 6, right associativity) : FIN.\n\n  End NOTATIONS.\n\n  (**\n  ** Theorems\n  *)\n\n  Module Type THMS_SIG.\n\n    Axiom t0Empty : t 0 -> False.\n\n    Axiom t1Singleton : forall x : t 1, x = last.\n\n    (**\n    One would want to prove\n    the correctness of [ofNat] and [toNat],\n    i.e. that [ofNat (toNat x) k = up' x] and\n    that [toNat (ofNat n k) = n].\n    It is however nontrivial to even state these,\n    since [(k + S n) = (S _)] does not automatically typecheck.\n    For my purposes,\n    I do not need to prove their correctness so\n    I will skip doing so.\n    *)\n\n  End THMS_SIG.\n\n  (**\n  ** Proofs\n  *)\n\n  Module THMS : THMS_SIG.\n\n    Theorem t0Empty (x : t 0) : False.\n    Proof. destruct x. Qed.\n\n    Theorem t1Singleton (x : t 1) : x = last.\n    Proof. destruct x as [x | x]; destruct x. reflexivity. Qed.\n\n  End THMS.\n\nEnd FIN.\n", "meta": {"author": "anderslundstedt", "repo": "pca-realizability", "sha": "56d9d0aea258fabaef780eefabc49b75cd9be1ff", "save_path": "github-repos/coq/anderslundstedt-pca-realizability", "path": "github-repos/coq/anderslundstedt-pca-realizability/pca-realizability-56d9d0aea258fabaef780eefabc49b75cd9be1ff/coq/fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.8031737987125613, "lm_q1q2_score": 0.7174827182116438}}
{"text": "Require Import Omega.\nLemma le_lt_S_eq : forall n p:nat, n <= p -> p < S n -> n = p.\nProof.\n intros; omega.\nQed.", "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/autotac/SRC/le_lt_S_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109826342961, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7174794892336755}}
{"text": "Module NatDefs.\n\n\nTheorem S_n_eq_add : forall n : nat,\n    1 + n = S n.\nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem mult_S_1 : forall n m : nat,\n    S n = m ->\n    m * (1 + n) = m * m.\nProof.\n  intros.\n  rewrite S_n_eq_add.\n  rewrite H.\n  reflexivity.\nQed.\n", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/mult_s_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7174782205048278}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus z (mult z y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj285_coqofml_K6qm52.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7174782062191595}}
{"text": "(**EXERCÍCIO x4.11.\nDefina usando equações recursivas a seqüência Fibonacci, como uma funcção de Nat para\nNat*)\n\nFixpoint fib (n : nat) : nat :=\n  match n with\n  | O => O\n  | S O => S O\n  | S (S n'' as n') => match n' with\n                        | 0 => 1\n                        | S n'' => fib n' + fib n''\n                       end\n  end.\nCompute fib 10.\n\n(**EXERCÍCIO x4.12*)\n\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\nFixpoint plus (x y : nat) : nat :=\nmatch x with\n  | O => y\n  | S x' => S(plus x' y)\n  end.\n\nlemma plus_0(x : nat) plus x 0= x. \nQed. \n  ", "meta": {"author": "Rickjoim", "repo": "fmc1-coq", "sha": "4cbde3e56f1abb02dc69882625a2a6bd3d9ab097", "save_path": "github-repos/coq/Rickjoim-fmc1-coq", "path": "github-repos/coq/Rickjoim-fmc1-coq/fmc1-coq-4cbde3e56f1abb02dc69882625a2a6bd3d9ab097/NatRecInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7174692416618825}}
{"text": "(* From mathcomp Require Import all_ssreflect. *)\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLemma sum_ord_const n m : \\sum_(i < n) m = n * m.\nProof. by rewrite sum_nat_const card_ord. Qed.\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># *)\n\n(** \n  ----\n  ** Exercise 1 \n*)\n\n(** \n   Prove the following state by induction and by following Gauss proof.\n *)\n\nLemma gauss_ex n : (\\sum_(i < n) i).*2 = n * n.-1.\nProof.\nQed.\n\n(** Hints\n\ninduction *)\n\nCheck big_ord_recr.\nCheck big_ord0.\nCheck doubleD.\nCheck muln2.\nCheck mulnDr.\nCheck addn2.\nCheck mulnC.\n\n(** Hints\n\nGauss (1 + 2 + 3).*2 = (1 + 2 + 3) + (3 + 2 + 1) = ((1 + 3) + (2 + 2) + (3 + 1) *)\n\nCheck addnn.\nCheck reindex_inj.\nCheck big_split.\nCheck sum_ord_const.\nPrint rev_ord.\nCheck rev_ord_proof.\nCheck rev_ord_inj.\nCheck eq_bigr.\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># *)\n\n\n(** \n  ----\n   ** Exercise 2\n*)\n\nLemma sum_odd1 n : \\sum_(i < n) (2 * i + 1) = n ^ 2.\nProof.\nQed.\n\n(** Hints *)\n\nCheck big_split.\nCheck big_distrr.\nCheck mul2n.\nCheck mulnDr.\nCheck addn1.\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># *)\n\n\n(** \n  ----\n  ** Exercise 3\n*)\n\nLemma sum_exp x n : x ^ n.+1 - 1 = (x - 1) * \\sum_(i < n.+1) x ^ i.\nProof.\nQed.\n\n(** Hints *)\n\nCheck mulnBl.\nCheck big_distrr.\nCheck big_ord_recr.\nCheck eq_bigr.\n\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># *)\n\n\n(**\n  ----\n ** Exercise 4\n*)\n\n(** Prove the following state by induction and by using a similar trick\n   as for Gauss noticing that n ^ 3 = n * (n ^ 2) *)\n\nLemma bound_square n : \\sum_(i < n) i ^ 2 <= n ^ 3.\nProof.\nQed.\n\n(** Hints *)\n\nCheck big_ind2.\nCheck leq_add.\nCheck leq_exp2r.\nCheck expnS.\nCheck ltnW.\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># *)\n\n\n(**\n  ----\n  ** Exercise 5 \n*)\n\n(**\n  building a monoid law \n*)\n\nSection cex.\n\nVariable op2 : nat -> nat -> nat.\n\nHypothesis op2n0 : right_id 0 op2.\n\nHypothesis op20n : left_id 0 op2.\n\nHypothesis op2A : associative op2.\n\nHypothesis op2add : forall x y, op2 x y = x + y.\n\nCanonical Structure op2Mon : Monoid.law 0 :=\n  Monoid.Law op2A op20n op2n0.\n\n(** Prove that *)\nLemma ex_op2 : \\big[op2/0]_(i < 3) i = 3.\nProof.\nQed.\n\nEnd cex.\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># *)\n\n\n(** \n  ----\n  ** Exercise 6\n*)\n\n(** \n   Try to formalize the following problem \n*)\n\n(** \n  Given a parking  where the boolean indicates if the slot is occupied or not \n*)\n\nDefinition parking n := 'I_n -> 'I_n -> bool.\n\n(**\n   Number of cars at line i \n*)               \n\nDefinition sumL n (p : parking n) i := \\sum_(j < n) p i j.\n\n(**\n   Number of cars at column j \n*)\n\nDefinition sumC n (p : parking n) j := \\sum_(i < n) p i j.\n\n(**\n   Show that if 0 < n there is always two lines, or two columns, or a column and a line\n   that have the same numbers of cars \n*)\n\n(**\n#\n<script>\nalignWithTop = true;\ncurrent = 0;\nslides = [];\nfunction select_current() {\n  for (var i = 0; i < slides.length; i++) {\n    var s = document.getElementById('slideno' + i);\n    if (i == current) {\n      s.setAttribute('class','slideno selected');\n    } else {\n      s.setAttribute('class','slideno');\n    }\n  }\t\n}\nfunction init_slides() {\n  var toolbar = document.getElementById('panel-wrapper');\n  if (toolbar) {\n  var tools = document.createElement(\"div\");\n  var tprev = document.createElement(\"div\");\n  var tnext = document.createElement(\"div\");\n  tools.setAttribute('id','tools');\n  tprev.setAttribute('id','prev');\n  tprev.setAttribute('onclick','prev_slide();');\n  tnext.setAttribute('id','next');\n  tnext.setAttribute('onclick','next_slide();');\n  toolbar.appendChild(tools);\n  tools.appendChild(tprev);\n  tools.appendChild(tnext);\n  \n  slides = document.getElementsByClassName('slide');\n  for (var i = 0; i < slides.length; i++) {\n    var s = document.createElement(\"div\");\n    s.setAttribute('id','slideno' + i);\n    s.setAttribute('class','slideno');\n    s.setAttribute('onclick','goto_slide('+ i +');');\n    s.innerHTML = i;\n    tools.appendChild(s);\n  }\n  select_current();\n  } else {\n  //retry later\n  setTimeout(init_slides,100);\t  \n  }\n}\nfunction on_screen(rect) {\n  return (\n    rect.top >= 0 &&\n    rect.top <= (window.innerHeight || document.documentElement.clientHeight)\n  );\n}\nfunction update_scrolled(){\n  for (var i = 0; i < slides.length; i++) {\n    var rect = slides[i].getBoundingClientRect();\n      if (on_screen(rect)) {\n        current = i;\n        select_current();\t\n    }\n  }\n}\nfunction goto_slide(n) {\n  current = n;\n  var element = slides[current];\n  console.log(element);\n  element.scrollIntoView(alignWithTop);\n  select_current();\n}\nfunction next_slide() {\n  current++;\n  if (current >= slides.length) { current = slides.length - 1; }\n  var element = slides[current];\n  console.log(element);\n  element.scrollIntoView(alignWithTop);\n  select_current();\n}\nfunction prev_slide() {\n  current--;\n  if (current < 0) { current = 0; }\n  var element = slides[current];\n  element.scrollIntoView(alignWithTop);\n  select_current();\n}\nwindow.onload = init_slides;\nwindow.onscroll = update_scrolled;\n</script>\n# *)", "meta": {"author": "gares", "repo": "MathCompWS", "sha": "f06e05bea3694857ce22fc9671efd3971b195d4c", "save_path": "github-repos/coq/gares-MathCompWS", "path": "github-repos/coq/gares-MathCompWS/MathCompWS-f06e05bea3694857ce22fc9671efd3971b195d4c/exercise2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7173319170914823}}
{"text": " (** * Basics: Functional Programming in Coq *)\n\n(* REMINDER:\n\n          #####################################################\n          ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n          #####################################################\n\n   (See the [Preface] for why.)\n*)\n\n(* ################################################################# *)\n(** * Introduction *)\n\n(** The functional style of programming is founded on simple, everyday\n    mathematical intuition: If a procedure or method has no side\n    effects, then (ignoring efficiency) all we need to understand\n    about it is how it maps inputs to outputs -- that is, we can think\n    of it as just a concrete method for computing a mathematical\n    function.  This is one sense of the word \"functional\" in\n    \"functional programming.\"  The direct connection between programs\n    and simple mathematical objects supports both formal correctness\n    proofs and sound informal reasoning about program behavior.\n\n    The other sense in which functional programming is \"functional\" is\n    that it emphasizes the use of functions as _first-class_ values --\n    i.e., values that can be passed as arguments to other functions,\n    returned as results, included in data structures, etc.  The\n    recognition that functions can be treated as data gives rise to a\n    host of useful and powerful programming idioms.\n\n    Other common features of functional languages include _algebraic\n    data types_ and _pattern matching_, which make it easy to\n    construct and manipulate rich data structures, and _polymorphic\n    type systems_ supporting abstraction and code reuse.  Coq offers\n    all of these features.\n\n    The first half of this chapter introduces the most essential\n    elements of Coq's native functional programming language, called\n    _Gallina_.  The second half introduces some basic _tactics_ that\n    can be used to prove properties of Gallina programs. *)\n\n(* ################################################################# *)\n(** * Data and Functions *)\n\n(* ================================================================= *)\n(** ** Enumerated Types *)\n\n(** One notable aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers a powerful mechanism for defining new\n    data types from scratch, with all these familiar types as\n    instances.\n\n    Naturally, the Coq distribution comes with an extensive standard\n    library providing definitions of booleans, numbers, and many\n    common data structures like lists and hash tables.  But there is\n    nothing magic or primitive about these library definitions.  To\n    illustrate this, this course we will explicitly recapitulate\n    (almost) all the definitions we need, rather than getting them\n    from the standard library. *)\n\n(* ================================================================= *)\n(** ** Days of the Week *)\n\n(** To see how this definition mechanism works, let's start with\n    a very simple example.  The following declaration tells Coq that\n    we are defining a set of data values -- a _type_. *)\n\nInductive day : Set :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\n\n(** The new type is called [day], and its members are [monday],\n    [tuesday], etc.\n\n    Having defined [day], we can write functions that operate on\n    days. *)\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 \n Compute (next_weekday tuesday).\n\n(** One point to note is that the argument and return types of\n    this function are explicitly declared.  Like most functional\n    programming languages, Coq can often figure out these types for\n    itself when they are not given explicitly -- i.e., it can do _type\n    inference_ -- but we'll generally include them to make reading\n    easier. *)\n\n(** Having defined a function, we should next check that it\n    works on some examples.  There are actually three different ways\n    to do the examples in Coq.  First, we can use the command\n    [Compute] to evaluate a compound expression involving\n    [next_weekday]. *)\n\nCompute (next_weekday friday).\n(* ==> monday : day *)\n\nCompute (next_weekday (next_weekday saturday)).\n(* ==> tuesday : day *)\n\n(** (We show Coq's responses in comments, but, if you have a\n    computer handy, this would be an excellent moment to fire up the\n    Coq interpreter under your favorite IDE -- either CoqIde or Proof\n    General -- and try it for yourself.  Load this file, [Basics.v],\n    from the book's Coq sources, find the above example, submit it to\n    Coq, and observe the result.) *)\n\n(** Second, we can record what we _expect_ the result to be in the\n    form of a Coq example: *)\n\nTheorem test_next_weekday :\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n(** This declaration does two things: it makes an\n    assertion (that the second weekday after [saturday] is [tuesday]),\n    and it gives the assertion a name that can be used to refer to it\n    later.  Having made the assertion, we can also ask Coq to verify\n    it like this: *)\n\nProof. simpl. reflexivity. \nQed.\n\n(** The details are not important just now, but essentially this\n    can be read as \"The assertion we've just made can be proved by\n    observing that both sides of the equality evaluate to the same\n    thing.\"\n\n    Third, we can ask Coq to _extract_, from our [Definition], a\n    program in another, more conventional, programming\n    language (OCaml, Scheme, or Haskell) with a high-performance\n    compiler.  This facility is very interesting, since it gives us a\n    path from proved-correct algorithms written in Gallina to\n    efficient machine code.  (Of course, we are trusting the\n    correctness of the OCaml/Haskell/Scheme compiler, and of Coq's\n    extraction facility itself, but this is still a big step forward\n    from the way most software is developed today.) Indeed, this is\n    one of the main uses for which Coq was developed.  We'll come back\n    to this topic in later chapters. *)\n\n(* ================================================================= *)\n(** ** Homework Submission Guidelines *)\n\n(** If you are using _Software Foundations_ in a course, your\n    instructor may use automatic scripts to help grade your homework\n    assignments.  In order for these scripts to work correctly (and\n    give you that you get full credit for your work!), please be\n    careful to follow these rules:\n      - The grading scripts work by extracting marked regions of the\n        [.v] files that you submit.  It is therefore important that\n        you do not alter the \"markup\" that delimits exercises: the\n        Exercise header, the name of the exercise, the \"empty square\n        bracket\" marker at the end, etc.  Please leave this markup\n        exactly as you find it.\n      - Do not delete exercises.  If you skip an exercise (e.g.,\n        because it is marked \"optional,\" or because you can't solve it),\n        it is OK to leave a partial proof in your [.v] file; in\n        this case, please make sure it ends with [Admitted] (not, for\n        example [Abort]).\n      - It is fine to use additional definitions (of helper functions,\n        useful lemmas, etc.) in your solutions.  You can put these\n        between the exercise header and the theorem you are asked to\n        prove.\n      - If you introduce a helper lemma that you end up being unable\n        to prove, hence end it with [Admitted], then make sure to also\n        end the main theorem in which you use it with [Admitted], not\n        [Qed].  That will help you get partial credit, in case you\n        use that main theorem to solve a later exercise.\n\n    You will also notice that each chapter (like [Basics.v]) is\n    accompanied by a _test script_ ([BasicsTest.v]) that automatically\n    calculates points for the finished homework problems in the\n    chapter.  These scripts are mostly for the auto-grading\n    tools, but you may also want to use them to double-check\n    that your file is well formatted before handing it in.  In a\n    terminal window, either type \"[make BasicsTest.vo]\" or do the\n    following:\n\n       coqc -Q . LF Basics.v\n       coqc -Q . LF BasicsTest.v\n\n    See the end of this chapter for more information about how to interpret\n    the output of test scripts.\n\n    There is no need to hand in [BasicsTest.v] itself (or [Preface.v]).\n\n    If your class is using the Canvas system to hand in assignments...\n      - If you submit multiple versions of the assignment, you may\n        notice that they are given different names.  This is fine: The\n        most recent submission is the one that will be graded.\n      - To hand in multiple files at the same time (if more than one\n        chapter is assigned in the same week), you need to make a\n        single submission with all the files at once using the button\n        \"Add another file\" just above the comment box. *)\n\n(** The [Require Export] statement on the next line tells Coq to use\n    the [String] module from the standard library.  We'll use strings\n    ourselves in later chapters, but we need to [Require] it here so\n    that the grading scripts can use it for internal purposes. *)\n \nFrom Coq Require Export String.\n\n(* ================================================================= *)\n(** ** Booleans *)\n\n(** In a similar way, we can define the standard type [bool] of\n    booleans, with members [true] and [false]. *)\n\nInductive bool : Type :=\n  | true\n  \t| false.\n\n(** Functions over booleans can be defined in the same way as\n    above: *)\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n\nDefinition andb_1 (b1 b2 : bool) : bool\n  := match b1, b2 with\n       | true, true => true\n       | true, false => false\n       | false, true => false\n       | false, false => false\n      end.\n\nDefinition andb_2 (b1 b2 : bool) : bool\n  := match b1, b2 with\n       | true, true => true\n       | _, _ => false\n      end.\n\nDefinition andb_3 (b1 b2 : bool) : bool\n  := match b1 with\n       | true => match b2 with\n                        | true => true\n                        | false => false\n                        end\n       | false => false\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(** (Although we are rolling our own booleans here for the sake\n    of building up everything from scratch, Coq does, of course,\n    provide a default implementation of the booleans, together with a\n    multitude of useful functions and lemmas.  Whenever possible,\n    we'll name our own definitions and theorems so that they exactly\n    coincide with the ones in the standard library.) *)\n\n(** The last two of these illustrate Coq's syntax for\n    multi-argument function definitions.  The corresponding\n    multi-argument application syntax is illustrated by the following\n    \"unit tests,\" which constitute a complete specification -- a truth\n    table -- for the [orb] function: *)\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.\nTheorem andb12 :\nforall b1 b2 : bool, andb_1 b1 b2 = andb_2 b1 b2.\nProof.\nintros. destruct b1, b2; simpl; reflexivity.\nQed.\n(** We can also introduce some familiar infix syntax for the\n    boolean operations we have just defined. The [Notation] command\n    defines a new symbolic notation for an existing definition. *)\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5:  false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(** _A note on notation_: In [.v] files, we use square brackets\n    to delimit fragments of Coq code within comments; this convention,\n    also used by the [coqdoc] documentation tool, keeps them visually\n    separate from the surrounding text.  In the HTML version of the\n    files, these pieces of text appear in a [different font]. *)\n\n(** These examples are also an opportunity to introduce one more small\n    feature of Coq's programming language: conditional expressions... *)\n\nDefinition negb' (b:bool) : bool :=\n  if b then false\n  else true.\nCompute (negb' false).\nDefinition andb' (b1:bool) (b2:bool) : bool :=\n  if b1 then b2\n  else false.\n\nDefinition orb' (b1:bool) (b2:bool) : bool :=\n  if b1 then true\n  else b2.\n\n(** Coq's conditionals are exactly like those found in any other\n    language, with one small generalization.  Since the [bool] type is\n    not built in, Coq actually supports conditional expressions over\n    _any_ inductively defined type with exactly two clauses in its\n    definition.  The guard is considered true if it evaluates to the\n    \"constructor\" of the first clause of the [Inductive]\n    definition (which just happens to be called [true] in this case)\n    and false if it evaluates to the second. *)\n\n(** **** Exercise: 1 star, standard (nandb)\n\n    The command [Admitted] can be used as a placeholder for an\n    incomplete proof.  We use it in exercises to indicate the parts\n    that we're leaving for you -- i.e., your job is to replace\n    [Admitted]s with real proofs.\n\n    Remove \"[Admitted.]\" and complete the definition of the following\n    function; then make sure that the [Example] assertions below can\n    each be verified by Coq.  (I.e., fill in each proof, following the\n    model of the [orb] tests above, and make sure Coq accepts it.) The\n    function should return [true] if either or both of its inputs are\n    [false]. *)\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\nmatch b1, b2 with\n  |true, true => false\n  |_, _ => true\n\tend.\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(** [] *)\n\n(** **** Exercise: 1 star, standard (andb3)\n\n    Do the same for the [andb3] function below. This function should\n    return [true] when all of its inputs are [true], and [false]\n    otherwise. *)\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\nmatch b1, b2, b3 with\n  |true, true, true => true\n  |_, _, _ => false\n\tend.\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(** [] *)\n\n(* ================================================================= *)\n(** ** Types *)\n\n(** Every expression in Coq has a type, describing what sort of\n    thing it computes. The [Check] command asks Coq to print the type\n    of an expression. *)\n\nCheck true.\n(* ===> true : bool *)\n\n(** If the expression after [Check] is followed by a colon and a type,\n    Coq will verify that the type of the expression matches the given\n    type and halt with an error if not. *)\n\nCheck true\n  : bool.\nCheck (negb true)\n  : bool.\n\n(** Functions like [negb] itself are also data values, just like\n    [true] and [false].  Their types are called _function types_, and\n    they are written with arrows. *)\n\nCheck negb\n  : bool -> bool.\n\nCheck (andb true).\n\n(** The type of [negb], written [bool -> bool] and pronounced\n    \"[bool] arrow [bool],\" can be read, \"Given an input of type\n    [bool], this function produces an output of type [bool].\"\n    Similarly, the type of [andb], written [bool -> bool -> bool], can\n    be read, \"Given two inputs, each of type [bool], this function\n    produces an output of type [bool].\" *)\n\n(* ================================================================= *)\n(** ** New Types from Old *)\n\n(** The types we have defined so far are examples of \"enumerated\n    types\": their definitions explicitly enumerate a finite set of\n    elements, called _constructors_.  Here is a more interesting type\n    definition, where one of the constructors takes an argument: *)\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\n(** Let's look at this in a little more detail.\n\n    An [Inductive] definition does two things:\n\n    - It defines a set of new _constructors_. E.g., [red],\n      [primary], [true], [false], [monday], etc. are constructors.\n\n    - It groups them into a new named type, like [bool], [rgb], or\n      [color].\n\n    _Constructor expressions_ are formed by applying a constructor\n    to zero or more other constructors or constructor expressions,\n    obeying the declared number and types of the constructor arguments.\n    E.g.,\n        - [red]\n        - [true]\n        - [primary red]\n        - etc.\n    But not\n        - [red primary]\n        - [true red]\n        - [primary (primary red)]\n        - etc.\n*)\n\n(** In particular, the definitions of [rgb] and [color] say\n    which constructor expressions belong to the sets [rgb] and\n    [color]:\n\n    - [red], [green], and [blue] belong to the set [rgb];\n    - [black] and [white] belong to the set [color];\n    - if [p] is a constructor expression belonging to the set [rgb],\n      then [primary p] (pronounced \"the constructor [primary] applied\n      to the argument [p]\") is a constructor expression belonging to\n      the set [color]; and\n    - constructor expressions formed in these ways are the _only_ ones\n      belonging to the sets [rgb] and [color]. *)\n\n(** We can define functions on colors using pattern matching just as\n    we did for [day] and [bool]. *)\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary _ => false\n  end.\n\n(** Since the [primary] constructor takes an argument, a pattern\n    matching [primary] should include either a variable (as above --\n    note that we can choose its name freely) or a constant of\n    appropriate type (as below). *)\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\n(** The pattern \"[primary _]\" here is shorthand for \"the constructor\n    [primary] applied to any [rgb] constructor except [red].\"  (The\n    wildcard pattern [_] has the same effect as the dummy pattern\n    variable [p] in the definition of [monochrome].) *)\n\n(* ================================================================= *)\n(** ** Modules *)\n\n(** Coq provides a _module system_ to aid in organizing large\n    developments.  We won't need most of its features,\n    but one is useful: If we enclose a collection of declarations\n    between [Module X] and [End X] markers, then, in the remainder of\n    the file after the [End], these definitions are referred to by\n    names like [X.foo] instead of just [foo].  We will use this\n    feature to limit the scope of definitions, so that we are free to\n    reuse names. *)\n\nModule Playground.\n  Definition b : rgb := blue.\nEnd Playground.\n\nDefinition b : bool := true.\n\nCheck Playground.b : rgb.\nCheck b : bool.\n\n(* ================================================================= *)\n(** ** Tuples *)\n\nModule TuplePlayground.\n\n(** A single constructor with multiple parameters can be used\n    to create a tuple type. As an example, consider representing\n    the four bits in a nybble (half a byte). We first define\n    a datatype [bit] that resembles [bool] (using the\n    constructors [B0] and [B1] for the two possible bit values)\n    and then define the datatype [nybble], which is essentially\n    a tuple of four bits. *)\n\nInductive bit : Set :=\n  | B0\n  | B1. \n\nInductive nybble : Set :=\n  |  bits (b0 b1 b2 b3 : bit). \n\nCheck (bits B1 B0 B1 B0).\n\n(** The [bits] constructor acts as a wrapper for its contents.\n    Unwrapping can be done by pattern-matching, as in the [all_zero]\n    function which tests a nybble to see if all its bits are [B0].  We\n    use underscore (_) as a _wildcard pattern_ to avoid inventing\n    variable names that will not be used. *)\n\nDefinition all_zero (nb : nybble) : bool :=\n  match nb with\n  | bits B0 B0 B0 B0 => true\n  | _ => false\n  end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\n(* ===> false : bool *)\nCompute (all_zero (bits B0 B0 B0 B0)).\n(* ===> true : bool *)\n\nEnd TuplePlayground.\n\n(* ================================================================= *)\n(** ** Numbers *)\n\n(** We put this section in a module so that our own definition of\n    natural numbers does not interfere with the one from the\n    standard library.  In the rest of the book, we'll want to use\n    the standard library's. *)\n\nModule NatPlayground.\n\n(** All the types we have defined so far -- both \"enumerated\n    types\" such as [day], [bool], and [bit] and tuple types such as\n    [nybble] built from them -- are finite.  The natural numbers, on\n    the other hand, are an infinite set, so we'll need to use a\n    slightly richer form of type declaration to represent them.\n\n    There are many representations of numbers to choose from. We are\n    most familiar with decimal notation (base 10), using the digits 0\n    through 9, for example, to form the number 123.  You may have\n    encountered hexadecimal notation (base 16), in which the same\n    number is represented as 7B, or octal (base 8), where it is 173,\n    or binary (base 2), where it is 1111011. Using an enumerated type\n    to represent digits, we could use any of these as our\n    representation natural numbers. Indeed, there are circumstances\n    where each of these choices would be useful.\n\n    The binary representation is valuable in computer hardware because\n    the digits can be represented with just two distinct voltage\n    levels, resulting in simple circuitry. Analogously, we wish here\n    to choose a representation that makes _proofs_ simpler.\n\n    In fact, there is a representation of numbers that is even simpler\n    than binary, namely unary (base 1), in which only a single digit\n    is used (as one might do to count days in prison by scratching on\n    the walls). To represent unary numbers with a Coq datatype, we use\n    two constructors. The capital-letter [O] constructor represents\n    zero.  When the [S] constructor is applied to the representation\n    of the natural number n, the result is the representation of\n    n+1, where [S] stands for \"successor\" (or \"scratch\" if one is in\n    prison).  Here is the complete datatype definition. *)\n\nInductive nat : Set :=\n  | O : nat\n  | S : nat -> nat.\n\nCheck (S (S (S O))).\n\n(** With this definition, 0 is represented by [O], 1 by [S O],\n    2 by [S (S O)], and so on. *)\n\n(** Informally, the clauses of the definition can be read:\n      - [O] is a natural number (remember this is the letter \"[O],\"\n        not the numeral \"[0]\").\n      - [S] can be put in front of a natural number to yield another\n        one -- if [n] is a natural number, then [S n] is too. *)\n\n(** Again, let's look at this in a little more detail.  The definition\n    of [nat] says how expressions in the set [nat] can be built:\n\n    - the constructor expression [O] belongs to the set [nat];\n    - if [n] is a constructor expression belonging to the set [nat],\n      then [S n] is also a constructor expression belonging to the set\n      [nat]; and\n    - constructor expressions formed in these two ways are the only\n      ones belonging to the set [nat]. *)\n\n(** These conditions are the precise force of the [Inductive]\n    declaration.  They imply that the constructor expression [O], the\n    constructor expression [S O], the constructor expression [S (S\n    O)], the constructor expression [S (S (S O))], and so on all\n    belong to the set [nat], while other constructor expressions, like\n    [true], [andb true false], [S (S false)], and [O (O (O S))] do\n    not.\n\n    A critical point here is that what we've done so far is just to\n    define a _representation_ of numbers: a way of writing them down.\n    The names [O] and [S] are arbitrary, and at this point they have\n    no special meaning -- they are just two different marks that we\n    can use to write down numbers (together with a rule that says any\n    [nat] will be written as some string of [S] marks followed by an\n    [O]).  If we like, we can write essentially the same definition\n    this way: *)\n\nInductive nat' : Set :=\n  | stop : nat'\n  | tick  : nat' -> nat'.\n\n(** The _interpretation_ of these marks comes from how we use them to\n    compute. *)\n\n(** We can do this by writing functions that pattern match on\n    representations of natural numbers just as we did above with\n    booleans and days -- for example, here is the predecessor\n    function: *)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S m => m\n  end.\n\n(** The second branch can be read: \"if [n] has the form [S n']\n    for some [n'], then return [n'].\"  *)\n\n(** The following [End] command closes the current module, so\n    [nat] will refer back to the type from the standard library. *)\n\nCheck (S (S (S (S O)))).\n\nEnd NatPlayground.\n\n(** Because natural numbers are such a pervasive form of data,\n    Coq provides a tiny bit of built-in magic for parsing and printing\n    them: ordinary decimal numerals can be used as an alternative to\n    the \"unary\" notation defined by the constructors [S] and [O].  Coq\n    prints numbers in decimal form by default: *)\n\nCheck (S (S (S (S O)))).\n(* ===> 4 : nat *)\n\nDefinition minustwo (n : nat) : nat :=\n  match n with\n  | O => O\n  | S O => O\n  | S (S p) => p\n  end.\n\nCompute (minustwo 14).\n(* ===> 2 : nat *)\n\n(** The constructor [S] has the type [nat -> nat], just like functions\n    such as [pred] and [minustwo]: *)\n\nCheck S        : nat -> nat.\nCheck pred     : nat -> nat.\nCheck minustwo : nat -> nat.\n\n(** These are all things that can be applied to a number to yield a\n    number.  However, there is a fundamental difference between [S]\n    and the other two: functions like [pred] and [minustwo] are\n    defined by giving _computation rules_ -- e.g., the definition of\n    [pred] says that [pred 2] can be simplified to [1] -- while the\n    definition of [S] has no such behavior attached.  Although it is\n    _like_ a function in the sense that it can be applied to an\n    argument, it does not _do_ anything at all!  It is just a way of\n    writing down numbers.\n\n    (Think about standard decimal numerals: the numeral [1] is not a\n    computation; it's a piece of data.  When we write [111] to mean\n    the number one hundred and eleven, we are using [1], three times,\n    to write down a concrete representation of a number.)\n\n    Now let's go on and define some more functions over numbers.\n\n    For most interesting computations involving numbers, simple\n    pattern matching is not enough: we also need recursion.  For\n    example, to check that a number [n] is even, we may need to\n    recursively check whether [n-2] is even.  Such functions are\n    introduced with the keyword [Fixpoint] instead of [Definition]. *)\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\n(** We could define [odd] by a similar [Fixpoint] declaration, but\n    here is a simpler way: *)\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.\n\n(** (You may notice if you step through these proofs that\n    [simpl] actually has no effect on the goal -- all of the work is\n    done by [reflexivity].  We'll discuss why that is shortly.)\n\n    Naturally, we can also define multi-argument functions by\n    recursion.  *)\n\nModule NatPlayground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with\n  | O => m\n  | S p => S (plus p m)\n  end.\n\n(** Adding three to two now gives us five, as we'd expect. *)\n\nCompute (plus 13 21).\n(* ===> 5 : nat *)\n\nTheorem test_1 (n : nat) : O + n = n.\nProof.\n  simpl. reflexivity.\nQed.\n\n(** The steps of simplification that Coq performs can be\n    visualized as follows: *)\n\n(*      [plus 3 2]\n   i.e. [plus (S (S (S O))) (S (S O))]\n    ==> [S (plus (S (S O)) (S (S O)))]\n          by the second clause of the [match]\n    ==> [S (S (plus (S O) (S (S O))))]\n          by the second clause of the [match]\n    ==> [S (S (S (plus O (S (S O)))))]\n          by the second clause of the [match]\n    ==> [S (S (S (S (S O))))]\n          by the first clause of the [match]\n   i.e. [5]  *)\n\n(** As a notational convenience, if two or more arguments have\n    the same type, they can be written together.  In the following\n    definition, [(n m : nat)] means just the same as if we had written\n    [(n : nat) (m : nat)]. *)\n\nFixpoint mult (n m : nat) : nat :=\n  match n with\n  | O => O\n  | S p => plus m (mult p m)\n  end.\n\nExample test_mult1: (mult 3 3) = 9.\nProof. simpl. reflexivity.  Qed.\n\n(** You can match two expressions at once by putting a comma\n    between them: *)\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 NatPlayground2.\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\n(** **** Exercise: 1 star, standard (factorial)\n\n    Recall the standard mathematical factorial function:\n\n       factorial(0)  =  1\n       factorial(n)  =  n * factorial(n-1)     (if n>0)\n\n    Translate this into Coq. *)\n\nCompute (minus 23 12).\n\nFixpoint factorial (n:nat) : nat :=\n\tmatch n with\n\t| O => S(O)\n\t| S(X) => mult (S( X)) (factorial (X))\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(** [] *)\n\n(** Again, we can make numerical expressions easier to read and write\n    by introducing notations for addition, multiplication, and\n    subtraction. *)\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) : nat.\n\n(** (The [level], [associativity], and [nat_scope] annotations\n    control how these notations are treated by Coq's parser.  The\n    details are not important for present purposes, but interested\n    readers can refer to the \"More on Notation\" section at the end of\n    this chapter.)\n\n    Note that these declarations do not change the definitions we've\n    already made: they are simply instructions to the Coq parser to\n    accept [x + y] in place of [plus x y] and, conversely, to the Coq\n    pretty-printer to display [plus x y] as [x + y]. *)\n\n(** When we say that Coq comes with almost nothing built-in, we really\n    mean it: even equality testing is a user-defined operation!\n    Here is a function [eqb], which tests natural numbers for\n    [eq]uality, yielding a [b]oolean.  Note the use of nested\n    [match]es (we could also have used a simultaneous match, as we did\n    in [minus].) *)\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 eqb1 (n m : nat) : bool :=\n  match n, m with\n  | O, O => true\n  | O, S _ => false\n  | S _, O => false\n  | S n', S m' => eqb n' m'\n  end.\n\n(** Similarly, the [leb] function tests whether its first argument is\n    less than or equal to its second argument, yielding a boolean. *)\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(** We'll be using these (especially [eqb]) a lot, so let's give\n    them infix notations. *)\n\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nExample test_leb3': (4 <=? 2) = false.\nProof. simpl. reflexivity.  Qed.\n\n(** We now have two symbols that look like equality: [=] and\n    [=?].  We'll have much more to say about the differences and\n    similarities between them later. For now, the main thing to notice\n    is that [x = y] is a logical _claim_ -- a \"proposition\" -- that we\n    can try to prove, while [x =? y] is an _expression_ whose\n    value (either [true] or [false]) we can compute. *)\n\n(** **** Exercise: 1 star, standard (ltb)\n\n    The [ltb] function tests natural numbers for [l]ess-[t]han,\n    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for\n    this one, define it in terms of a previously defined\n    function.  (It can be done with just one previously defined\n    function, but you can use two if you want.) *)\n\nDefinition ltb (n m : nat) : bool:=\n\tif n =? m then false\n\telse n <=? m.\n\nDefinition ltb2 (n m : nat) : bool:=\n\tmatch n =? m with \n\t|true => false\n\t|false => n <=? m\n\tend.\n\t\n\t\n\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1:             (ltb 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_ltb2:             (ltb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ltb3:             (ltb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Simplification *)\n\n(** Now that we've defined a few datatypes and functions, let's\n    turn to stating and proving properties of their behavior.\n    Actually, we've already started doing this: each [Example] in the\n    previous sections makes a precise claim about the behavior of some\n    function on some particular inputs.  The proofs of these claims\n    were always the same: use [simpl] to simplify both sides of the\n    equation, then use [reflexivity] to check that both sides contain\n    identical values.\n\n    The same sort of \"proof by simplification\" can be used to prove\n    more interesting properties as well.  For example, the fact that\n    [0] is a \"neutral element\" for [+] on the left can be proved just\n    by observing that [0 + n] reduces to [n] no matter what [n] is -- a\n    fact that can be read directly off the definition of [plus]. *)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity.\nQed.\n\n(** (You may notice that the above statement looks different in\n    the [.v] file in your IDE than it does in the HTML rendition in\n    your browser. In [.v] files, we write the universal quantifier\n    [forall] using the reserved identifier \"forall.\"  When the [.v]\n    files are converted to HTML, this gets transformed into the\n    standard upside-down-A symbol.)\n\n    This is a good place to mention that [reflexivity] is a bit more\n    powerful than we have acknowledged. In the examples we have seen,\n    the calls to [simpl] were actually not needed, because\n    [reflexivity] can perform some simplification automatically when\n    checking that two sides are equal; [simpl] was just added so that\n    we could see the intermediate state -- after simplification but\n    before finishing the proof.  Here is a shorter proof of the\n    theorem: *)\n\nTheorem plus_O_n' : forall n : nat, 0 + n = n.\nProof.\n  intros n. reflexivity. Qed.\n\n(** Moreover, it will be useful to know that [reflexivity] does\n    somewhat _more_ simplification than [simpl] does -- for example,\n    it tries \"unfolding\" defined terms, replacing them with their\n    right-hand sides.  The reason for this difference is that, if\n    reflexivity succeeds, the whole goal is finished and we don't need\n    to look at whatever expanded expressions [reflexivity] has created\n    by all this simplification and unfolding; by contrast, [simpl] is\n    used in situations where we may have to read and understand the\n    new goal that it creates, so we would not want it blindly\n    expanding definitions and leaving the goal in a messy state.\n\n    The form of the theorem we just stated and its proof are almost\n    exactly the same as the simpler examples we saw earlier; there are\n    just a few differences.\n\n    First, we've used the keyword [Theorem] instead of [Example].\n    This difference is mostly a matter of style; the keywords\n    [Example] and [Theorem] (and a few others, including [Lemma],\n    [Fact], and [Remark]) mean pretty much the same thing to Coq.\n\n    Second, we've added the quantifier [forall n:nat], so that our\n    theorem talks about _all_ natural numbers [n].  Informally, to\n    prove theorems of this form, we generally start by saying \"Suppose\n    [n] is some number...\"  Formally, this is achieved in the proof by\n    [intros n], which moves [n] from the quantifier in the goal to a\n    _context_ of current assumptions. Note that we could have used\n    another identifier instead of [n] in the [intros] clause, (though\n    of course this might be confusing to human readers of the proof): *)\n\nTheorem plus_O_n'' : forall n : nat, 0 + n = n.\nProof.\n  intros m. reflexivity. Qed.\n\n(** The keywords [intros], [simpl], and [reflexivity] are examples of\n    _tactics_.  A tactic is a command that is used between [Proof] and\n    [Qed] to guide the process of checking some claim we are making.\n    We will see several more tactics in the rest of this chapter and\n    many more in future chapters. *)\n\n(** Other similar theorems can be proved with the same pattern. *)\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(** The [_l] suffix in the names of these theorems is\n    pronounced \"on the left.\" *)\n\n(** It is worth stepping through these proofs to observe how the\n    context and the goal change.  You may want to add calls to [simpl]\n    before [reflexivity] to see the simplifications that Coq performs\n    on the terms before checking that they are equal. *)\n\n(* ################################################################# *)\n(** * Proof by Rewriting *)\n\n(** The following theorem is a bit more interesting than the\n    ones we've seen: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m ->\n  n + n = m + m.\n\n(** Instead of making a universal claim about all numbers [n] and [m],\n    it talks about a more specialized property that only holds when\n    [n = m].  The arrow symbol is pronounced \"implies.\"\n\n    As before, we need to be able to reason by assuming we are given such\n    numbers [n] and [m].  We also need to assume the hypothesis\n    [n = m]. The [intros] tactic will serve to move all three of these\n    from the goal into assumptions in the current context.\n\n    Since [n] and [m] are arbitrary numbers, we can't just use\n    simplification to prove this theorem.  Instead, we prove it by\n    observing that, if we are assuming [n = m], then we can replace\n    [n] with [m] in the goal statement and obtain an equality with the\n    same expression on both sides.  The tactic that tells Coq to\n    perform this replacement is called [rewrite]. *)\n\nProof.\n  (* move both quantifiers into the context: *)\n  intros n m.\n  (* move the hypothesis into the context: *)\n  intros neqm.\n  (* rewrite the goal using the hypothesis: *)\n  rewrite neqm.\n  reflexivity. \nQed.\n\n(** The first line of the proof moves the universally quantified\n    variables [n] and [m] into the context.  The second moves the\n    hypothesis [n = m] into the context and gives it the name [H].\n    The third tells Coq to rewrite the current goal ([n + n = m + m])\n    by replacing the left side of the equality hypothesis [H] with the\n    right side.\n\n    (The arrow symbol in the [rewrite] has nothing to do with\n    implication: it tells Coq to apply the rewrite from left to right.\n    In fact, you can omit the arrow, and Coq will default to rewriting\n    in this direction.  To rewrite from right to left, you can use\n    [rewrite <-].  Try making this change in the above proof and see\n    what difference it makes.) *)\n\n(** **** Exercise: 1 star, standard (plus_id_exercise)\n\n    Remove \"[Admitted.]\" and fill in the proof. *)\n\n(* SOOMER: KK: [plus_id_exercise] contains multiple hypotheses, and at\n   least one student was confused about this. Maybe we can talk about\n   [->] being right-associative before it. *)\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros. rewrite <- H at 2. rewrite <- H0. reflexivity.\nQed.\n  \n(** [] *)\n\n(** The [Admitted] command tells Coq that we want to skip trying\n    to prove this theorem and just accept it as a given.  This can be\n    useful for developing longer proofs, since we can state subsidiary\n    lemmas that we believe will be useful for making some larger\n    argument, use [Admitted] to accept them on faith for the moment,\n    and continue working on the main argument until we are sure it\n    makes sense; then we can go back and fill in the proofs we\n    skipped.  Be careful, though: every time you say [Admitted] you\n    are leaving a door open for total nonsense to enter Coq's nice,\n    rigorous, formally checked world! *)\n\n(** The [Check] command can also be used to examine the statements of\n    previously declared lemmas and theorems.  The two examples below\n    are lemmas about multiplication that are proved in the standard\n    library.  (We will see how to prove them ourselves in the next\n    chapter.) *)\n\nCheck mult_n_O.\n(* ===> forall n : nat, 0 = n * 0 *)\n\nCheck mult_n_Sm.\n(* ===> forall n m : nat, n * m + n = n * S m *)\n\n(** We can use the [rewrite] tactic with a previously proved theorem\n    instead of a hypothesis from the context. If the statement of the\n    previously proved theorem involves quantified variables, as in the\n    example below, Coq tries to instantiate them by matching with the\n    current goal. *)\n\nTheorem mult_n_0_m_0 : forall p q : nat,\n  (p * 0) + (q * 0) = 0.\nProof.\n  intros p q. \n  rewrite <- (mult_n_O p).\n  rewrite <- (mult_n_O q).\n  reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard (mult_n_1)\n\n    Use those two lemmas about multiplication that we just checked to\n    prove the following theorem.  Hint: recall that [1] is [S O]. *)\n\nTheorem mult_n_1 : forall p : nat,\n  p * 1 = p.\nProof. \n\tintros p. \n\trewrite <- (mult_n_Sm p 0). \n\trewrite <- (mult_n_O p).\n\treflexivity.\n\tQed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Proof by Case Analysis *)\n\n(** Of course, not everything can be proved by simple\n    calculation and rewriting: In general, unknown, hypothetical\n    values (arbitrary numbers, booleans, lists, etc.) can block\n    simplification.  For example, if we try to prove the following\n    fact using the [simpl] tactic as above, we get stuck.  (We then\n    use the [Abort] command to give up on it for the moment.)*)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n  simpl.  (* does nothing! *)\nAbort.\n\n(** The reason for this is that the definitions of both [eqb]\n    and [+] begin by performing a [match] on their first argument.\n    But here, the first argument to [+] is the unknown number [n] and\n    the argument to [eqb] is the compound expression [n + 1]; neither\n    can be simplified.\n\n    To make progress, we need to consider the possible forms of [n]\n    separately.  If [n] is [O], then we can calculate the final result\n    of [(n + 1) =? 0] and check that it is, indeed, [false].  And if\n    [n = S n'] for some [n'], then, although we don't know exactly\n    what number [n + 1] represents, we can calculate that, at least,\n    it will begin with one [S], and this is enough to calculate that,\n    again, [(n + 1) =? 0] will yield [false].\n\n    The tactic that tells Coq to consider, separately, the cases where\n    [n = O] and where [n = S n'] is called [destruct]. *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n  destruct n as [| n'] eqn: E.\n  { reflexivity. }\n  { reflexivity.\n  }\n Qed.\n\n(** The [destruct] generates _two_ subgoals, which we must then\n    prove, separately, in order to get Coq to accept the theorem.\n\n    The annotation \"[as [| n']]\" is called an _intro pattern_.  It\n    tells Coq what variable names to introduce in each subgoal.  In\n    general, what goes between the square brackets is a _list of\n    lists_ of names, separated by [|].  In this case, the first\n    component is empty, since the [O] constructor is nullary (it\n    doesn't have any arguments).  The second component gives a single\n    name, [n'], since [S] is a unary constructor.\n\n    In each subgoal, Coq remembers the assumption about [n] that is\n    relevant for this subgoal -- either [n = 0] or [n = S n'] for some\n    n'.  The [eqn:E] annotation tells [destruct] to give the name [E]\n    to this equation.  Leaving off the [eqn:E] annotation causes Coq\n    to elide these assumptions in the subgoals.  This slightly\n    streamlines proofs where the assumptions are not explicitly used,\n    but it is better practice to keep them for the sake of\n    documentation, as they can help keep you oriented when working\n    with the subgoals.\n\n    The [-] signs on the second and third lines are called _bullets_,\n    and they mark the parts of the proof that correspond to the two\n    generated subgoals.  The part of the proof script that comes after\n    a bullet is the entire proof for the corresponding subgoal.  In\n    this example, each of the subgoals is easily proved by a single\n    use of [reflexivity], which itself performs some simplification --\n    e.g., the second one simplifies [(S n' + 1) =? 0] to [false] by\n    first rewriting [(S n' + 1)] to [S (n' + 1)], then unfolding\n    [eqb], and then simplifying the [match].\n\n    Marking cases with bullets is optional: if bullets are not\n    present, Coq simply asks you to prove each subgoal in sequence,\n    one at a time. But it is a good idea to use bullets.  For one\n    thing, they make the structure of a proof apparent, improving\n    readability. Also, bullets instruct Coq to ensure that a subgoal\n    is complete before trying to verify the next one, preventing\n    proofs for different subgoals from getting mixed up. These issues\n    become especially important in large developments, where fragile\n    proofs lead to long debugging sessions.\n\n    There are no hard and fast rules for how proofs should be\n    formatted in Coq -- e.g., where lines should be broken and how\n    sections of the proof should be indented to indicate their nested\n    structure.  However, if the places where multiple subgoals are\n    generated are marked with explicit bullets at the beginning of\n    lines, then the proof will be readable almost no matter what\n    choices are made about other aspects of layout.\n\n    This is also a good place to mention one other piece of somewhat\n    obvious advice about line lengths.  Beginning Coq users sometimes\n    tend to the extremes, either writing each tactic on its own line\n    or writing entire proofs on a single line.  Good style lies\n    somewhere in the middle.  One reasonable guideline is to limit\n    yourself to 80-character lines.\n\n    The [destruct] tactic can be used with any inductively defined\n    datatype.  For example, we use it next to prove that boolean\n    negation is involutive -- i.e., that negation is its own\n    inverse. *)\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b eqn:E.\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** Note that the [destruct] here has no [as] clause because\n    none of the subcases of the [destruct] need to bind any variables,\n    so there is no need to specify any names.  In fact, we can omit\n    the [as] clause from _any_ [destruct] and Coq will fill in\n    variable names automatically.  This is generally considered bad\n    style, since Coq often makes confusing choices of names when left\n    to its own devices.\n\n    It is sometimes useful to invoke [destruct] inside a subgoal,\n    generating yet more proof obligations. In this case, we use\n    different kinds of bullets to mark goals on different \"levels.\"\n    For example: *)\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\n(** Each pair of calls to [reflexivity] corresponds to the\n    subgoals that were generated after the execution of the [destruct c]\n    line right above it. *)\n\n(** Besides [-] and [+], we can use [*] (asterisk) or any repetition\n    of a bullet symbol (e.g. [--] or [***]) as a bullet.  We can also\n    enclose sub-proofs in curly braces: *)\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  }\n  { destruct c eqn:Ec.\n    { reflexivity. }\n    { reflexivity. }\n  }\nQed.\n\n(** Since curly braces mark both the beginning and the end of a proof,\n    they can be used for multiple subgoal levels, as this example\n    shows. Furthermore, curly braces allow us to reuse the same bullet\n    shapes at multiple levels in a proof. The choice of braces,\n    bullets, or a combination of the two is purely a matter of\n    taste. *)\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; reflexivity. }\n    { destruct d eqn:Ed; reflexivity. }\n  }\n  { destruct c eqn:Ec.\n    { destruct d eqn:Ed; reflexivity. }\n    { destruct d eqn:Ed; reflexivity. }\n  }\nQed.\n\n(** **** Exercise: 2 stars, standard (andb_true_elim2)\n\n    Prove the following claim, marking cases (and subcases) with\n    bullets when you use [destruct]. Hint: delay introducing the\n    hypothesis until after you have an opportunity to simplify it. *)\n\nPrint andb.\nTheorem andb_true_elim2 : forall b c : bool,\n  andb b c \t= true -> c = true.\nProof.\n  intros [|] [|]; simpl; try reflexivity;\n  intros H; rewrite H; reflexivity.\nQed.\n\n(** [] *)\n\n(** Before closing the chapter, let's mention one final\n    convenience.  As you may have noticed, many proofs perform case\n    analysis on a variable right after introducing it:\n\n       intros x y. destruct y as [|y] eqn:E.\n\n    This pattern is so common that Coq provides a shorthand for it: we\n    can perform case analysis on a variable when introducing it by\n    using an intro pattern instead of a variable name. For instance,\n    here is a shorter proof of the [plus_1_neq_0] theorem\n    above.  (You'll also note one downside of this shorthand: we lose\n    the equation recording the assumption we are making in each\n    subgoal, which we previously got from the [eqn:E] annotation.) *)\n\nTheorem plus_1_neq_0' : forall n : nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.  Qed.\n\n(** If there are no constructor arguments that need names, we can just\n    write [[]] to get the case analysis. *)\n\nTheorem andb_commutative'' :\n  forall b c, andb b c = andb c b.\nProof.\n  intros [|] [|]; reflexivity.\nQed.\n\n(** **** Exercise: 1 star, standard (zero_nbeq_plus_1) *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  0 =? (n + 1) = false.\nProof.\n\tintros [|]. \n\t-reflexivity.\n\t-reflexivity.\nQed.\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** More on Notation (Optional) *)\n\n(** (In general, sections marked Optional are not needed to follow the\n    rest of the book, except possibly other Optional sections.  On a\n    first reading, you might want to skim these sections so that you\n    know what's there for future reference.)\n\n    Recall the notation definitions for infix plus and times: *)\n\nNotation \"x + y\" := (plus 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(** For each notation symbol in Coq, we can specify its _precedence\n    level_ and its _associativity_.  The precedence level [n] is\n    specified by writing [at level n]; this helps Coq parse compound\n    expressions.  The associativity setting helps to disambiguate\n    expressions containing multiple occurrences of the same\n    symbol. For example, the parameters specified above for [+] and\n    [*] say that the expression [1+2*3*4] is shorthand for\n    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and\n    _left_, _right_, or _no_ associativity.  We will see more examples\n    of this later, e.g., in the [Lists]\n    chapter.\n\n    Each notation symbol is also associated with a _notation scope_.\n    Coq tries to guess what scope is meant from context, so when it\n    sees [S(O*O)] it guesses [nat_scope], but when it sees the product\n    type [bool*bool] (which we'll see in later chapters) it guesses\n    [type_scope].  Occasionally, it is necessary to help it out with\n    percent-notation by writing [(x*y)%nat], and sometimes in what Coq\n    prints it will use [%nat] to indicate what scope a notation is in.\n\n    Notation scopes also apply to numeral notation ([3], [4], [5], [42],\n    etc.), so you may sometimes see [0%nat], which means [O] (the\n    natural number [0] that we're using in this chapter), or [0%Z],\n    which means the integer zero (which comes from a different part of\n    the standard library).\n\n    Pro tip: Coq's notation mechanism is not especially powerful.\n    Don't expect too much from it. *)\n\n(* ================================================================= *)\n(** ** Fixpoints and Structural Recursion (Optional) *)\n\n(** Here is a copy of the definition of addition: *)\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\n(** When Coq checks this definition, it notes that [plus'] is\n    \"decreasing on 1st argument.\"  What this means is that we are\n    performing a _structural recursion_ over the argument [n] -- i.e.,\n    that we make recursive calls only on strictly smaller values of\n    [n].  This implies that all calls to [plus'] will eventually\n    terminate.  Coq demands that some argument of _every_ [Fixpoint]\n    definition is \"decreasing.\"\n\n    This requirement is a fundamental feature of Coq's design: In\n    particular, it guarantees that every function that can be defined\n    in Coq will terminate on all inputs.  However, because Coq's\n    \"decreasing analysis\" is not very sophisticated, it is sometimes\n    necessary to write functions in slightly unnatural ways. *)\n\n(** **** Exercise: 2 stars, standard, optional (decreasing)\n\n    To get a concrete sense of this, find a way to write a sensible\n    [Fixpoint] definition (of a simple function on numbers, say) that\n    _does_ terminate on all inputs, but that Coq will reject because\n    of this restriction.  (If you choose to turn in this optional\n    exercise as part of a homework assignment, make sure you comment\n    out your solution so that it doesn't cause Coq to reject the whole\n    file!) *)\n\nFail Fixpoint plus2 (n m : nat) : nat :=\n  match n with\n  | O => m\n  | S O => S (plus2 O m)\n  | S (S n) => S (plus2 (S n) m)\n  end.\n\n\n\n(* ################################################################# *)\n(** * More Exercises *)\n\n(** **** Exercise: 1 star, standard (identity_fn_applied_twice)\n\n    Use the tactics you have learned so far to prove the following\n    theorem about boolean functions. *)\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\tintros. do 2 rewrite H. reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, standard (negation_fn_applied_twice)\n\n    Now state and prove a theorem [negation_fn_applied_twice] similar\n    to the previous one but where the second hypothesis says that the\n    function [f] has the property that [f x = negb x]. *)\n\nPrint negb.\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\tintros. do 2 rewrite H. destruct b0; reflexivity.\nQed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_negation_fn_applied_twice : option (nat*string) := None.\n(** (The last definition is used by the autograder.)\n\n    [] *)\n\n(** **** Exercise: 3 stars, standard, optional (andb_eq_orb)\n\n    Prove the following theorem.  (Hint: This one can be a bit tricky,\n    depending on how you approach it.  You will probably need both\n    [destruct] and [rewrite], but destructing everything in sight is\n    not the best way.) *)\n\n\nPrint test_orb1.\nPrint test_orb2.\nPrint test_orb3.\nPrint test_orb4.\n\n\n\nTheorem andb_eq_orb :\n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n\tintros []; simpl; intros; rewrite H; reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (binary)\n\n    We can generalize our unary representation of natural numbers to\n    the more efficient binary representation by treating a binary\n    number as a sequence of constructors [B0] and [B1] (representing 0s\n    and 1s), terminated by a [Z]. For comparison, in the unary\n    representation, a number is a sequence of [S] constructors terminated\n    by an [O].\n\n    For example:\n\n        decimal               binary                          unary\n           0                       Z                              O\n           1                    B1 Z                            S O\n           2                B0 (B1 Z)                        S (S O)\n           3                B1 (B1 Z)                     S (S (S O))\n           4            B0 (B0 (B1 Z))                 S (S (S (S O)))\n           5            B1 (B0 (B1 Z))              S (S (S (S (S O))))\n           6            B0 (B1 (B1 Z))           S (S (S (S (S (S O)))))\n           7            B1 (B1 (B1 Z))        S (S (S (S (S (S (S O))))))\n           8        B0 (B0 (B0 (B1 Z)))    S (S (S (S (S (S (S (S O)))))))\n\n    Note that the low-order bit is on the left and the high-order bit\n    is on the right -- the opposite of the way binary numbers are\n    usually written.  This choice makes them easier to manipulate. *)\n\nInductive bin : Type :=\n  | Z\n  | B0 (n : bin)\n  | B1 (n : bin).\n\n(** Complete the definitions below of an increment function [incr]\n    for binary numbers, and a function [bin_to_nat] to convert\n    binary numbers to unary numbers. *)\n\nFixpoint incr (m:bin) : bin :=\n\tmatch m with\n\t|\tZ => B1 Z\n\t|\tB0 m => B1 m\n\t| B1 m => B0 (incr m)\n\tend.\n\nFixpoint bin_to_nat (m:bin) : nat :=\n\tmatch m with\n\t| Z => O\n\t|\tB0 m => 2 * (bin_to_nat m)\n\t| B1 m => 2 * (bin_to_nat m) + 1\n\tend.\n\n(** The following \"unit tests\" of your increment and binary-to-unary\n    functions should pass after you have defined those functions correctly.\n    Of course, unit tests don't fully demonstrate the correctness of\n    your functions!  We'll return to that thought at the end of the\n    next chapter. *)\n\nExample test_bin_incr1 : (incr (B1 Z)) = B0 (B1 Z).\nProof. reflexivity. Qed.\n\nExample test_bin_incr2 : (incr (B0 (B1 Z))) = B1 (B1 Z).\nProof. reflexivity. Qed.\n\nExample test_bin_incr3 : (incr (B1 (B1 Z))) = B0 (B0 (B1 Z)).\nProof. reflexivity. Qed.\n\nExample test_bin_incr4 : bin_to_nat (B0 (B1 Z)) = 2.\nProof. reflexivity. Qed.\n\nExample test_bin_incr5 :\n        bin_to_nat (incr (B1 Z)) = 1 + bin_to_nat (B1 Z).\nProof. reflexivity. Qed.\n\nExample test_bin_incr6 :\n        bin_to_nat (incr (incr (B1 Z))) = 2 + bin_to_nat (B1 Z).\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Testing Your Solutions *)\n\n(** Each SF chapter comes with a test file containing scripts that\n    check whether you have solved the required exercises. If you're\n    using SF as part of a course, your instructors will likely be\n    running these test files to autograde your solutions. You can also\n    use these test files, if you like, to make sure you haven't missed\n    anything.\n\n    Important: This step is _optional_: if you've completed all the\n    non-optional exercises and Coq accepts your answers, this already\n    shows that you are in good shape.\n\n    The test file for this chapter is [BasicsTest.v]. To run it, make\n    sure you have saved [Basics.v] to disk.  Then do this:\n\n       coqc -Q . LF Basics.v\n       coqc -Q . LF BasicsTest.v\n\n    If you accidentally deleted an exercise or changed its name, then\n    [make BasicsTest.vo] will fail with an error that tells you the\n    name of the missing exercise.  Otherwise, you will get a lot of\n    useful output:\n\n    - First will be all the output produced by [Basics.v] itself.  At\n      the end of that you will see [COQC BasicsTest.v].\n\n    - Second, for each required exercise, there is a report that tells\n      you its point value (the number of stars or some fraction\n      thereof if there are multiple parts to the exercise), whether\n      its type is ok, and what assumptions it relies upon.\n\n      If the _type_ is not [ok], it means you proved the wrong thing:\n      most likely, you accidentally modified the theorem statement\n      while you were proving it.  The autograder won't give you any\n      points for that, so make sure to correct the theorem.\n\n      The _assumptions_ are any unproved theorems which your solution\n      relies upon.  \"Closed under the global context\" is a fancy way\n      of saying \"none\": you have solved the exercise. (Hooray!)  On\n      the other hand, a list of axioms means you haven't fully solved\n      the exercise. (But see below regarding \"Allowed Axioms.\") If the\n      exercise name itself is in the list, that means you haven't\n      solved it; probably you have [Admitted] it.\n\n    - Third, you will see the maximum number of points in standard and\n      advanced versions of the assignment.  That number is based on\n      the number of stars in the non-optional exercises.\n\n    - Fourth, you will see a list of \"Allowed Axioms\".  These are\n      unproved theorems that your solution is permitted to depend\n      upon.  You'll probably see something about\n      [functional_extensionality] for this chapter; we'll cover what\n      that means in a later chapter.\n\n    - Finally, you will see a summary of whether you have solved each\n      exercise.  Note that summary does not include the critical\n      information of whether the type is ok (that is, whether you\n      accidentally changed the theorem statement): you have to look\n      above for that information.\n\n    Exercises that are manually graded will also show up in the\n    output.  But since they have to be graded by a human, the test\n    script won't be able to tell you much about them.  *)\n\n(* 2021-08-11 15:08 *)\n", "meta": {"author": "I-Iaroslav", "repo": "Software-Foundations", "sha": "7655d26d1f7f97cf82beb6ecad0e47aa54d86af0", "save_path": "github-repos/coq/I-Iaroslav-Software-Foundations", "path": "github-repos/coq/I-Iaroslav-Software-Foundations/Software-Foundations-7655d26d1f7f97cf82beb6ecad0e47aa54d86af0/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7173319057375396}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (lf1 : natural) : natural :=\n  mult (Succ y) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj203_coqofml_5gOc2D.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7173146468082477}}
{"text": "Require Import Znumtheory Zdiv ZArith.\nLocal Open Scope Z_scope.\n\nImport N2Z.\n\n(* Lemmas I needed over what the Coq library supplies *)\n\nLemma div_swap_l: forall a b c, a <> 0 -> (a | b) -> b = a * c <-> b / a = c.\nProof.\n  intros a b c a_neq_0 a_div_b.\n  split.\n  - destruct a_div_b as [x def_a].\n    intros def_b.\n    rewrite def_a.\n    rewrite Z_div_mult_full; auto.\n    rewrite def_a, Z.mul_comm in def_b.\n    rewrite Z.mul_cancel_l in def_b; auto.\n  - intros def_b.\n    rewrite <- def_b.\n    rewrite <- Z.divide_div_mul_exact; auto.\n    rewrite Z.mul_comm.\n    symmetry.\n    apply Z_div_mult_full; auto.\nQed.\n\nLemma div_positive: forall a b, a > 0 -> b > 0 -> (a | b) -> b / a > 0.\nProof.\n  intros a b a_gt_0 b_gt_0.\n  intros a_div_b.\n  destruct a_div_b as [x def_of_x].\n  cut (x > 0). intro Cut.\n  rewrite def_of_x, Z_div_mult_full; omega.\n  rewrite def_of_x in b_gt_0.\n  apply (Zmult_gt_reg_r x 0 a); auto.\nQed.\n\nLemma square_le_lemma: forall m, m > 0 -> (m / 2) * (m / 2) <=  (m * m) / 4.\nProof.\n  intros m m_gt_0.\n  replace 4 with (2 * 2) by auto.\n  apply Zdiv_le_lower_bound; [omega | auto].\n  replace ((m / 2) * (m / 2) * (2 * 2)) with ((2 * (m / 2)) * (2 * (m / 2))) by ring.\n  apply Z.square_le_mono_nonneg; [auto | apply Z.mul_div_le; omega].\n  replace 0 with (2 * 0) by ring.\n  apply Zmult_le_compat_l; [apply Zdiv_le_lower_bound | auto]; omega.\nQed.\n\nLemma square_gt_0: forall n, n <> 0 -> n * n > 0.\nProof.\n  intros n n_not_zero.\n  destruct n;\n    [contradict n_not_zero; reflexivity |\n     auto |\n     rewrite <- Pos2Z.opp_pos, Z.mul_opp_opp];\n    rewrite <- Pos2Z.inj_mul; apply Zgt_pos_0.\nQed.\n\nLemma Zgt_ge_incl: forall n m: Z, m > n -> m >= n.\n  intros n m n_lt_m.\n  apply Z.gt_lt in n_lt_m.\n  apply Z.lt_le_incl in n_lt_m.\n  rewrite Z.ge_le_iff.\n  assumption.\nQed.\n\nLemma square_ge_0: forall n, n * n >= 0.\nProof.\n  intros n.\n  destruct n;\n    [omega |\n     auto |\n     rewrite <- Pos2Z.opp_pos, Z.mul_opp_opp];\n    rewrite <- Pos2Z.inj_mul; apply Zgt_ge_incl; apply Zgt_pos_0.\nQed.\n\nLemma sum_of_squares_eq_0: forall a b, a * a + b * b = 0 -> a = 0 /\\ b = 0.\nProof.\n  intros a b.\n  intros eq_0.\n  remember (square_ge_0 a).\n  remember (square_ge_0 b).\n  assert (b * b = 0) by omega.\n  rewrite H, Z.add_0_r in eq_0.\n  rewrite Z.eq_square_0 in H.\n  rewrite Z.eq_square_0 in eq_0.\n  split; assumption.\nQed.\n\nLemma sum_of_squares_gt_0: forall a b, a * a + b * b > 0 -> a * a > 0 \\/ b * b > 0.\nProof.\n  intros a b gt_0.\n  omega.\nQed.\n\n(* Begin descent apparatus *)\n\nDefinition descent_modulus a m :=\n  let m' := a mod m in\n  if Z_le_dec (2 * m') m then\n    m'\n  else\n    (a mod m) - m.\n\nLemma descent_modulus_le_m_div_2 : forall a m,\n    m > 0 -> Z.abs (descent_modulus a m) <= m / 2.\nProof.\n  intros a m m_gt_1.\n  unfold descent_modulus.\n  assert (m > 0) as m_gt_0 by omega.\n  remember (Z_mod_lt a _ m_gt_0) as m'_bound.\n  destruct Heqm'_bound.\n  remember (a mod m) as m'.\n  destruct (Z_le_dec (2 * m') m).\n  - assert (0 <= m') by omega.\n    apply Z.abs_eq_iff in H.\n    rewrite H.\n    apply Zdiv_le_lower_bound; omega.\n  - assert (a mod m - m <= 0) as HQuantityNegative by omega.\n    rewrite <- Heqm' in HQuantityNegative.\n    apply Z.abs_neq_iff in HQuantityNegative.\n    rewrite HQuantityNegative.\n    apply Zdiv_le_lower_bound; omega.\nQed.\n\nLemma descent_modulus_equiv_a_mod_m : forall a m,\n    m > 0 -> (descent_modulus a m) mod m = a mod m.\nProof.\n  intros a m m_gt_0.\n  unfold descent_modulus.\n  destruct (Z_le_dec (2 * (a mod m)) m).\n  - apply (Z_mod_lt a m) in m_gt_0.\n    rewrite Zmod_mod; reflexivity.\n  - apply (Z_mod_lt a m) in m_gt_0.\n    rewrite Zminus_mod, Z_mod_same_full, Z.sub_0_r.\n    repeat rewrite Zmod_mod.\n    reflexivity.\nQed.\n\nLemma descent_modulus_eq_0: forall a m, m > 0 -> descent_modulus a m = 0 -> (m | a).\nProof.\n  intros a m m_not_0.\n  unfold descent_modulus.\n  destruct (Z_le_dec (2 * (a mod m)) m).\n  - intros eq_0; apply Zmod_divide; omega.\n  - intros eq_0. apply Zmod_divide; [omega | ].\n    rewrite Z.sub_move_r in eq_0.\n    simpl in eq_0.\n    remember (Z_mod_lt a m).\n    omega.\nQed.\n\n(* N = a^2 + b^2 = m * q, return (c^2 + d^2)k*q, k < m *)\nDefinition descent a b q :=\n  let N := a * a + b * b in\n  let m := N / q in\n  if Z.eq_dec m 1 then\n    (1, a, b)\n  else\n    let (u, v) := (descent_modulus a m, descent_modulus b m) in\n    ((u * u + v * v) / m, (a * u + b * v)/m, (b * u - a * v)/m).\n\n(* 3^2 + 2^2 = 13 *)\n(* 5^2 + 1 = 2 * 13 *)\n\n(* Examples of the descent step *)\nCompute (descent 5 1 13).\nCompute (descent 12 1 29).\nCompute (descent (-7) 3 29).\nCompute (descent 442 1 953).\nCompute (descent 69 2 953).\nCompute (descent (-15) (-41) 953).\n\nLemma descent_inequality: forall m,\n    m > 0 -> (m / 2) * (m / 2) + (m / 2) * (m / 2) < m * m.\nProof.\n  intros m m_gt_0.\n  cut (((m * m) / 4) + (m * m) / 4 < m * m).\n  intros Cut.\n  remember (square_le_lemma m m_gt_0).\n  omega.\n  cut ((m * m / 4 + m * m / 4) <= (m * m / 2)).\n  intros Cut.\n  apply (Z.le_lt_trans _ (m * m / 2) _ Cut).\n  apply Z_div_lt; [omega | apply Zmult_gt_0_compat; auto].\n  replace ((m * m / 4) + (m * m / 4)) with (2 * (m * m / 4)) by ring.\n  apply Zdiv_le_lower_bound; [omega | auto].\n  replace (2 * (m * m / 4) * 2) with (4 * (m * m / 4)) by ring.\n  apply Z_mult_div_ge; omega.\nQed.\n\nLemma descent_nonzero_inequality: forall u v, ~ (u * u + v * v) = 0 -> u * u + v * v > 0.\nProof.\n  intros u v c.\n  remember (square_ge_0 u).\n  remember (square_ge_0 v).\n  omega.\nQed.\n\n\nLemma descent_nonzero: forall a b q N m,\n  prime q ->\n  q > 0 -> N > 0 ->\n  N = (a * a + b * b) ->\n  (q | N) ->\n  m = N / q ->\n  1 < m < q ->\n  descent_modulus a m * descent_modulus a m + descent_modulus b m * descent_modulus b m > 0.\nProof.\n  intros a b q N m q_prime q_gt_0 N_gt_0 def_N q_divides_N def_m mt_gt_1.\n  remember (descent_modulus a m) as u.\n  remember (descent_modulus b m) as v.\n  apply descent_nonzero_inequality.\n  assert (u * u + v * v = 0 -> (m | a) /\\ (m | b)) as zero_means_m_divides_a_and_b.\n  intros eq_0.\n  rewrite Hequ, Heqv in eq_0.\n  apply sum_of_squares_eq_0 in eq_0.\n  destruct eq_0 as [H I]; apply descent_modulus_eq_0 in H; apply descent_modulus_eq_0 in I;\n    [| omega | omega | omega ]; auto.\n  assert ((m | a) /\\ (m | b) -> (m * m | a * a + b * b)) as divide_one_divide_all.\n  intros [m_div_a m_div_b].\n  destruct m_div_a as [k def_k].\n  destruct m_div_b as [j def_j].\n  exists (k * k + j * j).\n  rewrite def_k, def_j; ring.\n  assert ((m * m | a * a + b * b) -> (m | q)) as divide_all_implies_divide_prime.\n  (* we know q * m = N *)\n  (* we know m * m divides N *)\n  (* so m divides q *)\n  rewrite <- def_N.\n  symmetry in def_m.\n  rewrite <- (div_swap_l q N) in def_m; [|omega|]; auto.\n  rewrite def_m.\n  rewrite Z.mul_divide_cancel_r; [|omega]; auto.\n  unfold not.\n  intros eq_0.\n  apply zero_means_m_divides_a_and_b in eq_0.\n  apply divide_one_divide_all in eq_0.\n  apply divide_all_implies_divide_prime in eq_0.\n  apply (prime_divisors q q_prime m) in eq_0.\n  omega.\nQed.\n\nLemma div_swap_lt_l: forall a b c, a > 0 -> (a | c) -> a * b < c <-> b < c / a.\nProof.\n  intros a b c a_gt_0 a_div_c.\n  destruct a_div_c as [x def_c].\n  rewrite def_c.\n  rewrite (Z.mul_comm a b).\n  rewrite Z_div_mult_full; [|omega]; auto.\n  rewrite <- Z.mul_lt_mono_pos_r; omega.\nQed.\n\nLemma div_swap_lt_r: forall a b c, a > 0 -> (a | b) -> b < a * c <-> b / a < c.\nProof.\n  intros a b c a_gt_0 a_div_c.\n  destruct a_div_c as [x def_c].\n  rewrite def_c.\n  rewrite Z_div_mult_full; [|omega]; auto.\n  rewrite (Z.mul_comm x a).\n  rewrite <- Z.mul_lt_mono_pos_l; omega.\nQed.\n\n(* Prove that the descent step either terminates or produces a smaller integer *)\nTheorem descent_smaller: forall a b q N m,\n  prime q ->\n  q > 0 -> N > 0 ->\n  N = (a * a + b * b) ->\n  (q | N) ->\n  m = N / q ->\n  m < q ->\n  forall k t1 t2,  (k, t1, t2) = descent a b q ->\n  k = 1 \\/ (0 < k < m).\nProof.\n  intros a b q N m q_prime q_gt_0 N_gt_0 def_N q_div_N def_m m_lt_q k u v.\n  assert (m > 0) as m_gt_0.\n  rewrite def_m; apply div_positive; auto.\n  unfold descent.\n  rewrite <- def_N, <- def_m.\n  destruct (Z.eq_dec m 1); intros descent_def; inversion descent_def.\n  - left; reflexivity.\n  - right.\n    split.\n    rewrite <- div_swap_lt_l; [ | omega | ]; auto.\n    remember (descent_nonzero a b q N m q_prime q_gt_0 N_gt_0 def_N q_div_N def_m); omega.\n    rewrite <- Z.mod_divide; [|omega].\n    rewrite Zplus_mod.\n    rewrite (Zmult_mod (descent_modulus a m)).\n    rewrite (Zmult_mod (descent_modulus b m)).\n    repeat rewrite descent_modulus_equiv_a_mod_m; auto.\n    repeat rewrite <- Zmult_mod.\n    repeat rewrite <- Zplus_mod.\n    rewrite <- def_N, Z.mod_divide; [|omega].\n    exists q.\n    rewrite div_swap_l; [auto | omega |assumption].\n    rewrite <- (Z.abs_square (descent_modulus a m)).\n    rewrite <- (Z.abs_square (descent_modulus b m)).\n    apply Z.div_lt_upper_bound; [apply Z.gt_lt; apply m_gt_0; auto | auto].\n    remember (descent_modulus_le_m_div_2 a m m_gt_0).\n    remember (descent_modulus_le_m_div_2 b m m_gt_0).\n    assert ((Z.abs (descent_modulus a m)) *\n            (Z.abs (descent_modulus a m)) <= (m / 2) * (m / 2)).\n    apply Z.square_le_mono_nonneg; [apply Z.abs_nonneg | auto].\n    assert ((Z.abs (descent_modulus b m)) *\n            (Z.abs (descent_modulus b m)) <= (m / 2) * (m / 2)).\n    apply Z.square_le_mono_nonneg; [apply Z.abs_nonneg | auto].\n    assert (Z.abs (descent_modulus a m) *\n            Z.abs (descent_modulus a m) +\n            Z.abs (descent_modulus b m) *\n            Z.abs (descent_modulus b m) <= (m / 2) * (m / 2) + (m / 2) * (m / 2)) by omega.\n    apply (Z.le_lt_trans _ _ _ H4).\n    apply descent_inequality; auto.\nQed.\n\nLemma diophantine_identity:\n  forall a b c d, (a * a + b * b) * (c * c + d * d) = (a * c + b * d) * (a * c + b * d) + (b * c - a * d) * (b * c - a * d).\nProof.\n  intros; ring.\nQed.\n\nLemma descent_div_sum: forall a b q N m,\n  q > 0 -> N > 0 ->\n  N = (a * a + b * b) ->\n  m = N / q ->\n  (q | N) ->\n  (m | (descent_modulus a m * descent_modulus a m + descent_modulus b m * descent_modulus b m)).\nProof.\n  intros a b q N m q_gt_0 N_gt_0 def_N def_m q_div_N.\n  assert (m > 0) as m_gt_0.\n  rewrite def_m; apply div_positive; auto.\n  rewrite <- Z.mod_divide; [|omega].\n  rewrite Zplus_mod.\n  repeat rewrite (Zmult_mod (descent_modulus a m) (descent_modulus a m) m), descent_modulus_equiv_a_mod_m; [|omega].\n  repeat rewrite (Zmult_mod (descent_modulus b m) (descent_modulus b m) m), descent_modulus_equiv_a_mod_m; [|omega].\n  repeat rewrite <- Zmult_mod.\n  rewrite <- Zplus_mod.\n  rewrite Z.mod_divide; [auto | omega].\n  exists q.\n  rewrite def_m, def_N.\n  apply Zdivide_Zdiv_eq; [omega | auto].\n  rewrite <- def_N; auto.\nQed.\n\nLemma descent_div_N: forall a b q N m,\n  q > 0 -> N > 0 ->\n  N = (a * a + b * b) ->\n  m = N / q ->\n  (q | N) -> (m | N).\nProof.\n  intros a b q N m q_gt_0 N_gt_0 def_N def_m q_div_N.\n  exists q.\n  rewrite def_m.\n  apply Zdivide_Zdiv_eq; [omega| auto].\nQed.\n\n(*\n  (u * u + v * v) / m * q =\n  (a * u + b * v) / m * ((a * u + b * v) / m) + (a * v - b * u) / m * ((a * v - b * u) / m)\n *)\n\nLemma descent_div_term1: forall a b q N m,\n  q > 0 -> N > 0 ->\n  N = (a * a + b * b) ->\n  m = N / q ->\n  (q | N) ->\n  (m | (a * descent_modulus a m + b * descent_modulus b m)).\nProof.\n  intros a b q N m q_gt_0 N_gt_0 def_N def_m q_div_N.\n  (* must show m > 0 as ever *)\n  assert (m > 0).\n  rewrite def_m; apply div_positive; auto.\n  rewrite <- Z.mod_divide; [| omega].\n  rewrite Zplus_mod, (Zmult_mod a _ _), (Zmult_mod b _ _).\n  repeat rewrite descent_modulus_equiv_a_mod_m; auto.\n  repeat rewrite <- Zmult_mod.\n  repeat rewrite <- Zplus_mod.\n  rewrite Z.mod_divide; [| omega].\n  exists q.\n  rewrite <- def_N.\n  rewrite div_swap_l; [auto| omega | auto].\nQed.\n\nLemma descent_div_term2: forall a b q N m,\n  q > 0 -> N > 0 ->\n  N = (a * a + b * b) ->\n  m = N / q ->\n  (q | N) ->\n  (m | (b * descent_modulus a m - a * descent_modulus b m)).\nProof.\n  intros a b q N m q_gt_0 N_gt_0 def_N def_m q_div_N.\n  (* must show m > 0 as ever *)\n  assert (m > 0).\n  rewrite def_m; apply div_positive; auto.\n  rewrite <- Z.mod_divide; [| omega].\n  rewrite Zminus_mod, (Zmult_mod a _ _), (Zmult_mod b _ _).\n  repeat rewrite descent_modulus_equiv_a_mod_m; auto.\n  repeat rewrite <- Zmult_mod.\n  repeat rewrite <- Zminus_mod.\n  rewrite Z.mul_comm.\n  rewrite Z.sub_diag.\n  rewrite Zmod_0_l; reflexivity.\nQed.\n\nLemma add_div_distr: forall a b c,\n    a <> 0 -> (a | b) -> (a | c) -> (b + c) / a = b / a + c / a.\nProof.\n  intros a b c a_not_0 a_div_b a_div_c.\n  destruct a_div_b as [k def_k].\n  destruct a_div_c as [j def_j].\n  rewrite def_k, def_j.\n  replace (k * a + j * a) with ((k + j) * a) by ring.\n  repeat rewrite Z_div_mult_full; auto.\nQed.\n\nLemma descent_mult_key_lemma_sublemma: forall t0 t1 m a,\n    m <> 0 ->\n    (m | t0) ->\n    (m | t1) ->\n    (t0 + t1 = m * a) -> (t0 / m + (t1 / m) = a).\nProof.\n  intros t0 t1 m a m_not_0 m_div_t0 m_div_t1.\n  rewrite (div_swap_l m (t0 + t1) a); auto.\n  rewrite add_div_distr; auto.\n  apply Z.divide_add_r; auto.\nQed.\n\nLemma square_div_rearrange: forall a b, b <> 0 -> (b | a) -> a * a / (b * b) = (a / b) * (a / b).\nProof.\n  intros a b b_not_0 b_div_a.\n  destruct b_div_a.\n  rewrite H.\n  replace (x * b * (x * b)) with (x * x * (b * b)) by ring.\n  repeat rewrite Z_div_mult_full; auto.\n  apply Z.neq_mul_0; auto.\nQed.\n\nLemma descent_mult_key_lemma: forall t0 t1 m a,\n    m <> 0 ->\n    (m | t0) ->\n    (m | t1) ->\n    (t0 * t0 + t1 * t1 = m * m * a) -> (t0 / m * (t0 / m) + t1 / m * (t1 / m) = a).\nProof.\n  intros t0 t1 m a m_not_0 m_div_t0 m_div_t1.\n  assert (m * m <> 0).\n  apply Z.neq_mul_0; auto.\n  rewrite (div_swap_l (m * m) (t0 * t0 + t1 * t1) a); auto.\n  rewrite add_div_distr; auto.\n  repeat rewrite square_div_rearrange; auto.\n  - destruct m_div_t0 as [k def_k]; exists (k * k); rewrite def_k; ring.\n  - destruct m_div_t1 as [j def_j]; exists (j * j); rewrite def_j; ring.\n  - destruct m_div_t0 as [k def_k].\n    destruct m_div_t1 as [j def_j].\n    rewrite def_k, def_j.\n    exists (k * k + j * j).\n    ring.\nQed.\n\nTheorem descent_mult: forall a b q N,\n    q > 0 -> N > 0 -> N = (a * a + b * b) -> (q | N) ->\n    forall k r s,\n      (k, r, s) = descent a b q ->\n      k * q = r * r + s * s.\nProof.\n  intros a b q N.\n  intros q_gt_0 N_gt_0 def_N q_div_N.\n  intros k r s descent_def.\n  unfold descent in descent_def.\n  rewrite <- def_N in descent_def.\n  remember (N / q) as m.\n  assert (m > 0) as m_gt_0.\n  rewrite Heqm; apply div_positive; auto.\n  destruct (Z.eq_dec m 1); inversion descent_def.\n  - destruct q_div_N as [x def_N_with_q].\n    rewrite Z.mul_1_l, <- def_N, def_N_with_q.\n    rewrite e, def_N_with_q in Heqm.\n    rewrite Z_div_mult_full in Heqm; [auto | omega].\n    symmetry in Heqm.\n    rewrite Heqm, Z.mul_1_l; reflexivity.\n  - remember (descent_modulus a m) as u.\n    remember (descent_modulus b m) as v.\n    remember (descent_div_sum a b q N m q_gt_0 N_gt_0 def_N Heqm q_div_N) as m_div_u_v.\n    destruct m_div_u_v as [x m_div_u_v].\n    assert ((u * u + v * v)*(a * a + b * b) = m * m * x * q) as H.\n    destruct Heqm_div_u_v.\n    rewrite <- Hequ, <- Heqv in m_div_u_v.\n    rewrite Z.gt_lt_iff in q_gt_0.\n    destruct q_div_N as [y def_N_with_q].\n    rewrite def_N_with_q, Z_div_mult_full in Heqm; [auto | omega].\n    rewrite <- Heqm in def_N_with_q.\n    rewrite <- def_N, m_div_u_v, def_N_with_q.\n    ring.\n    rewrite Z.mul_comm in H at 1.\n    rewrite diophantine_identity in H.\n    remember (a * u + b * v) as t0.\n    remember (b * u - a * v) as t1.\n    remember (descent_div_term1 a b q N m q_gt_0 N_gt_0 def_N Heqm q_div_N) as div_t0.\n    remember (descent_div_term2 a b q N m q_gt_0 N_gt_0 def_N Heqm q_div_N) as div_t1.\n    destruct Heqdiv_t0.\n    destruct Heqdiv_t1.\n    rewrite <- Hequ, <- Heqv, <- Heqt0 in div_t0.\n    rewrite <- Hequ, <- Heqv, <- Heqt1 in div_t1.\n    replace (m * m * x * q) with (m * m * (x * q)) in H by ring.\n    apply descent_mult_key_lemma in H; [ | omega | |]; auto.\n    rewrite H.\n    destruct Heqm_div_u_v.\n    rewrite <- Hequ, <- Heqv in m_div_u_v.\n    rewrite (Z.mul_comm x m) in m_div_u_v.\n    apply div_swap_l in m_div_u_v; [ | omega | rewrite Hequ, Heqv; apply (descent_div_sum a b q N m)]; auto.\n    rewrite m_div_u_v; reflexivity.\nQed.\n\nCompute (descent 557 55 12049).\nCompute (descent 242 41 12049).\n\nFixpoint prime_sum_of_squares_helper a b p (n: nat) :=\n  match n with\n  | S m => match descent a b p with\n             (k, u, v) => if Z.eq_dec k 1 then\n                            (u, v)\n                          else\n                            prime_sum_of_squares_helper u v p m\n           end\n  | zero => (0, 0)\n  end.\n\nDefinition prime_sum_of_squares a b p :=\n  match prime_sum_of_squares_helper a b p (Z.to_nat (a * a + b * b + 1))\n  with (u, v) => (Z.abs u, Z.abs v)\n  end.\n\nLemma prime_sum_of_squares_helper_works: forall n a b p u v,\n    prime p ->\n    p > 0 ->\n    a * a + b * b > 0 ->\n    a * a + b * b < p * p ->\n    (p | a*a + b*b) ->\n    Nat.lt (Z.to_nat (a * a + b * b)) n ->\n    (u, v) = prime_sum_of_squares_helper a b p n ->\n    u * u + v * v = p.\nProof.\n  induction n;\n    intros a b p u v p_prime p_gt_0 args_gt_0 args_lt_p_sq p_div_a_square_plus_b_square n_bound;\n     unfold prime_sum_of_squares_helper; intros def_u_v.\n  contradict n_bound; unfold Nat.lt; omega.\n  fold prime_sum_of_squares_helper in def_u_v.\n  remember (descent a b p) as c'.\n  destruct c' as [[k u'] v'].\n  assert ((k, u', v') = descent a b p) as Heqd' by assumption.\n  apply (descent_mult a b p (a * a + b * b)) in Heqc'; auto.\n  apply (descent_smaller a b p (a * a + b * b) ((a * a + b * b) / p)) in Heqd'; auto.\n  destruct (Z.eq_dec k 1); inversion def_u_v.\n  - rewrite <- Heqc', e, Z.mul_1_l; reflexivity.\n  - assert (u' * u' + v' * v' > 0) as result_gt_0.\n    destruct Heqd' as [k_eq_1 | k_bounded];\n      [|rewrite <- Heqc'; rewrite Z.gt_lt_iff; apply Z.mul_pos_pos]; omega.\n    assert (u' * u' + v' * v' < a * a + b * b) as recursion_bounded.\n    destruct Heqd'; [contradict H |]; auto.\n    rewrite <- Heqc'.\n    rewrite <- div_swap_lt_l in H; auto.\n    rewrite Z.mul_comm; destruct H; assumption.\n    apply IHn in def_u_v; [ | | | |omega | exists k; symmetry; assumption | ]; auto.\n    rewrite Z2Nat.inj_lt in recursion_bounded; [| omega | omega].\n    apply lt_n_Sm_le in n_bound.\n    apply (lt_le_trans _ (Z.to_nat (a * a + b * b)) _); [assumption | omega].\n  - rewrite <- div_swap_lt_r; auto.\nQed.\n\nTheorem prime_sum_of_squares_works: forall a b p u v,\n    prime p ->\n    p > 0 ->\n    a * a + b * b > 0 ->\n    a * a + b * b < p * p ->\n    (p | a*a + b*b) ->\n    (u, v) = prime_sum_of_squares a b p ->\n    u * u + v * v = p.\nProof.\n  intros a b p u v p_prime p_gt_0 args_gt_0 args_lt_p_sq p_div_a_square_plus_b_square.\n  unfold prime_sum_of_squares.\n  intros def_u_v.\n  remember (prime_sum_of_squares_helper a b p (Z.to_nat (a * a + b * b + 1))) as Q.\n  destruct Q as [u' v'].\n  apply (prime_sum_of_squares_helper_works (Z.to_nat (a * a + b * b + 1)) a b) in HeqQ;\n    [ | | | | | | apply Z2Nat.inj_lt; omega ];\n    auto.\n  inversion def_u_v.\n  repeat rewrite Z.abs_square; assumption.\nQed.\n", "meta": {"author": "tildedave", "repo": "coq-sum-of-squares", "sha": "bf1d81cfaf1f2988dcbcb9aa95fbf9fac4befd0c", "save_path": "github-repos/coq/tildedave-coq-sum-of-squares", "path": "github-repos/coq/tildedave-coq-sum-of-squares/coq-sum-of-squares-bf1d81cfaf1f2988dcbcb9aa95fbf9fac4befd0c/p_sumofsquares.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7172967780166993}}
{"text": "Require Import Ensembles.\nRequire Import Coq.Lists.List.\nRequire Import ListExt.\nRequire Import folProof.\nRequire Import folProp.\nRequire Vector.\nRequire Import Peano_dec.\nRequire Import misc.\nRequire Import Arith.\n\nSection Model_Theory.\n\nVariable L : Language.\n\nFixpoint naryFunc (A : Set) (n : nat) {struct n} : Set :=\n  match n with\n  | O => A\n  | S m => A -> naryFunc A m\n  end.\n\nFixpoint naryRel (A : Set) (n : nat) {struct n} : Type :=\n  match n with\n  | O => Prop\n  | S m => A -> naryRel A m\n  end.\n\nRecord Model : Type := model\n  {U : Set;\n   func : forall f : Functions L, naryFunc U (arityF L f);\n   rel : forall r : Relations L, naryRel U (arityR L r)}.\n\nVariable M : Model.\n\nFixpoint interpTerm (value : nat -> U M) (t : Term L) {struct t} : \n U M :=\n  match t with\n  | var v => value v\n  | apply f ts => interpTerms _ (func M f) value ts\n  end\n \n with interpTerms (m : nat) (f : naryFunc (U M) m) \n (value : nat -> U M) (ts : Terms L m) {struct ts} : \n U M :=\n  match ts in (Terms _ n) return (naryFunc (U M) n -> U M) with\n  | Tnil => fun f => f\n  | Tcons m t ts => fun f => interpTerms m (f (interpTerm value t)) value ts\n  end f.\n\nFixpoint interpRels (m : nat) (r : naryRel (U M) m) \n (value : nat -> U M) (ts : Terms L m) {struct ts} : Prop :=\n  match ts in (Terms _ n) return (naryRel (U M) n -> Prop) with\n  | Tnil => fun r => r\n  | Tcons m t ts => fun r => interpRels m (r (interpTerm value t)) value ts\n  end r.\n\nDefinition updateValue (value : nat -> U M) (n : nat) \n  (v : U M) (x : nat) : U M :=\n  match eq_nat_dec n x with\n  | left _ => v\n  | right _ => value x\n  end.\n\nFixpoint interpFormula (value : nat -> U M) (f : Formula L) {struct f} :\n Prop :=\n  match f with\n  | equal t s => interpTerm value t = interpTerm value s\n  | atomic r ts => interpRels _ (rel M r) value ts\n  | impH A B => interpFormula value A -> interpFormula value B\n  | notH A => interpFormula value A -> False\n  | forallH v A => forall x : U M, interpFormula (updateValue value v x) A\n  end.\n\nLemma freeVarInterpTerm (v1 v2 : nat -> U M) (t : Term L):\n (forall x : nat, In x (freeVarTerm L t) -> v1 x = v2 x) ->\n interpTerm v1 t = interpTerm v2 t.\nProof.\n  elim t using  Term_Terms_ind with\n    (P0 := fun (n : nat) (ts : Terms L n) =>\n             forall f : naryFunc (U M) n,\n               (forall x : nat, In x (freeVarTerms L n ts) -> v1 x = v2 x) ->\n               interpTerms n f v1 ts = interpTerms n f v2 ts); \n    simpl.\n  - intros n H; apply H; left; auto.\n  - intros f t0 H H0; apply H.\n    intros x H1; apply H0, H1.\n  - reflexivity. \n  - intros n t0 H t1 H0 f H1.\n    rewrite H.  \n    apply H0.\n    intros x H2; apply H1.\n    + unfold freeVarTerms; apply in_or_app.\n      right; apply H2.\n    + intros x H2; apply H1.\n      unfold freeVarTerms; apply in_or_app; left.\n      apply H2.\nQed.\n\nLemma freeVarInterpRel (v1 v2 : nat -> U M) (n : nat) \n  (ts : Terms L n) (r : naryRel (U M) n): \n  (forall x : nat, In x (freeVarTerms L n ts) -> v1 x = v2 x) ->\n  interpRels n r v1 ts -> interpRels n r v2 ts.\nProof.\n  intros H; induction ts as [| n t ts Hrects]; simpl in |- *.\n  - auto.\n  - rewrite (freeVarInterpTerm v1 v2).\n    + apply Hrects.\n      intros x H0; apply H.\n      unfold freeVarTerms; apply in_or_app; right; apply H0.\n    + intros x H0; apply H.\n      unfold freeVarTerms; apply in_or_app; left; apply H0.\nQed.\n\nLemma freeVarInterpFormula (v1 v2 : nat -> U M) (g : Formula L):\n (forall x : nat, In x (freeVarFormula L g) -> v1 x = v2 x) ->\n interpFormula v1 g -> interpFormula v2 g.\nProof.\n  revert v1 v2.\n  induction g as [t t0| r t| g1 Hrecg1 g0 Hrecg0| g Hrecg| n g Hrecg];\n    simpl in |- *; intros v1 v2 H.\n  - repeat rewrite (freeVarInterpTerm v1 v2).\n    + auto.\n    + intros x H0; apply H.\n      simpl; auto with datatypes.\n    + intros x H0; apply H.\n      simpl; auto with datatypes.\n  - intros H0; apply (freeVarInterpRel v1 v2).\n    + apply H. \n    + apply H0. \n  - assert (H0: interpFormula v2 g1 -> interpFormula v1 g1).\n    { apply Hrecg1.\n      intros x H0; symmetry; apply H.\n      simpl; auto with datatypes.\n    } \n    assert (H1: interpFormula v1 g0 -> interpFormula v2 g0).\n    { apply Hrecg0.\n      intros x H1; apply H; simpl; auto with datatypes.\n    } \n    tauto.\n  - intros H0 H1; apply H0.\n    apply Hrecg with v2.\n    intros x H2; symmetry; auto.\n    assumption.\n  - intros H0 x; apply Hrecg with (updateValue v1 n x).\n    + intros x0 H1; unfold updateValue; induction (eq_nat_dec n x0).\n      * reflexivity.\n      * apply H.\n        apply in_in_remove; auto.\n    + auto.\nQed.\n \nLemma subInterpTerm (value : nat -> U M) (t : Term L) (v : nat) (s : Term L):\n interpTerm (updateValue value v (interpTerm value s)) t =\n interpTerm value (substituteTerm L t v s).\nProof.\n  elim t using  Term_Terms_ind  with\n    (P0 := fun (n : nat) (ts : Terms L n) =>\n             forall f : naryFunc (U M) n,\n               interpTerms n f (updateValue value v (interpTerm value s)) ts =\n                 interpTerms n f value (substituteTerms L n ts v s)); \n    simpl.\n  - intro n; unfold updateValue; induction (eq_nat_dec v n); reflexivity.\n  - intros f t0 H; rewrite H.\n    + reflexivity.\n  - reflexivity.\n  - intros n t0 H t1 H0 f; rewrite H; apply H0.\nQed.                    \n\nLemma subInterpRel (value : nat -> U M) (n : nat) (ts : Terms L n) \n  (v : nat) (s : Term L) (r : naryRel (U M) n):\n  interpRels n r (updateValue value v (interpTerm value s)) ts <->\n    interpRels n r value (substituteTerms L n ts v s).\nProof.\n  induction ts as [| n t ts Hrects].\n  - simpl; tauto.\n  - simpl; rewrite <- subInterpTerm; apply Hrects.\nQed.\n\nLemma subInterpFormula :\n forall (value : nat -> U M) (f : Formula L) (v : nat) (s : Term L),\n interpFormula (updateValue value v (interpTerm value s)) f <->\n interpFormula value (substituteFormula L f v s).\nProof.\n  intros value f; revert value.\n  elim f using Formula_depth_ind2; simpl.\n  - intros t t0 value v s; repeat rewrite subInterpTerm.\n    tauto.\n  - intros r t value v s; apply subInterpRel.\n  - intros f0 H f1 H0 value v s; rewrite (subFormulaImp L).\n    simpl;\n    assert\n      (H1: interpFormula (updateValue value v (interpTerm value s)) f1 <->\n         interpFormula value (substituteFormula L f1 v s)) by auto.\n    assert\n      (H2: interpFormula (updateValue value v (interpTerm value s)) f0 <->\n         interpFormula value (substituteFormula L f0 v s)) by auto.\n    tauto.\n  - intros f0 H value v s; rewrite (subFormulaNot L).\n    simpl in |- *.\n    assert\n      (interpFormula (updateValue value v (interpTerm value s)) f0 <->\n         interpFormula value (substituteFormula L f0 v s)).\n    auto.\n    tauto.\n  - intros v a H value v0 s; rewrite (subFormulaForall L).\n    induction (eq_nat_dec v v0) as [a0 | b].\n    + rewrite a0.\n    simpl in |- *.\n    unfold updateValue in |- *.\n    split.\n      *  intros H0 x;  apply freeVarInterpFormula with\n           (fun x0 : nat =>\n              match eq_nat_dec v0 x0 with\n              | left _ => x\n              | right _ =>\n                  match eq_nat_dec v0 x0 with\n                  | left _ => interpTerm value s\n                  | right _ => value x0\n                  end\n              end).\n         -- intros x0 H1; induction (eq_nat_dec v0 x0); reflexivity.\n         -- auto.\n      * intros H0 x; apply\n          freeVarInterpFormula\n          with\n          (fun x0 : nat =>\n             match eq_nat_dec v0 x0 with\n             | left _ => x\n             | right _ => value x0\n             end).\n        -- intros x0 H1; induction (eq_nat_dec v0 x0); reflexivity.\n        --  auto.\n    + induction (In_dec eq_nat_dec v (freeVarTerm L s)) as [a0 | b0].\n      * simpl;\n        set (nv := newVar (v0 :: freeVarTerm L s ++ freeVarFormula L a)) in *.\n        assert (~ In nv (v0 :: freeVarTerm L s ++ freeVarFormula L a)).\n        { unfold nv in |- *.\n          apply newVar1. }\n        assert\n              (forall (x : U M) (x0 : nat),\n                  In x0 (freeVarFormula L a) ->\n                  updateValue (updateValue value v0 (interpTerm value s)) v x x0 =\n                    updateValue\n                      (updateValue (updateValue value nv x) v0\n                         (interpTerm (updateValue value nv x) s)) v\n                      (interpTerm\n                         (updateValue (updateValue value nv x) v0\n                            (interpTerm (updateValue value nv x) s)) \n                         (var nv)) x0).\n    { intros x x0 H1; unfold updateValue in |- *; simpl in |- *.\n      induction (eq_nat_dec v x0) as [a1 | ?].\n      - induction (eq_nat_dec v0 nv) as [a2 | b0].\n        + elim H0.\n          rewrite a2.\n          simpl in |- *.\n          auto.\n        + induction (eq_nat_dec nv nv) as [a2 | b1].\n          * reflexivity.\n          * elim b1; reflexivity.\n      - induction (eq_nat_dec v0 x0) as [a1 | b1].\n        + apply freeVarInterpTerm.\n          intros x1 H2; induction (eq_nat_dec nv x1).\n          * elim H0.\n            rewrite a2.\n            simpl in |- *.\n            auto with datatypes.\n          * reflexivity.\n        + induction (eq_nat_dec nv x0) as [a1 | ?].\n          * elim H0.\n            rewrite a1.\n            auto with datatypes.\n          * reflexivity.\n    }    \n    assert\n      (H2: (forall x : U M,\n           interpFormula\n             (updateValue\n                (updateValue (updateValue value nv x) v0\n                   (interpTerm (updateValue value nv x) s)) v\n                (interpTerm\n                   (updateValue (updateValue value nv x) v0\n                      (interpTerm (updateValue value nv x) s)) \n                   (var nv))) a) <->\n         (forall x : U M,\n             interpFormula (updateValue value nv x)\n               (substituteFormula L (substituteFormula L a v (var nv)) v0 s))).\n    { split.\n      - assert\n          (H2: forall b : Formula L,\n              lt_depth L b (forallH v a) ->\n              forall (value : nat -> U M) (v : nat) (s : Term L),\n                interpFormula (updateValue value v (interpTerm value s)) b ->\n                interpFormula value (substituteFormula L b v s)).\n        { intros b0 H2 value0 v1 s0 H3;\n          induction (H b0 H2 value0 v1 s0); auto.\n        }    \n        intros H3 x; apply H2.\n        + eapply eqDepth.\n          * symmetry; apply subFormulaDepth.\n          * apply depthForall.\n        + apply H2.\n          * apply depthForall.\n          * apply H3.\n      - intros H2 x.\n        assert\n          (H3: forall b : Formula L,\n              lt_depth L b (allH v, a)%fol ->\n              forall (value : nat -> U M) (v : nat) (s : Term L),\n                interpFormula value (substituteFormula L b v s) ->\n                interpFormula (updateValue value v (interpTerm value s)) b) \n          by (intros; induction (H b0 H3 value0 v1 s0); auto).\n        clear H; apply H3.\n        + apply depthForall.\n        + apply H3.\n          * eapply eqDepth.\n            -- symmetry; apply subFormulaDepth.\n            -- apply depthForall.\n          * auto.\n    }    \n    assert\n      (H3: (forall x : U M,\n           interpFormula\n             (updateValue (updateValue value v0 (interpTerm value s)) v x) a) <->\n         (forall x : U M,\n             interpFormula\n               (updateValue\n                  (updateValue (updateValue value nv x) v0\n                     (interpTerm (updateValue value nv x) s)) v\n                  (interpTerm\n                     (updateValue (updateValue value nv x) v0\n                        (interpTerm (updateValue value nv x) s)) \n                     (var nv))) a)).\n    { split.\n      - intros H3 x;\n        apply\n          freeVarInterpFormula\n          with (updateValue (updateValue value v0 (interpTerm value s)) v x).\n        auto.\n        auto.\n      - intros H3 x.\n        apply\n          freeVarInterpFormula\n          with\n          (updateValue\n             (updateValue (updateValue value nv x) v0\n                (interpTerm (updateValue value nv x) s)) v\n             (interpTerm\n                (updateValue (updateValue value nv x) v0\n                   (interpTerm (updateValue value nv x) s)) \n                (var nv))).\n        + intros x0 H4;\n          symmetry  in |- *.\n          auto.\n        + auto.\n    }    \n    tauto.\n      * simpl in |- *.\n        assert\n          (forall (x : U M) (x0 : nat),\n              In x0 (freeVarFormula L a) ->\n              updateValue (updateValue value v0 (interpTerm value s)) v x x0 =\n                updateValue (updateValue value v x) v0\n                  (interpTerm (updateValue value v x) s) x0).\n        { intros x x0 H0; unfold updateValue;\n          induction (eq_nat_dec v x0) as [a0 | b1].\n          - induction (eq_nat_dec v0 x0) as [a1 | ?].\n            + elim b.\n              transitivity x0; auto.\n            +  reflexivity.\n          - induction (eq_nat_dec v0 x0) as [a0 | ?].\n            + apply freeVarInterpTerm.\n              intros x1 H1; induction (eq_nat_dec v x1).\n              * elim b0.\n                rewrite a1.\n                auto.\n              * reflexivity.\n            + reflexivity.\n        }    \n        split.\n        --  intros H1 x;\n        assert\n          (H2: forall b : Formula L,\n              lt_depth L b (forallH v a) ->\n              forall (value : nat -> U M) (v : nat) (s : Term L),\n                interpFormula (updateValue value v (interpTerm value s)) b ->\n                interpFormula value (substituteFormula L b v s)).\n        { intros b1 H2 value0 v1 s0 H3; induction (H b1 H2 value0 v1 s0); auto. }\n        apply H2.\n        ++ apply depthForall.\n        ++ apply freeVarInterpFormula with \n             (updateValue (updateValue value v0 (interpTerm value s)) v x).\n           ** apply (H0 x).\n           ** apply H1.\n    -- assert\n        (forall b : Formula L,\n            lt_depth L b (forallH v a) ->\n            forall (value : nat -> U M) (v : nat) (s : Term L),\n              interpFormula value (substituteFormula L b v s) ->\n              interpFormula (updateValue value v (interpTerm value s)) b).\n       { intros b1 H1 value0 v1 s0 H2; induction (H b1 H1 value0 v1 s0); auto. }\n       intros H2 x; \n       apply\n         freeVarInterpFormula\n         with\n         (updateValue (updateValue value v x) v0\n            (interpTerm (updateValue value v x) s)).\n       ++ intros; symmetry  in |- *; auto.\n       ++ apply H1.\n          ** apply depthForall.\n          ** auto.\nQed.\n\nLemma subInterpFormula1 (value : nat -> U M) (f : Formula L) (v : nat) (s : Term L):\n interpFormula (updateValue value v (interpTerm value s)) f ->\n interpFormula value (substituteFormula L f v s).\nProof.\n  induction (subInterpFormula value f v s); auto.\nQed.\n\nLemma subInterpFormula2 (value : nat -> U M) (f : Formula L) (v : nat) (s : Term L):\n  interpFormula value (substituteFormula L f v s) ->\n  interpFormula (updateValue value v (interpTerm value s)) f.\nProof.\n  induction (subInterpFormula value f v s); auto.\nQed.\n\nFixpoint nnHelp (f : Formula L) : Formula L :=\n  match f with\n  | equal t s => equal t s\n  | atomic r ts => atomic r ts\n  | impH A B => impH (nnHelp A) (nnHelp B)\n  | notH A => notH (nnHelp A)\n  | forallH v A => (allH v, ~ ~ nnHelp A)%fol\n  end.\n\nDefinition nnTranslate (f : Formula L) : Formula L :=\n  notH (notH (nnHelp f)).\n\nLemma freeVarNNHelp (f : Formula L):  freeVarFormula L f = freeVarFormula L (nnHelp f).\nProof.\n  induction f as [t t0| r t| f1 Hrecf1 f0 Hrecf0| f Hrecf| n f Hrecf];\n    try reflexivity.\n  - simpl; now rewrite Hrecf1, Hrecf0.\n  - simpl; assumption.\n  - simpl; now rewrite Hrecf.\nQed.\n\nLemma subNNHelp :\n forall (f : Formula L) (v : nat) (s : Term L),\n substituteFormula L (nnHelp f) v s = nnHelp (substituteFormula L f v s).\nProof.\n  intro f; elim f using Formula_depth_ind2; intros; try reflexivity.\n  - simpl; rewrite subFormulaImp, H, H0. \n    now rewrite subFormulaImp.\n  - simpl; rewrite subFormulaNot, H, subFormulaNot; easy.\n  - simpl; do 2 rewrite subFormulaForall.\n    simpl; induction (eq_nat_dec v v0).\n    + simpl; reflexivity.\n    + induction (In_dec eq_nat_dec v (freeVarTerm L s)) as [? | ?].\n      * simpl; repeat rewrite subFormulaNot; repeat rewrite H.\n        -- now rewrite <- freeVarNNHelp.\n        -- eapply eqDepth.\n           ++ symmetry; apply subFormulaDepth.\n           ++ apply depthForall.\n        -- apply depthForall.\n      * repeat rewrite subFormulaNot.\n        rewrite H; simpl.\n        -- reflexivity.\n        -- apply depthForall.\nQed.\n\nSection Consistent_Theory.\n\n  Variable T : System L.\n\n  Fixpoint interpTermsVector (value : nat -> U M) (n : nat) \n    (ts : Terms L n) {struct ts} : Vector.t (U M) n :=\n    match ts in (Terms _ n) return (Vector.t (U M) n) with\n    | Tnil => Vector.nil (U M)\n    | Tcons m t ts =>\n        Vector.cons (U M) (interpTerm value t) m (interpTermsVector value m ts)\n    end.\n\nLemma preserveValue (value : nat -> U M):\n (forall f : Formula L,\n  mem _ T f -> interpFormula value (nnTranslate f)) ->\n forall g : Formula L, SysPrf L T g -> interpFormula value (nnTranslate g).\nProof.\n  intros H g H0.\n  induction H0 as (x, H0).\n  induction H0 as (x0, H0).\n  cut (forall g : Formula L, In g x -> interpFormula value (nnTranslate g)).\n  - clear H H0; revert value.\n    induction x0\n      as\n      [A|\n        Axm1 Axm2 A B x0_1 Hrecx0_1 x0_0 Hrecx0_0|\n        Axm A v n x0 Hrecx0|\n        A B|\n        A B C|\n        A B|\n        A v t|\n        A v n|\n        A B v|\n      |\n      |\n      |\n        R|\n        f]; intros; try (simpl in |- *; tauto).\n    + apply H.\n      auto with datatypes.\n    + assert (H0: interpFormula value (nnTranslate A))\n      by auto with datatypes.\n      assert (H1: interpFormula value (nnTranslate (A -> B)%fol))\n        by auto with datatypes.\n      clear Hrecx0_1 Hrecx0_0.\n      simpl in H0, H1. \n      simpl in |- *.\n      tauto.\n    + simpl in |- *.\n      intros.\n      apply H0.\n      clear H0.\n      intros.\n      simpl in Hrecx0.\n      apply (Hrecx0 (updateValue value v x)).\n      * intros.\n        simpl in H.\n        eapply H.\n        -- apply H1.\n        -- intros.\n           apply H2.\n           apply freeVarInterpFormula with value.\n           ++ intros.\n              rewrite <- freeVarNNHelp in H4.\n              unfold updateValue in |- *.\n              induction (eq_nat_dec v x1).\n              ** elim n.\n                 rewrite a.\n                 clear n x0 Hrecx0 H.\n                 induction Axm as [| a0 Axm HrecAxm].\n                 apply H1.\n                 simpl in |- *.\n                 simpl in H1.\n                 induction H1 as [H| H].\n                 rewrite H.\n                 auto with datatypes.\n                 auto with datatypes.\n              ** reflexivity.\n           ++ assumption.\n      * assumption.\n    + simpl in |- *.\n      intros.\n      apply H0.\n      intros.\n      elim H1 with (interpTerm value t).\n      intros.\n      apply H0.\n      intros.\n      rewrite <- subNNHelp.\n      apply subInterpFormula1.\n      auto.\n    + simpl in |- *.\n      intros.\n      apply H0.\n      intros.\n      apply H2.\n      apply freeVarInterpFormula with value.\n      * intros.\n        unfold updateValue in |- *.\n        induction (eq_nat_dec v x0).\n        -- elim n.\n           rewrite a.\n           rewrite freeVarNNHelp.\n           assumption.\n        -- reflexivity.\n      * assumption.\n    + simpl in |- *.\n      intros.\n      apply H0.\n      clear H0.\n      intros.\n      apply H0 with x.\n      intros.\n      apply H1 with x.\n      auto.\n    + simpl in |- *.\n      auto.\n    + simpl in |- *.\n      intros.\n      apply H0.\n      intros.\n      transitivity (value 1); auto.\n    + simpl in |- *.\n      intros.\n      apply H0.\n      clear H H0.\n      unfold AxmEq4 in |- *.\n      cut\n        (forall a b : Terms L (arityR L R),\n            interpTermsVector value _ a = \n              interpTermsVector value _ b ->\n            interpFormula value \n              (nnHelp (iffH (atomic R a) (atomic R b)))).\n      * assert\n          (H: forall A,\n              (forall a b : Terms L (arityR L R),\n                  interpTermsVector value (arityR L R) a =\n                    interpTermsVector value (arityR L R) b ->\n                  interpFormula value (nnHelp (A a b))) ->\n              interpFormula value\n                (nnHelp\n                   (nat_rec (fun _ : nat => Formula L)\n                      (prod_rec\n                         (fun\n                             _ : Terms L (arityR L  R) *\n                                   Terms L (arityR L R) => \n                             Formula L)\n                         (fun a b : Terms L (arityR L R) => A a b)\n                         (nVars L (arityR L R)))\n                      (fun (n : nat) (Hrecn : Formula L) =>\n                         (v_ (n + n)%nat = v_ (S (n+n))%nat -> Hrecn)%fol)\n                         \n                      (arityR L R)))).\n        { generalize (arityR L R).\n          simple induction n.\n          - simpl; intros A H; now apply H.\n          - intros n0 H A H0; simpl; induction (nVars L n0).\n            simpl in H |- *.\n            intro H1; apply\n                        (H\n                           (fun x y : Terms L n0 =>\n                              A (Tcons (var (n0 + n0)) x) \n                                (Tcons (var (S (n0 + n0))) y))).\n            intros a0 b0 H2; apply H0.\n            simpl; rewrite H1.\n            now rewrite H2.\n        } \n        apply (H (fun a b => iffH (atomic R a) (atomic R b))).\n      * simpl; generalize (rel M R).\n        generalize (arityR L R).\n        intros n n0 a b H H0.\n        induction a as [| n t a Hreca].\n        -- assert (H1: b = Tnil) by (symmetry; apply nilTerms).\n           rewrite H1 in H0; auto.\n        -- induction (consTerms L n b) as [x p].\n           induction x as (a0, b0).\n           simpl in p.\n           rewrite <- p in H0.\n           rewrite <- p in H.\n           simpl in H.\n           inversion H.\n           simpl in H0.\n           rewrite H2 in H0.\n           apply (Hreca (n0 (interpTerm value a0)) b0).\n           ++ apply (inj_right_pair2 _ eq_nat_dec _ _ _ _ H3).\n           ++ auto.\n    + simpl in |- *.\n      intros H0; apply H0.\n      clear H H0.\n      unfold AxmEq5 in |- *.\n      cut\n        (forall a b : Terms L (arityF L f),\n            interpTermsVector value _ a = interpTermsVector value _ b ->\n            interpFormula value (nnHelp (apply f a = apply f b)%fol)).\n      * assert\n          (H: forall A,\n              (forall a b : Terms L (arityF L f),\n                  interpTermsVector value (arityF L f) a =\n                    interpTermsVector value (arityF L f) b ->\n                  interpFormula value (nnHelp (A a b))) ->\n              interpFormula value\n                (nnHelp\n                   (nat_rec (fun _ : nat => Formula L)\n                      (prod_rec\n                         (fun _ : Terms L (arityF L f) * Terms L (arityF L f)  => Formula L)\n                         (fun a b : Terms L (arityF L f) => A a b)\n                         (nVars L (arityF L f)))\n                      (fun (n : nat) (Hrecn : Formula L) =>\n                         (v_ (n + n)%nat = v_ (S (n + n))%nat -> Hrecn)%fol)\n                           (arityF L f)))).\n        { generalize (arityF L f).\n          simple induction n.\n          - simpl; intros A H; auto. \n          - intros n0 H A H0; simpl.\n            induction (nVars L n0).\n            simpl in H |- *.\n            intros H1; \n              apply  (H\n                        (fun x y : Terms L n0 =>\n                           A (Tcons (var (n0 + n0)) x) \n                             (Tcons (var (S (n0 + n0))) y))).\n            intros a0 b0 H2; apply H0.\n            simpl; rewrite H1.\n            now rewrite H2.\n        }\n        apply (H (fun a b => equal (apply f a) (apply f b))).\n      * simpl; generalize (func M f).\n        generalize (arityF L f).\n        intros n n0 a b H.\n        induction a as [| n t a Hreca].\n        -- assert (H0: b = Tnil) by ( symmetry; apply nilTerms). \n           now rewrite H0.\n        -- induction (consTerms L n b) as [x p];\n           induction x as (a0, b0).\n           simpl in p; rewrite <- p; rewrite <- p in H.\n           simpl in H.\n           inversion H.\n           simpl; rewrite H1.\n           apply Hreca.\n           apply (inj_right_pair2 _ eq_nat_dec _ _ _ _ H2).\n  - auto.\nQed.\n\nLemma ModelConsistent (value : nat -> U M):\n  (forall f : Formula L,\n      mem _ T f -> interpFormula value (nnTranslate f)) ->\n  Consistent L T. \nProof.\n  intros H; unfold Consistent; exists (v_ O <> v_ 0)%fol.\n  intros H0; assert (H1: interpFormula value (nnTranslate (v_ O <> v_ 0)%fol)).\n  { apply preserveValue.\n    assumption.\n    auto.\n  }\n  apply H1; simpl; auto. \nQed.\n\nEnd Consistent_Theory.\n\nEnd Model_Theory.\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/Ackermann/model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7172967764771759}}
{"text": "(** This file generates unsatisfiable formulas for problems\n   commonly used to benchmark SAT solving procedures. *)\n\nRequire Import List.\nFixpoint introduce_vars \n  (P : list Prop -> Prop) (acc : list Prop) (n : nat) :=\n  match n with\n    | 0 => P (rev acc)\n    | S m => forall (x : Prop), introduce_vars P (x::acc) m\n  end.\nEval vm_compute in introduce_vars (fun l => l = l) nil 12.\n\n(** * Pigeon hole formulas \n   \n   The pigeon hole formula with [n] holes, [hole(n)], states that\n   there is no way to put [n+1] pigeons in [n] different holes such\n   that no two pigeons occupy the same hole. In its valid version,\n   it states that if [n+1] pigeons are in [n] different holes, at\n   least one hole contains two of them pigeons.\n*)\n\nSection HoleWithListVars.\n  Variable vars : list Prop.\n  Variable N : nat.\n\n  (** We define a propositional predicate [occ i j] which denotes\n     the fact that the pigeon [i] occupies the hole [j]. \n     *)\n  Definition occ (i j : nat) : Prop :=\n    nth (i * N + j) vars True.\n\n  (** The next definition, [is_home p n] builds a formula expressing\n     that the pigeon [p] is at least in one of the holes 0 to [n].\n     *)\n  Fixpoint is_home (p n : nat) : Prop :=\n    match n with\n      | O => occ p O\n      | S n0 => occ p n \\/ is_home p n0\n    end.\n\n  (** We can now build a conjunction expressing that all pigeons \n     number 0 to [n+1] have safely found home in the holes 0 to [n]. \n     *)\n  Fixpoint everyone_home_aux (n : nat) (p : nat) : Prop :=\n    match p with\n      | O => is_home O n\n      | S p0 => is_home p n /\\ everyone_home_aux n p0\n    end.\n  Definition everyone_home (n : nat) : Prop :=\n    everyone_home_aux n (S n).\n\n  (** This wraps up the first part of the pigeon hole formula. For the\n     second part, we need to express that for every hole [h], there \n     mustn't be two different pigeons [i] and [j] such that\n     [occ i h] and [occ j h] both stand.\n     We start by a quick definition for this very last part, two pigeons\n     are said to be \"safe\" with respect to a hole if at least one of them\n     is not in the hole.\n     *)\n  Definition safe (h : nat) (i j : nat) :=\n    ~occ i h \\/ ~occ j h.\n\n  (** Given a hole [h], we need a formula that says that all possible\n     pairs of pigeons are safe wrt that hole. Such a hole is called \n     \"sane\", and for efficiency reasons, we try to express every\n     pair of pigeon only once, by only adding a clause [safe h i j]\n     when [i < j].\n     *)\n  Fixpoint sane_aux_2 (h : nat) (p p' : nat) : Prop :=\n    match p' with\n      | O => safe h p O\n      | S p'0 => safe h p p' /\\ sane_aux_2 h p p'0\n    end.\n  Fixpoint sane_aux (h : nat) (p : nat) : Prop :=\n    match p with\n      | O => True (* unused, but correct nonetheless *)\n      | 1 => safe h 1 0\n      | S p0 => sane_aux_2 h p p0 /\\ sane_aux h p0\n    end.\n  Definition sane (h : nat) (n : nat) : Prop :=\n    sane_aux h (S n).\n\n  (** Finally, everyone is a happy pigeon when all holes are sane,\n     because it is well known that pigeons hate living in crowded areas. \n     *)\n  Fixpoint everyone_happy_aux (n : nat) (h : nat) : Prop :=\n    match h with\n      | O => sane O n\n      | S h0 => sane h n /\\ everyone_happy_aux n h0\n    end.\n  Definition everyone_happy (n : nat) : Prop :=\n    everyone_happy_aux n n.\nEnd HoleWithListVars.\n(** Now, we have everything we need to express the pigeon hole\n   formulas [hole n], which is true if and only if [n+1] pigeons\n   can live happily in [n] holes.\n   Note that up to this point, for practical reasons, we have\n   indexed pigeons and holes starting with 0. This means, for instance,\n   that the formula [everyone_happy n] actually ensures the sanity \n   property for [n+2] pigeons and [n+1] holes.\n   [hole] compensates for that by treating 0 as a special case (which\n   is of course [False] since there's no way a single pigeon will be\n   happy without at least one hole to live in).\n   *)\nDefinition hole (n : nat) : Prop :=\n  match n with\n    | O => False\n    | S n0 => \n      introduce_vars (fun l =>\n        (everyone_home l n n0 /\\ everyone_happy l n n0) -> False)\n      nil (S n * n)\n  end.\n\n(** A couple of examples of pigeon hole formulas for small values of [n].\n   Note that the size of the formula increases in [n] squared.\n*)\nSection Example.\n  Definition hole1 := hole 1.\n  Time Eval cbv -[not] in hole1.\n\n  Definition hole2 := hole 2.\n  Time Eval cbv -[not] in hole2.\n\n  Definition hole6 := hole 6.\n  Time Eval cbv -[not] in hole6.\n\n  Definition hole10 := hole 10.\n  Time Eval cbv -[not] in hole10.\nEnd Example.\n\n(* (** * Pigeon hole formulas (revisited) *)\n   \n(*    We now turn to another possible definition of the pigeon hole  *)\n(*    formulas, expressed in their valid flavour. The real difference *)\n(*    with the previous version is that the unsatisfiable version *)\n(*    was naturally expressed in CNF, whereas this one will not be *)\n(*    a CNF formula. Therefore it will stress the CNF conversion  *)\n(*    mechanism a little more. *)\n\n(*    We use the same family of variables [occ i j] of course. *)\n(* *) *)\n\n(* (** The first part of the formula expresses once again the fact *)\n(*    that every pigeon is in a hole, so we will reuse the [everyone_home] *)\n(*    function that we defined above. *)\n(*    The second part expresses that there is at least one hole with *)\n(*    two pigeons in it. We start by defining this last notion, ie. the *)\n(*    fact that two pigeons live in the same hole. *)\n(*    *) *)\n(* Definition room_mate (h : nat) (i j : nat) := *)\n(*   occ i h /\\ occ j h. *)\n\n(* (** Given a particular hole [h], the next formula expresses how *)\n(*    at least one pair of pigeon are room mates in this hole. *)\n(*    Such a hole is said to be \"crowded\". *)\n(*    As before, we make sure we only add each pair of pigeon once. *)\n(* *) *)\n(* Fixpoint crowded_aux_2 (h : nat) (p p' : nat) : Prop := *)\n(*   match p' with *)\n(*     | O => room_mate h p O *)\n(*     | S p'0 => room_mate h p p' \\/ crowded_aux_2 h p p'0 *)\n(*   end. *)\n(* Fixpoint crowded_aux (h : nat) (p : nat) : Prop := *)\n(*   match p with *)\n(*     | O => False (* unused, but correct nonetheless *) *)\n(*     | 1 => room_mate h 1 0 *)\n(*     | S p0 => crowded_aux_2 h p p0 \\/ crowded_aux h p0 *)\n(*   end. *)\n(* Definition crowded (h : nat) (n : nat) : Prop := *)\n(*   crowded_aux h (S n). *)\n\n(* (** Now, we are left to define a formula stating that at least *)\n(*    one hole must be crowded, which is a simple disjunction over *)\n(*    all possible holes.  *)\n(* *) *)\n(* Fixpoint one_is_crowded_aux (n : nat) (h : nat) : Prop := *)\n(*   match h with *)\n(*     | O => crowded O n *)\n(*     | S h0 => crowded h n \\/ one_is_crowded_aux n h0 *)\n(*   end. *)\n(* Definition one_is_crowded (n : nat) : Prop := *)\n(*   one_is_crowded_aux n n. *)\n\n(* (** Finally, a valid formula expressing the pigeon hole problem *)\n(*    is just the following implication : *)\n(* *) *)\n(* Definition vhole (n : nat) : Prop := *)\n(*   match n with *)\n(*     | O => True *)\n(*     | S n0 =>  *)\n(*       everyone_home n0 -> one_is_crowded n0 *)\n(*   end. *)\n\n(* (** Again, a couple of examples. *) *)\n(* Section VExample. *)\n(*   Definition vhole1 := vhole 1. *)\n(*   Time Eval cbv -[not] in vhole1. *)\n\n(*   Definition vhole2 := vhole 2. *)\n(*   Time Eval cbv -[not] in vhole2. *)\n\n(*   Definition vhole6 := vhole 6. *)\n(*   Time Eval cbv -[not] in vhole6. *)\n\n(*   Definition vhole10 := vhole 10. *)\n(*   Time Eval cbv -[not] in vhole10. *)\n(* End VExample. *)\n\n(** * De Bruijn formula\n\n   The De Bruijn formula with parameter [n] states that among [2n+1] boolean\n   variables set in a circular list, at least two adjacent variables are\n   equal.\n*)\nRequire Import Arith.\nSection WithListVars.\n  Variable variables : list Prop.\n\n  Definition x i := nth i variables True.\n\n  (** When the parameter of the problem is [n], variables should be indexed *)\n(*      modulo [2n+1], starting at 0. For that reason, we define what it means  *)\n(*      for two adjacent variables to be equal and we include a special case *)\n(*      for the first and last variables. *)\n  Definition equals (n : nat) (i : nat) : Prop :=\n    match i with\n      | O => x O <-> x (n+n)\n      | S i0 => x i <-> x i0\n    end.\n\n  (** Now, the formula we want is simply a big disjunction expressing that *)\n(*      there must be an equivalence between [var n i] and [var n (S i)] for *)\n(*      at least one [i] between 0 and [2*n].  *)\n(*      *)\n  Fixpoint some_are_equal (n : nat) (i : nat) :=\n    match i with\n      | O => equals n O\n      | S i0 => equals n i \\/ some_are_equal n i0\n    end.\nEnd WithListVars.\nDefinition de_bruijn (n : nat) : Prop :=\n  introduce_vars (fun l => ~(some_are_equal l n (n+n)) -> False) \n  nil (S (n+n)).\n\n(** A couple of examples for De Bruijn formulas.  *)\n(*    Unlike pigeon hole formulas, these De Bruijn formulas grow *)\n(*    linearly with the parameter [n]. *)\n(*    *)\nSection DBExample.\n  Definition deb1 := de_bruijn 1.\n  Time Eval cbv -[not iff] in deb1.\n\n  Definition deb2 := de_bruijn 2.\n  Time Eval cbv -[not iff] in deb2.\n\n  Definition deb6 := de_bruijn 6.\n  Time Eval cbv -[not iff] in deb6.\n\n  Definition deb10 := de_bruijn 10.\n  Time Eval cbv -[not iff] in deb10.\n\n  Definition deb50 := de_bruijn 50.\n  Time Eval cbv -[not iff] in deb50.\nEnd DBExample.\n\n(* (** * De Bruijn formula (in 2-SAT CNF) *)\n\n(*    We redefine the De Bruijn formula, this time such that the resulting *)\n(*    formula in not only in CNF, but also in the 2-SAT fragment. It will *)\n(*    be unsatisfiable, whereas the above formula was valid. *)\n(* *) *)\n(* Check x. *)\n(* Inductive x (i : nat) : Prop := *)\n(* | mk_x : x i. *)\n\n(* (** Conversely to what we did above, we define what it means for two *)\n(*    adjacent variables to be different. We again deal with the special  *)\n(*    case for the first and last variables. *) *)\n(* Definition differs (n : nat) (i : nat) : Prop := *)\n(*   match i with  *)\n(*     | O =>  *)\n(*       let n2 := n+n in (x O \\/ x n2) /\\ (~x 0 \\/ ~x n2) *)\n(*     | S i0 => (x i \\/ x i0) /\\ (~x i \\/ ~x i0) *)\n(*   end. *)\n\n(* (** Now, the formula we want is simply a big conjunction expressing that *)\n(*    all adjacent variables must differ.  *)\n(*    *) *)\n(* Fixpoint all_variables_differ (n : nat) (i : nat) := *)\n(*   match i with *)\n(*     | O => differs n O *)\n(*     | S i0 => differs n i /\\ all_variables_differ n i0 *)\n(*   end. *)\n(* Definition ude_bruijn (n : nat) : Prop := *)\n(*   all_variables_differ n (n+n). *)\n\n(* (** The same examples for the unsatisfiable 2-SAT version *)\n(*    of the De Bruijn formulas.  *)\n(*    *) *)\n(* Section DBExample2. *)\n(*   Definition udeb1 := ude_bruijn 1. *)\n(*   Time Eval cbv -[not iff] in udeb1. *)\n\n(*   Definition udeb2 := ude_bruijn 2. *)\n(*   Time Eval cbv -[not iff] in udeb2. *)\n\n(*   Definition udeb6 := ude_bruijn 6. *)\n(*   Time Eval cbv -[not iff] in udeb6. *)\n\n(*   Definition udeb10 := ude_bruijn 10. *)\n(*   Time Eval cbv -[not iff] in udeb10. *)\n\n(*   Definition udeb50 := ude_bruijn 50. *)\n(*   Time Eval cbv -[not iff] in udeb50. *)\n(* End DBExample2. *)\n\n(* (** * Associativity of equivalences  *)\n\n(*    The formula [equivn n] has the form : *)\n(*    [(a1 <-> (a2 <-> (.... an))) <-> (((a1 <-> a2) <-> ...) <-> an)] *)\n(*    and is valid. *)\n(* *) *)\n(* Inductive a : nat -> Prop := *)\n(* | mk_a : forall i, a i. *)\n\n(* Fixpoint Ln (n : nat) := *)\n(*   match n with *)\n(*     | O => a 0 *)\n(*     | S n0 => Ln n0 <-> a n *)\n(*   end. *)\n(* Fixpoint Rn (n : nat) := *)\n(*   match n with *)\n(*     | O => a 0 *)\n(*     | S n0 => a n <-> Rn n0 *)\n(*   end. *)\n(* Definition equivn (n : nat) := *)\n(*   Ln n <-> Rn n. *)\n\n(* Section EquivExample. *)\n(*   Definition equiv1 := equivn 1. *)\n(*   Time Eval cbv -[not iff] in equiv1. *)\n\n(*   Definition equiv2 := equivn 2. *)\n(*   Time Eval cbv -[not iff] in equiv2. *)\n\n(*   Definition equiv10 := equivn 10. *)\n(*   Time Eval cbv -[not iff] in equiv10. *)\n\n(*   Definition equiv30 := equivn 30. *)\n(*   Time Eval cbv -[not iff] in equiv30. *)\n(* End EquivExample. *)\n\n(* (** * Franzen formulas  *)\n\n(*    The Franzen formula with parameter [n] has the following form : *)\n(*    [(~a0 \\/ ~a1 .... \\/ ~an) \\/ (a0 /\\ a1 /\\ ... /\\ an)]. *)\n(*    It is valid since it means that at least one variable is false, *)\n(*    or they are all true. *)\n(* *) *)\n(* Fixpoint one_is_false (n : nat) := *)\n(*   match n with *)\n(*     | O => ~a O *)\n(*     | S n0 => one_is_false n0 \\/ ~a n *)\n(*   end. *)\n\n(* Fixpoint all_are_true (n : nat) := *)\n(*   match n with *)\n(*     | O => a O *)\n(*     | S n0 => all_are_true n0 /\\ a n *)\n(*   end. *)\n\n(* Definition Fn (n : nat) :=  *)\n(*   one_is_false n \\/ all_are_true n. *)\n\n(* Section FExample. *)\n(*   Definition f1 := Fn 1. *)\n(*   Time Eval cbv -[not iff] in f1. *)\n\n(*   Definition f2 := Fn 2. *)\n(*   Time Eval cbv -[not iff] in f2. *)\n\n(*   Definition f10 := Fn 10. *)\n(*   Time Eval cbv -[not iff] in f10. *)\n\n(*   Definition f30 := Fn 30. *)\n(*   Time Eval cbv -[not iff] in f30. *)\n(* End FExample. *)\n\n(* (** * Schwichtenberg formulas *) *)\n(* Fixpoint ant (n : nat) := *)\n(*   match n with  *)\n(*     | O => True *)\n(*     | S n0 => (a n -> a n -> a n0) /\\ ant n0 *)\n(*   end. *)\n(* Definition schwicht (n : nat) : Prop := *)\n(*   (a n /\\ ant n) -> a 0. *)\n\n(* Section SExample. *)\n(*   Definition s1 := schwicht 1. *)\n(*   Time Eval cbv -[not iff] in s1. *)\n\n(*   Definition s2 := schwicht 2. *)\n(*   Time Eval cbv -[not iff] in s2. *)\n\n(*   Definition s10 := schwicht 10. *)\n(*   Time Eval cbv -[not iff] in s10. *)\n\n(*   Definition s30 := schwicht 30. *)\n(*   Time Eval cbv -[not iff] in s30. *)\n(* End SExample. *)\n\n(* (** * Two formulas to test the sharing of subformulas *) *)\n(* Definition partage := hole 3 /\\ ~(hole 3). *)\n(* Definition partage2 :=  *)\n(*   (hole 3 <-> hole 2) \\/ (hole 2 <-> hole 1) \\/ (hole 1 <-> hole 3). *)\n", "meta": {"author": "coq-contribs", "repo": "ergo", "sha": "d31962ab6cb56861e5d83691d4d5cea1b769f2c2", "save_path": "github-repos/coq/coq-contribs-ergo", "path": "github-repos/coq/coq-contribs-ergo/ergo-d31962ab6cb56861e5d83691d4d5cea1b769f2c2/tests/GeneratorsNG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7172967744769981}}
{"text": "Coq < Section Resolution.\n\nCoq < Variables P Q R : Prop.\nP is assumed\nQ is assumed\nR is assumed\n\nCoq < Goal ((~P \\/ R) /\\ (P \\/ Q)) -> (Q \\/ R).\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  ============================\n   (~ P \\/ R) /\\ (P \\/ Q) -> Q \\/ R\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  ============================\n   Q \\/ R\n\nUnnamed_thm < elim H.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  ============================\n   ~ P \\/ R -> P \\/ Q -> Q \\/ R\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  H0 : ~ P \\/ R\n  ============================\n   P \\/ Q -> Q \\/ R\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  H0 : ~ P \\/ R\n  H1 : P \\/ Q\n  ============================\n   Q \\/ R\n\nUnnamed_thm < destruct H1.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  H0 : ~ P \\/ R\n  H1 : P\n  ============================\n   Q \\/ R\n\nsubgoal 2 is:\n Q \\/ R\n\nUnnamed_thm < right.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  H0 : ~ P \\/ R\n  H1 : P\n  ============================\n   R\n\nsubgoal 2 is:\n Q \\/ R\n\nUnnamed_thm < auto.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  H0 : ~ P \\/ R\n  H1 : P\n  ============================\n   R\n\nsubgoal 2 is:\n Q \\/ R\n\nUnnamed_thm < destruct H.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : ~ P \\/ R\n  H2 : P \\/ Q\n  H0 : ~ P \\/ R\n  H1 : P\n  ============================\n   R\n\nsubgoal 2 is:\n Q \\/ R\n\nUnnamed_thm < destruct H as [H3|H4].\n3 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H3 : ~ P\n  H2 : P \\/ Q\n  H0 : ~ P \\/ R\n  H1 : P\n  ============================\n   R\n\nsubgoal 2 is:\n R\nsubgoal 3 is:\n Q \\/ R\n\nUnnamed_thm < auto.\n3 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H3 : ~ P\n  H2 : P \\/ Q\n  H0 : ~ P \\/ R\n  H1 : P\n  ============================\n   R\n\nsubgoal 2 is:\n R\nsubgoal 3 is:\n Q \\/ R\n\nUnnamed_thm < tauto.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H4 : R\n  H2 : P \\/ Q\n  H0 : ~ P \\/ R\n  H1 : P\n  ============================\n   R\n\nsubgoal 2 is:\n Q \\/ R\n\nUnnamed_thm < exact H4.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  H0 : ~ P \\/ R\n  H1 : Q\n  ============================\n   Q \\/ R\n\nUnnamed_thm < left.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : (~ P \\/ R) /\\ (P \\/ Q)\n  H0 : ~ P \\/ R\n  H1 : Q\n  ============================\n   Q\n\nUnnamed_thm < exact H1.\nProof completed.\n\nUnnamed_thm < Qed.\nintro.\nelim H.\nintro.\nintro.\ndestruct H1.\n right.\n auto.\n destruct H.\n destruct H as [H3| H4].\n  auto.\n  tauto.\n  \n  exact H4.\n  \n left.\n exact H1.\n \nUnnamed_thm is defined\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/logic/chapt01/practice14.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7172967735031691}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export Basics.\n(** Require Export Lists.\nRequire Export Induction.\n *)\n(*** Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last couple of chapters, we've been working just\n    with lists of numbers.  Obviously, interesting programs also need\n    to be able to manipulate lists with elements from other types --\n    lists of strings, lists of booleans, lists of lists, etc.  We\n    _could_ just define a new inductive datatype for each of these,\n    for example... *)\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the header, and the occurrences of\n    [natlist] in the types of the constructors have been replaced by\n    [list X].  (We can re-use the constructor names [nil] and [cons]\n    because the earlier definition of [natlist] was inside of a\n    [Module] definition that is now out of scope.)\n\n    What sort of thing is [list] itself?  One good way to think\n    about it is that [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it another way, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is an [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list.\n(* ===> list : Type -> Type *)\n\n(** The parameter [X] in the definition of [list] becomes a parameter\n    to the constructors [nil] and [cons] -- that is, [nil] and [cons]\n    are now polymorphic constructors, that need to be supplied with\n    the type of the list they are building. As an example, [nil nat]\n    constructs the empty list of type [nat]. *)\n\nCheck (nil nat).\n(* ===> nil nat : list nat *)\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3.*)\n\nCheck (cons nat 3 (nil nat)).\n(* ===> cons nat 3 (nil nat) : list nat *)\n\n(** What might the type of [nil] be? We can read off the type [list X]\n    from the definition, but this omits the binding for [X] which is\n    the parameter to [list]. [Type -> list X] does not explain the\n    meaning of [X]. [(X : Type) -> list X] comes closer. Coq's\n    notation for this situation is [forall X : Type, list X]. *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier\n    is spelled out in letters.  In the generated HTML files and in the\n    way various IDEs show .v files (with certain settings of their\n    display controls), [forall] is usually typeset as the usual\n    mathematical \"upside down A,\" but you'll still see the spelled-out\n    \"forall\" in a few places.  This is just a quirk of typesetting:\n    there is no difference in meaning.) *)\n\n(** Having to supply a type argument for each use of a list\n    constructor may seem an awkward burden, but we will soon see\n    ways of reducing that burden. *) \n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (We've written [nil] and [cons] explicitly here because we haven't\n    yet defined the [ [] ] and [::] notations for the new version of\n    lists.  We'll do that in a bit.) *)\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n\nModule MumbleGrumble.\n\n(** **** Exercise: 2 stars (mumble_grumble)  *)\n(** Consider the following two inductively defined types. *)\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]\n[d mumble (b a 5)]\n[d bool (b a 5)]\n[e bool true]\n[e mumble (b c 0)]\n*)\n(** [] *)\n\nEnd MumbleGrumble.\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** It has exactly the same type type as [repeat].  Coq was able\n    to use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations are still quite useful as documentation and sanity\n    checks, so we will continue to use them most of the time.  You\n    should try to find a balance in your own code between too many\n    type annotations (which can clutter and distract) and too\n    few (which forces readers to perform type inference in their heads\n    in order to understand your code). *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write the \"implicit argument\"\n    [_], which can be read as \"Please try to figure out for yourself\n    what belongs here.\"  More precisely, when Coq encounters a [_], it\n    will attempt to _unify_ all locally available information -- the\n    type of the function being applied, the types of the other\n    arguments, and the type expected by the context in which the\n    application appears -- to determine what concrete type should\n    replace the [_].\n\n    This may sound similar to type annotation inference -- indeed, the\n    two procedures rely on the same underlying mechanisms.  Instead of\n    simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with [_]\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using implicit arguments, the [repeat] function can be written like\n    this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    writing this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use argument synthesis to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** We can go further and even avoid writing [_]'s in most cases by\n    telling Coq _always_ to infer the type argument(s) of a given\n    function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists its argument names, with curly braces\n    around any arguments to be treated as implicit.  (If some\n    arguments of a definition don't have a name, as is often the case\n    for constructors, they can be marked with a wildcard pattern\n    [_].) *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat''']; indeed, it would be invalid to\n    provide one!)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity.  Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, occasionally, Coq does not have enough local information to\n    determine a type argument; in such cases, we need to tell Coq that\n    we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, optional (poly_exercises)  *)\n(** Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros t l.\n  induction l as [|l'].\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\n  \nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros t l m n.\n  induction l.\n  - simpl. \n    reflexivity.\n  - simpl. rewrite IHl. reflexivity. \nQed.\n\nTheorem app_length_helper : forall A (l1 l2 : list A),\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  (* WORKED IN CLASS *)\n  intros t l1 l2. induction l1 as [| n l1' IHl1'].\n  - (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.  Qed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros t l1 l2.\n  induction l2.\n  - rewrite app_nil_r. simpl. \n    rewrite<-plus_n_O. reflexivity.\n  - simpl. rewrite app_length_helper. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (more_poly_exercises)  *)\n(** Here are some slightly more interesting ones... *)\n\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros t l1 l2.\n  induction l1 as [|h tail Hpre].\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite Hpre. rewrite app_assoc. reflexivity.\nQed.\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intro x. \n  intros l.\n  induction l as [|h t Hpre].\n  - reflexivity.\n  - simpl. rewrite rev_app_distr.  rewrite Hpre. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the type definition we gave in\n    the last chapter for pairs of numbers can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types.  This avoids a clash with\n    the multiplication symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, optional (combine_checks)  *)\n(** Try answering the following questions on paper and\n    checking your answers in coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print? *)\nCheck @combine.\nCompute (combine [1;2] [false;false;true;true]).\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (split)  *)\n(** The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y)\n  :=\n  match l with\n  | nil => ([],[])\n  | hp::tail => ((fst hp)::(fst (split tail)),\n                 (snd hp)::(snd (split tail)))\n  end.\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** One last polymorphic type for now: _polymorphic options_,\n    which generalize [natoption] from the previous chapter: *)\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\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 [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, optional (hd_error_poly)  *)\n(** Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X\n  :=\n  match l with\n  | nil => None\n  | h::t => Some h\n  end.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like many other modern programming languages -- including\n    all functional languages (ML, Haskell, Scheme, Scala, Clojure,\n    etc.) -- Coq treats functions as first-class citizens, allowing\n    them to be passed as arguments to other functions, returned as\n    results, stored in data structures, etc.*)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars (filter_even_gt7)  *)\n(** Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat\n  :=\n  filter (fun x => andb (evenb x) (negb (leb x 7))) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars (partition)  *)\n(** Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X\n  :=\n  (filter test l, filter (fun x => negb (test x)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y:Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars (map_rev)  *)\n(** Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nTheorem map_rev_helper : forall (X Y:Type) (f : X->Y) (l1:list X) (a:X),\n  map f (l1 ++ [a]) = map f l1 ++ [f a].\nProof.\n  intros X Y f l1 a.\n  induction l1 as [|h t Hpre].\n  - reflexivity.\n  - simpl. rewrite<-Hpre. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [|h t Hpre].\n  - reflexivity. \n  - simpl. rewrite<-Hpre. rewrite map_rev_helper. reflexivity. \nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (flat_map)  *)\n(** The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                   : (list Y)\n  :=\n  match l with\n  | nil => []\n  | h::t => (f h) ++ (flat_map f t)\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** Lists are not the only inductive type that we can write a\n    [map] function for.  Here is the definition of [map] for the\n    [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, optional (implicit_args)  *)\n(** The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.) \n*)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different)  *)\n(** Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\nCompute (fold (fun x y=> andb (leb x 10) y) [1;2;11;4] true).\n\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars (fold_length)  *)\n(** Many common functions on lists can be implemented in terms of\n   [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length]. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [|h t Hpre].\n  - reflexivity.\n  - simpl. rewrite<-Hpre. \n    reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars (fold_map)  *)\n(** We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y\n  :=\n  fold (fun x t => (f x)::t) l [].\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it. *)\n\nTheorem fold_map_correct : forall (X Y:Type) (l : list X) (f:X->Y),\n  fold_map f l = map f l.\nProof.\n  intros X Y l f.\n  induction l as [|h t Hpre].\n  - reflexivity.\n  - simpl. rewrite<-Hpre. reflexivity.\nQed.\n  \n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  *)\n(** In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z\n  := f (fst p) (snd p).\n\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z f x y.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  destruct p.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  *)\n(** Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X n l, length l = n -> @nth_error X l n = None\n\nInduction on n.\n1. When n=0, length 1=0 -> l=[], then n_th returns None.\n2. When n=n'+1, length l = length (h::l') = 1 + length l' = 1 + n', \n    thus length l' = n'.\n   nth_error l n = nth_error l' n'.\n   Since length l'=n' -> nth_error l' n' = None.\n   So length l = n -> @nth_error X l n = None.\n*)\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (church_numerals)  *)\n(** This exercise explores an alternative way of defining natural\n    numbers, using the so-called _Church numerals_, named after\n    mathematician Alonzo Church.  We can represent a natural number\n    [n] as a function that takes a function [f] as a parameter and\n    returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : nat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** Successor of a natural number: *)\n\nDefinition succ (n : nat) : nat\n  :=\n  fun (X:Type) (f:X->X) (x:X) => f(n X f x).\n\nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\n\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\n\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\n(** Addition of two natural numbers: *)\n\nDefinition plus (n m : nat) : nat\n  :=\n  fun (X:Type) (f:X->X) (x:X) => n X f (m X f x).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\n\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\n(** Multiplication: *)\n\nDefinition mult (n m : nat) : nat\n  := \n  fun (X:Type) (f:X->X) (x:X) =>n X (fun a=>m X f a) x.\n\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\n\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type: [nat] itself is usually problematic.) *)\n\n\nDefinition exp (n m : nat) : nat\n  :=\nfun (X : Type) (f : X -> X) (x : X) =>\n     (m (X->X) (fun y => (fun z => (n X y z))) f) x.\n\n\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\nExample exp_3 : exp three zero = one.\nProof. reflexivity. Qed.\n\nEnd Church.\n(** [] *)\n\nEnd Exercises.\n\n(** $Date: 2018-01-23 20:16:07 -0600 (Tue, 23 Jan 2018) $ *)\n\n", "meta": {"author": "fsq", "repo": "CS386L-Programming-Language", "sha": "2a4e01bba8dbee34d5ccc60b104ce831ff69ace1", "save_path": "github-repos/coq/fsq-CS386L-Programming-Language", "path": "github-repos/coq/fsq-CS386L-Programming-Language/CS386L-Programming-Language-2a4e01bba8dbee34d5ccc60b104ce831ff69ace1/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.8824278680004706, "lm_q1q2_score": 0.7172967662459588}}
{"text": "(*****************************************************************)\n(******       M1 Preuves Assistées par Ordinateur          *******)\n(****** Projet : compilation d'expressions avec sommations *******)\n(******               Pierre Letouzey                      *******)\n(*****************************************************************)\n\nRequire Import String Datatypes Arith NPeano List Lia.\nOpen Scope string_scope.\nOpen Scope list_scope.\nOpen Scope nat_scope.\n\n(** Travail demandé :\n    a) Enlever l'axiome TODO et remplacer ses usages par du code\n       convenable.\n    b) Remplacer tous les Admitted par de véritables preuves. *)\nAxiom TODO : forall {A:Type}, A.\n\n\n(** I) Bibliotheque *)\n\n(** Comparaisons d'entiers\n\n    En Coq, la comparaison a <= b est une affirmation logique\n    (dans Prop). On ne peut pas s'en servir pour un test dans\n    un programme. Pour cela il faut utiliser la comparaison\n    booléenne a <=? b (correspondant à la constante Nat.leb,\n    définie dans le module NPeano). Voici le lien entre ces\n    deux notions. *)\n\nLemma leb_le x y : (x <=? y) = true <-> x <= y.\nProof.\n apply Nat.leb_le.\nQed.\n\nLemma leb_gt x y : (x <=? y) = false <-> y < x.\nProof.\n rewrite Nat.lt_nge, <- leb_le. destruct (x <=? y); intuition.\nQed.\n\n(** Une soustraction sans arrondi.\n\n    Sur les entiers naturels, la soustraction usuelle de Coq\n    est tronquée : lorsque a < b, alors a - b = 0.\n    Ici on utilise None pour signaler ce cas, et Some pour\n    indiquer une soustraction \"réussie\". *)\n\nFixpoint safe_minus a b : option nat :=\n match b, a with\n   | 0, _ => Some a\n   | S b, 0 => None\n   | S b, S a => safe_minus a b\n end.\n\nLemma safe_minus_spec a b :\n match safe_minus a b with\n | Some c => a = b + c\n | None => a < b\n end.\nProof.\n revert b; induction a; destruct b; simpl; auto with arith.\n specialize (IHa b). destruct (safe_minus a b); auto with arith.\nQed.\n\n(** Accès au n-ieme élement d'une liste\n\n   NB: list_get existe aussi dans la bibliothèque standard,\n   c'est List.nth_error. *)\n\nFixpoint list_get {A} (l:list A) i : option A :=\n  match i,l with\n    | 0,   x::_ => Some x\n    | S j, _::l => list_get l j\n    | _, _ => None\n  end.\n\nDefinition option_map {A B} (f:A->B) (o:option A) :=\n  match o with\n    | Some a => Some (f a)\n    | None => None\n  end.\n\nFixpoint list_set {A} (l:list A) i x : option (list A) :=\n  match i,l with\n    | 0, _::l => Some (x::l)\n    | S j, a::l => option_map (cons a) (list_set l j x)\n    | _, _ => None\n  end.\n\nLemma get_app_l {A} (l l':list A)(n:nat) : n < length l ->\n  list_get (l++l') n = list_get l n.\nProof.\n revert l.\n induction n; destruct l; simpl; auto with arith; inversion 1.\nQed.\n\nLemma get_app_r {A} (l l':list A)(n:nat) :\n  list_get (l++l') (length l + n) = list_get l' n.\nProof.\n induction l; auto.\nQed.\n\nLemma get_app_r0 {A} (l l':list A)(n:nat) : n = length l ->\n  list_get (l++l') n = list_get l' 0.\nProof.\n  intros. rewrite <- (get_app_r l l'). f_equal. lia.\nQed.\n\nLemma get_app_r' {A} (l l':list A)(n:nat) : length l <= n ->\n  list_get (l++l') n = list_get l' (n-length l).\nProof.\n intros. rewrite <- (get_app_r l l'). f_equal. lia.\nQed.\n\nLemma get_None {A} (l:list A) n :\n list_get l n = None <-> length l <= n.\nProof.\n revert n. induction l; destruct n; simpl; rewrite ?IHl; split;\n  auto with arith; inversion 1.\nQed.\n\nLemma get_Some {A} (l:list A) n x :\n list_get l n = Some x -> n < length l.\nProof.\n revert n. induction l; destruct n; simpl; try discriminate.\n  - auto with arith.\n  - intros. apply IHl in H. auto with arith.\nQed.\n\n(** Equivalent de List.assoc, spécialisé aux string *)\n\nFixpoint lookup {A}(s:string)(l:list (string*A))(default:A) :=\n  match l with\n    | nil => default\n    | (x,d)::l => if string_dec s x then d else lookup s l default\n  end.\n\n(** Index d'un element dans une liste, spécialisé aux string *)\n\nFixpoint index (s:string)(l:list string) :=\n  match l with\n    | nil => 0\n    | x::l => if string_dec s x then 0 else S (index s l)\n  end.\n\n(** Opérateur de sommation : sum f x n = f x + ... + f (x+n).\n    Attention, il y a (n+1) termes dans cette somme.\n    En particulier sum f 0 n = f 0 + ... + f n. *)\n\nFixpoint sum f x k :=\n  match k with\n    | 0 => f x\n    | S n' => f x + sum f (S x) n'\n  end.\n\nCompute sum (fun _ => 1) 0 10. (* 11 *)\nCompute sum (fun x => x) 0 10. (* 0 + 1 + ... + 10 = 55 *)\n\n(** II) Expressions arithmétiques avec sommations *)\n\n(** Les expressions *)\n\nDefinition var := string.\n\nInductive op := Plus | Minus | Mult.\n\nInductive expr :=\n  | EInt : nat -> expr\n  | EVar : var -> expr\n  | EOp  : op -> expr -> expr -> expr\n  | ESum : var -> expr -> expr -> expr.\n\n(** (ESum var max body) est la somme des valeurs de body\n    lorsque var prend successivement les valeurs de 0 jusqu'à max\n    (inclus). Par exemple, voici la somme des carrés de 0 à 10,\n    ce qu'on écrit sum(x^2,x=0..10) en Maple ou encore\n    $\\sum_{x=0}^{10}{x^2}$ en LaTeX. *)\n\nDefinition test1 :=\n  ESum \"x\" (EInt 10) (EOp Mult (EVar \"x\") (EVar \"x\")).\n\n(** Un peu plus complexe, une double sommation:\n    sum(sum(x*y,y=0..x),x=0..10) *)\n\nDefinition test2 :=\n  ESum \"x\" (EInt 10)\n   (ESum \"y\" (EVar \"x\")\n     (EOp Mult (EVar \"x\") (EVar \"y\"))).\n\n\n(** Evaluation d'expression *)\n\nDefinition eval_op o :=\n  match o with\n    | Plus => plus\n    | Minus => minus\n    | Mult => mult\n  end.\n\nFixpoint eval (env:list (string*nat)) e :=\n  match e with\n    | EInt n => n\n    | EVar v => lookup v env 0\n    | EOp o e1 e2 => eval_op o (eval env e1) (eval env e2)\n    | ESum v efin ecorps => sum (fun i =>eval ((v,i)::env) ecorps) 0 (eval env efin)\n  end.\n\nCompute (eval nil test1). (* 385 attendu: n(n+1)(2n+1)/6 pour n=10 *)\nCompute (eval nil test2). (* 1705 attendu *)\n\n\n(** III) Machine à pile *)\n\n(** Notre machine est composée de deux piles : une pile principale\n    (pour les calculs) et une pile de variables. Les instructions\n    sont stockées à part. *)\n\nRecord machine :=\n  Mach {\n      (** Pointeur de code *)\n      pc : nat;\n      (** Pile principale *)\n      stack : list nat;\n      (** Pile de variables *)\n      vars : list nat\n    }.\n\nDefinition initial_machine := Mach 0 nil nil.\n\nInductive instr :=\n  (** Pousse une valeur entière sur la pile. *)\n  | Push : nat -> instr\n  (** Enleve la valeur au sommet de la pile. *)\n  | Pop : instr\n  (** Dépile deux valeurs et empile le resultat de l'operation binaire. *)\n  | Op : op -> instr\n  (** Crée une nouvelle variable en haut de la pile des variables,\n      contenant initialement 0. *)\n  | NewVar : instr\n  (** Enleve la variable en haut de la pile des variables.\n      Sa valeur actuelle est perdue. *)\n  | DelVar : instr\n  (** Pousse la valeur de la i-eme variable sur la pile. *)\n  | GetVar : nat -> instr\n  (** Enlève la valeur au sommet de la pile et donne-la à la i-eme variable. *)\n  | SetVar : nat -> instr\n  (** Jump offset: retire offset au pointeur de code si la première\n      variable est inférieure ou égale au sommet de pile.\n      Pile et variables sont gardées à l'identique. *)\n  | Jump : nat -> instr.\n\n(* NB: il n'y a pas d'instruction Halt, on s'arrête quand\n   pc arrive au delà du code. *)\n\n(* Sémantique de référence des instructions,\n   définie via une relation inductive *)\n\nInductive Stepi : instr -> machine -> machine -> Prop :=\n| SPush pc stk vs n :\n    Stepi (Push n) (Mach pc stk vs) (Mach (S pc) (n::stk) vs)\n| SPop pc stk vs x :\n    Stepi Pop (Mach pc (x::stk) vs) (Mach (S pc) stk vs)\n| SOp pc stk vs o y x :\n    Stepi (Op o) (Mach pc (y::x::stk) vs)\n                 (Mach (S pc) (eval_op o x y :: stk) vs)\n| SNewVar pc stk vs :\n    Stepi NewVar (Mach pc stk vs) (Mach (S pc) stk (0::vs))\n| SDelVar pc stk vs x :\n    Stepi DelVar (Mach pc stk (x::vs)) (Mach (S pc) stk vs)\n| SGetVar pc stk vs i x :\n    list_get vs i = Some x ->\n    Stepi (GetVar i) (Mach pc stk vs) (Mach (S pc) (x::stk) vs)\n| SSetVar pc stk vs vs' i x :\n    list_set vs i x = Some vs' ->\n    Stepi (SetVar i) (Mach pc (x::stk) vs)\n                     (Mach (S pc) stk vs')\n| SJumpYes pc stk vs v x off : off <= pc -> v <= x ->\n    Stepi (Jump off) (Mach pc (x::stk) (v::vs))\n                     (Mach (pc-off) (x::stk) (v::vs))\n| SJumpNo pc stk vs v x off : x < v ->\n    Stepi (Jump off) (Mach pc (x::stk) (v::vs))\n                     (Mach (S pc) (x::stk) (v::vs)).\n\nDefinition Step (code:list instr) (m m' : machine) : Prop :=\n match list_get code m.(pc) with\n  | Some instr => Stepi instr m m'\n  | None => False\n end.\n\nInductive Steps (code:list instr) : machine -> machine -> Prop :=\n | NoStep m : Steps code m m\n | SomeSteps m1 m2 m3 :\n     Step code m1 m2 -> Steps code m2 m3 -> Steps code m1 m3.\n\n(** state : état d'une machine, c'est à dire sa pile de calcul\n    et sa pile de variables, mais pas son pc. *)\n\nDefinition state := (list nat * list nat)%type.\n\n(** Une execution complète va de pc=0 à pc=(length code) *)\n\nDefinition Exec code '(stk, vs) '(stk', vs') :=\n  Steps code (Mach 0 stk vs) (Mach (length code) stk' vs').\n\n(** Run : relation entre un code et le résultat de son exécution. *)\n\nDefinition Run code res := Exec code (nil,nil) (res::nil,nil).\n\n(** Petit exemple d'usage de cette sémantique *)\n\nLemma Run_example :\n  Run (Push 7 :: Push 3 :: Op Minus :: nil) 4.\nProof.\n repeat econstructor.\nQed.\n\n(** Propriétés basiques de Steps : transitivité, ... *)\n\nHint Constructors Steps.\n\nLemma Steps_trans code m1 m2 m3 :\n Steps code m1 m2 -> Steps code m2 m3 -> Steps code m1 m3.\nProof.\n  intros.\n  induction H.\n  -assumption.\n  -eapply SomeSteps.\n  eassumption.\n  apply IHSteps.\n  easy.\nQed.\n\nLemma OneStep code st st' : Step code st st' -> Steps code st st'.\nProof.\n  intros.\n  eapply SomeSteps.\n  -eassumption.\n  -apply NoStep.\nQed.\n\n(** Décalage de pc dans une machine *)\n\nDefinition shift_pc k (p:machine) :=\n let '(Mach pc vars stk) := p in\n (Mach (k+pc) vars stk).\n\nLemma pc_shift n m : (shift_pc n m).(pc) = n + m.(pc).\nProof.\n now destruct m.\nQed.\n\n(** Ajout de code devant / derriere la zone intéressante *)\n\nHint Resolve get_Some.\n\nLemma Step_extend code code' m m' :\n Step code m m' -> Step (code++code') m m'.\nProof.\n  intros.\n  unfold Step in *.\n  destruct (list_get code (pc m)) eqn : Heq.\n  -rewrite get_app_l.\n    +rewrite Heq. easy.\n    +eapply get_Some in Heq. easy.\n  -easy.\nQed.\n  (* \n  assert (list_get (@nil instr) (pc m) = None).\n   *)\nLemma Steps_extend code code' m m' :\n Steps code m m' -> Steps (code++code') m m'.\nProof.\n  intros.\n  induction H.\n  -eapply NoStep.\n  -eapply Steps_trans in IHSteps.\n    +eassumption.\n    +eapply OneStep. eapply Step_extend. easy.\nQed.\n\nHint Constructors Stepi.\n\nLemma Stepi_shift instr n m m' :\n Stepi instr m m' ->\n Stepi instr (shift_pc n m) (shift_pc n m').\nProof.\n  intros.\n  destruct H.\n  -simpl. rewrite Nat.add_succ_r. eapply SPush.\n  -simpl. rewrite Nat.add_succ_r. eapply SPop.\n  -simpl. rewrite Nat.add_succ_r. eapply SOp.\n  -simpl. rewrite Nat.add_succ_r. eapply SNewVar.\n  -simpl. rewrite Nat.add_succ_r. eapply SDelVar.\n  -simpl. rewrite Nat.add_succ_r. eapply SGetVar. easy.\n  -simpl. rewrite Nat.add_succ_r. eapply SSetVar. easy.\n  -simpl. rewrite Nat.add_sub_assoc.\n    +eapply SJumpYes.\n      *lia.\n      *lia.\n    +lia.\n  -simpl. rewrite Nat.add_succ_r. eapply SJumpNo. lia.\nQed.\n\nLemma Step_shift code0 code m m' (n := List.length code0) :\n Step code m m' ->\n Step (code0 ++ code) (shift_pc n m) (shift_pc n m').\nProof.\n\n  intros.\n  unfold Step in *.\n  destruct (list_get code (pc m)) eqn : Heq.\n  -rewrite get_app_r'.\n    +rewrite pc_shift. rewrite Nat.add_comm. \n    rewrite <- Nat.add_sub_assoc.\n      *subst n.\n      rewrite Nat.sub_diag. rewrite Nat.add_0_r.\n      rewrite Heq. eapply Stepi_shift. easy.\n      *lia.\n    +subst n. eapply get_Some in Heq. rewrite pc_shift. lia.\n  -easy.\nQed.\n\nLemma Steps_shift code0 code  m m' (n := List.length code0) :\n Steps code m m' ->\n Steps (code0 ++ code) (shift_pc n m) (shift_pc n m').\nProof.\n  intros.\n  induction H.\n  -apply NoStep.\n  -eapply Step_shift in H. eapply OneStep in H.\n  eapply Steps_trans in IHSteps.\n    +eassumption.\n    +eassumption.\nQed.\n\n\n(** Composition d'exécutions complètes *)\n\nLemma Exec_trans code1 code2 stk1 vars1 stk2 vars2 stk3 vars3 :\n Exec code1 (stk1, vars1) (stk2, vars2) ->\n Exec code2 (stk2, vars2) (stk3, vars3) ->\n Exec (code1 ++ code2) (stk1, vars1) (stk3, vars3).\nProof.\n  unfold Exec.\n  intros.\n  -eapply Steps_trans.\n    +eapply Steps_extend. eassumption.\n    +eapply Steps_shift in H0. simpl in H0. rewrite Nat.add_0_r in H0.\n    rewrite app_length. eassumption.\nQed.\n\n\n(** Correction des sauts lors d'une boucle\n\n    - La variable 0 est la variable de boucle a,\n    - La variable 1 est l'accumulateur acc\n    - Le haut de pile est la limite haute b de la variable de boucle\n\n    On montre d'abord que si un code ajoute f(a) à acc et\n    incrémente a, alors la répétition de ce code (via un Jump\n    ultérieur) ajoutera (sum f a (b-a)) à acc.\n    La variable N (valant b-a) est le nombre de tours à faire.\n*)\n\n(* Ce lemme est difficile. N'hésitez pas à le sauter et à y revenir\n   après avoir fini la partie IV. *)\n\nHint Resolve le_n_S le_plus_r.\n\nLemma Steps_jump code n (f:nat->nat) stk vars b :\n  length code = n ->\n  (forall a acc,\n   Steps code\n         (Mach 0 (b::stk) (a::acc::vars))\n         (Mach n (b::stk) ((S a)::(acc + f a)::vars)))\n  ->\n  forall N a acc,\n    b = N + a ->\n    Steps (code++(Jump n)::nil)\n          (Mach 0 (b::stk) (a::acc::vars))\n          (Mach (S n) (b::stk) ((S b)::(acc + sum f a N)::vars)).\nProof.\n  (* intros.\n  eapply Steps_extend. *)\n\nAdmitted.\n\n(** Version spécialisée du résultat précédent, avec des\n    Exec au lieu de Step, et 0 comme valeur initiale des variables\n    de boucle et d'accumulateurs. *)\n\nLemma Exec_jump code (f:nat->nat) stk vars b :\n  (forall a acc,\n     Exec code (b::stk, a::acc::vars)\n               (b::stk, (S a)::(acc + f a)::vars))\n  ->\n  Exec (code++(Jump (length code))::nil)\n      (b::stk, 0::0::vars)\n      (b::stk, (S b)::(sum f 0 b)::vars).\nProof.\n  intros.\n  simpl.\n  unfold Exec in  *.\n  eapply Steps_jump with (acc:=0) (N:= b) (a:= 0) in H.\n  -rewrite last_length. eassumption.\n  -easy.\n  -lia.\nQed.\n\n(** IV) Le compilateur\n\n    On transforme une expression en instructions pour\n    notre machine à pile.\n\n    Conventions:\n     - à chaque entrée dans une boucle, on crée deux variables,\n       la variable de boucle et l'accumulateur.\n     - on s'arrange pour que les variables de boucles aient\n       des indices pairs dans la pile des variables\n     - l'environnement de compilation cenv ne contient que les\n       variables de boucles.\n    Voir également l'invariant EnvsOk ci-dessous. *)\nFixpoint comp (cenv:list string) e :=\n  match e with\n    | EInt n => Push n :: nil\n    | EVar v => GetVar (index v cenv*2) :: nil\n    | EOp o e1 e2 => (comp cenv e1)++(comp cenv e2) ++ Op o :: nil\n    | ESum v efin ecorps =>\n      let prologue :=(comp cenv efin)++NewVar::NewVar::nil in\n      let corps := (comp (v::cenv) ecorps)++GetVar 1:: Op Plus ::SetVar 1:: Push 1::GetVar 0::Op Plus ::SetVar 0 ::nil in\n      let boucle := corps ++ Jump (length corps) :: nil in\n      let epilogue := Pop:: GetVar 1::DelVar :: DelVar :: nil in\n      prologue ++ boucle ++ epilogue\n  end.\n\nDefinition compile e := comp nil e.\n\n(** Variables libres d'une expression *)\n\nInductive FV (v:var) : expr -> Prop :=\n| FVVar : FV v (EVar v)\n| FVSum e1 e2 v0: FV v e1 \\/ FV v e2 /\\  v<>v0 ->FV v (ESum v0 e1 e2)\n| FVOp e1 e2 o: FV v e1 \\/ FV v e2 -> FV v (EOp o e1 e2).\n\nHint Constructors FV.\n\nDefinition Closed e := forall v, ~ FV v e.\n\n(** Invariants sur les environnements.\n    env : environnement d'evaluation (list (string*nat))\n    cenv : environnement de compilation (list string)\n    vars : pile de variables pour nos machines *)\n\nDefinition EnvsOk e env cenv vars :=\n forall v, FV v e ->\n   In v cenv /\\\n   list_get vars (index v cenv * 2) = Some (lookup v env 0).\n\nHint Unfold EnvsOk.\n\nLemma EnvsOk_ESum v e1 e2 env cenv vars a b :\n  EnvsOk (ESum v e1 e2) env cenv vars ->\n  EnvsOk e2 ((v,a)::env) (v::cenv) (a::b::vars).\nProof.\n  unfold EnvsOk.\n  intros.\n  simpl.\n  destruct (string_dec v0 v).\n  -simpl. split.\n    +rewrite e. left. easy.\n    +easy.\n  -simpl. split. \n    +right. apply H. apply FVSum. right. easy.\n    +apply H. apply FVSum. right. easy.\n  Qed.\n\n(** Correction du compilateur *)\n\nLtac basic_exec :=\n  (* Cette tactique prouve des buts (Exec code m m')\n     quand le code et la machine m sont connus en détail. *)\n  unfold Exec; repeat (eapply SomeSteps; [constructor|]);\n   try apply NoStep; try reflexivity.\n\n(* Si vous avez l'impression de prouver quelque chose d'impossible,\n   peut-être est-ce le signe que vous vous êtes trompé dans la définition\n   de comp. *)\n\nTheorem comp_ok e env cenv vars stk :\n EnvsOk e env cenv vars ->\n Exec (comp cenv e) (stk,vars) (eval env e :: stk, vars).\nProof.\n  revert stk.\n  revert cenv.\n  revert vars.\n  revert env.\n  induction e.\n  -intros. basic_exec.\n  -intros. basic_exec. eapply H. eapply FVVar.\n  -intros.\n  change (comp cenv (EOp o e1 e2)) with ((comp cenv e1)++(comp cenv e2)\n  ++ Op o :: nil). \n  eapply Exec_trans.\n    +eapply IHe1. unfold EnvsOk in *. auto.\n    +eapply Exec_trans.\n      *eapply IHe2. unfold EnvsOk in *. auto.\n      *basic_exec.\n  -intros.\n  change (comp cenv (ESum v e1 e2)) with (let prologue :=(comp cenv e1)++NewVar::NewVar::nil in\n  let corps := (comp (v::cenv) e2)++ GetVar 1:: Op Plus ::SetVar 1::Push 1::GetVar 0::Op Plus ::SetVar 0 ::nil in\n  let boucle := corps ++ Jump (length corps) :: nil in\n  let epilogue := Pop::GetVar 1::DelVar :: DelVar :: nil in\n  prologue ++ boucle ++ epilogue).\n  eapply Exec_trans.\n    +eapply Exec_trans.\n      *eapply IHe1. auto.\n      *basic_exec.\n    +eapply Exec_trans.\n      *eapply Exec_jump. intros. eapply Exec_trans.\n        **eapply IHe2. eapply EnvsOk_ESum. eassumption.\n        **basic_exec. simpl. rewrite Nat.add_comm. easy.\n      *basic_exec.\n Qed.\n\nTheorem compile_ok e : Closed e -> Run (compile e) (eval nil e).\nProof.\n  unfold Closed.\n  unfold Run.\n  intros.\n  eapply comp_ok.\n  unfold EnvsOk.\n  intros.\n  destruct (H v).\n  easy.\n  Qed.\n\n(** V) Sémantique exécutable\n\n    A la place des relations précédentes (Step*, Exec, Run...),\n    on cherche maintenant à obtenir une fonction calculant\n    le résultat de l'exécution d'une machine à pile. *)\n\n(* Cette partie est nettement plus difficile que les précédentes\n   et est complètement optionnelle. *)\n\nInductive step_result : Type :=\n  | More : machine -> step_result (* calcul en cours *)\n  | Stop : machine -> step_result (* calcul fini (pc hors code) *)\n  | Bug : step_result. (* situation illégale, machine plantée *)\n\n(** Pour la fonction [step] ci-dessous, ces deux opérateurs\n    monadiques peuvent aider (même si c'est essentiellement\n    une affaire de goût). *)\n\nDefinition option_bind {A} (o:option A) (f : A -> step_result) :=\n  match o with\n    | None => Bug\n    | Some x => f x\n  end.\n\nInfix \">>=\" := option_bind (at level 20, left associativity).\n\nDefinition list_bind {A} (l:list A) (f:A->list A->step_result) :=\n match l with\n  | nil => Bug\n  | x::l => f x l\n end.\n\nInfix \"::>\" := list_bind (at level 20, left associativity).\n\n(** Un pas de calcul *)\n\nDefinition step code (m:machine) : step_result :=\n  let '(Mach pc stk vars) := m in\n  (** réponse usuelle: *)\n  let more := fun stk vars => More (Mach (S pc) stk vars) in\n  match list_get code pc with\n    | None => Stop m\n    | Some instr => match instr with\n      | Push n => more (n::stk) vars\n      | Pop => TODO\n      | Op o => TODO\n      | NewVar => TODO\n      | DelVar => TODO\n      | GetVar i => TODO\n      | SetVar i => TODO\n      | Jump off => TODO\n      end\n    end.\n\n(** La fonction [steps] itère [step] un nombre [count] de fois\n    (ou moins si [Stop _] ou [Bug] sont atteints). *)\n\nFixpoint steps count (code:list instr)(m:machine) :=\n  match count with\n    | 0 => More m\n    | S count' => TODO\n  end.\n\n(** La function [run] exécute un certain code à partir\n    de la machine initiale, puis extrait le résultat obtenu.\n    On répond [None] si le calcul n'est pas fini au bout\n    des [count] étapes indiquées, ou bien en cas d'anomalies\n    lors de l'exécution ou à la fin (p.ex. pile finale vide,\n    variables finales non vides, etc). *)\n\nDefinition run (count:nat)(code : list instr) : option nat :=\n  TODO.\n\nCompute (run 1000 (compile test1)). (* attendu: Some 385 *)\nCompute (run 1000 (compile test2)). (* attendu: Some 1705 *)\n\n(** Equivalence entre sémantiques *)\n\n(** TODO: dans cette partie, à vous de formuler les\n    lemmes intermédiaires. *)\n\nLemma run_equiv code res :\n Run code res <-> exists count, run count code = Some res.\nProof.\nAdmitted.\n\n(** Le theorème principal, formulé pour run *)\n\nTheorem run_compile e :\n Closed e ->\n exists count, run count (compile e) = Some (eval nil e).\nProof.\nAdmitted.", "meta": {"author": "harmonySD", "repo": "pao", "sha": "b7dbf9642c97a8022f7ca4e957217ba2a1524ddc", "save_path": "github-repos/coq/harmonySD-pao", "path": "github-repos/coq/harmonySD-pao/pao-b7dbf9642c97a8022f7ca4e957217ba2a1524ddc/projet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.843895100591521, "lm_q1q2_score": 0.7172865171957158}}
{"text": "From Coq Require Import ZArith Lia.\nFrom Coq Require Import Int63.\nFrom Coq Require Bool.\n\nFrom EVM Require Import Arith2 UInt63 Nibble.\n\nDefinition uint64 := (bool * int)%type.\nDefinition t := uint64.\n\nLocal Open Scope Z_scope.\n\nDefinition Z_of_uint64 (a: uint64)\n:= match a with\n   | (false, n) => Int63.to_Z n\n   | (true , n) => Int63.to_Z n + Int63.wB\n   end.\n\nDefinition Z_of_uint64_lor (a: uint64)\n:= match a with\n   | (false, n) => Int63.to_Z n\n   | (true , n) => Z.lor (Int63.to_Z n) Int63.wB\n   end.\n\nLemma Z_of_uint64_lor_ok (a: uint64):\n  Z_of_uint64_lor a = Z_of_uint64 a.\nProof.\nunfold Z_of_uint64_lor.\ndestruct a as (b, n).\nrewrite<- Arith2.Z_add_nocarry_lor. { trivial. }\napply Arith2.Z_land_pow2_small. { apply to_Z_bounded. }\napply Nat2Z.is_nonneg.\nQed.\n\nDefinition Z_of_uint64_lxor (a: uint64)\n:= match a with\n   | (false, n) => Int63.to_Z n\n   | (true , n) => Z.lxor (Int63.to_Z n) Int63.wB\n   end.\n\nLemma Z_of_uint64_lxor_ok (a: uint64):\n  Z_of_uint64_lxor a = Z_of_uint64 a.\nProof.\nunfold Z_of_uint64_lxor.\ndestruct a as (b, n).\nrewrite<- Z.add_nocarry_lxor. { trivial. }\napply Arith2.Z_land_pow2_small. { apply to_Z_bounded. }\napply Nat2Z.is_nonneg.\nQed.\n\nLemma Z_of_uint64_lower (a: uint64):\n  0 <= Z_of_uint64 a.\nProof.\ndestruct a as (hi, lo).\nassert(B := Int63.to_Z_bounded lo).\ndestruct B as (L, H).\ndestruct hi; unfold Z_of_uint64; lia.\nQed.\n\nLemma Z_of_uint64_upper (a: uint64):\n  Z_of_uint64 a < 2^64.\nProof.\ndestruct a as (hi, lo).\nassert(B := Int63.to_Z_bounded lo).\ndestruct B as (_, H).\nassert (E: Int63.wB = 2^63). { unfold Int63.wB. f_equal. }\ndestruct hi; unfold Z_of_uint64; lia.\nQed.\n\nDefinition Z_of_uint64' (a: uint64)\n:= let (b, n) := a in\n   Int63.to_Z n + (if b then 1 else 0) * Int63.wB.\n\nLemma Z_of_uint64_alt (a: uint64):\n  Z_of_uint64' a = Z_of_uint64 a.\nProof.\nunfold Z_of_uint64'. unfold Z_of_uint64.\ndestruct a as (b, n). destruct b; lia.\nQed.\n\nDefinition Z_of_uint64_lor' (a: uint64)\n:= let (b, n) := a in\n   Z.lor (Int63.to_Z n) ((if b then 1 else 0) * Int63.wB).\n\nLemma Z_of_uint64_lor'_ok (a: uint64):\n  Z_of_uint64_lor' a = Z_of_uint64' a.\nProof.\nunfold Z_of_uint64_lor'.\ndestruct a as (b, n).\nrewrite<- Arith2.Z_add_nocarry_lor. { trivial. }\ndestruct b.\n{\n  rewrite Z.mul_1_l. apply Arith2.Z_land_pow2_small. \n  { apply to_Z_bounded. } apply Nat2Z.is_nonneg.\n}\nrewrite Z.mul_0_l. rewrite Z.land_0_r. trivial.\nQed.\n\nDefinition uint64_of_Z (z: Z)\n                        (lower: 0 <= z)\n                        (upper: z < 2^64)\n: uint64\n:= (2^63 <=? z, Int63.of_Z z).\n\nLemma uint64_of_Z_of_uint64 (a: uint64):\n  uint64_of_Z (Z_of_uint64 a) (Z_of_uint64_lower a) (Z_of_uint64_upper a) = a.\nProof.\nassert (E: Int63.wB = 2^63). { unfold Int63.wB. f_equal. }\ndestruct a as (hi, lo).\nassert(B := Int63.to_Z_bounded lo).\ndestruct hi; unfold Z_of_uint64; unfold uint64_of_Z.\n{\n  rewrite E. f_equal.\n  { rewrite Z.leb_le. lia. }\n  rewrite<- E. clear E.\n  apply Int63.to_Z_inj. rewrite Int63.of_Z_spec.\n  rewrite Z.add_comm.\n  rewrite<- Zplus_mod_idemp_l.\n  rewrite Z_mod_same_full.\n  rewrite Z.add_0_l.\n  remember (Int63.to_Z lo) as n. clear Heqn.\n  exact (Z.mod_small _ _ B).\n}\nrewrite<- E.\nf_equal. { rewrite Z.leb_gt. tauto. }\napply Int63.of_to_Z.\nQed.\n\nLemma Z_of_uint64_of_Z (z: Z)\n                        (lower: 0 <= z)\n                        (upper: z < 2^64):\n  Z_of_uint64 (uint64_of_Z z lower upper) = z.\nProof.\nassert (E: Int63.wB = 2^63). { unfold Int63.wB. f_equal. }\nunfold Z_of_uint64. unfold uint64_of_Z.\nremember (2 ^ 63 <=? z) as is_high.\nrewrite Int63.of_Z_spec.\nsymmetry in Heqis_high.\ndestruct is_high.\n{\n  rewrite Z.leb_le in Heqis_high.\n  rewrite E. clear E.\n  remember (z - 2^63) as y.\n  assert (YL: 0 <= y) by lia.\n  assert (YU: y < 2^63) by lia.\n  assert (R: z mod 2^63 = y mod 2^63).\n  {\n    subst.\n    rewrite<- Zminus_mod_idemp_r.\n    rewrite Z_mod_same_full.\n    rewrite Z.sub_0_r.\n    trivial.\n  }\n  rewrite R.\n  rewrite (Z.mod_small _ _ (conj YL YU)).\n  lia.\n}\nrewrite Z.leb_gt in Heqis_high.\napply Z.mod_small. tauto.\nQed.\n\nDefinition uint64_of_Z_mod (z: Z)\n: uint64\n:= (Z.testbit z 63, Int63.of_Z z).\n\nLemma uint64_mod_pos_bound (a: Z):\n  0 <= a mod 2^64 < 2^64.\nProof.\napply Z.mod_pos_bound.\nrewrite<- Z.ltb_lt.\ntrivial.\nQed.\n \nLemma uint64_of_Z_mod_ok (z: Z):\n  uint64_of_Z_mod z = uint64_of_Z (z mod 2^64)\n                                  (proj1 (uint64_mod_pos_bound z))\n                                  (proj2 (uint64_mod_pos_bound z)).\nProof.\nunfold uint64_of_Z. unfold uint64_of_Z_mod.\nf_equal.\n{\n  rewrite<- (Z.mod_pow2_bits_low z 64 63) by now rewrite<- Z.ltb_lt.\n  assert (B := uint64_mod_pos_bound z).\n  remember (z mod 2 ^ 64) as x. clear Heqx.\n  rewrite (Z.testbit_odd x 63).\n  rewrite Z.shiftr_div_pow2 by now rewrite<- Z.leb_le.\n  remember (2 ^ 63 <=? x) as f. symmetry in Heqf.\n  destruct f.\n  {\n    rewrite Z.leb_le in Heqf.\n    assert(L: 1 <= x / 2 ^ 63).\n    {\n      rewrite<- (Z.div_same (2^63)) by discriminate.\n      apply Z.div_le_mono. { rewrite<- Z.ltb_lt. trivial. }\n      assumption.\n    }\n    assert (U: x / 2^63 <= (2 ^ 64 - 1) / 2 ^ 63).\n    {\n      apply Z.div_le_mono. { rewrite<- Z.ltb_lt. trivial. }\n      lia.\n    }\n    replace ((2 ^ 64 - 1) / 2 ^ 63) with 1 in U by trivial.\n    assert (E: x / 2 ^ 63 = 1) by lia.\n    now rewrite E.\n  }\n  rewrite (Logic2.b_false (Z.leb_le _ _)) in Heqf.\n  apply Z.nle_gt in Heqf.\n  replace (x / 2 ^ 63) with 0. 2:{ symmetry. apply Z.div_small. tauto. }\n  trivial.\n}\napply to_Z_inj.\nrepeat rewrite of_Z_spec. \napply Znumtheory.Zmod_div_mod; try rewrite<- Z.ltb_lt; trivial.\nreplace (2^64) with (2 * wB) by trivial.\napply Z.divide_factor_r.\nQed.\n\nLemma Z_of_uint64_of_Z_mod (z: Z):\n  Z_of_uint64 (uint64_of_Z_mod z) = z mod 2^64.\nProof.\nrewrite uint64_of_Z_mod_ok.\nrewrite Z_of_uint64_of_Z.\ntrivial.\nQed.\n\nDefinition uint64_0: uint64 := (false, 0%int63).\nLemma uint64_0_ok:\n  Z_of_uint64 uint64_0 = 0.\nProof. trivial. Qed.\nDefinition uint64_1: uint64 := (false, 1%int63).\nLemma uint64_1_ok:\n  Z_of_uint64 uint64_1 = 1.\nProof. trivial. Qed.\nDefinition uint64_max_value: uint64 := (true, max_int).\nLemma uint64_max_value_ok:\n  Z_of_uint64 uint64_max_value = 2^64 - 1.\nProof. trivial. Qed.\n\n(*******************************************************************************)\n\nDefinition add (a b: uint64)\n: uint64\n:= let (ha, la) := a in\n   let (hb, lb) := b in\n   let x := xorb ha hb in\n   match Int63.addc la lb with\n   | DoubleType.C0 c => (x, c)\n   | DoubleType.C1 c => (negb x, c)\n   end.\n\nLtac wB_up\n:= repeat (rewrite (Z.add_comm _ Int63.wB)\n        || rewrite (Z.add_comm _ (_ * Int63.wB)));\n   repeat rewrite Z.add_assoc;\n   repeat rewrite<- Z.mul_add_distr_r.\n\nLemma mod_wB (x: Z):\n  (x * Int63.wB) mod 2 ^ 64 = if Z.odd x then Int63.wB else 0.\nProof.\nremember (Z.odd x) as last_bit.\nrewrite (Zdiv2_odd_eqn x). subst.\nrewrite Z.mul_add_distr_r.\nreplace (2 * Z.div2 x) with (Z.div2 x * 2) by apply Z.mul_comm.\nrewrite<- Z.mul_assoc.\nreplace (2 * Int63.wB) with (2 ^ 64)%Z by trivial.\nrewrite Z.add_comm. rewrite Z.mod_add by discriminate.\nnow destruct (Z.odd x).\nQed.\n\nLemma add_ok (a b: uint64):\n  Z_of_uint64 (add a b) = ((Z_of_uint64 a + Z_of_uint64 b) mod 2^64).\nProof.\nassert (L := Z_of_uint64_lower (add a b)).\nassert (U := Z_of_uint64_upper (add a b)).\nrepeat rewrite<- Z_of_uint64_alt in *.\nrewrite<- (Z.mod_small (Z_of_uint64' (add a b)) (2 ^ 64)) by tauto.\nunfold add. destruct a as (ha, la). destruct b as (hb, lb).\nassert (R := Int63.addc_spec la lb).\ncbn in L. cbn in U.\nunfold DoubleType.interp_carry in R.\nremember (Int63.addc la lb) as x. clear Heqx.\nunfold Z_of_uint64'.\ndestruct x; \n  [rewrite R | try rewrite Z.mul_1_l in R;\n               replace (Int63.to_Z i) with (Int63.to_Z la + Int63.to_Z lb + (-1) * Int63.wB) by lia];\n  wB_up; wB_up; repeat rewrite<- Z.add_assoc;\n  apply Z_mod_add_r;\n  destruct ha, hb; rewrite mod_wB; trivial.\nQed.\n\n(*******************************************************************************)\n\nDefinition shr_uint63 (a: uint64) (sh: uint63)\n: uint64\n:= if (sh == 0)%int63\n     then a\n     else let (hi, lo) := a in\n       (false, if hi\n                 then (((1 << 62) >> (sh - 1)) lor (lo >> sh))%int63\n                 else lsr lo sh).\n\nLemma shr_uint63_ok (a: uint64) (sh: uint63):\n  Z_of_uint64 (shr_uint63 a sh) = Z.shiftr (Z_of_uint64 a) (Int63.to_Z sh).\nProof.\nunfold shr_uint63.\nremember ((sh == 0)%int63) as sh0 eqn:Sh0. symmetry in Sh0. destruct sh0.\n{ rewrite Int63.eqb_spec in Sh0. now subst. }\nassert(BS := to_Z_bounded sh). remember (to_Z sh) as s.\nassert(SPos: 0 < s).\n{\n  enough (s <> 0) by lia.\n  intro H. subst.\n  replace 0 with (to_Z 0) in H by trivial.\n  apply to_Z_inj in H.\n  apply eqb_spec in H.\n  rewrite H in Sh0.\n  discriminate.\n}\ndestruct a as (hi, lo).\ndestruct hi; unfold Z_of_uint64.\n2:{\n  (* low case *)\n  rewrite Int63.lsr_spec.\n  rewrite Z.shiftr_div_pow2 by tauto.\n  now subst.\n}\n(* high case *)\nrewrite Int63.lor_spec'.\nrewrite Int63.lsr_spec.\nrewrite Int63.lsr_spec.\nrewrite Int63.lsl_spec.\nrewrite Int63.sub_spec.\nreplace (to_Z 1) with 1 by trivial.\nreplace (to_Z 62) with 62 by trivial.\nrewrite<- Heqs.\nclear Sh0 Heqs.\nassert(BN := to_Z_bounded lo). remember (to_Z lo) as n. clear Heqn.\nrewrite Z.mul_1_l. rewrite Z.shiftr_div_pow2 by tauto.\nreplace (2 ^ 62 mod wB) with (2 ^ 62) by trivial.\nreplace ((s - 1) mod wB) with (s - 1). 2:{ symmetry. apply Z.mod_small. lia. }\nassert (CS: 64 <= s \\/ s <= 63) by lia.\ncase CS; clear CS; intro CS.\n{\n  (* large shift, everything is 0 *)\n  replace (n / 2 ^ s) with 0.\n  2:{\n    symmetry. apply Z.div_small.\n    split. { tauto. }\n    replace Int63.wB with (2 ^ 63) in * by trivial.\n    apply (Z.lt_trans n (2^63) (2^s)). { tauto. }\n    apply Z.pow_lt_mono_r; lia.\n  }\n  rewrite Z.lor_0_r. \n  rewrite Z.div_small.\n  2:{\n    split. { lia. }\n    apply Z.pow_lt_mono_r; lia.\n  }\n  rewrite Z.div_small. { trivial. }\n  split. { lia. }\n  apply (Z.lt_le_trans _ (2^64) (2^s)).\n  { replace (2 ^ 64) with (wB + wB) by trivial. lia. }\n  apply Z.pow_le_mono_r; lia.\n}\nreplace (2 ^ 62 / 2 ^ (s - 1)) with (2 ^ 63 / 2 ^ s). \n2:{\n  replace (2 ^ 63) with (2 * (2 ^ 62)) by trivial.\n  replace (2 ^ s) with ((2 ^ (1 + (s - 1)))) by now replace (1 + (s - 1)) with s by lia.\n  rewrite Z.pow_add_r; try lia.\n  rewrite Z.div_mul_cancel_l; try lia.\n  apply Z.pow_nonzero; lia.\n}\nrepeat rewrite<- Z.shiftr_div_pow2 by tauto.\nrewrite<- Z.shiftr_lor.\nf_equal.\nrewrite<- Arith2.Z_add_nocarry_lor. { apply Z.add_comm. }\nrewrite Z.land_comm.\napply Arith2.Z_land_pow2_small. { tauto. }\nnow rewrite<- Z.leb_le.\nQed.\n\n(*******************************************************************************)\n\nDefinition shl_uint63 (a: uint64) (sh: uint63)\n: uint64\n:= if (sh == 0)%int63\n     then a\n     else let (hi, lo) := a in\n       (get_digit lo (63 - sh), lsl lo sh).\n\nLemma shl_uint63_ok (a: uint64) (sh: uint63):\n  Z_of_uint64 (shl_uint63 a sh) = (Z.shiftl (Z_of_uint64 a) (Int63.to_Z sh) mod 2^64)%Z.\nProof.\nrepeat rewrite<- Z_of_uint64_alt. repeat rewrite<- Z_of_uint64_lor'_ok.\nunfold shl_uint63.\nremember ((sh == 0)%int63) as sh0 eqn:Sh0. symmetry in Sh0. destruct sh0.\n{ \n  rewrite Int63.eqb_spec in Sh0. subst. rewrite Z.shiftl_0_r.\n  symmetry. apply Z.mod_small.\n  rewrite Z_of_uint64_lor'_ok.\n  rewrite Z_of_uint64_alt.\n  split. { apply Z_of_uint64_lower. } apply Z_of_uint64_upper.\n}\nassert(BS := to_Z_bounded sh). remember (to_Z sh) as s.\nassert(SPos: 0 < s).\n{\n  enough (s <> 0) by lia.\n  intro H. subst.\n  replace 0 with (to_Z 0) in H by trivial.\n  apply to_Z_inj in H.\n  apply eqb_spec in H.\n  rewrite H in Sh0.\n  discriminate.\n}\ndestruct a as (hi, lo).\nrewrite uint63_testbit_Z.\nunfold Z_of_uint64_lor'.\nrewrite Int63.lsl_spec.\napply Z.bits_inj'. intros k Knonneg.\nrewrite Z.lor_spec.\nrewrite<- Z.shiftl_mul_pow2 by now subst.\nrewrite<- Heqs.\nassert (BN := to_Z_bounded lo). remember (to_Z lo) as n.\nrewrite Z.shiftl_lor.\nreplace wB with (2^63) by trivial.\nrepeat rewrite<- Z.land_ones.\nrewrite Z.land_lor_distr_l.\nreplace (Z.land (Z.shiftl ((if hi then 1 else 0) * 2 ^ 63) s) (Z.ones 64)) with 0.\n3-4: now rewrite<- Z.leb_le.\n2:{\n  destruct hi. 2:{ rewrite Z.mul_0_l. rewrite Z.shiftl_0_l. rewrite Z.land_0_l. trivial. }\n  symmetry.\n  rewrite Z.mul_1_l.\n  rewrite Z.shiftl_mul_pow2 by tauto.\n  rewrite Z.land_ones by now rewrite<- Z.leb_le.\n  rewrite<- Z.pow_add_r; try lia.\n  replace (2 ^ (63 + s)) with (2^(s - 1) * 2^64).\n  2:{ rewrite<- Z.pow_add_r; try f_equal; lia. }\n  apply Z_mod_mult.\n}\nrewrite Z.lor_0_r.\nrepeat rewrite Z.land_spec.\nrepeat rewrite Z.testbit_ones_nonneg; try lia.\nremember (Z.testbit (Z.shiftl n s) k) as x.\nassert (CK: k <> 63 \\/ k = 63) by lia.\ncase CK; clear CK; intro CK.\n{\n  replace (Z.testbit ((if Z.testbit n (to_Z (63 - sh)%int63) then 1 else 0) * 2 ^ 63) k) with false.\n  2:{\n    symmetry.\n    destruct (Z.testbit n (to_Z (63 - sh)%int63)); [ rewrite Z.mul_1_l | rewrite Z.mul_0_l ].\n    { apply Z.pow2_bits_false. lia. }\n    apply Z.bits_0.\n  }\n  rewrite Bool.orb_false_r.\n  f_equal.\n  rewrite Arith2.Z_ltb_lt_quad. split; lia.\n}\nsubst k x.\nreplace (63 <? 63) with false by trivial.\nreplace (63 <? 64) with true by trivial.\nrewrite Bool.andb_false_r. rewrite Bool.orb_false_l. rewrite Bool.andb_true_r.\nrewrite Arith2.Z_testbit_flag_mul_pow2 by lia.\nrewrite Z.shiftl_spec by lia.\nrewrite sub_spec. replace (to_Z 63) with 63 by trivial.\nrewrite<- Heqs.\nassert (WB63: 63 < wB) by now rewrite<- Z.ltb_lt.\nassert (Q: (63 - s) mod wB = 63 - s \\/ 63 < (63 - s) mod wB).\n{\n  assert(B: -wB < 63 - s) by lia.\n  assert(WBNZ: wB <> 0) by discriminate.\n  assert(D := Z.div_mod (63 - s) wB WBNZ).\n  assert(WBPos: 0 < wB) by lia.\n  assert(BQ := Z.mod_pos_bound (63 - s) wB WBPos).\n  remember ((63 - s) mod wB) as q.\n  clear Heqq.\n  assert (L: -1 <= (63 - s) / wB) by nia.\n  assert (U: (63 - s) / wB <= 0) by nia.\n  assert (T: (63 - s) / wB = 0 \\/ (63 - s) / wB = -1) by lia.\n  case T; clear T; intro T; lia.\n}\ncase Q; clear Q; intro Q. { now rewrite Q. }\nassert (S63: 63 < s).\n{\n  apply Z.nle_gt. intro H.\n  replace ((63 - s) mod wB) with (63 - s) in *. \n  2:{ \n    rewrite Z.mod_small. { trivial. } \n    lia.\n  }\n  lia.\n}\nrewrite (Z.testbit_neg_r n (63 - s)) by lia.\napply Arith2.Z_testbit_small. { tauto. }\nrefine (Z.lt_trans n wB _ _ _). { tauto. }\nreplace wB with (2^63) by trivial.\napply Z.pow_lt_mono_r; try lia.\napply Z.mod_pos_bound.\ntrivial. apply Q.\nQed.\n\n(*******************************************************************************)\n\nDefinition bitwise_or (a b: uint64)\n: uint64\n:= ((fst a || fst b)%bool,  Int63.lor (snd a) (snd b)).\n\nLemma bitwise_or_ok (a b: uint64):\n  Z_of_uint64 (bitwise_or a b) = (Z.lor (Z_of_uint64 a) (Z_of_uint64 b)).\nProof.\nrepeat rewrite<- Z_of_uint64_lor_ok.\ndestruct a as (a_hi, a_lo).\ndestruct b as (b_hi, b_lo).\nunfold Z_of_uint64_lor. unfold bitwise_or.\ndestruct a_hi, b_hi;\n  match goal with\n  |- (if ?cond then _ else _) = ?rhs  => remember cond as c; cbn in Heqc; subst\n  end;\n  repeat rewrite lor_spec';\n  replace (snd (_, a_lo)) with a_lo by trivial;\n  replace (snd (_, b_lo)) with b_lo by trivial;\n  remember (to_Z a_lo) as x;\n  remember (to_Z b_lo) as y;\n  repeat rewrite Z.lor_assoc; trivial.\n{\n  (* goal: Z.lor (Z.lor x y) wB = Z.lor (Z.lor (Z.lor x wB) y) wB *)\n  repeat rewrite<- Z.lor_assoc. f_equal.\n  rewrite Z.lor_comm.\n  rewrite Z.lor_assoc.\n  now replace (Z.lor wB wB) with wB by trivial.\n}\n(* goal: Z.lor (Z.lor x y) wB = Z.lor (Z.lor x wB) y *)\nrepeat rewrite<- Z.lor_assoc. f_equal.\napply Z.lor_comm.\nQed.\n\n(*******************************************************************************)\n\nDefinition bitwise_xor (a b: uint64)\n: uint64\n:= (xorb (fst a) (fst b),  Int63.lxor (snd a) (snd b)).\n\nLemma bitwise_xor_ok (a b: uint64):\n  Z_of_uint64 (bitwise_xor a b) = (Z.lxor (Z_of_uint64 a) (Z_of_uint64 b)).\nProof.\nrepeat rewrite<- Z_of_uint64_lxor_ok.\ndestruct a as (a_hi, a_lo).\ndestruct b as (b_hi, b_lo).\nunfold Z_of_uint64_lxor. unfold bitwise_xor.\ndestruct a_hi, b_hi;\n  match goal with\n  |- (if ?cond then _ else _) = ?rhs  => remember cond as c; cbn in Heqc; subst\n  end;\n  repeat rewrite lxor_spec';\n  replace (snd (_, a_lo)) with a_lo by trivial;\n  replace (snd (_, b_lo)) with b_lo by trivial;\n  remember (to_Z a_lo) as x;\n  remember (to_Z b_lo) as y; \n  repeat rewrite Z.lxor_assoc; trivial.\n{\n  (* goal: Z.lxor x y = Z.lxor x (Z.lxor wB (Z.lxor y wB)) *)\n  rewrite (Z.lxor_comm y wB). f_equal.\n  rewrite<- Z.lxor_assoc.\n  now replace (Z.lor wB wB) with wB by trivial.\n}\nf_equal. apply Z.lxor_comm.\nQed.\n\n(*******************************************************************************)\n\nDefinition bitwise_and (a b: uint64)\n: uint64\n:= ((fst a && fst b)%bool,  Int63.land (snd a) (snd b)).\n\nLemma bitwise_and_ok (a b: uint64):\n  Z_of_uint64 (bitwise_and a b) = (Z.land (Z_of_uint64 a) (Z_of_uint64 b)).\nProof.\nrepeat rewrite<- Z_of_uint64_lor_ok.\ndestruct a as (a_hi, a_lo).\ndestruct b as (b_hi, b_lo).\nunfold Z_of_uint64_lor. unfold bitwise_and.\ndestruct a_hi, b_hi;\n  match goal with\n  |- (if ?cond then _ else _) = ?rhs  => remember cond as c; cbn in Heqc; subst\n  end;\n  repeat rewrite land_spec';\n  replace (snd (_, a_lo)) with a_lo by trivial;\n  replace (snd (_, b_lo)) with b_lo by trivial;\n  remember (to_Z a_lo) as x;\n  remember (to_Z b_lo) as y;\n  repeat rewrite Z.land_assoc; trivial.\n{ apply Z.lor_land_distr_l. }\n{ \n  rewrite Z.land_lor_distr_l.\n  replace (Z.land wB y) with 0. { now rewrite Z.lor_0_r. }\n  symmetry. rewrite Z.land_comm. apply Arith2.Z_land_pow2_small.\n  { subst. apply to_Z_bounded. }\n  rewrite<- Z.leb_le. trivial.\n}\nrewrite Z.land_lor_distr_r.\nreplace (Z.land x wB) with 0. { now rewrite Z.lor_0_r. }\nsymmetry. apply Arith2.Z_land_pow2_small.\n{ subst. apply to_Z_bounded. }\nrewrite<- Z.leb_le. trivial.\nQed.\n\n(*******************************************************************************)\n\nDefinition bitwise_not (a: uint64)\n: uint64\n:= (negb (fst a),  Int63.lxor (snd a) (of_Z (-1))).\n\nLemma bitwise_not_via_xor (a: uint64):\n  bitwise_not a = bitwise_xor a uint64_max_value.\nProof.\ntrivial.\nQed.\n\nLemma bitwise_not_ok (a: uint64):\n  Z_of_uint64 (bitwise_not a) = (Z.lnot (Z_of_uint64 a)) mod 2^64.\nProof.\nrewrite bitwise_not_via_xor. rewrite bitwise_xor_ok.\nrewrite<- Z.lxor_m1_r. rewrite<- Z.land_ones. 2: { now rewrite<- Z.leb_le. }\nassert (L := Z_of_uint64_lower a).\nassert (U := Z_of_uint64_upper a).\nremember (Z_of_uint64 a) as x. clear Heqx.\nrewrite uint64_max_value_ok.\nreplace (2 ^ 64 - 1) with (Z.ones 64) by trivial.\nrewrite Z_land_lxor_distr_l.\nf_equal.\nsymmetry. apply Z.land_ones_low. { assumption. }\napply Arith2.Z_log2_lt_pow2; try assumption.\nnow rewrite<- Z.ltb_lt.\nQed.\n\n(*******************************************************************************)\n\nDefinition uint64_of_be_bytes (b: byte * byte * byte * byte * byte * byte * byte * byte)\n: uint64\n:= match b with\n   | (b7, b6, b5, b4, b3, b2, b1, b0) =>\n       bitwise_or (shl_uint63 (false, int_of_byte b7) 56%int63)\n                  (false, ((int_of_byte b6 << 48) lor (int_of_byte b5 << 40) lor (int_of_byte b4 << 32)\n                       lor (int_of_byte b3 << 24) lor (int_of_byte b2 << 16) lor (int_of_byte b1 << 8)\n                       lor int_of_byte b0)%int63)\n   end.\n\nDefinition uint64_to_be_bytes (a: uint64)\n: byte * byte * byte * byte * byte * byte * byte * byte\n:= let (f, i) := a in\n    (byte_of_int (snd (shr_uint63 a 56)),\n     byte_of_int (i >> 48),\n     byte_of_int (i >> 40),\n     byte_of_int (i >> 32),\n     byte_of_int (i >> 24),\n     byte_of_int (i >> 16),\n     byte_of_int (i >> 8),\n     byte_of_int i)%int63.\n\nDefinition uint64_to_le_bytes (a: uint64)\n: byte * byte * byte * byte * byte * byte * byte * byte\n:= let (f, i) := a in\n    (byte_of_int i,\n     byte_of_int (i >> 8),\n     byte_of_int (i >> 16),\n     byte_of_int (i >> 24),\n     byte_of_int (i >> 32),\n     byte_of_int (i >> 40),\n     byte_of_int (i >> 48),\n     byte_of_int (snd (shr_uint63 a 56)))%int63.\n", "meta": {"author": "formalize", "repo": "coq-evm", "sha": "790328bf9294e32fbca3d7e47be48576e330b9dd", "save_path": "github-repos/coq/formalize-coq-evm", "path": "github-repos/coq/formalize-coq-evm/coq-evm-790328bf9294e32fbca3d7e47be48576e330b9dd/Arith/UInt64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7172578259440069}}
{"text": "Require Import Arith Sorted Permutation List DivConq msort. \nImport List.ListNotations.\nOpen Scope list_scope.\n\nRequire Extraction.\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlNatInt.\n\nExtraction Language OCaml.\nSet Extraction AccessOpaque.\n\nDefinition sorted := Sorted le.\nDefinition permutation := @Permutation nat.\n\nSection PermSplitPivot.\n\nVariable A : Type.\nVariable le: A -> A -> Prop.\nVariable le_dec: forall (x y: A), {le x y} + {~le x y}.\nImplicit Type l : list A.\n\nLemma Permutation_split_pivot: forall (a : A) l,\n  Permutation (fst (split_pivot A le le_dec a l) \n    ++ snd (split_pivot A le le_dec a l)) l.\nProof.\ninduction l; simpl; auto.\ndestruct (split_pivot A le le_dec a l); simpl in *.\ndestruct (le_dec a0 a); simpl; auto;\nrewrite <- Permutation_middle; constructor; auto.\nDefined.\n\nEnd PermSplitPivot.\n\nLemma qsort_prog : \n  forall (l : list nat), {l' : list nat | sorted l' /\\ permutation l' l}.\nProof.\nunshelve eapply div_conq_pivot. exact le. exact le_dec.\n- exists []; split; constructor.\n- intros; destruct H,H0,a0,a1; exists (merge x (a :: x0)); split.\n  + apply merge_sorted; auto; constructor; auto.\n    assert (Forall (le a) x0).\n    eapply Permutation_Forall. apply Permutation_sym; apply H2.\n    apply Forall_snd_split_pivot; intros; \n    apply not_le, gt_le_S,le_Sn_le in H3; auto.\n    inversion H3; auto.\n  + rewrite permutation_merge_concat, <- Permutation_middle; constructor;\n    rewrite H0, H2; apply Permutation_split_pivot.\nDefined.\n\nExtraction \"extraction/qsort.ml\" qsort_prog.\n", "meta": {"author": "jinxinglim", "repo": "coq-formalized-divide-and-conquer", "sha": "543a746ccf5c20245bf268f0700aa6cbad267582", "save_path": "github-repos/coq/jinxinglim-coq-formalized-divide-and-conquer", "path": "github-repos/coq/jinxinglim-coq-formalized-divide-and-conquer/coq-formalized-divide-and-conquer-543a746ccf5c20245bf268f0700aa6cbad267582/theories/qsort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7172578048435274}}
{"text": "Require Export P05.\n\n\n\n(** **** Exercise: 4 stars, advanced (ev_alternate)  *)\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\n(*\nInductive ev' : nat -> Prop :=\n| ev'_0 : ev' 0\n| ev'_2 : ev' 2\n| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).\n*)\n\n(** Prove that this definition is logically equivalent to\n    the old one. *)\n\nTheorem ev'_ev : forall n, ev' n <-> ev n.\nProof.\n  intros n. split.\n  - intros H. induction H.\n    + constructor.\n    + repeat constructor.\n    + apply ev_sum; assumption.\n  - intros H. induction H.\n    + constructor.\n    + apply ev'_sum with (n := 2) (m := n). constructor. assumption.\nQed.\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/06/P06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7172496833476968}}
{"text": "Require Export Arith.\nRequire Export ZArith.\nRequire Export List.\n\n(*** The Succ function ***)\n(* Succ x y l means that x and y occur directly after each other in the list l *)\n\nFixpoint Succ (A: Set) (x: A) (y: A) (l: list A) {struct l}: Prop :=\n  match l with\n  | nil => False\n  | hd :: tl => match tl with\n                      | nil => False\n                      | hd2 :: tl2 => ((x = hd) /\\ (y = hd2)) \\/ (Succ A x y tl)\n                      end\n  end.\n\n(***  Primitive Recursive Arithmetic  ***)\n\nInductive form : Set :=\n  | f_lt : nat -> nat -> form\n  | f_le : nat -> nat -> form\n  | f_eq : nat -> nat -> form\n  | f_p_eq: (nat * nat) -> (nat * nat) -> form\n  | f_ge : nat -> nat -> form\n  | f_gt : nat -> nat -> form\n  | f_zlt : Z -> Z -> form\n  | f_zle : Z -> Z -> form\n  | f_zeq : Z -> Z -> form\n  | f_p_zeq: (Z * Z) -> (Z * Z) -> form\n  | f_zge : Z -> Z -> form\n  | f_zgt : Z -> Z -> form\n  | f_not : form -> form\n  | f_and : form -> form -> form\n  | f_or : form -> form -> form\n  | f_imp : form -> form -> form\n  | f_all : nat -> (nat -> form) -> form\n  | f_ex : nat -> (nat -> form) -> form\n  | f_all_el : list nat -> (nat -> form) -> form\n  | f_ex_el : list nat -> (nat -> form) -> form\n  | f_in : nat -> list nat -> form\n  | f_p_in : (nat * nat) -> list (nat * nat) -> form\n  | f_succ: nat -> nat -> list nat -> form\n\t| f_zsucc: Z -> Z -> list Z -> form\n  | f_zall : Z -> (Z -> form) -> form\n  | f_zex : Z -> (Z -> form) -> form\n  | f_zall_el : list Z -> (Z -> form) -> form\n  | f_zex_el : list Z -> (Z -> form) -> form\n  | f_zin : Z -> list Z -> form\n  | f_p_zin : (Z * Z) -> list (Z * Z) -> form.\n\n(***  Boolean logic  ***)\n\nFixpoint b_le (n : nat) : nat -> bool :=\n  match n with\n  | O => fun m : nat => true\n  | S x => fun m : nat => match m with\n                          | O => false\n                          | S y => b_le x y\n                          end\n  end.\n\nFixpoint b_eq (n m : nat) {struct m} : bool :=\n  match n, m with\n  | O, O => true\n  | O, S y => false\n  | S x, O => false\n  | S x, S y => b_eq x y\n  end.\n\nDefinition b_lt (n m : nat) := b_le (S n) m.\nDefinition b_ge (n m : nat) := b_le m n.\nDefinition b_gt (n m : nat) := b_lt m n.\n\nDefinition b_not (x : bool) :=\n  match x with\n  | true => false\n  | false => true\n  end.\nDefinition b_and (x y : bool) :=\n  match x with\n  | true => y\n  | false => false\n  end.\nDefinition b_or (x y : bool) := match x with\n                                | true => true\n                                | false => y\n                                end.\nDefinition b_imp (x y : bool) := match x with\n                                 | true => y\n                                 | false => true\n                                 end.\n\nDefinition b_p_eq (n m: nat * nat): bool :=\n  match n, m with\n  | pair n1 n2, pair m1 m2 => b_and (b_eq n1 m1) (b_eq n2 m2)\n  end.\n\nFixpoint b_all (b : nat) (f : nat -> bool) {struct b} : bool :=\n  match b with\n  | O => (f O)\n  | S m => b_and (f (S m)) (b_all m f)\n  end.\n\nFixpoint b_ex (b : nat) (f : nat -> bool) {struct b} : bool :=\n  match b with\n  | O => (f O)\n  | S m => b_or (f (S m)) (b_ex m f)\n  end.\n\nFixpoint b_all_el (l : list nat) (f : nat -> bool) {struct l} : bool :=\n  match l with\n  | nil => true\n  | hd :: tl => b_and (f hd) (b_all_el tl f)\n  end.\n\nFixpoint b_ex_el (l : list nat) (f : nat -> bool) {struct l} : bool :=\n  match l with\n  | nil => false\n  | hd :: tl => b_or (f hd) (b_ex_el tl f)\n  end.\n\nFixpoint b_in (n: nat) (l: list nat) {struct l}: bool :=\n  match l with\n  | nil => false\n  | hd :: tl => b_or (b_eq hd n) (b_in n tl)\n  end.\n\nFixpoint b_p_in (p: nat * nat) (l: list (nat * nat)) {struct l}: bool :=\n  match l with\n  | nil => false\n  | hd :: tl => b_or (b_p_eq hd p) (b_p_in p tl)\n  end.\n\nFixpoint b_succ (x y: nat) (l: list nat) {struct l} : bool :=\n  match l with\n  | nil => false\n  | hd :: tl => match tl with\n                      | nil => false\n                      | hd2 :: tl2 => (b_or (b_and (b_eq hd x) (b_eq hd2 y)) (b_succ x y tl))\n                      end\n  end.\n\nFixpoint b_pos_less (x y : positive) (r : bool) {struct x} : bool :=\n  match x with\n  | xO x' =>\n      match y with\n      | xO y' => b_pos_less x' y' r\n      | xI y' => b_pos_less x' y' true\n      | xH => false\n      end\n  | xI x' =>\n      match y with\n      | xO y' => b_pos_less x' y' false\n      | xI y' => b_pos_less x' y' r\n      | xH => false\n      end\n  | xH => match y with\n          | xO y' => true\n          | xI y' => true\n          | xH => r\n          end\n  end.\n\n\nFixpoint b_pos_eq (x y : positive) {struct x} : bool :=\n  match x with\n  | xO x' =>\n      match y with\n      | xO y' => b_pos_eq x' y'\n      | xI y' => false\n      | xH => false\n      end\n  | xI x' =>\n      match y with\n      | xO y' => false\n      | xI y' => b_pos_eq x' y'\n      | xH => false\n      end\n  | xH => match y with\n          | xO y' => false\n          | xI y' => false\n          | xH => true\n          end\n  end.\n\nDefinition b_zeq (x y : Z) : bool :=\n  match x with\n  | Zpos x' =>\n      match y with\n      | Zpos y' => b_pos_eq x' y'\n      | Zneg y' => false\n      | Z0 => false\n      end\n  | Zneg x' =>\n      match y with\n      | Zpos y' => false\n      | Zneg y' => b_pos_eq x' y'\n      | Z0 => false\n      end\n  | Z0 => match y with\n          | Zpos y' => false\n          | Zneg y' => false\n          | Z0 => true\n          end\n  end.\n\nDefinition b_p_zeq (p q: Z * Z) : bool :=\n  match p, q with\n     pair p1 p2, pair q1 q2 => (b_and (b_zeq p1 q1) (b_zeq p2 q2))\n  end.\n  \nDefinition b_zle (x y : Z) : bool :=\n  match x with\n  | Zpos x' =>\n      match y with\n      | Zpos y' => b_pos_less x' y' true\n      | Zneg y' => false\n      | Z0 => false\n      end\n  | Zneg x' =>\n      match y with\n      | Zpos y' => true\n      | Zneg y' => b_pos_less y' x' true\n      | Z0 => true\n      end\n  | Z0 => match y with\n          | Zpos y' => true\n          | Zneg y' => false\n          | Z0 => true\n          end\n  end.\n\nDefinition b_zlt (x y : Z) : bool :=\n  match x with\n  | Zpos x' =>\n      match y with\n      | Zpos y' => b_pos_less x' y' false\n      | Zneg y' => false\n      | Z0 => false\n      end\n  | Zneg x' =>\n      match y with\n      | Zpos y' => true\n      | Zneg y' => b_pos_less y' x' false\n      | Z0 => true\n      end\n  | Z0 => match y with\n          | Zpos y' => true\n          | Zneg y' => false\n          | Z0 => false\n          end\n  end.\n\nDefinition b_zgt (x y : Z) : bool :=\n  match x with\n  | Zpos x' =>\n      match y with\n      | Zpos y' => b_pos_less y' x' false\n      | Zneg y' => true\n      | Z0 => true\n      end\n  | Zneg x' =>\n      match y with\n      | Zpos y' => false\n      | Zneg y' => b_pos_less x' y' false\n      | Z0 => false\n      end\n  | Z0 => match y with\n          | Zpos y' => false\n          | Zneg y' => true\n          | Z0 => false\n          end\n  end.\n\nDefinition b_zge (x y : Z) : bool :=\n  match x with\n  | Zpos x' =>\n      match y with\n      | Zpos y' => b_pos_less y' x' true\n      | Zneg y' => true\n      | Z0 => true\n      end\n  | Zneg x' =>\n      match y with\n      | Zpos y' => false\n      | Zneg y' => b_pos_less x' y' true\n      | Z0 => false\n      end\n  | Z0 => match y with\n          | Zpos y' => false\n          | Zneg y' => true\n          | Z0 => true\n          end\n  end.\n\nFixpoint b_all_nat (n: nat) (f: Z -> bool) {struct n}: bool :=\n  match n with\n  | O => true\n  | S n' => b_and (f (Zpos (P_of_succ_nat n'))) (b_all_nat n' f)\n  end.\n\nDefinition b_zall (n : Z) (f : Z -> bool) : bool :=\n  match n with\n  | Z0 => true\n  | Zneg x => true\n  | Zpos p => b_all_nat (nat_of_P p) f\n  end.\n\nFixpoint b_ex_nat (n : nat) (f : Z -> bool) {struct n} : bool :=\n  match n with\n  | O => false\n  | S n' => b_or (f (Zpos (P_of_succ_nat n'))) (b_ex_nat n' f)\n  end.\n\nDefinition b_zex (n : Z) (f : Z -> bool) : bool :=\n  match n with\n  | Z0 => false\n  | Zneg x => false\n  | Zpos p => b_ex_nat (nat_of_P p) f\n  end.\n\nFixpoint b_zall_el (l : list Z) (f : Z -> bool) {struct l} : bool :=\n  match l with\n  | nil => true\n  | hd :: tl => b_and (f hd) (b_zall_el tl f)\n  end.\n\nFixpoint b_zex_el (l : list Z) (f : Z -> bool) {struct l} : bool :=\n  match l with\n  | nil => false\n  | hd :: tl => b_or (f hd) (b_zex_el tl f)\n  end.\n\nFixpoint b_zin (z: Z) (l: list Z) {struct l}: bool :=\n  match l with\n  | nil => false\n  | hd :: tl => b_or (b_zeq z hd) (b_zin z tl)\n  end.\n\nFixpoint b_p_zin (p: Z * Z) (l: list (Z * Z)) {struct l} : bool :=\n  match l with\n  | nil => false\n  | hd :: tl => b_or (b_p_zeq p hd) (b_p_zin p tl)\n  end.\n\nFixpoint b_zsucc (x y: Z) (l: list Z) {struct l} : bool :=\n  match l with\n  | nil => false\n  | hd :: tl => match tl with\n                      | nil => false\n                      | hd2 :: tl2 => (b_or (b_and (b_zeq hd x) (b_zeq hd2 y)) (b_zsucc x y tl))\n                      end\n  end.\n\n(***  Translate form to bool  ***)\n\nFixpoint checkValid (p : form) : bool :=\n  match p with\n  | f_lt s t => b_lt s t\n  | f_le s t => b_le s t\n  | f_eq s t => b_eq s t\n  | f_p_eq s t => b_p_eq s t\n  | f_ge s t => b_ge s t\n  | f_gt s t => b_gt s t\n  | f_zlt s t => b_zlt s t\n  | f_zle s t => b_zle s t\n  | f_zeq s t => b_zeq s t\n  | f_p_zeq s t => b_p_zeq s t\n  | f_zge s t => b_zge s t\n  | f_zgt s t => b_zgt s t\n  | f_not q => b_not (checkValid q)\n  | f_and q r => b_and (checkValid q) (checkValid r)\n  | f_or q r => b_or (checkValid q) (checkValid r)\n  | f_imp q r => b_imp (checkValid q) (checkValid r)\n  | f_all t f => b_all t (fun y : nat => checkValid (f y))\n  | f_ex t f => b_ex t (fun y : nat => checkValid (f y))\n  | f_all_el l f => b_all_el l (fun y : nat => checkValid (f y))\n  | f_ex_el l f => b_ex_el l (fun y : nat => checkValid (f y))\n  | f_in n l => b_in n l\n  | f_p_in n l => b_p_in n l\n  | f_succ s t l => b_succ s t l\n\t| f_zsucc s t l => b_zsucc s t l\n  | f_zall n p => b_zall n (fun s : Z => checkValid (p s))\n  | f_zex n p => b_zex n (fun s : Z => checkValid (p s))\n  | f_zall_el l p => b_zall_el l (fun s : Z => checkValid (p s))\n  | f_zex_el l p => b_zex_el l (fun s : Z => checkValid (p s))\n  | f_zin z l => b_zin z l\n  | f_p_zin p l => b_p_zin p l\n  end.\n\n(***  Translate form to Prop  ***)\n\nFixpoint isValid (p : form) : Prop :=\n  match p with\n  | f_lt s t => s < t\n  | f_le s t => s <= t\n  | f_eq s t => s = t\n  | f_p_eq s t => s = t\n  | f_ge s t => s >= t\n  | f_gt s t => s > t\n  | f_zlt s t => (s < t)%Z\n  | f_zle s t => (s <= t)%Z\n  | f_zeq s t => s = t\n  | f_p_zeq s t => s = t\n  | f_zge s t => (s >= t)%Z\n  | f_zgt s t => (s > t)%Z\n  | f_not q => ~ isValid q\n  | f_and q r => isValid q /\\ isValid r\n  | f_or q r => isValid q \\/ isValid r\n  | f_imp q r => isValid q -> isValid r\n  | f_all t f => forall y : nat, y <= t -> isValid (f y)\n  | f_ex t f => exists y : nat, y <= t /\\ isValid (f y)\n  | f_all_el l f => forall y : nat, In y l -> isValid (f y)\n  | f_ex_el l f => exists y : nat, In y l /\\ isValid (f y)\n  | f_in n l => (In n l)\n  | f_p_in p l => (In p l)\n  | f_succ s t l => Succ nat s t l\n\t| f_zsucc s t l => Succ Z s t l\n  | f_zall n f => forall s : Z, (s > 0)%Z /\\ (s <= n)%Z -> isValid (f s)\n  | f_zex n f => exists s : Z, ((s > 0)%Z /\\ (s <= n)%Z) /\\ isValid (f s)\n  | f_zall_el l f => forall s : Z, In s l -> isValid (f s)\n  | f_zex_el l f => exists s : Z, In s l /\\ isValid (f s)\n  | f_zin z l => (In z l)\n  | f_p_zin p l => (In p l)\n  end.\n\n(***  Translate bool to Prop  ***)\n\nDefinition istrue (x : bool) := if x then True else False.\n\nLemma b_and_intro :\n forall x y : bool, istrue x -> istrue y -> istrue (b_and x y).\nProof.\n   intro x. case x. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma b_and_elim1 : forall x y : bool, istrue (b_and x y) -> istrue x.\nProof.\n   intro x. case x. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma b_and_elim2 : forall x y : bool, istrue (b_and x y) -> istrue y.\nProof.\n   intro x. case x. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma b_or_intro1 : forall x y : bool, istrue x -> istrue (b_or x y).\nProof.\n   intro x. case x. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma b_or_intro2 : forall x y : bool, istrue y -> istrue (b_or x y).\nProof.\n   intro x. case x. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma b_or_elim :\n forall x y : bool, istrue (b_or x y) -> istrue x \\/ istrue y.\nProof.\n   intro x. case x. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma bpl_false_true :\n forall p q : positive,\n istrue (b_pos_less p q false) -> istrue (b_pos_less p q true).\nProof.\n  simple induction p.\n    simple induction q.\n      intros. apply (H p1). apply H1.\n      intros. apply H1.\n      contradiction.\n    simple induction q.\n      intro. intro. simpl in |- *. trivial.\n      intro. intro. simpl in |- *. apply (H p1).\n      contradiction.\n    intros. case q.\n      simpl in |- *. trivial.\n      simpl in |- *. trivial.\n      simpl in |- *. trivial.\nQed.\n\nLemma bpl_true_false :\n forall p q : positive,\n istrue (b_pos_less p q true) -> istrue (b_pos_less p q false) \\/ p = q.\nProof.\n  double induction p q.\n    intros. elim (H0 p0).\n      intros. left. simpl in |- *. apply H2.\n      intros. right. elim H2. reflexivity.\n      simpl in H1. apply H1.\n    intros. elim (H0 p0).\n      intros. simpl in |- *. left. apply H2.\n      intros. simpl in H1. left. simpl in |- *. apply H1.\n      simpl in H1. apply bpl_false_true. apply H1.\n    intros. simpl in H0. contradiction.\n    intros. simpl in H1. left. simpl in |- *. apply H1.\n    intros. elim (H0 p0).\n      intros. simpl in |- *. left. apply H2.\n      intros. right. elim H2. reflexivity.\n      simpl in H1. apply H1.\n    intros. simpl in H0. contradiction.\n    intros. simpl in |- *. left. trivial.\n    intros. simpl in |- *. left. trivial.\n    intros. right. reflexivity.\nQed.\n\nLemma bpl_inductive1 :\n forall p0 p1 : positive,\n (Zpos p1 <= Zpos p0)%Z ->\n ((Zpos p1 < Zpos p0)%Z -> istrue (b_pos_less p1 p0 false)) ->\n (istrue (b_pos_less p1 p0 false) -> (Zpos p1 < Zpos p0)%Z) ->\n istrue (b_pos_less p1 p0 true).\nProof.\n  double induction p0 p1.\n    intros. simpl in |- *. apply H0.\n      apply H1.\n      apply H2.\n      apply H3.\n    intros. apply bpl_false_true. apply H2. elim (Zle_lt_or_eq (Zpos (xO p)) (Zpos (xI p2))).\n      trivial.\n      intros. discriminate H4.\n      exact H1.\n    intros. simpl in |- *. trivial.\n    intros. simpl in |- *. apply H2. elim (Zle_lt_or_eq (Zpos (xI p)) (Zpos (xO p2))).\n      trivial.\n      intros. discriminate H4.\n      exact H1.\n    intros. simpl in |- *. apply H0.\n      apply H1.\n      apply H2.\n      apply H3.\n    intros. simpl in |- *. trivial.\n    intro. case p.\n      intros. change (4 * Zpos p2 + 3 <= 1)%Z in H0. absurd (4 * Zpos p2 + 3 <= 1)%Z.\n        compute in |- *. auto.\n        apply H0.\n      intros. change (4 * Zpos p2 + 2 <= 1)%Z in H0. absurd (4 * Zpos p2 + 2 <= 1)%Z.\n        compute in |- *. auto.\n        apply H0.\n      intros. absurd (3 <= 1)%Z.\n        compute in |- *. auto.\n        apply H0.\n    intro. case p.\n      intros. change (4 * Zpos p2 + 2 <= 1)%Z in H0. absurd (4 * Zpos p2 + 2 <= 1)%Z.\n        compute in |- *. auto.\n        apply H0.\n      intros. change (4 * Zpos p2 <= 1)%Z in H0. simpl in |- *. simpl in H1. apply H1. change (4 * Zpos p2 < 1)%Z in |- *. omega.\n      intros. absurd (2 <= 1)%Z.\n        auto.\n        apply H0.\n    intros. simpl in |- *. trivial.\nQed.\n\nLemma bpl_inductive2 :\n forall p0 p1 : positive,\n istrue (b_pos_less p1 p0 true) ->\n ((Zpos p1 < Zpos p0)%Z -> istrue (b_pos_less p1 p0 false)) ->\n (istrue (b_pos_less p1 p0 false) -> (Zpos p1 < Zpos p0)%Z) ->\n (Zpos p1 <= Zpos p0)%Z.\nProof.\n  double induction p0 p1.\n    intros. change (Zpos p <= Zpos p2)%Z in |- *. apply H0. apply H1.\n    intros. simpl in H2. apply H2. apply H4.\n    intros. apply H3.  simpl in |- *. apply H4.\n    intros. apply Zlt_le_weak. apply H3. simpl in |- *. simpl in H1. apply H1.\n    intros. apply Zlt_le_weak. apply H2. simpl in |- *. trivial.\n    intros. apply Zlt_le_weak. apply H3. simpl in |- *. simpl in H1. apply H1.\n    intros. change (Zpos p <= Zpos p2)%Z in |- *. apply H0. apply H1. apply H2. apply H3.\n    intros. apply Zlt_le_weak. apply H2. simpl in |- *. trivial.\n    intros. simpl in H0. contradiction.\n    intros. simpl in H0. contradiction.\n    intros. omega.\nQed.\n\nLemma pos_lt :\n forall p q : positive, (Zpos p < Zpos q)%Z <-> istrue (b_pos_less p q false).\nProof.\n  double induction p q.\n    intros. split.\n      intros. simpl in |- *. elim (H0 p0). intros. apply H2. apply H1.\n      intros. change (Zpos p1 < Zpos p0)%Z in |- *. elim (H0 p0). intros. apply H3. apply H1.\n    intros. split. \n      intros. simpl in |- *. elim (H0 p0). intros. apply H2. change (Zpos (xO p1) < Zpos (xO p0))%Z in |- *. apply Zlt_trans with (Zpos (xI p1)). \n        replace (Zpos (xI p1)) with (Zsucc (Zpos (xO p1))). \n          apply Zle_lt_succ. omega. \n          trivial.\n          exact H1.\n      intros. elim (H0 p0). intros. assert (Zpos p1 < Zpos p0)%Z. \n        apply H3. apply H1. \n        change (2 * Zpos p1 + 1 < 2 * Zpos p0)%Z in |- *. omega.\n    intros. split.\n      intros. compute in H0. discriminate H0.\n      intros. simpl in H0. contradiction.\n    intros. split.\n      intro. assert (Zpos p1 <= Zpos p0)%Z.\n        change (2 * Zpos p1 < 2 * Zpos p0 + 1)%Z in H1. omega.\n          simpl in |- *. elim (H0 p0). intros. apply bpl_inductive1. apply H2. \n        apply H3. \n        apply H4. \n      intro. simpl in H1. elim (H0 p0). intros. assert (Zpos p1 <= Zpos p0)%Z. \n        apply bpl_inductive2. apply H1. apply H2. apply H3. change (2 * Zpos p1 < 2 * Zpos p0 + 1)%Z in |- *. omega. \n    intros. split.\n      intros. simpl in |- *. elim (H0 p0). intros. apply H2. apply H1. \n      intros. elim (H0 p0). intros. apply H3. apply H1. \n    intros. split.\n      intros. compute in H0. discriminate H0.\n      intros. simpl in H0. contradiction.\n    intros. split.\n      intros. simpl in |- *. trivial.\n      intros. compute in |- *. reflexivity.\n    intros. split.\n      intros. simpl in |- *. trivial.\n      intros. compute in |- *. reflexivity.\n    intros. split.\n      intros. compute in H. discriminate H. \n      intros. simpl in H. contradiction.\nQed.\n\nLemma pos_eq : forall p q : positive, p = q <-> istrue (b_pos_eq p q).\nProof.\n  double induction p q.\n    intros. split.\n      intros. elim H1. simpl in |- *. elim (H0 p1). intros. apply H2. reflexivity.\n      intros. simpl in H1. elim (H0 p0). intros. assert (p1 = p0). \n        apply H3. apply H1.\n        elim H4. reflexivity.\n    intros. split.\n      intros. discriminate H1.\n      intros. simpl in H1. contradiction.\n    intros. split.\n      intros. discriminate H0.\n      intros. simpl in H0. contradiction.\n    intros. split.\n      intros. discriminate H1.\n      intros. simpl in H1. contradiction.\n    intros. split.\n      intros. elim H1. simpl in |- *. elim (H0 p1). intros. apply H2. reflexivity.\n      intros. simpl in H1. elim (H0 p0). intros. assert (p1 = p0).\n        apply H3. apply H1.\n        elim H4. reflexivity.\n    intros. split.\n      intros. discriminate H0.\n      intros. simpl in H0. contradiction.\n    intros. split.\n      intros. discriminate H0.\n      intros. simpl in H0. contradiction.\n    intros. split.\n      intros. discriminate H0.\n      intros. simpl in H0. contradiction.\n    intros. split.\n      intros. simpl in |- *. trivial.\n      intros. reflexivity.\nQed.\n\nLemma b_zlt_le : forall s t : Z, istrue (b_zlt s t) -> istrue (b_zle s t).\nProof.\n  double induction s t.\n    intros. simpl in |- *. trivial.\n    intros. simpl in |- *. trivial.\n    intros. simpl in H. contradiction.\n    intros. simpl in H. contradiction.\n    intros. simpl in |- *. simpl in H. apply bpl_false_true. apply H. \n    intros. simpl in H. contradiction.\n    intros. simpl in |- *. trivial.\n    intros. simpl in |- *. trivial.\n    intros. simpl in |- *. simpl in H. apply bpl_false_true. apply H.\nQed.\n\nLemma b_zle_lt_or_eq :\n forall s t : Z,\n istrue (b_zle s t) -> istrue (b_zlt s t) \\/ istrue (b_zeq s t).\n  double induction s t.\n    intros. right. trivial.\n    intros. left. trivial.\n    intros. simpl in H. contradiction.\n    intros. simpl in H. contradiction.\n    intros. simpl in |- *. simpl in H. elim (bpl_true_false p0 p). intros.\n      left. apply H0.\n      intros. right. elim (pos_eq p0 p). intros. apply H1. apply H0.\n      apply H.\n    intros. simpl in H. contradiction.\n    intros. simpl in |- *. left. trivial. \n    intros. simpl in |- *. left. trivial.\n    intros. simpl in |- *. simpl in H. elim (bpl_true_false p p0). intros. \n      left. apply H0.\n      intros. right. elim (pos_eq p0 p). intros. apply H1. elim H0. reflexivity.\n      apply H.\nQed.\n\nLemma b_zlt_gt : forall s t : Z, istrue (b_zlt s t) <-> istrue (b_zgt t s).\nProof.\n  double induction s t.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto. \n    intros. simpl in |- *. tauto. \n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\nQed.\n\nLemma b_zle_ge : forall s t : Z, istrue (b_zle s t) <-> istrue (b_zge t s).\nProof.\n  double induction s t.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\n    intros. simpl in |- *. tauto.\nQed.\n\n(***  Correctness  ***)\n\nLemma leok : forall s t : nat, s <= t <-> istrue (b_le s t).\nProof.\n   simple induction s.\n      simple induction t.\n         simpl in |- *. split.\n            trivial.\n            auto.\n         intros t1 IHt1. simpl in |- *. split.\n            auto.\n            (* Auto.  Werkt hier niet meer in 6.2... *)\n            intro. apply le_S. apply lt_n_Sm_le. apply lt_O_Sn.\n      intros s1 IHs1. simple induction t.\n         simpl in |- *. split.\n            exact (le_Sn_O s1).\n            tauto.\n         intros t1 IHt1. simpl in |- *. case (IHs1 t1). split.\n            intro. apply H. apply le_S_n. assumption.\n            intro. apply le_n_S. apply H0. assumption.\nQed.\n\nLemma eqok : forall s t : nat, s = t <-> istrue (b_eq s t).\nProof.\n   simple induction s.\n      simple induction t.\n         simpl in |- *. split.\n            trivial.\n            auto.\n         intros t1 IHt1. simpl in |- *. split.\n            intro H. discriminate H.\n            tauto.\n      intros s1 IHs1. simple induction t.\n         simpl in |- *. split.\n            intro H. discriminate H.\n            tauto.\n         intros t1 IHt1. simpl in |- *. case (IHs1 t1). split.\n            intro. apply H. injection H1. tauto.\n            intro. rewrite H0. reflexivity. assumption.\nQed.\n\nLemma ltok : forall s t : nat, s < t <-> istrue (b_lt s t).\nProof.\n   intros s t. unfold lt, b_lt in |- *. exact (leok (S s) t).\nQed.\n\nLemma geok : forall s t : nat, s >= t <-> istrue (b_ge s t).\nProof.\n   intros s t. unfold ge, b_ge in |- *. exact (leok t s).\nQed.\n\nLemma gtok : forall s t : nat, s > t <-> istrue (b_gt s t).\nProof.\n   intros s t. unfold gt, b_gt in |- *. exact (ltok t s).\nQed.\n\nLemma notok :\n forall (p : Prop) (a : bool), (p <-> istrue a) -> (~ p <-> istrue (b_not a)).\nProof.\n   intros p a. case a. simpl in |- *. split. case H. intros. apply H2. apply H1.\n   tauto. tauto. simpl in |- *. split. tauto. case H. tauto.\nQed.\n\nLemma andok :\n forall (p q : Prop) (a b : bool),\n (p <-> istrue a) -> (q <-> istrue b) -> (p /\\ q <-> istrue (b_and a b)).\nProof.\n   intros p q a b. case a. case b. simpl in |- *. tauto. simpl in |- *. tauto.\n   case b. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma orok :\n forall (p q : Prop) (a b : bool),\n (p <-> istrue a) -> (q <-> istrue b) -> (p \\/ q <-> istrue (b_or a b)).\nProof.\n   intros p q a b. case a. case b. simpl in |- *. tauto. simpl in |- *. tauto.\n   case b. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma impok :\n forall (p q : Prop) (a b : bool),\n (p <-> istrue a) -> (q <-> istrue b) -> ((p -> q) <-> istrue (b_imp a b)).\nProof.\n   intros p q a b. case a. case b. simpl in |- *. tauto.\n   simpl in |- *. split. intros. case H0. intros. apply H2. apply H1. case H.\n   intros. apply H5. trivial. intros. case H1.\n   case b. simpl in |- *. tauto. simpl in |- *. tauto.\nQed.\n\nLemma peqok : forall s t : (nat * nat), s = t <-> istrue (b_p_eq s t).\nProof.\n  simple induction s.\n    simple induction t.\n      split.\n         intros. simpl. elim (andok (a = a0) (b = b0) (b_eq a a0) (b_eq b b0)). \n            intros. apply H0. inversion H. split.\n              trivial.\n              trivial.\n            apply eqok. \n            apply eqok.\n         intros. elim (andok (a = a0) (b = b0) (b_eq a a0) (b_eq b b0)).\n            intros. elim H1. \n              intros. replace a0 with a. replace b0 with b. trivial.\n              apply H.\n           apply eqok. \n           apply eqok.\nQed.\n\nLemma allok :\n forall (n : nat) (p : nat -> Prop) (f : nat -> bool),\n (forall x : nat, p x <-> istrue (f x)) ->\n ((forall x : nat, x <= n -> p x) <-> istrue (b_all n f)).\nProof.\n   simple induction n.\n   simpl. intros. split.\n      intros. elim (H 0). intros. apply H1. apply H0. trivial.\n      intros. replace x with 0. \n         elim (H 0). intros. apply H3. apply H0.\n         apply le_n_O_eq. apply H1.\n  simpl. intros. split.\n     case (H p f).\n       assumption.\n       intros. apply b_and_intro. \n          case (H0 (S n0)). intros. apply H4. apply H3. trivial.\n          apply H1. intros. apply H3. apply le_S. assumption.\n       intros. case (H0 x). intros. apply H4. case (le_lt_or_eq x (S n0)).\n          assumption.\n          intro. elim (H p f). \n             intros. apply H3. apply H7. apply (b_and_elim2 (f (S n0)) (b_all n0 f)). apply H1.\n             apply lt_n_Sm_le. assumption.\n             assumption. \n          intros. rewrite H5. apply (b_and_elim1 (f (S n0)) (b_all n0 f)). assumption.\nQed.\n\nLemma exok :\n forall (n : nat) (p : nat -> Prop) (f : nat -> bool),\n (forall x : nat, p x <-> istrue (f x)) ->\n ((exists x : nat, x <= n /\\ p x) <-> istrue (b_ex n f)).\nProof.\n   simple induction n.\n   simpl. intros. split.\n      intros. case H0. intros. case H1. intros. case (le_lt_or_eq x 0).\n        assumption.\n        intros. absurd (x < 0).\n          apply (lt_n_O x).\n          assumption.\n        intros. replace x with 0 in H3. elim (H 0). intros. apply H5. assumption.\n       intros. exists 0. split.\n         trivial.\n         elim (H 0). intros. apply H2. assumption.\n  simpl. intros. split.\n     intros.  elim H1. intros. elim H2. intros. elim (le_lt_or_eq x (S n0)). \n       intros. apply (b_or_intro2 (f (S n0)) (b_ex n0 f)). elim (H p f). \n          intros. apply H6. exists x. split.\n             apply lt_n_Sm_le. assumption.       \n             assumption.\n          assumption.\n       intros. apply (b_or_intro1 (f (S n0)) (b_ex n0 f)). replace (S n0) with x.  elim (H0 x). intros. apply H6. assumption.\n       apply H3.\n    intros. elim (b_or_elim (f (S n0)) (b_ex n0 f)). \n       intros. exists (S n0). split.\n          trivial.\n          elim (H0 (S n0)). intros. apply H4. assumption.\n       intros. elim (H p f). \n         intros. elim H4. intros. exists x. elim H5. intros. split.\n            apply le_S. assumption.\n            assumption.\n         assumption.\n         assumption.\n      assumption.\nQed.\n\nLemma allelok :\n forall (l : list nat) (p : nat -> Prop) (f : nat -> bool),\n (forall x : nat, p x <-> istrue (f x)) ->\n ((forall x : nat, In x l -> p x) <-> istrue (b_all_el l f)).\nProof.\n  induction l.\n    split. \n      simpl in |- *. trivial.\n      simpl in |- *. contradiction.\n    intros. elim (IHl p f). \n      split.\n        simpl in |- *. intros. apply b_and_intro. \n          elim (H a). intros. apply H3. apply H2. left. trivial.\n          intros. apply H0. intros. apply (H2 x). right. exact H3.\n        intros. elim H3.\n          intros. replace x with a. elim (H a). intros. apply H6. apply (b_and_elim1 (f a) (b_all_el l f)). apply H2.\n          apply H1. apply (b_and_elim2 (f a)). apply H2.\n      exact H. \nQed.\n\nLemma exelok :\n forall (l : list nat) (p : nat -> Prop) (f : nat -> bool),\n (forall x : nat, p x <-> istrue (f x)) ->\n ((exists x : nat, In x l /\\ p x) <-> istrue (b_ex_el l f)).\nProof.\n  induction l.\n    split.\n      simpl in |- *. intros. elim H0. intros. elim H1. intros. exact H2.\n      simpl in |- *. contradiction.\n    intros. elim (IHl p f).\n      split.\n        intros. simpl in |- *. elim H2. intros. elim H3. intros. elim H4.\n          intros. apply b_or_intro1. replace a with x. elim (H x). intros. apply H7. exact H5.\n          intros. apply b_or_intro2. apply H0. exists x. split.\n            exact H6.\n            exact H5.\n        simpl in |- *. intros. case (b_or_elim (f a) (b_ex_el l f)). \n          exact H2.\n          intros. exists a. split.\n            left. trivial.\n            elim (H a). intros. apply H5. exact H3.\n          intros. elim H1.\n            intros. exists x. elim H4. intros. split.\n              right. exact H5.\n              exact H6.\n            exact H3.\n      exact H.\nQed.\n\nLemma inok : forall (n: nat) (l: list nat), (In n l) <-> istrue (b_in n l).\nProof.\n  intros. split.\n    intros. induction l.\n      simpl. trivial.\n      simpl. elim H.\n        intros. apply b_or_intro1. elim (eqok a n). intros. apply H1. apply H0.\n        intros. apply b_or_intro2. apply IHl. apply H0.\n    intros. induction l.\n      trivial.\n      simpl in H. elim (b_or_elim (b_eq a n) (b_in n l)).\n        intros. simpl. left. elim (eqok a n). intros. apply H2. apply H0.\n        intros. simpl. right. apply IHl. apply H0.\n        apply H.\nQed.\n \nLemma pinok : forall (p: nat * nat) (l: list (nat * nat)), (In p l) <-> istrue (b_p_in p l).\nProof.\n  intros. split.\n     intros. induction l.\n        simpl. trivial.\n        simpl. elim H. \n          intros. apply b_or_intro1. elim (peqok a p). intros. apply H1. apply H0.\n          intros. apply b_or_intro2. apply IHl. apply H0. \n     intros. induction l. \n       trivial. \n       simpl in H. elim (b_or_elim (b_p_eq a p) (b_p_in p l)). \n          intros. simpl. left. elim (peqok a p). intros. apply H2. apply H0. \n          intros. simpl. right. apply IHl. apply H0.\n          apply H.\nQed.\n\nLemma succok : forall (x y: nat) (l: list nat), \n  (Succ nat x y l) <-> (istrue (b_succ x y l)).\nProof.\n  intros. split.\n     intros. induction l.                 \n        simpl in H. contradiction.\n        induction l. \n           simpl in H. contradiction.\n           elim H. \n              intros. simpl. apply b_or_intro1. elim H0. intros. apply b_and_intro. \n                elim (eqok a x). intros. apply H3. replace x with a. trivial.\n                elim (eqok a0 y). intros. apply H3. replace y with a0. trivial.\n              intros. simpl. apply b_or_intro2. change (istrue (b_succ x y (a0::l))).  apply IHl. apply H0.\n     intros. induction l.\n        simpl in H. contradiction.\n        induction l.\n           simpl in H. contradiction.\n           elim (b_or_elim (b_and (b_eq a x) (b_eq a0 y)) (b_succ x y (a0::l))). \n              intros. simpl. left. split.\n                 symmetry. elim (eqok a x). intros. apply H2. apply (b_and_elim1 (b_eq a x) (b_eq a0 y)). apply H0.\n                 symmetry. elim (eqok a0 y). intros. apply H2. apply (b_and_elim2 (b_eq a x) (b_eq a0 y)). apply H0.\n              intros. simpl. right. change (Succ nat x y (a0::l)). apply IHl. apply H0.\n           apply H. \nQed.\n\nLemma zltok : forall s t : Z, (s < t)%Z <-> istrue (b_zlt s t).\nProof.\n  simple induction s.\n    simple induction t. \n      (* ZERO < ZERO *)\n      simpl in |- *. split.\n        apply Zlt_irrefl.\n        contradiction. \n      (* ZERO < POS *)\n      simpl in |- *. split.\n        trivial.\n        intros. apply Zgt_lt. apply Zorder.Zgt_pos_0. \n      (* ZERO < NEG *)\n      simpl in |- *. split.\n        apply Zle_not_lt. apply Zlt_le_weak. apply Zorder.Zlt_neg_0.\n        contradiction.\n    simple induction t.\n      (* POS < ZERO *)\n      simpl in |- *. split.\n        apply Zle_not_lt. apply Zlt_le_weak. apply Zgt_lt. apply Zorder.Zgt_pos_0.\n        contradiction.\n      (* POS < POS *)\n      simpl in |- *. intro. apply pos_lt. \n      (* POS < NEG *)\n      intros. split.\n        intros. compute in H. discriminate H. \n        intros. simpl in H. contradiction.\n    simple induction t.\n      (* NEG < ZERO *)\n      simpl in |- *. split.\n        trivial.\n        intros. compute in |- *. reflexivity.\n      (* NEG < POS *)\n      simpl in |- *. split.\n        trivial.\n        intros. compute in |- *. reflexivity.\n      (* NEG < NEG *)\n      intros. simpl in |- *. replace (Zneg p) with (- Zpos p)%Z. \n        replace (Zneg p0) with (- Zpos p0)%Z. \n          elim (pos_lt p0 p). intros. split.\n            intros. apply H. change ((Zpos p0 ?= Zpos p)%Z = Datatypes.Lt) in |- *. rewrite Zcompare_opp. exact H1.\n            intros. change ((- Zpos p ?= - Zpos p0)%Z = Datatypes.Lt) in |- *. rewrite <- Zcompare_opp. apply H0. exact H1.\n\t    rewrite <- Zopp_neg. apply Zopp_involutive. \n            rewrite <- Zopp_neg. apply Zopp_involutive. \nQed.\n\nLemma zeqok : forall s t : Z, s = t <-> istrue (b_zeq s t).\nProof.\n  double induction s t.\n    split.\n      intros. simpl in |- *. trivial.\n      intros. reflexivity.\n    intros. split.\n      intros. discriminate H.\n      intros. simpl in H. contradiction.\n    intros. split. \n      intros. discriminate H. \n      intros. simpl in H. contradiction.\n    intros. split.\n      intros. discriminate H.\n      intros. simpl in H. contradiction.\n    intros. split.\n      intros. simpl in |- *. elim (pos_eq p0 p). intros. apply H0. injection H. trivial.\n      intros. elim (pos_eq p0 p). intros. assert (p0 = p).\n        apply H1. apply H.\n        elim H2. reflexivity.\n    intros. split.\n      intros. discriminate H.\n      intros. simpl in H. contradiction.\n    intros. split.\n      intros. discriminate H.\n      intros. simpl in H. contradiction.\n    intros. split.\n      intros. discriminate H.\n      intros. simpl in H. contradiction.\n    intros. split.\n      intros. simpl in |- *. elim (pos_eq p0 p). intros. apply H0. injection H. trivial.\n      intros. elim (pos_eq p0 p). intros. assert (p0 = p).\n        apply H1. apply H.\n        elim H2. reflexivity.\nQed.\n\nLemma pzeqok : forall s t : (Z * Z), s = t <-> istrue (b_p_zeq s t).\nProof.\n  intros. split.\n     elim s. elim t. intros. elim H. \n        simpl. apply b_and_intro. \n           elim (zeqok a0 a0). intros. apply H0. trivial.\n           elim (zeqok b0 b0). intros. apply H0. trivial. \n    elim s. elim t. intros. simpl in H. replace a with a0. replace b with b0. trivial.\n       elim (zeqok b0 b). intros. apply H1. apply (b_and_elim2 (b_zeq a0 a) (b_zeq b0 b)). apply H.\n       elim (zeqok a0 a). intros. apply H1. apply (b_and_elim1 (b_zeq a0 a) (b_zeq b0 b)). apply H.\nQed.\n\nLemma zleok : forall s t : Z, (s <= t)%Z <-> istrue (b_zle s t).\nProof.\n  intros. split.\n    intros. elim (Zle_lt_or_eq s t). \n      intros. elim (zltok s t). intros. apply b_zlt_le. apply H1. apply H0.\n      intros. elim H0. case s.\n        simpl in |- *. trivial.\n        simpl in |- *. intros. induction p.\n          simpl in |- *. apply IHp.\n          simpl in |- *. apply IHp. \n          simpl in |- *. trivial.\n      intros. simpl in |- *. induction p.\n        simpl in |- *. apply IHp.\n        simpl in |- *. apply IHp.\n        simpl in |- *. trivial.\n      apply H.\n    intros. elim (b_zle_lt_or_eq s t). \n      intros. apply Zlt_le_weak. elim (zltok s t). intros. apply H2.  apply H0.\n      intros. elim (zeqok s t). intros. replace t with s.\n        apply Zeq_le. reflexivity.\n        apply H2. apply H0.\n      apply H.\nQed.\n\nLemma zgtok : forall s t : Z, (s > t)%Z <-> istrue (b_zgt s t).\nProof.\n  intros. elim (b_zlt_gt t s). intros. split.\n    intros. apply H. assert (t < s)%Z. \n      apply Zgt_lt. apply H1.\n      elim (zltok t s). intros. apply H3. apply H2.\n    intros. apply Zlt_gt. elim (zltok t s). intros. apply H3. apply H0. apply H1.\nQed.\n\nLemma zgeok : forall s t : Z, (s >= t)%Z <-> istrue (b_zge s t).\nProof.\n  intros. elim (b_zle_ge t s). intros. split.\n    intros. apply H. assert (t <= s)%Z.\n      apply Zge_le. apply H1.\n      elim (zleok t s). intros. apply H3. apply H2.\n    intros. apply Zle_ge. elim (zleok t s). intros. apply H3. apply H0. apply H1.\nQed.\n\nTheorem allnatok :\n forall (n : nat) (p : Z -> Prop) (f : Z -> bool),\n (forall x : positive, p (Zpos x) <-> istrue (f (Zpos x))) ->\n ((forall x : positive, (Zpos x < Zpos (P_of_succ_nat n))%Z -> p (Zpos x)) <->\n  istrue (b_all_nat n f)).\nProof.\n  intros. split.\n    intros. induction n as [| n Hrecn].\n      intros. simpl in |- *. trivial.\n      intros. simpl in |- *. apply b_and_intro. \n        elim (H (P_of_succ_nat n)). intros. apply H1. apply H0. simpl in |- *. rewrite Zpos_succ_morphism. apply Zlt_succ. \n        apply Hrecn. intros. apply H0. simpl in |- *. rewrite Zpos_succ_morphism. apply Zlt_lt_succ. assumption.\n      intros. elim (H x). intros. apply H3. induction n as [| n Hrecn].\n        absurd (Zpos x < Zsucc 0)%Z. \n          apply Zle_not_lt. apply Zgt_le_succ. apply Zorder.Zgt_pos_0. \n          apply H1.\n      elim\n       (andok (istrue (f (Zpos (P_of_succ_nat n)))) \n          (istrue (b_all_nat n f)) (f (Zpos (P_of_succ_nat n)))\n          (b_all_nat n f)).\n        intros. elim H5.\n          intros. elim (Zle_lt_or_eq (Zpos x) (Zpos (P_of_succ_nat n))).\n            intros. apply Hrecn.\n              apply H7.\n              apply H8.\n            intros. rewrite H8. apply H6.\n            simpl in H1. rewrite Zpos_succ_morphism in H1. apply Zlt_succ_le. apply H1.\n          apply H0.\n        tauto.\n        tauto.\nQed.\n\nTheorem zallok :\n forall (z : Z) (p : Z -> Prop) (f : Z -> bool),\n (forall x : Z, p x <-> istrue (f x)) ->\n ((forall x : Z, (x > 0)%Z /\\ (x <= z)%Z -> p x) <-> istrue (b_zall z f)).\nProof.\n  intros. split.\n    intros. induction z as [| p0| p0].\n      simpl in |- *. trivial.\n      simpl in |- *. elim (allnatok (nat_of_P p0) p f). \n        intros. apply H1. intros. apply H0. split.\n          apply Zorder.Zgt_pos_0.\n          rewrite P_of_succ_nat_o_nat_of_P_eq_succ in H3. rewrite Zpos_succ_morphism in H3. apply Zlt_succ_le. apply H3.\n        intros. apply H.\n      simpl in |- *. trivial.\n    intros. induction z as [| p0| p0].\n      elim H1. intros. absurd (x <= 0)%Z.\n        apply Zlt_not_le. apply Zgt_lt. apply H2.\n        apply H3.\n      induction x as [| p1| p1].\n        elim H1. intros. absurd (0 > 0)%Z.\n          apply Zgt_irrefl. \n          apply H2.\n        simpl in H0. elim (allnatok (nat_of_P p0) p f).\n          intros. apply H3.\n            apply H0.\n            rewrite P_of_succ_nat_o_nat_of_P_eq_succ. rewrite Zpos_succ_morphism. apply Zle_lt_succ. elim H1. intros. apply H5.\n          intros. apply H.\n        elim H1. intros. absurd (Zneg p1 > 0)%Z.\n          apply Zle_not_gt. apply Zlt_le_weak. apply Zorder.Zlt_neg_0.\n          apply H2.\n      elim H1. intros. absurd (x <= Zneg p0)%Z.\n        apply Zlt_not_le. apply Zgt_lt. apply Zgt_trans with 0%Z.\n          apply H2.\n          apply Zlt_gt. apply Zorder.Zlt_neg_0.\n        apply H3. \nQed.\n\nTheorem exnatok :\n forall (n : nat) (p : Z -> Prop) (f : Z -> bool),\n (forall x : positive, p (Zpos x) <-> istrue (f (Zpos x))) ->\n ((exists x : positive, (Zpos x < Zpos (P_of_succ_nat n))%Z /\\ p (Zpos x)) <->\n  istrue (b_ex_nat n f)).\nProof.\n  simple induction n.\n  simpl in |- *. split.\n    intros. elim H0. intros. elim H1. intros. absurd (Zpos x < Zsucc 0)%Z.\n      apply Zle_not_lt. apply Zgt_le_succ. apply Zorder.Zgt_pos_0.\n      apply H2.\n    tauto.\n  simpl in |- *. intros. case (H p f). assumption. split.\n    intros. case H3. intros. case H4. intros. case (Zle_lt_or_eq (Zpos x) (Zpos (P_of_succ_nat n0))).\n      apply Zlt_succ_le. rewrite Zpos_succ_morphism in H5. apply H5.\n      intros. apply b_or_intro2. apply H1. exists x. split.\n        apply H7.\n        apply H6.\n      intros. apply b_or_intro1. rewrite <- H7. case (H0 x). intros. apply H8. assumption.\n    intros. case (b_or_elim (f (Zpos (P_of_succ_nat n0))) (b_ex_nat n0 f)).\n      apply H3.\n      intros. exists (P_of_succ_nat n0). split.\n        rewrite Zpos_succ_morphism. apply Zlt_succ.\n        case (H0 (P_of_succ_nat n0)). tauto.\n      intros. case (H2 H4). intros. case H5. intros. exists x. split.\n      rewrite Zpos_succ_morphism. apply Zlt_lt_succ. apply H6. apply H7.\nQed.\n\nTheorem zexok :\n forall (z : Z) (p : Z -> Prop) (f : Z -> bool),\n (forall x : Z, p x <-> istrue (f x)) ->\n ((exists x : Z, ((x > 0)%Z /\\ (x <= z)%Z) /\\ p x) <-> istrue (b_zex z f)).\nProof.\n  intros. split.\n    intros. induction z as [| p0| p0].\n      case H0. intros. case H1. intros. case H2. intros. absurd (x <= 0)%Z.\n        apply Zlt_not_le. apply Zgt_lt. apply H4.\n        apply H5.\n      simpl in |- *. elim (exnatok (nat_of_P p0) p f).\n        intros. apply H1. case H0. intros. case H3. intros. case H4. intros. induction x as [| p1| p1].\n          absurd (0 > 0)%Z.\n            apply Zgt_irrefl.\n            apply H6.\n          exists p1. split.\n            rewrite P_of_succ_nat_o_nat_of_P_eq_succ. rewrite Zpos_succ_morphism. apply Zle_lt_succ. assumption.\n            apply H5.\n          absurd (Zneg p1 > 0)%Z.\n            apply Zle_not_gt. apply Zlt_le_weak. apply Zorder.Zlt_neg_0.\n            apply H6.\n        intros.\n      apply H. \n    case H0. intros. case H1. intros. case H2. intros. absurd (x <= Zneg p0)%Z.\n      apply Zlt_not_le. apply Zgt_lt. apply Zgt_trans with 0%Z.\n        apply H4.\n        apply Zlt_gt. apply Zorder.Zlt_neg_0.\n      apply H5.\n  intros. induction z as [| p0| p0].\n    simpl in H0. contradiction.\n    simpl in H0. elim (exnatok (nat_of_P p0) p f).\n      intros. case H2.\n        apply H0.\n        intros. exists (Zpos x). case H3. intros. split.\n          split.\n            apply Zorder.Zgt_pos_0.\n            rewrite P_of_succ_nat_o_nat_of_P_eq_succ in H4. rewrite Zpos_succ_morphism in H4. apply Zlt_succ_le. apply H4.\n          apply H5.\n      intros. apply H.\n    simpl in H0. contradiction.\nQed.\n\nLemma zallelok :\n forall (l : list Z) (p : Z -> Prop) (f : Z -> bool),\n (forall x : Z, p x <-> istrue (f x)) ->\n ((forall x : Z, In x l -> p x) <-> istrue (b_zall_el l f)).\nProof.\n  intros. induction l as [| a l Hrecl].\n    split. intros.\n      simpl in |- *. trivial.\n      simpl in |- *. contradiction.\n    intros. elim Hrecl. intros.\n      split.\n        simpl in |- *. intros. apply b_and_intro.\n          elim (H a). intros. apply H3. apply H2. left. reflexivity.\n          apply H0. intros. apply H2. right. exact H3.\n        simpl in |- *. intros. elim H3. \n          intros. elim H4. elim (H a). intros. apply H6. apply (b_and_elim1 (f a) (b_zall_el l f)). apply H2.\n          apply H1. apply (b_and_elim2 (f a)). apply H2.\nQed.\n\nLemma zexelok :\n forall (l : list Z) (p : Z -> Prop) (f : Z -> bool),\n (forall x : Z, p x <-> istrue (f x)) ->\n ((exists x : Z, In x l /\\ p x) <-> istrue (b_zex_el l f)).\nProof.\n  intros. induction l as [| a l Hrecl].\n    split.\n      intros. simpl in |- *. elim H0. intros. elim H1. intros. simpl in H2. assumption.\n      simpl in |- *. contradiction.\n    split.\n      intros. simpl in |- *. elim H0. intros. elim H1. intros. elim H2.\n        intros. apply b_or_intro1. replace a with x. elim (H x). intros. apply H5. assumption.\n        intros. apply b_or_intro2. elim Hrecl. intros. apply H5. exists x. split.\n          assumption.\n          assumption.\n      intros. simpl in H0. elim (b_or_elim (f a) (b_zex_el l f)). \n        intros. exists a. split.\n          simpl in |- *. left. reflexivity.\n          elim (H a). intros. apply H3. assumption.\n        intros. elim Hrecl. intros. elim H3.\n          intros. exists x. elim H4. intros. split.\n            simpl in |- *. right. assumption.\n            assumption.\n          assumption.\n      assumption.\nQed.\n\nLemma zinok: forall (z: Z) (l: list Z), (In z l) <-> istrue (b_zin z l).\nProof.\n  intros. split.\n    intros. induction l.\n      simpl. trivial.\n      simpl. elim H.\n        intros. apply b_or_intro1. elim (zeqok z a). intros. apply H1. symmetry. apply H0.\n        intros. apply b_or_intro2. apply IHl. apply H0.\n    intros. induction l.\n      simpl. trivial.\n      simpl. simpl in H. elim (b_or_elim (b_zeq z a) (b_zin z l)).\n        intros. left. elim (zeqok z a). intros. symmetry. apply H2. apply H0.\n        intros. right. apply IHl. apply H0.\n        apply H.\nQed.\n\nLemma pzinok: forall (p: Z * Z) (l: list (Z * Z)), (In p l) <-> istrue (b_p_zin p l).\nProof.\n  intros. split.\n     intros. induction l.      \n        simpl in H. contradiction.\n        simpl. elim H. \n           intros. apply b_or_intro1. elim (pzeqok p a). intros. apply H1. symmetry. apply H0.\n           intros. apply b_or_intro2. apply IHl. apply H0.\n     intros. induction l.  \n        simpl in H. contradiction.\n        simpl. simpl in H. elim (b_or_elim (b_p_zeq p a) (b_p_zin p l)).\n           intros. left. elim (pzeqok p a). intros. symmetry. apply H2. apply H0.\n           intros. right. apply IHl. apply H0.\n          apply H.\nQed.\n\nLemma zsuccok : forall (x y: Z) (l: list Z), \n  (Succ Z x y l) <-> (istrue (b_zsucc x y l)).\nProof.\n  intros. split.\n     intros. induction l.\n        simpl in H. contradiction.\n        induction l.\n           simpl in H. contradiction.\n           elim H.\n              intros. simpl. apply b_or_intro1. elim H0. intros. apply b_and_intro.\n                 elim (zeqok a x). intros. apply H3. replace x with a. trivial.\n                 elim (zeqok a0 y). intros. apply H3. replace y with a0. trivial.\n              intros. simpl. apply b_or_intro2. change (istrue (b_zsucc x y (a0::l))). apply IHl. apply H0.\n    intros. induction l.\n       simpl in H. contradiction.\n        induction l.\n           simpl in H. contradiction.\n           elim (b_or_elim (b_and (b_zeq a x) (b_zeq a0 y)) (b_zsucc x y (a0::l))).\n              intros. simpl. left. split.\n                 symmetry. elim (zeqok a x). intros. apply H2. apply (b_and_elim1 (b_zeq a x) (b_zeq a0 y)). apply H0.\n                 symmetry. elim (zeqok a0 y). intros. apply H2. apply (b_and_elim2 (b_zeq a x) (b_zeq a0 y)). apply H0.\n             intros. simpl. right. change (Succ Z x y (a0::l)). apply IHl. apply H0.\n           apply H.\nQed.\n\nTheorem ok : forall p : form, isValid p <-> istrue (checkValid p).\nProof.\n  simple induction p.\n    intros. exact (ltok n n0).\n    intros. exact (leok n n0).\n    intros. exact (eqok n n0).\n    intros. exact (peqok p0 p1).    \n    intros. exact (geok n n0).\n    intros. exact (gtok n n0).\n    intros. exact (zltok z z0). \n    intros. exact (zleok z z0).\n    intros. exact (zeqok z z0).\n    intros. exact (pzeqok p0 p1).\n    intros. exact (zgeok z z0).  \n    intros. exact (zgtok z z0). \n    intros. exact (notok (isValid f) (checkValid f) H).\n    intros. exact (andok (isValid f) (isValid f0) (checkValid f) (checkValid f0) H H0). \n    intros. exact (orok (isValid f) (isValid f0) (checkValid f) (checkValid f0) H H0).\n    intros. exact (impok (isValid f) (isValid f0) (checkValid f) (checkValid f0) H H0).\n    intros. exact\n  (allok n (fun y : nat => isValid (f y)) (fun y : nat => checkValid (f y))\n     (fun x : nat => H x)).  \n    intros. exact\n  (exok n (fun y : nat => isValid (f y)) (fun y : nat => checkValid (f y))\n     (fun x : nat => H x)).\n    intros. exact\n  (allelok l (fun y : nat => isValid (f y)) (fun y : nat => checkValid (f y))\n     (fun x : nat => H x)).\n    intros. exact\n  (exelok l (fun y : nat => isValid (f y)) (fun y : nat => checkValid (f y))\n     (fun x : nat => H x)).\n    intros. exact (inok n l).\n    intros. exact (pinok p0 l).\n    intros. exact (succok n n0 l). \n    intros. exact (zsuccok z z0 l).\n    intros. exact\n  (zallok z (fun y : Z => isValid (f y)) (fun y : Z => checkValid (f y))\n     (fun x : Z => H x)).  \n    intros. exact\n  (zexok z (fun y : Z => isValid (f y)) (fun y : Z => checkValid (f y))\n     (fun x : Z => H x)).\n    intros. exact\n  (zallelok l (fun y : Z => isValid (f y)) (fun y : Z => checkValid (f y))\n     (fun x : Z => H x)).\n    intros. exact\n  (zexelok l (fun y : Z => isValid (f y)) (fun y : Z => checkValid (f y))\n     (fun x : Z => H x)).\n    intros. exact (zinok z l).\n    intros. exact (pzinok p0 l).\nQed.\n", "meta": {"author": "jaapb", "repo": "pra", "sha": "2264f4b1b13d50ce5fd4a02b3de3a52986c717a6", "save_path": "github-repos/coq/jaapb-pra", "path": "github-repos/coq/jaapb-pra/pra-2264f4b1b13d50ce5fd4a02b3de3a52986c717a6/theories/pra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7172496823409775}}
{"text": "(**************************************************************)\n(*   Copyright                                                *)\n(*             Jean-François Monin           [+]              *)\n(*             Dominique Larchey-Wendling    [*]              *)\n(*                                                            *)\n(*            [+] Affiliation VERIMAG - Univ. Grenoble-Alpes  *)\n(*            [*] Affiliation LORIA -- CNRS                   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(* List traversal from right to left *)\n\nRequire Import List Utf8.\nImport ListNotations.\n\nRequire Import lr.\n\n(* ========================================================================== *)\n(* Tools for recursive programming on lists traversed from right to left *)\n\nSection sec_context.\n\nContext {A : Type}.\nImplicit Type l u : list A.\nImplicit Type r : lr A.\nImplicit Type z : A.\n\n(* High-level version *)\n(* \n                      𝔻listz u\n  ----------      ----------------\n  𝔻listz []       𝔻listz (u +: z)\n\n *)\n\nInductive 𝔻listz : list A → Prop :=\n| 𝔻nil : 𝔻listz []\n| 𝔻consr : ∀ u z, 𝔻listz u → 𝔻listz (u +: z)\n.\n\nDefinition 𝔻listz_all l : 𝔻listz l.\nProof.\n  induction l as [| x u D].\n  - constructor.\n  - induction D as [| u z D HD].\n    + change [x] with ([] +: x); do 2 constructor.\n    + apply (𝔻consr _ _ HD). (* (x :: (u +: z))  =  ((x :: u) +: z) *)\nDefined.\n\nUnset Elimination Schemes.\n\n(* We will use the following variant of the previous definition,\n   which sticks to the implementation of the fake pattern matching\n\n   |  fakematch l with  |    by     |   match l2r l with    |\n   |  | [] => ...       |           |   | Nilr => ...       |\n   |  | u +: z => ...   |           |   | Consr u z => ...  |\n   |  end               |           |   end                 |\n\n  and turns out to have an easier-to-explain inversion.\n\n  The introduction rules are:\n\n                       𝔻lz u         𝔻lr (l2r l)\n   ---------      ---------------     -----------\n   𝔻lr Nilr       𝔻lr (Consr u z)       𝔻lz l\n\n *)\n\nInductive 𝔻lz : list A -> Prop :=\n| 𝔻lz_1 l : 𝔻lr (l2r l) → 𝔻lz l\nwith 𝔻lr  : lr A -> Prop :=\n| 𝔻lr_Nilr : 𝔻lr Nilr\n| 𝔻lr_Consr : ∀ u z, 𝔻lz u → 𝔻lr (Consr u z)\n.\n\nSet Elimination Schemes.\n\n(* The induction scheme for 𝔻lz is easy to prove, by fixpoint,\n   basic pattern matchings, and a trivial rewriting step *)\nTheorem 𝔻lz_ind (P: list A → Prop) :\n  P []  →  (∀ u, P u → ∀ z, P (u +: z)) →\n  ∀ l, 𝔻lz l → P l.\nProof.\n  intros Pnil Pconsr.\n  refine (fix fxp l D {struct D} : _ := _).\n  destruct D as [l D]. rewrite <- lrl_id.\n  destruct D as [| u z Pu]; simpl.\n  - apply Pnil.\n  - apply Pconsr. apply (fxp u Pu).\nQed.\n\n(* Defining 𝔻lz_rect is more difficult.\n   Done below using the Braga approach *)\n\n(* The two definition of 𝔻lz are actually equivalent *)\nLemma lz_listz l : 𝔻lz l → 𝔻listz l.\nProof.\n  induction 1; constructor; assumption.\nQed.\n\nLemma listz_lz l : 𝔻listz l → 𝔻lz l.\nProof.\n  intros D.\n  induction D as [| u z D HD]; constructor.\n  - constructor.\n  - rewrite l2r_consr. constructor. apply HD.\nQed.\n\nCorollary 𝔻lz_all l : 𝔻lz l.\nProof. apply listz_lz, 𝔻listz_all. Qed.\n\n(* -------------------------------------------------------------------------- *)\n(* Structural projection of 𝔻consr *)\n\nLet shape r : Prop :=\n  match r with Consr u z => True | _ => False end.\n\n(* Simplest version without \"harmless\" (or \"singleton\") Prop to Type elim *)\n(* Recovering the u component of r when r is Consr u z with an available default value:\n   the u given as input.\n   This makes no assumption on the type of u, and\n   z could be recovered in the same way if needed, using\n        let z := match r with Consr u z => z | _ => z end in\n*)\n\n(* Designed in 2 steps *)\nLet π_𝔻lr {u z} (D: 𝔻lr (Consr u z)) : 𝔻lz u :=\n  match D in 𝔻lr r return\n        let u := match r with Consr u z => u | _ => u end \n        in shape r → 𝔻lz u with\n  | 𝔻lr_Consr u z D => λ G, D\n  |  _              => λ G, match G with end\n  end I.\n\n(* Versions using an auxiliary function defined first, for recovering u from r *)\n(* Version using a \"harmless\" (or \"singleton\") Prop to Type elim *)\n\nLet lrleft_he r : shape r → list A :=\n  match r with Consr u z => λ _, u | _ => λ G, (match G with end) end.\n\nLet π_𝔻lr_he {u z} (D: 𝔻lr (Consr u z)) : 𝔻lz u :=\n  match D in 𝔻lr r return ∀ G, 𝔻lz (lrleft_he r G) with\n  | 𝔻lr_Consr u0 z0 D0 => λ G, D0\n  |  _                  => λ G, match G with end\n  end I.\n\n(** Another version w/o harmless elim Prop -> Type using False_elim *)\n\nDefinition False_elim X : False -> X :=\n  fix loop f := loop (match f : False with end).\n\nLet lrleft_no_he r : shape r → list A :=\n  match r with Consr u z => λ _, u | _ => λ G, False_elim _ G end.\n\nLet π_𝔻lr_no_he {u z} (D: 𝔻lr (Consr u z)) : 𝔻lz u :=\n  match D in 𝔻lr r return ∀ G, 𝔻lz (lrleft_no_he r G) with\n  | 𝔻lr_Consr u0 z0 D0 => λ G, D0\n  |  _                  => λ G, match G with end\n  end I.\n\n(* Finally, the simple version given first can be written in a similar way *)\nLet lrleft r : list A → list A :=\n  match r with Consr u z => λ _, u | _ => λ u0, u0 end.\n\nLet π_𝔻lr' {u z} (D: 𝔻lr (Consr u z)) : 𝔻lz u :=\n  match D in 𝔻lr r return ∀(G: shape r), 𝔻lz (lrleft r u) with\n  | 𝔻lr_Consr u0 z0 D0 => λ G, D0\n  |  _                  => λ G, match G with end\n  end I.\n\n(* In contrast, lrleft_he and lrleft_no_he cannot be inlined\n   because they require a G argument, whose type depends on r.\n*)\n\n\n(* Definitions of π_𝔻lz *)\nDefinition π_𝔻lz {u z} (D : 𝔻lz (u +: z)) : 𝔻lz u :=\n  match D in 𝔻lz l return l = u+:z → _ with\n    𝔻lz_1 l Dr => λ G, π_𝔻lr (same_by_l2r_consr G Dr)\n  end eq_refl.\n\n(* Compact Version in 1 step *)\nDefinition π_𝔻lz_compact {u z} (D : 𝔻lz (u +: z)) : 𝔻lz u :=\n match D in 𝔻lz l return l = u+:z → _ with\n | 𝔻lz_1 _ Dr => λ G, \n   match same_by_l2r_consr G Dr in 𝔻lr r return\n         let u := match r with Consr u z => u | _ => u end in\n         shape r → 𝔻lz u with\n   | 𝔻lr_Consr u _ Du => λ G, Du\n   |  _               => λ G, match G with end\n   end (I : shape (Consr u z))\n end eq_refl.\n\n(* -------------------------------------------------------------------------- *)\n\n(* A recursor for Type which does NOT pattern match over 𝔻lz l\n   in Type context but there is eq_rect in it !! *)\n\n(* Using up_llP and down_llT in order to constrain the use of eq_ind\n   and eq_rect, hence a clearer view of the underlying reasoning *)\nDefinition 𝔻lz_rect (P: list A → Type) :\n  P []  →  (∀ u, P u → ∀ z, P (u +: z)) →  ∀ l, 𝔻lz l → P l :=\n  fun Pnil Pconsr =>\n    fix fxp l (D : 𝔻lz l) {struct D} : P l :=\n    (match l2r l as r return (𝔻lz (r2l r) → (P (r2l r) → P l) → P l)\n     with\n     | Nilr      => fun D L => L Pnil\n     | Consr u z => fun D L => L (Pconsr u (fxp u (π_𝔻lz D)) z)\n     end (up_llP 𝔻lz l D)) (down_llT P l).\n\n\n(* Interactive version, on all lists *)\nDefinition list_zrect (P: list A → Type) :\n  P []  →  (∀ u, P u → ∀ z, P (u +: z))  →  ∀ l, P l.\nProof.\n  intros Pnil Pconsr.\n  intro l. generalize (𝔻lz_all l). revert l.\n  refine (fix fxp l D {struct D} : _ := _).\n  generalize (down_llT P l).\n  apply up_llP in D.\n  revert D.\n  destruct (l2r l) as [| u z]; simpl; intros D L; apply L.\n  - apply Pnil.\n  - apply Pconsr, fxp, (π_𝔻lz D).\nDefined.\n\nEnd sec_context.\n", "meta": {"author": "DmxLarchey", "repo": "The-Braga-Method", "sha": "e4f51add22a73681103454ad94a05aeeda332c50", "save_path": "github-repos/coq/DmxLarchey-The-Braga-Method", "path": "github-repos/coq/DmxLarchey-The-Braga-Method/The-Braga-Method-e4f51add22a73681103454ad94a05aeeda332c50/theories/listz/lr_rec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7172345292558686}}
{"text": "From mathcomp.ssreflect Require Import ssreflect ssrfun.\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* exists size *)\nNotation \"'eS'\" := (existT _ _).\n\n(**\n Finite Coinductive Trees (indexed by shape)\n*)\nSection CTree.\n  Context (A : Type).\n\n  Inductive shape : Type :=\n  | SL : shape\n  | SN : shape -> shape -> shape.\n\n  Inductive tree : Type :=\n  | L : tree\n  | N : A -> tree -> tree -> tree.\n\n  CoInductive vtree : shape -> Type :=\n  | CL : vtree SL\n  | CN l r : A -> vtree l -> vtree r -> vtree (SN l r).\n\n  Inductive Fin : shape -> Prop :=\n  | FL : Fin SL\n  | FN l r : Fin l -> Fin r -> Fin (SN l r).\n\n  Lemma all_fin : forall t, Fin t.\n  Proof. by elim=>[|x l r]; constructor. Defined.\n\n  Lemma inv_fin1 : forall n l r, Fin n -> n = SN l r -> Fin l.\n  Proof. by move=> n l r; case=>// l' r' H0 H1 [<-]. Defined.\n\n  Lemma inv_fin2 : forall n l r, Fin n -> n = SN l r -> Fin r.\n  Proof. by move=> n l r; case=>// l' r' H0 H1 [_ <-]. Defined.\n\n  Fixpoint vtree_to_tree' n (x : vtree n) (d : Fin n) {struct d} : tree :=\n    match x in vtree m return n = m -> tree with\n    | CL => fun _ => L\n    | CN dl dr v l r =>\n      fun pf =>\n        N v (vtree_to_tree' l (inv_fin1 d pf))\n            (vtree_to_tree' r (inv_fin2 d pf))\n    end erefl.\n\n  Definition vtree_to_tree n (x : vtree n) : tree :=\n    vtree_to_tree' x (all_fin n).\n\n  Fixpoint tshape (t : tree) : shape :=\n    match t with\n    | L => SL\n    | N _ l r => SN (tshape l) (tshape r)\n    end.\n\n  Fixpoint tree_to_vtree (t : tree) : vtree (tshape t) :=\n    match t return vtree (tshape t) with\n    | L => CL\n    | N h l r => CN h (tree_to_vtree l) (tree_to_vtree r)\n    end.\n\n  Definition ftree := {n & vtree n}.\n  Definition f_leaf : ftree := existT _ _ CL.\n  Definition f_node h l r := existT _ _ (CN h (projT2 l) (projT2 r)).\n\n  Lemma ftree_ind (P : ftree -> Prop) :\n    P f_leaf ->\n    (forall h l r, P l -> P r -> P (f_node h l r)) ->\n    forall t, P t.\n  Proof.\n    move=>P_leaf P_node [n v].\n    elim: n v=>//; first by case E:_ / =>//.\n    move=> l Ihl r Ihr; case E:_ / =>[| l' r' x' cl cr]//.\n    move: E cl Ihl cr Ihr =>[<-<-] cl /(_ cl)-Pcl cr /(_ cr)-Pcr.\n    rewrite -/(f_node _ (existT _ _ _) (existT _ _ _)).\n    by apply: P_node.\n  Qed.\n\n  Definition ftree_to_tree v := vtree_to_tree (projT2 v).\n  Definition tree_to_ftree v := existT _ _ (tree_to_vtree v).\n\n  Lemma ftree_iso1 l : ftree_to_tree (tree_to_ftree l) = l.\n  Proof.\n    rewrite /ftree_to_tree/tree_to_ftree/vtree_to_tree/=.\n    by elim: l=>//= x l -> r ->.\n  Qed.\n\n  Lemma ftree_iso2 l : tree_to_ftree (ftree_to_tree l) = l.\n  Proof.\n    elim/ftree_ind: l=>//= h l r.\n    rewrite /ftree_to_tree/tree_to_ftree/= => IHl IHr.\n    rewrite -/(f_node h (existT _ _ _) (existT _ _ _)).\n    by rewrite -!/(vtree_to_tree _) IHl IHr.\n  Qed.\nEnd CTree.\n", "meta": {"author": "dcastrop", "repo": "coq_ind_coind", "sha": "f4e8ca5a9237829a14c7bc5bf8b7528a9c2773d3", "save_path": "github-repos/coq/dcastrop-coq_ind_coind", "path": "github-repos/coq/dcastrop-coq_ind_coind/coq_ind_coind-f4e8ca5a9237829a14c7bc5bf8b7528a9c2773d3/theories/stree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7172178196653862}}
{"text": "Coq < Section Distribution.\n\nCoq < Variables P Q R : Prop.\nP is assumed\nQ is assumed\nR is assumed\n\nCoq < Goal (P /\\ Q) \\/ (P /\\ R) -> (P /\\ (Q \\/ R)).\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  ============================\n   P /\\ Q \\/ P /\\ R -> P /\\ (Q \\/ R)\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ Q \\/ P /\\ R\n  ============================\n   P /\\ (Q \\/ R)\n\nUnnamed_thm < destruct H.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ Q\n  ============================\n   P /\\ (Q \\/ R)\n\nsubgoal 2 is:\n P /\\ (Q \\/ R)\n\nUnnamed_thm < split.\n3 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ Q\n  ============================\n   P\n\nsubgoal 2 is:\n Q \\/ R\nsubgoal 3 is:\n P /\\ (Q \\/ R)\n\nUnnamed_thm < auto.\n3 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ Q\n  ============================\n   P\n\nsubgoal 2 is:\n Q \\/ R\nsubgoal 3 is:\n P /\\ (Q \\/ R)\n\nUnnamed_thm < tauto.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ Q\n  ============================\n   Q \\/ R\n\nsubgoal 2 is:\n P /\\ (Q \\/ R)\n\nUnnamed_thm < left.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ Q\n  ============================\n   Q\n\nsubgoal 2 is:\n P /\\ (Q \\/ R)\n\nUnnamed_thm < tauto.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ R\n  ============================\n   P /\\ (Q \\/ R)\n\nUnnamed_thm < split.\n2 subgoals\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ R\n  ============================\n   P\n\nsubgoal 2 is:\n Q \\/ R\n\nUnnamed_thm < tauto.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ R\n  ============================\n   Q \\/ R\n\nUnnamed_thm < right.\n1 subgoal\n  \n  P : Prop\n  Q : Prop\n  R : Prop\n  H : P /\\ R\n  ============================\n   R\n\nUnnamed_thm < tauto.\nProof completed.\n\nUnnamed_thm < Qed.\nintro.\ndestruct H.\n split.\n  auto.\n  tauto.\n  \n  left.\n  tauto.\n  \n split.\n  tauto.\n  \n  right.\n  tauto.\n  \nUnnamed_thm is defined\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/logic/chapt01/practice16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7172178105244079}}
{"text": "\n(* Let's look at the following example: *)\nExample ex1: forall A B: Prop, (A -> B) -> A -> B.\n(* We want to prove, that for all propositions A and B if A implies B and A holds then B also holds.\n   Now we step through the proof in Coq, which is a sequence of tactics, and comment every single line\n   with its logical sense. Look at list of hypotheses and a subgoals. *) \nProof. (* We start proof *)\n  intro. (* Let's take some proposition A. *)\n  intro. (* Let's take some proposition B. *)\n  intro. (* To prove proposition (P -> Q) we usually assume P as a hypothesis and then prove Q. \n             So here we'll get hypothesis H: A -> B and the goal will be A -> B.\n             In fact, here we can stop and apply this H to the goal, but we'll go further instead. *)\n  intro. (* New hypothesis H0: A, goal: B. *)\n  apply H. (* No we can apply hypothesis H, because it's conclusion is the same as our goal. \n              Applying H will also set its premise as a new goal. *)\n  exact H0. (* Now goal coincides with one of hypotheses, namely H0, that allows us to use 'exact' tactic. *)\n  (* No more goals, proof is completed, save it. *)\nQed.\n\n(* This kind of reasoning is called 'backward reasoning, because we move from goals to the implications \n   in hypothesis and then to their premices.\n\n   The same proof can be written shorter thanks to tactic 'intros':\n *)\nExample ex11: forall A B: Prop, (A -> B) -> A -> B.\nProof.\n  intros. (* Introduce all propositions and premises as hypotheses. *)\n  apply H.\n  assumption. (* Find one of assumptions which coincides with the goal and it. This is sometimes better\n               than using particular name of hypothesis in 'exact'. *)\nQed.\n\nExample ex12: forall A B: Prop, (A -> B) -> A -> B.\nProof.\n  auto. (* Well, yeah, that's not fair, I know. But try to resist using this tactic until told so. *)\nQed.\n\n\n(* Now we learn how to deal with disjunctions, conjunctions and negations, \n   how to prove them (in goals) and use them (in hypotheses). *)\n\nExample ex2: forall A B: Prop, A -> A \\/ B.\nProof.\n  intros.\n  left. (* To prove disjunction we have to specify which part in particular we want to prove. \n           Here we can prove left part. Beware, intuitionistic logic here! *)\n  assumption.\nQed.\n\nExample ex3: forall x y z: Prop, (x -> z) -> (y -> z) -> (x \\/ y -> z).\nProof.\n  intros. (* Look at hypotheses, the main question here is how to use disjunction in H1. \n             We have to 'destruct' it, that means exploring two cases: if x holds and if y holds.\n             If disjunction in H1 holds then one of its parts is necessarily holds, but we don't\n             know which one, so we do really have two cases. *)\n  destruct H1. (* H1 becomes 'x', so x holds and we apply implication H. *)\n    (* Note indentation here, this is way to mark visually proofs for subgoals arisen after 'destruct'. *)\n    apply H. assumption. (* The first case is solved and we move to the second one. *)\n    (* H1 becomes 'y', so y holds and we apply implication H0. *)\n    apply H0. assumption.\nQed.\n\nExample ex4: forall a b: Prop, a /\\ b -> a.\nProof.\n  intros.\n  destruct H. (* Here we destruct conjunction so evidently we get two hypotheses for the same\n                 goal, which are both parts of conjuction. *)\n  assumption.\nQed.\n\nExample ex5: forall a b: Prop, a -> b -> a /\\ b.\nProof.\n  intros. (* How to prove conjunction? Well, we have to prove both parts. *)\n  split. (* We use 'split' to literally split conjunction into two parts. So we get two\n            subgoals and have to prove them both independently. \n            Happily, the proof is straightforward, we just use assumptions in  both cases. *)\n  assumption.\n  assumption.\nQed.\n  \n(* If proofs for several cases are the same we can use 'tactical' ; (semicolon),\n   as in example below. *)\nExample ex51: forall a b: Prop, a -> b -> a /\\ b.\nProof.\n  intros.\n  split; assumption. (* Tactic 'assumption' is executed for both subgoals arisen after 'split'. *)\nQed.\n\n(* We use negation ~P in the following sense: if we assume P then we come to contradiction (we get False).\n   So we can read (and use whenever we like) ~P as implication P->False. *)\nExample ex6: forall A: Prop, A -> ~~A.\nProof.\n  intros. (* Now we have ~~A in goals, according to our interpretation that means (~A->False), so use\n             intro one more time. *)\n  intro.  (* We can clearly see contradiction in hypotheses. To prove it we apply H0 (~A === A->False)\n             and then provide exact assumption. *)\n  apply H0. \n  exact H. \n  (* The last two steps are not necessary, we can use 'contradiction' tactic instead. The 'contradiction' \n     tactic tries to find hypotheses like 'P' and '~P' and finishes the proof if succeeding. *)\nQed.\n\n\n(* Next example is one direction of De Morgan's Law (the other one can't be proved in intuitionistic logic\n  without additional assumptions). To prove it we use plenty of destructions. \n  Note also use of ';' tactical. *)\nExample ex7: forall A B , A \\/ B -> ~ (~ A /\\ ~ B ).\nProof.\n  intros.\n  intro.\n  destruct H; destruct H0; contradiction.\nQed.  (* By the way, try to use 'auto' here. Does it work? *)\n\n(* P is predicate in the following Lemma, it takes the value from set T and turns it into proposition. *)\nLemma ex8: forall (T: Set) ( P : T -> Prop ), (~ exists x , P x ) -> forall x , ~ P x .\nProof.\n  intros.\n  intro.\n  apply H.\n  exists x. (* We have to provide something to prove 'exists' in goal. Well, we have what we need \n               (namely, x: T) in the list of assumptions. *)\n  assumption.\nQed.\n\n(* The words Example, Lemma, Theorem or Fact are true synonyms. Use whatever you feel appropriate. *)", "meta": {"author": "ulysses4ever", "repo": "certif-sw-2014", "sha": "846fb4dc34af70a0ab1ca153311b8bfff2a13827", "save_path": "github-repos/coq/ulysses4ever-certif-sw-2014", "path": "github-repos/coq/ulysses4ever-certif-sw-2014/certif-sw-2014-846fb4dc34af70a0ab1ca153311b8bfff2a13827/class-01-examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.717195733292678}}
{"text": "Require Import Setoid.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Program.Equality.\nImport ListNotations.\n\nRequire Import Lib.LinearOrder.\nRequire Import Lib.EqDec.\n\n\n\nInductive Sorted {A: Type} `{LinearOrder A} : list A -> Prop :=\n  | SortedNil : Sorted []\n  | SortedSing : forall h: A, Sorted [h]\n  | SortedCons : forall h h' : A, forall t: list A,\n      Sorted (h' :: t) -> ord h h' = true -> Sorted (h :: h' :: t).\n\nFixpoint count {A: Type} (p: A -> bool) (l: list A): nat :=\n  match l with\n  | nil => O\n  | cons h t => if p h then S (count p t) else count p t\n  end.\n\nDefinition permutation {A: Type} (a b : list A) :=\n  forall p : A -> bool, count p a = count p b.\n\n\n(* Remove *)\nFixpoint remove {A: Type} `{EqDec A} (x: A) (l: list A) :=\nmatch l with \n| []     => []\n| (h::t) => if eqf x h then t else h :: remove x t\nend.\n\nLemma remove_count_true {A: Type} `{EqDec A} (h: A) (l: list A) (p: A -> bool) :\n  In h l -> p h = true -> count p l = S (count p (remove h l)).\nProof.\n  induction l; intros I t; cbn in *; destruct I.\n  - subst. rewrite t, eqf_refl. auto.\n  - destruct (p a) eqn:e; destruct (eqf h a) eqn:e1; [auto|..].\n    + cbn in *. rewrite e, IHl; auto.\n    + rewrite <- eqf_iff in e1. subst. rewrite t in e. discriminate.\n    + cbn in *. rewrite e, IHl; auto.\nQed.\n\nLemma remove_count_false {A: Type} `{EqDec A} (h: A) (l: list A) (p: A -> bool) :\n  p h = false -> count p l = count p (remove h l).\nProof.\n  induction l; intros f; auto. cbn in *. \n  destruct (p a) eqn:e; destruct (eqf h a) eqn:e1; [| |auto|].\n  - rewrite <- eqf_iff in e1. subst. rewrite f in e. discriminate.\n  - cbn. rewrite e. f_equal. apply IHl; auto.\n  - cbn. rewrite e, IHl; auto.\nQed.\n\nLemma in_count_not_O {A: Type} `{EqDec A} (l: list A) (x: A) :\n  In x l <-> count (eqf x) l <> O.\nProof.\n  split.\n  - intros I. induction l; cbn in *; destruct I.\n    + subst. rewrite eqf_refl. auto.\n    + destruct (eqf x a) eqn: e; auto.\n  - intros C. induction l; cbn in *; [contradiction|].\n    destruct (eqf x a) eqn: e; auto. rewrite <- eqf_iff in e.\n    subst. left. auto.\nQed.\n\nLemma perm_in {A: Type} `{EqDec A} (l l': list A) (x: A) :\n  permutation l l' -> In x l -> In x l'.\nProof.\n  intros perm I. rewrite in_count_not_O. rewrite in_count_not_O in I.\n  specialize (perm (eqf x)). rewrite <-perm. assumption.\nQed.\n\nLemma remove_perm {A: Type} `{EqDec A} (h: A) (l l': list A) :\n  permutation (h :: l) l' -> permutation l (remove h l').\nProof.\n  unfold permutation. revert l'. induction l; intros l' perm p.\n  - assert (In h l') by (apply (perm_in [h]); auto; cbn; auto).\n    cbn. apply eq_add_S. specialize (perm p). cbn in *. destruct (p h) eqn:e.\n    + rewrite <-remove_count_true; auto.\n    + rewrite <-remove_count_false; auto.\n  - assert (In h l') by (apply (perm_in (h::a::l)); cbn; auto).\n    assert (In a l') by (apply (perm_in (h::a::l)); cbn; auto).\n    cbn. apply eq_add_S. apply eq_add_S. specialize (perm p). cbn in *.\n    destruct (p h) eqn:e.\n    + rewrite <-remove_count_true; auto.\n    + rewrite <-remove_count_false; auto.\nQed.\n\nLemma remove_perm' {A: Type} `{EqDec A} (h: A) (l l': list A) :\n  In h l' -> permutation l (remove h l') -> permutation (h :: l) l' .\nProof.\n  unfold permutation. induction l; intros I perm p.\n  - cbn in *. specialize (perm p). destruct (p h) eqn: e.\n    + rewrite (remove_count_true h); auto.\n    + rewrite (remove_count_false h); auto.\n  - cbn in *. specialize (perm p). destruct (p h) eqn: e.\n    + rewrite (remove_count_true h l'); auto.\n    + rewrite (remove_count_false h l'); auto.\nQed.\n\n\n\n(* Sorted lemmas *)\nLemma count_list_concat {A: Type} (l l': list A): \n  forall p: A-> bool, count p (l ++ l') = count p l + count p l'.\nProof.\n  intros p. induction l; [auto|].\n  cbn. destruct (p a); rewrite IHl; auto.\nQed.\n\nLemma sorted_without_head {A: Type} `{LinearOrder A} : forall l: list A, forall a: A,\n  Sorted (a::l) -> Sorted l.\nProof.\n  intros l. induction l; intro h.\n  - intros _. constructor.\n  - intro s. dependent destruction s. assumption.\nQed.\n\nLemma sorted_with_head {A: Type} `{LinearOrder A} : forall l: list A, forall a h: A,\n  Sorted (h::l) -> ord a h = true -> Sorted (a::h::l).\nProof.\n  intros l a h sort o. constructor.\n  - trivial.\n  - assumption.\nQed.\n\nLemma head_in_sorted {A: Type} `{LinearOrder A} (h: A) (l: list A) : Sorted l -> \n  (forall x: A, In x l -> ord h x = true) -> Sorted (h::l).\nProof.\n  intros s N. induction l; constructor; [auto|]. apply N. cbn. auto.\nQed. \n\nLemma concat_sorted {A: Type} `{LinearOrder A} (h: A) (l l': list A) : Sorted l -> Sorted (h :: l') -> \n  (forall x: A, In x l -> ord x h = true) -> Sorted (l ++ (h :: l')).\nProof.\n  intros s1 s2 N. induction l; [auto | destruct l]; cbn.\n  + constructor; [auto | ]. apply (N a). cbn. auto.\n  + cbn in *. constructor.\n    * apply IHl.\n      -- apply (sorted_without_head _ a). assumption.\n      -- intros x I. apply N. auto.\n    * dependent destruction s1. assumption.\nQed. \n\nLemma sorted_head_relation {A: Type} `{L: LinearOrder A} :\n  forall l: list A, forall h: A, Sorted (h::l) -> forall x: A, In x (h :: l) ->\n  ord h x = true.\nProof.\n  intros l. induction l; intros h sort x H.\n  - cbn in H. destruct H.\n    + subst. apply refl.\n    + contradiction.\n  - cbn in H. destruct H.\n    + subst. apply refl.\n    + assert (ord a x = true).\n      { apply IHl.\n        - apply (sorted_without_head _ h). assumption.\n        - assumption.\n      }\n      dependent destruction sort; try discriminate.\n      apply (trans h a x); assumption.\nQed.\n\nTheorem perm_sym {A: Type} : forall l l': list A, permutation l l' <-> permutation l' l.\nProof.\n  intros l l'. unfold permutation. split; intros H p; symmetry; apply (H p).\nQed.\n\nTheorem perm_trans {A: Type} : forall x y z: list A, \n  permutation x y -> permutation y z -> permutation x z.\nProof.\n  intros x y z H H0. unfold permutation in *. intro p. specialize (H p). specialize (H0 p).\n  transitivity (count p y); assumption.\nQed.\n\nLemma perm_without_head {A: Type} : forall l l': list A, forall a: A,\n  permutation (cons a l) (cons a l') -> permutation l l'.\nProof.\n  - intros l l' a H. unfold permutation in *. intro p. specialize (H p). cbn in H.\n    destruct (p a).\n    + inversion H. reflexivity. \n    + assumption.\nQed.\n\nLemma perm_with_head {A: Type} : forall l l': list A, forall a: A,\n  permutation l l' -> permutation (a::l) (a::l').\nProof.\n  intros l l' a perm. unfold permutation in *. intro p. specialize (perm p).\n  cbn. destruct (p a).\n  - destruct perm. trivial.\n  - assumption.\nQed.\n\nTheorem perm_for_element {A: Type} : forall l l': list A, forall x: A,\n  permutation l l' -> In x l' -> In x l.\nProof.\n  unfold permutation. intros l. induction l; intros l' x perm H.\n  - destruct l'.\n    + cbn in H. destruct H.\n    + specialize (perm (fun x => true)). cbn in perm. discriminate.\n  - destruct l'.\n    + cbn in H. destruct H.\n    + cbn. cbn in H. destruct H.\n      * subst. left.\nAbort.\n\nLemma singleton_perm {A: Type} `{L: LinearOrder A} (x y: A) :\n   x = y <-> permutation [x] [y].\nProof.\n  split.\n  - intros [] p. auto.\n  - intros perm. specialize (perm (eqf x)). cbn [count] in *. rewrite eqf_refl in perm.\n    destruct (eqf x y) eqn:e.\n    + rewrite <- eqf_iff in e; auto.\n    + inversion perm.\nQed.\n\nLemma week_eqf_in {A: Type} `{L: EqDec A} :\n  forall x: A, forall l: list A, In x l <-> count (eqf x) l <> O.\nProof.\n  intros x l. split.\n  - intros H. induction l.\n    + cbn in H. contradiction.\n    + cbn. destruct (eqf x a) eqn:eq.\n      * apply PeanoNat.Nat.neq_succ_0.\n      * apply IHl. destruct H; auto. subst. rewrite eqf_refl in eq.\n        inversion eq.\n  - intro H. induction l.\n    + cbn in H. contradiction.\n    + cbn. destruct (eqf x a) eqn:eq.\n      * left. apply eqf_iff. rewrite eqf_sym. assumption.\n      * right. apply IHl. cbn in H. rewrite eq in H. assumption.\nQed.\n\nTheorem weak_perm_in {A: Type} `{L: EqDec A} : forall l l': list A, forall x: A,  \n  permutation l l' -> In x l' -> In x l.\nProof.\n  unfold permutation. intros l l' x perm H. specialize (perm (eqf x)). cut (count (eqf x) l' <> O).\n  - intro H0. rewrite <- perm in H0. rewrite week_eqf_in. assumption.\n  - apply week_eqf_in. assumption.\nQed.\n\nLemma sorted_head_eq {A: Type} `{L: LinearOrder A} : forall l l': list A, forall a a': A, \n  permutation (a :: l) (a' :: l') -> Sorted (a :: l) -> Sorted (a' :: l') -> a = a'.\nProof.\n  intros l l' h h' perm s1 s2.\n  destruct (full h h').\n  - assert (In h (h'::l')).\n    + apply (weak_perm_in (h'::l') (h :: l) h); try apply perm_sym; auto.\n      cbn. left. reflexivity.\n    + assert (ord h' h = true) by (apply (sorted_head_relation l' h'); auto).\n      apply anti_sym; auto.\n  - assert (In h' (h::l)).\n    + apply (weak_perm_in (h::l) (h' :: l') h'); auto.\n      cbn. left. reflexivity.\n    + assert (ord h h' = true) by (apply (sorted_head_relation l h); auto).\n      apply anti_sym; auto.\nQed.\n\n(* Unique *)\n\nTheorem sorted_unique_representation {A: Type} `{L: LinearOrder A} :\n  forall l l': list A, permutation l l' -> Sorted l -> Sorted l' -> l = l'.\nProof.\n  intros l. induction l; intros l' perm sort sort'.\n  - destruct l'; auto. specialize (perm (fun _ => true)). cbn in perm. discriminate.\n  - destruct l'.\n    + specialize (perm (fun _ => true)). cbn in perm. discriminate.\n    + assert (a = a0) by (apply (sorted_head_eq l l'); auto). subst.\n      f_equal. apply IHl.\n      * apply (perm_without_head _ _ a0); auto.\n      * apply (sorted_without_head _ a0). auto.\n      * apply (sorted_without_head _ a0). auto.\nQed.", "meta": {"author": "speederking07", "repo": "magisterka", "sha": "602d1e328ac4a396c282e241744d129573a65381", "save_path": "github-repos/coq/speederking07-magisterka", "path": "github-repos/coq/speederking07-magisterka/magisterka-602d1e328ac4a396c282e241744d129573a65381/Master/Lib/Sorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289535, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7170595335043832}}
{"text": "Require Import Lia.\n\nFixpoint log2up (n : nat) : nat :=\n  match n with\n  | O => 0\n  | S O => 0\n  | S (S n') => 1 + (log2up n')\n  end.\nCompute log2up 6. (* 3 *)\nCompute log2up 7. (* 3 *)\nCompute log2up 8. (* 4 *)\n\n(* Search (nat -> nat -> bool). *)\nCompute (Nat.leb 3 2).\n\n(* After the fashion of\n   https://coq.inria.fr/library/Coq.Numbers.NatInt.NZLog.html *)\nLemma log2up_nonneg : forall (n : nat), 0 <= (log2up n). \nProof.\n  lia.\nQed.\n\nCompute (Nat.pow 2 3).\n\nLemma log2_lemma : forall (n : nat), n <= (Nat.pow 2 (log2up n)).\n(*\nProof.\n  intros.\n  induction n.\n  - lia.\n  - simpl.\nQed.\n *)\n", "meta": {"author": "ju-sh", "repo": "fun", "sha": "8cf20e8557f0534cb37ec3ac94e06f411dd3e308", "save_path": "github-repos/coq/ju-sh-fun", "path": "github-repos/coq/ju-sh-fun/fun-8cf20e8557f0534cb37ec3ac94e06f411dd3e308/coq/log2up.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.7170046304528245}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := mult y x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj276_coqofml_NOW9X1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7170046211645132}}
{"text": "Require Import Frap.\n\n\n(** * Syntax and semantics of a simple imperative language *)\n\nInductive exp :=\n| Const (n : nat)\n| Var (x : string)\n| Read (e1 : exp)\n| Plus (e1 e2 : exp)\n| Minus (e1 e2 : exp)\n| Mult (e1 e2 : exp).\n\nInductive bexp :=\n| Equal (e1 e2 : exp)\n| Less (e1 e2 : exp).\n\nDefinition heap := fmap nat nat.\nDefinition valuation := fmap var nat.\nDefinition assertion := heap -> valuation -> Prop.\n\nInductive cmd :=\n| Skip\n| Assign (x : var) (e : exp)\n| Write (e1 e2 : exp)\n| Seq (c1 c2 : cmd)\n| If_ (be : bexp) (then_ else_ : cmd)\n| While_ (inv : assertion) (be : bexp) (body : cmd)\n\n| Assert (a : assertion).\n\n(* Shorthand notation for looking up in a finite map, returning zero if the key\n * is not found *)\nNotation \"m $! k\" := (match m $? k with Some n => n | None => O end) (at level 30).\n\n(* Start of expression semantics: meaning of expressions *)\nFixpoint eval (e : exp) (h : heap) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x => v $! x\n  | Read e1 => h $! eval e1 h v\n  | Plus e1 e2 => eval e1 h v + eval e2 h v\n  | Minus e1 e2 => eval e1 h v - eval e2 h v\n  | Mult e1 e2 => eval e1 h v * eval e2 h v\n  end.\n\n(* Meaning of Boolean expressions *)\nFixpoint beval (b : bexp) (h : heap) (v : valuation) : bool :=\n  match b with\n  | Equal e1 e2 => if eval e1 h v ==n eval e2 h v then true else false\n  | Less e1 e2 => if eval e2 h v <=? eval e1 h v then false else true\n  end.\n\n(* A big-step operational semantics for commands *)\nInductive exec : heap -> valuation -> cmd -> heap -> valuation -> Prop :=\n| ExSkip : forall h v,\n  exec h v Skip h v\n| ExAssign : forall h v x e,\n  exec h v (Assign x e) h (v $+ (x, eval e h v))\n| ExWrite : forall h v e1 e2,\n  exec h v (Write e1 e2) (h $+ (eval e1 h v, eval e2 h v)) v\n| ExSeq : forall h1 v1 c1 h2 v2 c2 h3 v3,\n  exec h1 v1 c1 h2 v2\n  -> exec h2 v2 c2 h3 v3\n  -> exec h1 v1 (Seq c1 c2) h3 v3\n| ExIfTrue : forall h1 v1 b c1 c2 h2 v2,\n  beval b h1 v1 = true\n  -> exec h1 v1 c1 h2 v2\n  -> exec h1 v1 (If_ b c1 c2) h2 v2\n| ExIfFalse : forall h1 v1 b c1 c2 h2 v2,\n  beval b h1 v1 = false\n  -> exec h1 v1 c2 h2 v2\n  -> exec h1 v1 (If_ b c1 c2) h2 v2\n| ExWhileFalse : forall I h v b c,\n  beval b h v = false\n  -> exec h v (While_ I b c) h v\n| ExWhileTrue : forall I h1 v1 b c h2 v2 h3 v3,\n  beval b h1 v1 = true\n  -> exec h1 v1 c h2 v2\n  -> exec h2 v2 (While_ I b c) h3 v3\n  -> exec h1 v1 (While_ I b c) h3 v3\n\n(* Assertions execute only when they are true.  They provide a way to embed\n * proof obligations within programs. *)\n| ExAssert : forall h v (a : assertion),\n  a h v\n  -> exec h v (Assert a) h v.\n\n\n(** * Hoare logic *)\n\nInductive hoare_triple : assertion -> cmd -> assertion -> Prop :=\n| HtSkip : forall P, hoare_triple P Skip P\n| HtAssign : forall (P : assertion) x e,\n  hoare_triple P (Assign x e) (fun h v => exists v', P h v' /\\ v = v' $+ (x, eval e h v'))\n| HtWrite : forall (P : assertion) (e1 e2 : exp),\n  hoare_triple P (Write e1 e2) (fun h v => exists h', P h' v /\\ h = h' $+ (eval e1 h' v, eval e2 h' v))\n| HtSeq : forall (P Q R : assertion) c1 c2,\n  hoare_triple P c1 Q\n  -> hoare_triple Q c2 R\n  -> hoare_triple P (Seq c1 c2) R\n| HtIf : forall (P Q1 Q2 : assertion) b c1 c2,\n  hoare_triple (fun h v => P h v /\\ beval b h v = true) c1 Q1\n  -> hoare_triple (fun h v => P h v /\\ beval b h v = false) c2 Q2\n  -> hoare_triple P (If_ b c1 c2) (fun h v => Q1 h v \\/ Q2 h v)\n| HtWhile : forall (I P : assertion) b c,\n  (forall h v, P h v -> I h v)\n  -> hoare_triple (fun h v => I h v /\\ beval b h v = true) c I\n  -> hoare_triple P (While_ I b c) (fun h v => I h v /\\ beval b h v = false)\n| HtAssert : forall P I : assertion,\n  (forall h v, P h v -> I h v)\n  -> hoare_triple P (Assert I) P\n| HtConsequence : forall (P Q P' Q' : assertion) c,\n  hoare_triple P c Q\n  -> (forall h v, P' h v -> P h v)\n  -> (forall h v, Q h v -> Q' h v)\n  -> hoare_triple P' c Q'.\n\nLemma hoare_triple_big_step_while: forall (I : assertion) b c,\n  (forall h v h' v', exec h v c h' v'\n                     -> I h v\n                     -> beval b h v = true\n                     -> I h' v')\n  -> forall h v h' v', exec h v (While_ I b c) h' v'\n                       -> I h v\n                       -> I h' v' /\\ beval b h' v' = false.\nProof.\n  induct 2; eauto.\nQed.\n\nTheorem hoare_triple_big_step : forall pre c post,\n    hoare_triple pre c post\n    -> forall h v h' v', exec h v c h' v'\n                         -> pre h v\n                         -> post h' v'.\nProof.\n  induct 1; eauto; invert 1; eauto.\n\n  simplify.\n  eapply hoare_triple_big_step_while; eauto.\nQed.\n\n\n(* BEGIN syntax macros that won't be explained *)\nCoercion Const : nat >-> exp.\nCoercion Var : string >-> exp.\nNotation \"*[ e ]\" := (Read e) : cmd_scope.\nInfix \"+\" := Plus : cmd_scope.\nInfix \"-\" := Minus : cmd_scope.\nInfix \"*\" := Mult : cmd_scope.\nInfix \"=\" := Equal : cmd_scope.\nInfix \"<\" := Less : cmd_scope.\nDefinition set (dst src : exp) : cmd :=\n  match dst with\n  | Read dst' => Write dst' src\n  | Var dst' => Assign dst' src\n  | _ => Assign \"Bad LHS\" 0\n  end.\nInfix \"<-\" := set (no associativity, at level 70) : cmd_scope.\nInfix \";;\" := Seq (right associativity, at level 75) : cmd_scope.\nNotation \"'when' b 'then' then_ 'else' else_ 'done'\" := (If_ b then_ else_) (at level 75, b at level 0).\nNotation \"{{ I }} 'while' b 'loop' body 'done'\" := (While_ I b body) (at level 75).\nNotation \"'assert' {{ I }}\" := (Assert I) (at level 75).\nDelimit Scope cmd_scope with cmd.\n(* END macros *)\n\n(* We should draw some attention to the next notation, which defines special\n * lambdas for writing assertions. *)\nNotation \"h & v ~> e\" := (fun h v => e%nat%type) (at level 85, v at level 0).\n\n(* And here's the classic notation for Hoare triples. *)\nNotation \"{{ P }} c {{ Q }}\" := (hoare_triple P c%cmd Q) (at level 90, c at next level).\n\n(* Special case of consequence: keeping the precondition; only changing the\n * postcondition. *)\nLemma HtStrengthenPost : forall (P Q Q' : assertion) c,\n  hoare_triple P c Q\n  -> (forall h v, Q h v -> Q' h v)\n  -> hoare_triple P c Q'.\nProof.\n  simplify; eapply HtConsequence; eauto.\nQed.\n\n(* Finally, three tactic definitions that we won't explain.  The overall tactic\n * [ht] tries to prove Hoare triples, essentially by rote application of the\n * rules.  Some other obligations are generated, generally of implications\n * between assertions, and [ht] also makes a best effort to solve those. *)\n\nLtac ht1 :=\n  match goal with\n  | [  |- {{ _ }} _ {{ ?P }} ] =>\n    tryif is_evar P then\n      apply HtSkip || apply HtAssign || apply HtWrite || eapply HtSeq\n      || eapply HtIf || eapply HtWhile || eapply HtAssert\n    else\n      eapply HtStrengthenPost\n  end.\n\nLtac t := cbv beta; propositional; subst;\n          repeat match goal with\n                 | [ H : ex _ |- _ ] => invert H; propositional; subst\n                 end;\n          simplify;\n          repeat match goal with\n                 | [ _ : context[?a <=? ?b] |- _ ] => destruct (a <=? b); try discriminate\n                 | [ H : ?E = ?E |- _ ] => clear H\n                 end; simplify; propositional; auto; try equality; try linear_arithmetic.\n\nLtac ht := simplify; repeat ht1; t.\n\n\n(** * Some examples of verified programs *)\n\n(** ** Swapping the values in two variables *)\n\nTheorem swap_ok : forall a b,\n  {{_&v ~> v $! \"x\" = a /\\ v $! \"y\" = b}}\n    \"tmp\" <- \"x\";;\n    \"x\" <- \"y\";;\n    \"y\" <- \"tmp\"\n  {{_&v ~> v $! \"x\" = b /\\ v $! \"y\" = a}}.\nProof.\nAdmitted.\n\n(** ** Computing the maximum of two variables *)\n\nTheorem max_ok : forall a b,\n  {{_&v ~> v $! \"x\" = a /\\ v $! \"y\" = b}}\n    when \"x\" < \"y\" then\n      \"m\" <- \"y\"\n    else\n      \"m\" <- \"x\"\n    done\n  {{_&v ~> v $! \"m\" = max a b}}.\nProof.\nAdmitted.\n\n(** ** Iterative factorial *)\n\nTheorem fact_ok : forall n,\n  {{_&v ~> v $! \"n\" = n}}\n    \"acc\" <- 1;;\n    {{_&v ~> True}}\n    while 0 < \"n\" loop\n      \"acc\" <- \"acc\" * \"n\";;\n      \"n\" <- \"n\" - 1\n    done\n  {{_&v ~> v $! \"acc\" = fact n}}.\nProof.\nAdmitted.\n\n(** ** Selection sort *)\n\n(* This is our one example of a program reading/writing memory, which holds the\n * representation of an array that we want to sort in-place. *)\n\n(* One simple lemma turns out to be helpful to guide [eauto] properly. *)\nLemma leq_f : forall A (m : fmap A nat) x y,\n  x = y\n  -> m $! x <= m $! y.\nProof.\n  ht.\nQed.\n\nLocal Hint Resolve leq_f : core.\nLocal Hint Extern 1 (@eq nat _ _) => linear_arithmetic : core.\nLocal Hint Extern 1 (_ < _) => linear_arithmetic : core.\nLocal Hint Extern 1 (_ <= _) => linear_arithmetic : core.\n(* We also register [linear_arithmetic] as a step to try during proof search. *)\n\nTheorem selectionSort_ok :\n  {{_&_ ~> True}}\n    \"i\" <- 0;;\n    {{h&v ~> True}}\n    while \"i\" < \"n\" loop\n      \"j\" <- \"i\"+1;;\n      \"best\" <- \"i\";;\n      {{h&v ~> True}}\n      while \"j\" < \"n\" loop\n        when *[\"a\" + \"j\"] < *[\"a\" + \"best\"] then\n          \"best\" <- \"j\"\n        else\n          Skip\n        done;;\n        \"j\" <- \"j\" + 1\n      done;;\n      \"tmp\" <- *[\"a\" + \"best\"];;\n      *[\"a\" + \"best\"] <- *[\"a\" + \"i\"];;\n      *[\"a\" + \"i\"] <- \"tmp\";;\n      \"i\" <- \"i\" + 1\n    done\n  {{h&v ~> forall i j, i < j < v $! \"n\" -> h $! (v $! \"a\" + i) <= h $! (v $! \"a\" + j)}}.\nProof.\nAdmitted.\n\n\n(** * An alternative correctness theorem for Hoare logic, with small-step semantics *)\n\nInductive step : heap * valuation * cmd -> heap * valuation * cmd -> Prop :=\n| StAssign : forall h v x e,\n  step (h, v, Assign x e) (h, v $+ (x, eval e h v), Skip)\n| StWrite : forall h v e1 e2,\n  step (h, v, Write e1 e2) (h $+ (eval e1 h v, eval e2 h v), v, Skip)\n| StStepSkip : forall h v c,\n  step (h, v, Seq Skip c) (h, v, c)\n| StStepRec : forall h1 v1 c1 h2 v2 c1' c2,\n  step (h1, v1, c1) (h2, v2, c1')\n  -> step (h1, v1, Seq c1 c2) (h2, v2, Seq c1' c2)\n| StIfTrue : forall h v b c1 c2,\n  beval b h v = true\n  -> step (h, v, If_ b c1 c2) (h, v, c1)\n| StIfFalse : forall h v b c1 c2,\n  beval b h v = false\n  -> step (h, v, If_ b c1 c2) (h, v, c2)\n| StWhileFalse : forall I h v b c,\n  beval b h v = false\n  -> step (h, v, While_ I b c) (h, v, Skip)\n| StWhileTrue : forall I h v b c,\n  beval b h v = true\n  -> step (h, v, While_ I b c) (h, v, Seq c (While_ I b c))\n| StAssert : forall h v (a : assertion),\n  a h v\n  -> step (h, v, Assert a) (h, v, Skip).\n\nLocal Hint Constructors step : core.\n\nDefinition trsys_of (st : heap * valuation * cmd) := {|\n  Initial := {st};\n  Step := step\n|}.\n\nDefinition unstuck (st : heap * valuation * cmd) :=\n  snd st = Skip\n  \\/ exists st', step st st'.\n\nLemma hoare_triple_unstuck : forall P c Q,\n  {{P}} c {{Q}}\n  -> forall h v, P h v\n                 -> unstuck (h, v, c).\nProof.\n  induct 1; unfold unstuck; simplify; propositional; eauto.\n\n  apply IHhoare_triple1 in H1.\n  unfold unstuck in H1; simplify; first_order; subst; eauto.\n  cases x.\n  cases p.\n  eauto.\n\n  cases (beval b h v); eauto.\n\n  cases (beval b h v); eauto.\n\n  apply H0 in H2.\n  apply IHhoare_triple in H2.\n  unfold unstuck in H2; simplify; first_order.\nQed.\n\nLemma hoare_triple_Skip : forall P Q,\n  {{P}} Skip {{Q}}\n  -> forall h v, P h v -> Q h v.\nProof.\n  induct 1; auto.\nQed.\n\nLemma hoare_triple_step : forall P c Q,\n  {{P}} c {{Q}}\n  -> forall h v h' v' c',\n      step (h, v, c) (h', v', c')\n      -> P h v\n      -> {{h''&v'' ~> h'' = h' /\\ v'' = v'}} c' {{Q}}.\nProof.\n  induct 1.\n\n  invert 1.\n\n  invert 1; ht; eauto.\n\n  invert 1; ht; eauto.\n\n  invert 1; simplify.\n\n  eapply HtConsequence; eauto.\n  propositional; subst.\n  eapply hoare_triple_Skip; eauto.\n\n  econstructor; eauto.\n\n  invert 1; simplify.\n  eapply HtConsequence; eauto; equality.\n  eapply HtConsequence; eauto; equality.\n\n  invert 1; simplify.\n  eapply HtConsequence with (P := h'' & v'' ~> h'' = h' /\\ v'' = v').\n  apply HtSkip.\n  auto.\n  simplify; propositional; subst; eauto.\n\n  econstructor.\n  eapply HtConsequence; eauto.\n  simplify; propositional; subst; eauto.\n  econstructor; eauto.\n\n  invert 1; simplify.\n  eapply HtConsequence; eauto.\n  econstructor.\n  simplify; propositional; subst; eauto.\n\n  simplify.\n  eapply HtConsequence.\n  eapply IHhoare_triple; eauto.\n  simplify; propositional; subst; eauto.\n  auto.\nQed.\n\nTheorem hoare_triple_invariant : forall P c Q h v,\n  {{P}} c {{Q}}\n  -> P h v\n  -> invariantFor (trsys_of (h, v, c)) unstuck.\nProof.\n  simplify.\n  apply invariant_weaken with (invariant1 := fun st => {{h&v ~> h = fst (fst st)\n                                                           /\\ v = snd (fst st)}}\n                                                         snd st\n                                                       {{_&_ ~> True}}).\n\n  apply invariant_induction; simplify.\n\n  propositional; subst; simplify.\n  eapply HtConsequence; eauto.\n  equality.\n\n  cases s.\n  cases s'.\n  cases p.\n  cases p0.\n  simplify.\n  eapply hoare_triple_step; eauto.\n  simplify; auto.\n\n  simplify.\n  cases s.\n  cases p.\n  simplify.\n  eapply hoare_triple_unstuck; eauto.\n  simplify; auto.\nQed.\n\n(* A very simple example, just to show all this in action *)\nDefinition forever := (\n  \"i\" <- 1;;\n  \"n\" <- 1;;\n  {{h&v ~> v $! \"i\" > 0}}\n  while 0 < \"i\" loop\n    \"i\" <- \"i\" * 2;;\n    \"n\" <- \"n\" + \"i\";;\n    assert {{h&v ~> v $! \"n\" >= 1}}\n  done;;\n\n  assert {{_&_ ~> False}}\n  (* Note that this last assertion implies that the program never terminates! *)\n)%cmd.\n\nTheorem forever_ok : {{_&_ ~> True}} forever {{_&_ ~> False}}.\nProof.\n  ht.\nQed.\n\nTheorem forever_invariant : invariantFor (trsys_of ($0, $0, forever)) unstuck.\nProof.\n  eapply hoare_triple_invariant.\n  apply forever_ok.\n  simplify; trivial.\nQed.\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/HoareLogic_template.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7169441277631323}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) (lf1 : natural) : natural :=\n  plus lf3 lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj22_coqofml_zL19WU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7169441090758493}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\n\nSection Exponentiation.\n\n(* Why3 goal *)\nVariable t : Type.\nHypothesis t_WhyType : WhyType t.\nExisting Instance t_WhyType.\n\n(* Why3 goal *)\nVariable one: t.\n\n(* Why3 goal *)\nVariable infix_as: t -> t -> t.\n\n(* Why3 goal *)\nHypothesis Assoc : forall (x:t) (y:t) (z:t), ((infix_as (infix_as x y)\n  z) = (infix_as x (infix_as y z))).\n\n(* Why3 goal *)\nHypothesis Unit_def_l : forall (x:t), ((infix_as one x) = x).\n\n(* Why3 goal *)\nHypothesis Unit_def_r : forall (x:t), ((infix_as x one) = x).\n\n(* Why3 goal *)\nHypothesis Comm : forall (x:t) (y:t), ((infix_as x y) = (infix_as y x)).\n\n(* Why3 goal *)\nDefinition power: t -> Z -> t.\nintros x n.\nexact (iter_nat (Zabs_nat n) t (fun acc => infix_as x acc) one).\nDefined.\n\n(* Why3 goal *)\nLemma Power_0 : forall (x:t), ((power x 0%Z) = one).\nProof.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Power_s : forall (x:t) (n:Z), (0%Z <= n)%Z -> ((power x\n  (n + 1%Z)%Z) = (infix_as x (power x n))).\nProof.\nintros x n h1.\nunfold power.\nfold (Zsucc n).\nnow rewrite Zabs_nat_Zsucc.\nQed.\n\n(* Why3 goal *)\nLemma Power_s_alt : forall (x:t) (n:Z), (0%Z < n)%Z -> ((power x\n  n) = (infix_as x (power x (n - 1%Z)%Z))).\nintros x n h1.\nrewrite <- Power_s; auto with zarith.\nf_equal; omega.\nQed.\n\n(* Why3 goal *)\nLemma Power_1 : forall (x:t), ((power x 1%Z) = x).\nProof.\nexact Unit_def_r.\nQed.\n\n(* Why3 goal *)\nLemma Power_sum : forall (x:t) (n:Z) (m:Z), (0%Z <= n)%Z -> ((0%Z <= m)%Z ->\n  ((power x (n + m)%Z) = (infix_as (power x n) (power x m)))).\nProof.\nintros x n m Hn Hm.\nrevert n Hn.\napply natlike_ind.\napply sym_eq, Unit_def_l.\nintros n Hn IHn.\nreplace (Zsucc n + m)%Z with ((n + m) + 1)%Z by ring.\nrewrite Power_s by auto with zarith.\nrewrite IHn.\nnow rewrite <- Assoc, <- Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult : forall (x:t) (n:Z) (m:Z), (0%Z <= n)%Z -> ((0%Z <= m)%Z ->\n  ((power x (n * m)%Z) = (power (power x n) m))).\nProof.\nintros x n m Hn Hm.\nrevert m Hm.\napply natlike_ind.\nnow rewrite Zmult_0_r, 2!Power_0.\nintros m Hm IHm.\nreplace (n * Zsucc m)%Z with (n * m + n)%Z by ring.\nrewrite Power_sum by auto with zarith.\nrewrite IHm.\nnow rewrite Comm, <- Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult2 : forall (x:t) (y:t) (n:Z), (0%Z <= n)%Z ->\n  ((power (infix_as x y) n) = (infix_as (power x n) (power y n))).\nProof.\nintros x y.\napply natlike_ind.\napply sym_eq.\nrewrite 3!Power_0.\napply Unit_def_r.\nintros n Hn IHn.\nunfold Zsucc.\nrewrite 3!(Power_s _ _ Hn).\nrewrite IHn.\nnow rewrite Assoc, <- (Assoc y), (Comm y), 2!Assoc.\nQed.\n\nEnd Exponentiation.\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/int/Exponentiation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7169209500474215}}
{"text": "Require Import Lists.List.\n\nFixpoint sum (xs : list nat) : nat :=\nmatch xs with\n|nil => 0\n| x ::  xs => x + sum xs\nend.\n\nTheorem Pigeon_Hole_Principle:\nforall (xs : list nat), length xs < sum xs -> (exists x, 1 < x /\\ In x xs).\nProof.\nintros.\ninduction xs.\ncontradict H.\nsimpl.\napply Lt.lt_irrefl.\n\nRequire Import Omega.\nassert (a = 0 \\/ a = 1 \\/ a > 1).\nomega.\ndestruct H0.\ndestruct IHxs.\nreplace (sum xs) with (sum (a :: xs)).\napply (Lt.le_lt_trans (length xs) (length (a :: xs)) (sum (a::xs))).\nsimpl.\napply (Le.le_n_Sn (length xs)).\napply H.\nsimpl.\nreplace a with 0.\nreflexivity.\nexists x.\nsplit.\napply H1.\nsimpl.\nright.\napply H1.\ndestruct H0.\ndestruct IHxs.\napply (plus_lt_reg_l (length xs) (sum xs) a).\napply (NPeano.Nat.lt_stepl (length (a :: xs)) (sum (a :: xs)) (a + length xs)).\napply H.\nsimpl.\nreplace a with 1.\nreflexivity.\nexists x.\nsplit.\napply H1.\nsimpl.\nright.\napply H1.\nexists a.\nsplit.\napply H0.\nsimpl.\nleft.\nreflexivity.\nQed.\n\n\n\n", "meta": {"author": "ashiato45", "repo": "CoqEx2014", "sha": "83750632bf6a78db93ed493a739b4aeae8505df1", "save_path": "github-repos/coq/ashiato45-CoqEx2014", "path": "github-repos/coq/ashiato45-CoqEx2014/CoqEx2014-83750632bf6a78db93ed493a739b4aeae8505df1/3/12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818987, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7169209466657374}}
{"text": "Require Import List.\n\nInductive last {A:Type} : A -> list A -> Prop :=\n  | last1 : forall a:A, last a (cons a nil)\n  | last2 : forall (a x:A)(l:list A), last a l -> last a (cons x l).\n\nFixpoint last_fun {A:Type} (l:list A) : option A :=\n  match l with\n    | nil           => None\n    | (cons a nil)  => Some a\n    | (cons a l')   => last_fun l'\n  end.\n\n\nLemma last_a_l_not_nil : forall (A:Type)(a:A)(l:list A),\n  last a l -> l <> nil.\nProof.\n  intros A a l p. generalize p. elim p. intros b H. clear H.\n  intro H. apply nil_cons with (x:=b)(l:=nil). auto.\n  intros b x l' q H0 H1. clear H0 H1 q b p l a. intro H.\n  apply nil_cons with (x:=x)(l:=l'). auto.\nQed.\n\nLemma not_last_a_nil: forall (A:Type)(a:A),\n  ~last a nil.\nProof.\n  intros A a H. apply last_a_l_not_nil with (l:=nil)(a:=a).\n  exact H. reflexivity.\nQed.\n\nLemma last_coherence : forall (A:Type)(l:list A)(a:A),\n  last a l <-> last_fun l = Some a.\nProof.\n  (* -> *)\n  intros A l a. split. intro p. generalize p. elim p.\n  intros b H0. clear H0. simpl. reflexivity.\n  intros b x m. case m. intro H. apply False_ind.\n  apply not_last_a_nil with (a:=b). exact H.\n  intros c l' H H' H''. simpl. apply H'. exact H.\n  (* <- *)\n  elim l. simpl. intro H. discriminate H.\n  clear l. intros b l. case l. simpl. intros H H'.\n  cut(a = b). intro H''. rewrite <- H''. apply last1.\n  pose (g:= fun x =>  match x with | None    => a | Some c  => c end).\n  change (g (Some a) = g (Some b)). rewrite H'. reflexivity.\n  clear l. intros c l H H'. apply last2. apply H. rewrite <- H'.\n  simpl. reflexivity.\nQed.\n\n(* last_with_rest a l l' expresses the fact that l = l' ++ [a] \n** i.e. that a is the last element of l, and l' is what remains of\n** the list after removing the last element 'a'                    *)\nInductive last_with_rest {A:Type} : A -> list A -> list A -> Prop := \n  | last_with_rest1 : forall a:A, last_with_rest a (cons a nil) nil \n  | last_with_rest2 : forall (a b:A)(l m:list A), \n      last_with_rest a l m -> last_with_rest a (cons b l) (cons b m).\n\nInductive palindrome {A:Type} : list A -> Prop :=\n  | palindrome_nil    : palindrome nil\n  | palindrome_single : forall (a:A), palindrome (cons a nil)\n  | palindrome_a      : forall (a:A)(l m:list A), \n      last_with_rest a l m -> palindrome m -> palindrome (cons a l). \n\nDefinition pal_example1 := 1::2::3::4::5::4::3::2::1::nil.\nDefinition pal_example2 := 1::2::2::1::nil.\nDefinition pal_example3 := 1::2::nil. (* not a palindrome *)\n\nLemma palindrome_example2: palindrome pal_example2.\nProof.\n  unfold pal_example2. apply palindrome_a with (a:=1)(m:= 2::2::nil).\n  repeat apply last_with_rest2. apply last_with_rest1.\n  apply palindrome_a with (m:=nil). apply last_with_rest1. apply palindrome_nil.\nQed.\n\nLemma palindrome_example1: palindrome pal_example1.\nProof.\n  unfold pal_example1.\n  apply palindrome_a with (m:= 2::3::4::5::4::3::2::nil). \n  repeat apply last_with_rest2. apply last_with_rest1.\n  apply palindrome_a with (m:= 3::4::5::4::3::nil). \n  repeat apply last_with_rest2. apply last_with_rest1.\n  apply palindrome_a with (m:= 4::5::4::nil). \n  repeat apply last_with_rest2. apply last_with_rest1.\n  apply palindrome_a with (m:= 5::nil). \n  repeat apply last_with_rest2. apply last_with_rest1.\n  apply palindrome_single.\nQed.\n\n\nLemma last_with_rest_last: forall (A:Type)(a:A)(l m:list A),\n  last_with_rest a l m -> last a l.\nProof.\n  intros A a l m H. generalize H. elim H. clear H a m l.  \n  intros a H. apply last1. clear H m l a. intros a b l m.\n  intros H0 H1 H2. apply last2, H1, H0.\nQed.\n\nLemma last_single: forall (A:Type)(a b:A),\n  last a (b::nil) -> a = b.\nProof.\n  intros A a b H. rewrite last_coherence in H. simpl in H.\n  pose (g:= fun opt => match opt with | None => a | Some x => x end).\n  fold (g (Some b)). rewrite H. simpl. reflexivity.\nQed.\n\nLemma last_unique: forall (A:Type)(a b:A)(l:list A),\n  last a l -> last b l -> a = b.\nProof.\n  intros A a b l Ha Hb. \n  rewrite last_coherence in Ha. rewrite last_coherence in Hb.\n  rewrite Ha in Hb. \n  pose (g:= fun opt => match opt with | None => a | Some x => x end).\n  fold (g (Some b)). rewrite <- Hb. simpl. reflexivity. (* fold trick *)\nQed.\n\nLemma palindrome_law : forall (A:Type) (a b:A)(l m:list A),\n  palindrome l -> l = cons a m-> last b m -> a = b.\nProof.\n  intros A a b l m H. generalize H. generalize a b m.\n  clear a b m. elim H. intros a b m H0 H1. discriminate H1.\n  intros a x b m H0 H1 H2. fold(tl (x::m)) in H2. rewrite <- H1 in H2.\n  simpl in H2. apply False_ind. apply not_last_a_nil with (a:=b).\n  exact H2. clear H l. intros a l m. intros H0 H1 IH x b l' H2 H3 H4.\n  rewrite H3 in H2. cut(last a l). cut (last b l). cut (x = a).\n  intros H Hb Ha. rewrite H. apply last_unique with (l:=l). \n  exact Ha. exact Hb. \n  pose (g:= fun l => match l with | nil => x | (y::l') => y end). \n  fold(g (x::l')). rewrite <- H3. simpl. reflexivity.   (* fold trick *)\n  fold (tl(a::l)). rewrite H3. simpl. exact H4.         (* fold trick *)\n  apply last_with_rest_last with (m:=m). apply H0.\nQed.\n\n\nLemma palindrome_example3: ~palindrome pal_example3.\nProof.\n  unfold pal_example3. intro pal. cut(1 = 2). intro H.\n  discriminate H. apply palindrome_law with (l:= 1::2::nil)(m:=2::nil).\n  exact pal. reflexivity. apply last1.\nQed.\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/palindrome.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7168779971024085}}
{"text": "Require Import List.\n\nRequire Import CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\n\nPrint pred.\nExtraction pred.\n\n\nLemma zgtz : 0 > 0 -> False.\n  crush.\nQed.\n\nDefinition pred_strong1 (n : nat) : n > 0 -> nat :=\n  match n with\n    | O => fun pf : 0 > 0 => match zgtz pf with end\n    | S n' => fun _ => n'\n  end.\n\nTheorem two_gt0 : 2 > 0.\n  crush.\nQed.\n\nEval compute in pred_strong1 two_gt0.\n\nDefinition pred_strong1' (n : nat) : n > 0 -> nat :=\n  match n return n > 0 -> nat with\n    | O => fun pf : 0 > 0 => match zgtz pf with end\n    | S n' => fun _ => n'\n  end.\n\nExtraction pred_strong1.\n\nPrint sig.\n\n\nLocate \"{ _ : _ | _ }\".\n\n\nDefinition pred_strong2 (s : {n : nat | n > 0}) : nat :=\n  match s with\n    | exist O pf => match zgtz pf with end\n    | exist (S n') _ => n'\n  end.\n\n\nEval compute in pred_strong2 (exist _ 2 two_gt0).\n\nExtraction pred_strong2.\n\nDefinition pred_strong3 (s : {n : nat | n > 0}) : {m : nat | proj1_sig s = S m} :=\nmatch s return {m : nat | proj1_sig s = S m} with\n  | exist 0 pf => match zgtz pf with end\n  | exist (S n') pf => exist _ n' (eq_refl _)\nend.\n\nEval compute in pred_strong3 (exist _ 2 two_gt0).\n\nExtraction pred_strong3.\n\nDefinition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}.\n  refine (fun n =>\n    match n with\n      | O => fun _ => False_rec _ _\n      | S n' => fun _ => exist _ n' _\n    end).\n  Undo.\n  refine (fun n =>\n    match n with\n      | O => fun _ => False_rec _ _\n      | S n' => fun _ => exist _ n' _\n    end); crush.\nDefined.\n\nPrint pred_strong4.\n\nEval compute in pred_strong4 two_gt0.\n\nDefinition pred_strong4' : forall n : nat, n > 0 -> {m : nat | n = S m}.\n  refine (fun n =>\n    match n with\n      | O => fun _ => False_rec _ _\n      | S n' => fun _ => exist _ n' _\n    end); abstract crush.\nDefined.\n\nPrint pred_strong4'.\n\nNotation \"!\" := (False_rec _ _).\nNotation \"[ e ]\" := (exist _ e _).\n\nDefinition pred_strong5 : forall n : nat, n > 0 -> {m : nat | n = S m}.\n  refine (fun n =>\n    match n with\n      | O => fun _ => !\n      | S n' => fun _ => [n']\n    end); crush.\nDefined.\n\nEval compute in pred_strong5 two_gt0.\n\nObligation Tactic := crush.\n\nProgram Definition pred_strong6 (n : nat) (_ : n > 0) : {m : nat | n = S m} :=\n  match n with\n    | O => _\n    | S n' => n'\n  end.\n\nEval compute in pred_strong6 two_gt0.\n\n\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/Subset-test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7168779863053377}}
{"text": "(** DEPRECATED?  \n    \\o notation for composition is used in LibFixDemos\n*)\n\n(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Functions                                                               *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic LibContainer LibSet.\nGeneralizable Variables A.\n\n\n(* ********************************************************************** *)\n(** ** Indentity function *)\n\nDefinition id {A} (x : A) :=\n  x.\n\n\n(* ********************************************************************** *)\n(** Constant functions *)\n\nDefinition const {A B} (v : B) : A -> B :=\n  fun _ => v.\nDefinition const1 :=\n  @const.\nDefinition const2 {A1 A2 B} (v:B) : A1->A2->B :=\n  fun _ _ => v.\nDefinition const3 {A1 A2 A3 B} (v:B) : A1->A2->A3->B :=\n  fun _ _ _ => v.\nDefinition const4 {A1 A2 A3 A4 B} (v:B) : A1->A2->A3->A4->B :=\n  fun _ _ _ _ => v.\nDefinition const5 {A1 A2 A3 A4 A5 B} (v:B) : A1->A2->A3->A4->A5->B :=\n  fun _ _ _ _ _ => v.\n\n\n(* ********************************************************************** *)\n(** Function application *)\n\nDefinition apply {A B} (f : A -> B) (x : A) :=\n  f x.\n\nDefinition apply_to (A : Type) (x : A) (B : Type) (f : A -> B) :=\n  f x.\n\n\n(* ********************************************************************** *)\n(** Function composition *)\n\nDefinition compose {A B C} (g : B -> C) (f : A -> B) :=\n  fun x => g (f x).\n\nNotation \"f1 \\o f2\" := (compose f1 f2)\n  (at level 49, right associativity) : fun_scope.\n\nSection Combinators.\nOpen Scope fun_scope.\nVariables (A B C D : Type).\n\nLemma compose_id_l : forall (f:A->B),\n  id \\o f = f.\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_id_r : forall (f:A->B),\n  f \\o id = f.\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_assoc : forall (f:C->D) (g:B->C) (h:A->B),\n  (f \\o g) \\o h = f \\o (g \\o h).\nProof using. intros. apply~ fun_ext_1. Qed.\n\nLemma compose_eq_l : forall (f:B->C) (g1 g2:A->B),\n  g1 = g2 -> f \\o g1 = f \\o g2.\nProof using. intros. subst~. Qed.\n\nLemma compose_eq_r : forall (f:A->B) (g1 g2:B->C),\n  g1 = g2 -> g1 \\o f = g2 \\o f.\nProof using. intros. subst~. Qed.\n\n(** Composition of [LibList.map] behaves well. **)\n(* Could not be put in [LibList] because of circular dependencies. *)\nFrom TLC Require Import LibList.\n\nLemma list_map_compose : forall A B C (f : A -> B) (g : B -> C) l,\n  LibList.map g (LibList.map f l) = LibList.map (g \\o f) l.\nProof using.\n  introv. induction l.\n   reflexivity.\n   rew_listx. fequals~.\nQed.\n\nEnd Combinators.\n\n(** Tactic for simplifying function compositions *)\n(* --TODO: not used; might become deprecated *)\n\nHint Rewrite compose_id_l compose_id_r compose_assoc : rew_compose.\nTactic Notation \"rew_compose\" :=\n  autorewrite with rew_compose.\nTactic Notation \"rew_compose\" \"in\" \"*\" :=\n  autorewrite with rew_compose in *.\nTactic Notation \"rew_compose\" \"in\" hyp(H) :=\n  autorewrite with rew_compose in H.\n\n\n(* ********************************************************************** *)\n(** ** Function update *)\n\n(** [fupdate f a b x] is like [f] except that it returns [b] for input [a] *)\n\nDefinition fupdate A B (f : A -> B) (a : A) (b : B) : A -> B :=\n  fun x => If (x = a) then b else f x.\n\nLemma fupdate_eq : forall A B (f:A->B) a b x,\n  fupdate f a b x = If (x = a) then b else f x.\nProof using. auto. Qed.\n\nLemma fupdate_same : forall A B (f:A->B) a b,\n  fupdate f a b a = b.\nProof using. intros. unfold fupdate. case_if*. Qed.\n\nLemma fupdate_neq : forall A B (f:A->B) a b x,\n  x <> a ->\n  fupdate f a b x = f x.\nProof using. intros. unfold fupdate. case_if*. Qed.\n\n(* Opaque fupdate. -- could be added in the future *)\n\n\n(* ********************************************************************** *)\n(** ** Function image *)\n\nSection FunctionImage.\nOpen Scope set_scope.\nFrom TLC Require Import LibList.\n\nDefinition image A B (f : A -> B) (E : set A) : set B :=\n  \\set{ y | exists_ x \\in E, y = f x }.\n\nLemma in_image_prove_eq : forall A B x (f : A -> B) (E : set A),\n  x \\in E -> f x \\in image f E.\nProof using. introv N. unfold image. rew_set. exists* x. Qed.\n\nLemma in_image_prove : forall A B x y (f : A -> B) (E : set A),\n  x \\in E -> y = f x -> y \\in image f E.\nProof using. intros. subst. applys* in_image_prove_eq. Qed.\n\nLemma in_image_inv : forall A B y (f : A -> B) (E : set A),\n  y \\in image f E -> exists x, x \\in E /\\ y = f x.\nProof using. introv N. unfolds image. rew_set in N. auto. Qed.\n\nLemma finite_image : forall A B (f : A -> B) (E : set A),\n  finite E ->\n  finite (image f E).\nProof using.\n  introv M. lets (L&H): finite_inv_list_covers M.\n  applys finite_of_list_covers (LibList.map f L). introv N.\n  lets (y&Hy&Ey): in_image_inv (rm N). subst x. applys* mem_map.\nQed.\n\nLemma image_covariant : forall A B (f : A -> B) (E F : set A),\n  E \\c F ->\n  image f E \\c image f F.\nProof using.\n  introv. do 2 rewrite incl_in_eq. introv M N.\n  lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\nQed.\n\nLemma image_union : forall A B (f : A -> B) (E F : set A),\n  image f (E \\u F) = image f E \\u image f F.\nProof using.\n  Hint Resolve in_image_prove.\n  introv. apply in_extens. intros x. iff N.\n    lets (y&Hy&Ey): in_image_inv (rm N). rewrite in_union_eq in Hy.\n     rewrite in_union_eq. destruct* Hy.\n    rewrite in_union_eq in N. destruct N as [N|N].\n      lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\n       rewrite in_union_eq. eauto.\n      lets (y&Hy&Ey): in_image_inv (rm N). applys* in_image_prove.\n       rewrite in_union_eq. eauto.\nQed.\n\nLemma image_singleton : forall A B (f : A -> B) (x : A),\n  image f \\{x} = \\{f x}.\nProof using.\n  intros. apply in_extens. intros z. rewrite in_single_eq. iff N.\n    lets (y&Hy&Ey): in_image_inv (rm N). rewrite in_single_eq in Hy. subst~.\n    applys* in_image_prove. rewrite~ @in_single_eq. typeclass.\nQed.\n\nEnd FunctionImage.\n\nHint Resolve finite_image : finite.\n\n\n(* ********************************************************************** *)\n(** ** Function preimage *)\n\nSection FunctionPreimage.\nOpen Scope set_scope.\n\nDefinition preimage A B (f : A -> B) (E : set B) : set A :=\n  \\set{ x | exists_ y \\in E, y = f x }.\n\nEnd FunctionPreimage.\n\n\n(* ********************************************************************** *)\n(** ** Function iteration *)\n\nFixpoint applyn A n (f : A -> A) x :=\n  match n with\n  | O => x\n  | S n' => f (applyn n' f x)\n  end.\n\nLemma applyn_fix : forall A n f (x : A),\n  applyn (S n) f x = applyn n f (f x).\nProof using. introv. induction~ n. simpls. rewrite~ IHn. Qed.\n\nLemma applyn_comp : forall A n m f (x : A),\n  applyn n f (applyn m f x) = applyn (n + m) f x.\nProof using.\n  introv. gen m; induction n; introv; simpls~.\n  rewrite~ IHn.\nQed.\n\nLemma applyn_nested : forall A n m f (x : A),\n  applyn n (applyn m f) x = applyn (n * m) f x.\nProof using.\n  introv. gen m. induction n; introv; simpls~.\n  rewrite IHn. rewrite~ applyn_comp.\nQed.\n\nLemma applyn_altern : forall A B (f : A -> B) (g : B -> A) x n,\n  applyn n (fun x => f (g x)) (f x) =\n    f (applyn n (fun x => g (f x)) x).\nProof using. introv. gen x. induction~ n. introv. repeat rewrite applyn_fix. autos~. Qed.\n\nLemma applyn_ind : forall A (P : A -> Prop) (f : A -> A) x n,\n  (forall x, P x -> P (f x)) ->\n  P x ->\n  P (applyn n f x).\nProof using. introv I. induction n; introv Hx; autos*. Qed.\n\n\n(* --TODO: rename applyn to iter *)\n(* --TODO: migrate iteration of functionals from LibFix to here *)\n\n", "meta": {"author": "tilk", "repo": "tlc", "sha": "9a07c989dfc12aba4c5fb02107761c8d7e281996", "save_path": "github-repos/coq/tilk-tlc", "path": "github-repos/coq/tilk-tlc/tlc-9a07c989dfc12aba4c5fb02107761c8d7e281996/src/LibFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.7167887030139803}}
{"text": "(** **** Exercise: 5 stars, standard (linsearch_correct)  *)\n\n(** Prove that [linsearch] is correct. The simpler your\n    implementations of [linsearch] and [get], the better.\n\n    Hints: Start by inducting on the input list. The proof is somewhat\n    long and requires a lot of [destruct] and [bdestruct] but only the\n    one use of [induction]. We leave it to you to discover and factor\n    out any helper lemmas you might like. You do not need to write any\n    fancy Ltac automation. *)\n\nTheorem linsearch_correct : correct_search linsearch.\n\n(** We repeat the definition of [sorted] from _Software Foundations_:\n    *)\n\nInductive sorted: list nat -> Prop :=\n| sorted_nil:\n    sorted nil\n| sorted_1 : forall x,\n    sorted (x::nil)\n| sorted_cons: forall x y l,\n    x <= y -> sorted (y :: l) -> sorted (x :: y :: l).\n\n(** Now we specify what it means to be a correct search function. This\n    definition is a formal rendition of the informal specification of\n    the correctness of [linsearch] as given above. *)\n\nDefinition correct_search f :=\n  forall (a : list nat) (v : nat) (k : nat),\n    sorted a\n    -> f a v = k\n    -> (forall i, 1 <= i <= k ->\n            forall u, get a i = Some u -> u <= v)\n    /\\ (forall i, k < i <= length a ->\n            forall u, get a i = Some u -> u > v).\n\nLemma bounds_helper : forall i j,\n    1 <= S i <= S j -> i > 0 -> 1 <= i <= j.\n\nLemma linsearch_helper : forall h t v k,\n    v < h\n    -> sorted (h :: t)\n    -> linsearch (h :: t) v = k\n    -> k = 0 /\\ linsearch t v = 0.\n\nLemma sorted_helper : forall h t,\n    sorted (h :: t) -> sorted t.", "meta": {"author": "joyhuan", "repo": "FormalVerification", "sha": "aabe9cf623caf6cf9259bc0de97a7d6aa1f87499", "save_path": "github-repos/coq/joyhuan-FormalVerification", "path": "github-repos/coq/joyhuan-FormalVerification/FormalVerification-aabe9cf623caf6cf9259bc0de97a7d6aa1f87499/BrainTeasers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7167886912217697}}
{"text": "(*|\n###############################\nHow to optimize a search in Coq\n###############################\n\n:Link: https://stackoverflow.com/q/19747308\n|*)\n\n(*|\nQuestion\n********\n\nI have a simple search function for a property that I am interested\nin, and a proof that the function is correct. I want to evaluate the\nfunction, and use the correctness proof to get the theorem for the\noriginal property. Unfortunately, evaluation in Coq is very slow. As a\ntrivial example, consider looking for square roots:\n|*)\n\n(* Coq 8.4\n   A simple example to demonstrate searching.\n   Timings are rough and approximate. *)\n\nRequire Import Peano_dec.\n\nDefinition SearchSqrtLoop :=\n  fix f i n := if eq_nat_dec (i * i) n\n               then i\n               else match i with\n                    | 0 => 0 (* ~ Square n \\/ n = 0 *)\n                    | S j => f j n\n                    end.\n\nDefinition SearchSqrt n := SearchSqrtLoop n n.\n\n(* Compute SearchSqrt 484.\n   takes about 30 seconds. *)\n\nTheorem sqrt_484a : SearchSqrt 484 = 22.\n  apply eq_refl. (* 100 seconds *)\nQed. (* 50 seconds *)\n\nTheorem sqrt_484b : SearchSqrt 484 = 22.\n  vm_compute. (* 30 seconds *)\n  apply eq_refl.\nQed. (* 30 seconds *)\n\nTheorem sqrt_484c (a : nat) : SearchSqrt 484 = 22.\n  apply eq_refl. (* 100 seconds *)\nQed. (* 50 seconds *)\n\nTheorem sqrt_484d (a : nat) : SearchSqrt 484 = 22.\n  vm_compute. (* 60 seconds *)\n  apply eq_refl.\nQed. (* 60 seconds *)\n\n(*|\nNow try the corresponding function in Python:\n\n.. code-block:: python\n\n    def SearchSqrt(n):\n      for i in range(n, -1, -1):\n        if i * i == n:\n          return i\n      return 0\n\nor slightly more literally\n\n.. code-block:: python\n\n    def SearchSqrtLoop(i, n):\n      if i * i == n:\n        return i\n      if i == 0:\n        return 0\n      return SearchSqrtLoop(i - 1, n)\n\n    def SearchSqrt(n):\n      return SearchSqrtLoop(n, n)\n\nThe function is nearly instant in Python, but takes minutes in Coq,\ndepending on exactly how you try to call it. Also curious is that\nputting an extra variable in makes ``vm_compute`` take twice as long.\n\nI understand that everything is done symbolically in Coq, and thus\nslow, but it would be very useful if I could directly evaluate simple\nfunctions. Is there a way to do it? Just using native integers instead\nof linked lists would probably help a lot.\n|*)\n\n(*|\nAnswer (user1861759)\n********************\n\nYou'll get a speedup if you use binary arithmetic instead of unary\narithmetic. Take a look at ``NArith`` and ``ZArith``.\n\nhttp://coq.inria.fr/library/\n\nYou'll also get a speedup if you run your code on OCaml, Haskell, or\nScheme instead.\n\nhttp://coq.inria.fr/refman/Reference-Manual025.html\n|*)\n\n(*|\nAnswer (Anton Trunov)\n*********************\n\nThere is a much more efficient function for finding square roots in\nthe standard library (`sqrt\n<https://coq.inria.fr/library/Coq.Init.Nat.html#sqrt>`__):\n\n    The following square root function is linear (and tail-recursive).\n    With Peano representation, we can't do better. For faster\n    algorithm, see ``Psqrt``/``Zsqrt``/``Nsqrt``...\n\n.. coq::\n|*)\n\nRequire Import Coq.Init.Nat.\n\nTheorem sqrt_484a_v2 : sqrt 484 = 22.\n  Time apply eq_refl.\n  Time Qed.\n\n(*|\nAs ``Time`` tells us it works much faster (around 200 times faster\nthan ``sqrt_484a``).\n\nThe reason for this performance difference lies in the fact that\n``SearchSqrt`` squares its first argument on each iteration, which is\nan expensive operation.\n\n``sqrt``'s implementation, on the other hand, is based on the `Odd\nNumber Theorem <http://mathworld.wolfram.com/OddNumberTheorem.html>`__\n(``1 + 3 + 5 + ...`` is a square number). One just needs to count the\nnumber of increasing intervals that can be fitted into the input\nargument ``n`` and that would be the `integer square root\n<https://en.wikipedia.org/wiki/Integer_square_root>`__ of ``n``. E.g.\n``22 = (1 + 3 + 5 + 7) + 6``, which means there are 4 intervals (of\nlengths ``1``, ``3``, ``5``, and ``7``) in 22, so ``sqrt 22 = 4`` (and\nwe are not interested in the residual value 6).\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-to-optimize-a-search-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7167886904884604}}
{"text": "Require Import Nijn.Prelude.Checks.\nRequire Import Nijn.Prelude.Funext.\nRequire Import Bool.\n\n(** * Decidable propositions *)\n\n(** A proposition is called decidable if we can either find an element of it or if we can refute it. As such, decidable propositions are those for which the law of excluded middle holds. *)\n\n(** Decidable propositions are those for which we can compute whether they hold or not. We also use this notion to define types with decidable equality, which are types for which we can determine whether two inhabitants are equal. *)\nInductive dec (A : Prop) : Type :=\n| Yes : A -> dec A\n| No : (A -> False) -> dec A.\n\nArguments Yes {_} _.\nArguments No {_} _.\n\n(** * Examples of decidable propositions *)\nDefinition dec_True : dec True := Yes I.\n\nDefinition dec_False : dec False := No (fun z => z).\n\nDefinition dec_not {A : Prop} (x : dec A) : dec (~A)\n  := match x with\n     | Yes a => No (fun q => q a)\n     | No a => Yes a\n     end.\n\nDefinition dec_and {A B : Prop} (x : dec A) (y : dec B) : dec (A /\\ B)\n  := match x , y with\n     | Yes p , Yes q => Yes (conj p q)\n     | No p , _ => No (fun z => p (proj1 z))\n     | _ , No q => No (fun z => q (proj2 z))\n     end.\n\nDefinition dec_or {A B : Prop} (x : dec A) (y : dec B) : dec (A \\/ B)\n  := match x , y with\n     | No p , No q =>\n       No (fun z =>\n           match z with\n           | or_introl a => p a\n           | or_intror b => q b\n           end)\n     | Yes p , _ => Yes (or_introl p)\n     | _ , Yes q => Yes (or_intror q)\n     end.\n\n(** * Decidable equality *)\n\nClass decEq (A : Type) :=\n  {\n    dec_eq : forall (a₁ a₂ : A), dec (a₁ = a₂)\n  }.\n\n(** A tactic for proving decidable equality on finite types *)\nLtac decEq_finite :=\n  unshelve esplit ;\n  (let x := fresh in intro x ; induction x) ;\n  (let x := fresh in intro x ; induction x) ;\n  try (apply Yes ; abstract (reflexivity)) ;\n  try (apply No ; abstract (discriminate)).\n\nNotation \"! p\" := (eq_sym p) (at level 80).\n\n(** We use the so-called `transport` function at numerous occassions. Our usage is more technical though. *)\nDefinition transport\n           {A : Type}\n           (Y : A -> Type)\n           {a₁ a₂ : A}\n           (p : a₁ = a₂)\n  : Y a₁ -> Y a₂\n  := match p with\n     | eq_refl => fun z => z\n     end.\n\nLemma transport_sym_p\n      {A : Type}\n      (B : A -> Type)\n      {x y : A}\n      (p : x = y)\n      (b : B x)\n  : transport B (eq_sym p) (transport B p b) = b.\nProof.\n  subst.\n  cbn.\n  reflexivity.\nQed.\n\n(** Equality in sigma types *)\nProposition path_in_sigma_fst\n            {A : Type}\n            {B : A -> Type}\n            {x y : {x : A & B x}}\n            (p : x = y)\n  : projT1 x = projT1 y.\nProof.\n  induction p.\n  reflexivity.\nDefined.\n\nProposition path_in_sigma_snd\n            {A : Type}\n            {B : A -> Type}\n            {x y : {x : A & B x}}\n            (p : x = y)\n  : transport B (path_in_sigma_fst p) (projT2 x) = projT2 y.\nProof.\n  subst.\n  reflexivity.\nDefined.\n\nProposition from_path_in_sigma\n            {A : Type}\n            (B : A -> Type)\n            {a : A}\n            {b1 b2 : B a}\n            (p : existT _ a b1 = existT _ a b2)\n  : b1 = b2.\nProof.\n  pose (path_in_sigma_snd p) as q.\n  rewrite (UIP (path_in_sigma_fst p) eq_refl) in q.\n  exact q.\nDefined.\n\n(** * Examples of types with decidable equality *)\n\n(** The unit type has decidable equality *)\nDefinition dec_eq_unit\n           (x y : unit)\n  : dec (x = y)\n  := match x , y with\n     | tt , tt => Yes eq_refl\n     end.\n\nGlobal Instance decEq_unit : decEq unit\n  := {| dec_eq := dec_eq_unit |}.\n\n(** The booleans have decidable equality *)\nDefinition dec_eq_bool\n           (x y : bool)\n  : dec (x = y)\n  := match x , y with\n     | true , true => Yes eq_refl\n     | false , false => Yes eq_refl\n     | true , false => No diff_true_false\n     | false , true => No diff_false_true\n     end.\n\nGlobal Instance decEq_bool : decEq bool\n  := {| dec_eq := dec_eq_bool |}.\n  \n(** The product of types with decidable equality has decidable equality *)\nSection ProductDecEq.\n  Context {A B : Type}\n          `{decEq A}\n          `{decEq B}.\n\n  Definition path_pair\n             {a₁ a₂ : A}\n             {b₁ b₂ : B}\n             (p : a₁ = a₂)\n             (q : b₁ = b₂)\n    : (a₁ , b₁) = (a₂ , b₂)\n    := match p , q with\n       | eq_refl , eq_refl => eq_refl\n       end.\n\n  Definition dec_eq_product\n             (x y : A * B)\n    : dec (x = y)\n    := match x , y with\n       | (x1 , x2) , (y1 , y2) =>\n         match dec_eq x1 y1 with\n         | Yes p =>\n           match dec_eq x2 y2 with\n           | Yes q => Yes (path_pair p q)\n           | No q => No (fun (r : (x1 , x2) = (y1 , y2)) => q (f_equal snd r))\n           end\n         | No p => No (fun (r : (x1 , x2) = (y1 , y2)) => p (f_equal fst r))\n         end\n       end.\n\n  Global Instance decEq_product : decEq (A * B)\n    := {| dec_eq := dec_eq_product |}.\nEnd ProductDecEq.\n\n(** The sum of types with decidable equality has decidable equality *)\nSection SumDecEq.\n  Context {A B : Type}\n          `{decEq A}\n          `{decEq B}.\n\n  Definition inl_inj\n             {x y : A}\n             (p : (inl x : A + B) = inl y)\n    : x = y.\n  Proof.\n    inversion p.\n    reflexivity.\n  Qed.\n\n  Definition inr_inj\n             {x y : B}\n             (p : (inr x : A + B) = inr y)\n    : x = y.\n  Proof.\n    inversion p.\n    reflexivity.\n  Qed.\n\n  Definition inl_not_inr\n             {x : A}\n             {y : B}\n             (p : inl x = inr y)\n    : False.\n  Proof.\n    discriminate.\n  Qed.\n\n  Definition inr_not_inl\n             {x : B}\n             {y : A}\n             (p : inr x = inl y)\n    : False.\n  Proof.\n    discriminate.\n  Qed.\n  \n  Definition dec_eq_sum\n             (x y : A + B)\n    : dec (x = y)\n    := match x , y with\n       | inl x , inl y =>\n         match dec_eq x y with\n         | Yes p => Yes (f_equal inl p)\n         | No p => No (fun q => p (inl_inj q))\n         end\n       | inl x , inr y => No (fun q => inl_not_inr q)\n       | inr x , inl y => No (fun q => inr_not_inl q)\n       | inr x , inr y =>\n         match dec_eq x y with\n         | Yes p => Yes (f_equal inr p)\n         | No p => No (fun q => p (inr_inj q))\n         end\n       end.\n\n  Global Instance decEq_sum : decEq (A + B)\n    := {| dec_eq := dec_eq_sum |}.\nEnd SumDecEq.\n\n(** The natural numbers have decidable equality *)\nDefinition help_fam\n           (n : nat)\n  : Prop\n  := match n with\n     | 0 => True\n     | S _ => False\n     end.\n\nDefinition S_inj\n           {n m : nat}\n           (p : S n = S m)\n  : n = m.\nProof.\n  inversion p.\n  reflexivity.\nQed.\n\nFixpoint dec_eq_nat\n         (n : nat)\n  : forall (m : nat), dec (n = m)\n  := match n with\n     | 0 =>\n       fun m =>\n         match m with\n         | 0 => Yes eq_refl\n         | S m => No (fun (q : 0 = S m) => transport help_fam q I)\n         end\n     | S n =>\n       fun m =>\n         match m with\n         | 0 => No (fun (q : S n = 0) => transport help_fam (!q) I)\n         | S m =>\n           match dec_eq_nat n m with\n           | Yes p => Yes (f_equal S p)\n           | No p => No (fun q => p (S_inj q))\n           end\n         end\n     end.\n\nGlobal Instance decEq_nat : decEq nat\n  := {| dec_eq := dec_eq_nat |}.\n", "meta": {"author": "nmvdw", "repo": "Nijn", "sha": "9bd88a93cdf0ab521536249fe628e9e63341f473", "save_path": "github-repos/coq/nmvdw-Nijn", "path": "github-repos/coq/nmvdw-Nijn/Nijn-9bd88a93cdf0ab521536249fe628e9e63341f473/Code/Prelude/Basics/Decidable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7167886828287263}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nOpen Scope ring_scope.\n\nSection CPGE.\n(**\n\n*)\nSection ex_6_12.\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n* Exercices de mathématiques oraux X-ens Algebre 1\n\n* Exercise 6.12: Endomorphisms u such that Ker u = Im u.\n\nLet E be a vector space (any dimension, but in Coq we reason in finite\ndimension).\n\n*)\nVariables (F : fieldType) (n' : nat).\nLet n := n'.+1.\n\nSection Q1.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n** Question 1.\n\nLet u be an endomorphism of E, such that Ker u = Im u and S be a\ncomplement of Im u (\"supplémentaire\" in french), so that E is the\ndirect sum of S and Im u.\n\n*)\nVariable (u : 'M[F]_n) (S : 'M[F]_n).\nHypothesis eq_keru_imu : (kermx u :=: u)%MS.\nHypothesis S_u_direct : (S :&: u)%MS = 0.\nHypothesis S_u_eq1 : (S + u :=: 1)%MS.\n\nImplicit Types (x y z : 'rV[F]_n).\n(**\n\n*** Question 1.a.\n\nShow that for all x in E, there is a unique pair (y, z) in S² such\nthat x = y + u (z), and pose v and z so that y = v(x) and z = w(x).\n\nInstead of defining y and z for each x, we now define explicitly the\nmatrix that computes y and z from x.\n\n - A direct consequence of this is that v and w will be morphisms by\n  construction, you can thus skip the part of the paper proof that\n  deals with this.\n\n - Every morphism induces an ismorphism between a complement of its\n   kernel and its image.  The function #<code>pinvmx</code># is the\n   inverse of this isomporhism, but since the complement of the kernel\n   that was used to produce #<code>pinvmx</code># is arbitrary, we\n   must project the result of #<code>pinvmx</code># on S in order to\n   get the specific inverse with image S.\n*)\nDefinition w := locked (proj_mx S u).\nDefinition v := locked (proj_mx u S * pinvmx u * proj_mx S u).\n(**\n\nNote that we used locking in order to protect w and v from expanding\nunexpectedly during proofs.\n\n</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n**** Question 1.a.i.\n\nProve the following lemmas.\n\n*)\nLemma wS x : (x *m w <= S)%MS.\nProof.\nunlock w.\n(*D*)by rewrite proj_mx_sub.\n(*A*)Qed.\n\nLemma vS x : (x *m v <= S)%MS.\nProof.\nunlock v.\n(*D*)by rewrite mulmxA proj_mx_sub.\n(*A*)Qed.\n\nLemma w_id x : (x <= S)%MS -> x *m w = x.\nProof.\nunlock w => xS.\n(*D*)by rewrite proj_mx_id ?S_u_direct.\n(*A*)Qed.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n\n**** Question 1.a.ii.\n\nReuse and adapt and the proof in the course.\n\n- (hint: use mulmxKpV)\n\n*)\nLemma Su_rect x : x = x *m w + (x *m v) *m u.\nProof.\nunlock v w.\n(*\nremember we had t, z' and z\ny := x *m proj_mx S u\nt := x *m proj_mx u S\nz' := t *m pinvmx u\nz := z' *m proj_mx S u.\nand x = y + z *m u\n    z' *m u = z *m u\n    z' *m u = t\n*)\n(*D*)rewrite -{1}(@add_proj_mx _ _ _ S u x) ?S_u_direct ?S_u_eq1 ?submx1 //.\n(*D*)congr (_ + _); apply/eqP.\n(*D*)rewrite -[x *m proj_mx u S](@mulmxKpV _ _ _ _ _ u) ?proj_mx_sub //.\n(*D*)rewrite 2![x *m _ in X in _ == X]mulmxA -subr_eq0 -mulmxBl.\n(*D*)apply/eqP/sub_kermxP.\n(*D*)by rewrite eq_keru_imu proj_mx_compl_sub ?S_u_eq1 ?submx1.\n(*A*)Qed.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n**** Question 1.a.iii.\n\nFrom the proof\n\n*)\nLemma Su_dec_eq0 y z : (y <= S)%MS -> (z <= S)%MS ->\n  (y + z *m u == 0) = (y == 0) && (z == 0).\nProof.\nmove=> yS zS; apply/idP/idP; last first.\n  by move=> /andP[/eqP -> /eqP ->]; rewrite add0r mul0mx.\nrewrite addr_eq0 -mulNmx => /eqP eq_y_Nzu.\nhave : (y <= S :&: u)%MS by rewrite sub_capmx yS eq_y_Nzu submxMl.\nrewrite S_u_direct // submx0 => /eqP y_eq0.\nmove/eqP: eq_y_Nzu; rewrite y_eq0 eq_sym mulNmx oppr_eq0 eqxx /= => /eqP.\nmove=> /sub_kermxP; rewrite eq_keru_imu => z_keru.\nhave : (z <= S :&: u)%MS by rewrite sub_capmx zS.\nby rewrite S_u_direct // submx0.\nQed.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\ndeduce\n\n*)\nLemma Su_dec_uniq y y' z z' : (y <= S)%MS -> (z <= S)%MS ->\n                              (y' <= S)%MS -> (z' <= S)%MS ->\n  (y + z *m u == y' + z' *m u) = (y == y') && (z == z').\nProof.\n(*D*)move=> yS zS y'S z'S; rewrite -subr_eq0 opprD addrACA -mulmxBl.\n(*D*)by rewrite Su_dec_eq0 ?addmx_sub ?eqmx_opp // !subr_eq0.\n(*A*)Qed.\n(**\n**** Question 1.a.iii.\n\nShow some simplification lemmas\n- the two first are direct\n- the two last use Su_dec_uniq.\n\n*)\nLemma u2_eq0 : u *m u = 0.\n(*A*)Proof. by apply/sub_kermxP; rewrite eq_keru_imu. Qed.\n\nLemma u2K m (a : 'M_(m,n)) : a *m u *m u = 0.\n(*D*)Proof. by rewrite -mulmxA u2_eq0 mulmx0. Qed.\n\nLemma v_id x : (x <= S)%MS -> (x *m u) *m v = x.\nProof.\n(*D*)move=> xS; have /eqP := Su_rect (x *m u).\n(*D*)rewrite -[X in X == _]add0r Su_dec_uniq ?sub0mx ?vS ?wS //.\n(*D*)by move=> /andP [_ /eqP <-].\n(*A*)Qed.\n\nLemma w0 x : (x <= S)%MS -> (x *m u) *m w = 0.\nProof.\n(*D*)move=> xS; have /eqP := Su_rect (x *m u).\n(*D*)rewrite -[X in X == _]add0r Su_dec_uniq ?sub0mx ?vS ?wS //.\n(*D*)by move=> /andP [/eqP <-].\n(*A*)Qed.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n*** Question 1.b.\n\n- Show that v is linear.\n- Show that u o v + v o u = 1.\n\n*)\nLemma add_uv_vu : v *m u + u *m v = 1.\nProof.\n(*D*)apply/row_matrixP => i; rewrite !rowE; move: (delta_mx _ _) => x.\n(*D*)rewrite mulmx1 mulmxDr !mulmxA {2}[x]Su_rect mulmxDl u2K addr0.\n(*D*)by rewrite v_id ?wS // addrC -Su_rect.\n(*A*)Qed.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n*** Question 1.c.\n\n- Show that w is linear.\n- Show that u o w + w o u = u.\n\n*)\nLemma add_wu_uw : w *m u + u *m w = u.\nProof.\n(*D*)apply/row_matrixP => i; rewrite !rowE; move: (delta_mx _ _) => x.\n(*D*)rewrite mulmxDr !mulmxA {2}[x]Su_rect mulmxDl u2K addr0 w0 ?wS // addr0.\n(*D*)by have /(canLR (addrK _)) <- := Su_rect x; rewrite mulmxBl u2K subr0.\n(*A*)Qed.\n\nEnd Q1.\n(** #</div># *)\n(** -------------------------------------------- *)\n(** #<div class='slide'>#\n\n** State and prove question 2, and then 3...\n\n*)\n\nEnd ex_6_12.\nEnd CPGE.\n", "meta": {"author": "gares", "repo": "CWS16", "sha": "608148973a715994ebbedb0a48724f2755c7bc89", "save_path": "github-repos/coq/gares-CWS16", "path": "github-repos/coq/gares-CWS16/CWS16-608148973a715994ebbedb0a48724f2755c7bc89/exercise7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8670357529306639, "lm_q1q2_score": 0.7167886828287263}}
{"text": "Require Import ZArith.\nRequire Import Omega.\n\nLemma hoge : forall z : Z, (z ^ 4 - 4 * z ^ 2 + 4 > 0)%Z.\nProof.\n  intro.\n  replace (z^4-4*z^2+4)%Z with ((z*z-2)*(z*z-2))%Z by ring.\n  rewrite <- Z.square_spec.\n  assert (forall p, (Z.pos p * Z.pos p - 2)%Z <> 0%Z).\n  intros.\n  destruct p.\n  remember (Z.pos p~1) as m3.\n  assert (m3 >= 3)%Z.\n  rewrite Heqm3.\n  unfold Z.ge.\n  simpl.\n  unfold Pos.compare, Pos.compare_cont.\n  destruct p.\n  congruence.\n  congruence.\n  congruence.\n  assert (m3*m3 >= 3*m3)%Z.\n  apply Zmult_ge_compat_r.\n  assumption.\n  omega.\n  omega.\n  remember (Z.pos p~0) as m2.\n  assert (m2 >= 2)%Z.\n  rewrite Heqm2.\n  unfold Z.ge.\n  simpl.\n  unfold Pos.compare, Pos.compare_cont.\n  destruct p.\n  congruence.\n  congruence.\n  congruence.\n  assert (m2*m2 >= 2*m2)%Z.\n  apply Zmult_ge_compat_r.\n  assumption.\n  omega.\n  omega.\n  omega.\n  assert (z*z-2 <> 0)%Z.\n  destruct z.\n  omega.\n  apply H.\n  replace (Z.neg p * Z.neg p)%Z with (Z.pos p * Z.pos p)%Z.\n  apply H.\n  simpl.\n  reflexivity.\n  remember (z*z-2)%Z as y.\n  destruct y.\n  congruence.\n  simpl.\n  unfold Z.gt.\n  reflexivity.\n  simpl.\n  unfold Z.gt.\n  reflexivity.\nQed.", "meta": {"author": "kitayuta", "repo": "CoqEx2014", "sha": "ed9e347270aaed9872b4ebc50ab44a7c1e7ea24c", "save_path": "github-repos/coq/kitayuta-CoqEx2014", "path": "github-repos/coq/kitayuta-CoqEx2014/CoqEx2014-ed9e347270aaed9872b4ebc50ab44a7c1e7ea24c/Ex6/27.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346504434783, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.71675007044673}}
{"text": "Require Import Coq.Arith.PeanoNat.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Relations.Relation_Operators.\nRequire Import Coq.Setoids.Setoid.\nRequire Import DschingisKhan.Prelude.PreludeInit.\nRequire Import DschingisKhan.Prelude.PreludeMath.\nRequire Import DschingisKhan.Prelude.PreludeUtil.\n\nModule BasicPosetTheory.\n\n  Import ListNotations MathProps MathNotations MathClasses.\n\n  Lemma leProp_unfold {D : Type} {requiresPoset : isPoset D}\n    : forall x : D, forall y : D, x =< y <-> (forall z : D, z =< x -> z =< y).\n  Proof. exact (proj1 (PreOrder_iff leProp) (@leProp_PreOrder D requiresPoset)). Qed.\n\n  Definition isMonotonicMap {dom : Type} {cod : Type} {dom_isPoset : isPoset dom} {cod_isPoset : isPoset cod} (f : dom -> cod) : Prop :=\n    forall x : dom, forall x' : dom, forall x_le_x' : x =< x', f x =< f x'\n  .\n\n  Lemma isMonotonicMap_iff_preserves_leProp1 {dom : Type} {cod : Type} {dom_isPoset : isPoset dom} {cod_isPoset : isPoset cod} (f : dom -> cod)\n    : isMonotonicMap f <-> preserves_leProp1 f.\n  Proof. reflexivity. Qed.\n\n  Global Notation \" f '\\monotonic' \" := (preserves_leProp1 f)\n    (in custom math_form_scope at level 6, f custom math_term_scope at level 1, no associativity).\n  Global Notation \" '('  X  ')↑' \" := (UpperBoundsOf X)\n    (in custom math_form_scope at level 0, X custom math_term_scope at level 5).\n  Global Notation \" sup_X '=' '\\sup' X \" := (isSupremumOf sup_X X)\n    (in custom math_form_scope at level 6, sup_X custom math_term_scope at level 1, X custom math_term_scope at level 5).\n  Global Notation \" '('  X  ')↓' \" := (LowerBoundsOf X)\n    (in custom math_form_scope at level 0, X custom math_term_scope at level 5).\n  Global Notation \" inf_X '=' '\\inf' X \" := (isInfimumOf inf_X X)\n    (in custom math_form_scope at level 6, inf_X custom math_term_scope at level 1, X custom math_term_scope at level 5).\n  Global Notation \" '\\{' '\\sup' Y ':' X '∈' Xs '\\}' \" := (ensemble_bind Xs (fun X => fun sup => isSupremumOf sup Y))\n    (in custom math_term_scope at level 0, Xs custom math_term_scope at level 5, X pattern, Y custom math_term_scope at level 1, no associativity).\n  Global Notation \" '\\{' '\\inf' Y ':' X '∈' Xs '\\}' \" := (ensemble_bind Xs (fun X => fun inf => isInfimumOf inf Y))\n    (in custom math_term_scope at level 0, Xs custom math_term_scope at level 5, X pattern, Y custom math_term_scope at level 1, no associativity).\n\n  Create HintDb poset_hints.\n  Global Hint Unfold REFERENCE_HOLDER member UpperBoundsOf LowerBoundsOf isSupremumOf isInfimumOf isMonotonicMap : poset_hints.\n  Global Hint Resolve member_eq_leProp_with_impl member_eq_eqProp_with_iff leProp_lifted1 leProp_unfold : poset_hints.\n\n  Global Add Parametric Morphism {D : Type} (requiresPoset : isPoset D) :\n    (UpperBoundsOf (requiresPoset := requiresPoset)) with signature (eqProp ==> eqProp)\n    as UpperBoundsOf_compatWith_eqProp_wrtEnsembles.\n  Proof with eauto with *.\n    intros X Y X_eq_Y z. split; intros H_upper_bound.\n    - intros y y_in_Y. eapply H_upper_bound. unnw. rewrite -> X_eq_Y...\n    - intros x x_in_X. eapply H_upper_bound. unnw. rewrite <- X_eq_Y...\n  Qed.\n\n  Global Add Parametric Morphism {D : Type} (requiresPoset : isPoset D) :\n    (LowerBoundsOf (requiresPoset := requiresPoset)) with signature (eqProp ==> eqProp)\n    as LowerBoundsOf_compatWith_eqProp_wrtEnsembles.\n  Proof with eauto with *.\n    intros X Y X_eq_Y z. split; intros H_lower_bound.\n    - intros y y_in_Y. eapply H_lower_bound. unnw. rewrite -> X_eq_Y...\n    - intros x x_in_X. eapply H_lower_bound. unnw. rewrite <- X_eq_Y...\n  Qed.\n\n  Global Hint Resolve UpperBoundsOf_compatWith_eqProp_wrtEnsembles LowerBoundsOf_compatWith_eqProp_wrtEnsembles monotonic_guarantees_leProp_lifted1 monotonic_guarantees_leProp_lifted2 monotonic_guarantees_eqProp_lifted1 monotonic_guarantees_eqProp_lifted2 : poset_hints.\n\n  Section BASIC_FACTS_ON_SUPREMUM.\n\n  Context {D : Type} {requiresPoset : isPoset D}.\n\n  Lemma Supremum_isInfimumOf_itsUpperBounds (X : ensemble D) (q : D)\n    (q_isSupremumOf_X : isSupremumOf q X)\n    : isInfimumOf q (fun x : D => q =< x).\n  Proof with eauto with *.\n    intros d. unnw. split.\n    - intros d_le_q x q_le_x. rewrite d_le_q...\n    - intros d_in. eapply d_in, q_isSupremumOf_X.\n      ii; desnw. eapply q_isSupremumOf_X...\n  Qed.\n\n  Lemma Supremum_monotonic_wrtEnsembles (X1 : ensemble D) (X2 : ensemble D) (sup_X1 : D) (sup_X2 : D)\n    (sup_X1_isSupremumOf_X1 : isSupremumOf sup_X1 X1)\n    (sup_X2_isSupremumOf_X2 : isSupremumOf sup_X2 X2)\n    (X1_isSubsetOf_X2 : isSubsetOf X1 X2)\n    : sup_X1 =< sup_X2.\n  Proof.\n    eapply sup_X1_isSupremumOf_X1; ii.\n    eapply sup_X2_isSupremumOf_X2; eauto with *.\n  Qed.\n\n  Local Hint Resolve Supremum_monotonic_wrtEnsembles : poset_hints.\n\n  Lemma Supremum_unique (X1 : ensemble D) (X2 : ensemble D) (sup_X1 : D) (sup_X2 : D)\n    (sup_X1_isSupremumOf_X1 : isSupremumOf sup_X1 X1)\n    (sup_X2_isSupremumOf_X2 : isSupremumOf sup_X2 X2)\n    (X1_eq_X2 : X1 == X2)\n    : sup_X1 == sup_X2.\n  Proof.\n    pose proof (eqProp_implies_leProp X1 X2 X1_eq_X2) as claim1. symmetry in X1_eq_X2.\n    pose proof (eqProp_implies_leProp X2 X1 X1_eq_X2) as claim2. eapply leProp_Antisymmetric; eauto with *.\n  Qed.\n\n  Local Hint Resolve Supremum_unique : poset_hints.\n\n  Lemma Supremum_congruence (sup_X : D) (sup_Y : D) (X : ensemble D) (Y : ensemble D)\n    (sup_X_eq_sup_Y : sup_X == sup_Y)\n    (X_eq_Y : X == Y)\n    (sup_X_isSupremumOf_X : isSupremumOf sup_X X)\n    : isSupremumOf sup_Y Y.\n  Proof with eauto with *.\n    intros z. unnw. rewrite <- sup_X_eq_sup_Y. split.\n    - intros sup_X_le_z. rewrite <- X_eq_Y. eapply sup_X_isSupremumOf_X...\n    - intros z_isUpperBoundOf_Y. eapply sup_X_isSupremumOf_X. unnw. rewrite -> X_eq_Y...\n  Qed.\n\n  Local Hint Resolve Supremum_congruence : poset_hints.\n\n  Global Add Parametric Morphism :\n    (@isSupremumOf D requiresPoset) with signature (eqProp ==> eqProp ==> iff)\n    as Supremum_compatWith_eqProp_wrtEnsembles.\n  Proof. iis; eauto with *. Qed.\n\n  Definition MapSuprema (Xs : ensemble (ensemble D)) : ensemble D :=\n    bind Xs (fun X_i : ensemble D => fun sup_X_i : D => isSupremumOf sup_X_i X_i)\n  .\n\n  Lemma in_MapSuprema_iff (Xs : ensemble (ensemble D)) (sup : D)\n    : member sup (MapSuprema Xs) <-> (exists X_i : ensemble D, member X_i Xs /\\ isSupremumOf sup X_i).\n  Proof. reflexivity. Qed.\n\n  Lemma SupremumOfMapSuprema_ge_Suprema (sup : D) (Xs : ensemble (ensemble D)) (sup_X : D) (X : ensemble D)\n    (sup_isSupremumOf : isSupremumOf sup (MapSuprema Xs))\n    (X_in_Xs : member X Xs)\n    (sup_X_isSupremumOf_X : isSupremumOf sup_X X)\n    : sup_X =< sup.\n  Proof with eauto with *. eapply sup_isSupremumOf... eapply in_MapSuprema_iff... Qed.\n\n  Local Hint Resolve SupremumOfMapSuprema_ge_Suprema : poset_hints.\n\n  Theorem SupremumOfMapSuprema_isSupremumOf_unions (Xs : ensemble (ensemble D)) (sup : D)\n    (SUPS_EXIST : forall X : ensemble D, << H_IN : member X Xs >> -> exists sup_X : D, isSupremumOf sup_X X)\n    : isSupremumOf sup (MapSuprema Xs) <-> isSupremumOf sup (unions Xs).\n  Proof with eauto with *.\n    split; intros H_supremum z; split; ii; desnw.\n    - apply in_unions_iff in H_IN. destruct H_IN as [X_i [x_in_X_i X_i_in_Xs]].\n      pose proof (SUPS_EXIST X_i X_i_in_Xs) as [sup_X_i sup_X_i_isSupremumOf_X_i].\n      transitivity (sup_X_i).\n      + eapply sup_X_i_isSupremumOf_X_i...\n      + transitivity (sup)...\n    - eapply H_supremum. intros sup_X_i sup_X_i_in_MapSuprema.\n      apply in_MapSuprema_iff in sup_X_i_in_MapSuprema.\n      destruct sup_X_i_in_MapSuprema as [X_i [X_i_in_Xs sup_X_i_isSupremumOf_X_i]].\n      eapply sup_X_i_isSupremumOf_X_i. ii. desnw. eapply UPPER_BOUND. eapply in_unions_iff...\n    - apply in_MapSuprema_iff in H_IN. destruct H_IN as [X [X_in_Xs sup_X_isSupremumOf_X]].\n      rename x into sup_X. enough (to_show : sup_X =< sup) by now transitivity (sup).\n      eapply sup_X_isSupremumOf_X. ii; desnw. eapply H_supremum... eapply in_unions_iff...\n    - eapply H_supremum. ii; desnw. apply in_unions_iff in H_IN.\n      destruct H_IN as [X [x_in_X X_in_Xs]]. pose proof (SUPS_EXIST X X_in_Xs) as [sup_X sup_X_isSupremumOf_X].\n      transitivity (sup_X).\n      + eapply sup_X_isSupremumOf_X...\n      + eapply UPPER_BOUND, in_MapSuprema_iff...\n  Qed.\n\n  Theorem InfimumOfUpperBounds_isSupremum (sup_X : D) (X : ensemble D)\n    : isSupremumOf sup_X X <-> << sup_X_isInfimumOfUpperBounds : isInfimumOf sup_X (UpperBoundsOf X) >>.\n  Proof with eauto with *.\n    split.\n    - intros sup_X_isSupremumOf_X z. split; ii; desnw.\n      + rewrite LOWER_BOUND_LE_INFIMUM.\n        eapply sup_X_isSupremumOf_X...\n      + eapply LOWER_BOUND, sup_X_isSupremumOf_X...\n    - intros H_supremum z. split; ii; desnw.\n      + rewrite <- SUPREMUM_LE_UPPER_BOUND.\n        eapply sup_X_isInfimumOfUpperBounds. unnw.\n        intros upper_bound upper_bound_in. unnw.\n        exact (upper_bound_in x H_IN).\n      + unnw. eapply sup_X_isInfimumOfUpperBounds...\n  Qed.\n\n  Theorem SupremumOfLowerBounds_isInfimum (inf_X : D) (X : ensemble D)\n    : isInfimumOf inf_X X <-> << inf_X_isSupremumOfLowerBounds : isSupremumOf inf_X (LowerBoundsOf X) >>.\n  Proof with eauto with *.\n    split.\n    - intros inf_X_isInfimumOf_X z. split; ii; desnw.\n      + rewrite <- SUPREMUM_LE_UPPER_BOUND.\n        eapply inf_X_isInfimumOf_X...\n      + eapply UPPER_BOUND, inf_X_isInfimumOf_X...\n    - intros H_infimum z. split; ii; desnw.\n      + rewrite LOWER_BOUND_LE_INFIMUM.\n        eapply inf_X_isSupremumOfLowerBounds. unnw.\n        intros lower_bound lower_bound_in. unnw.\n        exact (lower_bound_in x H_IN).\n      + unnw. eapply inf_X_isSupremumOfLowerBounds...\n  Qed.\n\n  Lemma Infimum_monotonic_wrtEnsembles (X1 : ensemble D) (X2 : ensemble D) (inf_X1 : D) (inf_X2 : D)\n    (inf_X1_isInfimumOf_X1 : isInfimumOf inf_X1 X1)\n    (inf_X2_isInfimumOf_X2 : isInfimumOf inf_X2 X2)\n    (X1_isSubsetOf_X2 : isSubsetOf X1 X2)\n    : inf_X2 =< inf_X1.\n  Proof.\n    eapply inf_X1_isInfimumOf_X1; ii.\n    eapply inf_X2_isInfimumOf_X2; eauto with *.\n  Qed.\n\n  Local Hint Resolve Infimum_monotonic_wrtEnsembles : poset_hints.\n\n  Lemma Infimum_unique (X1 : ensemble D) (X2 : ensemble D) (inf_X1 : D) (inf_X2 : D)\n    (inf_X1_isInfimumOf_X1 : isInfimumOf inf_X1 X1)\n    (inf_X2_isInfimumOf_X2 : isInfimumOf inf_X2 X2)\n    (X1_eq_X2 : X1 == X2)\n    : inf_X1 == inf_X2.\n  Proof.\n    pose proof (eqProp_implies_leProp X1 X2 X1_eq_X2) as claim1. symmetry in X1_eq_X2.\n    pose proof (eqProp_implies_leProp X2 X1 X1_eq_X2) as claim2. eapply leProp_Antisymmetric; eauto with *.\n  Qed.\n\n  Lemma Infimum_congruence (inf_X : D) (inf_Y : D) (X : ensemble D) (Y : ensemble D)\n    (inf_X_eq_inf_Y : inf_X == inf_Y)\n    (X_eq_Y : X == Y)\n    (inf_X_isInfimumOf_X : isInfimumOf inf_X X)\n    : isInfimumOf inf_Y Y.\n  Proof with eauto with *.\n    intros z. unnw. rewrite <- inf_X_eq_inf_Y. split.\n    - intros z_le_inf_X. rewrite <- X_eq_Y. eapply inf_X_isInfimumOf_X...\n    - intros z_isLowerBoundOf_Y. eapply inf_X_isInfimumOf_X. unnw. rewrite -> X_eq_Y...\n  Qed.\n\n  Local Hint Resolve Infimum_unique Infimum_congruence : core.\n\n  Global Add Parametric Morphism :\n    (@isInfimumOf D requiresPoset) with signature (eqProp ==> eqProp ==> iff)\n    as Infimum_compatWith_eqProp_wrtEnsembles.\n  Proof. iis; eauto with *. Qed.\n\n  Definition isLeastFixedPointOf (lfp : D) (f : D -> D) : Prop :=\n    << IS_FIXED_POINT : member lfp (FixedPoints f) >> /\\ << LOWER_BOUND_OF_FIXED_POINTS : member lfp (LowerBoundsOf (FixedPoints f)) >>\n  .\n\n  Definition isGreatestFixedPointOf (gfp : D) (f : D -> D) : Prop :=\n    << IS_FIXED_POINT : member gfp (FixedPoints f) >> /\\ << UPPER_BOUND_OF_FIXED_POINTS : member gfp (UpperBoundsOf (FixedPoints f)) >>\n  .\n\n  Local Hint Unfold isLeastFixedPointOf isGreatestFixedPointOf : poset_hints.\n\n  Theorem theLeastFixedPointOfMonotonicMap (f : D -> D) (lfp : D)\n    (f_isMonotonicMap : isMonotonicMap f)\n    (lfp_isInfimumOfPrefixedPoints : isInfimumOf lfp (PrefixedPoints f))\n    : isLeastFixedPointOf lfp f.\n  Proof with eauto with *.\n    assert (claim1 : forall x : D, member x (FixedPoints f) -> lfp =< x).\n    { intros x H_IN. transitivity (f x).\n      - eapply lfp_isInfimumOfPrefixedPoints... eapply f_isMonotonicMap...\n      - eapply eqProp_implies_leProp...\n    }\n    assert (claim2 : f lfp =< lfp).\n    { eapply lfp_isInfimumOfPrefixedPoints. ii; desnw. transitivity (f x); trivial.\n      eapply f_isMonotonicMap, lfp_isInfimumOfPrefixedPoints...\n    }\n    assert (claim3 : lfp =< f lfp).\n    { eapply lfp_isInfimumOfPrefixedPoints... eapply f_isMonotonicMap... }\n    split... eapply leProp_Antisymmetric...\n  Qed.\n\n  Lemma theGreatestFixedPointOfMonotonicMap (f : D -> D) (gfp : D)\n    (f_isMonotonicMap : isMonotonicMap f)\n    (gfp_isSupremumOfPostfixedPoints : isSupremumOf gfp (PostfixedPoints f))\n    : isGreatestFixedPointOf gfp f.\n  Proof with eauto with *.\n    assert (claim1 : gfp =< f gfp).\n    { eapply gfp_isSupremumOfPostfixedPoints... ii; desnw. transitivity (f x); trivial.\n      eapply f_isMonotonicMap, gfp_isSupremumOfPostfixedPoints...\n    }\n    assert (claim2 : f gfp =< gfp).\n    { eapply gfp_isSupremumOfPostfixedPoints... eapply f_isMonotonicMap... }\n    split.\n    - eapply leProp_Antisymmetric...\n    - intros fix_f H_in. desnw.\n      eapply gfp_isSupremumOfPostfixedPoints...\n      eapply eqProp_implies_leProp...\n  Qed.\n\n  Definition isSupremumIn (sup : D) (X : ensemble D) (phi : D -> Prop) : Prop :=\n    ⟪ IN_SUBSET : phi sup ⟫ /\\ ⟪ SUPREMUM_OF_SUBSET : forall upper_bound : @sig D phi, << SUPREMUM_LE_UPPER_BOUND : sup =< (proj1_sig upper_bound) >> <-> << UPPER_BOUND : member (proj1_sig upper_bound) (UpperBoundsOf X) >> ⟫\n  .\n\n  Theorem isSupremumIn_iff (phi : D -> Prop) (sup_X : @sig D phi) (X : ensemble (@sig D phi))\n    : isSupremumIn (proj1_sig sup_X) (image (@proj1_sig D phi) X) phi <-> isSupremumOf sup_X X.\n  Proof with eauto with *.\n    split.\n    { intros [? ?] z; desnw; split.\n      - ii; desnw. eapply SUPREMUM_OF_SUBSET... eapply in_image_iff...\n      - ii; desnw. eapply SUPREMUM_OF_SUBSET.\n        intros x H_in_image. unnw. eapply in_image_iff in H_in_image.\n        destruct H_in_image as [[x' phi_x] [x_eq x_in]]. simpl in x_eq; subst x'.\n        change (@exist D phi x phi_x =< z)...\n    }\n    { intros sup_X_isSupremumOf_X. split.\n      - exact (proj2_sig sup_X).\n      - split; ii; desnw.\n        + eapply in_image_iff in H_IN. destruct H_IN as [[x' phi_x] [x_eq x_in]].\n          simpl in x_eq; subst x'. rewrite <- SUPREMUM_LE_UPPER_BOUND.\n          change (@exist D phi x phi_x =< sup_X). eapply sup_X_isSupremumOf_X...\n        + change (sup_X =< upper_bound). eapply sup_X_isSupremumOf_X.\n          intros x x_in. change (proj1_sig x =< proj1_sig upper_bound).\n          eapply UPPER_BOUND, in_image_iff...\n    }\n  Qed.\n\n  End BASIC_FACTS_ON_SUPREMUM.\n\n  Global Hint Resolve Supremum_monotonic_wrtEnsembles Supremum_unique Supremum_congruence Supremum_compatWith_eqProp_wrtEnsembles : poset_hints.\n\n  Class isDecidableTotalOrder (A : Type) {requiresPoset : isPoset A} : Type :=\n    { compare (lhs : A) (rhs : A) : comparison\n    ; compare_LT_implies (lhs : A) (rhs : A) (H_lt : compare lhs rhs = Lt) : lhs =< rhs /\\ ~ lhs == rhs\n    ; compare_EQ_implies (lhs : A) (rhs : A) (H_eq : compare lhs rhs = Eq) : lhs == rhs\n    ; compare_GT_implies (lhs : A) (rhs : A) (H_gt : compare lhs rhs = Gt) : rhs =< lhs /\\ ~ lhs == rhs\n    }\n  .\n\n  Local Hint Resolve compare_LT_implies compare_EQ_implies compare_GT_implies : poset_hints.\n\n  Section LEXICOGRAPHICAL_ORDER.\n\n  Context {A : Type} {requiresPoset : isPoset A} {requiresDecidableTotalOrder : isDecidableTotalOrder A (requiresPoset := requiresPoset)}.\n\n  Fixpoint lex_compare (xs : list A) (ys : list A) {struct xs} : comparison :=\n    match xs, ys with\n    | [], [] => Eq\n    | [], y :: ys => Lt\n    | x :: xs, [] => Gt\n    | x :: xs, y :: ys =>\n      match compare x y with\n      | Lt => Lt\n      | Eq => lex_compare xs ys\n      | Gt => Gt\n      end\n    end\n  .\n\n  Definition lex_eq (lhs : list A) (rhs : list A) : Prop := lex_compare lhs rhs = Eq.\n\n  Definition lex_le (lhs : list A) (rhs : list A) : Prop := lex_compare lhs rhs = Lt \\/ lex_compare lhs rhs = Eq.\n\n  Lemma compare_spec (lhs : A) (rhs : A) :\n    match compare lhs rhs with\n    | Lt => lhs =< rhs /\\ ~ lhs == rhs\n    | Eq => lhs == rhs\n    | Gt => rhs =< lhs /\\ ~ lhs == rhs\n    end.\n  Proof. destruct (compare lhs rhs) eqn: H_compare_result; eauto with *. Qed.\n\n  Local Instance lex_eq_Equivalence\n    : Equivalence lex_eq.\n  Proof with discriminate || eauto with *.\n    unfold lex_eq. split.\n    - intros xs1; induction xs1 as [ | x1 xs1 IH]; simpl...\n      pose proof (claim1 := compare_spec x1 x1).\n      destruct (compare x1 x1) eqn: H_compare_result1...\n      all: contradiction (proj2 claim1)...\n    - intros xs1 xs2; revert xs1 xs2; induction xs1 as [ | x1 xs1 IH]; destruct xs2 as [ | x2 xs2]; simpl...\n      pose proof (claim1 := compare_spec x1 x2); pose proof (claim2 := compare_spec x2 x1).\n      destruct (compare x1 x2) eqn: H_compare_result1; destruct (compare x2 x1) eqn: H_compare_result2...\n      all: contradiction (proj2 claim2)...\n    - intros xs1 xs2 xs3; revert xs1 xs3; induction xs2 as [ | x2 xs2 IH]; destruct xs1 as [ | x1 xs1]; destruct xs3 as [ | x3 xs3]; simpl...\n      pose proof (claim1 := compare_spec x1 x2); pose proof (claim2 := compare_spec x2 x3); pose proof (claim3 := compare_spec x1 x3).\n      destruct (compare x1 x2) eqn: H_compare_result1; destruct (compare x2 x3) eqn: H_compare_result2; destruct (compare x1 x3) eqn: H_compare_result3...\n      all: contradiction (proj2 claim3)...\n  Qed.\n\n  Local Instance listPointwiseEquivalence : isSetoid (list A) :=\n    { eqProp := lex_eq\n    ; eqProp_Equivalence := lex_eq_Equivalence\n    }\n  .\n\n  Local Instance lex_le_PreOrder\n    : PreOrder lex_le.\n  Proof with discriminate || eauto with *.\n    assert (lemma1 : forall x1 : A, forall x2 : A, x1 =< x2 -> x2 =< x1 -> x1 == x2). { ii... }\n    assert (lemma2 : forall x1 : A, forall x2 : A, x1 == x2 -> x1 =< x2). { ii... }\n    assert (lemma3 : forall x1 : A, forall x2 : A, x1 == x2 -> x2 =< x1). { ii... }\n    unfold lex_le. split.\n    - intros xs1; right. eapply lex_eq_Equivalence.\n    - intros xs1 xs2 xs3; revert xs1 xs3; induction xs2 as [ | x2 xs2 IH]; destruct xs1 as [ | x1 xs1]; destruct xs3 as [ | x3 xs3]; simpl...\n      intros [H_false | H_false]...\n      pose proof (claim1 := compare_spec x1 x2); pose proof (claim2 := compare_spec x2 x3); pose proof (claim3 := compare_spec x1 x3); pose proof (claim4 := IH xs1 xs3).\n      destruct (compare x1 x2) eqn: H_compare_result1; destruct (compare x2 x3) eqn: H_compare_result2; destruct (compare x1 x3) eqn: H_compare_result3...\n      + contradiction (proj2 claim3)...\n      + contradiction (proj2 claim2)...\n      + contradiction (proj2 claim3); eapply lemma1; [transitivity x2 | exact (proj1 claim3)]. eapply lemma2... exact (proj1 claim2).\n      + contradiction (proj2 claim2)...\n      + contradiction (proj2 claim1)...\n      + contradiction (proj2 claim3); eapply lemma1; [transitivity x2 | exact (proj1 claim3)]. exact (proj1 claim1). eapply lemma2...\n      + contradiction (proj2 claim1); eapply lemma1; [exact (proj1 claim1) | transitivity x3]. exact (proj1 claim2). eapply lemma2...\n      + contradiction (proj2 claim1); eapply lemma1; [exact (proj1 claim1) | transitivity x3]. exact (proj1 claim2). exact (proj1 claim3).\n      + intros ? [? | ?]...\n      + intros [? | ?]...\n      + intros [? | ?]...\n      + intros [? | ?]...\n  Qed.\n\n  Lemma lex_le_flip_spec (lhs : list A) (rhs : list A) :\n    match lex_compare lhs rhs with\n    | Lt => lex_compare rhs lhs = Gt\n    | Eq => lex_compare rhs lhs = Eq\n    | Gt => lex_compare rhs lhs = Lt\n    end.\n  Proof with discriminate || eauto with *.\n    revert lhs rhs.\n    assert (lemma1 : forall x1 : A, forall x2 : A, x1 =< x2 -> x2 =< x1 -> x1 == x2). { ii... }\n    assert (lemma2 : forall x1 : A, forall x2 : A, x1 == x2 -> x1 =< x2). { ii... }\n    assert (lemma3 : forall x1 : A, forall x2 : A, x1 == x2 -> x2 =< x1). { ii... }\n    assert (lemma4 : forall xs1 : list A, forall xs2 : list A, lex_compare xs1 xs2 = Lt <-> lex_compare xs2 xs1 = Gt).\n    { induction xs1 as [ | x1 xs1 IH]; destruct xs2 as [ | x2 xs2]; simpl... split...\n      pose proof (claim1 := compare_spec x1 x2); pose proof (claim2 := compare_spec x2 x1); pose proof (claim3 := IH xs2).\n      destruct (compare x1 x2) eqn: H_compare_result1; destruct (compare x2 x1) eqn: H_compare_result2...\n      - contradiction (proj2 claim2)...\n      - contradiction (proj2 claim2)...\n      - contradiction (proj2 claim1)...\n      - contradiction (proj2 claim1). eapply lemma1; [exact (proj1 claim1) | exact (proj1 claim2)].\n      - contradiction (proj2 claim1)...\n      - contradiction (proj2 claim1). eapply lemma1; [exact (proj1 claim2) | exact (proj1 claim1)].\n    }\n    assert (lemma5 : forall xs1 : list A, forall xs2 : list A, lex_compare xs1 xs2 = Eq <-> lex_compare xs2 xs1 = Eq).\n    { induction xs1 as [ | x1 xs1 IH]; destruct xs2 as [ | x2 xs2]; simpl... split... split...\n      pose proof (claim1 := compare_spec x1 x2); pose proof (claim2 := compare_spec x2 x1); pose proof (claim3 := IH xs2).\n      destruct (compare x1 x2) eqn: H_compare_result1; destruct (compare x2 x1) eqn: H_compare_result2...\n      - contradiction (proj2 claim2)...\n      - contradiction (proj2 claim2)...\n      - contradiction (proj2 claim1)...\n      - split...\n      - contradiction (proj2 claim1)...\n      - split...\n    }\n    assert (lemma6 : forall xs1 : list A, forall xs2 : list A, lex_compare xs1 xs2 = Gt <-> lex_compare xs2 xs1 = Lt) by firstorder.\n    intros lhs rhs; destruct (lex_compare lhs rhs) eqn: H_compare_result; now firstorder.\n  Qed.\n\n  Corollary lex_le_flip_iff (lhs : list A) (rhs : list A) (compare_result : comparison) :\n    lex_compare lhs rhs = compare_result <->\n    match compare_result with\n    | Lt => lex_compare rhs lhs = Gt\n    | Eq => lex_compare rhs lhs = Eq\n    | Gt => lex_compare rhs lhs = Lt\n    end.\n  Proof.\n    split.\n    - ii; subst compare_result. exact (lex_le_flip_spec lhs rhs).\n    - pose proof (lex_le_flip_spec rhs lhs) as claim1. intros H_eq.\n      destruct compare_result eqn: H_compare_result; now rewrite H_eq in claim1.\n  Qed.\n\n  Local Instance lex_le_PartialOrder\n    : PartialOrder lex_eq lex_le.\n  Proof with discriminate || eauto with *.\n    intros xs1 xs2; cbn. unfold flip, lex_eq, lex_le.\n    pose proof (claim1 := lex_le_flip_spec xs1 xs2).\n    destruct (lex_compare xs1 xs2) eqn: H_compare_result.\n    - split...\n    - split... intros [? [H_false | H_false]].\n      all: rewrite H_false in claim1...\n    - split... intros [[? | ?] ?]...\n  Qed.\n\n  Local Instance listLexicographicalOrder : isPoset (list A) :=\n    { leProp := lex_le\n    ; Poset_requiresSetoid := listPointwiseEquivalence\n    ; leProp_PreOrder := lex_le_PreOrder\n    ; leProp_PartialOrder := lex_le_PartialOrder\n    }\n  .\n\n  Local Obligation Tactic := cbn; unfold lex_le, lex_eq; ii.\n  Global Program Instance listLexicographicalOrder_liftsDecidableTotalOrder : isDecidableTotalOrder (list A) := { compare := lex_compare }.\n  Next Obligation. rewrite H_lt. split; [now left | congruence]. Qed.\n  Next Obligation. exact (H_eq). Qed.\n  Next Obligation. exploit (lex_le_flip_spec lhs rhs). rewrite H_gt. intros H_lt. rewrite H_lt. split; [now left | congruence]. Qed.\n\n  End LEXICOGRAPHICAL_ORDER.\n\n  Section NAT_TOSET.\n\n  Local Instance nat_isPoset : isPoset nat :=\n    { leProp := le\n    ; Poset_requiresSetoid := theFinestSetoidOf nat\n    ; leProp_PreOrder := Nat.le_preorder\n    ; leProp_PartialOrder := Nat.le_partialorder\n    }\n  .\n\n  Fixpoint nat_compare (x : nat) (y : nat) {struct x} : comparison :=\n    match x, y with\n    | O, O => Eq\n    | O, S y' => Lt\n    | S x', O => Gt\n    | S x', S y' => nat_compare x' y'\n    end\n  .\n\n  Lemma nat_compare_lt (x : nat) (y : nat)\n    (hyp_lt : nat_compare x y = Lt)\n    : x <= y /\\ x <> y.\n  Proof with eauto with *.\n    revert x y hyp_lt. induction x as [ | x IH], y as [ | y]; simpl; ii.\n    - inversion hyp_lt.\n    - split.\n      { eapply le_intro_0_le_n. }\n      { ii; eapply not_S_n_eq_0... }\n    - inversion hyp_lt.\n    - pose proof (IH y hyp_lt) as [x_le_y x_ne_y]. split.\n      { eapply le_intro_S_n_le_S_m... }\n      { ii. eapply x_ne_y, suc_n_eq_suc_m_elim... }\n  Qed.\n\n  Lemma nat_compare_eq (x : nat) (y : nat)\n    (hyp_lt : nat_compare x y = Eq)\n    : x = y.\n  Proof with eauto with *.\n    revert x y hyp_lt. induction x as [ | x IH], y as [ | y]; simpl; ii.\n    - reflexivity.\n    - inversion hyp_lt.\n    - inversion hyp_lt.\n    - pose proof (IH y hyp_lt) as x_eq_y.\n      exact (eq_congruence suc x y x_eq_y).\n  Qed.\n\n  Lemma nat_compare_gt (x : nat) (y : nat)\n    (hyp_lt : nat_compare x y = Gt)\n    : y <= x /\\ x <> y.\n  Proof with eauto with *.\n    cbn. revert x y hyp_lt. induction x as [ | x IH], y as [ | y]; simpl; ii.\n    - inversion hyp_lt.\n    - inversion hyp_lt.\n    - split.\n      { eapply le_intro_0_le_n. }\n      { ii; eapply not_S_n_eq_0... }\n    - pose proof (IH y hyp_lt) as [y_le_x x_ne_y]. split.\n      { eapply le_intro_S_n_le_S_m... }\n      { ii. eapply x_ne_y, suc_n_eq_suc_m_elim... }\n  Qed.\n\n  Local Instance nat_hasDecidableTotalOrder : isDecidableTotalOrder nat (requiresPoset := nat_isPoset) :=\n    { compare := nat_compare\n    ; compare_LT_implies := nat_compare_lt\n    ; compare_EQ_implies := nat_compare_eq\n    ; compare_GT_implies := nat_compare_gt\n    }\n  .\n\n  End NAT_TOSET.\n\nEnd BasicPosetTheory.\n\nModule DomainTheoryHelper.\n\n  Import ListNotations BasicPosetTheory.\n\n  Global Reserved Notation \" '⟬' X '⟶' Y '⟭' \" (X at level 60, Y at level 60, at level 0, no associativity).\n\n  Class isCoLa (D : Type) {requiresPoset : isPoset D} : Type := getSupremumOf_inCoLa (X : ensemble D) : {sup_X : D | isSupremumOf sup_X X}.\n\n  Global Hint Constructors image finite : poset_hints.\n\n  Definition isDirectedOrEmpty {D : Type} {requiresPoset : isPoset D} (X : ensemble D) : Prop :=\n    forall x1 : D, << H_IN1 : member x1 X >> ->\n    forall x2 : D, << H_IN2 : member x2 X >> ->\n    exists x3 : D, << H_IN3 : member x3 X >> /\\\n    << UPPER_BOUND : x1 =< x3 /\\ x2 =< x3 >>\n  .\n\n  Definition isDirected {D : Type} {requiresPoset : isPoset D} (X : ensemble D) : Prop :=\n    << NONEMPTY : exists x0 : D, member x0 X >> /\\ << DIRECTED_OR_EMPTY : isDirectedOrEmpty X >>\n  .\n\n  Lemma isDirected_iff {D : Type} {requiresPoset : isPoset D} (X : ensemble D)\n    : isDirected X <-> << DIRECTED : forall xs : list D, forall xs_isFiniteSubsetOf : isFiniteSubsetOf xs X, exists y : D, << H_IN : y \\in X >> /\\ << UPPER_BOUND : forall x : D, In x xs -> x =< y >> >>.\n  Proof with eauto with *.\n    split; intros DIRECTED.\n    - ii. destruct DIRECTED; desnw. induction xs as [ | x xs IH].\n      + exists (x0). split... intros z [].\n      + assert (xs_isFiniteSubsetOf' : isFiniteSubsetOf xs X).\n        { ii. eapply xs_isFiniteSubsetOf. right... }\n        pose proof (IH xs_isFiniteSubsetOf') as [y' ?]; desnw.\n        assert (x_in_X : x \\in X).\n        { eapply xs_isFiniteSubsetOf. left... }\n        pose proof (DIRECTED_OR_EMPTY x x_in_X y' H_IN) as [y [? [? ?]]].\n        exists (y). split... intros x1 [x1_eq_x | x1_in_xs].\n        { subst x1... }\n        { transitivity (y')... }\n    - unnw. split.\n      + assert (xs_isFiniteSubsetOf : isFiniteSubsetOf [] X).\n        { intros z []. }\n        pose proof (DIRECTED [] xs_isFiniteSubsetOf) as [x0 ?]; desnw.\n        exists (x0)...\n      + ii. set (xs := [x1; x2]).\n        assert (xs_isFiniteSubsetOf : isFiniteSubsetOf xs X).\n        { intros z [z_eq_x1 | [z_eq_x2 | []]]; subst z... }\n        pose proof (DIRECTED xs xs_isFiniteSubsetOf) as [y [H_IN UPPER_BOUND]].\n        exists (y). split... split; eapply UPPER_BOUND; [left | right; left]...\n  Qed.\n\n  Class isCPO (D : Type) {requiresPoset : isPoset D} : Type :=\n    { getBottom_inCPO : D\n    ; getSupremumOf_inCPO (X : ensemble D) (X_isDirected : isDirected X) : D\n    ; getBottom_inCPO_isBottom : forall x : D, getBottom_inCPO =< x\n    ; getSupremumOf_inCPO_isSupremum (X : ensemble D) (X_isDirected : isDirected X) : isSupremumOf (getSupremumOf_inCPO X X_isDirected) X\n    }\n  .\n\n  Lemma preservesDirected_if_isMonotonicMap {dom : Type} {cod : Type} {dom_requiresPoset : isPoset dom} {cod_requiresPoset : isPoset cod} (f : dom -> cod)\n    (f_isMonotonicMap : isMonotonicMap f)\n    : forall X : ensemble dom, << DIRECTED : isDirected X >> -> isDirected (image f X).\n  Proof.\n    ii; desnw. destruct DIRECTED; desnw. split; unnw.\n    - exists (f x0). econstructor; eauto.\n    - intros y1 ? y2 ?; desnw. apply in_image_iff in H_IN1, H_IN2.\n      destruct H_IN1 as [x1 [y1_eq x1_in]]; destruct H_IN2 as [x2 [y2_eq x2_in]]; subst y1 y2.\n      pose proof (DIRECTED_OR_EMPTY x1 x1_in x2 x2_in) as [x3 [x3_in [x1_le_x3 x2_le_x3]]]; unnw.\n      exists (f x3). rewrite in_image_iff. split; eauto with *.\n  Qed.\n\nEnd DomainTheoryHelper.\n", "meta": {"author": "KiJeong-Lim", "repo": "DschingisKhan", "sha": "b2d663f5c705f9732d44adc2faf49709b6ddec07", "save_path": "github-repos/coq/KiJeong-Lim-DschingisKhan", "path": "github-repos/coq/KiJeong-Lim-DschingisKhan/DschingisKhan-b2d663f5c705f9732d44adc2faf49709b6ddec07/theories/Math/BasicPosetTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7167090111210198}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := mult lf2 (plus Zero x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj245_coqofml_XiRgnv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.716667765715075}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  mult (Succ x) (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj201_coqofml_8BPUtn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7166677545126822}}
{"text": "Inductive Node : Type := \n| null\n| node (x:nat) (ls rs :Node).\n\nInductive cmpType :=\n|less\n|greater\n|equal.\n\nFixpoint cmp x y : cmpType := \nmatch x,y with\n|0,0 => equal\n|S n, 0 => greater\n|0, S n => less\n|S x, S y => cmp x y\nend.\n\nDefinition Greater ( x y : nat) : bool :=\n  match ( cmp x y ) with\n  | greater => true\n  | _ => false\n  end.\n\nDefinition Less ( x y : nat) : bool :=\n  match ( cmp x y ) with\n  | less => true\n  | _ => false\n  end.\n\nNotation \" x <? y\" := (Less x y ) ( at level 50 , left associativity).\nNotation \" x >? y\" := (Greater x y ) ( at level 50 , left associativity).\n\nFixpoint insert (rt : Node) (val : nat) : Node := \n  match rt with\n  | null => node val null null\n  | node x ls rs => \n      match cmp val x with\n      |equal => rt\n      |less  => node x (insert ls val) rs\n      |greater => node x ls (insert rs val)\n      end\n  end.\n\nNotation \"x <- y\" := (insert x y) (at level 50 , left associativity).\n\nFixpoint Count (rt : Node) (val : nat ) : bool :=\n  match rt with\n  |null => false\n  |node x ls rs => \n      match cmp val x with\n      |equal => true\n      |less  => Count ls val\n      |greater => Count rs val\n     end\n end.\n\nDefinition LL_Rotate (rt : Node) : Node :=\n match rt with\n|null => null\n|node gf (node f fl fr) gfr => node f fl (node gf fr gfr)  \n|_ => rt\nend.\n\nDefinition RR_Rotate (rt : Node) : Node :=\n match rt with\n|null => null\n|node gf gfl (node f fl fr)  => node f (node gf  gfl fl)  fr\n|_ => rt\nend.\n\nDefinition Max (x y : nat) : nat :=\n  match cmp x y with\n  |greater => x\n  |_ => y\n  end.\n\n\nFixpoint Depth (rt:Node) : nat := \n  match rt with\n  |null => 0\n  |node x ls rs => 1 + max (Depth ls) (Depth rs)\nend.\n\nDefinition t1 := null<-2<-1<-3<-4<-5.\n\nFixpoint Dif (x y : nat) : nat :=\n  match x,y with\n  |0,_ => y\n  |_,0 => x\n  |S x', S y' => Dif x' y'\n  end.\n\nDefinition LR_Rotate (rt:Node) : Node :=\n  match rt with\n  | null => null\n  | node x ls rs => \n      match ls with\n      |null => rt\n      |_    => LL_Rotate ( node x (RR_Rotate ls) rs )\n     end\nend.\n\nDefinition RL_Rotate (rt:Node) :Node :=\n  match rt with\n  | null => null\n  | node x ls rs => \n      match rs with\n      |null => rt\n      |_    => RR_Rotate ( node x ls (LL_Rotate rs) )\n     end\nend.\n\nInductive dir : Type :=\n|left\n|right.\n\nDefinition getVal(rt : Node) : nat :=\n  match rt with\n  | null => 0\n  |node x y z => x\n  end.\n\n\nDefinition Balance (rt : Node) (val : nat) (d :dir) : Node :=\n  match rt with\n  |null => null\n  |node x ls rs =>\n    match (Dif (Depth ls) (Depth rs)) , d with\n    |0,_ => rt\n    |1,_ => rt\n    |_,left => if ( val >? (getVal ls) ) then LL_Rotate rt\n               else LR_Rotate rt\n    |_,right => if( val <? (getVal rs) ) then RR_Rotate rt\n               else RL_Rotate rt\n    end\n end.\n\nFixpoint AVL_insert (rt : Node) (val : nat) : Node := \n  match rt with\n  | null => node val null null\n  | node x ls rs => \n      match cmp val x with\n      |equal => rt\n      |less  => Balance ( node x (AVL_insert ls val) rs ) val left  \n      |greater => Balance ( node x ls (AVL_insert rs val) ) val right \n      end\n  end.\n\nNotation \"x <. y\" := (AVL_insert x y) ( at level 50 , left associativity).\n\n\n\n\n\n\n", "meta": {"author": "477972324wlx", "repo": "Coq", "sha": "1dacd108df9995ff7f6194148e47fb7821e90b17", "save_path": "github-repos/coq/477972324wlx-Coq", "path": "github-repos/coq/477972324wlx-Coq/Coq-1dacd108df9995ff7f6194148e47fb7821e90b17/AVLTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7166677544890494}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) (lf1 : natural) : natural :=\n  mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj22_coqofml_uwdvzC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7166677465042206}}
{"text": "\n\n\n\n(* This file contains some important results on lists of elements from an ordered type. \n   Following are some important notions formalized in this file----------------------\n          \n IsOrd l           <==> l is an strictly increasing list\n isOrd l           ==> boolean function to check if the list is strictly increasing\n\n\n Some of the useful results in this file are:\n\n Lemma IsOrd_NoDup (l: list A): IsOrd l -> NoDup l.\n Lemma isOrdP (l:list A): reflect(IsOrd l)(isOrd l).\n \n Lemma head_equal (a b: A)(l s: list A): \n            IsOrd (a::l)-> IsOrd (b::s)-> Equal (a::l) (b::s)-> a=b.\n Lemma tail_equal (a b: A)(l s:list A):\n            IsOrd (a::l)->IsOrd (b::s)->Equal (a::l)(b::s)-> Equal l s.\n Lemma set_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> l=s.\n Lemma length_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> |l|=|s|. \n                                                                             ------- *)\n\n\nRequire Export Lists.List.\nRequire Export GenReflect SetSpecs OrdType.\nRequire Export DecList.\n\nSet Implicit Arguments.\n\nSection OrderedLists.\n  Context {A: ordType}. \n  (* Variable A: ordType.  *)\n\n  Lemma decA (x y:A): {x=y}+{x<>y}.\n  Proof. eapply reflect_dec with (b:= eqb x y). apply eqP. Qed.\n  \n  Lemma EM_A (x y: A): x=y \\/ x<>y.\n  Proof. eapply reflect_EM with (b:= eqb x y). apply eqP. Qed.\n   \n  (* ------------IsOrd Predicate  -----------------------------------------------  *)\n  Inductive IsOrd :list A -> Prop:=\n  |  IsOrd_nil: IsOrd nil\n  | IsOrd_singl: forall x:A, IsOrd (x::nil)\n  | IsOrd_cons: forall (x y: A)(l: list A), (ltb x y)-> IsOrd (y::l) -> IsOrd (x::y::l).\n\n  Lemma IsOrd_elim (l: list A)(x y: A): IsOrd (x::y::l)-> IsOrd (y::l).\n  Proof. intro H;inversion H; auto. Qed.\n  Lemma IsOrd_elim1 (l: list A)(x y: A): IsOrd (x::y::l)-> (ltb x y).\n  Proof. intro H;inversion H; auto. Qed.\n  Lemma IsOrd_elim0 (l:list A)(x:A): IsOrd (x::l)-> IsOrd(l).\n  Proof. case l. constructor. intros s l0. apply IsOrd_elim. Qed.\n  \n  Lemma IsOrd_intro (a:A)(l: list A): IsOrd l-> (forall x, In x l -> ltb a x)-> IsOrd (a::l).\n  Proof. intros H H1. case l eqn:H2. constructor. constructor.\n         apply H1. all: auto. Qed.\n  \n  Hint Resolve IsOrd_elim IsOrd_elim1 IsOrd_elim0 IsOrd_intro: core.\n  \n  \n  Lemma IsOrd_elim2(l:list A): forall a:A, IsOrd (a::l)-> (forall x:A, In x l-> ltb a x).\n  Proof. { induction l.\n         { intros a H x H0. inversion H0.  }\n         { intros a0 H x H0.\n           assert (H1: x=a \\/ In x l); auto.\n           destruct H1 as [H1 | H1]. rewrite H1. eapply IsOrd_elim1; exact H.\n           assert (H2: a <b x). apply IHl; eauto.\n           assert (H3 : a0 <b a). eapply IsOrd_elim1;exact H. eauto.   } } Qed.\n  \n   Lemma IsOrd_elim2a(l:list A)(a x:A): IsOrd (a::l)-> In x l -> ltb a x.\n  Proof. { intros H H1. eapply (@IsOrd_elim2 l a) in H. exact H. auto. } Qed. \n      \n  \n  Lemma IsOrd_elim3 (x a: A)(l: list A): IsOrd (a::l)-> ltb x a -> ~ In x (a::l).\n  Proof. { intros H H0 H1.\n         assert (H2: x=a \\/ In x l); eauto.\n         destruct H2. eapply ltb_not_eq; eauto.\n         assert (H3: a <b x). eapply IsOrd_elim2;eauto.  eapply ltb_antisym;eauto. } Qed. \n  \n  Lemma IsOrd_elim4 (a:A)(l: list A): IsOrd (a::l)-> ~ In a l.\n  Proof. { intros H H1. assert (H2: ltb a a). eapply IsOrd_elim2;eauto.\n           absurd (a <b a); auto. } Qed.\n\n  Lemma IsOrd_elim5 (a b:A)(l: list A): IsOrd (a::l)-> In b (a::l)-> (b=a \\/ a <b b).\n    Proof.  { intros H1 H2. cut (b=a \\/ In b l).\n           intro H0; destruct H0 as [Ha | Hb]. left;auto.\n           right; eapply IsOrd_elim2;eauto.  eauto. } Qed.\n\n  Hint Resolve IsOrd_elim2a IsOrd_elim3 IsOrd_elim4 IsOrd_elim5: core.  \n\n  Lemma IsOrd_NoDup (l: list A): IsOrd l -> NoDup l.\n  Proof. { intros. induction l. constructor.\n         constructor. eapply IsOrd_elim4;auto.  eauto. } Qed. \n\n  Fixpoint isOrd (l: list A): bool:=\n    match l with\n    |nil => true\n    |x ::l1=> match l1 with\n             | nil => true\n             | y::l2 => (ltb x y) && (isOrd l1)\n             end\n    end.\n   Lemma isOrd_elim (l: list A)(x y: A): isOrd (x::y::l)-> isOrd (y::l).\n   Proof.  simpl; move /andP; tauto.  Qed.\n   Lemma isOrd_elim1 (l: list A)(x y: A): isOrd (x::y::l)-> (ltb x y).\n   Proof. simpl; move /andP; tauto. Qed.\n   Lemma isOrd_elim0 (l:list A)(x:A): isOrd (x::l)-> isOrd(l).\n   Proof. case l. simpl;auto.  intros s l0. simpl; move /andP; tauto. Qed.\n\n   Hint Resolve isOrd_elim isOrd_elim1 isOrd_elim0: core.\n\n  Lemma isOrdP (l:list A): reflect(IsOrd l)(isOrd l).\n  Proof. { apply reflect_intro. split.\n         { intro H. induction l. \n         { simpl;auto. }\n         { simpl. case l eqn:H1.  auto. apply /andP.\n           split. eapply IsOrd_elim1;exact H. apply IHl. eauto. } }\n         {  intro H. induction l. constructor. case l eqn:H1.\n            constructor. constructor. eapply isOrd_elim1;exact H.\n            apply IHl. eapply isOrd_elim. apply H.  } } Qed.\n\n  Hint Resolve isOrdP: core.\n\n  Lemma NoDup_elim1(a:A)(l:list A): NoDup (a::l) -> ~ In a l.\n  Proof. eapply NoDup_cons_iff. Qed.\n\n  Lemma NoDup_elim2 (a: A)(l: list A): NoDup (a::l) -> NoDup l.\n  Proof. eapply NoDup_cons_iff. Qed.\n\n  Lemma NoDup_intro (a: A)(l: list A): ~ In a l -> NoDup l -> NoDup (a::l).\n  Proof. intros; eapply NoDup_cons_iff;auto. Qed.\n\n  \n  Hint Resolve NoDup_elim1 NoDup_elim2 NoDup_intro: core.\n\n  (* --------------------Equality of Ordered Lists---------------------------------------*)\n\n  Definition empty: list A:= nil.\n  \n  Lemma empty_equal_nil (l: list A): l [=] empty -> l = empty.\n  Proof. { case l. auto. intros s l0. unfold \"[=]\". intro H. \n           destruct H as [H1 H2]. absurd (In s empty). all: eauto. } Qed.\n\n  Lemma head_equal (a b: A)(l s: list A): IsOrd (a::l)-> IsOrd (b::s)-> Equal (a::l) (b::s)-> a = b.\n  Proof. { intros H H1 H2.\n         assert(H3: In b (a::l)).\n         unfold \"[=]\" in H2. apply H2. auto.   \n         assert(H3A: b=a \\/ a <b b).  eapply IsOrd_elim5; eauto. \n         assert(H4: In a (b::s)). unfold \"[=]\" in H2. apply H2. auto. \n         assert(H4A: a = b \\/ b <b a). eapply IsOrd_elim5; eauto. \n         destruct H3A; destruct H4A.\n         auto. symmetry;auto. auto. absurd (b <b a); auto. } Qed.\n         \n\n  Lemma tail_equal (a b: A)(l s:list A):IsOrd (a::l)->IsOrd (b::s)->Equal (a::l)(b::s)-> Equal l s.\n  Proof. { intros H H1 H2. unfold \"[=]\". \n         assert(H0: a = b). eapply head_equal;eauto. subst b.\n         split; intro x.\n         { intro H3. assert (H3A: a <b x).\n           eapply IsOrd_elim2a. exact H. auto. \n           assert (H3B: In x (a::l)). auto.\n           assert (H3C: x=a \\/ In x s).\n           { cut (In x (a::s)). eauto. apply H2;auto. }\n           destruct H3C. absurd (a <b x); eauto. auto. }\n          { intro H3. assert (H3A: a <b x). eapply IsOrd_elim2a. exact H1. auto.  \n           assert (H3B: In x (a::s)). auto.\n           assert (H3C: x=a \\/ In x l).\n           { cut (In x (a::l)). auto.  apply H2;auto. }\n           destruct H3C. absurd (a <b x); auto. auto. } } Qed.\n         \n  Lemma set_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> l=s.\n  Proof. { revert s. induction l; induction s.\n         { auto. }\n         { intros; symmetry; apply empty_equal_nil; unfold empty; auto.  }\n         { intros; apply empty_equal_nil; unfold empty; auto. }\n         { intros H H1 H2. replace a0 with a. replace s with l.\n           auto. apply IHl. eauto. eauto. \n           eapply tail_equal; eauto. eapply head_equal;eauto. } } Qed.  \n  \n  Lemma length_equal (l s: list A): IsOrd l -> IsOrd s -> Equal l s -> |l|=|s|.\n  Proof. intros. replace s with l. auto. eapply set_equal; eauto. Qed.\n\n  Hint Resolve head_equal tail_equal set_equal length_equal: core.\n\n  (*----------Misc property on ordList-------------------------------*)\n  Lemma nodup_Subset_elim(a:A)(l s: list A):\n    NoDup (a::l)-> NoDup (a::s)-> a::l [<=] a::s -> l [<=] s.\n  Proof. { intros H H1 H2 x H3. assert (Hs: In x (a::s)). apply H2; auto.\n         destruct Hs. subst x; absurd (In a l); auto. auto. } Qed.\n\n  Lemma IsOrd_Subset_elim1 (e a: A)(l s: list A):\n    IsOrd (e::l)-> IsOrd (a::s) -> e::l [<=] a::s -> a <=b e.\n  Proof. intros H H1 H2. match_up a e. subst a;auto. auto. absurd (In e (a::s)); auto.  Qed.\n  \n  Lemma IsOrd_Subset_elim2 (e a: A)(l s: list A):\n    IsOrd (e::l)-> IsOrd (a::s) -> e::l [<=] a::s -> e<>a -> e::l [<=] s.\n  Proof. { intros H H1 H2 H3 x Hl.\n         destruct Hl.\n         { subst x. cut (In e (a::s)). intro H4. destruct H4.\n           symmetry in H0. contradiction. auto. auto. }\n         { assert(H4: In x (a::s)). auto. destruct H4. subst x.\n           assert (H4: e <b a).\n           { apply leb_antisym2. exact H3. apply ltb_leb; eapply IsOrd_elim2a.\n             exact H. auto. }\n           assert (H5: a <=b e). eapply IsOrd_Subset_elim1;eauto.\n           by_conflict. auto. } } Qed.\n\n  Lemma idx_IsOrd (l: list A)(x y: A): IsOrd l -> In x l-> In y l-> x <b y -> idx x l < idx y l.\n  Proof. { induction l as [| a l'].\n           { simpl. tauto. }\n           { intros h1 h2 h3 h4.\n             assert (h5: x = a \\/ x <> a). eauto.\n             assert (h6: y = a \\/ y <> a). eauto.\n             destruct h5 as [h5 |h5]; destruct h6 as [h6 |h6].\n             { subst x; subst y. by_conflict. }\n             { assert (h3a: In y l'). eauto.\n               assert (h3b: idx y l' > 0). auto.\n               simpl. replace (x == a) with true.\n               replace (y == a) with false. replace (memb y l') with true.\n               omega. symmetry; apply /membP;auto. all: symmetry;auto. }\n             { assert (h3a: In x l'). eauto.\n               assert (h3b: a <b x). eauto. subst y. by_conflict. }\n             { assert (h2a: In x l'); eauto.\n               assert (h2b: idx x l' > 0); auto.\n               assert (h3a: In y l'); eauto.\n               assert (h3b: idx y l' > 0); auto.\n               simpl. replace (x == a) with false.\n               replace (y == a) with false. replace (memb y l') with true.\n               replace (memb x l') with true.\n               cut (idx x l' < idx y l'). omega. apply IHl';auto. eauto.\n               symmetry; apply /membP;auto. all: symmetry;auto. } } } Qed.\n  \n\nEnd OrderedLists.\n\n\n\nHint Resolve IsOrd_elim IsOrd_elim1 IsOrd_elim0 IsOrd_intro: core.\nHint Resolve IsOrd_elim2a IsOrd_elim3 IsOrd_elim4 IsOrd_elim5: core. \nHint Resolve isOrd_elim isOrd_elim1 isOrd_elim0: core.\nHint Resolve isOrdP: core.\n\nHint Resolve NoDup_elim1 NoDup_elim2 NoDup_intro: core.\nHint Immediate head_equal tail_equal set_equal length_equal: core.\nHint Resolve IsOrd_NoDup: core.\n\nHint Resolve nodup_Subset_elim IsOrd_Subset_elim1 IsOrd_Subset_elim2:core.\n\nHint Resolve idx_IsOrd:core.\n\n\n\n\n           \n\n", "meta": {"author": "Abhishek-TIFR", "repo": "wpgt", "sha": "48c612063cbfbe51d6eed41d244c044e43bf8d67", "save_path": "github-repos/coq/Abhishek-TIFR-wpgt", "path": "github-repos/coq/Abhishek-TIFR-wpgt/wpgt-48c612063cbfbe51d6eed41d244c044e43bf8d67/OrdList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.716651129419742}}
{"text": "(** Exercise 8.1 **)\n\nRequire Import List.\n\nInductive last\n  (A:Type) (a:A) : list A -> Prop :=\n  | last_b : last A a (a :: nil)\n  | last_i : forall (b:A) (l:list A),\n             last A a l -> last A a (b :: l).\n\nImplicit Arguments last [A].\n\nFixpoint last_fun\n  (A:Type) (l:list A): option A :=\n  match l with\n  | nil => None\n  | a :: nil => Some a\n  | a :: tail => last_fun A tail\n  end.\n\nImplicit Arguments last_fun [A].\n\nCompute (last_fun (1 :: 2 :: 3 :: 4 :: nil)).\nCompute (last_fun (1 :: nil)).\nCompute (last_fun (A := nat) nil).\n\nLemma last_ex_1:\n  last 3 (1 :: 2 :: 3 :: nil).\nProof.\n  do 2 apply last_i.\n  apply last_b.\nQed.\n\nLemma last_elem_implies_pos_len:\n  forall (A:Type) (a:A) (l:list A),\n  last a l -> 1 <= length l.\nProof.\n  intros A a l H1.\n  elim H1.\n  simpl; apply le_n.\n  intros b l' H2 H3.\n  simpl.\n  apply le_S; exact H3.\nQed.\n\nRequire Import Arith.\n\nLemma last_ex_2:\n  ~last 4 nil.\nProof.\n  intro H.\n  apply le_Sn_0 with (n := 0).\n  apply last_elem_implies_pos_len\n    with (l := nil) (a := 4).\n  exact H.\nQed.\n\nLemma len_1_list_is_base:\n  forall (A:Type) (a:A) (l:list A),\n  last a l /\\ length l = 1 -> l = a :: nil.\nProof.\n  intros A a b H1.\n  destruct H1 as [H1 H2].\n  destruct H1 as [| b].\n  reflexivity.\n  assert (1 <= length l) as H3.\n  apply last_elem_implies_pos_len\n    with (a := a) (l := l); exact H1.\n  assert (2 <= length(b :: l)) as H4.\n  simpl; apply le_n_S; exact H3.\n  rewrite H2 in H4.\n  assert False.\n  apply le_Sn_n with (n:=1); exact H4.\n  contradiction.\nQed.\n\nLemma only_last_matters:\n  forall (A:Type) (a b c:A) (l:list A),\n  last a (b :: c :: l) -> last a (c :: l).\nProof.\n  intros A a b c l H.\n  inversion H.\n  exact H1.\nQed.\n\nLemma last_ex_3:\n  ~last 4 (1 :: 2 :: 3 :: nil).\nProof.\n  intros H1.\n  assert (last 4 (3 :: nil)) as H2.\n  apply only_last_matters with (b := 2).\n  apply only_last_matters with (b := 1).\n  exact H1.\n  assert (3 :: nil = 4 :: nil) as H3.\n  apply len_1_list_is_base.\n  split.\n  exact H2.\n  simpl; reflexivity.\n  discriminate.\nQed.  \n\nTheorem last_equiv:\n  forall (A:Type) (a:A) (l:list A),\n  last a l <-> last_fun l = Some a.\nProof.\n  intros A a l.\n  split.\n  intros H1.\n  induction l.\n  assert (1 <= 0) as H2.\n  apply last_elem_implies_pos_len\n    with (a := a) (l := nil).\n  exact H1.\n  apply False_ind.\n  apply le_Sn_0 with (n := 0); exact H2.\n  destruct l.\n  assert (a = a0) as H2.\n  assert (a0 :: nil = a :: nil) as H3.\n  apply len_1_list_is_base.\n  split.\n  exact H1.\n  simpl; reflexivity.\n  injection H3.\n  intro H4.\n  rewrite H4; reflexivity.\n  rewrite <-H2.\n  simpl; reflexivity.\n  assert (last a (a1 :: l)) as H2.\n  apply only_last_matters with (b := a0).\n  exact H1.\n  simpl.\n  apply IHl; exact H2.\n  induction l.\n  simpl.\n  intro H1.\n  discriminate.\n  destruct l.\n  simpl.\n  intro H2.\n  assert (a = a0) as H3.\n  injection H2.\n  intro H3.\n  rewrite H3; reflexivity.\n  rewrite <-H3.\n  constructor.\n  intro H1.\n  apply last_i.\n  apply IHl.\n  rewrite <-H1.\n  simpl.\n  reflexivity.\nQed.\n\n(** Exercise 8.2 **)\n\nInductive split_last (A:Type):\n  list A -> list A -> A -> Prop :=\n  | split_last_s: \n      forall a:A, \n      split_last A (a :: nil) nil a\n  | split_last_i:\n      forall (a b:A) (l l':list A),\n      split_last A l l' a ->\n      split_last A (b :: l) (b :: l') a.\n\nImplicit Arguments split_last [A].\n\nLemma sl_ex_1: split_last (3 :: nil) nil 3.\nProof.\n  constructor.\nQed.\n\nLemma sl_ex_2: \n  split_last (3 :: 4 :: nil) (3 :: nil) 4.\nProof.\n  repeat constructor.\nQed.\n\nLemma sl_ex_3: ~split_last nil nil 5.\nProof.\n  intro H.\n  inversion H.\nQed.\n\nLemma sl_ex_4: \n  ~split_last (3 :: 4 :: nil) (3 :: nil) 5.\nProof.\n  intro H.\n  inversion H.\n  inversion H4.\nQed.\n\nLemma sl_ex_5: \n  ~split_last (3 :: 4 :: nil) (2 :: nil) 4.\nProof.\n  intro H.\n  inversion H.\nQed.\n\nInductive palindrome (A:Type): list A -> Prop :=\n  | palindrome_e: palindrome A nil\n  | palindrome_s: \n      forall a:A, palindrome A (a :: nil)\n  | palindrome_i:\n      forall (a:A) (l l':list A),\n      palindrome A l /\\ split_last l' l a ->\n      palindrome A (a :: l').\n\n\nImplicit Arguments palindrome [A].\n\nLemma pal_ex_1: palindrome (A := nat) nil.\nProof.\n  constructor.\nQed.\n\nLemma pal_ex_2: palindrome (3 :: nil).\nProof.\n  constructor.\nQed.\n\nLemma pal_ex_3: palindrome (4 :: 4 :: nil).\nProof.\n  apply palindrome_i \n    with (l' := 4 :: nil) (l := nil).\n  split; repeat constructor.\nQed.\n\nLemma pal_ex_4:\n palindrome (4 :: 6 :: 5 :: 6:: 4 :: nil).\nProof.\n  apply palindrome_i \n    with (l' := 6 :: 5 :: 6:: 4 :: nil)\n         (l := 6 :: 5 :: 6:: nil)\n         (a := 4).\n  split.\n  apply palindrome_i\n    with (l' := 5 :: 6 :: nil) \n         (l := 5 :: nil)\n         (a := 6).\n  split; repeat constructor.\n  repeat constructor.\nQed.\n\nLemma pal_ex_5: ~palindrome (4 :: 3 :: nil).\nProof.\n  intro H.\n  inversion H.\n  destruct H1 as [_ H1].\n  inversion H1.\n  inversion H7.\nQed.\n\nLemma no_split_nil:\n  forall (A:Type) (a:A) (l:list A),\n  ~split_last nil l a.\nProof.\n  intros A a l H.\n  inversion H.\nQed.\n\nLemma no_nil_when_splitting_big_lists:\n  forall (A:Type) (a b c:A) (l:list A),\n  ~split_last (a :: b :: l) nil c.\nProof.\n  intros A a b c l H.\n  inversion H.\nQed.\n\nLemma split_1st_doesnt_matter:\n  forall (A:Type) (a b c:A) (l l':list A),\n  split_last (a :: b :: l) (a :: l') c ->\n  split_last (b :: l) l' c.\nProof.\n  intros A a b c l l' H.\n  inversion H.\n  exact H4.\nQed.\n\nLemma pal_ex_6:\n ~palindrome (4 :: 6 :: 5 :: 7:: 4 :: nil).\nProof.\n  intro H1.\n  inversion H1.\n  clear H H2 a l'.\n  destruct H0 as [H2 H3].\n  inversion H3.\n  inversion H6.\n  inversion H11.\n  inversion H16.\n  rewrite <-H8, <-H13, <-H17 in H0.\n  rewrite <-H0 in H2.\n  clear - H2.\n  inversion H2.\n  destruct H0 as [H3 H4].\n  inversion H4.\n  inversion H8.\n  apply no_split_nil with (l := l'1) (a := 6).\n  assumption.\n  apply no_split_nil with (l := l'2) (a := 4).\n  assumption.\nQed.\n\n(** Exercise 8.3 **)\n\n(* TO BE DONE *)\n\n(** Exercise 8.4 **)\n\nInductive transp_two (A:Type) : \n  list A -> list A -> Prop :=\n  | transp_two_f:\n    forall (a b:A) (l:list A),\n    transp_two A (a :: b :: l) (b :: a :: l)\n  | transp_two_i:\n    forall (a:A) (l l':list A),\n    transp_two A l l' ->\n    transp_two A (a :: l) (a :: l').\n\nImplicit Arguments transp_two [A].\n\nLemma transp_two_ex1:\n  ~transp_two (1 :: 2 :: nil) (1 :: 2 :: nil).\nProof.\n  intro H.\n  inversion H.\n  inversion H1.\n  inversion H5.\nQed.\n\nLemma transp_two_ex2:\n  transp_two (1 :: 2 :: nil) (2 :: 1 :: nil).\nProof.\n  constructor.\nQed.\n\nLemma transp_two_ex3:\n  ~transp_two (1 :: 2 :: 3 :: nil)\n              (3 :: 1 :: 2 :: nil).\nProof.\n  intro H.\n  inversion H.\nQed.\n\nLemma transp_two_ex4:\n  transp_two (1 :: 2 :: 3 :: nil)\n             (1 :: 3 :: 2 :: nil).\nProof.\n  repeat constructor.\nQed.\n\nLemma transp_two_ex5:\n  ~transp_two (5 :: 1 :: 2 :: 3 :: nil)\n              (1 :: 5 :: 3 :: 2 :: nil).\nProof.\n  intro H.\n  inversion H.\nQed.\n\nLemma transp_two_ex6:\n  transp_two (5 :: 1 :: 2 :: 3 :: nil)\n             (1 :: 5 :: 2 :: 3 :: nil).\nProof.\n  repeat constructor.\nQed.\n\nInductive permuted (A:Type) :\n  list A -> list A -> Prop :=\n  | permuted_t:\n    forall (l l':list A),\n    transp_two l l' -> permuted A l l'\n  | permuted_i:\n    forall (l l' l'':list A),\n    permuted A l l' -> permuted A l' l'' ->\n    permuted A l l''.\n\nImplicit Arguments permuted [A].\n\nLemma permuted_ex1:\n  permuted (1 :: 2 :: nil) (1 :: 2 :: nil).\nProof.\n  assert (transp_two (1 :: 2 :: nil)\n                     (2 :: 1 :: nil)) as H1.\n  repeat constructor.\n  assert (transp_two (2 :: 1 :: nil)\n                     (1 :: 2 :: nil)) as H2.\n  repeat constructor.\n  apply permuted_i\n    with (l := (1 :: 2 :: nil))\n         (l' := (2 :: 1 :: nil)).\n  constructor; assumption.\n  constructor; assumption.\nQed.\n\nFixpoint list_count_f\n  (A:Type) (l:list A) (f:A->bool) : nat :=\n  match l with\n  | nil => 0\n  | h :: t =>\n      if (f h)\n      then S (list_count_f A t f)\n      else list_count_f A t f\n  end.\n\nImplicit Arguments list_count_f [A].\n\nLemma transp_two_doesnt_change_f_counts:\n  forall (A:Type) (l l':list A) (f:A->bool),\n  transp_two l l' ->\n  list_count_f l f = list_count_f l' f.\nProof.\n  intros A l l' f H.\n  induction H.\n  simpl.\n  case (f a), (f b); auto.\n  simpl.\n  case (f a); auto.\nQed.\n\nImplicit Arguments\n  transp_two_doesnt_change_f_counts [A].\n\nLemma permuted_doesnt_change_f_counts:\n  forall (A:Type) (l l':list A) (f:A->bool),\n  permuted l l' ->\n  list_count_f l f = list_count_f l' f.\nProof.\n  intros A l l' f H.\n  induction H.\n  apply transp_two_doesnt_change_f_counts;\n    assumption.\n  apply eq_trans\n    with (y := list_count_f l' f);\n    assumption.\nQed.\n\nLemma permuted_ex2:\n  ~permuted (2 :: 2 :: nil) (1 :: 2 :: nil).\nProof.\n  intro H.\n  cut (0 = 1).\n  apply O_S.\n  cut (list_count_f (2 :: 2 :: nil)\n                    (beq_nat 1) =\n       list_count_f (1 :: 2 :: nil)\n                    (beq_nat 1)).\n  simpl; auto.\n  apply permuted_doesnt_change_f_counts; \n    assumption.\nQed.\n\nLemma permuted_ex3:\n  ~permuted (1 :: 2 :: nil) \n            (1 :: 2 :: 3 :: nil).\nProof.\n  intro H.\n  cut (2 = 3).\n  apply n_Sn.\n  cut (list_count_f (1 :: 2 :: nil)\n                    (fun _ => true) =\n       list_count_f (1 :: 2 :: 3 ::nil)\n                    (fun _ => true)).\n  simpl; auto.\n  apply permuted_doesnt_change_f_counts; \n    assumption.\nQed.\n\nLemma permuted_refl:\n  forall (A:Type) (l:list A),\n  length l >= 2 -> permuted l l.\nProof.\n  intros A l H.\n  induction l.\n  inversion H.\n  induction l.\n  inversion H.\n  inversion H1.\n  clear.\n  apply permuted_i \n    with (l' := (a0 :: a :: l)).\n  repeat constructor.\n  repeat constructor.\nQed.\n\nLemma transp_two_symm:\n  forall (A:Type) (l l':list A),\n  transp_two l l' <-> transp_two l' l.\nProof.\n  intros A l l'.\n  split.\n  intros H.\n  induction H.\n  constructor.\n  constructor; assumption.\n  intros H.\n  induction H.\n  constructor.\n  constructor; assumption.\nQed.\n\nLemma permuted_symm:\n  forall (A:Type) (l l':list A),\n  permuted l l' <-> permuted l' l.\nProof.\n  intros A l l'.\n  split.\n  intros H.\n  induction H.\n  constructor.\n  apply transp_two_symm; assumption.\n  apply permuted_i with (l' := l');\n    assumption.\n  intros H.\n  induction H.\n  constructor.\n  apply transp_two_symm; assumption.\n  apply permuted_i with (l' := l');\n    assumption.\nQed.\n\nLemma permuted_trans:\n  forall (A:Type) (l l' l'':list A),\n  permuted l l' -> permuted l' l'' ->\n  permuted l l''.  \nProof.\n  intros A l l' l'' H1 H2.\n  apply permuted_i with (l' := l');\n    assumption.\nQed.\n\n(** Exercise 8.5 **)\n\n(* Given *)\n\nInductive par : Set := open | close.\n\n(* To do *)\n\nInductive wp: list par -> Prop :=\n  | wp_e: wp nil\n  | wp_p: forall l:list par,\n      wp l -> wp (open :: (l ++ (close :: nil)))\n  | wp_c: forall (l l':list par),\n      wp l -> wp l' -> wp (l ++ l').\n\nLemma wp_ex1: wp nil.\nProof.\n  constructor.\nQed.\n\nLemma wp_even_len: \n  forall l:list par, \n  wp l -> exists p:nat, length l = p + p.\nProof.\n  intros l H.\n  induction H.\n  exists 0; auto.\n  destruct IHwp as [p H2].\n  exists (S(p)); simpl.\n  rewrite app_length, H2; simpl.\n  rewrite <-plus_n_Sm, <-plus_n_O.\n  rewrite <-plus_n_Sm; reflexivity.\n  destruct IHwp1 as [p H1].\n  destruct IHwp2 as [p' H2].\n  exists (p + p').\n  rewrite app_length, H1, H2.\n  repeat rewrite plus_assoc.\n  rewrite plus_comm with (n := p + p) (m := p').\n  rewrite plus_comm with (n := p) (m := p').\n  repeat rewrite plus_assoc; reflexivity.\nQed.\n\nLemma wp_ex2: ~wp (open :: nil).\nProof.\n  intros H1.\n  cut (exists p, length (open :: nil) = p + p).\n  simpl.\n  intros [p H2].\n  induction p.\n  discriminate.\n  rewrite <-plus_n_Sm in H2.\n  simpl in H2.\n  assert (0 = S(p + p)) as H3.\n  apply eq_add_S; assumption.\n  discriminate H3.\n  apply wp_even_len; assumption.\nQed.\n\nLemma wp_oc: wp (cons open (cons close nil)).\nProof.\n  apply wp_p with (l := nil); constructor.\nQed.\n\nLemma cons_as_list_cat:\n  forall (A:Type) (a:A) (l:list A),\n  a :: l = (a :: nil) ++ l.\nProof.\n  intros A a l.\n  auto.\nQed.\n\nLemma wp_o_head_c:\n  forall l1 l2:list par,\n  wp l1 -> wp l2 ->\n  wp (cons open (app l1 (cons close l2))).\nProof.\n  intros l1 l2 H1 H2.\n  assert (close :: l2 = (close :: nil) ++ l2)\n    as H3.\n  auto.\n  rewrite H3.\n  rewrite app_assoc; auto.\n  apply wp_c\n    with (l := open :: (l1 ++ close :: nil))\n         (l' := l2).\n  rewrite app_comm_cons.\n  apply wp_p.\n  exact H1.\n  exact H2.\nQed.\n\nLemma wp_o_tail_c:\n  forall (l1 l2:list par),\n  wp l1 -> wp l2 ->\n  wp (app l1 \n          (cons open\n                (app l2 (cons close nil)))).\nProof.\n  intros l1 l2 H1 H2.\n  rewrite app_comm_cons.\n  apply wp_c.\n  exact H1.\n  apply wp_p.\n  exact H2.\nQed.\n\n(** Exercise 8.6 **)\n\n(* Given *)\n\nInductive bin : Set := \n| L : bin\n| N : bin -> bin -> bin.\n\nFixpoint bin_to_string (t:bin) : list par :=\n  match t with\n  | L => nil\n  | N u v =>\n      cons open\n           (app (bin_to_string u)\n                (cons close (bin_to_string v)))\n  end.\n\n(* To do *)\n\nLemma ex_8_6: \n  forall t:bin, wp (bin_to_string t).\nProof.\n  intros t.\n  induction t.\n  simpl; apply wp_e.\n  simpl; apply wp_o_head_c; assumption.\nQed.\n\n(** Exercise 8.7 **)\n\n(* Given *)\n\nFixpoint bin_to_string' (t:bin) : list par :=\n  match t with\n  | L => nil\n  | N u v =>\n      app (bin_to_string' u)\n          (cons open\n                (app (bin_to_string' v)\n                     (cons close nil)))\n  end.\n\n(* To do *)\n\nLemma ex_8_7:\n  forall t:bin, wp (bin_to_string' t).\nProof.\n  intros t.\n  induction t.\n  simpl; apply wp_e.\n  simpl; apply wp_o_tail_c; assumption.\nQed.\n\n(** Exercise 8.8 **)\n\nRequire Import JMeq.\n\nLemma ex_8_8:\n  forall x y z:nat, JMeq (x+(y+z)) ((x+y)+z).\n  intros x y z.\n  rewrite plus_assoc.\n  apply JMeq_refl.\nQed.\n\n(** Exercise 8.9 **)\n\n(* Given *)\n\nInductive even: nat->Prop :=\n  | O_even: even 0\n  | plus_2_even: \n      forall n:nat, even n -> even (S (S n)).\n\n(* To do *)\n\nLemma ex_8_9:\n  forall n:nat, \n  even n -> exists m:nat, n = m + m.\nProof.\n  intros n H.\n  induction H.\n  exists 0; auto.\n  destruct IHeven as [m IH].\n  exists (S m); rewrite <-plus_n_Sm; simpl.\n  repeat apply f_equal; assumption.\nQed.\n\n(** Exercise 8.10 **)\n\nLemma ex_8_10:\n  forall n:nat, even (n + n).\nProof.\n  intros n.\n  induction n.\n  simpl; constructor.\n  rewrite <-plus_n_Sm; simpl.\n  constructor; assumption.\nQed.\n\n(** Exercise 8.11 **)\n\nTheorem lt_le:\n  forall n p:nat, n < p -> n <= p.\nProof.\n  unfold lt.\n  intros n p H.\n  apply le_Sn_le; assumption.\nQed.\n\n(** Exercise 8.12 **)\n\n(* Given *)\n\nDefinition my_le (n p:nat) :=\n  forall P:nat -> Prop,\n  P n -> (forall q:nat, P q -> P (S q)) -> P p.\n\n(* To do *)\n\nLemma le_my_le:\n  forall n p:nat, n <= p -> my_le n p.\nProof.\n  unfold my_le.\n  intros n p H.\n  induction H.\n  intros P H1 H2; exact H1.\n  intros P H1 H2.\n  apply H2, IHle; assumption.\nQed.\n\n(** Exercise 8.13 **)\n\nLemma le_trans':\n  forall n p q:nat, n <= p -> p <= q -> n <= q.\nProof.\n  intros n p q H1 H2.\n  induction H2.\n  assumption.\n  apply le_S; assumption.\nQed.\n\nLemma my_le_trans:\n  forall n p q:nat, \n  my_le n p -> my_le p q -> my_le n q.\nProof.\n  unfold my_le.\n  intros n p q H1 H2.\n  apply H2.\n  assumption.\n  intros r H3 P H5 H6.\n  apply H6, H3; assumption.\nQed.\n\n(** Exercise 8.14 **)\n\n(* Given *)\n\nInductive le_diff (n m:nat) : Prop :=\n  le_d: forall x:nat, x + n = m -> le_diff n m.\n\n(* To do *)\n\nTheorem le_equiv_le_diff:\n  forall n m:nat, n <= m <-> le_diff n m.\nProof.\n  intros n m.\n  split.\n  intros H1.\n  induction H1.\n  apply le_d with (x := 0); auto.\n  destruct IHle as [x H2].\n  apply le_d with (x := S x).\n  simpl; rewrite H2; auto.\n  intros H1.\n  destruct H1 as [x H1].\n  generalize m H1.\n  clear H1 m.\n  induction x.\n  intros m H1.\n  simpl in H1; rewrite H1; apply le_n.\n  intros m H1.\n  assert (m = S (pred m)) as H2.\n  destruct m.\n  simpl in H1; discriminate.\n  simpl; auto.\n  rewrite H2.\n  apply le_S.\n  apply IHx with (m := pred m).\n  apply eq_add_S.\n  rewrite <-H2.\n  rewrite <-plus_Sn_m.\n  exact H1.\nQed.\n\n(** Exercise 8.15 **)\n\n(* Given *)\n\nInductive le': nat -> nat -> Prop :=\n  | le'_0_p: forall p:nat, le' 0 p\n  | le'_Sn_Sp: \n      forall n p:nat, \n      le' n p -> le' (S n) (S p).\n\n(* To do *)\n\nLemma le'_le_equiv:\n  forall n m: nat, le' n m <-> le n m.\nProof.\n  intros n m.\n  split.\n  intros H.\n  induction H.\n  apply le_0_n.\n  apply le_n_S; assumption.\n  intros H1.\n  induction H1.\n  induction n.\n  constructor.\n  constructor; assumption.\n  cut (forall n m p:nat,\n       le' n m -> le' (n + p) (m + p)).\n  intros H2.\n  cut (S m = (S m) - n + n).\n  intros H3.\n  rewrite H3, <-plus_O_n at 1.\n  apply H2; constructor.\n  rewrite plus_comm.\n  apply le_plus_minus, le_S; assumption.\n  intros n' m' p H2.\n  induction p.\n  repeat rewrite <-plus_n_O; exact H2.\n  repeat rewrite <-plus_n_Sm.\n  constructor; exact IHp.\nQed.\n\n(** Exercise 8.16 **)\n\n(* Given *)\n\nInductive sorted (A:Set)(R:A->A->Prop) :\n  list A -> Prop :=\n  | sorted0: sorted A R nil\n  | sorted1: forall x:A, sorted A R (cons x nil)\n  | sorted2:\n      forall (x y:A) (l:list A),\n      R x y ->\n      sorted A R (cons y l) ->\n      sorted A R (cons x (cons y l)).\n\nDefinition sorted' \n  (A:Set)(R:A->A->Prop)(l:list A) :=\n  forall (l1 l2:list A)(n1 n2:A),\n  l = app l1 (cons n1 (cons n2 l2)) -> R n1 n2.\n\n(* To do *)\n\nLemma nil_and_single_are_sorted':\n  forall (A:Set)(R:A->A->Prop),\n  sorted' A R nil /\\ \n  forall a:A, sorted' A R (a :: nil).\nProof.\n  unfold sorted'.\n  intros A R.\n  split.\n  intros l1 l2 n1 n2 H1.\n  destruct l1; simpl in H1; discriminate.\n  intros a l1 l2 n1 n2 H1.\n  destruct l1; simpl in H1; inversion H1.\n  destruct l1; simpl in H1; discriminate.\nQed.\n\nLemma sorted'_extension:\n  forall (A:Set)(R:A->A->Prop)(l:list A)\n         (a b:A),\n   R a b /\\ sorted' A R (b :: l) ->\n   sorted' A R (a :: b :: l).\nProof.\n  unfold sorted'.\n  intros A R l a b [H1 H2].\n  intros l1' l2' n1' n2' H3.\n  destruct l1' as [|a' l1''].\n  simpl in H3.\n  inversion H3.\n  rewrite <-H0, <-H4; auto.\n  rewrite <-app_comm_cons in H3.\n  inversion H3.\n  apply H2 with (l1 := l1'') (l2 := l2'); auto.\nQed.\n\nLemma sorted_equiv:\n  forall (A:Set)(R:A->A->Prop)(l:list A),\n  sorted A R l <-> sorted' A R l.\nProof.\n  intros A R l.\n  split.\n  intros H1.\n  cut (sorted' A R nil /\\\n       forall x:A, sorted' A R (x :: nil)).\n  induction H1; intros H2; try apply H2.\n  cut (sorted' A R (y :: l)).\n  intros H3.\n  apply sorted'_extension; auto.\n  apply IHsorted, H2.\n  apply nil_and_single_are_sorted'.\n  unfold sorted'.\n  intros H1.\n  induction l.\n  constructor.\n  destruct l as [| b l'].\n  constructor.\n  cut (R a b /\\ sorted A R (b :: l')).\n  intros [H2 H3].\n  apply sorted2; auto.\n  split.\n  apply H1 with (l1 := nil) (l2 := l') (n1 := a)\n                (n2 := b).\n  simpl; auto.\n  apply IHl.\n  intros l1' l2' n1' n2' H2.\n  apply H1 with (l1 := a :: l1') (l2 := l2')\n                (n1 := n1') (n2 := n2').\n  rewrite <-app_comm_cons.\n  rewrite H2; auto.\nQed.\n\n(** Exercise 8.17 **)\n\n(* TO BE DONE *)\n\n(** Exercise 8.18 **)\n\nSection weird_induc_proof.\n\n  Variable P: nat -> Prop.\n  Variable f: nat -> nat.\n\n  Hypothesis f_strict_mono:\n    forall n p:nat, lt n p -> lt (f n) (f p).\n  Hypothesis f_0: lt 0 (f 0).\n\n  Hypothesis P0: P 0.\n  Hypothesis P_Sn_n: \n    forall n:nat, P (S n) -> P n.\n  Hypothesis f_P: forall n:nat, P n -> P (f n).\n\n  Lemma sub_le_implies_equal:\n    forall n m:nat, \n    n <= m /\\ m - n = 0 -> n = m.\n  Proof.\n    intros n m [H1 H2].\n    rewrite plus_n_O, <-H2 at 1.\n    rewrite le_plus_minus_r;\n      [reflexivity | assumption].\n  Qed.\n\n  Lemma minus_minus_le:\n    forall n m:nat, n <= m -> n = m - (m - n).\n  Proof.\n    intros n m H1.\n    apply plus_minus.\n    rewrite plus_comm, <-le_plus_minus.\n    reflexivity.\n    assumption.\n  Qed.\n\n  Lemma lt_or_not_lt:\n    forall n m:nat, n < m \\/ ~(n < m).\n  Proof.\n    intros n m.\n    cut (n < m \\/ m <= n).\n    intros [H1 | H2].\n    left; exact H1.\n    right; apply le_not_lt; exact H2.\n    apply or_comm, le_or_lt.\n  Qed.\n\n  Lemma sub_succ_rel:\n    forall n m:nat,\n    S(m - S n) = m - n \\/ m - S n = 0.\n  Proof.\n    intros n m.\n    assert (n < m -> S(m - S n) = m - n) as H1.\n    intros H1.\n    rewrite minus_Sn_m.\n    simpl; reflexivity.\n    apply H1.\n    assert (~(n < m) -> m - S n = 0) as H2.\n    intros H2.\n    apply not_le_minus_0; exact H2.\n    cut ((n < m) \\/ ~(n < m)).\n    intros [H3 | H4].\n    left; apply H1; exact H3.\n    right; apply H2; exact H4.\n    apply lt_or_not_lt.\n  Qed.\n\n  Lemma rev_induc_le:\n    forall n m:nat,\n    (n <= m /\\ P m) -> P n.\n  Proof.\n    intros n m [H1 H2].\n    cut (forall p:nat, P m -> P (m - p)).\n    intros H3.\n    rewrite minus_minus_le with (m := m).\n    apply H3 with (p := m - n); assumption.\n    assumption.\n    induction p.\n    intros H3.\n    rewrite <-minus_n_O; assumption.\n    cut (P(m - p)).\n    intros H3 H4.\n    cut (S(m - S p) = m - p \\/ m - S p = 0).\n    intros [H5 | H6].\n    apply P_Sn_n.\n    rewrite H5; apply H3.\n    rewrite H6; apply P0.\n    apply sub_succ_rel.\n    apply IHp; apply H2.\n  Qed.\n\n  Lemma f_is_bigger:\n    forall p:nat, p < f p.\n  Proof.\n    induction p.\n    exact f_0.\n    cut (S p <= f p /\\ f p < f (S p)).\n    intros [H1 H2].\n    apply le_lt_trans with (m := f p);\n      assumption.\n    split.\n    exact IHp.\n    apply f_strict_mono, lt_n_Sn.\n  Qed.\n\n  Lemma induc_hyp:\n    forall n:nat, P n -> P (S n).\n  Proof.\n    intros n H1.\n    cut (S n <= f n).\n    intros H2.\n    apply rev_induc_le with (m := f n); split.\n    assumption.\n    apply f_P; assumption.\n    apply f_is_bigger.\n  Qed.\n\n  Theorem weird_induc: forall n:nat, P n.\n  Proof.\n    induction n.\n    apply P0.\n    apply induc_hyp; exact IHn.\n  Qed.\n\nEnd weird_induc_proof.\n\n(** Exercise 8.19 **)\n\nInductive wp': list par -> Prop :=\n  | wp'_nil: wp' nil\n  | wp'_cons: \n      forall (l1 l2:list par),\n      wp' l1 -> wp' l2 ->\n      wp' (cons open\n                (app l1\n                     (cons close l2))).\n\nLemma wp_has_first_par_comp:\n  forall l: list par, \n  l <> nil -> wp l ->\n  exists l1:list par,\n  exists l2:list par,\n  l = open :: l1 ++ close :: l2 /\\ \n  wp l1 /\\ wp l2.\nProof.\n  intros l H1 H2.\n  induction H2.\n  apply False_ind, H1; reflexivity.\n  exists l.\n  exists nil.\n  split.\n  reflexivity.\n  split.\n  assumption.\n  constructor.\n  induction l.\n  simpl.\n  apply IHwp2.\n  apply H1.\n  assert (exists l1 : list par,\n          exists l2 : list par,\n          a :: l =\n          open :: l1 ++\n          close :: l2 /\\\n          wp l1 /\\\n          wp l2) as H3.\n  apply IHwp1.\n  discriminate.\n  destruct H3 as [l3 [l4 [H3 [H4 H5]]]].\n  assert (wp (l4 ++ l')) as H6.\n  apply wp_c; assumption.\n  exists l3.\n  exists (l4 ++ l').\n  rewrite H3.\n  split.\n  repeat rewrite app_comm_cons.\n  repeat rewrite app_assoc.\n  reflexivity.\n  split; assumption.\nQed.\n\nLemma a_le_sum:\n  forall a b:nat, a <= a + b.\nProof.\n  intros a b.\n  induction b.\n  rewrite <-plus_n_O; apply le_n.\n  rewrite <-plus_n_Sm; apply le_S; exact IHb.\nQed.\n\nLemma sum_le: \n  forall a b c:nat, \n  a + b <= c -> (a <= c) /\\ (b <= c).\nProof.\n  intros a b c H.\n  cut ((a <= a + b) /\\ (b <= a + b)).\n  intros [H1 H2].\n  split;\n    apply le_trans\n      with (m := a + b) (p := c);\n    assumption.\n  split.\n  apply a_le_sum.\n  rewrite plus_comm.\n  apply a_le_sum with (a := b).\nQed.\n\nLemma wp_equiv_wp':\n  forall l:list par, wp l <-> wp' l.\n  cut (forall (n:nat) (l:list par),\n       (length l <= n -> (wp l <-> wp' l))).\n  intros H l.\n  apply H with (n := S (length l)).\n  apply le_S, le_n.\n  intros n.\n  induction n.\n  intros l H.\n  induction l.\n  split; intros; constructor.\n  simpl in H.\n  apply False_ind; \n    apply le_Sn_0 with (n := length l);\n    assumption.\n  intros l H.\n  split.\n  intros H2.\n  induction H2.\n  constructor.\n  apply wp'_cons.\n  apply IHwp.\n  cut (length (open :: l ++ close :: nil) =\n       S(S(length l))).\n  intros H3.\n  do 2 apply le_S_n.\n  rewrite <-H3.\n  do 2 apply le_S.\n  apply H.\n  simpl.\n  rewrite app_length; simpl.\n  rewrite <-plus_n_Sm, <-plus_n_O.\n  do 2 apply f_equal; reflexivity.\n  constructor.\n  cut (l ++ l' = nil \\/\n       (exists l1:list par,\n        exists l2:list par,\n        l ++ l' = open :: l1 ++ close :: l2 /\\ \n        wp l1 /\\ wp l2)).\n  intros [H4 | H3].\n  rewrite H4; constructor.\n  destruct H3 as [l1 [l2 [H3 [H4 H5]]]].\n  rewrite H3.\n  cut (length l1 <= n /\\ length l2 <= n).\n  intros [H6 H7].\n  apply wp'_cons.\n  apply IHn; [exact H6 | exact H4].\n  apply IHn; [exact H7 | exact H5].\n  cut (length(open :: l1 ++ close :: l2) =\n       S(S(length l1 + length l2))).\n  intros H6.\n  rewrite H3, H6 in H.\n  cut (length l1 + length l2 <= n).\n  intros H7.\n  apply sum_le; exact H7.\n  do 2 apply le_S_n.\n  apply le_S; exact H.\n  simpl.\n  apply f_equal.\n  rewrite app_length.\n  simpl.\n  rewrite <-plus_n_Sm.\n  reflexivity.\n  cut ((l ++ l' = nil) \\/ (l ++ l' <> nil)).\n  intros [H3 | H4].\n  left; exact H3.\n  right.\n  apply wp_has_first_par_comp.\n  exact H4.\n  apply wp_c; assumption.\n  case (l ++ l').\n  left; reflexivity.\n  intros p l0.\n  right; discriminate.\n  intros H2.\n  induction H2.\n  constructor.\n  cut ((length l1 <= n) /\\ (length l2 <= n)).\n  intros [H3 H4].\n  cut (open :: l1 ++ close :: l2 =\n       (open :: l1 ++ close :: nil) ++ l2).\n  intros H5.\n  rewrite H5.\n  apply wp_c.\n  apply wp_p.\n  apply IHn; [exact H3 | exact H2_].\n  apply IHn; [exact H4 | exact H2_0].\n  cut (forall (p:par) (l:list par),\n       p :: l = (p :: nil) ++ l).\n  intros H5. \n  rewrite H5 with (p := close) (l := l2).\n  rewrite H5\n    with (p := open) \n         (l := l1 ++ (close :: nil) ++ l2).\n  rewrite H5\n    with (p := open) \n         (l := l1 ++ (close :: nil)).\n  repeat rewrite app_assoc.\n  reflexivity.\n  intros p l; simpl; reflexivity.\n  cut (length (open :: l1 ++ close :: l2) =\n       S(S(length l1 + length l2))).\n  intros H3.\n  apply sum_le.\n  do 2 apply le_S_n.\n  rewrite <-H3.\n  apply le_S; exact H.\n  simpl; apply f_equal.\n  rewrite app_length; simpl.\n  rewrite plus_n_Sm; reflexivity.\nQed.\n\n(* A VERY BIG AND COMPLEX PROOF. IT CAN PROBABLY\n   BE IMPROVED A LOT... *)\n\n(** Exercise 8.20 **)\n\n(* Given *)\n\nInductive wp'': list par -> Prop :=\n  | wp''_nil: wp'' nil\n  | wp''_cons:\n      forall l1 l2:list par,\n      wp'' l1 -> wp'' l2 ->\n      wp'' (app l1\n                (cons open\n                      (app l2\n                           (cons close nil)))).\n\nLemma wp_has_last_par_comp:\n  forall l: list par, \n  l <> nil -> wp l ->\n  exists l1:list par,\n  exists l2:list par,\n  l = l1 ++ open :: l2 ++ close :: nil /\\\n  wp l1 /\\ wp l2.\nProof.\n  intros l H1 H2.\n  induction H2.\n  apply False_ind, H1; reflexivity.\n  exists nil.\n  exists l.\n  split; [auto | split; auto]; apply wp_e.\n  induction l'.\n  rewrite app_nil_r.\n  apply IHwp1.\n  rewrite app_nil_r in H1; exact H1.\n  remember (a :: l') as l''.\n  cut (exists l1:list par,\n       exists l2:list par,\n       (l'' =\n        l1 ++ open :: l2 ++ close :: nil) /\\\n       wp l1 /\\ wp l2).\n  intros [l1 [l2 [H3 [H4 H5]]]].\n  exists (l ++ l1).\n  exists l2.\n  split.\n  rewrite H3.\n  apply app_assoc.\n  split; [apply wp_c; assumption | assumption].\n  apply IHwp2.\n  rewrite Heql''; discriminate.\nQed.\n\nLemma len_le_zero_is_nil:\n  forall l:list par, length l <= 0 <-> l = nil.\nProof.\n  intros l.\n  case l.\n  split; intros;\n    [reflexivity | simpl; apply le_n].\n  simpl; split; intros.\n  apply False_ind; \n    apply le_Sn_O with (n := length l0);\n    assumption.\n  discriminate.\nQed.\n\nLemma cons_lens_equiv:\n  forall l l1 l2:list par,\n  l = l1 ++ (open :: l2) ++ close :: nil ->\n  length l = S(S(length l1 + length l2)).\nProof.\n  intros l l1 l2 H.\n  rewrite H.\n  repeat rewrite app_length; simpl.\n  repeat rewrite <-plus_n_Sm.\n  rewrite <-plus_n_O.\n  reflexivity.\nQed.\n\nLemma comp_len_val:\n  forall l l1 l2 l3:list par,\n  l = l1 ++ (open :: nil) ++ l2 ++\n      (close :: nil) ++ l3 ->\n  length l = \n  S(S(length l1 + length l2 + length l3)).\nProof.\n  intros l l1 l2 l3 H.\n  rewrite H.\n  repeat rewrite app_length; simpl.\n  repeat rewrite <-plus_n_Sm.\n  repeat rewrite plus_assoc.\n  reflexivity.\nQed.\n\nLemma sum_3_le: \n  forall n m p: nat, n <= n + m + p.\nProof.\n  intros n m p.\n  cut (0 <= m + p).\n  intros H.\n  rewrite plus_n_O with (n := n) at 1.\n  rewrite <-plus_assoc.\n  apply plus_le_compat_l; exact H.\n  apply le_O_n.\nQed.\n\nLemma comp_len_ineq:\n  forall l l1 l2 l3:list par,\n  l = l1 ++ (open :: nil) ++ l2 ++\n      (close :: nil) ++ l3 ->\n  length l1 < length l /\\\n  length l2 < length l /\\\n  length l3 < length l.\nProof.\n  intros l l1 l2 l3 H1.\n  cut (length l = \n       S(S(length l1 + length l2 + length l3))).\n  intros H2.\n  rewrite H2; unfold lt.\n  split.\n  apply le_n_S, le_S.\n  apply sum_3_le.\n  split.\n  rewrite plus_comm with (n := length l1).\n  apply le_n_S, le_S.\n  apply sum_3_le.\n  rewrite plus_comm.\n  apply le_n_S, le_S.\n  rewrite plus_assoc.\n  apply sum_3_le.\n  apply comp_len_val; exact H1.\nQed.\n\nLemma le_drop:\n  forall n m p:nat, n + m <= p -> n <= p.\nProof.\n  intros n m p H.\n  induction m.\n  rewrite plus_n_O with (n := n); exact H.\n  apply IHm, le_Sn_le.\n  rewrite plus_n_Sm; exact H.\nQed.\n\nLemma wp_equiv_wp'':\n  forall l:list par, wp l <-> wp'' l.\nProof.\n  (* we need to get a stronger induction\n     hypothesis *)\n  cut (forall (n:nat) (l:list par),\n       (length l <= n -> (wp l <-> wp'' l))).\n  (* first we get the desired result from the\n     induction hypothesis *)\n  intros H l.\n  apply H with (n := length l); apply le_n.\n  intros n.\n  (* then we do the induction *)\n  induction n.\n  (* the nil case is very easy *)\n  intros l H.\n  cut (l = nil).\n  intros.\n  split; intros; rewrite H0; constructor.\n  apply len_le_zero_is_nil; assumption.\n  (* now we need to do the inductive step *)\n  intros l H1.\n  split.\n  intros H2.\n  (* we use structural induction *)\n  induction H2.\n  (* the nil case of wp is trivial *)\n  constructor.\n  (* we handle the single parenthesized\n     expression using a nil prefix *)\n  apply wp''_cons with (l1 := nil).\n  constructor.\n  (* now we just have to find a way to apply\n     the structural recursion *)\n  cut (length l <= S n).\n  exact IHwp.\n  cut (length (open :: l ++ close :: nil) =\n       S(S(length l))).\n  intros H3.\n  do 2 apply le_S_n.\n  rewrite <-H3.\n  do 2 apply le_S.\n  exact H1.\n  (* now it's just a question of relating the\n     list lengths *)\n  rewrite app_comm_cons.\n  rewrite app_length; simpl.\n  rewrite <-plus_n_Sm, <-plus_n_O.\n  reflexivity.\n  (* for the concatenation case, we use the fact\n     that, if l' is not nil, it should have\n     a well-parenthesized expression as a \n     suffix *)\n  (* let's start by disposing of the nil case *)\n  induction l'.\n  rewrite app_nil_r.\n  apply IHwp1.\n  rewrite app_nil_r in H1.\n  exact H1.\n  remember (a :: l') as l''.\n  cut (l'' <> nil).\n  intros H3.\n  (* now we can assume that l'' is not nil *)\n  (* let's start with the fact that it ends with\n     a well-parenthesized expression *)\n  cut (exists l1:list par,\n       exists l2:list par,\n       l'' = l1 ++\n             open :: l2 ++\n             close :: nil /\\\n             wp l1 /\\ wp l2).\n  intros [l1 [l2 [H4 [H5 H6]]]].\n  rewrite H4.\n  rewrite app_assoc.\n  (* now it's ready to apply the constructor *)\n  apply wp''_cons.\n  (* we can only apply the inductive hypothesis\n     over the term lengths here *)\n  cut (length (l ++ l1) <= n).\n  intros H7.\n  apply IHn.\n  exact H7.\n  apply wp_c; assumption.\n  (* now it's boring length inequalities \n     again... *)\n  cut (length (l ++ l1 ++ open :: l2 ++\n               close :: nil) <= S n).\n  intros H7.\n  repeat rewrite app_length in H7.\n  simpl in H7.\n  rewrite app_length; simpl.\n  repeat rewrite <-plus_n_Sm in H7.\n  assert (length l +\n          (length l1 +\n           length (l2 ++ close :: nil)) <= n)\n    as H8.\n  apply le_S_n; exact H7.\n  rewrite plus_assoc in H8.\n  apply le_drop \n    with (m := length (l2 ++ close :: nil)).\n  exact H8.\n  rewrite H4 in H1.\n  exact H1.\n  (* now we need to do the same with the other\n     term *)\n  cut (length l2 <= n).\n  intros H7.\n  apply IHn.\n  exact H7.\n  exact H6.\n  cut (length l'' <= S n).\n  intros H7.\n  cut (length l'' =\n       S(S(length l1 + length l2))).\n  intros H8.\n  rewrite H8 in H7.\n  apply le_drop with (m := length l1).\n  rewrite plus_comm.\n  apply le_Sn_le, le_S_n; exact H7.\n  rewrite H4.\n  rewrite app_comm_cons.\n  repeat rewrite app_length; simpl.\n  repeat rewrite <-plus_n_Sm.\n  rewrite <-plus_n_O; reflexivity.\n  apply le_drop with (m := length l).\n  rewrite plus_comm.\n  rewrite <-app_length; exact H1.\n  apply wp_has_last_par_comp.\n  exact H3.\n  exact H2_0.\n  rewrite Heql''.\n  discriminate.\n  (* now we need to do the other direction,\n     it should be easier *)\n  intros H2.\n  induction H2.\n  apply wp_e.\n  set (l1 ++ open :: l2 ++ close :: nil) as l.\n  cut (length l1 < length l /\\\n       length l2 < length l /\\\n       length nil (A := par) < length l).\n  intros [H3 [H4 _]].\n  apply wp_c;\n    [apply IHwp''1 | apply wp_p; apply IHwp''2];\n    apply lt_le_weak; \n    apply lt_le_trans\n      with (m := length l) (p := S n);\n    assumption.\n  apply comp_len_ineq.\n  rewrite app_nil_r; reflexivity.\nQed.\n\n(** Exercise 8.21 **)\n\n(* Given *)\n\nFixpoint recognize (n:nat) (l:list par)\n  {struct l}: bool :=\n  match l with\n  | nil => match n with\n           | 0 => true\n           | _ => false\n           end\n  | cons open l' => recognize (S n) l'\n  | cons close l' => match n with\n                     | 0 => false\n                     | S n' => recognize n' l'\n                     end\n  end.\n\n(* To do *)\n\nTheorem recognize_complete_aux:\n  forall l:list par, wp l ->\n  forall (n:nat) (l':list par),\n  recognize n (app l l') = recognize n l'.\nProof.\n  intros l H.\n  induction H.\n  intros; rewrite app_nil_l; reflexivity.\n  intros; simpl.\n  rewrite <-app_assoc, IHwp; reflexivity.\n  intros; simpl.\n  rewrite <-app_assoc, IHwp1, IHwp2; reflexivity.\nQed.\n\nTheorem recognize_complete:\n  forall l:list par,\n  wp l -> recognize 0 l = true.\nProof.\n  intros l H.\n  rewrite <-app_nil_r with (l := l),\n          recognize_complete_aux \n            with (l' := nil); auto.\nQed.\n\n(** Exercise 8.22 **)\n\nLemma move_middle_elem:\n  forall (A:Type) (l l':list A) (a:A),\n  l ++ (a :: l') = l ++ (a :: nil) ++ l'.\nProof.\n  intros A l l' a.\n  induction l.\n  simpl; reflexivity.\n  rewrite <-app_comm_cons.\n  rewrite IHl, app_comm_cons; reflexivity.\nQed.\n\nLemma non_nil_list_has_last:\n  forall (A:Type) (l:list A),\n  l <> nil ->\n  exists l':list A, exists a:A,\n  l = l' ++ a :: nil.\nProof.\n  intros A l l_not_nil.\n  induction l as [| h t].\n  apply False_ind, l_not_nil; reflexivity.\n  destruct t as [| h' t].\n  exists nil; exists h; simpl; reflexivity.\n  cut (exists l'':list A, exists a:A,\n       h' :: t = l'' ++ a :: nil).\n  intros [l'' [a H]].\n  exists (h :: l''); exists a.\n  rewrite <-app_comm_cons, H; auto.\n  apply IHt; discriminate.\nQed.\n\nLemma app_firstn_1st_comp:\n  forall (A:Type) (l l':list A) (n:nat),\n  n <= length l -> \n  firstn n (l ++ l') = firstn n l.\nProof.\n  induction l.\n  intros l' n H1.\n  cut (0 = n).\n  intros H2; rewrite <-H2; auto.\n  apply le_n_0_eq; auto.\n  intros l' n H1.\n  rewrite <-app_comm_cons.\n  destruct n as [|n].\n  simpl; auto.\n  simpl.\n  cut (n <= length l).\n  intros H2.\n  rewrite IHl; auto.\n  apply le_S_n; auto.\nQed.\n\nLemma firstn_whole:\n  forall (A:Type) (l:list A) (n:nat),\n  length l <= n -> firstn n l = l.\nProof.\n  induction l.\n  intros n H.\n  destruct n; simpl; auto.\n  intros n H1.\n  destruct n as [| m].\n  simpl in H1.\n  apply False_ind,\n        le_Sn_O with (n := length l),\n        H1.\n  simpl in *.\n  rewrite IHl; auto.\n  apply le_S_n; auto.\nQed.\n\nFixpoint count_par (l:list par) (p:par) :=\n  match l, p with\n  | nil, _ => 0\n  | open :: t, open => S (count_par t p)\n  | close :: t, close => S (count_par t p)\n  | h :: t, _ => count_par t p\n  end.\n\nCompute count_par (open :: open :: close :: nil)\n                  open.\nCompute count_par (open :: open :: close :: nil)\n                  close.\n\nLemma count_par_app:\n  forall (l l':list par) (p:par),\n  count_par (l ++ l') p =\n  (count_par l p) + (count_par l' p).\nProof.\n  induction l; auto.\n  destruct a, p; simpl; try apply f_equal; auto.\nQed.\n\nLemma count_par_length:\n  forall (l:list par),\n  (count_par l open) + (count_par l close) =\n  length l.\nProof.\n  induction l; auto.\n  destruct a; simpl; try rewrite <-plus_n_Sm;\n    apply f_equal, IHl.\nQed.\n\nLemma wp_balanced_count_par:\n  forall (l:list par),\n  wp l -> count_par l open = count_par l close.\nProof.\n  intros l wp_l.\n  induction wp_l; auto.\n  rewrite app_comm_cons.\n  repeat rewrite count_par_app; simpl.\n  rewrite <-plus_n_Sm.\n  repeat rewrite <-plus_n_O; auto.\n  repeat rewrite count_par_app; auto.\nQed.\n\nFixpoint n_open_par (n:nat) :=\n  match n with\n  | 0 => nil\n  | S p => open :: n_open_par p\n  end.\n\nLemma n_open_par_len:\n  forall (n:nat), length (n_open_par n) = n.\nProof.\n  intros n.\n  induction n.\n  simpl; reflexivity.\n  simpl; rewrite IHn; reflexivity.\nQed.\n\nLemma n_open_par_concat_single:\n  forall n:nat,\n  (n_open_par n) ++ (open :: nil) =\n  (n_open_par (S n)).\nProof.\n  intros n.\n  induction n.\n  simpl; reflexivity.\n  simpl in IHn; simpl; rewrite IHn; reflexivity.\nQed.\n\nLemma n_open_par_counts:\n  forall n:nat,\n  count_par (n_open_par n) open = n /\\\n  count_par (n_open_par n) close = 0.\nProof.\n  induction n as [|n [IHn1 IHn2]]; simpl; auto.\nQed.\n\nLemma n_open_par_firstm:\n  forall (m n:nat),\n  m <= n ->\n  firstn m (n_open_par n) = n_open_par m.\nProof.\n  induction m.\n  intros; auto.\n  intros n H1.\n  destruct n as [| n].\n  apply False_ind, le_Sn_O with (n := m); auto.\n  simpl; rewrite IHm; auto.\n  apply le_S_n; auto.\nQed.\n\nLemma list_ending_aux_lemma:\n  forall (l l':list par) (n:nat),\n  open :: l ++ close :: nil =\n  n_open_par n ++ l' ->\n  exists l'':list par,\n  l' = l'' ++ close :: nil.\nProof.\n  intros l l' n H1.\n  cut (exists l'':list par, exists p:par,\n       l' = l'' ++ p :: nil).\n  intros [l'' [p H2]].\n  exists l''.\n  destruct p.\n  rewrite H2 in H1.\n  cut (open :: l = n_open_par n ++ l'' /\\\n       close = open).\n  intros [_ H3]; discriminate.\n  apply app_inj_tail.\n  rewrite <-app_assoc, <-app_comm_cons; auto.\n  auto.\n  apply non_nil_list_has_last.\n  destruct l', n.\n  cut (length(open :: l ++ close :: nil) =\n       length(n_open_par 0 ++ nil)).\n  rewrite app_length; simpl; intros; \n    discriminate.\n  rewrite H1; auto.\n  rewrite <-n_open_par_concat_single,\n          app_nil_r in H1.\n  cut (open :: l = n_open_par n /\\\n       close = open).\n  intros [_ H2]; discriminate.\n  apply app_inj_tail.\n  rewrite <-app_comm_cons; auto.\n  discriminate.\n  discriminate.\nQed.\n\nLemma wp_not_nil_len:\n  forall l:list par,\n  l <> nil -> wp l -> 2 <= length l.\nProof.\n  intros l H1 H2.\n  cut (count_par l open = count_par l close).\n  intros H3.\n  cut (length l = count_par l open +\n                  count_par l close).\n  intros H4.\n  destruct (count_par l close).\n  rewrite H3 in H4; simpl in H4.\n  destruct l.\n  apply False_ind, H1; reflexivity.\n  simpl in H4; discriminate.\n  rewrite H4, H3, <-plus_n_Sm; simpl.\n  do 2 apply le_n_S.\n  apply le_0_n.\n  rewrite count_par_length; auto.\n  apply wp_balanced_count_par; auto.\nQed.\n\nLemma wp_prefix_length_bounds:\n  forall (l l':list par),\n  l <> nil /\\ l' <> nil ->\n  wp l /\\ wp l' /\\ wp (l ++ l') ->\n  2 <= length l /\\\n  S (S (length l) ) <= length (l ++ l').\nProof.\n  intros l l' H1 H2.\n  split.\n  apply wp_not_nil_len, H2; apply H1.\n  rewrite app_length.\n  cut (2 <= length l').\n  intros H3.\n  cut (S (S (length l)) = length l + 2).\n  intros H4.\n  rewrite H4.\n  apply plus_le_compat; auto.\n  rewrite <-plus_n_Sm, <-plus_n_Sm, <-plus_n_O.\n  auto.\n  apply wp_not_nil_len, H2; apply H1.\nQed.\n\nLemma wp_1st_includes_open_par_seq:\nforall (l l' l'':list par) (n:nat),\n  l <> nil /\\ wp l /\\ wp l' /\\ wp (l ++ l') ->\n  l ++ l' = n_open_par n ++ l'' ->\n  exists l''':list par,\n  l = n_open_par n ++ l'''.\nProof.\n  intros l l' l'' n H1 H2.\n  exists (skipn n l).\n  cut (n <= length l \\/ length l < n).\n  intros [H3 | H4].\n  cut (firstn n l = n_open_par n).\n  intros H5.\n  rewrite <-H5.\n  symmetry.\n  apply firstn_skipn.\n  cut (firstn n l = firstn n (l ++ l')).\n  intros H5.\n  rewrite H5, H2.\n  rewrite app_firstn_1st_comp.\n  rewrite n_open_par_firstm; auto.\n  rewrite n_open_par_len; auto.\n  rewrite app_firstn_1st_comp; auto.\n  cut (l = n_open_par (length l)).\n  intros H5.\n  cut (length l = 0).\n  intros H6.\n  destruct l as [| h t ].\n  apply False_ind, H1; reflexivity.\n  simpl in H6; discriminate.\n  cut (count_par l open = count_par l close).\n  intros H6.\n  rewrite H5 in H6.\n  cut (count_par (n_open_par (length l)) open =\n       length l /\\\n       count_par (n_open_par (length l)) close =\n       0).\n  intros [H7 H8].\n  rewrite <-H7, <-H8, H6; auto.\n  apply n_open_par_counts.\n  apply wp_balanced_count_par, H1.\n  cut (l = firstn (length l) (l ++ l')).\n  intros H5.\n  rewrite H2 in H5.\n  rewrite app_firstn_1st_comp in H5; auto.\n  rewrite n_open_par_firstm in H5; auto.\n  apply lt_le_weak; auto.\n  rewrite n_open_par_len; apply lt_le_weak; auto.\n  rewrite app_firstn_1st_comp.\n  rewrite firstn_whole; auto.\n  apply le_n.\n  apply le_or_lt.\nQed.\n\nLemma n_open_par_close_aux:\n  forall (l:list par) (n:nat),\n  wp ((n_open_par n) ++ l) ->\n  wp ((n_open_par (S n)) ++ close :: l).\nProof.\n  cut (forall (n m:nat) (l:list par),\n       length (n_open_par m ++ l) <= n ->\n       wp (n_open_par m ++ l) ->\n       wp (n_open_par (S m) ++ close :: l)).\n  intros H l n;\n  apply\n    H with (n := length (n_open_par n ++ l)),\n    le_n.\n  induction n.\n  intros m l H1 _.\n  cut (m = 0 /\\ l = nil).\n  intros [H2 H3].\n  rewrite H2, H3; simpl.\n  apply wp_p with (l := nil), wp_e.\n  cut ((n_open_par m) = nil /\\ l = nil).\n  intros [H2 H3].\n  cut (length (n_open_par m) = 0).\n  intros H4.\n  rewrite n_open_par_len in H4.\n  split; assumption.\n  rewrite H2; auto.\n  cut (n_open_par m ++ l = nil).\n  intros; apply app_eq_nil; auto.\n  apply len_le_zero_is_nil; auto.\n  intros m l H1 H2.\n  destruct m as [|m].\n  simpl.\n  apply wp_c with (l := open :: close :: nil)\n                  (l' := l).\n  apply wp_p with (l := nil),\n        wp_e.\n  apply H2.\n  remember (n_open_par (S m) ++ l) as wpl.\n  induction H2.\n  simpl in Heqwpl; discriminate.\n  clear IHwp.\n  cut (exists l':list par,\n       n_open_par (S (S m)) ++ close :: l =\n       open :: (n_open_par (S m) ++\n       close :: l') ++ close :: nil).\n  intros [l' H3].\n  rewrite H3, app_comm_cons.\n  apply wp_p, IHn.\n  cut (length (n_open_par (S (S m)) ++\n               close :: l) <= S(S(S(n)))).\n  intros H4.\n  cut (length (open :: (n_open_par (S m) ++\n                        close :: l') ++\n               close :: nil) <= S(S(S(n)))).\n  intros H5.\n  simpl in H5.\n  repeat rewrite app_length in H5; simpl in H5.\n  repeat rewrite <-plus_n_Sm in H5.\n  rewrite <-plus_n_O in H5.\n  rewrite <-app_length in H5.\n  do 4 apply le_S_n; apply le_S; auto.\n  rewrite <-H3; auto.\n  rewrite app_length; simpl.\n  rewrite <-plus_n_Sm.\n  rewrite Heqwpl in H1.\n  rewrite app_length in H1.\n  simpl in H1.\n  do 2 apply le_n_S; auto.\n  cut (l0 = n_open_par m ++ l').\n  intros H4.\n  rewrite <-H4; auto.\n  cut (open :: l0 = n_open_par (S m) ++ l').\n  intros H4.\n  simpl in H4.\n  inversion H4; auto.\n  cut (open :: l0 ++ close :: nil =\n       n_open_par (S m) ++ l' ++ close :: nil).\n  intros H5.\n  rewrite app_comm_cons, app_assoc in H5.\n  cut (open :: l0 = n_open_par (S m) ++ l' /\\\n       close = close).\n  intros H6.\n  apply H6.\n  apply app_inj_tail\n    with (x := (open :: l0))\n         (y := (n_open_par (S m) ++ l')); auto.\n  rewrite Heqwpl.\n  apply f_equal.\n  apply app_inv_head\n    with (l := n_open_par (S (S m)) ++\n               close :: nil).\n  simpl in *.\n  repeat rewrite <-app_assoc; simpl.\n  rewrite H3; repeat apply f_equal.\n  rewrite <-app_assoc, app_comm_cons; auto.\n  cut (exists l', l = l' ++ close :: nil).\n  intros [l' H3].\n  exists l'.\n  rewrite H3; simpl; repeat apply f_equal.\n  rewrite app_comm_cons, <-app_assoc; auto.\n  apply list_ending_aux_lemma\n    with (l := l0) (l' := l) (n := S m); auto.\n  destruct l0, l'.\n  simpl in Heqwpl; discriminate.\n  apply IHwp2.\n  rewrite <-Heqwpl, app_nil_l; auto.\n  rewrite app_nil_l in H1; auto.\n  apply IHwp1.\n  rewrite <-Heqwpl, app_nil_r; auto.\n  rewrite app_nil_r in H1; auto.\n  remember (p :: l0) as l1.\n  remember (p0 :: l') as l2.\n  clear IHwp1 IHwp2.\n  cut (exists l1t:list par,\n       l1 = n_open_par (S m) ++ l1t).\n  intros [l1t H3].\n  cut (S (S (length l1)) <= length (l1 ++ l2)).\n  intros H4.\n  cut (length l1 <= n).\n  intros H5.\n  cut (wp(n_open_par (S (S m)) ++ close :: l1t)).\n  intros H6.\n  cut (n_open_par (S (S m)) ++\n       close :: l1t ++ l2 =\n       n_open_par (S (S m)) ++ close :: l).\n  intros H7.\n  rewrite <-H7, app_comm_cons, app_assoc.\n  apply wp_c; auto.\n  cut (l = l1t ++ l2).\n  intros H7.\n  rewrite H7; auto.\n  apply app_inv_head\n    with (l := n_open_par (S m)).\n  rewrite <-Heqwpl, app_assoc, <-H3; auto.\n  apply IHn.\n  rewrite <-H3; auto.\n  rewrite <-H3; auto.\n  do 2 apply le_S_n; apply le_S.\n  apply le_trans with (m := length (l1 ++ l2));\n    auto.\n  apply wp_prefix_length_bounds.\n  rewrite Heql1, Heql2; split; discriminate.\n  split; [auto | split; auto].\n  apply wp_c; auto.\n  Check wp_1st_includes_open_par_seq.\n  apply wp_1st_includes_open_par_seq\n    with (l := l1) (l' := l2) (n := S m)\n         (l'' := l).\n  split.\n  rewrite Heql1; discriminate.\n  split; try split; auto.\n  apply wp_c; auto.\n  auto.\nQed.\n\nLemma recognize_sound_aux:\n  forall (l:list par) (n:nat),\n  recognize n l = true ->\n  wp ((n_open_par n) ++ l).\nProof.\n  intros l.\n  induction l.\n  simpl; intros n H.\n  destruct n.\n  simpl; apply wp_e.\n  discriminate.\n  intros n H1.\n  destruct a.\n  rewrite move_middle_elem,\n          app_assoc,\n          n_open_par_concat_single.\n  apply IHl.\n  apply H1.\n  destruct n.\n  simpl in H1; discriminate.\n  apply n_open_par_close_aux, IHl.\n  simpl in H1; assumption.\nQed.\n\nTheorem recognize_sound:\n  forall l:list par,\n  recognize 0 l = true -> wp l.\nProof.\n  intros l H1.\n  cut (wp ((n_open_par 0) ++ l)).\n  simpl; intros; assumption.\n  apply recognize_sound_aux with (n := 0);\n    assumption.\nQed.\n\n(** Exercise 8.22 **)\n\n(* TO DO *)\n\n(** Exercise 8.23 **)\n\n(* TO DO *)\n\n(** Exercise 8.24 **)\n\n(* TO DO *)\n\n(** Exercise 8.25 **)\n\n(* TO DO *)\n\n(** Exercise 8.26 **)\n\n(* TO DO *)\n\n(** Exercise 8.27 **)\n\n(* TO DO *)\n\n(** Exercise 8.28 **)\n\nLemma ex_8_28:\n  ~sorted nat le (1 :: 3 :: 2 :: nil).\nProof.\n  intros H1.\n  cut (sorted nat le (3 :: 2 :: nil)).\n  intros H2.\n  inversion H2.\n  cut (1 <= 0).\n  intros H6.\n  inversion H6.\n  do 2 apply le_S_n; auto.\n  inversion H1; auto.\nQed.\n\n(** Exercise 8.29 **)\n\nInductive payable : nat -> Prop :=\n  | O_pay : payable 0\n  | inc_3_pay : \n      forall n:nat, payable n -> payable (n + 3)\n  | inc_5_pay :\n      forall n:nat, payable n -> payable (n + 5).\n\nLemma ex_8_29:\n  forall n:nat, 8 <= n -> payable n.\nProof.\n  (* we first transform the goal to do strong\n     induction *)\n  intros n.\n  cut (forall m, 8 <= m <= n -> payable m).\n\n  (* if we have the strong form, it's easy to\n     prove the weak *)\n  intros H1 H2.\n  apply H1.\n  split; [exact H2 | apply le_n].\n\n  (* now we can start our induction over n *)\n  induction n.\n\n  (* the base case is obviously uninteresting *)\n  intros m [H1 H2].\n  cut (8 <= 0).\n  intros H3.\n  apply False_ind, le_Sn_O with (n := 7); auto.\n  apply le_trans with (m := m); auto.\n\n  intros m [H1 H2].\n  (* we will now consider two cases:\n     - base (S n <= 10).\n     - inductive. *)\n  cut (S n <= 10 \\/ 10 < S n).\n  intros [H3 | H4].\n\n  (* this is just case analysis plus applying\n     the constructors *)\n  destruct H1.\n  rewrite plus_n_O.\n  do 3 rewrite plus_Sn_m, plus_n_Sm.\n  constructor.\n  rewrite plus_n_O.\n  do 5 rewrite plus_Sn_m, plus_n_Sm.\n  constructor.\n  constructor.\n  destruct H1.\n  do 3 (\n    rewrite plus_n_O;\n    do 3 rewrite plus_Sn_m, plus_n_Sm;\n    constructor ).\n  constructor.\n  destruct H1.\n  do 2 (\n    rewrite plus_n_O;\n    do 5 rewrite plus_Sn_m, plus_n_Sm;\n    constructor ).\n  constructor.\n\n  (* now we need to stop the destruction by\n     proving we were exhaustive *)\n  cut (m < m).\n  intros H5.\n  apply False_ind, lt_irrefl with (n := m);\n    auto.\n  unfold lt.\n  apply le_trans with (m := 8).\n  do 2 apply le_S_n.\n  apply le_trans with (m := S n); auto.\n  auto.\n\n  (* if we prove that we have payable (S n),\n     it's easy to show we are done *)\n  cut (payable (S n)).\n  intros H6.\n  cut (m < S n \\/ m = S n).\n  intros [H7 | H8].\n  apply IHn; split; auto.\n  apply le_S_n; auto.\n  rewrite H8; auto.\n  apply le_lt_or_eq; auto.\n\n  (* if we prove that (S n) - 3 falls in the\n     right range, we are done *)\n  cut (8 <= (S n) - 3 <= n).\n  intros [H5 H6].\n  rewrite le_plus_minus with (n := 3), plus_comm.\n  constructor.\n  apply IHn; split; auto.\n  apply le_trans with (m := 11).\n  do 8 apply le_S; apply le_n.\n  auto.\n\n  (* so we need to prove that inequality *)\n  split.\n\n  (* this is the \"hard\" one *)\n  apply plus_le_reg_l with (p := 3).\n  rewrite <-le_plus_minus.\n  simpl; auto.\n  apply le_trans with (m := 11).\n  do 8 apply le_S; apply le_n.\n  auto.\n\n  (* this one is easier *)\n  simpl; apply le_minus.\n\n  (* now we just need to justify the split *)\n  apply le_or_lt.  \nQed.\n", "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-ch8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7166511294197419}}
{"text": "(** * MoreCoq: More About Coq's Tactics *)\n\nRequire Export Poly.\n\nCheck NatList.swap_pair.\nCheck evenb.\n(** This chapter introduces several more proof strategies and\n    tactics that, together, allow us to prove theorems about the\n    functional programs we have been writing. In particular, we'll\n    reason about functions that work with natural numbers and lists.\n\n    In particular, we will see:\n    - how to use auxiliary lemmas, in both forwards and backwards reasoning;\n    - how to reason about data constructors, which are injective and disjoint;\n    - how to create a strong induction hypotheses (and when\n      strengthening is required); and\n    - how to reason by case analysis.\n *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p H G.\n  rewrite G.\n  rewrite H.\n  reflexivity.\nQed.\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2. \n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\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  apply H0.\nQed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal _exactly_ -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\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  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since \n            [apply] will perform simplification first. *)\n  apply H.  Qed.         \n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** Hint: you can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend. *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros.\n  rewrite H.\n  symmetry.\n  apply rev_involutive.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  Are there situations where both can usefully be\n    applied?\n  (* FILL IN HERE *)\n*)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might\n    abstract it out as a lemma recording once and for all\n    the fact that equality is transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. \n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to\n    prove the above example.  However, to do this we need\n    a slight refinement of the [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  (* If we simply tell Coq [apply trans_eq] at this point,\n     it can tell (by matching the goal against the\n     conclusion of the lemma) that it should instantiate [X]\n     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].\n     However, the matching process doesn't determine an\n     instantiation for [m]: we have to supply one explicitly\n     by adding [with (m:=[c,d])] to the invocation of\n     [apply]. *)\n  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.\n\n(**  Actually, we usually don't have to include the name [m]\n    in the [with] clause; Coq is often smart enough to\n    figure out which instantiation we're giving. We could\n    instead write: [apply trans_eq with [c,d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o). \nProof.\n  intros.\n  apply trans_eq with (m:=m).\n  apply H0.\n  apply H.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [inversion] tactic *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is clear from this definition that every number has one of two\n    forms: either it is the constructor [O] or it is built by applying\n    the constructor [S] to another number.  But there is more here than\n    meets the eye: implicit in the definition (and in our informal\n    understanding of how datatype declarations work in other\n    programming languages) are two other facts:\n\n    - The constructor [S] is _injective_.  That is, the only way we can\n      have [S n = S m] is if [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor is\n    injective and [nil] is different from every non-empty list.  For\n    booleans, [true] and [false] are unequal.  (Since neither [true]\n    nor [false] take any arguments, their injectivity is not an issue.) *)\n\n(** Coq provides a tactic called [inversion] that allows us to exploit\n    these principles in proofs.\n \n    The [inversion] tactic is used like this.  Suppose [H] is a\n    hypothesis in the context (or a previously proven lemma) of the\n    form\n      c a1 a2 ... an = d b1 b2 ... bm\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] instructs Coq to \"invert\" this\n    equality to extract the information it contains about these terms:\n\n    - If [c] and [d] are the same constructor, then we know, by the\n      injectivity of this constructor, that [a1 = b1], [a2 = b2],\n      etc.; [inversion H] adds these facts to the context, and tries\n      to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory.  That is, a false assumption has crept\n      into the context, and this means that any goal whatsoever is\n      provable!  In this case, [inversion H] marks the current goal as\n      completed and pops it off the goal stack. *)\n\n(** The [inversion] tactic is probably easier to understand by\n    seeing it in action than from general descriptions like the above.\n    Below you will find example theorems that demonstrate the use of\n    [inversion] and exercises to test your understanding. *)\n\nTheorem eq_add_S : forall (n m : nat),\n     S n = S m ->\n     n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.  Qed.\n\nTheorem silly4 : forall (n m : nat),\n     [n] = [m] ->\n     n = m.\nProof.\n  intros n o eq. inversion eq. reflexivity.  Qed.\n\n(** As a convenience, the [inversion] tactic can also\n    destruct equalities between complex values, binding\n    multiple variables as it goes. *)\n\nTheorem silly5 : forall (n m o : nat),\n     [n;m] = [o;o] ->\n     [n] = [m].\nProof.\n  intros n m o eq. inversion eq. reflexivity. Qed.\n\n(** **** Exercise: 1 star (sillyex1)  *) \nExample sillyex1 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  symmetry.\n  apply H2.\nQed.\n(** [] *)\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n  intros n m contra. inversion contra.  Qed.\n\n(** **** Exercise: 1 star (sillyex2)  *)\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = [] ->\n     y :: l = z :: j ->\n     x = z.\nProof.\n  intros.\n  inversion H.\nQed.\n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    [forall (n m : nat), S n = S m -> n = m], the reverse direction of\n    the implication is an instance of a more general fact about\n    constructors and functions, which we will often find useful: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A), \n    x = y -> f x = f y. \nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed. \n\n\n\n\n(** **** Exercise: 2 stars, optional (practice)  *)\n(** A couple more nontrivial but not-too-complicated proofs to work\n    together in class, or for you to work as exercises. *)\n \n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros.\n  induction n.\n  simpl. reflexivity.\n  inversion H.\nQed.  \n\nTheorem beq_nat_0_r : forall n,\n   beq_nat n 0 = true -> n = 0.\nProof.\n  intros.\n  induction n.\n  reflexivity.\n  inversion H.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b. \nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, the tactic [apply L in H] matches some\n    conditional statement [L] (of the form [L1 -> L2], say) against a\n    hypothesis [H] in the context.  However, unlike ordinary\n    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),\n    [apply L in H] matches [H] against [L1] and, if successful,\n    replaces it with [L2].\n \n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\" -- from [L1 -> L2] and a hypothesis matching [L1], it\n    gives us a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\" -- it says that if we know [L1->L2] and we\n    are trying to prove [L2], it suffices to prove [L1].  \n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\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  symmetry in H. apply eq in H. symmetry in H. \n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, Coq tends to favor backward reasoning, but in some\n    situations the forward style can be easier to use or to think\n    about.  *)\n\n(** **** Exercise: 3 stars (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise. *)\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  Case \"n = 0\".\n  intros m H.\n  destruct m as [| m'].\n  reflexivity.\n  inversion H.\n  Case \"n = S n'\".\n  intros m.\n  destruct m as [| m'].\n  intros.\n  inversion H.\n  intros. \n  inversion H.\n  rewrite <-plus_n_Sm in H1.\n  rewrite <-plus_n_Sm in H1.\n  inversion H1.\n  apply IHn' in H2.\n  rewrite -> H2.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose \n    we want to show that the [double] function is injective -- i.e., \n    that it always maps different arguments to different results:  \n    Theorem double_injective: forall n m, double n = double m -> n = m. \n    The way we _start_ this proof is a little bit delicate: if we \n    begin it with\n      intros n. induction n.\n]] \n    all is well.  But if we begin it with\n      intros n m. induction n.\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = O\". simpl. intros eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". intros eq. destruct m as [| m'].\n    SCase \"m = O\". inversion eq.\n    SCase \"m = S m'\".  apply f_equal. \n      (* Here we are stuck.  The induction hypothesis, [IHn'], does\n         not give us [n' = m'] -- there is an extra [S] in the\n         way -- so the goal is not provable. *)\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context -- \n    intuitively, we have told Coq, \"Let's consider some particular\n    [n] and [m]...\" and we now have to prove that, if [double n =\n    double m] for _this particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove that\n    the proposition\n\n      - [P n]  =  \"if [double n = double m], then [n = m]\"\n\n    holds for all [n] by showing\n\n      - [P O]              \n\n         (i.e., \"if [double O = double m] then [O = m]\")\n\n      - [P n -> P (S n)]  \n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help with proving [R]!  (If we\n    tried to prove [R] from [Q], we would say something like \"Suppose\n    [double (S n) = 10]...\" but then we'd be stuck: knowing that\n    [double (S n)] is [10] tells us nothing about whether [double n]\n    is [10], so [Q] is useless at this point.) *)\n\n(** To summarize: Trying to carry out this proof by induction on [n]\n    when [m] is already in the context doesn't work because we are\n    trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = O\". simpl. intros m eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". \n    (* Notice that both the goal and the induction\n       hypothesis have changed: the goal asks us to prove\n       something more general (i.e., to prove the\n       statement for _every_ [m]), but the IH is\n       correspondingly more flexible, allowing us to\n       choose any [m] we like when we apply the IH.  *)\n    intros m eq.\n    (* Now we choose a particular [m] and introduce the\n       assumption that [double n = double m].  Since we\n       are doing a case analysis on [n], we need a case\n       analysis on [m] to keep the two \"in sync.\" *)\n    destruct m as [| m'].\n    SCase \"m = O\". \n      (* The 0 case is trivial *)\n      inversion eq.  \n    SCase \"m = S m'\".  \n      apply f_equal. \n      (* At this point, since we are in the second\n         branch of the [destruct m], the [m'] mentioned\n         in the context at this point is actually the\n         predecessor of the one we started out talking\n         about.  Since we are also in the [S] branch of\n         the induction, this is perfect: if we\n         instantiate the generic [m] in the IH with the\n         [m'] that we are talking about right now (this\n         instantiation is performed automatically by\n         [apply]), then [IHn'] gives us exactly what we\n         need to finish the proof. *)\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What this teaches us is that we need to be careful about using\n    induction to try to prove something too specific: If we're proving\n    a property of [n] and [m] by induction on [n], we may need to\n    leave [m] generic. *)\n\n(** The proof of this theorem (left as an exercise) has to be treated similarly: *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n=0\".\n  intros m eq.\n  destruct m as [|m'].\n  SCase \"m=0\".\n  reflexivity.\n  SCase \"m=S m'\".\n  inversion eq.\n  Case \"n=S n'\".\n  intros m eq.\n  destruct m as [|m'].\n  SCase \"m=0\".\n  inversion eq.\n  SCase \"m=S m'\".\n  apply f_equal.\n  apply IHn'.\n  simpl in eq.\n  apply eq.\nQed.\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** The strategy of doing fewer [intros] before an [induction] doesn't\n    always work directly; sometimes a little _rearrangement_ of\n    quantified variables is needed.  Suppose, for example, that we\n    wanted to prove [double_injective] by induction on [m] instead of\n    [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  Case \"m = O\". simpl. intros eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq. \n  Case \"m = S m'\". intros eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\".  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce\n    [n] for us!)   *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    will work, but it's not nice: We don't want to have to mangle the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them -- we want to state them in the most clear and\n    natural way. *)\n\n(**  What we can do instead is to first introduce all the\n    quantified variables and then _re-generalize_ one or more of\n    them, taking them out of the context and putting them back at\n    the beginning of the goal.  The [generalize dependent] tactic\n    does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. \n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  Case \"m = O\". simpl. intros n eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq.\n  Case \"m = S m'\". intros n eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\". apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n_Theorem_: For any nats [n] and [m], if [double n = double m], then\n  [n = m].\n\n_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n  any [n], if [double n = double m] then [n = m].\n\n  - First, suppose [m = 0], and suppose [n] is a number such\n    that [double n = double m].  We must show that [n = 0].\n\n    Since [m = 0], by the definition of [double] we have [double n =\n    0].  There are two cases to consider for [n].  If [n = 0] we are\n    done, since this is what we wanted to show.  Otherwise, if [n = S\n    n'] for some [n'], we derive a contradiction: by the definition of\n    [double] we would have [double n = S (S (double n'))], but this\n    contradicts the assumption that [double n = 0].\n\n  - Otherwise, suppose [m = S m'] and that [n] is again a number such\n    that [double n = double m].  We must show that [n = S m'], with\n    the induction hypothesis that for every number [s], if [double s =\n    double m'] then [s = m'].\n \n    By the fact that [m = S m'] and the definition of [double], we\n    have [double n = S (S (double m'))].  There are two cases to\n    consider for [n].\n\n    If [n = 0], then by definition [double n = 0], a contradiction.\n    Thus, we may assume that [n = S n'] for some [n'], and again by\n    the definition of [double] we have [S (S (double n')) = S (S\n    (double m'))], which implies by inversion that [double n' = double\n    m'].\n\n    Instantiating the induction hypothesis with [n'] thus allows us to\n    conclude that [n' = m'], and it follows immediately that [S n' = S\n    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted\n    to show. [] *)\n\n\n\n(** Here's another illustration of [inversion] and using an\n    appropriately general induction hypothesis.  This is a slightly\n    roundabout way of stating a fact that we have already proved\n    above.  The extra equalities force us to do a little more\n    equational reasoning and exercise some of the tactics we've seen\n    recently. *)\n\nTheorem length_snoc' : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l. induction l as [| v' l'].\n\n  Case \"l = []\". \n    intros n eq. rewrite <- eq. reflexivity.\n\n  Case \"l = v' :: l'\". \n    intros n eq. simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.\n\n(** It might be tempting to start proving the above theorem\n    by introducing [n] and [eq] at the outset.  However, this leads\n    to an induction hypothesis that is not strong enough.  Compare\n    the above to the following (aborted) attempt: *)\n\nTheorem length_snoc_bad : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l n eq. induction l as [| v' l'].\n\n  Case \"l = []\". \n    rewrite <- eq. reflexivity.\n\n  Case \"l = v' :: l'\". \n    simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)\n\n\n(** As in the double examples, the problem is that by\n    introducing [n] before doing induction on [l], the induction\n    hypothesis is specialized to one particular natural number, namely\n    [n].  In the induction case, however, we need to be able to use\n    the induction hypothesis on some other natural number [n'].\n    Retaining the more general form of the induction hypothesis thus\n    gives us more flexibility.\n\n    In general, a good rule of thumb is to make the induction hypothesis\n    as general as possible. *)\n\n(** **** Exercise: 3 stars (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     index n l = None.\nProof.\n  intros n X l.\n  generalize dependent n.\n  induction l as [|v' l'].\n  Case \"l=[]\".\n  intros n eq. simpl. reflexivity.\n  Case \"l=v' l'\".\n  intros n eq.\n  induction n as [|n'].\n  SCase \"n=0\".\n  inversion eq.\n  SCase \"n=S n'\". \n  simpl. apply IHl'.\n  inversion eq. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal)  *)\n(** Write an informal proof corresponding to your Coq proof\n    of [index_after_last]:\n \n     _Theorem_: For all sets [X], lists [l : list X], and numbers\n      [n], if [length l = n] then [index n l = None].\n \n     _Proof_:\n     (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (gen_dep_practice_more)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem length_snoc''' : forall (n : nat) (X : Type) \n                              (v : X) (l : list X),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros n X v l.\n  generalize dependent n.\n  generalize dependent v.\n  induction l as [|v' l'].\n  Case \"l=[]\".\n  intros v n eq.\n  induction n as [|n'].\n  SCase \"n=0\".\n  simpl. reflexivity.\n  SCase \"n=S n'\".\n  inversion eq.\n  Case \"l=v' l'\".\n  intros v n eq.\n  induction n as [|n'].\n  SCase \"n=0\".\n  inversion eq.\n  SCase \"n=S n'\".\n  simpl.\n  apply f_equal.\n  apply IHl'.\n  inversion eq.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (app_length_cons)  *)\n(** Prove this by induction on [l1], without using [app_length]\n    from [Lists]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X) \n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  intros X l1 l2 x.\n  generalize dependent l2.\n  induction l1 as [|v1' l1'].\n  Case \"l1=[]\".\n  intros l2 n.\n  simpl. intros eq. apply eq.\n  Case \"l1=v1' l1'\".\n  intros l2 n. simpl.\n  induction n as [|n'].\n  SCase \"n=0\".\n  intros eq. inversion eq.\n  SCase \"n=S n'\".\n  intros eq. apply f_equal.\n  apply IHl1'.\n  inversion eq.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice)  *)\n(** Prove this by induction on [l], without using app_length. *)\nTheorem app_length_snoc' : forall (X:Type) (l1 l2:list X) (v:X),\nlength (l1 ++ (v::l2)) = S (length(l1++l2)).\nProof.\n  intros X l1 l2 v.\n  remember (length (l1 ++ v :: l2)) as len.\n  symmetry in Heqlen.\n  apply app_length_cons with (x:=v) in Heqlen.\n  symmetry.\n  apply Heqlen.\nQed.\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  intros X n l.\n  generalize dependent n.\n  induction l as [|v' l'].\n  Case \"l=[]\".\n  intros n eq.\n  induction n as [|n'].\n  SCase \"n=0\".\n  reflexivity.\n  SCase \"n=S n'\".\n  inversion eq.\n  Case \"l=v' l'\".\n  intros n eq.\n  induction n as [|n'].\n  SCase \"n=0\".\n  inversion eq.\n  SCase \"n=S n'\".\n  simpl.\n  apply f_equal.\n  rewrite <- plus_n_Sm.\n  inversion eq.\n  remember (length (l' ++ v'::l')) as len.\n  symmetry in Heqlen.\n  apply app_length_cons with (x:=v') in Heqlen.\n  rewrite <- Heqlen.\n  apply f_equal.\n  rewrite H0.\n  apply IHl' in H0.\n  rewrite H0. \n  reflexivity.\nQed.\n(** [] *)\n\n\n(** **** Exercise: 3 stars, optional (double_induction)  *)\n(** Prove the following principle of induction over two naturals. *)\n\nTheorem double_induction: forall (P : nat -> nat -> Prop), \n  P 0 0 ->\n  (forall m, P m 0 -> P (S m) 0) ->\n  (forall n, P 0 n -> P 0 (S n)) ->\n  (forall m n, P m n -> P (S m) (S n)) ->\n  forall m n, P m n.\nProof.\n  intros.\n  generalize dependent n.\n  induction m as [|m'].\n  Case \"m=0\".\n  intros n.\n  induction n as [|n'].\n  SCase \"n=0\".\n  apply H.\n  SCase \"n=S n'\".\n  apply H1. apply IHn'.\n  Case \"m=S m'\".\n  intros n.\n  induction n as [|n'].\n  SCase \"n=0\".\n  apply H0. apply IHm'.\n  SCase \"n=S n'\".\n  apply H2. apply IHm'.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where the [destruct] tactic is\n    used to perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nEval compute in sillyfun 3.\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun. \n  destruct (beq_nat n 3).\n    Case \"beq_nat n 3 = true\". reflexivity.\n    Case \"beq_nat n 3 = false\". destruct (beq_nat n 5).\n      SCase \"beq_nat n 5 = true\". reflexivity.\n      SCase \"beq_nat n 5 = false\". reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,\n    either [n] is equal to [3] or it isn't, so we use [destruct\n    (beq_nat n 3)] to let us reason about the two cases. \n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c].\n\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  intros X x1 x2 k1 k2 f.\n  unfold override.\n  destruct (beq_nat k1 k2).\n  Case \"beq_nat k1 k2 = true\".\n  reflexivity.\n  Case \"beq_nat k1 k2 = false\".\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (combine_split)  *)\n(** Complete the proof below *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l l1 l2.\n  intros H.\n  generalize dependent l1.\n  generalize dependent l2.\n  induction l as [|v' l'].\n  Case \"l=[]\".\n  intros l1 l2. simpl. intros H.\n  inversion H. simpl. reflexivity.\n  Case \"l=v' l'\".\n  intros l1 l2. intros H.\n  destruct v'.\n  inversion H. simpl. apply f_equal.\n  apply IHl'.\n  assert (G: forall X Y (x: X*Y), x = (fst x,snd x)).\n  intros. destruct x0. simpl. reflexivity.\n  apply G.\nQed.\n(** [] *)\n\n(** Sometimes, doing a [destruct] on a compound expression (a\n    non-variable) will erase information we need to complete a proof. *)\n(** For example, suppose\n    we define a function [sillyfun1] like this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** And suppose that we want to convince Coq of the rather\n    obvious observation that [sillyfun1 n] yields [true] only when [n]\n    is odd.  By analogy with the proofs we did with [sillyfun] above,\n    it is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution peformed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that since, in this branch of the case\n    analysis, [beq_nat n 3 = true], it must be that [n = 3], from\n    which it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation (with whatever\n    name we choose). *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got stuck\n    above, except that the context contains an extra equality\n    assumption, which is exactly what we need to make progress. *)\n    Case \"e3 = true\". apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    Case \"e3 = false\".\n     (* When we come to the second equality test in the body of the\n       function we are reasoning about, we can use [eqn:] again in the\n       same way, allow us to finish the proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5. \n        SCase \"e5 = true\".\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        SCase \"e5 = false\". inversion eq.  Qed.\n\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  intros.\n  destruct b.\n  Case \"b=true\".\n  destruct (f true) eqn:ft.\n  rewrite ft. rewrite ft. reflexivity.\n  destruct (f false) eqn:ff.\n  rewrite ft. reflexivity.\n  rewrite ff. reflexivity.\n  Case \"b=false\".\n  destruct (f false) eqn:ff.\n  destruct (f true) eqn:ft.\n  apply ft. apply ff.\n  rewrite ff. apply ff.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars (override_same)  *)\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.\n  unfold override.\n  destruct (beq_nat k1 k2) eqn:H1.\n  apply beq_nat_true in H1.\n  rewrite <- H1. symmetry. apply H.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen a bunch of Coq's fundamental tactics.  We'll\n    introduce a few more as we go along through the coming lectures,\n    and later in the course we'll introduce some more powerful\n    _automation_ tactics that make Coq do more of the low-level work\n    in many cases.  But basically we've got what we need to get work\n    done.\n\n    Here are the ones we've seen:\n\n      - [intros]: \n        move hypotheses/variables from goal to context \n\n      - [reflexivity]:\n        finish the proof (when the goal looks like [e = e])\n\n      - [apply]:\n        prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: \n        apply a hypothesis, lemma, or constructor to a hypothesis in\n        the context (forward reasoning)\n\n      - [apply... with...]:\n        explicitly specify values for variables that cannot be\n        determined by pattern matching\n\n      - [simpl]:\n        simplify computations in the goal \n\n      - [simpl in H]:\n        ... or a hypothesis \n\n      - [rewrite]:\n        use an equality hypothesis (or lemma) to rewrite the goal \n\n      - [rewrite ... in H]:\n        ... or a hypothesis \n\n      - [symmetry]:\n        changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]:\n        changes a hypothesis of the form [t=u] into [u=t]\n\n      - [unfold]:\n        replace a defined constant by its right-hand side in the goal \n\n      - [unfold... in H]:\n        ... or a hypothesis  \n\n      - [destruct... as...]:\n        case analysis on values of inductively defined types \n\n      - [destruct... eqn:...]:\n        specify the name of an equation to be added to the context,\n        recording the result of the case analysis\n\n      - [induction... as...]:\n        induction on values of inductively defined types \n\n      - [inversion]:\n        reason by injectivity and distinctness of constructors\n\n      - [assert (e) as H]:\n        introduce a \"local lemma\" [e] and call it [H] \n\n      - [generalize dependent x]:\n        move the variable [x] (and anything else that depends on it)\n        from the context back to an explicit hypothesis in the goal\n        formula \n*)\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\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  reflexivity.\n  SCase \"m=S m'\".\n  simpl. reflexivity.\n  Case \"n=S n'\".\n  intros m.\n  destruct m as [|m'].\n  SCase \"m=0\".\n  simpl. reflexivity.\n  SCase \"m=S m'\".\n  simpl.\n  apply IHn'.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  intros.\n  apply beq_nat_true in H.\n  rewrite <- H in H0.\n  apply H0.\nQed.\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We have just proven that for all lists of pairs, [combine] is the\n    inverse of [split].  How would you formalize the statement that\n    [split] is the inverse of [combine]? When is this property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)\n\nDefinition split_combine_statement : Prop :=\n  forall X (l1 l2 : list X),\n    length l1 = length l2 ->\n    split (combine l1 l2) = (l1,l2).\nTheorem split_combine : split_combine_statement.\nProof.\n  unfold split_combine_statement.\n  intros X l1.\n  induction l1 as [|v1' l1'].\n  Case \"l1=[]\".\n  intros l2 H.\n  induction l2 as [|v2' l2'].\n  SCase \"l2=[]\".\n  simpl. reflexivity.\n  SCase \"l2=v2' l2'\".\n  inversion H.\n  Case \"l1=v1' l1'\".\n  intros l2 H.\n  induction l2 as [|v2' l2'].\n  SCase \"l2=[]\".\n  inversion H.\n  SCase \"l2=v2' l2'\".\n  simpl.\n  rewrite IHl1'.\n  simpl. reflexivity.\n  inversion H. reflexivity.\nQed.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars (override_permute)  *)\nTheorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),\n  beq_nat k2 k1 = false ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n  intros.\n  unfold override.\n  destruct (beq_nat k1 k3) eqn:H1.\n  apply beq_nat_true in H1.\n  rewrite H1 in H.\n  rewrite H. reflexivity.\n  reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your IH. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  intros.\n  generalize dependent lf.\n  induction l as [|v' l'].\n  Case \"l=[]\".\n  simpl.\n  intros lf H. inversion H.\n  Case \"l=v' l'\".\n  intros lf H.\n  destruct lf as [|vf' lf'].\n  SCase \"lf=[]\".\n  simpl in H.\n  destruct (test v') eqn:eqV.\n  SSCase \"test v'=true\".\n  inversion H. rewrite H1 in eqV.\n  apply eqV.\n  SSCase \"test v'=false\".\n  apply IHl' in H. apply H.\n  SCase \"lf=vf' lf'\".\n  simpl in H.\n  destruct (test v') eqn:eqV.\n  SSCase \"test v'=true\".\n  inversion H. rewrite H1 in eqV. apply eqV.\n  SSCase \"test v'=false\".\n  apply IHl' in H. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n  \n      forallb evenb [0;2;4;5] = false\n  \n      forallb (beq_nat 5) [] = true\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n      existsb (beq_nat 5) [0;2;3;6] = false\n \n      existsb (andb true) [true;true;false] = true\n \n      existsb oddb [1;0;0;0;0;3] = true\n \n      existsb evenb [] = false\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n \n    Prove theorem [existsb_existsb'] that [existsb'] and [existsb] have\n    the same behavior.\n*)\nFixpoint forallb1 {X:Type} (f:X->bool) (l:list X) :bool:=\nmatch l with\n|nil=>true\n|h::t=>andb (f h) (forallb1 f t)\nend.\nEval compute in forallb1 evenb [2;4;6;8].\nFixpoint forallb {X:Type} (f:X->bool) (l:list X) :bool :=\nmatch l with\n| nil => true\n| h::t => andb (f h) (forallb f t)\nend.\nEval compute in forallb oddb [1;3;5].\nEval compute in forallb evenb [1;2;4].\nFixpoint existsb {X:Type} (f:X->bool) (l:list X):bool :=\nmatch l with\n|nil => false\n|h::t => orb (f h) (existsb f t)\nend.\nEval compute in existsb (beq_nat 5) [0;2;3;6].\nEval compute in existsb (andb true) [false;true].\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2014-12-31 16:01:37 -0500 (Wed, 31 Dec 2014) $ *)\n\n\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/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.7166501080662493}}
{"text": "(* * Maximum element in a list *)\n\nFrom Undecidability.TM.Util Require Export Prelim ArithPrelim.\n\n(* ** Basic lemmas about upper bounds *)\n\n(* An upper bound of a list is either in the list, or it is not in the list and is a strict upper bound *)\nLemma upperBound_In (xs : list nat) (u : nat) :\n  (forall x, In x xs -> x <= u) ->\n  (In u xs) \\/\n  (~ In u xs /\\ forall x, In x xs -> x < u).\nProof.\n  intros HUb. induction xs as [ | x xs IH]; intros; cbn in *.\n  - right. auto.\n  - spec_assert IH as [IH | [IH1 IH2]] by auto.\n    + auto.\n    + decide (x = u) as [ <- | Hdec].\n      * left. auto.\n      * right. split.\n        -- intros [<- | H]; congruence.\n        -- intros y [-> | H].\n           ++ specialize (HUb y ltac:(now left)). lia.\n           ++ specialize (IH2 y H). lia.\nQed.\n\n(* We assume that [M] is an upper bound of [s] and [xs]. We also assume that [M] is either in xs, or every element of [x] is smaller than [s]. Then, if [M] is actually a strict upper bound of [xs], then [s] is also a strict upper bound of [xs]. *)\nLemma strict_greatest_upper_bound : forall (xs : list nat) (M s : nat),\n    (In M xs \\/ (M = s /\\ forall x, In x xs -> x <= s)) ->\n    (s <= M) ->\n    (forall x, In x xs -> x < M) ->\n    (forall x, In x xs -> x < s).\nProof.\n  intros xs. induction xs as [ | x xs IH]; intros M s HM1 Hs HM2 y Hy; cbn in *.\n  - auto.\n  - destruct Hy as [ <- | Hy].\n    + destruct HM1 as [ [ <- | HM1] | (->&HM1)]; eauto.\n      * exfalso. specialize (HM2 x ltac:(eauto)). nia.\n      * rewrite HM2; eauto.\n    + destruct HM1 as [ [ <- | HM1] | (->&HM1)]; eauto.\n      exfalso. specialize (HM2 x ltac:(eauto)). nia.\nQed.\n\n\n\n(* ** Tail Recursive Definition *)\n\n(* Compute the maximum of a list and a start-value tail-recursively *)\nFixpoint max_list_rec (s : nat) (xs : list nat) { struct xs } : nat :=\n  match xs with\n  | nil => s\n  | x :: xs' => max_list_rec (max x s) xs'\n  end.\n\n(* We can remove the tail-recursion *)\nLemma max_list_rec_max (xs : list nat) (s1 s2 : nat) :\n  max_list_rec (max s1 s2) xs = max (max_list_rec s1 xs) (max_list_rec s2 xs).\nProof.\n  induction xs as [ | x xs IH] in s1,s2|-*; cbn in *.\n  - reflexivity.\n  - rewrite Max.max_assoc. rewrite !IH. nia.\nQed.\n\n(* If the list is not empty, and every element in the list is greater than start-values [s1] and [s2], then the choice of start-value [s1] or [s2] doesn't matter *)\nLemma max_list_rec_irrelevant (xs : list nat) (s1 s2 : nat) :\n  xs <> nil ->\n  (forall x, In x xs -> s1 <= x /\\ s2 <= x) ->\n  max_list_rec s1 xs = max_list_rec s2 xs.\nProof.\n  induction xs as [ | x xs IH]; intros Hneq Hxs; cbn in *.\n  - congruence.\n  - pose proof (Hxs x ltac:(auto)) as [Hxs1 Hxs2].\n    destruct xs as [ | x' xs].\n    + cbn. nia.\n    + rewrite !max_list_rec_max. rewrite IH; eauto. congruence.\nQed.\n\n(* The maximum is always greater or equal than the start-value *)\nLemma max_list_rec_ge (xs : list nat) (s : nat) :\n  s <= max_list_rec s xs.\nProof.\n  induction xs as [ | x' xs IH] in s|-*; cbn.\n  - reflexivity.\n  - rewrite <- IH. nia.\nQed.\n\n(* The maximum is greater or equal than every element in the list *)\nLemma max_list_rec_ge_el (xs : list nat) (s : nat) (x : nat) :\n  In x xs ->\n  x <= max_list_rec s xs.\nProof.\n  induction xs as [ | x' xs IH] in s,x|-*; intros Hel; cbn in *.\n  - tauto.\n  - destruct Hel as [ <- | Hel].\n    + rewrite max_list_rec_max. rewrite <- Nat.le_max_l. apply max_list_rec_ge.\n    + rewrite max_list_rec_max. rewrite <- IH; eauto. nia.\nQed.\n\nCorollary max_list_rec_ge_el_ge (xs : list nat) (s : nat) (x y : nat) :\n  In y xs ->\n  x <= y ->\n  x <= max_list_rec s xs.\nProof. intros. rewrite <- (max_list_rec_ge_el _ H); eauto. Qed.\n\n\n(* [max_list_rec] is monotone w.r.t. the start value *)\nLemma max_list_rec_monotone (xs : list nat) (s0 s1 : nat) :\n  s0 <= s1 ->\n  max_list_rec s0 xs <= max_list_rec s1 xs.\nProof.\n  revert s0 s1. induction xs as [ | x' xs' IH]; intros; cbn in *.\n  - assumption.\n  - rewrite IH; eauto. nia.\nQed.\n\n(* ... and also w.r.t. the lists *)\nLemma max_list_rec_monotone' (xs1 xs2 : list nat) (s0 s1 : nat) :\n  (Forall2 le xs1 xs2) ->\n  s0 <= s1 ->\n  max_list_rec s0 xs1 <= max_list_rec s1 xs2.\nProof.\n  intros H. revert s0 s1. induction H; intros; cbn.\n  - assumption.\n  - rewrite IHForall2. apply max_list_rec_monotone.\n    instantiate (1 := Init.Nat.max x s0). all:nia. \nQed.\n\n(* [max_list_rec] is a lower bound of [z], if every element is smaller than [z]. *)\nLemma max_list_rec_lower_bound (xs : list nat) (s : nat) (z : nat) :\n  s <= z ->\n  (forall x, In x xs -> x <= z) ->\n  max_list_rec s xs <= z.\nProof.\n  revert s z. induction xs as [ | x xs IH]; intros s z Hz Hxs; cbn in *.\n  - assumption.\n  - pose proof (Hxs x ltac:(eauto)) as Hxs'.\n    rewrite max_list_rec_max. rewrite !IH by eauto. nia.\nQed.\n\nCorollary max_list_rec_max' (xs : list nat) (s1 s2 : nat) :\n  max_list_rec (Init.Nat.max s1 s2) xs = Init.Nat.max s1 (max_list_rec s2 xs).\nProof.\n  apply Nat.le_antisymm.\n  - apply max_list_rec_lower_bound; eauto.\n    + apply Nat.max_le_compat_l. apply max_list_rec_ge.\n    + intros x Hx. rewrite <- Max.le_max_r. now apply max_list_rec_ge_el.\n  - rewrite max_list_rec_max.\n    apply Nat.max_le_compat; auto.\n    apply max_list_rec_ge.\nQed.\n\nCorollary max_list_rec_max'' (xs : list nat) (s1 s2 : nat) :\n  max_list_rec (Init.Nat.max s1 s2) xs = Init.Nat.max (max_list_rec s1 xs) s2.\nProof.\n  apply Nat.le_antisymm.\n  - apply max_list_rec_lower_bound; eauto.\n    + apply Nat.max_le_compat_r. apply max_list_rec_ge.\n    + intros x Hx. rewrite <- Max.le_max_l. now apply max_list_rec_ge_el.\n  - rewrite max_list_rec_max.\n    apply Nat.max_le_compat; auto.\n    apply max_list_rec_ge.\nQed.\n\nCorollary max_list_rec_idem s xs :\n  max_list_rec (max_list_rec s xs) xs = max_list_rec s xs.\nProof.\n  apply Nat.le_antisymm.\n  - apply max_list_rec_lower_bound; eauto. intros. now apply max_list_rec_ge_el.\n  - apply max_list_rec_lower_bound; eauto.\n    + now rewrite <- !max_list_rec_ge.\n    + intros. rewrite <- max_list_rec_ge. now apply max_list_rec_ge_el.\nQed.\n\n(* Either the maximum (with start-value [s]) is in the list, or it is equal to [s] and [s] is greater (or equal) than every element *)\nLemma max_list_rec_el_or_eq xs s :\n  max_list_rec s xs el xs \\/ max_list_rec s xs = s /\\ (forall x : nat, x el xs -> x <= s).\nProof.\n  revert s. induction xs as [ | x xs IH]; intros; cbn in *; eauto.\n  rewrite !max_list_rec_max.\n  assert (max_list_rec s xs <= max_list_rec x xs \\/ max_list_rec x xs <= max_list_rec s xs) as [H|H] by lia.\n  - rewrite !max_l by assumption.\n    specialize (IH x) as [IH|[<- IH]].\n    + left. eauto.\n    + rewrite !max_list_rec_idem. auto.\n  - rewrite !max_r by assumption.\n    specialize (IH s) as [IH|[<- IH]].\n    + left. eauto.\n    + right. split.\n      * apply max_list_rec_idem.\n      * intros y [<-|Hy].\n        -- rewrite <- H. apply max_list_rec_ge.\n        -- now apply IH.\nQed.\n\n(* This, is [max_list_rec s xs] is a strict upper bound, so is [s] *)\nCorollary max_list_rec_gt xs s :\n  (forall y : nat, y el xs -> y < max_list_rec s xs) ->\n  forall y : nat, y el xs -> y < s.\nProof.\n  intros.\n  apply strict_greatest_upper_bound with (M := max_list_rec s xs) (xs := xs); eauto.\n  - apply max_list_rec_el_or_eq.\n  - apply max_list_rec_ge.\nQed.\n\n(* ... and also [s] is equal to [max_list_rec s xs]. *)\nCorollary max_list_rec_gt' xs s :\n  (forall x : nat, x el xs -> x < max_list_rec s xs) ->\n  max_list_rec s xs = s /\\ (forall x : nat, x el xs -> x < s).\nProof.\n  split.\n  - revert H. generalize (max_list_rec_ge xs s) as L1.\n    set (m := (max_list_rec s xs)). intros.\n    enough (m <= s) by nia.\n    apply max_list_rec_lower_bound; auto.\n    intros x Hx.\n    apply Nat.lt_le_incl.\n    eapply max_list_rec_gt; eauto.\n  - now apply max_list_rec_gt.\nQed.\n\n(* To conclude, either the maximum is euqal to the start value (and s is a strict upper bound), or the maximum is actually in the list *)\nCorollary max_list_rec_In (xs : list nat) (s : nat) :\n  (max_list_rec s xs = s /\\ forall x, In x xs -> x < s) \\/\n  In (max_list_rec s xs) xs.\nProof.\n  pose proof @upperBound_In xs (max_list_rec s xs).\n  spec_assert H as [H | [H1 H2]].\n  - intros. now apply max_list_rec_ge_el.\n  - now right.\n  - left. now apply max_list_rec_gt'.\nQed.\n\n\n(* ** Definition of the maximum of a list *)\n\n\n(* We simply instantiate the accu to [0] *)\nDefinition max_list (xs : list nat) := max_list_rec 0 xs.\n\n(* The main lemmas can be simplified now *)\nLemma max_list_ge (xs : list nat) (x : nat) :\n  In x xs ->\n  x <= max_list xs.\nProof. intros. unfold max_list. rewrite <- max_list_rec_ge_el; eauto. Qed.\n\nLemma max_list_lower_bound (xs : list nat) (z : nat) :\n  (forall x, In x xs -> x <= z) ->\n  max_list xs <= z.\nProof. intros. unfold max_list. apply max_list_rec_lower_bound. lia. auto. Qed.\n\nLemma max_list_monotone (f : nat -> nat) (xs : list nat) :\n  (forall x, x <= f x) ->\n  max_list xs <= max_list (map f xs).\nProof.\n  intros. apply max_list_lower_bound.\n  intros x Hx. rewrite H. apply max_list_ge. apply in_map_iff. eauto.\nQed.\n\n(* If the list is not empty, then the maximum is in the list *)\nLemma max_list_In (xs : list nat) :\n  xs <> nil ->\n  In (max_list xs) xs.\nProof.\n  destruct xs as [ | x xs]; [ congruence | intros _].\n  pose proof max_list_rec_In (x :: xs) 0 as [ (_&Absurd) | NotSoAbsurd ].\n  - exfalso. specialize (Absurd x ltac:(auto)). lia.\n  - apply NotSoAbsurd.\nQed.\n\n\n(* ** Maximum of a function *)\n\n(* A size of a largest element in a list, w.r.t. to a size function *)\nSection max_list_map.\n  Variable (X : Type) (f : X -> nat).\n\n  Definition max_list_map (xs : list X) := max_list (map f xs).\n\n  (* This version may be useful sometimes *)\n  Definition max_list_map_rec (s : nat) (xs : list X) := max_list_rec s (map f xs).\n\n  Lemma max_list_map_ge (xs : list X) (x : X) :\n    In x xs ->\n    f x <= max_list_map xs.\n  Proof. intros. unfold max_list_map. apply max_list_ge. apply in_map_iff. eauto. Qed.\n\n  Lemma max_list_map_lower_bound (xs : list X) (z : nat) :\n    (forall x, In x xs -> f x <= z) ->\n    max_list_map xs <= z.\n  Proof. intros. unfold max_list_map. apply max_list_lower_bound. intros ? (?&<-&?) % in_map_iff. auto. Qed.\n\n  Lemma max_list_map_In (xs : list X) :\n    xs <> nil ->\n    exists x, f x = max_list_map xs /\\ In x xs.\n  Proof.\n    intros Hnil.\n    apply in_map_iff.\n    apply max_list_In.\n    destruct xs; cbn in *; congruence.\n  Qed.\n\nEnd max_list_map.\n\n(* [max_list_map] is monotone w.r.t. the function *)\nLemma max_list_map_monotone (X : Type) (f1 f2 : X -> nat) (xs : list X) :\n  (forall (x : X), In x xs -> f1 x <= f2 x) ->\n  max_list_map f1 xs <= max_list_map f2 xs.\nProof.\n  intros. unfold max_list_map. apply max_list_lower_bound.\n  intros ? (x&<-&?) % in_map_iff. rewrite H. apply max_list_ge. apply in_map_iff. eauto. auto.\nQed.\n", "meta": {"author": "uds-psl", "repo": "time-invariance-thesis-for-L", "sha": "41f4eb1f788cc4f096d9c7c286c9ca907588859f", "save_path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L", "path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L/time-invariance-thesis-for-L-41f4eb1f788cc4f096d9c7c286c9ca907588859f/theories/TM/PrettyBounds/MaxList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7166501051893432}}
{"text": "Require Import BuiltIn.\nRequire Import Relation_Definitions.\n\nOpen Scope Z_scope.\n\n(* Idea of the proof: by induction on (range := max_index - min_index)\nThe general proof of raising_order statement is in several steps:\n- change the lemmas in order to get min_index and range instead of min_index and max_index\n- prove raising_order_induction via trivial induction on range and use of transitive property\n  lt_trans\n- adapt this result to our use case *)\n\n(* First proving a general lemma proving that a simple raising order is true for\n   all types having a transitive relation *)\nLemma raising_order_induction:\n  forall (T: Type) (f: int -> T) (lt_T: relation T) (lt_trans: transitive T lt_T)\n    range min_index\n    (* Raising Order hypothesis *)\n    (Harr: forall k : int, min_index <= k <= min_index + Z.of_nat range ->\n      k + 1 <= min_index + Z.of_nat range -> lt_T (f k) (f (k + 1))),\n  (* New raising order conclusion *)\n  forall (i j: int)\n    (Hij: i < j)\n    (Hjrange: min_index <= j <= min_index + Z.of_nat range)\n    (Hirange: min_index <= i <= min_index + Z.of_nat range),\n      lt_T (f i) (f j).\nProof.\ninduction range; intros.\n\n(* Base case *)\n{\n assert (i = min_index) by (rewrite Nat2Z.inj_0 in Hirange; omega).\n assert (j = min_index) by (rewrite Nat2Z.inj_0 in Hjrange; omega).\n subst. destruct (Z.lt_irrefl _ Hij).\n}\n\n(* Induction case *)\n{\n (* There are 2 cases:\n  - we can use the induction hypothesis directly because j <= min_index + range\n  - we cannot because j = min_index + range + 1 *)\n assert (Hcase: j <= min_index + Z_of_nat range \\/ j = min_index + Z_of_nat (S range)).\n {\n  rewrite Nat2Z.inj_succ in Hjrange.\n  rewrite <- Zplus_succ_r_reverse in Hjrange.\n  destruct Hjrange. eapply Z.le_succ_r in H0. intuition. right. subst. simpl.\n  rewrite Zpos_P_of_succ_nat. omega.\n }\n\n destruct Hcase as [Hjless | Hjeq].\n (* First case is easily proved *)\n {\n  eapply IHrange; destruct Hjrange; eauto; try omega.\n  intros. eapply Harr; simpl; intuition. rewrite Zpos_P_of_succ_nat. omega.\n  rewrite Zpos_P_of_succ_nat. omega.\n }\n\n {\n  assert (lt_T (f (j - 1)) (f j)).\n  (* Some ugly transformation to get the property we need *)\n  {\n   pose (a := j-1). replace j with (a + 1).\n   replace (a + 1 - 1) with a.\n   eapply Harr; unfold a; eauto; try omega. omega.\n   unfold a. omega.\n  }\n\n  (* Again we need two cases *)\n  assert (j = i + 1 \\/ i < (j - 1)) by omega.\n\n  destruct H0.\n  (* First case is easy *)\n  { rewrite H0. eapply (Harr i); eauto. rewrite <- Hjeq. rewrite H0. omega. }\n\n  {\n   eapply lt_trans with (f (j - 1)); eauto.\n\n   (* Adapted Harr_rec to use the induction hyptohesis *)\n   assert (Harr_rec: forall k : int,\n           min_index <= k <= min_index + Z.of_nat range ->\n           k + 1 <= min_index + Z.of_nat range -> lt_T (f k) (f (k + 1))).\n   {\n    intros. eapply Harr.\n    intuition. eapply Z.le_trans; eauto. simpl. rewrite Zpos_P_of_succ_nat. omega.\n    eapply Z.le_trans; eauto. simpl. rewrite Zpos_P_of_succ_nat. omega.\n   }\n\n   (* Use induction hypothesis and prove last details *)\n   eapply (IHrange min_index Harr_rec i (j-1)); try eapply H0; eauto; try omega.\n   replace (Z.of_nat range) with (Z.of_nat (S range) - 1). omega.\n   simpl Z.of_nat. rewrite Zpos_P_of_succ_nat. omega.\n   replace (Z.of_nat range) with (Z.of_nat (S range) - 1). omega.\n   simpl Z.of_nat. rewrite Zpos_P_of_succ_nat. omega.\n  }\n }\n}\nQed.\n\n(* This is just adapting raising_order_induction to remove range from the statement *)\nLemma generic_raising_order:\n  forall (T: Type) (lt_T: relation T) (lt_trans: transitive T lt_T) (f : int -> T) max_int min_int\n    (Harr: forall i (Hirange: min_int <= i <= max_int), i + 1 <= max_int ->\n      lt_T (f i) (f (i + 1))),\n    forall i (Hirange: min_int <= i <= max_int) j (Hjrange: min_int <= j <= max_int),\n      i < j -> lt_T (f i) (f j).\nProof.\nintros.\npose (range := max_int - min_int).\nassert (max_int = min_int + range). unfold range. omega.\nrewrite H0 in *.\nassert (Hrange: 0 <= range) by (unfold range in *; omega).\ngeneralize (IZN range Hrange). intros Hex. destruct Hex as (n, Hn).\nrewrite Hn in *. eapply raising_order_induction; eauto.\nQed.\n\n(* This is just replacing the raising order hypothesis with the\n   exact right one. (Should be about (i-1) and i not i and (i + 1) *)\nLemma generic_raising_order_minus:\n  forall (T: Type) (lt_T: relation T) (lt_trans: transitive T lt_T) (f : int -> T) max_int min_int\n    (Harr: forall i (Hirange: min_int <= i <= max_int), i - 1 >= min_int ->\n      lt_T (f (i - 1)) (f i)),\n    forall i (Hirange: min_int <= i <= max_int) j (Hjrange: min_int <= j <= max_int),\n      i < j -> lt_T (f i) (f j).\nProof.\nintros.\npose (range := max_int - min_int).\nassert (max_int = min_int + range). unfold range. omega.\nrewrite H0 in *.\nassert (Hrange: 0 <= range) by (unfold range in *; omega).\ngeneralize (IZN range Hrange). intros Hex. destruct Hex as (n, Hn).\nrewrite Hn in *. eapply raising_order_induction; eauto.\nintros. assert (k = (k + 1) - 1). ring.\nrewrite H3. replace  (k + 1 - 1 + 1) with (k + 1) by ring.\neapply Harr; intuition.\nQed.\n", "meta": {"author": "florianschanda", "repo": "why3", "sha": "dc0d2720d58c6d130b9c3e1db820a07275a133eb", "save_path": "github-repos/coq/florianschanda-why3", "path": "github-repos/coq/florianschanda-why3/why3-dc0d2720d58c6d130b9c3e1db820a07275a133eb/lib/coq/spark/SPARK_Raising_Order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7166500882704009}}
{"text": "Require Export lecture3.\n\n(* # Contents *)\n(*\nIn this lecture, we will be formalizing a separation logic for the ML-like\nlanguage that we discussed in the second lecture. The topics that we discuss\nduring the lecture are as follows:\n\n- Separation logic\n- Deep embedding versus shallow embedding\n- Weakest preconditions\n*)\n(* # Separation logic *)\n(*\nThe syntax of our separation logic is as follows:\n\n  P, Q ::= emp\n         | P ** Q | P -* Q\n         | emp | l ~> v\n         | All x, P | Ex x, P |\n         | wp e (fun v => Q)\n\nWe will not explain all of these connectives in detail right immediately. The\nsemantics of most will be described in the course of this lecture, accompanied\nby a formal description in Coq. However, we will highlight the core connectives\nof separation logic, whose informal semantics is as follows:\n\n  l ~> v := _the points-to connective_\n            the memory consists of exactly one location `l` with value `v`\n\n  P ** Q := _separating conjunction_\n            the memory can be split into two _disjoint_ parts, so that the\n            first satisfies P and the second satisfies Q\n\n  emp    := _the empty connective_\n            the memory is empty\n\nUsing these connectives, one can give very precise descriptions of memory\nfootprints, for example:\n\n  l1 ~> 6 ** l2 ~> 8\n  \\Ex v, l1 ~> v ** l2 ~> 2 * v\n\nThe first example describes a memory that consists of two locations `l1` and\n`l2` that respectively contain the values 6 and 8. Since the separation\nconjunction `P ** Q` ensures that the parts of the memory described by `P` and\n`Q` are disjoint, we know that `l1` and `l2` are in different (i.e. they do not\nalias). This makes separating conjunction very different from conjunction\n`P /\\ Q`, which says that `P` and `Q` both hold for the same memory. \n\nThe second example describes the memories that contain two different locations\n`l1` and `l2`, so that the value of `l2` is twice that of `l1`.\n\nMaking use of separating conjunction, we can give very concise specifications of\nprograms that manipulate pointers, for example, take the following Hoare logic\nspecification of the swap function:\n\n  {{ l ~> v ** k ~> w }} swap l k {{ l ~> w ** k ~> v }}\n     ^                               ^\n   precondition                     postcondition\n\nThis specification expresses that swap is indeed swapping, as witnessed by the\nfact that the values of the locations `l` and `k` have been swapped. But apart\nfrom that, it also expresses in the precondition that the locations `l` and `k`\nshould be different before executing the program, and in the postcondition\nthat these are still different.\n*)\n\n(* # Shallow embedding versus deep embedding *)\n(*\nIn the second lecture, we have already seen how we could use Coq to model a\nprogramming language. In that section, we started by defining a _syntax_ for\nour language in terms of an inductive type, and then gave an operational\nsemantics for this language. The approach of first defining a syntax is called\na _deep embedding_.\n\nIn this section, we proceed differently: we are not going to define an explicit\nsyntax for our separation logic. Instead, we are going to define the connectives\nof our separation logic directly by their _semantic interpretation_.  This is\ncalled a _shallow embedding_.\n*)\n\n(* # Shallow embedding of separation logic *)\n(*\nThe first question that we need to answer is: what will be the semantic\ninterpretation of the connectives of our separation logic? As we have just seen,\nformulas in separation logic describe sets of memories. For example:\n\n  \\Ex v, l1 ~> v ** l2 ~> 2 * v\n\nDescribes describes all memories that contain two different locations `l1` and\n`l2`, so that the value of `l2` is twice that of `l1`.\n\nThe natural way to describe sets of memories in Coq is by means of a predicate:\n*)\nDefinition iProp := mem -> Prop.\n\n(*\nNow, let us try to give a semantic interpretation of separating conjunction.\nFor this, recall the informal description of `P ** Q`: the memory can be split\ninto two _disjoint_ parts, so that the first satisfies `P` and the second\nsatisfies `Q`. In the previous lecture we put a lot of effort in formalizing\ndisjointness and unions of finite maps. Since our memories are represented as\nfinite maps, that effort will pay of now:\n*)\nDefinition iSep (P Q : iProp) : iProp := fun m =>\n  exists m1 m2, m = munion m1 m2 /\\ mdisjoint m1 m2 /\\ P m1 /\\ Q m2.\nNotation \"P ** Q\" := (iSep P Q) (at level 80, right associativity).\n\n(*\nRecall that in predicates are functions. So, to construct an element of type\n`iProp` (i.e. `mem -> Prop`) we use a lambda abstraction of Coq.\n\nIn order to write down separation logic propositions in a concise way, we use\nthe `Notation` command to setup Coq's parser and pretty printer.\n*)\n\n(*\nIn the same spirit as separating conjunction, we can now describe the points-to\nconnective and the empty connective. These definitions crucially relies on the\nsingleton finite map `msingleton l v` and the empty finite map `mempty` that we\nhave defined in the first lecture.\n*)\nDefinition points_to (l : nat) (v : val) : iProp := fun m =>\n  m = msingleton l v.\nNotation \"l ~> v\" := (points_to l v) (at level 20).\n\nDefinition iEmp : iProp := fun m => m = mempty.\nNotation \"'emp'\" := iEmp.\n\n(*\nTogether with separating conjunction, we have a corresponding form of\nimplication: the magic wand `P -* Q`. It describes the memories described by `Q`\nminus those described by `P`, i.e., it describes the memories such that, if you\n(disjointly) add memories satisfying `P`, you obtain resources satisfying `Q`.\n*)\nDefinition iWand (P Q : iProp) : iProp := fun m =>\n  forall m2, mdisjoint m2 m -> P m2 -> Q (munion m2 m).\nNotation \"P -* Q\" :=\n  (iWand P Q) (at level 99, Q at level 200, right associativity).\n\n(*\nFinally, we lift the quantifiers of Coq into our separation logic. Note that\nwe use the functions of Coq to represent the binder.\n*)\nDefinition iForall {A} (P : A -> iProp) : iProp := fun m => forall x, P x m.\nNotation \"'All' x1 .. xn , P\" :=\n  (iForall (fun x1 => .. (iForall (fun xn => P)) ..))\n  (at level 200, x1 binder, xn binder, right associativity).\n\nDefinition iExists {A} (P : A -> iProp) : iProp := fun m => exists x, P x m.\nNotation \"'Ex' x1 .. xn , P\" :=\n  (iExists (fun x1 => .. (iExists (fun xn => P)) ..))\n  (at level 200, x1 binder, xn binder, right associativity).\n\n(*\nIn order to express mathematical statements in our separation logic (for as\nequality, that a number is even, ...), we will now define an embedding of Coq\npropositions (type `Prop`) into the propositions of our separation logic (type\n`iProp`). We define this using (higher-order) existential quantification.\n*)\nDefinition iPure (p : Prop) : iProp := Ex _ : p, emp.\nNotation \"@[ p ]\" := (iPure p) (at level 20, p at level 200).\n\n(* ## Weakest preconditions and Hoare triples *)\n(*\nSo far, we have defined basic logical connectives of our separation logic. But\nlast, but not least, we of course need some way of expressing properties of\nprograms. We do this using Hoare triples:\n\n  {{ P }} e {{ Q }}\n\nIn this lecture, we consider Hoare triples for total program correctness, so the\nintuitive meaning of the Hoare triple is:\n\n  If the precondition holds for the memory before hand, then the\n  expression `e` results in a value `v`, such that `Q v` holds.\n\nNote that our postconditions have type `val -> iProp`, which allows us to\ntalk about the result value of an expression. For example:\n\n  {{ l ~> v ** k ~> w }}\n    swap l k\n  {{ fun v => @[ v = VUnit ] ** l ~> w ** k ~> v }}\n\nInstead of defining Hoare triples directly, we first define the notion of\nweakest preconditions.\n\n  wp e Q\n\nAnd then define Hoare triples as :\n\n  {{ P }} e {{ Q }} := P |- wp e Q\n\nWhere |- is the point-wise entailment of `iProp`:\n*)\n\nDefinition iEntails (P Q : iProp) : Prop := forall m, P m -> Q m.\nNotation \"P |- Q\" := (iEntails P Q) (at level 99, Q at level 200).\n\n(*\nNow, before we give the formal definition of weakest preconditions, there is\none final catch. An important part of separation logic is that we have the\nso-called _framing_ rule:\n\n        {{ P }} e {{ Q }}\n  -----------------------------\n   {{ P ** R }} e {{ P ** R }}\n\nLet us see this rule in action. As we have seen before, we can give the\nfollowing specification to the swap function:\n\n  {{ l ~> v ** k ~> w }} swap l k {{ l ~> w ** k ~> v }}\n\nThis specification looks overly restrictive as the pre- and post-condition say\nthat the memory should exactly contain the locations `l` and `k`. However,\nusing the frame rule, we can derive also:\n\n  {{ l ~> v ** k ~> w ** R }} swap l k {{ l ~> w ** k ~> v ** R }}\n\nWhere `R` is any formula of separation logic, for example, `k' ~> w'` for\nsome other location `k'`. As we see here, the frame rule allows us to reason\nlocally: we can state and prove specifications with a small memory footprint,\nand then use framing to extend them to bigger memory footprints, so that we can\nuse the specification in larger contexts too.\n\nIn order to make sure that we can prove the framing rule, the definition of\nweakest preconditions becomes slightly more complicated. We also have to\nqualify over all possible frames `mf`:\n*)\nDefinition wp (e : expr) (Q : val -> iProp) : iProp := fun m =>\n  forall mf, mdisjoint m mf ->\n    exists m' v, mdisjoint m' mf /\\\n                 big_step e (munion m mf) v (munion m' mf) /\\\n                 Q v m'.\n\nDefinition hoare (P : iProp) (e : expr) (Q : val -> iProp) : Prop :=\n  P |- wp e Q.\n\n(* # Basic rules of the logic *)\n(*\nLet us first prove that entailment |- is a pre-order, i.e. it is reflexive and\ntransitive. These properties are crucial to compose proofs.\n*)\nLemma iEntails_refl P : P |- P.\nProof.\n  unfold iEntails.\n  intros m Hm.\n  assumption.\nQed.\nLemma iEntails_trans P Q R : (P |- Q) -> (Q |- R) -> P |- R.\nProof.\n  (* Note that we do not really have to unfold `iEntails`: the `intros` tactic\n  will do that for us. *)\n  intros HPQ HQR m HP. apply HQR. apply HPQ. assumption.\nQed.\n\n(* ## Rules for separating conjunction *)\n(*\nWe now prove the key properties of separating conjunction: monotonicity, the\nidentity laws w.r.t. `emp`, commutativity, and associativity.\n*)\nLemma iSep_mono_l P1 P2 Q : (P1 |- P2) -> P1 ** Q |- P2 ** Q.\nProof.\n  intros HP m Hm.\n  unfold iSep in Hm.\n  destruct Hm as [m1 Hm].\n  destruct Hm as [m2 Hm].\n  destruct Hm as [Heq Hm].\n  destruct Hm as [Hdisj Hm].\n  destruct Hm as [HPm1 HQm2].\n(* As we see, writing down this sequence of existential and conjunction\neliminations becomes pretty tedious. It requires many tactics, and we have to\nname all the auxiliary results. Fortunately, Coq allows us to nest these\n`destruct`s in the following way. *)\nRestart.\n  intros HP m Hm.\n  unfold iSep in Hm.\n  destruct Hm as [m1 [m2 [Heq [Hdisj [HPm1 HQm2]]]]].\n(* This is much shorter, but still results in a lot of brackets. Coq provides\nyet another syntax to make this more concise. *)\nRestart.\n  intros HP m Hm.\n  unfold iSep in Hm.\n  destruct Hm as (m1 & m2 & Heq & Hdisj & HPm1 & HQm2).\n(*\nThe syntax `(x1 & x2 & ... & xn)` is just sugar for `[x1 [x2 [... [xn-1 xn]]]]`.\n\nAnd finally, we can even perform the eliminations directly while introducing:\n*)\nRestart.\n  intros HP m (m1 & m2 & Heq & Hdisj & HP1 & HQ).\n  subst m.\n  unfold iSep.\n  exists m1, m2.\n  split.\n  { reflexivity. }\n  split.\n  { assumption. }\n  split.\n  { apply HP. assumption. }\n  assumption.\nRestart.\n(* Or to make the proof even shorter, we can use `eauto`, which uses all\nhypotheses (including implications, like the entailment) in the context by\ndefault. *)\n  intros HP m (m1 & m2 & Heq & Hdisj & HPm1 & HQm2).\n  subst m. unfold iSep. eauto 10.\nQed.\nLemma iSep_comm P Q : P ** Q |- Q ** P.\nProof.\n  intros m (m1 & m2 & Heq & Hdisj & HP & HQ).\n  exists m2, m1.\n  rewrite <-munion_comm by assumption.\n  auto using mdisjoint_sym.\nQed.\nLemma iSep_assoc P Q R : P ** (Q ** R) |- (P ** Q) ** R.\nProof.\n  intros m (m1 & m' & Heq & Hdisj & HP & (m2 & m3 & Heq' & Hdisj' & HQ & HR)).\n  subst.\n  exists (munion m1 m2), m3. split.\n  { rewrite munion_assoc. reflexivity. }\n  split.\n  { eauto using mdisjoint_union_l, mdisjoint_union_inv_rr. }\n  split.\n  { exists m1, m2. eauto using mdisjoint_union_inv_rl. }\n  assumption.\nQed.\n\n(** ### Exercise *)\n(*\nProve the following laws.\n*)\nLemma iSep_emp_l P : P |- emp ** P.\nProof. Admitted.\nLemma iSep_emp_l_inv P : emp ** P |- P.\nProof. Admitted.\n\n(* ## Rules for magic wand *)\nLemma iWand_intro_r P Q R : (P ** Q |- R) -> P |- Q -* R.\nProof.\n  intros H m Hm m' ? HQ. apply H. rewrite munion_comm by assumption.\n  exists m, m'; auto using mdisjoint_sym.\nQed.\nLemma iWand_elim P Q : P ** (P -* Q) |- Q.\nProof.\n  intros m (m1 & m2 & ? & ? & ? & ?). subst.\n  apply H2; auto.\nQed.\n\n(* ## Rules for universal quantification *)\nLemma iForall_intro {A} P (Q : A -> iProp) :\n  (forall x, P |- Q x) -> (P |- All x, Q x).\nProof. intros H m HP x. apply H. assumption. Qed.\nLemma iForall_elim {A} (P : A -> iProp) x : (All z, P z) |- P x.\nProof. intros m HP. apply HP. Qed.\n\n(* ## Rules for existential quantification *)\n(* ### Exercise *)\n(*\nProve the following laws.\n*)\nLemma iExist_intro {A} (P : A -> iProp) x : P x |- Ex z, P z.\nProof. Admitted.\nLemma iExist_elim {A} (P : A -> iProp) Q :\n  (forall x, P x |- Q) -> (Ex z, P z) |- Q.\nProof. Admitted.\n\n(* ## Derived rules of the logic *)\n(*\nSo far, we have proved a bunch of rules for our separation logic by unfolding\nthe definition of the separation logic connectives. However, it turns out that\nmany additional rules can be _derived_ from the rules we have seen so far.\n*)\nLemma iSep_emp_r P : P |- P ** emp.\nProof.\n  apply iEntails_trans with (emp ** P).\n  { apply iSep_emp_l. }\n  apply iSep_comm.\nQed.\nLemma iSep_emp_r_inv P : P ** emp |- P.\nProof.\n  apply iEntails_trans with (emp ** P).\n  { apply iSep_comm. }\n  apply iSep_emp_l_inv.\nQed.\n\nLemma iSep_mono_r P Q1 Q2 :\n  (Q1 |- Q2) -> P ** Q1 |- P ** Q2.\nProof.\n  intros HQ. apply iEntails_trans with (Q1 ** P).\n  { apply iSep_comm. }\n  apply iEntails_trans with (Q2 ** P).\n  { apply iSep_mono_l. assumption. }\n  apply iSep_comm.\nQed.\n\n(*** ## Exercise *)\n(*\nProve the following derived laws. Make sure to not unfold the definitions of\nthe connectives of our separation logic, but only use the rules we have already\nproven. Hint: you need to use transitivity of entailment many times.\n*)\nLemma iSep_mono P1 P2 Q1 Q2 :\n  (P1 |- P2) -> (Q1 |- Q2) -> P1 ** Q1 |- P2 ** Q2.\nProof. Admitted.\n\n(* This lemma is quite subtle: you need to use the rules for commutativity,\nassociativity and monotonicity of separating conjunction. I advice to first work\nout the proof on paper, and then do it in Coq. *)\nLemma iSep_assoc' P Q R : (P ** Q) ** R |- P ** (Q ** R).\nProof. Admitted.\n\nLemma iWand_intro_l P Q R : (Q ** P |- R) -> P |- Q -* R.\nProof. Admitted.\n\n(* This lemma is very difficult: you need to use the introduction and\nelimination rules for magic wand `-*`. *)\nLemma iExist_sep {A} (P : A -> iProp) Q :\n  (Ex x, P x) ** Q |- Ex x, P x ** Q.\nProof. Admitted.\n\nLemma iPure_intro (p : Prop) : p -> emp |- @[ p ].\nProof. Admitted.\n\nLemma iPure_elim (p : Prop) P Q : (p -> P |- Q) -> @[ p ] ** P |- Q.\nProof. Admitted.\n\n(* ## Logical rules for weakest preconditions *)\n(*\nWe now prove the framing rule for weakest preconditions. Convince yourself\nthat from this rule, we get the framing rule for Hoare triples.\n\nThe proof below is a bit subtle, as we need to use properties about `munion`\nand `mdisjoint` many times.\n*)\nLemma wp_frame Q R e :\n  wp e Q ** R |- wp e (fun v => Q v ** R).\nProof.\n  intros m (m1 & m2 & Heq & Hdisj & Hwp & HR). subst m.\n  intros mf Hm.\n  destruct (Hwp (munion m2 mf)) as (m' & v & Hdisj' & Hbig & HQ).\n  { eauto using mdisjoint_union_r, mdisjoint_union_inv_ll. }\n  exists (munion m' m2), v. split.\n  { eauto 4 using mdisjoint_union_l, mdisjoint_union_inv_rr, mdisjoint_union_inv_lr. }\n  split.\n  { rewrite <-!munion_assoc. assumption. }\n  exists m', m2. split.\n  { reflexivity. }\n  eauto using mdisjoint_union_inv_rl.\nQed.\n\n(* ### Exercise *)\n(*\nProve the rule below.\n*)\nLemma wp_mono Q R e :\n  (forall v, Q v |- R v) ->\n  wp e Q |- wp e R.\nProof. Admitted.\n\n(* # Structural rules for weakest preconditions *)\nLemma wp_val v Q : Q v |- wp (EVal v) Q.\nProof. intros m HQ mf Hm. exists m, v. eauto with big_step. Qed.\n\nLemma wp_ctx E e Q :\n  wp e (fun w => wp (fill E (EVal w)) Q) |- wp (fill E e) Q.\nProof.\n  intros m Hwp mf Hdisj.\n  destruct (Hwp mf) as (m' & v & Hdisj' & Hbig & Hwp').\n  { assumption. }\n  destruct (Hwp' mf) as (m'' & v'' & Hdisj'' & Hbig' & HQ).\n  { assumption. }\n  eauto 10 using big_step_fill.\nQed.\n\nLemma wp_let x e1 e2 Q :\n  wp e1 (fun v => wp (subst x v e2) Q) |- wp (ELet x e1 e2) Q.\nProof.\n  intros m Hwp mf Hdisj.\n  destruct (Hwp mf Hdisj) as (mf' & v' & Hdisj' & Hbig & Hwp2).\n  destruct (Hwp2 mf Hdisj') as (mf'' & v'' & Hdisj'' & Hbig' & HQ).\n  exists mf'',  v''. eauto with big_step.\nQed.\n\n(* ### Exercise *)\n(*\nProve the rules below: all of these follow the same structure as the proofs\nabove.\n*)\nLemma wp_seq e1 e2 Q :\n  wp e1 (fun _ => wp e2 Q) |- wp (ESeq e1 e2) Q.\nProof. Admitted.\n\nLemma wp_if_true e2 e3 Q :\n  wp e2 Q |- wp (EIf (EVal (VBool true)) e2 e3) Q.\nProof. Admitted.\n\nLemma wp_if_false e2 e3 Q :\n  wp e3 Q |- wp (EIf (EVal (VBool false)) e2 e3) Q.\nProof. Admitted.\n\nLemma wp_while e1 e2 Q :\n  wp (EIf e1 (ESeq e2 (EWhile e1 e2)) (EVal VUnit)) Q |- wp (EWhile e1 e2) Q.\nProof. Admitted.\n\nLemma wp_op op v1 v2 v Q :\n  eval_bin_op op v1 v2 = Some v ->\n  Q v |- wp (EOp op (EVal v1) (EVal v2)) Q.\nProof. Admitted.\n\n(* # Stateful rules for weakest preconditions *)\n(*\nWe finish by proving the rules for the operations of our language that\nmanipulate the state. Let us take a look at the rules for load and store (in\nmixed informal and Coq notations):\n\n  l ~> v ** (l ~> v -* Q v)     |- wp !l Q.\n  l ~> v ** (l ~> w -* Q VUnit) |- wp (!l := w) Q.\n\nSo, what does the second rule say: In order to prove the weakest precondition\nof a store, we have to show that `l` already exists in the memory. This is done\nby showing that we have the points-to connective `l ~> v`. Now, since the only\nway of introducing a separating conjunction is monotonicity, this means we have\nto give up the point-to connective `l ~> v`, which leaves us with\n`l ~> w -* Q VUnit`. By introducing the magic wand, we consequentially get the\npoint-to connective back, but now with the new value `w`.\n\nThe same kind of pattern is used for the other rules.\n*)\nLemma wp_load l v Q :\n  l ~> v ** (l ~> v -* Q v) |- wp (ELoad (EVal (VLoc l))) Q.\nProof.\n  intros m HQ mf Hdisj.\n  destruct HQ as (m1 & m2 & Heq & Hdisj' & Hpointsto & HQ). subst m.\n  unfold points_to in Hpointsto. subst m1.\n  exists (munion (msingleton l v) m2), v. split.\n  { assumption. }\n  split.\n  { eapply Load_big_step.\n    - eapply Val_big_step.\n    - rewrite <-munion_assoc. rewrite munion_lookup.\n      rewrite msingleton_lookup. simpl. reflexivity. }\n  apply HQ.\n  { assumption. }\n  unfold points_to. reflexivity.\nQed.\n\n(* ### Exercise (very difficult) *)\n(*\nProve the rules below: all of these follow the same structure as the proofs\nabove. Hint: you need to make extensive use of properties about finite maps.\nUse Coq's `Search` command to find these. For example:\n*)\nSearch (minsert _ _ (msingleton _ _) = _).\n(*\nYields:\n\n  minsert_singleton:\n    forall (A : Type) (i : nat) (x y : A),\n    minsert i x (msingleton i y) = msingleton i x\n*)\nLemma wp_store l v w Q :\n  l ~> v ** (l ~> w -* Q VUnit) |- wp (EStore (EVal (VLoc l)) (EVal w)) Q.\nProof. Admitted.\n\nLemma wp_alloc v Q :\n  (All l, l ~> v -* Q (VLoc l)) |- wp (EAlloc (EVal v)) Q.\nProof. Admitted.\n\nLemma wp_free l v Q :\n  l ~> v ** Q VUnit |- wp (EFree (EVal (VLoc l))) Q.\nProof. Admitted.\n\n(* # An example *)\n(*\nFinally, we will look at an example. We take the simplest program that\nmanipulates pointers: the swap function.\n*)\n\n(*\n  swap x y :=\n    let tmp := !x in\n    x := !y;\n    y := tmp\n*)\nDefinition swap (x y : val) : expr :=\n  ELet \"tmp\" (ELoad (EVal x))\n    (ESeq (EStore (EVal x) (ELoad (EVal y)))\n          (EStore (EVal y) (EVar \"tmp\"))).\n\n(* Transitivity with the premises swapped *)\nLemma iEntails_trans' P Q R : (Q |- R) -> (P |- Q) -> P |- R.\nProof. eauto using iEntails_trans. Qed.\n\nLemma swap_correct l k v w :\n  hoare\n    (l ~> v ** k ~> w)\n    (swap (VLoc l) (VLoc k))\n    (fun ret => @[ret = VUnit] ** l ~> w ** k ~> v).\nProof.\n  unfold hoare.\n  unfold swap.\n  eapply iEntails_trans'.\n  { apply wp_let. }\n  eapply iEntails_trans'.\n  { apply wp_load. }\n  apply iSep_mono_r. apply iWand_intro_l.\n  simpl.\n  eapply iEntails_trans'.\n  { apply (wp_ctx (SeqCtx _ :: StoreCtxR _ :: nil)). }\n  eapply iEntails_trans'.\n  { apply wp_load. }\n  eapply iEntails_trans'.\n  { apply iSep_comm. }\n  apply iSep_mono_l. apply iWand_intro_r.\n  simpl.\n  eapply iEntails_trans'.\n  { apply (wp_ctx (SeqCtx _ :: nil)). }\n  eapply iEntails_trans'.\n  { apply wp_store. }\n  apply iSep_mono_r. apply iWand_intro_l.\n  simpl.\n  eapply iEntails_trans'.\n  { apply wp_seq. }\n  eapply iEntails_trans'.\n  { apply wp_val. }\n  eapply iEntails_trans'.\n  { apply wp_store. }\n  eapply iEntails_trans'.\n  { apply iSep_comm. }\n  apply iSep_mono_l. apply iWand_intro_r.\n  eapply iEntails_trans.\n  { apply iSep_emp_l. }\n  apply iSep_mono_l.\n  apply iPure_intro.\n  reflexivity.\nQed.\n\n(* # Conclusion *)\n(*\nAs you have seen, proving the correctness of our simple example already takes\na lot of work. For example, we have to:\n\n- Use transitivity of entailment to use the weakest precondition rules.\n- After we have used a rule for a load or store, we have to \"frame\".\n- We often have to reorder the premises on the LHS of the turnstile.\n- We have to pick evaluation contexts ourselves when we use `wp_ctx`.\n\nOf course, most of these steps are completely mechanical, and as such, Coq is\nwell capable of automating this. Unfortunately, automating proofs in separation\nlogic in Coq is beyond the scope of these lectures.\n\nIf you would like to know more about it, please take a look at the following\npaper:\n\n  Robbert Krebbers, Amin Timany and Lars Birkedal\n  Interactive Proofs in Higher-Order Concurrent Separation Logic\n  POPL 2017\n\nIf you want to see separation logic in Coq in practice, try the Iris project,\na state-of-the art higher-order concurrent separation logic that has been\nimplemented and verified in Coq:\n\n  http://iris-project.org\n\n*)\n", "meta": {"author": "mroman42", "repo": "math-dgiim", "sha": "9fe939175c2f702dd18691c35ed22652a92563b7", "save_path": "github-repos/coq/mroman42-math-dgiim", "path": "github-repos/coq/mroman42-math-dgiim/math-dgiim-9fe939175c2f702dd18691c35ed22652a92563b7/code/EuTypes/lecture4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7166500863470565}}
{"text": "(* Exercise 30 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_030 : (exists x, P x \\/ Q x) /\\ (forall x, ~ Q x) -> (exists x, P x).\nProof.\nimp_i a1.\nexi_e (exists x:D, P x \\/ Q x) a a2.\ncon_e1 (forall x:D, ~Q x).\nhyp a1.\ndis_e (P a \\/ Q a) a3 a3.\nhyp a2.\nexi_i a.\nhyp a3.\nneg_e (Q a).\nall_e (forall x:D, ~Q x) a.\ncon_e2 (exists x:D, P x \\/ Q x).\nhyp a1.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred030.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.7166097123329238}}
{"text": "(*using definitions from http://www.math.ucla.edu/~tao/resource/general/121.1.00s/vector_axioms.html *)\n\nRequire Import Reals.Rbase.\nRequire Import Reals.Rfunctions.\n\nModule AxiomaticNormedRealVectorSpace.\n\nInductive rvector (d: nat) : Set :=\n| zero\n| add (x y : rvector d)\n| inverse (x: rvector d)\n| smult (r:R) (x: rvector d).\n\nClass NormedVectorSpace (d: nat) :=\n  {\n    norm:  rvector d -> R;\n\n    rv_axiom_additive : forall x y z : rvector d,\n    (add d x y) = (add d y x)  /\\\n    (add d (add d x y) z) = (add d x (add d y z)) /\\\n    (add d (zero d) x) = (add d x (zero d)) /\\\n    (add d x (zero d)) = x /\\\n    (add d (inverse d x) x) = (add d x (inverse d x)) /\\\n    (add d x (inverse d x)) = zero d;\n\n    rv_axiom_multiplicaive : forall (x : rvector d), forall (b c : R),\n    smult d R0 x = zero d /\\\n    smult d R1 x = x /\\\n    smult d (Rmult b c) x = smult d b (smult d c x);\n\n    rv_axiom_distributive : forall (x y : rvector d), forall (a b : R),\n    smult d b (add d x y) = add d (smult d b x) (smult d b y) /\\\n    smult d (Rplus a b) x = add d (smult d a x) (smult d b x);\n\n    norm_axiom_zero : forall (x:rvector d),\n          norm (zero d) = R0 <-> x=zero d;\n\n    norm_axiom_abs : forall (x: rvector d), forall (a:R), \n    norm (smult d a x) = Rmult (Rabs a) (norm x);\n\n    norm_axiom_add : forall (x y : rvector d),\n    norm (add d x y) = Rplus (norm x) (norm y);\n  }.\n\nEnd AxiomaticNormedRealVectorSpace.\n", "meta": {"author": "IBM", "repo": "FormalML", "sha": "e399d096f1ad572420dbd1c638d593eee2129cbe", "save_path": "github-repos/coq/IBM-FormalML", "path": "github-repos/coq/IBM-FormalML/FormalML-e399d096f1ad572420dbd1c638d593eee2129cbe/coq/NeuralNetworks/AxiomaticNormedRealVectorSpace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7165863027324934}}
{"text": "Require Import ZArith Zpow_facts.\n\nOpen Scope Z_scope.\n\nFixpoint plength (p: positive) : positive :=\n  match p with\n    xH => xH\n  | xO p1 => Pos.succ (plength p1)\n  | xI p1 => Pos.succ (plength p1)\n  end.\n\nTheorem plength_correct: forall p, (Zpos p < 2 ^ Zpos (plength p))%Z.\nassert (F: (forall p, 2 ^ (Zpos (Pos.succ p)) = 2 * 2 ^ Zpos p)%Z).\nintros p; replace (Zpos (Pos.succ p)) with (1 + Zpos p)%Z.\nrewrite Zpower_exp; auto with zarith.\nred; intros; discriminate.\nrewrite Zpos_succ_morphism; unfold Z.succ; auto with zarith.\nintros p; elim p; simpl plength; auto.\nintros p1 Hp1; rewrite F; repeat rewrite Zpos_xI.\nassert (tmp: (forall p, 2 * p = p + p)%Z);\n  try repeat rewrite tmp; auto with zarith.\nintros p1 Hp1; rewrite F; rewrite (Zpos_xO p1).\nassert (tmp: (forall p, 2 * p = p + p)%Z);\n  try repeat rewrite tmp; auto with zarith.\nrewrite Zpower_1_r; auto with zarith.\nQed.\n\nTheorem plength_pred_correct: forall p, (Zpos p <= 2 ^ Zpos (plength (Pos.pred p)))%Z.\nintros p; case (Psucc_pred p); intros H1.\nsubst; simpl plength.\nrewrite Zpower_1_r; auto with zarith.\npattern p at 1; rewrite <- H1.\nrewrite Zpos_succ_morphism; unfold Z.succ; auto with zarith.\ngeneralize (plength_correct (Pos.pred p)); auto with zarith.\nQed.\n\nDefinition Pdiv p q :=\n  match Z.div (Zpos p) (Zpos q) with\n    Zpos q1 => match (Zpos p) - (Zpos q) * (Zpos q1) with\n                 Z0 => q1\n               | _ => (Pos.succ q1)\n               end\n  |  _ => xH\n  end.\n\nTheorem Pdiv_le: forall p q,\n  Zpos p <= Zpos q * Zpos (Pdiv p q).\nintros p q.\nunfold Pdiv.\nassert (H1: Zpos q > 0); auto with zarith.\nassert (H1b: Zpos p >= 0).\n  red; intros; discriminate.\ngeneralize (Z_div_ge0 (Zpos p) (Zpos q) H1 H1b).\ngeneralize (Z_div_mod_eq (Zpos p) (Zpos q) H1); case Z.div.\n  intros HH _; rewrite HH; rewrite Zmult_0_r; rewrite Zmult_1_r; simpl.\ncase (Z_mod_lt (Zpos p) (Zpos q) H1); auto with zarith.\nintros q1 H2.\nreplace (Zpos p - Zpos q * Zpos q1) with (Zpos p mod Zpos q).\n  2: pattern (Zpos p) at 2; rewrite H2; auto with zarith.\ngeneralize H2 (Z_mod_lt (Zpos p) (Zpos q) H1); clear H2;\n  case Zmod.\n  intros HH _; rewrite HH; auto with zarith.\n  intros r1 HH (_,HH1); rewrite HH; rewrite Zpos_succ_morphism.\n  unfold Z.succ; rewrite Zmult_plus_distr_r; auto with zarith.\n  intros r1 _ (HH,_); case HH; auto.\nintros q1 HH; rewrite HH.\nunfold Z.ge; simpl Z.compare; intros HH1; case HH1; auto.\nQed.\n\nDefinition is_one p := match p with xH => true | _ => false end.\n\nTheorem is_one_one: forall p, is_one p = true -> p = xH.\nintros p; case p; auto; intros p1 H1; discriminate H1.\nQed.\n\nDefinition get_height digits p :=\n  let r := Pdiv p digits in\n   if is_one r then xH else Pos.succ (plength (Pos.pred r)).\n\nTheorem get_height_correct:\n  forall digits N,\n   Zpos N <= Zpos digits * (2 ^ (Zpos (get_height digits N) -1)).\nintros digits N.\nunfold get_height.\nassert (H1 := Pdiv_le N digits).\ncase_eq (is_one (Pdiv N digits)); intros H2.\nrewrite (is_one_one _ H2) in H1.\nrewrite Zmult_1_r in H1.\nchange (2^(1-1))%Z with 1; rewrite Zmult_1_r; auto.\nclear H2.\napply Z.le_trans with (1 := H1).\napply Zmult_le_compat_l; auto with zarith.\nrewrite Zpos_succ_morphism; unfold Z.succ.\nrewrite Zplus_comm; rewrite Zminus_plus.\napply plength_pred_correct.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-coqprime/coq-coqprime.1.0.3/src/Coqprime/num/Bits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7165439444649243}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf3 : natural) (lf2 : natural) : natural :=\n  plus z (plus lf2 lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_assoc/goal33conj162_coqofml_8KxVzz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7165439407251295}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export IndProp.\n\nDefinition relation (X: Type) := X -> X -> Prop.\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold not. unfold partial_function. intros Hc.\n  assert (0 = 1) as Nonsense. {\n    apply Hc with (x := 0).\n    - apply le_n.\n    - apply le_S. apply le_n. }\n  discriminate Nonsense. Qed.\n  \nTheorem total_relation_not_a_partial_function:\n  ~ (partial_function total_relation).\nProof.\n  unfold not. unfold partial_function. intros.\n  \n  assert (0=1) as shit. {\n  apply H with (x:=0).\n  - apply tot_rel.\n  - apply tot_rel. \n  }\n  inversion shit.\nQed.  \n\nTheorem empty_relation_partial_function:\n  partial_function empty_relation.\nProof.\n  unfold partial_function. intros. inversion H.\nQed.\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\nTheorem le_reflexive :\n  reflexive le.\nProof.\n  unfold reflexive. intros n. apply le_n. Qed.\n  \nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, (R a b) -> (R b c) -> (R a c).\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  - (* le_n *) apply Hnm.\n  - (* le_S *) apply le_S. apply IHHmo. Qed.\n\nTheorem lt_trans:\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  apply le_S in Hnm.\n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. Qed.\n  \nTheorem lt_trans' :\n  transitive lt.\nProof.\n  (* Prove this by induction on evidence that m is less than o. *)\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [| m' Hm'o].\n  - apply le_S in Hnm. apply Hnm.\n  - apply le_S in IHHm'o. apply IHHm'o.\nQed.\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  - inversion Hmo.\n  - apply le_S in Hnm.\n    apply le_trans with (a := (S n)) (b := (S m)) (c := (S o')).\n  -- apply Hnm. -- apply Hmo.\nQed.\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof.\n  intros n m H. apply le_trans with (S n).\n  - apply le_S. apply le_n.\n  - apply H.\nQed.\n\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  intros. inversion H.\n  - apply le_n.\n  - apply le_Sn_le in H1. apply H1.\nQed.\n\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n  unfold not. intros. induction n.\n  - inversion H. - apply IHn. apply le_S_n in H. apply H.\nQed.\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n  \nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  unfold not. unfold symmetric. intros.\n  assert (1<=0) as shit.\n  {intros. apply H. apply n_le_Sn.\n  }\n  inversion shit.\nQed.\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n  \nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  intros a b. generalize dependent a. induction b.\n  - intros. inversion H. reflexivity.\n  - intros. destruct a.\n  -- inversion H0.\n  -- Search S. \n  apply Sn_le_Sm__n_le_m in H.\n  apply IHb in H.\n  + rewrite H. reflexivity.\n  + apply Sn_le_Sm__n_le_m in H0. apply H0.\nQed.\n\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n  \nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split.\n    - (* refl *) apply le_reflexive.\n    - split.\n      + (* antisym *) apply le_antisymmetric.\n      + (* transitive. *) apply le_trans. 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/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7165285212780269}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  Float                                                     \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  *****************************************************************************\n  ******************************************************\n   Module Float.v \t\t\t\t   \t\n   Inspired by the Diadic of Patrick Loiseleur\n  *******************************************************)\nRequire Export Omega.\nRequire Export Compare.\nRequire Export Rpow.\nSection definitions.\nVariable radix : Z.\nHypothesis radixMoreThanOne : (1 < radix)%Z.\n \nLet radixMoreThanZERO := Zlt_1_O _ (Zlt_le_weak _ _ radixMoreThanOne).\nHint Resolve radixMoreThanZERO: zarith.\n(* The type float represents the set of numbers who can be written:  \t\n   x = n*b^p with  n and p in Z. (pdic numbers)\t\t\t\t\n   n = Fnum and p = Fexp \t\t\t\t\t\t*)\n \nRecord float : Set := Float {Fnum : Z; Fexp : Z}.\n \nTheorem floatEq :\n forall p q : float, Fnum p = Fnum q -> Fexp p = Fexp q -> p = q.\nintros p q; case p; case q; simpl in |- *; intros;\n apply (f_equal2 (A1:=Z) (A2:=Z)); auto.\nQed.\n \nTheorem floatDec : forall x y : float, {x = y} + {x <> y}.\nintros x y; case x; case y; intros Fnum2 Fexp2 Fnum1 Fexp1.\ncase (Z_eq_dec Fnum1 Fnum2); intros H1.\ncase (Z_eq_dec Fexp1 Fexp2); intros H2.\nleft; apply floatEq; auto.\nright; red in |- *; intros H'; Contradict H2; inversion H'; auto.\nright; red in |- *; intros H'; Contradict H1; inversion H'; auto.\nQed.\n \nDefinition Fzero (x : Z) := Float 0 x.\n \nDefinition is_Fzero (x : float) := Fnum x = 0%Z.\n \nTheorem is_FzeroP : forall x : float, is_Fzero x \\/ ~ is_Fzero x.\nunfold is_Fzero in |- *; intro; CaseEq (Fnum x); intros;\n (right; discriminate) || (left; auto).\nQed.\nCoercion IZR : Z >-> R.\nCoercion INR : nat >-> R.\nCoercion Z_of_nat : nat >-> Z.\n \nDefinition FtoR (x : float) := (Fnum x * powerRZ (IZR radix) (Fexp x))%R.\n \nLocal Coercion FtoR : float >-> R.\n \nTheorem FzeroisReallyZero : forall z : Z, Fzero z = 0%R :>R.\nintros z; unfold FtoR in |- *; simpl in |- *; auto with real.\nQed.\n \nTheorem is_Fzero_rep1 : forall x : float, is_Fzero x -> x = 0%R :>R.\nintros x H; unfold FtoR in |- *.\nred in H; rewrite H; simpl in |- *; auto with real.\nQed.\n \nTheorem LtFnumZERO : forall x : float, (0 < Fnum x)%Z -> (0 < x)%R.\nintros x; case x; unfold FtoR in |- *; simpl in |- *.\nintros Fnum1 Fexp1 H'; replace 0%R with (Fnum1 * 0)%R;\n [ apply Rmult_lt_compat_l | ring ]; auto with real zarith.\nQed.\n \nTheorem is_Fzero_rep2 : forall x : float, x = 0%R :>R -> is_Fzero x.\nintros x H'.\ncase (Rmult_integral _ _ H'); simpl in |- *; auto.\ncase x; simpl in |- *.\nintros Fnum1 Fexp1 H'0; red in |- *; simpl in |- *; auto with real zarith.\napply eq_IZR_R0; auto.\nintros H'0; Contradict H'0; apply powerRZ_NOR; auto with real zarith.\nQed.\n \nTheorem NisFzeroComp :\n forall x y : float, ~ is_Fzero x -> x = y :>R -> ~ is_Fzero y.\nintros x y H' H'0; Contradict H'.\napply is_Fzero_rep2; auto.\nrewrite H'0.\napply is_Fzero_rep1; auto.\nQed.\n(* Some inegalities that will be helpful *)\n \nTheorem Rlt_monotony_exp :\n forall (x y : R) (z : Z),\n (x < y)%R -> (x * powerRZ radix z < y * powerRZ radix z)%R.\nintros x y z H'; apply Rmult_lt_compat_r; auto with real zarith.\nQed.\n \nTheorem Rle_monotone_exp :\n forall (x y : R) (z : Z),\n (x <= y)%R -> (x * powerRZ radix z <= y * powerRZ radix z)%R.\nintros x y z H'; apply Rmult_le_compat_r; auto with real zarith.\nQed.\n \nTheorem Rlt_monotony_contra_exp :\n forall (x y : R) (z : Z),\n (x * powerRZ radix z < y * powerRZ radix z)%R -> (x < y)%R.\nintros x y z H'; apply Rmult_lt_reg_l with (r := powerRZ radix z);\n auto with real zarith.\nrepeat rewrite (Rmult_comm (powerRZ radix z)); auto.\nQed.\n \nTheorem Rle_monotony_contra_exp :\n forall (x y : R) (z : Z),\n (x * powerRZ radix z <= y * powerRZ radix z)%R -> (x <= y)%R.\nintros x y z H'; apply Rmult_le_reg_l with (r := powerRZ radix z);\n auto with real zarith.\nrepeat rewrite (Rmult_comm (powerRZ radix z)); auto.\nQed.\n \nTheorem FtoREqInv1 :\n forall p q : float, ~ is_Fzero p -> p = q :>R -> Fnum p = Fnum q -> p = q.\nintros p q H' H'0 H'1.\napply floatEq; auto.\nunfold FtoR in H'0.\napply Rpow_eq_inv with (r := IZR radix); auto 6 with real zarith.\napply Rlt_dichotomy_converse; right; red in |- *.\nunfold Rabs in |- *; case (Rcase_abs radix).\nintros H'2; Contradict H'2; apply Rle_not_lt; apply Ropp_le_cancel;\n auto with real.\nintros H'2; replace 1%R with (IZR 1); auto with real zarith.\napply Rmult_eq_reg_l with (r := IZR (Fnum p)); auto with real.\npattern (Fnum p) at 2 in |- *; rewrite H'1; auto.\nQed.\n \nTheorem FtoREqInv2 :\n forall p q : float, p = q :>R -> Fexp p = Fexp q -> p = q.\nintros p q H' H'0.\napply floatEq; auto.\napply eq_IZR; auto.\napply Rmult_eq_reg_l with (r := powerRZ radix (Fexp p));\n auto with real zarith.\nrepeat rewrite (Rmult_comm (powerRZ radix (Fexp p)));\n pattern (Fexp p) at 2 in |- *; rewrite H'0; auto with real zarith.\nQed.\n \nTheorem Rlt_Float_Zlt :\n forall p q r : Z, (Float p r < Float q r)%R -> (p < q)%Z.\nintros p q r H'.\napply lt_IZR.\napply Rlt_monotony_contra_exp with (z := r); auto with real.\nQed.\n \nTheorem Rle_Float_Zle :\n forall p q r : Z, (Float p r <= Float q r)%R -> (p <= q)%Z.\nintros p q r H'.\napply le_IZR.\napply Rle_monotony_contra_exp with (z := r); auto with real.\nQed.\n(* Properties for floats with 1 as mantissa *)\n \nTheorem oneExp_le :\n forall x y : Z, (x <= y)%Z -> (Float 1%nat x <= Float 1%nat y)%R.\nintros x y H'; unfold FtoR in |- *; simpl in |- *.\nrepeat rewrite Rmult_1_l; auto with real zarith.\napply Rle_powerRZ; try replace 1%R with (IZR 1); auto with real zarith zarith.\nQed.\n \nTheorem oneExp_lt :\n forall x y : Z, (x < y)%Z -> (Float 1%nat x < Float 1%nat y)%R.\nintros x y H'; unfold FtoR in |- *; simpl in |- *.\nrepeat rewrite Rmult_1_l; auto with real zarith.\nQed.\n \nTheorem oneExp_Zlt :\n forall x y : Z, (Float 1%nat x < Float 1%nat y)%R -> (x < y)%Z.\nintros x y H'; case (Zle_or_lt y x); auto; intros ZH; Contradict H'.\napply Rle_not_lt; apply oneExp_le; auto.\nQed.\n \nTheorem oneExp_Zle :\n forall x y : Z, (Float 1%nat x <= Float 1%nat y)%R -> (x <= y)%Z.\nintros x y H'; case (Zle_or_lt x y); auto; intros ZH; Contradict H'.\napply Rgt_not_le; red in |- *; apply oneExp_lt; auto.\nQed.\n \nDefinition Fdigit (p : float) := digit radix (Fnum p).\n \nDefinition Fshift (n : nat) (x : float) :=\n  Float (Fnum x * Zpower_nat radix n) (Fexp x - n).\n \nTheorem sameExpEq : forall p q : float, p = q :>R -> Fexp p = Fexp q -> p = q.\nintros p q; case p; case q; unfold FtoR in |- *; simpl in |- *.\nintros Fnum1 Fexp1 Fnum2 Fexp2 H' H'0; rewrite H'0; rewrite H'0 in H'.\ncut (Fnum1 = Fnum2).\nintros H'1; rewrite <- H'1; auto.\napply eq_IZR; auto.\napply Rmult_eq_reg_l with (r := powerRZ radix Fexp1);\n repeat rewrite (Rmult_comm (powerRZ radix Fexp1)); \n auto.\napply Rlt_dichotomy_converse; right; auto with real.\nred in |- *; auto with real.\nQed.\n \nTheorem FshiftFdigit :\n forall (n : nat) (x : float),\n ~ is_Fzero x -> Fdigit (Fshift n x) = Fdigit x + n.\nintros n x; case x; unfold Fshift, Fdigit, is_Fzero in |- *; simpl in |- *.\nintros p1 p2 H; apply digitAdd; auto.\nQed.\n \nTheorem FshiftCorrect : forall (n : nat) (x : float), Fshift n x = x :>R.\nintros n x; unfold FtoR in |- *; simpl in |- *.\nrewrite Rmult_IZR.\nrewrite Zpower_nat_Z_powerRZ; auto.\nrepeat rewrite Rmult_assoc.\nrewrite <- powerRZ_add; auto with real zarith.\nrewrite Zplus_minus; auto.\nQed.\n \nTheorem FshiftCorrectInv :\n forall x y : float,\n x = y :>R ->\n (Fexp x <= Fexp y)%Z -> Fshift (Zabs_nat (Fexp y - Fexp x)) y = x.\nintros x y H' H'0; try apply sameExpEq; auto.\napply trans_eq with (y := FtoR y); auto.\napply FshiftCorrect.\ngeneralize H' H'0; case x; case y; simpl in |- *; clear H' H'0 x y.\nintros Fnum1 Fexp1 Fnum2 Fexp2 H' H'0; rewrite inj_abs; auto with zarith.\nQed.\n \nTheorem FshiftO : forall x : float, Fshift 0 x = x.\nintros x; unfold Fshift in |- *; apply floatEq; simpl in |- *.\nreplace (Zpower_nat radix 0) with 1%Z; auto with zarith.\nsimpl in |- *; auto with zarith.\nQed.\n \nTheorem FshiftCorrectSym :\n forall x y : float,\n x = y :>R -> exists n : nat, (exists m : nat, Fshift n x = Fshift m y).\nintros x y H'.\ncase (Z_le_gt_dec (Fexp x) (Fexp y)); intros H'1.\nexists 0; exists (Zabs_nat (Fexp y - Fexp x)).\nrewrite FshiftO.\napply sym_equal.\napply FshiftCorrectInv; auto.\nexists (Zabs_nat (Fexp x - Fexp y)); exists 0.\nrewrite FshiftO.\napply FshiftCorrectInv; auto with zarith.\nQed.\n \nTheorem FshiftAdd :\n forall (n m : nat) (p : float), Fshift (n + m) p = Fshift n (Fshift m p).\nintros n m p; case p; unfold Fshift in |- *; simpl in |- *.\nintros Fnum1 Fexp1; apply floatEq; simpl in |- *; auto with zarith.\nrewrite Zpower_nat_is_exp; auto with zarith.\nrewrite (Zmult_comm (Zpower_nat radix n)); auto with zarith.\nrewrite <- (Zminus_plus_simpl_r (Fexp1 - m) n m).\nreplace (Fexp1 - m + m)%Z with Fexp1; auto with zarith.\nreplace (Z_of_nat (n + m)) with (n + m)%Z; auto with zarith arith.\nrewrite <- inj_plus; auto.\nQed.\n \nTheorem ReqGivesEqwithSameExp :\n forall p q : float,\n exists r : float,\n   (exists s : float, p = r :>R /\\ q = s :>R /\\ Fexp r = Fexp s).\nintros p q; exists (Fshift (Zabs_nat (Fexp p - Zmin (Fexp p) (Fexp q))) p);\n exists (Fshift (Zabs_nat (Fexp q - Zmin (Fexp p) (Fexp q))) q); \n repeat split; auto with real.\nrewrite FshiftCorrect; auto.\nrewrite FshiftCorrect; auto.\nsimpl in |- *.\nreplace (Z_of_nat (Zabs_nat (Fexp p - Zmin (Fexp p) (Fexp q)))) with\n (Fexp p - Zmin (Fexp p) (Fexp q))%Z.\nreplace (Z_of_nat (Zabs_nat (Fexp q - Zmin (Fexp p) (Fexp q)))) with\n (Fexp q - Zmin (Fexp p) (Fexp q))%Z.\ncase (Zmin_or (Fexp p) (Fexp q)); intros H'; rewrite H'; auto with zarith.\nrewrite inj_abs; auto.\napply Zplus_le_reg_l with (p := Zmin (Fexp p) (Fexp q)); auto with zarith.\ngeneralize (Zle_min_r (Fexp p) (Fexp q)); auto with zarith.\nrewrite inj_abs; auto.\napply Zplus_le_reg_l with (p := Zmin (Fexp p) (Fexp q)); auto with zarith.\nQed.\n \nTheorem FdigitEq :\n forall x y : float,\n ~ is_Fzero x -> x = y :>R -> Fdigit x = Fdigit y -> x = y.\nintros x y H' H'0 H'1.\ncut (~ is_Fzero y); [ intros NZy | idtac ].\n2: red in |- *; intros H'2; case H'.\n2: apply is_Fzero_rep2; rewrite H'0; apply is_Fzero_rep1; auto.\ncase (Zle_or_lt (Fexp x) (Fexp y)); intros Eq1.\ncase (Zle_lt_or_eq _ _ Eq1); clear Eq1; intros Eq1.\nabsurd\n (Fdigit (Fshift (Zabs_nat (Fexp y - Fexp x)) y) =\n  Fdigit y + Zabs_nat (Fexp y - Fexp x)).\nrewrite FshiftCorrectInv; auto.\nrewrite <- H'1.\nred in |- *; intros H'2.\nabsurd (0%Z = (Fexp y - Fexp x)%Z); auto with zarith arith.\nrewrite <- (inj_abs (Fexp y - Fexp x)); auto with zarith.\napply Zlt_le_weak; auto.\napply FshiftFdigit; auto.\napply sameExpEq; auto.\nabsurd\n (Fdigit (Fshift (Zabs_nat (Fexp x - Fexp y)) x) =\n  Fdigit x + Zabs_nat (Fexp x - Fexp y)).\nrewrite FshiftCorrectInv; auto.\nrewrite <- H'1.\nred in |- *; intros H'2.\nabsurd (0%Z = (Fexp x - Fexp y)%Z); auto with zarith arith.\nrewrite <- (inj_abs (Fexp x - Fexp y)); auto with zarith.\napply Zlt_le_weak; auto.\napply FshiftFdigit; auto.\nQed.\nEnd definitions.\nHint Resolve Rlt_monotony_exp Rle_monotone_exp: real.\nHint Resolve Zlt_not_eq Zlt_not_eq_rev: zarith.", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/Float.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7165284995809371}}
{"text": "Theorem le_0_n:\n        forall n:nat, 0 <= n.\nProof.\n        intros. elim n.\n        auto.\n        intros. auto.\nQed.\n\nTheorem le_n_0_eq:\n        forall n:nat, n <= 0 -> n =0.\nProof.\n        intros n h.\n        inversion h.\n        trivial.\nQed.\n\nTheorem le_plus_minus' :\n        forall n m : nat, m <= n -> n = m + (n - m).\nProof.\n        intro n. elim n.\n        intros m h. inversion h. trivial.        induction m.\n        intros; trivial.\n        intros. simpl. \n        assert (forall n m : nat, n = m -> S n = S m).\n        intros; auto.\n        apply H1. apply H. apply le_S_n.\n        trivial.\nQed.\n\nTheorem le_plus_minus2' :\n        forall n m:nat, m <= n -> n = m + (n - m).\nProof.\n        intro n. elim n.\n        intros m h; inversion h; simpl; trivial.\n        intro. intro. intro. case m. intros; simpl; trivial. intro. intro. simpl. assert (h: forall m n:nat,  m = n -> S m = S n). intros; simpl; rewrite <- H1; simpl ; trivial.\n        apply h; apply H; apply le_S_n; trivial.\nQed.\n\nSection primes.\n        Definition divides (n m : nat) := exists p:nat, p*n = m.\n        Theorem divides_0 :\n                forall n: nat, divides n 0.\n        Proof.\n                intro.\n                unfold divides.\n                exists 0;trivial.\n        Qed.\n\n        Theorem divides_plus:\n                forall n m : nat, divides n m -> divides n (n + m).\n        Proof.\n                unfold divides.\n                intros.\n                inversion H.\n                exists (S x). simpl. rewrite <- H0. trivial.\n        Qed.\n\nRequire Import Arith.\n\n        Theorem not_divides_plus:\n                forall n m:nat, 0 < m -> m < n -> ~divides n m.\n        Proof.\n                unfold divides.\n                unfold not.\n                intros n m h1 h2 h3. inversion h3.\n                destruct x. simpl in H; rewrite <- H in h1; inversion h1. assert ( S x >= S O). change ( 1 + x  >= 0 + 1).  SearchPattern (_ + _ = _ + _). rewrite <- plus_comm. SearchPattern(_ <= _ -> _ <= _). apply plus_le_compat_r. apply le_0_n.  assert (S x * n >= 1 * n). apply mult_le_compat_r. apply H0. rewrite -> H in H1. simpl in H1. unfold lt in h2. assert ( S m >= S (n + 0)). change (1 + m >= 1 + n + 0). SearchPattern (_ <= _ -> _ <= _). rewrite <- plus_assoc. apply plus_le_compat_l. apply H1. assert ( S(n + 0) <= n). eapply le_trans. apply H2. apply h2. rewrite <- plus_comm in H3. simpl in H3. assert (forall n, ~(S n <= n)). intro n0; elim n0. intro h7; inversion h7. unfold not; intros. apply H4. apply le_S_n. apply H5. unfold not in H4. eapply H4; apply H3. \n         Qed.\n\n        Theorem not_divides_lt:\n                forall n m : nat, 0 < m -> m < n -> ~divides n m.\n        Proof.\n                unfold not.\n                intros n m h1 h2 h3.\n                unfold divides in h3.\n                inversion h3.\n                destruct x. simpl in H; rewrite <- H in h1; inversion h1.\n                assert (forall x, S x >= S O).\n                intros; change (1 + x0 >= 1 + 0). SearchPattern (_ <= _ -> _ <= _). apply plus_le_compat_l; apply le_0_n. assert (S x * n >= 1 * n). apply mult_le_compat_r; apply H0. rewrite -> H in H1; simpl in H1; rewrite plus_comm in H1; simpl in H1. SearchPattern (_ <= _ -> ~ _ < _). assert (~m < n). apply le_not_lt. apply H1. contradiction.\n                Qed.\n        Lemma le_1_Sn:\n                forall x, S x >= S O.\n        Proof.\n                intro x; elim x. apply le_n. intros n h1; apply le_S; trivial.\n        Qed.\n\n        Theorem not_lt_2_divides :\n                forall n m : nat, n <> 1 -> n < 2 -> 0 < m -> ~divides n m.\n        Proof.\n                unfold not; unfold divides; intros n m h1 h2 h3 h4.\n                inversion h4. inversion h2. contradiction. inversion H1. rewrite -> H3 in H; rewrite -> mult_comm in H; simpl in H. rewrite <- H in h3; inversion h3. inversion H3.\n        Qed.\n\n        Definition le_plus_minus :\n               forall n m:nat, le m n -> n = m +(n-m) := le_plus_minus'.\n\n        Theorem lt_lt_or_eq:\n                forall n m : nat, n < S m -> n < m \\/ n = m.\n        Proof.\n                intros n m h1.\n                unfold lt in h1. assert (n <= m). apply le_S_n. apply h1. inversion H. right;trivial. left; unfold lt. change (1 + n <= 1 + m0). apply plus_le_compat_l. apply H0.\n        Qed.\n\n\nRequire Import ZArith.\n        Ltac tactic7p2 :=\n                match goal with\n                | [ |- context [( (xI ?X1))] ] => rewrite (Zpos_xI X1); tactic7p2\n                | [ |- context [( (xO ?X2))]] => match X2 with\n                | xH => fail 1\n                | _ => rewrite (Zpos_xO X2); tactic7p2 \n                end\n                | [ |- _] => idtac\n                end.\n\n        Theorem testtactic7p2:\n                forall x,Zpos(xI( xO (xO x))) =Zpos (xI( xO (xO x))).\n        Proof.\n                intros x.\n                tactic7p2.\n                Check Zpos_xI.\n        Abort.\n\n\n\n\n\n\n\n                \n                \n\n\n                             \n               \n                \n\n\n        \n       \n       \n        \n\n", "meta": {"author": "DKXXXL", "repo": "Coq-Art-Exercises", "sha": "139d1dbf85204f1106f4afe5d15f1f2aee1b48df", "save_path": "github-repos/coq/DKXXXL-Coq-Art-Exercises", "path": "github-repos/coq/DKXXXL-Coq-Art-Exercises/Coq-Art-Exercises-139d1dbf85204f1106f4afe5d15f1f2aee1b48df/7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7165138184421569}}
{"text": "Parameter A B C : Prop.\nLemma AimpA : A -> A.\nProof.\n\tintro.\n\tapply H.\nQed.\n\n\nLemma imp_trans : (A->B)->(B->C)->A->C.\nProof.\n\tintros.\n\tapply H in H1.\n\tapply H0 in H1.\n\tapply H1.\nQed.\n\n\nLemma and_comm : A /\\ B -> B /\\ A.\nProof.\n\tintro.\n\tdestruct H .\n\tsplit.\n\tapply H0.\n\tapply H.\nQed.\n\n\nLemma or_comm : A \\/ B -> B \\/ A.\nProof.\n\tintro.\n\tdestruct H.\n\tright.\n\tapply H.\n\tleft.\n\tapply H.\nQed.\n\n\n(* Using the Print command, print the proofs obtained \nfor AimpA and imp_trans. What are these terms ? Does it help\nunderstanding why -> is used both for logical implication \nand arrow types ? *)\nPrint AimpA.\nPrint imp_trans.\n\nLemma AimpNotA : A -> ~~A.\nProof.\n\tintro.\n\tunfold not.\n\tintros.\n\tapply H0 in H.\n\tapply H.\nQed.\n\nLemma noname : (A \\/ B)/\\ C -> A /\\ C \\/ B /\\ C.\nProof.\n\tintro.\n\tdestruct H.\n\tdestruct H.\n\tleft.\n\tsplit.\n\tapply H.\n\tapply H0.\n\tright.\n\tsplit.\n\tapply H.\n\tapply H0.\nQed.\n\nLemma EMequiv : (forall P:Prop, P \\/ ~P) <-> (forall P:Prop, ~~P -> P).\nProof.\n\tunfold iff.\n\tsplit.\n\tintros.\n\tdestruct H with P.\n\tapply H1.\n\tunfold not in H1.\n\tunfold not in H0.\n\tapply H0 in H1.\n\tcontradiction.\n\n\tintros.\n\tapply H.\n\tunfold not.\n\tintros.\n\tapply H0.\n\tright.\n\tintro.\n\tapply H0.\n\tleft.\n\tapply H1.\nQed.\n\n\n(*Require Import Classical.*)\n\n(* Socrate is a men, all mens are mortal, therefore socrate is mortal *)\n\nParameter Person:Type.\nParameter Socrate : Person.\nParameter Men Mortal : Person->Prop.\n\nLemma socrateMortal : Men Socrate /\\ (forall P:Person, Men P -> Mortal P) -> Mortal Socrate.\nProof.\n\tintros.\n\tdestruct H.\n\tapply H0 in H.\n\tapply H.\nQed.\n\n\n(* Drinker's paradox *)\n\nParameter EM : forall P, ~~ P -> P.\n\n\nLemma drinker : exists p:Person, ~ Mortal p -> forall q:Person, ~ (Mortal q).\nProof.\n\tapply EM.\n\tintro.\n\tapply H.\n\texists Socrate.\n\tintros.\n\tintro.\n\tapply H.\n\texists q.\n\tintros.\n\tcontradiction.\nQed.\n\n(* Element type *)\nParameter Elt:Type.\n(* Binary operator *)\nParameter op : Elt -> Elt -> Elt.\n(* Inversion operation *)\nParameter inv : Elt -> Elt.\n(* Associativity of op*)\nParameter assoc : forall a b c, op (op a b) c = op a (op b c).\nParameter e:Elt.\n(* there exists an identity element *)\nParameter id_l : forall a, op e a = a.\nParameter id_r : forall a, op a e = a.\n(* there exists an inverse element *)\nParameter inv_l : forall a, op (inv a) a = e.\nParameter inv_r : forall a, op a (inv a) = e.\n\nLemma group : forall x y, inv (op x y) = op (inv y) (inv x).\nProof.\n\tintros.\n\ttransitivity (op (op (inv y) (inv x)) (op (op x y) (inv (op x y)))).\n\trewrite assoc.\n\trewrite assoc.\n\trewrite <- assoc with (a:=inv x) (b:=x).\n\trewrite inv_l.\n\trewrite id_l.\n\trewrite <- assoc with (a:=inv y) (b:=y).\n\trewrite inv_l.\n\trewrite id_l.\n\treflexivity.\n\n\trewrite inv_r.\n\trewrite id_r.\n\treflexivity.\nQed.\n\n\n\n", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/PA/2021/TP1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7165138121276345}}
{"text": "(*\n  Verificación Formal - Unam 2020-2\n  Ciro Iván García López\n  Proyecto 1. Session Type Systems Verification\n*)\nFrom PROYI Require Import  Defs_Proposition.\n\n\n(*\nObservación presente en la definición 2.2 (primer parrafo).\n*)\nProposition Doble_Duality_ULLT  : \nforall A : Proposition , \n(A^⊥)^⊥ = A. \nProof.\n  intros.\n  induction A; auto. \n  - simpl. rewrite -> IHA1. rewrite -> IHA2. reflexivity.\n  - simpl. rewrite -> IHA1. rewrite -> IHA2. reflexivity.\n  - simpl. rewrite -> IHA. reflexivity. \n  - simpl. rewrite -> IHA. reflexivity. \nQed.\n\n\n(*\nPrueba de las propiedades descritas en la definición 2.2.\n*)\nProposition Dual_Implication_Tensor : \nforall A B : Proposition , \n((A −∘ B)^⊥) = (A ⊗ (B^⊥)).\nProof.\n  intros.\n  unfold ULLT_IMP.\n  simpl.\n  rewrite -> (Doble_Duality_ULLT A).\n  reflexivity.\nQed.\n\n\nProposition Dual_Tensor_Implication :  \nforall A B : Proposition, \n((A ⊗ B )^⊥) = (A −∘ (B^⊥)).\nProof.\n  intros.\n  simpl.\n  unfold ULLT_IMP.\n  reflexivity.\nQed.\n\n\nProposition Doble_Dual_Implication : \nforall A B : Proposition, \n(((A −∘ B)^⊥)^⊥) = (A −∘ B).\nProof.\n  intros.\n  unfold ULLT_IMP.\n  rewrite -> (Doble_Duality_ULLT).\n  reflexivity.\nQed.", "meta": {"author": "cigarcial", "repo": "VF2020II", "sha": "3a283400575564770e47f54e7f7cc66f996da0f1", "save_path": "github-repos/coq/cigarcial-VF2020II", "path": "github-repos/coq/cigarcial-VF2020II/VF2020II-3a283400575564770e47f54e7f7cc66f996da0f1/ProyI/Props_Propositions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483232, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7165138100035697}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) : natural := plus z (mult z y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj286_coqofml_nUcZ8g.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7165138078795051}}
{"text": "Module map.\nRequire Import Arith.\nInductive list (X : Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n Check nil.\nCheck (cons nat 2 (nil nat)).\n\nFixpoint 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' t)\n  end.\n\nArguments nil {_}.\nArguments cons {_} h t.\nCheck nil.\nCheck cons.\n\nFixpoint length'' {X: Type} (l: list X) : nat :=\n  match l with\n  | nil  => 0\n  | cons  h t => S (length' t)\n  end.\nExample test_length'': length'' (cons 1 nil) = 1.\nProof. simpl. reflexivity. Qed.\n\nFixpoint app {X: Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\nExample test_app1:\n  app (cons 1 (cons 2 nil)) (cons 3 nil) = (cons 1 (cons 2 (cons 3 nil))).\n Proof. simpl. reflexivity. Qed.\n\nFixpoint rev {X: Type} (l: list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\nExample test_rev1:\n  rev (cons 1 (cons 2 (cons 3 nil))) =  (cons 3 (cons 2 (cons 1 nil))). \n Proof. simpl. reflexivity. Qed.\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\nExample test_app2 : (cons 1 (cons 2 (cons 3 nil))) = [1, 2, 3].\n Proof. simpl. reflexivity. Qed.\n\n\nFixpoint repeat {X : Type} (n : X) (count : nat) : list X :=\n  match count with\n  | O => []\n  | S c' => n :: (repeat n c')\n  end.\nExample test_repeat1:\n  repeat true 2 = [true, true].\nProof. reflexivity. Qed.\n\nTheorem nil_app : forall X : Type, forall l : list X,\n  app [] l = l.\nProof.\n  intros X l. reflexivity. Qed.\n\nInductive prod (X Y: Type) : Type :=\n  pair : X -> Y -> prod X Y.\nCheck pair.\nCheck pair _ _ 1 2.\nArguments pair {_} {_} x y.\nCheck pair.\nCheck pair 1 [1].\nNotation \"( x , y )\" := (pair x y).\nCheck (1, 3).\nNotation \"X * Y\" := (prod X Y) : type_scope.\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with (x,y) => x end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with (x,y) => y end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match (lx,ly) with\n  | ([],_) => []\n  | (_,[]) => []\n  | (x::tx, y::ty) => (x,y) :: (combine tx ty)\n  end.\n\nInductive option (X: Type) : Type :=\n  | Some : X -> option X\n  | None: option X.\nArguments Some {_} x.\nArguments None {_}.\nCheck Some 2.\nCheck None.\n\nDefinition head {X: Type} (l : list X) : option X :=\n  match l with\n  | nil => None\n  | h::t => Some h\n  end.\nExample test_head1 : head [2, 4] = Some 2.\nProof. reflexivity. Qed.\n\nFixpoint filter {X:Type} (test: X -> bool) (l:list X)\n                : (list X) :=\n  match l with\n  | [] => []\n  | h :: t => if test h then h :: (filter test t)\n                        else filter test t\n  end.\n\nFixpoint map {X Y: Type} (f : X -> Y) (l : list X) : list Y :=\n  match l with\n  | nil => nil\n  | x :: t => f x :: (map f t)\n  end.\nExample test_map1 : map (plus 2) [1, 2, 3] = [3, 4, 5].\nProof. reflexivity. Qed. \n\nTheorem map_assoc : forall (X Y: Type) (f: X -> Y) (l1 l2: list X),\n   map f (l1 ++ l2) = (map f l1) ++ (map f l2).\nProof.\n  intros X Y f l1 l2.\n  induction l1 as [| n l1']. reflexivity.\n  simpl. rewrite -> IHl1'. reflexivity. Qed. \n  \n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [| n l']. reflexivity.\n  simpl. rewrite -> map_assoc. simpl. rewrite -> IHl'. reflexivity. Qed.\n\nFixpoint foldr {X Y : Type} (f : X -> Y -> Y) (l : list X) (b : Y) : Y :=\n  match l with \n  | nil => b\n  | h :: t => f h (foldr f t b)\n  end.\nExample test_foldr1 : foldr plus [1, 2, 3, 4] 0 = 10.\nProof. reflexivity. Qed.\n\n\nEnd map.", "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/map.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.7164951935292881}}
{"text": "Require Export BaseLists Removal.\n\n(**** Cardinality *)\n\nSection Cardinality.\n  Variable X : eqType.\n  Implicit Types A B : list X.\n\n  Fixpoint card A :=\n    match A with\n      | nil => 0\n      | x::A => if Dec (x el A) then card A else 1 + card A\n    end.\n\n  Lemma card_cons x A :\n    x el A -> card (x::A) = card A.\n  Proof.\n    intros H. cbn. decide (x el A) as [H1|H1]; tauto.\n  Qed.\n\n  Lemma card_cons' x A :\n    ~ x el A -> card (x::A) = 1 + card A.\n  Proof.\n    intros H. cbn. decide (x el A) as [H1|H1]; tauto.\n  Qed.\n  \n  Lemma card_in_rem x A :\n    x el A -> card A = 1 + card (rem A x).\n  Proof.\n    intros D. \n    induction A as [|y A].\n    - contradiction D.\n    - decide (y = x) as [->|H].\n      + clear D. rewrite rem_fst.\n        cbn. decide (x el A) as [H1|H1].\n        * auto.\n        * now rewrite (rem_id H1).\n      + assert (x el A) as H1 by (destruct D; tauto). clear D.\n        rewrite (rem_fst' _ H). specialize (IHA H1).\n        simpl card at 2. \n        decide (y el rem A x) as [H2|H2].\n        * rewrite card_cons. exact IHA.\n          apply in_rem_iff in H2. intuition.\n        * rewrite card_cons'. now rewrite IHA.\n          contradict H2.  now apply in_rem_iff.\n  Qed.\n  \n  Lemma card_not_in_rem A x :\n    ~ x el A -> card A = card (rem A x).\n  Proof.\n    intros D; rewrite rem_id; auto.\n  Qed.\n\n  Lemma card_le A B :\n    A <<= B -> card A <= card B.\n  Proof.\n  revert B. \n  induction A as [|x A]; intros B D; cbn.\n  - omega.\n  - apply incl_lcons in D as [D D1].\n    decide (x el A) as [E|E].\n    + auto.\n    + rewrite (card_in_rem D).\n      enough (card A <= card (rem B x)) by omega.\n      apply IHA. auto.\n  Qed.\n\n  Lemma card_eq A B :\n    A === B -> card A = card B.\n  Proof.\n    intros [E F]. apply card_le in E. apply card_le in F. omega.\n  Qed.\n\n  Lemma card_cons_rem x A :\n    card (x::A) = 1 + card (rem A x).\n  Proof.\n    rewrite (card_eq (rem_equi x A)). cbn.\n    decide (x el rem A x) as [D|D].\n    - exfalso. apply in_rem_iff in D; tauto.\n    - reflexivity.\n  Qed.\n\n  Lemma card_0 A :\n    card A = 0 -> A = nil.\n  Proof.\n    destruct A as [|x A]; intros D.\n    - reflexivity.\n    - exfalso. rewrite card_cons_rem in D. omega.\n  Qed.\n\n  Lemma card_ex A B :\n    card A < card B -> exists x, x el B /\\ ~ x el A.\n  Proof.\n    intros D.\n    decide (B <<= A) as [E|E].\n    - exfalso. apply card_le in E. omega.\n    - apply list_exists_not_incl; auto.\n  Qed.\n\n  Lemma card_equi A B :\n    A <<= B -> card A = card B -> A === B.\n  Proof.\n    revert B. \n    induction A as [|x A]; cbn; intros B D E.\n    - symmetry in E. apply card_0 in E. now rewrite E.\n    - apply incl_lcons in D as [D D1].\n      decide (x el A) as [F|F].\n      + rewrite (IHA B); auto.\n      + rewrite (IHA (rem B x)).\n        * symmetry. apply rem_reorder, D.\n        * auto.\n        * apply card_in_rem in D. omega.\n  Qed.\n\n  Lemma card_lt A B x :\n    A <<= B -> x el B -> ~ x el A -> card A < card B.\n  Proof.\n    intros D E F.\n    decide (card A = card B) as [G|G].\n    + exfalso. apply F. apply (card_equi D); auto.\n    + apply card_le in D. omega.\n  Qed.\n\n  Lemma card_or A B :\n    A <<= B -> A === B \\/ card A < card B.\n  Proof.\n    intros D.\n    decide (card A = card B) as [F|F].\n    - left. apply card_equi; auto.\n    - right. apply card_le in D. omega.\n  Qed.\n\nEnd Cardinality.\n\nInstance card_equi_proper (X: eqType) : \n  Proper (@equi X ==> eq) (@card X).\nProof. \n  hnf. apply card_eq.\nQed.\n", "meta": {"author": "uds-psl", "repo": "cbv-lambda-calculus-reasonable", "sha": "4f12b7c8ce2816cdd771d22d04943e0fa81c63fd", "save_path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable", "path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable/cbv-lambda-calculus-reasonable-4f12b7c8ce2816cdd771d22d04943e0fa81c63fd/Base/Lists/Cardinality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7164507690680147}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2021 - Pset 2 *)\n\nRequire Import Coq.NArith.NArith. Open Scope N_scope.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.micromega.Lia.\nRequire Import Frap.Frap.\n\nModule Type S.\n  Definition fact: N -> N :=\n    recurse by cases\n    | 0 => 1\n    | n + 1 => (n + 1) * recurse\n    end.\n\n  (*[5%]*) Parameter exp: N -> N -> N.\n  Axiom test_exp_2_3: exp 2 3 = 8.\n  Axiom test_exp_3_2: exp 3 2 = 9.\n  Axiom test_exp_4_1: exp 4 1 = 4.\n  Axiom test_exp_5_0: exp 5 0 = 1.\n  Axiom test_exp_1_3: exp 1 3 = 1.\n\n  Definition seq (f: N -> N): N -> N -> list N :=\n    recurse by cases\n    | 0 => fun start => []\n    | n + 1 => fun start => f start :: recurse (start + 1)\n    end.\n\n  Definition ith: N -> list N -> N :=\n    recurse by cases\n    | 0 => fun (l: list N) => match l with\n                              | h :: t => h\n                              | nil => 0\n                              end\n    | i + 1 => fun (l: list N) => match l with\n                                  | h :: t => recurse t\n                                  | nil => 0\n                                  end\n    end.\n\n  Fixpoint len(l: list N): N :=\n    match l with\n    | [] => 0\n    | h :: t => 1 + len t\n    end.\n\n  (*[12%]*)\n  Axiom seq_spec: forall f count i start, i < count -> ith i (seq f count start) = f (start + i).\n\n  (*[12%]*)\n  Axiom ith_out_of_bounds_0: forall i l, len l <= i -> ith i l = 0.\n\n  Definition C(n k: N): N := fact n / (fact (n - k) * fact k).\n\n  Definition bcoeff(n: N): N -> N :=\n    recurse by cases\n    | 0 => 1\n    | k + 1 => recurse * (n - k) / (k + 1)\n    end.\n\n  (*[7%]*)\n  Axiom fact_nonzero: forall n, fact n <> 0.\n\n  (*[7%]*)\n  Axiom Cn0: forall n, C n 0 = 1.\n\n  (*[7%]*)\n  Axiom Cnn: forall n, C n n = 1.\n\n  (*[25%]*)\n  Axiom bcoeff_correct: forall n k, k <= n -> bcoeff n k = C n k.\n\n  Definition Pascal's_rule: Prop := forall n k,\n      1 <= k <= n ->\n      C (n+1) k = C n (k - 1) + C n k.\n\n  Definition nextLine(l: list N): list N :=\n    1 :: seq (fun k => ith (k - 1) l + ith k l) (len l) 1.\n\n  Definition all_coeffs_fast: N -> list N :=\n    recurse by cases\n    | 0 => [1]\n    | n + 1 => nextLine recurse\n    end.\n\n  (*[25%]*)\n  Axiom all_coeffs_fast_correct:\n    Pascal's_rule ->\n    forall n k,\n      k <= n ->\n      ith k (all_coeffs_fast n) = C n k.\nEnd S.\n", "meta": {"author": "mit-frap", "repo": "spring21", "sha": "20ecdeccfda50653abcdeb253dfc8118099f8c40", "save_path": "github-repos/coq/mit-frap-spring21", "path": "github-repos/coq/mit-frap-spring21/spring21-20ecdeccfda50653abcdeb253dfc8118099f8c40/pset02_BinomialCoefficients/Pset2Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7164507649310534}}
{"text": "(* ************************************************* *)\n(* prop1 and simply typed lambda calculus *)\n(* ************************************************* *)\n\nSection prop1.\n\nParameters A B C : Prop.\n\n(* exercise 1 *)\n(* prove the following three lemma's *)\n(* also use Print to see the proof-term *)\nLemma one1 : ((A -> B -> A) -> A) -> A.\nProof.\nintros. apply H. intros. exact H0.\nQed.\n\nLemma one2 : (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\nintros. apply H. exact H1. apply H0. exact H1.\nQed.\n\nLemma one3 : (B -> (A -> B) -> C) -> B -> C.\nProof.\nintros. apply H. exact H0. intro. exact H0.\nQed.\n\n\n\n(* exercise 2 *)\n(* give of each of the following three types an inhabitant *)\nDefinition two1 : (A -> A -> B) -> (C -> A) -> C -> B :=\nfun (f : A -> A -> B) (g : C -> A) (c : C) =>\n  f (g c) (g c)\n  .\n\nDefinition two2 : (A -> A -> B) -> A -> B :=\nfun (f : A -> A -> B) (a:A) =>\n  f a a\n  .\n\nDefinition two3 : (A -> B -> C) -> B -> A -> C :=\nfun (f : A -> B -> C) (b:B) (a:A) =>\n  f a b\n  .\n\n\n\n(* exercise 3 *)\n(* complete the following four simply typed lambda terms *)\nDefinition three1 :=\n fun (x : A -> B -> C) (y : A -> B) (z : A) => x z (y z)\n  .\n\nDefinition three2 :=\n fun (x : B -> A -> C) (y : A -> B) (z : A) => x (y z) z\n  .\n\nDefinition three3 :=\n fun (x : (B -> A) -> A -> C) (y : A) => x (fun z : B => y) y\n  .\n\nDefinition three4 :=\n fun (x : A -> B -> C)\n     (y : (A -> B -> C) -> A)\n     (z : (A -> B -> C) -> B)\n  => x (y x) (z x)\n  .\n\n\n\n(* exercise 4 *)\n(* prove the following two lemma's *)\nLemma four1 : (~A \\/ B) -> (A -> B).\nProof.\nunfold not. intros. elim H. intros. elimtype False. apply H1. exact H0.\nintro H1. exact H1.\nQed.\n\nLemma four2 : (A \\/ ~ A) -> ~~A -> A.\nProof.\nunfold not. intros. elim H. intro H1. exact H1.\nintro H1. elimtype False. apply H0. exact H1.\nQed.\n\n\n\nEnd prop1.\n\n(* ************************************************* *)\n(* pred1 and lambda P *)\n(* ************************************************* *)\n\nSection pred1.\n\nParameter Terms : Set.\nParameters M N : Terms.\nParameters P Q : Terms -> Prop.\nParameters R : Terms -> Terms -> Prop.\n\n\n\n(* exercise 5 *)\n(* prove the following three lemma's *)\n(* use Print to see the proof-term *)\n(* see practical work 7 *)\nLemma five1 : (forall x:Terms, ~ (P x)) -> ~ (exists x:Terms, P x).\nProof.\nunfold not. intros Hall Hexists. elim Hexists. exact Hall.\nQed.\n\nLemma five2 : forall x:Terms, (P x -> ~ (forall y:Terms, ~(P y))).\nProof.\nunfold not. intros. apply H0 with x. exact H.\nQed.\n\nLemma five3 :\n  (forall x y :Terms, R x y -> ~ (R y x)) ->\n  (forall x:Terms, ~ (R x x)).\nProof.\nunfold not. intros.\napply H with x x. exact H0. exact H0.\nQed.\n\n\n   \n(* exercise 6 *)\n(* give inhabitants of the following two types *)\n\nDefinition six1 : \n  (forall x y : Terms, R x y -> R y x) ->\n  (forall x   : Terms, R x M -> R M x) :=\nfun (f : forall x y : Terms, R x y -> R y x) =>\n  fun (x:Terms) (r : R x M) => f x M r\n  .\n\nDefinition six2 :\n  (forall x y z : Terms, R x y -> R y z -> R x z) ->\n  R M N ->\n  R N M ->\n  R M M :=\nfun (f:forall x y z : Terms, R x y -> R y z -> R x z)\n    (rMN : R M N)\n    (rNM : R N M) =>\n  f M N M rMN rNM\n  .\n\n\n  \n(* exercise 7 *)\n(* complete the following two lambda-terms *)\n\nDefinition seven1 :=\n  fun (H : forall x:Terms, P x -> Q x) =>\n  fun (I : P M) =>\n  H M I\n  .\n\nDefinition seven2 :=\n  fun (H : forall x y : Terms, R x y -> R y x) =>\n  fun (I : R M N) =>\n  H M N I\n  .\n\nDefinition seven3 :=\n  fun (H : Terms -> P M) =>\n  fun (I : forall x, P x -> Q x) =>\n  I M (H M)\n  .\n\nEnd pred1.\n\n\n\n(* ************************************************* *)\n(* prop2 and polymorphic lambda calculus *)\n(* ************************************************* *)\n\nSection prop2.\n\n(* exercise 8 *)\n(* prove the following two lemma's *)\nLemma eight1 : forall a:Prop, a -> forall b:Prop, b -> a. \nProof.\nintros. exact H.\nQed.\n\nLemma eight2 : (forall a:Prop, a) -> \n  forall b:Prop, forall c:Prop, ((b->c)->b)->b.\nProof.\nintros. apply H0. intro. apply H. \nQed.\n\n\n\n(* exercise 9 *)\n(* find inhabitants of the following two types *)\nDefinition nine1 : forall a:Prop, (forall b:Prop, b) -> a :=\nfun (a:Prop) (H:forall b:Prop, b) => H a\n  .\n\nDefinition nine2 : forall a:Prop, a -> (forall b:Prop, ((a -> b) -> b)) :=\nfun (a:Prop) (H:a) (b:Prop) (H0:a->b) => H0 H\n  .\n\n\n\n(* exercise 10 *)\n(* complete the following lambda terms *)\n\nDefinition ten1 :=\n  fun (a:Prop) =>\n  fun (x: forall b:Prop, b) =>\n  x a\n  .\n\nDefinition ten2 :=\n  fun (a:Prop) =>\n  fun (x:a) =>\n  fun (b:Prop) =>\n  fun (y:b) =>\n  x\n  .\n \n\n\nEnd prop2.\n\n\n\n\n(* ************************************************* *)\n(* inductive datatypes and predicates *)\n(* ************************************************* *)\n\nSection inductivetypes.\n\n(* given *)\nFixpoint plus (n m : nat) {struct n} : nat :=\n  match n with\n  | O => m\n  | S p => S (plus p m)\n  end.\n\n\n\n(* exercise 11 *)\n(* prove the following three lemma's *)\nLemma plus_n_O : forall n : nat, n = plus n 0.\nProof.\nintro n. induction n.\nsimpl. reflexivity.\nsimpl. rewrite <- IHn. reflexivity.\nQed.\n\nLemma plus_n_S : forall n m : nat, S (plus n m) = plus n (S m).\nProof.\nintros n m. induction n.\nsimpl. reflexivity.\nsimpl. rewrite <- IHn. reflexivity.\nQed.\n\nLemma com : forall n m : nat, plus n m = plus m n.\nProof.\ninduction n. induction m. simpl. reflexivity.\nsimpl. rewrite <- IHm. simpl. reflexivity.\ninduction m. simpl. rewrite -> IHn. simpl. reflexivity.\nsimpl. rewrite IHn. rewrite <- IHm. simpl. rewrite -> IHn. reflexivity.\nQed.\n\n\n\n(* given *)\nInductive polybintree (X : Set) : Set :=\n    polyleaf : X -> polybintree X\n  | polynode : polybintree X -> polybintree X -> polybintree X.\n\n\n\n(* exercise 12 *)\n(* give a definition counttree that counts the number of leafs *)\n\nFixpoint counttree (X : Set) (b : polybintree X) {struct b} : nat :=\n  match b with\n  | polyleaf _ => O\n  | polynode l r => plus (counttree X l) (counttree X r)\n  end\n  .\n\n\n\n(* exercise 13 *)\n(* give a definition sum that adds the values on the leafs\n   for a tree with natural numbers on the leafs *)\n\nFixpoint sum (b:polybintree nat) {struct b} : nat :=\n  match b with\n  | polyleaf x => x\n  | polynode l r => plus (sum l) (sum r)\n  end\n  .\n\n\n(* given *)\nDefinition ifb (b1 b2 b3:bool) : bool :=\n  match b1 with\n  | true => b2\n  | false => b3\n  end.\n\n(* given *)\nDefinition andb (b1 b2:bool) : bool := ifb b1 b2 false.\n\n\n\n(* exercise 14 *)\n(* give a definition and that computes the conjunction\n   of the values of all leafs where all leafs have a \n   boolean label \n   use andb for conjunction on booleans *)\n\nFixpoint conjunction (t : polybintree bool) {struct t} : bool :=\n  match t with\n  | polyleaf b => b\n  | polynode l r => andb (conjunction l) (conjunction r)\n  end\n  .\n\n\n\nEnd inductivetypes.\n\n(*\nvim: filetype=coq\n*)\n", "meta": {"author": "mklinik", "repo": "radboud", "sha": "1b79730dbf7979221ca0de97fc369db82c405331", "save_path": "github-repos/coq/mklinik-radboud", "path": "github-repos/coq/mklinik-radboud/radboud-1b79730dbf7979221ca0de97fc369db82c405331/type-theory-IMC010/pw11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7164507620913956}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) : natural := mult (Succ y) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj286_coqofml_w9Amga.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.71640802176241}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (lf1 : natural) : natural :=\n  plus lf2 lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj23_coqofml_OPsK6H.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7164080214745508}}
{"text": "(* https://coq-math-problems.github.io/Problem1/ *)\n\nRequire Import PeanoNat.\n\nRequire Import Hack.CMP.Decr.\nRequire Import Hack.CMP.Bounded.\nRequire Hack.CMP.Arith.\n\n(* The solution was first prototyped in OCaml in p1.ml, and\n   the Coq proof work the same way, by noticing that either:\n   - the valley continues,\n   - the function from there on has a lower bound, and if not,\n   - we've eventually reached a bound of 0 *)\n\nDefinition eventually_bounded_by_at (f: nat -> nat) (n: nat) (x: nat)\n  := forall y, x <= y -> f y <= n.\nDefinition eventually_bounded_by (f: nat -> nat) (n: nat)\n  := exists x, eventually_bounded_by_at f n x.\nDefinition eventually_bounded (f: nat -> nat)\n  := exists n, eventually_bounded_by f n.\n\nTheorem bounded_is_eventually_bounded: forall f, bounded f -> eventually_bounded f.\nProof.\n  intros.\n  destruct H as [b pb].\n  refine (ex_intro _ b _).\n  refine (ex_intro _ 0 _).\n  unfold eventually_bounded_by_at.\n  intros.\n  exact (pb y).\nQed.\n\nDefinition valley (f: nat -> nat)(n x : nat) :=\n  forall y, (x <= y) -> (y <= x+n) -> f y = f x.\n\nLemma eventually_bounded_by_0:\n  forall f,\n  eventually_bounded_by f 0 ->\n  forall n, exists x, valley f n x.\nProof.\n  intros.\n  destruct H as [x px].\n  refine (ex_intro _ x _).\n  unfold valley.\n  intros.\n  transitivity 0.\n  - exact (proj1 (Nat.le_0_r _) (px y H)).\n  - symmetry.\n    exact (proj1 (Nat.le_0_r _) (px x (le_n x))).\nQed.\n\nLemma valley_continues_or_bound_decreases:\n  forall f n x m,\n  decr f ->\n  f x = m -> valley f n x ->\n  valley f (S n) x \\/ (eventually_bounded_by f (pred m)).\nProof.\n  intros.\n  case (Nat.eq_dec (f (x + S n)) m).\n  + intro.\n    left.\n    unfold valley.\n    intros y G0 G1.\n    assert (x + S n = S (x + n)). { apply eq_sym; trivial. }\n    rewrite H2 in G1.\n    case (Arith.leq_and_not _ _ G1).\n    - intro.\n      rewrite H3.\n      rewrite <- H2.\n      transitivity m.\n      * assumption.\n      * symmetry.\n        assumption.\n    - intro.\n      exact (H1 _ G0 H3).\n  + intro.\n    right.\n    refine (ex_intro _ (x + S n) _).\n    intros y H2.\n    pose (p := H1 (x + n) (Nat.le_add_r _ _) (le_n _)).\n    rewrite H0 in p.\n    pose (q := decr_estimate _ H _ _ (proj1 (Nat.add_le_mono_l _ _ x) (le_S n n (le_n _)))).\n    rewrite p in q.\n    exact (Nat.le_trans _ _ _ (decr_estimate _ H _ _ H2) (Arith.leq_and_not'' _ _ q n0)).\nQed.\n\nLemma decr_and_eventually_bounded_by:\n  forall f n m x,\n  decr f ->\n  eventually_bounded_by_at f (S m) x ->\n  valley f n x \\/ (eventually_bounded_by f m).\nProof.\n  intro f.\n  induction n.\n  + intros.\n    left.\n    unfold valley.\n    intros y H1 H2.\n    assert (x = y).\n    - rewrite <- plus_n_O in H2.\n      exact (Nat.le_antisymm _ _ H1 H2).\n    - rewrite H3.\n      reflexivity.\n  + intros m x D pb.\n    case (IHn m x D pb).\n    - intro.\n      case (valley_continues_or_bound_decreases f n x (f x) D eq_refl H).\n      * apply or_introl.\n      * intros H1.\n        right.\n        destruct H1 as [x0 px0].\n        refine (ex_intro _ x0 _).\n        intros y H1.\n        exact (Nat.le_trans _ _ _ (px0 y H1) (Nat.pred_le_mono _ _ (pb x (le_n _)))).\n    - apply or_intror.\nQed.\n\nLemma decr_valleys_lemma:\n  forall m f,\n  eventually_bounded_by f m -> decr f ->\n  forall n, exists x, valley f n x.\nProof.\n  induction m.\n  + intros f eB0 D.\n    exact (eventually_bounded_by_0 f eB0).\n  + intros f eBSM D n.\n    destruct eBSM as [x pb].\n    case (decr_and_eventually_bounded_by f n m x D pb).\n    - intro.\n      refine (ex_intro _ x _).\n      assumption.\n    - intro eBM.\n      exact (IHm f eBM D n).\nQed.\n\nTheorem decr_valleys: forall n f, decr f -> exists x, valley f n x.\nProof.\n  intros.\n  destruct (bounded_is_eventually_bounded f (decr_is_bounded f H)) as [b pb].\n  exact (decr_valleys_lemma b f pb H n).\nQed.\n", "meta": {"author": "rootmos", "repo": "coq-hack", "sha": "957da2727d3d269c0c12fe9294cba33b437da738", "save_path": "github-repos/coq/rootmos-coq-hack", "path": "github-repos/coq/rootmos-coq-hack/coq-hack-957da2727d3d269c0c12fe9294cba33b437da738/src/CMP/P1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7164080107191182}}
{"text": "\n(* Add some trivial facts about nats to the auto hint database,\n   so we don't have to use omega as much. *)\nRequire Import Iron.Tactics.\n\n\nLemma nat_eq_cases\n :  forall (n m : nat) \n ,  n = m \\/ ~(n = m).\nProof. intros. omega. Qed.\nHint Resolve nat_eq_cases.\n\n\nLemma nat_zero_le_all\n : forall n, 0 <= n.\nProof.\n intros. omega.\nQed.\nHint Resolve nat_zero_le_all.\n\n\nLemma nat_zero_lt_succ\n : forall n, 0 < S n.\nProof.\n intros. omega.\nQed.\nHint Resolve nat_zero_lt_succ.\n\n\n(* Don't add transitivity lemmas to the hints database as it\n   can severley degrade performance. *)\nLemma nat_trans_le\n : forall a b c\n , a <= b -> b <= c -> a <= c.\nProof.\n intros. omega.\nQed. \n\n\n(* Normalise naturals to use successor representation instead\n   of addition. *)\nLemma nat_plus_zero\n : forall n, n + 0 = n.\nProof. auto. Qed.\nHint Rewrite nat_plus_zero : global.\n\n\nLemma nat_zero_plus \n :  forall n, 0 + n = n.\nProof. auto. Qed.\nHint Rewrite nat_zero_plus : global.\n\n\nLemma nat_minus_zero\n : forall n, n - 0 = n.\nProof. intros. omega. Qed.\nHint Rewrite nat_minus_zero : global.\n\n\nLemma nat_plus_one\n : forall n, n + 1 = S n.\nProof. intros. omega. Qed.\n\n\n(* Tactics **********************************************************)\n(* Normalise naturals. *)\nTactic Notation \"norm_nat\" \n := first \n    [ rewrite nat_plus_zero\n    | rewrite nat_minus_zero\n    | rewrite nat_plus_one ].\n\n\n(* Convert boolean (in)equalities *)\nLtac eqs_beq_nat\n := repeat match goal with\n    | [ H : true = beq_nat ?n ?m |- _]\n    => symmetry in H; apply beq_nat_true in H\n   \n    | [H : false = beq_nat ?n ?m |- _]\n    => symmetry in H; apply beq_nat_false in H\n    end.\n\n\n(* Break on boolean equality *)\nLtac break_beq_nat\n := match goal with \n     |  [ |- context [beq_nat ?n ?m] ]\n     => let X := fresh in remember (beq_nat n m) as X; destruct X\n    end; eqs_beq_nat.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Data/Nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7163789374473237}}
{"text": "Inductive sign : Type :=\n  | pos : sign\n  | neg : sign.\n\nRecord rational : Type :=\n  { direction   : sign\n  ; numerator   : nat\n  ; denominator : nat (* The /predecesor/ of the denominator, to avoid division by zero *)\n  }.\n\nDefinition reduce_rational (x:rational) : rational :=\n  match x with\n  | {| direction   := s\n     ; numerator   := n\n     ; denominator := d\n     |} => let    gcf := Nat.gcd n (S d)\n           in let n'  := Nat.div n gcf\n           in let d'  := Nat.pred (Nat.div (S d) gcf)\n           in {| direction   := s\n               ; numerator   := n'\n               ; denominator := d'\n               |}\n  end.\n\n(* what does 2/4 reduce to? *)\nEval compute in (reduce_rational {| direction := pos; numerator := 2; denominator := 3 |}).\n\n(* Equality via simplification of factors *)\nDefinition eq_rational (x y : rational) : Prop :=\n  match x,y with\n  | {| numerator   := 0\n     ; denominator := 0\n     |}\n  , {| numerator   := 0\n     ; denominator := 0\n     |} => True (* if both numbers are 0/1 *)\n  | _,_ => match reduce_rational x, reduce_rational y with\n           | {| direction   := s1\n              ; numerator   := n1\n              ; denominator := d1\n              |}\n           , {| direction   := s2\n              ; numerator   := n2\n              ; denominator := d2\n              |} => s1 = s2 /\\ n1 = n2 /\\ d1 = d2 \n           end\n  end.\n\n(* does 1/2 = 2/4? *)\nEval compute in (eq_rational {| direction := pos; numerator := 1; denominator := 1 |}\n                             {| direction := pos; numerator := 2; denominator := 3 |}).\n\n", "meta": {"author": "athanclark", "repo": "simplex-bland-coq", "sha": "a9a767f24de84469b74b7b14bbb8e1c05a777c49", "save_path": "github-repos/coq/athanclark-simplex-bland-coq", "path": "github-repos/coq/athanclark-simplex-bland-coq/simplex-bland-coq-a9a767f24de84469b74b7b14bbb8e1c05a777c49/rational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7163694111517634}}
{"text": "\nFixpoint dist (m n : nat) : nat :=\n  match m with\n  | 0 => n\n  | S m' =>\n    match n with\n    | 0 => m\n    | S n' => dist m' n'\n    end\n  end.\n\nLemma dist_n_0 : forall n,\n  dist n 0 = n.\nProof.\n  destruct n; reflexivity.\nQed.\n\nLemma dist_sym : forall m n,\n  dist m n = dist n m.\nProof.\n  induction m; intro n.\n  - simpl.\n    symmetry; apply dist_n_0.\n  - simpl.\n    destruct n.\n    + reflexivity.\n    + apply IHm.\nQed.\n\n", "meta": {"author": "emarzion", "repo": "coqchess", "sha": "c5f69e87e169709e7c7d2a7c53b6623774d99bc5", "save_path": "github-repos/coq/emarzion-coqchess", "path": "github-repos/coq/emarzion-coqchess/coqchess-c5f69e87e169709e7c7d2a7c53b6623774d99bc5/src/Util/Dist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.716314605099088}}
{"text": "(* BEGIN FIX *)\nInductive AExp : Type :=\n| ALit (n : nat)\n| APlus (a1 a2 : AExp)\n| ASub (a1 a2 : AExp)\n(* END FIX *)\n| AMul (a1 a2 : AExp)\n.\n\n(* BEGIN FIX *)\nFixpoint aeval (a : AExp) : nat :=\nmatch a with\n | ALit n => n\n | APlus a1 a2 => aeval a1 + aeval a2\n | ASub a1 a2 => aeval a1 - aeval a2\n(* END FIX *)\n | AMul a1 a2 => aeval a1 * aeval a2\nend.\n\n(* BEGIN FIX *)\nExample aeval_test1 : forall n : nat, aeval (ALit n) = n.\nProof. reflexivity. Qed.\n(* END FIX *)\n\n(* BEGIN FIX *)\nExample aeval_test2 : forall n m : nat, aeval (APlus (ALit n) (ALit m)) = n + m.\nProof. reflexivity. Qed.\n(* END FIX *)\n\n(* Irj egy tesztet a szorzasra az osszeadas mintajara *)\nExample aeval_test3 : forall n m : nat, aeval (AMul (ALit n) (ALit m)) = n * m.\nProof.\n  reflexivity.\nQed.", "meta": {"author": "Kokan", "repo": "elte_msc", "sha": "2092ccd8f65bf33473eab54e9d7f5facb7eda6e1", "save_path": "github-repos/coq/Kokan-elte_msc", "path": "github-repos/coq/Kokan-elte_msc/elte_msc-2092ccd8f65bf33473eab54e9d7f5facb7eda6e1/formalsemantics/hf04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7163146032254087}}
{"text": "Require Export Poly.\n\nTheorem double_injective':\n  forall n m, double n = double m -> n = m.\nProof.\n  intros n.\n  induction n as [|n'].\n  Case \"n = 0\". simpl. intros m eq.\n  destruct m as [|m'].\n  SCase \"m = 0\". reflexivity.\n  SCase \"m = S m'\". inversion eq.\n  Case \"n = S n'\".\n  intros m eq.\n  destruct m as [|m'].\n  SCase \"m = 0\".\n  inversion eq.\n  SCase \"m = S m'\".\n  assert (n' = m') as H.\n  SSCase \"Proof os assertion\".\n  apply IHn'.\n  inversion eq. reflexivity.\n  rewrite -> H. reflexivity.\nQed.\n\nTheorem double_injective_take2:\n  forall n m, double n = double m -> n = m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m as [|m'].\n  Case \"m=0\". simpl. intros n eq. destruct n as [|n'].\n  SCase \"n=0\". reflexivity.\n  SCase \"n= S n'\". inversion eq.\n  Case \"m= S m'\". intros n eq.\n  destruct n as [|n'].\n  SCase \"n = 0\". inversion eq.\n  SCase \"n = S n'\".\n  assert (n' = m') as H.\n  SSCase \"Proof of assertion\".\n  apply IHm'.\n  inversion eq.\n  reflexivity.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem plus_n_n_injective_take2:\n  forall n m, n + n = m + m -> n = m.\nProof.\n  intros.\n  generalize dependent n.\n  induction m as [|m'].\n  Case \"m=0\".\n  destruct n as [|n'].\n  SCase \"n=0\". reflexivity.\n  SCase \"n=S n'\". intro. inversion H.\n  Case \"m=S m'\".\n  intros.\n  destruct n as [|n'].\n  SCase \"n = 0\".    inversion H.\n  SCase \"n = S n'\".\n  rewrite <- plus_n_Sm in H.\n  rewrite <- plus_n_Sm in H.\n  apply eq_remove_S.\n  apply IHm'.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem index_after_last:\n  forall (n:nat) (X:Type) (l :list X), length l = n -> index (S n) l = None.\nProof.\n  intros.\n  generalize dependent n.\n  induction l as [|l0 l'].\n  Case \"l=[]\".\n  simpl. intros. reflexivity.\n  Case \"l=l0:l'\".\n  simpl. intros.\n  rewrite <- H.\n  apply IHl'.\n  reflexivity.\nQed.\n\n\nTheorem length_snoc''':\n  forall (n : nat) (X : Type) (v : X) (l : list X),\n    length l = n -> length (snoc l v) = S n.\nProof.\n  intros.\n  generalize dependent n.\n  induction l as [| l0 l'].\n  Case \"l=[]\".\n  simpl. intros. rewrite <- H. reflexivity.\n  Case \"l=l0::l'\".\n  simpl. intros. apply eq_remove_S in H. rewrite <- H.\n  apply eq_remove_S.\n  apply IHl'.\n  reflexivity.\nQed.\n\nTheorem app_length_cons:\n  forall (X:Type) (l1 l2:list X) (x : X) (n : nat),\n    length (l1 ++ (x :: l2)) = n -> S (length (l1 ++ l2)) = n.\nProof.\n  intros.\n  generalize dependent n.\n  generalize dependent l2.\n  induction l1 as [|n0 l1'].\n  Case \"l1=[]\".\n  simpl. intros. apply H.\n  Case \"l1=n0 l1'\".\n  simpl. intros. rewrite <- H.\n  apply eq_remove_S. apply IHl1'.\n  reflexivity.\nQed.\n\nTheorem app_length_twice:\n  forall (X:Type) (n:nat) (l:list X),\n    length l = n -> length (l ++ l) = n + n.\nProof.\n  intros.\n  generalize dependent n.\n  induction l as [|n0 l'].\n  Case \"l=[]\".\n  simpl. intros. rewrite <- H. reflexivity.\n  Case \"l=n0:l'\".\n  intros. destruct n.\n  SCase \"n = 0\".\n  inversion H.\n  SCase \"n = S n'\".\n  simpl.\n  remember (length (l' ++ n0 :: l')) as nn.\n  symmetry in Heqnn.\n  apply app_length_cons in Heqnn.\n  rewrite <- Heqnn.\n  rewrite <- plus_n_Sm.\n  assert (length (l' ++ l') = n + n) as H1.\n  inversion H.\n  apply IHl'. reflexivity.\n  rewrite H1.\n  reflexivity.\nQed.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "coq-sf", "sha": "9f5088870d6734cebbbe9937f40b89b04ebd206b", "save_path": "github-repos/coq/seisyuu-hantatsushi-coq-sf", "path": "github-repos/coq/seisyuu-hantatsushi-coq-sf/coq-sf-9f5088870d6734cebbbe9937f40b89b04ebd206b/old/Gen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7163145957717078}}
{"text": "(** * ProofObjects: The Curry-Howard Correspondence *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export IndProp.\n\n(** \"Algorithms are the computational content of proofs.\"\n    (Robert Harper) *)\n\n(** We have seen that Coq has mechanisms both for _programming_,\n    using inductive data types like [nat] or [list] and functions over\n    these types, and for _proving_ properties of these programs, using\n    inductive propositions (like [ev]), implication, universal\n    quantification, and the like.  So far, we have mostly treated\n    these mechanisms as if they were quite separate, and for many\n    purposes this is a good way to think.  But we have also seen hints\n    that Coq's programming and proving facilities are closely related.\n    For example, the keyword [Inductive] is used to declare both data\n    types and propositions, and [->] is used both to describe the type\n    of functions on data and logical implication.  This is not just a\n    syntactic accident!  In fact, programs and proofs in Coq are\n    almost the same thing.  In this chapter we will study how this\n    works.\n\n    We have already seen the fundamental idea: provability in Coq is\n    represented by concrete _evidence_.  When we construct the proof\n    of a basic proposition, we are actually building a tree of\n    evidence, which can be thought of as a data structure.\n\n    If the proposition is an implication like [A -> B], then its proof\n    will be an evidence _transformer_: a recipe for converting\n    evidence for A into evidence for B.  So at a fundamental level,\n    proofs are simply programs that manipulate evidence. *)\n\n(** Question: If evidence is data, what are propositions themselves?\n\n    Answer: They are types! *)\n\n(** Look again at the formal definition of the [ev] property.  *)\n\nPrint ev.\n(* ==>\n  Inductive ev : nat -> Prop :=\n    | ev_0 : ev 0\n    | ev_SS : forall n, ev n -> ev (S (S n)).\n*)\n\n(** Suppose we introduce an alternative pronunciation of \"[:]\".\n    Instead of \"has type,\" we can say \"is a proof of.\"  For example,\n    the second line in the definition of [ev] declares that [ev_0 : ev\n    0].  Instead of \"[ev_0] has type [ev 0],\" we can say that \"[ev_0]\n    is a proof of [ev 0].\" *)\n\n(** This pun between types and propositions -- between [:] as \"has type\"\n    and [:] as \"is a proof of\" or \"is evidence for\" -- is called the\n    _Curry-Howard correspondence_.  It proposes a deep connection\n    between the world of logic and the world of computation:\n\n                 propositions  ~  types\n                 proofs        ~  data values\n\n    See [Wadler 2015] (in Bib.v) for a brief history and up-to-date\n    exposition. *)\n\n(** Many useful insights follow from this connection.  To begin with,\n    it gives us a natural interpretation of the type of the [ev_SS]\n    constructor: *)\n\nCheck ev_SS\n  : forall n,\n    ev n ->\n    ev (S (S n)).\n\n(** This can be read \"[ev_SS] is a constructor that takes two\n    arguments -- a number [n] and evidence for the proposition [ev\n    n] -- and yields evidence for the proposition [ev (S (S n))].\" *)\n\n(** Now let's look again at a previous proof involving [ev]. *)\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\n(** As with ordinary data values and functions, we can use the [Print]\n    command to see the _proof object_ that results from this proof\n    script. *)\n\nPrint ev_4.\n(* ===> ev_4 = ev_SS 2 (ev_SS 0 ev_0)\n      : ev 4  *)\n\n(** Indeed, we can also write down this proof object directly,\n    without the need for a separate proof script: *)\n\nCheck (ev_SS 2 (ev_SS 0 ev_0))\n  : ev 4.\n\n(** The expression [ev_SS 2 (ev_SS 0 ev_0)] can be thought of as\n    instantiating the parameterized constructor [ev_SS] with the\n    specific arguments [2] and [0] plus the corresponding proof\n    objects for its premises [ev 2] and [ev 0].  Alternatively, we can\n    think of [ev_SS] as a primitive \"evidence constructor\" that, when\n    applied to a particular number, wants to be further applied to\n    evidence that this number is even; its type,\n\n      forall n, ev n -> ev (S (S n)),\n\n    expresses this functionality, in the same way that the polymorphic\n    type [forall X, list X] expresses the fact that the constructor\n    [nil] can be thought of as a function from types to empty lists\n    with elements of that type. *)\n\n(** We saw in the [Logic] chapter that we can use function\n    application syntax to instantiate universally quantified variables\n    in lemmas, as well as to supply evidence for assumptions that\n    these lemmas impose.  For instance: *)\n\nTheorem ev_4': ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\n(* ################################################################# *)\n(** * Proof Scripts *)\n\n(** The _proof objects_ we've been discussing lie at the core of how\n    Coq operates.  When Coq is following a proof script, what is\n    happening internally is that it is gradually constructing a proof\n    object -- a term whose type is the proposition being proved.  The\n    tactics between [Proof] and [Qed] tell it how to build up a term\n    of the required type.  To see this process in action, let's use\n    the [Show Proof] command to display the current state of the proof\n    tree at various points in the following tactic proof. *)\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\n(** At any given moment, Coq has constructed a term with a\n    \"hole\" (indicated by [?Goal] here, and so on), and it knows what\n    type of evidence is needed to fill this hole.\n\n    Each hole corresponds to a subgoal, and the proof is\n    finished when there are no more subgoals.  At this point, the\n    evidence we've built is stored in the global context under the name\n    given in the [Theorem] command. *)\n\n(** Tactic proofs are useful and convenient, but they are not\n    essential: in principle, we can always construct the required\n    evidence by hand, as shown above. Then we can use [Definition]\n    (rather than [Theorem]) to give a global name directly to this\n    evidence. *)\n\nDefinition ev_4''' : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\n(** All these different ways of building the proof lead to exactly the\n    same evidence being saved in the global environment. *)\n\nPrint ev_4.\n(* ===> ev_4    =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'.\n(* ===> ev_4'   =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4''.\n(* ===> ev_4''  =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\nPrint ev_4'''.\n(* ===> ev_4''' =   ev_SS 2 (ev_SS 0 ev_0) : ev 4 *)\n\n(** **** Exercise: 2 stars, standard (eight_is_even)\n\n    Give a tactic proof and a proof object showing that [ev 8]. *)\n\nTheorem ev_8 : ev 8.\nProof.\n  repeat constructor.\nQed.\n\nDefinition ev_8' : ev 8 :=\n  ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0))).\n(** [] *)\n\n(* ################################################################# *)\n(** * Quantifiers, Implications, Functions *)\n\n(** In Coq's computational universe (where data structures and\n    programs live), there are two sorts of values that have arrows in\n    their types: _constructors_ introduced by [Inductive]ly defined\n    data types, and _functions_.\n\n    Similarly, in Coq's logical universe (where we carry out proofs),\n    there are two ways of giving evidence for an implication:\n    constructors introduced by [Inductive]ly defined propositions,\n    and... functions! *)\n\n(** For example, consider this statement: *)\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\n(** What is the proof object corresponding to [ev_plus4]?\n\n    We're looking for an expression whose _type_ is [forall n, ev n ->\n    ev (4 + n)] -- that is, a _function_ that takes two arguments (one\n    number and a piece of evidence) and returns a piece of evidence!\n\n    Here it is: *)\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\n(** Recall that [fun n => blah] means \"the function that, given [n],\n    yields [blah],\" and that Coq treats [4 + n] and [S (S (S (S n)))]\n    as synonyms. Another equivalent way to write this definition is: *)\n\nDefinition ev_plus4'' (n : nat) (H : ev n)\n                    : ev (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''\n  : forall n : nat,\n    ev n ->\n    ev (4 + n).\n\n(** When we view the proposition being proved by [ev_plus4] as a\n    function type, one interesting point becomes apparent: The second\n    argument's type, [ev n], mentions the _value_ of the first\n    argument, [n].\n\n    While such _dependent types_ are not found in conventional\n    programming languages, they can be useful in programming too, as\n    the recent flurry of activity in the functional programming\n    community demonstrates. *)\n\n(** Notice that both implication ([->]) and quantification ([forall])\n    correspond to functions on evidence.  In fact, they are really the\n    same thing: [->] is just a shorthand for a degenerate use of\n    [forall] where there is no dependency, i.e., no need to give a\n    name to the type on the left-hand side of the arrow:\n\n           forall (x:nat), nat\n        =  forall (_:nat), nat\n        =  nat -> nat\n*)\n\n(** For example, consider this proposition: *)\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : ev n), ev (n + 2).\n\n(** A proof term inhabiting this proposition would be a function\n    with two arguments: a number [n] and some evidence [E] that [n] is\n    even.  But the name [E] for this evidence is not used in the rest\n    of the statement of [ev_plus2], so it's a bit silly to bother\n    making up a name for it.  We could write it like this instead,\n    using the dummy identifier [_] in place of a real name: *)\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : ev n), ev (n + 2).\n\n(** Or, equivalently, we can write it in a more familiar way: *)\n\nDefinition ev_plus2'' : Prop :=\n  forall n, ev n -> ev (n + 2).\n\n(** In general, \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ################################################################# *)\n(** * Programming with Tactics *)\n\n(** If we can build proofs by giving explicit terms rather than\n    executing tactic scripts, you may be wondering whether we can\n    build _programs_ using _tactics_ rather than explicit terms.\n    Naturally, the answer is yes! *)\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n. Defined.\n\nPrint add1.\n(* ==>\n    add1 = fun n : nat => S n\n         : nat -> nat\n*)\n\nCompute add1 2.\n(* ==> 3 : nat *)\n\n(** Notice that we terminate the [Definition] with a [.] rather than\n    with [:=] followed by a term.  This tells Coq to enter _proof\n    scripting mode_ to build an object of type [nat -> nat].  Also, we\n    terminate the proof with [Defined] rather than [Qed]; this makes\n    the definition _transparent_ so that it can be used in computation\n    like a normally-defined function.  ([Qed]-defined objects are\n    opaque during computation.)\n\n    This feature is mainly useful for writing functions with dependent\n    types, which we won't explore much further in this book.  But it\n    does illustrate the uniformity and orthogonality of the basic\n    ideas in Coq. *)\n\n(* ################################################################# *)\n(** * Logical Connectives as Inductive Types *)\n\n(** Inductive definitions are powerful enough to express most of the\n    connectives we have seen so far.  Indeed, only universal\n    quantification (with implication as a special case) is built into\n    Coq; all the others are defined inductively.  We'll see these\n    definitions in this section. *)\n\nModule Props.\n\n(* ================================================================= *)\n(** ** Conjunction *)\n\n(** To prove that [P /\\ Q] holds, we must present evidence for both\n    [P] and [Q].  Thus, it makes sense to define a proof object for [P\n    /\\ Q] as consisting of a pair of two proofs: one for [P] and\n    another one for [Q]. This leads to the following definition. *)\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n  | conj : P -> Q -> and P Q.\n\nArguments conj [P] [Q].\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** Notice the similarity with the definition of the [prod] type,\n    given in chapter [Poly]; the only difference is that [prod] takes\n    [Type] arguments, whereas [and] takes [Prop] arguments. *)\n\nPrint prod.\n(* ===>\n   Inductive prod (X Y : Type) : Type :=\n   | pair : X -> Y -> X * Y. *)\n\n(** This similarity should clarify why [destruct] and [intros]\n    patterns can be used on a conjunctive hypothesis.  Case analysis\n    allows us to consider all possible ways in which [P /\\ Q] was\n    proved -- here just one (the [conj] constructor). *)\n\nTheorem proj1' : forall P Q,\n  P /\\ Q -> P.\nProof.\n  intros P Q HPQ. destruct HPQ as [HP HQ]. apply HP.\n  Show Proof.\nQed.\n\n(** Similarly, the [split] tactic actually works for any inductively\n    defined proposition with exactly one constructor.  In particular,\n    it works for [and]: *)\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HQ HP]. split.\n    + apply HP.\n    + apply HQ.\nQed.\n\nEnd And.\n\n(** This shows why the inductive definition of [and] can be\n    manipulated by tactics as we've been doing.  We can also use it to\n    build proofs directly, using pattern-matching.  For instance: *)\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) : Q /\\ P :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\n(** **** Exercise: 2 stars, standard (conj_fact)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Disjunction *)\n\n(** The inductive definition of disjunction uses two constructors, one\n    for each side of the disjunct: *)\n\nModule Or.\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nArguments or_introl [P] [Q].\nArguments or_intror [P] [Q].\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** This declaration explains the behavior of the [destruct] tactic on\n    a disjunctive hypothesis, since the generated subgoals match the\n    shape of the [or_introl] and [or_intror] constructors. *)\n\n(** Once again, we can also directly write proof objects for theorems\n    involving [or], without resorting to tactics. *)\n\nDefinition inj_l : forall (P Q : Prop), P -> P \\/ Q :=\n  fun P Q HP => or_introl HP.\n\nTheorem inj_l' : forall (P Q : Prop), P -> P \\/ Q.\nProof.\n  intros P Q HP. left. apply HP.\nQed.\n\nDefinition or_elim : forall (P Q R : Prop), (P \\/ Q) -> (P -> R) -> (Q -> R) -> R :=\n  fun P Q R HPQ HPR HQR =>\n    match HPQ with\n    | or_introl HP => HPR HP\n    | or_intror HQ => HQR HQ\n    end.\n\nTheorem or_elim' : forall (P Q R : Prop), (P \\/ Q) -> (P -> R) -> (Q -> R) -> R.\nProof.\n  intros P Q R HPQ HPR HQR.\n  destruct HPQ as [HP | HQ].\n  - apply HPR. apply HP.\n  - apply HQR. apply HQ.\nQed.\n\nEnd Or.\n\n(** **** Exercise: 2 stars, standard (or_commut')\n\n    Construct a proof object for the following proposition. *)\n\nDefinition or_commut' : forall P Q, P \\/ Q -> Q \\/ P :=\n  fun P Q HPQ =>\n    match HPQ with\n    | or_introl HP => or_intror HP\n    | or_intror HQ => or_introl HQ\n    end.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Existential Quantification *)\n\n(** To give evidence for an existential quantifier, we package a\n    witness [x] together with a proof that [x] satisfies the property\n    [P]: *)\n\nModule Ex.\n\nInductive ex {A : Type} (P : A -> Prop) : Prop :=\n  | ex_intro : forall x : A, P x -> ex P.\n\nNotation \"'exists' x , p\" :=\n  (ex (fun x => p))\n    (at level 200, right associativity) : type_scope.\n\nEnd Ex.\n\n(** This may benefit from a little unpacking.  The core definition is\n    for a type former [ex] that can be used to build propositions of\n    the form [ex P], where [P] itself is a _function_ from witness\n    values in the type [A] to propositions.  The [ex_intro]\n    constructor then offers a way of constructing evidence for [ex P],\n    given a witness [x] and a proof of [P x].\n\n    The notation in the standard library is a slight variant of\n    the above, enabling syntactic forms such as [exists x y, P x y]. *)\n\n(** The more familiar form [exists x, P x] desugars to an expression\n    involving [ex]: *)\n\nCheck ex (fun n => ev n) : Prop.\n\n(** Here's how to define an explicit proof object involving [ex]: *)\n\nDefinition some_nat_is_even : exists n, ev n :=\n  ex_intro ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** **** Exercise: 2 stars, standard (ex_ev_Sn)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) :=\n    ex_intro (fun n => ev (S n)) 3 (ev_SS 2 (ev_SS 0 ev_0)).\n(** [] *)\n\n(* ================================================================= *)\n(** ** [True] and [False] *)\n\n(** The inductive definition of the [True] proposition is simple: *)\n\nInductive True : Prop :=\n  | I : True.\n\n(** It has one constructor (so every proof of [True] is the same, so\n    being given a proof of [True] is not informative.) *)\n\n(** **** Exercise: 1 star, standard (p_implies_true)\n\n    Construct a proof object for the following proposition. *)\n\nDefinition p_implies_true : forall P, P -> True :=\n  fun P HP => I.\n(** [] *)\n\n(** [False] is equally simple -- indeed, so simple it may look\n    syntactically wrong at first glance! *)\n\nInductive False : Prop := .\n\n(** That is, [False] is an inductive type with _no_ constructors --\n    i.e., no way to build evidence for it. For example, there is\n    no way to complete the following definition such that it\n    succeeds (rather than fails). *)\n\nFail Definition contra : False :=\n  0 = 1.\n\n(** But it is possible to destruct [False] by pattern matching. There can\n    be no patterns that match it, since it has no constructors.  So\n    the pattern match also is so simple it may look syntactically\n    wrong at first glance. *)\n\nDefinition false_implies_zero_eq_one : False -> 0 = 1 :=\n  fun contra => match contra with end.\n\n(** Since there are no branches to evaluate, the [match] expression\n    can be considered to have any type we want, including [0 = 1].\n    Indeed, it's impossible to ever cause the [match] to be evaluated,\n    because we can never construct a value of type [False] to pass to\n    the function. *)\n\n(** **** Exercise: 1 star, standard (ex_falso_quodlibet')\n\n    Construct a proof object for the following proposition. *)\n\nDefinition ex_falso_quodlibet' : forall P, False -> P :=\n  fun P contra => match contra with end.\n(** [] *)\n\nEnd Props.\n\n(* ################################################################# *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  We can define\n    it ourselves: *)\n\nModule MyEquality.\n\nInductive eq {X:Type} : X -> X -> Prop :=\n  | eq_refl : forall x, eq x x.\n\nNotation \"x == y\" := (eq x y)\n                       (at level 70, no associativity)\n                     : type_scope.\n\n(** The way to think about this definition (which is just a slight\n    variant of the standard library's) is that, given a set [X], it\n    defines a _family_ of propositions \"[x] is equal to [y],\" indexed\n    by pairs of values ([x] and [y]) from [X].  There is just one way\n    of constructing evidence for members of this family: applying the\n    constructor [eq_refl] to a type [X] and a single value [x : X],\n    which yields evidence that [x] is equal to [x].\n\n    Other types of the form [eq x y] where [x] and [y] are not the\n    same are thus uninhabited. *)\n\n(** We can use [eq_refl] to construct evidence that, for example, [2 =\n    2].  Can we also use it to construct evidence that [1 + 1 = 2]?\n    Yes, we can.  Indeed, it is the very same piece of evidence!\n\n    The reason is that Coq treats as \"the same\" any two terms that are\n    _convertible_ according to a simple set of computation rules.\n\n    These rules, which are similar to those used by [Compute], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.  *)\n\nLemma four: 2 + 2 == 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\n(** The [reflexivity] tactic that we have used to prove\n    equalities up to now is essentially just shorthand for [apply\n    eq_refl].\n\n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).\n\n    But you can see them directly at work in the following explicit\n    proof objects: *)\n\nDefinition four' : 2 + 2 == 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X:Type) (x:X), []++[x] == x::[]  :=\n  fun (X:Type) (x:X) => eq_refl [x].\n\n(** **** Exercise: 2 stars, standard (equality__leibniz_equality)\n\n    The inductive definition of equality implies _Leibniz equality_:\n    what we mean when we say \"[x] and [y] are equal\" is that every\n    property on [P] that is true of [x] is also true of [y].  *)\n\nLemma equality__leibniz_equality : forall (X : Type) (x y: X),\n  x == y -> forall P:X->Prop, P x -> P y.\nProof.\n  intros.\n  inversion H.\n  subst.\n  assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, optional (leibniz_equality__equality)\n\n    Show that, in fact, the inductive definition of equality is\n    _equivalent_ to Leibniz equality.  Hint: the proof is quite short;\n    about all you need to do is to invent a clever property [P] to\n    instantiate the antecedent.*)\n\nLemma leibniz_equality__equality : forall (X : Type) (x y: X),\n  (forall P:X->Prop, P x -> P y) -> x == y.\nProof.\n  intros.\n  specialize (H (fun z => x == z)).\n  simpl in H.\n  assert (x == x). {constructor. }\n  apply H in H0.\n  assumption.\nQed.\n(** [] *)\n\nEnd MyEquality.\n\n(* ================================================================= *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves.\n\n    In general, the [inversion] tactic...\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n\n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are\n    two constructors, so two subgoals get generated.  The\n    conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [and], there is\n    only one constructor, so only one subgoal gets generated.  Again,\n    the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n    place any restrictions on the form of [P] or [Q], so we don't get\n    any extra equalities in the context of the subgoal.  The\n    constructor does have two arguments, though, and these can be seen\n    in the context in the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [eq], there is\n    again only one constructor, so only one subgoal gets generated.\n    Now, though, the form of the [eq_refl] constructor does give us\n    some extra information: it tells us that the two arguments to [eq]\n    must be the same!  The [inversion] tactic adds this fact to the\n    context. *)\n\n(* ################################################################# *)\n(** * The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is\n    \"why trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on. *)\n\n(** There are a few additional wrinkles:\n\n    First, since Coq types can themselves be expressions, the checker\n    must normalize these (by using the computation rules) before\n    comparing them.\n\n    Second, the checker must make sure that [match] expressions are\n    _exhaustive_.  That is, there must be an arm for every possible\n    constructor.  To see why, consider the following alleged proof\n    object: *)\n\nFail Definition or_bogus : forall P Q, P \\/ Q -> P :=\n  fun (P Q : Prop) (A : P \\/ Q) =>\n    match A with\n    | or_introl H => H\n    end.\n\n(** All the types here match correctly, but the [match] only\n    considers one of the possible constructors for [or].  Coq's\n    exhaustiveness check will reject this definition.\n\n    Third, the checker must make sure that each recursive function\n    terminates.  It does this using a syntactic check to make sure\n    that each recursive call is on a subexpression of the original\n    argument.  To see why this is essential, consider this alleged\n    proof: *)\n\nFail Fixpoint infinite_loop {X : Type} (n : nat) {struct n} : X :=\n  infinite_loop n.\nFail Definition falso : False := infinite_loop 0.\n\n(** Recursive function [infinite_loop] purports to return a\n    value of any type [X] that you would like.  (The [struct]\n    annotation on the function tells Coq that it recurses on argument\n    [n], not [X].)  Were Coq to allow [infinite_loop], then [falso]\n    would be definable, thus giving evidence for [False].  So Coq rejects\n    [infinite_loop]. *)\n\n(** Note that the soundness of Coq depends only on the\n    correctness of this typechecking engine, not on the tactic\n    machinery.  If there is a bug in a tactic implementation (and this\n    certainly does happen!), that tactic might construct an invalid\n    proof term.  But when you type [Qed], Coq checks the term for\n    validity from scratch.  Only theorems whose proofs pass the\n    type-checker can be used in further proof developments.  *)\n\n(* 2021-08-11 15:08 *)\n", "meta": {"author": "jiangsy", "repo": "fp_course", "sha": "b724bc18ae1587bf4bfdb7ebfb6c1852f14c4b88", "save_path": "github-repos/coq/jiangsy-fp_course", "path": "github-repos/coq/jiangsy-fp_course/fp_course-b724bc18ae1587bf4bfdb7ebfb6c1852f14c4b88/sf/lf/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.7163145952776531}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Print All.\n\n(* csm_5_set_theory.v は不使用である。 *)\n\nSection ライブラリfinsetの利用.\n  Variable M : finType.\n\n  Check setP : forall (T : finType) (A B : {set T}), A =i B <-> A = B. (* 定理 *)\n  \n  (* 有限集合の ∪ (:|:) と ∩ (:&:) を ∈ (\\in) と || と && にする。 *)\n  Check in_setU : forall (T : finType) (x : T) (A B : {set T}),\n      (x \\in A :|: B) = (x \\in A) || (x \\in B).\n  \n  Check in_setI : forall (T : finType) (x : T) (A B : {set T}),\n      (x \\in A :&: B) = (x \\in A) && (x \\in B).\n  \n  (* 実際は、inEだけ覚えておけばよい。 *)\n  Check inE.                                (* 略 *)\n  \n  Lemma demorgan (A B C : {set M}) : (A :&: B) :|: C = (A :|: C) :&: (B :|: C).\n  Proof.\n    (* = を =i に変換する。 *)\n    (* ``P =i Q`` は ``∀x, x \\in P = x \\in Q`` の構文糖衣である。 *)\n    apply/setP => x.\n    (* Goal : A :&: B :|: C =i (A :|: C) :&: (B :|: C) *)\n    (* Goal : (x \\in A :&: B :|: C) = (x \\in (A :|: C) :&: (B :|: C)) *)\n\n    (* Goal : (x \\in A :&: B :|: C) = (x \\in (A :|: C) :&: (B :|: C)) *)\n    (* :|: と :&: を || と && に変換する。 *)\n(*\n    rewrite !in_setU.\n    rewrite !in_setI.    \n    rewrite !in_setU.\n    Undo 3.\n*)    \n    rewrite !inE.\n    (* Goal : (x \\in A) && (x \\in B) || (x \\in C) =\n       ((x \\in A) || (x \\in C)) && ((x \\in B) || (x \\in C)) *)\n    \n    (* || と && の ド・モルガンの定理 *)\n    Check orb_andl : forall x y z : bool, x && y || z = (x || z) && (y || z).\n      by rewrite -orb_andl.\n  Qed.\n  \nEnd ライブラリfinsetの利用.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/csm/csm_5_set_theory_finset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7163145938775206}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_NCdistinct.\nRequire Import ProofCheckingEuclid.lemma_congruenceflip.\nRequire Import ProofCheckingEuclid.lemma_s_onray_assert_ABB.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_conga_sss :\n\tforall A B C a b c,\n\tCong A B a b->\n\tCong A C a c ->\n\tCong B C b c ->\n\tnCol A B C ->\n\tnCol a b c ->\n\tCongA A B C a b c.\nProof.\n\tintros A B C a b c.\n\tintros Cong_AB_ab.\n\tintros Cong_AC_ac.\n\tintros Cong_BC_bc.\n\tintros nCol_A_B_C.\n\tintros nCol_a_b_c.\n\n\tpose proof (\n\t\tlemma_NCdistinct _ _ _ nCol_A_B_C\n\t) as (_ & neq_B_C & _ & neq_B_A & _).\n\tpose proof (lemma_s_onray_assert_ABB _ _ neq_B_A) as OnRay_BA_A.\n\tpose proof (lemma_s_onray_assert_ABB _ _ neq_B_C) as OnRay_BC_C.\n\n\tpose proof (\n\t\tlemma_NCdistinct _ _ _ nCol_a_b_c\n\t) as (neq_a_b & neq_b_c & neq_a_c & neq_b_a & _).\n\tpose proof (lemma_s_onray_assert_ABB _ _ neq_b_a) as OnRay_ba_a.\n\tpose proof (lemma_s_onray_assert_ABB _ _ neq_b_c) as OnRay_bc_c.\n\n\tpose proof (lemma_congruenceflip _ _ _ _ Cong_AB_ab) as (Cong_BA_ba & _).\n\n\tunfold CongA.\n\texists A, C, a, c.\n\tsplit.\n\texact OnRay_BA_A.\n\tsplit.\n\texact OnRay_BC_C.\n\tsplit.\n\texact OnRay_ba_a.\n\tsplit.\n\texact OnRay_bc_c.\n\tsplit.\n\texact Cong_BA_ba.\n\tsplit.\n\texact Cong_BC_bc.\n\tsplit.\n\texact Cong_AC_ac.\n\texact nCol_A_B_C.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_conga_sss.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7163145864238194}}
{"text": "(**********************************************************************\n\n Hom functor for enriched categories\n\n Enrichments can also be formulated using functors and natural\n transformations. In this file, we show that every enrichment gives\n rise to a hom functor, and that the identity and composition give rise\n to natural transformations.\n\n Note that formulating enrichments using functors and natural\n transformations have additional laws, which expresses the\n functoriality and the naturality of the hom-functor and the identity\n and composition. The laws for enrichments have the same formulation\n irregardless of whether we use a formulation with functors and\n transformations or as given in Enrichments.v.\n\n Contents\n 1. The enriched hom functor\n 2. The transformation that is pointwise the enriched identity\n 3. The transformation that is pointwise the enriched composition\n\n **********************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.Univalence.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.opp_precat.\nRequire Import UniMath.CategoryTheory.Core.\nRequire Import UniMath.CategoryTheory.PrecategoryBinProduct.\nRequire Import UniMath.CategoryTheory.EnrichedCats.Enrichment.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentFunctor.\nRequire Import UniMath.CategoryTheory.EnrichedCats.EnrichmentTransformation.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\n\nImport MonoidalNotations.\n\nLocal Open Scope cat.\nLocal Open Scope moncat.\n\nLocal Notation \"C ⊠ D\" := (category_binproduct C D) (at level 38).\n\nSection HomFunctor.\n  Context {V : monoidal_cat}\n          {C : category}\n          (E : enrichment C V).\n\n  (**\n   1. The enriched hom functor\n   *)\n  Definition enriched_hom_functor_data\n    : functor_data (category_binproduct C^op C) V.\n  Proof.\n    use make_functor_data.\n    - exact (λ x, E ⦃ pr1 x , pr2 x ⦄).\n    - exact (λ x y f, precomp_arr E (pr2 x) (pr1 f) · postcomp_arr E (pr1 y) (pr2 f)).\n  Defined.\n\n  Definition enriched_hom_functor_laws\n    : is_functor enriched_hom_functor_data.\n  Proof.\n    split.\n    - intros x ; cbn.\n      rewrite precomp_arr_id, postcomp_arr_id.\n      apply id_left.\n    - intros x y z f g ; cbn.\n      rewrite precomp_arr_comp, postcomp_arr_comp ; cbn.\n      rewrite !assoc'.\n      apply maponpaths.\n      rewrite !assoc.\n      apply maponpaths_2.\n      apply precomp_postcomp_arr.\n  Qed.\n\n  Definition enriched_hom_functor\n    : category_binproduct C^op C ⟶ V.\n  Proof.\n    use make_functor.\n    - exact enriched_hom_functor_data.\n    - exact enriched_hom_functor_laws.\n  Defined.\n\n  (**\n   2. The transformation that is pointwise the enriched identity\n   *)\n  Definition enriched_id_nat_trans_data\n    : nat_trans_data\n        (constant_functor (core C) V (I_{V}))\n        (core_diag C ∙ enriched_hom_functor)\n    := λ x, enriched_id E x.\n\n  Definition enriched_id_nat_trans_laws\n    : is_nat_trans\n        _ _\n        enriched_id_nat_trans_data.\n  Proof.\n    intros x y f ; unfold enriched_id_nat_trans_data ; cbn.\n    rewrite id_left.\n    rewrite !assoc.\n    refine (!_).\n    etrans.\n    {\n      apply maponpaths_2.\n      apply enriched_id_precomp_arr.\n    }\n    etrans.\n    {\n      apply enriched_from_arr_postcomp.\n    }\n    etrans.\n    {\n      apply maponpaths.\n      exact (z_iso_after_z_iso_inv f).\n    }\n    apply enriched_from_arr_id.\n  Qed.\n\n  Definition enriched_id_nat_trans\n    : constant_functor _ V (I_{V}) ⟹ core_diag _ ∙ enriched_hom_functor.\n  Proof.\n    use make_nat_trans.\n    - exact enriched_id_nat_trans_data.\n    - exact enriched_id_nat_trans_laws.\n  Defined.\n\n  (**\n   3. The transformation that is pointwise the enriched composition\n   *)\n  Definition enriched_comp_nat_trans_left_functor\n    : category_binproduct (category_binproduct C^op (core C)) C ⟶ V\n    := bindelta_pair_functor\n         (bindelta_pair_functor\n            (pr1_functor _ _ ∙ pr2_functor _ _ ∙ functor_core_op _)\n            (pr2_functor _ _)\n            ∙ enriched_hom_functor)\n         (bindelta_pair_functor\n            (pr1_functor _ _ ∙ pr1_functor _ _)\n            (pr1_functor _ _ ∙ pr2_functor _ _ ∙ functor_core _)\n          ∙ enriched_hom_functor)\n       ∙ monoidal_cat_tensor _.\n\n  Definition enriched_comp_nat_trans_right_functor\n    : C^op ⊠ core C ⊠ C ⟶ V\n    := bindelta_pair_functor\n         (pr1_functor _ _ ∙ pr1_functor _ _)\n         (pr2_functor _ _)\n       ∙ enriched_hom_functor.\n\n  Definition enriched_comp_nat_trans_data\n    : nat_trans_data\n        enriched_comp_nat_trans_left_functor\n        enriched_comp_nat_trans_right_functor\n    := λ x, enriched_comp E (pr11 x) (pr21 x) (pr2 x).\n\n  Definition enriched_comp_nat_trans_laws\n    : is_nat_trans _ _ enriched_comp_nat_trans_data.\n  Proof.\n    intros x y f ; cbn.\n    enough ((precomp_arr E (pr2 x) (inv_from_z_iso (pr21 f))\n             · postcomp_arr E (pr21 y) (pr2 f))\n            #⊗ (precomp_arr E (pr21 x) (pr11 f) · postcomp_arr E (pr11 y) (pr121 f))\n            · enriched_comp_nat_trans_data y\n            =\n            enriched_comp_nat_trans_data x\n            · precomp_arr E (pr2 x) (pr11 f)\n            · postcomp_arr E (pr11 y) (pr2 f)) as X.\n    {\n      rewrite !assoc.\n      exact X.\n    }\n    unfold enriched_comp_nat_trans_data.\n    refine (!_).\n    etrans.\n    {\n      apply maponpaths_2.\n      apply enriched_comp_precomp_arr.\n    }\n    rewrite !assoc'.\n    etrans.\n    {\n      apply maponpaths.\n      apply enriched_comp_postcomp_arr.\n    }\n    rewrite !assoc.\n    etrans.\n    {\n      apply maponpaths_2.\n      exact (!(tensor_split _ _)).\n    }\n    refine (!_).\n    etrans.\n    {\n      apply maponpaths_2.\n      etrans.\n      {\n        apply maponpaths_2.\n        apply precomp_postcomp_arr.\n      }\n      apply tensor_comp_mor.\n    }\n    rewrite !assoc'.\n    apply maponpaths.\n    etrans.\n    {\n      apply maponpaths_2.\n      apply tensor_split.\n    }\n    unfold precomp_arr.\n    etrans.\n    {\n      rewrite !assoc'.\n      apply maponpaths.\n      rewrite !assoc.\n      apply maponpaths_2.\n      apply tensor_comp_id_r.\n    }\n    rewrite !assoc'.\n    etrans.\n    {\n      do 2 apply maponpaths.\n      apply enrichment_assoc.\n    }\n    rewrite !assoc.\n    refine (_ @ id_left _).\n    apply maponpaths_2.\n    rewrite !assoc'.\n    etrans.\n    {\n      apply maponpaths.\n      etrans.\n      {\n        apply maponpaths_2.\n        apply tensor_comp_id_r.\n      }\n      rewrite !assoc'.\n      apply maponpaths.\n      rewrite !assoc.\n      etrans.\n      {\n        apply maponpaths_2.\n        apply tensor_lassociator.\n      }\n      rewrite !assoc'.\n      apply maponpaths.\n      exact (!(tensor_comp_id_l _ _)).\n    }\n    etrans.\n    {\n      apply maponpaths.\n      rewrite !assoc.\n      apply maponpaths_2.\n      refine (!_).\n      apply mon_inv_triangle.\n    }\n    etrans.\n    {\n      apply maponpaths.\n      exact (!(tensor_comp_id_l _ _)).\n    }\n    refine (!(tensor_comp_id_l _ _) @ _).\n    refine (_ @ tensor_id_id _ _).\n    apply maponpaths.\n    refine (_ @ !(postcomp_arr_comp E (pr121 f) (inv_from_z_iso (pr21 f))) @ _).\n    - apply maponpaths.\n      rewrite !assoc.\n      apply idpath.\n    - etrans.\n      {\n        apply maponpaths.\n        exact (z_iso_inv_after_z_iso (pr21 f)).\n      }\n      apply postcomp_arr_id.\n  Qed.\n\n  Definition enriched_comp_nat_trans\n    : enriched_comp_nat_trans_left_functor ⟹ enriched_comp_nat_trans_right_functor.\n  Proof.\n    use make_nat_trans.\n    - exact enriched_comp_nat_trans_data.\n    - exact enriched_comp_nat_trans_laws.\n  Defined.\nEnd HomFunctor.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/EnrichedCats/Examples/HomFunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7162792741274648}}
{"text": "Require Import Lia Frap Datatypes.\nRequire Import Compare_dec.\n\nNotation t := nat.\n\nInductive tree :=\n| Leaf (* an empty tree *)\n| Node (d : t) (l r : tree).\n\nNotation compare := Compare_dec.lt_eq_lt_dec.\nNotation Lt := (inleft (left _)) (only parsing).\nNotation Eq := (inleft (right _)) (only parsing).\nNotation Gt := (inright _) (only parsing).\n\nModule Type S.\n  Definition Singleton (v: t) := Node v Leaf Leaf.\n  Parameter bst : forall (tr : tree) (s : t -> Prop), Prop.\n\n  Parameter rotate : tree -> tree.\n\n  (*[10%]*) Axiom bst_rotate : forall T s (H : bst T s), bst (rotate T) s.\n\n  Fixpoint insert (a: t) (tr: tree) : tree :=\n    match tr with\n    | Leaf => Singleton a\n    | Node v lt rt =>\n      match compare a v with\n      | Lt => Node v (insert a lt) rt\n      | Eq => tr\n      | Gt => Node v lt (insert a rt)\n      end\n    end.\n\n  Fixpoint rightmost (tr: tree) : option t :=\n    match tr with\n    | Leaf => None\n    | Node v _ rt =>\n      match rightmost rt with\n      | None => Some v\n      | r => r\n      end\n    end.\n\n  Definition is_leaf (tr : tree) : bool :=\n    match tr with Leaf => true | _ => false end.\n\n  Fixpoint delete_rightmost (tr: tree) : tree :=\n    match tr with\n    | Leaf => Leaf\n    | Node v lt rt =>\n      if is_leaf rt\n      then lt\n      else Node v lt (delete_rightmost rt)\n    end.\n\n  Definition merge_ordered lt rt :=\n    match rightmost lt with\n    | Some rv => Node rv (delete_rightmost lt) rt\n    | None => rt\n    end.\n\n  Fixpoint delete (a: t) (tr: tree) : tree :=\n    match tr with\n    | Leaf => Leaf\n    | Node v lt rt =>\n      match compare a v with\n      | Lt => Node v (delete a lt) rt\n      | Eq => merge_ordered lt rt\n      | Gt => Node v lt (delete a rt)\n      end\n    end.\n\n  (*[40%]*) Axiom bst_insert :\n    forall tr s a,\n      bst tr s ->\n      bst (insert a tr) (fun x => s x \\/ x = a).\n\n  (*[50%]*) Axiom bst_delete :\n    forall tr s a, bst tr s ->\n              bst (delete a tr) (fun x => s x /\\ x <> a).\nEnd S.\n\n(* three-way comparisions and [cases] support for them *)\nLtac cases E :=\n  (is_var E; destruct E) ||\n    match type of E with\n    | sumor (sumbool _ _) _ => destruct E as [[]|]\n    | {_} + {_} => destruct E\n    | _ => let Heq := fresh \"Heq\" in\n           destruct E eqn:Heq\n    end;\n   repeat\n    match goal with\n    | H:_ = left _ |- _ => clear H\n    | H:_ = right _ |- _ => clear H\n    | H:_ = inleft _ |- _ => clear H\n    | H:_ = inright _ |- _ => clear H\n    end.\n", "meta": {"author": "mit-frap", "repo": "spring21", "sha": "20ecdeccfda50653abcdeb253dfc8118099f8c40", "save_path": "github-repos/coq/mit-frap-spring21", "path": "github-repos/coq/mit-frap-spring21/spring21-20ecdeccfda50653abcdeb253dfc8118099f8c40/pset04_BSTs/Pset4Sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.716279267407689}}
{"text": "Require Export XR_Rplus_assoc.\nRequire Export XR_Rplus_0_l.\nRequire Export XR_Rplus_opp_l.\nRequire Export XR_Rplus_lt_compat_l.\n\nLocal Open Scope R_scope.\n\nLemma Rplus_lt_reg_l : forall r r1 r2, r + r1 < r + r2 -> r1 < r2.\nProof.\n  intros x y z.\n  intro h.\n  pattern y ; rewrite <- Rplus_0_l.\n  pattern z ; rewrite <- Rplus_0_l.\n  rewrite <- Rplus_opp_l with x.\n  repeat rewrite Rplus_assoc.\n  apply Rplus_lt_compat_l.\n  exact h.\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rplus_lt_reg_l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.716212408692678}}
{"text": "(* This file contains basic definitions and lemmas common to all other files in \n  the repository. *)\n\nRequire Import vcfloat.VCFloat.\n\nDefinition rounded (t : type) r:=\n(Generic_fmt.round Zaux.radix2 (SpecFloat.fexp (fprec t) (femax t))\n     (BinarySingleNaN.round_mode BinarySingleNaN.mode_NE) r).\n\nDefinition neg_zero {t: type} := Binary.B754_zero (fprec t) (femax t) true.\n\nSection NAN.\n\nDefinition default_rel (t: FPCore.type) : R :=\n  / 2 * Raux.bpow Zaux.radix2 (- fprec t + 1).\n\nDefinition default_abs (t: FPCore.type) : R :=\n  / 2 * Raux.bpow Zaux.radix2 (3 - femax t - fprec t).\n\nLemma default_rel_sep_0 t : \n  default_rel t <> 0.\nProof. \nunfold default_rel; apply Rabs_lt_pos.\nrewrite Rabs_pos_eq; [apply Rmult_lt_0_compat; try nra; apply bpow_gt_0 | \n  apply Rmult_le_pos; try nra; apply bpow_ge_0].\nQed.\n\nLemma default_rel_gt_0 t : \n  0 < default_rel t.\nProof. \nunfold default_rel.\napply Rmult_lt_0_compat; try nra.\napply bpow_gt_0.\nQed.\n \nLemma default_rel_ge_0 t : \n  0 <= default_rel t.\nProof. apply Rlt_le; apply default_rel_gt_0; auto. Qed.\n\nLemma default_rel_plus_1_ge_1 t :\n1 <= 1 + default_rel t.\nProof. \nrewrite Rplus_comm. \napply Rcomplements.Rle_minus_l; field_simplify.\napply default_rel_ge_0.\nQed.\n\nLemma default_rel_plus_1_gt_1 t :\n1 < 1 + default_rel t.\nProof.\nrewrite Rplus_comm. \napply Rcomplements.Rlt_minus_l; field_simplify.\napply default_rel_gt_0.\nQed.\n\nLemma default_rel_plus_1_gt_0 t :\n0 < 1 + default_rel t.\nProof.\neapply Rlt_trans with 1; [nra | ].\napply default_rel_plus_1_gt_1.\nQed.\n\n\nLemma default_rel_plus_1_ge_1' t n:\n1 <= (1 + default_rel t) ^ n.\nProof. \ninduction n; simpl; auto; try nra.\neapply Rle_trans with (1 * 1); try nra.\napply Rmult_le_compat; try nra.\napply default_rel_plus_1_ge_1.\nQed.\n\nLemma default_abs_gt_0 t : \n  0 < default_abs t.\nProof. \nunfold default_abs.\napply Rmult_lt_0_compat; try nra.\napply bpow_gt_0.\nQed.\n\nLemma default_abs_ge_0 t :\n  0 <= default_abs t.\nProof. apply Rlt_le; apply default_abs_gt_0; auto. Qed.\n\nDefinition g (t: type) (n: nat) : R := ((1 + (default_rel t )) ^ n - 1).\n\nLemma g_pos t n: \n  0 <= g t n. \nProof. \nunfold g. induction n.\nsimpl; nra. eapply Rle_trans; [apply IHn| apply Rplus_le_compat; try nra].\nsimpl. eapply Rle_trans with (1 * (1+default_rel t)^n); try nra.\napply Rmult_le_compat; try nra. rewrite Rplus_comm. apply Rcomplements.Rle_minus_l.\nfield_simplify. apply default_rel_ge_0.\nQed.\n\nLemma le_g_Sn t n : \n  g t n <= g t (S n).\nProof. \ninduction n; unfold g; simpl.\n  { field_simplify. apply default_rel_ge_0. }\n  unfold g in IHn. eapply Rplus_le_compat; try nra.\n  eapply Rmult_le_compat_l.\n  apply Rplus_le_le_0_compat; try nra; try apply default_rel_ge_0.\n  rewrite tech_pow_Rmult. apply Rle_pow; try lia.\n  rewrite Rplus_comm. apply Rcomplements.Rle_minus_l.\n  field_simplify; apply default_rel_ge_0. \nQed.\n\nLemma d_le_g t n:\ndefault_rel t <= g t (n + 1).\nProof. unfold g. induction n; simpl; field_simplify; try nra.\neapply Rle_trans; [apply IHn|].\napply Rplus_le_compat_r.\nreplace (default_rel t * (1 + default_rel t) ^ (n + 1) + (1 + default_rel t) ^ (n + 1))\nwith \n((1 + default_rel t) ^ (n + 1) * (default_rel t  + 1)) by nra.\neapply Rle_trans with ((1 + default_rel t) ^ (n + 1) * 1); try nra.\neapply Rmult_le_compat; try nra.\n{ apply pow_le. apply Fourier_util.Rle_zero_pos_plus1. apply default_rel_ge_0. }\napply Rcomplements.Rle_minus_l. field_simplify; apply default_rel_ge_0.\nQed.\n\nLemma d_le_g_1 t n:\n(1<= n)%nat -> default_rel t <= g t n.\nProof. \nintros; unfold g. \neapply Rle_trans with ((1 + default_rel t)^1 - 1).\nfield_simplify; nra.\napply Rplus_le_compat; try nra.\napply Rle_pow; try lia.\napply default_rel_plus_1_ge_1.\nQed.\n\n\nLemma one_plus_d_mul_g t a n:\n  (1 + default_rel t) * g t n * a + default_rel t * a  = g t (n + 1) * a.\nProof. unfold g. rewrite Rmult_minus_distr_l. rewrite tech_pow_Rmult. \nfield_simplify. f_equal. rewrite Rmult_comm; repeat f_equal; lia.\nQed.\n   \n\nDefinition g1 (t: type) (n1: nat) (n2: nat) : R := \n  INR n1 * default_abs t * (1 + g t n2 ).\n\nLemma g1_pos t n m : 0 <= g1 t n m. \nProof. unfold g1.\napply Rmult_le_pos; try apply pos_INR.\napply Rmult_le_pos; try apply pos_INR.\napply default_abs_ge_0. unfold g; field_simplify.\napply pow_le.\napply Fourier_util.Rle_zero_pos_plus1.\napply default_rel_ge_0. \nQed.\n\nLemma one_plus_d_mul_g1 t n:\n(1 <= n )%nat ->\ng1 t n (n - 1) * (1 + default_rel t)  =  g1 t n n.\nProof.\nintros.\nunfold g1, g; field_simplify.\nsymmetry. replace n with (S (n-1)) at 2.\nrewrite <- tech_pow_Rmult.\nfield_simplify; nra.\nrewrite <- Nat.sub_succ_l; auto.\nsimpl; lia.\nQed.\n\nLemma one_plus_d_mul_g1' t n m:\ng1 t n m * (1 + default_rel t)  =  g1 t n (S m).\nProof.\nintros.\nunfold g1, g; field_simplify.\nsymmetry. \nrewrite <- tech_pow_Rmult.\nfield_simplify; nra.\nQed.\n\nLemma e_le_g1 t n:\n(1 <= n )%nat ->\ndefault_abs t <= g1 t n n.\nProof.\nintros; unfold g1. eapply Rle_trans with (1 * default_abs t * 1); try nra.\napply Rmult_le_compat; try nra.\nrewrite Rmult_1_l.\napply default_abs_ge_0.\napply Rmult_le_compat; try nra.\napply default_abs_ge_0.\nreplace 1 with (INR 1) by (simpl; nra).\napply le_INR; auto.\nrewrite Rplus_comm.\napply Rcomplements.Rle_minus_l.\nfield_simplify; apply g_pos.\nQed.\n\nLemma plus_d_e_g1_le' t n m:\n(1 <= n )%nat -> (1 <= m)%nat ->\ng1 t n m + (1 + default_rel t) * default_abs t <= g1 t (S n) m.\nProof.\nintros; replace (S n) with (n + 1)%nat by lia.\nunfold g1; field_simplify.\nreplace (INR (n + 1)) with (INR n + 1).\nrewrite !Rmult_plus_distr_l.\nrewrite !Rmult_1_r. rewrite <- Rplus_assoc.\napply Rplus_le_compat_r.\nrewrite Rplus_comm.\nrewrite Rmult_comm.\nrewrite Rplus_comm.\nrewrite Rmult_assoc.\nrewrite  Rmult_comm.\nrewrite !Rplus_assoc.\napply Rplus_le_compat_l.\nrewrite  Rmult_comm.\nrewrite Rplus_comm.\napply Rplus_le_compat_r.\nrewrite  Rmult_comm.\napply Rmult_le_compat_l.\napply default_abs_ge_0.\napply d_le_g_1; auto.\nrewrite Nat.add_comm. \nrewrite S_O_plus_INR. simpl; nra.\nQed.\n\nLemma mult_d_e_g1_le' t n m:\n(1 <= n )%nat -> (1 <= m)%nat ->\ng1 t n m * (1 + default_rel t)  + default_abs t <= g1 t (S n) (S m).\nProof.\nintros; replace (S n) with (n + 1)%nat by lia.\nreplace (S m) with (m + 1)%nat by lia.\nunfold g1, g; field_simplify.\nreplace (INR (n + 1)) with (INR n + 1) by \n  (rewrite Nat.add_comm; rewrite S_O_plus_INR; simpl; nra).\nreplace (INR (m + 1)) with (INR m + 1) by\n  (rewrite Nat.add_comm; rewrite S_O_plus_INR; simpl; nra).\nrewrite !Rmult_plus_distr_l.\nrewrite !Rmult_1_r. replace\n(INR n * default_abs t * (1 + default_rel t) ^ m * default_rel t +\nINR n * default_abs t * (1 + default_rel t) ^ m) with\n(INR n * default_abs t * (1 + default_rel t) ^ m * (1 + default_rel t)) by nra.\nrewrite !Rmult_plus_distr_r.\napply Rplus_le_compat.\nrewrite !Rmult_assoc.\nrewrite Rmult_comm.\nrewrite !Rmult_assoc.\napply Rmult_le_compat_l. \napply default_abs_ge_0.\nrewrite <- !Rmult_assoc.\nrewrite Rmult_comm.\napply Rmult_le_compat_l; [apply pos_INR| ].\nrewrite Rmult_comm.\nrewrite tech_pow_Rmult.\nreplace (S m) with (m + 1)%nat by lia; nra.\nreplace (default_abs t) with (default_abs t * 1) at 1 by nra.\napply Rmult_le_compat_l; [apply  default_abs_ge_0 | ].\napply default_rel_plus_1_ge_1'.\nQed.\n\nLemma plus_d_e_g1_le t n:\n(1 <= n )%nat ->\ng1 t n n + (1 + default_rel t) * default_abs t <= g1 t (S n) n.\nProof.\npose proof plus_d_e_g1_le' t n n; auto.\nQed. \n\n\nLemma plus_e_g1_le t n:\ng1 t n n + default_abs t <= g1 t (S n) n.\nProof.\nreplace (S n) with (n + 1)%nat by lia.\nunfold g1; field_simplify.\nreplace (INR (n + 1)) with (INR n + 1).\nrewrite !Rmult_plus_distr_l.\nrewrite !Rmult_1_r. rewrite <- Rplus_assoc.\napply Rplus_le_compat_r.\nrewrite Rplus_comm.\nrewrite Rmult_comm.\nrewrite Rplus_comm.\napply Rplus_le_compat_r.\neapply Rle_trans with (default_abs t * INR n * g t n + 0); try nra.\napply Rplus_le_compat; try nra.\napply Rmult_le_pos.\napply default_abs_ge_0.\napply g_pos.\nrewrite Nat.add_comm. \nrewrite S_O_plus_INR. simpl; nra. \nQed.\n\nLemma g1n_le_g1Sn t n:\n(1 <= n )%nat ->\ng1 t n (n - 1) <= g1 t (S n) (S (n - 1)).\nProof.\nintros;\nreplace (S n) with (n + 1)%nat by lia.\nunfold g1; field_simplify.\nreplace (INR (n + 1)) with (INR n + 1).\nrewrite !Rmult_plus_distr_l.\nrewrite !Rmult_1_r. \napply Rplus_le_compat.\napply Rmult_le_compat; [\napply Rmult_le_pos; [apply pos_INR | apply default_abs_ge_0 ] | \n  apply g_pos | | ].\nrewrite Rplus_comm;\napply Rcomplements.Rle_minus_l; field_simplify; apply default_abs_ge_0.\nreplace ((n + 1 - 1))%nat with (S (n-1))%nat by lia.\napply le_g_Sn. \nrewrite Rplus_comm;\napply Rcomplements.Rle_minus_l; field_simplify; apply default_abs_ge_0.\nrewrite Nat.add_comm. \nrewrite S_O_plus_INR. simpl; nra. \nQed.\n\nLemma Rplus_le_lt_compat a1 a2 b1 b2 :\n a1 <= a2 -> b1 < b2 ->  a1 + b1 < a2 + b2.\nProof.  nra. Qed.\n\nLemma g1n_lt_g1Sn t n:\n(1 <= n )%nat ->\ng1 t n (n - 1) < g1 t (S n) (S (n - 1)).\nProof.\nintros;\nreplace (S n) with (n + 1)%nat by lia.\nunfold g1; field_simplify.\nreplace (INR (n + 1)) with (INR n + 1).\nrewrite !Rmult_plus_distr_l.\nrewrite !Rmult_1_r.\nassert (INR n * default_abs t < default_abs t * INR n + default_abs t).\n{ apply Rle_lt_trans with (INR n * default_abs t + 0) ; try nra.\napply Rplus_le_lt_compat; try nra.\napply default_abs_gt_0. }\napply Rplus_le_lt_compat; try nra.\napply Rmult_le_compat; [\napply Rmult_le_pos; [apply pos_INR | apply default_abs_ge_0 ] | \n  apply g_pos | | ].\nrewrite Rplus_comm;\napply Rcomplements.Rle_minus_l; field_simplify; apply default_abs_ge_0.\napply le_g_Sn.\nrewrite Nat.add_comm. \nrewrite S_O_plus_INR. simpl; nra. \nQed.\n\n\nDefinition error_rel (t: type) (n: nat) (r : R) : R :=\n  let e := default_abs t in\n  let d := default_rel t in\n  if (1 <=? Z.of_nat n) then \n    (g t (n-1)) * (Rabs r + e/d)\n  else 0%R.\n\nEnd NAN.", "meta": {"author": "VeriNum", "repo": "double-double", "sha": "a73bb5752bdd67b29cf036e63b2fb090f59f1cc9", "save_path": "github-repos/coq/VeriNum-double-double", "path": "github-repos/coq/VeriNum-double-double/double-double-a73bb5752bdd67b29cf036e63b2fb090f59f1cc9/common/common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7160614848729064}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Omega List Permutation.\n\nRequire Import tacs rel_utils list_utils.\n\nRequire Import formula sequent_rules.\nRequire Import relevant_LR1 mini_LI1.\n\nSet Implicit Arguments.\n\nSection Relational_phase_semantics.\n\n  Variable M : Type.\n\n  Implicit Types A B C : M -> Prop.\n\n  Variable cl : (M -> Prop) -> (M -> Prop).\n\n  Hypothesis cl_increase   : forall A, A inc1 cl A.\n  Hypothesis cl_monotone   : forall A B, A inc1 B -> cl A inc1 cl B.\n  Hypothesis cl_idempotent : forall A, cl (cl A) inc1 cl A.\n  \n  Proposition cl_prop A B : A inc1 cl B <-> cl A inc1 cl B.\n  Proof.\n    split; intros H x Hx.\n    apply cl_idempotent; revert Hx; apply cl_monotone; auto.\n    apply H, cl_increase; auto.\n  Qed.\n  \n  Definition cl_inc A B := proj1 (cl_prop A B).\n  Definition inc_cl A B := proj2 (cl_prop A B). \n  \n  Fact cl_eq1 A B : A ~eq1 B -> cl A ~eq1 cl B.\n  Proof.\n    intros []; split; apply cl_monotone; auto.\n  Qed.\n\n  Hint Resolve cl_inc cl_eq1 : core. (* inc_cl. *)\n\n  Notation closed := (fun x : M -> Prop => cl x inc1 x).\n  \n  Fact cl_closed A B : closed B -> A inc1 B -> cl A inc1 B.\n  Proof.\n    intros H1 H2.\n    apply inc1_trans with (2 := H1), cl_inc, \n          inc1_trans with (1 := H2), cl_increase.\n  Qed.\n\n  (* this is a relational/non-deterministic monoid *)\n\n  Variable Compose : M -> M -> M -> Prop.\n\n  (* Composition lifted to predicates *)\n\n  Inductive Composes (A B : M -> Prop) : M -> Prop :=\n    In_composes : forall a b c, A a -> B b -> Compose a b c -> Composes A B c.\n\n  Infix \"ø\" := Composes (at level 50, no associativity).\n\n  Proposition composes_monotone A A' B B' : A inc1 A' -> B inc1 B' ->  A ø B inc1 A' ø B'.\n  Proof. intros ? ? _ [ ? ? ? ? ? H ]; apply In_composes with (3 := H); auto. Qed.\n\n  Hint Resolve composes_monotone : core.\n\n  Variable e : M.\n\n  (* Stability is the important axiom in phase semantics *)\n\n  Definition cl_stability   := forall A B, cl A ø cl B inc1 cl (A ø B).\n  Definition cl_stability_l := forall A B, cl A ø    B inc1 cl (A ø B).\n  Definition cl_stability_r := forall A B,    A ø cl B inc1 cl (A ø B).\n\n  Proposition cl_stable_imp_stable_l : cl_stability -> cl_stability_l.\n  Proof. \n    intros H ? ? x Hx.\n    apply H; revert x Hx. \n    apply composes_monotone; auto.\n  Qed.\n\n  Proposition cl_stable_imp_stable_r : cl_stability -> cl_stability_r.\n  Proof. \n    intros H ? ? x Hx.\n    apply H; revert x Hx. \n    apply composes_monotone; auto.\n  Qed.\n\n  Proposition cl_stable_lr_imp_stable : cl_stability_l -> cl_stability_r -> cl_stability.\n  Proof. \n    intros H1 H2 A B x Hx.\n    apply cl_idempotent.\n    generalize (H1 _ _ _ Hx).\n    apply cl_monotone, H2.\n  Qed.\n\n  Hint Resolve cl_stable_imp_stable_l cl_stable_imp_stable_r cl_stable_lr_imp_stable : core.\n  \n  Notation sg := (@eq _).\n\n  Definition cl_neutrality_1 := forall a, cl (sg e ø sg a) a.\n  Definition cl_neutrality_2 := forall a, sg e ø sg a inc1 cl (sg a).\n  Definition cl_commutativity := forall a b, sg a ø sg b inc1 cl (sg b ø sg a).\n  Definition cl_associativity := forall a b c, sg a ø (sg b ø sg c) inc1 cl ((sg a ø sg b) ø sg c).\n\n  Hypothesis cl_commute : cl_commutativity.\n  \n  Fact sg_inc1 (A : M -> Prop) : forall x, A x -> sg x inc1 A.\n  Proof. intros ? ? ? []; trivial. Qed.\n\n  Proposition composes_commute_1 A B : A ø B inc1 cl (B ø A).\n  Proof.\n    intros _ [ a b c Ha Hb Hc ].\n    apply cl_monotone with (sg b ø sg a).\n    apply composes_monotone; apply sg_inc1; auto.\n    apply cl_commute.\n    constructor 1 with (3 := Hc); auto.\n  Qed.\n\n  Hint Resolve composes_commute_1 : core.\n\n  Proposition composes_commute A B : cl (A ø B) ~eq1 cl (B ø A).\n  Proof. \n    split; intros x Hx; apply cl_idempotent; revert Hx; apply cl_monotone; auto. \n  Qed. \n\n  Proposition cl_stable_l_imp_r : cl_stability_l -> cl_stability_r.\n  Proof.\n    intros Hl A B x Hx.\n    apply cl_idempotent.\n    apply cl_monotone with (cl B ø A).\n    apply inc1_trans with (cl ((cl B) ø A)); auto.\n    rewrite <- cl_prop; auto.\n    generalize (@composes_commute_1 B A); intros H.\n    rewrite cl_prop in H; auto.\n    apply composes_commute_1; auto.\n  Qed.\n  \n  Proposition cl_stable_r_imp_l : cl_stability_r -> cl_stability_l.\n  Proof.\n    intros Hl A B.\n    generalize (@composes_commute_1 B A); intros H.\n    rewrite cl_prop in H; auto.\n    apply inc1_trans with (B := cl (B ø cl A)),\n          inc1_trans with (2 := H); auto.\n    rewrite <- cl_prop; apply Hl.\n  Qed.\n\n  Hint Resolve cl_stable_l_imp_r cl_stable_r_imp_l : core.\n  \n  Proposition cl_stable_l_imp_stable : cl_stability_l -> cl_stability.    Proof. auto. Qed. \n  Proposition cl_stable_r_imp_stable : cl_stability_r -> cl_stability.    Proof. auto. Qed.\n\n  Hypothesis cl_stable_l : cl_stability_l.\n  \n  Proposition cl_stable_r : cl_stability_r.                               Proof. auto. Qed.\n  Proposition cl_stable : cl_stability.                                   Proof. auto. Qed.\n\n  Hint Resolve cl_stable_r cl_stable : core.\n\n  Hypothesis cl_neutral_1 : cl_neutrality_1.\n  Hypothesis cl_neutral_2 : cl_neutrality_2.\n  Hypothesis cl_associative : cl_associativity.\n\n  Definition Magicwand A B k := sg k ø A inc1 B.\n  Infix \"-ø\" := Magicwand (at level 51, right associativity).\n\n  Proposition magicwand_spec A B C : A ø B inc1 C <-> A inc1 B -ø C.\n  Proof.\n    split; intros H x Hx.\n    intros y Hy; apply H; revert Hy; apply composes_monotone; auto.\n    apply sg_inc1; auto.\n    destruct Hx as [ a b x Ha Hb Hx ].\n    apply (H _ Ha).\n    constructor 1 with a b; auto.\n  Qed.\n\n  Definition magicwand_adj_1 A B C := proj1 (magicwand_spec A B C).\n  Definition magicwand_adj_2 A B C := proj2 (magicwand_spec A B C).\n\n(*  Hint Resolve magicwand_adj_1 magicwand_adj_2. *)\n\n  Proposition magicwand_monotone A A' B B' : A inc1 A' -> B inc1 B' -> A' -ø B inc1 A -ø B'.\n  Proof.\n    intros ? HB; apply magicwand_adj_1, inc1_trans with (2 := HB).\n    intros _ [? ? ? Ha ? Hc]; apply Ha, In_composes with (3 := Hc); auto.\n  Qed.\n\n  Hint Resolve magicwand_monotone : core.\n\n  Proposition cl_magicwand_1 X Y : cl (X -ø cl Y) inc1 X -ø cl Y.\n  Proof. \n    apply magicwand_adj_1, \n          inc1_trans with (B := cl ((X -ø cl Y) ø X)); auto.\n    rewrite <- cl_prop; apply magicwand_spec; auto. \n  Qed.\n\n  Proposition cl_magicwand_2 X Y : cl X -ø Y inc1 X -ø Y.\n  Proof.\n    apply magicwand_monotone; auto.\n  Qed.\n \n  Hint Immediate cl_magicwand_1 cl_magicwand_2 : core.\n\n  Proposition cl_magicwand_3 X Y : X -ø cl Y inc1 cl X -ø cl Y.\n  Proof.\n    intros c Hc y.\n    apply inc1_trans with (B := cl (sg c ø X)); auto.\n    rewrite <- cl_prop.\n    intros ? [ a b d [] Hb ].\n    intros; apply Hc. \n    constructor 1 with c b; auto.\n  Qed.\n\n  Hint Immediate cl_magicwand_3 : core.\n\n  Proposition closed_magicwand X Y : closed Y -> closed (X -ø Y).\n  Proof. \n    simpl; intros ?.\n    apply inc1_trans with (B := cl (X -ø cl Y)); auto.\n    apply cl_monotone, magicwand_monotone; auto.\n    apply inc1_trans with (B := X -ø cl Y); auto.\n    apply magicwand_monotone; auto.\n  Qed.\n\n  Hint Resolve closed_magicwand : core.\n\n  Proposition magicwand_eq_1 X Y : X -ø cl Y ~eq1 cl X -ø cl Y.\n  Proof. split; auto. Qed.\n\n  Proposition magicwand_eq_2 X Y : cl (X -ø cl Y) ~eq1 X -ø cl Y.\n  Proof. split; auto. Qed.\n\n  Proposition magicwand_eq_3 X Y : cl (X -ø cl Y) ~eq1 cl X -ø cl Y.\n  Proof.\n    split; auto.\n    apply inc1_trans with (B := X -ø cl Y); auto.\n  Qed.\n\n  Hint Resolve magicwand_eq_1 magicwand_eq_2 magicwand_eq_3 : core.\n\n  Proposition cl_equiv_2 X Y : cl (cl X ø Y) ~eq1 cl (X ø Y).\n  Proof. \n    split.\n    rewrite <- cl_prop; auto.\n    apply cl_monotone, composes_monotone; auto.\n  Qed.\n\n  Proposition cl_equiv_3 X Y : cl (X ø cl Y) ~eq1 cl (X ø Y).\n  Proof.\n    split.\n    rewrite <- cl_prop; auto.\n    apply cl_monotone, composes_monotone; auto.\n  Qed.\n\n  Proposition cl_equiv_4 X Y : cl (cl X ø cl Y) ~eq1 cl (X ø Y).\n  Proof. \n    split.\n    rewrite <- cl_prop; auto.\n    apply cl_monotone, composes_monotone; auto.\n  Qed.\n\n  Hint Immediate cl_equiv_2 cl_equiv_3 cl_equiv_4 : core.\n\n  Proposition composes_associative_1 A B C : A ø (B ø C) inc1 cl ((A ø B) ø C).\n  Proof.\n    intros _ [a _ k Ha [b c y Hb Hc Hy] Hk].\n    generalize (@cl_associative a b c k); intros H.\n    spec_all H.\n    apply In_composes with (3 := Hk); auto.\n    apply In_composes with (3 := Hy); auto.\n    revert H.\n    apply cl_monotone.\n    repeat apply composes_monotone; apply sg_inc1; auto.\n  Qed.\n\n  Hint Immediate composes_associative_1 : core.\n\n  Proposition composes_associative A B C : cl (A ø (B ø C)) ~eq1 cl ((A ø B) ø C).\n  Proof.\n    split; auto.\n    rewrite <- cl_prop; auto.\n    rewrite <- cl_prop; auto.\n    apply inc1_trans with (1 := @composes_commute_1 _ _).\n    rewrite <- cl_prop.\n    apply inc1_trans with (B := C ø cl (A ø B)); auto.\n    apply composes_monotone; auto.\n    apply inc1_trans with (B := C ø cl (B ø A)); auto.\n    apply composes_monotone; auto.\n    apply composes_commute.\n    apply inc1_trans with (1 := @cl_stable_r _ _).\n    rewrite <- cl_prop.\n    apply inc1_trans with (1 := @composes_associative_1 _ _ _).\n    rewrite <- cl_prop.\n    apply inc1_trans with (1 := @composes_commute_1 _ _). \n    rewrite <- cl_prop.\n    apply inc1_trans with (B := A ø cl (C ø B)); auto.\n    apply composes_monotone; auto.\n    apply inc1_trans with (B := A ø cl (B ø C)); auto.\n    apply composes_monotone; auto.\n    apply composes_commute.\n  Qed.\n\n  Hint Immediate composes_associative : core.\n\n  Proposition composes_congruent_1 A B C : A inc1 cl B -> C ø A inc1 cl (C ø B).\n  Proof.\n    intros ?.\n    apply inc1_trans with (B := cl (C ø cl B)); auto.\n    apply cl_prop, cl_monotone, composes_monotone; auto.\n    apply cl_equiv_3.\n  Qed.\n\n  Hint Resolve composes_congruent_1 : core.\n\n  Proposition composes_congruent A B C : cl A ~eq1 cl B -> cl (C ø A) ~eq1 cl (C ø B).\n  Proof. \n    intros [H1 H2].\n    rewrite <- cl_prop in H1.\n    rewrite <- cl_prop in H2.\n    split; rewrite <- cl_prop;\n    apply inc1_trans with (2 := @cl_stable_r _ _), composes_monotone; auto.\n  Qed.\n\n  Proposition composes_assoc_special A A' B B' : cl((A ø A') ø (B ø B')) ~eq1 cl ((A ø B) ø (A' ø B')).\n  Proof.\n    do 2 apply eq1_sym, eq1_trans with (2 := composes_associative _ _ _).\n    apply composes_congruent.\n    apply eq1_sym, eq1_trans with (1 := composes_commute _ _).\n    apply eq1_sym, eq1_trans with (2 := composes_associative _ _ _).\n    apply composes_congruent, composes_commute.\n  Qed.\n\n  Definition composes_assoc_special_1 A A' B B' := proj1 (composes_assoc_special A A' B B').\n  \n  Proposition composes_neutral_1 A : A inc1 cl (sg e ø A).\n  Proof.\n    intros a Ha.\n    generalize (cl_neutral_1 a).\n    apply cl_monotone, composes_monotone; auto.\n    apply sg_inc1; auto.\n  Qed.\n\n  Proposition composes_neutral_2 A : sg e ø A inc1 cl A.\n  Proof.\n    intros _ [y a x [] Ha Hx].\n    generalize (@cl_neutral_2 a x); intros H.\n    spec_all H.\n    constructor 1 with e a; auto.\n    revert H; apply cl_monotone, sg_inc1; auto.\n  Qed.\n  \n  Hint Resolve composes_neutral_1 composes_neutral_2 : core.\n\n  Proposition composes_neutral A : cl (sg e ø A) ~eq1 cl A.\n  Proof. split; rewrite <- cl_prop; auto. Qed.\n\n  Notation \"x 'glb' y \" := (x cap1 y) (at level 60, no associativity).\n  Notation \"x 'lub' y\" := (cl (x cup1 y)) (at level 60, no associativity).\n\n  Proposition closed_glb A B : closed A -> closed B -> closed (A glb B).\n  Proof. \n    simpl; intros HA HB x Hx; split; \n      [ apply HA | apply HB ]; revert x Hx; \n      apply cl_monotone; tauto. \n  Qed.\n\n  Proposition lub_out A B C : closed C -> A inc1 C -> B inc1 C -> A lub B inc1 C.\n  Proof. \n    simpl.\n    intros H1 H2 H3.\n    apply inc1_trans with (2 := H1), cl_monotone.\n    intros ? [ ]; auto.\n  Qed.\n\n  Proposition glb_in A B C : C inc1 A -> C inc1 B -> C inc1 A glb B.\n  Proof. simpl; split; auto. Qed. \n\n  Proposition closed_lub A B : closed (cl (A cup1 B)).     Proof. simpl; apply cl_idempotent. Qed.\n  Proposition glb_out_l A B  : A glb B inc1 A .            Proof. simpl; tauto. Qed.\n  Proposition glb_out_r A B  : A glb B inc1 B.             Proof. simpl; tauto. Qed.\n  Proposition lub_in_l A B   : A inc1 A lub B.             Proof. apply inc1_trans with (2 := cl_increase _); tauto. Qed.\n  Proposition lub_in_r A B   : B inc1 A lub B.             Proof. apply inc1_trans with (2 := cl_increase _); tauto. Qed.\n\n  Notation \"x '**' y \" := (cl (x ø y)) (at level 59).\n\n  Proposition closed_times A B : closed (A ** B).\n  Proof. simpl; apply cl_idempotent. Qed.\n\n  Proposition times_monotone A A' B B' : A inc1 A' -> B inc1 B' -> A ** B inc1 A' ** B'.\n  Proof. simpl; intros ? ?; apply cl_monotone, composes_monotone; auto. Qed.\n\n  Notation top := (fun _ : M => True).\n  Notation bot := (cl (fun _ => False)).\n  Notation unit := (cl (sg e)). \n\n  Proposition closed_top     : closed top.         Proof. simpl; intros; auto. Qed. \n  Proposition closed_bot     : closed bot.         Proof. simpl; apply cl_idempotent. Qed.\n  Proposition closed_unit    : closed unit.        Proof. simpl; apply cl_idempotent. Qed.\n  Proposition top_greatest A : A inc1 top.         Proof. simpl; tauto. Qed. \n\n  Proposition bot_least A : closed A -> bot inc1 A.\n  Proof. intro H; apply inc1_trans with (2 := H), cl_monotone; tauto. Qed.\n\n  Proposition unit_neutral_1 A : closed A -> unit ** A inc1 A.\n  Proof. \n    intros H; apply inc1_trans with (2 := H).\n    rewrite <- cl_prop.\n    apply inc1_trans with (1 := @cl_stable_l _ _).\n    rewrite <- cl_prop.\n    apply composes_neutral_2.\n  Qed.\n\n  Proposition unit_neutral_2 A : A inc1 unit ** A.\n  Proof. \n    intros a Ha; simpl.\n    generalize (composes_neutral_1 _ _ Ha).\n    apply cl_monotone, composes_monotone; auto.\n  Qed.\n  \n(*  Hint Resolve unit_neutral_1 unit_neutral_2. *)\n\n  Proposition unit_neutral A : closed A -> unit ** A ~eq1 A.\n  Proof. \n    intros H; split. \n    revert H; apply unit_neutral_1.\n    apply unit_neutral_2.\n  Qed.\n\n  Proposition times_commute_1 A B : A ** B inc1 B ** A.\n  Proof. simpl; apply cl_inc, composes_commute_1. Qed.\n\n  Hint Resolve unit_neutral times_commute_1 : core.\n \n  Proposition times_commute A B : A ** B ~eq1 B ** A.\n  Proof. split; auto. Qed.\n\n  Proposition unit_neutral' A : closed A -> A ** unit ~eq1 A.\n  Proof. intros ?; apply eq1_trans with (1 := times_commute _ _); auto. Qed.\n\n  Proposition times_associative A B C : ((A ** B) ** C) ~eq1 (A ** (B ** C)).\n  Proof.\n    apply eq1_sym, eq1_trans with (1 := cl_equiv_3 _ _ ).\n    apply eq1_sym, eq1_trans with (1 := cl_equiv_2 _ _ ).\n    apply eq1_sym, composes_associative.\n  Qed.\n\n  Proposition times_associative_1 A B C : (A ** B) ** C inc1 A ** (B ** C).\n  Proof. apply times_associative. Qed.\n\n  Proposition times_associative_2 A B C : A ** (B ** C) inc1 (A ** B) ** C.\n  Proof. apply times_associative. Qed.\n\n  Hint Resolve times_associative_1 times_associative_2 : core.\n\n  Proposition times_congruence A A' B B' : A ~eq1 A' -> B ~eq1 B' -> A ** B ~eq1 A' ** B'.\n  Proof. \n    intros H1 H2.\n    apply eq1_trans with (A ** B').\n    apply composes_congruent; auto.\n    do 2 apply eq1_sym, eq1_trans with (1 := times_commute _ _).\n    apply composes_congruent; auto.\n  Qed.\n \n  Proposition adjunction_1 A B C : closed C -> A ** B inc1 C -> A inc1 B -ø C.\n  Proof. intros ? H; apply magicwand_adj_1, inc1_trans with (2 := H); auto. Qed.\n\n  Proposition adjunction_2 A B C : closed C -> A inc1 B -ø C -> A ** B inc1 C.\n  Proof. intros H ?; apply inc1_trans with (2 := H), cl_monotone, magicwand_adj_2; auto. Qed.\n\n  Hint Resolve times_congruence adjunction_1 (* adjunction_2 *) : core.\n \n  Proposition adjunction A B C : closed C -> (A ** B inc1 C <-> A inc1 B -ø C).\n  Proof.\n    split; [ apply adjunction_1 | apply  adjunction_2 ]; auto.\n  Qed.\n\n  Proposition times_bot_distrib_l A : bot ** A inc1 bot.\n  Proof.\n    apply adjunction_2; auto.\n    apply bot_least; auto.\n  Qed.\n\n  Proposition times_bot_distrib_r A : A ** bot inc1 bot.\n  Proof. apply inc1_trans with (1 := @times_commute_1 _ _), times_bot_distrib_l. Qed.\n \n  Hint Immediate times_bot_distrib_l times_bot_distrib_r : core.\n\n  Proposition times_lub_distrib_l A B C : (A lub B) ** C inc1 (A ** C) lub (B ** C).\n  Proof. \n    apply adjunction, lub_out; auto;\n    apply adjunction; auto. \n  Qed.\n\n  Proposition times_lub_distrib_r A B C : C ** (A lub B) inc1 (C ** A) lub (C ** B).\n  Proof. \n    apply inc1_trans with (1 := @times_commute_1 _ _),\n          inc1_trans with (1 := @times_lub_distrib_l _ _ _); auto.\n    apply lub_out; auto.\n  Qed.\n\n  Reserved Notation \"'[[' x ']]'\" (at level 50).\n  Reserved Notation \"'[|' x '|]'\" (at level 50).\n  \n  Variable (v : Var -> M -> Prop) (Hv : forall x, cl (v x) inc1 v x).\n  \n  Fixpoint Form_sem f :=\n    match f with\n      | £ x    => v x\n      | a %> b => [[a]] -ø [[b]]\n    end\n  where \"[[ a ]]\" := (Form_sem a).\n  \n  Fact cl_Form_sem f : cl ([[f]]) inc1 [[f]].\n  Proof.\n    induction f; simpl; auto.\n  Qed.\n  \n  Fixpoint FList_sem ll :=\n    match ll with\n      | nil   => unit\n      | x::ll => [[x]] ** [|ll|]\n    end\n  where \"[| ll |]\" := (FList_sem ll).\n  \n  Fact cl_FList_sem ll : cl ([|ll|]) inc1 [|ll|].\n  Proof.\n    induction ll; simpl; auto.\n  Qed.\n  \n  Hint Resolve cl_Form_sem cl_FList_sem : core.\n  \n  Fact FList_sem_app l m : [|l++m|] ~eq1 [|l|] ** [|m|].\n  Proof.\n    induction l; simpl.\n    apply eq1_sym, unit_neutral; auto.\n    apply eq1_sym, eq1_trans with (1 := @times_associative _ _ _), eq1_sym.\n    apply times_congruence; auto.\n  Qed.\n  \n  Fact FList_sem_perm l m : l ~p m -> [|l|] ~eq1 [|m|].\n  Proof.\n    induction 1 as [ | x l m _ IHl | x y l | l m k ]; auto.\n    apply composes_congruent, cl_eq1; auto.\n    simpl; do 2 apply eq1_sym, eq1_trans with (2 := @times_associative _ _ _).\n    apply times_congruence; auto.\n    apply eq1_trans with ([|m|]); auto.\n  Qed.\n  \n  Definition cl_weak_hyp := forall x, cl (sg e) x.\n  Definition cl_cntr_hyp := forall x, cl (sg x ø sg x) x.\n\n  Hypothesis cl_weak : cl_weak_hyp.\n  Hypothesis cl_cntr : cl_cntr_hyp.\n  \n  Proposition cl_weakening A : A inc1 unit.\n  Proof.\n    intros x Hx.\n    apply cl_weak.\n  Qed.\n  \n  Proposition cl_contract A : A inc1 A ** A.\n  Proof.\n    intros x Hx.\n    generalize (cl_cntr x).\n    apply times_monotone;\n    intros ? []; auto.\n  Qed.\n  \n  Theorem sem_LR1_sound : forall s, LR1_provable s -> [|fst s|] inc1 [[snd s]].\n  Proof.\n    induction 1 as [ A \n                   | ga A B IH \n                   | ga de th A B C H1 IH1 IH2 \n                   | ga de A B H1 IH \n                   | ga de th A B H1 IH1 IH2 ] using LR1_provable_ind; simpl in * |- *.\n \n    apply inc1_trans with (1 := @times_commute_1 _ _), unit_neutral_1; auto.\n    \n    apply adjunction_1; auto.\n    \n    apply inc1_trans with (1 := proj1 (FList_sem_perm H1)),\n          inc1_trans with (2 := IH2).\n    simpl.\n    apply inc1_trans with ([[A]] -ø[[B]] ** ([|ga|] ** [|de|])).\n    apply times_congruence; auto.\n    apply eq1_sym, FList_sem_app.\n    apply inc1_trans with (1 := @times_associative_2 _ _ _).\n    apply times_monotone; auto.\n    apply inc1_trans with ([[A]] -ø[[B]] ** [[A]]).\n    apply times_monotone; auto.\n    apply adjunction_2; auto.\n    \n    apply inc1_trans with (2 := IH),\n          inc1_trans with (1 := proj1 (FList_sem_perm H1)).\n    apply inc1_trans with (2 := @times_associative_1 _ _ _).\n    simpl; apply times_monotone; auto.\n    apply cl_contract.\n    \n    apply inc1_trans with (2 := IH2),\n          inc1_trans with (1 := proj1 (FList_sem_perm H1)),\n          inc1_trans with (1 := proj1 (FList_sem_app _ _)).\n    apply times_monotone; auto.\n  Qed.\n  \n  Theorem sem_LI1_sound : forall s, LI1_provable s -> [|fst s|] inc1 [[snd s]].\n  Proof.\n    induction 1 as [ A \n                   | ga A B IH \n                   | ga de th A B C H1 IH1 IH2 \n                   | ga de A B H1 IH \n                   | ga de A B H1 IH\n                   | ga de th A B H1 IH1 IH2 ] using LI1_provable_ind; simpl in * |- *.\n \n    apply inc1_trans with (1 := @times_commute_1 _ _), unit_neutral_1; auto.\n    \n    apply adjunction_1; auto.\n    \n    apply inc1_trans with (1 := proj1 (FList_sem_perm H1)),\n          inc1_trans with (2 := IH2).\n    simpl.\n    apply inc1_trans with ([[A]] -ø[[B]] ** ([|ga|] ** [|de|])).\n    apply times_congruence; auto.\n    apply eq1_sym, FList_sem_app.\n    apply inc1_trans with (1 := @times_associative_2 _ _ _).\n    apply times_monotone; auto.\n    apply inc1_trans with ([[A]] -ø[[B]] ** [[A]]).\n    apply times_monotone; auto.\n    apply adjunction_2; auto.\n    \n    apply inc1_trans with (2 := IH),\n          inc1_trans with (1 := proj1 (FList_sem_perm H1)).\n    apply inc1_trans with (2 := @times_associative_1 _ _ _).\n    simpl; apply times_monotone; auto.\n    apply cl_contract.\n    \n    apply inc1_trans with (2 := IH),\n          inc1_trans with (1 := proj1 (FList_sem_perm H1)).\n    apply inc1_trans with (2 := unit_neutral_1 (cl_FList_sem _)).\n    simpl; apply times_monotone; auto.\n    \n    apply inc1_trans with (2 := IH2),\n          inc1_trans with (1 := proj1 (FList_sem_perm H1)),\n          inc1_trans with (1 := proj1 (FList_sem_app _ _)).\n    apply times_monotone; auto.\n  Qed.\n  \nEnd Relational_phase_semantics.\n\nSection Cut_Adm.\n\n  Local Notation \" l '≻c' m \" := (list_contract Form_eq_dec l m) (at level 70, no associativity).\n\n  Variable (P : list Form -> Form -> Prop).\n\n  Notation \" g '|--' a \" := (P g a) (at level 70, no associativity).\n\n  Implicit Types (X Y : list Form -> Prop).\n\n  Local Definition cl X de := forall ga x, (forall th, X th -> ga++th |-- x) -> ga++de |-- x.\n  \n  Local Fact cl_increase X : X inc1 cl X.\n  Proof.\n    intros ? ? ? ?; auto.\n  Qed.\n  \n  Local Fact cl_mono X Y : X inc1 Y -> cl X inc1 cl Y.\n  Proof.\n    intros H1 de Hde ga x HY.\n    apply Hde.\n    intros; apply HY, H1; auto.\n  Qed.\n  \n  Local Fact cl_idem X : cl (cl X) inc1 cl X.\n  Proof.\n    intros de Hde ga x HX.\n    apply Hde.\n    intros th Hth.\n    apply Hth, HX.\n  Qed.\n  \n  Local Definition comp (ga de th : list Form) := ga ++ de ~p th.\n  Local Definition e : list Form := nil.\n  \n  Local Fact cl_comm : cl_commutativity cl comp.\n  Proof.\n    intros ga de _ [ ga' de' th ]. \n    intros; subst ga' de'.\n    intros rho x H; apply H.\n    constructor 1 with de ga; auto.\n    revert H1; unfold comp.\n    apply perm_trans, Permutation_app_comm.\n  Qed.\n  \n  Local Fact cl_neutral_1 : cl_neutrality_1 cl comp e.\n  Proof.\n    intros l th x H.\n    apply H.\n    constructor 1 with nil l; auto.\n    red; simpl; auto.\n  Qed.\n  \n  Hypothesis HP_perm : forall ga de x, ga ~p de -> ga |-- x -> de |-- x.\n  \n  Local Fact cl_neutral_2 : cl_neutrality_2 cl comp e.\n  Proof.\n    intros ga ? [ de th ka ? ? H1 ] rho x G; subst th de.\n    cbv in H1.\n    generalize (G _ eq_refl).\n    apply HP_perm, Permutation_app; auto.\n  Qed.\n\n  Local Fact cl_stable_l : cl_stability_l cl comp.\n  Proof.\n    intros X Y _ [ ga de th H1 H2 H3 ] rho x HXY.\n    red in H1.\n    apply HP_perm with ((rho++de)++ga).\n    rewrite app_ass.\n    apply Permutation_app; auto.\n    apply perm_trans with (2 := H3), Permutation_app_comm.\n    apply H1.\n    intros ka Hka.\n    rewrite app_ass.\n    apply HXY.\n    constructor 1 with ka de; auto.\n    apply Permutation_app_comm.\n  Qed.\n  \n  Local Fact cl_assoc : cl_associativity cl comp.\n  Proof.\n    intros ga de th _ [ ga' rho ka H2 H3 H4 ].\n    destruct H3 as [ de' th' to ]; subst ga' de' th'.\n    intros u x Hu.\n    specialize (Hu ((ga++de)++th)).\n    spec_all Hu.\n    constructor 1 with (ga++de) th; auto.\n    constructor 1 with ga de; auto.\n    red; auto.\n    red; auto.\n    revert Hu.\n    apply HP_perm, Permutation_app; auto.\n    rewrite app_ass.\n    apply Permutation_trans with (2 := H4).\n    apply Permutation_app; auto.\n  Qed.\n  \n  Hypothesis HP_contract : forall ga de x, ga ≻c de -> ga |-- x -> de |-- x.\n  \n  Local Fact cl_cntr : cl_cntr_hyp cl comp.\n  Proof.\n    intros ga rho x H.\n    specialize (H (ga++ga)).\n    spec_all H.\n    constructor 1 with ga ga; cbv; auto.\n    revert H; apply HP_contract.\n    intros d; repeat rewrite occ_app.\n    unfold nat_contract; omega.\n  Qed.\n  \n  Hypothesis HP_weak : forall ga de x, ga |-- x -> ga++de |-- x.\n  \n  Local Fact cl_weak : cl_weak_hyp cl nil.\n  Proof.\n    intros ga rho x H.\n    generalize (H _ eq_refl).\n    rewrite <- app_nil_end.\n    apply HP_weak.\n  Qed.\n  \n  Local Definition dc a ga := ga |-- a.\n  \n  Local Definition v x := dc (£ x).\n  \n  Local Fact Hv x : cl (v x) inc1 v x.\n  Proof.\n    intros ga Hga.\n    apply (Hga nil).\n    simpl; auto.\n  Qed.\n  \n  Local Definition cl_LR1_sound := @sem_LR1_sound _ _ cl_increase cl_mono cl_idem comp \n                                    _ cl_comm cl_stable_l cl_neutral_1 cl_neutral_2 cl_assoc \n                                    _ Hv cl_cntr.\n  \n  Local Definition cl_LI1_sound := @sem_LI1_sound _ _ cl_increase cl_mono cl_idem comp \n                                      _ cl_comm cl_stable_l cl_neutral_1 cl_neutral_2 cl_assoc \n                                      _ Hv cl_weak cl_cntr.\n                                    \n  Hypothesis HP_id : forall x, x :: nil |-- x.\n  \n  Local Fact rule_id x : Form_sem comp v (£ x) (£ x::nil).\n  Proof. simpl; apply HP_id. Qed.\n  \n  Notation sg := (@eq _).\n  Infix \"-ø\" := (Magicwand comp) (at level 51, right associativity).\n  \n  Hypothesis HP_r : forall ga a b, a::ga |-- b -> ga |-- a %> b.\n  \n  Local Fact rule_r A B : sg (A :: nil) -ø dc B inc1 dc (A %> B).\n  Proof.\n    intros th Hth.\n    apply HP_r, Hth.\n    constructor 1 with th (A :: nil); auto.\n    apply Permutation_app_comm.\n  Qed.\n  \n  Hypothesis HP_l : forall ga de a b c, ga |-- a -> b::de |-- c -> a%>b::ga++de |-- c.\n  \n  Local Fact rule_l A B : (dc A -ø cl (sg (B:: nil))) (A %> B :: nil).\n  Proof.\n    intros th Hth de C H.\n    destruct Hth as [ rho ga th H1 H2 H3 ].\n    subst rho; red in H3; simpl in H3.\n    apply HP_perm with (A%>B::ga++de).\n    apply perm_trans with (2 := Permutation_app_comm _ _). \n    apply Permutation_app with (1 := H3); auto.\n    apply HP_l; auto.\n    generalize (H _ eq_refl).\n    apply HP_perm, Permutation_app_comm.\n  Qed.\n  \n  Hint Resolve cl_increase cl_mono cl_idem cl_stable_l Hv : core.\n  \n  Local Fact mw_mono (X Y X' Y' : _ -> Prop) : X inc1 X' -> Y inc1 Y' -> X' -ø Y inc1 X -ø Y'.\n  Proof.\n    apply magicwand_monotone; auto.\n  Qed.\n  \n  Local Fact cl_sem A : cl (Form_sem comp v A) inc1 Form_sem comp v A.\n  Proof.\n    apply cl_Form_sem; eauto.\n  Qed.\n  \n  Local Fact cl_clos (A B : _ -> Prop) : cl B inc1 B -> A inc1 B -> cl A inc1 B.\n  Proof.\n    apply cl_closed; eauto.\n  Qed.\n   \n  Local Lemma cl_Okada A : Form_sem comp v A (A::nil) \n                        /\\ Form_sem comp v A inc1 fun ga => ga |-- A.\n  Proof.\n    induction A as [ x | A [ HA1 HA2 ] B [ HB1 HB2 ] ]; simpl; split.\n    \n    apply rule_id.\n    intros ga; auto.\n    \n    generalize (@rule_l A B).\n    apply mw_mono; auto.\n    apply cl_clos; auto.\n    apply cl_sem; auto.\n    intros ? []; auto.\n    \n    intros th Hth.\n    apply (@rule_r A B).\n    revert Hth.\n    revert th; apply mw_mono; auto.\n    intros ? []; auto.\n  Qed.\n  \n  Local Lemma cl_Okada_ctx ga : FList_sem cl comp e v ga ga.\n  Proof.\n    induction ga as [ | A ga Hga ]; simpl; \n      apply cl_increase; auto.\n    constructor 1 with (A :: nil) ga; auto.\n    apply cl_Okada.\n    apply Permutation_refl.\n  Qed.\n\nEnd Cut_Adm.\n\nLocal Hint Resolve LR1_cf_provable_perm \n                   LR1_cf_provable_contract\n                   LR1_cf_provable_id LR1_cf_provable_r : core.\n\nTheorem LR1_cut_admissibility : LR1_provable inc1 LR1_cf_provable.\nProof.\n  intros (ga,A) H.\n  apply cl_Okada with (P := fun ga a => LR1_cf_provable (ga,a)); auto.\n  apply LR1_cf_provable_perm.\n  intros ? ? ? ? ?; apply LR1_cf_provable_l; auto.\n  \n  apply cl_LR1_sound with (3 := H); simpl; auto.\n  apply LR1_cf_provable_perm.\n  apply LR1_cf_provable_contract.\n  apply cl_Okada_ctx; auto.\n  apply LR1_cf_provable_perm.\n  intros ? ? ? ? ?; apply LR1_cf_provable_l; auto.\nQed.\n\nLocal Hint Resolve LI1_cf_provable_perm \n                   LI1_cf_provable_contract LI1_cf_provable_weakening\n                   LI1_cf_provable_id LI1_cf_provable_r : core.\n\nTheorem LI1_cut_admissibility : LI1_provable inc1 LI1_cf_provable.\nProof.\n  intros (ga,A) H.\n  apply cl_Okada with (P := fun ga a => LI1_cf_provable (ga,a)); auto.\n  apply LI1_cf_provable_perm.\n  intros ? ? ? ? ?; apply LI1_cf_provable_l; auto.\n  \n  apply cl_LI1_sound with (4 := H); simpl; auto.\n  apply LI1_cf_provable_perm.\n  apply LI1_cf_provable_contract.\n  apply cl_Okada_ctx; auto.\n  apply LI1_cf_provable_perm.\n  intros ? ? ? ? ?; apply LI1_cf_provable_l; auto.\nQed.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Relevant-decidability", "sha": "6b1c4d48f734c4d440d9756630998d231b2cc02f", "save_path": "github-repos/coq/DmxLarchey-Relevant-decidability", "path": "github-repos/coq/DmxLarchey-Relevant-decidability/Relevant-decidability-6b1c4d48f734c4d440d9756630998d231b2cc02f/sem_cut_adm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7160586558852755}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom HB Require Import structures.\nFrom mathcomp Require Import all_ssreflect ssralg fingroup perm finalg matrix.\nFrom mathcomp Require Import boolp classical_sets Rstruct.\nFrom mathcomp Require Import ssrnum ereal.\nRequire Import Reals.\nRequire Import ssrR Reals_ext Lra Ranalysis_ext ssr_ext ssralg_ext logb Rbigop.\nRequire Import fdist.\nFrom mathcomp Require ssrnum vector.\n\n(******************************************************************************)\n(*                              Convexity                                     *)\n(*                                                                            *)\n(* This file provides the definition of convex spaces over a choiceType and   *)\n(* of real cones, and use them to define convex sets, hulls, to show that     *)\n(* probability distributions form convex spaces, and to define convex         *)\n(* functions.                                                                 *)\n(*                                                                            *)\n(* Convex spaces:                                                             *)\n(*         convType == the type of convex spaces, i.e., a choiceType with an  *)\n(*                     operator x <| p |> y where p is a probability          *)\n(*                     satisfying the following axioms:                       *)\n(*            conv1 == a <| 1%:pr |> b = a.                                   *)\n(*           convmm == a <| p |> a = a.                                       *)\n(*            convC == a <| p |> b = b <| p.~%:pr |> a.                       *)\n(*            convA == a <| p |> (b <| q |> c) =                              *)\n(*                     (a <| [r_of p, q] |> b) <| [s_of p, q] |> c.           *)\n(*          <|>_d f == generalization of the conv operator . <| . |> .        *)\n(*                     type: forall A n, {fdist 'I_n} -> ('I_n -> A) -> A     *)\n(*                     d is a finite distribution {fdist 'I_n}, f is a        *)\n(*                     sequence of points 'I_n -> A, A is a convType          *)\n(*  {affine T -> U} == affine function: homomorphism between convex spaces    *)\n(*          <$>_d f := <|>_d (f \\o enum_val)                                  *)\n(*                     type: forall A T, {fdist T} -> (T -> A) -> A           *)\n(*                     d is a finite distribution {fdist T}, f is a sequence  *)\n(*                     of points T -> A, A is a convType, T, is a finType     *)\n(*      segment x y := (fun p => conv p x y) @` [set: prob]                   *)\n(*                                                                            *)\n(*           scaled == Zero or a pair of a positive real (Rpos) with a point  *)\n(*                     in some type (i.e., a \"scaled point\" noted p *: a,     *)\n(*                     scope scaled_scope                                     *)\n(*             S1 a := 1%:pos *: a                                            *)\n(*  isQuasiRealCone == mixin of quasi real cones                              *)\n(*                     see Def. 4.5 of [Varacca & Winskell, MSCS, 2006]       *)\n(*            addpt == addition                                               *)\n(*          scalept == scaling                                                *)\n(* \\ssum_(i <- r) F == iterated addpt                                         *)\n(*       isRealCone == mixin of real cones                                    *)\n(*                     Def. 4.5 of [Varacca & Winskell, MSCS, 2006]           *)\n(* The mixins for real cones are instantiated with the type scaled A where    *)\n(* A is a convType, addpt := rx + qy = (r+q)(x <| r/(r+q) |> y), and          *)\n(* scalept := scalept r qy = (r*q)y.                                          *)\n(* Moreover, when A is a convType, scaled A can be equipped with a            *)\n(* structure of convex space by taking                                        *)\n(* convpt p x y := addpt (scalept p x) (scalept p.~ y). This is the canonical *)\n(* embedding of convex spaces into real cones.                                *)\n(*                                                                            *)\n(* More lemmas about convex spaces, including key lemmas by Stone:            *)\n(*        convACA == the entropic identity, i.e.,                             *)\n(*                      (a <|q|> b) <|p|> (c <|q|> d) =                       *)\n(*                      (a <|p|> c) <|q|> (b <|p|> d)                         *)\n(*                                                                            *)\n(*         hull X == the convex hull of set X : set T where T is a convType   *)\n(*  is_convex_set == Boolean predicate that characterizes convex sets over a  *)\n(*                   convType                                                 *)\n(* {convex_set A} == an object X of type \"set A\" where A is a convType and X  *)\n(*                   is convex                                                *)\n(*                                                                            *)\n(* Instances of convex spaces:                                                *)\n(*      R_convType == R                                                       *)\n(*     funConvType == functions A -> B with A a choiceType and B a convType   *)\n(*  depfunConvType == functions forall (a:A), B a with A a choiceType and B i *)\n(*                    is a A -> convType                                      *)\n(*    pairConvType == pairs of convTypes                                      *)\n(*  fdist_convType == finite distributions                                    *)\n(*                                                                            *)\n(* orderedconvType == ordered convex space, a convType augmented with an      *)\n(*                    order                                                   *)\n(* Instances: R, T -> U (T convType, U orderedConvType), opposite (see mkOpp) *)\n(*                                                                            *)\n(* Reference: R. Affeldt, J. Garrigue, T. Saikawa. Formal adventures in       *)\n(* convex and conical spaces. CICM 2020                                       *)\n(*                                                                            *)\n(* Definitions of convex, concave, affine functions                           *)\n(*   affine_functionP == a function is affine iff it is convex and concave    *)\n(*                                                                            *)\n(* Lemmas:                                                                    *)\n(* image_preserves_convex_hull == the image of a convex hull is the convex    *)\n(*                                hull of the image                           *)\n(*                                                                            *)\n(* Application to real analysis:                                              *)\n(* Definition of convex sets for R                                            *)\n(* Lemma second_derivative_convexf_pt == twice derivable is convex            *)\n(******************************************************************************)\n\nReserved Notation \"x <| p |> y\" (format \"x  <| p |>  y\", at level 49).\nReserved Notation \"{ 'convex_set' T }\" (format \"{ 'convex_set'  T }\").\nReserved Notation \"'<|>_' d f\" (at level 36, f at level 36, d at level 0,\n  format \"<|>_ d  f\").\nReserved Notation \"'<$>_' d f\" (at level 36, f at level 36, d at level 0,\n  format \"<$>_ d  f\").\nReserved Notation \"\\ssum_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n  format \"'[' \\ssum_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\ssum_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n  format \"'[' \\ssum_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\ssum_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n  format \"'[' \\ssum_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\ssum_ i F\"\n  (at level 41, F at level 41, i at level 0, right associativity,\n  format \"'[' \\ssum_ i '/  '  F ']'\").\nReserved Notation \"\\ssum_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50).\nReserved Notation \"\\ssum_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n  format \"'[' \\ssum_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\ssum_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n  format \"'[' \\ssum_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"{ 'affine' T '->' R }\"\n  (at level 36, T, R at next level, format \"{ 'affine'  T  '->'  R }\").\nReserved Notation \"p *: a\" (at level 40).\n\nDeclare Scope convex_scope.\nDeclare Scope ordered_convex_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope reals_ext_scope.\nLocal Open Scope fdist_scope.\n\n(* TODO: the following lemmas are currently not in use. Maybe remove? *)\nSection tmp.\nLemma fdist_convn_Add\n      (n m : nat) (d1 : {fdist 'I_n}) (d2 : {fdist 'I_m}) (p : prob)\n      (A : finType) (g : 'I_n -> fdist A) (h : 'I_m -> fdist A) :\n  fdist_convn (fdist_add d1 d2 p)\n    [ffun i => match fintype.split i with inl a => g a | inr a => h a end] =\n  (fdist_convn d1 g <| p |> fdist_convn d2 h)%fdist.\nProof.\napply/fdist_ext => a; rewrite !fdist_convE !fdist_convnE.\nrewrite 2!big_distrr /= big_split_ord /=; congr (_ + _)%R;\n   apply eq_bigr => i _; rewrite fdist_addE ffunE.\ncase: splitP => /= j ij.\nrewrite mulRA; congr (_ * d1 _ * (g _) a)%R; exact/val_inj.\nmove: (ltn_ord i); by rewrite ij -ltn_subRL subnn ltn0.\ncase: splitP => /= j ij.\nmove: (ltn_ord j); by rewrite -ij -ltn_subRL subnn ltn0.\nmove/eqP : ij; rewrite eqn_add2l => /eqP ij.\nrewrite mulRA; congr (_ * d2 _ * (h _) a)%R; exact/val_inj.\nQed.\n\nLemma fdist_convn_del\n      (A : finType) (n : nat) (g : 'I_n.+1 -> fdist A) (P : {fdist 'I_n.+1})\n      (j : 'I_n.+1) (H : (0 <= P j <= 1)%R) (Pj1 : P j != 1%R) :\n  let g' := fun i : 'I_n => g (fdist_del_idx j i) in\n  fdist_convn P g =\n    (g j <| Prob.mk_ H |> fdist_convn (fdist_del Pj1) g')%fdist.\nProof.\nmove=> g' /=; apply/fdist_ext => a.\nrewrite fdist_convE /= fdist_convnE (bigD1 j) //=; congr (_ + _)%R.\nrewrite fdist_convnE big_distrr /=.\nrewrite (bigID (fun i : 'I_n.+1 => (i < j)%nat)) //=.\nrewrite (bigID (fun i : 'I_n => (i < j)%nat)) //=; congr (_ + _)%R.\n  rewrite (@big_ord_narrow_cond _ _ _ j n.+1); first by rewrite ltnW.\n  move=> jn; rewrite (@big_ord_narrow_cond _ _ _ j n xpredT); first by rewrite -ltnS.\n  move=> jn'.\n  apply/eq_big.\n  by move=> /= i; apply/negP => /eqP/(congr1 val) /=; apply/eqP; rewrite ltn_eqF.\n  move=> /= i _.\n  rewrite fdist_delE /= ltn_ord fdistD1E /= ifF /=; last first.\n    by apply/negP => /eqP/(congr1 val) /=; apply/eqP; rewrite ltn_eqF.\n  rewrite mulRA mulRCA mulRV ?mulR1 ?onem_neq0 //.\n  congr (P _ * _)%R; first exact/val_inj.\n  by rewrite /g' /fdist_del_idx /= ltn_ord; congr (g _ a); exact/val_inj.\nrewrite (eq_bigl (fun i : 'I_n.+1 => (j < i)%nat)); last first.\n  move=> i; by rewrite -leqNgt eq_sym -ltn_neqAle.\nrewrite (eq_bigl (fun i : 'I_n => (j <= i)%nat)); last first.\n  move=> i; by rewrite -leqNgt.\nrewrite big_mkcond.\nrewrite big_ord_recl ltn0 /= add0R.\nrewrite [in RHS]big_mkcond.\napply eq_bigr => i _.\nrewrite /bump add1n ltnS; case: ifPn => // ji.\nrewrite fdist_delE fdistD1E ltnNge ji /= ifF; last first.\n  apply/eqP => /(congr1 val) => /=.\n  rewrite /bump add1n => ij.\n  by move: ji; apply/negP; rewrite -ij ltnn.\nrewrite /Rdiv mulRAC [in RHS] mulRC -mulRA mulVR // ?mulR1 ?onem_neq0 //.\nby rewrite /g' /fdist_del_idx ltnNge ji.\nQed.\nEnd tmp.\n\n(* TODO: move*)\nSection fintype_extra.\n\nLemma index_enum_cast_ord n m (e : n = m) :\n  index_enum (ordinal_finType m) = [seq cast_ord e i | i <- index_enum (ordinal_finType n)].\nProof.\nsubst m; rewrite -{1}(map_id (index_enum (ordinal_finType n))).\napply eq_map=> [[x xlt]].\nby rewrite /cast_ord; congr Ordinal; exact: bool_irrelevance.\nQed.\n\nLemma perm_map_bij [T : finType] [f : T -> T] (s : seq T) : bijective f ->\n  perm_eq (index_enum T) [seq f i | i <- index_enum T].\nProof.\nrewrite /index_enum; case: index_enum_key => /= fbij.\nrewrite /perm_eq -enumT -forallb_tnth; apply /forallP=>i /=.\ncase: fbij => g fg gf.\nrewrite enumT enumP count_map -size_filter (@eq_in_filter _ _\n    (pred1 (g (tnth (cat_tuple (enum_tuple T) (map_tuple [eta f] (enum_tuple T))) i)))).\n  by rewrite size_filter enumP.\nby move=> x _ /=; apply/eqP/eqP => [/(congr1 g) <-|->//].\nQed.\n\nEnd fintype_extra.\n\nModule CodomDFDist.\nSection def.\nLocal Open Scope classical_set_scope.\nVariables (A : Type) (n : nat) (g : 'I_n -> A) (e : {fdist 'I_n}) (y : set A).\nDefinition f := [ffun i : 'I_n => if g i \\in y then e i else 0%R].\nLemma f0 i : (0 <= f i)%R.\nProof. rewrite /f ffunE; case: ifPn => _ //; exact/leRR. Qed.\nLemma f1 (x : set A) (gX : g @` setT `<=` x `|` y)\n  (ge : forall i : 'I_n, x (g i) -> e i = 0%R) :\n  (\\sum_(i < n) f i = 1)%R.\nProof.\nrewrite /f -(FDist.f1 e) /=.\napply eq_bigr => i _; rewrite ffunE.\ncase: ifPn => // /negP; rewrite in_setE => ygi.\nrewrite ge //.\nhave : (x `|` y) (g i) by apply/gX; by exists i.\nby case.\nQed.\nDefinition d (x : set A) (gX : g @` setT `<=` x `|` y)\n  (ge : forall i : 'I_n, x (g i) -> e i = 0%R) : {fdist 'I_n} :=\n  locked (FDist.make f0 (f1 gX ge)).\nLemma dE (x : set A) (gX : g @` setT `<=` x `|` y)\n  (ge : forall i : 'I_n, x (g i) -> e i = 0%R) i :\n  d gX ge i = if g i \\in y then e i else 0%R.\nProof. by rewrite /d; unlock; rewrite ffunE. Qed.\nLemma f1' (x : set A) (gX : g @` setT `<=` x `|` y)\n  (ge : forall i : 'I_n, (x (g i)) /\\ (~ y (g i)) -> e i = 0%R) :\n  (\\sum_(i < n) f i = 1)%R.\nProof.\nrewrite /f -(FDist.f1 e) /=; apply eq_bigr => i _; rewrite ffunE.\ncase: ifPn => // /negP; rewrite in_setE => giy.\nrewrite ge //.\nhave : (x `|` y) (g i) by apply/gX; by exists i.\nby case.\nQed.\nDefinition d' (x : set A) (gX : g @` setT `<=` x `|` y)\n  (ge : forall i : 'I_n, (x (g i)) /\\ (~ y (g i)) -> e i = 0%R) :=\n  locked (FDist.make f0 (f1' gX ge)).\nLemma dE' (x : set A) (gX : g @` setT `<=` x `|` y)\n  (ge : forall i : 'I_n, (x (g i)) /\\ (~ y (g i)) -> e i = 0%R) i :\n  d' gX ge i = if g i \\in y then e i else 0%R.\nProof. by rewrite /d'; unlock; rewrite ffunE. Qed.\nEnd def.\nEnd CodomDFDist.\n\nModule isConvexSpace_.\nHB.mixin Record isConvexSpace (T : Type) := {\n  convexspacechoiceclass : Choice.class_of T ;\n  conv : prob -> T -> T -> T ;\n  conv1 : forall a b, conv 1%:pr a b = a ;\n  convmm : forall p a, conv p a a = a ;\n  convC : forall p a b, conv p a b = conv p.~%:pr b a;\n  convA : forall (p q : prob) (a b c : T),\n      conv p a (conv q b c) = conv [s_of p, q] (conv [r_of p, q] a b) c }.\n\n#[short(type=convType)]\nHB.structure Definition ConvexSpace := {T of isConvexSpace T }.\nEnd isConvexSpace_.\nExport -(coercions) isConvexSpace_.\n\nCoercion ConvexSpace.isConvexSpace__isConvexSpace_mixin :\n  ConvexSpace.axioms_ >-> isConvexSpace.axioms_.\n\nCanonical conv_eqType (T : convType) :=\n  Eval hnf in EqType (ConvexSpace.sort T) convexspacechoiceclass.\nCanonical conv_choiceType (T : convType) :=\n  Eval hnf in ChoiceType (ConvexSpace.sort T) convexspacechoiceclass.\nCoercion conv_choiceType : convType >-> choiceType.\n\nNotation \"a <| p |> b\" := (conv p a b) : convex_scope.\n\nLocal Open Scope convex_scope.\n\nSection convex_space_lemmas.\nVariables A : convType.\nImplicit Types a b : A.\n\nLemma conv0 a b : a <| 0%:pr |> b = b.\nProof.\nby rewrite convC /= (_ : _ %:pr = 1%:pr) ?conv1 //; apply/val_inj/onem0.\nQed.\nEnd convex_space_lemmas.\n\nSection segment.\nVariable A : convType.\nDefinition segment (x y : A) : set A := (fun p => conv p x y) @` [set: prob].\n\nLemma segment_sym u v : (segment u v `<=` segment v u)%classic.\nProof. by move=> x [p _ <-]; exists (p.~%:pr); rewrite -?convC. Qed.\n\nLemma segmentC u v : segment u v = segment v u.\nProof. by rewrite eqEsubset; split; exact: segment_sym. Qed.\n\nLemma segmentL x y : segment x y x. Proof. by exists 1%:pr; rewrite ?conv1. Qed.\n\nLemma segmentR x y : segment x y y. Proof. by exists 0%:pr; rewrite ?conv0. Qed.\n\nEnd segment.\n\nFixpoint Convn (A : convType) n : {fdist 'I_n} -> ('I_n -> A) -> A :=\n  match n return forall (e : {fdist 'I_n}) (g : 'I_n -> A), A with\n  | O => fun e g => False_rect A (fdistI0_False e)\n  | m.+1 => fun e g =>\n    match Bool.bool_dec (e ord0 == 1%R) true with\n    | left _ => g ord0\n    | right H => let G := fun i => g (fdist_del_idx ord0 i) in\n      g ord0 <| probfdist e ord0 |> Convn (fdist_del (Bool.eq_true_not_negb _ H)) G\n    end\n  end.\n\nNotation \"'<|>_' d f\" := (Convn d f) : convex_scope.\n\nDefinition affine (U V : convType) (f : U -> V) :=\n  forall p, {morph f : a b / a <| p |> b >-> a <| p |> b}.\n\nHB.mixin Record isAffine (U V : convType) (f : U -> V) := {\n  affine_conv : affine f }.\n\nHB.structure Definition Affine (U V : convType) := {f of isAffine U V f}.\n\nNotation \"{ 'affine' T '->' R }\" := (Affine.type T R) : convex_scope.\n\nSection affine_function_instances.\nVariables (U V W : convType) (f : {affine V -> W}) (h : {affine U -> V}).\n\nLet affine_idfun : affine (@idfun U). Proof. by []. Qed.\nHB.instance Definition _ := isAffine.Build _ _ idfun affine_idfun.\n\nLet affine_comp : affine (f \\o h).\nProof. by move=> x y t /=; rewrite 2!affine_conv. Qed.\n\nHB.instance Definition _ := isAffine.Build _ _ (f \\o h) affine_comp.\n\nEnd affine_function_instances.\n\nDeclare Scope scaled_scope.\nDelimit Scope scaled_scope with scaled.\n\nSection scaled.\nVariable A : Type.\n\n(* Note: we need the argument of Scaled to be an Rpos, because otherwise\n   addpt cannot make a commutative monoid:\n   1) if addpt (Scaled 0 x) (Scaled 0 y) = Scaled 0 x commutativity fails\n      so at least we need addpt (Scaled 0 x) (Scaled 0 y) = Zero\n   2) if addpt (Scaled 0 x) Zero = Zero then left/right identity fail\n   2) if addpt (Scaled 0 x) Zero = Scaled 0 x then associativity fails\n      addpt (Scaled 0 x) (addpt (Scaled 0 y) (Scaled 0 z)) = Scaled 0 x\n      addpt (addpt (Scaled 0 x) (Scaled 0 y)) (Scaled 0 z) = Scaled 0 z\n   So we cannot allow 0 as argument to Scaled.                             *)\nInductive scaled := Scaled of Rpos & A | Zero.\n\nDefinition sum_of_scaled (m : scaled) : Rpos * A + unit :=\n  match m with Scaled r a => inl _ (r, a) | Zero => inr _ tt end.\n\nLocal Notation \"p *: a\" := (Scaled p a).\n\nDefinition scaled_of_sum (m : (Rpos * A) + unit) :=\n  match m with inl p => p.1 *: p.2 | inr n => Zero end.\n\nLemma sum_of_scaledK : cancel sum_of_scaled scaled_of_sum.\nProof. by case. Qed.\n\nDefinition S1 a : scaled := 1%:pos *: a.\n\nLemma Scaled_inj p : injective (Scaled p).\nProof. by move=> x y []. Qed.\n\nDefinition S1_inj : injective S1 := @Scaled_inj Rpos1.\n\nDefinition raw_weight (pt : scaled) : R := if pt is r *: _ then r else 0.\n\nLemma weight_ge0 pt : (0 <= raw_weight pt)%R.\nProof. case: pt => /= [[x] /= /ltRP/ltRW //|]; by apply leRR. Qed.\n\nDefinition weight := mkNNFun weight_ge0.\n\nDefinition point pt : (weight pt > 0)%R -> A :=\n match pt with\n | t *: a => fun=> a\n | Zero => fun H : (weight Zero > 0)%R => match ltRR 0 H with end\n end.\n\nLemma point_Scaled p x H : @point (p *: x) H = x.\nProof. by []. Qed.\n\nLemma Scaled_point x H : mkRpos H *: @point x H = x.\nProof.\nby case: x H => [p x|] H; [congr (_ *: _); apply val_inj | case: (ltRR 0)].\nQed.\n\nEnd scaled.\nArguments Zero {A}.\nArguments point {A} pt.\nArguments weight {A}.\nNotation \"p *: a\" := (Scaled p a) : scaled_scope.\n\nDefinition scaled_eqMixin (A : eqType) := CanEqMixin (@sum_of_scaledK A).\nCanonical scaled_eqType (A : eqType) :=\n  Eval hnf in EqType (scaled A) (@scaled_eqMixin A).\nDefinition scaled_choiceMixin (A : choiceType) :=\n  CanChoiceMixin (@sum_of_scaledK A).\nCanonical scaled_choiceType (A : choiceType) :=\n  Eval hnf in ChoiceType (scaled A) (@scaled_choiceMixin A).\nCanonical scaled_pointedType (A : choiceType) := PointedType _ (@Zero A).\n\nSection scaled_eqType.\nVariable A : eqType.\n\nLemma S1_neq0 a : S1 a != @Zero A. Proof. by []. Qed.\n\nLemma weight_gt0 a : a != @Zero A -> (0 < weight a)%R.\nProof. by case: a => // p x _ /=. Qed.\n\nLemma weight_gt0b a : a != @Zero A -> (weight a >b 0)%R.\nProof. by move=> ?; exact/ltRP/weight_gt0. Qed.\n\nDefinition weight_neq0 a (a0 : a != @Zero A) := Rpos.mk (weight_gt0b a0).\n\nLocal Notation \"[ 'point' 'of' x ]\" := (@point _ _ (@weight_gt0 _ x))\n  (at level 0, format \"[ 'point'  'of'  x ]\").\nLocal Notation \"[ 'weight' 'of' x ]\" := (weight_neq0 x)\n  (at level 0, format \"[ 'weight'  'of'  x ]\").\n\nLemma point_S1 a : [point of S1_neq0 a] = a.\nProof. by []. Qed.\n\nLemma weight0_Zero a : weight a = 0%R -> a = @Zero A.\nProof. by case: a => //= r c /esym Hr; move/ltR_eqF: (Rpos_gt0 r) => /eqP. Qed.\n\nEnd scaled_eqType.\nNotation \"[ 'point' 'of' x ]\" := (@point _ _ (@weight_gt0 _ _ x))\n  (at level 0, format \"[ 'point'  'of'  x ]\").\nNotation \"[ 'weight' 'of' x ]\" := (weight_neq0 x)\n  (at level 0, format \"[ 'weight'  'of'  x ]\").\n\nHB.mixin Record isQuasiRealCone A := {\n  quasirealconechoiceclass : Choice.class_of A ;\n  addpt : A -> A -> A ;\n  zero : A ;\n  addptC : commutative addpt ;\n  addptA : associative addpt ;\n  addpt0 : right_id zero addpt ;\n  scalept : R -> A -> A ;\n  scale0pt : forall x, scalept 0%R x = zero ;\n  scale1pt : forall x, scalept 1%R x = x ;\n  scaleptDr : forall r, {morph scalept r : x y / addpt x y >-> addpt x y} ;\n  scaleptA : forall p q x, (0 <= p)%R -> (0 <= q)%R ->\n    scalept p (scalept q x) = scalept (p * q)%R x }.\n\n#[short(type=quasiRealCone)]\nHB.structure Definition QuasiRealCone := { A & isQuasiRealCone A}.\n\nCanonical quasirealcone_eqType (T : quasiRealCone) :=\n  Eval hnf in EqType (QuasiRealCone.sort T) quasirealconechoiceclass.\nCanonical quasirealcone_choiceType (T : quasiRealCone) :=\n  Eval hnf in ChoiceType (QuasiRealCone.sort T) quasirealconechoiceclass.\nCoercion quasirealcone_choiceType : quasiRealCone >-> choiceType.\n\nSection quasireal_cone_theory.\nVariable A : quasiRealCone.\n\nLemma add0pt : left_id (@zero A) addpt.\nProof. by move=> ?; rewrite addptC addpt0. Qed.\n\nLemma scalept0 p : (0 <= p)%R -> scalept p zero = @zero A.\nProof.\nby move=> p0; rewrite -[in LHS](scale0pt zero) scaleptA// mulR0 scale0pt.\nQed.\n\nCanonical addpt_monoid := Monoid.Law (@addptA A) add0pt addpt0.\nCanonical addpt_comoid := Monoid.ComLaw (@addptC A).\n\nDefinition big_morph_scalept q :=\n  @big_morph _ _ (@scalept A q) zero addpt zero _ (@scaleptDr A q).\n\nLocal Notation \"\\ssum_ ( i <- r ) F\" := (\\big[addpt/@zero A]_(i <- r) F).\nLocal Notation \"\\ssum_ ( i : t ) F\" := (\\big[addpt/@zero A]_(i : t) F) (only parsing).\nLocal Notation \"\\ssum_ i F\" := (\\big[addpt/@zero A]_i F).\nLocal Notation \"\\ssum_ ( i | P ) F\" := (\\big[addpt/@zero A]_(i | P) F).\nLocal Notation \"\\ssum_ ( i < n | P ) F\" := (\\big[addpt/@zero A]_(i < n | P%B) F).\nLocal Notation \"\\ssum_ ( i < n ) F\" := (\\big[addpt/@zero A]_(i < n) F).\n\nDefinition barycenter (pts : seq A) := \\ssum_(x <- pts) x.\n\nLemma barycenter_map (T : finType) (F : T -> A) :\n  barycenter [seq F i | i <- enum T] = \\ssum_i F i.\nProof. by rewrite /barycenter big_map big_filter. Qed.\n\nLemma scalept_barycenter p (H : (0 <= p)%R) pts :\n  scalept p (barycenter pts) = barycenter [seq scalept p i | i <- pts].\nProof. by rewrite big_morph_scalept ?scalept0// /barycenter big_map. Qed.\n\nLemma ssum_perm n (F : 'I_n -> A) (pe : 'S_n) :\n  \\ssum_(i < n) F i = \\ssum_(i < n) F (pe i).\nProof.\nrewrite -!barycenter_map /barycenter big_map map_comp big_map.\nexact/perm_big/perm_eq_perm.\nQed.\n\nEnd quasireal_cone_theory.\nNotation \"\\ssum_ ( i <- r ) F\" := (\\big[addpt/@zero _]_(i <- r) F).\nNotation \"\\ssum_ ( i <- r | P ) F\" := (\\big[addpt/@zero _]_(i <- r | P ) F).\nNotation \"\\ssum_ ( i : t ) F\" := (\\big[addpt/@zero _]_(i : t) F) (only parsing).\nNotation \"\\ssum_ i F\" := (\\big[addpt/@zero _]_i F).\nNotation \"\\ssum_ ( i | P ) F\" := (\\big[addpt/@zero _]_(i | P) F).\nNotation \"\\ssum_ ( i < n | P ) F\" := (\\big[addpt/@zero _]_(i < n | P%B) F).\nNotation \"\\ssum_ ( i < n ) F\" := (\\big[addpt/@zero _]_(i < n) F).\n\nHB.mixin Record isRealCone (A : Type) of isQuasiRealCone A := {\n  scaleptDl : forall p q x, (0 <= p)%R -> (0 <= q)%R ->\n    @scalept [the quasiRealCone of A] (p + q)%R x = addpt (scalept p x) (scalept q x) }.\n\n#[short(type=realCone)]\nHB.structure Definition RealCone := { A of isQuasiRealCone A & isRealCone A}.\n\nSection real_cone_theory.\nVariable A : realCone.\n\nLemma scalept_sum (B : finType) (P : pred B) (F : B ->R^+) (x : A) :\n  scalept (\\sum_(i | P i) F i) x = \\ssum_(b | P b) scalept (F b) x.\nProof.\napply: (@proj1 _ (0 <= \\sum_(i | P i) F i))%R.\napply: (big_ind2 (fun y q => scalept q x = y /\\ 0 <= q))%R.\n+ by rewrite scale0pt.\n+ move=> _ x2 _ y2 [<- ?] [<- ?].\n  by rewrite scaleptDl //; split => //; exact: addR_ge0.\n+ by move=> i _; split => //; exact/nneg_f_ge0.\nQed.\n\nSection barycenter_fdist_convn.\nVariables (n : nat) (B : finType).\nVariable p : {fdist 'I_n}.\nVariable q : 'I_n -> {fdist B}.\nVariable h : B -> A.\n\nLemma ssum_fdist_convn :\n  (* TODO: \\ssum_(j in B) notation? *)\n  \\ssum_(i < n) scalept (p i) (\\ssum_(j <- enum B) scalept (q i j) (h j)) =\n  \\ssum_(j <- enum B) scalept (fdist_convn p q j) (h j).\nProof.\ntransitivity (\\ssum_i \\ssum_(i0 <- enum B) scalept (p i) (scalept (q i i0) (h i0))).\n  by apply eq_bigr => i _; rewrite big_morph_scalept// scalept0.\nrewrite exchange_big /=; apply eq_bigr => j _; rewrite fdist_convnE.\nhave HF i : (0 <= p i * q i j)%R by exact/mulR_ge0.\nrewrite (scalept_sum _ (mkNNFun HF)) /=; apply eq_bigr => i _.\nby rewrite scaleptA.\nQed.\n\nEnd barycenter_fdist_convn.\n\nEnd real_cone_theory.\n\nSection real_cone_instance.\nVariable A : convType.\nLocal Open Scope R_scope.\nLocal Open Scope convex_scope.\nLocal Open Scope scaled_scope.\n\nLet addpt (a b : scaled A) :=\n  match a, b with\n  | r *: x, q *: y => (r + q)%:pos *: (x <| ((r / (r + q))%:pos)%:pr |> y)\n  | _, Zero => a\n  | Zero, _ => b\n  end.\n\nLet addptC : commutative addpt.\nProof.\nmove=> [r x|] [q y|] //=; congr (_ *: _); first by apply: val_inj; rewrite /= addRC.\nby rewrite convC; congr (_ <| _ |> _); exact/val_inj/onem_divRxxy.\nQed.\n\nLet addptA : associative addpt.\nProof.\nmove=> [p x|] [q y|] [r z|] //=; congr (_ *: _); first by apply val_inj; rewrite /= addRA.\nrewrite convA; congr (_ <| _ |> _ ); first exact: s_of_Rpos_probA.\nby congr (_ <| _ |> _); exact: r_of_Rpos_probA.\nQed.\n\nLet addpt0 : right_id (@Zero A) addpt. Proof. by case. Qed.\n\nLet add0pt : left_id (@Zero A) addpt. Proof. by case. Qed.\n\nLet scalept p (x : scaled A) :=\n  match Rlt_dec 0 p, x with\n  | left Hr, q *: y => (mkRpos Hr * q)%:pos *: y\n  | _, _ => Zero\n  end.\n\nLet scale0pt x : scalept 0 x = Zero.\nProof. by rewrite /scalept; case: Rlt_dec => // Hr; case: (ltRR 0). Qed.\n\nLet scalept0 p : scalept p Zero = Zero.\nProof. by rewrite /scalept; case: Rlt_dec. Qed.\n\nLet scale1pt x : scalept 1 x = x.\nProof.\ncase: x => [r c|]; last by rewrite scalept0.\nby rewrite /scalept/=; case: Rlt_dec => //= ?; congr (_ *: _); apply/val_inj => /=; rewrite mul1R.\nQed.\n\nLet scaleptDr r : {morph scalept r : x y / addpt x y >-> addpt x y}.\nProof.\nrewrite /scalept; case: Rlt_dec => // r_gt0 x y.\ncase: x => [p x|]; last by rewrite !add0pt.\ncase: y => [q y|]; last by rewrite !addpt0.\ncongr (_ *: _); first by apply val_inj => /=; rewrite mulRDr.\ncongr (_ <| _ |> _); apply val_inj; rewrite /= -mulRDr divRM ?gtR_eqF//.\nby rewrite /Rdiv -(mulRAC r) mulRV ?mul1R // gtR_eqF.\nQed.\n\nLet scalept_gt0 p (q : Rpos) x (p_gt0 : 0 < p) :\n  scalept p (q *: x) = (mkRpos p_gt0 * q)%:pos *: x.\nProof.\nby rewrite /scalept; case: Rlt_dec => // Hr; congr (_ *: _); exact/val_inj.\nQed.\n\nLet scaleptA p q x : 0 <= p -> 0 <= q -> scalept p (scalept q x) = scalept (p * q) x.\nProof.\ncase=> Hp; last by rewrite -Hp mul0R !scale0pt.\ncase=> Hq; last by rewrite -Hq mulR0 scale0pt scalept0.\ncase: x => [r x|]; rewrite ?scalept0 // !scalept_gt0; first exact: mulR_gt0.\nby move=> Hpq; congr (_ *: _); apply val_inj => /=; rewrite mulRA.\nQed.\n\nHB.instance Definition _ := @isQuasiRealCone.Build (scaled A)\n  (Choice.class (@scaled_choiceType A)) addpt Zero addptC addptA addpt0\n   scalept scale0pt scale1pt scaleptDr scaleptA.\n\nLet scaleptDl p q x : 0 <= p -> 0 <= q ->\n  scalept (p + q) x = addpt (scalept p x) (scalept q x).\nProof.\ncase=> p0; last by rewrite -p0 scale0pt add0R add0pt.\ncase=> q0; last by rewrite -q0 scale0pt addR0 addpt0.\ncase: x => [r c|]; last by rewrite !scalept0.\nrewrite !scalept_gt0 => [|pq0 /=]; first by apply addR_gt0.\nby rewrite convmm; congr (_ *: _); apply val_inj; rewrite /= mulRDl.\nQed.\n\nHB.instance Definition _ := @isRealCone.Build (scaled A) scaleptDl.\n\nEnd real_cone_instance.\n\nSection convpt_convex_space.\nVariable A : convType.\n\nLet convpt p (x y : scaled A) := addpt (scalept p x) (scalept p.~ y).\n\nLet convpt1 a b : convpt 1 a b = a.\nProof. by rewrite /convpt onem1 scale1pt scale0pt addpt0. Qed.\n\nLet convptmm (p : prob) a : convpt p a a = a.\nProof. by rewrite /convpt -scaleptDl // onemKC scale1pt. Qed.\n\nLet convptC (p : prob) a b : convpt p a b = convpt (p.~)%:pr b a.\nProof. by rewrite [RHS]addptC onemK. Qed.\n\nLet convptA (p q : prob) a b c :\n  convpt p a (convpt q b c) = convpt [s_of p, q] (convpt [r_of p, q] a b) c.\nProof.\nrewrite /convpt.\nrewrite !scaleptDr !scaleptA // -[RHS]addptA; congr addpt.\n  by rewrite (p_is_rs p q) mulRC.\nby rewrite pq_is_rs mulRC s_of_pqE onemK.\nQed.\n\nHB.instance Definition __cone := @isConvexSpace.Build (scaled A)\n  (Choice.class [the choiceType of scaled A]) convpt convpt1 convptmm convptC\n  convptA.\n\nLemma convptE p (a b : scaled A) : a <| p |> b = convpt p a b.\nProof. by []. Qed.\n\nEnd convpt_convex_space.\n\nSection scaled_convex.\nVariable A : convType.\nLocal Open Scope R_scope.\nLocal Open Scope convex_scope.\nLocal Open Scope scaled_scope.\n\nLemma scalept_Scaled p q (x : A) : scalept p (q *: x) = scalept (p * q) (S1 x).\nProof.\nrewrite /scalept /=.\ncase: Rlt_dec => Hp; case: Rlt_dec => Hpq //.\n- congr (_ *: _); apply val_inj; by rewrite /= mulR1.\n- elim Hpq; by apply /mulR_gt0.\n- elim Hp; move/pmulR_lgt0: Hpq; exact.\nQed.\n\nLemma scalept_gt0 p (q : Rpos) (x : A) (H : 0 < p) :\n  scalept p (q *: x) = (mkRpos H * q)%:pos *: x.\nProof.\nrewrite /scalept /= ; case: Rlt_dec => // Hr.\nby congr (_ *: _); apply val_inj.\nQed.\n\nLemma addptE a b (a0 : a != @Zero A) (b0 : b != Zero) :\n  let p := [weight of a0] in\n  let q := [weight of b0] in\n  let x := [point of a0] in\n  let y := [point of b0] in\n  addpt a b = (p + q)%:pos *: (x <| ((p / (p + q))%:pos)%:pr |> y).\nProof.\nmove: a b => [p x|//] [pb y|//] /= in a0 b0 *.\nby congr (_ *: (_ <| _ |> _)); exact: val_inj.\nQed.\n\nLemma weight_addpt : {morph @weight A : x y / addpt x y >-> x + y}.\nProof. move=> [p x|] [q y|] //=; by rewrite (add0R, addR0). Qed.\n\nLemma weight0 : weight (@Zero A) = 0. Proof. by []. Qed.\n\nLemma scalept_weight p (x : scaled A) : 0 <= p -> weight (scalept p x) = p * weight x.\nProof.\ncase=> [p0|<-]; last by rewrite scale0pt mul0R.\ncase: x => [r y|]; first by rewrite /= /scalept/=; case: Rlt_dec.\nby rewrite scalept0 ?mulR0//; exact/ltRW.\nQed.\n\nLemma weight_barycenter (pts : seq (scaled A)) :\n  weight (barycenter pts) = \\sum_(x <- pts) weight x.\nProof. by rewrite (big_morph weight weight_addpt weight0). Qed.\n\nSection adjunction.\n\nLemma affine_S1 : affine (@S1 A).\nProof.\nmove=> p x y.\nhave [p0|p0] := prob_ge0 p; last first.\n  by rewrite (_ : p = 0%:pr) ?conv0 //; exact/val_inj.\nhave [p1|p1] := prob_le1 p; last first.\n  by rewrite (_ : p = 1%:pr) ?conv1 //; exact/val_inj.\nrewrite convptE (scalept_gt0 _ _ p0) (@scalept_gt0 p.~); first exact/onem_gt0.\nmove=> mp0; congr (_ *: _) => /=; first by apply/val_inj => /=; rewrite !mulR1 onemKC.\nby congr (_ <| _ |> _); apply val_inj; rewrite /= !mulR1 addRC subRK divR1.\nQed.\n\nHB.instance Definition _ := isAffine.Build _ _ (@S1 A) affine_S1.\n\nEnd adjunction.\n\nEnd scaled_convex.\n\nSection convex_space_prop1.\nVariables T : convType.\nImplicit Types a b : T.\n\nLemma convA0 (p q r s : prob) a b c :\n  p = (r * s)%R :> R -> (s.~ = p.~ * q.~)%R ->\n  a <| p |> (b <| q |> c) = (a <| r |> b) <| s |> c.\nProof.\nmove=> H1 H2.\nhave [r0|r0] := eqVneq r 0%:pr.\n  rewrite r0 conv0 (_ : p = 0%:pr) ?conv0; last first.\n    by apply/val_inj; rewrite /= H1 r0 mul0R.\n  congr (_ <| _ |> _); move: H2; rewrite H1 r0 mul0R onem0 mul1R.\n  by move/(congr1 onem); rewrite !onemK => ?; exact/val_inj.\nhave [s0|s0] := eqVneq s 0%:pr.\n  have p0 : p = 0%:pr by apply/val_inj; rewrite /= H1 s0 mulR0.\n  rewrite s0 conv0 p0 // ?conv0.\n  rewrite (_ : q = 0%:pr) ?conv0 //.\n  move: H2; rewrite p0 onem0 mul1R => /(congr1 onem); rewrite !onemK => sq.\n  by rewrite -s0; exact/val_inj.\nrewrite convA; congr ((_ <| _ |> _) <| _ |> _).\n  by apply val_inj; rewrite /= s_of_pqE -H2 onemK.\nby rewrite (@r_of_pq_is_r  _ _ r s).\nQed.\n\nLemma convA' (r s : prob) a b c :\n  a <| [p_of r, s] |> (b <| [q_of r, s] |> c) = (a <| r |> b) <| s |> c.\nProof.\nhave [/eqP|H] := eqVneq [p_of r, s] 1%:pr.\n  by move=> /p_of_rs1P[-> ->]; rewrite p_of_r1 3!conv1.\nhave [->|s0] := eqVneq s 0%:pr; first by rewrite p_of_r0 q_of_r0 3!conv0.\nby rewrite convA s_of_pqK// r_of_pqK.\nQed.\n\nLemma convACA (a b c d : T) p q :\n  (a <|q|> b) <|p|> (c <|q|> d) = (a <|p|> c) <|q|> (b <|p|> d).\nProof.\napply: S1_inj; rewrite ![in LHS]affine_conv/= !convptE.\nrewrite !scaleptDr !scaleptA// !(mulRC p) !(mulRC p.~) addptA addptC.\nrewrite (addptC (scalept (q * p) _)) !addptA -addptA -!scaleptA -?scaleptDr//.\nby rewrite !(addptC (scalept _.~ _)) !affine_conv.\nQed.\n\nLemma convDr (x y z : T) (p q : prob) :\n  x <| p |> (y <| q |> z) = (x <| p |> y) <| q |> (x <| p |> z).\nProof. by rewrite -{1}(convmm q x) convACA. Qed.\n\nLemma convACA' (a b c d : T) (p q r : prob) :\n(*\n  let p1 := (q * p)%:opr in\n  let p2 := (q.~ * r)%:opr in\n  let r1 := (q * p.~)%:opr in\n  let r2 := (q.~ * r.~)%:opr in\n  let q' := ((p1 + p2) / (p1 + p2 + (r1 + r2)))%:opr in\n  let p' := (p1 / (p1 + p2))%:opr in\n  let r' := (r1 / (r1 + r2))%:opr in\n  (a <|p|> b) <|q|> (c <|r|> d) = (a <|p'|> c) <|q'|> (b <|r'|> d).\n*)\n  exists p' q' r', (a <|p|> b) <|q|> (c <|r|> d) = (a <|p'|> c) <|q'|> (b <|r'|> d).\nProof.\nrewrite (convC p) convA convC !convA.\nset C0 := _.~%:pr.\nset C1 := _.~%:pr.\nrewrite -convA' (convC _ d) convC.\nby eexists; eexists; eexists; congr ((_ <|_|> _) <|_|> (_ <|_|> _)).\nQed.\n\nLocal Open Scope vec_ext_scope.\n\nSection with_affine_projection.\nVariable U : convType.\nVariable prj : {affine T -> U}.\nLocal Open Scope scaled_scope.\n\nDefinition map_scaled (x : scaled T) : scaled U :=\n  if x is p *: a then p *: prj a else Zero.\n\nLemma affine_map_scaled : affine map_scaled.\nProof.\nmove=> p [q x|] [r y|] /=; rewrite 2!convptE ?scalept0 //.\n- rewrite !(scalept_Scaled p) !(scalept_Scaled p.~) /= /scalept /=.\n  case: Rlt_dec => Hpq; case: Rlt_dec => Hpr //=; congr (_ *: _).\n  by rewrite affine_conv.\n- by rewrite !addpt0 !(scalept_Scaled p) /= /scalept /=; case: Rlt_dec.\n- by rewrite !add0pt !(scalept_Scaled p.~) /= /scalept/=; case: Rlt_dec.\nQed.\n\nHB.instance Definition _ := isAffine.Build _ _ map_scaled affine_map_scaled.\n\nLemma S1_Convn_proj n (g : 'I_n -> T) d :\n  S1 (prj (<|>_d g)) = \\ssum_(i < n) scalept (d i) (S1 (prj (g i))).\nProof.\nelim: n g d => [|n IH] g d.\n  by move: (FDist.f1 d); rewrite /= big_ord0 => /Rlt_not_eq; case.\nrewrite /=; case: Bool.bool_dec => [/eqP|/Bool.eq_true_not_negb]Hd.\n  rewrite (bigD1 ord0) //= Hd big1 /=.\n    rewrite addpt0 (@scalept_gt0 _ 1).\n    by congr (_ *: _); apply val_inj; rewrite /= mulR1.\n  move=> i Hi; have := FDist.f1 d.\n  rewrite (bigD1 ord0) ?inE // Hd /= addRC => /(f_equal (Rminus^~ R1)).\n  by rewrite addRK subRR => /psumR_eq0P -> //; rewrite scale0pt.\nset d' := fdist_del Hd.\nset g' := fun i => g (fdist_del_idx ord0 i).\nrewrite /index_enum -enumT (bigD1_seq ord0) ?enum_uniq ?mem_enum //=.\nrewrite -big_filter (perm_big (map (lift ord0) (enum 'I_n))); last first.\n  exact: perm_filter_enum_ord.\nrewrite 2!affine_conv/=; congr addpt.\nrewrite IH -barycenter_map scalept_barycenter //.\nrewrite /barycenter 2!big_map [in RHS]big_map.\napply eq_bigr => i _.\nrewrite scaleptA // fdist_delE fdistD1E /=.\nrewrite /Rdiv (mulRC (d _)) mulRA mulRV ?mul1R //.\nby move: (Hd); apply contra => /eqP Hd'; rewrite -onem0 -Hd' onemK.\nQed.\n\nEnd with_affine_projection.\n\nLemma S1_Convn n (g : 'I_n -> T) d :\n  S1 (<|>_d g) = \\ssum_(i < n) scalept (d i) (S1 (g i)).\nProof. by rewrite (S1_Convn_proj [the {affine _ ->_} of idfun]). Qed.\n\nLemma fdist_convn_add n m p (g : 'I_(n + m) -> T) (d : {fdist 'I_n})\n    (e : {fdist 'I_m}) :\n  <|>_(fdist_add d e p) g =\n  <|>_d (g \\o @lshift n m) <| p |> <|>_e (g \\o @rshift n m).\nProof.\napply: S1_inj; rewrite affine_conv/= !S1_Convn convptE big_split_ord/=.\ndo 2 rewrite [in RHS]big_morph_scalept ?scalept0//.\ncongr addpt; apply eq_bigr => i _;\n  rewrite (scaleptA _ _ (S1 _) (prob_ge0 _) (FDist.ge0 _ _));\n  by rewrite fdist_addE (split_lshift,split_rshift).\nQed.\n\nEnd convex_space_prop1.\n\nSection convex_space_prop2.\nVariables T U : convType.\nImplicit Types a b : T.\n\nLemma Convn_comp (f : {affine T -> U}) n (g : 'I_n -> T) (d : {fdist 'I_n}) :\n  f (<|>_d g) = <|>_d (f \\o g).\nProof. by apply S1_inj; rewrite S1_Convn S1_Convn_proj. Qed.\n\nLemma eq_Convn n (g1 g2 : 'I_n -> T) (d1 d2 : {fdist 'I_n}) :\n  g1 =1 g2 -> d1 =1 d2 -> <|>_d1 g1 = <|>_d2 g2.\nProof.\nmove=> Hg Hd; apply S1_inj; rewrite !S1_Convn.\nby apply congr_big => // i _; rewrite Hg Hd.\nQed.\n\nLemma eq_dep_Convn n (g : 'I_n -> T) (d : {fdist 'I_n})\n      n0 (g0 : 'I_n0 -> T) (d0 : {fdist 'I_n0}) (Hn : n = n0)\n      (Hg : eq_rect n (fun m => 'I_m -> T) g n0 Hn = g0)\n      (Hd : eq_rect n (fun m => {fdist 'I_m}) d n0 Hn = d0) :\n  <|>_d g = <|>_d0 g0.\nProof.\nrefine (match Hd with erefl => _ end).\nrefine (match Hg with erefl => _ end).\nrefine (match Hn with erefl => _ end).\nreflexivity.\nQed.\n\nLemma Convn_proj n (g : 'I_n -> T) (d : {fdist 'I_n}) i :\n  d i = R1 -> <|>_d g = g i.\nProof.\nmove=> Hd; apply: S1_inj.\nrewrite S1_Convn (bigD1 i)//=.\nrewrite big1; first by rewrite addpt0 Hd scale1pt.\nmove=> j Hj.\nby move/eqP/fdist1P: Hd => -> //; rewrite scale0pt.\nQed.\n\nLemma Convn_fdist1 (n : nat) (j : 'I_n) (g : 'I_n -> T) :\n  <|>_(fdist1 j) g = g j.\nProof. by apply Convn_proj; rewrite fdist1xx. Qed.\n\nLemma ConvnI1E\n  (g : 'I_1 -> T) (e : {fdist 'I_1}) : <|>_ e g = g ord0.\nProof.\nrewrite /=; case: Bool.bool_dec => // /Bool.eq_true_not_negb H.\nexfalso; move/eqP: H; apply.\nby apply/eqP; rewrite fdist1E1 (fdist1I1 e).\nQed.\n\nLemma ConvnI1_eq_rect n (g : 'I_n -> T) (d : {fdist 'I_n}) (Hn1 : n = 1) :\n  <|>_d g = eq_rect n (fun n => 'I_n -> T) g 1 Hn1 ord0.\nProof.\nset d' := eq_rect n (fun n0 => {fdist 'I_n0}) d 1 Hn1.\nset g' := eq_rect n (fun n0 => 'I_n0 -> T) g 1 Hn1.\nsuff -> : <|>_d g = <|>_d' g' by rewrite ConvnI1E.\nby eapply eq_dep_Convn.\nQed.\n\nLemma ConvnI1_eq n (g : 'I_n -> T) (d : {fdist 'I_n})\n      (n1 : n = 1) (i : 'I_n) : <|>_d g = g i.\nProof.\nrewrite ConvnI1_eq_rect.\nhave -> /= : eq_rect n (fun n0 : nat => 'I_n0 -> T) g 1 n1 =\n    g \\o eq_rect 1 (fun n0 => 'I_1 -> 'I_n0) idfun n (esym n1)\n  by subst n.\nhave /(_ i) I_n_contr : forall a b : 'I_n, a = b\n    by rewrite n1 => a b; rewrite (ord1 a) (ord1 b).\nby rewrite -(I_n_contr (eq_rect 1 (fun n => 'I_1 -> 'I_n) idfun n (esym n1) ord0)).\nQed.\nGlobal Arguments ConvnI1_eq [n g d n1].\n\nLemma ConvnIE n (g : 'I_n.+1 -> T) (d : {fdist 'I_n.+1}) (i1 : d ord0 != 1%R) :\n  <|>_d g = g ord0 <| probfdist d ord0 |>\n            <|>_(fdist_del i1) (fun x => g (fdist_del_idx ord0 x)).\nProof.\nrewrite /=; case: Bool.bool_dec => /= [|/Bool.eq_true_not_negb] H.\nexfalso; by rewrite (eqP H) eqxx in i1.\nby rewrite (eq_irrelevance H i1).\nQed.\n\nLemma ConvnI2E (g : 'I_2 -> T) (d : {fdist 'I_2}) :\n  <|>_d g = g ord0 <| probfdist d ord0 |> g (lift ord0 ord0).\nProof.\nhave [/eqP|i1] := eqVneq (d ord0) 1%R.\n  rewrite fdist1E1 => /eqP ->; rewrite Convn_fdist1.\n  rewrite (_ : probfdist _ _ = 1%:pr) ?conv1 //.\n  by apply val_inj; rewrite /= fdist1xx.\nrewrite ConvnIE; congr (_ <| _ |> _).\nby rewrite ConvnI1E /fdist_del_idx ltnn.\nQed.\n\n(* ref: M.H.Stone, postulates for the barycentric calculus, lemma 2 *)\nLemma Convn_perm (n : nat) (d : {fdist 'I_n}) (g : 'I_n -> T) (s : 'S_n) :\n  <|>_d g = <|>_(fdistI_perm d s) (g \\o s).\nProof.\napply S1_inj; rewrite !S1_Convn (ssum_perm _ s).\nby apply eq_bigr => i _; rewrite fdistI_permE.\nQed.\n\n(* ref: M.H.Stone, postulates for the barycentric calculus, lemma 4 *)\nTheorem Convn_fdist_convn (n m : nat) (d : {fdist 'I_n})\n        (e : 'I_n -> {fdist 'I_m}) (x : 'I_m -> T) :\n  <|>_d (fun i => <|>_(e i) x) = <|>_(fdist_convn d e) x.\nProof.\napply S1_inj; rewrite !S1_Convn -[in RHS]big_enum -ssum_fdist_convn.\nby apply eq_bigr => i _; rewrite big_enum S1_Convn.\nQed.\n\nLemma Convn_cst (a : T) (n : nat) (d : {fdist 'I_n}) : <|>_d (fun=> a) = a.\nProof.\nelim: n d; first by move=> d; move/fdistI0_False: (d).\nmove=> n IHn d.\nhave [|] := eqVneq (d ord0) 1%R; first by move/(Convn_proj (fun=> a)).\nby move=> d0n0; rewrite ConvnIE IHn convmm.\nQed.\n\nLemma Convn_idem (a : T) (n : nat) (d : {fdist 'I_n}) (g : 'I_n -> T) :\n  (forall i : 'I_n, (d i != 0)%R -> g i = a) -> <|>_d g = a.\nProof.\nmove=> Hg; apply: S1_inj.\nrewrite S1_Convn (eq_bigr (fun i => scalept (d i) (S1 a))).\n  by rewrite -S1_Convn Convn_cst.\nmove=> /= i _.\nby have [-> //|/Hg ->//] := eqVneq (d i) 0%R; rewrite !scale0pt.\nQed.\n\nLemma Convn_weak n m (u : 'I_m -> 'I_n) (d : {fdist 'I_m}) (g : 'I_n -> T) :\n  <|>_d (g \\o u) = <|>_(fdistmap u d) g.\nProof.\napply S1_inj.\nrewrite !S1_Convn (partition_big u (fun _=> true)) //=.\napply eq_bigr => i _.\nrewrite fdistmapE /=.\nhave HF (a : 'I_m) : (0 <= d a)%R by [].\nrewrite (@scalept_sum _ _ _ (mkNNFun HF)) /=.\nby apply eq_bigr => a /eqP ->.\nQed.\n\nLemma ConvnDr n (p : prob) (x : T) (g : 'I_n -> T) (d : {fdist 'I_n}) :\n  x <|p|> <|>_d g = <|>_d (fun i => x <|p|> g i).\nProof.\nelim: n p x g d => [? ? ? d|n IHn p x g d]; first by move/fdistI0_False: (d).\nhave [d01|d0n1] := eqVneq (d ord0) 1%R.\n  by rewrite (Convn_proj g d01) (Convn_proj (fun i => x <|p|> g i) d01).\nby rewrite !ConvnIE !IHn; congr (<|>_ _ _); apply funext=> i; rewrite convDr.\nQed.\n\nLemma ConvnDl n (p : prob) (x : T) (g : 'I_n -> T) (d : {fdist 'I_n}) :\n  <|>_d g <|p|> x = <|>_d (fun i => g i <|p|> x).\nProof. by rewrite convC ConvnDr; apply eq_Convn =>// i; rewrite -convC. Qed.\n\nLemma ConvnDlr n m (p : prob) (f : 'I_n -> T) (d : {fdist 'I_n})\n                              (g : 'I_m -> T) (e : {fdist 'I_m}) :\n  <|>_d f <|p|> <|>_e g =\n  <|>_(fdist_add d e p)\n      (fun i => match fintype.split i with inl i => f i | inr i => g i end).\nProof.\napply: S1_inj; rewrite affine_conv/= 3!S1_Convn convptE.\ndo 2 rewrite big_morph_scalept ?scalept0//.\nrewrite big_split_ord/=.\ncongr addpt; apply: congr_big => //= i _; rewrite scaleptA// fdist_addE.\n- case: fintype.splitP => [j/= /ord_inj ->//|k/= ink].\n  by have := ltn_ord i; rewrite ink -ltn_subRL subnn.\n- case: fintype.splitP => [j/= nij|k/=/eqP/[!eqn_add2l]/eqP/ord_inj ->//].\n  by have := ltn_ord j; by rewrite -nij -ltn_subRL subnn.\nQed.\n\nEnd convex_space_prop2.\n\nSection hull_def.\nLocal Open Scope classical_set_scope.\nDefinition hull (T : convType) (X : set T) : set T :=\n  [set p : T | exists n (g : 'I_n -> T) d, g @` setT `<=` X /\\ p = <|>_d g].\nEnd hull_def.\n\nSection hull_prop.\nLocal Open Scope classical_set_scope.\nVariable A : convType.\nImplicit Types X Y : set A.\nImplicit Types a : A.\n\nLemma subset_hull X : X `<=` hull X.\nProof.\nmove=> x xX; rewrite /hull; exists 1, (fun=> x), (fdist1 ord0).\nsplit => [d [i _ <-] //|]; by rewrite ConvnI1E.\nQed.\n\nLemma hull0 : hull set0 = set0 :> set A.\nProof.\nrewrite funeqE => d; rewrite propeqE; split => //.\nmove=> [n [g [e [gX ->{d}]]]].\ndestruct n as [|n]; first by move: (fdistI0_False e).\nexfalso; apply: (gX (g ord0)); exact/imageP.\nQed.\n\nLemma hull_eq0 X : (hull X == set0) = (X == set0).\nProof.\napply/idP/idP=> [/eqP abs|]; last by move=> /eqP ->; rewrite hull0.\napply/negPn/negP => /set0P[/= d] => dX.\nmove: abs; rewrite funeqE => /(_ d); rewrite propeqE /set0 => -[H _]; apply H.\nexact/subset_hull.\nQed.\n\nLemma mem_hull_setU X Y a0 a1 p :\n  X a0 -> Y a1 -> hull (X `|` Y) (a0 <| p |> a1).\nProof.\nmove=> a0X a1y.\nexists 2, (fun i => if i == ord0 then a0 else a1), (fdistI2 p); split => /=.\n  by move=> _ [i _ <-] /=; case: ifPn => _; [left | right].\ncase: Bool.bool_dec => [/eqP|/Bool.eq_true_not_negb H].\n  rewrite fdistI2E eqxx /= => p1.\n  by rewrite (_ : p = 1%:pr) ?conv1 //; exact/val_inj.\ncongr (_ <| _ |> _); first by apply val_inj; rewrite /= fdistI2E eqxx.\ncase: Bool.bool_dec => // H'.\nexfalso.\nmove: H'; rewrite fdist_delE fdistD1E (eq_sym (lift _ _)) (negbTE (neq_lift _ _)).\nrewrite fdistI2E (eq_sym (lift _ _)) (negbTE (neq_lift _ _)) fdistI2E.\nrewrite eqxx divRR ?eqxx //.\nby move: H; rewrite fdistI2E eqxx onem_neq0.\nQed.\n\nLemma hull_monotone X Y : X `<=` Y -> hull X `<=` hull Y.\nProof.\nmove=> H a [n [g [d [H0 H1]]]]; exists n, g, d; split => //.\nby eapply subset_trans; first exact: H0.\nQed.\n\nEnd hull_prop.\n\n(* Convex sets in a convex space *)\n\nSection is_convex_set.\nLocal Open Scope classical_set_scope.\nVariable T : convType.\n\nDefinition is_convex_set (D : set T) : bool :=\n  `[<forall x y t, D x -> D y -> D (x <| t |> y)>].\n\nLemma is_convex_set0 : is_convex_set set0. Proof. exact/asboolP. Qed.\n\nLemma is_convex_set1 a : is_convex_set [set a].\nProof. by apply/asboolP => x y p /= => -> ->; rewrite convmm. Qed.\n\nLemma is_convex_setT : is_convex_set setT.\nProof. exact/asboolP. Qed.\n\nDefinition is_convex_set_n (X : set T) : bool :=\n  `[< forall n (g : 'I_n -> T) (d : {fdist 'I_n}),\n    g @` setT `<=` X -> X (<|>_d g) >].\n\nLemma is_convex_setP (X : set T) : is_convex_set X = is_convex_set_n X.\nProof.\napply/idP/idP => H; apply/asboolP.\n  elim => [g d|n IH g d]; first by move: (fdistI0_False d).\n  case: n => [|n] in IH g d * => gX.\n    rewrite {IH} (@Convn_proj _ _ _ _ ord0) //.\n      exact/gX/classical_sets.imageP.\n    by apply/eqP; rewrite fdist1E1 (fdist1I1 d).\n  have [d01|d01] := eqVneq (d ord0) 1%R.\n    suff -> : <|>_d g = g ord0 by apply gX; exists ord0.\n    by rewrite (@Convn_proj _ _ _ _ ord0).\n  set D : {fdist 'I_n.+1} := fdist_del d01.\n  pose G (i : 'I_n.+1) : T := g (fdist_del_idx (@ord0 _) i).\n  have /(IH _ D) {}IH : range G `<=` X.\n    move=> x -[i _ <-{x}]; rewrite /G /fdist_del_idx ltn0; apply gX.\n    by exists (lift ord0 i).\n  rewrite ConvnIE //.\n  by move/asboolP : H; apply => //; exact/gX/classical_sets.imageP.\nmove=> x y p xX yX.\nhave [->|p1] := eqVneq p 1%:pr; first by rewrite conv1.\nset g : 'I_2 -> T := fun i => if i == ord0 then x else y.\nhave gX : range g `<=` X by move=> a -[i _ <-]; rewrite /g; case: ifPn.\nmove/asboolP : H => /(_ _ g (fdistI2 p) gX).\nrewrite ConvnIE; first by rewrite fdistI2E eqxx.\nmove=> p1'.\nrewrite {1}/g eqxx (_ : probfdist _ _ = p); last first.\n  by apply val_inj; rewrite /= fdistI2E eqxx.\nby rewrite (_ : <|>_ _ _ = y) // (_ : (fun _ => _) = (fun=> y)) ?ConvnI1E.\nQed.\n\nLemma is_convex_segmentP (X : set T) :\n  reflect (forall x y, X x -> X y -> (segment x y `<=` X)%classic)\n          (is_convex_set X).\nProof.\napply: (iffP idP) => conv.\n  by move=> x y xX yX z [p _ <-]; move/asboolP : conv; apply.\nby apply/asboolP => x y p xX yX; apply: (conv _ _ xX yX); exists p.\nQed.\n\nLemma segment_is_convex (x y : T) : is_convex_set (segment x y).\nProof.\napply/asboolP => u v p [q _ <-] [r _ <-].\nhave [q' [p' [r' ->]]] := convACA' x y x y q p r.\nby rewrite convmm convmm; exists p'.\nQed.\n\nEnd is_convex_set.\n\nModule CSet.\nSection cset.\nVariable A : convType.\nRecord mixin_of (X : set A) : Type := Mixin { _ : is_convex_set X }.\nRecord t : Type := Pack { car : set A ; class : mixin_of car }.\nEnd cset.\nModule Exports.\nNotation convex_set := t.\nCoercion car : convex_set >-> set.\nEnd Exports.\nEnd CSet.\nExport CSet.Exports.\n\nDefinition convex_set_of (A : convType) :=\n  fun phT : phant (ConvexSpace.sort A) => convex_set A.\nNotation \"{ 'convex_set' T }\" := (convex_set_of (Phant T)) : convex_scope.\n\n(* kludge 2022-04-14 *)\nDefinition choice_of_Type (T : Type) : choiceType :=\n  Choice.Pack (Choice.Class (@gen_eqMixin T) gen_choiceMixin).\n\nSection cset_canonical.\nVariable (A : convType).\nCanonical cset_predType := Eval hnf in\n  PredType (fun t : convex_set A => (fun x => x \\in CSet.car t)).\nCanonical cset_eqType := Equality.Pack (@gen_eqMixin (convex_set A)).\nCanonical cset_choiceType := choice_of_Type (convex_set A).\nEnd cset_canonical.\n\nSection CSet_interface.\nVariable (A : convType).\nImplicit Types X Y : {convex_set A}.\nLemma convex_setP X : is_convex_set X.\nProof. by case: X => X []. Qed.\nLemma cset_ext X Y : X = Y :> set _ -> X = Y.\nProof.\nmove: X Y => -[X HX] [Y HY] /= ?; subst Y.\ncongr (CSet.Pack _); exact/Prop_irrelevance.\nQed.\nEnd CSet_interface.\n\nSection CSet_prop.\nLocal Open Scope classical_set_scope.\nVariable A : convType.\nImplicit Types X Y : {convex_set A}.\nImplicit Types a : A.\nImplicit Types x y : scaled A.\n\nLemma mem_convex_set a1 a2 p X : a1 \\in X -> a2 \\in X -> a1 <|p|> a2 \\in X.\nProof.\ncase: X => X [convX]; move: (convX) => convX_save.\nmove/asboolP : convX => convX Hx Hy.\nby rewrite in_setE; apply: convX; rewrite -in_setE.\nQed.\n\nDefinition cset0 : {convex_set A} := CSet.Pack (CSet.Mixin (is_convex_set0 A)).\n\nLemma cset0P X : (X == cset0) = (X == set0 :> set _).\nProof.\ncase: X => x [Hx] /=; apply/eqP/eqP => [-[] //| ?]; subst x; exact: cset_ext.\nQed.\n\nLemma cset0PN X : X != cset0 <-> X !=set0.\nProof.\nrewrite cset0P; case: X => //= x Hx; split; last first.\n  case=> a xa; apply/eqP => x0; move: xa; by rewrite x0.\nby case/set0P => /= d dx; exists d.\nQed.\n\nDefinition cset1 a : {convex_set A} := CSet.Pack (CSet.Mixin (is_convex_set1 a)).\n\nLemma cset1_neq0 a : cset1 a != cset0.\nProof. by apply/cset0PN; exists a. Qed.\n\nDefinition convex_set_of_segment (x y : A) : convex_set A :=\n  CSet.Pack (CSet.Mixin (segment_is_convex x y)).\n\nEnd CSet_prop.\n\n(* Lemmas on hull and convex set *)\n\nSection hull_is_convex.\nVariable A : convType.\n\nLemma hull_sub_convex (X : set A)(Y : {convex_set A}) :\n  (X `<=` Y -> hull X `<=` Y)%classic.\nProof.\nmove=> XY x [n [g [d [gX ->]]]].\nhave := convex_setP Y; rewrite is_convex_setP /is_convex_set_n.\nby move=> /asboolP/(_ _ g d (subset_trans gX XY)).\nQed.\n\nLemma hull_cset (X : {convex_set A}) : hull X = X.\nProof. by apply/seteqP; split; [exact/hull_sub_convex|exact/subset_hull]. Qed.\n\nLemma hull_is_convex (Z : set A) : is_convex_set (hull Z).\nProof.\napply/asboolP => x y p [n [g [d [gX ->{x}]]]] [m [h [e [hX ->{y}]]]].\nexists (n + m).\nexists [ffun i => match fintype.split i with inl a => g a | inr a => h a end].\nexists (fdist_add d e p).\nsplit.\n  move=> a -[i _]; rewrite ffunE.\n  by case: splitP => j _ <-; [apply gX; exists j | apply hX; exists j].\nby rewrite fdist_convn_add; congr (_ <| _ |> _); apply eq_Convn => i //=;\n  rewrite ffunE (split_lshift,split_rshift).\nQed.\n\nCanonical hull_is_convex_set (Z : set A) : convex_set A :=\n  CSet.Pack (CSet.Mixin (hull_is_convex Z)).\n\nLemma segment_hull (x y : A) : segment x y = hull [set x; y].\nProof.\nrewrite eqEsubset; split.\n  by have := hull_is_convex [set x; y] => /is_convex_segmentP/(_ x y); apply;\n    apply subset_hull; [left | right].\npose h := convex_set_of_segment x y.\nby have := @hull_sub_convex [set x; y] h; apply => z -[] ->;\n  [exact: segmentL|exact: segmentR].\nQed.\n\nEnd hull_is_convex.\n\nSection hull_convex_set.\nLocal Open Scope classical_set_scope.\nVariable A : convType.\nImplicit Types X Y Z : set A.\n\nLemma is_convex_hullE X : is_convex_set X = (hull X == X).\nProof.\napply/idP/idP => [conv|/eqP <-]; last exact: hull_is_convex.\nexact/eqP/(hull_cset {| CSet.car := X; CSet.class := CSet.Mixin conv |}).\nQed.\n\nLemma hull_eqEsubset X Y :\n  (X `<=` hull Y)%classic -> (Y `<=` hull X)%classic -> hull X = hull Y.\nProof.\nmove/hull_monotone; rewrite hull_cset /= => H1.\nmove/hull_monotone; rewrite hull_cset /= => H2.\nby rewrite eqEsubset.\nQed.\n\n(* hull (X `|` hull Y) = hull (hull (X `|` Y)) = hull (x `|` y);\n   the first equality looks like a tensorial strength under hull\n   Todo : Check why this is so. *)\nLemma hullU_strr X Y : hull (X `|` hull Y) = hull (X `|` Y).\nProof.\napply/hull_eqEsubset => a.\n- case; first by move=> ?; apply/subset_hull; left.\n  case=> n [d [g [H0 H1]]]; exists n, d, g; split => //.\n  apply (subset_trans H0) => ? ?; by right.\n- case => [?|?]; first by apply/subset_hull; left.\n  apply/subset_hull; right. exact/subset_hull.\nQed.\n\nLemma hullU_strl X Y : hull (hull X `|` Y) = hull (X `|` Y).\nProof. by rewrite [in LHS]setUC [in RHS]setUC hullU_strr. Qed.\n\nLemma hullUA X Y Z :\n  hull (X `|` hull (Y `|` Z)) = hull (hull (X `|` Y) `|` Z).\nProof. by rewrite hullU_strr hullU_strl setUA. Qed.\n\n(* NB: hullI exhibits a fundamental\n   algebraic property of hull, and since I expect there should be some\n   cases where inference of canonical structure does not work well for hulls\n   and a user needs to manually rewrite using such algebraic properties *)\nLemma hullI (X : set A) : hull (hull X) = hull X.\nProof.\nrewrite predeqE => d; split.\n- move=> -[n [g [e [gX ->{d}]]]].\n  move: (hull_is_convex X).\n  by rewrite is_convex_setP /is_convex_set_n => /asboolP/(_ _ g e gX).\n- by move/subset_hull.\nQed.\n\nEnd hull_convex_set.\n\nSection hull_setU.\nLocal Open Scope classical_set_scope.\nLocal Open Scope scaled_scope.\nVariable T : convType.\nImplicit Types Z : set T.\n\nDefinition scaled_set Z := [set x | if x is p *: a then Z a else True].\n\nLemma scalept_scaled_set Z r x :\n  x \\in scaled_set Z -> scalept r x \\in scaled_set Z.\nProof.\nrewrite /scalept/=.\nby case: Rlt_dec => //= Hr; [case: x | rewrite !in_setE].\nQed.\n\nLemma scaled_set_extract Z x (x0 : x != Zero) :\n  x \\in scaled_set Z -> [point of x0] \\in Z.\nProof. by case: x x0. Qed.\n\nLemma addpt_scaled_set (X : {convex_set T}) x y :\n  x \\in scaled_set X -> y \\in scaled_set X -> addpt x y \\in scaled_set X.\nProof.\ncase: x => [p x|]; case: y => [q y|] //=; exact: mem_convex_set.\nQed.\n\nLemma ssum_scaled_set n (P : pred 'I_n) (X : {convex_set T}) (d : {fdist 'I_n})\n  (g : 'I_n -> T) : (forall j, P j -> g j \\in X) ->\n  \\ssum_(i | P i) scalept (d i) (S1 (g i)) \\in scaled_set X.\nProof.\nmove=> PX; apply big_ind.\n- by rewrite in_setE.\n- exact: addpt_scaled_set.\n- by move=> i /PX => giX; exact: scalept_scaled_set.\nQed.\n\nLocal Open Scope reals_ext_scope.\n\nLemma hull_setU (z : T) (X Y : {convex_set T}) : X !=set0 -> Y !=set0 ->\n  hull (X `|` Y) z ->\n  exists2 x, x \\in X & exists2 y, y \\in Y & exists p, z = x <| p |> y.\nProof.\nmove=> [dx ?] [dy ?] [n -[g [d [gT zg]]]].\nsuff [a] : exists2 a, a \\in scaled_set X & exists2 b, b \\in scaled_set Y &\n    S1 z = addpt a b.\n  have [-> _ [b bY]|a0 aX [b]] := eqVneq a Zero.\n    rewrite add0pt => S1zy.\n    exists dx; rewrite ?in_setE //; exists z; last by exists 0%:pr; rewrite conv0.\n    by rewrite -(point_S1 z); apply: scaled_set_extract; rewrite S1zy.\n  have [-> _|b0 bY] := eqVneq b Zero.\n    rewrite addpt0 => S1zx.\n    exists z; last by exists dy; rewrite ?in_setE //; exists 1%:pr; rewrite conv1.\n    by rewrite -(point_S1 z); apply: scaled_set_extract; rewrite S1zx.\n  rewrite addptE => -[_ zxy].\n  exists [point of a0]; first exact: (@scaled_set_extract _ a).\n  exists [point of b0]; first exact: scaled_set_extract.\n  by eexists; rewrite zxy.\nmove/(congr1 (@S1 T)): zg; rewrite S1_Convn.\nrewrite (bigID (fun i => g i \\in X)) /=.\nset b := \\ssum_(i | _) _.\nset c := \\ssum_(i | _) _.\nmove=> zbc.\nexists b; first exact: ssum_scaled_set.\nexists c => //.\napply: (@ssum_scaled_set _ [pred i | g i \\notin X]) => i /=.\nmove/asboolP; rewrite in_setE.\nby case: (gT (g i) (imageP _ I)).\nQed.\n\nEnd hull_setU.\n\n(* TODO: move *)\nSection split_prod.\n\nLemma unsplit_prodp (m n : nat) (i : 'I_m) (j : 'I_n) : (i * n + j < m * n)%nat.\nProof.\nby rewrite -ltn_subRL -mulnBl (leq_trans (ltn_ord j))// leq_pmull// subn_gt0.\nQed.\n\nDefinition unsplit_prod (m n : nat) (i : 'I_m * 'I_n) : 'I_(m * n) :=\n  let (i, j) := i in Ordinal (unsplit_prodp i j).\n\nDefinition split_prodpl (m n : nat) (i : 'I_(m * n)): (i %/ n < m)%nat.\nProof. by move: n i => [|n i]; [rewrite muln0 => -[]|rewrite ltn_divLR]. Qed.\n\nDefinition split_prodpr (m n : nat) (i : 'I_(m * n)): (i %% n < n)%nat.\nProof. by move: n i => [|n i]; [rewrite muln0 => -[]|rewrite ltn_pmod]. Qed.\n\nDefinition split_prod (m n : nat) (i : 'I_(m * n)): 'I_m * 'I_n :=\n  (Ordinal (split_prodpl i), Ordinal (split_prodpr i)).\n\n(* TODO: find a suitable name *)\nLemma big_prod_ord [R' : Type] [idx : R'] (op : Monoid.com_law idx) [m n : nat]\n    (P : pred 'I_(m * n)) (F : 'I_(m * n) -> R') :\n  \\big[op/idx]_(i | P i) F i =\n  \\big[op/idx]_i \\big[op/idx]_(j | P (unsplit_prod (i, j))) F (unsplit_prod (i, j)).\nProof.\nelim: m =>[|m IHm] in P F *; first by rewrite 2!big_ord0.\nrewrite big_ord_recl big_split_ord; congr (op _ _).\n- apply congr_big => //=.\n    by move=> i/=; congr P; exact: val_inj.\n  by move=> i/= _; congr F; exact: val_inj.\n- rewrite IHm; apply eq_bigr => i _.\n  have e j : rshift n (unsplit_prod (i, j)) = Ordinal (unsplit_prodp (lift ord0 i) j).\n    by apply val_inj => /=; rewrite /bump leq0n addnA.\n  by apply: eq_big => // j; rewrite e.\nQed.\n\nLemma split_prodK n m : cancel (@split_prod n m) (@unsplit_prod n m).\nProof. by move=> i; apply val_inj => /=; rewrite -divn_eq. Qed.\n\nLemma unsplit_prodK n m : cancel (@unsplit_prod n m) (@split_prod n m).\nProof.\nmove: m => [[? [[]]]//|m [i j]]; congr (_, _); apply/val_inj => /=.\n- by rewrite divnMDl// divn_small// addn0.\n- by rewrite modnMDl modn_small.\nQed.\n\nEnd split_prod.\n\nSection lmodR_convex_space.\nVariable E : lmodType R.\nImplicit Type p q : prob.\nLocal Open Scope ring_scope.\nImport GRing.\n\nLet avg p (a b : E) := (Prob.p p) *: a + p.~ *: b.\n\nLet avg1 a b : avg 1%:pr a b = a.\nProof. by rewrite /avg /= scale1r onem1 scale0r addr0. Qed.\n\nLet avgI p x : avg p x x = x.\nProof.\nrewrite /avg -scalerDl.\nhave ->: (Prob.p p) + p.~ = Rplus (Prob.p p) p.~ by [].\nby rewrite onemKC scale1r.\nQed.\n\nLet avgC p x y : avg p x y = avg p.~%:pr y x.\nProof. by rewrite /avg onemK addrC. Qed.\n\nLet avgA p q (d0 d1 d2 : E) :\n  avg p d0 (avg q d1 d2) = avg [s_of p, q] (avg [r_of p, q] d0 d1) d2.\nProof.\nrewrite /avg /onem.\nset s := Prob.p [s_of p, q].\nset r := Prob.p [r_of p, q].\nrewrite (scalerDr s) -addrA (scalerA s) (mulrC s); congr add.\n  by rewrite (p_is_rs p q) -/s.\nrewrite scalerDr (scalerA _ _ d2).\nrewrite -/p.~ -/q.~ -/r.~ -/s.~.\nrewrite {2}/s (s_of_pqE p q) onemK; congr add.\nrewrite 2!scalerA; congr scale.\nhave ->: p.~ * q = (p.~ * q)%R by [].\nby rewrite pq_is_rs -/r -/s mulrC.\nQed.\n\nHB.instance Definition _ :=\n  @isConvexSpace.Build E (Choice.class _) avg avg1 avgI avgC avgA.\n\nLemma avgrE p (x y : E) : x <| p |> y = avg p x y. Proof. by []. Qed.\n\nEnd lmodR_convex_space.\n\nSection lmodR_convex_space_prop.\nVariable E : lmodType R.\nImplicit Type p q : prob.\nLocal Open Scope ring_scope.\nImport GRing.\n\nLemma avgr_addD p (a b c d : E) :\n  (a + b) <|p|> (c + d) = (a <|p|> c) + (b <|p|> d).\nProof.\nrewrite !avgrE !scalerDr !addrA; congr add; rewrite -!addrA; congr add.\nexact: addrC.\nQed.\n\nLemma avgr_oppD p (x y : E) : - x <| p |> - y = - (x <| p |> y).\nProof. by rewrite avgrE 2!scalerN -opprD. Qed.\n\nLemma avgr_scalerDr p : right_distributive *:%R (fun x y : E => x <| p |> y).\nProof.\nby move=> x ? ?; rewrite 2!avgrE scalerDr !scalerA; congr add; congr scale;\n  exact: mulrC.\nQed.\n\nLemma avgr_scalerDl p :\n  left_distributive *:%R (fun x y : regular_lmodType R_ringType => x <|p|> y).\nProof. by move=> x ? ?; rewrite avgrE scalerDl -2!scalerA. Qed.\n\n(* Introduce morphisms to prove avgnE *)\n\nDefinition scaler x : E := if x is (p *: y)%scaled then (Rpos.v p) *: y else 0.\n\nLemma Scaled1rK : cancel (@S1 (_ E)) scaler.\nProof. by move=> x /=; rewrite scale1r. Qed.\n\nLemma scaler_addpt : {morph scaler : x y / addpt x y >-> x + y}.\nProof.\nmove=> [p x|] [q y|] /=; rewrite ?(add0r,addr0) //.\nrewrite avgrE /divRposxxy /= onem_div /Rdiv; last by apply Rpos_neq0.\nrewrite -!(mulRC (/ _)%R) scalerDr !scalerA !mulrA.\nhave ->: (p + q)%R * (/ (p + q))%R = 1 by apply mulRV; last by apply Rpos_neq0.\nby rewrite !mul1r (addRC p) addRK.\nQed.\n\nLemma scaler0 : scaler Zero = 0. by []. Qed.\n\nLemma scaler_scalept r x : (0 <= r -> scaler (scalept r x) = r *: scaler x)%R.\nProof.\ncase: x => [q y|r0]; last by rewrite scalept0// GRing.scaler0.\ncase=> r0.\n  by rewrite scalept_gt0 /= scalerA.\nby rewrite -r0 scale0pt scale0r.\nQed.\n\nDefinition big_scaler := big_morph scaler scaler_addpt scaler0.\n\nDefinition avgnr n (g : 'I_n -> E) (e : {fdist 'I_n}) := \\sum_(i < n) e i *: g i.\n\nLemma avgnrE n (g : 'I_n -> E) e : <|>_e g = avgnr g e.\nProof.\nrewrite -[LHS]Scaled1rK S1_Convn big_scaler.\nby apply eq_bigr => i _; rewrite scaler_scalept // Scaled1rK.\nQed.\n\n(* TODO: Lemma preim_cancel: ... *)\n\nLemma avgnr_add n m (f : 'I_n -> E) (d : {fdist 'I_n}) (g : 'I_m -> E)\n    (e : {fdist 'I_m}) :\n  <|>_d f + <|>_e g = <|>_(fdistmap (@unsplit_prod n m) (d `x e))\n                           (fun i => let (i, j) := split_prod i in f i + g j).\nProof.\nrewrite -[<|>_e g]scale1r !avgnrE !/avgnr big_prod_ord.\nhave<-: 1%R = 1 by [].\nrewrite -(FDist.f1 d) scaler_suml -big_split; apply congr_big=>// i _.\ntransitivity (d i *: (1%R *: f i + \\sum_(i0 < m) e i0 *: g i0)).\n   by rewrite scale1r scalerDr.\nrewrite -(FDist.f1 e) scaler_suml -big_split scaler_sumr; apply congr_big=>// j _.\nrewrite scalerDr -!scalerDr scalerA unsplit_prodK; congr scale.\nrewrite fdistmapE (big_pred1 (i, j)) /= ?fdist_prodE//.\nmove=>[i' j'] /=; rewrite xpair_eqE inE /=.\napply/eqP/andP => /=; last by case => /eqP -> /eqP ->.\nmove=>/(congr1 (@split_prod n m))/=.\nby rewrite (unsplit_prodK (i, j)) (unsplit_prodK (i', j')) => -[-> ->].\nQed.\n\nEnd lmodR_convex_space_prop.\n\nSection freeN_combination.\nImport ssrnum vector.\nImport Order.POrderTheory Num.Theory.\nVariable (R : fieldType) (E : vectType R).\nLocal Open Scope ring_scope.\nLocal Open Scope classical_set_scope.\nImport GRing.\n\nLemma freeN_combination n (s : n.-tuple E) : ~~ free s ->\n  exists k : 'I_n -> R, (\\sum_i k i *: s`_i = 0) /\\ exists i, k i != 0.\nProof.\nrewrite freeNE => /existsP[[i ilt] /coord_span /=].\nmove: (ilt) s.\nhave ne : (n = i.+1 + (n - i.+1))%nat by rewrite subnKC.\nrewrite ne => ilt' s sin.\nhave hk m : (m < n - i.+1 -> m < i.+1 + (n - i.+1) - i.+1)%nat.\n  by move=> mni; rewrite -addnBAC// subnn add0n.\npose k (x : 'I_(i.+1 + (n - i.+1))) :=\n  match fintype.split x with\n  | inl (@Ordinal _ m _) => if m == i then 1 else 0\n  | inr (@Ordinal _ m i0) => - coord (drop_tuple i.+1 s) (Ordinal (hk m i0)) s`_i\n  end.\nexists k; split; last first.\n  exists (Ordinal ilt'); rewrite /k; case: splitP.\n    by case=> j ji/= <-; rewrite eqxx; exact/oner_neq0.\n  by case=> j jni/= /eqP; rewrite lt_eqF// ltEnat/= addSn ltnS leq_addr.\nrewrite big_split_ord big_ord_recr/= big1 ?add0r; last first.\n  case=> j ji _; rewrite /k; case: splitP.\n    by case=> m mi /= jm; rewrite -jm lt_eqF ?ltEnat// !scale0r.\n  by case=> m mni /= jim; move: ji; rewrite jim addSnnS -ltn_subRL subnn.\nrewrite {1}/k /=; case: splitP => /=; last first.\n  by move=> m /eqP; rewrite lt_eqF// ltEnat/= addSn ltnS leq_addr.\ncase=> j/= ji ij; rewrite [in j == i]ij eqxx scale1r.\napply/eqP; rewrite addrC addr_eq0 sin -sumrN; apply/eqP.\nhave {}ne : (i.+1 + (n - i.+1) - i.+1 = n - i.+1)%nat by rewrite -addnBAC// subnn.\nrewrite (index_enum_cast_ord ne) big_map; apply congr_big=>// [[x xlt]] _.\nrewrite nth_drop -scaleNr; congr (_ *: _).\nrewrite /k; case: splitP.\n  by case=> m + /= ixm; rewrite -ixm -ltn_subRL subnn.\ncase=> m/= mni /eqP; rewrite eqn_add2l => /eqP kl.\nby congr (- coord _ _ _); exact/val_inj.\nQed.\n\nEnd freeN_combination.\n\nSection caratheodory.\nImport ssrnum vector.\nImport Order.POrderTheory Num.Theory.\nVariable E : vectType R.\nLocal Open Scope ring_scope.\nLocal Open Scope classical_set_scope.\nImport GRing.\n\n(* TODO: move? *)\nImport Order.TotalTheory.\n\nLemma caratheodory (A : set (Vector.lmodType E)) x : x \\in hull A ->\n  exists (n : nat) (g : 'I_n -> Vector.lmodType E) (d : {fdist 'I_n}),\n    [/\\ (n <= (dimv (@fullv R_fieldType E)).+1)%nat, range g `<=` A & x = <|>_d g].\nProof.\nmove=> /set_mem[n [g [d [gA ->]]]].\nelim: n => [|n IHn] in g d gA *; first by case: (fdistI0_False d).\nhave [nsgt|nsgt] := leqP n (dimv (@fullv R_fieldType E)).\n   by exists n.+1, g, d.\nhave [mu [muR muE [i mui]]] : exists mu : 'I_n.+1 -> R,\n  [/\\ \\sum_(i < n.+1) mu i = 0, \\sum_(i < n.+1) (mu i) *: g i = 0 &\n     exists i, mu i != 0 ].\n  rewrite {IHn}.\n  have [sf|/freeN_combination[mu [musum [i mui]]]] :=\n      boolP (free [tuple g (lift ord0 i) - g ord0 | i < n]).\n    have : basis_of fullv [tuple g (lift ord0 i) - g ord0 | i < n].\n      by rewrite basisEfree size_tuple (ltnW nsgt) andbT sf subvf.\n    rewrite in_tupleE basisEdim size_map => /andP[_].\n    by move=> /leq_ltn_trans => /(_ _ nsgt); rewrite size_tuple ltnn.\n  exists (fun i => if i is @Ordinal _ i.+1 ilt then mu (Ordinal (ltnSE ilt)) else - \\sum_i mu i); split.\n  - rewrite big_ord_recl /= addrC; apply/eqP; rewrite subr_eq0; apply/eqP.\n    by apply: eq_bigr => j _; congr mu; exact/val_inj.\n  - rewrite big_ord_recl /= scaleNr addrC scaler_suml -sumrB -{2}musum.\n    apply: eq_bigr => j _; rewrite (nth_map j) ?size_tuple//.\n    rewrite scalerBr; congr (mu _ *: g _ - _); apply/val_inj => //=.\n    by rewrite nth_ord_enum.\n  - by exists (lift ord0 i) => /=; rewrite (_ : Ordinal _ = i)//; exact/val_inj.\nwlog: mu muR muE mui / mu i > 0.\n   move=> H.\n   have [mui0|mui0] := ltP 0%R (mu i); first exact: (H mu).\n   apply (H (fun i => - mu i)).\n   - by rewrite sumrN muR oppr0.\n   - by under eq_bigr do rewrite scaleNr; rewrite sumrN muE oppr0.\n   + by rewrite oppr_eq0.\n   + by rewrite oppr_gt0 lt_neqAle mui.\nmove=>/(@arg_minP _ _ _ i (fun i => 0 < mu i) (fun i => d i / mu i)) [im muip muim] {i mui}.\nwlog: g d gA mu muR muE im muip muim / (im == ord0)%N.\n   set f := fun i : nat => if i == im :> nat then 0%nat else if i == 0%nat then nat_of_ord im else i.\n   have fcan : cancel f f.\n     move=> m; rewrite /f; have [->|mim] := eqVneq m im.\n       by rewrite eqxx; case: ifPn => // /eqP.\n     have [->|m0] := eqVneq m 0%N; first by rewrite eqxx.\n     by rewrite (negbTE mim) (negbTE m0).\n   have flt (i : 'I_n.+1) : (f i < n.+1)%nat.\n     by rewrite /f; case: ifPn => // iim; case: ifPn.\n   set f' := fun i => Ordinal (flt i).\n   have fcan' : cancel f' f' by move=> [j jlt]; exact/val_inj/fcan.\n   have fbij : bijective f' by exists f'; move=> [j jlt]; exact/fcan'.\n   move=>/(_ (fun i => g (f' i)) (fdistmap f' d)).\n   have gA' : [set g (f' i) | i in [set: 'I_n.+1]] `<=` A.\n     by move=>y [i _ <-]; apply gA; eexists.\n   move=>/(_ gA' (fun i => mu (f' i))).\n   have mu'R : \\sum_(i0 < n.+1) mu (f' i0) = 0.\n     rewrite (perm_big _ (perm_map_bij _ fbij)); [| exact nil ].\n     by rewrite big_map -{4}muR; apply congr_big=>// [[j jlt]] _; congr mu; apply fcan'.\n   move=>/(_ mu'R).\n   have mu'E: \\sum_(i0 < n.+1) mu (f' i0) *: g (f' i0) = 0.\n      rewrite (perm_big _ (perm_map_bij _ fbij)); [| exact nil ].\n      rewrite big_map -{4}muE; apply congr_big=>// j _.\n      by congr (mu _ *: g _); exact/fcan'.\n   move=>/(_ mu'E (f' im)).\n   have muip' : 0 < mu (f' (f' im)) by rewrite fcan'.\n   move=>/(_ muip').\n   have muim' (j : ordinal_finType n.+1) :\n     0 < mu (f' j) ->\n     fdistmap f' d (f' im) / mu (f' (f' im)) <= fdistmap f' d j / mu (f' j).\n     move=> /muim.\n     rewrite fcan' fdistmapE (big_pred1 im) /=; last first.\n       move=> i; apply/idP/idP; rewrite !inE; last by move=> /eqP ->.\n       by move=> /eqP /(bij_inj fbij) /eqP.\n     rewrite fdistmapE (big_pred1 (f' j)) //.\n     by move=> /= i; apply/idP/idP; rewrite !inE => /eqP;\n       [move=> <-; rewrite fcan' | move=> ->; rewrite fcan'].\n   move=>/(_ muim').\n   have im0 : f' im == ord0 by apply/eqP/val_inj => /=; rewrite /f eqxx.\n   move=>/(_ im0) [n' [g' [d' [n'le g'A e]]]].\n   exists n', g', d'; split=>//; rewrite -e.\n   rewrite 2!avgnrE /avgnr.\n   rewrite (perm_big _ (perm_map_bij _ fbij)); [| exact nil ].\n   rewrite big_map; apply congr_big=>// j _.\n   rewrite fdistmapE (big_pred1 (f' j))=>// k /=.\n   by rewrite unfold_in=>/=; apply/eqP/eqP=>e'; apply (bij_inj fbij); rewrite fcan'.\nmove=>/eqP ime; move: muip muim; rewrite {im}ime => muip muim.\nhave mu0 : mu ord0 != 0 by apply /eqP=>mu0; move: muip; rewrite mu0 lt0r eq_refl.\nhave k0mu0 : d ord0 / mu ord0 * mu ord0 = d ord0.\n  by rewrite -{2}[mu ord0]divr1 mulf_div [_*1]mulrC -mulf_div divr1 mulfV // mulr1.\nset ef : 'I_n -> R := finfun (fun i => d (lift ord0 i) - d ord0 / mu ord0 * mu (lift ord0 i)).\nhave ef0 i : (0 <= ef i)%R.\n   apply/RleP; rewrite /ef ffunE subr_ge0.\n   have [mujp|mujp] := ltP 0 (mu (lift ord0 i)).\n      by rewrite -ler_pdivl_mulr // muim.\n   rewrite (@le_trans _ _ 0)//; last exact/leRP.\n   by rewrite mulr_ge0_le0//= divr_ge0//; [exact/leRP|exact/ltW].\nhave ef1 : (\\sum_(a in 'I_n) ef a = 1)%R.\n  rewrite -[1%R]subr0 -(mulr0 (d ord0 / mu ord0)) -(FDist.f1 d) -muR mulr_sumr.\n  rewrite -sumrB big_ord_recl k0mu0 subrr add0r.\n  by apply eq_bigr => i _; rewrite /ef ffunE.\npose e := FDist.make ef0 ef1.\nhave /IHn - /(_ e): [set g (lift ord0 i) | i in [set: 'I_n]] `<=` A.\n  by move=>y [i _ <-]; exact/gA.\nmove=> -[n' [g' [d' [n'le g'A' gde]]]].\nexists n', g', d'; split=> //.\nrewrite -gde 2!avgnrE /avgnr big_ord_recl -k0mu0 -scalerA.\nmove/eqP: muE; rewrite big_ord_recl addr_eq0 => /eqP ->.\nrewrite scalerN -scaleNr scaler_sumr -big_split; apply congr_big=>// i _.\nby rewrite scalerA /= -scalerDl; congr scale; rewrite addrC mulNr ffunE.\nQed.\n\nEnd caratheodory.\n\nSection linear_affine.\nOpen Scope ring_scope.\nVariables (E F : lmodType R) (f : {linear E -> F}).\nImport GRing.\n\nLet linear_is_affine: affine f.\nProof. by move=>p x y; rewrite linearD 2!linearZZ. Qed.\n\nHB.instance Definition _ := isAffine.Build _ _ _ linear_is_affine.\n\nEnd linear_affine.\n\n(* TOTHINK: Should we keep this section, only define R_convType, or something else ? *)\nSection R_convex_space.\nImplicit Types p q : prob.\n\nLet avg p (a b : [the lmodType R of R^o]) := a <| p |> b.\n\nLet avgE p a b : avg p a b = (p * a + p.~ * b)%R.\nProof. by []. Qed.\n\nLet avg1 a b : avg 1%:pr a b = a. Proof. by rewrite /avg conv1. Qed.\n\nLet avgI p x : avg p x x = x. Proof. by rewrite /avg convmm. Qed.\n\nLet avgC p x y : avg p x y = avg p.~%:pr y x. Proof. by rewrite /avg convC. Qed.\n\nLet avgA p q (d0 d1 d2 : R) :\n  avg p d0 (avg q d1 d2) = avg [s_of p, q] (avg [r_of p, q] d0 d1) d2.\nProof. by rewrite /avg convA. Qed.\n\nHB.instance Definition _ := @isConvexSpace.Build R\n  (Choice.class _) _ avg1 avgI avgC avgA.\n\nLemma avgRE p (x y : R) : x <| p |> y = (p * x + p.~ * y)%R. Proof. by []. Qed.\n\nLemma avgR_oppD p x y : (- x <| p |> - y = - (x <| p |> y))%R.\nProof. exact: (@avgr_oppD [lmodType R of R^o]). Qed.\n\nLemma avgR_mulDr p : right_distributive Rmult (fun x y => x <| p |> y).\nProof. exact: (@avgr_scalerDr [lmodType R of R^o]). Qed.\n\nLemma avgR_mulDl p : left_distributive Rmult (fun x y => x <| p |> y).\nProof. exact: @avgr_scalerDl. Qed.\n\n(* Introduce morphisms to prove avgnE *)\n\nDefinition scaleR x : R := if x is (p *: y)%scaled then p * y else 0.\n\nLemma Scaled1RK : cancel (@S1 _) scaleR.\nProof. by move=> x /=; rewrite mul1R. Qed.\n\nLemma scaleR_addpt : {morph scaleR : x y / addpt x y >-> (x + y)%R}.\nProof.\nmove=> [p x|] [q y|] /=; rewrite ?(add0R,addR0) //.\nrewrite avgRE /avg /divRposxxy /= onem_div /Rdiv; last by apply Rpos_neq0.\nrewrite -!(mulRC (/ _)%R) mulRDr !mulRA mulRV; last by apply Rpos_neq0.\nby rewrite !mul1R (addRC p) addRK.\nQed.\n\nLemma scaleR0 : scaleR Zero = R0. by []. Qed.\n\nLemma scaleR_scalept r x : (0 <= r -> scaleR (scalept r x) = r * scaleR x)%R.\nProof.\ncase: x => [q y|r0]; last by rewrite scalept0// mulR0.\ncase=> r0. by rewrite scalept_gt0 /= mulRA.\nby rewrite -r0 scale0pt mul0R.\nQed.\n\nDefinition big_scaleR := big_morph scaleR scaleR_addpt scaleR0.\n\nDefinition avgnR n (g : 'I_n -> R) (e : {fdist 'I_n}) := (\\sum_(i < n) e i * g i)%R.\n\nLemma avgnRE n (g : 'I_n -> R) e : <|>_e g = avgnR g e.\nProof.\nrewrite -[LHS]Scaled1RK S1_Convn big_scaleR.\nby apply eq_bigr => i _; rewrite scaleR_scalept // Scaled1RK.\nQed.\n\nEnd R_convex_space.\n\nSection fun_convex_space.\nVariables (A : choiceType) (B : convType).\nLet T := A -> B.\nImplicit Types p q : prob.\nLet avg p (x y : T) := fun a : A => (x a <| p |> y a).\nLet avg1 (x y : T) : avg 1%:pr x y = x.\nProof. rewrite funeqE => a; exact/conv1. Qed.\nLet avgI p (x : T) : avg p x x = x.\nProof. rewrite funeqE => a; exact/convmm. Qed.\nLet avgC p (x y : T) : avg p x y = avg p.~%:pr y x.\nProof. rewrite funeqE => a; exact/convC. Qed.\nLet avgA p q (d0 d1 d2 : T) :\n  avg p d0 (avg q d1 d2) = avg [s_of p, q] (avg [r_of p, q] d0 d1) d2.\nProof. move=> *; rewrite funeqE => a; exact/convA. Qed.\nHB.instance Definition _ := @isConvexSpace.Build T (Choice.class _) _\n  avg1 avgI avgC avgA.\nEnd fun_convex_space.\n\nSection depfun_convex_space.\nVariables (A : choiceType) (B : A -> convType).\nLet T := dep_arrow_choiceType B.\nImplicit Types p q : prob.\nLet avg p (x y : T) := fun a : A => (x a <| p |> y a).\nLet avg1 (x y : T) : avg 1%:pr x y = x.\nProof.\napply FunctionalExtensionality.functional_extensionality_dep => a.\nexact/conv1.\nQed.\nLet avgI p (x : T) : avg p x x = x.\nProof.\napply FunctionalExtensionality.functional_extensionality_dep => a.\nexact/convmm.\nQed.\nLet avgC p (x y : T) : avg p x y = avg p.~%:pr y x.\nProof.\napply FunctionalExtensionality.functional_extensionality_dep => a.\nexact/convC.\nQed.\nLet avgA p q (d0 d1 d2 : T) :\n  avg p d0 (avg q d1 d2) = avg [s_of p, q] (avg [r_of p, q] d0 d1) d2.\nProof.\nmove => *.\napply FunctionalExtensionality.functional_extensionality_dep => a.\nexact/convA.\nQed.\nHB.instance Definition _ := @isConvexSpace.Build _ (Choice.class _)\n  _ avg1 avgI avgC avgA.\nEnd depfun_convex_space.\n\nSection pair_convex_space.\nVariables (A B : convType).\nLet T := (A * B)%type.\nImplicit Types p q : prob.\nLet avg p (x y : T) := (x.1 <| p |> y.1, x.2 <| p |> y.2).\nLet avg1 (x y : T) : avg 1%:pr x y = x.\nProof. rewrite /avg (conv1 x.1) (conv1 x.2); by case x. Qed.\nLet avgI p (x : T) : avg p x x = x.\nProof. rewrite /avg (convmm _ x.1) (convmm _ x.2); by case x. Qed.\nLet avgC p (x y : T) : avg p x y = avg p.~%:pr y x.\nProof. by congr (pair _ _); apply convC. Qed.\nLet avgA p q (d0 d1 d2 : T) :\n  avg p d0 (avg q d1 d2) = avg [s_of p, q] (avg [r_of p, q] d0 d1) d2.\nProof. move => *; congr (pair _ _); by apply convA. Qed.\n\nHB.instance Definition _ :=\n  @isConvexSpace.Build T (Choice.class _) avg avg1 avgI avgC avgA.\n\nEnd pair_convex_space.\n\nSection fdist_convex_space.\nVariable A : finType.\nImplicit Types a b c : fdist A.\n\nLet conv1 a b : (a <| 1%:pr |> b)%fdist = a.\nProof.\nby apply/fdist_ext => a0; rewrite fdist_convE /= onem1 mul1R mul0R addR0.\nQed.\n\nLet convC p a b : (a <| p |> b = b <| p.~%:pr |> a)%fdist.\nProof. by apply/fdist_ext => a0 /=; rewrite 2!fdist_convE onemK addRC. Qed.\n\nLet convmm p a : (a <| p |> a)%fdist = a.\nProof.\nby apply/fdist_ext => a0; rewrite fdist_convE mulRBl mul1R addRCA addRN addR0.\nQed.\n\nLet convA p q a b c :\n  (a <| p |> (b <| q |> c) = (a <| [r_of p, q] |> b) <| [s_of p, q] |> c)%fdist.\nProof.\napply/fdist_ext => a0 /=; rewrite 4!fdist_convE /=.\nset r := r_of_pq p q.  set s := s_of_pq p q.\ntransitivity (p * a a0 + p.~ * q * b a0 + p.~ * q.~ * c a0)%R; first lra.\ntransitivity (r * s * a a0 + r.~ * s * b a0 + s.~ * c a0)%R; last first.\n  by rewrite 2!(mulRC _ s) -2!mulRA -mulRDr.\nrewrite s_of_pqE onemK; congr (_ + _)%R.\nrewrite (_ : (p.~ * q.~).~ = [s_of p, q]); last by rewrite s_of_pqE.\nby rewrite -pq_is_rs -p_is_rs.\nQed.\n\nHB.instance Definition _  := @isConvexSpace.Build (fdist A)\n  (Choice.class (choice_of_Type (fdist A)))\n  (@fdist_conv A) conv1 convmm convC convA.\nEnd fdist_convex_space.\n\nSection scaled_convex_lemmas_depending_on_T_convType.\nLocal Open Scope R_scope.\n\nLemma scalept_conv (T : convType) (x y : R) (s : scaled T) (p : prob):\n  0 <= x -> 0 <= y ->\n  scalept (x <|p|> y) s = scalept x s <|p|> scalept y s.\nProof.\nmove=> x0 y0; rewrite scaleptDl; [|exact/mulR_ge0|exact/mulR_ge0].\nby rewrite convptE !scaleptA.\nQed.\n\nLemma big_scalept_conv_split (T : convType) (I : Type) (r : seq I) (P : pred I)\n  (F G : I -> scaled T) (p : prob) :\n    \\ssum_(i <- r | P i) (F i <|p|> G i) =\n    (\\ssum_(i <- r | P i) F i) <|p|> \\ssum_(i <- r | P i) G i.\nProof.\nrewrite convptE big_split /=.\nby do 2 rewrite [in RHS]big_morph_scalept ?scalept0//.\nQed.\n\nLemma scalept_addRnng (T : convType) (x : scaled T) :\n  {morph (fun (r : Rnng) => scalept r x) : r s / addRnneg r s >-> addpt r s}.\nProof. by move=> -[] r /= /leRP Hr [] s /= /leRP Hs; exact: scaleptDl. Qed.\n\nDefinition big_scaleptl (T : convType) (x : scaled T) :=\n  @big_morph\n    (@scaled T)\n    Rnng\n    (fun r : Rnng => scalept r x)\n    Zero\n    (@addpt [the realCone of scaled T])\n    Rnng0\n    addRnneg\n    (@scalept_addRnng T x).\n\nLemma big_scaleptl' (T : convType) (x : scaled T) :\n  scalept R0 x = Zero ->\n  forall (I : Type) (r : seq I) (P : pred I) (F : I -> R),\n    (forall i : I, 0 <= F i) ->\n    scalept (\\sum_(i <- r | P i) F i) x = \\ssum_(i <- r | P i) scalept (F i) x.\nProof.\nmove=> H I r P F H'.\ntransitivity (\\ssum_(i <- r | P i) (fun r0 : Rnng => scalept r0 x) (mkRnng (H' i))); last reflexivity.\nrewrite -big_scaleptl ?scalept0 //.\ncongr scalept.\ntransitivity (\\sum_(i <- r | P i) mkRnng (H' i)); first reflexivity.\napply (big_ind2 (fun x y => x = (Rnng.v y))) => //.\nby move=> x1 [v Hv] y1 y2 -> ->.\nQed.\n\nEnd scaled_convex_lemmas_depending_on_T_convType.\n\nModule Convn_finType.\nSection def.\nLocal Open Scope R_scope.\nVariables (A : convType) (T : finType) (d' : {fdist T}) (f : T -> A).\nLet n := #| T |.\n\nDefinition t0 : T.\nProof.\nmove/card_gt0P/xchoose: (fdist_card_neq0 d') => t0; exact t0.\nDefined.\n\nLet enum : 'I_n -> T := enum_val.\n\nDefinition d_enum := [ffun i => d' (enum i)].\n\nLemma d_enum0 : forall b, 0 <= d_enum b. Proof. by move=> ?; rewrite ffunE. Qed.\n\nLemma d_enum1 : \\sum_(b in 'I_n) d_enum b = 1.\nProof.\nrewrite -(@FDist.f1 T d') (eq_bigr (d' \\o enum)); last by move=> i _; rewrite ffunE.\nrewrite (@reindex _ _ _ _ _ enum_rank) //; last first.\n  by exists enum_val => i; [rewrite enum_rankK | rewrite enum_valK].\napply eq_bigr => i _; congr (d' _); by rewrite -[in RHS](enum_rankK i).\nQed.\n\nDefinition d : {fdist 'I_n} := FDist.make d_enum0 d_enum1.\n\nDefinition Convn_finType : A := <|>_d (f \\o enum).\n\nEnd def.\nModule Exports.\nNotation \"'<$>_' d f\" := (Convn_finType d f) : convex_scope.\nEnd Exports.\nEnd Convn_finType.\nExport Convn_finType.Exports.\n\nSection S1_Convn_finType.\nVariables (A : convType) (T : finType) (d : {fdist T}) (f : T -> A).\n\nLemma S1_Convn_finType : S1 (<$>_d f) = \\ssum_i scalept (d i) (S1 (f i)).\nProof.\nrewrite /Convn_finType.Convn_finType S1_Convn /=.\nrewrite (reindex_onto enum_rank enum_val) /=; last by move=> i _; rewrite enum_valK.\napply eq_big => /=; first by move=> i; rewrite enum_rankK eqxx.\nmove=> i _; rewrite /Convn_finType.d_enum ffunE.\nby rewrite enum_rankK.\nQed.\n\nEnd S1_Convn_finType.\n\nSection S1_proj_Convn_finType.\nVariables (A B : convType) (prj : {affine A -> B}).\nVariables (T : finType) (d : {fdist T}) (f : T -> A).\n\nLemma S1_proj_Convn_finType :\n  S1 (prj (<$>_d f)) = \\ssum_i scalept (d i) (S1 (prj (f i))).\nProof. by rewrite Convn_comp; exact: S1_Convn_finType. Qed.\n\nEnd S1_proj_Convn_finType.\n\nHB.mixin Record isOrdered (T : Type) := {\n  orderedchoiceclass : Choice.class_of T ;\n  leconv : T -> T -> Prop ;\n  leconvR : forall a, leconv a a;\n  leconv_trans : forall b a c, leconv a b -> leconv b c -> leconv a c ;\n  eqconv_le : forall a b, a = b <-> leconv a b /\\ leconv b a }.\n\n#[short(type=orderedConvType)]\nHB.structure Definition OrderedConvexSpace := {T of isOrdered T & ConvexSpace T}.\n\nCanonical ordered_eqType (T : orderedConvType) := EqType T orderedchoiceclass.\nCanonical ordered_choiceType (T : orderedConvType) :=\n  ChoiceType T orderedchoiceclass.\n\nArguments leconv_trans {s b a c}.\n\nNotation \"x <= y\" := (leconv x y) : ordered_convex_scope.\nNotation \"x <= y <= z\" := (leconv x y /\\ leconv y z) : ordered_convex_scope.\n\nHB.instance Definition _ :=\n  @isOrdered.Build R (Choice.class _) Rle leRR leR_trans eqR_le.\n\nModule FunLe.\nSection lefun.\nLocal Open Scope ordered_convex_scope.\nVariables (T : convType) (U : orderedConvType).\n\nDefinition lefun (f g : T -> U) := forall a, f a <= g a.\n\nLemma lefunR f : lefun f f.\nProof. move => *; exact: leconvR. Qed.\n\nLemma lefun_trans g f h : lefun f g -> lefun g h -> lefun f h.\nProof. move => Hfg Hgh a; move : (Hfg a) (Hgh a); exact: leconv_trans. Qed.\n\nLemma eqfun_le f g : f = g <-> lefun f g /\\ lefun g f.\nProof.\nsplit; [move ->; by move: lefunR |].\ncase=> Hfg Hgh; rewrite funeqE => a.\nmove : (Hfg a) (Hgh a) => Hfg' Hgh'; exact/eqconv_le.\nQed.\n\nEnd lefun.\nEnd FunLe.\n\nSection fun_ordered_convex_space.\nVariables (T : convType) (U : orderedConvType).\nImport FunLe.\n\nHB.instance Definition _ := @isOrdered.Build (T -> U)\n  (Choice.class _) (@lefun T U) (@lefunR T U) (@lefun_trans T U) (@eqfun_le T U).\n\nEnd fun_ordered_convex_space.\n\nModule OppositeOrderedConvexSpace.\nSection def.\nVariable A : orderedConvType.\n\nCoInductive T := mkOpp : A -> T.\n\nLemma A_of_TK : cancel (fun t => let: mkOpp a := t in a) mkOpp.\nProof. by case. Qed.\n\nDefinition A_of_T_eqMixin := CanEqMixin A_of_TK.\n\nCanonical A_of_T_eqType := Eval hnf in EqType T A_of_T_eqMixin.\n\nDefinition A_of_T_choiceMixin := CanChoiceMixin A_of_TK.\n\nCanonical A_of_T_choiceType := Eval hnf in ChoiceType T A_of_T_choiceMixin.\nEnd def.\n\nSection leopp.\nLocal Open Scope ordered_convex_scope.\nVariable A : orderedConvType.\nNotation T := (T A).\nDefinition leopp (x y : T) :=\n  match (x, y) with (mkOpp x', mkOpp y') => y' <= x' end.\n\nLemma leoppR x : leopp x x.\nProof. case x; exact: leconvR. Qed.\n\nLemma leopp_trans y x z : leopp x y -> leopp y z -> leopp x z.\nProof. by move: x y z => [x] [y] [z] ? yz; apply: (leconv_trans yz). Qed.\n\nLemma eqopp_le x y : x = y <-> leopp x y /\\ leopp y x.\nProof.\nby split; [move ->; move: leoppR |move: x y => [x'] [y'] => /eqconv_le ->].\nQed.\n\nEnd leopp.\n\nSection convtype.\nLocal Open Scope convex_scope.\nVariable A : orderedConvType.\nNotation T := (T A).\nImplicit Types p q : prob.\n\nDefinition unbox (x : T) := match x with mkOpp x' => x' end.\n\nDefinition avg p a b := mkOpp (unbox a <| p |> unbox b).\n\nLemma avg1 a b : avg 1%:pr a b = a.\nProof. by case a;case b=>b' a';rewrite/avg/unbox/=conv1. Qed.\n\nLemma avgI p x : avg p x x = x.\nProof. by case x=>x';rewrite/avg/unbox/=convmm. Qed.\n\nLemma avgC p x y : avg p x y = avg p.~%:pr y x.\nProof. by case x;case y=>y' x'; rewrite/avg/unbox/=convC. Qed.\n\nLemma avgA p q d0 d1 d2 :\n  avg p d0 (avg q d1 d2) = avg [s_of p, q] (avg [r_of p, q] d0 d1) d2.\nProof. by case d0;case d1;case d2=>d2' d1' d0';rewrite/avg/unbox/=convA. Qed.\n\n#[export]\nHB.instance Definition _ := @isConvexSpace.Build T (Choice.class _) _\n  avg1 avgI avgC avgA.\n\nEnd convtype.\nEnd OppositeOrderedConvexSpace.\nHB.export OppositeOrderedConvexSpace.\n\nSection opposite_ordered_convex_space.\nImport OppositeOrderedConvexSpace.\nVariable A : orderedConvType.\n\nHB.instance Definition _ := @isOrdered.Build (T A)\n  (Choice.class _) (@leopp A) (@leoppR A) (@leopp_trans A) (@eqopp_le A).\n\nEnd opposite_ordered_convex_space.\n\nNotation \"'\\opp{' a '}'\" := (OppositeOrderedConvexSpace.mkOpp a)\n  (at level 10, format \"\\opp{ a }\") : ordered_convex_scope.\n\nSection opposite_ordered_convex_space_prop.\nLocal Open Scope ordered_convex_scope.\nImport OppositeOrderedConvexSpace.\nVariable A : orderedConvType.\n\nLemma conv_leoppD (a b : A) t : \\opp{a} <|t|> \\opp{b} = \\opp{a <|t|> b}.\nProof. by []. Qed.\n\nLemma unboxK (a : A) : unbox (\\opp{a}) = a.\nProof. reflexivity. Qed.\n\nLemma leoppP (a b : T A) : a <= b <-> unbox b <= unbox a.\nProof. by case a;case b=>*;rewrite !unboxK. Qed.\n\nEnd opposite_ordered_convex_space_prop.\n\nSection convex_function_def.\nLocal Open Scope ordered_convex_scope.\nVariables (T : convType) (U : orderedConvType).\nImplicit Types f : T -> U.\n\nDefinition convex_function_at f a b p := f (a <| p |> b) <= f a <| p |> f b.\n\n(* NB(rei): move from 'I_n -> A to 'rV[A]_n? *)\nDefinition convex_function_at_Convn f n (a : 'I_n -> T) (d : {fdist 'I_n}) :=\n  f (<|>_d a) <= <|>_d (f \\o a).\n\nDefinition strictly_convexf_at f := forall a b (t : prob),\n  a <> b -> (0 < t < 1)%R -> convex_function_at f a b t.\n\nLemma convex_function_atxx f a t : convex_function_at f a a t.\nProof. rewrite /convex_function_at !convmm; exact/leconvR. Qed.\n\nEnd convex_function_def.\n\nDefinition convex_function (U : convType) (V : orderedConvType) (f : U -> V) :=\n forall a b (t : prob), convex_function_at f a b t.\n\n(* see Additive in ssralg *)\nHB.mixin Record isConvexFunction\n    (U : convType) (V : orderedConvType) (f : U -> V) := {\n  convex_functionP : convex_function f }.\n\nHB.structure Definition ConvexFunction (U : convType) (V : orderedConvType) :=\n  { f of isConvexFunction U V f }.\n\nArguments convex_functionP {U V} s.\n\nNotation \"{ 'convex' T '->' R }\" :=\n  (ConvexFunction.type T R) (at level 36, T, R at next level,\n    format \"{ 'convex'  T  '->'  R }\") : convex_scope.\n\nSection convex_function_prop'.\nLocal Open Scope ordered_convex_scope.\nVariable (T : convType) (U V : orderedConvType).\n\nLemma convex_function_sym (f : T -> U) a b :\n  (forall t, convex_function_at f a b t) ->\n  (forall t, convex_function_at f b a t).\nProof.\nmove=> H t; move: (H t.~%:pr).\nby rewrite /convex_function_at /= convC -probK (convC _ (f a)) -probK.\nQed.\n\nLemma convex_function_comp (f : {convex T -> U}) (g : {convex U -> V}) :\n  (forall a b t, f (a <|t|> b) <= f a <|t|> f b ->\n                 g (f (a <|t|> b)) <= g (f a <|t|> f b)) ->\n  convex_function (g \\o f).\nProof.\nmove=> fg a b t; have := convex_functionP g (f a) (f b) t.\nby move=> Hg; apply/(leconv_trans _ Hg)/fg/convex_functionP.\nQed.\n\nLemma convex_function_comp' (f : {convex T -> U}) (g : {convex U -> V})\n    (g_monotone : forall x y, x <= y -> g x <= g y) :\n  convex_function (g \\o f).\nProof. by apply convex_function_comp => // *; exact: g_monotone. Qed.\n\nEnd convex_function_prop'.\n\nSection convex_in_both.\nLocal Open Scope ordered_convex_scope.\nVariables (T U : convType) (V : orderedConvType) (f : T -> U -> V).\n\nDefinition convex_in_both := convex_function (uncurry f).\n\nLemma convex_in_bothP : convex_in_both <->\n  forall a0 a1 b0 b1 t,\n    f (a0 <| t |> a1) (b0 <| t |> b1) <= f a0 b0 <| t |> f a1 b1.\nProof.\nsplit => [H a0 a1 b0 b1 t | H];\n  first by move: (H (a0,b0) (a1,b1) t); rewrite /convex_function_at /uncurry.\nby case => a0 b0 [a1 b1] t; move:(H a0 a1 b0 b1 t).\nQed.\n\nEnd convex_in_both.\n\nSection biconvex_function.\nLocal Open Scope ordered_convex_scope.\n\nSection definition.\nVariables (T U : convType) (V : orderedConvType) (f : T -> U -> V).\nDefinition biconvex_function :=\n  (forall a, convex_function (f a)) /\\ (forall b, convex_function (f^~ b)).\n(*\nLemma biconvex_functionP : biconvex_function <->\n  convex_function f /\\ @convex_function B (fun_orderedConvType A C) (fun b a => f a b).\nProof.\nchange ((forall (a : A) (a0 b : B) (t : prob),\n   f a (a0 <|t|> b) <= f a a0 <|t|> f a b) /\\\n  (forall (b : B) (a b0 : A) (t : prob),\n   f (a <|t|> b0) b <= f a b <|t|> f b0 b) <->\n  (forall (a b : A) (t : prob) (a0 : B),\n   f (a <|t|> b) a0 <= f a a0 <|t|> f b a0) /\\\n  (forall (a b : B) (t : prob) (a0 : A),\n   f a0 (a <|t|> b) <= f a0 a <|t|> f a0 b)).\nby split; case => [H0 H1]; split => *; try apply H0; try apply H1.\nQed.\n *)\nEnd definition.\n\nSection counterexample.\nLocal Open Scope R_scope.\n\nExample biconvex_is_not_convex_in_both :\n  exists f : R -> R -> R, biconvex_function f /\\ ~ convex_in_both f.\nProof.\nexists Rmult; split.\n  by split => [a b0 b1 t | b a0 a1 t];\n    rewrite /convex_function_at /=; rewrite avgRE;\n    [rewrite avgR_mulDr|rewrite avgR_mulDl]; exact: leRR.\nmove/convex_in_bothP/(_ (-1)%R 1%R 1%R (-1)%R (probinvn 1)).\nrewrite /leconv /probinvn /= 3!avgRE /=.\nrewrite !(mul1R,mulR1,mulRN1) -oppRD onemKC.\nrewrite (_ : - / (1 + 1) + (/ (1 + 1)).~ = 0); last first.\n  by rewrite /onem addRCA -oppRD -div1R eps2 addRN.\nby rewrite mul0R leR_oppr oppR0 leRNgt; exact.\nQed.\nEnd counterexample.\n\nEnd biconvex_function.\n\nSection concave_function_def.\nLocal Open Scope ordered_convex_scope.\nVariables (A : convType) (B : orderedConvType).\nImplicit Types f : A -> B.\nDefinition concave_function_at f a b t := @convex_function_at A _\n  (fun a => \\opp{f a}) a b t.\nDefinition concave_function_at' f a b t := (f a <| t |> f b <= f (a <| t |> b)).\nDefinition strictly_concavef_at f := forall a b (t : prob),\n  a <> b -> (0 < t < 1)%R -> concave_function_at f a b t.\nLemma concave_function_at'P f a b t :\n  concave_function_at' f a b t <-> concave_function_at f a b t.\nProof.\nrewrite /concave_function_at'/concave_function_at/convex_function_at.\nby rewrite conv_leoppD leoppP.\nQed.\nEnd concave_function_def.\n\nDefinition concave_function (U : convType) (V : orderedConvType) (f : U -> V) :=\n forall a b (t : prob), concave_function_at f a b t.\n\nHB.mixin Record isConcaveFunction\n    (U : convType) (V : orderedConvType) (f : U -> V) := {\n  concave_functionP : concave_function f }.\n\nHB.structure Definition ConcaveFunction (U : convType) (V : orderedConvType) :=\n  { f of isConcaveFunction U V f }.\n\nArguments concave_functionP {U V} s.\n\nNotation \"{ 'concave' T '->' R }\" :=\n  (ConvexFunction.type T R) (at level 36, T, R at next level,\n    format \"{ 'concave'  T  '->'  R }\") : convex_scope.\n\nSection concave_function_prop.\nLocal Open Scope ordered_convex_scope.\nVariable (T : convType) (V : orderedConvType).\n\nLemma concave_function_atxx (f : T -> V) a t :\n  concave_function_at f a a t.\nProof. exact: convex_function_atxx. Qed.\n\nSection Rprop.\nImplicit Types f : T -> R.\n\nLemma R_convex_function_atN f a b t :\n  concave_function_at f a b t -> convex_function_at (fun x => - f x)%R a b t.\nProof. by rewrite /convex_function_at /leconv /= avgR_oppD leR_oppl oppRK. Qed.\n\nLemma R_concave_function_atN f a b t :\n  convex_function_at f a b t -> concave_function_at (fun x => - f x)%R a b t.\nProof.\nrewrite /concave_function_at /convex_function_at.\nby rewrite /leconv/= /leopp/= avgR_oppD /leconv/= leR_oppl oppRK.\nQed.\n\nLemma R_convex_functionN f :\n  concave_function f -> convex_function (fun x => - f x)%R.\nProof. by move=> H a b t; exact/R_convex_function_atN/H. Qed.\n\nLemma R_concave_functionN f :\n  convex_function f -> concave_function (fun x => - f x)%R.\nProof. by move=> H a b t; exact/R_concave_function_atN/H. Qed.\n\nLemma RNconvex_function_at f a b t :\n  concave_function_at (fun x => - f x)%R a b t -> convex_function_at f a b t.\nProof. by move/(R_convex_function_atN); rewrite/convex_function_at !oppRK. Qed.\n\nLemma RNconcave_function_at f a b t :\n  convex_function_at (fun x => - f x)%R a b t -> concave_function_at f a b t.\nProof.\nmove/(R_concave_function_atN).\nby rewrite/concave_function_at/convex_function_at !oppRK.\nQed.\n\nLemma RNconvex_function f :\n  concave_function (fun x => - f x)%R -> convex_function f.\nProof. move=> H a b t; exact/RNconvex_function_at/H. Qed.\n\nLemma RNconcave_function f :\n  convex_function (fun x => - f x)%R -> concave_function f.\nProof. move=> H a b t; exact/RNconcave_function_at/H. Qed.\n\nEnd Rprop.\n\nSection Rprop2.\n\nLemma R_convex_functionB f (g : T -> R) :\n  convex_function f -> concave_function g ->\n  convex_function (fun x => f x - g x)%R.\nProof.\nmove=> Hf Hg p q t.\nrewrite /convex_function_at /= avgRE 2!mulRBr addRAC addRA.\nrewrite -addR_opp -addRA; apply: (leR_add _ _ _ _ (Hf _ _ _)).\nby rewrite -2!mulRN addRC; exact: (R_convex_functionN Hg).\nQed.\n\nLemma R_concave_functionB f (g : T -> R) :\n  concave_function f -> convex_function g ->\n  concave_function (fun x => f x - g x)%R.\nProof.\nmove=> Hf Hg.\nrewrite (_ : (fun _ => _) = (fun x => - (g x - f x)))%R; last first.\n  by apply/funext => x; rewrite oppRB.\nexact/R_concave_functionN/R_convex_functionB.\nQed.\n\nEnd Rprop2.\n\nEnd concave_function_prop.\n\nSection affine_function_prop.\nVariables (T : convType) (U : orderedConvType).\n\nLemma affine_functionP (f : T -> U) :\n  affine f <-> convex_function f /\\ concave_function f.\nProof.\nsplit => [H | [H1 H2] p q t]; last first.\n  by rewrite eqconv_le; split; [exact/H1|exact/H2].\nsplit => p q t.\n- by rewrite /convex_function_at H; exact/leconvR.\n- by rewrite /concave_function_at/convex_function_at H; exact/leconvR.\nQed.\n\nEnd affine_function_prop.\n\nSection affine_function_image.\nLocal Open Scope classical_set_scope.\nVariables T U : convType.\n\nProposition image_preserves_convex_hull (f : {affine T -> U}) (Z : set T) :\n  f @` (hull Z) = hull (f @` Z).\nProof.\nrewrite predeqE => b; split.\n  case=> a [n [g [e [Hg]]]] ->{a} <-{b}.\n  exists n, (f \\o g), e; split.\n    move=> b /= [i _] <-{b} /=.\n    by exists (g i) => //; apply Hg; exists i.\n  by rewrite Convn_comp.\ncase=> n [g [e [Hg]]] ->{b}.\nsuff [h Hh] : exists h : 'I_n -> T, forall i, Z (h i) /\\ f (h i) = g i.\n  exists (<|>_e h).\n    exists n; exists h; exists e; split => //.\n    move=> a [i _] <-.\n    by case: (Hh i).\n  rewrite Convn_comp; apply eq_Convn => // i /=.\n  by case: (Hh i).\napply (@fin_all_exists _ _ (fun i hi => Z hi /\\ f hi = g i)) => i.\ncase: (Hg (g i)); first by exists i.\nmove=> a // HZa Hfa; by exists a.\nQed.\n\nLemma is_convex_set_image (f : {affine T -> U}) (a : {convex_set T}) :\n  is_convex_set (f @` a).\nProof.\nrewrite /is_convex_set.\napply/asboolP => x y p [a0 Ha0 <-{x}] [a1 Ha1 <-{y}].\nexists (a0 <|p|> a1); last by rewrite affine_conv.\nby rewrite -in_setE; apply/mem_convex_set; rewrite in_setE.\nQed.\n\nLemma preimage_subset_convex_hull (f: {affine T -> U}) (Z: set U): hull (f @^-1` Z) `<=` f @^-1` (hull Z).\nProof.\nmove=>x [n [g [d [gZ ->]]]] /=.\nrewrite Convn_comp.\nexists n, (f \\o g), d; split=>//.\nby move=>y [i _ <-]; apply gZ; exists i.\nQed.\n\nEnd affine_function_image.\n\n(* TODO: rename, move to mathcomp *)\nLemma factorize_range (A B C : Type) (f : B -> C) (g : A -> C) :\n  (range g `<=` range f)%classic ->\n  exists h : A -> B, g = f \\o h.\nProof.\nmove=> gf; have [h gfh] : {h & forall a, g a = f (h a)}.\n  apply: (@choice _ _ (fun a b => g a = f b)) => a.\n  have /cid2[b _ <-] : range f (g a) by apply gf; exists a.\n  by exists b.\nby exists h; apply/funext => a; rewrite gfh.\nQed.\n\n(* NB: PR has been merged into mathcomp-analysis *)\nLemma image2_subset {aT bT rT : Type} [f : aT -> bT -> rT] [A B: set aT] [C D : set bT] :\n  (A `<=` B)%classic -> (C `<=` D)%classic ->\n  ([set f x y | x in A & y in C] `<=` [set f x y | x in B & y in D])%classic.\nProof.\nmove=> AB CD x [a aA [c cC xe]]; subst x; exists a; (try by apply AB).\nby exists c; (try by apply CD).\nQed.\n\nSection linear_function_image0.\nLocal Open Scope classical_set_scope.\nLocal Open Scope ring_scope.\nVariables (R : ringType) (T U : lmodType R).\n\n(* TODO: move to mathcomp *)\nLemma preimage_add_ker (f : {linear T -> U}) (A: set U) :\n  [set a + b | a in f @^-1` A & b in f @^-1` [set 0]] = f @^-1` A.\nProof.\nrewrite eqEsubset; split.\n-  move=> x [a /= aA] [b /= bker] xe; subst x.\n   by rewrite GRing.linearD bker GRing.addr0.\n- move=> x /= fx; exists x=>//.\n  by exists 0; [ apply GRing.linear0 | apply GRing.addr0].\nQed.\n\nEnd linear_function_image0.\n\nSection linear_function_image.\nLocal Open Scope classical_set_scope.\nLocal Open Scope ring_scope.\nVariables (T U : lmodType R).\n\n(* TODO: find how to speak about multilinear maps. *)\nLemma hull_add (A B : set T) :\n  hull [set a + b | a in A & b in B] =\n  [set a + b | a in hull A & b in hull B].\nProof.\nrewrite eqEsubset; split.\n- have conv : is_convex_set [set a + b | a in hull A & b in hull B].\n    apply/asboolP=>x y p [ax axA] [bx bxB] <- [ay ayA] [by' byB] <-.\n    rewrite avgr_addD; exists (ax <|p|> ay).\n       by move: (hull_is_convex A)=>/asboolP; apply.\n    exists (bx <|p|> by')=>//.\n    by move: (hull_is_convex B)=>/asboolP; apply.\n  apply (@hull_sub_convex _ _ (CSet.Pack (CSet.Mixin conv))), image2_subset;\n  exact (@subset_hull _ _).\n- move=>x [a [na [ga [da [gaA ->]]]]] [b [nb [gb [db [gbB ->]]]]] <-.\n  rewrite avgnr_add.\n  exists (na * nb)%nat,\n    (fun i => let (i, j) := split_prod i in ga i + gb j),\n    (fdistmap (unsplit_prod (n:=nb)) da `x db); split=>// y [i _ <-].\n  by case: split_prod=>ia ib; exists (ga ia); [by apply gaA; exists ia |];\n    exists (gb ib)=>//; apply gbB; exists ib.\nQed.\n\nImport GRing.\n\nProposition preimage_preserves_convex_hull (f : {linear T -> U}) (Z : set U) :\n  Z `<=` range f -> f @^-1` (hull Z) = hull (f @^-1` Z).\nProof.\nrewrite eqEsubset=>Zf; split; last by apply preimage_subset_convex_hull.\nmove=>x [n [g [d [gZ fx]]]].\nmove: Zf=>/(subset_trans gZ)/factorize_range [h ge]; subst g.\nrewrite -preimage_add_ker hull_add.\nexists (<|>_d h).\n   by exists n, h, d; split=>// y [z _ <-] /=; apply gZ; exists z.\nexists (x - <|>_d h).\n   by apply subset_hull=>/=; rewrite linearB Convn_comp fx subrr.\nby rewrite addrC -addrA [-_+_]addrC subrr addr0.\nQed.\n\nEnd linear_function_image.\n\nSection R_affine_function_prop.\nVariables (T : convType) (f : T -> R).\nLemma R_affine_functionN : affine f -> affine (fun x => - f x)%R.\nProof.\nmove/affine_functionP => [H1 H2]; rewrite affine_functionP.\nsplit => //; [exact/R_convex_functionN|exact/R_concave_functionN].\nQed.\nEnd R_affine_function_prop.\n\nSection convex_function_in_def.\nVariables (T : convType) (U : orderedConvType) (D : convex_set T) (f : T -> U).\n\nDefinition convex_function_in :=\n  forall a b p, a \\in D -> b \\in D -> convex_function_at f a b p.\n\nDefinition concave_function_in :=\n  forall a b p, a \\in D -> b \\in D -> concave_function_at f a b p.\n\nEnd convex_function_in_def.\n\n(*\nLemma Conv2DistdE (A : choiceType) (a b : Dist A) (p : prob) (x : A) :\n  (a <| p |> b) x = a x <| p |> b x.\nProof. by rewrite Conv2Dist.dE. Qed.\n\n\nLemma DistBindConv (A : finType) (B : finType)(p : prob) (dx dy : dist A) (f : A -> dist B) :\n  DistBind.d dx f <|p|> DistBind.d dy f = DistBind.d (dx <|p|> dy) f.\nProof.\napply/dist_ext => b0.\nrewrite !(Conv2Dist.dE,DistBind.dE) !big_distrr -big_split; apply eq_bigr => a0 _ /=.\nby rewrite Conv2Dist.dE mulRDl 2!mulRA.\nQed.\n\nLemma rsum_Conv (A : finType) (p : prob) (dx dy : dist A):\n  \\rsum_(a in A) (dx a <|p|> dy a) =\n  \\rsum_(a in A) dx a <|p|> \\rsum_(a in A) dy a.\nProof. by rewrite /Conv /= /avg big_split /= -2!big_distrr. Qed.\n\nTODO: see convex_type.v\n*)\n\nSection convex_set_R.\n\nLemma Rpos_convex : is_convex_set (fun x => 0 < x)%R.\nProof.\napply/asboolP => x y t Hx Hy.\ncase/boolP : (t == 0%:pr) => [/eqP ->| Ht0]; first by rewrite conv0.\napply addR_gt0wl; first by apply mulR_gt0 => //; exact/prob_gt0.\napply mulR_ge0 => //; exact: ltRW.\nQed.\n\nDefinition Rpos_interval : {convex_set R} := CSet.Pack (CSet.Mixin Rpos_convex).\n\nLemma Rnonneg_convex : is_convex_set (fun x => 0 <= x)%R.\nProof. apply/asboolP=> x y t Hx Hy; apply addR_ge0; exact/mulR_ge0. Qed.\n\nDefinition Rnonneg_interval := CSet.Pack (CSet.Mixin Rnonneg_convex).\n\nLemma open_interval_convex a b (Hab : (a < b)%R) : is_convex_set (fun x => a < x < b)%R.\nProof.\napply/asboolP => x y t [xa xb] [ya yb].\ncase/boolP : (t == 0%:pr) => [/eqP|]t0; first by rewrite t0 conv0.\ncase/boolP : (t == 1%:pr) => [/eqP|]t1; first by rewrite t1 conv1.\napply conj.\n- rewrite -[X in (X < t * x + t.~ * y)%R]mul1R -(onemKC t) mulRDl.\n  apply ltR_add; rewrite ltR_pmul2l //; [exact/prob_gt0 | exact/onem_gt0/prob_lt1].\n- rewrite -[X in (_ + _ < X)%R]mul1R -(onemKC t) mulRDl.\n  apply ltR_add; rewrite ltR_pmul2l //; [exact/prob_gt0 | exact/onem_gt0/prob_lt1].\nQed.\n\nLemma open_unit_interval_convex : is_convex_set (fun x => 0 < x < 1)%R.\nProof. exact: open_interval_convex. Qed.\n\nDefinition open_unit_interval := CSet.Pack (CSet.Mixin open_unit_interval_convex).\n\nEnd convex_set_R.\n\nSection convex_function_R.\n\nImplicit Types f : R -> R.\n\nLemma concave_function_atN f x y t : concave_function_at f x y t ->\n  forall k, (0 <= k)%R -> concave_function_at (fun x => f x * k)%R x y t.\nProof.\nmove=> H k k0; rewrite /concave_function_at /convex_function_at.\nrewrite conv_leoppD leoppP avgRE.\nrewrite /leconv /= -avgR_mulDl.\nexact: leR_wpmul2r.\nQed.\n\nLemma convexf_at_onem x y (t : prob) f : (0 < x -> 0 < y -> x < y ->\n  convex_function_at f x y t -> convex_function_at f y x t.~%:pr)%R.\nProof.\nmove=> x0 y0 xy H; rewrite /convex_function_at.\nrewrite [in X in leconv _ X]avgRE /= onemK addRC.\nrewrite /convex_function_at !avgRE in H.\nrewrite avgRE /= onemK addRC.\napply: (leR_trans H); rewrite addRC; exact/leRR.\nQed.\n\nLemma concavef_at_onem x y (t : prob) f : (0 < x -> 0 < y -> x < y ->\n  concave_function_at f x y t -> concave_function_at f y x t.~%:pr)%R.\nProof.\nmove=>x0 y0 xy; rewrite/concave_function_at/convex_function_at.\nrewrite !conv_leoppD !leoppP/=.\nrewrite !avgRE /= onemK.\nby rewrite addRC [in X in leconv _ X -> _]addRC.\nQed.\nEnd convex_function_R.\n\n(* NB:\nAssume f is twice differentiable on an open interval I.\nLet Df and DDf be the first and second derivatives of f.\nFurther assume DDf is always positive.  By applying MVT, we have :\nforall a x \\in I, exists c1 \\in [a,x], f(x) = f(a) + (x-a) * Df(c1).\nFix a and x.  Applying MVT again, we further get :\nexists c2 \\in (a,c1), Df(c1) = Df(a) + (c1-a) * DDf(c2).\nThe two equations combined is :\nf(x) = f(a) + (x-a) * Df(a) + (x-a)(c1-a) * DDf(c2).\nThe last term is then positive thanks to the assumption on DDf.\nNow this is an equivalent condition to the convexity of f.\n *)\n\n(* ref: http://www.math.wisc.edu/~nagel/convexity.pdf *)\nSection twice_derivable_convex.\n\nVariables (f : R -> R) (a b : R).\nLet I := fun x0 => (a <= x0 <= b)%R.\nHypothesis HDf : pderivable f I.\nVariable Df : R -> R.\nHypothesis DfE : forall x (Hx : I x), Df x = derive_pt f x (HDf Hx).\nHypothesis HDDf : pderivable Df I.\nVariable DDf : R -> R.\nHypothesis DDfE : forall x (Hx : I x), DDf x = derive_pt Df x (HDDf Hx).\nHypothesis DDf_ge0 : forall x, I x -> (0 <= DDf x)%R.\n\nDefinition L (x : R) := (f a + (x - a) / (b - a) * (f b - f a))%R.\n\nHypothesis ab : (a < b)%R.\n\nLemma LE x : L x = ((b - x) / (b - a) * f a + (x - a) / (b - a) * f b)%R.\nProof.\nrewrite /L mulRBr [in LHS]addRA addRAC; congr (_ + _)%R.\nrewrite addR_opp -{1}(mul1R (f a)) -mulRBl; congr (_ * _)%R.\nrewrite -(mulRV (b - a)); last by rewrite subR_eq0'; exact/gtR_eqF.\nby rewrite -mulRBl -addR_opp oppRB addRA subRK addR_opp.\nQed.\n\nLemma convexf_ptP : (forall x, a <= x <= b -> 0 <= L x - f x)%R ->\n  forall t : prob, convex_function_at f a b t.\nProof.\nmove=> H t; rewrite /convex_function_at.\nset x := (t * a + t.~ * b)%R.\nhave : (a <= x <= b)%R.\n  rewrite /x; split.\n  - apply (@leR_trans (t * a + t.~ * a)).\n      rewrite -mulRDl addRCA addR_opp subRR addR0 mul1R; exact/leRR.\n    have [->|t1] := eqVneq t 1%:pr.\n      rewrite /onem subRR !mul0R !addR0; exact/leRR.\n    rewrite leR_add2l; apply leR_wpmul2l => //; exact/ltRW.\n  - apply (@leR_trans (t * b + t.~ * b)); last first.\n      rewrite -mulRDl addRCA addR_opp subRR addR0 mul1R; exact/leRR.\n    rewrite leR_add2r; apply leR_wpmul2l => //; exact/ltRW.\nmove/H; rewrite subR_ge0 => /leR_trans; apply.\nrewrite LE //.\nhave -> : ((b - x) / (b - a) = t)%R.\n  rewrite /x -addR_opp oppRD addRCA mulRBl mul1R oppRB (addRCA b).\n  rewrite addR_opp subRR addR0 -mulRN addRC -mulRDr addR_opp.\n  rewrite /Rdiv -mulRA mulRV ?mulR1 // subR_eq0'; exact/gtR_eqF.\nhave -> : ((x - a) / (b - a) = t.~)%R.\n  rewrite /x -addR_opp addRAC -{1}(oppRK a) mulRN -mulNR -{2}(mul1R (- a)%R).\n  rewrite -mulRDl (addRC _ R1) addR_opp -mulRDr addRC addR_opp.\n  rewrite /Rdiv -mulRA mulRV ?mulR1 // subR_eq0'; exact/gtR_eqF.\nexact/leRR.\nQed.\n\nLemma second_derivative_convexf_pt : forall t : prob, convex_function_at f a b t.\nProof.\nhave note1 : forall x, R1 = ((x - a) / (b - a) + (b - x) / (b - a))%R.\n  move=> x; rewrite -mulRDl addRC addRA subRK addR_opp mulRV // subR_eq0'.\n  exact/gtR_eqF.\nhave step1 : forall x, f x = ((x - a) / (b - a) * f x + (b - x) / (b - a) * f x)%R.\n  by move=> x; rewrite -mulRDl -note1 mul1R.\napply convexf_ptP => // x axb.\nrewrite /L.\ncase: axb.\n  rewrite leR_eqVlt => -[-> _|].\n  rewrite /L subRR div0R mul0R addR0 subRR; exact/leRR.\nmove=> ax.\nrewrite leR_eqVlt => -[->|].\nrewrite /L /Rdiv mulRV ?mul1R; last by rewrite subR_eq0'; exact/gtR_eqF.\nrewrite addRC subRK subRR; exact/leRR.\nmove=> xb.\nhave {step1}step2 : (L x - f x =\n  (x - a) * (b - x) / (b - a) * ((f b - f x) / (b - x)) -\n  (b - x) * (x - a) / (b - a) * ((f x - f a) / (x - a)))%R.\n  rewrite {1}step1 {step1}.\n  rewrite -addR_opp oppRD addRA addRC addRA.\n  rewrite LE //.\n  rewrite {1}/Rdiv -(mulRN _ (f x)) -/(Rdiv _ _).\n  rewrite addRA -mulRDr (addRC _ (f a)) (addR_opp (f a)).\n  rewrite -mulRN -addRA -mulRDr (addR_opp (f b)).\n  rewrite addRC.\n  rewrite -(oppRK (f a - f x)) mulRN addR_opp oppRB.\n  congr (_ + _)%R.\n  - rewrite {1}/Rdiv -!mulRA; congr (_ * _)%R; rewrite mulRCA; congr (_ * _)%R.\n    rewrite mulRCA mulRV ?mulR1 // subR_eq0'; exact/gtR_eqF.\n  - rewrite -!mulNR -!mulRA; congr (_ * _)%R; rewrite mulRCA; congr (_ * _)%R.\n    rewrite mulRCA mulRV ?mulR1 // subR_eq0'; exact/gtR_eqF.\nhave [c2 [Ic2 Hc2]] : exists c2, (x < c2 < b /\\ (f b - f x) / (b - x) = Df c2)%R.\n  have H : pderivable f (fun x0 => x <= x0 <= b)%R.\n    move=> z [z1 z2]; apply HDf; split => //.\n    apply (@leR_trans x) => //; exact: ltRW.\n  case: (@MVT_cor1_pderivable x b f H xb) => c2 [Ic2 [H1 H2]].\n  exists c2; split => //.\n  rewrite H1 /Rdiv -mulRA mulRV ?mulR1; last first.\n    by rewrite subR_eq0'; exact/gtR_eqF.\n  rewrite DfE; last by move=> ?; exact: proof_derive_irrelevance.\n  split.\n    apply (@leR_trans x); [exact/ltRW | by case: Ic2 H1].\n  by case: H2 => _ /ltRW.\nhave [c1 [Ic1 Hc1]] : exists c1, (a < c1 < x /\\ (f x - f a) / (x - a) = Df c1)%R.\n  have H : pderivable f (fun x0 => a <= x0 <= x)%R.\n    move=> z [z1 z2]; apply HDf; split => //.\n    apply (@leR_trans x) => //; exact: ltRW.\n  case: (@MVT_cor1_pderivable a x f H ax) => c1 [Ic1 [H1 H2]].\n  exists c1; split => //.\n  rewrite H1 /Rdiv -mulRA mulRV ?mulR1; last first.\n    by rewrite subR_eq0'; exact/gtR_eqF.\n  rewrite DfE; last by move=> ?; exact: proof_derive_irrelevance.\n  split.\n  - by case: H2 => /ltRW.\n  - apply (@leR_trans x).\n    by case: H2 => _ /ltRW.\n    apply (@leR_trans c2); apply/ltRW; by case: Ic2.\nhave c1c2 : (c1 < c2)%R by apply (@ltR_trans x); [case: Ic1 | case: Ic2].\nhave {step2 Hc1 Hc2}step3 : (L x - f x =\n  (b - x) * (x - a) * (c2 - c1) / (b - a) * ((Df c2 - Df c1) / (c2 - c1)))%R.\n  rewrite {}step2 Hc2 Hc1 (mulRC (x - a)%R) -mulRBr {1}/Rdiv -!mulRA.\n  congr (_ * (_ * _))%R; rewrite mulRCA; congr (_ * _)%R.\n  rewrite mulRCA mulRV ?mulR1 // subR_eq0'; by move/gtR_eqF : c1c2.\nhave [d [Id H]] : exists d, (c1 < d < c2 /\\ (Df c2 - Df c1) / (c2 - c1) = DDf d)%R.\n  have H : pderivable Df (fun x0 => c1 <= x0 <= c2)%R.\n    move=> z [z1 z2]; apply HDDf; split => //.\n    - apply (@leR_trans c1) => //; by case: Ic1 => /ltRW.\n    - apply (@leR_trans c2) => //; by case: Ic2 => _ /ltRW.\n  case: (@MVT_cor1_pderivable c1 c2 Df H c1c2) => d [Id [H1 H2]].\n  exists d; split => //.\n  rewrite H1 /Rdiv -mulRA mulRV ?mulR1; last first.\n    by rewrite subR_eq0'; exact/gtR_eqF.\n  rewrite DDfE; last by move=> ?; exact: proof_derive_irrelevance.\n  split.\n  - apply (@leR_trans c1); last by case: Id H1.\n    by apply/ltRW; case: Ic1.\n  - apply (@leR_trans c2); last by case: Ic2 => _ /ltRW.\n    by case: H2 => _ /ltRW.\nrewrite {}step3 {}H.\napply/mulR_ge0; last first.\n  apply: DDf_ge0; split.\n    apply (@leR_trans c1).\n      apply/ltRW; by case: Ic1.\n     by case: Id => /ltRW.\n  apply (@leR_trans c2).\n    by case: Id => _ /ltRW.\n  apply/ltRW; by case: Ic2.\napply/mulR_ge0; last by apply/invR_ge0; rewrite subR_gt0.\napply/mulR_ge0; last first.\n  by rewrite subR_ge0; case: Id => Id1 Id2; apply (@leR_trans d); exact/ltRW.\nby apply/mulR_ge0; rewrite subR_ge0; exact/ltRW.\nQed.\n\nEnd twice_derivable_convex.\n\nSection ereal_convex.\nLocal Open Scope ereal_scope.\n\nLet conv_ereal (p : prob) x y := (p : R)%:E * x + p.~%:E * y.\n\nLet conv_ereal_conv1 a b : conv_ereal 1%:pr a b = a.\nProof. by rewrite /conv_ereal probpK onem1 /= mul1e mul0e adde0. Qed.\n\nLet conv_ereal_convmm p a : conv_ereal p a a = a.\nProof.\nrewrite /conv_ereal; case/boolP : (a \\is a fin_num) => [?|].\n  by rewrite -muleDl// -EFinD /GRing.add /= probKC mul1e.\nrewrite fin_numE negb_and !negbK => /predU1P[-> | /eqP->].\n- rewrite -ge0_muleDl.\n  + by rewrite -EFinD /GRing.add /= probKC mul1e.\n  + by rewrite lee_fin; apply/RleP/prob_ge0.\n  + by rewrite lee_fin; apply/RleP/prob_ge0.\n- rewrite -ge0_muleDl.\n  + by rewrite -EFinD /GRing.add /= probKC mul1e.\n  + by rewrite lee_fin; apply/RleP/prob_ge0.\n  + by rewrite lee_fin; apply/RleP/prob_ge0.\nQed.\n\nLet conv_ereal_convC p a b : conv_ereal p a b = conv_ereal (p.~)%:pr b a.\nProof. by rewrite [in RHS]/conv_ereal onemK addeC. Qed.\n\nLemma oprob_sg1 (p : oprob) : Num.sg (Prob.p p) = 1%R.\nProof.\ncase/ltR2P: (OProb.O1 p)=> /[swap] _ /RltP /(conj Num.Theory.sgr_cp0) [] <-.\nby move/eqP.\nQed.\n\nLet conv_ereal_convA p q a b c :\n  conv_ereal p a (conv_ereal q b c) =\n  conv_ereal [s_of p, q] (conv_ereal [r_of p, q] a b) c.\nProof.\nrewrite /conv_ereal.\napply (prob_trichotomy' p);\n  [ by rewrite s_of_0q r_of_0q !mul0e !add0e !onem0 !mul1e\n  | by rewrite s_of_1q r_of_1q !mul1e !onem1 !mul0e !adde0\n  | rewrite {p}=> p].\napply (prob_trichotomy' q);\n  [ by rewrite s_of_p0 r_of_p0_oprob onem1 onem0 mul0e !mul1e add0e adde0\n  | by rewrite s_of_p1 r_of_p1 onem1 !mul1e mul0e !adde0\n  | rewrite {q}=> q].\nhave sgp := oprob_sg1 p.\nhave sgq := oprob_sg1 q.\nhave sgonemp := oprob_sg1 p.~%:opr.\nhave sgonemq := oprob_sg1 q.~%:opr.\nhave sgrpq := oprob_sg1 [r_of p, q]%:opr.\nhave sgspq := oprob_sg1 [s_of p, q]%:opr.\nhave sgonemrpq := oprob_sg1 [r_of p, q].~%:opr.\nhave sgonemspq := oprob_sg1 [s_of p, q].~%:opr.\nLtac mulr_infty X := do ! (rewrite mulr_infty X mul1e).\nset sg := (sgp,sgq,sgonemp,sgonemq,sgrpq,sgspq,sgonemrpq,sgonemspq).\ncase: a=> [a | | ]; case: b=> [b | | ]; case: c=> [c | | ];\n  try by mulr_infty sg.\nrewrite muleDr // addeA.\ncongr (_ + _)%E; last by rewrite s_of_pqE onemK EFinM muleA.\nrewrite muleDr //.\ncongr (_ + _)%E; first  by rewrite (p_is_rs p q) mulRC EFinM muleA.\nrewrite muleA -!EFinM.\nrewrite /GRing.mul /= (pq_is_rs (OProb.p p) q).\nrewrite mulRA.\nby rewrite (mulRC [r_of p, q].~).\nQed.\n\nHB.instance Definition _ := @isConvexSpace.Build (\\bar R) (Choice.class _) _\n  conv_ereal_conv1 conv_ereal_convmm conv_ereal_convC conv_ereal_convA.\n\nLemma conv_erealE p (a b : \\bar R) : a <| p |> b = conv_ereal p a b.\nProof. by []. Qed.\n\nEnd ereal_convex.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/probability/convex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7160586502412815}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := mult x lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj245_coqofml_6r8Fah.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7160586494312156}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Solange Coupet-Grimal and William Delobel, 2006-01-09\n\nVarious properties of preorders\n*)\n\nFrom CoLoR Require Import LogicUtil.\nFrom Coq Require Import Relations.\n\nSection PreOrderFacts.\n  Variable A : Type.\n  Variable leA : relation A.\n\n  Definition eqA : relation A := fun (f g : A) => leA f g /\\ leA g f.\n  Definition ltA : (relation A) := fun (f g : A) => leA f g /\\ ~ eqA f g.\n\n  Variable leA_preorder : preorder A leA.\n  \n  Lemma eqA_equivalence : equivalence A eqA.\n  Proof.\n    inversion leA_preorder.\n    split.\n    (* reflexive : *)\n    intro a; split; apply preord_refl.\n    (* transitive : *)\n    intros a b c H1 H2.\n    elim H1; clear H1; intros a_le_g b_le_a.\n    elim H2; clear H2; intros b_le_c c_le_b.\n    split.\n    apply preord_trans with b; hyp.\n    apply preord_trans with b; hyp.\n    (* symmetric : *)\n    intros a b H.\n    elim H; split; hyp.\n  Qed.\n    \n  Lemma ltA_antisym : forall (a b : A), ltA a b -> ltA b a -> False.\n  Proof.\n    intros a b H1 H2.\n    elim H1; clear H1; intros a_le_b b_neq_a.\n    elim H2; clear H2; intros b_le_a a_neq_b.\n    apply a_neq_b; split; hyp.\n  Qed.\n    \n  Lemma ltA_trans : transitive A ltA.\n  Proof.\n    inversion leA_preorder.\n    intros a b c H1 H2.\n    elim H1; clear H1; intros a_le_b a_neq_b.\n    elim H2; clear H2; intros b_le_c b_neq_c.\n    split.\n    apply preord_trans with b; hyp.\n    intro H.\n    elim H; clear H; intros a_le_c c_le_a.\n    apply a_neq_b; split.\n    hyp.\n    apply preord_trans with c; hyp.\n  Qed.\n\n  Lemma leA_dec_to_eqA_dec : (forall (a b : A), leA a b \\/ ~ leA a b) ->\n    forall (a b : A), eqA a b \\/ ~ eqA a b.\n  Proof.\n    intros leA_dec a b; elim (leA_dec a b); intro case_a_le_b.\n    elim (leA_dec b a); intro case_b_le_a; [left | right].\n    split; trivial.\n    intro H; elim H; clear H; intros H1 H2.\n    apply case_b_le_a; trivial.\n    right; intro H; apply case_a_le_b.\n    elim H; trivial.\n  Qed.\n\n  Lemma ltA_eqA_compat_r : forall (a b b' :A), eqA b b' -> ltA a b -> ltA a b'.\n  Proof.\n    inversion leA_preorder.\n    intros a b b' b_eq a_lt_b.\n    elim a_lt_b; clear a_lt_b; intros a_le_b a_neq_b.\n    split.\n    elim b_eq; clear b_eq; intros b_le_b' b'_le_b.\n    apply preord_trans with b; hyp.\n    elim (eqA_equivalence); intros eqA_refl eqA_trans eqA_sym.\n    intro; apply a_neq_b; apply eqA_trans with b'; trivial.\n    elim b_eq; split; trivial.\n  Qed.\n\n  Lemma ltA_eqA_compat_l : forall (a b b' :A), eqA b b' -> ltA b a -> ltA b' a. \n  Proof.\n    inversion leA_preorder.\n    intros a b b' b_eq b_lt_a.\n    elim b_lt_a; clear b_lt_a; intros b_le_a b_neq_a.\n    split.\n    elim b_eq; clear b_eq; intros b_le_b' b'_le_b.\n    apply preord_trans with b; hyp.\n    elim (eqA_equivalence); intros eqA_refl eqA_trans eqA_sym.\n    intro; apply b_neq_a; apply eqA_trans with b'; trivial.\n  Qed.\n\n  Section Decidability.\n\n    Variable leA_dec : forall a b, {leA a b} + {~leA a b}.\n\n    Lemma eqA_dec : forall a b, {eqA a b} + {~eqA a b}.\n\n    Proof.\n      intros. unfold eqA.\n      destruct (leA_dec a b); intuition.\n      destruct (leA_dec b a); intuition.\n    Defined.\n\n    Lemma ltA_dec : forall a b, {ltA a b} + {~ltA a b}.\n\n    Proof.\n      intros. unfold ltA.\n      destruct (leA_dec a b); intuition.\n      destruct (eqA_dec a b); intuition.\n    Defined.\n\n  End Decidability.\n\nEnd PreOrderFacts.  \n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Util/Relation/Preorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.716021094846572}}
{"text": "Require Export Coq.Init.Nat.\n\nDefinition smallerThan3 (n:nat) : bool := ltb n 3.\n\nCompute smallerThan3 0.\n\nFixpoint firstn {A:Set} (l:list A) (n:nat) : list A :=\n    match l with\n    | nil => nil\n    | cons h l' => match n with\n                    | 0 => nil\n                    | S n' => cons h (firstn l' n')\n                    end\n    end.\n\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n(* Implicit Arguments firstn {A}. *)\nCompute (firstn [1;2;3;4;5;6] 7).\n\nPrint snd.\n\nDefinition split {A B : Set} : list (A*B) -> list A * list B :=\n    fix f (lab : list (A*B)) : list A * list B := \n        match lab with\n        | nil => (nil, nil)\n        | cons h lab' => match h with (a, b) => let tmp := (f lab') in (cons a (fst tmp), cons b (snd tmp)) \n        end\n        end.\n\nCompute (split ([(1,2); (2,3); (3,4)])).\n\nInductive List (A:Set) : Set :=\n| nil : List A\n| cons : A -> List A -> List A.\n\nCheck\n  (fun l:List nat =>\n     match l with\n     | nil _ => nil nat\n     | cons _ _ l' => l'\n     end).", "meta": {"author": "haoyang9804", "repo": "coq-Art", "sha": "52204f59312510c678a7dd9f4e60f15d44af9226", "save_path": "github-repos/coq/haoyang9804-coq-Art", "path": "github-repos/coq/haoyang9804-coq-Art/coq-Art-52204f59312510c678a7dd9f4e60f15d44af9226/_KloppSrc/chap6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059267, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7160210863567867}}
{"text": "\nFrom Undecidability.Shared.Libs.PSL Require Import FinTypes.\n\nFixpoint position {X : eqType} (x : X) (l : list X) : option (Fin.t (length l)).\nProof.\n  induction l.\n  - exact None.\n  - cbn. decide (a = x).\n    + exact (Some Fin.F1).\n    + destruct (position _ x l) as [res | ].\n      * exact (Some (Fin.FS res)). \n      * exact None.\nDefined.\n\nLemma position_in {X : eqType} (x : X) (l : list X) (H : x el l) : \n  { i | position x l = Some i}.\nProof.  \n    induction l; cbn in *.\n    - inv H.\n    - decide (a = x).\n        + eauto.\n        + destruct IHl as [i IH]. firstorder. rewrite IH. eauto.\nDefined. \n\nDefinition posIn {X : eqType} (x : X) (l : list X) (H : x el l) : Fin.t (length l).\nProof.\n    eapply position_in in H. destruct (position x l) as [i | ]. exact i.\n    abstract (exfalso; firstorder congruence).\nDefined.\n\nFixpoint getat {X : Type} (l : list X) (i : Fin.t (length l)) : X.\nProof.\n    destruct l.\n    - inv i.\n    - cbn in i. eapply (Fin.caseS' i (fun _ => X)).\n      + exact x.\n      + eapply getat.\nDefined.\n\nArguments getat {_} _ _.\n\nLemma getatIn {X : Type} (l : list X) (i : Fin.t (length l)) : \n    getat l i el l.\nProof.\n    induction l.\n    - inv i.\n    - cbn in *. eapply (Fin.caseS' i); cbn. eauto. eauto.\nQed.\n\nLemma finite_n (F : finType) :\n    { n & {f : F -> Fin.t n & { g : Fin.t n -> F | (forall i, f (g i) = i) /\\ forall x, g (f x) = x }}}.\nProof.\n    destruct F as (X & [l H]). cbn in *. \n    exists (length l).\n    assert (Hin : forall x, x el l). { intros x. eapply count_in_equiv. rewrite H. lia. }\n    exists (fun x => proj1_sig (position_in (Hin x))). exists (@getat _ l). split.\n    - intros i. destruct position_in. cbn.\n      specialize (H (getat l i)). clear - H e. \n      induction l.\n      + inv x.\n      + cbn in *. revert H e.\n        eapply (Fin.caseS' i). cbn.\n        * decide (a = a); congruence.\n        * cbn. intros. decide (getat l p = a).\n         -- decide (a = getat l p); try congruence. subst. inv e. inv H.\n            eapply countZero in H1 as []. eapply getatIn.\n         -- decide (a = getat l p); try congruence.\n            destruct position eqn:E; inv e. eapply IHl in E; congruence.\n    - intros x. generalize (Hin x). clear. intros H.\n      destruct (position_in H) as [i H1]. cbn.\n      induction l; cbn in *. \n      + inv H1.\n      + decide (a = x).\n        * inv H1. cbn. reflexivity.\n        * destruct (position x l) eqn:E; inv H1.\n          cbn. eapply IHl. firstorder. reflexivity.\nQed.", "meta": {"author": "yforster", "repo": "coq-synthetic-computability", "sha": "b9523cb33180dc58b227432e60045cc38615b711", "save_path": "github-repos/coq/yforster-coq-synthetic-computability", "path": "github-repos/coq/yforster-coq-synthetic-computability/coq-synthetic-computability-b9523cb33180dc58b227432e60045cc38615b711/Shared/FinTypeEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7160210831681869}}
{"text": "From Coq Require Import \n  Utf8 Pnat BinNatDef\n  BinPos List Lia.\n\nImport ListNotations.\n\nSection Prob.\n\n (* We formalise the probability as a rational \n    number where denominator is positive. \n    By construction, we can only construct \n    zero or positive values. *)\n  Record prob := \n    mk_prob {num : nat; denum : positive}.\n\n  Declare Scope Prob_scope.\n  Delimit Scope Prob_scope with P.\n  Local Open Scope Prob_scope.\n\n  Definition prob_eq (p q : prob) : bool := \n    match p, q with \n    | mk_prob pa pb, mk_prob qa qb => \n      Nat.eqb (pa * Pos.to_nat qb) (qa * Pos.to_nat pb)\n    end.\n\n  (* Print Grammar constr. *)\n  Local Infix \"=p=\" := prob_eq\n    (at level 70, no associativity) : Prob_scope.\n\n\n  \n  (* prob_eq is an equivalence relation *)\n  Lemma prob_eq_refl : forall p, p =p= p = true.\n  Proof.\n    intros [pa pb]; simpl; f_equal.\n    apply PeanoNat.Nat.eqb_eq; \n    reflexivity.\n  Qed.\n\n\n  Lemma prob_eq_sym : forall p q,\n    p =p= q = true -> q =p= p = true.\n  Proof.\n    intros [pa pb] [qa qb]; simpl; intro Heq.\n    apply PeanoNat.Nat.eqb_eq in Heq.\n    apply PeanoNat.Nat.eqb_eq.\n    lia.\n  Qed.\n\n  Lemma prob_eq_trans : forall p q r, \n    p =p= q = true -> q =p= r = true -> \n    p =p= r = true.\n  Proof.\n    intros [pa pb] [qa qb] [ra rb]; simpl;\n    intros Ha Hb.\n    apply PeanoNat.Nat.eqb_eq in Ha, Hb.\n    apply PeanoNat.Nat.eqb_eq.\n    nia. (* facinating! lia can't solve this goal *) \n  Qed.\n  (* end of equivalence relation *)\n\n\n  Definition zero : prob := mk_prob 0 1.\n\n  Definition one : prob := mk_prob 1 1.\n\n\n  Definition add_prob (p q : prob) : prob :=\n    match p, q with\n    | mk_prob a b, mk_prob c d => \n        mk_prob \n        (a * Pos.to_nat d + c * Pos.to_nat b) \n        (b * d) \n    end.\n\n  \n  Local Infix \"+p\" := (add_prob) \n    (at level 50, left associativity) : Prob_scope.\n\n  \n  \n  Lemma add_prob_assoc : forall p q r : prob, \n    p +p q +p r = p +p (q +p r).\n  Proof.\n    intros [px dpx] [qx dqx] [rx drx]; simpl; \n     f_equal; try lia.\n  Qed.\n\n  Lemma add_prob_comm : forall p q, p +p q = q +p p.\n  Proof.\n    intros [px Hpx] [qx Hqx]; simpl; \n    f_equal; try lia.\n  Qed.\n\n\n  Definition mul_prob (p q : prob) : prob :=\n    match p, q with\n    | mk_prob a b , mk_prob c d => \n        mk_prob (a * c) (b * d)\n    end.\n\n  Local Infix \"*p\" := (mul_prob) \n    (at level 40, left associativity) : Prob_scope.\n\n  Lemma mul_prob_assoc : forall px pxx pt,  \n    px *p pxx *p pt =  px *p (pxx *p pt).\n  Proof.\n    intros [pxn pxd] [ppxn ppxd] [ptn ptd];\n    simpl; f_equal; lia.\n  Qed.\n\n  Lemma mul_prob_comm: forall p q,  \n    p *p q = q *p p.\n  Proof.\n    intros [px Hpx] [qx Hqx]; simpl; \n    f_equal; try lia.\n  Qed.\n\n\n\n  Definition leq (p q : prob) : bool :=\n    match p, q with\n    | mk_prob pa pb, mk_prob qa qb => \n      Nat.leb (pa * Pos.to_nat qb) (qa * Pos.to_nat pb)\n    end.\n\n    \n  Local Infix \"<p=\" := (leq) (at level 70). (* associativity? *)\n  (* Print Grammar constr. *)\n\n  Lemma prob_leq_refl : forall p, \n    p <p= p = true.\n  Proof.\n    intros [pa pb]; simpl. \n    apply PeanoNat.Nat.leb_le.\n    nia.\n  Qed.\n  \n  Lemma prob_leq_trans : forall p q r, \n    p <p= q = true -> q <p= r = true -> p <p= r = true.\n  Proof.\n    intros [pxn pxd] [ppxn ppxd] [ptn ptd]; \n      simpl; intros Hpq Hqr.\n    apply PeanoNat.Nat.leb_le. \n    apply PeanoNat.Nat.leb_le in Hpq, Hqr.\n    nia.\n  Qed.\n\n  Lemma prob_leq_add_r : forall p q r, \n    p <p= q = true -> p +p r <p= q +p r = true.\n  Proof.\n    intros [pxn pxd] [ppxn ppxd] [ptn ptd]; \n      simpl; intros Hpq.\n    apply PeanoNat.Nat.leb_le. \n    apply PeanoNat.Nat.leb_le in Hpq.\n    nia.\n  Qed.\n\n  Lemma prob_leq_add_l : forall p q r, \n    p <p= q = true -> r +p p <p= r +p q = true.\n  Proof.\n    intros [pxn pxd] [ppxn ppxd] [ptn ptd]; \n      simpl; intros Hpq.\n    apply PeanoNat.Nat.leb_le. \n    apply PeanoNat.Nat.leb_le in Hpq.\n    nia.\n  Qed.\n\n  Lemma prob_leq_mul_r : forall p q r, \n    p <p= q = true -> p *p r <p= q *p r = true.\n  Proof.\n    intros [pxn pxd] [ppxn ppxd] [ptn ptd]; \n      simpl; intros Hpq.\n    apply PeanoNat.Nat.leb_le. \n    apply PeanoNat.Nat.leb_le in Hpq.\n    repeat rewrite Pos2Nat.inj_mul, \n      PeanoNat.Nat.mul_assoc.\n    apply PeanoNat.Nat.mul_le_mono_r. \n    nia.\n  Qed.\n    \n\n  Lemma prob_leq_mul_l : forall p q r, \n    p <p= q = true ->  r *p p <p= r *p q = true.\n  Proof.\n    intros [pxn pxd] [ppxn ppxd] [ptn ptd]; \n      simpl; intros Hpq.\n    apply PeanoNat.Nat.leb_le. \n    apply PeanoNat.Nat.leb_le in Hpq.\n    repeat rewrite Pos2Nat.inj_mul, \n      PeanoNat.Nat.mul_assoc.\n    assert (Ht: ptn * pxn * Pos.to_nat ptd * Pos.to_nat ppxd = \n      ptn * (Pos.to_nat ptd * pxn * Pos.to_nat ppxd)). \n    nia.\n    rewrite Ht; clear Ht.\n    assert (Ht: ptn * ppxn * Pos.to_nat ptd * Pos.to_nat pxd = \n      ptn * (Pos.to_nat ptd * ppxn * Pos.to_nat pxd)). \n    nia.\n    rewrite Ht; clear Ht.\n    eapply PeanoNat.Nat.mul_le_mono_nonneg_l with (p := ptn); \n    try nia.\n  Qed.\n\n  Lemma leq_prob : forall p q, \n    p <p= q = true <-> \n    num p * (Pos.to_nat (denum q)) <= num q * (Pos.to_nat (denum p)).\n  Proof.\n    intros [px qx] [py qy]; simpl.\n    split; intros H;\n    [apply PeanoNat.Nat.leb_le in H |\n      apply PeanoNat.Nat.leb_le];\n    nia.\n  Qed.\n\nEnd Prob.\n\n\n\n\n\n\n\n\n\n\n\n  ", "meta": {"author": "mukeshtiwari", "repo": "Dlog-zkp", "sha": "c291925d28609f57eab069bd8479d868e7e7f66c", "save_path": "github-repos/coq/mukeshtiwari-Dlog-zkp", "path": "github-repos/coq/mukeshtiwari-Dlog-zkp/Dlog-zkp-c291925d28609f57eab069bd8479d868e7e7f66c/src/Prob.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7160126961252847}}
{"text": "Fixpoint grb (n m : nat) : bool :=\n  match n with\n  | O => false\n  | S n' =>\n      match m with\n      | O => true\n      | S m' => grb n' m'\n      end\n  end.\n  \nDefinition negb (b: bool) : bool :=\n  match b with\n  | true => false\n  | false => true\n  end.\n  \nExample test_blt_nat1: grb 2 0 = true.\nProof. simpl. reflexivity. Qed.\n\n\nExample test_blt_nat2: (grb 2 2) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat3: (grb 2 1) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_blt_nat4: (grb 2 3) = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem t': forall (n: nat), grb (S n) n = true.\nProof.\n  intros.\n  induction n.\n  - simpl. reflexivity.\n  - simpl. apply IHn.\nQed.\n\n\nTheorem inf_nat: forall (m: nat), exists (n: nat), grb n m = true.\nProof.\n  intros m.\n  induction m.\n  - exists 1. simpl. reflexivity.\n  - exists (S (S m)). simpl. apply t' with (n:=S m). \nQed.\n\nLemma wrong: forall x: nat, 2 * x = 1 -> False.\nProof.\n  intros x. induction x.\n  - intros. inversion H.\n  - intros. apply IHx. destruct x. inversion H. inversion H. \nQed.\n\n(* This black magic proof should be referred back to a lot. \n   important to note that intros moves LHS from the goal to the context.\n   somehow I didn't understand that completely, all this time.\n*)\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  (* question: how can we just destruct m, if we haven't introduced it? \n   * answer from lolisa on #coq: destruct introduces m, and all variables that come before it. *)\n  Case \"n=0\".\n  destruct m.\n    SCase \"m=0\". intro H. reflexivity.\n    SCase \"m>0\". \n      (* cleverly not introducing the hypothesis until later. *)\n      simpl. intro contra. inversion contra.\n  Case \"n>0\".\n  destruct m as [|m'].\n    SCase \"m=0\". intros contra. inversion contra.\n    SCase \"m>0\".\n      intro H.\n      apply eq_remove_S.\n      (* here is some magic trick:\n        applying a hypothesis with an assumption moves the assumption to the goal. \n        but it can only be done when your goal matches whats on the RHS of that assumption.\n        this really makes sense though: \n          if you know A -> B, and you need to prove B, \n          then if you can prove A, you're good.  \n            (also if you can disprove A, i guess, but that doesn't apply here).\n      *)\n      apply IHn'.\n      (* in the rest, nothing really interesting happens. *)\n     simpl in H. inversion H. rewrite <- plus_n_Sm in H1. rewrite <- plus_n_Sm in H1. inversion H1. reflexivity.\nQed.\n*)\n\nDefinition prop' (m n k: nat) := forall (m: nat), exists (n: nat), grb n m = true /\\ ~ exists (k: nat), 2 * k = n.\nCheck prop'.\n\nDefinition hasFactor (f n: nat) := true.\n\nTheorem inf_nat_filter': forall (m n k: nat), hasFactor 2 m = true -> prop' m n k /\\ hasFactor 2 m = false -> prop' m n k.  \nProof.\n  intros m.\n  induction m.\n  - \n  induction m.\n  - exists 1. unfold not. split.\n    + simpl. reflexivity.\n    + intros. destruct H. apply wrong with (x:=x). apply H.\n  - exists (S (S m)). unfold not. split.\n    + apply t' with (n:=S m).\n    (* Stuck *)\n    + intros. destruct H. destruct IHm. unfold not in H0. destruct H0. apply H1.", "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/numbers_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7160126875301506}}
{"text": "(** Regex derivatives\n *\n * Regular expression derivatives are a particularly elegant approach\n * to matching and reasoning about regular expressions and\n * languages. The idea is to consider the derivative of a language L\n * (a set of strings) with respect to a character c, defined as {w |\n * cw in L}. In terms of automata, what does the automata match if fed the\n * character c first? It turns out that derivatives of regular languages have\n * two nice properties: the derivative of a regular language is regular, and the\n * derivative of a language expressed as a regular expression can be expressed\n * in a simple syntatic manner.\n *\n * This development defines regexes as syntax and as predicates,\n * defines derivatives syntactically and as a transformation of a\n * predicate, and proves a relationship between these\n * two. Specifically, [[ dr/dc ]] = d [[ r ]]/dc, abusing d/dc for\n * both the syntatic and denotational derivative and using [[ r ]] to\n * denote the denotation of a regex.\n *\n * These derivative tools give a simple and natural regex matcher with a\n * correctness proof in its type.\n *)\n\nRequire Import List.\n\nSection RegularExpressions.\n\n  (** The alphabet for strings *)\n  Variable Sigma:Type.\n  (** We only require decidable equality on the alphabet for matching\n  and derivatives to work (in particular, no finiteness\n  constraint). *)\n  Variable Sigma_dec : forall (c c': Sigma), {c = c'} + {c <> c'}.\n\n  (** * Standard names\n\n  These simple definitions give standard names from the theory of computation to\n  the analogues in this setting.\n   *)\n\n  (** A string takes elements from the (arbitrary) alphabet above. *)\n  Definition string := list Sigma.\n  (** A language is traditionally a set of strings. In Coq's constructive logic,\n  the best to express (possibly infinite) sets is as a predicate over strings;\n  the interpretation will be that forall (l: language) (s: string), l s is true\n  for exactly those strings in the language l *)\n  Definition language := string -> Prop.\n\n  (** A cool feature of Coq, mirroring standard practice in programming languages papers.\n\n  This command means, for example, that when we use the letter s for a variable\n  without a type annotation, it should default to being of type string, before\n  types are inferred.\n\n   This might seem like a horrible thing to do, and it is indeed confusing when\n   done on a whiteboard or in a paper, but here it serves an important purpose:\n   it ensures that when we use the letters c, s, or l (or those characters\n   followed by numbers or prime symbols ' actually), they must represent the\n   expected type. *)\n  Implicit Types (c: Sigma) (s: string) (l: language).\n\n  Definition string_dec : forall (s s': string), {s = s'} + {s <> s'} :=\n    List.list_eq_dec Sigma_dec.\n\n  Inductive regex :=\n    (** Empty is the empty language, matching no strings. *)\n  | Empty\n  | Char (c:Sigma)\n  | Or (r1:regex) (r2:regex)\n  | Seq (r1:regex) (r2:regex)\n  | Star (r:regex).\n\n  (** Eps is a derived regex that matches only the empty string. *)\n  Definition Eps := Star Empty.\n\n  (** First we give an auxiliary inductive definition to take the Kleene star of\n  a language. *)\n  Inductive star (l: language) : language :=\n  | star_empty : star l nil\n  | star_iter : forall s1 s2,\n      l s1 ->\n      star l s2 ->\n      star l (s1 ++ s2).\n\n  (** The denotation of a regex is a language.\n\n      Regular expressions give a nice way to think about denotational vs\n      operational definitions. We could define what a regular expression does in\n      terms of an automata, which gives regexes a meaning operationally.\n      Instead, we give a denotation (think \"interpretation\" or \"meaning\") for\n      each regex, mapping them to a concept we have in our metatheory.\n\n      Normally the metatheory is mathematics, but here we are using the Coq\n      programming language as the metatheory. In mathematics we would use a set\n      of strings as the denotation of a regex, whereas here we use [language] as\n      defined above. *)\n  Fixpoint denotation (r:regex) : language :=\n    match r with\n    | Empty => fun _ => False\n    | Char c => fun s => s = c::nil\n    | Or r1 r2 => fun s => denotation r1 s \\/ denotation r2 s\n    | Seq r1 r2 => fun s =>\n                    exists s1 s2, s = s1 ++ s2 /\\\n                             denotation r1 s1 /\\\n                             denotation r2 s2\n    | Star r => fun s => star (denotation r) s\n    end.\n\n  (* We will want to automatically prove the denotation star with its\n  constructors *)\n  Hint Constructors star : core.\n\n  Lemma star_false : forall s,\n      star (fun _ => False) s ->\n      s = nil.\n  Proof.\n    inversion 1; intuition.\n  Qed.\n\n  (** Some automation that covers most proofs here. *)\n\n  (* Helper for instantiating existential hypotheses, preserving names. *)\n  Ltac deex H :=\n    lazymatch type of H with\n    | exists (varname: _), _ =>\n      let name := fresh varname in\n      destruct H as [name ?]\n    end.\n\n  Ltac crush :=\n    repeat match goal with\n           | _ => progress (intros; simpl in *; subst)\n           | [ H: exists _, _ |- _ ] => deex H\n           | [ H: nil = _ ++ _ |- _ ] =>\n             destruct (app_eq_nil _ _ (eq_sym H))\n           | [ H: star (fun _ => False) _ |- _ ] =>\n             apply star_false in H\n           | [ H: _ :: _ = _ :: _ |- _ ] =>\n             inversion H; clear H\n           | _ => progress (intuition eauto 10)\n           | [ |- exists (_ : string), _ ] =>\n             solve [ exists nil; crush ]\n           | _ => congruence\n           end.\n\n  (* Eps indeed represents the language consisting only of the empty string. *)\n  Remark eps_denotation : forall s, denotation Eps s <-> s = nil.\n  Proof.\n    crush.\n  Qed.\n\n  (* The [observation_map] of a regex is one (equivalent to) Eps if nil\n  is in the language and one (equivalent to) Empty otherwise. *)\n  Fixpoint observation_map (r:regex) : regex :=\n    match r with\n    | Empty => Empty\n    | Char _ => Empty\n    | Or r1 r2 => Or (observation_map r1) (observation_map r2)\n    | Seq r1 r2 => Seq (observation_map r1) (observation_map r2)\n    | Star r => Eps\n    end.\n\n  (** Characterization of observation_map: when the resulting regex\n  holds, it is equivalent to Eps (an artifact of how observation_map\n  is defined) and nil is in r *)\n  Section ObservationMap.\n\n    Lemma observation_map_1 : forall r s,\n      denotation (observation_map r) s ->\n      s = nil.\n    Proof.\n      induction r; crush.\n      rewrite (IHr1 s1); eauto.\n    Qed.\n\n    Lemma observation_map_2 : forall r,\n        denotation (observation_map r) nil ->\n        denotation r nil.\n    Proof.\n      induction r; crush.\n    Qed.\n\n    Lemma observation_map_eps : forall r s,\n        denotation (observation_map r) s ->\n        (s = nil /\\ denotation r nil).\n    Proof.\n      intros.\n      pose proof (observation_map_1 _ _ H); subst.\n      intuition auto using observation_map_2.\n    Qed.\n\n    (* converse to the above *)\n    Lemma observation_map_holds : forall r,\n        denotation r nil ->\n        denotation (observation_map r) nil.\n    Proof.\n      induction r; crush.\n    Qed.\n\n  End ObservationMap.\n\n  (** Finally, we define the syntactic continuation map or derivative\n    of a regular expression, with respect to c. *)\n  Section Derivative.\n    (** This is the character we are taking the derivative with respect to.\n    Making it a variable means we don't have to pass it in recursive calls. *)\n    Variable c:Sigma.\n\n    Fixpoint continuation_map (r:regex) : regex :=\n      match r with\n      | Empty => Empty\n      | Char c' => if Sigma_dec c c' then Eps else Empty\n      | Or r1 r2 => Or (continuation_map r1) (continuation_map r2)\n      | Seq r1 r2 => Or\n                      (Seq (continuation_map r1) r2)\n                      (Seq (observation_map r1) (continuation_map r2))\n      | Star r => Seq (continuation_map r) (Star r)\n      end.\n  End Derivative.\n\n  (** To write the correctness of the continuation_map, [derivative]\n  defines derivative for a language in a straightforward,\n  interpretable way. *)\n  Definition derivative (c:Sigma) (l: language) : language :=\n    fun s => l (c :: s).\n\n  Hint Resolve app_comm_cons : core.\n  Hint Resolve observation_map_eps observation_map_holds : core.\n\n  (** The correctness theorem has the form that two languages (the denotation\n      of the continuation map and the derivative of the regex language) are the\n      same.\n\n      In Coq the natural way to express that l1 and l2 are the same is to prove\n      forall s, l1 <-> l2. This is easiest done by proving each direction\n      separately, amounting to proving l1 is a subset of l2 (forall s, l1 -> l2)\n      and that l2 is a subset of l1 (forall s, l2 -> l1). *)\n\n  Theorem continuation_map_denotes_derivative_1 : forall r c,\n      forall s, denotation (continuation_map c r) s ->\n           derivative c (denotation r) s.\n  Proof.\n    unfold derivative.\n    induction r; crush.\n    - destruct (Sigma_dec c0 c); crush.\n    - do 2 eexists; crush.\n    - pose proof (observation_map_eps _ _ H); crush.\n    - rewrite app_comm_cons.\n      eauto.\n  Qed.\n\n  Theorem continuation_map_denotes_derivative_2 : forall r c,\n      forall s, derivative c (denotation r) s ->\n           denotation (continuation_map c r) s.\n  Proof.\n    unfold derivative.\n    induction r; crush.\n    - destruct (Sigma_dec c c); crush.\n    - destruct s1; solve [ left + right; crush ].\n    - remember (c::s).\n      generalize dependent s.\n      match goal with\n      | [ H: star _ _ |- _ ] => induction H; crush\n      end.\n      destruct s1; crush.\n  Qed.\n\n  Theorem continuation_map_denotes_derivative : forall r c,\n      forall s, denotation (continuation_map c r) s <->\n           derivative c (denotation r) s.\n  Proof.\n    split; auto using continuation_map_denotes_derivative_1,\n           continuation_map_denotes_derivative_2.\n  Qed.\n\n  (** With these definitions it is easy to write a regex matcher, verified\n  against the denotation given above *)\n\n  Section Matching.\n\n    Ltac t := try solve [ left + right; crush ].\n\n    (** auxilliary function to make observation_map computable *)\n    Definition includes_nil r :\n      {denotation (observation_map r) nil} +\n      {forall s, ~denotation (observation_map r) s}.\n      induction r; crush; t.\n    Defined.\n\n    (** unfold definition of derivative to drive hints *)\n    Definition derivative_unfold : forall r c s,\n        derivative c (denotation r) s ->\n        denotation r (c::s)\n      := ltac:(auto).\n\n    Hint Resolve derivative_unfold : core.\n    Hint Resolve observation_map_2 : core.\n    Hint Resolve continuation_map_denotes_derivative_1 : core.\n    Hint Resolve continuation_map_denotes_derivative_2 : core.\n\n    (** Regex matching, with correctness built into the return type *)\n    Fixpoint regex_match r s : {denotation r s} + {~denotation r s}.\n      destruct s.\n      - destruct (includes_nil r); t.\n      - destruct (regex_match (continuation_map s r) s0); t.\n    Defined.\n\n    Section LazyEvaluation.\n\n      (** Check if a regex represents the empty language. *)\n      Fixpoint is_empty r : {forall s, ~denotation r s} + {exists s, denotation r s}.\n        destruct r; simpl; t.\n        - destruct (is_empty r1); t.\n          destruct (is_empty r2); t.\n        - destruct (is_empty r1); t.\n          destruct (is_empty r2); t.\n      Defined.\n\n      (** This (probably more efficient) matcher first checks if the regex\n      language has become empty; if so, it stops matching and uses the is_empty\n      proof underneath a right constructor *)\n      Fixpoint lazy_regex_match r s : {denotation r s} + {~denotation r s}.\n        destruct s.\n        - destruct (includes_nil r); t.\n        - destruct (is_empty (continuation_map s r)); t.\n          destruct (regex_match (continuation_map s r) s0); t.\n      Defined.\n\n    End LazyEvaluation.\n\n  End Matching.\n\nEnd RegularExpressions.\n\n(* Local Variables: *)\n(* company-coq-local-symbols: ((\"Sigma\" . ?Σ)) *)\n(* End: *)\n", "meta": {"author": "tchajed", "repo": "regex-derivative", "sha": "f05440c5d6f8f9e53b3be6d8a7799fecfad08d18", "save_path": "github-repos/coq/tchajed-regex-derivative", "path": "github-repos/coq/tchajed-regex-derivative/regex-derivative-f05440c5d6f8f9e53b3be6d8a7799fecfad08d18/regex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.715971153248044}}
{"text": "From Equations Require Import Equations.\nRequire Import Arith.\nRequire Import Lia.\nRequire Import Coq.Lists.SetoidList. (* For Sorted *)\nRequire Import Sumbool.\nRequire Export JMeq.\nImport Sigma_Notations.\nRequire Import Coq.Program.Tactics.\n\nNotation dec x := (sumbool_of_bool x).\n  \n\nLemma lte_div2 : \nforall (n m : nat),\n    n <= m\n  ->\n    Nat.div2 n <= Nat.div2 m.\n    \nintros.\nrewrite Nat.div2_div.\nrewrite Nat.div2_div.\napply Nat.div_le_mono.\nlia.\napply H.\nQed.\n\n\nLemma lte_plus_div2 : \nforall (n m : nat),\n    m <= (n + m) / 2\n  -> \n    m <= n.\n    \nintros.\napply mult_le_compat_l with (p:= 2) in H.\napply Nat.le_trans with (p:= 2*(n+m)/2) in H.\nreplace (2*(n+m)) with ((n+m)*2) in H.\nrewrite Nat.div_mul with (b:= 2) in H.\nlia.\nlia.\nlia.\napply Nat.div_mul_le.\nlia.\nQed.\n\n\nLemma lt_div2_min : \nforall (n m : nat),\n    n < m\n  ->\n    Nat.div2 (n + m) - n < m - n.\n\nintros.\ndestruct (Nat.div2 (n+m)<? m) as []eqn:?.\napply Nat.ltb_lt in Heqb.\nlia.\napply Nat.ltb_ge in Heqb.\nrewrite Nat.div2_div in Heqb.\napply lte_plus_div2 in Heqb.\napply le_not_lt in Heqb.\ncontradiction.\nQed.\n\n\nSet Program Mode.\n\n\nEquations? binarysearch (l: list nat) (target L R :nat) : option nat by wf (R-L) lt:=\nbinarysearch l t L R with dec(R <=? L) =>\n  | left H => None;\n  | right H with dec(t =? nth (Nat.div2 L+R) l (t+1))=> \n      | left H => Some (Nat.div2 L+R);\n      | right H => if nth ((Nat.div2 L+R)) l (t+1) <? t \n                     then binarysearch l t ((Nat.div2 (L+R))+1) R\n                     else binarysearch l t L (Nat.div2 (L+R)).  \n                     \n                     \napply leb_complete_conv in H.\napply Nat.le_lt_trans with (m:= R - (Nat.div2 (2*L) + 1)).\nrewrite Nat.sub_add_distr.\nrewrite Nat.sub_add_distr.\napply Nat.sub_le_mono_r.\napply Nat.sub_le_mono_l.\napply lte_div2.\nlia.\nrewrite Nat.div2_double.\nrewrite Nat.sub_add_distr.\napply Nat.sub_gt in H.\nlia.\napply leb_complete_conv in H.\napply lt_div2_min.\napply H.\nDefined.\n\nCheck binarysearch_elim.\n\n(* The return type containing the correctness property: *)\n(* {p: option nat | Sorted le l -> (forall (e:nat), p=Some e -> nth e l (target+1) = target) /\\ (p=None -> ~ In target l)}. *)\n \n(* This is one part of the correctness property: *)\nTheorem binarysearch_correct : forall (l : list nat) (a index : nat),\nSorted le l\n->\n~ In a l\n-> \nbinarysearch l a 0 (length l) = None.\n\nintros.\napply binarysearch_elim.\nintros.\ntrivial.\nintros.\ninversion e.\napply beq_nat_true in H2.\nAdmitted.\n(* 2:{\nintros.\ndestruct (nth (Nat.div2 L + R) l0 0 <? target) as []eqn:?.\napply H1.\napply H2. *)\n\n", "meta": {"author": "KirstenHagenaars", "repo": "BachelorThesis", "sha": "3c6dec361e51d635dd2e1cabc8dfcea9540891a0", "save_path": "github-repos/coq/KirstenHagenaars-BachelorThesis", "path": "github-repos/coq/KirstenHagenaars-BachelorThesis/BachelorThesis-3c6dec361e51d635dd2e1cabc8dfcea9540891a0/Code/BinarysearchTry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7158249048406805}}
{"text": "Require Import Coq.Setoids.Setoid.\nRequire Import ELRefine.Refinement.\n\n(** The abstract domain **)\nInductive Parity := Even | Odd.\n\n(** The Abstraction Relation **)\nInductive Abstracts : Parity -> nat -> Prop :=\n| A_Even : Abstracts Even 0\n| A_Odd : Abstracts Odd 1\n| A_SS : forall n p, Abstracts p n -> Abstracts p (2 + n).\n\n(** Plus on the abstract domain **)\nDefinition plusParity (a b : Parity) : Parity :=\n  match a , b with\n    | Even , Odd\n    | Odd , Even => Odd\n    | _ , _ => Even\n  end.\n\n(** Lemmas **)\nDefinition opp (p : Parity) : Parity :=\n  match p with\n    | Even => Odd\n    | Odd => Even\n  end.\n\nLemma Abstracts_SS : forall n p, Abstracts p n <-> Abstracts p (S (S n)).\nProof.\n  intros.\n  destruct n; intuition; repeat constructor; auto.\n  inversion H; auto.\n  inversion H. auto.\nQed.\n\nTheorem Abstracts_S : forall n p, Abstracts p n <-> Abstracts (opp p) (S n).\nProof.\n  induction n.\n  { intros. split. inversion 1. subst. constructor.\n    destruct p; simpl; try constructor. inversion 1. }\n  { intros.\n    rewrite <- Abstracts_SS.\n    specialize (IHn (opp p)); symmetry.\n    destruct p; auto. }\nQed.\n\nTheorem plusParity_plus\n: hrespectful Abstracts (hrespectful Abstracts Abstracts) plusParity plus.\nProof.\n  repeat red; intros.\n  induction H; simpl; intros; try solve [ repeat constructor ].\n  { destruct x0; assumption. }\n  { rewrite Abstracts_S.\n    constructor. destruct x0; assumption. }\n  { rewrite <- Abstracts_SS. assumption. }\nQed.\n", "meta": {"author": "gmalecha", "repo": "coq-refinement", "sha": "93b31e167fe92315917afbd65367cc5a5bb3e830", "save_path": "github-repos/coq/gmalecha-coq-refinement", "path": "github-repos/coq/gmalecha-coq-refinement/coq-refinement-93b31e167fe92315917afbd65367cc5a5bb3e830/examples/Parity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.924141826246517, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7158249032223796}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection IntLogic.\n\nVariables A B C : Prop.\n\nLemma notTrue_iff_False : (~ True) <-> False.\nProof.\nAdmitted.\n\nLemma dne_False : ~ ~ False -> False.\nProof.\nAdmitted.\n\nLemma dne_True : ~ ~ True -> True.\nProof.\nAdmitted.\n\nLemma weak_peirce : ((((A -> B) -> A) -> A) -> B) -> B.\nProof.\nAdmitted.\n\nLemma imp_trans : (A -> B) -> (B -> C) -> (A -> C).\nProof.\nAdmitted.\n\nEnd IntLogic.\n\n\n(** Let's get familiarize ourselves with some lemmas from [ssrbool] module.\n    The proofs are very easy, so the lemma statements are more important here.\n *)\nSection BooleanLogic.\n\nVariables (A B : Type) (x : A) (f : A -> B) (a b : bool) (vT vF : A).\n\nLemma negbNE : ~~ ~~ b -> b.\nProof.\nAdmitted.\n\n(** Figure out what [involutive] and [injective] mean\n    using Coq's interactive queries. Prove the lemmas.\n    Hint: to unfold a definition in the goal use [rewrite /definition] command.\n*)\nLemma negbK : involutive negb.\nProof.\nAdmitted.\n\nLemma negb_inj : injective negb.\nProof.\nAdmitted.\n\nLemma ifT : b -> (if b then vT else vF) = vT.\nProof.\nAdmitted.\n\nLemma ifF : b = false -> (if b then vT else vF) = vF.\nProof.\nAdmitted.\n\nLemma if_same : (if b then vT else vT) = vT.\nProof.\nAdmitted.\n\nLemma if_neg : (if ~~ b then vT else vF) = if b then vF else vT.\nProof.\nAdmitted.\n\nLemma fun_if : f (if b then vT else vF) = if b then f vT else f vF.\nProof.\nAdmitted.\n\nLemma if_arg (fT fF : A -> B) :\n  (if b then fT else fF) x = if b then fT x else fF x.\nProof.\nAdmitted.\n\nLemma andbK : a && b || a = a.\nProof.\nAdmitted.\n\n(** Find out what [left_id], [right_id] mean\n    using Coq's interactive queries. Prove the lemmas.\n *)\nLemma addFb : left_id false addb.    (* [addb] means XOR (eXclusive OR operation) *)\nProof.\nAdmitted.\n\nLemma addbF : right_id false addb.\nProof.\nAdmitted.\n\nLemma addbC : commutative addb.\nProof.\nAdmitted.\n\nLemma addbA : associative addb.\nProof.\nAdmitted.\n\n\n(** Formulate analogous laws (left/right identity, commutativity, associativity)\n    for boolean AND and OR and proove those.\n    Find the names of corresponding lemmas in the standard library using\n    [Search] command. For instance: [Search _ andb left_id.]\n    Have you noticed the naming patterns?\n *)\n\nEnd BooleanLogic.\n\n\n\nSection NaturalNumbers.\n(** Figure out what [cancel], [succn], [predn] mean\n    using Coq's interactive queries. Prove the lemmas.\n *)\nLemma succnK : cancel succn predn.\nProof.\nAdmitted.\n\nLemma add0n : left_id 0 addn.\nProof.\nAdmitted.\n\nLemma addSn m n : m.+1 + n = (m + n).+1.\nProof.\nAdmitted.\n\nLemma add1n n : 1 + n = n.+1.\nProof.\nAdmitted.\n\nLemma add2n m : 2 + m = m.+2.\nProof.\nAdmitted.\n\nLemma subn0 : right_id 0 subn.\nProof.\nAdmitted.\n\nEnd NaturalNumbers.", "meta": {"author": "kudryashovaia", "repo": "coq", "sha": "ff0e2139e4c23091edb6fba3947170c392a35ae4", "save_path": "github-repos/coq/kudryashovaia-coq", "path": "github-repos/coq/kudryashovaia-coq/coq-ff0e2139e4c23091edb6fba3947170c392a35ae4/homework/hw02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7158248870854041}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import NZAxioms NZBase Decidable OrdersTac.\n\nModule Type NZOrderProp\n(Import NZ : NZOrdSig')(Import NZBase : NZBaseProp NZ).\n\nInstance le_wd : Proper (eq==>eq==>iff) le.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_wd\".  \nintros n n' Hn m m' Hm. now rewrite <- !lt_succ_r, Hn, Hm.\nQed.\n\nLtac le_elim H := rewrite lt_eq_cases in H; destruct H as [H | H].\n\nTheorem lt_le_incl : forall n m, n < m -> n <= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_le_incl\".  \nintros. apply lt_eq_cases. now left.\nQed.\n\nTheorem le_refl : forall n, n <= n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_refl\".  \nintro. apply lt_eq_cases. now right.\nQed.\n\nTheorem lt_succ_diag_r : forall n, n < S n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_succ_diag_r\".  \nintro n. rewrite lt_succ_r. apply le_refl.\nQed.\n\nTheorem le_succ_diag_r : forall n, n <= S n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_succ_diag_r\".  \nintro; apply lt_le_incl; apply lt_succ_diag_r.\nQed.\n\nTheorem neq_succ_diag_l : forall n, S n ~= n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.neq_succ_diag_l\".  \nintros n H. apply (lt_irrefl n). rewrite <- H at 2. apply lt_succ_diag_r.\nQed.\n\nTheorem neq_succ_diag_r : forall n, n ~= S n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.neq_succ_diag_r\".  \nintro n; apply neq_sym, neq_succ_diag_l.\nQed.\n\nTheorem nlt_succ_diag_l : forall n, ~ S n < n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.nlt_succ_diag_l\".  \nintros n H. apply (lt_irrefl (S n)). rewrite lt_succ_r. now apply lt_le_incl.\nQed.\n\nTheorem nle_succ_diag_l : forall n, ~ S n <= n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.nle_succ_diag_l\".  \nintros n H; le_elim H.\nfalse_hyp H nlt_succ_diag_l. false_hyp H neq_succ_diag_l.\nQed.\n\nTheorem le_succ_l : forall n m, S n <= m <-> n < m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_succ_l\".  \nintro n; nzinduct m n.\nsplit; intro H. false_hyp H nle_succ_diag_l. false_hyp H lt_irrefl.\nintro m.\nrewrite (lt_eq_cases (S n) (S m)), !lt_succ_r, (lt_eq_cases n m), succ_inj_wd.\nrewrite or_cancel_r.\nreflexivity.\nintros LE EQ; rewrite EQ in LE; false_hyp LE nle_succ_diag_l.\nintros LT EQ; rewrite EQ in LT; false_hyp LT lt_irrefl.\nQed.\n\n\n\nTheorem le_gt_cases : forall n m, n <= m \\/ n > m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_gt_cases\".  \nintros n m; nzinduct n m.\nleft; apply le_refl.\nintro n. rewrite lt_succ_r, le_succ_l, !lt_eq_cases. intuition.\nQed.\n\nTheorem lt_trichotomy : forall n m,  n < m \\/ n == m \\/ m < n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_trichotomy\".  \nintros n m. generalize (le_gt_cases n m); rewrite lt_eq_cases; tauto.\nQed.\n\nNotation lt_eq_gt_cases := lt_trichotomy (only parsing).\n\n\n\nTheorem lt_asymm : forall n m, n < m -> ~ m < n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_asymm\".  \nintros n m; nzinduct n m.\nintros H; false_hyp H lt_irrefl.\nintro n; split; intros H H1 H2.\napply lt_succ_r in H2. le_elim H2.\napply H; auto. apply le_succ_l. now apply lt_le_incl.\nrewrite H2 in H1. false_hyp H1 nlt_succ_diag_l.\napply le_succ_l in H1. le_elim H1.\napply H; auto. rewrite lt_succ_r. now apply lt_le_incl.\nrewrite <- H1 in H2. false_hyp H2 nlt_succ_diag_l.\nQed.\n\nNotation lt_ngt := lt_asymm (only parsing).\n\nTheorem lt_trans : forall n m p, n < m -> m < p -> n < p.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_trans\".  \nintros n m p; nzinduct p m.\nintros _ H; false_hyp H lt_irrefl.\nintro p. rewrite 2 lt_succ_r.\nsplit; intros H H1 H2.\napply lt_le_incl; le_elim H2; [now apply H | now rewrite H2 in H1].\nassert (n <= p) as H3 by (auto using lt_le_incl).\nle_elim H3. assumption. rewrite <- H3 in H2.\nelim (lt_asymm n m); auto.\nQed.\n\nTheorem le_trans : forall n m p, n <= m -> m <= p -> n <= p.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_trans\".  \nintros n m p. rewrite 3 lt_eq_cases.\nintros [LT|EQ] [LT'|EQ']; try rewrite EQ; try rewrite <- EQ';\ngeneralize (lt_trans n m p); auto with relations.\nQed.\n\n\n\nInstance lt_strorder : StrictOrder lt.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_strorder\".   split. exact lt_irrefl. exact lt_trans. Qed.\n\nInstance le_preorder : PreOrder le.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_preorder\".   split. exact le_refl. exact le_trans. Qed.\n\nInstance le_partialorder : PartialOrder _ le.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_partialorder\".  \nintros x y. compute. split.\nintro EQ; now rewrite EQ.\nrewrite 2 lt_eq_cases. intuition. elim (lt_irrefl x). now transitivity y.\nQed.\n\n\n\nDefinition lt_compat := lt_wd.\nDefinition lt_total := lt_trichotomy.\nDefinition le_lteq := lt_eq_cases.\n\nModule Private_OrderTac.\nModule IsTotal.\nDefinition eq_equiv := eq_equiv.\nDefinition lt_strorder := lt_strorder.\nDefinition lt_compat := lt_compat.\nDefinition lt_total := lt_total.\nDefinition le_lteq := le_lteq.\nEnd IsTotal.\nModule Tac := !MakeOrderTac NZ IsTotal.\nEnd Private_OrderTac.\nLtac order := Private_OrderTac.Tac.order.\n\n\n\nTheorem lt_neq : forall n m, n < m -> n ~= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_neq\".   order. Qed.\n\nTheorem le_neq : forall n m, n < m <-> n <= m /\\ n ~= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_neq\".   intuition order. Qed.\n\nTheorem eq_le_incl : forall n m, n == m -> n <= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.eq_le_incl\".   order. Qed.\n\nLemma lt_stepl : forall x y z, x < y -> x == z -> z < y.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_stepl\".   order. Qed.\n\nLemma lt_stepr : forall x y z, x < y -> y == z -> x < z.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_stepr\".   order. Qed.\n\nLemma le_stepl : forall x y z, x <= y -> x == z -> z <= y.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_stepl\".   order. Qed.\n\nLemma le_stepr : forall x y z, x <= y -> y == z -> x <= z.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_stepr\".   order. Qed.\n\nDeclare Left  Step lt_stepl.\nDeclare Right Step lt_stepr.\nDeclare Left  Step le_stepl.\nDeclare Right Step le_stepr.\n\nTheorem le_lt_trans : forall n m p, n <= m -> m < p -> n < p.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_lt_trans\".   order. Qed.\n\nTheorem lt_le_trans : forall n m p, n < m -> m <= p -> n < p.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_le_trans\".   order. Qed.\n\nTheorem le_antisymm : forall n m, n <= m -> m <= n -> n == m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_antisymm\".   order. Qed.\n\n\n\nTheorem le_succ_r : forall n m, n <= S m <-> n <= m \\/ n == S m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_succ_r\".  \nintros n m; rewrite lt_eq_cases. now rewrite lt_succ_r.\nQed.\n\nTheorem lt_succ_l : forall n m, S n < m -> n < m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_succ_l\".  \nintros n m H; apply le_succ_l; order.\nQed.\n\nTheorem le_le_succ_r : forall n m, n <= m -> n <= S m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_le_succ_r\".  \nintros n m LE. apply lt_succ_r in LE. order.\nQed.\n\nTheorem lt_lt_succ_r : forall n m, n < m -> n < S m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_lt_succ_r\".  \nintros. rewrite lt_succ_r. order.\nQed.\n\nTheorem succ_lt_mono : forall n m, n < m <-> S n < S m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.succ_lt_mono\".  \nintros n m. rewrite <- le_succ_l. symmetry. apply lt_succ_r.\nQed.\n\nTheorem succ_le_mono : forall n m, n <= m <-> S n <= S m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.succ_le_mono\".  \nintros n m. now rewrite 2 lt_eq_cases, <- succ_lt_mono, succ_inj_wd.\nQed.\n\nTheorem lt_0_1 : 0 < 1.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_0_1\".  \nrewrite one_succ. apply lt_succ_diag_r.\nQed.\n\nTheorem le_0_1 : 0 <= 1.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_0_1\".  \napply lt_le_incl, lt_0_1.\nQed.\n\nTheorem lt_1_2 : 1 < 2.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_1_2\".  \nrewrite two_succ. apply lt_succ_diag_r.\nQed.\n\nTheorem lt_0_2 : 0 < 2.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_0_2\".  \ntransitivity 1. apply lt_0_1. apply lt_1_2.\nQed.\n\nTheorem le_0_2 : 0 <= 2.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_0_2\".  \napply lt_le_incl, lt_0_2.\nQed.\n\n\n\nLtac order' := generalize lt_0_1 lt_1_2; order.\n\nTheorem lt_1_l : forall n m, 0 < n -> n < m -> 1 < m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_1_l\".  \nintros n m H1 H2. rewrite <- le_succ_l, <- one_succ in H1. order.\nQed.\n\n\n\n\n\nTheorem lt_ge_cases : forall n m, n < m \\/ n >= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_ge_cases\".  \nintros n m; destruct (le_gt_cases m n); intuition order.\nQed.\n\nTheorem le_ge_cases : forall n m, n <= m \\/ n >= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_ge_cases\".  \nintros n m; destruct (le_gt_cases n m); intuition order.\nQed.\n\nTheorem lt_gt_cases : forall n m, n ~= m <-> n < m \\/ n > m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_gt_cases\".  \nintros n m; destruct (lt_trichotomy n m); intuition order.\nQed.\n\n\n\nTheorem eq_decidable : forall n m, decidable (n == m).\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.eq_decidable\".  \nintros n m; destruct (lt_trichotomy n m) as [ | [ | ]];\n(right; order) || (left; order).\nQed.\n\n\n\nTheorem eq_dne : forall n m, ~ ~ n == m <-> n == m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.eq_dne\".  \nintros n m; split; intro H.\ndestruct (eq_decidable n m) as [H1 | H1].\nassumption. false_hyp H1 H.\nintro H1; now apply H1.\nQed.\n\nTheorem le_ngt : forall n m, n <= m <-> ~ n > m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_ngt\".   intuition order. Qed.\n\n\n\nTheorem nlt_ge : forall n m, ~ n < m <-> n >= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.nlt_ge\".   intuition order. Qed.\n\nTheorem lt_decidable : forall n m, decidable (n < m).\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_decidable\".  \nintros n m; destruct (le_gt_cases m n); [right|left]; order.\nQed.\n\nTheorem lt_dne : forall n m, ~ ~ n < m <-> n < m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_dne\".  \nintros n m; split; intro H.\ndestruct (lt_decidable n m) as [H1 | H1]; [assumption | false_hyp H1 H].\nintro H1; false_hyp H H1.\nQed.\n\nTheorem nle_gt : forall n m, ~ n <= m <-> n > m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.nle_gt\".   intuition order. Qed.\n\n\n\nTheorem lt_nge : forall n m, n < m <-> ~ n >= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_nge\".   intuition order. Qed.\n\nTheorem le_decidable : forall n m, decidable (n <= m).\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_decidable\".  \nintros n m; destruct (le_gt_cases n m); [left|right]; order.\nQed.\n\nTheorem le_dne : forall n m, ~ ~ n <= m <-> n <= m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_dne\".  \nintros n m; split; intro H.\ndestruct (le_decidable n m) as [H1 | H1]; [assumption | false_hyp H1 H].\nintro H1; false_hyp H H1.\nQed.\n\nTheorem nlt_succ_r : forall n m, ~ m < S n <-> n < m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.nlt_succ_r\".  \nintros n m; rewrite lt_succ_r. intuition order.\nQed.\n\n\n\nLemma lt_exists_pred_strong :\nforall z n m, z < m -> m <= n -> exists k, m == S k /\\ z <= k.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_exists_pred_strong\".  \nintro z; nzinduct n z.\norder.\nintro n; split; intros IH m H1 H2.\napply le_succ_r in H2. destruct H2 as [H2 | H2].\nnow apply IH. exists n. now split; [| rewrite <- lt_succ_r; rewrite <- H2].\napply IH. assumption. now apply le_le_succ_r.\nQed.\n\nTheorem lt_exists_pred :\nforall z n, z < n -> exists k, n == S k /\\ z <= k.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_exists_pred\".  \nintros z n H; apply lt_exists_pred_strong with (z := z) (n := n).\nassumption. apply le_refl.\nQed.\n\nLemma lt_succ_pred : forall z n, z < n -> S (P n) == n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_succ_pred\".  \nintros z n H.\ndestruct (lt_exists_pred _ _ H) as (n' & EQ & LE).\nrewrite EQ. now rewrite pred_succ.\nQed.\n\n\n\nSection Induction.\n\nVariable A : t -> Prop.\nHypothesis A_wd : Proper (eq==>iff) A.\n\nSection Center.\n\nVariable z : t.\n\nSection RightInduction.\n\nLet A' (n : t) := forall m, z <= m -> m < n -> A m.\nLet right_step :=   forall n, z <= n -> A n -> A (S n).\nLet right_step' :=  forall n, z <= n -> A' n -> A n.\nLet right_step'' := forall n, A' n <-> A' (S n).\n\nLemma rs_rs' :  A z -> right_step -> right_step'.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.rs_rs'\".  \nintros Az RS n H1 H2.\nle_elim H1. apply lt_exists_pred in H1. destruct H1 as [k [H3 H4]].\nrewrite H3. apply RS; trivial. apply H2; trivial.\nrewrite H3; apply lt_succ_diag_r.\nrewrite <- H1; apply Az.\nQed.\n\nLemma rs'_rs'' : right_step' -> right_step''.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.rs'_rs''\".  \nintros RS' n; split; intros H1 m H2 H3.\napply lt_succ_r in H3; le_elim H3;\n[now apply H1 | rewrite H3 in *; now apply RS'].\napply H1; [assumption | now apply lt_lt_succ_r].\nQed.\n\nLemma rbase : A' z.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.rbase\".  \nintros m H1 H2. apply le_ngt in H1. false_hyp H2 H1.\nQed.\n\nLemma A'A_right : (forall n, A' n) -> forall n, z <= n -> A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.A'A_right\".  \nintros H1 n H2. apply H1 with (n := S n); [assumption | apply lt_succ_diag_r].\nQed.\n\nTheorem strong_right_induction: right_step' -> forall n, z <= n -> A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.strong_right_induction\".  \nintro RS'; apply A'A_right; unfold A'; nzinduct n z;\n[apply rbase | apply rs'_rs''; apply RS'].\nQed.\n\nTheorem right_induction : A z -> right_step -> forall n, z <= n -> A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.right_induction\".  \nintros Az RS; apply strong_right_induction; now apply rs_rs'.\nQed.\n\nTheorem right_induction' :\n(forall n, n <= z -> A n) -> right_step -> forall n, A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.right_induction'\".  \nintros L R n.\ndestruct (lt_trichotomy n z) as [H | [H | H]].\napply L; now apply lt_le_incl.\napply L; now apply eq_le_incl.\napply right_induction. apply L; now apply eq_le_incl. assumption.\nnow apply lt_le_incl.\nQed.\n\nTheorem strong_right_induction' :\n(forall n, n <= z -> A n) -> right_step' -> forall n, A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.strong_right_induction'\".  \nintros L R n.\ndestruct (lt_trichotomy n z) as [H | [H | H]].\napply L; now apply lt_le_incl.\napply L; now apply eq_le_incl.\napply strong_right_induction. assumption. now apply lt_le_incl.\nQed.\n\nEnd RightInduction.\n\nSection LeftInduction.\n\nLet A' (n : t) := forall m, m <= z -> n <= m -> A m.\nLet left_step :=   forall n, n < z -> A (S n) -> A n.\nLet left_step' :=  forall n, n <= z -> A' (S n) -> A n.\nLet left_step'' := forall n, A' n <-> A' (S n).\n\nLemma ls_ls' :  A z -> left_step -> left_step'.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.ls_ls'\".  \nintros Az LS n H1 H2. le_elim H1.\napply LS; trivial. apply H2; [now apply le_succ_l | now apply eq_le_incl].\nrewrite H1; apply Az.\nQed.\n\nLemma ls'_ls'' : left_step' -> left_step''.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.ls'_ls''\".  \nintros LS' n; split; intros H1 m H2 H3.\napply le_succ_l in H3. apply lt_le_incl in H3. now apply H1.\nle_elim H3.\napply le_succ_l in H3. now apply H1.\nrewrite <- H3 in *; now apply LS'.\nQed.\n\nLemma lbase : A' (S z).\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lbase\".  \nintros m H1 H2. apply le_succ_l in H2.\napply le_ngt in H1. false_hyp H2 H1.\nQed.\n\nLemma A'A_left : (forall n, A' n) -> forall n, n <= z -> A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.A'A_left\".  \nintros H1 n H2. apply (H1 n); [assumption | now apply eq_le_incl].\nQed.\n\nTheorem strong_left_induction: left_step' -> forall n, n <= z -> A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.strong_left_induction\".  \nintro LS'; apply A'A_left; unfold A'; nzinduct n (S z);\n[apply lbase | apply ls'_ls''; apply LS'].\nQed.\n\nTheorem left_induction : A z -> left_step -> forall n, n <= z -> A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.left_induction\".  \nintros Az LS; apply strong_left_induction; now apply ls_ls'.\nQed.\n\nTheorem left_induction' :\n(forall n, z <= n -> A n) -> left_step -> forall n, A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.left_induction'\".  \nintros R L n.\ndestruct (lt_trichotomy n z) as [H | [H | H]].\napply left_induction. apply R. now apply eq_le_incl. assumption.\nnow apply lt_le_incl.\nrewrite H; apply R; now apply eq_le_incl.\napply R; now apply lt_le_incl.\nQed.\n\nTheorem strong_left_induction' :\n(forall n, z <= n -> A n) -> left_step' -> forall n, A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.strong_left_induction'\".  \nintros R L n.\ndestruct (lt_trichotomy n z) as [H | [H | H]].\napply strong_left_induction; auto. now apply lt_le_incl.\nrewrite H; apply R; now apply eq_le_incl.\napply R; now apply lt_le_incl.\nQed.\n\nEnd LeftInduction.\n\nTheorem order_induction :\nA z ->\n(forall n, z <= n -> A n -> A (S n)) ->\n(forall n, n < z  -> A (S n) -> A n) ->\nforall n, A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.order_induction\".  \nintros Az RS LS n.\ndestruct (lt_trichotomy n z) as [H | [H | H]].\nnow apply left_induction; [| | apply lt_le_incl].\nnow rewrite H.\nnow apply right_induction; [| | apply lt_le_incl].\nQed.\n\nTheorem order_induction' :\nA z ->\n(forall n, z <= n -> A n -> A (S n)) ->\n(forall n, n <= z -> A n -> A (P n)) ->\nforall n, A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.order_induction'\".  \nintros Az AS AP n; apply order_induction; try assumption.\nintros m H1 H2. apply AP in H2; [|now apply le_succ_l].\nnow rewrite pred_succ in H2.\nQed.\n\nEnd Center.\n\nTheorem order_induction_0 :\nA 0 ->\n(forall n, 0 <= n -> A n -> A (S n)) ->\n(forall n, n < 0  -> A (S n) -> A n) ->\nforall n, A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.order_induction_0\".  exact ((order_induction 0)). Qed.\n\nTheorem order_induction'_0 :\nA 0 ->\n(forall n, 0 <= n -> A n -> A (S n)) ->\n(forall n, n <= 0 -> A n -> A (P n)) ->\nforall n, A n.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.order_induction'_0\".  exact ((order_induction' 0)). Qed.\n\n\n\nTheorem lt_ind : forall (n : t),\nA (S n) ->\n(forall m, n < m -> A m -> A (S m)) ->\nforall m, n < m -> A m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_ind\".  \nintros n H1 H2 m H3.\napply right_induction with (S n); [assumption | | now apply le_succ_l].\nintros; apply H2; try assumption. now apply le_succ_l.\nQed.\n\n\n\nTheorem le_ind : forall (n : t),\nA n ->\n(forall m, n <= m -> A m -> A (S m)) ->\nforall m, n <= m -> A m.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.le_ind\".  \nintros n H1 H2 m H3.\nnow apply right_induction with n.\nQed.\n\nEnd Induction.\n\nTactic Notation \"nzord_induct\" ident(n) :=\ninduction_maker n ltac:(apply order_induction_0).\n\nTactic Notation \"nzord_induct\" ident(n) constr(z) :=\ninduction_maker n ltac:(apply order_induction with z).\n\nSection WF.\n\nVariable z : t.\n\nLet Rlt (n m : t) := z <= n < m.\nLet Rgt (n m : t) := m < n <= z.\n\nInstance Rlt_wd : Proper (eq ==> eq ==> iff) Rlt.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.Rlt_wd\".  \nintros x1 x2 H1 x3 x4 H2; unfold Rlt. rewrite H1; now rewrite H2.\nQed.\n\nInstance Rgt_wd : Proper (eq ==> eq ==> iff) Rgt.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.Rgt_wd\".  \nintros x1 x2 H1 x3 x4 H2; unfold Rgt; rewrite H1; now rewrite H2.\nQed.\n\nTheorem lt_wf : well_founded Rlt.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.lt_wf\".  \nunfold well_founded.\napply strong_right_induction' with (z := z).\nauto with typeclass_instances.\nintros n H; constructor; intros y [H1 H2].\napply nle_gt in H2. elim H2. now apply le_trans with z.\nintros n H1 H2; constructor; intros m [H3 H4]. now apply H2.\nQed.\n\nTheorem gt_wf : well_founded Rgt.\nProof. hammer_hook \"NZOrder\" \"NZOrder.NZOrderProp.gt_wf\".  \nunfold well_founded.\napply strong_left_induction' with (z := z).\nauto with typeclass_instances.\nintros n H; constructor; intros y [H1 H2].\napply nle_gt in H2. elim H2. now apply le_lt_trans with n.\nintros n H1 H2; constructor; intros m [H3 H4].\napply H2. assumption. now apply le_succ_l.\nQed.\n\nEnd WF.\n\nEnd NZOrderProp.\n\n\n\n\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/NatInt/NZOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7157956132127757}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) (lf1 : natural)\n  : natural := mult x (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj194_coqofml_VbyEGs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.715779328330055}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := mult y (plus x Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj276_coqofml_e6FyFU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7157793281114802}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := mult y (plus Zero x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj276_coqofml_QinoIV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7157793188146124}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  plus x (plus (Succ y) lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj182_coqofml_D9SS1N.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7157296791116827}}
{"text": "(* week_36d_fac.v *)\n(* dIFP 2014-2015, Q1, Week 36 *)\n(* Olivier Danvy <danvy@cs.au.dk> *)\n\n(* ********** *)\n\nRequire Import Arith Bool.\n\nRequire Import unfold_tactic.\n\n(* ********** *)\n\nNotation \"A === B\" := (beq_nat A B) (at level 70, right associativity).\n\nDefinition unit_tests_for_factorial (fac : nat -> nat) :=\n  (fac 0 === 1)\n  &&\n  (fac 1 === 1)\n  &&\n  (fac 5 === 120).\n\n(* ********** *)\n\nDefinition specification_of_factorial (fac : nat -> nat) :=\n  (fac O = 1)\n  /\\\n  (forall n' : nat,\n    fac (S n') = (S n') * (fac n')).\n\nProposition there_is_only_one_factorial_function :\n  forall fac1 fac2 : nat -> nat,\n    specification_of_factorial fac1 ->\n    specification_of_factorial fac2 ->\n    forall n : nat,\n      fac1 n = fac2 n.\nProof.\n  intros fac1 fac2 S_fac1 S_fac2 n.\n  unfold specification_of_factorial in S_fac1.\n  destruct S_fac1 as [H_fac1_bc H_fac1_ic].\n  unfold specification_of_factorial in S_fac2.\n  destruct S_fac2 as [H_fac2_bc H_fac2_ic].\n\n  induction n as [ | n' IHn'].\n\n  rewrite -> H_fac1_bc.\n  rewrite -> H_fac2_bc.\n  reflexivity.\n\n  rewrite -> (H_fac1_ic n').\n  rewrite -> (H_fac2_ic n').\n  rewrite -> IHn'.\n  \n  reflexivity.\n\n Qed.\n(* ********** *)\n\nFixpoint fac_ds (n : nat) :=\n  match n with\n    | 0 => 1\n    | S n' => (S n') * (fac_ds n')\n  end.\n\nDefinition fac_v0 (n : nat) :=\n  fac_ds n.\n\nCompute unit_tests_for_factorial fac_v0.\n\n(* The two mandatory unfold lemmas: *)\n\nLemma unfold_fac_ds_bc :\n  fac_ds 0 = 1.\nProof.\n  unfold_tactic fac_ds.\nQed.\n\nLemma unfold_fac_ds_ic :\n  forall n' : nat,\n    fac_ds (S n') = (S n') * (fac_ds n').\nProof.\n  unfold_tactic fac_ds.\nQed.\n\nTheorem fac_v0_satisfies_the_specification_of_factorial :\n  specification_of_factorial fac_v0.\nProof.\n  unfold specification_of_factorial.\n  split.\n    unfold fac_v0.\n    apply unfold_fac_ds_bc.\n  intro n'.\n  unfold fac_v0.\n  apply (unfold_fac_ds_ic n').\nQed.\n\n  \n(* ********** *)\n\nFixpoint fac_acc (n a : nat) :=\n  match n with\n    | 0 => a\n    | S n' => fac_acc n' (S n' * a)\n  end.\n\nDefinition fac_v1 (n : nat) :=\n  fac_acc n 1.\n\nCompute unit_tests_for_factorial fac_v1.\n\n(* The two mandatory unfold lemmas: *)\n\nLemma unfold_fac_acc_bc :\n  forall a : nat,\n    fac_acc 0 a = a.\nProof.\n  unfold_tactic fac_acc.\nQed.\n\nLemma unfold_fac_acc_ic :\n  forall n' a : nat,\n    fac_acc (S n') a = fac_acc n' (S n' * a).\nProof.\n  unfold_tactic fac_acc.\nQed.\n\nTheorem fac_v1_satisfies_the_specification_of_factorial_first_try :\n  specification_of_factorial fac_v1.\nProof.\n  unfold specification_of_factorial.\n  unfold fac_v1.\n\n  split.\n  apply (unfold_fac_acc_bc 1).\n\n  intro n'.\n  rewrite -> (unfold_fac_acc_ic n' 1).\n  Check mult_1_r.\n  rewrite -> (mult_1_r (S n')).\n Abort.\n\nLemma about_fac_acc_tentative :\n  forall n a : nat,\n    fac_acc n a = a * (fac_acc n 1).\nProof.\nAdmitted.\n\nTheorem fac_v1_satisfies_the_specification_of_factorial_second_try :\n  specification_of_factorial fac_v1.\nProof.\n  unfold specification_of_factorial.\n  unfold fac_v1.\n\n  split.\n  apply (unfold_fac_acc_bc 1).\n\n  intro n'.\n  rewrite -> (unfold_fac_acc_ic n' 1).\n  Check mult_1_r.\n  rewrite -> (mult_1_r (S n')).\n  rewrite -> (about_fac_acc_tentative n' (S n')).\n  reflexivity.\nAbort.\n\nLemma about_fac_acc :\n  forall n a : nat,\n    fac_acc n a = a * (fac_acc n 1).\nProof.\n  intros n a.\n  induction n as [ | n' IHn'].\n\n  rewrite -> (unfold_fac_acc_bc a).\n  rewrite -> (unfold_fac_acc_bc 1).\n  rewrite -> (mult_1_r a).\n  reflexivity.\n\n  rewrite -> (unfold_fac_acc_ic n' a).\n  rewrite -> (unfold_fac_acc_ic n' 1).\n  rewrite -> (mult_1_r (S n')).\n  \n  Restart.\n\n  intro n.\n  induction n as [ | n' IHn'].\n  intro a.\n  rewrite -> (unfold_fac_acc_bc a).\n  rewrite -> (unfold_fac_acc_bc 1).\n  rewrite -> (mult_1_r a).\n  reflexivity.\n\n  intro a.\n  rewrite -> (unfold_fac_acc_ic n' a).\n  rewrite -> (unfold_fac_acc_ic n' 1).\nAbort. (* DU NÅEDE HERTIL *)\n(* OG DU MANGLER AT SKRIVE NOGET IND ET ANDET STED OGSÅ *)\n\n(* ********** *)\n\nFixpoint fac_cps (ans : Type) (n : nat) (k : nat -> ans) :=\n  match n with\n    | 0 => k 1\n    | S n' => fac_cps ans n' (fun v => k (S n' * v))\n  end.\n\nDefinition fac_v2 (n : nat) :=\n  fac_cps nat n (fun v => v).\n\nCompute unit_tests_for_factorial fac_v2.\n\n(* The two mandatory unfold lemmas: *)\n\nLemma unfold_fac_cps_bc :\n  forall (ans : Type)\n         (k : nat -> ans),\n    fac_cps ans 0 k = k 1.\nProof.\n  unfold_tactic fac_cps.\nQed.\n\nLemma unfold_fac_cps_ic :\n  forall (ans : Type)\n         (n' : nat)\n         (k : nat -> ans),\n    fac_cps ans (S n') k = fac_cps ans n' (fun v => k (S n' * v)).\nProof.\n  unfold_tactic fac_cps.\nQed.\n\nLemma about_fac_cps :\n  forall (n : nat)\n         (k : nat -> nat),\n    fac_cps nat n k = k (fac_cps nat n (fun v => v)).\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n\n  intro k.\n  rewrite -> (unfold_fac_cps_bc nat k).\n  rewrite -> (unfold_fac_cps_bc nat (fun v : nat => v)).\n  reflexivity.\n\n  intro k.\n  rewrite -> (unfold_fac_cps_ic nat n' k).\n  rewrite -> (IHn' (fun v : nat => k (S n' * v))).\n  rewrite -> (unfold_fac_cps_ic nat n' (fun v : nat => v)).\n  rewrite -> (IHn' (fun v : nat => S n' * v)).\n  reflexivity.\nQed.\n\nTheorem fac_v2_satisfies_the_specification_of_factorial :\n  specification_of_factorial fac_v2.\nProof.\n  unfold specification_of_factorial.\n  unfold fac_v2.\n  split.\n  \n  apply (unfold_fac_cps_bc nat (fun v => v)).\n\n  intro n'.\n  rewrite -> (unfold_fac_cps_ic nat n' (fun v => v)).\n  rewrite -> (about_fac_cps n' (fun v => S n' * v)).\n  reflexivity.\nQed.\n\n(* ********** *)\n\n(* end of week_36d_fac.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/week_36d_fac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7156988224974558}}
{"text": "(* Hernán Gurmendi *)\n\nSet Asymmetric Patterns.\n\nSection Ejercicio1.\n\nInductive list (A : Set) : Set :=\n  | emptyL : list A\n  | cons : A -> list A -> list A.\n\nInductive bintree (A : Set) : Set :=\n  | emptyBT : bintree A\n  | merge : bintree A -> A -> bintree A -> bintree A.\n\n\nInductive array (A : Set) : nat -> Set :=\n  | emptyA : array A 0\n  | add : forall (n : nat), A -> array A n -> array A (S n).\n\nInductive matrix (A : Set) : nat -> nat -> Set :=\n  | oneCol : forall n : nat, array A n -> matrix A n 1\n  | addCol : forall n m : nat, array A n -> matrix A n m -> matrix A n (S m).\n\nInductive leq : nat -> nat -> Prop :=\n  | leq0 : forall m : nat, leq 0 m\n  | leqS : forall n m : nat, leq n m -> leq (S n) (S m).\n\nInductive eq_list (A : Set) : list A -> list A -> Prop :=\n  | eqlistE : eq_list A (emptyL A) (emptyL A)\n  | eqlistC : forall (l r : list A) (x : A), eq_list A l r -> eq_list A (cons A x l) (cons A x r).\n\nInductive eq_list' (A : Set) (R : A -> A -> Prop) : list A -> list A -> Prop :=\n  | eqlistE' : eq_list' A R (emptyL A) (emptyL A)\n  | eqlistC' : forall (l r : list A) (x y : A), eq_list' A R l r -> R x y -> eq_list' A R (cons A x l) (cons A y r).\n\nInductive sorted (A : Set) (R : A -> A -> Prop) : list A -> Prop :=\n  | sortedE : sorted A R (emptyL A)\n  | sortedS : forall x : A, sorted A R (cons A x (emptyL A)) (* Singleton *)\n  | sortedC : forall (x y : A) (l : list A), R x y -> sorted A R (cons A x (cons A y l)).\n\nInductive mirror (A : Set) : bintree A -> bintree A -> Prop :=\n  | mirrorE : mirror A (emptyBT A) (emptyBT A)\n  | mirrorM : forall (x : A) (ll lr rl rr : bintree A), mirror A ll rr -> mirror A lr rl -> mirror A (merge A ll x lr) (merge A rl x rr).\n\nInductive isomorfo (A : Set) : bintree A -> bintree A -> Prop :=\n  | isomorfoE : isomorfo A (emptyBT A) (emptyBT A)\n  | isomorfoM : forall (ll lr rl rr : bintree A) (x y : A), isomorfo A ll rl -> isomorfo A lr rr -> isomorfo A (merge A ll x lr) (merge A rl y rr).\n\nEnd Ejercicio1.\n\nSection Ejercicio3.\n\nFixpoint sum (n m : nat) : nat :=\n    match n, m with\n    | 0, m     => m\n    | (S n), m => S (sum n m)\n    end.\n\nFixpoint prod (n m : nat) : nat :=\n    match n, m with\n    | 0, m     => 0\n    | (S n), m => sum m (prod n m)\n    end.\n\nFixpoint pot (n m : nat) : nat :=\n    match m with\n    | 0     => 1\n    | (S m) => prod n (pot n m)\n    end.\n\nEnd Ejercicio3.\n\nSection Ejercicio4.\n\nFixpoint length (A : Set) (l : list A) : nat :=\n    match l with\n    | emptyL    => 0\n    | cons x xs => 1 + length A xs\n    end.\n\nFixpoint length' (A : Set) (l : list A) :=\n    match l with\n    | emptyL    => 0\n    | cons _ xs => S (length' A xs)\n    end.\n\nFixpoint append (A : Set) (l r : list A) : list A :=\n    match l with\n    | emptyL    => r\n    | cons x xs => cons A x (append A xs r)\n    end.\n\nFixpoint reverse (A : Set) (l : list A) : list A :=\n    match l with\n    | emptyL    => emptyL A\n    | cons x xs => append A (reverse A xs) (cons A x (emptyL A))\n    end.\n\nFixpoint filter (A : Set) (p : A -> bool) (l : list A) : list A :=\n    match l with\n    | emptyL    => emptyL A\n    | cons x xs =>\n        match (p x) with\n        | true  => cons A x (filter A p xs)\n        | false => filter A p xs\n        end\n    end.\n\nFixpoint map (A B : Set) (f : A -> B) (l : list A) : list B :=\n    match l with\n    | emptyL    => emptyL B\n    | cons x xs => cons B (f x) (map A B f xs)\n    end.\n\nFixpoint exists_ (A : Set) (p : A -> bool) (l : list A) : bool :=\n    match l with\n    | emptyL    => false\n    | cons x xs =>\n        match (p x) with\n        | false => exists_ A p xs\n        | true  => true\n        end\n    end.\n\nEnd Ejercicio4.\n\nSection Ejercicio5.\n\nFixpoint inverse (A : Set) (t : bintree A) : bintree A :=\n  match t with\n  | emptyBT     => emptyBT A\n  | merge l x r => merge A (inverse A r) x (inverse A l)\n  end.\n\nEnd Ejercicio5.\n\nSection Ejercicio9.\n\nLemma SumO : forall n : nat, sum n 0 = n /\\ sum 0 n = n.\nProof.\n  intros.\n  induction n; split; simpl.\n  - reflexivity.\n  - reflexivity.\n  - elim IHn. intros. rewrite H. reflexivity.\n  - reflexivity.\nQed.\n\nLemma SumS : forall n m : nat, sum n (S m) = sum (S n) m.\nProof.\n  intros.\n  induction n; simpl.\n  - reflexivity.\n  - rewrite IHn. reflexivity.\nQed.\n\nLemma SumAsoc : forall n m p : nat, sum n (sum m p) = sum (sum n m) p.\nProof.\n  intros.\n  induction n; simpl.\n  - reflexivity.\n  - rewrite IHn. reflexivity.\nQed.\n\nLemma SumConm : forall n m : nat, sum n m = sum m n.\nProof.\n  intros.\n  induction n; simpl.\n  - induction m; simpl.\n    + reflexivity.\n    + rewrite <- IHm. reflexivity.\n  - rewrite IHn. rewrite SumS. simpl. reflexivity.\nQed.\n\nEnd Ejercicio9.\n\nSection Ejercicio12.\n\nLemma L7 : forall (A B : Set) (l m : list A) (f : A -> B),\n  map A B f (append A l m) = append B (map A B f l) (map A B f m).\nProof.\n  intros.\n  induction l; simpl.\n  - reflexivity.\n  - rewrite IHl. reflexivity.\nQed.\n\nLemma L8 : forall (A : Set) (l m : list A) (P : A -> bool),\n  filter A P (append A l m) = append A (filter A P l) (filter A P m).\nProof.\n  intros.\n  induction l; simpl.\n  - reflexivity.\n  - case (P a); simpl; rewrite IHl; reflexivity.\nQed.\n\nLemma L9 : forall (A : Set) (l : list A) (P : A -> bool),\n  filter A P (filter A P l) = filter A P l.\nProof.\n  intros.\n  induction l; simpl.\n  - reflexivity.\n  - assert (P a = true \\/ P a =  false). case (P a); [left | right]; reflexivity.\n    elim H; intros Assumption; rewrite Assumption; simpl.\n    + rewrite Assumption. rewrite IHl. reflexivity.\n    + rewrite IHl. reflexivity.\nQed.\n\nLemma L10 : forall (A : Set) (l m n : list A),\n  append A l (append A m n) = append A (append A l m) n.\nProof.\n  intros.\n  induction l; simpl.\n  - reflexivity.\n  - rewrite IHl. reflexivity.\nQed.\n\nEnd Ejercicio12.\n\nSection Ejercicio14.\n\nLemma Ej14 : forall (A : Set) (t : bintree A), mirror A (inverse A t) t.\nProof.\n  intros.\n  induction t; simpl.\n  - apply mirrorE.\n  - apply mirrorM; assumption.\nQed.\n\nEnd Ejercicio14.\n\nSection Ejercicio17.\n\nInductive posfijo (A : Set) : list A -> list A -> Prop :=\n  | posfE : forall l : list A, posfijo A l l\n  | posfC : forall (l1 l2 : list A) (x : A), posfijo A l1 l2 -> posfijo A l1 (cons A x l2).\n\nLemma Ej17_2_1 : forall (A : Set) (l1 l2 l3 : list A), l2 = append A l3 l1 -> posfijo A l1 l2.\nProof.\n  intros.\n  rewrite H.\n  clear H.\n  induction l3; simpl.\n  - apply posfE.\n  - apply posfC. apply IHl3.\nQed.\n\nLemma Ej17_2_2 : forall (A : Set) (l1 l2 : list A), posfijo A l1 l2 -> exists l3 : list A, l2 = append A l3 l1.\nProof.\n  intros.\n  induction H.\n  - exists (emptyL A). simpl. reflexivity.\n  - elim IHposfijo. intros. rewrite H0. exists (cons A x x0). simpl. reflexivity.\nQed.\n\nLemma Ej17_3_1 : forall (A : Set) (l1 l2 l3 : list A),\nposfijo A l2 (append A l1 l2).\nProof.\n  intros.\n  induction l1; simpl.\n  - apply posfE.\n  - apply posfC. assumption.\nQed.\n\nLemma EmptyAppends : forall (A : Set) (l1 l2 : list A),\nappend A l1 l2 = emptyL A -> l1 = emptyL A /\\ l2 = emptyL A.\nProof.\n  intros.\n  split; rewrite <- H; induction l1.\n  - symmetry. assumption.\n  - simpl in H. discriminate.\n  - simpl. reflexivity.\n  - simpl in H. discriminate.\nQed.\n\nAxiom AppendEmptyLeft : forall (A : Set) (l1 l2 : list A), append A l1 l2 = l2 -> l1 = emptyL A.\n\nLemma Ej17_3_2 : forall (A : Set) (l1 l2 : list A),\nposfijo A l1 l2 -> posfijo A l2 l1 -> l1 = l2.\nProof.\n  intros.\n  assert (exists l3 : list A, l2 = append A l3 l1). apply Ej17_2_2. assumption.\n  assert (exists l3 : list A, l1 = append A l3 l2). apply Ej17_2_2. assumption.\n  elim H1. intros.\n  elim H2. intros.\n  rewrite H4 in H3.\n  rewrite L10 in H3.\n  assert (append A x x0 = emptyL A).\n  - apply (AppendEmptyLeft A (append A x x0) l2). symmetry. assumption.\n  - assert (x0 = emptyL A).\n    + elim (EmptyAppends A x x0).\n      * intros. assumption.\n      * assumption.\n    + rewrite H6 in H4. simpl in H4. assumption.\nQed.\n\nLemma Ej17_3_3 : forall (A : Set) (l1 l2 l3 : list A),\nposfijo A l1 l2 -> posfijo A l2 l3 -> posfijo A l1 l3.\nProof.\n  intros.\n  induction H0.\n  - induction l; assumption.\n  - induction H0; apply posfC.\n    + assumption.\n    + apply IHposfijo. assumption.\nQed.\n\nFixpoint ultimo (A : Set) (l : list A) : list A :=\n  match l with\n  | emptyL    => emptyL A\n  | cons x xs =>\n  match xs with\n    | emptyL => cons A x (emptyL A)\n    | _      => ultimo A xs\n    end\n  end.\n\nLemma Ej17_5 : forall (A : Set) (l : list A), posfijo A (ultimo A l) l.\nProof.\n  intros.\n  induction l; simpl.\n  - apply posfE.\n  - destruct l.\n    + apply posfE.\n    + apply posfC. assumption.\nQed.\n\nEnd Ejercicio17.\n\nSection Ejercicio20.\n\nInductive ACom (A : Set) : nat -> Set :=\n  | single : A -> ACom A O\n  | combine : forall n : nat, ACom A n -> A -> ACom A n -> ACom A (S n).\n\nFixpoint h (A : Set) (n : nat) (t : ACom A n) : nat :=\n  match t with\n  | single x => 1\n  | combine _ t1 x t2 => sum (h A _ t1) (h A _ t2)\n  end.\n\n(* Parameter pot: nat -> nat -> nat. *) \nAxiom potO : forall n : nat, pot (S n) 0 = 1.  \nAxiom potS : forall m: nat, pot 2 (S m) = sum (pot 2 m) (pot 2 m).\n\nLemma Ej20_3 : forall (A : Set) (n : nat) (t : ACom A n),\n(h A n t) = (pot 2 n).\nProof.\n  intros.\n  induction t; simpl.\n  - reflexivity.\n  - rewrite IHt1. rewrite IHt2. elim (SumO (pot 2 n)). intros. rewrite H. reflexivity.\nQed.\n\nEnd Ejercicio20.\n\n", "meta": {"author": "hgurmendi", "repo": "cfptt-coq", "sha": "07afcbf049d81adde65ce573c40a2185ab2f8171", "save_path": "github-repos/coq/hgurmendi-cfptt-coq", "path": "github-repos/coq/hgurmendi-cfptt-coq/cfptt-coq-07afcbf049d81adde65ce573c40a2185ab2f8171/practica/entregas/practico4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7156988224846278}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.omega.Omega.\n\nRequire Import BWT.Sorting.Ord.\nRequire Import BWT.Sorting.Sorted.\nRequire Import BWT.Sorting.StablePerm.\nRequire Import BWT.Sorting.InsertionSort.\nRequire Import BWT.Rotation.Rotation.\nRequire Import BWT.Lib.Repeat.\nRequire Import BWT.Lib.Permutation.\nRequire Import BWT.Sorting.Key.\nRequire Import BWT.Lib.List.\nRequire Import BWT.Columns.\nRequire Import BWT.Sorting.Lexicographic.\nRequire Import BWT.Sorting.PermFun.\n\nSection RadixSort.\n  Context {A : Type} {O : Preord A}.\n\n  Open Scope program_scope.\n\n  Implicit Type m : list (list A).\n  Implicit Type n : nat.\n\n  Definition radixsort m (n : nat) : list (list A)\n    := rep (hdsort ∘ map rrot) n m.\n\n  Remark radixsort_S : forall l j,\n      radixsort l (S j) = hdsort (map rrot (radixsort l j)).\n  Proof. reflexivity. Qed.\n\n  Lemma radixsort_perm_inv : forall j m,\n      Permutation (rep (map rrot) j m) (rep (hdsort ∘ map rrot) j m).\n  Proof.\n    induction j as [|j IH]; intro m; [reflexivity|].\n    cbn; symmetry.\n    transitivity (map rrot (rep (hdsort ∘ map rrot) j m)).\n    symmetry. apply sort_perm.\n    apply Permutation_map.\n    symmetry. apply IH.\n  Qed.\n\n  Theorem radixsort_perm : forall n m,\n      Forall (fun r => length r = n) m ->\n      Permutation m (radixsort m n).\n  Proof.\n    intros n m HL.\n    unfold radixsort.\n    rewrite <- map_id at 1.\n    rewrite map_forall_eq with (g := rep rrot n).\n    rewrite <- rep_map.\n    apply radixsort_perm_inv.\n    eapply Forall_impl; [|apply HL].\n    cbn; intros a HN.\n    rewrite <- HN. symmetry. apply rrot_rep_id.\n  Qed.\n\n  Lemma radixsort_nil : forall n, radixsort nil n = nil.\n  Proof.\n    intros. unfold radixsort.\n    apply rep_preserves; [|auto].\n    intros x HIn. unfold compose.\n    subst.\n    reflexivity.\n  Qed.\n\n  Theorem radixsort_length : forall n j l,\n      Forall (fun x => length x = n) l ->\n      Forall (fun x => length x = n) (radixsort l j).\n  Proof.\n    intros n j l HL.\n    unfold radixsort.\n    apply rep_preserves; [|auto].\n    clear HL l.\n    intros l HL.\n    apply Forall_forall.\n    intros x HIn. unfold compose in HIn.\n    apply Permutation_in with (l' := map rrot l) in HIn; [|symmetry; apply sort_perm].\n    apply in_map_iff in HIn.\n    destruct HIn as [prex [Hprex HIn]].\n    rewrite <- Hprex, <- rrot_length.\n    apply Forall_forall with (x := prex) in HL.\n    apply HL. apply HIn.\n  Qed.\n\n  Lemma StablePerm_map_rrot : forall m m' : list (list A),\n      StablePerm m m' -> StablePerm (map rrot m) (map rrot m').\n  Proof.\n    intros m m' HS.\n    apply StablePermInd_iff in HS.\n    induction HS.\n    - reflexivity.\n    - cbn. apply StablePerm_skip. apply IHHS.\n    - cbn. apply StablePerm_swap.\n      intro c; apply H.\n      symmetry.\n      apply lex_eqv_iff in c.\n      apply lex_eqv_iff.\n      rewrite <- @r_l_rot_inverse with (l := x).\n      rewrite <- @r_l_rot_inverse with (l := y).\n      apply Forall2_lrot. easy.\n    - transitivity (map rrot l'); easy.\n  Qed.\n\n  Lemma radixsort_stable_inv : forall j m,\n      StablePerm (rep (map rrot) j m) (rep (hdsort ∘ map rrot) j m).\n  Proof.\n    induction j; intros l; [reflexivity|].\n    cbn; symmetry.\n    transitivity (map rrot (rep (hdsort ∘ map rrot) j l)).\n    apply PrefixStable_firstn_1.\n    symmetry. apply sort_stable.\n    apply StablePerm_map_rrot. symmetry. apply IHj.\n  Qed.\n\n  Theorem radixsort_stable : forall n l,\n      Forall (fun x => length x = n) l ->\n      StablePerm l (radixsort l n).\n  Proof.\n    intros n l HL.\n    etransitivity; [|apply radixsort_stable_inv].\n    rewrite rep_map.\n    replace (map (rep rrot n) l) with (map (fun x => x) l); [rewrite map_id; easy|].\n    apply map_forall_eq.\n    eapply Forall_impl; [|apply HL].\n    intros. rewrite <- H. symmetry; apply rrot_rep_id.\n  Qed.\n\n  Lemma radixsort_sorted_inv : forall n j m,\n      j <= n ->\n      Forall (fun r => length r = n) m ->\n      PrefixSorted j (radixsort m j).\n  Proof.\n    induction j; intros m HJ HL; [apply PrefixSorted_zero|].\n    destruct m as [|r m]; [rewrite radixsort_nil; apply Sorted_nil|].\n    destruct r as [|d t] eqn:Ht;\n      [apply Forall_inv in HL; cbn in HL; omega|rewrite <- Ht in *; clear t Ht].\n    rewrite radixsort_S.\n    apply hdsort_sorted_S.\n    rewrite map_rrot_prepend with (d0 := d)\n      by (eapply Forall_impl; [|apply radixsort_length with (j := j) (n := n); easy];\n          cbn; intros; intro c; subst; cbn in HJ; omega).\n    rewrite map_tl_prepend by (rewrite !map_length; omega).\n    apply key_sorted. rewrite map_map.\n    rewrite map_forall_eq with (g := firstn j)\n      by (apply radixsort_length with (j := j) in HL;\n          eapply Forall_impl; [|apply HL]; cbn; intros; apply firstn_init; omega).\n    apply key_sorted; fold (PrefixSorted j (radixsort (r :: m) j)).\n    apply IHj; [omega|auto].\n  Qed.\n\n  Theorem radixsort_sorted : forall n m,\n      Forall (fun x => length x = n) m ->\n      Sorted (radixsort m n).\n  Proof.\n    intros n m HL.\n    rewrite <- map_id.\n    rewrite map_forall_eq with (g := firstn n)\n      by (apply radixsort_length with (j := n) in HL;\n          eapply Forall_impl; [|apply HL];\n          cbn; intros; subst; symmetry; apply firstn_all).\n    apply key_sorted; fold (PrefixSorted n (radixsort m n)).\n    apply radixsort_sorted_inv with (n := n); [omega|easy].\n  Qed.\n\n  Theorem radixsort_correct : forall n m,\n      Forall (fun x => length x = n) m ->\n      Sorted (radixsort m n) /\\ Permutation (radixsort m n) m.\n  Proof.\n    split; [apply radixsort_sorted|symmetry; apply radixsort_perm]; easy.\n  Qed.\nEnd RadixSort.\n", "meta": {"author": "jbaum98", "repo": "verified_bzip2", "sha": "d8ffd2e181f4951f588cce596b68fb2d0ebe7964", "save_path": "github-repos/coq/jbaum98-verified_bzip2", "path": "github-repos/coq/jbaum98-verified_bzip2/verified_bzip2-d8ffd2e181f4951f588cce596b68fb2d0ebe7964/theories/BWT/Sorting/RadixSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7156988206731322}}
{"text": "Require Import group.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nStructure hom M (G : group M) M' (G' : group M') := {\n  hom_f : M -> M';\n  hom_is_map : map hom_f G G';\n  hom_law : forall x y, hom_f (bin G x y) = bin G' (hom_f x) (hom_f y)\n}.\n\nTheorem hom_id_map_id : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  hom_f h (id G) = id G'.\nProof.\n  intros.\n  assert (hom_f h (id G) = hom_f h (bin G (id G) (id G)))\n    as f_id_G_eq_f__id_G_id_G\n    by (rewrite (idR G (id G)); reflexivity).\n\n  rewrite (hom_law h (id G) (id G)) in f_id_G_eq_f__id_G_id_G.\n  rename f_id_G_eq_f__id_G_id_G into f_id_G_eq_f_id_G_f_id_G.\n\n  apply (both_sides_L (bin G') (inverse G' (hom_f h (id G)))) in f_id_G_eq_f_id_G_f_id_G.\n  rename f_id_G_eq_f_id_G_f_id_G into inv_f_id_G_f_id_G_eq_inv_f_id_G_f_id_G_f_id_G.\n\n  rewrite (assoc G' (inverse G' (hom_f h (id G))) (hom_f h (id G)) (hom_f h (id G)))\n    in inv_f_id_G_f_id_G_eq_inv_f_id_G_f_id_G_f_id_G.\n\n  rewrite (invL G' (hom_f h (id G)))\n    in inv_f_id_G_f_id_G_eq_inv_f_id_G_f_id_G_f_id_G.\n  rename inv_f_id_G_f_id_G_eq_inv_f_id_G_f_id_G_f_id_G\n    into f_id_G_eq_inv_f_id_G_f_id_G_f_id_G.\n\n  rewrite (idL G' (hom_f h (id G))) in f_id_G_eq_inv_f_id_G_f_id_G_f_id_G.\n  symmetry.\n  assumption.\nQed.\n\nTheorem hom_inverse_map_inverse : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  forall x, hom_f h (inverse G x) = inverse G' (hom_f h x).\nProof.\n  intros.\n  assert (f_id_G_eq_id_G' := hom_id_map_id h).\n\n  rewrite <- (invR G x) in f_id_G_eq_id_G'.\n  rename f_id_G_eq_id_G' into f_x_x'_eq_id_G'.\n  rewrite (hom_law h x (inverse G x)) in f_x_x'_eq_id_G'.\n  rename f_x_x'_eq_id_G' into f_x_f_x'_eq_id_G'.\n\n  apply (both_sides_L (bin G'))\n    with (z:=(inverse G' (hom_f h x)))\n    in f_x_f_x'_eq_id_G'\n    as f_x'_f_x_f_x'_eq_f_x'_id_G'.\n  rewrite (assoc G' (inverse G' (hom_f h x)) (hom_f h x) (hom_f h (inverse G x))) in f_x'_f_x_f_x'_eq_f_x'_id_G'.\n\n  rewrite (idR G' (inverse G' (hom_f h x)))\n    in f_x'_f_x_f_x'_eq_f_x'_id_G'.\n  rename f_x'_f_x_f_x'_eq_f_x'_id_G' into f_x'_f_x_f_x'_eq_f_x'.\n\n  rewrite (invL G' (hom_f h x)) in f_x'_f_x_f_x'_eq_f_x'.\n  rename f_x'_f_x_f_x'_eq_f_x' into id_G'_f_x'_eq_f_x'.\n\n  rewrite (idL G' (hom_f h (inverse G x))) in id_G'_f_x'_eq_f_x'.\n  rename id_G'_f_x'_eq_f_x' into f_x'_eq_f_x'.\n  assumption.\nQed.\n\nDefinition kernel (M M' : Type) (G : group M) (G' : group M') (h : hom G G') : set M :=\n  fun x => hom_f h x = id G'.\nArguments kernel M M' G G' h /.\n\nTheorem kernel_has_id : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  (id G) \\in (kernel h).\nProof.\n  simpl. intros.\n  apply hom_id_map_id.\nQed.\n\nTheorem kernel_is_entire : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  forall x y, x \\in (kernel h) -> y \\in (kernel h) -> (bin G x y) \\in (kernel h).\nProof.\n  simpl. intros.\n  assert (f_xy_eq_fx_fy := hom_law h x y).\n  rewrite H in f_xy_eq_fx_fy.\n  rewrite H0 in f_xy_eq_fx_fy.\n  rename f_xy_eq_fx_fy into f_xy_eq_id_G'_id_G'.\n\n  rewrite (idR G' (id G')) in f_xy_eq_id_G'_id_G'.\n  assumption.\nQed.\n\nTheorem kernel_has_inverse : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  forall x, x \\in (kernel  h) -> (inverse G x) \\in (kernel h).\nProof.\n  simpl. intros.\n  rewrite (hom_inverse_map_inverse h x).\n  rewrite H.\n  rewrite id_inverse_eq_id.\n  reflexivity.\nQed.\n\nDefinition image (M M' : Type) (G : group M) (G' : group M') (h : hom G G') : set M' :=\n  fun x => exists y, hom_f h y = x.\nArguments image M M' G G' h /.\n\nTheorem image_has_id : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  (id G') \\in (image h).\nProof.\n  simpl. intros.\n  exists (id G).\n  apply hom_id_map_id.\nQed.\n\nTheorem image_is_entire : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  forall x y, x \\in (image h) -> y \\in (image h) -> (bin G' x y) \\in (image h).\nProof.\n  simpl.\n  intros.\n  inversion H as [x1].\n  inversion H0 as [y1].\n  exists (bin G x1 y1).\n  rewrite <- H1.\n  rewrite <- H2.\n  rewrite (hom_law h).\n  reflexivity.\nQed.\n\nTheorem image_has_inverse : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  forall x, x \\in (image h) -> (inverse G' x) \\in (image h).\nProof.\n  simpl. intros.\n  inversion H.\n  exists (inverse G x0).\n  rewrite <- H0.\n  apply hom_inverse_map_inverse.\nQed.\n\n\n(* 準同型f: G -> G' に対し、 fが単射である <-> Ker(f) = {id_G} *)\n\nTheorem hom_is_injection_iff_kernel_is_id : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  injection (hom_f h) G G' <->\n  forall x y, x \\in (kernel h) -> y \\in (kernel h) -> x = y /\\ x = id G.\nProof.\n  simpl. intros.\n  split.\n  - (* -> *)\n    intros.\n    split.\n    +\n      rewrite <- H1 in H0.\n      apply (H (hom_is_map h) x y H0).\n    +\n      assert (H2 := hom_id_map_id h).\n      rewrite <- H2 in H0.\n      apply (H (hom_is_map h) x (id G) H0).\n  - (* <- *)\n    intros.\n    assert (H2 := hom_law h x (inverse G y)).\n    rewrite (hom_inverse_map_inverse h y) in H2.\n    rewrite H1 in H2.\n    rewrite (invR G') in H2.\n    assert (H3 := H (bin G x (inverse G y)) (id G) H2 (hom_id_map_id h)).\n    inversion H3.\n    apply (both_sides_R (bin G)) with (z := y) in H4.\n    rewrite <- (assoc G) with (z := y) in H4.\n    rewrite (invL G y) in H4.\n    rewrite (idR G x) in H4.\n    rewrite (idL G y) in H4.\n    assumption.\nQed.\n\nSection g_Aut_G_hom.\n  Variables M : Type.\n  Variables G : group M.\n  Definition M' := M -> M.\n  Variables G' : group M'.\n\n  Definition i g := fun h:M => bin G (bin G g h) (inverse G g).\n  (* i_g h = g h g^(-1) *)\n  Arguments i g /.\n  Definition f g := i g.  (* f: G -> Aut G\n                             f: g |-> i g *)\n  Arguments f g /.\n\n  Definition comp (f f' : M') :=\n    fun x => f (f' x).\n  Arguments comp f f' /.\n\n  Theorem f_is_map : map f G G'.\n  Proof.\n  Admitted.\n\n  Axiom extensionality : forall (X Y:Type) (x:X) (f g:X->Y),\n    f x = g x -> f = g.\n  Theorem f_sat_hom_law : forall g1 g2, f (bin G g1 g2) = (comp (f g1) (f g2)).\n  Proof.\n    simpl.\n    intros.\n    apply (@extensionality M M g1).\n    rewrite (inverse_distributive G g1 g2).\n    rewrite <- (assoc G g1 g2 g1).\n    rewrite (assoc G (bin G g1 (bin G g2 g1)) (inverse G g2) (inverse G g1)).\n    rewrite <- (assoc G g1 (bin G g2 g1) (inverse G g2)).\n    reflexivity.\n  Qed.\nEnd g_Aut_G_hom.\n\nSection id_is_hom.\n  Variables M : Type.\n  Variables G : group M.\n\n  Definition id_f := fun x:M => x.\n\n  Theorem id_is_map : map id_f G G.\n  Proof.\n    simpl. intros.\n    unfold id_f.\n    assumption.\n  Qed.\n\n  Theorem id_sat_hom_law : forall x y,\n    id_f (bin G x y) = bin G (id_f x) (id_f y).\n  Proof.\n    simpl. intros.\n    unfold id_f.\n    reflexivity.\n  Qed.\n\n  Theorem id_is_hom : hom G G.\n  Proof.\n    apply (Build_hom id_is_map id_sat_hom_law).\n  Qed.\nEnd id_is_hom.\n\nDefinition kernel_group (M M' : Type) (G : group M) (G' : group M') (h : hom G G') : group M :=\n  Build_group\n   (kernel_has_id h)\n   (@kernel_has_inverse M M' G G' h)\n   (@kernel_is_entire M M' G G' h)\n   (assoc G)\n   (idR G) (idL G)\n   (invR G) (invL G).\n\nTheorem kernel_group_is_normal_group : forall (M M' : Type) (G : group M) (G' : group M') (h : hom G G'),\n  normalgroup (kernel_group h) G.\nProof.\n  simpl. intros.\n  rewrite hom_law. rewrite hom_law.\n  rewrite H1.\n  rewrite idR.\n  rewrite hom_inverse_map_inverse.\n  rewrite invR.\n  reflexivity.\nQed.\n", "meta": {"author": "ryuta-ito", "repo": "algebra_1", "sha": "dc268e65e3338ef2c2be393b57acf3fa58453309", "save_path": "github-repos/coq/ryuta-ito-algebra_1", "path": "github-repos/coq/ryuta-ito-algebra_1/algebra_1-dc268e65e3338ef2c2be393b57acf3fa58453309/homomorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7156186072394699}}
{"text": "Require Import Coq.Program.Tactics.\nRequire Import CT.Algebra.Magma.\nRequire Import CT.Algebra.Semigroup.\nRequire Import FunctionalExtensionality.\nRequire Import ProofIrrelevance.\n\nSet Primitive Projections.\n\nRecord Monoid {T : Type} :=\n  { semigroup :> @Semigroup T;\n    one : T;\n    monoid_left_one : forall x, semigroup.(magma).(mu) one x = x;\n    monoid_right_one : forall x, semigroup.(magma).(mu) x one = x\n  }.\n\nHint Resolve monoid_right_one.\nHint Resolve monoid_left_one.\n\nFixpoint mu_power {T : Type} (M : @Monoid T) (t : T) (n : nat) :=\n  match n with\n  | 0 => one M\n  | S n => mu M t (mu_power M t n)\n  end.\n\n(** ** Monoid identity is unique. *)\nTheorem monoid_identity_unique {T} {M : @Monoid T} e :\n  (forall x, mu M x e = x) -> e = one M.\nProof.\n  intros.\n  destruct M.\n  simpl in *.\n  destruct (H e).\n  rewrite <- (H one0).\n  rewrite monoid_left_one0.\n  trivial.\nQed.\n\nCorollary monoid_identity_commutes {T} {M : @Monoid T} :\n  forall a,\n    mu M a (one M) = mu M (one M) a.\nProof.\n  intros.\n  rewrite monoid_left_one.\n  rewrite monoid_right_one.\n  trivial.\nQed.\n\n(* Possibly separate this out at some point. *)\n\n(** * Monoid homomorphisms.\n\nMagma homomorphisms that also preserve identity.\n*)\nRecord MonoidHomomorphism {A B} (M : @Monoid A) (N : @Monoid B) :=\n  { monoid_hom :> @MagmaHomomorphism A B M N;\n    monoid_hom_id_law : magma_hom M N monoid_hom (one M) = one N\n  }.\n\n(** * Composition of maps. *)\nProgram Definition monoid_hom_composition\n        {T U V : Type}\n        {A : @Monoid T}\n        {B : @Monoid U}\n        {C : @Monoid V}\n        (map1 : MonoidHomomorphism A B)\n        (map2 : MonoidHomomorphism B C) :\n  MonoidHomomorphism A C :=\n  {| monoid_hom :=\n       {| magma_hom := fun a => (magma_hom B C map2) ((magma_hom A B map1) a)\n       |}\n  |}.\nNext Obligation.\nProof.\n  destruct A, B, C, map1, map2.\n  simpl in *.\n  rewrite magma_hom_law.\n  rewrite magma_hom_law.\n  trivial.\nQed.\nNext Obligation.\n  destruct A, B, C, map1, map2.\n  simpl in *.\n  rewrite monoid_hom_id_law0.\n  rewrite monoid_hom_id_law1.\n  trivial.\nQed.\n\n(** * Equality of maps, assuming proof irrelevance. *)\nTheorem monoid_hom_eq : forall A B F G (M N : MonoidHomomorphism F G),\n    @monoid_hom A B F G M = @monoid_hom A B F G N ->\n    M = N.\nProof.\n  intros.\n  destruct M, N.\n  simpl in *.\n  subst.\n  f_equal.\n  apply proof_irrelevance.\nQed.\n\n(** * Associativity of composition of maps. *)\nProgram Definition monoid_hom_composition_assoc\n        {T : Type}\n        {A B C D : @Monoid T}\n        (f : MonoidHomomorphism A B)\n        (g : MonoidHomomorphism B C)\n        (h : MonoidHomomorphism C D) :\n  monoid_hom_composition f (monoid_hom_composition g h) =\n  monoid_hom_composition (monoid_hom_composition f g) h.\nProof.\n  destruct f, g, h.\n  apply monoid_hom_eq.\n  simpl.\n  f_equal.\n  intros.\n  apply proof_irrelevance.\n  (* There's got to be a better way. *)\nQed.\n\n(** * Identity map. *)\nProgram Definition monoid_hom_id\n        {A : Type}\n        {M : @Monoid A} :\n  MonoidHomomorphism M M :=\n  {| monoid_hom := {| magma_hom := fun a => a |} |}.", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Algebra/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7155958434129381}}
{"text": "Inductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\nArguments nil {X}.\nArguments cons {X}.\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\nArguments pair {X} {Y}.\nNotation \"( x , y )\" := (pair x y).\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n\n\n\n(* Our last polymorphic type for now is polymorphic options, which generalize natoption from the previous chapter. *)\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\nArguments Some {X}.\nArguments None {X}.\n\n(* We can now rewrite the nth_error function so that it works with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\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.\n\n(* Exercise hd_error_poly *)\nDefinition hd_error {X : Type} (l : list X) : option X :=\n    match l with \n    | nil => None \n    | h :: t => Some h\n    end.\n\nCheck @hd_error : forall X : Type, list X -> option X.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\n\nExample test_hd_error2 : hd_error [[1];[2]] = Some [1].\nProof. reflexivity. 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/poly/lessons/polymorphic_options.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7155958384192009}}
{"text": "Require Import List.\n\nFixpoint nth {A} (l:list A) (i:nat) : option A :=\n  match l with\n    | nil => None\n    | x :: xs => match i with\n                   | 0 => Some x\n                   | S j => nth xs j\n                 end\n  end.\n\nLemma nth_map A B l i (f : A -> B) : nth (map f l) i = option_map f (nth l i).\nProof.\n  intros.\n  generalize dependent i.\n  induction l; intros; simpl. reflexivity.\n\n  destruct i; simpl;auto.\nQed.\n", "meta": {"author": "pa-ba", "repo": "calc-comp", "sha": "337a5b89dfb8ceb9e2724e5911519a60d14a4f99", "save_path": "github-repos/coq/pa-ba-calc-comp", "path": "github-repos/coq/pa-ba-calc-comp/calc-comp-337a5b89dfb8ceb9e2724e5911519a60d14a4f99/ListIndex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7155958367980494}}
{"text": "(********** EXERCICE 1 **********)\nRequire Import ZArith.\nOpen Scope Z_scope.\n\n(* Question 1 *)\nInductive gauss : Set :=\n(* | Gauss (a : Z) (b : Z). *)\n| Gauss: Z -> Z -> gauss.\n\nDefinition g0 := Gauss 0 0.\nDefinition g1 := Gauss 1 0.\nDefinition gi := Gauss 0 1.\n\n(* Question 2 *)\nFixpoint conjug_gauss (g : gauss) :=\nmatch g with\n| Gauss a b => Gauss a (-b)\nend.\n\nFixpoint add_gauss (x y : gauss) :=\nmatch (x,y) with\n| (Gauss a b, Gauss c d) => Gauss (a+c) (b+d)\nend.\n\nFixpoint mult_gauss (x y : gauss) :=\nmatch (x,y) with\n| (Gauss a b, Gauss c d) => Gauss (a*c) (b*d)\nend.\n\nDefinition sub_gauss (x y : gauss) :=\nadd_gauss x (conjug_gauss y).\n\n(* Question 3 *)\nLemma q3 : forall a : gauss,\nadd_gauss g0 a = a.\nProof.\nintros.\ndestruct a.\nsimpl.\nreflexivity.\nQed.\n\n(* Question 4 *)\nLemma gauss_plus_comm : forall a b : gauss,\nadd_gauss a b = add_gauss b a.\nProof.\nintros.\ndestruct a,b.\nsimpl.\nrewrite Zplus_comm.\nrewrite (Zplus_comm z0 z2).\nreflexivity.\nQed.\n\nLemma gauss_plus_assoc : forall a b c : gauss,\nadd_gauss (add_gauss a b) c = add_gauss a (add_gauss b c).\nProof.\nintros.\ndestruct a,b,c.\nsimpl.\nrewrite Zplus_assoc.\nrewrite (Zplus_assoc z0 z2 z4).\nreflexivity.\nQed.\n\nLemma gauss_mult_comm : forall a b : gauss,\nmult_gauss a b = mult_gauss b a.\nProof.\nintros.\ndestruct a,b.\nsimpl.\nrewrite Zmult_comm.\nrewrite (Zmult_comm z0 z2).\nreflexivity.\nQed.\nClose Scope Z_scope.\n(********** EXERCICE 2 **********)\n(* Question 1 *)\nInductive jour : Set :=\n| Lundi : jour\n| Mardi : jour\n| Mercredi : jour\n| Jeudi : jour\n| Vendredi : jour\n| Samedi : jour\n| Dimanche : jour.\n\n(* Question 2 *)\nDefinition jour_suivant (j:jour) : jour :=\nmatch j with\n| Lundi => Mardi\n| Mardi => Mercredi\n| Mercredi => Jeudi\n| Jeudi => Vendredi\n| Vendredi => Samedi\n| Samedi => Dimanche\n| Dimanche => Lundi\nend.\n\nDefinition jour_precedent (j:jour) : jour :=\nmatch j with\n| Lundi => Dimanche\n| Mardi => Lundi\n| Mercredi => Mardi\n| Jeudi => Mercredi\n| Vendredi => Jeudi\n| Samedi => Vendredi\n| Dimanche => Samedi\nend.\n\n(* Question 3 *)\nLemma j_suivant : forall j : jour,\njour_suivant (jour_precedent j) = j.\nProof.\nintros.\nelim j; simpl; reflexivity.\nQed.\n\nLemma j_precedent : forall j : jour,\njour_precedent (jour_suivant j) = j.\nProof.\nintros.\nelim j; simpl; reflexivity.\nQed.\n\n(* Question 4 *)\nFixpoint iter_jour (n:nat) (f:jour -> jour) (j:jour) :=\nmatch n with\n| 0 => j\n| S m => f (iter_jour m f j)\nend.\n\nLemma iter_jour_j_suivant : forall j : jour,\niter_jour 7 jour_suivant j = j.\nProof.\nintros.\nelim j; simpl; reflexivity.\nQed.\n\n(* Question 5 *)\nLemma iter_jour_j_precedent : forall j : jour,\niter_jour 7 jour_precedent j = j.\nProof.\nintros.\nelim j; simpl; reflexivity.\nQed.\n\n(* Question 6 *)\nLemma q6 : forall (n m: nat) (f: jour->jour),\nforall j : jour, iter_jour(n+m) f j = iter_jour n f (iter_jour m f j).\nProof.\nintros.\ninduction n.\nsimpl.\nreflexivity.\nsimpl.\nrewrite IHn.\nreflexivity.\nQed.\n\n(* Question 7 *)\nRequire Import Arith.\n\nLemma iter_jour_j_modulo : forall (n:nat) (j:jour),\niter_jour (7*n) jour_suivant j = j.\nProof.\nintros.\ninduction n.\nsimpl.\nreflexivity.\nrewrite mult_comm.\nrewrite mult_succ_l.\nrewrite q6.\nrewrite mult_comm.\nrewrite iter_jour_j_suivant.\nassumption.\nQed.", "meta": {"author": "Neo-Purpinc", "repo": "Preuves-Assistees-par-Ordinateur", "sha": "f285b2efa87283e3940121095a67a98b1b488357", "save_path": "github-repos/coq/Neo-Purpinc-Preuves-Assistees-par-Ordinateur", "path": "github-repos/coq/Neo-Purpinc-Preuves-Assistees-par-Ordinateur/Preuves-Assistees-par-Ordinateur-f285b2efa87283e3940121095a67a98b1b488357/TP2/TP2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7155958350031871}}
{"text": "From Coq Require Import List Arith.\nImport ListNotations.\n\n(* Arithmetic expressions language *)\nInductive expr : Type :=\n| Const : nat -> expr\n| Plus : expr -> expr -> expr\n| Minus : expr -> expr -> expr.\n\n(* Semantics of arithmetic expressions *)\nFixpoint eval (e : expr) : nat :=\n  match e with\n  | Const n => n\n  | Plus e1 e2 => eval e1 + eval e2\n  | Minus e1 e2 => eval e1 - eval e2\n  end.\n\n(* Stack machine instructions *)\nInductive instr :=\n| Push : nat -> instr\n| Add\n| Sub.\n\n(* Stack programs *)\nDefinition prog := list instr.\n\n(* Stack *)\nDefinition stack := list nat.\n\n(* Stack machine semantics *)\nFixpoint run (p : prog) (s : stack) {struct p}: stack :=\n  match p with\n  | [] => s\n  | i :: p' =>\n    match i with\n    | Push n => run p' (n :: s)\n    | Add =>\n      match s with\n      | a :: b :: s' => run p' (b + a :: s')\n      | _ => [] (* if stack underflow -- interrupt\n                   execution and return empty stack *)\n      end\n    | Sub =>\n      match s with\n      | a :: b :: s' => run p' (b - a :: s')\n      | _ => [] (* if stack underflow -- interrupt\n                   execution and return empty stack *)\n      end\n    end\n  end.\n\n(* Compilation from arithmetic expressions\n   into stack programs *)\nFixpoint compile (e : expr) : prog :=\n  match e with\n  | Const n => [Push n]\n  | Plus e1 e2 =>\n    compile e1 ++ compile e2 ++ [Add]\n  | Minus e1 e2 =>\n    compile e1 ++ compile e2 ++ [Sub]\n  end.\n\n\nLemma compile_correct' : \n  forall (e : expr) (p : prog) (s : stack),\n    run p (eval e :: s) = run (compile e ++ p) s.\nProof.\n    induction e.\n\n    simpl.\n    reflexivity.\n\n    intros.\n    simpl.\n    rewrite app_assoc_reverse.\n    rewrite <- IHe1.\n    rewrite app_assoc_reverse.\n    rewrite <- IHe2.\n    intuition.\n    \n    intros.\n    simpl.\n    rewrite app_assoc_reverse.\n    rewrite <- IHe1.\n    rewrite app_assoc_reverse.\n    rewrite <- IHe2.\n    intuition.\nQed.\n\nTheorem compile_correct :\n  forall e,\n    [eval e] = run (compile e) [].\nProof.\n  intros.\n  rewrite (app_nil_end (compile e)).\n  rewrite <- compile_correct'.\n  intuition.\nQed.", "meta": {"author": "K-dizzled", "repo": "coq-proofs-matlog-hw5", "sha": "07f53dc2d342602fa4b2c4be54b46e638dc4dfdc", "save_path": "github-repos/coq/K-dizzled-coq-proofs-matlog-hw5", "path": "github-repos/coq/K-dizzled-coq-proofs-matlog-hw5/coq-proofs-matlog-hw5-07f53dc2d342602fa4b2c4be54b46e638dc4dfdc/lab05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7853085834000791, "lm_q1q2_score": 0.7155572491863947}}
{"text": "Require Import Coq.Program.Basics.\n\nOpen Scope program_scope.\n\n\n(** A binary \"multiplication\" operation. *)\nClass Mappend (A : Type) : Type :=\n  mappend : A -> A -> A.\n\nNotation \"f ⊗ x\" := (mappend f x) (at level 65, left associativity)\n                    : monoid_scope.\nOpen Scope monoid_scope.\n\n(** A semigroup just has an associative binary operation. *)\nClass Semigroup (A : Type) `{Mappend A} : Prop :=\n  { mappend_assoc : forall x y z, (x ⊗ y) ⊗ z = x ⊗ (y ⊗ z) }.\n\n(** A distinguished element of A. *)\nClass Mempty (A : Type) : Type :=\n  mempty : A.\n\n(** A monoid is a semigroup in addition to a distinguished element\n    which is the left and right unit of the multiplicaton operator. *)\nClass Monoid (A : Type) `{Semigroup A} `{Mempty A} : Prop :=\n  { mempty_left : forall x, mempty ⊗ x = x\n  ; mempty_right : forall x, x ⊗ mempty = x }.\n\n\n(** Example instances for nat. *)\nRequire Import NArith.\nInstance Mappend_nat : Mappend nat := Nat.add.\nInstance Semigroup_nat : Semigroup nat.\nProof. firstorder. Qed.\nInstance Mempty_nat : Mempty nat := O.\nInstance Monoid_nat : Monoid nat.\nProof. firstorder. Qed.\n", "meta": {"author": "bagnalla", "repo": "functors-monads", "sha": "ff0a9cb56c4cef878d3bdd47c2c8d2aa0c0e6809", "save_path": "github-repos/coq/bagnalla-functors-monads", "path": "github-repos/coq/bagnalla-functors-monads/functors-monads-ff0a9cb56c4cef878d3bdd47c2c8d2aa0c0e6809/theories/monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7155572404247503}}
{"text": "Require Export Arith.\nRequire Export ArithRing.\nRequire Export Omega.\nRequire Export Wf_nat.\n \nDefinition div8_spec:\n forall n,  ({q : nat & {r : nat | n = 8 * q + r /\\ r < 8}}).\nrefine (fix\n        div8 (n : nat) : {q : nat & {r : nat | n = 8 * q + r /\\ r < 8}} :=\n           match n return {q : nat & {r : nat | n = 8 * q + r /\\ r < 8}} with\n              S (S (S (S (S (S (S (S x))))))) =>\n                match div8 x with existS q' (exist r (conj Heq Hlt)) => _ end\n             | _ => _\n           end).\nexists 0; exists 0; omega.\nexists 0; exists 1; omega.\nexists 0; exists 2; omega.\nexists 0; exists 3; omega.\nexists 0; exists 4; omega.\nexists 0; exists 5; omega.\nexists 0; exists 6; omega.\nexists 0; exists 7; omega.\nexists (S q'); exists r; omega.\nQed.\n(* We use a different inequality to express that the cubic root we provide is\n  not an underestimation, but we will produce a more intuitive specification\n  in the final function.  The specication we use here should make the proofs by\n  omega easier. *)\n \nDefinition cubic_F:\n forall n,\n (forall y,\n  y < n ->\n   ({s : nat & {r : nat | y = (s * s) * s + r /\\ r <= 3 * (s * s) + 3 * s}})) ->\n  ({s : nat & {r : nat | n = (s * s) * s + r /\\ r <= 3 * (s * s) + 3 * s}}).\nrefine (fun n cubic =>\n           match div8_spec n with\n             existS (S q) (exist r8 (conj Heq Hltr8)) =>\n               match cubic (S q) _ with\n                 existS c' (exist r (conj Heqc Hltr)) =>\n                   match le_lt_dec ((12 * (c' * c') + 6 * c') + 1) (8 * r + r8)\n                    with left Hle => _ | right Hlt => _ end\n               end\n            | existS 0 (exist 0 (conj Heq _)) => _\n            | existS 0 (exist (S n') (conj Heq Hlt)) => _\n           end).\nexists 0; exists 0; rewrite Heq; omega.\nexists 1; exists n'; rewrite Heq; omega.\nomega.\nexists (2 * c' + 1); exists ((8 * r + r8) - ((12 * (c' * c') + 6 * c') + 1)).\nrewrite Heq.\nreplace\n (((2 * c' + 1) * (2 * c' + 1)) * (2 * c' + 1) +\n  ((8 * r + r8) - ((12 * (c' * c') + 6 * c') + 1)))\n     with\n      (((8 * c') * c') * c' +\n       (((12 * (c' * c') + 6 * c') + 1) +\n        ((8 * r + r8) - ((12 * (c' * c') + 6 * c') + 1)))).\nrewrite le_plus_minus_r.\nrewrite Heqc.\nsplit.\nring.\napply plus_le_reg_l with ((12 * (c' * c') + 6 * c') + 1).\nrewrite le_plus_minus_r.\nreplace ((2 * c' + 1) * (2 * c' + 1)) with ((4 * (c' * c') + 4 * c') + 1).\nomega.\nring.\nexact Hle.\nexact Hle.\nring.\nexists (2 * c'); exists (8 * r + r8); split.\nrewrite Heq; rewrite Heqc; ring.\nreplace ((2 * c') * (2 * c')) with (4 * (c' * c')).\nomega.\nring.\nQed.\n \nDefinition cubic:\n forall n,\n  ({c : nat &\n   {r : nat | n = (c * c) * c + r /\\ n < ((c + 1) * (c + 1)) * (c + 1)}}).\nintros n;\n elim\n  (well_founded_induction\n    lt_wf\n    (fun n =>\n     {c : nat & {r : nat | n = (c * c) * c + r /\\ r <= 3 * (c * c) + 3 * c}})\n    cubic_F n).\nintros c [r [Heq Hle]].\nexists c; exists r; split; trivial.\nreplace (((c + 1) * (c + 1)) * (c + 1))\n     with ((((c * c) * c + 3 * (c * c)) + 3 * c) + 1).\nomega.\nring.\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/gen-rec/SRC/cubic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7155572355325196}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import Omega.\n\n(** All elements of a list have a property. *)\nFixpoint listall A P (xs:list A) :=\n  match xs with\n      nil => True\n    | (x::xs) => P x /\\ listall _ P xs\n  end.\n\n(** All elements of a list have the same (given) value. *)\nDefinition allEq A xs y := listall A (fun x => x = y) xs.\n\n(** Return the first n elements of a list. *)\nFixpoint take A n (xs : list A) :=\n  match xs with\n      nil => nil\n    | (x::xs) =>\n      match n with\n          0 => nil\n        | S n => x :: take _ n xs\n      end\n  end.\n\n(** After conjuring up n copies of an element, taking n of them is a no-op. *)\nLemma take_repeat:\n  forall A n c,\n    take A n (repeat c n) = repeat c n.\nProof.\n induction n.\n  simpl.\n  auto.\n simpl.\n intro c.\n rewrite IHn.\n auto.\nQed.\n\n(** Taking n elements of a concatentation, when n is less than the\n    length of the first concatenand, gives just n elements of that concatenand. *)\nLemma take_app:\n  forall A n (xs ys : list A),\n  n <= length xs ->\n  take A n (xs ++ ys) = take A n xs.\nProof.\n induction n.\n  intros.\n  simpl.\n  destruct xs; destruct ys; auto.\n intros.\n simpl.\n destruct xs.\n  simpl.\n  destruct ys.\n   auto.\n  simpl in H.\n  exfalso; omega.\n simpl.\n rewrite IHn.\n  auto.\n simpl in H.\n omega.\nQed.\n\n(** If we conjure copies of a value, all the elements of the list are equal to that value. *)\nLemma listall_repeat :\n  forall A c n,\n    listall A (fun x => x = c) (repeat c n).\nProof.\n induction n; simpl.\n  auto.\n split; auto.\nQed.\n\n(** Return what follows after the first n elements of a list. *)\nFixpoint drop A n (xs : list A) :=\n  match n with\n      0 => xs\n    | S n =>\n      match xs with\n          nil => nil\n        | (x::xs) =>\n          drop _ n xs\n      end\n  end.\n\n(** Dropping the first n elements of a concatenation, when n is the\n    length of the first concatenand, gives just the second concatenand. *)\nLemma drop_app:\n  forall A n (xs ys : list A),\n    n = length xs ->\n    drop A n (xs ++ ys) = ys.\nProof.\n induction n.\n  intros.\n  simpl.\n  destruct xs; auto.\n  simpl in *.\n  discriminate.\n intros.\n destruct xs; simpl in *.\n  discriminate.\n rewrite IHn; auto.\nQed.\n\nHint Rewrite take_repeat take_app drop_app app_length repeat_length : list_lemmas.\n", "meta": {"author": "ezrakilty", "repo": "hillel-challenge", "sha": "10db5df58df33da5766b15d351ce83c310e38a87", "save_path": "github-repos/coq/ezrakilty-hillel-challenge", "path": "github-repos/coq/ezrakilty-hillel-challenge/hillel-challenge-10db5df58df33da5766b15d351ce83c310e38a87/listkit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.715527545038327}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.SetoidList.\n\nDefinition equiv_2 A B p1 p2 := forall (a : A) (b : B), p1 a b <-> p2 a b.\n\nLemma equiv_2_trans : forall A B a b c, @equiv_2 A B a b -> equiv_2 b c -> equiv_2 a c.\n  unfold equiv_2; intros; split; intros.\n  eapply H0; eapply H; eauto.\n  eapply H; eapply H0; eauto.\nQed.\n\nLemma InA_eq_In_iff : forall elt (ls : list elt) (x : elt), InA eq x ls <-> List.In x ls.\n  induction ls; simpl; intros.\n  intuition.\n  eapply InA_nil in H; eauto.\n  split; intros.\n  inversion H; subst.\n  eauto.\n  right.\n  eapply IHls.\n  eauto.\n  destruct H.\n  subst.\n  econstructor 1.\n  eauto.\n  econstructor 2.\n  eapply IHls.\n  eauto.\nQed.\n\nLemma InA_weaken :\n  forall A (P : A -> A -> Prop) (x : A) (ls : list A),\n    InA P x ls ->\n    forall (P' : A -> A -> Prop) x',\n      (forall y, P x y -> P' x' y) ->\n      InA P' x' ls.\n  induction 1; simpl; intuition.\nQed.\n\nLemma equiv_InA : forall elt (eq1 eq2 : elt -> elt -> Prop), equiv_2 eq1 eq2 -> equiv_2 (InA eq1) (InA eq2).\n  unfold equiv_2; split; intros; eapply InA_weaken; eauto; intros; eapply H; eauto.\nQed.\n\nLemma In_InA : forall A (x : A) ls,\n  List.In x ls\n  -> InA eq x ls.\n  intros; eapply InA_eq_In_iff; eauto.\nQed.\n\nLemma InA_In : forall A (x : A) ls,\n  InA eq x ls ->\n  List.In x ls.\n  intros; eapply InA_eq_In_iff; eauto.\nQed.\n\nLocal Hint Constructors List.NoDup NoDupA.\n\nLemma NoDupA_NoDup : forall A ls,\n  @NoDupA A eq ls\n  -> List.NoDup ls.\n  induction 1; intuition auto using In_InA.\nQed.\n\nLemma NoDup_NoDupA : forall A ls,\n  List.NoDup ls ->\n  @NoDupA A eq ls.\n  induction 1; intuition auto using InA_In.\nQed.\n\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/SetoidListFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7155275366059012}}
{"text": "(*\nWenrui Meng finish this assignment by himself.\n*)\n(** * Basics: Functional Programming in Coq *)\n \n(* This library definition is included here temporarily \n   for backward compatibility with Coq 8.3.  \n   Please ignore. *)\nDefinition admit {T: Type} : T.  Admitted.\n\n(* ###################################################################### *)\n(** * Introduction *)\n\n(** The functional programming style brings programming closer to\n    mathematics: If a procedure or method has no side effects, then\n    pretty much all you need to understand about it is how it maps\n    inputs to outputs -- that is, you can think of its behavior as\n    just computing a mathematical function.  This is one reason for\n    the word \"functional\" in \"functional programming.\"  This direct\n    connection between programs and simple mathematical objects\n    supports both sound informal reasoning and formal proofs of\n    correctness.\n\n    The other sense in which functional programming is \"functional\" is\n    that it emphasizes the use of functions (or methods) as\n    _first-class_ values -- i.e., values that can be passed as\n    arguments to other functions, returned as results, stored in data\n    structures, etc.  The recognition that functions can be treated as\n    data in this way enables a host of useful idioms, as we will see.\n\n    Other common features of functional languages include _algebraic\n    data types_ and _pattern matching_, which make it easy to construct\n    and manipulate rich data structures, and sophisticated\n    _polymorphic type systems_ that support abstraction and code\n    reuse.  Coq shares all of these features.\n*)\n\n(* ###################################################################### *)\n(** * Enumerated Types *)\n\n(** One unusual aspect of Coq is that its set of built-in\n    features is _extremely_ small.  For example, instead of providing\n    the usual palette of atomic data types (booleans, integers,\n    strings, etc.), Coq offers an extremely powerful mechanism for\n    defining new data types from scratch -- so powerful that all these\n    familiar types arise as instances.  \n\n    Naturally, the Coq distribution comes with an extensive standard\n    library providing definitions of booleans, numbers, and many\n    common data structures like lists and hash tables.  But there is\n    nothing magic or primitive about these library definitions: they\n    are ordinary user code.\n\n    To see how this works, let's start with a very simple example. *)\n\n(* ###################################################################### *)\n(** ** Days of the Week *)\n\n(** The following declaration tells Coq that we are defining\n    a new set of data values -- a _type_. *)\n\nInductive day : Type :=\n  | monday : day\n  | tuesday : day\n  | wednesday : day\n  | thursday : day\n  | friday : day\n  | saturday : day\n  | sunday : day.\n\n(** The type is called [day], and its members are [monday],\n    [tuesday], etc.  The second through eighth lines of the definition\n    can be read \"[monday] is a [day], [tuesday] is a [day], etc.\"\n\n    Having defined [day], we can write functions that operate on\n    days. *)\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\n(** One thing to note is that the argument and return types of\n    this function are explicitly declared.  Like most functional\n    programming languages, Coq can often work out these types even if\n    they are not given explicitly -- i.e., it performs some _type\n    inference_ -- but we'll always include them to make reading\n    easier. *)\n\n(** Having defined a function, we should check that it works on\n    some examples.  There are actually three different ways to do this\n    in Coq.  First, we can use the command [Eval simpl] to evaluate a\n    compound expression involving [next_weekday].  *)\n\nEval simpl in (next_weekday friday).\n   (* ==> monday : day *)\nEval simpl in (next_weekday (next_weekday saturday)).\n   (* ==> tuesday : day *)\n\n(** If you have a computer handy, now would be an excellent\n    moment to fire up the Coq interpreter under your favorite IDE --\n    either CoqIde or Proof General -- and try this for yourself.  Load\n    this file ([Basics.v]) from the book's accompanying Coq sources,\n    find the above example, submit it to Coq, and observe the\n    result. *)\n\n(** The keyword [simpl] (\"simplify\") tells Coq precisely how to\n    evaluate the expression we give it.  For the moment, [simpl] is\n    the only one we'll need; later on we'll see some alternatives that\n    are sometimes useful. *)\n\n(** Second, we can record what we _expect_ the result to be in\n    the form of a Coq example: *)\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\n(** This declaration does two things: it makes an\n    assertion (that the second weekday after [saturday] is [tuesday]),\n    and it gives the assertion a name that can be used to refer to it\n    later. *)\n(** Having made the assertion, we can also ask Coq to verify it,\n    like this: *)\n\nProof. simpl. reflexivity.  Qed.\n\n(** The details are not important for now (we'll come back to\n    them in a bit), but essentially this can be read as \"The assertion\n    we've just made can be proved by observing that both sides of the\n    equality are the same after simplification.\" *)\n\n(** Third, we can ask Coq to \"extract,\" from a [Definition], a\n    program in some other, more conventional, programming\n    language (OCaml, Scheme, or Haskell) with a high-performance\n    compiler.  This facility is very interesting, since it gives us a\n    way to construct _fully certified_ programs in mainstream\n    languages.  Indeed, this is one of the main uses for which Coq was\n    developed.  We'll come back to this topic in later chapters.\n    More information can also be found in the Coq'Art book by Bertot\n    and Casteran, as well as the Coq reference manual. *)\n\n\n(* ###################################################################### *)\n(** ** Booleans *)\n\n(** In a similar way, we can define the type [bool] of booleans,\n    with members [true] and [false]. *)\n\nInductive bool : Type :=\n  | true : bool\n  | false : bool.\n\n(** Although we are rolling our own booleans here for the sake\n    of building up everything from scratch, Coq does, of course,\n    provide a default implementation of the booleans in its standard\n    library, together with a multitude of useful functions and\n    lemmas.  (Take a look at [Coq.Init.Datatypes] in the Coq library\n    documentation if you're interested.)  Whenever possible, we'll\n    name our own definitions and theorems so that they exactly\n    coincide with the ones in the standard library. *)\n\n(** Functions over booleans can be defined in the same way as\n    above: *)\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(** The last two illustrate the syntax for multi-argument\n    function definitions. *)\n\n(** The following four \"unit tests\" constitute a complete\n    specification -- a truth table -- for the [orb] function: *)\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(** _A note on notation_: We use square brackets to delimit\n    fragments of Coq code in comments in .v files; this convention,\n    also used by the [coqdoc] documentation tool, keeps them visually\n    separate from the surrounding text.  In the html version of the\n    files, these pieces of text appear in a [different font]. *)\n\n(** The values [Admitted] and [admit] can be used to fill\n    a hole in an incomplete definition or proof.  We'll use them in the\n    following exercises.  In general, your job in the exercises is \n    to replace [admit] or [Admitted] with real definitions or proofs. *)\n\n(** **** Exercise: 1 star (nandb) *)\n(** Complete the definition of the following functions, then make\n    sure that the [Example] assertions below each can be verified by\n    Coq.  *)\n\n(** This function should return [true] if either or both of\n    its inputs are [false]. *)\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  | false => true\n  end.  \n(* FILL IN HERE *)\n\n(** Remove \"[Admitted.]\" and fill in each proof with \n    \"[Proof. simpl. reflexivity. Qed.]\" *)\n\nExample test_nandb1:               (nandb true false) = true.\n(* FILL IN HERE *)\nProof. simpl. reflexivity. Qed.\nExample test_nandb2:               (nandb false false) = true.\n(* FILL IN HERE *)\nProof. simpl. reflexivity. Qed.\nExample test_nandb3:               (nandb false true) = true.\n(* FILL IN HERE *) \nProof. simpl. reflexivity. Qed.\nExample test_nandb4:               (nandb true true) = false.\n(* FILL IN HERE *) \nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 1 star (andb3) *)\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  (* FILL IN HERE *)\n match b1 with\n     | false => false\n     | true => match b2 with\n                   | false => false\n                   | true => match b3 with\n                                 | false => false\n                                 | true => true\n                             end\n               end\n end.\n\n\nExample test_andb31:                 (andb3 true true true) = true.\n(* FILL IN HERE *)\nProof. simpl. reflexivity. Qed.\nExample test_andb32:                 (andb3 false true true) = false.\n(* FILL IN HERE *)\nProof. simpl. reflexivity. Qed.\nExample test_andb33:                 (andb3 true false true) = false.\n(* FILL IN HERE *) \nProof. simpl. reflexivity. Qed.\nExample test_andb34:                 (andb3 true true false) = false.\n(* FILL IN HERE *) \nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################################### *)\n(** ** Function Types *)\n\n(** The [Check] command causes Coq to print the type of an\n    expression.  For example, the type of [negb true] is [bool]. *)\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\n\n(** Functions like [negb] itself are also data values, just like\n    [true] and [false].  Their types are called _function types_, and\n    they are written with arrows. *)\n\nCheck negb.\n(* ===> negb : bool -> bool *)\n\n(** The type of [negb], written [bool -> bool] and pronounced\n    \"[bool] arrow [bool],\" can be read, \"Given an input of type\n    [bool], this function produces an output of type [bool].\"\n    Similarly, the type of [andb], written [bool -> bool -> bool], can\n    be read, \"Given two inputs, both of type [bool], this function\n    produces an output of type [bool].\" *)\n\n(* ###################################################################### *)\n(** ** Numbers *)\n\n(** _Technical digression_: Coq provides a fairly sophisticated\n    _module system_, to aid in organizing large developments.  In this\n    course we won't need most of its features, but one is useful: If\n    we enclose a collection of declarations between [Module X] and\n    [End X] markers, then, in the remainder of the file after the\n    [End], these definitions will be referred to by names like [X.foo]\n    instead of just [foo].  Here, we use this feature to introduce the\n    definition of the type [nat] in an inner module so that it does\n    not shadow the one from the standard library. *)\n\nModule Playground1.\n\n(** The types we have defined so far are examples of \"enumerated\n    types\": their definitions explicitly enumerate a finite set of\n    elements.  A more interesting way of defining a type is to give a\n    collection of \"inductive rules\" describing its elements.  For\n    example, we can define the natural numbers as follows: *)\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\n(** The clauses of this definition can be read: \n      - [O] is a natural number (note that this is the letter \"[O],\" not\n        the numeral \"[0]\").\n      - [S] is a \"constructor\" that takes a natural number and yields\n        another one -- that is, if [n] is a natural number, then [S n]\n        is too.\n\n    Let's look at this in a little more detail.  \n\n    Every inductively defined set ([weekday], [nat], [bool], etc.) is\n    actually a set of _expressions_.  The definition of [nat] says how\n    expressions in the set [nat] can be constructed:\n\n    - the expression [O] belongs to the set [nat]; \n    - if [n] is an expression belonging to the set [nat], then [S n]\n      is also an expression belonging to the set [nat]; and\n    - expressions formed in these two ways are the only ones belonging\n      to the set [nat]. *)\n\n(** These three conditions are the precise force of the\n    [Inductive] declaration.  They imply that the expression [O], the\n    expression [S O], the expression [S (S O)], the expression\n    [S (S (S O))], and so on all belong to the set [nat], while other\n    expressions like [true], [andb true false], and [S (S false)] do\n    not.\n\n    We can write simple functions that pattern match on natural\n    numbers just as we did above -- for example, predecessor: *)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n    | O => O\n    | S n' => n'\n  end.\n\n(** The second branch can be read: \"if [n] has the form [S n']\n    for some [n'], then return [n'].\"  *)\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\n(** Because natural numbers are such a pervasive form of data,\n    Coq provides a tiny bit of built-in magic for parsing and printing\n    them: ordinary arabic numerals can be used as an alternative to\n    the \"unary\" notation defined by the constructors [S] and [O].  Coq\n    prints numbers in arabic form by default: *)\n\nCheck (S (S (S (S O)))).\nEval simpl in (minustwo 4).\n\n(** The constructor [S] has the type [nat -> nat], just like the\n    functions [minustwo] and [pred]: *)\n\nCheck S.\nCheck pred.\nCheck minustwo.\n\n(** These are all things that can be applied to a number to yield a\n    number.  However, there is a fundamental difference: functions\n    like [pred] and [minustwo] come with _computation rules_\n    -- e.g., the definition of [pred] says that [pred n] can be\n    simplified to [match n with | O => O | S m' => m' end] -- while\n    the definition of [S] has no such behavior attached.  Although it\n    is like a function in the sense that it can be applied to an\n    argument, it does not _do_ anything at all! *)\n\n(** For most function definitions over numbers, pure pattern\n    matching is not enough: we also need recursion.  For example, to\n    check that a number [n] is even, we may need to recursively check\n    whether [n-2] is even.  To write such functions, we use the\n    keyword [Fixpoint]. *)\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(** We can define [oddb] by a similar [Fixpoint] declaration, but here\n    is a simpler definition that will be a bit easier to work with: *)\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\n(** Naturally, we can also define multi-argument functions by\n    recursion.  (Once again, we use a module to avoid polluting the\n    namespace.) *)\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\n(** Adding three to two now gives us five, as we'd expect. *)\n\nEval simpl in (plus (S (S (S O))) (S (S O))).\n\n(** The simplification that Coq performs to reach this conclusion can\n    be visualized as follows: *)\n\n(*  [plus (S (S (S O))) (S (S O))]    \n==> [S (plus (S (S O)) (S (S O)))] by the second clause of the [match]\n==> [S (S (plus (S O) (S (S O))))] by the second clause of the [match]\n==> [S (S (S (plus O (S (S O)))))] by the second clause of the [match]\n==> [S (S (S (S (S O))))]          by the first clause of the [match]\n*)\n\n(** As a notational convenience, if two or more arguments have\n    the same type, they can be written together.  In the following\n    definition, [(n m : nat)] means just the same as if we had written\n    [(n : nat) (m : nat)]. *)\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(** You can match two expressions at once by putting a comma\n    between them: *)\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\n(** The _ in the first line is a _wildcard pattern_.  Writing _ in a\n    pattern is the same as writing some variable that doesn't get used\n    on the right-hand side.  This avoids the need to invent a bogus\n    variable name. *)\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\n(** **** Exercise: 1 star (factorial) *)\n(** Recall the standard factorial function:\n<<\n    factorial(0)  =  1 \n    factorial(n)  =  n * factorial(n-1)     (if n>0)\n>>\n    Translate this into Coq. *)\n\nFixpoint factorial (n:nat) : nat := \n(* FILL IN HERE *)\n  match n with \n      | O => 1\n      | S n' => mult n (factorial n')\n  end.\nExample test_factorial1:          (factorial 3) = 6.\nProof. simpl. reflexivity. Qed.\n(* FILL IN HERE *) \n\nExample test_factorial2:          (factorial 5) = (mult 10 12).\n(* FILL IN HERE *) Proof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** We can make numerical expressions a little easier to read and\n    write by introducing \"notations\" for addition, multiplication, and\n    subtraction. *)\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\n(** (The [level], [associativity], and [nat_scope] annotations\n   control how these notations are treated by Coq's parser.  The\n   details are not important, but interested readers can refer to the\n   \"More on Notation\" subsection in the \"Optional Material\" section at\n   the end of this chapter.) *)\n\n(** Note that these do not change the definitions we've already\n    made: they are simply instructions to the Coq parser to accept [x\n    + y] in place of [plus x y] and, conversely, to the Coq\n    pretty-printer to display [plus x y] as [x + y]. *)\n\n(** When we say that Coq comes with nothing built-in, we really\n    mean it: even equality testing for numbers is a user-defined\n    operation! *)\n(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,\n    yielding a [b]oolean.  Note the use of nested [match]es (we could\n    also have used a simultaneous match, as we did in [minus].)  *)\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\n(** Similarly, the [ble_nat] function tests [nat]ural numbers for\n    [l]ess-or-[e]qual, yielding a [b]oolean. *)\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\n(** **** Exercise: 2 stars (blt_nat) *)\n(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,\n    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for\n    this one, define it in terms of a previously defined function.  \n    \n    Note: If you have trouble with the [simpl] tactic, try using\n    [compute], which is like [simpl] on steroids.  However, there is a\n    simple, elegant solution for which [simpl] suffices. *)\n\nDefinition blt_nat (n m : nat) : bool := \n  match m with\n  | O => false\n  | S m' => ble_nat n (minus m 1) \n  end.\n\nExample test_blt_nat1:             (blt_nat 2 2) = false.\n(* FILL IN HERE *) simpl. reflexivity. Qed.\nExample test_blt_nat2:             (blt_nat 2 4) = true.\n(* FILL IN HERE *) compute. reflexivity. Qed.\nExample test_blt_nat3:             (blt_nat 4 2) = false.\n(* FILL IN HERE *) simpl. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Proof By Simplification *)\n\n(** Now that we've defined a few datatypes and functions, let's\n    turn to the question of how to state and prove properties of their\n    behavior.  Actually, in a sense, we've already started doing this:\n    each [Example] in the previous sections makes a precise claim\n    about the behavior of some function on some particular inputs.\n    The proofs of these claims were always the same: use the\n    function's definition to simplify the expressions on both sides of\n    the [=] and notice that they become identical.\n\n    The same sort of \"proof by simplification\" can be used to prove\n    more interesting properties as well.  For example, the fact that\n    [0] is a \"neutral element\" for [+] on the left can be proved\n    just by observing that [0 + n] reduces to [n] no matter what\n    [n] is, since the definition of [+] is recursive in its first\n    argument. *)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  simpl. reflexivity.  Qed.\n\n(** The form of this theorem and proof are almost exactly the\n    same as the examples above: the only differences are that we've\n    added the quantifier [forall n:nat] and that we've used the\n    keyword [Theorem] instead of [Example].  Indeed, the latter\n    difference is purely a matter of style; the keywords [Example] and\n    [Theorem] (and a few others, including [Lemma], [Fact], and\n    [Remark]) mean exactly the same thing to Coq.\n\n    The keywords [simpl] and [reflexivity] are examples of _tactics_.\n    A tactic is a command that is used between [Proof] and [Qed] to\n    tell Coq how it should check the correctness of some claim we are\n    making.  We will see several more tactics in the rest of this\n    lecture, and yet more in future lectures. *)\n\n(** The [reflexivity] command implicitly simplifies both sides of the\n    equality before testing to see if they are the same, so we can\n    shorten the proof a little. *)\n(** (It will be useful later to know that [reflexivity] actually\n    does somewhat more than [simpl] -- for example, it tries\n    \"unfolding\" defined terms, replacing them with their right-hand\n    sides.  The reason for this difference is that, when reflexivity\n    succeeds, the whole goal is finished and we don't need to look at\n    whatever expanded expressions [reflexivity] has found; by\n    contrast, [simpl] is used in situations where we may have to read\n    and understand the new goal, so we would not want it blindly\n    expanding definitions.) *)\n\nTheorem plus_O_n' : forall n:nat, 0 + n = n.\nProof.\n  reflexivity.  Qed.\n\n(** **** Exercise: 1 star, optional (simpl_plus) *)\n(** What will Coq print in response to this query? *)\n\n(* Eval simpl in (forall n:nat, n + 0 = n). *)\n\n(** What about this one? *)\n\n(* Eval simpl in (forall n:nat, 0 + n = n). *)\n\n(** Explain the difference.  [] *)\n\n(* ###################################################################### *)\n(** * The [intros] Tactic *)\n\n(** Aside from unit tests, which apply functions to particular\n    arguments, most of the properties we will be interested in proving\n    about programs will begin with some quantifiers (e.g., \"for all\n    numbers [n], ...\") and/or hypothesis (\"assuming [m=n], ...\").  In\n    such situations, we will need to be able to reason by _assuming\n    the hypothesis_ -- i.e., we start by saying \"OK, suppose [n] is\n    some arbitrary number,\" or \"OK, suppose [m=n].\"\n\n    The [intros] tactic permits us to do this by moving one or more\n    quantifiers or hypotheses from the goal to a \"context\" of current\n    assumptions.\n\n    For example, here is a slightly different proof of the same theorem. *)\n\nTheorem plus_O_n'' : forall n:nat, 0 + n = n.\nProof.\n  intros n. reflexivity.  Qed.\n\n(** Step through this proof in Coq and notice how the goal and\n    context change. *)\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(** The [_l] suffix in the names of these theorems is\n    pronounced \"on the left.\" *)\n\n(* ###################################################################### *)\n(** * Proof by Rewriting *)\n\n(** Here is a slightly more interesting theorem: *)\n\nTheorem plus_id_example : forall n m:nat,\n  n = m -> \n  n + n = m + m.\n\n(** Instead of making a completely universal claim about all numbers\n    [n] and [m], this theorem talks about a more specialized property\n    that only holds when [n = m].  The arrow symbol is pronounced\n    \"implies.\"\n\n    Since [n] and [m] are arbitrary numbers, we can't just use\n    simplification to prove this theorem.  Instead, we prove it by\n    observing that, if we are assuming [n = m], then we can replace\n    [n] with [m] in the goal statement and obtain an equality with the\n    same expression on both sides.  The tactic that tells Coq to\n    perform this replacement is called [rewrite]. *)\n\nProof.\n  intros n m.   (* move both quantifiers into the context *)\n  intros H.     (* move the hypothesis into the context *)\n  rewrite -> H. (* Rewrite the goal using the hypothesis *)\n  reflexivity.  Qed.\n\n(** The first line of the proof moves the universally quantified\n    variables [n] and [m] into the context.  The second moves the\n    hypothesis [n = m] into the context and gives it the name [H].\n    The third tells Coq to rewrite the current goal ([n + n = m + m])\n    by replacing the left side of the equality hypothesis [H] with the\n    right side.\n\n    (The arrow symbol in the [rewrite] has nothing to do with\n    implication: it tells Coq to apply the rewrite from left to right.\n    To rewrite from right to left, you can use [rewrite <-].  Try\n    making this change in the above proof and see what difference it\n    makes in Coq's behavior.) *)\n\n(** **** Exercise: 1 star (plus_id_exercise) *)\n(** Remove \"[Admitted.]\" and fill in the proof. *)\n\nTheorem plus_id_exercise : forall n m o : nat,\n  n = m -> m = o -> n + m = m + o.\nProof. \nintros n m o.\nintros H1 H2.\nrewrite -> H1.\nrewrite -> H2.\nreflexivity.\nQed.\n  (* FILL IN HERE *)\n(** [] *)\n\n(** As we've seen in earlier examples, the [Admitted] command\n    tells Coq that we want to skip trying to prove this theorem and\n    just accept it as a given.  This can be useful for developing\n    longer proofs, since we can state subsidiary facts that we believe\n    will be useful for making some larger argument, use [Admitted] to\n    accept them on faith for the moment, and continue thinking about\n    the larger argument until we are sure it makes sense; then we can\n    go back and fill in the proofs we skipped.  Be careful, though:\n    every time you say [Admitted] (or [admit]) you are leaving a door\n    open for total nonsense to enter Coq's nice, rigorous, formally\n    checked world! *)\n\n(** We can also use the [rewrite] tactic with a previously proved\n    theorem instead of a hypothesis from the context. *)\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\n(** **** Exercise: 2 stars (mult_1_plus) *)\nTheorem mult_1_plus : forall n m : nat,\n  (1 + n) * m = m + (n * m).\nProof.\nintros n m. \nsimpl. reflexivity. Qed.\n(*TODO use rewrite? *)\n  (* FILL IN HERE *) (** [] *)\n\n(* ###################################################################### *)\n(** * Proof by Case Analysis *) \n\n(** Of course, not everything can be proved by simple\n    calculation: In general, unknown, hypothetical values (arbitrary\n    numbers, booleans, lists, etc.) can block the calculation.  \n    For example, if we try to prove the following fact using the \n    [simpl] tactic as above, we get stuck. *)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. \n  simpl.  (* does nothing! *)\nAdmitted.\n\n(** The reason for this is that the definitions of both\n    [beq_nat] and [+] begin by performing a [match] on their first\n    argument.  But here, the first argument to [+] is the unknown\n    number [n] and the argument to [beq_nat] is the compound\n    expression [n + 1]; neither can be simplified.\n\n    What we need is to be able to consider the possible forms of [n]\n    separately.  If [n] is [O], then we can calculate the final result\n    of [beq_nat (n + 1) 0] and check that it is, indeed, [false].\n    And if [n = S n'] for some [n'], then, although we don't know\n    exactly what number [n + 1] yields, we can calculate that, at\n    least, it will begin with one [S], and this is enough to calculate\n    that, again, [beq_nat (n + 1) 0] will yield [false].\n\n    The tactic that tells Coq to consider, separately, the cases where\n    [n = O] and where [n = S n'] is called [destruct]. *)\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof.\n  intros n. destruct n as [| n'].\n    reflexivity.\n    reflexivity.  Qed.\n\n(** The [destruct] generates _two_ subgoals, which we must then\n    prove, separately, in order to get Coq to accept the theorem as\n    proved.  (No special command is needed for moving from one subgoal\n    to the other.  When the first subgoal has been proved, it just\n    disappears and we are left with the other \"in focus.\")  In this\n    proof, each of the subgoals is easily proved by a single use of\n    [reflexivity].\n\n    The annotation \"[as [| n']]\" is called an _intro pattern_.  It\n    tells Coq what variable names to introduce in each subgoal.  In\n    general, what goes between the square brackets is a _list_ of\n    lists of names, separated by [|].  Here, the first component is\n    empty, since the [O] constructor is nullary (it doesn't carry any\n    data).  The second component gives a single name, [n'], since [S]\n    is a unary constructor.\n\n    The [destruct] tactic can be used with any inductively defined\n    datatype.  For example, we use it here to prove that boolean\n    negation is involutive -- i.e., that negation is its own\n    inverse. *)\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n    reflexivity.\n    reflexivity.  Qed.\n\n(** Note that the [destruct] here has no [as] clause because\n    none of the subcases of the [destruct] need to bind any variables,\n    so there is no need to specify any names.  (We could also have\n    written [as [|]], or [as []].)  In fact, we can omit the [as]\n    clause from _any_ [destruct] and Coq will fill in variable names\n    automatically.  Although this is convenient, it is arguably bad\n    style, since Coq often makes confusing choices of names when left\n    to its own devices. *)\n\n(** **** Exercise: 1 star (zero_nbeq_plus_1) *)\nTheorem zero_nbeq_plus_1 : forall n : nat,\n  beq_nat 0 (n + 1) = false.\nProof.\n  (* FILL IN HERE *) intros n. destruct n as [ |n']. reflexivity. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################################### *)\n(** * More Exercises *)\n\n(** **** Exercise: 2 stars (boolean functions) *)\n(** Use the tactics you have learned so far to prove the following \n    theorem about boolean functions. *)\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. intro. intro. intro. rewrite -> H. rewrite -> H. reflexivity. Qed.\n  (* FILL IN HERE *) \n\n(** Now state and prove a theorem [negation_fn_applied_twice] similar\n    to the previous one but where the second hypothesis says that the\n    function [f] has the property that [f x = negb x].*)\n\n(* FILL IN HERE *)\n\n(** **** Exercise: 2 stars (andb_eq_orb) *)\n(** Prove the following theorem.  (You may need to first prove a\n    subsidiary lemma or two.) *)\n\nTheorem andb_eq_orb : \n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  (* FILL IN HERE *) intro. intro. destruct b. destruct c.\nsimpl.   reflexivity. \nsimpl. intro.  rewrite -> H. reflexivity.\ndestruct c. \nsimpl. intro. rewrite -> H. reflexivity. \nsimpl.  reflexivity. Qed.\n(** **** Exercise: 3 stars (binary) *)\n(** Consider a different, more efficient representation of natural\n    numbers using a binary rather than unary system.  That is, instead\n    of saying that each natural number is either zero or the successor\n    of a natural number, we can say that each binary number is either\n\n      - zero,\n      - twice a binary number, or\n      - one more than twice a binary number.\n\n    (a) First, write an inductive definition of the type [bin]\n        corresponding to this description of binary numbers. \n\n    (Hint: Recall that the definition of [nat] from class,\n    Inductive nat : Type :=\n      | O : nat\n      | S : nat -> nat.\n    says nothing about what [O] and [S] \"mean.\"  It just says \"[O] is\n    in the set called [nat], and if [n] is in the set then so is [S\n    n].\"  The interpretation of [O] as zero and [S] as successor/plus\n    one comes from the way that we _use_ [nat] values, by writing\n    functions to do things with them, proving things about them, and\n    so on.  Your definition of [bin] should be correspondingly simple;\n    it is the functions you will write next that will give it\n    mathematical meaning.)\n\n    (b) Next, write an increment function for binary numbers, and a\n        function to convert binary numbers to unary numbers.\n\n    (c) Write some unit tests for your increment and binary-to-unary\n        functions. Notice that incrementing a binary number and\n        then converting it to unary should yield the same result as first\n        converting it to unary and then incrementing. \n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* ###################################################################### *)\n(** * Optional Material *)\n\n(** ** More on Notation *)\n\nNotation \"x + y\" := (plus 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    For each notation-symbol in Coq we can specify its _precedence level_\n    and its _associativity_. The precedence level n can be specified by the\n    keywords [at level n] and it is helpful to disambiguate\n    expressions containing different symbols. The associativity is helpful\n    to disambiguate expressions containing more occurrences of the same \n    symbol. For example, the parameters specified above for [+] and [*]\n    say that the expression [1+2*3*4] is a shorthand for the expression\n    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and \n    _left_, _right_, or _no_ associativity.\n\n    Each notation-symbol in Coq is also active in a _notation scope_.  \n    Coq tries to guess what scope you mean, so when you write [S(O*O)] \n    it guesses [nat_scope], but when you write the cartesian\n    product (tuple) type [bool*bool] it guesses [type_scope].\n    Occasionally you have to help it out with percent-notation by\n    writing [(x*y)%nat], and sometimes in Coq's feedback to you it\n    will use [%nat] to indicate what scope a notation is in.\n\n    Notation scopes also apply to numeral notation (3,4,5, etc.), so you\n    may sometimes see [0%nat] which means [O], or [0%Z] which means the\n    Integer zero.\n*)\n\n(** ** [Fixpoint]s and Structural Recursion *)\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\n(** When Coq checks this definition, it notes that [plus'] is\n    \"decreasing on 1st argument.\"  What this means is that we are\n    performing a _structural recursion_ over the argument [n] -- i.e.,\n    that we make recursive calls only on strictly smaller values of\n    [n].  This implies that all calls to [plus'] will eventually\n    terminate.  Coq demands that some argument of _every_ [Fixpoint]\n    definition is \"decreasing\".\n    \n    This requirement is a fundamental feature of Coq's design: In\n    particular, it guarantees that every function that can be defined\n    in Coq will terminate on all inputs.  However, because Coq's\n    \"decreasing analysis\" is not very sophisticated, it is sometimes\n    necessary to write functions in slightly unnatural ways. *)\n\n(** **** Exercise: 2 stars, optional (decreasing) *)\n(** To get a concrete sense of this, find a way to write a sensible\n    [Fixpoint] definition (of a simple function on numbers, say) that\n    _does_ terminate on all inputs, but that Coq will _not_ accept\n    because of this restriction. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* $Date: 2013-01-09 14:02:50 -0500 (Wed, 09 Jan 2013) $ *)\n\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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7155275335803275}}
{"text": "Load MyLists.\n\nSearch (nat -> nat -> bool).\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | []        => 0\n  | cons x s' => match (Nat.eqb x v) with\n                | true  => 1 + (count v s')\n                | false => count v s'\n                end\n  end.\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\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 := cons 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\nDefinition member (v:nat) (s:bag) : bool := negb (Nat.leb (count v s) 0).\n\nExample test_member1: member 1 [1;4;1] = true.\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nExample test_member2: member 2 [1;4;1] = false.\nProof.\n  simpl.\n  reflexivity.\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/4_bag_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7154895548075669}}
{"text": "(** *Monoids.\n\nAn implementation of monoids.\n\n *)\n\n(* Lists in the standard library are not universe\n   polymorphic. This does not work well with the\n   `call` element of the Verse AST\n*)\nRequire Import Monoid.PList.\nRequire Export SetoidClass.\nRequire Export Setoid.\nRequire Import RelationClasses.\nRequire Export Relation_Definitions.\n\n\n(* TODO : Move eq_setoid and its setoids monoids to the bottom of the\n          file. Will avoid errors like that happened with\n          dep_point_monoid\n*)\n\nClass BinOp (t : Type) := binop : t -> t -> t.\nInfix \"**\" := binop (right associativity, at level 60).\n\n\n\nClass Monoid t `{Setoid t} `{BinOp t}\n  := { ε  : t;\n       proper_oper    : Proper (SetoidClass.equiv ==> SetoidClass.equiv ==> SetoidClass.equiv) binop;\n       left_identity  : forall x : t, (ε ** x) == x;\n       right_identity : forall x : t, (x ** ε) == x;\n       associativity  : forall x y z : t,\n           (x ** (y ** z)) == ((x ** y) ** z)\n     }.\n\nLtac intro_destruct := let x := fresh \"x\" in (intro x; destruct x; simpl).\n\nLtac crush_monoid :=\n  repeat match goal with\n         | [ H1 : False |- _ ] => intuition\n         | [ _ :  _ = ?X,  _ : ?X = _ |- _ = _ ] => intros; transitivity X; eauto\n         | [ _ :  _ == ?X,  _ : ?X == _ |- _ == _ ] => intros; transitivity X; eauto\n         | [ H : ?X == _ |- context[?X] ] => rewrite H\n         | [ |- context[ε] ] => try (rewrite left_identity); try (rewrite right_identity)\n         | _ => intuition; try (apply associativity)\n         | [ |- _ == _ ] => try (rewrite symmetry)\n         end.\n\nLtac crush_morph_tac n :=\n  do n (do 2 intro_destruct; let hyp := fresh \"eqhyp\" in intro hyp); crush_monoid.\n\nTactic Notation \"crush_morph\" integer(n) := (crush_morph_tac n).\n\n(** It should be possible to rewrite with monoid equivalence and\n    operation. For this we register the underlying setoid equivalence\n    and declare the monoid operation as a morphism *)\n\nAdd Parametric Relation T  (tsetoid : Setoid T)(bop : BinOp T)`{ _ : @Monoid T tsetoid bop} : T  (SetoidClass.equiv)\n    reflexivity proved by (setoid_refl tsetoid)\n    symmetry proved by (setoid_sym (sa:=tsetoid) )\n    transitivity proved by (setoid_trans (sa:=tsetoid) ) as monoid_equivalence.\n\nAdd Parametric Morphism T `{Monoid T} : binop with signature\n    (SetoidClass.equiv ==> SetoidClass.equiv ==> SetoidClass.equiv) as binop_mor.\nProof.\n  exact proper_oper.\nQed.\n\nFixpoint ntimes {t} `{Monoid t} n T\n  := match n with\n     | 0   => ε\n     | S m => T ** ntimes m T\n     end.\n\nDefinition mconcat {t}`{mon: Monoid t} : list t -> t\n  := fun l => fold_left binop l ε.\n\nAdd Parametric Morphism {t} `{Monoid t} (l : list t) : (fold_left binop l)\n    with signature (SetoidClass.equiv ==> SetoidClass.equiv) as foldleft_mor.\nProof.\n  induction l; intros x y eqxy.\n  * trivial.\n  * apply IHl.\n    crush_monoid.\nQed.\n\nDefinition mapMconcat {A}{t}`{mon : Monoid t}\n           (f : A -> t) (xs : list A)\n  : t\n  := mconcat (map f xs).\n\nLemma foldleft_init {t}`{mon: Monoid t} l i1 i2 :\n  fold_left binop l (i1 ** i2) == i1 ** fold_left binop l i2.\nProof.\n  revert i1 i2.\n  induction l; intro i.\n  * simpl.\n    crush_monoid.\n  * simpl.\n    intro.\n    rewrite <- associativity.\n    apply IHl.\nQed.\n\nLemma mapMconcat_app {A}{t}`{mon : Monoid t}\n      (f : A -> t) l1 l2\n  : mapMconcat f (l1 ++ l2) == mapMconcat f l1 ** mapMconcat f l2.\nProof.\n  unfold mapMconcat, mconcat.\n  rewrite map_app.\n  rewrite fold_left_app.\n  induction l2.\n  * simpl.\n    now crush_monoid.\n  * simpl.\n    rewrite left_identity.\n    apply foldleft_init.\nQed.\n\nLemma mapMconcat_cons {A}{t}`{mon : Monoid t}\n      (f : A -> t) a l\n  : mapMconcat f (a :: l) == f a ** mapMconcat f l.\nProof.\n  unfold mapMconcat, mconcat.\n  rewrite map_cons.\n  simpl.\n  rewrite left_identity.\n  rewrite <- (right_identity (f a)).\n  rewrite foldleft_init.\n  now rewrite right_identity.\nQed.\n\n(** ** State transition.\n\nTransitions over a state space are just functions and can be given a\nmonoid structure. In the context of state transition it is more\nnatural to define the monoid multiplication in terms of the reverse\ncomposition. We define a new notation for this and define the monoid\ninstance.\n\n*)\n\n(* begin hide *)\nRequire Import Basics.\n(* end hide *)\n\nNotation \"f >-> g\" := (compose g f) (left associativity, at level 40).\n\n\n(** Now for the laws of monoid *)\n\nModule LawsTransition.\n  Definition left_identity_compose : forall A (f : A -> A),  (@id A) >-> f = f.\n    trivial.\n  Qed.\n\n  Definition right_identity_compose : forall A (f : A -> A),  f >-> (@id A)  = f.\n    trivial.\n  Qed.\n\n  Definition assoc_compose : forall A (f g h : A -> A), f >-> (g >-> h) = (f >-> g) >-> h.\n    trivial.\n  Qed.\n\n  Definition assoc_compose' : forall A (f g h : A -> A), (h >-> g) >-> f = h >-> (g >-> f).\n    trivial.\n  Qed.\n\n\nEnd LawsTransition.\n\nImport LawsTransition.\n\n\n\nSection FunctionEquivalence.\n  Context {B : Type}`{Setoid B}{A : Type}.\n  Definition equiv_function : relation (A -> B) := fun (f g : A -> B) => forall x, f x == g x.\n  Lemma equiv_function_refl : reflexive _ equiv_function.\n    intros f x. reflexivity.\n  Qed.\n\n  Lemma equiv_function_symm : symmetric _ equiv_function.\n    intros f g fEg x.\n    symmetry; eauto.\n  Qed.\n\n  Lemma equiv_function_transitive : transitive _ equiv_function.\n    intros f g h fEg gEh x; transitivity (g x); eauto.\n  Qed.\n\n  Global Add Parametric Relation : (A -> B) equiv_function\n    reflexivity proved by equiv_function_refl\n    symmetry proved by equiv_function_symm\n    transitivity proved by equiv_function_transitive\n  as function_equivalence.\n\nEnd FunctionEquivalence.\n\n\n#[global] Instance function_setoid B `{Setoid B} A : Setoid (A -> B) | 1 :=\n  {| SetoidClass.equiv := equiv_function;\n     setoid_equiv := function_equivalence\n  |}.\n\nSection FunctionEquivalence.\n  Context {B : Type}`{Monoid B}{A : Type}.\n  Definition function_product (f g : A -> B) : A -> B := fun x => f x ** g x.\n\n  Global Add Parametric Morphism : function_product with signature\n      (SetoidClass.equiv ==> SetoidClass.equiv ==> SetoidClass.equiv) as function_product_mor.\n  Proof.\n    intros f g fEQg fp gp fEQgP; intro.\n    unfold function_product. rewrite (fEQg x). rewrite (fEQgP x); reflexivity.\n  Qed.\n\nEnd FunctionEquivalence.\n\n#[global] Instance function_binop A B `{Monoid B} : BinOp (A -> B) :=\n  fun f g x => f x ** g x.\n\n#[global] Program Instance function_monoid A B `{Monoid B} : Monoid (A -> B) | 1 :=\n  {| ε              := fun _ => ε;\n     proper_oper    := function_product_mor_Proper;\n     left_identity  := _;\n     right_identity := _;\n     associativity  := _;\n  |}.\n\nNext Obligation.\n  unfold equiv_function; intros;apply left_identity.\nQed.\n\nNext Obligation.\n  unfold equiv_function; intros; apply right_identity.\nQed.\n\nNext Obligation.\n  unfold equiv_function.\n  intros. apply associativity.\nQed.\n\n(* TODO *)\n#[global] Instance dep_point_setoid A (F : A -> Type)\n         `{forall a, Setoid (F a)}\n  : Setoid (forall a, F a) | 2 :=\n  {| SetoidClass.equiv f g := forall x, f x == g x;\n     setoid_equiv := {|\n                      Equivalence_Reflexive := fun f a =>\n                                                 reflexivity (f a);\n                      Equivalence_Symmetric := fun (f g : forall a, F a)\n                                                   (H :\n                                                      forall a : A,\n                                                        f a == g a)\n                                                   (a : A) =>\n                                                 symmetry (H a);\n                      Equivalence_Transitive := fun (f g h : forall a, F a)\n                                                    (Hfg :\n                                                       forall a : A,\n                                                         (f a == g a))\n                                                    (Hgh :\n                                                       forall a : A,\n                                                         (g a == h a))\n                                                    (a : A) =>\n                                                  transitivity (Hfg a) (Hgh a)\n                    |}\n  |}.\n\n#[global] Instance dep_point_binop  A (F : A -> Type)\n         `{forall a, BinOp (F a)}\n  : BinOp (forall a, F a) := fun f g => fun a => f a ** g a.\n\nAdd Parametric Morphism A (F : A -> Type)\n    `{forall a, Setoid (F a)}\n    `{forall a, BinOp (F a)}\n    `{forall a, Proper (SetoidClass.equiv (A := F a) ==> SetoidClass.equiv ==> SetoidClass.equiv) binop}\n\n  : binop  with signature\n    SetoidClass.equiv (A := forall a, F a) ==> SetoidClass.equiv ==> SetoidClass.equiv\n      as dep_point_binop_mor.\n  intros f g. simpl.\n  intro fEg.\n  intros h k. simpl.\n  intro hEk.\n  intro x. unfold binop. unfold dep_point_binop.\n  rewrite (fEg x).\n  rewrite (hEk x).\n  reflexivity.\nQed.\n\n#[global] Program Instance dep_point_monoid A (F : A -> Type)\n         `{forall a, Setoid (F a)}\n         `{forall a, BinOp (F a)}\n         `{forall a, Monoid (F a)}\n  : Monoid (forall a, F a) | 2\n                          := {| ε := fun _ => ε;\n                                left_identity  := _;\n                                right_identity := _;\n                                associativity  := _;\n                             |}.\nNext Obligation.\n  unfold binop. unfold dep_point_binop. crush_monoid.\nQed.\n\nNext Obligation.\n  unfold binop. unfold dep_point_binop. crush_monoid.\nQed.\n\nNext Obligation.\n  unfold binop. unfold dep_point_binop. crush_monoid.\nQed.\n\n\nClass Hom [t1 t2]`{Monoid t1} `{Monoid t2} (f : t1 -> t2) : Prop\n  := { proper_morphism  : Proper (SetoidClass.equiv ==> SetoidClass.equiv) f;\n       preserves_unit      : f ε == ε;\n       preserves_product   : forall {a b}, f (a ** b) == f a ** f b\n     }.\n\n#[global] Instance monoid_homomorphism_Proper t1 t2 (f : t1 -> t2) `{Hom t1 t2 f} : Proper (SetoidClass.equiv ==> SetoidClass.equiv) f\n  := proper_morphism.\n\nArguments preserves_unit [t1 t2] {_ _ _ _ _} _.\nArguments preserves_product [t1 t2] {_ _ _ _ _} _.\n\n(**\n\nMonoidal version of concat. The function [mconcat] takes a list of\nelements in the monoid and multiplies them to get the results\n\n *)\n\n\n(**  * Monoid instance A + {E}.\n\n*)\n\n\nRequire Import Verse.Error.\n\nSection Error.\n  Context {E : Prop}{A : Type}`{Monoid A}.\n\n  Definition eq_error (x y : A + {E}) : Prop :=\n    match x , y with\n    | error xe, error ye => xe = ye\n    | {- xa -}, {- ya -} => xa == ya\n    | _, _               => False\n    end.\n\n  Lemma eq_error_refl : Reflexive eq_error.\n  Proof.\n    intro; destruct x; simpl; reflexivity.\n  Qed.\n\n  Lemma eq_error_sym : Symmetric  eq_error.\n  Proof.\n    intros x y; destruct x; destruct y; simpl;\n      repeat intuition.\n  Qed.\n\n  Lemma eq_error_trans : Transitive eq_error.\n  Proof.\n    do 3 intro_destruct; crush_monoid.\n  Qed.\n\n  Global Add Parametric Relation : (A + {E}) eq_error\n      reflexivity proved by eq_error_refl\n      symmetry proved by eq_error_sym\n      transitivity proved by eq_error_trans as error_equivalence.\n\n  #[global] Instance error_setoid : Setoid (A + {E}) :=\n    {| SetoidClass.equiv :=  eq_error;\n       SetoidClass.setoid_equiv := error_equivalence\n    |}.\n\n  Definition error_prod (x y : A + {E}) : A + {E} :=\n    match x, y with\n    | {- a -}, {- b -}  => {- a ** b -}\n    | error e, _       => error e\n    | _      , error e => error e\n    end.\n\n\n  Global Add Parametric Morphism : error_prod with signature\n      (eq_error ==> eq_error ==> eq_error) as error_prod_mor.\n  Proof.\n    crush_morph 2.\n  Qed.\n\n  #[global] Instance binop_error : BinOp (A + {E}) := error_prod.\n\n  Global Program Instance error_monoid\n  : Monoid (A + {E}) :=\n  {| ε := {- ε -};\n     left_identity := _;\n     right_identity := _;\n     associativity := _;\n  |}.\n\n\n\n  Next Obligation.\n    destruct x; simpl; trivial; apply left_identity.\n  Qed.\n  Next Obligation.\n    destruct x; simpl; trivial; apply right_identity.\n  Qed.\n\n  Next Obligation.\n    destruct x; destruct y; destruct z; simpl; trivial;apply associativity.\n  Qed.\n\nEnd Error.\n\nSection Prod.\n\n  Context (A B : Type)`{Monoid A} `{Monoid B}.\n  Definition eq_prod (x y : A * B) := (fst x == fst y) /\\ (snd x == snd y).\n\n  Definition eq_prod_refl : Reflexive eq_prod\n      := fun x => conj (Equivalence_Reflexive (fst x)) (Equivalence_Reflexive (snd x)).\n\n  Definition eq_prod_symm : Symmetric eq_prod\n      := fun x y r => let (rf, rs) := r in\n                      conj (Equivalence_Symmetric _ _ rf)\n                           (Equivalence_Symmetric _ _ rs).\n\n  Definition eq_prod_trans : Transitive eq_prod\n      := fun x y z rxy ryz =>\n               let (rxyf, rxys) := rxy in\n               let (ryzf, ryzs) := ryz in\n               conj (Equivalence_Transitive _ _ _ rxyf ryzf)\n                    (Equivalence_Transitive _ _ _ rxys ryzs).\n\n  Add Parametric Relation : (A * B)%type  eq_prod\n      reflexivity proved by eq_prod_refl\n      symmetry proved by eq_prod_symm\n      transitivity proved by eq_prod_trans as prod_equivalence.\n\n  #[global] Instance prod_setoid  : Setoid (A * B)\n    := {| SetoidClass.equiv        := eq_prod; |}.\n\n\n\n  #[global] Instance prod_binop : BinOp (A * B) := fun x y => (fst x ** fst y, snd x ** snd y).\n\n  Global Add Parametric Morphism : binop with signature\n      eq_prod ==> eq_prod ==> eq_prod\n        as product_binop_mor.\n    unfold eq_prod.\n    crush_morph 2.\n  Qed.\n\n  Global Program Instance prod_monoid : Monoid (A * B) :=\n    {| ε := (ε, ε);\n       left_identity := _;\n       right_identity := _;\n       associativity := _\n    |}.\n  Next Obligation.\n    unfold eq_prod; simpl; crush_monoid.\n  Qed.\n\n  Next Obligation.\n    unfold eq_prod; simpl; crush_monoid.\n  Qed.\n\n  Next Obligation.\n    unfold eq_prod; simpl; crush_monoid.\n  Qed.\n\n\nEnd Prod.\nClass LActionOp G A := lact : G -> A -> A.\n\nInfix \"•\" := (lact) (right associativity, at level 58).\n\n(* TODO MAYBE:\n\nOne can also capture right action but since our application is for\ntransforms acting on state predicates, we only capture left actions\nas of now\n\n<<\n\nClass RActionOp A G := ract : A -> G -> A.\nInfix \"↑\" := (ract) (left associativity, at level 59).\n\n>>\n\n *)\n\n\nClass LAction G A `{Monoid A}`{Monoid G}`{LActionOp G A} :=\n  { proper_laction\n    : Proper (SetoidClass.equiv (A:=G) ==> SetoidClass.equiv (A:=A) ==> SetoidClass.equiv (A:=A)) lact;\n    lact_unit                : forall g, g•ε == ε;\n    lact_preserve_product  : forall g a1 a2, g•(a1 ** a2) == g•a1 ** g•a2;\n    lact_trivial           : forall a, ε•a == a;\n    lact_compose           : forall g1 g2 a, (g1 ** g2)•a  == g1•g2•a\n  }.\n\n#[global] Instance monoid_action_Proper G A `{LAction G A}\n  : Proper (SetoidClass.equiv (A:=G) ==> SetoidClass.equiv (A:=A) ==> SetoidClass.equiv(A:=A)) lact\n  := proper_laction.\n\n\nInductive SemiR G A := semiR : G -> A -> SemiR G A.\nInfix \"⋉\" := SemiR (left associativity, at level 59).\n\nDefinition srFst [G A] (sr : SemiR G A) := let (g, _) := sr in g.\nDefinition srSnd [G A] (sr : SemiR G A) := let (_, a) := sr in a.\n\nArguments semiR {G A}.\n\nSection SemiDirectProduct.\n\n  Context {G A : Type}\n          `{LAction G A}.\n\n  Definition eqSemiR (s1 s2 : G ⋉ A) :=\n    match s1, s2 with\n    | semiR g1 a1, semiR g2 a2 =>\n        g1 == g2 /\\ a1 == a2\n    end.\n\n  Definition eqsemi_refl : Reflexive eqSemiR.\n    unfold Reflexive.\n    intro_destruct. crush_monoid.\n  Qed.\n\n  Definition eqsemi_sym : Symmetric eqSemiR.\n    unfold Symmetric.\n    do 2 intro_destruct; crush_monoid.\n  Qed.\n\n  Definition eqsemi_trans : Transitive eqSemiR.\n    unfold Transitive.\n    do 3 intro_destruct; crush_monoid.\n  Qed.\n\n  Global Add Parametric Relation : (G ⋉ A) eqSemiR\n         reflexivity proved by eqsemi_refl\n         symmetry proved by eqsemi_sym\n         transitivity proved by eqsemi_trans as semiR_equiv.\n\n  #[global] Instance rsemi_direct_product : BinOp (G ⋉ A) :=\n    fun s1 s2 => match s1, s2 with\n              | semiR g1 a1, semiR g2 a2 => semiR (g1 ** g2) (a1 ** g1 • a2)\n              end.\n\n  #[global] Instance semiRSetoid : Setoid (G ⋉ A) :=\n    {| SetoidClass.equiv := eqSemiR |}.\n\n  Global Add Parametric Morphism : binop with signature\n         SetoidClass.equiv ==>\n                           SetoidClass.equiv  ==> SetoidClass.equiv\n           as rsemi_direct_product_mor.\n  crush_morph 2.\n  Qed.\n\n  #[global] Program Instance semiR_monoid : Monoid (G ⋉ A) :=\n    {| ε := semiR ε ε;\n      left_identity := _;\n      right_identity := _;\n      associativity := _;\n    |}.\n\n  Next Obligation.\n    destruct x as [g a];\n      simpl; crush_monoid;\n      rewrite (lact_trivial a); crush_monoid.\n  Qed.\n\n  Next Obligation.\n    destruct x as [g a]; simpl;\n      crush_monoid;\n      rewrite (lact_unit g); crush_monoid.\n  Qed.\n\n  Next Obligation.\n    destruct x as [g a];\n      destruct y as [h b];\n      destruct z as [k c]; simpl.\n    crush_monoid.\n    rewrite (lact_compose g h c).\n    rewrite (lact_preserve_product g b (h•c)).\n    crush_monoid.\n  Qed.\n\nEnd SemiDirectProduct.\n\n(** **\n\nThis marks the separator between definitions that should not be using\nthe eq_setoid and those that 'can'.\n\n *)\n\n#[global] Instance eq_setoid T : Setoid T | 10\n  := { equiv := eq }.\n\n#[global] Instance list_append_binop (A : Type) : BinOp (list A) := List.app (A :=A).\n\n#[global] Instance list_is_monoid (A : Type)\n  : Monoid (list A) := {| ε  := nil;\n                          left_identity  := app_nil_l (A:=A);\n                          right_identity := app_nil_r (A:=A);\n                          associativity  := app_assoc (A:=A)\n                       |}.\n\n\n#[global] Instance transition_binop (A : Type) : BinOp (A -> A) :=  fun (f g : A -> A) => compose g f.\n#[global] Instance transition_setoid (A : Type) : Setoid (A -> A) :=\n  {| SetoidClass.equiv := eq |}.\nAdd Parametric Morphism A : binop with signature\n    SetoidClass.equiv (A:= A -> A)==> SetoidClass.equiv  ==> SetoidClass.equiv\n      as transition_mor.\n  crush_monoid.\nQed.\n\n#[global] Program Instance transition_monoid (A : Type) : Monoid (A -> A) :=\n  {| ε := @id A |}.\n\n#[global] Instance prop_prod : BinOp Prop := and.\n#[global] Program Instance prop_monoid : Monoid Prop :=\n  {| ε := True |}.\nNext Obligation.\n  unfold binop; unfold prop_prod. intuition.\nQed.\n\nNext Obligation.\n  unfold binop; unfold prop_prod. intuition.\nQed.\n\nNext Obligation.\n  unfold binop; unfold prop_prod. intuition.\nQed.\n\n(* The following definitions are towards giving a monoid structure for\n   the Abstract Machine.\n\n   Code there is of the type\n\n   (state -> state) * (state * state -> Prop)\n\n   to capture both the state transition and annotations on the state.\n *)\n\n(*\nDefinition comp A B `{Monoid B} : action (A -> A) (A -> B).\n  refine (existT _ twist\n                 {|\n                   well_def := _;\n                   unit_map := _;\n                   commute  := _\n                 |}).\nunfold twist.\nsimpl.\nunfold End.eq.\nsimpl.\nintros.\nunfold \">->\".\nnow rewrite H1.\n\neasy.\neasy.\nDefined.\n\nDefinition halfcomp A B `{Monoid B} : action (A -> A) (A*A -> B).\n\n  refine (existT _ halftwist\n                 {|\n                   well_def := _;\n                   unit_map := _;\n                   commute  := _\n                 |}).\n\nsimpl.\nunfold halftwist.\nunfold End.eq.\nsimpl.\nunfold \">->\".\nintros.\nnow rewrite H1.\n\nsimpl.\nunfold End.eq.\nunfold halftwist.\nsimpl.\nunfold id.\nunfold compose.\nintros.\nnow rewrite <- (surjective_pairing).\n\nnow unfold halftwist.\n\nDefined.\n\n#[global] Instance sdp_halfcomp A B `{Monoid B} : Monoid ((A -> A)*(A*A -> B))\n  := semi_direct_prod _ _ (halfcomp A B).\n*)\n\nRequire List.\nImport List.ListNotations.\n\nGoal [1 ; 2] ** [2 ; 3] = [1 ; 2 ; 2 ; 3].\n  trivial.\nQed.\n\n\nGoal ([1] , [1]) ** ([2] , [2]) = ([1 ; 2] , [1; 2]).\n  trivial.\nQed.\n\nGoal {- [1] -} ** error I = error I.\n  trivial.\nQed.\n", "meta": {"author": "raaz-crypto", "repo": "verse-coq", "sha": "621f86f4adc3bad53458186f0272425db13d2db7", "save_path": "github-repos/coq/raaz-crypto-verse-coq", "path": "github-repos/coq/raaz-crypto-verse-coq/verse-coq-621f86f4adc3bad53458186f0272425db13d2db7/src/Verse/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7154137119221352}}
{"text": "Inductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n\nArguments nil {X}.\nArguments cons {X}.\n\nFixpoint app {X : Type} (l1 l2 : list X) : list X :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(* Prior proven theorems/lemmas *)\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n    intros A l m n. induction l as [| k l' IHl'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHl'. reflexivity.\n    Qed.\n                     \n(* additional lemmas *)\nLemma list_app_nil : forall X (l1 : list X),\n    l1 ++ [] = l1.\nProof.\n    intros X l1. induction l1 as [| n l1' IHl1'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> IHl1'. reflexivity.\n    Qed.\n\n(* exercise *)\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n    intros X l1 l2. induction l1 as [| n l1' IHl'].\n    - simpl. rewrite -> list_app_nil. reflexivity.\n    - simpl. rewrite -> IHl'. rewrite -> app_assoc. reflexivity.\n    Qed.\n\n(* exercise *)\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n    intros X l. induction l as [| n l' IHl'].\n    - simpl. reflexivity.\n    - simpl. rewrite -> rev_app_distr. rewrite -> IHl'. simpl. 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/poly/exercises/more_poly_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339716830605, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7154137069268485}}
{"text": "(* \"especially useful\" *)\n\nInductive natlist : Type :=\n  | nil\n  | cons (n : nat) (l : natlist).\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\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).\n\n\n(* A bag (or multiset) is like a set, except that each element can appear multiple times rather than just once. One possible representation for a bag of numbers is as a list. *)\nDefinition bag := natlist.\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 count (v : nat) (s : bag) : nat :=\n    match s with \n    | nil => O \n    | h :: t => match eqb v h with \n        | true => 1 + count v t\n        | false => count v t\n        end\n    end.\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\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  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\nFixpoint member (v : nat) (s : bag) : bool :=\n  match s with \n  | nil => false \n  | h :: t => match eqb h v with\n    | true => true\n    | false => member v t\n    end\n  end.\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.", "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/lists/exercises/bag_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7154136906232488}}
{"text": "(** This file was originally written by Niels van der Weide and Dan Frumin.  *)\nRequire Import HoTT.\nFrom GCTT Require Export basics.heterogeneous_equality basics.path_over.\n\n(** Squares represents heterogeneous equalities between paths.\n    A square has 4 sides `t`, `l`, `r`, `d` and it represents `l^ @ t @ r = d`.\n    One way to define it, is using an inductive type with one constructor.\n *)\nInductive square {A : Type} : \n  forall {lt rt ld rd : A}\n         (t : lt = rt)\n         (l : ld = lt) (r : rd = rt)\n         (d : ld = rd),\n    Type\n  := id_square : forall {a : A},\n      square (@idpath _ a) idpath idpath (@idpath _ a).\n\n(** We can also use another constructor. *)\nInductive square_lr  {A : Type} : \n  forall {lt rt ld rd : A}\n         (t : lt = rt)\n         (l : ld = lt) (r : rd = rt)\n         (d : ld = rd),\n    Type\n  := id_square_lr : forall {t d : A}\n                           {l : d = t} {r : d = t}\n                           (h : l = r),\n      square_lr idpath l r idpath.\n\nSection equivalences.\n  (** An equivalent definition of `square t l r d` is `l @ t = d @ r`.\n      So, it is equivalent to a homotopy.\n   *)\n  Definition square_to_path\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n             (s : square t l r d)\n    : l @ t = d @ r\n    := match s with\n       | id_square a => idpath\n       end.\n\n  Definition path_to_square\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n             (p : l @ t = d @ r)\n    : square t l r d.\n  Proof.\n    induction t, l, d.\n    exact (transport\n             (fun z => square 1 1 z 1)\n             (cancelL idpath idpath r p)\n             id_square).\n  Defined.\n\n  Global Instance square_to_path_is_equiv\n         {A : Type}\n         {lt rt ld rd : A}\n         {t : lt = rt}\n         {l : ld = lt} {r : rd = rt}\n         {d : ld = rd}\n    : IsEquiv (@square_to_path _ _ _ _ _ t l r d).\n  Proof.\n    simple refine (isequiv_adjointify _ path_to_square _ _).\n    - intros p.\n      induction t, l, d ; cbn.\n      refine (_ @ @eissect _ _ (cancelL 1 1 r) (isequiv_cancelL _ _ _) _).\n      induction (cancelL idpath idpath r p) ; cbn.\n      reflexivity.\n    - intros x.\n      induction x ; reflexivity.\n  Defined.\n\n  (** The two inductive definitions of squares are equivalent. *)\n  Definition square_to_square_lr\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n             (s : square t l r d)             \n    : square_lr t l r d\n    := match s with\n       | id_square _ => id_square_lr idpath\n       end.\n\n  Definition square_lr_to_square\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n             (s : square_lr t l r d)\n    : square t l r d.\n  Proof.\n    induction s, l.\n    exact (transport\n             (fun z => square idpath idpath z idpath)\n             h\n             id_square).\n  Defined.\n\n  Global Instance square_to_square_lr_isequiv\n         {A : Type}\n         {lt rt ld rd : A}\n         {t : lt = rt}\n         {l : ld = lt} {r : rd = rt}\n         {d : ld = rd}\n    : IsEquiv (@square_to_square_lr _ _ _ _ _ t l r d).\n  Proof.\n    simple refine (isequiv_adjointify _ square_lr_to_square _ _).\n    - intros x.\n      induction x, l, h ; reflexivity.\n    - intros x ; induction x.\n      reflexivity.\n  Defined.\n\n  (** A square is a path over a pair of paths in a family of paths. *)\n  Definition square_to_path_over\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n             (s : square t l r d)             \n    : path_over (fun (x : A * A) => fst x = snd x) (path_prod' d t) l r\n    := match s with\n       | id_square a => path_over_id _\n       end.\n\n  Definition path_over_to_square\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n             (q : path_over (fun (x : A * A) => fst x = snd x) (path_prod' d t) l r)\n    : square t l r d.\n  Proof.\n    induction t, l, d.\n    exact (transport\n             (fun z => square idpath idpath z idpath)\n             (path_over_to_path q)\n             id_square).\n  Defined.\n\n  Global Instance square_to_path_over_is_equiv\n         {A : Type}\n         {lt rt ld rd : A}\n         {t : lt = rt}\n         {l : ld = lt} {r : rd = rt}\n         {d : ld = rd}\n    : IsEquiv (@square_to_path_over A lt rt ld rd t l r d).\n  Proof.\n    simple refine (isequiv_adjointify _ (@path_over_to_square A _ _ _ _ t l r d) _ _).\n    - intros x ; induction t, l, d ; cbn in *.\n      refine (_ @ eissect path_over_to_path x).\n      induction (path_over_to_path x).\n      reflexivity.\n    - intros x ; induction x.\n      reflexivity.\n  Defined.\nEnd equivalences.\n\nSection operations.\n  (** We have two identity paths.\n      The first one is between the top and bottom side.\n   *)\n  Definition hrefl\n             {A : Type} {a b : A}\n             (p : a = b)\n    : square p idpath idpath p\n    := match p with\n       | idpath => id_square\n       end.\n\n  (** The second identity is between the left and right side. *)\n  Definition vrefl\n             {A : Type} {a b : A}\n             (p : a = b)\n    : square idpath p p idpath\n    := match p with\n       | idpath => id_square\n       end.\n\n  (** We can apply maps to squares. *)\n  Definition ap_square\n             {A B : Type} (f : A -> B)\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n             (s : square t l r d)\n    : square (ap f t) (ap f l) (ap f r) (ap f d)\n    := match s with\n       | id_square _ => id_square\n       end.\n\n  (** We can make squares of pairs. *)\n  Definition pair_square\n             {A B : Type}\n             {lta rta lda rda : A}\n             {ta : lta = rta}\n             {la : lda = lta} {ra : rda = rta}\n             {da : lda = rda}\n             {ltb rtb ldb rdb : B}\n             {tb : ltb = rtb}\n             {lb : ldb = ltb} {rb : rdb = rtb}\n             {db : ldb = rdb}\n             (sa : square ta la ra da)\n             (sb : square tb lb rb db)\n    : square (path_prod' ta tb)\n             (path_prod' la lb)\n             (path_prod' ra rb)\n             (path_prod' da db)\n    := match sa, sb with\n       | id_square _, id_square _ => id_square\n       end.\n\n  (** We can move a square along paths in each coordinate. *)\n  Definition whisker_square\n             {A : Type}\n             {lt rt ld rd : A}\n             {t₁ t₂ : lt = rt}\n             {l₁ l₂ : ld = lt} {r₁ r₂ : rd = rt}\n             {d₁ d₂ : ld = rd}\n             (pt : t₁ = t₂)\n             (pl : l₁ = l₂) (pr : r₁ = r₂)\n             (pd : d₁ = d₂)\n             (s : square t₁ l₁ r₁ d₁)\n    : square t₂ l₂ r₂ d₂.\n  Proof.\n    induction s.\n    refine (transport (square t₂ l₂ r₂) pd _).\n    refine (transport (fun z => square t₂ l₂ z _) pr _).\n    refine (transport (fun z => square t₂ z _ _) pl _).\n    exact (transport (fun z => square z _ _ _) pt id_square).\n  Defined.\n\n  (** Vertical composition of squares. *)\n  Definition compose_square_v\n             {A : Type}\n             {lt rt : A}\n             {lm rm : A}\n             {ld rd : A}\n             {t : lt = rt}\n             {l₁ : lm = lt} {r₁ : rm = rt}\n             {m : lm = rm}\n             {l₂ : ld = lm} {r₂ : rd = rm}\n             {d : ld = rd}\n             (s₁ : square t l₁ r₁ m)\n             (s₂ : square m l₂ r₂ d)\n    : square t (l₂ @ l₁) (r₂ @ r₁) d.\n  Proof.\n    induction s₁.\n    exact (whisker_square\n             idpath\n             (concat_p1 l₂)^\n             (concat_p1 r₂)^\n             idpath\n             s₂).\n  Defined.\n\n  (** Horizontal composition of squares. *)\n  Definition compose_square_h\n             {A : Type}\n             {lt mt rt : A}\n             {ld md rd : A}\n             {t₁ : lt = mt} {t₂ : mt = rt}\n             {l : ld = lt} {m : md = mt} {r : rd = rt}\n             {d₁ : ld = md} {d₂ : md = rd}\n             (s₁ : square t₁ l m d₁)\n             (s₂ : square t₂ m r d₂)\n    : square (t₁ @ t₂) l r (d₁ @ d₂).\n  Proof.\n    induction s₁.\n    exact (whisker_square\n             ((concat_1p t₂)^)\n             idpath\n             idpath\n             ((concat_1p d₂)^)\n             s₂).\n  Defined.\n\n  (** We can rotate squares.\n      This gives an equivalence.\n   *)\n  Definition square_symmetry\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n             (s : square t l r d)\n    : square r d t l\n    := match s with\n       | id_square _ => id_square\n       end.\n\n  Global Instance square_symmetry_isequiv\n         {A : Type}\n         {lt rt ld rd : A}\n         {t : lt = rt}\n         {l : ld = lt} {r : rd = rt}\n         {d : ld = rd}\n    : IsEquiv (@square_symmetry A lt rt ld rd t l r d).\n  Proof.\n    simple refine (isequiv_adjointify _ square_symmetry _ _) ;\n      intro x ; induction x ; reflexivity.\n  Defined.\n\n  (** If one side of the square is missing, then we can fill it.\n      This is a Kan-filling.\n   *)\n  Definition fill_square_top\n             {A : Type}\n             {lt rt ld rd : A}\n             {l : ld = lt} {r : rd = rt}\n             {d : ld = rd}\n    : {t : lt = rt & square t l r d}\n    := (l^ @ d @ r;\n          path_to_square ((concat_p_pp _ _ _)\n                            @ (ap (fun z => z @ _) (concat_p_pp _ _ _))\n                            @ (ap (fun z => (z @ _) @ _) (concat_pV l))\n                            @ (ap (fun z => z @ _) (concat_1p _)))).\n\n  Definition fill_square_left\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {r : rd = rt}\n             {d : ld = rd}\n    : {l : ld = lt & square t l r d}\n    := (d @ r @ t^;\n          path_to_square ((ap (fun z => z @ _) (concat_pp_p _ _ _))\n                            @ (concat_pp_p _ _ _)\n                            @ (ap (fun z => _ @ z) (concat_pp_p _ _ _))\n                            @ (ap (fun z => _ @ (_ @ z)) (concat_Vp _))\n                            @ (ap (fun z => _ @ z) (concat_p1 _)))).\n\n  Definition fill_square_right\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt}\n             {d : ld = rd}\n    : {r : rd = rt & square t l r d}\n    := (d^ @ l @ t;\n          path_to_square ((ap (fun z => z @ _) (concat_1p _)^)\n                            @ (ap (fun z => (z @ _) @ _) (concat_pV _)^)\n                            @ (ap (fun z => z @ _) (concat_p_pp _ _ _)^)\n                            @ (concat_p_pp _ _ _)^)).\n\n  Definition fill_square_down\n             {A : Type}\n             {lt rt ld rd : A}\n             {t : lt = rt}\n             {l : ld = lt} {r : rd = rt}\n    : {d : ld = rd & square t l r d}\n    := (l @ t @ r^;\n          path_to_square ((ap (fun z => _ @ z) (concat_p1 _)^)\n                            @ (ap (fun z => (_ @ (_ @ z))) (concat_Vp _)^)\n                            @ (ap (fun z => _ @ z) (concat_pp_p _ _ _)^)\n                            @ ((concat_pp_p _ _ _)^)\n                            @ (ap (fun z => z @ _) (concat_pp_p _ _ _)^))).\n\n  (** Next we want look at squares of the form `square t (ap f p) (ap g p) d`.\n      These are the same as paths over `p` in the family `f z = g z.\n      For that, we first need some lemmata.\n   *)\n  Definition path_to_transport\n             {A B : Type} {f g : A -> B}\n             {a₁ a₂ : A} {p : a₁ = a₂}\n    : forall {l : f a₁ = g a₁} {r : f a₂ = g a₂} (q : ap f p @ r = l @ ap g p),\n      transport (fun z : A => f z = g z) p l = r\n    := match p with\n       | idpath => fun l r q => (concat_p1 l)^ @ q^ @ concat_1p r\n       end.\n\n  Definition transport_to_path\n             {A B : Type} {f g : A -> B}\n             {a₁ a₂ : A} {p : a₁ = a₂}\n    : forall {l : f a₁ = g a₁} {r : f a₂ = g a₂}\n             (q : transport (fun z : A => f z = g z) p l = r),\n      ap f p @ r = l @ ap g p\n    := match p with\n       | idpath => fun l r q => concat_1p r @ q^ @ (concat_p1 l)^\n       end.\n\n  Global Instance path_to_transport_is_equiv\n         {A B : Type} {f g : A -> B}\n         {a₁ a₂ : A} {p : a₁ = a₂}\n         {l : f a₁ = g a₁} {r : f a₂ = g a₂}\n    : IsEquiv (@path_to_transport A B f g a₁ a₂ p l r).\n  Proof.\n    simple refine (isequiv_adjointify _ transport_to_path _ _).\n    - intros x.\n      induction x, p ; cbn.\n      rewrite !inv_pp, inv_V ; cbn.\n      hott_simpl.\n    - intros x.\n      induction p ; cbn in * ; induction l ; cbn in *.\n      rewrite !inv_pp, !inv_V ; cbn.\n      hott_simpl.\n  Defined.\n\n  (** `path_over` in a family of equations is the same as giving a square. *)\n  Definition map_path_over\n             {A B : Type} {f g : A -> B}\n             {a₁ a₂ : A} {p : a₁ = a₂}\n             {l : f a₁ = g a₁} {r : f a₂ = g a₂}\n    : square r (ap f p) (ap g p) l -> path_over (fun z => f z = g z) p l r\n    := path_over_to_path^-1 o path_to_transport o square_to_path.\n\n  Global Instance path_over_map_isequiv\n         {A B : Type} {f g : A -> B}\n         {a₁ a₂ : A} {p : a₁ = a₂}\n         {l : f a₁ = g a₁} {r : f a₂ = g a₂}\n    : IsEquiv (@map_path_over A B f g a₁ a₂ p l r).\n  Proof.\n    unfold map_path_over.\n    apply isequiv_compose.\n  Defined.\nEnd operations.\n\n(** `path_over` in a family of equations between dependent maps is the same as a square. *)\nDefinition map_path_over_D\n           {A : Type}\n           {Y : A -> Type}\n           (f g : forall (a : A), Y a)\n           {a₁ a₂ : A}\n           (p : a₁ = a₂)\n           (c₁ : f a₁ = g a₁) (c₂ : f a₂ = g a₂)\n           (s : square c₂ (apD f p) (apD g p) (ap (transport Y p) c₁))\n  : path_over (fun a => f a = g a) p c₁ c₂.\nProof.\n  induction p.\n  apply path_to_path_over ; simpl in *.\n  exact ((concat_1p _)^ @ square_to_path s @ concat_p1 _ @ ap_idmap _)^.\nDefined.\n", "meta": {"author": "kalfsvag", "repo": "group_completions", "sha": "cc65e902a68dbb6dc05315651dce3064704a9815", "save_path": "github-repos/coq/kalfsvag-group_completions", "path": "github-repos/coq/kalfsvag-group_completions/group_completions-cc65e902a68dbb6dc05315651dce3064704a9815/cquot/basics/square.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7153932197520508}}
{"text": "From mathcomp Require Import ssreflect ssrbool eqtype ssrnat ssralg ssrnum ssrint.\n\nImport GRing.\nOpen Scope ring_scope.\n\nDefinition IMO1_problem (f: int -> int) := forall a b: int,\n    (f(a * 2%:R) + f(b) * 2%:R = f(f(a + b))).\n\nDefinition IMO1_solution (f: int -> int) :=\n  (exists t : int, forall x, f(x) = (x * 2%:R + t))\n  \\/ (forall x, f(x) = 0).\n\nTheorem IMO1_complete (f: int -> int): IMO1_problem f -> IMO1_solution f.\nProof.\n  move=> H.\n  have H1 : (forall a : int, f(a*2%:R) + f(0) = f(a)*2%:R).\n    move=> a; apply/eqP; rewrite eq_sym -subr_eq -(addrKA (f 0)) subr_eq -mulr2n.\n    by rewrite -[f 0 *+ _]mulr_natr -{1}addrC -(mul0r 2%:R) !H add0r mul0r addr0.\n  have H2 : (forall a b c d : int, a + b = c + d -> f(a) + f(b) = f(c) + f(d)).\n  move=> a b c d abcd_eq; apply: (@mulrIz int_numDomainType 2%:R); first by [].\n  rewrite -![2%:R *~ _]mulrzl !intz !mulrDl -[f(a)*_]H1 -[f(c)*_]H1 -![_ + f 0]addrC.\n  by rewrite -!addrA; congr(_ + _); rewrite !H abcd_eq.\n  have H3 : (forall a : int, f(a) = (f(1) - f(0))*a + f(0)).\n  elim/int_ind => [| n IHn| n IHn]; first by rewrite mulr0 add0r.\n  rewrite !intS; have H4 : f(0) + f(n.+1) = f(1) + f(n) by apply H2.\n  rewrite -(addr0 (f (1 + n%:Z))) -{1}(subrr (f 0)) addrA [_ + f 0]addrC H4 IHn.\n  rewrite !mulrDl !mulrDr !mulr1 -(addrA (f 1 * n)) (addrA (f 1)).\n  rewrite -2?(addrA (f 1 + f 1 * n)); congr(_ + _); by rewrite addrC addrA.\n  rewrite !intS; have H5 : f(1) + f(-(1 + n%:Z)) = f(0) + f(-n%:Z).\n    by apply H2; rewrite -{1}(add0r 1) addrKA.\n  rewrite -(addr0 (f (-(1 + n%:Z)))) -{1}(subrr (f 1)) addrA [_ + f 1]addrC H5 IHn.\n  rewrite !mulrDl addrA addrC (addrC (f 0)) 3?addrA -{1}(mulr1 (f 1)) -mulrN.\n  rewrite -{2 3 5}(mulr1 (f 0)) !mulrNN -2?addrA -[in RHS]addrA; congr(_ + _).\n    by rewrite -mulrDr; congr(_ * _); apply/eqP; rewrite -addr_eq0 (addrC 1) subrKA.\n  rewrite -!mulrDr; congr(_ * _); by rewrite addrA (addrC n%:Z).\n  move:(H 0 0); rewrite mul0r add0r [in f(f(_))]H3 mulrC -{1 5}(mul1r (f 0)) -!mulrDl.\n  set f00 := (f 0 == 0); have H6 : ((f 0 == 0) = f00) by [].\n  case: f00 H6 => /eqP; rewrite ?eqb_id ?eqbF_neg; move=> H6.\n    move=> _; move: (H 0 1); rewrite [in f(f(_))]H3 H6 subr0 !add0r addr0.\n    set f10 := (f 1 == 0); have H7 : ((f 1 == 0) = f10) by [].\n    case: f10 H7 => /eqP; move=> H8.\n      move=> _; right; move=> x; by rewrite H3 H6 H8 subr0 mul0r.\n    move=> H9; have H10: f 1 = 2.\n      apply: (@mulrIz int_numDomainType (f 1)); first by apply/eqP.\n      by rewrite -![(f 1) *~ _]mulrzl !intz -H9 mulrC.\n    left; exists 0; move=> x; by rewrite H3 H6 H10 subr0 !addr0 mulrC.\n  move=> H11; left; exists (f 0); move=> x; rewrite H3 mulrC; congr((_ * _) + _).\n  apply/eqP; rewrite -(addr0 (f 1 - f 0)) -{2}(subrr 1) addrA subr_eq eq_sym addrC.\n  apply/eqP; apply: (@mulrIz int_numDomainType (f 0)) ; first by apply/eqP.\n     by rewrite -![(f 0) *~ _]mulrzl !intz -H11 mulrC.\nQed.\n\nTheorem IMO1_sound (f: int -> int): IMO1_solution f -> IMO1_problem f.\nProof.\n  move=> [[t H] | H] a b; rewrite !H; last by rewrite mul0r.\n  rewrite !mulrDl -!(addrA (a * 2 * 2)); congr(_ + _); by rewrite addrC.\nQed.\n", "meta": {"author": "bdiehs", "repo": "IMOcoq", "sha": "d192270b22be6b0e78ac467a935d5951e9bf617c", "save_path": "github-repos/coq/bdiehs-IMOcoq", "path": "github-repos/coq/bdiehs-IMOcoq/IMOcoq-d192270b22be6b0e78ac467a935d5951e9bf617c/IMO2019_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7153760085953106}}
{"text": "(******************************************************************************\nSeptember 2004\nAuthors: Jean-Yves Vion-dury and Pierre Geneves \n\njean-yves.vion-dury@xrce.xerox.com\nWAM Research Project, INRIA Rhone-Alpes and Xerox Research Center Europe\n\npierre.geneves@inrialpes.fr\nWAM Research Project, INRIA Rhone-Alpes\n\nPlease do not reuse or publish this code without explicit consent from authors.\n*******************************************************************************)\nRequire Import ZArith.\nRequire Import setOrder.\nRequire Import Bool.\nRequire Import genSetsInt.\n\n\nModule geneSets (theorder: CmpOrderTheory) : genSetsInt with Definition\n  A := theorder.A with Definition A_le := theorder.le with Definition\n  A_lt := theorder.lt with Definition A_eq := theorder.eq. \n\nDefinition A := theorder.A.\nDefinition A_le := theorder.le.\nDefinition A_lt := theorder.lt.\nDefinition A_eq := theorder.eq. \n\n\n\n(* ----------------------------------------------------------------- *)\n(*\tthe data structure, very much like lists                     *)\n\nInductive set : Set :=\n  | empty : set\n  | item : A -> set -> set.\n \nDefinition single (x : A) := item x empty.\n\n(*  -----------------------------------------------------------------\n     tests the membership\n ----------------------------------------------------------------- \nFixpoint s_in [a:A;s:set]: bool :=\nCases s of \n| empty => false\n| (item b ss) => if (A_le b a) \n\t         then \n\t\t      if (A_le a b) \n\t\t      then true\n\t\t      else (s_in a ss)\n\t\t else \n \t\t      false\nend.\n*)\n\n\n\n(*  -----------------------------------------------------------------\n     tests the membership (simplified)\n ----------------------------------------------------------------- *)\n\nFixpoint s_in (a : A) (s : set) {struct s} : bool :=\n  match s with\n  | empty => false\n  | item b ss => if A_eq a b then true else s_in a ss\n  end.\n\n\n\n\n(*  -----------------------------------------------------------------\n     Concatenation of two sets\n ----------------------------------------------------------------- *)\n\nFixpoint cat (s1 s2 : set) {struct s1} : set :=\n  match s1 with\n  | empty => s2\n  | item a ss1 => item a (cat ss1 s2)\n  end.\n\n\n(* ---------------------------------------------------------------- *)\n(* Well formedness: all items are unique in the set, and ordered    *)\n(*----------------------------------------------------------------- *)\nFixpoint wf (s : set) : bool :=\n  match s with\n  | empty => true\n  | item a ss =>\n      if s_in a ss\n      then false\n      else\n       if wf ss\n       then match ss with\n            | item b _ => A_lt a b\n            | empty => true\n            end\n       else false\n  end.\n\n\n\n(* -----------------------------------------------------------------\n\tcardinal of sets. Always positive Z \n-----------------------------------------------------------------  *)\nFixpoint card (s : set) : Z :=\n  match s with\n  | empty => 0%Z\n  | item _ ss => Zsucc (card ss)\n  end.\n(* Zs is the successor function for Z *)\n\n\n(* -----------------------------------------------------------------\n\tconstructors and tests \n-----------------------------------------------------------------  *)\n\nFixpoint add (a : A) (s : set) {struct s} : set :=\n  match s with\n  | empty => item a empty\n  | item b ss =>\n      if A_le b a\n      then if A_le a b then s else item b (add a ss)\n      else item a s\n  end.\n\nFixpoint sub (a : A) (s : set) {struct s} : set :=\n  match s with\n  | empty => empty\n  | item b ss =>\n      if A_le b a then if A_le a b then ss else item b (sub a ss) else s\n  end.\n\nSection set_reduction.\n\n Variable B : Set.\n Fixpoint reduce (f : B -> A -> B) (b : B) (s : set) {struct s} : B :=\n   match s with\n   | empty => b\n   | item a ss => reduce f (f b a) ss\n   end.\n\nEnd set_reduction.\n\n\n\n  Fixpoint inter (x : set) : set -> set :=\n    match x with\n    | empty => fun y => empty\n    | item a1 x1 =>\n        fun y => if s_in a1 y then item a1 (inter x1 y) else inter x1 y\n    end.\n\n  Fixpoint union (x y : set) {struct y} : set :=\n    match y with\n    | empty => x\n    | item a1 y1 => add a1 (union x y1)\n    end.\n\n        \n  (** returns the set of all els of [x] that does not belong to [y] *)\n  Fixpoint diff (x y : set) {struct x} : set :=\n    match x with\n    | empty => empty\n    | item a1 x1 => if s_in a1 y then diff x1 y else item a1 (diff x1 y)\n    end.\n\n\n\n    Fixpoint incl (s1 s2 : set) {struct s1} : bool :=\n      match s1 with\n      | empty => true\n      | item a s => if s_in a s2 then incl s s2 else false\n      end.\n\n    Fixpoint s_eq (s1 s2 : set) {struct s2} : bool :=\n      match s1, s2 with\n      | empty, empty => true\n      | item a1 ss1, item a2 ss2 =>\n          if A_eq a1 a2 then s_eq ss1 ss2 else false\n      | _, _ => false\n      end.\n(*\n    Definition s_eq:set->set->bool :=\n\t[s1,s2:set]\n\tif (incl s1 s2) then (incl s2 s1) else false\n\t.\n*)\n    Fixpoint product (s : set) (fs : A -> set) {struct s} : set :=\n      match s with\n      | empty => empty\n      | item a s1 => union (fs a) (product s1 fs)\n      end.\n\n\n    Fixpoint filter (s : set) (fs : A -> bool) {struct s} : set :=\n      match s with\n      | empty => empty\n      | item a s1 => if fs a then item a (filter s1 fs) else filter s1 fs\n      end.\n\n\n\n\n(* ----- Properties ------- *)\n\n\n\n\nAxiom not_single_empty : forall x : A, single x <> empty.\nAxiom single_sem : forall x : A, s_in x (single x) = true.\nAxiom in_single : forall x y : A, s_in x (single y) = true -> x=y.\n\n\n\n\n\n(* ----- cat ------- *)\n\t\n\t\nAxiom\n  cat_incl :\n    forall s1 s2 : set,\n    wf (cat s1 s2) = true ->\n    forall a : A,\n    (s_in a s1 = true -> s_in a s2 = false) /\\\n    (s_in a s2 = true -> s_in a s1 = false).\n\nAxiom\n  cat_union :\n    forall s1 s2 : set, wf (cat s1 s2) = true -> cat s1 s2 = union s1 s2.\nAxiom\n  cat_inter :\n    forall s1 s2 : set, wf (cat s1 s2) = true -> inter s1 s2 = empty.\n\n\n\n\n\n\n(* ----- in ------- *)\n\nTheorem in_add2 : forall (a : A) (s : set), s_in a (add a s) = true.\nProof.\nintros.\ninduction  s as [| a0 s Hrecs].\nsimpl in |- *.\nassert (H := theorder.eq_reflexive a).\ncompute in |- *.\nrewrite H.\nreflexivity.\n\nsimpl in |- *.\ncut ({A_le a a0 = true} + {A_le a a0 = false}).\ncut ({A_le a0 a = true} + {A_le a0 a = false}).\nintros.\nelim H.\nelim H0.\nintros.\nrewrite a1.\nrewrite a2.\nassert (a = a0).\napply theorder.le_antisymmetric.\nassumption.\n\nassumption.\n\nrewrite H1.\nsimpl in |- *.\nassert (A_eq a0 a0 = true).\napply theorder.eq_reflexive.\n\nrewrite H2.\nreflexivity.\n\nintros.\nrewrite b.\nrewrite a1.\nsimpl in |- *.\nassert (A_eq a a0 = false).\ncompute in |- *.\napply theorder.le_nle_neq.\nassumption.\n\nassumption.\n\nrewrite H1.\napply Hrecs.\n\nintros.\nrewrite b.\nsimpl in |- *.\nassert (A_eq a a = true).\napply theorder.eq_reflexive.\n\nrewrite H1.\nreflexivity.\n\napply theorder.le_dec.\n\napply theorder.le_dec.\nQed.\n\n\n\nTheorem in_add :\n forall (a : A) (s : set),\n s_in a s = true -> forall b : A, s_in a (add b s) = true.\nProof.\nsimple induction s.\nsimpl in |- *.\nintros.\ndiscriminate.\n\nintros.\nassert ({A_eq a b = true} + {A_eq a b = false}).\napply theorder.eq_dec.\n\nelim H1.\nintro.\nassert (a = b).\napply theorder.eq_eq.\ncompute in a1.\nassumption.\n\nrewrite H2.\napply in_add2.\n\nintro.\nsimpl in |- *.\ncut ({A_le a0 b = true} + {A_le a0 b = false}).\ncut ({A_le b a0 = true} + {A_le b a0 = false}).\nintros.\nelim H2.\nelim H3.\nintros.\nrewrite a1.\nrewrite a2.\nassumption.\n\nintros.\nrewrite b1.\nsimpl in |- *.\nrewrite b0.\nunfold s_in in H0.\nassumption.\n\nintros.\nrewrite b1.\nelim H3.\nintro.\nrewrite a1.\nsimpl in |- *.\ncut ({A_eq a a0 = true} + {A_eq a a0 = false}).\nintros.\nelim H4.\nintro.\nrewrite a2.\nreflexivity.\n\nintro.\nrewrite b2.\napply H.\nunfold s_in in H0.\nrewrite b2 in H0.\nexact H0.\n\napply theorder.eq_dec.\n\nintro.\nrewrite b2.\nunfold s_in in |- *.\nrewrite b0.\nassumption.\n\napply theorder.le_dec.\n\napply theorder.le_dec.\nQed.\n\n\n\n\n\n\n\n\n\nAxiom\n  nin_add :\n    forall (a b : A) (s : set), s_in a (add b s) = false -> s_in a s = false.\n\n(*\nInduction s.\nSimpl.\nIntros.\nReflexivity.\n\nIntros.\nSimpl in H0.\nCut {(A_le a0 b)=true}+{(A_le a0 b)=false}.\nCut {(A_le b a0)=true}+{(A_le b a0)=false}.\nIntros.\nElim H1.\nElim H2.\nIntros.\nRewrite -> a1 in H0.\nRewrite -> a2 in H0.\nAssumption.\n\nIntros.\nRewrite -> a1 in H0.\nRewrite -> b0 in H0.\nExact ((nin_succ a b (item a0 s0)) H0).\n\nIntro.\nRewrite -> b0 in H0.\nElim H2.\nIntro.\nRewrite -> a1 in H0.\n\n \n \n\nAxiom nin_add2 : (a,b,c:A; s : set) (s_in a (add b (item c s)))=false->(s_in a (add b s))=false.\n\n\n\nAxiom nin_add2 : (a,b,c:A; s : set) (s_in a (add b (item c s)))=false->(A_eq a c)=false.\n\n*)\n\n\n\n\n\nTheorem in_sem1 : forall a : A, s_in a empty = false. \nProof.\nauto.\nQed.\n\nTheorem in_sem2 : forall (a : A) (s : set), s_in a (item a s) = true.\nProof.\nintros; simpl in |- *; rewrite theorder.eq_reflexive; reflexivity.\nQed.\n\n\nAxiom\n  in_sem3 :\n    forall (a : A) (s : set),\n    wf s = true ->\n    s_in a s = true ->\n    exists s1 : set, (exists s2 : set, s = cat s1 (item a s2)).\n\nAxiom\n  in_sem4 :\n    forall (a : A) (s1 s2 : set),\n    wf (cat s1 s2) = true ->\n    s_in a (cat s1 s2) = true -> s_in a s1 = true \\/ s_in a s2 = true.\n\n\nAxiom in_sem5 : forall (a b : A) (s : set), \ns_in a s = true -> s_in a (item b s) = true.\n\nAxiom in_sem6 : forall (a b : A) (s : set), \ns_in a (item b s) = true -> ~a=b -> s_in a s = true.\n\nAxiom\n  in_Lunion :\n    forall (a : A) (s1 s2 : set),\n     s_in a (union s1 s2) = true -> s_in a s2 = false ->\n     s_in a s1 = true.\n\nAxiom\n  in_unionL :\n    forall (a : A) (s s2 : set),\n    s_in a s = true -> s_in a (union s s2) = true.\n\nAxiom\n  in_unionR :\n    forall (a : A) (s s2 : set),\n    s_in a s = true -> s_in a (union s2 s) = true.\n\n\n\n\n\nAxiom in_union: forall (a b : set)(y : A),\n(s_in y (union a b)=true)\n->((s_in y a=true) \\/ (s_in y b=true)).\n\nAxiom in_inter1: forall (a b :set) (y : A),\n (s_in y (inter a b)=true)->\n((s_in y a=true) /\\ (s_in y b=true)).\n\nAxiom in_inter2: forall (a b : set) (y : A),\n((s_in y a=true) /\\ (s_in y b=true)) ->\n(s_in y (inter a b)=true).\n\n\n\n\n\n(* Why dealing with wf here ?\nAxiom in_embedded: \n  (a,b:A;s:set) \n  (wf (item b s))=true -> \n  (s_in a s)=true -> \n  (s_in a (item b s))=true\n  .\n*)\n\n\nAxiom\n  in_embedded :\n    forall (a b : A) (s : set), s_in a s = true -> s_in a (item b s) = true.\n\n\n\n\nTheorem in_succ :\n forall (a b : A) (s : set),\n A_eq a b = false -> s_in a (item b s) = true -> s_in a s = true.\nProof.\nintros a b s.\nsimpl in |- *.\ncase A_eq.\nintro.\ndiscriminate.\nintros.\nassumption.\nQed.\n\n\n\n\nTheorem nin_succ :\n forall (a b : A) (s : set), s_in a (item b s) = false -> s_in a s = false.\nProof.\nsimple induction s.\nsimpl in |- *.\nintros.\nreflexivity.\n\nintros.\ncut ({A_eq a a0 = true} + {A_eq a a0 = false}).\nintros.\nelim H1.\nintro.\nsimpl in |- *.\nrewrite a1.\nsimpl in H0.\nrewrite a1 in H0.\nassert ({A_eq a b = true} + {A_eq a b = false}).\napply theorder.eq_dec.\n\nelim H2.\nintro.\nrewrite a2 in H0.\ndiscriminate.\n\nintro.\nrewrite b0 in H0.\ndiscriminate.\n\nintro.\nsimpl in |- *.\nrewrite b0.\napply H.\nsimpl in H0.\nrewrite b0 in H0.\ncut ({A_eq a b = true} + {A_eq a b = false}).\nintros.\nelim H2.\nintro.\nrewrite a1 in H0.\ndiscriminate.\n\nintro.\nrewrite b1 in H0.\nsimpl in |- *.\nrewrite b1.\nassumption.\n\napply theorder.eq_dec.\n\napply theorder.eq_dec.\nQed.\n\n\n\nTheorem in_dec :\n forall (s : set) (a : A), {s_in a s = true} + {s_in a s = false}.\n(* Obsolete : *)\n(*\nProof.\nInduction s.\nSimpl;Auto.\n\nIntros a0 s0 H a1.\nSimpl.\nAssert H1:=(theorder.le_dec a0 a1).\nAssert H2:=(theorder.le_dec a1 a0).\nElim H1; Elim H2.\n\nIntros H3 H4; Rewrite -> H3; Rewrite -> H4; Auto.\nIntros H3 H4; Rewrite -> H3; Rewrite -> H4; Auto.\nIntros H3 H4; Rewrite -> H3; Rewrite -> H4; Auto.\nIntros H3 H4; Rewrite -> H3; Rewrite -> H4; Auto.\nQed.\n*)\n\n(* new proof for simplified version of s_in: *)\nProof.\nsimple induction s.\nsimpl in |- *; auto.\n\nintros.\nsimpl in |- *.\nassert (H1 := theorder.eq_dec a0 a).\nelim H1.\nintro.\ncase A_eq.\nleft.\nreflexivity.\n\napply (H a0).\n\nintro.\ncase A_eq.\nleft.\nreflexivity.\n\napply (H a0).\n\nQed.\n\n\n\n(* ----- card ------- *)\n\n\nTheorem card_is_pos : forall s : set, (0 <= card s)%Z.\nProof.\nsimple induction s.\ncompute in |- *; intro H; discriminate H.\nintros a l; simpl in |- *; apply Zle_le_succ.\nQed.\n\nTheorem card_empty : card empty = 0%Z. \nProof.\nauto.\nQed.\n\n\n\n\n\n\n\n\n\n(* ----- add ------- *)\n\n\nAxiom add_sem1 : forall (a : A) (s : set), s_in a s = true -> add a s = s.\n(*\nTheorem add_sem1:\n\t(a:A;s:set)\n\t(s_in a s)=true -> (add a s)=s .\nProof.\nInduction s.\nSimpl;Intro H; Discriminate H.\n\nIntros a1 s0 Hind;Simpl.\nCase (A_le a1 a);Case (A_le a a1).\nAuto.\n\nIntro H; Assert H1:=(Hind H); Rewrite -> H1; Reflexivity.\n\nIntro H; Discriminate H.\nAbort.\n*)\n\n\nTheorem add_sem2 : forall (a : A) (s : set), s_in a (add a s) = true.\nProof.\nintros.\ncase s.\nsimpl in |- *.\nassert (H := theorder.eq_reflexive a).\ncompute in |- *.\nrewrite H. \nreflexivity.\n\nintros.\napply in_add2.\nQed.\n\n\n\nAxiom add_wf : forall (a : A) (s : set), wf s = true -> wf (add a s) = true.\nAxiom\n  add_card1 :\n    forall (a : A) (s : set),\n    s_in a s = false -> card (add a s) = (card s + 1)%Z.\nAxiom add_card2 : forall (a : A) (s : set), (card (add a s) >= card s)%Z.\n\n\n\n\n(* ---- equality ---- *)\nAxiom\n  s_eq_sem : forall s1 s2 : set, s_eq s1 s2 = andb (incl s1 s2) (incl s2 s1).\nAxiom\n  s_eq_eq :\n    forall s1 s2 : set,\n    wf s1 = true -> wf s2 = true -> (s1 = s2 <-> s_eq s1 s2 = true).\nAxiom\n  s_neq_neq :\n    forall s1 s2 : set,\n    wf s1 = true -> wf s2 = true -> (s1 <> s2 <-> s_eq s1 s2 = false).\n\nSection decidableEq.\n  Axiom\n    s_eq_dec : forall s1 s2 : set, {s_eq s1 s2 = true} + {s_eq s1 s2 = false}.\n  Axiom s_eq_struct : forall s1 s2 : set, s_eq s1 s2 = true -> s1 = s2.\n  Axiom s_eq_reflexive : forall s : set, s_eq s s = true.\n  Axiom\n    s_eq_symmetric :\n      forall s1 s2 : set, s_eq s1 s2 = true -> s_eq s2 s1 = true.\n  Axiom\n    s_eq_transitive :\n      forall s1 s2 s3 : set,\n      s_eq s1 s2 = true -> s_eq s2 s3 = true -> s_eq s1 s3 = true.\nEnd decidableEq.\n\n\n\n\n\n\n(* ----- sub ------- *)\nAxiom sub_sem1 : forall (a : A) (s : set), s_in a s = false -> sub a s = s.\nAxiom sub_sem2 : forall (a : A) (s : set), s_in a (sub a s) = false.\nAxiom sub_wf : forall (a : A) (s : set), wf s = true -> wf (sub a s) = true.\nAxiom\n  sub_card1 :\n    forall (a : A) (s : set),\n    s_in a s = true -> card (sub a s) = (card s - 1)%Z.\nAxiom sub_card2 : forall (a : A) (s : set), (card (sub a s) <= card s)%Z.\nAxiom sub_add_sem : forall (a : A) (s : set), sub a (add a s) = s.\n\n\n(* ----- inter ------- *)\nAxiom\n  inter_semL :\n    forall (a : A) (s1 s2 : set),\n    s_in a s1 = true -> s_in a s2 = true -> s_in a (inter s1 s2) = true.\nAxiom inter_empty : forall s : set, inter s empty = empty.\nAxiom inter_incl : forall s1 s2 : set, incl s1 s2 = true -> inter s1 s2 = s1.\nAxiom inter_idem : forall s : set, inter s s = s.\nAxiom inter_sym : forall s1 s2 : set, inter s1 s2 = inter s2 s1.\nAxiom\n  inter_assoc :\n    forall s1 s2 s3 : set, inter s1 (inter s2 s3) = inter (inter s1 s2) s3.\n\nAxiom\n  wf_inter :\n    forall s1 s2 : set,\n    wf s1 = true -> wf s2 = true -> wf (inter s1 s2) = true.\nAxiom card_interL : forall s1 s2 : set, (card (inter s1 s2) <= card s1)%Z.\nAxiom card_interR : forall s1 s2 : set, (card (inter s1 s2) <= card s2)%Z.\n\n(* ----- diff ------- *)\nAxiom\n  inter_sem :\n    forall (a : A) (s1 s2 : set),\n    s_in a s2 = true -> s_in a (diff s1 s2) = false.\nAxiom diff_empty : forall s : set, diff s empty = s.\nAxiom diff_diff : forall s : set, diff s s = empty.\nAxiom diff_inter : forall s1 s2 : set, diff s1 s2 = diff s1 (inter s1 s2).\nAxiom\n  diff_inter_empty :\n    forall s1 s2 : set, inter s1 s2 = empty -> diff s1 s2 = s1.\nAxiom\n  wf_diff :\n    forall s1 s2 : set,\n    wf s1 = true -> wf s2 = true -> wf (diff s1 s2) = true.\nAxiom card_diff : forall s1 s2 : set, (card (diff s1 s2) <= card s1)%Z.\nAxiom\n  incl_inter_union :\n    forall s1 s2 : set, incl (inter s1 s2) (union s1 s2) = true.\n\n\n\n(* ----- union ------- *)\nAxiom\n  union_semL :\n    forall (a : A) (s1 s2 : set),\n    s_in a s1 = true -> s_in a (union s1 s2) = true.\nAxiom\n  union_semR :\n    forall (a : A) (s1 s2 : set),\n    s_in a s2 = true -> s_in a (union s1 s2) = true.\n\nAxiom union_incl : forall s1 s2 : set, incl s1 s2 = true -> union s1 s2 = s2.\nAxiom union_empty : forall s : set, union s empty = s.\nAxiom union_empty2 : forall s : set, union empty s = s.\nAxiom union_idem : forall s : set, union s s = s.\n\n\nAxiom\n  union_item :\n    forall (a : A) (s1 s2 : set),\n    union (item a s1) s2 = union (item a empty) (union s1 s2). \n\n\n\nAxiom union_sym : forall s1 s2 : set, union s1 s2 = union s2 s1.\n\n\n\nAxiom\n  union_assoc :\n    forall s1 s2 s3 : set, union s1 (union s2 s3) = union (union s1 s2) s3.\n\n\n\n\n\nAxiom\n  wf_union :\n    forall s1 s2 : set,\n    wf s1 = true -> wf s2 = true -> wf (union s1 s2) = true.\nAxiom\n  card_union :\n    forall s1 s2 : set, (card (union s1 s2) <= card s1 + card s2)%Z.\n\n\n\n(* ---- inclusion ---- *)\n\nTheorem incl_succ :\n forall (a1 : A) (s1 s2 : set),\n incl (item a1 s1) s2 = true -> incl s1 s2 = true.\nProof.\nintros.\nassert ({s_in a1 s2 = true} + {s_in a1 s2 = false}).\napply in_dec.\n\nelim H0.\nintro.\nunfold incl in H.\nrewrite a in H.\napply H.\n\nintro.\nunfold incl in H.\nrewrite b in H.\ndiscriminate.\nQed.\n\n\n\n\nAxiom\n  in_incl :\n    forall s1 s2 : set,\n    (forall a : A, s_in a s1 = true -> s_in a s2 = true) <->\n    incl s1 s2 = true.\n\nAxiom incl_empty : forall s : set, incl empty s = true.\nAxiom incl_empty_not : forall s : set, s <> empty -> incl s empty = false.\n\n\nAxiom incl_reflexive : forall s : set, incl s s = true.\n\n\n\nSection reflexiveSets.\n\nTheorem incl_dec :\n forall s1 s2 : set, {incl s1 s2 = true} + {incl s1 s2 = false}.\nProof.\nsimple induction s1.\nintro.\nsimpl in |- *.\nleft.\nreflexivity.\n\nintros.\ncut ({incl s s2 = true} + {incl s s2 = false}).\ncut ({s_in a s2 = true} + {s_in a s2 = false}).\nintros.\nelim H0.\nelim H1.\nintros.\nleft.\nunfold incl in |- *.\nrewrite a1.\nexact a0.\n\nintros.\nright.\nunfold incl in |- *.\nrewrite a0.\nassumption.\n\nintros.\nright.\nunfold incl in |- *.\nrewrite b.\nreflexivity.\n\napply in_dec.\n\napply (H s2).\nQed.\n\n(*Axiom incl_reflexive:(x:set)(incl x x)=true.*)\n\n\n(* wrong *)\n(*Axiom incl_asymmetric:(x,y:set)(incl x y)=false -> (incl y x)=true.*)\n\n\n\n\nTheorem incl_antisymmetric :\n forall x y : set, incl x y = true -> incl y x = true -> x = y.\nProof.\nintros.\napply s_eq_struct.\nassert (H1 := s_eq_sem x y).\nrewrite H1.\nrewrite H.\nrewrite H0.\ncompute in |- *.\nreflexivity.\nQed.\n\n\n\nAxiom\n  incl_transitive :\n    forall (b : bool) (x y z : set),\n    incl x y = b -> incl y z = b -> incl x z = b.\nEnd reflexiveSets.\n\n\n\nTheorem incl_add :\n forall (a : A) (s1 s2 : set), incl s1 s2 = true -> incl s1 (add a s2) = true.\nProof.\nsimple induction s1.\nsimpl in |- *.\ntrivial.\n\nintros.\nunfold incl in |- *.\ncut ({s_in a0 (add a s2) = true} + {s_in a0 (add a s2) = false}).\nintros.\nelim H1.\nintro.\nrewrite a1.\napply H.\ngeneralize H0.\napply incl_succ.\n\nintro.\nrewrite b.\ncut ({A_eq a a0 = true} + {A_eq a a0 = false}).\nintro.\nelim H2.\nintro.\nassert (a = a0).\napply theorder.eq_eq.\nassumption.\n\nrewrite H3 in b.\nassert (HC := in_add2 a0 s2).\nrewrite HC in b.\ndiscriminate.\n\nintro.\nsimpl in H0.\nassert (s_in a0 s2 = false).\ngeneralize b.\napply nin_add.\n\nrewrite H3 in H0.\ndiscriminate.\n\napply theorder.eq_dec.\n\napply in_dec.\nQed.\n\n\n\nTheorem incl_unionR : forall s1 s2 : set, incl s2 (union s1 s2) = true.\nProof.\nsimple induction s2.\nsimpl in |- *.\nreflexivity.\n\nintros.\nsimpl in |- *.\ncut (s_in a (add a (union s1 s)) = true).\nintro.\nrewrite H0.\napply incl_add.\nassumption.\n\napply in_add2.\nQed.\n\nTheorem incl_unionL : forall s1 s2 : set, incl s1 (union s1 s2) = true.\nProof.\nintros.\nassert (union s1 s2 = union s2 s1).\napply union_sym.\n\nrewrite H.\napply incl_unionR.\nQed.\n\n\n\n\n\n\n\n\n\n\n\nTheorem incl_incl_unionR :\n forall s s1 s2 : set, incl s s2 = true -> incl s (union s1 s2) = true.\nProof.\nsimple induction s.\nsimpl in |- *.\nintros; assumption.\n\nintros.\nassert ({s_in a s2 = true} + {s_in a s2 = false}).\napply in_dec.\n\nassert ({incl s0 s2 = true} + {incl s0 s2 = false}).\napply incl_dec.\n\nelim H1.\nintro.\nelim H2.\nintro.\nunfold incl in |- *.\nassert (s_in a (union s1 s2) = true).\napply in_unionR.\nexact a0.\n\nrewrite H3.\napply H.\nexact a1.\n\nintro.\nassert (incl s0 s2 = true).\ngeneralize H0.\napply incl_succ.\n\nrewrite b in H3.\ndiscriminate.\n\nintro.\nunfold incl in H0.\nrewrite b in H0.\ndiscriminate.\nQed.\n\n\n\n\nTheorem incl_incl_unionL :\n forall s s1 s2 : set, incl s s2 = true -> incl s (union s2 s1) = true.\nProof.\nintros.\nrewrite union_sym.\napply incl_incl_unionR.\napply H.\nQed.\n\n\n\n\nAxiom\n  incl_add_union :\n    forall (s1 s2 : set) (a : A),\n    incl s1 s2 = true -> incl (add a s1) (add a s2) = true.\n\n(*\nProof\nInduction s1.\nIntros.\nSimpl.\nAssert (s_in a (add a s2))=true.\nApply in_add2.\n\nRewrite -> H0.\nReflexivity.\n\nIntros.\nSimpl.\nCut {(A_le a a0)=true}+{(A_le a a0)=false}.\nCut {(A_le a0 a)=true}+{(A_le a0 a)=false}.\nIntros.\nElim H1.\nElim H2.\nIntros.\nRewrite -> a1.\nRewrite -> a2.\nAssert a=a0.\nApply theorder.le_antisymmetric.\nAssumption.\n\nAssumption.\n\nRewrite <- H3.\nApply incl_add.\nApply H0.\n\nIntros.\nRewrite -> b.\nSimpl.\nAssert (s_in a0 (add a0 s2))=true.\nApply in_add2.\n\nRewrite -> H3.\nAbort.\n\n*)\n\n\n\nTheorem incl_union_unionR :\n forall s s1 s2 : set,\n incl s1 s2 = true -> incl (union s1 s) (union s2 s) = true.\nProof.\nsimple induction s.\nintros.\nsimpl in |- *.\nexact H.\n\nintros.\nsimpl in |- *.\napply incl_add_union.\napply H.\nexact H0.\nQed.\n\n\nTheorem incl_union_union :\n forall s s1 s2 : set,\n incl s1 s2 = true -> incl (union s s1) (union s s2) = true.\nProof.\nintros.\nassert (union s s1 = union s1 s).\napply union_sym.\n\nassert (union s s2 = union s2 s).\napply union_sym.\n\nrewrite H0; rewrite H1.\napply incl_union_unionR.\napply H.\nQed.\n\n\n\n(* ----- wf ------- *)\n\n\n\n\nAxiom\n  wf_cat :\n    forall s1 s2 : set,\n    wf s1 = true ->\n    wf s2 = true ->\n    forall (s11 s22 : set) (a b : A),\n    s1 = cat s11 (item a empty) ->\n    s2 = item b s22 -> A_lt a b = true -> wf (cat s1 s2) = true.\n\n\n\nAxiom wf_emb : forall (a : A) (s : set), wf (item a s) = true -> wf s = true.\n(*Lemma wf_emb:(a:A;s:set) (wf (item a s))=true -> (wf s)=true.\nProof.\nIntros a s H.\nElim H.\n\nIntro H1; Intro H2; Elim H2.\nIntro H3; Intro H4.\nUnfold wf.\nExact H3.\nQed.\n*)\n\nAxiom\n  wf_in_lt :\n    forall (a : A) (s : set),\n    wf (item a s) = true -> forall b : A, s_in b s = true -> A_lt a b = true.\n(*\nProof.\nInduction s;[\n  Intros wf b H;Contradiction\n| \n  Intros a0 s0 Hind H b H1;\n  Assert HH:=(wf_emb a (item a0 s0) H);\n  Cut (A_eq b a0)=true \\/ (A_lt a0 b)=true;[\n    Intro H2;Elim H2;[\n\tIntro H3\n    |\n\n    ]\n  |\n    ...\n  ]\n].\nQed.\n*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(* ---- product ---- *)\n\nAxiom product_empty : forall f : A -> set, product empty f = empty.\n\nAxiom product_empty2 : forall s : set, product s (fun a : A => empty) = empty.\n\nAxiom\n  product_single : forall (f : A -> set) (a : A), product (single a) f = f a.\n\n\n(* -- on les a tous-- *)\n\nTheorem product_sem :\n forall (f : A -> set) (a : A) (s : set),\n s_in a s = true -> incl (f a) (product s f) = true.\nProof.\nsimple induction s.\nsimpl in |- *.\nintro.\ndiscriminate.\n\nintros.\nsimpl in |- *.\ncut ({A_eq a a0 = true} + {A_eq a a0 = false}).\nintros.\nelim H1.\nintro H'.\nassert (H2 : a = a0).\napply theorder.eq_eq.\nassumption.\n\nrewrite H2.\napply incl_unionL.\n\nintros.\napply incl_incl_unionR.\napply H.\ngeneralize H0.\napply in_succ.\nexact b.\n\napply theorder.eq_dec.\nQed.\n\n\n(* -- manque la réciproque -- *)\n\n\nAxiom product_sem2 :\n forall (f : A -> set) (a : A) (s : set),\n (product (item a s) f) = union (f a) (product s f).\n\n\n\n\n\nTheorem incl_pa_up :\n forall (f : A -> set) (a : A) (s : set),\n incl (product (add a s) f) (union (f a) (product s f)) = true.\nProof.\nsimple induction s.\nsimpl in |- *.\napply incl_reflexive.\n\nintros.\nsimpl in |- *.\ncut ({A_le a0 a = true} + {A_le a0 a = false}).\ncut ({A_le a a0 = true} + {A_le a a0 = false}).\nintros.\nelim H0.\nelim H1.\nintros.\nrewrite a1.\nrewrite a2.\nsimpl in |- *.\nassert (HE := union_sym (f a) (union (f a0) (product s0 f))).\nrewrite HE.\nassert (HA := union_assoc).\nrewrite <- HA.\napply incl_union_union.\napply incl_unionL.\n\nintros.\nrewrite b.\nsimpl in |- *.\napply incl_union_union.\napply incl_reflexive.\n\nelim H1.\nintros.\nrewrite a1.\nrewrite b.\nsimpl in |- *.\nassert (HE := union_sym (f a) (union (f a0) (product s0 f))).\nrewrite HE.\nassert (HA := union_assoc).\nrewrite <- HA.\napply incl_union_union.\nrewrite union_sym.\napply H.\n\nintros.\nrewrite b.\nsimpl in |- *.\napply incl_union_union; apply incl_reflexive.\n\napply theorder.le_dec.\n\napply theorder.le_dec.\n\nQed.\n\n\n\n\nTheorem incl_up_pa :\n forall (f : A -> set) (a : A) (s : set),\n incl (union (f a) (product s f)) (product (add a s) f) = true.\nProof.\nsimple induction s.\nsimpl in |- *.\napply incl_reflexive.\n\nintros.\nsimpl in |- *.\ncut ({A_le a0 a = true} + {A_le a0 a = false}).\ncut ({A_le a a0 = true} + {A_le a a0 = false}).\nintros.\nelim H0.\nelim H1.\nintros.\nrewrite a1.\nrewrite a2.\nsimpl in |- *.\nassert (a = a0).\napply theorder.le_antisymmetric.\nunfold A_le in a2.\nunfold A_le in a1.\nassumption.\n\nassumption.\n\nrewrite H2.\nrewrite union_assoc.\nrewrite union_idem.\napply incl_reflexive.\n\nintros.\nrewrite a1.\nrewrite b.\nsimpl in |- *.\napply incl_union_union.\napply incl_reflexive.\n\nelim H1; intros.\nrewrite a1; rewrite b; simpl in |- *.\nrewrite union_sym.\nrewrite <- union_assoc.\napply incl_union_union.\nrewrite union_sym.\napply H.\n\nrewrite b.\nsimpl in |- *.\napply incl_union_union.\napply incl_reflexive.\n\napply theorder.le_dec.\n\napply theorder.le_dec.\nQed.\n\n\n\n\n\nTheorem product_add :\n forall (f : A -> set) (a : A) (s : set),\n product (add a s) f = union (f a) (product s f).\nProof.\nintros.\napply incl_antisymmetric.\napply incl_pa_up.\n\napply incl_up_pa.\nQed.\n\n\n\n\nTheorem incl_pu_up :\n forall (f : A -> set) (s1 s2 : set),\n incl (product (union s1 s2) f) (union (product s1 f) (product s2 f)) = true.\nProof.\nsimple induction s2.\nsimpl in |- *.\napply incl_reflexive.\n\nintros a0 s Hrec.\nsimpl in |- *.\nassert (H := product_add f a0 (union s1 s)).\nrewrite H.\nclear H.\nassert (H := union_sym (product s1 f) (union (f a0) (product s f))).\nrewrite H.\nclear H.\nassert (H := union_assoc (f a0) (product s f) (product s1 f)).\nrewrite <- H.\napply incl_union_union.\nclear H.\nassert (H := union_sym (product s f) (product s1 f)).\nrewrite H; clear H.\napply Hrec.\nQed.\n\n\n\n\nTheorem incl_up_pu :\n forall (f : A -> set) (s1 s2 : set),\n incl (union (product s1 f) (product s2 f)) (product (union s1 s2) f) = true.\nProof.\nsimple induction s2.\nsimpl in |- *.\napply incl_reflexive.\n\nintros.\nsimpl in |- *.\nrewrite union_sym.\nrewrite <- union_assoc.\nrewrite product_add.\napply incl_union_union.\nrewrite union_sym.\napply H.\nQed.\n\n\n\n\n\n\nTheorem product_unionL :\n forall (f : A -> set) (s1 s2 : set),\n product (union s1 s2) f = union (product s1 f) (product s2 f).\nProof.\nintros.\napply incl_antisymmetric.\napply incl_pu_up.\napply incl_up_pu.\nQed.\n\n\n\n\n\n\nTheorem incl_puR_up :\n forall (f1 f2 : A -> set) (s : set),\n incl (product s (fun x : A => union (f1 x) (f2 x)))\n   (union (product s f1) (product s f2)) = true.\nProof.\nsimple induction s.\nsimpl in |- *.\nreflexivity.\n\nintros.\nsimpl in |- *.\nrewrite <- union_assoc.\nrewrite <- union_assoc.\napply incl_union_union.\nassert (H2 := union_sym (product s0 f1) (union (f2 a) (product s0 f2))).\nrewrite H2.\nrewrite <- union_assoc.\napply incl_union_union.\nclear H2.\nassert (H3 := union_sym (product s0 f2) (product s0 f1)).\nrewrite H3.\napply H.\nQed.\n\n\n\nTheorem incl_up_puR :\n forall (f1 f2 : A -> set) (s : set),\n incl (union (product s f1) (product s f2))\n   (product s (fun x : A => union (f1 x) (f2 x))) = true.\nProof.\nsimple induction s.\nsimpl in |- *.\nreflexivity.\n\nintros.\nsimpl in |- *.\nrewrite <- union_assoc.\nassert (H4 := union_sym (product s0 f1) (union (f2 a) (product s0 f2))).\nrewrite H4.\nrewrite union_assoc.\nrewrite union_assoc.\nrewrite <- union_assoc.\napply incl_union_union.\nclear H4.\nrewrite union_sym.\napply H.\nQed.\n\n\n\n\n\n\nTheorem product_unionR :\n forall (f1 f2 : A -> set) (s : set),\n product s (fun x : A => union (f1 x) (f2 x)) =\n union (product s f1) (product s f2).\nProof.\nintros.\napply incl_antisymmetric.\napply incl_puR_up.\napply incl_up_puR.\nQed.\n\n\n(*\n\n\nTheorem product_associativity: \n\t(s:set)(f:A->set)(a:A) \n\t((product (product s f) f))=true\n\nbad...\n\n\ntransitivity?\n\n\n*)\n\n\n\n\n\n\n\n\t\n\t\n\t\nAxiom\n  wf_product :\n    forall (f : A -> set) (s : set),\n    wf s = true -> (forall a : A, wf (f a) = true) -> wf (product s f) = true. \n\n\n\n\n(* ---- filter ---- *)\n\nAxiom\n  filter_sem1 :\n    forall (f : A -> bool) (s : set) (a : A),\n    s_in a s = true -> f a = true -> s_in a (filter s f) = true.  \n\nAxiom\n  filter_sem2 :\n    forall (f : A -> bool) (s : set) (a : A),\n    s_in a s = true -> f a = false -> s_in a (filter s f) = false.  \n\n\n(* used *)\nAxiom filter_sem3: \n    forall (f : A -> bool),\n    filter empty f = empty.\n       \n(* used *)\nAxiom filter_sem4:\n    forall (f : A -> bool) (s : set) (a : A),\n    filter (item a s) f = if (f a) then (item a (filter s f)) else (filter s f).\n\n\n\nAxiom filter_sem5:\n    forall (f : A -> bool) (s : set) (a : A),\n    (f a=true)->s_in a (filter (item a s) f) = true.\n    \nAxiom filter_sem6:\n    forall (f : A -> bool) (s : set) (a : A),\n    (f a=false)->s_in a (filter (item a s) f) = false.\n\n\n\n\n\n\nAxiom\n  wf_filter :\n    forall (f : A -> bool) (s : set), wf s = true -> wf (filter s f) = true. \n\n\n\n\n\n\n\n\n\n\n\n\n\nEnd geneSets.\n\n\nModule SetOrder (M: genSetsInt) : PartialReflexiveOrder.\n\nDefinition A := M.set.\nDefinition A_le := M.incl.\nDefinition dec := M.incl_dec.\nDefinition reflexive := M.incl_reflexive.\nDefinition antisymmetric := M.incl_antisymmetric.\nDefinition transitive := M.incl_transitive.\n\nEnd SetOrder.\n\nModule SetDecidableEq (M: genSetsInt) : DecidableEquality with Definition\n  A := M.set.\n\nDefinition A := M.set.\nDefinition A_eq := M.s_eq.\nDefinition dec := M.s_eq_dec.\nDefinition reflexive := M.s_eq_reflexive.\nDefinition symmetric := M.s_eq_symmetric.\nDefinition transitive := M.s_eq_transitive.\nDefinition eq_struct := M.s_eq_struct.\n\nEnd SetDecidableEq.\n", "meta": {"author": "mattam82", "repo": "typex", "sha": "37a01ce082e63a304fddadbc60ec281057fa6e1a", "save_path": "github-repos/coq/mattam82-typex", "path": "github-repos/coq/mattam82-typex/typex-37a01ce082e63a304fddadbc60ec281057fa6e1a/theories/XPath/DataStructures/genSets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.71537599108183}}
{"text": "Require Omega. \nRequire Export Bool List.\nExport ListNotations.\nRequire Export Arith Arith.EqNat.\nRequire Export Smallest Insort.\n\nFunction dist a b := max a b - min a b.\n\nInductive are_merged : list nat -> list nat -> list nat -> Prop :=\n  merged_nil_left: forall (l : list nat), are_merged [] l l\n| merged_nil_right : forall (l : list nat), are_merged l [] l\n| merged_le : forall m n l l' l'', \n    m <= n -> are_merged l (n::l') l'' -> are_merged (m::l) (n::l') (m::l'')\n| merged_gt : forall m n l l' l'', \n    n <= m -> are_merged (m::l) l' l'' -> are_merged (m::l) (n::l') (n::l'').\n\nRequire Import Permutation.\n\nLemma dist_S_l a b: dist a b <= 1 -> min a b = a -> dist (S a) b <= 1.\nProof.\nunfold dist. intros H1 H2. rewrite H2 in H1. \n  assert (a <= b) as H_3. rewrite <- H2; apply Min.le_min_r; auto.\n  assert (max a b = b) as H0. apply max_r; auto. rewrite H0 in H1.\n  inversion H1 as [H_1|c H_1 H_2];\n  destruct (Min.min_spec (S a) b) as [H3|H3]; destruct H3 as [H3 H4];\n  destruct (Max.max_spec (S a) b) as [H5|H5]; destruct H5 as [H5 H6]; try omega.\nQed.\n\nLemma dist_S_r a b: dist a b <= 1 -> min a b = b -> dist a (S b) <= 1.\nProof. \nunfold dist. intros H1 H2. rewrite H2 in H1. \n  assert (b <= a) as H_3. rewrite <- H2; apply Min.le_min_l; auto.\n  assert (max a b = a) as H0. apply max_l; auto. rewrite H0 in H1.\n  inversion H1 as [H_1|c H_1 H_2];\n  destruct (Min.min_spec a (S b)) as [H3|H3]; destruct H3 as [H3 H4];\n  destruct (Max.max_spec a (S b)) as [H5|H5]; destruct H5 as [H5 H6]; try omega.\nQed.\n\nLemma can_split : forall (l : list nat), \n  {l' | Permutation ((fst l') ++ (snd l')) l & dist (length (fst l')) (length (snd l')) <= 1}.\nProof.\ninduction l. exists ([], []); auto.\n  destruct IHl. destruct x as [pl pr]. simpl in p, l0.\n    unfold dist in l0.\n      destruct (Min.min_dec (length pl) (length pr)) as [H1 | H1].\n        exists (a :: pl, pr). simpl. apply perm_skip; auto.\n          simpl. apply dist_S_l; auto.              \n        exists (pl, a :: pr). simpl.\n          apply Permutation_sym; apply Permutation_cons_app; apply Permutation_sym; auto.\n          simpl. apply dist_S_r; auto.\nQed.\n\nLemma merged_permutation : forall (l l' l'': list nat), \n  are_merged l l' l'' -> Permutation (l ++ l') l''.\nProof.\nintros. induction H; simpl; try rewrite app_nil_r; auto.\n  apply Permutation_sym. apply (@Permutation_cons_app _ l'' (m :: l) l' n).\n    apply Permutation_sym; auto.\nQed.\n\nLemma merge : forall (a b : list nat),\n  is_sorted a -> is_sorted b -> {ab | is_sorted ab & are_merged a b ab}.\nProof.\ninduction a as [| ah al].\n  intros b _ H. exists b; auto. constructor.\n  induction b as [| bh bl].\n    intros H _. exists (ah::al); auto. constructor.\n    intros H1 H2. destruct (lt_eq_lt_dec ah bh) as [H3|H3].\n      assert (is_sorted al) as H4. apply (tail_is_sorted _ _ H1).\n      pose (IHal (bh::bl) H4 H2) as H5. destruct H5 as [l H5 H6].\n      exists (ah::l); auto. constructor; auto. apply in_list_smallest. left; auto.\n        intros x H; destruct H. omega.\n        apply merged_permutation in H6. apply Permutation_sym in H6.\n          apply (Permutation_in x H6) in H. apply in_app_or in H. destruct H.\n            apply (smallest_in (ah::al)). apply head_is_smallest; auto. right; auto.\n            apply (le_trans ah bh x). destruct H3; omega.\n              apply (smallest_in (bh::bl)). apply head_is_smallest; auto. auto.\n        apply merged_le; destruct H3; auto; omega. \n    assert (is_sorted bl) as H4. apply (tail_is_sorted _ _ H2).\n    pose (IHbl H1 H4) as H5. destruct H5 as [l H5 H6].\n      exists (bh::l); auto. constructor; auto. apply in_list_smallest. left; auto.\n        intros x H; destruct H. omega.\n        apply merged_permutation in H6. apply Permutation_sym in H6.\n          apply (Permutation_in x H6) in H. apply in_app_or in H. destruct H.\n            apply (le_trans bh ah x). destruct H3; omega.\n              apply (smallest_in (ah::al)). apply head_is_smallest; auto. auto.\n            apply (smallest_in (bh::bl)). apply head_is_smallest; auto. right; auto.\n        apply merged_gt. omega. auto.\nQed.\n\n\nTheorem genListInd_big_l {A} (P : list A -> Type) (l : list A) :\n  P [] ->\n  (forall l1 : list A,\n      (forall l2, length l2 <  length l1 -> P l2)  ->\n      (forall l2, length l2 <= length l1 -> P l2)\n  ) ->\n  (forall l1 : list A, length l1 <= length l -> P l1).\nProof.\nintros HBase; induction l.\n  intros _ l1; simpl.\n    destruct l1; auto. intros H; apply le_Sn_0 in H; inversion H.\n  intros H1. apply H1. intros l2 H2. simpl in H2.\n    apply gt_S_le in H2. apply IHl; auto.\nQed.\n\nTheorem genListInd_big {A} (P : list A -> Type) :\n  P [] ->\n  (forall l : list A,\n      (forall l1, length l1 <  length l -> P l1) ->\n      (forall l1, length l1 <= length l -> P l1)\n  ) ->\n  (forall l : list A, P l).\nProof. intros HBase HStep l; apply (genListInd_big_l P l); auto. Qed.\n\nTheorem genListInd {A} (P : list A -> Type) :\n  P [] -> (forall l1, (forall l2, length l2 < length l1 -> P l2) -> P l1) ->\n  (forall l, P l).\nProof.\nintros HBase HStep. apply genListInd_big; auto.\n  intros l H1 l1 H2. apply HStep. intros l2 H3. apply H1.\n    apply (lt_le_trans _ _ _ H3 H2).\nQed.\n\nTheorem merge_sort : forall (l : list nat), {l' | Permutation l l' & is_sorted l'}.\nProof.\napply genListInd. exists []; auto.\n  intros l HStep.\n    pose (can_split l). destruct s as [x H1 H2]. destruct x as [hl rl]. simpl in H1, H2.\n      destruct hl; destruct rl. exists []; auto; simpl in H1; rewrite <- H1; auto.\n        simpl in H1, H2. unfold dist in H2; simpl in H2.\n          apply le_S_gt in H2; destruct rl. exists [n]; auto; rewrite <- H1; auto.\n            simpl in H2; omega.\n        rewrite app_nil_r in H1. unfold dist in H2; simpl in H2.\n          apply le_S_gt in H2; destruct hl. exists [n]; auto; rewrite <- H1; auto.\n            simpl in H2; omega.\n        assert (length (n  :: hl) < length l) as H3.\n          rewrite <- (Permutation_length H1).\n            rewrite app_length. apply NPeano.Nat.lt_add_pos_r. simpl; omega.\n        assert (length (n0 :: rl) < length l) as H4.\n          rewrite <- (Permutation_length H1).\n            rewrite app_length. apply NPeano.Nat.lt_add_pos_l. simpl; omega.\n        apply HStep in H3; apply HStep in H4. destruct H3; destruct H4.\n          pose (merge x x0 i i0) as H3. destruct H3. exists x1; auto.\n            remember (Permutation_app p p0) as H3. clear HeqH3. apply Permutation_sym in H1.\n              apply (Permutation_trans H1) in H3. apply (Permutation_trans H3).\n                apply merged_permutation; auto.\nQed.\n\n\n(* Program Fixpoint Definition. *)\n\nProgram Fixpoint can_split_fix (l : list nat) :\n  {l' | Permutation ((fst l') ++ (snd l')) l /\\ dist (length (fst l')) (length (snd l')) <= 1} :=\n  match l with\n  | [] => ([], [])\n  | a :: l =>\n    let: (pl, pr) := can_split_fix l in\n    match (Min.min_dec (length pl) (length pr)) with\n    | left  _ => (a::pl, pr)\n    | right _ => (pl, a::pr)\n    end \n  end.\nNext Obligation. split. apply perm_skip; auto. apply dist_S_l; auto. Defined.\nNext Obligation.\nsplit. apply Permutation_sym; apply Permutation_cons_app; apply Permutation_sym; auto.\n  apply dist_S_r; auto.\nDefined.\n\nDefinition mm (lls : list nat * list nat) := let (l1, l2) := lls in length l1 + length l2.\n\nRequire Import Coq.Program.Wf Recdef.\n\nProgram Fixpoint merge_fix (ab : list nat * list nat) {measure (mm ab)} :\n    is_sorted (fst ab) -> is_sorted (snd ab) ->\n     {l | is_sorted l /\\ are_merged (fst ab) (snd ab) l} := fun aS bS =>\n  let: a := fst ab in (* In case you use 'let' instead 'let:' there will be not *)\n  let: b := snd ab in (* information in obligation proof.                       *)\n  match a with\n  | [] => b\n  | ah :: al =>\n    match b with\n    | [] => ah :: al\n    | bh :: bl =>\n      match lt_eq_lt_dec ah bh with\n      | inleft  _ => let: l := merge_fix (al, bh::bl) _ _ in\n                     ah :: l\n      | inright _ => let: l := merge_fix (ah::al, bl) _ _ in\n                     bh :: l  (* In case you use 'a' instread of 'ah::al'   *)\n      end                     (* There will be not enough information in    *)\n    end                       (* obligation proof. The same thing with 'b'. *)\n  end.\nNext Obligation. split; auto. simpl. apply merged_nil_left.              Qed.\nNext Obligation. split. rewrite Heq_a; auto.  apply merged_nil_right.    Qed.\nNext Obligation. simpl in *; rewrite <- Heq_a, <- Heq_b. simpl. omega.   Qed.\nNext Obligation. simpl in *. rewrite <- Heq_a in aS. inversion aS; auto. Qed.\nNext Obligation. simpl in *. rewrite <- Heq_b in bS; auto.               Qed.\nNext Obligation.\nsimpl in *.\n  remember (merge_fix (al, bh :: bl)\n            (merge_fix_obligation_3 (l0, l1) merge_fix aS bS l0 eq_refl l1\n               eq_refl ah al Heq_a bh bl Heq_b wildcard' Heq_anonymous1)\n            (merge_fix_obligation_4 (l0, l1) merge_fix aS bS l0 eq_refl l1\n               eq_refl ah al Heq_a bh bl Heq_b wildcard' Heq_anonymous1)\n            (merge_fix_obligation_5 (l0, l1) merge_fix aS bS l0 eq_refl l1\n               eq_refl ah al Heq_a bh bl Heq_b wildcard' Heq_anonymous1)).\n  clear Heqs. destruct s; simpl; destruct a; simpl in *.\n    split.\n      constructor; auto. apply in_list_smallest. left; auto.\n        intros y H1; destruct H1. omega.\n          apply merged_permutation in H0. apply Permutation_sym in H0.\n            apply (Permutation_in y H0) in H1. apply in_app_or in H1. destruct H1.\n              apply (smallest_in (ah :: al)). apply head_is_smallest; auto.\n                rewrite Heq_a; auto. right; auto.\n              apply (le_trans ah bh y). destruct wildcard'; omega.\n                apply (smallest_in (bh :: bl)); auto. apply head_is_smallest; auto.\n                  rewrite Heq_b; auto.\n      constructor; auto. destruct wildcard'; omega.\nQed.\nNext Obligation. simpl in *. rewrite <- Heq_a, <- Heq_b. simpl. omega.   Qed.\nNext Obligation. simpl in *. rewrite Heq_a; auto.                        Qed.\nNext Obligation. simpl in *. rewrite <- Heq_b in bS. inversion bS; auto. Qed.\nNext Obligation.\nsimpl in *.\n  remember (merge_fix (ah :: al, bl)\n            (merge_fix_obligation_7 (l0, l1) merge_fix aS bS l0 eq_refl l1\n               eq_refl ah al Heq_a bh bl Heq_b wildcard' Heq_anonymous1)\n            (merge_fix_obligation_8 (l0, l1) merge_fix aS bS l0 eq_refl l1\n               eq_refl ah al Heq_a bh bl Heq_b wildcard' Heq_anonymous1)\n            (merge_fix_obligation_9 (l0, l1) merge_fix aS bS l0 eq_refl l1\n               eq_refl ah al Heq_a bh bl Heq_b wildcard' Heq_anonymous1)).\n  clear Heqs. destruct s; simpl; destruct a; simpl in *.\n    split.\n      constructor; auto. apply in_list_smallest. left; auto.\n        intros y H1; destruct H1. omega.\n          apply merged_permutation in H0. apply Permutation_sym in H0.\n            apply (Permutation_in y H0) in H1. apply in_app_or in H1. destruct H1.\n              apply (le_trans bh ah y). omega.\n                apply (smallest_in (ah :: al)); auto. apply head_is_smallest; auto.\n                  rewrite Heq_a; auto. \n              apply (smallest_in (bh :: bl)). apply head_is_smallest; auto.\n                rewrite Heq_b; auto. right; auto.\n     constructor; auto. omega.\nQed.\n\nProgram Fixpoint merge_sort_fix (l : list nat) {measure (length l)} :\n    {l' | Permutation l l' /\\ is_sorted l'} :=\n  let: (nl, nr):= can_split_fix l in\n  match nl, nr with\n  | [], _ => nr\n  | _, [] => nl\n  | hl::tl, hr::tr =>\n    let: sl := merge_sort_fix nl in\n    let: sr := merge_sort_fix nr in\n    merge_fix (sl, sr) _ _\n  end.\nNext Obligation.\nremember (can_split_fix l) as spl. clear Heqspl. destruct spl as [lr H1].\n  destruct H1 as [H1 H2]; simpl in *. rewrite <- Heq_anonymous in *; simpl in *.\n    apply Permutation_sym in H1; split; auto.\n      assert (length nr <= 1). unfold dist in H2; simpl in H2.\n        rewrite <- minus_n_O in H2; auto.\n        destruct nr; auto; destruct nr; auto. simpl in H. omega.\nQed.\nNext Obligation.  \nremember (can_split_fix l) as spl. clear Heqspl. destruct spl as [lr H1].\n  destruct H1 as [H1 H2]; simpl in *. rewrite <- Heq_anonymous in *; simpl in *.\n    rewrite app_nil_r in H1. apply Permutation_sym in H1; split; auto.\n      assert (length nl <= 1). unfold dist in H2. \n        rewrite (Min.min_0_r (length nl)) in H2. rewrite (Max.max_0_r (length nl)) in H2.\n        rewrite <- minus_n_O in H2; auto.\n      destruct nl; auto; destruct nl; auto. simpl in H0. omega.\nQed.\nNext Obligation. \nremember (can_split_fix l) as spl. clear Heqspl. destruct spl as [lr H1].\n  destruct H1 as [H1 H2]; simpl in *. rewrite <- Heq_anonymous in *; simpl in *.\n    apply Permutation_length in H1. rewrite <- H1. simpl.\n      rewrite app_length. simpl. omega.\nQed.\nNext Obligation.\nremember (can_split_fix l) as spl. clear Heqspl. destruct spl as [lr H1].\n  destruct H1 as [H1 H2]; simpl in *. rewrite <- Heq_anonymous in *; simpl in *.\n    apply Permutation_length in H1. rewrite <- H1. simpl.\n      rewrite app_length. simpl. omega.\nQed.\nNext Obligation.\nremember (merge_sort_fix (hl :: tl)\n           (merge_sort_fix_obligation_3 l merge_sort_fix \n              (hl :: tl) (hr :: tr) Heq_anonymous hl tl hr tr eq_refl eq_refl)) as spl.\n  clear Heqspl. destruct spl as [lr H1]. destruct H1 as [H1 H2]; auto.\nQed.\nNext Obligation.\nremember (merge_sort_fix (hr :: tr)\n           (merge_sort_fix_obligation_4 l merge_sort_fix \n              (hl :: tl) (hr :: tr) Heq_anonymous hl tl hr tr eq_refl eq_refl\n              (proj1_sig\n                 (merge_sort_fix (hl :: tl)\n                    (merge_sort_fix_obligation_3 l merge_sort_fix \n                       (hl :: tl) (hr :: tr) Heq_anonymous hl tl hr tr\n                       eq_refl eq_refl))) eq_refl)) as spl.\n  clear Heqspl. destruct spl as [lr H1]. destruct H1 as [H1 H2]; auto.\nQed.\nNext Obligation. admit. Qed.", "meta": {"author": "dboulytchev", "repo": "direct-curry-howard", "sha": "3e73befad8ccd701eabe3469468b4857f4ea6890", "save_path": "github-repos/coq/dboulytchev-direct-curry-howard", "path": "github-repos/coq/dboulytchev-direct-curry-howard/direct-curry-howard-3e73befad8ccd701eabe3469468b4857f4ea6890/MergeSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.715375989112289}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf3 : natural) : natural :=\n  plus z (plus Zero lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj146_coqofml_Kx7AII.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7153759868397906}}
{"text": "(** This file is self study of coinduction in Coq. \n    The contents are based on \n    http://www.cse.chalmers.se/research/group/logic/TypesSS05/Extra/bertot_sl2.pdf\n    https://www.labri.fr/perso/casteran/CoqArt/Tsinghua/C7.pdf\n  *)\n\n(*\n   This is solution for https://www.labri.fr/perso/casteran/CoqArt/Tsinghua/exercises_7.v\n *)\n\nRequire Import List.\nRequire Import ArithRing.\n\nSet Implicit Arguments.\n\n(** Let us consider the following co-inductive definition *)\n\n CoInductive LList (A: Type) : Type := (* lazy lists *)\n |  LNil : LList A\n |  LCons : A -> LList A -> LList A.\n\n\nCheck (LCons 1 (LCons 2 (LCons 3 (LNil nat)))).\n\n\n(* builds the infinite list n, 1+n, 2+n, 3+n, etc. *)\n\nCoFixpoint from (n : nat) : LList nat := LCons n (from (S n)).\n\nDefinition nat_stream := from 0.\n\n\n\n(* exercise 1 :\n\nBuild the infinite list  true_false_alter  which alternates the \n boolean values :  true,false,true,false, ... \n*)\n\nCoFixpoint alter (b : bool) : LList bool := LCons b (alter (negb b)).\n\n(* exercise 2 *)\n(* generate the infinite list n_times_n  :\n                   1,2,2,3,3,3,4,4,4,4, .... *)\n\nCoFixpoint n_times_n (n : nat) (m : nat) : LList nat :=\n  match m with\n  | 0 => LCons (S n) (n_times_n (S n) n)\n  | S m' => LCons n (n_times_n n m')\n  end.\n\n(* exercise 3 :\n : Let A be any type and f : A -> A.\n  define  \"iterates f a\" as the infinite list \n     a, f a , f (f a), f (f (f a), etc. \n\n  apply this functional for defining the sequence Exp2 of powers of 2 :\n  1,2,4,8,16, etc.\n*)\n\nCoFixpoint iterates (A : Type) (f : A -> A) (a : A) : LList A :=\n  LCons a (iterates f (f a)).\n\nDefinition isEmpty (A:Type) (l:LList A) : Prop :=\n  match l with\n  | LNil _ => True\n  | LCons a l' => False\n  end.\n\n(* exercise 4: prove the following lemma *)\n\nLemma nat_stream_not_Empty : ~ isEmpty nat_stream.\nProof.\n  unfold isEmpty. intro contra.\n  unfold nat_stream in contra.\n  simpl in contra. destruct contra.\n  Qed.\n\n\nDefinition LHead (A:Type) (l:LList A) : option A :=\n  match l with\n  | LNil _ => None \n  | LCons a l' => Some a\n  end.\n\nEval compute in (LHead (LCons 1 (LCons 2 (LCons 3 (LNil nat))))).\n\n(* Exercise 5 : \n  prove the following lemma *)\n\nLemma Head_of_from : forall n, LHead (from n) = Some n.\nProof.\n  intros. reflexivity. Qed.\n\nDefinition LTail (A:Type) (l:LList A) : LList A :=\n  match l with\n  | LNil _ => LNil A\n  | LCons a l' => l'\n  end.\n\n(* Exercise 6 :\n\n define a function Nth (A:Type)  (n:nat) (l:LList A) : option A\n   such that (Nth n l) returns \n     - (Some a) if a is the n-th element of l (0-based)\n     - None if l has less than n+1 elements\n\n\nIf your solution is good, you can make a simple test :\n\nEval compute in (LNth 5 Exp2).\nSome 32 : option nat\n\n*)\n\nFixpoint LNth (A : Type) (n : nat) (l : LList A) : option A :=\n  match l, n with\n  | LCons a l', S n' => LNth n' l'\n  | LCons a l', 0 => Some a\n  | LNil _, _ => None\n  end.\n\n(* Exercise 7 :\n\n   For this exercise (and perhaps another one) , you may use the \n   following tools  (but it's not mandatory) :\n   \n   Standard library's  theorem f_equal \n   tactic ring on natural numbers (from  the ArithRing module) : \n\n\nProove the following theorem :\n\n   \nLemma LNth_from : forall n p, LNth n (from p) = Some (n+p).\n*)\n\nLemma LNth_from : forall n p, LNth n (from p) = Some (n+p).\nProof.\n  intros. generalize dependent p. induction n.\n  - simpl. reflexivity.\n  - intros. simpl. rewrite -> IHn. \n    assert (n + S p = S (n + p)) by ring.\n    rewrite H. reflexivity.\n  Qed.\n\n\n(* exercise 8 : \n   define a function   list_inj (A:Type)(l : list A) : LList A\n \n  which maps any (finite) list to a lazy list having the same elements\n  in the same order\n *)\n\nFixpoint LList_inj (A : Type) (l : list A) : LList A :=\n  match l with\n  | nil => LNil A\n  | a :: l' => LCons a (LList_inj l')\n  end.\n\n(* exercise 9 :\n\n  in order to validate your function list_inj,\n   prove the lemma list_inj_ok (which uses the following nth function on \n   finite lists).\n *)\n\nFixpoint nth (A:Type)  (n:nat) (l:list A)  {struct l} : option A :=\nmatch n,l  with | _,nil => None\n                | 0,a::_ =>  Some a\n                | S p, _::l' => nth p l'\nend.\n           \n(*\nLemma list_inj_Ok : forall (A:Type)(l : list A)(n:nat),\n   nth n l  = LNth  n (list_inj l) .\n\n*)\n\nLemma list_inj_Ok : forall (A:Type)(l : list A)(n:nat),\n   nth n l  = LNth  n (LList_inj l) .\nProof.\n  intros. generalize dependent l. induction n.\n  - intros. simpl. destruct l.\n    + reflexivity.\n    + simpl. reflexivity.\n  - intros. simpl. destruct l.\n    + simpl. reflexivity.\n    + simpl. rewrite -> IHn. reflexivity.\n  Qed.\n\nFixpoint firsts (A : Type) (n : nat) (l : LList A) : list A :=\n  match l, n with\n  | LCons a l', S n' => a :: (firsts n' l')\n  | _, _ => nil\n  end.\n\n(* exercise 10 :\n  Define a \"reciprocal\"  to list_inj :\n   firsts (A:Type) n (l:LList A): list A\n   returns the list of n-ths first elements of l\n\n   if l is finite and too short, firsts returns the list of all elements of l\n\nHere is a little test :\n*)\nDefinition Exp2 : LList nat := iterates (fun n => 2 * n) 1.\n  \n\nEval compute in (firsts 6 Exp2).\n\nEval compute in (firsts 10 (n_times_n 1 1)).\n\n\n\n(* Exercise 11 (not so easy) :\n Prove that Exp2 truely contains the sequence of all powers of 2 *)\n\n\nInductive Finite(A:Type): LList A -> Prop :=\n Finite_LNil : Finite (LNil A)\n|Finite_Lcons : forall a l, Finite l -> Finite (LCons a l).\n\nCoInductive Infinite(A:Type): LList A -> Prop :=\n Infinite_LCons : forall a l, Infinite l -> Infinite (LCons a l).\n\nCoInductive LList_eq (A:Type): LList A -> LList A -> Prop :=\n| LList_eq_LNil : LList_eq (LNil A) (LNil A)\n| LList_eq_LCons : forall a l l', LList_eq l l' ->\n                                  LList_eq (LCons a l) (LCons a l').\n\nDefinition LList_decomp (A:Type) (l:LList A) : LList A :=\n  match l with\n  | LNil _ => LNil A\n  | LCons a l' => LCons a l'\n  end.\n\nEval simpl in (LList_decomp (n_times_n 1 1)).\n\n\nLemma LList_decompose : forall (A:Type) (l:LList A), l = LList_decomp l.\nProof.\n intros A l; case l; trivial.\nQed.\n\nLtac unwind_i := \n match goal with | |- ?t1= ?t2  =>\n          apply trans_equal with (1 := LList_decompose t1);auto\nend.\n\nLtac unwind term1 term2 := \n  let eg := fresh \"eg\" in\n  assert(eg : term1 = term2);\n     [unwind_i|idtac].\n\n\n\nLemma bool_alternate_Infinite : forall b, Infinite (alter b).\nProof.\n cofix H.\n intro b.\n unwind (alter b) (LCons b (alter (negb b))).\n rewrite eg.\n constructor.\n auto.\nGuarded.\nQed.\n\n\n(* exercise 12 : Prove the following lemmas\n\nLemma Exp2_Infinite : Infinite Exp2. \n\n\nLemma bool_alternate_eqn : forall b, bool_alternate b =\n                                     LCons b (bool_alternate (negb b)).\n*)\nLemma iterates_Infinite : forall (A : Type) (f : A -> A) (n : A),\n  Infinite (iterates f n).\nProof.\n  intro A. cofix H. intros.\n  unwind (iterates f n) (LCons n (iterates f (f n))).\n  rewrite eg. apply Infinite_LCons.\n  apply H. Qed.\n\nLemma bool_alternate_eqn : \n  forall b, alter b = LCons b (alter (negb b)).\nProof.\n  intro.\n  unwind (alter b) (LCons b (alter (negb b))).\n  apply eg. Qed.\n\nCoFixpoint LAppend (A:Type) (u v:LList A) : LList A :=\n  match u with\n  | LNil _ => v\n  | LCons a u' => LCons a (LAppend u' v)\n  end.\n\nLemma LAppend_LNil : forall (A:Type) (v:LList A), LAppend (LNil A) v = v.\nProof.\n intros A v.\n destruct v; unwind_i.\nQed.\n\n\nLemma LAppend_LCons :\n  forall (A:Type) (a:A) (u v:LList A),\n    LAppend (LCons a u) v = LCons a (LAppend u v).\nProof.\n intros A a u v.\n unwind_i.\nQed.\n \nHint Rewrite  LAppend_LNil LAppend_LCons : llists.\n\n\n\nLemma LAppend_Infinite_1 : forall (A:Type)(u v : LList A),\n                             Infinite u -> Infinite (LAppend u v).\nProof.\n intro A;cofix H1.\n destruct u.\n intros v H;inversion H.\n intros v H;rewrite LAppend_LCons.\nconstructor;auto.\n apply H1.\n inversion H;auto.\nQed.\n\n(* exercise 13 :\nProve the following lemma :\n\nLemma LAppend_Infinite_2 : forall (A:Type)(u v : LList A),\n                           Infinite v -> Infinite (LAppend u v).\n*)\n\nLemma LAppend_Infinite_2 : forall (A:Type)(u v : LList A),\n                           Infinite v -> Infinite (LAppend u v).\nProof.\n  intro A. cofix H.\n  intros. destruct v.\n  - inversion H0.\n  - destruct u.\n    + rewrite LAppend_LNil. apply H0.\n    + rewrite LAppend_LCons.\n      constructor. apply H. apply H0.\n  Qed.\n\n(* exercise 14 :\nProve the following lemma :\n\nLemma LAppend_Infinite_3 : forall (A:Type)(u v : LList A),\n                             Infinite (LAppend u v) -> \n                             Finite u ->  Infinite v.\n*)\n\nLemma LAppend_Infinite_3 : forall (A:Type)(u v : LList A),\n                             Infinite (LAppend u v) -> \n                             Finite u ->  Infinite v.\nProof.\n  intro A. cofix H. intros.\n  destruct v.\n  - induction H1.\n    + rewrite LAppend_LNil in H0. inversion H0.\n    + rewrite LAppend_LCons in H0.\n      inversion H0; subst. apply IHFinite in H3.\n      inversion H3.\n  - induction H1.\n    + rewrite LAppend_LNil in H0. apply H0.\n    + apply IHFinite.\n      rewrite LAppend_LCons in H0.\n      inversion H0; subst. apply H3.\n  Qed.\n\n(* exercise 15 :\nProve the following lemma :\nLemma LAppend_absorbent : forall (A:Type)( u v: LList A),\n                                       Infinite u -> \n                                       LList_eq u (LAppend u v).\n*)\n\nLemma LAppend_absorbent : forall (A:Type)( u v: LList A),\n                                       Infinite u -> \n                                       LList_eq u (LAppend u v).\nProof.\n  intro A. cofix H.\n  intros.\n  destruct u.\n  - inversion H0.\n  - rewrite LAppend_LCons. apply LList_eq_LCons.\n    apply H. inversion H0; subst. apply H2.\n  Qed.\n\n", "meta": {"author": "mekty2012", "repo": "Theories-of-Programming-Languages-Implementation", "sha": "fd633d121b628bbcf7bdd8078953f473fd8dc333", "save_path": "github-repos/coq/mekty2012-Theories-of-Programming-Languages-Implementation", "path": "github-repos/coq/mekty2012-Theories-of-Programming-Languages-Implementation/Theories-of-Programming-Languages-Implementation-fd633d121b628bbcf7bdd8078953f473fd8dc333/CoInduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.7153475923585538}}
{"text": "Require Import Coq.Logic.Classical_Prop.\nAbout classic.\n(*Axiom LEM : forall P:Prop, P \\/ ~ P.*)\n\nTheorem NDRid1 : forall (p q : Prop), q -> (p \\/ q).\nProof. \nintros.\nright. exact H. Show Proof.\nQed.\n\nTheorem NDRid2 : forall (p q : Prop), p -> (p \\/ q).\nProof. \nintros.\nleft. exact H.\nQed.\n\n\nTheorem Conversion: forall (p q: Prop),(p -> q) -> (~ p \\/ q).\nProof.\n  intros p q.\n  intros p_implies_q.\n  destruct (classic p) as [p_true | p_not_true].\n  - apply p_implies_q in p_true as q_true. apply NDRid1. exact q_true. Show Proof. (* prove ~p \\/ q using p *)\n  - apply NDRid2. exact p_not_true. Show Proof. (* prove ~p \\/ q using ~p *)\nQed.\n(*demostracion demorgan*)\nLemma morgan : forall P Q : Prop, ~(P \\/ Q) -> ~P /\\ ~Q.\nProof.\n  unfold not.\n  intros P Q PorQ_false.\n    split.\n    intros P_holds.\n    apply PorQ_false.\n    left.\n      exact P_holds.\n      intros Q_holds.\n      apply PorQ_false.\n    right.\n      exact Q_holds.\nQed.\n\n(*Double negation*)\nTheorem double_neg : forall (P : Prop),\n  P -> ~~P.\nProof.\n  unfold not.\n  intros.\n  destruct (H0 H).\nQed.\n\n(*distributes_law*)\nTheorem distributes_law: forall (P Q R : Prop),\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  split.\n  - intros [HP | [HQ HR]].\n    + split.\n      * left. apply HP.\n      * left. apply HP.\n    + split.\n      * right. apply HQ.\n      * right. apply HR.\n  - intros [[HP | HQ] [HP' | HR]].\n    + left. apply HP.\n    + left. apply HP.\n    + left. apply HP'.\n    + right.\n      split.\n      * apply HQ.\n      * apply HR.\nQed.", "meta": {"author": "JoanDaniel18", "repo": "Coq_Test-Projects", "sha": "56142f09f040332abe1d4462488a1a389fd412ab", "save_path": "github-repos/coq/JoanDaniel18-Coq_Test-Projects", "path": "github-repos/coq/JoanDaniel18-Coq_Test-Projects/Coq_Test-Projects-56142f09f040332abe1d4462488a1a389fd412ab/coqprojects/homework2-Daniel_Rivas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7153475890620353}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Reals.Rtrigo_def.\nRequire Reals.Rpower.\nRequire BuiltIn.\nRequire real.Real.\n\nImport Rtrigo_def.\nImport Rpower.\n\n(* Why3 comment *)\n(* exp is replaced with (Reals.Rtrigo_def.exp x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Exp_zero : ((Reals.Rtrigo_def.exp 0%R) = 1%R).\nexact exp_0.\nQed.\n\nRequire Import Exp_prop.\n\n(* Why3 goal *)\nLemma Exp_sum : forall (x:R) (y:R),\n  ((Reals.Rtrigo_def.exp (x + y)%R) = ((Reals.Rtrigo_def.exp x) * (Reals.Rtrigo_def.exp y))%R).\nexact exp_plus.\nQed.\n\n(* Why3 comment *)\n(* log is replaced with (Reals.Rpower.ln x) by the coq driver *)\n\n(* Why3 goal *)\nLemma Log_one : ((Reals.Rpower.ln 1%R) = 0%R).\nexact ln_1.\nQed.\n\n(* Why3 goal *)\nLemma Log_mul : forall (x:R) (y:R), ((0%R < x)%R /\\ (0%R < y)%R) ->\n  ((Reals.Rpower.ln (x * y)%R) = ((Reals.Rpower.ln x) + (Reals.Rpower.ln y))%R).\nintros x y (Hx,Hy).\nnow apply ln_mult.\nQed.\n\n(* Why3 goal *)\nLemma Log_exp : forall (x:R),\n  ((Reals.Rpower.ln (Reals.Rtrigo_def.exp x)) = x).\nexact ln_exp.\nQed.\n\n(* Why3 goal *)\nLemma Exp_log : forall (x:R), (0%R < x)%R ->\n  ((Reals.Rtrigo_def.exp (Reals.Rpower.ln x)) = x).\nexact exp_ln.\nQed.\n\n(* Why3 assumption *)\nDefinition log2 (x:R): R := ((Reals.Rpower.ln x) / (Reals.Rpower.ln 2%R))%R.\n\n(* Why3 assumption *)\nDefinition log10 (x:R): R :=\n  ((Reals.Rpower.ln x) / (Reals.Rpower.ln 10%R))%R.\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/real/ExpLog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.715347587092504}}
{"text": "(* Difference of squares. *)\n\nRequire Import Omega.\nRequire Import Arith.\n\n(* If you're still on 8.4 (laggard!), try this instead: *)\n(* Import NPeano.Nat. *)\nImport Nat.\n\n(* Some useful lemmas from the standard library... *)\nCheck mul_sub_distr_l: forall n m p, p * (n - m) = p * n - p * m.\nCheck mul_add_distr_r: forall n m p, (n + m) * p = n * p + m * p.\nCheck mult_assoc: forall n m p, n * (m * p) = n * m * p.\nCheck mult_comm: forall n m, n * m = m * n.\nCheck mul_1_r: forall n, n * 1 = n.\n\n(* None of these lemmas require induction. Just use the library lemmas above. *)\nLemma squared_squared:\n  forall x, x ^ 4 = (x * x) * (x * x).\nProof.\n\nQed.\n\n(* Expand the right hand side first. *)\nLemma difference_of_squares:\n  forall a b, a * a - b * b = (a + b) * (a - b).\nProof.\n\nQed.\n\n(* Use both lemmas you just proved. *)\nLemma difference_of_squares_nested:\n  forall a b, a ^ 4 - b ^ 4 = (a * a + b * b) * (a + b) * (a - b).\nProof.\n\nQed.\n", "meta": {"author": "mbrcknl", "repo": "coq-fight-2016", "sha": "8925a35a86ba1d1cdd4dc69c91ad683db212bfd8", "save_path": "github-repos/coq/mbrcknl-coq-fight-2016", "path": "github-repos/coq/mbrcknl-coq-fight-2016/coq-fight-2016-8925a35a86ba1d1cdd4dc69c91ad683db212bfd8/submissions/L06-difference-of-squares.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384593, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7153186689400892}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := plus y (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj83_coqofml_gkRCc3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.715318664643919}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus Zero (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj1910_coqofml_Qwomvu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7153186602333192}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling    [*]              *)\n(*             Jean-François Monin           [+]              *)\n(*                                                            *)\n(*            [*] Affiliation LORIA -- CNRS                   *)\n(*            [+] Affiliation VERIMAG - Univ. Grenoble-Alpes  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** Using the simulated IR definition of \n\n              𝔻 : Ω -> Prop and nm : forall e, 𝔻 e -> Ω\n\n    we show show partial correctness of nm:\n\n      a) if De : 𝔻 e then nm e De is normal\n\n      b) if De : 𝔻 e then nm e De is equivalent to e\n\n    both by dependent induction on De : 𝔻 e\n*)\n\nRequire Import Arith Omega Wellfounded.\n\nRequire Import nm_defs.\n\nSet Implicit Arguments.\n\n(* Now we show the partial correctness of nm, independently of its termination *)\n\n(** normal forms only have atoms as boolean condition ie. b in if b then _ else _ *)\n\nInductive normal : Ω -> Prop :=\n  | in_normal_0 : normal α\n  | in_normal_1 : forall y z, normal y -> normal z -> normal (ω α y z).\n\nNotation ℕ := normal.\n\n(** nm produces normal forms *)\n\nTheorem nm_normal e D : ℕ (nm e D).\nProof.\n  induction D as [ e D1 D2 | | y z D1 ID1 D2 ID2 | u v w y z D1 ID1 D2 ID2 D3 ID3 ].\n  - rewrite (nm_pirr _ D1); auto.\n  - rewrite nm_fix_0; constructor.\n  - rewrite nm_fix_1; constructor; auto.\n  - rewrite nm_fix_2; auto.\nQed.\n\n(** equiv is the congruence generated by ω (ω a b c) y z ~e ω a (ω b y z) (ω c y z) *)\n\nReserved Notation \"x '~Ω' y\" (at level 70, no associativity).\n\nInductive equiv : Ω -> Ω -> Prop :=\n  | in_eq_0 : forall u v w y z, ω (ω u v w) y z ~Ω ω u (ω v y z) (ω w y z)\n  | in_eq_1 : forall x x' y y' z z', x ~Ω x' -> y ~Ω y' -> z ~Ω z'-> ω x y z ~Ω ω x' y' z'\n  | in_eq_2 : α ~Ω α\n  | in_eq_3 : forall x y z, x ~Ω y -> y ~Ω z -> x ~Ω z\nwhere \"x ~Ω y\" := (equiv x y).\n\nHint Constructors equiv.\n\nFact equiv_refl e : e ~Ω e.\nProof. induction e; auto. Qed.\n\nHint Resolve equiv_refl.\n\nNotation equiv_trans := in_eq_3.\n\n(** nm preserves equivalence *)\n\nFact nm_equiv e D : e ~Ω nm e D.\nProof.\n  induction D as [ e D1 D2 | | y z D1 ID1 D2 ID2 | u v w y z D1 ID1 D2 ID2 D3 ID3 ].\n  - rewrite (nm_pirr _ D1); auto.\n  - rewrite nm_fix_0; auto.\n  - rewrite nm_fix_1; auto.\n  - rewrite nm_fix_2.\n    apply equiv_trans with (2 := ID3),\n          equiv_trans with (1 := in_eq_0 _ _ _ _ _); auto.\nQed.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "ite-normalisation", "sha": "bbfa30858b97b5a6216f68312a9e918c8256dc20", "save_path": "github-repos/coq/DmxLarchey-ite-normalisation", "path": "github-repos/coq/DmxLarchey-ite-normalisation/ite-normalisation-bbfa30858b97b5a6216f68312a9e918c8256dc20/nm_correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7153186581424489}}
{"text": "Require Import ZArith Znumtheory.\nRequire Import MyNat Ztools.\n\n(** * Results about [eqm], congruence modulo some integer *)\n\nNotation \" a ≡ b [ p ] \" := ( eqm p a b ) (at level 70).\n\nExisting Instances eqm_setoid Zplus_eqm Zminus_eqm Zmult_eqm.\n\nLemma mod0_eqm : forall x m, x ≡ 0 [m] <-> x mod m = 0.\nProof.\n  intros x m.\n  rewrite <- Zmod_0_l with m.\n  intuition.\nQed.\n\nLemma divide_eqm : forall x m, m <> 0 -> (x ≡ 0 [m] <-> (m | x)).\nProof.\n  intros x m Nm; split; rewrite mod0_eqm; intros H.\n    apply Zmod_divide; auto.\n    apply Zdivide_mod; auto.\nQed.\n\nLemma eq_eqm : forall m a b, a = b -> a ≡ b [m].\nProof.\n  intros; subst; reflexivity.\nQed.\n\nLemma eqm_diag : forall m, m ≡ 0 [m].\nProof.\n  intros; red; rewrite Z_mod_same_full; reflexivity.\nQed.\n\nLemma eqm_minus_0 : forall a b m, a ≡ b [m] <-> a - b ≡ 0 [m].\nProof.\n  intros a b m; split; intros E.\n    rewrite E; red; f_equal; ring.\n    rewrite <- (Zminus_0_r a), <- E; red; f_equal; ring.\nQed.\n\nLemma eqm_divide m a b : m <> 0 -> a ≡ b [ m ] <-> (m | a - b).\nProof.\n  intros mz.\n  rewrite eqm_minus_0.\n  rewrite <-Z.mod_divide; tauto.\nQed.\n\nLemma eqm_mult_compat_l : forall k a b m, a ≡ b [m] -> k * a ≡ k * b [k * m].\nProof.\n  intros k a b m E.\n  red.\n  repeat rewrite Zmult_mod_distr_l.\n  rewrite E.\n  auto.\nQed.\n\nLemma eqm_mult_compat_r : forall k a b m, a ≡ b [m] -> a * k ≡ b * k [k * m].\nProof.\n  intros k a b m.\n  repeat rewrite <- (Zmult_comm k).\n  apply eqm_mult_compat_l.\nQed.\n\n\n(** Modulo m if a≡m/2 then a²≡m²/4 *)\n\nLemma eqm_square_half : forall x m, 0 <> m ->\n  x ≡ m [2 * m] -> x * x ≡ m * m [4 * (m * m)].\nProof.\n  intros x m Nm D.\n  rewrite eqm_minus_0 in D.\n  rewrite divide_eqm in D; notzero.\n  destruct (Zdivide_inf _ _ D) as (k, Ek).\n  replace x with (x - m + m) by ring.\n  rewrite Ek.\n  apply eqm_minus_0.\n  ring_simplify.\n  apply divide_eqm; notzero.\n  exists (k + k ^ 2).\n  ring.\nQed.\n", "meta": {"author": "coq-community", "repo": "coqtail-math", "sha": "be26e1a6a52f2e13e0779c68aba685ddfb4f0535", "save_path": "github-repos/coq/coq-community-coqtail-math", "path": "github-repos/coq/coq-community-coqtail-math/coqtail-math-be26e1a6a52f2e13e0779c68aba685ddfb4f0535/Arith/Zeqm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7153186538462786}}
{"text": "(* begin hide *)\n\nUnset Implicit Arguments.\nSet Asymmetric Patterns.\nAxiom todo : forall {A}, A.\nLtac todo := apply todo.\n(* end hide *)\n\nClass Monoid {A:Type} (dot : A -> A -> A) (one : A) : Type := \n  { dot_assoc : forall x y z : A, dot x (dot y z) = dot (dot x y) z;\n    one_left : forall x, dot one x = x;\n    one_right : forall x, dot x one = x }.\n\nGeneralizable Variables A dot one.\n\n(** %\\end{frame}\\begin{frame}\\frametitle{Generic notations}%\n   Global names for parameters: *)\n\nDefinition monop `{Monoid A dot one} := dot.\nDefinition monunit `{Monoid A dot one} := one.\n\n(** Generic notations: *)\n\nInfix \"*\" := monop.\nNotation \"1\" := monunit.\n\nSection Reification.\n  Context `{Monoid A dot one}.\n\n  Inductive MonoidExpr A :=\n  | monoid_cst : A -> MonoidExpr A (* for any constant not recognized as the unit or operation *)\n  | monoid_unit : MonoidExpr A\n  | monoid_op : MonoidExpr A -> MonoidExpr A -> MonoidExpr A.\n\n  Fixpoint interp (e : MonoidExpr A) : A :=\n    match e with\n    | monoid_cst x => x\n    | monoid_unit => one\n    | monoid_op x y => dot (interp x) (interp y)\n    end.\n\n  Class ReifyExpr (a : A) :=\n    { reified_expr : MonoidExpr A;\n      reified_correct : interp reified_expr = a }.\n\n  Instance reify_var (a : A) : ReifyExpr a | 100 := {| reified_expr := monoid_cst _ a |}.\n  Proof. reflexivity. Defined.\n\n  Instance reify_op (a b : A) (ra : ReifyExpr a) (rb : ReifyExpr b) : ReifyExpr (dot a b) := \n    {| reified_expr := monoid_op _ (reified_expr (a:=a)) (reified_expr (a:=b)) |}.\n  Proof. simpl. rewrite !reified_correct. reflexivity. Defined.\n\n  Instance reify_unit : ReifyExpr one :=\n    {| reified_expr := monoid_unit _ |}.\n  Proof. simpl. reflexivity. Defined.\n\n  Fixpoint simplify_expr (x : MonoidExpr A) : MonoidExpr A :=\n    match x with\n    | monoid_op x y =>\n      match simplify_expr x, simplify_expr y with\n      | monoid_unit, y => y\n      | x, monoid_unit => x\n      | x, y => monoid_op _ x y\n      end\n    | x => x\n    end.\n\n  (* Show it is correct: it should only apply valid laws of the monoid *)\n  Lemma simplify_expr_correct (e : MonoidExpr A) : interp (simplify_expr e) = interp e.\n  Proof.\n    induction e; simpl; auto.\n    destruct (simplify_expr e1) eqn:eq1;\n    destruct (simplify_expr e2) eqn:eq2;\n    rewrite <- IHe1, <- IHe2;\n    simpl in *; auto. subst; auto. now rewrite one_right.\n    now rewrite one_left.\n    now rewrite one_left.\n    now rewrite (one_left (one:=one)).\n    now rewrite (one_right (one:=one)).\n  Qed.\n    \n  (* Using correctness, show that simplifying a reified expression for [a]\n     and interpreting it back gives a term equal to [a] *)\n  Lemma simplify_monoid (a : A) {e : ReifyExpr a} : a = interp (simplify_expr reified_expr).\n  Proof. \n    rewrite simplify_expr_correct.\n    now rewrite reified_correct.\n  Qed.\n\n  (** This proof script should go through once the above is finished. *)\n  Example simpl_goal (x : A) : monop x monunit = x.\n  Proof. pose proof (simplify_monoid (monop x monunit)) as Heq.\n    simpl in Heq. assumption. Qed.\n\nEnd Reification.v", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/PA/2021/reification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7152909650726711}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2020 - Pset 5 *)\n\n(* Author: Samuel Gruetter <gruetter@mit.edu> *)\n\nRequire Import Frap.Frap.\nRequire Import Pset5Sig.\n\n(* Delete this line if you don't like bullet points and errors like\n   \"Expected a single focused goal but 2 goals are focused.\" *)\n(* Set Default Goal Selector \"!\". *)\n\n(* In this pset, we will explore different ways of defining semantics for the\n   simple imperative language we used in Chapter 4 (Interpreters.v) and\n   Chapter 7 (OperationalSemantics.v).\n   Make sure to re-read these two files, because many definitions we ask you\n   to come up with in this pset are similar to definitions in these two files.\n\n   Pset5Sig.v contains the number of points you get for each definition and\n   proof. Note that since we ask you to come up with some definitions\n   yourself, all proofs being accepted by Coq does not necessarily guarantee a\n   full score: You also need to make sure that your definitions correspond to\n   what we ask for in the instructions. *)\n\n(* Our language has arithmetic expressions (note that we removed Times and Minus,\n   because they don't add anything interesting for this pset): *)\nInductive arith : Set :=\n| Const(n: nat)\n| Var(x: var)\n| Plus(e1 e2: arith).\n\n(* And it has commands, some of which contain arithmetic expressions: *)\nInductive cmd :=\n| Skip\n| Assign(x: var)(e: arith)\n| Sequence(c1 c2: cmd)\n| If(e: arith)(thn els: cmd)\n| While(e: arith)(body: cmd).\n\n(* As in the lecture, we use a finite map to store the values the variables: *)\nDefinition valuation := fmap var nat.\n\n(* To make it a bit more interesting, we add a twist:\n   If an arithmetic expression reads an undefined variable, instead of just\n   returning 0, we specify that an arbitrary value can be returned.\n   Therefore, the signature we used in class,\n\n     Fixpoint interp (e : arith) (v : valuation) : nat := ...\n\n   will not work any more, because that one can only return one value.\n   Instead, we will use the following definition: *)\nFixpoint interp(e: arith)(v: valuation)(a: nat): Prop :=\n  match e with\n  | Const n => a = n\n  | Var x =>\n    match v $? x with\n    | None => True (* any a is possible! *)\n    | Some n => a = n\n    end\n  | Plus e1 e2 => exists a1 a2, interp e1 v a1 /\\ interp e2 v a2 /\\ a = a1 + a2\n  end.\n(* You can read \"interp e v a\" as the claim \"interpreting expression e under\n   the valuation v can return the value a\".\n   And if we don't provide the last argument, we can think of \"interp e v\",\n   which has type \"nat -> Prop\", as \"the set of all possible values e could\n   return\". *)\n\n(* For example, if we interpret the expression \"y+z\" in a valuation where\n   y is defined to be 2, but z is undefined, we can get any value for z,\n   so the possible results are all values greater or equal to 2. *)\nGoal interp (Plus (Var \"y\") (Var \"z\")) ($0 $+ (\"y\", 2)) = (fun a => 2 <= a).\nProof.\n  simplify.\n  apply sets_equal.\n  split; simplify.\n  - invert H. invert H0. linear_arithmetic.\n  - exists 2, (x - 2). linear_arithmetic.\nQed.\n(* Hint which will be useful later:\n   In the above proof, you can see how you can deal with existentials:\n   - If you have an \"H: exists x, P\" above the line, you can \"invert H\"\n     do obtain such an \"x\" and an \"H0: P\".\n   - If you have an \"exists x, P\" below the line, you can use \"exists y\"\n     to provide the value for which you want to prove the existential. *)\n\n(* An alternative way of specifying how arithmetic expressions are evaluated\n   is by using inference rules, where we put preconditions above the line,\n   and the conclusion below the line, and a name of the rule to the right of\n   the line, and use \"Oxford brackets\" to write statements of the form\n   \"a ∈ [[e]]_v\" which we read as \"the natural number a is in the set of\n   values to which e can evaluate under the valuation v\".\n   If we were to write this on a blackboard, it might look like this:\n\n                      ------------ ValuesConst\n                      n ∈ [[n]]_v\n\n                       ( x ↦  a) ∈  v\n                      ------------ ValuesVarDefined\n                      a ∈ [[x]]_v\n\n                      x ∉  dom(v)\n                     ------------- ValuesVarUndefined\n                     a ∈ [[x]]_v\n\n          a1 ∈ [[e1]]_v   a2 ∈ [[e2]]_v   a= a1 + a2\n          ----------------------------------------- ValuesPlus\n                     a ∈ [[e1+e2]]_v\n\n   Let's translate this to an Inductive Prop in Coq called \"values\", that is,\n   \"values e v a\" should mean \"the natural number a is in the set of\n   values to which e can evaluate under the valuation v\".\n   Define an Inductive with four constructors, one for each of the four rules\n   above, using the names written to the right of the lines above as the\n   constructor names.\n*)\nInductive values: arith -> valuation -> nat -> Prop :=\n  | ValuesConst : forall v a, values (Const a) v a\n  | ValuesVarDefined : forall v x a, v $? x = Some a -> values (Var x) v a  \n  | ValuesVarUndefined : forall v x a,  v $? x = None -> values (Var x) v a\n  | ValuesPlus : forall a1 a2 e1 e2 v a, values e1 v a1 -> values e2 v a2 -> a = a1 + a2 -> values (Plus e1 e2) v (a).\n(* Note that the following alternative would also work for ValuesPlus:\n\n          a1 ∈ [[e1]]_v     a2 ∈ [[e2]]_v\n          --------------------------------- ValuesPlus\n                a1+a2 ∈ [[e1+e2]]_v\n\n   But in Coq, this would be a bit less convenient, because the tactic\n   \"eapply ValuesPlus\" would only work if the goal is of the shape\n   \"values _ _ (_ + _)\", whereas if we add this extra equality,\n   \"eapply ValuesPlus\" works no matter what the last argument to \"values\" is. *)\n\n(* Contrary to the Fixpoint-based definition \"interp\", we can't do simplification\n   of the kind \"replace interp by its body and substitute the arguments in it\",\n   because an Inductive Prop describes a family of proof trees, and isn't a\n   function with a right-hand side you could plug in somewhere else.\n   In order to prove the example Goal from above for \"values\", we need to construct\n   the following proof tree:\n\n  (\"y\"↦2) ∈ {\"y\"↦2}                         \"z\" ∉ dom({\"y\"↦2})\n -------------------- ValuesVarDefined      ------------------------ ValuesVarUndefined\n 2 ∈ [[\"y\"]]_{\"y\"↦2}                        a-2 ∈ [[\"z\"]]_{\"y\"↦2}                          a=2+a-2\n ---------------------------------------------------------------------------------------------------- ValuesPlus\n                                a ∈ [[\"y\"+\"z\"]]_{\"y\"↦2}\n*)\nExample values_example: forall a,\n    2 <= a ->\n    values (Plus (Var \"y\") (Var \"z\")) ($0 $+ (\"y\", 2)) a.\nProof.\n  (* \"simplify\" only introduces the hypotheses but can't really simplify\n     anything here. This is not a limitation of \"simplify\", but by design. *)\n  simplify.\n  (* Once you define the four constructors for \"values\", you can uncomment\n     the script below. Make sure you understand how it relates to the proof\n     tree above! *)\n  eapply ValuesPlus with (a1 := 2) (a2 := a - 2).\n  - eapply ValuesVarDefined. simplify. equality.\n  - eapply ValuesVarUndefined. simplify. equality.\n  - linear_arithmetic.\nQed.\n    \nLemma constructor_const_impl: forall n v a, interp (Const n) v a -> values (Const n) v a.\nProof.\nsimplify.\nrewrite H.\neconstructor.\nQed.\n\nLemma constructor_var_impl: forall x v a, interp (Var x) v a -> values (Var x) v a.\nProof.\n- simplify.\n  cases (v $? x).\n  + econstructor. equality. \n  + eapply ValuesVarUndefined. equality.\nQed.\n\n(* Now, let's prove that \"interp\" and \"values\" are equivalent: *)\nTheorem interp_to_values: forall e v a,\n    interp e v a -> values e v a.\nProof.\n  simplify.\n  induct e.\n  - apply constructor_const_impl. assumption.    \n  - apply constructor_var_impl.   assumption.\n  - invert H.\n    invert H0.\n    propositional.\n    apply IHe1 in H0.\n    apply IHe2 in H.\n    simplify.\n    apply ValuesPlus with (a1:=x) (a2:=x0); assumption.\nQed.\n\n(* To prove the other direction, we can induct on the proof tree of \"values\" *)\nTheorem values_to_interp: forall e v a,\n    values e v a -> interp e v a.\nProof.\n  induct 1; (* <-- do not change this line *)\n    simplify.\n    equality.\n    cases (v $? x).\n    assert (n = a) by equality. equality.\n    equality.\n    rewrite H.\n    equality.\n    exists a1, a2.\n    propositional.\nQed.\n\n(* Note that we could also induct on e, but this is a bit more work\n   (let's still do it as an exercise, though). *)\nTheorem values_to_interp_induction_on_e: forall e v a,\n    values e v a -> interp e v a.\nProof.\n  induct e; (* <-- BAD, but for the sake of the exercise, do not change this line *)\n    simplify.\n    invert H.\n    equality.\n    cases  (v $? x).\n    simplify.\n    \n    invert H.\n    equality.\n    equality.\n    equality.\n    invert H.\n    specialize (IHe1 v a1).\n    specialize (IHe2 v a2).\n    exists a1, a2.\n    propositional.\nQed.\n(* Let's define nondeterministic big-step semantics for evaluating a command.\n   Define \"eval\" as an Inductive Prop such that \"eval v1 c v2\" means\n   \"If we run command c on valuation v1, we can obtain valuation v2\".\n   Whenever you encounter an arithmetic expression, use \"values\" to obtain a\n   value it can step to.\n   Hint: This will be quite similar to \"eval\" in OperationalSemantics.v! *)\nInductive eval : valuation -> cmd -> valuation -> Prop :=\n  | EvalSkip : forall v,\n    eval v Skip v\n  | EvalAssign : forall v x e a,\n    interp e v a -> eval v (Assign x e) (v $+ (x, a))\n  | EvalSeq : forall v c1 v1 c2 v2,\n    eval v c1 v1\n    -> eval v1 c2 v2\n    -> eval v (Sequence c1 c2) v2\n  | EvalIfTrue : forall n v e thn els v',\n    interp e v n\n    -> n <> 0\n    -> eval v thn v'\n    -> eval v (If e thn els) v'\n  | EvalIfFalse : forall v e thn els v',\n    interp e v 0\n    -> eval v els v'\n    -> eval v (If e thn els) v'\n  | EvalWhileTrue : forall n v e body v' v'',\n    interp e v n\n    -> n <> 0\n    -> eval v body v'\n    -> eval v' (While e body) v''\n    -> eval v (While e body) v''\n  | EvalWhileFalse : forall v e body,\n    interp e v 0 \n    -> eval v (While e body) v.\n\n\n(* Before you continue your epic journey through this adventure game, I want\n   to give you another tool. It's much more powerful than any combination of\n   \"invert\", \"simplify\", \"exists\", \"eapply\", etc you could ever imagine, so\n   please make sure to keep the following tool at an easy to access place in\n   your toolbox. Here it is, in the form of a hint:\n\n   Hint: Many of the proofs below will depend on definitions we ask you to\n   find yourself, and if you get these definitions wrong, the proofs will\n   not work, so keep in mind that you might have to go back and adapt your\n   definitions!\n   Also, it can happen that many proofs go through and you become (overly)\n   confident that your definitions are correct, even though they aren't. *)\n\n(* Here's an example program. If we run it on the empty valuation, reading the\n   variable \"oops\" can return any value, but after that, no matter whether\n   \"oops\" was zero or not, we assign a non-zero value to \"tmp\", so the answer\n   will always be 42. *)\nExample the_answer_is_42 :=\n  Sequence (Assign \"x\" (Var \"oops\"))\n           (Sequence (If (Var \"x\")\n                         (Assign \"tmp\" (Plus (Var \"x\") (Var \"x\")))\n                         (Assign \"tmp\" (Const 1)))\n                     (If (Var \"tmp\")\n                         (Assign \"answer\" (Const 42))\n                         (Assign \"answer\" (Const 24)))).\n\n(* To prove that this sample program always returns 42, we first prove a handy\n   helper lemma: *)\nLemma read_last_value: forall x v c n,\n    values (Var x) (v $+ (x, c)) n -> n = c.\nProof.\n  simplify.\n  apply values_to_interp in H.\n  simplify.\n  equality.\nQed.\n\n(* Hint: This one is a bit boring -- it's about 30 lines of \"invert\", \"simplify\",\n   \"discriminate\", \"equality\", \"exfalso\", \"linear_arithmetic\" and\n   \"apply read_last_value in H\", \"subst\" in our solution.\n   But it's a good test case to make sure you got the definition of \"eval\" right!\n   And note that inverting the hypotheses in the right order, i.e.\n   in the order the program is executed, as well as using read_last_value\n   whenever possible, will make your proof less long. *)\nTheorem the_answer_is_indeed_42:\n  forall v, eval $0 the_answer_is_42 v -> v $? \"answer\" = Some 42.\nProof.\n  simplify.\n  invert H.\n  simplify.\n  invert H3.\n  simplify.\n  invert H5.\n  simplify.\n  - simplify.\n    invert H2.\n    + simplify.\n      invert H8.\n      simplify.\n      invert H3.\n      invert H.\n      propositional.\n      invert H6.\n      simplify.\n      invert H11.\n      simplify.\n      equality.\n      simplify.\n      invert H10.\n      simplify.\n      linear_arithmetic.\n    + simplify.\n      invert H7.\n      simplify.\n      invert H6.\n      simplify.\n      invert H8.\n      simplify.\n      equality.\n      simplify.\n      equality.\nQed.\n\n\n\n(* Here's another example program. If we run it on a valuation which is\n   undefined for \"x\", it will read the undefined variable \"x\" to decide\n   whether to abort the loop, so any number of loop iterations is possible. *)\nExample loop_of_unknown_length :=\n  (While (Var \"x\") (Assign \"counter\" (Plus (Var \"counter\") (Const 1)))).\n\n(* Hint: you might need the \"maps_equal\" tactic to prove that two maps are the same. *)\nTheorem eval_loop_of_unknown_length: forall n initialCounter,\n    eval ($0 $+ (\"counter\", initialCounter))\n         loop_of_unknown_length\n         ($0 $+ (\"counter\", initialCounter + n)).\nProof.\n  unfold loop_of_unknown_length.\n  induct n; simplify.\n  + replace (initialCounter + 0) with initialCounter by linear_arithmetic. \n    eapply EvalWhileFalse. \n    simplify.\n    equality.\n  +\n    eapply EvalWhileTrue.\n    simplify.\n    equality.\n    eauto.\n    econstructor.\n    simplify.\n    exists initialCounter, 1.\n    propositional.\n    specialize (IHn (initialCounter + 1)).\n    replace ($0 $+ (\"counter\", initialCounter) $+ (\"counter\", initialCounter + 1)) with ($0 $+ (\"counter\", initialCounter + 1)) by maps_equal. \n    replace (initialCounter + S n) with (initialCounter + 1 + n) by linear_arithmetic. \n    assumption.\nQed.\n\n(* Wherever this TODO_FILL_IN is used, you should replace it with your solution *)\nAxiom TODO_FILL_IN: Prop.\n\n(* You might wonder whether we can use \"Fixpoint\" instead of \"Inductive\" to define\n   such nondeterministic big-step evaluation of commands, and indeed we can.\n   But we need some trick to convince Coq that this Fixpoint will always terminate,\n   even though there could be infinite loops.\n   We achieve this by using a \"fuel\" argument that limits the recursion depth.\n   This does not exclude any possible final valuations, because for every final\n   valuation, there exists a recursion depth sufficient to reach it.\n   So let's define a Fixpoint \"run\" such that \"run fuel v1 c v2\" means\n   \"if we run command c on valuation v1, and limit the recursion depth to fuel,\n   we can obtain valuation v2\".\n   We already defined all cases for you except the \"While\" case, but all the\n   building blocks you need can be found in the other cases too.\n *)\nFixpoint run(fuel: nat)(v1: valuation)(c: cmd)(v2: valuation): Prop :=\n  match fuel with\n  | O => False\n  | S fuel' =>\n    match c with\n    | Skip => v1 = v2\n    | Assign x e => exists a, interp e v1 a /\\ v2 = (v1 $+ (x, a))\n    | Sequence c1 c2 => exists vmid, run fuel' v1 c1 vmid /\\ run fuel' vmid c2 v2\n    | If e c1 c2 =>\n      (exists r, interp e v1 r /\\ r <> 0 /\\ run fuel' v1 c1 v2) \\/\n      (interp e v1 0 /\\ run fuel' v1 c2 v2)\n    | While e c1 =>\n      (interp e v1 0 /\\ v1 = v2) \\/ \n      (exists v', exists r, interp e v1 r /\\ r <> 0 /\\ run fuel' v1 c1 v' /\\ run fuel' v' (While e c1) v2) \n    end\n  end.\n\n(* Now let's prove that \"run\" and \"eval\" are equivalent! *)\n(*Lemma running_with_more_fuel: forall fuel v1 c v2, run (S fuel) v1 c v2 -> run fuel v1 c v2.\nProof.\n  induct fuel.\n  simplify.\n  cases c.\n  equality.\n  simplify.\n*)\nTheorem run_to_eval: forall fuel v1 c v2,\n    run fuel v1 c v2 ->\n    eval v1 c v2.\nProof.\n  simplify.\n  induct fuel.\n  simplify.\n  equality.\n\n\n  simplify.\n  \n  cases c.\n  rewrite H.\n  eapply EvalSkip.\n\n  invert H.\n  propositional.\n  rewrite H1.\n  eapply EvalAssign.\n  assumption.\n\n\n  invert H.\n  propositional.\n  eapply EvalSeq.\n  eauto.\n  apply IHfuel.\n  assumption.\n\n  { \n    invert H.\n    invert H0.\n\n    propositional.\n    eapply EvalIfTrue. \n    eauto.\n    assumption.\n    apply IHfuel.\n    assumption.\n\n    propositional.\n    eapply EvalIfFalse. \n    eauto.\n    apply IHfuel.\n    assumption.\n  }\n\n  propositional.\n  rewrite <- H1.\n  eapply EvalWhileFalse.\n  assumption.\n\n  invert H0.\n  invert H.\n  propositional.\n  eapply EvalWhileTrue.\n\n  eauto.\n  assumption.\n  eauto.\n  apply IHfuel.\n  assumption.\nQed.\n\n(* For the other direction, we could naively start proving it like this: *)\nTheorem eval_to_run: forall v1 c v2,\n    eval v1 c v2 ->\n    exists fuel, run fuel v1 c v2.\nProof.\n  induct 1; simplify.\n\n  exists 1.\n  simplify.\n  equality.\n\n\n  exists 1.\n  simplify.\n  exists a.\n  propositional.\n  \n  exists 1.\n  simplify.\n  eexists.\n  equality.\n  propositional.\n  invert IHeval1.\n  invert IHeval2.\n  simplify.\n  (* feel free to prove part of this to experience how tedious the existentials\n     are, but don't waste too much time on it, because there's a better way\n     to do it below! *)\nAbort. (* <-- do not change this line *)\n\n(* To prove the other direction, we will first define a wrapper around \"run\"\n   that hides the existential: *)\nDefinition wrun(v1: valuation)(c: cmd)(v2: valuation): Prop :=\n  exists fuel, run fuel v1 c v2.\n\n(* The idea is that in the run_to_eval proof above, using the constructors of\n   \"eval\", i.e. doing \"eapply EvalAssign\", \"eapply EvalSeq\", \"eapply EvalIfTrue\",\n   was quite convenient, so let's expose the same \"API\" for constructing proofs\n   of \"run\" (or actually, proofs of the slightly nicer \"wrun\"). *)\n\n(* But first, we need a helper lemma run_monotone.\n   Hint: Here, some proof automation might pay off!\n   You could try writing a \"repeat match goal\" loop, to do all possible\n   simplifications on your hypotheses, and then use \"eauto\" to solve\n   the goal. Maybe you need to increase the maximum search depth of eauto;\n   in our solution, we had to write \"eauto 10\" instead of just \"eauto\",\n   which defaults to \"eauto 5\".\n   And note that \"eauto\" does not know about linear arithmetic by default,\n   so either you have to register that as an extern hint, but a simpler\n   way here would be to use the lemma \"le_S_n\" to turn \"S fuel1 <= S fuel2\"\n   into \"fuel1 <= fuel2\", which will be needed for the IH. *)\n\n\nLemma run_monotone_less_fuel_impl: forall fuel1 v1 c v2,\n  run fuel1 v1 c v2 -> run (S fuel1) v1 c v2.\nProof.\n  induct fuel1.\n  simplify.\n  equality.\n\n  intros.\n  cases c.\n  assumption.\n  assumption.\n  invert H.\n  propositional.\n\n  + apply IHfuel1 in H.\n    apply IHfuel1 in H1.\n    econstructor.\n    eauto.\n  +\n    simpl in H.\n    invert H.\n    invert H0.\n    propositional.\n    apply IHfuel1 in H2.\n    econstructor.\n    eexists.\n    eauto.\n\n    propositional.\n    apply IHfuel1 in H1.\n    constructor 2.\n    propositional.\n  +\n    simpl in H.\n    invert H.\n    - propositional.\n      econstructor 1.\n      propositional.\n    - invert H0.\n      invert H.\n      propositional.\n      econstructor 2.\n      eexists.\n      eexists.\n      apply IHfuel1 in H1.\n      propositional.\n      eauto.\n      linear_arithmetic.\n      eauto.\n      apply IHfuel1 in H3.\n      assumption.\nQed.\n\nLemma run_monotone: forall fuel1 fuel2 v1 c v2,\n    fuel1 <= fuel2 ->\n    run fuel1 v1 c v2 ->\n    run fuel2 v1 c v2.\nProof.\n  induct 1.\n  trivial.\n  induct m.\n  apply le_lt_or_eq in H.\n  cases H.\n  linear_arithmetic.\n  rewrite H.\n  simplify. equality.\n  \n  intros.\n  apply IHle in H0.\n  apply run_monotone_less_fuel_impl.\n  assumption.\nQed.\n\n(* Now let's define proof rules to get the same \"API\" for \"wrun\" as for \"eval\".\n   Hint: Again, some proof automation might simplify the task (but manual proofs are\n   possible too, of course). *)\n\nLemma WRunSkip: forall v,\n    wrun v Skip v.\nProof.\nsimplify.\neexists 1.\nsimplify.\nequality.\nQed.\n\nLemma WRunAssign: forall v x e a,\n    interp e v a ->\n    wrun v (Assign x e) (v $+ (x, a)).\nProof.\n  exists 1.\n  simplify.\n  exists a.\n  propositional.\nQed. \n\nLemma WRunSeq: forall v c1 v1 c2 v2,\n    wrun v c1 v1 ->\n    wrun v1 c2 v2 ->\n    wrun v (Sequence c1 c2) v2.\nProof.\n  simplify.\n  invert H.\n  invert H0.\n\n  exists (S x + S x0).\n  simplify.\n  econstructor.\n  propositional.\n  apply run_monotone with (fuel2:= x + S x0) in H1; eauto; linear_arithmetic.\n  apply run_monotone with (fuel2:= x + S x0) in H; eauto; linear_arithmetic.\nQed.\n\nLemma WRunIfTrue: forall n v e thn els v',\n  interp e v n ->\n  n <> 0 ->\n  wrun v thn v' ->\n  wrun v (If e thn els) v'.\nProof.\n  simplify.\n  invert H1.\n  exists (S x).\n  econstructor.\n  eexists.\n  propositional.\n  eauto.\n  equality.\nQed.\n\nLemma WRunIfFalse: forall v e thn els v',\n    interp e v 0\n    -> wrun v els v'\n    -> wrun v (If e thn els) v'.\nProof.\n  simplify.\n  invert H0.\n  exists (S x).\n  econstructor 2.\n  propositional.\nQed.\n\nLemma WRunWhileTrue: forall n v e body v' v'',\n    interp e v n\n    -> n <> 0\n    -> wrun v body v'\n    -> wrun v' (While e body) v''\n    -> wrun v (While e body) v''.\nProof.\n  simplify.\n  invert H1.\n  invert H2.\n  exists (S x + S x0).\n  econstructor 2.\n  eexists.\n  eexists.\n  propositional.\n  eauto.\n  equality.\n  apply run_monotone with (fuel2:= x + S x0) in H3; eauto; linear_arithmetic.\n  apply run_monotone with (fuel2:= x + S x0) in H1; eauto; linear_arithmetic.\nQed.\n\n\n\nLemma WRunWhileFalse: forall v e body,\n    interp e v 0 \n    -> wrun v (While e body) v.\nProof.\nsimplify.\nexists 1.\neconstructor.\npropositional.\nQed.\n\n(* Now, thanks to these helper lemmas, proving the direction from eval to wrun\n   becomes easy: *)\nTheorem eval_to_wrun: forall v1 c v2,\n    eval v1 c v2 ->\n    wrun v1 c v2.\nProof.\n  induct 1.\n  apply WRunSkip.\n  apply WRunAssign; assumption.\n  apply WRunSeq with (v:=v) (c1:=c1)(v1:=v1); assumption.\n  apply WRunIfTrue with (v:=v) (n:=n);assumption.\n  apply WRunIfFalse with (v:=v) ;assumption.\n  apply WRunWhileTrue with (n:=n) (v:=v) (v':=v'); assumption.\n  apply WRunWhileFalse with (v:=v) (e:=e); assumption.\nQed.\n\n(* The following definitions are needed because of a limitation of Coq\n   (the kernel does not recognize that a parameter can be instantiated by an\n   inductive type).\n   Please do not remove them! *)\nDefinition values_alias_for_grading := values.\nDefinition eval_alias_for_grading := eval.\n\n(* You've reached the end of this pset, congratulations! *)\n\n(* ****** Everything below this line is optional ****** *)\n\n(* Let's take the deterministic semantics we used in OperationalSemantics.v, but\n   prefix them with \"d\" to mark them as deterministic: *)\n\nFixpoint dinterp(e: arith)(v: valuation): nat :=\n  match e with\n  | Const n => n\n  | Var x =>\n    match v $? x with\n    | None => 0\n    | Some n => n\n    end\n  | Plus e1 e2 => dinterp e1 v + dinterp e2 v\n  end.\n\nInductive deval: valuation -> cmd -> valuation -> Prop :=\n| DEvalSkip: forall v,\n    deval v Skip v\n| DEvalAssign: forall v x e,\n    deval v (Assign x e) (v $+ (x, dinterp e v))\n| DEvalSeq: forall v c1 v1 c2 v2,\n    deval v c1 v1 ->\n    deval v1 c2 v2 ->\n    deval v (Sequence c1 c2) v2\n| DEvalIfTrue: forall v e thn els v',\n    dinterp e v <> 0 ->\n    deval v thn v' ->\n    deval v (If e thn els) v'\n| DEvalIfFalse: forall v e thn els v',\n    dinterp e v = 0 ->\n    deval v els v' ->\n    deval v (If e thn els) v'\n| DEvalWhileTrue: forall v e body v' v'',\n    dinterp e v <> 0 ->\n    deval v body v' ->\n    deval v' (While e body) v'' ->\n    deval v (While e body) v''\n| DEvalWhileFalse: forall v e body,\n    dinterp e v = 0 ->\n    deval v (While e body) v.\n\nLemma interp_same_dinerp: forall e v, interp e v (dinterp e v).\nProof.\n  induct e; simplify; try equality.\n  cases ( v $? x); try equality.\n  exists (dinterp e1 v).\n  exists (dinterp e2 v).\n  specialize (IHe1 v).\n  specialize (IHe2 v).\n  propositional.\nQed.\n\n(* Now let's prove that if a program evaluates to a valuation according to the\n   deterministic semantics, it also evaluates to that valuation according to\n   the nondeterministic semantics (the other direction does not hold, though). *)\nTheorem deval_to_eval: forall v1 v2 c,\n    deval v1 c v2 ->\n    eval v1 c v2.\nProof.\n  induct 1; simplify.\n  econstructor.\n  + econstructor.\n    apply interp_same_dinerp.\n  + econstructor; eauto; assumption.\n  + econstructor. instantiate (1:= dinterp e v). apply interp_same_dinerp. \n    assumption. assumption.\n  + constructor. replace 0 with (dinterp e v). apply interp_same_dinerp. assumption. \n  + econstructor. instantiate (1:=dinterp e v). apply interp_same_dinerp.\n    assumption. eauto. assumption.\n  + constructor. replace 0 with (dinterp e v). apply interp_same_dinerp.\nQed.\n\n(* In deterministic semantics, Fixpoints work a bit better, because they\n   can return just one value, and let's use \"option\" to indicate whether\n   we ran out of fuel: *)\nFixpoint drun(fuel: nat)(v: valuation)(c: cmd): option valuation := \n  match fuel with\n  | O => None\n  | S fuel' =>\n    match c with\n    | Skip => Some v\n    | Assign x e => Some (v $+ (x, (dinterp e v)))\n    | Sequence c1 c2 => \n        match (drun fuel' v c1) with \n        | None => None\n        | Some v2 => drun fuel' v2  c2\n        end\n    | If e c1 c2 =>\n        match (dinterp e v) with\n        | 0 =>   drun fuel' v c2 \n        | _ =>   drun fuel' v c1\n        end\n    | While e c1 =>\n        match (dinterp e v) with\n        | 0 => Some v \n        | _ => match (drun fuel' v c1) with\n               | None => None  \n               | Some v2 => drun fuel' v2 (While e c1)\n               end\n        end\n    end\n  end.\n\nLemma run_once: forall fuel1 v1 c,\n  drun (S fuel1) v1 c =  match c with\n    | Skip => Some v1\n    | Assign x e => Some (v1 $+ (x, dinterp e v1))\n    | Sequence c1 c2 =>\n        match drun fuel1 v1 c1 with\n        | Some v2 => drun fuel1 v2 c2\n        | None => None\n        end\n    | If e c1 c2 =>\n        match dinterp e v1 with\n        | 0 => drun fuel1 v1 c2\n        | S _ => drun fuel1 v1 c1\n        end\n    | While e c1 =>\n        match dinterp e v1 with\n        | 0 => Some v1\n        | S _ =>\n            match drun fuel1 v1 c1 with\n            | Some v2 => drun fuel1 v2 (While e c1)\n            | None => None\n            end\n        end\n    end. \nProof.\n  equality.\nQed.\n\nLemma drun_monotone_less_fuel_impl: forall fuel1 v1 c v2,\n  drun fuel1 v1 c = Some v2 -> drun (S fuel1) v1 c = Some v2.\nProof.\n  induct fuel1.\n  simplify.\n  equality.\n\n  intros. \n  cases c.\n  simpl in H.\n  + simpl; try assumption.\n  + simpl; try assumption.\n  + rewrite run_once. simpl in H. cases (drun fuel1 v1 c1).\n    - apply IHfuel1 in Heq. rewrite Heq. apply IHfuel1 in H. assumption. \n    - equality.\n  + rewrite run_once. simpl in H. cases (dinterp e v1).\n    - apply IHfuel1 in H. assumption. \n    - apply IHfuel1 in H. assumption.\n  + rewrite run_once. simpl in H. cases (dinterp e v1).\n    - assumption. \n    - cases (drun fuel1 v1 c).\n     --  apply IHfuel1 in Heq0. rewrite Heq0. apply IHfuel1 in H. assumption.\n     -- equality.\nQed.\n\nLemma drun_monotone: forall fuel1 fuel2 v1 c v2,\n    fuel1 <= fuel2 ->\n    drun fuel1 v1 c = Some v2 ->\n    drun fuel2 v1 c = Some v2.\nProof.\n  induct 1.\n  trivial.\n  induct m.\n  apply le_lt_or_eq in H.\n  cases H.\n  linear_arithmetic.\n  rewrite H.\n  simplify. equality.\n  \n  intros.\n  apply IHle in H0.\n  apply drun_monotone_less_fuel_impl.\n  assumption.\nQed.\n\nDefinition dwrun(v1: valuation)(c: cmd)(v2: valuation): Prop :=\n  exists fuel, drun fuel v1 c = Some v2.\n\n\nLemma dWRunSkip: forall v,\n    dwrun v Skip v.\nProof.\nsimplify.\neexists 1.\nsimplify.\nequality.\nQed.\n\nLemma dWRunAssign: forall v x e a,\n    dinterp e v = a ->\n    dwrun v (Assign x e) (v $+ (x, a)).\nProof.\n  exists 1.\n  simplify.\n  rewrite H.\n  equality.\nQed. \n\nLemma dWRunSeq: forall v c1 v1 c2 v2,\n    dwrun v c1 v1 ->\n    dwrun v1 c2 v2 ->\n    dwrun v (Sequence c1 c2) v2.\nProof.\n  simplify.\n  invert H.\n  invert H0.\n\n  exists (S (x + x0)).\n  rewrite run_once.\n  apply drun_monotone with (fuel1:= x) (fuel2:= (x + x0)) in H1.\n  rewrite H1.\n  apply drun_monotone with (fuel2:= (x + x0)) in H.\n  assumption.\n  linear_arithmetic.\n  linear_arithmetic.\nQed.\n\nLemma dWRunIfTrue: forall v e thn els v',\n  dinterp e v <> 0 ->\n  dwrun v thn v' ->\n  dwrun v (If e thn els) v'.\nProof.\n  simplify.\n  invert H0.\n  exists (S x).\n  cases (dinterp e v).\n  equality.\n  simpl.\n  rewrite Heq.\n  assumption.\nQed.\n\n\nLemma dWRunIfFalse: forall v e thn els v',\n    dinterp e v = 0\n    -> dwrun v els v'\n    -> dwrun v (If e thn els) v'.\nProof.\n  simplify.\n  invert H0.\n  exists (S x).\n  rewrite run_once.\n  cases (dinterp e v).\n  equality.\n  equality.\nQed.\n\nLemma dWRunWhileFalse: forall v e body,\n    dinterp e v = 0 \n    -> dwrun v (While e body) v.\nProof.\nsimplify.\nexists 1.\nsimpl.\ncases (dinterp e v); equality.\nQed.\n\nLemma dWRunWhileTrue: forall v e body v' v'',\n    dinterp e v <> 0\n    -> dwrun v body v'\n    -> dwrun v' (While e body) v''\n    -> dwrun v (While e body) v''.\nProof.\n  simplify.\n  invert H1.\n  invert H0.\n  exists (S (x + x0)).\n  rewrite run_once.\n  cases (dinterp e v ).\n  equality.\n  apply drun_monotone with (fuel2:= x + x0) in H1. rewrite H1.\n  apply drun_monotone with (fuel2:=x + x0) in H2. assumption.\n  linear_arithmetic.\n  linear_arithmetic.\nQed.\n\n\nLemma deval_to_drun: forall v1 c v2, \n  deval v1 c v2 -> exists f, drun f v1 c = Some v2.\nProof.\n  induct 1.\n  apply dWRunSkip.\n  apply dWRunAssign. equality.\n  apply dWRunSeq with (v:=v) (c1:=c1)(v1:=v1); assumption.\n  apply dWRunIfTrue with (v:=v); assumption.\n  apply dWRunIfFalse with (v:=v) ;assumption.\n  apply dWRunWhileTrue with (v:=v) (v':=v'); assumption.\n  apply dWRunWhileFalse with (v:=v) (e:=e); assumption.\nQed.\n\nLemma drun_to_run: forall f v1 c v2 ,\n  drun f v1 c = Some v2 -> run f v1 c v2.\nProof.\n  induct f.\n\n  simplify.\n  equality.\n  intros.\n  cases c.\n  + simplify. equality.\n  + simplify. econstructor. eexists. instantiate (1:=dinterp e v1). apply interp_same_dinerp. equality.\n  + rewrite run_once in H. cases (drun f v1 c1).\n   - econstructor. instantiate (1:= v). propositional; first_order. \n   - equality.\n  + simplify. cases (dinterp e v1). econstructor 2. propositional. rewrite <- Heq. apply interp_same_dinerp. apply IHf. assumption.\n    econstructor 1. exists (S n). propositional. rewrite <- Heq. apply interp_same_dinerp. equality. apply IHf. assumption.  \n  + simplify. cases (dinterp e v1). \n    - econstructor 1. propositional; try equality. rewrite <- Heq. apply interp_same_dinerp.\n    - cases (drun f v1 c). econstructor 2. eexists. eexists. propositional. instantiate (1:= S n). rewrite <- Heq. apply interp_same_dinerp. equality.\n      apply IHf. eauto. apply IHf. assumption. equality. \nQed.\n\n(* More open-ended exercise:\n   Now we have six different definitions of semantics:\n\n                        deterministic     nondeterministic\n\n   Inductive            deval             eval\n\n   Wrapped Fixpoint     dwrun             wrun\n\n   Fixpoint             drun              run\n\n   We have proved that all the nondeterministic semantics are equivalent among\n   each other.\n   If you want, you could also prove that all the deterministic semantics are\n   equivalent among each other and experiment whether it's worth creating an\n   \"Inductive\"-like API for \"dwrun\", or whether you're ok dealing with drun's\n   existentials when proving deval_to_drun.\n   Moreover, we have proved that \"deval\" implies \"eval\", so every definition in\n   the left column of the above table implies every definition in the right\n   column of the table.\n   If you're curious to learn more about the trade-offs between Inductive Props\n   and Fixpoints, you can try to prove some of these implications directly,\n   and see how much harder than \"deval_to_eval\" it is (we believe that\n   \"deval_to_eval\" is the simplest one).\n *)\n\n", "meta": {"author": "nicolas3355", "repo": "FormalReasoningAboutProgramsSpring2020", "sha": "85a908b07ea5b95212979ce224f902ad23497208", "save_path": "github-repos/coq/nicolas3355-FormalReasoningAboutProgramsSpring2020", "path": "github-repos/coq/nicolas3355-FormalReasoningAboutProgramsSpring2020/FormalReasoningAboutProgramsSpring2020-85a908b07ea5b95212979ce224f902ad23497208/pset05_BigStepVsInterpreter/Pset5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7152909449612309}}
{"text": "(*\n        #####################################################\n        ###  PLEASE DO NOT DISTRIBUTE SOLUTIONS PUBLICLY  ###\n        #####################################################\n*)\n\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Lists.List.\nFrom Turing Require Import Lang.\nFrom Turing Require Import Util.\nImport LangNotations.\nImport ListNotations.\nImport Lang.Examples.\nOpen Scope lang_scope.\nOpen Scope char_scope.\n\n(* ---------------------------------------------------------------------------*)\n\n\n\n\n(**\n\nShow that any word that is in L4 is either empty or starts with \"a\".\n\n *)\nTheorem ex1:\n  forall w, L4 w -> w = [] \\/ exists w', w = \"a\" :: w'.\nProof. \n  intros.\n  destruct H.\n  destruct x.\n  - Search (_>>_). \n    apply pow_pow_in_inv in H.\n    simpl in H.\n    left.\n    rewrite H.\n    easy.\n  - apply pow_pow_in_inv in H.\n    simpl in H.\n    right.\n    exists (pow1 \"a\" x ++ \"b\" :: pow1 \"b\" x).\n    apply H.\nQed.\n\n(**\n\nShow that the following word is accepted by the given language.\n\n *)\nTheorem ex2:\n  In [\"a\"; \"b\"; \"b\"; \"a\"] (\"a\" >> \"b\" * >> \"a\").\nProof.\n  Search (_>>_).\n  apply app_assoc_in_1.\n  Search (_>>_).\n  apply app_l_char_in.\n  Search (_>>_).\n  apply app_in with (w1:=[\"b\";\"b\"]) (w2:=[\"a\"]).\n  - Search (_>>_).\n    apply pow_to_star with (n:=2) .\n    Search (In _ (_^^ _)).\n    apply pow_char_in.\n  - Search (In _ (_) ).\n    apply char_in.\n  - easy.\nQed.\n\n\n(**\n\nShow that the following word is rejected by the given language.\n\n *)\nTheorem ex3:\n  ~ In [\"b\"; \"b\"] (\"a\" >> \"b\" * >> \"a\").\nProof.\n  intros s.\n  Search (_>>_).\n  apply app_assoc_in_2 in s.\n  Search (_>>_).\n  apply app_l_char_in_inv with (c:=\"a\") in s.\n  destruct s. \n  destruct H. \n  easy.\nQed.\n\n(**\n\nShow that the following language is empty.\n\n *)\nTheorem ex4:\n  \"0\" * >> {} == {}.\nProof.\n apply app_r_void_rw.\nQed.\n\n(**\n\nRearrange the following terms. Hint use the distribution and absorption laws.\n\n *)\nTheorem ex5:\n  (\"0\" U Nil) >> ( \"1\" * ) == ( \"0\" >> \"1\" * ) U ( \"1\" * ).\nProof. \n  unfold Equiv; intros.\n  - rewrite <- app_union_distr_l.\n    Search (Nil).\n    rewrite app_l_nil_rw.\n    reflexivity.\nQed.\n\n(**\n\nShow that the following langue only accepts two words.\n\n *)\nTheorem ex6:\n  (\"0\" >> \"1\" U \"1\" >> \"0\") == fun w => (w = [\"0\"; \"1\"] \\/ w = [\"1\"; \"0\"]).\nProof. unfold Equiv.\n  split; intros.\n  - unfold Union, In, App in *.\n    destruct H. destruct H as (x, (x0, H)). \n    left.\n    -- destruct H. rewrite H. inversion H0. \n       unfold Char in *. rewrite H1. rewrite H2. reflexivity.\n    -- right. destruct H as (x, (x0, (H, (H0, H1)))).\n       unfold Char in *.\n       rewrite H, H0, H1.\n       reflexivity.\n  - unfold In, Union, App in *. destruct H.\n    -- left. exists [\"0\"], [\"1\"]. split.\n       * rewrite H. reflexivity.  \n       * split. \n          ** unfold Char; reflexivity. \n          ** unfold Char; reflexivity.\n    -- unfold In, Union, App. right. exists [\"1\"], [\"0\"]. split.\n       * rewrite H. reflexivity. \n       * split. \n         ** unfold Char; reflexivity. \n         ** unfold Char; reflexivity.\nQed.\n\n\n\nTheorem ex7:\n  \"b\" >> (\"a\" U \"b\" U Nil) * >> Nil == \"b\" >> (\"b\" U \"a\") *.\nProof.\n    split;intros A.\n   Search(_ >> _).\n  - rewrite app_r_nil_rw in A.\n    Search(_ U _). \n    rewrite union_sym_rw in A.\n     Search(_ U _). \n    rewrite  star_union_nil_rw in A.\n    Search(_ U _).\n    rewrite  union_sym_rw in A.\n    apply A.\n   - rewrite app_r_nil_rw.\n    rewrite union_sym_rw.\n    rewrite star_union_nil_rw.\n    rewrite union_sym_rw in A.\n    apply A.\nQed.\n\n\nTheorem ex8:\n  ((\"b\" >> (\"a\" U {}) ) U (Nil >> {} >> \"c\")* ) * == (\"b\" >> \"a\") *.\nProof.\n  split;intros.\n- rewrite union_r_void_rw in H.\n  rewrite app_r_void_rw in H.\n  rewrite app_l_void_rw in H.\n  rewrite star_void_rw in H.\n  rewrite union_sym_rw in H.\n  rewrite star_union_nil_rw in H.\n  apply H.\n- rewrite union_r_void_rw.\n  rewrite app_r_void_rw.\n  rewrite app_l_void_rw.\n  rewrite star_void_rw.\n  rewrite union_sym_rw.\n  rewrite star_union_nil_rw.\n  apply H.\nQed.\n\n\n\n\nStudent\nDivya Thota\nAutograder Score\n100.0 / 100.0\n", "meta": {"author": "divya-thota", "repo": "Masters-Program-CS420", "sha": "1c5c2c06bb1dc2ba2817cf8dbc99d703512c3723", "save_path": "github-repos/coq/divya-thota-Masters-Program-CS420", "path": "github-repos/coq/divya-thota-Masters-Program-CS420/Masters-Program-CS420-1c5c2c06bb1dc2ba2817cf8dbc99d703512c3723/hw3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7152543665656167}}
{"text": "(* Add LoadPath \"/\". *)\n\nRequire Export poly_j.\n\nDefinition plus_fact : Prop := 2+2 = 4.\nCheck plus_fact.\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity. Qed.\n\nDefinition strange_prop1 : Prop :=\n  (2+2 = 5) -> (99+26 = 42).\n\nDefinition strange_prop2 :=\n  forall n, (ble_nat n 17 = true) -> (ble_nat n 99 = true).\n\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\n\nCheck even.\nCheck(even 4).\nCheck(even 3).\n\nDefinition even_n__even__SSn (n:nat) : Prop :=\n  (even n) -> (even (S (S n))).\n\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\n\nDefinition teen : nat -> Prop := between 13 19.\n\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\n\nDefinition true_for_n__true_for_Sn (P:nat->Prop) (n:nat) : Prop :=\n  P n -> P (S n).\n\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\n\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\n\nDefinition our_nat_induction (P:nat->Prop) : Prop :=\n  (true_for_zero P) ->\n  (preserved_by_S P) ->\n  (true_for_all_numbers P).\n\nInductive good_day : day ->  Prop :=\n  | gd_sat : good_day saturday\n  | gd_sun : good_day sunday.\n\nTheorem gds : good_day sunday.\nProof. apply gd_sun. Qed.\n\nInductive day_before : day -> day -> Prop :=\n  | db_tue : day_before tuesday monday\n  | db_wed : day_before wednesday tuesday\n  | db_thu : day_before thursday wednesday\n  | db_fri : day_before friday thursday\n  | db_sat : day_before saturday friday\n  | db_sun : day_before sunday saturday\n  | db_mon : day_before monday sunday.\n\nInductive fine_day_for_singing : day -> Prop :=\n  | fdfs_any : forall d:day, fine_day_for_singing d.\n\nTheorem fdfs_wed : fine_day_for_singing wednesday.\nProof. apply fdfs_any. Qed.\n\nDefinition fdfs_wed' : fine_day_for_singing wednesday :=\n  fdfs_any wednesday.\n\nCheck fdfs_wed.\nCheck fdfs_wed'.\n\nInductive ok_day : day -> Prop :=\n  | okd_gd : forall d,\n      good_day d ->\n      ok_day d\n  | okd_before : forall d1 d2,\n      ok_day d2 ->\n      day_before d2 d1 ->\n      ok_day d1.\n\nDefinition okdw : ok_day wednesday :=\n  okd_before wednesday thursday\n    (okd_before thursday friday\n       (okd_before friday saturday\n         (okd_gd saturday gd_sat)\n         db_sat)\n       db_fri)\n    db_thu.\n\nTheorem okdw' : ok_day wednesday.\nProof.\n  apply okd_before with (d2:=thursday).\n    apply okd_before with (d2:=friday).\n      apply okd_before with (d2:=saturday).\n        apply okd_gd. apply gd_sat.\n        apply db_sat.\n      apply db_fri.\n   apply db_thu. Qed.\n\nPrint okdw'.\n\nDefinition okd_before2 := forall d1 d2 d3,\n  ok_day d3 ->\n  day_before d2 d1 ->\n  day_before d3 d2 ->\n  ok_day d1.\n\nTheorem okd_before2_valid : okd_before2.\nProof.\n  unfold okd_before2.\n  intros.\n  generalize dependent H0.\n  apply okd_before.\n  generalize dependent H1.\n  apply okd_before.\n  apply H.\nQed.\n\nDefinition okd_before2_valid' : okd_before2 :=\n  fun (d1 d2 d3  : day) =>\n  fun (H : ok_day d3) =>\n  fun (H0 : day_before d2 d1) =>\n  fun (H1 : day_before d3 d2) =>\n  okd_before d1 d2 (okd_before d2 d3 H H1) H0.\n\nPrint okd_before2_valid.\n\nCheck nat_ind.\n\nTheorem mult_0_r' : forall n:nat,\n  n*0 = 0.\nProof.\n  apply nat_ind.\n  Case \"O\". reflexivity.\n  Case \"S\". simpl. intros n IHn. rewrite -> IHn.\n    reflexivity. Qed.\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  Case \"O\". reflexivity.\n  Case \"S\". intros. simpl. rewrite H. reflexivity.\nQed.\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind.\n\nInductive rgb : Type :=\n  | red : rgb\n  | green :rgb\n  | blue : rgb.\n\nCheck rgb_ind.\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\n\nCheck natlist1_ind.\n\nInductive ExSet : Type :=\n  | con1 : bool -> ExSet\n  | con2 : nat -> ExSet -> ExSet.\n\nCheck ExSet_ind.\n\nInductive tree (X:Type) : Type :=\n  | leaf : X -> tree X\n  | node : tree X -> tree X -> tree X.\nCheck tree_ind.\n\nInductive mytype (X : Type) :=\n  | constr1 : X -> mytype X\n  | constr2 : nat -> mytype X\n  | constr3 : mytype X -> nat -> mytype X.\n\nCheck mytype_ind.\n\nInductive foo (X Y : Type) :=\n  | bar : X -> foo X Y\n  | baz : Y -> foo X Y\n  | quux : (nat -> foo X Y) -> foo X Y.\n\nCheck foo_ind.\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\n\nDefinition P_m0r' : nat->Prop :=\n  fun n =>  n * 0 = 0.\n\nTheorem mult_0_r'' : forall n:nat,\n  P_m0r n.\nProof.\n  apply nat_ind.\n  Case \"n = O\". reflexivity.\n  Case \"n = S n'\".\n    unfold P_m0r. simpl. intros n' IHn'.\n    apply IHn'. Qed.\n\nInductive ev: nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\nTheorem four_ev' :\n  ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nDefinition four_ev : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\nDefinition ev_plus4 : forall n, ev n -> ev (4+n) :=\n  fun(n : nat) => fun(p : ev n)\n  => ev_SS (S (S n)) (ev_SS n p).\nTheorem ev_plus4' : forall n,\n  ev n -> ev (4+n).\nProof.\n  intros.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\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\nTheorem ev_minus2: forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct 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\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'. Qed.\n\nTheorem ev_sum : forall n m,\n  ev n -> ev m -> ev (n+m).\nProof.\n  intros. induction H.\n  simpl. apply H0. simpl. apply ev_SS. apply IHev. Qed.\n\nTheorem SSev_ev : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E. inversion E as [| n' E']. apply E'.\nQed.\n\nTheorem SSSSev_even : forall n,\n  ev(S (S (S (S  n)))) -> ev n.\nProof.\n  intros. inversion H. inversion H1. apply H3.\nQed.\n\nTheorem even5_nonsense:\n  ev 5 -> 2+2 = 9.\nProof.\n  intros. inversion H. inversion H1. inversion H3.\nQed.\n\nTheorem ev_minu2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E. inversion E as [| n' E'].\n  Case \"E = ev_0\". simpl. apply ev_0.\n  Case \"E = ev_SS n' E'\". simpl. apply E'.\nQed.\n\nTheorem ev_ev_even : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros.\n  induction H0. simpl in H. apply H. inversion H. apply IHev.\n  apply H2.\nQed.\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_even with (m:=m+p) (n:=n+m).\n  replace (n+m+(m+p)) with (n+p+double m).\n  apply ev_sum.\n  apply H0.\n  apply double_even.\n  rewrite double_plus.\n  rewrite plus_swap.\n  rewrite plus_swap with (n:=n+m).\n  SearchAbout (_+_+_).\n  rewrite <- plus_assoc.\n  rewrite <- plus_assoc.\n  replace (p+m) with (m+p).\n  reflexivity.\n  apply plus_comm.\n  apply H.\nQed.\n\nInductive MyProp : nat -> Prop :=\n  | MyProp1 : MyProp 4\n  | MyProp2 : forall n:nat, MyProp n -> MyProp(4+n)\n  | MyProp3 : forall n:nat, MyProp (2+n) -> MyProp n.\n\nTheorem MyProp_ten : MyProp 10.\nProof.\n  apply MyProp3. simpl.\n  assert (12 = 4 + 8) as H12.\n    Case \"Proof of assertion\". reflexivity.\n  rewrite -> H12.\n  apply MyProp2.\n  assert (8 = 4 + 4) as H8.\n    Case \"Proof of assertion\". reflexivity.\n  rewrite -> H8.\n  apply MyProp2.\n  apply MyProp1.   Qed.\n\nTheorem MyProp_0 : MyProp 0.\nProof.\n  apply MyProp3.\n  apply MyProp3.\n  simpl.\n  apply MyProp1.\nQed.\n\nTheorem MyProp_plustwo : forall n:nat, MyProp n -> MyProp (S (S n)).\nProof.\n  intros.\n  apply MyProp3.\n  apply MyProp2.\n  apply H.\nQed.\n\nTheorem MyProp_ev : forall n:nat,\n  ev n -> MyProp n.\nProof.\n  intros n E.\n  induction E as [| n' E'].\n  Case \"E = ev_0\".\n    apply MyProp_0.\n  Case \"E = ev_SS n' E'\".\n    apply MyProp_plustwo. apply IHE'.  Qed.\n\nTheorem ev_MyProp : forall n:nat,\n  MyProp n -> ev n.\nProof.\n  intros.\n  induction H.\n  Case \"MyProp1\". \n    apply ev_SS.\n    apply ev_SS.\n    apply ev_0.\n  Case \"MyProp2\".\n    apply ev_SS.\n    apply ev_SS.\n    apply IHMyProp.\n  Case \"MyProp3\".\n    apply ev_minus2 in IHMyProp.\n    simpl in IHMyProp.\n    apply IHMyProp.\nQed.\n\nFixpoint true_upto_n__true_everywhere (n:nat) (f:nat->Prop) : Prop :=\n  match n with\n  | O => forall m : nat, f m\n  | S n' => f n -> (true_upto_n__true_everywhere n' f)\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\nCheck ev_ind.\n\nTheorem ev_even' : forall n,\n  ev n -> even n.\nProof.\n  apply ev_ind.\n  Case \"ev_0\". unfold even. reflexivity.\n  Case \"ev_SS\". intros n' E' IHE'. unfold even. apply IHE'. Qed.\n\nCheck list_ind.\nCheck ev_ind.\nPrint MyProp.\nCheck MyProp_ind.\n\nTheorem ev_MyProp' : forall n:nat,\n  MyProp n -> ev n.\nProof.\n  apply MyProp_ind.\n  Case \"MyProp1\".\n    apply ev_SS. apply ev_SS. apply ev_0.\n  Case \"MyProp2\".\n    intros. apply ev_SS. apply ev_SS. apply H0.\n  Case \"MyProp3\".\n    intros. apply ev_minus2 in H0. simpl in H0. apply H0.\nQed.\n\n\nModule P.\n\n(*hgoegeg*)\n\nInductive p : (tree nat) -> nat -> Prop :=\n   | c1 : forall n, p (leaf _ n) 1\n   | c2 : forall t1 t2 n1 n2,\n            p t1 n1 -> p t2 n2 -> p (node _ t1 t2) (n1 + n2)\n   | c3 : forall t n, p t n -> p t (S n).\n\nEnd P.\n\n", "meta": {"author": "sntea-hogex", "repo": "symbol_j", "sha": "55d2f019ce0442cb79887e30c26d1676038781e6", "save_path": "github-repos/coq/sntea-hogex-symbol_j", "path": "github-repos/coq/sntea-hogex-symbol_j/symbol_j-55d2f019ce0442cb79887e30c26d1676038781e6/prop_j.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7152543591278404}}
{"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\n\n\nDefinition next_weekday (d:day) : day :=\nmatch d with \n| monday => tuesday\n| tuesday => wednesday\n| wednesday => thursday\n| thursday => friday\n| friday => monday\n| saturday => monday\n| sunday => monday\nend.\n\nInductive bool : Type :=\n| true : bool\n| false : bool.\n\nDefinition negb (b: bool) : bool :=\nmatch b with\n| true => false\n| false => true\nend.\n\nDefinition andb (b1:bool) (b2:bool) : bool :=\nmatch b1 with\n| true => b2\n| false => false\nend.\n\nDefinition orb (b1:bool) (b2:bool) : bool :=\nmatch b1 with\n| true => true\n| false => b2\nend.\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\nInfix \"&&\" := andb.\n\nInfix \"||\" := orb.\n\nDefinition nandb (b1:bool) (b2:bool) : bool := (negb (andb b1 b2)).\n\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\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool := (andb b1 (andb b2 b3)).\n\n\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\nInductive nat : Type :=\n| O : nat\n| S : nat -> nat.\n\nDefinition pred (n : nat) : nat :=\nmatch n with \n| O => O\n| S n' => n'\nend.\n\nDefinition succ (n:nat) :nat :=\nmatch n with \n| O => (S O)\n| S n' => S (S n')\nend.\n\n\n\n\n\n\n", "meta": {"author": "soumyadsanyal", "repo": "sf", "sha": "6103ef0efb46d1e9d4f34f5f8269cdc1a554afc7", "save_path": "github-repos/coq/soumyadsanyal-sf", "path": "github-repos/coq/soumyadsanyal-sf/sf-6103ef0efb46d1e9d4f34f5f8269cdc1a554afc7/first.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7152543580859367}}
{"text": "Inductive term : Type :=\n| tmtrue : term\n| tmfalse : term\n| tmif : term -> term -> term -> term\n| tmzero : term\n| tmsucc : term -> term\n| tmpred : term -> term\n| tmiszero : term -> term.\n\nInductive type : Type := Bool | Nat.\n\nInductive is_numeric_val : term -> Prop :=\n| N_Zero :\n    is_numeric_val tmzero\n| N_Succ : forall t,\n    is_numeric_val t ->\n    is_numeric_val (tmsucc t).\n\nInductive is_val : term -> Prop :=\n| V_True :\n    is_val tmtrue\n| V_False :\n    is_val tmfalse\n| V_numericalval : forall t,\n    is_numeric_val t ->\n    is_val t.\n\nInductive subterm : term -> term -> Prop :=\n| S_IfCond : forall t t1 t2,\n    subterm t (tmif t t1 t2)\n| S_IfTrue : forall t t1 t2,\n    subterm t1 (tmif t t1 t2)\n| S_IfFalse : forall t t1 t2,\n    subterm t2 (tmif t t1 t2)\n| S_Succ : forall t,\n    subterm t (tmsucc t)\n| S_Pred : forall t,\n    subterm t (tmpred t)\n| S_IsZero : forall t,\n    subterm t (tmiszero t).\n\nInductive typed : term -> type -> Prop :=\n| T_True :\n    typed tmtrue Bool\n| T_False :\n    typed tmfalse Bool\n| T_Zero :\n    typed tmzero Nat\n| T_If : forall t t1 t2 T,\n    typed t Bool ->\n    typed t1 T ->\n    typed t2 T ->\n    typed (tmif t t1 t2) T\n| T_Succ : forall t,\n    typed t Nat ->\n    typed (tmsucc t) Nat\n| T_Pred : forall t,\n    typed t Nat ->\n    typed (tmpred t) Nat\n| T_IsZero : forall t,\n    typed t Nat ->\n    typed (tmiszero t) Bool.\n\nLemma subterm_typed : forall t T, typed t T -> forall s, subterm s t -> exists U, typed s U.\n  intros t T t_typed s s_t_subterm.\n  inversion s_t_subterm; subst; inversion t_typed.\n  -exists Bool; assumption.\n  -exists T; assumption.\n  -exists T; assumption.\n  -exists Nat; assumption.\n  -exists Nat; assumption.\n  -exists Nat; assumption.\nQed.\n\nLemma typed_bool : forall t, typed t Bool -> is_val t -> t = tmtrue \\/ t = tmfalse.\n  intros t H_type H_val.\n  induction H_val.\n  -left; reflexivity. (* t is true*)\n  -right; reflexivity. (* t is false *)\n  -inversion H. (* t is a numeric value (contradiction) *)\n   +rewrite <- H0 in H_type.\n    inversion H_type.\n   +rewrite <- H1 in H_type.\n    inversion H_type.\nQed.\n\nLemma typed_numericval : forall t, typed t Nat -> is_val t -> is_numeric_val t.\n  intros t H_type H_val.\n  induction H_val.\n  -inversion H_type. (* t is true (contradiction) *)\n  -inversion H_type. (* t is false (contradiction) *)\n  -assumption. (* t is a numeric value *)\nQed.\n\nReserved Notation \"x --> y\" (at level 80, no associativity).\n\nInductive step : term -> term -> Prop :=\n| E_IfTrue : forall t t',\n    (tmif tmtrue t t') --> t\n| E_IfFalse : forall t t',\n    (tmif tmfalse t t') --> t'\n| E_If : forall t t' t1 t2,\n    (t --> t') ->\n    ((tmif t t1 t2) --> (tmif t' t1 t2))\n| E_Succ : forall t t',\n    (t --> t') ->\n    tmsucc t --> tmsucc t'\n| E_Pred : forall t t',\n    (t --> t') ->\n    tmpred t --> tmpred t'\n| E_PredZero :\n    tmpred tmzero --> tmzero\n| E_PredSucc : forall nv,\n    is_numeric_val nv ->\n    tmpred (tmsucc nv) --> nv\n| E_IsZeroZero :\n    tmiszero tmzero --> tmtrue\n| E_IsZeroSucc : forall nv,\n    is_numeric_val nv ->\n    tmiszero (tmsucc nv) --> tmfalse\n| E_IsZero : forall t t',\n    t --> t' ->\n    tmiszero t --> tmiszero t'\n\nwhere \"x --> y\" := (step x y).\n\nLtac solve_by_inverts n :=\n  match goal with\n  | H : ?T |- _ =>\n    match type of T with Prop =>\n                         solve [\n                             inversion H;\n                             match n with S (S (?n')) => subst; solve_by_inverts (S n') end ]\n    end\n  end.\nLtac solve_by_invert := solve_by_inverts 1.\n\nDefinition relation (X : Type) := X -> X -> Prop.\n\nDefinition normal_form {X : Type} (R : relation X) (t : X) : Prop :=\n  not (exists t', R t t').\n\nLemma numericval_no_eval : forall nv, is_numeric_val nv -> normal_form step nv.\n  unfold normal_form.\n  intros nv H.\n  induction H.\n  - unfold not. intro H. inversion H. inversion H0.\n  - unfold not. intro H'. inversion H'. inversion H0.\n    apply IHis_numeric_val.\n    exists t'.\n    assumption.\nQed.\n\nTheorem value_is_nf : forall t, is_val t -> normal_form step t.\n  intros t t_val.\n  induction t_val.\n  - unfold normal_form. unfold not. intro H'. inversion H'. inversion H.\n  - unfold normal_form. unfold not. intro H'. inversion H'. inversion H.\n  - apply (numericval_no_eval t H).\nQed.\n\nLtac find_eqn :=\n  match goal with\n  | IH: forall t, ?P t -> ?L = ?R, H: ?P ?X |- _ => rewrite (IH X H) in *\nend.\n\nLtac find_succ :=\n  match goal with\n  | H1: is_numeric_val ?X, H2: ?X --> ?Y\n    |- _ => destruct (value_is_nf _ (V_numericalval _ H1)); exists Y; assumption\n  | H1: is_numeric_val ?X, H2: tmsucc ?X --> ?Y\n    |- _ => inversion H2; find_succ\n  end.\n\nLemma step_unique : forall t t1 t2, t --> t1 -> t --> t2 -> t1 = t2.\n  intros t t' t'' t_step_t' t_step_t''.\n  generalize dependent t''.\n  induction t_step_t'; intros t'' t_step_t''; inversion t_step_t''; subst;\n    try solve_by_invert; try find_eqn; try find_succ; auto.\nQed.\n\nTheorem process : forall t T, typed t T -> is_val t \\/ (exists t', t --> t').\n  intros t T t_typed.\n  induction t_typed.\n  -left; constructor.\n  -left; constructor.\n  -left; constructor; constructor.\n  -right.\n   case IHt_typed1.\n   +intro t_val.\n    assert (t = tmtrue \\/ t = tmfalse) as t_true_or_false.\n    { apply (typed_bool t t_typed1 t_val). }\n    case t_true_or_false.\n    *intro t_true; exists t1; rewrite t_true; constructor.\n    *intro t_false; exists t2; rewrite t_false; constructor.\n   +intro t_process.\n    destruct t_process as [t' t_process].\n    exists (tmif t' t1 t2); constructor; assumption.\n  -case IHt_typed.\n   +intro t_val; left.\n    constructor.\n    constructor.\n    apply (typed_numericval t t_typed t_val).\n   +intro t_process; right.\n    destruct t_process as [t' t_process].\n    exists (tmsucc t'); constructor; assumption.\n  -right.\n   case IHt_typed.\n   +intro t_val.\n    assert (is_numeric_val t) as t_numeric.\n    { apply (typed_numericval t t_typed t_val). }\n    inversion t_numeric.\n    *exists tmzero; constructor.\n    *exists t0; constructor; assumption.\n   +intro t_process.\n    destruct t_process as [t' t_process].\n    exists (tmpred t').\n    apply (E_Pred t t' t_process).\n  -case IHt_typed.\n   +intro t_val; right.\n    assert (is_numeric_val t) as t_numeric.\n    { apply (typed_numericval t t_typed t_val). }\n    inversion t_numeric.\n    *exists tmtrue.\n     constructor.\n    *exists tmfalse.\n     constructor; assumption.\n   +intro t_process; right.\n    destruct t_process as [t' t_process].\n    exists (tmiszero t'); constructor; assumption.\nQed.\n\nHint Constructors typed.\nLemma numericval_nat : forall t, is_numeric_val t -> typed t Nat.\n  intros t t_nv. induction t_nv; auto.\nQed.\n\nLtac find_process :=\n  match goal with\n  | Ht: typed ?X ?T, IH: forall t', ?X --> t' -> typed t' ?T, Hp: ?P ?X --> ?Y\n                                                      |- _ => solve [ inversion Hp; constructor; auto ]\nend.\n\nTheorem preserve : forall t t' T, typed t T -> t --> t' -> typed t' T.\n  intros t t' T t_typed t_process.\n  generalize dependent t'.\n  induction t_typed; intros t' t'_process; try solve_by_invert; try find_process; auto.\n  - (* T_If *)\n    inversion t'_process; try (rewrite <- H3; assumption).\n    specialize (IHt_typed1 t'0).\n    specialize (IHt_typed1 H3).\n    apply (T_If t'0 t1 t2 T IHt_typed1 t_typed2 t_typed3).\n  - (* T_Pred *)\n    inversion t'_process; try constructor.\n    + specialize (IHt_typed t'0). (* E_Pred *)\n      specialize (IHt_typed H0). auto.\n    +apply (numericval_nat t' H0). (* E_PredSucc *)\nQed.\n\nTheorem preserve' : forall t t' T, typed t T -> t --> t' -> typed t' T.\n  Hint Resolve numericval_nat.\n  intros t t' T t_typed t_process.\n  generalize dependent T.\n  induction t_process; intros T t_typed; inversion t_typed; try constructor; auto.\nQed.\n", "meta": {"author": "daichimukai", "repo": "tapl-rs", "sha": "dd9c72b1a277c1c926b65b60556d3ffe2eea080e", "save_path": "github-repos/coq/daichimukai-tapl-rs", "path": "github-repos/coq/daichimukai-tapl-rs/tapl-rs-dd9c72b1a277c1c926b65b60556d3ffe2eea080e/coq/arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7152318130219111}}
{"text": "Require Import String.\nRequire Import List.\nRequire Import PeanoNat.\nFrom mathcomp Require Import all_ssreflect.\n\n(* length and app *)\n\nLemma length_app {A : Type}:\n    forall l1 l2 : list A,\n        length (l1 ++ l2) = length l1 + length l2.\nProof.\n    move=> l1 l2; induction l1 as [|hd l1 HRec]; simpl.\n    {\n        rewrite add0n; trivial.\n    }\n    {\n        rewrite addSn.\n        rewrite HRec; reflexivity.\n    }\nQed.\n\nLemma length_app_eq {A : Type}:\n    forall l1 l2 : list A,\n    forall i1 i2,\n        length l1 = i1 -> length (l1 ++ l2) = i1 + i2 -> length l2 = i2.\nProof.\n    move=> l1 l2; induction l1 as [|hd l1 HRec]; simpl.\n    all: move=> i1 i2 <-.\n    {\n        rewrite add0n; trivial.\n    }\n    {\n        rewrite addSn.\n        move=> HEq; inversion HEq.\n        refine (HRec _ _ _ _).\n        + reflexivity.\n        + assumption.\n    }\nQed.\n\nLemma case_last {A : Type}: forall l : list A, {l = nil} + {exists l' last, l = l' ++ last::nil}.\nProof.\n    induction l as [|hd tl HRec]; simpl; auto.\n    right.\n    destruct HRec as [->|[l' [last' ->]]].\n    {\n        exists nil; exists hd; simpl; reflexivity.\n    }\n    {\n        exists (hd::l'); exists last'; simpl; reflexivity.\n    }\nQed.\n\n\nLemma Forall_length_1_concat {A : Type}:\n    forall l : list (list A),\n        Forall (fun l2 => length l2 = 1) l -> length (concat l) = length l.\nProof.\n    move=> l; induction l as [|hd l HRec]; simpl; trivial.\n    move=> HForall.\n    rewrite length_app.\n    rewrite HRec.\n    + apply Forall_inv in HForall; rewrite HForall; rewrite add1n; reflexivity.\n    + apply Forall_inv_tail in HForall; assumption.\nQed.\n\nLemma leb_add_1_l:\n    forall n, n + 1 <=? n  = false.\nProof.\n    induction n; simpl; auto.\nQed.\n\nLemma String_append_length:\n    forall (s1 s2 : string),\n        String.length (s1 ++ s2)%string = String.length s1 + String.length s2.\nProof.\n    intros s1 s2; induction s1; simpl.\n    + reflexivity.\n    + rewrite IHs1; reflexivity.\nQed.\n\n(* list map is ss_reflect map *)\nTheorem list_map_seq_map {A B : Type} (f : A -> B):\n    forall l, List.map f l = [seq f i | i <- l].\nProof.\n    move=> l; induction l as [|hd tl HRec]; simpl; trivial.\nQed.\n", "meta": {"author": "samsa1", "repo": "usuba_coq", "sha": "330d365e74fef62b90ff20244d160f0bcbbf4234", "save_path": "github-repos/coq/samsa1-usuba_coq", "path": "github-repos/coq/samsa1-usuba_coq/usuba_coq-330d365e74fef62b90ff20244d160f0bcbbf4234/src/coq_missing_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7152317941431686}}
{"text": "Require Export Ensemble.\n\n(* Section 3.1 *)\nDefinition Topology X cT := cT ⊂ cP(X) ∧\n  X ∈ cT ∧ ∅ ∈ cT ∧ (∀ A B, A ∈ cT → B ∈ cT → A ∩ B ∈ cT) ∧\n  (∀ cT1, cT1 ⊂ cT → ∪cT1 ∈ cT).\n\nDefinition Ordinary X := [X] ⋃ [∅].\n\nTheorem Theorem3_1 : ∀ X, Ensemble X → Topology X (Ordinary X).\nProof with eauto.\n  intros * Hxe. pose proof EmptySet as Hee. repeat split...\n  - intros A Ha. apply ClaI; Ens. apply UnionIE in Ha as [];\n    apply SingE in H; subst... intros x... intros z Hz; exfalso0.\n  - apply UnionIE. left; apply ClaI...\n  - apply UnionIE. right; apply ClaI...\n  - unfold Ordinary. intros. apply IntSinEm...\n  - intros. unfold Ordinary. apply EleUSinEm...\nQed.\n\nDefinition Discrete X := cP(X).\n\nTheorem Theorem3_2 : ∀ X, Ensemble X → Topology X (Discrete X).\nProof with eauto.\n  intros. repeat split. intros A Ha... apply ClaI... intros A...\n  apply ClaI. Empt. intros A Ha; exfalso0.\n  intros * Ha Hb. apply ClaE in Ha as []; apply ClaE in Hb as [].\n  apply ClaI. apply InterEn... intros z Hz.\n  apply InterIE in Hz as []... intros. apply ClaI. apply EleUAx.\n  apply PowerP in H as []. unfold Discrete in H0. eapply SubAxI...\n  intros x Hx. apply ClaE in Hx as [Hxe [A [Hx Ha]]].\n  apply H0 in Ha. apply ClaE in Ha as []...\nQed.\n\n(* Section 3.2 *)\nDefinition TNeigh x U X cT := Topology X cT ∧ x ∈ X ∧ U ⊂ X ∧\n  ∃ V, V ∈ cT ∧ x ∈ V ∧ V ⊂ U.\n\nCorollary TNeighP : ∀ x U X cT, Ensemble X →\n  Topology X cT → x ∈ U → U ∈ cT → TNeigh x U X cT.\nProof with eauto.\n  intros * Hxe Ht Hx Hu. split... assert (Hxx : U ⊂ X).\n  { apply Ht in Hu. apply PowerIE in Hu... } split... split...\n  exists U. repeat split... intros z...\nQed.\n\nDefinition TNeighS x X cT := \\{λ U, TNeigh x U X cT \\}.\n\nFact TNeighSIE : ∀ x U X cT,\n  Ensemble X → TNeigh x U X cT ↔ U ∈ TNeighS x X cT.\nProof.\n  split; intros. apply ClaI; auto. eapply SubAxI; eauto. apply H0.\n  apply ClaE in H0. tauto.\nQed.\n\nDefinition TONeigh x U X cT := TNeigh x U X cT ∧ x ∈ U ∧ U ∈ cT.\n\nCorollary TNeighP1 : ∀ x U X cT, Ensemble X → TNeigh x U X cT →\n  ∃ V, TONeigh x V X cT ∧ V ⊂ U.\nProof.\n  intros * Hxe [Ht [_ [Hv [V [Hvo [Hxv Huv]]]]]].\n  exists V. split; auto. split. apply TNeighP; auto. tauto.\nQed.\n\n(* Theorem3_3 *)\nLemma LeTh3_3 : ∀ U, U = ∪(\\{λ t, ∃ x, x ∈ U ∧ t = [x]\\}).\nProof with eauto.\n  intro. AppE. apply EleUIE. exists [x]. split. apply SingI. Ens.\n  apply ClaI. apply SingEn. Ens. exists x. split...\n  apply EleUIE in H as [y [Hy Heq]].\n  apply ClaE in Heq as [_ [z [Hz Heq]]].\n  subst. apply SingE in Hy. subst... Ens.\nQed.\n\nDefinition Ux x U cT := ∪\\{λ V, x ∈ U ∧ V ∈ cT ∧ x ∈ V ∧ V ⊂ U \\}.\n\nTheorem Theorem3_3 : ∀ U X cT, Ensemble X → Topology X cT → U ⊂ X →\n  (U ∈ cT ↔ ∀ x, x ∈ U → U ∈ TNeighS x X cT).\nProof with eauto.\n  intros * Hxe Ht Hsub. split; intros Hp.\n  - intros * Hx. apply TNeighSIE... apply TNeighP...\n  - destruct (classic (U = ∅)). subst; apply Ht.\n    assert (H1 : ∪(\\{λ t, ∃ x, x ∈ U ∧ t = [x]\\}) ⊂\n       ∪(\\{λ t, ∃ x, x ∈ U ∧ t = Ux x U cT\\})).\n    { intros z Hz. apply EleUIE in Hz as [y [Hy Hz]].\n      apply ClaE in Hz as [_ [x0 [Hx0 Hz]]]. subst...\n      apply SingE in Hy; Ens. subst. assert (Hx0' := Hx0).\n      apply Hp in Hx0. apply TNeighSIE in Hx0... apply EleUIE. \n      exists (Ux x0 U cT). split. apply EleUIE. assert (Hn := Hx0).\n      destruct Hx0 as [_ [_ [_ [V [Hv [Hx0 Hvu]]]]]].\n      exists V. split... apply ClaI; Ens. apply ClaI...\n      apply (SubAxI U). apply (SubAxI X)... intros z Hz.\n      apply EleUIE in Hz as [A [Ha Hz]].\n      apply ClaE in Hz as [_ [_ [_ [_ Hz]]]]... }\n    assert (H2 : ∪(\\{λ t, ∃ x, x ∈ U ∧ t = Ux x U cT\\}) ⊂ U).\n    { intros z Hz. apply EleUIE in Hz as [y [Hy Hz]].\n      apply ClaE in Hz as [_ [t [Htu Hz]]]. subst... apply EleUIE in\n        Hy as [e [Hz Hy]]. apply ClaE in Hy. apply Hy... }\n    assert (Hg : U = ∪(\\{λ t, ∃ x, x ∈ U ∧ t = Ux x U cT\\})).\n    { apply ReSyTrP... rewrite <- LeTh3_3 in H1... }\n    rewrite Hg. apply Ht. intros V Hv.\n    apply ClaE in Hv as [_ [x [Hx Heq]]]. subst.\n    apply Ht. intros z Hz. apply ClaE in Hz; tauto.\nQed.\n\n(* Theorem3_4 *)\nTheorem Theorem3_4a : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →\n  TNeighS x X cT ≠ ∅ ∧ (∀ U, U ∈ TNeighS x X cT → x ∈ U).\nProof with eauto.\n  intros * Hxe Ht Hx. split.\n  - assert (X ∈ TNeighS x X cT).\n    { apply ClaI... split... split... split. intros z...\n      exists X. split. apply Ht. split... intros z... }\n    intro. rewrite H0 in H. exfalso0.\n  - intros * Hu. apply TNeighSIE in Hu as [_[_[_[V [_[Hv Hsub]]]]]]...\nQed.\n\nTheorem Theorem3_4b : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →\n  (∀ U V, U ∈ TNeighS x X cT → V ∈ TNeighS x X cT →\n  U ∩ V ∈ TNeighS x X cT).\nProof with eauto.\n  intros * Hxe Ht Hx * Hu Hv.\n  apply TNeighSIE in Hu as [_ [_ [Hux [U0 [Ho1 [Hu0 Hsub1]]]]]]...\n  apply TNeighSIE in Hv as [_ [_ [Hvx [V0 [Ho2 [Hv0 Hsub2]]]]]]...\n  assert (Huv : x ∈ U0 ∩ V0 ∧ U0 ∩ V0 ⊂ U ∩ V).\n  { split. apply InterIE. tauto. intros z Hz.\n    apply InterIE in Hz as [Hzu Hzv]. apply InterIE. split... }\n  apply TNeighSIE... split... split... split. intros z Hz.\n  apply InterIE in Hz as [Hz1 _]... exists (U0 ∩ V0).\n  split; try apply Ht...\nQed.\n\nTheorem Theorem3_4c : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →\n  ∀ U V, U ∈ TNeighS x X cT → V ⊂ X → U ⊂ V → V ∈ TNeighS x X cT.\nProof with eauto.\n  intros * Hxe Ht Hx * Hu Hv Hsub.\n  apply TNeighSIE in Hu as [_ [_ [Hux [U0 [Hou [Hu0 Hsub1]]]]]]...\n  apply TNeighSIE... split... split... split...\n  exists U0. repeat split... eapply ReSyTrP...\nQed.\n\nTheorem Theorem3_4d : ∀ x X cT, Ensemble X → Topology X cT → x ∈ X →\n  ∀ U, U ∈ TNeighS x X cT → ∃ V, V ∈ TNeighS x X cT ∧ V ⊂ U ∧\n  (∀ y, y ∈ V → V ∈ TNeighS y X cT).\nProof with eauto.\n  intros * Hxe Ht Hx * Hu. assert (Hu' := Hu).\n  apply TNeighSIE in Hu as [_ [_ [Hux [V [Hvo [Hvx Hsub]]]]]]...\n  exists V. split. apply TNeighSIE... split... split... split.\n  eapply ReSyTrP... exists V. split... split... intros z...\n  split... apply Theorem3_3... eapply ReSyTrP...\nQed.\n\n(* Section 3.3 *)\nDefinition Condensa x A X cT := Topology X cT ∧ A ⊂ X ∧ x ∈ X ∧\n  ∀ U, TNeigh x U X cT → U ∩ (A - [x]) ≠ ∅.\n\nDefinition Derivaed A X cT := \\{λ x, Condensa x A X cT \\}.\n\nFact DerivaedIE : ∀ x A X cT, Condensa x A X cT ↔ x ∈ Derivaed A X cT.\nProof.\n  split; intros. apply ClaI; auto. destruct H as [_ [_ [Hx _]]]. Ens.\n  apply ClaE in H. tauto.\nQed.\n\nCorollary DerivaedP : ∀ A X cT, Derivaed A X cT ⊂ X.\nProof. intros * x Hx. apply ClaE in Hx. apply Hx. Qed.\n\nCorollary DerivaedP1 : ∀ x C X cT, Topology X cT → C ⊂ X → x ∈ X →\n  x ∉ Derivaed C X cT → ∃ U, TNeigh x U X cT ∧ U ∩ (C - [x]) = ∅.\nProof with eauto.\n  intros * Ht Hsub Hx Hp.\n  destruct (classic (∃ U, TNeigh x U X cT ∧ U ∩ (C - [x]) = ∅))...\n  elim Hp. apply ClaI. Ens. split... split... split...\nQed.\n\n(* Theorem3_5 *)\nTheorem Theorem3_5a : ∀ X cT,\n  Ensemble X → Topology X cT → Derivaed ∅ X cT = ∅.\nProof with eauto.\n  intros * Hxe Ht. AppE; [|exfalso0].\n  apply DerivaedIE in H as [_ [_ [Hx Hp]]]. eapply TNeighP in Ht...\n  apply Hp in Ht. elim Ht. AppE; [|exfalso0]. apply InterIE in H as\n    [_ H]. apply SetminIE in H as []; tauto. apply Ht.\nQed.\n\nTheorem Theorem3_5b : ∀ A B X cT, Ensemble X → Topology X cT →\n  A ⊂ X → B ⊂ X → A ⊂ B → Derivaed A X cT ⊂ Derivaed B X cT.\nProof with eauto.\n  intros * HXe Ht Ha Hb Hsub. intros x Hx.\n  apply DerivaedIE in Hx as [_ [_ [Hx Hp]]]. apply DerivaedIE.\n  split... split... split... intros U Hu. apply Hp in Hu.\n  assert (U ∩ A - [x] ⊂ U ∩ B - [x]).\n  { intros z Hz. apply InterIE in Hz as [Hz Hza].\n    apply SetminIE in Hza as [Hza Hneq]. apply InterIE. split...\n    apply SetminIE. split... }\n  intro. rewrite H0 in H. assert (U ∩ A - [x] = ∅).\n  { apply ReSyTrP... intros z Hz. exfalso0. } tauto.\nQed.\n\nTheorem Theorem3_5c : ∀ A B X cT,\n  Ensemble X → Topology X cT → A ⊂ X → B ⊂ X →\n  Derivaed (A ⋃ B) X cT = Derivaed A X cT ⋃ Derivaed B X cT.\nProof with eauto.\n  intros * HXe Ht Ha Hb. assert (A ⊂ A ⋃ B ∧ B ⊂ A ⋃ B).\n  { split; intros x Hx; apply UnionIE... }\n  destruct H as [Hsa Hsb]. assert (A ⋃ B ⊂ X).\n  { intros z Hz. apply UnionIE in Hz as []... }\n  eapply Theorem3_5b in Hsa... eapply Theorem3_5b in Hsb...\n  AppE; revgoals. apply UnionIE in H0 as []...\n  destruct (classic (x ∈ Derivaed A X cT ⋃ Derivaed B X cT))...\n  assert (Hab : x ∉ Derivaed A X cT ∧ x ∉ Derivaed B X cT).\n  { split; intro; elim H1; apply UnionIE... }\n  clear H1; destruct Hab as [Hna Hnb]. assert (H0' := H0).\n  apply DerivaedIE in H0' as [_ [_ [Hx _]]].\n  apply DerivaedP1 in Hna as [U [Hun Hue]]...\n  apply DerivaedP1 in Hnb as [V [Hvn Hve]]...\n  set (U ∩ V) as D. assert (Hd : D ∩ ((A ⋃ B) - [x]) = ∅).\n  { assert (H1 : D ∩ ((A ⋃ B) - [x]) = D ∩ ((A - [x]) ⋃ (B - [x]))).\n    { assert ((A ⋃ B) - [x] = A - [x] ⋃ B - [x]).\n      { AppE. apply SetminIE in H1 as [Hab H1].\n        apply UnionIE in Hab as []; apply UnionIE.\n        left; apply SetminIE... right; apply SetminIE...\n        apply UnionIE in H1 as []; apply SetminIE in H1 as [H1 He];\n        apply ClaI; Ens; split; auto; apply ClaI; Ens. }\n      rewrite H1... }\n    assert (H2 : D ∩ (A - [x] ⋃ B - [x]) =\n      (D ∩ (A - [x])) ⋃ (D ∩ (B - [x]))).\n    { apply DistribuLI... }\n    assert (H3 : (D ∩ (A - [x])) ⋃ (D ∩ (B - [x])) ⊂\n      (U ∩ (A - [x])) ⋃ (V ∩ (B - [x]))).\n    { intros z Hz. apply UnionIE in Hz as []; apply UnionIE;\n      apply InterIE in H3 as [H3 Hz]; apply InterIE in H3 as [Hu Hv].\n      left; apply InterIE... right; apply InterIE... }\n    assert (H4 : (U ∩ (A - [x])) ⋃ (V ∩ (B - [x])) = ∅).\n    { rewrite Hue, Hve. AppE.\n      apply UnionIE in H4 as []; exfalso0. exfalso0. }\n    rewrite H1, H2. rewrite H4 in H3. apply ReSyTrP...\n     intros z Hz; exfalso0. }\n  assert (x ∉ Derivaed (A ⋃ B) X cT).\n  { apply DerivaedIE in H0 as [_ [_ H0]]. assert (D ∈ TNeighS x X cT).\n    { apply Theorem3_4b; try (apply ClaI); eauto; apply (SubAxI X _)...\n      apply Hun. apply Hvn. }\n    apply TNeighSIE in H1... apply H0 in H1; tauto. } tauto.\nQed.\n\nTheorem Theorem2_4_1d : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Derivaed (Derivaed A X cT) X cT ⊂ A ⋃ Derivaed A X cT.\nProof with eauto.\n  intros * HXe Ht Hsub x Hx.\n  destruct (classic (x ∈ A ⋃ Derivaed A X cT))...\n  apply UnionNE in H as [Hxa Hxd]. assert (Hx' := Hx).\n  apply DerivaedIE in Hx as [_ [_ [Hx _]]].\n  apply DerivaedP1 in Hxd as [U [Hun Hue]]...\n  assert (U ∈ TNeighS x X cT). apply TNeighSIE...\n  pose proof Theorem3_4d x X cT HXe Ht Hx as Hu.\n  apply Hu in H as [V [Htv [Hvu Hp]]]; clear Hu. assert (V ⊂ X).\n  { destruct Hun as [_ [_ [Hun _]]]. eapply ReSyTrP... }\n  pose proof Theorem3_3 _ _ _ HXe Ht H.\n  pose proof Hp as Hp'. apply H0 in Hp; clear H H0.\n  assert (V ∩ A - [x] = ∅).\n  { AppE; [| exfalso0]. assert (V ∩ A - [x] ⊂ U ∩ A - [x]).\n    { intros z Hz. apply InterIE in Hz as []. apply InterIE. split... }\n    apply H0 in H. rewrite Hue in H. exfalso0. }\n  assert (V ∩ A = ∅). { apply (InterEqEmI x V A); Ens. }\n  assert (∀ y, y ∈ V → y ∉ A).\n  { intros * Hy Hn. assert (y ∈ V ∩ A). apply InterIE...\n    rewrite H0 in H1... exfalso0. }\n  assert (∀ y, y ∈ V → V ∩ A - [y] = ∅).\n  { intros. AppE; [| exfalso0]. apply InterIE in H3 as [].\n    apply SetminIE in H4 as []. apply H1 in H3... tauto. }\n  assert (∀ y, y ∈ V → y ∉ Derivaed A X cT).\n  { intros. intro. apply DerivaedIE in H4 as [_ [_ [_ H4]]].\n    pose proof H3. apply H2 in H3. apply Hp' in H5.\n    apply TNeighSIE in H5... apply H4 in H5. tauto. }\n  assert (V ∩ Derivaed A X cT - [x] = ∅).\n  { AppE; [| exfalso0]. apply InterIE in H4 as [].\n    apply H3 in H4. apply SetminIE in H5 as []. tauto. }\n  apply DerivaedIE in Hx' as [_ [_ [_ Hx']]]. apply TNeighSIE in Htv...\n  apply Hx' in Htv. tauto.\nQed.\n\n(* Section 3.4 *)\nDefinition Closed A X cT :=\n  Topology X cT ∧ A ⊂ X ∧ Derivaed A X cT ⊂ A.\n\n(* Theorem3_6 *)\nTheorem Theorem3_6 : ∀ A X cT, Ensemble X → Topology X cT → A ⊂ X →\n  Closed A X cT ↔ X - A ∈ cT.\nProof with eauto.\n  intros * HXe Ht Hsub. pose proof (IncludP2 A X) as Hsub'.\n  split; intros Hp.\n  - destruct Hp as [_ [_ Hp]]. eapply Theorem3_3...\n    intros * Hx. apply SetminIE in Hx as [Hx Hn].\n    assert (x ∉ Derivaed A X cT). { intro. apply Hp in H; tauto. }\n    apply DerivaedP1 in H as\n      [U [[_ [_ [Hus [V [Hvo [Hvx Hvu]]]]]] Hue]]...\n    apply (InterEqEmI x _ _) in Hue; Ens. assert (U ⊂ X - A).\n    { intros z Hz. apply SetminIE. split... intro.\n      assert (z ∈ U ∩ A). apply InterIE...\n      rewrite Hue in H0. exfalso0. }\n    apply TNeighSIE... split... split... split...\n    exists V. split... split... eapply ReSyTrP...\n  - assert (∀ x, x ∈ X-A → TNeigh x (X-A) X cT ∧ x ∉ Derivaed A X cT).\n    { intros x Hx. apply (Theorem3_3 (X-A) _ _) in Ht...\n      eapply Ht in Hp... apply TNeighSIE in Hp... split...\n      intro. apply ClaE in H as [_ [_ [_ [_ H0]]]]. apply H0 in Hp.\n      assert (X - A ∩ A - [x] = ∅).\n      { AppE; [| exfalso0]. apply InterIE in H as [Hn H].\n        apply SetminIE in Hn. apply SetminIE in H; tauto. } tauto. }\n    split... split... intros x Hx. destruct (classic (x ∈ A))...\n    assert (x ∈ X - A). { apply DerivaedIE in Hx as [_ [_ [Hx _]]].\n      apply SetminIE... } apply H in H1 as [_ H1]; tauto.\nQed.\n\n(* Theorem3_7 *)\nDefinition cF X cT := \\{λ U, U ⊂ X ∧ X - U ∈ cT \\}.\n\nFact cFIE : ∀ U X cT, Ensemble X → U ⊂ X ∧ X - U ∈ cT ↔ U ∈ cF X cT.\nProof.\n  split; intros. apply ClaI; auto. apply (SubAxI X U); tauto.\n  apply ClaE in H0. tauto.\nQed.\n\nCorollary cFP : ∀ X cT, Ensemble X → cF X cT ⊂ cP(X).\nProof.\n  intros * HXe U Hu. apply ClaE in Hu. apply PowerIE; tauto.\nQed.\n\nTheorem Theorem3_7a : ∀ X cT, Ensemble X → Topology X cT →\n  X ∈ cF X cT ∧ ∅ ∈ cF X cT.\nProof with eauto.\n  intros * Hxe Ht. split.\n  - apply cFIE... split. intros z... rewrite SetminId. apply Ht.\n  - apply ClaI. Empt. split. intros z Hz; exfalso0.\n    rewrite SetminEm. apply Ht.\nQed.\n\nTheorem Theorem3_7b : ∀ A B X cT, Ensemble X → Topology X cT →\n  A ∈ cF X cT → B ∈ cF X cT → A ⋃ B ∈ cF X cT.\nProof with eauto.\n  intros * He Ht Ha Hb. apply cFIE in Ha as [Ha Hac]...\n  apply cFIE in Hb as [Hb Hbc]... assert (X - A ∩ X - B ∈ cT).\n  apply Ht... apply TwSetmin in Ha. apply TwSetmin in Hb.\n  rewrite <- Ha, <- Hb.\n  assert (X - (X - A) ⋃ X - (X - B) = X - (X - A ∩ X - B)).\n  { AppE. rewrite TwDeMorgan; apply UnionIE;\n    apply UnionIE in H0 as []... rewrite TwDeMorgan in H0... }\n  rewrite H0. apply (cFIE _ X cT)... split. apply IncludP2.\n  rewrite TwSetmin... intros z Hz. apply InterIE in Hz as [_ Hz].\n  apply SetminIE in Hz; tauto.\nQed.\n\nTheorem Theorem3_7c : ∀ cF1 X cT, Ensemble X →\n  Topology X cT → cF1 ≠ ∅ → cF1 ⊂ cF X cT → ⋂cF1 ∈ cF X cT.\nProof with eauto.\n  intros cF1 * HXe Ht Hne Hsub.\n  set \\{λ A, A ⊂ X ∧ X - A ∈ cF1 \\} as cT1. assert (HcT : cT1 ⊂ cT).\n  { intros A Ha. apply ClaE in Ha as [_ [Hsa Ha]]. apply Hsub in Ha.\n    apply cFIE in Ha as [Hc Ha]... rewrite TwSetmin in Ha... }\n  apply Ht in HcT. assert (H4 : (X - ∪cT1) ∈ cF X cT).\n  { apply (cFIE _ X cT)... split. apply IncludP2.\n    rewrite TwSetmin... apply Ht in HcT. apply PowerIE in HcT... }\n  assert (H3 : (X - ∪(AAr X cF1)) = (X - ∪cT1)).\n  { AppE; apply SetminIE in H as [Hx Hn]; apply SetminIE; split...\n    - intro. elim Hn. apply EleUIE in H as [B [Hb Hbt]].\n      apply ClaE in Hbt as [_ [Hbs Hb']]. apply EleUIE.\n      exists (X - (X - B)). split. rewrite TwSetmin... apply AArI...\n    - intro. elim Hn; clear Hn. apply EleUIE in H as [B [Hb Hbt]].\n      pose proof Hbt. apply AArE in Hbt as [T [Hbt Heq]].\n      apply EleUIE. exists B. split... apply ClaI... Ens. split; subst.\n      apply IncludP2. rewrite TwSetmin... apply Hsub in Hbt.\n      apply ClaE in Hbt; tauto. }\n  rewrite DeMorganUI in H3; try apply AArP...\n  assert (⋂ cF1 = ⋂ AAr X (AAr X cF1)).\n  { AppE; apply ClaE in H as []; apply ClaI; auto; intros.\n    - apply ClaE in H1 as [_ [B [Hb Heq]]]. apply ClaE in Hb as\n        [_ [C [Hc Heq1]]]. apply H0. subst. rewrite TwSetmin...\n      apply Hsub in Hc. apply ClaE in Hc; tauto.\n    - assert (y ⊂ X). { apply Hsub in H1. apply ClaE in H1; tauto. }\n      apply H0. apply ClaI. Ens. exists (X - y). split.\n      apply (AArI X _  cF1)... rewrite TwSetmin... } rewrite H, H3...\nQed.\n", "meta": {"author": "BalanceYan", "repo": "CT.Yang", "sha": "26f594a126750eb07f44e524c5ff6375f313882a", "save_path": "github-repos/coq/BalanceYan-CT.Yang", "path": "github-repos/coq/BalanceYan-CT.Yang/CT.Yang-26f594a126750eb07f44e524c5ff6375f313882a/Topology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7152317906207301}}
{"text": "From Coq Require Import Arith.\nRequire Import Arith.\n\nRequire Import Psatz.\n\nFixpoint div2 (n : nat) : nat :=\n  match n with\n    | 0 => 0\n    | 1 => 0\n    | S (S m) => S (div2 m)\n  end.\n\nTheorem div2_n: forall n k, div2 (2 * n + k) = n + div2 (k).\nProof.\n  intros.\n  induction n.\n  - reflexivity.\n  - rewrite Nat.mul_comm.\n    simpl.\n    rewrite Nat.mul_comm.\n    rewrite IHn.\n    reflexivity.\nQed.\n\n\nFixpoint arith_sum (n : nat) : nat :=\n  match n with\n  | 0 => 0\n  | S m => n + arith_sum m\n  end.\n\nDefinition arith_formula2 (n : nat) : nat := div2 (n * (n + 1)).\n\n\nDefinition arith_formula (n : nat) : nat := div2 (n * (n + 1)).\n\nTheorem arith_eq (n : nat) : arith_formula n = arith_sum n.\nProof.\n  intros.\n  induction n.\n    compute.\n    reflexivity.\n    unfold arith_formula.\n    simpl arith_sum.\n    rewrite <- IHn.\n    simpl Nat.add.\n    simpl Nat.mul.\n    rewrite Nat.mul_comm.\n    simpl Nat.mul.\n    rewrite Nat.mul_comm.\n    rewrite Nat.add_assoc.\n    rewrite (Nat.add_comm n 1).\n    simpl Nat.add.\n    simpl div2.\n    f_equal.\n    unfold arith_formula.\n    assert (forall x y : nat, div2 (x + x + y) = x + div2 (y)).\n      intros x y.\n      induction x.\n        simpl.\n        reflexivity.\n        simpl Nat.add.\n        rewrite (Nat.add_comm x (S x)).\n        simpl Nat.add.\n        simpl div2.\n        f_equal.\n        assumption.\n    rewrite H.\n    f_equal.\n    f_equal.\n    rewrite (Nat.add_comm n 1).\n    simpl Nat.add.\n    reflexivity.\n    Show Proof.\nQed.\n\nTheorem arith_eq2 : forall (n : nat), arith_formula n = arith_sum n.\nProof.\n  intros n.\n  induction n.\n    compute.\n    reflexivity.\n    simpl arith_sum.\n    rewrite <- IHn.\n    unfold arith_formula.\n    simpl Nat.mul.\n    rewrite (Nat.add_comm n 1).\n    simpl Nat.add.\n    simpl div2.\n    f_equal.\n    rewrite Nat.mul_comm.\n    simpl Nat.mul.\n    rewrite Nat.add_assoc.\n    assert (forall x y : nat, div2 (x + x + y) = x + div2 y).\n      intros x y.\n      induction x.\n      simpl.\n      reflexivity.\n      simpl Nat.add.\n      rewrite (Nat.add_comm x (S x)).\n      simpl Nat.add.\n      simpl div2.\n      f_equal.\n      assumption.\n    rewrite H.\n    f_equal. f_equal.\n    rewrite (Nat.mul_comm n (S n)).\n    simpl Nat.mul.\n    reflexivity.\n    Show Proof.\nQed.\n\nTheorem arith_eq3 : forall (n : nat), arith_formula n = arith_sum n.\nProof.\n  intros n.\n  induction n.\n  - compute.\n    reflexivity.\n  - simpl.\n    rewrite <- IHn.\n    unfold arith_formula.\n    rewrite Nat.add_comm.\n    simpl.\n    rewrite Nat.mul_comm.\n    simpl.\n    pose proof div2_n n.\n    simpl \"*\" in H.\n    rewrite Nat.add_0_r in H.\n    rewrite Nat.add_assoc.\n    rewrite (H (n + n * n)).\n    f_equal.\n    f_equal.\n    f_equal.\n    symmetry.\n    rewrite Nat.mul_comm.\n    rewrite Nat.add_comm.\n    simpl.\n    reflexivity.\nQed.\n(*\nTheorem div2_formula : forall (x : nat), exists (y : nat), 2 * y = x * (x + 1).\nProof.\n  intros x.\n  induction x.\n    exists 0.\n    simpl.\n    reflexivity.\n    simpl Nat.mul.\n    rewrite (Nat.add_comm x 1).\n    simpl Nat.add.\n    rewrite (Nat.mul_comm x (S (S x))).\n    simpl Nat.mul.\n    simpl Nat.add.\n    assert (p : nat).\n      trivial.\n    exists (x + (S p)).\n    simpl Nat.add.\n    rewrite Nat.add_comm.\n    rewrite (Nat.add_comm x (S p)).\n    simpl Nat.add.\n    rewrite Nat.add_comm.\n    simpl Nat.add.\n    f_equal.\n    f_equal.\n    rewrite (Nat.add_comm p x).\n    destruct IHx as [h H].\n    simpl Nat.mul in H.\n    rewrite (Nat.add_comm x 1) in H.\n    simpl Nat.mul in H.\n    rewrite Nat.mul_comm in H.\n    simpl in H .\n    rewrite <- H.\n    rewrite (Nat.add_comm h 0).\n    rewrite (Nat.add_comm).\n    rewrite (Nat.add_comm (x + p) 0).\n    simpl Nat.add.\n    repeat rewrite Nat.add_assoc.\n*)\n\n\nTheorem div2_formula : forall (x : nat), exists (y : nat), 2 * y = x * (x + 1).\nProof.\n  intros.\n  assert (forall a : nat, exists b : nat, (a = 2 * b) \\/ (S a = 2 * b)).\n    intros.\n    induction a.\n    simpl.\n    exists 0.\n    left.\n    simpl.\n    reflexivity.\n    destruct IHa as [b' H].\n    destruct H as [H | H].\n    exists (S b').\n    right.\n    rewrite (Nat.mul_comm).\n    simpl Nat.mul.\n    rewrite (Nat.mul_comm).\n    rewrite <- H.\n    reflexivity.\n    exists b'.\n    left.\n    assumption.\n  destruct (H x) as [b e].\n  destruct e as [e | e].\n    rewrite e.\n    exists (b * (2 * b + 1)).\n    rewrite Nat.mul_assoc.\n    reflexivity.\n    rewrite (Nat.add_comm).\n    simpl Nat.add.\n    rewrite e.\n    rewrite (Nat.mul_comm).\n    exists (b * x).\n    rewrite Nat.mul_assoc.\n    reflexivity.\n  Show Proof.\nQed.\n\nTheorem inducted_div2 (x y : nat) : div2 (2 * x + y) = x + div2 (y).\nProof.\n  induction x.\n    simpl.\n    reflexivity.\n    simpl Nat.add.\n    rewrite (Nat.add_comm x 0).\n    simpl Nat.add.\n    rewrite (Nat.add_comm x (S x)).\n    simpl Nat.add.\n    simpl div2.\n    f_equal.\n    assert (x + x = 2 * x).\n    simpl.\n    rewrite (Nat.add_comm x 0).\n    simpl.\n    reflexivity.\n    rewrite H.\n    assumption.\nQed.\n\nDefinition even n := exists y,     2 * y = n.\nDefinition odd  n := exists y, 1 + 2 * y = n.\n\nTheorem even_div2 (n : nat) : even n -> 2 * div2 n = n.\nProof.\n  intros.\n  unfold even in H.\n  destruct H.\n  rewrite <- H.\n  assert (2 * x = 2 * x + 0); auto.\n  rewrite H0 at 1.\n  rewrite (inducted_div2 x).\n  simpl div2.\n  simpl.\n  rewrite (Nat.add_comm x 0).\n  simpl.\n  rewrite (Nat.add_comm x 0).\n  simpl.\n  reflexivity.\nQed.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/arithsum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7151891666664142}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := mult y (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj196_coqofml_JMfN5r.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7151536776301719}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) : natural := mult z (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj286_coqofml_4wZeiw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7151536737657925}}
{"text": "(* Exercise 101b *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\n(* Double Contrapositive, give a constructive proof *)\n\nTheorem exercise_101b : (A -> B) -> (~~A -> ~~B).\nProof.\nimp_i a1.\nimp_i a2.\nneg_i B a3.\nhyp a3.\nimp_e A.\nhyp a1.\nneg_e' (~A) a4.\nhyp a2.\nhyp a4.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak10/Taak10_prop101b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7151003318236615}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus (Succ Zero) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj2510_coqofml_dDq1Lw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7151003244648785}}
{"text": "From Coq Require Import NArith Arith Lia List.\n\nLocal Open Scope list_scope.\n\nDefinition range (offset count: N)\n: list N\n:= let fix range' (countdown: nat)\n   := match countdown with\n      | O => nil\n      | S k => cons (offset + count - 1 - N.of_nat k)%N\n                    (range' k)\n      end\n   in range' (N.to_nat count).\n\nLocal Example range_example:\n  range 5 3 = (5 :: 6 :: 7 :: nil)%N.\nProof.\ntrivial.\nQed.\n\nDefinition range_nat (offset count: nat)\n: list N\n:= let fix range' (countdown: nat)\n   := match countdown with\n      | O => nil\n      | S k => cons (N.of_nat (offset + count - 1 - k))\n                    (range' k)\n      end\n   in range' count.\n\nLemma range_nat_ok (offset count: nat):\n  range_nat offset count = range (N.of_nat offset) (N.of_nat count).\nProof.\nunfold range, range_nat.\nrewrite Nat2N.id.\nrevert offset. induction count. { trivial. }\nintro offset. cbn.\nassert (IH := IHcount (S offset)). clear IHcount.\nf_equal. { f_equal. lia. }\nassert (EqLHS:\n          forall t,\n            (fix range' (countdown : nat) : list N :=\n             match countdown with\n             | 0 => nil\n             | S k => (N.of_nat (offset + S count - 1 - k)) :: range' k\n             end) t\n              =\n            (fix range' (countdown : nat) : list N :=\n             match countdown with\n             | 0 => nil\n             | S k => (N.of_nat (S offset + count - 1 - k)) :: range' k\n             end) t).\n{\n  clear IH. intro t.\n  revert offset. induction t. { easy. }\n  intro offset.\n  f_equal. 2:apply IHt.\n  f_equal. f_equal. lia.\n}\nrewrite EqLHS. clear EqLHS.\nassert (EqRHS:\n          forall t,\n            (fix range' (countdown : nat) : list N :=\n             match countdown with\n             | 0 => nil\n             | S k =>\n                 (N.of_nat offset + N.pos (Pos.of_succ_nat count) - 1 - N.of_nat k)%N :: range' k\n             end) t\n              =\n            (fix range' (countdown : nat) : list N :=\n             match countdown with\n             | 0 => nil\n             | S k => (N.of_nat (S offset) + N.of_nat count - 1 - N.of_nat k)%N :: range' k\n             end) t).\n{\n  clear IH. intro t.\n  revert offset. induction t. { easy. }\n  intro offset.\n  f_equal. 2:apply IHt.\n  f_equal. f_equal. lia.\n}\nrewrite EqRHS. clear EqRHS.\napply IH.\nQed.\n\nLemma range_via_nat (offset count: N):\n  range offset count = range_nat (N.to_nat offset) (N.to_nat count).\nProof.\nrewrite range_nat_ok.\nnow repeat rewrite N2Nat.id.\nQed.\n\nLemma range_cons (offset count: N):\n  range offset (N.succ count) = offset :: range (N.succ offset) count.\nProof.\nrewrite range_via_nat.\nunfold range_nat.\nrevert offset. induction count; intros.\n{\n  cbn. replace (Pos.to_nat 1) with 1 by easy.\n  f_equal. lia.\n}\ncbn. rewrite Pnat.Pos2Nat.inj_succ.\nf_equal. { lia. }\nmatch goal with\n|- ?l _ = ?r _ =>\n        enough (forall x, l x = r x) by easy\nend.\nintro x. induction x. { trivial. }\nf_equal. { lia. }\napply IHx.\nQed.\n", "meta": {"author": "formalize", "repo": "coq-vyper", "sha": "8996c1534b9d56696f92b60031ff1523b3593690", "save_path": "github-repos/coq/formalize-coq-vyper", "path": "github-repos/coq/formalize-coq-vyper/coq-vyper-8996c1534b9d56696f92b60031ff1523b3593690/Range.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7150610065337458}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** * This module proves the validity of\n    - well-founded recursion (also known as course of values)\n    - well-founded induction\n    from a well-founded ordering on a given set *)\n\nSet Implicit Arguments.\n\nRequire Import Notations.\nRequire Import Logic.\nRequire Import Datatypes.\n\n(** Well-founded induction principle on [Prop] *)\n\nSection Well_founded.\n\n Variable A : Type.\n Variable R : A -> A -> Prop.\n\n (** The accessibility predicate is defined to be non-informative *)\n (** (Acc_rect is automatically defined because Acc is a singleton type) *)\n\n Inductive Acc (x: A) : Prop :=\n     Acc_intro : (forall y:A, R y x -> Acc y) -> Acc x.\n\n Lemma Acc_inv : forall x:A, Acc x -> forall y:A, R y x -> Acc y.\n  destruct 1; trivial.\n Defined.\n\n Global Arguments Acc_inv [x] _ [y] _, [x] _ y _.\n\n (** A relation is well-founded if every element is accessible *)\n\n Definition well_founded := forall a:A, Acc a.\n\n (** Well-founded induction on [Set] and [Prop] *)\n\n Hypothesis Rwf : well_founded.\n\n Theorem well_founded_induction_type :\n  forall P:A -> Type,\n    (forall x:A, (forall y:A, R y x -> P y) -> P x) -> forall a:A, P a.\n Proof.\n  intros; apply Acc_rect; auto.\n Defined.\n\n Theorem well_founded_induction :\n  forall P:A -> Set,\n    (forall x:A, (forall y:A, R y x -> P y) -> P x) -> forall a:A, P a.\n Proof.\n  exact (fun P:A -> Set => well_founded_induction_type P).\n Defined.\n\n Theorem well_founded_ind :\n  forall P:A -> Prop,\n    (forall x:A, (forall y:A, R y x -> P y) -> P x) -> forall a:A, P a.\n Proof.\n  exact (fun P:A -> Prop => well_founded_induction_type P).\n Defined.\n\n(** Well-founded fixpoints *)\n\n Section FixPoint.\n\n  Variable P : A -> Type.\n  Variable F : forall x:A, (forall y:A, R y x -> P y) -> P x.\n\n  Fixpoint Fix_F (x:A) (a:Acc x) : P x :=\n    F (fun (y:A) (h:R y x) => Fix_F (Acc_inv a h)).\n\n  Scheme Acc_inv_dep := Induction for Acc Sort Prop.\n\n  Lemma Fix_F_eq :\n   forall (x:A) (r:Acc x),\n     F (fun (y:A) (p:R y x) => Fix_F (x:=y) (Acc_inv r p)) = Fix_F (x:=x) r.\n  Proof.\n   destruct r using Acc_inv_dep; auto.\n  Qed.\n\n  Definition Fix (x:A) := Fix_F (Rwf x).\n\n  (** Proof that [well_founded_induction] satisfies the fixpoint equation.\n      It requires an extra property of the functional *)\n\n  Hypothesis\n    F_ext :\n      forall (x:A) (f g:forall y:A, R y x -> P y),\n        (forall (y:A) (p:R y x), f y p = g y p) -> F f = F g.\n\n  Lemma Fix_F_inv : forall (x:A) (r s:Acc x), Fix_F r = Fix_F s.\n  Proof.\n   intro x; induction (Rwf x); intros.\n   rewrite <- (Fix_F_eq r); rewrite <- (Fix_F_eq s); intros.\n   apply F_ext; auto.\n  Qed.\n\n  Lemma Fix_eq : forall x:A, Fix x = F (fun (y:A) (p:R y x) => Fix y).\n  Proof.\n   intro x; unfold Fix.\n   rewrite <- Fix_F_eq.\n   apply F_ext; intros.\n   apply Fix_F_inv.\n  Qed.\n\n End FixPoint.\n\nEnd Well_founded.\n\n(** Well-founded fixpoints over pairs *)\n\nSection Well_founded_2.\n\n  Variables A B : Type.\n  Variable R : A * B -> A * B -> Prop.\n\n  Variable P : A -> B -> Type.\n\n  Section FixPoint_2.\n\n  Variable\n    F :\n      forall (x:A) (x':B),\n        (forall (y:A) (y':B), R (y, y') (x, x') -> P y y') -> P x x'.\n\n  Fixpoint Fix_F_2 (x:A) (x':B) (a:Acc R (x, x')) : P x x' :=\n    F\n      (fun (y:A) (y':B) (h:R (y, y') (x, x')) =>\n         Fix_F_2 (x:=y) (x':=y') (Acc_inv a (y,y') h)).\n\n  End FixPoint_2.\n\n  Hypothesis Rwf : well_founded R.\n\n  Theorem well_founded_induction_type_2 :\n   (forall (x:A) (x':B),\n      (forall (y:A) (y':B), R (y, y') (x, x') -> P y y') -> P x x') ->\n   forall (a:A) (b:B), P a b.\n  Proof.\n   intros; apply Fix_F_2; auto.\n  Defined.\n\nEnd Well_founded_2.\n\nNotation Acc_iter   := Fix_F   (only parsing). (* compatibility *)\nNotation Acc_iter_2 := Fix_F_2 (only parsing). (* compatibility *)\n\n\n\n(* Added by Julien Forest on 13/11/20 *)\nSection Acc_generator.\n  Variable A : Type.\n  Variable R : A -> A -> Prop.\n\n  (* *Lazily* add 2^n - 1 Acc_intro on top of wf. \n     Needed for fast reductions using Function and Program Fixpoint \n     and probably using Fix and Fix_F_2 \n   *)    \n  Fixpoint Acc_intro_generator n (wf : well_founded R)  := \n    match n with \n        | O => wf\n        | S n => fun x => Acc_intro x (fun y _ => Acc_intro_generator n (Acc_intro_generator n wf) y)\n    end.\n\n\nEnd Acc_generator.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Init/Wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7150609939503643}}
{"text": "Theorem ex50: forall a b c : Prop,\n              (a -> b) -> ((b -> c) -> (a -> c)).\nProof.\n  intros. apply (H0 (H H1)).\nQed.\n\nTheorem ex50_1: forall a b c : Prop,\n                (a <-> b) -> ((b <-> c) -> (a <-> c)).\nProof.\n  Require Import Coq.Program.Basics.\n  intros. elim H. elim H0. intros. split.\n  apply (compose H1 H3). apply (compose H4 H2).\nQed.\n\nTheorem ex50_2: forall a b c : Prop,\n                (a -> b) -> ((c -> a) -> (c -> b)).\nProof.\n  intros. apply (H (H0 H1)).\nQed.\n\nTheorem ex51: forall a b c : Prop,\n              (a -> (b -> c)) <-> (b -> (a -> c)).\nProof.\n  split. intros. apply (H H1 H0). intros.\n  apply (H H1 H0).\nQed.\n\nTheorem ex52: forall a b c : Prop,\n              (a -> (b -> c)) <-> (a /\\ b -> c).\nProof.\n  split. intros. elim H0. assumption.\n  intros. apply H. split. assumption. assumption.\nQed.\n\nTheorem ex53: forall a b : Prop,\n              ~a -> (a -> b).\nProof.\n  intros. contradiction.\nQed.\n\nTheorem ex53_1: forall a b : Prop,\n                ((a -> b) -> a) -> a.\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. cut a. intro.\n  contradiction. apply H. intro. contradiction.\nQed.\n\nTheorem ex53_2: forall a b c : Prop,\n                (((a -> b) -> c) -> (a -> b)) -> (a -> b).\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro. apply H1.\n  apply H. intro. elim H1. cut b. intro.\n  contradiction. apply (H2 H0). assumption.\nQed.\n\nTheorem ex53_3: forall a b : Prop,\n                ((((a -> b) -> a) -> a) -> a) -> a.\nProof.\n  Require Import Classical.\n  intros. apply NNPP. intro.\n  apply H0. apply H. intro.\n  apply H1. intro. apply NNPP. intro.\n  apply H0. assumption.\nQed.\n\nTheorem ex53_4: forall a b : Prop,\n                ((((a -> b) -> a) -> a) -> b) -> b.\nProof.\n  Require Import Coq.Program.Basics.\n  intros. apply H. intros. apply H0. intro.\n  refine (apply H (fun H0 => H1)).\nQed.\n\nTheorem ex53_5: forall a b c : Prop,\n                ((((((a -> b) -> c) -> c) \n                 -> a) -> a) -> b) -> b.\nProof.\n  intros. apply H. intros. apply H0. intros.\n  apply H1. intros. apply H.\n  intros. assumption.\nQed.\n\nTheorem ex53_6: forall a b c d : Prop,\n                ((((((((a -> b) -> c) -> c) -> d)\n                    -> d) -> a) -> a) -> b) -> b.\nProof.\n  intros. apply H. intros. apply H0. intros.\n  apply H1. intros. apply H2. intros.\n  apply H. intros. assumption.\nQed.\n\nTheorem ex53_7: forall a b : Prop,\n                ((a -> b) -> b) -> ((b -> a) -> a).\nProof.\n  intros. apply NNPP. intro.\n  apply H1. apply H0. apply H. intro. contradiction.\nQed.", "meta": {"author": "limitedeternity", "repo": "PrPr-Labs", "sha": "0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62", "save_path": "github-repos/coq/limitedeternity-PrPr-Labs", "path": "github-repos/coq/limitedeternity-PrPr-Labs/PrPr-Labs-0c83eb2dbf0c8b15e558ed7586d5e39e18a51c62/PrPr-01/TypeTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7150609937097121}}
{"text": "(* This file is extracted from the TLC library.\n   http://github.com/charguer/tlc\n   DO NOT EDIT. *)\n\n(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Reflection between booleans and propositions                            *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom SLF Require Import LibTactics.\nFrom SLF Require Export LibBool LibLogic.\n\nImplicit Type P : Prop.\nImplicit Type b : bool.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Reflection between booleans and propositions *)\n\n(** - [istrue b] produces a proposition that is [True] if and only if\n      the boolean [b] is equal to [true].\n\n    - [isTrue P] produces a boolean expression that is [true] if and only\n      if the proposition [P] is equal to [True]. *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Translation from booleans into propositions *)\n\n(** Any boolean [b] can be viewed as a proposition through the\n    relation [b = true]. *)\n\nCoercion istrue (b : bool) : Prop := (b = true).\n\n(** Specification *)\n\nLemma istrue_eq_eq_true : forall b,\n  istrue b = (b = true).\nProof using. reflexivity. Qed.\n\nLemma istrue_true_eq :\n  istrue true = True.\nProof using. rewrite istrue_eq_eq_true. extens*. Qed.\n\nLemma istrue_false_eq :\n  istrue false = False.\nProof using. rewrite istrue_eq_eq_true. extens. iff; auto_false. Qed.\n\nGlobal Opaque istrue.\n\n(** Proving the goals [true] and [~ false] *)\n\nLemma istrue_true : istrue true. (* [true] *)\nProof using. reflexivity. Qed.\n\nLemma not_istrue_false : ~ (istrue false). (* ~ false. *)\nProof using. rewrite istrue_false_eq. intuition. Qed.\n\n(** Equivalence of [false] and [False] *)\n\nLemma false_of_False :\n  False ->\n  false.\nProof using. intros K. false. Qed.\n\nLemma False_of_false :\n  false ->\n  False.\nProof using. intros K. rewrite~ istrue_false_eq in K. Qed.\n\n(** Hints for proving [false] and [False] *)\n\nHint Resolve istrue_true not_istrue_false.\n\nHint Extern 1 (istrue false) =>\n  apply false_of_False.\n\nHint Extern 1 (False) => match goal with\n  | H: istrue false |- _ => apply (not_istrue_false H) end.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Translation from propositions into booleans *)\n\n(** The expression [isTrue P] evaluates to [true] if and only if\n    the proposition [P] is [True]. *)\n\nDefinition isTrue (P : Prop) : bool :=\n  If P then true else false.\n\n(** Specification *)\n\nLemma isTrue_eq_if : forall P,\n  isTrue P = If P then true else false.\nProof using. reflexivity. Qed.\n\nLemma isTrue_True :\n  isTrue True = true.\nProof using. unfolds. case_if; auto_false~. Qed.\n\nLemma isTrue_False :\n  isTrue False = false.\nProof using. unfolds. case_if; auto_false~. Qed.\n\nGlobal Opaque isTrue.\n\n(** Lemmas *)\n\nLemma isTrue_eq_true : forall P,\n  P ->\n  isTrue P = true.\nProof using. intros. rewrite isTrue_eq_if. case_if*. Qed.\n\nLemma isTrue_eq_false : forall P,\n  ~ P ->\n  isTrue P = false.\nProof using. intros. rewrite isTrue_eq_if. case_if*. Qed.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Extensionality for boolean equality, stated using [istrue] *)\n\nLemma bool_ext : forall b1 b2,\n  (b1 <-> b2) ->\n  b1 = b2.\nProof using.\n  destruct b1; destruct b2; intros; auto_false.\n  destruct H. false H; auto.\n  destruct H. false H0; auto.\nQed.\n\nLemma bool_ext_eq : forall b1 b2,\n  (b1 = b2) = (b1 <-> b2).\nProof using.\n  intros. extens. iff M. { subst*. } { applys* bool_ext. }\nQed.\n\nInstance Extensionality_bool : Extensionality bool.\nProof using. apply (Extensionality_make bool_ext). Defined.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Specification of boolean equality *)\n\nDefinition is_beq A (beq:A->A->bool) :=\n  forall x y, beq x y = isTrue (x = y).\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Rewriting rules *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Rewriting rules for distributing [istrue] *)\n\nLemma istrue_isTrue_eq : forall P,\n  istrue (isTrue P) = P.\nProof using. extens. rewrite isTrue_eq_if. case_if; auto_false*. Qed.\n\nLemma istrue_neg_eq : forall b,\n  istrue (!b) = ~ (istrue b).\nProof using. extens. tautob. Qed.\n\nLemma istrue_and_eq : forall b1 b2,\n  istrue (b1 && b2) = (istrue b1 /\\ istrue b2).\nProof using. extens. tautob. Qed.\n\nLemma istrue_or_eq : forall b1 b2,\n  istrue (b1 || b2) = (istrue b1 \\/ istrue b2).\nProof using. extens. tautob. Qed.\n\n(** Corollary *)\n\nLemma istrue_neg_isTrue : forall P,\n  istrue (! isTrue P) = ~ P.\nProof using. intros. rewrite istrue_neg_eq. rewrite~ istrue_isTrue_eq. Qed.\n\n(** [istrue] and conditionals *)\n\nLemma If_istrue : forall b A (x y : A),\n    (If istrue b then x else y)\n  = (if b then x else y).\nProof using. intros. case_if as C; case_if as D; auto. Qed.\n\nLemma istrue_If_eq : forall P b1 b2,\n    istrue (If P then b1 else b2)\n  = (If P then istrue b1 else istrue b2).\nProof using. extens. case_if*. Qed.\n\nLemma istrue_if_eq : forall b1 b2 b3,\n    istrue (if b1 then b2 else b3)\n  = (If istrue b1 then istrue b2 else istrue b3).\nProof using. intros. do 2 case_if; auto. Qed.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Rewriting rules for distributing [isTrue] *)\n\nLemma isTrue_istrue : forall b,\n  isTrue (istrue b) = b.\nProof using. extens. rewrite* istrue_isTrue_eq. Qed.\n\nLemma isTrue_not : forall P,\n  isTrue (~ P) = ! isTrue P.\nProof using. extens. do 2 rewrite isTrue_eq_if. do 2 case_if; auto_false*. Qed.\n\nLemma isTrue_and : forall P1 P2,\n  isTrue (P1 /\\ P2) = (isTrue P1 && isTrue P2).\nProof using. extens. do 3 rewrite isTrue_eq_if. do 3 case_if; auto_false*. Qed.\n\nLemma isTrue_or : forall P1 P2,\n  isTrue (P1 \\/ P2) = (isTrue P1 || isTrue P2).\nProof using. extens. do 3 rewrite isTrue_eq_if. do 3 case_if; auto_false*. Qed.\n\n(** Corollary *)\n\nLemma isTrue_not_istrue : forall b,\n  isTrue (~ istrue b) = !b.\nProof using. intros. rewrite isTrue_not. rewrite~ isTrue_istrue. Qed.\n\n(** Simplification of equalities involving isTrue *)\n\nSection IsTrueEqualities.\n\nLtac prove_isTrue_lemma :=\n  intros; try extens; try iff; rewrite isTrue_eq_if in *; case_if; auto_false*.\n\nLemma true_eq_isTrue_eq : forall P,\n  (true = isTrue P) = P.\nProof using. prove_isTrue_lemma. Qed.\n\nLemma isTrue_eq_true_eq : forall P,\n  (isTrue P = true) = P.\nProof using. prove_isTrue_lemma. Qed.\n\nLemma false_eq_isTrue_eq : forall P,\n  (false = isTrue P) = ~ P.\nProof using. prove_isTrue_lemma. Qed.\n\nLemma isTrue_eq_false_eq : forall P,\n  (isTrue P = false) = ~ P.\nProof using. prove_isTrue_lemma. Qed.\n\nLemma isTrue_eq_isTrue_eq : forall P1 P2,\n  (isTrue P1 = isTrue P2) = (P1 <-> P2).\nProof using.\n  intros. extens. iff; repeat rewrite isTrue_eq_if in *;\n  repeat case_if; auto_false*.\nQed.\n\nEnd IsTrueEqualities.\n\n(** [isTrue] and conditionals *)\n\nLemma if_isTrue : forall P A (x y : A),\n    (if isTrue P then x else y)\n  = (If P then x else y).\nProof using.\n  intros. case_if as C; case_if as D; auto.\n  { rewrite* isTrue_eq_true_eq in C. }\n  { rewrite* isTrue_eq_false_eq in C. }\nQed.\n\nLemma isTrue_If : forall P1 P2 P3,\n    isTrue (If P1 then P2 else P3)\n  = If P1 then isTrue P2 else isTrue P3.\nProof using. extens. case_if*. Qed.\n\nLemma isTrue_If_eq_if_isTrue : forall P1 P2 P3,\n    isTrue (If P1 then P2 else P3)\n  = (if isTrue P1 then isTrue P2 else isTrue P3).\nProof using. intros. rewrite if_isTrue. rewrite~ isTrue_If. Qed.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Lemmas for testing booleans *)\n\nLemma bool_inv_or : forall b,\n  b \\/ !b.\nProof using. tautob. Qed.\n\nLemma bool_inv_or_eq : forall b,\n  b = true \\/ b = false.\nProof using. tautob. Qed.\n\nLemma xor_inv_or : forall b1 b2,\n  xor b1 b2 ->\n     (b1 = true /\\ b2 = false)\n  \\/ (b1 = false /\\ b2 = true).\nProof using. tautob; auto_false*. Qed.\n\nArguments xor_inv_or [b1] [b2].\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Lemmas for normalizing [b = true] and [b = false] terms *)\n\nLemma bool_eq_true_eq : forall b,\n  (b = true) = istrue b.\nProof using. extens. tautob. Qed.\n\nLemma bool_eq_false_eq : forall b,\n  (b = false) = istrue (!b).\nProof using. extens. tautob. Qed.\n\nLemma true_eq_bool_eq : forall b,\n  (true = b) = istrue b.\nProof using. extens. tautob. Qed.\n\nLemma false_eq_bool_eq : forall b,\n  (false = b) = istrue (!b).\nProof using. extens. tautob. Qed.\n\n(* ********************************************************************** *)\n(* ################################################################# *)\n(** * Tactics *)\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics [rew_istrue] to distribute [istrue] *)\n\n(** [rew_istrue] distributes [istrue]. It is useful to replace all\n    boolean operators with corresponding logical operators. *)\n\nHint Rewrite istrue_true_eq istrue_false_eq istrue_isTrue_eq\n  istrue_neg_eq istrue_and_eq istrue_or_eq\n  If_istrue istrue_If_eq istrue_if_eq: rew_istrue.\n\nTactic Notation \"rew_istrue\" :=\n  autorewrite with rew_istrue.\nTactic Notation \"rew_istrue\" \"in\" hyp(H) :=\n  autorewrite with rew_istrue in H.\nTactic Notation \"rew_istrue\" \"in\" \"*\" :=\n  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_istrue).\n  (* autorewrite with rew_istrue in *. *)\n\nTactic Notation \"rew_istrue\" \"~\" :=\n  rew_istrue; auto_tilde.\nTactic Notation \"rew_istrue\" \"~\" \"in\" hyp(H) :=\n  rew_istrue in H; auto_tilde.\nTactic Notation \"rew_istrue\" \"~\" \"in\" \"*\" :=\n  rew_istrue in *; auto_tilde.\n\nTactic Notation \"rew_istrue\" \"*\" :=\n  rew_istrue; auto_star.\nTactic Notation \"rew_istrue\" \"*\" \"in\" hyp(H) :=\n  rew_istrue in H; auto_star.\nTactic Notation \"rew_istrue\" \"*\" \"in\" \"*\" :=\n  rew_istrue in *; auto_star.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics [rew_isTrue] to distribute [isTrue] *)\n\n(** [rew_isTrue] distributes [isTrue].\n    This tactic is probably much less useful than [rew_istrue], since logical\n    operators are often simpler to work with. *)\n\nHint Rewrite isTrue_True isTrue_False isTrue_istrue\n  isTrue_not isTrue_and isTrue_or\n  if_isTrue isTrue_If : rew_isTrue.\n\nTactic Notation \"rew_isTrue\" :=\n  autorewrite with rew_isTrue.\nTactic Notation \"rew_isTrue\" \"in\" hyp(H) :=\n  autorewrite with rew_isTrue in H.\nTactic Notation \"rew_isTrue\" \"in\" \"*\" :=\n  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_isTrue).\n  (* autorewrite with rew_isTrue in *. *)\n\nTactic Notation \"rew_isTrue\" \"~\" :=\n  rew_isTrue; auto_tilde.\nTactic Notation \"rew_isTrue\" \"~\" \"in\" hyp(H) :=\n  rew_isTrue in H; auto_tilde.\nTactic Notation \"rew_isTrue\" \"~\" \"in\" \"*\" :=\n  rew_isTrue in *; auto_tilde.\n\nTactic Notation \"rew_isTrue\" \"*\" :=\n  rew_isTrue; auto_star.\nTactic Notation \"rew_isTrue\" \"*\" \"in\" hyp(H) :=\n  rew_isTrue in H; auto_star.\nTactic Notation \"rew_isTrue\" \"*\" \"in\" \"*\" :=\n  rew_isTrue in *; auto_star.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Tactics useful for program verification, when reasoning about\n       the result of if-statements over boolean expressions, i.e.\n       an expression of the form [b = ..] or [.. = b], which produces\n       hypotheses of the form [true = ..] and [false = ..] or symmetric.\n       It is used as post-treatment for tactic [case_if]. *)\n\nHint Rewrite\n  true_eq_isTrue_eq isTrue_eq_true_eq\n  false_eq_isTrue_eq isTrue_eq_false_eq\n  isTrue_eq_isTrue_eq\n  not_not_eq\n  istrue_true_eq istrue_false_eq istrue_isTrue_eq\n  istrue_neg_eq istrue_and_eq istrue_or_eq\n  bool_eq_true_eq bool_eq_false_eq true_eq_bool_eq false_eq_bool_eq\n  : rew_bool_eq.\n\nTactic Notation \"rew_bool_eq\" :=\n  autorewrite with rew_bool_eq.\nTactic Notation \"rew_bool_eq\" \"~\" :=\n  rew_bool_eq; auto_tilde.\nTactic Notation \"rew_bool_eq\" \"*\" :=\n  rew_bool_eq; auto_star.\n\nTactic Notation \"rew_bool_eq\" \"in\" hyp(H) :=\n  autorewrite with rew_bool_eq in H.\nTactic Notation \"rew_bool_eq\" \"~\" \"in\" hyp(H) :=\n  rew_bool_eq in H; auto_tilde.\nTactic Notation \"rew_bool_eq\" \"*\" \"in\" hyp(H) :=\n  rew_bool_eq in H; auto_star.\n\nTactic Notation \"rew_bool_eq\" \"in\" \"*\" :=\n  autorewrite_in_star_patch ltac:(fun tt => autorewrite with rew_bool_eq).\n  (* autorewrite with rew_bool_eq in *. *)\nTactic Notation \"rew_bool_eq\" \"~\" \"in\" \"*\" :=\n  rew_bool_eq; auto_tilde.\nTactic Notation \"rew_bool_eq\" \"*\" \"in\" \"*\" :=\n  rew_bool_eq; auto_star.\n\n(* ---------------------------------------------------------------------- *)\n(* ================================================================= *)\n(** ** Tactics extended for reflection *)\n\n(** Extension of the tactic [case_if] to automatically performs\n    simplification using [logics].\n\n    For less aggressive introduction of [istrue], consider rewriting\n    without the lemmas:\n    [bool_eq_true_eq bool_eq_false_eq true_eq_bool_eq false_eq_bool_eq]\n*)\n\nLtac case_if_post H ::=\n  rew_bool_eq in H; tryfalse.\n\n(** Extension of the tactic [test_dispatch] from LibLogic.v, so as to\n    be able to call the tactic [tests] directly on boolean expressions *)\n\nLtac tests_bool_base E H1 H2 :=\n  tests_prop_base (istrue E) H1 H2.\n\nLtac tests_dispatch E H1 H2 ::=\n  match type of E with\n  | bool => tests_bool_base E H1 H2\n  | Prop => tests_prop_base E H1 H2\n  | {_}+{_} => tests_ssum_base E H1 H2\n  end.\n\n(** Extension of the tactic [apply_to_head_of] (see LibTactics). *)\n\nLtac apply_to_head_of E cont ::=\n  let go E := let P := get_head E in cont P in\n  match E with\n  | istrue ?A => go A\n  | istrue (neg ?A) => go A\n  | ?A = ?B => first [ go A | go B ]\n  | ?A => go A\n  end.\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/LibReflect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7150495522836976}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*             Ralph Matthes [+]                              *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*                             [+] Affiliation IRIT -- CNRS   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega Wellfounded Permutation.\n\nRequire Import list_utils.\n\nSet Implicit Arguments.\n\nSection sorted.\n\n  Variable (X : Type) (R : X -> X -> Prop).\n\n  Inductive sorted : list X -> Prop :=\n    | in_sorted_0 : sorted nil\n    | in_sorted_1 : forall x l, Forall (R x) l -> sorted l -> sorted (x::l).\n\n  Fact sorted_app l m : (forall x y, In x l -> In y m -> R x y) -> sorted l -> sorted m -> sorted (l++m).\n  Proof.\n    intros H H1 Hm; revert H1 H.\n    induction 1 as [ | x l H1 H2 IH2 ]; intros H3; simpl; auto.\n    constructor.\n    + apply Forall_app; auto.\n      apply Forall_forall; intros; apply H3; simpl; auto.\n    + apply IH2; intros; apply H3; simpl; auto.\n  Qed.\n\n  Variable (f : X -> X) (Hf : forall x y, R x y -> R (f x) (f y)).\n\n  Fact sorted_map l : sorted l -> sorted (map f l).\n  Proof.\n    induction 1 as [ | x l H1 H2 IH2 ]; simpl; constructor; auto.\n    apply Forall_forall.\n    rewrite Forall_forall in H1.\n    intros y; rewrite in_map_iff.\n    intros (? & ? & ?); subst; auto.\n  Qed.\n\nEnd sorted.\n\nFact sorted_mono X (R S : X -> X -> Prop) l : (forall x y, In x l -> In y l -> R x y -> S x y) -> sorted R l -> sorted S l.\nProof.\n  intros H1 H2; revert H2 H1.\n  induction 1 as [ | x l H1 H2 IH2 ]; intros H3.\n  + constructor.\n  + constructor.\n    * revert H1; do 2 rewrite Forall_forall.\n      intros H1 y Hy; apply H3; simpl; auto.\n    * apply IH2; intros ? ? ? ?; apply H3; simpl; auto.\nQed.\n\nSection list_has_dup.\n\n  Variable (X : Type).\n\n  Implicit Types (l m : list X).\n  \n  Inductive list_has_dup : list X -> Prop :=\n    | in_list_hd0 : forall l x, In x l -> list_has_dup (x::l)\n    | in_list_hd1 : forall l x, list_has_dup l -> list_has_dup (x::l).\n  \n  Fact list_hd_cons_inv x l : list_has_dup (x::l) -> In x l \\/ list_has_dup l.\n  Proof. inversion 1; subst; auto. Qed.\n  \n  Fact list_has_dup_app_left l m : list_has_dup m -> list_has_dup (l++m).\n  Proof. induction l; simpl; auto; constructor 2; auto. Qed.\n  \n  Fact list_has_dup_app_right l m : list_has_dup l -> list_has_dup (l++m).\n  Proof. \n    induction 1; simpl.\n    + constructor 1; apply in_or_app; left; auto.\n    + constructor 2; auto.\n  Qed.\n\n  Fact perm_list_has_dup l m : l ~p m -> list_has_dup l -> list_has_dup m.\n  Proof.\n    induction 1 as [ | x l m H1 IH1 | x y l | ]; auto; \n      intros H; apply list_hd_cons_inv in H.\n    + destruct H as [ H | H ].\n      * apply Permutation_in with (1 := H1) in H.\n        apply in_list_hd0; auto.\n      * apply in_list_hd1; auto.\n    + destruct H as [ [ H | H ] | H ]; subst.\n      * apply in_list_hd0; left; auto.\n      * apply in_list_hd1, in_list_hd0; auto.\n      * apply list_hd_cons_inv in H.\n        destruct H as [ H | H ].\n        - apply in_list_hd0; right; auto.\n        - do 2 apply in_list_hd1; auto.\n  Qed.\n\n  Fact list_has_dup_eq_duplicates m: list_has_dup m <-> exists x aa bb cc, m = aa++x::bb++x::cc.\n  Proof.\n    split.\n    + induction 1 as [ m x Hm | m x _ IHm ].\n      - apply in_split in Hm.\n        destruct Hm as (bb & cc & Hm).\n        exists x, nil, bb, cc; subst; auto.\n      - destruct IHm as (y & aa & bb & cc & IHm).\n        exists y, (x::aa), bb, cc; subst; auto.\n    + intros (x & aa & bb & cc & Hm).\n      subst m.\n      apply list_has_dup_app_left.\n      constructor 1; apply in_or_app; right.\n      constructor 1; reflexivity.\n  Qed.\n\nEnd list_has_dup.\n\nSection sorted_no_dup.\n \n  Variables (X : Type) (R : X -> X -> Prop) (HR : forall x, ~ R x x).\n\n  Lemma sorted_no_dup l : sorted R l -> ~ list_has_dup l.\n  Proof.\n    induction 1 as [ | x l H1 H2 IH2 ]; intros H.\n    + inversion H.\n    + apply list_hd_cons_inv in H.\n      destruct H as [ H | H ]; try tauto.\n      rewrite Forall_forall in H1; firstorder.\n  Qed.\n\nEnd sorted_no_dup.\n\nSection no_dup_sorted_with_ineq.\n\n  Variables (X : Type).\n  \n  Let R := fun (x y: X) => x <> y.\n\n  (** for this specific relation, not having duplicates is equivalent to being sorted: *)\n\n  Lemma no_dup_sorted_with_ineq l: sorted R l <-> ~ list_has_dup l.\n  Proof.\n    split.\n    * apply sorted_no_dup; intros ? []; trivial.\n    * induction l as [ | x l IHl].\n      - constructor.\n      - intros H; constructor.\n        + rewrite Forall_forall.\n          intros y Hy ?; subst.\n          apply H.\n          constructor 1; trivial.\n        + apply IHl; contradict H.\n          constructor 2; trivial.\n  Qed.\n\nEnd no_dup_sorted_with_ineq.\n\nSection no_dups_eq_perm.\n  \n  Variables (X : Type). \n\n  Lemma no_dups_eq_perm (l m : list X) : \n        (forall x, In x l <-> In x m)\n     -> ~ list_has_dup l\n     -> ~ list_has_dup m\n     -> l ~p m.\n  Proof.\n    revert m; induction l as [ | x l IH ]; intros m H1 H2 H3.\n    * destruct m as [ | y m ].\n      + constructor.\n      + exfalso; apply (H1 y); simpl; auto.\n    * assert (In x m) as Hm.\n      { apply H1; simpl; auto. }\n      apply in_split in Hm.\n      destruct Hm as (m1 & m2 & ?); subst.\n      assert (~ In x l) as H4.\n      { contradict H2; constructor 1; auto. }\n      assert (~ In x m1) as H5.\n      { contradict H3.\n        apply in_split in H3.\n        destruct H3 as (p1 & p2 & ?); subst.\n        apply list_has_dup_eq_duplicates.\n        exists x,p1,p2,m2; rewrite app_ass; auto. }\n      assert (~ In x m2) as H6.\n      { contradict H3.\n        apply in_split in H3.\n        destruct H3 as (p1 & p2 & ?); subst.\n        apply list_has_dup_eq_duplicates.\n        exists x,m1,p1,p2; auto. }\n      apply Permutation_cons_app, IH.\n      + intros y; split.\n        - intros G1.\n          generalize (proj1 (H1 y) (or_intror G1)).\n          intros G2.\n          apply in_app_or in G2.\n          apply in_or_app.\n          destruct G2 as [|[|]]; subst; tauto.\n        - intros G1.\n          generalize (proj2 (H1 y)); intros G2.\n          apply in_app_or in G1.\n          destruct G2; subst; try tauto.\n          apply in_or_app; simpl; tauto.\n      + contradict H2; constructor 2; auto.\n      + contradict H3.\n        apply perm_list_has_dup with (1 := Permutation_middle _ _ _).\n        constructor 2; auto.\n  Qed.\n\nEnd no_dups_eq_perm.\n\nSection sorted_perm.\n\n  Variables (X : Type) (R S : X -> X -> Prop) (l m : list X) \n            (Hlm : forall x, In x l <-> In x m)\n            (HR : forall x, ~ R x x) \n            (HS : forall x, ~ S x x)\n            (Hl : sorted R l) (Hm : sorted S m).\n\n  Theorem sorted_perm : l ~p m.\n  Proof. \n    apply no_dups_eq_perm; auto.\n    + apply sorted_no_dup with (1 := HR); trivial.\n    + apply sorted_no_dup with (1 := HS); trivial.\n  Qed.\n\nEnd sorted_perm.\n\n", "meta": {"author": "DmxLarchey", "repo": "BFE", "sha": "0bf8376a80ca4378be1630689f6561744d43474e", "save_path": "github-repos/coq/DmxLarchey-BFE", "path": "github-repos/coq/DmxLarchey-BFE/BFE-0bf8376a80ca4378be1630689f6561744d43474e/coq/sorted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7150495496459027}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\nSet Implicit Arguments.\n\nRequire Import FCF.Crypto.\nRequire Import FCF.RndNat.\nRequire Import FCF.NotationV1.\n\nDefinition Bernoulli(r : Rat) : Comp bool :=\n  match r with\n    | RatIntro n d =>\n      v <-$ RndNat d; ret (if (lt_dec v n) then true else false)\n  end.\n\n\nTheorem Bernoulli_correct : \n  forall (r : Rat),\n    r <= 1 ->\n    Pr[Bernoulli r] == r.\n\n  unfold Bernoulli.\n  intuition.\n  destruct r.\n\n  rewrite RndNat_seq.\n  \n  rewrite (sumList_filter_partition (fun z => if (lt_dec z n) then true else false)).\n  eapply eqRat_trans.\n  eapply ratMult_eqRat_compat.\n  eapply eqRat_refl.\n  eapply ratAdd_eqRat_compat.\n\n  eapply sumList_all.\n  intros.\n  destruct ( lt_dec a n).\n  simpl.\n  destruct ( EqDec_dec bool_EqDec true true).\n  eapply eqRat_refl.\n  intuition.\n  apply filter_In in H0.\n  intuition.\n  exfalso.\n  destruct (lt_dec a n); intuition.\n\n  eapply sumList_0.\n  intros.\n  apply filter_In in H0.\n  intuition.\n  destruct (lt_dec a n); simpl in *.\n  discriminate.\n  destruct (EqDec_dec bool_EqDec false true); intuition.\n\n  rewrite allNatsLt_filter_lt.\n  rewrite <- ratAdd_0_r.\n  rewrite ratMult_1_r.\n  rewrite allNatsLt_length.\n  rewrite <- ratMult_num_den.\n  eapply eqRat_terms.\n  omega.\n  unfold posnatMult, posnatToNat, natToPosnat.\n  destruct p.\n  omega.\n\n  eapply rat_le_1_if; trivial.\n\nQed.\n\nTheorem Bernoulli_wf : \n  forall r, \n    well_formed_comp (Bernoulli r).\n\n  intuition.\n  unfold Bernoulli.\n  destruct r.\n  wftac.\n\nQed.\n\nTheorem Bernoulli_correct_complement : \n  forall (r : Rat),\n    r <= 1 ->\n    evalDist (Bernoulli r) false == \n    ratSubtract 1 r.\n\n  intuition.\n  eapply eqRat_trans.\n  eapply evalDist_complement.\n  eapply Bernoulli_wf.\n  eapply ratSubtract_eqRat_compat; intuition.\n  eapply Bernoulli_correct.\n  trivial.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/FCF/Bernoulli.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7150495426341659}}
{"text": "Require Export XR_R.\nRequire Export XR_Rle.\nRequire Export XR_Rle_antisym.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rle_le_eq : forall r1 r2, r1 <= r2 /\\ r2 <= r1 <-> r1 = r2.\nProof.\nintros x y.\nsplit.\n{\n  intros [ hxy hyx ].\n  apply Rle_antisym.\n  { exact hxy. }\n  { exact hyx. }\n}\n{\n  intro heq.\n  subst y.\n  split.\n  { unfold \"<=\". right. reflexivity. }\n  { unfold \"<=\". right. reflexivity. }\n}\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rle_le_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.715049538226648}}
{"text": "Require Import univalenceSolutions.\n\nSection category.\n\n  Record caty:=\n    {obj:Type;\n     arr:Type;\n     s:arr->obj;\n     t:arr->obj;\n     e:obj->arr;\n     t_section:\n       forall x:obj,\n         t(e(x)) = x;\n     s_section:\n       forall x:obj,\n         x = s(e(x));\n     comp:\n       forall g f:arr,\n         t(f)=s(g) -> arr;\n     s_comp:\n       forall g f:arr,\n       forall H:t(f)=s(g),\n         s(f) = s(comp g f H);\n     t_comp:\n       forall g f:arr,\n       forall H:t(f)=s(g),\n         t(comp g f H) = t(g);\n     left_id:\n       forall g:arr, forall m:obj,\n           forall H:t(e(m)) = s(g),\n           comp g (e(m)) H = g;\n     right_id:\n       forall g:arr, forall m:obj,\n           forall H:t(g) = s(e(m)),\n             comp (e(m)) g H = g;\n     assoc:\n       forall h g f:arr,\n       forall H:t(f)=s(g),\n       forall K:t(g)=s(h),\n         comp (comp h g K) f (eq_trans H (s_comp h g K)) = comp h (comp g f H) (eq_trans (t_comp g f H) K)\n    }.\n\n  Arguments t {c}.\n  Arguments s {c}.\n  Arguments e {c}.\n  Arguments comp {c}.\n  Arguments t_section {c}.\n  Arguments s_section {c}.\n  Arguments s_comp {c}.\n  Arguments t_comp {c}.\n  Arguments left_id {c}.\n  Arguments right_id {c}.\n  Arguments assoc {c}.\n\n  Record hom {C:caty} (a b:obj C):=\n    {arrow:>arr C;\n     source:(s(arrow)=a);\n     target:(t(arrow)=b)}.\n\n  Lemma s_hom {C:caty} {a b:obj C} (f:hom a b):\n    s(f) = a.\n  Proof.\n    apply source. Defined.\n\n  Lemma t_hom {C:caty} {a b:obj C} (f:hom a b):\n    t(f) = b.\n  Proof.\n    apply target. Defined.\n\n  Definition comp_hom {C:caty} {a b c:obj C}\n             (g:hom b c) (f:hom a b):arr C.\n  Proof.\n    apply (comp g f). rewrite t_hom. rewrite s_hom. reflexivity.\n    Defined.\n\n  Definition isIso {C:caty} (f:arr C):=\n    exists g:arr C, exists (H:t(f)=s(g)), exists (K:t(g)=s(f)),\n          (comp g f H) = e(s(f)) /\\ (comp f g K) = e(s(g)).\n\n  Definition iso {C:caty} (a b:obj C):=\n    exists f:arr C,\n      (s(f) = a)/\\(t(f) = b)/\\(isIso f).\n\n  Lemma idToIso {C:caty} (a b:obj C):\n    (Id a b) -> iso a b.\n  Proof.\n    intros. unfold iso. induction X. exists (e(x)).\n    split.\n    - apply eq_sym. apply s_section.\n    - split.\n      -- apply t_section.\n      -- unfold isIso. exists (e(x)).\n         exists (eq_trans (t_section x) (s_section x)).\n         exists (eq_trans (t_section x) (s_section x)).\n         split.\n         --- rewrite (s_section x). rewrite left_id.\n             rewrite <- s_section. rewrite <- s_section.\n             reflexivity.\n         --- rewrite (s_section x). rewrite left_id.\n             rewrite <- s_section. rewrite <- s_section.\n             reflexivity.\n  Defined.\n\n  Axiom caty_univalence:\n    forall {C:caty} (a b:obj C),\n      IsEquiv(idToIso a b).\n\nEnd category.\n\nArguments t {c}.\nArguments s {c}.\nArguments e {c}.\nArguments comp {c}.\nArguments t_section {c}.\nArguments s_section {c}.\nArguments s_comp {c}.\nArguments t_comp {c}.\nArguments left_id {c}.\nArguments right_id {c}.\nArguments assoc {c}.\n\n", "meta": {"author": "mwpb", "repo": "introduction-univalence-coq", "sha": "106643b5aea0937740e5ea51993a21da117dca2a", "save_path": "github-repos/coq/mwpb-introduction-univalence-coq", "path": "github-repos/coq/mwpb-introduction-univalence-coq/introduction-univalence-coq-106643b5aea0937740e5ea51993a21da117dca2a/category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7149707979634693}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  mult (Succ y) (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj201_coqofml_ehlZ9R.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7149707963236039}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus z (mult x z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj235_coqofml_Yo9ilS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7149707931603395}}
{"text": "Require Export Dm_nex.\nRequire Export Dm_alln.\nSection ml.\nTheorem Dm_nexe: forall A:Set -> Prop, \n(~ exists x:Set, A x) <-> forall x:Set, ~ A x.\nProof.\nsplit.\napply Dm_nex.\napply Dm_alln.\nQed.\nEnd ml.\n\nCheck Dm_nexe.", "meta": {"author": "ya0201", "repo": "mycoq-learning", "sha": "cc25eeeb8ef82917af329d69c4ea079935155005", "save_path": "github-repos/coq/ya0201-mycoq-learning", "path": "github-repos/coq/ya0201-mycoq-learning/mycoq-learning-cc25eeeb8ef82917af329d69c4ea079935155005/acintui/Dm_nexe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7149615194040774}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (z : natural) (lf2 : natural)\n  : natural := mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj164_coqofml_GFbnAj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7149615145426298}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) (y : natural)\n  : natural := plus Zero (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj297_coqofml_lRzcKI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.7718434873426303, "lm_q1q2_score": 0.714961503098855}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Definition(s): \n    Deterministic Simple Stack Machines\n*)\n\nRequire Import List.\nRequire Import Relation_Operators.\n\nDefinition stack : Set := list bool.\nDefinition state : Set := nat.\n(* configuration: left stack, state, right stack *)\nDefinition config : Set := stack * state * stack. \n(* direction: true = move left, false = move right *)\nDefinition dir : Set := bool. \n(* stack symbol: true = 1, false = 0 *)\nDefinition symbol : Set := bool. \n(* instruction: \n  (x, y, a, b, true ) = ax -> by \n  (x, y, b, a, false ) = xb -> ay *)\nDefinition instruction : Set := state * state * symbol * symbol * dir.\n(* simple stack machine: list of instructions *)\nDefinition ssm : Set := list instruction. \n\nInductive step (M : ssm) : config -> config -> Prop :=\n  (* transition AaxB -> AybB *)\n  | step_l (x y: state) (a b: symbol) (A B: stack) : \n    In (x, y, a, b, true) M -> step M (a::A, x, B) (A, y, b::B)\n  (* transition AxbB -> AayB *)\n  | step_r (x y: state) (a b: symbol) (A B: stack) : \n    In (x, y, b, a, false) M -> step M (A, x, b::B) (a::A, y, B).\n\n(* step is functional *)\nDefinition deterministic (M: ssm) := forall (X Y Z: config), step M X Y -> step M X Z -> Y = Z.\n\n(* deterministic simple stack machine *)\nDefinition dssm := { M : ssm | deterministic M }.\n\n(* reflexive transitive closure of step *)\nDefinition reachable (M: ssm) : config -> config -> Prop := clos_refl_trans config (step M).\n", "meta": {"author": "uds-psl", "repo": "2020-fscd-semi-unification", "sha": "392b549c00a2baf1280c9d71eded2dd1fcce4ceb", "save_path": "github-repos/coq/uds-psl-2020-fscd-semi-unification", "path": "github-repos/coq/uds-psl-2020-fscd-semi-unification/2020-fscd-semi-unification-392b549c00a2baf1280c9d71eded2dd1fcce4ceb/SM/SSM_prelim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7148996011389533}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype prime.\nFrom mathcomp Require Import div ssralg poly polydiv polyorder ssrnum zmodp polyrcf.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nImport GRing.Theory. (*Num.Theory Num.Def.*)\nImport Pdiv.Idomain.\n\nOpen Scope ring_scope.\n\nSection more_deriv.\n\nLemma derivXsubCexpSn : forall (R : idomainType) (c : R) (n : nat),\n   (('X-c%:P) ^+(n.+1))^`() = (n.+1)%:R *: ('X-c%:P) ^+ n.\nProof.\nmove=> R c; elim=> [|m Hm]; first by rewrite scaler_nat expr0 expr1 derivXsubC.\nrewrite exprSr derivM derivXsubC Hm -scalerAl -exprSr mulr1 scaler_nat -mulrSr.\nby rewrite -scaler_nat.\nQed.\n\nLemma derivXsubCexpn : forall (R : idomainType) (c : R) (n : nat),\n   (0 < n)%N -> (('X-c%:P) ^+n)^`() = n%:R *: ('X-c%:P) ^+ (n.-1).\nProof. by move=> R c; elim=> [|m Hm H] //=; rewrite derivXsubCexpSn. Qed.\n\nEnd more_deriv.\n\nSection poly_simple_roots.\n\nVariable R : idomainType.\nHypothesis HR : [char R] =i pred0.\n\nLemma mu_x_gcdp : forall (p : {poly R}) (x : R), (p != 0) -> (root p x) ->\n   \\mu_x (gcdp p p^`()) == (\\mu_x p) .-1.\nProof.\nmove=> p x Hp zero_x.\n(*about p*)\nhave [q Hq Hpp] := (@mu_spec R p x Hp).\n(*mu x > 0*)\nhave Hmu : ((\\mu_x p)%R > 0)%N by rewrite mu_gt0.\n(*about p'*)\nhave Hpderiv : (deriv p) =\n   ('X - x%:P) ^+ (\\mu_x p).-1 * ((\\mu_x p)%:R *: q + ('X-x%:P) * (deriv q)).\n  by rewrite mulrDr mulrA -exprSr prednK // -scalerCA -derivXsubCexpn //\n     -derivM mulrC {1}Hpp.\n(**********)\nrewrite eq_sym -muP.\n  apply/andP; split.\n(*(X-x)^m-1 divides pgcd*)\n    rewrite dvdp_gcd.\n    apply/andP; split.\n(*(X-x)^m-1 divides p*)\n      by rewrite {2}Hpp -(@prednK (\\mu_x p)) // exprS mulrA; apply dvdp_mulIr.\n(*(X-x)^m-1 divides p'*)\n    by rewrite Hpderiv; apply dvdp_mulIl.\n(*(X-x)^m doesn't divide pgcd*)\n  rewrite prednK // dvdp_gcd negb_and.\n  apply/orP; right.\n(*(X-x)^m doesn't divide p'*)\n  rewrite Hpderiv -{1}(@prednK (\\mu_x p)) // exprSr dvdp_mul2l.\n(*(X-x) doesn't divide the remaining factor of p'*)\n    rewrite dvdp_addl; last by apply dvdp_mulr.\n    rewrite (@eqp_dvdr _  q ((\\mu_x p)%:R *: q) ('X -x%:P)).\n      by rewrite dvdp_XsubCl.\n    apply eqp_scale.\n    have/charf0P ->:= HR.\n    by rewrite -lt0n //.\n  by rewrite -size_poly_gt0 size_exp_XsubC prednK //.\nby rewrite gcdp_eq0 negb_and Hp.\nQed.\n\nLemma mu_gcdp_eq1 : forall (p : {poly R}) (x : R), (p != 0) -> root p x ->\n   (\\mu_x (divp p (gcdp p p^`())) == 1)%N.\nProof.\nmove=> p x Hp zero_x.\nrewrite -(@eqn_add2r ((\\mu_x)%R p)) (@addnC 1%N _) addn1 \n  -{1}(@prednK ((\\mu_x)%R p)) ?mu_gt0 //.\nrewrite addnS -(eqP (mu_x_gcdp Hp zero_x)) -mu_mul.\n  rewrite divpK ?mu_mulC //; last by apply dvdp_gcdl.\n  by apply lc_expn_scalp_neq0.\nrewrite divpK.\n  rewrite -size_poly_gt0 -mul_polyC size_Cmul ?size_poly_gt0 //.\n  by apply lc_expn_scalp_neq0.\nby apply dvdp_gcdl.\nQed.\n\nLemma same_roots_1 : forall (p : {poly R}) (x : R), root p x ->\n   root (divp p (gcdp p p^`())) x.\nProof.\nmove=> p x zero_x.\ncase h: (p==0).\n  by move/eqP: h => H; move : zero_x; rewrite H deriv0 gcd0p div0p.\nmove/negbT: h => H; rewrite -mu_gt0.\n  by move/eqP : (mu_gcdp_eq1 H zero_x) => ->.\nrewrite divpN0; first by apply: leq_gcdpl.\nby move/negPf : H => H; rewrite gcdp_eq0 H.\nQed.\n\nLemma same_roots_2 : forall (p : {poly R}) (x : R),\n   root (divp p (gcdp p p^`())) x -> root p x.\nProof.\nmove=> p x zero_x.\nrewrite -(@rootZ R x (lead_coef (gcdp p p^`()) ^+ scalp (R:=R) p\n   (gcdp p p^`())) p).\n  rewrite -divpK.\n    by rewrite rootM zero_x.\n  by apply dvdp_gcdl.\nby apply lc_expn_scalp_neq0.\nQed.\n\nLemma gcdp_simple_roots : forall (p : {poly R}) (x : R), (p != 0) ->\n   root (divp p (gcdp p p^`())) x ->\n   (\\mu_x (divp p (gcdp p p^`())) == 1)%N.\nProof.\nby move=> p x Hp zero_x; apply (mu_gcdp_eq1 Hp); apply same_roots_2.\nQed.\n(*p!=0 beause of mu_polyC.*)\n\nEnd poly_simple_roots.\n", "meta": {"author": "math-comp", "repo": "trajectories", "sha": "cc6e1298208a93592230f5b4ee3228a024aa03e7", "save_path": "github-repos/coq/math-comp-trajectories", "path": "github-repos/coq/math-comp-trajectories/trajectories-cc6e1298208a93592230f5b4ee3228a024aa03e7/theories/square_free.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.714899599448537}}
{"text": "Fixpoint factorial (n:nat) : nat :=\n    match n with\n    | 0 => 1\n    | S n => mult (plus n 1) (factorial n)\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.", "meta": {"author": "jstzwj", "repo": "LearnCoq", "sha": "2cce1a6d3ac32ef90d1e961a27f6e661cd585646", "save_path": "github-repos/coq/jstzwj-LearnCoq", "path": "github-repos/coq/jstzwj-LearnCoq/LearnCoq-2cce1a6d3ac32ef90d1e961a27f6e661cd585646/exercise/factorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7148634846711145}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import set_notations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection UniqueExample.\n  Variable U:Type.\n  Import SetNotations.\n  \n  Goal forall (A B: Ensemble U),\n      (exists! x, x ∈ A) ->\n                  (forall (x:U),(x∈ A) -> (x ∈ B)) -> exists x, (x∈ A) /\\ (x ∈ B).\n  Proof.\n    move => A B H H0.\n    destruct H.\n    unfold unique in H.\n    exists x.\n    inversion H.\n    split.\n    apply H1.\n    apply H0.\n    apply H1.\n  Qed.\n\nEnd UniqueExample.", "meta": {"author": "seisyuu-hantatsushi", "repo": "coq_ssreflect_practice", "sha": "96e1d440c8c69673209ae0d86046b6b9305f8bab", "save_path": "github-repos/coq/seisyuu-hantatsushi-coq_ssreflect_practice", "path": "github-repos/coq/seisyuu-hantatsushi-coq_ssreflect_practice/coq_ssreflect_practice-96e1d440c8c69673209ae0d86046b6b9305f8bab/practices/unique_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7148383976240053}}
{"text": "From mathcomp Require Import all_ssreflect.\n\n(******************************************************************************)\n(*                                                                            *)\n(* f is a strictly increasing function such that f (f n) = 3 n                *)\n(* does it exist an n0 such that f n0 = 2022                                  *)\n(*                                                                            *)\n(******************************************************************************)\n\n\nSection PuzzleFF.\n\nVariable f : nat -> nat.\n\nHypothesis monof : {mono f : m n / m < n}.\n\nLemma leqfD a b : f a + b <= f (a + b).\nProof.\nelim: b a => [a|b IH a]; first by rewrite !addn0.\nby rewrite !addnS (leq_ltn_trans (IH a)) //= monof.\nQed.\n\nLemma leqf2D a b c : f (a + c) <= b + c -> f a <= b.\nProof.\nelim: c => [|c IH fLb]; first by rewrite !addn0.\napply: IH.\nby rewrite -ltnS -addnS (leq_trans _ fLb) // monof addnS.\nQed.\n\nLemma eqf2D a b c : f (a + b) = f a + b -> c <= b -> f (a + c) = f a + c.\nProof.\nelim: c => [|c IH  fabE cLb]; first by by rewrite !addn0.\nhave facE : f (a + c) = f a + c by apply: IH => //; apply: ltnW.\napply/eqP; rewrite eqn_leq leqfD andbT.\napply: leqf2D (_ : _ <= _ + (b - c.+1)).\nby do 2 rewrite -addnA (subnKC cLb) ?fabE.\nQed.\n\nLemma leqnfn n : n <= f n.\nProof.\nby elim: n => // n IH; apply: leq_ltn_trans IH _; rewrite monof.\nQed.\n\nHypothesis ffE : forall n, f (f n) = 3 * n. \n\nLemma ltnfn n : 0 < n -> n < f n.\nProof.\nmove=> n_gt0.\nhave := leqnfn n; rewrite leq_eqVlt; case: eqP => // nE _.\nhave : f n = 3 * n by rewrite [in LHS]nE ffE.\nmove=> /eqP; rewrite -nE -{1}(mul1n n) eqn_mul2r.\nby case: (n) n_gt0.\nQed.\n\nLemma leqfn3n n : f n <= 3 * n.\nProof. by rewrite -ltnS -monof ffE (leqnfn (S (3 * n))). Qed.\n\nLemma ltfn3n n : 0 < n -> f n < 3 * n.\nProof.\nmove=> n_gt0.\nhave := leqfn3n n; rewrite leq_eqVlt; case: eqP => // fnE _.\nhave : 3 * n < f (3 * n) by apply: ltnfn; rewrite muln_gt0.\nby rewrite -[in X in _ < X -> _]fnE ffE ltnn.\nQed.\n\nLemma f1E : f 1 = 2.\nProof.\nby apply/eqP; rewrite eqn_leq ltnfn // -ltnS ltfn3n.\nQed.\n\nLemma f2E : f 2 = 3.\nProof. by rewrite -[in LHS]f1E ffE. Qed.\n\nLemma f3nE n : f (3 ^ n) = 2 * 3 ^ n /\\ f (2 * 3 ^ n) = 3 ^ (S n).\nProof.\nelim: n => [|n [IH1 IH2]]; first by rewrite f1E f2E.\nhave f3SnE : f (3 ^ n.+1) = 2 * 3 ^ n.+1 . \n  by rewrite -[in LHS]IH2 ffE mulnC -mulnA expnS [3 * _]mulnC.\nby split => //; rewrite -f3SnE ffE !expnS.\nQed.\n\nFact f1293E : f 1293 = 2022.\nProof.\ndestruct (f3nE 6) as [H1 H2].\nrewrite -[2022]/(2 * 3 ^ 6 + (2022 - 2 * (3 ^ 6))).\nrewrite -{1}[1293]/(3 ^ 6 + (2022 - 2 * (3 ^ 6))).\nrewrite -[X in _ = X + _]H1.\napply: eqf2D (_ : _ = _ + 3 ^ 6) _ => //.\nby rewrite -[3 ^ 6 + 3 ^ 6]/(2 * 3 ^ 6) H2 H1.\nQed.\n\nEnd PuzzleFF.", "meta": {"author": "thery", "repo": "mathcomp-extra", "sha": "e776299ceebf276502a6ee1a787febf5c806293d", "save_path": "github-repos/coq/thery-mathcomp-extra", "path": "github-repos/coq/thery-mathcomp-extra/mathcomp-extra-e776299ceebf276502a6ee1a787febf5c806293d/puzzleFF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7148383976240053}}
{"text": "Require Import List.\n\nImport ListNotations.\n\nSection RegExp.\n\nVariable char : Type.\n\nDefinition c : Type := char.\n\nInductive r : Type :=\n | r_zero\n | r_unit\n | r_char (c5:c)\n | r_plus (r0:r) (r1:r)\n | r_times (r0:r) (r1:r)\n | r_star (r0:r).\n\nDefinition s : Type := list char.\n\nInductive s_in_regexp_lang : s -> r -> Prop :=\n | s_in_regexp_lang_unit : \n     s_in_regexp_lang  []  r_unit\n | s_in_regexp_lang_char : forall (c5:c),\n     s_in_regexp_lang  ( c5  :: [])  (r_char c5)\n | s_in_regexp_lang_plus_1 : forall (s5:s) (r1 r2:r),\n     s_in_regexp_lang s5 r1 ->\n     s_in_regexp_lang s5 (r_plus r1 r2)\n | s_in_regexp_lang_plus_2 : forall (s5:s) (r1 r2:r),\n     s_in_regexp_lang s5 r2 ->\n     s_in_regexp_lang s5 (r_plus r1 r2)\n | s_in_regexp_lang_times : forall (s5 s':s) (r1 r2:r),\n     s_in_regexp_lang s5 r1 ->\n     s_in_regexp_lang s' r2 ->\n     s_in_regexp_lang  ( s5  ++  s' )  (r_times r1 r2)\n | s_in_regexp_lang_star_1 : forall (r:r),\n     s_in_regexp_lang  []  (r_star r)\n | s_in_regexp_lang_star_2 : forall (s5 s':s) (r0:r),\n     s_in_regexp_lang s5 r0 ->\n     s_in_regexp_lang s' (r_star r0) ->\n     s_in_regexp_lang  ( s5  ++  s' )  (r_star r0).\n\nInductive s_in_regexp_c_lang : s -> r -> c -> Prop :=\n | s_in_regexp_c_lang_cs : forall (s5:s) (r0:r) (c5:c),\n     s_in_regexp_lang  (  ( c5  :: [])   ++  s5 )  r0 ->\n     s_in_regexp_c_lang s5 r0 c5.\n\nEnd RegExp.\n\nArguments r_zero [char].\nArguments r_unit [char].\nArguments r_char [char] _.\nArguments r_plus [char] _ _.\nArguments r_times [char] _ _.\nArguments r_star [char] _.\n", "meta": {"author": "proofengineering", "repo": "regmatch", "sha": "1873ac0d8fe9f6b09e8eaa768d992563dbd63ad5", "save_path": "github-repos/coq/proofengineering-regmatch", "path": "github-repos/coq/proofengineering-regmatch/regmatch-1873ac0d8fe9f6b09e8eaa768d992563dbd63ad5/regexp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7148380199830506}}
{"text": "Require Export chapter08.\n\nTheorem eight_is_beautiful'': beautiful 8.\nProof.\n   Show Proof.\n   apply b_sum with (n:=3) (m:=5).\n   Show Proof.\n   apply b_3.\n   Show Proof.\n   apply b_5.\n   Show Proof.\nQed.\n\nTheorem six_is_beautiful :\n  beautiful 6.\nProof.\n  apply b_sum with (n := 3) (m := 3).\n  apply b_3. apply b_3.\nQed.\n\nDefinition six_is_beautiful' : beautiful 6 :=\n  b_sum 3 3 b_3 b_3.\n\nTheorem b_times2: forall n, beautiful n -> beautiful (2*n).\nProof.\n  intros. simpl. apply b_sum. apply H. apply b_sum. apply H. apply b_0.\nQed.\n\nDefinition b_times2': forall n, beautiful n -> beautiful (2*n) :=\n  fun (n : nat) => fun (e : beautiful n) => b_sum n (n + 0) e (b_sum n 0 e b_0).\n\nTheorem and_example : \n  (beautiful 0) /\\ (beautiful 3).\nProof.\n  apply conj.\n   Case \"left\". apply b_0.\n   Case \"right\". apply b_3. Qed.\n\nPrint and_example.\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  fun (P Q R : Prop) (PAndQ : P /\\ Q) (QAndR : Q /\\ R) =>\n    match PAndQ with\n    | conj HP HQ1 => match QAndR with\n                     | conj HQ2 HR => conj P R HP HR\n                     end\n    end.", "meta": {"author": "serras", "repo": "sf-exercises", "sha": "078cbb82b717d282248c3504941f31308fab5fbc", "save_path": "github-repos/coq/serras-sf-exercises", "path": "github-repos/coq/serras-sf-exercises/sf-exercises-078cbb82b717d282248c3504941f31308fab5fbc/chapter09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7148379718568854}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Main.\nFrom Categories Require Import Functor.Functor.\nFrom Categories Require Import Cat.Cat.\n\nSection NatTrans.\n  Context {C C' : Category}.\n\n(**\nFor categories C and C' and functors F : C -> C' and F' : C -> C', a natural\ntransformation N : F -> F' is a family of arrows 'Trans N' in the co-domain\ncategory (here C') indexed by objects of the domain category (here C),\nTrans N c : F _o c -> F' _o c.\n\nIn addition, for all arrows h : c → c' the following diagram must\ncommute (Trans_com):\n\n#\n<pre>\n             F _a h\nF _o c ————————————————––> F _o c'\n |                          |\n |                          |\n |                          |\n | Trans N c                | Trans N c'\n |                          |\n |                          |\n ∨                          ∨\nF' _o c ————————————————–> F' _o c'\n            F' _a h\n</pre>\n#\nTrans_com_sym is the symmetric form of Trans_com.\n*)\n  Record NatTrans (F F' : (C –≻ C')%functor) :=\n    {\n      Trans (c : C) : ((F _o c) –≻ (F' _o c))%object%morphism;\n      Trans_com {c c' : C} (h : (c –≻ c')%morphism) :\n        ((Trans c') ∘ F _a h = F' _a h ∘ (Trans c))%morphism;\n      Trans_com_sym {c c' : C} (h : (c –≻ c')%morphism) :\n        (F' _a h ∘ (Trans c) = (Trans c') ∘ F _a h)%morphism\n    }.\n\n  Notation \"F –≻ F'\" := (NatTrans F F') : nattrans_scope.\n\n  (** Two natural transformations are equal if their arrow families are.\n      That is, commutative diagrams are assumed to be equal by\n      proof irrelevance. *)\n  Lemma NatTrans_eq_simplify {F F' : (C –≻ C')%functor}\n        (N N' : (F –≻ F')%nattrans) : (@Trans _ _ N) = (@Trans _ _ N') -> N = N'.\n  Proof.\n    destruct N; destruct N'.\n    basic_simpl.\n    ElimEq.\n    PIR; trivial.\n  Qed.\n\nEnd NatTrans.\n\nArguments Trans {_ _ _ _} _ _.\nArguments Trans_com {_ _ _ _} _ {_ _} _.\nArguments Trans_com_sym {_ _ _ _} _ {_ _} _.\n\nBind Scope nattrans_scope with NatTrans.\n\nNotation \"F –≻ F'\" := (NatTrans F F') : nattrans_scope.\n\nLocal Open Scope nattrans_scope.\n\nSection NatTrans_Compose.\n  Context {C C' : Category}.\n  \n  (** Natural transformations are composable. The arrow family of the result is\n      just the composition of corresponding components in each natural\n      transformation. Graphically:\n#\n<pre>\n         F                            F\n   C ———————————————–> D        C ———————————————–> D \n           ||                           ||\n           ||N                          ||\n           ||                           ||\n           \\/                           ||\n   C ———————————————–> D                || N' ∘ N\n         G                              ||\n           ||                           ||\n           ||N'                         ||\n           ||                           ||\n           \\/                           \\/\n   C ———————————————–> D        C ———————————————–> D \n         H                            H\n</pre>\n#\n\nThis kind of composition is sometimes also called vertical composition of\nnatural transformations.\n*)\n  Program Definition NatTrans_compose {F F' F'' : (C –≻ C')%functor}\n          (tr : F –≻ F') (tr' : F' –≻ F'') : (F –≻ F'')%nattrans :=\n    {|\n      Trans := fun c : Obj => ((Trans tr' c) ∘ (Trans tr c)) % morphism\n    |}.\n\n  Next Obligation. (* Trans_com*)\n  Proof.\n    rewrite assoc.\n    rewrite Trans_com.\n    rewrite assoc_sym.\n    rewrite Trans_com; auto.\n  Qed.\n\n  Next Obligation. (* Trans_com_sym *)\n  Proof.\n    symmetry.\n    apply NatTrans_compose_obligation_1.\n  Qed.\n\nEnd NatTrans_Compose.\n\nNotation \"N ∘ N'\" := (NatTrans_compose N' N) : nattrans_scope.\n\nSection NatTrans_Props.\n  Context {C C' : Category}.\n  \n  (** The composition of natural transformations is associative. *)\n  Theorem NatTrans_compose_assoc {F G H I : (C –≻ C')%functor} (N : F –≻ G)\n          (N' : G –≻ H) (N'' : H –≻ I)\n    : ((N'' ∘ N') ∘ N = N'' ∘ (N' ∘ N))%nattrans\n  .\n  Proof.\n    apply NatTrans_eq_simplify; cbn; auto.\n  Qed.\n\n  (** The identity natural transformation. The arrow family are just\n      all identity arrows: *)\n  Program Definition NatTrans_id (F : (C –≻ C')%functor) : F –≻ F :=\n    {|\n      Trans := fun x : Obj => id\n    |}.\n\n  Theorem NatTrans_id_unit_left {F G : (C –≻ C')%functor} (N : F –≻ G)\n    : (NatTrans_id G) ∘ N = N.\n  Proof.\n    apply NatTrans_eq_simplify; cbn; auto.\n  Qed.\n\n  Theorem NatTrans_id_unit_right {F G : (C –≻ C')%functor} (N : F –≻ G)\n    : N ∘ (NatTrans_id F) = N.\n  Proof.\n    apply NatTrans_eq_simplify; cbn; auto.\n  Qed.\n  \nEnd NatTrans_Props.\n\nHint Resolve NatTrans_eq_simplify.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/Categories/NatTrans/NatTrans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7148379576936461}}
{"text": "(* Software Foundations *)\n(* Exercice 2 stars, override_same *)\n\nDefinition override {X: Type}(f: nat -> X) k v:=\n  fun k' => if Nat.eqb k k' then v else f k'.\n\nLemma beq_nat_true: forall n m: nat, Nat.eqb n m = true -> n = m.\nAdmitted.\n\nTheorem override_same : forall (X: Type) x1 k1 k2 (f: nat -> X ), \n  f k1 = x1 -> (override f k1 x1) k2 = f k2.\nProof.\n    intros. unfold override.\n    destruct (Nat.eqb k1 k2) eqn: eqek1k2.\n    apply beq_nat_true in eqek1k2. rewrite <- eqek1k2. rewrite H. reflexivity.\n    reflexivity.\nQed.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter7_Library_MoreCoq/override_same.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7147992685729121}}
{"text": "\nRequire Import ZArith ROmega.\n\n(* Submitted by Xavier Urbain 18 Jan 2002 *)\n\nLemma lem1 :\n forall x y : Z, (-5 < x < 5)%Z -> (-5 < y)%Z -> (-5 < x + y + 5)%Z.\nProof.\nintros x y.\nromega.\nQed.\n\n(* Proposed by Pierre Crégut *)\n\nLemma lem2 : forall x : Z, (x < 4)%Z -> (x > 2)%Z -> x = 3%Z.\nintro.\n romega.\nQed.\n\n(* Proposed by Jean-Christophe Filliâtre *)\n\nLemma lem3 : forall x y : Z, x = y -> (x + x)%Z = (y + y)%Z.\nProof.\nintros.\nromega.\nQed.\n\n(* Proposed by Jean-Christophe Filliâtre: confusion between an Omega *)\n(* internal variable and a section variable (June 2001) *)\n\nSection A.\nVariable x y : Z.\nHypothesis H : (x > y)%Z.\nLemma lem4 : (x > y)%Z.\n romega.\nQed.\nEnd A.\n\n(* Proposed by Yves Bertot: because a section var, L was wrongly renamed L0 *)\n(* May 2002 *)\n\nSection B.\nVariable R1 R2 S1 S2 H S : Z.\nHypothesis I : (R1 < 0)%Z -> R2 = (R1 + (2 * S1 - 1))%Z.\nHypothesis J : (R1 < 0)%Z -> S2 = (S1 - 1)%Z.\nHypothesis K : (R1 >= 0)%Z -> R2 = R1.\nHypothesis L : (R1 >= 0)%Z -> S2 = S1.\nHypothesis M : (H <= 2 * S)%Z.\nHypothesis N : (S < H)%Z.\nLemma lem5 : (H > 0)%Z.\n romega.\nQed.\nEnd B.\n\n(* From Nicolas Oury (BZ#180): handling -> on Set (fixed Oct 2002) *)\nLemma lem6 :\n forall (A : Set) (i : Z), (i <= 0)%Z -> ((i <= 0)%Z -> A) -> (i <= 0)%Z.\nintros.\n romega.\nQed.\n\n(* Adapted from an example in Nijmegen/FTA/ftc/RefSeparating (Oct 2002) *)\nRequire Import Omega.\nSection C.\nParameter g : forall m : nat, m <> 0 -> Prop.\nParameter f : forall (m : nat) (H : m <> 0), g m H.\nVariable n : nat.\nVariable ap_n : n <> 0.\nLet delta := f n ap_n.\nLemma lem7 : n = n.\n romega with nat.\nQed.\nEnd C.\n\n(* Problem of dependencies *)\nRequire Import Omega.\nLemma lem8 : forall H : 0 = 0 -> 0 = 0, H = H -> 0 = 0.\nintros.\nromega with nat.\nQed.\n\n(* Bug that what caused by the use of intro_using in Omega *)\nRequire Import Omega.\nLemma lem9 :\n forall p q : nat, ~ (p <= q /\\ p < q \\/ q <= p /\\ p < q) -> p < p \\/ p <= p.\nintros.\nromega with nat.\nQed.\n\n(* Check that the interpretation of mult on nat enforces its positivity *)\n(* Submitted by Hubert Thierry (BZ#743) *)\n(* Postponed... problem with goals of the form \"(n*m=0)%nat -> (n*m=0)%Z\" *)\nLemma lem10 : forall n m : nat, le n (plus n (mult n m)).\nProof.\nintros; romega with nat.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/success/ROmega.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7147992566664108}}
{"text": "(* Author: Christian Doczkal *)\nRequire Import ssreflect ssrbool eqtype ssrnat seq.\nRequire Import ssrfun choice fintype finset path fingraph bigop.\nRequire Import Relations.\nRequire Import tactics.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** * A least fixed point operator for finType *)\n\nLemma iter_fix T (F : T -> T) x k n : \n  iter k F x = iter k.+1 F x -> k <= n -> iter n F x = iter n.+1 F x.\nProof.\n  move => e. elim: n. rewrite leqn0. by move/eqP<-.\n  move => n IH. rewrite leq_eqVlt; case/orP; first by move/eqP<-.\n  move/IH => /= IHe. by rewrite -!IHe.\nQed.\n\nSection FixPoint.\n  Variable T :finType.\n  Definition set_op := {set T} -> {set T}.\n  Definition mono (F : set_op)  := forall p q : {set T} , p \\subset q -> F p \\subset F q.\n\n  Variable F : {set T} -> {set T}.\n  Hypothesis monoF : mono F.\n\n  Definition lfp := iter #|T|.+1 F set0.\n\n  Lemma lfp_ind (P : {set T} -> Type) : P set0 -> (forall s , P s -> P (F s)) -> P lfp.\n  Proof.\n    move => P0 Pn. rewrite /lfp. set n := #|T|.+1. elim: n => //= n. exact: Pn.\n  Qed.\n\n  Lemma iterFsub n : iter n F set0 \\subset iter n.+1 F set0.\n  Proof.\n    elim: n => //=; first by rewrite sub0set.\n    move => n IH /=. by apply: monoF.\n  Qed.\n\n  Lemma iterFsubn m n : m <= n -> iter m F set0 \\subset iter n F set0.\n  Proof.\n    elim : n; first by rewrite leqn0 ; move/eqP->.\n    move => n IH. rewrite leq_eqVlt; case/orP; first by move/eqP<-.\n    move/IH => /= IHe. apply: subset_trans; first apply IHe. exact:iterFsub.\n  Qed.\n \n  Lemma lfpE : lfp = F lfp.\n  Proof.\n    have: ~~ [ forall m : 'I_#|T|.+1 , iter m F set0 \\proper iter m.+1 F set0 ].\n      apply/negP => /forallP H.\n      have P : forall n : 'I_#|T|.+1 , exists x : T , x \\in iter n.+1 F set0 :\\: iter n F set0.\n        move => n ; move : (H n). case/properP => _ [x x1 x2]. exists x. by rewrite in_setD x1 x2.\n      pose i (o : 'I_#|T|.+1) : T := xchoose (P o).\n      have inj_i : injective i. \n        move => o o'. rewrite /i => e. move : (xchooseP (P o)) (xchooseP (P o')).\n        rewrite e {e}. set x := xchoose _. move : o o' x => [n pn] [m pm] x.\n        rewrite !in_setD /=. case/andP => Hn1 Hn2. case/andP => Hm1 Hm2.\n        case (ltngtP n m); last by move/eqP => e'; apply/eqP.\n        - move => /iterFsubn /subsetP /(_ x Hn2). by rewrite (negbTE Hm1).\n        - move => /iterFsubn /subsetP /(_ x Hm2). by rewrite (negbTE Hn1).\n      move : (max_card (fun x => x \\in codom i)). by rewrite (card_codom inj_i) /= !card_ord ltnn. \n    rewrite negb_forall. case/existsP => x H.\n    have A : iter x F set0 = iter x.+1 F set0. \n      apply/eqP. by rewrite eqEproper iterFsub /= H.\n    apply : iter_fix; first apply A. by case:x {H A} => *; auto.\n  Qed.\nEnd FixPoint.\n\n", "meta": {"author": "Janno", "repo": "Bachelor-Thesis", "sha": "3ba23a0803ffa6d2cb69dcd10ec3533e367d9294", "save_path": "github-repos/coq/Janno-Bachelor-Thesis", "path": "github-repos/coq/Janno-Bachelor-Thesis/Bachelor-Thesis-3ba23a0803ffa6d2cb69dcd10ec3533e367d9294/src/base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7147605899264625}}
{"text": "Load ListCost.\n\nInductive permutation {A} : list A -> list A -> Prop :=\n  | permutation_nil : permutation [] []\n  | permutation_insert a l1 l2 l3 :\n    permutation (l1 ++ l2) l3 ->\n    permutation (l1 ++ a :: l2) (a :: l3).\n\nInductive permutation_small {A} : list A -> list A -> Prop :=\n  | permutation_small_empty : permutation_small [] []\n  | permutation_small_cons a l1 l2 : permutation_small l1 l2 -> permutation_small (a :: l1) (a :: l2)\n  | permutation_small_swap a b l : permutation_small (b :: a :: l) (a :: b :: l)\n  | permutation_small_trans l1 l2 l3 :\n    permutation_small l1 l2 ->\n    permutation_small l2 l3 ->\n    permutation_small l1 l3.\n\nSection Example.\n\nTheorem permutation_example : permutation [5; 3; 1; 2; 4] [1; 2; 3; 4; 5].\nProof.\n  replace [5; 3; 1; 2; 4] with ([5; 3] ++ 1 :: [2; 4]) by auto; apply permutation_insert; simpl.\n  replace [5; 3; 2; 4] with ([5; 3] ++ 2 :: [4]) by auto; apply permutation_insert; simpl.\n  replace [5; 3; 4] with ([5] ++ 3 :: [4]) by auto; apply permutation_insert; simpl.\n  replace [5; 4] with ([5] ++ 4 :: []) by auto; apply permutation_insert; simpl.\n  replace [5] with ([] ++ 5 :: []) by auto; apply permutation_insert; simpl.\n  apply permutation_nil.\nQed.\n\nTheorem permutation_example_move : permutation [5; 3; 1; 2; 4] [3; 1; 2; 4; 5].\nProof.\n  replace [5; 3; 1; 2; 4] with ([5] ++ 3 :: [1; 2; 4]) by auto; apply permutation_insert; simpl.\n  replace [5; 1; 2; 4] with ([5] ++ 1 :: [2; 4]) by auto; apply permutation_insert; simpl.\n  replace [5; 2; 4] with ([5] ++ 2 :: [4]) by auto; apply permutation_insert; simpl.\n  replace [5; 4] with ([5] ++ 4 :: []) by auto; apply permutation_insert; simpl.\n  replace [5] with ([] ++ 5 :: []) by auto; apply permutation_insert; simpl.\n  apply permutation_nil.\nQed.\n\nTheorem permutation_example_sym : permutation [1; 2; 3; 4; 5] [5; 3; 1; 2; 4].\nProof.\n  replace [1; 2; 3; 4; 5] with ([1; 2; 3; 4] ++ 5 :: []) by auto; apply permutation_insert; simpl.\n  replace [1; 2; 3; 4] with ([1; 2] ++ 3 :: [4]) by auto; apply permutation_insert; simpl.\n  replace [1; 2; 4] with ([] ++ 1 :: [2; 4]) by auto; apply permutation_insert; simpl.\n  replace [2; 4] with ([] ++ 2 :: [4]) by auto; apply permutation_insert; simpl.\n  replace [4] with ([] ++ 4 :: []) by auto; apply permutation_insert; simpl.\n  apply permutation_nil.\nQed.\n\nTheorem permutation_small_example : permutation_small [5; 3; 1; 2; 4] [1; 2; 3; 4; 5].\nProof.\n  apply permutation_small_trans with [5; 1; 3; 2; 4].\n  apply permutation_small_cons.\n  apply permutation_small_swap.\n  apply permutation_small_trans with [1; 5; 3; 2; 4].\n  apply permutation_small_swap.\n  apply permutation_small_cons.\n  apply permutation_small_trans with [5; 2; 3; 4].\n  apply permutation_small_cons.\n  apply permutation_small_swap.\n  apply permutation_small_trans with [2; 5; 3; 4].\n  apply permutation_small_swap.\n  apply permutation_small_cons.\n  apply permutation_small_trans with [3; 5; 4].\n  apply permutation_small_swap.\n  apply permutation_small_cons.\n  apply permutation_small_swap.\nQed.\n\nEnd Example.\n\nTheorem permutation_small_refl : forall {A} (l : list A), permutation_small l l.\nProof.\n  induction l.\n  - apply permutation_small_empty.\n  - apply permutation_small_cons. auto.\nQed.\n\nTheorem permutation_refl : forall {A} (l : list A), permutation l l.\nProof.\n  induction l.\n  - apply permutation_nil.\n  - replace (a :: l) with ([] ++ a :: l) by auto. apply permutation_insert. auto.\nQed.\n\nTheorem permutation_refl_long : forall {A} (l1 l2 : list A), l1 = l2 -> permutation l1 l2.\nProof.\n  intros ? ? ? ->. apply permutation_refl.\nQed.\n\nLemma app_insert_split :\n  forall {A} a (l1 l2 l3 l4 : list A),\n  l1 ++ l2 = l3 ++ a :: l4 ->\n    (exists l5 : list A, l3 = l1 ++ l5 /\\ l2 = l5 ++ a :: l4) \\/\n    (exists l5 : list A, l4 = l5 ++ l2 /\\ l1 = l3 ++ a :: l5).\nProof.\n  intros ? a l1. induction l1; intros l2 l3 l4 ?.\n  - destruct l3.\n    + simpl in H. subst l2. left. exists []. auto.\n    + rename a0 into b. simpl in H. subst l2. left. exists (b :: l3). auto.\n  - rename a0 into b. destruct l3.\n    + injection H as -> <-. right. exists l1. auto.\n    + rename a0 into c. injection H as -> ?. specialize (IHl1 _ _ _ H). clear H.\n      destruct IHl1 as [(l5 & -> & ->) | (l5 & -> & ->)].\n      * left. exists l5. auto.\n      * right. exists l5. auto.\nQed.\n\nLemma permutation_split:\n  forall {A} a (l1 l2 l3 : list A),\n  permutation l1 (l2 ++ a :: l3) ->\n  exists l4 l5, l1 = l4 ++ a :: l5 /\\ permutation (l4 ++ l5) (l2 ++ l3).\nProof.\n  intros ? a l1 l2 l3 ?. remember (l2 ++ a :: l3) as l4. generalize dependent l2. induction H; intros l2' Heql4.\n  - destruct l2'; discriminate.\n  - rename a0 into b. destruct l2'.\n    + injection Heql4 as <- ->. exists l1, l2. auto.\n    + injection Heql4 as <- ->.\n      specialize (IHpermutation l2' eq_refl).  destruct IHpermutation as (l9 & l10 & ? & ?).\n      apply app_insert_split in H0. destruct H0 as [(l6 & -> & ->) | (l6 & -> & ->)].\n      * rewrite app_assoc in H1. exists (l1 ++ b :: l6), l10. simpl. split.\n        -- rewrite app_assoc. auto.\n        -- rewrite app_assoc. simpl. apply permutation_insert. auto.\n      * rewrite app_assoc in H. exists l9, (l6 ++ b :: l2). simpl. split.\n        -- rewrite app_assoc. auto.\n        -- rewrite <- app_assoc. apply permutation_insert. rewrite app_assoc. auto.\nQed.\n\nLemma permutation_move :\n  forall {A} a (l1 l2 l3 : list A),\n  permutation l1 (l2 ++ a :: l3) ->\n  permutation l1 (a :: l2 ++ l3).\nProof.\n  intros A a l1 l2 l3 ?.\n  apply permutation_split in H. destruct H as (l4 & l5 & -> & ?).\n  apply permutation_insert. auto.\nQed.\n\nTheorem permutation_trans :\n  forall {A} (l1 l2 l3 : list A),\n  permutation l1 l2 ->\n  permutation l2 l3 ->\n  permutation l1 l3.\nProof.\n  intros ? l1 l2 l3 ? ?.\n  generalize dependent l2. generalize dependent l1. induction l3; intros l1 l2 H1 H2.\n  - inversion H2. subst l2. auto.\n  - inversion H2. subst a0 l2 l5. clear H2.\n    apply permutation_move in H1.\n    inversion H1. subst a0 l1 l6. apply permutation_insert. apply IHl3 with (l0 ++ l4); auto.\nQed.\n\nTheorem permutation_sym :\n  forall {A} (l1 l2 : list A),\n  permutation l1 l2 ->\n  permutation l2 l1.\nProof.\n  intros ? l1 l2 ?. generalize dependent l1. induction l2; intros l1 ?.\n  - inversion H. apply permutation_nil.\n  - inversion H. subst a0 l1 l4. clear H. apply IHl2 in H2. clear IHl2.\n    generalize dependent l3. generalize dependent l2. induction l0; intros l2 l3 ?.\n    + simpl. simpl in H2. replace (a :: l2) with ([] ++ a :: l2) by auto.\n      apply permutation_insert. auto.\n    + rename a0 into b. simpl in H2. inversion H2. subst a0 l2 l5. simpl.\n      replace (a :: l1 ++ b :: l4) with ((a :: l1) ++ b :: l4) by auto.\n      apply permutation_insert. simpl. auto.\nQed.\n\nLemma permutation_move_back :\n  forall {A} a (l1 l2 l3 : list A),\n  permutation l1 (a :: l2 ++ l3) ->\n  permutation l1 (l2 ++ a :: l3).\nProof.\n  intros ? ? ? ? ? ?. apply permutation_trans with (a :: l2 ++ l3).\n  - auto.\n  - apply permutation_sym. apply permutation_move. apply permutation_refl.\nQed.\n\nTheorem permutation_cons :\n  forall {A} a (l1 l2 : list A),\n  permutation l1 l2 ->\n  permutation (a :: l1) (a :: l2).\nProof.\n  intros ? ? ? ? ?. replace (a :: l1) with ([] ++ a :: l1) by auto. apply permutation_insert. auto.\nQed.\n\nTheorem permutation_swap :\n  forall {A} a b (l1 l2 : list A),\n  permutation l1 l2 ->\n  permutation (b :: a :: l1) (a :: b :: l2).\nProof.\n  intros ? ? ? ? ? ?.\n  replace (b :: a :: l1) with ([b] ++ a :: l1) by auto. apply permutation_insert.\n  apply permutation_cons. auto.\nQed.\n\nTheorem permutation_small_permutation :\n  forall {A} (l1 l2 : list A),\n  permutation_small l1 l2 <-> permutation l1 l2.\nProof.\n  intros ? l1 l2. split.\n  - intros ?. induction H.\n    + apply permutation_nil.\n    + replace (a :: l1) with ([] ++ a :: l1) by auto. apply permutation_insert; auto.\n    + cut (permutation (b :: [a] ++ l) (a :: [b] ++ l)).\n      * auto.\n      * apply permutation_move. apply permutation_refl.\n    + clear H H0. apply permutation_trans with l2; auto.\n  - intros ?. induction H.\n    + apply permutation_small_empty.\n    + apply permutation_small_trans with (a :: l1 ++ l2).\n      * clear H IHpermutation l3. induction l1.\n        -- simpl. apply permutation_small_refl.\n        -- rename a0 into b. simpl. apply permutation_small_trans with (b :: a :: l1 ++ l2).\n           ++ apply permutation_small_cons. auto.\n           ++ apply permutation_small_swap.\n      * apply permutation_small_cons. auto.\nQed.\n\nTheorem permutation_length : forall {A} (l1 l2 : list A), permutation l1 l2 -> length l2 = length l1.\nProof.\n  intros ? ? ? ?. induction H.\n  - auto.\n  - rewrite length_app. rewrite length_app in IHpermutation. simpl. lia.\nQed.\n\nTheorem list_forall_permutation :\n  forall {A} f (l1 l2 : list A),\n  permutation l1 l2 ->\n  list_forall f l1 -> list_forall f l2.\nProof.\n  intros ? ? ? ? ?. induction H; intros ?.\n  - auto.\n  - simpl. apply list_forall_app in H0. simpl in H0.\n    rewrite list_forall_app in IHpermutation. intuition auto.\nQed.\n\nDefinition predicate_xor {A} f1 f2 := forall (x : A), f1 x = true /\\ f2 x = false \\/ f1 x = false /\\ f2 x = true.\n\nTheorem permutation_filter :\n  forall {A} (l : list A) f1 f2,\n  predicate_xor f1 f2 ->\n  permutation (filter f1 l ++ filter (fun x => f2 x) l) l.\nProof.\n  intros ? ? ? ? ?. induction l.\n  - simpl. apply permutation_nil.\n  - simpl. unfold predicate_xor in H. specialize (H a). destruct (f1 a), (f2 a).\n    + intuition auto; discriminate.\n    + simpl. apply permutation_cons. auto.\n    + simpl. apply permutation_insert. auto.\n    + intuition auto; discriminate.\nQed.\n\nTheorem permutation_same_head_inversion :\n  forall {A} a (l1 l2 : list A),\n  permutation (a :: l1) (a :: l2) ->\n  permutation l1 l2.\nProof.\n  intros ? ? ? ? ?. inversion H. subst a0 l4. destruct l0.\n  - injection H0 as ->. auto.\n  - injection H0 as -> <-. apply permutation_sym. apply permutation_move_back. apply permutation_sym. auto.\nQed.\n\nTheorem permutation_app_inversion :\n  forall {A} (l1 l2 l3 l4 : list A),\n  permutation (l1 ++ l3) (l2 ++ l4) ->\n  permutation l1 l2 ->\n  permutation l3 l4.\nProof.\n  intros ? ? ? ? ? ? ?. generalize dependent l4. generalize dependent l3. induction H0; intros l3_ l4_ ?.\n  - auto.\n  - rewrite app_assoc in H. simpl in H.\n    apply permutation_sym in H. apply permutation_move in H. apply permutation_sym in H.\n    apply permutation_same_head_inversion in H. apply IHpermutation. rewrite app_assoc. auto.\nQed.\n\nTheorem permutation_nil_inversion :\n  forall {A} (l : list A),\n  permutation l [] ->\n  l = [].\nProof.\n  intros ? ? ?. inversion H. auto.\nQed.\n\nTheorem permutation_single_inversion :\n  forall {A} a (l : list A),\n  permutation l [a] ->\n  l = [a].\nProof.\n  intros ? ? ? ?. inversion H. subst a0 l3. apply permutation_nil_inversion in H2.\n  apply app_nil_inversion in H2. destruct H2 as (-> & ->). auto.\nQed.\n\nTheorem permutation_single_inversion' :\n  forall {A} (a b : A),\n  permutation [a] [b] ->\n  a = b.\nProof.\n  intros ? ? ? ?. apply permutation_single_inversion in H. injection H as ->. auto.\nQed.\n\nTheorem permutation_cons_inversion :\n  forall {A} a b (l1 l2 : list A),\n  permutation (a :: l1) (b :: l2) ->\n  a = b \\/ list_in a l2 /\\ list_in b l1.\nProof.\n  intros ? ? ? ? ? ?. inversion H. subst a0 l4. destruct l0.\n  - injection H0 as -> ->. left. auto.\n  - injection H0 as -> <-. right. split.\n    + apply permutation_sym in H2. inversion H2. subst a0 l5. apply list_in_insert.\n    + apply list_in_insert.\nQed.\n\nTheorem permutation_app :\n  forall {A} (l1 l2 l3 l4 : list A),\n  permutation l1 l2 ->\n  permutation l3 l4 ->\n  permutation (l1 ++ l3) (l2 ++ l4).\nProof.\n  intros ? ?. induction l1; intros ? ? ? ? ?.\n  - apply permutation_sym in H. apply permutation_nil_inversion in H. subst l2. auto.\n  - apply permutation_sym in H. inversion H; subst a0 l1 l2; clear H.\n    apply permutation_sym. rewrite app_assoc. simpl. apply permutation_insert.\n    apply permutation_sym. rewrite <- app_assoc. apply IHl1.\n    + apply permutation_sym. auto.\n    + auto.\nQed.\n\nTheorem permutation_app_trans :\n  forall {A} (l1 l2 l3 l4 l5 : list A),\n  permutation (l1 ++ l2) l5 ->\n  permutation l1 l3 ->\n  permutation l2 l4 ->\n  permutation (l3 ++ l4) l5.\nProof.\n  intros ? ?. induction l1; intros ? ? ? ? ? ? ?.\n  - apply permutation_sym in H0. apply permutation_nil_inversion in H0. subst l3.\n    simpl. simpl in H. eauto using permutation_sym, permutation_trans.\n  - apply permutation_sym in H. apply permutation_move_back in H.\n    apply permutation_split in H. destruct H as (l6 & l7 & -> & ?).\n    apply permutation_sym in H0. inversion H0; subst a0 l1 l3; clear H0.\n    apply permutation_move_back. rewrite app_assoc. simpl. apply permutation_insert.\n    apply permutation_trans with (l8 ++ l2).\n    + clear H. rewrite <- app_assoc. apply IHl1 with l2.\n      * apply permutation_refl.\n      * apply permutation_sym. auto.\n      * auto.\n    + apply permutation_sym. auto.\nQed.\n", "meta": {"author": "afdw", "repo": "fav_coq", "sha": "e4c1cf35f3013be30f2fda9172019b17fa6257d1", "save_path": "github-repos/coq/afdw-fav_coq", "path": "github-repos/coq/afdw-fav_coq/fav_coq-e4c1cf35f3013be30f2fda9172019b17fa6257d1/Permutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7147605809807034}}
{"text": "(*\n  Introduction\n*)\nTheorem my_first_proof : (forall A : Prop, A -> A).\nProof.\n  intros A.\n  intros proof_of_A.\n  exact proof_of_A.\nQed.\n\n(*\n  Proofs with ->\n*)\nTheorem forward_small : (forall A B : Prop, A -> (A->B) -> B).\nProof.\n  intros A.\n  intros B.\n  intros proof_of_A.\n  intros A_implies_B.\n  pose (proof_of_B := A_implies_B proof_of_A).\n  exact proof_of_B.\nQed.\n\nTheorem backward_small : (forall A B : Prop, A -> (A->B)->B).\nProof.\n  intros A B.\n  intros proof_of_A A_implies_B.\n  refine (A_implies_B _).\n    exact proof_of_A.\nQed.\n\nTheorem backward_large : (forall A B C : Prop, A -> (A->B) -> (B->C) -> C).\nProof.\n  intros A B C.\n  intros proof_of_A A_implies_B B_implies_C.\n  refine (B_implies_C _).\n    refine (A_implies_B _).\n      exact proof_of_A.\nQed.\n\nTheorem backward_huge : (forall A B C : Prop, A -> (A->B) -> (A->B->C) -> C).\nProof.\n  intros A B C.\n  intros proof_of_A A_implies_B A_imp_B_imp_C.\n  refine (A_imp_B_imp_C _ _).\n    exact proof_of_A.\n\n    refine (A_implies_B _).\n      exact proof_of_A.\nQed.\n\nTheorem forward_huge : (forall A B C : Prop, A -> (A->B) -> (A->B->C) -> C).\nProof.\n  intros A B C.\n  intros proof_of_A A_implies_B A_imp_B_imp_C.\n  pose (proof_of_B := A_implies_B proof_of_A).\n  pose (proof_of_C := A_imp_B_imp_C proof_of_A proof_of_B).\n  exact proof_of_C.\nShow Proof.\nQed.\n\n(*\n  Boolean\n*)\n\n(*Inductive False : Prop := .\n\nInductive True : Prop :=\n  | I : True.*)\n\n(*Inductive bool : Set :=\n  | true : bool\n  | false : bool.*)\n\nTheorem True_can_be_proven : True.\n  exact I.\nQed.\n\nDefinition not (A : Prop) := A -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nTheorem False_cannot_be_proven : ~False.\nProof.\n  unfold not.\n  intros proof_of_False.\n  exact proof_of_False.\nQed.\n\nTheorem False_cannot_be_proven_again : ~False.\nProof.\n  intros proof_of_false.\n  case proof_of_false.\nQed.\n\nTheorem thm_true_imp_true : True -> True.\nProof.\n  intros proof_of_True.\n  exact I.\nQed.\n\nTheorem thm_false_imp_true : False -> True.\nProof.\n  intros proof_of_false.\n  exact I.\nQed.\n\nTheorem thm_false_imp_false : False -> False.\nProof. \n  intros proof_of_false.\n  case proof_of_false.\nQed.\n\nTheorem thm_true_imp_false : ~(True -> False).\nProof.\n  intros T_imp_F.\n  refine (T_imp_F _).\n   exact I.\nQed.\n\nTheorem absurd2 : forall A C : Prop, A -> ~ A -> C.\nProof.\n  intros A C.\n  intros proof_of_A proof_that_A_cannot_be_proven.\n  unfold not in proof_that_A_cannot_be_proven.\n  pose (proof_of_False := proof_that_A_cannot_be_proven proof_of_A).\n  case proof_of_False.\nQed.\n\nRequire Import Bool.\n\nTheorem true_is_True : Is_true true.\nProof.\n  simpl.\n  exact I.\nQed.\n\nTheorem not_eqb_true_false : ~(Is_true (eqb true false)).\nProof.\n  simpl.\n  exact False_cannot_be_proven.\nQed.\n\nTheorem eqb_a_a : (forall a : bool, Is_true (eqb a a)).\nProof.\n  intros a.\n  case a.\n    (*Suppose a is true*)\n    simpl.\n    exact I.\n    (*Suppose a is false*)\n    simpl.\n    exact I.\nQed.\n\nTheorem thm_eqb_a_t : (forall a:bool, (Is_true (eqb a true)) -> (Is_true a)).\nProof.\n  intros a.\n  case a.\n    (*Suppose a is true*)\n    simpl.\n    intros proof_of_true.\n    exact I.\n    (*Suppose a is false*)\n    simpl.\n    intros proof_of_false.\n    case proof_of_false.\nQed.\n\n(*\n  AND and OR\n*)\nTheorem left_or : (forall A B : Prop, A -> A \\/ B).\nProof.\n  intros A B.\n  intros proof_of_A.\n  pose (proof_of_A_or_B := or_introl proof_of_A : A \\/ B).\n  exact proof_of_A_or_B.\nQed.\n\nTheorem right_or : (forall A B : Prop, B -> A \\/ B).\nProof.\n  intros A B.\n  intros proof_of_B.\n  refine (or_intror _).\n    exact proof_of_B.\nQed.\n\nTheorem or_commutes : (forall A B : Prop, A \\/ B -> B \\/ A).\nProof.\n  intros A B.\n  intros A_or_B.\n  case A_or_B.\n    intros proof_of_A.\n    refine (or_intror _).\n      exact proof_of_A.\n\n    intros proof_of_B.\n    refine (or_introl _).\n      exact proof_of_B.\nQed.\n\nTheorem both_and : (forall A B : Prop, A -> B -> A /\\ B).\nProof.\n  intros A B.\n  intros proof_of_A proof_of_B.\n  refine (conj _ _).\n    exact proof_of_A.\n\n    exact proof_of_B.\nQed.\n\nTheorem and_commutes : (forall A B, A /\\ B -> B /\\ A).\nProof.\n  intros A B.\n  intros A_and_B.\n  destruct A_and_B as [ proof_of_A proof_of_B ].\n  refine (conj _ _).\n    exact proof_of_B.\n    exact proof_of_A.\n  (*case A_and_B.\n    intros proof_of_A proof_of_B.\n    refine (conj _ _).\n      exact proof_of_B.\n      \n      exact proof_of_A.*)\nQed.\n\nTheorem orb_is_or : (forall a b, Is_true (orb a b) <-> Is_true a \\/ Is_true b).\nProof.\n  intros a b.\n  unfold iff.\n  refine (conj _ _).\n    intros H.\n    case a, b.\n      (*T T*)\n      simpl.\n      refine (or_introl _).\n        exact I.\n      (*T F*)\n      exact (or_introl I).\n      (*F T*)\n      exact (or_intror I).\n      (*F F*)\n      simpl in H.\n      case H.\n  intros H.\n  case a, b.\n    (*T T*)\n    simpl.\n    exact I.\n    (*T F*)\n    exact I.\n    (*F T*)\n    exact I.\n    (*F F*)\n    case H.\n      (*H is (or_introl A)*)\n      intros A.\n      simpl in A.\n      case A.\n      \n      (*H is (or_intror B)*)\n      intros B.\n      simpl in B.\n      case B.\nQed.\n\nTheorem andb_is_and : (forall a b, Is_true (andb a b) <-> Is_true a /\\ Is_true b).\nProof.\n  intros a b.\n  unfold iff.\n  refine (conj _ _).\n    intros H.\n    case a, b.\n      (*T T*)\n      simpl.\n      exact (conj I I).\n      (*T F*)\n      simpl in H.\n      case H.\n      (*F T*)\n      simpl in H.\n      case H.\n      (*F F*)\n      simpl in H.\n      case H.\n     intros H.\n     case a, b.\n      (*T T*)\n      simpl.\n      exact I.\n      (*T F*)\n      simpl in H.\n      destruct H as [A B].\n      case B.\n      (*F T*)\n      simpl in H.\n      destruct H as [A B].\n      case A.\n      (*F F*)\n      simpl in H.\n      destruct H as [A B].\n      case A.\nQed.\n\n(*\n  Existence and Equality\n*)\nDefinition basic_predicate := \n  (fun a => Is_true (andb a true)).\n\nTheorem thm_exists_basics : (ex basic_predicate).\nProof.\n  pose (witness := true).\n  refine (ex_intro basic_predicate witness _).\n    unfold basic_predicate.\n    simpl.\n    exact I.\nQed.\n\nTheorem thm_exists_basics_again : (exists a, Is_true (andb a true)).\nProof. \n  pose (witness := true).\n  refine (ex_intro _ witness _).\n    simpl.\n    exact I.\nQed.\n\nTheorem thm_forall_exists : (forall b, (exists a, Is_true(eqb a b))).\nProof.\n  intros b.\n  case b.\n    (*b is True*)\n    pose (witness := true).\n    refine (ex_intro _ witness _).\n      simpl.\n      exact I.\n    (*b is False*)\n    pose (witness := false).\n    refine (ex_intro _ witness _).\n      simpl.\n      exact I.\nQed.\n\nTheorem thm_forall_exists_again : (forall b, (exists a, Is_true(eqb a b))).\nProof.\n  intros b.\n  refine (ex_intro _ b _).\n  exact (eqb_a_a b).\nQed.\n\nTheorem forall_exists : (forall P : Set->Prop, (forall x, ~(P x)) -> ~(exists x, P x)).\nProof.\n  intros P.\n  intros forall_x_not_Px.\n  unfold not.\n  intros exists_x_Px.\n  destruct exists_x_Px as [witness proof_of_Pwitness].\n  pose (not_Pwitness := forall_x_not_Px witness).\n  unfold not in not_Pwitness.\n  pose (proof_of_False := not_Pwitness proof_of_Pwitness).\n  case proof_of_False.\nQed.", "meta": {"author": "personal-practice", "repo": "coq", "sha": "df9a5f44b57323b02ba108126569a22e98b433e2", "save_path": "github-repos/coq/personal-practice-coq", "path": "github-repos/coq/personal-practice-coq/coq-df9a5f44b57323b02ba108126569a22e98b433e2/Tutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7147605675620644}}
{"text": "Require Import XR_Rmax.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rle_lt_trans.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rmax_Rlt : forall x y z, Rmax x y < z <-> x < z /\\ y < z.\nProof.\n  intros x y z.\n  split.\n  {\n    intro h.\n    unfold Rmax in h.\n    destruct (Rle_dec x y) as [ hl | hr ].\n    {\n      split.\n      {\n        apply Rle_lt_trans with y.\n        { exact hl. }\n        { exact h. }\n      }\n      { exact h. }\n    }\n    {\n      split.\n      { exact h. }\n      {\n        apply Rle_lt_trans with x.\n        {\n          left.\n          apply Rnot_le_lt.\n          exact hr.\n        }\n        { exact h. }\n      }\n    }\n  }\n  {\n    intros [ hx hy ].\n    unfold Rmax.\n    destruct (Rle_dec x y) as [ hl | hr ].\n    { exact hy. }\n    { exact hx. }\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rmax_Rlt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7146296645954966}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra ssrnum.\n\n(** ITERATIVE : Turning a recursive algo in an iterative one                  *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory Num.Theory Order.POrderTheory Num.ExtraDef Num.\n\nSection iterative.\n\nLocal Open Scope ring_scope.\n\n(* Arbitrary ring *)\nVariable R : ringType.\n\nImplicit Type p : {poly R}.\n\nVariable left : nat -> {poly R} -> {poly R}.\nVariable right : nat -> {poly R} -> {poly R}.\nVariable merge : nat -> {poly R} -> {poly R} -> {poly R}.\n\nHypothesis size_left : \n  forall n p, (size p <= 2 ^ n.+1 -> size (left n p) <= 2 ^ n)%N.\nHypothesis size_right : \n  forall n p, (size p <= 2 ^ n.+1 -> size (right n p) <= 2 ^ n)%N.\nHypothesis size_merge : \n  forall n (p q : {poly R}), (size p <= 2 ^ n -> size q <= 2 ^ n -> \n               size (merge n p q) <= 2 ^ n.+1)%N.\nHypothesis merge0 : forall n, merge n 0 0 = 0. \n\nFixpoint algo (n : nat) (p : {poly R}) := \n  if n is n1.+1 then \n    merge n1 (algo n1 (left n1 p)) (algo n1 (right n1 p)) \n  else (p`_0)%:P.\n\nLemma size_algo n p : (size (algo n p) <= 2 ^ n)%N.\nProof.\nelim: n p => /= [|n IH] p; first by rewrite size_polyC; case: eqP.\nby apply: size_merge; apply: IH.\nQed.\n\nFixpoint bottom (n : nat) (p : {poly R}) := \n  if n is n1.+1 then \n    bottom n1 (left n1 p) + 'X^(2 ^n1) * bottom n1 (right n1 p)\n  else (p`_0)%:P.\n\nLemma size_bottom n p : (size (bottom n p) <= 2 ^ n)%N.\nProof.\nelim: n p => /= [|n IH] p; first by apply: size_polyC_leq1.\napply: leq_trans (size_add _ _) _.\nrewrite geq_max (leq_trans (IH _)) //=; last by rewrite leq_exp2l.\napply: leq_trans (size_mul_leq _ _) _.\nby rewrite size_polyXn expnS mul2n -addnn leq_add.\nQed.\n\nDefinition left_poly m (p : {poly R}) := \\poly_(i < m) p`_i.\nDefinition right_poly m (p : {poly R}) := \\poly_(i < m) p`_(i + m).\n\nLemma coef_left_poly m p i : \n  (left_poly m p)`_ i = if (i < m)%N then p`_ i else 0.\nProof. by rewrite coef_poly. Qed.\n\nLemma coef_right_poly m p i : \n  (right_poly m p)`_ i = if (i < m)%N then p`_ (i + m) else 0.\nProof. by rewrite coef_poly. Qed.\n\nLemma left_poly_id m p : (size p <= m)%N -> left_poly m p = p.\nProof.\nmove=> Hs; apply/polyP => i.\nrewrite coef_poly; case: leqP => // Hs1.\nby apply/sym_equal/nth_default/(leq_trans Hs).\nQed.\n\nLemma left_polyMXn m p : left_poly m ('X^ m * p) = 0.\nProof.\napply/polyP => i.\nrewrite -[_ * p]commr_polyXn coef_poly coefMXn coef0.\nby case: leqP.\nQed.\n\nLemma left_poly_add m (p q : {poly R}) :\n  left_poly m (p + q) = left_poly m p + left_poly m q.\nProof.\napply/polyP => i; rewrite !(coefD, coef_poly).\nby case: leqP; rewrite ?add0r.\nQed.\n\nLemma left_poly0 m : left_poly m 0 = 0.\nProof. by apply/polyP => i; rewrite coef_poly coef0 if_same. Qed.\n\nLemma left_poly_sum m n (p : 'I_n -> {poly R}) :\n  left_poly m (\\sum_(i < n) p i) = \\sum_(i < n) (left_poly m (p i)).\nProof.\nhave F (q : nat -> _) : \n       left_poly m (\\sum_(i < n) q i) = \\sum_(i < n) (left_poly m (q i)).\n  elim: n {p}q => [|n IH] q; first by rewrite !big_ord0 left_poly0.\n  by rewrite !big_ord_recr /= left_poly_add IH.\ncase: n p F => [|n] p F; first by rewrite !big_ord0 left_poly0.\nhave := F (fun x => p (inord x)).\nunder eq_bigr do rewrite inord_val.\nby under [X in _ = X -> _]eq_bigr do rewrite inord_val.\nQed.\n\nLemma right_poly_size_0 m p : (size p <= m)%N -> right_poly m p = 0.\nProof.\nmove=> Hs; apply/polyP => i.\nrewrite coef_poly coef0; case: leqP => // Hs1.\napply: nth_default.\nby apply: leq_trans Hs (leq_addl _ _).\nQed.\n\nLemma right_polyMXn m p : (size p <= m)%N -> right_poly m ('X^ m * p) = p.\nProof.\nmove=> Hs; apply/polyP => i.\nrewrite -[_ * p]commr_polyXn coef_poly coefMXn addnK.\nrewrite [(_ + _ < _)%N]ltnNge leq_addl /=.\ncase: leqP => // mLi.\nby apply/sym_equal/nth_default/(leq_trans _ mLi).\nQed.\n\nLemma right_poly_add m (p q : {poly R}) :\n  right_poly m (p + q) = right_poly m p + right_poly m q.\nProof.\napply/polyP => i; rewrite !(coefD, coef_poly).\nby case: leqP; rewrite ?add0r.\nQed.\n\nLemma right_poly0 m : right_poly m 0 = 0.\nProof. by apply/polyP => i; rewrite coef_poly !coef0 if_same. Qed.\n\nLemma right_poly_sum m n (p : 'I_n -> {poly R}) :\n  right_poly m (\\sum_(i < n) p i) = \\sum_(i < n) (right_poly m (p i)).\nProof.\nhave F (q : nat -> _) : \n       right_poly m (\\sum_(i < n) q i) = \\sum_(i < n) (right_poly m (q i)).\n  elim: n {p}q => [|n IH] q; first by rewrite !big_ord0 right_poly0.\n  by rewrite !big_ord_recr /= right_poly_add IH.\ncase: n p F => [|n] p F; first by rewrite !big_ord0 right_poly0.\nhave := F (fun x => p (inord x)).\nunder eq_bigr do rewrite inord_val.\nby under [X in _ = X -> _]eq_bigr do rewrite inord_val.\nQed.\n\nLemma left_right_polyE m p :\n  (size p <= m.*2)%N -> p = left_poly m p + right_poly m p * 'X^m.\nProof.\nmove=> sL2m; apply/polyP => i.\nrewrite coefD coefMXn !coef_poly.\ncase: leqP => HlP; last by rewrite addr0.\ncase: leqP => H1lP; last by rewrite subnK ?add0r.\nrewrite add0r nth_default //.\napply: leq_trans sL2m _.\nby rewrite -addnn -leq_subRL.\nQed.\n\nFixpoint invariant_algo m n p q :=\n  if m is m1.+1 then \n  invariant_algo m1 n (left (m1 + n) p) (left_poly (2 ^ (m1 + n)) q) /\\ \n  invariant_algo m1 n (right (m1 + n) p) (right_poly (2 ^ (m1 + n)) q)\n  else q = algo n p.\n\nLemma invariantS_algo m n p q :\n  invariant_algo m.+1 n p q <->\n  invariant_algo m n (left (m + n) p) (left_poly (2 ^ (m + n)) q) /\\ \n  invariant_algo m n (right (m + n) p) (right_poly (2 ^ (m + n)) q).\nProof. by []. Qed.\n\nLemma invariant_algo_bottom p m :\n  invariant_algo m 0 p (bottom m p).\nProof.\nelim: m p => //= m IH p.\nrewrite addn0 left_poly_add right_poly_add; split.\n  rewrite left_polyMXn addr0 left_poly_id; first by by apply: IH.\n  by apply: size_bottom.\n  \nrewrite (right_poly_size_0 (size_bottom _ _)) add0r.\nrewrite right_polyMXn; last by apply: size_bottom.\nby apply: IH.\nQed.\n\nDefinition step m n (p : {poly R}) :=\n  \\sum_(l < 2 ^ m)\n  let le := \\poly_(i < 2 ^ n) p`_(i + l * 2 ^ n.+1) in\n  let ri := \\poly_(i < 2 ^ n) p`_(i + l * 2 ^ n.+1 + 2 ^ n) in\n    merge n le ri * 'X^(l * 2 ^ n.+1).\n\nLemma size_step m n p : (size (step m n p) <= (2 ^ (m + n).+1))%N.\nProof.\napply: leq_trans (size_sum _ _ _) _.\napply/bigmax_leqP_seq => i _ _.\napply: leq_trans (size_mul_leq _ _ ) _.\nrewrite size_polyXn addnS /=.\napply: leq_trans (leq_add (size_merge (size_poly _ _) (size_poly _ _)) \n                          (leqnn _)) _.\nby rewrite -mulSn -addnS expnD leq_mul2r ltn_ord orbT.\nQed.\n\nLemma left_step m n (p : {poly R}) :\n  (size p <= 2 ^ (m + n).+2)%N ->\n  left_poly (2 ^ (m + n).+1) (step m.+1 n p) =\n  step m n (left_poly (2 ^ (m + n).+1) p).\nProof.\nmove=> pLmn.\napply/polyP=> i; rewrite coef_left_poly.\ncase: leqP => [mnLi|iLmn].\n  rewrite nth_default //.\n  by apply: leq_trans (size_step _ _ _) _.\nrewrite !coef_sum expnS mul2n -addnn big_split_ord /=.\nrewrite [X in _ + X = _]big1 ?addr0 => [|j _]; last first.\n  by rewrite coefMXn ifT // (leq_trans iLmn) // mulnDl -expnD addnS leq_addr.\napply: eq_bigr => j _.\ncongr ((merge _ _ _ * _) `_ _).\n  apply/polyP => k; rewrite !coef_poly.\n  case: leqP => // kLn.\n  rewrite ifT // -[in X in (_ < X)%N]addnS expnD.\n  rewrite -[X in (_ < X * _)%N]prednK ?expn_gt0 // mulSn -addSn.\n  apply: leq_add.\n    by apply: leq_trans kLn _; rewrite leq_exp2l.\n  by rewrite leq_mul2r -ltnS prednK ?expn_gt0 // ltn_ord orbT.\napply/polyP => k; rewrite !coef_poly.\ncase: leqP => // kLn.\nrewrite ifT // -[in X in (_ < X)%N]addnS expnD addnAC.\nrewrite -[X in (_ < X * _)%N]prednK ?expn_gt0 // mulSn -addSn.\napply: leq_add.\n  by rewrite expnS mul2n -addnn ltn_add2r.\nby rewrite leq_mul2r -ltnS prednK ?expn_gt0 // ltn_ord orbT.\nQed.\n\nLemma right_step m n (p : {poly R}) :\n  (size p <= 2 ^ (m + n).+2)%N ->\n  right_poly (2 ^ (m + n).+1) (step m.+1 n p) =\n  step m n (right_poly (2 ^ (m + n).+1) p).\nProof.\nmove=> pLmn.\napply/polyP=> i; rewrite coef_right_poly.\ncase: leqP => [mnLi|iLmn].\n  rewrite nth_default //.\n  by apply: leq_trans (size_step _ _ _) _.\nrewrite !coef_sum expnS mul2n -addnn big_split_ord /=.\nrewrite [X in X + _ = _]big1 ?add0r => [|j _]; last first.\n  rewrite coefMXn ifN; last first.\n    rewrite -leqNgt (leq_trans _ (leq_addl _ _)) //.\n    by rewrite -addnS expnD leq_mul2r // ltnW ?orbT.\n  rewrite nth_default // (leq_trans (size_merge _ _)) // ?size_poly //.\n  rewrite leq_subRL (leq_trans _ (leq_addl _ _)) //.\n    by rewrite addnC -mulSn -addnS expnD leq_mul2r ltn_ord orbT.\n  by rewrite -addnS expnD leq_mul2r ltnW ?orbT // ltn_ord.\napply: eq_bigr => j _.\nrewrite !coefMXn addnC mulnDl -expnD addnS ltn_add2l.\ncase: leqP => // jLi; rewrite subnDl.\ncongr ((merge _ _ _) `_ _).\n  apply/polyP => k; rewrite !coef_poly.\n  case: leqP => // kLn.\n  rewrite ifT; first by rewrite addnAC addnA.\n  rewrite -[in X in (_ < X)%N]addnS expnD.\n  rewrite -[X in (_ < X * _)%N]prednK ?expn_gt0 // mulSn -addSn.\n  apply: leq_add.\n    by apply: leq_trans kLn _; rewrite leq_exp2l.\n  by rewrite leq_mul2r -ltnS prednK ?expn_gt0 // ltn_ord orbT.\napply/polyP => k; rewrite !coef_poly.\ncase: leqP => // kLn.\nrewrite ifT.\n  rewrite -!addnA.\n  congr (_ `_ (_ + _)); first by rewrite addnC !addnA.\nrewrite addnAC -[in X in (_ < X)%N]addnS expnD.\nrewrite -[X in (_ < X * _)%N]prednK ?expn_gt0 // mulSn -addSn.\napply: leq_add.\n  by rewrite expnS mul2n -addnn ltn_add2r.\nby rewrite leq_mul2r -ltnS prednK ?expn_gt0 // ltn_ord orbT.\nQed.\n\nLemma invariant_algo_step m n p p1 :\n  (size p <= 2 ^ (m + n).+1)%N ->\n  (size p1 <= 2 ^ (m + n).+1)%N ->\n  invariant_algo m.+1 n p p1 ->\n  invariant_algo m n.+1 p (step m n p1).\nProof.\nelim: m n p p1; last first.\n  move=> m IH n p p1 Hsp Hsp1/invariantS_algo[H2 H3].\n  apply/invariantS_algo; split.\n    rewrite addnS left_step //.\n    apply: IH => //.\n      by apply: leq_trans (size_left _) _.\n    by rewrite size_poly.\n  rewrite addnS right_step //.\n  apply: IH => //.\n    by apply: leq_trans (size_right _) _.\n  by rewrite size_poly.\nmove=> n p p1; rewrite add0n => Hp Hp1 [H1 H2].\nrewrite /= -H1 -H2.\nrewrite /step big_ord1 mul0n mulr1.\nby congr (merge _ _ _); apply/polyP=> i; rewrite !coef_poly !add0n !addn0.\nQed.\n\nFixpoint istep_aux m n p :=\n  if m is m1.+1 then  istep_aux m1 n.+1 (step m1 n p) else p.\n\nDefinition istep n p := istep_aux n 0 (bottom n p).\n\nLemma istep_algo n p : (size p <= 2 ^ n)%N -> istep n p = algo n p.\nProof.\nmove=> Hs.\nsuff /(_ n 0%N): forall m1 n1 (p1 q1 : {poly R}), \n    (size p1 <= 2 ^ (m1 + n1))%N ->\n    (size q1 <= 2 ^ (m1 + n1))%N ->\n    invariant_algo m1 n1 p1 q1 -> \n    invariant_algo 0 (m1 + n1) p1 (istep_aux m1 n1 q1).\n  rewrite addn0; apply => //; first by apply: size_bottom.\n  by apply: invariant_algo_bottom.\nelim => [//| m1 IH] n1 p1 q1 Hs1 Hs2 H1.\nrewrite /istep_aux -/istep_aux addSnnS.\napply: IH; first by rewrite addnS.\n  rewrite addnS.\n  by apply: leq_trans (size_step _ _ _) _.\nby apply: invariant_algo_step.\nQed.\n\nEnd iterative.\n", "meta": {"author": "thery", "repo": "mathcomp-extra", "sha": "e776299ceebf276502a6ee1a787febf5c806293d", "save_path": "github-repos/coq/thery-mathcomp-extra", "path": "github-repos/coq/thery-mathcomp-extra/mathcomp-extra-e776299ceebf276502a6ee1a787febf5c806293d/iterative.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7146232496233946}}
{"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\nCompute (next_weekday friday).\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nInductive bool : Type :=\n| true  : bool\n| false : bool.\n\nDefinition negb (b:bool) : bool :=\n  match b with\n  | true => false\n  | fase => 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\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(*\n\n  1d star. nandb.\n  The function should return true if either or both of its inputs are false.\n *)\n\nDefinition nandb (b1:bool) (b2:bool) : bool :=\n  match b1 with\n  | true => negb b2\n  | false => true\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\nExample test_nandb3: (nandb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nandb4: (nandb true true) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=\n  (b1 && b2 && b3).\n\nExample test_and31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_and32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_and33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_and34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\nCheck true.\n(* ===> true : bool *)\nCheck (negb true).\n(* ===> negb true : bool *)\nCheck negb.\n(* ===> negb : bool -> bool *)\n\nInductive rgb : Type :=\n| red : rgb\n| green : rgb\n| blue : rgb.\n\nInductive color : Type :=\n  | black : color\n  | white : color\n  | primary : rgb -> color.\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black => true\n  | white => false\n  | primary p => false\n  end.\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.", "meta": {"author": "seisyuu-hantatsushi", "repo": "coq-sf", "sha": "9f5088870d6734cebbbe9937f40b89b04ebd206b", "save_path": "github-repos/coq/seisyuu-hantatsushi-coq-sf", "path": "github-repos/coq/seisyuu-hantatsushi-coq-sf/coq-sf-9f5088870d6734cebbbe9937f40b89b04ebd206b/lf/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.7146232481449268}}
{"text": "Require Import Omega.\nRequire Import prelims.\nRequire Import repeater.\nRequire Import increasing_expanding.\nRequire Import inverse.\n\n(*\n==================================================================================\n***************************** SECTION 5: COUNTDOWN  *****************************\n==================================================================================\n *)\n\n(* \n * Earlier we explored how to compute inverse of a function's repeater \n * solely from the function's own inverse, without directly computing the \n * repeater itself. The first lemma addresses this.\n *\n * We base the definition of \"contractions\" and \"countdown\" on this observation.\n * We also give a computation for countdown and prove several useful results \n * about it. \n * \n * The inverse of (repeater_from a F) is the minimum number of applications\n * of (inverse F) to the input to get a result less than or equal to a.\n *  This serves as motivation to contractions and countdown \n *)\nLemma upp_inv_repeater :\n  forall a f F f',\n    upp_inv_rel f F ->\n    upp_inv_rel f' (repeater_from F a) ->\n    (forall n m, f' n <= m <-> repeat f m n <= a).\nProof.\n  intros a f F f' HfF Hf'F n m.\n  rewrite (Hf'F m n). rewrite repeater_from_repeat.\n  symmetry. apply (upp_inv_repeat m f F HfF a n).\nQed.\n\n\n(* ****** CONTRACTIONS ****** *)\n\n(* Definition of non-strict contractions *)\nDefinition contracting (f : nat -> nat) : Prop :=\n  forall n, f n <= n.\n\n(* Definition of strict expansion *)\nDefinition contract_strict_above (a : nat) (f : nat -> nat) : Prop :=\n  contracting f /\\ (forall n, a < n -> f n < n).\n\n(* Upper inverses of expansions are contractions *)\nTheorem upp_inv_expand_contract :\n    forall f F, expanding F -> upp_inv_rel f F -> contracting f.\nProof.\n  intros f F HF HfF n. rewrite (HfF n n). apply HF.\nQed.\n\n(* Upper inverses of \"strict-from-a expansions\" themselves contract above a *)\nTheorem upp_inv_expand_contract_strict :\n  forall a f F,\n    expand_strict_from a F ->\n      upp_inv_rel f F -> contract_strict_above a f.\nProof.\n  intros a f F HF HfF. destruct HF as [HF HaF].\n  split.\n  1: apply (upp_inv_expand_contract _ F HF HfF). \n  intro n. destruct n; [omega|]. repeat rewrite <- lt_S_le.\n  rewrite (HfF n _). apply HaF.\nQed.\n\n\n(* ****** PROPERTIES OF CONTRACTIONS *******)\n\n(* Repeat of contractions make the result smaller *)\nLemma repeat_contract :\n  forall f n k l,\n    contracting f -> k <= l -> repeat f l n <= repeat f k n.\nProof.\n  intros f n k l Hf Hkl. induction l; inversion Hkl; trivial.\n  apply IHl in H0.\n  apply (Nat.le_trans _ (repeat f l n) _); [apply Hf | apply H0].\nQed.\n\n(* Stricter version of the above *)\nLemma repeat_contract_strict :\n  forall a f n k,\n    contract_strict_above a f ->\n    S a <= repeat f k n -> (S k) + repeat f (S k) n <= n.\nProof.\n  intros a f n k Hf Han. destruct Hf as [Hf Haf]. induction k.\n  1: simpl in Han; simpl; apply Haf in Han; omega. \n  apply (Nat.le_trans _ (S k + repeat f (S k) n) _).\n  - apply Haf in Han. simpl in Han; simpl. omega.\n  - assert (S a <= repeat f k n) as Han0.\n    { apply (Nat.le_trans _ (repeat f (S k) n) _); [apply Han|].\n      apply Haf in Han. simpl. apply Hf. }\n    apply IHk in Han0. omega.\nQed.\n\n\n\n(* ****** COUNTDOWN ****** *)\n\n(* Repeats \"f\" \"k\" times over, or until we go below \"a\".\n   Outputs \"min(k, min{l : repeat f l n <= a})\" *)\nFixpoint cdn_wkr (f : nat -> nat) (a : nat)  (n k : nat) : nat :=\n  match k with\n  | 0    => 0\n  | S k' => if (n <=? a) then 0 else\n             S (cdn_wkr f a (f n) k')\n  end.\n\n(* Actual defintion. We give the worker a budget of \"n\" steps, which\n   guarantees that it reaches below \"a\" before terminating *)\nDefinition countdown_to f a n := cdn_wkr f a n n.\n\n\n\n(* ****** COUNTDOWN CORRECTNESS THEOREMS ****** *)\n\n(* INITIAL VALUE THEOREM\n   Basically countdown returns 0 if \"n\" is already below \"a\" *)\nTheorem countdown_init :\n  forall a f n k, n <= a -> cdn_wkr f a n k = 0.\nProof.\n  intros a f n k Hna.\n  destruct k; trivial.\n  rewrite <- Nat.leb_le in Hna.\n  unfold cdn_wkr. rewrite Hna; trivial.\nQed.\n\n(* EXISTENCE OF COUNTDOWN VALUE LEMMA *)\n(* Basically the existence of the countdown value for strict contractions\n   It asserts there is a minimum \"l\" for which repeating \"f\" \"l\" times from \"n\"\n   will give a result less than or equal to \"a\" *)\nLemma repeat_contract_strict_threshold :\n  forall a f n,\n    contract_strict_above a f -> a < n ->\n    exists l, (S l) <= n /\\ repeat f (S l) n <= a < repeat f l n.\nProof.\n  intros a f n Hf Han. destruct Hf as [Hf Haf].\n  remember (n - a) as m.\n  destruct m; [omega|].\n  assert (forall b, (a <= b) -> f (S b) <= b) as Ha\n      by (intros b Hab; rewrite le_S_n_m; apply Haf; omega).\n  generalize dependent a.\n  induction m.\n  - intros. exists 0.\n    simpl. split; [|split];\n    [|replace n with (S a) by omega; apply Ha|]; omega.\n  - intros. destruct (IHm (S a)); try omega.\n    + intros p Hp. apply Haf. omega.\n    + intros b Hab. apply Ha. omega.\n    + destruct H as [H0 H1]. destruct H1 as [Hl Hr]. inversion Hl.\n      2: exists x; split; [apply H0 | omega].\n      exists (S x). simpl. rewrite H1. split.\n      2: split; [apply Ha|]; omega.\n      apply (Nat.le_trans _ (S x + (repeat f (S x) n)) _);\n                  [simpl; rewrite H1; omega|].\n      apply (repeat_contract_strict a f n x);\n      [split; assumption | omega].\nQed.\n\n\n(* INTERMEDIATE STATE LEMMA\n   Similar to the general recursion formula for \"countdown_recurse_rel\" *)\nTheorem countdown_intermediate :\n  forall a f n k i,\n    contracting f ->\n    S i <= k ->\n    a < repeat f i n ->\n    cdn_wkr f a n k =\n    (S i) + cdn_wkr f a (repeat f (S i) n) (k - (S i)).\nProof.\n  assert (forall a f n k,\n             contracting f -> 1 <= k -> a < n ->\n             cdn_wkr f a n k =\n             1 + cdn_wkr f a (f n) (k - 1) ) as case_0.\n  { simpl. intros a f n k Hf Hk Ha. destruct k; [omega|].\n    replace (S k - 1) with k by omega. unfold cdn_wkr.\n    rewrite Nat.lt_nge, <- Nat.leb_nle in Ha. rewrite Ha. trivial.\n  }\n  intros a f n k i Hf Hik Hai.\n  induction i; [simpl; apply case_0; trivial|].\n  rewrite IHi; [|omega|].\n  2: apply (Nat.le_trans _ (repeat f (S i) n) _);\n     [trivial | apply Hf].\n  simpl. remember (f (repeat f i n)) as m. remember (k - S i) as l.\n  replace (k - S(S i)) with (l - 1) by omega.\n  rewrite case_0; [omega | trivial | omega|].\n  simpl in Hai. rewrite Heqm. trivial.\nQed.\n\n(* COUNTDOWN VS REPEAT THEOREM\n   Correctness theorem for this countdown defintion *)\nTheorem countdown_repeat :\n  forall a f n k,\n    contract_strict_above a f ->\n      countdown_to f a n <= k <-> repeat f k n <= a.\nProof.\n  intros a f n k Haf. inversion Haf as [Hf _].\n  unfold countdown_to; split.\n  - intro. rewrite not_lt. intro.\n    rewrite (countdown_intermediate a f n n k Hf) in H;\n      [omega | trivial..].\n    apply (Nat.le_trans _ (S k + (repeat f (S k) n)) _); [omega|].\n    apply (repeat_contract_strict a f n k Haf H0). \n  - intro. destruct k.\n    1: simpl in H; rewrite (countdown_init a f n); omega; apply H. \n    remember (n - a) as m.\n    destruct m; [rewrite countdown_init; omega|]. \n    destruct (repeat_contract_strict_threshold a f n Haf); [omega|].\n    destruct H0 as [Hx0 [Hxl Hxr]].\n    assert (cdn_wkr f a n n = S x) as Hx.\n    { rewrite (countdown_intermediate a f n n x); trivial.\n      rewrite countdown_init; [omega | trivial].\n    }\n    rewrite Hx. apply not_le. intro.\n    apply (repeat_contract f n (S k) x) in H0; [omega | apply Hf].\nQed.\n\n(* RECURSION FOR CONTRACTORS THEOREM *)\nTheorem countdown_recursion :\n  forall a f n,\n    contract_strict_above a f ->\n    (n <= a -> countdown_to f a n = 0) /\\\n    (a < n -> countdown_to f a n = S (countdown_to f a (f n))).\nProof.\n  intros a f n Hf. split.\n  1: intro Han; unfold countdown_to; apply countdown_init; apply Han.\n  intro Han.\n  assert (countdown_to f a n <= S (countdown_to f a (f n))) as G1.\n  { rewrite countdown_repeat by apply Hf.\n    rewrite repeat_S_comm.\n    rewrite <- countdown_repeat by apply Hf.\n    trivial. }\n  assert (1 <= countdown_to f a n) as G0.\n  { rewrite le_lt_S. rewrite <- not_le.\n    rewrite countdown_repeat by apply Hf.\n    simpl. omega. }\n  assert (countdown_to f a (f n) <= countdown_to f a n - 1).\n  { rewrite countdown_repeat by apply Hf.\n    rewrite <- repeat_S_comm.\n    replace (S (countdown_to f a n - 1)) with\n              (countdown_to f a n) by omega.\n    rewrite <- countdown_repeat by apply Hf. trivial. }\n  omega.\nQed.\n\nCorollary countdown_antirecursion :\n  forall a f n,\n    contract_strict_above a f ->\n      countdown_to f a (f n) = countdown_to f a n - 1.\nProof.\n  intros a f n Haf.\n  assert (H := Haf).\n  destruct (Nat.lt_ge_cases a n) as [Han | Han];\n    apply (countdown_recursion a f n) in H.\n  1: apply H in Han; omega.\n  assert (f n <= a) as Hafn\n      by (apply (Nat.le_trans _ n _); [apply Haf | apply Han]).\n  apply (countdown_recursion a f (f n)) in Haf.\n  apply Haf in Hafn. apply H in Han. omega.\nQed.\n\n\n(* STRICT CONTRACTIVENESS PRESERVATION THEOREM *)\nTheorem countdown_contract_strict :\n  forall a f t,\n    1 <= a ->\n    contract_strict_above a f ->\n    contract_strict_above t (countdown_to f a).\nProof.\n  intros a f t Ha Haf. split.\n  - intro n. rewrite countdown_repeat by apply Haf.\n    rewrite not_lt. intro.\n    apply repeat_contract_strict in H; [omega | apply Haf..].\n  - intros n Hn. destruct n; [omega|]. rewrite <- lt_S_le.\n    rewrite countdown_repeat by apply Haf. destruct n;  trivial.\n    remember (repeat f n (S (S n)) - a) as m. destruct m.\n    1: apply (Nat.le_trans _ (repeat f n (S (S n))) _);\n       [apply Haf | omega]. \n    assert (S n + repeat f (S n) (S (S n)) <= (S n) + a)\n      by (apply (Nat.le_trans _ (S (S n)) _);\n          [apply (repeat_contract_strict a _ _ _ Haf)|]; omega).\n    omega.\nQed.\n\n(* ****** COUNTDOWN - REPEATER - INVERSE PRESERVATION **************** *)\n\n(* \n * This theorem is important. \n * It says that countdown and repeater will preserve the \n * upper inverse relation on their respective results.\n * We need this to prove the correctness of inverse hyperoperations and\n *  inverse Ackermann towers built with countdown later on \n *)\nTheorem countdown_repeater_upp_inverse :\n  forall a f F,\n    expand_strict_from a F ->\n    upp_inv_rel f F ->\n    upp_inv_rel (countdown_to f a) (repeater_from F a).\nProof.\n  intros a f F HaF HfF n N.\n  apply (upp_inv_expand_contract_strict a f F) in HaF; [|trivial].\n  rewrite repeater_from_repeat. apply (upp_inv_repeat n _ _) in HfF.\n  rewrite <- (HfF a N). apply countdown_repeat. trivial.\nQed.", "meta": {"author": "inv-ack", "repo": "inv-ack", "sha": "195209ba895061fc51368c3c46c1d8760f05df50", "save_path": "github-repos/coq/inv-ack-inv-ack", "path": "github-repos/coq/inv-ack-inv-ack/inv-ack-195209ba895061fc51368c3c46c1d8760f05df50/countdown.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7146232435204977}}
{"text": "Require Import Tree List Omega.\n\nSet Implicit Arguments.\n\nInductive BaseTree := B: list BaseTree -> BaseTree.\n\nSection ListProp.\n  Variable A: Type.\n  Variable def: A.\n  Theorem appLastNth: forall l i a, i = length l -> nth i (l ++ (a :: nil)) def = a.\n  Proof.\n    intros l.\n    induction l.\n    intros i a i_len.\n    simpl in *.\n    rewrite i_len.\n    auto.\n    intros i a0 i_len.\n    unfold length in i_len.\n    fold (length l) in i_len.\n    rewrite i_len.\n    unfold app.\n    fold (app l (a0 :: nil)).\n    simpl.\n    specialize (IHl (length l) a0).\n    assert (length l = length l) by auto.\n    specialize (IHl H).\n    assumption.\n  Qed.\n\n  Theorem appNotLastNth: forall l i a, i < length l -> nth i (l ++ (a :: nil)) def = nth i l def.\n  Proof.\n    intros l.\n    induction l.\n    intros i a i_len.\n    simpl in *.\n    omega.\n    intros i a0 i_len.\n    unfold app.\n    fold (app l (a0::nil)).\n    destruct i.\n    simpl.\n    auto.\n    simpl.\n    simpl in i_len.\n    assert (i < length l) by omega.\n    specialize (IHl i a0 H).\n    assumption.\n  Qed.\n\n  Theorem appLen: forall (l: list A) a, length (l ++ a :: nil) = S (length l).\n  Proof.\n    intros l a.\n    induction l.\n    simpl.\n    auto.\n    unfold app.\n    fold (app l (a :: nil)).\n    simpl.\n    omega.\n  Qed.\n\n  Theorem revLen: forall (l: list A), length l = length (rev l).\n  Proof.\n    intros l.\n    induction l.\n    simpl.\n    auto.\n    simpl.\n    pose proof (appLen (rev l) a).\n    rewrite H; clear H.\n    omega.\n  Qed.\n\n  Theorem revProp: forall l i, i < length l -> nth i l def = nth (length l - S i) (rev l) def.\n  Proof.\n    intros l.\n    induction l.\n    intros i i_lt_len.\n    simpl in *.\n    omega.\n    intros i i_lt_len.\n    unfold rev.\n    fold (rev l).\n    unfold length.\n    fold (length l).\n    assert (S (length l) - S i = (length l) - i) by omega.\n    rewrite H.\n    clear H.\n    destruct i.\n    simpl.\n    assert (length l - 0 = length l) by omega.\n    rewrite H; clear H.\n    pose proof (revLen l) as H.\n    rewrite H; clear H.\n    assert (length (rev l) = length (rev l)) by reflexivity.\n    pose proof (appLastNth _ a H).\n    rewrite H0.\n    auto.\n    simpl in i_lt_len.\n    pose proof (revLen l) as H.\n    assert (length l - S i < length (rev l)) by omega.\n    pose proof (appNotLastNth _ a H0).\n    rewrite H1.\n    simpl.\n    assert (i < length l) by omega.\n    specialize (IHl i H2).\n    assumption.\n  Qed.\n\n  Section EqLen.\n    Context (l: list A).\n    Context {B: Type}.\n    Context (f: A -> list A -> B).\n    Fixpoint trans ls :=\n      match ls with\n        | nil => nil\n        | x :: xs => f x xs :: trans xs\n      end.\n    Theorem eqLen: length (trans l) = length l.\n    Proof.\n      induction l.\n      simpl.\n      reflexivity.\n      simpl.\n      f_equal.\n      assumption.\n    Qed.\n  End EqLen.\nEnd ListProp.\n\nSection Strange.\n  Variable (nm: list nat).\n\n  Fixpoint mkNameList ls :=\n    match ls with\n      | nil => nil\n      | x :: xs => (C (length xs :: nm) x) :: mkNameList xs\n    end.\n\n  Theorem mkNameListLength ls: length (mkNameList ls) = length ls.\n  Proof.\n    induction ls.\n    simpl.\n    auto.\n    simpl.\n    f_equal.\n    auto.\n  Qed.\n\n  Theorem posValue: forall ls i, i < length ls -> match nth i (mkNameList ls) (C nil nil) with\n                                                      | C x _ => x = (length ls - S i) :: nm\n                                                    end.\n  Proof.\n    intros ls.\n    induction ls.\n    intros i i_lt_l.\n    simpl in i_lt_l.\n    omega.\n    intros i i_lt_l.\n    simpl in i_lt_l.\n    unfold mkNameList.\n    fold mkNameList.\n    destruct i.\n    simpl.\n    assert (H: length ls - 0 = length ls) by omega.\n    rewrite H; clear H.\n    auto.\n    simpl.\n    assert (H: i < length ls) by omega.\n    apply (IHls i H).\n  Qed.\n\n  Theorem posValueRev': forall ls i, i < length ls ->\n                                       match nth (length ls - S i) (rev (mkNameList ls)) (C nil nil) with\n                                         | C x _ => x = (length ls - S i) :: nm\n                                       end.\n  Proof.\n    intros ls i i_lt_n.\n    pose proof (posValue _ i_lt_n) as gdOne.\n    pose proof (mkNameListLength ls) as t1.\n    rewrite <- t1 in i_lt_n.\n    pose proof (revProp (C nil nil) _ i_lt_n) as bdOne.\n    rewrite t1 in bdOne.\n    rewrite bdOne in gdOne.\n    auto.\n  Qed.\n\n  Theorem posValueRev: forall ls i, i < length ls ->\n                                      match nth i (rev (mkNameList ls)) (C nil nil) with\n                                        | C x _ => x = i :: nm\n                                      end.\n  Proof.\n    intros ls i i_lt_n.\n    assert (sth: length ls - S i < length ls) by omega.\n    pose proof (posValueRev' _ sth) as sth2.\n    assert (H: length ls - S (length ls - S i) = i) by omega.\n    rewrite H in sth2.\n    assumption.\n  Qed.\nEnd Strange.\n\nFixpoint getCs nm b :=\n  match b with\n    | B bs => rev (mkNameList nm\n                              ((fix addC bs :=\n                                  match bs with\n                                    | nil => nil\n                                    | b' :: bs' => getCs (length bs' :: nm) b' :: addC bs'\n                                  end) bs))\n  end.\n\nDefinition getC nm b := C nm (getCs nm b).\n\nTheorem parentTreeName c p np bp: parent c p ->\n                                  p = getC np bp ->\n                                  exists nc bc, c = getC nc bc.\nProof.\n  intros c_p pEq.\n  unfold parent in *; unfold getC in *.\n  destruct p.\n  injection pEq as lEqNp l0Eq.\n  rewrite lEqNp in *; rewrite l0Eq in *; clear lEqNp l0Eq.\n  clear pEq.\n  destruct bp.\n  simpl in c_p.\n  pose proof @In_rev as sth.\n  assert (In_rev: forall A l (x: A), In x (rev l) -> In x l) by\n         (generalize sth; clear;\n          intros sth A l x inl; specialize (sth A l x);\n          destruct sth;\n          intuition); clear sth.\n  pose proof (In_rev _ _ _ c_p) as inp; clear In_rev c_p l0 l.\n  induction l1.\n  simpl in *.\n  intuition.\n  simpl in inp.\n  pose proof (eqLen l1 (fun x y => getCs (length y :: np) x)) as sth.\n  unfold trans in sth.\n  rewrite sth in inp.\n  destruct inp.\n  exists (length l1 :: np); exists a; auto.\n  specialize (IHl1 H).\n  assumption.\nQed.\n\nTheorem treeNameHelp nm b:\n  match getC nm b with\n    | C x ls => treeNthName x ls\n  end.\nProof.\n  unfold treeNthName.\n  unfold getC.\n  destruct b.\n  simpl.\n  intros n n_lt_len.\n  apply posValueRev.\n  remember  ((fix addC (bs : list BaseTree) : list (list Tree) :=\n         match bs with\n         | nil => nil\n         | b' :: bs' => getCs (length bs' :: nm) b' :: addC bs'\n         end) l) as sth.\n  clear Heqsth.\n  pose proof (mkNameListLength nm sth) as H.\n  pose proof (revLen (mkNameList nm sth)) as H0.\n  rewrite H in H0.\n  rewrite <- H0 in n_lt_len.\n  assumption.\nQed.\n\nTheorem descImpGetc p c: descendent c p ->\n                         (exists np bp, p = getC np bp) ->\n                         exists nc bc, c = getC nc bc.\nProof.\n  intros desc.\n  induction desc.\n  intros [np [bp pEq]].\n  apply (parentTreeName _ H pEq).\n  intros [np [bp pEq]].\n  exists np; exists bp; intuition.\n  intros use.\n  specialize (IHdesc2 use).\n  specialize (IHdesc1 IHdesc2).\n  assumption.\nQed.\n", "meta": {"author": "vmurali", "repo": "CacheProofParam", "sha": "05b793704113956bda53c5a30ae6e52adeb58075", "save_path": "github-repos/coq/vmurali-CacheProofParam", "path": "github-repos/coq/vmurali-CacheProofParam/CacheProofParam-05b793704113956bda53c5a30ae6e52adeb58075/BaseTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7146232296472101}}
{"text": "(** Binary trees the nodes of which are labelled with type A *)\n\nSection Some_type_A.\nVariable A: Type.\n\nInductive tree  : Type :=\n  | leaf  \n  | node (label: A)(left_son right_son : tree).\n\n\nInductive subtree  (t:tree) : tree -> Prop :=\n  | subtree1 : forall t'  (x:A), subtree  t (node  x t t')\n  | subtree2 : forall (t':tree) (x:A), subtree  t (node  x t' t).\n\nTheorem well_founded_subtree :  well_founded subtree.\nProof.\n intros t; induction  t as [ | x t1 IHt1 t2 IHt2].\n - split; inversion 1. \n - split; intros y Hsub; inversion_clear Hsub; assumption.\nQed.\n\n(** Alternate arithmetic proof \n\n   Using several lemmas in library Wellfounded, we use tree size\n  as a measure for proving well_foundedness \n\n*)\n\nRequire Import Omega\n               Inverse_Image Wellfounded.Inclusion Wf_nat.\n\nFixpoint size (t:tree) : nat :=\nmatch t with leaf => 1\n           | node _ t1 t2 => 1 + size t1 + size t2\nend.\n\n\n\nLemma subtree_smaller : forall (t t': tree), subtree t t' -> size t < size t'.\nProof. \n inversion 1;simpl;omega.\nQed.\n\nLemma well_founded_subtree' : well_founded subtree.\nProof.\n apply wf_incl with (fun t t' => size t < size t').\n intros x y Hxy; now  apply subtree_smaller.\n apply wf_inverse_image; apply lt_wf.\nQed.\n\nEnd Some_type_A.", "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/ch15_general_recursion/SRC/btreewf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7146232230801831}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Crypto.Algebra.Hierarchy Crypto.Algebra.Monoid.\n\nModule Import ModuloCoq8485.\n  Import NPeano Nat.\n  Infix \"mod\" := modulo.\nEnd ModuloCoq8485.\n\nSection ScalarMultProperties.\n  Context {G eq add zero} `{monoidG:@monoid G eq add zero}.\n  Context {mul:nat->G->G}.\n  Local Infix \"=\" := eq : type_scope. Local Infix \"=\" := eq.\n  Local Infix \"+\" := add. Local Infix \"*\" := mul.\n  Class is_scalarmult :=\n    {\n      scalarmult_0_l : forall P, 0 * P = zero;\n      scalarmult_S_l : forall n P, S n * P = P + n * P;\n\n      scalarmult_Proper : Proper (Logic.eq==>eq==>eq) mul\n    }.\n  Global Existing Instance scalarmult_Proper.\n  Context `{mul_is_scalarmult:is_scalarmult}.\n\n  Fixpoint scalarmult_ref (n:nat) (P:G) {struct n} :=\n    match n with\n    | O => zero\n    | S n' => add P (scalarmult_ref n' P)\n    end.\n\n  Global Instance Proper_scalarmult_ref : Proper (Logic.eq==>eq==>eq) scalarmult_ref.\n  Proof using monoidG.\n    repeat intro; subst.\n    match goal with [n:nat |- _ ] => induction n; simpl @scalarmult_ref; [reflexivity|] end.\n    repeat match goal with [H:_ |- _ ] => rewrite H end; reflexivity.\n  Qed.\n\n  Lemma scalarmult_ext : forall n P, mul n P = scalarmult_ref n P.\n  Proof using Type*.\n\n    induction n; simpl @scalarmult_ref; intros; rewrite <-?IHn; (apply scalarmult_0_l || apply scalarmult_S_l).\n  Qed.\n\n  Lemma scalarmult_1_l : forall P, 1*P = P.\n  Proof using Type*. intros. rewrite scalarmult_S_l, scalarmult_0_l, right_identity; reflexivity. Qed.\n\n  Lemma scalarmult_add_l : forall (n m:nat) (P:G), ((n + m)%nat * P = n * P + m * P).\n  Proof using Type*.\n    induction n; intros;\n      rewrite ?scalarmult_0_l, ?scalarmult_S_l, ?plus_Sn_m, ?plus_O_n, ?scalarmult_S_l, ?left_identity, <-?associative, <-?IHn; reflexivity.\n  Qed.\n\n  Lemma scalarmult_zero_r : forall m, m * zero = zero.\n  Proof using Type*. induction m; rewrite ?scalarmult_S_l, ?scalarmult_0_l, ?left_identity, ?IHm; try reflexivity. Qed.\n\n  Lemma scalarmult_assoc : forall (n m : nat) P, n * (m * P) = (m * n)%nat * P.\n  Proof using Type*.\n    induction n; intros.\n    { rewrite <-mult_n_O, !scalarmult_0_l. reflexivity. }\n    { rewrite scalarmult_S_l, <-mult_n_Sm, <-Plus.plus_comm, scalarmult_add_l.\n      rewrite IHn. reflexivity. }\n  Qed.\n\n  Lemma scalarmult_times_order : forall l B, l*B = zero -> forall n, (l * n) * B = zero.\n  Proof using Type*. intros ? ? Hl ?. rewrite <-scalarmult_assoc, Hl, scalarmult_zero_r. reflexivity. Qed.\n\n  Lemma scalarmult_mod_order : forall l B, l <> 0%nat -> l*B = zero -> forall n, n mod l * B = n * B.\n  Proof using Type*.\n    intros ? ? Hnz Hmod ?.\n    rewrite (NPeano.Nat.div_mod n l Hnz) at 2.\n    rewrite scalarmult_add_l, scalarmult_times_order, left_identity by auto. reflexivity.\n  Qed.\nEnd ScalarMultProperties.\n\nSection ScalarMultHomomorphism.\n  Context {G EQ ADD ZERO} {monoidG:@monoid G EQ ADD ZERO}.\n  Context {H eq add zero} {monoidH:@monoid H eq add zero}.\n  Local Infix \"=\" := eq : type_scope. Local Infix \"=\" := eq : eq_scope.\n  Context {MUL} {MUL_is_scalarmult:@is_scalarmult G EQ ADD ZERO MUL }.\n  Context {mul} {mul_is_scalarmult:@is_scalarmult H eq add zero mul }.\n  Context {phi} {homom:@Monoid.is_homomorphism G EQ ADD H eq add phi}.\n  Context (phi_ZERO:phi ZERO = zero).\n\n  Lemma homomorphism_scalarmult : forall n P, phi (MUL n P) = mul n (phi P).\n  Proof using Type*.\n    setoid_rewrite scalarmult_ext.\n    induction n; intros; simpl; rewrite ?Monoid.homomorphism, ?IHn; easy.\n  Qed.\nEnd ScalarMultHomomorphism.\n\nGlobal Instance scalarmult_ref_is_scalarmult {G eq add zero} `{@monoid G eq add zero}\n  : @is_scalarmult G eq add zero (@scalarmult_ref G add zero).\nProof. split; try exact _; intros; reflexivity. Qed.", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_nsatz/src/Algebra/ScalarMult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7145577899792462}}
{"text": "Require Export prosa.util.tactics prosa.util.notation.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\n(** In this section, we introduce useful lemmas about the concatenation operation performed\n    over an arbitrary range of sequences. *)\nSection BigCatLemmas.\n\n  (** Consider any type supporting equality comparisons... *)\n  Variable T: eqType.\n\n  (** ...and a function that, given an index, yields a sequence. *)\n  Variable f: nat -> list T.\n\n  (** In this section, we prove that the concatenation over sequences works as expected: \n      no element is lost during the concatenation, and no new element is introduced. *)\n  Section BigCatElements.\n    \n    (** First, we show that the concatenation comprises all the elements of each sequence; \n        i.e. any element contained in one of the sequences will also be an element of the \n        result of the concatenation. *)\n    Lemma mem_bigcat_nat:\n      forall x m n j,\n        m <= j < n ->\n        x \\in f j ->\n        x \\in \\cat_(m <= i < n) (f i).\n    Proof.\n      intros x m n j LE IN; move: LE => /andP [LE LE0].\n      rewrite -> big_cat_nat with (n := j); simpl; [| by ins | by apply ltnW].\n      rewrite mem_cat; apply/orP; right.\n      destruct n; first by rewrite ltn0 in LE0.\n      rewrite big_nat_recl; last by ins.\n        by rewrite mem_cat; apply/orP; left.\n    Qed.\n\n    (** Conversely, we prove that any element belonging to a concatenation of sequences \n        must come from one of the sequences. *)\n    Lemma mem_bigcat_nat_exists :\n      forall x m n,\n        x \\in \\cat_(m <= i < n) (f i) ->\n        exists i,\n          x \\in f i /\\ m <= i < n.\n    Proof.\n      intros x m n IN.\n      induction n; first by rewrite big_geq // in IN.\n      destruct (leqP m n); last by rewrite big_geq ?in_nil // ltnW in IN.\n      rewrite big_nat_recr // /= mem_cat in IN.\n      move: IN => /orP [HEAD | TAIL].\n      {\n        apply IHn in HEAD; destruct HEAD; exists x0.  move: H => [H /andP [H0 H1]].\n        split; first by done.\n          by apply/andP; split; [by done | by apply ltnW]. }\n      {\n        exists n; split; first by done.\n        apply/andP; split; [by done | by apply ltnSn]. }\n    Qed.\n    \n  End BigCatElements.\n\n  (** In this section, we show how we can preserve uniqueness of the elements \n      (i.e. the absence of a duplicate) over a concatenation of sequences. *)\n  Section BigCatDistinctElements.\n\n    (** Assume that there are no duplicates in each of the possible\n        sequences to concatenate... *)\n    Hypothesis H_uniq_seq: forall i, uniq (f i).\n\n    (** ...and that there are no elements in common between the sequences. *)\n    Hypothesis H_no_elements_in_common:\n      forall x i1 i2, x \\in f i1 -> x \\in f i2 -> i1 = i2.\n    \n    (** We prove that the concatenation will yield a sequence with unique elements. *)\n    Lemma bigcat_nat_uniq :\n      forall n1 n2,\n        uniq (\\cat_(n1 <= i < n2) (f i)).\n    Proof.\n      intros n1 n2.\n      case (leqP n1 n2) => [LE | GT]; last by rewrite big_geq // ltnW.\n      rewrite -[n2](addKn n1).\n      rewrite -addnBA //; set delta := n2 - n1.\n      induction delta; first by rewrite addn0 big_geq.\n      rewrite addnS big_nat_recr /=; last by apply leq_addr.\n      rewrite cat_uniq; apply/andP; split; first by apply IHdelta.\n      apply /andP; split; last by apply H_uniq_seq.\n      rewrite -all_predC; apply/allP; intros x INx.\n      simpl; apply/negP; unfold not; intro BUG.\n      apply mem_bigcat_nat_exists in BUG.\n      move: BUG => [i [IN /andP [_ LTi]]].\n      apply H_no_elements_in_common with (i1 := i) in INx; last by done.\n      by rewrite INx ltnn in LTi.\n    Qed.\n    \n  End BigCatDistinctElements.\n  \nEnd BigCatLemmas.\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/util/bigcat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7145035473511385}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export Omega.\nRequire Export Zwf.\nRequire Export Relations.\nRequire Export Inverse_Image.\nRequire Export Transitive_Closure.\nRequire Export Zdiv.\n\nOpen Scope nat_scope.\n\nTheorem verif_divide :\n    forall m p:nat, 0 < m -> 0 < p ->\n    (exists q:nat, m = q*p)->(Z_of_nat m mod Z_of_nat p = 0)%Z.\nProof.\n intros m p Hltm Hltp (q, Heq); rewrite Heq.\n rewrite inj_mult.\n replace (Z_of_nat q * Z_of_nat p)%Z with (0 + Z_of_nat q * Z_of_nat p)%Z;\n    try ring.\n rewrite Z_mod_plus; auto.\n omega.\nQed.\n\nTheorem divisor_smaller :\n    forall m p:nat, 0 < m -> forall q:nat, m = q*p -> q <= m.\nProof.\n intros m p Hlt; case p.\n -  intros q Heq; rewrite Heq in Hlt; rewrite mult_comm in Hlt.\n    elim (lt_irrefl 0);exact Hlt.\n -  intros p' q; case q.\n    +  intros Heq; rewrite Heq in Hlt.\n       elim (lt_irrefl 0);exact Hlt.\n    +  intros q' Heq; rewrite Heq.\n       rewrite mult_comm; simpl; auto with arith.\nQed.\n\nFixpoint check_range (v:Z)(r:nat)(sr:Z){struct r} : bool :=\n  match r with\n    O => true\n  | S r' =>\n    match (v mod sr)%Z with\n      Z0 => false\n    | _ => check_range v r' (Z.pred sr)\n    end\n  end.\n\nDefinition check_primality (n:nat) :=\n  check_range (Z_of_nat n)(pred (pred n))(Z_of_nat (pred n)).\n\n(** Tests :\n\nCompute check_primality 2333.\n\nCompute check_primality 2330.\n*)\n\n\nFixpoint check_range' (v:Z)(r:nat){struct r} : bool :=\n  match r with\n    0 => true | 1 => true\n  | S r' =>\n      match (v mod Z_of_nat r)%Z with\n      | 0%Z => false\n      | _ => check_range' v r'\n      end\n  end.\n\nDefinition check_primality' (n:nat) :=\n  check_range' (Zpos (P_of_succ_nat (pred n)))(pred (pred n)).\n\nTheorem Zabs_nat_0 : forall x:Z, Z.abs_nat x = 0 -> (x = 0)%Z.\nProof.\n intros x; case x.\n -  simpl; auto.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\nQed.\n\nTheorem Z_to_nat_and_back :\n forall x:Z, (0 <= x)%Z -> (Z.of_nat (Z.abs_nat x))=x.\nProof.\n intros x; case x.\n -  auto.\n -  intros p Hd; elim p.\n    +  unfold Z.abs_nat; intros p' Hrec; rewrite nat_of_P_xI.\n       rewrite inj_S.\n       rewrite inj_mult.\n       rewrite Zpos_xI.\n       unfold Z.succ.\n       rewrite Hrec.\n       simpl; auto.\n    +  unfold Z.abs_nat.\n       intros p' Hrec; rewrite nat_of_P_xO.\n       rewrite inj_mult.\n       rewrite Zpos_xO.\n       unfold Z.succ.\n       rewrite Hrec.\n       simpl; auto.\n    +  simpl; auto.\n - intros p' Hd; elim Hd;auto.\nQed.\n\nTheorem check_range_correct :\n  forall (v:Z)(r:nat)(rz:Z),\n  (0 < v)%Z ->\n  Z_of_nat (S r) = rz -> check_range v r rz = true ->\n  ~ (exists k:nat, k <= (S r) /\\ k <> 1 /\\ \n                       (exists q:nat, Z.abs_nat v = q*k)).\nProof.\n intros v r; elim r.\n -  intros rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n   +  intros (Hle, (Hne1, (q, Heq))).\n      rewrite mult_comm in Heq; simpl in Heq.\n      rewrite (Zabs_nat_0 _ Heq) in Hlt.\n      elim (Z.lt_irrefl 0); assumption.\n   +  intros k' (Hle, (Hne1, (q, Heq))).\n      inversion Hle.\n      assert (H':k'=0).\n      * assumption.\n      * rewrite H' in Hne1; elim Hne1;auto.\n      * assert (H': S k' <= 0) by  assumption.\n        inversion H'.\n-  intros r' Hrec rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n   +  intros (Hle, (Hne1, (q, Heq))).\n      rewrite mult_comm in Heq; simpl in Heq.\n      rewrite (Zabs_nat_0 _ Heq) in Hlt.\n      elim (Z.lt_irrefl 0); assumption.\n   +  intros k' (Hle, (Hne1, (q, Heq))).\n      inversion Hle.\n      rewrite <- H1 in H2. \n      rewrite <- (Z_to_nat_and_back v) in H2.\n      assert (Hmod:(Z_of_nat (Z.abs_nat v) mod Z.of_nat (S (S r')) = 0)%Z).\n      *  apply verif_divide.\n         replace 0 with (Z.abs_nat 0%Z).\n         apply Zabs_nat_lt.\n         omega.\n         simpl; auto.\n         auto with arith.\n         exists q.\n         assert (H': k' = S r') by assumption.\n         rewrite <- H';auto.\n      *   unfold check_range in H2.\n         rewrite Hmod in H2; discriminate H2.\n      *  omega.\n      *  unfold check_range in H2; fold check_range in H2.\n         case_eq ((v mod rz)%Z).\n         intros Heqmod.\n         rewrite Heqmod in H2.\n         discriminate H2.\n         intros pmod Heqmod; rewrite Heqmod in H2.\n         elim (Hrec (Z.pred rz) Hlt).\n         rewrite <- H1.\n         rewrite inj_S.\n         rewrite inj_S.\n         rewrite inj_S.\n         rewrite <- Zpred_succ.\n         auto.\n         assumption.\n         exists (S k').\n         repeat split;auto.\n         exists q; assumption.\n         intros p Hmod.\n         elim (Z_mod_lt v rz).\n         rewrite Hmod.\n         unfold Z.le; simpl; intros Hle'; elim Hle';auto.\n         rewrite <- H1.\n         rewrite inj_S.\n         unfold Z.succ.\n         generalize (Zle_0_nat (S r')).\n         intros; omega.\nQed.\n\nTheorem nat_of_P_Psucc : \n forall p:positive, nat_of_P (Pos.succ p) = S (nat_of_P p).\nProof.\n intros p; elim p.\n -  simpl; intros p'; rewrite nat_of_P_xO.\n    intros Heq; rewrite Heq; rewrite nat_of_P_xI; ring.\n - intros p' Heq; simpl.\n   rewrite nat_of_P_xI.\n   rewrite nat_of_P_xO;auto.\n -  auto.\nQed.\n\nTheorem nat_to_Z_and_back:\n forall n:nat, Z.abs_nat (Z.of_nat n) = n.\nProof.\n intros n; elim n.\n -  auto.\n - intros n'; simpl; case n'.\n  + simpl; auto.\n  +  intros n''; simpl; rewrite nat_of_P_Psucc.\n     intros Heq; rewrite Heq; auto.\nQed.\n \n\nTheorem check_correct :\n  forall p:nat, 0 < p -> check_primality p = true ->\n  ~(exists k:nat, k <> 1 /\\ k <> p /\\ (exists q:nat, p = q*k)).\nProof.\n unfold lt; intros p Hle; elim Hle.\n -  intros Hcp (k, (Hne1, (Hne1bis, (q, Heq))));\n   rewrite mult_comm in Heq.\n    assert (Hle' : k < 1).\n   +  elim (le_lt_or_eq k 1); try(intuition; fail).\n      apply divisor_smaller with (2:= Heq); auto.\n   + case_eq k.\n     intros Heq'; rewrite Heq' in Heq; simpl in Heq; discriminate Heq.\n     intros; omega.\n -  intros p' Hlep' Hrec; unfold check_primality.\n    assert (H':(exists p'':nat, p' = (S p''))).\n    +  inversion Hlep'.\n       exists 0; auto.\n       eapply ex_intro;eauto.\n    +  elim H'; intros p'' Hp''; rewrite Hp''.\n       repeat rewrite <- pred_Sn.\n       intros Hcr Hex.\n       elim check_range_correct with (3:= Hcr).\n       rewrite inj_S; generalize (Zle_0_nat (S p'')).\n       intros; omega.\n       auto.\n       elim Hex; intros k (Hne1, (HneSSp'', (q, Heq))); exists k.\n       split.\n       assert (HkleSSp'': k <= S (S p'')).\n       * apply (divisor_smaller (S (S p'')) q).\n         auto with arith.\n         rewrite mult_comm.\n         assumption.\n       *  omega.\n       * split.\n         assumption.\n         exists q; now rewrite nat_to_Z_and_back.\nQed.\n\n\nTheorem prime_2333 :\n ~(exists k:nat, k <> 1 /\\ k <> 2333 /\\ (exists q:nat, 2333 = q*k)).\nProof.\n Time apply check_correct; auto with arith.\n(**Finished transaction in 132. secs (131.01u,0.62s)*)\nTime Qed.\n\n\nTheorem reflection_test :\n forall x y z t u:nat, x+(y+z+(t+u)) = x+y+(z+(t+u)).\nProof.\n intros; repeat rewrite plus_assoc; auto.\nQed.\n\nInductive bin : Set := node : bin->bin->bin | leaf : nat->bin.\n\nFixpoint flatten_aux (t fin:bin){struct t} : bin :=\n  match t with\n  | node t1 t2 => flatten_aux t1 (flatten_aux t2 fin)\n  | x => node x fin\n  end.\n\nFixpoint flatten (t:bin) : bin :=\n  match t with\n  | node t1 t2 => flatten_aux t1 (flatten t2)\n  | x => x\n  end.\n\nCompute \n  flatten\n     (node (leaf 1) (node (node (leaf 2)(leaf 3)) (leaf 4))).\n\nFixpoint bin_nat (t:bin) : nat :=\n  match t with\n  | node t1 t2 => bin_nat t1 + bin_nat t2\n  | leaf n => n\n  end.\n\nEval lazy beta iota delta [bin_nat] in\n (bin_nat\n   (node (leaf 1) (node (node (leaf 2) (leaf 3)) (leaf 4)))).\n\nTheorem flatten_aux_valid :\n forall t t':bin, bin_nat t + bin_nat t' = bin_nat (flatten_aux t t').\nProof.\n intros t; elim t; simpl; auto.\n intros t1 IHt1 t2 IHt2 t'; rewrite <- IHt1; rewrite <- IHt2.\n rewrite plus_assoc; trivial.\nQed.\n\nTheorem flatten_valid : forall t:bin, bin_nat t = bin_nat (flatten t).\nProof.\n intros t; elim t; simpl; auto.\n intros t1 IHt1 t2 IHt2; rewrite <- flatten_aux_valid; rewrite <- IHt2.\n trivial.\nQed.\n\nTheorem flatten_valid_2 :\n  forall t t':bin, bin_nat (flatten t) = bin_nat (flatten t')->\n  bin_nat t = bin_nat t'.\nProof.\n intros; rewrite (flatten_valid t); rewrite (flatten_valid t');\n auto.\nQed.\n\nTheorem reflection_test' :\n forall x y z t u:nat, x+(y+z+(t+u))=x+y+(z+(t+u)).\nProof.\n intros.\n change\n   (bin_nat\n      (node (leaf x)\n         (node (node (leaf y) (leaf z))\n               (node (leaf t)(leaf u)))) =\n    bin_nat\n      (node (node (leaf x)(leaf y))\n         (node (leaf z)\n               (node (leaf t)(leaf u))))).\n apply flatten_valid_2; auto.\nQed.\n\nLtac model v :=\n  match v with\n  | (?X1 + ?X2) =>\n    let r1 := model X1 \n              with r2 := model X2 in constr:(node r1 r2)\n  | ?X1 => constr:(leaf X1)\n  end.\n\nLtac assoc_eq_nat :=\n  match goal with\n  | [ |- (?X1 = ?X2 :>nat) ] =>\n   let term1 := model X1 with term2 := model X2 in\n   (change (bin_nat term1 = bin_nat term2);\n    apply flatten_valid_2;\n    lazy beta iota zeta delta [flatten flatten_aux bin_nat]; \n    auto)\n  end.\n\n\nTheorem reflection_test'' :\n forall x y z t u:nat, x+(y+z+(t+u)) = x+y+(z+(t+u)).\nProof.\n intros; assoc_eq_nat.\nQed.\n\nSection assoc_eq.\nVariables (A : Type)(f : A->A->A)\n  (assoc : forall x y z:A, f x (f y z) = f (f x y) z).\n\nFixpoint bin_A (l:list A)(def:A)(t:bin){struct t} : A :=\n  match t with\n  | node t1 t2 => f (bin_A l def t1)(bin_A l def t2)\n  | leaf n => nth n l def\n  end.\n\nTheorem flatten_aux_valid_A :\n forall (l:list A)(def:A)(t t':bin),\n f (bin_A l def t)(bin_A l def t') = bin_A l def (flatten_aux t t').\nProof.\n intros l def t; elim t; simpl; auto.\n intros t1 IHt1 t2 IHt2 t';  rewrite <- IHt1; rewrite <- IHt2.\n symmetry; apply assoc.\nQed.\n\nTheorem flatten_valid_A :\n forall (l:list A)(def:A)(t:bin),\n   bin_A l def t = bin_A l def (flatten t).\nProof.\n intros l def t; elim t; simpl; trivial.\n intros t1 IHt1 t2 IHt2; rewrite <- flatten_aux_valid_A; now rewrite <- IHt2.\nQed.\n\nTheorem flatten_valid_A_2 :\n forall (t t':bin)(l:list A)(def:A),\n   bin_A l def (flatten t) = bin_A l def (flatten t')->\n   bin_A l def t = bin_A l def t'. \nProof.\n intros t t' l def Heq.\n rewrite (flatten_valid_A l def t); now rewrite (flatten_valid_A l def t').\nQed.\n\nEnd assoc_eq.\n\nLtac term_list f l v :=\n  match v with\n  | (f ?X1 ?X2) =>\n    let l1 := term_list f l X2 in term_list f l1 X1\n  | ?X1 => constr:(cons X1 l)\n  end.\n\nLtac compute_rank l n v :=\n  match l with\n  | (cons ?X1 ?X2) =>\n    let tl := constr:(X2) in\n    match constr:(X1 = v) with\n    | (?X1 = ?X1) => n\n    | _ => compute_rank tl (S n) v\n    end\n  end.\n\nLtac model_aux l f v :=\n  match v with\n  | (f ?X1 ?X2) =>\n    let r1 := model_aux l f X1 with r2 := model_aux l f X2 in\n      constr:(node r1 r2)\n  | ?X1 => let n := compute_rank l 0 X1 in constr:(leaf n)\n  | _ => constr:(leaf 0)\n  end.\n\nLtac model_A A f def v :=\n  let l := term_list f (nil (A:=A)) v in\n  let t := model_aux l f v in\n  constr:(bin_A A f l def t).\n\nLtac assoc_eq A f assoc_thm :=\n  match goal with\n  | [ |- (@eq A ?X1 ?X2) ] =>\n  let term1 := model_A A f X1 X1 \n  with term2 := model_A A f X1 X2 in\n  (change (term1 = term2);\n   apply flatten_valid_A_2 with (1 := assoc_thm); auto)\n  end.\n\nTheorem reflection_test3 :\n forall x y z t u:Z, (x*(y*z*(t*u)) = x*y*(z*(t*u)))%Z.\nProof.\n intros; assoc_eq Z Zmult Zmult_assoc.\nQed.\n\n\nFixpoint nat_le_bool (n m:nat){struct m} : bool :=\n  match n, m with\n  | O, _ => true\n  | S _, O => false\n  | S n, S m => nat_le_bool n m\n  end.\n\nFixpoint insert_bin (n:nat)(t:bin){struct t} : bin :=\n  match t with\n  | leaf m => match nat_le_bool n m with\n              | true => node (leaf n)(leaf m)\n              | false => node (leaf m)(leaf n)\n              end\n  | node (leaf m) t' => match nat_le_bool n m with\n                        | true => node (leaf n) t\n                        | false => \n                            node (leaf m)(insert_bin n t')\n                        end\n  | t => node (leaf n) t\n  end.\n\nFixpoint sort_bin (t:bin) : bin :=\n  match t with\n  | node (leaf n) t' => insert_bin n (sort_bin t')\n  | t => t\n  end.\n\n\n\n\nSection commut_eq.\n(** this section contains some primed versions of previous constructions\n   (for avoiding Reset commands)\n\n*)\n\n Variables (A : Type)(f : A->A->A).\n Hypothesis comm : forall x y:A, f x y = f y x.\n Hypothesis assoc : forall x y z:A, f x (f y z) = f (f x y) z.\n\n Fixpoint bin_A' (l:list A)(def:A)(t:bin){struct t} : A :=\n   match t with\n   | node t1 t2 => f (bin_A' l def t1)(bin_A' l def t2)\n   | leaf n => nth n l def\n   end.\n\n Theorem flatten_aux_valid_A' :\n  forall (l:list A)(def:A)(t t':bin),\n   f (bin_A' l def t)(bin_A' l def t') = bin_A' l def (flatten_aux t t').\n Proof.\n  intros l def t; elim t; simpl; auto.\n  intros t1 IHt1 t2 IHt2 t';  rewrite <- IHt1; rewrite <- IHt2.\n  symmetry; apply assoc.\n Qed.\n\n Theorem flatten_valid_A' :\n  forall (l:list A)(def:A)(t:bin),\n    bin_A' l def t = bin_A' l def (flatten t).\n Proof.\n  intros l def t; elim t; simpl; trivial.\n  intros t1 IHt1 t2 IHt2; rewrite <- flatten_aux_valid_A'; rewrite <- IHt2.\n  trivial.\n Qed.\n\nTheorem flatten_valid_A_2' :\n forall (t t':bin)(l:list A)(def:A),\n   bin_A' l def (flatten t) = bin_A' l def (flatten t')->\n   bin_A' l def t = bin_A' l def t'. \nProof.\n intros t t' l def Heq.\n rewrite (flatten_valid_A' l def t); rewrite (flatten_valid_A' l def t').\n trivial.\nQed.\n\nTheorem insert_is_f : forall (l:list A)(def:A)(n:nat)(t:bin),\n   bin_A' l def (insert_bin n t) = \n   f (nth n l def) (bin_A' l def t).\nProof.\n intros l def n t; elim t.\n intros t1; case t1.\n intros t1' t1'' IHt1 t2 IHt2.\n simpl.\n auto.\n intros n0 IHt1 t2 IHt2.\n simpl.\n case (nat_le_bool n n0).\n simpl.\n auto.\n simpl.\n rewrite IHt2.\n repeat rewrite assoc; rewrite (comm (nth n l def)); auto.\n simpl.\n intros n0; case (nat_le_bool n n0); auto.\n rewrite comm; auto.\nQed.\n\nTheorem sort_eq : forall (l:list A)(def:A)(t:bin),\n    bin_A' l def (sort_bin t) = bin_A' l def t.  \nProof.\n intros l def t; elim t.\n intros t1 IHt1; case t1.\n auto.\n intros n t2 IHt2; simpl; rewrite insert_is_f.\n rewrite IHt2; auto.\n auto.\nQed.\n\n\nTheorem sort_eq_2 :\n forall (l:list A)(def:A)(t1 t2:bin),\n   bin_A' l def (sort_bin t1) = bin_A' l def (sort_bin t2)->\n   bin_A' l def t1 = bin_A' l def t2.  \nProof.\n intros l def t1 t2.\n rewrite <- (sort_eq l def t1); rewrite <- (sort_eq l def t2).\n trivial.\nQed.\n\nEnd commut_eq.\n\n\nLtac term_list' f l v :=\n  match v with\n  | (f ?X1 ?X2) =>\n    let l1 := term_list' f l X2 in term_list' f l1 X1\n  | ?X1 => constr:(cons X1 l)\n  end.\n\nLtac compute_rank' l n v :=\n  match l with\n  | (cons ?X1 ?X2) =>\n    let tl := constr:(X2) in\n    match constr:(X1 = v) with\n    | (?X1 = ?X1) => n\n    | _ => compute_rank' tl (S n) v\n    end\n  end.\n\nLtac model_aux' l f v :=\n  match v with\n  | (f ?X1 ?X2) =>\n    let r1 := model_aux' l f X1 with r2 := model_aux' l f X2 in\n      constr:(node r1 r2)\n  | ?X1 => let n := compute_rank' l 0 X1 in constr:(leaf n)\n  | _ => constr:(leaf 0)\n  end.\n\nLtac comm_eq' A f assoc_thm comm_thm :=\n  match goal with\n  | [ |- (?X1 = ?X2 :>A) ] =>\n    let l := term_list' f (nil (A:=A)) X1 in\n    let term1 := model_aux' l f X1 \n    with term2 := model_aux' l f X2 in\n    (change (bin_A' A f l X1 term1 = bin_A' A f l X1 term2);\n      apply flatten_valid_A_2' with (1 := assoc_thm);\n      apply sort_eq_2 with (1 := comm_thm)(2 := assoc_thm); \n      auto)\n  end.\n\nTheorem reflection_test4 : forall x y z:Z, (x+(y+z) = (z+x)+y)%Z.\nProof.\n intros x y z. comm_eq' Z Zplus Zplus_assoc Zplus_comm.\nQed.\n\n", "meta": {"author": "baberrehman", "repo": "interactive-theorem-proving", "sha": "e8e9de4bc664f4dd1b0fd72d6edf84f736da8874", "save_path": "github-repos/coq/baberrehman-interactive-theorem-proving", "path": "github-repos/coq/baberrehman-interactive-theorem-proving/interactive-theorem-proving-e8e9de4bc664f4dd1b0fd72d6edf84f736da8874/coq-art-8.13.0/ch16_proof_by_reflection/SRC/chap16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7143631652009849}}
{"text": "Require Import Nat List Bool PeanoNat Orders.\nRequire Import Coq.Structures.OrdersFacts.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Sorting.Sorted.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Sorticoq.SortedList.\nRequire Import Sorticoq.BinaryTree.\nImport ListNotations.\n\nModule TreeSort (Import O: UsualOrderedTypeFull').\n(*\nModule Bdefs := UsualOrderedTypeFull'_to_BinaryTree O.\nImport Bdefs.\n*)\nInclude (BinaryTree_over_OrderedType O).\n\nFixpoint makeBST (l: list A) : BinaryTree :=\n  match l with\n  | nil => BT_nil\n  | h::t => BST_Insert (makeBST t) h\n  end.\n\nLemma makeBST_ok: forall x (l: list A),\n  In_tree x (makeBST l) <-> In x l.\nProof.\n  split; intros; induction l; simpl in *;\n    [inversion H |  idtac | inversion H | idtac ].\n  - apply In_tree_insert in H; intuition.\n  - apply In_insert_cond; intuition.\nQed.\n\nDefinition Treesort (l: list A) : list A :=\n  BT_get_list (makeBST l).\n\nLemma Treesort_is_LocallySorted: forall l,\n  LocallySorted lte (Treesort l).\nProof.\n  intros. apply BST_is_LocallySorted.\n  induction l; simpl; auto.\n  apply Insert_not_change_BSTSP. assumption.\nQed.\n\nLemma Treesort_Permutation: forall l,\n  Permutation l (Treesort l).\nProof.\n  induction l; simpl; auto.\n  unfold Treesort in *. simpl.\n  remember (BST_Insert _ a) as Tr. symmetry in HeqTr.\n  apply BST_Insert_emplace in HeqTr. destruct HeqTr as [e1 [e2 [H' H'']]].\n  rewrite <- H'. rewrite <- H'' in IHl.\n  simpl. apply Permutation_cons_app. auto.\nQed.\n\nTheorem Treesort_is_sorting_algo:\n  is_sorting_algo lte Treesort.\nProof.\n  unfold is_sorting_algo. split.\n  - apply Treesort_Permutation.\n  - apply Sorted_LocallySorted_iff. apply Treesort_is_LocallySorted.\nQed.\n\nEnd TreeSort.\n", "meta": {"author": "holmuk", "repo": "Sorticoq", "sha": "ac115f2a80deb5c2db2a56ba6b7adfad043e84b5", "save_path": "github-repos/coq/holmuk-Sorticoq", "path": "github-repos/coq/holmuk-Sorticoq/Sorticoq-ac115f2a80deb5c2db2a56ba6b7adfad043e84b5/src/Treesort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.714363148004888}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\nRequire Import BinPos BinNat Nnat ZArith_base ROmega ZArithRing Morphisms Zdiv.\nRequire Export Ndiv_def Zdiv_def.\nRequire ZBinary ZDivTrunc.\n\nLocal Open Scope Z_scope.\n\n(** This file provides results about the Round-Toward-Zero Euclidean\n  division [Zquotrem], whose projections are [Zquot] and [Zrem].\n  Definition of this division can be found in file [Zdiv_def].\n\n  This division and the one defined in Zdiv agree only on positive\n  numbers. Otherwise, Zdiv performs Round-Toward-Bottom (a.k.a Floor).\n\n  The current approach is compatible with the division of usual\n  programming languages such as Ocaml. In addition, it has nicer\n  properties with respect to opposite and other usual operations.\n*)\n\n(** * Relation between division on N and on Z. *)\n\nLemma Ndiv_Zquot : forall a b:N,\n  Z_of_N (a/b) = (Z_of_N a ÷ Z_of_N b).\nProof.\n  intros.\n  destruct a; destruct b; simpl; auto.\n  unfold Ndiv, Zquot; simpl; destruct Pdiv_eucl; auto.\nQed.\n\nLemma Nmod_Zrem : forall a b:N,\n  Z_of_N (a mod b) = Zrem (Z_of_N a) (Z_of_N b).\nProof.\n  intros.\n  destruct a; destruct b; simpl; auto.\n  unfold Nmod, Zrem; simpl; destruct Pdiv_eucl; auto.\nQed.\n\n(** * Characterization of this euclidean division. *)\n\n(** First, the usual equation [a=q*b+r]. Notice that [a mod 0]\n   has been chosen to be [a], so this equation holds even for [b=0].\n*)\n\nNotation Z_quot_rem_eq := Z_quot_rem_eq (only parsing).\n\n(** Then, the inequalities constraining the remainder:\n    The remainder is bounded by the divisor, in term of absolute values *)\n\nTheorem Zrem_lt : forall a b:Z, b<>0 ->\n  Zabs (Zrem a b) < Zabs b.\nProof.\n  destruct b as [ |b|b]; intro H; try solve [elim H;auto];\n  destruct a as [ |a|a]; try solve [compute;auto]; unfold Zrem, Zquotrem;\n  generalize (Pdiv_eucl_remainder a b); destruct Pdiv_eucl; simpl;\n  try rewrite Zabs_Zopp; rewrite Zabs_eq; auto using Z_of_N_le_0;\n  intros LT; apply (Z_of_N_lt _ _ LT).\nQed.\n\n(** The sign of the remainder is the one of [a]. Due to the possible\n   nullity of [a], a general result is to be stated in the following form:\n*)\n\nTheorem Zrem_sgn : forall a b:Z,\n  0 <= Zsgn (Zrem a b) * Zsgn a.\nProof.\n  destruct b as [ |b|b]; destruct a as [ |a|a]; simpl; auto with zarith;\n  unfold Zrem, Zquotrem; destruct Pdiv_eucl;\n  simpl; destruct n0; simpl; auto with zarith.\nQed.\n\n(** This can also be said in a simplier way: *)\n\nTheorem Zsgn_pos_iff : forall z, 0 <= Zsgn z <-> 0 <= z.\nProof.\n destruct z; simpl; intuition auto with zarith.\nQed.\n\nTheorem Zrem_sgn2 : forall a b:Z,\n  0 <= (Zrem a b) * a.\nProof.\n  intros; rewrite <-Zsgn_pos_iff, Zsgn_Zmult; apply Zrem_sgn.\nQed.\n\n(** Reformulation of [Zquot_lt] and [Zrem_sgn] in 2\n  then 4 particular cases. *)\n\nTheorem Zrem_lt_pos : forall a b:Z, 0<=a -> b<>0 ->\n  0 <= Zrem a b < Zabs b.\nProof.\n  intros.\n  assert (0 <= Zrem a b).\n   generalize (Zrem_sgn a b).\n   destruct (Zle_lt_or_eq 0 a H).\n   rewrite <- Zsgn_pos in H1; rewrite H1; romega with *.\n   subst a; simpl; auto.\n  generalize (Zrem_lt a b H0); romega with *.\nQed.\n\nTheorem Zrem_lt_neg : forall a b:Z, a<=0 -> b<>0 ->\n  -Zabs b < Zrem a b <= 0.\nProof.\n  intros.\n  assert (Zrem a b <= 0).\n   generalize (Zrem_sgn a b).\n   destruct (Zle_lt_or_eq a 0 H).\n   rewrite <- Zsgn_neg in H1; rewrite H1; romega with *.\n   subst a; simpl; auto.\n  generalize (Zrem_lt a b H0); romega with *.\nQed.\n\nTheorem Zrem_lt_pos_pos : forall a b:Z, 0<=a -> 0<b -> 0 <= Zrem a b < b.\nProof.\n  intros; generalize (Zrem_lt_pos a b); romega with *.\nQed.\n\nTheorem Zrem_lt_pos_neg : forall a b:Z, 0<=a -> b<0 -> 0 <= Zrem a b < -b.\nProof.\n  intros; generalize (Zrem_lt_pos a b); romega with *.\nQed.\n\nTheorem Zrem_lt_neg_pos : forall a b:Z, a<=0 -> 0<b -> -b < Zrem a b <= 0.\nProof.\n  intros; generalize (Zrem_lt_neg a b); romega with *.\nQed.\n\nTheorem Zrem_lt_neg_neg : forall a b:Z, a<=0 -> b<0 -> b < Zrem a b <= 0.\nProof.\n  intros; generalize (Zrem_lt_neg a b); romega with *.\nQed.\n\n(** * Division and Opposite *)\n\n(* The precise equalities that are invalid with \"historic\" Zdiv. *)\n\nTheorem Zquot_opp_l : forall a b:Z, (-a)÷b = -(a÷b).\nProof.\n destruct a; destruct b; simpl; auto;\n  unfold Zquot, Zquotrem; destruct Pdiv_eucl; simpl; auto with zarith.\nQed.\n\nTheorem Zquot_opp_r : forall a b:Z, a÷(-b) = -(a÷b).\nProof.\n destruct a; destruct b; simpl; auto;\n  unfold Zquot, Zquotrem; destruct Pdiv_eucl; simpl; auto with zarith.\nQed.\n\nTheorem Zrem_opp_l : forall a b:Z, Zrem (-a) b = -(Zrem a b).\nProof.\n destruct a; destruct b; simpl; auto;\n  unfold Zrem, Zquotrem; destruct Pdiv_eucl; simpl; auto with zarith.\nQed.\n\nTheorem Zrem_opp_r : forall a b:Z, Zrem a (-b) = Zrem a b.\nProof.\n destruct a; destruct b; simpl; auto;\n  unfold Zrem, Zquotrem; destruct Pdiv_eucl; simpl; auto with zarith.\nQed.\n\nTheorem Zquot_opp_opp : forall a b:Z, (-a)÷(-b) = a÷b.\nProof.\n destruct a; destruct b; simpl; auto;\n  unfold Zquot, Zquotrem; destruct Pdiv_eucl; simpl; auto with zarith.\nQed.\n\nTheorem Zrem_opp_opp : forall a b:Z, Zrem (-a) (-b) = -(Zrem a b).\nProof.\n destruct a; destruct b; simpl; auto;\n  unfold Zrem, Zquotrem; destruct Pdiv_eucl; simpl; auto with zarith.\nQed.\n\n(** * Unicity results *)\n\nDefinition Remainder a b r :=\n  (0 <= a /\\ 0 <= r < Zabs b) \\/ (a <= 0 /\\ -Zabs b < r <= 0).\n\nDefinition Remainder_alt a b r :=\n  Zabs r < Zabs b /\\ 0 <= r * a.\n\nLemma Remainder_equiv : forall a b r,\n Remainder a b r <-> Remainder_alt a b r.\nProof.\n  unfold Remainder, Remainder_alt; intuition.\n  romega with *.\n  romega with *.\n  rewrite <-(Zmult_opp_opp).\n  apply Zmult_le_0_compat; romega.\n  assert (0 <= Zsgn r * Zsgn a) by (rewrite <-Zsgn_Zmult, Zsgn_pos_iff; auto).\n  destruct r; simpl Zsgn in *; romega with *.\nQed.\n\nTheorem Zquot_mod_unique_full:\n forall a b q r, Remainder a b r ->\n   a = b*q + r -> q = a÷b /\\ r = Zrem a b.\nProof.\n  destruct 1 as [(H,H0)|(H,H0)]; intros.\n  apply Zdiv_mod_unique with b; auto.\n  apply Zrem_lt_pos; auto.\n  romega with *.\n  rewrite <- H1; apply Z_quot_rem_eq.\n\n  rewrite <- (Zopp_involutive a).\n  rewrite Zquot_opp_l, Zrem_opp_l.\n  generalize (Zdiv_mod_unique b (-q) (-a÷b) (-r) (Zrem (-a) b)).\n  generalize (Zrem_lt_pos (-a) b).\n  rewrite <-Z_quot_rem_eq, <-Zopp_mult_distr_r, <-Zopp_plus_distr, <-H1.\n  romega with *.\nQed.\n\nTheorem Zquot_unique_full:\n forall a b q r, Remainder a b r ->\n  a = b*q + r -> q = a÷b.\nProof.\n intros; destruct (Zquot_mod_unique_full a b q r); auto.\nQed.\n\nTheorem Zquot_unique:\n forall a b q r, 0 <= a -> 0 <= r < b ->\n   a = b*q + r -> q = a÷b.\nProof. exact Z.quot_unique. Qed.\n\nTheorem Zrem_unique_full:\n forall a b q r, Remainder a b r ->\n  a = b*q + r -> r = Zrem a b.\nProof.\n intros; destruct (Zquot_mod_unique_full a b q r); auto.\nQed.\n\nTheorem Zrem_unique:\n forall a b q r, 0 <= a -> 0 <= r < b ->\n   a = b*q + r -> r = Zrem a b.\nProof. exact Z.rem_unique. Qed.\n\n(** * Basic values of divisions and modulo. *)\n\nLemma Zrem_0_l: forall a, Zrem 0 a = 0.\nProof.\n  destruct a; simpl; auto.\nQed.\n\nLemma Zrem_0_r: forall a, Zrem a 0 = a.\nProof.\n  destruct a; simpl; auto.\nQed.\n\nLemma Zquot_0_l: forall a, 0÷a = 0.\nProof.\n  destruct a; simpl; auto.\nQed.\n\nLemma Zquot_0_r: forall a, a÷0 = 0.\nProof.\n  destruct a; simpl; auto.\nQed.\n\nLemma Zrem_1_r: forall a, Zrem a 1 = 0.\nProof. exact Z.rem_1_r. Qed.\n\nLemma Zquot_1_r: forall a, a÷1 = a.\nProof. exact Z.quot_1_r. Qed.\n\nHint Resolve Zrem_0_l Zrem_0_r Zquot_0_l Zquot_0_r Zquot_1_r Zrem_1_r\n : zarith.\n\nLemma Zquot_1_l: forall a, 1 < a -> 1÷a = 0.\nProof. exact Z.quot_1_l. Qed.\n\nLemma Zrem_1_l: forall a, 1 < a -> Zrem 1 a = 1.\nProof. exact Z.rem_1_l. Qed.\n\nLemma Z_quot_same : forall a:Z, a<>0 -> a÷a = 1.\nProof. exact Z.quot_same. Qed.\n\nLtac zero_or_not a :=\n  destruct (Z_eq_dec a 0);\n  [subst; rewrite ?Zrem_0_l, ?Zquot_0_l, ?Zrem_0_r, ?Zquot_0_r;\n   auto with zarith|].\n\nLemma Z_rem_same : forall a, Zrem a a = 0.\nProof. intros. zero_or_not a. apply Z.rem_same; auto. Qed.\n\nLemma Z_rem_mult : forall a b, Zrem (a*b) b = 0.\nProof. intros. zero_or_not b. apply Z.rem_mul; auto. Qed.\n\nLemma Z_quot_mult : forall a b:Z, b <> 0 -> (a*b)÷b = a.\nProof. exact Z.quot_mul. Qed.\n\n(** * Order results about Zrem and Zquot *)\n\n(* Division of positive numbers is positive. *)\n\nLemma Z_quot_pos: forall a b, 0 <= a -> 0 <= b -> 0 <= a÷b.\nProof. intros. zero_or_not b. apply Z.quot_pos; auto with zarith. Qed.\n\n(** As soon as the divisor is greater or equal than 2,\n    the division is strictly decreasing. *)\n\nLemma Z_quot_lt : forall a b:Z, 0 < a -> 2 <= b -> a÷b < a.\nProof. intros. apply Z.quot_lt; auto with zarith. Qed.\n\n(** A division of a small number by a bigger one yields zero. *)\n\nTheorem Zquot_small: forall a b, 0 <= a < b -> a÷b = 0.\nProof. exact Z.quot_small. Qed.\n\n(** Same situation, in term of modulo: *)\n\nTheorem Zrem_small: forall a n, 0 <= a < n -> Zrem a n = a.\nProof. exact Z.rem_small. Qed.\n\n(** [Zge] is compatible with a positive division. *)\n\nLemma Z_quot_monotone : forall a b c, 0<=c -> a<=b -> a÷c <= b÷c.\nProof. intros. zero_or_not c. apply Z.quot_le_mono; auto with zarith. Qed.\n\n(** With our choice of division, rounding of (a÷b) is always done toward zero: *)\n\nLemma Z_mult_quot_le : forall a b:Z, 0 <= a -> 0 <= b*(a÷b) <= a.\nProof. intros. zero_or_not b. apply Z.mul_quot_le; auto with zarith. Qed.\n\nLemma Z_mult_quot_ge : forall a b:Z, a <= 0 -> a <= b*(a÷b) <= 0.\nProof. intros. zero_or_not b. apply Z.mul_quot_ge; auto with zarith. Qed.\n\n(** The previous inequalities between [b*(a÷b)] and [a] are exact\n    iff the modulo is zero. *)\n\nLemma Z_quot_exact_full : forall a b:Z, a = b*(a÷b) <-> Zrem a b = 0.\nProof. intros. zero_or_not b. intuition. apply Z.quot_exact; auto. Qed.\n\n(** A modulo cannot grow beyond its starting point. *)\n\nTheorem Zrem_le: forall a b, 0 <= a -> 0 <= b -> Zrem a b <= a.\nProof. intros. zero_or_not b. apply Z.rem_le; auto with zarith. Qed.\n\n(** Some additionnal inequalities about Zdiv. *)\n\nTheorem Zquot_le_upper_bound:\n  forall a b q, 0 < b -> a <= q*b -> a÷b <= q.\nProof. intros a b q; rewrite Zmult_comm; apply Z.quot_le_upper_bound. Qed.\n\nTheorem Zquot_lt_upper_bound:\n  forall a b q, 0 <= a -> 0 < b -> a < q*b -> a÷b < q.\nProof. intros a b q; rewrite Zmult_comm; apply Z.quot_lt_upper_bound. Qed.\n\nTheorem Zquot_le_lower_bound:\n  forall a b q, 0 < b -> q*b <= a -> q <= a÷b.\nProof. intros a b q; rewrite Zmult_comm; apply Z.quot_le_lower_bound. Qed.\n\nTheorem Zquot_sgn: forall a b,\n  0 <= Zsgn (a÷b) * Zsgn a * Zsgn b.\nProof.\n  destruct a as [ |a|a]; destruct b as [ |b|b]; simpl; auto with zarith;\n  unfold Zquot; simpl; destruct Pdiv_eucl; simpl; destruct n; simpl; auto with zarith.\nQed.\n\n(** * Relations between usual operations and Zmod and Zdiv *)\n\n(** First, a result that used to be always valid with Zdiv,\n    but must be restricted here.\n    For instance, now (9+(-5)*2) rem 2 = -1 <> 1 = 9 rem 2 *)\n\nLemma Z_rem_plus : forall a b c:Z,\n 0 <= (a+b*c) * a ->\n Zrem (a + b * c) c = Zrem a c.\nProof. intros. zero_or_not c. apply Z.rem_add; auto with zarith. Qed.\n\nLemma Z_quot_plus : forall a b c:Z,\n 0 <= (a+b*c) * a -> c<>0 ->\n (a + b * c) ÷ c = a ÷ c + b.\nProof. intros. apply Z.quot_add; auto with zarith. Qed.\n\nTheorem Z_quot_plus_l: forall a b c : Z,\n 0 <= (a*b+c)*c -> b<>0 ->\n b<>0 -> (a * b + c) ÷ b = a + c ÷ b.\nProof. intros. apply Z.quot_add_l; auto with zarith. Qed.\n\n(** Cancellations. *)\n\nLemma Zquot_mult_cancel_r : forall a b c:Z,\n c<>0 -> (a*c)÷(b*c) = a÷b.\nProof. intros. zero_or_not b. apply Z.quot_mul_cancel_r; auto. Qed.\n\nLemma Zquot_mult_cancel_l : forall a b c:Z,\n c<>0 -> (c*a)÷(c*b) = a÷b.\nProof.\n intros. rewrite (Zmult_comm c b). zero_or_not b.\n rewrite (Zmult_comm b c). apply Z.quot_mul_cancel_l; auto.\nQed.\n\nLemma Zmult_rem_distr_l: forall a b c,\n  Zrem (c*a) (c*b) = c * (Zrem a b).\nProof.\n intros. zero_or_not c. rewrite (Zmult_comm c b). zero_or_not b.\n rewrite (Zmult_comm b c). apply Z.mul_rem_distr_l; auto.\nQed.\n\nLemma Zmult_rem_distr_r: forall a b c,\n  Zrem (a*c) (b*c) = (Zrem a b) * c.\nProof.\n intros. zero_or_not b. rewrite (Zmult_comm b c). zero_or_not c.\n rewrite (Zmult_comm c b). apply Z.mul_rem_distr_r; auto.\nQed.\n\n(** Operations modulo. *)\n\nTheorem Zrem_rem: forall a n, Zrem (Zrem a n) n = Zrem a n.\nProof. intros. zero_or_not n. apply Z.rem_rem; auto. Qed.\n\nTheorem Zmult_rem: forall a b n,\n Zrem (a * b) n = Zrem (Zrem a n * Zrem b n) n.\nProof. intros. zero_or_not n. apply Z.mul_rem; auto. Qed.\n\n(** addition and modulo\n\n  Generally speaking, unlike with Zdiv, we don't have\n       (a+b) rem n = (a rem n + b rem n) rem n\n  for any a and b.\n  For instance, take (8 + (-10)) rem 3 = -2 whereas\n  (8 rem 3 + (-10 rem 3)) rem 3 = 1. *)\n\nTheorem Zplus_rem: forall a b n,\n 0 <= a * b ->\n Zrem (a + b) n = Zrem (Zrem a n + Zrem b n) n.\nProof. intros. zero_or_not n. apply Z.add_rem; auto. Qed.\n\nLemma Zplus_rem_idemp_l: forall a b n,\n 0 <= a * b ->\n Zrem (Zrem a n + b) n = Zrem (a + b) n.\nProof. intros. zero_or_not n. apply Z.add_rem_idemp_l; auto. Qed.\n\nLemma Zplus_rem_idemp_r: forall a b n,\n 0 <= a*b ->\n Zrem (b + Zrem a n) n = Zrem (b + a) n.\nProof.\n intros. zero_or_not n. apply Z.add_rem_idemp_r; auto.\n rewrite Zmult_comm; auto.\nQed.\n\nLemma Zmult_rem_idemp_l: forall a b n, Zrem (Zrem a n * b) n = Zrem (a * b) n.\nProof. intros. zero_or_not n. apply Z.mul_rem_idemp_l; auto. Qed.\n\nLemma Zmult_rem_idemp_r: forall a b n, Zrem (b * Zrem a n) n = Zrem (b * a) n.\nProof. intros. zero_or_not n. apply Z.mul_rem_idemp_r; auto. Qed.\n\n(** Unlike with Zdiv, the following result is true without restrictions. *)\n\nLemma Zquot_Zquot : forall a b c, (a÷b)÷c = a÷(b*c).\nProof.\n intros. zero_or_not b. rewrite Zmult_comm. zero_or_not c.\n rewrite Zmult_comm. apply Z.quot_quot; auto.\nQed.\n\n(** A last inequality: *)\n\nTheorem Zquot_mult_le:\n forall a b c, 0<=a -> 0<=b -> 0<=c -> c*(a÷b) <= (c*a)÷b.\nProof. intros. zero_or_not b. apply Z.quot_mul_le; auto with zarith. Qed.\n\n(** Zrem is related to divisibility (see more in Znumtheory) *)\n\nLemma Zrem_divides : forall a b,\n Zrem a b = 0 <-> exists c, a = b*c.\nProof.\n intros. zero_or_not b. firstorder.\n rewrite Z.rem_divide; trivial. split; intros (c,Hc); exists c; auto.\nQed.\n\n(** Particular case : dividing by 2 is related with parity *)\n\nLemma Zquot2_odd_remainder : forall a,\n Remainder a 2 (if Zodd_bool a then Zsgn a else 0).\nProof.\n intros [ |p|p]. simpl.\n left. simpl. auto with zarith.\n left. destruct p; simpl; auto with zarith.\n right. destruct p; simpl; split; now auto with zarith.\nQed.\n\nLemma Zquot2_quot : forall a, Zquot2 a = a÷2.\nProof.\n intros.\n apply Zquot_unique_full with (if Zodd_bool a then Zsgn a else 0).\n apply Zquot2_odd_remainder.\n apply Zquot2_odd_eqn.\nQed.\n\nLemma Zrem_odd : forall a, Zrem a 2 = if Zodd_bool a then Zsgn a else 0.\nProof.\n intros. symmetry.\n apply Zrem_unique_full with (Zquot2 a).\n apply Zquot2_odd_remainder.\n apply Zquot2_odd_eqn.\nQed.\n\nLemma Zrem_even : forall a, Zrem a 2 = if Zeven_bool a then 0 else Zsgn a.\nProof.\n intros a. rewrite Zrem_odd, Zodd_even_bool. now destruct Zeven_bool.\nQed.\n\nLemma Zeven_rem : forall a, Zeven_bool a = Zeq_bool (Zrem a 2) 0.\nProof.\n intros a. rewrite Zrem_even.\n destruct a as [ |p|p]; trivial; now destruct p.\nQed.\n\nLemma Zodd_rem : forall a, Zodd_bool a = negb (Zeq_bool (Zrem a 2) 0).\nProof.\n intros a. rewrite Zrem_odd.\n destruct a as [ |p|p]; trivial; now destruct p.\nQed.\n\n(** * Interaction with \"historic\" Zdiv *)\n\n(** They agree at least on positive numbers: *)\n\nTheorem Zquotrem_Zdiv_eucl_pos : forall a b:Z, 0 <= a -> 0 < b ->\n  a÷b = a/b /\\ Zrem a b = a mod b.\nProof.\n  intros.\n  apply Zdiv_mod_unique with b.\n  apply Zrem_lt_pos; auto with zarith.\n  rewrite Zabs_eq; auto with *; apply Z_mod_lt; auto with *.\n  rewrite <- Z_div_mod_eq; auto with *.\n  symmetry; apply Z_quot_rem_eq; auto with *.\nQed.\n\nTheorem Zquot_Zdiv_pos : forall a b, 0 <= a -> 0 <= b ->\n  a÷b = a/b.\nProof.\n intros a b Ha Hb.\n destruct (Zle_lt_or_eq _ _ Hb).\n generalize (Zquotrem_Zdiv_eucl_pos a b Ha H); intuition.\n subst; rewrite Zquot_0_r, Zdiv_0_r; reflexivity.\nQed.\n\nTheorem Zrem_Zmod_pos : forall a b, 0 <= a -> 0 < b ->\n  Zrem a b = a mod b.\nProof.\n intros a b Ha Hb; generalize (Zquotrem_Zdiv_eucl_pos a b Ha Hb);\n intuition.\nQed.\n\n(** Modulos are null at the same places *)\n\nTheorem Zrem_Zmod_zero : forall a b, b<>0 ->\n (Zrem a b = 0 <-> a mod b = 0).\nProof.\n intros.\n rewrite Zrem_divides, Zmod_divides; intuition.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/ZArith/Zquot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417086, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7143399251515029}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import bigenough cauchyreals.\nRequire Import extra_mathcomp extra_cauchyreals.\nRequire Import tactics shift bigopz arithmetics seq_defs.\nRequire Import c_props s_props z3seq_props a_props b_props b_over_a_props.\nRequire hanson.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GRing.Theory Num.Theory BigEnough.\n\nLocal Open Scope ring_scope.\n\n(******************************************************************************)\n(* In this file we define the real number zeta(3) and prove that it is        *)\n(* irrational. This is a constructive proof which is essentially based on the *)\n(* two following 'informal' proofs:                                           *)\n(* - A proof that Euler missed, an informal report, A. van der Poorten,       *)\n(*   Mathematical Intelligencer, vol 1 (1979), pp 195-203                     *)\n(* - An Algolib-aided Version of Apery's Proof of the Irrationality of        *)\n(*   zeta(3) Bruno Salvy, 2003, Maple worksheet available online at           *)\n(*   http://algo.inria.fr/libraries/autocomb/Apery2-html/apery1.html          *)\n(* We however had to make explicit or more elementary some parts of the proof *)\n(* to complete the formalization, see the comments below.                     *)\n(* For the time being, the proof still relies on a result we did not          *)\n(* formalize about the asymptotic behaviour of the sequence lcm(1,...,n).     *)\n(******************************************************************************)\n\n\nLtac raise_big_enough := solve [big_enough_trans].\n\n\n(* We prove that z3seq is a Cauchy sequence. *)\nLemma creal_z3seq : creal_axiom z3seq.\nProof.\nrewrite /creal_axiom.\npose n_inv_seq (n : nat) := n%:Q^-1.\nhave [/= modulus_n_inv modulus_n_inv_P] : {asympt e : i / n_inv_seq i < e}.\n  exists_big_modulus M rat => /=.\n    move=> eps i lt_eps0 hMi.\n    rewrite /n_inv_seq -div1r ltr_pdivr_mulr;\n      last by rewrite ltr0n; raise_big_enough.\n    rewrite -ltr_pdivr_mull // mulr1.\n    apply: lt_trans (archi_boundP _) _; first by rewrite ger0E ltW.\n    rewrite ltr_nat; raise_big_enough.\n  by close.\nexists_big_modulus m rat.\n  move=> eps i j lt_eps_0 hmi hmj.\n  wlog ltij : i j hmi hmj / (j < i)%N.\n    move=> hwlog; case: (ltngtP i j); last by move ->; rewrite subrr.\n    - rewrite distrC; exact/hwlog.\n    - exact/hwlog.\n  rewrite gtr0_norm; last exact: lt_0_Dz3seq.\n  pose v (n : nat) := n%:Q ^- 2.\n  have vpos (n : nat) : (0 < n)%N -> 0 < v n.\n    by move=> ?; rewrite /v invr_gt0; apply: exprn_gt0; rewrite ltr0n.\n  have maj : z3seq i - z3seq j <=\n             - 2%:Q^-1 * \\sum_(j <= k < i) (v (k + 1)%N - v k).\n    rewrite Dz3seqE // big_add1 /= mulr_sumr.\n    apply: ler_sum_nat => k /andP[hjk hki]; rewrite /v addn1.\n    apply: z3seq_smd_maj; rewrite ltr0n; apply: leq_trans _ hjk.\n    raise_big_enough.\n  apply: le_lt_trans maj _; rewrite telescope_nat //.\n  suff maj : v j < 2%:Q * eps.\n    rewrite mulNr -mulrN opprB ltr_pdivr_mull // ltr_subl_addr.\n    apply: lt_trans maj _; rewrite ltr_addl; apply: vpos; exact: ltn_trans ltij.\n  have maj : v j < j%:Q^-1.\n    rewrite /v -div1r ltr_pdivr_mulr; last by rewrite exprn_gt0 // ltr0n.\n    by rewrite mulKf ?ltr1n // lt0r_neq0 // ltr0n.\n  by apply: lt_trans maj _; apply: modulus_n_inv_P; rewrite // pmulr_rgt0.\nby close.\nQed.\n\n\n(* Actual definition of \\zeta(3) as a Cauchy real, i.e. the equivalence class *)\n(* of the sequence z3seq for Cauchy equivalence. *)\nDefinition z3 : creal rat_realFieldType := CReal creal_z3seq.\n\n(* We prove that the sequences z3seq and b / a are asymptotically close. *)\nLemma z3seq_b_over_a_asympt : {asympt e : i / `|z3seq i - b_over_a_seq i| < e}.\nProof.\nexists_big_modulus M rat.\n  move=> eps i peps hmi /=.\n  suff step1 : \\sum_(0 <= i0 < Posz i + 1 :> int) `|c i i0 * s i i0| < eps * a i.\n    suff -> : b_over_a_seq i =\n              z3seq i + (\\sum_(0 <= k < Posz i + 1 :> int) c i k * s i k) / a i.\n      rewrite opprD addNKr normrN normrM normfV.\n      rewrite [X in _ / X](gtr0_norm (lt_0_a _)) // ltr_pdivr_mulr ?lt_0_a //.\n      exact: le_lt_trans (ler_norm_sum _ _ _) _.\n    apply: canLR (mulfK _) _; rewrite ?mulrDl ?divfK ?a_neq0 //.\n    rewrite mulr_sumr -big_split /=; apply: eq_bigr => j _.\n    by rewrite /v /u mulrDr mulrC.\n  rewrite -PoszD !eq_big_int_nat /=.\n  have step2 (i0 : nat) : (0 <= i0 <= i)%N ->\n    `|c i i0 * s i i0| <= c i i0 * i0%:Q / (2%:Q * i%:Q ^ 2).\n    case/andP=> _ hi0; rewrite normrM [`|c i i0|]gtr0_norm ?lt_0_c //.\n    rewrite -mulrA ler_pmul2l //; last exact: lt_0_c.\n    apply: s_maj; rewrite // ltr0n; raise_big_enough.\n  apply: (@le_lt_trans _ _ (\\sum_(0 <= i0 < i + 1)\n                   c i i0 * i0%:Q / (2%:Q * i%:Q ^ 2))).\n    apply: ler_sum_nat => j /andP[h0j].\n    rewrite addn1 ltnS => hji; exact: step2.\n  apply:(@le_lt_trans _ _ ((\\sum_(0 <= i0 < i + 1) c i i0) / (2%:Q * i%:Q))).\n    rewrite mulr_suml; apply: ler_sum_nat => j /andP[h0j].\n    rewrite addn1 ltnS => hji; rewrite -mulrA ler_pmul2l ?lt_0_c //.\n    rewrite mulrA invfM mulrCA ger_pmulr; last by rewrite gtr0E mulr_gt0 ?ltr0n.\n    by rewrite ler_pdivr_mulr ?ltr0n // mul1r ler_nat.\n  rewrite mulrC -eq_big_int_nat /= ltr_pmul2r; last first.\n    rewrite -/(a i); exact: lt_0_a.\n  rewrite invfM ltr_pdivr_mulr ?ltr0n // mulrC -ltr_pdivr_mulr //.\n  apply: lt_trans (archi_boundP _) _; last by rewrite ltr_nat; raise_big_enough.\n  by rewrite mulr_ge0 // invr_ge0 ltW.\nby close.\nQed.\n\n(* As a corollary, b_over_a itself is also a Cauchy sequence. *)\nCorollary creal_b_over_a_seq : creal_axiom b_over_a_seq.\nProof. apply: (@asympt_eq_creal _ z3); exact: z3seq_b_over_a_asympt. Qed.\n\n(* We define the Cauchy real b_over_a, i.e. the equivalent class *)\n(* of the sequence b / a for Cauchy equivalence. *)\nDefinition b_over_a := CReal creal_b_over_a_seq.\n\n(* Obviously, z3 and b_over_a are the same Cauchy real. *)\nFact z3_eq_b_over_a : (z3 == b_over_a)%CR.\nProof. exact/eq_crealP/z3seq_b_over_a_asympt. Qed.\n\n\n(* Using the properties of the Casoratian of a and b, we establish the *)\n(* positivity of zeta3 - b n / an. *)\nLemma lt0_z3_minus_b_over_a (n : nat) :\n  (2 <= n)%N -> (0%:CR < z3 - (b_over_a_seq n)%:CR)%CR.\nProof.\nmove=> le2n.\npose_big_enough m.\n  have diff_pos1 (k l : nat) : (k < l)%N -> (1 < k)%N ->\n                               0 < b_over_a_seq l - b_over_a_seq k.\n    move=> ltkn lt1k; rewrite Db_over_a_casoratian //.\n    rewrite (big_cat_nat _ _ _ (leqnSn _) ltkn) big_nat1 /=.\n    have aux (i : nat) : 0 < 6%:Q / (i%:Q + 1) ^ 3 / (a (int.shift 1 i) * a i).\n      apply: divr_gt0; first by apply: lt_0_ba_casoratian.\n      apply:mulr_gt0; exact: lt_0_a.\n    apply: ltr_spaddl => //;  apply: sumr_ge0 => i _; exact: ltW.\n  have -> : (z3 - (b_over_a_seq n)%:CR ==\n         z3 - (b_over_a_seq m)%:CR + (b_over_a_seq m - b_over_a_seq n)%:CR)%CR.\n    by apply: eq_creal_ext => i /=; ring.\n  rewrite z3_eq_b_over_a; apply: ltcr_spaddr.\n    apply/lt_creal_cst/diff_pos1; raise_big_enough.\n  by apply: (@le_crealP _ m.+1) => *; apply/ltW/diff_pos1; raise_big_enough.\nby close.\nQed.\n\n(* Again using the properties of the casoratian, we can prove that *)\n(* delta n := a(n)zeta3(n) - b(n) is dominated by O(1 / a(n)^2). An easy   *)\n(* constant is (a \"nearby\" rational number equal or greater than) 6 * zeta(3).*)\nDefinition Kdelta := ubound (6%:Q%:CR * z3)%CR.\n\n(* Later in the study of sequence sigma we'll need the fact that this constant *)\n(* is non zero. *)\nFact lt_0_Kdelta : 0 < Kdelta.\nProof. exact: ubound_gt0. Qed.\n\nLemma delta_asympt : {large : nat | forall n, (large <= n)%N ->\n     ((a n)%:CR * z3 - (b n)%:CR <= (Kdelta * (1 / a n))%:CR)%CR}.\nProof.\npose_big_enough large.\nexists large => n hlarge.\n  apply: (@lecr_trans _ (6%:Q%:CR * z3 * (1 / a n)%:CR))%CR; last first.\n    rewrite cst_crealM.\n    by apply/lecr_mulf2r/divr_ge0/le_0_a; first exact: le_ubound.\n  rewrite {1}z3_eq_b_over_a; apply: (@le_crealP _ n) => i leni /=.\n  rewrite mul1r ler_subl_addr mulrC -ler_pdivl_mulr ?lt_0_a // mulrDl.\n  rewrite -[_ / _ / _]mulrA -[_ / _]invfM -expr2 -ler_subl_addr.\n  rewrite -/(b_over_a_seq n).\n  have leSnSi : (n.+1 <= i.+1)%N by [].\n  rewrite z3seqE mulr_sumr (big_cat_nat _ _ _ _ leSnSi) //= mulrDl ler_paddl //.\n    rewrite divr_ge0 ?exprn_ge0 ?le_0_a ?sumr_ge0 // => k _.\n    by rewrite divr_ge0 ?exprn_ge0 ?ler0n.\n  rewrite big_add1 /= Db_over_a_casoratian; [ | raise_big_enough | exact: leni].\n  rewrite mulr_suml; apply: ler_sum_nat => j /andP[hnj hji].\n  rewrite -mulrSr ler_pmul2l; last by apply/divr_gt0/exprz_gt0; rewrite ltr0n.\n  rewrite lef_pinv; [| apply: mulr_gt0; exact: lt_0_a..].\n  by apply: ler_pmul; rewrite ?le_0_a //; apply: a_incr; lia.\nby close.\nQed.\n\nDefinition Ndelta := projT1 delta_asympt.\n\nFact NdeltaP (n : nat) : (Ndelta <= n)%N ->\n     ((a n)%:CR * z3 - (b n)%:CR <= (Kdelta * (1 / a n))%:CR)%CR.\nProof. by rewrite /Ndelta; case: delta_asympt => /= ?; exact. Qed.\n\n\n(* We define an a priori real valued sequence whose properties forbid *)\n(* zeta(3) to be irrational. ***)\n\nLocal Notation l := iter_lcmn.\n\nDefinition sigma (n : nat) :=\n  (2%:Q%:CR * ((l n)%:Q ^ 3)%:CR * ((a n)%:CR * z3 - (b n)%:CR))%CR.\n\n(* Sequence sigma has positive terms. *)\nLemma lt_0_sigma (n : nat) : (2 <= n)%N -> (0%CR < sigma n)%CR.\nProof.\nmove=> le2n; rewrite /sigma -!cst_crealM; apply: mulr_gtcr0.\n  by apply/lt_creal_cst; rewrite mulr_gt0 // exprz_gt0 ?ltr0n.\nsuff : (0 < (a n)%:CR * (z3 - (b_over_a_seq n)%:CR))%CR.\n  by rewrite mulcrDr mulcrN -cst_crealM mulrC mulfVK // a_neq0.\nexact/mulr_gtcr0/lt0_z3_minus_b_over_a/le2n/lt_creal_cst/lt_0_a.\nQed.\n\n(* This is the *statement* of the result we use without a formal *)\n(* proof. It is a weak corollary of the Prime Number Theorem (pnt) but *)\n(* can be obtained directly from more elementary means, see a proof in *)\n(* \"On the product of the primes\" D. Hanson, *)\n(* Canad. Math. Bull. Vol. 15(1), 1972. *)\n(* A close inspection of the paper validates in particular the *)\n(* hypothesis we need on K2^3. *)\n\n(* Definition weak_pnt := exists K2 : rat, exists K3 : rat, exists N : nat, *)\n(*   [/\\ 0 < K2, *)\n(*       0 < K3, *)\n(*       K2 ^ 3 < 33%:~R & *)\n(*       forall n : nat, (N <= n)%N ->  (l n)%:~R < K3 * K2 ^ n]. *)\n\n(* In the following two sections, we work in a context which assumes *)\n(* that property weak_pnt holds. *)\nSection SigmaGoesToZero.\n\nLemma hanson : exists K2 : rat, exists K3 : rat, exists N : nat,\n  [/\\ 0 < K2,\n      0 < K3,\n      K2 ^ 3 < 33%:Q &\n      forall n : nat, (N <= n)%N ->  (l n)%:Q < K3 * K2 ^ n].\nProof.\nexists 3%:Q.\ncase: hanson.Hanson.t3 => K [Hpos H].\nexists (K.+1)%:Q; exists 0%N.\nrewrite !ltr0n; split => // n _; apply: le_lt_trans (H n) _.\nby rewrite -exprnP -natrX -natrM ltr_nat ltn_mul2r expn_gt0 /=. (* funny: does not work without the /= *)\nQed.\n\nLemma sigma_goes_to_0 (eps : rat) : 0 < eps ->\n  exists M : nat, forall n : nat, (M <= n)%N -> (sigma n < eps%:CR)%CR.\nProof.\nmove=> eps_pos.\nhave [K2 [K3 [large [K2pos K3pos K2_maj hanson]]]] := hanson.\npose C := 2%:Q * (K3 ^ 3) * Kdelta * Ka ^-1.\nhave Cpos : 0 < C.\n  by rewrite !(exprz_gt0, mulr_gt0) ?invr_gt0 ?lt_0_Ka ?lt_0_Kdelta.\nhave heps : 0 < eps / C by apply: divr_gt0.\nhave hr : 0 < K2 ^ 3 / 33%:Q < 1.\n  by rewrite andbC -ltr_pdivl_mulr // invrK mul1r K2_maj divr_gt0 // exprn_gt0.\nhave [N hN] := Gseqlt1 heps hr.\npose_big_enough M.\n  exists M => n hn.\n  have aux : (sigma n <\n         (2%:Q * (K3 * K2 ^ n) ^ 3 * Kdelta / Ka / 33%:Q ^ n)%:CR)%CR.\n    rewrite /sigma -mulcrA -3!mulrA [in X in (_ < X)%CR]cst_crealM.\n    apply: ltcr_mul2l; last exact/lt_creal_cst.\n    have Dn_pos : 0 < (l n)%:Q.\n      rewrite -[0]/(0%:Q) ltr_nat iter_lcmn_gt0; raise_big_enough.\n    rewrite [in X in (_ < X)%CR]cst_crealM.\n    apply: ltcr_pmul; first exact/lt_creal_cst/exprn_gt0.\n    - apply/lt_creal_cst; apply: mulr_gt0; first exact: lt_0_Kdelta.\n      apply: divr_gt0; last by apply: exprn_gt0; rewrite ltr0n.\n      rewrite invr_gt0; exact: lt_0_Ka.\n    - apply/lt_creal_cst; rewrite ltr_expn2r //; first exact: ltW.\n      apply: hanson; raise_big_enough.\n    - apply: lecr_lt_trans (NdeltaP _) _; first by raise_big_enough.\n      apply/lt_creal_cst; rewrite ltr_pmul2l; last exact: lt_0_Kdelta.\n      apply: a_asympt; raise_big_enough.\n  apply: lt_creal_trans aux _; apply/lt_creal_cst; set lhs := (X in (X < _)).\n  have -> : lhs = C * (K2 ^ 3 / 33%:Q) ^ n.\n    (* what an ugly script... rat_field is bad with _ ^ n *)\n    rewrite {}/lhs /C [in RHS]expfzMl exprzAC -[in RHS]expfV.\n    set x := _ ^ n; set y := _ ^ n; field.\n    by rewrite expfz_neq0 ?intr_eq0 // lt0r_neq0 ?lt_0_Ka.\n  rewrite -ltr_pdivl_mull -[X in _ < X]mulrC; last by rewrite mulrC; exact: Cpos.\n  apply: hN; raise_big_enough.\nby close.\nQed.\n\nEnd  SigmaGoesToZero.\n\nSection AperyConstantIsIrrational.\n\n(* Finally, the irrationality proof of zeta(3). We do not use the standard *)\n(* irrationality criterium using the denominator scale, but rather a *)\n(* simpler argument based on iter_lcmn_mul_rat that works in our case. *)\nTheorem zeta_3_irrational : ~ exists (r : rat), (z3 == r%:CR)%CR.\nProof.\ncase=> z3_rat z3_ratP; case: (denqP z3_rat) z3_ratP => d dP z3_ratP.\nhave heps : 0 < 1 / 2%:Q by [].\nhave [M MP] := sigma_goes_to_0 heps.\npose sigma_Q (n : nat) := 2%:Q * (l n)%:Q ^ 3%N * (a n * z3_rat - b n).\nhave sigma_QP (n : nat) : ((sigma_Q n)%:CR == sigma n)%CR.\n  by rewrite /sigma z3_ratP -!cst_crealM -cst_crealB -cst_crealM.\npose_big_enough n.\n  have h_pos : 0 < sigma_Q n.\n    apply/lt_creal_cst; rewrite sigma_QP; apply: lt_0_sigma; raise_big_enough.\n  have h_lt1 : sigma_Q n < 1 / 2%:Q.\n    apply/lt_creal_cst; rewrite sigma_QP; apply: MP; raise_big_enough.\n  suff : 1 <= sigma_Q n by apply/negP; rewrite -ltNge; apply: lt_trans h_lt1 _.\n  suff /QintP [z zP] : sigma_Q n \\is a Qint.\n    by move: h_pos; rewrite zP ler1z -gtz0_ge1 ltr0z; apply.\n  rewrite /sigma_Q mulrDr mulrN; apply/rpredB/Qint_l3b.\n  rewrite -mulrA; apply: rpredM (rpred_int _ _) _.\n  rewrite /exprz exprSr mulrACA mulrC.\n  apply/rpredM/rpredM/Qint_a/rpredX/rpred_int/iter_lcmn_mul_rat.\n  rewrite normr_denq dP lez_nat; raise_big_enough.\nby close.\nQed.\n\nEnd AperyConstantIsIrrational.\n\nAbout zeta_3_irrational.\n (* Time *) Print Assumptions zeta_3_irrational.\n", "meta": {"author": "coq-community", "repo": "apery", "sha": "305046d98025d75ca426cc44283302963389f1dc", "save_path": "github-repos/coq/coq-community-apery", "path": "github-repos/coq/coq-community-apery/apery-305046d98025d75ca426cc44283302963389f1dc/theories/z3irrational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7142585414366532}}
{"text": "Require Import Setoid.\nRequire Import Morphisms.\nRequire Import Coq.Program.Basics.\nRequire Import NArith.\nRequire Import ClassicalFacts.\n\nUnset Printing Records.\n\nFrom Ordinal Require Import Defs.\nFrom Ordinal Require Import Operators.\nFrom Ordinal Require Import Classical.\n\n(* We say a function f enumerates a class of ordinals P if\n   f x is the least element of P that is strictly above\n   all f y for y < x. *)\nRecord enumerates (f:Ord -> Ord) (P:Ord -> Prop) : Prop :=\n  Enumerates\n    { enumerates_included   : forall x, P (f x);\n      enumerates_monotone   : forall x y, x ≤ y -> f x ≤ f y;\n      enumerates_increasing : forall x y, x < y -> f x < f y;\n      enumerates_least      : forall x z, P z -> (forall y, y < x -> f y < z) -> f x ≤ z\n    }.\n\nLemma enumerates_range (EM:excluded_middle) f :\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  (forall x y, x < y -> f x < f y) ->\n  enumerates f (fun x => exists y, x ≈ f y).\nProof.\n  intros Hmono Hinc.\n  constructor; auto.\n  - intro x; exists x; reflexivity.\n  - intros x z [y Hy] H.\n    rewrite Hy.\n    destruct (classical.order_total EM x y).\n    + apply Hmono; auto.\n    + apply H in H0.\n      rewrite <- Hy in H0.\n      elim (ord_lt_irreflexive z); auto.\nQed.\n\nLemma enumerates_equiv_pred f P P' :\n  (forall x, P x <-> P' x) ->\n  enumerates f P ->\n  enumerates f P'.\nProof.\n  intros Hp Hf.\n  constructor.\n  - intro x. apply Hp. apply enumerates_included; auto.\n  - eapply enumerates_monotone; eauto.\n  - eapply enumerates_increasing; eauto.\n  - intros x z Hz1 Hz2.\n    apply (enumerates_least f P Hf); auto.\n    apply Hp; auto.\nQed.\n\n\nLemma enumerates_unique_aux f g P :\n  enumerates f P ->\n  enumerates g P ->\n  (forall x, f x ≤ g x).\nProof.\n  intros Hf Hg.\n  induction x using ordinal_induction.\n  apply (enumerates_least f P Hf x); auto.\n  apply (enumerates_included g P Hg x).\n  intros y Hy.\n  apply ord_le_lt_trans with (g y).\n  apply H; auto.\n  apply (enumerates_increasing g P Hg y x); auto.\nQed.\n\nTheorem enumerates_unique f g P :\n  enumerates f P ->\n  enumerates g P ->\n  (forall x, f x ≈ g x).\nProof.\n  intros; split; apply enumerates_unique_aux with P; auto.\nQed.\n\n(* If f enumeates P then f 0 is the least element of P *)\nTheorem enumerates_zero f P :\n  enumerates f P ->\n  (forall z, P z -> f 0 ≤ z).\nProof.\n  intros Henum z Hz.\n  apply (enumerates_least f P Henum 0); auto.\n  intros.\n  rewrite ord_lt_unfold in H.\n  destruct H as [[] _].\nQed.\n\n(* If f enumeates P then f (S x) is the least element of P strictly above (f x) *)\nTheorem enumerates_succ f P :\n  enumerates f P ->\n  (forall x z, P z -> f x < z -> f (succOrd x) <= z).\nProof.\n  intros Henum x z Hz Hx.\n  apply (enumerates_least f P Henum (succOrd x)); auto.\n  intros y Hy.\n  apply ord_le_lt_trans with (f x); auto.\n  apply (enumerates_monotone f P Henum y x); auto.\n  rewrite ord_lt_unfold in Hy.\n  destruct Hy as [[] Hy].\n  auto.\nQed.\n\n(* Classically, we can show that if f enumerates P then\n   f is surjective on P.\n *)\nTheorem enumerates_surjective (EM:excluded_middle) f P:\n  enumerates f P -> forall x, P x -> exists a, f a ≈ x.\nProof.\n  intros Henum x Hx.\n  set (Q z := f z >= x).\n  destruct (classical.ord_well_ordered EM Q x) as [a [??]]; auto.\n  - hnf. apply increasing_inflationary.\n    apply (enumerates_increasing f P Henum).\n  - exists a. unfold Q in *.\n    split; auto.\n    apply (enumerates_least f P Henum a); auto.\n    intros y Hy.\n    destruct (classical.order_total EM x (f y)); auto.\n    apply H0 in H1.\n    elim (ord_lt_irreflexive y).\n    apply ord_lt_le_trans with a; auto.\nQed.\n\n(* Morover, classically a monotone, increasing, surjective function onto P enumerates P.\n *)\nTheorem increasing_surjective_enumerates (EM:excluded_middle) f (P:Ord -> Prop) :\n  (forall x y, x ≤ y -> f x ≤ f y) ->\n  (forall x y, x < y -> f x < f y) ->\n  (forall x, P x -> exists a, f a ≈ x) ->\n  (forall x, P (f x)) ->\n  enumerates f P.\nProof.\n  intros Hmono Hinc Hsurj HP.\n  constructor; auto.\n\n  intros x z Hz1 Hz2.\n  destruct (Hsurj z) as [a Ha]; auto.\n  rewrite <- Ha.\n  destruct (classical.order_total EM x a); auto.\n  apply Hz2 in H.\n  elim (ord_lt_irreflexive z).\n  apply ord_le_lt_trans with (f a); auto.\n  apply Ha.\nQed.\n\n\nDefinition unbounded (P:Ord -> Prop) :=\n  forall x, P x -> exists y, x < y /\\ P y.\n\nCorollary enumerates_unbounded (EM:excluded_middle) f P :\n  enumerates f P -> unbounded P.\nProof.\n  intros Henum x Hx.\n  destruct (enumerates_surjective EM f P Henum x Hx) as [a Ha].\n  exists (f (succOrd a)).\n  split.\n  rewrite <- Ha.\n  apply enumerates_increasing with P; auto.\n  apply succ_lt.\n  apply enumerates_included. auto.\nQed.\n\n", "meta": {"author": "robdockins", "repo": "ordinals", "sha": "063164521baddfc99ab8c2d222cb01637e8833e1", "save_path": "github-repos/coq/robdockins-ordinals", "path": "github-repos/coq/robdockins-ordinals/ordinals-063164521baddfc99ab8c2d222cb01637e8833e1/Ordinal/Enumerate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7142585392617848}}
{"text": "Section Declaration.\n    Variable n: nat.\n    Hypothesis Pos_n: (gt n 0).\n    Check gt.\n    Definition one:= (S O).\n    Definition two : nat := S one.\n    Definition three: nat:=S two.\n    Definition double (m:nat):=plus m m.\nSection Minimal_Logic.\n    Variables A B C : Prop.\n    Check (A->B).\n    Goal ( A -> B -> C) -> ( A -> B ) -> A -> C.\n    intro H.\n    intros H' HA.\n    apply H.\n    exact HA.\n    apply H'.\n    assumption.\n", "meta": {"author": "TralahM", "repo": "CoqProofs", "sha": "f9280492e2f124fd63546f2878486cfc5396cda6", "save_path": "github-repos/coq/TralahM-CoqProofs", "path": "github-repos/coq/TralahM-CoqProofs/CoqProofs-f9280492e2f124fd63546f2878486cfc5396cda6/getting_started.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7142585327257909}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import PeanoNat.\n\nLocal Open Scope nat_scope.\n\n\n\nNotation lt_irrefl := Nat.lt_irrefl.\n\nHint Resolve lt_irrefl: arith.\n\n\n\nTheorem lt_le_S n m : n < m -> S n <= m.\nProof. hammer_hook \"Lt\" \"Lt.lt_le_S\".\napply Nat.le_succ_l.\nQed.\n\nTheorem lt_n_Sm_le n m : n < S m -> n <= m.\nProof. hammer_hook \"Lt\" \"Lt.lt_n_Sm_le\".\napply Nat.lt_succ_r.\nQed.\n\nTheorem le_lt_n_Sm n m : n <= m -> n < S m.\nProof. hammer_hook \"Lt\" \"Lt.le_lt_n_Sm\".\napply Nat.lt_succ_r.\nQed.\n\nHint Immediate lt_le_S: arith.\nHint Immediate lt_n_Sm_le: arith.\nHint Immediate le_lt_n_Sm: arith.\n\nTheorem le_not_lt n m : n <= m -> ~ m < n.\nProof. hammer_hook \"Lt\" \"Lt.le_not_lt\".\napply Nat.le_ngt.\nQed.\n\nTheorem lt_not_le n m : n < m -> ~ m <= n.\nProof. hammer_hook \"Lt\" \"Lt.lt_not_le\".\napply Nat.lt_nge.\nQed.\n\nHint Immediate le_not_lt lt_not_le: arith.\n\n\n\nNotation lt_asym := Nat.lt_asymm.\n\n\n\nNotation lt_0_Sn := Nat.lt_0_succ.\nNotation lt_n_0 := Nat.nlt_0_r.\n\nTheorem neq_0_lt n : 0 <> n -> 0 < n.\nProof. hammer_hook \"Lt\" \"Lt.neq_0_lt\".\nintros. now apply Nat.neq_0_lt_0, Nat.neq_sym.\nQed.\n\nTheorem lt_0_neq n : 0 < n -> 0 <> n.\nProof. hammer_hook \"Lt\" \"Lt.lt_0_neq\".\nintros. now apply Nat.neq_sym, Nat.neq_0_lt_0.\nQed.\n\nHint Resolve lt_0_Sn lt_n_0 : arith.\nHint Immediate neq_0_lt lt_0_neq: arith.\n\n\n\nNotation lt_n_Sn := Nat.lt_succ_diag_r.\nNotation lt_S := Nat.lt_lt_succ_r.\n\nTheorem lt_n_S n m : n < m -> S n < S m.\nProof. hammer_hook \"Lt\" \"Lt.lt_n_S\".\napply Nat.succ_lt_mono.\nQed.\n\nTheorem lt_S_n n m : S n < S m -> n < m.\nProof. hammer_hook \"Lt\" \"Lt.lt_S_n\".\napply Nat.succ_lt_mono.\nQed.\n\nHint Resolve lt_n_Sn lt_S lt_n_S : arith.\nHint Immediate lt_S_n : arith.\n\n\n\nLemma S_pred n m : m < n -> n = S (pred n).\nProof. hammer_hook \"Lt\" \"Lt.S_pred\".\nintros. symmetry. now apply Nat.lt_succ_pred with m.\nQed.\n\nLemma lt_pred n m : S n < m -> n < pred m.\nProof. hammer_hook \"Lt\" \"Lt.lt_pred\".\napply Nat.lt_succ_lt_pred.\nQed.\n\nLemma lt_pred_n_n n : 0 < n -> pred n < n.\nProof. hammer_hook \"Lt\" \"Lt.lt_pred_n_n\".\nintros. now apply Nat.lt_pred_l, Nat.neq_0_lt_0.\nQed.\n\nHint Immediate lt_pred: arith.\nHint Resolve lt_pred_n_n: arith.\n\n\n\nNotation lt_trans := Nat.lt_trans.\nNotation lt_le_trans := Nat.lt_le_trans.\nNotation le_lt_trans := Nat.le_lt_trans.\n\nHint Resolve lt_trans lt_le_trans le_lt_trans: arith.\n\n\n\nNotation le_lt_or_eq_iff := Nat.lt_eq_cases.\n\nTheorem le_lt_or_eq n m : n <= m -> n < m \\/ n = m.\nProof. hammer_hook \"Lt\" \"Lt.le_lt_or_eq\".\napply Nat.lt_eq_cases.\nQed.\n\nNotation lt_le_weak := Nat.lt_le_incl.\n\nHint Immediate lt_le_weak: arith.\n\n\n\nNotation le_or_lt := Nat.le_gt_cases.\n\nTheorem nat_total_order n m : n <> m -> n < m \\/ m < n.\nProof. hammer_hook \"Lt\" \"Lt.nat_total_order\".\napply Nat.lt_gt_cases.\nQed.\n\n\nNotation lt_O_Sn := lt_0_Sn (only parsing).\nNotation neq_O_lt := neq_0_lt (only parsing).\nNotation lt_O_neq := lt_0_neq (only parsing).\nNotation lt_n_O := lt_n_0 (only parsing).\n\n\n\n\nRequire Import Le.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/quick/Lt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7141624566491288}}
{"text": "\nSection Minimal_propositional_logic.\n Variables P Q R T : Prop.\n\n\n Theorem imp_trans : (P->Q)->(Q->R)->P->R.\n Proof.\n  intros H H' p.\n  apply H'.\n  apply H.\n  assumption.\n Qed.\n\n \n Theorem imp_trans' : (P->Q)->(Q->R)->P->R.\n Proof.\n  intros H H' p; apply H'; apply H; assumption.\n Qed.\n\n Theorem imp_trans'' : (P->Q)->(Q->R)->P->R.\n Proof.\n  auto. \n Qed.\n\n Theorem delta : (P->P->Q)->P->Q.\n Proof (fun (H:P->P->Q)(p:P) => H p p).\n\n Lemma apply_example : (Q->R->T)->(P->Q)->P->R->T.\n Proof.\n  intros H H0 p.\n  apply H.\n  exact (H0 p).\n Qed.\n\n Theorem imp_dist : (P->Q->R)->(P->Q)->(P->R).\n Proof.\n  intros H H' p.\n  apply H.  \n  - assumption.\n  - apply H'; assumption.\n Qed.\n\n Theorem K : P->Q->P.\n Proof.\n  intros p q;  assumption.\n Qed.\n\n\n \n Section proof_of_triple_impl.\n  Hypothesis H : ((P->Q)->Q)-> Q.\n  Hypothesis p : P.\n\n  Remark  R1 : (P->Q)->Q.\n  Proof fun H0:P->Q => H0 p.\n\n  Theorem triple_impl : Q.\n  Proof H R1.\n\n End proof_of_triple_impl.\n\n\n Theorem triple_impl_one_liner : (((P->Q)->Q)->Q)->P->Q.\n Proof.\n  intros H p; apply H; intro H0; apply H0; assumption.\n Qed.\n\n Lemma imp_dist' : (P->Q->R)->(P->Q)->(P->R).\n Proof.\n  intros H H' p.\n  apply H;[assumption | apply H'; assumption].\n Qed.\n\n\n\n\n\n Section section_assert_example.\n  Hypotheses (H : P->Q)\n             (H0 : Q->R)\n             (H1 : (P->R)->T->Q)\n             (H2 : (P->R)->T).\n \n  Lemma assert_example : Q.\n  Proof.\n   assert (H3 : P -> R).\n   -  intro p; apply H0; apply H; assumption.\n   -  apply H1;[assumption | apply H2; assumption].\n  Qed.\n\n Print assert_example.\n\n End section_assert_example.\n\n Lemma triple_impl2 : (((P->Q)->Q)->Q)->P->Q.\n Proof.\n  auto.\n Qed.\n\nEnd Minimal_propositional_logic.\n\nPrint imp_dist.\n\nSection using_imp_dist.\n Variables (P1 P2 P3 : Prop).\n\n Check imp_dist P1 P2 P3.\n\n Check imp_dist (P1->P2) (P2->P3) (P3->P1).\n\nEnd using_imp_dist.\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/ch3_propositions_proofs/SRC/chap3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759128, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7141624555225571}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := leaf : Tree | node : Nat -> Tree -> Tree -> Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : Lst) (qreva_arg1 : Lst) : Lst\n           := match qreva_arg0, qreva_arg1 with\n              | nil, x => x\n              | cons z x, y => qreva x (cons z y)\n              end.\n\nFixpoint revflat (revflat_arg0 : Tree) : Lst\n           := match revflat_arg0 with\n              | leaf => nil\n              | node d l r => append (revflat l) (cons d (revflat r))\n              end.\n\nFixpoint qrevaflat (qrevaflat_arg0 : Tree) (qrevaflat_arg1 : Lst) : Lst\n           := match qrevaflat_arg0, qrevaflat_arg1 with\n              | leaf, x => x\n              | node d l r, x => qrevaflat l (cons d (qrevaflat r x))\n              end.\n\nLemma append_assoc : forall (x y z : Lst), append (append x y) z = append x (append y z).\nProof.\n  intros.\n  induction x.\n  - reflexivity.\n  - simpl. rewrite IHx. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : Tree) (y : Lst), eq (append (revflat x) y) (qrevaflat x y).\nProof.\n  induction x.\n  - reflexivity.\n  - intros. simpl. rewrite append_assoc. simpl. rewrite IHx2. rewrite IHx1. reflexivity.\nQed.\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal76.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759128, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7141624464205194}}
{"text": "Require Import Bool.\n\nNotation \"[ a ] < [ b ]\" := (forall (F : a -> b), exists (y : b), forall (x : a), F x <> y).\nNotation \"[ a ] > [ b ]\" := ([b] < [a]).\nNotation \"[ a ] = [ b ]\" := (~([a] < [b]) /\\ ~([a] > [b])).\n\nDefinition lemma1 : forall (A : Type)(B : Type)(F : A -> B)(G : A -> B), F = G -> forall (x : A), F x = G x\n := fun A B F G H x => f_equal (fun a : A -> B => a x) H.\n\nDefinition prop1 : forall (A : Type), [A] < [A -> bool] :=\n  fun (A : Type) (F : A -> A -> bool) =>\n    let AbP  := fun y => forall (x : A), F x <> y in\n    let diag := fun x => negb (F x x) in\n    ex_intro AbP diag (fun x H =>\n      no_fixpoint_negb (F x x)\n      (eq_sym (f_equal (fun a => a x) H))\n    ).\n\nDefinition prop2 : forall (A : Type), [A] = [A] :=\n  fun A =>\n    let id : A -> A := (fun a => a) in\n    let P : ~([A] < [A]) := (fun x =>\n      match x id with\n        | ex_intro _ y H => (H y) (eq_refl y)\n      end\n    ) in\n    conj P P.\n", "meta": {"author": "aidatorajiro", "repo": "WorksOfProof", "sha": "e65dd026f5e700ce37ca5ffab86e863616af8641", "save_path": "github-repos/coq/aidatorajiro-WorksOfProof", "path": "github-repos/coq/aidatorajiro-WorksOfProof/WorksOfProof-e65dd026f5e700ce37ca5ffab86e863616af8641/shugo_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7141327313250897}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) : natural :=\n  mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj43_coqofml_pPAck4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741298, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7141053233336061}}
{"text": "(* Reformulation of single Diophantine equations, i.e. p = q for Diophantine polynomials, without parameters. *)\n\nInductive dio_op_pfree := do_add_pfree | do_mul_pfree.\n\n(* Syntax without a constructor for parameters, variables fixed to range over nat *)\n\nInductive dio_polynomial_pfree : Set :=\n| dp_nat_pfree : nat -> dio_polynomial_pfree (* natural number constant *)\n| dp_var_pfree : nat -> dio_polynomial_pfree (* existentially quantified variable *)\n| dp_comp_pfree : dio_op_pfree -> dio_polynomial_pfree -> dio_polynomial_pfree -> dio_polynomial_pfree.\n\nFixpoint dp_eval_pfree φ p := \n  match p with\n  | dp_nat_pfree n => n\n  | dp_var_pfree v => φ v\n  | dp_comp_pfree do_add_pfree p q => dp_eval_pfree φ p + dp_eval_pfree φ q \n  | dp_comp_pfree do_mul_pfree p q => dp_eval_pfree φ p * dp_eval_pfree φ q \n  end.\n\nDefinition H10p_PROBLEM := (dio_polynomial_pfree * dio_polynomial_pfree)%type.\nDefinition H10p_sem e φ := dp_eval_pfree φ (fst e) = dp_eval_pfree φ (snd e). \nDefinition H10p (e : H10p_PROBLEM) := exists φ, H10p_sem e φ.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/H10/H10p.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7140814572489564}}
{"text": "From Coq Require Import List.\nFrom Coq Require Import Psatz.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import Znumtheory.\nImport ListNotations.\n\nLocal Open Scope Z.\n\nFixpoint egcd_aux\n        (n : nat)\n        (r0 a0 b0 r1 a1 b1 : Z) {struct n} : Z * Z :=\n  match n with\n  | 0%nat => (0, 0)\n  | S n => let (q, r) := Z.div_eucl r0 r1 in\n           if r =? 0 then\n             (a1, b1)\n           else\n             egcd_aux n r1 a1 b1 r (a0 - q*a1) (b0 - q*b1)\n  end.\n\n(* returns (x, y) such that x*m + y*n = Z.gcd(x, y) *)\nDefinition egcd (m n : Z) : Z * Z :=\n  if m =? 0 then\n    (0, Z.sgn n)\n  else if n =? 0 then\n    (Z.sgn m, 0)\n  else\n    let num_steps := S (Z.to_nat (Z.log2 (Z.abs m) + Z.log2 (Z.abs n))) in\n    if Z.abs m <? Z.abs n then\n      let (x, y) := egcd_aux num_steps (Z.abs n) 1 0 (Z.abs m) 0 1 in\n      (Z.sgn m * y, Z.sgn n * x)\n    else\n      let (x, y) := egcd_aux num_steps (Z.abs m) 1 0 (Z.abs n) 0 1 in\n      (Z.sgn m * x, Z.sgn n * y).\n\nLemma egcd_aux_spec m n steps r0 a0 b0 r1 a1 b1 :\n  Z.log2 r0 + Z.log2 r1 < Z.of_nat steps ->\n  0 < r1 ->\n  r1 <= r0 ->\n  r0 = a0*m + b0*n ->\n  r1 = a1*m + b1*n ->\n  Z.gcd r0 r1 = Z.gcd m n ->\n  let (x, y) := egcd_aux steps r0 a0 b0 r1 a1 b1 in\n  x*m + y*n = Z.gcd m n.\nProof.\n  revert r0 a0 b0 r1 a1 b1.\n  induction steps as [|steps IH];\n    intros r0 a0 b0 r1 a1 b1 enough_steps r1pos r1gt r0eq r1eq is_gcd.\n  {\n    cbn -[Z.add] in enough_steps.\n    pose proof (Z.log2_nonneg r0).\n    pose proof (Z.log2_nonneg r1).\n    lia.\n  }\n  cbn.\n  pose proof (Z_div_mod r0 r1 ltac:(lia)).\n  destruct (Z.div_eucl r0 r1) as [q r].\n  destruct (Z.eqb_spec r 0) as [->|?].\n  - destruct H.\n    rewrite Z.add_0_r in *.\n    rewrite <- r1eq.\n    rewrite <- is_gcd.\n    rewrite H.\n    rewrite Z.gcd_comm.\n    now rewrite Z.gcd_mul_diag_l by lia.\n  - apply IH; auto.\n    + destruct H.\n      destruct q; try lia; cycle 1.\n      {\n        pose proof (Z.mul_pos_neg r1 (Z.neg p) ltac:(lia) ltac:(lia)).\n        lia.\n      }\n      assert (r + r1 <= r0).\n      {\n        enough (r1 <= r1 * Z.pos p) by lia.\n        apply Z.le_mul_diag_r; lia.\n      }\n      assert (Z.log2 r1 + Z.log2 r < Z.log2 r0 + Z.log2 r1).\n      {\n        enough (Z.log2 r < Z.log2 r0) by lia.\n        pose proof (Z.log2_le_mono (r*2^1) r0 ltac:(lia)).\n        rewrite <- Z.shiftl_mul_pow2 in H2 by lia.\n        rewrite Z.log2_shiftl in H2 by lia.\n        lia.\n      }\n      lia.\n    + lia.\n    + lia.\n    + rewrite !Z.mul_sub_distr_r.\n      replace (a0 * m - q * a1 * m + (b0 * n - q * b1 * n))\n        with (a0 * m + b0*n + (-1) * (q*(a1*m + b1*n)))\n        by lia.\n      rewrite <- r0eq, <-r1eq.\n      lia.\n    + rewrite <- is_gcd.\n      rewrite (proj1 H).\n      rewrite (Z.gcd_comm (r1 * q + r)).\n      rewrite Z.add_comm, Z.mul_comm.\n      now rewrite Z.gcd_add_mult_diag_r.\nQed.\n\nLemma egcd_spec m n :\n  let (x, y) := egcd m n in\n  m*x + n*y = Z.gcd m n.\nProof.\n  unfold egcd.\n  destruct (Z.eqb_spec m 0) as [->|?].\n  { apply Z.sgn_abs. }\n  destruct (Z.eqb_spec n 0) as [->|?].\n  { rewrite Z.gcd_0_r, Z.add_0_r; apply Z.sgn_abs. }\n  pose proof (Z.log2_nonneg (Z.abs m)).\n  pose proof (Z.log2_nonneg (Z.abs n)).\n  destruct (Z.ltb_spec (Z.abs m) (Z.abs n)).\n  - unshelve epose proof (egcd_aux_spec\n                            (Z.abs n) (Z.abs m)\n                            (S (Z.to_nat (Z.log2 (Z.abs m) + Z.log2 (Z.abs n))))\n                            (Z.abs n) 1 0\n                            (Z.abs m) 0 1\n                            _ _ _ _ _ _).\n    + rewrite Nat2Z.inj_succ.\n      rewrite Z2Nat.id by lia.\n      lia.\n    + lia.\n    + lia.\n    + lia.\n    + lia.\n    + lia.\n    + destruct (egcd_aux _ _ _ _ _ _ _).\n      rewrite !Z.mul_assoc.\n      rewrite Z.gcd_abs_l, Z.gcd_comm, Z.gcd_abs_l in H2.\n      rewrite !Z.sgn_abs.\n      lia.\n  - unshelve epose proof (egcd_aux_spec\n                            (Z.abs m) (Z.abs n)\n                            (S (Z.to_nat (Z.log2 (Z.abs m) + Z.log2 (Z.abs n))))\n                            (Z.abs m) 1 0\n                            (Z.abs n) 0 1\n                            _ _ _ _ _ _).\n    + rewrite Nat2Z.inj_succ.\n      rewrite Z2Nat.id by lia.\n      lia.\n    + lia.\n    + lia.\n    + lia.\n    + lia.\n    + lia.\n    + destruct (egcd_aux _ _ _ _ _ _ _).\n      rewrite !Z.mul_assoc.\n      rewrite Z.gcd_abs_l, Z.gcd_comm, Z.gcd_abs_l, Z.gcd_comm in H2.\n      rewrite !Z.sgn_abs.\n      lia.\nQed.\n\nLemma mul_fst_egcd a n :\n  rel_prime a n ->\n  a * fst (egcd a n) mod n = 1 mod n.\nProof.\n  destruct (Z.eqb_spec n 0) as [->|?].\n  { intros; now rewrite !Zmod_0_r. }\n  intros relprime.\n  pose proof (egcd_spec a n).\n  destruct (egcd a n) as [x y]; cbn.\n  rewrite (proj2 (Zgcd_1_rel_prime _ _) relprime) in H.\n  replace (a * x) with (1  + (-y)*n) by lia.\n  rewrite <- Z.add_mod_idemp_r by lia.\n  now rewrite Z.mod_mul, Z.add_0_r by lia.\nQed.\n\nLemma egcd_divides a b :\n  b <> 0 ->\n  (b | a) ->\n  egcd a b = (0, Z.sgn b).\nProof.\n  intros b0 divides.\n  unfold egcd.\n  destruct (Z.eqb_spec a 0) as [->|a0]; [easy|].\n  rewrite (proj2 (Z.eqb_neq _ _) b0).\n  assert (Z.abs b <= Z.abs a) by (apply Zdivide_bounds; auto).\n  replace (Z.abs a <? Z.abs b) with false; cycle 1.\n  { now symmetry; apply Z.ltb_ge. }\n  cbn.\n  pose proof (Z_div_mod_full (Z.abs a) (Z.abs b) ltac:(lia)).\n  destruct (Z.div_eucl (Z.abs a) (Z.abs b)) as [q r].\n  rewrite (Zmod_unique_full _ _ _ _ (proj2 H0) (proj1 H0)).\n  apply Z.divide_abs_l, Z.divide_abs_r in divides.\n  rewrite (Zdivide_mod _ _ divides).\n  cbn.\n  now rewrite Z.mul_0_r, Z.mul_1_r.\nQed.\n", "meta": {"author": "malthelange", "repo": "CLVM", "sha": "e80aef02c3112b5b62db79bc2b233020367b0bde", "save_path": "github-repos/coq/malthelange-CLVM", "path": "github-repos/coq/malthelange-CLVM/CLVM-e80aef02c3112b5b62db79bc2b233020367b0bde/execution/theories/Examples/Egcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7140814486751249}}
{"text": "(* TCfM から圏論の定義の部分を抜き出す。 *)\n(* \"Type Classes for Mathematics in Type Theory\" *)\n\n(* Global Generalizable All Variables. *)\n\n(* Set Implicit Arguments. *)\n\nRequire Import Arith.\nRequire Import Omega.\nRequire Import Relations.                   (* relation など *)\nRequire Import Morphisms.                   (* Proper *)\n\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.ProofIrrelevance.\n\nSection Category_Class.\n  Generalizable Variables O x y.\n  \n  Class Arrows (O : Type) : Type := arrow : O -> O -> Type.\n  Class Equiv A := equiv : relation A.\n  \n  Notation \"A == B\" := (equiv A B) (at level 55, right associativity).\n  Notation \"A --> B\" := (arrow A B) (at level 55, right associativity).\n  \n  Class CatId O `{Arrows O} := cat_id : `(x --> x).\n  Class CatComp O `{Arrows O} :=\n    comp : forall {x y z}, (y --> z) -> (x --> y) -> (x --> z).\n  \n  Notation \"A \\o B\" := (comp A B) (at level 40, left associativity).\n  \n  Class Setoid A {Ae : Equiv A} : Prop :=\n    setoid_eq :> Equivalence (@equiv A Ae).\n  (* これは、Operational Class である。\n     Prop. Class にした場合は、unfold Setoid を split に変える。 *)\n  \n  Section setoid_morphisms.\n  Context {A B} {Ae : Equiv A} {Be : Equiv B} (f : A -> B).    \n    Class Setoid_Morphism :=\n      {\n        setoidmor_a : Setoid A;\n        setoidmor_b : Setoid B;\n        sm_proper :> Proper (equiv ==> equiv) f\n      }. \n  End setoid_morphisms.\n  \n  Class Category (O : Type)\n        `{!Arrows O}\n        `{forall x y : O, Equiv (x --> y)}\n        `{!CatId O}\n        `{!CatComp O} : Prop :=\n    {\n      (* Setid である。 *)\n      arrow_equiv :> forall x y, Setoid (x --> y);\n      (* comp で繋いだ項をequivでの書換の対象にできる。 *)\n      comp_proper :> forall x y z, Proper (equiv ==> equiv ==> equiv) (@comp _ _ _ x y z);\n      (* comp の結合性が成立する。 *)\n      comp_assoc w x y z (a : w --> x) (b : x --> y) (c : y --> z) :\n        c \\o (b \\o a) = (c \\o b) \\o a;\n      (* comp の単位元が存在する。 *)\n      id_l `(a : x --> y) : cat_id _ \\o a = a;\n      id_r `(a : x --> y) : a \\o cat_id _ = a;\n    }.\nEnd Category_Class.\n\nNotation \"A == B\" := (equiv A B) (at level 55, right associativity).\nNotation \"A --> B\" := (arrow A B) (at level 55, right associativity).\nNotation \"A \\o B\" := (comp A B) (at level 40, left associativity).\n\n(* *********** *)\n(* シングルトン *)\n(* *********** *)\n(* \n対象の集合 : unit\n対象（唯一） : tt\n射の集合（唯一） : tt --> tt (= nat と定める)\n射の例     : 0,1,2.....\n射の合成   : natの加算\n恒等射     : 0\n *)\n\nDefinition O0 : Type := unit.\nInstance A0 : Arrows O0 := fun (x y : O0) => nat.\nInstance E0 (x y : O0) : Equiv (A0 x y) := fun (m n : nat) => m = n. (* 射の等しさ *)\nInstance I0 : CatId O0 := fun (_ : O0) => 0.\nInstance C0 : CatComp O0 := fun (_ _ _ : O0) (m n : nat) => m + n.\n\nCheck Category O0 : Prop.\nCheck @Category O0 A0 E0 I0 C0 : Prop.\nProgram Instance SPLUS : @Category O0 A0 E0 I0 C0.\nObligation 1.                               (* Setoid (x --> y) *)\nProof.\n  unfold Setoid.                            (* Equivalence equiv *)\n  unfold equiv.                             (* Equivalence (E0 x y) *)\n  unfold E0.                                (* Equivalence (fun m n : nat => m = n) *)\n  split.\n  + now unfold Reflexive.\n  + now unfold Symmetric.\n  + unfold Transitive.\n    intros x' y' z' H1 H2.\n    now rewrite H1, H2.\nQed.\nObligation 2.                               (* c \\o (b \\o a) = c \\o b \\o a *)\nProof.\n  unfold comp, C0.\n  (* c + (b + a) = c + b + a *)\n  now apply plus_assoc.\nQed.\n\n(* 例 *)\nCheck @arrow O0 A0 tt tt.                   (* 射の型 *)\nCheck tt --> tt.                            (* 上記の構文糖 *)\nCheck 1 : tt --> tt.                        (* 1 は射の例 *)\nCheck 0 : tt --> tt.                        (* 0 は射の例 *)\n\n(* 射 2 と 3 の合成は 5 になる。 *)\nCheck comp 3 2 : tt --> tt.\nCompute comp 3 2.                           (* 5 *)\nCheck @comp O0 A0 C0 tt tt tt 3 2 : tt --> tt.\nCompute @comp O0 A0 C0 tt tt tt 3 2.        (* 5 *)\n\nCheck cat_id tt : tt --> tt.\nCompute cat_id tt.                          (* 0 *)\nCheck @cat_id O0 A0 I0 tt : tt --> tt.\nCompute @cat_id O0 A0 I0 tt.                (* 0 *)\n\n\n(* ******** *)\n(* 集合の圏 *)\n(* ******** *)\n(* \n対象の集合 : Set\n対象の例   : nat など\n射の集合の例 : nat -> nat  など\n射の例     : plus 0 (= id_nat), plus 1, plus 2,.... (関数)\n射の合成   : 関数の合成\n恒等射     : id_nat など\n\n注意：対象は自然数の集合natである。0,1,2,..は対象ではない。\n *)\n\nDefinition O1 : Type := Set.\nInstance A1 : Arrows O1 := fun (x y : O1) => x -> y.\nInstance E1 (x y : O1) : Equiv (A1 x y) := (* x -> y *)\n  fun (f g : A1 x y) => forall (a : x), f a = g a.\n(*\nInstance E1 (x y : O1) : Equiv (A1 x y) := (* x -> y *)\n  fun (f g : A1 x y) => f = g.\n*)\nInstance I1 : CatId O1 := fun (a : O1) (x : a) => x.\nInstance C1 : CatComp O1 :=\n  fun (x y z : O1) (f : A1 y z) (g : A1 x y) (a : x) => f (g a).\n\nCheck Category O1 : Prop.\nCheck @Category O1 A1 E1 I1 C1 : Prop.\nProgram Instance SETS : @Category O1 A1 E1 I1 C1.\nObligation 1.\nProof.                                      (* Setoid (x --> y) *)\n  unfold Setoid, equiv, E1.\n  split.\n  + now unfold Reflexive.\n  + now unfold Symmetric.\n  + unfold Transitive.\n    intros x' y' z' H1 H2 a.\n    rewrite H1.\n    rewrite <- H2.\n    easy.\nQed.\nObligation 2.            (* Proper (equiv ==> equiv ==> equiv) comp *)\nProof.\n  unfold equiv, E1, comp, C1.\n  intros yz yz' H1 xy xy' H2 a.\n  rewrite <- H2.\n  rewrite <- H1.\n  (* yz (xy a) = yz (xy a) *)\n  easy.\nQed.\n\n(* 例 *)\nCheck @arrow O1 A1 nat nat.                 (* 射の型のひとつ *)\nCheck nat --> nat.                          (* 上記の構文糖 *)\nCheck plus 1 : nat --> nat.                 (* plus 1 は射の例 *)\nCheck plus 0 : nat --> nat.                 (* plus 0 は射の例 *)\n\n(* 射 plus 2 と plus 3 の合成は plus 5 になる。 *)\nCheck comp (plus 3) (plus 2) : nat --> nat.\nCompute comp (plus 3) (plus 2).             (* plus 5 *)\nCheck @comp O1 A1 C1 nat nat nat (plus 3) (plus 2) : nat --> nat.\nGoal plus 5 = @comp O1 A1 C1 nat nat nat (plus 3) (plus 2).\nProof.\n  unfold comp, C1.\n  easy.\nQed.\nCompute @comp O1 A1 C1 nat nat nat (plus 3) (plus 2). (* plus 5 *)\n\nCheck cat_id nat : nat --> nat.\nCompute cat_id nat.                        (* id *)\nCheck @cat_id O1 A1 I1 nat : nat --> nat.  (* cat_id は射のひとつ *)\nGoal id = @cat_id O1 A1 I1 nat.            (* cat_id は id に等しい *)\nProof.\n  unfold cat_id, I1.\n  easy.\nQed.\nCompute @cat_id O1 A1 I1 nat.               (* id *)\n\n\n(* ************* *)\n(* 半順序集合の圏 *)\n(* ************* *)\n(* \n対象の集合 : nat\n対象の例   : 0,1,2,....\n射の集合の例 : 0 --> 0, 0 --> 1,...\n射の例     : 0≦0, 0≦1,.. (対象が決まると唯一決まる)\n射の合成   : 不等号の遷移性\n恒等射     : 0≦0, 1≦1,..\n *)\n\nDefinition O2 : Type := nat.\nInstance A2 : Arrows O2 := fun (x y : O2) => x <= y.\nInstance E2 (x y : O2) : Equiv (A2 x y) := (* x <= y *)\n  fun (H1 H2 : A2 x y) => H1 = H2.\nInstance I2 : CatId O2 := le_n.\nInstance C2 : CatComp O2 :=\n  fun (x y z : O2) H1 H2 => le_trans x y z H2 H1.\n\nCheck @Category O2 A2 E2 I2 C2 : Prop.\nProgram Instance LE : @Category O2 A2 E2 I2 C2.\nObligation 1.                               (* Setoid (x --> y) *)\n  unfold Setoid, equiv, E2.\n  split.\n  + now unfold Reflexive.\n  + now unfold Symmetric.\n  + unfold Transitive.\n    intros x' y' z' H1 H2.\n    now rewrite H1, H2.\nQed.\nObligation 2.                               (* c \\o (b \\o a) = c \\o b \\o a *)\nProof.\n  unfold comp, C2.\n  unfold arrow, A2 in *.\n  (* Nat.le_trans w y z (Nat.le_trans w x y a b) c =\n     Nat.le_trans w x z a (Nat.le_trans x y z b c) *)\n  \n  (* 普段ゴールには、定理（型）が出現するはずなのに、\n     証明（値）であるle_transが出てきてしまった！ *)\n  \n  (* (w <= x -> x <= y) -> y <= z -> w <= z *)\n  Check Nat.le_trans w y z (Nat.le_trans w x y a b) c : w <= z.\n  (* w <= x -> (x <= y -> y <= z) -> w <= z *)\n  Check Nat.le_trans w x z a (Nat.le_trans x y z b c) : w <= z.\n  \n  (* 公理：型が同じ値は同じ。\n     …こんなことはありえない。irrelevence は 見当違い、無関係 の意味。\n     しかし、証明する定理（型）が同じなら、証明（値）は同じ。\n     …といえば納得できる。つまり、定理に対する証明の一意性を公理として導入する。 *)\n  Check proof_irrelevance : forall (P : Prop) (p1 p2 : P), p1 = p2.\n  now apply proof_irrelevance.\nQed.\nObligation 3.\n  unfold comp, C2.                          (* cat_id y \\o a = a *)\n  unfold arrow, A2 in *.\n  (* Nat.le_trans x y y a (cat_id y) = a *)\n  (* x <= y -> y <= y -> x <= y *)\n  Check Nat.le_trans x y y a (cat_id y).\n  now apply proof_irrelevance.\nQed.\nObligation 4.\n  unfold comp, C2.                          (* a \\o cat_id x = a *)\n  unfold arrow, A2 in *.\n  (* Nat.le_trans x x y (cat_id x) a = a *)\n  (* x <= x -> x <= y -> x <= y *)\n  now apply proof_irrelevance.\nQed.\n\n(* 例 *)\nCheck @arrow O2 A2 3 3.                     (* 射の型のひとつ *)\nCheck 3 --> 3.                              (* 上記の構文糖 *)\nCheck 3 --> 4.                              (* 射の型のひとつ *)\nCheck 4 --> 5.                              (* 射の型のひとつ *)\nCheck 3 --> 5.                              (* 射の型のひとつ *)\n\nDefinition le33 : 3 <= 3. Proof. easy. Defined.\nDefinition le34 : 3 <= 4. Proof. omega. Defined.\nDefinition le45 : 4 <= 5. Proof. omega. Defined.\nDefinition le35 : 3 <= 5. Proof. omega. Defined.\n\nCheck le33 : 3 --> 3.                       (* この型の射は唯一 *)\nCheck le34 : 3 --> 4.                       (* この型の射は唯一 *)\nCheck le45 : 4 --> 5.                       (* この型の射は唯一 *)\nCheck le35 : 3 --> 5.                       (* この型の射は唯一 *)\n\n(* 3≦4 と 4≦5 を 合成すると 3≦5 になる。 *)\nCheck comp le45 le34 : 3 --> 5.\nCompute comp le45 le34.\nCheck @comp O2 A2 C2 3 4 5 le45 le34 : 3 --> 5.\nCompute @comp O2 A2 C2 3 4 5 le45 le34.\nGoal le35 = @comp O2 A2 C2 3 4 5 le45 le34.\nProof.\n  unfold comp, C2.\n  apply proof_irrelevance.\nQed.\n\nCheck cat_id 3  : 3 --> 3.           (* cat_id は射のひとつ *)\nCompute cat_id 3.                    (* le_n 3 *)\nCheck @cat_id O2 A2 I2 3  : 3 --> 3. (* cat_id は射のひとつ *)\nCompute @cat_id O2 A2 I2 3.                 (* le_n 3 *)\nGoal le_n 3 = @cat_id O2 A2 I2 3.    (* cat_id 3 は 3≦3 に等しい。 *)\nProof.\n  unfold cat_id, I2.\n  easy.\nQed.\n\n\n(* *********** *)\n(* しりとりの圏 *)\n(* *********** *)\n(* \n対象の集合 : ひらがな\n対象の例   : こ,ぶ,た,ぬ,き,い,や,...\n射の集合の例 : た --> き\n射の例     : たぬき, たいやき\n射の合成   : しりとりをした文字列の連結\n恒等射     : こ,た,... (1文字語)\n *)\n\nInductive O3 : Type := こ | ぶ | た | ぬ | き | つ | ね | い | や.\nInductive A3 : Arrows O3 :=\n  | single : forall A, A3 A A\n  | cons : forall {A' B : O3} (A : O3) (tl : A3 A' B), A3 A B.\n\nCheck cons こ (cons ぶ (single た)) : A3 こ た.\nGoal cons こ (cons ぶ (single た)) = cons こ (cons ぶ (single た)).\nProof. reflexivity. Qed.                    (* 普通に = が成り立つ。 *)\n\nInstance E3 (x y : O3) : Equiv (A3 x y) :=\n  fun (s t : A3 x y) => s = t.\nDefinition I3 : CatId O3 := single.\nDefinition C3 (x y z : O3) (t : A3 y z) (s : A3 x y) : A3 x z.\nProof.\n  induction s.\n  + easy.\n  + now apply (cons A (IHs t)).\nDefined.\nCheck C3 : CatComp O3.\n\nCheck @Category O3 A3 E3 I3 C3 : Prop.\nProgram Instance SIRI : @Category O3 A3 E3 I3 C3.\nObligation 1.                               (* Setoid (x --> y) *)\n  unfold Setoid, equiv, E3.\n  split.\n  + now unfold Reflexive.\n  + now unfold Symmetric.\n  + unfold Transitive.\n    intros x' y' z' H1 H2.\n    now rewrite H1, H2.\nQed.\nObligation 2.                               (* c \\o (b \\o a) = c \\o b \\o a *)\nProof.\n  unfold comp, C3.\n  induction a; simpl.\n  - easy.\n  - now rewrite IHa.\nQed.\nObligation 3.                               (* cat_id y \\o a = a *)\nProof.\n  unfold comp, C3, cat_id, I3.\n  induction a; simpl.\n  - easy.\n  - now rewrite IHa.\nQed.\n\n(* 例 *)\nCheck @arrow O3 A3 ね こ.                   (* 射の型のひとつ *)\nCheck ね --> こ.                            (* 上記の構文糖衣 *)\nCheck こ --> こ.                            (* 射の型のひとつ *)\nCheck た --> き.                            (* 射の型のひとつ *)\nCheck き --> ね.                            (* 射の型のひとつ *)\nCheck た --> ね.                            (* 射の型のひとつ *)\n\nDefinition neko := cons ね (single こ).\nDefinition ko := single こ.\nDefinition koneko := cons こ (cons ね (single こ)).\nDefinition tanuki := cons た (cons ぬ (single き)).\nDefinition taiyaki := cons た (cons い (cons や (single き))).\nDefinition kitune := cons き (cons つ (single ね)).\nDefinition tanukitune := cons た (cons ぬ (cons き (cons つ (single ね)))).\n\nCheck neko    : ね --> こ.                  (* この型の射の例 *)\nCheck ko      : こ --> こ.                  (* この型の射の例 *)\nCheck koneko  : こ --> こ.                  (* この型の射の例、別の例 *)\nCheck tanuki  : た --> き.                  (* この型の射の例 *)\nCheck taiyaki : た --> き.                  (* この型の射の例、別の例 *)\nCheck kitune  : き --> ね.                  (* この型の射の例 *)\nCheck tanukitune : た --> ね.               (* この型の射の例 *)\n\n(* たぬき と きつね を 合成すると たぬきつね になる。 *)\n\nCheck comp kitune tanuki : た --> ね.\n(* Compute comp kitune tanuki. *)\nCheck @comp O3 A3 C3 た き ね kitune tanuki : た --> ね.\nGoal tanukitune = @comp O3 A3 C3 た き ね kitune tanuki.\nCompute @comp O3 A3 C3 た き ね kitune tanuki.\nProof.\n  unfold comp, C3.\n  easy.\nQed.\n\nCheck cat_id こ : こ --> こ.\n(* Compute cat_id こ. *)\nCheck @cat_id O3 A3 I3 こ : こ --> こ.      (* cat_id は射のひとつ *)\nGoal ko = @cat_id O3 A3 I3 こ. (* cat_id こ は single こ に等しい。 *)\nCompute @cat_id O3 A3 I3 こ.                 (* single こ *)\nProof.\n  unfold cat_id, I3.\n  easy.\nQed.\n\n(* こねこ は cat_id ではないことに注意してください。 *)\nCompute @comp O3 A3 C3 ね こ こ ko neko.     (* ねこ と こ の連結は ねこ *)\nCompute @comp O3 A3 C3 ね こ こ koneko neko. (* ねこ と こねこ の連結は ねこねこ *)\n\n\n(* 始対象 *)\nSection initiality.\n  Generalizable Variables X.\n  Context `{Category X}.\n  \n  Class InitialArrow (x : X) : Type := initial_arrow: forall y, x --> y.\n\n  Class Initial (x : X) `{InitialArrow x}: Prop :=\n    initial_arrow_unique : forall y f', initial_arrow y = f'.\nEnd initiality.\n\nProgram Definition IA0 (x : O0) : @InitialArrow O0 A0 x := fun (y : O0) => _.\nObligation 1.\nAdmitted.\n\nProgram Instance ISNGL : @Initial O0 A0 tt (IA0 tt).\nObligation 1.\nProof.\n  unfold initial_arrow, IA0.\n  Admitted.\n\n(* 関手 *)\n\nSection functor_class.\n  Generalizable Variables C D x y z a.\n  \n  Context `{Category C} `{Category D} (M : C -> D).\n  \n  Class Fmap : Type := fmap : forall {v w : C}, (v --> w) -> (M v --> M w).\n  \n  Class Functor `(Fmap) : Prop :=\n    {\n      functor_from : Category C;\n      functor_to : Category D;\n      functor_morphism :> forall a b : C, Setoid_Morphism (@fmap _ a b);\n      preserves_id : `(fmap (cat_id _ : a --> a) = cat_id _);\n      preserves_comp `(f : y --> z) `(g : x --> y) : fmap (f \\o g) = fmap f \\o fmap g\n    }.\nEnd functor_class.\n\nDefinition M01 (a : unit) : O1 := nat.\n\nCheck @Fmap.\nCheck @Fmap O0 A0 O1 A1 M01 : Type.\nCheck Fmap M01 : Type.\n\nDefinition f01 (x y : O0) (n : nat) := fun (x : nat) => x + n.\nDefinition F01 : @Fmap O0 A0 O1 A1 M01 := f01.\n\nCheck @Functor O0 A0 E0 I0 C0 O1 A1 E1 I1 C1 M01 F01.\nCheck Functor M01 F01.\nProgram Instance FUN01 : Functor M01 F01.\nObligation 1.\nProof.\n  split.\n  - split.                                  (* Setoid (a --> b) *)\n    + unfold Reflexive.\n      now unfold equiv, E0.\n    + unfold Symmetric.\n      now unfold equiv, E0.\n    + unfold Transitive.\n      unfold equiv, E0.\n      intros.\n      now subst.\n  - split.                                  (* Setoid (M a --> M b) *)\n    + unfold Reflexive.\n      now unfold equiv, E1.\n    + unfold Symmetric.\n      now unfold equiv, E1.\n    + unfold Transitive.\n      unfold equiv, E1.\n      intros.\n      erewrite H.\n      erewrite <- H0.\n      easy.\n  - intro x.                                (* Proper (equiv ==> equiv) (fmap M01) *)\n    intros y H.\n    unfold equiv, E0 in H.\n    rewrite H.\n    easy.\nQed.\n\nCheck Fmap M01.\nCheck F01.\nCheck @fmap O0 A0 O1 A1 M01 F01 tt tt : tt --> tt -> nat --> nat.\nCheck @fmap O0 A0 O1 A1 M01 F01 tt tt   1         :  nat --> nat.\n\nGoal @fmap O0 A0 O1 A1 M01 F01 tt tt   1 = fun x => x + 1.\nProof.\n  unfold fmap, M01, F01, f01.\n  easy.\nQed.\n\nGoal forall n : nat, @fmap O0 A0 O1 A1 M01 F01 tt tt   n = fun x => x + n.\nProof.\n  unfold fmap, M01, F01, f01.\n  easy.\nQed.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/categories/tcfm_category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7139700034460399}}
{"text": "(* begin hide *)\n(**********************************************************************)\n(* Equations                                                          *)\n(* Copyright (c) 2009-2021 Matthieu Sozeau <matthieu.sozeau@inria.fr> *)\n(**********************************************************************)\n(* This file is distributed under the terms of the                    *)\n(* GNU Lesser General Public License Version 2.1                      *)\n(**********************************************************************)\n\nFrom Equations Require Import Equations.\nFrom Coq Require Import List Program.Syntax Arith Lia.\nRequire Import List.\nImport ListNotations.\n(* end hide *)\n(** * Well-founded recursion\n\n  Equations provide support for well-founded recursion, potentially nested and mutual.\n\n  Here we show a standard example of the [nubBy] function from Haskell's prelude,\n  which is naturally expressed using well-founded recursion on the length of the list.\n  To show this, we however use the argument that [filter f l] always returns a sublist of [l].\n *)\n\nEquations filter_length {A} (l : list A) (f : A -> bool) : length (filter f l) <= length l :=\n filter_length [] f := le_n 0;\n filter_length (x :: xs) f with f x :=\n                         { | true => le_n_S _ _ (filter_length xs f);\n                           | false => le_S _ _ (filter_length xs f) }.\n\nSection nubBy.\n  Context {A} (eq : A -> A -> bool).\n\n  (** The proof that this function is well-founded uses simply the lemma [filter_length] and\n      standard arithmetic reasoning. *)\n  Equations? nubBy (l : list A) : list A by wf (length l) lt :=\n  nubBy []        => [];\n  nubBy (x :: xs) => x :: nubBy (filter (fun y => negb (eq x y)) xs).\n  Proof. simpl. auto using filter_length with arith. Defined.\nEnd nubBy.\n\n(** Using functional elimination, we can show standard properties of [nubBy], without having\n    to repeat the well-founded induction principle *)\n\nLemma nubBy_length {A} (eq : A -> A -> bool) (l : list A) : length (nubBy eq l) <= length l.\nProof.\n  funelim (nubBy eq l); simpl; trivial.\n  rewrite filter_length in H. auto with arith.\nQed.\n\nLemma In_filter {A} (f : A -> bool) (l : list A) a : In a (filter f l) -> In a l /\\ f a = true.\nProof.\n  induction l; simpl. intros [].\n  destruct (f a0) eqn:Heq.\n  simpl. intuition auto. now subst a0.\n  intuition auto.\nQed.\n\nLemma In_nubBy {A} (eq : A -> A -> bool) (l : list A) (a : A) :\n  In a (nubBy eq l) -> In a l.\nProof.\n  funelim (nubBy eq l).\n  + trivial.\n  + intros H0.\n    destruct H0 as [->|H0]; auto. simpl. auto.\n    specialize (H _ H0). apply In_filter in H as [Inal eqa]. right; auto.\nQed.\n\n(** This allows to show that [nubBy] returns a list without duplicates in a few\n    lines of proof. *)\nLemma nuBy_nodup {A} (eq : A -> A -> bool) (l : list A) :\n  (forall x y, (eq x y = true) <-> (x = y)) -> NoDup (nubBy eq l).\nProof.\n  funelim (nubBy eq l). constructor. intros Heq; specialize (H Heq).\n  constructor. intros Hi. apply In_nubBy, In_filter in Hi as [_ eqaa].\n  specialize (Heq x x). destruct (eq x x). discriminate.\n  destruct (proj2 Heq). reflexivity. discriminate.\n  auto.\nQed.\n\nEquations ack (m n : nat) : nat by wf (m, n) (Equations.Prop.Subterm.lexprod _ _ lt lt) :=\n  ack 0 0         := 1;\n  ack 0 (S n)     := S (S n);\n  ack (S m) 0     := ack m 1;\n  ack (S m) (S n) := ack m (ack (S m) n).\n", "meta": {"author": "mattam82", "repo": "Coq-Equations", "sha": "5603bfff39f3866eed8f010591b5503d5776fa4e", "save_path": "github-repos/coq/mattam82-Coq-Equations", "path": "github-repos/coq/mattam82-Coq-Equations/Coq-Equations-5603bfff39f3866eed8f010591b5503d5776fa4e/examples/wfrec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7138866864865641}}
{"text": "Require Import Coq.Strings.String.\n\nInductive id : Type :=\n| Id      : string -> id.\n\nDefinition beq_id id1 id2 :=\n  match id1,id2 with\n  | Id n1, Id n2 => if string_dec n1 n2 then true else false\n  end.\n\nTheorem beq_id_true_iff :\n  forall x y : id,\n  beq_id x y = true <-> x = y.\nProof.\n  intros. split.\n  -intros. unfold beq_id in *. destruct x. destruct y.\n   destruct (string_dec s s0). +subst. auto. +inversion H.\n  -intros. unfold beq_id. destruct x. destruct y.\n   destruct (string_dec s s0). +auto. +inversion H. subst.\n   destruct n. auto.\nQed.\n\n\nTheorem false_beq_id :\n  forall x y : id,\n  x <> y <-> beq_id x y = false.\nProof.\n  intros. split; unfold beq_id in *.\n  -intros. destruct x. destruct y. destruct (string_dec s s0).\n   +subst. destruct H. auto. +auto.\n  -intros. destruct x. destruct y. destruct (string_dec s s0).\n   +inversion H. +clear H. unfold not in *. intros. inversion H.\n    contradiction.\nQed.\n\n", "meta": {"author": "PKUTCS", "repo": "CSVerifi", "sha": "3def80d210c3dc5765c5527683b8f0284b52fed6", "save_path": "github-repos/coq/PKUTCS-CSVerifi", "path": "github-repos/coq/PKUTCS-CSVerifi/CSVerifi-3def80d210c3dc5765c5527683b8f0284b52fed6/util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7138866682417053}}
{"text": "(************************)\n(************************)\n(****                ****)\n(****   Categories   ****)\n(****                ****)\n(************************)\n(************************)\n\nRequire Import Coq.Logic.ProofIrrelevance.\nRequire Import Main.Tactics.\n\n#[local] Set Universe Polymorphism.\n\n(* Metavariables for categories: `C`, `D`, `E` *)\n\nRecord category := newCategory {\n  object : Type; (* Objects: `w`, `x`, `y`, `z` *)\n  arrow : object -> object -> Type; (* Arrows: `f`, `g`, `h` *)\n  compose {x y z} : arrow y z -> arrow x y -> arrow x z;\n  id {x}: arrow x x;\n\n  cAssoc {w x y z} (f : arrow w x) (g : arrow x y) (h : arrow y z) :\n    compose h (compose g f) = compose (compose h g) f;\n  cIdentLeft {x y} (f : arrow x y) : compose id f = f;\n  cIdentRight {x y} (f : arrow x y) : compose f id = f;\n}.\n\nArguments arrow {_}.\nArguments compose {_} {_} {_} {_}.\nArguments id {_} {_}.\nArguments cAssoc {_} {_} {_} {_} {_}.\nArguments cIdentLeft {_} {_} {_}.\nArguments cIdentRight {_} {_} {_}.\n\n#[export] Hint Resolve cAssoc : main.\n#[export] Hint Resolve cIdentLeft : main.\n#[export] Hint Rewrite @cIdentLeft : main.\n#[export] Hint Resolve cIdentRight : main.\n#[export] Hint Rewrite @cIdentRight : main.\n\n#[local] Theorem opCAssoc\n  {C}\n  (w x y z : object C)\n  (f : arrow x w)\n  (g : arrow y x)\n  (h : arrow z y)\n: compose (compose f g) h = compose f (compose g h).\nProof.\n  search.\nQed.\n\n#[local] Theorem opCIdentLeft {C} (x y : object C) (f : arrow y x) :\n  compose f id = f.\nProof.\n  search.\nQed.\n\n#[local] Theorem opCIdentRight {C} (x y : object C) (f : arrow y x) :\n  compose id f = f.\nProof.\n  search.\nQed.\n\nDefinition oppositeCategory C : category := newCategory\n  (object C)\n  (fun x y => arrow y x)\n  (fun _ _ _ f g => compose g f)\n  (fun _ => id)\n  opCAssoc\n  opCIdentLeft\n  opCIdentRight.\n\nTheorem oppositeInvolution C : oppositeCategory (oppositeCategory C) = C.\nProof.\n  unfold oppositeCategory.\n  destruct C.\n  f_equal; apply proof_irrelevance.\nQed.\n\n#[export] Hint Resolve oppositeInvolution : main.\n", "meta": {"author": "stepchowfun", "repo": "proofs", "sha": "00da33f63a56080227d06d37fd0f28b560f24624", "save_path": "github-repos/coq/stepchowfun-proofs", "path": "github-repos/coq/stepchowfun-proofs/proofs-00da33f63a56080227d06d37fd0f28b560f24624/proofs/CategoryTheory/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7138674509434729}}
{"text": "(* -*- mode: coq -*- *)\n(* Time-stamp: <2014/8/22 1:34:0> *)\n(*\n  order.v \n  - mathink : Author\n *)\n\n(* SSReflect libraries *)\nRequire Import\n  Ssreflect.ssreflect\n  Ssreflect.ssrbool\n  Ssreflect.ssrfun\n  Ssreflect.eqtype.\n\n(* Implicity *)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nStructure totalOrder (T: Type) :=\n  Build_totalOrder\n    { total_ord:> rel T;\n\n    ord_antisymmetric: antisymmetric total_ord;\n    ord_transitive: transitive total_ord;\n    ord_total: total total_ord }.\nNotation makeTotalOrder ord := (@Build_totalOrder _ ord _ _ _).\nLemma ord_reflexive T (ord: totalOrder T): reflexive ord.\nProof.\n  move=> x.\n  move: (ord_total ord x x) => /orP [] //.\nQed.\n\nHint Resolve ord_antisymmetric ord_transitive ord_total ord_reflexive.\n\n\nDefinition strict_ord  {T: eqType}(ord: totalOrder T): rel T :=\n  fun x y => (ord x y) && (x != y).\n\nNotation \"ord !\" := (strict_ord ord) (at level 5, left associativity).\n\nSection Strict.\n\n  Context {T: eqType}(ord: totalOrder T).\n\n  Lemma sord_transitive: transitive ord!.\n  Proof.\n    move=> y x z /andP [Hlexy Hneqxy] /andP [Hleyz Hneqyz].\n    apply/andP; split.\n    - by apply ord_transitive with y.\n    - apply/eqP=> Heqxz; move: Hneqxy => /eqP; apply.\n        by rewrite -Heqxz in Hleyz;\n        apply: ord_antisymmetric => //; apply/andP; split.\n  Qed.\n  Hint Resolve sord_transitive.\n\n\n  Lemma sord_irrefl x:\n    ~~ (ord! x x).\n  Proof.\n      by rewrite negb_and ord_reflexive eq_refl //=.\n  Qed.\n\n  Lemma ord_neg_sord x y:\n    ~~ (ord x y) = (ord! y x).\n  Proof.\n    move: (ord_total ord x y) => /orP [] Hle; apply/eqP.\n    - rewrite Hle /=.\n      case Hle':  (ord y x); rewrite /strict_ord Hle' //=.\n      have: x = y; first by apply: ord_antisymmetric=>//; apply/andP.\n        by move=> ->; rewrite eq_refl.\n    - rewrite /strict_ord Hle /=.\n      case Hle':  (ord x y) => //=.\n      + have: x = y; first by apply: ord_antisymmetric=>//; apply/andP.\n          by move=> ->; rewrite eq_refl.\n      + case: (x =P y) => [Heq | Hneq].\n        * by rewrite Heq eq_refl /= -Hle' Heq ord_reflexive.\n        * by rewrite [y==x]eq_sym; move: Hneq => /eqP ->.\n  Qed.\n\n  Lemma sord_neg_ord x y:\n    ~~ (ord! x y) = (ord y x).\n  Proof.\n      by apply/eqP; rewrite eqb_negLR ord_neg_sord.\n  Qed.\n\nEnd Strict.\n", "meta": {"author": "mathink", "repo": "adlib-ssr", "sha": "1c84b7c7e17f25d1b50c6067cc7149c6fd4566d5", "save_path": "github-repos/coq/mathink-adlib-ssr", "path": "github-repos/coq/mathink-adlib-ssr/adlib-ssr-1c84b7c7e17f25d1b50c6067cc7149c6fd4566d5/order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7138674459354261}}
{"text": "(** * IndPrinciples: Induction Principles *)\n\n(** Every time we declare a new [Inductive] datatype, Coq\n    automatically generates an _induction principle_ for this type.\n    This induction principle is a theorem like any other: If [t] is\n    defined inductively, the corresponding induction principle is\n    called [t_ind]. *)\n\nSet Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export ProofObjects.\n\n(* ################################################################# *)\n(** * Basics *)\n\n(** Here is the induction principle for natural numbers: *)\n\nCheck nat_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, P n -> P (S n)) ->\n    forall n : nat, P n.\n\n(** In English: Suppose [P] is a property of natural numbers (that is,\n      [P n] is a [Prop] for every [n]). To show that [P n] holds of all\n      [n], it suffices to show:\n\n      - [P] holds of [0]\n      - for any [n], if [P] holds of [n], then [P] holds of [S n]. *)\n\n(** The [induction] tactic is a straightforward wrapper that, at its\n    core, simply performs [apply t_ind].  To see this more clearly,\n    let's experiment with directly using [apply nat_ind], instead of\n    the [induction] tactic, to carry out some proofs.  Here, for\n    example, is an alternate proof of a theorem that we saw in the\n    [Induction] chapter. *)\n\nTheorem mul_0_r' : forall n:nat,\n  n * 0 = 0.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *) simpl. intros n' IHn'. rewrite -> IHn'.\n    reflexivity.  Qed.\n\n(** This proof is basically the same as the earlier one, but a\n    few minor differences are worth noting.\n\n    First, in the induction step of the proof (the [S] case), we\n    have to do a little bookkeeping manually (the [intros]) that\n    [induction] does automatically.\n\n    Second, we do not introduce [n] into the context before applying\n    [nat_ind] -- the conclusion of [nat_ind] is a quantified formula,\n    and [apply] needs this conclusion to exactly match the shape of\n    the goal state, including the quantifier.  By contrast, the\n    [induction] tactic works either with a variable in the context or\n    a quantified variable in the goal.\n\n    Third, we had to manually supply the name of the induction principle\n    with [apply], but [induction] figures that out itself.\n\n    These conveniences make [induction] nicer to use in practice than\n    applying induction principles like [nat_ind] directly.  But it is\n    important to realize that, modulo these bits of bookkeeping,\n    applying [nat_ind] is what we are really doing. *)\n\n(** **** Exercise: 2 stars, standard (plus_one_r')\n\n    Complete this proof without using the [induction] tactic. *)\n\nTheorem plus_one_r' : forall n:nat,\n  n + 1 = S n.\nProof.\n  apply nat_ind.\n  - reflexivity.\n  - intros n' IHn'. simpl. rewrite IHn'. reflexivity. Qed.\n(** [] *)\n\n(** Coq generates induction principles for every datatype\n    defined with [Inductive], including those that aren't recursive.\n    Although of course we don't need the proof technique of induction\n    to prove properties of non-recursive datatypes, the idea of an\n    induction principle still makes sense for them: it gives a way to\n    prove that a property holds for all values of the type. *)\n\n(** These generated principles follow a similar pattern. If we\n    define a type [t] with constructors [c1] ... [cn], Coq generates a\n    theorem with this shape:\n\n    t_ind : forall P : t -> Prop,\n              ... case for c1 ... ->\n              ... case for c2 ... -> ...\n              ... case for cn ... ->\n              forall n : t, P n\n\n    The specific shape of each case depends on the arguments to the\n    corresponding constructor. *)\n\n(** Before trying to write down a general rule, let's look at\n    some more examples. First, an example where the constructors take\n    no arguments: *)\n\nInductive time : Type :=\n  | day\n  | night.\n\nCheck time_ind :\n  forall P : time -> Prop,\n    P day ->\n    P night ->\n    forall t : time, P t.\n\n(** **** Exercise: 1 star, standard, optional (rgb)\n\n    Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\nCheck rgb_ind :\n  forall P : rgb -> Prop,\n    P red ->\n    P green ->\n    P blue ->\n    forall x : rgb, P x.\n(** [] *)\n\n(** Here's another example, this time with one of the constructors\n    taking some arguments. *)\n\nInductive natlist : Type :=\n  | nnil\n  | ncons (n : nat) (l : natlist).\n\nCheck natlist_ind :\n  forall P : natlist -> Prop,\n    P nnil  ->\n    (forall (n : nat) (l : natlist),\n        P l -> P (ncons n l)) ->\n    forall l : natlist, P l.\n\n(** In general, the automatically generated induction principle for\n    inductive type [t] is formed as follows:\n\n    - Each constructor [c] generates one case of the principle.\n    - If [c] takes no arguments, that case is:\n\n      \"P holds of c\"\n\n    - If [c] takes arguments [x1:a1] ... [xn:an], that case is:\n\n      \"For all x1:a1 ... xn:an,\n          if [P] holds of each of the arguments of type [t],\n          then [P] holds of [c x1 ... xn]\"\n\n      But that oversimplifies a little.  An assumption about [P]\n      holding of an argument [x] of type [t] actually occurs\n      immediately after the quantification of [x].\n*)\n\n(** For example, suppose we had written the definition of [natlist] a little\n    differently: *)\n\nInductive natlist' : Type :=\n  | nnil'\n  | nsnoc (l : natlist') (n : nat).\n\n(** Now the induction principle case for [nsnoc1] is a bit different\n    than the earlier case for [ncons]: *)\n\nCheck natlist'_ind :\n  forall P : natlist' -> Prop,\n    P nnil' ->\n    (forall l : natlist', P l -> forall n : nat, P (nsnoc l n)) ->\n    forall n : natlist', P n.\n\n(** **** Exercise: 2 stars, standard (booltree_ind)\n\n    Here is a type for trees that contain a boolean value at each leaf\n    and branch. *)\n\nInductive booltree : Type :=\n  | bt_empty\n  | bt_leaf (b : bool)\n  | bt_branch (b : bool) (t1 t2 : booltree).\n\n(* What is the induction principle for [booltree]? Of course you could\n   ask Coq, but try not to do that. Instead, write it down yourself on\n   paper. Then look at the definition of [booltree_ind_type], below.\n   It has three missing pieces, which are provided by the definitions\n   in between here and there. Fill in those definitions based on what\n   you wrote on paper. *)\n\nDefinition booltree_property_type : Type := booltree -> Prop.\n\nDefinition base_case (P : booltree_property_type) : Prop\n  := P bt_empty.\n\nDefinition leaf_case (P : booltree_property_type) : Prop\n  := forall b : bool, P (bt_leaf b).\n\nDefinition branch_case (P : booltree_property_type) : Prop\n  := forall (b : bool) (t1 : booltree), P t1 -> forall (t2 : booltree), P t2 -> P (bt_branch b t1 t2).\n\nDefinition booltree_ind_type :=\n  forall (P : booltree_property_type),\n    base_case P ->\n    leaf_case P ->\n    branch_case P ->\n    forall (b : booltree), P b.\n\n(** Now check the correctness of your answers by proving the following\n    theorem. If you have them right, you can complete the proof with\n    just one tactic: [exact booltree_ind]. That will work because the\n    automatically generated induction principle [booltree_ind] has the\n    same type as what you just defined. *)\n\nTheorem booltree_ind_type_correct : booltree_ind_type.\nProof. exact booltree_ind. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (toy_ind)\n\n    Here is an induction principle for a toy type:\n\n  forall P : Toy -> Prop,\n    (forall b : bool, P (con1 b)) ->\n    (forall (n : nat) (t : Toy), P t -> P (con2 n t)) ->\n    forall t : Toy, P t\n\n    Give an [Inductive] definition of [Toy], such that the induction\n    principle Coq generates is that given above: *)\n\nInductive Toy : Type :=\n  | con1 (b : bool)\n  | con2 (n : nat) (t : Toy)\n.\n\n(** Show that your definition is correct by proving the following theorem.\n    You should be able to instantiate [f] and [g] with your two constructors,\n    then immediately finish the proof with [exact Toy_ind]. As in the previous\n    exercise, that will work because the automatically generated induction\n    principle [Toy_ind] will have the same type. *)\n\nTheorem Toy_correct : exists f g,\n  forall P : Toy -> Prop,\n    (forall b : bool, P (f b)) ->\n    (forall (n : nat) (t : Toy), P t -> P (g n t)) ->\n    forall t : Toy, P t.\nProof. exists con1. exists con2. exact Toy_ind. Qed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** What about polymorphic datatypes?\n\n    The inductive definition of polymorphic lists\n\n      Inductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\n\n    is very similar to that of [natlist].  The main difference is\n    that, here, the whole definition is _parameterized_ on a set [X]:\n    that is, we are defining a _family_ of inductive types [list X],\n    one for each [X].  (Note that, wherever [list] appears in the body\n    of the declaration, it is always applied to the parameter [X].)\n*)\n\n(**  The induction principle is likewise parameterized on [X]:\n\n      list_ind :\n        forall (X : Type) (P : list X -> Prop),\n           P [] ->\n           (forall (x : X) (l : list X), P l -> P (x :: l)) ->\n           forall l : list X, P l\n\n    Note that the _whole_ induction principle is parameterized on\n    [X].  That is, [list_ind] can be thought of as a polymorphic\n    function that, when applied to a type [X], gives us back an\n    induction principle specialized to the type [list X]. *)\n\n(** **** Exercise: 1 star, standard, optional (tree)\n\n    Write out the induction principle that Coq will generate for\n   the following datatype.  Compare your answer with what Coq\n   prints. *)\n\nInductive tree (X:Type) : Type :=\n  | leaf (x : X)\n  | node (t1 t2 : tree X).\nCheck tree_ind :\n  forall (X : Type) (P : tree X -> Prop), (forall (x : X), P (leaf X x)) -> (forall (t1 : tree X), P t1 -> forall (t2 : tree X), P t2 -> P (node X t1 t2)) -> forall (t : tree X), P t.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (mytype)\n\n    Find an inductive definition that gives rise to the\n    following induction principle:\n\n      mytype_ind :\n        forall (X : Type) (P : mytype X -> Prop),\n            (forall x : X, P (constr1 X x)) ->\n            (forall n : nat, P (constr2 X n)) ->\n            (forall m : mytype X, P m ->\n               forall n : nat, P (constr3 X m n)) ->\n            forall m : mytype X, P m\n*) \nInductive mytype (X:Type) : Type :=\n  | constr1 (x:X)\n  | constr2 (n:nat)\n  | constr3 (m:mytype X) (n:nat).\nCheck mytype_ind :\n  forall (X : Type) (P : mytype X -> Prop),\n    (forall x : X, P (constr1 X x)) ->\n    (forall n : nat, P (constr2 X n)) ->\n    (forall m : mytype X, P m ->\n      forall n : nat, P (constr3 X m n)) ->\n    forall m : mytype X, P m.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (foo)\n\n    Find an inductive definition that gives rise to the\n    following induction principle:\n\n      foo_ind :\n        forall (X Y : Type) (P : foo X Y -> Prop),\n             (forall x : X, P (bar X Y x)) ->\n             (forall y : Y, P (baz X Y y)) ->\n             (forall f1 : nat -> foo X Y,\n               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n             forall f2 : foo X Y, P f2\n*) \nInductive foo (X Y : Type) : Type :=\n  | bar (x : X)\n  | baz (y : Y)\n  | quux (f : nat -> foo X Y).\nCheck foo_ind :\n  forall (X Y : Type) (P : foo X Y -> Prop),\n    (forall x : X, P (bar X Y x)) ->\n    (forall y : Y, P (baz X Y y)) ->\n    (forall f1 : nat -> foo X Y,\n      (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n    forall f2 : foo X Y, P f2.\n(** [] *)\n\n(** **** Exercise: 1 star, standard, optional (foo')\n\n    Consider the following inductive definition: *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 (l : list X) (f : foo' X)\n  | C2.\n\n(** What induction principle will Coq generate for [foo']?  (Fill\n   in the blanks, then check your answer with Coq.)\n\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    _______________________ ->\n                    _______________________   ) ->\n             ___________________________________________ ->\n             forall f : foo' X, ________________________\n*)\nCheck foo'_ind :\n  forall (X : Type) (P : foo' X -> Prop),\n    (forall (l : list X) (f : foo' X),\n      P f -> P (C1 X l f)) ->\n    P (C2 X) ->\n    forall f : foo' X, P f.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?\n\n    The induction principle for numbers\n\n       forall P : nat -> Prop,\n            P 0  ->\n            (forall n : nat, P n -> P (S n))  ->\n            forall n : nat, P n\n\n   is a generic statement that holds for all propositions\n   [P] (or rather, strictly speaking, for all families of\n   propositions [P] indexed by a number [n]).  Each time we\n   use this principle, we are choosing [P] to be a particular\n   expression of type [nat -> Prop].\n\n   We can make proofs by induction more explicit by giving\n   this expression a name.  For example, instead of stating\n   the theorem [mul_0_r] as \"[forall n, n * 0 = 0],\" we can\n   write it as \"[forall n, P_m0r n]\", where [P_m0r] is defined\n   as... *)\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\n\n(** ... or equivalently: *)\n\nDefinition P_m0r' : nat -> Prop :=\n  fun n => n * 0 = 0.\n\n(** Now it is easier to see where [P_m0r] appears in the proof. *)\n\nTheorem mul_0_r'' : forall n:nat,\n  P_m0r n.\nProof.\n  apply nat_ind.\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    (* Note the proof state at this point! *)\n    intros n IHn.\n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n(** This extra naming step isn't something that we do in\n    normal proofs, but it is useful to do it explicitly for an example\n    or two, because it allows us to see exactly what the induction\n    hypothesis is.  If we prove [forall n, P_m0r n] by induction on\n    [n] (using either [induction] or [apply nat_ind]), we see that the\n    first subgoal requires us to prove [P_m0r 0] (\"[P] holds for\n    zero\"), while the second subgoal requires us to prove [forall n',\n    P_m0r n' -> P_m0r (S n')] (that is \"[P] holds of [S n'] if it\n    holds of [n']\" or, more elegantly, \"[P] is preserved by [S]\").\n    The _induction hypothesis_ is the premise of this latter\n    implication -- the assumption that [P] holds of [n'], which we are\n    allowed to use in proving that [P] holds for [S n']. *)\n\n(* ################################################################# *)\n(** * More on the [induction] Tactic *)\n\n(** The [induction] tactic actually does even more low-level\n    bookkeeping for us than we discussed above.\n\n    Recall the informal statement of the induction principle for\n    natural numbers:\n      - If [P n] is some proposition involving a natural number n, and\n        we want to show that P holds for _all_ numbers n, we can\n        reason like this:\n          - show that [P O] holds\n          - show that, if [P n'] holds, then so does [P (S n')]\n          - conclude that [P n] holds for all n.\n    So, when we begin a proof with [intros n] and then [induction n],\n    we are first telling Coq to consider a _particular_ [n] (by\n    introducing it into the context) and then telling it to prove\n    something about _all_ numbers (by using induction).\n*)\n\n(**  What Coq actually does in this situation, internally, is it\n    \"re-generalizes\" the variable we perform induction on.  For\n    example, in our original proof that [plus] is associative... *)\n\nTheorem add_assoc' : forall n m p : nat,\n  n + (m + p) = (n + m) + p.\nProof.\n  (* ...we first introduce all 3 variables into the context,\n     which amounts to saying \"Consider an arbitrary [n], [m], and\n     [p]...\" *)\n  intros n m p.\n  (* ...We now use the [induction] tactic to prove [P n] (that\n     is, [n + (m + p) = (n + m) + p]) for _all_ [n],\n     and hence also for the particular [n] that is in the context\n     at the moment. *)\n  induction n as [| n'].\n  - (* n = O *) reflexivity.\n  - (* n = S n' *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n(** It also works to apply [induction] to a variable that is\n    quantified in the goal. *)\n\nTheorem add_comm' : forall n m : nat,\n  n + m = m + n.\nProof.\n  induction n as [| n'].\n  - (* n = O *) intros m. rewrite -> add_0_r. reflexivity.\n  - (* n = S n' *) intros m. simpl. rewrite -> IHn'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** Note that [induction n] leaves [m] still bound in the goal --\n    i.e., what we are proving inductively is a statement beginning\n    with [forall m].\n\n    If we do [induction] on a variable that is quantified in the goal\n    _after_ some other quantifiers, the [induction] tactic will\n    automatically introduce the variables bound by these quantifiers\n    into the context. *)\n\nTheorem add_comm'' : forall n m : nat,\n  n + m = m + n.\nProof.\n  (* Let's do induction on [m] this time, instead of [n]... *)\n  induction m as [| m']. (* [n] is already introduced into the context *)\n  - (* m = O *) simpl. rewrite -> add_0_r. reflexivity.\n  - (* m = S m' *) simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, standard, optional (plus_explicit_prop)\n\n    Rewrite both [add_assoc'] and [add_comm'] and their proofs in\n    the same style as [mul_0_r''] above -- that is, for each theorem,\n    give an explicit [Definition] of the proposition being proved by\n    induction, and state the theorem and proof in terms of this\n    defined proposition.  *)\n\nDefinition Passoc (n m p : nat) : Prop := n + (m + p) = (n + m) + p.\nDefinition Pcomm (n m : nat) : Prop := n + m = m + n.\n\nTheorem add_assoc'' : forall n m p : nat, Passoc n m p.\nProof.\n  intros n m p.\n  induction n as [| n'].\n  - reflexivity.\n  - unfold Passoc. simpl. rewrite -> IHn'. reflexivity.\nQed.\n\nTheorem add_comm''' : forall n m : nat, Pcomm n m.\nProof.\n  induction n as [| n'].\n  - intros m. unfold Pcomm. rewrite -> add_0_r. reflexivity.\n  - intros m. unfold Pcomm. simpl. rewrite -> IHn'.\n    rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Induction Principles for Propositions *)\n\n(** Inductive definitions of propositions also cause Coq to generate\n    induction priniciples.  For example, recall our proposition [ev]\n    from [IndProp]: *)\n\nPrint ev.\n\n(* ===>\n\n  Inductive ev : nat -> Prop :=\n  | ev_0 : ev 0\n  | ev_SS : forall n : nat, ev n -> ev (S (S n)))\n\n*)\n\nCheck ev_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, ev n -> P n -> P (S (S n))) ->\n    forall n : nat, ev n -> P n.\n\n(** In English, [ev_ind] says: Suppose [P] is a property of natural\n    numbers.  To show that [P n] holds whenever [n] is even, it suffices\n    to show:\n\n      - [P] holds for [0],\n\n      - for any [n], if [n] is even and [P] holds for [n], then [P]\n        holds for [S (S n)]. *)\n\n(** As expected, we can apply [ev_ind] directly instead of using\n    [induction].  For example, we can use it to show that [ev'] (the\n    slightly awkward alternate definition of evenness that we saw in\n    an exercise in the [IndProp] chapter) is equivalent to the\n    cleaner inductive definition [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\nTheorem ev_ev' : forall n, ev n -> ev' n.\nProof.\n  apply ev_ind.\n  - (* ev_0 *)\n    apply ev'_0.\n  - (* ev_SS *)\n    intros m Hm IH.\n    apply (ev'_sum 2 m).\n    + apply ev'_2.\n    + apply IH.\nQed.\n\n(** The precise form of an [Inductive] definition can affect the\n    induction principle Coq generates. *)\n\nInductive le1 : nat -> nat -> Prop :=\n  | le1_n : forall n, le1 n n\n  | le1_S : forall n m, (le1 n m) -> (le1 n (S m)).\n\nNotation \"m <=1 n\" := (le1 m n) (at level 70).\n\n(** This definition can be streamlined a little by observing that the\n    left-hand argument [n] is the same everywhere in the definition,\n    so we can actually make it a \"general parameter\" to the whole\n    definition, rather than an argument to each constructor. *)\n\nInductive le2 (n:nat) : nat -> Prop :=\n  | le2_n : le2 n n\n  | le2_S m (H : le2 n m) : le2 n (S m).\n\nNotation \"m <=2 n\" := (le2 m n) (at level 70).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. *)\n\nCheck le1_ind :\n  forall P : nat -> nat -> Prop,\n    (forall n : nat, P n n) ->\n    (forall n m : nat, n <=1 m -> P n m -> P n (S m)) ->\n    forall n n0 : nat, n <=1 n0 -> P n n0.\n\nCheck le2_ind :\n  forall (n : nat) (P : nat -> Prop),\n    P n ->\n    (forall m : nat, n <=2 m -> P m -> P (S m)) ->\n    forall n0 : nat, n <=2 n0 -> P n0.\n\n(* ################################################################# *)\n(** * Another Form of Induction Principles on Propositions (Optional) *)\n\n(** The induction principle that Coq generated for [ev] was parameterized\n    on a natural number [n].  It could have additionally been parameterized\n    on the evidence that [n] was even, which would have led to this\n    induction principle:\n\n    forall P : (forall n : nat, ev'' n -> Prop),\n      P O ev_0 ->\n      (forall (m : nat) (E : ev'' m),\n        P m E -> P (S (S m)) (ev_SS m E)) ->\n      forall (n : nat) (E : ev'' n), P n E\n*)\n\n(**   ... because:\n\n     - Since [ev] is indexed by a number [n] (every [ev] object [E] is\n       a piece of evidence that some particular number [n] is even),\n       the proposition [P] is parameterized by both [n] and [E] --\n       that is, the induction principle can be used to prove\n       assertions involving both an even number and the evidence that\n       it is even.\n\n     - Since there are two ways of giving evidence of evenness ([even]\n       has two constructors), applying the induction principle\n       generates two subgoals:\n\n         - We must prove that [P] holds for [O] and [ev_0].\n\n         - We must prove that, whenever [m] is an even number and [E]\n           is an evidence of its evenness, if [P] holds of [m] and\n           [E], then it also holds of [S (S m)] and [ev_SS m E].\n\n     - If these subgoals can be proved, then the induction principle\n       tells us that [P] is true for _all_ even numbers [n] and\n       evidence [E] of their evenness.\n\n    This is more flexibility than we normally need or want: it is\n    giving us a way to prove logical assertions where the assertion\n    involves properties of some piece of _evidence_ of evenness, while\n    all we really care about is proving properties of _numbers_ that\n    are even -- we are interested in assertions about numbers, not\n    about evidence.  It would therefore be more convenient to have an\n    induction principle for proving propositions [P] that are\n    parameterized just by [n] and whose conclusion establishes [P] for\n    all even numbers [n]:\n\n       forall P : nat -> Prop,\n         ... ->\n       forall n : nat,\n         even n -> P n\n\n    That is why Coq actually generates the induction principle\n    [ev_ind] that we saw before. *)\n\n(* ################################################################# *)\n(** * Formal vs. Informal Proofs by Induction *)\n\n(** Question: What is the relation between a formal proof of a\n    proposition [P] and an informal proof of the same proposition [P]?\n\n    Answer: The latter should _teach_ the reader everything they would\n    need to understand to be able to produce the former.\n\n    Question: How much detail does that require?\n\n    Unfortunately, there is no single right answer; rather, there is a\n    range of choices.\n\n    At one end of the spectrum, we can essentially give the reader the\n    whole formal proof (i.e., the \"informal\" proof will amount to just\n    transcribing the formal one into words).  This may give the reader\n    the ability to reproduce the formal one for themselves, but it\n    probably doesn't _teach_ them anything much.\n\n   At the other end of the spectrum, we can say \"The theorem is true\n   and you can figure out why for yourself if you think about it hard\n   enough.\"  This is also not a good teaching strategy, because often\n   writing the proof requires one or more significant insights into\n   the thing we're proving, and most readers will give up before they\n   rediscover all the same insights as we did.\n\n   In the middle is the golden mean -- a proof that includes all of\n   the essential insights (saving the reader the hard work that we\n   went through to find the proof in the first place) plus high-level\n   suggestions for the more routine parts to save the reader from\n   spending too much time reconstructing these (e.g., what the IH says\n   and what must be shown in each case of an inductive proof), but not\n   so much detail that the main ideas are obscured.\n\n   Since we've spent much of this chapter looking \"under the hood\" at\n   formal proofs by induction, now is a good moment to talk a little\n   about _informal_ proofs by induction.\n\n   In the real world of mathematical communication, written proofs\n   range from extremely longwinded and pedantic to extremely brief and\n   telegraphic.  Although the ideal is somewhere in between, while one\n   is getting used to the style it is better to start out at the\n   pedantic end.  Also, during the learning phase, it is probably\n   helpful to have a clear standard to compare against.  With this in\n   mind, we offer two templates -- one for proofs by induction over\n   _data_ (i.e., where the thing we're doing induction on lives in\n   [Type]) and one for proofs by induction over _evidence_ (i.e.,\n   where the inductively defined thing lives in [Prop]). *)\n\n(* ================================================================= *)\n(** ** Induction Over an Inductively Defined Set *)\n\n(** _Template_:\n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_:\n\n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if [length [] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of [index].\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n\n            length l = length (x::l') = S (length l'),\n\n          it suffices to show that\n\n            index (S (length l')) l' = None.\n\n          But this follows directly from the induction hypothesis,\n          picking [n'] to be [length l'].  [] *)\n\n(* ================================================================= *)\n(** ** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_.\n\n    _Template_:\n\n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n\n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n(* ################################################################# *)\n(** * Explicit Proof Objects for Induction (Optional) *)\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n\n(** Recall again the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declaration for [nat]. *)\n\nCheck nat_ind :\n  forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, P n -> P (S n)) ->\n    forall n : nat, P n.\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n\nPrint nat_ind.\n\n(** We can rewrite that more tidily as follows: *)\nFixpoint build_proof\n         (P : nat -> Prop)\n         (evPO : P 0)\n         (evPS : forall n : nat, P n -> P (S n))\n         (n : nat) : P n :=\n  match n with\n  | 0 => evPO\n  | S k => evPS k (build_proof P evPO evPS k)\n  end.\n\nDefinition nat_ind_tidy := build_proof.\n\n(** We can read [build_proof] as follows: Suppose we have\n    evidence [evPO] that [P] holds on 0, and evidence [evPS] that [forall\n    n:nat, P n -> P (S n)].  Then we can prove that [P] holds of an\n    arbitrary nat [n] using recursive function [build_proof], which\n    pattern matches on [n]:\n\n      - If [n] is 0, [build_proof] returns [evPO] to show that [P n]\n        holds.\n\n      - If [n] is [S k], [build_proof] applies itself recursively on\n        [k] to obtain evidence that [P k] holds; then it applies\n        [evPS] on that evidence to show that [P (S n)] holds. *)\n\n(** Recursive function [build_proof] thus pattern matches against\n    [n], recursing all the way down to 0, and building up a proof\n    as it returns. *)\n\n(** The actual [nat_ind] that Coq generates uses a recursive\n    function [F] defined with [fix] instead of [Fixpoint]. *)\n\n(** We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  As a motivating example,\n    suppose that we want to prove the following lemma, directly\n    relating the [ev] predicate we defined in [IndProp]\n    to the [even] function defined in [Basics]. *)\n\nLemma even_ev : forall n: nat, even n = true -> ev n.\nProof.\n  induction n; intros.\n  - apply ev_0.\n  - destruct n.\n    + simpl in H. inversion H.\n    + simpl in H.\n      apply ev_SS.\nAbort.\n\n(** Attempts to prove this by standard induction on [n] fail in the case for\n    [S (S n)], because the induction hypothesis only tells us something about\n    [S n], which is useless. There are various ways to hack around this problem;\n    for example, we _can_ use ordinary induction on [n] to prove this (try it!):\n\n    [Lemma even_ev' : forall n : nat,\n     (even n = true -> ev n) /\\ (even (S n) = true -> ev (S n))].\n\n    But we can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n *)\n\nDefinition nat_ind2 :\n  forall (P : nat -> Prop),\n  P 0 ->\n  P 1 ->\n  (forall n : nat, P n -> P (S(S n))) ->\n  forall n : nat , P n :=\n    fun P => fun P0 => fun P1 => fun PSS =>\n      fix f (n:nat) := match n with\n                         0 => P0\n                       | 1 => P1\n                       | S (S n') => PSS n' (f n')\n                       end.\n\n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive.\n\n     The [induction ... using] tactic variant gives a convenient way to\n     utilize a non-standard induction principle like this. *)\n\nLemma even_ev : forall n, even n = true -> ev n.\nProof.\n  intros.\n  induction n as [ | |n'] using nat_ind2.\n  - apply ev_0.\n  - simpl in H.\n    inversion H.\n  - simpl in H.\n    apply ev_SS.\n    apply IHn'.\n    apply H.\nQed.\n\n\n\n(** **** Exercise: 4 stars, standard, optional (t_tree)\n\n    What if we wanted to define binary trees as follows, using a\n    constructor that bundles the children and value at a node into a\n    tuple? *)\n\nNotation \"( x , y , .. , z )\" := (pair .. (pair x y) .. z) : core_scope.\n\nInductive t_tree (X : Type) : Type :=\n| t_leaf\n| t_branch : (t_tree X * X * t_tree X) -> t_tree X.\n\nArguments t_leaf {X}.\nArguments t_branch {X}.\n\n(** Unfortunately, the automatically-generated induction principle is\n    not as strong as we need. It doesn't introduce induction hypotheses\n    for the subtrees. *)\n\nCheck t_tree_ind.\n\n(** That will get us in trouble if we want to prove something by\n    induction, such as that [reflect] is an involution. *)\n\nFixpoint reflect {X : Type} (t : t_tree X) : t_tree X :=\n  match t with\n  | t_leaf => t_leaf\n  | t_branch (l, v, r) => t_branch (reflect r, v, reflect l)\n  end.\n\nTheorem reflect_involution : forall (X : Type) (t : t_tree X),\n    reflect (reflect t) = t.\nProof.\n  intros X t. induction t.\n  - reflexivity.\n  - destruct p as [[l v] r]. simpl. Abort.\n\n(** We get stuck, because we have no inductive hypothesis for [l] or\n    [r]. So, we need to define our own custom induction principle, and\n    use it to complete the proof.\n\n    First, define the type of the induction principle that you want to\n    use. There are many possible answers. Recall that you can use\n    [match] as part of the definition. *)\n\nDefinition better_t_tree_ind_type : Prop\n  := forall (X : Type) (P : t_tree X -> Prop), P (t_leaf) -> (forall v : X, forall l : t_tree X, P l -> forall r : t_tree X, P r -> P (t_branch (l, v, r))) -> forall (t : t_tree X), P t.\n\n(** Second, define the induction principle by giving a term of that\n    type. Use the examples about [nat], above, as models. *)\n\nDefinition better_t_tree_ind : better_t_tree_ind_type\n  := fun X P Pleaf Pbranch => fix f t :=\n    match t with\n    | t_leaf => Pleaf\n    | t_branch (l, v, r) => Pbranch v l (f l) r (f r)\n    end.\n\n(** Finally, prove the theorem. If [induction...using] gives you an\n    error about \"Cannot recognize an induction scheme\", don't worry\n    about it. The [induction] tactic is picky about the shape of the\n    theorem you pass to it, but it doesn't give you much information\n    to debug what is wrong about that shape.  You can use [apply]\n    instead, as we saw at the beginning of this file. *)\n\nTheorem reflect_involution : forall (X : Type) (t : t_tree X),\n    reflect (reflect t) = t.\nProof.\n  intros X.\n  apply better_t_tree_ind.\n  - reflexivity.\n  - intros v l IHl r IHr. simpl. rewrite IHl. rewrite IHr. reflexivity.\nQed.\n\n(** [] *)\n\n(* 2022-08-08 17:13 *)\n", "meta": {"author": "marshall-lee", "repo": "software_foundations", "sha": "d45ee7466f45de8d836692a3455742764ed58b83", "save_path": "github-repos/coq/marshall-lee-software_foundations", "path": "github-repos/coq/marshall-lee-software_foundations/software_foundations-d45ee7466f45de8d836692a3455742764ed58b83/lf/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.8807970685907242, "lm_q1q2_score": 0.7138674388473416}}
{"text": "Require Import List.\nSet  Implicit Arguments.\n \nSection perms.\nVariable A : Set.\n \nInductive transpose : list A -> list A ->  Prop :=\n  transpose_hd:\n    forall (a b : A) (l : list A),  transpose (a :: (b :: l)) (b :: (a :: l))\n | transpose_tl:\n     forall (a : A) (l l' : list A),\n     transpose l l' ->  transpose (a :: l) (a :: l') .\n \nInductive perm (l : list A) : list A ->  Prop :=\n  perm_id: perm l l\n | perm_tr:\n     forall (l' l'' : list A), perm l l' -> transpose l' l'' ->  perm l l'' .\n \nEnd perms.\nRequire Import Arith.\nCheck eq_nat_dec.\n \nFixpoint nb_occ (n : nat) (l : list nat) {struct l} : nat :=\n match l with\n   nil => 0\n  | p :: l' =>\n      match eq_nat_dec n p with   left _ => S (nb_occ n l')\n                                 | right _ => nb_occ n l' end\n end.\nPrint eq_nat_dec.\n \nLemma transpose_nb_occ:\n forall (l l' : list nat),\n transpose l l' -> forall (n : nat),  nb_occ n l = nb_occ n l'.\nProof.\nintros l l' H; elim H; simpl.\nintros a b l0 n; case (eq_nat_dec n a); case (eq_nat_dec n b); simpl; auto.\nintros a l0 l'0 H0 H1 n; case (eq_nat_dec n a); simpl; auto.\nQed.\n \nLemma perm_nb_occ:\n forall (l l' : list nat),\n perm l l' -> forall (n : nat),  nb_occ n l = nb_occ n l'.\nProof.\nintros l l' H; elim H; auto.\nintros l'0; intros.\ntransitivity (nb_occ n l'0).\nauto.\napply transpose_nb_occ; auto.\nQed.\n \nLemma not_perm: ~ perm (2 :: (3 :: (1 :: nil))) (3 :: (1 :: (1 :: nil))).\nProof.\nintros abs.\ngeneralize (perm_nb_occ abs 1).\nsimpl; discriminate 1.\nQed.\n(* What follows is the solution to the last exercise proposed \n  in the chapter on reflexion.  It uses a computation of numbers\n  of occurrences to decide that two lists are not equal. *)\n \nFixpoint eq_nat_bool (n1 n2 : nat) {struct n1} : bool :=\n match n1, n2 with\n   0, 0 => true\n  | S n1', S n2' => eq_nat_bool n1' n2'\n  | _, _ => false\n end.\n \nFixpoint check_all_occs (l1 l2 l3 : list nat) {struct l3} : bool :=\n match l3 with\n   nil => true\n  | a :: tl =>\n      if eq_nat_bool (nb_occ a l1) (nb_occ a l2) then check_all_occs l1 l2 tl\n        else false\n end.\n \nTheorem eq_nat_bool_false:\n forall n1 n2, eq_nat_bool n1 n2 = false ->  ~ n1 = n2.\ninduction n1; destruct n2; simpl; intros; discriminate || auto.\nQed.\n \nTheorem check_all_occs_false:\n forall l1 l2 l3,\n check_all_occs l1 l2 l3 = false ->\n  (exists n : nat , nb_occ n l1 <> nb_occ n l2 ).\nintros l1 l2 l3; elim l3.\nsimpl; intros; discriminate.\nintros n l IHl; simpl.\ngeneralize (@eq_nat_bool_false (nb_occ n l1) (nb_occ n l2)).\ncase (eq_nat_bool (nb_occ n l1) (nb_occ n l2)).\nauto.\nintros; exists n; auto.\nQed.\n \nTheorem check_all_occs_not_perm:\n forall l1 l2, check_all_occs l1 l2 l1 = false ->  ~ perm l1 l2.\nintros l1 l2 Heq Hperm; elim (check_all_occs_false l1 l2 l1 Heq); intros n Hneq;\n elim Hneq; apply perm_nb_occ; assumption.\nQed.\n \nLtac\nnoperm := match goal with\n          | |- ~ perm ?l1 ?l2 => apply check_all_occs_not_perm; reflexivity end.\n \nTheorem not_perm2:\n ~ perm (1 :: (3 :: (2 :: nil))) (3 :: (1 :: (1 :: (4 :: (2 :: nil))))).\nnoperm.\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/moreperms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389113, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7138277828622709}}
{"text": "Require Import MyTactics.\nRequire Import RelationClasses.\nRequire Import Relations.\nRequire Import Ensembles.\n\n(** Equivalence classes. *)\n\nDefinition class {A} (R: relation A) (x: A) := R x.\nHint Unfold class.\n\nLemma class_eq_inv {A} {R: relation A} {E: Equivalence R} :\n  forall (x y: A),\n    class R x = class R y ->\n    R x y.\nProof.\nintros x y H.\nfold (class R x). rewrite H.\nreflexivity.\nQed.\n\nLemma class_eq_compat {A} {R: relation A} {E: Equivalence R} :\n  forall (x y: A),\n    R x y ->\n    class R x = class R y.\nProof.\nintros x y H. apply Extensionality_Ensembles.\nsplit; intros z Hz; compute; compute in Hz.\n* transitivity x; trivial. symmetry; trivial.\n* transitivity y; trivial.\nQed.\n\nLemma class_trans_R {A} {R: relation A} {E: Equivalence R} :\n  forall (x y z: A),\n    In _ (class R x) z ->\n    In _ (class R y) z ->\n    R x y.\nProof.\nintros x y z Hx Hy. compute in Hx. compute in Hy.\ntransitivity z; trivial. symmetry; trivial.\nQed.\n\nLemma class_trans_eq {A} {R: relation A} {E: Equivalence R} :\n  forall (x y z: A),\n    In _ (class R x) z ->\n    In _ (class R y) z ->\n    class R x = class R y.\nProof.\nintros x y z Hx Hy. apply class_eq_compat.\ncompute in Hx. compute in Hy. transitivity z; trivial. symmetry; trivial.\nQed.\n\nLemma class_sym {A} {R: relation A} {E: Equivalence R} :\n  forall (x y: A),\n    In _ (class R x) y ->\n    In _ (class R y) x.\nProof.\ncompute. intros x y H. symmetry. trivial.\nQed.\n\nLemma class_refl {A} {R: relation A} {E: Equivalence R} :\n  forall x, In _ (class R x) x.\nProof.\nintros x. compute. reflexivity.\nQed.\n\nLemma class_included_rel {A}\n      (R1: relation A) {E1: Equivalence R1}\n      (R2: relation A) {E2: Equivalence R2} :\n  inclusion _ R1 R2 ->\n  forall x,\n  Included _ (class R1 x) (class R2 x).\nProof.\nintros H x y Hy. apply H. assumption.\nQed.\n\nLemma class_eq_rel {A}\n      (R1: relation A) {E1: Equivalence R1}\n      (R2: relation A) {E2: Equivalence R2} :\n  same_relation _ R1 R2 ->\n  forall x,\n  class R1 x = class R2 x.\nProof.\nintros [H1 H2] x. apply Extensionality_Ensembles.\nsplit; apply class_included_rel; trivial.\nQed.\n\nLemma class_eq_included_rel {A}\n      (R1: relation A) {E1: Equivalence R1}\n      (R2: relation A) {E2: Equivalence R2} :\n  inclusion _ R1 R2 ->\n  forall x y,\n    class R1 x = class R1 y ->\n    class R2 x = class R2 y.\nProof.\nintros H x y H1.\napply class_eq_compat. apply H.\napply class_eq_inv. assumption.\nQed.\n\nLemma not_rel_class_neq {A} (R: relation A) {E: Equivalence R} :\n  forall x y,\n    ~ R x y ->\n    class R x <> class R y.\nProof.\nintros x y H Hn. apply H.\napply class_eq_inv. assumption.\nQed.\n", "meta": {"author": "esope", "repo": "robustness_coq", "sha": "149b3b60f5f018237ad5371212cdb1e9e4603fdf", "save_path": "github-repos/coq/esope-robustness_coq", "path": "github-repos/coq/esope-robustness_coq/robustness_coq-149b3b60f5f018237ad5371212cdb1e9e4603fdf/EquivClass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7138277789479459}}
{"text": "(* LongsTheorem.v *)\n(* author: Peter Urbak *)\n(* version: 2014-06-02 *)\n\n(** * Long's Theorem *)\n\n(** ** Requirements *)\n\n(* Standard library *)\nRequire Import Arith.\n\n(* Own modules *)\nRequire Import Cases.\nRequire Import Power.\nRequire Import BinomialCoefficients.\nRequire Import ListCalculus.\nRequire Import StreamCalculus.\nRequire Import DualMoessnersSieve.\nRequire Import CharacteristicFunction.\nRequire Import MoessnersTheorem.\n\n(** * Parameterized monomial *)\n\n(* {P_MONOMIAL} *)\nDefinition p_monomial (x n k d : nat) : nat :=\n  d * C(n,k) * x ^ k.\n(* {END} *)\nHint Unfold p_monomial : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_monomial :\n  forall (x n k d : nat),\n    p_monomial x n k d = d * C(n, k) * x ^ k.\nProof.\n  intros x n k c.\n  unfold p_monomial.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_monomial : long.\n\n(** *** Properties *)\n\nLemma p_monomial_k_eq_0_implies_d :\n  forall (x n d : nat),\n    p_monomial x n 0 d = d.\nProof.\n  intros x n d.\n  rewrite -> unfold_p_monomial.\n  rewrite -> unfold_binomial_coefficient_base_case_n_0.\n  rewrite ->2 mult_1_r.\n  reflexivity.\nQed.\nHint Rewrite p_monomial_k_eq_0_implies_d : long.\n\nLemma p_monomial_n_lt_k_implies_0 :\n  forall (x n k d : nat),\n    n < k ->\n    p_monomial x n k d = 0.\nProof.\n  intros x n k d H_n_lt_k.\n  rewrite -> unfold_p_monomial.\n  inversion_clear H_n_lt_k.\n\n  Case \"k = S n\".\n  rewrite -> binomial_coefficient_n_lt_k_implies_0;\n    [ idtac | unfold lt; apply le_n ].\n  rewrite -> mult_0_r, mult_0_l.\n  reflexivity.\n\n  Case \"k = S m\".\n  rename H into H_S_n_le_m.\n  rewrite -> binomial_coefficient_n_lt_k_implies_0;\n    [ idtac | unfold lt; apply le_S; exact H_S_n_le_m ].\n  rewrite -> mult_0_r, -> mult_0_l.\n  reflexivity.\nQed.\nHint Rewrite p_monomial_n_lt_k_implies_0 : long.\n\nLemma p_monomial_n_eq_k_implies_power :\n  forall (x n d : nat),\n    p_monomial x n n d = d * x ^ n.\nProof.\n  intros x n d.\n  rewrite -> unfold_p_monomial.\n  rewrite -> binomial_coefficient_n_eq_k_implies_1.\n  rewrite -> mult_1_r.\n  reflexivity.\nQed.\nHint Rewrite p_monomial_n_eq_k_implies_power : long.\n\nLemma p_monomial_Pascal_s_rule :\n  forall (x n' k' d : nat),\n    p_monomial x (S n') (S k') d =\n    p_monomial x n' (S k') d + x * p_monomial x n' k' d.\nProof.\n  intros x n' k' d.\n  rewrite ->2 unfold_p_monomial.\n  rewrite -> Pascal_s_rule.\n  rewrite <- mult_assoc.\n  rewrite -> mult_plus_distr_r.\n  rewrite -> mult_plus_distr_l.\n  rewrite -> mult_assoc.\n  rewrite <- unfold_p_monomial.\n  rewrite -> unfold_power_induction_case.\n  rewrite -> (NPeano.Nat.mul_shuffle3 (C(n', k')) x (x ^ k')).\n  rewrite -> NPeano.Nat.mul_shuffle3.\n  rewrite -> (mult_assoc d _ _).\n  rewrite <- (unfold_p_monomial _ _ _ d).\n  reflexivity.\nQed.\nHint Rewrite p_monomial_Pascal_s_rule : long.\n\n(** * Parameteriezd characteristic function of Moessner's sieve *)\n\n(** ** Moessner Entry Binomial\n\n  Given a value [d], rank [r], a row [n], a column [k], and a triangle [t],\n  calculate the specific entry of a Moessner triangle.\n\n  *** Definition *)\n\n(* {P_MOESSNER_ENTRY} *)\nFixpoint p_moessner_entry (r n k t d : nat) : nat :=\n  match n with\n    | 0 => match k with\n             | 0 => d\n             | S k' => 0\n           end\n    | S n' => match k with\n                | 0 => p_monomial t r (S n') d +\n                       p_moessner_entry r n' 0 t d\n                | S k' => p_moessner_entry r n' (S k') t d +\n                          p_moessner_entry r n' k' t d\n              end\n  end.\n(* {END} *)\nHint Unfold p_moessner_entry : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_moessner_entry_base_case_O :\n  forall (r t d : nat),\n    p_moessner_entry r 0 0 t d = d.\nProof.\n  intros r t d.\n  unfold p_moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_moessner_entry_base_case_O : long.\n\nLemma unfold_p_moessner_entry_base_case_S :\n  forall (r k' t d : nat),\n    p_moessner_entry r 0 (S k') t d = 0.\nProof.\n  intros r k' t d.\n  unfold p_moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_moessner_entry_base_case_S : long.\n\nLemma unfold_p_moessner_entry_induction_case_O :\n  forall (n' r t d : nat),\n    p_moessner_entry r (S n') 0 t d =\n    p_monomial t r (S n') d + p_moessner_entry r n' 0 t d.\nProof.\n  intros n' r t d.\n  unfold p_moessner_entry; fold p_moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_moessner_entry_induction_case_O : long.\n\nLemma unfold_p_moessner_entry_induction_case_S :\n  forall (n' r k' t d : nat),\n    p_moessner_entry r (S n') (S k') t d =\n    p_moessner_entry r n' (S k') t d +\n    p_moessner_entry r n' k' t d.\nProof.\n  intros n' r k' t d.\n  unfold p_moessner_entry; fold p_moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_moessner_entry_induction_case_S : long.\n\n(** *** Properties *)\n\nDefinition p_moessner_entry_Pascal_s_rule :=\n  unfold_p_moessner_entry_induction_case_S.\nHint Rewrite p_moessner_entry_Pascal_s_rule : long.\n\nLemma p_moessner_entry_eq_c_binomial_coefficient :\n  forall (r k n d : nat),\n    p_moessner_entry n r k 0 d = d * C(r, k).\nProof.\n  induction r as [ | r' IH_r' ].\n\n  Case \"r = 0\".\n  intros n k d.\n  unfold p_moessner_entry, binomial_coefficient.\n  case n as [ | n' ];\n    [ rewrite -> mult_1_r; reflexivity |\n      rewrite -> mult_0_r; reflexivity ].\n\n  Case \"r = S r'\".\n  case k as [ | k' ].\n\n  SCase \"k = 0\".\n  intros n d.\n  rewrite -> unfold_p_moessner_entry_induction_case_O.\n  rewrite -> (IH_r' 0 n).\n  rewrite -> unfold_p_monomial.\n  rewrite -> power_0_e.\n  rewrite -> mult_0_r.\n  rewrite -> plus_0_l.\n  rewrite ->2 unfold_binomial_coefficient_base_case_n_0.\n  rewrite -> mult_1_r.\n  reflexivity.\n\n  SCase \"k = S k'\".\n  intros n d.\n  rewrite -> p_moessner_entry_Pascal_s_rule.\n  rewrite -> (IH_r' (S k') n).\n  rewrite -> (IH_r' k' n).\n  rewrite <- mult_plus_distr_l.\n  rewrite <- Pascal_s_rule.\n  reflexivity.\nQed.\nHint Rewrite p_moessner_entry_eq_c_binomial_coefficient : long.\n\nLemma p_moessner_entry_n_lt_k_implies_0 :\n  forall (r n k t d : nat),\n    n < k ->\n    p_moessner_entry r n k t d = 0.\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  case k as [ | k' ].\n\n  SCase \"k = 0\".\n  intros t d H_absurd; inversion H_absurd.\n\n  SCase \"k = S k'\".\n  intros t d H_0_lt_S_k'.\n  rewrite -> unfold_p_moessner_entry_base_case_S.\n  reflexivity.\n\n  Case \"n = S n'\".\n  case k as [ | k' ].\n\n  SCase \"k = 0\".\n  intros t d H_absurd; inversion H_absurd.\n\n  SCase \"k = S k'\".\n  intros t d H_S_n'_lt_S_k'.\n  rewrite -> p_moessner_entry_Pascal_s_rule.\n\n  assert (H_n'_lt_S_k': n' < S k').\n    apply lt_S_n.\n    unfold lt.\n    apply le_S.\n    unfold lt in H_S_n'_lt_S_k'.\n    exact H_S_n'_lt_S_k'.\n\n  rewrite -> (IH_n' (S k') t d H_n'_lt_S_k'); clear H_n'_lt_S_k'.\n  rewrite -> plus_0_l.\n\n  assert (H_n'_lt_k': n' < k').\n    apply lt_S_n.\n    exact H_S_n'_lt_S_k'.\n\n  rewrite -> (IH_n' k' t d H_n'_lt_k').\n  reflexivity.\nQed.\nHint Resolve p_moessner_entry_n_lt_k_implies_0 : long.\n\nLemma p_moessner_entry_n_eq_k_implies_d :\n  forall (n r t d : nat),\n    p_moessner_entry r n n t d = d.\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros r t d.\n  rewrite -> unfold_p_moessner_entry_base_case_O.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intros r t d.\n  rewrite -> p_moessner_entry_Pascal_s_rule.\n  rewrite -> (IH_n' r t).\n  rewrite -> p_moessner_entry_n_lt_k_implies_0;\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  reflexivity.\nQed.\nHint Rewrite p_moessner_entry_n_eq_k_implies_d : long.\n\n(** ** Moessner Entries Binomial\n\n  [p_moessner_entry] as a [Stream nat].\n\n  *** Definition *)\n\n(* {P_MOESSNER_ENTRIES} *)\nCoFixpoint p_moessner_entries (r n k t d : nat) : Stream nat :=\n  (p_moessner_entry r n k t d) :::\n  (p_moessner_entries r n (S k) t d).\n(* {END} *)\nHint Unfold p_moessner_entries : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_moessner_entries :\n  forall (r n k t d : nat),\n    p_moessner_entries r n k t d =\n    (p_moessner_entry r n k t d) :::\n    (p_moessner_entries r n (S k) t d).\nProof.\n  intros r n k t d.\n  rewrite -> (unfold_Stream (p_moessner_entries r n k t d)).\n  unfold p_moessner_entries; fold p_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_moessner_entries : long.\n\nLemma p_moessner_entries_initial_value :\n  forall (r n k t d : nat),\n    (p_moessner_entries r n k t d)(0) =\n    (p_moessner_entry r n k t d).\nProof.\n  intros r n k t d.\n  rewrite -> initial_value.\n  rewrite -> unfold_p_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite p_moessner_entries_initial_value : long.\n\nLemma p_moessner_entries_stream_derivative :\n  forall (r n k t d : nat),\n    (p_moessner_entries r n k t d)` =\n    (p_moessner_entries r n (S k) t d).\nProof.\n  intros r n k t d.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_p_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite p_moessner_entries_stream_derivative : long.\n\n(** ** Properties *)\n\nLemma Str_nth_p_moessner_entries :\n  forall (i r n k t d : nat),\n    Str_nth i (p_moessner_entries r n k t d) =\n    p_moessner_entry r n (i + k) t d.\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros r n k t d.\n  rewrite -> Str_nth_0.\n  rewrite -> p_moessner_entries_initial_value.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros r n k t d.\n  rewrite -> Str_nth_S_n.\n  rewrite -> p_moessner_entries_stream_derivative.\n  rewrite -> (IH_i' r n (S k) t d).\n  rewrite <- plus_n_Sm.\n  rewrite -> plus_Sn_m.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_moessner_entries : long.\n\n(** ** Moessner Entry Rotated\n\n  Given a rank [n], a row [r], a column [c], and a triangle [t],\n  calculate the specific entry of a Moessner triangle.\n\n  *** Definition *)\n\n(* {P_ROTATED_MOESSNER_ENTRY} *)\nDefinition p_rotated_moessner_entry (n r c t d : nat) : nat :=\n  p_moessner_entry n (c + r) c t d.\n(* {END} *)\nHint Unfold p_rotated_moessner_entry : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_rotated_moessner_entry :\n  forall (n r c t d : nat),\n    p_rotated_moessner_entry n r c t d =\n    p_moessner_entry n (c + r) c t d.\nProof.\n  intros n r c t d.\n  unfold p_rotated_moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_rotated_moessner_entry : long.\n\nLemma p_rotated_moessner_entry_Pascal_s_rule :\n  forall (n r' c' t d : nat),\n    p_rotated_moessner_entry n (S r') (S c') t d =\n    p_rotated_moessner_entry n r' (S c') t d +\n    p_rotated_moessner_entry n (S r') c' t d.\nProof.\n  intros n r' c' t d.\n  rewrite ->3 unfold_p_rotated_moessner_entry.\n  rewrite <-2 plus_n_Sm.\n  rewrite -> plus_Sn_m.\n  rewrite -> p_moessner_entry_Pascal_s_rule.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_Pascal_s_rule : long.\n\n(** *** Properties *)\n\nLemma p_rotated_moessner_entry_eq_d_binomial_coefficient :\n  forall (n r c d : nat),\n    p_rotated_moessner_entry n r c 0 d = d * C(c + r, c).\nProof.\n  intros n r c d.\n  rewrite -> unfold_p_rotated_moessner_entry.\n  rewrite -> p_moessner_entry_eq_c_binomial_coefficient.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_eq_d_binomial_coefficient : long.\n\n(* {P_ROTATED_MOESSNER_ENTRY_EQ_D_ROTATED_BINOMIAL_COEFFICIENT} *)\nCorollary p_rotated_moessner_entry_eq_d_rotated_binomial_coefficient :\n  forall (n r c d : nat),\n    p_rotated_moessner_entry n r c 0 d = d * R(r, c).\n(* {END} *)\nProof.\n  intros n r c d.\n  rewrite -> p_rotated_moessner_entry_eq_d_binomial_coefficient.\n  rewrite -> rotated_binomial_coefficient_is_symmetric.\n  rewrite -> unfold_rotated_binomial_coefficient.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_eq_d_rotated_binomial_coefficient : long.\n\nLemma p_rotated_moessner_entry_r_eq_0_implies_d :\n  forall (c n t d : nat),\n    p_rotated_moessner_entry n 0 c t d = d.\nProof.\n  intros c n t d.\n  rewrite -> unfold_p_rotated_moessner_entry.\n  rewrite -> plus_0_r.\n  rewrite -> p_moessner_entry_n_eq_k_implies_d.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_r_eq_0_implies_d : long.\n\nLemma p_rotated_moessner_entry_c_eq_0 :\n  forall (r' n t d : nat),\n    p_rotated_moessner_entry n (S r') 0 t d =\n    p_monomial t n (S r') d + p_rotated_moessner_entry n r' 0 t d.\nProof.\n  intros r' n t d.\n  rewrite ->2 unfold_p_rotated_moessner_entry.\n  rewrite ->2 plus_0_l.\n  rewrite -> unfold_p_moessner_entry_induction_case_O.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_c_eq_0 : long.\n\n(** ** Moessner Entries Rotated\n\n  *** Definition *)\n\n(* {P_ROTATED_MOESSNER_ENTRIES} *)\nCoFixpoint p_rotated_moessner_entries (n r c t d : nat) : Stream nat :=\n  (p_rotated_moessner_entry n r c t d) :::\n  (p_rotated_moessner_entries n (S r) c t d).\n(* {END} *)\nHint Unfold p_rotated_moessner_entries : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_rotated_moessner_entries :\n  forall (n r c t d : nat),\n    p_rotated_moessner_entries n r c t d =\n    (p_rotated_moessner_entry n r c t d) :::\n    (p_rotated_moessner_entries n (S r) c t d).\nProof.\n  intros n r c t d.\n  rewrite -> (unfold_Stream (p_rotated_moessner_entries n r c t d)).\n  unfold p_rotated_moessner_entries; fold p_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_rotated_moessner_entries : long.\n\nLemma p_rotated_moessner_entries_initial_value :\n  forall (n r c t d : nat),\n    (p_rotated_moessner_entries n r c t d)(0) =\n    (p_rotated_moessner_entry n r c t d).\nProof.\n  intros n r c t d.\n  rewrite -> initial_value.\n  rewrite -> unfold_p_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entries_initial_value : long.\n\nLemma p_rotated_moessner_entries_stream_derivative :\n  forall (n r c t d : nat),\n    (p_rotated_moessner_entries n r c t d)` =\n    (p_rotated_moessner_entries n (S r) c t d).\nProof.\n  intros n r c t d.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_p_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entries_stream_derivative : long.\n\n(** ** Properties *)\n\nLemma Str_nth_p_rotated_moessner_entries :\n  forall (i n r c t d : nat),\n    Str_nth i (p_rotated_moessner_entries n r c t d) =\n    p_rotated_moessner_entry n (r + i) c t d.\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros n r c t d.\n  rewrite -> Str_nth_0.\n  rewrite -> p_rotated_moessner_entries_initial_value.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros n r c t d.\n  rewrite -> Str_nth_S_n.\n  rewrite -> p_rotated_moessner_entries_stream_derivative.\n  rewrite -> (IH_i' n (S r) c t d).\n  rewrite <- plus_n_Sm, -> plus_Sn_m.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_rotated_moessner_entries : long.\n\nCorollary Str_nth_p_rotated_moessner_entries_t_eq_0 :\n  forall (i n r c d : nat),\n    Str_nth i (p_rotated_moessner_entries n r c 0 d) =\n    d * C(c + (r + i), c).\nProof.\n  intros i n r c d.\n  rewrite -> Str_nth_p_rotated_moessner_entries.\n  rewrite -> p_rotated_moessner_entry_eq_d_binomial_coefficient.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_rotated_moessner_entries_t_eq_0 : long.\n\nLemma p_rotated_moessner_entries_Pascal_s_rule :\n  forall (n r' c' t d : nat),\n    p_rotated_moessner_entries n (S r') (S c') t d ~\n    (p_rotated_moessner_entries n (S r') c' t d) s+\n    (p_rotated_moessner_entries n r' (S c') t d).\nProof.\n  pcofix coIH.\n  intros n r' c' t d.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> stream_sum_initial_value.\n  rewrite ->3 p_rotated_moessner_entries_initial_value.\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  rewrite -> plus_comm.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> stream_sum_stream_derivative.\n  rewrite ->3 p_rotated_moessner_entries_stream_derivative.\n  exact (coIH n (S r') c' t d).\nQed.\nHint Rewrite p_rotated_moessner_entries_Pascal_s_rule : long.\n\n(** * Streams of P_Monomials *)\n\n(** ** P_Monomials\n\n  The stream of p_monomials of the binomial expansion.\n\n  *** Definition *)\n\n(* {P_MONOMIALS} *)\nCoFixpoint p_monomials (t r n d : nat) : Stream nat :=\n  (p_monomial t r n d) ::: (p_monomials t r (S n) d).\n(* {END} *)\nHint Unfold p_monomials : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_monomials :\n  forall (t r n d : nat),\n    p_monomials t r n d = (p_monomial t r n d) ::: (p_monomials t r (S n) d).\nProof.\n  intros t r n d.\n  rewrite -> (unfold_Stream (p_monomials t r n d)).\n  unfold p_monomials; fold p_monomials.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_monomials : long.\n\nLemma p_monomials_initial_value :\n  forall (t r n d : nat),\n    (p_monomials t r n d)(0) = (p_monomial t r n d).\nProof.\n  intros t r n d.\n  rewrite -> initial_value.\n  rewrite -> unfold_p_monomials.\n  reflexivity.\nQed.\nHint Rewrite p_monomials_initial_value : long.\n\nLemma p_monomials_stream_derivative :\n  forall (t r n d : nat),\n    (p_monomials t r n d)` = (p_monomials t r (S n) d).\nProof.\n  intros t r n d.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_p_monomials.\n  reflexivity.\nQed.\nHint Rewrite p_monomials_stream_derivative : long.\n\n(** *** Properties *)\n\nLemma Str_nth_p_monomials :\n  forall (i t r n d : nat),\n    Str_nth i (p_monomials t r n d) = p_monomial t r (i + n) d.\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros t r n d.\n  rewrite -> Str_nth_0.\n  rewrite -> p_monomials_initial_value.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros t r n d.\n  rewrite -> Str_nth_S_n.\n  rewrite -> p_monomials_stream_derivative.\n  rewrite -> (IH_i' t r (S n) d).\n  rewrite -> plus_Sn_m, <- plus_n_Sm.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_monomials : long.\n\nLemma Str_nth_p_monomials_i_plus_n_gt_r_implies_0 :\n  forall (i r n t d : nat),\n    r < n + i ->\n    Str_nth i (p_monomials t r n d) = 0.\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros r n t d H_r_lt_n.\n  rewrite -> plus_0_r in H_r_lt_n.\n  rewrite -> Str_nth_0.\n  rewrite -> p_monomials_initial_value.\n  rewrite -> unfold_p_monomial.\n  rewrite -> (binomial_coefficient_n_lt_k_implies_0 r n H_r_lt_n).\n  rewrite -> mult_0_r, -> mult_0_l.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros r n t d H_r_lt_n_plus_S_i'.\n  rewrite -> Str_nth_S_n.\n  rewrite p_monomials_stream_derivative.\n  rewrite -> (IH_i' r (S n) t d);\n    [ idtac | rewrite -> plus_Sn_m, -> plus_n_Sm; exact H_r_lt_n_plus_S_i' ].\n  reflexivity.\nQed.\nHint Resolve Str_nth_p_monomials_i_plus_n_gt_r_implies_0 : long.\n\nLemma p_monomials_t_eq_0_aux :\n  forall (k n d : nat),\n    (p_monomials 0 k n d)` ~ #0.\nProof.\n  pcofix coIH.\n  intros k n d.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> p_monomials_stream_derivative.\n  rewrite -> p_monomials_initial_value.\n  rewrite -> unfold_p_monomial.\n  rewrite -> power_0_e.\n  rewrite -> mult_0_r.\n  rewrite -> stream_constant_initial_value.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> p_monomials_stream_derivative.\n  rewrite -> stream_constant_stream_derivative.\n  exact (coIH k (S n) d).\nQed.\nHint Rewrite p_monomials_t_eq_0_aux : long.\n\nCorollary p_monomials_t_eq_0 :\n  forall (k d : nat),\n    (p_monomials 0 k 0 d) ~ d ::: #0.\nProof.\n  intros k d.\n  rewrite -> (decompose_Stream (p_monomials 0 k 0 d)).\n  rewrite -> (p_monomials_t_eq_0_aux k 0).\n  rewrite -> p_monomials_initial_value.\n  rewrite -> unfold_p_monomial.\n  rewrite -> unfold_power_base_case.\n  rewrite -> unfold_binomial_coefficient_base_case_n_0.\n  rewrite ->2 mult_1_r.\n  reflexivity.\nQed.\nHint Rewrite p_monomials_t_eq_0 : long.\n\nLemma p_monomials_tail_of_0s :\n  forall (i n t d : nat),\n    Str_nth_tl (S i) (p_monomials t i n d) ~ #0.\nProof.\n  pcofix coIH.\n  intros i n t d.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite <- unfold_Str_nth.\n  rewrite -> Str_nth_p_monomials_i_plus_n_gt_r_implies_0;\n    [ idtac | unfold lt; apply le_plus_r ].\n  rewrite -> stream_constant_initial_value.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> Str_nth_tl_stream_derivative_case_i_gt_0.\n  rewrite ->2 p_monomials_stream_derivative.\n  rewrite -> stream_constant_stream_derivative.\n  exact (coIH i (S n) t d).\nQed.\nHint Rewrite p_monomials_tail_of_0s : long.\n\nLemma rev_Str_prefix_p_monomials :\n  forall (l n r t d : nat),\n    rev (Str_prefix (S l) (p_monomials t r n d)) =\n    p_monomial t r (n + l) d :: rev (Str_prefix l (p_monomials t r n d)).\nProof.\n  induction l as [ | l' IH_l' ].\n\n  Case \"l = 0\".\n  intros n r t d.\n  rewrite -> plus_0_r.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite -> unfold_rev_base_case.\n  rewrite -> p_monomials_initial_value.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> unfold_rev_base_case.\n  rewrite -> app_nil_l.\n  reflexivity.\n\n  Case \"l = S l'\".\n  intros n r t d.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> p_monomials_stream_derivative.\n  rewrite -> IH_l'.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> p_monomials_initial_value.\n  rewrite -> p_monomials_stream_derivative.\n  rewrite <- plus_n_Sm, -> plus_Sn_m.\n  rewrite -> unfold_rev_induction_case.\n  rewrite <- app_comm_cons.\n  reflexivity.\nQed.\nHint Rewrite rev_Str_prefix_p_monomials : long.\n\n(** ** P_Monomials Sum\n\n  *** Definition *)\n\n(* {P_MONOMIALS_SUM} *)\nCoFixpoint p_monomials_sum (t r n a d : nat) : Stream nat :=\n  let a' := (p_monomial t r n d) + a in\n  a' ::: (p_monomials_sum t r (S n) a' d).\n(* {END} *)\nHint Unfold p_monomials_sum : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_monomials_sum :\n  forall (t r n a d : nat),\n    p_monomials_sum t r n a d =\n    ((p_monomial t r n d) + a) :::\n    (p_monomials_sum t r (S n) ((p_monomial t r n d) + a) d).\nProof.\n  intros t r n a d.\n  rewrite -> (unfold_Stream (p_monomials_sum t r n a d)).\n  unfold p_monomials_sum; fold p_monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_monomials_sum : long.\n\nLemma p_monomials_sum_initial_value :\n  forall (t r n a d : nat),\n    (p_monomials_sum t r n a d)(0) = (p_monomial t r n d) + a.\nProof.\n  intros t r n a d.\n  rewrite -> initial_value.\n  rewrite -> unfold_p_monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite p_monomials_sum_initial_value : long.\n\nLemma p_monomials_sum_stream_derivative :\n  forall (t r n a d : nat),\n    (p_monomials_sum t r n a d)` =\n    (p_monomials_sum t r (S n) ((p_monomial t r n d) + a) d).\nProof.\n  intros t r n a d.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_p_monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite p_monomials_sum_stream_derivative : long.\n\n(** *** Properties *)\n\nLemma p_monomials_sum_acc_aux :\n  forall (t l n i j d : nat),\n    (p_monomials_sum t l n (i + j) d) ~\n    (p_monomials_sum t l n i d) s+ #j.\nProof.\n  pcofix coIH.\n  intros t l n i j d.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> p_monomials_sum_initial_value.\n  rewrite -> stream_sum_initial_value.\n  rewrite -> p_monomials_sum_initial_value.\n  rewrite -> stream_constant_initial_value.\n  rewrite <- plus_assoc.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> p_monomials_sum_stream_derivative.\n  rewrite -> stream_sum_stream_derivative.\n  rewrite -> p_monomials_sum_stream_derivative.\n  rewrite -> stream_constant_stream_derivative.\n  rewrite -> plus_assoc.\n  exact (coIH t l (S n) ((p_monomial t l n d) + i) j d).\nQed.\nHint Rewrite p_monomials_sum_acc_aux : long.\n\nCorollary p_monomials_sum_acc :\n  forall (t l n a d : nat),\n    (p_monomials_sum t l n a d) ~\n    (p_monomials_sum t l n 0 d) s+ #a.\nProof.\n  intros t l n a d.\n  rewrite <- p_monomials_sum_acc_aux.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Rewrite p_monomials_sum_acc : long.\n\nLemma Str_nth_p_monomials_sum_stream_derivative :\n  forall (i n t l a d : nat),\n    Str_nth i (p_monomials_sum t l n a d)` =\n    Str_nth i ((p_monomials_sum t l (S n) a d) s+ #(p_monomial t l n d)).\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros n t l a d.\n  rewrite -> p_monomials_sum_stream_derivative.\n  rewrite ->2 Str_nth_0.\n  rewrite -> stream_sum_initial_value.\n  rewrite ->2 p_monomials_sum_initial_value.\n  rewrite -> stream_constant_initial_value.\n  rewrite <- plus_assoc.\n  f_equal.\n  rewrite -> plus_comm.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros n t l a d.\n  rewrite ->2 Str_nth_S_n.\n  rewrite -> p_monomials_sum_stream_derivative.\n  rewrite -> stream_sum_stream_derivative.\n  rewrite -> (IH_i' (S n) t l ((p_monomial t l n d) + a)).\n  rewrite -> p_monomials_sum_stream_derivative.\n  rewrite -> stream_constant_stream_derivative.\n  rewrite <-2 p_monomials_sum_acc_aux.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  rewrite -> (plus_comm a _).\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_monomials_sum_stream_derivative : long.\n\nCorollary p_monomials_sum_stream_derivative_bisim :\n  forall (n t l a d : nat),\n    (p_monomials_sum t l n a d)` ~\n    (p_monomials_sum t l (S n) a d) s+ #(p_monomial t l n d).\nProof.\n  intros n t l a d.\n  apply Str_nth_implies_bisimilarity; intro i.\n  exact (Str_nth_p_monomials_sum_stream_derivative i n t l a d).\nQed.\nHint Rewrite p_monomials_sum_stream_derivative_bisim : long.\n\nLemma Str_nth_p_monomials_sum_r_eq_0 :\n  forall (i t n' m' a d : nat),\n    Str_nth i (p_monomials_sum t 0 (S n') a d) =\n    Str_nth i (p_monomials_sum t 0 (S m') a d).\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros t n' m' a d.\n  rewrite ->2 Str_nth_0.\n  rewrite ->2 p_monomials_sum_initial_value.\n  rewrite ->2 unfold_p_monomial.\n  rewrite ->2 unfold_binomial_coefficient_base_case_0_S_k'.\n  rewrite -> mult_0_r, ->2 mult_0_l.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros t n' m' a d.\n  rewrite ->2 Str_nth_S_n.\n  rewrite ->2 Str_nth_p_monomials_sum_stream_derivative.\n  unfold stream_sum.\n  rewrite ->2 Str_nth_stream_zip.\n  rewrite -> (IH_i' t (S n') (S m') a d).\n  rewrite ->2 Str_nth_stream_constant.\n  rewrite ->2 unfold_p_monomial.\n  rewrite ->2 unfold_binomial_coefficient_base_case_0_S_k'.\n  rewrite -> mult_0_r, -> mult_0_l, ->2 plus_0_r.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_monomials_sum_r_eq_0 : long.\n\nLemma about_p_monomial_and_p_monomials_sum :\n  forall (i' r n a t d : nat),\n   p_monomial t r n d + Str_nth i' (p_monomials_sum t r (S n) a d) =\n   p_monomial t r (n + (S i')) d + Str_nth i' (p_monomials_sum t r n a d).\nProof.\n  induction i' as [ | i'' IH_i'' ].\n\n  Case \"i' = 0\".\n  intros r n a t d.\n  rewrite ->2 Str_nth_0.\n  rewrite ->2 p_monomials_sum_initial_value.\n  rewrite -> plus_permute.\n  rewrite -> (plus_comm n 1).\n  reflexivity.\n\n  Case \"i' = S i''\".\n  intros r n a t d.\n  rewrite -> Str_nth_S_n.\n  rewrite -> Str_nth_p_monomials_sum_stream_derivative.\n  unfold stream_sum.\n  rewrite -> Str_nth_stream_zip.\n  rewrite -> Str_nth_stream_constant.\n  rewrite <- (plus_comm (p_monomial t r (S n) d) _).\n  rewrite -> (IH_i'' r (S n) a t d).\n  rewrite <-3 plus_n_Sm, -> plus_Sn_m.\n\n  rewrite -> Str_nth_S_n.\n  rewrite -> Str_nth_p_monomials_sum_stream_derivative.\n  unfold stream_sum.\n  rewrite -> Str_nth_stream_zip.\n  rewrite -> Str_nth_stream_constant.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  reflexivity.\nQed.\nHint Rewrite about_p_monomial_and_p_monomials_sum : long.\n\n(** * Equivalence relations *)\n\nTheorem Str_nth_p_monomials_sum_eq_p_rotated_moessner_entry :\n  forall (i t r a d : nat),\n    Str_nth i (p_monomials_sum t r 0 a d) =\n    (p_rotated_moessner_entry r i 0 t d) + a.\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros t r a d.\n  rewrite -> Str_nth_0.\n  rewrite -> p_monomials_sum_initial_value.\n  rewrite -> unfold_p_monomial.\n  rewrite -> unfold_power_base_case.\n  rewrite -> mult_1_r.\n  rewrite -> unfold_binomial_coefficient_base_case_n_0.\n\n  rewrite -> unfold_p_rotated_moessner_entry.\n  rewrite -> plus_0_r, -> mult_1_r.\n  rewrite -> unfold_p_moessner_entry_base_case_O.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros t r a d.\n  rewrite -> Str_nth_S_n.\n  rewrite -> Str_nth_p_monomials_sum_stream_derivative.\n  unfold stream_sum.\n  rewrite -> Str_nth_stream_zip.\n  rewrite -> Str_nth_stream_constant.\n  rewrite -> plus_comm.\n\n  unfold p_rotated_moessner_entry in *.\n  rewrite -> plus_0_l in *.\n  rewrite -> unfold_p_moessner_entry_induction_case_O.\n  rewrite <- plus_assoc.\n  rewrite <- (IH_i' t r a d).\n  rewrite -> about_p_monomial_and_p_monomials_sum.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_monomials_sum_eq_p_rotated_moessner_entry : long.\n\nLemma stream_partial_sums_acc_p_monomials_bisim_p_monomials_sum :\n  forall (t l n a d : nat),\n    stream_partial_sums_acc a (p_monomials t l n d) ~\n    p_monomials_sum t l n a d.\nProof.\n  pcofix coIH.\n  intros t l n a d.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> stream_partial_sums_acc_initial_value.\n  rewrite -> p_monomials_initial_value.\n  rewrite -> p_monomials_sum_initial_value.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> stream_partial_sums_acc_stream_derivative.\n  rewrite -> p_monomials_stream_derivative.\n  rewrite -> p_monomials_sum_stream_derivative.\n  rewrite -> p_monomials_initial_value.\n  exact (coIH t l (S n) (p_monomial t l n d + a) d).\nQed.\nHint Rewrite stream_partial_sums_acc_p_monomials_bisim_p_monomials_sum : long.\n\n(* {STREAM_PARTIAL_SUMS_P_MONOMIALS_BISIM_P_MONOMIALS_SUM} *)\nCorollary stream_partial_sums_p_monomials_bisim_p_monomials_sum :\n  forall (t l n d : nat),\n    stream_partial_sums (p_monomials t l n d) ~\n    p_monomials_sum t l n 0 d.\n(* {END} *)\nProof.\n  intros t l n d.\n  rewrite -> unfold_stream_partial_sums.\n  exact (stream_partial_sums_acc_p_monomials_bisim_p_monomials_sum t l n 0 d).\nQed.\nHint Rewrite stream_partial_sums_p_monomials_bisim_p_monomials_sum : long.\n\n(* {P_MONOMIALS_AND_MAKE_TUPLE} *)\nCorollary p_monomials_and_make_tuple :\n  forall (l t r n a d : nat),\n    make_tuple (Str_prefix (S l) (p_monomials t r n d)) a =\n    Str_prefix l (p_monomials_sum t r n a d).\n(* {END} *)\nProof.\n  intros l t r n a d.\n  rewrite -> equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  rewrite -> stream_partial_sums_acc_p_monomials_bisim_p_monomials_sum.\n  reflexivity.\nQed.\nHint Rewrite p_monomials_and_make_tuple : long.\n\nCorollary p_monomials_and_p_rotated_moessner_entry :\n  forall (l t r a d : nat),\n    nth l (make_tuple (Str_prefix (S (S l)) (p_monomials t r 0 d)) a) 0 =\n    p_rotated_moessner_entry r l 0 t d + a.\nProof.\n  intros l t r a d.\n  rewrite <- Str_nth_p_monomials_sum_eq_p_rotated_moessner_entry.\n  rewrite -> p_monomials_and_make_tuple.\n  rewrite -> (nth_and_Str_nth l (S l) (p_monomials_sum t r 0 a d));\n      [ idtac | unfold lt; apply le_n ].\n  reflexivity.\nQed.\nHint Rewrite p_monomials_and_p_rotated_moessner_entry : long.\n\n(* {P_ROTATED_MOESSNER_ENTRIES_BISIM_P_MONOMIALS_SUM} *)\nCorollary p_rotated_moessner_entries_bisim_p_monomials_sum :\n  forall (n t d : nat),\n    p_rotated_moessner_entries n 0 0 t d ~\n    p_monomials_sum t n 0 0 d.\n(* {END} *)\nProof.\n  intros n t d.\n  apply Str_nth_implies_bisimilarity; intro i.\n  rewrite -> Str_nth_p_rotated_moessner_entries.\n  rewrite -> plus_0_l.\n  rewrite -> Str_nth_p_monomials_sum_eq_p_rotated_moessner_entry.\n  rewrite -> plus_0_r.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entries_bisim_p_monomials_sum : long.\n\n(** * Columns of Moessner Entries Rotated *)\n\n(** Proof that partially summing the [c']th column of rotated moessner entries\n  gives the [S c']th column *)\n\nLemma Str_nth_p_rotated_moessner_entries_inductive_case :\n  forall (i n r' c' t d : nat),\n    Str_nth i (p_rotated_moessner_entries n (S r') (S c') t d) =\n    Str_nth i (stream_partial_sums_acc\n                 (p_rotated_moessner_entry n r' (S c') t d)\n                 (p_rotated_moessner_entries n (S r') c' t d)).\nProof.\n  induction i as [ | i' IH_i' ].\n\n  Case \"i = 0\".\n  intros n r' c' t d.\n  rewrite ->2 Str_nth_0.\n  rewrite -> stream_partial_sums_acc_initial_value.\n  rewrite ->2 p_rotated_moessner_entries_initial_value.\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  rewrite -> plus_comm.\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros n r' c' t d.\n  rewrite ->2 Str_nth_S_n.\n  rewrite -> stream_partial_sums_acc_stream_derivative.\n  rewrite ->2 p_rotated_moessner_entries_stream_derivative.\n  rewrite -> p_rotated_moessner_entries_initial_value.\n  rewrite -> (IH_i' n (S r') c' t d).\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_rotated_moessner_entries_inductive_case : long.\n\n(* {P_ROTATED_MOESSNER_ENTRIES_BISIM_PREVIOUS_COLUMN_INDUCTIVE_CASE} *)\nCorollary p_rotated_moessner_entries_bisim_previous_column_inductive_case :\n  forall (n r' c' t d : nat),\n    (p_rotated_moessner_entries n (S r') (S c') t d) ~\n    (stream_partial_sums_acc (p_rotated_moessner_entry n r' (S c') t d)\n                      (p_rotated_moessner_entries n (S r') c' t d)).\n(* {END} *)\nProof.\n  intros n r' c' t d.\n  apply Str_nth_implies_bisimilarity; intro i.\n  exact\n  (Str_nth_p_rotated_moessner_entries_inductive_case i n r' c' t d).\nQed.\nHint Rewrite p_rotated_moessner_entries_bisim_previous_column_inductive_case\n  : long.\n\nLemma Str_nth_p_rotated_moessner_entries_base_case :\n  forall (i n c' t d : nat),\n    Str_nth i (p_rotated_moessner_entries n 0 (S c') t d) =\n    Str_nth i (stream_partial_sums_acc 0 (p_rotated_moessner_entries n 0 c' t d)).\nProof.\n  case i as [ | i' ].\n\n  Case \"i = 0\".\n  intros n c' t d.\n  rewrite ->2 Str_nth_0.\n  rewrite -> stream_partial_sums_acc_initial_value.\n  rewrite -> plus_0_r.\n  rewrite ->2 p_rotated_moessner_entries_initial_value.\n  rewrite ->2 unfold_p_rotated_moessner_entry.\n  rewrite ->2 plus_0_r.\n  rewrite -> p_moessner_entry_Pascal_s_rule.\n  rewrite -> p_moessner_entry_n_lt_k_implies_0;\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  reflexivity.\n\n  Case \"i = S i'\".\n  intros n c' t d.\n  rewrite ->2 Str_nth_S_n.\n  rewrite -> stream_partial_sums_acc_stream_derivative.\n  rewrite -> plus_0_r.\n  rewrite ->2 p_rotated_moessner_entries_stream_derivative.\n  rewrite -> p_rotated_moessner_entries_initial_value.\n  rewrite -> Str_nth_p_rotated_moessner_entries_inductive_case.\n  rewrite ->2 unfold_p_rotated_moessner_entry.\n  rewrite ->2 plus_0_r.\n  rewrite -> p_moessner_entry_Pascal_s_rule.\n  rewrite -> p_moessner_entry_n_lt_k_implies_0;\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  reflexivity.\nQed.\nHint Rewrite Str_nth_p_rotated_moessner_entries_base_case : long.\n\n(* {P_ROTATED_MOESSNER_ENTRIES_BISIM_PREVIOUS_COLUMN_BASE_CASE} *)\nCorollary p_rotated_moessner_entries_bisim_previous_column_base_case :\n  forall (n c' t d : nat),\n    (p_rotated_moessner_entries n 0 (S c') t d) ~\n    (stream_partial_sums_acc 0 (p_rotated_moessner_entries n 0 c' t d)).\n(* {END} *)\nProof.\n  intros n c' t d.\n  apply Str_nth_implies_bisimilarity; intro i.\n  exact (Str_nth_p_rotated_moessner_entries_base_case i n c' t d).\nQed.\nHint Rewrite p_rotated_moessner_entries_bisim_previous_column_base_case : long.\n\nLemma last_of_p_rotated_moessner_entries :\n  forall (c l n t d : nat),\n    last (Str_prefix (S l) (p_rotated_moessner_entries n 0 c t d)) 0 =\n    p_rotated_moessner_entry n l c t d.\nProof.\n  intros c l n t d.\n  rewrite -> (length_implies_last_index l);\n    [ idtac | rewrite -> Str_prefix_length; reflexivity ].\n  rewrite -> nth_and_Str_nth;\n    [ idtac | unfold lt; apply le_n ].\n  rewrite -> Str_nth_p_rotated_moessner_entries.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Rewrite last_of_p_rotated_moessner_entries : long.\n\nCorollary last_of_p_rotated_moessner_entries_to_binomial :\n  forall (c l n t d : nat),\n    last (Str_prefix (S l) (p_rotated_moessner_entries n 0 c t d)) 0 =\n    p_moessner_entry n (c + l) c t d.\nProof.\n  intros c l n t d.\n  rewrite -> last_of_p_rotated_moessner_entries.\n  rewrite -> unfold_p_rotated_moessner_entry.\n  reflexivity.\nQed.\nHint Rewrite last_of_p_rotated_moessner_entries_to_binomial : long.\n\n(** Proof that applying [make_tuple] on a column of [p_rotated_moessner_entries]\n  gives the next column *)\n\n(* {MAKE_TUPLE_P_ROTATED_MOESSNER_ENTRIES} *)\nCorollary make_tuple_p_rotated_moessner_entries :\n  forall (l' n' c' t d : nat),\n    make_tuple (Str_prefix (S l') (p_rotated_moessner_entries n' 0 c' t d)) 0 =\n    Str_prefix l' (p_rotated_moessner_entries n' 0 (S c') t d).\n(* {END} *)\nProof.\n  intros l' n' c' t d.\n  rewrite -> p_rotated_moessner_entries_bisim_previous_column_base_case.\n  rewrite -> equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  reflexivity.\nQed.\nHint Rewrite make_tuple_p_rotated_moessner_entries : long.\n\n(** * Spelled out correctness proof of P Moessner Entry Rotated *)\n\n(** ** Correctness proof of repeat_make_tuple and p_rotated_moessner_entry *)\n\nTheorem Str_prefix_p_rotated_moessner_entries :\n  forall (c l n t d : nat),\n    Str_prefix l (p_rotated_moessner_entries n 0 c t d) =\n    repeat_make_tuple\n      (Str_prefix (c + l) (p_rotated_moessner_entries n 0 0 t d)) 0 c.\nProof.\n  induction c as [ | c' IH_c' ].\n\n  Case \"c = 0\".\n  intros l n t d.\n  rewrite -> plus_0_l.\n  rewrite -> unfold_repeat_make_tuple_base_case.\n  reflexivity.\n\n  Case \"c = S c'\".\n  intros l n t d.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite <- shift_make_tuple_in_repeat_make_tuple.\n  rewrite -> plus_Sn_m, -> plus_n_Sm.\n  rewrite <- (IH_c' (S l) n t d).\n  rewrite -> make_tuple_p_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite Str_prefix_p_rotated_moessner_entries : long.\n\n(* {REPEAT_MAKE_TUPLE_P_MONOMIALS_EQ_MOESSNER_ENTRIES} *)\nCorollary repeat_make_tuple_p_monomials_eq_moessner_entries :\n  forall (c l n t d : nat),\n    Str_prefix l (p_rotated_moessner_entries n 0 c t d) =\n    repeat_make_tuple (Str_prefix (S c + l) (p_monomials t n 0 d)) 0 (S c).\n(* {END} *)\nProof.\n  intros c l n t d.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> plus_Sn_m.\n  rewrite -> p_monomials_and_make_tuple.\n  rewrite <- p_rotated_moessner_entries_bisim_p_monomials_sum.\n  rewrite <- Str_prefix_p_rotated_moessner_entries.\n  reflexivity.\nQed.\nHint Rewrite repeat_make_tuple_p_monomials_eq_moessner_entries : long.\n\nLemma repeat_make_tuple_p_monomials_eq_moessner_entries_general :\n  forall (k j n t d : nat),\n    j <= k ->\n    Str_prefix (k - j) (p_rotated_moessner_entries n 0 j t d) =\n    repeat_make_tuple (Str_prefix (S k) (p_monomials t n 0 d)) 0 (S j).\nProof.\n  induction k as [ | k' IH_k' ].\n\n  Case \"k = 0\".\n  intros j n t d H_j_le_0.\n  unfold minus.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite -> p_monomials_initial_value.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite -> unfold_make_tuple_base_case_x_nil.\n  rewrite -> repeat_make_tuple_nil.\n  reflexivity.\n\n  Case \"k = S k'\".\n  induction j as [ | j' IH_j' ].\n\n  SCase \"j = 0\".\n  intros n t d H_0_le_S_k'.\n  rewrite <- minus_n_O.\n  rewrite -> repeat_make_tuple_p_monomials_eq_moessner_entries.\n  reflexivity.\n\n  SCase \"j = S j'\".\n  intros n t d H_S_j_le_S_k.\n  rewrite -> unfold_repeat_make_tuple_induction_case.\n  rewrite <- shift_make_tuple_in_repeat_make_tuple.\n  rewrite <- (IH_j' n t d);\n    [ idtac | apply lt_le_weak; unfold lt; exact H_S_j_le_S_k ].\n  rewrite <- make_tuple_p_rotated_moessner_entries.\n  rewrite -> NPeano.Nat.sub_succ.\n  rewrite -> minus_Sn_m;\n    [ idtac | apply gt_S_le; unfold gt, lt; exact H_S_j_le_S_k ].\n  reflexivity.\nQed.\nHint Resolve repeat_make_tuple_p_monomials_eq_moessner_entries_general : long.\n\n(* {CORRECTNESS_OF_P_ROTATED_MOESSNER_ENTRY} *)\nTheorem correctness_of_p_rotated_moessner_entry :\n  forall (i j r t d : nat),\n    j <= S r ->\n    S i <= S r - j ->\n    (nth i\n         (nth j\n              (create_triangle_vertically\n                 (tuple_constant (S (S r)) 0)\n                 (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n              [])\n         0) =\n    p_rotated_moessner_entry r i j t d.\n(* {END} *)\nProof.\n  intros i j r t d H_j_le_S_r H_S_i_le_S_r_minus_j.\n\n  assert (H_length_helper: (S (S r)) =\n             (length (Str_prefix (S (S r)) (p_monomials t r 0 d)))).\n    rewrite -> Str_prefix_length.\n    reflexivity.\n\n  assert (H_rewrite_helper:\n            (tuple_constant (S (S r)) 0) =\n            (tuple_constant\n               (length (Str_prefix (S (S r)) (p_monomials t r 0 d)))) 0).\n    f_equal.\n    exact H_length_helper.\n\n  rewrite -> H_rewrite_helper; clear H_length_helper H_rewrite_helper.\n  rewrite <- correctness_of_repeat_make_tuple.\n\n  rewrite <- repeat_make_tuple_p_monomials_eq_moessner_entries_general;\n    [ idtac | exact H_j_le_S_r ].\n\n  rewrite -> nth_and_Str_nth;\n    [ idtac | unfold lt; exact H_S_i_le_S_r_minus_j ].\n\n  rewrite -> Str_nth_p_rotated_moessner_entries.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Resolve correctness_of_p_rotated_moessner_entry : long.\n\n(** * Decomposition by Rank *)\n\n(* Decomposition by rank (moessner entry rotated) *)\n\nTheorem p_rotated_moessner_entry_rank_decompose_by_row :\n  forall (r c n t d : nat),\n  p_rotated_moessner_entry (S n) (S r) c t d =\n  t * p_rotated_moessner_entry n r c t d +\n  p_rotated_moessner_entry n (S r) c t d.\nProof.\n  induction r as [ | r' IH_r' ].\n\n  Case \"r = 0\".\n  induction c as [ | c' IH_c' ].\n\n  SCase \"c = 0\".\n  intros n t d.\n  rewrite -> p_rotated_moessner_entry_r_eq_0_implies_d.\n  rewrite ->2 unfold_p_rotated_moessner_entry.\n  rewrite -> plus_0_l.\n  rewrite ->2 unfold_p_moessner_entry_induction_case_O.\n  rewrite ->2 unfold_p_moessner_entry_base_case_O.\n  rewrite -> plus_comm.\n  symmetry.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  rewrite <- plus_permute.\n  f_equal.\n  rewrite ->2 unfold_p_monomial.\n  rewrite -> power_b_1.\n  rewrite -> Pascal_s_rule.\n  rewrite -> unfold_binomial_coefficient_base_case_n_0.\n  rewrite -> mult_plus_distr_l.\n  rewrite -> mult_plus_distr_r.\n  rewrite -> mult_1_r.\n  rewrite -> (mult_comm d t).\n  reflexivity.\n\n  SCase \"c = S c'\".\n  intros n t d.\n  rewrite -> p_rotated_moessner_entry_r_eq_0_implies_d.\n  rewrite ->2 p_rotated_moessner_entry_Pascal_s_rule.\n  rewrite ->2 p_rotated_moessner_entry_r_eq_0_implies_d.\n  rewrite <- plus_permute.\n  f_equal.\n  rewrite -> (IH_c' n t d).\n  rewrite -> p_rotated_moessner_entry_r_eq_0_implies_d.\n  reflexivity.\n\n  Case \"r = S r'\".\n  induction c as [ | c' IH_c' ].\n\n  SCase \"c = 0\".\n  intros n t d.\n  rewrite -> p_rotated_moessner_entry_c_eq_0.\n  rewrite -> IH_r'.\n  symmetry.\n  rewrite -> p_rotated_moessner_entry_c_eq_0.\n  rewrite -> mult_plus_distr_l.\n  rewrite <- plus_assoc.\n  rewrite <- plus_permute.\n  symmetry.\n  rewrite <- plus_permute.\n  f_equal.\n  rewrite -> p_monomial_Pascal_s_rule.\n  rewrite <- plus_assoc.\n  rewrite <- plus_permute.\n  symmetry.\n  rewrite ->2 p_rotated_moessner_entry_c_eq_0.\n  reflexivity.\n\n  SCase \"c = S c'\".\n  intros n t d.\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  rewrite -> (IH_c' n t d).\n  rewrite -> (IH_r' (S c') n t d).\n  symmetry.\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  rewrite -> mult_plus_distr_l.\n  rewrite <-3 plus_assoc.\n  f_equal.\n  symmetry.\n  rewrite <-2 (plus_permute (t * p_rotated_moessner_entry n (S r') c' t d)).\n  f_equal.\n  symmetry.\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  rewrite <- plus_assoc.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_rank_decompose_by_row : long.\n\nCorollary p_moessner_entry_rank_decompose_by_row :\n  forall (r c n t d : nat),\n   p_moessner_entry (S n) (c + S r) c t d =\n   t * p_moessner_entry n (c + r) c t d +\n   p_moessner_entry n (c + S r) c t d.\nProof.\n  intros r c n t d.\n  rewrite <-3 unfold_p_rotated_moessner_entry.\n  exact (p_rotated_moessner_entry_rank_decompose_by_row r c n t d).\nQed.\nHint Rewrite p_moessner_entry_rank_decompose_by_row : long.\n\nCorollary p_rotated_moessner_entry_rank_decompose_Pascal_like_c_eq_0 :\n  forall (r n t d : nat),\n    p_rotated_moessner_entry (S n) (S r) 0 t d =\n    (S t) * p_rotated_moessner_entry n r 0 t d +\n    p_monomial t n (S r) d.\nProof.\n  intros r n t d.\n  rewrite -> p_rotated_moessner_entry_rank_decompose_by_row.\n  unfold mult; fold mult.\n  rewrite <- plus_assoc.\n  rewrite <- plus_permute.\n  f_equal.\n  rewrite -> p_rotated_moessner_entry_c_eq_0.\n  rewrite -> plus_comm.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_rank_decompose_Pascal_like_c_eq_0 : long.\n\nCorollary p_moessner_entry_rank_decompose_Pascal_like_c_eq_0 :\n  forall (r n t d : nat),\n    p_moessner_entry (S n) (S r) 0 t d =\n    S t * p_moessner_entry n r 0 t d +\n    p_monomial t n (S r) d.\nProof.\n  intros r n t d.\n  rewrite <- (plus_0_l (S r)).\n  rewrite <- unfold_p_rotated_moessner_entry.\n  rewrite <- (plus_0_l r).\n  rewrite <- unfold_p_rotated_moessner_entry.\n  rewrite -> plus_0_l.\n  exact (p_rotated_moessner_entry_rank_decompose_Pascal_like_c_eq_0 r n t d).\nQed.\nHint Rewrite p_moessner_entry_rank_decompose_Pascal_like_c_eq_0 : long.\n\nCorollary p_rotated_moessner_entry_rank_decompose_Pascal_like_c_gt_0 :\n  forall (r c n t d : nat),\n  p_rotated_moessner_entry (S n) (S r) (S c) t d =\n  (S t) * p_rotated_moessner_entry n r (S c) t d +\n  p_rotated_moessner_entry n (S r) c t d.\nProof.\n  intros r c n t d.\n  rewrite -> p_rotated_moessner_entry_rank_decompose_by_row.\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  unfold mult; fold mult.\n  rewrite <- plus_assoc.\n  rewrite <- plus_permute.\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_rank_decompose_Pascal_like_c_gt_0\n  : long.\n\nCorollary p_moessner_entry_rank_decompose_Pascal_like_c_gt_0 :\n  forall (r c n t d : nat),\n   p_moessner_entry (S n) (S c + S r) (S c) t d =\n   (S t) * p_moessner_entry n (S c + r) (S c) t  d+\n   p_moessner_entry n (c + S r) c t d.\nProof.\n  intros r c n t d.\n  rewrite -> p_moessner_entry_rank_decompose_by_row.\n  rewrite <- plus_n_Sm.\n  rewrite -> p_moessner_entry_Pascal_s_rule.\n  unfold mult; fold mult.\n  rewrite <- plus_assoc.\n  rewrite <- plus_permute.\n  rewrite <- plus_n_Sm, -> plus_Sn_m.\n  reflexivity.\nQed.\nHint Rewrite p_moessner_entry_rank_decompose_Pascal_like_c_gt_0\n  : long.\n\n(* Decomposition by rank (create_triangle_vertically) *)\n\nCorollary p_create_triangle_vertically_decompose_by_rank :\n  forall (i j r t d : nat),\n    j <= r ->\n    S i <= r - j ->\n    (nth (S i)\n         (nth j\n              (create_triangle_vertically\n                 (tuple_constant (S (S (S r))) 0)\n                 (Str_prefix (S (S (S r))) (p_monomials t (S r) 0 d)))\n              [])\n         0) =\n    t * (nth i\n             (nth j\n                  (create_triangle_vertically\n                     (tuple_constant (S (S r)) 0)\n                     (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n                  [])\n             0) +\n    (nth (S i)\n         (nth j\n              (create_triangle_vertically\n                 (tuple_constant (S (S r)) 0)\n                 (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n              [])\n         0).\nProof.\n  intros i j r t d H_j_le_r H_S_i_le_r_minus_j.\n  rewrite -> correctness_of_p_rotated_moessner_entry;\n    [ idtac |\n      apply le_S; apply le_S; exact H_j_le_r |\n      rewrite <- minus_Sn_m;\n        [ idtac | apply le_S; exact H_j_le_r ];\n        apply le_n_S; rewrite <- minus_Sn_m; [ idtac | exact H_j_le_r ];\n        apply le_S; exact H_S_i_le_r_minus_j ].\n\n  rewrite -> correctness_of_p_rotated_moessner_entry;\n    [ idtac |\n      apply le_S; exact H_j_le_r |\n      rewrite <- minus_Sn_m; [ idtac | exact H_j_le_r ];\n      apply le_S; exact H_S_i_le_r_minus_j ].\n\n  rewrite -> correctness_of_p_rotated_moessner_entry;\n    [ idtac |\n      apply le_S; exact H_j_le_r |\n      rewrite <- minus_Sn_m; [ idtac | exact H_j_le_r ];\n      apply le_n_S; exact H_S_i_le_r_minus_j ].\n\n  exact (p_rotated_moessner_entry_rank_decompose_by_row i j r t d).\nQed.\nHint Rewrite p_create_triangle_vertically_decompose_by_rank : long.\n\nCorollary p_create_triangle_vertically_rank_decompose_Pascal_like_c_eq_0 :\n  forall (i r t d : nat),\n    i < (S r) ->\n    (nth (S i)\n         (nth 0\n              (create_triangle_vertically\n                 (tuple_constant (S (S (S r))) 0)\n                 (Str_prefix (S (S (S r))) (p_monomials t (S r) 0 d)))\n              [])\n         0) =\n    (S t) * (nth i\n                 (nth 0\n                      (create_triangle_vertically\n                         (tuple_constant (S (S r)) 0)\n                         (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n                      [])\n                   0) +\n    p_monomial t r (S i) d.\nProof.\n  intros i r t d H_i_lt_S_r.\n\n  rewrite -> correctness_of_p_rotated_moessner_entry;\n    [ idtac |\n      exact (le_0_n (S (S r))) |\n      unfold lt in H_i_lt_S_r; rewrite <- minus_n_O;\n      apply le_n_S; exact H_i_lt_S_r ].\n\n  rewrite -> correctness_of_p_rotated_moessner_entry;\n    [ idtac |\n      exact (le_0_n (S r)) |\n      unfold lt in H_i_lt_S_r; rewrite <- minus_n_O;\n      exact H_i_lt_S_r ].\n\n  exact (p_rotated_moessner_entry_rank_decompose_Pascal_like_c_eq_0 i r t d).\nQed.\nHint Resolve p_create_triangle_vertically_rank_decompose_Pascal_like_c_eq_0\n  : long.\n\nCorollary p_create_triangle_vertically_rank_decompose_Pascal_like_c_gt_0 :\n  forall (i j r t d : nat),\n    j <= r ->\n    S i <= r - j ->\n    (nth (S i)\n         (nth (S j)\n              (create_triangle_vertically\n                 (tuple_constant (S (S (S r))) 0)\n                 (Str_prefix (S (S (S r))) (p_monomials t (S r) 0 d)))\n              [])\n         0) =\n\n    (S t) * (nth i\n                 (nth (S j)\n                      (create_triangle_vertically\n                         (tuple_constant (S (S r)) 0)\n                         (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n                      [])\n                   0) +\n    (nth (S i)\n         (nth j\n              (create_triangle_vertically\n                 (tuple_constant (S (S r)) 0)\n                 (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n              [])\n         0).\nProof.\n  intros i j r t d H_j_le_r H_S_i_le_r_minus_j.\n\n  rewrite -> correctness_of_p_rotated_moessner_entry;\n    [ idtac |\n      apply le_S; apply le_n_S; exact H_j_le_r |\n      rewrite <- minus_Sn_m; [ idtac | apply le_n_S; exact H_j_le_r ];\n      unfold minus; fold minus;\n      apply le_n_S; exact H_S_i_le_r_minus_j ].\n\n  rewrite -> correctness_of_p_rotated_moessner_entry;\n    [ idtac |\n      apply le_n_S; exact H_j_le_r |\n      unfold minus; fold minus; exact H_S_i_le_r_minus_j ].\n\n  rewrite -> correctness_of_p_rotated_moessner_entry;\n    [ idtac |\n      apply le_S; exact H_j_le_r |\n      rewrite <- minus_Sn_m; [ idtac | exact H_j_le_r ];\n      apply le_n_S; exact H_S_i_le_r_minus_j ].\n\n  exact (p_rotated_moessner_entry_rank_decompose_Pascal_like_c_gt_0 i j r t d).\nQed.\nHint Rewrite p_create_triangle_vertically_rank_decompose_Pascal_like_c_gt_0\n  : long.\n\n(** * Equivalence of Characteristic function and P_Monomial *)\n\nLemma p_rotated_moessner_entry_constrained_negative_Pascal_s_rule :\n  forall (n' k' t d : nat),\n    S k' <= n' ->\n    p_rotated_moessner_entry n' k' (n' - k') t d +\n    p_rotated_moessner_entry n' (S k') (n' - S k') t d =\n    p_rotated_moessner_entry n' (S k') (n' - k') t d.\nProof.\n  induction n' as [ | n'' IH_n'' ].\n\n  Case \"n' = 0\".\n  intros k' t d H_absurd.\n  inversion H_absurd.\n\n  Case \"n' = S n''\".\n  induction k' as [ | k'' IH_k'' ].\n\n  SCase \"k' = 0\".\n  intros t H d.\n  unfold minus; fold minus.\n  rewrite <- minus_n_O.\n  rewrite -> p_rotated_moessner_entry_Pascal_s_rule.\n  reflexivity.\n\n  SCase \"k' = S k''\".\n  intros t d H.\n  rewrite <- (minus_Sn_m);\n    [ idtac | apply gt_S_le; unfold gt, lt; exact H ].\n  rewrite ->3 p_rotated_moessner_entry_Pascal_s_rule.\n  unfold minus;fold minus.\n  reflexivity.\nQed.\n\n(* {P_ROTATED_MOESSNER_ENTRY_EQ_P_MONOMIAL} *)\nTheorem p_rotated_moessner_entry_eq_p_monomial :\n  forall (n k t d : nat),\n    k <= n ->\n    p_rotated_moessner_entry n k (n - k) t d =\n    p_monomial (S t) n k d.\n(* {END} *)\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros k t d H.\n  inversion_clear H.\n  rewrite <- minus_n_O.\n  rewrite -> p_rotated_moessner_entry_r_eq_0_implies_d.\n  rewrite -> p_monomial_k_eq_0_implies_d.\n  reflexivity.\n\n  Case \"n = S n'\".\n  induction k as [ | k' IH_k' ].\n\n  SCase \"k = 0\".\n  intros t d _.\n  rewrite <- minus_n_O.\n  rewrite -> p_rotated_moessner_entry_r_eq_0_implies_d.\n  rewrite -> p_monomial_k_eq_0_implies_d.\n  reflexivity.\n\n  SCase \"k = S k'\".\n  intros t d H_S_k'_le_S_n'.\n  inversion_clear H_S_k'_le_S_n'.\n\n  SSCase \"k' = n'\".\n  rewrite -> minus_diag.\n  rewrite -> p_rotated_moessner_entry_rank_decompose_by_row.\n  specialize (IH_n' n' t d).\n  rewrite -> minus_diag in IH_n'.\n  rewrite -> IH_n'; [ idtac | apply le_n ].\n  rewrite -> p_rotated_moessner_entry_c_eq_0.\n  rewrite -> IH_n'; [ idtac | apply le_n ].\n  rewrite -> p_monomial_Pascal_s_rule.\n  unfold mult; fold mult.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n  rewrite -> (p_monomial_n_lt_k_implies_0 t n' (S n') d);\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  rewrite -> (p_monomial_n_lt_k_implies_0 (S t) n' (S n') d);\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  reflexivity.\n\n  SSCase \"S k' <= n'\".\n  subst; rename H into H_S_k'_le_n'.\n  rewrite <- minus_Sn_m;\n    [ idtac | apply H_S_k'_le_n' ].\n  rewrite -> p_rotated_moessner_entry_rank_decompose_by_row.\n  rewrite -> p_monomial_Pascal_s_rule.\n  rewrite <- (IH_n' (S k') t d);\n    [ idtac | apply H_S_k'_le_n' ].\n  rewrite -> minus_Sn_m;\n    [ idtac | apply H_S_k'_le_n' ].\n  rewrite -> NPeano.Nat.sub_succ.\n  rewrite <- (IH_n' k' t d);\n    [ idtac | apply lt_le_weak; unfold lt; exact H_S_k'_le_n' ].\n  unfold mult; fold mult.\n  symmetry.\n  rewrite -> plus_comm.\n  rewrite <- plus_assoc.\n\n  rewrite <- (plus_permute\n                (t * p_rotated_moessner_entry n' k' (n' - k') t d) _).\n  f_equal.\n\n  rewrite -> p_rotated_moessner_entry_constrained_negative_Pascal_s_rule;\n    [ idtac | apply H_S_k'_le_n' ].\n  reflexivity.\nQed.\nHint Rewrite p_rotated_moessner_entry_eq_p_monomial : long.\n\n(* {P_MOESSNER_ENTRY_EQ_P_MONOMIAL} *)\nCorollary p_moessner_entry_eq_p_monomial :\n  forall (n k t d : nat),\n    k <= n ->\n    p_moessner_entry n n (n - k) t d =\n    p_monomial (S t) n k d.\n(* {END} *)\nProof.\n  intros n k t d H.\n  assert (H_helper:\n            p_moessner_entry n n (n - k) t d =\n            p_moessner_entry n (n - k + k) (n - k) t d).\n    rewrite -> (NPeano.Nat.sub_add k n H).\n    reflexivity.\n\n  rewrite -> H_helper; clear H_helper.\n  rewrite <- unfold_p_rotated_moessner_entry.\n  rewrite -> (p_rotated_moessner_entry_eq_p_monomial n k t d H).\n  reflexivity.\nQed.\nHint Rewrite p_moessner_entry_eq_p_monomial : long.\n\n(** ** The p_Binomial Theorem *)\n\nTheorem p_Binomial_theorem :\n  forall (t n d : nat),\n    d * (S t) ^ n = Str_nth (S n) (stream_partial_sums (p_monomials t n 0 d)).\nProof.\n  intros t n d.\n  rewrite -> stream_partial_sums_p_monomials_bisim_p_monomials_sum.\n  rewrite -> Str_nth_p_monomials_sum_eq_p_rotated_moessner_entry;\n    rewrite -> plus_0_r.\n  rewrite -> p_rotated_moessner_entry_c_eq_0.\n  rewrite -> p_monomial_n_lt_k_implies_0;\n    [ rewrite -> plus_0_l | unfold lt; apply le_n ].\n  rewrite <- (minus_diag n);\n    rewrite -> p_rotated_moessner_entry_eq_p_monomial;\n    [ idtac | apply le_n ].\n  rewrite -> p_monomial_n_eq_k_implies_power.\n  reflexivity.\nQed.\nHint Rewrite p_Binomial_theorem : long.\n\n(** * Describing the diagonal of a triangle *)\n\n(** Proof that [read_diagonal] of [create_triangle] starting from\n  [p_monomials] yields a row [p_moessner_entry] *)\n\n(* {HYPOTENUSE_CREATE_TRIANGLE_VERTICALLY_P_ROTATED_MOESSNER_ENTRIES} *)\nTheorem hypotenuse_create_triangle_vertically_p_rotated_moessner_entries :\n  forall (l r c t d : nat),\n    hypotenuse\n      (create_triangle_vertically\n         (tuple_constant (S l) 0)\n         (Str_prefix (S l) (p_rotated_moessner_entries r 0 c t d))) =\n    Str_prefix l (p_moessner_entries r (c + l) (S c) t d).\n(* {END} *)\nProof.\n  induction l as [ | l' IH_l' ].\n\n  Case \"l = 0\".\n  intros r c t d.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite -> unfold_tuple_constant_induction_case.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite -> unfold_create_triangle_vertically_base_case_x_nil.\n  rewrite -> unfold_hypotenuse_base_case.\n  reflexivity.\n\n  Case \"l = S l'\".\n  intros r c t d.\n  rewrite ->2 unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite -> unfold_create_triangle_vertically_induction_case.\n  rewrite <-2 unfold_Str_prefix_induction_case.\n  rewrite <- unfold_tuple_constant_induction_case.\n  rewrite -> unfold_hypotenuse_induction_case.\n\n  symmetry.\n\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> p_moessner_entries_initial_value.\n  rewrite -> p_moessner_entries_stream_derivative.\n  rewrite -> make_tuple_p_rotated_moessner_entries.\n  f_equal.\n\n  SCase \"head\".\n  rewrite -> last_of_p_rotated_moessner_entries_to_binomial.\n  rewrite <- plus_n_Sm, -> plus_Sn_m.\n  reflexivity.\n\n  SCase \"tail\".\n  rewrite -> (IH_l' r (S c) t d).\n  rewrite <- plus_n_Sm, -> plus_Sn_m.\n  reflexivity.\nQed.\nHint Rewrite hypotenuse_create_triangle_vertically_p_rotated_moessner_entries\n  : long.\n\n(* {HYPOTENUSE_CREATE_TRIANGLE_VERTICALLY_MOESSNER_ENTRIES_P_MONOMIALS} *)\nLemma hypotenuse_create_triangle_vertically_moessner_entries_p_monomials :\n  forall (l r t d : nat),\n    hypotenuse\n      (create_triangle_vertically\n         (tuple_constant (S (S l)) 0)\n         (Str_prefix (S (S l)) (p_monomials t r 0 d))) =\n    (Str_prefix (S l) (p_moessner_entries r l 0 t d)).\n(* {END} *)\nProof.\n  intros l r t d.\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite ->2 unfold_Str_prefix_induction_case.\n  rewrite -> unfold_create_triangle_vertically_induction_case.\n  rewrite <- unfold_tuple_constant_induction_case.\n  rewrite <-2 unfold_Str_prefix_induction_case.\n  rewrite -> p_monomials_and_make_tuple.\n  rewrite <- p_rotated_moessner_entries_bisim_p_monomials_sum.\n  rewrite -> unfold_hypotenuse_induction_case.\n  symmetry.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> p_moessner_entries_initial_value.\n  rewrite -> p_moessner_entries_stream_derivative.\n  f_equal.\n\n  Case \"head\".\n  rewrite -> (length_implies_last_index l);\n    [ idtac | rewrite -> Str_prefix_length; reflexivity ].\n  rewrite -> nth_and_Str_nth;\n    [ idtac | unfold lt; apply le_n ].\n  rewrite -> Str_nth_p_rotated_moessner_entries.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"tail\".\n  symmetry.\n  rewrite -> hypotenuse_create_triangle_vertically_p_rotated_moessner_entries.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Rewrite hypotenuse_create_triangle_vertically_moessner_entries_p_monomials\n  : long.\n\n(** P_Monomials List\n\n  The list of p_monomials of the binomial expansion.\n\n  *** Definition *)\n\n(* {P_MONOMIALS_LIST} *)\nFixpoint p_monomials_list (t r n d : nat) : list nat :=\n  match n with\n    | 0 => [p_monomial t r 0 d]\n    | S n' => (p_monomial t r (S n') d) :: (p_monomials_list t r n' d)\n  end.\n(* {END} *)\nHint Unfold p_monomials_list : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_monomials_list_base_case :\n  forall (t r d : nat),\n    p_monomials_list t r 0 d = [p_monomial t r 0 d].\nProof.\n  intros t r d.\n  unfold p_monomials_list.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_monomials_list_base_case : long.\n\nLemma unfold_p_monomials_list_induction_case :\n  forall (t r n' d : nat),\n    p_monomials_list t r (S n') d =\n    (p_monomial t r (S n') d) :: (p_monomials_list t r n' d).\nProof.\n  intros t r n' d.\n  unfold p_monomials_list; fold p_monomials_list.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_monomials_list_induction_case : long.\n\n(** *** Properties *)\n\nLemma rev_p_monomials_list_eq_p_monomials :\n  forall (n r t d : nat),\n    p_monomials_list t r n d =\n    rev (Str_prefix (S n) (p_monomials t r 0 d)).\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros r t d.\n  rewrite -> unfold_p_monomials_list_base_case.\n\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> unfold_Str_prefix_base_case.\n  rewrite -> p_monomials_initial_value.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> unfold_rev_base_case.\n  rewrite -> app_nil_l.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intros r t d.\n  rewrite -> unfold_p_monomials_list_induction_case.\n  rewrite -> (IH_n' r t d).\n  symmetry.\n\n  rewrite -> rev_Str_prefix_p_monomials.\n  rewrite -> plus_0_l.\n  reflexivity.\nQed.\nHint Rewrite rev_p_monomials_list_eq_p_monomials : long.\n\nLemma p_monomials_list_eq_Str_prefix_p_moessner_entries :\n  forall (l n t' d : nat),\n    l <= n ->\n    Str_prefix (S l) (p_moessner_entries n n (n - l) t' d) =\n    p_monomials_list (S t') n l d.\nProof.\n  induction l as [ | l' IH_l' ].\n\n  Case \"l = 0\".\n  intros n t' d H_0_le_n.\n  rewrite <- minus_n_O.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> unfold_Str_prefix_base_case.\n  rewrite -> p_moessner_entries_initial_value.\n  rewrite -> p_moessner_entry_n_eq_k_implies_d.\n\n  rewrite -> unfold_p_monomials_list_base_case.\n  rewrite -> unfold_p_monomial.\n  rewrite -> unfold_binomial_coefficient_base_case_n_0.\n  rewrite -> unfold_power_base_case.\n  rewrite ->2 mult_1_r.\n  reflexivity.\n\n  Case \"l = S l'\".\n  intros n t' d H_S_l'_le_n.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> p_moessner_entries_stream_derivative.\n  rewrite -> minus_Sn_m;\n    [ idtac | apply H_S_l'_le_n ].\n  rewrite -> NPeano.Nat.sub_succ.\n  rewrite -> IH_l';\n    [ idtac | apply lt_le_weak; unfold lt; exact H_S_l'_le_n ].\n  rewrite -> p_moessner_entries_initial_value.\n  rewrite -> unfold_p_monomials_list_induction_case.\n  f_equal.\n  rewrite -> p_moessner_entry_eq_p_monomial;\n    [ reflexivity | exact H_S_l'_le_n ].\nQed.\nHint Rewrite p_monomials_list_eq_Str_prefix_p_moessner_entries : long.\n\nLemma rev_Str_prefix_p_moessner_entries_eq_p_monomials :\n  forall (r t' d : nat),\n    Str_prefix (S r) (p_moessner_entries r r 0 t' d) =\n    rev (Str_prefix (S r) (p_monomials (S t') r 0 d)).\nProof.\n  intros r t' d.\n  rewrite <- (minus_diag r).\n  rewrite -> p_monomials_list_eq_Str_prefix_p_moessner_entries;\n    [ idtac | apply le_n ].\n  rewrite -> rev_p_monomials_list_eq_p_monomials.\n  rewrite -> minus_diag.\n  reflexivity.\nQed.\nHint Rewrite rev_Str_prefix_p_moessner_entries_eq_p_monomials : long.\n\nLemma pad_p_monomials :\n  forall (r t n d : nat),\n    Str_prefix (S (S r)) (p_monomials (S t) r n d) =\n    Str_prefix (S r) (p_monomials (S t) r n d) ++ [0].\nProof.\n  intros r t n d.\n  rewrite -> Str_prefix_split_with_Str_nth.\n  unfold Str_nth.\n  rewrite -> p_monomials_tail_of_0s.\n  rewrite -> stream_constant_initial_value.\n  reflexivity.\nQed.\nHint Rewrite pad_p_monomials : long.\n\n(* {HYPOTENUSE_CREATE_TRIANGLE_VERTICALLY_P_MONOMIALS} *)\nCorollary hypotenuse_create_triangle_vertically_p_monomials :\n  forall (r t d : nat),\n    hypotenuse\n      (create_triangle_vertically\n         (tuple_constant (S (S r)) 0)\n         (Str_prefix (S (S r)) (p_monomials t r 0 d))) =\n    (rev (Str_prefix (S r) (p_monomials (S t) r 0 d))).\n(* {END} *)\nProof.\n  intros r t d.\n  rewrite -> hypotenuse_create_triangle_vertically_moessner_entries_p_monomials.\n  rewrite -> rev_Str_prefix_p_moessner_entries_eq_p_monomials.\n  reflexivity.\nQed.\nHint Rewrite hypotenuse_create_triangle_vertically_p_monomials : long.\n\n(** * P Long's weak theorem *)\n\n(* {NTH_TRIANGLE_CREATE_TRIANGLES_VERTICALLY_P_MONOMIALS} *)\nTheorem nth_triangle_create_triangles_vertically_p_monomials :\n  forall (n r t d : nat),\n    nth n\n      (create_triangles_vertically n\n         (tuple_constant (S (S r)) 0)\n         (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n      [] =\n    (create_triangle_vertically\n       (tuple_constant (S (S r)) 0)\n       (Str_prefix (S (S r)) (p_monomials (n + t) r 0 d))).\n(* {END} *)\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros r t d.\n  rewrite -> unfold_create_triangles_vertically_base_case.\n  rewrite -> unfold_nth_base_case_cons.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intros r t d.\n  rewrite -> unfold_create_triangles_vertically_induction_case.\n  rewrite -> hypotenuse_create_triangle_vertically_p_monomials.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> rev_involutive.\n  rewrite <- pad_p_monomials.\n  rewrite -> unfold_nth_induction_case_cons.\n  rewrite -> (IH_n' r (S t)).\n  rewrite <- plus_n_Sm, -> plus_Sn_m.\n  reflexivity.\nQed.\nHint Rewrite nth_triangle_create_triangles_vertically_p_monomials : long.\n\nCorollary hypotenuse_of_last_triangle_create_triangles_vertically_p_monomials :\n  forall (n r t d : nat),\n    hypotenuse\n      (nth n\n           (create_triangles_vertically\n              n\n              (tuple_constant (S (S r)) 0)\n              (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n           []) =\n    p_monomials_list (S (n + t)) r r d.\nProof.\n  intros n r t d.\n  rewrite -> nth_triangle_create_triangles_vertically_p_monomials.\n  rewrite -> hypotenuse_create_triangle_vertically_p_monomials.\n  rewrite <- rev_p_monomials_list_eq_p_monomials.\n  reflexivity.\nQed.\nHint Rewrite hypotenuse_of_last_triangle_create_triangles_vertically_p_monomials\n  : long.\n\nCorollary bottom_element_of_nth_triangle_create_triangles_vertically_p_monomials :\n  forall (n r t d : nat),\n    nth 0\n        (hypotenuse\n           (nth n\n                (create_triangles_vertically\n                   n\n                   (tuple_constant (S (S r)) 0)\n                   (Str_prefix (S (S r)) (p_monomials t r 0 d)))\n                []))\n        1 = p_monomial (S (n + t)) r r d.\nProof.\n  intros n r t d.\n  rewrite -> hypotenuse_of_last_triangle_create_triangles_vertically_p_monomials.\n  case r as [ | r' ].\n\n  Case \"r = 0\".\n  rewrite -> unfold_p_monomials_list_base_case.\n  rewrite -> unfold_nth_base_case_cons.\n  reflexivity.\n\n  Case \"r = S r'\".\n  rewrite -> unfold_p_monomials_list_induction_case.\n  rewrite -> unfold_nth_base_case_cons.\n  reflexivity.\nQed.\nHint Rewrite bottom_element_of_nth_triangle_create_triangles_vertically_p_monomials\n  : long.\n\n(* {BOTTOM_ELEMENT_OF_NTH_TRIANGLE_P_MONOMIALS_IS_POWER} *)\nCorollary bottom_element_of_nth_triangle_p_monomials_is_power :\n  forall (n r d : nat),\n    nth 0\n        (hypotenuse\n           (nth n\n                (create_triangles_vertically\n                   n\n                   (tuple_constant (S (S r)) 0)\n                   (Str_prefix (S (S r)) (p_monomials 0 r 0 d)))\n                []))\n        1 = d * (S n) ^ r.\n(* {END} *)\nProof.\n  intros n r d.\n  rewrite -> bottom_element_of_nth_triangle_create_triangles_vertically_p_monomials.\n  rewrite -> p_monomial_n_eq_k_implies_power.\n  rewrite -> plus_0_r.\n  reflexivity.\nQed.\nHint Rewrite bottom_element_of_nth_triangle_p_monomials_is_power : long.\n\n(** ** Moessner Stream\n\n  *** Definition *)\n\n(* {P_MOESSNER_STREAM} *)\nCoFixpoint p_moessner_stream (n r d : nat) : Stream nat :=\n  (nth 0 (hypotenuse\n            (nth n\n                 (create_triangles_vertically\n                    n\n                    (tuple_constant (S (S r)) 0)\n                    (Str_prefix (S (S r)) (p_monomials 0 r 0 d)))\n                 [])) 1)\n    ::: (p_moessner_stream (S n) r d).\n(* {END} *)\nHint Unfold p_moessner_stream : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_p_moessner_stream :\n  forall (n r d : nat),\n    (p_moessner_stream n r d) =\n    (nth 0 (hypotenuse\n              (nth n\n                   (create_triangles_vertically\n                      n\n                      (tuple_constant (S (S r)) 0)\n                      (Str_prefix (S (S r)) (p_monomials 0 r 0 d)))\n                   [])) 1)\n      ::: (p_moessner_stream (S n) r d).\nProof.\n  intros n r d.\n  rewrite -> (unfold_Stream (p_moessner_stream n r d)).\n  unfold p_moessner_stream; fold p_moessner_stream.\n  reflexivity.\nQed.\nHint Rewrite unfold_p_moessner_stream : long.\n\nLemma p_moessner_stream_initial_value :\n  forall (n r d : nat),\n    (p_moessner_stream n r d)(0) =\n    (nth 0 (hypotenuse\n              (nth n\n                   (create_triangles_vertically\n                      n\n                      (tuple_constant (S (S r)) 0)\n                      (Str_prefix (S (S r)) (p_monomials 0 r 0 d)))\n                   [])) 1).\nProof.\n  intros n r d.\n  rewrite -> initial_value.\n  rewrite -> unfold_p_moessner_stream.\n  reflexivity.\nQed.\nHint Rewrite p_moessner_stream_initial_value : long.\n\nLemma p_moessner_stream_stream_derivative :\n  forall (n r d : nat),\n    (p_moessner_stream n r d)` = (p_moessner_stream (S n) r d).\nProof.\n  intros n r d.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_p_moessner_stream.\n  reflexivity.\nQed.\nHint Rewrite p_moessner_stream_stream_derivative : long.\n\n(** ** Long's weak theorem *)\n\n(* {LONG_S_WEAK_THEOREM} *)\nTheorem Long_s_weak_theorem :\n  forall (b e d : nat),\n    p_moessner_stream b e d ~ d n* successive_powers b e.\n(* {END} *)\nProof.\n  pcofix coIH.\n  intros b e d.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> p_moessner_stream_initial_value.\n  rewrite -> bottom_element_of_nth_triangle_p_monomials_is_power.\n  rewrite -> stream_scalar_multiplication_initial_value.\n  rewrite -> successive_powers_initial_value.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> p_moessner_stream_stream_derivative.\n  rewrite -> stream_scalar_multiplication_stream_derivative.\n  rewrite -> successive_powers_stream_derivative.\n  exact (coIH (S b) e d).\nQed.\nHint Rewrite Long_s_weak_theorem : long.\n\n(** * Long's idealized theorem *)\n\n(* If we look at how we can decompose a Long-like sieve,\n\n     d     d      d       d      d     d        d       d       d      d     d     d\n c c+d  c+2d   c+3d    c+4d   c+5d           c+6d    c+7d    c+8d   c+9d c+10d\n 0 c+d 2c+3d  3c+6d  4c+10d                5c+16d  6c+23d  7c+31d 8c+40d\n 0 c+d 3c+4d 6c+10d                       11c+26d 17c+49d 24c+80d\n 0 c+d 4c+5d                              15c+31d 32c+80d\n 0 c+d                                    16c+32d\n 0\n\n  into a sum of two sieves, where we also generalize the stream of [d]s to be a\n  [d] followed by 0s\n\n      0   0   0   0   0   0        0   0   0   0   0   0\n\n  c   c   c   c   c   c            c   c   c   c   c\n  0   c  2c  3c  4c               5c  6c  7c  8c\n  0   c  3c  6c                  11c 17c 24c\n  0   c  4c                      15c 32c\n  0   c                          16c\n  0\n\n  +\n\n      d   0   0   0   0   0   0        0   0   0   0   0   0   0\n\n  0   d   d   d   d   d   d            d   d   d   d   d   d\n  0   d  2d  3d  4d  5d               6d  7d  8d  9d 10d\n  0   d  3d  6d 10d                  16d 23d 31d 40d\n  0   d  4d 10d                      26d 49d 80d\n  0   d  5d                          31d 80d\n  0   d                              32d\n  0\n\n  then we can use the symmetric property to flip the two seed tuples for the [d]\n  sieve which gives us\n\n      0   0   0   0   0   0        0   0   0   0   0   0\n\n  c   c   c   c   c   c            c   c   c   c   c\n  0   c  2c  3c  4c               5c  6c  7c  8c\n  0   c  3c  6c                  11c 17c 24c\n  0   c  4c                      15c 32c\n  0   c                          16c\n  0\n\n  +\n\n      0   0   0   0   0   0   0        0   0   0   0   0   0   0\n\n  d   d   d   d   d   d   d            d   d   d   d   d   d\n  0   d  2d  3d  4d  5d               6d  7d  8d  9d 10d\n  0   d  3d  6d 10d                  16d 23d 31d 40d\n  0   d  4d 10d                      26d 49d 80d\n  0   d  5d                          31d 80d\n  0   d                              32d\n  0\n\n  which we can then recompose into a Long-like sieve, if we want:\n\n     0     0      0       0      0     0     0             0       0       0      0     0     0      0\n d   d     d      d       d      d     d           d       d       d       d      d     d     d\n c c+d  c+2d   c+3d    c+4d   c+5d             c+ 5d    c+6d    c+7d    c+8d   c+9d c+10d\n 0 c+d 2c+3d  3c+6d  4c+10d                   4c+10d  5c+16d  6c+23d  7c+31d 8c+40d\n 0 c+d 3c+4d 6c+10d                           6c+10d 11c+26d 17c+49d 24c+80d\n 0 c+d 4c+5d                                  4c+ 5d 15c+31d 32c+80d\n 0 c+d                                         c+  d 16c+32d\n 0                                                 0\n\n*)\n\n(** ** Distributivity of sum in seed tuples for Moessner triangles *)\n\n(** *** Helper lemmas *)\n\n(* {LENGTH_OF_LIST_SUM} *)\nLemma length_of_list_sum :\n  forall (xs ys : list nat),\n    length (xs l+ ys) = max (length xs) (length ys).\n(* {END} *)\nProof.\n  induction xs as [ | x xs' IH_xs' ].\n\n  Case \"xs = []\".\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  rewrite -> unfold_list_sum_base_case_nil.\n  rewrite -> unfold_length_base_case.\n  unfold max.\n  reflexivity.\n\n  SCase \"ys = y :: ys'\".\n  rewrite -> unfold_list_sum_base_case_cons.\n  rewrite -> unfold_length_base_case.\n  unfold max.\n  reflexivity.\n\n  Case \"xs = x :: xs'\".\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  rewrite -> unfold_list_sum_induction_case_nil.\n  rewrite -> unfold_length_base_case.\n  rewrite -> Max.max_0_r.\n  reflexivity.\n\n  SCase \"ys = y :: ys'\".\n  rewrite -> unfold_list_sum_induction_case_cons.\n  rewrite -> unfold_length_induction_case.\n  rewrite -> (IH_xs' ys').\n  rewrite ->2 unfold_length_induction_case.\n  unfold max; fold max.\n  reflexivity.\nQed.\nHint Rewrite length_of_list_sum : long.\n\n(* {NTH_MAKE_TUPLE_LIST_SUM} *)\nLemma nth_make_tuple_list_sum :\n  forall (n r i j : nat) (sigma tau : Stream nat),\n    nth n (make_tuple (Str_prefix r sigma) i) 0 +\n    nth n (make_tuple (Str_prefix r tau) j) 0 =\n    nth n ((make_tuple (Str_prefix r sigma) i) l+\n           (make_tuple (Str_prefix r tau) j)) 0.\n(* {END} *)\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  case r as [ | r' ].\n\n  SCase \"r = 0\".\n  intros i j sigma tau.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite ->2 unfold_make_tuple_base_case_nil.\n  rewrite -> unfold_list_sum_base_case_nil.\n  rewrite -> unfold_nth_base_case_nil.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  SCase \"r = S r'\".\n  case r' as [ | r'' ].\n\n  SSCase \"r' = 0\".\n  intros i j sigma tau.\n  rewrite ->2 unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite ->2 unfold_make_tuple_base_case_x_nil.\n  rewrite -> unfold_list_sum_base_case_nil.\n  rewrite -> unfold_nth_base_case_nil.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  SSCase \"r' = S r''\".\n  intros i j sigma tau.\n  rewrite ->4 unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_make_tuple_induction_case.\n  rewrite ->2 unfold_nth_base_case_cons.\n  rewrite -> unfold_list_sum_induction_case_cons.\n  rewrite -> unfold_nth_base_case_cons.\n  reflexivity.\n\n  Case \"n = S n'\".\n  case r as [ | r' ].\n\n  SCase \"r = 0\".\n  intros i j sigma tau.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite ->2 unfold_make_tuple_base_case_nil.\n  rewrite -> unfold_list_sum_base_case_nil.\n  rewrite -> unfold_nth_induction_case_nil.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  SCase \"r = S r'\".\n  case r' as [ | r'' ].\n\n  SSCase \"r' = 0\".\n  intros i j sigma tau.\n  rewrite ->2 unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite ->2 unfold_make_tuple_base_case_x_nil.\n  rewrite -> unfold_list_sum_base_case_nil.\n  rewrite -> unfold_nth_induction_case_nil.\n  rewrite -> plus_0_r.\n  reflexivity.\n\n  SSCase \"r' = S r''\".\n  intros i j sigma tau.\n  rewrite ->4 unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_make_tuple_induction_case.\n  rewrite ->2 unfold_nth_induction_case_cons.\n  rewrite <-2 unfold_Str_prefix_induction_case.\n  rewrite -> (IH_n' (S r'') (sigma(0) + i) (tau(0) + j)).\n  rewrite -> unfold_list_sum_induction_case_cons.\n  rewrite -> unfold_nth_induction_case_cons.\n  reflexivity.\nQed.\nHint Rewrite nth_make_tuple_list_sum : long.\n\n(* {HYPOTENUSE_CREATE_TRIANGLE_VERTICALLY_LIST_SUM} *)\nTheorem hypotenuse_create_triangle_vertically_list_sum :\n  forall (r : nat) (sigma tau : Stream nat),\n    hypotenuse\n      (create_triangle_vertically\n         (tuple_constant r 0)\n         ((Str_prefix r sigma) l+\n          (Str_prefix r tau))) =\n    (hypotenuse\n       (create_triangle_vertically\n          (tuple_constant r 0)\n          (Str_prefix r sigma))) l+\n    (hypotenuse\n       (create_triangle_vertically\n          (tuple_constant r 0)\n          (Str_prefix r tau))).\n(* {END} *)\nProof.\n  induction r as [ | r' IH_r' ].\n\n  Case \"r = 0\".\n  intros sigma tau.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite -> unfold_list_sum_base_case_nil.\n  rewrite -> unfold_create_triangle_vertically_base_case_nil.\n  rewrite -> unfold_hypotenuse_base_case.\n  rewrite -> unfold_list_sum_base_case_nil.\n  reflexivity.\n\n  Case \"r = S r'\".\n  case r' as [ | r'' ].\n\n  SCase \"r' = 0\".\n  intros sigma tau.\n  rewrite -> unfold_tuple_constant_induction_case.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite ->2 unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite -> unfold_list_sum_induction_case_cons.\n  rewrite -> unfold_list_sum_base_case_nil.\n  rewrite ->3 unfold_create_triangle_vertically_base_case_x_nil.\n  rewrite -> unfold_hypotenuse_base_case.\n  rewrite -> unfold_list_sum_base_case_nil.\n  reflexivity.\n\n  SCase \"r' = S r'\".\n  intros sigma tau.\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite -> unfold_create_triangle_vertically_induction_case.\n  rewrite -> unfold_hypotenuse_induction_case.\n  rewrite <- unfold_tuple_constant_induction_case.\n  rewrite -> unfold_list_sum.\n  rewrite <- Str_prefix_stream_zip.\n  rewrite -> equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  rewrite -> stream_partial_sums_acc_sum.\n  unfold stream_sum.\n  rewrite -> Str_prefix_stream_zip.\n  rewrite <- unfold_list_sum.\n  rewrite -> (IH_r' (stream_partial_sums_acc 0 sigma) (stream_partial_sums_acc 0 tau)).\n  symmetry.\n\n  rewrite -> unfold_tuple_constant_induction_case.\n  rewrite ->2 unfold_create_triangle_vertically_induction_case.\n  rewrite <- unfold_tuple_constant_induction_case.\n  rewrite ->2 unfold_hypotenuse_induction_case.\n  rewrite -> unfold_list_sum_induction_case_cons.\n  rewrite <-2 equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  f_equal.\n\n  (*\n  (* {LAST_MAKE_TUPLE_EXAMPLE} *)\n    last (make_tuple (Str_prefix (S (S r'')) sigma) 0) 0 +\n    last (make_tuple (Str_prefix (S (S r'')) tau) 0) 0 =\n    last ((make_tuple (Str_prefix (S (S r'')) sigma) 0) l+\n          (make_tuple (Str_prefix (S (S r'')) tau) 0)) 0\n  (* {END} *)\n  *)\n\n  rewrite -> (length_implies_last_index r'');\n    [ idtac | rewrite ->2 unfold_Str_prefix_induction_case;\n              rewrite -> unfold_make_tuple_induction_case;\n              rewrite -> unfold_length_induction_case;\n              rewrite -> S_length_make_tuple;\n              rewrite <- unfold_Str_prefix_induction_case;\n              rewrite -> Str_prefix_length;\n              reflexivity ].\n\n  rewrite -> (length_implies_last_index r'');\n    [ idtac | rewrite ->2 unfold_Str_prefix_induction_case;\n              rewrite -> unfold_make_tuple_induction_case;\n              rewrite -> unfold_length_induction_case;\n              rewrite -> S_length_make_tuple;\n              rewrite <- unfold_Str_prefix_induction_case;\n              rewrite -> Str_prefix_length;\n              reflexivity ].\n\n  rewrite -> nth_make_tuple_list_sum.\n  rewrite -> (length_implies_last_index r'');\n    [ idtac | rewrite -> length_of_list_sum;\n              rewrite ->4 unfold_Str_prefix_induction_case;\n              rewrite ->2 unfold_make_tuple_induction_case;\n              rewrite ->2 unfold_length_induction_case;\n              rewrite ->2 S_length_make_tuple;\n              rewrite ->2 unfold_length_induction_case;\n              rewrite ->2 Str_prefix_length;\n              rewrite -> Max.max_idempotent;\n              reflexivity ].\n\n  reflexivity.\nQed.\nHint Rewrite hypotenuse_create_triangle_vertically_list_sum : long.\n\n(* {HYPOTENUSE_CREATE_TRIANGLE_VERTICALLY_P_MONOMIALS_LIST_SUM} *)\nCorollary hypotenuse_create_triangle_vertically_p_monomials_list_sum :\n  forall (r t d c : nat),\n    hypotenuse\n      (create_triangle_vertically\n         (tuple_constant (S (S (S r))) 0)\n         ((Str_prefix (S (S (S r))) (0 ::: (p_monomials t r 0 c))) l+\n          (Str_prefix (S (S (S r))) (p_monomials t (S r) 0 d)))) =\n    (hypotenuse\n       (create_triangle_vertically\n          (tuple_constant (S (S (S r))) 0)\n          (Str_prefix (S (S (S r))) (0 ::: (p_monomials t r 0 c))))) l+\n    (hypotenuse\n       (create_triangle_vertically\n          (tuple_constant (S (S (S r))) 0)\n          (Str_prefix (S (S (S r))) (p_monomials t (S r) 0 d)))).\n(* {END} *)\nProof.\n  intros r t d c.\n  exact (hypotenuse_create_triangle_vertically_list_sum\n           (S (S (S r)))\n           (0 ::: p_monomials t r 0 c)\n           (p_monomials t (S r) 0 d)).\nQed.\nHint Rewrite hypotenuse_create_triangle_vertically_p_monomials_list_sum\n  : long.\n\n(** ** Distributivity of list sum for the [n]th Moessner triangle *)\n\n(* {HYPOTENUSE_CREATE_TRIANGLE_VERTICALLY_REMOVE_PADDING} *)\nLemma hypotenuse_create_triangle_vertically_remove_padding :\n  forall (r : nat) (sigma : Stream nat),\n    hypotenuse (create_triangle_vertically\n                  (tuple_constant (S r) 0)\n                  (Str_prefix (S r) (0 ::: sigma))) =\n    hypotenuse (create_triangle_vertically\n                  (tuple_constant (S r) 0)\n                  (Str_prefix r sigma)).\n(* {END} *)\nProof.\n  induction r as [ | r' IH_r' ].\n\n  Case \"r = 0\".\n  intro sigma.\n  rewrite -> unfold_tuple_constant_induction_case.\n  rewrite -> unfold_tuple_constant_base_case.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite -> initial_value.\n  rewrite ->2 unfold_create_triangle_vertically_base_case_x_nil.\n  reflexivity.\n\n  Case \"r = S r'\".\n  intro sigma.\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite ->2 unfold_create_triangle_vertically_induction_case.\n  rewrite <- unfold_tuple_constant_induction_case.\n  rewrite ->2 unfold_hypotenuse_induction_case.\n  f_equal.\n\n  SCase \"hd\".\n  induction r' as [ | r'' IH_r'' ].\n\n  SSCase \"r' = 0\".\n  rewrite ->3 unfold_Str_prefix_induction_case.\n  rewrite ->2 unfold_Str_prefix_base_case.\n  rewrite -> initial_value.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_make_tuple_induction_case.\n  rewrite ->2 unfold_make_tuple_base_case_x_nil.\n  rewrite -> plus_0_r.\n  rewrite -> unfold_last_base_case_cons.\n  rewrite -> unfold_last_base_case_nil.\n  reflexivity.\n\n  SSCase \"r' = S r''\".\n  rewrite ->5 unfold_Str_prefix_induction_case.\n  rewrite ->3 unfold_make_tuple_induction_case.\n  rewrite -> unfold_last_induction_case.\n  rewrite ->2 plus_0_r.\n  rewrite -> stream_derivative.\n  reflexivity.\n\n  SCase \"tl\".\n  rewrite -> equivalence_of_make_tuple_and_stream_partial_sums_acc.\n\n  replace (stream_partial_sums_acc 0 (0 ::: sigma))\n  with (0 ::: (stream_partial_sums_acc 0 sigma));\n    [ idtac | symmetry;\n              rewrite -> unfold_stream_partial_sums_acc;\n              rewrite -> initial_value;\n              rewrite -> plus_0_r;\n              rewrite -> stream_derivative;\n              reflexivity ].\n\n  rewrite -> (IH_r' (stream_partial_sums_acc 0 sigma)).\n  rewrite <- equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  reflexivity.\nQed.\nHint Rewrite hypotenuse_create_triangle_vertically_remove_padding : long.\n\n(* {CREATE_TRIANGLE_VERTICALLY_HORIZONTAL_SEED_TUPLE_PADDING} *)\nLemma create_triangle_vertically_horizontal_seed_tuple_padding :\n  forall (r : nat) (sigma : Stream nat),\n    hypotenuse\n      (create_triangle_vertically\n         (tuple_constant (S (S r)) 0)\n         (Str_prefix (S r) sigma)) =\n    (hypotenuse\n       (create_triangle_vertically\n          (tuple_constant (S r) 0)\n          (Str_prefix (S r) sigma))) ++ [0].\n(* {END} *)\nProof.\n  induction r as [ | r' IH_r' ].\n\n  Case \"r = 0\".\n  intro sigma.\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> unfold_Str_prefix_base_case.\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite -> unfold_create_triangle_vertically_induction_case.\n  rewrite -> unfold_make_tuple_base_case_x_nil.\n  rewrite -> unfold_create_triangle_vertically_base_case_x_nil.\n  rewrite -> unfold_create_triangle_vertically_base_case_x_nil.\n  rewrite -> unfold_hypotenuse_base_case.\n  rewrite -> unfold_hypotenuse_induction_case.\n  rewrite -> unfold_hypotenuse_base_case.\n  rewrite -> app_nil_l.\n  rewrite -> unfold_last_base_case_nil.\n  reflexivity.\n\n  Case \"r = S r'\".\n  intro sigma.\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite -> unfold_create_triangle_vertically_induction_case.\n  rewrite <- unfold_tuple_constant_induction_case.\n  rewrite -> unfold_hypotenuse_induction_case.\n  rewrite -> equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  rewrite -> (IH_r' (stream_partial_sums_acc 0 sigma)).\n  rewrite <- equivalence_of_make_tuple_and_stream_partial_sums_acc.\n  symmetry.\n\n  rewrite ->2 unfold_tuple_constant_induction_case.\n  rewrite -> unfold_create_triangle_vertically_induction_case.\n  rewrite <- unfold_tuple_constant_induction_case.\n  rewrite -> unfold_hypotenuse_induction_case.\n  rewrite -> app_comm_cons.\n  reflexivity.\nQed.\nHint Rewrite create_triangle_vertically_horizontal_seed_tuple_padding : long.\n\n(* {LIST_ZIP_APPEND} *)\nLemma list_zip_append :\n  forall (vs xs ws ys : list nat) (f : nat -> nat -> nat),\n    length vs = length xs ->\n    length ws = length ys ->\n    list_zip f (vs ++ ws) (xs ++ ys) =\n    (list_zip f vs xs) ++ (list_zip f ws ys).\n(* {END} *)\nProof.\n  induction vs as [ | v vs' IH_vs' ].\n\n  Case \"vs = []\".\n  case xs as [ | x xs' ].\n\n  SCase \"xs = []\".\n  intros ws ys f H_length_vs_xs H_length_ws_ys.\n  rewrite ->2 app_nil_l.\n  rewrite -> unfold_list_zip_base_case_nil.\n  rewrite -> app_nil_l.\n  reflexivity.\n\n  SCase \"xs = x :: xs'\".\n  intros ws ys f H_length_vs_xs H_length_ws_ys.\n  inversion H_length_vs_xs.\n\n  Case \"vs = v :: vs'\".\n  case xs as [ | x xs' ].\n\n  SCase \"xs = []\".\n  intros ws ys f H_length_vs_xs H_length_ws_ys.\n  inversion H_length_vs_xs.\n\n  SCase \"xs = x :: xs'\".\n  intros ws ys f H_length_vs_xs H_length_ws_ys.\n  rewrite -> unfold_list_zip_induction_case_cons.\n  rewrite <-3 app_comm_cons.\n  rewrite -> unfold_list_zip_induction_case_cons.\n  f_equal.\n  rewrite -> IH_vs';\n    [ idtac |\n      apply eq_add_S; exact H_length_vs_xs |\n      exact H_length_ws_ys ].\n  reflexivity.\nQed.\nHint Resolve list_zip_append : long.\n\n(* {REV_LIST_ZIP} *)\nLemma rev_list_zip :\n  forall (xs ys : list nat) (f : nat -> nat -> nat),\n    length xs = length ys ->\n    rev (list_zip f xs ys) =\n    (list_zip f (rev xs) (rev ys)).\n(* {END} *)\nProof.\n  induction xs as [ | x xs' IH_xs' ].\n\n  Case \"xs = []\".\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  intros f H_length_xs_ys.\n  rewrite ->2 unfold_rev_base_case.\n  rewrite -> unfold_list_zip_base_case_nil.\n  reflexivity.\n\n  SCase \"ys = y :: ys'\".\n  intros f H_length_xs_ys.\n  inversion H_length_xs_ys.\n\n  Case \"xs = x :: xs'\".\n  case ys as [ | y ys' ].\n\n  SCase \"ys = []\".\n  intros f H_length_xs_ys.\n  inversion H_length_xs_ys.\n\n  SCase \"ys = y :: ys'\".\n  intros f H_length_xs_ys.\n  rewrite -> unfold_list_zip_induction_case_cons.\n  rewrite ->3 unfold_rev_induction_case.\n  rewrite -> IH_xs';\n    [ idtac | apply eq_add_S;\n              exact H_length_xs_ys ].\n  rewrite -> list_zip_append;\n    [ idtac | rewrite ->2 rev_length;\n              apply eq_add_S;\n              exact H_length_xs_ys | rewrite ->2 unfold_length_induction_case;\n                                     rewrite -> unfold_length_base_case;\n                                     reflexivity ].\n  rewrite -> unfold_list_zip_induction_case_cons.\n  rewrite -> unfold_list_zip_base_case_nil.\n  reflexivity.\nQed.\nHint Resolve rev_list_zip : long.\n\n(* {NTH_TRIANGLE_CREATE_TRIANGLES_VERTICALLY_P_MONOMIALS_LIST_SUM} *)\nTheorem nth_triangle_create_triangles_vertically_p_monomials_list_sum :\n  forall (n r t d c : nat),\n    nth n\n      (create_triangles_vertically n\n         (tuple_constant (S (S (S r))) 0)\n         ((Str_prefix (S (S (S r))) (0 ::: (p_monomials t r 0 c))) l+\n          (Str_prefix (S (S (S r))) (p_monomials t (S r) 0 d)))) [] =\n    (create_triangle_vertically\n       (tuple_constant (S (S (S r))) 0)\n       ((Str_prefix (S (S (S r))) (0 ::: (p_monomials (n + t) r 0 c))) l+\n        (Str_prefix (S (S (S r))) (p_monomials (n + t) (S r) 0 d)))).\n(* {END} *)\nProof.\n  induction n as [ | n' IH_n' ].\n\n  Case \"n = 0\".\n  intros r t d c.\n  rewrite -> unfold_create_triangles_vertically_base_case.\n  rewrite -> unfold_nth_base_case_cons.\n  rewrite -> plus_0_l.\n  reflexivity.\n\n  Case \"n = S n'\".\n  intros r t d c.\n  rewrite -> unfold_create_triangles_vertically_induction_case.\n  rewrite -> unfold_nth_induction_case_cons.\n  rewrite -> hypotenuse_create_triangle_vertically_p_monomials_list_sum.\n  rewrite -> hypotenuse_create_triangle_vertically_p_monomials.\n  rewrite -> hypotenuse_create_triangle_vertically_remove_padding.\n  rewrite -> create_triangle_vertically_horizontal_seed_tuple_padding.\n  rewrite -> hypotenuse_create_triangle_vertically_p_monomials.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> unfold_list_sum.\n  rewrite -> rev_list_zip;\n    [ idtac | rewrite -> app_length;\n              rewrite -> unfold_length_induction_case;\n              rewrite -> unfold_length_base_case;\n              rewrite ->2 rev_length;\n              rewrite ->2 Str_prefix_length;\n              rewrite -> plus_comm;\n              reflexivity ].\n  rewrite -> rev_app_distr.\n  rewrite -> unfold_rev_induction_case.\n  rewrite -> unfold_rev_base_case.\n  rewrite -> app_nil_l.\n  rewrite ->2 rev_involutive.\n  rewrite <- unfold_list_sum.\n\n  replace ([0] ++ Str_prefix (S r) (p_monomials (S t) r 0 c))\n  with (Str_prefix (S (S r))  (0 ::: (p_monomials (S t) r 0 c)));\n    [ idtac | reflexivity ].\n\n  replace (Str_prefix (S (S r)) (0 ::: p_monomials (S t) r 0 c)\n         l+ Str_prefix (S (S r)) (p_monomials (S t) (S r) 0 d) ++\n         [0])\n  with ((Str_prefix (S (S r)) (0 ::: p_monomials (S t) r 0 c) ++ [0]) l+\n        (Str_prefix (S (S r)) (p_monomials (S t) (S r) 0 d) ++ [0]));\n    [ idtac |\n      rewrite -> unfold_list_sum;\n        rewrite -> list_zip_append;\n        [ rewrite ->4 unfold_Str_prefix_induction_case;\n          rewrite -> stream_derivative;\n          rewrite ->3 p_monomials_stream_derivative;\n          rewrite ->3 unfold_list_zip_induction_case_cons, -> plus_0_r;\n          rewrite ->2 unfold_list_sum_induction_case_cons;\n          rewrite -> unfold_list_zip_base_case_nil;\n          rewrite -> p_monomials_initial_value;\n          rewrite -> initial_value, -> plus_0_l;\n          unfold list_sum;\n          reflexivity | rewrite ->4 unfold_Str_prefix_induction_case;\n                        rewrite ->4 unfold_length_induction_case;\n                        rewrite ->2 p_monomials_stream_derivative;\n                        rewrite ->2 Str_prefix_length;\n                        reflexivity | reflexivity ] ].\n\n  rewrite -> unfold_Str_prefix_induction_case.\n  rewrite -> initial_value.\n  rewrite -> stream_derivative.\n  rewrite <- pad_p_monomials.\n  rewrite <- app_comm_cons.\n  rewrite <- pad_p_monomials.\n\n  replace (0 :: Str_prefix (S (S r)) (p_monomials (S t) r 0 c))\n  with (Str_prefix (S (S (S r))) (0 ::: (p_monomials (S t) r 0 c)));\n    [ idtac | reflexivity ].\n\n  rewrite -> (IH_n' r (S t)).\n  rewrite <- plus_n_Sm, -> plus_Sn_m.\n  reflexivity.\nQed.\nHint Rewrite nth_triangle_create_triangles_vertically_p_monomials_list_sum\n  : long.\n\n(** ** Hypotenuse and bottom element of [n]th Moessner triangle *)\n\nCorollary hypotenuse_of_last_triangle_create_triangles_vertically_p_monomials_list_sum :\n  forall (n r t d c : nat),\n    hypotenuse\n      (nth n\n           (create_triangles_vertically\n              n\n              (tuple_constant (S (S (S r))) 0)\n              ((Str_prefix (S (S (S r))) (0 ::: (p_monomials t r 0 c))) l+\n               (Str_prefix (S (S (S r))) (p_monomials t (S r) 0 d))))\n           []) =\n    (p_monomials_list (S (n + t)) r r c ++ [0])\n      l+ (p_monomials_list (S (n + t)) (S r) (S r) d).\nProof.\n  intros n r t d c.\n  rewrite -> nth_triangle_create_triangles_vertically_p_monomials_list_sum.\n  rewrite -> hypotenuse_create_triangle_vertically_p_monomials_list_sum.\n  rewrite -> hypotenuse_create_triangle_vertically_p_monomials.\n  rewrite -> hypotenuse_create_triangle_vertically_remove_padding.\n  rewrite -> create_triangle_vertically_horizontal_seed_tuple_padding.\n  rewrite -> hypotenuse_create_triangle_vertically_p_monomials.\n  rewrite <-2 rev_p_monomials_list_eq_p_monomials.\n  reflexivity.\nQed.\nHint Rewrite hypotenuse_of_last_triangle_create_triangles_vertically_p_monomials_list_sum\n  : long.\n\nCorollary bottom_element_of_nth_triangle_create_triangles_vertically_p_monomials_list_sum :\n  forall (n r t d c : nat),\n    nth 0\n        (hypotenuse\n           (nth n\n                (create_triangles_vertically\n                   n\n                   (tuple_constant (S (S (S r))) 0)\n                   ((Str_prefix (S (S (S r))) (0 ::: (p_monomials t r 0 c))) l+\n                    (Str_prefix (S (S (S r))) (p_monomials t (S r) 0 d))))\n                []))\n        1 = p_monomial (S (n + t)) r r c + p_monomial (S (n + t)) (S r) (S r) d.\nProof.\n  intros n r t d c.\n  rewrite -> hypotenuse_of_last_triangle_create_triangles_vertically_p_monomials_list_sum.\n  case r as [ | r' ].\n\n  Case \"r = 0\".\n  rewrite -> unfold_p_monomials_list_induction_case.\n  rewrite ->2 unfold_p_monomials_list_base_case.\n  unfold app; fold app.\n  rewrite ->2 unfold_list_sum_induction_case_cons.\n  rewrite -> unfold_list_sum_base_case_nil.\n  rewrite -> unfold_nth_base_case_cons.\n  reflexivity.\n\n  Case \"r = S r'\".\n  rewrite -> unfold_p_monomials_list_induction_case.\n  rewrite <- app_comm_cons.\n  rewrite -> unfold_p_monomials_list_induction_case.\n  rewrite -> unfold_list_sum_induction_case_cons.\n  rewrite -> unfold_nth_base_case_cons.\n  reflexivity.\nQed.\nHint Rewrite bottom_element_of_nth_triangle_create_triangles_vertically_p_monomials_list_sum\n  : long.\n\n(* {BOTTOM_ELEMENT_OF_NTH_TRIANGLE_IS_POWER_P_MONOMIALS_LIST_SUM} *)\nCorollary bottom_element_of_nth_triangle_is_power_p_monomials_list_sum :\n  forall (n r d c : nat),\n    nth 0\n        (hypotenuse\n           (nth n\n                (create_triangles_vertically\n                   n\n                   (tuple_constant (S (S (S r))) 0)\n                   ((Str_prefix (S (S (S r)))\n                                (0 ::: (p_monomials 0 r 0 c))) l+\n                    (Str_prefix (S (S (S r)))\n                                (p_monomials 0 (S r) 0 d)))) [])) 1 =\n    (c * (S n) ^ r) + (d * (S n) ^ (S r)).\n(* {END} *)\nProof.\n  intros n r d c.\n  rewrite ->\n  bottom_element_of_nth_triangle_create_triangles_vertically_p_monomials_list_sum.\n  rewrite ->2 p_monomial_n_eq_k_implies_power.\n  rewrite -> plus_0_r.\n  reflexivity.\nQed.\nHint Rewrite bottom_element_of_nth_triangle_is_power_p_monomials_list_sum : long.\n\n(** ** Long Stream\n\n  *** Definition *)\n\n(* {LONG_STREAM} *)\nCoFixpoint long_stream (n r d c : nat) : Stream nat :=\n  (nth 0 (hypotenuse\n            (nth n\n                 (create_triangles_vertically\n                    n\n                    (tuple_constant (S (S (S r))) 0)\n                    ((Str_prefix (S (S (S r)))\n                                 (0 ::: (p_monomials 0 r 0 c))) l+\n                    (Str_prefix (S (S (S r)))\n                                (p_monomials 0 (S r) 0 d)))) [])) 1)\n    ::: (long_stream (S n) r d c).\n(* {END} *)\nHint Unfold long_stream : long.\n\n(** *** Unfolding lemmas *)\n\nLemma unfold_long_stream :\n  forall (n r d c : nat),\n    (long_stream n r d c) =\n  (nth 0 (hypotenuse\n            (nth n\n                 (create_triangles_vertically\n                    n\n                    (tuple_constant (S (S (S r))) 0)\n                    ((Str_prefix (S (S (S r)))\n                                 (0 ::: (p_monomials 0 r 0 c))) l+\n                    (Str_prefix (S (S (S r)))\n                                (p_monomials 0 (S r) 0 d)))) [])) 1)\n      ::: (long_stream (S n) r d c).\nProof.\n  intros n r d c.\n  rewrite -> (unfold_Stream (long_stream n r d c)).\n  unfold long_stream; fold long_stream.\n  reflexivity.\nQed.\nHint Rewrite unfold_long_stream : long.\n\nLemma long_stream_initial_value :\n  forall (n r d c : nat),\n    (long_stream n r d c)(0) =\n  (nth 0 (hypotenuse\n            (nth n\n                 (create_triangles_vertically\n                    n\n                    (tuple_constant (S (S (S r))) 0)\n                    ((Str_prefix (S (S (S r)))\n                                 (0 ::: (p_monomials 0 r 0 c))) l+\n                    (Str_prefix (S (S (S r)))\n                                (p_monomials 0 (S r) 0 d)))) [])) 1).\nProof.\n  intros n r d c.\n  rewrite -> initial_value.\n  rewrite -> unfold_long_stream.\n  reflexivity.\nQed.\nHint Rewrite long_stream_initial_value : long.\n\nLemma long_stream_stream_derivative :\n  forall (n r d c : nat),\n    (long_stream n r d c)` = (long_stream (S n) r d c).\nProof.\n  intros n r d c.\n  rewrite -> stream_derivative.\n  rewrite -> unfold_long_stream.\n  reflexivity.\nQed.\nHint Rewrite long_stream_stream_derivative : long.\n\n(** ** Long's theorem *)\n\n(* {LONG_S_THEOREM} *)\nTheorem Long_s_theorem :\n  forall (b e d c : nat),\n    long_stream b e d c ~\n    (c n* (successive_powers b e)) s+ (d n* (successive_powers b (S e))).\n(* {END} *)\nProof.\n  pcofix coIH.\n  intros b e d c.\n  bisimilar.\n\n  Case \"initial value\".\n  rewrite -> long_stream_initial_value.\n  rewrite -> bottom_element_of_nth_triangle_is_power_p_monomials_list_sum.\n  rewrite -> stream_sum_initial_value.\n  rewrite ->2 stream_scalar_multiplication_initial_value.\n  rewrite ->2 successive_powers_initial_value.\n  reflexivity.\n\n  Case \"stream derivative\".\n  rewrite -> long_stream_stream_derivative.\n  rewrite -> stream_sum_stream_derivative.\n  rewrite ->2 stream_scalar_multiplication_stream_derivative.\n  rewrite ->2 successive_powers_stream_derivative.\n  exact (coIH (S b) e d c).\nQed.\nHint Rewrite Long_s_theorem : long.", "meta": {"author": "dragonwasrobot", "repo": "formal-moessner", "sha": "6cf07fd0051f80e401458bbd255be7659c809dd1", "save_path": "github-repos/coq/dragonwasrobot-formal-moessner", "path": "github-repos/coq/dragonwasrobot-formal-moessner/formal-moessner-6cf07fd0051f80e401458bbd255be7659c809dd1/LongsTheorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7138277626552428}}
{"text": "(* Copyright (c)  Inria. All rights reserved. *)\nFrom mathcomp Require Import all_ssreflect all_algebra ssrnum.\nRequire Import digitn.\n\n(******************************************************************************)\n(*                                                                            *)\n(*             Proof of the Fast Fourier Transform                            *)\n(*              inspired by a paper by V. Capretta                            *)\n(******************************************************************************)\n\n(******************************************************************************)\n(*                                                                            *)\n(* fft n w p    = naive algorithn that returns the polynomial                 *)\n(*                p[1] + p[w] * 'X + ... + p[w^(2^n - 1)] * 'X^(2^n - 1)      *)\n(* fft1 n w p   = returns the polynomial                                      *)\n(*                p[1] + p[w] * 'X + ... + p[w^(2^n - 1)] * 'X^(2^n - 1)      *)\n(* istep n w p  = naive iterative algorithn that returns the polynomial       *)\n(*                p[1] + p[w] * 'X + ... + p[w^(2^n - 1)] * 'X^(2^n - 1)      *)\n(* istep1 n w p = iterative algorithm that returns the polynomial             *)\n(*                p[1] + p[w] * 'X + ... + p[w^(2^n - 1)] * 'X^(2^n - 1)      *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory Num.Theory Order.POrderTheory Num.ExtraDef Num.\n\n\nSection FFT.\n\nLocal Open Scope ring_scope.\n\n(* Arbitary idomain                                                           *)\n(* In fact  it works for an arbitray ring. We ask for idomain in order to use *)\n(* primitive-root and sqr_eqf1                                                *)\nVariable R : idomainType.\n\nImplicit Type p : {poly R}.\n\nLemma prim_exp2nS n (w : R) : (2 ^ n.+1).-primitive_root w -> w ^+ (2 ^ n) = -1.\nProof.\nmove=> Hp; have /prim_expr_order/eqP := Hp.\nrewrite expnS mulnC exprM sqrf_eq1 => /orP[]/eqP // /eqP.\nby rewrite -(prim_order_dvd Hp) dvdn_Pexp2l // ltnn.\nQed.\n\nLemma prim_sqr n (w : R) :\n  (2 ^ n.+1).-primitive_root w -> (2 ^ n).-primitive_root (w ^+ 2).\nProof.\nmove=> Hp.\nhave -> : (2 ^ n = 2 ^ n.+1 %/ (gcdn 2 (2 ^ n.+1)))%N.\n  by rewrite -(expn_min _ 1) (minn_idPl _) // expnS mulKn.\nby rewrite exp_prim_root.\nQed.\n \n(* The recursive algorithm                                                    *)\nFixpoint fft (n : nat) (w : R) (p : {poly R}) : {poly R} := \n  if n is n1.+1 then\n    let ev := fft n1 (w ^+ 2) (even_poly p) in\n    let ov := fft n1 (w ^+ 2) (odd_poly p) in\n    \\poly_(i < 2 ^ n1.+1) let j := (i %% 2 ^ n1)%N in ev`_j + ov`_ j * w ^+ i \n  else (p`_0)%:P.\n\nLemma size_fft n w p : (size (fft n w p) <= 2 ^ n)%N.\nProof. \nby case: n => [|n] /=; [rewrite size_polyC; case: eqP | apply: size_poly].\nQed.\n\nFact size_odd_poly_exp2n n p : \n  (size p <= 2 ^ n.+1 -> size (odd_poly p) <= 2 ^ n)%N.\nProof.\nmove=> Hs; apply: leq_trans (size_odd_poly _) _.\nby rewrite leq_half_double (leq_trans Hs) // -mul2n -expnS.\nQed.\n\nFact half_exp2n n : (uphalf (2 ^ n.+1) = 2 ^ n)%N.\nProof.\nby rewrite uphalf_half !expnS !mul2n doubleK odd_double add0n.\nQed.\n\nFact size_even_poly_exp2n n p : \n  (size p <= 2 ^ n.+1 -> size (even_poly p) <= 2 ^ n)%N.\nProof.\nmove=> Hs; apply: leq_trans (size_even_poly _) _.\nby rewrite -half_exp2n uphalf_leq.\nQed.\n\nLemma poly_size1 p : (size p <= 1)%N -> p = (p`_0)%:P.\nProof.\nmove=> sL.\nrewrite -[LHS]coefK poly_def; case E : size sL => [|[]]// _.\n  by rewrite big_ord0 -[p]coefK E poly_def big_ord0 !coefC.\nby rewrite big_ord1 alg_polyC.\nQed.\n\nLemma poly_size2 p : (size p <= 2)%N -> p = (p`_0)%:P + (p`_1)%:P * 'X.\nProof.\nrewrite leq_eqVlt => /orP[/eqP spE|/poly_size1->]; last first.\n  by rewrite !coefC /= mul0r addr0.\nby rewrite -[LHS]coefK poly_def spE big_ord_recr /= \n           big_ord1 alg_polyC mul_polyC.\nQed.\n\n(* Its correctness                                                            *)\nLemma fftE n (w : R) p : \n  (size p <= 2 ^ n)%N -> (2 ^ n).-primitive_root w ->\n  fft n w p = \\poly_(i < 2 ^ n) p.[w ^+ i].\nProof.\nelim: n w p => [/= w p sL _ |n IH w p sL wE /=].\n  by rewrite poly_def big_ord1 expr0 [p]poly_size1 // !hornerE alg_polyC coefC.\napply/polyP => i; rewrite !coef_poly; case: leqP => // iL.\nhave imL : (i %% 2 ^ n < 2 ^ n)%N by apply/ltn_pmod/expn_gt0.\nhave n2P : (0 < 2 ^ n.+1)%N by rewrite expn_gt0.\nhave wwE := prim_sqr wE.\nrewrite !IH ?coef_poly ?imL ?size_even_poly_exp2n ?size_odd_poly_exp2n //.\nrewrite -[p in RHS]poly_even_odd.\nrewrite !(hornerD, horner_comp, hornerMX, hornerX).\nsuff -> : (w ^+ 2) ^+ (i %% 2 ^ n) = w ^+ i * w ^+ i by [].\nrewrite -!expr2 -!exprM.\nhave [iLm|mLi] := leqP (2 ^ n) i; last by rewrite modn_small // mulnC.\nhave -> : (i %% 2 ^ n = i - 2 ^ n)%N.\n  rewrite -[in LHS](subnK iLm) modnDr modn_small //.\n  by rewrite ltn_psubLR ?expn_gt0 // addnn -mul2n -expnS.\nhave -> : (i * 2 = 2 * (i - 2 ^ n) + 2 ^ n.+1)%N.\n  by rewrite mulnC mulnBr -expnS subnK // expnS leq_mul2l.\nrewrite exprD.\nsuff -> : w ^+ (2 ^ n.+1) = 1 by rewrite mulr1.\nby rewrite expnS exprM (prim_expr_order wwE).\nQed.\n\n(* The algorithm with explicitely the butterfly                               *)\nFixpoint fft1 n w p : {poly R} := \n  if n is n1.+1 then\n  let ev := fft1 n1 (w ^+ 2) (even_poly p) in\n  let ov := fft1 n1 (w ^+ 2) (odd_poly p) in\n  \\sum_(j < 2 ^ n1)\n    ((ev`_j + ov`_ j * w ^+ j) *: 'X^j +\n     (ev`_j - ov`_ j * w ^+ j) *: 'X^(j + 2 ^ n1)) \n  else (p`_0)%:P.\n\nLemma fft1S n w p : \n  fft1 n.+1 w p = \n  let ev := fft1 n (w ^+ 2) (even_poly p) in\n  let ov := fft1 n (w ^+ 2) (odd_poly p) in\n  \\sum_(j < 2 ^ n)\n    ((ev`_j + ov`_ j * w ^+ j) *: 'X^j +\n     (ev`_j - ov`_ j * w ^+ j) *: 'X^(j + 2 ^ n)).\nProof. by []. Qed. \n\nLemma fft1E n (w : R) p : (2 ^ n).-primitive_root w -> fft1 n w p = fft n w p.\nProof.\nelim: n w p => [// |n IH w p wE /=].\nhave wwE := prim_sqr wE.\nrewrite poly_def -(@big_mkord _ (0 : {poly R}) +%R (2 ^ n.+1) xpredT\n   (fun (i : nat) => \n      ((fft n (w ^+ 2) (even_poly p))`_(i %% 2 ^ n) +\n    (fft n (w ^+ 2) (odd_poly p))`_(i %% 2 ^ n) * w ^+ i) *: 'X^i)).\nhave F : (2 ^ n <= 2 ^ n.+1)%N by rewrite leq_exp2l.\napply: sym_equal.\nrewrite (big_cat_nat _ _ _ _ F) //=.\nrewrite big_nat; under eq_bigr do rewrite modn_small // ; rewrite -big_nat /=.\nrewrite -(add0n (2 ^ n)%N) big_addn add0n.\nrewrite [(2 ^ n.+1)%N]expnS mul2n -addnn addnK.\nrewrite big_split /= big_mkord; congr (_ + _).\n  by apply: eq_bigr => i _;\n      rewrite !IH ?size_even_poly_exp2n ?size_odd_poly_exp2n //.\nrewrite big_nat; under eq_bigr do\n    rewrite modnDr modn_small // exprD (prim_exp2nS wE) mulrN1 mulrN;\n    rewrite -big_nat /=.\nrewrite big_mkord; apply: eq_bigr => i _.\nby rewrite !IH ?size_even_poly_exp2n ?size_odd_poly_exp2n.\nQed.\n\nDefinition step m n w (p : {poly R}) :=\n  \\sum_(l < 2 ^ m)\n  let ev := \\poly_(i < 2 ^ n) p`_(i + l * 2 ^ n.+1) in\n  let ov := \\poly_(i < 2 ^ n) p`_(i + l * 2 ^ n.+1 + 2 ^ n) in\n    \\sum_(j < 2 ^ n)\n      ((ev`_j + ov`_ j * w ^+ j) *: 'X^(j + l * 2 ^ n.+1) +\n       (ev`_j - ov`_ j * w ^+ j) *: 'X^(j + l * 2 ^ n.+1 + 2 ^ n)).\n\nLemma stepE m n w (p : {poly R}) :\n  step m n w p =\n  \\sum_(l < 2 ^ m)\n  let ev := \\poly_(i < 2 ^ n) p`_(i + l * 2 ^ n.+1) in\n  let ov := \\poly_(i < 2 ^ n) p`_(i + l * 2 ^ n.+1 + 2 ^ n) in\n    (\\sum_(j < 2 ^ n)\n      ((ev`_j + ov`_ j * w ^+ j) *: 'X^j +\n       (ev`_j - ov`_ j * w ^+ j) *: 'X^(j + 2 ^ n))) * \n    'X^ (l * 2 ^ n.+1).\nProof.\napply: eq_bigr => i _ /=.\nrewrite [RHS]mulr_suml.\napply: eq_bigr => j _ /=.\nrewrite mulrDl; congr (_ + _); rewrite -scalerAl -exprD //.\nby rewrite addnAC.\nQed.\n\nFact bound_step m n i j : \n  (i < 2 ^ m -> j < 2 ^ n -> \n   j + i * 2 ^ n.+1 + 2 ^ n < 2 ^ (m + n).+1)%N.\nProof.\nmove=> Hi Hj.\nrewrite addnAC.\napply: leq_trans (_ : 2 ^ n + 2 ^ n + i *2 ^ n.+1 <= _ )%N.\n  by rewrite -!addnA ltn_add2r.\nby rewrite addnn -mul2n -expnS -mulSn -addnS expnD leq_mul2r expn_eq0 /=.\nQed.\n\nLemma size_step m n w p : (size (step m n w p) <= (2 ^ (m + n).+1))%N.\nProof.\napply: leq_trans (size_sum _ _ _) _.\napply/bigmax_leqP_seq => i _ _.\napply: leq_trans (size_sum _ _ _) _.\napply/bigmax_leqP_seq => j _ _.\napply: leq_trans (size_add _ _) _.\nrewrite geq_max; apply/andP; split; \n    apply: leq_trans (size_scale_leq _ _) _; rewrite size_polyXn.\n  apply: leq_trans (bound_step (ltn_ord i) (ltn_ord j)).\n  by rewrite ltnS leq_addr.\nby apply: bound_step.\nQed.\n\nFact stepE1 (m n : nat) w p i : \n  w ^+ (2 ^ n) = -1 ->\n  (i < 2 ^ (m + n).+1)%N ->\n  let l := (i %/ 2 ^ n.+1)%N in \n  let j := (i %% 2 ^ n.+1)%N in \n  let j1 := (i %% 2 ^ n)%N in\n  (step m n w p)`_i =\n      p`_(j1 + l * 2 ^ n.+1) + \n      p`_(j1 + l * 2 ^ n.+1 + 2 ^ n) * w ^+ j.\nProof.\nmove=> Hw Hi l j j1.\nhave lL2m : (l < 2 ^ m)%N.\n  by rewrite ltn_divLR ?expn_gt0 // -expnD addnS.\nhave jL2n : (j < 2 ^ n.+1)%N by rewrite ltn_mod // expn_gt0.\nhave j1L2n : (j1 < 2 ^ n)%N by rewrite ltn_mod // expn_gt0.\nhave F1 : (2 ^ n <= j -> j = 2 ^ n + j1)%N.\n  move=> Hj.\n  rewrite (divn_eq j (2 ^ n)) modn_dvdm -/j1 ?dvdn_Pexp2l //.\n  suff-> : (j %/ 2 ^ n = 1)%N by rewrite mul1n.\n  have F1 : (j - 2 ^ n < 2 ^ n)%N.\n    by rewrite ltn_subLR // addnn -mul2n -expnS.\n  rewrite -(subnK Hj) divnD ?expn_gt0 // divn_small ?F1 //.\n  rewrite add0n divnn expn_gt0 //=.\n  by rewrite modn_small ?(ltnW F1) // modnn addn0 leqNgt F1 addn0.\nhave F2 : (j < 2 ^ n -> j = j1)%N.\n  move=> F2.\n  by rewrite -(modn_small F2) modn_dvdm // dvdn_Pexp2l.\nrewrite coef_sum (bigD1 (Ordinal lL2m)) //= [X in _ + X]big1 ?addr0.\n  rewrite coef_sum (bigD1 (Ordinal j1L2n)) //= [X in _ + X]big1 ?addr0.\n    rewrite !(coefD, coefZ, coefXn, coef_poly).\n    rewrite j1L2n (divn_eq i (2 ^ n.+1)) -/l [(l * _ + _)%N]addnC.\n    rewrite [(_ + 2 ^ n)%N]addnC addnA !eqn_add2r -/j -/j1.\n    have [Hul|Hlu] := leqP (2 ^ n) j.\n      rewrite F1 // -[X in _ == X]add0n eqn_add2r expn_eq0 mulr0 add0r.\n      by rewrite eqxx mulr1 exprD Hw mulN1r mulrN.\n    by rewrite F2 // eqxx mulr1 -[X in X == _]add0n eqn_add2r eq_sym \n               expn_eq0 mulr0 addr0.\n  move=> i1 /eqP/val_eqP/= Hi1.   \n  rewrite !(coefD, coefZ, coefXn, coef_poly).\n  rewrite ltn_ord // (divn_eq i (2 ^ n.+1)) -/l [(l * _ + _)%N]addnC.\n  rewrite [(_ + 2 ^ n)%N]addnC addnA !eqn_add2r -/j -/j1.\n  have [Hul|Hlu] := leqP (2 ^ n) j.\n    rewrite eqn_leq [(j <= _)%N]leqNgt (leq_trans (ltn_ord _)) //=.\n    rewrite mulr0 add0r.\n    by rewrite F1 // eqn_add2l eq_sym (negPf Hi1) mulr0.\n  rewrite [(_ == (_ + _))%N]eqn_leq [(_ <= j)%N]leqNgt.\n  rewrite (leq_trans Hlu) ?leq_addr // andbF mulr0 addr0.\n  by rewrite F2 // eq_sym (negPf Hi1) mulr0.\nmove=> i1 /eqP/val_eqP/= Hi1.\nrewrite coef_sum big1 // => i2 _.\nrewrite !(coefD, coefZ, coefXn, coef_poly).\nrewrite (_ : _ == _ = false); last first.\n  apply/idP => /eqP iE; have /eqP[] := Hi1.\n  rewrite /l iE divnDMl ?expn_gt0 // divn_small //.\n  by rewrite (leq_trans (ltn_ord _)) // leq_exp2l.\nrewrite (_ : _ == _ = false) ?mulr0 ?addr0 //.\napply/idP => /eqP iE; have /eqP[] := Hi1.\nrewrite addnC addnA in iE.\nrewrite /l iE divnDMl ?expn_gt0 // divn_small //.\nrewrite expnS mul2n -addnn ltn_add2l.\nby rewrite (leq_trans (ltn_ord _)) // leq_exp2l.\nQed.\n\nLemma take_step m n w (p : {poly R}) :\n  (size p <= 2 ^ (m + n).+2)%N ->\n  take_poly (2 ^ (m + n).+1) (step m.+1 n w p) =\n  step m n w (take_poly (2 ^ (m + n).+1) p).\nProof.\nmove=> pLmn; rewrite stepE.\napply/polyP=> i; rewrite coef_take_poly.\ncase: leqP => [mnLi|iLmn].\n  rewrite nth_default //.\n  by apply: leq_trans (size_step _ _ _ _) _.\nrewrite stepE !coef_sum expnS mul2n -addnn big_split_ord /=.\nrewrite [X in _ + X = _]big1 ?addr0 => [|j _]; last first.\n  by rewrite coefMXn ifT // (leq_trans iLmn) // mulnDl -expnD addnS leq_addr.\napply: eq_bigr => j _.\ncongr (((_ * _) : {poly R}) `_ _).\napply: eq_bigr => k _.\nhave F : (k + j * 2 ^ n.+1 < 2 ^ (m + n).+1)%N.\n  apply: leq_trans (bound_step (ltn_ord j) (ltn_ord k)).\n  by rewrite ltnS leq_addr.\nhave F1 : (k + j * 2 ^ n.+1 + 2 ^ n < 2 ^ (m + n).+1)%N.\n  by apply: bound_step.\nby rewrite !coef_poly F F1.\nQed.\n\nLemma drop_step m n w (p : {poly R}) :\n  (size p <= 2 ^ (m + n).+2)%N ->\n  drop_poly (2 ^ (m + n).+1) (step m.+1 n w p) =\n  step m n w (drop_poly (2 ^ (m + n).+1) p).\nProof.\nmove=> pLmn.\napply/polyP=> i; rewrite coef_drop_poly.\nrewrite !stepE !coef_sum expnS mul2n -addnn big_split_ord /=.\nrewrite [X in X + _ = _]big1 ?add0r => [|j _]; last first.\n  rewrite coefMXn ifN; last first.\n    rewrite -leqNgt (leq_trans _ (leq_addl _ _)) //.\n    by rewrite -addnS expnD leq_mul2r // ltnW ?orbT.\n  rewrite nth_default //.\n  apply: leq_trans (_ : 2 ^ n.+1 <= _)%N.\n    apply: leq_trans (size_sum _ _ _) _.\n    apply/bigmax_leqP => k _.\n    apply: leq_trans (size_add _ _) _.\n    rewrite geq_max; apply/andP; split; apply: leq_trans (size_scale_leq _ _) _.\n      rewrite size_polyXn.\n      by apply: leq_trans (ltn_ord _) _; rewrite leq_exp2l.\n    by rewrite size_polyXn expnS mul2n -addnn ltn_add2r.\n  rewrite leq_subRL (leq_trans _ (leq_addl _ _)) //.\n    by rewrite addnC -mulSn -addnS expnD leq_mul2r ltn_ord orbT.\n  by rewrite -addnS expnD leq_mul2r ltnW ?orbT // ltn_ord.\napply: eq_bigr => j _.\nrewrite !coefMXn addnC mulnDl -expnD addnS ltn_add2l.\ncase: leqP => // jLi; rewrite subnDl.\ncongr ((_ : {poly R}) `_ _).\napply: eq_bigr => k _.\nhave F : (k + j * 2 ^ n.+1 + 2 ^ (m + n).+1 = \n          k + (2 ^ (m + n).+1 + j * 2 ^ n.+1))%N.\n  by rewrite addnAC addnA.\nhave F1 : \n  ((k + j * 2 ^ n.+1 + 2 ^ n + 2 ^ (m + n).+1) =\n    (k + (2 ^ (m + n).+1 + j * 2 ^ n.+1) + 2 ^ n))%N.\n  by rewrite !addnA [(k + _ + _)%N in RHS]addnAC [(_ + 2 ^ n)%N in RHS]addnAC. \nby rewrite !(coef_drop_poly, coef_poly) ltn_ord // F F1.\nQed.\n\nDefinition reverse_poly n (p : {poly R}) :=\n  \\poly_(i < 2 ^ n) p`_(rdigitn 2 n i).\n\nLemma size_reverse_poly  n p : (size (reverse_poly n p) <= 2 ^ n)%N.\nProof. by rewrite size_poly. Qed.\n\nLemma reverse_poly0 p : reverse_poly 0 p = (p`_0)%:P.\nProof. by apply/polyP => [] [|i]; rewrite coef_poly coefC. Qed.\n\nLemma reverse_polyS n p : \n  reverse_poly n.+1 p = \n  reverse_poly n (even_poly p) + reverse_poly n (odd_poly p) * 'X^(2 ^ n).\nProof.\nrewrite /reverse_poly /even_poly /odd_poly.\nunder [X in X + _]eq_poly do rewrite coef_poly.\nunder [X in _ + X * _]eq_poly do rewrite coef_poly.\napply/polyP => i.\nrewrite coefD coefMXn !coef_poly.\nhave [tnLi|iLtn] := leqP (2 ^ n) i.\n  rewrite ltn_subLR // addnn -mul2n -expnS add0r.\n  case: leqP => [//|iLtSn].\n  suff Hf : (rdigitn 2 n.+1 i) = (rdigitn 2 n (i - 2 ^ n)).*2.+1.\n    case: leqP => [iLn|nLi]; last by rewrite Hf.\n    suff/leq_sizeP-> : (size p <= rdigitn 2 n.+1 i)%N by [].\n    rewrite Hf.\n    by rewrite leq_half_double in iLn.\n  rewrite !rdigitnE big_ord_recl /= subn0 muln1 /bump /= .\n  rewrite {1}/digitn -{1}(subnK tnLi).\n  rewrite divnDr ?dvdnn // divnn expn_gt0 /= divn_small ?add1n; last first.\n    by rewrite ltn_subLR // addnn -mul2n -expnS.\n  under eq_bigr do rewrite add1n; congr (_.+1).\n  under eq_bigr do rewrite expnS mulnCA.\n  rewrite -big_distrr /= mul2n; congr (_.*2).\n  apply: eq_bigr => j _; congr (_ * _)%N.\n  have ->: (n.-1 - j = n - j.+1)%N.\n    rewrite subnS.\n    by case: (n) j => //= n1 j; rewrite subSn // -ltnS.\n  rewrite /digitn -{1}(subnK tnLi) -[X in (_ + 2 ^ X)%N](subnK (ltn_ord j)).\n  rewrite expnD mulnC divnDMl ?expn_gt0 //.\n  by rewrite -modnDm // expnS modnMr addn0 modn_mod.\nrewrite addr0 ifT; last by rewrite (leq_trans iLtn) // leq_exp2l.\nsuff Hf : (rdigitn 2 n.+1 i) = (rdigitn 2 n i).*2.\n  case: leqP => [iLn|nLi]; last by rewrite Hf.\n  suff/leq_sizeP-> : (size p <= rdigitn 2 n.+1 i)%N by [].\n  rewrite leq_uphalf_double in iLn.\n  by rewrite (leq_trans iLn) // Hf.\nrewrite !rdigitnE big_ord_recl /= subn0 muln1 /bump /= .\nrewrite {1}/digitn divn_small // add0n.\nunder eq_bigr do rewrite add1n expnS mulnCA.\nrewrite -big_distrr /= mul2n; congr (_.*2).\napply: eq_bigr => j _; congr (_ _ _ * _)%N.\nrewrite subnS.\nby case: (n) j => //= n1 j; rewrite subSn // -ltnS.\nQed.\n\nFixpoint all_results_fft1 n m w p q :=\n  if n is n1.+1 then \n  all_results_fft1 n1 m w (even_poly p) (take_poly (2 ^ (m + n1)) q) /\\ \n  all_results_fft1 n1 m w (odd_poly p) (drop_poly (2 ^ (m + n1)) q) \n  else q = fft1 m w p.\n\nLemma all_resultsS_fft1 n m w p q :\n  all_results_fft1 n.+1 m w p q <->\n  all_results_fft1 n m w (even_poly p) (take_poly (2 ^ (m + n)) q) /\\ \n  all_results_fft1 n m w (odd_poly p) (drop_poly (2 ^ (m + n)) q).\nProof. by []. Qed.\n\nLemma all_results_fft1_reverse_poly p n w :\n  (size p <= 2 ^ n)%N -> all_results_fft1 n 0 w p (reverse_poly n p).\nProof.\nelim: n p => /= [p spL1|n IH p spLb].\n  by rewrite reverse_poly0 -poly_size1.\nsplit.\n  rewrite /take_poly reverse_polyS poly_def.\n  under eq_bigr do rewrite coefD coefMXn ifT // addr0.\n  rewrite -poly_def.\n  have -> : \\poly_(i < 2 ^ n) (reverse_poly n (even_poly p))`_i = \n            \\poly_(i < size (reverse_poly n (even_poly p)))\n                       (reverse_poly n (even_poly p))`_i.\n    apply/polyP => i; rewrite coef_poly [RHS]coef_poly.\n    case: leqP => [n2Li|iLn2].\n      by rewrite ifN // -leqNgt (leq_trans _ n2Li) // size_reverse_poly.\n    case: leqP => [epLi|iLep] => //.\n    by suff /leq_sizeP-> : (size (reverse_poly n (even_poly p)) <= i)%N by [].\n  rewrite coefK.\n  apply: IH.\n  by rewrite size_even_poly_exp2n.\nrewrite add0n.\nhave -> : drop_poly (2 ^ n) (reverse_poly n.+1 p) =\n         \\poly_(i < 2 ^ n) (reverse_poly n.+1 p)`_(i + 2 ^ n).\n  apply/polyP=> i; rewrite coef_drop_poly coef_poly.\n  case: leqP => // nLn; rewrite nth_default //.\n  apply: leq_trans (size_reverse_poly _ _) _.\n  by rewrite expnS mul2n -addnn leq_add2r.\nrewrite reverse_polyS poly_def.\nunder eq_bigr do rewrite coefD coefMXn ltnNge leq_addl /= addnK scalerDl.\nrewrite big_split /= big1 ?add0r => [|i _]; last first.\n  suff /leq_sizeP-> : (size (reverse_poly n (even_poly p)) <= i + 2 ^ n)%N.\n  - by rewrite scale0r.\n  - by [].\n  by apply: leq_trans (size_reverse_poly _ _) (leq_addl _ _).\nrewrite -poly_def.\nhave -> : \\poly_(i < 2 ^ n) (reverse_poly n (odd_poly p))`_i = \n          \\poly_(i < size (reverse_poly n (odd_poly p)))\n                      (reverse_poly n (odd_poly p))`_i.\n  apply/polyP => i; rewrite coef_poly [RHS]coef_poly.\n  case: leqP => [n2Li|iLn2].\n    by rewrite ifN // -leqNgt (leq_trans _ n2Li) // size_reverse_poly.\n  case: leqP => [epLi|iLep] => //.\n  by suff /leq_sizeP-> : (size (reverse_poly n (odd_poly p)) <= i)%N by [].\nrewrite coefK.\napply: IH.\nby rewrite size_odd_poly_exp2n.\nQed.\n\nLemma poly1 (s : nat -> R) : \\poly_(i < 1) s i = (s 0%N)%:P.\nProof. by apply/polyP => i; rewrite coef_poly coefC; case: i. Qed.\n\nLemma all_results_fft1_step m n w (p q : {poly R}):\n  (size p <= 2 ^ (m + n).+1)%N ->\n  (size q <= 2 ^ (m + n).+1)%N ->\n  all_results_fft1 m.+1 n (w ^+ 2) p q ->\n  all_results_fft1 m n.+1 w p (step m n w q).\nProof.\nelim: m n w p q => [n p w q|\n                    m IH n w p q Hsp Hsp1/all_resultsS_fft1[H2 H3]].\n  rewrite add0n => Hp Hq [H1 H2].\n  rewrite /= -H1 -H2 /step big_ord1 mul0n !addn0.\n  apply: eq_bigr => /= i _.\n  by rewrite !coef_drop_poly !coef_poly !addn0 ltn_ord.\napply/all_resultsS_fft1; split.\n  rewrite [(_ + m)%N]addnC addnS take_step //.\n  apply: IH => //.\n  - by apply: size_even_poly_exp2n.\n  - by rewrite size_poly.\n  by rewrite [(m + _)%N]addnC -addnS.\nrewrite addnC addnS drop_step //.\napply: IH => //.\n- by apply: size_odd_poly_exp2n.\n- rewrite size_drop_poly.\n  by rewrite leq_subLR addnn -mul2n -expnS.\nby rewrite [(m + _)%N]addnC -addnS.\nQed.\n\nFixpoint istep_aux m n w p :=\n  if m is m1.+1 then istep_aux m1 n.+1 w (step m1 n (w ^+ (2 ^ m1)) p) else p.\n\nDefinition istep n w p := istep_aux n 0 w (reverse_poly n p).\n\nLemma istep_fft1 n p w : (size p <= 2 ^ n)%N -> istep n w p = fft1 n w p.\nProof.\nmove=> Hs.\nsuff /(_ n 0%N): forall m1 n1 (p1 q1 : {poly R}), \n    (size p1 <= 2 ^ (m1 + n1))%N ->\n    (size q1 <= 2 ^ (m1 + n1))%N ->\n    all_results_fft1 m1 n1 (w ^+ (2 ^ m1)) p1 q1 -> \n    all_results_fft1 0 (m1 + n1) w p1 (istep_aux m1 n1 w q1).\n  rewrite addn0 /=.\n   apply => //; first by apply: size_reverse_poly.\n  by apply: all_results_fft1_reverse_poly.\nelim => [//| m1 IH] n1 p1 q1 Hs1 Hs2 H1.\nrewrite /istep_aux -/istep_aux addSnnS.\napply: IH; first by rewrite addnS.\n  rewrite addnS.\n  by apply: size_step.\napply: all_results_fft1_step => //.\nby rewrite -exprM mulnC -expnS.\nQed.\n\n(* Refined version of step 1                                                  *)\nDefinition step1 m n w (p : {poly R}) :=\n  \\poly_(i < 2 ^ (m + n).+1)\n    let j := (i %% 2 ^ n.+1)%N in\n    if (j < 2 ^ n)%N then \n      p`_i + p`_(i + 2 ^ n) * w ^+ j\n    else \n      p`_(i - 2 ^ n) - p`_i * w ^+ (j - 2 ^ n).\n\nLemma step1E m n w p : step1 m n w p = step m n w p.\nProof.\napply/polyP => i.\nrewrite coef_poly coef_sum.\nhave [mnLi|iLmn] := leqP.\n  rewrite big1 // => j _; rewrite coef_sum /=.\n  rewrite big1 // => k _; rewrite !coef_poly !(coefD, coefZ, coefXn).\n  rewrite !gtn_eqF ?mulr0 ?addr0 // (leq_trans _ mnLi) //.\n    by apply: bound_step.\n  apply: leq_trans (bound_step (ltn_ord j) (ltn_ord k)).\n  by rewrite ltnS leq_addr.\nset l := (i %/ 2 ^ n.+1)%N.\nhave l_ltn : (l < 2 ^ m)%N.\n  by rewrite ltn_divLR ?expn_gt0 // -expnD addnS.\nrewrite (bigD1 (Ordinal l_ltn)) //= [X in _ = _ + X]big1; last first.\n  move=> i1 /eqP/val_eqP /= i1Dl.\n  rewrite coef_sum big1 // => i2 _.\n  rewrite coefD !coefZ !coefXn.\n  case: (ltngtP i1 l) i1Dl => // i1Dl _.\n    rewrite leq_divRL ?expn_gt0 // in i1Dl.\n    rewrite !gtn_eqF ?mulr0 ?addr0 //; apply: leq_trans i1Dl.\n      by rewrite addnAC mulSn -!addSn leq_add // expnS mul2n -addnn leq_add2r.\n    rewrite mulSn -!addSn leq_add // (leq_trans (ltn_ord _)) //.\n    by rewrite expnS mul2n -addnn leq_addr.\n  rewrite ltn_divLR ?expn_gt0 // in i1Dl.\n  rewrite !ltn_eqF ?mulr0 ?addr0 //; apply: leq_trans i1Dl _.\n    by rewrite addnAC leq_addl.\n  by rewrite leq_addl.\nrewrite addr0.\nhave F : (i %% 2 ^ n.+1 + l * 2 ^ n.+1 = i)%N by rewrite addnC -divn_eq.\nrewrite coef_sum.\ncase: leqP => H.\n  have Fi : (2 ^ n <= i)%N by apply: leq_trans H (leq_mod _ _).\n  have F1 : (i %% 2 ^ n.+1 - 2 ^ n < 2 ^ n)%N.\n    by rewrite ltn_subLR // addnn -mul2n -expnS ltn_pmod ?expn_gt0.\n  have F2 : ((i %% 2 ^ n.+1) %% 2 ^ n = i %% 2 ^ n.+1 - 2 ^ n)%N.\n    by rewrite -[in LHS](subnK H) modnDr modn_small.\n  rewrite (bigD1 (Ordinal F1)) //= ?big1.\n    rewrite addr0 coefD !coefZ !coefXn.\n    rewrite addnBAC // F subnK // eqxx mulr1 gtn_eqF; last first.\n      by rewrite ltn_subLR // (ltn_add2r _ 0) expn_gt0.\n    rewrite mulr0 add0r !coef_poly F1.\n    by rewrite addnBAC // F subnK // eqxx mulr1 gtn_eqF.\n  move=> i1 /eqP/val_eqP/= Hi1.\n  rewrite !coef_poly ltn_ord coefD !coefZ !coefXn.\n  rewrite -F addnAC !eqn_add2r gtn_eqF ?mulr0 ?add0r; last first.\n    by apply: leq_trans H.\n  by rewrite -(subnK H) eqn_add2r eq_sym (negPf Hi1) mulr0.\nrewrite (bigD1 (Ordinal H)) //= ?big1.\n  rewrite addr0 coefD !coefZ !coefXn F.\n  rewrite eqxx mulr1 ltn_eqF ?mulr0 ?addr0 // ?(ltn_add2l _ 0) ?expn_gt0 //.\n    by rewrite !coef_poly F H.\n  by rewrite addnC (ltn_add2r _ 0) expn_gt0.\nmove=> i1 /eqP/val_eqP/= Hi1.\nrewrite !coef_poly ltn_ord coefD !coefZ !coefXn.\nrewrite -F eqn_add2r eq_sym (negPf Hi1) mulr0 add0r.\nrewrite addnAC eqn_add2r ltn_eqF ?mulr0 //.\nby apply: leq_trans H (leq_addl _ _).\nQed.    \n\nFixpoint istep1_aux m n w p :=\n  if m is m1.+1 then istep1_aux m1 n.+1 w (step1 m1 n (w ^+ (2 ^ m1)) p) else p.\n\nDefinition istep1 n w p := istep1_aux n 0 w (reverse_poly n p).\n\nLemma istep1_fft1 n p w : (size p <= 2 ^ n)%N -> istep1 n w p = fft1 n w p.\nProof.\nmove=> Hs; rewrite -istep_fft1 // /istep1 /istep.\nelim: n {Hs}(size_reverse_poly n p) 0%N w (reverse_poly _ _) => \n    //= n IH pLn n1 w p1.\nrewrite step1E.\napply: IH.\nby apply: size_reverse_poly.\nQed.\n\n\nEnd FFT.\n\nSection iFFT.\n\nLocal Open Scope ring_scope.\n\n(* Arbitrary field                                                            *)\nVariable F : fieldType.\n\nLemma unity_rootJ n (w : F) : n.-unity_root w^-1 = n.-unity_root w.\nProof.\napply/unity_rootP/unity_rootP; rewrite exprVn => /eqP.\n  by rewrite invr_eq1 => /eqP.\nby move=> H; apply/eqP; rewrite invr_eq1.\nQed. \n\nLemma primJ n (w : F) : n.-primitive_root w -> n.-primitive_root (w^-1).\nProof.\nmove/andP=> [nP /forallP H]; apply/andP; split => //.\napply/forallP => i; apply/eqP; rewrite -(eqP (H i)).\nby apply: unity_rootJ.\nQed.\n\nImplicit Type p : {poly F}.\n\n(* The inverse algorithm                                                      *)\nDefinition ifft n w p : {poly F} := (2^ n)%:R^-1%:P * (fft n w^-1 p).\n\n(* Its correctness                                                            *)\nLemma fftK n (w : F) p : \n  2%:R != 0 :> F -> (size p <= 2 ^ n)%N -> (2 ^ n).-primitive_root w ->\n  ifft n w (fft n w p) = p.\nProof.\nmove=> char2 sL wE.\nhave wE1 : w ^+ (2 ^ n) = 1 by apply: prim_expr_order.\nhave wNZ : w != 0.\n  apply/eqP=> wZ; move/eqP: wE1.\n  by rewrite eq_sym wZ expr0n expn_eq0 /= oner_eq0.\nhave wVE := primJ wE.\nhave wIE : w^-1 = w ^+ (2 ^ n).-1.\n  by apply: (mulfI wNZ); rewrite mulfV // -exprS prednK ?expn_gt0.\nrewrite /ifft !fftE ?size_poly //.\napply/polyP => i; rewrite coefCM coef_poly /=.\ncase: leqP => iL; first by rewrite nth_default ?mulr0 // (leq_trans _ iL).\nrewrite horner_poly.\nhave pE : p = \\poly_(j <  2 ^ n) p`_j.\n  apply/polyP => j; rewrite coef_poly; case: leqP => // jL.\n  by rewrite nth_default // (leq_trans _ jL).\nunder [X in _ * X = _]eq_bigr => j H do\n  rewrite {1}pE horner_poly /= mulr_suml (bigD1 (Ordinal iL)) //=\n          -!exprM mulnC -mulrA -exprMn ?(divff, expr1n, mulr1, addr0) //.\nrewrite big_split /=.\nrewrite sumr_const card_ord mulrDr.\nrewrite -[X in _ * X + _ = _]mulr_natl mulrA mulVf ?mul1r; last first.\n  by rewrite natrX expf_eq0 (negPf char2) andbF.\nrewrite exchange_big /= big1 ?(mulr0, addr0) //= => k /eqP /val_eqP /= kDi.\nunder [LHS] eq_bigr do \n  rewrite -mulrA -exprM mulnC !exprM -exprMn wIE -!exprM -exprD.\nset x := w ^+ _; rewrite -mulr_sumr.\nsuff xDone : x - 1 != 0.\n  suff -> : (\\sum_(i0 < 2 ^ n) x ^+ i0) = 0 by rewrite mulr0.\n  apply: (mulfI xDone).\n  by rewrite -subrX1 mulr0 -exprM mulnC exprM wE1 expr1n subrr.\n(* There should be a simpler way to prove this *)\nrewrite subr_eq0 -(prim_order_dvd wE).\ncase: {x}i iL kDi => [|i] iL xDi.\n  rewrite muln0 addn0; apply/negP=> /dvdn_leq.\n  by rewrite lt0n leqNgt ltn_ord => /(_ xDi).\nrewrite -subn1 mulnBl mul1n mulnS addnC [(_ ^ _ + _)%N]addnC.\nrewrite -addnBA ?(leq_trans _ iL) //.\nrewrite /dvdn mulnC -addnA modnMDl; apply/negP => /dvdnP[q /eqP qE].\nsuff : (q < 2)%N.\n  case: q qE => [|[|]] //.\n    by rewrite mul0n; rewrite addn_eq0 subn_eq0 leqNgt iL.\n  by rewrite mul1n -(eqn_add2r (i.+1)) addnAC subnK \n             ?(eqn_add2l, negPf xDi) // ltnW.\nrewrite -(ltn_pmul2r (_ : 0 < 2 ^ n)%N) ?expn_gt0 //.\nrewrite -(eqP qE) mul2n -addnn.\napply: (leq_trans (_ : _ <= 2 ^ n - i.+1 + 2 ^ n)%N).\n  by rewrite ltn_add2l.\nby rewrite leq_add2r leq_subr.\nQed.\n\nEnd iFFT.", "meta": {"author": "thery", "repo": "mathcomp-extra", "sha": "e776299ceebf276502a6ee1a787febf5c806293d", "save_path": "github-repos/coq/thery-mathcomp-extra", "path": "github-repos/coq/thery-mathcomp-extra/mathcomp-extra-e776299ceebf276502a6ee1a787febf5c806293d/fft.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7138277608345313}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import NAxioms NSub NZGcd.\n\nModule Type NGcdProp\n(Import A : NAxiomsSig')\n(Import B : NSubProp A).\n\nInclude NZGcdProp A A B.\n\n\n\nDefinition divide_1_r n : (n | 1) -> n == 1\n:= divide_1_r_nonneg n (le_0_l n).\n\nDefinition divide_antisym n m : (n | m) -> (m | n) -> n == m\n:= divide_antisym_nonneg n m (le_0_l n) (le_0_l m).\n\nLemma divide_add_cancel_r : forall n m p, (n | m) -> (n | m + p) -> (n | p).\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.divide_add_cancel_r\".  \nintros n m p (q,Hq) (r,Hr).\nexists (r-q). rewrite mul_sub_distr_r, <- Hq, <- Hr.\nnow rewrite add_comm, add_sub.\nQed.\n\nLemma divide_sub_r : forall n m p, (n | m) -> (n | p) -> (n | m - p).\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.divide_sub_r\".  \nintros n m p H H'.\ndestruct (le_ge_cases m p) as [LE|LE].\napply sub_0_le in LE. rewrite LE. apply divide_0_r.\napply divide_add_cancel_r with p; trivial.\nnow rewrite add_comm, sub_add.\nQed.\n\n\n\nDefinition gcd_0_l n : gcd 0 n == n := gcd_0_l_nonneg n (le_0_l n).\nDefinition gcd_0_r n : gcd n 0 == n := gcd_0_r_nonneg n (le_0_l n).\nDefinition gcd_diag n : gcd n n == n := gcd_diag_nonneg n (le_0_l n).\nDefinition gcd_unique' n m p := gcd_unique n m p (le_0_l p).\nDefinition gcd_unique_alt' n m p := gcd_unique_alt n m p (le_0_l p).\nDefinition divide_gcd_iff' n m := divide_gcd_iff n m (le_0_l n).\n\nLemma gcd_add_mult_diag_r : forall n m p, gcd n (m+p*n) == gcd n m.\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gcd_add_mult_diag_r\".  \nintros. apply gcd_unique_alt'.\nintros. rewrite gcd_divide_iff. split; intros (U,V); split; trivial.\napply divide_add_r; trivial. now apply divide_mul_r.\napply divide_add_cancel_r with (p*n); trivial.\nnow apply divide_mul_r. now rewrite add_comm.\nQed.\n\nLemma gcd_add_diag_r : forall n m, gcd n (m+n) == gcd n m.\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gcd_add_diag_r\".  \nintros n m. rewrite <- (mul_1_l n) at 2. apply gcd_add_mult_diag_r.\nQed.\n\nLemma gcd_sub_diag_r : forall n m, n<=m -> gcd n (m-n) == gcd n m.\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gcd_sub_diag_r\".  \nintros n m H. symmetry.\nrewrite <- (sub_add n m H) at 1. apply gcd_add_diag_r.\nQed.\n\n\n\nDefinition Bezout n m p := exists a b, a*n == p + b*m.\n\nInstance Bezout_wd : Proper (eq==>eq==>eq==>iff) Bezout.\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.Bezout_wd\".  \nunfold Bezout. intros x x' Hx y y' Hy z z' Hz.\nsetoid_rewrite Hx. setoid_rewrite Hy. now setoid_rewrite Hz.\nQed.\n\nLemma bezout_1_gcd : forall n m, Bezout n m 1 -> gcd n m == 1.\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.bezout_1_gcd\".  \nintros n m (q & r & H).\napply gcd_unique; trivial using divide_1_l, le_0_1.\nintros p Hn Hm.\napply divide_add_cancel_r with (r*m).\nnow apply divide_mul_r.\nrewrite add_comm, <- H. now apply divide_mul_r.\nQed.\n\n\n\nLemma gcd_bezout_pos_pos : forall n, 0<n -> forall m, 0<m ->\nBezout n m (gcd n m) /\\ Bezout m n (gcd n m).\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gcd_bezout_pos_pos\".  \nintros n Hn. rewrite <- le_succ_l, <- one_succ in Hn.\npattern n. apply strong_right_induction with (z:=1); trivial.\nunfold Bezout. solve_proper.\nclear n Hn. intros n Hn IHn.\nintros m Hm. rewrite <- le_succ_l, <- one_succ in Hm.\npattern m. apply strong_right_induction with (z:=1); trivial.\nunfold Bezout. solve_proper.\nclear m Hm. intros m Hm IHm.\ndestruct (lt_trichotomy n m) as [LT|[EQ|LT]].\n\ndestruct (IHm (m-n)) as ((a & b & EQ), (a' & b' & EQ')).\nrewrite one_succ, le_succ_l.\napply lt_add_lt_sub_l; now nzsimpl.\napply sub_lt; order'.\nsplit.\nexists (a+b). exists b.\nrewrite mul_add_distr_r, EQ, mul_sub_distr_l, <- add_assoc.\nrewrite gcd_sub_diag_r by order.\nrewrite sub_add. reflexivity. apply mul_le_mono_l; order.\nexists a'. exists (a'+b').\nrewrite gcd_sub_diag_r in EQ' by order.\nrewrite (add_comm a'), mul_add_distr_r, add_assoc, <- EQ'.\nrewrite mul_sub_distr_l, sub_add. reflexivity. apply mul_le_mono_l; order.\n\nrewrite EQ. rewrite gcd_diag.\nsplit.\nexists 1. exists 0. now nzsimpl.\nexists 1. exists 0. now nzsimpl.\n\nrewrite gcd_comm, and_comm.\napply IHn; trivial.\nnow rewrite <- le_succ_l, <- one_succ.\nQed.\n\nLemma gcd_bezout_pos : forall n m, 0<n -> Bezout n m (gcd n m).\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gcd_bezout_pos\".  \nintros n m Hn.\ndestruct (eq_0_gt_0_cases m) as [EQ|LT].\nrewrite EQ, gcd_0_r. exists 1. exists 0. now nzsimpl.\nnow apply gcd_bezout_pos_pos.\nQed.\n\n\n\nLemma gcd_bezout : forall n m,\nBezout n m (gcd n m) \\/ Bezout m n (gcd n m).\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gcd_bezout\".  \nintros n m.\ndestruct (eq_0_gt_0_cases n) as [EQ|LT].\nright. rewrite EQ, gcd_0_l. exists 1. exists 0. now nzsimpl.\nleft. now apply gcd_bezout_pos.\nQed.\n\nLemma gcd_mul_mono_l :\nforall n m p, gcd (p * n) (p * m) == p * gcd n m.\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gcd_mul_mono_l\".  \nintros n m p.\napply gcd_unique'.\napply mul_divide_mono_l, gcd_divide_l.\napply mul_divide_mono_l, gcd_divide_r.\nintros q H H'.\ndestruct (eq_0_gt_0_cases n) as [EQ|LT].\nrewrite EQ in *. now rewrite gcd_0_l.\ndestruct (gcd_bezout_pos n m) as (a & b & EQ); trivial.\napply divide_add_cancel_r with (p*m*b).\nnow apply divide_mul_l.\nrewrite <- mul_assoc, <- mul_add_distr_l, add_comm, (mul_comm m), <- EQ.\nrewrite (mul_comm a), mul_assoc.\nnow apply divide_mul_l.\nQed.\n\nLemma gcd_mul_mono_r :\nforall n m p, gcd (n*p) (m*p) == gcd n m * p.\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gcd_mul_mono_r\".  \nintros. rewrite !(mul_comm _ p). apply gcd_mul_mono_l.\nQed.\n\nLemma gauss : forall n m p, (n | m * p) -> gcd n m == 1 -> (n | p).\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.gauss\".  \nintros n m p H G.\ndestruct (eq_0_gt_0_cases n) as [EQ|LT].\nrewrite EQ in *. rewrite gcd_0_l in G. now rewrite <- (mul_1_l p), <- G.\ndestruct (gcd_bezout_pos n m) as (a & b & EQ); trivial.\nrewrite G in EQ.\napply divide_add_cancel_r with (m*p*b).\nnow apply divide_mul_l.\nrewrite (mul_comm _ b), mul_assoc. rewrite <- (mul_1_l p) at 2.\nrewrite <- mul_add_distr_r, add_comm, <- EQ.\nnow apply divide_mul_l, divide_factor_r.\nQed.\n\nLemma divide_mul_split : forall n m p, n ~= 0 -> (n | m * p) ->\nexists q r, n == q*r /\\ (q | m) /\\ (r | p).\nProof. hammer_hook \"NGcd\" \"NGcd.NGcdProp.divide_mul_split\".  \nintros n m p Hn H.\nassert (G := gcd_nonneg n m). le_elim G.\ndestruct (gcd_divide_l n m) as (q,Hq).\nexists (gcd n m). exists q.\nsplit. now rewrite mul_comm.\nsplit. apply gcd_divide_r.\ndestruct (gcd_divide_r n m) as (r,Hr).\nrewrite Hr in H. rewrite Hq in H at 1.\nrewrite mul_shuffle0 in H. apply mul_divide_cancel_r in H; [|order].\napply gauss with r; trivial.\napply mul_cancel_r with (gcd n m); [order|].\nrewrite mul_1_l.\nrewrite <- gcd_mul_mono_r, <- Hq, <- Hr; order.\nsymmetry in G. apply gcd_eq_0 in G. destruct G as (Hn',_); order.\nQed.\n\n\n\n\n\nEnd NGcdProp.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Numbers/Natural/Abstract/NGcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7137969079694353}}
{"text": "(** * Utheory.v: Specification of [U], interval [ [0,1] ] *)\n\nAdd Rec LoadPath \".\" as ALEA.\n\nRequire Export Misc.\nRequire Export Ccpo.\nSet Implicit Arguments.\nOpen Local Scope O_scope.\n\n(** ** Basic operators of U *)\n(** \n    - Constants : [0] and [1]\n    - Constructor : [ [1/1+] n ] $(\\equiv \\frac{1}{n+1})$ #(=1/(1+n))#\n    - Operations : [x+y] (=min (x+y,1)), [x*y], [ [1-] x]\n    - Relations : [x <= y], [x==y]\n*)\n\nModule Type Universe.\nParameter U : Type.\nGeneralizable All Variables.\nDeclare Instance ordU: ord U.\nDeclare Instance cpoU: cpo U.\nBind Scope U_scope with U.\nDelimit Scope U_scope with U.\n\nParameters Uplus Umult Udiv: U -> U -> U.\nParameter Uinv : U -> U.\nParameter Unth : nat -> U.\n\n\nInfix \"+\" := Uplus : U_scope.\nInfix \"*\"  := Umult  : U_scope.\nInfix \"/\"  := Udiv  : U_scope.\nNotation \"[1-]  x\" := (Uinv x)  (at level 35, right associativity) : U_scope.\n\nNotation \"[1/]1+ n\" := (Unth n) (at level 35, right associativity) : U_scope.\nOpen Local Scope U_scope.\n\nDefinition U1 : U := [1-] 0. \nNotation \"1\" := U1 : U_scope.\nNotation \"0\" := (@D0 U ordU cpoU) : U_scope.\n\n(** ** Basic Properties *)\n\nHypothesis Udiff_0_1 : ~ 0 == 1.\n(*\nHypothesis Unit : forall x:U, x <= 1. \n*)\n\nHypothesis Uplus_sym : forall x y:U, x + y == y + x.\nHypothesis Uplus_assoc : forall x y z:U, x + (y + z) == x + y + z.\nHypothesis Uplus_zero_left : forall x:U, 0 + x == x.\n\nHypothesis Umult_sym : forall x y:U, x * y == y * x.\nHypothesis Umult_assoc : forall x y z:U, x * (y * z) == x * y * z.\nHypothesis Umult_one_left : forall x:U, 1 * x == x.\n\nHypothesis Uinv_one : [1-] 1 == 0. \n\n(*\nHypothesis Uinv_opp_left : forall x, [1-] x + x == 1.\n*)\n\nHypothesis Umult_div : forall x y, ~ 0 == y -> x <= y -> y * (x/y) == x.\nHypothesis Udiv_le_one : forall x y,  ~ 0 == y -> y <= x -> (x/y) == 1.\nHypothesis Udiv_by_zero : forall x y,  0 == y -> (x/y) == 0.\n\n(** - Property  : [1 - (x + y) + x = 1 - y ] holds when [x+y] does not overflow *)\nHypothesis Uinv_plus_left : forall x y, y <= [1-] x -> [1-] (x + y) + x == [1-] y.\n\n(** - Property  : [(x + y) * z  = x * z + y * z] holds when [x+y] does not overflow *)\nHypothesis Udistr_plus_right : forall x y z, x <= [1-] y -> (x + y) * z == x * z + y * z.\n\n(** - Property  : [1 - (x  y) = (1 - x) * y + (1-y) ] *)\nHypothesis Udistr_inv_right : forall x y:U,  [1-] (x * y) == ([1-] x) * y + [1-] y.\n\n(** - Totality of the order *)\nHypothesis Ule_class : forall x y : U, class (x <= y).\n\nHypothesis Ule_total : forall x y : U, orc (x <= y) (y <= x).\nImplicit Arguments Ule_total [].\n\n(** - The relation [x <=  y] is compatible with operators *)\n\nDeclare Instance Uplus_mon_right :forall x,monotonic (Uplus x).\n\n(* Instance Uplus_mon_right : forall x, monotonic (Uplus x). *)\n\nDeclare Instance Umult_mon_right : forall x, monotonic (Umult x).\n(* Instance Umult_mon_right : forall x, monotonic (Umult x). *)\n\nHypothesis Uinv_le_compat : forall x y:U, x <= y -> [1-] y <= [1-] x.\n\n(** - Properties of simplification in case there is no overflow *)\nHypothesis Uplus_le_simpl_right : forall x y z, z <= [1-] x -> x + z <= y + z -> x <= y.\n\nHypothesis Umult_le_simpl_left : forall x y z: U, ~ 0 == z -> z * x <= z * y -> x <= y .\n\n(** -  Property of [Unth]: [1 / n+1 == 1 - n  * (1/n+1)] *)\nHypothesis Unth_prop : forall n, [1/]1+n == [1-](compn Uplus 0 (fun k => [1/]1+n) n).\n\n(** - Archimedian property *)\nHypothesis archimedian : forall x, ~0 == x -> exc (fun n => [1/]1+n <= x).\n\n(** - Stability properties of lubs with respect to [+] and [*] *)\n\nHypothesis Uplus_right_continuous : forall k, continuous (mon (Uplus k)).\nHypothesis Umult_right_continuous : forall k, continuous (mon (Umult k)).\n\nEnd Universe.\n\nDeclare Module Univ:Universe.\nExport Univ.\n\nHint Resolve Udiff_0_1 Unth_prop.\nHint Resolve Uplus_sym Uplus_assoc Umult_sym Umult_assoc.\nHint Resolve Uinv_one  Uinv_plus_left Umult_div Udiv_le_one Udiv_by_zero.\nHint Resolve Uplus_zero_left Umult_one_left Udistr_plus_right Udistr_inv_right.\nHint Resolve Uplus_mon_right Umult_mon_right Uinv_le_compat.\nHint Resolve lub_le le_lub Uplus_right_continuous Umult_right_continuous. \n(* lub_eq_mult lub_eq_plus_cte_left.*)\nHint Resolve Ule_total Ule_class.\n\n", "meta": {"author": "hivert", "repo": "Coq-HookLength", "sha": "f9f044a6defdeea7db48d8fe38735c32129cd928", "save_path": "github-repos/coq/hivert-Coq-HookLength", "path": "github-repos/coq/hivert-Coq-HookLength/Coq-HookLength-f9f044a6defdeea7db48d8fe38735c32129cd928/ALEA/src/Utheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8267117855317473, "lm_q1q2_score": 0.7137760282124299}}
{"text": "(** * Decide: Programming with Decision Procedures *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom VFA Require Import Perm.\n\n(* ################################################################# *)\n(** * Using [reflect] to characterize decision procedures *)\n\n(** Thus far in _Verified Functional Algorithms_ we have been using\n   - propositions ([Prop]) such as [a<b] (which is Notation for [lt a b])\n   - booleans ([bool]) such as [a<?b] (which is Notation for [ltb a b]). *)\n\nCheck Nat.lt.  (* : nat -> nat -> Prop *)\nCheck Nat.ltb.  (* : nat -> nat -> bool *)\n\n(** The [Perm] chapter defined a tactic called [bdestruct] that\n    does case analysis on (x <? y) while giving you hypotheses (above\n    the line) of the form (x<y).   This tactic is built using the [reflect] \n    type and the [blt_reflect] theorem. *)\n\nPrint reflect.\n(* Inductive reflect (P : Prop) : bool -> Set :=\n    | ReflectT : P -> reflect P true \n    | ReflectF : ~ P -> reflect P false  *)\n\nCheck blt_reflect.  (* : forall x y, reflect (x<y) (x <? y) *)\n\n(** The name [reflect] for this type is a reference to _computational\n   reflection_,  a technique in logic.  One takes a logical formula, or \n   proposition, or predicate,  and designs a syntactic embedding of \n   this formula as an \"object value\" in the logic.  That is, _reflect_ the\n   formula back into the logic. Then one can design computations \n   expressible inside the logic that manipulate these syntactic object \n   values.  Finally, one proves that the computations make transformations\n   that are equivalent to derivations (or equivalences) in the logic.\n\n   The first use of computational reflection was by Goedel, in 1931:\n   his syntactic embedding encoded formulas as natural numbers, a \n   \"Goedel numbering.\"  The second and third uses of reflection were\n   by Church and Turing, in 1936: they encoded (respectively) \n   lambda-expressions and Turing machines.\n\n   In Coq it is easy to do reflection, because the Calculus of Inductive\n   Constructions (CiC) has Inductive data types that can easily encode \n   syntax trees.  We could, for example, take some of our propositional \n   operators such as [and], [or], and make an [Inductive] type that is an \n   encoding of these, and build a computational reasoning system for\n   boolean satisfiability.\n\n   But in this chapter I will show something much simpler.  When \n   reasoning about less-than comparisons on natural numbers, we have\n   the advantage that [nat] already an inductive type; it is \"pre-reflected,\"\n   in some sense.  (The same for [Z], [list], [bool], etc.)  *)\n\n(** Now, let's examine how [reflect] expresses the coherence between\n  [lt] and [ltb]. Suppose we have a value [v] whose type is \n  [reflect (3<7) (3<?7)].  What is [v]?  Either it is\n  - ReflectT [P] (3<?7), where [P] is a proof of [3<7],  and [3<?7] is [true], or\n  - ReflectF [Q] (3<?7), where [Q] is a proof of [~(3<7)], and [3<?7] is [false].\n  In the case of [3,7], we are well advised to use [ReflectT], because\n   (3<?7) cannot match the [false] required by [ReflectF]. *)\n\nGoal (3<?7 = true). Proof. reflexivity. Qed.\n\n(** So [v] cannot be [ReflectF Q (3<?7)] for any [Q], because that would\n   not type-check.  Now, the next question:  must there exist a value\n   of type [reflect (3<7) (3<?7)]  ?  The answer is yes; that is the\n   [blt_reflect] theorem.  The result of [Check blt_reflect], above, says that\n   for any [x,y], there does exist a value (blt_reflect x y) whose type\n   is exactly [reflect (x<y)(x<?y)].     So let's look at that value!  That is,\n   examine what [H], and [P], and [Q] are equal to at \"Case 1\" and \"Case 2\": *)\n\nTheorem three_less_seven_1: 3<7.\nProof.\nassert (H := blt_reflect 3 7).\nremember (3<?7) as b.\ndestruct H as [P|Q] eqn:?.\n* (* Case 1: H = ReflectT (3<7) P *)\napply P.\n* (* Case 2: H = ReflectF (3<7) Q *)\ncompute in Heqb.\ninversion Heqb.\nQed.\n\n(** Here is another proof that uses [inversion] instead of [destruct].\n   The [ReflectF] case is eliminated automatically by [inversion]\n   because [3<?7] does not match [false]. *)\n\nTheorem three_less_seven_2: 3<7.\nProof.\nassert (H := blt_reflect 3 7).\ninversion H as [P|Q].\napply P.\nQed.\n\n(** The [reflect] inductive data type is a way of relating a _decision\n   procedure_ (a function from X to [bool]) with a predicate (a function\n   from X to [Prop]).   The convenience of [reflect], in the verification\n   of functional programs, is that we can do [destruct (blt_reflect a b)],\n   which relates [a<?b] (in the program) to the [a<b] (in the proof).\n   That's just how the [bdestruct] tactic works; you can go back\n   to [Perm.v] and examine how it is implemented in the [Ltac]\n   tactic-definition language. *)\n\n(* ################################################################# *)\n(** * Using [sumbool] to Characterize Decision Procedures *)\n\nModule ScratchPad.\n\n(** An alternate way to characterize decision procedures,\n   widely used in Coq, is via the inductive type [sumbool].\n\n   Suppose [Q]  is a proposition, that is, [Q: Prop].  We say [Q] is\n   _decidable_ if there is an algorithm for computing a proof of\n   [Q] or [~Q].  More generally, when [P] is a predicate (a function \n   from some type [T] to [Prop]), we say [P] is decidable when \n   [forall x:T, decidable(P)].\n\n   We represent this concept in Coq by an inductive datatype: *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B\n | right : B -> sumbool A B.\n\n(** Let's consider [sumbool] applied to two propositions: *)\n\nDefinition t1 := sumbool (3<7) (3>2).\nLemma less37: 3<7. Proof. omega. Qed.\nLemma greater23: 3>2. Proof. omega. Qed.\n\nDefinition v1a: t1 := left (3<7) (3>2) less37.\nDefinition v1b: t1 := right (3<7) (3>2) greater23.\n\n(** A value of type [sumbool (3<7) (3>2)] is either one of:\n  - [left] applied to a proof of (3<7), or\n  - [right] applied to a proof of (3>2).   *)\n\n(** Now let's consider: *)\n\nDefinition t2 := sumbool (3<7) (2>3).\nDefinition v2a: t2 := left (3<7) (2>3) less37.\n\n(** A value of type [sumbool (3<7) (2>3)] is either one of:\n  - [left] applied to a proof of (3<7), or\n  - [right] applied to a proof of (2>3).\n  But since there are no proofs of 2>3, only [left] values (such as [v2a])\n  exist.  That's OK. *)\n\n(** [sumbool] is in the Coq standard library, where there is [Notation] \n   for it:  the expression [ {A}+{B} ] means [sumbool A B]. *)\n\nNotation \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\n(** A very common use of [sumbool] is on a proposition and its negation.\n   For example, *)\n\nDefinition t4 := forall a b, {a<b}+{~(a<b)}.\n\n(** That expression, [forall a b, {a<b}+{~(a<b)}], says that for any \n natural numbers [a] and [b], either [a<b] or [a>=b].  But it is _more_\n than that!  Because [sumbool] is an Inductive type with two constructors\n [left] and [right], then given the [{3<7}+{~(3<7)}] you can pattern-match\n on it and learn _constructively_ which thing is true.  *)\n\nDefinition v3: {3<7}+{~(3<7)} := left _ _ less37.\n\nDefinition is_3_less_7:  bool :=\n match v3 with\n | left _ _ _ => true\n | right _ _ _ => false\n end.\n\nEval compute in is_3_less_7. (* = true : bool *)\n\nPrint t4.  (* = forall a b : nat, {a < b} + {~ a < b} *)\n\n(** Suppose there existed a value [lt_dec] of type [t4].  That would be a \n  _decision procedure_ for the less-than function on natural numbers.\n  For any nats [a] and [b], you could calculate [lt_dec a b], which would\n  be either [left ...] (if [a<b] was provable) or [right ...] (if [~(a<b)] was\n  provable).\n\n  Let's go ahead and implement [lt_dec].  We can base it on the function\n  [ltb: nat -> nat -> bool] which calculates whether [a] is less than [b],\n  as a boolean.  We already have a theorem that this function on booleans\n  is related to the proposition [a<b]; that theorem is called [blt_reflect]. *)\n\nCheck blt_reflect.  (* : forall x y, reflect (x<y) (x<?y) *)\n\n(** It's not too hard to use [blt_reflect] to define [lt_dec] *)\n\nDefinition lt_dec (a: nat) (b: nat) : {a<b}+{~(a<b)} :=\nmatch blt_reflect a b with\n| ReflectT _ P => left (a < b) (~ a < b) P\n| ReflectF _ Q => right (a < b) (~ a < b) Q\nend.\n\n(** Another, equivalent way to define [lt_dec] is to use \n     definition-by-tactic: *)\n\nDefinition lt_dec' (a: nat) (b: nat) : {a<b}+{~(a<b)}.\n  destruct (blt_reflect a b) as [P|Q]. left. apply P.  right. apply Q.\nDefined.\n\nPrint lt_dec.\nPrint lt_dec'.\n\nTheorem lt_dec_equivalent: forall a b, lt_dec a b = lt_dec' a b.\nProof.\nintros.\nunfold lt_dec, lt_dec'.\nreflexivity.\nQed.\n\n(** Warning: these definitions of [lt_dec] are not as nice as the\n  definition in the Coq standard library, because these are not\n  fully computable.  See the discussion below. *)\n\nEnd ScratchPad.\n\n(* ================================================================= *)\n(** ** [sumbool] in the Coq Standard Library *)\n\nModule ScratchPad2.\nLocate sumbool. (* Coq.Init.Specif.sumbool *)\nPrint sumbool.\n\n(** The output of [Print sumbool] explains that the first two arguments \n   of [left] and [right] are implicit.  We use them as follows (notice that\n   [left] has only one explicit argument [P]:  *)\n\nDefinition lt_dec (a: nat) (b: nat) : {a<b}+{~(a<b)} :=\nmatch blt_reflect a b with\n| ReflectT _ P => left P\n| ReflectF _ Q => right Q\nend.\n\nDefinition le_dec (a: nat) (b: nat) : {a<=b}+{~(a<=b)} :=\nmatch ble_reflect a b with\n| ReflectT _ P => left P\n| ReflectF _ Q => right Q\nend.\n\n(** Now, let's use [le_dec] directly in the implementation of insertion\n   sort, without mentioning [ltb] at all. *)\n\nFixpoint insert (x:nat) (l: list nat) := \n  match l with\n  | nil => x::nil\n  | h::t => if le_dec x h then x::h::t else h :: insert x t\n end.\n\nFixpoint sort (l: list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h::t => insert h (sort t)\nend.\n\nInductive sorted: list nat -> Prop := \n| sorted_nil:\n    sorted nil\n| sorted_1: forall x,\n    sorted (x::nil)\n| sorted_cons: forall x y l,\n   x <= y -> sorted (y::l) -> sorted (x::y::l).\n\n(** **** Exercise: 2 stars (insert_sorted_le_dec)  *)\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (insert a l).\nProof.\n  intros a l H.\n  induction H.\n  - constructor.\n  - unfold insert.\n    destruct (le_dec a x) as [ Hle | Hgt].\n\n   (** Look at the proof state now.  In the first subgoal, we have\n      above the line, [Hle: a <= x].  In the second subgoal, we have\n      [Hgt: ~ (a < x)].  These are put there automatically by the \n      [destruct (le_dec a x)].  Now, the rest of the proof can proceed\n      as it did in [Sort.v], but using [destruct (le_dec _ _)] instead of\n      [bdestruct (_ <=? _)]. *)\n\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Decidability and Computability *)\n\n(** Before studying the rest of this chapter, it is helpful to study the\n   [ProofObjects] chapter of _Software Foundations volume 1_ if you\n   have not done so already.\n\n   A predicate [P: T->Prop] is _decidable_ if there is a computable\n   function [f: T->bool] such that, forall [x:T], [f x = true <-> P x].\n   The second and most famous example of an _undecidable_ predicate\n   is the Halting Problem (Turing, 1936): [T] is the type of Turing-machine\n   descriptions, and [P(x)] is, Turing machine [x] halts.  The first, and not\n   as famous, example is due to Church, 1936 (six months earlier): test\n   whether a lambda-expression has a normal form.  In 1936-37, as a \n   first-year PhD student before beginning his PhD thesis work, Turing\n   proved these two problems are equivalent.\n\n   Classical logic contains the axiom [forall P, P \\/ ~P].  This is not provable\n   in core Coq, that is, in the bare Calculus of Inductive Constructions.  But\n   its negation is not provable either.   You could add this axiom to Coq\n   and the system would still be consistent (i.e., no way to prove [False]).\n\n   But [P \\/ ~P] is a weaker statement than [ {P}+{~P} ], that is,\n   [sumbool P (~P)].  From [ {P}+{~P} ] you can actually _calculate_ or\n   [compute] either [left (x:P)] or [right(y: ~P)].     From [P \\/ ~P] you cannot \n   [compute] whether [P] is true.  Yes, you can [destruct] it in a proof, \n   but not in a calculation.  \n\n   For most purposes its unnecessary to add the axiom [P \\/ ~P] to Coq,\n   because for specific predicates there's a specific way to prove [P \\/ ~P]\n   as a theorem.  For example,  less-than on natural numbers is decidable,\n   and the existence of [blt_reflect] or [lt_dec] (as a theorem, not as an axiom)\n   is a demonstration of that.\n\n   Furthermore, in this \"book\" we are interested in _algorithms_.  An axiom\n   [P \\/ ~P] does not give us an algorithm to compute whether P is true.  As\n   you saw in the definition of [insert] above, we can use [lt_dec] not only as\n   a theorem that either [3<7] or [~(3<7)], we can use it as a function to\n   compute whether [3<7].  In Coq, you can't compute with axioms!\n   Let's try it: *)\n\nAxiom lt_dec_axiom_1:  forall i j: nat, i<j \\/ ~(i<j).\n\n(** Now, can we use this axiom to compute with?  *)\n\n(* Uncomment and try this: \nDefinition max (i j: nat) : nat :=\n   if lt_dec_axiom_1 i j then j else i.\n*)\n\n(** That doesn't work, because an [if] statement requires an [Inductive]\n  data type with exactly two constructors; but [lt_dec_axiom_1 i j] has\n  type [i<j \\/ ~(i<j)],  which is not Inductive.  But let's try a different axiom: *)\n\nAxiom lt_dec_axiom_2:  forall i j: nat, {i<j} + {~(i<j)}.\n\nDefinition max_with_axiom (i j: nat) : nat :=\n   if lt_dec_axiom_2 i j then j else i.\n\n(** This typechecks, because [lt_dec_axiom_2 i j]  belongs to type\n     [sumbool (i<j) (~(i<j))]   (also written [ {i<j} + {~(i<j)} ]), which does have\n     two constructors.\n\n     Now, let's use this function: *)\n\nEval compute in max_with_axiom 3 7.\n  (*  = if lt_dec_axiom_2 3 7 then 7 else 3\n     : nat *)\n\n(** This [compute] didn't compute very much!  Let's try to evaluate it\n    using [unfold]: *)\n\nLemma prove_with_max_axiom:   max_with_axiom 3 7 = 7.\nProof.\nunfold max_with_axiom.\ntry reflexivity.  (* does not do anything, reflexivity fails *)\n(* uncomment this line and try it: \n   unfold lt_dec_axiom_2.\n*)\ndestruct (lt_dec_axiom_2 3 7).\nreflexivity.\ncontradiction n. omega.\nQed.\n\n(** It is dangerous to add Axioms to Coq: if you add one that's inconsistent,\n   then it leads to the ability to prove [False].  While that's a convenient way\n   to get a lot of things proved, it's unsound; the proofs are useless.  \n\n   The Axioms above, [lt_dec_axiom_1] and [lt_dec_axiom_2], are safe enough:\n   they are consistent.  But they don't help in computation.  Axioms are not\n   useful here. *)\n\nEnd ScratchPad2.\n\n\n(* ################################################################# *)\n(** * Opacity of [Qed] *)\n\n(** This lemma [prove_with_max_axiom] turned out to be _provable_, but the proof\n    could not go by _computation_.  In contrast, let's use [lt_dec], which was built\n    without any axioms: *)\n\nLemma compute_with_lt_dec:  (if ScratchPad2.lt_dec 3 7 then 7 else 3) = 7.\nProof.\ncompute.\n(* uncomment this line and try it:\n   unfold blt_reflect.\n*)\nAbort.\n\n(** Unfortunately, even though [blt_reflect] was proved without any axioms, it\n    is an _opaque theorem_  (proved with [Qed] instead of with [Defined]), and\n    one cannot compute with opaque theorems.  Not only that, but it is proved with\n    other opaque theorems such as [iff_sym] and [Nat.ltb_lt].  If we want to\n    compute with an implementation of [lt_dec] built from [blt_reflect], then\n    we will have to rebuild [blt_reflect] without using [Qed] anywhere, only [Defined].\n\n    Instead, let's use the version of [lt_dec] from the Coq standard library,\n    which _is_ carefully built without any opaque ([Qed]) theorems.\n*)\n\nLemma compute_with_StdLib_lt_dec:  (if lt_dec 3 7 then 7 else 3) = 7.\nProof.\ncompute.\nreflexivity.\nQed.\n\n(** The Coq standard library has many decidability theorems.  You can\n   examine them by doing the following [Search] command. The results\n   shown here are only for the subset of the library that's currently\n   imported (by the [Import] commands above); there's even more out there. *)\n\nSearch ({_}+{~_}).\n(*\nreflect_dec: forall (P : Prop) (b : bool), reflect P b -> {P} + {~ P}\nlt_dec: forall n m : nat, {n < m} + {~ n < m}\nlist_eq_dec:\n  forall A : Type,\n  (forall x y : A, {x = y} + {x <> y}) ->\n  forall l l' : list A, {l = l'} + {l <> l'}\nle_dec: forall n m : nat, {n <= m} + {~ n <= m}\nin_dec:\n  forall A : Type,\n  (forall x y : A, {x = y} + {x <> y}) ->\n  forall (a : A) (l : list A), {In a l} + {~ In a l}\ngt_dec: forall n m : nat, {n > m} + {~ n > m}\nge_dec: forall n m : nat, {n >= m} + {~ n >= m}\neq_nat_decide: forall n m : nat, {eq_nat n m} + {~ eq_nat n m}\neq_nat_dec: forall n m : nat, {n = m} + {n <> m}\nbool_dec: forall b1 b2 : bool, {b1 = b2} + {b1 <> b2}\nZodd_dec: forall n : Z, {Zodd n} + {~ Zodd n}\nZeven_dec: forall n : Z, {Zeven n} + {~ Zeven n}\nZ_zerop: forall x : Z, {x = 0%Z} + {x <> 0%Z}\nZ_lt_dec: forall x y : Z, {(x < y)%Z} + {~ (x < y)%Z}\nZ_le_dec: forall x y : Z, {(x <= y)%Z} + {~ (x <= y)%Z}\nZ_gt_dec: forall x y : Z, {(x > y)%Z} + {~ (x > y)%Z}\nZ_ge_dec: forall x y : Z, {(x >= y)%Z} + {~ (x >= y)%Z}\n*)\n\n(** The type of [list_eq_dec] is worth looking at.  It says that if you\n     have  a decidable equality for an element type [A], then\n    [list_eq_dec] calculates for you a decidable equality for type [list A].\n    Try it out: *)\n\nDefinition list_nat_eq_dec: \n    (forall al bl : list nat, {al=bl}+{al<>bl}) :=\n  list_eq_dec eq_nat_dec.\n\nEval compute in if list_nat_eq_dec [1;3;4] [1;4;3] then true else false.\n (* = false : bool *)\n\nEval compute in if list_nat_eq_dec [1;3;4] [1;3;4] then true else false.\n (* = true : bool *)\n\n(** **** Exercise: 2 stars (list_nat_in)  *)\n(** Use [in_dec] to build this function. *)\n\nDefinition list_nat_in: forall (i: nat) (al: list nat), {In i al}+{~ In i al}\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample in_4_pi:  (if list_nat_in 4  [3;1;4;1;5;9;2;6] then true else false) = true.\nProof.\nsimpl.\n(* reflexivity. *)\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** In general, beyond [list_eq_dec] and [in_dec], one can construct a\n     whole programmable calculus of decidability, using the\n     programs-as-proof  language of Coq.  But is it a good idea?  Read on! *)\n\n(* ################################################################# *)\n(** * Advantages and Disadvantages of [reflect] Versus [sumbool] *)\n\n(** I have shown two ways to program decision procedures in Coq,\n    one using [reflect] and the other using [{_}+{~_}], i.e., [sumbool].\n\n   - With [sumbool], you define _two_ things: the operator in [Prop]\n      such as [lt: nat -> nat -> Prop] and the decidability \"theorem\"\n      in [sumbool], such as [lt_dec: forall i j, {lt i j}+{~ lt i j}].  I say\n      \"theorem\" in quotes because it's not _just_ a theorem, it's also\n      a (nonopaque) computable function.\n\n   - With [reflect], you define _three_ things:  the operator in [Prop],\n      the operator in [bool] (such as [ltb: nat -> nat -> bool], and the\n      theorem that relates them (such as [ltb_reflect]).  \n\n   Defining three things seems like more work than defining two.\n   But it may be easier and more efficient.  Programming in [bool],\n   you may have more control over how your functions are implemented,\n   you will have fewer difficult uses of dependent types, and you\n   will run into fewer difficulties with opaque theorems.\n\n   However, among Coq programmers, [sumbool] seems to be more\n   widely used, and it seems to have better support in the Coq standard\n   library.  So you may encounter it, and it is worth understanding what\n   it does.   Either of these two methods is a reasonable way of programming\n   with proof.  *)\n\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/libs/vfa/Decide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7137496627372293}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := mult lf2 x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj245_coqofml_Jov0DE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7136162659275425}}
{"text": "Require Import OrderedType.\nRequire Import Arith.\n \nModule NatOrder <: OrderedType.\n  Definition t := nat. \n\n  (* \n  Definition eq (A:Type) := eq A.  \n  Definition lt := lt. \n  *) \n\n  Definition eq_refl : forall x : t, x = x.\n  Proof. \n    auto. \n  Defined.\n  \n  Definition eq_sym : forall x y : t, eq x y -> eq y x.\n  Proof.\n    auto.\n  Defined.\n\n  Definition eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n  Proof.\n    congruence.\n  Defined.\n\n  Require Import Omega.\n  Definition lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof. \n    intros ; omega.\n  Defined.\n  \n  Definition lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof. \n    intros ; omega.\n  Defined. \n\n  Definition eq := eq (A:=nat).  \n  Definition lt := lt. \n  Hint Unfold eq.\n  Hint Unfold lt.\n\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof. \n    intros. case (lt_eq_lt_dec x y) ; firstorder.\n  Defined.\n  \nEnd NatOrder.", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/poitin-coq/NatOrdered.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7799929053683039, "lm_q1q2_score": 0.7136162540092101}}
{"text": "Require Import Coq.micromega.Lia.\nRequire Import Coq.NArith.NArith.\n\nModule N.\n  Lemma testbit_ones n i : N.testbit (N.ones n) i = N.ltb i n.\n  Proof using Type.\n    pose proof N.ones_spec_iff n i.\n    destruct (N.testbit _ _) eqn:? in*; destruct (N.ltb_spec i n); trivial.\n    { pose proof (proj1 H eq_refl); lia. }\n    { pose proof (proj2 H H0). inversion H1. }\n  Qed.\n\n  Lemma ones_min m n : N.ones (N.min m n) = N.land (N.ones m) (N.ones n).\n  Proof using Type.\n    eapply N.bits_inj_iff; intro i.\n    rewrite N.land_spec.\n    rewrite !N.testbit_ones.\n    destruct (N.ltb_spec0 i (N.min m n));\n      destruct (N.ltb_spec0 i m);\n      destruct (N.ltb_spec0 i n);\n      try reflexivity;\n      lia.\n  Qed.\nEnd N.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/NUtil/Testbit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.71361625400921}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) (lf1 : natural)\n  : natural := mult x lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj194_coqofml_xo1OEO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7136162529499008}}
{"text": "(*|\n#############################\nProof by contradiction in Coq\n#############################\n\n:Link: https://stackoverflow.com/q/71945260\n|*)\n\n(*|\nQuestion\n********\n\nI am trying to understand the apparent paradox of the logical\nframework of theorem provers like Coq not including LEM yet also being\nable to construct proofs by contradiction. Specifically the\nintuitionistic type theory that these theorem provers are based on\ndoes not allow for any logical construction of the form ``￢(￢P)⇒P``,\nand so what is required in order to artificially construct this in a\nlanguage like Coq? And how is the constructive character of the system\npreserved if this is allowed?\n|*)\n\n(*|\nAnswer (Arthur Azevedo De Amorim)\n*********************************\n\nI think you are mixing up two related uses of contradiction in logic.\nOne is the technique of *proof by contradiction*, which says that you\ncan prove ``P`` by proving ``~ (~ P)`` -- that is, by showing that ``~\nP`` entails a contradiction. This technique is actually *not*\navailable in general in constructive logics like Coq, unless one of\nthe following applies.\n\n1. You add the excluded middle ``forall P, P \\/ ~ P`` as an axiom. Coq\n   supports this, but this addition means that you are not working in\n   a constructive logic anymore.\n2. The proposition ``P`` is known to be decidable (i.e., ``P \\/ ~ P``\n   holds). This is the case, for example, for the equality of two\n   natural numbers ``n`` and ``m``, which we can prove by induction.\n3. The proposition ``P`` is of the form ``~ Q``. Since ``Q -> ~ (~\n   Q)`` holds constructively, by the law of contrapositives (which is\n   also valid constructively), we obtain ``~ (~ (~ Q)) -> (~ Q)``.\n\nThe other use of contradiction is the `principle of explosion\n<https://en.wikipedia.org/wiki/Principle_of_explosion>`__, which says\nthat anything follows once you assume a contradiction (i.e., ``False``\nin Coq). Unlike proof by contradiction, the principle of explosion is\n*always* valid in constructive logic, so there is no paradox here.\n|*)\n\n(*|\nAnswer (L. Garde)\n*****************\n\nIn constructive logic, by definition, a contradiction is an inhabitant\nof the empty type ``0``, and, also by definition, the negation ``￢P``\nof a proposition ``P`` is a function of type: ``P -> 0`` that gives an\ninhabitant of the empty type ``0`` from an inhabitant (a proof) of\n``P``.\n\nIf you assume an inhabitant (proof) of ``P``, and derive\nconstructively an inhabitant of ``0``, you have defined a function\ninhabiting the type ``P -> 0``, i.e. a proof of ``￢P``. This is a\nconstructive sort of proof by contradiction: assume ``P``, derive a\ncontradiction, conclude ``￢P``.\n\nNow if you assume ``￢P`` and derive a contradiction, you have a\nconstructive proof of ``￢￢P``, but cannot conclude constructively\nthat you have a proof of ``P``: for this you need the LEM axiom.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/proof-by-contradiction-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937771, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7136126819579846}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Main.\n\n(** Monoids are categories. *)\nRecord Monoid : Type :=\n{\n  Mon_car : Type;\n\n  Mon_op : Mon_car → Mon_car → Mon_car;\n\n  Mon_assoc : ∀ a b c, Mon_op a (Mon_op b c) = Mon_op (Mon_op a b) c;\n\n  Mon_unit : Mon_car;\n\n  Mon_unit_left : ∀ a, Mon_op Mon_unit a = a;\n\n  Mon_unit_right : ∀ a, Mon_op a Mon_unit = a\n}.\n\nSection Monoid_Cat.\n  Context (M : Monoid).\n\n  Hint Resolve Mon_unit_left Mon_unit_right Mon_assoc : core.\n\n  Program Definition Monoid_Cat : Category :=\n    {|\n      Obj := unit;\n      Hom := fun _ _ => Mon_car M;\n      compose := fun _ _ _ => Mon_op M;\n      id := fun a => Mon_unit M\n    |}.\n\nEnd Monoid_Cat.\n", "meta": {"author": "amintimany", "repo": "Categories", "sha": "1839108875df0107fa4f6061c654003decda2d49", "save_path": "github-repos/coq/amintimany-Categories", "path": "github-repos/coq/amintimany-Categories/Categories-1839108875df0107fa4f6061c654003decda2d49/Archetypal/Monoid_Cat/Monoid_Cat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164656, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.713584646209898}}
{"text": "From Coq Require Import PeanoNat Lia.\n\nTheorem a_pow_4_sub_b_pow_4 : forall a b,\n  a ^ 4 - b ^ 4 = (a - b) * (a + b) * (a ^ 2 + b ^ 2).\nProof.\n  intros.\n  assert (a <= b \\/ a > b) by lia.\n  destruct H.\n  rewrite <- Nat.sub_0_le in H.\n  enough (a ^ 4 - b ^ 4 = 0) by lia.\n  rewrite Nat.sub_0_le in H.\n  assert (a ^ 4 <= b ^ 4).\n  simpl.\n  enough (a * a <= b * b) by nia.\n  nia.\n  rewrite Nat.sub_0_le.\n  exact H0.\n  assert ((a - b) * (a + b) = a * a - b * b) by nia.\n  rewrite H0.\n  simpl.\n  nia.\nQed.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/pow4nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7135846412931995}}
{"text": "Require Import pra.QuoteTerm.\n\n(* Primality of natural numbers *)\nDefinition divides (n m : nat) : Prop := exists k : nat, k <= m /\\ k * n = m.\n\nDefinition prime (n : nat) : Prop :=\n  n > 1 /\\ (forall d : nat, d <= n -> divides d n -> (d = 1 \\/ d = n)).\n\nTheorem prime_test: prime 61.\nProof.\n  unfold prime. unfold divides. Time PRA.\nQed.\n\nTheorem prime_test2: ~(prime 60).\nProof.\n  unfold prime. unfold divides. Time PRA.\nQed.\n\nTheorem prime_test3: ~(prime 100).\nProof.\n  unfold prime. unfold divides. Time PRA.\nQed.\n\nTheorem prime_test4: prime 101.\nProof.\n  unfold prime. unfold divides. Time PRA.\nQed.\n\n\n(* Primality of integers with ZArith *)\nDefinition zdivides (n m : Z) : Prop :=\n  exists k : Z, ((k > 0)%Z /\\ (k <= m)%Z) /\\ (k * n)%Z = m.\n\nDefinition zprime (n : Z) : Prop :=\n  (n > 1)%Z /\\ (forall d : Z,\n  (d > 0)%Z /\\ (d <= n)%Z -> zdivides d n -> (d = 1%Z \\/ d = n)).\n\nTheorem zprime_test: zprime 61.\nProof.\n  unfold zprime. unfold zdivides. Time PRA.\nQed.\n\nTheorem zprime_test2: ~(zprime 60).\nProof.\n  unfold zprime. unfold zdivides. Time PRA.\nQed.\n", "meta": {"author": "jaapb", "repo": "pra", "sha": "2264f4b1b13d50ce5fd4a02b3de3a52986c717a6", "save_path": "github-repos/coq/jaapb-pra", "path": "github-repos/coq/jaapb-pra/pra-2264f4b1b13d50ce5fd4a02b3de3a52986c717a6/theories/prime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7135454338317497}}
{"text": "Require Import Arith.\n\nAxiom todo : forall {A}, A.\n\n(* Tactics needed:\n   [intros], [destruct], [induction], [exists], [apply],\n   [rewrite], [assumption], [contradiction] *)\n\n(* The proof of easy_implication consists in breaking the pair of data\n   stored in hypothesis {n : nat | P n = true} and to\n   instantaeoulsy rebuild a new pair, with the same components,\n   in a different 'container', which lands in sort Prop. *)\nLemma easy_implication (P : nat -> bool) :\n{n : nat | P n = true} -> exists n, P n = true.\nProof.\n  intros [n Pn]. exists n. assumption.\nQed.\n\n(* However the same operation does not work in the opposite\n  direction, because of restricted elimination rules. *)\nLemma harder_implication (P : nat -> bool) :\n  (exists n, P n = true) -> {n : nat | P n = true}.\nProof.\n  intros H. Fail destruct H.\nAbort.\n\nSection Markov.\n\n(* This is what we call a boolean predicate on natural numbers. A\n    witness for P is an (x : nat) for which P x = true. *)\n\nVariable (P : nat -> bool).\n\n(* We should not formalize the existence of a witness for P as:\n   Variable (x : nat).\n   Hypothesis Px : P x = true.\n\n   This is indeed a stronger statement than the exP hypothesis\n   that we use below, since it readily breaks the pair which seemed\n   difficult to break in script harder above... *)\n\nHypothesis exP : exists n, P n = true.\n\n(* The purpose of this exercise is to show that it is still possible\n   to forge a proof term which takes benefit from exP in order to\n   build an instance of the Type-sorted pair, without hitting\n   the restricted elimination barrier.*)\n\n(* The computational content of a statement asserting the\n   existence of an (x : nat) such that P x = true is a search\n   algorithm which terminates with outputting a natural number\n   for which P x = true.*)\n\n(* The harder statement states that from a 'non computational'\n   proof (in sort Prop), possibly using a computational axiom,\n   we can deduce a computational proof  (a search algorithm) that\n   eventually terminates and produces a concrete and correct\n   natural number. This algorithm will be the naive search\n   trying natural numbers one after the other starting from 0\n   and exP the justification that it terminates. We need\n   to turn exP into a data we can compute on by recursion. *)\n\n(* The structure of a proof term of the proposition\n   (acc_nat i) measures the distance from i to a witness for P.\n   By distance we mean the distance between i and a greater or equal\n   number at which P holds. *)\n\n(* Note that this a simplified version of the instance of the\n   Acc accessiblity predicate that could also be used for\n   the purpose of this proof. *)\n\n(* Note that in the AccNatS constructor, we see how\n   values of the parameters can be modified in the arguments of\n   constructors, while being imposed in their conclusion:\n   we use an (acc_nat (S i)) to build a term in (acc_nat i). *)\n\nInductive acc_nat (i : nat) : Prop :=\n  |AccNat0 : P i = true -> acc_nat i\n  |AccNatS : acc_nat (S i) -> acc_nat i.\n\n\n(* The following lemma describes formally the informal intuition\n   described above.  *)\n(* uses plus_Snm_nSm *)\nLemma acc_nat_plus :  forall x n : nat, P (x + n) = true -> acc_nat n.\nProof.\n   intros.\n\tinduction x as [|x' Hx'] in n,H |-*.\n\tapply AccNat0.\n\tapply H.\n\tapply AccNatS.\n\tapply Hx'.\n\trewrite <- plus_Snm_nSm.\n\tapply H.\nQed.\n\n(* In particular we can use exP to show that acc_nat holds at\n   0, since we carefully put the acc_nat predicate in Prop. *)\n(* uses plus_0_r *)\nLemma acc_nat0 : acc_nat 0.\nProof.\n   destruct exP .\n   apply (acc_nat_plus x).\n   rewrite plus_0_r.\n   apply H.\nQed.\n\n(* Now the main step of the proof : if acc_nat holds for an (n : nat),\n   we can compute a value for which P holds. We compute\n   by induction on the proof of (acc_nat n). *)\nLemma find_ex : forall n : nat, acc_nat n -> {m | P m = true}.\nProof.\nfix find_ex 2.\nShow Proof.\n(* we could be tempted to cheat using the seamingly correct\n   correct:\n\n   exact find_ex.\n   Qed.\n\n   but Coq complains because the proof term we just built is\n   a non-terminating recursive function, of the form:\n      fix f n := f n\n   which cannot be accepted without risking consistency troubles... *)\n   intros n accn.\n   \n   case (Bool.bool_dec (P n) true); intros Heq.\n   exists n. assumption.\n   apply (find_ex (S n)).\n   destruct accn.\n   - contradiction.\n   - apply accn.\nQed.\n\n(* We are done: *)\nTheorem Markov : {m | P m = true}.\nProof.\n  \napply todo.\nQed.\n\nEnd Markov.\n\n(* Here is the complete statement we prouved, as available outside\n   of the section. *)\nCheck Markov.\n", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/PA/2021/lecture5_markov.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7134932097530539}}
{"text": "(** ** Section\n他の tactic の説明の前に、Section というコマンドを紹介しましょう。\nSection というのはセクションを作ります。\nFoo というセクションを作るには Section Foo. でセクションを始めて、\nEnd Foo. でセクションを終ります。\nセクションの中では共通する仮定を宣言することができ、\nその仮定に依存した証明は、セクションを終ると、仮定を引数として受け取るように変形されます。\n*)\n\nSection SectionExplanation.\n\nVariable P : Prop.\n(**\nVariable コマンドにより、P が Prop である、つまり何らかの命題Pが存在することが宣言されます。\n*)\n\nLemma LemmaPP': P -> P.\nProof. auto. Qed.\n(**\n何らかの命題 P が存在することを前提を用いて、\nP が成り立つならば P が成り立つことを証明し、その証明に LemmaPP' という名前をつけます。\n*)\n\nPrint LemmaPP'.\n(**\n<<\nLemmaPP' = fun H : P => H\n     : P -> P\n>>\n証明が終った後、セクションを終る前に、\nPrint LemmaPP' とすると、上のように表示されます。\nつまり、LemmaPP' は P型の値Hを受け取ってHを返す関数です。\n*)\n\nEnd SectionExplanation.\n\nPrint LemmaPP'.\n(**\n<<\nLemmaPP' = fun (P : Prop) (H : P) => H\n     : forall P : Prop, P -> P\n>>\nセクションを終ってから再度 Print LemmaPP' とすると、上のように異なる表示になります。\nここでは、命題Pを受け取り、P型の値Hを受け取り、Hを返す関数となっています。\nつまり、セクションの中での LemmaPP' の値の外側に、Pを受け取る関数抽象が追加されています。\n*)\n\n", "meta": {"author": "akr", "repo": "coq-curry-howard", "sha": "37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5", "save_path": "github-repos/coq/akr-coq-curry-howard", "path": "github-repos/coq/akr-coq-curry-howard/coq-curry-howard-37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5/theories/section.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7134300390567624}}
{"text": "(** * Merge:  Merge Sort, With Specification and Proof of Correctness*)\n\nFrom VFA Require Import Perm.\nFrom VFA Require Import Sort.\nFrom Coq Require Import Recdef.  (* needed for [Function] feature *)\n\n(** Mergesort is a well-known sorting algorithm, normally presented\n    as an imperative algorithm on arrays, that has worst-case\n    O(n log n) execution time and requires O(n) auxiliary space.\n\n    The basic idea is simple: we divide the data to be sorted into two\n    halves, recursively sort each of them, and then\n    merge together the (sorted) results from each half:\n\n    [[\n    mergesort xs =\n      split xs into ys,zs;\n      ys' = mergesort ys;\n      zs' = mergesort zs;\n      return (merge ys' zs')\n    ]]\n\n    (As usual, if you are unfamiliar with mergesort see Wikipedia or\n    your favorite algorithms textbook.)\n\n    Mergesort on lists works essentially the same way: we split the\n    original list into two halves, recursively sort each sublist,\n    and then merge the two sublists together again.  The only \n    difference, compared to the imperative algorithm, is that splitting\n    the list takes O(n) rather than O(1) time; however, that \n    does not affect the asymptotic cost, since the merge step already\n    takes O(n) anyhow. \n*)\n\n(* ================================================================= *)\n(** ** Split and its properties *)\n\n(** Let us try to write down the Gallina code for mergesort.\n    The first step is to write a splitting function. There are\n    several ways to do this, since the exact splitting method does\n    not matter as long as the results are (roughly) equal in size.\n    For example, if we know the length of the list, we could use that to split\n    at the half-way point. But here is an attractive alternative, which simply\n    alternates assigning the elements into left and right sublists:\n*)     \n\nFixpoint split {X:Type} (l:list X) : (list X * list X) :=\n  match l with\n  | [] => ([],[])\n  | [x] => ([x],[])\n  | x1::x2::l' =>\n    let (l1,l2) := split l' in\n    (x1::l1,x2::l2)\n  end.\n\n(** Note: For generality, we made this function polymorphic, since the\n    type of the values in the list is irrelevant to the splitting process. \n\n    While this function is straightforward to define, it can be a bit challenging\n    to work with.  Let's try to prove the following lemma, which is obviously true:\n*)\n\nLemma split_len_first_try: forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n  induction l; intros. \n  - inv H. simpl. omega. \n  - destruct l as [| x l'].\n    + inv H. \n      split; simpl; auto.\n    + inv H. destruct (split l') as [l1' l2'] eqn:E. inv H1. \n      (* We're stuck! The IH talks about [split (x::l')] but we\n         only know aobut [split (a::x::l'). *)\nAbort.\n\n(** The problem here is that the standard induction principle for lists\n    requires us to show that the property being proved follows for      \n    any non-empty list if it holds for the tail of that list.\n    What we want here is a \"two-step\" induction principle, that instead requires\n    us to show that the property being proved follows for a list of\n    length at least two, if it holds for the tail of the tail of that list.\n    Formally: \n*)\n\nDefinition list_ind2_principle:=\n    forall (A : Type) (P : list A -> Prop),\n      P [] ->\n      (forall (a:A), P [a]) ->\n      (forall (a b : A) (l : list A), P l -> P (a :: b :: l)) ->\n      forall l : list A, P l.\n\n(** If we assume the correctness of this \"non-standard\" induction principle, \n    our [split_len] proof is easy, using a form of the [induction] tactic \n    that lets us specify the induction principle to use: \n*)\n\nLemma split_len': list_ind2_principle -> \n    forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n  unfold list_ind2_principle; intro IP.\n  induction l using IP; intros.\n  - inv H. omega.\n  - inv H. simpl; omega.\n  - inv H. destruct (split l) as [l1' l2']. inv H1. \n    simpl. \n    destruct (IHl l1' l2') as [P1 P2]; auto; omega.\nQed.\n\n(** We still need to prove [list_ind2_principle].  There are several\n    ways to do this, but one direct way is to write an explicit proof\n    term, thus: *)\n\nDefinition list_ind2 :\n  forall (A : Type) (P : list A -> Prop),\n      P [] ->\n      (forall (a:A), P [a]) ->\n      (forall (a b : A) (l : list A), P l -> P (a :: b :: l)) ->\n      forall l : list A, P l :=\n  fun (A : Type)\n      (P : list A -> Prop)\n      (H : P [])\n      (H0 : forall a : A, P [a])\n      (H1 : forall (a b : A) (l : list A), P l -> P (a :: b :: l))  => \n    fix IH (l : list A) :  P l :=\n    match l with\n    | [] => H\n    | [x] => H0 x\n    | x::y::l' => H1 x y l' (IH l')\n    end.\n\n(** Here, the [fix] keyword defines a local recursive function [IH]\n    of type [forall l:list A, P l], which is returned as the overall value of\n    [list_ind2]. As usual, this function must be obviously terminating \n    to Coq (which it is because the recursive call is on a sublist [l'] \n    of the original argument [l]) and the [match] must be exhaustive over\n    all possible lists (which it evidently is). \n*)\n\n(** With our induction principle in hand, we can finally prove \n    [split_len] free and clear: \n*)\n\nLemma split_len: forall {X} (l:list X) (l1 l2: list X),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n apply (@split_len' list_ind2).\nQed.\n\n(** **** Exercise: 3 stars, standard (split_perm)  *)\n\n(** Here's another fact about [split] that we will find useful later on.  \n*)\n\nLemma split_perm : forall {X:Type} (l l1 l2: list X),\n    split l = (l1,l2) -> Permutation l (l1 ++ l2).\nProof.\n  induction l as [| x | x1 x2 l1' IHl'] using list_ind2; intros.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Defining Merge *)\n\n(** Next, we need a [merge] function, which takes two\n    sorted lists (of naturals) and returns their sorted result.\n    This would seem easy to write:\n\n    [[\n    Fixpoint merge l1 l2 :=\n      match l1, l2 with\n      | [], _ => l2\n      | _, [] => l1\n      | a1::l1', a2::l2' =>\n          if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge l1 l2'\n      end.\n    ]]\n\n    But Coq will reject this definition with the message:\n\n    [[\n    Error: Cannot guess decreasing argument of fix.\n    ]]\n\n    Coq insists the every [Fixpoint] definition be structurally recursive\n    on some specified argument, meaning that at each recursive call the\n    callee is passed a value that is a sub-term of the caller's argument value.\n    This check guarantees that every [Fixpoint] is actually terminating.\n\n    It is fairly obvious that this function is in fact terminating, because\n    at each call, either [l1] or [l2] is passed the tail of its original value.\n    But unfortunately, [Fixpoint] recursive calls must always decrease on\n    a _single fixed_ argument -- and neither [l1] nor [l2] will do. (That's\n    why Coq couldn't guess the one to use.)  We might reasonably wish\n    that Coq was a little smarter, but it isn't.\n\n    There are a number of ways to get around the problem of convincing\n    Coq that a function is actually terminating when the \"natural\" [Fixpoint]\n    doesn't work. In this case, a little creativity (or a peek at the Coq\n    library) might lead us to the following definition:\n*)\n\nFixpoint merge l1 l2  {struct l1} :=\n  let fix merge_aux l2 :=\n  match l1, l2 with\n  | [], _ => l2\n  | _, [] => l1\n  | a1::l1', a2::l2' =>\n      if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n  end\n  in merge_aux l2.\n\n(** Coq accepts the outer definition because it is structurally\n    decreasing on [l1] (we specify that with the [{struct l1}] annotation,\n    although Coq would have guessed this even if we didn't write it), \n    and it accepts the inner definition because it is structurally recursive \n    on its (sole) argument. (Note that [let fix ... in ... end] is just a \n    mechanism for  defining a local recursive function.)  \n\n    This definition will turn out to work pretty well; the only irritation \n    is that simplification will show the definition of [merge_aux], as\n    illustrated by the following examples. \n\n    First, let's remind ourselves that Coq desugars a [match] over multiple \n    arguments into a nested sequence of matches: \n*)\n\nPrint merge.\n\n(** ==> (after a little renaming for clarity)\n\n    [[\n    fix merge (l1 l2 : list nat) {struct l1} : list nat :=\n      let\n        fix merge_aux (l2 : list nat) : list nat :=\n          match l1 with\n          | [] => l2\n          | a1 :: l1' =>\n              match l2 with\n              | [] => l1\n              | a2 :: l2' =>\n                  if a1 <=? a2 then a1 :: merge l1' l2 else a2 :: merge_aux l2'\n              end\n          end in\n      merge_aux l2.\n    ]]\n*)\n\n(** Let's prove the following simple lemmas about [merge]: \n*)\n\nLemma merge2 : forall (x1 x2:nat) r1 r2,\n    x1 <= x2 ->\n    merge (x1::r1) (x2::r2) =\n    x1::merge r1 (x2::r2).\nProof.\n  intros.\n  simpl. (* This blows up in an unpleasant way, but we can\n      still make some sense of it.  Look at the\n      [(fix merge_aux ...)] term. It represents the\n      the local function [merge_aux] after the value of the\n      free variable [l1] has been substituted by [x1::r1],\n      the match over [l1] has been simplified to its\n      second arm (the non-empty case) and [x1] and [r1] have\n      been substituted for the pattern variables [a1] and [l1']. \n      The entire [fix] is applied to [r2], but Coq won't attempt\n      any further simplification until the structure of [r2] \n      is known. *)\n  bdestruct (x1 <=? x2).\n  - auto.\n  - (* Since [H] and [H0] are contradictory, this case follows by [omega].\n       But (ignoring that for the moment), note that we can get further \n       simplification to occur if we give some structure to [l2]: *)\n    simpl. (* does nothing *)\n    destruct r2; simpl.  (* makes some progress *)\n    + omega.\n    + omega. \nQed.  \n\nLemma merge_nil_l : forall l, merge [] l = l. \nProof.\n  intros. simpl.\n  (* Once again, we see a version of [merge_aux] specialized to\n  the value [l1 = nil]. Now we see only the first arm (the\n  empty case) of the [match] expression, which simply returns [l2];\n  in other words, here the [fix] is just the identity function. \n  And once again, the [fix] is applied to [l].  Irritatingly,\n  Coq _still_ refuses to perform the application unless [l]\n  is destructured first (even though the answer is always [l]). *)\n  destruct l.\n  - auto.\n  - auto. \nQed.\n\n(** Morals: \n\n    (1) Even though the proof state involving local recursive\n        functions can can be hard to read, persevere!\n\n    (2) If Coq won't simplify an \"obvious\" application, try destructing\n        the argument.\n\n    We will defer stating and proving other properties of [merge] until later.\n*)\n\n(* ================================================================= *)\n(** ** Defining Mergesort *)\n\n(** Finally, we need to define the main mergesort function itself.\n    Once again, we might hope to write something simple like this:\n\n    [[\n    Fixpoint mergesort (l: list nat) :  list nat :=\n       let (l1,l2) := split l in\n       merge (mergesort l1) (mergesort l2).\n    ]]\n\n    Since this function has only one argument, Coq guesses that it is\n    intended to be structurally decreasing, but still \n    rejects the definition, this time with the complaint:\n\n    [[\n    Recursive call to mergesort has principal argument equal to \n    \"l1\" instead of a subterm of \"l\".\n    ]]\n\n    Again, the problem is that Coq has no way to know that [l1] and [l2]\n    are \"smaller\" than [l].  And this time, it is hard to complain that\n    Coq is being stupid, since the fact that [split] returns smaller\n    lists than it is passed is nontrivial.\n\n    In fact, it isn't true! Consider the behavior of [split] on \n    empty or singleton lists...  This is case where Coq's totality\n    requirements can actually help us correct the definition of \n    our code.  What we really want to write is something more like:\n\n    [[\n    Fixpoint mergesort (l: list nat) :  list nat :=\n        match l with\n        | [] => []\n        | [x] => [x]\n        | _ => let (l1,l2) := split l in merge (mergesort l1) (mergesort l2).\n    ]]\n\n    Now this function really is terminating!  But Coq still won't let us\n    write it with a [Fixpoint].  Instead, we need to use a mechanism \n    (there are several available) for defining functions that accommodates\n    an explicit way to show that the function only calls itself on smaller\n    arguments.   We will use the [Function] command:\n*)\n\nFunction mergesort (l: list nat) {measure length l} :  list nat :=\n  match l with\n  | [] => []\n  | [x] => [x]\n  | _ => let (l1,l2) := split l in\n         merge (mergesort l1) (mergesort l2)\n  end.\n\n(** [Function] is similar to [Fixpoint], but it lets us specify \n    an explicit _measure_ on the function arguments. \n    The annotation [{measure length l}] says that the function \n    [length] applied to argument [l] serves as a decreasing measure.  \n    After processing this definition, Coq enters proof mode and demands \n    proofs that each recursive call is indeed on a shorter list. \n    Happily, we proved that fact already. \n*)\n\nProof.\n  - (* recursive call on l1 *)\n    intros.\n    simpl in *.  destruct (split l1) as [l1' l2'] eqn:E. inv teq1. \n    destruct (split_len _ _ _ E).\n    simpl. omega.\n  - (* recursive call on l2 *)\n    intros.\n    simpl in *. destruct (split l1) as [l1' l2'] eqn:E. inv teq1. \n    destruct (split_len _ _ _ E).\n    simpl. omega.\nDefined.\n\n(** Notice that the [Proof] must end with the keyword [Defined] rather\n    than [Qed]; if we don't do this, we won't be able to actually \n    compute with [mergesort]. \n\n    Defining [mergesort] with [Function] rather than [Fixpoint] causes\n    the automatic generation of some useful auxiliary definitions that we \n    will need when working with it. \n    First, we get a lemma [mergesort_equation], which performs a one-level\n    unfolding of the function. *)\n\nCheck mergesort_equation.\n \n(** ==> \n\n    [[\n    mergesort_equation\n     : forall l : list nat,\n       mergesort l =\n       match l with\n       | [] => []\n       | [x] => [x]\n       | x :: _ :: _ =>\n           let (l2, l3) := split l in merge (mergesort l2) (mergesort l3)\n       end\n    ]]\n\n    We should always use [apply mergesort_equation]\n    to simplify a call to [mergesort] rather than trying to [unfold] or [simpl]\n    it, which will lead to ugly or mysterious results.\n\n    Second, we get an induction principle [mergesort_ind]; performing\n    induction using this principle can be much easier than trying to\n    use list induction over the argument [l].  \n*)\n\nCheck mergesort_ind.\n\n(** ==>   \n    [[\n    mergesort_ind\n     : forall P : list nat -> list nat -> Prop,\n       (forall l : list nat, l = [] -> P [] []) ->\n       (forall (l : list nat) (x : nat), l = [x] -> P [x] [x]) ->\n       (forall l _x : list nat,\n        l = _x ->\n        match _x with\n        | _ :: _ :: _ => True\n        | _ => False\n        end ->\n        forall l1 l2 : list nat,\n        split l = (l1, l2) ->\n        P l1 (mergesort l1) ->\n        P l2 (mergesort l2) -> P _x (merge (mergesort l1) (mergesort l2))) ->\n        forall l : list nat, P l (mergesort l)\n    ]]\n*)\n\n(* ================================================================= *)\n(** ** Correctness: Sortedness *)\n\n(** As with insertion sort, our goal is to prove that mergesort produces\n    a sorted list that is a permutation of the original list, i.e. to prove\n    \n    [[\n    is_a_sorting_algorithm mergesort\n    ]] \n  \n    We will start by showing that [mergesort] produces a sorted list.  The key \n    lemma is to show that [merge] of two sorted lists produces a sorted list.\n    It is perhaps easiest to break out a sub-lemma first:\n*)\n\n(** **** Exercise: 2 stars, standard (sorted_merge1)  *)\nLemma sorted_merge1 : forall x x1 l1 x2 l2,\n    x <= x1 -> x <= x2 -> \n    sorted (merge (x1::l1) (x2::l2)) ->\n    sorted (x :: merge (x1::l1) (x2::l2)).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, standard (sorted_merge)  *)\nLemma sorted_merge : forall l1, sorted l1 ->\n                     forall l2, sorted l2 ->\n                     sorted (merge l1 l2).\nProof.\n  (* Hint: This is one unusual case where it is _much_ easier to do induction on \n     [l1] rather than on [sorted l1]. You will also need to do\n     nested inductions on [l2]. *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (mergesort_sorts)  *)\nLemma mergesort_sorts: forall l, sorted (mergesort l).\nProof. \n  apply mergesort_ind; intros. (* Note that we use the special induction principle. *)\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Correctness: Permutation *)\n\n(** Finally, we must show that [mergesort] returns a permutation of its input.\n\n    As usual, the key lemma is for [merge]. \n\n    Incidentally, you are welcome to import the alternative characterizations\n    of permutations as multisets given in [Multiset] or [BagPerm] \n    and use that instead of [Permutation] if you think it will be easier. \n    (I'm not sure!)\n*)\n\n(** **** Exercise: 3 stars, advanced (merge_perm)  *)\nLemma merge_perm: forall (l1 l2: list nat),\n    Permutation (l1 ++ l2) (merge l1 l2).\nProof. \n  (* Hint: A nested induction on [l2] is required. *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (mergesort_perm)  *)\nLemma mergesort_perm: forall l, Permutation l (mergesort l).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Putting it all together: *)\n\nTheorem mergesort_correct:\n  is_a_sorting_algorithm mergesort.\nProof.\n  split.\n  apply mergesort_perm.\n  apply mergesort_sorts.\nQed.\n\n(** $Date$ *)\n\n(* 2020-08-07 17:08 *)\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/vfa/Merge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7134300390567624}}
{"text": "(*EXAMEN GRUPO B*)\n(* Directorio /PRACTICAS/EI/ExMD2Dic/P2 *)\n\n(*NOMBRE: JESUS ANGEL PEREZ-ROCA FERNANDEZ*)\n\n(* ejercicio 1:(PUNTOS: 2 )\n  Probar las siguientes proposiciones sin hacer uso de Tauto ni de Auto: *)\n\nTheorem Imp_trans:(P,Q,R:Prop)(P->Q)->(Q->R)->(P->R).\nIntros.\nApply (H0 (H H1)).\nDefined.\n\nTheorem Ignore_Q:(P,Q,R:Prop)(P->R)->P->Q->R.\nIntros.\nApply (H H0).\nDefined.\n\nTheorem Delta_imp:(P,Q:Prop)(P->P->Q)->P->Q.\nIntros.\nApply (H H0).\nTrivial.\nDefined.\n\nTheorem Losange:(P,Q,R,S:Prop)(P->Q)->(P->R)->(Q->R->S)->P->S.\nIntros.\nApply (H1 (H H2) (H0 H2)).\nDefined.\n\nPrint Imp_trans.\nPrint Ignore_Q.\nPrint Delta_imp.\nPrint Losange.\n\n(* En logica intuicionista de segundo orden, los conectivos\n\"falso\", \"o\" e \"y\" pueden ser definidos en funcion de \"para todo\" y\nla implicacion *) \n\n(* definicion de falso *)\n\nDefinition new_false := (a:Prop)a .\n\n\n(* exercise 2: (PUNTOS 2) \n   probar el siguiente teorema *)\n\nTheorem ef : (a:Prop)(new_false -> a).\nIntros.\nApply H.\nDefined.\n\nPrint ef.\n\n(* Definicion de \"o\":\n a\"o\"b es verdad si todo lo que se deduce de {a} y de {b} es verdad *)\n\nDefinition new_or:=[a,b:Prop](c:Prop)(a->c)->(b->c)->c.\n\n(* ejercicio 3 :(PUNTOS 3) \n   probar dos teoremas que juntos demuestren la \n   equivalencia de new_or y \\/. *)\n\n\nTheorem equiv_or1: (a,b:Prop)(new_or a b)->(a\\/b).\nIntros.\nApply H.\nIntro.\nLeft.\nTrivial.\nIntro.\nRight.\nTrivial.\nDefined.\n\nTheorem equiv_or2: (a,b:Prop)(a\\/b)->(new_or a b).\nIntros.\nUnfold new_or.\nIntros.\nElim H.\nTrivial.\nTrivial.\nDefined.\n\n(* usando polimorfismo podemos definir tipos de datos como \n   numeros naturales y booleanos aunque\n   Coq use definiciones inductivas porque resulta\n   mas eficiente *)   \n\n(* booleanos *)\n\nDefinition new_bool := (a:Set)(a->a->a) .\nDefinition t := [a:Set][x,y:a]x .\nDefinition f := [a:Set][x,y:a]y .\n\n(* exercicio 4 :(PUNTOS 3)\n   Dar una definicion de new_not:new_bool -> new_bool\n   para la negacion en new_bool\n   y chequearla con dos entradas diferentes *)\n\nDefinition new_not:new_bool->new_bool.\nUnfold new_bool.\nIntros.\nApply H.\nExact H1.\nExact H0.\nDefined.\n\nPrint new_not.\n\nEval Compute in (new_not t).\n\nEval Compute in (new_not f).\n\n(* Estos dos resultados serian para los tipos polimorficos. \n   Si quisieramos probarlo para el tipo bool la comprobacion seria asi:*)\n   \nEval Compute in (t bool true false).\n\nEval Compute in ((new_not t) bool true false).\n\nEval Compute in (f bool true false).\n\nEval Compute in ((new_not f) bool true false).\n", "meta": {"author": "yisus82", "repo": "fic-md2", "sha": "4c7bab0d63e1bf0dbd1fe60b1ba58003125825ba", "save_path": "github-repos/coq/yisus82-fic-md2", "path": "github-repos/coq/yisus82-fic-md2/fic-md2-4c7bab0d63e1bf0dbd1fe60b1ba58003125825ba/examen2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.713344319732116}}
{"text": "Theorem True_provable : True.\nProof.\n  exact I.\nQed.\n\nDefinition not (A:Prop) := A -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nTheorem False_unprovable : ~ False.\nProof.\n  unfold not.\n  intros pf_False.\n  exact pf_False.\nQed.\n\nTheorem False_unprovable_again : ~ False.\nProof.\n  unfold not.\n  intros pf_False.\n  case pf_False.\nQed.\n\nTheorem True_not_implies_False : ~ (True -> False).\nProof.\n  unfold not.\n  intros True_imp_False.\n  pose (pf_False := True_imp_False I).\n  case pf_False.\nQed.\n\nTheorem False_implies_True : False -> True.\nProof.\n  intros pf_False.\n  case pf_False.\nQed.\n\nTheorem False_implies_False : False -> False.\nProof.\n  intros pf_False.\n  case pf_False.\nQed.\n\nRequire Import Bool.\n\nTheorem true_is_True : Is_true true.\nProof.\n  simpl.\n  exact I.\nQed.\n\nTheorem not_true_eqb_false : ~ (Is_true (eqb true false)).\nProof.\n  simpl.\n  exact False_unprovable.\nQed.\n\nTheorem left_or : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B pf_A.\n  pose (pf_A_or_B := or_introl pf_A : A \\/ B).\n  exact pf_A_or_B.\nQed.\n\nTheorem right_or : forall A B : Prop, B -> A \\/ B.\nProof.\n  intros A B pf_B.\n  pose (pf_A_or_B := or_intror pf_B : A \\/ B).\n  exact pf_A_or_B.\nQed.\n\nTheorem or_commutes : forall A B, A \\/ B -> B \\/ A.\nProof.\n  intros A B pf_A_or_B.\n  case pf_A_or_B.\n    (* right *)\n    intros pf_A.\n    refine (or_intror _).\n    exact pf_A.\n    (* left *)\n    intros pf_B.\n    refine (or_introl _).\n    exact pf_B.\nQed.\n\nTheorem both_and : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B pf_A pf_B.\n  pose (pf_A_and_B := conj pf_A pf_B).\n  exact pf_A_and_B.\nQed.\n\nTheorem and_commutes : forall A B : Prop, A /\\ B -> B /\\ A.\nProof.\n  intros A B pf_A_and_B.\n  case pf_A_and_B.\n  intros pf_A pf_B.\n  pose (pf_B_and_A := conj pf_B pf_A).\n  exact pf_B_and_A.\nQed.\n\nTheorem and_commutes_1 : forall A B : Prop, A /\\ B -> B /\\ A.\nProof.\n  intros A B pf_A_and_B.\n  case pf_A_and_B.\n  intros pf_A pf_B.\n  refine (conj _ _).\n    exact pf_B.\n    exact pf_A.\nQed.\n\nTheorem and_commutes_2 : forall A B : Prop, A /\\ B -> B /\\ A.\nProof.\n  intros A B pf_A_and_B.\n  destruct pf_A_and_B as [ pf_A pf_B ].\n  refine (conj _ _).\n    exact pf_B.\n    exact pf_A.\nQed.\n\nTheorem orb_is_or : forall a b, Is_true (orb a b) <-> Is_true a \\/ Is_true b.\nProof.\n  intros a b.\n  unfold iff.\n  refine (conj _ _).\n    (* forward *)\n    intros H.\n    case a, b.\n      simpl.\n      exact (or_introl I).\n      exact (or_introl I).\n      exact (or_intror I).\n      simpl in H.\n      case H.\n    (* backward *)\n    intros H.\n    case a, b.\n      simpl. exact I.\n      simpl. exact I.\n      simpl.\n      case H.\n        simpl. exact False_implies_True.\n        simpl. intros pf_True. exact I.\n      simpl in H.\n      case H.\n        simpl. exact False_implies_False.\n        simpl. exact False_implies_False.\nQed.", "meta": {"author": "Riib11", "repo": "Coq-Work", "sha": "e163edd331fd15549910f0fe0a361bc93ca951d7", "save_path": "github-repos/coq/Riib11-Coq-Work", "path": "github-repos/coq/Riib11-Coq-Work/Coq-Work-e163edd331fd15549910f0fe0a361bc93ca951d7/Inria/booleans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276222, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7133443195993578}}
{"text": "Require Import List.\n\nInductive last(A : Set) : list A -> A -> Prop :=\n  single : forall a : A, last A (a :: nil) a\n| compound : forall (l : list A)(a b : A), last A l a -> last A (b :: l) a.\n\nFixpoint last_fun(A : Set)(l : list A) : option A :=\n  match l with\n  | nil => None\n  | a :: nil => Some a\n  | a :: b => last_fun A b\n  end.\n\nGoal forall(A : Set)(l : list A)(a : A), last A l a -> last_fun A l = Some a.\n  intros.\n  elim H.\n  reflexivity.\n  intros.\n  rewrite <- H1.\n  simpl.\n  destruct l0.\n  inversion H1.\n  reflexivity.\nQed.\n\nInductive permutation(A : Set) : list A -> list A -> Prop :=\n  transpose : \n    forall (l r : A)(lis : list A),\n      permutation A (l :: r :: lis) (r :: l :: lis)\n| trans : forall a b c, permutation A a b -> permutation A b c -> permutation A a c\n| id : forall a, permutation A a a.\n\nRequire Import Relations.\n\nTheorem equiv_perm : forall A : Set, equiv _ (permutation A).\n  intros.\n  repeat split.\n  unfold reflexive.\n  constructor.\n  unfold transitive.\n  intros.\n  apply (trans A x y z);assumption.\n  unfold symmetric.\n  intros.\n  elim H.\n  intros.\n  constructor.\n  intros.\n  econstructor.\n  eassumption.\n  assumption.\n  constructor.\nQed.\n\nRequire Import JMeq.\nRequire Import Arith.\n\nLemma plus_assoc_JM : \n  forall n p q:nat,\n    JMeq (n+(p+q)) (n+p+q).\n  intros.\n  rewrite plus_assoc.\n  constructor.\nQed.\n\nInductive even : nat -> Prop :=\n| O_even : even 0\n| plus_2_even : forall n:nat, even n -> even (S (S n)).\n\nHint Resolve O_even plus_2_even.\n\nFixpoint mult2 (n:nat) : nat :=\n  match n with\n  | O => 0\n  | S p => S (S (mult2 p))\n  end.\n\nGoal forall n, even (n * 2).\n  intros.\n  induction n.\n  auto.\n  rewrite mult_succ_l.\n  rewrite plus_comm.\n  simpl.\n  auto.\nQed.\n\nGoal forall n, even n -> exists x, x * 2 = n.\n  intros.\n  induction H.\n  exists 0.\n  auto.\n  destruct IHeven.\n  exists (S x).\n  rewrite mult_succ_l.\n  rewrite plus_comm.\n  simpl.\n  auto with arith.\nQed.\n\nLemma even_plus : forall n m, even n -> even m -> even (n + m).\n  intros.\n  induction H.\n  auto.\n  simpl.\n  auto.\nQed.\n\nGoal forall n, even n -> even (n * n).\n  intros.\n  induction H.\n  auto.\n  repeat rewrite mult_succ_l.\n  repeat rewrite mult_succ_r.\n  repeat apply even_plus;auto.\nQed.\n\nTheorem lt_le : forall n p:nat, n < p -> n <= p.\n  intros n p H.\n  apply (le_ind (S n)).\n  repeat constructor.\n  intros.\n  constructor.\n  assumption.\n  assumption. \nQed.\n\nDefinition my_le (n p:nat) :=\n  forall P:nat->Prop,\n    P n ->\n      (forall q:nat, P q -> P (S q)) ->\n        P p.\n\nLemma my_le_n : forall n:nat, my_le n n.\n  unfold my_le.\n  intros.\n  assumption.\nQed.\n\nLemma my_le_S : forall n p:nat, my_le n p -> my_le n (S p).\n  unfold my_le.\n  intros.\n  apply H.\n  auto.\n  intros.\n  auto.\nQed.\n\nLemma my_le_inv : forall n p:nat, my_le n p -> n=p \\/ my_le (S n) p.\n  unfold my_le.\n  intros.\n  apply H.\n  left.\n  auto.\n  intros.\n  destruct H0.\n  right.\n  intros.\n  rewrite <- H0.\n  auto.\n  right.\n  intros.\n  apply H2.\n  apply H0;\n  auto.\nQed.\n\nLemma my_le_inv2 :\n  forall n p:nat, my_le (S n) p ->\n    exists q, p=(S q) /\\ my_le n q.\n  unfold my_le.\n  intros.\n  apply H.\n  exists n.\n  split;\n  auto.\n  intros.\n  destruct H0.\n  destruct H0.\n  exists (S x).\n  split.\n  auto with arith.\n  intros.\n  apply H3.\n  apply H1;\n  auto.\nQed.\n\nLemma my_le_n_O : forall n:nat, my_le n 0 -> n = 0.\n  intros.\n  destruct n.\n  auto.\n  ecase my_le_inv2.\n  eassumption.\n  intros.\n  destruct H0.\n  discriminate H0.\nQed.\n\nLemma my_le_le : forall n p:nat, my_le n p -> le n p.\n  intros.\n  apply H;\n  auto.\nQed.\n\nLemma le_my_le : forall n p:nat, le n p -> my_le n p.\n  unfold my_le.\n  intros.\n  induction H;\n  auto.\nQed.\nRequire Export Program.\nInductive par := open | close.\nInductive wp : list par -> Prop :=\n| wp_nil : wp []\n| wp_par l : wp l -> wp (open :: (l ++ [close]))\n| wp_app l r : wp l -> wp r -> wp (l ++ r).\nHint Constructors wp.\n\nTheorem cons_app { A } (l : A) r : l :: r = [l] ++ r.\n  trivial.\nQed.\n\nTheorem wp_oc : wp [open;close].\n  rewrite (cons_app open); repeat constructor.\nQed.\n\nTheorem wp_o_head_c l1 l2 : wp l1 -> wp l2 -> wp (open :: l1 ++ close :: l2).\n  intros; rewrite (cons_app open), (cons_app close).\n  rewrite !app_assoc; apply wp_app; simpl; auto.\nQed.\n\nTheorem wp_o_tail_c l1 l2 : wp l1 -> wp l2 -> wp (l1 ++ open :: l2 ++ [close]).\n  intros; rewrite (cons_app open).\n  apply wp_app; simpl; auto.\nQed.\n\nFixpoint recognize n (l : list par) : bool :=\n  match l, n with\n  | [], 0 => true\n  | open :: l', _ => recognize (S n) l'\n  | close :: l', S n' => recognize n' l'\n  | _, _ => false\n  end.\n\nTheorem repeat_shift { A } (e : A) n : repeat e n ++ [e] = e :: repeat e n.\n  induction n; simpl in *; f_equal; auto.\nQed.\n\nTheorem get_last { A } (l : list A) : l = [] \\/ exists l' e, l = l' ++ [e].\n  induction l; intuition idtac; program_simpl.\n  right; exists (@nil A) a; trivial.\n  right; exists (a :: H) H0; trivial.\nQed.\nHint Resolve wp_oc.\n\nInductive wp' : list par -> Prop :=\n| wp'_nil : wp' []\n| wp'_cons l r : wp' l -> wp' r -> wp' (open :: l ++ close :: r).\nHint Constructors wp'.\nTheorem wp'_app l r : wp' l -> wp' r -> wp' (l ++ r).\n  intros HL HR; induction HL; simpl in *; auto.\n  rewrite <- app_assoc, <- app_comm_cons; auto.\nQed.\nHint Resolve wp'_app.\nTheorem wp_wp' l : wp l -> wp' l.\n  induction 1; simpl in *; auto.\nQed.\n\nTheorem wp'_wp l : wp' l -> wp l.\n  induction 1; auto.\n  replace (open :: l ++ close :: r) with ((open :: l ++ [close]) ++ r); auto.\n  simpl; f_equal; rewrite <- app_assoc; trivial.\nQed.\n\nHint Resolve wp_wp' wp'_wp.\n\nRequire Export Omega.\n\nTheorem wp_close_false l : wp (close :: l) -> False.\n  intros H; dependent induction H.\n  destruct l0; inversion x; simpl in *; subst; eauto.\nQed.\n\nTheorem wp_open_false l : wp (l ++ [open]) -> False.\n  intros H; dependent induction H; destruct l; program_simpl.\n  destruct l0; program_simpl.\n  apply app_inj_tail in H2; intuition congruence.\n  destruct l0, r; program_simpl.\n  specialize(IHwp2 []); program_simpl.\n  destruct l0; specialize(IHwp1 []); program_simpl.\n  destruct l0, p0; program_simpl.\n  destruct (get_last r); program_simpl; rewrite ?app_nil_r in *; subst; eauto.\n  rewrite app_assoc in *; apply app_inj_tail in x; intuition; program_simpl; eauto.\nQed.\n\nHint Resolve wp_close_false wp_open_false.\n\nTheorem wp_app_inv n l : length l < n -> wp (open :: close :: l) -> wp l.\n  revert l; induction n; intros; [omega|].\n  apply wp_wp' in H0; inversion H0; clear H0; simpl in *.\n  destruct l0; simpl in *; program_simpl.\n  apply wp'_wp in H2; exfalso; eauto.\nQed.\n\nLtac invcs s := inversion s; clear s; subst.\nTheorem par_destruct_aux n l : length l < n -> head l = Some open -> \n  (exists n, l = repeat open n) \\/ (exists n li, l = repeat open n ++ close :: li).\n  revert l; induction n; intros; simpl in *; [omega|].\n  destruct l as [|[]]; simpl in *; invcs H0.\n  destruct l as [|[]]; simpl in *.\n  left; exists 1; trivial.\n  destruct (IHn (open :: l)) as [[]|[? []]]; simpl in *; omega || trivial;\n  destruct x; simpl in *; invcs H0.\n  left; exists (S (S x)); trivial.\n  right; exists (S (S x)) x0; trivial.\n  right; exists 1 l; trivial.\nQed.\n\nTheorem par_destruct l :\n  (exists n, l = repeat open n) \\/ (exists n li, l = repeat open n ++ close :: li).\n  destruct l as [|[]].\n  left; exists 0; trivial.\n  destruct (par_destruct_aux (S (S (length l))) (open :: l)); \n  simpl in *; program_simpl; omega || trivial.\n  destruct H; invcs H0.\n  left; exists (S H); trivial.\n  destruct H; simpl in *; invcs H1.\n  right; exists (S H) H0; trivial.\n  right; exists 0 l; trivial.\nQed.\n\nTheorem length_eq { A } { l r : list A } (H : l = r) : length l = length r.\n  subst; trivial.\nQed.\n\nTheorem app_eq { A } { ll lr rl rr : list A } : \n  ll ++ lr = rl ++ rr -> exists l, ll = rl ++ l \\/ rl = ll ++ l.\n  revert lr rl rr.\n  induction ll; program_simpl; eauto.\n  destruct rl; simpl in *; invcs H; eauto.\n  specialize(IHll _ _ _ H2); program_simpl; intuition idtac; subst; eauto.\nQed.\n\nTheorem wp_remove_aux n : forall l r, length l + length r < n ->\n  wp (l ++ [open; close] ++ r) -> wp (l ++ r).\n  induction n; simpl in *; intros; [omega|].\n  apply wp_wp' in H0; invcs H0.\n  destruct l; simpl in *; congruence.\n  destruct l; simpl in *; invcs H1.\n  destruct l0; simpl in *; invcs H4; eauto with *.\n  destruct (app_eq H5) as [? []]; subst;\n  rewrite <- app_assoc in *;\n  apply app_inv_head in H5.\n  destruct x; invcs H5.\n  destruct x; invcs H4; try solve [exfalso; eauto].\n  apply wp'_wp in H2; eapply IHn in H2; \n  repeat (simpl in *; rewrite ?app_length in *); try omega.\n  replace \n    (open :: l ++ x ++ close :: r0) with \n    ((open :: l ++ x ++ [close]) ++ r0) by\n    (simpl; f_equal; rewrite <- app_assoc; f_equal; rewrite <- app_assoc; trivial).\n  apply wp_app; auto.\n  rewrite app_assoc; auto.\n  destruct x; simpl in *; invcs H5.\n  replace \n    (open :: l0 ++ close :: x ++ r) with \n    ((open :: l0 ++ [close]) ++ x ++ r) by\n    (simpl; f_equal; rewrite <- app_assoc; f_equal).\n  apply wp_app; auto.\n  eapply IHn; repeat (simpl in *; rewrite ?app_length in *); omega || auto.\nQed.\n\nTheorem wp_remove l r : wp (l ++ open :: close :: r) -> wp (l ++ r).\n  intros; eapply wp_remove_aux; auto.\nQed.\n\nTheorem recognize_complete_aux l : wp l -> forall n l', recognize n (l ++ l') = recognize n l'.\n  induction 1; intros; simpl in *; rewrite <- ?app_assoc, ?IHwp, ?IHwp1, ?IHwp2; trivial.\nQed.\n\nTheorem recognize_complete l : wp l -> recognize 0 l = true.\n  induction 1; simpl in *; rewrite ?recognize_complete_aux; trivial.\nQed.\n\nTheorem wp_destruct l : wp l -> \n  l = [] \\/ \n  (exists l1 l2, l = l1 ++ l2 /\\ wp l1 /\\ wp l2 /\\ l1 <> [] /\\ l2 <> []) \\/ \n  (exists l1, l = open :: l1 ++ [close] /\\ wp l1).\n  induction 1; intros; try solve [intuition idtac].\n  right; right; exists l; intuition.\n  destruct IHwp1; program_simpl; simpl in *; trivial.\n  destruct IHwp2; program_simpl; simpl in *; rewrite ?app_nil_r in *; eauto.\n  right; left; exists l r; intuition idtac; program_simpl;\n  match goal with H : ?X ++ ?Y = [] |- _ => destruct X; simpl in *; congruence end.\nQed.\n\nTheorem wp_insert : forall n a b c, \n  length a + length b + length c < n -> wp (a ++ c) -> wp b -> wp (a ++ b ++ c).\n  induction n; intros; simpl in *; [omega|].\n  apply wp_destruct in H0; intuition idtac; program_simpl.\n  + destruct a, c; simpl in *; rewrite ?app_nil_r; congruence.\n  + destruct (app_eq H3); intuition idtac; subst; rewrite <- app_assoc in *;\n    apply app_inv_head in H3; subst; repeat (simpl in *; rewrite ?app_length in *).\n    - apply wp_app; eauto.\n      eapply IHn; eauto.\n      destruct H0; simpl in *; congruence || omega.\n    - rewrite !app_assoc; apply wp_app; eauto.\n      rewrite <- app_assoc; eapply IHn; eauto.\n      destruct H2; simpl in *; congruence || omega.\n  + destruct a; simpl in *; invcs H2; eauto.\n    destruct (get_last c); program_simpl;\n    repeat (rewrite ?app_nil_r, ?app_length, <- ?plus_n_O in *; subst; simpl in *).\n    - rewrite app_comm_cons; eauto.\n    - rewrite app_assoc in H6; apply app_inj_tail in H6; intuition idtac; subst.\n      rewrite !app_assoc; apply wp_par; rewrite <- app_assoc; eapply IHn; eauto; omega.\nQed.\n\nTheorem recognize_sound n l : recognize n l = true -> wp ((repeat open n) ++ l).\n  revert n; induction l; intros; simpl in *.\n  destruct n; simpl; congruence || auto.\n  destruct a, n; simpl in *; try specialize (IHl _ H); simpl in *; congruence || auto.\n  rewrite (cons_app _ l), app_assoc, repeat_shift; simpl; trivial.\n  rewrite app_comm_cons, <- repeat_shift, <- app_assoc, (cons_app _ l), (app_assoc _ _ l).\n  eapply wp_insert; eauto.\nQed.", "meta": {"author": "DKXXXL", "repo": "CoqArt", "sha": "ae8f577a618aeb7182c4478642a9d5ce4b289b46", "save_path": "github-repos/coq/DKXXXL-CoqArt", "path": "github-repos/coq/DKXXXL-CoqArt/CoqArt-ae8f577a618aeb7182c4478642a9d5ce4b289b46/Chapter8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7133443166013553}}
{"text": "Theorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H1 contra.\n  unfold not.\n  unfold not in contra.\n  intros HP.\n  apply contra in H1. \n  apply H1.\n  apply HP.\nQed.", "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/Chapter6/contrapositive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7132928451439398}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Strings.String.\n\nImport ListNotations.\n\n\n(* Syntax of Clock-based Dynamic Logic *)\n\n(* Syntax of SEP_exp (Synchonous Event Program) *)\n\n\n(* ========================= Syntax of SEP_exp ========================*)\n\n(* =============== Syntax of Expressions ===================*)\n\n(* Arith Expression `e'*)\n\nInductive e_exp := \n  enumC : nat -> e_exp | \n  evarC : string -> e_exp | \n  eplusC : e_exp -> e_exp -> e_exp |\n  (*non-necessary expression*)\n  eminusC : e_exp -> e_exp -> e_exp |\n  emulC : e_exp -> e_exp -> e_exp |\n  edivC : e_exp -> e_exp -> e_exp\n.\nPrint e_exp.\n\n\nNotation \"e1 '+ e2\" := (eplusC e1 e2) (at level 31, right associativity).\nLocate \"'+\".\nNotation \"e1 '- e2\" := (eminusC e1 e2) (at level 31, right associativity).\n\nNotation \"e1 '* e2\" := (emulC e1 e2) (at level 21, right associativity).\n\n(*** Open Scope e_exp_scope. ***)\n\nLocate \"*\".\nCheck (enumC 4) '* (enumC 5 '+ enumC 6).\n\nNotation \"e1 '/ e2\" := (edivC e1 e2) (at level 21, right associativity).\nCheck (enumC 4) '/ (enumC 4).\n\nCoercion enumC : nat >-> e_exp.\nCoercion evarC : string >-> e_exp.\nDefinition x : string := \"x\".\nDefinition y : string := \"y\".\nDefinition z : string := \"z\".\nDefinition k : string := \"k\".\n\nCheck 4 '* (5 '+ 2).\nCheck (5 '+ 4) '* 8.\nCheck x '- 3.\nCheck 5 '+ 4 '* 5.\n\n\n\n(* Boolean Expression `P'*)\nInductive P_exp := \n  PtrueC : P_exp |\n  PlteC : e_exp -> e_exp -> P_exp |\n  PnegC : P_exp -> P_exp |\n  PandC : P_exp -> P_exp -> P_exp |\n  (*non-necesarry expression*)\n  PfalseC : P_exp |\n  PltC : e_exp -> e_exp -> P_exp |\n  PgtC : e_exp -> e_exp -> P_exp |\n  PgteC : e_exp -> e_exp -> P_exp |\n  PeqC : e_exp -> e_exp -> P_exp |\n  PorC : P_exp -> P_exp -> P_exp |\n  PimpC : P_exp -> P_exp -> P_exp\n.\nPrint P_exp.\n\n(* 33 - 41 *)\nNotation \"''tt'\" := PtrueC (at level 35).\nNotation \"e1 '<= e2\" := (PlteC e1 e2) (at level 33).\nNotation \"'~ P\" := (PnegC P) (at level 36).\nNotation \"P1 '/\\ P2\" := (PandC P1 P2) (at level 37, right associativity).\nNotation \"''ff'\" := PfalseC (at level 35).\nNotation \"e1 '< e2\" := (PltC e1 e2) (at level 33).\nNotation \"e1 '> e2\" := (PgtC e1 e2) (at level 33).\nNotation \"e1 '>= e2\" := (PgteC e1 e2) (at level 33).\nNotation \"e1 '= e2\" := (PeqC e1 e2) (at level 33).\nNotation \"P1 '\\/ P2\" := (PorC P1 P2) (at level 37, right associativity).\nNotation \"P1 '-> P2\" := (PimpC P1 P2) (at level 38, right associativity).\n\nLocate \"'/\\\".\nCheck 'tt '-> 'ff.\nCheck 5 '+ x '>= 5 '-> 3 '> 7.\n\n\n(* Evaluation *)\nDefinition state := string -> nat.\n\n(***\n  Definging the evaluation for expressions is for checking the validation of FOL formulas after \n  transformation. \n***)\n\nFixpoint eval_e_exp (e : e_exp) (st : state) : nat :=  \n(* st maps each var name to a value --- it is a state *)\n  match e with\n  | enumC n => n\n  | evarC s => st s\n  | eplusC e1 e2 => (eval_e_exp e1 st) + (eval_e_exp e2 st)\n  | eminusC e1 e2 => (eval_e_exp e1 st) - (eval_e_exp e2 st)\n  | emulC e1 e2 => (eval_e_exp e1 st) * (eval_e_exp e2 st)\n  | edivC e1 e2 => (eval_e_exp e1 st) / (eval_e_exp e2 st)\n  end.\n\n\nFixpoint eval_P_exp (P : P_exp) (st : state) : Prop :=\n  match P with\n  | PtrueC => True\n  | PlteC e1 e2 => (eval_e_exp e1 st) <= (eval_e_exp e2 st)\n  | PnegC P' => ~ (eval_P_exp P' st)\n  | PandC P1 P2 => (eval_P_exp P1 st) /\\ (eval_P_exp P1 st)\n  | PfalseC => False\n  | PltC e1 e2 => (eval_e_exp e1 st) < (eval_e_exp e2 st)\n  | PgtC e1 e2 => (eval_e_exp e1 st) > (eval_e_exp e2 st)\n  | PgteC e1 e2 => (eval_e_exp e1 st) >= (eval_e_exp e2 st)\n  | PeqC e1 e2 => (eval_e_exp e1 st) = (eval_e_exp e2 st)\n  | PorC P1 P2 => (eval_P_exp P1 st) \\/ (eval_P_exp P1 st)\n  | PimpC P1 P2 => (eval_P_exp P1 st) -> (eval_P_exp P1 st)\n  end.\n\n(* =============== Syntax of Event ===================*)\n\n\n(* Event *)\nInductive EvtElement := \n  sigC : string -> e_exp -> EvtElement | (* Signal *)\n  assC : string -> e_exp -> EvtElement  (* Assignment *)\n.\nCheck EvtElement. \n\nNotation \"s ! e\" := (sigC s e) (at level 45).\nNotation \"x :=' e\" := (assC x e) (at level 45).\n\n(* currently we do not make distinguish between variable and clock names, both are strings*)\nDefinition c : string := \"c\".\nDefinition d : string := \"d\".\nDefinition c1 : string := \"c1\".\nDefinition c2 : string := \"c2\".\nDefinition c3 : string := \"c3\".\nDefinition c4 : string := \"c4\".\n\nCheck x :=' 4.\nCheck c ! (x '+ 4).\n\nDefinition Evt := list EvtElement.\n\nCheck Evt.\nCheck (x :=' 4) :: (c!(x '+ 4)) :: nil.\n\n(* ========================= Syntax of program ========================*)\nInductive SEP_exp : Type := \n  skip : SEP_exp | (* skip program $\\varepsilon$ *)\n  evtC : Evt -> SEP_exp | (* Event *)\n  tstC : P_exp -> Evt -> SEP_exp | (* Test *)\n  seqC : SEP_exp -> SEP_exp -> SEP_exp | (* sequence *)\n  choC : SEP_exp -> SEP_exp -> SEP_exp | (* choice *)\n  loopC : SEP_exp -> SEP_exp (* loop *)\n.\n\nCoercion evtC : Evt >-> SEP_exp.\nNotation \"{ a1 | .. | an }\" := (cons a1 .. (cons an nil) .. ) (at level 45). \nNotation \"@ a\" := (evtC a) (at level 46).\nDefinition idle : Evt := nil.\nNotation \"P ? a\" := (tstC P a) (at level 48).\nNotation \"P1 ; P2\" := (seqC P1 P2) (at level 49, left associativity).\nNotation \"P1 'U' P2\" := (choC P1 P2) (at level 51, left associativity).\nNotation \"P **\" := (loopC P) (at level 47, left associativity).\n\nLocate \"**\".\nCheck x :=' 4 :: nil.\nCheck evtC (x :=' 4 :: nil).\nCheck { x :=' 4 }.\nCheck { x :=' 4 | c1 ! 5}.\nCheck @ { x :=' 4 | c1 ! 5 }.\nCheck idle.\nCheck x '> 0 ? {c!4}.\n\n(* ========================================= Syntax of CDL Formula ===============================================*)\n\n(* ================== CCSL ======================== *)\n(* clock relation *)\n(***\n  Currently, we model clocks as `strings', becuase now we don't need to give its semantics. \n  It won't work anymore if we consider its semantics later.\n***)\n\nInductive CRel := \n  crSubClC : string -> string -> CRel |\n  crExclC : string -> string -> CRel |\n  crPrecC : string -> string -> CRel |\n  crCausC : string -> string -> CRel\n.\nCheck CRel.\n\nNotation \"c1 'sub' c2\" := (crSubClC c1 c2) (at level 52).\nNotation \"c1 # c2\" := (crExclC c1 c2) (at level 52).\nNotation \"c1 << c2\" := (crPrecC c1 c2) (at level 52).\nNotation \"c1 <<= c2\" := (crCausC c1 c2) (at level 52).\n\nCheck c1 << c2.\nCheck c1 # c2.\nCheck c1 sub c2.\n\n(* ================== CDL Formula ======================== *)\n(* Clock relation in formula *)\nInductive rel := \n  rRelC : CRel -> rel |\n  rConjC : list CRel -> rel\n.\nPrint rel.\n\nCoercion rRelC : CRel >-> rel.\nCheck c1 << c2.\n\nNotation \"/\\{ c1 , .. , cn }\" := (rConjC (cons c1 .. (cons cn nil) ..)).\nCheck /\\{ c1 << c2 , c2 sub c3 , c1 <<= c3}.\n\n\n(* Arith Expression `E' *)\n(*DEL\n(* define a map that maps each clock/signal to a variable that records the number it has ticked in history. *)\nDefinition CntClk := string -> string. \n\n(* define a map that maps each clock/signal to a variable that records the current state of this clock. *)\nDefinition StClk := string -> string. \nDEL*)\n\nInductive E_exp :=\n  EvarC : string -> E_exp |\n  ECntClkC : string -> E_exp | (* define a map that maps each clock/signal to a variable that records the number it has ticked in history. *)\n  EStClkC : string -> E_exp | (* define a map that maps each clock/signal to a variable that records the current state of this clock. *)\n  EnumC : nat -> E_exp |\n  EplusC : E_exp -> E_exp -> E_exp |\n  (* unecessary expression *)\n  EmulC : E_exp -> E_exp -> E_exp |\n  EminusC : E_exp -> E_exp -> E_exp |\n  EdivC : E_exp -> E_exp -> E_exp\n.\nPrint E_exp. \n\nCoercion EvarC : string >-> E_exp.\nNotation \"n( c )\" := (ECntClkC c) (at level 52). (* the only DIFFERENCE between e_exp and E_exp *)\nNotation \"s( c )\" := (EStClkC c) (at level 52).\nCoercion EnumC : nat >-> E_exp.\nNotation \"e1 +' e2\" := (EplusC e1 e2) (at level 55, right associativity).\nNotation \"e1 *' e2\" := (EmulC e1 e2) (at level 53, right associativity).\nNotation \"e1 -' e2\" := (EminusC e1 e2) (at level 55, right associativity).\nNotation \"e1 /' e2\" := (EdivC e1 e2) (at level 53, right associativity).\n\nCheck 5 +' 3.\nCheck 5 '+ 3.\nCheck 5 *' (3 +' 5).\nCheck n(c) *' 4.\n\n\n\n\n\n(* CDL Formula *)\nInductive CDL_exp := \n  cdl_trueC : CDL_exp |\n  cdl_ltC : E_exp -> E_exp -> CDL_exp |\n  cdl_box1C : SEP_exp -> rel -> CDL_exp |\n  cdl_box2C : SEP_exp -> CDL_exp -> CDL_exp |\n  cdl_negC : CDL_exp -> CDL_exp |\n  cdl_andC : CDL_exp -> CDL_exp -> CDL_exp |\n  cdl_forallC : string -> CDL_exp -> CDL_exp |\n  (* unnecessary expressions *)\n  cdl_falseC : CDL_exp |\n  cdl_lteC : E_exp -> E_exp -> CDL_exp |\n  cdl_gtC : E_exp -> E_exp -> CDL_exp |\n  cdl_gteC : E_exp -> E_exp -> CDL_exp |\n  cdl_eqC : E_exp -> E_exp -> CDL_exp |\n  cdl_dia1C : SEP_exp -> rel -> CDL_exp |\n  cdl_dia2C : SEP_exp -> CDL_exp -> CDL_exp |\n  cdl_orC : CDL_exp -> CDL_exp -> CDL_exp |\n  cdl_impC : CDL_exp -> CDL_exp -> CDL_exp\n.\n\nNotation \"'tt''\" := cdl_trueC (at level 65).\nNotation \"e1 <' e2\" := (cdl_ltC e1 e2) (at level 61).\nNotation \"[ p ]' r\" := (cdl_box1C p r) (at level 63, p at level 62, r at level 62).\nNotation \"[ p ] e\" := (cdl_box2C p e) (at level 63, p at level 62, e at level 62).\nNotation \"~' e\" := (cdl_negC e) (at level 67).\nNotation \"e1 /\\' e2\" := (cdl_andC e1 e2) (at level 69, right associativity).\nNotation \"'all' x , e\" := (cdl_forallC x e) (at level 68, x at level 67).\n(* unnecessary expressions *)\nNotation \"'ff''\" := cdl_falseC (at level 65).\nNotation \"e1 <=' e2\" := (cdl_lteC e1 e2) (at level 61).\nNotation \"e1 >' e2\" := (cdl_gtC e1 e2) (at level 61).\nNotation \"e1 >=' e2\" := (cdl_gteC e1 e2) (at level 61).\nNotation \"e1 =' e2\" := (cdl_eqC e1 e2) (at level 61).\nNotation \"< p >' r\" := (cdl_dia1C p r) (at level 63).\nNotation \"< p > e\" := (cdl_dia2C p e) (at level 63).\nNotation \"e1 \\/' e2\" := (cdl_orC e1 e2) (at level 71, right associativity).\nNotation \"e1 ->' e2\" := (cdl_impC e1 e2) (at level 72, right associativity).\n\nCheck tt'.\nCheck ff'.\nCheck (5 -' 3) <' 2.\nCheck ([ skip ]' c1 << c2) /\\' 2 >' 5 /\\' tt'.\nCheck [ @ {x :=' 4 | c1 ! 5} ; (x '> 0) ? {c2!4} ; @ idle; skip] n(c) >' 0.\nCheck [(@ {x :=' 4 | c1 ! 5} ; (x '> 0) ? {c2!4} ; @ idle; skip)** ]' c1<<c2.\nCheck [ skip ]' c1 << c2 .\nCheck all x , 4 =' 5.\n\n\n\n\n\n(* ===================================================== CDL Calculus ======================================*)\n\n\n(*************************** Auxiliary Functions ***************************)\n(*check if a dynamic formula is a pure FOL formula *)\n\nFixpoint CheckPureFOL (e : CDL_exp) : Prop :=\n  match e with\n  | cdl_trueC => True\n  | cdl_ltC e1 e2 => True\n  | cdl_box1C p r => False\n  | cdl_box2C p e' => False\n  | cdl_negC e' => CheckPureFOL e'\n  | cdl_andC e1 e2 => (CheckPureFOL e1) /\\ (CheckPureFOL e2)\n  | cdl_forallC x e' => (CheckPureFOL e')\n  | cdl_falseC => True\n  | cdl_lteC e1 e2 => True\n  | cdl_gtC e1 e2 => True\n  | cdl_gteC e1 e2 => True\n  | cdl_eqC e1 e2 => True\n  | cdl_dia1C p r => False\n  | cdl_dia2C p e' => False\n  | cdl_orC e1 e2 => (CheckPureFOL e1) /\\ (CheckPureFOL e2)\n  | cdl_impC e1 e2 => (CheckPureFOL e1) /\\ (CheckPureFOL e2)\n  end.\n\n\n(* a structure of (true, false, `undefined') *)\nInductive Bool :=\n  bBoolC : Prop -> Bool |\n  bUndefC : Bool\n.\n\n(*\nNotation \"[ b ]\" := (bBoolC b) (at level 74).\nNotation \"_|_\" := bUndefC (at level 74).\n*)\n\n(* evaluate a pure FOL formula in CDL formula *)\n\n\n(* during the derivation we need to translate expression e to expression E. In the semantics of dynamic logic, their \ncorresponding arithmetical opertors have the same meanings *)\n\nFixpoint e_2_E (e : e_exp) : E_exp :=\n  match e with\n  | enumC n => EnumC n\n  | evarC s => EvarC s\n  | eplusC e1 e2 => EplusC (e_2_E e1) (e_2_E e2)\n  | eminusC e1 e2 => EminusC (e_2_E e1) (e_2_E e2)\n  | emulC e1 e2 => EmulC (e_2_E e1) (e_2_E e2)\n  | edivC e1 e2 => EdivC (e_2_E e1) (e_2_E e2)\n  end.\n\n\n\n\n\n(* -------------------------------computation of free variables in cdl formula----------------------------------------*)\n(***\nNote that actually here we compute all occurrences of free variables in a cdl formula, not really all free variables, because\nhere we use `list' as the structure to `store' each appearance of free variables. \nIt is enough for us to check whether a variable is a free variable or not in a formula checking if it does not equal to \neach occurrence of variables. \n***)\n\n(* this function check whether a variable (i.e. a string) belongs to a list of variables (list of string) *)\nFixpoint NotIn_bool (s : string) (vec : list string) : bool :=\n  match vec with\n  | nil => true\n  | v :: vec' => if (string_dec s v) then false else NotIn_bool s vec'\n  end.\n\nCompute NotIn_bool x (x :: y :: z :: nil).\nCompute NotIn_bool c (x :: y :: z :: nil).\n\n(* this is another version for Prop type, just in case we need it in building the proof system*)\nFixpoint NotIn (s : string) (vec : list string) : Prop :=\n  match vec with\n  | nil => True\n  | v :: vec' => if (string_dec s v) then False else NotIn s vec'\n  end.\n\nCompute NotIn x (x :: y :: z :: nil).\nCompute NotIn c (x :: y :: z :: nil).\n\nFixpoint In (s : string) (vec : list string) : Prop :=\n  match vec with\n  | nil => False\n  | v :: vec' => if (string_dec s v) then True else In s vec'\n  end.\n\nFixpoint E_exp_FV (e : E_exp) (bv : list string) : list string := (*bv : list of bounded variables at current time *)\n  match e with\n  | EvarC v => if (NotIn_bool v bv) then (v :: nil) else nil\n  | ECntClkC c => nil\n  | EStClkC c => nil\n  | EnumC n => nil\n  | EplusC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  | EmulC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  | EminusC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  | EdivC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  end\n.\n\nCompute E_exp_FV (x +' 3 *' n(c)) nil.\nCompute E_exp_FV (x +' 3 *' z) nil.\nCompute E_exp_FV (x +' 3 *' z) (x :: nil).\n\n\nFixpoint e_exp_FV (e : e_exp) (bv : list string) : list string :=\n  match e with \n  | enumC n => nil\n  | evarC s => if (NotIn_bool s bv) then (s :: nil) else nil\n  | eplusC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  | eminusC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  | emulC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  | edivC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  end\n.\n\nCompute e_exp_FV (x '+ 3 '* 5) nil.\nCompute e_exp_FV (x '+ 3 '* z) nil.\nCompute e_exp_FV (x '+ 3 '/ z) (x :: nil).\n\nFixpoint P_exp_FV (P : P_exp) (bv : list string) : list string :=\n  match P with\n  | PtrueC => nil\n  | PlteC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  | PnegC P' => P_exp_FV P' bv\n  | PandC P1 P2 => (P_exp_FV P1 bv) ++ (P_exp_FV P2 bv)\n  | PfalseC => nil\n  | PltC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  | PgtC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  | PgteC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  | PeqC e1 e2 => (e_exp_FV e1 bv) ++ (e_exp_FV e2 bv)\n  | PorC P1 P2 => (P_exp_FV P1 bv) ++ (P_exp_FV P2 bv)\n  | PimpC P1 P2 => (P_exp_FV P1 bv) ++ (P_exp_FV P2 bv)\n  end\n.\n\nCompute P_exp_FV ('tt '/\\ (3 '= 5 '* x)) nil.\nCompute P_exp_FV ('tt '/\\ (3 '= 5 '* x)) (x :: nil).\nCompute P_exp_FV (y '<= 5 '/\\ (3 '= 5 '* x)) (z :: nil).\n\nFixpoint EvtE_FV (e : EvtElement) (bv : list string) : list string :=\n  match e with \n  | sigC s e' => e_exp_FV e' bv\n  | assC s e' => e_exp_FV e' bv\n  end\n.\n\nFixpoint Evt_FV (evt : Evt) (bv : list string) : list string :=\n  match evt with \n  | nil => nil\n  | e :: evt' => (EvtE_FV e bv) ++ (Evt_FV evt' bv)\n  end\n.\n\nCompute Evt_FV ({ x:='y '+ 2 | c ! (z '* 38)}) nil.\nCompute Evt_FV ({ x:='y '+ 2 | c ! (z '* 38)}) (y :: nil).\n\nFixpoint SEP_exp_FV (e : SEP_exp) (bv : list string) : list string :=\n  match e with \n  | skip => nil\n  | evtC evt => (Evt_FV evt bv)\n  | tstC P evt => (P_exp_FV P bv) ++ (Evt_FV evt bv)\n  | seqC e1 e2 => (SEP_exp_FV e1 bv) ++ (SEP_exp_FV e2 bv)\n  | choC e1 e2 => (SEP_exp_FV e1 bv) ++ (SEP_exp_FV e2 bv)\n  | loopC e' => (SEP_exp_FV e' bv)\n  end\n.\n\nCheck x '> 2 ? { y :=' y '- z}.\nCompute SEP_exp_FV ((@ { x :=' 5}; x '> 2 ? { y :=' y '- z} U skip) **) nil.\n\nFixpoint cdl_FV (e : CDL_exp) (bv : list string) : list string := (*bv : list of bounded variables at current time *)\n  match e with\n  | cdl_trueC => nil\n  | cdl_ltC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  | cdl_box1C p r => SEP_exp_FV p bv\n  | cdl_box2C p e' => (SEP_exp_FV p bv) ++ (cdl_FV e' bv)\n  | cdl_negC e' => cdl_FV e' bv\n  | cdl_andC e1 e2 => (cdl_FV e1 bv) ++ (cdl_FV e2 bv)\n  | cdl_forallC x1 e' => cdl_FV e' (x1 :: bv) (* x1 is a bounded variable *)\n  | cdl_falseC => nil\n  | cdl_lteC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  | cdl_gtC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  | cdl_gteC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  | cdl_eqC e1 e2 => (E_exp_FV e1 bv) ++ (E_exp_FV e2 bv)\n  | cdl_dia1C p r => SEP_exp_FV p bv\n  | cdl_dia2C p e' => (SEP_exp_FV p bv) ++ (cdl_FV e' bv)\n  | cdl_orC e1 e2 => (cdl_FV e1 bv) ++ (cdl_FV e2 bv)\n  | cdl_impC e1 e2 => (cdl_FV e1 bv) ++ (cdl_FV e2 bv)\n  end\n.\n\nCheck ( all y , y =' 7 ) .\nCompute cdl_FV ([ (@ { x :=' 5}; x '> 2 ? { y :=' y '- z} U skip) ] x >' 0 /\\' ( all y , y =' 7 ) ) nil.\nCompute cdl_FV ([ (@ { x :=' 5}; x '> 2 ? { y :=' y '- z} U skip) ] x >' 0 /\\' ( all y , y =' 7 ) ) (y :: nil).\n\n\n(* for list *)\nFixpoint cdl_FV_l (T : list CDL_exp) (bv : list string) : list string :=\n  match T with \n  | nil => nil\n  | e :: T' => (cdl_FV e bv) ++ (cdl_FV_l T' bv)\n  end.\n\n(* -------------------------------substitution for single variable----------------------------------------*)\nFixpoint E_exp_subs (e : E_exp) (x' : string) (x : string) : E_exp := \n  match e with\n  | EvarC v => if (string_dec v x) then EvarC x' else EvarC v\n  | ECntClkC c => ECntClkC c (* do not consider replacing a clock-related variable *)\n  | EStClkC c => EStClkC c\n  | EnumC n => EnumC n\n  | EplusC e1 e2 => EplusC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | EmulC e1 e2 => EmulC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | EminusC e1 e2 => EminusC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | EdivC e1 e2 => EdivC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  end\n.\n\nCompute E_exp_subs (x +' y) y x.\nCompute E_exp_subs (x *' z) y c.\nCompute E_exp_subs (n(c) *' z) y z.\n\nNotation \"e [ x' 'subs-E' x ]\" := (E_exp_subs e x' x) (at level 9).\n\nFixpoint e_exp_subs (e : e_exp) (x' : string) (x : string) : e_exp :=\n  match e with\n  | enumC n => enumC n\n  | evarC s => if (string_dec s x) then evarC x' else evarC s\n  | eplusC e1 e2 => eplusC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | eminusC e1 e2 => eminusC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | emulC e1 e2 => emulC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | edivC e1 e2 => edivC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  end\n.\n\nCompute e_exp_subs ((z '- 5) '* x '+ z) y z.\n\nFixpoint P_exp_subs (P : P_exp) (x' : string) (x : string) : P_exp :=\n  match P with\n  | PtrueC => PtrueC \n  | PlteC e1 e2 => PlteC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PnegC P' => PnegC (P_exp_subs P' x' x)\n  | PandC P1 P2 => PandC (P_exp_subs P1 x' x) (P_exp_subs P2 x' x)\n  | PfalseC => PfalseC\n  | PltC e1 e2 => PltC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PgtC e1 e2 => PgtC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PgteC e1 e2 => PgteC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PeqC e1 e2 => PeqC (e_exp_subs e1 x' x) (e_exp_subs e2 x' x)\n  | PorC P1 P2 => PorC (P_exp_subs P1 x' x) (P_exp_subs P2 x' x)\n  | PimpC P1 P2 => PimpC (P_exp_subs P1 x' x) (P_exp_subs P2 x' x)\n  end\n.\n\nCompute P_exp_subs ('tt '/\\ '~ (x '< 5)) z x.\n\nFixpoint EvtE_subs (e : EvtElement) (x' : string) (x : string) : EvtElement :=\n  match e with \n  | sigC s e' => sigC s (e_exp_subs e' x' x)\n  | assC s e' => assC s (e_exp_subs e' x' x)\n  end\n.\n\nCompute EvtE_subs (c ! x '+ 5) y x.\nCompute EvtE_subs (x :=' (5 '* x '+ 3 '/ y)) z x. \n\nFixpoint Evt_subs (evt : Evt) (x' : string) (x : string) : Evt :=\n  match evt with \n  | nil => nil\n  | e :: evt' => (EvtE_subs e x' x) :: (Evt_subs evt' x' x)\n  end\n.\n\nCompute Evt_subs ( { c ! x '+ 5 | x :=' 5 '* x '+ 3 '/ y }) z x. \n\n\nFixpoint SEP_exp_subs (e : SEP_exp) (x' : string) (x : string) : SEP_exp :=\n  match e with \n  | skip => skip\n  | evtC evt => evtC (Evt_subs evt x' x)\n  | tstC P evt => tstC (P_exp_subs P x' x) (Evt_subs evt x' x) \n  | seqC e1 e2 => seqC (SEP_exp_subs e1 x' x) (SEP_exp_subs e2 x' x)\n  | choC e1 e2 => choC (SEP_exp_subs e1 x' x) (SEP_exp_subs e2 x' x)\n  | loopC e' => loopC (SEP_exp_subs e' x' x)\n  end\n.\n\nCompute SEP_exp_subs ( @ { c ! x '+ 5 | x :=' 5 '* x '+ 3 '/ y }) z x. \n\nFixpoint cdl_subs (e : CDL_exp) (x' : string) (x : string) : CDL_exp := (* e[x' // x] *)\n  match e with\n  | cdl_trueC => cdl_trueC\n  | cdl_ltC e1 e2 => cdl_ltC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_box1C p r => cdl_box1C (SEP_exp_subs p x' x) r (* do not consider replacing a clock-related variable *)\n  | cdl_box2C p e' => cdl_box2C (SEP_exp_subs p x' x) (cdl_subs e' x' x)\n  | cdl_negC e' => cdl_negC (cdl_subs e' x' x)\n  | cdl_andC e1 e2 => cdl_andC (cdl_subs e1 x' x) (cdl_subs e2 x' x)\n  | cdl_forallC x1 e' => if (string_dec x1 x) then cdl_forallC x1 e' else (cdl_subs e' x' x) \n  | cdl_falseC => cdl_falseC\n  | cdl_lteC e1 e2 => cdl_lteC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_gtC e1 e2 => cdl_gtC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_gteC e1 e2 => cdl_gteC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_eqC e1 e2 => cdl_eqC (E_exp_subs e1 x' x) (E_exp_subs e2 x' x)\n  | cdl_dia1C p r => cdl_dia1C (SEP_exp_subs p x' x) r (* do not consider replacing a clock-related variable *)\n  | cdl_dia2C p e' => cdl_dia2C (SEP_exp_subs p x' x) (cdl_subs e' x' x)\n  | cdl_orC e1 e2 => cdl_orC (cdl_subs e1 x' x) (cdl_subs e2 x' x)\n  | cdl_impC e1 e2 => cdl_impC (cdl_subs e1 x' x) (cdl_subs e2 x' x)\n  end.\n\nNotation \"e [ x' 'subs' x ]\" := (cdl_subs e x' x) (at level 9).\nCheck [ skip ]' c1 << c2 .\nLocate \"/\".\nLocate \"//\".\nCompute ([ y '> 1 ? { x :=' x '+ 1 }; skip ; @ { x :=' x '+ 1 }]' c1 << c2) [ y subs x ] .\n\n\n(* substitution for list *)\nFixpoint cdl_subs_l (T : list CDL_exp) (x' : string) (x : string) : list CDL_exp := (* T [x' // x] *)\n  match T with\n  | nil => nil\n  | e :: T' => (cdl_subs e x' x) :: (cdl_subs_l T' x' x)\n  end.\n\nNotation \"T [ x' 'subs-l' x ]\" := (cdl_subs_l T x' x) (at level 9).\n\n\n(* ====================================================== CDL Rules =============================================*)\n\nDefinition Gamma := list CDL_exp.\nDefinition Delta := list CDL_exp.\n\n(***DEL Definition SequentL : Gamma -> CDL_exp -> Delta -> Prop.*)\n\n\n(* we arrange a place special for the dynamic formula we want to verify in the sequent, other formulas in Gamma\nand Delta are pure FOL formulas. \n\nWe define two types of sequent: sequentL and sequentR, where L and R indicate the verifiying formula is on the left\nor right side of the sequent. \n*)\n\nInductive place := \n  exp : CDL_exp -> place |\n  empty : place\n.\n\n\n(*\nNotation \"'<<' e '>>'\" := (exp e) (at level 74, e at level 72).\nNotation \"<< >>\" := empty (at level 74).\nCheck << x <=' y >> .\nCheck << >>.\nLocate \"<< >>\".\n*)\n\n\nReserved Notation \"{ T , p1 ==> p2 , D }\" (at level 75).\n(*Reserved Notation \"T ==> p , D\" (at level 75).*)\n\nLocate \"==>\".\n\n(*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& a simple test &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*)\n\n(*** as a test, we firstly implement a simple rule here, to check if everything in my mind would work well, \nwe first realize the rule: \n    T[x'/x],x = e[x'/x] => E, D[x'/x]\n    ---------------------------------\n    T => [x := e] E, D\n\nIt is equavalent to realize the rule:\n    forall x'. (x' not free in T, e, D) -> (T[x'/x],x = e[x'/x] => E, D[x'/x]) -> (T => [x := e] E, D)\n***)\n\n(* To be simple, we firstly define a sequent as a triple (\\Gamma, formula, \\Delta), where \\Gamma and \\Delta are the context of \nthe formula that we are going to transform. *)\n\n(**DEL\nInductive tstSeq : Gamma -> place -> place -> Delta -> Type :=\n  tst1 : forall (T : Gamma) (D : Delta) (e : e_exp) (phi : CDL_exp) (x : string), \n          (\n          forall (z : string), \n          (tstSeq ((x =' (e_2_E e) [z subs-E x]) :: (T [ z subs-l x ])) \n                   empty \n                  (exp phi) \n                  (D [ z subs-l x ]) )\n        ) -> \n    (tstSeq T empty (exp ([ @ {x :=' e} ] phi)) D)\nwhere \"{ T , p1 ==> p2 , D }\" := (tstSeq T p1 p2 D)\n.\n\n(* Theorem thm1 : (x =' 1) :: nil , empty ==> [ @ {x :=' x '+ 1}] x >' 2 , nil .*)\n\nTheorem thm1 : tstSeq ((y =' 1) :: nil) empty (exp ([ @ {y :=' y '+ z}] y >' 2)) nil .\nProof. \napply tst1.\nintros. simpl. \nAbort.\n\nTheorem thm2 : { ((y =' 1):: nil) , empty ==> exp ([ @ {y :=' y '+ z}] y >' 2) , nil }.\nDEL**)\n\nInductive tstSeq2 : Gamma -> place -> place -> Delta -> Type :=\n  tst2 : forall (T : Gamma) (D : Delta) (e : e_exp) (phi : CDL_exp) (x : string) (A : Evt), \n          (\n          forall (z : string), \n          (forall (n : string), (In n ((cdl_FV_l T nil) ++ (cdl_FV_l D nil) ++ (e_exp_FV e nil) ++ (Evt_FV A nil) ++ (cdl_FV phi nil)))\n                                  -> (n <> z)\n          ) ->\n          (tstSeq2 ((x =' (e_2_E e) [z subs-E x]) :: (T [ z subs-l x ])) \n                   empty \n                  (exp ([ @ A ] phi)) \n                  (D [ z subs-l x ]) )\n        ) -> \n    (tstSeq2 T empty (exp ([ @ ((x :=' e) :: A) ] phi)) D) \n  |\n  tst3 : forall (T : Gamma) (D : Delta) (phi : CDL_exp), \n          (\n          tstSeq2 T \n                   empty \n                  (exp phi) \n                  D\n        ) -> \n    (tstSeq2 T empty (exp ([ @ idle ] phi)) D)\nwhere \"{ T , p1 ==> p2 , D }\" := (tstSeq2 T p1 p2 D)\n.\n\nLocate \"<>\".\n\nCompute x = y.\n\nTheorem thm2 : { ((y =' 1):: nil) , empty ==> exp ([ @ {y :=' y '+ z | y :=' y '+ 1}] y >' 2) , nil }.\nProof. \napply tst2.\nintros. simpl.\napply tst2.\nintros. simpl.\napply tst3. simpl.\nsimpl H.\nAbort.\n\n(*DEL\nInductive E_expt :=\n  tvarC : Type -> E_expt |\n  tCntClkC : Type -> E_expt | \n  tStClkC : Type -> E_expt |\n  tnumC : nat -> E_expt |\n  tplusC : E_expt -> E_expt -> E_expt |\n  (* unecessary expression *)\n  tmulC : E_expt -> E_expt -> E_expt |\n  tminusC : E_expt -> E_expt -> E_expt |\n  tdivC : E_expt -> E_expt -> E_expt\n.\nPrint E_expt.\n\nVariable X : Type. \nVariable Y : Type. \n\nFixpoint E_expt_subs (e : E_expt) (x' : Type) (x : Type) : E_expt := \n  match e with\n  | tvarC x => tvarC x\n  | tCntClkC c => tCntClkC c (* do not consider replacing a clock-related variable *)\n  | tStClkC c => tStClkC c\n  | tnumC n => tnumC n\n  | tplusC e1 e2 => tplusC (E_expt_subs e1 x' x) (E_expt_subs e2 x' x)\n  | tmulC e1 e2 => tmulC (E_expt_subs e1 x' x) (E_expt_subs e2 x' x)\n  | tminusC e1 e2 => tminusC (E_expt_subs e1 x' x) (E_expt_subs e2 x' x)\n  | tdivC e1 e2 => tdivC (E_expt_subs e1 x' x) (E_expt_subs e2 x' x)\n  end\n.\nPrint E_expt_subs.\n***DEL*)\n\n(*** exploring how the `apply' works and how the pattern matching works in Coq ***)\nInductive ev : nat -> Prop :=\n  ev_0 : ev 0 |\n  ev_SS : forall (n : nat), ev n -> ev ( S (S n))\n.\n\nTheorem ev_4 : ev 4.\nProof. \napply ev_SS. apply ev_SS. apply ev_0.\nQed.\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\nInductive month : Set :=\n  Jan | Feb | Mar\n.\n \n\n(*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&  end of test &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*)\nInductive validSeq : sequent -> Type :=\n  tst : forall (T : Gamma) (p : CDL_exp) (D : Delta), (CheckPureFOL p) -> validSeq ( T ==> p , D ).\n\n", "meta": {"author": "zyr-rekcaha", "repo": "CDL", "sha": "eb9ea66875a709247c23d0ac132e57c8fdee3655", "save_path": "github-repos/coq/zyr-rekcaha-CDL", "path": "github-repos/coq/zyr-rekcaha-CDL/CDL-eb9ea66875a709247c23d0ac132e57c8fdee3655/CDLCalculus-191219.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859265, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7132722092875018}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling    [*]              *)\n(*             Jean-François Monin           [+]              *)\n(*                                                            *)\n(*           [*] Affiliation Univ. Lorraine - CNRS - LORIA    *)\n(*           [+] Affiliation VERIMAG - Univ. Grenoble Alpes   *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*        CeCILL v2.1 FREE SOFTWARE LICENSE AGREEMENT         *)\n(**************************************************************)\n\nFrom Coq Require Import Utf8.\n\nFrom MuRec Require Import relations arith_mini.\n\nSection btwn.\n\n  Variable P : nat → Prop.\n\n  (* Weak between formulated in FO arithmetic *)\n  Local Definition wbtwn n m := ∀ i, n ≤ i → i < m → P i.\n\n  (* Simulated constructors for weak between *)\n  Local Fact wbtwn_refl n : wbtwn n n.\n  Proof. intros ? H₁ H₂; destruct (lt_irrefl (le_lt_trans H₁ H₂)). Qed.\n\n  Local Fact wbtwn_next {n m} : wbtwn n m → P m → wbtwn n (S m).\n  Proof.\n    intros Bnm Hm i H₁ H₂.\n    destruct (le_S_n H₂); trivial.\n    apply Bnm; trivial.\n    now apply le_n_S.\n  Qed.\n\n  (* Between formulated in FO arithmetic *)\n  Definition btwn n m := n ≤ m ∧ wbtwn n m.\n\n  (* Simulated constructors for between *)\n  Fact btwn_refl n : btwn n n.\n  Proof. split; [apply le_n | apply wbtwn_refl]. Qed.\n\n  Fact btwn_next n m : btwn n m → P m → btwn n (S m).\n  Proof. intros [b w] p; split; [apply le_S, b | apply (wbtwn_next w p)]. Qed.\n\nEnd btwn.\n\nArguments btwn_refl {P n}.\nArguments btwn_next {P n m}.\n\n(* Monotonicity *)\nLocal Fact wbtwn_monotonic (P Q : nat → Prop) : P ⊆₁ Q → wbtwn P ⊆₂ wbtwn Q.\nProof. now intros M ? ? Hnm ? ? ?; apply M, Hnm. Qed.\n\nFact btwn_monotonic (P Q : nat → Prop) : P ⊆₁ Q → btwn P ⊆₂ btwn Q.\nProof.\n  intros ? ? ? [? H]; split; trivial.\n  revert H; now apply wbtwn_monotonic.\nQed.\n\nFact btwn_monotonic₁ {P Q : nat → Prop} s : P ⊆₁ Q → btwn P s ⊆₁ btwn Q s.\nProof. exact (λ i_pq, btwn_monotonic P Q i_pq s). Qed.\n\n(* Choice property for between *)\nFact btwn_eq_or_holds {P a n m} : btwn P a n → btwn P a m → n = m ∨ P n ∨ P m.\nProof.\n  intros [an wn] [am wm].\n  destruct (lt_eq_lt_dec n m).\n  + right; left; now apply wm.\n  + now left.\n  + right; right; now apply wn.\nQed.\n\n(* A useful interval reverse induction principle for nat,\n   suitable for btwn, see below *)\nLocal Definition nat_interval_rev_ind {P : nat → Prop} :\n  ∀{a b}, a ≤ b → (∀n, a <= n → n < b → P (S n) → P n) → P b → P a :=\n  fix loop {a b} (Hab : a <= b) :=\n    match Hab with\n      | le_n     => λ _  Pa,  Pa\n      | le_S Hab => λ HP PSb, loop Hab (λ n Ha Hb, HP _ Ha (le_n_S (lt_le_weak Hb)))\n                                       (HP _ Hab le_n PSb)\n    end.\n\n(* (Reverse) induction principle for between *)\nCorollary btwn_ind (P : nat → Prop) a b : btwn (λ n, P (S n) → P n) a b → P b → P a.\nProof. intros [Hab HP]; exact (nat_interval_rev_ind Hab HP). Qed.\n\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Murec_Extraction", "sha": "73681e2a65bd3fc04e03e9ef835a351b44860125", "save_path": "github-repos/coq/DmxLarchey-Murec_Extraction", "path": "github-repos/coq/DmxLarchey-Murec_Extraction/Murec_Extraction-73681e2a65bd3fc04e03e9ef835a351b44860125/theories/between.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695836, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7132721948916046}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf1 : natural) (lf2 : natural)\n  : natural := plus (mult y z) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj174_coqofml_dyuGl6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7132167752704875}}
{"text": "\n\n(** Anthony Bordg, June 2017 ********************************************\n\nContents:\n\n- Bilinear morphisms between modules over a ring ([bilinearfun])\n- Algebras over a commutative ring ([algebra]) and associative, commutative, unital algebras ([assoc_comm_unital_algebra]), see Serge Lang,\nAlgebra, III.1, p.121 in the revised third edition.\n- Morphisms between (non-associative) algebras aver a commutative ring ([algebrafun])\n- The opposite algebra ([algebra_opp])\n- Subalgebras of an algebra ([subalgebra])\n\n ***********************************************)\n\nRequire Import UniMath.Algebra.Rigs_and_Rings.\nRequire Import UniMath.Algebra.Modules.\nRequire Import Types_and_groups_with_operators.\n\n\n(** * Bilinear morphims between modules over a ring *)\n\nDefinition isbilinear {R : rng} {M N P : module R} (f : M -> N -> P) : UU :=\n  (∏ x : M, ismodulefun (λ y : N, f x y) ) × (∏ y : N, ismodulefun (λ x : M, f x y)).\n\nDefinition bilinearfun {R : rng} (M N P : module R) : UU := ∑ f : M -> N -> P, isbilinear f.\n\nDefinition pr1bilinearfun {R : rng} {M N P : module R} (f : bilinearfun M N P) : M -> N -> P := pr1 f.\n\nCoercion pr1bilinearfun : bilinearfun >-> Funclass.\n\n\n(** * Algebras over a commutative ring *)\n\nSection algebras.\nVariable R : commrng.\n\n(** Non-associative algebras over a commutative ring *)\n\n\nDefinition algebra : UU := ∑ M : module R, bilinearfun M M M.\n\nDefinition pr1algebra (A : algebra) : module R := pr1 A.\n\nCoercion pr1algebra : algebra >-> module.\n\nDefinition algebra_pair (M : module R) (f : bilinearfun M M M) : algebra := tpair (λ X : module R, bilinearfun X X X) M f.\n\nDefinition mult_algebra (A : algebra) : binop A := pr1 (pr2 A).\n\nDefinition isbilinear_mult_algebra (A : algebra) : isbilinear (mult_algebra A) := pr2 (pr2 A).\n\nNotation \"x * y\" := (mult_algebra _ x y) : algebras_scope.\n\nDelimit Scope algebras_scope with algebras.\n\n(** Commutative algebras over a commutative ring *)\n\nDefinition iscomm_algebra (A : algebra) : UU := iscomm (mult_algebra A).\n\nDefinition commalgebra : UU := ∑ A : algebra, iscomm_algebra A.\n\nDefinition commalgebra_pair (A : algebra) (is : iscomm_algebra A) : commalgebra := tpair _ A is.\n\nDefinition commalgebra_to_algebra (A : commalgebra) : algebra := pr1 A.\n\nCoercion commalgebra_to_algebra : commalgebra >-> algebra.\n\n(** Associative  algebras over a commutative ring *)\n\nDefinition isassoc_algebra (A : algebra) : UU := isassoc (mult_algebra A).\n\nDefinition assocalgebra : UU := ∑ A : algebra, isassoc_algebra A.\n\nDefinition assocalgebra_pair (A : algebra) (is : isassoc_algebra A) : assocalgebra := tpair _ A is.\n\nDefinition assocalgebra_to_algebra (A : assocalgebra) : algebra := pr1 A.\n\nCoercion assocalgebra_to_algebra : assocalgebra >-> algebra.\n\n(** Unital algebras over a commutative ring *)\n\nDefinition isunital_algebra (A : algebra) : UU := isunital (mult_algebra A).\n\nDefinition unitalalgebra : UU := ∑ A : algebra, isunital_algebra A.\n\nDefinition unitalalgebra_pair (A : algebra) (is : isunital_algebra A) : unitalalgebra := tpair _ A is.\n\nDefinition unitalalgebra_to_algebra (A : unitalalgebra) : algebra := pr1 A.\n\nCoercion unitalalgebra_to_algebra : unitalalgebra >-> algebra.\n\n(** Unital associative algebras over a commutative ring *)\n\nDefinition unital_assoc_algebra : UU := ∑ A : algebra, (isassoc_algebra A) × (isunital_algebra A).\n\nDefinition unital_assoc_algebra_to_algebra (A : unital_assoc_algebra) : algebra := pr1 A.\n\nCoercion unital_assoc_algebra_to_algebra : unital_assoc_algebra >-> algebra.\n\n(** Associative, commutative, unital algebras over a ring *)\n\nDefinition assoc_comm_unital_algebra : UU := ∑ A : unital_assoc_algebra, iscomm_algebra A.\n\n(** Morphisms between (non-associative) algebras over a commutative ring *)\n\nLocal Open Scope algebras.\n\nDefinition algebrafun (A B : algebra) : UU := ∑ f : modulefun A B, ∏ x y : A, f (x * y) = f x * f y.\n\n(** * The opposite algebra  *)\n\nDefinition mult_opp (A : algebra) : A -> A -> A := λ x y : A, y * x.\n\nDefinition isbilinear_mult_opp (A : algebra) : isbilinear (mult_opp A).\nProof.\n  apply dirprodpair.\n  - intro a. apply dirprodpair.\n    + intros x x'. apply (pr1 (pr2 (isbilinear_mult_algebra A) a) x x').\n    + intros r b. apply (pr2 (pr2  (isbilinear_mult_algebra A) a) r b).\n  - intro a. apply dirprodpair.\n    + intros x x'. apply (pr1 (pr1 (isbilinear_mult_algebra A) a) x x').\n    + intros r b. apply (pr2 (pr1  (isbilinear_mult_algebra A) a) r b).\nDefined.\n\nDefinition bilinear_mult_opp (A : algebra) : bilinearfun A A A := tpair _ (mult_opp A) (isbilinear_mult_opp A).\n\nDefinition algebra_opp (A : algebra) : algebra := tpair (λ X : module R, bilinearfun X X X) A (bilinear_mult_opp A).\n\n(** * Subalgebras of an algebra *)\n\nDefinition subalgebra (A : algebra) : UU := ∑ B : submodule (pr1 A), isstable_by_action (mult_algebra A) (pr1 B).\n\nDefinition subalgebra_to_module {A : algebra} (B : subalgebra A) : module R := submodule_to_module (pr1 B).\n\nDefinition subalgebra_to_mult {A : algebra} (B : subalgebra A) : binop (subalgebra_to_module B).\nProof.\n  intros x y.\n  split with (mult_algebra A (pr1 x) (pr1 y)).\n  exact (pr2 B (pr1 x) (pr1 y) (pr2 y)).\nDefined.\n\nDefinition isbilinear_subalgebra_to_mult {A : algebra } (B : subalgebra A) : isbilinear (subalgebra_to_mult B).\nProof.\n  apply dirprodpair.\n  - intro x. unfold ismodulefun.\n    apply dirprodpair.\n    +  unfold isbinopfun. intros x0 x'.\n       use total2_paths2_f.\n       apply (dirprod_pr1 (pr2 (pr2 A))).\n       apply propproperty.\n    +  intros r y.\n       use total2_paths2_f.\n       apply (dirprod_pr1 (pr2 (pr2 A))).\n       apply propproperty.\n  - intro y. apply dirprodpair.\n    + intros x x'.\n      use total2_paths2_f.\n      apply (dirprod_pr2 (pr2 (pr2 A))).\n      apply propproperty.\n    + intros r x.\n      use total2_paths2_f.\n      apply (dirprod_pr2 (pr2 (pr2 A))).\n      apply propproperty.\nDefined.\n\nDefinition subalgebra_to_bilinearfun {A : algebra} (B : subalgebra A) :\n  bilinearfun (subalgebra_to_module B) (subalgebra_to_module B) (subalgebra_to_module B) :=\n    tpair _ (subalgebra_to_mult B) (isbilinear_subalgebra_to_mult B).\n\nDefinition subalgebra_to_algebra {A : algebra} (B : subalgebra A) : algebra :=\n  algebra_pair (subalgebra_to_module B) (subalgebra_to_bilinearfun B).\n\nEnd algebras.", "meta": {"author": "AnthonyBordg", "repo": "UniLab", "sha": "0e470d57a045bd93c4fa7dbe40332771f37e0761", "save_path": "github-repos/coq/AnthonyBordg-UniLab", "path": "github-repos/coq/AnthonyBordg-UniLab/UniLab-0e470d57a045bd93c4fa7dbe40332771f37e0761/UniLab/UniMath/Algebras.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.713208959928821}}
{"text": "Definition my_False : Prop := forall P:Prop, P.\n\nDefinition my_not (P:Prop) : Prop := P -> my_False.\n\nDefinition my_and (P Q:Prop) : Prop := forall R:Prop, (P -> Q -> R) -> R.\n\nDefinition my_or (P Q:Prop) : Prop :=\n  forall R:Prop, (P -> R) -> (Q -> R) -> R.\n\nDefinition my_ex (A:Set) (P:A -> Prop) : Prop :=\n  forall R:Prop, (forall x:A, P x -> R) -> R.\n\n\nTheorem my_and_left : forall P Q:Prop, my_and P Q -> P.\nProof.\n intros P Q H; apply H; auto.\nQed.\n\nTheorem my_and_right : forall P Q:Prop, my_and P Q -> Q.\nProof.\n intros P Q H; apply H; auto.\nQed.\n\nTheorem my_and_ind : forall P Q R:Prop, (P -> Q -> R) -> my_and P Q -> R.\nProof.\n  intros P Q R H H0; apply H0; assumption.\nQed.\n\n\nTheorem my_or_introl : forall P Q:Prop, P -> my_or P Q.\nProof.\n  unfold my_or; auto.  \nQed.\n\nTheorem my_or_intror : forall P Q:Prop, Q -> my_or P Q.\nProof.\n  unfold my_or; auto.  \nQed.\n\nTheorem my_or_ind : forall P Q R:Prop, (P -> R) -> (Q -> R) -> my_or P Q -> R.\nProof.\n  intros P Q R H H0 H1; apply H1; assumption.\nQed.\n\nTheorem my_or_False : forall P:Prop, my_or P my_False -> P.\nProof.\n unfold my_False; intros P H; apply H; intro H0; apply H0.\nQed.\n\nTheorem my_or_comm : forall P Q:Prop, my_or P Q -> my_or Q P.\nProof.\n intros P Q H; apply H; intros H0 R; auto.\nQed.\n\n\nTheorem my_ex_intro : forall (A:Set) (P:A -> Prop) (a:A), P a -> my_ex A P.\nProof.\n intros A P a Ha R H; eapply H; eauto.\nQed.\n\nTheorem my_not_ex_all :\n forall (A:Set) (P:A -> Prop), my_not (my_ex A P) -> forall a:A, my_not (P a).\nProof.\n intros A P H a H'.\n apply H; eapply my_ex_intro; eauto.\nQed.\n\n\n\n\nTheorem my_ex_ex : forall (A:Set) (P:A -> Prop), my_ex A P -> ex P.\nProof.\n intros A P H; apply H.\n intros x Hx; exists x; assumption.\nQed.\n\n\n\nTheorem ex_my_ex : forall (A:Set) (P:A -> Prop), ex P -> my_ex _ P.\nProof.\n intros A P H; elim H; intros x Hx R.\n intros H0; eapply H0; eapply Hx.\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/depprod/SRC/impred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7131096756839277}}
{"text": "(* De Morgan Algebra *)\n\n(** A De Morgan algebra is an algebraic structure ([A], [∨], [∧], [¬]) consisting of:\n    - a set [A].\n    - three binary operations [∨], [∧] and [¬] on [A], such that\n      - ([A], [∨], [∧]) is a bounded distributive lattice.\n      - [¬] is a De Morgan involution.\n *)\n\nParameter A : Set.\n\nParameter O : A.\nParameter I : A.\n\nParameter join : A -> A -> A.\nInfix \"∨\" := join (left associativity, at level 50): type_scope.\n\nParameter meet : A -> A -> A.\nInfix \"∧\" := meet (left associativity, at level 50): type_scope.\n\nParameter involution : A -> A.\nNotation \"¬ x\" := (involution x) (at level 50): type_scope.\n\nAxiom join_commutativity : forall a b, a ∨ b = b ∨ a.\nAxiom meet_commutativity : forall a b, a ∧ b = b ∧ a.\n\nAxiom join_associativity : forall a b c, a ∨ (b ∨ c) = (a ∨ b) ∨ c.\nAxiom meet_associativity : forall a b c, a ∧ (b ∧ c) = (a ∧ b) ∧ c.\n\nAxiom join_absorptivity : forall a b, a ∨ (a ∧ b) = a.\nAxiom meet_absorptivity : forall a b, a ∧ (a ∨ b) = a.\n\n(* bounded lattice *)\nAxiom join_identity_element_existence : forall a, a ∨ O = a /\\ O ∨ a = a.\nAxiom meet_identity_element_existence : forall a, a ∧ I = a /\\ I ∧ a = a.\n\n(* distributive lattice *)\nAxiom left_distributivity : forall a b c, a ∨ (b ∧ c) = (a ∨ b) ∧ (a ∨ c).\n(* right_distributivity follows from join_commutativity and left_distributivity:\n   (a ∧ b) ∨ c = c ∨ (a ∧ b) = (c ∨ a) ∧ (c ∨ b) = (a ∨ c) ∧ (b ∨ c).\n *)\nTheorem right_distributivity: forall a b c, (a ∧ b) ∨ c = (a ∨ c) ∧ (b ∨ c).\nProof.\n  intros a b c.\n  rewrite <- join_commutativity.\n  rewrite -> left_distributivity.\n  pattern (c ∨ a); rewrite <- join_commutativity.\n  pattern (c ∨ b); rewrite <- join_commutativity.\n  trivial.\nQed.\n\n(* De Morgan's laws *)\nAxiom de_morgan_1 : forall a b, ¬(a ∧ b) = ¬a ∨ ¬b.\nAxiom de_morgan_2 : forall a, ¬(¬a) = a.\n", "meta": {"author": "soimort", "repo": "some-proofs", "sha": "42748bb7ab35ea157114f83acb7ea7bc955b08d8", "save_path": "github-repos/coq/soimort-some-proofs", "path": "github-repos/coq/soimort-some-proofs/some-proofs-42748bb7ab35ea157114f83acb7ea7bc955b08d8/Algebras/DeMorgan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7131096734790285}}
{"text": "(* gcd a b with computation of a/gcd a b and b/gcd a b on the fly *)\n\nRequire Import Utf8 Arith Psatz.\nRequire Import Main.Misc Misc.\n\nSet Nested Proofs Allowed.\n\nTactic Notation \"flia\" hyp_list(Hs) := clear - Hs; lia.\n\nFixpoint ggcdn it a b :=\n  match it with\n  | 0 => (0, (0, 0))\n  | S it' =>\n      match a with\n      | 0 => (b, (0, b / b))\n      | _ =>\n          match Nat.compare a b with\n          | Eq => (a, (1, 1))\n          | Lt =>\n              let '(g, (a', b')) := ggcdn it' (b - a) a in\n              (g, (b', a' + b'))\n          | Gt =>\n              let '(g, (a', b')) := ggcdn it' b (a - b) in\n              (g, (a' + b', a'))\n          end\n      end\n  end.\nDefinition ggcd a b := ggcdn (a + b + 1) a b.\n\nTheorem ggcdn_gcd : ∀ a b n, a + b + 1 ≤ n → fst (ggcdn n a b) = Nat.gcd a b.\nProof.\nintros * Hab.\nrevert a b Hab.\ninduction n; intros.\n-now apply Nat.le_0_r, Nat.eq_add_0 in Hab.\n-simpl.\n destruct a; [ easy | ].\n simpl in Hab.\n apply Nat.succ_le_mono in Hab.\n remember (Nat.compare (S a) b) as c eqn:Hc; symmetry in Hc.\n destruct c.\n +apply Nat.compare_eq_iff in Hc; rewrite Hc.\n  now rewrite Nat.gcd_diag.\n +apply Nat.compare_lt_iff in Hc.\n  specialize (IHn (b - S a) (S a)) as H1.\n  assert (H : b - S a + S a + 1 ≤ n) by flia Hab Hc.\n  specialize (H1 H); clear H.\n  remember (ggcdn n (b - S a) (S a)) as gab eqn:Hgab.\n  symmetry in Hgab.\n  destruct gab as (g, (a', b')).\n  rewrite Nat.gcd_comm, Nat.gcd_sub_diag_r in H1; [ easy | flia Hc ].\n +apply Nat.compare_gt_iff in Hc.\n  destruct b.\n  *destruct n; [ now rewrite Nat.add_comm in Hab | simpl ].\n   now rewrite Nat.sub_diag.\n  *specialize (IHn (S b) (S a - S b)) as H1.\n   assert (H : S b + (S a - S b) + 1 ≤ n) by flia Hab Hc.\n   specialize (H1 H); clear H.\n   remember (ggcdn n (S b) (S a - S b)) as gab eqn:Hgab.\n   symmetry in Hgab.\n   destruct gab as (g, (a', b')).\n   rewrite Nat.gcd_sub_diag_r in H1; [ | flia Hc ].\n   now rewrite Nat.gcd_comm in H1.\nQed.\n\nTheorem ggcd_gcd : ∀ a b, fst (ggcd a b) = Nat.gcd a b.\nProof. now intros; apply ggcdn_gcd. Qed.\n\nTheorem ggcdn_correct_divisors : ∀ a b n,\n  a + b + 1 ≤ n\n  → let '(g, (aa, bb)) := ggcdn n a b in\n     a = g * aa ∧ b = g * bb.\nProof.\nintros * Hn.\nremember (ggcdn n a b) as g eqn:Hg.\ndestruct g as (g, (aa, bb)).\nrevert a b g aa bb (*Hb*) Hn Hg.\ninduction n; intros; [ flia Hn | ].\nsimpl in Hg.\ndestruct a.\n-injection Hg; clear Hg; intros; subst g aa bb.\n destruct b; [ easy | ].\n rewrite Nat.div_same; [ flia | easy ].\n-remember (S a ?= b) as c1 eqn:Hc1; symmetry in Hc1.\n destruct c1.\n +apply Nat.compare_eq_iff in Hc1.\n  subst b.\n  injection Hg; clear Hg; intros; subst g aa bb; flia.\n +apply Nat.compare_lt_iff in Hc1.\n  remember (ggcdn n (b - S a) (S a)) as g1 eqn:Hg1.\n  destruct g1 as (g1, (aa1, bb1)).\n  injection Hg; clear Hg; intros; subst g1 bb1 bb.\n  specialize (IHn (b - S a) (S a) g aa1 aa (*Nat.neq_succ_0 a*)) as H1.\n  assert (H : b - S a + S a + 1 ≤ n) by flia Hn Hc1.\n  specialize (H1 H Hg1) as (H1, H2); clear H.\n  split; [ easy | ].\n  apply Nat.add_sub_eq_nz in H1; [ flia H1 H2 | ].\n  intros H.\n  apply Nat.eq_mul_0 in H.\n  destruct H as [H| H]; [ now subst g | subst aa1; flia Hc1 H1 ].\n +apply Nat.compare_gt_iff in Hc1.\n  remember (ggcdn n b (S a - b)) as g1 eqn:Hg1.\n  destruct g1 as (g1, (aa1, bb1)).\n  injection Hg; clear Hg; intros; subst g1 aa1 aa.\n  destruct b.\n  *rewrite Nat.sub_0_r in Hg1.\n   destruct n; [ flia Hn | ].\n   remember (S a) as aa; simpl in Hg1; subst aa.\n   rewrite Nat.div_same in Hg1; [ | easy ].\n   injection Hg1; clear Hg1; intros; subst g bb bb1.\n   now rewrite Nat.add_0_l, Nat.mul_1_r, Nat.mul_0_r.\n  *specialize (IHn (S b) (S a - S b) g bb bb1) as H1.\n   assert (H : S b + (S a - S b) + 1 ≤ n) by flia Hn Hc1.\n   specialize (H1 H Hg1) as (H1, H2); clear H.\n   split; [ | easy ].\n   apply Nat.add_sub_eq_nz in H2; [ flia H1 H2 | ].\n   intros H.\n   apply Nat.eq_mul_0 in H.\n   destruct H as [H| H]; [ now subst g | subst bb1; flia Hc1 H2 ].\nQed.\n\nTheorem ggcd_correct_divisors : ∀ a b,\n  let '(g, (aa, bb)) := ggcd a b in\n  a = g * aa ∧ b = g * bb.\nProof. now intros; apply ggcdn_correct_divisors. Qed.\n\nTheorem ggcd_fst_snd : ∀ a b, fst (snd (ggcd a b)) = a / Nat.gcd a b.\nProof.\nintros.\nspecialize (ggcd_correct_divisors a b) as H.\nremember (ggcd a b) as g eqn:Hg.\ndestruct g as (g, (aa, bb)).\ndestruct H as (H1, H2); simpl.\ndestruct g.\n-simpl in H1, H2; subst a b; simpl.\n unfold ggcd in Hg; simpl in Hg.\n now injection Hg; intros; subst aa.\n-subst a b.\n specialize (ggcd_gcd (S g * aa) (S g * bb)) as H1.\n rewrite <- Hg in H1.\n rewrite <- H1.\n rewrite Nat.mul_comm, Nat.div_mul; [ easy | ].\n now intros H; simpl in H.\nQed.\n\nTheorem ggcd_snd_snd : ∀ a b, snd (snd (ggcd a b)) = b / Nat.gcd a b.\nProof.\nintros.\nspecialize (ggcd_correct_divisors a b) as H.\nremember (ggcd a b) as g eqn:Hg.\ndestruct g as (g, (aa, bb)).\ndestruct H as (H1, H2); simpl.\ndestruct g.\n-simpl in H1, H2; subst a b; simpl.\n unfold ggcd in Hg; simpl in Hg.\n now injection Hg; intros; subst bb.\n-subst a b.\n specialize (ggcd_gcd (S g * aa) (S g * bb)) as H1.\n rewrite <- Hg in H1.\n rewrite <- H1.\n rewrite Nat.mul_comm, Nat.div_mul; [ easy | ].\n now intros H; simpl in H.\nQed.\n\nTheorem ggcd_swap : ∀ a b g aa bb,\n  ggcd a b = (g, (aa, bb)) → ggcd b a = (g, (bb, aa)).\nProof.\nintros * Hab.\nspecialize (ggcd_fst_snd a b) as H1.\nspecialize (ggcd_snd_snd a b) as H2.\nspecialize (ggcd_fst_snd b a) as H3.\nspecialize (ggcd_snd_snd b a) as H4.\nrewrite Hab in H1; simpl in H1.\nrewrite Hab in H2; simpl in H2.\nrewrite Nat.gcd_comm, <- H2 in H3.\nrewrite Nat.gcd_comm, <- H1 in H4.\nremember (ggcd b a) as g1 eqn:Hg1.\ndestruct g1 as (g1, (aa1, bb1)).\nsimpl in H3, H4; subst aa1 bb1; f_equal.\nspecialize (ggcd_gcd a b) as H3.\nspecialize (ggcd_gcd b a) as H4.\nrewrite Hab in H3; simpl in H3.\nrewrite <- Hg1 in H4; simpl in H4.\nnow rewrite Nat.gcd_comm, <- H3 in H4.\nQed.\n\nTheorem ggcd_succ_l_neq_0 : ∀ a b, fst (snd (ggcd (S a) b)) ≠ 0.\nProof.\nintros.\nrewrite ggcd_fst_snd.\nintros H1.\napply Nat.div_small_iff in H1.\n+apply Nat.nle_gt in H1; apply H1.\n now apply Nat_gcd_le_l.\n+intros H2.\n now apply Nat.gcd_eq_0_l in H2.\nQed.\n\nTheorem ggcd_split : ∀ a b g,\n  g = Nat.gcd a b → ggcd a b = (g, (a / g, b / g)).\nProof.\nintros * Hg.\nremember (ggcd a b) as g1 eqn:Hg1.\ndestruct g1 as (g1, (aa1, bb1)).\nspecialize (ggcd_gcd a b) as H1.\nrewrite <- Hg1, <- Hg in H1; simpl in H1; subst g1.\nspecialize (ggcd_fst_snd a b) as H1.\nrewrite <- Hg1, <- Hg in H1; simpl in H1; subst aa1.\nspecialize (ggcd_snd_snd a b) as H1.\nrewrite <- Hg1, <- Hg in H1; simpl in H1; subst bb1.\neasy.\nQed.\n\nTheorem snd_ggcd_mul_mono_l : ∀ a b c,\n  c ≠ 0\n  → snd (ggcd (c * a) (c * b)) = snd (ggcd a b).\nProof.\nintros * Hc.\nremember (Nat.gcd (c * a) (c * b)) as g eqn:Hg.\nrewrite (ggcd_split _ _ g); [ | easy ].\nrewrite Nat.gcd_mul_mono_l in Hg.\nremember (Nat.gcd a b) as g1 eqn:Hg1.\ndestruct g1.\n-rewrite Nat.mul_0_r in Hg; subst g.\n symmetry in Hg1.\n apply Nat.gcd_eq_0 in Hg1.\n now destruct Hg1; subst a b.\n-subst g.\n rewrite Nat.div_mul_cancel_l; [ | easy | easy ].\n rewrite Nat.div_mul_cancel_l; [ | easy | easy ].\n now rewrite (ggcd_split _ _ (S g1)).\nQed.\n\nTheorem ggcd_mul_mono_l : ∀ a b c,\n  c ≠ 0\n  → ggcd (c * a) (c * b) = (c * Nat.gcd a b, snd (ggcd a b)).\nProof.\nintros * Hc.\nspecialize (snd_ggcd_mul_mono_l a b c Hc) as H.\nremember (ggcd (c * a) (c * b)) as g eqn:Hg.\ndestruct g as (g, (aa, bb)).\nsimpl in H; rewrite H; f_equal.\nspecialize (ggcd_gcd (c * a) (c * b)) as H1.\nrewrite <- Hg in H1; simpl in H1.\nnow rewrite Nat.gcd_mul_mono_l in H1.\nQed.\n\nTheorem ggcd_succ_l : ∀ a b g aa bb,\n  ggcd (S a) b = (g, (aa, bb)) → g ≠ 0 ∧ aa ≠ 0.\nProof.\nintros * Hg.\nerewrite ggcd_split in Hg; [ | easy ].\nremember S as f; simpl.\ninjection Hg; clear Hg; intros; subst g aa bb.\nsubst f.\nsplit.\n-now intros H; apply Nat.gcd_eq_0_l in H.\n-intros H.\n apply Nat.div_small_iff in H.\n +apply Nat.nle_gt in H; apply H.\n  now apply Nat_gcd_le_l.\n +now intros H1; apply Nat.gcd_eq_0_l in H1.\nQed.\n\nTheorem ggcd_succ_r : ∀ a b g aa bb,\n  ggcd a (S b) = (g, (aa, bb)) → g ≠ 0 ∧ bb ≠ 0.\nProof.\nintros * Hg.\nerewrite ggcd_split in Hg; [ | easy ].\nremember S as f; simpl.\ninjection Hg; clear Hg; intros; subst g aa bb.\nsubst f.\nsplit.\n-now intros H; apply Nat.gcd_eq_0_r in H.\n-intros H.\n apply Nat.div_small_iff in H.\n +apply Nat.nle_gt in H; apply H.\n  now apply Nat_gcd_le_r.\n +now intros H1; apply Nat.gcd_eq_0_r in H1.\nQed.\n\nTheorem ggcd_1_l : ∀ n, ggcd 1 n = (1, (1, n)).\nProof.\nintros.\nerewrite ggcd_split; [ | easy ].\nrewrite Nat.gcd_1_l.\nnow do 2 rewrite Nat.div_1_r.\nQed.\n\nTheorem ggcd_1_r : ∀ n, ggcd n 1 = (1, (n, 1)).\nProof.\nintros.\nerewrite ggcd_split; [ | easy ].\nrewrite Nat.gcd_1_r.\nnow do 2 rewrite Nat.div_1_r.\nQed.\n\nTheorem ggcd_diag : ∀ a, a ≠ 0 → ggcd a a = (a, (1, 1)).\nProof.\nintros.\nunfold ggcd.\nrewrite Nat.add_1_r; simpl.\ndestruct a; [ easy | ].\nnow rewrite Nat.compare_refl.\nQed.\n", "meta": {"author": "roglo", "repo": "coq_sensitivity", "sha": "398291aa86a447f0f35b4918043e94d9eb703c12", "save_path": "github-repos/coq/roglo-coq_sensitivity", "path": "github-repos/coq/roglo-coq_sensitivity/coq_sensitivity-398291aa86a447f0f35b4918043e94d9eb703c12/rngl_alg/Nat_ggcd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7131096581453202}}
{"text": "Require Export bbv.BinNotation.\nRequire Import Coq.ZArith.BinInt.\n\nNotation \"'Ob' a\" := (Z.of_N (bin a)) (at level 50).\n\nGoal Ob\"01000001\" = 65%Z.\nProof. reflexivity. Qed.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/bbv/BinNotationZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7130985281220442}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import extra.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection tarjan.\n\nVariable (V : finType) (successors : V -> seq V).\nNotation infty := #|V|.\n\n(**********************************************************)\n(*               Tarjan 72 algorithm,                     *)\n(* rewritten in a functional style by JJ Levy & Ran Chen  *)\n(**********************************************************)\n\nDefinition split_after (T :eqType) (x : T) (s : seq T) :=\n  let i := index x s in (rcons (take i s) x, drop i.+1 s).\n\nFixpoint rank (x : V) stack : nat :=\n  if stack isn't y :: s then infty\n  else if (x == y) && (x \\notin s) then size s else rank x s.\n\nRecord env := Env {blacks : {set V}; stack : seq V; esccs : {set {set V}}}.\nDefinition grays (e : env) := [set x in stack e] :\\: blacks e.\nDefinition whites (e : env) := ~: (grays e :|: blacks e).\n\nDefinition add_stack x e := Env (blacks e) (x :: stack e) (esccs e).\nDefinition add_blacks x e := Env (x |: blacks e) (stack e) (esccs e).\nDefinition add_sccs x e := let (s2, s3) := split_after x (stack e) in\n                            Env (x |: blacks e) s3 ([set y in s2] |: esccs e).\n\nDefinition dfs1 (dfs' : {set V} -> env -> nat * env) (x : V) e :=\n    let m := rank x (x :: stack e) in\n    let: (m1, e1) := dfs' [set y in successors x] (add_stack x e) in\n    if m1 < m then (m1, add_blacks x e1) else (infty, add_sccs x e1).\n\nDefinition dfs' dfs1 dfs' (roots : {set V}) e :=\n  if [pick x in roots] isn't Some x then (infty, e)\n  else let roots' := roots :\\ x in\n       let: (m1, e1) :=\n         if x \\in stack e then (rank x (stack e), e)\n         else if x \\in blacks e then (infty, e)\n         else dfs1 x e in\n       let: (m2, e2) := dfs' roots' e1 in (minn m1 m2, e2).\n\nFixpoint tarjan_rec n : {set V} -> env -> nat * env :=\n  if n is n.+1 then dfs' (dfs1 (tarjan_rec n)) (tarjan_rec n)\n  else fun r e => (infty, e).\n\nLet N := #|V| * #|V|.+1 + #|V|.\nDefinition e0 := (Env set0 [::] set0).\nDefinition tarjan := esccs (tarjan_rec N setT e0).2.\n\n(*****************)\n(* Abbreviations *)\n(*****************)\n\nNotation edge := (grel successors).\nNotation gconnect := (connect edge).\nNotation gsymconnect := (symconnect edge).\nNotation gsccs := (sccs edge).\nNotation gscc_of := (pblock gsccs).\n\n(**************************************************************)\n(* Well formed environements and operations on environements. *)\n(**************************************************************)\n\nInductive wf_env e := WfEnv {\n   wf_stack : [set x in stack e] =\n              grays e :|: (blacks e :\\: cover (esccs e));\n   wf_sccs : cover (esccs e) \\subset blacks e;\n   wf_stack_uniq : uniq (stack e)\n}.\n\nInductive color_spec x e : bool -> bool -> bool -> bool -> bool -> Type :=\n| ColorGray of x \\in grays e : color_spec x e false true false true false\n| ColorSccs of x \\in cover (esccs e) :\n                       color_spec x e true false true false false\n| ColorWhite of x \\in whites e : color_spec x e false false false false true\n| ColorBlackStack of x \\in blacks e & x \\in stack e :\n                        color_spec x e true true false false false.\n\nLemma colorP x e : wf_env e ->\n                   color_spec x e (x \\in blacks e) (x \\in stack e)\n                              (x \\in cover (esccs e))\n                              (x \\in grays e) (x \\in whites e).\nProof.\nmove=> [/setP /(_ x) s_def] /subsetP /(_ x) /implyP.\nmove: s_def; rewrite /grays /whites !inE.\ncase x_black: (_ \\in blacks _) => /=;\ncase x_stack : (_ \\in stack _) => /=;\ncase x_sccs : (_ \\in cover _) => //=; do ?by constructor.\n  by constructor=> //; rewrite /grays !inE x_black.\nby constructor; rewrite /whites !inE x_black x_stack.\nQed.\n\nLemma grays0 : grays e0 = set0.\nProof. by apply/setP=> x; rewrite !inE /=. Qed.\n\nLemma cover0 : cover set0 = set0 :> {set V}.\nProof.\nby apply/setP=> x; rewrite !inE; apply/negP=> /bigcupP[?]; rewrite inE.\nQed.\n\nLemma whites_blacksF x e : x \\in whites e -> x \\in blacks e = false.\nProof. by rewrite !inE; case: (x \\in blacks _). Qed.\n\nLemma whites_stackF x e : x \\in whites e -> x \\in stack e = false.\nProof. by rewrite !inE andbC; case: (x \\in stack _); rewrite //= orNb. Qed.\n\nLemma whites_graysF x e : x \\in whites e -> x \\in grays e = false.\nProof. by rewrite !inE andbC; case: (x \\in stack _); rewrite //= orNb. Qed.\n\nLemma grays_stack x e : x \\in grays e -> x \\in stack e.\nProof. by rewrite !inE andbC; case: (x \\in stack _). Qed.\n\nLemma grays_sccsF x e : wf_env e -> x \\in grays e ->\n   x \\in cover (esccs e) = false.\nProof. by case/colorP. Qed.\n\nLemma sccs_stackF x e : wf_env e ->\n  x \\in cover (esccs e) -> x \\in stack e = false.\nProof. by case/colorP. Qed.\n\nLemma whites_add_stack x e : whites (add_stack x e) = whites e :\\ x.\nProof.\napply/setP=> y; rewrite !inE /=.\nby case: (_ \\in _) (_ \\in _) (_ == _) => [] [] [].\nQed.\n\nLemma grays_add_stack x e : x \\in whites e ->\n  grays (add_stack x e) = x |: grays e.\nProof.\nmove=> x_whites; apply/setP=> y; move: x_whites; rewrite !inE.\nby case: eqP => [->|]; case: (_ \\in _) (_ \\in _)=> [] [].\nQed.\n\nLemma stack_add_stack x e : stack (add_stack x e) = x :: stack e.\nProof. by []. Qed.\n\nLemma add_stack_ewf x e : x \\in whites e -> wf_env e -> wf_env (add_stack x e).\nProof.\nmove=> x_white [s_def sccs_blacks s_uniq]; split => //=;\n  last by rewrite whites_stackF.\napply/setP=> y; rewrite !inE.\nby have [->|] := altP (y =P x); case: colorP=> //=; case: colorP x_white.\nQed.\n\nLemma add_blacks_ewf x e : x \\in grays e -> wf_env e -> wf_env (add_blacks x e).\nProof.\nmove=> x_gray [s_def sccs_blacks s_uniq]; split => //=; last first.\n  by rewrite subsetU // sccs_blacks orbT.\napply/setP=> y; rewrite !inE.\nby have [->|] := altP (y =P x); case: colorP=> //=; case: colorP x_gray.\nQed.\n\nHint Resolve wf_stack_uniq : core.\n\nLemma add_sccs_wf x e :\n  take (index x (stack e)) (stack e) \\subset blacks e ->\n  x \\in grays e -> wf_env e -> wf_env (add_sccs x e).\nProof.\nmove=> /subsetP new_blacks x_gray e_wf.\nhave [s_def /subsetP sccs_blacks s_uniq] := e_wf.\nsplit => //=; last first.\n- by rewrite (subseq_uniq (drop_subseq _ _)).\n- apply/subsetP=> y; rewrite !inE.\n  rewrite /cover bigcup_setU inE big_set1 !inE /= => /orP[|/sccs_blacks->];\n    last by rewrite !orbT.\n  by rewrite mem_rcons !inE; case: eqP => //= _ /new_blacks.\napply/setP=> y; rewrite !inE /cover bigcup_setU inE big_set1 !inE !negb_or.\nhave [->|neq_xy] //= := altP (y =P x); rewrite ?(andbT, andbF).\n  case: path.splitP new_blacks s_uniq => //=; first by rewrite grays_stack.\n  move=> s1 s2 s1x_blacks s_uniq; rewrite grays_sccsF // andbT.\n  by rewrite (uniq_catRL s_uniq) // mem_cat mem_rcons mem_head.\ncase: colorP; rewrite ?(andbT, andbF, orbT, orbF) //=.\n  by move=> y_sccs; apply: contraTF y_sccs => /mem_drop; case: colorP.\nmove=> y_blacks; case: path.splitP s_uniq; first by rewrite grays_stack.\nby move=> s1 s2 s_uniq y_in; apply: uniq_catRL.\nQed.\n\nLemma grays_add_blacks e x : grays (add_blacks x e) = grays e :\\ x.\nProof. by apply/setP=> y; rewrite !inE /= negb_or andbA. Qed.\n\nLemma whites_add_blacks e x : whites (add_blacks x e) = whites e :\\ x.\nProof.\nby apply/setP=> y; rewrite !inE; case: (_ == _) (_ \\in _) (_ \\in _) => [] [].\nQed.\n\nLemma grays_add_sccs e x :\n  let s := take (index x (stack e)) (stack e) in\n  uniq (stack e) -> s \\subset blacks e -> x \\in grays e ->\n  grays (add_sccs x e) = grays e :\\ x.\nProof.\nmove=> /= se_uniq sb x_gray; rewrite /add_sccs /grays /=.\ncase: path.splitP sb se_uniq; first by rewrite grays_stack.\nmove=> s s' sb sxs'_uniq.\napply/setP=> y; rewrite !inE mem_cat mem_rcons in_cons.\nhave [->|] //= := altP eqP; rewrite orbC ![(y \\notin _) && _]andbC.\nhave [|yNs' neq_yx] //= := boolP (y \\in s').\nby have [y_s|] //= := boolP (y \\in s); rewrite (subsetP sb).\nQed.\n\nLemma whites_add_sccs e x :\n  let s := take (index x (stack e)) (stack e) in\n  x \\in grays e -> uniq (stack e) -> s \\subset blacks e ->\n  whites (add_sccs x e) = whites e.\nProof.\nmove=> /= x_gray se_uniq sb; rewrite /whites grays_add_sccs //=.\nby rewrite setUCA setUA setD1K.\nQed.\n\nLemma blacks_add_sccs e x : blacks (add_sccs x e) = x |: blacks e.\nProof. by []. Qed.\n\nLemma sccs_add_sccs e x :\n  let s := take (index x (stack e)) (stack e) in\n  esccs (add_sccs x e) = [set y in rcons s x] |: esccs e.\nProof. by []. Qed.\n\nLemma stack_add_sccs e x :\n  let s := drop (index x (stack e)).+1 (stack e) in\n  stack (add_sccs x e) = s.\nProof. by []. Qed.\n\n(***************)\n(* Rank Theory *)\n(***************)\n\nLemma rankE x stack :\n  rank x stack = if x \\in stack then index x (rev stack) else infty.\nProof.\nelim: stack => [|a s /= ->] //.\nhave [->|neq_xa] /= := altP eqP; rewrite rev_cons -cats1.\n  by rewrite mem_head index_cat mem_rev /= eqxx addn0 size_rev; case: in_mem.\nby rewrite in_cons (negPf neq_xa) /= index_cat /= mem_rev; case: in_mem.\nQed.\n\nLemma rank_cons x y s : rank x (y :: s) =\n  if (x == y) && (x \\notin s) then size s else rank x s.\nProof. by []. Qed.\n\nLemma rank_catl x s s' : x \\in s' -> rank x (s ++ s') = rank x s'.\nProof.\nby move=> x_s; rewrite !rankE rev_cat mem_cat x_s orbT index_cat mem_rev x_s.\nQed.\n\nLemma rank_catr x s s' :\n  x \\in s -> x \\notin s' -> rank x (s ++ s') = size s' + rank x s.\nProof.\nmove=> x_s xNs'; rewrite !rankE rev_cat mem_cat x_s /=.\nby rewrite index_cat mem_rev (negPf xNs') size_rev.\nQed.\n\nLemma rank_small x s : uniq s -> (rank x s < size s) = (x \\in s).\nProof.\nmove=> s_uniq; rewrite rankE; case: (boolP (x \\in s)) => [xNs|_].\n  by rewrite -size_rev index_mem mem_rev.\napply: negbTE; rewrite -ltnNge ltnS cardE uniq_leq_size //.\nby move=> y; rewrite mem_enum.\nQed.\n\nArguments rank : simpl never.\n\nLemma rank_le x (s : seq V) : uniq s -> rank x s <= infty.\nProof.\nmove=> s_uniq; rewrite rankE; case: ifP => // x_s.\nby rewrite (leq_trans (index_size _ _)) ?size_rev -?(card_uniqP _) // max_card.\nQed.\n\nLemma rank_lt x (s : seq V) : uniq s -> (rank x s < infty) = (x \\in s).\nProof.\nrewrite rankE; case: ifPn; rewrite ?ltnn // => x_s s_uniq.\nrewrite (@leq_trans (size (rev s))) ?index_mem ?mem_rev ?size_rev //.\nby rewrite -?(card_uniqP _) // max_card.\nQed.\n\nLemma rank_infty x (s : seq V) : x \\notin s -> rank x s = infty.\nProof. by rewrite rankE => /negPf->. Qed.\n\nLemma rank_mem x s : x \\in s -> rank x s < size s.\nProof. by move=> x_s; rewrite rankE x_s -size_rev index_mem mem_rev. Qed.\n\nLemma rank_le_head s z x : x \\notin s -> z \\in s ->\n  rank z (x :: s) < rank x (x :: s).\nProof.\nby move=> xNs z_s; rewrite !rank_cons z_s andbF eqxx xNs /= rank_mem.\nQed.\n\n(********************)\n(*   Main Proof !   *)\n(********************)\n\nDefinition noblack_to_white e :=\n  forall x, x \\in blacks e -> [disjoint successors x & whites e].\n\nInductive wf_graph e := WfGraph {\n  wf_grays_to_stack : {in grays e & stack e, forall x y,\n         (rank x (stack e) <= rank y (stack e)) -> gconnect x y};\n  wf_stack_to_grays : forall y, y \\in stack e ->\n                      exists x, [/\\ x \\in grays e,\n     (rank x (stack e) <= rank y (stack e)) & gconnect y x]\n  }.\n\nDefinition access_to e (roots : {set V}) :=\n  (forall x, x \\in grays e ->\n   forall y, y \\in roots -> gconnect x y).\n\nDefinition black_gsccs e := [set scc in gsccs | scc \\subset blacks e].\n\nInductive pre_dfs (roots : {set V}) (e : env) := PreDfs {\n  pre_access_to : access_to e roots;\n  pre_wf_env : wf_env e;\n  pre_wf_graph : wf_graph e;\n  wf_noblack_towhite : noblack_to_white e;\n  pre_sccs : esccs e = black_gsccs e;\n}.\n\nLemma add_stack_gwf e w :\n  access_to e [set w] -> wf_env e -> w \\in whites e -> wf_graph e ->\n  wf_graph (add_stack w e).\nProof.\nmove=> grays_to e_wf w_white [gs sg]; split.\n- rewrite grays_add_stack //= => x y; rewrite rank_cons !inE.\n  move=> /orP[/eqP->|/andP[xNb xs]] /orP[/eqP->|/=ys];\n  rewrite ?rank_cons ?eqxx ?(@whites_stackF w) ?xs ?ys ?(andbF, andbT) //=.\n  + by rewrite leqNgt rank_small ?wf_stack_uniq // ys.\n  + by move=> _; rewrite grays_to ?inE //= xNb.\n  + by apply: gs; rewrite ?inE ?xNb.\n- move=> y; rewrite inE => /predU1P [->|].\n    exists w; rewrite ?grays_add_stack ?inE ?eqxx //.\n    by rewrite whites_blacksF ?whites_stackF.\n  move=> y_stack; have /sg [x [x_gray le_xy y_to_x]] := y_stack.\n  exists x; split=> //.\n    by rewrite grays_add_stack // inE x_gray orbT.\n  rewrite stack_add_stack !rank_cons [x == w]negbTE /= 1?[y == w]negbTE //=.\n    by apply: contraTneq y_stack => ->; rewrite whites_stackF.\n  by apply: contraTneq x_gray => ->; rewrite whites_graysF.\nQed.\n\nLemma add_stack_pre e w :\n  access_to e [set w] -> wf_env e -> w \\in whites e -> wf_graph e ->\n  access_to (add_stack w e) [set x in successors w].\nProof.\nmove=> grays_to e_wf w_white e_gwf.\nmove=> x; rewrite grays_add_stack // 2?inE => /predU1P [->|].\n  by move=> y; rewrite inE => y_succ_w; rewrite connect1.\nmove=> /grays_to x_to_y y; rewrite inE => y_succ_w.\nby rewrite (connect_trans _ (connect1 y_succ_w)) // x_to_y ?inE.\nQed.\n\nDefinition xedges (new old : seq V) :=\n  [set y in old | [exists x in new, (x \\notin old) && edge x y]].\n\nDefinition rank_of_reachable m x s :=\n  exists2 y, y \\in gconnect x & m = rank y s.\n\nDefinition post_dfs (roots : {set V}) (e e' : env) (m : nat) :=\n[/\\ [/\\ wf_env e', wf_graph e', noblack_to_white e',\n    grays e' = grays e & esccs e' = black_gsccs e'],\n\n   [/\\\n    exists2 s, stack e' = s ++ stack e & s \\subset (blacks e'),\n    blacks e \\subset blacks e'  & esccs e \\subset esccs e' ]&\n\n   [/\\\n    forall x, x \\in roots -> m <= rank x (stack e'),\n    m = infty \\/ exists2 x, x \\in roots & rank_of_reachable m x (stack e') &\n    forall y, y \\in xedges (stack e') (stack e) -> m <= rank y (stack e')\n   ]\n  ].\n\nDefinition dfs1_correct (dfs1 : V -> env -> nat * env) x e :=\n  (x \\in whites e) -> pre_dfs [set x] e ->\n  let (m, e') := dfs1 x e in\n  (x \\in blacks e') /\\ post_dfs [set x] e e' m.\n\nDefinition dfs'_correct (dfs' : {set V} -> env -> nat * env) roots e :=\n  pre_dfs roots e ->\n  let (m, e') := dfs' roots e in\n  roots \\subset blacks e' :|: grays e' /\\ post_dfs roots e e' m.\n\nLemma pre_dfs_subroots (roots roots' : {set V}) e : roots' \\subset roots ->\n  pre_dfs roots e -> pre_dfs roots' e.\nProof.\nmove=> sub_roots [to_roots e_wf e_gwf black_sccs Nbw]; split=> //.\nby move=> x x_gray y y_roots'; rewrite to_roots //; apply: subsetP y_roots'.\nQed.\n\nLemma dfs'_is_correct dfs1 dfsrec' (roots : {set V}) e :\n  (forall x, x \\in roots -> dfs1_correct dfs1 x e) ->\n  (forall x, x \\in roots -> forall e1, whites e1 \\subset whites e ->\n         dfs'_correct dfsrec' (roots :\\ x) e1) ->\n  dfs'_correct (dfs' dfs1 dfsrec') roots e.\nProof.\nmove=> dfs1_is_correct dfs'_is_correct; rewrite /dfs'_correct /dfs'.\ncase: pickP => [x|no_roots]; last first.\n  move=> [gto_roots e_wf e_gwf black_sccs]; split=> //.\n    by apply/subsetP=> x; rewrite !inE no_roots.\n  split=> //; first by split=> //; first by exists [::] => //; apply/subsetP.\n  split=> //; first by move=> x; rewrite no_roots.\n    by left.\n  by move=> y; rewrite inE => /andP[_ /existsP [x /and3P[->]]].\nmove=> x_root; have := dfs'_is_correct _ x_root; rewrite /dfs'_correct.\ncase: ifPn=> [x_stack|xNstack].\n  move=> /(_ _ (subxx _)); case: (dfsrec' _ _) => [m2 e'].\n  move=> e'_correct [to_roots e_wf e_gwf Nbw black_sccs].\n  have e_uniq := wf_stack_uniq e_wf.\n  case: e'_correct; first exact: (pre_dfs_subroots (subD1set _ _)).\n  move=> change_color [invariants monotony [pc1 pc2 pc3]].\n  split=> //.\n  - rewrite -(setD1K x_root) subUset change_color sub1set !inE.\n    have [//|xNblack /=] := boolP (x \\in blacks _).\n    by have [[s ->]] := monotony; rewrite mem_cat x_stack orbT.\n  split=> //; split=> //.\n  - move=> y y_root; have [->|neq_yx]:= eqVneq y x; last first.\n      by rewrite geq_min pc1 ?orbT // !inE neq_yx.\n    by have [[s -> _ _ _]] := monotony; rewrite rank_catl // geq_min leqnn.\n  - right; case: (leqP (rank x (stack e)) m2) => [rx_small|/ltnW rx_big].\n      exists x => //; exists x; rewrite ?inE ?connect0 //.\n      by have [[s ->]] := monotony; rewrite rank_catl.\n    case: pc2 rx_big=> [->|[y]]; first by rewrite leqNgt rank_lt ?x_stack.\n    rewrite !inE => /andP[neq_yx y_roots [z y_to_z m_def]].\n    by move=> m_small; exists y => //; exists z.\n  - by move=> y y_xedge; rewrite (@leq_trans m2) ?pc3 // geq_min leqnn orbT.\ncase: ifPn=> [x_black|xNblack] //=.\n  move=> /(_ _ (subxx _)); case: (dfsrec' _ _) => [m2 e'].\n  move=> e'_correct [to_roots e_wf e_gwf Nbw black_sccs].\n  case: e'_correct; first exact: (pre_dfs_subroots (subD1set _ _)).\n  move=> change_color [[e'_wf e'_gwf keep_gray Nbw' sccs'_black]\n                       [mon1 mon2 mon3] [pc1 pc2 pc3]].\n  have e'_uniq := wf_stack_uniq e'_wf.\n  split=> //.\n    by rewrite -(setD1K x_root) subUset change_color sub1set !inE (subsetP mon2).\n  have m2_rank: m2 <= infty by case: pc2=> [->|[?? [??->]]]; rewrite ?rank_le.\n  split=> //; split=> //.\n  - move=> y y_root; have [->{y y_root}|neq_yx]:= eqVneq y x; last first.\n      by rewrite geq_min pc1 ?orbT // !inE neq_yx.\n    rewrite rank_infty ?geq_min ?leqnn // sccs_stackF //.\n    by apply: (subsetP (subset_cover mon3)); case: colorP x_black xNstack.\n  - rewrite (minn_idPr _) //; case: pc2 => [->//|]; first by left.\n    by move=> [y]; rewrite !inE => /andP[_ ?]; right; exists y.\n  - by move=> y y_xedge; rewrite (@leq_trans m2) ?pc3 // geq_min leqnn orbT.\nhave := dfs1_is_correct _ x_root; rewrite /dfs1_correct.\ncase: (dfs1 _ _) => [m1 e1] post_dfs1.\nmove=> /(_ e1); case: (dfsrec' _ _) => [m2 e2] post_dfs'.\nmove=> pre {dfs1_is_correct dfs'_is_correct}.\nhave [e_access_to e_wf e_gwf Nbw sccs_black] := pre.\nhave e_uniq := wf_stack_uniq e_wf.\nhave x_white : x \\in whites e by case: colorP xNstack xNblack.\nhave := post_dfs1 x_white (pre_dfs_subroots _ pre).\nrewrite sub1set x_root => /(_ isT) {post_dfs1}.\ncase=> [x_black [[e1_wf e1_gwf Nbw1 keep_gray sccs_e1]\n       [[s1 s1_def s1b] mo_b1 mo_sccs1] [pc1 pc2 pc3]]].\nhave e1_uniq := wf_stack_uniq e1_wf.\ncase: post_dfs'.\n- by rewrite subCset setCK setUSS // keep_gray.\n- split=> // y; rewrite !inE s1_def mem_cat.\n  case: (y \\in s1) (subsetP s1b y) => //= [->//|_ /andP[yNb ys]].\n  move=> z; rewrite inE => /andP[_ z_roots]; rewrite e_access_to //.\n  by rewrite !inE ys andbT; apply: contraNN yNb; apply/subsetP.\nmove=> rootsDx_subset [[e2_wf e2_gwf Nbw2 keep_gray2 sccs_e2]\n  [[s2 s2_def s2b] mo_b2 mo_sccs2] [pc21 pc22 pc23]].\nhave e2_uniq := wf_stack_uniq e2_wf.\nsplit.\n  rewrite -(setD1K x_root) subUset rootsDx_subset andbT sub1set.\n  by rewrite inE (subsetP mo_b2).\nsplit; first by rewrite keep_gray2 keep_gray.\n  split.\n  + exists (s2 ++ s1); first by rewrite s2_def s1_def catA.\n    apply/subsetP=> y; rewrite mem_cat => /orP [/(subsetP s2b) //|].\n    by apply/subsetP/(subset_trans s1b).\n  + exact/(subset_trans mo_b1).\n  + exact/(subset_trans mo_sccs1).\nhave m1_rank: m1 <= infty by case: pc2=> [->|[?? [??->]]]; rewrite ?rank_le.\nhave m2_rank: m2 <= infty by case: pc22=> [->|[?? [??->]]]; rewrite ?rank_le.\nsplit.\n- move=> y y_roots; have [->|neq_yx] := eqVneq y x; last first.\n    by rewrite (@leq_trans m2) ?geq_minr // pc21 // !inE neq_yx.\n  have [xs|xNs] := boolP (x \\in stack e1).\n    by rewrite s2_def rank_catl // (@leq_trans m1) ?geq_minl // pc1 ?inE.\n  have x_sccs2 : x \\in cover (esccs e2).\n    apply: (subsetP (subset_cover mo_sccs2)).\n    by case: colorP xNs x_black.\n  by rewrite rank_infty ?geq_min ?m1_rank //; case: colorP x_sccs2.\n- case: pc22 => [->|m2_reachable].\n  + rewrite (minn_idPl _) //; case: pc2=> [->|pc2]; [by left|].\n    case: ltngtP m1_rank => // [m1_lt _|]; last by left.\n    right; exists x => //.\n    case: pc2=> z; rewrite inE => /eqP -> [t x_to_t m1_def].\n    by exists t => //; rewrite s2_def rank_catl // -rank_lt -?m1_def.\n  + case: (leqP m1 m2) => [m12|/ltnW m21]; last first.\n      case: m2_reachable => y; rewrite !inE => /andP[_ y_root] [z y_to_z m2_def].\n      by right; exists y => //; exists z => //.\n    case: ltngtP m1_rank => // [m1_lt _|]; last by left.\n    right; exists x => //; case: pc2=> [m1_infty|[z]].\n      by rewrite m1_infty ltnn in m1_lt.\n    rewrite inE => /eqP -> [t x_to_t m1_def].\n    by exists t => //; rewrite s2_def rank_catl // -rank_lt -?m1_def.\n- move=> y.\n  rewrite !inE => /andP [y_s0 /existsP[z /and3P [z_s2 zNs0 z_to_y]]].\n  move: z_s2; rewrite s2_def mem_cat orbC.\n  have [z_s1 _|/= zNs1 z_s2] := boolP (z \\in stack e1).\n    rewrite rank_catl; last by rewrite s1_def mem_cat y_s0 orbT.\n    rewrite (@leq_trans m1) ?geq_minl // pc3 // inE y_s0.\n    by apply/existsP; exists z; rewrite z_s1 zNs0.\n  rewrite -s2_def (@leq_trans m2) ?geq_minr // pc23 // inE.\n  rewrite s1_def mem_cat y_s0 orbT /=.\n  apply/existsP; exists z; rewrite s2_def mem_cat z_s2 /= [X in _ && X]z_to_y.\n  by rewrite -s1_def zNs1.\nQed.\n\nLemma path_xset_xedge x y (s : pred V) :\n  gconnect x y -> x \\in s -> y \\notin s ->\n  exists x' y', [/\\ x' \\in s, y' \\notin s,\n                    gconnect x x', edge x' y' & gconnect y' y].\nProof.\nmove=> /connectP [p path_xp ->] xs yNs.\npose n := find (predC s) p.\nhave hasNs_p : has (predC s) p.\n  apply/hasP; exists (last x p) => //=.\n  have := mem_last x p; rewrite in_cons => /predU1P [eq_x|//].\n  by rewrite eq_x xs in yNs.\nhave n_small : n < size p by rewrite -has_find.\nexists (nth x (x :: p) n), (nth x p n).\nrewrite [_ \\notin s](@nth_find _ _ (predC s)) ?(pathP _ _) //.\nhave [->|n_gt0] := posnP n.\n  rewrite ?nth0 /= xs connect0; split=> //.\n    by case: (p) yNs path_xp => [|? ? _ /andP[]]; rewrite //= xs.\n  case: p {yNs n hasNs_p n_small} path_xp => //= z p.\n  by move=> /andP [xz zp]; rewrite (appP connectP idP) //; exists p.\nrewrite -{1 2}[n]prednK //= -[_ \\in s]negbK.\nrewrite [_ \\notin s](@before_find _ _ (predC s)) ?prednK //=.\nsplit=> //.\n  - apply/connectP; exists (take n p).\n      by move: path_xp; rewrite -{1}[p](@cat_take_drop n) cat_path=> /andP[].\n    rewrite (last_nth x) size_take n_small.\n    by case: (n) n_gt0 => //= k _; rewrite nth_take.\n  - by have /pathP/(_ _ n_small) :=  path_xp => /(_ x).\napply/connectP; exists (drop n.+1 p).\n  move: path_xp; rewrite -{1}[p](@cat_take_drop n.+1) cat_path=> /andP[_].\n  rewrite (last_nth x) /= size_take ltn_neqAle n_small andbT.\n   by have [->|] := altP eqP; rewrite /= ?drop_size ?nth_take.\nrewrite !(last_nth x) size_drop.\nmove: n_small; rewrite leq_eqVlt => /predU1P[<-|]; rewrite ?subnn //.\ncase: (size p) => //= - [|k] //; rewrite !ltnS => n_small.\nby rewrite subSS subSn // [RHS]/= nth_drop addSn subnKC.\nQed.\n\nLemma dfs1_is_correct dfs' (x : V) e :\n  (dfs'_correct dfs' [set y in successors x] (add_stack x e)) ->\n  dfs1_correct (dfs1 dfs') x e.\nProof.\nrewrite /dfs1 /dfs1_correct /dfs'_correct; case: (dfs' _ _) => m1 e1.\nmove=> post_dfs'; set m := rank x _.\nmove=> x_white [access_to_x e_wf e_gwf Nbw black_sccs].\nhave e_uniq := wf_stack_uniq e_wf.\ncase: post_dfs' => //=.\n  split => //; do?[exact: add_stack_ewf|exact: add_stack_gwf]; last first.\n     move=> y /Nbw; rewrite whites_add_stack.\n     rewrite ![[disjoint successors _ & _]]disjoint_sym.\n     by apply/disjointWl/subsetDl.\n  move=> y; rewrite grays_add_stack // => /setU1P [->|]; last first.\n    move=> y_gray z; rewrite inE => /(@connect1 _ edge).\n    by apply/connect_trans/access_to_x; rewrite ?set11.\n  by move=> z; rewrite inE => /(@connect1 _ edge).\nmove=> succ_bVg [[e1_wf e1_gwf Nbw1 keep_gray black_sccs1]\n                   [[s/= s_def sb] mo_b mo_sccs] [pc1 pc2 pc3]].\nset s2 := rcons s x.\nhave e1_uniq := wf_stack_uniq e1_wf.\nhave xe_uniq : uniq (x :: stack e).\n  by have := e1_uniq; rewrite s_def cat_uniq => /and3P [].\nhave x_stack : x \\in stack e1 by rewrite s_def mem_cat mem_head orbT.\nhave x_grays : x \\in grays e1 by rewrite keep_gray grays_add_stack ?setU11.\nhave sx_subscc : is_subscc edge [set y in rcons s x].\n  apply: (@is_subscc1 _ _ x); first by rewrite inE mem_rcons mem_head.\n  move=> y; rewrite !inE mem_rcons in_cons => /predU1P [->//|y_s]; split.\n    apply: (@wf_grays_to_stack e1) => //; first by rewrite s_def mem_cat y_s.\n    rewrite s_def rank_catl ?mem_head // rank_catr //=; last first.\n       by rewrite -(@uniq_catLR _ _ s) ?mem_cat ?y_s // -?s_def //.\n    rewrite rankE mem_head (leq_trans (index_size _ _)) //.\n    by rewrite size_rev leq_addr.\n  have [] := @wf_stack_to_grays _ e1_gwf y; first by rewrite s_def mem_cat y_s.\n  move=> z [z_gray rank_z] /connect_trans; apply.\n  rewrite (@wf_grays_to_stack e1) // s_def.\n  have := z_gray; rewrite !(inE, s_def) mem_cat.\n  case: (boolP (z \\in s)) => [/(subsetP sb)->//|_ /= /andP [_ z_xe]].\n  rewrite !rank_catl ?mem_head //.\n  move: z_xe; rewrite in_cons.\n  have [->//|neq_zx /= z_s] := altP eqP.\n  rewrite ltnW // rank_le_head //.\n  rewrite -(@uniq_catLR _ _ (rcons s x)) ?mem_rcons ?mem_head //.\n    by rewrite cat_rcons -s_def wf_stack_uniq.\n  by rewrite mem_cat mem_rcons mem_head.\ncase: ltnP => [m1_small|m1_big] //=; rewrite !inE eqxx /=; split=> //.\n  have [x1 rank_x1 x_to_x1] : exists2 x1,\n    rank x1 (stack e1) = m1 & gconnect x x1.\n    case: pc2 m1_small => [->|]; first by rewrite /m ltnNge ?rank_le.\n    move=> [y]; rewrite inE => /(@connect1 _ edge) x_to_y.\n    move=> [x1 y_to_x1 rank_x1 _]; exists x1 => //.\n    by rewrite (connect_trans x_to_y).\n  have [x' [rank_x' x'_gray x_to_x' ]] : exists x',\n    [/\\ rank x' (stack e1) < rank x (stack e1), x' \\in grays e1 & gconnect x x'].\n    move: m1_small; rewrite -{}rank_x1 => rank_x1.\n    have x1_stack : x1 \\in stack e1.\n      by rewrite -rank_lt ?(leq_trans rank_x1) // rank_le.\n    have [z [z_gray rank_z y_to_z]] := wf_stack_to_grays e1_gwf x1_stack.\n    exists z; split=> //; rewrite 2?inE ?z_gray ?andbT.\n    - rewrite (leq_ltn_trans rank_z) // (leq_trans rank_x1) // /m.\n      by rewrite s_def rank_catl ?mem_head.\n    - by rewrite (connect_trans x_to_x1).\n  have neq_x'x : x' != x by apply: contraTneq rank_x' => ->; rewrite -ltnNge.\n  split=> //.\n  - split=> //; first exact: add_blacks_ewf.\n    + split => //.\n        move=> y z /=; rewrite grays_add_blacks => y_gray z_stack.\n        apply: wf_grays_to_stack => //; apply: subsetP y_gray.\n        by rewrite subD1set.\n      move=> y /= y_stack; rewrite grays_add_blacks.\n      have [z] // := wf_stack_to_grays e1_gwf y_stack.\n      have [->{z} [_ rank_x y_to_x]|] := eqVneq z x; last first.\n        move=> neq_zx [z_gray rank_z y_to_z].\n        by exists z; split=> //; rewrite 2!inE neq_zx.\n      exists x'; split; rewrite 2?inE ?x'_gray ?andbT //.\n      - by rewrite (leq_trans _ rank_x) 1?ltnW // {2}s_def rank_catl ?mem_head.\n      - by rewrite (connect_trans y_to_x).\n    + move=> y; rewrite !inE whites_add_blacks.\n      move=> /predU1P [->{y}|y_black]; last first.\n        apply/pred0P=> z /=; rewrite 2!inE.\n        have /pred0P /(_ z) /= := Nbw1 _ y_black.\n        by apply: contraFF=> /and3P[->_->].\n      apply/pred0P=> z /=; rewrite 2!inE.\n      have /subsetP /(_ z) := succ_bVg.\n      rewrite 2!inE => /implyP.\n      by case: (_ \\in successors _) (_ == _) colorP => [] [] [].\n    + rewrite grays_add_blacks keep_gray grays_add_stack //.\n      by rewrite setU1K // whites_graysF.\n    + rewrite /= black_sccs1; apply/setP=> scc; rewrite !inE /=.\n      have [scc_gsccs|] //= := boolP (scc \\in gsccs).\n      apply/idP/idP; first by move=> /subset_trans; apply; rewrite subsetU1.\n      move=> /subsetP scc_sub; apply/subsetP => y y_scc.\n      have /setU1P [eq_yx|//] := scc_sub y y_scc.\n      rewrite eq_yx in y_scc.\n      have x'_scc : (x' \\in scc).\n        rewrite -(def_scc scc_gsccs y_scc) // mem_scc /symconnect /= x_to_x' /=.\n        by rewrite (wf_grays_to_stack e1_gwf) // ltnW.\n      have /scc_sub := x'_scc.\n      rewrite !inE (negPf neq_x'x) /=.\n      by case: colorP x'_gray.\n  - split=> //=.\n    + exists (rcons s x); first by rewrite cat_rcons.\n      apply/subsetP=> y; rewrite !inE mem_rcons in_cons=> /predU1P [->|].\n        by rewrite eqxx.\n      by move=> y_s; rewrite (subsetP sb) ?orbT.\n    + by rewrite subsetU // mo_b orbT.\n  - split=> //=.\n    + move=> y; rewrite inE => /eqP->.\n      by rewrite s_def rank_catl ?mem_head // ltnW.\n    + by right; exists x; rewrite ?set11 //; exists x1.\n    + move=> y; rewrite inE => /andP [y_stack /existsP].\n      move=> [z /and3P[z_stack1 zNstack zy]].\n      have [eq_zx|neq_zx] := eqVneq z x.\n        by rewrite pc1 // -eq_zx inE.\n      apply: pc3; rewrite inE in_cons y_stack orbT /=.\n      apply/existsP; exists z.\n      by rewrite z_stack1 in_cons negb_or neq_zx zNstack.\nhave scc_max : gscc_of x \\subset [set y in s2].\n  apply/subsetP=> y; rewrite inE=> y_sccx; apply: contraTT isT => yNs2.\n  have xy : gconnect x y.\n    by have := y_sccx; rewrite mem_scc /= => /andP[].\n  have x_s2 : x \\in s2 by rewrite mem_rcons mem_head.\n  have [x' [y' [x'_s2 y'Ns xx' x'y' y'y]]] := path_xset_xedge xy x_s2 yNs2.\n  apply: contraNN y'Ns => _.\n  have: y' \\in ([set y in stack e1] :|:\n               (\\bigcup_(scc in esccs e1) scc :|: whites e1)).\n    by rewrite !inE; case: colorP.\n  rewrite 3!inE => /or3P[].\n  - rewrite s_def -cat_rcons mem_cat => /orP[//|y'_stack].\n    have xNstack: x \\notin stack e.\n      rewrite -(@uniq_catLR _ x s2) ?mem_cat ?x_s2 //.\n      by rewrite cat_rcons -s_def wf_stack_uniq.\n    have x'Nstack: x' \\notin stack e.\n      rewrite -(@uniq_catLR _ x' s2) ?mem_cat ?x'_s2 //.\n      by rewrite cat_rcons -s_def wf_stack_uniq.\n    have rank_y': rank y' (x :: stack e) < rank x (x :: stack e).\n      by rewrite rank_le_head //.\n    have neq_y'x : y' != x by apply: contraTneq rank_y' => ->; rewrite ltnn.\n    have [eq_x'x|neq_x'x] := eqVneq x' x.\n      have := pc1 y'; rewrite inE -eq_x'x => /(_ x'y').\n      rewrite leqNgt (leq_trans _ m1_big) // /m.\n      by rewrite s_def rank_catl ?in_cons ?y'_stack ?orbT.\n    apply: contraTT rank_y' => y'Ns2; rewrite -leqNgt.\n    rewrite [rank y' _]rank_cons (negPf neq_y'x) /=.\n    have := pc3 y'; rewrite inE in_cons y'_stack orbT /=.\n    rewrite {2}s_def -cat_rcons rank_catl // => /(_ _) /(leq_trans _) -> //.\n    apply/existsP; exists x'; rewrite s_def -cat_rcons mem_cat x'_s2 /=.\n    by rewrite in_cons (negPf neq_x'x) /= x'Nstack.\n  - move=> /bigcupP [scc'].\n    rewrite black_sccs1 inE => /andP[scc'_gsccs scc'_black].\n    move=> /def_scc - /(_ _ scc'_gsccs) eq_scc'; rewrite -eq_scc' in scc'_black.\n    have : x \\in gscc_of y'.\n      have:= y_sccx; rewrite /= !mem_scc /symconnect /= andbC => /andP[yx _].\n      by rewrite (connect_trans y'y) //= (connect_trans xx') //= connect1.\n    by move=> /(subsetP scc'_black); case: colorP x_grays.\n  - move: x'_s2; rewrite mem_rcons in_cons => /predU1P [eq_x'x|x_s].\n      have /subsetP /(_ y') := succ_bVg.\n      by rewrite 2!inE -eq_x'x => /(_ x'y'); case: colorP.\n    have /(_ x') := Nbw1; rewrite (subsetP sb) => // /(_ isT).\n    by move=> /pred0P /(_ y') /=; rewrite [_ \\in _]x'y' /= => ->.\nhave take_s : take (index x (stack e1)) (stack e1) = s.\n  rewrite s_def index_cat /= eqxx addn0.\n  rewrite (@uniq_catLR _ _ _ (x :: stack e)) -?s_def ?wf_stack_uniq //.\n  by rewrite mem_head /= ?s_def take_cat ltnn subnn take0 cats0.\nhave drop_s : drop (index x (stack e1)).+1 (stack e1) = stack e.\n  rewrite s_def index_cat /= eqxx addn0.\n  rewrite (@uniq_catLR _ _ _ (x :: stack e)) -?s_def ?wf_stack_uniq //.\n  rewrite mem_head /= ?s_def drop_cat ltnNge leqW //.\n  by rewrite subSn // subnn //= drop0.\nhave g1Nx : grays e1 :\\ x = grays e.\n  by rewrite keep_gray grays_add_stack // setU1K // whites_graysF.\nsplit=> //.\n- split=> //.\n  + by apply: add_sccs_wf=> //; rewrite take_s //.\n  + split=> //; rewrite ?grays_add_sccs ?stack_add_sccs ?take_s ?drop_s// ?g1Nx.\n      exact: wf_grays_to_stack.\n      exact: wf_stack_to_grays.\n  + move=> y; rewrite !inE whites_add_sccs ?take_s //.\n    move=> /predU1P [->|/Nbw1//]; apply/pred0P=> z //=.\n    rewrite 2!inE; have /subsetP /(_ z) := succ_bVg.\n    by rewrite 2!inE => /implyP; rewrite -negb_imply orbC => ->.\n  + by rewrite grays_add_sccs ?take_s ?g1Nx.\n  + rewrite sccs_add_sccs take_s //=; apply/setP=> scc.\n    rewrite !inE blacks_add_sccs ?take_s//= black_sccs1 !inE.\n    have x_s2 : x \\in [set y in s2] by rewrite inE mem_rcons mem_head.\n    have s2_gsccs : [set y in rcons s x] \\in gsccs.\n       apply/imsetP => /=; exists x => //.\n      rewrite -[RHS](@def_scc _ edge _ x); last 2 first.\n      * by apply/imsetP; exists x.\n      * by rewrite !inE /symconnect ?connect0.\n      apply/eqP; rewrite eqEsubset scc_max.\n      have [scc' scc'_gsccs sub'] := is_subscc_in_scc sx_subscc.\n      by rewrite (@def_scc _ edge scc') ?sub' //; apply: (subsetP sub').\n    have [scc_gsccs|] //= := boolP (scc \\in gsccs); last first.\n      by apply: contraNF; rewrite orbF => /eqP->.\n    apply/idP/idP.\n      move=> /predU1P [->|].\n        apply/subsetP => y; rewrite !inE mem_rcons in_cons.\n        by case: eqP=> [->|] //= _ => /(subsetP sb).\n      by move=> /subset_trans; apply; rewrite subsetU1.\n    have [x_scc|xNscc] := boolP (x \\in scc).\n      by move=> _; rewrite -(def_scc scc_gsccs x_scc) // (def_scc s2_gsccs) ?eqxx.\n    rewrite -subDset (setDidPl _); first by move->; rewrite orbT.\n    by rewrite disjoint_sym (@eq_disjoint1 _ x) // => y; rewrite !inE.\n- split=> //.\n  + rewrite stack_add_sccs drop_s; exists [::] => //.\n    by apply/subsetP=> y; rewrite inE.\n  + by rewrite blacks_add_sccs ?take_s// (subset_trans mo_b) ?subsetU1.\n  + by rewrite sccs_add_sccs take_s (subset_trans mo_sccs) ?subsetU1.\n- split=> //; do ?by [left].\n  + move=> y; rewrite inE => /eqP->.\n    by rewrite stack_add_sccs drop_s leqNgt rank_lt ?whites_stackF.\n  + move=> y; rewrite inE stack_add_sccs drop_s => /andP[_ /existsP].\n    by move=> [z /and3P[->]].\nQed.\n\nTheorem tarjan_rec_terminates n (roots : {set V}) e :\n  n >= #|whites e| * #|V|.+1 + #|roots| ->\n  dfs'_correct (tarjan_rec n) roots e.\nProof.\nmove=> n_ge; wlog ->: e n roots {n_ge} / roots = set0 => [noroot|]; last first.\n  have := @dfs'_is_correct (dfs1 (tarjan_rec 0)) (tarjan_rec 0) set0 e.\n  rewrite /tarjan_rec /dfs'_correct /dfs' /=.\n  case: n=> [|n /=]; case: pickP => [x|_/=]; rewrite ?inE //;\n  by apply => ?; rewrite inE.\nhave [V0|VN0] := posnP #|V|.\n  have := max_card (mem roots).\n  by rewrite V0 leqn0 cards_eq0 => /eqP /noroot; apply.\nelim: n => [|n IHn] in roots e n_ge *.\n  move: n_ge; rewrite leqn0 addn_eq0 cards_eq0.\n  by move=> /andP [_ /eqP/noroot]; apply.\nmove=> pre; rewrite /dfs'_correct /=.\napply: dfs'_is_correct => //= x x_root.\n  move=> x_white; apply: dfs1_is_correct => //; apply: IHn.\n  rewrite whites_add_stack cardsDS ?sub1set // cards1 subn1.\n  rewrite -ltnS (leq_trans _ n_ge) //.\n  rewrite (@ltn_div2r #|V|.+1) ?divnMDl ?divn_small ?addn0 ?ltnS ?max_card //=.\n  by rewrite prednK //; apply/card_gt0P; exists x.\nmove=> e1 whites_e1; apply: IHn; rewrite -ltnS (leq_trans _ n_ge) //.\nhave /subset_leq_card := whites_e1.\nrewrite leq_eqVlt => /predU1P [->|lt_wh]; last first.\n  by rewrite (@ltn_div2r #|V|.+1) ?divnMDl ?divn_small ?addn0 ?ltnS ?max_card.\nby rewrite ltn_add2l [X in _ < X](cardsD1 x) x_root.\nQed.\n\nLemma tarjan_rec_is_correct :\n  tarjan_rec N setT e0 = (infty, Env setT [::] gsccs).\nProof.\nhave := @tarjan_rec_terminates N setT e0; rewrite /dfs'_correct.\ncase: tarjan_rec => [m e] [].\n- by rewrite ?leq_add ?leq_mul ?max_card.\n- split=> //.\n  + by move=> x; rewrite grays0 inE.\n  + by split=> //; rewrite /= ?cover0 ?grays0 ?set0D ?setU0.\n  + by move=> x; rewrite inE.\n  + apply/setP=> y; rewrite !inE /= subset0 andbC; case: eqP => //= ->.\n    by have /and3P [_ _ /negPf->] := sccs_partition edge.\nrewrite subTset => /eqP blackse [[[stack_wf _ _] _ _]].\nrewrite grays0 => grayse; rewrite grayse setU0 in blackse.\nrewrite /black_gsccs /= blackse => sccse _ [_ minfty _].\nhave {}sccse: esccs e = gsccs.\n  by apply/setP=> scc; rewrite sccse inE subsetT andbT.\nhave stacke : stack e = [::].\n  have := stack_wf; rewrite grayse blackse sccse cover_sccs set0U setDv.\n  by case: stack => // x s /setP /(_ x); rewrite !inE eqxx.\ncongr (_, _); first by case: minfty => // [[x _ [y xy]]]; rewrite stacke.\nby case: e blackse sccse stacke {stack_wf grayse minfty} => //= *; congr Env.\nQed.\n\nTheorem tarjan_correct : tarjan = gsccs.\nProof. by rewrite /tarjan tarjan_rec_is_correct. Qed.\n\nEnd tarjan.\n", "meta": {"author": "coq-community", "repo": "tarjan", "sha": "afc3e6f51db80bc6171ff882caec5433b6290b50", "save_path": "github-repos/coq/coq-community-tarjan", "path": "github-repos/coq/coq-community-tarjan/tarjan-afc3e6f51db80bc6171ff882caec5433b6290b50/theories/tarjan_rank.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7130985237251335}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) : natural := mult lf1 y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj84_coqofml_6b4p5X.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7130985194373904}}
{"text": "Require Import Logic_and_Set_Theory.\nRequire Import EoM_Zorns_Lemma.\nRequire Import L_1_4_10_EoM_Intro.\nFrom Coq Require Import Powerset_facts.\nFrom Coq Require Import Finite_sets.\nFrom Coq Require Import Powerset_Classical_facts.\nFrom Coq Require Import Finite_sets_facts.\nFrom Coq Require Import Constructive_sets.\n\n\n\nLemma Strong_Weakening: forall (Pi : Ensemble Formula) (f : Formula), ND Pi f -> forall (Gamma : Ensemble Formula), Inc Pi Gamma -> ND Gamma f.\nProof.\n    intros Pi f H. induction H; intros.\n    -apply ax. apply H0. apply H.\n    -apply conjE1 with (f2:=f2). apply IHND. apply H0.\n    -apply conjE2 with (f1:=f1). apply IHND. apply H0.\n    -apply conjI.\n        +apply IHND1. apply H1.\n        +apply IHND2. apply H1. \n    -apply disjE with (f1:=f1) (f2:=f2).\n        +apply IHND1. apply incl_add. apply H2.\n        +apply IHND2. apply incl_add. apply H2.\n        +apply IHND3. apply H2.\n    -apply disjI1. apply IHND. apply H0.\n    -apply disjI2. apply IHND. apply H0.\n    -apply impE with (f1:=f1).\n        +apply IHND1. apply H1.\n        +apply IHND2. apply H1.\n    -apply impI. apply IHND. apply incl_add. apply H0.\n    -apply negE with (f:=f). \n        +apply IHND1. apply H1.\n        +apply IHND2. apply H1.\n    -apply negI. apply IHND. apply incl_add. apply H0.\n    -apply botE. apply IHND. apply H0.\n    -apply RAA. apply IHND. apply incl_add. apply H0.\n    Qed.\n\n", "meta": {"author": "TypicalMath", "repo": "cpc", "sha": "a2041b156d0ab954f57f76fda7cd4e27d2f8881c", "save_path": "github-repos/coq/TypicalMath-cpc", "path": "github-repos/coq/TypicalMath-cpc/cpc-a2041b156d0ab954f57f76fda7cd4e27d2f8881c/L_1_4_10_EoM_Strong_Weakening.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121366457407, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7130985153679813}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus y (plus x Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj2910_coqofml_tca20B.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7130985150950635}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice.\nFrom mathcomp Require Import fintype bigop ssralg poly.\n\n(******************************************************************************)\n(* This file provides a library for the basic theory of Euclidean and pseudo- *)\n(* Euclidean division for polynomials over ring structures.                   *)\n(* The library defines two versions of the pseudo-euclidean division: one for *)\n(* coefficients in a (not necessarily commutative) ring structure and one for *)\n(* coefficients equipped with a structure of integral domain. From the latter *)\n(* we derive the definition of the usual Euclidean division for coefficients  *)\n(* in a field. Only the definition of the pseudo-division for coefficients in *)\n(* an integral domain is exported by default and benefits from notations.     *)\n(* Also, the only theory exported by default is the one of division for       *)\n(* polynomials with coefficients in a field.                                  *)\n(* Other definitions and facts are qualified using name spaces indicating the *)\n(* hypotheses made on the structure of coefficients and the properties of the *)\n(* polynomial one divides with.                                               *)\n(*                                                                            *)\n(* Pdiv.Field (exported by the present library):                              *)\n(*          edivp p q == pseudo-division of p by q with p q : {poly R} where  *)\n(*                       R is an idomainType.                                 *)\n(*                       Computes (k, quo, rem) : nat * {poly r} * {poly R},  *)\n(*                       such that size rem < size q and:                     *)\n(*                       + if lead_coef q is not a unit, then:                *)\n(*                         (lead_coef q ^+ k) *: p = q * quo + rem            *)\n(*                       + else if lead_coef q is a unit, then:               *)\n(*                         p = q * quo + rem and k = 0                        *)\n(*             p %/ q == quotient (second component) computed by (edivp p q). *)\n(*             p %% q == remainder (third component) computed by (edivp p q). *)\n(*          scalp p q == exponent (first component) computed by (edivp p q).  *)\n(*             p %| q == tests the nullity of the remainder of the            *)\n(*                       pseudo-division of p by q.                           *)\n(*         rgcdp p q  == Pseudo-greater common divisor obtained by performing *)\n(*                       the Euclidean algorithm on p and q using redivp as   *)\n(*                       Euclidean division.                                  *)\n(*             p %= q == p and q are associate polynomials, i.e., p %| q and  *)\n(*                       q %| p, or equivalently, p = c *: q for some nonzero *)\n(*                       constant c.                                          *)\n(*           gcdp p q == Pseudo-greater common divisor obtained by performing *)\n(*                       the Euclidean algorithm on p and q using  edivp as   *)\n(*                       Euclidean division.                                  *)\n(*          egcdp p q == The pair of Bezout coefficients: if e := egcdp p q,  *)\n(*                       then size e.1 <= size q, size e.2 <= size p, and     *)\n(*                       gcdp p q %= e.1 * p + e.2 * q                        *)\n(*       coprimep p q == p and q are coprime, i.e., (gcdp p q) is a nonzero   *)\n(*                       constant.                                            *)\n(*          gdcop q p == greatest divisor of p which is coprime to q.         *)\n(* irreducible_poly p <-> p has only trivial (constant) divisors.             *)\n(*                                                                            *)\n(* Pdiv.Idomain: theory available for edivp and the related operation under   *)\n(*    the sole assumption that the ring of coefficients is canonically an     *)\n(*    integral domain (R : idomainType).                                      *)\n(*                                                                            *)\n(* Pdiv.IdomainMonic:  theory available for edivp and the related operations  *)\n(*    under the assumption that the ring of coefficients is canonically       *)\n(*    and integral domain (R : idomainType) an the divisor is monic.          *)\n(*                                                                            *)\n(* Pdiv.IdomainUnit: theory available for edivp and the related operations    *)\n(*    under the assumption that the ring of coefficients is canonically an    *)\n(*    integral domain (R : idomainType) and the leading coefficient of the    *)\n(*    divisor is a unit.                                                      *)\n(*                                                                            *)\n(* Pdiv.ClosedField: theory available for edivp and the related operation     *)\n(*    under the sole assumption that the ring of coefficients is canonically  *)\n(*    an algebraically closed field (R : closedField).                        *)\n(*                                                                            *)\n(*  Pdiv.Ring :                                                               *)\n(*   redivp p q == pseudo-division of p by q with p q : {poly R} where R is   *)\n(*                 a ringType.                                                *)\n(*                 Computes (k, quo, rem) : nat * {poly r} * {poly R},        *)\n(*                 such that if rem = 0 then quo * q = p * (lead_coef q ^+ k) *)\n(*                                                                            *)\n(*   rdivp p q  == quotient (second component) computed by (redivp p q).      *)\n(*   rmodp p q  == remainder (third component) computed by (redivp p q).      *)\n(*   rscalp p q == exponent (first component) computed by (redivp p q).       *)\n(*   rdvdp p q  == tests the nullity of the remainder of the pseudo-division  *)\n(*                 of p by q.                                                 *)\n(*   rgcdp p q  == analogue of gcdp for coefficients in a ringType.           *)\n(*   rgdcop p q == analogue of gdcop for coefficients in a ringType.          *)\n(*rcoprimep p q == analogue of coprimep p q for coefficients in a ringType.   *)\n(*                                                                            *)\n(* Pdiv.RingComRreg : theory of the operations defined in Pdiv.Ring, when the *)\n(*   ring of coefficients is canonically commutative (R : comRingType) and    *)\n(*   the leading coefficient of the divisor is both right regular and         *)\n(*   commutes as a constant polynomial with the divisor itself                *)\n(*                                                                            *)\n(* Pdiv.RingMonic : theory of the operations defined in Pdiv.Ring, under the  *)\n(*   assumption that the divisor is monic.                                    *)\n(*                                                                            *)\n(* Pdiv.UnitRing: theory of the operations defined in Pdiv.Ring, when the     *)\n(*   ring R of coefficients is canonically with units (R : unitRingType).     *)\n(*                                                                            *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nLocal Open Scope ring_scope.\n\nReserved Notation \"p %= q\" (at level 70, no associativity).\n\nLocal Notation simp := Monoid.simpm.\n\nModule Pdiv.\n\nModule CommonRing.\n\nSection RingPseudoDivision.\n\nVariable R : ringType.\nImplicit Types d p q r : {poly R}.\n\n(* Pseudo division, defined on an arbitrary ring *)\nDefinition redivp_rec (q : {poly R}) :=\n  let sq := size q in\n  let cq := lead_coef q in\n   fix loop (k : nat) (qq r : {poly R})(n : nat) {struct n} :=\n    if size r < sq then (k, qq, r) else\n    let m := (lead_coef r) *: 'X^(size r - sq) in\n    let qq1 := qq * cq%:P + m in\n    let r1 := r * cq%:P - m * q in\n       if n is n1.+1 then loop k.+1 qq1 r1 n1 else (k.+1, qq1, r1).\n\nDefinition redivp_expanded_def p q :=\n   if q == 0 then (0%N, 0, p) else redivp_rec q 0 0 p (size p).\nFact redivp_key : unit. Proof. by []. Qed.\nDefinition redivp : {poly R} -> {poly R} -> nat * {poly R} * {poly R} :=\n  locked_with redivp_key redivp_expanded_def.\nCanonical redivp_unlockable := [unlockable fun redivp].\n\nDefinition rdivp p q := ((redivp p q).1).2.\nDefinition rmodp p q := (redivp p q).2.\nDefinition rscalp p q := ((redivp p q).1).1.\nDefinition rdvdp p q := rmodp q p == 0.\n(*Definition rmultp := [rel m d | rdvdp d m].*)\nLemma redivp_def p q : redivp p q = (rscalp p q, rdivp p q, rmodp p q).\nProof. by rewrite /rscalp /rdivp /rmodp; case: (redivp p q) => [[]] /=. Qed.\n\nLemma rdiv0p p : rdivp 0 p = 0.\nProof.\nrewrite /rdivp unlock; case: ifP => // Hp; rewrite /redivp_rec !size_poly0.\nby rewrite polySpred ?Hp.\nQed.\n\nLemma rdivp0 p : rdivp p 0 = 0. Proof. by rewrite /rdivp unlock eqxx. Qed.\n\nLemma rdivp_small p q : size p < size q -> rdivp p q = 0.\nProof.\nrewrite /rdivp unlock; have [-> | _ ltpq] := eqP; first by rewrite size_poly0.\nby case: (size p) => [|s]; rewrite /= ltpq.\nQed.\n\nLemma leq_rdivp p q : size (rdivp p q) <= size p.\nProof.\nhave [/rdivp_small->|] := ltnP (size p) (size q); first by rewrite size_poly0.\nrewrite /rdivp /rmodp /rscalp unlock.\nhave [->|q0] //= := eqVneq q 0.\nhave: size (0 : {poly R}) <= size p by rewrite size_poly0.\nmove: {2 3 4 6}(size p) (leqnn (size p)) => A.\nelim: (size p) 0%N (0 : {poly R}) {1 3 4}p (leqnn (size p)) => [|n ihn] k q1 r.\n  by move/size_poly_leq0P->; rewrite /= size_poly0 size_poly_gt0 q0.\nmove=> /= hrn hr hq1 hq; case: ltnP => //= hqr.\nhave sq: 0 < size q by rewrite size_poly_gt0.\nhave sr: 0 < size r by apply: leq_trans sq hqr.\napply: ihn => //.\n- apply/leq_sizeP => j hnj.\n  rewrite coefB -scalerAl coefZ coefXnM ltn_subRL ltnNge.\n  have hj : (size r).-1 <= j by apply: leq_trans hnj; rewrite -ltnS prednK.\n  rewrite [leqLHS]polySpred -?size_poly_gt0 // coefMC.\n  rewrite (leq_ltn_trans hj) /=; last by rewrite -add1n leq_add2r.\n  move: hj; rewrite leq_eqVlt prednK // => /predU1P [<- | hj].\n    by rewrite -subn1 subnAC subKn // !subn1 !lead_coefE subrr.\n  have/leq_sizeP-> //: size q <= j - (size r - size q).\n    by rewrite subnBA // leq_psubRL // leq_add2r.\n  by move/leq_sizeP: (hj) => -> //; rewrite mul0r mulr0 subr0.\n- apply: leq_trans (size_add _ _) _; rewrite geq_max; apply/andP; split.\n    apply: leq_trans (size_mul_leq _ _) _.\n    by rewrite size_polyC lead_coef_eq0 q0 /= addn1.\n  rewrite size_opp; apply: leq_trans (size_mul_leq _ _) _.\n  apply: leq_trans hr; rewrite -subn1 leq_subLR -[in (1 + _)%N](subnK hqr).\n  by rewrite addnA leq_add2r add1n -(@size_polyXn R) size_scale_leq.\napply: leq_trans (size_add _ _) _; rewrite geq_max; apply/andP; split.\n  apply: leq_trans (size_mul_leq _ _) _.\n  by rewrite size_polyC lead_coef_eq0 q0 /= addnS addn0.\napply: leq_trans (size_scale_leq _ _) _.\nby rewrite size_polyXn -subSn // leq_subLR -add1n leq_add.\nQed.\n\nLemma rmod0p p : rmodp 0 p = 0.\nProof.\nrewrite /rmodp unlock; case: ifP => // Hp; rewrite /redivp_rec !size_poly0.\nby rewrite polySpred ?Hp.\nQed.\n\nLemma rmodp0 p : rmodp p 0 = p. Proof. by rewrite /rmodp unlock eqxx. Qed.\n\nLemma rscalp_small p q : size p < size q -> rscalp p q = 0%N.\nProof.\nrewrite /rscalp unlock; case: eqP => _ // spq.\nby case sp: (size p) => [| s] /=; rewrite spq.\nQed.\n\nLemma ltn_rmodp p q : (size (rmodp p q) < size q) = (q != 0).\nProof.\nrewrite /rdivp /rmodp /rscalp unlock; have [->|q0] := eqVneq q 0.\n  by rewrite /= size_poly0 ltn0.\nelim: (size p) 0%N 0 {1 3}p (leqnn (size p)) => [|n ihn] k q1 r.\n  move/size_poly_leq0P->.\n  by rewrite /= size_poly0 size_poly_gt0 q0 size_poly0 size_poly_gt0.\nmove=> hr /=; case: (ltnP (size r)) => // hsrq; apply/ihn/leq_sizeP => j hnj.\nrewrite coefB -scalerAl !coefZ coefXnM coefMC ltn_subRL ltnNge.\nhave sq: 0 < size q by rewrite size_poly_gt0.\nhave sr: 0 < size r by apply: leq_trans hsrq.\nhave hj: (size r).-1 <= j by apply: leq_trans hnj; rewrite -ltnS prednK.\nmove: (leq_add sq hj); rewrite add1n prednK // => -> /=.\nmove: hj; rewrite leq_eqVlt prednK // => /predU1P [<- | hj].\n  by rewrite -predn_sub subKn // !lead_coefE subrr.\nhave/leq_sizeP -> //: size q <= j - (size r - size q).\n  by rewrite subnBA // leq_subRL ?leq_add2r // (leq_trans hj) // leq_addr.\nby move/leq_sizeP: hj => -> //; rewrite mul0r mulr0 subr0.\nQed.\n\nLemma ltn_rmodpN0 p q : q != 0 -> size (rmodp p q) < size q.\nProof. by rewrite ltn_rmodp. Qed.\n\nLemma rmodp1 p : rmodp p 1 = 0.\nProof.\napply/eqP; have := ltn_rmodp p 1.\nby rewrite !oner_neq0 -size_poly_eq0 size_poly1 ltnS leqn0.\nQed.\n\nLemma rmodp_small p q : size p < size q -> rmodp p q = p.\nProof.\nrewrite /rmodp unlock; have [->|_] := eqP; first by rewrite size_poly0.\nby case sp: (size p) => [| s] Hs /=; rewrite sp Hs /=.\nQed.\n\nLemma leq_rmodp m d : size (rmodp m d) <= size m.\nProof.\nhave [/rmodp_small -> //|h] := ltnP (size m) (size d).\nhave [->|d0] := eqVneq d 0; first by rewrite rmodp0.\nby apply: leq_trans h; apply: ltnW; rewrite ltn_rmodp.\nQed.\n\nLemma rmodpC p c : c != 0 -> rmodp p c%:P = 0.\nProof.\nmove=> Hc; apply/eqP; rewrite -size_poly_leq0 -ltnS.\nhave -> : 1%N = nat_of_bool (c != 0) by rewrite Hc.\nby rewrite -size_polyC ltn_rmodp polyC_eq0.\nQed.\n\nLemma rdvdp0 d : rdvdp d 0. Proof. by rewrite /rdvdp rmod0p. Qed.\n\nLemma rdvd0p n : rdvdp 0 n = (n == 0). Proof. by rewrite /rdvdp rmodp0. Qed.\n\nLemma rdvd0pP n : reflect (n = 0) (rdvdp 0 n).\nProof. by apply: (iffP idP); rewrite rdvd0p; move/eqP. Qed.\n\nLemma rdvdpN0 p q : rdvdp p q -> q != 0 -> p != 0.\nProof. by move=> pq hq; apply: contraTneq pq => ->; rewrite rdvd0p. Qed.\n\nLemma rdvdp1 d : rdvdp d 1 = (size d == 1%N).\nProof.\nrewrite /rdvdp; have [->|] := eqVneq d 0.\n  by rewrite rmodp0 size_poly0 (negPf (oner_neq0 _)).\nrewrite -size_poly_leq0 -ltnS; case: ltngtP => // [|/eqP] hd _.\n  by rewrite rmodp_small ?size_poly1 // oner_eq0.\nhave [c cn0 ->] := size_poly1P _ hd.\nrewrite /rmodp unlock -size_poly_eq0 size_poly1 /= size_poly1 size_polyC cn0 /=.\nby rewrite polyC_eq0 (negPf cn0) !lead_coefC !scale1r subrr !size_poly0.\nQed.\n\nLemma rdvd1p m : rdvdp 1 m. Proof. by rewrite /rdvdp rmodp1. Qed.\n\nLemma Nrdvdp_small (n d : {poly R}) :\n  n != 0 -> size n < size d -> rdvdp d n = false.\nProof. by move=> nn0 hs; rewrite /rdvdp (rmodp_small hs); apply: negPf. Qed.\n\nLemma rmodp_eq0P p q : reflect (rmodp p q = 0) (rdvdp q p).\nProof. exact: (iffP eqP). Qed.\n\nLemma rmodp_eq0 p q : rdvdp q p -> rmodp p q = 0. Proof. exact: rmodp_eq0P. Qed.\n\nLemma rdvdp_leq p q : rdvdp p q -> q != 0 -> size p <= size q.\nProof. by move=> dvd_pq; rewrite leqNgt; apply: contra => /rmodp_small <-. Qed.\n\nDefinition rgcdp p q :=\n  let: (p1, q1) := if size p < size q then (q, p) else (p, q) in\n  if p1 == 0 then q1 else\n  let fix loop (n : nat) (pp qq : {poly R}) {struct n} :=\n      let rr := rmodp pp qq in\n      if rr == 0 then qq else\n      if n is n1.+1 then loop n1 qq rr else rr in\n  loop (size p1) p1 q1.\n\nLemma rgcd0p : left_id 0 rgcdp.\nProof.\nmove=> p; rewrite /rgcdp size_poly0 size_poly_gt0 if_neg.\ncase: ifP => /= [_ | nzp]; first by rewrite eqxx.\nby rewrite polySpred !(rmodp0, nzp) //; case: _.-1 => [|m]; rewrite rmod0p eqxx.\nQed.\n\nLemma rgcdp0 : right_id 0 rgcdp.\nProof.\nmove=> p; have:= rgcd0p p; rewrite /rgcdp size_poly0 size_poly_gt0.\nby case: eqVneq => p0; rewrite ?(eqxx, p0) //= eqxx.\nQed.\n\nLemma rgcdpE p q :\n  rgcdp p q = if size p < size q\n    then rgcdp (rmodp q p) p else rgcdp (rmodp p q) q.\nProof.\npose rgcdp_rec := fix rgcdp_rec (n : nat) (pp qq : {poly R}) {struct n} :=\n   let rr := rmodp pp qq in\n   if rr == 0 then qq else\n   if n is n1.+1 then rgcdp_rec n1 qq rr else rr.\nhave Irec: forall m n p q, size q <= m -> size q <= n\n      -> size q < size p -> rgcdp_rec m p q = rgcdp_rec n p q.\n  + elim=> [|m Hrec] [|n] //= p1 q1.\n    - move/size_poly_leq0P=> -> _; rewrite size_poly0 size_poly_gt0 rmodp0.\n      by move/negPf->; case: n => [|n] /=; rewrite rmod0p eqxx.\n    - move=> _ /size_poly_leq0P ->; rewrite size_poly0 size_poly_gt0 rmodp0.\n      by move/negPf->; case: m {Hrec} => [|m] /=; rewrite rmod0p eqxx.\n  case: eqVneq => Epq Sm Sn Sq //; have [->|nzq] := eqVneq q1 0.\n    by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite rmod0p eqxx.\n  apply: Hrec; last by rewrite ltn_rmodp.\n    by rewrite -ltnS (leq_trans _ Sm) // ltn_rmodp.\n  by rewrite -ltnS (leq_trans _ Sn) // ltn_rmodp.\nhave [->|nzp] := eqVneq p 0.\n  by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same.\nhave [->|nzq] := eqVneq q 0.\n  by rewrite rmod0p rmodp0 rgcd0p rgcdp0 if_same.\nrewrite /rgcdp -/rgcdp_rec !ltn_rmodp (negPf nzp) (negPf nzq) /=.\nhave [ltpq|leqp] := ltnP; rewrite !(negPf nzp, negPf nzq) //= polySpred //=.\n  have [->|nzqp] := eqVneq.\n    by case: (size p) => [|[|s]]; rewrite /= rmodp0 (negPf nzp) // rmod0p eqxx.\n  apply: Irec => //; last by rewrite ltn_rmodp.\n    by rewrite -ltnS -polySpred // (leq_trans _ ltpq) ?leqW // ltn_rmodp.\n  by rewrite ltnW // ltn_rmodp.\nhave [->|nzpq] := eqVneq.\n  by case: (size q) => [|[|s]]; rewrite /= rmodp0 (negPf nzq) // rmod0p eqxx.\napply: Irec => //; last by rewrite ltn_rmodp.\n  by rewrite -ltnS -polySpred // (leq_trans _ leqp) // ltn_rmodp.\nby rewrite ltnW // ltn_rmodp.\nQed.\n\nVariant comm_redivp_spec m d : nat * {poly R} * {poly R} -> Type :=\n  ComEdivnSpec k (q r : {poly R}) of\n   (GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ k)%:P = q * d + r) &\n   (d != 0 -> size r < size d) : comm_redivp_spec m d (k, q, r).\n\nLemma comm_redivpP m d : comm_redivp_spec m d (redivp m d).\nProof.\nrewrite unlock; have [->|Hd] := eqVneq d 0.\n  by constructor; rewrite !(simp, eqxx).\nhave: GRing.comm d (lead_coef d)%:P -> m * (lead_coef d ^+ 0)%:P = 0 * d + m.\n  by rewrite !simp.\nelim: (size m) 0%N 0 {1 4 6}m (leqnn (size m)) => [|n IHn] k q r Hr /=.\n  move/size_poly_leq0P: Hr ->.\n  suff hsd: size (0: {poly R}) < size d by rewrite hsd => /= ?; constructor.\n  by rewrite size_poly0 size_poly_gt0.\ncase: ltnP => Hlt Heq; first by constructor.\napply/IHn=> [|Cda]; last first.\n  rewrite mulrDl addrAC -addrA subrK exprSr polyCM mulrA Heq //.\n  by rewrite mulrDl -mulrA Cda mulrA.\napply/leq_sizeP => j Hj; rewrite coefB coefMC -scalerAl coefZ coefXnM.\nrewrite ltn_subRL ltnNge (leq_trans Hr) /=; last first.\n  by apply: leq_ltn_trans Hj _; rewrite -add1n leq_add2r size_poly_gt0.\nmove: Hj; rewrite leq_eqVlt; case/predU1P => [<-{j} | Hj]; last first.\n  rewrite !nth_default ?simp ?oppr0 ?(leq_trans Hr) //.\n  by rewrite -{1}(subKn Hlt) leq_sub2r // (leq_trans Hr).\nmove: Hr; rewrite leq_eqVlt ltnS; case/predU1P=> Hqq; last first.\n  by rewrite !nth_default ?simp ?oppr0 // -{1}(subKn Hlt) leq_sub2r.\nrewrite /lead_coef Hqq polySpred // subSS subKn ?addrN //.\nby rewrite -subn1 leq_subLR add1n -Hqq.\nQed.\n\nLemma rmodpp p : GRing.comm p (lead_coef p)%:P -> rmodp p p = 0.\nProof.\nmove=> hC; rewrite /rmodp unlock; have [-> //|] := eqVneq.\nrewrite -size_poly_eq0 /redivp_rec; case sp: (size p)=> [|n] // _.\nrewrite sp ltnn subnn expr0 hC alg_polyC !simp subrr.\nby case: n sp => [|n] sp; rewrite size_polyC /= eqxx.\nQed.\n\nDefinition rcoprimep (p q : {poly R}) := size (rgcdp p q) == 1%N.\n\nFixpoint rgdcop_rec q p n :=\n  if n is m.+1 then\n      if rcoprimep p q then p\n        else rgdcop_rec q (rdivp p (rgcdp p q)) m\n    else (q == 0)%:R.\n\nDefinition rgdcop q p := rgdcop_rec q p (size p).\n\nLemma rgdcop0 q : rgdcop q 0 = (q == 0)%:R.\nProof. by rewrite /rgdcop size_poly0. Qed.\n\nEnd RingPseudoDivision.\n\nEnd CommonRing.\n\nModule RingComRreg.\n\nImport CommonRing.\n\nSection ComRegDivisor.\n\nVariable R : ringType.\nVariable d : {poly R}.\nHypothesis Cdl : GRing.comm d (lead_coef d)%:P.\nHypothesis Rreg : GRing.rreg (lead_coef d).\n\nImplicit Types p q r : {poly R}.\n\nLemma redivp_eq q r :\n    size r < size d ->\n    let k := (redivp (q * d + r) d).1.1 in\n    let c := (lead_coef d ^+ k)%:P in\n  redivp (q * d + r) d = (k, q * c, r * c).\nProof.\nmove=> lt_rd; case: comm_redivpP=> k q1 r1 /(_ Cdl) Heq.\nhave dn0: d != 0 by case: (size d) lt_rd (size_poly_eq0 d) => // n _ <-.\nmove=> /(_ dn0) Hs.\nhave eC : q * d * (lead_coef d ^+ k)%:P = q * (lead_coef d ^+ k)%:P * d.\n  by rewrite -mulrA polyC_exp (commrX k Cdl) mulrA.\nsuff e1 : q1 = q * (lead_coef d ^+ k)%:P.\n  congr (_, _, _) => //=; move/eqP: Heq.\n  by rewrite [_ + r1]addrC -subr_eq e1 mulrDl addrAC eC subrr add0r; move/eqP.\nhave : (q1 - q * (lead_coef d ^+ k)%:P) * d = r * (lead_coef d ^+ k)%:P - r1.\n  apply: (@addIr _ r1); rewrite subrK.\n  apply: (@addrI _ ((q * (lead_coef d ^+ k)%:P) * d)).\n  by rewrite mulrDl mulNr !addrA [_ + (q1 * d)]addrC addrK -eC -mulrDl.\nmove/eqP; rewrite -[_ == _ - _]subr_eq0 rreg_div0 //.\n  by case/andP; rewrite subr_eq0; move/eqP.\nrewrite size_opp; apply: (leq_ltn_trans (size_add _ _)); rewrite size_opp.\nrewrite gtn_max Hs (leq_ltn_trans (size_mul_leq _ _)) //.\nrewrite size_polyC; case: (_ == _); last by rewrite addnS addn0.\nby rewrite addn0; apply: leq_ltn_trans lt_rd; case: size.\nQed.\n\n(* this is a bad name *)\nLemma rdivp_eq p :\n  p * (lead_coef d ^+ (rscalp p d))%:P = (rdivp p d) * d + (rmodp p d).\nProof.\nby rewrite /rdivp /rmodp /rscalp; case: comm_redivpP=> k q1 r1 Hc _; apply: Hc.\nQed.\n\n(* section variables impose an inconvenient order on parameters *)\nLemma eq_rdvdp k q1 p:\n  p * ((lead_coef d)^+ k)%:P = q1 * d -> rdvdp d p.\nProof.\nmove=> he.\nhave Hnq0 := rreg_lead0 Rreg; set lq := lead_coef d.\npose v := rscalp p d; pose m := maxn v k.\nrewrite /rdvdp -(rreg_polyMC_eq0 _ (@rregX _ _ (m - v) Rreg)).\nsuff:\n ((rdivp p d) * (lq ^+ (m - v))%:P - q1 * (lq ^+ (m - k))%:P) * d +\n  (rmodp p d) * (lq ^+ (m - v))%:P == 0.\n  rewrite rreg_div0 //; first by case/andP.\n  by rewrite rreg_size ?ltn_rmodp //; exact: rregX.\nrewrite mulrDl addrAC mulNr -!mulrA polyC_exp -(commrX (m-v) Cdl).\nrewrite -polyC_exp mulrA -mulrDl -rdivp_eq // [(_ ^+ (m - k))%:P]polyC_exp.\nrewrite -(commrX (m-k) Cdl) -polyC_exp mulrA -he -!mulrA -!polyCM -/v.\nby rewrite -!exprD addnC subnK ?leq_maxl // addnC subnK ?subrr ?leq_maxr.\nQed.\n\nVariant rdvdp_spec p q : {poly R} -> bool -> Type :=\n  | Rdvdp k q1 & p * ((lead_coef q)^+ k)%:P = q1 * q : rdvdp_spec p q 0 true\n  | RdvdpN & rmodp p q != 0 : rdvdp_spec p q (rmodp p q) false.\n\n(* Is that version useable ? *)\n\nLemma rdvdp_eqP p : rdvdp_spec p d (rmodp p d) (rdvdp d p).\nProof.\ncase hdvd: (rdvdp d p); last by apply: RdvdpN; move/rmodp_eq0P/eqP: hdvd.\nmove/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ (rscalp p d) (rdivp p d)).\nby rewrite rdivp_eq //; move/rmodp_eq0P: (hdvd)->; rewrite addr0.\nQed.\n\nLemma rdvdp_mull p : rdvdp d (p * d).\nProof. by apply: (@eq_rdvdp 0%N p); rewrite expr0 mulr1. Qed.\n\nLemma rmodp_mull p : rmodp (p * d) d = 0. Proof. exact/eqP/rdvdp_mull. Qed.\n\nLemma rmodpp : rmodp d d = 0.\nProof. by rewrite -[d in rmodp d _]mul1r rmodp_mull. Qed.\n\nLemma rdivpp : rdivp d d = (lead_coef d ^+ rscalp d d)%:P.\nProof.\nhave dn0 : d != 0 by rewrite -lead_coef_eq0 rreg_neq0.\nmove: (rdivp_eq d); rewrite rmodpp addr0.\nsuff ->: GRing.comm d (lead_coef d ^+ rscalp d d)%:P by move/(rreg_lead Rreg)->.\nby rewrite polyC_exp; apply: commrX.\nQed.\n\nLemma rdvdpp : rdvdp d d. Proof. exact/eqP/rmodpp. Qed.\n\nLemma rdivpK p : rdvdp d p ->\n  rdivp p d * d = p * (lead_coef d ^+ rscalp p d)%:P.\nProof. by rewrite rdivp_eq /rdvdp; move/eqP->; rewrite addr0. Qed.\n\nEnd ComRegDivisor.\n\nEnd RingComRreg.\n\nModule RingMonic.\n\nImport CommonRing.\n\nImport RingComRreg.\n\nSection RingMonic.\n\nVariable R : ringType.\nImplicit Types p q r : {poly R}.\n\nSection MonicDivisor.\n\nVariable d : {poly R}.\nHypothesis mond : d \\is monic.\n\nLemma redivp_eq q r : size r < size d ->\n  let k := (redivp (q * d + r) d).1.1 in\n  redivp (q * d + r) d = (k, q, r).\nProof.\ncase: (monic_comreg mond)=> Hc Hr /(redivp_eq Hc Hr q).\nby rewrite (eqP mond) => -> /=; rewrite expr1n !mulr1.\nQed.\n\nLemma rdivp_eq p : p = rdivp p d * d + rmodp p d.\nProof.\nrewrite -rdivp_eq (eqP mond); last exact: commr1.\nby rewrite expr1n mulr1.\nQed.\n\nLemma rdivpp : rdivp d d = 1.\nProof.\nby case: (monic_comreg mond) => hc hr; rewrite rdivpp // (eqP mond) expr1n.\nQed.\n\nLemma rdivp_addl_mul_small q r : size r < size d -> rdivp (q * d + r) d = q.\nProof.\nby move=> Hd; case: (monic_comreg mond)=> Hc Hr; rewrite /rdivp redivp_eq.\nQed.\n\nLemma rdivp_addl_mul q r : rdivp (q * d + r) d = q + rdivp r d.\nProof.\ncase: (monic_comreg mond)=> Hc Hr; rewrite [r in _ * _ + r]rdivp_eq addrA.\nby rewrite -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0.\nQed.\n\nLemma rdivpDl q r : rdvdp d q -> rdivp (q + r) d = rdivp q d + rdivp r d.\nProof.\ncase: (monic_comreg mond)=> Hc Hr; rewrite [r in q + r]rdivp_eq addrA.\nrewrite [q in q + _ + _]rdivp_eq; move/rmodp_eq0P->.\nby rewrite addr0 -mulrDl rdivp_addl_mul_small // ltn_rmodp monic_neq0.\nQed.\n\nLemma rdivpDr q r : rdvdp d r -> rdivp (q + r) d = rdivp q d + rdivp r d.\nProof. by rewrite addrC; move/rdivpDl->; rewrite addrC. Qed.\n\nLemma rdivp_mull p : rdivp (p * d) d = p.\nProof. by rewrite -[p * d]addr0 rdivp_addl_mul rdiv0p addr0. Qed.\n\nLemma rmodp_mull p : rmodp (p * d) d = 0.\nProof.\nby apply: rmodp_mull; rewrite (eqP mond); [apply: commr1 | apply: rreg1].\nQed.\n\nLemma rmodpp : rmodp d d = 0.\nProof.\nby apply: rmodpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1].\nQed.\n\nLemma rmodp_addl_mul_small q r : size r < size d -> rmodp (q * d + r) d = r.\nProof.\nby move=> Hd; case: (monic_comreg mond)=> Hc Hr; rewrite /rmodp redivp_eq.\nQed.\n\nLemma rmodpD p q : rmodp (p + q) d = rmodp p d + rmodp q d.\nProof.\nrewrite [p in LHS]rdivp_eq [q in LHS]rdivp_eq addrACA -mulrDl.\nrewrite rmodp_addl_mul_small //; apply: (leq_ltn_trans (size_add _ _)).\nby rewrite gtn_max !ltn_rmodp // monic_neq0.\nQed.\n\nLemma rmodp_mulmr p q : rmodp (p * (rmodp q d)) d = rmodp (p * q) d.\nProof.\nby rewrite [q in RHS]rdivp_eq mulrDr rmodpD mulrA rmodp_mull add0r.\nQed.\n\nLemma rdvdpp : rdvdp d d.\nProof.\nby apply: rdvdpp; rewrite (eqP mond); [apply: commr1 | apply: rreg1].\nQed.\n\n(* section variables impose an inconvenient order on parameters *)\nLemma eq_rdvdp q1 p : p = q1 * d -> rdvdp d p.\nProof.\n(*  this probably means I need to specify impl args for comm_rref_rdvdp *)\nmove=> h; apply: (@eq_rdvdp _ _ _ _ 1%N q1); rewrite (eqP mond).\n- exact: commr1.\n- exact: rreg1.\nby rewrite expr1n mulr1.\nQed.\n\nLemma rdvdp_mull p : rdvdp d (p * d).\nProof.\nby apply: rdvdp_mull; rewrite (eqP mond) //; [apply: commr1 | apply: rreg1].\nQed.\n\nLemma rdvdpP p : reflect (exists qq, p = qq * d) (rdvdp d p).\nProof.\ncase: (monic_comreg mond)=> Hc Hr; apply: (iffP idP) => [|[qq] /eq_rdvdp //].\nby case: rdvdp_eqP=> // k qq; rewrite (eqP mond) expr1n mulr1 => ->; exists qq.\nQed.\n\nLemma rdivpK p : rdvdp d p -> (rdivp p d) * d = p.\nProof. by move=> dvddp; rewrite [RHS]rdivp_eq rmodp_eq0 ?addr0. Qed.\n\nEnd MonicDivisor.\n\nLemma drop_poly_rdivp n p : drop_poly n p = rdivp p 'X^n.\nProof.\nrewrite -[p in RHS](poly_take_drop n) addrC rdivp_addl_mul ?monicXn//.\nby rewrite rdivp_small ?addr0// size_polyXn ltnS size_take_poly.\nQed.\n\nLemma take_poly_rmodp n p : take_poly n p = rmodp p 'X^n.\nProof.\nhave mX := monicXn R n; rewrite -[p in RHS](poly_take_drop n) rmodpD//.\nby rewrite rmodp_small ?rmodp_mull ?addr0// size_polyXn ltnS size_take_poly.\nQed.\n\nEnd RingMonic.\n\nEnd RingMonic.\n\nModule Ring.\n\nInclude CommonRing.\nImport RingMonic.\n\nSection ExtraMonicDivisor.\n\nVariable R : ringType.\n\nImplicit Types d p q r : {poly R}.\n\nLemma rdivp1 p : rdivp p 1 = p.\nProof. by rewrite -[p in LHS]mulr1 rdivp_mull // monic1. Qed.\n\nLemma rdvdp_XsubCl p x : rdvdp ('X - x%:P) p = root p x.\nProof.\nhave [HcX Hr] := monic_comreg (monicXsubC x).\napply/rmodp_eq0P/factor_theorem => [|[p1 ->]]; last exact/rmodp_mull/monicXsubC.\nmove=> e0; exists (rdivp p ('X - x%:P)).\nby rewrite [LHS](rdivp_eq (monicXsubC x)) e0 addr0.\nQed.\n\nLemma polyXsubCP p x : reflect (p.[x] = 0) (rdvdp ('X - x%:P) p).\nProof. by apply: (iffP idP); rewrite rdvdp_XsubCl; move/rootP. Qed.\n\nLemma root_factor_theorem p x : root p x = (rdvdp ('X - x%:P) p).\nProof. by rewrite rdvdp_XsubCl. Qed.\n\nEnd ExtraMonicDivisor.\n\nEnd Ring.\n\nModule ComRing.\n\nImport Ring.\n\nImport RingComRreg.\n\nSection CommutativeRingPseudoDivision.\n\nVariable R : comRingType.\n\nImplicit Types d p q m n r : {poly R}.\n\nVariant redivp_spec (m d : {poly R}) : nat * {poly R} * {poly R} -> Type :=\n  EdivnSpec k (q r: {poly R}) of\n    (lead_coef d ^+ k) *: m = q * d + r &\n   (d != 0 -> size r < size d) : redivp_spec m d (k, q, r).\n\nLemma redivpP m d : redivp_spec m d (redivp m d).\nProof.\nrewrite redivp_def; constructor; last by move=> dn0; rewrite ltn_rmodp.\nby rewrite -mul_polyC mulrC rdivp_eq //= /GRing.comm mulrC.\nQed.\n\nLemma rdivp_eq d p :\n  (lead_coef d ^+ rscalp p d) *: p = rdivp p d * d + rmodp p d.\nProof.\nby rewrite /rdivp /rmodp /rscalp; case: redivpP=> k q1 r1 Hc _; apply: Hc.\nQed.\n\nLemma rdvdp_eqP d p : rdvdp_spec p d (rmodp p d) (rdvdp d p).\nProof.\ncase hdvd: (rdvdp d p); last by move/rmodp_eq0P/eqP/RdvdpN: hdvd.\nmove/rmodp_eq0P: (hdvd)->; apply: (@Rdvdp _ _ _ (rscalp p d) (rdivp p d)).\nby rewrite mulrC mul_polyC rdivp_eq; move/rmodp_eq0P: (hdvd)->; rewrite addr0.\nQed.\n\nLemma rdvdp_eq q p :\n  rdvdp q p = (lead_coef q ^+ rscalp p q *: p == rdivp p q * q).\nProof.\nrewrite rdivp_eq; apply/rmodp_eq0P/eqP => [->|/eqP]; first by rewrite addr0.\nby rewrite eq_sym addrC -subr_eq subrr; move/eqP<-.\nQed.\n\nEnd CommutativeRingPseudoDivision.\n\nEnd ComRing.\n\nModule UnitRing.\n\nImport Ring.\n\nSection UnitRingPseudoDivision.\n\nVariable R : unitRingType.\nImplicit Type p q r d : {poly R}.\n\nLemma uniq_roots_rdvdp p rs :\n  all (root p) rs -> uniq_roots rs -> rdvdp (\\prod_(z <- rs) ('X - z%:P)) p.\nProof.\nmove=> rrs /(uniq_roots_prod_XsubC rrs) [q ->].\nexact/RingMonic.rdvdp_mull/monic_prod_XsubC.\nQed.\n\nEnd UnitRingPseudoDivision.\n\nEnd UnitRing.\n\nModule IdomainDefs.\n\nImport Ring.\n\nSection IDomainPseudoDivisionDefs.\n\nVariable R : idomainType.\nImplicit Type p q r d : {poly R}.\n\nDefinition edivp_expanded_def p q :=\n  let: (k, d, r) as edvpq := redivp p q in\n  if lead_coef q \\in GRing.unit then\n    (0%N, (lead_coef q)^-k *: d, (lead_coef q)^-k *: r)\n  else edvpq.\nFact edivp_key : unit. Proof. by []. Qed.\nDefinition edivp := locked_with edivp_key edivp_expanded_def.\nCanonical edivp_unlockable := [unlockable fun edivp].\n\nDefinition divp p q := ((edivp p q).1).2.\nDefinition modp p q := (edivp p q).2.\nDefinition scalp p q := ((edivp p q).1).1.\nDefinition dvdp p q := modp q p == 0.\nDefinition eqp p q := (dvdp p q) && (dvdp q p).\n\nEnd IDomainPseudoDivisionDefs.\n\nNotation \"m %/ d\" := (divp m d) : ring_scope.\nNotation \"m %% d\" := (modp m d) : ring_scope.\nNotation \"p %| q\" := (dvdp p q) : ring_scope.\nNotation \"p %= q\" := (eqp p q) : ring_scope.\nEnd IdomainDefs.\n\nModule WeakIdomain.\n\nImport Ring ComRing UnitRing IdomainDefs.\n\nSection WeakTheoryForIDomainPseudoDivision.\n\nVariable R : idomainType.\nImplicit Type p q r d : {poly R}.\n\nLemma edivp_def p q : edivp p q = (scalp p q, divp p q, modp p q).\nProof. by rewrite /scalp /divp /modp; case: (edivp p q) => [[]] /=. Qed.\n\nLemma edivp_redivp p q : lead_coef q \\in GRing.unit = false ->\n  edivp p q = redivp p q.\nProof. by move=> hu; rewrite unlock hu; case: (redivp p q) => [[? ?] ?]. Qed.\n\nLemma divpE p q :\n  p %/ q = if lead_coef q \\in GRing.unit\n    then lead_coef q ^- rscalp p q *: rdivp p q\n    else rdivp p q.\nProof. by case: ifP; rewrite /divp unlock redivp_def => ->. Qed.\n\nLemma modpE p q :\n  p %% q = if lead_coef q \\in GRing.unit\n    then lead_coef q ^- rscalp p q *: (rmodp p q)\n    else rmodp p q.\nProof. by case: ifP; rewrite /modp unlock redivp_def => ->. Qed.\n\nLemma scalpE p q :\n  scalp p q = if lead_coef q \\in GRing.unit then 0%N else rscalp p q.\nProof. by case: ifP; rewrite /scalp unlock redivp_def => ->. Qed.\n\nLemma dvdpE p q : p %| q = rdvdp p q.\nProof.\nrewrite /dvdp modpE /rdvdp; case ulcq: (lead_coef p \\in GRing.unit)=> //.\nrewrite -[in LHS]size_poly_eq0 size_scale ?size_poly_eq0 //.\nby rewrite invr_eq0 expf_neq0 //; apply: contraTneq ulcq => ->; rewrite unitr0.\nQed.\n\nLemma lc_expn_scalp_neq0 p q : lead_coef q ^+ scalp p q != 0.\nProof.\nhave [->|nzq] := eqVneq q 0; last by rewrite expf_neq0 ?lead_coef_eq0.\nby rewrite /scalp 2!unlock /= eqxx lead_coef0 unitr0 /= oner_neq0.\nQed.\n\nHint Resolve lc_expn_scalp_neq0 : core.\n\nVariant edivp_spec (m d : {poly R}) :\n                                     nat * {poly R} * {poly R} -> bool -> Type :=\n|Redivp_spec k (q r: {poly R}) of\n  (lead_coef d ^+ k) *: m = q * d + r & lead_coef d \\notin GRing.unit &\n  (d != 0 -> size r < size d) : edivp_spec m d (k, q, r) false\n|Fedivp_spec (q r: {poly R}) of m = q * d + r & (lead_coef d \\in GRing.unit) &\n  (d != 0 -> size r < size d) : edivp_spec m d (0%N, q, r) true.\n\n(* There are several ways to state this fact. The most appropriate statement*)\n(* might be polished in light of usage. *)\nLemma edivpP m d : edivp_spec m d (edivp m d) (lead_coef d \\in GRing.unit).\nProof.\nhave hC : GRing.comm d (lead_coef d)%:P by rewrite /GRing.comm mulrC.\ncase ud: (lead_coef d \\in GRing.unit); last first.\n  rewrite edivp_redivp // redivp_def; constructor; rewrite ?ltn_rmodp // ?ud //.\n  by rewrite rdivp_eq.\nhave cdn0: lead_coef d != 0 by apply: contraTneq ud => ->; rewrite unitr0.\nrewrite unlock ud redivp_def; constructor => //.\n  rewrite -scalerAl -scalerDr -mul_polyC.\n  have hn0 : (lead_coef d ^+ rscalp m d)%:P != 0.\n    by rewrite polyC_eq0; apply: expf_neq0.\n  apply: (mulfI hn0); rewrite !mulrA -exprVn !polyC_exp -exprMn -polyCM.\n  by rewrite divrr // expr1n mul1r -polyC_exp mul_polyC rdivp_eq.\nmove=> dn0; rewrite size_scale ?ltn_rmodp // -exprVn expf_eq0 negb_and.\nby rewrite invr_eq0 cdn0 orbT.\nQed.\n\nLemma edivp_eq d q r : size r < size d -> lead_coef d \\in GRing.unit ->\n  edivp (q * d + r) d = (0%N, q, r).\nProof.\nhave hC : GRing.comm d (lead_coef d)%:P by apply: mulrC.\nmove=> hsrd hu; rewrite unlock hu; case et: (redivp _ _) => [[s qq] rr].\nhave cdn0 : lead_coef d != 0 by case: eqP hu => //= ->; rewrite unitr0.\nmove: (et); rewrite RingComRreg.redivp_eq //; last exact/rregP.\nrewrite et /= mulrC (mulrC r) !mul_polyC; case=> <- <-.\nby rewrite !scalerA mulVr ?scale1r // unitrX.\nQed.\n\nLemma divp_eq p q : (lead_coef q ^+ scalp p q) *: p = (p %/ q) * q + (p %% q).\nProof.\nrewrite divpE modpE scalpE.\ncase uq: (lead_coef q \\in GRing.unit); last by rewrite rdivp_eq.\nrewrite expr0 scale1r; have [->|qn0] := eqVneq q 0.\n  by rewrite lead_coef0 expr0n /rscalp unlock eqxx invr1 !scale1r rmodp0 !simp.\nby rewrite -scalerAl -scalerDr -rdivp_eq scalerA mulVr (scale1r, unitrX).\nQed.\n\nLemma dvdp_eq q p : (q %| p) = (lead_coef q ^+ scalp p q *: p == (p %/ q) * q).\nProof.\nrewrite dvdpE rdvdp_eq scalpE divpE; case: ifP => ulcq //.\nrewrite expr0 scale1r -scalerAl; apply/eqP/eqP => [<- | {2}->].\n  by rewrite scalerA mulVr ?scale1r // unitrX.\nby rewrite scalerA mulrV ?scale1r // unitrX.\nQed.\n\nLemma divpK d p : d %| p -> p %/ d * d = (lead_coef d ^+ scalp p d) *: p.\nProof. by rewrite dvdp_eq; move/eqP->. Qed.\n\nLemma divpKC d p : d %| p -> d * (p %/ d) = (lead_coef d ^+ scalp p d) *: p.\nProof. by move=> ?; rewrite mulrC divpK. Qed.\n\nLemma dvdpP q p :\n  reflect (exists2 cqq, cqq.1 != 0 & cqq.1 *: p = cqq.2 * q) (q %| p).\nProof.\nrewrite dvdp_eq; apply: (iffP eqP) => [e | [[c qq] cn0 e]].\n  by exists (lead_coef q ^+ scalp p q, p %/ q) => //=.\napply/eqP; rewrite -dvdp_eq dvdpE.\nhave Ecc: c%:P != 0 by rewrite polyC_eq0.\nhave [->|nz_p] := eqVneq p 0; first by rewrite rdvdp0.\npose p1 : {poly R} := lead_coef q ^+ rscalp p q *: qq - c *: (rdivp p q).\nhave E1: c *: rmodp p q = p1 * q.\n  rewrite mulrDl mulNr -scalerAl -e scalerA mulrC -scalerA -scalerAl.\n  by rewrite -scalerBr rdivp_eq addrC addKr.\nsuff: p1 * q == 0 by rewrite -E1 -mul_polyC mulf_eq0 (negPf Ecc).\nrewrite mulf_eq0; apply/norP; case=> p1_nz q_nz; have:= ltn_rmodp p q.\nby rewrite q_nz -(size_scale _ cn0) E1 size_mul // polySpred // ltnNge leq_addl.\nQed.\n\nLemma mulpK p q : q != 0 -> p * q %/ q = lead_coef q ^+ scalp (p * q) q *: p.\nProof.\nmove=> qn0; apply: (rregP qn0); rewrite -scalerAl divp_eq.\nsuff -> : (p * q) %% q = 0 by rewrite addr0.\nrewrite modpE RingComRreg.rmodp_mull ?scaler0 ?if_same //.\n  by red; rewrite mulrC.\nby apply/rregP; rewrite lead_coef_eq0.\nQed.\n\nLemma mulKp p q : q != 0 -> q * p %/ q = lead_coef q ^+ scalp (p * q) q *: p.\nProof. by move=> nzq; rewrite mulrC; apply: mulpK. Qed.\n\nLemma divpp p : p != 0 -> p %/ p = (lead_coef p ^+ scalp p p)%:P.\nProof.\nmove=> np0; have := divp_eq p p.\nsuff -> : p %% p = 0 by rewrite addr0 -mul_polyC; move/(mulIf np0).\nrewrite modpE Ring.rmodpp; last by red; rewrite mulrC.\nby rewrite scaler0 if_same.\nQed.\n\nEnd WeakTheoryForIDomainPseudoDivision.\n\n#[global] Hint Resolve lc_expn_scalp_neq0 : core.\n\nEnd WeakIdomain.\n\nModule CommonIdomain.\n\nImport Ring ComRing UnitRing IdomainDefs WeakIdomain.\n\nSection IDomainPseudoDivision.\n\nVariable R : idomainType.\nImplicit Type p q r d m n : {poly R}.\n\nLemma scalp0 p : scalp p 0 = 0%N.\nProof. by rewrite /scalp unlock lead_coef0 unitr0 unlock eqxx. Qed.\n\nLemma divp_small p q : size p < size q -> p %/ q = 0.\nProof.\nmove=> spq; rewrite /divp unlock redivp_def /=.\nby case: ifP; rewrite rdivp_small // scaler0.\nQed.\n\nLemma leq_divp p q : (size (p %/ q) <= size p).\nProof.\nrewrite /divp unlock redivp_def /=; case: ifP => ulcq; rewrite ?leq_rdivp //=.\nrewrite size_scale ?leq_rdivp // -exprVn expf_neq0 // invr_eq0.\nby case: eqP ulcq => // ->; rewrite unitr0.\nQed.\n\nLemma div0p p : 0 %/ p = 0.\nProof.\nby rewrite /divp unlock redivp_def /=; case: ifP; rewrite rdiv0p // scaler0.\nQed.\n\nLemma divp0 p : p %/ 0 = 0.\nProof.\nby rewrite /divp unlock redivp_def /=; case: ifP; rewrite rdivp0 // scaler0.\nQed.\n\nLemma divp1 m : m %/ 1 = m.\nProof.\nby rewrite divpE lead_coefC unitr1 Ring.rdivp1 expr1n invr1 scale1r.\nQed.\n\nLemma modp0 p : p %% 0 = p.\nProof.\nrewrite /modp unlock redivp_def; case: ifP; rewrite rmodp0 //= lead_coef0.\nby rewrite unitr0.\nQed.\n\nLemma mod0p p : 0 %% p = 0.\nProof.\nby rewrite /modp unlock redivp_def /=; case: ifP; rewrite rmod0p // scaler0.\nQed.\n\nLemma modp1 p : p %% 1 = 0.\nProof.\nby rewrite /modp unlock redivp_def /=; case: ifP; rewrite rmodp1 // scaler0.\nQed.\n\nHint Resolve divp0 divp1 mod0p modp0 modp1 : core.\n\nLemma modp_small p q : size p < size q -> p %% q = p.\nProof.\nmove=> spq; rewrite /modp unlock redivp_def; case: ifP; rewrite rmodp_small //.\nby rewrite /= rscalp_small // expr0 /= invr1 scale1r.\nQed.\n\nLemma modpC p c : c != 0 -> p %% c%:P = 0.\nProof.\nmove=> cn0; rewrite /modp unlock redivp_def /=; case: ifP; rewrite ?rmodpC //.\nby rewrite scaler0.\nQed.\n\nLemma modp_mull p q : (p * q) %% q = 0.\nProof.\nhave [-> | nq0] := eqVneq q 0; first by rewrite modp0 mulr0.\nhave rlcq : GRing.rreg (lead_coef q) by apply/rregP; rewrite lead_coef_eq0.\nhave hC : GRing.comm q (lead_coef q)%:P by red; rewrite mulrC.\nby rewrite modpE; case: ifP => ulcq; rewrite RingComRreg.rmodp_mull // scaler0.\nQed.\n\nLemma modp_mulr d p : (d * p) %% d = 0. Proof. by rewrite mulrC modp_mull. Qed.\n\nLemma modpp d : d %% d = 0.\nProof. by rewrite -[d in d %% _]mul1r modp_mull. Qed.\n\nLemma ltn_modp p q : (size (p %% q) < size q) = (q != 0).\nProof.\nrewrite /modp unlock redivp_def /=; case: ifP=> ulcq; rewrite ?ltn_rmodp //=.\nrewrite size_scale ?ltn_rmodp // -exprVn expf_neq0 // invr_eq0.\nby case: eqP ulcq => // ->; rewrite unitr0.\nQed.\n\nLemma ltn_divpl d q p : d != 0 ->\n   (size (q %/ d) < size p) = (size q < size (p * d)).\nProof.\nmove=> dn0.\nhave: (lead_coef d) ^+ (scalp q d) != 0 by apply: lc_expn_scalp_neq0.\nmove/(size_scale q)<-; rewrite divp_eq; have [->|quo0] := eqVneq (q %/ d) 0.\n  rewrite mul0r add0r size_poly0 size_poly_gt0.\n  have [->|pn0] := eqVneq p 0; first by rewrite mul0r size_poly0 ltn0.\n  by rewrite size_mul // (polySpred pn0) addSn ltn_addl // ltn_modp.\nrewrite size_addl; last first.\n  by rewrite size_mul // (polySpred quo0) addSn /= ltn_addl // ltn_modp.\nhave [->|pn0] := eqVneq p 0; first by rewrite mul0r size_poly0 !ltn0.\nby rewrite !size_mul ?quo0 // (polySpred dn0) !addnS ltn_add2r.\nQed.\n\nLemma leq_divpr d p q : d != 0 ->\n   (size p <= size (q %/ d)) = (size (p * d) <= size q).\nProof. by move=> dn0; rewrite leqNgt ltn_divpl // -leqNgt. Qed.\n\nLemma divpN0 d p : d != 0 -> (p %/ d != 0) = (size d <= size p).\nProof.\nmove=> dn0.\nby rewrite -[d in RHS]mul1r -leq_divpr // size_polyC oner_eq0 size_poly_gt0.\nQed.\n\nLemma size_divp p q : q != 0 -> size (p %/ q) = (size p - (size q).-1)%N.\nProof.\nmove=> nq0; case: (leqP (size q) (size p)) => sqp; last first.\n  move: (sqp); rewrite -{1}(ltn_predK sqp) ltnS -subn_eq0 divp_small //.\n  by move/eqP->; rewrite size_poly0.\nhave np0 : p != 0.\n  by rewrite -size_poly_gt0; apply: leq_trans sqp; rewrite size_poly_gt0.\nhave /= := congr1 (size \\o @polyseq R) (divp_eq p q).\nrewrite size_scale; last by rewrite expf_eq0 lead_coef_eq0 (negPf nq0) andbF.\nhave [->|qq0] := eqVneq (p %/ q) 0.\n  by rewrite mul0r add0r=> es; move: nq0; rewrite -(ltn_modp p) -es ltnNge sqp.\nrewrite size_addl.\n  by move->; apply/eqP; rewrite size_mul // (polySpred nq0) addnS /= addnK.\nrewrite size_mul ?qq0 //.\nmove: nq0; rewrite -(ltn_modp p); move/leq_trans; apply.\nby rewrite (polySpred qq0) addSn /= leq_addl.\nQed.\n\nLemma ltn_modpN0 p q : q != 0 -> size (p %% q) < size q.\nProof. by rewrite ltn_modp. Qed.\n\nLemma modp_mod p q : (p %% q) %% q = p %% q.\nProof.\nby have [->|qn0] := eqVneq q 0; rewrite ?modp0 // modp_small ?ltn_modp.\nQed.\n\nLemma leq_modp m d : size (m %% d) <= size m.\nProof.\nrewrite /modp unlock redivp_def /=; case: ifP; rewrite ?leq_rmodp //.\nmove=> ud; rewrite size_scale ?leq_rmodp // invr_eq0 expf_neq0 //.\nby apply: contraTneq ud => ->; rewrite unitr0.\nQed.\n\nLemma dvdp0 d : d %| 0. Proof. by rewrite /dvdp mod0p. Qed.\n\nHint Resolve dvdp0 : core.\n\nLemma dvd0p p : (0 %| p) = (p == 0). Proof. by rewrite /dvdp modp0. Qed.\n\nLemma dvd0pP p : reflect (p = 0) (0 %| p).\nProof. by apply: (iffP idP); rewrite dvd0p; move/eqP. Qed.\n\nLemma dvdpN0 p q : p %| q -> q != 0 -> p != 0.\nProof. by move=> pq hq; apply: contraTneq pq => ->; rewrite dvd0p. Qed.\n\nLemma dvdp1 d : (d %| 1) = (size d == 1%N).\nProof.\nrewrite /dvdp modpE; case ud: (lead_coef d \\in GRing.unit); last exact: rdvdp1.\nrewrite -size_poly_eq0 size_scale; first by rewrite size_poly_eq0 -rdvdp1.\nby rewrite invr_eq0 expf_neq0 //; apply: contraTneq ud => ->; rewrite unitr0.\nQed.\n\nLemma dvd1p m : 1 %| m. Proof. by rewrite /dvdp modp1. Qed.\n\nLemma gtNdvdp p q : p != 0 -> size p < size q -> (q %| p) = false.\nProof.\nby move=> nn0 hs; rewrite /dvdp; rewrite (modp_small hs); apply: negPf.\nQed.\n\nLemma modp_eq0P p q : reflect (p %% q = 0) (q %| p).\nProof. exact: (iffP eqP). Qed.\n\nLemma modp_eq0 p q : (q %| p) -> p %% q = 0. Proof. exact: modp_eq0P. Qed.\n\nLemma leq_divpl d p q :\n  d %| p -> (size (p %/ d) <= size q) = (size p <= size (q * d)).\nProof.\ncase: (eqVneq d 0) => [-> /dvd0pP -> | nd0 hd].\n  by rewrite divp0 size_poly0 !leq0n.\nrewrite leq_eqVlt ltn_divpl // (leq_eqVlt (size p)).\ncase lhs: (size p < size (q * d)); rewrite ?orbT ?orbF //.\nhave: (lead_coef d) ^+ (scalp p d) != 0 by rewrite expf_neq0 // lead_coef_eq0.\nmove/(size_scale p)<-; rewrite divp_eq; move/modp_eq0P: hd->; rewrite addr0.\nhave [-> | quon0] := eqVneq (p %/ d) 0.\n  rewrite mul0r size_poly0 2!(eq_sym 0%N) !size_poly_eq0.\n  by rewrite mulf_eq0 (negPf nd0) orbF.\nhave [-> | nq0] := eqVneq q 0.\n  by rewrite mul0r size_poly0 !size_poly_eq0 mulf_eq0 (negPf nd0) orbF.\nby rewrite !size_mul // (polySpred nd0) !addnS /= eqn_add2r.\nQed.\n\nLemma dvdp_leq p q : q != 0 -> p %| q -> size p <= size q.\nProof.\nmove=> nq0 /modp_eq0P.\nby case: leqP => // /modp_small -> /eqP; rewrite (negPf nq0).\nQed.\n\nLemma eq_dvdp c quo q p : c != 0 -> c *: p = quo * q -> q %| p.\nProof.\nmove=> cn0; case: (eqVneq p 0) => [->|nz_quo def_quo] //.\npose p1 : {poly R} := lead_coef q ^+ scalp p q *: quo - c *: (p %/ q).\nhave E1: c *: (p %% q) = p1 * q.\n  rewrite mulrDl mulNr -scalerAl -def_quo scalerA mulrC -scalerA.\n  by rewrite -scalerAl -scalerBr divp_eq addrAC subrr add0r.\nrewrite /dvdp; apply/idPn=> m_nz.\nhave: p1 * q != 0 by rewrite -E1 -mul_polyC mulf_neq0 // polyC_eq0.\nrewrite mulf_eq0; case/norP=> p1_nz q_nz.\nhave := ltn_modp p q; rewrite q_nz -(size_scale (p %% q) cn0) E1.\nby rewrite size_mul // polySpred // ltnNge leq_addl.\nQed.\n\nLemma dvdpp d : d %| d. Proof. by rewrite /dvdp modpp. Qed.\n\nHint Resolve dvdpp : core.\n\nLemma divp_dvd p q : p %| q -> (q %/ p) %| q.\nProof.\nhave [-> | np0] := eqVneq p 0; first by rewrite divp0.\nrewrite dvdp_eq => /eqP h.\napply: (@eq_dvdp ((lead_coef p)^+ (scalp q p)) p); last by rewrite mulrC.\nby rewrite expf_neq0 // lead_coef_eq0.\nQed.\n\nLemma dvdp_mull m d n : d %| n -> d %| m * n.\nProof.\ncase: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite mulr0 dvdpp.\nrewrite dvdp_eq => /eqP e.\napply: (@eq_dvdp (lead_coef d ^+ scalp n d) (m * (n %/ d))).\n  by rewrite expf_neq0 // lead_coef_eq0.\nby rewrite scalerAr e mulrA.\nQed.\n\nLemma dvdp_mulr n d m : d %| m -> d %| m * n.\nProof. by move=> hdm; rewrite mulrC dvdp_mull. Qed.\n\nHint Resolve dvdp_mull dvdp_mulr : core.\n\nLemma dvdp_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\ncase: (eqVneq d1 0) => [-> /dvd0pP -> | d1n0]; first by rewrite !mul0r dvdpp.\ncase: (eqVneq d2 0) => [-> _ /dvd0pP -> | d2n0]; first by rewrite !mulr0.\nrewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Hq1.\nrewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Hq2.\napply: (@eq_dvdp (c1 * c2) (q1 * q2)).\n  by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0.\nrewrite -scalerA scalerAr scalerAl Hq1 Hq2 -!mulrA.\nby rewrite [d1 * (q2 * _)]mulrCA.\nQed.\n\nLemma dvdp_addr m d n : d %| m -> (d %| m + n) = (d %| n).\nProof.\ncase: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite add0r.\nrewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1.\napply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _.\n  have sn0 : c1 * c2 != 0.\n    by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF.\n  move/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 - c2 *: q1) _ _ sn0).\n  rewrite mulrDl -scaleNr -!scalerAl -Eq1 -Eq2 !scalerA.\n  by rewrite mulNr mulrC scaleNr -scalerBr addrC addKr.\nhave sn0 : c1 * c2 != 0.\n  by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF.\nmove/eqP=> Eq2; apply: (@eq_dvdp _ (c1 *: q2 + c2 *: q1) _ _ sn0).\nby rewrite mulrDl -!scalerAl -Eq1 -Eq2 !scalerA mulrC addrC scalerDr.\nQed.\n\nLemma dvdp_addl n d m : d %| n -> (d %| m + n) = (d %| m).\nProof. by rewrite addrC; apply: dvdp_addr. Qed.\n\nLemma dvdp_add d m n : d %| m -> d %| n -> d %| m + n.\nProof. by move/dvdp_addr->. Qed.\n\nLemma dvdp_add_eq d m n : d %| m + n -> (d %| m) = (d %| n).\nProof. by move=> ?; apply/idP/idP; [move/dvdp_addr <-| move/dvdp_addl <-]. Qed.\n\nLemma dvdp_subr d m n : d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> ?; apply: dvdp_add_eq; rewrite -addrA addNr simp. Qed.\n\nLemma dvdp_subl d m n : d %| n -> (d %| m - n) = (d %| m).\nProof. by move/dvdp_addl<-; rewrite subrK. Qed.\n\nLemma dvdp_sub d m n : d %| m -> d %| n -> d %| m - n.\nProof. by move=> *; rewrite dvdp_subl. Qed.\n\nLemma dvdp_mod d n m : d %| n -> (d %| m) = (d %| m %% n).\nProof.\nhave [-> | nn0] := eqVneq n 0; first by rewrite modp0.\ncase: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite modp0.\nrewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Eq1.\napply/idP/idP; rewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _.\n  have sn0 : c1 * c2 != 0.\n   by rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 (negPf dn0) andbF.\n  pose quo := (c1 * lead_coef n ^+ scalp m n) *: q2 - c2 *: (m %/ n) * q1.\n  move/eqP=> Eq2; apply: (@eq_dvdp _ quo _ _ sn0).\n  rewrite mulrDl mulNr -!scalerAl -!mulrA -Eq1 -Eq2 -scalerAr !scalerA.\n  rewrite mulrC [_ * c2]mulrC mulrA -[((_ * _) * _) *: _]scalerA -scalerBr.\n  by rewrite divp_eq addrC addKr.\nhave sn0 : c1 * c2 * lead_coef n ^+ scalp m n != 0.\n  rewrite !mulf_neq0 // expf_eq0 lead_coef_eq0 ?(negPf dn0) ?andbF //.\n  by rewrite (negPf nn0) andbF.\nmove/eqP=> Eq2; apply: (@eq_dvdp _ (c2 *: (m %/ n) * q1 + c1 *: q2) _ _ sn0).\nrewrite -scalerA divp_eq scalerDr -!scalerA Eq2 scalerAl scalerAr Eq1.\nby rewrite scalerAl mulrDl mulrA.\nQed.\n\nLemma dvdp_trans : transitive (@dvdp R).\nProof.\nmove=> n d m.\ncase: (eqVneq d 0) => [-> /dvd0pP -> // | dn0].\ncase: (eqVneq n 0) => [-> _ /dvd0pP -> // | nn0].\nrewrite dvdp_eq; set c1 := _ ^+ _; set q1 := _ %/ _; move/eqP=> Hq1.\nrewrite dvdp_eq; set c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> Hq2.\nhave sn0 : c1 * c2 != 0 by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0.\nby apply: (@eq_dvdp _ (q2 * q1) _ _ sn0); rewrite -scalerA Hq2 scalerAr Hq1 mulrA.\nQed.\n\nLemma dvdp_mulIl p q : p %| p * q. Proof. exact/dvdp_mulr/dvdpp. Qed.\n\nLemma dvdp_mulIr p q : q %| p * q. Proof. exact/dvdp_mull/dvdpp. Qed.\n\nLemma dvdp_mul2r r p q : r != 0 -> (p * r %| q * r) = (p %| q).\nProof.\nmove=> nzr.\nhave [-> | pn0] := eqVneq p 0.\n  by rewrite mul0r !dvd0p mulf_eq0 (negPf nzr) orbF.\nhave [-> | qn0] := eqVneq q 0; first by rewrite mul0r !dvdp0.\napply/idP/idP; last by move=> ?; rewrite dvdp_mul ?dvdpp.\nrewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> Hx.\napply: (@eq_dvdp c x); first by rewrite expf_neq0 // lead_coef_eq0 mulf_neq0.\nby apply: (mulIf nzr); rewrite -mulrA -scalerAl.\nQed.\n\nLemma dvdp_mul2l r p q: r != 0 -> (r * p %| r * q) = (p %| q).\nProof. by rewrite ![r * _]mulrC; apply: dvdp_mul2r. Qed.\n\nLemma ltn_divpr d p q :\n  d %| q -> (size p < size (q %/ d)) = (size (p * d) < size q).\nProof. by move=> dv_d_q; rewrite !ltnNge leq_divpl. Qed.\n\nLemma dvdp_exp d k p : 0 < k -> d %| p -> d %| (p ^+ k).\nProof. by case: k => // k _ d_dv_m; rewrite exprS dvdp_mulr. Qed.\n\nLemma dvdp_exp2l d k l : k <= l -> d ^+ k %| d ^+ l.\nProof. by move/subnK <-; rewrite exprD dvdp_mull // ?lead_coef_exp ?unitrX. Qed.\n\nLemma dvdp_Pexp2l d k l : 1 < size d -> (d ^+ k %| d ^+ l) = (k <= l).\nProof.\nmove=> sd; case: leqP => [|gt_n_m]; first exact: dvdp_exp2l.\nhave dn0 : d != 0 by rewrite -size_poly_gt0; apply: ltn_trans sd.\nrewrite gtNdvdp ?expf_neq0 // polySpred ?expf_neq0 // size_exp /=.\nrewrite [size (d ^+ k)]polySpred ?expf_neq0 // size_exp ltnS ltn_mul2l.\nby move: sd; rewrite -subn_gt0 subn1; move->.\nQed.\n\nLemma dvdp_exp2r p q k : p %| q -> p ^+ k %| q ^+ k.\nProof.\ncase: (eqVneq p 0) => [-> /dvd0pP -> // | pn0].\nrewrite dvdp_eq; set c := _ ^+ _; set t := _ %/ _; move/eqP=> e.\napply: (@eq_dvdp (c ^+ k) (t ^+ k)); first by rewrite !expf_neq0 ?lead_coef_eq0.\nby rewrite -exprMn -exprZn; congr (_ ^+ k).\nQed.\n\nLemma dvdp_exp_sub p q k l: p != 0 ->\n  (p ^+ k %| q * p ^+ l) = (p ^+ (k - l) %| q).\nProof.\nmove=> pn0; case: (leqP k l)=> [|/ltnW] hkl.\n  move: (hkl); rewrite -subn_eq0; move/eqP->; rewrite expr0 dvd1p.\n  exact/dvdp_mull/dvdp_exp2l.\nby rewrite -[in LHS](subnK hkl) exprD dvdp_mul2r // expf_eq0 (negPf pn0) andbF.\nQed.\n\nLemma dvdp_XsubCl p x : ('X - x%:P) %| p = root p x.\nProof. by rewrite dvdpE; apply: Ring.rdvdp_XsubCl. Qed.\n\nLemma polyXsubCP p x : reflect (p.[x] = 0) (('X - x%:P) %| p).\nProof. by rewrite dvdpE; apply: Ring.polyXsubCP. Qed.\n\nLemma eqp_div_XsubC p c :\n  (p == (p %/ ('X - c%:P)) * ('X - c%:P)) = ('X - c%:P %| p).\nProof. by rewrite dvdp_eq lead_coefXsubC expr1n scale1r. Qed.\n\nLemma root_factor_theorem p x : root p x = (('X - x%:P) %| p).\nProof. by rewrite dvdp_XsubCl. Qed.\n\nLemma uniq_roots_dvdp p rs : all (root p) rs -> uniq_roots rs ->\n  (\\prod_(z <- rs) ('X - z%:P)) %| p.\nProof.\nmove=> rrs; case/(uniq_roots_prod_XsubC rrs)=> q ->.\nby apply: dvdp_mull; rewrite // (eqP (monic_prod_XsubC _)) unitr1.\nQed.\n\nLemma root_bigmul x (ps : seq {poly R}) :\n  ~~root (\\big[*%R/1]_(p <- ps) p) x = all (fun p => ~~ root p x) ps.\nProof.\nelim: ps => [|p ps ihp]; first by rewrite big_nil root1.\nby rewrite big_cons /= rootM negb_or ihp.\nQed.\n\nLemma eqpP m n :\n  reflect (exists2 c12, (c12.1 != 0) && (c12.2 != 0) & c12.1 *: m = c12.2 *: n)\n          (m %= n).\nProof.\napply: (iffP idP) => [| [[c1 c2]/andP[nz_c1 nz_c2 eq_cmn]]]; last first.\n  rewrite /eqp (@eq_dvdp c2 c1%:P) -?eq_cmn ?mul_polyC // (@eq_dvdp c1 c2%:P) //.\n  by rewrite eq_cmn mul_polyC.\ncase: (eqVneq m 0) => [-> /andP [/dvd0pP -> _] | m_nz].\n  by exists (1, 1); rewrite ?scaler0 // oner_eq0.\ncase: (eqVneq n 0) => [-> /andP [_ /dvd0pP ->] | n_nz /andP []].\n  by exists (1, 1); rewrite ?scaler0 // oner_eq0.\nrewrite !dvdp_eq; set c1 := _ ^+ _; set c2 := _ ^+ _.\nset q1 := _ %/ _; set q2 := _ %/ _; move/eqP => Hq1 /eqP Hq2;\nhave Hc1 : c1 != 0 by rewrite expf_eq0 lead_coef_eq0 negb_and m_nz orbT.\nhave Hc2 : c2 != 0 by rewrite expf_eq0 lead_coef_eq0 negb_and n_nz orbT.\nhave def_q12: q1 * q2 = (c1 * c2)%:P.\n  apply: (mulIf m_nz); rewrite mulrAC mulrC -Hq1 -scalerAr -Hq2 scalerA.\n  by rewrite -mul_polyC.\nhave: q1 * q2 != 0 by rewrite def_q12 -size_poly_eq0 size_polyC mulf_neq0.\nrewrite mulf_eq0; case/norP=> nz_q1 nz_q2.\nhave: size q2 <= 1%N.\n  have:= size_mul nz_q1 nz_q2; rewrite def_q12 size_polyC mulf_neq0 //=.\n  by rewrite polySpred // => ->; rewrite leq_addl.\nrewrite leq_eqVlt ltnS size_poly_leq0 (negPf nz_q2) orbF.\ncase/size_poly1P=> c cn0 cqe; exists (c2, c); first by rewrite Hc2.\nby rewrite Hq2 -mul_polyC -cqe.\nQed.\n\nLemma eqp_eq p q: p %= q -> (lead_coef q) *: p = (lead_coef p) *: q.\nProof.\nmove=> /eqpP [[c1 c2] /= /andP [nz_c1 nz_c2]] eq.\nhave/(congr1 lead_coef) := eq; rewrite !lead_coefZ.\nmove=> eqC; apply/(@mulfI _ c2%:P); rewrite ?polyC_eq0 //.\nby rewrite !mul_polyC scalerA -eqC mulrC -scalerA eq !scalerA mulrC.\nQed.\n\nLemma eqpxx : reflexive (@eqp R). Proof. by move=> p; rewrite /eqp dvdpp. Qed.\n\nHint Resolve eqpxx : core.\n\nLemma eqp_sym : symmetric (@eqp R).\nProof. by move=> p q; rewrite /eqp andbC. Qed.\n\nLemma eqp_trans : transitive (@eqp R).\nProof.\nmove=> p q r; case/andP=> Dp pD; case/andP=> Dq qD.\nby rewrite /eqp (dvdp_trans Dp) // (dvdp_trans qD).\nQed.\n\nLemma eqp_ltrans : left_transitive (@eqp R).\nProof. exact: sym_left_transitive eqp_sym eqp_trans. Qed.\n\nLemma eqp_rtrans : right_transitive (@eqp R).\nProof. exact: sym_right_transitive eqp_sym eqp_trans. Qed.\n\nLemma eqp0 p : (p %= 0) = (p == 0).\nProof. by apply/idP/eqP => [/andP [_ /dvd0pP] | -> //]. Qed.\n\nLemma eqp01 : 0 %= (1 : {poly R}) = false.\nProof. by rewrite eqp_sym eqp0 oner_eq0. Qed.\n\nLemma eqp_scale p c : c != 0 -> c *: p %= p.\nProof.\nmove=> c0; apply/eqpP; exists (1, c); first by rewrite c0 oner_eq0.\nby rewrite scale1r.\nQed.\n\nLemma eqp_size p q : p %= q -> size p = size q.\nProof.\nhave [->|Eq] := eqVneq q 0; first by rewrite eqp0; move/eqP->.\nrewrite eqp_sym; have [->|Ep] := eqVneq p 0; first by rewrite eqp0; move/eqP->.\nby case/andP => Dp Dq; apply: anti_leq; rewrite !dvdp_leq.\nQed.\n\nLemma size_poly_eq1 p : (size p == 1%N) = (p %= 1).\nProof.\napply/size_poly1P/idP=> [[c cn0 ep] |].\n  by apply/eqpP; exists (1, c); rewrite ?oner_eq0 // alg_polyC scale1r.\nby move/eqp_size; rewrite size_poly1; move/eqP/size_poly1P.\nQed.\n\nLemma polyXsubC_eqp1 (x : R) : ('X - x%:P %= 1) = false.\nProof. by rewrite -size_poly_eq1 size_XsubC. Qed.\n\nLemma dvdp_eqp1 p q : p %| q -> q %= 1 -> p %= 1.\nProof.\nmove=> dpq hq.\nhave sizeq : size q == 1%N by rewrite size_poly_eq1.\nhave n0q : q != 0 by case: eqP hq => // ->; rewrite eqp01.\nrewrite -size_poly_eq1 eqn_leq -{1}(eqP sizeq) dvdp_leq //= size_poly_gt0.\nby apply/eqP => p0; move: dpq n0q; rewrite p0 dvd0p => ->.\nQed.\n\nLemma eqp_dvdr q p d: p %= q -> d %| p = (d %| q).\nProof.\nsuff Hmn m n: m %= n -> (d %| m) -> (d %| n).\n  by move=> mn; apply/idP/idP; apply: Hmn=> //; rewrite eqp_sym.\nby rewrite /eqp; case/andP=> pq qp dp; apply: (dvdp_trans dp).\nQed.\n\nLemma eqp_dvdl d2 d1 p : d1 %= d2 -> d1 %| p = (d2 %| p).\nsuff Hmn m n: m %= n -> (m %| p) -> (n %| p).\n  by move=> ?; apply/idP/idP; apply: Hmn; rewrite // eqp_sym.\nby rewrite /eqp; case/andP=> dd' d'd dp; apply: (dvdp_trans d'd).\nQed.\n\nLemma dvdpZr c m n : c != 0 -> m %| c *: n = (m %| n).\nProof. by move=> cn0; exact/eqp_dvdr/eqp_scale. Qed.\n\nLemma dvdpZl c m n : c != 0 -> (c *: m %| n) = (m %| n).\nProof. by move=> cn0; exact/eqp_dvdl/eqp_scale. Qed.\n\nLemma dvdpNl d p : (- d) %| p = (d %| p).\nProof.\nby rewrite -scaleN1r; apply/eqp_dvdl/eqp_scale; rewrite oppr_eq0 oner_neq0.\nQed.\n\nLemma dvdpNr d p : d %| (- p) = (d %| p).\nProof. by apply: eqp_dvdr; rewrite -scaleN1r eqp_scale ?oppr_eq0 ?oner_eq0. Qed.\n\nLemma eqp_mul2r r p q : r != 0 -> (p * r %= q * r) = (p %= q).\nProof. by move=> nz_r; rewrite /eqp !dvdp_mul2r. Qed.\n\nLemma eqp_mul2l r p q: r != 0 -> (r * p %= r * q) = (p %= q).\nProof. by move=> nz_r; rewrite /eqp !dvdp_mul2l. Qed.\n\nLemma eqp_mull r p q: q %= r -> p * q %= p * r.\nProof.\ncase/eqpP=> [[c d]] /andP [c0 d0 e]; apply/eqpP; exists (c, d); rewrite ?c0 //.\nby rewrite scalerAr e -scalerAr.\nQed.\n\nLemma eqp_mulr q p r : p %= q -> p * r %= q * r.\nProof. by move=> epq; rewrite ![_ * r]mulrC eqp_mull. Qed.\n\nLemma eqp_exp p q k : p %= q -> p ^+ k %= q ^+ k.\nProof.\nmove=> pq; elim: k=> [|k ihk]; first by rewrite !expr0 eqpxx.\nby rewrite !exprS (@eqp_trans (q * p ^+ k)) // (eqp_mulr, eqp_mull).\nQed.\n\nLemma polyC_eqp1 (c : R) : (c%:P %= 1) = (c != 0).\nProof.\napply/eqpP/idP => [[[x y]] |nc0] /=.\n  case: (eqVneq c) => [->|] //= /andP [_] /negPf <- /eqP.\n  by rewrite alg_polyC scaler0 eq_sym polyC_eq0.\nexists (1, c); first by rewrite nc0 /= oner_neq0.\nby rewrite alg_polyC scale1r.\nQed.\n\nLemma dvdUp d p: d %= 1 -> d %| p.\nProof. by move/eqp_dvdl->; rewrite dvd1p. Qed.\n\nLemma dvdp_size_eqp p q : p %| q -> size p == size q = (p %= q).\nProof.\nmove=> pq; apply/idP/idP; last by move/eqp_size->.\nhave [->|Hq] := eqVneq q 0; first by rewrite size_poly0 size_poly_eq0 eqp0.\nhave [->|Hp] := eqVneq p 0.\n  by rewrite size_poly0 eq_sym size_poly_eq0 eqp_sym eqp0.\nmove: pq; rewrite dvdp_eq; set c := _ ^+ _; set x := _ %/ _; move/eqP=> eqpq.\nhave /= := congr1 (size \\o @polyseq R) eqpq.\nhave cn0 : c != 0 by rewrite expf_neq0 // lead_coef_eq0.\nrewrite (@eqp_size _ q); last exact: eqp_scale.\nrewrite size_mul ?p0 // => [-> HH|]; last first.\n  apply/eqP=> HH; move: eqpq; rewrite HH mul0r.\n  by move/eqP; rewrite scale_poly_eq0 (negPf Hq) (negPf cn0).\nsuff: size x == 1%N.\n  case/size_poly1P=> y H1y H2y.\n  by apply/eqpP; exists (y, c); rewrite ?H1y // eqpq H2y mul_polyC.\ncase: (size p) HH (size_poly_eq0 p)=> [|n]; first by case: eqP Hp.\nby rewrite addnS -add1n eqn_add2r; move/eqP->.\nQed.\n\nLemma eqp_root p q : p %= q -> root p =1 root q.\nProof.\nmove/eqpP=> [[c d]] /andP [c0 d0 e] x; move/negPf:c0=>c0; move/negPf:d0=>d0.\nby rewrite rootE -[_==_]orFb -c0 -mulf_eq0 -hornerZ e hornerZ mulf_eq0 d0.\nQed.\n\nLemma eqp_rmod_mod p q : rmodp p q %= modp p q.\nProof.\nrewrite modpE eqp_sym; case: ifP => ulcq //.\napply: eqp_scale; rewrite invr_eq0 //.\nby apply: expf_neq0; apply: contraTneq ulcq => ->; rewrite unitr0.\nQed.\n\nLemma eqp_rdiv_div p q : rdivp p q %= divp p q.\nProof.\nrewrite divpE eqp_sym; case: ifP=> ulcq //; apply: eqp_scale; rewrite invr_eq0 //.\nby apply: expf_neq0; apply: contraTneq ulcq => ->; rewrite unitr0.\nQed.\n\nLemma dvd_eqp_divl d p q (dvd_dp : d %| q) (eq_pq : p %= q) :\n  p %/ d %= q %/ d.\nProof.\ncase: (eqVneq q 0) eq_pq=> [->|q_neq0]; first by rewrite eqp0=> /eqP->.\nhave d_neq0: d != 0 by apply: contraTneq dvd_dp=> ->; rewrite dvd0p.\nmove=> eq_pq; rewrite -(@eqp_mul2r d) // !divpK // ?(eqp_dvdr _ eq_pq) //.\nrewrite (eqp_ltrans (eqp_scale _ _)) ?lc_expn_scalp_neq0 //.\nby rewrite (eqp_rtrans (eqp_scale _ _)) ?lc_expn_scalp_neq0.\nQed.\n\nDefinition gcdp_rec p q :=\n  let: (p1, q1) := if size p < size q then (q, p) else (p, q) in\n  if p1 == 0 then q1 else\n  let fix loop (n : nat) (pp qq : {poly R}) {struct n} :=\n      let rr := modp pp qq in\n      if rr == 0 then qq else\n      if n is n1.+1 then loop n1 qq rr else rr in\n  loop (size p1) p1 q1.\n\nDefinition gcdp := nosimpl gcdp_rec.\n\nLemma gcd0p : left_id 0 gcdp.\nProof.\nmove=> p; rewrite /gcdp /gcdp_rec size_poly0 size_poly_gt0 if_neg.\ncase: ifP => /= [_ | nzp]; first by rewrite eqxx.\nby rewrite polySpred !(modp0, nzp) //; case: _.-1 => [|m]; rewrite mod0p eqxx.\nQed.\n\nLemma gcdp0 : right_id 0 gcdp.\nProof.\nmove=> p; have:= gcd0p p; rewrite /gcdp /gcdp_rec size_poly0 size_poly_gt0.\nby case: eqVneq => //= ->; rewrite eqxx.\nQed.\n\nLemma gcdpE p q :\n  gcdp p q = if size p < size q\n    then gcdp (modp q p) p else gcdp (modp p q) q.\nProof.\npose gcdpE_rec := fix gcdpE_rec (n : nat) (pp qq : {poly R}) {struct n} :=\n   let rr := modp pp qq in\n   if rr == 0 then qq else\n   if n is n1.+1 then gcdpE_rec n1 qq rr else rr.\nhave Irec: forall k l p q, size q <= k -> size q <= l\n      -> size q < size p -> gcdpE_rec k p q = gcdpE_rec l p q.\n+ elim=> [|m Hrec] [|n] //= p1 q1.\n  - move/size_poly_leq0P=> -> _; rewrite size_poly0 size_poly_gt0 modp0.\n    by move/negPf ->; case: n => [|n] /=; rewrite mod0p eqxx.\n  - move=> _ /size_poly_leq0P ->; rewrite size_poly0 size_poly_gt0 modp0.\n    by move/negPf ->; case: m {Hrec} => [|m] /=; rewrite mod0p eqxx.\n  case: eqP => Epq Sm Sn Sq //; have [->|nzq] := eqVneq q1 0.\n    by case: n m {Sm Sn Hrec} => [|m] [|n] //=; rewrite mod0p eqxx.\n  apply: Hrec; last by rewrite ltn_modp.\n    by rewrite -ltnS (leq_trans _ Sm) // ltn_modp.\n  by rewrite -ltnS (leq_trans _ Sn) // ltn_modp.\nhave [->|nzp] := eqVneq p 0; first by rewrite mod0p modp0 gcd0p gcdp0 if_same.\nhave [->|nzq] := eqVneq q 0; first by rewrite mod0p modp0 gcd0p gcdp0 if_same.\nrewrite /gcdp /gcdp_rec !ltn_modp !(negPf nzp, negPf nzq) /=.\nhave [ltpq|leqp] := ltnP; rewrite !(negPf nzp, negPf nzq) /= polySpred //.\n  have [->|nzqp] := eqVneq.\n    by case: (size p) => [|[|s]]; rewrite /= modp0 (negPf nzp) // mod0p eqxx.\n  apply: Irec => //; last by rewrite ltn_modp.\n    by rewrite -ltnS -polySpred // (leq_trans _ ltpq) ?leqW // ltn_modp.\n  by rewrite ltnW // ltn_modp.\ncase: eqVneq => [->|nzpq].\n  by case: (size q) => [|[|s]]; rewrite /= modp0 (negPf nzq) // mod0p eqxx.\napply: Irec => //; rewrite ?ltn_modp //.\n  by rewrite -ltnS -polySpred // (leq_trans _ leqp) // ltn_modp.\nby rewrite ltnW // ltn_modp.\nQed.\n\nLemma size_gcd1p p : size (gcdp 1 p) = 1%N.\nProof.\nrewrite gcdpE size_polyC oner_eq0 /= modp1; have [|/size1_polyC ->] := ltnP.\n  by rewrite gcd0p size_polyC oner_eq0.\nhave [->|p00] := eqVneq p`_0 0; first by rewrite modp0 gcdp0 size_poly1.\nby rewrite modpC // gcd0p size_polyC p00.\nQed.\n\nLemma size_gcdp1 p : size (gcdp p 1) = 1%N.\nProof.\nrewrite gcdpE size_polyC oner_eq0 /= modp1 ltnS; case: leqP.\n  by move/size_poly_leq0P->; rewrite gcdp0 modp0 size_polyC oner_eq0.\nby rewrite gcd0p size_polyC oner_eq0.\nQed.\n\nLemma gcdpp : idempotent gcdp.\nProof. by move=> p; rewrite gcdpE ltnn modpp gcd0p. Qed.\n\nLemma dvdp_gcdlr p q : (gcdp p q %| p) && (gcdp p q %| q).\nProof.\nhave [r] := ubnP (minn (size q) (size p)); elim: r => // r IHr in p q *.\nhave [-> | nz_p] := eqVneq p 0; first by rewrite gcd0p dvdpp andbT.\nhave [-> | nz_q] := eqVneq q 0; first by rewrite gcdp0 dvdpp /=.\nrewrite ltnS gcdpE; case: leqP => [le_pq | lt_pq] le_qr.\n  suffices /IHr/andP[E1 E2]: minn (size q) (size (p %% q)) < r.\n    by rewrite E2 andbT (dvdp_mod _ E2).\n  by rewrite gtn_min orbC (leq_trans _ le_qr) ?ltn_modp.\nsuffices /IHr/andP[E1 E2]: minn (size p) (size (q %% p)) < r.\n  by rewrite E2 (dvdp_mod _ E2).\nby rewrite gtn_min orbC (leq_trans _ le_qr) ?ltn_modp.\nQed.\n\nLemma dvdp_gcdl p q : gcdp p q %| p. Proof. by case/andP: (dvdp_gcdlr p q). Qed.\n\nLemma dvdp_gcdr p q :gcdp p q %| q. Proof. by case/andP: (dvdp_gcdlr p q). Qed.\n\nLemma leq_gcdpl p q : p != 0 -> size (gcdp p q) <= size p.\nProof. by move=> pn0; move: (dvdp_gcdl p q); apply: dvdp_leq. Qed.\n\nLemma leq_gcdpr p q : q != 0 -> size (gcdp p q) <= size q.\nProof. by move=> qn0; move: (dvdp_gcdr p q); apply: dvdp_leq. Qed.\n\nLemma dvdp_gcd p m n : p %| gcdp m n = (p %| m) && (p %| n).\nProof.\napply/idP/andP=> [dv_pmn | []].\n  by rewrite ?(dvdp_trans dv_pmn) ?dvdp_gcdl ?dvdp_gcdr.\nhave [r] := ubnP (minn (size n) (size m)); elim: r => // r IHr in m n *.\nhave [-> | nz_m] := eqVneq m 0; first by rewrite gcd0p.\nhave [-> | nz_n] := eqVneq n 0; first by rewrite gcdp0.\nrewrite gcdpE ltnS; case: leqP => [le_nm | lt_mn] le_r dv_m dv_n.\n  apply: IHr => //; last by rewrite -(dvdp_mod _ dv_n).\n  by rewrite gtn_min orbC (leq_trans _ le_r) ?ltn_modp.\napply: IHr => //; last by rewrite -(dvdp_mod _ dv_m).\nby rewrite gtn_min orbC (leq_trans _ le_r) ?ltn_modp.\nQed.\n\nLemma gcdpC p q : gcdp p q %= gcdp q p.\nProof. by rewrite /eqp !dvdp_gcd !dvdp_gcdl !dvdp_gcdr. Qed.\n\nLemma gcd1p p : gcdp 1 p %= 1.\nProof.\nrewrite -size_poly_eq1 gcdpE size_poly1; case: ltnP.\n  by rewrite modp1 gcd0p size_poly1 eqxx.\nmove/size1_polyC=> e; rewrite e.\nhave [->|p00] := eqVneq p`_0 0; first by rewrite modp0 gcdp0 size_poly1.\nby rewrite modpC // gcd0p size_polyC p00.\nQed.\n\nLemma gcdp1 p : gcdp p 1 %= 1.\nProof. by rewrite (eqp_ltrans (gcdpC _ _)) gcd1p. Qed.\n\nLemma gcdp_addl_mul p q r: gcdp r (p * r + q) %= gcdp r q.\nProof.\nsuff h m n d : gcdp d n %| gcdp d (m * d + n).\n  apply/andP; split => //.\n  by rewrite {2}(_: q = (-p) * r + (p * r + q)) ?H // mulNr addKr.\nby rewrite dvdp_gcd dvdp_gcdl /= dvdp_addr ?dvdp_gcdr ?dvdp_mull ?dvdp_gcdl.\nQed.\n\nLemma gcdp_addl m n : gcdp m (m + n) %= gcdp m n.\nProof. by rewrite -[m in m + _]mul1r gcdp_addl_mul. Qed.\n\nLemma gcdp_addr m n : gcdp m (n + m) %= gcdp m n.\nProof. by rewrite addrC gcdp_addl. Qed.\n\nLemma gcdp_mull m n : gcdp n (m * n) %= n.\nProof.\nhave [-> | nn0] := eqVneq n 0; first by rewrite gcd0p mulr0 eqpxx.\nhave [-> | mn0] := eqVneq m 0; first by rewrite mul0r gcdp0 eqpxx.\nrewrite gcdpE modp_mull gcd0p size_mul //; case: leqP; last by rewrite eqpxx.\nrewrite (polySpred mn0) addSn /= -[leqRHS]add0n leq_add2r -ltnS.\nrewrite -polySpred //= leq_eqVlt ltnS size_poly_leq0 (negPf mn0) orbF.\ncase/size_poly1P=> c cn0 -> {mn0 m}; rewrite mul_polyC.\nsuff -> : n %% (c *: n) = 0 by rewrite gcd0p; apply: eqp_scale.\nby apply/modp_eq0P; rewrite dvdpZl.\nQed.\n\nLemma gcdp_mulr m n : gcdp n (n * m) %= n.\nProof. by rewrite mulrC gcdp_mull. Qed.\n\nLemma gcdp_scalel c m n : c != 0 -> gcdp (c *: m) n %= gcdp m n.\nProof.\nmove=> cn0; rewrite /eqp dvdp_gcd [gcdp m n %| _]dvdp_gcd !dvdp_gcdr !andbT.\napply/andP; split; last first.\n  by apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdpZr.\nby apply: dvdp_trans (dvdp_gcdl _ _) _; rewrite dvdpZl.\nQed.\n\nLemma gcdp_scaler c m n : c != 0 -> gcdp m (c *: n) %= gcdp m n.\nProof.\nmove=> cn0; apply: eqp_trans (gcdpC _ _) _.\nby apply: eqp_trans (gcdp_scalel _ _ _) _ => //; apply: gcdpC.\nQed.\n\nLemma dvdp_gcd_idl m n : m %| n -> gcdp m n %= m.\nProof.\nhave [-> | mn0] := eqVneq m 0.\n  by rewrite dvd0p => /eqP ->; rewrite gcdp0 eqpxx.\nrewrite dvdp_eq; move/eqP/(f_equal (gcdp m)) => h.\napply: eqp_trans (gcdp_mull (n %/ m) _).\nby rewrite -h eqp_sym gcdp_scaler // expf_neq0 // lead_coef_eq0.\nQed.\n\nLemma dvdp_gcd_idr m n : n %| m -> gcdp m n %= n.\nProof. by move/dvdp_gcd_idl; exact/eqp_trans/gcdpC. Qed.\n\nLemma gcdp_exp p k l : gcdp (p ^+ k) (p ^+ l) %= p ^+ minn k l.\nProof.\ncase: leqP => [|/ltnW] /subnK <-; rewrite exprD; first exact: gcdp_mull.\nexact/(eqp_trans (gcdpC _ _))/gcdp_mull.\nQed.\n\nLemma gcdp_eq0 p q : gcdp p q == 0 = (p == 0) && (q == 0).\nProof.\napply/idP/idP; last by case/andP => /eqP -> /eqP ->; rewrite gcdp0.\nhave h m n: gcdp m n == 0 -> (m == 0).\n  by rewrite -(dvd0p m); move/eqP<-; rewrite dvdp_gcdl.\nby move=> ?; rewrite (h _ q) // (h _ p) // -eqp0 (eqp_ltrans (gcdpC _ _)) eqp0.\nQed.\n\nLemma eqp_gcdr p q r : q %= r -> gcdp p q %= gcdp p r.\nProof.\nmove=> eqr; rewrite /eqp !(dvdp_gcd, dvdp_gcdl, andbT) /=.\nby rewrite -(eqp_dvdr _ eqr) dvdp_gcdr (eqp_dvdr _ eqr) dvdp_gcdr.\nQed.\n\nLemma eqp_gcdl r p q : p %= q -> gcdp p r %= gcdp q r.\nProof.\nmove=> eqr; rewrite /eqp !(dvdp_gcd, dvdp_gcdr, andbT) /=.\nby rewrite -(eqp_dvdr _ eqr) dvdp_gcdl (eqp_dvdr _ eqr) dvdp_gcdl.\nQed.\n\nLemma eqp_gcd p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> gcdp p1 q1 %= gcdp p2 q2.\nProof. move=> e1 e2; exact: eqp_trans (eqp_gcdr _ e2) (eqp_gcdl _ e1). Qed.\n\nLemma eqp_rgcd_gcd p q : rgcdp p q %= gcdp p q.\nProof.\nmove: {2}(minn (size p) (size q)) (leqnn (minn (size p) (size q))) => n.\nelim: n p q => [p q|n ihn p q hs].\n  rewrite leqn0; case: ltnP => _; rewrite size_poly_eq0; move/eqP->.\n    by rewrite gcd0p rgcd0p eqpxx.\n  by rewrite gcdp0 rgcdp0 eqpxx.\nhave [-> | pn0] := eqVneq p 0; first by rewrite gcd0p rgcd0p eqpxx.\nhave [-> | qn0] := eqVneq q 0; first by rewrite gcdp0 rgcdp0 eqpxx.\nrewrite gcdpE rgcdpE; case: ltnP hs => sp hs.\n  have e := eqp_rmod_mod q p; apply/eqp_trans/ihn: (eqp_gcdl p e).\n  by rewrite (eqp_size e) geq_min -ltnS (leq_trans _ hs) ?ltn_modp.\nhave e := eqp_rmod_mod p q; apply/eqp_trans/ihn: (eqp_gcdl q e).\nby rewrite (eqp_size e) geq_min -ltnS (leq_trans _ hs) ?ltn_modp.\nQed.\n\nLemma gcdp_modl m n : gcdp (m %% n) n %= gcdp m n.\nProof.\nhave [/modp_small -> // | lenm] := ltnP (size m) (size n).\nby rewrite (gcdpE m n) ltnNge lenm.\nQed.\n\nLemma gcdp_modr m n : gcdp m (n %% m) %= gcdp m n.\nProof.\napply: eqp_trans (gcdpC _ _); apply: eqp_trans (gcdp_modl _ _); exact: gcdpC.\nQed.\n\nLemma gcdp_def d m n :\n    d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) ->\n  gcdp m n %= d.\nProof.\nmove=> dm dn h; rewrite /eqp dvdp_gcd dm dn !andbT.\nby apply: h; [apply: dvdp_gcdl | apply: dvdp_gcdr].\nQed.\n\nDefinition coprimep p q := size (gcdp p q) == 1%N.\n\nLemma coprimep_size_gcd p q : coprimep p q -> size (gcdp p q) = 1%N.\nProof. by rewrite /coprimep=> /eqP. Qed.\n\nLemma coprimep_def p q : coprimep p q = (size (gcdp p q) == 1%N).\nProof. done. Qed.\n\nLemma coprimepZl c m n : c != 0 -> coprimep (c *: m) n = coprimep m n.\nProof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scalel _ _ _)). Qed.\n\nLemma coprimepZr c m n: c != 0 -> coprimep m (c *: n) = coprimep m n.\nProof. by move=> ?; rewrite !coprimep_def (eqp_size (gcdp_scaler _ _ _)). Qed.\n\nLemma coprimepp p : coprimep p p = (size p == 1%N).\nProof. by rewrite coprimep_def gcdpp. Qed.\n\nLemma gcdp_eqp1 p q : gcdp p q %= 1 = coprimep p q.\nProof. by rewrite coprimep_def size_poly_eq1. Qed.\n\nLemma coprimep_sym p q : coprimep p q = coprimep q p.\nProof. by rewrite -!gcdp_eqp1; apply: eqp_ltrans; rewrite gcdpC. Qed.\n\nLemma coprime1p p : coprimep 1 p.\nProof. by rewrite /coprimep -[1%N](size_poly1 R); exact/eqP/eqp_size/gcd1p. Qed.\n\nLemma coprimep1 p : coprimep p 1.\nProof. by rewrite coprimep_sym; apply: coprime1p. Qed.\n\nLemma coprimep0 p : coprimep p 0 = (p %= 1).\nProof. by rewrite /coprimep gcdp0 size_poly_eq1. Qed.\n\nLemma coprime0p p : coprimep 0 p = (p %= 1).\nProof. by rewrite coprimep_sym coprimep0. Qed.\n\n(* This is different from coprimeP in div. shall we keep this? *)\nLemma coprimepP p q :\n reflect (forall d, d %| p -> d %| q -> d %= 1) (coprimep p q).\nProof.\nrewrite /coprimep; apply: (iffP idP) => [/eqP hs d dvddp dvddq | h].\n  have/dvdp_eqp1: d %| gcdp p q by rewrite dvdp_gcd dvddp dvddq.\n  by rewrite -size_poly_eq1 hs; exact.\nby rewrite size_poly_eq1; case/andP: (dvdp_gcdlr p q); apply: h.\nQed.\n\nLemma coprimepPn p q : p != 0 ->\n  reflect (exists d, (d %| gcdp p q) && ~~ (d %= 1)) (~~ coprimep p q).\nProof.\nmove=> p0; apply: (iffP idP).\n  by rewrite -gcdp_eqp1=> ng1; exists (gcdp p q); rewrite dvdpp /=.\ncase=> d /andP [dg]; apply: contra; rewrite -gcdp_eqp1=> g1.\nby move: dg; rewrite (eqp_dvdr _ g1) dvdp1 size_poly_eq1.\nQed.\n\nLemma coprimep_dvdl q p r : r %| q -> coprimep p q -> coprimep p r.\nProof.\nmove=> rp /coprimepP cpq'; apply/coprimepP => d dp dr.\nexact/cpq'/(dvdp_trans dr).\nQed.\n\nLemma coprimep_dvdr p q r : r %| p -> coprimep p q -> coprimep r q.\nProof.\nby move=> rp; rewrite ![coprimep _ q]coprimep_sym; apply/coprimep_dvdl.\nQed.\n\nLemma coprimep_modl p q : coprimep (p %% q) q = coprimep p q.\nProof.\nrewrite !coprimep_def [in RHS]gcdpE.\nby case: ltnP => // hpq; rewrite modp_small // gcdpE hpq.\nQed.\n\nLemma coprimep_modr q p : coprimep q (p %% q) = coprimep q p.\nProof. by rewrite ![coprimep q _]coprimep_sym coprimep_modl. Qed.\n\nLemma rcoprimep_coprimep q p : rcoprimep q p = coprimep q p.\nProof. by rewrite /coprimep /rcoprimep (eqp_size (eqp_rgcd_gcd _ _)). Qed.\n\nLemma eqp_coprimepr p q r : q %= r -> coprimep p q = coprimep p r.\nProof. by rewrite -!gcdp_eqp1; move/(eqp_gcdr p)/eqp_ltrans. Qed.\n\nLemma eqp_coprimepl p q r : q %= r -> coprimep q p = coprimep r p.\nProof. by rewrite !(coprimep_sym _ p); apply: eqp_coprimepr. Qed.\n\n(* This should be implemented with an extended remainder sequence *)\nFixpoint egcdp_rec p q k {struct k} : {poly R} * {poly R} :=\n  if k is k'.+1 then\n    if q == 0 then (1, 0) else\n    let: (u, v) := egcdp_rec q (p %% q) k' in\n      (lead_coef q ^+ scalp p q *: v, (u - v * (p %/ q)))\n  else (1, 0).\n\nDefinition egcdp p q :=\n  if size q <= size p then egcdp_rec p q (size q)\n    else let e := egcdp_rec q p (size p) in (e.2, e.1).\n\n(* No provable egcd0p *)\nLemma egcdp0 p : egcdp p 0 = (1, 0). Proof. by rewrite /egcdp size_poly0. Qed.\n\nLemma egcdp_recP : forall k p q, q != 0 -> size q <= k -> size q <= size p ->\n  let e := (egcdp_rec p q k) in\n    [/\\ size e.1 <= size q, size e.2 <= size p & gcdp p q %= e.1 * p + e.2 * q].\nProof.\nelim=> [|k ihk] p q /= qn0; first by rewrite size_poly_leq0 (negPf qn0).\nmove=> sqSn qsp; rewrite (negPf qn0).\nhave sp : size p > 0 by apply: leq_trans qsp; rewrite size_poly_gt0.\nhave [r0 | rn0] /= := eqVneq (p %%q) 0.\n  rewrite r0 /egcdp_rec; case: k ihk sqSn => [|n] ihn sqSn /=.\n    rewrite !scaler0 !mul0r subr0 add0r mul1r size_poly0 size_poly1.\n    by rewrite dvdp_gcd_idr /dvdp ?r0.\n  rewrite !eqxx mul0r scaler0 /= mul0r add0r subr0 mul1r size_poly0 size_poly1.\n  by rewrite dvdp_gcd_idr /dvdp ?r0 //.\nhave h1 : size (p %% q) <= k.\n  by rewrite -ltnS; apply: leq_trans sqSn; rewrite ltn_modp.\nhave h2 : size (p %% q) <= size q by rewrite ltnW // ltn_modp.\nhave := ihk q (p %% q) rn0 h1 h2.\ncase: (egcdp_rec _ _)=> u v /= => [[ihn'1 ihn'2 ihn'3]].\nrewrite gcdpE ltnNge qsp //= (eqp_ltrans (gcdpC _ _)); split; last first.\n- apply: (eqp_trans ihn'3).\n  rewrite mulrBl addrCA -scalerAl scalerAr -mulrA -mulrBr.\n  by rewrite divp_eq addrAC subrr add0r eqpxx.\n- apply: (leq_trans (size_add _ _)).\n  have [-> | vn0] := eqVneq v 0.\n    rewrite mul0r size_opp size_poly0 maxn0; apply: leq_trans ihn'1 _.\n    exact: leq_modp.\n  have [-> | qqn0] := eqVneq (p %/ q) 0.\n    rewrite mulr0 size_opp size_poly0 maxn0; apply: leq_trans ihn'1 _.\n    exact: leq_modp.\n  rewrite geq_max (leq_trans ihn'1) ?leq_modp //= size_opp size_mul //.\n  move: (ihn'2); rewrite (polySpred vn0) (polySpred qn0).\n  rewrite -(ltn_add2r (size (p %/ q))) !addSn /= ltnS; move/leq_trans; apply.\n  rewrite size_divp // addnBA ?addKn //.\n  by apply: leq_trans qsp; apply: leq_pred.\n- by rewrite size_scale // lc_expn_scalp_neq0.\nQed.\n\nLemma egcdpP p q : p != 0 -> q != 0 -> forall (e := egcdp p q),\n  [/\\ size e.1 <= size q, size e.2 <= size p & gcdp p q %= e.1 * p + e.2 * q].\nProof.\nrewrite /egcdp => pn0 qn0; case: (leqP (size q) (size p)) => /= [|/ltnW] hp.\n  exact: egcdp_recP.\ncase: (egcdp_recP pn0 (leqnn (size p)) hp) => h1 h2 h3; split => //.\nby rewrite (eqp_ltrans (gcdpC _ _)) addrC.\nQed.\n\nLemma egcdpE p q (e := egcdp p q) : gcdp p q %= e.1 * p + e.2 * q.\nProof.\nrewrite {}/e; have [-> /= | qn0] := eqVneq q 0.\n  by rewrite gcdp0 egcdp0 mul1r mulr0 addr0.\nhave [-> | pn0] := eqVneq p 0; last by case: (egcdpP pn0 qn0).\nby rewrite gcd0p /egcdp size_poly0 size_poly_leq0 (negPf qn0) /= !simp.\nQed.\n\nLemma Bezoutp p q : exists u, u.1 * p + u.2 * q %= (gcdp p q).\nProof.\nhave [-> | pn0] := eqVneq p 0.\n  by rewrite gcd0p; exists (0, 1); rewrite mul0r mul1r add0r.\nhave [-> | qn0] := eqVneq q 0.\n  by rewrite gcdp0; exists (1, 0); rewrite mul0r mul1r addr0.\npose e := egcdp p q; exists e; rewrite eqp_sym.\nby case: (egcdpP pn0 qn0).\nQed.\n\nLemma Bezout_coprimepP p q :\n  reflect (exists u, u.1 * p + u.2 * q %= 1) (coprimep p q).\nProof.\nrewrite -gcdp_eqp1; apply: (iffP idP)=> [g1|].\n  by case: (Bezoutp p q) => [[u v] Puv]; exists (u, v); apply: eqp_trans g1.\ncase=> [[u v]]; rewrite eqp_sym=> Puv; rewrite /eqp (eqp_dvdr _ Puv).\nby rewrite dvdp_addr dvdp_mull ?dvdp_gcdl ?dvdp_gcdr //= dvd1p.\nQed.\n\nLemma coprimep_root p q x : coprimep p q -> root p x -> q.[x] != 0.\nProof.\ncase/Bezout_coprimepP=> [[u v] euv] px0.\nmove/eqpP: euv => [[c1 c2]] /andP /= [c1n0 c2n0 e].\nsuffices: c1 * (v.[x] * q.[x]) != 0.\n  by rewrite !mulf_eq0 !negb_or c1n0 /=; case/andP.\nhave := f_equal (horner^~ x) e; rewrite /= !hornerZ hornerD.\nby rewrite !hornerM (eqP px0) mulr0 add0r hornerC mulr1; move->.\nQed.\n\nLemma Gauss_dvdpl p q d: coprimep d q -> (d %| p * q) = (d %| p).\nProof.\nmove/Bezout_coprimepP=>[[u v] Puv]; apply/idP/idP; last exact: dvdp_mulr.\nmove/(eqp_mull p): Puv; rewrite mulr1 mulrDr eqp_sym=> peq dpq.\nrewrite (eqp_dvdr _ peq) dvdp_addr; first by rewrite mulrA mulrAC dvdp_mulr.\nby rewrite mulrA dvdp_mull ?dvdpp.\nQed.\n\nLemma Gauss_dvdpr p q d: coprimep d q -> (d %| q * p) = (d %| p).\nProof. by rewrite mulrC; apply: Gauss_dvdpl. Qed.\n\n(* This could be simplified with the introduction of lcmp *)\nLemma Gauss_dvdp m n p : coprimep m n -> (m * n %| p) = (m %| p) && (n %| p).\nProof.\nhave [-> | mn0] := eqVneq m 0.\n  by rewrite coprime0p => /eqp_dvdl->; rewrite !mul0r dvd0p dvd1p andbT.\nhave [-> | nn0] := eqVneq n 0.\n  by rewrite coprimep0 => /eqp_dvdl->; rewrite !mulr0 dvd1p.\nmove=> hc; apply/idP/idP => [mnmp | /andP [dmp dnp]].\n  move/Gauss_dvdpl: hc => <-; move: (dvdp_mull m mnmp); rewrite dvdp_mul2l //.\n  move->; move: (dvdp_mulr n mnmp); rewrite dvdp_mul2r // andbT.\n  exact: dvdp_mulr.\nmove: (dnp); rewrite dvdp_eq.\nset c2 := _ ^+ _; set q2 := _ %/ _; move/eqP=> e2.\nhave/esym := Gauss_dvdpl q2 hc; rewrite -e2.\nhave -> : m %| c2 *: p by rewrite -mul_polyC dvdp_mull.\nrewrite dvdp_eq; set c3 := _ ^+ _; set q3 := _ %/ _; move/eqP=> e3.\napply: (@eq_dvdp (c3 * c2) q3).\n  by rewrite mulf_neq0 // expf_neq0 // lead_coef_eq0.\nby rewrite mulrA -e3 -scalerAl -e2 scalerA.\nQed.\n\nLemma Gauss_gcdpr p m n : coprimep p m -> gcdp p (m * n) %= gcdp p n.\nProof.\nmove=> co_pm; apply/eqP; rewrite /eqp !dvdp_gcd !dvdp_gcdl /= andbC.\nrewrite dvdp_mull ?dvdp_gcdr // -(@Gauss_dvdpl _ m).\n  by rewrite mulrC dvdp_gcdr.\napply/coprimepP=> d; rewrite dvdp_gcd; case/andP=> hdp _ hdm.\nby move/coprimepP: co_pm; apply.\nQed.\n\nLemma Gauss_gcdpl p m n : coprimep p n -> gcdp p (m * n) %= gcdp p m.\nProof. by move=> co_pn; rewrite mulrC Gauss_gcdpr. Qed.\n\nLemma coprimepMr p q r : coprimep p (q * r) = (coprimep p q && coprimep p r).\nProof.\napply/coprimepP/andP=> [hp | [/coprimepP-hq hr]].\n  by split; apply/coprimepP=> d dp dq; rewrite hp //;\n     [apply/dvdp_mulr | apply/dvdp_mull].\nmove=> d dp dqr; move/(_ _ dp) in hq.\nrewrite Gauss_dvdpl in dqr; first exact: hq.\nby move/coprimep_dvdr: hr; apply.\nQed.\n\nLemma coprimepMl p q r: coprimep (q * r) p = (coprimep q p && coprimep r p).\nProof. by rewrite ![coprimep _ p]coprimep_sym coprimepMr. Qed.\n\nLemma modp_coprime k u n : k != 0 -> (k * u) %% n %= 1 -> coprimep k n.\nProof.\nmove=> kn0 hmod; apply/Bezout_coprimepP.\nexists (((lead_coef n)^+(scalp (k * u) n) *: u), (- (k * u %/ n))).\nrewrite -scalerAl mulrC (divp_eq (u * k) n) mulNr -addrAC subrr add0r.\nby rewrite mulrC.\nQed.\n\nLemma coprimep_pexpl k m n : 0 < k -> coprimep (m ^+ k) n = coprimep m n.\nProof.\ncase: k => // k _; elim: k => [|k IHk]; first by rewrite expr1.\nby rewrite exprS coprimepMl -IHk andbb.\nQed.\n\nLemma coprimep_pexpr k m n : 0 < k -> coprimep m (n ^+ k) = coprimep m n.\nProof. by move=> k_gt0; rewrite !(coprimep_sym m) coprimep_pexpl. Qed.\n\nLemma coprimep_expl k m n : coprimep m n -> coprimep (m ^+ k) n.\nProof. by case: k => [|k] co_pm; rewrite ?coprime1p // coprimep_pexpl. Qed.\n\nLemma coprimep_expr k m n : coprimep m n -> coprimep m (n ^+ k).\nProof. by rewrite !(coprimep_sym m); apply: coprimep_expl. Qed.\n\nLemma gcdp_mul2l p q r : gcdp (p * q) (p * r) %= (p * gcdp q r).\nProof.\nhave [->|hp] := eqVneq p 0; first by rewrite !mul0r gcdp0 eqpxx.\nrewrite /eqp !dvdp_gcd !dvdp_mul2l // dvdp_gcdr dvdp_gcdl !andbT.\nmove: (Bezoutp q r) => [[u v]] huv.\nrewrite eqp_sym in huv; rewrite (eqp_dvdr _ (eqp_mull _ huv)).\nrewrite mulrDr ![p * (_ * _)]mulrCA.\nby apply: dvdp_add; rewrite dvdp_mull// (dvdp_gcdr, dvdp_gcdl).\nQed.\n\nLemma gcdp_mul2r q r p : gcdp (q * p) (r * p) %= gcdp q r * p.\nProof. by rewrite ![_ * p]mulrC gcdp_mul2l. Qed.\n\nLemma mulp_gcdr p q r : r * (gcdp p q) %= gcdp (r * p) (r * q).\nProof. by rewrite eqp_sym gcdp_mul2l. Qed.\n\nLemma mulp_gcdl p q r : (gcdp p q) * r %= gcdp (p * r) (q * r).\nProof. by rewrite eqp_sym gcdp_mul2r. Qed.\n\nLemma coprimep_div_gcd p q : (p != 0) || (q != 0) ->\n  coprimep (p %/ (gcdp p q)) (q %/ gcdp p q).\nProof.\nrewrite -negb_and -gcdp_eq0 -gcdp_eqp1 => gpq0.\nrewrite -(@eqp_mul2r (gcdp p q)) // mul1r (eqp_ltrans (mulp_gcdl _ _ _)).\nhave: gcdp p q %| p by rewrite dvdp_gcdl.\nhave: gcdp p q %| q by rewrite dvdp_gcdr.\nrewrite !dvdp_eq => /eqP <- /eqP <-.\nhave lcn0 k : (lead_coef (gcdp p q)) ^+ k != 0.\n  by rewrite expf_neq0 ?lead_coef_eq0.\nby apply: eqp_gcd; rewrite ?eqp_scale.\nQed.\n\nLemma divp_eq0 p q : (p %/ q == 0) = [|| p == 0, q ==0 | size p < size q].\nProof.\napply/eqP/idP=> [d0|]; last first.\n  case/or3P; [by move/eqP->; rewrite div0p| by move/eqP->; rewrite divp0|].\n  by move/divp_small.\ncase: eqVneq => // _; case: eqVneq => // qn0.\nmove: (divp_eq p q); rewrite d0 mul0r add0r.\nmove/(f_equal (fun x : {poly R} => size x)).\nby rewrite size_scale ?lc_expn_scalp_neq0 // => ->; rewrite ltn_modp qn0 !orbT.\nQed.\n\nLemma dvdp_div_eq0 p q : q %| p -> (p %/ q == 0) = (p == 0).\nProof.\nmove=> dvdp_qp; have [->|p_neq0] := eqVneq p 0; first by rewrite div0p eqxx.\nrewrite divp_eq0 ltnNge dvdp_leq // (negPf p_neq0) orbF /=.\nby apply: contraTF dvdp_qp=> /eqP ->; rewrite dvd0p.\nQed.\n\nLemma Bezout_coprimepPn p q : p != 0 -> q != 0 ->\n  reflect (exists2 uv : {poly R} * {poly R},\n    (0 < size uv.1 < size q) && (0 < size uv.2 < size p) &\n      uv.1 * p = uv.2 * q)\n    (~~ (coprimep p q)).\nProof.\nmove=> pn0 qn0; apply: (iffP idP); last first.\n  case=> [[u v] /= /andP [/andP [ps1 s1] /andP [ps2 s2]] e].\n  have: ~~(size (q * p) <= size (u * p)).\n    rewrite -ltnNge !size_mul // -?size_poly_gt0 // (polySpred pn0) !addnS.\n    by rewrite ltn_add2r.\n  apply: contra => ?; apply: dvdp_leq; rewrite ?mulf_neq0 // -?size_poly_gt0 //.\n  by rewrite mulrC Gauss_dvdp // dvdp_mull // e dvdp_mull.\nrewrite coprimep_def neq_ltn ltnS size_poly_leq0 gcdp_eq0.\nrewrite (negPf pn0) (negPf qn0) /=.\ncase sg: (size (gcdp p q)) => [|n] //; case: n sg=> [|n] // sg _.\nmove: (dvdp_gcdl p q); rewrite dvdp_eq; set c1 := _ ^+ _; move/eqP=> hu1.\nmove: (dvdp_gcdr p q); rewrite dvdp_eq; set c2 := _ ^+ _; move/eqP=> hv1.\nexists (c1 *: (q %/ gcdp p q), c2 *: (p %/ gcdp p q)); last first.\n  by rewrite -!scalerAl !scalerAr hu1 hv1 mulrCA.\nrewrite !size_scale ?lc_expn_scalp_neq0 //= !size_poly_gt0 !divp_eq0.\nrewrite gcdp_eq0 !(negPf pn0) !(negPf qn0) /= -!leqNgt leq_gcdpl //.\nrewrite leq_gcdpr //= !ltn_divpl -?size_poly_eq0 ?sg //.\nrewrite !size_mul // -?size_poly_eq0 ?sg // ![(_ + n.+2)%N]addnS /=.\nby rewrite -!(addn1 (size _)) !leq_add2l.\nQed.\n\nLemma dvdp_pexp2r m n k : k > 0 -> (m ^+ k %| n ^+ k) = (m %| n).\nProof.\nmove=> k_gt0; apply/idP/idP; last exact: dvdp_exp2r.\nhave [-> // | nn0] := eqVneq n 0; have [-> | mn0] := eqVneq m 0.\n  move/prednK: k_gt0=> {1}<-; rewrite exprS mul0r //= !dvd0p expf_eq0.\n  by case/andP=> _ ->.\nset d := gcdp m n; have := dvdp_gcdr m n; rewrite -/d dvdp_eq.\nset c1 := _ ^+ _; set n' := _ %/ _; move/eqP=> def_n.\nhave := dvdp_gcdl m n; rewrite -/d dvdp_eq.\nset c2 := _ ^+ _; set m' := _ %/ _; move/eqP=> def_m.\nhave dn0 : d != 0 by rewrite gcdp_eq0 negb_and nn0 orbT.\nhave c1n0 : c1 != 0 by rewrite !expf_neq0 // lead_coef_eq0.\nhave c2n0 : c2 != 0 by rewrite !expf_neq0 // lead_coef_eq0.\nhave c2k_n0 : c2 ^+ k != 0 by rewrite !expf_neq0 // lead_coef_eq0.\nrewrite -(@dvdpZr (c1 ^+ k)) ?expf_neq0 ?lead_coef_eq0 //.\nrewrite -(@dvdpZl (c2 ^+ k)) // -!exprZn def_m def_n !exprMn.\nrewrite dvdp_mul2r ?expf_neq0 //.\nhave: coprimep (m' ^+ k) (n' ^+ k).\n  by rewrite coprimep_pexpl // coprimep_pexpr // coprimep_div_gcd ?mn0.\nmove/coprimepP=> hc hd.\nhave /size_poly1P [c cn0 em'] : size m' == 1%N.\n  case: (eqVneq m' 0) def_m => [-> /eqP | m'_n0 def_m].\n    by rewrite mul0r scale_poly_eq0 (negPf mn0) (negPf c2n0).\n  have := hc _ (dvdpp _) hd; rewrite -size_poly_eq1.\n  rewrite polySpred; last by rewrite expf_eq0 negb_and m'_n0 orbT.\n  by rewrite size_exp eqSS muln_eq0 orbC eqn0Ngt k_gt0 /= -eqSS -polySpred.\nrewrite -(@dvdpZl c2) // def_m em' mul_polyC dvdpZl //.\nby rewrite -(@dvdpZr c1) // def_n dvdp_mull.\nQed.\n\nLemma root_gcd p q x : root (gcdp p q) x = root p x && root q x.\nProof.\nrewrite /= !root_factor_theorem; apply/idP/andP=> [dg| [dp dq]].\n  by split; apply: dvdp_trans dg _; rewrite ?(dvdp_gcdl, dvdp_gcdr).\nhave:= Bezoutp p q => [[[u v]]]; rewrite eqp_sym=> e.\nby rewrite (eqp_dvdr _ e) dvdp_addl dvdp_mull.\nQed.\n\nLemma root_biggcd x (ps : seq {poly R}) :\n  root (\\big[gcdp/0]_(p <- ps) p) x = all (fun p => root p x) ps.\nProof.\nelim: ps => [|p ps ihp]; first by rewrite big_nil root0.\nby rewrite big_cons /= root_gcd ihp.\nQed.\n\n(* \"gdcop Q P\" is the Greatest Divisor of P which is coprime to Q *)\n(* if P null, we pose that gdcop returns 1 if Q null, 0 otherwise*)\nFixpoint gdcop_rec q p k :=\n  if k is m.+1 then\n      if coprimep p q then p\n        else gdcop_rec q (divp p (gcdp p q)) m\n    else (q == 0)%:R.\n\nDefinition gdcop q p := gdcop_rec q p (size p).\n\nVariant gdcop_spec q p : {poly R} -> Type :=\n  GdcopSpec r of (dvdp r p) & ((coprimep r q) || (p == 0))\n  & (forall d, dvdp d p -> coprimep d q -> dvdp d r)\n  : gdcop_spec q p r.\n\nLemma gdcop0 q : gdcop q 0 = (q == 0)%:R.\nProof. by rewrite /gdcop size_poly0. Qed.\n\nLemma gdcop_recP q p k : size p <= k -> gdcop_spec q p (gdcop_rec q p k).\nProof.\nelim: k p => [p | k ihk p] /=.\n  move/size_poly_leq0P->.\n  have [->|q0] := eqVneq; split; rewrite ?coprime1p // ?eqxx ?orbT //.\n  by move=> d _; rewrite coprimep0 dvdp1 size_poly_eq1.\nmove=> hs; case cop : (coprimep _ _); first by split; rewrite ?dvdpp ?cop.\nhave [-> | p0] := eqVneq p 0.\n  by rewrite div0p; apply: ihk; rewrite size_poly0 leq0n.\nhave [-> | q0] := eqVneq q 0.\n  rewrite gcdp0 divpp ?p0 //= => {hs ihk}; case: k=> /=.\n    rewrite eqxx; split; rewrite ?dvd1p ?coprimep0 ?eqpxx //=.\n    by move=> d _; rewrite coprimep0 dvdp1 size_poly_eq1.\n  move=> n; rewrite coprimep0 polyC_eqp1 //; rewrite lc_expn_scalp_neq0.\n  split; first by rewrite (@eqp_dvdl 1) ?dvd1p // polyC_eqp1 lc_expn_scalp_neq0.\n    by rewrite coprimep0 polyC_eqp1 // ?lc_expn_scalp_neq0.\n  by move=> d _; rewrite coprimep0; move/eqp_dvdl->; rewrite dvd1p.\nmove: (dvdp_gcdl p q); rewrite dvdp_eq; move/eqP=> e.\nhave sgp : size (gcdp p q) <= size p.\n  by apply: dvdp_leq; rewrite ?gcdp_eq0 ?p0 ?q0 // dvdp_gcdl.\nhave : p %/ gcdp p q != 0; last move/negPf=>p'n0.\n  apply: dvdpN0 (dvdp_mulIl (p %/ gcdp p q) (gcdp p q)) _.\n  by rewrite -e scale_poly_eq0 negb_or lc_expn_scalp_neq0.\nhave gn0 : gcdp p q != 0.\n  apply: dvdpN0 (dvdp_mulIr (p %/ gcdp p q) (gcdp p q)) _.\n  by rewrite -e scale_poly_eq0 negb_or lc_expn_scalp_neq0.\nhave sp' : size (p %/ (gcdp p q)) <= k.\n  rewrite size_divp ?sgp // leq_subLR (leq_trans hs) // -add1n leq_add2r -subn1.\n  by rewrite ltn_subRL add1n ltn_neqAle eq_sym [_ == _]cop size_poly_gt0 gn0.\ncase (ihk _ sp')=> r' dr'p'; first rewrite p'n0 orbF=> cr'q maxr'.\nconstructor=> //=; rewrite ?(negPf p0) ?orbF //.\n  exact/(dvdp_trans dr'p')/divp_dvd/dvdp_gcdl.\nmove=> d dp cdq; apply: maxr'; last by rewrite cdq.\ncase dpq: (d %| gcdp p q).\n  move: (dpq); rewrite dvdp_gcd dp /= => dq; apply: dvdUp.\n  apply: contraLR cdq => nd1; apply/coprimepPn; last first.\n    by exists d; rewrite dvdp_gcd dvdpp dq nd1.\n  by apply: contraNneq p0 => d0; move: dp; rewrite d0 dvd0p.\napply: contraLR dp => ndp'.\nrewrite (@eqp_dvdr ((lead_coef (gcdp p q) ^+ scalp p (gcdp p q))*:p)).\n  by rewrite e; rewrite Gauss_dvdpl //; apply: (coprimep_dvdl (dvdp_gcdr _ _)).\nby rewrite eqp_sym eqp_scale // lc_expn_scalp_neq0.\nQed.\n\nLemma gdcopP q p : gdcop_spec q p (gdcop q p).\nProof. by rewrite /gdcop; apply: gdcop_recP. Qed.\n\nLemma coprimep_gdco p q : (q != 0)%B -> coprimep (gdcop p q) p.\nProof. by move=> q_neq0; case: gdcopP=> d; rewrite (negPf q_neq0) orbF. Qed.\n\nLemma size2_dvdp_gdco p q d : p != 0 -> size d = 2%N ->\n  (d %| (gdcop q p)) = (d %| p) && ~~(d %| q).\nProof.\nhave [-> | dn0] := eqVneq d 0; first by rewrite size_poly0.\nmove=> p0 sd; apply/idP/idP.\n  case: gdcopP=> r rp crq maxr dr; move/negPf: (p0)=> p0f.\n  rewrite (dvdp_trans dr) //=.\n  apply: contraL crq => dq; rewrite p0f orbF; apply/coprimepPn.\n    by apply: contraNneq p0 => r0; move: rp; rewrite r0 dvd0p.\n  by exists d; rewrite dvdp_gcd dr dq -size_poly_eq1 sd.\ncase/andP=> dp dq; case: gdcopP=> r rp crq maxr; apply: maxr=> //.\napply/coprimepP=> x xd xq.\nmove: (dvdp_leq dn0 xd); rewrite leq_eqVlt sd; case/orP; last first.\n  rewrite ltnS leq_eqVlt ltnS size_poly_leq0 orbC.\n  case/predU1P => [x0|]; last by rewrite -size_poly_eq1.\n  by move: xd; rewrite x0 dvd0p (negPf dn0).\nby rewrite -sd dvdp_size_eqp //; move/(eqp_dvdl q); rewrite xq (negPf dq).\nQed.\n\nLemma dvdp_gdco p q : (gdcop p q) %| q. Proof. by case: gdcopP. Qed.\n\nLemma root_gdco p q x : p != 0 -> root (gdcop q p) x = root p x && ~~(root q x).\nProof.\nmove=> p0 /=; rewrite !root_factor_theorem.\napply: size2_dvdp_gdco; rewrite ?p0 //.\nby rewrite size_addl size_polyX // size_opp size_polyC ltnS; case: (x != 0).\nQed.\n\nLemma dvdp_comp_poly r p q : (p %| q) -> (p \\Po r) %| (q \\Po r).\nProof.\nhave [-> | pn0] := eqVneq p 0.\n  by rewrite comp_poly0 !dvd0p; move/eqP->; rewrite comp_poly0.\nrewrite dvdp_eq; set c := _ ^+ _; set s := _ %/ _; move/eqP=> Hq.\napply: (@eq_dvdp c (s \\Po r)); first by rewrite expf_neq0 // lead_coef_eq0.\nby rewrite -comp_polyZ Hq comp_polyM.\nQed.\n\nLemma gcdp_comp_poly r p q : gcdp p q \\Po r %= gcdp (p \\Po r) (q \\Po r).\nProof.\napply/andP; split.\n  by rewrite dvdp_gcd !dvdp_comp_poly ?dvdp_gcdl ?dvdp_gcdr.\ncase: (Bezoutp p q) => [[u v]] /andP [].\nmove/(dvdp_comp_poly r) => Huv _.\nrewrite (dvdp_trans _ Huv) // comp_polyD !comp_polyM.\nby rewrite dvdp_add // dvdp_mull // (dvdp_gcdl,dvdp_gcdr).\nQed.\n\nLemma coprimep_comp_poly r p q : coprimep p q -> coprimep (p \\Po r) (q \\Po r).\nProof.\nrewrite -!gcdp_eqp1 -!size_poly_eq1 -!dvdp1; move/(dvdp_comp_poly r).\nrewrite comp_polyC => Hgcd.\nby apply: dvdp_trans Hgcd; case/andP: (gcdp_comp_poly r p q).\nQed.\n\nLemma coprimep_addl_mul p q r : coprimep r (p * r + q) = coprimep r q.\nProof. by rewrite !coprimep_def (eqp_size (gcdp_addl_mul _ _ _)). Qed.\n\nDefinition irreducible_poly p :=\n  (size p > 1) * (forall q, size q != 1%N -> q %| p -> q %= p) : Prop.\n\nLemma irredp_neq0 p : irreducible_poly p -> p != 0.\nProof. by rewrite -size_poly_gt0 => [[/ltnW]]. Qed.\n\nDefinition apply_irredp p (irr_p : irreducible_poly p) := irr_p.2.\nCoercion apply_irredp : irreducible_poly >-> Funclass.\n\nLemma modp_XsubC p c : p %% ('X - c%:P) = p.[c]%:P.\nProof.\nhave/factor_theorem [q /(canRL (subrK _)) Dp]: root (p - p.[c]%:P) c.\n  by rewrite /root !hornerE subrr.\nrewrite modpE /= lead_coefXsubC unitr1 expr1n invr1 scale1r [in LHS]Dp.\nrewrite RingMonic.rmodp_addl_mul_small // ?monicXsubC // size_XsubC size_polyC.\nby case: (p.[c] == 0).\nQed.\n\nLemma coprimep_XsubC p c : coprimep p ('X - c%:P) = ~~ root p c.\nProof.\nrewrite -coprimep_modl modp_XsubC /root -alg_polyC.\nhave [-> | /coprimepZl->] := eqVneq; last exact: coprime1p.\nby rewrite scale0r /coprimep gcd0p size_XsubC.\nQed.\n\nLemma coprimep_XsubC2 (a b : R) : b - a != 0 ->\n  coprimep ('X - a%:P) ('X - b%:P).\nProof. by move=> bBa_neq0; rewrite coprimep_XsubC rootE hornerXsubC. Qed.\n\nLemma coprimepX p : coprimep p 'X = ~~ root p 0.\nProof. by rewrite -['X]subr0 coprimep_XsubC. Qed.\n\nLemma eqp_monic : {in monic &, forall p q, (p %= q) = (p == q)}.\nProof.\nmove=> p q monic_p monic_q; apply/idP/eqP=> [|-> //].\ncase/eqpP=> [[a b] /= /andP[a_neq0 _] eq_pq].\napply: (@mulfI _ a%:P); first by rewrite polyC_eq0.\nrewrite !mul_polyC eq_pq; congr (_ *: q); apply: (mulIf (oner_neq0 _)).\nby rewrite -[in LHS](monicP monic_q) -(monicP monic_p) -!lead_coefZ eq_pq.\nQed.\n\nLemma dvdp_mul_XsubC p q c :\n  (p %| ('X - c%:P) * q) = ((if root p c then p %/ ('X - c%:P) else p) %| q).\nProof.\ncase: ifPn => [| not_pc0]; last by rewrite Gauss_dvdpr ?coprimep_XsubC.\nrewrite root_factor_theorem -eqp_div_XsubC mulrC => /eqP{1}->.\nby rewrite dvdp_mul2l ?polyXsubC_eq0.\nQed.\n\nLemma dvdp_prod_XsubC (I : Type) (r : seq I) (F : I -> R) p :\n    p %| \\prod_(i <- r) ('X - (F i)%:P) ->\n  {m | p %= \\prod_(i <- mask m r) ('X - (F i)%:P)}.\nProof.\nelim: r => [|i r IHr] in p *.\n  by rewrite big_nil dvdp1; exists nil; rewrite // big_nil -size_poly_eq1.\nrewrite big_cons dvdp_mul_XsubC root_factor_theorem -eqp_div_XsubC.\ncase: eqP => [{2}-> | _] /IHr[m Dp]; last by exists (false :: m).\nby exists (true :: m); rewrite /= mulrC big_cons eqp_mul2l ?polyXsubC_eq0.\nQed.\n\nLemma irredp_XsubC (x : R) : irreducible_poly ('X - x%:P).\nProof.\nsplit=> [|d size_d d_dv_Xx]; first by rewrite size_XsubC.\nhave: ~ d %= 1 by apply/negP; rewrite -size_poly_eq1.\nhave [|m /=] := @dvdp_prod_XsubC _ [:: x] id d; first by rewrite big_seq1.\nby case: m => [|[] [|_ _] /=]; rewrite (big_nil, big_seq1).\nQed.\n\nLemma irredp_XsubCP d p :\n  irreducible_poly p -> d %| p -> {d %= 1} + {d %= p}.\nProof.\nmove=> irred_p dvd_dp; have [] := boolP (_ %= 1); first by left.\nby rewrite -size_poly_eq1=> /irred_p /(_ dvd_dp); right.\nQed.\n\nEnd IDomainPseudoDivision.\n\n#[global] Hint Resolve eqpxx divp0 divp1 mod0p modp0 modp1 : core.\n#[global] Hint Resolve dvdp_mull dvdp_mulr dvdpp dvdp0 : core.\n\nEnd CommonIdomain.\n\nModule Idomain.\n\nInclude IdomainDefs.\nExport IdomainDefs.\nInclude WeakIdomain.\nInclude CommonIdomain.\n\nEnd Idomain.\n\nModule IdomainMonic.\n\nImport Ring ComRing UnitRing IdomainDefs Idomain.\n\nSection IdomainMonic.\n\nVariable R : idomainType.\n\nImplicit Type p d r : {poly R}.\n\nSection MonicDivisor.\n\nVariable q : {poly R}.\nHypothesis monq : q \\is monic.\n\nLemma divpE p : p %/ q = rdivp p q.\nProof. by rewrite divpE (eqP monq) unitr1 expr1n invr1 scale1r. Qed.\n\nLemma modpE p : p %% q = rmodp p q.\nProof. by rewrite modpE (eqP monq) unitr1 expr1n invr1 scale1r. Qed.\n\nLemma scalpE p : scalp p q = 0%N.\nProof. by rewrite scalpE (eqP monq) unitr1. Qed.\n\nLemma divp_eq p : p = (p %/ q) * q + (p %% q).\nProof. by rewrite -divp_eq (eqP monq) expr1n scale1r. Qed.\n\nLemma divpp p : q %/ q = 1.\nProof. by rewrite divpp ?monic_neq0 // (eqP monq) expr1n. Qed.\n\nLemma dvdp_eq p : (q %| p) = (p == (p %/ q) * q).\nProof. by rewrite dvdp_eq (eqP monq) expr1n scale1r. Qed.\n\nLemma dvdpP p : reflect (exists qq, p = qq * q) (q %| p).\nProof.\napply: (iffP idP); first by rewrite dvdp_eq; move/eqP=> e; exists (p %/ q).\nby case=> qq ->; rewrite dvdp_mull // dvdpp.\nQed.\n\nLemma mulpK p : p * q %/ q = p.\nProof. by rewrite mulpK ?monic_neq0 // (eqP monq) expr1n scale1r. Qed.\n\nLemma mulKp p : q * p %/ q = p. Proof. by rewrite mulrC mulpK. Qed.\n\nEnd MonicDivisor.\n\nLemma drop_poly_divp n p : drop_poly n p = p %/ 'X^n.\nProof. by rewrite RingMonic.drop_poly_rdivp divpE // monicXn. Qed.\n\nLemma take_poly_modp n p : take_poly n p = p %% 'X^n.\nProof. by rewrite RingMonic.take_poly_rmodp modpE // monicXn. Qed.\n\nEnd IdomainMonic.\n\nEnd IdomainMonic.\n\nModule IdomainUnit.\n\nImport Ring ComRing UnitRing IdomainDefs Idomain.\n\nSection UnitDivisor.\n\nVariable R : idomainType.\nVariable d : {poly R}.\n\nHypothesis ulcd : lead_coef d \\in GRing.unit.\n\nImplicit Type p q r : {poly R}.\n\nLemma divp_eq p : p = (p %/ d) * d + (p %% d).\nProof. by have := divp_eq p d; rewrite scalpE ulcd expr0 scale1r. Qed.\n\nLemma edivpP p q r : p = q * d + r -> size r < size d ->\n  q = (p %/ d) /\\ r = p %% d.\nProof.\nmove=> ep srd; have := divp_eq p; rewrite [LHS]ep.\nmove/eqP; rewrite -subr_eq -addrA addrC eq_sym -subr_eq -mulrBl; move/eqP.\nhave lcdn0 : lead_coef d != 0 by apply: contraTneq ulcd => ->; rewrite unitr0.\nhave [-> /esym /eqP|abs] := eqVneq (p %/ d) q.\n  by rewrite subrr mul0r subr_eq0 => /eqP<-.\nhave hleq : size d <= size ((p %/ d - q) * d).\n  rewrite size_proper_mul; last first.\n    by rewrite mulf_eq0 (negPf lcdn0) orbF lead_coef_eq0 subr_eq0.\n  by move: abs; rewrite -subr_eq0; move/polySpred->; rewrite addSn /= leq_addl.\nhave hlt : size (r - p %% d) < size d.\n  apply: leq_ltn_trans (size_add _ _) _.\n  by rewrite gtn_max srd size_opp ltn_modp -lead_coef_eq0.\nby move=> e; have:= leq_trans hlt hleq; rewrite e ltnn.\nQed.\n\nLemma divpP p q r : p = q * d + r -> size r < size d -> q = (p %/ d).\nProof. by move/edivpP=> h; case/h. Qed.\n\nLemma modpP p q r : p = q * d + r -> size r < size d -> r = (p %% d).\nProof. by move/edivpP=> h; case/h. Qed.\n\nLemma ulc_eqpP p q : lead_coef q \\is a GRing.unit ->\n  reflect (exists2 c : R, c != 0 & p = c *: q) (p %= q).\nProof.\nhave [->|] := eqVneq (lead_coef q) 0; first by rewrite unitr0.\nrewrite lead_coef_eq0 => nz_q ulcq; apply: (iffP idP).\n  have [->|nz_p] := eqVneq p 0; first by rewrite eqp_sym eqp0 (negPf nz_q).\n  move/eqp_eq=> eq; exists (lead_coef p / lead_coef q).\n    by rewrite mulf_neq0 // ?invr_eq0 lead_coef_eq0.\n  by apply/(scaler_injl ulcq); rewrite scalerA mulrCA divrr // mulr1.\nby case=> c nz_c ->; apply/eqpP; exists (1, c); rewrite ?scale1r ?oner_eq0.\nQed.\n\nLemma dvdp_eq p : (d %| p) = (p == p %/ d * d).\nProof.\napply/eqP/eqP=> [modp0 | ->]; last exact: modp_mull.\nby rewrite [p in LHS]divp_eq modp0 addr0.\nQed.\n\nLemma ucl_eqp_eq p q : lead_coef q \\is a GRing.unit ->\n  p %= q -> p = (lead_coef p / lead_coef q) *: q.\nProof.\nmove=> ulcq /eqp_eq; move/(congr1 ( *:%R (lead_coef q)^-1 )).\nby rewrite !scalerA mulrC divrr // scale1r mulrC.\nQed.\n\nLemma modpZl c p : (c *: p) %% d = c *: (p %% d).\nProof.\nhave [-> | cn0] := eqVneq c 0; first by rewrite !scale0r mod0p.\nhave e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d).\n  by rewrite -scalerAl -scalerDr -divp_eq.\nsuff s: size (c *: (p %% d)) < size d by case: (edivpP e s) => _ ->.\nrewrite -mul_polyC; apply: leq_ltn_trans (size_mul_leq _ _) _.\nrewrite size_polyC cn0 addSn add0n /= ltn_modp -lead_coef_eq0.\nby apply: contraTneq ulcd => ->; rewrite unitr0.\nQed.\n\nLemma divpZl c p : (c *: p) %/ d = c *: (p %/ d).\nProof.\nhave [-> | cn0] := eqVneq c 0; first by rewrite !scale0r div0p.\nhave e : (c *: p) = (c *: (p %/ d)) * d + c *: (p %% d).\n  by rewrite -scalerAl -scalerDr -divp_eq.\nsuff s: size (c *: (p %% d)) < size d by case: (edivpP e s) => ->.\nrewrite -mul_polyC; apply: leq_ltn_trans (size_mul_leq _ _) _.\nrewrite size_polyC cn0 addSn add0n /= ltn_modp -lead_coef_eq0.\nby apply: contraTneq ulcd => ->; rewrite unitr0.\nQed.\n\nLemma eqp_modpl p q : p %= q -> (p %% d) %= (q %% d).\nProof.\ncase/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e].\nby apply/eqpP; exists (c1, c2); rewrite ?c1n0 //= -!modpZl e.\nQed.\n\nLemma eqp_divl p q : p %= q -> (p %/ d) %= (q %/ d).\nProof.\ncase/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e].\nby apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!divpZl e.\nQed.\n\nLemma modpN p : (- p) %% d = - (p %% d).\nProof. by rewrite -mulN1r -[RHS]mulN1r -polyCN !mul_polyC modpZl. Qed.\n\nLemma divpN p : (- p) %/ d = - (p %/ d).\nProof. by rewrite -mulN1r -[RHS]mulN1r -polyCN !mul_polyC divpZl. Qed.\n\nLemma modpD p q : (p + q) %% d = p %% d + q %% d.\nProof.\nhave/edivpP [] // : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d).\n  by rewrite mulrDl addrACA -!divp_eq.\napply: leq_ltn_trans (size_add _ _) _.\nrewrite gtn_max !ltn_modp andbb -lead_coef_eq0.\nby apply: contraTneq ulcd => ->; rewrite unitr0.\nQed.\n\nLemma divpD p q : (p + q) %/ d = p %/ d + q %/ d.\nProof.\nhave/edivpP [] // : (p + q) = (p %/ d + q %/ d) * d + (p %% d + q %% d).\n  by rewrite mulrDl addrACA -!divp_eq.\napply: leq_ltn_trans (size_add _ _) _.\nrewrite gtn_max !ltn_modp andbb -lead_coef_eq0.\nby apply: contraTneq ulcd => ->; rewrite unitr0.\nQed.\n\nLemma mulpK q : (q * d) %/ d = q.\nProof.\ncase/esym/edivpP: (addr0 (q * d)); rewrite // size_poly0 size_poly_gt0.\nby rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0.\nQed.\n\nLemma mulKp q : (d * q) %/ d = q. Proof. by rewrite mulrC; apply: mulpK. Qed.\n\nLemma divp_addl_mul_small q r : size r < size d -> (q * d + r) %/ d = q.\nProof. by move=> srd; rewrite divpD (divp_small srd) addr0 mulpK. Qed.\n\nLemma modp_addl_mul_small q r : size r < size d -> (q * d + r) %% d = r.\nProof. by move=> srd; rewrite modpD modp_mull add0r modp_small. Qed.\n\nLemma divp_addl_mul q r : (q * d + r) %/ d = q + r %/ d.\nProof. by rewrite divpD mulpK. Qed.\n\nLemma divpp : d %/ d = 1. Proof. by rewrite -[d in d %/ _]mul1r mulpK. Qed.\n\nLemma leq_trunc_divp m : size (m %/ d * d) <= size m.\nProof.\ncase: (eqVneq d 0) ulcd => [->|dn0 _]; first by rewrite lead_coef0 unitr0.\nhave [->|q0] := eqVneq (m %/ d) 0; first by rewrite mul0r size_poly0 leq0n.\nrewrite {2}(divp_eq m) size_addl // size_mul // (polySpred q0) addSn /=.\nby rewrite ltn_addl // ltn_modp.\nQed.\n\nLemma dvdpP p : reflect (exists q, p = q * d) (d %| p).\nProof.\napply: (iffP idP) => [| [k ->]]; last by apply/eqP; rewrite modp_mull.\nby rewrite dvdp_eq; move/eqP->; exists (p %/ d).\nQed.\n\nLemma divpK p : d %| p -> p %/ d * d = p.\nProof. by rewrite dvdp_eq; move/eqP. Qed.\n\nLemma divpKC p : d %| p -> d * (p %/ d) = p.\nProof. by move=> ?; rewrite mulrC divpK. Qed.\n\nLemma dvdp_eq_div p q : d %| p -> (q == p %/ d) = (q * d == p).\nProof.\nmove/divpK=> {2}<-; apply/eqP/eqP; first by move->.\napply/mulIf; rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->.\nby rewrite unitr0.\nQed.\n\nLemma dvdp_eq_mul p q : d %| p -> (p == q * d) = (p %/ d == q).\nProof. by move=> dv_d_p; rewrite eq_sym -dvdp_eq_div // eq_sym. Qed.\n\nLemma divp_mulA p q : d %| q -> p * (q %/ d) = p * q %/ d.\nProof.\nmove=> hdm; apply/eqP; rewrite eq_sym -dvdp_eq_mul.\n  by rewrite -mulrA divpK.\nby move/divpK: hdm<-; rewrite mulrA dvdp_mull // dvdpp.\nQed.\n\nLemma divp_mulAC m n : d %| m -> m %/ d * n = m * n %/ d.\nProof. by move=> hdm; rewrite mulrC (mulrC m); apply: divp_mulA. Qed.\n\nLemma divp_mulCA p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d).\nProof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed.\n\nLemma modp_mul p q : (p * (q %% d)) %% d = (p * q) %% d.\nProof. by rewrite [q in RHS]divp_eq mulrDr modpD mulrA modp_mull add0r. Qed.\n\nEnd UnitDivisor.\n\nSection MoreUnitDivisor.\n\nVariable R : idomainType.\nVariable d : {poly R}.\nHypothesis ulcd : lead_coef d \\in GRing.unit.\n\nImplicit Types p q : {poly R}.\n\nLemma expp_sub m n : n <= m -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n.\nProof. by move/subnK=> {2}<-; rewrite exprD mulpK // lead_coef_exp unitrX. Qed.\n\nLemma divp_pmul2l p q : lead_coef q \\in GRing.unit -> d * p %/ (d * q) = p %/ q.\nProof.\nmove=> uq; rewrite {1}(divp_eq uq p) mulrDr mulrCA divp_addl_mul //; last first.\n  by rewrite lead_coefM unitrM_comm ?ulcd //; red; rewrite mulrC.\nhave dn0 : d != 0.\n  by rewrite -lead_coef_eq0; apply: contraTneq ulcd => ->; rewrite unitr0.\nhave qn0 : q != 0.\n  by rewrite -lead_coef_eq0; apply: contraTneq uq => ->; rewrite unitr0.\nhave dqn0 : d * q != 0 by rewrite mulf_eq0 negb_or dn0.\nsuff : size (d * (p %% q)) < size (d * q).\n  by rewrite ltnNge -divpN0 // negbK => /eqP ->; rewrite addr0.\nhave [-> | rn0] := eqVneq (p %% q) 0.\n  by rewrite mulr0 size_poly0 size_poly_gt0.\nby rewrite !size_mul // (polySpred dn0) !addSn /= ltn_add2l ltn_modp.\nQed.\n\nLemma divp_pmul2r p q : lead_coef p \\in GRing.unit -> q * d %/ (p * d) = q %/ p.\nProof. by move=> uq; rewrite -!(mulrC d) divp_pmul2l. Qed.\n\nLemma divp_divl r p q :\n    lead_coef r \\in GRing.unit -> lead_coef p \\in GRing.unit ->\n  q %/ p %/ r = q %/ (p * r).\nProof.\nmove=> ulcr ulcp.\nhave e : q = (q %/ p %/ r) * (p * r) + ((q %/ p) %% r * p + q %% p).\n  by rewrite addrA (mulrC p) mulrA -mulrDl; rewrite -divp_eq //; apply: divp_eq.\nhave pn0 : p != 0.\n  by rewrite -lead_coef_eq0; apply: contraTneq ulcp => ->; rewrite unitr0.\nhave rn0 : r != 0.\n  by rewrite -lead_coef_eq0; apply: contraTneq ulcr => ->; rewrite unitr0.\nhave s : size ((q %/ p) %% r * p + q %% p) < size (p * r).\n  have [-> | qn0] := eqVneq ((q %/ p) %% r) 0.\n    rewrite mul0r add0r size_mul // (polySpred rn0) addnS /=.\n    by apply: leq_trans (leq_addr _ _); rewrite ltn_modp.\n  rewrite size_addl mulrC.\n    by rewrite !size_mul // (polySpred pn0) !addSn /= ltn_add2l ltn_modp.\n  rewrite size_mul // (polySpred qn0) addnS /=.\n  by apply: leq_trans (leq_addr _ _); rewrite ltn_modp.\ncase: (edivpP _ e s) => //; rewrite lead_coefM unitrM_comm ?ulcp //.\nby red; rewrite mulrC.\nQed.\n\nLemma divpAC p q : lead_coef p \\in GRing.unit -> q %/ d %/ p = q %/ p %/ d.\nProof. by move=> ulcp; rewrite !divp_divl // mulrC. Qed.\n\nLemma modpZr c p : c \\in GRing.unit -> p %% (c *: d) = (p %% d).\nProof.\ncase: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !modp0.\nhave e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d).\n  by rewrite scalerCA scalerA mulVr // scale1r -(divp_eq ulcd).\nsuff s : size (p %% d) < size (c *: d).\n  by rewrite (modpP _ e s) // -mul_polyC lead_coefM lead_coefC unitrM cn0.\nby rewrite size_scale ?ltn_modp //; apply: contraTneq cn0 => ->; rewrite unitr0.\nQed.\n\nLemma divpZr c p : c \\in GRing.unit -> p %/ (c *: d) = c^-1 *: (p %/ d).\nProof.\ncase: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !divp0 scaler0.\nhave e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d).\n  by rewrite scalerCA scalerA mulVr // scale1r -(divp_eq ulcd).\nsuff s : size (p %% d) < size (c *: d).\n  by rewrite (divpP _ e s) // -mul_polyC lead_coefM lead_coefC unitrM cn0.\nby rewrite size_scale ?ltn_modp //; apply: contraTneq cn0 => ->; rewrite unitr0.\nQed.\n\nEnd MoreUnitDivisor.\n\nEnd IdomainUnit.\n\nModule Field.\n\nImport Ring ComRing UnitRing.\nInclude IdomainDefs.\nExport IdomainDefs.\nInclude CommonIdomain.\n\nSection FieldDivision.\n\nVariable F : fieldType.\n\nImplicit Type p q r d : {poly F}.\n\nLemma divp_eq p q : p = (p %/ q) * q + (p %% q).\nProof.\nhave [-> | qn0] := eqVneq q 0; first by rewrite modp0 mulr0 add0r.\nby apply: IdomainUnit.divp_eq; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divp_modpP p q d r : p = q * d + r -> size r < size d ->\n  q = (p %/ d) /\\ r = p %% d.\nProof.\nmove=> he hs; apply: IdomainUnit.edivpP => //; rewrite unitfE lead_coef_eq0.\nby rewrite -size_poly_gt0; apply: leq_trans hs.\nQed.\n\nLemma divpP p q d r : p = q * d + r -> size r < size d ->\n  q = (p %/ d).\nProof. by move/divp_modpP=> h; case/h. Qed.\n\nLemma modpP p q d r : p = q * d + r -> size r < size d -> r = (p %% d).\nProof. by move/divp_modpP=> h; case/h. Qed.\n\nLemma eqpfP p q : p %= q -> p = (lead_coef p / lead_coef q) *: q.\nProof.\nhave [->|nz_q] := eqVneq q 0; first by rewrite eqp0 scaler0 => /eqP ->.\nby apply/IdomainUnit.ucl_eqp_eq; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma dvdp_eq q p : (q %| p) = (p == p %/ q * q).\nProof.\nhave [-> | qn0] := eqVneq q 0; first by rewrite dvd0p mulr0 eq_sym.\nby apply: IdomainUnit.dvdp_eq; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma eqpf_eq p q : reflect (exists2 c, c != 0 & p = c *: q) (p %= q).\nProof.\napply: (iffP idP); last first.\n  case=> c nz_c ->; apply/eqpP.\n  by exists (1, c); rewrite ?scale1r ?oner_eq0.\nhave [->|nz_q] := eqVneq q 0.\n  by rewrite eqp0=> /eqP ->; exists 1; rewrite ?scale1r ?oner_eq0.\ncase/IdomainUnit.ulc_eqpP; first by rewrite unitfE lead_coef_eq0.\nby move=> c nz_c ->; exists c.\nQed.\n\nLemma modpZl c p q : (c *: p) %% q = c *: (p %% q).\nProof.\nhave [-> | qn0] := eqVneq q 0; first by rewrite !modp0.\nby apply: IdomainUnit.modpZl; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma mulpK p q : q != 0 -> p * q %/ q = p.\nProof. by move=> qn0; rewrite IdomainUnit.mulpK // unitfE lead_coef_eq0. Qed.\n\nLemma mulKp p q : q != 0 -> q * p %/ q = p.\nProof. by rewrite mulrC; apply: mulpK. Qed.\n\nLemma divpZl c p q : (c *: p) %/ q = c *: (p %/ q).\nProof.\nhave [-> | qn0] := eqVneq q 0; first by rewrite !divp0 scaler0.\nby apply: IdomainUnit.divpZl; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma modpZr c p d : c != 0 -> p %% (c *: d) = (p %% d).\nProof.\ncase: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !modp0.\nhave e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d).\n  by rewrite scalerCA scalerA mulVf // scale1r -divp_eq.\nsuff s : size (p %% d) < size (c *: d) by rewrite (modpP e s).\nby rewrite size_scale ?ltn_modp.\nQed.\n\nLemma divpZr c p d : c != 0 -> p %/ (c *: d) = c^-1 *: (p %/ d).\nProof.\ncase: (eqVneq d 0) => [-> | dn0 cn0]; first by rewrite scaler0 !divp0 scaler0.\nhave e : p = (c^-1 *: (p %/ d)) * (c *: d) + (p %% d).\n  by rewrite scalerCA scalerA mulVf // scale1r -divp_eq.\nsuff s : size (p %% d) < size (c *: d) by rewrite (divpP e s).\nby rewrite size_scale ?ltn_modp.\nQed.\n\nLemma eqp_modpl d p q : p %= q -> (p %% d) %= (q %% d).\nProof.\ncase/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e].\nby apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!modpZl e.\nQed.\n\nLemma eqp_divl d p q : p %= q -> (p %/ d) %= (q %/ d).\nProof.\ncase/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0 e].\nby apply/eqpP; exists (c1, c2); rewrite ?c1n0 // -!divpZl e.\nQed.\n\nLemma eqp_modpr d p q : p %= q -> (d %% p) %= (d %% q).\nProof.\ncase/eqpP=> [[c1 c2]] /andP [c1n0 c2n0 e].\nhave -> : p = (c1^-1 * c2) *: q by rewrite -scalerA -e scalerA mulVf // scale1r.\nby rewrite modpZr ?eqpxx // mulf_eq0 negb_or invr_eq0 c1n0.\nQed.\n\nLemma eqp_mod p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> p1 %% q1 %= p2 %% q2.\nProof. move=> e1 e2; exact: eqp_trans (eqp_modpl _ e1) (eqp_modpr _ e2). Qed.\n\nLemma eqp_divr (d m n : {poly F}) : m %= n -> (d %/ m) %= (d %/ n).\nProof.\ncase/eqpP=> [[c1 c2]] /andP [c1n0 c2n0 e].\nhave -> : m = (c1^-1 * c2) *: n by rewrite -scalerA -e scalerA mulVf // scale1r.\nby rewrite divpZr ?eqp_scale // ?invr_eq0 mulf_eq0 negb_or invr_eq0 c1n0.\nQed.\n\nLemma eqp_div p1 p2 q1 q2 : p1 %= p2 -> q1 %= q2 -> p1 %/ q1 %= p2 %/ q2.\nProof. move=> e1 e2; exact: eqp_trans (eqp_divl _ e1) (eqp_divr _ e2). Qed.\n\nLemma eqp_gdcor p q r : q %= r -> gdcop p q %= gdcop p r.\nProof.\nmove=> eqr; rewrite /gdcop (eqp_size eqr).\nmove: (size r)=> n; elim: n p q r eqr => [|n ihn] p q r; first by rewrite eqpxx.\nmove=> eqr /=; rewrite (eqp_coprimepl p eqr); case: ifP => _ //.\nexact/ihn/eqp_div/eqp_gcdl.\nQed.\n\nLemma eqp_gdcol p q r : q %= r -> gdcop q p %= gdcop r p.\nProof.\nmove=> eqr; rewrite /gdcop; move: (size p)=> n.\nelim: n p q r eqr {1 3}p (eqpxx p) => [|n ihn] p q r eqr s esp /=.\n  case: (eqVneq q 0) eqr => [-> | nq0 eqr] /=.\n    by rewrite eqp_sym eqp0 => ->; rewrite eqpxx.\n  by case: (eqVneq r 0) eqr nq0 => [->|]; rewrite ?eqpxx // eqp0 => ->.\nrewrite (eqp_coprimepr _ eqr) (eqp_coprimepl _ esp); case: ifP=> _ //.\nexact/ihn/eqp_div/eqp_gcd.\nQed.\n\nLemma eqp_rgdco_gdco q p : rgdcop q p %= gdcop q p.\nProof.\nrewrite /rgdcop /gdcop; move: (size p)=> n.\nelim: n p q {1 3}p {1 3}q (eqpxx p) (eqpxx q) => [|n ihn] p q s t /= sp tq.\n  case: (eqVneq t 0) tq => [-> | nt0 etq].\n    by rewrite eqp_sym eqp0 => ->; rewrite eqpxx.\n  by case: (eqVneq q 0) etq nt0 => [->|]; rewrite ?eqpxx // eqp0 => ->.\nrewrite rcoprimep_coprimep (eqp_coprimepl t sp) (eqp_coprimepr p tq).\ncase: ifP=> // _; apply: ihn => //; apply: eqp_trans (eqp_rdiv_div _ _) _.\nby apply: eqp_div => //; apply: eqp_trans (eqp_rgcd_gcd _ _) _; apply: eqp_gcd.\nQed.\n\nLemma modpD d p q : (p + q) %% d = p %% d + q %% d.\nProof.\nhave [-> | dn0] := eqVneq d 0; first by rewrite !modp0.\nby apply: IdomainUnit.modpD; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma modpN p q : (- p) %% q = - (p %% q).\nProof. by apply/eqP; rewrite -addr_eq0 -modpD addNr mod0p. Qed.\n\nLemma modNp p q : (- p) %% q = - (p %% q). Proof. exact: modpN. Qed.\n\nLemma divpD d p q : (p + q) %/ d = p %/ d + q %/ d.\nProof.\nhave [-> | dn0] := eqVneq d 0; first by rewrite !divp0 addr0.\nby apply: IdomainUnit.divpD; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divpN p q : (- p) %/ q = - (p %/ q).\nProof. by apply/eqP; rewrite -addr_eq0 -divpD addNr div0p. Qed.\n\nLemma divp_addl_mul_small d q r : size r < size d -> (q * d + r) %/ d = q.\nProof.\nmove=> srd; rewrite divpD (divp_small srd) addr0 mulpK // -size_poly_gt0.\nexact: leq_trans srd.\nQed.\n\nLemma modp_addl_mul_small d q r : size r < size d -> (q * d + r) %% d = r.\nProof. by move=> srd; rewrite modpD modp_mull add0r modp_small. Qed.\n\nLemma divp_addl_mul d q r : d != 0 -> (q * d + r) %/ d = q + r %/ d.\nProof. by move=> dn0; rewrite divpD mulpK. Qed.\n\nLemma divpp d : d != 0 -> d %/ d = 1.\nProof.\nby move=> dn0; apply: IdomainUnit.divpp; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma leq_trunc_divp d m : size (m %/ d * d) <= size m.\nProof.\nhave [-> | dn0] := eqVneq d 0; first by rewrite mulr0 size_poly0.\nby apply: IdomainUnit.leq_trunc_divp; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divpK d p : d %| p -> p %/ d * d = p.\nProof.\ncase: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite mulr0.\nby apply: IdomainUnit.divpK; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divpKC d p : d %| p -> d * (p %/ d) = p.\nProof. by move=> ?; rewrite mulrC divpK. Qed.\n\nLemma dvdp_eq_div d p q : d != 0 -> d %| p -> (q == p %/ d) = (q * d == p).\nProof.\nby move=> dn0; apply: IdomainUnit.dvdp_eq_div; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma dvdp_eq_mul d p q : d != 0 -> d %| p -> (p == q * d) = (p %/ d == q).\nProof. by move=> dn0 dv_d_p; rewrite eq_sym -dvdp_eq_div // eq_sym. Qed.\n\nLemma divp_mulA d p q : d %| q -> p * (q %/ d) = p * q %/ d.\nProof.\ncase: (eqVneq d 0) => [-> /dvd0pP -> | dn0]; first by rewrite !divp0 mulr0.\nby apply: IdomainUnit.divp_mulA; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divp_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d.\nProof. by move=> hdm; rewrite mulrC (mulrC m); apply: divp_mulA. Qed.\n\nLemma divp_mulCA d p q : d %| p -> d %| q -> p * (q %/ d) = q * (p %/ d).\nProof. by move=> hdp hdq; rewrite mulrC divp_mulAC // divp_mulA. Qed.\n\nLemma expp_sub d m n : d != 0 -> m >= n -> (d ^+ (m - n))%N = d ^+ m %/ d ^+ n.\nProof. by move=> dn0 /subnK=> {2}<-; rewrite exprD mulpK // expf_neq0. Qed.\n\nLemma divp_pmul2l d q p : d != 0 -> q != 0 -> d * p %/ (d * q) = p %/ q.\nProof.\nby move=> dn0 qn0; apply: IdomainUnit.divp_pmul2l; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divp_pmul2r d p q : d != 0 -> p != 0 -> q * d %/ (p * d) = q %/ p.\nProof. by move=> dn0 qn0; rewrite -!(mulrC d) divp_pmul2l. Qed.\n\nLemma divp_divl r p q : q %/ p %/ r = q %/ (p * r).\nProof.\nhave [-> | rn0] := eqVneq r 0; first by rewrite mulr0 !divp0.\nhave [-> | pn0] := eqVneq p 0; first by rewrite mul0r !divp0 div0p.\nby apply: IdomainUnit.divp_divl; rewrite unitfE lead_coef_eq0.\nQed.\n\nLemma divpAC d p q : q %/ d %/ p = q %/ p %/ d.\nProof. by rewrite !divp_divl // mulrC. Qed.\n\nLemma edivp_def p q : edivp p q = (0%N, p %/ q, p %% q).\nProof.\nrewrite Idomain.edivp_def; congr (_, _, _); rewrite /scalp 2!unlock /=.\nhave [-> | qn0] := eqVneq; first by rewrite lead_coef0 unitr0.\nby rewrite unitfE lead_coef_eq0 qn0 /=; case: (redivp_rec _ _ _ _) => [[]].\nQed.\n\nLemma divpE p q : p %/ q = (lead_coef q)^-(rscalp p q) *: (rdivp p q).\nProof.\nhave [-> | qn0] := eqVneq q 0; first by rewrite rdivp0 divp0 scaler0.\nby rewrite Idomain.divpE unitfE lead_coef_eq0 qn0.\nQed.\n\nLemma modpE p q : p %% q = (lead_coef q)^-(rscalp p q) *: (rmodp p q).\nProof.\nhave [-> | qn0] := eqVneq q 0.\n  by rewrite rmodp0 modp0 /rscalp unlock eqxx lead_coef0 expr0 invr1 scale1r.\nby rewrite Idomain.modpE unitfE lead_coef_eq0 qn0.\nQed.\n\nLemma scalpE p q : scalp p q = 0%N.\nProof.\nhave [-> | qn0] := eqVneq q 0; first by rewrite scalp0.\nby rewrite Idomain.scalpE unitfE lead_coef_eq0 qn0.\nQed.\n\n(* Just to have it without importing the weak theory *)\nLemma dvdpE p q : p %| q = rdvdp p q. Proof. exact: Idomain.dvdpE. Qed.\n\nVariant edivp_spec m d : nat * {poly F} * {poly F} -> Type :=\n  EdivpSpec n q r of\n  m = q * d + r & (d != 0) ==> (size r < size d) : edivp_spec m d (n, q, r).\n\nLemma edivpP m d : edivp_spec m d (edivp m d).\nProof.\nrewrite edivp_def; constructor; first exact: divp_eq.\nby apply/implyP=> dn0; rewrite ltn_modp.\nQed.\n\nLemma edivp_eq d q r : size r < size d -> edivp (q * d + r) d = (0%N, q, r).\nProof.\nmove=> srd; apply: Idomain.edivp_eq; rewrite // unitfE lead_coef_eq0.\nby rewrite -size_poly_gt0; apply: leq_trans srd.\nQed.\n\nLemma modp_mul p q m : (p * (q %% m)) %% m = (p * q) %% m.\nProof. by rewrite [in RHS](divp_eq q m) mulrDr modpD mulrA modp_mull add0r. Qed.\n\nLemma dvdpP p q : reflect (exists qq, p = qq * q) (q %| p).\nProof.\nhave [-> | qn0] := eqVneq q 0; last first.\n  by apply: IdomainUnit.dvdpP; rewrite unitfE lead_coef_eq0.\nby rewrite dvd0p; apply: (iffP eqP) => [->| [? ->]]; [exists 1|]; rewrite mulr0.\nQed.\n\nLemma Bezout_eq1_coprimepP p q :\n  reflect (exists u, u.1 * p + u.2 * q = 1) (coprimep p q).\nProof.\napply: (iffP idP)=> [hpq|]; last first.\n  by case=> [[u v]] /= e; apply/Bezout_coprimepP; exists (u, v); rewrite e eqpxx.\ncase/Bezout_coprimepP: hpq => [[u v]] /=.\ncase/eqpP=> [[c1 c2]] /andP /= [c1n0 c2n0] e.\nexists (c2^-1 *: (c1 *: u), c2^-1 *: (c1 *: v)); rewrite /= -!scalerAl.\nby rewrite -!scalerDr e scalerA mulVf // scale1r.\nQed.\n\nLemma dvdp_gdcor p q : q != 0 -> p %| (gdcop q p) * (q ^+ size p).\nProof.\nrewrite /gdcop => nz_q; have [n hsp] := ubnPleq (size p).\nelim: n => [|n IHn] /= in p hsp *; first by rewrite (negPf nz_q) mul0r dvdp0.\nhave [_ | ncop_pq] := ifPn; first by rewrite dvdp_mulr.\nhave g_gt1: 1 < size (gcdp p q).\n  rewrite ltn_neqAle eq_sym ncop_pq size_poly_gt0 gcdp_eq0.\n  by rewrite negb_and nz_q orbT.\nhave [-> | nz_p] := eqVneq p 0.\n  by rewrite div0p exprSr mulrA dvdp_mulr // IHn // size_poly0.\nhave le_d_p: size (p %/ gcdp p q) < size p.\n  rewrite size_divp -?size_poly_eq0 -(subnKC g_gt1) // add2n /=.\n  by rewrite polySpred // ltnS subSS leq_subr.\nrewrite -[p in p %| _](divpK (dvdp_gcdl p q)) exprSr mulrA.\nby rewrite dvdp_mul ?IHn ?dvdp_gcdr // -ltnS (leq_trans le_d_p).\nQed.\n\nLemma reducible_cubic_root p q :\n  size p <= 4 -> 1 < size q < size p -> q %| p -> {r | root p r}.\nProof.\nmove=> p_le4 /andP[]; rewrite leq_eqVlt eq_sym.\nhave [/poly2_root[x qx0] _ _ | _ /= q_gt2 p_gt_q] := size q =P 2%N.\n  by exists x; rewrite -!dvdp_XsubCl in qx0 *; apply: (dvdp_trans qx0).\ncase/dvdpP/sig_eqW=> r def_p; rewrite def_p.\nsuffices /poly2_root[x rx0]: size r = 2%N by exists x; rewrite rootM rx0.\nhave /norP[nz_r nz_q]: ~~ [|| r == 0 | q == 0].\n  by rewrite -mulf_eq0 -def_p -size_poly_gt0 (leq_ltn_trans _ p_gt_q).\nrewrite def_p size_mul // -subn1 leq_subLR ltn_subRL in p_gt_q p_le4.\nby apply/eqP; rewrite -(eqn_add2r (size q)) eqn_leq (leq_trans p_le4).\nQed.\n\nLemma cubic_irreducible p :\n  1 < size p <= 4 -> (forall x, ~~ root p x) -> irreducible_poly p.\nProof.\nmove=> /andP[p_gt1 p_le4] root'p; split=> // q sz_q_neq1 q_dv_p.\nhave nz_p: p != 0 by rewrite -size_poly_gt0 ltnW.\nhave nz_q: q != 0 by apply: contraTneq q_dv_p => ->; rewrite dvd0p.\nhave q_gt1: size q > 1 by rewrite ltn_neqAle eq_sym sz_q_neq1 size_poly_gt0.\nrewrite -dvdp_size_eqp // eqn_leq dvdp_leq //= leqNgt; apply/negP=> p_gt_q.\nby have [|x /idPn//] := reducible_cubic_root p_le4 _ q_dv_p; rewrite q_gt1.\nQed.\n\nSection FieldRingMap.\n\nVariable rR : ringType.\n\nVariable f : {rmorphism F -> rR}.\nLocal Notation \"p ^f\" := (map_poly f p) : ring_scope.\n\nImplicit Type a b : {poly F}.\n\nLemma redivp_map a b :\n  redivp a^f b^f = (rscalp a b, (rdivp a b)^f, (rmodp a b)^f).\nProof.\nrewrite /rdivp /rscalp /rmodp !unlock map_poly_eq0 size_map_poly.\nhave [// | q_nz] := ifPn; rewrite -(rmorph0 (map_poly_rmorphism f)) //.\nhave [m _] := ubnPeq (size a); elim: m 0%N 0 a => [|m IHm] qq r a /=.\n  rewrite -!mul_polyC !size_map_poly !lead_coef_map // -(map_polyXn f).\n  by rewrite -!(map_polyC f) -!rmorphM -rmorphB -rmorphD; case: (_ < _).\nrewrite -!mul_polyC !size_map_poly !lead_coef_map // -(map_polyXn f).\nby rewrite -!(map_polyC f) -!rmorphM -rmorphB -rmorphD /= IHm; case: (_ < _).\nQed.\n\nEnd FieldRingMap.\n\nSection FieldMap.\n\nVariable rR : idomainType.\n\nVariable f : {rmorphism F -> rR}.\nLocal Notation \"p ^f\" := (map_poly f p) : ring_scope.\n\nImplicit Type a b : {poly F}.\n\nLemma edivp_map a b :\n  edivp a^f b^f = (0%N, (a %/ b)^f, (a %% b)^f).\nProof.\nhave [-> | bn0] := eqVneq b 0.\n  rewrite (rmorph0 (map_poly_rmorphism f)) WeakIdomain.edivp_def !modp0 !divp0.\n  by rewrite (rmorph0 (map_poly_rmorphism f)) scalp0.\nrewrite unlock redivp_map lead_coef_map rmorph_unit; last first.\n  by rewrite unitfE lead_coef_eq0.\nrewrite modpE divpE !map_polyZ !rmorphV ?rmorphX // unitfE.\nby rewrite expf_neq0 // lead_coef_eq0.\nQed.\n\nLemma scalp_map p q : scalp p^f q^f = scalp p q.\nProof. by rewrite /scalp edivp_map edivp_def. Qed.\n\nLemma map_divp p q : (p %/ q)^f = p^f %/ q^f.\nProof. by rewrite /divp edivp_map edivp_def. Qed.\n\nLemma map_modp p q : (p %% q)^f = p^f %% q^f.\nProof. by rewrite /modp edivp_map edivp_def. Qed.\n\nLemma egcdp_map p q :\n  egcdp (map_poly f p) (map_poly f q)\n     = (map_poly f (egcdp p q).1, map_poly f (egcdp p q).2).\nProof.\nwlog le_qp: p q / size q <= size p.\n  move=> IH; have [/IH// | lt_qp] := leqP (size q) (size p).\n  have /IH := ltnW lt_qp; rewrite /egcdp !size_map_poly ltnW // leqNgt lt_qp /=.\n  by case: (egcdp_rec _ _ _) => u v [-> ->].\nrewrite /egcdp !size_map_poly {}le_qp; move: (size q) => n.\nelim: n => /= [|n IHn] in p q *; first by rewrite rmorph1 rmorph0.\nrewrite map_poly_eq0; have [_ | nz_q] := ifPn; first by rewrite rmorph1 rmorph0.\nrewrite -map_modp (IHn q (p %% q)); case: (egcdp_rec _ _ n) => u v /=.\nby rewrite map_polyZ lead_coef_map -rmorphX scalp_map rmorphB rmorphM -map_divp.\nQed.\n\nLemma dvdp_map p q : (p^f %| q^f) = (p %| q).\nProof. by rewrite /dvdp -map_modp map_poly_eq0. Qed.\n\nLemma eqp_map p q : (p^f %= q^f) = (p %= q).\nProof. by rewrite /eqp !dvdp_map. Qed.\n\nLemma gcdp_map p q : (gcdp p q)^f = gcdp p^f q^f.\nProof.\nwlog lt_p_q: p q / size p < size q.\n  move=> IHpq; case: (ltnP (size p) (size q)) => [|le_q_p]; first exact: IHpq.\n  rewrite gcdpE (gcdpE p^f) !size_map_poly ltnNge le_q_p /= -map_modp.\n  have [-> | q_nz] := eqVneq q 0; first by rewrite rmorph0 !gcdp0.\n  by rewrite IHpq ?ltn_modp.\nhave [m le_q_m] := ubnP (size q); elim: m => // m IHm in p q lt_p_q le_q_m *.\nrewrite gcdpE (gcdpE p^f) !size_map_poly lt_p_q -map_modp.\nhave [-> | q_nz] := eqVneq p 0; first by rewrite rmorph0 !gcdp0.\nby rewrite IHm ?(leq_trans lt_p_q) ?ltn_modp.\nQed.\n\nLemma coprimep_map p q : coprimep p^f q^f = coprimep p q.\nProof. by rewrite -!gcdp_eqp1 -eqp_map rmorph1 gcdp_map. Qed.\n\nLemma gdcop_rec_map p q n : (gdcop_rec p q n)^f = gdcop_rec p^f q^f n.\nProof.\nelim: n p q => [|n IH] => /= p q.\n  by rewrite map_poly_eq0; case: eqP; rewrite ?rmorph1 ?rmorph0.\nrewrite /coprimep -gcdp_map size_map_poly.\nby case: eqP => Hq0 //; rewrite -map_divp -IH.\nQed.\n\nLemma gdcop_map p q : (gdcop p q)^f = gdcop p^f q^f.\nProof. by rewrite /gdcop gdcop_rec_map !size_map_poly. Qed.\n\nEnd FieldMap.\n\nEnd FieldDivision.\n\nEnd Field.\n\nModule ClosedField.\n\nImport Field.\n\nSection closed.\n\nVariable F : closedFieldType.\n\nLemma root_coprimep (p q : {poly F}):\n  (forall x, root p x -> q.[x] != 0) -> coprimep p q.\nProof.\nmove=> Ncmn; rewrite -gcdp_eqp1 -size_poly_eq1; apply/closed_rootP.\nby case=> r; rewrite root_gcd !rootE=> /andP [/Ncmn/negPf->].\nQed.\n\nLemma coprimepP (p q : {poly F}):\n  reflect (forall x, root p x -> q.[x] != 0) (coprimep p q).\nProof. by apply: (iffP idP)=> [/coprimep_root|/root_coprimep]. Qed.\n\nEnd closed.\n\nEnd ClosedField.\n\nEnd Pdiv.\n\nExport Pdiv.Field.\n", "meta": {"author": "math-comp", "repo": "math-comp", "sha": "e39f9173b484f2e8e7f69f746a619dcc8f3abc1b", "save_path": "github-repos/coq/math-comp-math-comp", "path": "github-repos/coq/math-comp-math-comp/math-comp-e39f9173b484f2e8e7f69f746a619dcc8f3abc1b/mathcomp/algebra/polydiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.71306102266931}}
{"text": "(************************************************************************)\n(* Copyright 2007 Milad Niqui                                           *)\n(* This file is distributed under the terms of the                      *)\n(* GNU Lesser General Public License Version 2.1                        *)\n(* A copy of the license can be found at                                *)\n(*                  <http://www.gnu.org/licenses/lgpl.txt>              *)\n(************************************************************************)\n\nRequire Import Arith Omega.\n\nRequire Coq.Structures.OrderedTypeEx.\nRequire Coq.FSets.FSetList.\nModule NatSet := FSetList.Make(OrderedTypeEx.Nat_as_OT).\nImport NatSet.\n\nInfix \"++\" := add (at level 60, right associativity).\nNotation \"s [=] t\" := (Equal s t) (at level 70, no associativity).\n\nRequire Coq.FSets.FSetFacts Coq.FSets.FSetProperties.\nRequire Extraction.\n\nModule GeneralProperties := FSetProperties.Properties NatSet.\nImport GeneralProperties.\n\nSection problem_knows_not_refl.\n\nVariable town: t.\nVariable n:nat.\nVariable cardinality: cardinal town = 2*n+1.\n\nVariable knows: elt -> elt -> Prop. \n\nVariable knows_sym: forall m n, knows m n ->  knows n m.\nVariable knows_extensional:forall m n p, E.eq n p -> knows m n-> knows m p.\n\nVariable property: forall B, Subset B town -> cardinal B = n -> \n           {d:elt | In d (diff town B)/\\(forall b, In b B -> knows d b)}.\n\nLemma extendible_by_one:forall B', cardinal B' <= (cardinal town)-1 -> {d:elt| In d town /\\ ~(In d B')}.\nProof.\n clear knows knows_sym knows_extensional property.\n intros B' H_cardinal_town.\n assert (H_town:1<=(cardinal town)); [omega|].\n rewrite <- (diff_inter_cardinal town B') in H_cardinal_town.\n rewrite <- (diff_inter_cardinal town B') in H_town.\n assert (H_inter:cardinal (inter town B') <= cardinal B');\n  [apply (subset_cardinal);apply (inter_subset_2)|].\n generalize (le_trans _ _ _ H_inter H_cardinal_town); intro H1.\n assert (H2:1<=cardinal (diff town B')); [omega|].\n assert (H3:=(S_pred _ _ H2)).\n destruct (cardinal_inv_2 H3) as [d Hd].\n exists d; split.\n  apply diff_1 with B'; assumption.\n  apply diff_2 with town; assumption.\nQed.  \n\nLemma extendible_to_n:forall B', Subset B' town -> cardinal B' <= n -> \n     {B:t| cardinal B = n /\\  Subset B' B /\\ Subset B town}.  \nProof.\n intros B' H_sub H_B'_cardinal.\n assert (H_cardinal_aux_3:2*n<=(cardinal town)-1);[apply le_trans with (2*n); omega|].\n clear property.\n induction n in H_B'_cardinal, H_cardinal_aux_3 |- *.\n (* n = 0 *)\n generalize (sym_eq (le_n_O_eq _ H_B'_cardinal)); intro H_eq.\n generalize (empty_is_empty_1 (cardinal_inv_1 H_eq)).\n intro H_B'.\n exists empty; repeat split. \n  rewrite H_B'; apply subset_empty.\n  apply subset_empty.\n (* n = S n0 *)\n destruct (le_lt_eq_dec _ _ H_B'_cardinal) as [H_lt|H_le].\n  generalize (lt_n_Sm_le _ _ H_lt); clear H_lt; intro H_le.\n  assert (H_cardinal_town_2:2 * n0 <= cardinal town - 1);[omega|].\n  destruct (IHn0 H_le H_cardinal_town_2) as [C [HC1 [HC2 HC3]]].\n  assert (HC5:cardinal C <= cardinal town - 1).\n   rewrite HC1; apply le_trans with (2*(S n0));[omega| assumption].\n  destruct (extendible_by_one C HC5) as [d [Hd1 Hd2]].\n  exists (d ++ C).\n  repeat split.\n   rewrite (add_cardinal_2 Hd2); rewrite HC1; reflexivity.\n   apply subset_add_2; assumption.\n   apply subset_add_3; assumption.\n  \n  exists B'.\n  repeat split; trivial; apply subset_refl.\nQed.\n\n\n(** The following property, proven by induction, is the heart of the\nsolution, and is due to Tonny Hurkens. *)\nLemma inductive_invariant:forall m, m<= n ->\n   {B':t| Subset B' town /\\ cardinal B' = m /\\ forall b'0 b'1, In b'0 B' -> In b'1 B' -> ~(E.eq b'0 b'1) -> knows b'0 b'1}.\nProof.\n intros m.\n induction m; intros H_le.\n  (* 0 *)\n  exists empty.\n  repeat split.\n   apply subset_empty.\n   intros b'0 b'1 H0 H1; apply False_ind. \n   elim (FM.empty_iff b'0); intros H2 _; apply H2; assumption.\n  (* S n *)\n  assert (H_le0:=le_Sn_le _ _ H_le).\n  destruct (IHm H_le0) as [B' [H3' [H1 H2]]].\n  rewrite <- H1 in H_le0.\n  destruct (extendible_to_n B' H3' H_le0) as [B [HB1 [HB2 HB3]]].\n  destruct (property B HB3 HB1) as [d [Hd1 Hd2]].\n  exists (add d B'); repeat split.\n   (* subset of town *)\n   apply subset_add_3.\n   apply diff_1 with B; assumption.\n   apply subset_trans with B; assumption.\n   (* cardinality *)\n   rewrite <- H1.\n   apply add_cardinal_2.\n   intro Hd4.\n   generalize (in_subset Hd4 HB2).\n   apply diff_2 with town; assumption.\n(* second big goal *)\n   intros b'0 b'1 H_b'0 H_b'1 H_neq.\n   destruct ((proj1 (FM.add_iff B' d b'0)) H_b'0) as [H3|H3].\n    apply knows_sym; apply knows_extensional with d; trivial.\n    destruct ((proj1 (FM.add_iff B' d b'1)) H_b'1) as [H4|H4].\n     apply False_ind; apply H_neq; rewrite <- H3; assumption.\n     apply knows_sym. \n     apply Hd2; apply in_subset with B'; trivial.\n    destruct ((proj1 (FM.add_iff B' d b'1)) H_b'1) as [H4|H4].\n     apply knows_extensional with d; trivial.\n     apply knows_sym.\n     apply Hd2; apply in_subset with B'; trivial.\n     apply H2; assumption.\nQed.\n\nTheorem AMM11262: {e:elt | In e town /\\ forall u, In u town /\\ ~(E.eq u e)-> knows e u}.\nProof.\n destruct (inductive_invariant n (le_refl n)) as [B [HB1 [HB2 HB3]]].\n destruct (property B HB1 HB2) as [d [Hd1 Hd2]].\n set (C:=(diff town (d ++ B))).\n (* C subset town *)\n assert (H_susbset_C:Subset C town);\n [ subst C; apply subset_diff; apply subset_refl\n | ].\n (* inter town *) \n assert (H_inter_town: inter town (d ++ B)[=]d ++ B).\n  rewrite inter_sym; apply inter_subset_equal;\n  apply subset_add_3; trivial; apply diff_1 with B; assumption.\n (* ~ In d B *)\n assert (H_d_nin_B:~In d B); [apply diff_2 with town; assumption|].\n (* cardinal C = n *)\n assert (H_cardinal_C:cardinal C=n).\n  assert (H_aux:cardinal (inter town (d ++ B))=S n).\n   rewrite (@Equal_cardinal (inter town (d ++ B)) (d++B) H_inter_town);\n   rewrite (add_cardinal_2 H_d_nin_B); rewrite HB2; reflexivity.\n  generalize (diff_inter_cardinal town (d++B));\n  fold C; rewrite H_aux; rewrite cardinality; omega.\n \n destruct (property C H_susbset_C H_cardinal_C) as [e [He1 He2]].\n exists e.\n (* Subset (d++B) town *)\n assert (H_dB_town:Subset (d++B) town).\n  intros a Ha0; destruct ((proj1 (FM.add_iff B d a)) Ha0) as [Had|HaB].  \n   rewrite <- Had; apply diff_1 with B; assumption.\n   apply HB1; assumption.\n (* diff town C = d++B *)\n assert (H_diff:diff town C [=] d++B ).\n  unfold C; split; intro H_mem.\n   (* => *)\n   assert (H_a0:=diff_1 H_mem);\n   assert (H_a1:=diff_2 H_mem);\n   destruct (In_dec a (d++B)) as [H_a2|H_a2]; trivial;\n   apply False_ind; apply H_a1; exact (diff_3 H_a0 H_a2).\n   (* <= *)\n   destruct (In_dec a (diff town (d++B))) as [H_a2|H_a2].\n    apply False_ind; exact (diff_2 H_a2 H_mem). \n    apply diff_3; trivial; apply H_dB_town; assumption.\n (* In e (d++B) *)\n assert (H_e_dB:In e (d++B)); [rewrite <- H_diff; assumption|].\n\n split.\n  apply diff_1 with C; assumption...\n  intros u [Hu Hu'].\n  assert (H_town_part:town [=] (union C (d++B))).\n   rewrite <- (diff_inter_all town (d++B)); rewrite H_inter_town; apply equal_refl.\n   rewrite H_town_part in Hu.\n   destruct (union_1 Hu) as [HuC|HudB].\n    (* In u C *)\n    apply He2; assumption. \n    (* In u (d++B) *)\n    destruct ((proj1 (FM.add_iff B d u)) HudB) as [Hud|HuB].\n     (* d=u *)\n     apply knows_extensional with d; trivial.\n     apply knows_sym.\n     destruct ((proj1 (FM.add_iff B d e)) H_e_dB) as [Hed|HeB].\n      (* d=e *)\n      apply False_ind; apply Hu'; rewrite <- Hud; assumption.\n      (* In e B *)\n      apply Hd2; assumption.\n     (* In u B *)\n     destruct ((proj1 (FM.add_iff B d e)) H_e_dB) as [Hed|HeB].\n      (* d=e *) \n      apply knows_sym; apply knows_extensional with d; trivial;\n      apply knows_sym; apply Hd2; assumption.\n      (* In e B *)\n      apply HB3; assumption || contradict Hu'; auto with *.\nQed.\n\nEnd problem_knows_not_refl.\n\nExtraction \"amm11262\" AMM11262.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/amm11262/ascii_format/AMM11262.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7130610156329187}}
{"text": "(** * Perm: Basic Techniques for Permutations and Ordering *)\n\n(** Consider these algorithms and data structures:\n - sort a sequence of numbers;\n - finite maps from numbers to (arbitrary-type) data\n - finite maps from any ordered type to (arbitrary-type) data\n - priority queues: finding/deleting the highest number in a set\n\n To prove the correctness of such programs, we need to reason\n about less-than comparisons (for example, on integers) and about\n \"these two sets/sequences have the same contents\".  In this\n chapter, we introduce some techniques for reasoning about:\n - less-than comparisons on natural numbers\n - permutations (rearrangements of lists)\n Then, in later chapters, we'll apply these proof techniques\n to reasoning about algorithms and data structures.\n *)\n\nRequire Export Coq.Bool.Bool.\nRequire Export Coq.Arith.Arith.\nRequire Export Coq.Arith.EqNat.\nRequire Export Coq.omega.Omega.\nRequire Export Coq.Lists.List. \nExport ListNotations.\nRequire Export Permutation.\n\n(* ################################################################# *)\n(** * The Less-Than Order on the Natural Numbers *)\n\n(** These [Check] and [Locate] commands remind us about\n  _Propositional_ and the _Boolean_ less-than operators\n  in the Coq standard library. *)\n\nCheck Nat.lt.        (* : nat -> nat -> Prop *)\nCheck lt.             (* : nat -> nat -> Prop *)\nGoal Nat.lt = lt. Proof. reflexivity. Qed. (* They are the same *)\nCheck Nat.ltb.       (* : nat -> nat -> bool *)\nLocate \"_ < _\".  (* \"x < y\" := lt x y *)\nLocate \"<?\".     (* x <? y  := Nat.ltb x y *)\n\n(** We write [x < y] for the Proposition that [x] _is_ less than [y],\n    and we write [x <? y] for the computable _test_ that returns\n    [true] or [false] depending on whether [x<y].  The theorem that\n    [lt] is related in this way to [ltb] is this one: *)\n\nCheck Nat.ltb_lt.\n(* : forall n m : nat, (n <? m) = true <-> n < m *)\n\n(** For some reason, the Coq library has [ <? ] and [ <=? ] \n    notations, but is missing these three: *)\n\nNotation  \"a >=? b\" := (Nat.leb b a)\n                          (at level 70, only parsing) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a)\n                       (at level 70, only parsing) : nat_scope.\nNotation \" a =? b\"  := (beq_nat a b)\n                       (at level 70) : nat_scope.\n\n(* ================================================================= *)\n(** ** Relating [Prop] to [bool] *)\n\n(** The [reflect] relation connects a [Proposition] to a [Boolean]. *)\n\nPrint reflect.\n\n(** That is, [reflect P b] means that [P<->True] if and only if [b=true].\n     The way to use [reflect] is, for each of your operators, make a\n     lemma like these next three:\n*)\n\nLemma beq_reflect : forall x y, reflect (x = y) (x =? y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry.  apply beq_nat_true_iff.\nQed.\n\nLemma blt_reflect : forall x y, reflect (x < y) (x <? y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply Nat.ltb_lt.\nQed.\n\nLemma ble_reflect : forall x y, reflect (x <= y) (x <=? y).\nProof.\n  intros x y.\n  apply iff_reflect. symmetry. apply Nat.leb_le.\nQed.\n\n(** Here's an example of how you could use these lemmas.\n    Suppose you have this simple program, [(if a <? 5 then a else 2)],\n    and you want to prove that it evaluates to a number smaller than 6.\n    You can use [blt_reflect] \"by hand\": *)\n    \nExample reflect_example1: forall a, (if a<?5 then a else 2) < 6.\nProof. \n  intros.\n  destruct (blt_reflect a 5) as [H|H].\n  * (* Notice that [H] above the line has a [Prop]ositional\n       fact _related_ to [a<?5]*)\n     omega.  (* More explanation of [omega] later in this chapter. *)\n  * (* Notice that [H] above the line has a a _different_\n       [Prop]ositional fact. *)\n     apply not_lt in H.  (* This step is not necessary,\n          it just makes the hypothesis [H] look pretty *)\n     omega.\nQed.\n\n(** But there's another way to use [blt_reflect], etc: read on. *)\n\n(* ================================================================= *)\n(** ** Some Advanced Tactical Hacking *)\n(** You may skip ahead to \"Inversion/clear/subst\".\n     Right here, we build some machinery that you'll want to\n     _use_, but you won't need to know how to _build_ it.\n\n    Let's put several of these [reflect] lemmas into a Hint database,\n    called [bdestruct] because we'll use it in our boolean-destruction\n    tactic: *)\n\nHint Resolve blt_reflect ble_reflect beq_reflect : bdestruct.\n\n(** Our high-tech _boolean destruction_ tactic: *)\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n       [ | try first [apply not_lt in H | apply not_le in H]]].\n\n(** Here's a brief example of how to use [bdestruct].  There\n     are more examples later. *)\n\nExample reflect_example2: forall a, (if a<?5 then a else 2) < 6.\nProof. \n  intros.\n  bdestruct (a<?5).  (* instead of: [destruct (blt_reflect a 5) as [H|H]]. *)\n  * (* Notice that [H] above the line has a [Prop]ositional\n       fact _related_ to [a<?5]*)\n     omega.  (* More explanation of [omega] later in this chapter. *)\n  * (* Notice that [H] above the line has a a _different_\n       [Prop]ositional fact. We don't need to apply [not_lt],\n       as [bdestruct] has already done it. *)\n     omega.\nQed.\n\n(* ================================================================= *)\n(** ** [inversion] / [clear] / [subst] *)\n(** Coq's [inversion H] tactic is so good at extracting information\n    from the hypothesis [H] that [H] becomes completely redundant,\n    and one might as well [clear] it from the goal.  Then, since the\n    [inversion] typically creates some equality facts, why not then\n    [subst] ?   This motivates the following useful tactic, [inv]:  *)\n\nLtac inv H := inversion H; clear H; subst. \n\n(* ================================================================= *)\n(** ** Linear Integer Inequalities *)\n\n(** In our proofs about searching and sorting algorithms, we \n    sometimes have to reason about the consequences of \n    less-than and greater-than.  Here's a contrived example. *)\n\nModule Exploration1.\n\nTheorem omega_example1: \n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n\n(** Now, there's a hard way to prove this, and an easy way.\n    Here's the hard way. *)\n\n  (* try to remember the name of the lemma about negation and [<=] *)\n  Search (~ _ <= _ -> _). \n  apply not_le in H0.\n  (* try to remember the name of the transitivity lemma about [>] *)\n  Search (_ > _ -> _ > _ -> _ > _).  \n  apply gt_trans with j.\n  apply gt_trans with (k-3).\n  (* _OBVIOUSLY_, [k] is greater than [k-3].  But _OOPS_,\n     this is not actually true, because we are talking about\n     natural numbers with \"bogus subtraction.\" *)\nAbort.\n\nTheorem bogus_subtraction: ~ (forall k:nat, k > k - 3).\nProof.\n  (* [intro] introduces exactly one thing, like [intros ?] *)\n  intro.  \n  (* [specialize] applies a hypothesis to an argument *)\n  specialize (H O).  \n  simpl in H. inversion H.\nQed.\n\n(** With bogus subtraction, this omega_example1 theorem even True?\n    Yes it is; let's try again, the hard way, to find the proof. *)\n\nTheorem omega_example1: \n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof. (* try again! *)\n  intros.\n  apply not_le in H0.\n  unfold gt in H0.\n  unfold gt.\n  (* try to remember the name ... *)\n  Search (_ < _ -> _ <= _ -> _ < _).  \n  apply lt_le_trans with j.\n  apply H.\n  apply le_trans with (k-3).\n  Search (_ < _ -> _ <= _).\n  apply lt_le_weak.\n  auto.\n  apply le_minus.\nQed.  (* Oof!  That was exhausting and tedious.  *)\n\n(** And here's the easy way. *)\n\nTheorem omega_example2: \n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n  omega.\nQed.\n\n(** Here we have used the [omega] tactic, made available by importing\n    [Coq.omega.Omega] as we have done above.  Omega is an algorithm\n    for integer linear programming, invented in 1991 by William Pugh.\n    Because ILP is NP-complete, we might expect that this algorithm is\n    exponential-time in the worst case, and indeed that's true: if you\n    have [N] equations, it could take [2^N] time.  But in the typical\n    cases that result from reasoning about programs, omega is much\n    faster than that.  Coq's [omega] tactic is an implementation of\n    this algorithm that generates a machine-checkable Coq proof.  It\n    \"understands\" the types Z and nat, and these operators: [<] [=] [>] [<=]\n    [>=] [+] [-] [~], as well as multiplication by small integer\n    literals (such as 0,1,2,3...) and some uses of [\\/] and [/\\].\n\n    Omega does _not_ understand other operators.  It treats things\n    like [a*b] and [f x y] as if they were variables.  That is, it can\n    prove [f x y > a*b -> f x y + 3 >= a*b], in the same way it would\n    prove [u > v -> u+3 >= v]. \n\n    Now let's consider a silly little program: swap the first two\n    elements of a list, if they are out of order. *)\n\nDefinition maybe_swap (al: list nat) : list nat :=\n  match al with\n  | a :: b :: ar => if a >? b then b::a::ar else a::b::ar\n  | _ => al\n  end.\n\nExample maybe_swap_123:\n  maybe_swap [1; 2; 3] = [1; 2; 3].\nProof. reflexivity. Qed.\n\nExample maybe_swap_321:\n  maybe_swap [3; 2; 1] = [2; 3; 1].\nProof. reflexivity. Qed.\n\n(** In this program, we wrote [a>?b] instead of [a>b].  Why is that? *)\n\nCheck (1>2).  (* : Prop *)\nCheck (1>?2). (* : bool *)\n\n(** We cannot compute with elements of [Prop]: we need some kind of\n    constructible (and pattern-matchable) value.  For that we use\n    [bool]. *)\n\nLocate \">?\".  (* a >? b :=  ltb b a *)\n\n(** The name [ltb] stands for \"less-than boolean.\" *)\n\nPrint Nat.ltb.\n(* =  fun n m : nat => S n <=? m : nat -> nat -> bool  *)\nLocate \">=?\".\n\n(** Instead of defining an operator [Nat.geb], the standard library just\n    defines the notation for greater-or-equal-boolean as a\n    less-or-equal-boolean with the arguments swapped. *)\n\nLocate leb.\nPrint leb.\nPrint Nat.leb.  (* The computation to compare natural numbers. *)\n\n(** Here's a theorem: [maybe_swap] is idempotent -- that is, applying it\n    twice gives the same result as applying it once. *)\n\nTheorem maybe_swap_idempotent:\n  forall al, maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros.\n  destruct al as [ | a al].\n  simpl.\n  reflexivity.\n  destruct al as [ | b al].\n  simpl.\n  reflexivity.\n  simpl.\n\n  (** What do we do here?   We must proceed by case analysis on\n     whether a>b. *)\n\n  destruct (b <? a) eqn:H.\n  simpl.\n  destruct (a <? b) eqn:H0.\n\n  (** Now what?  Look at the hypotheses [H: b<a] and [H0: a<b]\n      above the line. They can't both be true.  In fact, [omega]\n      \"knows\" how to prove that kind of thing.  Let's try it: *)\n\n  try omega.\n\n  (** [omega] didn't work, because it operates on comparisons in [Prop],\n      such as [a>b]; not upon comparisons yielding bool, such as [a>?b].\n      We need to convert these comparisons to [Prop], so that we can use\n      [omega].\n\n      Actually, we don't \"need\" to.  Instead, we could reason directly\n      about these operations in [bool].  But that would be even more\n      tedious than the [omega_example1] proof.  Therefore: let's set up\n      some machinery so that we can use [omega] on boolean tests. *)\n\nAbort.\n\n(** Let's try again, a new way: *)\n\nTheorem maybe_swap_idempotent:\n  forall al, maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros.\n  destruct al as [ | a al].\n  simpl.\n  reflexivity.\n  destruct al as [ | b al].\n  simpl.\n  reflexivity.\n  simpl.\n\n  (** This is where we left off before. Now, watch: *)\n\n  destruct (blt_reflect b a).   (* THIS LINE *)\n  (* Notice that [b<a] is above the line as a Prop, not a bool.\n     Now, comment out THIS LINE, and uncomment THAT LINE.  *)\n  (* bdestruct (b <? a).    (* THAT LINE *) *)\n  (* THAT LINE, with [bdestruct], does the same thing as THIS LINE. *)\n* (* case b<a *)\n  simpl.\n  bdestruct (a <? b).\n  omega.\n\n  (** The [omega] tactic noticed that above the line we have an\n      arithmetic contradiction.  Perhaps it seems wasteful to bring\n      out the \"big gun\" to shoot this flea, but really, it's easier\n      than remembering the names of all those lemmas about\n      arithmetic! *)\n\n  reflexivity.\n* (* case a >= b *)\n  simpl.\n  bdestruct (b <? a).\n  omega.\n  reflexivity.\nQed.\n\n(** Moral of this story: When proving things about a program that uses\n    boolean comparisons [(a <? b)], use [bdestruct].  Then use\n    [omega].  Let's review that proof without all the comments. *)\n\nTheorem maybe_swap_idempotent':\n  forall al, maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros.\n  destruct al as [ | a al].\n  simpl.\n  reflexivity.\n  destruct al as [ | b al].\n  simpl.\n  reflexivity.\n  simpl.\n  bdestruct (b <? a).\n* \n  simpl.\n  bdestruct (a <? b).\n  omega.\n  reflexivity.\n*\n  simpl.\n  bdestruct (b <? a).\n  omega.\n  reflexivity.\nQed.\n\n(* ################################################################# *)\n(** * Permutations *)\n\n(** Another useful fact about [maybe_swap] is that it doesn't add or\n    remove elements from the list: it only reorders them.  We can say\n    that the output list is a _permutation_ of the input.  The Coq\n    [Permutation] library has an inductive definition of permutations,\n    along with some lemmas about them. *)\n\nLocate Permutation. (* Inductive Coq.Sorting.Permutation.Permutation *)\nCheck Permutation. (*  : forall {A : Type}, list A -> list A -> Prop *)\n\n(** We say \"list [al] is a permutation of list [bl]\",\n     written [Permutation al bl], if the elements of [al] can be \n     reordered (without insertions or deletions) to get the list [bl]. *)\n\nPrint Permutation. \n(*\n Inductive Permutation {A : Type} : list A -> list A -> Prop :=\n    perm_nil : Permutation [] []\n  | perm_skip : forall (x : A) (l l' : list A),\n                Permutation l l' -> \n                Permutation (x :: l) (x :: l')\n  | perm_swap : forall (x y : A) (l : list A),\n                Permutation (y :: x :: l) (x :: y :: l)\n  | perm_trans : forall l l' l'' : list A,\n                 Permutation l l' -> \n                 Permutation l' l'' -> \n                 Permutation l l''.\n*)\n\n(** You might wonder, \"is that really the right definition?\"  And\n    indeed, it's important that we get a right definition, because\n    [Permutation] is going to be used in the specification of\n    correctness of our searching and sorting algorithms.  If we have\n    the wrong specification, then all our proofs of \"correctness\" will\n    be useless.\n\n    It's not obvious that this is indeed the right specification of\n    permutations. (It happens to be true, but it's not obvious!)  In\n    order to gain confidence that we have the right specification, we\n    should use this specification to prove some properties that we\n    think permutations ought to have. *)\n\n(** **** Exercise: 2 stars (Permutation_properties)  *)\n(** Think of some properties of the [Permutation] relation and write\n    them down informally in English, or a mix of Coq and English.\n    Here are four to get you started:\n     - 1. If [Permutation al bl], then [length al = length bl].\n     - 2. If [Permutation al bl], then [Permutation bl al].\n     - 3. [[1;1]] is NOT a permutation of [[1;2]].\n     - 4. [[1;2;3;4]] IS a permutation of [[3;4;2;1]]. \n\n   YOUR ASSIGNMENT: Add three more properties. Write them here: *)\n\n(** Now, let's examine all the theorems in the Coq library about\n    permutations: *)\n\nSearch Permutation.  (* Browse through the results of this query! *)\n\n(** Which of the properties that you wrote down above have already\n    been proved as theorems by the Coq library developers?  Answer\n    here:\n\n*)\n(** [] *)\n\n(** Let's use the permutation rules in the library to prove the\n    following theorem. *)\n    \nExample butterfly: forall b u t e r f l y : nat,\n  Permutation ([b;u;t;t;e;r]++[f;l;y]) ([f;l;u;t;t;e;r]++[b;y]).\nProof.\n intros.\n (* Just to illustrate a method, let's group [u;t;t;e;r] together: *)\n change [b;u;t;t;e;r] with ([b]++[u;t;t;e;r]).\n change [f;l;u;t;t;e;r] with ([f;l]++[u;t;t;e;r]).\n remember [u;t;t;e;r] as utter. \n clear Hequtter.\n (* Next, let's cancel [utter] from both sides.  In order to do that,\n    we need to bring [utter] to the beginning of each list. *)\nCheck app_assoc.\n  rewrite <- app_assoc.\n  rewrite <- app_assoc.\nCheck perm_trans.\n  apply perm_trans with (utter ++ [f;l;y] ++ [b]).\n  rewrite (app_assoc utter [f;l;y]).\nCheck Permutation_app_comm.\n  apply Permutation_app_comm.\n eapply perm_trans.\n 2: apply Permutation_app_comm.\n  rewrite <- app_assoc.\nSearch (Permutation (_++_) (_++_)).\n apply Permutation_app_head.\n (* Now that [utter] is utterly removed from the goal, let's cancel [f;l]. *)\n eapply perm_trans.\n 2: apply Permutation_app_comm.\n simpl.\nCheck perm_skip.\n apply perm_skip.\n apply perm_skip.\nSearch (Permutation (_::_) (_::_)).\n apply perm_swap.\nQed.\n\n(** That example illustrates a general method for proving\n  permutations involving cons [::] and append [++].  \n  You identify some portion appearing in both sides;\n  you bring that portion to the front on each side using\n  lemmas such as [Permutation_app_comm] and [perm_swap],\n  with generous use of [perm_trans].  Then, you use\n  [perm_skip] to cancel a single element, or [Permutation_app_head]\n  to cancel an append-chunk. *)\n\n(** **** Exercise: 3 stars (permut_example)  *)\n(** Use the permutation rules in the library (see the [Search],\n    above) to prove the following theorem.  These [Check] commands\n   are a hint about what lemmas you'll need. *)\n\nCheck perm_skip.\nCheck Permutation_refl.\nCheck Permutation_app_comm.\nCheck app_assoc.\n\nExample permut_example: forall (a b: list nat),\n  Permutation (5::6::a++b) ((5::b)++(6::a++[])).\nProof.\n (* After you cancel the [5], then bring the [6] to the front... *)\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (not_a_permutation)  *)\n(** Prove that [[1;1]] is not a permutation of [[1;2]].\n    Hints are given as [Check] commands. *)\n\nCheck Permutation_cons_inv.\nCheck Permutation_length_1_inv.\n\nExample not_a_permutation:\n  ~ Permutation [1;1] [1;2].\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Back to [maybe_swap].  We prove that it doesn't lose or gain\n   any elements, only reorders them. *)\n\nTheorem maybe_swap_perm: forall al,\n  Permutation al (maybe_swap al).\nProof.\n  (* WORKED IN CLASS *)\n  intros.\n  destruct al as [ | a al].\n  simpl. apply Permutation_refl.\n  destruct al as [ | b al].\n  simpl. apply Permutation_refl.\n  simpl.\n  bdestruct (a>?b).\n  apply perm_swap.\n  apply Permutation_refl.\nQed.\n\n(** Now let us specify functional correctness of [maybe_swap]:\n    it rearranges the elements in such a way that the first is\n    less-or-equal than the second. *)\n\nDefinition first_le_second (al: list nat) : Prop :=\n  match al with\n  | a::b::_ => a <= b\n  | _ => True\n  end.\n\nTheorem maybe_swap_correct: forall al,\n    Permutation al (maybe_swap al) \n    /\\ first_le_second (maybe_swap al).\nProof.\n  intros.\n  split.\n  apply maybe_swap_perm.\n  (* WORKED IN CLASS *)\n  destruct al as [ | a al].\n  simpl. auto.\n  destruct al as [ | b al].\n  simpl. auto.\n  simpl.\n  bdestruct (b <? a).\n  simpl.\n  omega.\n  simpl.\n  omega.\nQed.\n\nEnd Exploration1.\n\n(* ################################################################# *)\n(** * Summary: Comparisons and Permutations *)\n\n(** To prove correctness of algorithms for sorting and searching,\n  we'll reason about comparisons and permutations using the tools\n  developed in this chapter.  The [maybe_swap] program is a tiny\n  little example of a sorting program.  The proof style in\n  [maybe_swap_correct] will be applied (at a larger scale) in\n  the next few chapters. *)\n\n(** **** Exercise: 2 stars (Forall_perm)  *)\n(** To close, a useful utility lemma.  Prove this by induction;\n  but is it induction on [al], or on [bl], or on [Permutation al bl],\n  or on [Forall f al]  ? *)\n\nTheorem Forall_perm: forall {A} (f: A -> Prop) al bl,\n  Permutation al bl ->\n  Forall f al -> Forall f bl.\nProof. \n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** $Date: 2017-08-25 14:01:08 -0400 (Fri, 25 Aug 2017) $ *)\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/wand_demo/vfa/Perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.8933094117351309, "lm_q1q2_score": 0.7130277694543553}}
{"text": "Require Import Nat Arith Bool.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := nil : Lst | cons : Nat -> Lst -> Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint even (even_arg0 : Nat) : bool\n           := match even_arg0 with\n              | zero => true\n              | succ n => negb (even n)\n              end.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : Lst) : Nat\n           := match len_arg0 with\n              | nil => zero\n              | cons x y => succ (len y)\n              end.\n\nTheorem theorem0 : forall (w : Lst) (z : Lst) (x : Nat) (y : Nat), eq (even (len (append w z))) (even (len (append w (cons x (cons y z))))).\nProof.\n  intros.\n  induction w.\n  - simpl. rewrite negb_involutive. reflexivity.\n  - simpl. rewrite IHw. reflexivity.\nQed.\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.7130192152147012}}
{"text": "(***************************************************************************)\n(* Formalization of the Chou, Gao and Zhang's decision procedure.          *)\n(* Julien Narboux (Julien@narboux.fr)                                      *)\n(* LIX/INRIA FUTURS 2004-2006                                              *)\n(* University of Strasbourg 2008                                           *)\n(***************************************************************************)\n\nRequire  Import area_method.\n\n(** The Pappus line theorem *)\n\nTheorem Pappus : forall A B C A' B' C' P Q R :Point,\n  on_line C A B ->\n  on_line C' A' B' ->\n  inter_ll P A' B A B' ->\n  inter_ll Q A C' A' C ->\n  inter_ll R B' C B C' ->\n  Col P Q R.\nProof.\narea_method.\nQed.\n\n(** This version uses an extra point *)\n\nTheorem Pappus_2 : forall A B C A' B' C' P Q R T:Point,\n  on_line C A B ->\n  on_line C' A' B' ->\n  inter_ll P A' B A B' ->\n  inter_ll Q A C' A' C ->\n  inter_ll R B' C B C' ->\n  inter_ll T B' C P Q ->\n  C<>R -> C<>T ->\n  parallel B' R C R ->\n  parallel B' T C T ->\n  B'**R / C**R = B'**T / C**T.\nProof.\narea_method.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "area-method", "sha": "84cab885dd166ba80049973590a1080524fd9306", "save_path": "github-repos/coq/coq-contribs-area-method", "path": "github-repos/coq/coq-contribs-area-method/area-method-84cab885dd166ba80049973590a1080524fd9306/examples_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7130042498303995}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := plus Zero (mult y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj86_coqofml_Hr1JEe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.7905303162021597, "lm_q1q2_score": 0.7129956417743234}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(******************************************************************************)\n(* This file deals with divisibility for natural numbers.                     *)\n(* It contains the definitions of:                                            *)\n(*      edivn m d   == the pair composed of the quotient and remainder        *)\n(*                     of the Euclidean division of m by d.                   *)\n(*          m %/ d  == quotient of the Euclidean division of m by d.          *)\n(*          m %% d  == remainder of the Euclidean division of m by d.         *)\n(*  m = n %[mod d]  <-> m equals n modulo d.                                  *)\n(*  m == n %[mod d] <=> m equals n modulo d (boolean version).                *)\n(*  m <> n %[mod d] <-> m differs from n modulo d.                            *)\n(*  m != n %[mod d] <=> m differs from n modulo d (boolean version).          *)\n(*           d %| m <=> d divides m.                                          *)\n(*         gcdn m n == the GCD of m and n.                                    *)\n(*        egcdn m n == the extended GCD (Bezout coefficient pair) of m and n. *)\n(*                     If egcdn m n = (u, v), then gcdn m n = m * u - n * v.  *)\n(*         lcmn m n == the LCM of m and n.                                    *)\n(*      coprime m n <=> m and n are coprime (:= gcdn m n == 1).               *)\n(*  chinese m n r s == witness of the chinese remainder theorem.              *)\n(* We adjoin an m to operator suffixes to indicate a nested %% (modn), as in  *)\n(*   modnDml : m %% d + n = m + n %[mod d].                                   *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** Euclidean division *)\n\nDefinition edivn_rec d :=\n  fix loop m q := if m - d is m'.+1 then loop m' q.+1 else (q, m).\n\nDefinition edivn m d := if d > 0 then edivn_rec d.-1 m 0 else (0, m).\n\nCoInductive edivn_spec m d : nat * nat -> Type :=\n  EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r).\n\nLemma edivnP m d : edivn_spec m d (edivn m d).\nProof.\nrewrite -{1}[m]/(0 * d + m) /edivn; case: d => //= d.\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //= le_mn.\nhave le_m'n: m - d <= n by rewrite (leq_trans (leq_subr d m)).\nrewrite subn_if_gt; case: ltnP => [// | le_dm].\nby rewrite -{1}(subnKC le_dm) -addSn addnA -mulSnr; apply: IHn.\nQed.\n\nLemma edivn_eq d q r : r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> lt_rd; have d_gt0: 0 < d by apply: leq_trans lt_rd.\ncase: edivnP lt_rd => q' r'; rewrite d_gt0 /=.\nwlog: q q' r r' / q <= q' by case/orP: (leq_total q q'); last symmetry; eauto.\nrewrite leq_eqVlt; case/predU1P => [-> /addnI-> |] //=.\nrewrite -(leq_pmul2r d_gt0) => /leq_add lt_qr eq_qr _ /lt_qr {lt_qr}.\nby rewrite addnS ltnNge mulSn -addnA eq_qr addnCA addnA leq_addr.\nQed.\n\nDefinition divn m d := (edivn m d).1.\n\nNotation \"m %/ d\" := (divn m d) : nat_scope.\n\n(* We redefine modn so that it is structurally decreasing. *)\n\nDefinition modn_rec d := fix loop m := if m - d is m'.+1 then loop m' else m.\n\nDefinition modn m d := if d > 0 then modn_rec d.-1 m else m.\n\nNotation \"m %% d\" := (modn m d) : nat_scope.\nNotation \"m = n %[mod d ]\" := (m %% d = n %% d) : nat_scope.\nNotation \"m == n %[mod d ]\" := (m %% d == n %% d) : nat_scope.\nNotation \"m <> n %[mod d ]\" := (m %% d <> n %% d) : nat_scope.\nNotation \"m != n %[mod d ]\" := (m %% d != n %% d) : nat_scope.\n\nLemma modn_def m d : m %% d = (edivn m d).2.\nProof.\ncase: d => //= d; rewrite /modn /edivn /=.\nelim: m {-2}m 0 (leqnn m) => [|n IHn] [|m] q //=.\nrewrite ltnS !subn_if_gt; case: (d <= m) => // le_mn.\nby apply: IHn; apply: leq_trans le_mn; apply: leq_subr.\nQed.\n\nLemma edivn_def m d : edivn m d = (m %/ d, m %% d).\nProof. by rewrite /divn modn_def; case: (edivn m d). Qed.\n\nLemma divn_eq m d : m = m %/ d * d + m %% d.\nProof. by rewrite /divn modn_def; case: edivnP. Qed.\n\nLemma div0n d : 0 %/ d = 0. Proof. by case: d. Qed.\nLemma divn0 m : m %/ 0 = 0. Proof. by []. Qed.\nLemma mod0n d : 0 %% d = 0. Proof. by case: d. Qed.\nLemma modn0 m : m %% 0 = m. Proof. by []. Qed.\n\nLemma divn_small m d : m < d -> m %/ d = 0.\nProof. by move=> lt_md; rewrite /divn (edivn_eq 0). Qed.\n\nLemma divnMDl q m d : 0 < d -> (q * d + m) %/ d = q + m %/ d.\nProof.\nmove=> d_gt0; rewrite {1}(divn_eq m d) addnA -mulnDl.\nby rewrite /divn edivn_eq // modn_def; case: edivnP; rewrite d_gt0.\nQed.\n\nLemma mulnK m d : 0 < d -> m * d %/ d = m.\nProof. by move=> d_gt0; rewrite -[m * d]addn0 divnMDl // div0n addn0. Qed.\n\nLemma mulKn m d : 0 < d -> d * m %/ d = m.\nProof. by move=> d_gt0; rewrite mulnC mulnK. Qed.\n\nLemma expnB p m n : p > 0 -> m >= n -> p ^ (m - n) = p ^ m %/ p ^ n.\nProof.\nby move=> p_gt0 /subnK{2}<-; rewrite expnD mulnK // expn_gt0 p_gt0.\nQed.\n\nLemma modn1 m : m %% 1 = 0.\nProof. by rewrite modn_def; case: edivnP => ? []. Qed.\n\nLemma divn1 m : m %/ 1 = m.\nProof. by rewrite {2}(@divn_eq m 1) // modn1 addn0 muln1. Qed.\n\nLemma divnn d : d %/ d = (0 < d).\nProof. by case: d => // d; rewrite -{1}[d.+1]muln1 mulKn. Qed.\n\nLemma divnMl p m d : p > 0 -> p * m %/ (p * d) = m %/ d.\nProof.\nmove=> p_gt0; case: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nrewrite {2}/divn; case: edivnP; rewrite d_gt0 /= => q r ->{m} lt_rd.\nrewrite mulnDr mulnCA divnMDl; last by rewrite muln_gt0 p_gt0.\nby rewrite addnC divn_small // ltn_pmul2l.\nQed.\nImplicit Arguments divnMl [p m d].\n\nLemma divnMr p m d : p > 0 -> m * p %/ (d * p) = m %/ d.\nProof. by move=> p_gt0; rewrite -!(mulnC p) divnMl. Qed.\nImplicit Arguments divnMr [p m d].\n\nLemma ltn_mod m d : (m %% d < d) = (0 < d).\nProof. by case: d => // d; rewrite modn_def; case: edivnP. Qed.\n\nLemma ltn_pmod m d : 0 < d -> m %% d < d.\nProof. by rewrite ltn_mod. Qed.\n\nLemma leq_trunc_div m d : m %/ d * d <= m.\nProof. by rewrite {2}(divn_eq m d) leq_addr. Qed.\n\nLemma leq_mod m d : m %% d  <= m.\nProof. by rewrite {2}(divn_eq m d) leq_addl. Qed.\n\nLemma leq_div m d : m %/ d <= m.\nProof.\nby case: d => // d; apply: leq_trans (leq_pmulr _ _) (leq_trunc_div _ _).\nQed.\n\nLemma ltn_ceil m d : 0 < d -> m < (m %/ d).+1 * d.\nProof.\nby move=> d_gt0; rewrite {1}(divn_eq m d) -addnS mulSnr leq_add2l ltn_mod.\nQed.\n\nLemma ltn_divLR m n d : d > 0 -> (m %/ d < n) = (m < n * d).\nProof.\nmove=> d_gt0; apply/idP/idP.\n  by rewrite -(leq_pmul2r d_gt0); apply: leq_trans (ltn_ceil _ _).\nrewrite !ltnNge -(@leq_pmul2r d n) //; apply: contra => le_nd_floor.\nexact: leq_trans le_nd_floor (leq_trunc_div _ _).\nQed.\n\nLemma leq_divRL m n d : d > 0 -> (m <= n %/ d) = (m * d <= n).\nProof. by move=> d_gt0; rewrite leqNgt ltn_divLR // -leqNgt. Qed.\n\nLemma ltn_Pdiv m d : 1 < d -> 0 < m -> m %/ d < m.\nProof. by move=> d_gt1 m_gt0; rewrite ltn_divLR ?ltn_Pmulr // ltnW. Qed.\n\nLemma divn_gt0 d m : 0 < d -> (0 < m %/ d) = (d <= m).\nProof. by move=> d_gt0; rewrite leq_divRL ?mul1n. Qed.\n\nLemma leq_div2r d m n : m <= n -> m %/ d <= n %/ d.\nProof.\nhave [-> //| d_gt0 le_mn] := posnP d.\nby rewrite leq_divRL // (leq_trans _ le_mn) -?leq_divRL.\nQed.\n\nLemma leq_div2l m d e : 0 < d -> d <= e -> m %/ e <= m %/ d.\nProof.\nmove/leq_divRL=> -> le_de.\nby apply: leq_trans (leq_trunc_div m e); apply: leq_mul.\nQed.\n\nLemma leq_divDl p m n : (m + n) %/ p <= m %/ p + n %/ p + 1.\nProof.\nhave [-> //| p_gt0] := posnP p; rewrite -ltnS -addnS ltn_divLR // ltnW //.\nrewrite {1}(divn_eq n p) {1}(divn_eq m p) addnACA !mulnDl -3!addnS leq_add2l.\nby rewrite mul2n -addnn -addSn leq_add // ltn_mod.\nQed.\n\nLemma geq_divBl k m p : k %/ p - m %/ p <= (k - m) %/ p + 1.\nProof.\nrewrite leq_subLR addnA; apply: leq_trans (leq_divDl _ _ _).\nby rewrite -maxnE leq_div2r ?leq_maxr.\nQed.\n\nLemma divnMA m n p : m %/ (n * p) = m %/ n %/ p. \nProof.\ncase: n p => [|n] [|p]; rewrite ?muln0 ?div0n //.\nrewrite {2}(divn_eq m (n.+1 * p.+1)) mulnA mulnAC !divnMDl //.\nby rewrite [_ %/ p.+1]divn_small ?addn0 // ltn_divLR // mulnC ltn_mod.\nQed.\n\nLemma divnAC m n p : m %/ n %/ p =  m %/ p %/ n.\nProof. by rewrite -!divnMA mulnC. Qed.\n\nLemma modn_small m d : m < d -> m %% d = m.\nProof. by move=> lt_md; rewrite {2}(divn_eq m d) divn_small. Qed.\n\nLemma modn_mod m d : m %% d = m %[mod d].\nProof. by case: d => // d; apply: modn_small; rewrite ltn_mod. Qed.\n\nLemma modnMDl p m d : p * d + m = m %[mod d].\nProof.\ncase: (posnP d) => [-> | d_gt0]; first by rewrite muln0.\nby rewrite {1}(divn_eq m d) addnA -mulnDl modn_def edivn_eq // ltn_mod.\nQed.\n\nLemma muln_modr {p m d} : 0 < p -> p * (m %% d) = (p * m) %% (p * d).\nProof.\nmove=> p_gt0; apply: (@addnI (p * (m %/ d * d))).\nby rewrite -mulnDr -divn_eq mulnCA -(divnMl p_gt0) -divn_eq.\nQed.\n\nLemma muln_modl {p m d} : 0 < p -> (m %% d) * p = (m * p) %% (d * p).\nProof. by rewrite -!(mulnC p); apply: muln_modr. Qed.\n\nLemma modnDl m d : d + m = m %[mod d].\nProof. by rewrite -{1}[d]mul1n modnMDl. Qed.\n\nLemma modnDr m d : m + d = m %[mod d].\nProof. by rewrite addnC modnDl. Qed.\n\nLemma modnn d : d %% d = 0.\nProof. by rewrite -{1}[d]addn0 modnDl mod0n. Qed.\n\nLemma modnMl p d : p * d %% d = 0.\nProof. by rewrite -[p * d]addn0 modnMDl mod0n. Qed.\n\nLemma modnMr p d : d * p %% d = 0.\nProof. by rewrite mulnC modnMl. Qed.\n\nLemma modnDml m n d : m %% d + n = m + n %[mod d].\nProof. by rewrite {2}(divn_eq m d) -addnA modnMDl. Qed.\n\nLemma modnDmr m n d : m + n %% d = m + n %[mod d].\nProof. by rewrite !(addnC m) modnDml. Qed.\n\nLemma modnDm m n d : m %% d  + n %% d = m + n %[mod d].\nProof. by rewrite modnDml modnDmr. Qed.\n\nLemma eqn_modDl p m n d : (p + m == p + n %[mod d]) = (m == n %[mod d]).\nProof.\ncase: d => [|d]; first by rewrite !modn0 eqn_add2l.\napply/eqP/eqP=> eq_mn; last by rewrite -modnDmr eq_mn modnDmr.\nrewrite -(modnMDl p m) -(modnMDl p n) !mulnSr -!addnA.\nby rewrite -modnDmr eq_mn modnDmr.\nQed.\n\nLemma eqn_modDr p m n d : (m + p == n + p %[mod d]) = (m == n %[mod d]).\nProof. by rewrite -!(addnC p) eqn_modDl. Qed.\n\nLemma modnMml m n d : m %% d * n = m * n %[mod d].\nProof. by rewrite {2}(divn_eq m d) mulnDl mulnAC modnMDl. Qed.\n\nLemma modnMmr m n d : m * (n %% d) = m * n %[mod d].\nProof. by rewrite !(mulnC m) modnMml. Qed.\n\nLemma modnMm m n d : m %% d * (n %% d) = m * n %[mod d].\nProof. by rewrite modnMml modnMmr. Qed.\n\nLemma modn2 m : m %% 2 = odd m.\nProof. by elim: m => //= m IHm; rewrite -addn1 -modnDml IHm; case odd. Qed.\n\nLemma divn2 m : m %/ 2 = m./2.\nProof. by rewrite {2}(divn_eq m 2) modn2 muln2 addnC half_bit_double. Qed.\n\nLemma odd_mod m d : odd d = false -> odd (m %% d) = odd m.\nProof.\nby move=> d_even; rewrite {2}(divn_eq m d) odd_add odd_mul d_even andbF.\nQed.\n\nLemma modnXm m n a : (a %% n) ^ m = a ^ m %[mod n].\nProof.\nby elim: m => // m IHm; rewrite !expnS -modnMmr IHm modnMml modnMmr.\nQed.\n\n(** Divisibility **)\n\nDefinition dvdn d m := m %% d == 0.\n\nNotation \"m %| d\" := (dvdn m d) : nat_scope.\n\nLemma dvdnP d m : reflect (exists k, m = k * d) (d %| m).\nProof.\napply: (iffP eqP) => [md0 | [k ->]]; last by rewrite modnMl.\nby exists (m %/ d); rewrite {1}(divn_eq m d) md0 addn0.\nQed.\nImplicit Arguments dvdnP [d m].\nPrenex Implicits dvdnP.\n\nLemma dvdn0 d : d %| 0.\nProof. by case: d. Qed.\n\nLemma dvd0n n : (0 %| n) = (n == 0).\nProof. by case: n. Qed.\n\nLemma dvdn1 d : (d %| 1) = (d == 1).\nProof. by case: d => [|[|d]] //; rewrite /dvdn modn_small. Qed.\n\nLemma dvd1n m : 1 %| m.\nProof. by rewrite /dvdn modn1. Qed.\n\nLemma dvdn_gt0 d m : m > 0 -> d %| m -> d > 0.\nProof. by case: d => // /prednK <-. Qed.\n\nLemma dvdnn m : m %| m.\nProof. by rewrite /dvdn modnn. Qed.\n\nLemma dvdn_mull d m n : d %| n -> d %| m * n.\nProof. by case/dvdnP=> n' ->; rewrite /dvdn mulnA modnMl. Qed.\n\nLemma dvdn_mulr d m n : d %| m -> d %| m * n.\nProof. by move=> d_m; rewrite mulnC dvdn_mull. Qed.\nHint Resolve dvdn0 dvd1n dvdnn dvdn_mull dvdn_mulr.\n\nLemma dvdn_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\nby move=> /dvdnP[q1 ->] /dvdnP[q2 ->]; rewrite mulnCA -mulnA 2?dvdn_mull.\nQed.\n\nLemma dvdn_trans n d m : d %| n -> n %| m -> d %| m.\nProof. by move=> d_dv_n /dvdnP[n1 ->]; apply: dvdn_mull. Qed.\n\nLemma dvdn_eq d m : (d %| m) = (m %/ d * d == m).\nProof.\napply/eqP/eqP=> [modm0 | <-]; last exact: modnMl.\nby rewrite {2}(divn_eq m d) modm0 addn0.\nQed.\n\nLemma dvdn2 n : (2 %| n) = ~~ odd n.\nProof. by rewrite /dvdn modn2; case (odd n). Qed.\n\nLemma dvdn_odd m n : m %| n -> odd n -> odd m.\nProof.\nby move=> m_dv_n; apply: contraTT; rewrite -!dvdn2 => /dvdn_trans->.\nQed.\n\nLemma divnK d m : d %| m -> m %/ d * d = m.\nProof. by rewrite dvdn_eq; move/eqP. Qed.\n\nLemma leq_divLR d m n : d %| m -> (m %/ d <= n) = (m <= n * d).\nProof. by case: d m => [|d] [|m] ///divnK=> {2}<-; rewrite leq_pmul2r. Qed.\n\nLemma ltn_divRL d m n : d %| m -> (n < m %/ d) = (n * d < m).\nProof. by move=> dv_d_m; rewrite !ltnNge leq_divLR. Qed.\n\nLemma eqn_div d m n : d > 0 -> d %| m -> (n == m %/ d) = (n * d == m).\nProof. by move=> d_gt0 dv_d_m; rewrite -(eqn_pmul2r d_gt0) divnK. Qed.\n\nLemma eqn_mul d m n : d > 0 -> d %| m -> (m == n * d) = (m %/ d == n).\nProof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqn_div // eq_sym. Qed.\n\nLemma divn_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d.\nProof.\ncase: d m => [[] //| d m] dv_d_m; apply/eqP.\nby rewrite eqn_div ?dvdn_mulr // mulnAC divnK.\nQed.\n\nLemma muln_divA d m n : d %| n -> m * (n %/ d) = m * n %/ d.\nProof. by move=> dv_d_m; rewrite !(mulnC m) divn_mulAC. Qed.\n\nLemma muln_divCA d m n : d %| m -> d %| n -> m * (n %/ d) = n * (m %/ d).\nProof. by move=> dv_d_m dv_d_n; rewrite mulnC divn_mulAC ?muln_divA. Qed.\n\nLemma divnA m n p : p %| n -> m %/ (n %/ p) = m * p %/ n.\nProof. by case: p => [|p] dv_n; rewrite -{2}(divnK dv_n) // divnMr. Qed.\n\nLemma modn_dvdm m n d : d %| m -> n %% m = n %[mod d].\nProof.\nby case/dvdnP=> q def_m; rewrite {2}(divn_eq n m) {3}def_m mulnA modnMDl.\nQed.\n\nLemma dvdn_leq d m : 0 < m -> d %| m -> d <= m.\nProof. by move=> m_gt0 /dvdnP[[|k] Dm]; rewrite Dm // leq_addr in m_gt0 *. Qed.\n\nLemma gtnNdvd n d : 0 < n -> n < d -> (d %| n) = false.\nProof. by move=> n_gt0 lt_nd; rewrite /dvdn eqn0Ngt modn_small ?n_gt0. Qed.\n\nLemma eqn_dvd m n : (m == n) = (m %| n) && (n %| m).\nProof.\ncase: m n => [|m] [|n] //; apply/idP/andP; first by move/eqP->; auto.\nrewrite eqn_leq => [[Hmn Hnm]]; apply/andP; have:= dvdn_leq; auto.\nQed.\n\nLemma dvdn_pmul2l p d m : 0 < p -> (p * d %| p * m) = (d %| m).\nProof. by case: p => // p _; rewrite /dvdn -muln_modr // muln_eq0. Qed.\nImplicit Arguments dvdn_pmul2l [p m d].\n\nLemma dvdn_pmul2r p d m : 0 < p -> (d * p %| m * p) = (d %| m).\nProof. by move=> p_gt0; rewrite -!(mulnC p) dvdn_pmul2l. Qed.\nImplicit Arguments dvdn_pmul2r [p m d].\n\nLemma dvdn_divLR p d m : 0 < p -> p %| d -> (d %/ p %| m) = (d %| m * p).\nProof. by move=> /(@dvdn_pmul2r p _ m) <- /divnK->. Qed.\n\nLemma dvdn_divRL p d m : p %| m -> (d %| m %/ p) = (d * p %| m).\nProof.\nhave [-> | /(@dvdn_pmul2r p d) <- /divnK-> //] := posnP p.\nby rewrite divn0 muln0 dvdn0.\nQed.\n\nLemma dvdn_div d m : d %| m -> m %/ d %| m.\nProof. by move/divnK=> {2}<-; apply: dvdn_mulr. Qed.\n\nLemma dvdn_exp2l p m n : m <= n -> p ^ m %| p ^ n.\nProof. by move/subnK <-; rewrite expnD dvdn_mull. Qed.\n\nLemma dvdn_Pexp2l p m n : p > 1 -> (p ^ m %| p ^ n) = (m <= n).\nProof.\nmove=> p_gt1; case: leqP => [|gt_n_m]; first exact: dvdn_exp2l.\nby rewrite gtnNdvd ?ltn_exp2l ?expn_gt0 // ltnW.\nQed.\n\nLemma dvdn_exp2r m n k : m %| n -> m ^ k %| n ^ k.\nProof. by case/dvdnP=> q ->; rewrite expnMn dvdn_mull. Qed.\n\nLemma dvdn_addr m d n : d %| m -> (d %| m + n) = (d %| n).\nProof. by case/dvdnP=> q ->; rewrite /dvdn modnMDl. Qed.\n\nLemma dvdn_addl n d m : d %| n -> (d %| m + n) = (d %| m).\nProof. by rewrite addnC; apply: dvdn_addr. Qed.\n\nLemma dvdn_add d m n : d %| m -> d %| n -> d %| m + n.\nProof. by move/dvdn_addr->. Qed.\n\nLemma dvdn_add_eq d m n : d %| m + n -> (d %| m) = (d %| n).\nProof. by move=> dv_d_mn; apply/idP/idP => [/dvdn_addr | /dvdn_addl] <-. Qed.\n\nLemma dvdn_subr d m n : n <= m -> d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> le_n_m dv_d_m; apply: dvdn_add_eq; rewrite subnK. Qed.\n\nLemma dvdn_subl d m n : n <= m -> d %| n -> (d %| m - n) = (d %| m).\nProof. by move=> le_n_m dv_d_m; rewrite -(dvdn_addl _ dv_d_m) subnK. Qed.\n\nLemma dvdn_sub d m n : d %| m -> d %| n -> d %| m - n.\nProof.\nby case: (leqP n m) => [le_nm /dvdn_subr <- // | /ltnW/eqnP ->]; rewrite dvdn0.\nQed.\n\nLemma dvdn_exp k d m : 0 < k -> d %| m -> d %| (m ^ k).\nProof. by case: k => // k _ d_dv_m; rewrite expnS dvdn_mulr. Qed.\n\nHint Resolve dvdn_add dvdn_sub dvdn_exp.\n\nLemma eqn_mod_dvd d m n : n <= m -> (m == n %[mod d]) = (d %| m - n).\nProof.\nby move=> le_mn; rewrite -{1}[n]add0n -{1}(subnK le_mn) eqn_modDr mod0n.\nQed.\n\nLemma divnDl m n d : d %| m -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by case: d => // d /divnK{1}<-; rewrite divnMDl. Qed.\n\nLemma divnDr m n d : d %| n -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by move=> dv_n; rewrite addnC divnDl // addnC. Qed.\n\n(***********************************************************************)\n(*   A function that computes the gcd of 2 numbers                     *)\n(***********************************************************************)\n\nFixpoint gcdn_rec m n :=\n  let n' := n %% m in if n' is 0 then m else\n  if m - n'.-1 is m'.+1 then gcdn_rec (m' %% n') n' else n'.\n\nDefinition gcdn := nosimpl gcdn_rec.\n\nLemma gcdnE m n : gcdn m n = if m == 0 then n else gcdn (n %% m) m.\nProof.\nrewrite /gcdn; elim: m {-2}m (leqnn m) n => [|s IHs] [|m] le_ms [|n] //=.\ncase def_n': (_ %% _) => // [n'].\nhave{def_n'} lt_n'm: n' < m by rewrite -def_n' -ltnS ltn_pmod.\nrewrite {}IHs ?(leq_trans lt_n'm) // subn_if_gt ltnW //=; congr gcdn_rec.\nby rewrite -{2}(subnK (ltnW lt_n'm)) -addnS modnDr.\nQed.\n\nLemma gcdnn : idempotent gcdn.\nProof. by case=> // n; rewrite gcdnE modnn. Qed.\n\nLemma gcdnC : commutative gcdn.\nProof.\nmove=> m n; wlog lt_nm: m n / n < m.\n  by case: (ltngtP n m) => [||-> //]; last symmetry; auto.\nby rewrite gcdnE -{1}(ltn_predK lt_nm) modn_small.\nQed.\n\nLemma gcd0n : left_id 0 gcdn. Proof. by case. Qed.\nLemma gcdn0 : right_id 0 gcdn. Proof. by case. Qed.\n\nLemma gcd1n : left_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnE modn1. Qed.\n\nLemma gcdn1 : right_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnC gcd1n. Qed.\n\nLemma dvdn_gcdr m n : gcdn m n %| n.\nProof.\nelim: m {-2}m (leqnn m) n => [|s IHs] [|m] le_ms [|n] //.\nrewrite gcdnE; case def_n': (_ %% _) => [|n']; first by rewrite /dvdn def_n'.\nhave lt_n's: n' < s by rewrite -ltnS (leq_trans _ le_ms) // -def_n' ltn_pmod.\nrewrite /= (divn_eq n.+1 m.+1) def_n' dvdn_addr ?dvdn_mull //; last exact: IHs.\nby rewrite gcdnE /= IHs // (leq_trans _ lt_n's) // ltnW // ltn_pmod.\nQed.\n\nLemma dvdn_gcdl m n : gcdn m n %| m.\nProof. by rewrite gcdnC dvdn_gcdr. Qed.\n\nLemma gcdn_gt0 m n : (0 < gcdn m n) = (0 < m) || (0 < n).\nProof.\nby case: m n => [|m] [|n] //; apply: (@dvdn_gt0 _ m.+1) => //; apply: dvdn_gcdl.\nQed.\n\nLemma gcdnMDl k m n : gcdn m (k * m + n) = gcdn m n.\nProof. by rewrite !(gcdnE m) modnMDl mulnC; case: m. Qed.\n\nLemma gcdnDl m n : gcdn m (m + n) = gcdn m n.\nProof. by rewrite -{2}(mul1n m) gcdnMDl. Qed.\n\nLemma gcdnDr m n : gcdn m (n + m) = gcdn m n.\nProof. by rewrite addnC gcdnDl. Qed.\n\nLemma gcdnMl n m : gcdn n (m * n) = n.\nProof. by case: n => [|n]; rewrite gcdnE modnMl gcd0n. Qed.\n\nLemma gcdnMr n m : gcdn n (n * m) = n.\nProof. by rewrite mulnC gcdnMl. Qed.\n\nLemma gcdn_idPl {m n} : reflect (gcdn m n = m) (m %| n).\nProof.\nby apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (gcdnMl, dvdn_gcdr).\nQed.\n\nLemma gcdn_idPr {m n} : reflect (gcdn m n = n) (n %| m).\nProof. by rewrite gcdnC; apply: gcdn_idPl. Qed.\n\nLemma expn_min e m n : e ^ minn m n = gcdn (e ^ m) (e ^ n).\nProof.\nrewrite /minn; case: leqP; [rewrite gcdnC | move/ltnW];\n  by move/(dvdn_exp2l e)/gcdn_idPl.\nQed.\n\nLemma gcdn_modr m n : gcdn m (n %% m) = gcdn m n.\nProof. by rewrite {2}(divn_eq n m) gcdnMDl. Qed.\n\nLemma gcdn_modl m n : gcdn (m %% n) n = gcdn m n.\nProof. by rewrite !(gcdnC _ n) gcdn_modr. Qed.\n\n(* Extended gcd, which computes Bezout coefficients. *)\n\nFixpoint Bezout_rec km kn qs :=\n  if qs is q :: qs' then Bezout_rec kn (NatTrec.add_mul q kn km) qs'\n  else (km, kn).\n\nFixpoint egcdn_rec m n s qs :=\n  if s is s'.+1 then\n    let: (q, r) := edivn m n in\n    if r > 0 then egcdn_rec n r s' (q :: qs) else\n    if odd (size qs) then qs else q.-1 :: qs\n  else [::0].\n\nDefinition egcdn m n := Bezout_rec 0 1 (egcdn_rec m n n [::]).\n\nCoInductive egcdn_spec m n : nat * nat -> Type :=\n  EgcdnSpec km kn of km * m = kn * n + gcdn m n & kn * gcdn m n < m :\n    egcdn_spec m n (km, kn).\n\nLemma egcd0n n : egcdn 0 n = (1, 0).\nProof. by case: n. Qed.\n\nLemma egcdnP m n : m > 0 -> egcdn_spec m n (egcdn m n).\nProof.\nrewrite /egcdn; have: (n, m) = Bezout_rec n m [::] by [].\ncase: (posnP n) => [-> /=|]; first by split; rewrite // mul1n gcdn0.\nmove: {2 6}n {4 6}n {1 4}m [::] (ltnSn n) => s n0 m0.\nelim: s n m => [[]//|s IHs] n m qs /= le_ns n_gt0 def_mn0 m_gt0.\ncase: edivnP => q r def_m; rewrite n_gt0 /= => lt_rn.\ncase: posnP => [r0 {s le_ns IHs lt_rn}|r_gt0]; last first.\n  by apply: IHs => //=; [rewrite (leq_trans lt_rn) | rewrite natTrecE -def_m].\nrewrite {r}r0 addn0 in def_m; set b := odd _; pose d := gcdn m n.\npose km := ~~ b : nat; pose kn := if b then 1 else q.-1.\nrewrite (_ : Bezout_rec _ _ _ = Bezout_rec km kn qs); last first.\n  by rewrite /kn /km; case: (b) => //=; rewrite natTrecE addn0 muln1.\nhave def_d: d = n by rewrite /d def_m gcdnC gcdnE modnMl gcd0n -[n]prednK.\nhave: km * m + 2 * b * d = kn * n + d.\n  rewrite {}/kn {}/km def_m def_d -mulSnr; case: b; rewrite //= addn0 mul1n.\n  by rewrite prednK //; apply: dvdn_gt0 m_gt0 _; rewrite def_m dvdn_mulr.\nhave{def_m}: kn * d <= m.\n  have q_gt0 : 0 < q by rewrite def_m muln_gt0 n_gt0 ?andbT in m_gt0.\n  by rewrite /kn; case b; rewrite def_d def_m leq_pmul2r // leq_pred.\nhave{def_d}: km * d <= n by rewrite -[n]mul1n def_d leq_pmul2r // leq_b1.\nmove: km {q}kn m_gt0 n_gt0 def_mn0; rewrite {}/d {}/b.\nelim: qs m n => [|q qs IHq] n r kn kr n_gt0 r_gt0 /=.\n  case=> -> -> {m0 n0}; rewrite !addn0 => le_kn_r _ def_d; split=> //.\n  have d_gt0: 0 < gcdn n r by rewrite gcdn_gt0 n_gt0.\n  have: 0 < kn * n by rewrite def_d addn_gt0 d_gt0 orbT.\n  rewrite muln_gt0 n_gt0 andbT; move/ltn_pmul2l <-.\n  by rewrite def_d -addn1 leq_add // mulnCA leq_mul2l le_kn_r orbT.\nrewrite !natTrecE; set m:= _ + r; set km := _ * _ + kn; pose d := gcdn m n.\nhave ->: gcdn n r = d by rewrite [d]gcdnC gcdnMDl.\nhave m_gt0: 0 < m by rewrite addn_gt0 r_gt0 orbT.\nhave d_gt0: 0 < d by rewrite gcdn_gt0 m_gt0.\nmove/IHq=> {IHq} IHq le_kn_r le_kr_n def_d; apply: IHq => //; rewrite -/d.\n  by rewrite mulnDl leq_add // -mulnA leq_mul2l le_kr_n orbT.\napply: (@addIn d); rewrite -!addnA addnn addnCA mulnDr -addnA addnCA.\nrewrite /km mulnDl mulnCA mulnA -addnA; congr (_ + _).\nby rewrite -def_d addnC -addnA -mulnDl -mulnDr addn_negb -mul2n.\nQed.\n\nLemma Bezoutl m n : m > 0 -> {a | a < m & m %| gcdn m n + a * n}.\nProof.\nmove=> m_gt0; case: (egcdnP n m_gt0) => km kn def_d lt_kn_m.\nexists kn; last by rewrite addnC -def_d dvdn_mull.\napply: leq_ltn_trans lt_kn_m.\nby rewrite -{1}[kn]muln1 leq_mul2l gcdn_gt0 m_gt0 orbT.\nQed.\n\nLemma Bezoutr m n : n > 0 -> {a | a < n & n %| gcdn m n + a * m}.\nProof. by rewrite gcdnC; apply: Bezoutl. Qed.\n\n(* Back to the gcd. *)\n\nLemma dvdn_gcd p m n : p %| gcdn m n = (p %| m) && (p %| n).\nProof.\napply/idP/andP=> [dv_pmn | [dv_pm dv_pn]].\n  by rewrite !(dvdn_trans dv_pmn) ?dvdn_gcdl ?dvdn_gcdr.\ncase (posnP n) => [->|n_gt0]; first by rewrite gcdn0.\ncase: (Bezoutr m n_gt0) => // km _ /(dvdn_trans dv_pn).\nby rewrite dvdn_addl // dvdn_mull.\nQed.\n\nLemma gcdnAC : right_commutative gcdn.\nProof.\nsuffices dvd m n p: gcdn (gcdn m n) p %| gcdn (gcdn m p) n.\n  by move=> m n p; apply/eqP; rewrite eqn_dvd !dvd.\nrewrite !dvdn_gcd dvdn_gcdr.\nby rewrite !(dvdn_trans (dvdn_gcdl _ p)) ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma gcdnA : associative gcdn.\nProof. by move=> m n p; rewrite !(gcdnC m) gcdnAC. Qed.\n\nLemma gcdnCA : left_commutative gcdn.\nProof. by move=> m n p; rewrite !gcdnA (gcdnC m). Qed.\n\nLemma gcdnACA : interchange gcdn gcdn.\nProof. by move=> m n p q; rewrite -!gcdnA (gcdnCA n). Qed.\n\nLemma muln_gcdr : right_distributive muln gcdn.\nProof.\nmove=> p m n; case: (posnP p) => [-> //| p_gt0].\nelim: {m}m.+1 {-2}m n (ltnSn m) => // s IHs m n; rewrite ltnS => le_ms.\nrewrite gcdnE [rhs in _ = rhs]gcdnE muln_eq0 (gtn_eqF p_gt0) -muln_modr //=.\nby case: posnP => // m_gt0; apply: IHs; apply: leq_trans le_ms; apply: ltn_pmod.\nQed.\n\nLemma muln_gcdl : left_distributive muln gcdn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_gcdr. Qed.\n\nLemma gcdn_def d m n :\n    d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) ->\n  gcdn m n = d.\nProof.\nmove=> dv_dm dv_dn gdv_d; apply/eqP.\nby rewrite eqn_dvd dvdn_gcd dv_dm dv_dn gdv_d ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma muln_divCA_gcd n m : n * (m %/ gcdn n m)  = m * (n %/ gcdn n m).\nProof. by rewrite muln_divCA ?dvdn_gcdl ?dvdn_gcdr. Qed.\n\n(* We derive the lcm directly. *)\n\nDefinition lcmn m n := m * n %/ gcdn m n.\n\nLemma lcmnC : commutative lcmn.\nProof. by move=> m n; rewrite /lcmn mulnC gcdnC. Qed.\n\nLemma lcm0n : left_zero 0 lcmn.  Proof. by move=> n; apply: div0n. Qed.\nLemma lcmn0 : right_zero 0 lcmn. Proof. by move=> n; rewrite lcmnC lcm0n. Qed.\n\nLemma lcm1n : left_id 1 lcmn.\nProof. by move=> n; rewrite /lcmn gcd1n mul1n divn1. Qed.\n\nLemma lcmn1 : right_id 1 lcmn.\nProof. by move=> n; rewrite lcmnC lcm1n. Qed.\n\nLemma muln_lcm_gcd m n : lcmn m n * gcdn m n = m * n.\nProof. by apply/eqP; rewrite divnK ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma lcmn_gt0 m n : (0 < lcmn m n) = (0 < m) && (0 < n).\nProof. by rewrite -muln_gt0 ltn_divRL ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma muln_lcmr : right_distributive muln lcmn.\nProof.\ncase=> // m n p; rewrite /lcmn -muln_gcdr -!mulnA divnMl // mulnCA.\nby rewrite muln_divA ?dvdn_mull ?dvdn_gcdr.\nQed.\n\nLemma muln_lcml : left_distributive muln lcmn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_lcmr. Qed.\n\nLemma lcmnA : associative lcmn.\nProof.\nmove=> m n p; rewrite {1 3}/lcmn mulnC !divn_mulAC ?dvdn_mull ?dvdn_gcdr //.\nrewrite -!divnMA ?dvdn_mulr ?dvdn_gcdl // mulnC mulnA !muln_gcdr.\nby rewrite ![_ * lcmn _ _]mulnC !muln_lcm_gcd !muln_gcdl -!(mulnC m) gcdnA.\nQed.\n\nLemma lcmnCA : left_commutative lcmn.\nProof. by move=> m n p; rewrite !lcmnA (lcmnC m). Qed.\n\nLemma lcmnAC : right_commutative lcmn.\nProof. by move=> m n p; rewrite -!lcmnA (lcmnC n). Qed.\n\nLemma lcmnACA : interchange lcmn lcmn.\nProof. by move=> m n p q; rewrite -!lcmnA (lcmnCA n). Qed.\n\nLemma dvdn_lcml d1 d2 : d1 %| lcmn d1 d2.\nProof. by rewrite /lcmn -muln_divA ?dvdn_gcdr ?dvdn_mulr. Qed.\n\nLemma dvdn_lcmr d1 d2 : d2 %| lcmn d1 d2.\nProof. by rewrite lcmnC dvdn_lcml. Qed.\n\nLemma dvdn_lcm d1 d2 m : lcmn d1 d2 %| m = (d1 %| m) && (d2 %| m).\nProof.\ncase: d1 d2 => [|d1] [|d2]; try by case: m => [|m]; rewrite ?lcmn0 ?andbF.\nrewrite -(@dvdn_pmul2r (gcdn d1.+1 d2.+1)) ?gcdn_gt0 // muln_lcm_gcd.\nby rewrite muln_gcdr dvdn_gcd {1}mulnC andbC !dvdn_pmul2r.\nQed.\n\nLemma lcmnMl m n : lcmn m (m * n) = m * n.\nProof. by case: m => // m; rewrite /lcmn gcdnMr mulKn. Qed.\n\nLemma lcmnMr m n : lcmn n (m * n) = m * n.\nProof. by rewrite mulnC lcmnMl. Qed.\n\nLemma lcmn_idPr {m n} : reflect (lcmn m n = n) (m %| n).\nProof.\nby apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (lcmnMr, dvdn_lcml).\nQed.\n\nLemma lcmn_idPl {m n} : reflect (lcmn m n = m) (n %| m).\nProof. by rewrite lcmnC; apply: lcmn_idPr. Qed.\n\nLemma expn_max e m n : e ^ maxn m n = lcmn (e ^ m) (e ^ n).\nProof.\nrewrite /maxn; case: leqP; [rewrite lcmnC | move/ltnW];\n by move/(dvdn_exp2l e)/lcmn_idPr.\nQed.\n\n(* Coprime factors *)\n\nDefinition coprime m n := gcdn m n == 1.\n\nLemma coprime1n n : coprime 1 n.\nProof. by rewrite /coprime gcd1n. Qed.\n\nLemma coprimen1 n : coprime n 1.\nProof. by rewrite /coprime gcdn1. Qed.\n\nLemma coprime_sym m n : coprime m n = coprime n m.\nProof. by rewrite /coprime gcdnC. Qed.\n\nLemma coprime_modl m n : coprime (m %% n) n = coprime m n.\nProof. by rewrite /coprime gcdn_modl. Qed.\n\nLemma coprime_modr m n : coprime m (n %% m) = coprime m n.\nProof. by rewrite /coprime gcdn_modr. Qed.\n\nLemma coprime2n n : coprime 2 n = odd n.\nProof. by rewrite -coprime_modr modn2; case: (odd n). Qed.\n\nLemma coprimen2 n : coprime n 2 = odd n.\nProof. by rewrite coprime_sym coprime2n. Qed.\n\nLemma coprimeSn n : coprime n.+1 n.\nProof. by rewrite -coprime_modl (modnDr 1) coprime_modl coprime1n. Qed.\n\nLemma coprimenS n : coprime n n.+1.\nProof. by rewrite coprime_sym coprimeSn. Qed.\n\nLemma coprimePn n : n > 0 -> coprime n.-1 n.\nProof. by case: n => // n _; rewrite coprimenS. Qed.\n\nLemma coprimenP n : n > 0 -> coprime n n.-1.\nProof. by case: n => // n _; rewrite coprimeSn. Qed.\n\nLemma coprimeP n m :\n  n > 0 -> reflect (exists u, u.1 * n - u.2 * m = 1) (coprime n m).\nProof.\nmove=> n_gt0; apply: (iffP eqP) => [<-| [[kn km] /= kn_km_1]].\n  by have [kn km kg _] := egcdnP m n_gt0; exists (kn, km); rewrite kg addKn.\napply gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m.\nby rewrite -kn_km_1 dvdn_subr ?dvdn_mull // ltnW // -subn_gt0 kn_km_1.\nQed.\n\nLemma modn_coprime k n : 0 < k -> (exists u, (k * u) %% n = 1) -> coprime k n.\nProof.\nmove=> k_gt0 [u Hu]; apply/coprimeP=> //.\nby exists (u, k * u %/ n); rewrite /= mulnC {1}(divn_eq (k * u) n) addKn.\nQed.\n\nLemma Gauss_dvd m n p : coprime m n -> (m * n %| p) = (m %| p) && (n %| p).\nProof. by move=> co_mn; rewrite -muln_lcm_gcd (eqnP co_mn) muln1 dvdn_lcm. Qed.\n\nLemma Gauss_dvdr m n p : coprime m n -> (m %| n * p) = (m %| p).\nProof.\ncase: n => [|n] co_mn; first by case: m co_mn => [|[]] // _; rewrite !dvd1n.\nby symmetry; rewrite mulnC -(@dvdn_pmul2r n.+1) ?Gauss_dvd // andbC dvdn_mull.\nQed.\n\nLemma Gauss_dvdl m n p : coprime m p -> (m %| n * p) = (m %| n).\nProof. by rewrite mulnC; apply: Gauss_dvdr. Qed.\n\nLemma dvdn_double_leq m n : m %| n -> odd m -> ~~ odd n -> 0 < n -> m.*2 <= n.\nProof.\nmove=> m_dv_n odd_m even_n n_gt0.\nby rewrite -muln2 dvdn_leq // Gauss_dvd ?coprimen2 ?m_dv_n ?dvdn2.\nQed.\n\nLemma dvdn_double_ltn m n : m %| n.-1 -> odd m -> odd n -> 1 < n -> m.*2 < n.\nProof. by case: n => //; apply: dvdn_double_leq. Qed.\n\nLemma Gauss_gcdr p m n : coprime p m -> gcdn p (m * n) = gcdn p n.\nProof.\nmove=> co_pm; apply/eqP; rewrite eqn_dvd !dvdn_gcd !dvdn_gcdl /=.\nrewrite andbC dvdn_mull ?dvdn_gcdr //= -(@Gauss_dvdr _ m) ?dvdn_gcdr //.\nby rewrite /coprime gcdnAC (eqnP co_pm) gcd1n.\nQed.\n\nLemma Gauss_gcdl p m n : coprime p n -> gcdn p (m * n) = gcdn p m.\nProof. by move=> co_pn; rewrite mulnC Gauss_gcdr. Qed.\n\nLemma coprime_mulr p m n : coprime p (m * n) = coprime p m && coprime p n.\nProof.\ncase co_pm: (coprime p m) => /=; first by rewrite /coprime Gauss_gcdr.\napply/eqP=> co_p_mn; case/eqnP: co_pm; apply gcdn_def => // d dv_dp dv_dm.\nby rewrite -co_p_mn dvdn_gcd dv_dp dvdn_mulr.\nQed.\n\nLemma coprime_mull p m n : coprime (m * n) p = coprime m p && coprime n p.\nProof. by rewrite -!(coprime_sym p) coprime_mulr. Qed.\n\nLemma coprime_pexpl k m n : 0 < k -> coprime (m ^ k) n = coprime m n.\nProof.\ncase: k => // k _; elim: k => [|k IHk]; first by rewrite expn1.\nby rewrite expnS coprime_mull -IHk; case coprime.\nQed.\n\nLemma coprime_pexpr k m n : 0 < k -> coprime m (n ^ k) = coprime m n.\nProof. by move=> k_gt0; rewrite !(coprime_sym m) coprime_pexpl. Qed.\n\nLemma coprime_expl k m n : coprime m n -> coprime (m ^ k) n.\nProof. by case: k => [|k] co_pm; rewrite ?coprime1n // coprime_pexpl. Qed.\n\nLemma coprime_expr k m n : coprime m n -> coprime m (n ^ k).\nProof. by rewrite !(coprime_sym m); apply: coprime_expl. Qed.\n\nLemma coprime_dvdl m n p : m %| n -> coprime n p -> coprime m p.\nProof. by case/dvdnP=> d ->; rewrite coprime_mull => /andP[]. Qed.\n\nLemma coprime_dvdr m n p : m %| n -> coprime p n -> coprime p m.\nProof. by rewrite !(coprime_sym p); apply: coprime_dvdl. Qed.\n\nLemma coprime_egcdn n m : n > 0 -> coprime (egcdn n m).1 (egcdn n m).2.\nProof.\nmove=> n_gt0; case: (egcdnP m n_gt0) => kn km /= /eqP.\nhave [/dvdnP[u defn] /dvdnP[v defm]] := (dvdn_gcdl n m, dvdn_gcdr n m).\nrewrite -[gcdn n m]mul1n {1}defm {1}defn !mulnA -mulnDl addnC.\nrewrite eqn_pmul2r ?gcdn_gt0 ?n_gt0 //; case: kn => // kn /eqP def_knu _.\nby apply/coprimeP=> //; exists (u, v); rewrite mulnC def_knu mulnC addnK.\nQed.\n\nLemma dvdn_pexp2r m n k : k > 0 -> (m ^ k %| n ^ k) = (m %| n).\nProof.\nmove=> k_gt0; apply/idP/idP=> [dv_mn_k|]; last exact: dvdn_exp2r.\ncase: (posnP n) => [-> | n_gt0]; first by rewrite dvdn0.\nhave [n' def_n] := dvdnP (dvdn_gcdr m n); set d := gcdn m n in def_n.\nhave [m' def_m] := dvdnP (dvdn_gcdl m n); rewrite -/d in def_m.\nhave d_gt0: d > 0 by rewrite gcdn_gt0 n_gt0 orbT.\nrewrite def_m def_n !expnMn dvdn_pmul2r ?expn_gt0 ?d_gt0 // in dv_mn_k.\nhave: coprime (m' ^ k) (n' ^ k).\n  rewrite coprime_pexpl // coprime_pexpr // /coprime -(eqn_pmul2r d_gt0) mul1n.\n  by rewrite muln_gcdl -def_m -def_n.\nrewrite /coprime -gcdn_modr (eqnP dv_mn_k) gcdn0 -(exp1n k).\nby rewrite (inj_eq (expIn k_gt0)) def_m; move/eqP->; rewrite mul1n dvdn_gcdr.\nQed.\n\nSection Chinese.\n\n(***********************************************************************)\n(*   The chinese remainder theorem                                     *)\n(***********************************************************************)\n\nVariables m1 m2 : nat.\nHypothesis co_m12 : coprime m1 m2.\n\nLemma chinese_remainder x y :\n  (x == y %[mod m1 * m2]) = (x == y %[mod m1]) && (x == y %[mod m2]).\nProof.\nwlog le_yx : x y / y <= x; last by rewrite !eqn_mod_dvd // Gauss_dvd.\nby case/orP: (leq_total y x); last rewrite !(eq_sym (x %% _)); auto.\nQed.\n\n(***********************************************************************)\n(*   A function that solves the chinese remainder problem              *)\n(***********************************************************************)\n\nDefinition chinese r1 r2 :=\n  r1 * m2 * (egcdn m2 m1).1 + r2 * m1 * (egcdn m1 m2).1.\n\nLemma chinese_modl r1 r2 : chinese r1 r2 = r1 %[mod m1].\nProof.\nrewrite /chinese; case: (posnP m2) co_m12 => [-> /eqnP | m2_gt0 _].\n  by rewrite gcdn0 => ->; rewrite !modn1.\ncase: egcdnP => // k2 k1 def_m1 _.\nrewrite mulnAC -mulnA def_m1 gcdnC (eqnP co_m12) mulnDr mulnA muln1.\nby rewrite addnAC (mulnAC _ m1) -mulnDl modnMDl.\nQed.\n\nLemma chinese_modr r1 r2 : chinese r1 r2 = r2 %[mod m2].\nProof.\nrewrite /chinese; case: (posnP m1) co_m12 => [-> /eqnP | m1_gt0 _].\n  by rewrite gcd0n => ->; rewrite !modn1.\ncase: (egcdnP m2) => // k1 k2 def_m2 _.\nrewrite addnC mulnAC -mulnA def_m2 (eqnP co_m12) mulnDr mulnA muln1.\nby rewrite addnAC (mulnAC _ m2) -mulnDl modnMDl.\nQed.\n\nLemma chinese_mod x : x = chinese (x %% m1) (x %% m2) %[mod m1 * m2].\nProof.\napply/eqP; rewrite chinese_remainder //.\nby rewrite chinese_modl chinese_modr !modn_mod !eqxx.\nQed.\n\nEnd Chinese.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/theories/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7129279869397621}}
{"text": "\nRequire Import Znumtheory .\nRequire Import Zdiv .\nRequire Import ZArith .\n\nSection SimpleChineseRemainder .\n\nOpen Scope Z_scope .\n\nDefinition modulo (a b n : Z) : Prop := (n | (a - b)) .\nNotation \"( a == b [ n ])\" := (modulo a b n) .\n\nLemma modulo_tran : forall a b c n : Z, \n    (a == b [ n ]) -> (b == c [ n ]) -> (a == c [ n ]) .\nProof .\n  intros a b c n Hab Hbc .\n  red in Hab, Hbc |- * .\n  cut (a - c = a - b + (b - c)) .\n  - intros H .\n    rewrite H .\n    apply Zdivide_plus_r .\n    + trivial .\n    + trivial .\n  - auto with * .\nQed .\n\nLemma modulo_plus_subst : forall a b c n : Z,\n    (a == b [ n ]) -> (a + c == b + c [ n ]) .\nProof .\n  intros a b c n Hc .\n  red in Hc |- * .\n  cut (a + c - (b + c) = a - b) .\n  - intros H .\n    rewrite H .\n    + trivial .\n  - auto with * .\nQed .\n\nLemma modulo_mult_subst : forall a b c n : Z,\n    (a == b [ n ]) -> (a * c == b * c [ n ]) .\nProof .\n  intros a b c n H .\n  red in H |- * .\n  cut (a * c - b * c = c * (a - b)) .\n  - intros H1 .\n    rewrite H1 .\n    + auto with * .\n  - auto with * .\nQed .\n\nHypothesis m n : Z .\nHypothesis co_prime : rel_prime m n .\n\nTheorem modulo_inv : forall m n : Z, rel_prime m n ->\n                       exists x : Z, (m * x == 1 [ n ]) .\nProof .\n  intros m0 n0 H .\n  cut (Bezout m0 n0 1) .\n  - intros H0 .\n    elim H0 .\n    intros u v H1 .\n    exists u .\n    red .\n    red .\n    exists (-v) .\n    rewrite (Zmult_comm m0 u).\n    rewrite <- (Zminus_plus_simpl_r (u * m0) 1 (v * n0)) .\n    rewrite H1 .\n    unfold Zminus .\n    rewrite (Zopp_plus_distr 1 (v * n0)) .\n    rewrite (Zplus_comm (-(1)) (-(v*n0))) .\n    rewrite (Zplus_permute 1 (-(v*n0)) (-(1))) .\n    rewrite (Zplus_opp_r 1) .\n    rewrite (Zplus_0_r (- (v * n0))) .\n    rewrite (Zopp_mult_distr_l v n0) .\n    reflexivity .\n  - apply (rel_prime_bezout m0 n0) .\n    exact H .\nQed.\n\nTheorem SimpleChineseRemainder : forall a b : Z,\n  exists x : Z, (x == a [ m ]) /\\ (x == b [ n ]) .\nProof .\n  intros a0 b0 .\n  destruct (modulo_inv m n co_prime) .\n  unfold rel_prime in co_prime .\n  apply (Zis_gcd_sym m n 1) in co_prime .\n  fold (rel_prime n m) in co_prime .\n  destruct (modulo_inv n m co_prime) .\n  apply (modulo_mult_subst (m * x) 1 b0 n) in H .\n  apply (modulo_mult_subst (n * x0) 1 a0 m) in H0 .\n  rewrite (Zmult_1_l b0) in H .\n  rewrite (Zmult_1_l a0) in H0 .\n  exists (m * x * b0 + n * x0 * a0) .\n  split .\n  - apply (modulo_plus_subst (n * x0 * a0) a0 (m * x * b0) m) in H0 .\n    rewrite (Zplus_comm (n * x0 * a0) (m * x * b0)) in H0 .\n    cut (a0 + m * x * b0 == a0 [m]) .\n    + intro H1 .\n      apply (modulo_tran (m * x * b0 + n * x0 * a0) (a0 + m * x * b0) a0 m) in H0 .\n      * exact H0 .\n      * exact H1 .\n    + red .\n      unfold Zminus .\n      rewrite (Zplus_comm (a0 + m * x * b0) (- a0)) .\n      rewrite (Zplus_assoc (-a0) a0 (m * x * b0)) .\n      rewrite (Zplus_opp_l a0) .\n      rewrite (Zplus_0_l (m * x * b0)) .\n      red .\n      exists (x * b0) .\n      rewrite <- (Zmult_assoc m x b0) .\n      rewrite (Zmult_comm m (x * b0)) .\n      reflexivity .\n  - apply (modulo_plus_subst (m * x * b0) b0 (n * x0 * a0) n) in H .\n    cut (b0 + n * x0 * a0 == b0 [n]) .\n    + intro H1 .\n      apply (modulo_tran (m * x * b0 + n * x0 * a0) (b0 + n * x0 * a0) b0 n) in H .\n      * exact H .\n      * exact H1 .\n    + red .\n      unfold Zminus .\n      rewrite (Zplus_comm (b0 + n * x0 * a0) (- b0)) .\n      rewrite (Zplus_assoc (-b0) b0 (n * x0 * a0)) .\n      rewrite (Zplus_opp_l b0) .\n      rewrite (Zplus_0_l (n * x0 * a0)) .\n      red .\n      exists (x0 * a0) .\n      rewrite <- (Zmult_assoc n x0 a0) .\n      rewrite (Zmult_comm n (x0 * a0)) .\n      reflexivity .\nQed .\n\nEnd SimpleChineseRemainder .\n\nCheck SimpleChineseRemainder .\n", "meta": {"author": "ChexterWang", "repo": "i2cl", "sha": "ca00bf480f735bd0f87a61a0c580ca81fadf892f", "save_path": "github-repos/coq/ChexterWang-i2cl", "path": "github-repos/coq/ChexterWang-i2cl/i2cl-ca00bf480f735bd0f87a61a0c580ca81fadf892f/pa2/hw2-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188344, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.7129251829452646}}
{"text": "(**\nThe Little Prover の memb?/remb をCoqで解いてみる\n *)\n\nRequire Import Bool.\nRequire Import List.\nRequire Import Program.\nSet Implicit Arguments.\n\n(** * はじめに *)\n\n(**\nThe Little Prover (TLP) の第6章では、memb?/remb という定理が扱われています。\nこれは、リニアなリストの要素から、文字 '?' を削除する関数 remb と、\nこれは、リニアなリストの要素に、文字 '?' が含まれるかを判定する関数 memb? が\n定義されているとき、\n任意のリスト xs に対して、(memb? (remb xs)) が必ず False になるというものです。\n\nオリジナルはLisp系の言語なので、リストの要素は任意のデータでよいのですが、\nCoqの場合は、false と true からなる bool型のリストとし、もじ '?' の代わりに true とします。\n  *)\n\n(**\nソースコードは、\n#<a href=\"https://github.com/suharahiromichi/coq/blob/master/prog/coq_membp_remb.v\">\nここ\n</a>\nにあります。\n *)\n\n(**\nまず、membp (memb? に対応する) のリストにtrueが含まれていることを判定する関数を定義ましす。\nリストの先頭から見ていき true が含まれていたらそこで True を返します。\n*)\n\nFixpoint membp (xs : list bool) : Prop :=\n  match xs with\n  | nil => False\n  | true :: xs' => True\n  | false :: xs' =>  membp xs'\n  end.\n\nCompute membp (true :: false :: true :: nil).         (** ==> [True] *)\n\nCompute membp (false :: false :: false :: nil).       (** ==> [False] *)\n\nCompute membp nil.                                    (** ==> [False] *)\n\n(**\nついで、remb のリストからtrueを削除する関数を定義します。\nリストの先頭から見ていき true なら、それを含まない結果を返し\nfalse なら、それを含む結果を返します。\n*)\n\nFixpoint remb (xs : list bool) : list bool :=\n  match xs with\n  | nil => nil\n  | true :: xs' => remb xs'\n  | false :: xs' => false :: remb xs'\n  end.\n\nCompute remb (true :: false :: true :: nil).         (** ==> [[false]] *)\n\n(** * memb?/remb の証明 *)\n\n(**\nmemb?/remb に対応する membp_remb は、文字通りの定義です。\n結果は偽であるため、「~」がついています。\n *)\n\nDefinition membp_remb (xs : list bool) := ~ membp (remb xs).\n\n(** 以下に、membp_remb を証明します。線形リスト xs に対する帰納法と、\n要素 x に対する場合分けだけで証明されています。\nなお、帰納法の仮定IHxsは、ふたつめとみっつめのnowでトリビアルに使われます。\n *)\n  \nGoal forall (xs : list bool), membp_remb xs.\nProof.\n  unfold membp_remb.\n  intros xs.\n  induction xs as [|x xs IHxs].\n  - now simpl.\n  - case x.\n    + now simpl.\n    + now simpl.\n\n  Restart.\n  unfold membp_remb.\n  intros xs.\n  induction xs as [|x xs IHxs]; try auto.\n  now case x.\nQed.\n\n(**\nmemb?/remb は定理としては自明ですが、trueが含まれないことをチェックする関数membpによって、\ntrueを削除する関数rembが正しく動作していることを証明する、と考えることができます。\n\nこれは、関数の定義とその証明を同時におこなう証明駆動開発の一例となります。\nCoqにはそれをサポートする「Program」コマンドがあります。\nこれを使って remb を再定義してみましょう。\n\nremb' の値は、単なる list bool ではなく、\n[{ys : list bool | ~ membp ys}]\nすなわち、\n[~ membp ys] を満たす [ys] の集合の要素、\nとなります。\n\nこれだと、最初に想定した型と違うので困ると思うかもしれませんが、\n「Program」コマンドの中では、そのサブタイプ・コアーションの機能によって、\nlist boot 型と同一視されます。\n\nremb' の結果が普通にconsされていることに気づいてください。\n\n「Program」コマンドの中では、そのサブタイプ・コアーションは、\n再帰呼び出しのみならず、他の（定義済みの）任意な関数に適用されます。\n *)\n\nProgram Fixpoint remb' (xs : list bool) : {ys : list bool | ~ membp ys} :=\n  match xs with\n  | nil => nil\n  | true :: xs' => remb' xs'\n  | false :: xs' => false :: remb' xs'\n  end.\n\n(**\n*response* ウインドウに\n\n[[\nSolving obligations automatically...\nremb'_obligation_1 is defined\nremb'_obligation_2 is defined\nNo more obligations remaining\nremb' is defined\nremb' is recursively defined (decreasing on 1st argument)\n]]\n\nと表示されたはずですが、これは自動的に証明が終わったことを意味します。\n *)\n\n(**\nremb' を「Program」コマンドの外から実行するときは、proj1_sig で値を取り出す必要があります。\n\nこれは、[`] という演算子として定義されています。\n*)\n\nCompute ` (remb' (true :: false :: true :: nil)). (** ==> [[false]] *)\n\nExtraction remb'.\n(**\n生成されたコードには、rembp は含まれていない。\n\n[[\nval remb' : bool list -> bool list\n\nlet rec remb' = function\n| Nil -> Nil\n| Cons (b, xs') ->\n  (match b with\n   | True -> remb' xs'\n   | False -> Cons (False, (remb' xs')))\n]]\n*)\n\n(** * 証明駆動開発 *)\n\n(**\nこれからは、TLP の範囲を越える事項ですが、\nremb' の定義を「リストからtrueを除去する関数」の証明付き定義と考えると問題があります。\n\nmembp はtrueの有無しかチェックしていませんから、\nremb の本体が「つねにnil」を返すような定義であっても問題なくパスします。これではだめです。\n\nremb の厳密な定義は、(1)に加えて(2)も満たさないといけません。\n\n(1) 結果のリストに true が含まれないこと(0個であること)。\n\n(2) もとのリストと結果のリストととで、false の個数が同じであること。\n *)\n\n\n(**\nリストのなかの true ないし false の個数を数える関数を定義します。\n *)\n\nFixpoint count_occ (l : list bool) (x : bool) : nat :=\n  match l with\n  | [] => 0\n  | y :: tl =>\n    match (x, y) with\n    | (true, true) => S (count_occ tl x)\n    | (false, false) => S (count_occ tl x)\n    | _ => count_occ tl x\n    end\n  end.\n\nCompute count_occ (true :: false :: true :: nil) true. (** ==> [2] *)\n\nCompute count_occ (true :: false :: true :: nil) false. (** ==> [1] *)\n\n\n(**\n定理を直接証明します。\n(1) と (2) を連言(/\\)でつなぎます。\nまた let ... in は普通の意味で、ys は構文的な意味しかもちません。\n*)\n\nGoal forall (xs : list bool),\n    let ys := remb xs in\n    count_occ ys true = 0 /\\  count_occ xs false = count_occ ys false.\nProof.\n  intros xs.\n  split.\n  - induction xs as [| x' xs' IHxs].\n    + now simpl.\n    + case x'.\n      * now simpl.\n      * now simpl.\n  - induction xs as [| x' xs'IHxs].\n    + reflexivity.\n    + case x' as [x' | y']; simpl in *.\n      * now rewrite <- IHxs'IHxs.\n      * now rewrite IHxs'IHxs.\n\n  Restart.\n  intros xs.\n  split; induction xs as [|x xs IHxs]; auto; case x; auto.\n  now case x; simpl; [rewrite <- IHxs | rewrite IHxs].\nQed.\n\n(**\n「Program」コマンドでの定義に条件を追加します。\n今回も自動証明できました。\n*)\n\nProgram Fixpoint remb'' (xs : list bool) :\n  {ys : list bool | count_occ ys true = 0 /\\\n                    count_occ xs false = count_occ ys false} :=\n  match xs with\n  | nil => nil\n  | false :: xs' => false :: remb'' xs'\n  | true :: xs' => remb'' xs'\n  end.\n\nCompute ` (remb'' (true :: false :: true :: nil)). (** ==> [[false]] *)\n\nExtraction remb''.\n\n(**\n生成されたコードには、count_occ は含まれていません。\n\n[[\nval remb'' : bool list -> bool list\n\nlet rec remb'' = function\n| Nil -> Nil\n| Cons (b, xs') ->\n  (match b with\n   | True -> remb'' xs'\n   | False -> Cons (False, (remb'' xs')))\n]]\n *)\n\n(** * 帰納法の公理 *)\n\n(**\nTLPにもどって、帰納法による証明について考えてみましょう。\nTLPでは、（例によって、天から降ってきた）「inductive claim」を証明しています。\nこれの導きかたは第6章の最後に記載されていますが、Coqの場合は、\nリストの型定義にもとづく「公理」を使います。\n *)\n\nCheck list_ind : forall (A : Type) (P : list A -> Prop),\n    P [] ->\n    (forall (a : A) (l : list A), P l -> P (a :: l)) ->\n    forall l : list A, P l.\n\n(**\nこれを membp_remb に適用すると次を得ます。\n繰り返しますが、これは証明するべきものではなく、「公理」です。\n *)\n\nCheck list_ind membp_remb :\n  membp_remb [] ->\n  (forall (a : bool) (l : list bool), membp_remb l -> membp_remb (a :: l)) ->\n  forall l : list bool, membp_remb l.\n\n(**\nこの公理を使うなら、\n\n[forall l : list bool, membp_remb l]\n\nを証明するには、\n\n[membp_remb []]\n\nと\n\n[forall (a : bool) (l : list bool), membp_remb l -> membp_remb (a :: l)]\n\nとを証明すればよいことになります。後者は、TLPでは、l は nil でないことを条件に、\n[(cdr l)] をとっていて、つまり、\n\n[forall (l : list bool), membp_remb (tl l) -> membp_remb l]\n\nとなっています。おなじですね。\n *)\n\n(**\n実際の証明は、以下の通りです。\n *)\n\nGoal forall xs, membp_remb xs.\nProof.\n  intros xs.\n  apply (list_ind membp_remb).\n  - now simpl.\n  - intros x' xs' IHxs.\n    case x'.\n    + now simpl.\n    + now simpl.\nQed.\n\n(**\n最初の証明では、\n\n[induction xs] というタクティクを使いましたが、\n\nこの公理を\n\n[apply (list_ind membp_remb)]\n\nとして、適用することと同じです。\n *)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/prog/coq_membp_remb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7128673802912866}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\n(** Fixed precision machine words *)\n\nRequire Import Coq.Arith.Arith\n        Coq.Arith.Div2\n        Coq.NArith.NArith\n        Coq.Bool.Bool\n        Coq.ZArith.ZArith.\nRequire Import Bedrock.Nomega.\n\nSet Implicit Arguments.\n\n\n(** * Basic definitions and conversion to and from [nat] *)\n\nInductive word : nat -> Set :=\n| WO : word O\n| WS : bool -> forall n, word n -> word (S n).\n\nFixpoint wordToNat sz (w : word sz) : nat :=\n  match w with\n    | WO => O\n    | WS false w' => (wordToNat w') * 2\n    | WS true w' => S (wordToNat w' * 2)\n  end.\n\nFixpoint wordToNat' sz (w : word sz) : nat :=\n  match w with\n    | WO => O\n    | WS false w' => 2 * wordToNat w'\n    | WS true w' => S (2 * wordToNat w')\n  end.\n\nTheorem wordToNat_wordToNat' : forall sz (w : word sz),\n  wordToNat w = wordToNat' w.\nProof.\n  induction w. auto. simpl. rewrite mult_comm. reflexivity.\nQed.\n\nFixpoint mod2 (n : nat) : bool :=\n  match n with\n    | 0 => false\n    | 1 => true\n    | S (S n') => mod2 n'\n  end.\n\nFixpoint natToWord (sz n : nat) : word sz :=\n  match sz with\n    | O => WO\n    | S sz' => WS (mod2 n) (natToWord sz' (div2 n))\n  end.\n\nFixpoint wordToN sz (w : word sz) : N :=\n  match w with\n    | WO => 0\n    | WS false w' => 2 * wordToN w'\n    | WS true w' => N.succ (2 * wordToN w')\n  end%N.\n\nDefinition Nmod2 (n : N) : bool :=\n  match n with\n    | N0 => false\n    | Npos (xO _) => false\n    | _ => true\n  end.\n\nDefinition wzero sz := natToWord sz 0.\n\nFixpoint wzero' (sz : nat) : word sz :=\n  match sz with\n    | O => WO\n    | S sz' => WS false (wzero' sz')\n  end.\n\nFixpoint posToWord (sz : nat) (p : positive) {struct p} : word sz :=\n  match sz with\n    | O => WO\n    | S sz' =>\n      match p with\n        | xI p' => WS true (posToWord sz' p')\n        | xO p' => WS false (posToWord sz' p')\n        | xH => WS true (wzero' sz')\n      end\n  end.\n\nDefinition NToWord (sz : nat) (n : N) : word sz :=\n  match n with\n    | N0 => wzero' sz\n    | Npos p => posToWord sz p\n  end.\n\nFixpoint Npow2 (n : nat) : N :=\n  match n with\n    | O => 1\n    | S n' => 2 * Npow2 n'\n  end%N.\n\n\nLtac rethink :=\n  match goal with\n    | [ H : ?f ?n = _ |- ?f ?m = _ ] => replace m with n; simpl; auto\n  end.\n\nTheorem mod2_S_double : forall n, mod2 (S (2 * n)) = true.\n  induction n; simpl; intuition; rethink.\nQed.\n\nTheorem mod2_double : forall n, mod2 (2 * n) = false.\n  induction n; simpl; intuition; rewrite <- plus_n_Sm; rethink.\nQed.\n\nLocal Hint Resolve mod2_S_double mod2_double.\n\nTheorem div2_double : forall n, div2 (2 * n) = n.\n  induction n; simpl; intuition; rewrite <- plus_n_Sm; f_equal; rethink.\nQed.\n\nTheorem div2_S_double : forall n, div2 (S (2 * n)) = n.\n  induction n; simpl; intuition; f_equal; rethink.\nQed.\n\nHint Rewrite div2_double div2_S_double : div2.\n\nTheorem natToWord_wordToNat : forall sz w, natToWord sz (wordToNat w) = w.\n  induction w; rewrite wordToNat_wordToNat'; intuition; f_equal; unfold natToWord, wordToNat'; fold natToWord; fold wordToNat';\n    destruct b; f_equal; autorewrite with div2; intuition.\nQed.\n\nFixpoint pow2 (n : nat) : nat :=\n  match n with\n    | O => 1\n    | S n' => 2 * pow2 n'\n  end.\n\nTheorem roundTrip_0 : forall sz, wordToNat (natToWord sz 0) = 0.\n  induction sz; simpl; intuition.\nQed.\n\nHint Rewrite roundTrip_0 : wordToNat.\n\nLocal Hint Extern 1 (@eq nat _ _) => omega.\n\nTheorem untimes2 : forall n, n + (n + 0) = 2 * n.\n  auto.\nQed.\n\nSection strong.\n  Variable P : nat -> Prop.\n\n  Hypothesis PH : forall n, (forall m, m < n -> P m) -> P n.\n\n  Lemma strong' : forall n m, m <= n -> P m.\n    induction n; simpl; intuition; apply PH; intuition.\n    exfalso; omega.\n  Qed.\n\n  Theorem strong : forall n, P n.\n    intros; eapply strong'; eauto.\n  Qed.\nEnd strong.\n\nTheorem div2_odd : forall n,\n  mod2 n = true\n  -> n = S (2 * div2 n).\n  induction n using strong; simpl; intuition.\n\n  destruct n; simpl in *; intuition.\n    try discriminate.\n  destruct n; simpl in *; intuition.\n  do 2 f_equal.\n  replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto.\nQed.\n\nTheorem div2_even : forall n,\n  mod2 n = false\n  -> n = 2 * div2 n.\n  induction n using strong; simpl; intuition.\n\n  destruct n; simpl in *; intuition.\n  destruct n; simpl in *; intuition.\n    try discriminate.\n  f_equal.\n  replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto.\nQed.\n\nLemma wordToNat_natToWord' : forall sz w, exists k, wordToNat (natToWord sz w) + k * pow2 sz = w.\n  induction sz; simpl; intuition; repeat rewrite untimes2.\n\n  exists w; intuition.\n\n  case_eq (mod2 w); intro Hmw.\n\n  specialize (IHsz (div2 w)); firstorder.\n  rewrite wordToNat_wordToNat' in *.\n  exists x; intuition.\n  rewrite mult_assoc.\n  rewrite (mult_comm x 2).\n  rewrite mult_comm. simpl mult at 1.\n  rewrite (plus_Sn_m (2 * wordToNat' (natToWord sz (div2 w)))).\n  rewrite <- mult_assoc.\n  rewrite <- mult_plus_distr_l.\n  rewrite H; clear H.\n  symmetry; apply div2_odd; auto.\n\n  specialize (IHsz (div2 w)); firstorder.\n  exists x; intuition.\n  rewrite mult_assoc.\n  rewrite (mult_comm x 2).\n  rewrite <- mult_assoc.\n  rewrite mult_comm.\n  rewrite <- mult_plus_distr_l.\n  rewrite H; clear H.\n  symmetry; apply div2_even; auto.\nQed.\n\nTheorem wordToNat_natToWord : forall sz w, exists k, wordToNat (natToWord sz w) = w - k * pow2 sz /\\ k * pow2 sz <= w.\n  intros; destruct (wordToNat_natToWord' sz w) as [k]; exists k; intuition.\nQed.\n\nDefinition wone sz := natToWord sz 1.\n\nFixpoint wones (sz : nat) : word sz :=\n  match sz with\n    | O => WO\n    | S sz' => WS true (wones sz')\n  end.\n\n\n(** Comparisons *)\n\nFixpoint wmsb sz (w : word sz) (a : bool) : bool :=\n  match w with\n    | WO => a\n    | WS b x => wmsb x b\n  end.\n\nDefinition whd sz (w : word (S sz)) : bool :=\n  match w in word sz' return match sz' with\n                               | O => unit\n                               | S _ => bool\n                             end with\n    | WO => tt\n    | WS b _ => b\n  end.\n\nDefinition wtl sz (w : word (S sz)) : word sz :=\n  match w in word sz' return match sz' with\n                               | O => unit\n                               | S sz'' => word sz''\n                             end with\n    | WO => tt\n    | WS _ w' => w'\n  end.\n\nTheorem WS_neq : forall b1 b2 sz (w1 w2 : word sz),\n  (b1 <> b2 \\/ w1 <> w2)\n  -> WS b1 w1 <> WS b2 w2.\n  intuition.\n  apply (f_equal (@whd _)) in H0; tauto.\n  apply (f_equal (@wtl _)) in H0; tauto.\nQed.\n\n\n(** Shattering **)\n\nLemma shatter_word : forall n (a : word n),\n  match n return word n -> Prop with\n    | O => fun a => a = WO\n    | S _ => fun a => a = WS (whd a) (wtl a)\n  end a.\n  destruct a; eauto.\nQed.\n\nLemma shatter_word_S : forall n (a : word (S n)),\n  exists b, exists c, a = WS b c.\nProof.\n  intros; repeat eexists; apply (shatter_word a).\nQed.\nLemma shatter_word_0 : forall a : word 0,\n  a = WO.\nProof.\n  intros; apply (shatter_word a).\nQed.\n\nHint Resolve shatter_word_0.\n\nRequire Import Coq.Logic.Eqdep_dec.\n\nDefinition weq : forall sz (x y : word sz), {x = y} + {x <> y}.\n  refine (fix weq sz (x : word sz) : forall y : word sz, {x = y} + {x <> y} :=\n    match x in word sz return forall y : word sz, {x = y} + {x <> y} with\n      | WO => fun _ => left _ _\n      | WS b x' => fun y => if bool_dec b (whd y)\n        then if weq _ x' (wtl y) then left _ _ else right _ _\n        else right _ _\n    end); clear weq.\n\n  abstract (symmetry; apply shatter_word_0).\n\n  abstract (subst; symmetry; apply (shatter_word y)).\n\n  abstract (rewrite (shatter_word y); simpl; intro; injection H; intros;\n    apply n0; apply inj_pair2_eq_dec in H0; [ auto | apply eq_nat_dec ]).\n\n  abstract (rewrite (shatter_word y); simpl; intro; apply n0; injection H; auto).\nDefined.\n\nFixpoint weqb sz (x : word sz) : word sz -> bool :=\n  match x in word sz return word sz -> bool with\n    | WO => fun _ => true\n    | WS b x' => fun y =>\n      if eqb b (whd y)\n      then if @weqb _ x' (wtl y) then true else false\n      else false\n  end.\n\nTheorem weqb_true_iff : forall sz x y,\n  @weqb sz x y = true <-> x = y.\nProof.\n  induction x; simpl; intros.\n  { split; auto. }\n  { rewrite (shatter_word y) in *. simpl in *.\n    case_eq (eqb b (whd y)); intros.\n    case_eq (weqb x (wtl y)); intros.\n    split; auto; intros. rewrite eqb_true_iff in H. f_equal; eauto. eapply IHx; eauto.\n    split; intros; try congruence. inversion H1; clear H1; subst.\n    eapply inj_pair2_eq_dec in H4. eapply IHx in H4. congruence.\n    eapply Peano_dec.eq_nat_dec.\n    split; intros; try congruence.\n    inversion H0. apply eqb_false_iff in H. congruence. }\nQed.\n\n(** * Combining and splitting *)\n\nFixpoint combine (sz1 : nat) (w : word sz1) : forall sz2, word sz2 -> word (sz1 + sz2) :=\n  match w in word sz1 return forall sz2, word sz2 -> word (sz1 + sz2) with\n    | WO => fun _ w' => w'\n    | WS b w' => fun _ w'' => WS b (combine w' w'')\n  end.\n\nFixpoint split1 (sz1 sz2 : nat) : word (sz1 + sz2) -> word sz1 :=\n  match sz1 with\n    | O => fun _ => WO\n    | S sz1' => fun w => WS (whd w) (split1 sz1' sz2 (wtl w))\n  end.\n\nFixpoint split2 (sz1 sz2 : nat) : word (sz1 + sz2) -> word sz2 :=\n  match sz1 with\n    | O => fun w => w\n    | S sz1' => fun w => split2 sz1' sz2 (wtl w)\n  end.\n\nLtac shatterer := simpl; intuition;\n  match goal with\n    | [ w : _ |- _ ] => rewrite (shatter_word w); simpl\n  end; f_equal; auto.\n\nTheorem combine_split : forall sz1 sz2 (w : word (sz1 + sz2)),\n  combine (split1 sz1 sz2 w) (split2 sz1 sz2 w) = w.\n  induction sz1; shatterer.\nQed.\n\nTheorem split1_combine : forall sz1 sz2 (w : word sz1) (z : word sz2),\n  split1 sz1 sz2 (combine w z) = w.\n  induction sz1; shatterer.\nQed.\n\nTheorem split2_combine : forall sz1 sz2 (w : word sz1) (z : word sz2),\n  split2 sz1 sz2 (combine w z) = z.\n  induction sz1; shatterer.\nQed.\n\nRequire Import Coq.Logic.Eqdep_dec.\n\n\nTheorem combine_assoc : forall n1 (w1 : word n1) n2 n3 (w2 : word n2) (w3 : word n3) Heq,\n  combine (combine w1 w2) w3\n  = match Heq in _ = N return word N with\n      | refl_equal => combine w1 (combine w2 w3)\n    end.\n  induction w1; simpl; intuition.\n\n  rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)); reflexivity.\n\n  rewrite (IHw1 _ _ _ _ (plus_assoc _ _ _)); clear IHw1.\n  repeat match goal with\n           | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf\n         end.\n  generalize dependent (combine w1 (combine w2 w3)).\n  rewrite plus_assoc; intros.\n  rewrite (UIP_dec eq_nat_dec e (refl_equal _)).\n  rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)).\n  reflexivity.\nQed.\n\nTheorem split2_iter : forall n1 n2 n3 Heq w,\n  split2 n2 n3 (split2 n1 (n2 + n3) w)\n  = split2 (n1 + n2) n3 (match Heq in _ = N return word N with\n                           | refl_equal => w\n                         end).\n  induction n1; simpl; intuition.\n\n  rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)); reflexivity.\n\n  rewrite (IHn1 _ _ (plus_assoc _ _ _)).\n  f_equal.\n  repeat match goal with\n           | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf\n         end.\n  generalize dependent w.\n  simpl.\n  fold plus.\n  generalize (n1 + (n2 + n3)); clear.\n  intros.\n  generalize Heq e.\n  subst.\n  intros.\n  rewrite (UIP_dec eq_nat_dec e (refl_equal _)).\n  rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)).\n  reflexivity.\nQed.\n\nTheorem combine_end : forall n1 n2 n3 Heq w,\n  combine (split1 n2 n3 (split2 n1 (n2 + n3) w))\n  (split2 (n1 + n2) n3 (match Heq in _ = N return word N with\n                          | refl_equal => w\n                        end))\n  = split2 n1 (n2 + n3) w.\n  induction n1; simpl; intros.\n\n  rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)).\n  apply combine_split.\n\n  rewrite (shatter_word w) in *.\n  simpl.\n  eapply trans_eq; [ | apply IHn1 with (Heq := plus_assoc _ _ _) ]; clear IHn1.\n  repeat f_equal.\n  repeat match goal with\n           | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf\n         end.\n  simpl.\n  generalize dependent w.\n  rewrite plus_assoc.\n  intros.\n  rewrite (UIP_dec eq_nat_dec e (refl_equal _)).\n  rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)).\n  reflexivity.\nQed.\n\n\n(** * Extension operators *)\n\nDefinition sext (sz : nat) (w : word sz) (sz' : nat) : word (sz + sz') :=\n  if wmsb w false then\n    combine w (wones sz')\n  else\n    combine w (wzero sz').\n\nDefinition zext (sz : nat) (w : word sz) (sz' : nat) : word (sz + sz') :=\n  combine w (wzero sz').\n\n\n(** * Arithmetic *)\n\nDefinition wneg sz (x : word sz) : word sz :=\n  NToWord sz (Npow2 sz - wordToN x).\n\nDefinition wordBin (f : N -> N -> N) sz (x y : word sz) : word sz :=\n  NToWord sz (f (wordToN x) (wordToN y)).\n\nDefinition wplus := wordBin Nplus.\nDefinition wmult := wordBin Nmult.\nDefinition wmult' sz (x y : word sz) : word sz :=\n  split2 sz sz (NToWord (sz + sz) (Nmult (wordToN x) (wordToN y))).\nDefinition wminus sz (x y : word sz) : word sz := wplus x (wneg y).\n\nDefinition wnegN sz (x : word sz) : word sz :=\n  natToWord sz (pow2 sz - wordToNat x).\n\nDefinition wordBinN (f : nat -> nat -> nat) sz (x y : word sz) : word sz :=\n  natToWord sz (f (wordToNat x) (wordToNat y)).\n\nDefinition wplusN := wordBinN plus.\n\nDefinition wmultN := wordBinN mult.\nDefinition wmultN' sz (x y : word sz) : word sz :=\n  split2 sz sz (natToWord (sz + sz) (mult (wordToNat x) (wordToNat y))).\n\nDefinition wminusN sz (x y : word sz) : word sz := wplusN x (wnegN y).\n\n(** * Notations *)\n\nDelimit Scope word_scope with word.\nBind Scope word_scope with word.\n\nNotation \"w ~ 1\" := (WS true w)\n (at level 7, left associativity, format \"w '~' '1'\") : word_scope.\nNotation \"w ~ 0\" := (WS false w)\n (at level 7, left associativity, format \"w '~' '0'\") : word_scope.\n\nNotation \"^~\" := wneg.\nNotation \"l ^+ r\" := (@wplus _ l%word r%word) (at level 50, left associativity).\nNotation \"l ^* r\" := (@wmult _ l%word r%word) (at level 40, left associativity).\nNotation \"l ^- r\" := (@wminus _ l%word r%word) (at level 50, left associativity).\n\nTheorem wordToN_nat : forall sz (w : word sz), wordToN w = N_of_nat (wordToNat w).\n  induction w; intuition.\n  destruct b; unfold wordToN, wordToNat; fold wordToN; fold wordToNat.\n\n  rewrite N_of_S.\n  rewrite N_of_mult.\n  rewrite <- IHw.\n  rewrite Nmult_comm.\n  reflexivity.\n\n  rewrite N_of_mult.\n  rewrite <- IHw.\n  rewrite Nmult_comm.\n  reflexivity.\nQed.\n\nTheorem mod2_S : forall n k,\n  2 * k = S n\n  -> mod2 n = true.\n  induction n using strong; intros.\n  destruct n; simpl in *.\n  exfalso; omega.\n  destruct n; simpl in *; auto.\n  destruct k; simpl in *.\n  discriminate.\n  apply H with k; auto.\nQed.\n\nTheorem wzero'_def : forall sz, wzero' sz = wzero sz.\n  unfold wzero; induction sz; simpl; intuition.\n  congruence.\nQed.\n\nTheorem posToWord_nat : forall p sz, posToWord sz p = natToWord sz (nat_of_P p).\n  induction p; destruct sz; simpl; intuition; f_equal; try rewrite wzero'_def in *.\n\n  rewrite ZL6.\n  destruct (ZL4 p) as [? Heq]; rewrite Heq; simpl.\n  replace (x + S x) with (S (2 * x)) by omega.\n  symmetry; apply mod2_S_double.\n\n  rewrite IHp.\n  rewrite ZL6.\n  destruct (nat_of_P p); simpl; intuition.\n  replace (n + S n) with (S (2 * n)) by omega.\n  rewrite div2_S_double; auto.\n\n  unfold nat_of_P; simpl.\n  rewrite ZL6.\n  replace (nat_of_P p + nat_of_P p) with (2 * nat_of_P p) by omega.\n  symmetry; apply mod2_double.\n\n  rewrite IHp.\n  unfold nat_of_P; simpl.\n  rewrite ZL6.\n  replace (nat_of_P p + nat_of_P p) with (2 * nat_of_P p) by omega.\n  rewrite div2_double.\n  auto.\n  auto.\nQed.\n\nTheorem NToWord_nat : forall sz n, NToWord sz n = natToWord sz (nat_of_N n).\n  destruct n; simpl; intuition; try rewrite wzero'_def in *.\n  auto.\n  apply posToWord_nat.\nQed.\n\nTheorem wplus_alt : forall sz (x y : word sz), wplus x y = wplusN x y.\n  unfold wplusN, wplus, wordBinN, wordBin; intros.\n\n  repeat rewrite wordToN_nat; repeat rewrite NToWord_nat.\n  rewrite nat_of_Nplus.\n  repeat rewrite nat_of_N_of_nat.\n  reflexivity.\nQed.\n\nTheorem wmult_alt : forall sz (x y : word sz), wmult x y = wmultN x y.\n  unfold wmultN, wmult, wordBinN, wordBin; intros.\n\n  repeat rewrite wordToN_nat; repeat rewrite NToWord_nat.\n  rewrite nat_of_Nmult.\n  repeat rewrite nat_of_N_of_nat.\n  reflexivity.\nQed.\n\nTheorem Npow2_nat : forall n, nat_of_N (Npow2 n) = pow2 n.\n  induction n; simpl; intuition.\n  rewrite <- IHn; clear IHn.\n  case_eq (Npow2 n); intuition;\n    rewrite untimes2; replace (Npos p~0) with (N.double (Npos p)) by reflexivity;\n    apply nat_of_Ndouble.\nQed.\n\nTheorem wneg_alt : forall sz (x : word sz), wneg x = wnegN x.\n  unfold wnegN, wneg; intros.\n  repeat rewrite wordToN_nat; repeat rewrite NToWord_nat.\n  rewrite nat_of_Nminus.\n  do 2 f_equal.\n  apply Npow2_nat.\n  apply nat_of_N_of_nat.\nQed.\n\nTheorem wminus_Alt : forall sz (x y : word sz), wminus x y = wminusN x y.\n  intros; unfold wminusN, wminus; rewrite wneg_alt; apply wplus_alt.\nQed.\n\nTheorem wplus_unit : forall sz (x : word sz), natToWord sz 0 ^+ x = x.\n  intros; rewrite wplus_alt; unfold wplusN, wordBinN; intros.\n  rewrite roundTrip_0; apply natToWord_wordToNat.\nQed.\n\nTheorem wplus_comm : forall sz (x y : word sz), x ^+ y = y ^+ x.\n  intros; repeat rewrite wplus_alt; unfold wplusN, wordBinN; f_equal; auto.\nQed.\n\nTheorem drop_mod2 : forall n k,\n  2 * k <= n\n  -> mod2 (n - 2 * k) = mod2 n.\n  induction n using strong; intros.\n\n  do 2 (destruct n; simpl in *; repeat rewrite untimes2 in *; intuition).\n\n  destruct k; simpl in *; intuition.\n\n  destruct k; simpl; intuition.\n  rewrite <- plus_n_Sm.\n  repeat rewrite untimes2 in *.\n  simpl; auto.\n  apply H; omega.\nQed.\n\nTheorem div2_minus_2 : forall n k,\n  2 * k <= n\n  -> div2 (n - 2 * k) = div2 n - k.\n  induction n using strong; intros.\n\n  do 2 (destruct n; simpl in *; intuition; repeat rewrite untimes2 in *).\n  destruct k; simpl in *; intuition.\n\n  destruct k; simpl in *; intuition.\n  rewrite <- plus_n_Sm.\n  apply H; omega.\nQed.\n\nTheorem div2_bound : forall k n,\n  2 * k <= n\n  -> k <= div2 n.\n  intros; case_eq (mod2 n); intro Heq.\n\n  rewrite (div2_odd _ Heq) in H.\n  omega.\n\n  rewrite (div2_even _ Heq) in H.\n  omega.\nQed.\n\nTheorem drop_sub : forall sz n k,\n  k * pow2 sz <= n\n  -> natToWord sz (n - k * pow2 sz) = natToWord sz n.\n  induction sz; simpl; intuition; repeat rewrite untimes2 in *; f_equal.\n\n  rewrite mult_assoc.\n  rewrite (mult_comm k).\n  rewrite <- mult_assoc.\n  apply drop_mod2.\n  rewrite mult_assoc.\n  rewrite (mult_comm 2).\n  rewrite <- mult_assoc.\n  auto.\n\n  rewrite <- (IHsz (div2 n) k).\n  rewrite mult_assoc.\n  rewrite (mult_comm k).\n  rewrite <- mult_assoc.\n  rewrite div2_minus_2.\n  reflexivity.\n  rewrite mult_assoc.\n  rewrite (mult_comm 2).\n  rewrite <- mult_assoc.\n  auto.\n\n  apply div2_bound.\n  rewrite mult_assoc.\n  rewrite (mult_comm 2).\n  rewrite <- mult_assoc.\n  auto.\nQed.\n\nLocal Hint Extern 1 (_ <= _) => omega.\n\nTheorem wplus_assoc : forall sz (x y z : word sz), x ^+ (y ^+ z) = x ^+ y ^+ z.\n  intros; repeat rewrite wplus_alt; unfold wplusN, wordBinN; intros.\n\n  repeat match goal with\n           | [ |- context[wordToNat (natToWord ?sz ?w)] ] =>\n             let Heq := fresh \"Heq\" in\n               destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq\n         end.\n\n  replace (wordToNat x + wordToNat y - x1 * pow2 sz + wordToNat z)\n    with (wordToNat x + wordToNat y + wordToNat z - x1 * pow2 sz) by auto.\n  replace (wordToNat x + (wordToNat y + wordToNat z - x0 * pow2 sz))\n    with (wordToNat x + wordToNat y + wordToNat z - x0 * pow2 sz) by auto.\n  repeat rewrite drop_sub; auto.\nQed.\n\nTheorem roundTrip_1 : forall sz, wordToNat (natToWord (S sz) 1) = 1.\n  induction sz; simpl in *; intuition.\nQed.\n\nTheorem mod2_WS : forall sz (x : word sz) b, mod2 (wordToNat (WS b x)) = b.\n  intros. rewrite wordToNat_wordToNat'.\n  destruct b; simpl.\n\n  rewrite untimes2.\n  case_eq (2 * wordToNat x); intuition.\n  eapply mod2_S; eauto.\n  rewrite <- (mod2_double (wordToNat x)); f_equal; omega.\nQed.\n\nTheorem div2_WS : forall sz (x : word sz) b, div2 (wordToNat (WS b x)) = wordToNat x.\n  destruct b; rewrite wordToNat_wordToNat'; unfold wordToNat'; fold wordToNat'.\n  apply div2_S_double.\n  apply div2_double.\nQed.\n\nTheorem wmult_unit : forall sz (x : word sz), natToWord sz 1 ^* x = x.\n  intros; rewrite wmult_alt; unfold wmultN, wordBinN; intros.\n  destruct sz; simpl.\n  rewrite (shatter_word x); reflexivity.\n  rewrite roundTrip_0; simpl.\n  rewrite plus_0_r.\n  rewrite (shatter_word x).\n  f_equal.\n\n  apply mod2_WS.\n\n  rewrite div2_WS.\n  apply natToWord_wordToNat.\nQed.\n\nTheorem wmult_comm : forall sz (x y : word sz), x ^* y = y ^* x.\n  intros; repeat rewrite wmult_alt; unfold wmultN, wordBinN; auto with arith.\nQed.\n\nTheorem wmult_assoc : forall sz (x y z : word sz), x ^* (y ^* z) = x ^* y ^* z.\n  intros; repeat rewrite wmult_alt; unfold wmultN, wordBinN; intros.\n\n  repeat match goal with\n           | [ |- context[wordToNat (natToWord ?sz ?w)] ] =>\n             let Heq := fresh \"Heq\" in\n               destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq\n         end.\n\n  rewrite mult_minus_distr_l.\n  rewrite mult_minus_distr_r.\n  rewrite (mult_assoc (wordToNat x) x0).\n  rewrite <- (mult_assoc x1).\n  rewrite (mult_comm (pow2 sz)).\n  rewrite (mult_assoc x1).\n  repeat rewrite drop_sub; auto with arith.\n  rewrite (mult_comm x1).\n  rewrite <- (mult_assoc (wordToNat x)).\n  rewrite (mult_comm (wordToNat y)).\n  rewrite mult_assoc.\n  rewrite (mult_comm (wordToNat x)).\n  repeat rewrite <- mult_assoc.\n  auto with arith.\n  repeat rewrite <- mult_assoc.\n  auto with arith.\nQed.\n\nTheorem wmult_plus_distr : forall sz (x y z : word sz), (x ^+ y) ^* z = (x ^* z) ^+ (y ^* z).\n  intros; repeat rewrite wmult_alt; repeat rewrite wplus_alt; unfold wmultN, wplusN, wordBinN; intros.\n\n  repeat match goal with\n           | [ |- context[wordToNat (natToWord ?sz ?w)] ] =>\n             let Heq := fresh \"Heq\" in\n               destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq\n         end.\n\n  rewrite mult_minus_distr_r.\n  rewrite <- (mult_assoc x0).\n  rewrite (mult_comm (pow2 sz)).\n  rewrite (mult_assoc x0).\n\n  replace (wordToNat x * wordToNat z - x1 * pow2 sz +\n    (wordToNat y * wordToNat z - x2 * pow2 sz))\n    with (wordToNat x * wordToNat z + wordToNat y * wordToNat z - x1 * pow2 sz - x2 * pow2 sz).\n  repeat rewrite drop_sub; auto with arith.\n  rewrite (mult_comm x0).\n  rewrite (mult_comm (wordToNat x + wordToNat y)).\n  rewrite <- (mult_assoc (wordToNat z)).\n  auto with arith.\n  generalize dependent (wordToNat x * wordToNat z).\n  generalize dependent (wordToNat y * wordToNat z).\n  intros.\n  omega.\nQed.\n\nTheorem wminus_def : forall sz (x y : word sz), x ^- y = x ^+ ^~ y.\n  reflexivity.\nQed.\n\nTheorem wordToNat_bound : forall sz (w : word sz), wordToNat w < pow2 sz.\n  induction w; simpl; intuition.\n  destruct b; simpl; omega.\nQed.\n\nTheorem natToWord_pow2 : forall sz, natToWord sz (pow2 sz) = natToWord sz 0.\n  induction sz; simpl; intuition.\n\n  generalize (div2_double (pow2 sz)); simpl; intro Hr; rewrite Hr; clear Hr.\n  f_equal.\n  generalize (mod2_double (pow2 sz)); auto.\n  auto.\nQed.\n\nTheorem wminus_inv : forall sz (x : word sz), x ^+ ^~ x = wzero sz.\n  intros; rewrite wneg_alt; rewrite wplus_alt; unfold wnegN, wplusN, wzero, wordBinN; intros.\n\n  repeat match goal with\n           | [ |- context[wordToNat (natToWord ?sz ?w)] ] =>\n             let Heq := fresh \"Heq\" in\n               destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq\n         end.\n\n  replace (wordToNat x + (pow2 sz - wordToNat x - x0 * pow2 sz))\n    with (pow2 sz - x0 * pow2 sz).\n  rewrite drop_sub; auto with arith.\n  apply natToWord_pow2.\n  generalize (wordToNat_bound x).\n  omega.\nQed.\n\nDefinition wring (sz : nat) : ring_theory (wzero sz) (wone sz) (@wplus sz) (@wmult sz) (@wminus sz) (@wneg sz) (@eq _) :=\n  mk_rt _ _ _ _ _ _ _\n  (@wplus_unit _) (@wplus_comm _) (@wplus_assoc _)\n  (@wmult_unit _) (@wmult_comm _) (@wmult_assoc _)\n  (@wmult_plus_distr _) (@wminus_def _) (@wminus_inv _).\n\nTheorem weqb_sound : forall sz (x y : word sz), weqb x y = true -> x = y.\nProof.\n  eapply weqb_true_iff.\nQed.\n\nLtac isWcst w :=\n  match eval hnf in w with\n    | WO => constr:(true)\n    | WS ?b ?w' =>\n      match eval hnf in b with\n        | true => isWcst w'\n        | false => isWcst w'\n        | _ => constr:(false)\n      end\n    | _ => constr:(false)\n  end.\n\nLtac wcst w :=\n  let b := isWcst w in\n    match b with\n      | true => w\n      | _ => constr:(NotConstant)\n    end.\n\n(* Here's how you can add a ring for a specific bit-width.\n   There doesn't seem to be a polymorphic method, so this code really does need to be copied. *)\n\n(*\nDefinition wring8 := wring 8.\nAdd Ring wring8 : wring8 (decidable (weqb_sound 8), constants [wcst]).\n*)\n\n\n(** * Bitwise operators *)\n\nFixpoint wnot sz (w : word sz) : word sz :=\n  match w with\n    | WO => WO\n    | WS b w' => WS (negb b) (wnot w')\n  end.\n\nFixpoint bitwp (f : bool -> bool -> bool) sz (w1 : word sz) : word sz -> word sz :=\n  match w1 with\n    | WO => fun _ => WO\n    | WS b w1' => fun w2 => WS (f b (whd w2)) (bitwp f w1' (wtl w2))\n  end.\n\nDefinition wor := bitwp orb.\nDefinition wand := bitwp andb.\nDefinition wxor := bitwp xorb.\n\nNotation \"l ^| r\" := (@wor _ l%word r%word) (at level 50, left associativity).\nNotation \"l ^& r\" := (@wand _ l%word r%word) (at level 40, left associativity).\n\nTheorem wor_unit : forall sz (x : word sz), wzero sz ^| x = x.\n  unfold wzero, wor; induction x; simpl; intuition congruence.\nQed.\n\nTheorem wor_comm : forall sz (x y : word sz), x ^| y = y ^| x.\n  unfold wor; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool.\nQed.\n\nTheorem wor_assoc : forall sz (x y z : word sz), x ^| (y ^| z) = x ^| y ^| z.\n  unfold wor; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool.\nQed.\n\nTheorem wand_unit : forall sz (x : word sz), wones sz ^& x = x.\n  unfold wand; induction x; simpl; intuition congruence.\nQed.\n\nTheorem wand_kill : forall sz (x : word sz), wzero sz ^& x = wzero sz.\n  unfold wzero, wand; induction x; simpl; intuition congruence.\nQed.\n\nTheorem wand_comm : forall sz (x y : word sz), x ^& y = y ^& x.\n  unfold wand; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool.\nQed.\n\nTheorem wand_assoc : forall sz (x y z : word sz), x ^& (y ^& z) = x ^& y ^& z.\n  unfold wand; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool.\nQed.\n\nTheorem wand_or_distr : forall sz (x y z : word sz), (x ^| y) ^& z = (x ^& z) ^| (y ^& z).\n  unfold wand, wor; induction x; intro y; rewrite (shatter_word y); intro z; rewrite (shatter_word z); simpl; intuition; f_equal; auto with bool.\n  destruct (whd y); destruct (whd z); destruct b; reflexivity.\nQed.\n\nDefinition wbring (sz : nat) : semi_ring_theory (wzero sz) (wones sz) (@wor sz) (@wand sz) (@eq _) :=\n  mk_srt _ _ _ _ _\n  (@wor_unit _) (@wor_comm _) (@wor_assoc _)\n  (@wand_unit _) (@wand_kill _) (@wand_comm _) (@wand_assoc _)\n  (@wand_or_distr _).\n\n\n(** * Inequality proofs *)\n\nLtac word_simpl := unfold sext, zext, wzero in *; simpl in *.\n\nLtac word_eq := ring.\n\nLtac word_eq1 := match goal with\n                   | _ => ring\n                   | [ H : _ = _ |- _ ] => ring [H]\n                 end.\n\nTheorem word_neq : forall sz (w1 w2 : word sz),\n  w1 ^- w2 <> wzero sz\n  -> w1 <> w2.\n  intros; intro; subst.\n  unfold wminus in H.\n  rewrite wminus_inv in H.\n  tauto.\nQed.\n\nLtac word_neq := apply word_neq; let H := fresh \"H\" in intro H; simpl in H; ring_simplify in H; try discriminate.\n\nLtac word_contra := match goal with\n                      | [ H : _ <> _ |- False ] => apply H; ring\n                    end.\n\nLtac word_contra1 := match goal with\n                       | [ H : _ <> _ |- False ] => apply H;\n                         match goal with\n                           | _ => ring\n                           | [ H' : _ = _ |- _ ] => ring [H']\n                         end\n                     end.\n\nOpen Scope word_scope.\n\n(** * Signed Logic **)\nFixpoint wordToZ sz (w : word sz) : Z :=\n  if wmsb w true then\n    (** Negative **)\n    match wordToN (wneg w) with\n      | N0 => 0%Z\n      | Npos x => Zneg x\n    end\n  else\n    (** Positive **)\n    match wordToN w with\n      | N0 => 0%Z\n      | Npos x => Zpos x\n    end.\n\n(** * Comparison Predicates and Deciders **)\nDefinition wlt sz (l r : word sz) : Prop :=\n  N.lt (wordToN l) (wordToN r).\nDefinition wslt sz (l r : word sz) : Prop :=\n  Z.lt (wordToZ l) (wordToZ r).\n\nNotation \"w1 > w2\" := (@wlt _ w2%word w1%word) : word_scope.\nNotation \"w1 >= w2\" := (~(@wlt _ w1%word w2%word)) : word_scope.\nNotation \"w1 < w2\" := (@wlt _ w1%word w2%word) : word_scope.\nNotation \"w1 <= w2\" := (~(@wlt _ w2%word w1%word)) : word_scope.\n\nNotation \"w1 '>s' w2\" := (@wslt _ w2%word w1%word) (at level 70) : word_scope.\nNotation \"w1 '>s=' w2\" := (~(@wslt _ w1%word w2%word)) (at level 70) : word_scope.\nNotation \"w1 '<s' w2\" := (@wslt _ w1%word w2%word) (at level 70) : word_scope.\nNotation \"w1 '<s=' w2\" := (~(@wslt _ w2%word w1%word)) (at level 70) : word_scope.\n\nDefinition wlt_dec : forall sz (l r : word sz), {l < r} + {l >= r}.\n  refine (fun sz l r =>\n    match N.compare (wordToN l) (wordToN r) as k return N.compare (wordToN l) (wordToN r) = k -> _ with\n      | Lt => fun pf => left _ _\n      | _ => fun pf => right _ _\n    end (refl_equal _));\n  abstract congruence.\nDefined.\n\nDefinition wslt_dec : forall sz (l r : word sz), {l <s r} + {l >s= r}.\n  refine (fun sz l r =>\n    match Z.compare (wordToZ l) (wordToZ r) as c return Z.compare (wordToZ l) (wordToZ r) = c -> _ with\n      | Lt => fun pf => left _ _\n      | _ => fun pf => right _ _\n    end (refl_equal _));\n  abstract congruence.\nDefined.\n\n(* Ordering Lemmas **)\nLemma lt_le : forall sz (a b : word sz),\n  a < b -> a <= b.\nProof.\n  unfold wlt, N.lt. intros. intro. rewrite <- Ncompare_antisym in H0. rewrite H in H0. simpl in *. congruence.\nQed.\nLemma eq_le : forall sz (a b : word sz),\n  a = b -> a <= b.\nProof.\n  intros; subst. unfold wlt, N.lt. rewrite N.compare_refl. congruence.\nQed.\nLemma wordToN_inj : forall sz (a b : word sz),\n  wordToN a = wordToN b -> a = b.\nProof.\n  induction a; intro b0; rewrite (shatter_word b0); intuition.\n  simpl in H.\n  destruct b; destruct (whd b0); intros.\n  f_equal. eapply IHa. eapply N.succ_inj in H.\n  destruct (wordToN a); destruct (wordToN (wtl b0)); try congruence.\n  destruct (wordToN (wtl b0)); destruct (wordToN a); inversion H.\n  destruct (wordToN (wtl b0)); destruct (wordToN a); inversion H.\n  f_equal. eapply IHa.\n  destruct (wordToN a); destruct (wordToN (wtl b0)); try congruence.\nQed.\nLemma unique_inverse : forall sz (a b1 b2 : word sz),\n  a ^+ b1 = wzero _ ->\n  a ^+ b2 = wzero _ ->\n  b1 = b2.\nProof.\n  intros.\n  transitivity (b1 ^+ wzero _).\n  rewrite wplus_comm. rewrite wplus_unit. auto.\n  transitivity (b1 ^+ (a ^+ b2)). congruence.\n  rewrite wplus_assoc.\n  rewrite (wplus_comm b1). rewrite H. rewrite wplus_unit. auto.\nQed.\nLemma sub_0_eq : forall sz (a b : word sz),\n  a ^- b = wzero _ -> a = b.\nProof.\n  intros. destruct (weq (wneg b) (wneg a)).\n  transitivity (a ^+ (^~ b ^+ b)).\n  rewrite (wplus_comm (^~ b)). rewrite wminus_inv.\n  rewrite wplus_comm. rewrite wplus_unit. auto.\n  rewrite e. rewrite wplus_assoc. rewrite wminus_inv. rewrite wplus_unit. auto.\n  unfold wminus in H.\n  generalize (unique_inverse a (wneg a) (^~ b)).\n  intros. exfalso. apply n. symmetry; apply H0.\n  apply wminus_inv.\n  auto.\nQed.\n\nLemma le_neq_lt : forall sz (a b : word sz),\n  b <= a -> a <> b -> b < a.\nProof.\n  intros; destruct (wlt_dec b a); auto.\n  exfalso. apply H0. unfold wlt, N.lt in *.\n  eapply wordToN_inj. eapply Ncompare_eq_correct.\n  case_eq ((wordToN a ?= wordToN b)%N); auto; try congruence.\n  intros. rewrite <- Ncompare_antisym in n. rewrite H1 in n. simpl in *. congruence.\nQed.\n\n\nHint Resolve word_neq lt_le eq_le sub_0_eq le_neq_lt : worder.\n\nLtac shatter_word x :=\n  match type of x with\n    | word 0 => try rewrite (shatter_word_0 x) in *\n    | word (S ?N) =>\n      let x' := fresh in\n      let H := fresh in\n      destruct (@shatter_word_S N x) as [ ? [ x' H ] ];\n      rewrite H in *; clear H; shatter_word x'\n  end.\n\n\n(** Uniqueness of equality proofs **)\nLemma rewrite_weq : forall sz (a b : word sz)\n  (pf : a = b),\n  weq a b = left _ pf.\nProof.\n  intros; destruct (weq a b); try solve [ exfalso; auto ].\n  f_equal.\n  eapply UIP_dec. eapply weq.\nQed.\n\n\n(** * Some more useful derived facts *)\n\nLemma natToWord_plus : forall sz n m, natToWord sz (n + m) = natToWord _ n ^+ natToWord _ m.\n  destruct sz; intuition.\n  rewrite wplus_alt.\n  unfold wplusN, wordBinN.\n  destruct (wordToNat_natToWord (S sz) n); intuition.\n  destruct (wordToNat_natToWord (S sz) m); intuition.\n  rewrite H0; rewrite H2; clear H0 H2.\n  replace (n - x * pow2 (S sz) + (m - x0 * pow2 (S sz))) with (n + m - x * pow2 (S sz) - x0 * pow2 (S sz))\n    by omega.\n  repeat rewrite drop_sub; auto; omega.\nQed.\n\nLemma natToWord_S : forall sz n, natToWord sz (S n) = natToWord _ 1 ^+ natToWord _ n.\n  intros; change (S n) with (1 + n); apply natToWord_plus.\nQed.\n\nTheorem natToWord_inj : forall sz n m, natToWord sz n = natToWord sz m\n  -> (n < pow2 sz)%nat\n  -> (m < pow2 sz)%nat\n  -> n = m.\n  intros.\n  apply (f_equal (@wordToNat _)) in H.\n  destruct (wordToNat_natToWord sz n).\n  destruct (wordToNat_natToWord sz m).\n  intuition.\n  rewrite H4 in H; rewrite H2 in H; clear H4 H2.\n  assert (x = 0).\n  destruct x; auto; simpl in *; generalize dependent (x * pow2 sz); intros; omega.\n  assert (x0 = 0).\n  destruct x0; auto; simpl in *; generalize dependent (x0 * pow2 sz); intros; omega.\n  subst; simpl in *; omega.\nQed.\n\nLemma wordToNat_natToWord_idempotent : forall sz n,\n  (N.of_nat n < Npow2 sz)%N\n  -> wordToNat (natToWord sz n) = n.\n  intros.\n  destruct (wordToNat_natToWord sz n); intuition.\n  destruct x.\n  simpl in *; omega.\n  simpl in *.\n  apply Nlt_out in H.\n  autorewrite with N in *.\n  rewrite Npow2_nat in *.\n  generalize dependent (x * pow2 sz).\n  intros; omega.\nQed.\n\nLemma wplus_cancel : forall sz (a b c : word sz),\n  a ^+ c = b ^+ c\n  -> a = b.\n  intros.\n  apply (f_equal (fun x => x ^+ ^~ c)) in H.\n  repeat rewrite <- wplus_assoc in H.\n  rewrite wminus_inv in H.\n  repeat rewrite (wplus_comm _ (wzero sz)) in H.\n  repeat rewrite wplus_unit in H.\n  assumption.\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/Bedrock/Word.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7128673793887277}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nSet Implicit Arguments.\n\nRequire Export Notations.\n\nNotation \"A -> B\" := (forall (_ : A), B) : type_scope.\n\n(** * Propositional connectives *)\n\n(** [True] is the always true proposition *)\n\nInductive True : Prop :=\n  I : True.\n\n(** [False] is the always false proposition *)\nInductive False : Prop :=.\n\n(** [not A], written [~A], is the negation of [A] *)\nDefinition not (A:Prop) := A -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nHint Unfold not: core.\n\n  (** [and A B], written [A /\\ B], is the conjunction of [A] and [B]\n\n      [conj p q] is a proof of [A /\\ B] as soon as\n      [p] is a proof of [A] and [q] a proof of [B]\n\n      [proj1] and [proj2] are first and second projections of a conjunction *)\n\nInductive and (A B:Prop) : Prop :=\n  conj : A -> B -> A /\\ B\n\nwhere \"A /\\ B\" := (and A B) : type_scope.\n\nSection Conjunction.\n\n  Variables A B : Prop.\n\n  Theorem proj1 : A /\\ B -> A.\n  Proof.\n    destruct 1; trivial.\n  Qed.\n\n  Theorem proj2 : A /\\ B -> B.\n  Proof.\n    destruct 1; trivial.\n  Qed.\n\nEnd Conjunction.\n\n(** [or A B], written [A \\/ B], is the disjunction of [A] and [B] *)\n\nInductive or (A B:Prop) : Prop :=\n  | or_introl : A -> A \\/ B\n  | or_intror : B -> A \\/ B\n\nwhere \"A \\/ B\" := (or A B) : type_scope.\n\nArguments or_introl [A B] _, [A] B _.\nArguments or_intror [A B] _, A [B] _.\n\n(** [iff A B], written [A <-> B], expresses the equivalence of [A] and [B] *)\n\nDefinition iff (A B:Prop) := (A -> B) /\\ (B -> A).\n\nNotation \"A <-> B\" := (iff A B) : type_scope.\n\nSection Equivalence.\n\nTheorem iff_refl : forall A:Prop, A <-> A.\n  Proof.\n    split; auto.\n  Qed.\n\nTheorem iff_trans : forall A B C:Prop, (A <-> B) -> (B <-> C) -> (A <-> C).\n  Proof.\n    intros A B C [H1 H2] [H3 H4]; split; auto.\n  Qed.\n\nTheorem iff_sym : forall A B:Prop, (A <-> B) -> (B <-> A).\n  Proof.\n    intros A B [H1 H2]; split; auto.\n  Qed.\n\nEnd Equivalence.\n\nHint Unfold iff: extcore.\n\n(** Backward direction of the equivalences above does not need assumptions *)\n\nTheorem and_iff_compat_l : forall A B C : Prop,\n  (B <-> C) -> (A /\\ B <-> A /\\ C).\nProof.\n  intros ? ? ? [Hl Hr]; split; intros [? ?]; (split; [ assumption | ]);\n  [apply Hl | apply Hr]; assumption.\nQed.\n\nTheorem and_iff_compat_r : forall A B C : Prop,\n  (B <-> C) -> (B /\\ A <-> C /\\ A).\nProof.\n  intros ? ? ? [Hl Hr]; split; intros [? ?]; (split; [ | assumption ]);\n  [apply Hl | apply Hr]; assumption.\nQed.\n\nTheorem or_iff_compat_l : forall A B C : Prop,\n  (B <-> C) -> (A \\/ B <-> A \\/ C).\nProof.\n  intros ? ? ? [Hl Hr]; split; (intros [?|?]; [left; assumption| right]);\n  [apply Hl | apply Hr]; assumption.\nQed.\n\nTheorem or_iff_compat_r : forall A B C : Prop,\n  (B <-> C) -> (B \\/ A <-> C \\/ A).\nProof.\n  intros ? ? ? [Hl Hr]; split; (intros [?|?]; [left| right; assumption]);\n  [apply Hl | apply Hr]; assumption.\nQed.\n\nTheorem imp_iff_compat_l : forall A B C : Prop,\n  (B <-> C) -> ((A -> B) <-> (A -> C)).\nProof.\n  intros ? ? ? [Hl Hr]; split; intros H ?; [apply Hl | apply Hr]; apply H; assumption.\nQed.\n\nTheorem imp_iff_compat_r : forall A B C : Prop,\n  (B <-> C) -> ((B -> A) <-> (C -> A)).\nProof.\n  intros ? ? ? [Hl Hr]; split; intros H ?; [apply H, Hr | apply H, Hl]; assumption.\nQed.\n\nTheorem not_iff_compat : forall A B : Prop,\n  (A <-> B) -> (~ A <-> ~B).\nProof.\n  intros; apply imp_iff_compat_r; assumption.\nQed.\n\n\n(** Some equivalences *)\n\nTheorem neg_false : forall A : Prop, ~ A <-> (A <-> False).\nProof.\n  intro A; unfold not; split.\n  - intro H; split; [exact H | intro H1; elim H1].\n  - intros [H _]; exact H.\nQed.\n\nTheorem and_cancel_l : forall A B C : Prop,\n  (B -> A) -> (C -> A) -> ((A /\\ B <-> A /\\ C) <-> (B <-> C)).\nProof.\n  intros A B C Hl Hr.\n  split; [ | apply and_iff_compat_l]; intros [HypL HypR]; split; intros.\n  + apply HypL; split; [apply Hl | ]; assumption.\n  + apply HypR; split; [apply Hr | ]; assumption.\nQed.\n\nTheorem and_cancel_r : forall A B C : Prop,\n  (B -> A) -> (C -> A) -> ((B /\\ A <-> C /\\ A) <-> (B <-> C)).\nProof.\n  intros A B C Hl Hr.\n  split; [ | apply and_iff_compat_r]; intros [HypL HypR]; split; intros.\n  + apply HypL; split; [ | apply Hl ]; assumption.\n  + apply HypR; split; [ | apply Hr ]; assumption.\nQed.\n\nTheorem and_comm : forall A B : Prop, A /\\ B <-> B /\\ A.\nProof.\n  intros; split; intros [? ?]; split; assumption.\nQed.\n\nTheorem and_assoc : forall A B C : Prop, (A /\\ B) /\\ C <-> A /\\ B /\\ C.\nProof.\n  intros; split; [ intros [[? ?] ?]| intros [? [? ?]]]; repeat split; assumption.\nQed.\n\nTheorem or_cancel_l : forall A B C : Prop,\n  (B -> ~ A) -> (C -> ~ A) -> ((A \\/ B <-> A \\/ C) <-> (B <-> C)).\nProof.\n  intros ? ? ? Fl Fr; split; [ | apply or_iff_compat_l]; intros [Hl Hr]; split; intros.\n  { destruct Hl; [ right | destruct Fl | ]; assumption. }\n  { destruct Hr; [ right | destruct Fr | ]; assumption. }\nQed.\n\nTheorem or_cancel_r : forall A B C : Prop,\n  (B -> ~ A) -> (C -> ~ A) -> ((B \\/ A <-> C \\/ A) <-> (B <-> C)).\nProof.\n  intros ? ? ? Fl Fr; split; [ | apply or_iff_compat_r]; intros [Hl Hr]; split; intros.\n  { destruct Hl; [ left | | destruct Fl ]; assumption. }\n  { destruct Hr; [ left | | destruct Fr ]; assumption. }\nQed.\n\nTheorem or_comm : forall A B : Prop, (A \\/ B) <-> (B \\/ A).\nProof.\n  intros; split; (intros [? | ?]; [ right | left ]; assumption).\nQed.\n\nTheorem or_assoc : forall A B C : Prop, (A \\/ B) \\/ C <-> A \\/ B \\/ C.\nProof.\n  intros; split; [ intros [[?|?]|?]| intros [?|[?|?]]].\n  + left; assumption.\n  + right; left; assumption.\n  + right; right; assumption.\n  + left; left; assumption.\n  + left; right; assumption.\n  + right; assumption.\nQed.\nLemma iff_and : forall A B : Prop, (A <-> B) -> (A -> B) /\\ (B -> A).\nProof.\n  intros A B []; split; trivial.\nQed.\n\nLemma iff_to_and : forall A B : Prop, (A <-> B) <-> (A -> B) /\\ (B -> A).\nProof.\n  intros; split; intros [Hl Hr]; (split; intros; [ apply Hl | apply Hr]); assumption.\nQed.\n\n(** [(IF_then_else P Q R)], written [IF P then Q else R] denotes\n    either [P] and [Q], or [~P] and [R] *)\n\nDefinition IF_then_else (P Q R:Prop) := P /\\ Q \\/ ~ P /\\ R.\n\nNotation \"'IF' c1 'then' c2 'else' c3\" := (IF_then_else c1 c2 c3)\n  (at level 200, right associativity) : type_scope.\n\n(** * First-order quantifiers *)\n\n(** [ex P], or simply [exists x, P x], or also [exists x:A, P x],\n    expresses the existence of an [x] of some type [A] in [Set] which\n    satisfies the predicate [P].  This is existential quantification.\n\n    [ex2 P Q], or simply [exists2 x, P x & Q x], or also\n    [exists2 x:A, P x & Q x], expresses the existence of an [x] of\n    type [A] which satisfies both predicates [P] and [Q].\n\n    Universal quantification is primitively written [forall x:A, Q]. By\n    symmetry with existential quantification, the construction [all P]\n    is provided too.\n*)\n\nInductive ex (A:Type) (P:A -> Prop) : Prop :=\n  ex_intro : forall x:A, P x -> ex (A:=A) P.\n\nInductive ex2 (A:Type) (P Q:A -> Prop) : Prop :=\n  ex_intro2 : forall x:A, P x -> Q x -> ex2 (A:=A) P Q.\n\nDefinition all (A:Type) (P:A -> Prop) := forall x:A, P x.\n\n(* Rule order is important to give printing priority to fully typed exists *)\n\nNotation \"'exists' x .. y , p\" := (ex (fun x => .. (ex (fun y => p)) ..))\n  (at level 200, x binder, right associativity,\n   format \"'[' 'exists'  '/  ' x  ..  y ,  '/  ' p ']'\")\n  : type_scope.\n\nNotation \"'exists2' x , p & q\" := (ex2 (fun x => p) (fun x => q))\n  (at level 200, x ident, p at level 200, right associativity) : type_scope.\nNotation \"'exists2' x : A , p & q\" := (ex2 (A:=A) (fun x => p) (fun x => q))\n  (at level 200, x ident, A at level 200, p at level 200, right associativity,\n    format \"'[' 'exists2'  '/  ' x  :  A ,  '/  ' '[' p  &  '/' q ']' ']'\")\n  : type_scope.\n\nNotation \"'exists2' ' x , p & q\" := (ex2 (fun x => p) (fun x => q))\n  (at level 200, x strict pattern, p at level 200, right associativity) : type_scope.\nNotation \"'exists2' ' x : A , p & q\" := (ex2 (A:=A) (fun x => p) (fun x => q))\n  (at level 200, x strict pattern, A at level 200, p at level 200, right associativity,\n    format \"'[' 'exists2'  '/  ' ' x  :  A ,  '/  ' '[' p  &  '/' q ']' ']'\")\n  : type_scope.\n\n(** Derived rules for universal quantification *)\n\nSection universal_quantification.\n\n  Variable A : Type.\n  Variable P : A -> Prop.\n\n  Theorem inst : forall x:A, all (fun x => P x) -> P x.\n  Proof.\n    unfold all; auto.\n  Qed.\n\n  Theorem gen : forall (B:Prop) (f:forall y:A, B -> P y), B -> all P.\n  Proof.\n    red; auto.\n  Qed.\n\nEnd universal_quantification.\n\n(** * Equality *)\n\n(** [eq x y], or simply [x=y] expresses the equality of [x] and\n    [y]. Both [x] and [y] must belong to the same type [A].\n    The definition is inductive and states the reflexivity of the equality.\n    The others properties (symmetry, transitivity, replacement of\n    equals by equals) are proved below. The type of [x] and [y] can be\n    made explicit using the notation [x = y :> A]. This is Leibniz equality\n    as it expresses that [x] and [y] are equal iff every property on\n    [A] which is true of [x] is also true of [y] *)\n\nInductive eq (A:Type) (x:A) : A -> Prop :=\n    eq_refl : x = x :>A\n\nwhere \"x = y :> A\" := (@eq A x y) : type_scope.\n\nNotation \"x = y\" := (x = y :>_) : type_scope.\nNotation \"x <> y  :> T\" := (~ x = y :>T) : type_scope.\nNotation \"x <> y\" := (x <> y :>_) : type_scope.\n\nArguments eq {A} x _.\nArguments eq_refl {A x} , [A] x.\n\nArguments eq_ind [A] x P _ y _.\nArguments eq_rec [A] x P _ y _.\nArguments eq_rect [A] x P _ y _.\n\nHint Resolve I conj or_introl or_intror : core.\nHint Resolve eq_refl: core.\nHint Resolve ex_intro ex_intro2: core.\n\nSection Logic_lemmas.\n\n  Theorem absurd : forall A C:Prop, A -> ~ A -> C.\n  Proof.\n    unfold not; intros A C h1 h2.\n    destruct (h2 h1).\n  Qed.\n\n  Section equality.\n    Variables A B : Type.\n    Variable f : A -> B.\n    Variables x y z : A.\n\n    Theorem eq_sym : x = y -> y = x.\n    Proof.\n      destruct 1; trivial.\n    Defined.\n\n    Theorem eq_trans : x = y -> y = z -> x = z.\n    Proof.\n      destruct 2; trivial.\n    Defined.\n\n    Theorem f_equal : x = y -> f x = f y.\n    Proof.\n      destruct 1; trivial.\n    Defined.\n\n    Theorem not_eq_sym : x <> y -> y <> x.\n    Proof.\n      red; intros h1 h2; apply h1; destruct h2; trivial.\n    Qed.\n\n  End equality.\n\n  Definition eq_ind_r :\n    forall (A:Type) (x:A) (P:A -> Prop), P x -> forall y:A, y = x -> P y.\n    intros A x P H y H0. elim eq_sym with (1 := H0); assumption.\n  Defined.\n\n  Definition eq_rec_r :\n    forall (A:Type) (x:A) (P:A -> Set), P x -> forall y:A, y = x -> P y.\n    intros A x P H y H0; elim eq_sym with (1 := H0); assumption.\n  Defined.\n\n  Definition eq_rect_r :\n    forall (A:Type) (x:A) (P:A -> Type), P x -> forall y:A, y = x -> P y.\n    intros A x P H y H0; elim eq_sym with (1 := H0); assumption.\n  Defined.\nEnd Logic_lemmas.\n\nModule EqNotations.\n  Notation \"'rew' H 'in' H'\" := (eq_rect _ _ H' _ H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew'  H  in  '/' H' ']'\").\n  Notation \"'rew' [ P ] H 'in' H'\" := (eq_rect _ P H' _ H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew'  [ P ]  '/    ' H  in  '/' H' ']'\").\n  Notation \"'rew' <- H 'in' H'\" := (eq_rect_r _ H' H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew'  <-  H  in  '/' H' ']'\").\n  Notation \"'rew' <- [ P ] H 'in' H'\" := (eq_rect_r P H' H)\n    (at level 10, H' at level 10,\n     format \"'[' 'rew'  <-  [ P ]  '/    ' H  in  '/' H' ']'\").\n  Notation \"'rew' -> H 'in' H'\" := (eq_rect _ _ H' _ H)\n    (at level 10, H' at level 10, only parsing).\n  Notation \"'rew' -> [ P ] H 'in' H'\" := (eq_rect _ P H' _ H)\n    (at level 10, H' at level 10, only parsing).\n\nEnd EqNotations.\n\nImport EqNotations.\n\nLemma rew_opp_r : forall A (P:A->Type) (x y:A) (H:x=y) (a:P y), rew H in rew <- H in a = a.\nProof.\nintros.\ndestruct H.\nreflexivity.\nDefined.\n\nLemma rew_opp_l : forall A (P:A->Type) (x y:A) (H:x=y) (a:P x), rew <- H in rew H in a = a.\nProof.\nintros.\ndestruct H.\nreflexivity.\nDefined.\n\nTheorem f_equal2 :\n  forall (A1 A2 B:Type) (f:A1 -> A2 -> B) (x1 y1:A1)\n    (x2 y2:A2), x1 = y1 -> x2 = y2 -> f x1 x2 = f y1 y2.\nProof.\n  destruct 1; destruct 1; reflexivity.\nQed.\n\nTheorem f_equal3 :\n  forall (A1 A2 A3 B:Type) (f:A1 -> A2 -> A3 -> B) (x1 y1:A1)\n    (x2 y2:A2) (x3 y3:A3),\n    x1 = y1 -> x2 = y2 -> x3 = y3 -> f x1 x2 x3 = f y1 y2 y3.\nProof.\n  destruct 1; destruct 1; destruct 1; reflexivity.\nQed.\n\nTheorem f_equal4 :\n  forall (A1 A2 A3 A4 B:Type) (f:A1 -> A2 -> A3 -> A4 -> B)\n    (x1 y1:A1) (x2 y2:A2) (x3 y3:A3) (x4 y4:A4),\n    x1 = y1 -> x2 = y2 -> x3 = y3 -> x4 = y4 -> f x1 x2 x3 x4 = f y1 y2 y3 y4.\nProof.\n  destruct 1; destruct 1; destruct 1; destruct 1; reflexivity.\nQed.\n\nTheorem f_equal5 :\n  forall (A1 A2 A3 A4 A5 B:Type) (f:A1 -> A2 -> A3 -> A4 -> A5 -> B)\n    (x1 y1:A1) (x2 y2:A2) (x3 y3:A3) (x4 y4:A4) (x5 y5:A5),\n    x1 = y1 ->\n    x2 = y2 ->\n    x3 = y3 -> x4 = y4 -> x5 = y5 -> f x1 x2 x3 x4 x5 = f y1 y2 y3 y4 y5.\nProof.\n  destruct 1; destruct 1; destruct 1; destruct 1; destruct 1; reflexivity.\nQed.\n\nTheorem f_equal_compose : forall A B C (a b:A) (f:A->B) (g:B->C) (e:a=b),\n  f_equal g (f_equal f e) = f_equal (fun a => g (f a)) e.\nProof.\n  destruct e. reflexivity.\nDefined.\n\n(** The goupoid structure of equality *)\n\nTheorem eq_trans_refl_l : forall A (x y:A) (e:x=y), eq_trans eq_refl e = e.\nProof.\n  destruct e. reflexivity.\nDefined.\n\nTheorem eq_trans_refl_r : forall A (x y:A) (e:x=y), eq_trans e eq_refl = e.\nProof.\n  destruct e. reflexivity.\nDefined.\n\nTheorem eq_sym_involutive : forall A (x y:A) (e:x=y), eq_sym (eq_sym e) = e.\nProof.\n  destruct e; reflexivity.\nDefined.\n\nTheorem eq_trans_sym_inv_l : forall A (x y:A) (e:x=y), eq_trans (eq_sym e) e = eq_refl.\nProof.\n  destruct e; reflexivity.\nDefined.\n\nTheorem eq_trans_sym_inv_r : forall A (x y:A) (e:x=y), eq_trans e (eq_sym e) = eq_refl.\nProof.\n  destruct e; reflexivity.\nDefined.\n\nTheorem eq_trans_assoc : forall A (x y z t:A) (e:x=y) (e':y=z) (e'':z=t),\n  eq_trans e (eq_trans e' e'') = eq_trans (eq_trans e e') e''.\nProof.\n  destruct e''; reflexivity.\nDefined.\n\n(** Extra properties of equality *)\n\nTheorem eq_id_comm_l : forall A (f:A->A) (Hf:forall a, a = f a), forall a, f_equal f (Hf a) = Hf (f a).\nProof.\n  intros.\n  unfold f_equal.\n  rewrite <- (eq_trans_sym_inv_l (Hf a)).\n  destruct (Hf a) at 1 2.\n  destruct (Hf a).\n  reflexivity.\nDefined.\n\nTheorem eq_id_comm_r : forall A (f:A->A) (Hf:forall a, f a = a), forall a, f_equal f (Hf a) = Hf (f a).\nProof.\n  intros.\n  unfold f_equal.\n  rewrite <- (eq_trans_sym_inv_l (Hf (f (f a)))).\n  set (Hfsymf := fun a => eq_sym (Hf a)).\n  change (eq_sym (Hf (f (f a)))) with (Hfsymf (f (f a))).\n  pattern (Hfsymf (f (f a))).\n  destruct (eq_id_comm_l f Hfsymf (f a)).\n  destruct (eq_id_comm_l f Hfsymf a).\n  unfold Hfsymf.\n  destruct (Hf a). simpl.\n  rewrite eq_trans_refl_l.\n  reflexivity.\nDefined.\n\nLemma eq_refl_map_distr : forall A B x (f:A->B), f_equal f (eq_refl x) = eq_refl (f x).\nProof.\n  reflexivity.\nQed.\n\nLemma eq_trans_map_distr : forall A B x y z (f:A->B) (e:x=y) (e':y=z), f_equal f (eq_trans e e') = eq_trans (f_equal f e) (f_equal f e').\nProof.\ndestruct e'.\nreflexivity.\nDefined.\n\nLemma eq_sym_map_distr : forall A B (x y:A) (f:A->B) (e:x=y), eq_sym (f_equal f e) = f_equal f (eq_sym e).\nProof.\ndestruct e.\nreflexivity.\nDefined.\n\nLemma eq_trans_sym_distr : forall A (x y z:A) (e:x=y) (e':y=z), eq_sym (eq_trans e e') = eq_trans (eq_sym e') (eq_sym e).\nProof.\ndestruct e, e'.\nreflexivity.\nDefined.\n\nLemma eq_trans_rew_distr : forall A (P:A -> Type) (x y z:A) (e:x=y) (e':y=z) (k:P x),\n    rew (eq_trans e e') in k = rew e' in rew e in k.\nProof.\n  destruct e, e'; reflexivity.\nQed.\n\nLemma rew_const : forall A P (x y:A) (e:x=y) (k:P),\n    rew [fun _ => P] e in k = k.\nProof.\n  destruct e; reflexivity.\nQed.\n\n\n(* Aliases *)\n\nNotation sym_eq := eq_sym (only parsing).\nNotation trans_eq := eq_trans (only parsing).\nNotation sym_not_eq := not_eq_sym (only parsing).\n\nNotation refl_equal := eq_refl (only parsing).\nNotation sym_equal := eq_sym (only parsing).\nNotation trans_equal := eq_trans (only parsing).\nNotation sym_not_equal := not_eq_sym (only parsing).\n\nHint Immediate eq_sym not_eq_sym: core.\n\n(** Basic definitions about relations and properties *)\n\nDefinition subrelation (A B : Type) (R R' : A->B->Prop) :=\n  forall x y, R x y -> R' x y.\n\nDefinition unique (A : Type) (P : A->Prop) (x:A) :=\n  P x /\\ forall (x':A), P x' -> x=x'.\n\nDefinition uniqueness (A:Type) (P:A->Prop) := forall x y, P x -> P y -> x = y.\n\n(** Unique existence *)\n\nNotation \"'exists' ! x .. y , p\" :=\n  (ex (unique (fun x => .. (ex (unique (fun y => p))) ..)))\n  (at level 200, x binder, right associativity,\n   format \"'[' 'exists'  !  '/  ' x  ..  y ,  '/  ' p ']'\")\n  : type_scope.\n\nLemma unique_existence : forall (A:Type) (P:A->Prop),\n  ((exists x, P x) /\\ uniqueness P) <-> (exists! x, P x).\nProof.\n  intros A P; split.\n  - intros ((x,Hx),Huni); exists x; red; auto.\n  - intros (x,(Hx,Huni)); split.\n    + exists x; assumption.\n    + intros x' x'' Hx' Hx''; transitivity x.\n      symmetry; auto.\n      auto.\nQed.\n\nLemma forall_exists_unique_domain_coincide :\n  forall A (P:A->Prop), (exists! x, P x) ->\n  forall Q:A->Prop, (forall x, P x -> Q x) <-> (exists x, P x /\\ Q x).\nProof.\n  intros A P (x & Hp & Huniq); split.\n  - intro; exists x; auto.\n  - intros (x0 & HPx0 & HQx0) x1 HPx1.\n    assert (H : x0 = x1) by (transitivity x; [symmetry|]; auto).\n    destruct H.\n    assumption.\nQed.\n\nLemma forall_exists_coincide_unique_domain :\n  forall A (P:A->Prop),\n  (forall Q:A->Prop, (forall x, P x -> Q x) <-> (exists x, P x /\\ Q x))\n  -> (exists! x, P x).\nProof.\n  intros A P H.\n  destruct H with (Q:=P) as ((x & Hx & _),_); [trivial|].\n  exists x. split; [trivial|].\n  destruct H with (Q:=fun x'=>x=x') as (_,Huniq).\n  apply Huniq. exists x; auto.\nQed.\n\n(** * Being inhabited *)\n\n(** The predicate [inhabited] can be used in different contexts. If [A] is\n    thought as a type, [inhabited A] states that [A] is inhabited. If [A] is\n    thought as a computationally relevant proposition, then\n    [inhabited A] weakens [A] so as to hide its computational meaning.\n    The so-weakened proof remains computationally relevant but only in\n    a propositional context.\n*)\n\nInductive inhabited (A:Type) : Prop := inhabits : A -> inhabited A.\n\nHint Resolve inhabits: core.\n\nLemma exists_inhabited : forall (A:Type) (P:A->Prop),\n  (exists x, P x) -> inhabited A.\nProof.\n  destruct 1; auto.\nQed.\n\nLemma inhabited_covariant (A B : Type) : (A -> B) -> inhabited A -> inhabited B.\nProof.\n  intros f [x];exact (inhabits (f x)).\nQed.\n\n(** Declaration of stepl and stepr for eq and iff *)\n\nLemma eq_stepl : forall (A : Type) (x y z : A), x = y -> x = z -> z = y.\nProof.\n  intros A x y z H1 H2. rewrite <- H2; exact H1.\nQed.\n\nDeclare Left Step eq_stepl.\nDeclare Right Step eq_trans.\n\nLemma iff_stepl : forall A B C : Prop, (A <-> B) -> (A <-> C) -> (C <-> B).\nProof.\n  intros ? ? ? [? ?] [? ?]; split; intros; auto.\nQed.\n\nDeclare Left Step iff_stepl.\nDeclare Right Step iff_trans.\n\nLocal Notation \"'rew' 'dependent' H 'in' H'\"\n  := (match H with\n      | eq_refl => H'\n      end)\n       (at level 10, H' at level 10,\n        format \"'[' 'rew'  'dependent'  '/    ' H  in  '/' H' ']'\").\n\n(** Equality for [ex] *)\nSection ex.\n  Local Unset Implicit Arguments.\n  Definition eq_ex_uncurried {A : Type} (P : A -> Prop) {u1 v1 : A} {u2 : P u1} {v2 : P v1}\n             (pq : exists p : u1 = v1, rew p in u2 = v2)\n  : ex_intro P u1 u2 = ex_intro P v1 v2.\n  Proof.\n    destruct pq as [p q].\n    destruct q; simpl in *.\n    destruct p; reflexivity.\n  Qed.\n\n  Definition eq_ex {A : Type} {P : A -> Prop} (u1 v1 : A) (u2 : P u1) (v2 : P v1)\n             (p : u1 = v1) (q : rew p in u2 = v2)\n  : ex_intro P u1 u2 = ex_intro P v1 v2\n    := eq_ex_uncurried P (ex_intro _ p q).\n\n  Definition eq_ex_hprop {A} {P : A -> Prop} (P_hprop : forall (x : A) (p q : P x), p = q)\n             (u1 v1 : A) (u2 : P u1) (v2 : P v1)\n             (p : u1 = v1)\n    : ex_intro P u1 u2 = ex_intro P v1 v2\n    := eq_ex u1 v1 u2 v2 p (P_hprop _ _ _).\n\n  Lemma rew_ex {A x} {P : A -> Type} (Q : forall a, P a -> Prop) (u : exists p, Q x p) {y} (H : x = y)\n  : rew [fun a => exists p, Q a p] H in u\n    = match u with\n        | ex_intro _ u1 u2\n          => ex_intro\n               (Q y)\n               (rew H in u1)\n               (rew dependent H in u2)\n      end.\n  Proof.\n    destruct H, u; reflexivity.\n  Qed.\nEnd ex.\n\n(** Equality for [ex2] *)\nSection ex2.\n  Local Unset Implicit Arguments.\n\n  Definition eq_ex2_uncurried {A : Type} (P Q : A -> Prop) {u1 v1 : A}\n             {u2 : P u1} {v2 : P v1}\n             {u3 : Q u1} {v3 : Q v1}\n             (pq : exists2 p : u1 = v1, rew p in u2 = v2 & rew p in u3 = v3)\n  : ex_intro2 P Q u1 u2 u3 = ex_intro2 P Q v1 v2 v3.\n  Proof.\n    destruct pq as [p q r].\n    destruct r, q, p; simpl in *.\n    reflexivity.\n  Qed.\n\n  Definition eq_ex2 {A : Type} {P Q : A -> Prop}\n             (u1 v1 : A)\n             (u2 : P u1) (v2 : P v1)\n             (u3 : Q u1) (v3 : Q v1)\n             (p : u1 = v1) (q : rew p in u2 = v2) (r : rew p in u3 = v3)\n  : ex_intro2 P Q u1 u2 u3 = ex_intro2 P Q v1 v2 v3\n    := eq_ex2_uncurried P Q (ex_intro2 _ _ p q r).\n\n  Definition eq_ex2_hprop {A} {P Q : A -> Prop}\n             (P_hprop : forall (x : A) (p q : P x), p = q)\n             (Q_hprop : forall (x : A) (p q : Q x), p = q)\n             (u1 v1 : A) (u2 : P u1) (v2 : P v1) (u3 : Q u1) (v3 : Q v1)\n             (p : u1 = v1)\n    : ex_intro2 P Q u1 u2 u3 = ex_intro2 P Q v1 v2 v3\n    := eq_ex2 u1 v1 u2 v2 u3 v3 p (P_hprop _ _ _) (Q_hprop _ _ _).\n\n  Lemma rew_ex2 {A x} {P : A -> Type}\n        (Q : forall a, P a -> Prop)\n        (R : forall a, P a -> Prop)\n        (u : exists2 p, Q x p & R x p) {y} (H : x = y)\n  : rew [fun a => exists2 p, Q a p & R a p] H in u\n    = match u with\n        | ex_intro2 _ _ u1 u2 u3\n          => ex_intro2\n               (Q y)\n               (R y)\n               (rew H in u1)\n               (rew dependent H in u2)\n               (rew dependent H in u3)\n      end.\n  Proof.\n    destruct H, u; reflexivity.\n  Qed.\nEnd ex2.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Init/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652496, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.712851482042086}}
{"text": "Require Import\n  Coq.Classes.RelationClasses Coq.Classes.Morphisms Coq.Program.Program\n  MathClasses.interfaces.universal_algebra MathClasses.interfaces.canonical_names MathClasses.theory.ua_subalgebra.\n\n(* In theory/ua_subalgebra.v we defined closed proper subsets and showed that\nthey yield subalgebras. We now expand on this result and show that they\nalso yield subvarieties (by showing that the laws still hold in the subalgebra). *)\n\nSection contents.\n  Context `{InVariety et A} `{@ClosedSubset et A _ _ P}. (* todo: why so ugly? *)\n\n  Definition Pvars (vars: Vars et (carrier P) nat): Vars et A nat\n    := λ s n, ` (vars s n).\n\n  (* To prove that the laws still hold in the subalgebra, we first prove that evaluation in it\n   is the same as evaluation in the original: *)\n\n  Program Fixpoint heq {o}: op_type (carrier P) o → op_type A o → Prop :=\n    match o with\n    | ne_list.one _ => λ a b, `a = b\n    | ne_list.cons _ _ => λ a b, ∀ u, heq (a u) (b u)\n    end.\n\n  Instance heq_proper {o}: Proper ((=) ==> (=) ==> iff) (@heq o).\n  Proof with intuition.\n   intros x y U x0 y0 K.\n   induction o; simpl in *.\n    destruct x, y.\n    change (x = x1) in U.\n    simpl in *.\n    split; intro.\n     transitivity x...\n     transitivity x0...\n    transitivity x1...\n    transitivity y0...\n   assert (∀ u, x u = y u). intros. apply U...\n   split; repeat intro.\n    apply -> (IHo (x u) (y u) (H1 u) (x0 (proj1_sig u)))...\n    apply K...\n   apply <- (IHo (x u) (y u) (H1 u) (x0 (proj1_sig u)))...\n   apply K...\n  Qed.\n\n  Lemma heq_eval vars {o} (t: T et o): heq (eval et vars t) (eval et (Pvars vars) t).\n  Proof with intuition.\n   induction t; simpl...\n     unfold Pvars...\n    simpl in IHt1.\n    generalize (IHt1 (eval et vars t3)). clear IHt1.\n    apply heq_proper.\n     pose proof (@eval_proper et (carrier P) _ _ _ nat (ne_list.cons y t1)).\n     apply H1; try intro...\n    pose proof (@eval_proper et A _ _ _ nat (ne_list.cons y t1)).\n    apply H1...\n    unfold heq in IHt2. (* todo: this wasn't needed in a previous Coq version *)\n    rewrite IHt2.\n    apply (@eval_proper et A _ _ _ nat (ne_list.one y))...\n   unfold impl, algebra_op.\n   generalize (subset_closed P o).\n   unfold algebra_op.\n   generalize (AlgebraOps0 o).\n   intros.\n   induction (et o); simpl in *...\n  Qed.\n\n  Lemma heq_eval_const vars {o} (t: T et (ne_list.one o)): ` (eval et vars t) = eval et (Pvars vars) t.\n  Proof. apply (heq_eval vars t). Qed.\n    (* todo: this specialization wasn't needed in a previous Coq version *)\n\n  Lemma laws s: et_laws et s → ∀ vars: ∀ a, nat → carrier P a, eval_stmt et vars s.\n  Proof with intuition.\n   intros.\n   generalize (@variety_laws et A _ _ _ s H1 (Pvars vars)). clear H1.\n   destruct s as [x [? [t t0]]].\n   induction x as [| [x1 [t1 t2]]]; simpl in *; intros.\n    unfold equiv, sig_equiv.\n    rewrite (heq_eval_const vars t).\n    rewrite (heq_eval_const vars t0)...\n   apply IHx, H1.\n   rewrite <- (heq_eval_const vars t1).\n   rewrite <- (heq_eval_const vars t2)...\n  Qed.\n\n  (* Which gives us our variety: *)\n\n  Global Instance: InVariety et (carrier P) := { variety_laws := laws }.\n\nEnd contents.\n", "meta": {"author": "coq-community", "repo": "math-classes", "sha": "c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc", "save_path": "github-repos/coq/coq-community-math-classes", "path": "github-repos/coq/coq-community-math-classes/math-classes-c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc/theory/ua_subvariety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7128514642510037}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_ss :\n\tforall P Q A B X U V,\n\tCol A B U ->\n\tCol A B V ->\n\tBetS P U X ->\n\tBetS Q V X ->\n\tnCol A B P ->\n\tnCol A B Q ->\n\tSS P Q A B.\nProof.\n\tintros P Q A B X U V.\n\tintros Col_A_B_U.\n\tintros Col_A_B_V.\n\tintros BetS_P_U_X.\n\tintros BetS_Q_V_X.\n\tintros nCol_A_B_P.\n\tintros nCol_A_B_Q.\n\n\texists X, U, V.\n\tsplit.\n\texact Col_A_B_U.\n\tsplit.\n\texact Col_A_B_V.\n\tsplit.\n\texact BetS_P_U_X.\n\tsplit.\n\texact BetS_Q_V_X.\n\tsplit.\n\texact nCol_A_B_P.\n\texact nCol_A_B_Q.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_ss.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7128514595896865}}
{"text": "(* http://www.iij-ii.co.jp/lab/techdoc/coqt/coqt2.html *)\nGoal forall (P Q : Prop), (forall P :Prop, (P -> Q) -> Q) -> ((P -> Q) -> P) -> P.\nintros.apply H0.intro.apply (H (P -> Q)).intros.apply H2.apply H1.Qed.\n  \nGoal forall (P Q R : Prop), (P -> Q) -> (Q -> R) -> P -> R.\nintros.apply H0.apply H.apply H1.Qed.\n\nInductive False : Prop :=.\nDefinition not (A: Prop) := A -> False.\nGoal forall P : Prop, P -> not (not P).\nintro.intros.intro.apply H0.apply H.Qed.\n\nInductive or (A B : Prop) : Prop :=\n| or_introl : A -> or A B\n| or_intror : B -> or A B.\nGoal forall (P Q : Prop), (or P Q) -> (or Q P).\nintros.destruct H.apply or_intror.apply H.apply or_introl.apply H.Qed.\n\nInductive and (A B : Prop) : Prop :=\n  conj : A -> B -> and A B.\nGoal forall (P Q : Prop), (and P Q) -> (and Q P).\nintros.apply conj.destruct H.apply H0.destruct H.apply H.Qed.\n\nGoal forall (P : Prop), not (and P (not P)).\n  intros.intro.destruct H.destruct H0.apply H.Qed.\n\nGoal forall (P Q : Prop), (or (not P) (not Q)) -> (not (and P Q)).\nintros.intro.destruct H0.destruct H.apply H.apply H0.apply H.apply H1.Qed.\n\nGoal forall (P : Prop), (forall (P : Prop), (not (not P)) -> P) -> (or P (not P)).\nintros.apply H.intro.apply H0.right.intro.apply H0.left.apply H1.", "meta": {"author": "unaoya", "repo": "coq_intro", "sha": "c417320df036d96f22744c7bb90695160c012e91", "save_path": "github-repos/coq/unaoya-coq_intro", "path": "github-repos/coq/unaoya-coq_intro/coq_intro-c417320df036d96f22744c7bb90695160c012e91/proof-editing-mode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7126612144038492}}
{"text": "Require Import Indices.\nRequire Import SetoidList.\n(* Require Import SetoidListEquiv. *)\n\n\nModule mkFacts (I:IndexType).\n\n  (* perhaps I should use PairOrderedType and build a ListOrderedType ? *)\n\n  Definition ci_eq  (ci ci': I.t * I.t) := I.eq (fst ci) (fst ci') /\\ I.eq (snd ci) (snd ci').\n\n  Theorem ci_eq_refl: forall ci, ci_eq ci ci.\n  Proof.\n    intros; destruct ci; unfold ci_eq; simpl;  split; apply I.eq_refl.\n  Qed.\n\n  Theorem ci_eq_sym: forall ci ci', ci_eq ci ci' -> ci_eq ci' ci.\n  Proof.\n    intros.\n    destruct ci; destruct ci'.\n    unfold ci_eq in *; simpl in *; destruct H; split;\n      apply I.eq_sym; assumption.\n  Qed.\n\n  Theorem ci_eq_trans: forall ci1 ci2 ci3,\n    ci_eq ci1 ci2 -> ci_eq ci2 ci3 -> ci_eq ci1 ci3.\n  Proof.\n    intros.\n    destruct ci1; destruct ci2; destruct ci3.\n    unfold ci_eq in *; simpl in *; destruct H; destruct H0; split;\n      [apply I.eq_trans with t1 |apply I.eq_trans with t2]; auto.\n  Qed.\n\n  Theorem ci_eq_Equiv : Equivalence ci_eq.\n    apply Build_Equivalence.\n    unfold Reflexive; apply ci_eq_refl.\n    unfold Symmetric; apply ci_eq_sym.\n    unfold Transitive; apply ci_eq_trans.\n  Qed.\n\n  Definition cil_eq := eqlistA ci_eq.\n\n  Definition cil_Equiv : Equivalence cil_eq.\n  eapply eqlistA_equiv.\n  exact ci_eq_Equiv.\n  Defined.\n\nEnd mkFacts.\n", "meta": {"author": "doerrie", "repo": "confinement-proof", "sha": "db7bfb3522990d0820de64f13baa97b67e694c44", "save_path": "github-repos/coq/doerrie-confinement-proof", "path": "github-repos/coq/doerrie-confinement-proof/confinement-proof-db7bfb3522990d0820de64f13baa97b67e694c44/CapIndexListFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.7126612070701661}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith List Wellfounded.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import php.\n\nFrom Undecidability.Shared.Libs.DLW.Wf \n  Require Import acc_irr measure_ind wf_chains.\n\nSet Implicit Arguments.\n\n(* Results about the well-foundedness of strict (reverse)\n    inclusion between lists \n\n    These proofs avoid the need of decidable equality\n    and use the finitary Pigeon Hole Principle (PHP) \n    instead\n*)\n\nSection sincl.\n\n  (* Strict inclusion between lists is a well founded relation *)\n\n  Variable (X : Type).\n\n  Implicit Type (l m : list X).\n    \n  (* sincl l m if incl l m and there is a witness in m \\ l *)\n\n  Definition sincl l m := incl l m /\\ exists x, ~ In x l /\\ In x m.\n\n  (* Any n-chain m ~~> l contains a \n     duplication-free subset of l of size n \n     which does not intersect m  *)\n\n  Lemma sincl_chain n m l :   \n       chain sincl n m l -> incl m l \n                         /\\ exists ll, ~ list_has_dup ll \n                                      /\\ length ll = n \n                                      /\\ incl ll l\n                                      /\\ forall x, In x m -> In x ll -> False.\n  Proof.\n    induction 1 as [ m | n m l k H1 H2 (H7 & ll & H3 & H4 & H5 & H6) ].\n    + split.\n      * intros ?; auto.\n      * exists nil; simpl; repeat split; auto.\n        - inversion 1.\n        - intros _ [].\n    + split.\n      * intros ? ?; apply H7, H1; auto.\n      * destruct H1 as (G1 & x & G2 & G3).\n        exists (x::ll); simpl; repeat split; auto.\n        - contradict H3.\n          apply list_has_dup_cons_inv in H3.\n          destruct H3 as [ H3 | ]; auto.\n          destruct (H6 x); auto.\n        - apply incl_cons; auto.\n        - intros y F1 [ F2 | F2 ]; subst.\n          ** tauto.\n          ** apply (H6 y); auto.\n  Qed.\n\n  (* Hence, by the PHP, if there is a n-chain to l then n must be less than length l *)\n\n  Corollary sincl_chain_bounded l m n : chain sincl n m l -> n <= length l.\n  Proof.\n    intros H.\n    apply sincl_chain in H.\n    destruct H as (_ & ll & H1 & H2 & H3 & _).\n    destruct (le_lt_dec n (length l)) as [ | C ]; auto.\n    subst; destruct H1.\n    apply finite_php_dup with l; auto.\n  Qed.\n\n  (* Hence sincl is well-founded because n-chains to l have length bounded by length l *)\n   \n  Theorem wf_sincl : well_founded sincl.\n  Proof.\n    apply wf_chains.\n    intros l; exists (length l).\n    intros ? ?; apply sincl_chain_bounded.\n  Qed.\n\nEnd sincl.\n\nArguments wf_sincl {X}.\n\nSection rincl_fin.\n\n  (* Strict reverse inclusion between lists is well founded over a finite domain *)\n \n  (* M the upper-bound/finiteness of the domain *)\n\n  Variable (X : Type) (M : list X). \n\n  (* l cap M strictly contains in m cap M *)\n\n  Definition rincl_fin l m := (forall x, In x m -> In x M -> In x l) \n                            /\\ exists x, ~ In x m /\\ In x l /\\ In x M.\n\n  (* Any n-chain m ~~> l contains a duplication-free subset of M of size n *)\n                            \n  Lemma rincl_fin_chains n m l :   chain rincl_fin n m l \n                   -> exists ll, ~ list_has_dup ll \n                                /\\ incl ll M \n                                /\\ length ll = n \n                                /\\ incl ll m.\n  Proof.\n    induction 1 as [ x | n m k l H1 H2 (ll & H3 & H4 & H5 & H6) ].\n    + exists nil.\n      repeat split; simpl; auto; inversion 1.\n    + destruct H1 as (H1 & a & G1 & G2 & G3).\n      exists (a::ll).\n      repeat split.\n      * contradict H3.\n        apply list_has_dup_cons_inv in H3.\n        destruct H3 as [ H3 | ]; auto.\n        destruct G1; apply H6; auto.\n      * apply incl_cons; auto.\n      * simpl; f_equal; auto.\n      * apply incl_cons; auto.\n        intros ? ?; auto.\n  Qed.\n\n  (* Hence, by the PHP, if there is a n-chain to l then n is less than length M *)\n\n  Corollary rincl_fin_chain_bounded l m n : chain rincl_fin n m l -> n <= length M.\n  Proof.\n    intros H.\n    apply rincl_fin_chains in H.\n    destruct H as (ll & H1 & H2 & H3 & _).\n    destruct (le_lt_dec n (length M)) as [ | C ]; auto.\n    subst n; destruct H1.\n    apply finite_php_dup with M; auto.\n  Qed.\n\n  Theorem wf_rincl_fin : well_founded rincl_fin.\n  Proof.\n    apply wf_chains.\n    intros l; exists (length M).\n    intros ? ?; apply rincl_fin_chain_bounded.\n  Qed.\n\nEnd rincl_fin.\n\nArguments wf_rincl_fin {X}.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/Shared/Libs/DLW/Wf/wf_incl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.7126611975463828}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=  Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : lst) (qreva_arg1 : lst) : lst\n           := match qreva_arg0, qreva_arg1 with\n              | Nil, x => x\n              | Cons z x, y => qreva x (Cons z y)\n              end.\n\nLemma append_nil : forall (x : lst), append x Nil = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma append_assoc : forall (x y z : lst), append (append x y) z = append x (append y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma rev_append : forall (x y : lst), rev (append x y) = append (rev y) (rev x).\nProof.\n   intros.\n   induction x.\n   - simpl. rewrite append_nil. reflexivity.\n   - simpl. rewrite IHx. rewrite append_assoc. reflexivity.\nQed.\n\nLemma rev_rev : forall (x : lst), rev (rev x) = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite rev_append. simpl. rewrite IHx. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (rev (qreva x (rev y))) (append y x).\nProof.\n   induction x.\n   - intros. simpl. rewrite rev_rev. rewrite append_nil. reflexivity.\n   - intros. simpl. rewrite (eq_refl : Cons n (rev y) = append (rev (Cons n Nil)) (rev y)). rewrite <- rev_append. rewrite IHx. rewrite append_assoc. simpl. reflexivity.\nQed.\n              \n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal78.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7126086544984548}}
{"text": "(*Here we show that for any countable type (which injects into\n  the natural numbers), we can generate a list of distinct\n  elements of the type not present in some input list.\n  This is useful for generating new free variables and\n  unique names.*)\nRequire Import Coq.Lists.List.\nRequire Import Coq.Logic.FinFun.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Common.\nSection NoDupsList.\n\nContext {A: Type}.\nVariable (f: nat -> A).\n(*We have an injection nat -> A*)\nVariable (Hinj: forall n1 n2, f n1 = f n2 -> n1 = n2).\n\n(*Generate list with n distinct elements*)\nDefinition gen_dist (n: nat) : list A :=\n  map f (seq 0 n).\n\nLemma gen_dist_length (n: nat): length (gen_dist n) = n.\nProof.\n  unfold gen_dist. rewrite map_length, seq_length. reflexivity.\nQed.\n\nLemma gen_dist_correct (n: nat): NoDup (gen_dist n).\nProof.\n  unfold gen_dist. apply Injective_map_NoDup.\n  unfold Injective. apply Hinj.\n  apply seq_NoDup.\nQed.\n\n(*Generate list of n distinct elements, all of which are not\n  in l*)\nVariable eq_dec: forall (x y: A), {x=y} +{x<>y}.\nDefinition gen_notin (n: nat) (l: list A): list A :=\n  firstn n \n    (filter (fun x => negb(in_dec eq_dec x l)) (gen_dist (n + length l))).\n\n(*Proving that this is correct is not trivial*)\n(*A version of the pigeonhole principle: given two lists l1 and l2,\n  if l2 is larger and has no duplicates, it has at least \n    (length l2) - (length l1) elements that are not in l1*)\nLemma php (l1 l2: list A):\n  NoDup l2 -> \n  length l1 <= length l2 ->\n  length l2 - length l1 <= \n    length (filter (fun x => negb(in_dec eq_dec x l1)) l2).\nProof.\n  (*Try alternate, then go back*)\n  revert l2. induction l1; intros; auto.\n  - simpl. rewrite Nat.sub_0_r.\n    assert ((filter (fun _ : A => true) l2) = l2). {\n      apply all_filter. apply forallb_forall. auto.\n    }\n    rewrite H1. auto.\n  - destruct (in_dec eq_dec a l2).\n    2: {\n      rewrite filter_in_notin; auto; simpl.\n      specialize (IHl1 _ H). lia.\n    }\n    (*For this one, we have to split l2 depending on\n      where a appears*)\n    apply in_split in i.\n    destruct i as [p1 [p2 Hl2]].\n    rewrite Hl2, filter_app, filter_cons.\n    assert (Hnodup:=H).\n    rewrite Hl2 in H.\n    rewrite NoDup_app_iff in H. destruct H as [Hn1 [Hn2 [Hnotin1 Hnotin2]]].\n    inversion Hn2. subst x l.\n    assert (~ In a p1). {\n      apply Hnotin2. left; auto.\n    } \n    rewrite !filter_in_notin; auto.\n    simpl. destruct (eq_dec a a); auto; try contradiction.\n    simpl. rewrite <- filter_app.\n    assert (Hn3: NoDup (p1 ++ p2)). {\n      rewrite NoDup_app_iff. repeat split; auto.\n      - intros; intro C. apply (Hnotin1 x H1). right; auto.\n      - intros; apply Hnotin2. right; auto.\n    }\n    specialize (IHl1 _ Hn3).\n    rewrite !app_length; simpl. simpl in H0.\n    rewrite !app_length in IHl1. lia.\nQed.\n\n(*Now we can prove our function correct*)\nLemma gen_notin_length (n: nat) (l: list A):\n  length (gen_notin n l) = n.\nProof.\n  unfold gen_notin.\n  rewrite firstn_length_le; auto.\n  pose proof (php l (gen_dist (n + length l))).\n  rewrite gen_dist_length in H.\n  specialize (H (gen_dist_correct _)). lia.\nQed.\n\nLemma gen_notin_nodup (n: nat) (l: list A):\n  NoDup (gen_notin n l).\nProof.\n  unfold gen_notin.\n  apply NoDup_firstn.\n  apply NoDup_filter.\n  apply gen_dist_correct.\nQed.\n\nLemma gen_notin_notin (n: nat) (l: list A):\n  forall y, In y (gen_notin n l) -> ~ In y l.\nProof.\n  intros. unfold gen_notin in H.\n  apply In_firstn in H.\n  rewrite in_filter in H. destruct H.\n  destruct (in_dec eq_dec y l); auto. inversion H.\nQed.\n\nLemma add_notin_nodup (l1: list A) n:\n  NoDup l1 ->\n  NoDup (l1 ++ gen_notin n l1).\nProof.\n  intros.\n  rewrite NoDup_app_iff; split_all; auto.\n  + apply gen_notin_nodup; apply nth_vs_inj.\n  + intros. intro C. apply gen_notin_notin in C. contradiction.\n  + intros. apply gen_notin_notin in H0. auto.\nQed.\n\nEnd NoDupsList.\n\n(*We want to apply this to strings and vsymbols.\n  To do this, we want to give decent names (at least\n  x0, x1, etc) and not just 0, 00, 000 or something\n  easy to define and prove injective. Converting \n  nats to strings is surprisingly difficult*)\n\n(*Apply this to vsymbols*)\nRequire Import Types.\nRequire Import Syntax.\nRequire Import Coq.Strings.String.\nRequire Import FunInd.\nRequire Import Recdef.\nFrom mathcomp Require Import all_ssreflect ssrnat div.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nSection NatToStr.\n\nLocal Open Scope string_scope.\n\nDefinition nat_to_digit (n : nat) : string :=\n  match n with\n    | 0 => \"0\"%string\n    | 1 => \"1\"%string\n    | 2 => \"2\"%string\n    | 3 => \"3\"%string\n    | 4 => \"4\"%string\n    | 5 => \"5\"%string\n    | 6 => \"6\"%string\n    | 7 => \"7\"%string\n    | 8 => \"8\"%string\n    | _ => \"9\"%string\n  end.\n\n(*Gives list of digits in reverse order*)\nFunction nat_to_digits (n : nat) {measure (fun x => x) n} : list string :=\n  if n < 10 then [nat_to_digit (n %% 10)] else \n  nat_to_digit (n %% 10) :: nat_to_digits (n %/ 10).\nProof.\n  move=> n Hn10. apply /ltP.\n  apply ltn_Pdiv=>//.\n  move: Hn10. by case: n.\nDefined.\n\nLemma nat_to_digits_simpl n :\n  nat_to_digits n = nat_to_digit (n %% 10) :: if n < 10 then nil else \n    nat_to_digits (n %/ 10).\nProof.\n  rewrite nat_to_digits_equation.\n  by case: (n < 10).\nQed.\n\n(*Injectivity*)\n\nLtac solve_or :=\n  match goal with\n  | |- ?P \\/ ?Q => solve[left; solve_or] + solve[right; solve_or] \n  | |- _ => auto\n  end.\n\n(*Makes things easier*)\nLemma nat_lt10 (n: nat):\n  n < 10 ->\n  n = 0 \\/ n = 1 \\/ n = 2 \\/ n = 3 \\/ n =4 \\/\n  n = 5 \\/ n = 6 \\/ n = 7 \\/ n = 8 \\/ n= 9.\nProof.\n  move=> Hn.\n  do 10 (destruct n as [| n]; solve_or). inversion Hn.\nQed.\n\nLtac case_or :=\n  repeat match goal with\n  | H: ?P \\/ ?Q |- _ => destruct H\n  end.\n\n(*Just do all 100 cases*)\nLemma nat_to_digit_inj (n1 n2: nat):\n  n1 < 10 ->\n  n2 < 10 ->\n  nat_to_digit n1 = nat_to_digit n2 ->\n  n1 = n2.\nProof.\n  move=>Hn1 Hn2.\n  apply nat_lt10 in Hn1; apply nat_lt10 in Hn2.\n  case_or; subst; simpl; auto; intros H; inversion H.\nQed.\n\nLemma nat_to_digits_nil n:\n  ~ (nat_to_digits n = nil).\nProof. \n  by rewrite nat_to_digits_simpl.\nQed.\n\nLemma modn_inj (m n d: nat):\n  m < d ->\n  n < d ->\n  m = n %[mod d] ->\n  m = n.\nProof.\n  move=> Hm Hn Hmod.\n  by rewrite (divn_eq m d) (divn_eq n d) !divn_small.\nQed.\n\nLemma nat_to_digits_inj n1 n2:\n  nat_to_digits n1 = nat_to_digits n2 ->\n  n1 = n2.\nProof.\n  move: n2.\n  apply nat_to_digits_ind with\n    (P:=fun m1 m2 => forall n2, m2 = nat_to_digits n2 -> m1 = n2).\n  - move=> n Hn n2.\n    rewrite nat_to_digits_simpl => [[]].\n    case Hn2: (n2 < 10).\n    + move=> Hdig _.\n      apply nat_to_digit_inj in Hdig; try by\n      apply ltn_pmod.\n      by apply (modn_inj _ _ _ Hn).\n    + by rewrite nat_to_digits_simpl.\n  - move=> n2 [//| Hn2 _ Hdigits n3].\n    rewrite (nat_to_digits_simpl n3).\n    case Hn3: (n3 < 10).\n    + move=> []. by rewrite nat_to_digits_simpl.\n    + move=> [Heq1 Heq2].\n      apply Hdigits in Heq2.\n      apply nat_to_digit_inj in Heq1; try by\n      apply ltn_pmod.\n      by rewrite (divn_eq n2 10) (divn_eq n3 10) Heq1 Heq2.\nQed.\n\n(*Convert digits to string*)\nDefinition digits_to_string (l: list string) : string :=\n  concat \"\" l.\n\n(*How is this not in the stdlib?*)\nLemma append_length s1 s2:\n  length (s1 ++ s2) = length s1 + length s2.\nProof.\n  elim: s1 =>//=a s IH. by rewrite IH.\nQed.\n\n(*Intermediate cases for injectivity - concat is annoying*)\n\nLemma concat_nil l:\n  (forall x, In x l -> length x = 1) -> \n  concat \"\" l = \"\" -> l = nil.\nProof.\n  case: l => //= x l Hallin Heq.\n  have //: 1 <= length \"\".\n  rewrite -Heq {Heq}. move: Hallin.\n  by case: l =>//=[Hallin | y l Hallin];\n  [|rewrite append_length]; rewrite Hallin; auto.\nQed.\n\nLemma concat_cons_case x1 x2 y1 l1:\n  length x1 = 1 ->\n  length x2 = 1 ->\n  length y1 = 1 ->\n  x1 ++ concat \"\" (y1 :: l1) <> x2.\nProof.\n  move=> Hlen1 Hlen2 Hlen3.\n  rewrite /=. case: l1=>[| z1 l1].\n  - move=> Heq.\n    have: length x1 + length y1 = length x2 by \n      rewrite -Heq append_length.\n    by rewrite Hlen1 Hlen2 Hlen3.\n  - move=> Heq.\n    have: length x1 + length y1 + length (concat \"\" (z1 :: l1)) =\n      length x2 by rewrite -Heq !append_length addnA.\n    rewrite Hlen1 Hlen2 Hlen3 => Heq2. \n    by have: 1 + 1 <= 1 by rewrite -{3}Heq2.\nQed.\n\nLemma append_inj s1 s2 s3 s4:\n  length s1 = length s2 ->\n  s1 ++ s3 = s2 ++ s4 ->\n  s1 = s2 /\\ s3 = s4.\nProof.\n  revert s2.\n  elim: s1 => [[| a2 s2]//=| a1 s1/= IH [| a2 s2]//= [Hlen] [Hstr] Heq].\n  apply IH in Heq=>//. case: Heq => [Hseq Hseq2].\n  by subst.\nQed.\n\nLemma concat_cons x1 x2 l1 l2:\n  (forall x, In x (x1 :: l1) -> length x = 1) ->\n  (forall x, In x (x2 :: l2) -> length x = 1) ->\n  concat \"\" (x1 :: l1) = concat \"\" (x2 :: l2) ->\n  x1 = x2 /\\ concat \"\" l1 = concat \"\" l2.\nProof.\n  rewrite /=. case: l1 =>[| y1 l1]; case: l2 =>[| y2 l2] //.\n  - move=>/= Hall1 Hall2 Heq. symmetry in Heq.\n    by apply concat_cons_case in Heq; auto.\n  - move=>/= Hall1 Hall2 Heq.\n    by apply concat_cons_case in Heq; auto.\n  - move=> Hall1 Hall2 Heq.\n    by apply append_inj in Heq; last by\n      rewrite Hall1; auto; rewrite Hall2; auto.\nQed.\n\n\nLemma digits_to_string_inj (l1 l2: list string):\n  (forall x, In x l1 -> length x = 1) ->\n  (forall x, In x l2 -> length x = 1) ->\n  digits_to_string l1 = digits_to_string l2 ->\n  l1 = l2.\nProof.\n  revert l2. rewrite /digits_to_string.\n  elim: l1=>[/=| x1 l1 IHl [|x2 l2]].\n  - move=>l2 _ Hallin Heq.\n    symmetry in Heq. by apply concat_nil in Heq.\n  - move=> Hallin _ Heq. by apply concat_nil in Heq.\n  - move=> Hall1 Hall2 Heq.\n    apply concat_cons in Heq=>//.\n    case: Heq => [Hxeq Hceq].\n    rewrite Hxeq. f_equal. by apply IHl=>//;\n    [intros; apply Hall1 | intros; apply Hall2]=>/=; auto.\nQed.\n\nLemma rev_inj {A: Type} (l1 l2: list A):\n  rev l1 = rev l2 ->\n  l1 = l2.\nProof.\n  move=> Hrev.\n  by rewrite -(revK l1) Hrev revK.\nQed.\n\n(*All things in digit list have length 1*)\nLemma nat_to_digit_len n:\n  length (nat_to_digit n) = 1.\nProof.\n  repeat (destruct n; auto).\nQed.\n\nLemma nat_to_digits_len n:\n  forall x, In x (nat_to_digits n) -> length x = 1.\nProof.\n  apply nat_to_digits_ind with (P:=fun m1 m2 => forall x, In x m2 -> length x = 1).\n  - move=> n1 Hn1 x/= [Hx | []]. by rewrite -Hx nat_to_digit_len.\n  - move=> n1 [//| Hn1 _] IH x/= [Hh | Htl].\n    + by rewrite -Hh nat_to_digit_len.\n    + by apply IH.\nQed.\n\nLemma in_rev {A: Type} x (l: list A):\n  In x l <-> In x (rev l).\nProof.\n  elim: l=>//= y l IH.\n  by rewrite IH rev_cons -cats1 in_app_iff /= or_false_r or_comm.\nQed.\n\n(*Finally, the full function and theorem*)\nDefinition nat_to_string (n: nat) : string :=\n  digits_to_string (rev (nat_to_digits n)).\n\n(*Some tests*)\nEval compute in (nat_to_string 654).\nEval compute in (nat_to_string 0).\nEval compute in (nat_to_string 1000).\n\nLemma nat_to_string_inj n1 n2:\n  nat_to_string n1 = nat_to_string n2 ->\n  n1 = n2.\nProof.\n  rewrite /nat_to_string.\n  move=> Hn.\n  apply digits_to_string_inj in Hn;\n  try (move=> x; rewrite -in_rev; apply nat_to_digits_len).\n  apply rev_inj in Hn.\n  by apply nat_to_digits_inj in Hn.\nQed.\n\nEnd NatToStr.\n\n(*Get the string xn*)\nDefinition nth_str (n: nat) : string :=\n  \"x\" ++ nat_to_string n.\n\nLemma nth_str_inj: forall n1 n2,\n  nth_str n1 = nth_str n2 ->\n  n1 = n2.\nProof.\n  intros n1 n2. unfold nth_str.\n  intros. inversion H.\n  apply nat_to_string_inj in H1; auto.\nQed.\n\nDefinition nth_vs (n: nat) : vsymbol :=\n  (nth_str n, vty_int).\n\nLemma nth_vs_inj: forall n1 n2,\n  nth_vs n1 = nth_vs n2 ->\n  n1 = n2.\nProof.\n  intros. unfold nth_vs in H. inversion H; subst.\n  apply nat_to_string_inj in H1; auto.\nQed.\n\n(*We give a specific function for generating n distinct\n  vsymbols not in list l*)\nDefinition gen_vars (n: nat) (l: list vsymbol) :=\n  gen_notin nth_vs vsymbol_eq_dec n l.\n\nLemma gen_vars_length (n: nat) (l: list vsymbol):\n  List.length (gen_vars n l) = n.\nProof.\n  apply gen_notin_length. apply nth_vs_inj.\nQed.\n\nLemma gen_vars_nodup (n: nat) (l: list vsymbol):\n  NoDup (gen_vars n l).\nProof.\n  apply gen_notin_nodup. apply nth_vs_inj.\nQed.\n\nLemma gen_vars_notin (n: nat) (l: list vsymbol):\n  forall x, In x (gen_vars n l) -> ~ In x l.\nProof.\n  apply gen_notin_notin.\nQed.\n\n(*And one to generate new variable names*)\nDefinition gen_strs (n: nat) (l: list vsymbol) : list string :=\n  gen_notin nth_str string_dec n (map fst l).\n\nLemma gen_strs_length n l:\n  List.length (gen_strs n l) = n.\nProof.\n  apply gen_notin_length. apply nth_str_inj.\nQed.\n\nLemma gen_strs_nodup n l:\n  NoDup (gen_strs n l).\nProof.\n  apply gen_notin_nodup. apply nth_str_inj.\nQed.\n\nLemma gen_strs_notin (n: nat) (l: list vsymbol):\n  forall (x: vsymbol), In (fst x) (gen_strs n l) -> ~ In x l.\nProof.\n  intros. apply gen_notin_notin in H.\n  rewrite in_map_iff in H. intro Hin.\n  apply H. exists x. split; auto.\nQed.", "meta": {"author": "joscoh", "repo": "why3-semantics", "sha": "d4d1801e43728a599ffd5442e3b6701797e61774", "save_path": "github-repos/coq/joscoh-why3-semantics", "path": "github-repos/coq/joscoh-why3-semantics/why3-semantics-d4d1801e43728a599ffd5442e3b6701797e61774/proofs/core/GenElts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7126086412719154}}
{"text": "Require Export XR_R.\nRequire Export XR_Rlt.\nRequire Export XR_Rtotal_order.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rdichotomy : forall r1 r2, r1 <> r2 -> r1 < r2 \\/ r2 < r1.\nProof.\n  intros x y.\n  unfold not.\n  intro hneq.\n  destruct (Rtotal_order x y) as [ hxy | [ heq | hxy ] ].\n  { left. exact hxy. }\n  {\n    specialize (hneq heq).\n    contradiction.\n  }\n  { right. exact hxy. }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rdichotomy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7125794954424841}}
{"text": "Require Export Families.\nRequire Export Image.\nRequire Import ImageImplicit.\nRequire Import FiniteTypes.\nRequire Export EnsemblesTactics.\n\nSet Implicit Arguments.\n\nSection IndexedFamilies.\n\nVariable A T:Type.\nDefinition IndexedFamily := A -> Ensemble T.\nVariable F:IndexedFamily.\n\nInductive IndexedUnion : Ensemble T :=\n  | indexed_union_intro: forall (a:A) (x:T),\n    In (F a) x -> In IndexedUnion x.\n\nInductive IndexedIntersection : Ensemble T :=\n  | indexed_intersection_intro: forall (x:T),\n    (forall a:A, In (F a) x) -> In IndexedIntersection x.\n\nEnd IndexedFamilies.\n\nSection IndexedFamilyFacts.\n\n(* unions and intersections over subsets of the index set *)\nLemma sub_indexed_union: forall {A B T:Type} (f:A->B)\n  (F:IndexedFamily B T),\n  let subF := (fun a:A => F (f a)) in\n    Included (IndexedUnion subF) (IndexedUnion F).\nProof.\nunfold Included.\nintros.\ndestruct H.\napply indexed_union_intro with (f a).\nassumption.\nQed.\n\nLemma sub_indexed_intersection: forall {A B T:Type} (f:A->B)\n  (F:IndexedFamily B T),\n  let subF := (fun a:A => F (f a)) in\n    Included (IndexedIntersection F) (IndexedIntersection subF).\nProof.\nunfold Included.\nintros.\nconstructor.\ndestruct H.\nintro.\napply H.\nQed.\n\nLemma empty_indexed_intersection: forall {T:Type}\n  (F:IndexedFamily False T),\n  IndexedIntersection F = Full_set.\nProof.\nintros.\napply Extensionality_Ensembles; red; split; red; intros;\n  auto with sets.\nconstructor.\nconstructor.\ndestruct a.\nQed.\n\nLemma empty_indexed_union: forall {T:Type}\n  (F:IndexedFamily False T),\n  IndexedUnion F = Empty_set.\nProof.\nintros.\napply Extensionality_Ensembles; red; split; red; intros.\ndestruct H.\ndestruct a.\ndestruct H.\nQed.\n\nLemma finite_indexed_union {A T : Type} {F : IndexedFamily A T} :\n  FiniteT A ->\n  (forall a, Finite _ (F a)) ->\n  Finite _ (IndexedUnion F).\nProof.\nintro H.\ninduction H;\n  intros.\n- replace (IndexedUnion F) with (@Empty_set T).\n  + constructor.\n  + extensionality_ensembles.\n    destruct a.\n- replace (IndexedUnion F) with (Union (IndexedUnion (fun t => In (F (Some t)))) (F None)).\n  apply Union_preserves_Finite.\n  + apply IHFiniteT.\n    intro.\n    apply H0.\n  + apply H0.\n  + extensionality_ensembles.\n    * econstructor.\n      eassumption.\n    * econstructor.\n      eassumption.\n    * destruct a.\n      ** left.\n         econstructor.\n         eassumption.\n      ** now right.\n- replace (IndexedUnion F) with (IndexedUnion (fun x => F (f x))).\n  + apply IHFiniteT.\n    intro.\n    apply H1.\n  + extensionality_ensembles.\n    * econstructor.\n      eassumption.\n    * destruct H0.\n      rewrite <- (H3 a) in H2.\n      econstructor.\n      eassumption.\nQed.\n\nEnd IndexedFamilyFacts.\n\nSection IndexedFamilyToFamily.\n\n(* relation to families of subsets of T *)\nVariable T:Type.\nVariable A:Type.\nVariable F:IndexedFamily A T.\n\nDefinition ImageFamily : Family T :=\n  Im Full_set F.\n\nLemma indexed_to_family_union: IndexedUnion F = FamilyUnion ImageFamily.\nProof.\napply Extensionality_Ensembles.\nunfold Same_set.\nunfold Included.\nintuition.\ndestruct H.\napply family_union_intro with (F a).\napply Im_intro with a.\nconstructor.\nreflexivity.\nassumption.\n\ndestruct H.\ndestruct H.\napply indexed_union_intro with x0.\nrewrite <- H1.\nassumption.\nQed.\n\nLemma indexed_to_family_intersection:\n  IndexedIntersection F = FamilyIntersection ImageFamily.\nProof.\napply Extensionality_Ensembles.\nunfold Same_set.\nunfold Included.\nintuition.\nconstructor.\nintros.\ndestruct H.\ndestruct H0.\nrewrite H1.\napply H.\n\nconstructor.\nintro.\ndestruct H.\napply H.\napply Im_intro with a.\nconstructor.\nreflexivity.\nQed.\n\nEnd IndexedFamilyToFamily.\n", "meta": {"author": "coq-community", "repo": "zorns-lemma", "sha": "aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8", "save_path": "github-repos/coq/coq-community-zorns-lemma", "path": "github-repos/coq/coq-community-zorns-lemma/zorns-lemma-aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8/IndexedFamilies.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7125794846872933}}
{"text": "(** * Uniform die program. *)\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nFrom Coq Require Import Streams Basics QArith String Lia Lra.\nLocal Open Scope program_scope.\nLocal Open Scope string_scope.\n\nFrom ITree Require Import\n  ITree ITreeFacts.\nImport ITreeNotations.\nLocal Open Scope itree_scope.\n\nFrom zar Require Import\n  compile cotree cocwp cpGCL cpo cwp equidistribution eR misc itree order tactics tree.\nLocal Open Scope cpGCL_scope.\n\nRequire Import prelude.\n\nDefinition die (out : string) (n : nat) : cpGCL :=\n  CUniform (const n) (fun m => out <-- m).\n\nLemma wf_die (out : string) (n : nat) :\n  (0 < n)%nat ->\n  wf_cpGCL (die out n).\nProof. intro Hlt; repeat constructor; auto. Qed.\n\n(** The probability of assigning any m < n to the output variable is\n    equal to 1/n. *)\nTheorem die_correct (out : string) (n m : nat) :\n  (m < n)%nat ->\n  cwp (die out n) (fun s => if Nat.eqb (as_nat (s out)) m then 1 else 0) empty =\n    1 / INeR n.\nProof.\n  intro Hn.\n  unfold cwp, die, wp, wlp, const; simpl; eRauto.\n  unfold upd; simpl.  \n  rewrite String.eqb_refl; simpl.\n  assert (H: sum (List.map (fun _ : nat => 1 / INeR n) (range n)) = 1).\n  { rewrite sum_map_const with (c := 1 / INeR n).\n    - rewrite range_length.\n      unfold eRdiv.\n      eRauto.\n      rewrite eRinv_r; eRauto.\n      destruct n.\n      + inv Hn.\n      + apply not_0_INeR; lia.\n    - apply List.Forall_impl with (P := const True); auto.\n      apply Forall_const_true. }\n  rewrite H; clear H.\n  eRauto.\n  unfold eRdiv.\n  rewrite sum_map_scalar_r.\n  f_equal.\n  induction n; simpl.\n  { inv Hn. }\n  rewrite List.map_app; simpl.\n  rewrite sum_app; simpl; eRauto.\n  destruct (Nat.eqb_spec n m); subst.\n  - rewrite sum_map_count.\n    rewrite Forall_not_in_countb_list_0.\n    + rewrite INeR_0; eRauto.\n    + unfold compose.\n      eapply List.Forall_impl.\n      2: { apply List_forall_neq_range. }\n      simpl; intros a Ha HC; apply Ha.\n      rewrite Nat.eqb_sym; auto.\n  - rewrite IHn; eRauto; lia.\nQed.\n\nSection die_equidistribution.\n  Context (env : SamplingEnvironment) (P : St -> bool) (samples : nat -> St).\n  Context (out : string) (n : nat) (Hn : (0 < n)%nat).\n  Hypothesis bitstreams_samples :\n    forall i, iproduces (eq (samples i)) (env.(bitstreams) i)\n           (cpGCL_to_itree (die out n) empty).\n\n  Theorem die_samples_equidistributed :\n    converges (freq (is_true ∘ P) ∘ prefix samples)\n      (cwp (die out n) (fun s => if P s then 1 else 0) empty).\n  Proof.\n    eapply cpGCL_samples_equidistributed; eauto; apply wf_die; auto.\n  Qed.\nEnd die_equidistribution.\n\n(** Extracting the sampler. *)\nFrom Coq Require Import ExtrOcamlBasic ExtrOcamlString.\nDefinition sampler (n : nat) : itree boolE nat :=\n  ITree.map (fun s => as_nat (s \"n\")) (cpGCL_to_itree (die \"n\" n) empty).\nExtraction \"extract/die/die.ml\" sampler.\n\n(* From Coq Require Import ExtrHaskellBasic. *)\n(* Extraction Language Haskell. *)\n(* Definition sampler (n : nat) : itree boolE (unit + nat) := *)\n(*   ITree.map (fun lr => match lr with *)\n(*                     | inl tt => inl tt *)\n(*                     | inr s => inr (as_nat (s \"n\")) *)\n(*                     end) (cpGCL_to_itree_open (die \"n\" n) empty). *)\n(* Extraction \"extract/die/Sampler.hs\" sampler. *)\n", "meta": {"author": "bagnalla", "repo": "zar", "sha": "ec7ef01ac4c2cf2c1b2b59a921a92f05cc2f1f51", "save_path": "github-repos/coq/bagnalla-zar", "path": "github-repos/coq/bagnalla-zar/zar-ec7ef01ac4c2cf2c1b2b59a921a92f05cc2f1f51/die.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772384450968, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7125761629835179}}
{"text": "Require Import Lia.\nRequire Import Bool.\nRequire Import List.\nImport PeanoNat.Nat.\nImport ListNotations.\nRequire Extraction.\nRequire Import Program.Wf.\nRequire Import Arith.Wf_nat.\n\nRequire Import Definitions.\n\nFixpoint decode_nat (x : message) : nat := match x with\n  | [] => 0\n  | x :: xs => (if x then 1 else 0) + 2 * decode_nat xs\n  end.\n\nFixpoint div2 (n acc : nat) : nat * bool := match n with\n  | 0       => (acc,false)\n  | 1       => (acc,true)\n  | S (S n) => div2 n (S acc)\n  end.\n\nLemma div2_nk : forall n k,\n   fst (div2 n (S k)) <= S (fst (div2 n k)) /\\\n   fst (div2 (S n) (S k)) <= S (fst (div2 (S n) k)).\nProof.\n  induction n; intros.\n  simpl. lia.\n  split. destruct (IHn k). auto. \n  simpl. destruct (IHn (S k)). lia.\nQed.\n\nLemma div2_le : forall n k, n <> 0 -> \n  fst (div2 n k) < n + k /\\\n  fst (div2 (S n) k) < S n + k.\nProof.\n  intros.\n  generalize dependent k.\n  induction n; intros. exfalso; apply H; auto.\n  destruct n. simpl. lia.\n  simpl. specialize IHn with k. destruct IHn as [IH1 IH2]. auto.\n  split. change (div2 n (S k)) with (div2 (S (S n)) k). lia.\n  destruct n. simpl. lia.\n  simpl. change (div2 n (S (S k))) with (div2 (S (S n)) (S k)). \n  pose proof (div2_nk (S (S n)) k). lia.\nQed.\n\nLemma div2_le_0 : forall n, n <> 0 ->\n  fst (div2 n 0) < n.\nProof. intros. destruct (div2_le n 0); auto. lia.\nQed.\n\nTheorem nat_two_induction (P : nat -> Prop) :\n  P 0 -> \n  P 1 -> \n  (forall n, P n -> P (S n) -> P (S (S n))) ->\n  (forall n, P n).\nProof.\n  intros H0 H1 IH n.\n  enough (P n /\\ P (S n)) by easy.\n  induction n; intuition. \nQed.\n\nLemma div2_eq : forall n k q b,\n  div2 n k = (q, b) ->\n  match b with\n  | true  => 2 * q + 1 = n + 2 * k\n  | false => 2 * q     = n + 2 * k\n  end.\nProof.\n  induction n using nat_two_induction; intros.\n  - simpl in *. inversion H; subst. auto.\n  - simpl in *. inversion H; subst. lia. \n  - simpl in H.\n    specialize IHn with (S k) q b. \n    assert (S (S n) + 2 * k = n + 2 * S k). lia. rewrite H0.\n    apply IHn; auto.\nQed.\n\nFixpoint encode_nat' (n n_meas : nat) :message := match n with\n  | 0 => []\n  | 1 => [B1]\n  | S (S _) => (match n_meas with\n    | 0 => [] (* Unreachable from encode_nat *)\n    | S n_meas' => (match div2 n 0 with\n      | (q,true)  => B1 :: encode_nat' q n_meas'\n      | (q,false) => B0 :: encode_nat' q n_meas'\n      end)\n    end)\n  end.\nDefinition encode_nat (n : nat) := encode_nat' n n.\n\nLemma encode_nat'_reduce : forall n X,\n  n <= X ->\n  encode_nat' n X = encode_nat' n n.\nProof.\n  induction n using lt_wf_ind; intros.\n  destruct n. destruct X; simpl; auto. \n  destruct n. destruct X; simpl; auto. \n  destruct X. inversion H0.\n  destruct X. lia.\n  destruct (div2 n 1) eqn:?. \n  remember (encode_nat' (S (S n)) (S (S X))) as E.\n  assert (E = match div2 (S (S n)) 0 with | (q,true) => B1 :: encode_nat' q (S X) | (q,false) => B0 :: encode_nat' q (S X) end).\n  simpl. subst. auto.\n  rewrite H1.\n  remember (encode_nat' (S (S n)) (S (S n))) as F.\n  assert (F= match div2 (S (S n)) 0 with | (q,true) => B1 :: encode_nat' q (S n) | (q,false) => B0 :: encode_nat' q (S n) end).\n  simpl; subst; auto.\n  rewrite H2.\n  destruct (div2 (S (S n)) 0) as [q b'] eqn:?.\n  clear H1. clear H2. clear HeqF. clear HeqE. clear E. clear F.\n  assert (fst (div2 (S (S n)) 0) = q). rewrite Heqp0. auto. \n  assert (q < S (S n)). rewrite <- H1. apply div2_le_0. auto.\n  destruct b'.\n  - rewrite H; try lia. assert (encode_nat' q (S n) = encode_nat' q q). rewrite H; try lia; auto. rewrite H3. auto. \n  - rewrite H; try lia. assert (encode_nat' q (S n) = encode_nat' q q). rewrite H; try lia; auto. rewrite H3. auto. \nQed.\n  \n(** The main theorem relating encoding and decoding: encode_nat and decode_nat are inverses. This is the lemma that is needed for the final proof. *)\nLemma encode_inv : forall X,\n  X = decode_nat (encode_nat X).\nProof.\n  intros.\n  induction X using lt_wf_ind. \n  destruct (div2 X 0) eqn:?. destruct X. auto. \n  assert (n < S X). { assert (n = fst (div2 (S X) 0)). rewrite Heqp. auto. rewrite H0. apply div2_le_0; auto. }\n  specialize H with n.\n  unfold encode_nat, encode_nat'; simpl; fold encode_nat'.\n  destruct X; auto.\n  simpl in Heqp. rewrite Heqp.\n  destruct b.\n  - assert (encode_nat' n (S X) = encode_nat n). { rewrite encode_nat'_reduce; auto; lia. } rewrite H1. simpl. rewrite <- H; auto. \n    pose proof (div2_eq X 1 n true Heqp). simpl in H2. lia.\n  - assert (encode_nat' n (S X) = encode_nat n). apply encode_nat'_reduce; try lia. rewrite H1. simpl. rewrite <- H; auto. \n    pose proof (div2_eq X 1 n false Heqp). simpl in H2. lia.\nQed.\n", "meta": {"author": "tmoux", "repo": "verified-cp", "sha": "beeac6acf403c69fc33cdf526917c4a619f179e1", "save_path": "github-repos/coq/tmoux-verified-cp", "path": "github-repos/coq/tmoux-verified-cp/verified-cp-beeac6acf403c69fc33cdf526917c4a619f179e1/BrokenDevice/EncodeNat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7125761522869205}}
{"text": "(** \nPerfect Crypto - Simple definitions for message encryption and signing using\nsymmetric and assymetric keys\n\nPerry Alexander\nThe University of Kansas\n\nProvides definitions for:\n\n- [keyType] - [symmetric], [public] and [private] key constructors.\n- [inverse] - defines the inverse of any key.\n- [is_inverse] - proof that [inverse] is decidable and provides a decision procesure for [inverse].\n- [is_not_decryptable] - predicate indicating that a message is or is not decryptable using a specified key.\n- [decrypt] - attempts to decrypt a message with a given key.  Returns the decrypted message if decryption occurs.  Returns a proof that the message cannot be decrypted with the key if decryption does not occur.\n- [is_signed] - proof that signature checking is decidable and provides a decision procedure for signature check.\n- [check] - checks a signature on a message with a given key.  Returns a proof that the check succeeds or does not succeed.\n- [check_dec] - proof that signature checking is decidable and provides a decision procedure for signature checking.  Alternative function for [check].\n*)\n\nRequire Import Omega.\nRequire Import Ensembles.\nRequire Import CpdtTactics.\nRequire Import Eqdep_dec.\nRequire Import Peano_dec.\nRequire Import Coq.Program.Equality.\n(*Require Import Messages.*)\n\n(** Ltac helper functions for discharging cases generated from sumbool types\n  using one or two boolean cases. *)\n\nLtac eq_not_eq P := destruct P;\n  [ (left; subst; reflexivity) |\n    (right; unfold not; intros; inversion H; contradiction) ].\n\nLtac eq_not_eq' P Q := destruct P; destruct Q;\n  [ (subst; left; reflexivity) |\n    (right; unfold not; intros; inversion H; contradiction) |\n    (right; unfold not; intros; inversion H; contradiction) |\n    (right; unfold not; intros; inversion H; contradiction) ].\n\n(** Key values will be [nat] by default.  Could be anything satisfying\n properties following.  *)\n\nDefinition key_val : Type := nat.\n\n(** Key types are [symmetric], [public] and [private]. *)\nInductive keyType: Type :=\n| symmetric : key_val -> keyType\n| private : key_val -> keyType\n| public : key_val -> keyType.\n\n(** A [symmetric] key is its own inverse.  A [public] key is the inverse of\n  the [private] key with the same [key_val].  A [private] key is the inverse of\n  the [public] key with the same [key_val]. *)\n\nFixpoint inverse(k:keyType):keyType :=\nmatch k with\n| symmetric k => symmetric k\n| public k => private k\n| private k => public k\nend.\n\n(** Proof that inverse is decidable for any two keys. The resulting proof\n gives us the function [is_inverse] that is a decision procedure for key \n inverse checking.  It will be used in [decrypt] and [check] later in the\n specification. *)\n\nTheorem is_inverse (k k':keyType) : {k = (inverse k')}+{k <> (inverse k')}.\nProof.\n  intros.\n  destruct k; destruct k';\n  match goal with\n  | [ |- {symmetric ?P = (inverse (symmetric ?Q))}+{symmetric ?P <> (inverse (symmetric ?Q))} ] => (eq_not_eq (eq_nat_dec P Q))\n  | [ |- {private ?P = (inverse (public ?Q))}+{private ?P <> (inverse (public ?Q))} ] => (eq_not_eq (eq_nat_dec P Q))\n  | [ |- {public ?P = (inverse (private ?Q))}+{public ?P <> (inverse (private ?Q))} ] => (eq_not_eq (eq_nat_dec P Q))\n  | [ |- _ ] => right; simpl; unfold not; intros; inversion H\n  end.\nDefined.\n\nEval compute in (is_inverse (public 1) (private 1)).\n\nEval compute in (is_inverse (public 1) (private 2)).\n\nEval compute in (is_inverse (public 2) (private 1)).\n\nEval compute in (is_inverse (private 1) (public 1)).\n\nEval compute in (is_inverse (symmetric 1) (symmetric 1)).\n\nEval compute in (is_inverse (symmetric 1) (symmetric 2)).\n\n(** Various proofs for keys and properties of the inverse operation.  All keys\n  must have an inverse.  All keys have a unique inverse.  Equal inverses come\n  from equal keys *)\n\nTheorem inverse_injective : forall k1 k2, inverse k1 = inverse k2 -> k1 = k2.\nProof.\n  intros.\n  destruct k1; destruct k2; simpl in H; try (inversion H); try (reflexivity).\nDefined.\n\nHint Resolve inverse_injective.\n\nTheorem inverse_inverse : forall k, inverse (inverse k) = k.\nProof.\n  intros. destruct k; try reflexivity.\nDefined.\n\nHint Resolve inverse_inverse.\n\nTheorem inverse_surjective : forall k, exists k', (inverse k) = k'.\nProof.\n  intros. exists (inverse k). auto.\nDefined.\n\nHint Resolve inverse_surjective.\n\nTheorem inverse_bijective : forall k k',\n    inverse k = inverse k' -> k = k'\n  /\\ forall k, exists k'', inverse k = k''.\nProof.\n  auto.\nDefined.\n\nLemma infoPri : forall k' n', (k' <> (private n')) ->\n                         exists n, (k' = (public n)) \\/\n                          ((k' = (symmetric n)) \\/\n                         exists n, (k' = (private n)) /\\ (n <> n')).\nProof.\n  intros. destruct k'. destruct k. exists 0. right. left. reflexivity.\n  exists (S k). right. left. reflexivity. destruct (eq_nat_dec k n'). subst. unfold not in H. assert (private n' = private n'). reflexivity. apply H in H0. inversion H0. exists 0. right. right. exists k. split. reflexivity. assumption. exists k. left. reflexivity.\nDefined.\n\nLemma inverse_info : forall k k',\n    k = inverse k' ->\n    exists n, k = symmetric n /\\  k' = symmetric n \\/\n    exists n, (k = public n) /\\ (k' = private n) \\/\n                          exists n, (k = private n) /\\ (k' = public n).\nProof.\n  intros. destruct k; destruct k'; try inversion H. inversion H. exists k0. left.  split; reflexivity. exists 0. right. exists 0. right. exists k0. split; reflexivity. exists 0. right. exists k0. left. split; reflexivity. \nDefined.\n\n\nInductive type : Type :=\n| Basic : type\n| Key : type\n| Encrypt : type -> type\n| Hash : type\n| Pair : type -> type -> type\n| Either : type -> type -> type.\n\n(** Basic messages are natural numbers.  Really should be held abstract, but we\n  need an equality decision procedure to determine message equality.  Compound \n  messages are keys, encrypted messages, hashes and pairs. Note that signed\n  messages are pairs of a message and encrypted hash. *) \n\nInductive message : type -> Type :=\n| basic : nat -> message Basic\n| key : keyType -> message Key\n| encrypt (t:type) : message t -> keyType -> message (Encrypt t)\n| hash : forall t, message t -> message (Hash)\n| pair : forall t1 t2, message t1 -> message t2 -> message (Pair t1 t2)\n| leither : forall t1 t2, message t1 -> message (Either t1 t2)\n| reither : forall t1 t2, message t2 -> message (Either t1 t2)\n| bad : forall t1,  message t1.\n\nDefinition getP1Type (t:type):type :=\n  match t with\n  | Pair t1 t2 => t1\n  | _ => t\n  end.\n\nDefinition getP2Type (t:type):type :=\n  match t with\n  | Pair t1 t2 => t2\n  | _ => t\n  end.\n\nDefinition pairFst{t1 t2: type} (m:message (Pair t1 t2)) : message t1 :=\n  match m in message t' return message (getP1Type t') with \n  | pair _ _ m1 _ => m1\n  | bad _ => bad _\n  | _ => bad _                \n  end.\n\n(*\nDefinition pair1 := pair _ _ (basic 1) (basic 2).\nEval compute in pairFst pair1.\nDefinition pair1' := pair _ _ (bad Basic) (basic 2).\nEval compute in pairFst pair1'.\nDefinition pair1'' := pair _ _ (basic 1) (bad Basic).\nEval compute in pairFst pair1''. *)\n\nDefinition pairSnd{t1 t2: type} (m:message (Pair t1 t2)) : message t2 :=\n  match m in message t' return message (getP2Type t') with\n  | pair _ _ _ m2 => m2\n  | bad _ => bad _ \n  | _ => bad _                \n  end.\n\n(*\nDefinition pair2 := pair _ _ (basic 1) (basic 2).\nEval compute in pairSnd pair2.\nDefinition pair2' := pair  _ _ (basic 1) (bad Basic).\nEval compute in pairSnd pair2'. *)\n\n(** Predicate that determines if a message cannot be decrypted.  Could be\n  that it is not encrypted to begin with or the wrong key is used. *)\n\nDefinition is_not_decryptable{t:type}(m:message t)(k:keyType):Prop :=\n  match m with\n  | encrypt _ m' k' => k <> inverse k'\n  (*| bad _ => False     *)                         \n  | _ => True\n  end.\n\nDefinition is_decryptable{t:type}(m:message t)(k:keyType):Prop :=\n  match m with\n  | encrypt _ m' k' => k = inverse k'\n  (*| bad _ => True*)                                \n  | _ => False\n  end.\n\n(** Prove that is_not_decryptable and is_decryptable are inverses.  This is a\n  bit sloppy.  Should really only have one or the other, but this theorem\n  assures they play together correctly.  Note that it is not installed as\n  a Hint.  *)\n\nTheorem decryptable_inverse: forall t:type, forall m:(message t), forall k,\n    (is_not_decryptable m k) <-> not (is_decryptable m k).\nProof.\n  intros.\n  split. destruct m; try (tauto).\n  simpl. intros. assumption.\n  intros. destruct m; try (reflexivity).\n  simpl. tauto. Defined.\n  (*simpl. unfold not in H. simpl in H. apply H. trivial. \nDefined. *)\n\n(** [decrypt] returns either a decrypted message or a proof of why the message\n  cannot be decrypted.  Really should be able to shorten the proof. *)\n\n(*\nInductive sumor (A : Type) (B : Prop) : Type :=\n    inleft : A -> A + {B} | inright : B -> A + {B}\n*)\n\nTheorem is_not_decryptable_basic: forall n k, is_not_decryptable (basic n) k.\nProof.\n  intros.\n  reflexivity.\nDefined.\n\nTheorem is_not_decryptable_key: forall k k', is_not_decryptable (key k) k'.\nProof.\n  intros.\n  reflexivity.\nDefined.  \n\nTheorem is_not_decryptable_hash: forall t n k, is_not_decryptable (hash t n) k.\nProof.\n  intros.\n  reflexivity.\nDefined.\n\nTheorem is_not_decryptable_pair: forall t1 t2 n m k, is_not_decryptable (pair t1 t2 n m) k.\nProof.\n  intros.\n  reflexivity.\nDefined.\n\nTheorem is_not_decryptable_bad: forall t k, is_not_decryptable (bad t) k.\nProof.\n  intros.\n  reflexivity.\nDefined.\n\nDefinition decrypt_type(t:type):type :=\n  match t with\n  | Encrypt t' => t'\n  | _ => t\n  end.\n\nInductive decryptable {t:type} : (message (Encrypt t)) -> keyType -> Prop :=\n| cDecryptable {m':message t} {j:keyType} : decryptable (encrypt _ m' j) (inverse j).\n\nFixpoint decrypt{t:type}(m:message (Encrypt t))(k:keyType) :\n  (message t * is_decryptable m k)+\n  {(is_not_decryptable m k)}.\n  refine match m in message t' return (message (decrypt_type t') * is_decryptable m k) + {(is_not_decryptable m k)} with\n         | basic _ => inright _ _\n         | key _ => inright _ _\n         | encrypt _ m' j => (if (is_inverse k j) then (inleft _ (m',_)) else (inright _ _ ))\n         | hash _ _ => inright _ _\n         | pair _ _ _ _ => inright _ _\n         | leither _ _ _ => inright _ _\n         | reither _ _ _ => inright _ _                           \n         | bad _ => inright _ _\n         end.\nProof.\n  reflexivity.\n  reflexivity.\n  simpl. assumption.\n  simpl. assumption.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  reflexivity.\nDefined.\n(*\nFixpoint decrypt{t:type}(m:message (Encrypt t))(k:keyType):(message t)+{(is_not_decryptable m k)}.\n  refine match m in message t' return (message (decrypt_type t') + {(is_not_decryptable m k)}) with\n         | basic _ => inright _ _\n         | key _ => inright _ _\n         | encrypt m' j => (if (is_inverse k j) then (inleft _) else (inright _ _ ))\n         | hash _ _ => inright _ _\n         | pair  _ _ => inright _ _\n         | leither _ _ _ => inright _ _\n         | reither _ _ _ => inright _ _                           \n         | bad _ => inright _ _\n         end.\nProof.\n  reflexivity.\n  reflexivity.\n  simpl. assumption.\n  simpl. assumption.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  reflexivity.\nDefined.\n *)\n\nDefinition encrypted_with {t:type}(m:message (Encrypt t)) : keyType :=\n  match m with\n  | encrypt _ m' j => j\n  | _ => (public 0)\n  end.\n\nEval compute in encrypted_with (bad (Encrypt Basic)).\nEval compute in encrypted_with (encrypt _ _ (public 33)).\n\nDefinition decrypt'{t:type}(m:message (Encrypt t))(k:keyType) : (k = inverse (encrypted_with m)) -> message t.\n  refine\n  ( fun pf => \n  match m with\n         | basic _ => _\n         | key _ => _\n         | encrypt _ m' j => _\n         | hash _ _ =>  _\n         | pair  _ _ _ _ =>  _\n         | leither _ _ _ => _\n         | reither _ _ _ => _                           \n         | bad _ =>  _\n  end ).\n  (exact (fun (x:Type) => (fun x => x))).\n  (exact (fun (x:Type) => (fun x => x))).\n  exact m'.\n  (exact (fun (x:Type) => (fun x => x))).\n  (exact (fun (x:Type) => (fun x => x))).\n  (exact (fun (x:Type) => (fun x => x))).\n  (exact (fun (x:Type) => (fun x => x))).\n  destruct t0.\n  (exact (fun (x:Type) => (fun x => x))).\n  (exact (fun (x:Type) => (fun x => x))).\n  exact (bad t0).\n  (exact (fun (x:Type) => (fun x => x))).\n  (exact (fun (x:Type) => (fun x => x))).\n  (exact (fun (x:Type) => (fun x => x))). Defined.\n\n  (*\nDefinition almostMessage := decrypt' (encrypt (basic 0) (public 1)) (private 1). *)\n\nExample same_inverse : forall n, (private n) = inverse (public n).\nProof.\n  intros. reflexivity. Qed.\n\n(*\nEval compute in almostMessage (same_inverse 1).\n *)\n\nDefinition decryptM {t:type} (m:message (Encrypt t)) (k:keyType):message t :=\n  match decrypt m k with\n  | inleft (m',_) => m'\n  | inright _ => bad t\n  end.\n\n(*\nDefinition decryptM {t:type} (m:message (Encrypt t)) (k:keyType):message t :=\n  match decrypt m k with\n  | inleft m' => m'\n  | inright _ => bad t\n  end.\n *)\n\n(*\nDefinition enc1 := encrypt (basic 42) (public 1). Check enc1.\nDefinition enc2 := encrypt enc1 (public 2).\nEval compute in decryptM enc1 (private 1).\nEval compute in decryptM enc1 (private 0).\nEval compute in decryptM enc2 (private 2).\nEval compute in decryptM (decryptM enc2 (private 2)) (private 1). *)\n\n(*Fixpoint decrypt'{t:type}(m:message (Encrypt t))(k:keyType):message t+{(is_not_decryptable m k)}.\nrefine\n  match m with\n  | basic _ => inright _ is_not_decryptable_basic\n  | key _ => inright _ is_not_decryptable_key\n  | encrypt t m' j => (if (is_inverse k j) then (inleft _ m') else (inright _ _ ))\n  | hash _ _ => inright _ is_not_decryptable_hash\n  | pair _ _ _ _ => inright _ is_not_decryptable_pair\n  end.\nProof.\n  simpl. assumption.\nAbort. *)\n\n(** This should solve the previous proof if there is a way to try it on every\n  proof generated by refine\n\n  repeat try (match goal with\n  | [ |- is_not_decryptable (encrypt ?X ?Y) ?Z ] => simpl; assumption\n  | [ |- _ ] => reflexivity\n  end).\n*)\n\n(*\nEval compute in decrypt(encrypt (basic 1) (symmetric 1)) (symmetric 1).\n\nEval compute in decrypt(encrypt (basic 1) (symmetric 1)) (symmetric 2). *)\n\n(** Generate a signature using encryption and hash *)\n\nDefinition sign{t:type}(m:message t)(k:keyType) :=\n  (pair  _ _ m (encrypt _ (hash t m) k)).\n\n(*\nEval compute in sign (basic 1) (public 1). *)\n\nLtac eq_key_helper :=\n  match goal with\n  | [ |- {symmetric ?P = symmetric ?Q} + {symmetric ?P <> symmetric ?Q} ] =>\n    (eq_not_eq (eq_nat_dec P Q))\n  | [ |- {public ?P = public ?Q} + {public ?P <> public ?Q} ] =>\n    (eq_not_eq (eq_nat_dec P Q))\n  | [ |- {private ?P = private ?Q} + {private ?P <> private ?Q} ] =>\n    (eq_not_eq (eq_nat_dec P Q))\n  | [ |- _ ] => right; unfold not; intros; inversion H\n  end.\n\nTheorem eq_key_type_dec (k k':keyType) : {k=k'}+{k<>k'}.\nProof.\n  intros.\n  destruct k; destruct k'; eq_key_helper.\nDefined.\n\nTheorem eq_key_dec : forall (k k':message Key), {k=k'}+{k<>k'}.\nProof.\n  intros.\n  dep_destruct k; dep_destruct k'.\n  destruct k0; destruct k1; try (right; unfold not; intros; inversion H; contradiction).\n  destruct (eq_nat_dec k0 k1).\n  left. subst. reflexivity.\n  right. unfold not. intros. inversion H. contradiction.\n  destruct (eq_nat_dec k0 k1).\n  left. subst. reflexivity.\n  right. unfold not. intros. inversion H. contradiction.\n    destruct (eq_nat_dec k0 k1).\n  left. subst. reflexivity.\n  right. unfold not. intros. inversion H. contradiction.\n  right. unfold not. intros. inversion H.\n  right. unfold not. intros. inversion H.\n  left. reflexivity.\nDefined.\n\nPrint eq_key_dec.\n\nCheck eq_key_dec.\n  \nHint Resolve eq_key_dec.\n\nTheorem eq_type_dec : forall (x y:type), {x = y} + {x <> y}.\nProof.\n  induction x, y;\n  match goal with\n  | [ |- {?T = ?T} + {?T <> ?T} ] => left; reflexivity\n  | [ |- {?C ?T = ?C ?U} + {?C ?T <> ?C ?U} ] => specialize IHx with y; destruct IHx; [ left; subst; reflexivity | right; unfold not; intros; inversion H; contradiction ]\n  | [ |- {?C ?T ?U = ?C ?T' ?U'} + {?C ?T ?U <> ?C ?T' ?U'} ] => specialize IHx1 with y1; specialize IHx2 with y2; destruct IHx1; destruct IHx2; \n  [ left; subst; reflexivity\n   | subst; right; unfold not; intros; inversion H; contradiction\n   | subst; right; unfold not; intros; inversion H; contradiction\n   | subst; right; unfold not; intros; inversion H; contradiction ]\n  | [ |- _ ] => right; unfold not; intros; inversion H \n  end. (*destruct IHx. subst. admit.*)\nDefined.\n\nTheorem message_eq_lemma: forall t, forall m:(message t), forall m':(message t), forall k k',\n    {m=m'}+{m<>m'} ->\n    {k=k'}+{k<>k'} ->\n    {(encrypt _ m k)=(encrypt _ m' k')}+{(encrypt _ m k) <> (encrypt _ m' k')}.\nProof.\n  intros.\n  destruct H; destruct H0.\n  left; subst; reflexivity.\n  right; subst; unfold not; intros; inversion H; contradiction.\n  right. subst. unfold not. intros. inversion H. apply inj_pair2_eq_dec in H1. contradiction.\n  apply eq_type_dec.\n  right. unfold not. intros. inversion H. apply inj_pair2_eq_dec in H1. contradiction.\n  apply eq_type_dec.\nDefined.\n\nHint Resolve message_eq_lemma.\n\nLtac whack_right :=\n  match goal with\n  | [ |- {basic ?P = basic ?Q}+{basic ?P <> basic ?Q} ] =>\n    (eq_not_eq (eq_nat_dec P Q))\n  | [ |- {key ?P = key ?Q}+{key ?P <> key ?Q} ] =>\n    (eq_not_eq (eq_key_dec P Q))\n  | [ |- {encrypt ?P ?P' = encrypt ?Q ?Q'}+{encrypt ?P ?P' <> encrypt ?Q ?Q'} ] =>\n    auto \n  | [ H : {?P = ?Q}+{?P <> ?Q} |- {hash ?P = hash ?Q}+{hash ?P <> hash ?Q} ] =>\n    (eq_not_eq H)\n  | [ H1 : {?P = ?P'}+{?P <> ?P'},\n      H2 : {?Q = ?Q'}+{?Q <> ?Q'}\n      |- {pair ?P ?Q = pair ?P' ?Q'}+{pair ?P ?Q <> pair ?P' ?Q'} ] =>\n    (eq_not_eq' H1 H2)\n  | [ |- _ ] => right; unfold not; intros; inversion H\n  end.\n\n(*Theorem message_eq_dec: forall t, forall m:(message t), forall m':(message t), {m=m'}+{m<>m'}.\nProof.\n  dependent induction m; dependent induction m'.\n  (eq_not_eq (eq_nat_dec n n0)).\n  right; unfold not; intros; inversion H.\n  (eq_not_eq (eq_key_type_dec k k0)).\n  right; unfold not; intros; inversion H.\n\n  specialize IHm with m'.\n  destruct IHm; destruct (eq_key_type_dec k k0);\n  [ left; subst; reflexivity\n  | right; unfold not; intros; inversion H; contradiction\n  | right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1;\n    [contradiction | apply eq_type_dec]\n  | right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1;\n    [contradiction | apply eq_type_dec]].\n\n  right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1.\n  \n  specialize IHm with m'.\n  destruct IHm;\n  [ left; subst; reflexivity \n  | right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1;\n    [contradiction | apply eq_type_dec]].\n\n  right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1.\n\n  specialize IHm2 with m'2.\n  specialize IHm1 with m'1.\n  destruct IHm1; destruct IHm2;\n  [ left; subst; reflexivity \n  | right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1; apply inj_pair2_eq_dec in H2; [ contradiction | apply eq_type_dec | apply eq_type_dec | apply eq_type_dec ]\n  | right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1; apply inj_pair2_eq_dec in H2; [ contradiction | apply eq_type_dec | apply eq_type_dec | apply eq_type_dec ]\n  | right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1; apply inj_pair2_eq_dec in H2; [ contradiction | apply eq_type_dec | apply eq_type_dec | apply eq_type_dec ]]. \n\n  right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1.\n  right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1\n  right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1.\n  right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1.\n  right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1.\n  right; unfold not; intros; inversion H; apply inj_pair2_eq_dec in H1.\n  left; reflexivity.\nDefined.\n *)\n\n(*Hint Resolve message_eq_dec. *)\n\nPrint encrypt.\n\n(*Definition is_signed{t:type}(m:message (Pair t (Encrypt (Hash t))))(k:keyType):Prop :=\n  match m with\n  | pair t t' n n' => n' = sign n k\n  | _ => False\n  end.\n  \n  match m with\n  | (pair r (Encrypt (Hash r')) m' m'') => match (decrypt m'' k) with\n                      | inleft (hash r m''') => m'=m'''\n                      | inleft _ => False\n                      | inright _ => False\n                      end\n  | _ => False\n  end.\n\n\n\n    \n  | (pair t t' m m') => match m' with\n                       | encrypt t m'' k' =>  match m'' with\n                                            | (hash t m''') => m=m''' /\\ (k = inverse k')\n                                      end\n                  end\n  end. \n\nExample sign_1_ex: is_signed (pair (basic 1) (encrypt (hash (basic 1)) (private sf1))) (public 1).\nProof.\n  simpl. tauto.\nDefined.\n\nExample sign_2_ex: not (is_signed (pair (basic 1) (encrypt (hash (basic 1)) (private 1))) (public 2)).\nProof.\n  unfold not. intros.\n  simpl in H. inversion H. inversion H1.\nDefined.\n\nTheorem check_dec: forall m:message, forall k, {(is_signed m k)}+{not (is_signed m k)}.\nProof.\n  intros.\n  destruct m; try tauto.\n  destruct m2; try tauto.\n    destruct m2; try tauto.\n      destruct (is_inverse k k0).\n        destruct (message_eq_dec m1 m2); try tauto.\n        left. subst. simpl. tauto.\n          right. unfold not. intros. simpl in H. tauto.\n          right. unfold not. intros. simpl in H. tauto.\nDefined. \n            \nEval compute in check_dec (sign (basic 1) (private 1)) (public 1).\n\nEval compute in check_dec (sign (basic 1) (private 1)) (public 2).\n\nNotation \" 'good' \" := (left _ _).\n\nNotation \" 'bad' \" := (right _ _).\n\nEval compute in check_dec (sign (basic 1) (private 1)) (public 1).\n\nEval compute in check_dec (sign (basic 1) (private 1)) (public 2). *)\n\nTheorem m2 : forall P Q R: Prop, P -> Q -> R -> Q.\nProof.\n  intros. match goal with | [ B : _ |- _ ] => exact B end.\nDefined.                                                 \n\n(** [notHyp] determines if [P] is in the assumption set of a proof state.\n  The first match case simply checks to see if [P] matches any assumption and\n  fails if it does.  The second match case grabs everything else.  If [P]\n  is a conjunction, it checks to see if either of its conjuncts is an\n  assumption calling [notHyp] recursively. \n\n*)\n\nLtac notHyp P :=\n  match goal with\n  | [ _ : P |- _ ] => fail 1\n  | _ =>\n    match P with\n    | ?P1 /\\ ?P2 => first [ notHyp P1 | notHyp P2 | fail 2 ]\n    | _ => idtac\n    end\n  end.\n                           \nLtac extend pf :=\n  let t := type of pf in\n  notHyp t; generalize pf; intro.", "meta": {"author": "armoredsoftware", "repo": "session", "sha": "ca06d4263c20e0d4a3ef36b70d9eccd0e7cf9173", "save_path": "github-repos/coq/armoredsoftware-session", "path": "github-repos/coq/armoredsoftware-session/session-ca06d4263c20e0d4a3ef36b70d9eccd0e7cf9173/Crypto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7125299189329711}}
{"text": "(*\nInductive and (P Q:Prop) : Prop :=\n| conj: P -> Q -> and P Q\n.\n\nArguments conj {P} {Q} _ _.\n\nNotation \"P /\\ Q\" := (conj P Q).\n*)\n\nTheorem and_comm : forall (P Q:Prop),\n    P /\\ Q -> Q /\\ P.\nProof.\n    intros P Q [H1 H2]. split.\n    - exact H2.\n    - exact H1.\nQed.\n\nTheorem and_assoc : forall (P Q R:Prop),\n    P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n    intros P Q R [H1 [H2 H3]]. split.\n    - split.\n        + exact H1.\n        + exact H2.\n    - exact H3.\nQed.\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/sf/and.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7125299187288986}}
{"text": "Require Export GeoCoq.Tarski_dev.Annexes.circles.\nRequire Export GeoCoq.Axioms.continuity_axioms.\n\nSection Tangency.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(** Euclid Book III, Prop 11 and Prop 12\n We do not need to distinguish between internal or external tangency. *)\n\n(** If two circles are tangent, the common point is on the line joining the centers. *)\n\nLemma TangentCC_Col : forall A B C D X,\n TangentCC A B C D ->\n OnCircle X A B ->\n OnCircle X C D ->\n Col X A C.\nProof.\nintros.\n\nunfold TangentCC in *.\n\ninduction(eq_dec_points A C).\nsubst C.\nCol.\n\nassert(HS:=ex_sym1 A C X H2).\nex_and HS Y.\nex_and H4 M.\n\nassert(Cong X A Y A).\napply(is_image_col_cong A C X Y A H2 H6); Col.\nassert(Cong X C Y C).\napply(is_image_col_cong A C X Y C H2 H6); Col.\n\ndestruct H.\nunfold unique in H.\n\nassert(x =X).\napply H.\nsplit; auto.\nsubst x.\nassert(OnCircle Y A B).\nunfold OnCircle in *.\napply cong_transitivity with A X; Cong.\nassert(OnCircle Y C D).\nunfold OnCircle in *.\napply cong_transitivity with C X; Cong.\nassert(X = Y).\napply H.\nsplit; auto.\nsubst Y.\n\nunfold Reflect in H6.\ninduction H6.\nspliter.\nunfold ReflectL in *.\nspliter.\nex_and H11 Z.\n\nassert(Z = X).\napply l7_3; auto.\nsubst Z.\nCol.\nspliter.\ncontradiction.\nQed.\n\nLemma tangent_neq : forall A B O P,\n O<>P -> Tangent A B O P -> A<>B.\nProof.\nintros.\nintro.\nsubst B.\nunfold Tangent in *.\nunfold unique in *.\nex_and H0 T.\nassert(HH:=symmetric_point_construction T O).\nex_and HH T'.\nassert(OnCircle T' O P).\napply (symmetric_oncircle T T' O P); auto.\nassert(T = T').\napply H1.\nsplit; Col.\nsubst T'.\napply H.\napply l7_3 in H3.\nsubst T.\nunfold OnCircle in H2.\ntreat_equalities; tauto.\nQed.\n\n(** A line going through the center is not tangent to the circle. *)\n\nLemma diam_not_tangent : forall O P A B, \n  P <> O -> Col O A B -> ~ Tangent A B O P.\nProof.\nintros O P A B HOP HCol HTan.\ndestruct HTan as [Q [[HQCol HQOn] HQUnique]].\ndestruct(eq_dec_points A B).\n  subst B.\n  destruct (segment_construction Q O O P) as [Q' [HQ'1 HQ'2]].\n  assert (HQQ' : Q <> Q') by (intro; treat_equalities; auto).\n  apply HQQ', HQUnique; split; Col.\ndestruct (diff_col_ex3 A B O) as [C [HOC [HAC [HBC HColC]]]]; Col.\ndestruct (diam_points O P C) as [Q1 [Q2 [HBet [HQ1Q2C [HQ1On HQ2On]]]]].\nassert (HQ1Q2 : Q1 <> Q2).\n  intro; treat_equalities; auto.\nassert(Q = Q1) by (apply HQUnique; split; ColR).\nassert(Q = Q2) by (apply HQUnique; split; ColR).\ntreat_equalities; auto.\nQed.\n\n(** Every point on the tangent different from the point of tangency is strictly outside the circle. *)\n\nLemma tangent_out : forall A B O P T X,\n  X <> T -> Col A B X -> TangentAt A B O P T -> OutCircleS X O P.\nProof.\nintros.\nunfold TangentAt in *.\nspliter.\n\ninduction(eq_dec_points O P).\nsubst P.\nunfold OutCircleS.\nunfold Lt.\n\nsplit.\napply le_trivial.\nintro.\nunfold OnCircle in *.\nassert(T = O).\napply cong_identity with O; Cong.\nassert(X = O).\napply cong_identity with O; Cong.\nsubst O.\ncontradiction.\n\nassert(InCircle X O P -> X = T).\nintro.\n\nassert(HH:= chord_completion O P T X H3 H5).\nex_and HH T'.\nassert(A <> B).\napply (tangent_neq A B O P); auto.\nunfold Tangent in *.\nunfold unique in *.\nex_and H1 TT.\nassert(TT= T).\napply H9.\nsplit; auto.\nsubst TT.\nassert(T = T').\napply H9.\nsplit; auto.\napply bet_col in H7.\n\nassert(Col A X T); ColR.\nsubst T'.\napply between_identity in H7.\nsubst X.\ntauto.\n\nassert(~InCircle X O P).\nintro.\napply H5 in H6.\ncontradiction.\napply ninc__outcs.\nassumption.\nQed.\n\n(** If line AB is tangent to a circle of center O at a point T, then OT is perpendicular to AB.\nThis is Euclid Book III, Prop 18 *)\n\nLemma tangentat_perp : \nforall A B O P T, O <> P -> TangentAt A B O P T -> Perp A B O T.\nProof.\nintros.\nassert(TA:=H0).\nunfold TangentAt in H0.\nspliter.\nassert(A <> B).\napply (tangent_neq A B O P); auto.\nassert(~Col A B O).\nintro.\nassert(~Tangent A B O P).\napply(diam_not_tangent); Col.\ncontradiction.\n\nassert(HH:= l8_18_existence A B O H4).\nex_and HH R.\n\ninduction(eq_dec_points T R).\nsubst R.\nauto.\n\nassert(HH:= (symmetric_point_construction T R)).\nex_and HH T'.\n\ninduction(eq_dec_points A R).\nsubst A.\nassert(Perp T R R O).\napply perp_comm.\napply (perp_col R B O R T); Col.\nassert(Perp_at R T R R O).\napply perp_in_comm.\napply perp_perp_in.\nPerp.\nassert(Per O R T).\napply l8_2.\napply perp_in_per; auto.\nunfold Per in *.\nex_and H11 T''.\nassert(T' = T'').\napply (symmetric_point_uniqueness T R T' T''); auto.\nsubst T''.\n\nassert(T <> T').\nintro.\nsubst T'.\napply H7.\napply sym_equal.\napply l7_3; auto.\n\nassert(OnCircle T' O P).\nunfold OnCircle in *.\napply cong_transitivity with O T; Cong.\n\nassert(OutCircleS T' O P).\napply (tangent_out R B O P T T'); ColR.\nunfold OutCircleS in *.\nunfold Lt in *.\nspliter.\nunfold OnCircle in H14.\napply False_ind.\napply H16.\nCong.\n\n\nassert(Perp T R R O).\napply perp_comm.\napply (perp_col R A O R T); Col.\napply perp_left_comm.\neapply (perp_col A B O R R); auto.\nunfold Midpoint in *.\nspliter.\napply bet_col in H8.\nColR.\nassert(Perp_at R T R R O).\napply perp_in_comm.\napply perp_perp_in.\nPerp.\n\n\nassert(Per O R T).\napply l8_2.\napply perp_in_per; auto.\nunfold Per in *.\nex_and H12 T''.\nassert(T' = T'').\napply (symmetric_point_uniqueness T R T' T''); auto.\nsubst T''.\n\nassert(T <> T').\nintro.\nsubst T'.\napply H7.\napply sym_equal.\napply l7_3; auto.\n\nassert(OnCircle T' O P).\nunfold OnCircle in *.\napply cong_transitivity with O T; Cong.\n\nassert(OutCircleS T' O P).\nunfold Midpoint in *.\nspliter.\napply bet_col in H12.\napply (tangent_out A B O P T T'); auto.\nColR.\nunfold OutCircleS in *.\nunfold Lt in *.\nspliter.\nunfold OnCircle in H14.\napply False_ind.\napply H17.\nCong.\nQed.\n\n(** AB is tangent to the circle (O,P) iff they intersect at a point X\nsuch that AB is perpendicular to OX. *)\n\nLemma tangency_chara : forall A B O P, P <> O ->\n (exists X, OnCircle X O P /\\ Perp_at X A B O X) <-> Tangent A B O P.\nProof.\nintros.\n\nsplit.\nintro.\nex_and H0 T.\nunfold Tangent.\nunfold unique.\nexists T.\nsplit.\nsplit; auto.\napply perp_in_col in H1.\ntauto.\nintros.\nspliter.\nassert(Col A B T).\napply perp_in_col in H1.\ntauto.\n\ninduction(eq_dec_points T x').\nauto.\napply False_ind.\n\nassert(Perp T x' O T).\napply (perp_col2 A B); auto.\napply perp_in_perp in H1.\nauto.\n\nassert(Perp_at T T x' O T).\napply perp_perp_in; auto.\n\nassert(Per x' T O).\napply perp_in_comm in H7.\napply perp_in_per; auto.\n\nassert(~Col x' T O).\napply perp_not_col in H6.\nColR.\n\nassert(Lt T x' x' O /\\ Lt T O x' O).\nassert_diffs.\napply(l11_46 x' T O); auto.\nunfold OnCircle in *.\nunfold Lt in H10.\nspliter.\napply H12.\napply cong_transitivity with O P; Cong.\n\nintros.\nassert(HT:=H0).\nunfold Tangent in H0.\nunfold unique in H0.\nex_and H0 T.\n\nassert(TangentAt A B O P T).\nunfold TangentAt.\nrepeat split; auto.\nexists T.\nsplit; auto.\nassert(HH:=tangentat_perp A B O P T).\nassert(Perp A B O T).\napply HH; auto.\n\napply(l8_14_2_1b_bis A B O T T H4); Col.\nQed.\n\n\nLemma tangency_chara2 : forall A B O P Q,\n OnCircle Q O P -> Col Q A B -> \n ((forall X, Col A B X -> X = Q \\/ OutCircleS X O P) <-> Tangent A B O P).\nProof.\nintros.\nsplit.\nintros.\nunfold Tangent.\nunfold unique.\nexists Q.\nrepeat split; Col.\nintros.\nspliter.\nassert(HH:=(H1 x' H2)).\ninduction HH.\nauto.\nunfold OnCircle in *.\nunfold OutCircleS in *.\nunfold Lt in *.\nspliter.\napply False_ind.\napply H5; Cong.\n\nintros.\nassert(TangentAt A B O P Q).\nunfold TangentAt.\nrepeat split; Col.\n\ninduction(eq_dec_points X Q).\nleft; auto;\n\nunfold Tangent in H1.\nright.\n\napply(tangent_out A B O P Q X); auto.\nQed.\n\n\nLemma tangency_chara3 : forall A B O P Q, A <> B ->\n OnCircle Q O P -> Col Q A B -> \n ((forall X, Col A B X -> OutCircle X O P) <-> Tangent A B O P).\nProof.\n\nintros.\nsplit.\nintros.\n\nassert(HT:= (tangency_chara2 A B O P Q H0 H1)); auto.\napply HT.\nintros.\ninduction(eq_dec_points X Q).\nleft; auto.\nright.\nassert(OutCircle X O P).\napply H2; Col.\n\nunfold OutCircleS.\nunfold OutCircle in H5.\nunfold Lt.\nsplit; auto.\nintro.\n\nassert(HH:=midpoint_existence X Q).\nex_and HH M.\nassert(InCircleS M O P).\napply(bet_inc2__incs O P Q X M); Circle.\nintro.\nsubst M.\n\napply l7_2 in H7.\napply is_midpoint_id in H7.\nsubst X; tauto.\nintro.\nsubst M.\napply is_midpoint_id in H7.\ncontradiction.\nunfold Midpoint in H7.\nspliter.\nBetween.\n\nassert(Col A B M).\nunfold Midpoint in *.\nspliter.\nColR.\nassert(HH:=(H2 M H9)).\nunfold InCircleS in *.\nunfold OutCircle in *.\n\napply le__nlt in HH.\ncontradiction.\n\nintros.\nassert(TangentAt A B O P Q).\nunfold TangentAt.\nrepeat split; Col.\n\ninduction(eq_dec_points X Q).\nsubst X.\nunfold TangentAt in *.\nspliter.\napply onc__outc; auto.\n\nassert(OutCircleS X O P).\napply(tangent_out A B O P Q X); auto.\nunfold OutCircleS in *.\nunfold OutCircle.\nunfold Lt in H6.\ntauto.\nQed.\n\n(** Euclid Book III Prop 5 \n If two circles cut one another, then they do not have the same center. *)\n\nLemma intercc__neq :  forall A B C D,\n InterCC A B C D -> A<>C.\nProof.\nintros.\nunfold InterCC in *.\nex_and H P.\nex_and H0 Q.\nunfold InterCCAt in *.\nspliter.\nunfold OnCircle in *.\nintro.\nsubst C.\napply H.\nunfold EqC.\nunfold OnCircle in *.\nassert(Cong A B A D) by (apply cong_transitivity with A P; Cong).\nintro.\nsplit.\nintro.\napply cong_transitivity with A B; Cong.\nintro.\napply cong_transitivity with A D; Cong.\nQed.\n\n(** Euclid Book III Prop 6 \nIf two circles touch one another, then they do not have the same center.\n*)\n\nLemma tangentcc__neq: forall A B C D,\n A<>B ->\n TangentCC A B C D ->\n A<>C.\nProof.\nintros.\nunfold TangentCC in *.\nunfold unique in *.\nex_and H0 T.\nintro.\nsubst C.\nunfold OnCircle in *.\nassert(Cong A B A D) by (apply cong_transitivity with A T; Cong).\nassert(T = B).\napply(H1 B); Cong.\nsubst T.\nassert(HH:=symmetric_point_construction B A).\nex_and HH B'.\nunfold Midpoint in *.\nspliter.\nassert(B = B').\n  apply(H1 B'); split; Cong.\n  apply cong_transitivity with A B; Cong.\nsubst B'.\ntreat_equalities; tauto.\nQed.\n\nLemma interccat__neq : forall A B C D P Q, InterCCAt A B C D P Q -> A <> C.\nProof.\nintros.\napply intercc__neq  with B D.\nunfold InterCC.\nexists P; exists Q;auto.\nQed.\n\n(** Prop 17 construction of the tangent to a circle at a given point *)\n\nLemma tangent_construction : forall O P X, segment_circle -> OutCircle X O P \n                                                  -> exists Y, Tangent X Y O P.\nProof.\nintros.\ninduction(eq_dec_points O P).\nsubst P.\nexists O.\nunfold Tangent.\nunfold unique.\nunfold OnCircle in *.\nexists O.\nrepeat split; Col; Cong.\nintros.\nspliter.\ntreat_equalities; auto.\n\nassert(O <> X).\n{\n  intro.\n  rewrite H2 in *;clear H2.\n  treat_equalities.\n  intuition.\n}\n\nassert(HH:=circle_cases O P X).\ninduction HH.\n\nassert(HH:= perp_exists X O X H2).\nex_and HH Y.\nunfold OnCircle in *.\nexists Y.\napply tangency_chara; auto.\nexists X.\napply perp_perp_in in H4.\nsplit; Circle.\n\ninduction H3.\nunfold OutCircle in *.\nunfold InCircleS in *.\napply lt__nle in H3; contradiction.\n\n\nassert(exists Q : Tpoint, OnCircle Q O P /\\ Out O X Q).\n{\n  apply(onc_exists); auto.\n}\n\nex_and H4 U.\n\nassert(Bet O U X).\n{\n  unfold Out in H5.\n  spliter.\n  induction H7.\n  unfold OutCircleS in *.\n  unfold OnCircle in *.\n  assert(Le O X O U).\n  {\n    unfold Le.\n    exists X.\n    split; Cong.\n  }\n  assert(Lt O U O X).\n  {\n    apply(cong2_lt__lt O P O X); Cong.\n  }\n  apply le__nlt in H8.\n  contradiction.\n  assumption.\n}\n\nassert(exists X : Tpoint, Perp U X O U).\n{\n  apply(perp_exists U O U).\n  intro.\n  unfold OnCircle in H4.\n  treat_equalities; tauto.\n}\nex_and H7 R.\nassert(HP:=symmetric_point_construction X O).\nex_and HP W.\nunfold Midpoint in *.\nspliter.\nassert(exists X0 : Tpoint, (Bet U R X0 \\/ Bet U X0 R) /\\ Cong U X0 W X).\n{\n  apply(segment_construction_2 R U W X).\n  apply perp_distinct in H8.\n  spliter.\n  auto.\n}\n\nex_and H10 T.\n\nassert(InCircleS U O X).\n{\n  unfold InCircleS.\n  unfold OutCircleS in H3.\n  unfold OnCircle in H4.\n  apply(cong2_lt__lt O P O X); Cong.\n}\n\nassert(OutCircleS T O X).\n{\n  apply(diam_cong_incs__outcs O X X W U T); auto.\n  unfold Diam.\n  unfold OnCircle.\n  repeat split; Cong.\n  Cong.\n}\nunfold segment_circle in H.\nassert(exists Z : Tpoint, Bet U Z T /\\ OnCircle Z O X).\n{\n  apply(H O X U T).\n  apply incs__inc; auto.\n  apply outcs__outc; auto.\n}\n\nex_and H14 Y.\nassert(exists Q : Tpoint, OnCircle Q O P /\\ Out O Y Q).\n{\n  apply(onc_exists O P Y); auto.\n  intro.\n  unfold OnCircle in H15.\n  treat_equalities; tauto.\n}\nex_and H16 V.\n\nexists V.\n\nassert(Bet O V Y).\n{\n  unfold Out in H17.\n  spliter.\n  induction H19.\n  unfold OutCircleS in H3.\n  assert(Lt O V O Y).\n  {\n    apply (cong2_lt__lt O P O X); Cong.\n  }\n  unfold OnCircle in *.\n  assert(Le O Y O V).\n  {\n    unfold Le.\n    exists Y.\n    split; Cong.\n  }\n  apply le__nlt in H21.\n  contradiction.\n  assumption.\n}\n\nassert(Cong O X O Y) by Cong.\nassert(Cong O U O V) by (apply cong_transitivity with O P; Cong).\n\n\nassert(CongA X O V Y O U).\n{\n  unfold OnCircle in *.\n  apply(l11_10 U O Y Y O U X V Y U).\n  apply conga_left_comm.\n  apply conga_refl; intro;treat_equalities; tauto.\n  repeat split; try(intro;treat_equalities; tauto).\n  right; auto.\n  repeat split; try(intro;treat_equalities; tauto).\n  left; auto.\n  apply out_trivial; intro;treat_equalities; tauto.\n  apply out_trivial; intro;treat_equalities; tauto.\n}\n\nassert(Cong V X U Y).\n{\n\n  apply(cong2_conga_cong V O X U O Y); Cong.\n  CongA.\n}\n\nassert(CongA O U Y O V X).\n{\n  unfold OnCircle in *.\n  apply(cong3_conga O U Y O V X).\n  intro;treat_equalities; tauto.\n  intro;treat_equalities.\n  unfold OutCircleS in *.\n  unfold Lt in *.\n  spliter.\n  Cong.\n  repeat split; Cong.\n}\n\nassert(Per O V X).\n{\n  apply(l11_17 O U Y O V X).\n  apply(perp_col _ _ _ _ Y) in H8.\n\n  apply perp_perp_in in H8.\n  apply perp_in_comm in H8.\n  apply perp_in_per.\n  apply perp_in_sym.\n  apply perp_in_comm.\n  assumption.\n  intro.\n  treat_equalities.\n  unfold CongA in H23.\n  tauto.\n  induction H10;\n  ColR.\n  assumption.\n}\n\napply tangency_chara; auto.\nexists V.\nsplit; auto.\napply per_perp_in in H24; Cong.\napply perp_in_left_comm.\napply perp_in_sym.\nassumption.\nunfold OnCircle in *.\nintro.\ntreat_equalities; tauto.\nintro.\ntreat_equalities.\nunfold CongA in H23.\ntauto.\nQed.\n\nLemma interccat__ncol : forall A B C D P Q,\n InterCCAt A B C D P Q -> ~ Col A C P.\nProof.\nintros.\nintro.\nassert (HH := H).\nunfold InterCCAt in HH.\nspliter.\napply H2.\napply (l4_18 A C).\napply interccat__neq in H.\nauto.\nassumption.\napply cong_transitivity with A B; Cong.\napply cong_transitivity with C D; Cong.\nQed.\n\n(** Euclid Book III Prop 10\n A circle does not cut a circle at more than two points.\n *)\nLemma cop_onc2__oreq : forall A B C D P Q,\n InterCCAt A B C D P Q -> Coplanar A C P Q ->\n forall Z, OnCircle Z A B -> OnCircle Z C D -> Coplanar A C P Z -> Z=P \\/ Z=Q.\nProof.\nintros.\nassert(HIC := H).\nunfold InterCCAt in H.\nspliter.\ninduction (eq_dec_points Z Q).\n  right; auto.\nleft.\nassert(HH:=midpoint_existence Q P).\nex_and HH M.\nassert(Per A M Q).\napply(mid_onc2__per A B Q P M); auto.\nassert(Per C M Q).\napply(mid_onc2__per C D Q P M); auto.\n\nassert(HH:=midpoint_existence Z Q).\nex_and HH N.\n\nassert(Per A N Q).\napply(mid_onc2__per A Z Q Z).\napply cong_transitivity with A B; Cong.\nCircle.\nMidpoint.\n\n\nassert(Per C N Q).\napply(mid_onc2__per C Z Q Z).\napply cong_transitivity with C D; Cong.\nCircle.\nMidpoint.\n\nassert(Col A C M).\napply cop_per2__col with Q; auto.\ninduction(col_dec P Q A).\nexists M.\nleft.\nsplit; ColR.\napply coplanar_perm_12, col_cop__cop with P; Col; Cop.\nassert_diffs;auto.\n\nassert(A <> C).\napply(interccat__neq A B C D P Q); auto.\n\nassert(Col A C N).\napply cop_per2__col with Q; auto.\napply coplanar_perm_12, col_cop__cop with Z; Col.\napply coplanar_trans_1 with P; Cop.\napply interccat__ncol in HIC.\nCol.\nassert_diffs;auto.\n\nassert(Perp A C Q P).\ninduction(eq_dec_points A M).\nsubst M.\napply per_perp_in in H12; auto.\napply perp_in_comm in H12.\n\napply perp_in_perp in H12.\napply perp_sym.\napply (perp_col Q A A C P); Perp.\nColR.\nassert_diffs;auto.\n\napply per_perp_in in H11; auto.\napply perp_in_comm in H11.\napply perp_in_perp in H11.\napply perp_comm in H11.\napply (perp_col A M M Q C) in H11; Col.\napply perp_sym in H11.\napply perp_comm in H11.\napply (perp_col Q M C A P) in H11; Col.\nPerp.\nassert_diffs;auto.\n\nassert(Col Q N Z).\nColR.\n\nassert(Perp A C Q Z).\ninduction(eq_dec_points A N).\nsubst N.\napply per_perp_in in H15; auto.\napply perp_in_comm in H15.\napply perp_in_perp in H15.\napply perp_sym.\napply (perp_col Q A A C Z); Perp.\nassert_diffs;auto.\n\napply per_perp_in in H14; auto.\napply perp_in_comm in H14.\napply perp_in_perp in H14.\napply perp_comm in H14.\napply (perp_col A N N Q C) in H14; Col.\napply perp_sym in H14.\napply perp_comm in H14.\napply (perp_col Q N C A Z) in H14; Col.\nPerp.\nassert_diffs;auto.\n\napply perp_sym in H21.\napply perp_sym in H19.\nassert (HH : Par Q P Q Z).\napply (l12_9 _ _ _ _ A C); auto.\nCop.\napply coplanar_trans_1 with P; Cop.\napply interccat__ncol in HIC.\nCol.\ninduction HH.\nunfold Par_strict in H22.\nspliter.\napply False_ind.\napply H23.\nexists Q.\nsplit; ColR.\nspliter.\nassert(Z = P \\/ Z = Q).\napply(line_circle_two_points A B P Q Z H4); auto.\ninduction H26; tauto.\nQed.\n\nEnd Tangency.\n\nSection Tangency_2D.\n\nContext `{T2D:Tarski_2D}.\n\nLemma onc2__oreq : forall A B C D P Q,\n InterCCAt A B C D P Q ->\n forall Z, OnCircle Z A B -> OnCircle Z C D  -> Z=P \\/ Z=Q.\nProof.\nintros.\nassert(HCop := all_coplanar A C P Q).\nassert(HCop1 := all_coplanar A C P Z).\napply(cop_onc2__oreq A B C D); assumption.\nQed.\n\nEnd Tangency_2D.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Tarski_dev/Annexes/tangency.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7125299138003236}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) (lf1 : natural) : natural :=\n  plus Zero lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj22_coqofml_NF9DHr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7125200820966693}}
{"text": "Inductive seq : nat -> Set :=\n| niln : seq 0\n| consn : forall n : nat , nat -> seq n -> seq (S n).\n\nFixpoint length (n:nat) (s:seq n) {struct s} : nat :=\n  match s with\n  | niln => 0\n  | consn i _ s' => S (length i s')\n  end.\n", "meta": {"author": "isqnwtn", "repo": "coqworks", "sha": "d4d280d01da598158f22401136613795bdcd0f99", "save_path": "github-repos/coq/isqnwtn-coqworks", "path": "github-repos/coq/isqnwtn-coqworks/coqworks-d4d280d01da598158f22401136613795bdcd0f99/basic/seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.7125200746357754}}
{"text": "Require Import XR_Rmin.\nRequire Import XR_Rlt.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rlt_le_trans.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rmin_Rgt_l : forall r1 r2 r, r < Rmin r1 r2  -> r < r1 /\\ r < r2.\nProof.\n  intros x y z.\n  intro h.\n  unfold Rmin in h.\n  destruct (Rle_dec x y) as [ hminl | hminr ].\n  {\n    split.\n    { exact h. }\n    {\n      apply Rlt_le_trans with x.\n      { exact h. }\n      { exact hminl. }\n    }\n  }\n  {\n    split.\n    {\n      apply Rlt_trans with y.\n      { exact h. }\n      {\n        apply Rnot_le_lt.\n        exact hminr.\n      }\n    }\n    {\n      exact h.\n    }\n  }\nQed.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rmin_Rgt_l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7125200651060223}}
{"text": "Require Import Wf.\nRequire Import Wf_nat.\n\nRequire Import Relation_Definitions.\n\nSection WfInclusion.\n  Variable A : Type.\n  Variables R1 R2 : A -> A -> Prop.\n\n  Lemma Acc_incl : inclusion A R1 R2 -> forall z:A, Acc R2 z -> Acc R1 z.\n  Proof.\n    induction 2.\n    apply Acc_intro; auto with sets.\n  Defined.\n  Hint Resolve Acc_incl.\n\n  Theorem wf_incl : inclusion A R1 R2 -> well_founded R2 -> well_founded R1.\n  Proof.\n    unfold well_founded in |- *; auto with sets.\n  Defined.\nEnd WfInclusion.\n\nSection Inverse_Image.\n  Variables A B : Type.\n  Variable R : B -> B -> Prop.\n  Variable f : A -> B.\n\n  Let Rof (x y:A) : Prop := R (f x) (f y).\n\n  Remark Acc_lemma : forall y:B, Acc R y -> forall x:A, y = f x -> Acc Rof x.\n  Proof.\n    induction 1 as [y _ IHAcc]; intros x H.\n    apply Acc_intro; intros y0 H1.\n    apply (IHAcc (f y0)); try trivial.\n    rewrite H; trivial.\n  Defined.\n\n  Lemma Acc_inverse_image : forall x:A, Acc R (f x) -> Acc Rof x.\n  Proof.\n    intros; apply (Acc_lemma (f x)); trivial.\n  Defined.\n\n  Theorem wf_inverse_image : well_founded R -> well_founded Rof.\n  Proof.\n    red in |- *; intros; apply Acc_inverse_image; auto.\n  Defined.\nEnd Inverse_Image.\n\n(** This section's aim is to prove that the lexicographic product of [<] *)\nSection Wf_lt_lexic.\n  Definition lex2 (p p' : nat*nat) : Prop :=\n    (fst p) < (fst p') \\/\n    (fst p) = (fst p') /\\ (snd p) < (snd p').\n  \n  Variable A B : Type.\n  Variable measA: A -> nat.\n  Variable measB: B -> nat.\n  \n  Definition orderAB : (A*B) -> (A*B) -> Prop :=\n    fun ab1 ab2 => \n      let (a1,b1) := ab1 in\n        let (a2, b2) := ab2 in\n          lex2 (measA a1, measB b1) (measA a2, measB b2).\n  \n  Theorem wf_lt_lexico : well_founded orderAB.\n  Proof.\n    intros [a b].\n    set (acc_a := (Wf_nat.well_founded_ltof A measA) a).\n    generalize b; clear b; induction acc_a as [a acc_a IHa].\n    pose (gen := refl_equal (measA a)).\n    intro b. generalize gen.\n    cut (forall a0, measA a = measA a0 -> Acc orderAB (a0,b)).\n    intros; auto.\n    pattern b; refine (well_founded_ind \n      (Wf_nat.well_founded_ltof B measB) _ _ b).\n    clear b; intros b IHb.\n    constructor.\n    intros [a1 b1] H2; destruct H2 as [H2 | H2]; simpl in H2.\n    apply (IHa a1). unfold Wf_nat.ltof.\n    rewrite H; assumption.\n    destruct H2 as [H2 H3].\n    apply (IHb b1). unfold Wf_nat.ltof.\n    assumption.\n    rewrite H2; assumption.\n  Defined.\nEnd Wf_lt_lexic.\n", "meta": {"author": "coq-contribs", "repo": "ergo", "sha": "d31962ab6cb56861e5d83691d4d5cea1b769f2c2", "save_path": "github-repos/coq/coq-contribs-ergo", "path": "github-repos/coq/coq-contribs-ergo/ergo-d31962ab6cb56861e5d83691d4d5cea1b769f2c2/theories/Lexico.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.7125200644835075}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf3 : natural) (z : natural) (lf2 : natural)\n  : natural := mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj133_coqofml_RmYkcE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723468, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7124417789107795}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) (y : natural) (x : natural)\n  : natural := mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj214_coqofml_XNwBb6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.7124019005260077}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (z : natural) (x : natural)\n  : natural := mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj275_coqofml_BhPYY3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.712401895623297}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf2 : natural) : natural :=\n  plus lf2 (mult (Succ y) z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_assoc/goal33conj192_coqofml_zTwiQD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7124018927026952}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (y : natural) (lf1 : natural)\n  : natural := mult x (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj195_coqofml_BlF6JQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7124018893646471}}
{"text": "(* Exercise 34 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_034 : ~(forall x, P x \\/ (Q x -> S x)) -> ~(forall x, S x).\nProof.\nimp_i a1.\nneg_i (forall x:D, P x \\/ (Q x -> S x)) a2.\nhyp a1.\nall_i a.\ndis_i2.\nimp_i a3.\nall_e (forall x:D, S x) a.\nhyp a2.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred034.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7124018858178752}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Category.\n\n(**\nA sub category of C is a category whose objects are a subset (here we ues \nsubset types, i.e., sig) of objects of C and whose arrows are a subset of\narrows of C.\n\nHere, we define a subcategory using two functions Obj_Cri : Obj C -> Prop\nwhich defines the objects of subcategory and \nHom_Cri : ∀ (a b : Obj) -> Hom a b -> Prop\nwhich defines the arrows of subcategory.\nIn other words, Obj_Cri and Hom_Cri are respectively cirteria for objects and\narrows being in the sub category. We furthermore, require that the Hom_Cri\nprovides that identity arrows of all objects in the subcategory are part of\nthe arrows of the subcategory. Additionally, For ant two composable arrow that\nare in the subcategory, their composition must also be in the subcategory.\n*)\nSection SubCategory.\n  Context (C : Category)\n          (Obj_Cri : Obj → Type)\n          (Hom_Cri : ∀ a b, (a –≻ b)%morphism → Prop).\n\n  Arguments Hom_Cri {_ _} _.\n  \n  Context (Hom_Cri_id : ∀ a, Obj_Cri a → Hom_Cri (id a))\n          (Hom_Cri_compose :\n             ∀ a b c (f : (a –≻ b)%morphism)\n               (g : (b –≻ c)%morphism),\n               Hom_Cri f → Hom_Cri g → Hom_Cri (g ∘ f)).\n\n  Arguments Hom_Cri_id {_} _.\n  Arguments Hom_Cri_compose {_ _ _ _ _} _ _.\n\n  Local Obligation Tactic := idtac.\n\n  Program Definition SubCategory : Category :=\n  {|\n    Obj := sigT Obj_Cri;\n\n    Hom :=\n      fun a b =>\n        sig (@Hom_Cri (projT1 a) (projT1 b));\n\n    compose :=\n      fun _ _ _ f g =>\n        exist _ _\n              (Hom_Cri_compose (proj2_sig f) (proj2_sig g));\n\n    id :=\n      fun a =>\n        exist _ _ (Hom_Cri_id (projT2 a))\n  |}.\n\n  Next Obligation.\n    intros.\n    apply sig_proof_irrelevance; simpl; abstract auto.\n  Qed.\n\n  Next Obligation.\n    symmetry.\n    apply SubCategory_obligation_1.\n  Qed.\n\n  Local Hint Extern 3 => simpl.\n  \n  Local Obligation Tactic := basic_simpl; auto.\n\n  Solve Obligations.\n\nEnd SubCategory.\n\n\n(**\nA wide subcategory of C is a subcategory of C that has all the objects of C but\nnot necessarily all its arrows.\n*)\nNotation Wide_SubCategory C Hom_Cri := (SubCategory C (fun _ => True) Hom_Cri).\n\n(**\nA Full subcategory of C is a subcategory of C that for any pair of objects of\nthe category that it has, it has all the arrows between them. In practice, we\nconstruct a full subcategory by only expecting an object criterion and setting\nthe arrow criterrion to accept all arrows.\n*)\nNotation Full_SubCategory C Obj_Cri :=\n  (SubCategory C Obj_Cri (fun _ _ _ => True) (fun _ _ => I) (fun _ _ _ _ _ _ _ => I)).\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/Categories/Category/SubCategory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7123452979905446}}
{"text": "Require Import List.\nImport ListNotations.\n\n(* 再帰関数の定義 *)\nFixpoint reverse {A : Type} (xs : list A) :=\n  match xs with\n  | nil => nil\n  | x :: xs' =>\n    reverse xs' ++ [x]\n  end.\n\nCompute reverse [1; 2; 3]. (* = [3; 2; 1] : list nat *)\n\n(* 補題 *)\nLemma reverse_append : forall (A : Type) (xs ys : list A),\n  reverse (xs ++ ys) = reverse ys ++ reverse xs.\nProof.\n  intros A xs ys.\n  induction xs.\n- simpl.\n  rewrite app_nil_r.\n  reflexivity.\n- simpl.\n  rewrite IHxs.\n  rewrite app_assoc.\n  reflexivity.\nQed.\n\nTheorem reverse_reverse : forall (A : Type) (xs : list A),\n  reverse (reverse xs) = xs.\nProof.\n  intros A xs.\n  induction xs.\n- simpl.\n  reflexivity.\n- simpl.\n  rewrite reverse_append.\n  simpl.\n  rewrite IHxs.\n  reflexivity.\nQed.\n", "meta": {"author": "0918nobita", "repo": "Coq", "sha": "da804200fa18645a422e77e76157652c5fedd05f", "save_path": "github-repos/coq/0918nobita-Coq", "path": "github-repos/coq/0918nobita-Coq/Coq-da804200fa18645a422e77e76157652c5fedd05f/reverse_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276107, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7123452960787534}}
{"text": "Require Export MoreCoq.\n\nCheck (3=3).\n\nCheck (forall (n : nat), n = 2).\n\nTheorem silly :\n  0 * 3 = 0.\n  reflexivity.\nQed.\n\nPrint silly.\n\nCheck eq_refl.\n\nCheck Prop.\nCheck silly.\n\nTheorem silly_1 :\n  forall (n:nat),\n    n = n.\n  reflexivity.\nQed.\n\nCheck silly_1.\nCheck (0*3 =0).\nCheck (0).\nCheck (forall (n m:nat),n = m).\nCheck (eq_refl).\nPrint silly.\n\nLemma silly_implication :\n  (1+1)=2 -> 0*3 = 0.\n  intros H.\n  reflexivity.\nQed.\n\nPrint silly_implication.\n\nPrint silly_1.\nCheck mult.\nCheck (nat -> nat -> nat).\nCheck (forall p q, p -> q).\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\nCheck and.\nCheck (conj).\nCheck (forall (p : Prop), p -> p -> and p p).\nCheck (0 = 0).\nCheck (nat).\n\nTheorem aaaaaa:\n  Prop -> Prop -> Prop.\n  apply and.\nQed.\nTheorem and_example :\n  (0 = 0) /\\ (4 = mult 2 2).\n  apply conj.\n  reflexivity.\n  reflexivity.\nQed.\nPrint and_example.\n\nPrint conj.\nPrint and.\nTheorem proj1 :\n  forall (P Q : Prop),\n    P /\\ Q -> P.\n  intros P Q H.\n  destruct H.\n  apply H.\nQed.\n\nPrint proj1.\n\nCheck proj1.\n\nTheorem and_commut :\n  forall (P Q : Prop),\n    P /\\ Q -> Q /\\ P.\n  intros P Q.\n  intros H.\n  destruct H.\n  apply conj.\n  apply H0.\n  apply H.\nQed.\n\nTheorem and_assoc :\n  forall (P Q R : Prop),\n    P /\\ ( Q /\\ R ) -> (P /\\ Q) /\\ R.\n\n  intros P Q R h.\n  destruct h.\n  destruct H0.\n  apply conj.\n  apply conj.\n  apply H.\n  apply H0.\n  apply H1.\nQed.\n\nDefinition iff ( P Q :Prop) := (P -> Q) /\\ (Q /\\ P).\nNotation \"P <-> Q\" := (iff P Q)\n                        (at level 95, no associativity)\n                      : type_scope.\nTheorem iff_implies :\n  forall (P Q :Prop),\n    (P <-> Q) -> P -> Q.\n  intros P Q.\n  intros H.\n  intros H1.\n  destruct H.\n  apply H in H1.\n  apply H1.\nQed.\n\nTheorem iff_sym :\n  forall (P Q : Prop),\n    (P <-> Q) -> (Q <-> P).\n  intros P Q h.\n  destruct h.\n  destruct H0.\n  apply conj.\n  intros q.\n  apply H1.\n  apply conj.\n  apply H1.\n  apply H0.\nQed.\n\nInductive or (P Q : Prop) : Prop :=\n| or_introl : P -> or P Q\n| or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\nCheck (or_introl).\n\nTheorem or_commut :\n  forall (P Q : Prop),\n    P \\/ Q -> Q \\/ P.\n  intros P Q h.\n  destruct h.\n  apply or_intror.\n  apply H.\n  apply or_introl.\n  apply H.\nQed.\n\nTheorem or_distributes_over_and_1 :\n  forall (P Q R : Prop),\n    P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\n  intros P Q R h.\n  apply conj.\n  destruct h.\n  left.\n  apply H.\n  destruct H.\n  right.\n  apply H.\n  destruct h.\n  left.\n  apply H.\n  destruct H.\n  right.\n  apply H0.\nQed.\n\nTheorem andb_prop :\n  forall (b c : bool),\n    andb b c = true ->\n    b = true /\\ c = true.\n  intros b c h.\n  unfold andb in h.\n  destruct b.\n  rewrite -> h.\n  apply conj.\n  reflexivity.\n  reflexivity.\n  apply conj.\n  apply h.\n  inversion h.\nQed.\n\nCheck true.\nCheck and.\n\nInductive False : Prop :=.\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\n  intros  h.\n  inversion h.\nQed.\n\nTheorem False_iiiiiiiiiii :\n  False -> 1 + 1 = 3.\n  intros h.\n\n  destruct h.\nQed.\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\n  intros h.\n  inversion h.\nQed.\n\nInductive Truth : Prop :=\n| fact : Truth.\n\nDefinition not (P : Prop) := P -> False.\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n\nTheorem contradiction_implies_anything :\n  forall (P Q :Prop),\n    (P /\\ (~P)) -> Q.\n  intros P Q.\n  intros H.\n  unfold not in H.\n  destruct H.\n  apply H0 in H.\n  inversion H.\nQed.\n\nTheorem double_neg :\n  forall (P : Prop),\n    P -> ~~P.\n  intros P p.\n  unfold not.\n  unfold not.\n  intros h.\n  apply h in p.\n  inversion p.\nQed.\n\nDefinition peirce :=\n  forall (P Q : Prop),\n    ((P -> Q) -> P) -> P.\n\nDefinition classic :=\n  forall (P : Prop),\n    ~~P -> P.\n\nTheorem O :\n  peirce <-> classic.\n  apply conj.\n  intro h.\n  unfold peirce in h.\n  unfold classic.\n  unfold not.\n  intro P.\n  intro h1.\nAbort.\n\nTheorem contrapositive:\n  forall (P Q : Prop),\n    (P -> Q) -> (~Q -> ~P).\n  intros P Q.\n  intros h.\n  unfold not.\n  intros h1.\n  intros p.\n  apply h in p.\n  apply h1 in p.\n  destruct p.\nQed.\n\nTheorem not_False:\n  False -> False.\n  intros h.\n  inversion h.\nQed.\n\nPrint not_False.\nTheorem excluded_middle_irrefutable:\n  forall (P : Prop),\n   ~~(P \\/ (~P)).\n  intros p.\n  unfold not.\n  intros h.\n  apply h.\n  right.\n  intros p1.\n  apply h.\n  left.\n  apply p1.\nQed.\n\nPrint excluded_middle_irrefutable.\n\n\n\nTheorem peirce_classic :\n  peirce -> classic.\n  unfold peirce.\n  unfold classic.\n  intros h.\n  unfold not.\n  intros P.\n  assert (((P -> False) -> P) -> P) as H.\n  apply h.\n  intros h1.\n  apply H.\n  intro h2.\n  apply h1 in h2.\n  inversion h2.\nQed.\n\nDefinition excluded_middle :=\n  forall (P : Prop),\n    P \\/ ~P.\n\nTheorem classic_excluded_middle :\n  classic -> excluded_middle.\n  unfold classic.\n  unfold excluded_middle.\n  intros H.\n  intros P.\n  assert (~~(P\\/~P)) as h.\n  apply excluded_middle_irrefutable.\n  apply H in h.\n  apply h.\nQed.\n\nDefinition de_morgan_not_and_not :=\n  forall (P Q :Prop),\n    ~(~P /\\ ~Q) -> P\\/Q.\n(*\nTheorem excluded_middle_de_morgan_not_and_not :\n  classic -> de_morgan_not_and_not.\n  unfold de_morgan_not_and_not.\n  unfold classic.\n  unfold not.\n  intros h.\n  intros p q.\n  intros h1.\n  apply h.\n  intros h2.\n  apply h1.\n  apply conj.\n  intros p1.\n  apply h2.\n  left.\n  apply p1.\n  intros q1.\n  apply h2.\n  right.\n  apply q1.\nQed.\n*)\nTheorem excluded_middle_classic :\n  excluded_middle -> classic.\n  unfold excluded_middle.\n  unfold classic.\n  unfold not.\n  intros h1.\n  intros p.\n  intros h.\n  assert (p \\/ (p -> False)) as H.\n  apply h1.\n  destruct H.\n  apply H.\n  apply h in H.\n  inversion H.\nQed.\n\nTheorem excluded_middle_de_morgan_not_and_not :\n  excluded_middle -> de_morgan_not_and_not.\n  unfold excluded_middle.\n  unfold de_morgan_not_and_not.\n  unfold not.\n  intros h.\n  intros p q.\n  intro h1.\n  assert (p \\/ ( p -> False)) as H.\n  apply h.\n  destruct H.\n  left.\n  apply H.\n  assert (q \\/ (q -> False)) as H2.\n  apply h.\n  destruct H2.\n  right.\n  apply H0.\n  assert ((p -> False) /\\ (q -> False)) as H3.\n  apply conj.\n  apply H.\n  apply H0.\n  apply h1 in H3.\n  inversion H3.\nQed.\n\nDefinition implies_to_or :=\n  forall p q:Prop,\n    (p -> q) -> (~p\\/q).\n\nTheorem de_morgan_not_and_not_implies_to_or:\n  de_morgan_not_and_not -> implies_to_or.\n  unfold de_morgan_not_and_not.\n  unfold implies_to_or.\n  unfold not.\n  intros H.\n  intros p q.\n  intros h1.\n  apply H.\n  intros h2.\n  destruct h2.\n  apply H0.\n  intros p'.\n  apply H1.\n  apply h1.\n  apply p'.\nQed.\n\nTheorem implies_to_or_peirce :\n  implies_to_or -> peirce.\n  unfold implies_to_or.\n  unfold peirce.\n  unfold not.\n  intros H.\n  intros p q.\n  intros h.\n  assert ((p -> p) -> (p -> False) \\/ p) as h1.\n  apply H.\n  assert ( p->p) as h2.\n  intros p'.\n  apply p'.\n  apply h1 in h2.\n  destruct h2.\n  apply h.\n  intros p'.\n  apply H0 in p'.\n  inversion p'.\n  apply H0.\nQed.\n\n(* Please all use excluded_middle *)\n\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\nTheorem not_false_then_true :\n  forall (b : bool),\n    b <> false -> b = true.\n\n  intros b.\n  intros h.\n  destruct b.\n  reflexivity.\n  unfold not in h.\n  assert (false = false) as h'.\n  reflexivity.\n  apply h in h'.\n  inversion h'.\nQed.\n", "meta": {"author": "DKXXXL", "repo": "SoftwareFoundations-BeforeCh15", "sha": "fa69bb170f91e5e358747575815f03ad8846646f", "save_path": "github-repos/coq/DKXXXL-SoftwareFoundations-BeforeCh15", "path": "github-repos/coq/DKXXXL-SoftwareFoundations-BeforeCh15/SoftwareFoundations-BeforeCh15-fa69bb170f91e5e358747575815f03ad8846646f/7th.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.712345293294006}}
{"text": "(** A library of positive multivariate polynomials *)\n\nRequire Import Arith List.\nRequire Import BellantoniCook.Lib.\n\n(** * Representation of polynomials:\n\n  - [pow] is the type of a variable identifier and its exponent.\n\n  - [mon] is the type of a monomial, consisting of a coefficient and a list of variable identifiers with their exponents.\n\n  - [pol] is the type of a polynomial, consisting of the number of variables and a list of monomials.\n*)\n\nDefinition pow : Type := (nat*nat)%type.\nDefinition mon : Type := (nat * list pow)%type.\nDefinition pol : Type := (nat * list mon)%type.\n\n(** * Evaluation of polynomials\n\n  - [peval p [v0, v1,...]] is the evaluation of the polynomial [p] with variables [0], [1]... respectively\n    instantiated with the values [v0], [v1]...\n    If a variable is not assigned a value, then it is assumed to be [0].\n    Values that do not correspond to a variable are ignored.\n*)\n\nDefinition peval_pow (xn:pow)(l:list nat) : nat :=\n  power (nth (fst xn) l 0) (snd xn).\n\nDefinition peval_mon (m:mon)(l:list nat) : nat :=\n  (fst m) * multl (map (fun x => peval_pow x l) (snd m)).\n\nDefinition peval (p:pol)(l:list nat) :=\n  plusl (map (fun m => peval_mon m l) (snd p)).\n\nLemma peval_parity : forall ar p l,\n  peval (ar, snd p) l = peval p l.\nProof. intros ar [ar0 ml] l; simpl; trivial. Qed.\n\nLemma peval_pow_monotonic : forall xn l1 l2, \n  (forall i, nth i l1 0 <= nth i l2 0) ->\n  peval_pow xn l1 <= peval_pow xn l2.\nProof.\n intros [x n] l1 l2 H; simpl.\n apply power_le_l; trivial.\nQed.\n\nLemma peval_mon_monotonic : forall m l1 l2, \n  (forall i, nth i l1 0 <= nth i l2 0) ->\n  peval_mon m l1 <= peval_mon m l2.\nProof.\n unfold peval_mon; intros [a xl] l1 l2 H.\n induction xl; simpl; trivial.\n rewrite !mult_assoc, !(mult_comm a), <- !mult_assoc.\n apply mult_le_compat; trivial.\n apply peval_pow_monotonic; trivial.\nQed.\n\nLemma peval_monotonic : forall p l1 l2, \n  (forall i, nth i l1 0 <= nth i l2 0) ->\n  peval p l1 <= peval p l2.\nProof.\n unfold peval; intros [ar ml] l1 l2 H.\n induction ml; simpl; trivial.\n apply plus_le_compat; trivial.\n apply peval_mon_monotonic; trivial.\nQed.\n\nLemma peval_nth i pl p l :\n  peval (nth i pl p) l =\n  nth i (map (fun p => peval p l) pl) (peval p l).\nProof.\n intros; revert i.\n induction pl; intros [ | i]; simpl; intros; trivial.\nQed.\n\nNotation parity := (@fst nat (list mon)).\n\n(** * Well-formedness of polynomials *)\n\nDefinition pWF_pow (ar:nat)(xn:pow) : Prop :=\n  fst xn < ar.\n\nDefinition pWF_mon (ar:nat)(m:mon) : Prop :=\n  andl (pWF_pow ar) (snd m).\n\nDefinition pWF' (ar:nat)(ml:list mon) : Prop :=\n  andl (pWF_mon ar) ml.\n\nDefinition pWF (p:pol) : Prop :=\n  pWF' (fst p) (snd p).\n\nLemma pWF_mon_le : forall ar1 ar2 m,\n  ar1 <= ar2 -> \n  pWF_mon ar1 m -> pWF_mon ar2 m.\nProof.\n unfold pWF_mon, pWF_pow; intros ar1 ar2 [a xl].\n induction xl as [ | xn xl' IH]; simpl; intros; trivial.\n destruct xn as [x n]; simpl in *.\n split;[ omega | tauto].\nQed.\n\nLemma pWF'_le ar1 ar2 ml :\n  ar1 <= ar2 -> pWF' ar1 ml -> pWF' ar2 ml.\nProof.\n induction ml; simpl; intros; trivial.\n split;[ | tauto].\n apply pWF_mon_le with ar1; trivial; tauto.\nQed.\n\nLemma pWF_mon_app : forall ar a1 xl1 a2 xl2,\n  pWF_mon ar (a1, xl1) -> pWF_mon ar (a2, xl2) ->\n  pWF_mon ar (a1*a2, xl1++xl2).\nProof.\n unfold pWF_mon, pWF_pow.\n induction xl1 as [ | [x n] xl1' IH]; simpl; intros; trivial.\n split;[ tauto | ].\n apply IH with a1; tauto.\nQed.\n\nLemma pWF'_app ar ml1 ml2 :\n  pWF' ar ml1 -> pWF' ar ml2 -> pWF' ar (ml1++ml2).\nProof.\n induction ml1 as [ | m1 ml1' IH]; simpl; intros; trivial.\n split;[ tauto | ].\n apply IH; tauto.\nQed.\n\nLemma pWF_nth i pl p0 :\n  andl pWF pl -> pWF p0 -> pWF (nth i pl p0).\nProof.\n intros; revert i.\n induction pl; simpl in *; intros; case i; intros; trivial.\n tauto.\n apply IHpl; tauto.\nQed.\n\nLemma parity_mon_correct : forall ar m l l1 l2,\n  pWF_mon ar m -> length l = ar -> peval_mon m (l++l1) = peval_mon m (l++l2).\nProof.\n unfold peval_mon, peval_pow, pWF_mon, pWF_pow.\n intros ar [a xl] l l1 l2 H1 H2; simpl in *; f_equal; f_equal.\n induction xl as [ | [x n] xl' IH]; simpl in *; trivial.\n f_equal;[ | tauto].\n f_equal; rewrite !app_nth1; trivial; omega.\nQed.\n\nLemma parity_correct : forall p l l1 l2,\n  pWF p -> length l = parity p -> peval p (l++l1) = peval p (l++l2).\nProof.\n unfold peval, peval_mon, peval_pow, pWF, pWF_mon, pWF_pow.\n intros [ar ml] l l1 l2 H1 H2; simpl in *; f_equal.\n induction ml as [ | m ml' IH]; simpl in *; trivial.\n f_equal;[ | tauto].\n apply parity_mon_correct with ar; tauto.\nQed.\n\n(** * Basic polynomials *)\n\n(** ** Constant polynomial\n\n  - [pcst ar a] is the constant polynomial with [ar] variables and equal to the constant [a].\n*)\n\nDefinition pcst (ar a:nat) : pol :=\n  (ar, [(a,nil)]).\n\nLemma parity_pcst ar a :\n  parity (pcst ar a) = ar.\nProof. trivial. Qed.\n\nLemma pWF_pcst ar a : pWF (pcst ar a).\nProof. compute; intros; tauto. Qed.\n\nLemma pcst_correct : forall ar k l, peval (pcst ar k) l = k.\nProof. unfold peval, peval_mon, peval_pow; simpl; intros; omega. Qed.\n\n(** ** Single variable polynomial\n\n  - [pproj ar i] is the polynomial with [ar] variables and equal to the [i]th variable.\n*)\n\nDefinition pproj (ar i:nat) : pol :=\n  (ar,[(1,[(i,1)])]).\n\nLemma parity_pproj n i :\n  parity (pproj n i) = n.\nProof. trivial. Qed.\n\nLemma pWF_pproj ar i : i < ar -> pWF (pproj ar i).\nProof. compute; intros; tauto. Qed.\n\nLemma pproj_correct : forall ar i l,\n peval (pproj ar i) l = nth i l 0.\nProof. unfold peval, peval_mon, peval_pow; simpl; intros; omega. Qed.\n\n(** ** Scalar multiplication of a polynomial\n\n  - [pscalar n p] is the polynomial [p] where all coefficients have been multiplied by [n].\n*)\n\nDefinition pscalar_mon (n:nat)(m:mon) : mon :=\n  (n * fst m, snd m).\n\nDefinition pscalar (n:nat)(p:pol) : pol :=\n  (fst p, map (pscalar_mon n) (snd p)).\n\nLemma parity_pscalar n p :\n  parity (pscalar n p) = parity p.\nProof. trivial. Qed.\n\nLemma pWF_pscalar : forall n p,\n  pWF p -> pWF (pscalar n p).\nProof.\n unfold pWF, pWF_mon, pWF_pow; intros n [ar ml] H.\n induction ml; simpl in *; trivial; tauto.\nQed.\n\nLemma pscalar_mon_correct : forall n m l,\n  peval_mon (pscalar_mon n m) l = n * peval_mon m l.\nProof. unfold peval_mon; intros n [a xl] l; simpl; ring. Qed.\n\nLemma map_pscalar_mon n ml l :\n  plusl (map (fun m => peval_mon (pscalar_mon n m) l) ml) =\n  n * plusl (map (fun m => peval_mon m l) ml).\nProof.\n induction ml; simpl; trivial.\n rewrite pscalar_mon_correct, IHml; ring.\nQed.\n\nLemma pscalar_correct : forall n p l,\n  peval (pscalar n p) l = n * peval p l.\nProof.\n unfold peval, pscalar; intros n [ar pl] l.\n induction pl; simpl in *; trivial.\n rewrite map_map in *.\n rewrite pscalar_mon_correct; simpl in IHpl.\n rewrite IHpl; ring.\nQed.\n\n(** ** Sum of polynomials\n\n  - [pplus p1 p2] is the sum of the polynomials [p1] and [p2].\n\n  - [pplusl pl] is the sum of the polynomials in the list [pl].\n*)\n\nDefinition pplus (p1 p2:pol) : pol :=\n  (max (fst p1) (fst p2), snd p1 ++ snd p2).\n\nLemma parity_pplus : forall p1 p2,\n  parity (pplus p1 p2) = max (parity p1) (parity p2).\nProof.\n intros [ar1 ml1] [ar2 ml2]; trivial.\nQed.\n\nLemma pWF_pplus : forall p1 p2,\n  pWF p1 -> pWF p2 -> pWF (pplus p1 p2).\nProof.\n unfold pWF, pWF_mon, pWF_pow.\n intros [ar1 ml1] [ar2 ml2] H1 H2; simpl in *.\n induction ml1 as [ | m1 ml1' IH]; simpl in *.\n apply pWF'_le with ar2; auto with arith.\n split;[ | tauto ].\n apply pWF_mon_le with ar1; auto with arith; tauto.\nQed.\n\nLemma pplus_correct : forall p1 p2 l,\n peval (pplus p1 p2) l = peval p1 l + peval p2 l.\nProof.\n unfold peval, peval_mon, peval_pow.\n intros [ar1 ml1] [ar2 ml2] l.\n induction ml1 as [ | m1 ml1' IH]; simpl in *; trivial.\n unfold peval, pplus in IH; rewrite IH; ring.\nQed.\n\nDefinition pplusl (pl:list pol) : pol :=\n  fold_right pplus (pcst 0 0) pl.\n\nLemma parity_pplusl : forall pl,\n  parity (pplusl pl) = maxl (map parity pl).\nProof.\n induction pl; trivial; simpl pplusl.\n rewrite parity_pplus, IHpl; trivial.\nQed.\n\nDefinition pWF_pplusl : forall pl,\n  andl pWF pl -> pWF (pplusl pl).\nProof.\n unfold pWF, pWF_mon, pWF_pow.\n induction pl; intros;[ simpl; tauto |].\n apply pWF_pplus; simpl in *; tauto.\nQed.\n\nLemma pplusl_correct : forall pl l,\n  peval (pplusl pl) l = plusl (map (fun p => peval p l) pl).\nProof.\n induction pl; simpl; intros; trivial.\n rewrite pplus_correct, IHpl; trivial.\nQed.\n\nLemma peval_nth_pplus : forall pl l i n,\n  peval (nth i pl (pcst n 0)) l <=\n  peval (pplusl pl) l.\nProof.\n induction pl; simpl; intros; case i; trivial; rewrite pplus_correct; [ omega | ].\n intros; eapply le_trans;[ apply IHpl | ].\n omega.\nQed.\n\n(** ** Multiplication of polynomials\n\n  - [pmult p1 p2] is the multiplication of the polynomials [p1] and [p2].\n\n  - [pmultl pl] is the multiplication of the polynomials in the list [pl].\n*)\n\nDefinition pmult_mon (m12:mon*mon) : mon :=\n  (fst (fst m12) * fst (snd m12), snd (fst m12) ++  snd (snd m12)).\n\nDefinition pmult (p1 p2:pol) : pol :=\n  (max (fst p1) (fst p2), map pmult_mon (list_prod (snd p1) (snd p2))).\n\nLemma parity_pmult : forall p1 p2,\n  parity (pmult p1 p2) = max (parity p1) (parity p2).\nProof. intros [ar1 ml1] [ar2 ml2]; trivial. Qed.\n\nLemma pWF_pmult_mon : forall ar1 m1 ar2 m2,\n  pWF_mon ar1 m1 -> pWF_mon ar2 m2 ->\n  pWF_mon (max ar1 ar2) (pmult_mon (m1, m2)).\nProof.\n intros ar1 [a1 xl1] ar2 [a2 xl2]; simpl pmult_mon; intros.\n apply pWF_mon_app.\n apply pWF_mon_le with ar1; auto with arith.\n apply pWF_mon_le with ar2; auto with arith.\nQed.\n\nLemma pWF_pmult : forall p1 p2,\n  pWF p1 -> pWF p2 -> pWF (pmult p1 p2).\nProof.\n unfold pWF, pWF_mon, pWF_pow.\n intros [ar1 ml1] [ar2 ml2] H1 H2; simpl in *.\n induction ml1 as [ | m1 ml1' IH1]; simpl in *; intros; trivial.\n rewrite map_app, map_map.\n apply pWF'_app;[ | tauto ].\n clear IH1.\n induction ml2 as [ | m2 ml2' IH2]; simpl in *; intros; trivial.\n split;[ | tauto ].\n apply pWF_pmult_mon; tauto.\nQed.\n\nLemma pmult_mon_correct : forall m12 l,\n  peval_mon (pmult_mon m12) l =\n  peval_mon (fst m12) l * peval_mon (snd m12) l.\nProof.\n unfold peval_mon, peval_pow.\n intros [[a1 xl1] [a2 xl2]] l; simpl.\n induction xl1 as [ | x1 xl1' IH]; simpl;[ ring | ring [IH] ].\nQed.\n\nLemma map_pmult_mon : forall m1 ml2 l,\n map (fun m2 => peval_mon (pmult_mon (m1, m2)) l) ml2 =\n map (fun m2 => peval_mon m1 l * peval_mon m2 l) ml2.\nProof.\n unfold peval_mon, peval_pow.\n intros [a1 xl1] ml2 l; simpl.\n induction ml2 as [ | [a2 xl2] ml2' IH]; simpl; trivial.\n rewrite IH, map_app, multl_app; f_equal; ring.\nQed.\n\nLemma pmult_correct : forall p1 p2 l,\n peval (pmult p1 p2) l = peval p1 l * peval p2 l.\nProof.\n unfold peval; intros [ar1 ml1] [ar2 ml2] l; simpl.\n induction ml1 as [ | m1 ml1' IH]; simpl; trivial.\n rewrite !map_app, !map_map, map_pmult_mon, plusl_app.\n rewrite map_map in IH; rewrite IH.\n rewrite mult_plus_distr_r.\n f_equal.\n rewrite multl_plus_distr_l, map_map; trivial.\nQed.\n\nDefinition pmultl (pl:list pol) : pol :=\n  fold_right pmult (pcst 0 1) pl.\n\nLemma parity_pmultl pl :\n  parity (pmultl pl) = maxl (map parity pl).\nProof.\n induction pl; simpl pmultl; trivial.\n rewrite parity_pmult, IHpl; trivial.\nQed.\n\nDefinition pWF_pmultl pl :\n  andl pWF pl -> pWF (pmultl pl).\nProof.\n induction pl; simpl pmultl; intros.\n apply pWF_pcst.\n apply pWF_pmult; simpl in *; tauto.\nQed.\n\nLemma pmultl_correct pl l :\n  peval (pmultl pl) l = multl (map (fun p => peval p l) pl).\nProof.\n induction pl; simpl; intros; trivial.\n rewrite pmult_correct, IHpl; trivial.\nQed.\n\n(** ** Power of a polynomial\n\n  - [ppower p n] is the polynomial [p] to the power [n].\n*)\n\nFixpoint ppower (p:pol)(n:nat) : pol :=\n  match n with\n  | 0 => pcst (fst p) 1\n  | S n' => pmult p (ppower p n')\n  end.\n\nLemma parity_ppower p n :\n  parity (ppower p n) = parity p.\nProof.\n induction n; simpl ppower; trivial.\n rewrite parity_pmult, IHn; auto with arith.\nQed.\n\nLemma pWF_ppower p n :\n  pWF p -> pWF (ppower p n).\nProof.\n induction n; simpl ppower; intros.\n apply pWF_pcst.\n apply pWF_pmult; tauto.\nQed.\n\nLemma ppower_correct p n l :\n  peval (ppower p n) l = power (peval p l) n.\nProof.\n induction n; simpl; intros; trivial.\n rewrite pmult_correct, IHn;trivial.\nQed.\n\n(** ** Composition of polynomials\n\n  - [pcomp p pl] is the polynomial [p] where each variable [i] is replaced by the [i]th polynomial in \n    the list [pl].\n*)\n\nDefinition pcomp_pow' (xn:pow)(pl:list pol) : pol :=\n  ppower (nth (fst xn) pl (pcst 0 0)) (snd xn).\n\nDefinition pcomp_pow (xn:pow)(pl:list pol) : pol :=\n  (maxl (map parity pl), snd (pcomp_pow' xn pl)).\n\nDefinition pcomp_mon' (m:mon)(pl:list pol) : pol :=\n  pscalar (fst m) (pmultl (map (fun xn => pcomp_pow xn pl) (snd m))).\n\nDefinition pcomp_mon (m:mon)(pl:list pol) : pol :=\n  (maxl (map parity pl), snd (pcomp_mon' m pl)).\n\nDefinition pcomp' (p:pol)(pl:list pol) : pol :=\n  pplusl (map (fun m => pcomp_mon m pl) (snd p)).\n\nDefinition pcomp (p:pol)(pl:list pol) : pol :=\n  (maxl (map parity pl), snd (pcomp' p pl)).\n\nLemma parity_pcomp_pow : forall xn pl,\n  parity (pcomp_pow xn pl) = maxl (map parity pl).\nProof.\n unfold pcomp_pow; intros [x n] pl; simpl.\n case_eq (ppower (nth x pl (pcst 0 0)) n); trivial.\nQed.\n\nLemma map_parity_pcomp_pow xl pl :\n  map (fun xn => parity (pcomp_pow xn pl)) xl = map (fun _ => maxl (map parity pl)) xl.\nProof. destruct xl; simpl; trivial. Qed.\n\nLemma parity_pcomp_mon' : forall m pl,\n  parity (pcomp_mon' m pl) <= maxl (map parity pl).\nProof.\n intros [a xl] pl; simpl.\n rewrite parity_pmultl.\n induction xl; simpl.\n omega.\n apply Nat.max_lub; trivial.\nQed.\n\nLemma parity_pcomp_mon : forall m pl,\n  parity (pcomp_mon m pl) = maxl (map parity pl).\nProof.\n unfold pcomp_mon; intros [a xl] pl; simpl; trivial.\nQed.\n\nLemma parity_pcomp p pl :\n  parity (pcomp p pl) = maxl (map parity pl).\nProof.\n unfold pcomp; intros.\n case (pcomp' p pl); trivial.\nQed.\n\nLemma pWF_pcomp_pow' : forall xn pl,\n  andl pWF pl -> pWF (pcomp_pow' xn pl).\nProof.\n intros [x n] pl H; simpl.\n apply pWF_ppower.\n apply pWF_nth; trivial.\n apply pWF_pcst.\nQed.\n\nLemma pWF_pcomp_pow : forall xn pl,\n  andl pWF pl -> pWF (pcomp_pow xn pl).\nProof.\n intros [x n] pl H.\n apply pWF'_le with (ar1 := fst (pcomp_pow' (x, n) pl)).\n rewrite parity_pcomp_pow.\n unfold pcomp_pow'.\n rewrite parity_ppower.\n destruct (le_lt_dec (length pl) x).\n rewrite nth_overflow; auto with arith.\n apply in_le_maxl.\n apply in_map.\n apply nth_In; trivial.\n apply pWF_pcomp_pow'; trivial.\nQed.\n\nLemma pWF_pcomp_mon' : forall m pl,\n  andl pWF pl -> pWF (pcomp_mon' m pl).\nProof.\n unfold pWF, pWF', pWF_mon, pWF_pow.\n intros [a xl] pl H.\n induction xl as [ | [x n]  xl' IH].\n simpl; tauto.\n apply pWF_pscalar.\n apply pWF_pmultl.\n clear IH.\n induction xl'; simpl in *.\n split; trivial.\n apply pWF_pcomp_pow; trivial.\n split;[ tauto | split ].\n apply pWF_pcomp_pow; trivial.\n apply IHxl'.\nQed.\n\nLemma pWF_pcomp_mon : forall m pl,\n  andl pWF pl -> pWF (pcomp_mon m pl).\nProof.\n intros [a xl] pl H.\n apply pWF'_le with (ar1 := fst (pcomp_mon' (a, xl) pl)).\n apply parity_pcomp_mon'.\n apply pWF_pcomp_mon'; trivial.\nQed.\n\nLemma pWF_pcomp' : forall p pl,\n  andl pWF pl -> pWF (pcomp' p pl).\nProof.\n intros [ar ml] pl H; simpl.\n apply pWF_pplusl.\n induction ml; simpl in *; trivial.\n split; trivial.\n apply pWF_pcomp_mon; trivial.\nQed.\n\nLemma pWF_pcomp : forall p pl,\n  andl pWF pl -> pWF (pcomp p pl).\nProof.\n intros [ar ml] pl H.\n apply pWF'_le with (ar1 := fst (pcomp' (ar, ml) pl)).\n rewrite parity_pcomp; unfold pcomp'.\n rewrite parity_pplusl, map_map.\n induction ml; simpl.\n omega.\n apply Nat.max_lub; trivial.\n apply pWF_pcomp'; trivial.\nQed.\n\nLemma pcomp_pow'_correct : forall xn pl l,\n  peval (pcomp_pow' xn pl) l =\n  power (peval (nth (fst xn) pl (pcst 0 0)) l) (snd xn).\nProof. intros [x n] pl l; simpl; apply ppower_correct. Qed.\n\nLemma pcomp_pow_correct xn pl l :\n  peval (pcomp_pow xn pl) l =\n  power (peval (nth (fst xn) pl (pcst 0 0)) l) (snd xn).\nProof.\n intros; unfold pcomp_pow; apply pcomp_pow'_correct.\nQed.\n\nLemma pcomp_mon'_correct : forall m pl l,\n  peval (pcomp_mon' m pl) l = peval_mon m (map (fun p => peval p l) pl).\nProof.\n intros [a xl] pl l; induction xl.\n unfold peval, peval_mon.\n simpl; ring.\n unfold pcomp_mon' in *; simpl in *.\n rewrite pscalar_correct, pmult_correct, pmultl_correct in *.\n rewrite mult_assoc, (mult_comm a), <- mult_assoc, IHxl, pcomp_pow_correct, peval_nth.\n destruct a0 as [x n].\n unfold peval_mon, peval_pow.\n rewrite pcst_correct; simpl; ring.\nQed.\n\nLemma pcomp_mon_correct : forall m pl l,\n  peval (pcomp_mon m pl) l = peval_mon m (map (fun p => peval p l) pl).\nProof.\n intros [a xl] pl l; unfold pcomp_mon.\n rewrite peval_parity.\n apply pcomp_mon'_correct.\nQed.\n\nLemma pcomp'_correct : forall p pl l,\n  peval (pcomp' p pl) l = peval p (map (fun p' => peval p' l) pl).\nProof.\n unfold pcomp'; intros [ar ml] pl l.\n induction ml; simpl in *; trivial.\n rewrite pplus_correct, pcomp_mon_correct, IHml; trivial.\nQed.\n\nLemma pcomp_correct p pl l :\n  peval (pcomp p pl) l = peval p (map (fun p => peval p l) pl).\nProof.\n intros; unfold pcomp; rewrite peval_parity.\n apply pcomp'_correct.\nQed.\n\n(** ** Shifting of a polynomial\n\n  - [pshift p] is the polynomial [p] with one more variable and where each variable [i] is replaced by [i+1].\n*)\n\nDefinition pshift_pow (xn:pow) : pow :=\n  (S (fst xn), snd xn).\n\nDefinition pshift_mon (m:mon) : mon :=\n  (fst m, map pshift_pow (snd m)).\n\nDefinition pshift (p:pol) : pol :=\n  (S (fst p), map pshift_mon (snd p)).\n\nLemma parity_pshift : forall p,\n  parity (pshift p) = S (parity p).\nProof. intros [ar ml]; trivial. Qed.\n\nLemma pWF_pshift_mon : forall ar m,\n  pWF_mon ar m -> pWF_mon (S ar) (pshift_mon m).\nProof.\n unfold pWF_mon, pWF_pow.\n intros ar [a xl] H; simpl.\n induction xl as [ | [x n]  xl' IH]; simpl in *; trivial.\n split; [ omega | tauto ].\nQed.\n\nLemma pWF_pshift : forall p, pWF p -> pWF (pshift p).\nProof.\n unfold pWF; intros [ar ml] H; simpl.\n induction ml; simpl in *; trivial.\n split;[ | tauto].\n apply pWF_pshift_mon; tauto.\nQed.\n\nLemma pshift_pow_correct : forall xn l,\n  peval_pow (pshift_pow xn) l = peval_pow xn (tl l).\nProof.\n unfold peval_pow; intros [x n] l; simpl; f_equal.\n rewrite nth_S_tl; trivial.\nQed.\n\nLemma pshift_mon_correct : forall m l,\n  peval_mon (pshift_mon m) l = peval_mon m (tl l).\nProof.\n unfold peval_mon; intros [a xl] l.\n induction xl; simpl in * ;trivial.\n rewrite mult_assoc, (mult_comm a), <- mult_assoc, pshift_pow_correct, IHxl; ring.\nQed.\n\nLemma pshift_correct : forall p l,\n  peval (pshift p) l = peval p (tl l).\nProof.\n unfold peval; intros [ar ml] l.\n induction ml; simpl in *; trivial.\n rewrite pshift_mon_correct, IHml; trivial.\nQed.\n\n(** ** Polynomial defined as a sum of a range of variables\n\n  - [psum start len] is the polynomial with [start+len] variables and\n    consisting in the sum of the variables [start] to [start+len-1].\n*)\n\nDefinition psum (start len : nat) : pol :=\n  pplus (pcst (start+len) 0) (pplusl (map (pproj (start+len)) (seq start len))).\n\nLemma psum_correct start len l :\n  peval (psum start len) l = \n  plusl (map (fun i => nth i l 0) (seq start len)).\nProof.\n intros; unfold psum.\n rewrite pplus_correct, pcst_correct, pplusl_correct; simpl; f_equal.\n induction (seq start len); simpl; intros; trivial.\n rewrite pproj_correct; congruence.\nQed.\n\nLemma pWF_psum start len : pWF (psum start len).\nProof.\n intros;unfold psum.\n apply pWF_pplus.\n apply pWF_pcst.\n apply pWF_pplusl.\n rewrite <- forall_andl; intros.\n rewrite in_map_iff in H.\n destruct H as (y & H1 & H2); subst.\n apply pWF_pproj.\n rewrite in_seq_iff in H2.\n tauto.\nQed.\n\nLemma parity_psum start len : \n  parity (psum start len) = start + len.\nProof.\n intros; unfold psum.\n rewrite parity_pplus, parity_pcst, parity_pplusl, max_l; trivial.\n apply maxl_map.\n intros p H.\n rewrite in_map_iff in H.\n destruct H as (x & H & _).\n subst; trivial.\nQed.\n\n(** * Tactic for well-formedness\n\n  - The tactic [pWF] attempts to prove automatically goals of the form [pWF p] where\n    [p] is a polynomial.\n*)\n\nLtac pWF :=\n  match goal with\n  | |- pWF (pcst _ _) => apply pWF_pcst\n  | |- pWF (pproj _ _) => apply pWF_pproj; try omega\n  | |- pWF (pscalar _ _) => apply pWF_pscalar; pWF\n  | |- pWF (pplus _ _) => apply pWF_pplus; pWF\n  | |- pWF (pplusl _) => apply pWF_pplusl; rewrite <- forall_andl; intros; pWF\n  | |- pWF (pmult _ _) => apply pWF_pmult; pWF\n  | |- pWF (pmultl _) => apply pWF_pmultl; rewrite <- forall_andl; intros; pWF\n  | |- pWF (ppower _ _) => apply pWF_ppower; pWF\n  | |- pWF (pcomp _ _) => apply pWF_pcomp; rewrite <- forall_andl; intros; pWF\n  | |- pWF (pshift _) => apply pWF_pshift; pWF\n  | |- pWF (psum _ _) => apply pWF_psum\n  | |- _ => idtac\n  end.\n\n(** * Degree of a polynomial\n\n  - [deg p] is the degree of the polynomial [p].\n*)\n\nDefinition deg_mon (m:mon) : nat :=\n  plusl (map (@snd _ _) (snd m)).\n\nDefinition deg (p:pol) : nat :=\n  maxl (map deg_mon (snd p)).\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/bellantonicook/src/BellantoniCook/MultiPoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7123452812820582}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Functor.\nRequire Import Functor.Functor_Ops.\n\nLocal Open Scope functor_scope.\n\nSection Functor_Properties.\n  Context {C C' : Category} (F : C –≻ C').\n\n  Local Open Scope object_scope.\n  Local Open Scope isomorphism_scope.\n  Local Open Scope morphism_scope.\n    \n  (** A functor is said to be injective if its object map is. *)\n  Definition Injective_Func := ∀ (c c' : Obj), F _o c = F _o c' → c = c'.\n\n  (** A functor is said to be essentially injective if its object map maps\nequal objects to isomorphic objects in the codomain category. *)\n  Definition Essentially_Injective_Func :=\n    ∀ (c c' : Obj), F _o c = F _o c' → c ≃ c'.\n  \n  (** A functor is said to be surjective if its object map is. *)\n  Definition Surjective_Func := ∀ (c : Obj), {c' : Obj | F _o c' = c}.\n\n  (** A functor is said to be essentially surjective if for each object in the\ncodomain category there is an aobject in the domain category that is mapped\nto an aobject isomorphic to it. *)\n  Definition Essentially_Surjective_Func :=\n    ∀ (c : Obj), {c' : Obj & F _o c' ≃ c}.\n\n  (** A functor is said to be faithful if its arrow map is injective. *)\n  Definition Faithful_Func := ∀ (c c' : Obj) (h h' : (c –≻ c')%morphism),\n      F _a h = F _a h' → h = h'.\n\n  (** A functor is said to be full if its arrow map is surjective. *)\n  Definition Full_Func :=\n    ∀ (c1 c2 : Obj) (h' : ((F _o c1) –≻ (F _o c2))%morphism),\n      {h : (c1 –≻ c2)%morphism | F _a h = h'}\n  .\n\n  Local Ltac Inv_FTH :=\n    match goal with\n      [fl : Full_Func |- _] =>\n      progress (\n          repeat\n            match goal with\n              [|- context [(F _a (proj1_sig (fl _ _ ?x)))]] =>\n              rewrite (proj2_sig (fl _ _ x))\n            end\n        )\n    end\n  .\n\n  Local Hint Extern 1 => Inv_FTH.\n\n  Local Hint Extern 1 => rewrite F_compose.\n\n  Local Hint Extern 1 =>\n  match goal with\n    [fth : Faithful_Func |- _ = _ ] => apply fth\n  end\n  .\n\n  Local Obligation Tactic := basic_simpl; auto 6.\n  \n  (** Any fully-faithful functor is essentially surjective. *)\n  Program Definition Fully_Faithful_Essentially_Injective\n          (fth : Faithful_Func) (fl : Full_Func) : Essentially_Injective_Func\n    :=\n      fun c c' eq =>\n        {|\n          iso_morphism :=\n            proj1_sig (\n                fl\n                  _\n                  _\n                  match eq in _ = y return\n                        (_ –≻ y)%morphism\n                  with\n                    eq_refl => id (F _o c)\n                  end\n              );\n          inverse_morphism :=\n            proj1_sig (\n                fl\n                  _\n                  _\n                  match eq in _ = y return\n                        (y –≻ _)%morphism\n                  with\n                    eq_refl => id (F _o c)\n                  end\n              )\n        |}\n  .\n\n  (** Any fully-faithful functor is conservative.\n      A conservative functor is one for which we have to objects of the domain\n      category are isomorphic if their images are ismorphic. *)\n  Program Definition Fully_Faithful_Conservative\n          (fth : Faithful_Func) (fl : Full_Func)\n    : ∀ (c c' : Obj), F _o c ≃ F _o c' → c ≃ c' :=\n    fun c c' I =>\n      {|\n        iso_morphism := proj1_sig (fl _ _ I);\n        inverse_morphism := proj1_sig (fl _ _ (I⁻¹))\n      |}\n  .\n\nEnd Functor_Properties.\n\n(** Functors Preserve Isomorphisms. *)\nSection Functors_Preserve_Isos.\n  Context {C C' : Category} (F : C –≻ C')\n          {a b : C} (I : (a ≃≃ b ::> C)%isomorphism).\n\n  Program Definition Functors_Preserve_Isos : (F _o a ≃ F _o b)%isomorphism :=\n    {|\n      iso_morphism := (F _a I)%morphism;\n      inverse_morphism := (F _a (I⁻¹))%morphism\n    |}.\n\nEnd Functors_Preserve_Isos.\n  \nSection Embedding.\n  Context (C C' : Category).\n\n  (**\n    An embedding is a functor that is fully-faithful. Such a functor is\n    necessarily essentially injective and conservative, i.e.,\n    if F _O c ≃ F _O c' then c ≃ c'.\n   *)\n\n  Record Embedding : Type :=\n    {\n      Emb_Func : C –≻ C';\n\n      Emb_Faithful : Faithful_Func Emb_Func;\n      \n      Emb_Full : Full_Func Emb_Func\n    }.\n\n  Coercion Emb_Func : Embedding >-> Functor.\n\n  Definition Emb_Essent_Inj (E : Embedding) :=\n    Fully_Faithful_Essentially_Injective\n      (Emb_Func E) (Emb_Faithful E) (Emb_Full E).\n  \n  Definition Emb_Conservative (E : Embedding) :=\n    Fully_Faithful_Conservative\n      (Emb_Func E) (Emb_Faithful E) (Emb_Full E).\n\nEnd Embedding.\n\nArguments Emb_Func {_ _} _.\nArguments Emb_Faithful {_ _} _ {_ _} _ _ _.\nArguments Emb_Full {_ _} _ {_ _} _.", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Categories/Functor/Functor_Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7123452765855193}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq path.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** ** Braun trees *)\n\n(** Three Algorithms on Braun Trees - C.\nOkasaki(1997):\n\nFor any given node of a Braun tree, the\nleft subtree is either exactly the same\nsize as the right subtree, or one element\nlarger.\n\nBraun trees always have minimum height,\nand the shape of each Braun tree is\ncompletely determined by its size.\n\nIn return for this rigor, algorithms that\nmanipulate Braun trees are often\nexceptionally simple and elegant, and need\nnot maintain any explicit balance\ninformation.\n *)\n\nSection BinaryTree.\n\nVariable T : Type.\n\nInductive btree : Type :=\n| BTempty\n| BTnode\n    (l : btree)\n    (a : T)\n    (r : btree).\n\nImplicit Type bt : btree.\n\n(** A generic binary tree size algorithm *)\nFixpoint bt_size bt : nat :=\n  if bt is (BTnode l _ r) then\n    (bt_size l +\n     bt_size r).+1\n  else\n    0.\n\nEnd BinaryTree.\n\nArguments BTempty {T}.\nArguments BTnode {T} l a r.\nArguments bt_size {T}.\n\nSection BraunTree.\n\nVariable T : Type.\nImplicit Type brt : btree T.\nFixpoint is_brtree brt : bool :=\n  if brt is (BTnode l _ r) then\n    [&& is_brtree l,\n        is_brtree r &\n        (bt_size l == (bt_size r)) ||\n        (bt_size l == (bt_size r).+1)]\n  else\n    true.\n\nArguments is_brtree : simpl never.\n\n(** As for the size, with Braun trees\n    we can do better! *)\n\nFixpoint brt_diff brt s : nat :=\n  match brt with\n  | BTempty => 0\n  | BTnode l _ r =>\n    if s == 0 then 1\n    else if odd s then brt_diff l (s %/ 2)\n    else brt_diff r (s.-1 %/ 2)\n  end.\n\nFixpoint brt_size brt : nat :=\n  if brt is (BTnode l _ r) then\n    let: sr := brt_size r in\n    (2 * sr + brt_diff l sr).+1\n  else 0.\n\n(** Rewrite multi-rule *)\n(** Exercise *)\nLemma is_brtree_node l x r :\n  is_brtree (BTnode l x r) ->\n  (is_brtree l * is_brtree r) *\n  (bt_size r <= bt_size l) *\n  ((bt_size l == bt_size r) ||\n   (bt_size l == (bt_size r).+1)).\nProof.\nAdmitted.\n\n(** Exercise *)\nLemma bt_size1 (bt : btree T) :\n  bt_size bt = 1 ->\n  exists x,\n    bt = BTnode BTempty x BTempty.\nProof.\nAdmitted.\n\n(** Exercise *)\nLemma brt_diff_correct brt s :\n  is_brtree brt ->\n  (bt_size brt == s) ||\n  (bt_size brt == s.+1) ->\n  brt_diff brt s = bt_size brt - s.\nProof.\nAdmitted.\n\n\n(** The spec of [brt_size] is [bt_size] *)\nLemma brt_size_correct brt :\n  is_brtree brt ->\n  brt_size brt = bt_size brt.\nProof.\nelim: brt => // l _ x r IHr.\nmove=> /is_brtree_node node /=.\nrewrite IHr ?node //.\nrewrite brt_diff_correct ?node //.\nrewrite mulSn mul1n -addnA.\n(* subnKC : forall m n : nat, m <= n -> m + (n - m) = n *)\nby rewrite subnKC ?node // addnC.\nQed.\n\nEnd BraunTree.\n\nArguments is_brtree {T} brt.\nArguments is_brtree_node {T l x r}.\n\n\n\nSection BraunTreeInsert.\n\nVariable T : Type.\nVariable leT : rel T.\nImplicit Types (a e : T) (bt : btree T).\n\nFixpoint br_insert e bt : btree T :=\n  if bt is (BTnode l a r) then\n    if leT e a then\n      BTnode\n        (br_insert a r) e l\n    else\n      BTnode\n        (br_insert e r) a l\n  else\n    BTnode\n      BTempty\n      e\n      BTempty.\n\nLemma br_insert_size e bt :\n  bt_size (br_insert e bt) =\n  (bt_size bt).+1.\nProof.\nAdmitted.\n\nLemma dup {A} : A -> A * A.\nProof. by []. Qed.\n\nLemma br_insert_is_brtree e bt :\n  is_brtree bt ->\n  is_brtree (br_insert e bt).\nProof.\nelim: bt e => // l IHl a r IHr e.\nmove=> /is_brtree_node Br.\nmove=> /=.\ncase: ifP=> [le | gt] /=.\n- rewrite br_insert_size.\n  rewrite IHr ?Br //.\n  case: Br => _; case/orP=> /eqP->.\n  - by rewrite eq_refl orbT.\n  by rewrite eq_refl.\n(** Exercise: remove proof duplication *)\nrewrite br_insert_size.\nrewrite IHr ?Br //.\ncase: Br => _; case/orP=> /eqP->.\n- by rewrite eq_refl orbT.\nby rewrite eq_refl.\nQed.\n\nEnd BraunTreeInsert.\n\n\nSection BraunTreeRemove.\n\nVariable T : Type.\n(** [def] is a default element we have\n    to have since the type system\n    does not prevent us from considering\n    the case of empty tree *)\nVariable (def : T).\nImplicit Types (bt : btree T).\n\nFixpoint br_remove_min bt : T * btree T :=\n  match bt with\n  | BTempty => (def, BTempty)\n  | BTnode BTempty a r => (a, BTempty)\n  | BTnode l a r =>\n      let: (min, l) := br_remove_min l in\n      (min, BTnode r a l)\n  end.\n\nLemma br_remove_min_is_brtree bt :\n  is_brtree bt ->\n  is_brtree (br_remove_min bt).2.\nProof.\nAdmitted.\n\nEnd BraunTreeRemove.\n\n\n(** Packing it all together *)\nModule Sub.\nSection BraunTreeSubType.\n\nVariable T : Type.\n\nInductive brtree :=\n  BrTree (bt : btree T) of is_brtree bt.\n\nCoercion tree_of_brtree (brt : brtree) :=\n  let: BrTree bt _ := brt in bt.\n\nCanonical brtree_subType :=\n  [subType for tree_of_brtree].\n\nEnd BraunTreeSubType.\nEnd Sub.\n\n\n\n(** Another take on Braun trees *)\n\n(** Extrinsic vs intrinsic verification *)\n\nFrom Coq Require Import Extraction Program.\n\nModule BraunTreeIntrinsic.\nSection BraunTreeIntrinsic.\n\nVariable T : Type.\n\nInductive brtree : nat -> Type :=\n| BrTempty : brtree 0\n| BrTnode\n    m (l : brtree m)\n    (a : T)\n    n (r : brtree n)\n    of (m = n \\/ m = n.+1)\n  : brtree (m+n).+1.\n\nDefinition brt_size' {n} (brt : brtree n) :=\n  n.\n\n(** What's the problem with this definition? *)\n\nEnd BraunTreeIntrinsic.\n\nArguments BrTempty {T}.\n\n(** Let's talk about running verified\n    algorithms. *)\n\nExtraction brt_size'.\n\n(**\nval brt_size' : nat -> 'a1 brtree -> nat\n\nlet brt_size' n _ =\n  n\n\nBut we do not want to keep the size\nof the tree at run-time.\n*)\n\n\nSection BraunTree.\nVariable T : Type.\n\nFixpoint brt_slow_size1\n           {n} (brt : brtree T n)\n  : nat :=\n  if brt is (BrTnode _ l _ _ r _) then\n    (brt_slow_size1 l +\n     brt_slow_size1 r).+1\n  else\n    0.\n\nFixpoint brt_slow_size2\n           {n} (brt : brtree T n)\n  : {s | s = n}.\ncase: brt.\n- by exists 0.\nmove=> m' l x n' r pf.\nexists (sval (brt_slow_size2 _ l) +\n        sval (brt_slow_size2 _ r)).+1.\ncase: (brt_slow_size2 _ _).\ncase: (brt_slow_size2 _ _).\nmove=>/=.\nby move=> ? -> ? ->.\nDefined.\n\nPrint brt_slow_size2.\n\n\nFail Program Fixpoint brt_slow_size3\n           {n} (brt : brtree T n)\n  : {s | s = n} :=\n  if brt is (BrTnode _ l _ _ r _) then\n      ((brt_slow_size3 l) +\n       (brt_slow_size3 r)).+1\n  else\n    0.\n\nVariable leT : rel T.\n\nFail Fixpoint br_insert {n} (e : T)\n         (brt : brtree T n)\n  : brtree T n.+1 :=\n  if brt is (BrTnode _ l a _ r _) then\n    if leT e a then\n      BrTnode\n        (br_insert a r) e l\n    else\n      BrTnode\n        (br_insert e r) a l\n  else\n    BrTnode\n      BrTempty\n      e\n      BrTempty\n      (or_introl erefl).\n\n(** But we can know express more\n    in types, compare this to\n    bt_remove_min *)\nFixpoint brt_remove_min {n}\n         (bt : brtree T n.+1) :\n  T * brtree T n.\nAdmitted.\n\nEnd BraunTree.\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/lectures/lecture11.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8267118004748678, "lm_q1q2_score": 0.7122438013575633}}
{"text": "(* two_by_two_matrices.v *)\n(* dIFP 2014-2015, Q1 *)\n(* Teacher: Olivier Danvy <danvy@cs.au.dk> *)\n\n(* Student name: ... *)\n(* Student number: ... *)\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/dProgSprog12/Supplementary-material/more-about-induction-proofs.pdf\n*)\n\nRequire Import Arith.\nRequire Import unfold_tactic.\n\nLemma unfold_plus_bc :\n  forall j : nat,\n    plus 0 j = j.\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_plus_ic :\n  forall i' j : nat,\n    plus (S i') j = S (plus i' j).\nProof.\n  unfold_tactic plus.\nQed.\n\nProposition plus_1_S :\n  forall n : nat,\n    S n = plus 1 n.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n    rewrite -> (plus_0_r 1).\n    reflexivity.\n    \n    rewrite -> (unfold_plus_ic).\n    rewrite -> (plus_0_l (S n')).\n    reflexivity.\nQed.\n\n\n\nInductive m22 : Type :=\n| M22 : nat -> nat -> nat -> nat -> m22.\n\nDefinition matr1 := (M22 1 2 3 4).\nDefinition matr2 := (M22 2 3 4 5).\n\nDefinition nine (m1 m2 : m22) : m22 :=\n  match m1 with\n    | (M22 x1 x2 x3 x4) => match m2 with\n        | (M22 y1 y2 y3 y4) => (M22 (x1*y1 + x2*y3) (x1*y2 + x2*y4) (x3*y1 + x4*y3) (x3*y2 + x4*y4))\n     end\n  end.\n\nDefinition ninetwo (m1 m2 : m22) : m22 :=\n  match m1,m2 with\n      | (M22 x1 x2 x3 x4), (M22 y1 y2 y3 y4) => M22 (x1*y1 + x2*y3) (x1*y2 + x2*y4) (x3*y1 + x4*y3) (x3*y2 + x4*y4)\n  end.\n\nLemma matrix_helper : \n  forall (x1 x2 x3 x4 y1 y2 y3 y4 : nat),\n    nine (M22 x1 x2 x3 x4) (M22 y1 y2 y3 y4) = M22 (x1*y1 + x2*y3) (x1*y2 + x2*y4) (x3*y1 + x4*y3) (x3*y2 + x4*y4).\nProof.\n  intros x1 x2 x3 x4 y1 y2 y3 y4.\n  unfold nine.\n  reflexivity.\nQed.\n\nCompute ninetwo matr1 matr2.\n\nCompute nine matr1 matr2.\n\n\n\nDefinition identity : m22 := (M22 1 0 0 1).\n\nCompute ninetwo identity identity.\n\nFixpoint exp (m : m22) (n : nat) : m22 :=\n  match n with\n    | 0 => identity\n    | S n' => nine (exp m n') m\nend.\n\nLemma unfold_exp_base_case : \n  forall m : m22,\n    exp m 0 = identity.\nProof.\n  unfold_tactic exp.\nQed.\n\nLemma unfold_exp_induction_case : \n  forall (m : m22) (n : nat),\n    exp m (S n) = nine (exp m n) m.\nProof.\n  unfold_tactic exp.\nQed.\n\nCompute exp identity 4.\n\n\nLemma matrix_comm_help :\n  forall n1 n2 n3 n4 n5 n6 n7 n8 : nat,\n    n1 * (n2 * n3 + n4 * n5) + n6 * (n7 * n3 + n8 * n5) = (n1 * n2 + n6 * n7) * n3 + (n1 * n4 + n6 * n8) * n5.\nProof.\n  intros n1 n2 n3 n4 n5 n6 n7 n8.\n  ring.\nQed.\n\nLemma matrices_are_communative : \n  forall (m1 m2 m3 : m22),\n    nine m1 (nine m2 m3) = nine (nine m1 m2) m3.\nProof.\n  intros m1 m2 m3.\n  induction m1,m2,m3 as [ ].\n  rewrite ->4 matrix_helper.\n  rewrite -> (matrix_comm_help n n3 n7 n4 n9 n0 n5 n6).\n  rewrite -> (matrix_comm_help n n3 n8 n4 n10 n0 n5 n6).\n  rewrite -> (matrix_comm_help n1 n3 n7 n4 n9 n2 n5 n6).\n  rewrite -> (matrix_comm_help n1 n3 n8 n4 n10 n2 n5 n6).\n  reflexivity.\nQed.\n\n\nLemma identity_matrix_is_netrual_l :\n  forall m : m22,\n    nine identity m = m.\nProof.\n  intros [x1 x2 x3 x4].\n  unfold identity.\n  unfold nine.\n  rewrite ->4 (mult_1_l).\n  rewrite ->4 (mult_0_l).\n  rewrite ->2 (plus_0_r).\n  rewrite ->2 (plus_0_l).\n  reflexivity.\nQed.\n\nLemma identity_matrix_is_netrual_r :\n  forall m : m22,\n    nine m identity = m.\nProof.\n  intro m.\n  induction m as [ ].\n  unfold identity.\n  unfold nine.\n  rewrite ->4 (mult_1_r).\n  rewrite ->4 (mult_0_r).\n  rewrite ->2 (plus_0_l).\n  rewrite ->2 (plus_0_r).\n  reflexivity.\nQed.\n\nLemma proposition_14 : \n  forall (n : nat),\n    exp (M22 1 1 0 1) n = (M22 1 n 0 1).\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  rewrite -> (unfold_exp_base_case).\n  unfold identity.\n  reflexivity.\n\n  rewrite -> (unfold_exp_induction_case).\n  rewrite -> (IHn').\n  rewrite -> (matrix_helper).\n  rewrite ->3 (mult_1_r).\n  rewrite ->2 (mult_0_r).\n  rewrite ->2 (plus_0_l).\n  rewrite -> (plus_0_r).\n  rewrite -> (plus_1_S n').\n  reflexivity.\nQed.\n\nFixpoint exp_alt (m : m22) (n : nat) : m22 :=\n  match n with\n    | 0 => identity\n    | S n' => nine m (exp_alt m n')\nend.\n\nLemma unfold_exp_alt_base_case : \n  forall m : m22,\n    exp_alt m 0 = identity.\nProof.\n  unfold_tactic exp_alt.\nQed.\n\nLemma unfold_exp_alt_induction_case : \n  forall (m : m22) (n : nat),\n    exp_alt m (S n) = nine m (exp_alt m n).\nProof.\n  unfold_tactic exp_alt.\nQed.\n\nLemma proposition_14_alt : \n  forall (n : nat),\n    exp_alt (M22 1 1 0 1) n = (M22 1 n 0 1).\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n  rewrite -> (unfold_exp_alt_base_case).\n  unfold identity.\n  reflexivity.\n\n  rewrite -> (unfold_exp_alt_induction_case).\n  rewrite -> (IHn').\n  rewrite -> (matrix_helper).\n  rewrite ->3 (mult_1_l).\n  rewrite ->2 (mult_0_l).\n  rewrite ->2 (plus_0_l).\n  rewrite -> (plus_0_r).\n  rewrite -> (plus_1_S n').\n  rewrite -> (plus_comm n' 1).\n  reflexivity.\nQed.\n\nLemma proposition_29 :\n  forall (m : m22) (n : nat),\n    nine m (exp m n) = nine (exp m n) m.\nProof.\n  intros m n.\n  induction n as [ | n' IHn'].\n  \n  rewrite -> (unfold_exp_base_case).\n  rewrite -> (identity_matrix_is_netrual_r).\n  rewrite -> (identity_matrix_is_netrual_l).\n  reflexivity.\n\n  (* We want both sides *)\n  rewrite -> (unfold_exp_induction_case).\n  rewrite -> (matrices_are_communative).\n  rewrite -> (IHn').\n  reflexivity.\nQed.\n\nLemma proposition_31 : \n  forall (m : m22) (n : nat),\n    nine m (exp_alt m n) = nine (exp_alt m n) m.\nProof.\n  intros m n.\n  induction n as [ | n' IHn'].\n  rewrite -> (unfold_exp_alt_base_case).\n  rewrite -> (identity_matrix_is_netrual_l).\n  rewrite -> (identity_matrix_is_netrual_r).\n  reflexivity.\n\n  (* Again, both sides *)\n  rewrite -> (unfold_exp_alt_induction_case).\n\n  (* Sjov egenskab - her er det baglæns *)\n  rewrite <- (matrices_are_communative).\n  rewrite <- (IHn').\n  reflexivity.\nQed.\n  \nLemma coro32 : \n  forall (m : m22) (n : nat),\n    exp m n = exp_alt m n.\nProof.\n  intros m n.\n  \n  induction n as [ | n' IHn'].\n  rewrite -> (unfold_exp_alt_base_case).\n  rewrite -> (unfold_exp_base_case).\n  reflexivity.\n\n  rewrite -> (unfold_exp_alt_induction_case).\n  rewrite -> (unfold_exp_induction_case).\n  rewrite -> (IHn').\n  symmetry.\n  apply proposition_31.\nQed.\n\nLemma proposition_33_34 :\n  forall n : nat,\n    exp (M22 1 0 1 1) n = (M22 1 0 n 1).\nProof.\n  intro n.\n\n  induction n as [ | n' IHn'].\n  rewrite -> (unfold_exp_base_case).\n  unfold identity.\n  reflexivity.\n\n  rewrite -> (unfold_exp_induction_case).\n  rewrite -> (IHn').\n  rewrite -> (matrix_helper).\n  rewrite -> (mult_0_l).\n  rewrite ->2 (mult_0_r).\n  rewrite ->2 (mult_1_r).\n  rewrite ->2 (plus_0_r).\n  rewrite -> (plus_0_l).\n  rewrite -> (plus_comm n' 1).\n  rewrite -> (plus_1_S n').\n  reflexivity.\nQed.\n\nDefinition transpose(m : m22) : m22 :=\n  match m with\n    | (M22 x1 x2 x3 x4) => (M22 x1 x3 x2 x4)\n  end.\n\nLemma transpose_is_involutive : \n  forall m : m22,\n    transpose(transpose(m)) = m.\nProof.\n  intro m.\n  induction m as [ ].\n  unfold transpose.\n  reflexivity.\nQed.\n\nLemma transpose_is_something :\n  forall (m n : m22),\n    transpose(nine m n) = nine (transpose n) (transpose m).\nProof.\n\n  intros m n.\n  induction m,n as [ ].\n  unfold nine.\n  unfold transpose.\n  rewrite -> (mult_comm n1 n5).\n  rewrite -> (mult_comm).\n  rewrite -> (mult_comm n2 n).\n  rewrite -> (mult_comm n3 n5).\n  rewrite -> (mult_comm n0 n4).\n  rewrite -> (mult_comm n1 n6).\n  rewrite -> (mult_comm n2 n4).\n  rewrite -> (mult_comm n3 n6).\n  reflexivity.\nQed.\n\nLemma proposition_38_transpose_and_exp_commute :\n  forall (m : m22) (n : nat),\n    transpose(exp m n) = exp (transpose m) n.\nProof.\n  intros m n.\n  induction m as [].\n  induction n as [ | n' IHn'].\n  rewrite -> (unfold_exp_base_case).\n  rewrite -> (unfold_exp_base_case).\n  unfold identity.\n  unfold transpose.\n  reflexivity.\n\n  rewrite ->2 (unfold_exp_induction_case).\n  rewrite <- (IHn').\n  rewrite <- (transpose_is_something).\n  rewrite -> (proposition_29).\n  reflexivity.\nQed.\n\n\nLemma proposition_40 : \n  forall (n : nat),\n    exp (transpose (M22 1 1 0 1)) n = transpose (M22 1 n 0 1).\nProof.\n  intro n.\n  rewrite <- (proposition_38_transpose_and_exp_commute).\n  rewrite -> (proposition_14).\n  reflexivity.\nQed.\n\n\n(* You are asked to:\n\n   * implement Definitions 9, 11, and 13, x\n\n   * prove Properties 10 and 12, x\n\n   * prove Proposition 14, x\n\n   * implement Definition 27, x\n\n   * solve Exercise 28, x\n\n   * prove Proposition 29, x\n\n   * solve Exercise 31, x\n\n   * implement Corollary 32,\n\n   * solve Exercise 34, x\n\n   * implement Definition 35, x\n\n   * prove Property 36, x\n\n   * prove Lemma 37, x\n\n   * prove Proposition 38, and to x\n\n   * solve Exercise 40. x\n*)\n\n(*********** *)\n\nDefinition matf := (M22 1 1 1 0).\n\nCompute exp matf 0. (* 1 0 0 1 *)\nCompute exp matf 1. (* 1 1 1 0 *)\nCompute exp matf 2. (* 2 1 1 1 *)\nCompute exp matf 3. (* 3 2 2 1 *)\nCompute exp matf 4. (* 5 3 3 2 *)\nCompute exp matf 5. (* 8 5 5 3 *)\nCompute exp matf 6. (* 13 8 8 5 *)\nCompute exp matf 7. (* 21 13 13 8 *)\nCompute exp matf 8. (* 34 21 21 13 *)\n\n(* For the over-achievers:\n\n   * solve Exercise 25.\n*)\n\n(* ********** *)\n\n(* end of two_by_two_matrices.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/difp/term-projects/two_by_two_matrices.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7122437881228284}}
{"text": "(* Exercise 5.2 *)\n(* Using tactics, redo the proofs of Exercise 4.5 *)\nTheorem all_perm' : forall (A : Type) (P : A -> A -> Prop),\n    (forall x y : A, P x y)\n    -> forall x y : A, P y x.\nProof.\n  intros A P H x y.\n  apply H.\nQed.\n\nTheorem resolution : forall (A : Type) (P Q R S : A -> Prop),\n    (forall a : A, Q a -> R a -> S a)\n    -> (forall b : A, P b -> Q b)\n    -> (forall c : A, P c -> R c -> S c).\nProof.\n  intros A P Q R S H H0 c pc rc.\n  apply H.\n  apply H0.\n  assumption.\n  assumption.\nQed.", "meta": {"author": "aymanosman", "repo": "coq-art-exercises", "sha": "ff7e2aba35a5094d366be5b9f55dfdd13d38cd48", "save_path": "github-repos/coq/aymanosman-coq-art-exercises", "path": "github-repos/coq/aymanosman-coq-art-exercises/coq-art-exercises-ff7e2aba35a5094d366be5b9f55dfdd13d38cd48/05_everyday_logic/exercise_02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.712210515270794}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n(* A generic one-time pad that can be reused in other proofs. Also included are specializations for bit vectors and finite cyclic groups. *)\n\nSet Implicit Arguments.\n\nRequire Import FCF.FCF.\n\nDefinition D := evalDist.\nDefinition dist_iso := evalDist_iso.\n\nLtac r_ident_r :=\n  symmetry;\n  rewrite <- evalDist_right_ident;\n  symmetry.\n\nLtac xorTac_once :=\n  match goal with\n    | [|- context[?x xor (?x xor ?x0)] ]=> rewrite <- BVxor_assoc; rewrite BVxor_same_id; rewrite BVxor_id_l\n    | [|- context[(?x xor ?x0) xor ?x] ]=> rewrite <- BVxor_comm\n  end.\n\nLtac xorTac := repeat xorTac_once;\n              simpl; try reflexivity; try eapply in_getAllBvectors.\n\n(*\n(* Simple example used for illustration *)\nSection OTP.\n  Variable c : nat.\n  Definition OTP (x : Bvector c) : Comp (Bvector c) \n    := p <-$ {0, 1}^c; ret (BVxor c p x).\n\n  Theorem OTP_eq_Rnd: \n    forall (x y : Bvector c),\n      D (OTP x) y == D ({0, 1}^c) y.\n\n    intuition.\n    unfold OTP.\n    r_ident_r.\n    eapply (dist_iso (BVxor c x) (BVxor c x)); \n      intuition; xorTac.\n  Qed.\n\nEnd OTP.\n*)\n\n(* The actual argument is more general (and more complex) *)\nSection OTP.\n\n  Variable T : Set.\n  Hypothesis T_EqDec : EqDec T.\n  Variable RndT : Comp T.\n  Variable T_op : T -> T -> T.\n  Hypothesis op_assoc : forall x y z, T_op (T_op x y) z = T_op x (T_op y z).\n  Variable T_inverse : T -> T. \n  Variable T_ident : T.\n  Hypothesis inverse_l_ident : forall x, T_op (T_inverse x) x = T_ident.\n  Hypothesis inverse_r_ident : forall x, T_op x (T_inverse x) = T_ident.\n  Hypothesis ident_l : forall x, T_op T_ident x = x.\n  Hypothesis ident_r : forall x, T_op x T_ident = x.\n  Hypothesis RndT_uniform : forall x y, comp_spec (fun a b => a = x <-> b = y) RndT RndT.\n\n  Theorem all_in_support : \n    forall y, In y (getSupport RndT) ->\n    forall x, In x (getSupport RndT).\n\n    intuition.\n    eapply getSupport_In_evalDist.\n    intuition.\n    eapply getSupport_In_evalDist.\n    eapply H.\n    rewrite <- H0.\n    eapply comp_spec_impl_eq.\n    trivial.\n    \n  Qed.\n \n  Theorem OTP_inf_th_sec_l : \n    forall (x : T),\n      comp_spec eq RndT (r <-$ RndT; ret (T_op x r)).\n\n    intros.\n\n    eapply (@comp_spec_eq_trans_l _ _ _ _ RndT (x <-$ RndT; ret x)).\n    eapply comp_spec_eq_symm.\n    eapply comp_spec_right_ident.\n  \n    eapply comp_spec_seq.\n    trivial.\n    trivial.\n    \n    eapply comp_spec_symm.\n    eapply (comp_spec_iso (T_op x) (T_op (T_inverse x))); intuition.\n    rewrite <- op_assoc.\n    rewrite inverse_r_ident.\n    eauto.\n    rewrite <- op_assoc.\n    rewrite inverse_l_ident.\n    eauto.\n\n    eapply all_in_support; eauto. \n\n    intuition.\n    subst.\n    eapply comp_spec_eq_refl.\n    \n  Qed.\n\n  Theorem OTP_inf_th_sec_r : \n    forall (x : T),\n      comp_spec eq RndT (r <-$ RndT; ret (T_op r x)).\n\n    intros.\n\n    eapply (@comp_spec_eq_trans_l _ _ _ _ RndT (x <-$ RndT; ret x)).\n    eapply comp_spec_eq_symm.\n    eapply comp_spec_right_ident.\n\n    eapply comp_spec_seq.\n    trivial.\n    trivial.\n \n    eapply comp_spec_symm.\n    eapply (comp_spec_iso (fun b => T_op b x) (fun b => T_op b (T_inverse x))); intuition.\n    rewrite op_assoc.\n    rewrite inverse_l_ident.\n    eauto.\n    rewrite op_assoc.\n    rewrite inverse_r_ident.\n    eauto.\n\n    eapply all_in_support; eauto.\n\n    intuition.\n    subst.\n    eapply comp_spec_eq_refl.\n\n  Qed.\n\nEnd OTP.\n\n(* OTP for bitstrings with xor *)\nSection xor_OTP.\n\n  Variable n : nat.\n\n  Theorem xor_OTP: \n    forall (x : Bvector n),\n      comp_spec eq (Rnd n) (r <-$ Rnd n; ret (BVxor n x r)).\n\n    eapply OTP_inf_th_sec_l; intuition.\n    eapply BVxor_assoc.\n    eapply BVxor_same_id.\n    eapply BVxor_same_id.\n    eapply BVxor_id_l.\n\n    eapply comp_spec_rnd.\n   \n  Qed.\n\n  Theorem xor_OTP_eq: \n    forall (x y : Bvector n),\n       evalDist (r <-$ Rnd n; ret (BVxor n x r)) y ==\n       evalDist (Rnd n) y.\n\n    intuition.\n    symmetry.\n    eapply comp_spec_eq_impl_eq.\n    eapply xor_OTP.\n\n  Qed.\n\n\nEnd xor_OTP.\n\n\n(* OTP for cyclic groups *)\nRequire Import FCF.RndNat.\nRequire Import FCF.RndGrpElem.\n\nLocal Open Scope group_scope.\n\nSection Group_OTP.\n\n  Context`{FCG : FiniteCyclicGroup}.\n\n  Hypothesis GroupElement_EqDec : EqDec GroupElement.\n \n  Theorem group_OTP_l : \n    forall (x : GroupElement),\n      comp_spec eq (RndG) (r <-$ RndG; ret (groupOp x r)).\n\n    eapply OTP_inf_th_sec_l; intuition.\n    \n    apply associativity.\n    eapply left_inverse.\n    eapply right_inverse.\n    eapply left_identity.\n   \n    eapply RndGrpElem_spec.\n  Qed.\n\n  Theorem group_OTP_r : \n    forall (x : GroupElement),\n      comp_spec eq (RndG) (r <-$ RndG; ret (groupOp r x)).\n\n    eapply OTP_inf_th_sec_r; intuition.\n    \n    apply associativity.\n    eapply left_inverse.\n    eapply right_inverse.\n    eapply right_identity.\n    eapply RndGrpElem_spec.\n  Qed.\n\nEnd Group_OTP.\n\n#[export] Hint Resolve RndGrpElem_wf : wftac.\n", "meta": {"author": "adampetcher", "repo": "fcf", "sha": "10a39a091eb695daba8175cb59bf481dd85d8ce2", "save_path": "github-repos/coq/adampetcher-fcf", "path": "github-repos/coq/adampetcher-fcf/fcf-10a39a091eb695daba8175cb59bf481dd85d8ce2/src/FCF/OTP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7122104955101346}}
{"text": "Require Import Omega Arith.\nImport Nat.\n\nDefinition sq n := n * n.\n\n(* Some useful lemmas from the standard library. *)\nCheck mul_sub_distr_l: forall n m p, p * (n - m) = p * n - p * m.\nCheck mul_add_distr_r: forall n m p, (n + m) * p = n * p + m * p.\nCheck mul_comm: forall n m, n * m = m * n.\n\nLemma difference_of_squares:\n  forall a b, sq a - sq b = (a + b) * (a - b).\nProof.\n\nQed.\n", "meta": {"author": "mbrcknl", "repo": "coq-fight-2017", "sha": "7f5ec82d47b79769d3b92ae7f0d8cb8e45891aba", "save_path": "github-repos/coq/mbrcknl-coq-fight-2017", "path": "github-repos/coq/mbrcknl-coq-fight-2017/coq-fight-2017-7f5ec82d47b79769d3b92ae7f0d8cb8e45891aba/diff-square.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7121857993618638}}
{"text": "(*** Constant list ***)\n\nRequire Import Arith.\nRequire Import List.\nRequire Import Omega.\nRequire Import Ott.ott_list_support.\nRequire Import Ott.ott_list_base.\nRequire Import Ott.ott_list_nth.\nImport List_lib_Arith.\n\n\n\nSection Lists.\n\nVariables A B C : Type.\nImplicit Types x : A.\nImplicit Types y : B.\nImplicit Types z : C.\nImplicit Types xs l : list A.\nImplicit Types ys : list B.\nImplicit Types zs : list C.\nImplicit Types f : A -> B.\nImplicit Types g : B -> C.\nImplicit Types m n : nat.\nSet Implicit Arguments.\n\nFixpoint repeat n x {struct n} : list A :=\n  match n with\n    | 0 => nil\n    | S m => x :: repeat m x\n  end.\n\nLemma repeat_length : forall n x, length (repeat n x) = n.\nProof.\n  induction n; intros. reflexivity. simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma repeat_app :\n  forall n m x, repeat (n + m) x = repeat n x ++ repeat m x.\nProof.\n  induction n; simpl; intros. reflexivity. rewrite IHn. reflexivity.\nQed.\n\nLemma repeat_S : forall n x, repeat (S n) x = repeat n x ++ x::nil.\nProof.\n  intros. replace (S n) with (n+1). 2: omega.\n  rewrite repeat_app. reflexivity.\nQed.\n\nLemma nth_error_repeat :\n  forall m n x,\n    nth_error (repeat n x) m = if le_lt_dec n m then error else value x.\nProof.\n  induction m; destruct n; intros; try reflexivity.\n  simpl repeat. simpl nth_error. rewrite IHm.\n  symmetry. apply le_lt_dec_S.\nQed.\n\nLemma nth_repeat :\n  forall m n x,\n    nth m (repeat n x) x = x.\nProof.\n  induction m; destruct n; intros; try reflexivity.\n  simpl. rewrite IHm. reflexivity.\nQed.\n\nLemma nth_safe_repeat :\n  forall m n x H,\n    nth_safe (repeat n x) m H = x.\nProof.\n  intros. assert (value (nth_safe (repeat n x) m H) = value x).\n  rewrite nth_safe_eq_nth_error. rewrite nth_error_repeat.\n  rewrite repeat_length in H.\n  destruct (le_lt_dec n m). elimtype False; omega. reflexivity.\n  injection H0. tauto.\nQed.\n\nEnd Lists.\n\n\n\nHint Rewrite repeat_length repeat_app repeat_S : lists.\nHint Rewrite nth_error_repeat nth_repeat nth_safe_repeat : lists.\n", "meta": {"author": "goldfirere", "repo": "ott-tutorial", "sha": "af68e617e7b3ff007a520eecbc2840812f250806", "save_path": "github-repos/coq/goldfirere-ott-tutorial", "path": "github-repos/coq/goldfirere-ott-tutorial/ott-tutorial-af68e617e7b3ff007a520eecbc2840812f250806/stlc4/ott-coq-files/ott_list_repeat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7121589374892039}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.lemma_congruencesymmetric.\nRequire Import ProofCheckingEuclid.lemma_congruencetransitive.\nRequire Import ProofCheckingEuclid.lemma_localextension.\nRequire Import ProofCheckingEuclid.proposition_02.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_extension_eq_B_P :\n\tforall A B P Q,\n\tneq A B ->\n\tneq P Q ->\n\teq B P ->\n\texists X, BetS A B X /\\ Cong B X P Q.\nProof.\n\tintros A B P Q.\n\tintros neq_A_B.\n\tintros neq_P_Q.\n\tintros eq_B_P.\n\n\tassert (neq B Q) as neq_B_Q by (rewrite eq_B_P; exact neq_P_Q).\n\n\tpose proof (lemma_localextension _ _ _ neq_A_B neq_B_Q) as (X & BetS_A_B_X & Cong_BX_BQ).\n\n\tassert (Cong B X P Q) as Cong_BX_PQ by (rewrite <- eq_B_P; exact Cong_BX_BQ).\n\n\texists X.\n\tsplit.\n\texact BetS_A_B_X.\n\texact Cong_BX_PQ.\nQed.\n\nLemma lemma_extension_neq_B_P :\n\tforall A B P Q,\n\tneq A B ->\n\tneq P Q ->\n\tneq B P ->\n\texists X, BetS A B X /\\ Cong B X P Q.\nProof.\n\tintros A B P Q.\n\tintros neq_A_B.\n\tintros neq_P_Q.\n\tintros neq_B_P.\n\n\tpose proof (proposition_02 _ _ _ neq_B_P neq_P_Q) as (D & Cong_BD_PQ).\n\tpose proof (lemma_congruencesymmetric _ _ _ _ Cong_BD_PQ) as Cong_PQ_BD.\n\tpose proof (axiom_nocollapse _ _ _ _ neq_P_Q Cong_PQ_BD) as neq_B_D.\n\n\tpose proof (lemma_localextension _ _ _ neq_A_B neq_B_D) as (X & BetS_A_B_X & Cong_BX_BD).\n\tpose proof (lemma_congruencetransitive _ _ _ _ _ _ Cong_BX_BD Cong_BD_PQ) as Cong_BX_PQ.\n\n\texists X.\n\tsplit.\n\texact BetS_A_B_X.\n\texact Cong_BX_PQ.\nQed.\n\nLemma lemma_extension :\n\tforall A B P Q,\n\tneq A B ->\n\tneq P Q ->\n\texists X, BetS A B X /\\ Cong B X P Q.\nProof.\n\tintros A B P Q.\n\tintros neq_A_B.\n\tintros neq_P_Q.\n\n\tassert (eq B P \\/ neq B P) as eq_B_P_or_neq_B_P by (apply Classical_Prop.classic).\n\tdestruct eq_B_P_or_neq_B_P as [eq_B_P | neq_B_P].\n\t{\n\t\tpose proof (\n\t\t\tlemma_extension_eq_B_P _ _ _ _ neq_A_B neq_P_Q eq_B_P\n\t\t) as (X & BetS_A_B_X & Cong_BX_PQ).\n\n\t\texists X.\n\t\tsplit.\n\t\texact BetS_A_B_X.\n\t\texact Cong_BX_PQ.\n\t}\n\t{\n\t\tpose proof (\n\t\t\tlemma_extension_neq_B_P _ _ _ _ neq_A_B neq_P_Q neq_B_P\n\t\t) as (X & BetS_A_B_X & Cong_BX_PQ).\n\n\t\texists X.\n\t\tsplit.\n\t\texact BetS_A_B_X.\n\t\texact Cong_BX_PQ.\n\t}\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_extension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7121360565223519}}
{"text": "(* --------------------------------------------------------------------\n * Copyright (c) - 2006--2012 - IMDEA Software Institute\n * Copyright (c) - 2006--2012 - Inria\n * Copyright (c) - 2006--2012 - Microsoft Coprporation\n *\n * Distributed under the terms of the CeCILL-B-V1 license\n * -------------------------------------------------------------------- *)\n\n\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Permutation.v                        \n                                                                     \n    Defintion and properties of permutations                         \n   **********************************************************************)\nRequire Export List.\nRequire Export ListAux.\n \nSection permutation.\nVariable A : Type.\n\n(************************************** \n   Definition of permutations as sequences of adjacent transpositions\n **************************************)\n \nInductive permutation : list A -> list A -> Prop :=\n  | permutation_nil : permutation nil nil\n  | permutation_skip :\n      forall (a : A) (l1 l2 : list A),\n      permutation l2 l1 -> permutation (a :: l2) (a :: l1)\n  | permutation_swap :\n      forall (a b : A) (l : list A), permutation (a :: b :: l) (b :: a :: l)\n  | permutation_trans :\n      forall l1 l2 l3 : list A,\n      permutation l1 l2 -> permutation l2 l3 -> permutation l1 l3.\nHint Constructors permutation.\n\n(************************************** \n   Reflexivity\n **************************************)\n \nTheorem permutation_refl : forall l : list A, permutation l l.\nsimple induction l.\napply permutation_nil.\nintros a l1 H.\napply permutation_skip with (1 := H).\nQed.\nHint Resolve permutation_refl.\n\n(************************************** \n   Symmetry\n   **************************************)\n \nTheorem permutation_sym :\n forall l m : list A, permutation l m -> permutation m l.\nintros l1 l2 H'; elim H'.\napply permutation_nil.\nintros a l1' l2' H1 H2.\napply permutation_skip with (1 := H2).\nintros a b l1'.\napply permutation_swap.\nintros l1' l2' l3' H1 H2 H3 H4.\napply permutation_trans with (1 := H4) (2 := H2).\nQed.\n\n(************************************** \n   Compatibility with list length\n   **************************************)\n \nTheorem permutation_length :\n forall l m : list A, permutation l m -> length l = length m.\nintros l m H'; elim H'; simpl in |- *; auto.\nintros l1 l2 l3 H'0 H'1 H'2 H'3.\nrewrite <- H'3; auto.\nQed.\n\n(************************************** \n   A permutation of the nil list is the nil list\n   **************************************)\n \nTheorem permutation_nil_inv : forall l : list A, permutation l nil -> l = nil.\nintros l H; generalize (permutation_length _ _ H); case l; simpl in |- *;\n auto.\nintros; discriminate.\nQed.\n \n(************************************** \n   A permutation of the singleton list is the singleton list\n   **************************************)\n \nLet permutation_one_inv_aux :\n  forall l1 l2 : list A,\n  permutation l1 l2 -> forall a : A, l1 = a :: nil -> l2 = a :: nil.\nintros l1 l2 H; elim H; clear H l1 l2; auto.\nintros a l3 l4 H0 H1 b H2.\neq_tac.\ninjection H2; auto.\napply permutation_nil_inv; auto.\ninjection H2; intros H3 H4; rewrite <- H3; auto.\napply permutation_sym; auto.\nintros; discriminate.\nQed.\n\nTheorem permutation_one_inv :\n forall (a : A) (l : list A), permutation (a :: nil) l -> l = a :: nil.\nintros a l H; apply permutation_one_inv_aux with (l1 := a :: nil); auto.\nQed.\n\n(************************************** \n   Compatibility with the belonging\n   **************************************)\n \nTheorem permutation_in :\n forall (a : A) (l m : list A), permutation l m -> In a l -> In a m.\nintros a l m H; elim H; simpl in |- *; auto; intuition.\nQed.\n\n(************************************** \n   Compatibility with the append function\n   **************************************)\n \nTheorem permutation_app_comp :\n forall l1 l2 l3 l4,\n permutation l1 l2 -> permutation l3 l4 -> permutation (l1 ++ l3) (l2 ++ l4).\nintros l1 l2 l3 l4 H1; generalize l3 l4; elim H1; clear H1 l1 l2 l3 l4;\n simpl in |- *; auto.\nintros a b l l3 l4 H.\ncut (permutation (l ++ l3) (l ++ l4)); auto.\nintros; apply permutation_trans with (a :: b :: l ++ l4); auto.\nelim l; simpl in |- *; auto.\nintros l1 l2 l3 H H0 H1 H2 l4 l5 H3.\napply permutation_trans with (l2 ++ l4); auto.\nQed.\nHint Resolve permutation_app_comp.\n\n(************************************** \n   Swap two sublists\n   **************************************)\n \nTheorem permutation_app_swap :\n forall l1 l2, permutation (l1 ++ l2) (l2 ++ l1).\nintros l1; elim l1; auto.\nintros; rewrite <- app_nil_end; auto.\nintros a l H l2.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\napply permutation_trans with (l ++ l2 ++ a :: nil); auto.\napply permutation_trans with (((a :: nil) ++ l2) ++ l); auto.\nsimpl in |- *; auto.\napply permutation_trans with (l ++ (a :: nil) ++ l2); auto.\napply permutation_sym; auto.\nreplace (l2 ++ a :: l) with ((l2 ++ a :: nil) ++ l).\napply permutation_app_comp; auto.\nelim l2; simpl in |- *; auto.\nintros a0 l0 H0.\napply permutation_trans with (a0 :: a :: l0); auto.\napply (app_ass l2 (a :: nil) l).\napply (app_ass l2 (a :: nil) l).\nQed.\n\n(************************************** \n   A transposition is a permutation\n   **************************************)\n \nTheorem permutation_transposition :\n forall a b l1 l2 l3,\n permutation (l1 ++ a :: l2 ++ b :: l3) (l1 ++ b :: l2 ++ a :: l3).\nintros a b l1 l2 l3.\napply permutation_app_comp; auto.\nchange\n  (permutation ((a :: nil) ++ l2 ++ (b :: nil) ++ l3)\n     ((b :: nil) ++ l2 ++ (a :: nil) ++ l3)) in |- *.\nrepeat rewrite <- app_ass.\napply permutation_app_comp; auto.\napply permutation_trans with ((b :: nil) ++ (a :: nil) ++ l2); auto.\napply permutation_app_swap; auto.\nrepeat rewrite app_ass.\napply permutation_app_comp; auto.\napply permutation_app_swap; auto.\nQed.\n\n(************************************** \n   An element of a list can be put on top of the list to get a permutation\n   **************************************)\n \nTheorem in_permutation_ex :\n forall a l, In a l -> exists l1 : list A, permutation (a :: l1) l.\nintros a l; elim l; simpl in |- *; auto.\nintros H; case H; auto.\nintros a0 l0 H [H0| H0].\nexists l0; rewrite H0; auto.\ncase H; auto; intros l1 Hl1; exists (a0 :: l1).\napply permutation_trans with (a0 :: a :: l1); auto.\nQed.\n \n(************************************** \n   A permutation of a cons can be inverted\n   **************************************)\n\nLet permutation_cons_ex_aux :\n  forall (a : A) (l1 l2 : list A),\n  permutation l1 l2 ->\n  forall l11 l12 : list A,\n  l1 = l11 ++ a :: l12 ->\n  exists l3 : list A,\n    (exists l4 : list A,\n       l2 = l3 ++ a :: l4 /\\ permutation (l11 ++ l12) (l3 ++ l4)).\nintros a l1 l2 H; elim H; clear H l1 l2.\nintros l11 l12; case l11; simpl in |- *; intros; discriminate.\nintros a0 l1 l2 H H0 l11 l12; case l11; simpl in |- *.\nexists (nil (A:=A)); exists l1; simpl in |- *; split; auto.\neq_tac; injection H1; auto.\ninjection H1; intros H2 H3; rewrite <- H2; auto.\nintros a1 l111 H1.\ncase (H0 l111 l12); auto.\ninjection H1; auto.\nintros l3 (l4, (Hl1, Hl2)).\nexists (a0 :: l3); exists l4; split; simpl in |- *; auto.\neq_tac; injection H1; auto.\ninjection H1; intros H2 H3; rewrite H3; auto.\nintros a0 b l l11 l12; case l11; simpl in |- *.\ncase l12; try (intros; discriminate).\nintros a1 l0 H; exists (b :: nil); exists l0; simpl in |- *; split; auto.\nrepeat eq_tac; injection H; auto.\ninjection H; intros H1 H2 H3; rewrite H2; auto.\nintros a1 l111; case l111; simpl in |- *.\nintros H; exists (nil (A:=A)); exists (a0 :: l12); simpl in |- *; split; auto.\nrepeat eq_tac; injection H; auto.\ninjection H; intros H1 H2 H3; rewrite H3; auto.\nintros a2 H1111 H; exists (a2 :: a1 :: H1111); exists l12; simpl in |- *;\n split; auto.\nrepeat eq_tac; injection H; auto.\nintros l1 l2 l3 H H0 H1 H2 l11 l12 H3.\ncase H0 with (1 := H3).\nintros l4 (l5, (Hl1, Hl2)).\ncase H2 with (1 := Hl1).\nintros l6 (l7, (Hl3, Hl4)).\nexists l6; exists l7; split; auto.\napply permutation_trans with (1 := Hl2); auto.\nQed.\n \nTheorem permutation_cons_ex :\n forall (a : A) (l1 l2 : list A),\n permutation (a :: l1) l2 ->\n exists l3 : list A,\n   (exists l4 : list A, l2 = l3 ++ a :: l4 /\\ permutation l1 (l3 ++ l4)).\nintros a l1 l2 H.\napply (permutation_cons_ex_aux a (a :: l1) l2 H nil l1); simpl in |- *; auto.\nQed.\n\n(************************************** \n   A permutation can be simply inverted if the two list starts with a cons\n   **************************************)\n \nTheorem permutation_inv :\n forall (a : A) (l1 l2 : list A),\n permutation (a :: l1) (a :: l2) -> permutation l1 l2.\nintros a l1 l2 H; case permutation_cons_ex with (1 := H).\nintros l3 (l4, (Hl1, Hl2)).\napply permutation_trans with (1 := Hl2).\ngeneralize Hl1; case l3; simpl in |- *; auto.\nintros H1; injection H1; intros H2; rewrite H2; auto.\nintros a0 l5 H1; injection H1; intros H2 H3; rewrite H2; rewrite H3; auto.\napply permutation_trans with (a0 :: l4 ++ l5); auto.\napply permutation_skip; apply permutation_app_swap.\napply (permutation_app_swap (a0 :: l4) l5).\nQed.\n\n(************************************** \n   Take a list and return tle list of all pairs of an element of the \n   list and the remaining list\n   **************************************)\n \nFixpoint split_one (l : list A) : list (A * list A) :=\n  match l with\n  | nil => nil (A:=A * list A)\n  | a :: l1 =>\n      (a, l1)\n      :: map (fun p : A * list A => (fst p, a :: snd p)) (split_one l1)\n  end.\n\n(************************************** \n   The pairs of the list are a permutation\n   **************************************)\n \nTheorem split_one_permutation :\n forall (a : A) (l1 l2 : list A),\n In (a, l1) (split_one l2) -> permutation (a :: l1) l2.\nintros a l1 l2; generalize a l1; elim l2; clear a l1 l2; simpl in |- *; auto.\nintros a l1 H1; case H1.\nintros a l H a0 l1 [H0| H0].\ninjection H0; intros H1 H2; rewrite H2; rewrite H1; auto.\ngeneralize H H0; elim (split_one l); simpl in |- *; auto.\nintros H1 H2; case H2.\nintros a1 l0 H1 H2 [H3| H3]; auto.\ninjection H3; intros H4 H5; (rewrite <- H4; rewrite <- H5).\napply permutation_trans with (a :: fst a1 :: snd a1); auto.\napply permutation_skip.\napply H2; auto.\ncase a1; simpl in |- *; auto.\nQed.\n\n(************************************** \n   All elements of the list are there\n   **************************************)\n \nTheorem split_one_in_ex :\n forall (a : A) (l1 : list A),\n In a l1 -> exists l2 : list A, In (a, l2) (split_one l1).\nintros a l1; elim l1; simpl in |- *; auto.\nintros H; case H.\nintros a0 l H [H0| H0]; auto.\nexists l; left; eq_tac; auto.\ncase H; auto.\nintros x H1; exists (a0 :: x); right; auto.\napply\n (in_map (fun p : A * list A => (fst p, a0 :: snd p)) (split_one l) (a, x));\n auto.\nQed.\n\n(************************************** \n   An auxillary function to generate all permutations\n   **************************************)\n \nFixpoint all_permutations_aux (l : list A) (n : nat) {struct n} :\n list (list A) :=\n  match n with\n  | O => nil :: nil\n  | S n1 =>\n      flat_map\n        (fun p : A * list A =>\n         map (cons (fst p)) (all_permutations_aux (snd p) n1)) (\n        split_one l)\n  end.\n(************************************** \n   Generate all the permutations\n   **************************************)\n \nDefinition all_permutations (l : list A) := all_permutations_aux l (length l).\n \n(************************************** \n   All the elements of the list are permutations\n   **************************************)\n\nLet all_permutations_aux_permutation :\n  forall (n : nat) (l1 l2 : list A),\n  n = length l2 -> In l1 (all_permutations_aux l2 n) -> permutation l1 l2.\nintros n; elim n; simpl in |- *; auto.\nintros l1 l2; case l2.\nsimpl in |- *; intros H0 [H1| H1].\nrewrite <- H1; auto.\ncase H1.\nsimpl in |- *; intros; discriminate.\nintros n0 H l1 l2 H0 H1.\ncase in_flat_map_ex with (1 := H1).\nclear H1; intros x; case x; clear x; intros a1 l3 (H1, H2).\ncase in_map_inv with (1 := H2).\nsimpl in |- *; intros y (H3, H4).\nrewrite H4; auto.\napply permutation_trans with (a1 :: l3); auto.\napply permutation_skip; auto.\napply H with (2 := H3).\napply eq_add_S.\napply trans_equal with (1 := H0).\nchange (length l2 = length (a1 :: l3)) in |- *.\napply permutation_length; auto.\napply permutation_sym; apply split_one_permutation; auto.\napply split_one_permutation; auto.\nQed.\n \nTheorem all_permutations_permutation :\n forall l1 l2 : list A, In l1 (all_permutations l2) -> permutation l1 l2.\nintros l1 l2 H; apply all_permutations_aux_permutation with (n := length l2);\n auto.\nQed.\n \n(************************************** \n   A permutation is in the list\n   **************************************)\n\nLet permutation_all_permutations_aux :\n  forall (n : nat) (l1 l2 : list A),\n  n = length l2 -> permutation l1 l2 -> In l1 (all_permutations_aux l2 n).\nintros n; elim n; simpl in |- *; auto.\nintros l1 l2; case l2.\nintros H H0; rewrite permutation_nil_inv with (1 := H0); auto with datatypes.\nsimpl in |- *; intros; discriminate.\nintros n0 H l1; case l1.\nintros l2 H0 H1;\n rewrite permutation_nil_inv with (1 := permutation_sym _ _ H1) in H0;\n discriminate.\nclear l1; intros a1 l1 l2 H1 H2.\ncase (split_one_in_ex a1 l2); auto.\napply permutation_in with (1 := H2); auto with datatypes.\nintros x H0.\napply in_flat_map with (b := (a1, x)); auto.\napply in_map; simpl in |- *.\napply H; auto.\napply eq_add_S.\napply trans_equal with (1 := H1).\nchange (length l2 = length (a1 :: x)) in |- *.\napply permutation_length; auto.\napply permutation_sym; apply split_one_permutation; auto.\napply permutation_inv with (a := a1).\napply permutation_trans with (1 := H2).\napply permutation_sym; apply split_one_permutation; auto.\nQed.\n \nTheorem permutation_all_permutations :\n forall l1 l2 : list A, permutation l1 l2 -> In l1 (all_permutations l2).\nintros l1 l2 H; unfold all_permutations in |- *;\n apply permutation_all_permutations_aux; auto.\nQed.\n\n(************************************** \n   Permutation is decidable\n   **************************************)\n \nDefinition permutation_dec :\n  (forall a b : A, {a = b} + {a <> b}) ->\n  forall l1 l2 : list A, {permutation l1 l2} + {~ permutation l1 l2}.\nintros H l1 l2.\ncase (In_dec (list_eq_dec H) l1 (all_permutations l2)).\nintros i; left; apply all_permutations_permutation; auto.\nintros i; right; contradict i; apply permutation_all_permutations; auto.\nDefined.\n \nEnd permutation.\n\n(************************************** \n   Hints\n   **************************************)\n\nHint Constructors permutation.\nHint Resolve permutation_refl.\nHint Resolve permutation_app_comp.\nHint Resolve permutation_app_swap.\n\n(************************************** \n   Implicits\n   **************************************)\n\nImplicit Arguments permutation [A].\nImplicit Arguments split_one [A].\nImplicit Arguments all_permutations [A].\nImplicit Arguments permutation_dec [A].\n\n(************************************** \n   Permutation is compatible with map\n   **************************************)\n \nTheorem permutation_map :\n forall (A B : Type) (f : A -> B) l1 l2,\n permutation l1 l2 -> permutation (map f l1) (map f l2).\nintros A B f l1 l2 H; elim H; simpl in |- *; auto.\nintros l0 l3 l4 H0 H1 H2 H3; apply permutation_trans with (2 := H3); auto.\nQed.\nHint Resolve permutation_map.\n \n(************************************** \n  Permutation  of a map can be inverted\n  *************************************)\n\nLet permutation_map_ex_aux :\n  forall (A B : Type) (f : A -> B) l1 l2 l3,\n  permutation l1 l2 ->\n  l1 = map f l3 -> exists l4, permutation l4 l3 /\\ l2 = map f l4.\nintros A1 B1 f l1 l2 l3 H; generalize l3; elim H; clear H l1 l2 l3.\nintros l3; case l3; simpl in |- *; auto.\nintros H; exists (nil (A:=A1)); auto.\nintros; discriminate.\nintros a0 l1 l2 H H0 l3; case l3; simpl in |- *; auto.\nintros; discriminate.\nintros a1 l H1; case (H0 l); auto.\ninjection H1; auto.\nintros l5 (H2, H3); exists (a1 :: l5); split; simpl in |- *; auto.\neq_tac; auto; injection H1; auto.\nintros a0 b l l3; case l3.\nintros; discriminate.\nintros a1 l0; case l0; simpl in |- *.\nintros; discriminate.\nintros a2 l1 H; exists (a2 :: a1 :: l1); split; simpl in |- *; auto.\nrepeat eq_tac; injection H; auto.\nintros l1 l2 l3 H H0 H1 H2 l0 H3.\ncase H0 with (1 := H3); auto.\nintros l4 (HH1, HH2).\ncase H2 with (1 := HH2); auto.\nintros l5 (HH3, HH4); exists l5; split; auto.\napply permutation_trans with (1 := HH3); auto.\nQed.\n \nTheorem permutation_map_ex :\n forall (A B : Type) (f : A -> B) l1 l2,\n permutation (map f l1) l2 ->\n exists l3, permutation l3 l1 /\\ l2 = map f l3.\nintros A0 B f l1 l2 H; apply permutation_map_ex_aux with (l1 := map f l1);\n auto.\nQed.\n\n(************************************** \n   Permutation is compatible with flat_map\n **************************************)\n \nTheorem permutation_flat_map :\n forall (A B : Type) (f : A -> list B) l1 l2,\n permutation l1 l2 -> permutation (flat_map f l1) (flat_map f l2).\nintros A B f l1 l2 H; elim H; simpl in |- *; auto.\nintros a b l; auto.\nrepeat rewrite <- app_ass.\napply permutation_app_comp; auto.\nintros k3 l4 l5 H0 H1 H2 H3; apply permutation_trans with (1 := H1); auto.\nQed.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Examples/Indifferentiability/ECurve/List/Permutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7121360198576548}}
{"text": "(* My first theorem *)\n\nDefinition pierce := forall (p q : Prop),\n  ((p -> q) -> p) -> p.\nDefinition lem := forall p, p \\/ ~p.\n\nTheorem pierce_equiv_lem: pierce <-> lem.\nProof.\n   unfold pierce, lem.\n   firstorder.\n   apply H with (q := ~ (p \\/ ~p)).\n   firstorder.\n   destruct (H p).\n   assumption.\n   tauto.\nQed.\n\n\n", "meta": {"author": "richardsouthwell", "repo": "startcoq", "sha": "d9779af6ddff2b962e30bbd0f1b34920b76a29bc", "save_path": "github-repos/coq/richardsouthwell-startcoq", "path": "github-repos/coq/richardsouthwell-startcoq/startcoq-d9779af6ddff2b962e30bbd0f1b34920b76a29bc/firstProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7120918742983577}}
{"text": "Require Export Poly.\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros.\n  rewrite <- H.\n  apply H0.\nQed.\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros.\n  apply H0. apply H.\nQed.\n\n\nTheorem silly2a : forall(n m : nat),\n     (n,n) = (m,m) ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros.\n  apply H0. apply H.\nQed.\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  apply H0.\nQed.\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5 ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros.\n  simpl.\n  symmetry.\n  apply H.\nQed.\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  intros.\n  rewrite -> H.\n  symmetry.\n  apply rev_involutive.\nQed.\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros.\n  rewrite -> H.\n  rewrite -> H0.\n  reflexivity.\nQed.\n\nTheorem trans_eq : forall (X: Type) (n m o: X),\n  n = m -> m = o -> n = o.\nProof.\n  intros.\n  rewrite -> H.\n  rewrite -> H0.\n  reflexivity.\nQed.\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros.\n  apply trans_eq with (m:=[c;d]).\n  apply H. apply H0.\nQed.\n\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minusTwo o) ->\n     (n + p) = m ->\n     (n + p) = (minusTwo o).\nProof.\n  intros.\n  apply trans_eq with (m).\n  apply H0. apply H.\nQed.  \n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros.\n  inversion H.\n  reflexivity.\nQed.\n\nLemma S_injective_backwards : forall (n m : nat),\n  n = m ->\n  S n = S m.\nProof.\n  intros. inversion H. reflexivity.\nQed.\n\nTheorem inversion_ex1 : forall (n m o : nat),\n  [n; m] = [o; o] ->\n  [n] = [m].\nProof.\n  intros.\n  inversion H.\n  reflexivity.\nQed.\n\nTheorem inversion_ex2 : forall (n m : nat),\n  [n] = [m] ->\n  n = m.\nProof.\n  intros.\n  inversion H.\n  reflexivity.\nQed.\n\nExample inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n  x :: y :: l = z :: j ->\n  y :: l = x :: j ->\n  x = y.\nProof.\n  intros.\n  inversion H0.\n  reflexivity.\nQed.\n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  intros.\n  destruct n as [| n'].\n  - reflexivity.\n  - inversion H.\nQed.\n\nTheorem inversion_ex4 : forall (n : nat),\n  S n = O ->\n  2 + 2 = 5.\nProof.\n  intros.\n  inversion H.\nQed.\n\nTheorem inversion_ex5 : forall (n m : nat),\n  false = true ->\n  [n] = [m].\nProof.\n  intros.\n  inversion H.\nQed.\n\nExample inversion_ex6 : forall (X : Type)\n                          (x y z : X) (l j : list X),\n  x :: y :: l = [] ->\n  y :: l = z :: j ->\n  x = z.\nProof.\n  intros.\n  inversion H.\nQed.\n\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),\n  x = y -> f x = f y.\nProof.\n  intros.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b ->\n     beq_nat n m = b.\nProof.\n  intros.\n  simpl in H. apply H.\nQed.\n\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  symmetry in H0. apply H in H0. symmetry in H0. apply H0.\nQed.\n\n(* didn't work when I used 'intros.' at the outset... *)\n\nTheorem plus_n_n_injective : forall n m,\n     n + n = m + m ->\n     n = m.\nProof.\n  intros n.\n  induction n as [| n' IHn].\n  - intros. destruct m as [| m'].\n    + reflexivity.\n    + inversion H.\n  - intros. destruct m as [| m'].\n    + intros. inversion H.\n    + intros. inversion H.\n      rewrite <- plus_n_Sm in H1.\n      rewrite <- plus_n_Sm in H1.\n      inversion H1.\n      apply IHn in H2.\n      rewrite -> H2.\n      reflexivity.\nQed.\n\n\nTheorem double_injective : forall n m : nat,\n     double n = double m ->\n     n = m.\nProof.\n  intros n.\n  induction n as [| n' IHn].\n  - intros.\n    destruct m as [| m'].\n    + reflexivity.\n    + inversion H.\n  - intros.\n    destruct m as [| m'].\n    + inversion H.\n    + apply f_equal.\n      apply IHn.\n      inversion H.\n      reflexivity.\nQed.\n\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n.\n  induction n as [| n' IHn].\n  - intros.\n    destruct m as [| m'].\n    + reflexivity.\n    + inversion H.\n  - intros.\n    destruct m as [| m'].\n    + inversion H.\n    + apply f_equal.\n      apply IHn.\n      inversion H.\n      reflexivity.\nQed.\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros.\n  generalize dependent n.\n  induction m as [| m' IHm].\n  - intros.\n    destruct n as [| n'].\n    + reflexivity.\n    + inversion H.\n  - intros.\n    destruct n as [| n'].\n    + inversion H.\n    + apply f_equal.\n      apply IHm.\n      inversion H.\n      reflexivity.\nQed.\n\n\nTheorem beq_id_true : forall x y,\n  beq_id x y = true -> x = y.\nProof.\n  intros [m] [n].\n  simpl.\n  intros.\n  assert (H' : m = n).\n  - apply beq_nat_true. apply H.\n  - rewrite -> H'. reflexivity.\nQed.\n\n\nTheorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     nth_error l n = None.\nProof.\n  intros.\n  generalize dependent n.\n  induction l as [| h t IH].\n  - intros.\n    rewrite <- H.\n    reflexivity.\n  - intros.\n    rewrite <- H.\n    simpl.\n    apply IH.\n    reflexivity.\nQed.\n\nDefinition square n := n * n.\n\nLemma square_mult : forall n m, square (n * m) = square n * square m.\nProof.\n  intros.\n  unfold square.\n  rewrite -> mult_assoc.\n  assert (H : n * m * n = n * n * m).\n  - rewrite -> mult_comm. apply mult_assoc.\n  - rewrite -> H. rewrite -> mult_assoc.\n    reflexivity.\nQed.\n\nDefinition foo (x: nat) := 5.\n\nFact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.\nProof.\n  intros m.\n  reflexivity.\nQed.\n\nDefinition bar x :=\n  match x with\n  | O => 5\n  | S _ => 5\n  end.\n\nFact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.\nProof.\n  intros m.\n  unfold bar.\n  destruct m.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros.\n  unfold sillyfun.\n  destruct (beq_nat n 3).\n  - reflexivity.\n  - destruct (beq_nat n 5).\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem tail_eq: forall (X: Type) (h: X) (l1 l2: list X),\n    l1 = l2 -> h :: l1 = h :: l2.\nProof.\n  intros. apply f_equal. apply H.\nQed.\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  intros X Y l.\n  induction l as [| h t IH].\n  - intros.\n    inversion H.\n    reflexivity.\n  - intros.\n    inversion H.\n    destruct h.\n    destruct (split t).\n    simpl in H1.\n    inversion H1.\n    simpl.\n    apply tail_eq.\n    apply IH.\n    reflexivity.\nQed.\n\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros.\n  unfold sillyfun1 in H.\n  destruct (beq_nat n 3) eqn:neq3.\n  - apply beq_nat_true in neq3.\n    rewrite -> neq3.\n    reflexivity.\n  - destruct (beq_nat n 5) eqn:neq5.\n    + apply beq_nat_true in neq5.\n      rewrite -> neq5.\n      reflexivity.\n    + inversion H.\nQed.\n\nTheorem bool_fn_applied_thrice :\n  forall (f : bool -> bool) (b : bool),\n  f (f (f b)) = f b.\nProof.\n  intros.\n  destruct b.\n  - destruct (f true) eqn:fTrue.\n    + rewrite -> fTrue.\n      apply fTrue.\n    + destruct (f false) eqn:fFalse.\n      * apply fTrue.\n      * apply fFalse.\n - destruct (f false) eqn: fFalse.\n   + destruct (f true) eqn:fTrue.\n     * apply fTrue.\n     * apply fFalse.\n   + rewrite -> fFalse.\n     apply fFalse.\nQed.\n\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  intros.\n  generalize dependent m.\n  induction n as [| n' IHn].\n  - intros. destruct m as [| m'].\n    + reflexivity.\n    + reflexivity.\n  - intros. destruct m as [| m'].\n    + reflexivity.\n    + apply IHn.\nQed.\n\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  intros.\n  destruct n as [| n'].\n  - apply beq_nat_true in H.\n    rewrite <- H in H0.\n    apply beq_nat_true in H0.\n    rewrite <- H0.\n    reflexivity.\n  - apply beq_nat_true in H.\n    rewrite <- H in H0.\n    apply H0.\nQed.\n\n\nDefinition split_combine_statement : Prop :=\n  forall (X: Type) (l1 l2: list X),\n  length l1 = length l2 ->\n  split (combine l1 l2) = (l1, l2).\n\nTheorem split_combine : split_combine_statement.\nProof.\n  intros X l1.\n  induction l1 as [| h1 t1 IH1].\n  - intros.\n    simpl.\n    destruct l2 as [| h2 t2 IH2].\n    + reflexivity.\n    + inversion H.\n  - intros.\n    inversion H.\n    destruct l2 as [| h2 t2].\n    + inversion H1.\n    + inversion H1.\n      apply IH1 in H2.\n      simpl.\n      rewrite -> H2.\n      reflexivity.\nQed.\n\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool) (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  intros.\n  generalize dependent lf.\n  induction l as [| h t IH].\n  - intros.\n    simpl in H.\n    inversion H.\n  - intros.\n    generalize dependent H.\n    destruct lf as [| hf tf].\n    + simpl.\n      intros.\n      destruct (test h) eqn:testH.\n      * inversion H.\n        rewrite -> H1 in testH.        \n        apply testH.\n      * apply IH in H.\n        apply H.\n    + simpl.\n      intros.\n      destruct (test h) eqn:testH.\n      * inversion H.\n        rewrite -> H1 in testH.\n        apply testH.\n      * apply IH in H.\n        apply H.\nQed.\n\nFixpoint forallb {X: Type} (test: X -> bool) (l: list X) : bool :=\n  match l with\n  | [] => true\n  | h :: t => (test h) && (forallb test t)\n  end.\n\nFixpoint existsb {X: Type} (test: X -> bool) (l: list X) : bool :=\n  match l with\n  | [] => false\n  | h :: t => (test h) || (existsb test t)\n  end.\n\nExample forallb_1: forallb oddb [1;3;5;7;9] = true.\nProof. reflexivity. Qed.\n\nExample forallb_2: forallb negb [false;false] = true.\nProof. reflexivity. Qed.\n\nExample forallb_3: forallb evenb [0;2;4;5] = false.\nProof. reflexivity. Qed.\n\nExample forallb_4: forallb (beq_nat 5) [] = true.\nProof. reflexivity. Qed.\n\nExample existsb_1: existsb (beq_nat 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\n\nExample existsb_2: existsb (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\n\nExample existsb_3: existsb oddb [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\n\nExample existsb_4: existsb evenb [] = false.\nProof. reflexivity. Qed.\n\n\nDefinition existsb' {X: Type} (test: X -> bool) (l: list X) :=\n  negb (forallb (fun a => negb (test a)) l).\n\nExample existsb'_1: existsb' (beq_nat 5) [0;2;3;6] = false.\nProof. reflexivity. Qed.\n\nExample existsb'_2: existsb' (andb true) [true;true;false] = true.\nProof. reflexivity. Qed.\n\nExample existsb'_3: existsb' oddb [1;0;0;0;0;3] = true.\nProof. reflexivity. Qed.\n\nExample existsb'_4: existsb' evenb [] = false.\nProof. reflexivity. Qed.\n\n\nTheorem existsb_existsb': forall (X: Type) (test: X -> bool) (l: list X),\n  existsb test l = existsb' test l.\nProof.\n  intros.\n  unfold existsb.\n  unfold existsb'.\n  induction l as [| h t IH].\n  - simpl. reflexivity.\n  - simpl.\n    destruct (test h) eqn:testH.\n    + simpl. reflexivity.\n    + simpl. apply IH.\nQed.\n\nDefinition forallb' {X: Type} (test: X -> bool) (l: list X) : bool :=\n  fold (fun item acc => acc && (test item)) l true.\n\nExample forallb'_1: forallb' oddb [1;3;5;7;9] = true.\nProof. reflexivity. Qed.\n\nExample forallb'_2: forallb' negb [false;false] = true.\nProof. reflexivity. Qed.\n\nExample forallb'_3: forallb' evenb [0;2;4;5] = false.\nProof. reflexivity. Qed.\n\nExample forallb'_4: forallb' (beq_nat 5) [] = true.\nProof. reflexivity. Qed.\n\nTheorem andb_true_r: forall (a: bool),\n    a && true = a.\nProof.\n  intros.\n  destruct a.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem forallb_forallb': forall (X: Type) (test: X -> bool) (l: list X),\n  forallb test l = forallb' test l.\nProof.\n  intros.\n  unfold forallb.\n  unfold forallb'.\n  induction l as [| h t IH].\n  - simpl. reflexivity.\n  - simpl.\n    destruct (test h) eqn:testH.\n    + simpl.\n      rewrite -> IH.\n      rewrite -> andb_true_r.\n      reflexivity.\n    + simpl.\n      rewrite -> andb_false_r.\n      reflexivity.\nQed.\n\nTheorem map_length_unchanged: forall (A B: Type) (f: A -> B) (l: list A),\n    length l = length (map f l).\nProof.\n  intros.\n  induction l as [| h t IH].\n  - reflexivity.\n  - simpl.\n    rewrite -> IH.\n    reflexivity.\nQed.\n\nDefinition flat_map_fold {X Y: Type} (f: X -> list Y) (l: list X) : list Y :=\n  fold (fun item acc => (f item) ++ acc) l [].\n\nTheorem flat_map_fold_correct: forall (X Y: Type) (f: X -> list Y) (l: list X),\n  flat_map f l = flat_map_fold f l.\nProof.\n  intros.\n  unfold flat_map_fold.\n  unfold flat_map.\n  induction l as [| h t IH].\n  - reflexivity.\n  - simpl.\n    rewrite -> IH.\n    reflexivity.\nQed.\n", "meta": {"author": "atungare", "repo": "coq-software-foundations", "sha": "49bf005d87f530a54274ce9de06b6bce99c1e8aa", "save_path": "github-repos/coq/atungare-coq-software-foundations", "path": "github-repos/coq/atungare-coq-software-foundations/coq-software-foundations-49bf005d87f530a54274ce9de06b6bce99c1e8aa/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7120673370028405}}
{"text": "(*****************************************************************)\n(******    M2 LMFI Preuves Assistées par Ordinateur        *******)\n(****** Projet : compilation d'expressions avec sommations *******)\n(******               Pierre Letouzey                      *******)\n(*****************************************************************)\n\nRequire Import String Datatypes Arith List Lia.\nImport ListNotations.\nOpen Scope string_scope.\nOpen Scope list_scope.\n\n(** I) Bibliotheque *)\n\n(** Comparaisons d'entiers\n\n    En Coq, la comparaison a <= b est une affirmation logique\n    (dans Prop). On ne peut pas s'en servir pour un test dans\n    un programme. Pour cela il faut utiliser la comparaison\n    booléenne a <=? b (correspondant à la constante Nat.leb).\n    Voici le lien entre ces deux notions,  *)\n\n\nLemma leb_le x y : (x <=? y)%nat = true <-> x <= y.\nProof.\n apply Nat.leb_le.\nQed.\n\nLemma leb_gt x y : (x <=? y)%nat = false <-> y < x.\nProof.\n apply Nat.leb_gt.\nQed.\n\n(** Une soustraction sans arrondi.\n\n    Sur les entiers naturels, la soustraction usuelle de Coq\n    est tronquée : lorsque a < b, alors a - b = 0.\n    Ici on utilise None pour signaler ce cas, et Some pour\n    indiquer une soustraction \"réussie\". *)\n\nFixpoint safe_minus a b : option nat :=\n match b, a with\n   | 0, _ => Some a\n   | S b, 0 => None\n   | S b, S a => safe_minus a b\n end.\n\nLemma safe_minus_spec a b :\n match safe_minus a b with\n | Some c => a = b + c\n | None => a < b\n end.\nProof.\n revert b; induction a; destruct b; simpl; auto with arith.\n specialize (IHa b). destruct (safe_minus a b); auto with arith.\nQed.\n\n(** Accès au n-ieme élement d'une liste\n\n   NB: list_get existe aussi dans la bibliothèque standard,\n   c'est List.nth_error. *)\n\nFixpoint list_get {A} (l:list A) i : option A :=\n  match i,l with\n    | 0,   x::_ => Some x\n    | S j, _::l => list_get l j\n    | _, _ => None\n  end.\n\nDefinition option_map {A B} (f:A->B) (o:option A) :=\n  match o with\n    | Some a => Some (f a)\n    | None => None\n  end.\n\nFixpoint list_set {A} (l:list A) i x : option (list A) :=\n  match i,l with\n    | 0, _::l => Some (x::l)\n    | S j, a::l => option_map (cons a) (list_set l j x)\n    | _, _ => None\n  end.\n\nLemma get_app_l {A} (l l':list A)(n:nat) : n < length l ->\n  list_get (l++l') n = list_get l n.\nProof.\n revert l.\n induction n; destruct l; simpl; auto with arith; inversion 1.\nQed.\n\nLemma get_app_r {A} (l l':list A)(n:nat) :\n  list_get (l++l') (length l + n) = list_get l' n.\nProof.\n induction l; auto.\nQed.\n\nLemma get_app_r0 {A} (l l':list A)(n:nat) : n = length l ->\n  list_get (l++l') n = list_get l' 0.\nProof.\n  intros. rewrite <- (get_app_r l l'). f_equal. lia.\nQed.\n\nLemma get_app_r' {A} (l l':list A)(n:nat) : length l <= n ->\n  list_get (l++l') n = list_get l' (n-length l).\nProof.\n intros. rewrite <- (get_app_r l l'). f_equal. lia.\nQed.\n\nLemma get_None {A} (l:list A) n :\n list_get l n = None <-> length l <= n.\nProof.\n revert n. induction l; destruct n; simpl; rewrite ?IHl; split;\n  auto with arith; inversion 1.\nQed.\n\nLemma get_Some {A} (l:list A) n x :\n list_get l n = Some x -> n < length l.\nProof.\n revert n. induction l; destruct n; simpl; try discriminate.\n  - auto with arith.\n  - intros. apply IHl in H. auto with arith.\nQed.\n\nGlobal Hint Resolve get_Some : core.\n\n(** Equivalent de List.assoc, spécialisé aux string. Ici =? est String.eqb *)\n\nFixpoint lookup {A}(s:string)(l:list (string*A))(default:A) :=\n  match l with\n    | nil => default\n    | (x,d)::l => if s =? x then d else lookup s l default\n  end.\n\n(** Index d'un element dans une liste, spécialisé aux string *)\n\nFixpoint index (s:string)(l:list string) :=\n  match l with\n    | nil => 0\n    | x::l => if s =? x then 0 else S (index s l)\n  end.\n\n(** Opérateur de sommation : sum f x n = f x + ... + f (x+n).\n    Attention, il y a (n+1) termes dans cette somme.\n    En particulier sum f 0 n = f 0 + ... + f n. *)\n\nFixpoint sum f x k :=\n  match k with\n    | 0 => f x\n    | S n' => f x + sum f (S x) n'\n  end.\n\nCompute sum (fun _ => 1) 0 10. (* 11 *)\nCompute sum (fun x => x) 0 10. (* 0 + 1 + ... + 10 = 55 *)\n\n(** II) Expressions arithmétiques avec sommations *)\n\n(** Les expressions *)\n\nDefinition var := string.\n\nInductive op := Plus | Minus | Mult.\n\nInductive expr :=\n  | EInt : nat -> expr\n  | EVar : var -> expr\n  | EOp  : op -> expr -> expr -> expr\n  | ESum : var -> expr -> expr -> expr.\n\n(** (ESum var max body) est la somme des valeurs de body\n    lorsque var prend successivement les valeurs de 0 jusqu'à max\n    (inclus). Par exemple, voici la somme des carrés de 0 à 10,\n    ce qu'on écrit sum(x^2,x=0..10) en Maple ou encore\n    $\\sum_{x=0}^{10}{x^2}$ en LaTeX. *)\n\nDefinition test1 :=\n  ESum \"x\" (EInt 10) (EOp Mult (EVar \"x\") (EVar \"x\")).\n\n(** Un peu plus complexe, une double sommation:\n    sum(sum(x*y,y=0..x),x=0..10) *)\n\nDefinition test2 :=\n  ESum \"x\" (EInt 10)\n   (ESum \"y\" (EVar \"x\")\n     (EOp Mult (EVar \"x\") (EVar \"y\"))).\n\n\n(** Evaluation d'expression *)\n\nDefinition eval_op o :=\n  match o with\n    | Plus => plus\n    | Minus => minus\n    | Mult => mult\n  end.\n\nFixpoint eval (env:list (string*nat)) e :=\n  match e with\n    | EInt n => n\n    | EVar v => lookup v env 0\n    | EOp o e1 e2 => (eval_op o) (eval env e1) (eval env e2)\n    | ESum v efin ecorps => sum (fun i => eval ( (v,i)::env ) ecorps) 0 (eval env efin)\n  end.\n\n\nCompute (eval nil (EOp Plus (EInt 37) (EInt 5) )). (* 37+5=42 *)\nCompute (eval nil test1). (* 385 attendu: n(n+1)(2n+1)/6 pour n=10 *)\nCompute (eval nil test2). (* 1705 attendu *)\n\n\n(** III) Machine à pile *)\n\n(** Notre machine est composée de deux piles : une pile principale\n    (pour les calculs) et une pile de variables. Les instructions\n    sont stockées à part. *)\n\nRecord machine :=\n  Mach {\n      (** Pointeur de code *)\n      pc : nat;\n      (** Pile principale *)\n      stack : list nat;\n      (** Pile de variables *)\n      vars : list nat\n    }.\n\nDefinition initial_machine := Mach 0 nil nil.\n\nInductive instr :=\n  (** Pousse une valeur entière sur la pile. *)\n  | Push : nat -> instr\n  (** Enlève la valeur au sommet de la pile. *)\n  | Pop : instr\n  (** Dépile deux valeurs et empile le resultat de l'operation binaire. *)\n  | Op : op -> instr\n  (** Crée une nouvelle variable en haut de la pile des variables,\n      contenant initialement 0. *)\n  | NewVar : instr\n  (** Enlève la variable en haut de la pile des variables.\n      Sa valeur actuelle est perdue. *)\n  | DelVar : instr\n  (** Pousse la valeur de la i-eme variable sur la pile. *)\n  | GetVar : nat -> instr\n  (** Enlève la valeur au sommet de la pile et met-la dans la i-eme variable. *)\n  | SetVar : nat -> instr\n  (** Jump offset: retire offset au pointeur de code si la première\n      variable est inférieure ou égale au sommet de pile.\n      Pile et variables sont gardées à l'identique. *)\n  | Jump : nat -> instr.\n\n(* NB: il n'y a pas d'instruction Halt, on s'arrête quand\n   pc arrive au delà du code. *)\n\n(* Sémantique de référence des instructions,\n   définie via une relation inductive *)\n\nInductive Stepi : instr -> machine -> machine -> Prop :=\n| SPush pc stk vs n :\n    Stepi (Push n) (Mach pc stk vs) (Mach (S pc) (n::stk) vs)\n| SPop pc stk vs x :\n    Stepi Pop (Mach pc (x::stk) vs) (Mach (S pc) stk vs)\n| SOp pc stk vs o y x :\n    Stepi (Op o) (Mach pc (y::x::stk) vs)\n                 (Mach (S pc) (eval_op o x y :: stk) vs)\n| SNewVar pc stk vs :\n    Stepi NewVar (Mach pc stk vs) (Mach (S pc) stk (0::vs))\n| SDelVar pc stk vs x :\n    Stepi DelVar (Mach pc stk (x::vs)) (Mach (S pc) stk vs)\n| SGetVar pc stk vs i x :\n    list_get vs i = Some x ->\n    Stepi (GetVar i) (Mach pc stk vs) (Mach (S pc) (x::stk) vs)\n| SSetVar pc stk vs vs' i x :\n    list_set vs i x = Some vs' ->\n    Stepi (SetVar i) (Mach pc (x::stk) vs)\n                     (Mach (S pc) stk vs')\n| SJumpYes pc stk vs v x off : off <= pc -> v <= x ->\n    Stepi (Jump off) (Mach pc (x::stk) (v::vs))\n                     (Mach (pc-off) (x::stk) (v::vs))\n| SJumpNo pc stk vs v x off : x < v ->\n    Stepi (Jump off) (Mach pc (x::stk) (v::vs))\n                     (Mach (S pc) (x::stk) (v::vs)).\n\nDefinition Step (code:list instr) (m m' : machine) : Prop :=\n match list_get code m.(pc) with\n  | Some instr => Stepi instr m m'\n  | None => False\n end.\n\nInductive Steps (code:list instr) : machine -> machine -> Prop :=\n | NoStep m : Steps code m m\n | SomeSteps m1 m2 m3 :\n     Step code m1 m2 -> Steps code m2 m3 -> Steps code m1 m3.\n\n(** state : état d'une machine, c'est à dire sa pile de calcul\n    et sa pile de variables, mais pas son pc. *)\n\nDefinition state := (list nat * list nat)%type.\n\n(** Une execution complète va de pc=0 à pc=(length code) *)\n\nDefinition Exec code '(stk, vs) '(stk', vs') :=\n  Steps code (Mach 0 stk vs) (Mach (length code) stk' vs').\n\n(** Run : relation entre un code et le résultat de son exécution. *)\n\nDefinition Run code res := Exec code (nil,nil) (res::nil,nil).\n\n(** Petit exemple d'usage de cette sémantique *)\n\nLemma Run_example :\n  Run (Push 7 :: Push 3 :: Op Minus :: nil) 4.\nProof.\n repeat econstructor.\nQed.\n\n(** Propriétés basiques de Steps : transitivité, ... *)\n\nGlobal Hint Constructors Stepi Steps : core.\n\nLemma Steps_trans code m1 m2 m3 :\n Steps code m1 m2 -> Steps code m2 m3 -> Steps code m1 m3.\nProof.\n  intros.\n  induction H.\n  - apply H0.\n  - apply IHSteps in H0. apply SomeSteps with m2; [apply H | apply H0].\nQed.\n\nLemma OneStep code st st' : Step code st st' -> Steps code st st'.\nProof.\n  intro.\n  apply SomeSteps with st'.\n  - apply H.\n  - apply NoStep.\nQed.\n\n\n(** Décalage de pc dans une machine *)\n\nDefinition shift_pc k (p:machine) :=\n let '(Mach pc stk vars) := p in\n (Mach (k+pc) stk vars).\n\nLemma pc_shift n m : (shift_pc n m).(pc) = n + m.(pc).\nProof.\n now destruct m.\nQed.\n\n\n\n(* Lemma pc_shift' n m stk vars : shift_pc n {|pc := 0+m; stack := stk; vars := vars|} =  {|pc := n+m; stack := stk; vars := vars|}.\nProof.\n  unfold shift_pc.\n  rewrite Nat.add_0_l.\n  reflexivity.\nQed. *)\n\n(** Ajout de code devant / derriere la zone intéressante *)\n\nLemma Step_extend code code' m m' :\n Step code m m' -> Step (code++code') m m'.\nProof.\n  unfold Step.\n  elim (le_or_lt (List.length code) (pc m));intros.\n  - rewrite <- get_None in H.\n    rewrite H in H0.\n    contradiction.\n  - rewrite get_app_l; assumption.\nQed.\n\nLemma Steps_extend code code' m m' :\n Steps code m m' -> Steps (code++code') m m'.\nProof.\n  intro.\n  induction H.\n  - apply NoStep.\n  - apply Steps_trans with m2.  \n    * apply OneStep. apply Step_extend. apply H.\n    * apply IHSteps.\nQed.\n\n\n\nLemma Stepi_shift instr n m m' :\n Stepi instr m m' ->\n Stepi instr (shift_pc n m) (shift_pc n m').\nProof.\n  intro.\n  Check Nat.add_succ_r.\n  induction H;simpl; try rewrite Nat.add_succ_r; auto.\n   - remember (n+pc0) as pc. \n      replace (n+(pc0-off)) with (pc-off).\n      + constructor.\n        * lia.\n        * assumption.\n      + lia.\nQed.\n\nLemma Step_shift code0 code m m' (n := List.length code0) :\n Step code m m' ->\n Step (code0 ++ code) (shift_pc n m) (shift_pc n m').\nProof.\n  unfold Step.\n  intro.\n  elim (le_or_lt (List.length code) (pc m));intros.\n  (* Hypothesis list_get outside code *)\n  - rewrite <- get_None in H0.\n    rewrite H0 in H.\n    contradiction.\n  (* Hypothesis list_get inside code *)\n  - rewrite pc_shift in *; unfold n in *.\n    rewrite get_app_r; destruct list_get.\n     * apply Stepi_shift. assumption. \n     * contradiction.\nQed.\n\nLemma Steps_shift code0 code  m m' (n := List.length code0) :\n Steps code m m' ->\n Steps (code0 ++ code) (shift_pc n m) (shift_pc n m').\nProof.\n  intro.\n  induction H.\n  - destruct m . apply NoStep.\n  - unfold n in *. apply SomeSteps with (shift_pc (length code0) m2). \n     + apply Step_shift. apply H.\n     + assumption. \nQed.\n\n(** Composition d'exécutions complètes *)\n\nLemma Exec_trans code1 code2 stk1 vars1 stk2 vars2 stk3 vars3 :\n Exec code1 (stk1, vars1) (stk2, vars2) ->\n Exec code2 (stk2, vars2) (stk3, vars3) ->\n Exec (code1 ++ code2) (stk1, vars1) (stk3, vars3).\nProof.\n  unfold Exec.\n  intros. \n  apply Steps_trans with ({| pc := length code1; stack := stk2; vars := vars2 |}).\n  - apply Steps_extend. assumption.\n  - apply Steps_shift with (code0:= code1) in H0.\n    simpl in H0.\n    rewrite app_length. \n    rewrite <- plus_n_O in H0. \n    assumption.\nQed.\n\n(** Correction des sauts lors d'une boucle\n\n    - La variable 0 est la variable de boucle a,\n    - La variable 1 est l'accumulateur acc\n    - Le haut de pile est la limite haute b de la variable de boucle\n\n    On montre d'abord que si un code ajoute f(a) à acc et\n    incrémente a, alors la répétition de ce code (via un Jump\n    ultérieur) ajoutera (sum f a (b-a)) à acc.\n    La variable N (valant b-a) est le nombre de tours à faire.\n*)\n\n(** Ce lemme est difficile. N'hésitez pas à le sauter et à y revenir\n    après avoir fini la partie IV. *)\n\nGlobal Hint Resolve le_n_S le_plus_r : core.\n\nLemma eqAddS_to_leq (a b N : nat) : b = S N + a -> S a <= b.\nProof.\n  intro.\n  apply Nat.lt_le_trans with (m:= a+S N);lia.\nQed.\n\nLemma Steps_jump code n (f:nat->nat) stk vars b :\n  length code = n ->\n  (forall a acc,\n   Steps code\n         (Mach 0 (b::stk) (a::acc::vars))\n         (Mach n (b::stk) ((S a)::(acc + f a)::vars)))\n  ->\n  forall N a acc,\n    b = N + a ->\n    Steps (code++(Jump n)::nil)\n          (Mach 0 (b::stk) (a::acc::vars))\n          (Mach (S n) (b::stk) ((S b)::(acc + sum f a N)::vars)).\nProof.\n  intro. intro.\n  induction N; intros.\n  - apply Steps_trans with (m2:= {| pc := n; stack := b :: stk; vars := S a :: acc + f a :: vars |}).\n    + apply Steps_extend.\n      apply H0.\n    + apply OneStep.\n      unfold Step.\n      simpl in *. \n      rewrite H1.\n      (* [Jump n] goes from [pc = n] to [pc = S n] because [a < S a] *) \n      rewrite get_app_r0; simpl; auto.\n  - apply Steps_trans with (m2:= {| pc := n; stack := b :: stk; vars := S a :: acc + f a :: vars |}).\n    + apply Steps_extend.\n      apply H0.\n    + apply Steps_trans with (m2:= {|pc := n - n; stack := b :: stk; vars := S a :: (acc + f a :: vars)|}).  \n      * apply OneStep.\n        unfold Step; simpl.\n        apply eqAddS_to_leq in H1.\n        (* [Jump n] goes from [pc = n ] to [pc = 0] since [S a <= b] *) \n        rewrite get_app_r0; simpl; auto.\n      * simpl.\n        rewrite Nat.add_assoc.\n        rewrite Nat.sub_diag.\n        apply IHN.\n        rewrite <- plus_Snm_nSm.\n        assumption.\nQed.\n\n\n(** Version spécialisée du résultat précédent, avec des\n    Exec au lieu de Step, et 0 comme valeur initiale des variables\n    de boucle et d'accumulateurs. *)\n\nLemma Exec_jump code (f:nat->nat) stk vars b :\n  (forall a acc,\n     Exec code (b::stk, a::acc::vars)\n               (b::stk, (S a)::(acc + f a)::vars))\n  ->\n  Exec (code++(Jump (length code))::nil)\n      (b::stk, 0::0::vars)\n      (b::stk, (S b)::(sum f 0 b)::vars).\nProof.\n  intros.\n  unfold Exec in *.\n  apply Steps_jump with (b:=b) (a:=0) (acc:=0) (N:=b) in H.\n  - simpl in *.\n    rewrite last_length.\n    assumption.\n  - trivial.\n  - trivial.\nQed.\n\n\n(** IV) Le compilateur\n\n    On transforme une expression en instructions pour\n    notre machine à pile.\n\n    Conventions:\n     - à chaque entrée dans une boucle, on crée deux variables,\n       la variable de boucle et l'accumulateur.\n     - on s'arrange pour que les variables de boucles aient\n       des indices pairs dans la pile des variables\n     - l'environnement de compilation cenv ne contient que les\n       variables de boucles.\n    Voir également l'invariant EnvsOk ci-dessous. *)\n\nFixpoint comp (cenv:list string) e :=\n  match e with\n    | EInt n => Push n :: nil\n    | EVar v => \n      let x := (index v cenv * 2) in\n      GetVar x::nil \n    | EOp o e1 e2 => \n      let x1 := comp cenv e1 in\n      let x2 := comp cenv e2 in\n      x1++x2++(Op o::nil)\n    | ESum v efin ecorps =>\n      let prologue := (comp cenv efin)++(NewVar::NewVar::nil) in\n      let corps := comp (v::cenv) ecorps in\n      let it := GetVar 1::Op Plus::SetVar 1::Push 1::GetVar 0::Op Plus::SetVar 0:: nil in \n      \n      let boucle := (corps ++ it) ++ [Jump (length (corps ++ it))]  in\n      \n      let epilogue := Pop::GetVar 1::DelVar::DelVar::nil in\n      prologue ++ boucle ++ epilogue\n  end.\n\nDefinition compile e := comp nil e.\n\n(** Variables libres d'une expression *)\n\nInductive FV (v:var) : expr -> Prop :=\n| FVVar : FV v (EVar v)\n| FVOpL (o:op) (e1 e2 : expr) : FV v e1 -> FV v (EOp o e1 e2)\n| FVOpR (o:op) (e1 e2 : expr) : FV v e2 -> FV v (EOp o e1 e2)\n| FVSumFin (v' :var) (efin ecorps : expr) :  FV v efin -> FV v (ESum v' efin ecorps)\n| FVSumCorps (v' :var) (efin ecorps : expr) : FV v ecorps -> FV v (ESum v' efin ecorps)\n.\n\nGlobal Hint Constructors FV : core.\n\nDefinition Closed e := forall v, ~ FV v e.\n\n(** Invariants sur les environnements.\n    env : environnement d'evaluation (list (string*nat))\n    cenv : environnement de compilation (list string)\n    vars : pile de variables pour nos machines *)\n\nDefinition EnvsOk e env cenv vars :=\n forall v, FV v e ->\n   In v cenv /\\\n   list_get vars (index v cenv * 2) = Some (lookup v env 0).\n\nGlobal Hint Unfold EnvsOk : core.\n\nLemma EnvsOk_ESum v e1 e2 env cenv vars a b :\n  EnvsOk (ESum v e1 e2) env cenv vars ->\n  EnvsOk e2 ((v,a)::env) (v::cenv) (a::b::vars).\nProof.\n  intros.\n  unfold EnvsOk in *.\n  intros.\n  elim (string_dec v0 v); intro; [rewrite a0|]; split; simpl.\n  - left. reflexivity.\n  - rewrite eqb_refl. simpl. reflexivity.\n  - right. apply H. apply FVSumCorps. assumption.\n  - rewrite <- eqb_neq in b0. rewrite b0. simpl.  \n    apply H. apply FVSumCorps. assumption.\nQed.\n\n\n(** Correction du compilateur *)\n\nLtac basic_exec :=\n  (* Cette tactique prouve des buts (Exec code m m')\n     quand le code et la machine m sont connus en détail. *)\n  unfold Exec; repeat (eapply SomeSteps; [constructor|]);\n   try apply NoStep; try reflexivity.\n  \n(* Si vous avez l'impression de prouver quelque chose d'impossible,\n   peut-être est-ce le signe que vous vous êtes trompé dans la définition\n   de comp. *)\n\nTheorem comp_ok e env cenv vars stk :\n EnvsOk e env cenv vars ->\n Exec (comp cenv e) (stk,vars) (eval env e :: stk, vars).\nProof.\n  revert stk.\n  revert vars.\n  revert cenv.\n  revert env.\n  \n  induction e; intros;basic_exec; simpl.\n  - unfold EnvsOk in H.\n    unfold eval.\n    apply H.\n    constructor.\n  - apply Exec_trans with (stk2:= eval env e1::stk) (vars2:= vars0).\n    + apply IHe1. auto.\n    + apply Exec_trans with (stk2:= eval env e2::eval env e1::stk) (vars2:= vars0).\n      * apply IHe2 with (stk:=eval env e1::stk).\n        auto.\n      * simpl.\n        apply OneStep.\n        constructor.\n  - rewrite app_assoc.\n    apply Exec_trans with (stk2:=(eval env e1)::stk) (vars2:= S (eval env e1) :: sum (fun i => eval ((v, i) :: env) e2) 0 (eval env e1)::vars0).\n    apply Exec_trans with (vars2:=0::0::vars0) (stk2:=eval env e1::stk).\n    (* prologue *)\n    + apply Exec_trans with (vars2:= vars0) (stk2:= eval env e1::stk).\n      * apply IHe1 with (stk:=stk) (vars:= vars0).\n        intuition.\n      * basic_exec.\n    (* boucle *)\n    + apply Exec_jump.\n      intros.\n      apply Exec_trans with (stk2:= eval ((v,a)::env) e2::eval env e1::stk) (vars2:= a::acc::vars0).\n      * apply IHe2 .\n        apply EnvsOk_ESum with (a:=a) (b:=acc) in H.\n        assumption.\n      * basic_exec.\n        unfold eval_op.\n        unfold list_set.\n        simpl.\n        rewrite Nat.add_comm.\n        reflexivity.\n    (* epilogue *)\n    + basic_exec.\nQed.\n\nTheorem compile_ok e : Closed e -> Run (compile e) (eval nil e).\nProof.\n  unfold Closed.\n  unfold Run.\n  intro.\n  apply comp_ok.\n  unfold EnvsOk.\n  intros.\n  elim H with v.\n  assumption.\nQed.\n\n(** V) Sémantique exécutable\n\n    A la place des relations précédentes (Step*, Exec, Run...),\n    on cherche maintenant à obtenir une fonction calculant\n    le résultat de l'exécution d'une machine à pile. *)\n\n(** Cette partie est nettement plus difficile que les précédentes\n    et est complètement optionnelle. *)\n    \n  Axiom TODO : forall {A:Type}, A.\n\nInductive step_result : Type :=\n  | More : machine -> step_result (* calcul en cours *)\n  | Stop : machine -> step_result (* calcul fini (pc hors code) *)\n  | Bug : step_result. (* situation illégale, machine plantée *)\n\n(** Pour la fonction [step] ci-dessous, ces deux opérateurs\n    monadiques peuvent aider (même si c'est essentiellement\n    une affaire de goût). *)\n\nDefinition option_bind {A} (o:option A) (f : A -> step_result) :=\n  match o with\n    | None => Bug\n    | Some x => f x\n  end.\n\nInfix \">>=\" := option_bind (at level 20, left associativity).\n\nDefinition list_bind {A} (l:list A) (f:A->list A->step_result) :=\n match l with\n  | nil => Bug\n  | x::l => f x l\n end.\n\nInfix \"::>\" := list_bind (at level 20, left associativity).\n\n(** Un pas de calcul *)\n\nDefinition step code (m:machine) : step_result :=\n  let '(Mach pc stk vars) := m in\n  (** réponse usuelle: *)\n  let more := fun stk vars => More (Mach (S pc) stk vars) in\n  match list_get code pc with\n    | None => Stop m\n    | Some instr => match instr with\n      | Push n => more (n::stk) vars\n      | Pop => TODO\n      | Op o => TODO\n      | NewVar => TODO\n      | DelVar => TODO\n      | GetVar i => TODO\n      | SetVar i => TODO\n      | Jump off => TODO\n      end\n    end.\n\n(** La fonction [steps] itère [step] un nombre [count] de fois\n    (ou moins si [Stop _] ou [Bug] sont atteints). *)\n\nFixpoint steps count (code:list instr)(m:machine) :=\n  match count with\n    | 0 => More m\n    | S count' => TODO\n  end.\n\n(** La function [run] exécute un certain code à partir\n    de la machine initiale, puis extrait le résultat obtenu.\n    On répond [None] si le calcul n'est pas fini au bout\n    des [count] étapes indiquées, ou bien en cas d'anomalies\n    lors de l'exécution ou à la fin (p.ex. pile finale vide,\n    variables finales non vides, etc). *)\n\nDefinition run (count:nat)(code : list instr) : option nat :=\n  TODO.\n\nCompute (run 1000 (compile test1)). (* attendu: Some 385 *)\nCompute (run 1000 (compile test2)). (* attendu: Some 1705 *)\n\n(** Equivalence entre sémantiques *)\n\n(** TODO: dans cette partie, à vous de formuler les\n    lemmes intermédiaires. *)\n\nLemma run_equiv code res :\n Run code res <-> exists count, run count code = Some res.\nProof.\nAdmitted.\n\n(** Le theorème principal, formulé pour run *)\n\nTheorem run_compile e :\n Closed e ->\n exists count, run count (compile e) = Some (eval nil e).\nProof.\nAdmitted.\n", "meta": {"author": "sebastienPatte", "repo": "Coq", "sha": "1c031f13db8d7101ca356c23b36d560c0a194de1", "save_path": "github-repos/coq/sebastienPatte-Coq", "path": "github-repos/coq/sebastienPatte-Coq/Coq-1c031f13db8d7101ca356c23b36d560c0a194de1/LMFI/projet-compilo/Marthe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7120673237481147}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf4 : natural) (lf2 : natural) : natural := plus lf2 lf4.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj92_coqofml_7u05Tt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.711967487251694}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** Maps (or dictionaries) are ubiquitous data structures, both in\n    software construction generally and in the theory of programming\n    languages in particular; we're going to need them in many places\n    in the coming chapters.  They also make a nice case study using\n    ideas we've seen in previous chapters, including building data\n    structures out of higher-order functions (from [Basics] and\n    [Poly]) and the use of reflection to streamline proofs (from\n    [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which return an [option] to\n    indicate success or failure.  The latter is defined in terms of\n    the former, using [None] as the default element. *)\n\n(* ###################################################################### *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we start.\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (and, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** Documentation for the standard library can be found at\n    http://coq.inria.fr/library/.\n\n    The [SearchAbout] command is a good way to look for theorems\n    involving objects of specific types. *)\n\n(* ###################################################################### *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our\n    maps.  For this purpose, we again use the type [id] from the\n    [Lists] chapter.  To make this chapter self contained, we repeat\n    its definition here, together with the equality comparison\n    function for [id]s and its fundamental property. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id id1 id2 :=\n  match id1,id2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall id, true = beq_id id id.\nProof.\n  intros [n]. simpl. rewrite <- beq_nat_refl.\n  reflexivity. Qed.\n\n(** The following useful property of [beq_id] follows from an\n    analogous lemma about numbers: *)\n\nTheorem beq_id_true_iff : forall id1 id2 : id,\n  beq_id id1 id2 = true <-> id1 = id2.\nProof.\n   intros [n1] [n2].\n   unfold beq_id.\n   rewrite beq_nat_true_iff.\n   split.\n   - (* -> *) intros H. rewrite H. reflexivity.\n   - (* <- *) intros H. inversion H. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This useful variant follows just by rewriting: *)\n\nTheorem false_beq_id : forall x y : id,\n   x <> y\n   -> beq_id x y = false.\nProof.\n  intros x y. rewrite beq_id_false_iff.\n  intros H. apply H. Qed.\n\n(* ###################################################################### *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about their behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps.\n\n    We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A:Type) := id -> A.\n\n(** Intuitively, a total map over an element type [A] _is_ just a\n    function that can be used to look up [id]s, yielding [A]s.\n\n    The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any id. *)\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : id) (v : A) :=\n  fun x' => if beq_id x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming.\n    The [t_update] function takes a _function_ [m] and yields a new\n    function [fun x' => ...] that behaves like the desired map.\n\n    For example, we can build a map taking [id]s to [bool]s, where [Id\n    3] is mapped to [true] and every other key is mapped to [false],\n    like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) (Id 1) false)\n           (Id 3) true.\n\n(** This completes the definition of total maps.  Note that we don't\n    need to define a [find] operation because it is just function\n    application! *)\n\nExample update_example1 : examplemap (Id 0) = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap (Id 1) = false.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap (Id 2) = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap (Id 3) = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental\n    facts about how they behave.  Even if you don't work the following\n    exercises, make sure you thoroughly understand the statements of\n    the lemmas!  (Some of the proofs require the functional\n    extensionality axiom discussed in the [Logic] chapter, which is\n    also included in the standard library.) *)\n\n(** **** Exercise: 2 stars, optional (t_update_eq)  *)\n(** First, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall A (m: total_map A) x v,\n  (t_update m x v) x = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_neq)  *)\n(** On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (X:Type) v x1 x2\n                         (m : total_map X),\n  x1 <> x2 ->\n  (t_update m x1 v) x2 = m x2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_shadow)  *)\n(** If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    t_update (t_update m x v1) x v2\n  = t_update m x v2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n    the reflection idioms introduced in chapter [IndProp].  We begin\n    by proving a fundamental _reflection lemma_ relating the equality\n    proposition on [id]s with the boolean function [beq_id]. *)\n\n(** **** Exercise: 2 stars (beq_idP)  *)\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma beq_idP : forall x y, reflect (x = y) (beq_id x y).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now, given [id]s [x1] and [x2], we can use the [destruct (beq_idP\n    x1 x2)] to simultaneously perform case analysis on the result of\n    [beq_id x1 x2] and generate hypotheses about the equality (in the\n    sense of [=]) of [x1] and [x2]. *)\n\n(** **** Exercise: 2 stars (t_update_same)  *)\n(** Using the example in chapter [IndProp] as a template, use\n    [beq_idP] to prove the following theorem, which states that if we\n    update a map to assign key [x] the same value as it already has in\n    [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall X x (m : total_map X),\n  t_update m x (m x) = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (t_update_permute)  *)\n(** Use [beq_idP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n    (t_update (t_update m x2 v2) x1 v1)\n  = (t_update (t_update m x1 v1) x2 v2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A:Type} (m : partial_map A)\n                  (x : id) (v : A) :=\n  t_update m x (Some v).\n\n(** We can now lift all of the basic lemmas about total maps to\n    partial maps.  *)\n\nLemma update_eq : forall A (m: partial_map A) x v,\n  (update m x v) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (X:Type) v x1 x2\n                       (m : partial_map X),\n  x2 <> x1 ->\n  (update m x2 v) x1 = m x1.\nProof.\n  intros X v x1 x2 m H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall A (m: partial_map A) v1 v2 x,\n  update (update m x v1) x v2 = update m x v2.\nProof.\n  intros A m v1 v2 x1. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall X v x (m : partial_map X),\n  m x = Some v ->\n  update m x v = m.\nProof.\n  intros X v x m H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (X:Type) v1 v2 x1 x2\n                                (m : partial_map X),\n  x2 <> x1 ->\n    (update (update m x2 v2) x1 v1)\n  = (update (update m x1 v1) x2 v2).\nProof.\n  intros X v1 v2 x1 x2 m. unfold update.\n  apply t_update_permute.\nQed.\n\n(** $Date: 2015-12-11 17:17:29 -0500 (Fri, 11 Dec 2015) $ *)\n\n", "meta": {"author": "perng", "repo": "proof", "sha": "bf181860d43bffdc67f7cd52269518f5fcaf27f1", "save_path": "github-repos/coq/perng-proof", "path": "github-repos/coq/perng-proof/proof-bf181860d43bffdc67f7cd52269518f5fcaf27f1/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.8976952845805988, "lm_q1q2_score": 0.711967481330661}}
{"text": "(** Proof for the fact that square root of 2 is irrational. **)\n\nRequire Import Reals.Reals.\nRequire Import Bool.\n(* Require Import Natural.Peano.NPeano.\n*)\n\n(* Count tailing zeros for positive type. *)\nFixpoint ctz_Pos (x : positive) : nat :=\n  match x with\n    | xH   => O                            (* 1 *)\n    | xO t => S (ctz_Pos t)   (* t ~ 0 *)\n    | xI t => O                            (* t ~ 1 *)\n  end.\n\n(* Lift to Z. *)\nDefinition ctz_Z (x : Z) : nat :=\n  match x with\n    | Z0     => O\n    | Zpos t => ctz_Pos t\n    | Zneg t => ctz_Pos t\n  end.\n\n(* If x = a * 2^k, then 2*x = a * 2^(k+1). *)\nLemma double_inc_ctz :\n  forall x, (x <> 0%Z) -> ctz_Z (2 * x) = S (ctz_Z x).\nProof.\n  destruct x; intuition || intro; reflexivity.\nQed.\n\n(* For a suqare number, even_repeat(x) must be even. *)\nLemma square_ctz_even :\n  forall x : Z, Nat.even (ctz_Z (x * x)) = true.\nProof.\n  (* At first, prove the positive case. *)\n  assert (hypothesis_positive : forall k : positive, Nat.even (ctz_Pos (k * k)) = true).\n  + induction k.\n    - reflexivity.\n    - simpl; rewrite Pos.mul_comm; simpl; assumption.\n    - reflexivity.\n  + destruct x; simpl; rewrite hypothesis_positive || idtac; reflexivity.\nQed.\n\nLemma cannot_both_even :\n  forall x, Nat.even x = negb (Nat.even (S x)).\nProof.\n  induction x.\n  + reflexivity.\n  + simpl (Nat.even (S (S x))).\n    rewrite IHx; rewrite negb_involutive; reflexivity.\nQed.\n\nLemma sqrt_mult_sqrt_eq_n :\n  forall x : R, (0 <= x)%R -> (sqrt x * sqrt x)%R = x.\nProof.\n  apply sqrt_def.\nQed.\n\nDefinition irrational (x : R) : Prop :=\n  ~ exists p q : Z, (q > 0)%Z /\\ (IZR p / IZR q)%R = x.\n\nTheorem sqrt_2_irrational :\n  irrational (sqrt 2%R)%R.\nProof.\n  unfold irrational.\n  (* Get two hypotheses, and now we need to find the contradiction (proof \"False\"). *)\n  intros [p [q [q_gt_0_Z p'q_eq_sqrt_2_R]]].\n\n  (* To be proved: \"p*p = 2*q*q\". *)\n\n  assert (q_gt_0_R : (IZR q > 0)%R).\n    replace 0%R with (IZR 0).\n    apply Rlt_gt; apply IZR_lt; auto with zarith.\n    reflexivity.\n\n  assert (p_eq_sqrt_2_q_R : (IZR p = sqrt 2 * IZR q)%R).\n    rewrite <- p'q_eq_sqrt_2_R.\n    field; apply Rgt_not_eq; apply q_gt_0_R.\n\n  assert (pp_eq_2qq_R : (IZR p * IZR p = (sqrt 2 * IZR q) * (sqrt 2 * IZR q))%R).\n    rewrite <- p_eq_sqrt_2_q_R; reflexivity. (* Or use \"congruence\". *)\n\n  assert (pp_eq_2qq_Z : (p * p = 2 * q * q)%Z).\n    replace ((sqrt 2 * IZR q) * (sqrt 2 * IZR q))%R\n      with ((sqrt 2 * sqrt 2) * IZR q * IZR q)%R\n      in pp_eq_2qq_R\n      by ring.\n    rewrite sqrt_def in pp_eq_2qq_R\n      by auto with real.\n    replace 2%R with (IZR 2) in pp_eq_2qq_R\n      by reflexivity.\n    repeat rewrite <- mult_IZR in pp_eq_2qq_R.\n    apply eq_IZR; assumption.\n\n  (* Counting tailing zeros for \"p*p\" and \"q*q\". *)\n\n  assert (ctz_p : Nat.even (ctz_Z (p * p)) = true).\n    apply square_ctz_even.\n  assert (ctz_q : Nat.even (ctz_Z (q * q)) = true).\n    apply square_ctz_even.\n\n  assert (ctz_p_eq_S_ctz_q : ctz_Z (p*p) = S (ctz_Z (q * q))).\n    rewrite <- double_inc_ctz.\n    rewrite pp_eq_2qq_Z; rewrite Z.mul_assoc; reflexivity.\n    assert (q*q > 0)%Z.\n      auto with zarith.\n    auto with zarith.\n\n  rewrite ctz_p_eq_S_ctz_q in ctz_p.\n  rewrite cannot_both_even in ctz_q.\n  rewrite ctz_p in ctz_q; inversion ctz_q.\nQed.\n\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/sqrt-2-irrational/sqrt_2_irrational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7119674785930101}}
{"text": "Require Export Subbases.\nRequire Export Relation_Definitions_Implicit.\nRequire Export SeparatednessAxioms.\n\nSection OrderTopology.\n\nVariable X:Type.\nVariable R:relation X.\nHypothesis R_ord: order R.\n\nInductive order_topology_subbasis : Family X :=\n  | intro_lower_interval: forall x:X, In order_topology_subbasis [ y:X | R y x /\\ y <> x ]\n  | intro_upper_interval: forall x:X, In order_topology_subbasis [ y:X | R x y /\\ y <> x ].\n\nDefinition OrderTopology : TopologicalSpace :=\n  Build_TopologicalSpace_from_subbasis X order_topology_subbasis.\n\nSection if_total_order.\n\nHypothesis R_total: forall x y:X, R x y \\/ R y x.\n\nLemma lower_closed_interval_closed: forall x:X,\n  closed [ y:X | R y x ] (X:=OrderTopology).\nProof.\nintro.\nred.\nmatch goal with |- open ?U => cut (U = interior U) end.\nintro.\nrewrite H; apply interior_open.\napply Extensionality_Ensembles; split.\n2:apply interior_deflationary.\nintros y ?.\nred in H.\nred in H.\nassert (R x y).\ndestruct (R_total x y); trivial.\ncontradiction H.\nconstructor; trivial.\nexists ([z:X | R x z /\\ z <> x]).\nconstructor; split.\napply (Build_TopologicalSpace_from_subbasis_subbasis\n  _ order_topology_subbasis).\nconstructor.\nred; intros z ?.\ndestruct H1.\ndestruct H1.\nintro.\ndestruct H3.\ncontradiction H2.\napply (ord_antisym R_ord); trivial.\nconstructor.\nsplit; trivial.\nintro.\ncontradiction H.\nconstructor.\ndestruct H1; apply (ord_refl R_ord).\nQed.\n\nLemma upper_closed_interval_closed: forall x:X,\n  closed [y:X | R x y] (X:=OrderTopology).\nProof.\nintro.\nred.\nmatch goal with |- open ?U => cut (U = interior U) end.\nintro.\nrewrite H; apply interior_open.\napply Extensionality_Ensembles; split.\n2:apply interior_deflationary.\nintros y ?.\nred in H.\nred in H.\nassert (R y x).\ndestruct (R_total x y); trivial.\ncontradiction H.\nconstructor; trivial.\nexists ([z:X | R z x /\\ z <> x]).\nconstructor; split.\napply (Build_TopologicalSpace_from_subbasis_subbasis\n  _ order_topology_subbasis).\nconstructor.\nred; intros z ?.\ndestruct H1.\ndestruct H1.\nintro.\ndestruct H3.\ncontradiction H2.\napply (ord_antisym R_ord); trivial.\nconstructor.\nsplit; trivial.\nintro.\ncontradiction H.\nconstructor.\ndestruct H1; apply (ord_refl R_ord).\nQed.\n\nLemma order_topology_Hausdorff: Hausdorff OrderTopology.\nProof.\nred.\nmatch goal with |- forall x y:point_set OrderTopology, ?P =>\n  cut (forall x y:point_set OrderTopology, R x y -> P)\n  end.\nintros.\ndestruct (R_total x y).\nexact (H x y H1 H0).\nassert (y <> x).\nauto.\ndestruct (H y x H1 H2) as [V [U [? [? [? []]]]]].\nexists U; exists V; repeat split; trivial.\ntransitivity (Intersection V U); trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H8; constructor; trivial.\ndestruct H8; constructor; trivial.\n\nintros.\npose proof (Build_TopologicalSpace_from_subbasis_subbasis\n  _ order_topology_subbasis).\ndestruct (classic (exists z:X, R x z /\\ R z y /\\ z <> x /\\ z <> y)).\ndestruct H2 as [z [? [? []]]].\nexists ([w:X | R w z /\\ w <> z]);\nexists ([w:X | R z w /\\ w <> z]).\nrepeat split; trivial.\napply H1.\nconstructor.\napply H1.\nconstructor.\nauto.\nauto.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\ndestruct H6.\ndestruct H7.\ndestruct H6.\ndestruct H7.\ncontradiction H8.\napply (ord_antisym R_ord); trivial.\ndestruct H6.\n\nexists ([w:X | R w y /\\ w <> y]);\nexists ([w:X | R x w /\\ w <> x]).\nrepeat split.\napply H1.\nconstructor.\napply H1.\nconstructor.\ntrivial.\ntrivial.\ntrivial.\nauto.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H3.\ndestruct H3.\ndestruct H4.\ndestruct H3.\ndestruct H4.\ncontradiction H2.\nexists x0; repeat split; trivial.\ndestruct H3.\nQed.\n\nEnd if_total_order.\n\nEnd OrderTopology.\n\nArguments OrderTopology [X].\n", "meta": {"author": "verimath", "repo": "topology", "sha": "9405aaf18d99c718769f1d2af8e030a902687837", "save_path": "github-repos/coq/verimath-topology", "path": "github-repos/coq/verimath-topology/topology-9405aaf18d99c718769f1d2af8e030a902687837/src/top/OrderTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7119674719353913}}
{"text": "(* Chap 1 Basics *)\n(* Chap 1.1 Data and Functions *)\n(* Days of the week *)\nInductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\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\nCompute (next_weekday friday).\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\n(* Booleans *)\nInductive bool : Type :=\n  | true\n  | false.\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  | false => false\n  | true => b2\n  end.\n\nDefinition orb (b1: bool) (b2: bool) : bool :=\n  match b1 with\n  | true => true\n  | false => b2\n  end.\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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition nandb (b1: bool) (b2: bool) : bool := negb (b1 && b2).\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\nDefinition andb3 (b1: bool) (b2: bool) (b3: bool) : bool := (b1 && b2 && b3).\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\n(* Types *)\nCheck true.\nCheck (negb true).\nCheck negb.\n\n(* New Types from Old *)\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p: rgb).\n\nDefinition monochrome (c: color) : bool :=\n  match c with\n  | black => true\n  | white => true\n  | primary q => false\n  end.\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(* Note: _ is a shorthand for primary applied \n   to any rgb constructor except red. *)\n\n(* Tuples *)\nInductive bit : Type :=\n  | B0\n  | B1.\n\nInductive nybble : Type :=\n  | bits (b0 b1 b2 b3: bit).\n\nCheck (bits B1 B0 B1 B0).\n\nDefinition all_zero (nb: nybble) : bool := \n  match nb with\n  | (bits B0 B0 B0 B0) => true\n  | _ => false\n  end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\nCompute (all_zero (bits B0 B0 B0 B0)).\n\n\n(* Modules *)\n(* Note: like namespace in Cpp *)\n\nModule NatPlayground.\n\n(* Numbers *)\nInductive nat : Type :=\n  | O\n  | S (n: nat).\n\nInductive nat' : Type :=\n  | stop\n  | tick (foo: nat').\n(* Note: these shows that O and S have no \n   special meanings, they are just symbols. *)\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\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\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 1 = true.\nProof. simpl. reflexivity. Qed.\nExample test_oddb2: oddb 4 = false.\nProof. simpl. reflexivity. Qed.\n\nModule NatPlayground2.\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\nFixpoint mult (n m: nat) : nat :=\n  match n with\n  | O => O\n  | S n' => plus m (mult n' m)\n  end.\n(* Note: (n m: nat) equals to (n: nat) (m: nat) *)\n\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.\n\nEnd NatPlayground2.\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\n(* Exercise factorial *)\nFixpoint factorial (n: nat) : nat :=\n  match n with\n  | O => S O\n  | S n' => mult (S n') (factorial n')\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 eqb (n m: nat) : bool :=\n  match n with\n  | O =>\n    match m with\n    | O => true\n    | _ => false\n    end\n  | S n' =>\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\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\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\nExample test_leb3': (4 <=? 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Exercise ltb *)\n\nDefinition ltb (n m : nat) : bool :=\n  (leb n m) && (negb (eqb n m)).\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1: (ltb 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_ltb2: (ltb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ltb3: (ltb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\n(* Chap 1.2 Proof by Simplification *)\nTheorem plus_O_n: forall n: nat, 0 + n = n.\nProof.\n  intros n.\n  simpl.   (* Note: sometimes we don't need simpl. *)\n  reflexivity.\nQed.\n\nTheorem plus_1_l: forall n: nat, 1 + n = S n.\nProof.\n  intros n.\n  reflexivity.\nQed.\n\nTheorem mult_0_l: forall n:nat, 0 * n = 0.\nProof.\n  intros n.\n  reflexivity.\nQed.\n(* Note: _l means on the left (is L not one) *)\n\n(* Chap 1.3 Proof by rewriting *)\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\nTheorem plus_id_exercise: forall n m o: nat,\n  n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o H1 H2.\n  rewrite -> H1.\n  rewrite -> H2.\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_O_n.\n  reflexivity. \nQed.\n\n(* Exercise: mult_S_1 *)\nTheorem mult_S_1: forall n m: nat,\n  m = S n -> m * (1 + n) = m * m.\nProof.\n  intros n m.\n  intros H.\n  rewrite -> plus_1_l.\n  rewrite <- H.\n  reflexivity.\nQed.\n\n(* Chap 1.4 Proof by Case Analysis *)\nTheorem plus_1_neq_0: forall n: nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros n.\n  destruct n.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem negb_involutive: forall b: bool,\n  negb (negb b) = b.\nProof.\n  intros b.\n  destruct b.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commutative: forall b c, 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 andb3_exchange:\n  forall b c d, 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  - reflexivity.\nQed.\n\nTheorem plus_1_neq_0': forall n: nat,\n  (n + 1) =? 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n(* Note: means exactly same as:\n  intros n'.\n  destruct n' as [|n].*)\n\nTheorem andb_commutative'':\n  forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* Exercise andb_true_elim2 *)\nTheorem andb_true_elim2: forall b c: bool,\n  andb b c = true -> c = true.\nProof.\n  intros b c.\n  destruct c.\n  - reflexivity.\n  - intros H. \n    rewrite <- H. \n    rewrite -> andb_commutative. \n    reflexivity.\nQed.\n\n(* Exercise zero_nbeq_plus_1 *)\nTheorem zero_nbeq_plus_1: forall n: nat,\n  0 =? (n + 1) = false.\nProof.\n  intros n.\n  destruct n.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* Chap 1.5 More Exercises *)\n\nTheorem identity_fn_applied_twice:\n  forall (f: bool -> bool), \n  (forall (x: bool), f x = x) -> forall (b: bool), f (f b) = b.\nProof.\n  intros f.\n  intros H.\n  intros b.\n  rewrite -> H.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nTheorem andb_eq_orb:\n  forall (b c: bool),\n  (andb b c = orb b c) -> b = c.\nProof.\n  intros b c.\n  destruct b.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\nQed.\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\nExample test_bin_inc1: incr Z = B Z.\nProof. reflexivity. Qed.\nExample test_bin_inc2: incr (A (A (B Z))) = (B (A (B Z))).\nProof. reflexivity. Qed.\nExample test_bin_inc3: incr (B (B (B Z))) = (A (A (A (B Z)))).\nProof. reflexivity. Qed.\n\nFixpoint bin_to_nat' (m: bin) : nat :=\n  match m with\n  | Z => O\n  | A m => plus (bin_to_nat' m) (bin_to_nat' m)\n  | B m => plus (plus (bin_to_nat' m) (bin_to_nat' m)) (S O)\n  end.\n(* Original Form: too stupid. *)\n\nFixpoint bin_to_nat (m: bin) : nat :=\n  match m with\n  | Z => 0\n  | A m => 2 * (bin_to_nat m)\n  | B m => 1 + 2 * (bin_to_nat m)\n  end.\n\nExample test_bin_to_nat1: bin_to_nat (A (A (A (B Z)))) = 8.\nProof. reflexivity. Qed.\nExample test_bin_to_nat2: bin_to_nat (B (A (B Z))) = 5.\nProof. reflexivity. Qed.", "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/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7119528301566829}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import collect_operator.\nRequire Import direct_product.\nRequire Import binary_relation.\n\n(* 写像のグラフは集合である.\n   グラフは2つの集合の直積集合の部分集合であり,第一射影の要素に対して第二射影の要素がただ一つ決まる. *)\n(* 写像のグラフが満たさないと行けない条件 *)\nDefinition ConditionOfGraphOfMapping {U:Type} (G:TypeOfDirectProduct U) (A B:Collection U) :=\n  G ⊂ A × B /\\ forall x:U, x ∈ A -> exists! y:U, <|x,y|> ∈ G.\n\nDefinition MappingFunction {U:Type} (f: U -> U) (A B:Collection U) :=\n  forall x:U, x ∈ A -> exists y:U, y = f x /\\ y ∈ B.\n\n(* 関数が与えられると決定されるGraph *)\nDefinition GraphOfFunction {U:Type} (f: U -> U) (A B:Collection U) :\n  TypeOfDirectProduct U := GraphOfBinaryRelation (fun (x y:U) => y = f x) A B.\n\nDefinition IdentityFunction U : U -> U := fun x:U => x.\n\nDefinition GraphOfIdentity {U:Type} (X:Collection U) : TypeOfDirectProduct U :=\n  GraphOfFunction (IdentityFunction U) X X.\n\nDefinition CompoundFunction {U:Type} (g f: U -> U) : U -> U :=\n  fun x:U => g ( f x ).\n\n(* Unicode ◦ :25E6*)\nNotation \"g ◦ f\" :=  (CompoundFunction g f) (right associativity, at level 33).\n\nAxiom AxiomOfFuncionalExtensionality: forall (U:Type) (f g :U -> U),\n    (forall x:U, f x = g x) -> f = g.\n\nSection Mapping.\n  Variable U:Type.\n\n  Theorem function_determine_domain:\n    forall {f:U -> U} (A B:Collection U) (G:TypeOfDirectProduct U),\n      G = GraphOfFunction f A B -> 𝕯( G ) ⊂ A.\n  Proof.\n    move => f A B G HG.\n    move: (relation_determine_domain U (fun (x y:U) => y = f x) A B G).\n    apply.\n    rewrite HG.\n    reflexivity.\n  Qed.\n\n  Theorem function_determine_range:\n    forall {f:U -> U} (A B:Collection U) (G:TypeOfDirectProduct U),\n      G = GraphOfFunction f A B -> 𝕽( G ) ⊂ B.\n  Proof.\n    move => f A B G HG.\n    move: (relation_determine_range U (fun (x y:U) => y = f x) A B G).\n    apply.\n    rewrite HG.\n    reflexivity.\n  Qed.\n\n  Theorem direct_product_included_graph_of_function:\n    forall (f:U -> U) (A B:Collection U) (G:TypeOfDirectProduct U),\n      G = GraphOfFunction f A B -> G ⊂ A × B.\n  Proof.\n    move => A B G.\n    apply graph_of_correspondence_is_subset_of_direct_product.\n  Qed.\n\n  Lemma rewrite_function_range:\n    forall (f:U -> U) (A B:Collection U),\n      (forall x:U, exists y:U, y = f x /\\ <|x, y|> ∈ A × B) ->\n      (forall x:U, exists y:U, x ∈ A /\\ y = f x /\\ y ∈ B).\n  Proof.\n    move => f A B H x.\n    move: (H x) => Hx.\n    inversion Hx as [y [Hf HAB]].\n    exists y.\n    apply ordered_pair_in_direct_product_to_in_and in HAB.\n    inversion HAB as [HA HB].\n    split;[trivial|split; trivial].\n  Qed.\n\n  Theorem function_satisfies_graph_of_mapping:\n    forall (f:U -> U) (A B:Collection U) (G:TypeOfDirectProduct U),\n      (forall x:U, exists y:U, y = f x /\\ <|x, y|> ∈ A × B) ->\n      G = GraphOfFunction f A B ->\n      ConditionOfGraphOfMapping G A B.\n  Proof.\n    move => f A B G HF HG.\n    split.\n    +apply (direct_product_included_graph_of_function f). by [].\n    +move => x HA.\n     move: (HF x) => HFx.\n     inversion HFx as [y []].\n     exists y.\n     split.\n     rewrite HG.\n     split.\n     exists x.\n     exists y.\n     split; [reflexivity|split;trivial].\n     move => z HG0.\n     rewrite HG in HG0.\n     inversion HG0.\n     inversion H1 as [x0 [z0 [Heqz [Hfz HABz]]]].\n     apply ordered_pair_to_and in Heqz.\n     inversion Heqz.\n     rewrite -H3 -H4 in Hfz.\n     rewrite -Hfz in H.\n     trivial.\n  Qed.\n\n  Theorem image_of_function_of_domain_is_empty_is_empty:\n    forall (f:U -> U) (A B:Collection U) (G:TypeOfDirectProduct U),\n      G = GraphOfFunction f A B -> 𝕴𝖒( G , `Ø` ) = `Ø`.\n  Proof.\n    move => f A B G HG.\n    apply (image_of_domain_is_empty_is_empty U (fun x y:U => y = f x) A B).\n    rewrite HG.\n    reflexivity.\n  Qed.\n\n  Theorem condition_of_image_of_function_is_not_empty:\n    forall (f:U -> U) (A B C:Collection U) (G:TypeOfDirectProduct U),\n      MappingFunction f A B ->\n      C <> `Ø` -> C ⊂ A ->\n      G = GraphOfFunction f A B ->\n      exists (y:U), y ∈ 𝕴𝖒( G , C ).\n  Proof.\n    move => f A B C G HF HNEC HCA HG.\n    apply: (condition_of_image_of_binary_relation_is_not_empty U (fun x y:U => y = f x) A B).\n    apply HF.\n    apply HNEC.\n    apply HCA.\n    trivial.\n  Qed.\n\n  Theorem mapping_function_to_singleton_image:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U) (x y:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      x ∈ X ->\n      y = f x ->\n      {|y|} = 𝕴𝖒( F , {|x|} ).\n  Proof.\n    move => f X Y F x y Hf HF HxX Hyfx.\n    have L1: exists y:U, y = f x /\\ y ∈ Y.\n    apply Hf.\n    trivial.\n    apply mutally_included_to_eq.\n    split.\n    +move => y0 H.\n     apply singleton_to_eq in H.\n     split.\n     exists x.\n     split.\n     apply eq_to_singleton.\n     reflexivity.\n     rewrite H.\n     rewrite HF.\n     split.\n     inversion L1 as [y1].\n     exists x.\n     exists y.\n     split.\n     reflexivity.\n     split.\n     trivial.\n     apply ordered_pair_in_direct_product_iff_in_and.\n     split.\n     trivial.\n     inversion H0.\n     rewrite H1 in H2.\n     rewrite Hyfx.\n     assumption.\n    +move => y0 H.\n     inversion H as [y1].\n     inversion H0 as [x0].\n     inversion H2.\n     apply singleton_to_eq in H3.\n     rewrite H3 in H4.\n     rewrite HF in H4.\n     inversion H4 as [Z' [x1 [y2]]].\n     inversion H5.\n     apply ordered_pair_to_and in H7.\n     inversion H7.\n     rewrite -H10 -H9 in H8.\n     inversion H8.\n     rewrite H11.\n     apply eq_to_singleton.\n     apply eq_sym.\n     assumption.\n  Qed.\n\n  Theorem singleton_image_to_mapping_function:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U) (x y:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      x ∈ X ->\n      {|y|} = 𝕴𝖒( F , {|x|} ) ->\n      y = f x.\n  Proof.\n    move => f X Y F x y Hf HF HxX H.\n    have L1: exists y:U, y = f x /\\ y ∈ Y.\n    apply Hf.\n    trivial.\n    apply mutally_included_iff_eq in H.\n    inversion H.\n    inversion L1 as [y0].\n    inversion H2.\n    rewrite -H3.\n    apply eq_sym.\n    apply singleton_to_eq.\n    apply: (H1 y0).\n    split.\n    exists x.\n    split.\n    apply singleton_iff_eq.\n    reflexivity.\n    rewrite HF.\n    split.\n    exists x.\n    exists y0.\n    split.\n    reflexivity.\n    split.\n    trivial.\n    apply ordered_pair_in_direct_product_iff_in_and.\n    split; assumption.\n  Qed.\n\n  Theorem mapping_function_iff_singleton_image:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U) (x y:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      x ∈ X ->\n      y = f x <->\n      {|y|} = 𝕴𝖒( F , {|x|} ).\n  Proof.\n    move => f X Y F x y Hf HF HxX.\n    rewrite /iff; split;\n      [apply: (mapping_function_to_singleton_image f X Y)|\n       apply: (singleton_image_to_mapping_function f X Y)];\n      trivial;\n      trivial;\n      assumption.\n  Qed.\n\n  Theorem singleton_domain_image_eq_to_function_eq:\n    forall (f g:U -> U) (X Y:Collection U) (F G:TypeOfDirectProduct U) (x:U),\n      MappingFunction f X Y ->\n      MappingFunction g X Y ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g X Y ->\n      x ∈ X ->\n      𝕴𝖒( F , {|x|} ) = 𝕴𝖒( G , {|x|} ) ->\n      f x = g x.\n  Proof.\n    move => f g X Y F G x Hf Hg HF HG HxX HI.\n    have L1: exists y:U, y = f x /\\ y ∈ Y.\n    apply Hf.\n    trivial.\n    have L2: exists y:U, y = g x /\\ y ∈ Y.\n    apply Hg.\n    trivial.\n    inversion L1 as [y0].\n    inversion L2 as [y1].\n    inversion H.\n    inversion H0.\n    apply eq_sym.\n    rewrite -H3.\n    apply: (singleton_image_to_mapping_function f X Y F x y1);trivial.\n    rewrite HI.\n    apply: (mapping_function_to_singleton_image g X Y G x y1);trivial.\n  Qed.\n\n  Theorem function_eq_to_singleton_domain_image_eq:\n    forall (f g:U -> U) (X Y:Collection U) (F G:TypeOfDirectProduct U) (x:U),\n      MappingFunction f X Y ->\n      MappingFunction g X Y ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g X Y ->\n      x ∈ X ->\n      f x = g x ->\n      𝕴𝖒( F , {|x|} ) = 𝕴𝖒( G , {|x|} ).\n  Proof.\n    move => f g X Y F G x Hf Hg HF HG HxX Heq.\n    apply mutally_included_to_eq.\n    split => y H;\n               inversion H as [y0 [x0]];\n               inversion H0;\n               apply singleton_to_eq in H2;\n               rewrite H2 in H3;[rewrite HF in H3|\n                                 rewrite HG in H3];\n               split;\n               exists x; split.\n    +apply singleton_iff_eq;reflexivity.\n     rewrite HG.\n     inversion H3.\n     inversion H4 as [x1 [y1]].\n     inversion H6.\n     apply ordered_pair_to_and in H7.\n     inversion H7.\n     rewrite -H9 -H10 in H8.\n     split.\n     exists x.\n     exists y.\n     split;[reflexivity|rewrite Heq in H8;assumption].\n    +apply singleton_iff_eq;reflexivity.\n     rewrite HF.\n     inversion H3.\n     inversion H4 as [x1 [y1]].\n     inversion H6.\n     apply ordered_pair_to_and in H7.\n     inversion H7.\n     rewrite -H9 -H10 in H8.\n     split.\n     exists x.\n     exists y.\n     split;[reflexivity|rewrite -Heq in H8;assumption].\n  Qed.\n\n  Theorem singleton_domain_image_eq_iff_function_eq:\n    forall (f g:U -> U) (X Y:Collection U) (F G:TypeOfDirectProduct U) (x:U),\n      MappingFunction f X Y ->\n      MappingFunction g X Y ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g X Y ->\n      x ∈ X ->\n      𝕴𝖒( F , {|x|} ) = 𝕴𝖒( G , {|x|} ) <->\n      f x = g x.\n  Proof.\n    move => f g X Y F G x Hf Hg HF HG HxX.\n    rewrite /iff.\n    split;[apply (singleton_domain_image_eq_to_function_eq f g X Y)|\n           apply (function_eq_to_singleton_domain_image_eq f g X Y)];\n    trivial;\n    trivial;\n    trivial;\n    trivial.\n  Qed.\n\n  Theorem graph_of_function_eq_to_function_eq:\n    forall (f g:U -> U) (X Y:Collection U) (F G:TypeOfDirectProduct U),\n      MappingFunction f X Y ->\n      MappingFunction g X Y ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g X Y ->\n      F = G -> (forall x:U, x ∈ X -> f x = g x).\n  Proof.\n    move => f g X Y F G Hf Hg HF HG Heq x HxX.\n    apply (singleton_domain_image_eq_to_function_eq f g X Y F G);trivial.\n    rewrite Heq.\n    reflexivity.\n  Qed.\n\n  Theorem function_eq_to_graph_of_function_eq:\n    forall (f g:U -> U) (X Y:Collection U) (F G:TypeOfDirectProduct U),\n      MappingFunction f X Y ->\n      MappingFunction g X Y ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g X Y ->\n      (forall x:U, x ∈ X -> f x = g x) ->\n      F = G.\n  Proof.\n    move => f g X Y F G Hf Hg HF HG Heq.\n    rewrite HF HG.\n    apply mutally_included_to_eq.\n    split => Z' H; inversion H as [Z0' [x0 [y0]]];\n               [inversion H0 as [HZ0' [Hy0fx0 HX0Y0]]|\n                inversion H0 as [HZ0' [Hy0gx0 HX0Y0]]];\n               apply ordered_pair_in_direct_product_iff_in_and in HX0Y0;\n               inversion HX0Y0;\n               split;\n               exists x0;\n               exists y0;\n               move: (Heq x0) => Heqx0;\n                                   apply Heqx0 in H2;\n                                   [rewrite -H2|rewrite H2];trivial.\n  Qed.\n\n  Theorem graph_of_function_eq_iff_function_eq:\n    forall (f g:U -> U) (X Y:Collection U) (F G:TypeOfDirectProduct U),\n      MappingFunction f X Y ->\n      MappingFunction g X Y ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g X Y ->\n      F = G <-> (forall x:U, x ∈ X -> f x = g x).\n  Proof.\n    move => f g X Y F G Hf Hg HF HG.\n    rewrite /iff.\n    split;[apply (graph_of_function_eq_to_function_eq f g X Y F G)|\n           apply (function_eq_to_graph_of_function_eq f g X Y F G)];\n    trivial.\n  Qed.\n\n  Theorem singleton_image_to_ordered_pair_in_graph:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U) (x y:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      x ∈ X ->\n      {| y |} = 𝕴𝖒( F , {| x |} ) ->\n      <|x,y|> ∈ F.\n  Proof.\n    move => f X Y F x y Hf HF HxX HI.\n    have L1: exists y:U, y = f x /\\ y ∈ Y.\n    apply Hf.\n    trivial.\n    inversion L1 as [y0 [Hy0fx HY]].\n    apply (singleton_image_to_mapping_function f X Y F) in HI.\n    rewrite HF.\n    split.\n    exists x.\n    exists y0.\n    rewrite -HI in Hy0fx.\n    rewrite Hy0fx.\n    rewrite Hy0fx in HY.\n    split;[reflexivity|split;[trivial|\n                              apply ordered_pair_in_direct_product_iff_in_and;\n                              split;\n                              trivial]].\n    trivial.\n    trivial.\n    assumption.\n  Qed.\n\n  Theorem ordered_pair_in_graph_to_singleton_image:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U) (x y:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      x ∈ X ->\n      <|x,y|> ∈ F ->\n      {| y |} = 𝕴𝖒( F , {| x |} ).\n  Proof.\n    move => f X Y F x y Hf HF HxX HoF.\n    have L1: exists y:U, y = f x /\\ y ∈ Y.\n    apply Hf.\n    trivial.\n    inversion L1 as [y0 [Hy0fx HY]].\n    apply (mapping_function_to_singleton_image f X Y F); trivial.\n    rewrite HF in HoF.\n    inversion HoF.\n    inversion H as [x1 [y1]].\n    inversion H1.\n    apply ordered_pair_to_and in H2.\n    inversion H2.\n    rewrite -H4 -H5 in H3.\n    apply H3.\n  Qed.\n\n  Theorem singleton_image_iff_ordered_pair_in_graph:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U) (x y:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      x ∈ X ->\n      {| y |} = 𝕴𝖒( F , {| x |} ) <->\n      <|x, y|> ∈ F.\n  Proof.\n    move => f X Y F x y Hf HF HxX.\n    rewrite /iff; split;\n      [apply (singleton_image_to_ordered_pair_in_graph f X Y F)|\n       apply (ordered_pair_in_graph_to_singleton_image f X Y F)];\n      trivial;\n      trivial;\n      assumption.\n  Qed.\n\n  Theorem singleton_image_is_unique:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U) (x y y':U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      x ∈ X ->\n      {|y|} = 𝕴𝖒( F , {|x|} ) /\\ {|y'|} = 𝕴𝖒( F , {|x|} ) ->\n      y = y'.\n  Proof.\n    move => f X Y F x y y' Hf HF HxX [Hy Hy'].\n    apply (singleton_image_to_mapping_function f X Y) in Hy;trivial.\n    apply (singleton_image_to_mapping_function f X Y) in Hy';trivial.\n    rewrite Hy Hy'.\n    reflexivity.\n  Qed.\n\n  Theorem cup_domain_is_cup_image_in_function:\n    forall (f:U -> U) (A B C D:Collection U) (G:TypeOfDirectProduct U),\n      G = GraphOfFunction f A B ->\n      𝕴𝖒( G , C ∪ D ) = 𝕴𝖒( G , C ) ∪ 𝕴𝖒( G , D ).\n  Proof.\n    move => f A B C D G HG.\n    apply (cup_domain_is_cup_image U (fun x y:U => y = f x) A B).\n    apply HG.\n  Qed.\n\n  Theorem image_of_correspondence_function_include_chain_image:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G GF:TypeOfDirectProduct U),\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      GF = GraphOfCompoundCorrespondence G F ->\n      𝕴𝖒( G ,  𝕴𝖒( F, X ) ) ⊂ 𝕴𝖒( GF, X ).\n  Proof.\n    move => f g X Y Z F G GF HF HG HGF z.\n    apply: (image_of_correspondence_include_chain_image\n              U (fun x y => y = f x) (fun y z => z = g y) X Y Z F G GF);trivial.\n  Qed.\n\n  Theorem chain_image_include_image_of_correspondence_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G GF:TypeOfDirectProduct U),\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      GF = GraphOfCompoundCorrespondence G F ->\n      𝕴𝖒( GF, X ) ⊂ 𝕴𝖒( G, 𝕴𝖒( F , X )).\n  Proof.\n    move => f g X Y Z F G GF HF HG HGF z.\n    apply: (chain_image_include_image_of_correspondence\n              U (fun x y => y = f x) (fun y z => z = g y) X Y Z F G GF); trivial.\n  Qed.\n\n  Theorem chain_image_is_image_of_correspondence_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G GF:TypeOfDirectProduct U),\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      GF = GraphOfCompoundCorrespondence G F ->\n      𝕴𝖒( G, 𝕴𝖒( F , X )) = 𝕴𝖒( GF, X ).\n  Proof.\n    move => f g X Y Z F G GF HF HG HGF.\n    apply (chain_image_is_image_of_correspondence U (fun x y => y = f x) (fun y z => z = g y) X Y Z F G GF);trivial.\n  Qed.\n\n  Theorem compound_graph_of_function_include_graph_of_compound_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      GraphOfFunction (CompoundFunction g f) X Z ⊂ G ⊙ F.\n  Proof.\n    move => f g X Y Z F G Hf HF HG Z' H.\n    inversion H as [Z0'].\n    inversion H0 as [x [z]].\n    inversion H2.\n    inversion H4.\n    split.\n    exists x.\n    exists z.\n    split;[trivial|].\n    apply ordered_pair_in_direct_product_iff_in_and in H6.\n    inversion H6.\n    apply Hf in H7.\n    inversion H7 as [y].\n    inversion H9.\n    exists y.\n    split;[rewrite HF|rewrite HG];split.\n    exists x.\n    exists y.\n    split;[reflexivity|split;\n                       [trivial|\n                        apply ordered_pair_in_direct_product_iff_in_and;\n                        split;[apply H6|trivial]]].\n    exists y.\n    exists z.\n    split;[reflexivity|split;\n                       [rewrite H10;trivial|\n                        apply ordered_pair_in_direct_product_iff_in_and;\n                        split;trivial]].\n  Qed.\n\n  Theorem graph_of_compound_function_include_compound_graph_of_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U),\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      G ⊙ F ⊂ GraphOfFunction (CompoundFunction g f) X Z.\n  Proof.\n    move => f g X Y Z F G HF HG Z' H.\n    inversion H as [Z0'].\n    inversion H0 as [x [z]].\n    inversion H2.\n    inversion H4 as [y].\n    inversion H5.\n    rewrite H3.\n    split.\n    exists x.\n    exists z.\n    split;[reflexivity|].\n    rewrite HF in H6.\n    rewrite HG in H7.\n    inversion H6 as [Y' [x0 [y0]]].\n    inversion H8.\n    inversion H11.\n    inversion H7.\n    inversion H7 as [Z1' [y1 [z1]]].\n    inversion H16.\n    inversion H19.\n    apply ordered_pair_to_and in H10.\n    inversion H10.\n    rewrite -H22 -H23 in H12.\n    apply ordered_pair_to_and in H18.\n    inversion H18.\n    rewrite -H24 -H25 in H20.\n    rewrite H12 in H20.\n    split.\n    trivial.\n    rewrite -H22 -H23 in H13.\n    rewrite -H24 -H25 in H21.\n    apply ordered_pair_in_direct_product_iff_in_and in H13.\n    apply ordered_pair_in_direct_product_iff_in_and in H21.\n    apply ordered_pair_in_direct_product_iff_in_and.\n    split;[apply H13|apply H21].\n  Qed.\n\n  Theorem compound_graph_of_function_eq_graph_of_compound_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      GraphOfFunction (CompoundFunction g f) X Z = G ⊙ F.\n  Proof.\n    move => f g X Y Z F G Hf HF HG.\n    apply mutally_included_iff_eq.\n    split;[apply (compound_graph_of_function_include_graph_of_compound_function f g X Y Z F G)|\n           apply (graph_of_compound_function_include_compound_graph_of_function f g X Y Z F G)];\n    trivial.\n  Qed.\n\n  Theorem compound_function_to_in_image_of_graph_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U) (x z:U),\n      MappingFunction f X Y ->\n      MappingFunction g Y Z ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      z = (CompoundFunction g f) x -> z ∈ 𝕴𝖒((GraphOfFunction (CompoundFunction g f) X Z), {|x|}).\n  Proof.\n    move => f g X Y Z F G x z Hf Hg HF HG HxX H.\n    split.\n    exists x.\n    split.\n    apply singleton_iff_eq.\n    reflexivity.\n    split.\n    exists x.\n    exists z.\n    split.\n    reflexivity.\n    split.\n    trivial.\n    apply ordered_pair_in_direct_product_iff_in_and.\n    split;[trivial|].\n    apply Hf in HxX.\n    inversion HxX as [y Hfx].\n    unfold MappingFunction in Hg.\n    inversion Hfx as [Hyfx HyY].\n    apply Hg in HyY.\n    inversion HyY as [z0].\n    rewrite Hyfx in H0.\n    inversion H0.\n    unfold CompoundFunction in H.\n    rewrite -H in H1.\n    rewrite -H1.\n    trivial.\n  Qed.\n\n  Theorem in_image_of_graph_function_to_compound_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G: TypeOfDirectProduct U) (x z:U),\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      z ∈ (𝕴𝖒((GraphOfFunction (CompoundFunction g f) X Z), {|x|})) -> z = (CompoundFunction g f) x.\n  Proof.\n    move => f g X Y Z F G x z HF HG HxX H.\n    inversion H as [z0].\n    inversion H0 as [x0].\n    inversion H2.\n    apply singleton_to_eq in H3.\n    rewrite H3 in H4.\n    inversion H4.\n    inversion H5 as [x1 [z1]].\n    inversion H7.\n    apply ordered_pair_to_and in H8.\n    inversion H8.\n    inversion H9.\n    rewrite H10 H11.\n    trivial.\n  Qed.\n\n  Theorem compound_function_iff_in_image_of_graph_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U) (x z:U),\n      MappingFunction f X Y ->\n      MappingFunction g Y Z ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      z = (g ◦ f) x <-> z ∈ 𝕴𝖒((GraphOfFunction (CompoundFunction g f) X Z), {|x|}).\n  Proof.\n    move => f g X Y Z F G x z Hf Hg HF HG HxX.\n    rewrite /iff.\n    split;[apply (compound_function_to_in_image_of_graph_function f g X Y Z F G)|\n           apply (in_image_of_graph_function_to_compound_function f g X Y Z F G)];\n    trivial.\n  Qed.\n\n  Theorem mapping_compound_function_to_singleton_image:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U) (x z:U),\n      MappingFunction f X Y ->\n      MappingFunction g Y Z ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      z = (g ◦ f) x ->\n      {|z|} = 𝕴𝖒( G ⊙ F , {|x|} ).\n  Proof.\n    move => f g X Y Z F G x z Hf Hg HF HG HxX Hgf.\n    rewrite -(compound_graph_of_function_eq_graph_of_compound_function f g X Y Z F G).\n    apply (mapping_function_iff_singleton_image (g ◦ f) X Z (GraphOfFunction (g ◦ f) X Z) x z).\n    move => x' Hx'X.\n    apply Hf in Hx'X.\n    inversion Hx'X as [y'].\n    inversion H.\n    apply Hg in H1.\n    inversion H1 as [z'].\n    inversion H2.\n    exists z'.\n    split.\n    rewrite H0 in H3.\n    trivial.\n    trivial.\n    reflexivity.\n    trivial.\n    trivial.\n    trivial.\n    trivial.\n    trivial.\n  Qed.\n\n  Theorem singleton_image_to_mapping_compound_function:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U) (x z:U),\n      MappingFunction f X Y ->\n      MappingFunction g Y Z ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      {|z|} = 𝕴𝖒( G ⊙ F , {|x|} ) ->\n      z = (g ◦ f) x.\n  Proof.\n    move => f g X Y Z F G x z Hf Hg HF HG HxX HI.\n    apply (singleton_image_to_mapping_function (g ◦ f) X Z (GraphOfFunction (g ◦ f) X Z) x z).\n    move => x' Hx'X.\n    apply Hf in Hx'X.\n    inversion Hx'X as [y'].\n    inversion H.\n    apply Hg in H1.\n    inversion H1 as [z'].\n    inversion H2.\n    exists z'.\n    rewrite H0 in H3.\n    split; trivial.\n    reflexivity.\n    trivial.\n    rewrite (compound_graph_of_function_eq_graph_of_compound_function f g X Y Z F G); trivial.\n  Qed.\n\n  Theorem mapping_compound_function_iff_singleton_image:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U) (x z:U),\n      MappingFunction f X Y ->\n      MappingFunction g Y Z ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      z = (g ◦ f) x <->\n      {|z|} = 𝕴𝖒( G ⊙ F , {|x|} ).\n  Proof.\n    move => f g X Y Z F G x z Hf Hg HF HG HxX.\n    rewrite /iff.\n    split;\n      [apply (mapping_compound_function_to_singleton_image f g X Y Z F G x z)|\n       apply (singleton_image_to_mapping_compound_function f g X Y Z F G x z)];\n    trivial.\n  Qed.\n\n  Theorem compound_function_value_exists_unique:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U),\n      MappingFunction f X Y ->\n      MappingFunction g Y Z ->\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      forall x:U, x ∈ X ->\n                  exists z:U, {|z|} = 𝕴𝖒( G ⊙ F , {|x|} ) ->\n                              forall z':U, {|z'|} = 𝕴𝖒( G ⊙ F , {|x|} ) -> z = z'.\n  Proof.\n    move => f g X Y Z F G Hf Hg HF HG x HxX.\n    move Hfgz: (g (f x)) => z.\n    exists z.\n    move => H z' H0.\n    apply (mapping_compound_function_iff_singleton_image f g X Y Z F G x z') in H0; trivial.\n    rewrite H0 -Hfgz.\n    reflexivity.\n  Qed.\n\n  Theorem compound_function_value_unique:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U),\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      forall x z z':U, x ∈ X ->\n                       {|z|} = 𝕴𝖒( G ⊙ F , {|x|} ) ->\n                       {|z'|} = 𝕴𝖒( G ⊙ F , {|x|} ) -> z = z'.\n  Proof.\n    move => f g X Y Z F G HF HG x z z' HxX HIz HIz'.\n    apply singleton_eq_iff_element_eq.\n    rewrite HIz HIz'.\n    reflexivity.\n  Qed.\n\n  Theorem singleton_image_of_compound_graph_to_ordered_pair_in_compound_graph:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U) (x z:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      MappingFunction g Y Z ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      {| z |} = 𝕴𝖒( G ⊙ F , {| x |} ) ->\n      <|x,z|> ∈ G ⊙ F.\n  Proof.\n    move => f g X Y Z F G x z Hf HF Hg HG HxX H.\n    apply (singleton_image_iff_ordered_pair_in_graph (g ◦ f) X Z (G ⊙ F) x z).\n    move => x' Hx'X.\n    apply Hf in Hx'X.\n    inversion Hx'X as [y [Hyfx' HyY]].\n    apply Hg in HyY.\n    inversion HyY as [z' [Hzgy Hz'Z]].\n    exists z'.\n    split.\n    unfold CompoundFunction.\n    rewrite -Hyfx'.\n    trivial.\n    trivial.\n    apply sym_eq.\n    rewrite (compound_graph_of_function_eq_graph_of_compound_function f g X Y Z F G).\n    reflexivity.\n    trivial.\n    trivial.\n    trivial.\n    trivial.\n    assumption.\n  Qed.\n\n  Theorem ordered_pair_in_compound_graph_to_singleton_image_of_compound_graph:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U) (x z:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      MappingFunction g Y Z ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      <|x,z|> ∈ G ⊙ F ->\n          {| z |} = 𝕴𝖒( G ⊙ F , {| x |} ).\n  Proof.\n    move => f g X Y Z F G x z Hf HF Hg HG HxX H.\n    apply (singleton_image_iff_ordered_pair_in_graph (g ◦ f) X Z (G ⊙ F) x z).\n    move => x' Hx'X.\n    apply Hf in Hx'X.\n    inversion Hx'X as [y [Hyfx' HyY]].\n    apply Hg in HyY.\n    inversion HyY as [z' [Hzgy Hz'Z]].\n    exists z'.\n    split.\n    unfold CompoundFunction.\n    rewrite -Hyfx'.\n    trivial.\n    trivial.\n    rewrite (compound_graph_of_function_eq_graph_of_compound_function f g X Y Z F G).\n    reflexivity.\n    trivial.\n    trivial.\n    trivial.\n    trivial.\n    assumption.\n  Qed.\n\n  Theorem singleton_image_of_compound_graph_iff_ordered_pair_in_compound_graph:\n    forall (f g:U -> U) (X Y Z:Collection U) (F G:TypeOfDirectProduct U) (x z:U),\n      MappingFunction f X Y ->\n      F = GraphOfFunction f X Y ->\n      MappingFunction g Y Z ->\n      G = GraphOfFunction g Y Z ->\n      x ∈ X ->\n      {| z |} = 𝕴𝖒( G ⊙ F , {| x |} ) <->\n      <|x,z|> ∈ G ⊙ F.\n  Proof.\n    move => f g X Y Z F G x z Hf HF Hg HG HxX.\n    rewrite /iff.\n    split; [apply (singleton_image_of_compound_graph_to_ordered_pair_in_compound_graph f g X Y Z)|\n            apply (ordered_pair_in_compound_graph_to_singleton_image_of_compound_graph f g X Y Z)];\n    trivial.\n  Qed.\n\n  Theorem image_singleton_domain_of_graph_of_identity_eq_singleton_domain:\n    forall (X:Collection U) (x:U),\n      x ∈ X -> {|x|} = 𝕴𝖒( GraphOfIdentity X , {|x|} ).\n  Proof.\n    move => X x HxX.\n    apply mutally_included_to_eq.\n    split; move => x0 H.\n    apply singleton_to_eq in H.\n    split.\n    exists x0.\n    split;[apply singleton_iff_eq;trivial|\n           split;\n           exists x0;\n           exists x0;\n           split;[reflexivity|\n                  split]].\n    trivial.\n    rewrite H.\n    apply ordered_pair_in_direct_product_iff_in_and.\n    split; trivial.\n    inversion H as [x'].\n    inversion H0 as [x0'].\n    inversion H2.\n    inversion H4.\n    inversion H5 as [x1 [x2]].\n    inversion H7.\n    inversion H9.\n    rewrite H10 in H8.\n    apply ordered_pair_to_and in H8.\n    inversion H8.\n    rewrite -H12 in H13.\n    rewrite H13.\n    assumption.\n  Qed.\n\n  Theorem compound_graph_eq_to_compound_function_eq:\n    forall (f0 f1 g0 g1:U->U) (X Y Z:Collection U) (F0 F1 G0 G1:TypeOfDirectProduct U),\n      MappingFunction f0 X Y ->\n      F0 = GraphOfFunction f0 X Y ->\n      MappingFunction f1 X Y ->\n      F1 = GraphOfFunction f1 X Y ->\n      MappingFunction g0 Y Z ->\n      G0 = GraphOfFunction g0 Y Z ->\n      MappingFunction g1 Y Z ->\n      G1 = GraphOfFunction g1 Y Z ->\n      G0 ⊙ F0 = G1 ⊙ F1 ->\n      forall x:U, x ∈ X -> (g0 ◦ f0) x = (g1 ◦ f1) x.\n  Proof.\n    move => f0 f1 g0 g1 X Y Z F0 F1 G0 G1 Hf0 HF0 Hf1 HF1 Hg0 HG0 Hg1 HG1 Heq x HxX.\n    have Hg0f0: MappingFunction (g0 ◦ f0) X Z.\n    move => x0 Hx0X.\n    apply Hf0 in Hx0X.\n    inversion Hx0X as [y [Hyf0x0 HyY]].\n    apply Hg0 in HyY.\n    inversion HyY as [z [Hzg0y HzZ]].\n    exists z.\n    split;[unfold CompoundFunction; rewrite -Hyf0x0|];trivial.\n    have Hg1f1: MappingFunction (g1 ◦ f1) X Z.\n    move => x0 Hx0X.\n    apply Hf1 in Hx0X.\n    inversion Hx0X as [y [Hyf1x0 HyY]].\n    apply Hg1 in HyY.\n    inversion HyY as [z [Hzg1y HzZ]].\n    exists z.\n    split;[unfold CompoundFunction; rewrite -Hyf1x0|];trivial.\n    apply (graph_of_function_eq_iff_function_eq (g0 ◦ f0) (g1 ◦ f1) X Z (G0 ⊙ F0) (G1 ⊙ F1));trivial.\n    apply sym_eq.\n    apply (compound_graph_of_function_eq_graph_of_compound_function f0 g0 X Y Z F0 G0); trivial.\n    apply sym_eq.\n    apply (compound_graph_of_function_eq_graph_of_compound_function f1 g1 X Y Z F1 G1); trivial.\n  Qed.\n\n  Theorem compound_function_eq_to_compound_graph_eq:\n    forall (f0 f1 g0 g1:U->U) (X Y Z:Collection U) (F0 F1 G0 G1:TypeOfDirectProduct U),\n      MappingFunction f0 X Y ->\n      F0 = GraphOfFunction f0 X Y ->\n      MappingFunction f1 X Y ->\n      F1 = GraphOfFunction f1 X Y ->\n      MappingFunction g0 Y Z ->\n      G0 = GraphOfFunction g0 Y Z ->\n      MappingFunction g1 Y Z ->\n      G1 = GraphOfFunction g1 Y Z ->\n      (forall x:U, x ∈ X -> (g0 ◦ f0) x = (g1 ◦ f1) x) ->\n      G0 ⊙ F0 = G1 ⊙ F1.\n  Proof.\n    move => f0 f1 g0 g1 X Y Z F0 F1 G0 G1 Hf0 HF0 Hf1 HF1 Hg0 HG0 Hg1 HG1 H.\n    have Hg0f0: MappingFunction (g0 ◦ f0) X Z.\n    move => x0 Hx0X.\n    apply Hf0 in Hx0X.\n    inversion Hx0X as [y [Hyf0x0 HyY]].\n    apply Hg0 in HyY.\n    inversion HyY as [z [Hzg0y HzZ]].\n    exists z.\n    split;[unfold CompoundFunction; rewrite -Hyf0x0|];trivial.\n    have Hg1f1: MappingFunction (g1 ◦ f1) X Z.\n    move => x0 Hx0X.\n    apply Hf1 in Hx0X.\n    inversion Hx0X as [y [Hyf1x0 HyY]].\n    apply Hg1 in HyY.\n    inversion HyY as [z [Hzg1y HzZ]].\n    exists z.\n    split;[unfold CompoundFunction; rewrite -Hyf1x0|];trivial.\n    apply (graph_of_function_eq_iff_function_eq (g0 ◦ f0) (g1 ◦ f1) X Z (G0 ⊙ F0) (G1 ⊙ F1)).\n    trivial.\n    trivial.\n    apply sym_eq.\n    apply (compound_graph_of_function_eq_graph_of_compound_function f0 g0 X Y Z F0 G0); trivial.\n    apply sym_eq.\n    apply (compound_graph_of_function_eq_graph_of_compound_function f1 g1 X Y Z F1 G1); trivial.\n    assumption.\n  Qed.\n\n  Theorem compound_graph_eq_iff_compound_function_eq:\n    forall (f0 f1 g0 g1:U->U) (X Y Z:Collection U) (F0 F1 G0 G1:TypeOfDirectProduct U),\n      MappingFunction f0 X Y ->\n      F0 = GraphOfFunction f0 X Y ->\n      MappingFunction f1 X Y ->\n      F1 = GraphOfFunction f1 X Y ->\n      MappingFunction g0 Y Z ->\n      G0 = GraphOfFunction g0 Y Z ->\n      MappingFunction g1 Y Z ->\n      G1 = GraphOfFunction g1 Y Z ->\n      (G0 ⊙ F0 = G1 ⊙ F1 <->\n       forall x:U, x ∈ X -> (g0 ◦ f0) x = (g1 ◦ f1) x).\n  Proof.\n    move => f0 f1 g0 g1 X Y Z F0 F1 G0 G1 Hf0 HF0 Hf1 HF1 Hg0 HG0 Hg1 HG1.\n    rewrite /iff.\n    split;[apply (compound_graph_eq_to_compound_function_eq f0 f1 g0 g1 X Y Z F0 F1 G0 G1)|\n           apply (compound_function_eq_to_compound_graph_eq f0 f1 g0 g1 X Y Z F0 F1 G0 G1)];trivial.\n  Qed.\n\n  Theorem ordered_pair_in_graph_of_identity:\n    forall (X:Collection U) (x:U),\n      x ∈ X -> <|x,x|> ∈ GraphOfIdentity X.\n  Proof.\n    move => X x HxX.\n    split.\n    exists x.\n    exists x.\n    split;[reflexivity|split;\n                       [reflexivity|\n                        apply ordered_pair_in_direct_product_iff_in_and;\n                        split;\n                        assumption]].\n  Qed.\n\n  Theorem ordered_pair_in_graph_to_eq:\n    forall (X:Collection U) (x x':U),\n      <|x,x'|> ∈ GraphOfIdentity X -> x = x'.\n  Proof.\n    move => X x x' H.\n    inversion H as [Z [x0 [x0']]].\n    inversion H0 as [H2 [H3]].\n    apply ordered_pair_to_and in H2.\n    inversion H2.\n    rewrite -H5 -H6 in H3.\n    rewrite H3.\n    reflexivity.\n  Qed.\n\n  Theorem same_element_pair_in_identity:\n    forall (X:Collection U) (x x':U),\n      x ∈ X /\\ x = x' -> <|x,x'|> ∈ GraphOfIdentity X.\n  Proof.\n    move => X x x'.\n    case => HxX Heq.\n    rewrite -Heq.\n    apply ordered_pair_in_graph_of_identity.\n    assumption.\n  Qed.\n\n  Theorem ordered_pair_in_graph_iff_eq:\n    forall (X:Collection U) (x x':U),\n      x ∈ X /\\ x = x' <-> <|x,x'|> ∈ GraphOfIdentity X.\n  Proof.\n    move => X x x'.\n    rewrite /iff.\n    split.\n    +case => HxX Heq.\n     rewrite -Heq.\n     apply ordered_pair_in_graph_of_identity.\n     assumption.\n    +move => H.\n     inversion H.\n     inversion H0 as [x0 [x'0]].\n     inversion H2.\n     inversion H4.\n     rewrite -H3 in H6.\n     apply ordered_pair_in_direct_product_iff_in_and in H6.\n     inversion H6.\n     apply ordered_pair_to_and in H3.\n     inversion H3.\n     rewrite -H9 -H10 in H5.\n     split;[trivial|apply eq_sym;assumption].\n  Qed.\n\n  Theorem compound_identity_function_r:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U),\n      F = GraphOfFunction f X Y ->\n      F = F ⊙ GraphOfIdentity X.\n  Proof.\n    move => f' X Y F HF.\n    rewrite HF.\n    apply mutally_included_to_eq.\n    split => Z HFZ;\n               inversion HFZ as [Z0 [x0 [y0]]];\n               inversion H.\n    inversion H2.\n    split.\n    exists x0.\n    exists y0.\n    split;[trivial|].\n    exists x0.\n    split.\n    apply ordered_pair_in_graph_of_identity.\n    apply ordered_pair_in_direct_product_to_in_and in H4.\n    apply H4.\n    split.\n    exists x0.\n    exists y0.\n    split;[reflexivity|trivial].\n    inversion H2 as [x0'].\n    inversion H3.\n    apply ordered_pair_in_graph_to_eq in H4.\n    rewrite -H4 in H5.\n    rewrite H1.\n    assumption.\n  Qed.\n\n  Theorem compound_identity_function_l:\n    forall (f:U -> U) (X Y:Collection U) (F:TypeOfDirectProduct U),\n      F = GraphOfFunction f X Y ->\n      F = GraphOfIdentity Y ⊙ F.\n  Proof.\n    move => f' X Y F HF.\n    rewrite HF.\n    apply mutally_included_to_eq.\n    split => Z H;\n               inversion H;\n               inversion H0 as [x [y]].\n    +inversion H2 as [H3 [H4 H5]].\n     split.\n     exists x.\n     exists y.\n     split;[trivial|exists y;\n                    rewrite -H3;\n                    split;[trivial|\n                           apply ordered_pair_in_graph_of_identity;\n                           apply ordered_pair_in_direct_product_iff_in_and in H5;\n                           apply H5]].\n    +inversion H2 as [H3 H4].\n     inversion H4 as [y' [H5 H6]].\n     apply ordered_pair_in_graph_to_eq in H6.\n     rewrite H6 in H5.\n     rewrite H3.\n     assumption.\n  Qed.\n\n  Theorem associativity_of_graph_of_function:\n    forall (f g h:U -> U) (X Y Z W:Collection U) (F G H:TypeOfDirectProduct U),\n      F = GraphOfFunction f X Y ->\n      G = GraphOfFunction g Y Z ->\n      H = GraphOfFunction h Z W ->\n      (H ⊙ G) ⊙ F = H ⊙ (G ⊙ F).\n  Proof.\n    move => f' g' h' X Y Z W F G H HF HG HH.\n    apply (associativity_of_graph_of_binary_relation U\n                                                     (fun x y => y = f' x)\n                                                     (fun x y => y = g' x)\n                                                     (fun x y => y = h' x)\n                                                     X Y Z W F G H);trivial.\n  Qed.\n\nEnd Mapping.\n\nRequire Export binary_relation.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "implement_set_theory_in_coq", "sha": "49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c", "save_path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq", "path": "github-repos/coq/seisyuu-hantatsushi-implement_set_theory_in_coq/implement_set_theory_in_coq-49ec25bb83fcc4f7c70b2add3e7dbd1e1907cb8c/coq/mapping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7119464975238002}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Arith.Bool_nat.\nRequire Import Init.Nat.\nImport ListNotations.\n\nDefinition vertex := nat.\nDefinition edge := prod vertex vertex.\n\nInductive graph {X : Type} : Set :=\n| Empty : graph\n| Add_node : forall (x : X) (g : graph), x \n\nCheck \" :> \".\nDefinition cover := list edge.\n\nDefinition size (c : cover) := length c.\n\nDefinition gt n m := negb (n <=? m).\n    \nDefinition empty : graph := Graph [] [].\n\nDefinition incident (v : vertex) (e : edge) := \nmatch e with \n| (x,y) => x = v \\/ y = v\nend.\n\nDefinition incident_b (v : vertex) (e : edge) := \nmatch e with \n| (x,y) => orb (x =? v) (y =? v)\nend.\n\nDefinition is_cover (es : cover) (g : graph) := \nincl es (e_list g) /\\\nforall v : vertex, In v (v_list g) -> \n  ex (fun e => In e (e_list g) /\\ incident v e).\n\nFixpoint elem {X : Type} (f : X -> X -> bool) e l := \nmatch l with \n| [] => false\n| x::xs => if f e x then true else elem f e xs\nend.\n\nDefinition incl_b {X : Type} f (l m : list X) := forallb (fun x => elem f x m) l.\nDefinition is_cover_b (es : cover) (g : graph) := \nandb \n(incl_b (fun e1 e2 => match (e1,e2) with ((x1,y1),(x2,y2)) => andb (eqb x1 x2) (eqb y1 y2) end)\n es (e_list g))\n(forallb (fun v => existsb (incident_b v) es) (v_list g)).\n\nFixpoint all_subset {X : Type} (l : list X) := \nmatch l with \n| [] => [[]]\n| x::xs => \n  let subsets := all_subset xs in \n  subsets ++ (map (fun e => x::e) subsets)\nend.\n\nCompute all_subset [1;2;3].\nCheck option.\n\nSearch (False -> _).\nCheck fold_left.\nDefinition min (l : list nat) d := fold_left (fun acc x => if x <? acc then x else acc) l d.\n\nFixpoint min_vc (g : graph) : option nat := \nlet covers := filter (fun c => is_cover_b c g) (all_subset (e_list g)) in \nmatch covers with \n| [] => None\n| x::xs => \n  let k := min (map (fun c => length c) covers) (length x) in \n    Some k\nend.\n\nCompute min_vc (Graph [1;2;3;4;5] [(1,2);(3,2);(3,4);(5,4)]). \n\nTheorem min_vc_correct : forall (k : nat) (g : graph), \nmin_vc g = Some k -> ~ ex (fun c => is_cover c g /\\  size c <= k).\nProof.\nAdmitted.", "meta": {"author": "kaonn", "repo": "5", "sha": "a0bff50104ec09cea6e7cc8c93f021a2b83063e9", "save_path": "github-repos/coq/kaonn-5", "path": "github-repos/coq/kaonn-5/5-a0bff50104ec09cea6e7cc8c93f021a2b83063e9/Graph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7119464841298726}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf3 : natural) : natural :=\n  plus Zero (plus z lf3).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj146_coqofml_tPssub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7119464711873956}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf3 : natural) : natural :=\n  plus Zero (plus lf3 z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj146_coqofml_58Kw1b.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7119464711229027}}
{"text": "(* Adapted from Barendregt: https://gist.github.com/palmskog/341da4e54ff7e805077b6e0b3af7d21d *)\nSection Barendregt.\n\nVariable P : Prop.\n\nFixpoint B (n : nat) := match n with | O => P | S n' => P <-> B n' end.\n\nLemma B2n: forall n, B (1 + n * 2).\nProof.\nexact (fix B2n n : B (1 + n * 2) :=\n  match n with\n  | O => iff_refl P\n  | S n' => let IH : B (1 + n' * 2) := B2n n' in\n            ltac:(tauto) : P <-> (P <-> B (1 + n' * 2))\n  end).\nQed.\n\nEnd Barendregt.\n\nLemma iffP : forall P : Prop, P <-> (P <-> (P <-> (P <-> (P <-> (P <-> (P <-> (P <-> (P <-> P)))))))).\nProof.\nexact (fun P => B2n P 4).\nQed.\n", "meta": {"author": "jashug", "repo": "MiscTypeTheory", "sha": "8f8995809c0d2bc8b1418bba793ce3766f013d8b", "save_path": "github-repos/coq/jashug-MiscTypeTheory", "path": "github-repos/coq/jashug-MiscTypeTheory/MiscTypeTheory-8f8995809c0d2bc8b1418bba793ce3766f013d8b/ProofByReflectionExample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.7119407122538122}}
{"text": "Require Import Relation_Definitions.\nRequire Import Relation_Operators.\n\nSection FixDomain.\n\n  Variable M : Set.\n\n  Definition terminates (gamma : M) (R : relation M) :=\n    Acc R gamma.\n\n  Inductive clos (A : Type) (R : A -> A -> Prop) : bool -> A -> A -> Prop :=\n  | clos_refl : forall a, clos A R false a a\n  | clos_step : forall s a b, R a b -> clos A R s a b\n  | clos_trans : forall s a b c,\n    clos A R s a b -> clos A R s b c -> clos A R s a c. \n\n  Lemma clos_faithful (A : Type) (R : relation A) (strict : bool) :\n    forall l r,\n      clos A R strict l r <->\n      if strict\n        then Relation_Operators.clos_trans A R l r\n        else clos_refl_trans A R l r.\n  Proof.\n    split.\n      induction 1; try (destruct s); econstructor solve[eauto].\n      destruct strict; induction 1; econstructor solve[eauto].\n  Qed.\n\n  Definition clos_unstrict A (R : relation A) a b\n    (step : clos A R true a b) : clos A R false a b.\n  Proof.\n    induction step; eauto using clos.\n  Defined.\n\n  Inductive clos_left (A : Type) (R : A -> A -> Prop) :\n    bool -> A -> A -> Prop :=\n  | clos_left_refl : forall a, clos_left A R false a a\n  | clos_left_step : forall s a b, R a b -> clos_left A R s a b\n  | clos_left_ext : forall s a b c,\n    R a b -> clos_left A R s b c -> clos_left A R s a c.\n  \n  Lemma clos_left_trans (A : Type) (R : A -> A -> Prop)\n    strict a b c :\n    clos_left A R strict a b -> clos_left A R strict b c ->\n    clos_left A R strict a c.\n    induction 1.  \n    auto.\n    apply clos_left_ext. assumption.\n    intros. specialize (IHclos_left H1).\n    eapply clos_left_ext; eassumption.\n  Qed.\n\n  Lemma clos_iff_left (A : Type) (R : A -> A -> Prop)\n    strict a b : clos A R strict a b <-> clos_left A R strict a b.\n  Proof.  \n    split.\n    induction 1.\n    constructor.\n    constructor;assumption.\n    eapply clos_left_trans;eassumption.\n    \n    induction 1.\n    constructor.\n    constructor;assumption.\n    eauto using clos.\n  Qed.\n\n  Lemma clos_cons_lt A (R : relation A) a b s c :\n    clos A R true a b -> clos A R s b c -> clos A R true a c.\n  Proof. induction 2;eauto using clos. Qed.\n\n  Lemma clos_trans_lt A (R : relation A) a b s c :\n    clos A R s a b -> clos A R false b c -> clos A R s a c.\n  Proof. destruct s; eauto using clos_cons_lt, clos. Qed.\n\n  Lemma clos_cons_rt A (R : relation A) a s b c :\n    clos A R s a b -> clos A R true b c -> clos A R true a c.\n  Proof. induction 1;eauto using clos. Qed.\n\n  Lemma clos_cat A (R : relation A) a s1 b s2 c :\n    clos A R s1 a b -> clos A R s2 b c -> clos A R (orb s1 s2) a c.\n  Proof.\n    destruct s1. apply clos_cons_lt.\n    destruct s2. apply clos_cons_rt.\n    apply clos_trans.\n  Qed.\n\n  Lemma clos_cat' A (R : relation A) a s1 b s2 s3 c :\n    clos A R s1 a b -> clos A R s2 b c -> s3 = orb s1 s2 -> clos A R s3 a c.\n  Proof.\n    destruct s1; destruct s2; intros; rewrite H1; eapply clos_cat; eauto.\n  Qed.\n\n  Definition impliesb (a b : bool) :=\n    a = false \\/ b = true.\n\n  Lemma clos_cat'' A (R : relation A) a s1 b s2 s3 c :\n    clos A R s1 a b -> clos A R s2 b c -> impliesb s3 (orb s1 s2) -> clos A R s3 a c.\n  Proof.\n    intros; destruct s1; destruct s2; destruct s3.\n    eapply clos_cat'; eauto.\n    try (apply clos_unstrict; eauto using clos ).\n    eapply (clos_cat' A R _ _ _ _ _ _ H H0). compute. reflexivity.\n    try (apply clos_unstrict; eauto using clos ).\n    eapply (clos_cat' A R _ _ _ _ _ _ H H0). compute. reflexivity.\n    eapply (clos_cat' A R _ _ _ _ _ _ H H0). compute. reflexivity.\n    try (apply clos_unstrict; eauto using clos ).\n    eapply (clos_cat' A R _ _ _ _ _ _ H H0). compute. reflexivity.\n    compute in H1; destruct H1; inversion H1. \n    eapply (clos_cat' A R _ _ _ _ _ _ H H0). compute. reflexivity.\nQed.    \n\n  Lemma terminates_fwd (R : relation M) (gamma : M) :\n    terminates gamma R ->\n    forall strict gamma', clos M R strict gamma' gamma ->\n      terminates gamma' R.\n  Proof.\n    intros.\n    induction H0.\n    assumption.\n    destruct H. apply H. assumption.\n    auto.\n  Qed.\n\n  Lemma clos_weaken (A : Type) (R1 R2 : relation A) strict x y :\n    (forall a b, R1 a b -> R2 a b) ->\n    clos A R1 strict x y -> clos A R2 strict x y.\n  Proof. induction 2; eauto using clos. Defined.\n\n  Lemma Acc_weaken A (R1 R2 : relation A)\n    (HWeak : forall a b, R2 a b -> R1 a b)\n    (x : A) : Acc R1 x -> Acc R2 x.\n  Proof. induction 1; constructor; auto. Qed.\n\nEnd FixDomain.\n", "meta": {"author": "andreistefanescu", "repo": "matching-logic", "sha": "210c27a7a8b6365bbede2e91b8707c8393049e65", "save_path": "github-repos/coq/andreistefanescu-matching-logic", "path": "github-repos/coq/andreistefanescu-matching-logic/matching-logic-210c27a7a8b6365bbede2e91b8707c8393049e65/coq/condsys-clean/Closure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639067, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7118986196123648}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\nRequire Import PeanoNat Lt.\n\nLocal Open Scope nat_scope.\n\nImplicit Types m n p : nat.\n\nSection Well_founded_Nat.\n\nVariable A : Type.\n\nVariable f : A -> nat.\nDefinition ltof (a b:A) := f a < f b.\nDefinition gtof (a b:A) := f b > f a.\n\nTheorem well_founded_ltof : well_founded ltof.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.well_founded_ltof\".  \nassert (H : forall n (a:A), f a < n -> Acc ltof a).\n{ induction n.\n- intros; absurd (f a < 0); auto with arith.\n- intros a Ha. apply Acc_intro. unfold ltof at 1. intros b Hb.\napply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }\nintros a. apply (H (S (f a))). auto with arith.\nDefined.\n\nTheorem well_founded_gtof : well_founded gtof.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.well_founded_gtof\".  \nexact well_founded_ltof.\nDefined.\n\n\n\nTheorem induction_ltof1 :\nforall P:A -> Set,\n(forall x:A, (forall y:A, ltof y x -> P y) -> P x) -> forall a:A, P a.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.induction_ltof1\".  \nintros P F.\nassert (H : forall n (a:A), f a < n -> P a).\n{ induction n.\n- intros; absurd (f a < 0); auto with arith.\n- intros a Ha. apply F. unfold ltof. intros b Hb.\napply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }\nintros a. apply (H (S (f a))). auto with arith.\nDefined.\n\nTheorem induction_gtof1 :\nforall P:A -> Set,\n(forall x:A, (forall y:A, gtof y x -> P y) -> P x) -> forall a:A, P a.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.induction_gtof1\".  \nexact induction_ltof1.\nDefined.\n\nTheorem induction_ltof2 :\nforall P:A -> Set,\n(forall x:A, (forall y:A, ltof y x -> P y) -> P x) -> forall a:A, P a.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.induction_ltof2\".  \nexact (well_founded_induction well_founded_ltof).\nDefined.\n\nTheorem induction_gtof2 :\nforall P:A -> Set,\n(forall x:A, (forall y:A, gtof y x -> P y) -> P x) -> forall a:A, P a.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.induction_gtof2\".  \nexact induction_ltof2.\nDefined.\n\n\n\nVariable R : A -> A -> Prop.\n\nHypothesis H_compat : forall x y:A, R x y -> f x < f y.\n\nTheorem well_founded_lt_compat : well_founded R.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.well_founded_lt_compat\".  \nassert (H : forall n (a:A), f a < n -> Acc R a).\n{ induction n.\n- intros; absurd (f a < 0); auto with arith.\n- intros a Ha. apply Acc_intro. intros b Hb.\napply IHn. apply Nat.lt_le_trans with (f a); auto with arith. }\nintros a. apply (H (S (f a))). auto with arith.\nDefined.\n\nEnd Well_founded_Nat.\n\nLemma lt_wf : well_founded lt.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.lt_wf\".  \nexact (well_founded_ltof nat (fun m => m)).\nDefined.\n\nLemma lt_wf_rec1 :\nforall n (P:nat -> Set), (forall n, (forall m, m < n -> P m) -> P n) -> P n.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.lt_wf_rec1\".  \nexact (fun p P F => induction_ltof1 nat (fun m => m) P F p).\nDefined.\n\nLemma lt_wf_rec :\nforall n (P:nat -> Set), (forall n, (forall m, m < n -> P m) -> P n) -> P n.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.lt_wf_rec\".  \nexact (fun p P F => induction_ltof2 nat (fun m => m) P F p).\nDefined.\n\nLemma lt_wf_ind :\nforall n (P:nat -> Prop), (forall n, (forall m, m < n -> P m) -> P n) -> P n.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.lt_wf_ind\".  \nintro p; intros; elim (lt_wf p); auto with arith.\nQed.\n\nLemma gt_wf_rec :\nforall n (P:nat -> Set), (forall n, (forall m, n > m -> P m) -> P n) -> P n.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.gt_wf_rec\".  \nexact lt_wf_rec.\nDefined.\n\nLemma gt_wf_ind :\nforall n (P:nat -> Prop), (forall n, (forall m, n > m -> P m) -> P n) -> P n.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.gt_wf_ind\".  exact (lt_wf_ind). Qed.\n\nLemma lt_wf_double_rec :\nforall P:nat -> nat -> Set,\n(forall n m,\n(forall p q, p < n -> P p q) ->\n(forall p, p < m -> P n p) -> P n m) -> forall n m, P n m.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.lt_wf_double_rec\".  \nintros P Hrec p; pattern p; apply lt_wf_rec.\nintros n H q; pattern q; apply lt_wf_rec; auto with arith.\nDefined.\n\nLemma lt_wf_double_ind :\nforall P:nat -> nat -> Prop,\n(forall n m,\n(forall p (q:nat), p < n -> P p q) ->\n(forall p, p < m -> P n p) -> P n m) -> forall n m, P n m.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.lt_wf_double_ind\".  \nintros P Hrec p; pattern p; apply lt_wf_ind.\nintros n H q; pattern q; apply lt_wf_ind; auto with arith.\nQed.\n\nHint Resolve lt_wf: arith.\nHint Resolve well_founded_lt_compat: arith.\n\nSection LT_WF_REL.\nVariable A : Set.\nVariable R : A -> A -> Prop.\n\n\nVariable F : A -> nat -> Prop.\nDefinition inv_lt_rel x y := exists2 n, F x n & (forall m, F y m -> n < m).\n\nHypothesis F_compat : forall x y:A, R x y -> inv_lt_rel x y.\nRemark acc_lt_rel : forall x:A, (exists n, F x n) -> Acc R x.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.acc_lt_rel\".  \nintros x [n fxn]; generalize dependent x.\npattern n; apply lt_wf_ind; intros.\nconstructor; intros.\ndestruct (F_compat y x) as (x0,H1,H2); trivial.\napply (H x0); auto.\nQed.\n\nTheorem well_founded_inv_lt_rel_compat : well_founded R.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.well_founded_inv_lt_rel_compat\".  \nconstructor; intros.\ncase (F_compat y a); trivial; intros.\napply acc_lt_rel; trivial.\nexists x; trivial.\nQed.\n\nEnd LT_WF_REL.\n\nLemma well_founded_inv_rel_inv_lt_rel :\nforall (A:Set) (F:A -> nat -> Prop), well_founded (inv_lt_rel A F).\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.well_founded_inv_rel_inv_lt_rel\".  \nintros; apply (well_founded_inv_lt_rel_compat A (inv_lt_rel A F) F); trivial.\nQed.\n\n\n\nSet Implicit Arguments.\n\nRequire Import Le.\nRequire Import Compare_dec.\nRequire Import Decidable.\n\nDefinition has_unique_least_element (A:Type) (R:A->A->Prop) (P:A->Prop) :=\nexists! x, P x /\\ forall x', P x' -> R x x'.\n\nLemma dec_inh_nat_subset_has_unique_least_element :\nforall P:nat->Prop, (forall n, P n \\/ ~ P n) ->\n(exists n, P n) -> has_unique_least_element le P.\nProof. hammer_hook \"Wf_nat\" \"Wf_nat.dec_inh_nat_subset_has_unique_least_element\".  \nintros P Pdec (n0,HPn0).\nassert\n(forall n, (exists n', n'<n /\\ P n' /\\ forall n'', P n'' -> n'<=n'')\n\\/ (forall n', P n' -> n<=n')).\n{ induction n.\n- right. intros. apply Nat.le_0_l.\n- destruct IHn as [(n' & IH1 & IH2)|IH].\n+ left. exists n'; auto with arith.\n+ destruct (Pdec n) as [HP|HP].\n* left. exists n; auto with arith.\n* right. intros n' Hn'.\napply Nat.le_neq; split; auto. intros <-. auto. }\ndestruct (H n0) as [(n & H1 & H2 & H3)|H0]; [exists n | exists n0];\nrepeat split; trivial;\nintros n' (HPn',Hn'); apply Nat.le_antisymm; auto.\nQed.\n\nUnset Implicit Arguments.\n\nNotation iter_nat n A f x := (nat_rect (fun _ => A) x (fun _ => f) n) (only parsing).\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Arith/Wf_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7118986096867386}}
{"text": "Require Import Omega.\nRequire Import ssreflect.\nSection ScalarRec.\n\nVariable T:Type.\nVariable g : nat -> T -> T.\n\nFixpoint rec_fn (n:nat) (s:T) := match n with\n  | 0 => s\n  | S n => (rec_fn n (g n s))\n  end.\n\nFixpoint rec_fn_rev_acc (n:nat) (m:nat) (s:T) := match n with\n  | 0 => s\n  | S n => g (m - n - 1) (rec_fn_rev_acc n m s)\n  end.\n\nDefinition rec_fn_rev (n:nat) (s:T) :=\n  rec_fn_rev_acc n n s.\n\nLemma rec_fn_rev_acc_S : forall m n s,\n  rec_fn_rev_acc (S n) (S m) s = rec_fn_rev_acc n m (g m s).\nProof.\n  induction n => s. simpl.\n  by rewrite Nat.sub_0_r .\n  change (rec_fn_rev_acc (S (S n)) (S m) s) with (g (S m - S n - 1) (rec_fn_rev_acc (S n) (S m) s)).\n  rewrite IHn.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem Tail_Head_equiv : forall n s, rec_fn n s = rec_fn_rev n s.\nProof.\n  induction n => s //.\n  rewrite /rec_fn_rev rec_fn_rev_acc_S.\n  simpl.\n  by rewrite IHn.\nQed.\n\nEnd ScalarRec.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/proofs/spec/Libs/HeadTailRec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7118960963458505}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult x y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj259_coqofml_ggNrck.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7118960856822771}}
{"text": "Add LoadPath \"/Users/lubis/Documents/study/software_foundations\".\nRequire Export Induction.\nRequire Export Basics.\n\nModule NatList.\n\nCompute (bin_to_nat Z).\n\nInductive natprod: Type :=\n  | pair (n1 n2: nat).\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\nNotation \"( x , y )\" := (pair x y).\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\nTheorem surjective_pairing':\n  forall n m: nat, (n,m) = (fst (n,m), snd (n,m)).\nProof. reflexivity. Qed.\n\nTheorem surjective_pairing_stuck:\n  forall p: natprod, p = (fst p, snd p).\nProof. Abort.\n\nTheorem surjective_pairing:\n  forall p: natprod, p = (fst p, snd p).\nProof.\n  intros p.\n  destruct p as [n m]. reflexivity.\nQed.\n\n(* Exercise starts *)\n\nTheorem snd_fst_is_swap:\n  forall p: natprod, (snd p, fst p) = swap_pair p.\nProof.\n  intros p.\n  destruct p as [n m]. simpl. reflexivity.\nQed.\n\nTheorem fst_swap_is_snd:\n  forall p: natprod, fst (swap_pair p) = snd p.\nProof.\n  intros p. destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\n(* Exercise ends *)\n\nInductive natlist: Type :=\n  | nil\n  | cons (n: nat) (l: natlist).\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\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 length (l: natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2: natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | x :: l => x :: (app l l2)\n  end.\n\nNotation \"x ++ y\" := (app x y) (at level 60, right associativity).\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\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 starts. Page 56. *)\n\nFixpoint nonzeros (l: natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => \n    match h with \n    | O => nonzeros t\n    | S n => h :: (nonzeros t)\n    end\n  end.\n\nExample test_nonzeros:\n  nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof. reflexivity. Qed.\n\nCompute (negb false).\n\nFixpoint oddmembers (l: natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t =>\n    match (evenb h) with\n    | false => h :: (oddmembers t)\n    | true => oddmembers t\n    end\n  end.\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\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n  | nil, nil => nil\n  | nil, h :: t => l2\n  | h :: t, nil => l1\n  | h1 :: t1, h2 :: t2 => h1 :: (h2 :: (alternate t1 t2))\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\nDefinition bag := natlist.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => O\n  | h :: t =>\n    match (eqb h v) with\n    | true => S (count v t)\n    | false => count v t\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\nDefinition sum (s1 s2: bag) : bag := app s1 s2.\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 := \n  negb ((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\nFixpoint remove_one (v:nat) (s:bag) : bag :=\n  match s with\n  | nil => nil\n  | h :: t =>\n    match (eqb 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.\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  | h :: t =>\n    match (eqb 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.\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 => \n    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(* Exercise ends. *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof. reflexivity. Qed.\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.  \nQed.\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.  \nQed.\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\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    simpl.\n    rewrite <- IHl'.\nAbort.\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\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\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(* Exercise starts. Page 65 *)\n\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.\n\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. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1', app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite -> rev_app_distr, IHl'.\n    simpl. reflexivity.\nQed.\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  - simpl. rewrite -> app_assoc. reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - simpl. reflexivity.\n  - destruct n as [| n'].\n    + simpl. rewrite -> IHl1'. reflexivity.\n    + simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\nFixpoint eqblist (l1 l2 : natlist) : bool :=\n  match l1, l2 with\n  | nil, nil => true\n  | nil, h :: t => false\n  | h :: t, nil => false\n  | h1 :: t1, h2 :: t2 =>\n    match (eqb h1 h2) with\n    | true => eqblist t1 t2\n    | false => false\n    end\n  end. \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 eqblist_refl : forall l:natlist,\n  true = eqblist l l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. rewrite <- eqb_refl, IHl'. reflexivity.\nQed.\n\n(* Exercise ends. *)\n\n\n(* Exercise starts. Page 66. *)\n\nTheorem count_member_nonzero : forall (s : bag),\n  1 <=? (count 1 (1 :: s)) = true.\nProof.\n  intros s. induction s as [| n s' IHs'].\n  - 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.  \nQed.\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  - simpl. reflexivity.\n  - destruct n as [| n'].\n    + simpl. rewrite -> leb_n_Sn. reflexivity.\n    + simpl. rewrite -> IHs'. reflexivity.\nQed.\n\n(* Exercise ends. *)\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\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  | 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\nFixpoint nth_error' (l: natlist) (n: nat) : natoption :=\n  match l with\n  | nil => None\n  | a :: l' =>\n    if n =? O then Some a else nth_error' l' (pred n)\n  end.\n\nDefinition option_elim (d: nat) (o: natoption) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\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. 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\nTheorem option_elim_hd:\n  forall (l:natlist) (default:nat), hd default l = option_elim default (hd_error l).\nProof.\n  intros l default. induction l as [| n l' IHl'].\n  - reflexivity.\n  - simpl. reflexivity.\nQed.\n\nInductive id: Type := \n  | Id (n: nat).\n\nDefinition eqb_id (x1 x2: id) : bool :=\n  match x1, x2 with\n  | Id n1, Id n2 => n1 =? n2\n  end.\n\nTheorem eqb_id_refl:\n  forall x: id, true = eqb_id x x.\nProof.\n  intros x. destruct x as [x']. simpl. \n  rewrite <- eqb_refl. reflexivity.\nQed.\n\nInductive partial_map: Type :=\n  | empty\n  | record (i: id) (v: nat) (m: partial_map).\n\nDefinition update (d: partial_map) (x: id) (value: nat) : partial_map :=\n  record x value d.\n\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 then Some v else find x d'\n  end.\n\nTheorem update_eq:\n  forall (d:partial_map) (x:id) (v:nat), find x (update d x v) = Some v.\nProof.\n  intros d x v. induction d as [| i n d' IHd'].\n  - simpl. rewrite <- eqb_id_refl. reflexivity.\n  - simpl. rewrite <- eqb_id_refl. reflexivity.\nQed.\n\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. intros H.\n  induction d as [| i v d' IHd'].\n  - simpl. rewrite -> H. reflexivity.\n  - simpl. rewrite -> H. reflexivity.\nQed.\n\nEnd NatList.\n\n\n\n\n\n", "meta": {"author": "ansharlubis", "repo": "software-foundations", "sha": "bd29007e65c19f8a8e2fca87aec2db90be27ae13", "save_path": "github-repos/coq/ansharlubis-software-foundations", "path": "github-repos/coq/ansharlubis-software-foundations/software-foundations-bd29007e65c19f8a8e2fca87aec2db90be27ae13/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7118335350151906}}
{"text": "(** * Lecture 02 Exercises *)\n\n(** infer some type arguments automatically *)\nSet Implicit Arguments.\n\nInductive list (A: Set) : Set :=\n| nil : list A\n| cons : A -> list A -> list A.\n\nArguments nil {A}.\n\nFixpoint length (A: Set) (l: list A) : nat :=\n  match l with\n  | nil => O\n  | cons x xs => S (length xs)\n  end.\n\n(** add one list to the end of another *)\nFixpoint app (A: Set) (l1: list A) (l2: list A) : list A :=\n  match l1 with\n  | nil => l2\n  | cons x xs => cons x (app xs l2)\n  end.\n\nTheorem app_nil:\n  forall A (l: list A),\n  app l nil = l.\nProof.\n  intros.\n  induction l.\n  + simpl. reflexivity.\n  + simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem app_assoc:\n  forall A (l1 l2 l3: list A),\n  app (app l1 l2) l3 = app l1 (app l2 l3).\nProof.\n  intros.\n  induction l1.\n  + simpl. reflexivity.\n  + simpl. rewrite IHl1. reflexivity.\nQed.\n\n(** simple but inefficient way to reverse a list *)\nFixpoint rev (A: Set) (l: list A) : list A :=\n  match l with\n  | nil => nil\n  | cons x xs => app (rev xs) (cons x nil)\n  end.\n\n(** tail recursion is faster, but more complicated *)\nFixpoint fast_rev_aux (A: Set) (l: list A) (acc: list A) : list A :=\n  match l with\n  | nil => acc\n  | cons x xs => fast_rev_aux xs (cons x acc)\n  end.\n\nDefinition fast_rev (A: Set) (l: list A) : list A :=\n  fast_rev_aux l nil.\n\n(** add an element to the end of a list *)\nFixpoint snoc (A: Set) (l: list A) (x: A) : list A :=\n  match l with\n  | nil => cons x nil\n  | cons y ys => cons y (snoc ys x)\n  end.\n\nTheorem snoc_app_singleton:\n  forall A (l: list A) (x: A),\n  snoc l x = app l (cons x nil).\nProof.\n  intros.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl.\n    reflexivity.\nQed.\n\nTheorem app_snoc_l:\n  forall A (l1: list A) (l2: list A) (x: A),\n  app (snoc l1 x) l2 = app l1 (cons x l2).\nProof.\n  intros. \n  induction l1.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1.\n    reflexivity.\nQed.\n\nTheorem app_snoc_r:\n  forall A (l1: list A) (l2: list A) (x: A),\n  app l1 (snoc l2 x) = snoc (app l1 l2) x.\nProof.\n  intros. \n  induction l1.\n  - simpl. reflexivity.\n  - simpl. rewrite IHl1.\n    reflexivity.\nQed.\n\n(** simple but inefficient way to reverse a list *)\nFixpoint rev_snoc (A: Set) (l: list A) : list A :=\n  match l with\n  | nil => nil\n  | cons x xs => snoc (rev_snoc xs) x\n  end.\n\nLemma fast_rev_ok_snoc:\n  forall A (l: list A),\n  fast_rev l = rev_snoc l.\nProof.\n  (** TODO -- you will need to define a helper lemma\n              very similar to how we proved fast_ref_ok *)\nAdmitted.\n\n(** useful in proving rev_length below *)\nLemma plus_1_S:\n  forall n,\n  plus n 1 = S n.\nProof.\n  intros.\n  induction n.\n  + simpl. reflexivity.\n  + simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma rev_length:\n  forall A (l: list A),\n  length (rev l) = length l.\nProof.\n  (** TODO -- you will need to define a helper lemma\n              that relates length and app *)\nAdmitted.\n\nLemma rev_involutive:\n  forall A (l: list A),\n  rev (rev l) = l.\nProof.\n  (** TODO -- you will need to define a helper lemma \n              that relates rev and app, its proof should\n              use app_assoc *)\nAdmitted.L02_exercise.vL02_exercise.vL02_exercise.vL02_exercise.vL02_exercise.v", "meta": {"author": "Mestway", "repo": "CourseWork", "sha": "912cf0e4a7127f2f0940cbdf1e7af274f6e2680c", "save_path": "github-repos/coq/Mestway-CourseWork", "path": "github-repos/coq/Mestway-CourseWork/CourseWork-912cf0e4a7127f2f0940cbdf1e7af274f6e2680c/CSE505/lecture/L02_inClass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7118335130771083}}
{"text": "(** Sketch of the proof of {p:nat|p<=n} = {p:nat|p<=m} -> n=m\n\n  - preliminary results on the irrelevance of boundedness proofs\n  - introduce the notion of finite cardinal |A|\n  - prove that |{p:nat|p<=n}| = n\n  - prove that |A| = n /\\ |A| = m -> n = m if equality is decidable on A\n  - prove that equality is decidable on A\n  - conclude\n*)\n\n(** * Preliminary results on [nat] and [le] *)\n\n(** Proving axiom K on [nat] *)\n\nRequire Import Eqdep_dec.\nRequire Import Arith.\n\nTheorem eq_rect_eq_nat :\n  forall (p:nat) (Q:nat->Type) (x:Q p) (h:p=p), x = eq_rect p Q x p h.\nProof.\nintros.\napply K_dec_set with (p := h).\napply eq_nat_dec.\nreflexivity.\nQed.\n\n(** Proving unicity of proofs of [(n<=m)%nat] *)\n\nScheme le_ind' := Induction for le Sort Prop.\n\nTheorem le_uniqueness_proof : forall (n m : nat) (p q : n <= m), p = q.\nProof.\ninduction p using le_ind'; intro q.\n replace (le_n n) with\n  (eq_rect _ (fun n0 => n <= n0) (le_n n) _ (refl_equal n)).\n 2:reflexivity.\n  generalize (refl_equal n).\n    pattern n at 2 4 6 10, q; case q; [intro | intros m l e].\n     rewrite <- eq_rect_eq_nat; trivial.\n     contradiction (le_Sn_n m); rewrite <- e; assumption.\n replace (le_S n m p) with\n  (eq_rect _ (fun n0 => n <= n0) (le_S n m p) _ (refl_equal (S m))).\n 2:reflexivity.\n  generalize (refl_equal (S m)).\n    pattern (S m) at 1 3 4 6, q; case q; [intro Heq | intros m0 l HeqS].\n     contradiction (le_Sn_n m); rewrite Heq; assumption.\n     injection HeqS; intro Heq; generalize l HeqS.\n      rewrite <- Heq; intros; rewrite <- eq_rect_eq_nat.\n      rewrite (IHp l0); reflexivity.\nQed.\n\n(** Proving irrelevance of boundedness proofs while building\n    elements of interval *)\n\nLemma dep_pair_intro :\n  forall (n x y:nat) (Hx : x<=n) (Hy : y<=n), x=y ->\n    exist (fun x => x <= n) x Hx = exist (fun x => x <= n) y Hy.\nProof.\nintros n x y Hx Hy Heq.\ngeneralize Hy.\nrewrite <- Heq.\nintros.\nrewrite (le_uniqueness_proof x n Hx Hy0).\nreflexivity.\nQed.\n\n(** * Proving that {p:nat|p<=n} = {p:nat|p<=m} -> n=m *)\n\n(** Definition of having finite cardinality [n+1] for a set [A] *)\n\nDefinition card (A:Set) n :=\n  exists f,\n    (forall x:A, f x <= n) /\\\n    (forall x y:A, f x = f y -> x = y) /\\\n    (forall m, m <= n -> exists x:A, f x = m).\n\nRequire Import Arith.\n\n(** Showing that the interval [0;n] has cardinality [n+1] *)\n\nTheorem card_interval : forall n, card {x:nat|x<=n} n.\nProof.\nintro n.\nexists (fun x:{x:nat|x<=n} => proj1_sig x).\nsplit.\n(* bounded *)\nintro x; apply (proj2_sig x).\nsplit.\n(* injectivity *)\nintros (p,Hp) (q,Hq).\nsimpl.\nintro Hpq.\napply dep_pair_intro; assumption.\n(* surjectivity *)\nintros m Hmn.\nexists (exist (fun x : nat => x <= n) m Hmn).\nreflexivity.\nQed.\n\n(** Showing that equality on the interval [0;n] is decidable *)\n\nLemma interval_dec :\n  forall n (x y : {m:nat|m<=n}), {x=y}+{x<>y}.\nProof.\nintros n (p,Hp).\ninduction p; intros ([|q],Hq).\nleft.\n  apply dep_pair_intro.\n  reflexivity.\nright.\n  intro H; discriminate H.\nright.\n  intro H; discriminate H.\nassert (Hp' : p <= n).\n  apply le_Sn_le; assumption.\nassert (Hq' : q <= n).\n  apply le_Sn_le; assumption.\ndestruct (IHp Hp' (exist (fun m => m <= n) q Hq'))\n  as [Heq|Hneq].\nleft.\n  injection Heq; intro Heq'.\n  apply dep_pair_intro.\n  apply eq_S.\n  assumption.\nright.\n  intro HeqS.\n  injection HeqS; intro Heq.\n  apply Hneq.\n  apply dep_pair_intro.\n  assumption.\nQed.\n\n(** Showing that the cardinality relation is functional on decidable sets *)\n\nLemma card_inj_aux :\n  forall (A:Type) f g n,\n    (forall x:A, f x <= 0) ->\n    (forall x y:A, f x = f y -> x = y) ->\n    (forall m, m <= S n -> exists x:A, g x = m)\n     -> False.\nProof.\nintros A f g n Hfbound Hfinj Hgsurj.\ndestruct (Hgsurj (S n) (le_n _)) as (x,Hx).\ndestruct (Hgsurj n (le_S _ _ (le_n _))) as (x',Hx').\nassert (Hfx : 0 = f x).\napply le_n_O_eq.\napply Hfbound.\nassert (Hfx' : 0 = f x').\napply le_n_O_eq.\napply Hfbound.\nassert (x=x').\napply Hfinj.\nrewrite <- Hfx.\nrewrite <- Hfx'.\nreflexivity.\nrewrite H in Hx.\nrewrite Hx' in Hx.\napply (n_Sn _ Hx).\nQed.\n\n(** For [dec_restrict], we use a lemma on the negation of equality\nthat requires proof-irrelevance. It should be possible to avoid this\nlemma by generalizing over a first-order definition of [x<>y], say\n[neq] such that [{x=y}+{neq x y}] and [~(x=y /\\ neq x y)]; for such\n[neq], unicity of proofs could be proven *)\n\n  Require Import Classical.\n  Lemma neq_dep_intro :\n   forall (A:Set) (z x y:A) (p:x<>z) (q:y<>z), x=y ->\n      exist (fun x => x <> z) x p = exist (fun x => x <> z) y q.\n  Proof.\n  intros A z x y p q Heq.\n   generalize q; clear q; rewrite <- Heq; intro q.\n   rewrite (proof_irrelevance _ p q); reflexivity.\n  Qed.\n\nLemma dec_restrict :\n  forall (A:Set),\n    (forall x y :A, {x=y}+{x<>y}) ->\n     forall z (x y :{a:A|a<>z}), {x=y}+{x<>y}.\nProof.\nintros A Hdec z (x,Hx) (y,Hy).\ndestruct (Hdec x y) as [Heq|Hneq].\nleft; apply neq_dep_intro; assumption.\nright; intro Heq; injection Heq; exact Hneq.\nQed.\n\nLemma pred_inj : forall n m,\n  0 <> n -> 0 <> m -> pred m = pred n -> m = n.\nProof.\ndestruct n.\nintros m H; destruct H; reflexivity.\ndestruct m.\nintros _ H; destruct H; reflexivity.\nsimpl; intros _ _ H.\nrewrite H.\nreflexivity.\nQed.\n\nLemma le_neq_lt : forall n m, n <= m -> n<>m -> n < m.\nProof.\nintros n m Hle Hneq.\ndestruct (le_lt_eq_dec n m Hle).\nassumption.\ncontradiction.\nQed.\n\nLemma inj_restrict :\n  forall (A:Set) (f:A->nat) x y z,\n    (forall x y : A, f x = f y -> x = y)\n    -> x <> z -> f y < f z -> f z <= f x\n    -> pred (f x) = f y\n    -> False.\n\n(* Search error sans le type de f !! *)\nProof.\nintros A f x y z Hfinj Hneqx Hfy Hfx Heq.\nassert (f z <> f x).\n  apply sym_not_eq.\n  intro Heqf.\n  apply Hneqx.\n  apply Hfinj.\n  assumption.\nassert (f x = S (f y)).\n  assert (0 < f x).\n    apply le_lt_trans with (f z).\n    apply le_O_n.\n    apply le_neq_lt; assumption.\n  apply pred_inj.\n  apply O_S.\n  apply lt_O_neq; assumption.\n  exact Heq.\nassert (f z <= f y).\ndestruct (le_lt_or_eq _ _ Hfx).\n  apply lt_n_Sm_le.\n  rewrite <- H0.\n  assumption.\n  contradiction Hneqx.\n  symmetry.\n  apply Hfinj.\n  assumption.\ncontradiction (lt_not_le (f y) (f z)).\nQed.\n\nTheorem card_inj : forall m n (A:Set),\n  (forall x y :A, {x=y}+{x<>y}) ->\n  card A m -> card A n -> m = n.\nProof.\ninduction m; destruct n;\nintros A Hdec\n (f,(Hfbound,(Hfinj,Hfsurj)))\n (g,(Hgbound,(Hginj,Hgsurj))).\n(* 0/0 *)\nreflexivity.\n(* 0/Sm *)\ndestruct (card_inj_aux _ _ _ _ Hfbound Hfinj Hgsurj).\n(* Sn/0 *)\ndestruct (card_inj_aux _ _ _ _ Hgbound Hginj Hfsurj).\n(* Sn/Sm *)\ndestruct (Hgsurj (S n) (le_n _)) as (xSn,HSnx).\nrewrite IHm with (n:=n) (A := {x:A|x<>xSn}).\nreflexivity.\n(* decidability of eq on {x:A|x<>xSm} *)\napply dec_restrict.\nassumption.\n(* cardinality of {x:A|x<>xSn} is m *)\npose (f' := fun x' : {x:A|x<>xSn} =>\n    let (x,Hneq) := x' in\n    if le_lt_dec (f xSn) (f x)\n    then pred (f x)\n    else f x).\nexists f'.\nsplit.\n(* f' is bounded *)\nunfold f'.\nintros (x,_).\ndestruct (le_lt_dec (f xSn) (f x)) as [Hle|Hge].\nchange m with (pred (S m)).\napply le_pred.\napply Hfbound.\napply le_S_n.\napply le_trans with (f xSn).\nexact Hge.\napply Hfbound.\nsplit.\n(* f' is injective *)\nunfold f'.\nintros (x,Hneqx) (y,Hneqy) Heqf'.\ndestruct (le_lt_dec (f xSn) (f x)) as [Hlefx|Hgefx];\ndestruct (le_lt_dec (f xSn) (f y)) as [Hlefy|Hgefy].\n(* f xSn <= f x et f xSn <= f y *)\nassert (Heq : x = y).\n  apply Hfinj.\n  assert (f xSn <> f y).\n    apply sym_not_eq.\n    intro Heqf.\n    apply Hneqy.\n    apply Hfinj.\n    assumption.\n  assert (0 < f y).\n    apply le_lt_trans with (f xSn).\n    apply le_O_n.\n    apply le_neq_lt; assumption.\n  assert (f xSn <> f x).\n    apply sym_not_eq.\n    intro Heqf.\n    apply Hneqx.\n    apply Hfinj.\n    assumption.\n  assert (0 < f x).\n    apply le_lt_trans with (f xSn).\n    apply le_O_n.\n    apply le_neq_lt; assumption.\n  apply pred_inj.\n  apply lt_O_neq; assumption.\n  apply lt_O_neq; assumption.\n  assumption.\napply neq_dep_intro; assumption.\n(* f y < f xSn <= f x *)\ndestruct (inj_restrict A f x y xSn); assumption.\n(* f x < f xSn <= f y *)\nsymmetry in Heqf'.\ndestruct (inj_restrict A f y x xSn); assumption.\n(* f x < f xSn et f y < f xSn *)\nassert (Heq : x=y).\n  apply Hfinj; assumption.\napply neq_dep_intro; assumption.\n(* f' is surjective *)\nintros p Hlep.\ndestruct (le_lt_dec (f xSn) p) as [Hle|Hlt].\n(* case f xSn <= p *)\ndestruct (Hfsurj (S p) (le_n_S _ _ Hlep)) as (x,Hx).\nassert (Hneq : x <> xSn).\n  intro Heqx.\n  rewrite Heqx in Hx.\n  rewrite Hx in Hle.\n  apply le_Sn_n with p; assumption.\nexists (exist (fun a => a<>xSn) x Hneq).\nunfold f'.\ndestruct (le_lt_dec (f xSn) (f x)) as [Hle'|Hlt'].\nrewrite Hx; reflexivity.\nrewrite Hx in Hlt'.\ncontradiction (le_not_lt (f xSn) p).\napply lt_trans with (S p).\napply lt_n_Sn.\nassumption.\n(* case p < f xSn *)\ndestruct (Hfsurj p (le_S _ _ Hlep)) as (x,Hx).\nassert (Hneq : x <> xSn).\n  intro Heqx.\n  rewrite Heqx in Hx.\n  rewrite Hx in Hlt.\n  apply (lt_irrefl p).\n  assumption.\nexists (exist (fun a => a<>xSn) x Hneq).\nunfold f'.\ndestruct (le_lt_dec (f xSn) (f x)) as [Hle'|Hlt'].\n  rewrite Hx in Hle'.\n  contradiction (lt_irrefl p).\n  apply lt_le_trans with (f xSn); assumption.\n  assumption.\n(* cardinality of {x:A|x<>xSn} is n *)\npose (g' := fun x' : {x:A|x<>xSn} =>\n   let (x,Hneq) := x' in\n   if Hdec x xSn then 0 else g x).\nexists g'.\nsplit.\n(* g is bounded *)\nunfold g'.\nintros (x,_).\ndestruct (Hdec x xSn) as [_|Hneq].\napply le_O_n.\nassert (Hle_gx:=Hgbound x).\ndestruct (le_lt_or_eq _ _ Hle_gx).\napply lt_n_Sm_le.\nassumption.\ncontradiction Hneq.\napply Hginj.\nrewrite HSnx.\nassumption.\nsplit.\n(* g is injective *)\nunfold g'.\nintros (x,Hneqx) (y,Hneqy) Heqg'.\ndestruct (Hdec x xSn) as [Heqx|_].\ncontradiction Hneqx.\ndestruct (Hdec y xSn) as [Heqy|_].\ncontradiction Hneqy.\nassert (Heq : x=y).\n  apply Hginj; assumption.\napply neq_dep_intro; assumption.\n(* g is surjective *)\nintros p Hlep.\ndestruct (Hgsurj p (le_S _ _ Hlep)) as (x,Hx).\nassert (Hneq : x<>xSn).\n  intro Heq.\n  rewrite Heq in Hx.\n  rewrite Hx in HSnx.\n  rewrite HSnx in Hlep.\n  contradiction (le_Sn_n _ Hlep).\nexists (exist (fun a => a<>xSn) x Hneq).\nsimpl.\ndestruct (Hdec x xSn) as [Heqx|_].\ncontradiction Hneq.\nassumption.\nQed.\n\n(** Conclusion *)\n\nTheorem interval_discr :\n  forall n m, {p:nat|p<=n} = {p:nat|p<=m} -> n=m.\nProof.\nintros n m Heq.\napply card_inj with (A := {p:nat|p<=n}).\napply interval_dec.\napply card_interval.\nrewrite Heq.\napply card_interval.\nQed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/doc/faq/interval_discr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8244619177503206, "lm_q1q2_score": 0.7118334909363186}}
{"text": "Require Export ZArith.\nRequire Export Arith.\n\n\nFixpoint check_range (v:Z)(r:nat)(sr:Z){struct r} : bool :=\n  match r with\n    O => true\n  | S r' =>\n    match (v mod sr)%Z with\n      Z0 => false\n    | _ => check_range v r' (Z.pred sr)\n    end\n  end.\n\nDefinition check_primality (n:nat) :=\n  check_range (Z_of_nat n)(pred (pred n))(Z_of_nat (pred n)).\n\nTheorem verif_divide :\n    forall m p:nat, 0 < m -> 0 < p ->\n    (exists q:nat, m = q*p) -> (Z_of_nat m mod Z_of_nat p = 0)%Z.\nProof.\n intros m p Hltm Hltp (q, Heq); rewrite Heq.\n rewrite inj_mult.\n replace (Z_of_nat q * Z_of_nat p)%Z with (0 + Z_of_nat q * Z_of_nat p)%Z;\n    try ring.\n rewrite Z_mod_plus; auto.\n omega.\nQed.\n\nTheorem divisor_smaller :\n    forall m p:nat, 0 < m -> forall q:nat, m = q*p -> q <= m.\nProof.\n intros m p Hlt; case p.\n -  intros q Heq; rewrite Heq in Hlt; rewrite mult_comm in Hlt.\n     elim (lt_irrefl 0);exact Hlt.\n -  intros p' q; case q.\n    +  intros Heq; rewrite Heq in Hlt.\n       elim (lt_irrefl _ Hlt).\n    + intros q' Heq; rewrite Heq.\n      rewrite mult_comm; simpl; auto with arith.\nQed.\n\nTheorem Zabs_nat_0 : forall x:Z, Z.abs_nat x = 0 -> (x = 0)%Z.\nProof.\n intros x; case x.\n -  simpl; auto.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\nQed.\n\nTheorem Z_to_nat_and_back :\n forall x:Z, (0 <= x)%Z -> (Z.of_nat (Z.abs_nat x))=x.\nProof.\n intros x; case x.\n - reflexivity. \n -  intros p Hd; elim p.\n   +  unfold Z.abs_nat; intros p' Hrec; rewrite nat_of_P_xI.\n      rewrite inj_S,  inj_mult,  Zpos_xI.\n      unfold Z.succ; rewrite Hrec;  simpl; auto.\n   +  unfold Z.abs_nat; intros p' Hrec; rewrite nat_of_P_xO.\n      rewrite inj_mult,  Zpos_xO.\n      unfold Z.succ; rewrite Hrec; simpl; auto.\n   +  simpl; auto.\n \n -  intros p' Hd; elim Hd;auto.\nQed.\n\nTheorem  check_range_correct :\n  forall (v:Z)(r:nat)(rz:Z),\n  (0 < v)%Z -> Z_of_nat (S r) = rz -> check_range v r rz = true ->\n  ~(exists k:nat, k <= S r /\\ k <> 1 /\\ \n                       (exists q:nat, Z.abs_nat v = q*k)).\nProof.\n intros v r; elim r.\n -  intros rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n   +  intros (Hle, (Hne1, (q, Heq))).\n      rewrite mult_comm in Heq; simpl in Heq.\n      rewrite (Zabs_nat_0 _ Heq) in Hlt.\n      elim (Z.lt_irrefl 0); assumption.\n \n   + intros k' (Hle, (Hne1, (q, Heq))).\n     inversion Hle.\n     *  assert (H':k'=0) by  assumption.\n        rewrite H' in Hne1; elim Hne1;auto.\n     *  assert (H': S k' <= 0) by  assumption.\n        inversion H'.\n\n -  intros r' Hrec rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n    intros (Hle, (Hne1, (q, Heq))).\n    rewrite mult_comm in Heq; simpl in Heq.\n    rewrite (Zabs_nat_0 _ Heq) in Hlt.\n    elim (Z.lt_irrefl 0); assumption.\n    intros k' (Hle, (Hne1, (q, Heq))).\n    inversion Hle.\n    rewrite <- H1 in H2. \n    rewrite <- (Z_to_nat_and_back v) in H2.\n    assert (Hmod:(Z.of_nat (Z.abs_nat v) mod Z.of_nat (S (S r')) = 0)%Z).\n    +  apply verif_divide.\n       replace 0 with (Z.abs_nat 0%Z).\n       apply Zabs_nat_lt.\n       omega.\n       simpl; auto.\n       auto with arith.\n       exists q.\n       assert (H': k' = S r') by  assumption.\n       rewrite <- H'.\n       assumption.\n    +  unfold check_range in H2.\n       rewrite Hmod in H2.\n       discriminate H2.\n      + omega.\n      + unfold check_range in H2; fold check_range in H2.\n        case_eq ((v mod rz)%Z).\n        *  intros Heqmod; rewrite Heqmod in H2; discriminate H2.\n        *  intros pmod Heqmod; rewrite Heqmod in H2;  elim (Hrec (Z.pred rz) Hlt).\n           rewrite <- H1; repeat rewrite inj_S;  rewrite <- Zpred_succ; auto. \n          assumption.\n          exists (S k'); repeat split;auto.\n          exists q; assumption.\n\n        * intros p Hmod; elim (Z_mod_lt v rz).\n          rewrite Hmod; unfold Z.le; simpl; intros Hle'; elim Hle';auto.\n          rewrite <- H1; rewrite inj_S; unfold Z.succ;\n            generalize (Zle_0_nat (S r')).\n          intros; omega.\nQed.\n\nTheorem nat_of_P_Psucc : \n forall p:positive, nat_of_P (Pos.succ p) = S (nat_of_P p).\nProof.\n intros p; elim p.\n - simpl; intros p'; rewrite nat_of_P_xO.\n   intros Heq; rewrite Heq.\n   rewrite nat_of_P_xI; ring.\n- intros p' Heq; simpl; rewrite nat_of_P_xI; rewrite nat_of_P_xO;auto.\n-  auto.\nQed.\n\nTheorem nat_to_Z_and_back:\n forall n:nat, Z.abs_nat (Z_of_nat n) = n.\nProof.\n intros n; elim n.\n -  auto.\n - intros n'; simpl; case n'.\n  +  simpl; auto.\n  +  intros n''; simpl; rewrite nat_of_P_Psucc; intros Heq; rewrite Heq; auto.\nQed.\n\nTheorem check_correct :\n  forall p:nat, 0 < p -> check_primality p = true ->\n  ~(exists k:nat, k <> 1 /\\ k <> p /\\ (exists q:nat, p = q*k)).\nProof.\n unfold lt; intros p Hle; elim Hle.\n -  intros Hcp (k, (Hne1, (Hne1bis, (q, Heq)))); rewrite mult_comm in Heq.\n    assert (Hle' : k < 1).\n    +  elim (le_lt_or_eq k 1); try(intuition; fail).\n       apply divisor_smaller with (2:= Heq); auto.\n    +  case_eq k.\n       *  intros Heq'; rewrite Heq' in Heq; simpl in Heq; discriminate Heq.\n       *  intros; omega.\n -  intros p' Hlep' Hrec; unfold check_primality.\n    assert (H':(exists p'':nat, p' = (S p''))).\n   +  inversion Hlep'.  \n      *     exists 0; auto.\n      *  eapply ex_intro;eauto.\n   +  elim H'; intros p'' Hp''; rewrite Hp''.\n      repeat rewrite <- pred_Sn.\n      intros Hcr Hex;  elim check_range_correct with (3:= Hcr).\n     *  rewrite inj_S; generalize (Zle_0_nat (S p'')).\n        intros; omega.\n     *  auto.\n     *  elim Hex; intros k (Hne1, (HneSSp'', (q, Heq))); exists k.\n       split.\n       assert (HkleSSp'': k <= S (S p'')).\n       apply (divisor_smaller (S (S p'')) q); auto with arith.\n       rewrite mult_comm; assumption.\n       omega.\n       split.\n       assumption.\n       exists q; now  rewrite nat_to_Z_and_back.\nQed.\n", "meta": {"author": "baberrehman", "repo": "interactive-theorem-proving", "sha": "e8e9de4bc664f4dd1b0fd72d6edf84f736da8874", "save_path": "github-repos/coq/baberrehman-interactive-theorem-proving", "path": "github-repos/coq/baberrehman-interactive-theorem-proving/interactive-theorem-proving-e8e9de4bc664f4dd1b0fd72d6edf84f736da8874/coq-art-8.13.0/ch16_proof_by_reflection/SRC/verif_divide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7118317824155574}}
{"text": "(* ================================================================== *)\nSection EX.\n\nVariables (A:Set) (P : A->Prop).\nVariable Q:Prop.\n\n\n(* Check the type of an expression. *)\nCheck P.\nCheck Set.\nCheck A -> Prop.\n\nVariable a:A.\n\nCheck P a.\n\n\nLemma trivial : forall x:A, P x -> P x.\nProof.\n  intros.\n  assumption.\nQed.\n\n\n(* Prints the definition of an identifier. *)\nPrint trivial.\n\n\nLemma example : forall x:A, (Q -> Q -> P x) -> Q -> P x.\nProof using .\n  intros x H H0.\n  apply H.\n  assumption.\n  assumption.\nQed.\n\nPrint example.\n\n\nProposition nova : Q -> ~ ~ Q.\nProof.\n  intros.\n  unfold not.\n  intros.\n  apply H0.\n  assumption.\nQed.           (* when we close the proof the definition of the identifier \n                  \"nova\" goes to the global environment *)\n\nTheorem demo : forall y,  Q -> (~ ~ Q -> P y) -> P y.\nProof.\n  intros.\n  apply H0.\n  apply nova.   (* we can use a definition in the global environment *)\n  assumption.\nQed.\n\n  \nEnd EX.\n\nPrint trivial.\nPrint example.\n(* ================================================================== *)\n\n\n\n\n(* ================================================================== *)\n(* ====================== Propositional Logic ======================= *)\n(* ================================================================== *)\n\nSection ExamplesPL.\n\nVariables Q P :Prop.\n\nLemma ex1 : (P -> Q) -> ~Q -> ~P.\nProof.\n  tauto.\nQed.\n\nPrint ex1.\n\nLemma ex1' : (P -> Q) -> ~Q -> ~P.\nProof.\n  intros.\n  intro.\n  apply H0.\n  apply H.\n  assumption.\nQed.\n\nPrint ex1'.\n\n\nLemma ex2 : P /\\ Q -> Q /\\ P.\nProof.\n  intro H.\n  split.\n  destruct H as [H1 H2].\n  exact H2.\n  destruct H; assumption.\nQed.\n\n(* We can itemize the subgoals using - for each of them. Note that whem entering in this mode the other subgoals are not displayed. For nested item use the symbols -, +, *, --, ++, **, ... *)\nLemma ex2' : P /\\ Q -> Q /\\ P.\nProof.\n  intro H.  split.\n  - destruct H as [H1 H2]. exact H2.\n  - destruct H; assumption.\nQed.\n\n\nLemma ex3 : P \\/ Q -> Q \\/ P.\nProof.\n  intros.\n  destruct H as [h1 | h2].\n  - right. assumption.\n  - left; assumption.\nQed.\n\n\n\nTheorem ex4 : forall A:Prop, A -> ~~A.\nProof.\n  intros.\n  intro.\n  unfold not in H0.\n  apply H0. \n  exact H.\nQed.\n\nLemma ex4' : forall A:Prop, A -> ~~A.\nProof.\n  intros.\n  red.     (* does only the unfolding of the head of the goal *)\n  intro.\n  unfold not in H0.   (* unfold – applies the delta rule for a transparent constant. *)\n  apply H0; assumption.   (* exact (H0 H) *)\nQed.\n\n\n\n\nAxiom double_neg_law : forall A:Prop, ~~A -> A.  (* classical *)\n\n(* CAUTION: Axiom is a global declaration. \n   Even after the section is closed double_neg_law is assume in the enviroment, and can be used. \n   If we want to avoid this we should declare double_neg_law using the command Hypothesis. \n*)  \n\n\nLemma ex5 : (~Q -> ~P) -> P -> Q.   (* this result is only valid classically *)\nProof.\n  intros.\n  apply double_neg_law.\n  intro.\n  (* apply H; assumption. *)\n  apply H.\n  - assumption.\n  - assumption.\nQed.\n\n\nLemma ex6 : (P\\/Q)/\\~P -> Q.\nProof.\n  intros.\n  elim H. intros .\n  destruct H0.\n  - contradiction.\n  - assumption.\nQed.\n\n\nLemma ex7 : ~(P \\/ Q) <-> ~P /\\ ~Q.\nProof.\n  red.\n  split.\n  - intros.\n    split.\n    + unfold not in H.\n      intro H1.\n      apply H.\n      left; assumption.\n    + intro H1; apply H; right; assumption.\n  - intros H H1.\n    destruct H.\n    destruct H1.  \n    + contradiction.\n    + contradiction.\nQed.\n\n\nLemma ex7' : ~(P \\/ Q) <-> ~P /\\ ~Q.\nProof.\n  tauto.\nQed.\n\n\n\nVariable B :Prop.\nVariable C :Prop.\n\n\n(* exercise *)\nLemma ex8 : (P->Q) /\\ (B->C) /\\ P /\\ B -> Q/\\C. \nProof using .\n  intros.\n  destruct H.\n  destruct H0.\n  destruct H1.\n  split.\n  - apply H. assumption.\n  - apply H0. assumption.\nQed.\n\n\n(* exercise *)\nLemma ex9 : ~ (P /\\ ~P).\nProof using .\n  red.\n  intro.\n  destruct H.\n  apply H0.\n  assumption.\nQed.\n\nEnd ExamplesPL.\n\n(* ================================================================== *)\n(* =======================  First-Order Logic ======================= *)\n(* ================================================================== *)\n\nSection ExamplesFOL.\n\nVariable X :Set.\nVariable t :X. \nVariables R W : X -> Prop.\n\nLemma ex10 : R(t) -> (forall x, R(x)->~W(x)) -> ~W(t).\nProof.\n  intros.\n  apply H0.\n  exact H.\nQed.\n\n\n\nLemma ex11 : forall x, R x -> exists x, R x.\nProof.\n  intros.\n  exists x.\n  assumption.\nQed.\n\n\nLemma ex11' : forall x, R x -> exists x, R x.\nProof.\n  firstorder.\nQed.\n\n\n\nLemma ex12 : (exists x, ~(R x)) -> ~ (forall x, R x).\nProof.\n  intros H H1.\n  destruct H as [x0 H0].\n  apply H0.\n  apply H1.\nQed.\n\n\n(* Exercise *)\nLemma ex13 : (forall x, R x) \\/ (forall x, W x) -> forall x, (R x) \\/ (W x).\nProof using .\n  intros.\n  destruct H as [H1|H2].\n  - left.\n    apply H1.\n  - right.\n    apply H2.\nQed.\n\nVariable G : X->X->Prop.\n\n(* Exercise *)\nLemma ex14 : (exists x, exists y, (G x y)) -> exists y, exists x, (G x y).\nProof.\n  intros.\n  firstorder.\nQed.  \n  \n(* Exercise *)\nProposition ex15: (forall x, W x)/\\(forall x, R x) -> (forall x, W x /\\ R x).\nProof.\n  firstorder.\nQed.\n\n(* ------- Note that we can have nested sections ----------- *)\nSection Relations.\n\nVariable D : Set.\nVariable Rel : D->D->Prop.\n\nHypothesis R_symmetric : forall x y:D, Rel x y -> Rel y x.\nHypothesis R_transitive : forall x y z:D, Rel x y -> Rel y z -> Rel x z.\n\n\nLemma refl_if : forall x:D, (exists y, Rel x y) -> Rel x x.\nProof.\n  intros.\n  destruct H.\n  (* try \"apply R_transitive\" to see de error message *)\n  apply R_transitive with x0.\n  - assumption.\n  - apply R_symmetric.\n    assumption.\nQed.\n\nCheck refl_if.\n\nEnd Relations.\n\nCheck refl_if. (* Note the difference after the end of the section Relations. *)\n\n\n\n(* ====== OTHER USES OF AXIOMS ====== *)\n\n(* --- A stack abstract data type --- *)\nSection Stack.\n\nVariable U:Type.\n\nParameter stack : Type -> Type.\nParameter emptyS : stack U. \nParameter push : U -> stack U -> stack U.\nParameter pop : stack U -> stack U.\nParameter top : stack U -> U.\nParameter isEmpty : stack U -> Prop.\n\nAxiom emptyS_isEmpty : isEmpty emptyS.\nAxiom push_notEmpty : forall x s, ~isEmpty (push x s).\nAxiom pop_push : forall x s, pop (push x s) = s.\nAxiom top_push : forall x s, top (push x s) = x.\n\nEnd Stack.\n\nCheck pop_push.\n\n(* Now we can make use of stacks in our formalisation!!! *)\n\n(* A NOTE OF CAUTION!!! *)\n(* The capability to extend the underlying theory with arbitary axiom \n   is a powerful but dangerous mechanism. We must avoid inconsistency. \n*)\nSection Caution.\n\nCheck False_ind.\n\nHypothesis ABSURD : False.\n\nTheorem oops : forall (P:Prop), P /\\ ~P.\nelim ABSURD.\nQed.\n\nEnd Caution. (* We have declared ABSURD as an hypothesis to avoid its use outside this section. *)\n\n\n\n", "meta": {"author": "lrpereira", "repo": "software-verification", "sha": "d732c6341c6fa581a367b839820f43e0488db5c2", "save_path": "github-repos/coq/lrpereira-software-verification", "path": "github-repos/coq/lrpereira-software-verification/software-verification-d732c6341c6fa581a367b839820f43e0488db5c2/coq/lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7117925591040685}}
{"text": "(** Fixed precision machine words *)\n\nRequire Import Coq.Arith.Arith Coq.Arith.Div2 Coq.NArith.NArith Coq.Bool.Bool Coq.omega.Omega.\nRequire Import Bedrock.Nomega.\n\nSet Implicit Arguments.\n\n\n(** * Basic definitions and conversion to and from [nat] *)\n\nInductive word : nat -> Set :=\n| WO : word O\n| WS : bool -> forall n, word n -> word (S n).\n\nFixpoint wordToNat sz (w : word sz) : nat :=\n  match w with\n    | WO => O\n    | WS false _ w' => (wordToNat w') * 2\n    | WS true _ w' => S (wordToNat w' * 2)\n  end.\n\nFixpoint wordToNat' sz (w : word sz) : nat :=\n  match w with\n    | WO => O\n    | WS false _ w' => 2 * wordToNat w'\n    | WS true _ w' => S (2 * wordToNat w')\n  end.\n\nTheorem wordToNat_wordToNat' : forall sz (w : word sz),\n  wordToNat w = wordToNat' w.\nProof.\n  induction w. auto. simpl. rewrite mult_comm. reflexivity.\nQed.\n\nFixpoint mod2 (n : nat) : bool :=\n  match n with\n    | 0 => false\n    | 1 => true\n    | S (S n') => mod2 n'\n  end.\n\nFixpoint natToWord (sz n : nat) : word sz :=\n  match sz with\n    | O => WO\n    | S sz' => WS (mod2 n) (natToWord sz' (div2 n))\n  end.\n\nFixpoint wordToN sz (w : word sz) : N :=\n  match w with\n    | WO => 0\n    | WS false _ w' => 2 * wordToN w'\n    | WS true _ w' => Nsucc (2 * wordToN w')\n  end%N.\n\nDefinition Nmod2 (n : N) : bool :=\n  match n with\n    | N0 => false\n    | Npos (xO _) => false\n    | _ => true\n  end.\n\nDefinition wzero sz := natToWord sz 0.\n\nFixpoint wzero' (sz : nat) : word sz :=\n  match sz with\n    | O => WO\n    | S sz' => WS false (wzero' sz')\n  end.\n\nFixpoint posToWord (sz : nat) (p : positive) {struct p} : word sz :=\n  match sz with\n    | O => WO\n    | S sz' =>\n      match p with\n        | xI p' => WS true (posToWord sz' p')\n        | xO p' => WS false (posToWord sz' p')\n        | xH => WS true (wzero' sz')\n      end\n  end.\n\nDefinition NToWord (sz : nat) (n : N) : word sz :=\n  match n with\n    | N0 => wzero' sz\n    | Npos p => posToWord sz p\n  end.\n\nFixpoint Npow2 (n : nat) : N :=\n  match n with\n    | O => 1\n    | S n' => 2 * Npow2 n'\n  end%N.\n\n\nLtac rethink :=\n  match goal with\n    | [ H : ?f ?n = _ |- ?f ?m = _ ] => replace m with n; simpl; auto\n  end.\n\nTheorem mod2_S_double : forall n, mod2 (S (2 * n)) = true.\n  induction n; simpl; intuition; rethink.\nQed.\n\nTheorem mod2_double : forall n, mod2 (2 * n) = false.\n  induction n; simpl; intuition; rewrite <- plus_n_Sm; rethink.\nQed.\n\nLocal Hint Resolve mod2_S_double mod2_double.\n\nTheorem div2_double : forall n, div2 (2 * n) = n.\n  induction n; simpl; intuition; rewrite <- plus_n_Sm; f_equal; rethink.\nQed.\n\nTheorem div2_S_double : forall n, div2 (S (2 * n)) = n.\n  induction n; simpl; intuition; f_equal; rethink.\nQed.\n\nHint Rewrite div2_double div2_S_double : div2.\n\nTheorem natToWord_wordToNat : forall sz w, natToWord sz (wordToNat w) = w.\n  induction w; rewrite wordToNat_wordToNat'; intuition; f_equal; unfold natToWord, wordToNat'; fold natToWord; fold wordToNat';\n    destruct b; f_equal; autorewrite with div2; intuition.\nQed.\n\nFixpoint pow2 (n : nat) : nat :=\n  match n with\n    | O => 1\n    | S n' => 2 * pow2 n'\n  end.\n\nTheorem roundTrip_0 : forall sz, wordToNat (natToWord sz 0) = 0.\n  induction sz; simpl; intuition.\nQed.\n\nHint Rewrite roundTrip_0 : wordToNat.\n\nLocal Hint Extern 1 (@eq nat _ _) => omega.\n\nTheorem untimes2 : forall n, n + (n + 0) = 2 * n.\n  auto.\nQed.\n\nSection strong.\n  Variable P : nat -> Prop.\n\n  Hypothesis PH : forall n, (forall m, m < n -> P m) -> P n.\n\n  Lemma strong' : forall n m, m <= n -> P m.\n    induction n; simpl; intuition; apply PH; intuition.\n    elimtype False; omega.\n  Qed.\n\n  Theorem strong : forall n, P n.\n    intros; eapply strong'; eauto.\n  Qed.\nEnd strong.\n\nTheorem div2_odd : forall n,\n  mod2 n = true\n  -> n = S (2 * div2 n).\n  induction n using strong; simpl; intuition.\n\n  destruct n; simpl in *; intuition.\n    discriminate.\n  destruct n; simpl in *; intuition.\n  do 2 f_equal.\n  replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto.\nQed.\n\nTheorem div2_even : forall n,\n  mod2 n = false\n  -> n = 2 * div2 n.\n  induction n using strong; simpl; intuition.\n\n  destruct n; simpl in *; intuition.\n  destruct n; simpl in *; intuition.\n    discriminate.\n  f_equal.\n  replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto.\nQed.\n\nLemma wordToNat_natToWord' : forall sz w, exists k, wordToNat (natToWord sz w) + k * pow2 sz = w.\n  induction sz; simpl; intuition; repeat rewrite untimes2.\n\n  exists w; intuition.\n\n  case_eq (mod2 w); intro Hmw.\n\n  specialize (IHsz (div2 w)); firstorder.\n  rewrite wordToNat_wordToNat' in *.\n  exists x; intuition.\n  rewrite mult_assoc.\n  rewrite (mult_comm x 2).\n  rewrite mult_comm. simpl mult at 1.\n  rewrite (plus_Sn_m (2 * wordToNat' (natToWord sz (div2 w)))).\n  rewrite <- mult_assoc.\n  rewrite <- mult_plus_distr_l.\n  rewrite H; clear H.\n  symmetry; apply div2_odd; auto.\n\n  specialize (IHsz (div2 w)); firstorder.\n  exists x; intuition.\n  rewrite mult_assoc.\n  rewrite (mult_comm x 2).\n  rewrite <- mult_assoc.\n  rewrite mult_comm.\n  rewrite <- mult_plus_distr_l.\n  rewrite H; clear H.\n  symmetry; apply div2_even; auto.\nQed.\n\nTheorem wordToNat_natToWord : forall sz w, exists k, wordToNat (natToWord sz w) = w - k * pow2 sz /\\ k * pow2 sz <= w.\n  intros; destruct (wordToNat_natToWord' sz w) as [k]; exists k; intuition.\nQed.\n\nDefinition wone sz := natToWord sz 1.\n\nFixpoint wones (sz : nat) : word sz :=\n  match sz with\n    | O => WO\n    | S sz' => WS true (wones sz')\n  end.\n\n\n(** Comparisons *)\n\nFixpoint wmsb sz (w : word sz) (a : bool) : bool :=\n  match w with\n    | WO => a\n    | WS b _ x => wmsb x b\n  end.\n\nDefinition whd sz (w : word (S sz)) : bool :=\n  match w in word sz' return match sz' with\n                               | O => unit\n                               | S _ => bool\n                             end with\n    | WO => tt\n    | WS b _ _ => b\n  end.\n\nDefinition wtl sz (w : word (S sz)) : word sz :=\n  match w in word sz' return match sz' with\n                               | O => unit\n                               | S sz'' => word sz''\n                             end with\n    | WO => tt\n    | WS _ _ w' => w'\n  end.\n\nTheorem WS_neq : forall b1 b2 sz (w1 w2 : word sz),\n  (b1 <> b2 \\/ w1 <> w2)\n  -> WS b1 w1 <> WS b2 w2.\n  intuition.\n  apply (f_equal (@whd _)) in H0; tauto.\n  apply (f_equal (@wtl _)) in H0; tauto.\nQed.\n\n\n(** Shattering **)\n\nLemma shatter_word : forall n (a : word n),\n  match n return word n -> Prop with\n    | O => fun a => a = WO\n    | S _ => fun a => a = WS (whd a) (wtl a)\n  end a.\n  destruct a; eauto.\nQed.\n\nLemma shatter_word_S : forall n (a : word (S n)),\n  exists b, exists c, a = WS b c.\nProof.\n  intros; repeat eexists; apply (shatter_word a).\nQed.\nLemma shatter_word_0 : forall a : word 0,\n  a = WO.\nProof.\n  intros; apply (shatter_word a).\nQed.\n\nHint Resolve shatter_word_0.\n\nRequire Import Coq.Logic.Eqdep_dec.\n\nDefinition weq : forall sz (x y : word sz), {x = y} + {x <> y}.\n  refine (fix weq sz (x : word sz) : forall y : word sz, {x = y} + {x <> y} :=\n    match x in word sz return forall y : word sz, {x = y} + {x <> y} with\n      | WO => fun _ => left _ _\n      | WS b _ x' => fun y => if bool_dec b (whd y)\n        then if weq _ x' (wtl y) then left _ _ else right _ _\n        else right _ _\n    end); clear weq.\n\n  abstract (symmetry; apply shatter_word_0).\n\n  abstract (subst; symmetry; apply (shatter_word y)).\n\n  abstract (rewrite (shatter_word y); simpl; intro; injection H; intros;\n    apply _H0; apply inj_pair2_eq_dec in H0; [ auto | apply eq_nat_dec ]).\n\n  abstract (rewrite (shatter_word y); simpl; intro; apply _H; injection H; auto).\nDefined.\n\nFixpoint weqb sz (x : word sz) : word sz -> bool :=\n  match x in word sz return word sz -> bool with\n    | WO => fun _ => true\n    | WS b _ x' => fun y =>\n      if eqb b (whd y)\n      then if @weqb _ x' (wtl y) then true else false\n      else false\n  end.\n\nTheorem weqb_true_iff : forall sz x y,\n  @weqb sz x y = true <-> x = y.\nProof.\n  induction x; simpl; intros.\n  { split; auto. }\n  { rewrite (shatter_word y) in *. simpl in *.\n    case_eq (eqb b (whd y)); intros.\n    case_eq (weqb x (wtl y)); intros.\n    split; auto; intros. rewrite eqb_true_iff in H. f_equal; eauto. eapply IHx; eauto.\n    split; intros; try congruence. inversion H1; clear H1; subst.\n    eapply inj_pair2_eq_dec in H4. eapply IHx in H4. congruence.\n    eapply Peano_dec.eq_nat_dec.\n    split; intros; try congruence.\n    inversion H0. apply eqb_false_iff in H. congruence. }\nQed.\n\n(** * Combining and splitting *)\n\nFixpoint combine (sz1 : nat) (w : word sz1) : forall sz2, word sz2 -> word (sz1 + sz2) :=\n  match w in word sz1 return forall sz2, word sz2 -> word (sz1 + sz2) with\n    | WO => fun _ w' => w'\n    | WS b _ w' => fun _ w'' => WS b (combine w' w'')\n  end.\n\nFixpoint split1 (sz1 sz2 : nat) : word (sz1 + sz2) -> word sz1 :=\n  match sz1 with\n    | O => fun _ => WO\n    | S sz1' => fun w => WS (whd w) (split1 sz1' sz2 (wtl w))\n  end.\n\nFixpoint split2 (sz1 sz2 : nat) : word (sz1 + sz2) -> word sz2 :=\n  match sz1 with\n    | O => fun w => w\n    | S sz1' => fun w => split2 sz1' sz2 (wtl w)\n  end.\n\nLtac shatterer := simpl; intuition;\n  match goal with\n    | [ w : _ |- _ ] => rewrite (shatter_word w); simpl\n  end; f_equal; auto.\n\nTheorem combine_split : forall sz1 sz2 (w : word (sz1 + sz2)),\n  combine (split1 sz1 sz2 w) (split2 sz1 sz2 w) = w.\n  induction sz1; shatterer.\nQed.\n\nTheorem split1_combine : forall sz1 sz2 (w : word sz1) (z : word sz2),\n  split1 sz1 sz2 (combine w z) = w.\n  induction sz1; shatterer.\nQed.\n\nTheorem split2_combine : forall sz1 sz2 (w : word sz1) (z : word sz2),\n  split2 sz1 sz2 (combine w z) = z.\n  induction sz1; shatterer.\nQed.\n\nRequire Import Coq.Logic.Eqdep_dec.\n\n\nTheorem combine_assoc : forall n1 (w1 : word n1) n2 n3 (w2 : word n2) (w3 : word n3) Heq,\n  combine (combine w1 w2) w3\n  = match Heq in _ = N return word N with\n      | refl_equal => combine w1 (combine w2 w3)\n    end.\n  induction w1; simpl; intuition.\n\n  rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)); reflexivity.\n\n  rewrite (IHw1 _ _ _ _ (plus_assoc _ _ _)); clear IHw1.\n  repeat match goal with\n           | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf\n         end.\n  generalize dependent (combine w1 (combine w2 w3)).\n  rewrite plus_assoc; intros.\n  rewrite (UIP_dec eq_nat_dec e (refl_equal _)).\n  rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)).\n  reflexivity.\nQed.\n\nTheorem split2_iter : forall n1 n2 n3 Heq w,\n  split2 n2 n3 (split2 n1 (n2 + n3) w)\n  = split2 (n1 + n2) n3 (match Heq in _ = N return word N with\n                           | refl_equal => w\n                         end).\n  induction n1; simpl; intuition.\n\n  rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)); reflexivity.\n\n  rewrite (IHn1 _ _ (plus_assoc _ _ _)).\n  f_equal.\n  repeat match goal with\n           | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf\n         end.\n  generalize dependent w.\n  simpl.\n  fold plus.\n  generalize (n1 + (n2 + n3)); clear.\n  intros.\n  generalize Heq e.\n  subst.\n  intros.\n  rewrite (UIP_dec eq_nat_dec e (refl_equal _)).\n  rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)).\n  reflexivity.\nQed.\n\nTheorem combine_end : forall n1 n2 n3 Heq w,\n  combine (split1 n2 n3 (split2 n1 (n2 + n3) w))\n  (split2 (n1 + n2) n3 (match Heq in _ = N return word N with\n                          | refl_equal => w\n                        end))\n  = split2 n1 (n2 + n3) w.\n  induction n1; simpl; intros.\n\n  rewrite (UIP_dec eq_nat_dec Heq (refl_equal _)).\n  apply combine_split.\n\n  rewrite (shatter_word w) in *.\n  simpl.\n  eapply trans_eq; [ | apply IHn1 with (Heq := plus_assoc _ _ _) ]; clear IHn1.\n  repeat f_equal.\n  repeat match goal with\n           | [ |- context[match ?pf with refl_equal => _ end] ] => generalize pf\n         end.\n  simpl.\n  generalize dependent w.\n  rewrite plus_assoc.\n  intros.\n  rewrite (UIP_dec eq_nat_dec e (refl_equal _)).\n  rewrite (UIP_dec eq_nat_dec Heq0 (refl_equal _)).\n  reflexivity.\nQed.\n\n\n(** * Extension operators *)\n\nDefinition sext (sz : nat) (w : word sz) (sz' : nat) : word (sz + sz') :=\n  if wmsb w false then\n    combine w (wones sz')\n  else\n    combine w (wzero sz').\n\nDefinition zext (sz : nat) (w : word sz) (sz' : nat) : word (sz + sz') :=\n  combine w (wzero sz').\n\n\n(** * Arithmetic *)\n\nDefinition wneg sz (x : word sz) : word sz :=\n  NToWord sz (Npow2 sz - wordToN x).\n\nDefinition wordBin (f : N -> N -> N) sz (x y : word sz) : word sz :=\n  NToWord sz (f (wordToN x) (wordToN y)).\n\nDefinition wplus := wordBin Nplus.\nDefinition wmult := wordBin Nmult.\nDefinition wmult' sz (x y : word sz) : word sz :=\n  split2 sz sz (NToWord (sz + sz) (Nmult (wordToN x) (wordToN y))).\nDefinition wminus sz (x y : word sz) : word sz := wplus x (wneg y).\n\nDefinition wnegN sz (x : word sz) : word sz :=\n  natToWord sz (pow2 sz - wordToNat x).\n\nDefinition wordBinN (f : nat -> nat -> nat) sz (x y : word sz) : word sz :=\n  natToWord sz (f (wordToNat x) (wordToNat y)).\n\nDefinition wplusN := wordBinN plus.\n\nDefinition wmultN := wordBinN mult.\nDefinition wmultN' sz (x y : word sz) : word sz :=\n  split2 sz sz (natToWord (sz + sz) (mult (wordToNat x) (wordToNat y))).\n\nDefinition wminusN sz (x y : word sz) : word sz := wplusN x (wnegN y).\n\n(** * Notations *)\n\nDelimit Scope word_scope with word.\nBind Scope word_scope with word.\n\nNotation \"w ~ 1\" := (WS true w)\n (at level 7, left associativity, format \"w '~' '1'\") : word_scope.\nNotation \"w ~ 0\" := (WS false w)\n (at level 7, left associativity, format \"w '~' '0'\") : word_scope.\n\nNotation \"^~\" := wneg.\nNotation \"l ^+ r\" := (@wplus _ l%word r%word) (at level 50, left associativity).\nNotation \"l ^* r\" := (@wmult _ l%word r%word) (at level 40, left associativity).\nNotation \"l ^- r\" := (@wminus _ l%word r%word) (at level 50, left associativity).\n\nTheorem wordToN_nat : forall sz (w : word sz), wordToN w = N_of_nat (wordToNat w).\n  induction w; intuition.\n  destruct b; unfold wordToN, wordToNat; fold wordToN; fold wordToNat.\n\n  rewrite N_of_S.\n  rewrite N_of_mult.\n  rewrite <- IHw.\n  rewrite Nmult_comm.\n  reflexivity.\n\n  rewrite N_of_mult.\n  rewrite <- IHw.\n  rewrite Nmult_comm.\n  reflexivity.\nQed.\n\nTheorem mod2_S : forall n k,\n  2 * k = S n\n  -> mod2 n = true.\n  induction n using strong; intros.\n  destruct n; simpl in *.\n  elimtype False; omega.\n  destruct n; simpl in *; auto.\n  destruct k; simpl in *.\n  discriminate.\n  apply H with k; auto.\nQed.\n\nTheorem wzero'_def : forall sz, wzero' sz = wzero sz.\n  unfold wzero; induction sz; simpl; intuition.\n  congruence.\nQed.\n\nTheorem posToWord_nat : forall p sz, posToWord sz p = natToWord sz (nat_of_P p).\n  induction p; destruct sz; simpl; intuition; f_equal; try rewrite wzero'_def in *.\n\n  rewrite ZL6.\n  destruct (ZL4 p) as [? Heq]; rewrite Heq; simpl.\n  replace (x + S x) with (S (2 * x)) by omega.\n  symmetry; apply mod2_S_double.\n\n  rewrite IHp.\n  rewrite ZL6.\n  destruct (nat_of_P p); simpl; intuition.\n  replace (n + S n) with (S (2 * n)) by omega.\n  rewrite div2_S_double; auto.\n\n  unfold nat_of_P; simpl.\n  rewrite ZL6.\n  replace (nat_of_P p + nat_of_P p) with (2 * nat_of_P p) by omega.\n  symmetry; apply mod2_double.\n\n  rewrite IHp.\n  unfold nat_of_P; simpl.\n  rewrite ZL6.\n  replace (nat_of_P p + nat_of_P p) with (2 * nat_of_P p) by omega.\n  rewrite div2_double.\n  auto.\n  auto.\nQed.\n\nTheorem NToWord_nat : forall sz n, NToWord sz n = natToWord sz (nat_of_N n).\n  destruct n; simpl; intuition; try rewrite wzero'_def in *.\n  auto.\n  apply posToWord_nat.\nQed.\n\nTheorem wplus_alt : forall sz (x y : word sz), wplus x y = wplusN x y.\n  unfold wplusN, wplus, wordBinN, wordBin; intros.\n\n  repeat rewrite wordToN_nat; repeat rewrite NToWord_nat.\n  rewrite nat_of_Nplus.\n  repeat rewrite nat_of_N_of_nat.\n  reflexivity.\nQed.\n\nTheorem wmult_alt : forall sz (x y : word sz), wmult x y = wmultN x y.\n  unfold wmultN, wmult, wordBinN, wordBin; intros.\n\n  repeat rewrite wordToN_nat; repeat rewrite NToWord_nat.\n  rewrite nat_of_Nmult.\n  repeat rewrite nat_of_N_of_nat.\n  reflexivity.\nQed.\n\nTheorem Npow2_nat : forall n, nat_of_N (Npow2 n) = pow2 n.\n  induction n; simpl; intuition.\n  rewrite <- IHn; clear IHn.\n  case_eq (Npow2 n); intuition.\n  rewrite untimes2.\n  replace (Npos p~0) with (Ndouble (Npos p)) by reflexivity.\n  apply nat_of_Ndouble.\nQed.\n\nTheorem wneg_alt : forall sz (x : word sz), wneg x = wnegN x.\n  unfold wnegN, wneg; intros.\n  repeat rewrite wordToN_nat; repeat rewrite NToWord_nat.\n  rewrite nat_of_Nminus.\n  do 2 f_equal.\n  apply Npow2_nat.\n  apply nat_of_N_of_nat.\nQed.\n\nTheorem wminus_Alt : forall sz (x y : word sz), wminus x y = wminusN x y.\n  intros; unfold wminusN, wminus; rewrite wneg_alt; apply wplus_alt.\nQed.\n\nTheorem wplus_unit : forall sz (x : word sz), natToWord sz 0 ^+ x = x.\n  intros; rewrite wplus_alt; unfold wplusN, wordBinN; intros.\n  rewrite roundTrip_0; apply natToWord_wordToNat.\nQed.\n\nTheorem wplus_comm : forall sz (x y : word sz), x ^+ y = y ^+ x.\n  intros; repeat rewrite wplus_alt; unfold wplusN, wordBinN; f_equal; auto.\nQed.\n\nTheorem drop_mod2 : forall n k,\n  2 * k <= n\n  -> mod2 (n - 2 * k) = mod2 n.\n  induction n using strong; intros.\n\n  do 2 (destruct n; simpl in *; repeat rewrite untimes2 in *; intuition).\n\n  destruct k; simpl in *; intuition.\n\n  destruct k; simpl; intuition.\n  rewrite <- plus_n_Sm.\n  repeat rewrite untimes2 in *.\n  simpl; auto.\n  apply H; omega.\nQed.\n\nTheorem div2_minus_2 : forall n k,\n  2 * k <= n\n  -> div2 (n - 2 * k) = div2 n - k.\n  induction n using strong; intros.\n\n  do 2 (destruct n; simpl in *; intuition; repeat rewrite untimes2 in *).\n  destruct k; simpl in *; intuition.\n\n  destruct k; simpl in *; intuition.\n  rewrite <- plus_n_Sm.\n  apply H; omega.\nQed.\n\nTheorem div2_bound : forall k n,\n  2 * k <= n\n  -> k <= div2 n.\n  intros; case_eq (mod2 n); intro Heq.\n\n  rewrite (div2_odd _ Heq) in H.\n  omega.\n\n  rewrite (div2_even _ Heq) in H.\n  omega.\nQed.\n\nTheorem drop_sub : forall sz n k,\n  k * pow2 sz <= n\n  -> natToWord sz (n - k * pow2 sz) = natToWord sz n.\n  induction sz; simpl; intuition; repeat rewrite untimes2 in *; f_equal.\n\n  rewrite mult_assoc.\n  rewrite (mult_comm k).\n  rewrite <- mult_assoc.\n  apply drop_mod2.\n  rewrite mult_assoc.\n  rewrite (mult_comm 2).\n  rewrite <- mult_assoc.\n  auto.\n\n  rewrite <- (IHsz (div2 n) k).\n  rewrite mult_assoc.\n  rewrite (mult_comm k).\n  rewrite <- mult_assoc.\n  rewrite div2_minus_2.\n  reflexivity.\n  rewrite mult_assoc.\n  rewrite (mult_comm 2).\n  rewrite <- mult_assoc.\n  auto.\n\n  apply div2_bound.\n  rewrite mult_assoc.\n  rewrite (mult_comm 2).\n  rewrite <- mult_assoc.\n  auto.\nQed.\n\nLocal Hint Extern 1 (_ <= _) => omega.\n\nTheorem wplus_assoc : forall sz (x y z : word sz), x ^+ (y ^+ z) = x ^+ y ^+ z.\n  intros; repeat rewrite wplus_alt; unfold wplusN, wordBinN; intros.\n\n  repeat match goal with\n           | [ |- context[wordToNat (natToWord ?sz ?w)] ] =>\n             let Heq := fresh \"Heq\" in\n               destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq\n         end.\n\n  replace (wordToNat x + wordToNat y - x1 * pow2 sz + wordToNat z)\n    with (wordToNat x + wordToNat y + wordToNat z - x1 * pow2 sz) by auto.\n  replace (wordToNat x + (wordToNat y + wordToNat z - x0 * pow2 sz))\n    with (wordToNat x + wordToNat y + wordToNat z - x0 * pow2 sz) by auto.\n  repeat rewrite drop_sub; auto.\nQed.\n\nTheorem roundTrip_1 : forall sz, wordToNat (natToWord (S sz) 1) = 1.\n  induction sz; simpl in *; intuition.\nQed.\n\nTheorem mod2_WS : forall sz (x : word sz) b, mod2 (wordToNat (WS b x)) = b.\n  intros. rewrite wordToNat_wordToNat'.\n  destruct b; simpl.\n\n  rewrite untimes2.\n  case_eq (2 * wordToNat x); intuition.\n  eapply mod2_S; eauto.\n  rewrite <- (mod2_double (wordToNat x)); f_equal; omega.\nQed.\n\nTheorem div2_WS : forall sz (x : word sz) b, div2 (wordToNat (WS b x)) = wordToNat x.\n  destruct b; rewrite wordToNat_wordToNat'; unfold wordToNat'; fold wordToNat'.\n  apply div2_S_double.\n  apply div2_double.\nQed.\n\nTheorem wmult_unit : forall sz (x : word sz), natToWord sz 1 ^* x = x.\n  intros; rewrite wmult_alt; unfold wmultN, wordBinN; intros.\n  destruct sz; simpl.\n  rewrite (shatter_word x); reflexivity.\n  rewrite roundTrip_0; simpl.\n  rewrite plus_0_r.\n  rewrite (shatter_word x).\n  f_equal.\n\n  apply mod2_WS.\n\n  rewrite div2_WS.\n  apply natToWord_wordToNat.\nQed.\n\nTheorem wmult_comm : forall sz (x y : word sz), x ^* y = y ^* x.\n  intros; repeat rewrite wmult_alt; unfold wmultN, wordBinN; auto with arith.\nQed.\n\nTheorem wmult_assoc : forall sz (x y z : word sz), x ^* (y ^* z) = x ^* y ^* z.\n  intros; repeat rewrite wmult_alt; unfold wmultN, wordBinN; intros.\n\n  repeat match goal with\n           | [ |- context[wordToNat (natToWord ?sz ?w)] ] =>\n             let Heq := fresh \"Heq\" in\n               destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq\n         end.\n\n  rewrite mult_minus_distr_l.\n  rewrite mult_minus_distr_r.\n  rewrite (mult_assoc (wordToNat x) x0).\n  rewrite <- (mult_assoc x1).\n  rewrite (mult_comm (pow2 sz)).\n  rewrite (mult_assoc x1).\n  repeat rewrite drop_sub; auto with arith.\n  rewrite (mult_comm x1).\n  rewrite <- (mult_assoc (wordToNat x)).\n  rewrite (mult_comm (wordToNat y)).\n  rewrite mult_assoc.\n  rewrite (mult_comm (wordToNat x)).\n  repeat rewrite <- mult_assoc.\n  auto with arith.\n  repeat rewrite <- mult_assoc.\n  auto with arith.\nQed.\n\nTheorem wmult_plus_distr : forall sz (x y z : word sz), (x ^+ y) ^* z = (x ^* z) ^+ (y ^* z).\n  intros; repeat rewrite wmult_alt; repeat rewrite wplus_alt; unfold wmultN, wplusN, wordBinN; intros.\n\n  repeat match goal with\n           | [ |- context[wordToNat (natToWord ?sz ?w)] ] =>\n             let Heq := fresh \"Heq\" in\n               destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq\n         end.\n\n  rewrite mult_minus_distr_r.\n  rewrite <- (mult_assoc x0).\n  rewrite (mult_comm (pow2 sz)).\n  rewrite (mult_assoc x0).\n\n  replace (wordToNat x * wordToNat z - x1 * pow2 sz +\n    (wordToNat y * wordToNat z - x2 * pow2 sz))\n    with (wordToNat x * wordToNat z + wordToNat y * wordToNat z - x1 * pow2 sz - x2 * pow2 sz).\n  repeat rewrite drop_sub; auto with arith.\n  rewrite (mult_comm x0).\n  rewrite (mult_comm (wordToNat x + wordToNat y)).\n  rewrite <- (mult_assoc (wordToNat z)).\n  auto with arith.\n  generalize dependent (wordToNat x * wordToNat z).\n  generalize dependent (wordToNat y * wordToNat z).\n  intros.\n  omega.\nQed.\n\nTheorem wminus_def : forall sz (x y : word sz), x ^- y = x ^+ ^~ y.\n  reflexivity.\nQed.\n\nTheorem wordToNat_bound : forall sz (w : word sz), wordToNat w < pow2 sz.\n  induction w; simpl; intuition.\n  destruct b; simpl; omega.\nQed.\n\nTheorem natToWord_pow2 : forall sz, natToWord sz (pow2 sz) = natToWord sz 0.\n  induction sz; simpl; intuition.\n\n  generalize (div2_double (pow2 sz)); simpl; intro Hr; rewrite Hr; clear Hr.\n  f_equal.\n  generalize (mod2_double (pow2 sz)); auto.\n  auto.\nQed.\n\nTheorem wminus_inv : forall sz (x : word sz), x ^+ ^~ x = wzero sz.\n  intros; rewrite wneg_alt; rewrite wplus_alt; unfold wnegN, wplusN, wzero, wordBinN; intros.\n\n  repeat match goal with\n           | [ |- context[wordToNat (natToWord ?sz ?w)] ] =>\n             let Heq := fresh \"Heq\" in\n               destruct (wordToNat_natToWord sz w) as [? [Heq ?]]; rewrite Heq\n         end.\n\n  replace (wordToNat x + (pow2 sz - wordToNat x - x0 * pow2 sz))\n    with (pow2 sz - x0 * pow2 sz).\n  rewrite drop_sub; auto with arith.\n  apply natToWord_pow2.\n  generalize (wordToNat_bound x).\n  omega.\nQed.\n\nDefinition wring (sz : nat) : ring_theory (wzero sz) (wone sz) (@wplus sz) (@wmult sz) (@wminus sz) (@wneg sz) (@eq _) :=\n  mk_rt _ _ _ _ _ _ _\n  (@wplus_unit _) (@wplus_comm _) (@wplus_assoc _)\n  (@wmult_unit _) (@wmult_comm _) (@wmult_assoc _)\n  (@wmult_plus_distr _) (@wminus_def _) (@wminus_inv _).\n\nTheorem weqb_sound : forall sz (x y : word sz), weqb x y = true -> x = y.\nProof.\n  eapply weqb_true_iff.\nQed.\n\nImplicit Arguments weqb_sound [].\n\nLtac isWcst w :=\n  match eval hnf in w with\n    | WO => constr:true\n    | WS ?b ?w' =>\n      match eval hnf in b with\n        | true => isWcst w'\n        | false => isWcst w'\n        | _ => constr:false\n      end\n    | _ => constr:false\n  end.\n\nLtac wcst w :=\n  let b := isWcst w in\n    match b with\n      | true => w\n      | _ => constr:NotConstant\n    end.\n\n(* Here's how you can add a ring for a specific bit-width.\n   There doesn't seem to be a polymorphic method, so this code really does need to be copied. *)\n\n(*\nDefinition wring8 := wring 8.\nAdd Ring wring8 : wring8 (decidable (weqb_sound 8), constants [wcst]).\n*)\n\n\n(** * Bitwise operators *)\n\nFixpoint wnot sz (w : word sz) : word sz :=\n  match w with\n    | WO => WO\n    | WS b _ w' => WS (negb b) (wnot w')\n  end.\n\nFixpoint bitwp (f : bool -> bool -> bool) sz (w1 : word sz) : word sz -> word sz :=\n  match w1 with\n    | WO => fun _ => WO\n    | WS b _ w1' => fun w2 => WS (f b (whd w2)) (bitwp f w1' (wtl w2))\n  end.\n\nDefinition wor := bitwp orb.\nDefinition wand := bitwp andb.\nDefinition wxor := bitwp xorb.\n\nNotation \"l ^| r\" := (@wor _ l%word r%word) (at level 50, left associativity).\nNotation \"l ^& r\" := (@wand _ l%word r%word) (at level 40, left associativity).\n\nTheorem wor_unit : forall sz (x : word sz), wzero sz ^| x = x.\n  unfold wzero, wor; induction x; simpl; intuition congruence.\nQed.\n\nTheorem wor_comm : forall sz (x y : word sz), x ^| y = y ^| x.\n  unfold wor; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool.\nQed.\n\nTheorem wor_assoc : forall sz (x y z : word sz), x ^| (y ^| z) = x ^| y ^| z.\n  unfold wor; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool.\nQed.\n\nTheorem wand_unit : forall sz (x : word sz), wones sz ^& x = x.\n  unfold wand; induction x; simpl; intuition congruence.\nQed.\n\nTheorem wand_kill : forall sz (x : word sz), wzero sz ^& x = wzero sz.\n  unfold wzero, wand; induction x; simpl; intuition congruence.\nQed.\n\nTheorem wand_comm : forall sz (x y : word sz), x ^& y = y ^& x.\n  unfold wand; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool.\nQed.\n\nTheorem wand_assoc : forall sz (x y z : word sz), x ^& (y ^& z) = x ^& y ^& z.\n  unfold wand; induction x; intro y; rewrite (shatter_word y); simpl; intuition; f_equal; auto with bool.\nQed.\n\nTheorem wand_or_distr : forall sz (x y z : word sz), (x ^| y) ^& z = (x ^& z) ^| (y ^& z).\n  unfold wand, wor; induction x; intro y; rewrite (shatter_word y); intro z; rewrite (shatter_word z); simpl; intuition; f_equal; auto with bool.\n  destruct (whd y); destruct (whd z); destruct b; reflexivity.\nQed.\n\nDefinition wbring (sz : nat) : semi_ring_theory (wzero sz) (wones sz) (@wor sz) (@wand sz) (@eq _) :=\n  mk_srt _ _ _ _ _\n  (@wor_unit _) (@wor_comm _) (@wor_assoc _)\n  (@wand_unit _) (@wand_kill _) (@wand_comm _) (@wand_assoc _)\n  (@wand_or_distr _).\n\n\n(** * Inequality proofs *)\n\nLtac word_simpl := unfold sext, zext, wzero in *; simpl in *.\n\nLtac word_eq := ring.\n\nLtac word_eq1 := match goal with\n                   | _ => ring\n                   | [ H : _ = _ |- _ ] => ring [H]\n                 end.\n\nTheorem word_neq : forall sz (w1 w2 : word sz),\n  w1 ^- w2 <> wzero sz\n  -> w1 <> w2.\n  intros; intro; subst.\n  unfold wminus in H.\n  rewrite wminus_inv in H.\n  tauto.\nQed.\n\nLtac word_neq := apply word_neq; let H := fresh \"H\" in intro H; simpl in H; ring_simplify in H; try discriminate.\n\nLtac word_contra := match goal with\n                      | [ H : _ <> _ |- False ] => apply H; ring\n                    end.\n\nLtac word_contra1 := match goal with\n                       | [ H : _ <> _ |- False ] => apply H;\n                         match goal with\n                           | _ => ring\n                           | [ H' : _ = _ |- _ ] => ring [H']\n                         end\n                     end.\n\nOpen Scope word_scope.\n\n(** * Signed Logic **)\nFixpoint wordToZ sz (w : word sz) : Z :=\n  if wmsb w true then\n    (** Negative **)\n    match wordToN (wneg w) with\n      | N0 => 0%Z\n      | Npos x => Zneg x\n    end\n  else\n    (** Positive **)\n    match wordToN w with\n      | N0 => 0%Z\n      | Npos x => Zpos x\n    end.\n\n(** * Comparison Predicates and Deciders **)\nDefinition wlt sz (l r : word sz) : Prop :=\n  Nlt (wordToN l) (wordToN r).\nDefinition wslt sz (l r : word sz) : Prop :=\n  Zlt (wordToZ l) (wordToZ r).\n\nNotation \"w1 > w2\" := (@wlt _ w2%word w1%word) : word_scope.\nNotation \"w1 >= w2\" := (~(@wlt _ w1%word w2%word)) : word_scope.\nNotation \"w1 < w2\" := (@wlt _ w1%word w2%word) : word_scope.\nNotation \"w1 <= w2\" := (~(@wlt _ w2%word w1%word)) : word_scope.\n\nNotation \"w1 '>s' w2\" := (@wslt _ w2%word w1%word) (at level 70) : word_scope.\nNotation \"w1 '>s=' w2\" := (~(@wslt _ w1%word w2%word)) (at level 70) : word_scope.\nNotation \"w1 '<s' w2\" := (@wslt _ w1%word w2%word) (at level 70) : word_scope.\nNotation \"w1 '<s=' w2\" := (~(@wslt _ w2%word w1%word)) (at level 70) : word_scope.\n\nDefinition wlt_dec : forall sz (l r : word sz), {l < r} + {l >= r}.\n  refine (fun sz l r =>\n    match Ncompare (wordToN l) (wordToN r) as k return Ncompare (wordToN l) (wordToN r) = k -> _ with\n      | Lt => fun pf => left _ _\n      | _ => fun pf => right _ _\n    end (refl_equal _));\n  abstract congruence.\nDefined.\n\nDefinition wslt_dec : forall sz (l r : word sz), {l <s r} + {l >s= r}.\n  refine (fun sz l r =>\n    match Zcompare (wordToZ l) (wordToZ r) as c return Zcompare (wordToZ l) (wordToZ r) = c -> _ with\n      | Lt => fun pf => left _ _\n      | _ => fun pf => right _ _\n    end (refl_equal _));\n  abstract congruence.\nDefined.\n\n(* Ordering Lemmas **)\nLemma lt_le : forall sz (a b : word sz),\n  a < b -> a <= b.\nProof.\n  unfold wlt, Nlt. intros. intro. rewrite <- Ncompare_antisym in H0. rewrite H in H0. simpl in *. congruence.\nQed.\nLemma eq_le : forall sz (a b : word sz),\n  a = b -> a <= b.\nProof.\n  intros; subst. unfold wlt, Nlt. rewrite Ncompare_refl. congruence.\nQed.\nLemma wordToN_inj : forall sz (a b : word sz),\n  wordToN a = wordToN b -> a = b.\nProof.\n  induction a; intro b0; rewrite (shatter_word b0); intuition.\n  simpl in H.\n  destruct b; destruct (whd b0); intros.\n  f_equal. eapply IHa. eapply Nsucc_inj in H.\n  destruct (wordToN a); destruct (wordToN (wtl b0)); try congruence.\n  destruct (wordToN (wtl b0)); destruct (wordToN a); inversion H.\n  destruct (wordToN (wtl b0)); destruct (wordToN a); inversion H.\n  f_equal. eapply IHa.\n  destruct (wordToN a); destruct (wordToN (wtl b0)); try congruence.\nQed.\nLemma unique_inverse : forall sz (a b1 b2 : word sz),\n  a ^+ b1 = wzero _ ->\n  a ^+ b2 = wzero _ ->\n  b1 = b2.\nProof.\n  intros.\n  transitivity (b1 ^+ wzero _).\n  rewrite wplus_comm. rewrite wplus_unit. auto.\n  transitivity (b1 ^+ (a ^+ b2)). congruence.\n  rewrite wplus_assoc.\n  rewrite (wplus_comm b1). rewrite H. rewrite wplus_unit. auto.\nQed.\nLemma sub_0_eq : forall sz (a b : word sz),\n  a ^- b = wzero _ -> a = b.\nProof.\n  intros. destruct (weq (wneg b) (wneg a)).\n  transitivity (a ^+ (^~ b ^+ b)).\n  rewrite (wplus_comm (^~ b)). rewrite wminus_inv.\n  rewrite wplus_comm. rewrite wplus_unit. auto.\n  rewrite e. rewrite wplus_assoc. rewrite wminus_inv. rewrite wplus_unit. auto.\n  unfold wminus in H.\n  generalize (unique_inverse a (wneg a) (^~ b)).\n  intros. elimtype False. apply n. symmetry; apply H0.\n  apply wminus_inv.\n  auto.\nQed.\n\nLemma le_neq_lt : forall sz (a b : word sz),\n  b <= a -> a <> b -> b < a.\nProof.\n  intros; destruct (wlt_dec b a); auto.\n  elimtype False. apply H0. unfold wlt, Nlt in *.\n  eapply wordToN_inj. eapply Ncompare_eq_correct.\n  case_eq ((wordToN a ?= wordToN b)%N); auto; try congruence.\n  intros. rewrite <- Ncompare_antisym in n. rewrite H1 in n. simpl in *. congruence.\nQed.\n\n\nHint Resolve word_neq lt_le eq_le sub_0_eq le_neq_lt : worder.\n\nLtac shatter_word x :=\n  match type of x with\n    | word 0 => try rewrite (shatter_word_0 x) in *\n    | word (S ?N) =>\n      let x' := fresh in\n      let H := fresh in\n      destruct (@shatter_word_S N x) as [ ? [ x' H ] ];\n      rewrite H in *; clear H; shatter_word x'\n  end.\n\n\n(** Uniqueness of equality proofs **)\nLemma rewrite_weq : forall sz (a b : word sz)\n  (pf : a = b),\n  weq a b = left _ pf.\nProof.\n  intros; destruct (weq a b); try solve [ elimtype False; auto ].\n  f_equal.\n  eapply UIP_dec. eapply weq.\nQed.\n\n\n(** * Some more useful derived facts *)\n\nLemma natToWord_plus : forall sz n m, natToWord sz (n + m) = natToWord _ n ^+ natToWord _ m.\n  destruct sz; intuition.\n  rewrite wplus_alt.\n  unfold wplusN, wordBinN.\n  destruct (wordToNat_natToWord (S sz) n); intuition.\n  destruct (wordToNat_natToWord (S sz) m); intuition.\n  rewrite H0; rewrite H2; clear H0 H2.\n  replace (n - x * pow2 (S sz) + (m - x0 * pow2 (S sz))) with (n + m - x * pow2 (S sz) - x0 * pow2 (S sz))\n    by omega.\n  repeat rewrite drop_sub; auto; omega.\nQed.\n\nLemma natToWord_S : forall sz n, natToWord sz (S n) = natToWord _ 1 ^+ natToWord _ n.\n  intros; change (S n) with (1 + n); apply natToWord_plus.\nQed.\n\nTheorem natToWord_inj : forall sz n m, natToWord sz n = natToWord sz m\n  -> (n < pow2 sz)%nat\n  -> (m < pow2 sz)%nat\n  -> n = m.\n  intros.\n  apply (f_equal (@wordToNat _)) in H.\n  destruct (wordToNat_natToWord sz n).\n  destruct (wordToNat_natToWord sz m).\n  intuition.\n  rewrite H4 in H; rewrite H2 in H; clear H4 H2.\n  assert (x = 0).\n  destruct x; auto.\n  simpl in *.\n  generalize dependent (x * pow2 sz).\n  intros.\n  omega.\n  assert (x0 = 0).\n  destruct x0; auto.\n  simpl in *.\n  generalize dependent (x0 * pow2 sz).\n  intros.\n  omega.\n  subst; simpl in *; omega.\nQed.\n\nLemma wordToNat_natToWord_idempotent : forall sz n,\n  (N.of_nat n < Npow2 sz)%N\n  -> wordToNat (natToWord sz n) = n.\n  intros.\n  destruct (wordToNat_natToWord sz n); intuition.\n  destruct x.\n  simpl in *; omega.\n  simpl in *.\n  apply Nlt_out in H.\n  autorewrite with N in *.\n  rewrite Npow2_nat in *.\n  generalize dependent (x * pow2 sz).\n  intros; omega.\nQed.\n\nLemma wplus_cancel : forall sz (a b c : word sz),\n  a ^+ c = b ^+ c\n  -> a = b.\n  intros.\n  apply (f_equal (fun x => x ^+ ^~ c)) in H.\n  repeat rewrite <- wplus_assoc in H.\n  rewrite wminus_inv in H.\n  repeat rewrite (wplus_comm _ (wzero sz)) in H.\n  repeat rewrite wplus_unit in H.\n  assumption.\nQed.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/src/Word.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7117925358975461}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\n\n(******************************************************************************)\n(* This file deals with divisibility for natural numbers.                     *)\n(* It contains the definitions of:                                            *)\n(*      edivn m d   == the pair composed of the quotient and remainder        *)\n(*                     of the Euclidean division of m by d.                   *)\n(*          m %/ d  == quotient of the Euclidean division of m by d.          *)\n(*          m %% d  == remainder of the Euclidean division of m by d.         *)\n(*  m = n %[mod d]  <-> m equals n modulo d.                                  *)\n(*  m == n %[mod d] <=> m equals n modulo d (boolean version).                *)\n(*  m <> n %[mod d] <-> m differs from n modulo d.                            *)\n(*  m != n %[mod d] <=> m differs from n modulo d (boolean version).          *)\n(*           d %| m <=> d divides m.                                          *)\n(*         gcdn m n == the GCD of m and n.                                    *)\n(*        egcdn m n == the extended GCD (Bezout coefficient pair) of m and n. *)\n(*                     If egcdn m n = (u, v), then gcdn m n = m * u - n * v.  *)\n(*         lcmn m n == the LCM of m and n.                                    *)\n(*      coprime m n <=> m and n are coprime (:= gcdn m n == 1).               *)\n(*  chinese m n r s == witness of the chinese remainder theorem.              *)\n(* We adjoin an m to operator suffixes to indicate a nested %% (modn), as in  *)\n(*   modnDml : m %% d + n = m + n %[mod d].                                   *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** Euclidean division *)\n\nDefinition edivn_rec d :=\n  fix loop m q := if m - d is m'.+1 then loop m' q.+1 else (q, m).\n\nDefinition edivn m d := if d > 0 then edivn_rec d.-1 m 0 else (0, m).\n\nVariant edivn_spec m d : nat * nat -> Type :=\n  EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r).\n\nLemma edivnP m d : edivn_spec m d (edivn m d).\nProof.\nrewrite -[m in edivn_spec m]/(0 * d + m) /edivn; case: d => //= d.\nelim/ltn_ind: m 0 => -[|m] IHm q //=; rewrite subn_if_gt.\ncase: ltnP => // le_dm; rewrite -[in m.+1](subnKC le_dm) -addSn.\nby rewrite addnA -mulSnr; apply/IHm/leq_subr.\nQed.\n\nLemma edivn_eq d q r : r < d -> edivn (q * d + r) d = (q, r).\nProof.\nmove=> lt_rd; have d_gt0: 0 < d by apply: leq_trans lt_rd.\ncase: edivnP lt_rd => q' r'; rewrite d_gt0 /=.\nwlog: q q' r r' / q <= q' by case/orP: (leq_total q q'); last symmetry; eauto.\nhave [||-> _ /addnI ->] //= := ltngtP q q'.\nrewrite -(leq_pmul2r d_gt0) => /leq_add lt_qr _ eq_qr _ /lt_qr {lt_qr}.\nby rewrite addnS ltnNge mulSn -addnA eq_qr addnCA addnA leq_addr.\nQed.\n\nDefinition divn m d := (edivn m d).1.\n\nNotation \"m %/ d\" := (divn m d) : nat_scope.\n\n(* We redefine modn so that it is structurally decreasing. *)\n\nDefinition modn_rec d := fix loop m := if m - d is m'.+1 then loop m' else m.\n\nDefinition modn m d := if d > 0 then modn_rec d.-1 m else m.\n\nNotation \"m %% d\" := (modn m d) : nat_scope.\nNotation \"m = n %[mod d ]\" := (m %% d = n %% d) : nat_scope.\nNotation \"m == n %[mod d ]\" := (m %% d == n %% d) : nat_scope.\nNotation \"m <> n %[mod d ]\" := (m %% d <> n %% d) : nat_scope.\nNotation \"m != n %[mod d ]\" := (m %% d != n %% d) : nat_scope.\n\nLemma modn_def m d : m %% d = (edivn m d).2.\nProof.\ncase: d => //= d; rewrite /modn /edivn /=; elim/ltn_ind: m 0 => -[|m] IHm q //=.\nby rewrite !subn_if_gt; case: (d <= m) => //; apply/IHm/leq_subr.\nQed.\n\nLemma edivn_def m d : edivn m d = (m %/ d, m %% d).\nProof. by rewrite /divn modn_def; case: (edivn m d). Qed.\n\nLemma divn_eq m d : m = m %/ d * d + m %% d.\nProof. by rewrite /divn modn_def; case: edivnP. Qed.\n\nLemma div0n d : 0 %/ d = 0. Proof. by case: d. Qed.\nLemma divn0 m : m %/ 0 = 0. Proof. by []. Qed.\nLemma mod0n d : 0 %% d = 0. Proof. by case: d. Qed.\nLemma modn0 m : m %% 0 = m. Proof. by []. Qed.\n\nLemma divn_small m d : m < d -> m %/ d = 0.\nProof. by move=> lt_md; rewrite /divn (edivn_eq 0). Qed.\n\nLemma divnMDl q m d : 0 < d -> (q * d + m) %/ d = q + m %/ d.\nProof.\nmove=> d_gt0; rewrite [in LHS](divn_eq m d) addnA -mulnDl.\nby rewrite /divn edivn_eq // modn_def; case: edivnP; rewrite d_gt0.\nQed.\n\nLemma mulnK m d : 0 < d -> m * d %/ d = m.\nProof. by move=> d_gt0; rewrite -[m * d]addn0 divnMDl // div0n addn0. Qed.\n\nLemma mulKn m d : 0 < d -> d * m %/ d = m.\nProof. by move=> d_gt0; rewrite mulnC mulnK. Qed.\n\nLemma expnB p m n : p > 0 -> m >= n -> p ^ (m - n) = p ^ m %/ p ^ n.\nProof.\nby move=> p_gt0 /subnK-Dm; rewrite -[in RHS]Dm expnD mulnK // expn_gt0 p_gt0.\nQed.\n\nLemma modn1 m : m %% 1 = 0.\nProof. by rewrite modn_def; case: edivnP => ? []. Qed.\n\nLemma divn1 m : m %/ 1 = m.\nProof. by rewrite [RHS](@divn_eq m 1) // modn1 addn0 muln1. Qed.\n\nLemma divnn d : d %/ d = (0 < d).\nProof. by case: d => // d; rewrite -[n in n %/ _]muln1 mulKn. Qed.\n\nLemma divnMl p m d : p > 0 -> p * m %/ (p * d) = m %/ d.\nProof.\nmove=> p_gt0; have [->|d_gt0] := posnP d; first by rewrite muln0.\nrewrite [RHS]/divn; case: edivnP; rewrite d_gt0 /= => q r ->{m} lt_rd.\nrewrite mulnDr mulnCA divnMDl; last by rewrite muln_gt0 p_gt0.\nby rewrite addnC divn_small // ltn_pmul2l.\nQed.\nArguments divnMl [p m d].\n\nLemma divnMr p m d : p > 0 -> m * p %/ (d * p) = m %/ d.\nProof. by move=> p_gt0; rewrite -!(mulnC p) divnMl. Qed.\nArguments divnMr [p m d].\n\nLemma ltn_mod m d : (m %% d < d) = (0 < d).\nProof. by case: d => // d; rewrite modn_def; case: edivnP. Qed.\n\nLemma ltn_pmod m d : 0 < d -> m %% d < d.\nProof. by rewrite ltn_mod. Qed.\n\nLemma leq_trunc_div m d : m %/ d * d <= m.\nProof. by rewrite [leqRHS](divn_eq m d) leq_addr. Qed.\n\nLemma leq_mod m d : m %% d <= m.\nProof. by rewrite [leqRHS](divn_eq m d) leq_addl. Qed.\n\nLemma leq_div m d : m %/ d <= m.\nProof.\nby case: d => // d; apply: leq_trans (leq_pmulr _ _) (leq_trunc_div _ _).\nQed.\n\nLemma ltn_ceil m d : 0 < d -> m < (m %/ d).+1 * d.\nProof.\nby move=> d_gt0; rewrite [in m.+1](divn_eq m d) -addnS mulSnr leq_add2l ltn_mod.\nQed.\n\nLemma ltn_divLR m n d : d > 0 -> (m %/ d < n) = (m < n * d).\nProof.\nmove=> d_gt0; apply/idP/idP.\n  by rewrite -(leq_pmul2r d_gt0); apply: leq_trans (ltn_ceil _ _).\nrewrite !ltnNge -(@leq_pmul2r d n) //; apply: contra => le_nd_floor.\nexact: leq_trans le_nd_floor (leq_trunc_div _ _).\nQed.\n\nLemma leq_divRL m n d : d > 0 -> (m <= n %/ d) = (m * d <= n).\nProof. by move=> d_gt0; rewrite leqNgt ltn_divLR // -leqNgt. Qed.\n\nLemma ltn_Pdiv m d : 1 < d -> 0 < m -> m %/ d < m.\nProof. by move=> d_gt1 m_gt0; rewrite ltn_divLR ?ltn_Pmulr // ltnW. Qed.\n\nLemma divn_gt0 d m : 0 < d -> (0 < m %/ d) = (d <= m).\nProof. by move=> d_gt0; rewrite leq_divRL ?mul1n. Qed.\n\nLemma leq_div2r d m n : m <= n -> m %/ d <= n %/ d.\nProof.\nhave [-> //| d_gt0 le_mn] := posnP d.\nby rewrite leq_divRL // (leq_trans _ le_mn) -?leq_divRL.\nQed.\n\nLemma leq_div2l m d e : 0 < d -> d <= e -> m %/ e <= m %/ d.\nProof.\nmove/leq_divRL=> -> le_de.\nby apply: leq_trans (leq_trunc_div m e); apply: leq_mul.\nQed.\n\nLemma edivnD m n d (offset := m %% d + n %% d >= d) : 0 < d ->\n   edivn (m + n) d = (m %/ d + n %/ d + offset, m %% d + n %% d - offset * d).\nProof.\nrewrite {}/offset; case: d => // d _; rewrite /divn !modn_def.\ncase: (edivnP m d.+1) (edivnP n d.+1) => [/= q r -> r_lt] [/= p s -> s_lt].\nrewrite addnACA -mulnDl; have [r_le s_le] := (ltnW r_lt, ltnW s_lt).\nhave [d_ge|d_lt] := leqP; first by rewrite addn0 mul0n subn0 edivn_eq.\nrewrite addn1 mul1n -[in LHS](subnKC d_lt) addnA -mulSnr edivn_eq//.\nby rewrite ltn_subLR// -addnS leq_add.\nQed.\n\nLemma divnD m n d : 0 < d ->\n  (m + n) %/ d = (m %/ d) + (n %/ d) + (m %% d + n %% d >= d).\nProof. by move=> /(@edivnD m n); rewrite edivn_def => -[]. Qed.\n\nLemma modnD m n d : 0 < d ->\n  (m + n) %% d = m %% d + n %% d - (m %% d + n %% d >= d) * d.\nProof. by move=> /(@edivnD m n); rewrite edivn_def => -[]. Qed.\n\nLemma leqDmod m n d : 0 < d ->\n  (d <= m %% d + n %% d) = ((m + n) %% d < n %% d).\nProof.\nmove=> d_gt0; rewrite modnD//.\nhave [d_le|_] := leqP d; last by rewrite subn0 ltnNge leq_addl.\nby rewrite -(ltn_add2r d) mul1n (subnK d_le) addnC ltn_add2l ltn_pmod.\nQed.\n\nLemma divnB n m d : 0 < d ->\n  (m - n) %/ d = (m %/ d) - (n %/ d) - (m %% d < n %% d).\nProof.\nmove=> d_gt0; have [mn|/ltnW nm] := leqP m n.\n  by rewrite (eqP mn) (eqP (leq_div2r _ _)) ?div0n.\nby rewrite -[in m %/ d](subnK nm) divnD// addnAC addnK leqDmod ?subnK ?addnK.\nQed.\n\nLemma modnB m n d : 0 < d -> n <= m ->\n  (m - n) %% d = (m %% d < n %% d) * d + m %% d - n %% d.\nProof.\nmove=> d_gt0 nm; rewrite -[in m %% _](subnK nm) -leqDmod// modnD//.\nhave [d_le|_] := leqP d; last by rewrite mul0n add0n subn0 addnK.\nby rewrite mul1n addnBA// addnC !addnK.\nQed.\n\nLemma edivnB m n d (offset := m %% d < n %% d) : 0 < d -> n <= m ->\n   edivn (m - n) d = (m %/ d - n %/ d - offset, offset * d + m %% d - n %% d).\nProof. by move=> d_gt0 le_nm; rewrite edivn_def divnB// modnB. Qed.\n\nLemma leq_divDl p m n : (m + n) %/ p <= m %/ p + n %/ p + 1.\nProof. by have [->//|p_gt0] := posnP p; rewrite divnD// !leq_add// leq_b1. Qed.\n\nLemma geq_divBl k m p : k %/ p - m %/ p <= (k - m) %/ p + 1.\nProof.\nrewrite leq_subLR addnA; apply: leq_trans (leq_divDl _ _ _).\nby rewrite -maxnE leq_div2r ?leq_maxr.\nQed.\n\nLemma divnMA m n p : m %/ (n * p) = m %/ n %/ p.\nProof.\ncase: n p => [|n] [|p]; rewrite ?muln0 ?div0n //.\nrewrite [in RHS](divn_eq m (n.+1 * p.+1)) mulnA mulnAC !divnMDl //.\nby rewrite [_ %/ p.+1]divn_small ?addn0 // ltn_divLR // mulnC ltn_mod.\nQed.\n\nLemma divnAC m n p : m %/ n %/ p =  m %/ p %/ n.\nProof. by rewrite -!divnMA mulnC. Qed.\n\nLemma modn_small m d : m < d -> m %% d = m.\nProof. by move=> lt_md; rewrite [RHS](divn_eq m d) divn_small. Qed.\n\nLemma modn_mod m d : m %% d = m %[mod d].\nProof. by case: d => // d; apply: modn_small; rewrite ltn_mod. Qed.\n\nLemma modnMDl p m d : p * d + m = m %[mod d].\nProof.\nhave [->|d_gt0] := posnP d; first by rewrite muln0.\nby rewrite [in LHS](divn_eq m d) addnA -mulnDl modn_def edivn_eq // ltn_mod.\nQed.\n\nLemma muln_modr p m d : p * (m %% d) = (p * m) %% (p * d).\nProof.\nhave [->//|p_gt0] := posnP p; apply: (@addnI (p * (m %/ d * d))).\nby rewrite -mulnDr -divn_eq mulnCA -(divnMl p_gt0) -divn_eq.\nQed.\n\nLemma muln_modl p m d : (m %% d) * p = (m * p) %% (d * p).\nProof. by rewrite -!(mulnC p); apply: muln_modr. Qed.\n\nLemma modn_divl m n d : (m %/ d) %% n = m %% (n * d) %/ d.\nProof.\ncase: d n => [|d] [|n] //; rewrite [in LHS]/divn [in LHS]modn_def.\ncase: (edivnP m d.+1) edivnP => [/= _ r -> le_rd] [/= q s -> le_sn].\nrewrite mulnDl -mulnA -addnA modnMDl modn_small ?divnMDl ?divn_small ?addn0//.\nby rewrite mulSnr -addnS leq_add ?leq_mul2r.\nQed.\n\nLemma modnDl m d : d + m = m %[mod d].\nProof. by rewrite -[m %% _](modnMDl 1) mul1n. Qed.\n\nLemma modnDr m d : m + d = m %[mod d]. Proof. by rewrite addnC modnDl. Qed.\n\nLemma modnn d : d %% d = 0. Proof. by rewrite [d %% d](modnDr 0) mod0n. Qed.\n\nLemma modnMl p d : p * d %% d = 0.\nProof. by rewrite -[p * d]addn0 modnMDl mod0n. Qed.\n\nLemma modnMr p d : d * p %% d = 0. Proof. by rewrite mulnC modnMl. Qed.\n\nLemma modnDml m n d : m %% d + n = m + n %[mod d].\nProof. by rewrite [in RHS](divn_eq m d) -addnA modnMDl. Qed.\n\nLemma modnDmr m n d : m + n %% d = m + n %[mod d].\nProof. by rewrite !(addnC m) modnDml. Qed.\n\nLemma modnDm m n d : m %% d + n %% d = m + n %[mod d].\nProof. by rewrite modnDml modnDmr. Qed.\n\nLemma eqn_modDl p m n d : (p + m == p + n %[mod d]) = (m == n %[mod d]).\nProof.\ncase: d => [|d]; first by rewrite !modn0 eqn_add2l.\napply/eqP/eqP=> eq_mn; last by rewrite -modnDmr eq_mn modnDmr.\nrewrite -(modnMDl p m) -(modnMDl p n) !mulnSr -!addnA.\nby rewrite -modnDmr eq_mn modnDmr.\nQed.\n\nLemma eqn_modDr p m n d : (m + p == n + p %[mod d]) = (m == n %[mod d]).\nProof. by rewrite -!(addnC p) eqn_modDl. Qed.\n\nLemma modnMml m n d : m %% d * n = m * n %[mod d].\nProof. by rewrite [in RHS](divn_eq m d) mulnDl mulnAC modnMDl. Qed.\n\nLemma modnMmr m n d : m * (n %% d) = m * n %[mod d].\nProof. by rewrite !(mulnC m) modnMml. Qed.\n\nLemma modnMm m n d : m %% d * (n %% d) = m * n %[mod d].\nProof. by rewrite modnMml modnMmr. Qed.\n\nLemma modn2 m : m %% 2 = odd m.\nProof. by elim: m => //= m IHm; rewrite -addn1 -modnDml IHm; case odd. Qed.\n\nLemma divn2 m : m %/ 2 = m./2.\nProof. by rewrite [in RHS](divn_eq m 2) modn2 muln2 addnC half_bit_double. Qed.\n\nLemma odd_mod m d : odd d = false -> odd (m %% d) = odd m.\nProof.\nby move=> d_even; rewrite [in RHS](divn_eq m d) oddD oddM d_even andbF.\nQed.\n\nLemma modnXm m n a : (a %% n) ^ m = a ^ m %[mod n].\nProof. by elim: m => // m IHm; rewrite !expnS -modnMmr IHm modnMml modnMmr. Qed.\n\n(** Divisibility **)\n\nDefinition dvdn d m := m %% d == 0.\n\nNotation \"m %| d\" := (dvdn m d) : nat_scope.\n\nLemma dvdnP d m : reflect (exists k, m = k * d) (d %| m).\nProof.\napply: (iffP eqP) => [md0 | [k ->]]; last by rewrite modnMl.\nby exists (m %/ d); rewrite [LHS](divn_eq m d) md0 addn0.\nQed.\nArguments dvdnP {d m}.\n\nLemma dvdn0 d : d %| 0.\nProof. by case: d. Qed.\n\nLemma dvd0n n : (0 %| n) = (n == 0).\nProof. by case: n. Qed.\n\nLemma dvdn1 d : (d %| 1) = (d == 1).\nProof. by case: d => [|[|d]] //; rewrite /dvdn modn_small. Qed.\n\nLemma dvd1n m : 1 %| m.\nProof. by rewrite /dvdn modn1. Qed.\n\nLemma dvdn_gt0 d m : m > 0 -> d %| m -> d > 0.\nProof. by case: d => // /prednK <-. Qed.\n\nLemma dvdnn m : m %| m.\nProof. by rewrite /dvdn modnn. Qed.\n\nLemma dvdn_mull d m n : d %| n -> d %| m * n.\nProof. by case/dvdnP=> n' ->; rewrite /dvdn mulnA modnMl. Qed.\n\nLemma dvdn_mulr d m n : d %| m -> d %| m * n.\nProof. by move=> d_m; rewrite mulnC dvdn_mull. Qed.\n#[global] Hint Resolve dvdn0 dvd1n dvdnn dvdn_mull dvdn_mulr : core.\n\nLemma dvdn_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2.\nProof.\nby move=> /dvdnP[q1 ->] /dvdnP[q2 ->]; rewrite mulnCA -mulnA 2?dvdn_mull.\nQed.\n\nLemma dvdn_trans n d m : d %| n -> n %| m -> d %| m.\nProof. by move=> d_dv_n /dvdnP[n1 ->]; apply: dvdn_mull. Qed.\n\nLemma dvdn_eq d m : (d %| m) = (m %/ d * d == m).\nProof.\napply/eqP/eqP=> [modm0 | <-]; last exact: modnMl.\nby rewrite [RHS](divn_eq m d) modm0 addn0.\nQed.\n\nLemma dvdn2 n : (2 %| n) = ~~ odd n.\nProof. by rewrite /dvdn modn2; case (odd n). Qed.\n\nLemma dvdn_odd m n : m %| n -> odd n -> odd m.\nProof. by move=> m_dv_n; apply: contraTT; rewrite -!dvdn2 => /dvdn_trans->. Qed.\n\nLemma divnK d m : d %| m -> m %/ d * d = m.\nProof. by rewrite dvdn_eq; move/eqP. Qed.\n\nLemma leq_divLR d m n : d %| m -> (m %/ d <= n) = (m <= n * d).\nProof. by case: d m => [|d] [|m] ///divnK=> {2}<-; rewrite leq_pmul2r. Qed.\n\nLemma ltn_divRL d m n : d %| m -> (n < m %/ d) = (n * d < m).\nProof. by move=> dv_d_m; rewrite !ltnNge leq_divLR. Qed.\n\nLemma eqn_div d m n : d > 0 -> d %| m -> (n == m %/ d) = (n * d == m).\nProof. by move=> d_gt0 dv_d_m; rewrite -(eqn_pmul2r d_gt0) divnK. Qed.\n\nLemma eqn_mul d m n : d > 0 -> d %| m -> (m == n * d) = (m %/ d == n).\nProof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqn_div // eq_sym. Qed.\n\nLemma divn_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d.\nProof.\ncase: d m => [[] //| d m] dv_d_m; apply/eqP.\nby rewrite eqn_div ?dvdn_mulr // mulnAC divnK.\nQed.\n\nLemma muln_divA d m n : d %| n -> m * (n %/ d) = m * n %/ d.\nProof. by move=> dv_d_m; rewrite !(mulnC m) divn_mulAC. Qed.\n\nLemma muln_divCA d m n : d %| m -> d %| n -> m * (n %/ d) = n * (m %/ d).\nProof. by move=> dv_d_m dv_d_n; rewrite mulnC divn_mulAC ?muln_divA. Qed.\n\nLemma divnA m n p : p %| n -> m %/ (n %/ p) = m * p %/ n.\nProof. by case: p => [|p] dv_n; rewrite -[in RHS](divnK dv_n) // divnMr. Qed.\n\nLemma modn_dvdm m n d : d %| m -> n %% m = n %[mod d].\nProof.\nby case/dvdnP=> q def_m; rewrite [in RHS](divn_eq n m) def_m mulnA modnMDl.\nQed.\n\nLemma dvdn_leq d m : 0 < m -> d %| m -> d <= m.\nProof. by move=> m_gt0 /dvdnP[[|k] Dm]; rewrite Dm // leq_addr in m_gt0 *. Qed.\n\nLemma gtnNdvd n d : 0 < n -> n < d -> (d %| n) = false.\nProof. by move=> n_gt0 lt_nd; rewrite /dvdn eqn0Ngt modn_small ?n_gt0. Qed.\n\nLemma eqn_dvd m n : (m == n) = (m %| n) && (n %| m).\nProof.\ncase: m n => [|m] [|n] //; apply/idP/andP => [/eqP -> //| []].\nby rewrite eqn_leq => Hmn Hnm; do 2 rewrite dvdn_leq //.\nQed.\n\nLemma dvdn_pmul2l p d m : 0 < p -> (p * d %| p * m) = (d %| m).\nProof. by case: p => // p _; rewrite /dvdn -muln_modr // muln_eq0. Qed.\nArguments dvdn_pmul2l [p d m].\n\nLemma dvdn_pmul2r p d m : 0 < p -> (d * p %| m * p) = (d %| m).\nProof. by move=> p_gt0; rewrite -!(mulnC p) dvdn_pmul2l. Qed.\nArguments dvdn_pmul2r [p d m].\n\nLemma dvdn_divLR p d m : 0 < p -> p %| d -> (d %/ p %| m) = (d %| m * p).\nProof. by move=> /(@dvdn_pmul2r p _ m) <- /divnK->. Qed.\n\nLemma dvdn_divRL p d m : p %| m -> (d %| m %/ p) = (d * p %| m).\nProof.\nhave [-> | /(@dvdn_pmul2r p d) <- /divnK-> //] := posnP p.\nby rewrite divn0 muln0 dvdn0.\nQed.\n\nLemma dvdn_div d m : d %| m -> m %/ d %| m.\nProof. by move/divnK=> {2}<-; apply: dvdn_mulr. Qed.\n\nLemma dvdn_exp2l p m n : m <= n -> p ^ m %| p ^ n.\nProof. by move/subnK <-; rewrite expnD dvdn_mull. Qed.\n\nLemma dvdn_Pexp2l p m n : p > 1 -> (p ^ m %| p ^ n) = (m <= n).\nProof.\nmove=> p_gt1; case: leqP => [|gt_n_m]; first exact: dvdn_exp2l.\nby rewrite gtnNdvd ?ltn_exp2l ?expn_gt0 // ltnW.\nQed.\n\nLemma dvdn_exp2r m n k : m %| n -> m ^ k %| n ^ k.\nProof. by case/dvdnP=> q ->; rewrite expnMn dvdn_mull. Qed.\n\nLemma divn_modl m n d : d %| n -> (m %% n) %/ d = (m %/ d) %% (n %/ d).\nProof. by move=> dvd_dn; rewrite modn_divl divnK. Qed.\n\nLemma dvdn_addr m d n : d %| m -> (d %| m + n) = (d %| n).\nProof. by case/dvdnP=> q ->; rewrite /dvdn modnMDl. Qed.\n\nLemma dvdn_addl n d m : d %| n -> (d %| m + n) = (d %| m).\nProof. by rewrite addnC; apply: dvdn_addr. Qed.\n\nLemma dvdn_add d m n : d %| m -> d %| n -> d %| m + n.\nProof. by move/dvdn_addr->. Qed.\n\nLemma dvdn_add_eq d m n : d %| m + n -> (d %| m) = (d %| n).\nProof. by move=> dv_d_mn; apply/idP/idP => [/dvdn_addr | /dvdn_addl] <-. Qed.\n\nLemma dvdn_subr d m n : n <= m -> d %| m -> (d %| m - n) = (d %| n).\nProof. by move=> le_n_m dv_d_m; apply: dvdn_add_eq; rewrite subnK. Qed.\n\nLemma dvdn_subl d m n : n <= m -> d %| n -> (d %| m - n) = (d %| m).\nProof. by move=> le_n_m dv_d_m; rewrite -(dvdn_addl _ dv_d_m) subnK. Qed.\n\nLemma dvdn_sub d m n : d %| m -> d %| n -> d %| m - n.\nProof.\nby case: (leqP n m) => [le_nm /dvdn_subr <- // | /ltnW/eqnP ->]; rewrite dvdn0.\nQed.\n\nLemma dvdn_exp k d m : 0 < k -> d %| m -> d %| (m ^ k).\nProof. by case: k => // k _ d_dv_m; rewrite expnS dvdn_mulr. Qed.\n\nLemma dvdn_fact m n : 0 < m <= n -> m %| n`!.\nProof.\ncase: m => //= m; elim: n => //= n IHn; rewrite ltnS.\nhave [/IHn/dvdn_mull->||-> _] // := ltngtP m n; exact: dvdn_mulr.\nQed.\n\n#[global] Hint Resolve dvdn_add dvdn_sub dvdn_exp : core.\n\nLemma eqn_mod_dvd d m n : n <= m -> (m == n %[mod d]) = (d %| m - n).\nProof.\nby move/subnK=> Dm; rewrite -[n in LHS]add0n -[in LHS]Dm eqn_modDr mod0n.\nQed.\n\nLemma divnDMl q m d : 0 < d -> (m + q * d) %/ d = (m %/ d) + q.\nProof. by move=> d_gt0; rewrite addnC divnMDl// addnC. Qed.\n\nLemma divnMBl q m d : 0 < d -> (q * d - m) %/ d = q - (m %/ d) - (~~ (d %| m)).\nProof. by move=> d_gt0; rewrite divnB// mulnK// modnMl lt0n. Qed.\n\nLemma divnBMl q m d : (m - q * d) %/ d = (m %/ d) - q.\nProof. by case: d => [|d]//=; rewrite divnB// mulnK// modnMl ltn0 subn0. Qed.\n\nLemma divnDl m n d : d %| m -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by case: d => // d /divnK-Dm; rewrite -[in LHS]Dm divnMDl. Qed.\n\nLemma divnDr m n d : d %| n -> (m + n) %/ d = m %/ d + n %/ d.\nProof. by move=> dv_n; rewrite addnC divnDl // addnC. Qed.\n\nLemma divnBl m n d : d %| m -> (m - n) %/ d = m %/ d - (n %/ d) - (~~ (d %| n)).\nProof. by case: d => [|d] // /divnK-Dm; rewrite -[in LHS]Dm divnMBl. Qed.\n\nLemma divnBr m n d : d %| n -> (m - n) %/ d = m %/ d - n %/ d.\nProof. by case: d => [|d]// /divnK-Dm; rewrite -[in LHS]Dm divnBMl. Qed.\n\nLemma edivnS m d : 0 < d -> edivn m.+1 d =\n  if d %| m.+1 then ((m %/ d).+1, 0) else (m %/ d, (m %% d).+1).\nProof.\ncase: d => [|[|d]] //= _; first by rewrite edivn_def modn1 dvd1n !divn1.\nrewrite -addn1 /dvdn modn_def edivnD//= (@modn_small 1)// (@divn_small 1)//.\nrewrite addn1 addn0 ltnS; have [||<-] := ltngtP d.+1.\n- by rewrite ltnNge -ltnS ltn_pmod.\n- by rewrite addn0 mul0n subn0.\n- by rewrite addn1 mul1n subnn.\nQed.\n\nLemma modnS m d : m.+1 %% d = if d %| m.+1 then 0 else (m %% d).+1.\nProof. by case: d => [|d]//; rewrite modn_def edivnS//; case: ifP. Qed.\n\nLemma divnS m d : 0 < d -> m.+1 %/ d = (d %| m.+1) + m %/ d.\nProof. by move=> d_gt0; rewrite /divn edivnS//; case: ifP. Qed.\n\nLemma divn_pred m d : m.-1 %/ d = (m %/ d) - (d %| m).\nProof.\nby case: d m => [|d] [|m]; rewrite ?divn1 ?dvd1n ?subn1//= divnS// addnC addnK.\nQed.\n\nLemma modn_pred m d : d != 1 -> 0 < m ->\n  m.-1 %% d = if d %| m then d.-1 else (m %% d).-1.\nProof.\nrewrite -subn1; case: d m => [|[|d]] [|m]//= _ _.\n  by rewrite ?modn1 ?dvd1n ?modn0 ?subn1.\nrewrite modnB// (@modn_small 1)// [_ < _]leqn0 /dvdn mulnbl/= subn1.\nby case: eqP => // ->; rewrite addn0.\nQed.\n\nLemma edivn_pred m d : d != 1 -> 0 < m ->\n  edivn m.-1 d = if d %| m then ((m %/ d).-1, d.-1) else (m %/ d, (m %% d).-1).\nProof.\nmove=> d_neq1 m_gt0; rewrite edivn_def divn_pred modn_pred//.\nby case: ifP; rewrite ?subn0 ?subn1.\nQed.\n\n(***********************************************************************)\n(*   A function that computes the gcd of 2 numbers                     *)\n(***********************************************************************)\n\nFixpoint gcdn_rec m n :=\n  let n' := n %% m in if n' is 0 then m else\n  if m - n'.-1 is m'.+1 then gcdn_rec (m' %% n') n' else n'.\n\nDefinition gcdn := nosimpl gcdn_rec.\n\nLemma gcdnE m n : gcdn m n = if m == 0 then n else gcdn (n %% m) m.\nProof.\nrewrite /gcdn; elim/ltn_ind: m n => -[|m] IHm [|n] //=.\ncase def_p: (_ %% _) => // [p].\nhave{def_p} lt_pm: p.+1 < m.+1 by rewrite -def_p ltn_pmod.\nrewrite {}IHm // subn_if_gt ltnW //=; congr gcdn_rec.\nby rewrite -(subnK (ltnW lt_pm)) modnDr.\nQed.\n\nLemma gcdnn : idempotent gcdn.\nProof. by case=> // n; rewrite gcdnE modnn. Qed.\n\nLemma gcdnC : commutative gcdn.\nProof.\nmove=> m n; wlog lt_nm: m n / n < m by have [? ->|? <-|-> //] := ltngtP n m.\nby rewrite gcdnE -[in m == 0](ltn_predK lt_nm) modn_small.\nQed.\n\nLemma gcd0n : left_id 0 gcdn. Proof. by case. Qed.\nLemma gcdn0 : right_id 0 gcdn. Proof. by case. Qed.\n\nLemma gcd1n : left_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnE modn1. Qed.\n\nLemma gcdn1 : right_zero 1 gcdn.\nProof. by move=> n; rewrite gcdnC gcd1n. Qed.\n\nLemma dvdn_gcdr m n : gcdn m n %| n.\nProof.\nelim/ltn_ind: m n => -[|m] IHm [|n] //=.\nrewrite gcdnE; case def_p: (_ %% _) => [|p]; first by rewrite /dvdn def_p.\nhave lt_pm: p < m by rewrite -ltnS -def_p ltn_pmod.\nrewrite /= (divn_eq n.+1 m.+1) def_p dvdn_addr ?dvdn_mull //; last exact: IHm.\nby rewrite gcdnE /= IHm // (ltn_trans (ltn_pmod _ _)).\nQed.\n\nLemma dvdn_gcdl m n : gcdn m n %| m.\nProof. by rewrite gcdnC dvdn_gcdr. Qed.\n\nLemma gcdn_gt0 m n : (0 < gcdn m n) = (0 < m) || (0 < n).\nProof.\nby case: m n => [|m] [|n] //; apply: (@dvdn_gt0 _ m.+1) => //; apply: dvdn_gcdl.\nQed.\n\nLemma gcdnMDl k m n : gcdn m (k * m + n) = gcdn m n.\nProof. by rewrite !(gcdnE m) modnMDl mulnC; case: m. Qed.\n\nLemma gcdnDl m n : gcdn m (m + n) = gcdn m n.\nProof. by rewrite -[m in m + n]mul1n gcdnMDl. Qed.\n\nLemma gcdnDr m n : gcdn m (n + m) = gcdn m n.\nProof. by rewrite addnC gcdnDl. Qed.\n\nLemma gcdnMl n m : gcdn n (m * n) = n.\nProof. by case: n => [|n]; rewrite gcdnE modnMl // muln0. Qed.\n\nLemma gcdnMr n m : gcdn n (n * m) = n.\nProof. by rewrite mulnC gcdnMl. Qed.\n\nLemma gcdn_idPl {m n} : reflect (gcdn m n = m) (m %| n).\nProof.\nby apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (gcdnMl, dvdn_gcdr).\nQed.\n\nLemma gcdn_idPr {m n} : reflect (gcdn m n = n) (n %| m).\nProof. by rewrite gcdnC; apply: gcdn_idPl. Qed.\n\nLemma expn_min e m n : e ^ minn m n = gcdn (e ^ m) (e ^ n).\nProof. by case: leqP => [|/ltnW] /(dvdn_exp2l e) /gcdn_idPl; rewrite gcdnC. Qed.\n\nLemma gcdn_modr m n : gcdn m (n %% m) = gcdn m n.\nProof. by rewrite [in RHS](divn_eq n m) gcdnMDl. Qed.\n\nLemma gcdn_modl m n : gcdn (m %% n) n = gcdn m n.\nProof. by rewrite !(gcdnC _ n) gcdn_modr. Qed.\n\n(* Extended gcd, which computes Bezout coefficients. *)\n\nFixpoint Bezout_rec km kn qs :=\n  if qs is q :: qs' then Bezout_rec kn (NatTrec.add_mul q kn km) qs'\n  else (km, kn).\n\nFixpoint egcdn_rec m n s qs :=\n  if s is s'.+1 then\n    let: (q, r) := edivn m n in\n    if r > 0 then egcdn_rec n r s' (q :: qs) else\n    if odd (size qs) then qs else q.-1 :: qs\n  else [::0].\n\nDefinition egcdn m n := Bezout_rec 0 1 (egcdn_rec m n n [::]).\n\nVariant egcdn_spec m n : nat * nat -> Type :=\n  EgcdnSpec km kn of km * m = kn * n + gcdn m n & kn * gcdn m n < m :\n    egcdn_spec m n (km, kn).\n\nLemma egcd0n n : egcdn 0 n = (1, 0).\nProof. by case: n. Qed.\n\nLemma egcdnP m n : m > 0 -> egcdn_spec m n (egcdn m n).\nProof.\nhave [-> /= | n_gt0 m_gt0] := posnP n; first by split; rewrite // mul1n gcdn0.\nrewrite /egcdn; set s := (s in egcdn_rec _ _ s); pose bz := Bezout_rec n m [::].\nhave: n < s.+1 by []; move defSpec: (egcdn_spec bz.2 bz.1) s => Spec s.\nelim: s => [[]|s IHs] //= in n m (qs := [::]) bz defSpec n_gt0 m_gt0 *.\ncase: edivnP => q r def_m; rewrite n_gt0 ltnS /= => lt_rn le_ns1.\ncase: posnP => [r0 {s le_ns1 IHs lt_rn}|r_gt0]; last first.\n  by apply: IHs => //=; [rewrite natTrecE -def_m | rewrite (leq_trans lt_rn)].\nrewrite {r}r0 addn0 in def_m; set b := odd _; pose d := gcdn m n.\npose km := ~~ b : nat; pose kn := if b then 1 else q.-1.\nrewrite [bz in Spec bz](_ : _ = Bezout_rec km kn qs); last first.\n  by rewrite /kn /km; case: (b) => //=; rewrite natTrecE addn0 muln1.\nhave def_d: d = n by rewrite /d def_m gcdnC gcdnE modnMl gcd0n -[n]prednK.\nhave: km * m + 2 * b * d = kn * n + d.\n  rewrite {}/kn {}/km def_m def_d -mulSnr; case: b; rewrite //= addn0 mul1n.\n  by rewrite prednK //; apply: dvdn_gt0 m_gt0 _; rewrite def_m dvdn_mulr.\nhave{def_m}: kn * d <= m.\n  have q_gt0 : 0 < q by rewrite def_m muln_gt0 n_gt0 ?andbT in m_gt0.\n  by rewrite /kn; case b; rewrite def_d def_m leq_pmul2r // leq_pred.\nhave{def_d}: km * d <= n by rewrite -[n]mul1n def_d leq_pmul2r // leq_b1.\nmove: km {q}kn m_gt0 n_gt0 defSpec; rewrite {}/b {}/d {}/bz.\nelim: qs m n => [|q qs IHq] n r kn kr n_gt0 r_gt0 /=.\n  set d := gcdn n r; rewrite mul0n addn0 => <- le_kn_r _ def_d; split=> //.\n  have d_gt0: 0 < d by rewrite gcdn_gt0 n_gt0.\n  have /ltn_pmul2l<-: 0 < kn by rewrite -(ltn_pmul2r n_gt0) def_d ltn_addl.\n  by rewrite def_d -addn1 leq_add // mulnCA leq_mul2l le_kn_r orbT.\nrewrite !natTrecE; set m := _ + r; set km := _ + kn; pose d := gcdn m n.\nhave ->: gcdn n r = d by rewrite [d]gcdnC gcdnMDl.\nhave m_gt0: 0 < m by rewrite addn_gt0 r_gt0 orbT.\nhave d_gt0: 0 < d by rewrite gcdn_gt0 m_gt0.\nmove=> {}/IHq IHq le_kn_r le_kr_n def_d; apply: IHq => //; rewrite -/d.\n  by rewrite mulnDl leq_add // -mulnA leq_mul2l le_kr_n orbT.\napply: (@addIn d); rewrite mulnDr -addnA addnACA -def_d addnACA mulnA.\nrewrite -!mulnDl -mulnDr -addnA [kr * _]mulnC; congr addn.\nby rewrite addnC addn_negb muln1 mul2n addnn.\nQed.\n\nLemma Bezoutl m n : m > 0 -> {a | a < m & m %| gcdn m n + a * n}.\nProof.\nmove=> m_gt0; case: (egcdnP n m_gt0) => km kn def_d lt_kn_m.\nexists kn; last by rewrite addnC -def_d dvdn_mull.\napply: leq_ltn_trans lt_kn_m.\nby rewrite -{1}[kn]muln1 leq_mul2l gcdn_gt0 m_gt0 orbT.\nQed.\n\nLemma Bezoutr m n : n > 0 -> {a | a < n & n %| gcdn m n + a * m}.\nProof. by rewrite gcdnC; apply: Bezoutl. Qed.\n\n(* Back to the gcd. *)\n\nLemma dvdn_gcd p m n : p %| gcdn m n = (p %| m) && (p %| n).\nProof.\napply/idP/andP=> [dv_pmn | [dv_pm dv_pn]].\n  by rewrite !(dvdn_trans dv_pmn) ?dvdn_gcdl ?dvdn_gcdr.\nhave [->|n_gt0] := posnP n; first by rewrite gcdn0.\ncase: (Bezoutr m n_gt0) => // km _ /(dvdn_trans dv_pn).\nby rewrite dvdn_addl // dvdn_mull.\nQed.\n\nLemma gcdnAC : right_commutative gcdn.\nProof.\nsuffices dvd m n p: gcdn (gcdn m n) p %| gcdn (gcdn m p) n.\n  by move=> m n p; apply/eqP; rewrite eqn_dvd !dvd.\nrewrite !dvdn_gcd dvdn_gcdr.\nby rewrite !(dvdn_trans (dvdn_gcdl _ p)) ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma gcdnA : associative gcdn.\nProof. by move=> m n p; rewrite !(gcdnC m) gcdnAC. Qed.\n\nLemma gcdnCA : left_commutative gcdn.\nProof. by move=> m n p; rewrite !gcdnA (gcdnC m). Qed.\n\nLemma gcdnACA : interchange gcdn gcdn.\nProof. by move=> m n p q; rewrite -!gcdnA (gcdnCA n). Qed.\n\nLemma muln_gcdr : right_distributive muln gcdn.\nProof.\nmove=> p m n; have [-> //|p_gt0] := posnP p.\nelim/ltn_ind: m n => m IHm n; rewrite gcdnE [RHS]gcdnE muln_eq0 (gtn_eqF p_gt0).\nby case: posnP => // m_gt0; rewrite -muln_modr //=; apply/IHm/ltn_pmod.\nQed.\n\nLemma muln_gcdl : left_distributive muln gcdn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_gcdr. Qed.\n\nLemma gcdn_def d m n :\n    d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) ->\n  gcdn m n = d.\nProof.\nmove=> dv_dm dv_dn gdv_d; apply/eqP.\nby rewrite eqn_dvd dvdn_gcd dv_dm dv_dn gdv_d ?dvdn_gcdl ?dvdn_gcdr.\nQed.\n\nLemma muln_divCA_gcd n m : n * (m %/ gcdn n m)  = m * (n %/ gcdn n m).\nProof. by rewrite muln_divCA ?dvdn_gcdl ?dvdn_gcdr. Qed.\n\n(* We derive the lcm directly. *)\n\nDefinition lcmn m n := m * n %/ gcdn m n.\n\nLemma lcmnC : commutative lcmn.\nProof. by move=> m n; rewrite /lcmn mulnC gcdnC. Qed.\n\nLemma lcm0n : left_zero 0 lcmn.  Proof. by move=> n; apply: div0n. Qed.\nLemma lcmn0 : right_zero 0 lcmn. Proof. by move=> n; rewrite lcmnC lcm0n. Qed.\n\nLemma lcm1n : left_id 1 lcmn.\nProof. by move=> n; rewrite /lcmn gcd1n mul1n divn1. Qed.\n\nLemma lcmn1 : right_id 1 lcmn.\nProof. by move=> n; rewrite lcmnC lcm1n. Qed.\n\nLemma muln_lcm_gcd m n : lcmn m n * gcdn m n = m * n.\nProof. by apply/eqP; rewrite divnK ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma lcmn_gt0 m n : (0 < lcmn m n) = (0 < m) && (0 < n).\nProof. by rewrite -muln_gt0 ltn_divRL ?dvdn_mull ?dvdn_gcdr. Qed.\n\nLemma muln_lcmr : right_distributive muln lcmn.\nProof.\ncase=> // m n p; rewrite /lcmn -muln_gcdr -!mulnA divnMl // mulnCA.\nby rewrite muln_divA ?dvdn_mull ?dvdn_gcdr.\nQed.\n\nLemma muln_lcml : left_distributive muln lcmn.\nProof. by move=> m n p; rewrite -!(mulnC p) muln_lcmr. Qed.\n\nLemma lcmnA : associative lcmn.\nProof.\nmove=> m n p; rewrite [LHS]/lcmn [RHS]/lcmn mulnC.\nrewrite !divn_mulAC ?dvdn_mull ?dvdn_gcdr // -!divnMA ?dvdn_mulr ?dvdn_gcdl //.\nrewrite mulnC mulnA !muln_gcdr; congr (_ %/ _).\nby rewrite ![_ * lcmn _ _]mulnC !muln_lcm_gcd !muln_gcdl -!(mulnC m) gcdnA.\nQed.\n\nLemma lcmnCA : left_commutative lcmn.\nProof. by move=> m n p; rewrite !lcmnA (lcmnC m). Qed.\n\nLemma lcmnAC : right_commutative lcmn.\nProof. by move=> m n p; rewrite -!lcmnA (lcmnC n). Qed.\n\nLemma lcmnACA : interchange lcmn lcmn.\nProof. by move=> m n p q; rewrite -!lcmnA (lcmnCA n). Qed.\n\nLemma dvdn_lcml d1 d2 : d1 %| lcmn d1 d2.\nProof. by rewrite /lcmn -muln_divA ?dvdn_gcdr ?dvdn_mulr. Qed.\n\nLemma dvdn_lcmr d1 d2 : d2 %| lcmn d1 d2.\nProof. by rewrite lcmnC dvdn_lcml. Qed.\n\nLemma dvdn_lcm d1 d2 m : lcmn d1 d2 %| m = (d1 %| m) && (d2 %| m).\nProof.\ncase: d1 d2 => [|d1] [|d2]; try by case: m => [|m]; rewrite ?lcmn0 ?andbF.\nrewrite -(@dvdn_pmul2r (gcdn d1.+1 d2.+1)) ?gcdn_gt0 // muln_lcm_gcd.\nby rewrite muln_gcdr dvdn_gcd {1}mulnC andbC !dvdn_pmul2r.\nQed.\n\nLemma lcmnMl m n : lcmn m (m * n) = m * n.\nProof. by case: m => // m; rewrite /lcmn gcdnMr mulKn. Qed.\n\nLemma lcmnMr m n : lcmn n (m * n) = m * n.\nProof. by rewrite mulnC lcmnMl. Qed.\n\nLemma lcmn_idPr {m n} : reflect (lcmn m n = n) (m %| n).\nProof.\nby apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (lcmnMr, dvdn_lcml).\nQed.\n\nLemma lcmn_idPl {m n} : reflect (lcmn m n = m) (n %| m).\nProof. by rewrite lcmnC; apply: lcmn_idPr. Qed.\n\nLemma expn_max e m n : e ^ maxn m n = lcmn (e ^ m) (e ^ n).\nProof. by case: leqP => [|/ltnW] /(dvdn_exp2l e) /lcmn_idPl; rewrite lcmnC. Qed.\n\n(* Coprime factors *)\n\nDefinition coprime m n := gcdn m n == 1.\n\nLemma coprime1n n : coprime 1 n.\nProof. by rewrite /coprime gcd1n. Qed.\n\nLemma coprimen1 n : coprime n 1.\nProof. by rewrite /coprime gcdn1. Qed.\n\nLemma coprime_sym m n : coprime m n = coprime n m.\nProof. by rewrite /coprime gcdnC. Qed.\n\nLemma coprime_modl m n : coprime (m %% n) n = coprime m n.\nProof. by rewrite /coprime gcdn_modl. Qed.\n\nLemma coprime_modr m n : coprime m (n %% m) = coprime m n.\nProof. by rewrite /coprime gcdn_modr. Qed.\n\nLemma coprime2n n : coprime 2 n = odd n.\nProof. by rewrite -coprime_modr modn2; case: (odd n). Qed.\n\nLemma coprimen2 n : coprime n 2 = odd n.\nProof. by rewrite coprime_sym coprime2n. Qed.\n\nLemma coprimeSn n : coprime n.+1 n.\nProof. by rewrite -coprime_modl (modnDr 1) coprime_modl coprime1n. Qed.\n\nLemma coprimenS n : coprime n n.+1.\nProof. by rewrite coprime_sym coprimeSn. Qed.\n\nLemma coprimePn n : n > 0 -> coprime n.-1 n.\nProof. by case: n => // n _; rewrite coprimenS. Qed.\n\nLemma coprimenP n : n > 0 -> coprime n n.-1.\nProof. by case: n => // n _; rewrite coprimeSn. Qed.\n\nLemma coprimeP n m :\n  n > 0 -> reflect (exists u, u.1 * n - u.2 * m = 1) (coprime n m).\nProof.\nmove=> n_gt0; apply: (iffP eqP) => [<-| [[kn km] /= kn_km_1]].\n  by have [kn km kg _] := egcdnP m n_gt0; exists (kn, km); rewrite kg addKn.\napply gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m.\nby rewrite -kn_km_1 dvdn_subr ?dvdn_mull // ltnW // -subn_gt0 kn_km_1.\nQed.\n\nLemma modn_coprime k n : 0 < k -> (exists u, (k * u) %% n = 1) -> coprime k n.\nProof.\nmove=> k_gt0 [u Hu]; apply/coprimeP=> //.\nby exists (u, k * u %/ n); rewrite /= mulnC {1}(divn_eq (k * u) n) addKn.\nQed.\n\nLemma Gauss_dvd m n p : coprime m n -> (m * n %| p) = (m %| p) && (n %| p).\nProof. by move=> co_mn; rewrite -muln_lcm_gcd (eqnP co_mn) muln1 dvdn_lcm. Qed.\n\nLemma Gauss_dvdr m n p : coprime m n -> (m %| n * p) = (m %| p).\nProof.\ncase: n => [|n] co_mn; first by case: m co_mn => [|[]] // _; rewrite !dvd1n.\nby symmetry; rewrite mulnC -(@dvdn_pmul2r n.+1) ?Gauss_dvd // andbC dvdn_mull.\nQed.\n\nLemma Gauss_dvdl m n p : coprime m p -> (m %| n * p) = (m %| n).\nProof. by rewrite mulnC; apply: Gauss_dvdr. Qed.\n\nLemma dvdn_double_leq m n : m %| n -> odd m -> ~~ odd n -> 0 < n -> m.*2 <= n.\nProof.\nmove=> m_dv_n odd_m even_n n_gt0.\nby rewrite -muln2 dvdn_leq // Gauss_dvd ?coprimen2 ?m_dv_n ?dvdn2.\nQed.\n\nLemma dvdn_double_ltn m n : m %| n.-1 -> odd m -> odd n -> 1 < n -> m.*2 < n.\nProof. by case: n => //; apply: dvdn_double_leq. Qed.\n\nLemma Gauss_gcdr p m n : coprime p m -> gcdn p (m * n) = gcdn p n.\nProof.\nmove=> co_pm; apply/eqP; rewrite eqn_dvd !dvdn_gcd !dvdn_gcdl /=.\nrewrite andbC dvdn_mull ?dvdn_gcdr //= -(@Gauss_dvdr _ m) ?dvdn_gcdr //.\nby rewrite /coprime gcdnAC (eqnP co_pm) gcd1n.\nQed.\n\nLemma Gauss_gcdl p m n : coprime p n -> gcdn p (m * n) = gcdn p m.\nProof. by move=> co_pn; rewrite mulnC Gauss_gcdr. Qed.\n\nLemma coprimeMr p m n : coprime p (m * n) = coprime p m && coprime p n.\nProof.\ncase co_pm: (coprime p m) => /=; first by rewrite /coprime Gauss_gcdr.\napply/eqP=> co_p_mn; case/eqnP: co_pm; apply gcdn_def => // d dv_dp dv_dm.\nby rewrite -co_p_mn dvdn_gcd dv_dp dvdn_mulr.\nQed.\n\nLemma coprimeMl p m n : coprime (m * n) p = coprime m p && coprime n p.\nProof. by rewrite -!(coprime_sym p) coprimeMr. Qed.\n\nLemma coprime_pexpl k m n : 0 < k -> coprime (m ^ k) n = coprime m n.\nProof.\ncase: k => // k _; elim: k => [|k IHk]; first by rewrite expn1.\nby rewrite expnS coprimeMl -IHk; case coprime.\nQed.\n\nLemma coprime_pexpr k m n : 0 < k -> coprime m (n ^ k) = coprime m n.\nProof. by move=> k_gt0; rewrite !(coprime_sym m) coprime_pexpl. Qed.\n\nLemma coprimeXl k m n : coprime m n -> coprime (m ^ k) n.\nProof. by case: k => [|k] co_pm; rewrite ?coprime1n // coprime_pexpl. Qed.\n\nLemma coprimeXr k m n : coprime m n -> coprime m (n ^ k).\nProof. by rewrite !(coprime_sym m); apply: coprimeXl. Qed.\n\nLemma coprime_dvdl m n p : m %| n -> coprime n p -> coprime m p.\nProof. by case/dvdnP=> d ->; rewrite coprimeMl => /andP[]. Qed.\n\nLemma coprime_dvdr m n p : m %| n -> coprime p n -> coprime p m.\nProof. by rewrite !(coprime_sym p); apply: coprime_dvdl. Qed.\n\nLemma coprime_egcdn n m : n > 0 -> coprime (egcdn n m).1 (egcdn n m).2.\nProof.\nmove=> n_gt0; case: (egcdnP m n_gt0) => kn km /= /eqP.\nhave [/dvdnP[u defn] /dvdnP[v defm]] := (dvdn_gcdl n m, dvdn_gcdr n m).\nrewrite -[gcdn n m]mul1n {1}defm {1}defn !mulnA -mulnDl addnC.\nrewrite eqn_pmul2r ?gcdn_gt0 ?n_gt0 //; case: kn => // kn /eqP def_knu _.\nby apply/coprimeP=> //; exists (u, v); rewrite mulnC def_knu mulnC addnK.\nQed.\n\nLemma dvdn_pexp2r m n k : k > 0 -> (m ^ k %| n ^ k) = (m %| n).\nProof.\nmove=> k_gt0; apply/idP/idP=> [dv_mn_k|]; last exact: dvdn_exp2r.\nhave [->|n_gt0] := posnP n; first by rewrite dvdn0.\nhave [n' def_n] := dvdnP (dvdn_gcdr m n); set d := gcdn m n in def_n.\nhave [m' def_m] := dvdnP (dvdn_gcdl m n); rewrite -/d in def_m.\nhave d_gt0: d > 0 by rewrite gcdn_gt0 n_gt0 orbT.\nrewrite def_m def_n !expnMn dvdn_pmul2r ?expn_gt0 ?d_gt0 // in dv_mn_k.\nhave: coprime (m' ^ k) (n' ^ k).\n  rewrite coprime_pexpl // coprime_pexpr // /coprime -(eqn_pmul2r d_gt0) mul1n.\n  by rewrite muln_gcdl -def_m -def_n.\nrewrite /coprime -gcdn_modr (eqnP dv_mn_k) gcdn0 -(exp1n k).\nby rewrite (inj_eq (expIn k_gt0)) def_m; move/eqP->; rewrite mul1n dvdn_gcdr.\nQed.\n\nSection Chinese.\n\n(***********************************************************************)\n(*   The chinese remainder theorem                                     *)\n(***********************************************************************)\n\nVariables m1 m2 : nat.\nHypothesis co_m12 : coprime m1 m2.\n\nLemma chinese_remainder x y :\n  (x == y %[mod m1 * m2]) = (x == y %[mod m1]) && (x == y %[mod m2]).\nProof.\nwlog le_yx : x y / y <= x; last by rewrite !eqn_mod_dvd // Gauss_dvd.\nby have [?|/ltnW ?] := leqP y x; last rewrite !(eq_sym (x %% _)); apply.\nQed.\n\n(***********************************************************************)\n(*   A function that solves the chinese remainder problem              *)\n(***********************************************************************)\n\nDefinition chinese r1 r2 :=\n  r1 * m2 * (egcdn m2 m1).1 + r2 * m1 * (egcdn m1 m2).1.\n\nLemma chinese_modl r1 r2 : chinese r1 r2 = r1 %[mod m1].\nProof.\nrewrite /chinese; case: (posnP m2) co_m12 => [-> /eqnP | m2_gt0 _].\n  by rewrite gcdn0 => ->; rewrite !modn1.\ncase: egcdnP => // k2 k1 def_m1 _.\nrewrite mulnAC -mulnA def_m1 gcdnC (eqnP co_m12) mulnDr mulnA muln1.\nby rewrite addnAC (mulnAC _ m1) -mulnDl modnMDl.\nQed.\n\nLemma chinese_modr r1 r2 : chinese r1 r2 = r2 %[mod m2].\nProof.\nrewrite /chinese; case: (posnP m1) co_m12 => [-> /eqnP | m1_gt0 _].\n  by rewrite gcd0n => ->; rewrite !modn1.\ncase: (egcdnP m2) => // k1 k2 def_m2 _.\nrewrite addnC mulnAC -mulnA def_m2 (eqnP co_m12) mulnDr mulnA muln1.\nby rewrite addnAC (mulnAC _ m2) -mulnDl modnMDl.\nQed.\n\nLemma chinese_mod x : x = chinese (x %% m1) (x %% m2) %[mod m1 * m2].\nProof.\napply/eqP; rewrite chinese_remainder //.\nby rewrite chinese_modl chinese_modr !modn_mod !eqxx.\nQed.\n\nEnd Chinese.\n", "meta": {"author": "math-comp", "repo": "math-comp", "sha": "e39f9173b484f2e8e7f69f746a619dcc8f3abc1b", "save_path": "github-repos/coq/math-comp-math-comp", "path": "github-repos/coq/math-comp-math-comp/math-comp-e39f9173b484f2e8e7f69f746a619dcc8f3abc1b/mathcomp/ssreflect/div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7117781177992304}}
{"text": "(* Arithmetic expressions *)\n\nRequire Import imports.\nRequire Import String.\nLocal Open Scope Z_scope.\n\nDefinition vname := string.\nDefinition val := Z.\n\nInductive aexpr :=\n| Anum : val -> aexpr\n| Avar : vname -> aexpr\n| Aplus : aexpr -> aexpr -> aexpr.\n\nDefinition state := vname -> val.\n\nFixpoint aval (s : state) (e : aexpr) :=\n  match e with\n  | Anum n => n\n  | Avar x => s x\n  | Aplus x y => aval s x + aval s y\n  end.\n\nFixpoint asimp_const (e : aexpr) :=\n  match e with\n  | Anum n => Anum n\n  | Avar x => Avar x\n  | Aplus e1 e2 =>\n    match asimp_const e1, asimp_const e2 with\n    | Anum n1, Anum n2 => Anum (n1 + n2)\n    | e1', e2' => Aplus e1' e2'\n    end\n  end.\n\nLemma lem_aval_asimp_const : forall s e, aval s (asimp_const e) = aval s e.\nProof.\n  induction e; sauto.\nQed.\n\nFixpoint plus (e1 e2 : aexpr) :=\n  match e1, e2 with\n  | Anum n1, Anum n2 => Anum (n1 + n2)\n  | Anum 0, _ => e2\n  | _, Anum 0 => e1\n  | _, _ => Aplus e1 e2\n  end.\n\nLemma lem_aval_plus : forall s e1 e2, aval s (plus e1 e2) = aval s e1 + aval s e2.\nProof.\n  Reconstr.scrush (** hammer *).\nQed.\n\nFixpoint asimp (e : aexpr) :=\n  match e with\n  | Aplus x y => plus (asimp x) (asimp y)\n  | _ => e\n  end.\n\nLemma lem_aval_asimp : forall s e, aval s (asimp e) = aval s e.\nProof.\n  induction e; sauto.\n  Reconstr.htrivial Reconstr.AllHyps\n                    (@lem_aval_plus)\n                    Reconstr.Empty.\nQed.\n", "meta": {"author": "lukaszcz", "repo": "COQ-IMP", "sha": "2caaab1d568be095c6a35de778146310e6542f02", "save_path": "github-repos/coq/lukaszcz-COQ-IMP", "path": "github-repos/coq/lukaszcz-COQ-IMP/COQ-IMP-2caaab1d568be095c6a35de778146310e6542f02/AExp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7117781131193934}}
{"text": "Require Import Frap.\n\n(* Levels of verification *)\nFixpoint my_reverse (A: Type) (l: list A): list A :=\n  match l with\n  | nil => nil\n  | cons head tail => app (my_reverse A tail) (cons head nil)\n  end.\n\nArguments my_reverse [A].\n\nTheorem my_reverse_correct1: forall (A: Type) (l: list A),\n  length l = length (my_reverse l).\nProof.\n  simplify.\n  induct l.\n  + simplify. trivial.\n  + simplify.\n    rewrite IHl.\n    Search (length (_ ++ _) = length _ + length _).\n    (* https://coq.inria.fr/library/Coq.Lists.List.html *)\n    rewrite app_length.\n    simplify.\n    linear_arithmetic.\nQed.\n\nTheorem my_reverse_correct2: forall (A: Type) (l: list A),\n  length l = length (my_reverse l) /\\\n  (forall (e: A), (In e l) -> In e (my_reverse l)) /\\\n  (forall (e: A), (In e (my_reverse l)) -> In e l).\nProof.\n  simplify.\n  propositional.\n  + apply my_reverse_correct1.\n  + induct l.\n    - simplify. trivial.\n    - simplify.\n      Locate \"\\/\".\n      Print or.\n      destruct H. (* alternatively invert from Frap *)\n      * \n        Search (In _ _ \\/ In _ _ -> In _ (_ ++ _)).\n        apply in_or_app.\n        simplify.\n        propositional.\n      * apply in_or_app.\n        (* version 1: natural-deduction like *)\n        apply or_introl.\n        apply IHl.\n        assumption.\n        (* alternatively:\n         apply IHl in H. propositional *)\n  + induct l.\n    - simplify. trivial.\n    - simplify.\n      Search (In _ (_ ++ _) -> In _ _ \\/ In _ _).\n      apply in_app_or in H.\n      destruct H.\n      * apply or_intror.\n        apply IHl.\n        assumption.\n      * simplify.\n        propositional.\nQed.\n\nTheorem my_reverse_correct3: forall (A: Type) (l: list A),\n  length l = length (my_reverse l) /\\\n  (forall (a: A), my_reverse [a] = [a]) /\\\n  forall (l1 l2: list A) (a1 a2: A),\n    (my_reverse (l1 ++ [a1; a2] ++ l2)) = (my_reverse l2) ++ [a2; a1] ++ (my_reverse l1).\nProof.\n  pose my_reverse_correct1.\n  simplify.\n  propositional.\n  + apply e.\n  + induct l1; induct l2; simplify.\n    - equality.\n    - Search ((_ ++ _) ++ _ = _ ++ (_ ++ _)).\n      rewrite app_assoc_reverse.\n      simplify.\n      equality.\n    - specialize IHl1 with (l2 := nil) (a1 := a1) (a2 := a2).\n      rewrite IHl1.\n      simplify.\n      equality.\n    - specialize IHl1 with (l2 := a0 :: l2).\n      rewrite IHl1.\n      simplify.\n      rewrite app_assoc_reverse.\n      simplify.\n      equality.\nQed.\n\nSearch (nat -> list _ ->  _).\nSearch (list _ ->  nat -> _).\nTheorem my_reverse_really_correct: forall (A: Type) (l: list A),\n    length l = length (my_reverse l) /\\\n    forall (i: nat), i < length l -> nth_error l i = nth_error (my_reverse l) (length l - i - 1).\nProof.\n  pose my_reverse_correct1.\n  simplify.\n  propositional.\n  - apply e.\n  - induct l.\n    + simplify. linear_arithmetic.\n    + cases i.\n      -- simplify.\n         rewrite nth_error_app2.\n         ++ rewrite e with A l.\n            assert (length (my_reverse l) - 0 - length (my_reverse l) = 0) by linear_arithmetic.\n            rewrite H0.\n            simplify.\n            equality.\n         ++ specialize e with A l.\n            linear_arithmetic.\n      -- simplify.\n         rewrite nth_error_app1.\n         ++ apply IHl. linear_arithmetic.\n         ++ specialize e with A l.\n            linear_arithmetic.\nQed.\n", "meta": {"author": "KinanBab", "repo": "CS591K1-Labs", "sha": "d4569bf99d20c22cd56721024688cda247d1447f", "save_path": "github-repos/coq/KinanBab-CS591K1-Labs", "path": "github-repos/coq/KinanBab-CS591K1-Labs/CS591K1-Labs-d4569bf99d20c22cd56721024688cda247d1447f/lab3/code/reverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7117781106890629}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool.\nFrom mathcomp.ssreflect\nRequire Import ssrnat.\nFrom mathcomp.ssreflect\nRequire Import seq.\n\n\n(* Recap: we can define simple inductive types as seen before \nInductive unit : Set := it. \n*)\n\n(* seemingly, types of symbols are inferred to be elements\n* i.e it : unit\n*)\n\n(* Inductive types can be empty *)\nInductive empty: Set := .\n\n(* Recap: Types can hold multiple values\n    Inductive bool : Set := true : bool | false : bool.\n*)\n\n\n(* Recap: quick example of a simple \n*  non-recursive function \n    Definition negate b :=\n        match b with\n        | true => false\n        | false => true\n        end.\n*)\n\n(* A simple custom add operation:\n*    add n m:\n*       if n == 0:\n*           return m\n*       else:\n*           return (add (n-1) m) + 1\n*)\nFixpoint custom_plus n m :=\n    match n with\n    | 0 => m\n(* New: we haven't used temporary variables before - looks like they act like haskell. *)\n    | n'.+1 => let tmp := custom_plus n' m in tmp.+1\n    end.\n\n(* \n* ssreflect provides a couple of utility constructs that can make proofs faster.\n* specifically, the if-is notation\n* which is exactly rust's if-let construct.\n*)\nFixpoint custom_plus' (n m: nat) :=\n    if n is n'.+1 then (custom_plus' n' m).+1\n                  else m.\n\n(* COOL stuff: now we're cooking with functionals!\n* we're going to use the recursion principle \n* to implement custom_plus \n*)\nDefinition custom_plus'' (n m: nat) :=\n    nat_rec (fun _ => nat) m (fun n' m' => m'.+1) n.\n(*\n* All values of P n are natural numbers\n* f (base of the recursion is m)\n* f0 n' m' returns m'.+1\n* and then is applied to n.\n*\n* so once executed, it becomes\n* f0 (m-1) (f0 (m-2) (f0 (m-3) .... (f0 1 0) ..)\n* which evaluates to \n*  0.+1.+1.+1 ... .+1 = result\n*)\n\nExample plus_works: custom_plus'' 2 3 = 5.\nsimpl.\nreflexivity.\nQed.\n\n(* Note how Coq's compile time restrictions allows for dependantly typed functions\n* to illustrate the point, we'll implement a complex one\n*)\nDefinition sum_no_zero n :=\n    (* P is a function that return the unit type if input is 0 else the natural type *)\n    let: P := (fun n => if n is 0 then unit else nat) in\n    (* our type generator function is P, our initial element is the only element in unit\n    * tt, our combiner function *)\n    nat_rec P tt (fun n' m =>\n        match n' return P n' -> _ with (* Note: the return construct is a type annotation *)\n        | 0 => fun _ => 1  (* maps from unit to nat - is the first function in the\n                sequence  *)\n        | n''.+1 => fun m => custom_plus'' m (n'.+1) (* maps from nat to nat *)\n        end m) n.\n\n(* Having looked at the definition of empty_rect, we can see that it's type signiture:\n* (P: empty -> Type) -> (e: empty) -> P e\n* i.e given a mapping from empty to a type, and given an element of empty, we can construct\n* a member of any type\n* \n* This is a vacuous truth - much like false -> anything, we can never get an element of empty\n* so this would never apply.\n*)\n\n(*\n* However, a type with no elements is not the only way we can construct an \n* un-instantiateable type.\n*\n* for example:\n*)\n\nInductive strange : Set := cs : strange -> strange.\n\n(*\n* The definition of strange_rect is as follows:\n*strange_rect\n*    : forall P : strange -> Type,\n*      (forall s : strange, P s -> P (cs s)) -> forall s : strange, P s\n* i.e,  given a mapping from strange to type = P,\n*       and a mapping from P s to P (cs s)\n*       we can get P s\n*)\n\n\n(*\n* Now consider the definition of prod - coq's equivalent of a pair type.\n*\n* Inductive prod (A B : Type) : Type := A -> B -> A * B\n*\n*  This becomes clearer when you look at how  a pair is constructed.\n* \n*  Check pair 1 tt.\n*  \n* (1, tt)\n*      : nat * unit\n*\n*  which can be corroborated by considering the type of the type prod\n*  \n* Check prod. \n*\n* prod\n*     : Type -> Type -> Type\n*\n* I.e, like in Haskell, the prod takes in two arguments and produces a type.\n*\n* We can manually specify the type (rather than allowing it to be inferred) using @:\n*\n* Check @pair nat unit 1 tt.\n*\n*)\n\n\n(*\n*\n* Now, finally, to include some bread-and-butter functional programming utilities,\n*  let's consider the union and list types - sum and seq.\n* Sum : (A B : Type) : Type = inl : A -> A + B \n*                           | inr : B -> A + B.\n*\n* seq : (A : Type) : Type := nil : seq A\n*                           | cons: A -> seq A -> seq A\n* \n* We can also do nifty typedefs as follows:\n*)\nNotation seq := list.\n\n\n(* \n*\n* Let's try using this stuff out by implementing an alternate function, which alternates the elements of two lists.\n*\n*)\n\n(* This is how we'd implement it in Haskell,\n*  However, this is not permitted by the coq language\n*  as it has no clear recursive variant - no parameter is always decreasing \nFixpoint alternate (a : seq nat) (b : seq nat) : seq nat :=\n    match a return seq nat with\n    | nil => b\n    | cons head' tail' => cons head' (alternate b tail)\n    end.\n*  we can implement it as follows:\n*)\n\nFixpoint alternate (a b : seq nat) : seq nat :=\n        match a return seq nat with\n                | nil => b\n                | cons head_a tail_a => match b with\n                                    | nil => cons head_a tail_a\n                                    | cons head_b tail_b => cons head_a (cons head_b\n                                            (alternate\n                                            tail_a tail_b))\n                                    end\n                end.\n\n\n(*\n*\n* Now we will consider how we can use ssreflect to speed up our proofs\n*  here we'll consider a shorter way to define pairs\n*)\n\nInductive custom_prod (A B : Type) : Type := custom_pair of A & B.\n\n(*\n* Here, we will use of & structure to allow A and B to be the parameters of the type as well a the constructor.\n*\n* However with this format, we need to provide the types explicitly.\n* We can work around this using the Implicit arguments of coq.\n*)\n\nImplicit Arguments custom_pair [A B].\n\n\n(* \n*\n* Alongside implicit arguments, coq provides additional utilities is the form of\n* custom notation to represent our own types for ease of reading.\n*)\n\nNotation \"X ** Y\" := (custom_prod X Y) (at level 2).\nNotation \"( X ,, Y )\" := (custom_pair X Y).\n\n(*\n*\n* You can see this notation in action by running Check (1 ,, 3).\n*)\n\n", "meta": {"author": "Gopiandcode", "repo": "coq-projects", "sha": "5408268dd954080a7a1956382238625bfd5d95b2", "save_path": "github-repos/coq/Gopiandcode-coq-projects", "path": "github-repos/coq/Gopiandcode-coq-projects/coq-projects-5408268dd954080a7a1956382238625bfd5d95b2/pnp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650403, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.711743244021256}}
{"text": "Require Export P02.\n\nTheorem S_injective : forall (n m : nat),\n  S n = S m ->\n  n = m.\nProof.\n  intros n m H. inversion H. reflexivity.\nQed.\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  - rewrite <- plus_n_Sm. 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\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  - intros m H. simpl in H. destruct m.\n    + reflexivity.\n    + inversion H.\n  - intros m H. simpl in H. destruct m.\n    + inversion H.\n    + symmetry in H. rewrite <- plus_n_Sm in H. apply S_injective in H.\n      rewrite <- plus_n_Sm in H. rewrite -> plus_comm in H. rewrite <- plus_n_Sm in H.\n      apply S_injective in H. symmetry in H. apply IHn' in H. rewrite H. reflexivity.\nQed.\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/04/P07.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7117336908550027}}
{"text": "Require Import Omega List.\nRequire Import List.\nPrint list.\nPrint nil.\nRequire Setoid.\nRequire Import PeanoNat Le Gt Minus Bool Lt.\nOpen Scope list_scope.\n\nDefinition szam(k:option(nat)):nat:=\n  match k with\n  | None => 0\n  | Some k => k\n  end.\n\n\n\nFixpoint listaszum(k:list(option(nat))):nat:=\n  match k with\n  | nil => 0\n  | cons x l' => szam x+ listaszum l'\n  end.\n\n\nEval compute in listaszum (Some(2)::None::Some(4)::nil).\n\nRequire Import NAxioms NProperties OrdersFacts.\n\nPrint min_l.\n\nEval compute in Init.Nat.min 5 6.\n\nFixpoint listakicsi(k:list(option(nat))):nat:=\n  match k with\n  | nil => 0\n  | cons x l' => Init.Nat.min (szam x) (listakicsi l')\n  end.\n\nEval compute in listakicsi (Some(2)::None::Some(4)::nil).\n\nPrint Init.Nat.\n\nEval compute in (Init.Nat.eqb(Init.Nat.min 5 6)  (5)).\n\n\nDefinition MinPairTwo(x y : option (nat*nat)) : nat :=\n  match x, y with\n    | None, None => 0\n    | None, Some (b,m) => b\n    | Some (a,n), None => a\n    | Some (a, n), Some (b, m) =>  match (Init.Nat.eqb(Init.Nat.min n m)(n)) with\n          |true => a\n          |_ => b\n          end\n  end.\n\nDefinition MinPairTwoVege(x y : option (nat*nat)) : option(nat*nat) :=\n  match x, y with\n    | None, None => None\n    | None, Some (b,m) => Some(b,m)\n    | Some (a,n), None => Some(a,n)\n    | Some (a, n), Some (b, m) =>  match (Init.Nat.eqb(Init.Nat.min n m)(n)) with\n          |true => Some(a,n)\n          |_ => Some(b,m)\n          end\n  end.\n\nDefinition elsokinyer (x:option(nat*nat)):option(nat):=\n  match x with\n  |None => None\n  |Some(a,b)=>Some(a)\n  end.\n\nEval compute in MinPairTwoVege (Some(2,3)) (Some (1,4)).\n\n\nFixpoint listaminpar(k:list(option(nat*nat))):option(nat*nat):=\n  match k with\n  | nil => None\n  | cons x l' => MinPairTwoVege(x) (listaminpar l')\n  end.\n\nDefinition legkisebbpar (k:list(option(nat*nat))):option(nat):=\n  elsokinyer (listaminpar k).\n\nEval compute in legkisebbpar (Some(2,3)::None::Some(4,1)::Some(88,0)::nil).\n\n", "meta": {"author": "mozow01", "repo": "bizcoq2021", "sha": "f98f22ba3ce80899bc88605ce3193d8972102c92", "save_path": "github-repos/coq/mozow01-bizcoq2021", "path": "github-repos/coq/mozow01-bizcoq2021/bizcoq2021-f98f22ba3ce80899bc88605ce3193d8972102c92/hallgatoi/molnarbarna/ZH_5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7117336888037454}}
{"text": "Require Import ZArith.\nRequire Import NPeano.\n\nLoad \"Bijection\".\n\nDefinition nat_lt N := e_lift {n : nat | n < N}.\n\nDefinition finite (A : eqset) : Type :=\n  { n : nat | eq_cardinal A (nat_lt n) }.\n\nLemma finite_nat_lt : forall N, finite (nat_lt N).\nProof.\n  intro N.\n  unfold finite.\n  exists N.\n  apply eq_cardinal_reflexive.\nQed.\n\nDefinition finite_cardinal A (A_finite : finite A) : nat.\n  elim A_finite.\n  intro n.\n  intros.\n  apply n.\nDefined.\n\nLemma _nat_lt_ge_dec : forall n m : nat, {n < m} + {n >= m}.\nProof.\n  intros n m.\n  assert ({n < m} + {n = m} + {n > m}) as nm_opts.\n  apply lt_eq_lt_dec.\n  destruct nm_opts as [[n_lt_m | n_eq_m] | n_gt_m].\n  left; assumption.\n  right; apply Nat.eq_le_incl; symmetry; assumption.\n  right; apply lt_le_weak; assumption.\nQed.\n\nLemma eq_in_lift : forall A (x y : e_set (e_lift A)), x == y -> x = y. \nProof.\n  intros A x y H.\n  compute in H.\n  assumption.\nQed.\n\n(*\n * 0 1 2 ... x-1 x x+1     N-1\n *\n * 0 1 2 ... x-1 x x+1 ... N-1 N\n * 0 1 2 ... x-1   x+1 ... N-1 N\n *)\nDefinition bijection_n_Sn_removal_function N (x : e_set (nat_lt (S N))) :\n               e_set (nat_lt N) -> e_set (eqset_remove (nat_lt (S N)) x).\n  intro y.\n  assert ({proj1_sig y < proj1_sig x} + {proj1_sig y >= proj1_sig x})\n      as xy_opts.\n    apply _nat_lt_ge_dec.\n  destruct xy_opts as [y_lt_x | y_ge_x].\n  (* y < x *)\n  assert (proj1_sig y < S N) as hyp_LT.\n    apply lt_trans with (proj1_sig x).\n    assumption.\n    apply (proj2_sig x).\n  exists (exist (fun z => z < S N) (proj1_sig y) hyp_LT).\n  simpl.\n  compute.\n  intro x_eq_fy.\n  assert (proj1_sig x = proj1_sig (exist (fun z : nat => z < S N) (proj1_sig y) hyp_LT))\n      as H. apply f_equal. assumption.\n  simpl in H.\n  assert (proj1_sig x <> proj1_sig y).\n    apply not_eq_sym.\n    apply Nat.lt_neq.\n    assumption.\n  contradiction.\n  (* y >= x *)\n  assert (proj1_sig y + 1 < S N) as hyp_LT.\n    rewrite plus_comm.\n    simpl.\n    apply lt_n_S.\n    apply (proj2_sig y).\n  exists (exist (fun z => z < S N) (proj1_sig y + 1) hyp_LT).\n  simpl.\n  compute.\n  intro x_eq_fy.\n  assert (proj1_sig x = proj1_sig (exist (fun z : nat => z < S N) (proj1_sig y + 1) hyp_LT))\n      as H. apply f_equal. assumption.\n  simpl in H.\n  assert (proj1_sig x <> proj1_sig y + 1).\n    apply le_gt_S in y_ge_x.\n    rewrite plus_comm.\n    simpl.\n    apply Nat.lt_neq.\n    assumption.\n  contradiction.\nDefined.\n\nDefinition bijection_n_Sn_removal_functional N (x : e_set (nat_lt (S N))) :\n               e_set (nat_lt N ==> eqset_remove (nat_lt (S N)) x).\n  simpl.\n  unfold e_function_set.\n  exists (bijection_n_Sn_removal_function N x).\n  intros y1 y2 y1_eq_y2.\n  compute in y1_eq_y2.\n  replace y2 with y1.\n  apply e_reflexive.\nDefined.\n\nLemma bijection_n_Sn_removal :\n  forall N (x : e_set (nat_lt (S N))),\n    eq_cardinal (nat_lt N) (eqset_remove (nat_lt (S N)) x).\nProof.                                       \n  intros N x.\n  unfold eq_cardinal.\n  exists (bijection_n_Sn_removal_functional N x).\n  apply inhabits.\n  unfold bijection.\n  intro fy.\n  assert ({proj1_sig (proj1_sig fy) < proj1_sig x} +\n          {proj1_sig (proj1_sig fy) = proj1_sig x} +\n          {proj1_sig (proj1_sig fy) > proj1_sig x})\n      as fy_opts.\n    apply lt_eq_lt_dec.\n  case fy_opts as [[fy_lt_x | fy_eq_x ] | fy_gt_x].\n    (* fy < x *)\n    admit.\n    (* fy = x *)\n    assert (~(x == proj1_sig fy)) as H.\n      apply (proj2_sig fy).\n      (** TODO **)\n    (* fy > x *)\n    admit.\nQed.\n\n  \n\nLemma eq_cardinal_imp_eq_nat :\n        forall N M, eq_cardinal (nat_lt N) (nat_lt M) -> N = M.\nProof.\n  intro N.\n  induction N.\n  \n  (* 0 *)\n  intros M eq_card_N_M.\n  unfold eq_cardinal in eq_card_N_M.\n  elim eq_card_N_M.\n  intros f inh_f_bij; case inh_f_bij; intro f_bij.\n  assert ({0 = M} + {0 <> M}) as M_cases.\n    apply eq_nat_dec.\n  case M_cases.\n  tauto.\n  intro neq_0_M.\n  assert (M > 0) as gt_0_M.\n  apply neq_0_lt.\n  assumption.\n  unfold bijection in f_bij.\n  elim f_bij with (exist (fun n => n < M) 0 gt_0_M).\n  intro impossible_element.\n  simpl in impossible_element.\n  assert (proj1_sig impossible_element < 0).\n  apply (proj2_sig impossible_element).\n  assert (~proj1_sig impossible_element < 0).\n  apply lt_n_0.\n  contradiction.\n  \n  (* S N *)\n  intros M eq_card_N_M.\n  unfold eq_cardinal in eq_card_N_M.\n  elim eq_card_N_M.\n  intros f inh_f_bij; case inh_f_bij; intro f_bij.\n\n  \nQed.\n\nLemma finite_cardinal_well_defined :\n  forall A (A_fin1 A_fin2 : finite A),\n    finite_cardinal A A_fin1 = finite_cardinal A A_fin2.\nProof.\n  intros A A_fin1 A_fin2.\n  unfold finite in A_fin1.\n  elim A_fin1; intros n bijection_A_n.\n  elim A_fin2; intros m bijection_A_m.\n  induction n.\n    (* 0 *)\n    simpl.\n    \n\n     \n    (* S n *)\n\n\n(*** TODO :\n\n     Demostrar que si tengo dos demostraciones de que un conjunto\n     es finito, la primera componente (su cardinal), siempre coincide.\n     Por induccion.\n\n ***)\n\n(**** Groups ****)\n\nStructure group :=\n  mk_group {\n      g_eqset : eqset ;\n      g_unit : e_set g_eqset ;\n      g_op : e_set g_eqset -> e_set g_eqset -> e_set g_eqset ;\n      g_inv : e_set g_eqset -> e_set g_eqset ;\n      g_unit_l : forall x, g_op g_unit x == x ;\n      g_unit_r : forall x, g_op x g_unit == x ;\n      g_assoc : forall x y z, g_op x (g_op y z) == g_op (g_op x y) z ;\n      g_inv_r : forall x, g_op x (g_inv x) == g_unit\n  }.\n\nNotation \"[ G ]\" := (e_set (g_eqset G)).\nNotation \"a ** b\" := (g_op _ a b) (at level 35).\nNotation \"a !\" := (g_inv _ a) (at level 25).\n\nDefinition g_finite (G : group) := finite (e_set (g_eqset G)).\n\nDefinition g_order G (G_finite : g_finite G) : nat.\n  unfold g_finite in G_finite.\n  unfold finite in G_finite.\n  elim G_finite.\n  intros n _.\n  apply n.\nDefined.\n\n\nDefinition subgroup (H G : group) : Prop :=\n  e_subset (g_eqset H) (g_eqset G).\n\n(****)\n\nInductive Z2_set := Z2_0 | Z2_1.\n\nDefinition Z2_op (a b : Z2_set) :=\n  match a with\n  | Z2_0 => b\n  | Z2_1 => (match b with\n             | Z2_0 => Z2_1\n             | Z2_1 => Z2_0\n             end)\n  end.\n\nDefinition Z2_inv (a : Z2_set) := a.\n\nLemma Z2_unit_l : forall x, Z2_op Z2_0 x = x.\nProof.\n  intro x.\n  case x.\n  compute; reflexivity.\n  compute; reflexivity.\nQed.\n\nLemma Z2_unit_r : forall x, Z2_op x Z2_0 = x.\nProof.\n  intro x.\n  case x.\n  compute; reflexivity.\n  compute; reflexivity.\nQed.\n\nLemma Z2_assoc : forall x y z, Z2_op x (Z2_op y z) = Z2_op (Z2_op x y) z.\nProof.\n  intros x y z.\n  case x.\n  case y.\n  compute; reflexivity.\n  compute; reflexivity.\n  case y.\n  compute; reflexivity.\n  case z.\n  compute; reflexivity.\n  compute; reflexivity.\nQed.\n\nLemma Z2_inv_r : forall x, Z2_op x (Z2_inv x) = Z2_0.\nProof.\n  intro x.  \n  case x.\n  compute; reflexivity.\n  compute; reflexivity.\nQed.\n\nDefinition Z2 : group := mk_group \n      Z2_set\n      Z2_0\n      Z2_op\n      Z2_inv\n      Z2_unit_l\n      Z2_unit_r\n      Z2_assoc\n      Z2_inv_r.\n\nLemma nat_lt_2_cases : forall x : nat_lt 2, {proj1_sig x = 0} + {proj1_sig x = 1}.\nProof.\n  intro x.\n  assert (proj1_sig x <= 1) as x_shape.\n    unfold nat_lt in x.\n    elim x.\n    intros x_value x_prop.\n    simpl.\n    apply lt_n_Sm_le.\n    assumption.\n  SearchAbout lt.\n  rewrite <- NPeano.Nat.lt_1_r.\n  replace (proj1_sig x = 0) with (proj1_sig x < 1).\n  apply le_lt_eq_dec.\n  assumption.\nQed.\n\nDefinition Z2_enum (x : nat_lt 2) : Z2_set.\n  assert (proj1_sig x = 0 \\/ proj1_sig x = 1) as x_cases.\n  apply nat_lt_2_cases.\n  case x_cases.\n\n\nLemma Z2_set_finite : finite Z2_set.\nProof.\n  unfold finite.\n  exists 2.\n  exists (fun x => nat_lt_2 x).\n", "meta": {"author": "foones", "repo": "dharma", "sha": "bea2a54256082c9349e267caae318d20e79cf8b6", "save_path": "github-repos/coq/foones-dharma", "path": "github-repos/coq/foones-dharma/dharma-bea2a54256082c9349e267caae318d20e79cf8b6/coq/math1/fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7117336841076148}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (x : natural) : natural := mult z (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj236_coqofml_jBVRuP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7879311881731379, "lm_q1q2_score": 0.7117336837118704}}
{"text": "Inductive bin: Type := | O : bin | B: bin -> bin | S: bin -> bin.\n\nFixpoint incr (b : bin) : bin :=\nmatch b with\n|O => S O\n|B n' => S n'\n|S n' => B (incr n')\nend.\n\nExample test_incr_1:\nincr(O) = S O. \n\nProof. simpl. reflexivity. Qed.\n\nExample test_incr_2:\nincr(S O) = B (S O).\n\nProof. simpl. reflexivity. Qed.", "meta": {"author": "Asap7772", "repo": "coq_softwarefoundations", "sha": "a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d", "save_path": "github-repos/coq/Asap7772-coq_softwarefoundations", "path": "github-repos/coq/Asap7772-coq_softwarefoundations/coq_softwarefoundations-a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d/chapter1/bin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7117336779538431}}
{"text": "Require Import Coq.Arith.EqNat Coq.Arith.Compare_dec.\nRequire Import Coq.Lists.List.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.\nSet Implicit Arguments.\n\nLocal Arguments leb !_ !_.\n\nSection fixedpoints.\n  Context {A : Type}\n          (sizeof : A -> nat)\n          (step : A -> A)\n          (step_monotonic : forall a, sizeof (step a) <= sizeof a)\n          (step_eq : forall a, sizeof (step a) = sizeof a -> step a = a)\n          (upperbound : A).\n\n  Definition greatest_fixpoint_step\n             (greatest_fixpoint : nat -> A -> A)\n             (sz : nat)\n             (a : A)\n    : A\n    := match sz with\n       | 0 => a\n       | S sz'\n         => let a' := step a in\n            let sza := sizeof a in\n            let sza' := sizeof a' in\n            if leb (S sza') sza\n            then greatest_fixpoint sz' a'\n            else a\n       end.\n\n  Fixpoint greatest_fixpoint' (sz : nat)\n    : A -> A\n    := greatest_fixpoint_step greatest_fixpoint' sz.\n\n  Definition greatest_fixpoint (a : A) := greatest_fixpoint' (sizeof a) a.\n\n  Lemma greatest_fixpoint_fixpoint a : step (greatest_fixpoint a) = greatest_fixpoint a.\n  Proof.\n    unfold greatest_fixpoint.\n    set (sz := sizeof a).\n    assert (H : sizeof a <= sz) by reflexivity.\n    clearbody sz.\n    revert dependent a.\n    induction sz as [|sz IHsz].\n    { simpl.\n      intros a Hle.\n      assert (sizeof (step a) <= 0) by (etransitivity; [ apply step_monotonic | apply Hle ]).\n      apply step_eq; omega. }\n    { simpl.\n      intros.\n      repeat match goal with\n             | [ |- context[if ?e then _ else _] ] => destruct e eqn:?\n             | [ H : leb _ _ = true |- _ ]\n               => apply leb_iff in H\n             | [ H : leb _ _ = false |- _ ]\n               => apply leb_iff_conv in H\n             | _ => solve [ eauto with nocore ]\n             | [ |- step _ = _ ] => apply step_eq\n             | _ => omega\n             | [ H : forall a, _ -> _ = _ |- _ ] => rewrite H by omega\n             | [ H : _ < _ |- _ ] => hnf in H\n             | [ H : S _ <= S _ |- _ ] => apply Le.le_S_n in H\n             | [ H : sizeof ?x <= ?y, H' : ?y <= sizeof (step ?x) |- _ ]\n               => let H'' := fresh in\n                  assert (H'' : sizeof (step x) <= sizeof x) by apply step_monotonic;\n                    assert (sizeof x = y) by omega;\n                    assert (y = sizeof (step x)) by omega;\n                    clear H H' H''\n             | [ H : sizeof ?x <= sizeof (step ?x) |- _ ]\n               => let H'' := fresh in\n                  assert (H'' : sizeof (step x) <= sizeof x) by apply step_monotonic;\n                    assert (sizeof x = sizeof (step x)) by omega;\n                    clear H H''\n             end. }\n  Qed.\nEnd fixedpoints.\n\nSection listpair.\n  Context {A B : Type}\n          (fA : list A -> list B -> A -> bool)\n          (fB : list A -> list B -> B -> bool)\n          (upperA : list A)\n          (upperB : list B).\n\n  Definition sizeof_pair (lss : list A * list B) : nat\n    := length (fst lss) + length (snd lss).\n\n  Let step (lss : list A * list B) : list A * list B\n    := (filter (fA (fst lss) (snd lss)) (fst lss),\n        filter (fB (fst lss) (snd lss)) (snd lss)).\n\n  Lemma step_monotonic lss : sizeof_pair (step lss) <= sizeof_pair lss.\n  Proof.\n    unfold step, sizeof_pair; simpl;\n      apply Plus.plus_le_compat;\n      apply length_filter.\n  Qed.\n\n  Lemma step_eq lss\n    : sizeof_pair (step lss) = sizeof_pair lss -> step lss = lss.\n  Proof.\n    unfold sizeof_pair, step; simpl.\n    destruct lss as [lsA lsB]; simpl.\n    intro H.\n    repeat match goal with\n           | [ H : context[filter ?f ?ls] |- _ ]\n             => unique pose proof (length_filter f ls)\n           end.\n    match goal with\n    | [ H : ?x + ?y = ?x' + ?y' |- _ = _ :> list _ * list _ ]\n      => assert (x = x') by omega;\n           assert (y = y') by omega;\n           clear H\n    end.\n    rewrite !length_filter_eq by omega.\n    reflexivity.\n  Qed.\n\n  Definition greatest_fixpoint_of_lists : list A * list B\n    := greatest_fixpoint sizeof_pair step (upperA, upperB).\n\n  Definition greatest_fixpoint_of_lists_fixpoint\n    : step greatest_fixpoint_of_lists = greatest_fixpoint_of_lists.\n  Proof.\n    apply greatest_fixpoint_fixpoint.\n    { intros; apply step_monotonic. }\n    { intros; apply step_eq; assumption. }\n  Qed.\n\n  Lemma greatest_fixpoint_of_lists_correct_1\n        (lsA := fst greatest_fixpoint_of_lists)\n        (lsB := snd greatest_fixpoint_of_lists)\n    : fold_right andb true (map (fA lsA lsB) lsA) = true.\n  Proof.\n    unfold lsA at 2.\n    rewrite <- greatest_fixpoint_of_lists_fixpoint.\n    unfold step; simpl.\n    apply fold_right_andb_true_map_filter.\n  Qed.\n\n  Lemma greatest_fixpoint_of_lists_correct_2\n        (lsA := fst greatest_fixpoint_of_lists)\n        (lsB := snd greatest_fixpoint_of_lists)\n    : fold_right andb true (map (fB lsA lsB) lsB) = true.\n  Proof.\n    unfold lsB at 2.\n    rewrite <- greatest_fixpoint_of_lists_fixpoint.\n    unfold step; simpl.\n    apply fold_right_andb_true_map_filter.\n  Qed.\nEnd listpair.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_simpl_example/src/Common/FixedPoints.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7117336691551979}}
{"text": "Require Import Quote.\n\nParameters A B C : Prop.\n\nInductive Formula : Type :=\n| fAnd : Formula -> Formula -> Formula\n| fOr  : Formula -> Formula -> Formula\n| fNot : Formula -> Formula\n| fTrue: Formula\n| fCon : Prop -> Formula    (* Constructor for constants *)\n.\n\n\nFixpoint eval (p:Formula) : Prop :=\n    match p with\n    | fAnd p1 p2    => eval p1 /\\ eval p2\n    | fOr  p1 p2    => eval p1 \\/ eval p2\n    | fNot p1       => ~ eval p1\n    | fTrue         => True\n    | fCon c        => c\n    end.\n\n\nLemma L1 : A /\\ (A /\\ True) /\\ ~B /\\ (A <-> A).\nProof.\n    quote eval.\n\nShow.\n\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/ref/quote.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7116937242979928}}
{"text": "Require Import\n  HoTT.Classes.interfaces.abstract_algebra\n  HoTT.Classes.interfaces.orders\n  HoTT.Classes.theory.apartness.\n\nGeneralizable Variables A.\n\nLemma irrefl_neq `{R : Relation A} `{!Irreflexive R}\n  : forall x y, R x y -> x <> y.\nProof.\nintros ?? E e;rewrite e in E. apply (irreflexivity _ _ E).\nQed.\n\nLemma le_flip `{Le A} `{!TotalRelation (≤)} x y : ~(y ≤ x) -> x ≤ y.\nProof.\nintros nle.\ndestruct (total _ x y) as [?|le];auto.\ndestruct (nle le).\nQed.\n\nSection partial_order.\n  Context `{PartialOrder A}.\n\n  Lemma eq_le x y : x = y -> x ≤ y.\n  Proof.\n  intros E.\n  rewrite E.\n  apply reflexivity.\n  Qed.\n\n  Lemma eq_le_flip x y : x = y -> y ≤ x.\n  Proof.\n  intros E.\n  rewrite E.\n  apply reflexivity.\n  Qed.\n\n  Lemma not_le_ne x y : ~(x ≤ y) -> x <> y.\n  Proof.\n  intros E1 E2.\n  apply E1.\n  rewrite E2.\n  apply reflexivity.\n  Qed.\n\n  Lemma eq_iff_le x y : x = y <-> x ≤ y /\\ y ≤ x.\n  Proof.\n  split; intros E.\n  - rewrite E. split;apply reflexivity.\n  - apply (antisymmetry (≤) x y);apply E.\n  Qed.\nEnd partial_order.\n\nSection strict_order.\n  Context `{StrictOrder A}.\n\n  Lemma lt_flip x y : x < y -> ~(y < x).\n  Proof.\n  intros E1 E2.\n  apply (irreflexivity (<) x).\n  transitivity y;assumption.\n  Qed.\n\n  Lemma lt_antisym x y : ~(x < y < x).\n  Proof.\n  intros [E1 E2].\n  destruct (lt_flip x y);assumption.\n  Qed.\n\n  Lemma lt_ne x y : x < y -> x <> y.\n  Proof.\n  intros E1 E2.\n  rewrite E2 in E1.\n  apply (irreflexivity (<) y). assumption.\n  Qed.\n\n  Lemma lt_ne_flip x y : x < y -> y <> x.\n  Proof.\n  intro.\n  apply symmetric_neq, lt_ne.\n  assumption.\n  Qed.\n\n  Lemma eq_not_lt x y : x = y -> ~(x < y).\n  Proof.\n  intros E.\n  rewrite E.\n  apply (irreflexivity (<)).\n  Qed.\nEnd strict_order.\n\nSection pseudo_order.\n  Context `{PseudoOrder A}.\n\n  Local Existing Instance pseudo_order_apart.\n\n  Lemma apart_total_lt x y : x ≶ y -> x < y |_| y < x.\n  Proof.\n  intros.\n  apply apart_iff_total_lt.\n  assumption.\n  Qed.\n\n  Lemma pseudo_order_lt_apart x y : x < y -> x ≶ y.\n  Proof.\n  intros.\n  apply apart_iff_total_lt.\n  auto.\n  Qed.\n\n  Lemma pseudo_order_lt_apart_flip x y : x < y -> y ≶ x.\n  Proof.\n  intros.\n  apply apart_iff_total_lt.\n  auto.\n  Qed.\n\n  Lemma not_lt_apart_lt_flip x y : ~(x < y) -> x ≶ y -> y < x.\n  Proof.\n  intros nlt neq. apply apart_iff_total_lt in neq.\n  destruct neq.\n  - destruct nlt;auto.\n  - auto.\n  Qed.\n\n  Lemma pseudo_order_cotrans_twice x₁ y₁ x₂ y₂\n    : x₁ < y₁ -> merely (x₂ < y₂ |_| x₁ < x₂ |_| y₂ < y₁).\n  Proof.\n  intros E1.\n  apply (merely_destruct (cotransitive E1 x₂));intros [?|E2];\n  try solve [apply tr;auto].\n  apply (merely_destruct (cotransitive E2 y₂));intros [?|?];apply tr;auto.\n  Qed.\n\n  Lemma pseudo_order_lt_ext x₁ y₁ x₂ y₂ : x₁ < y₁ ->\n    merely (x₂ < y₂ |_| x₁ ≶ x₂ |_| y₂ ≶ y₁).\n  Proof.\n  intros E.\n  apply (merely_destruct (pseudo_order_cotrans_twice x₁ y₁ x₂ y₂ E));\n  intros [?|[?|?]];apply tr;\n  auto using pseudo_order_lt_apart.\n  Qed.\n\n  Global Instance pseudoorder_strictorder : StrictOrder (_ : Lt A).\n  Proof.\n  split.\n  - apply _.\n  - intros x E.\n    destruct (pseudo_order_antisym x x); auto.\n  - intros x y z E1 E2.\n    apply (merely_destruct (cotransitive E1 z));intros [?|?]; trivial.\n    destruct (pseudo_order_antisym y z); auto.\n  Qed.\n\n  Global Instance nlt_trans : Transitive (complement (<)).\n  Proof.\n  intros x y z.\n  intros E1 E2 E3.\n  apply (merely_destruct (cotransitive E3 y));\n  intros [?|?]; contradiction.\n  Qed.\n\n  Global Instance nlt_antisymm : AntiSymmetric (complement (<)).\n  Proof.\n  intros x y H1 H2.\n  apply tight_apart. intros nap. apply apart_iff_total_lt in nap.\n  destruct nap;auto.\n  Qed.\n\n  Lemma ne_total_lt `{!TrivialApart A} x y : x <> y -> x < y |_| y < x.\n  Proof.\n  intros neq;apply trivial_apart in neq.\n  apply apart_total_lt. assumption.\n  Qed.\n\n  Global Instance lt_trichotomy `{!TrivialApart A} `{DecidablePaths A}\n    : Trichotomy (<).\n  Proof.\n  intros x y.\n  destruct (dec (x = y)) as [?|?]; try auto.\n  destruct (ne_total_lt x y); auto.\n  Qed.\nEnd pseudo_order.\n\nSection full_partial_order.\n  Context `{FullPartialOrder A}.\n\n  Local Existing Instance strict_po_apart.\n\n  (* Duplicate of strong_setoids.apart_ne. This is useful because a\n    StrongSetoid is not defined as a substructure of a FullPartialOrder *)\n  Instance strict_po_apart_ne x y : PropHolds (x ≶ y) -> PropHolds (x <> y).\n  Proof.\n  intros; apply _.\n  Qed.\n\n  Global Instance fullpartialorder_strictorder : StrictOrder (<).\n  Proof.\n  split; try apply _.\n  - apply strict_po_mere_lt.\n  - intros x. red. intros E;apply lt_iff_le_apart in E.\n    destruct E as [_ ?].\n    apply (irreflexivity (≶) x).\n    assumption.\n  Qed.\n\n  Lemma lt_le x y : PropHolds (x < y) -> PropHolds (x ≤ y).\n  Proof.\n  intro.\n  apply lt_iff_le_apart.\n  assumption.\n  Qed.\n\n  Lemma not_le_not_lt x y : ~(x ≤ y) -> ~(x < y).\n  Proof.\n  intros E1 E2.\n  apply E1. apply lt_le. assumption.\n  Qed.\n\n  Lemma lt_apart x y : x < y -> x ≶ y.\n  Proof.\n  intro.\n  apply lt_iff_le_apart.\n  assumption.\n  Qed.\n\n  Lemma lt_apart_flip x y : x < y -> y ≶ x.\n  Proof.\n  intro.\n  apply symmetry, lt_iff_le_apart.\n  assumption.\n  Qed.\n\n  Lemma le_not_lt_flip x y : y ≤ x -> ~(x < y).\n  Proof.\n  intros E1 E2;apply lt_iff_le_apart in E2.\n  destruct E2 as [E2a E2b].\n  revert E2b. apply tight_apart.\n  apply (antisymmetry (≤));assumption.\n  Qed.\n\n  Lemma lt_not_le_flip x y : y < x -> ~(x ≤ y).\n  Proof.\n  intros E1 E2.\n  apply (le_not_lt_flip y x);assumption.\n  Qed.\n\n  Lemma lt_le_trans x y z : x < y -> y ≤ z -> x < z.\n  Proof.\n  intros E1 E2.\n  apply lt_iff_le_apart. apply lt_iff_le_apart in E1.\n  destruct E1 as [E1a E1b].\n  split.\n  - transitivity y;assumption.\n  - apply (merely_destruct (cotransitive E1b z));intros [E3 | E3]; trivial.\n    apply lt_apart. apply symmetry in E3.\n    transitivity y;apply lt_iff_le_apart; auto.\n  Qed.\n\n  Lemma le_lt_trans x y z : x ≤ y -> y < z -> x < z.\n  Proof.\n  intros E2 E1.\n  apply lt_iff_le_apart. apply lt_iff_le_apart in E1.\n  destruct E1 as [E1a E1b].\n  split.\n  - transitivity y;auto.\n  - apply (merely_destruct (cotransitive E1b x));intros [E3 | E3]; trivial.\n    apply lt_apart. apply symmetry in E3.\n    transitivity y; apply lt_iff_le_apart; auto.\n  Qed.\n\n  Lemma lt_iff_le_ne `{!TrivialApart A} x y : x < y <-> x ≤ y /\\ x <> y.\n  Proof.\n   transitivity (x <= y /\\ apart x y).\n   - apply lt_iff_le_apart.\n   - split;intros [E1 E2];split;trivial;apply trivial_apart;trivial.\n  Qed.\n\n  Lemma le_equiv_lt `{!TrivialApart A} `{forall x y : A, Decidable (x = y)} x y\n    : x ≤ y -> x = y |_| x < y.\n  Proof.\n  intros.\n  destruct (dec (x = y)); try auto.\n  right.\n  apply lt_iff_le_ne; auto.\n  Qed.\n\n  Instance dec_from_lt_dec `{!TrivialApart A} `{forall x y, Decidable (x ≤ y)}\n    : DecidablePaths A.\n  Proof.\n  intros x y.\n  destruct (decide_rel (<=) x y) as [E1|E1];\n  [destruct (decide_rel (<=) y x) as [E2|E2]|].\n  - left. apply (antisymmetry (<=));assumption.\n  - right. intros E3;apply E2.\n    pattern y. apply (transport _ E3).\n    apply reflexivity.\n  - right. intros E3;apply E1.\n    pattern y; apply (transport _ E3).\n    apply reflexivity.\n  Defined.\n\n  Definition lt_dec_slow `{!TrivialApart A} `{forall x y, Decidable (x ≤ y)} :\n    forall x y, Decidable (x < y).\n  Proof.\n  intros x y.\n  destruct (dec (x ≤ y));\n  [destruct (dec (x = y))|].\n  - right. apply eq_not_lt. assumption.\n  - left. apply lt_iff_le_ne. auto.\n  - right. apply not_le_not_lt. assumption.\n  Defined.\nEnd full_partial_order.\n\n(* Due to bug #2528 *)\n#[export]\nHint Extern 5 (PropHolds (_ <> _)) =>\n  eapply @strict_po_apart_ne :  typeclass_instances.\n#[export]\nHint Extern 10 (PropHolds (_ ≤ _)) =>\n  eapply @lt_le : typeclass_instances.\n#[export]\nHint Extern 20 (Decidable (_ < _)) =>\n  eapply @lt_dec_slow : typeclass_instances.\n\nSection full_pseudo_order.\n  Context `{FullPseudoOrder A}.\n\n  Local Existing Instance pseudo_order_apart.\n\n  Lemma not_lt_le_flip x y : ~(y < x) -> x ≤ y.\n  Proof.\n  intros.\n  apply le_iff_not_lt_flip.\n  assumption.\n  Qed.\n\n  Instance fullpseudo_partial : PartialOrder (≤) | 10.\n  Proof.\n  repeat split.\n  - apply _.\n  - apply _.\n  - intros x. apply not_lt_le_flip, (irreflexivity (<)).\n  - intros x y z E1 E2.\n    apply le_iff_not_lt_flip;\n    apply le_iff_not_lt_flip in E1;\n    apply le_iff_not_lt_flip in E2.\n    change (complement (<) z x).\n    transitivity y;assumption.\n  - intros x y E1 E2.\n    apply le_iff_not_lt_flip in E1;\n    apply le_iff_not_lt_flip in E2.\n    apply (antisymmetry (complement (<)));assumption.\n  Qed.\n\n  Lemma fullpseudo_fullpartial' : FullPartialOrder Ale Alt.\n  Proof.\n  split; try apply _.\n  intros x y.\n  split.\n  - intros E. split.\n    + apply not_lt_le_flip. apply lt_flip;assumption.\n    + apply pseudo_order_lt_apart. assumption.\n  - intros [? E]. apply not_lt_apart_lt_flip;[|symmetry;trivial].\n    apply le_iff_not_lt_flip. trivial.\n  Qed.\n\n  Global Instance fullpseudo_fullpartial@{i} : FullPartialOrder Ale Alt\n    := ltac:(first [exact fullpseudo_fullpartial'@{i i Set Set Set}|\n                    exact fullpseudo_fullpartial'@{i i}]).\n\n  Global Instance le_stable : forall x y, Stable (x ≤ y).\n  Proof.\n  intros x y. unfold Stable.\n  intros dn. apply le_iff_not_lt_flip.\n  intros E. apply dn.\n  intros E';apply le_iff_not_lt_flip in E';auto.\n  Qed.\n\n  Lemma le_or_lt `{!TrivialApart A} `{DecidablePaths A} x y : x ≤ y |_| y < x.\n  Proof.\n  destruct (trichotomy (<) x y) as [|[|]]; try auto.\n  - left. apply lt_le;trivial.\n  - left. apply eq_le;trivial.\n  Qed.\n\n  Global Instance le_total `{!TrivialApart A} `{DecidablePaths A}\n    : TotalOrder (≤).\n  Proof.\n  split; try apply _.\n  intros x y.\n  destruct (le_or_lt x y); auto.\n  right. apply lt_le.\n  trivial.\n  Qed.\n\n  Lemma not_le_lt_flip `{!TrivialApart A} `{DecidablePaths A} x y\n    : ~(y ≤ x) -> x < y.\n  Proof.\n  intros.\n  destruct (le_or_lt y x); auto.\n  contradiction.\n  Qed.\n\n  Existing Instance dec_from_lt_dec.\n\n  Definition lt_dec `{!TrivialApart A} `{forall x y, Decidable (x ≤ y)}\n    : forall x y, Decidable (x < y).\n  Proof.\n  intros.\n  destruct (decide_rel (<=) y x).\n  - right;apply le_not_lt_flip;assumption.\n  - left; apply not_le_lt_flip;assumption.\n  Defined.\nEnd full_pseudo_order.\n\n#[export]\nHint Extern 8 (Decidable (_ < _)) => eapply @lt_dec : typeclass_instances.\n(*\nThe following instances would be tempting, but turn out to be a bad idea.\n\n#[export]\nHint Extern 10 (PropHolds (_ <> _)) => eapply @le_ne : typeclass_instances.\n#[export]\nHint Extern 10 (PropHolds (_ <> _)) => eapply @le_ne_flip : typeclass_instances.\n\nIt will then loop like:\n\nsemirings.lt_0_1 -> lt_ne_flip -> ...\n*)\n\nSection dec_strict_setoid_order.\n  Context `{StrictOrder A} `{Apart A} `{!TrivialApart A} `{DecidablePaths A}.\n\n  Instance: IsApart A := dec_strong_setoid.\n\n  Context `{!Trichotomy (<)}.\n\n  Instance dec_strict_pseudo_order: PseudoOrder (<).\n  Proof.\n  split; try apply _.\n  - intros x y [??].\n    destruct (lt_antisym x y); auto.\n  - intros x y Exy z.\n    destruct (trichotomy (<) x z) as [? | [Exz | Exz]];apply tr; try auto.\n    right. rewrite <-Exz. assumption.\n  - intros x y. transitivity (x <> y);[split;apply trivial_apart|].\n    split.\n    + destruct (trichotomy (<) x y) as [?|[?|?]]; auto.\n      intros E;contradiction E.\n    + intros [?|?];[apply lt_ne|apply lt_ne_flip];trivial.\n  Qed.\nEnd dec_strict_setoid_order.\n\nSection dec_partial_order.\n  Context `{PartialOrder A} `{DecidablePaths A}.\n\n  Definition dec_lt: Lt A := fun x y => x ≤ y /\\ x <> y.\n\n  Context `{Alt : Lt A} `{is_mere_relation A lt}\n    (lt_correct : forall x y, x < y <-> x ≤ y /\\ x <> y).\n\n  Instance dec_order: StrictOrder (<).\n  Proof.\n  split.\n  - apply _.\n  - intros x E. apply lt_correct in E. destruct E as [_ []];trivial.\n  - intros x y z E1 E2.\n    apply lt_correct;\n    apply lt_correct in E1;\n    apply lt_correct in E2.\n    destruct E1 as [E1a E1b],E2 as [E2a E2b].\n    split.\n    + transitivity y;trivial.\n    + intros E3. destruct E2b.\n      apply (antisymmetry (≤)); trivial.\n      rewrite <-E3. assumption.\n  Qed.\n\n  Context `{Apart A} `{!TrivialApart A}.\n\n  Instance: IsApart A := dec_strong_setoid.\n\n  Instance dec_full_partial_order: FullPartialOrder (≤) (<).\n  Proof.\n  split;try apply _.\n  intros. transitivity (x <= y /\\ x <> y);[|\n  split;intros [? ?];split;trivial;apply trivial_apart;trivial].\n  apply lt_correct.\n  Qed.\n\n  Context `{!TotalRelation (≤)}.\n\n  Instance: Trichotomy (<).\n  Proof.\n  intros x y.\n  destruct (dec (x = y)); try auto.\n  destruct (total (≤) x y);[left|right;right];\n  apply lt_correct;auto.\n  split;auto.\n  intro E;apply symmetry in E;auto.\n  Qed.\n\n  Instance dec_pseudo_order: PseudoOrder (<) := dec_strict_pseudo_order.\n\n  Instance dec_full_pseudo_order: FullPseudoOrder (≤) (<).\n  Proof.\n  split; try apply _.\n  intros x y.\n  split.\n  - intros ? E. apply lt_correct in E;destruct E as [? []].\n    apply (antisymmetry (≤));assumption.\n  - intros E1.\n    destruct (total (≤) x y); trivial.\n    destruct (dec (x = y)) as [E2|E2].\n    + rewrite E2. apply reflexivity.\n    + destruct E1. apply lt_correct;split;auto.\n      apply symmetric_neq;assumption.\n  Qed.\nEnd dec_partial_order.\n\nLemma lt_eq_trans `{Lt A} : forall x y z, x < y -> y = z -> x < z.\nProof.\nintros ???? [];trivial.\nQed.\n\nSection pseudo.\n  Context {A : Type}.\n  Context `{PseudoOrder A}.\n\n  Lemma nlt_lt_trans {x y z : A} : ~ (y < x) -> y < z -> x < z.\n  Proof.\n    intros nltyx ltyz.\n    assert (disj := cotransitive ltyz x).\n    strip_truncations.\n    destruct disj as [ltyx|ltxz].\n    - destruct (nltyx ltyx).\n    - exact ltxz.\n  Qed.\n\n  Lemma lt_nlt_trans {x y z : A} : x < y -> ~ (z < y) -> x < z.\n  Proof.\n    intros ltxy nltzy.\n    assert (disj := cotransitive ltxy z).\n    strip_truncations.\n    destruct disj as [ltxz|ltzy].\n    - exact ltxz.\n    - destruct (nltzy ltzy).\n  Qed.\n\n  Lemma lt_transitive : Transitive (_ : Lt A).\n  Proof.\n    intros x y z ltxy ltyz.\n    assert (ltxyz := cotransitive ltxy z).\n    strip_truncations.\n    destruct ltxyz as [ltxz|ltzy].\n    - assumption.\n    - destruct (pseudo_order_antisym y z (ltyz , ltzy)).\n  Qed.\n\n  Global Existing Instance lt_transitive.\n\nEnd pseudo.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Classes/orders/orders.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7116220661957041}}
{"text": "Require Export BaseLists Removal.\n\n(** *** Cardinality *)\n\nSection Cardinality.\n  Variable X : eqType.\n  Implicit Types A B : list X.\n\n  Fixpoint card A :=\n    match A with\n      | nil => 0\n      | x::A => if Dec (x el A) then card A else 1 + card A\n    end.\n\n  Lemma card_cons x A :\n    x el A -> card (x::A) = card A.\n  Proof.\n    intros H. cbn. decide (x el A) as [H1|H1]; tauto.\n  Qed.\n\n  Lemma card_cons' x A :\n    ~ x el A -> card (x::A) = 1 + card A.\n  Proof.\n    intros H. cbn. decide (x el A) as [H1|H1]; tauto.\n  Qed.\n  \n  Lemma card_in_rem x A :\n    x el A -> card A = 1 + card (rem A x).\n  Proof.\n    intros D. \n    induction A as [|y A].\n    - contradiction D.\n    - decide (y = x) as [->|H].\n      + clear D. rewrite rem_fst.\n        cbn. decide (x el A) as [H1|H1].\n        * auto.\n        * now rewrite (rem_id H1).\n      + assert (x el A) as H1 by (destruct D; tauto). clear D.\n        rewrite (rem_fst' _ H). specialize (IHA H1).\n        simpl card at 2. \n        decide (y el rem A x) as [H2|H2].\n        * rewrite card_cons. exact IHA.\n          apply in_rem_iff in H2. intuition.\n        * rewrite card_cons'. now rewrite IHA.\n          contradict H2.  now apply in_rem_iff.\n  Qed.\n  \n  Lemma card_not_in_rem A x :\n    ~ x el A -> card A = card (rem A x).\n  Proof.\n    intros D; rewrite rem_id; auto.\n  Qed.\n\n  Lemma card_le A B :\n    A <<= B -> card A <= card B.\n  Proof.\n  revert B. \n  induction A as [|x A]; intros B D; cbn.\n  - omega.\n  - apply incl_lcons in D as [D D1].\n    decide (x el A) as [E|E].\n    + auto.\n    + rewrite (card_in_rem D).\n      enough (card A <= card (rem B x)) by omega.\n      apply IHA. auto.\n  Qed.\n\n  Lemma card_eq A B :\n    A === B -> card A = card B.\n  Proof.\n    intros [E F]. apply card_le in E. apply card_le in F. omega.\n  Qed.\n\n  Lemma card_cons_rem x A :\n    card (x::A) = 1 + card (rem A x).\n  Proof.\n    rewrite (card_eq (rem_equi x A)). cbn.\n    decide (x el rem A x) as [D|D].\n    - exfalso. apply in_rem_iff in D; tauto.\n    - reflexivity.\n  Qed.\n\n  Lemma card_0 A :\n    card A = 0 -> A = nil.\n  Proof.\n    destruct A as [|x A]; intros D.\n    - reflexivity.\n    - exfalso. rewrite card_cons_rem in D. omega.\n  Qed.\n\n  Lemma card_ex A B :\n    card A < card B -> exists x, x el B /\\ ~ x el A.\n  Proof.\n    intros D.\n    decide (B <<= A) as [E|E].\n    - exfalso. apply card_le in E. omega.\n    - apply list_exists_not_incl; auto.\n  Qed.\n\n  Lemma card_equi A B :\n    A <<= B -> card A = card B -> A === B.\n  Proof.\n    revert B. \n    induction A as [|x A]; cbn; intros B D E.\n    - symmetry in E. apply card_0 in E. now rewrite E.\n    - apply incl_lcons in D as [D D1].\n      decide (x el A) as [F|F].\n      + rewrite (IHA B); auto.\n      + rewrite (IHA (rem B x)).\n        * symmetry. apply rem_reorder, D.\n        * auto.\n        * apply card_in_rem in D. omega.\n  Qed.\n\n  Lemma card_lt A B x :\n    A <<= B -> x el B -> ~ x el A -> card A < card B.\n  Proof.\n    intros D E F.\n    decide (card A = card B) as [G|G].\n    + exfalso. apply F. apply (card_equi D); auto.\n    + apply card_le in D. omega.\n  Qed.\n\n  Lemma card_or A B :\n    A <<= B -> A === B \\/ card A < card B.\n  Proof.\n    intros D.\n    decide (card A = card B) as [F|F].\n    - left. apply card_equi; auto.\n    - right. apply card_le in D. omega.\n  Qed.\n\nEnd Cardinality.\n\nInstance card_equi_proper (X: eqType) : \n  Proper (@equi X ==> eq) (@card X).\nProof. \n  hnf. apply card_eq.\nQed.\n", "meta": {"author": "uds-psl", "repo": "base-library", "sha": "d9f3b8abf379d4c12049dd25c8d1fdf1973dab48", "save_path": "github-repos/coq/uds-psl-base-library", "path": "github-repos/coq/uds-psl-base-library/base-library-d9f3b8abf379d4c12049dd25c8d1fdf1973dab48/Lists/Cardinality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7116220596095797}}
{"text": "(*定义类型 day*)\nInductive day : Type :=\n    |monday\n    |tuesday\n    |thursday\n    |wednesday\n    |friday\n    |saturday\n    |sunday.\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\n(*通过Compute命令计算next_weekday表达式的值*)\nCompute (next_weekday friday).\nCompute (next_weekday (next_weekday saturday)).\n\n(*期望的结果*)\n(*先定义一个断言assertion，名字叫做test_next_weekday，方便以后引用*)\nExample test_next_weekday:\n    (next_weekday (next_weekday saturday)) = tuesday.\n(*通过Proof来证明断言的正确性*)\nProof. \n    simpl.\n    reflexivity. \nQed.\n\n(*定义布尔类型*)\nInductive bool : Type :=\n    |true\n    |false.\n\nDefinition negb (b:bool) : bool :=\n    match b with\n    |true => false\n    |fasle => 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(*对上述布尔函数进行测试*)\nExample test_orb1: \n    (orb true false) = true.\nProof.\n    simpl.\n    reflexivity.\nQed.\nExample test_orb2:\n    (orb false false) = false.\nProof.\n    simpl.\n    reflexivity.\nQed.\nExample test_orb3:\n    (orb false true) = true.\nProof.\n    simpl.\n    reflexivity.\nQed.\n\nExample test_orb4:\n    (orb true true) = true.\nProof.\n    simpl.\n    reflexivity.\nQed.\n\n(*使用Notation简化Definition*)\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5:\n    false || false || true = true.\nProof.\n    simpl.\n    reflexivity.\nQed.\n\n(*条件表达式*)\nDefinition negb' (b:bool) : bool:=\n    if b\n        then false\n    else \n        true.\n\nDefinition andb' (b1:bool)(b2:bool) : bool:=\n    if b1\n        then b2\n    else\n        false.\n\nDefinition orb' (b1:bool)(b2:bool) : bool:=\n    if b1\n        then true\n    else\n        b2.\n\n(*练习1，nandb*)\nDefinition nandb (b1:bool)(b2:bool) : bool:=\n    match b1 with\n    |true => negb b2\n    |false => true\n    end.\nExample test_nandb1: \n    (nandb true false) = true.\nProof.\n    simpl.\n    reflexivity.\nQed.\nExample test_nandb2: \n    (nandb false false) = true.\nProof.\n    simpl.\n    reflexivity.\nQed.\nExample test_nandb3: \n    (nandb false true) = true.\nProof.\n    simpl.\n    reflexivity.\nQed.\nExample test_nandb4: \n    (nandb true true) = false.\nProof.\n    simpl.\n    reflexivity.\nQed.\n\n(*练习2，andb3*)\nDefinition andb3 (b1:bool)(b2:bool)(b3:bool) : bool :=\n    match b1 with\n    |true => andb b2 b3\n    |false => false\n    end.\nExample test_andb31: \n    (andb3 true true true) = true.\nProof.\n    simpl.\n    reflexivity.\nQed.\nExample test_andb32: \n    (andb3 false true true) = false.\nProof.\n    simpl.\n    reflexivity.\nQed.\nExample test_andb33: \n    (andb3 true false true) = false.\nProof.\n    simpl.\n    reflexivity.\nQed.\nExample test_andb34: \n    (andb3 true true false) = false.\nProof.\n    simpl.\n    reflexivity.\nQed.\n\n(*类型Type，包括表达式和函数*)\nCheck true.\nCheck true : bool.\nCheck (negb true) : bool.\nCheck negb : bool -> bool.\n\n(*由旧类型构造新类型，类似于复合定义*)\nInductive rgb : Type :=\n    |red\n    |green\n    |blue.\n\nInductive color : Type :=\n    |black\n    |white\n    |primary (p:rgb).\n\nDefinition monochrome (c:color) : bool :=\n    match c with\n    |black => true\n    |white => true\n    |primary p => false\n    end.\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\n(*模块Modules*)\nModule Playground.\n    Definition b : rgb := blue.        \nEnd Playground.\n\nDefinition b : bool := true.\nCheck b : bool.\n\n(*元组Tuples*)\nModule TuplePlayground.\nInductive bit : Type :=\n    |B0\n    |B1.\n\nInductive nybble : Type :=\n    |bits (b0 b1 b2 b3 : bit).\n\nCheck (bits B1 B0 B1 B0) : nybble.\n\nDefinition all_zero (nb : nybble) : bool :=\n    match nb with\n    |(bits B0 B0 B0 B0) => true\n    |(bits _ _ _ _) => false\n    end.\n\nCompute (all_zero (bits B1 B0 B1 B0)).\nCompute (all_zero (bits B0 B0 B0 B0)).\nEnd TuplePlayground.\n\n(*自然数Numbers*)\nModule NatPlayground.\nInductive nat : Type :=\n    |O\n    |S (n : nat).\n\nInductive nat' : Type :=\n    |stop\n    |tick (foo : nat').\n\nCheck tick stop.\n", "meta": {"author": "Enchavin", "repo": "Coq", "sha": "13403868fed19d774de69b17d0df3dc67c8fc722", "save_path": "github-repos/coq/Enchavin-Coq", "path": "github-repos/coq/Enchavin-Coq/Coq-13403868fed19d774de69b17d0df3dc67c8fc722/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7115865085794406}}
{"text": "Module NatList.\nInductive natprod : Type :=\n  | pair (n1 n2 : nat).\n\nNotation \"( x , y )\" := (pair x y).\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\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\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", "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/Chapter3/fst_swap_is_snd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517042, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7115864939832441}}
{"text": "Inductive day : Type :=\n  | monday\n  | tuesday\n  | wednesday\n  | thursday\n  | friday\n  | saturday\n  | sunday.\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\nCompute (next_weekday friday).\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\nProof. simpl. reflexivity. Qed.\n\nFrom Coq Require Export String.\n\nInductive bool : Type := \n  | true\n  | false.\n\nDefinition negb (b : bool) : bool :=\n  match b with\n  | true  => false\n  | false => true\n  end.\n\nDefinition andb (b_1 : bool) (b_2 : bool) : bool :=\n  match b_1 with\n  | true  => b_2\n  | false => false\n  end.\n\nDefinition orb (b_1 : bool) (b_2 : bool) : bool :=\n  match b_1 with\n  | true  => true\n  | false => b_2\n  end.\n\nExample test_orb1: (orb true false) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb2: (orb false false) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb3: (orb false true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_orb4: (orb true true) = true.\nProof. simpl. reflexivity. Qed.\n\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5: false || false || true = true.\nProof. simpl. reflexivity. Qed.\n\nDefinition nandb (b_1 : bool) (b_2 : bool) : bool :=\n  negb (andb b_1 b_2).\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\nExample test_nandb3: (nandb false true)  = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_nandb4: (nandb true true)   = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition andb3 (b_1 : bool) (b_2 : bool) (b_3 : bool) : bool :=\n  andb (andb b_1 b_2) b_3.\n\nExample test_andb31: (andb3 true true true) = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb32: (andb3 false true true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb33: (andb3 true false true) = false.\nProof. simpl. reflexivity. Qed.\n\nExample test_andb34: (andb3 true true false) = false.\nProof. simpl. reflexivity. Qed.\n\nCheck true.\n\nCheck true : bool.\n\nCheck (negb true) : bool.\n\nCheck negb : bool -> bool.\n\nInductive rgb : Type :=\n  | red\n  | green\n  | blue.\n\nInductive color : Type :=\n  | black\n  | white\n  | primary (p : rgb).\n\nDefinition monochrome (c : color) : bool :=\n  match c with\n  | black     => true\n  | white     => true\n  | primary p => false\n  end.\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\nModule Playground.\n  Definition b : rgb := blue.\nEnd Playground.\n\nDefinition b : bool := true.\n\nCheck Playground.b : rgb.\nCheck b : bool.\n\nModule TuplePlayground.\n\nInductive bit : Type :=\n  | B_0\n  | B_1.\n\nInductive nybble : Type :=\n  | bits (b_0 b_1 b_2 b_3 : bit).\n\nCheck (bits B_1 B_0 B_1 B_0) : nybble.\n\nModule NatPlayground.\n\nInductive nat : Type :=\n  | O\n  | S (n : nat).\n\nDefinition pred (n : nat) : nat :=\n  match n with\n  | O => O\n  | S n' => n'\n  end.\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\nCheck S : nat -> nat.\nCheck pred : nat -> nat.\nCheck minustwo : nat -> nat.\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.\n\nExample test_odd2: odd 4 = false.\nProof. simpl. reflexivity. Qed.\n\nModule NatPlayground2.\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 5).\n\nFixpoint mult (n : nat) (m : nat) : nat :=\n  match n with\n  | O    => O\n  | S n' => plus m (mult n' m )\n  end.\n\nCompute (mult 3 5).\n\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.\n\nCompute (minus 5 3).\n\nEnd NatPlayground2.\n\nFixpoint exp (n m : nat) : nat :=\n  match m with\n  | O    => S O\n  | S m' => mult n (exp n m')\n  end.\n\nCompute (exp 2 3).\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 3) = 6.\nProof. simpl. reflexivity. Qed.\n\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.\nCheck ((0 + 1) + 1) : nat.\n\nFixpoint eqb (n m : nat) : bool :=\n  match n with\n  | O    => match m with\n            | O    => true\n            | S _  => 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, m with\n  | O, _       => true\n  | S n', O    => false\n  | S n', S m' => leb n' m'\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\nNotation \"x =? y\" := (eqb x y) (at level 70) : nat_scope.\nNotation \"x <=? y\" := (leb x y) (at level 70) : nat_scope.\n\nExample test_leb3': (4 <=? 2) = false.\nProof. simpl. reflexivity. Qed.\n\nDefinition ltb (n m : nat) : bool := \n  andb (leb n m) (negb (eqb n m)).\n\nNotation \"x <? y\" := (ltb x y) (at level 70) : nat_scope.\n\nExample test_ltb1: (ltb 2 2) = false.\nProof. simpl. reflexivity. Qed.\nExample test_ltb2: (ltb 2 4) = true.\nProof. simpl. reflexivity. Qed.\nExample test_ltb3: (ltb 4 2) = false.\nProof. simpl. reflexivity. Qed.\n\nTheorem plus_O_n : forall n : nat, O + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_1_l : forall n : nat, 1 + n = S n.\nProof. intros n. reflexivity. Qed.\n\nTheorem mult_0_l : forall n : nat, 0 * n = 0.\nProof. intros n. reflexivity. Qed.\n\nTheorem plus_id_example : forall n m : nat,\n  n = m -> 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 H2.\n  rewrite -> H1.\n  rewrite <- H2.\n  reflexivity.\nQed.\n\nTheorem mult_n_0_m_0 : forall p q : nat,\n  (p * 0) + (q * 0) = 0.\nProof.\n  intros p q.\n  rewrite <- mult_n_O.\n  rewrite <- mult_n_O.\n  reflexivity.\nQed.\n\nTheorem mult_n_1 : forall p : nat,\n  p * 1 = p.\nProof.\n  intro p.\n  rewrite <- mult_n_Sm.\n  rewrite <- mult_n_O.\n  reflexivity.\nQed.\n\nTheorem plus_1_neg_0 : forall n : nat, (n+1) =? 0 = false.\nProof.\n  intro n.\n  destruct n as [|n'] eqn: E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem negb_involutive : forall b : bool, negb (negb b) = b.\nProof.\n  intro b.\n  destruct b eqn: E.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem andb_commmutative : forall b c, andb b c = andb c b.\nProof.\n  intros b c.\n  destruct c eqn:Ec.\n  - destruct b eqn:Eb.\n    + reflexivity.\n    + reflexivity.\n  - destruct b eqn:Eb.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem andb3_exchange : 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 abdb_true_elim2 : forall b c : bool, andb b c = true -> c = true.\nProof.\n  intros b c. destruct c eqn:Ec.\n  - destruct b eqn:Eb.\n  -- reflexivity.\n  -- reflexivity.\n  - destruct b eqn:Eb.\n  -- intro H. rewrite <- H. reflexivity.\n  -- intro H. rewrite <- H. reflexivity.\nQed.\n\n\n\n\n\n\n\n", "meta": {"author": "stschulte1967", "repo": "proofs", "sha": "b8222f5764e01c4ed50f0ec1a6b5ce76987b7dda", "save_path": "github-repos/coq/stschulte1967-proofs", "path": "github-repos/coq/stschulte1967-proofs/proofs-b8222f5764e01c4ed50f0ec1a6b5ce76987b7dda/SoftwareFoundations/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985637, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7115864882237315}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrfun ssrbool eqtype ssrnat seq div.\nFrom mathcomp\nRequire Import fintype bigop finset prime fingroup ssralg finalg.\n\n(******************************************************************************)\n(*  Definition of the additive group and ring Zp, represented as 'I_p         *)\n(******************************************************************************)\n(* Definitions:                                                               *)\n(* From fintype.v:                                                            *)\n(*     'I_p == the subtype of integers less than p, taken here as the type of *)\n(*             the integers mod p.                                            *)\n(* This file:                                                                 *)\n(*     inZp == the natural projection from nat into the integers mod p,       *)\n(*             represented as 'I_p. Here p is implicit, but MUST be of the    *)\n(*             form n.+1.                                                     *)\n(* The operations:                                                            *)\n(*      Zp0 == the identity element for addition                              *)\n(*      Zp1 == the identity element for multiplication, and a generator of    *)\n(*             additive group                                                 *)\n(*   Zp_opp == inverse function for addition                                  *)\n(*   Zp_add == addition                                                       *)\n(*   Zp_mul == multiplication                                                 *)\n(*   Zp_inv == inverse function for multiplication                            *)\n(* Note that while 'I_n.+1 has canonical finZmodType and finGroupType         *)\n(* structures, only 'I_n.+2 has a canonical ring structure (it has, in fact,  *)\n(* a canonical finComUnitRing structure), and hence an associated             *)\n(* multiplicative unit finGroupType. To mitigate the issues caused by the     *)\n(* trivial \"ring\" (which is, indeed is NOT a ring in the ssralg/finalg        *)\n(* formalization), we define additional notation:                             *)\n(*       'Z_p == the type of integers mod (max p 2); this is always a proper  *)\n(*               ring, by constructions. Note that 'Z_p is provably equal to  *)\n(*               'I_p if p > 1, and convertible to 'I_p if p is of the form   *)\n(*               n.+2.                                                        *)\n(*       Zp p == the subgroup of integers mod (max p 1) in 'Z_p; this is thus *)\n(*               is thus all of 'Z_p if p > 1, and else the trivial group.    *)\n(* units_Zp p == the group of all units of 'Z_p -- i.e., the group of         *)\n(*               (multiplicative) automorphisms of Zp p.                      *)\n(* We show that Zp and units_Zp are abelian, and compute their orders.        *)\n(* We use a similar technique to represent the prime fields:                  *)\n(*        'F_p == the finite field of integers mod the first prime divisor of *)\n(*                maxn p 2. This is provably equal to 'Z_p and 'I_p if p is   *)\n(*                provably prime, and indeed convertible to the above if p is *)\n(*                a concrete prime such as 2, 5 or 23.                        *)\n(* Note finally that due to the canonical structures it is possible to use    *)\n(* 0%R instead of Zp0, and 1%R instead of Zp1 (for the latter, p must be of   *)\n(* the form n.+2, and 1%R : nat will simplify to 1%N).                        *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\n\nSection ZpDef.\n\n(***********************************************************************)\n(*                                                                     *)\n(*  Mod p arithmetic on the finite set {0, 1, 2, ..., p - 1}           *)\n(*                                                                     *)\n(***********************************************************************)\n\nVariable p' : nat.\nLocal Notation p := p'.+1.\n\nImplicit Types x y z : 'I_p.\n\n(* Standard injection; val (inZp i) = i %% p *)\nDefinition inZp i := Ordinal (ltn_pmod i (ltn0Sn p')).\nLemma modZp x : x %% p = x.\nProof. by rewrite modn_small ?ltn_ord. Qed.\nLemma valZpK x : inZp x = x.\nProof. by apply: val_inj; rewrite /= modZp. Qed.\n\n(* Operations *)\nDefinition Zp0 : 'I_p := ord0.\nDefinition Zp1 := inZp 1.\nDefinition Zp_opp x := inZp (p - x).\nDefinition Zp_add x y := inZp (x + y).\nDefinition Zp_mul x y := inZp (x * y).\nDefinition Zp_inv x := if coprime p x then inZp (egcdn x p).1 else x.\n\n(* Additive group structure. *)\n\nLemma Zp_add0z : left_id Zp0 Zp_add.\nProof. exact: valZpK. Qed.\n\nLemma Zp_addNz : left_inverse Zp0 Zp_opp Zp_add.\nProof.\nby move=> x; apply: val_inj; rewrite /= modnDml subnK ?modnn // ltnW.\nQed.\n\nLemma Zp_addA : associative Zp_add.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modnDml modnDmr addnA.\nQed.\n\nLemma Zp_addC : commutative Zp_add.\nProof. by move=> x y; apply: val_inj; rewrite /= addnC. Qed.\n\nDefinition Zp_zmodMixin := ZmodMixin Zp_addA Zp_addC Zp_add0z Zp_addNz.\nCanonical Zp_zmodType := Eval hnf in ZmodType 'I_p Zp_zmodMixin.\nCanonical Zp_finZmodType := Eval hnf in [finZmodType of 'I_p].\nCanonical Zp_baseFinGroupType := Eval hnf in [baseFinGroupType of 'I_p for +%R].\nCanonical Zp_finGroupType := Eval hnf in [finGroupType of 'I_p for +%R].\n\n(* Ring operations *)\n\nLemma Zp_mul1z : left_id Zp1 Zp_mul.\nProof. by move=> x; apply: val_inj; rewrite /= modnMml mul1n modZp. Qed.\n\nLemma Zp_mulC : commutative Zp_mul.\nProof. by move=> x y; apply: val_inj; rewrite /= mulnC. Qed.\n\nLemma Zp_mulz1 : right_id Zp1 Zp_mul.\nProof. by move=> x; rewrite Zp_mulC Zp_mul1z. Qed.\n\nLemma Zp_mulA : associative Zp_mul.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modnMml modnMmr mulnA.\nQed.\n\nLemma Zp_mul_addr : right_distributive Zp_mul Zp_add.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modnMmr modnDm mulnDr.\nQed.\n\nLemma Zp_mul_addl : left_distributive Zp_mul Zp_add.\nProof. by move=> x y z; rewrite -!(Zp_mulC z) Zp_mul_addr. Qed.\n\nLemma Zp_mulVz x : coprime p x -> Zp_mul (Zp_inv x) x = Zp1.\nProof.\nmove=> co_p_x; apply: val_inj; rewrite /Zp_inv co_p_x /= modnMml.\nby rewrite -(chinese_modl co_p_x 1 0) /chinese addn0 mul1n mulnC.\nQed.\n\nLemma Zp_mulzV x : coprime p x -> Zp_mul x (Zp_inv x) = Zp1.\nProof. by move=> Ux; rewrite /= Zp_mulC Zp_mulVz. Qed.\n\nLemma Zp_intro_unit x y : Zp_mul y x = Zp1 -> coprime p x.\nProof.\ncase=> yx1; have:= coprimen1 p.\nby rewrite -coprime_modr -yx1 coprime_modr coprime_mulr; case/andP.\nQed.\n\nLemma Zp_inv_out x : ~~ coprime p x -> Zp_inv x = x.\nProof. by rewrite /Zp_inv => /negPf->. Qed.\n\nLemma Zp_mulrn x n : x *+ n = inZp (x * n).\nProof.\napply: val_inj => /=; elim: n => [|n IHn]; first by rewrite muln0 modn_small.\nby rewrite !GRing.mulrS /= IHn modnDmr mulnS.\nQed.\n\nImport GroupScope.\n\nLemma Zp_mulgC : @commutative 'I_p _ mulg.\nProof. exact: Zp_addC. Qed.\n\nLemma Zp_abelian : abelian [set: 'I_p].\nProof. exact: FinRing.zmod_abelian. Qed.\n\nLemma Zp_expg x n : x ^+ n = inZp (x * n).\nProof. exact: Zp_mulrn. Qed.\n\nLemma Zp1_expgz x : Zp1 ^+ x = x.\nProof. by rewrite Zp_expg; apply: Zp_mul1z. Qed.\n\nLemma Zp_cycle : setT = <[Zp1]>.\nProof. by apply/setP=> x; rewrite -[x]Zp1_expgz inE groupX ?mem_gen ?set11. Qed.\n\nLemma order_Zp1 : #[Zp1] = p.\nProof. by rewrite orderE -Zp_cycle cardsT card_ord. Qed.\n\nEnd ZpDef.\n\nArguments Zp0 {p'}.\nArguments Zp1 {p'}.\nArguments inZp {p'}.\n\nLemma ord1 : all_equal_to (0 : 'I_1).\nProof. by case=> [[] // ?]; apply: val_inj. Qed.\n\nLemma lshift0 m n : lshift m (0 : 'I_n.+1) = (0 : 'I_(n + m).+1).\nProof. exact: val_inj. Qed.\n\nLemma rshift1 n : @rshift 1 n =1 lift (0 : 'I_n.+1).\nProof. by move=> i; apply: val_inj. Qed.\n\nLemma split1 n i :\n  split (i : 'I_(1 + n)) = oapp (@inr _ _) (inl _ 0) (unlift 0 i).\nProof.\ncase: unliftP => [i'|] -> /=.\n  by rewrite -rshift1 (unsplitK (inr _ _)).\nby rewrite -(lshift0 n 0) (unsplitK (inl _ _)).\nQed.\n\nLemma big_ord1 R idx (op : @Monoid.law R idx) F :\n  \\big[op/idx]_(i < 1) F i = F 0.\nProof. by rewrite big_ord_recl big_ord0 Monoid.mulm1. Qed.\n\nLemma big_ord1_cond R idx (op : @Monoid.law R idx) P F :\n  \\big[op/idx]_(i < 1 | P i) F i = if P 0 then F 0 else idx.\nProof. by rewrite big_mkcond big_ord1. Qed.\n\nSection ZpRing.\n\nVariable p' : nat.\nLocal Notation p := p'.+2.\n\nLemma Zp_nontrivial : Zp1 != 0 :> 'I_p. Proof. by []. Qed.\n\nDefinition Zp_ringMixin :=\n  ComRingMixin (@Zp_mulA _) (@Zp_mulC _) (@Zp_mul1z _) (@Zp_mul_addl _)\n               Zp_nontrivial.\nCanonical Zp_ringType := Eval hnf in RingType 'I_p Zp_ringMixin.\nCanonical Zp_finRingType := Eval hnf in [finRingType of 'I_p].\nCanonical Zp_comRingType := Eval hnf in ComRingType 'I_p (@Zp_mulC _).\nCanonical Zp_finComRingType := Eval hnf in [finComRingType of 'I_p].\n\nDefinition Zp_unitRingMixin :=\n  ComUnitRingMixin (@Zp_mulVz _) (@Zp_intro_unit _) (@Zp_inv_out _).\nCanonical Zp_unitRingType := Eval hnf in UnitRingType 'I_p Zp_unitRingMixin.\nCanonical Zp_finUnitRingType := Eval hnf in [finUnitRingType of 'I_p].\nCanonical Zp_comUnitRingType := Eval hnf in [comUnitRingType of 'I_p].\nCanonical Zp_finComUnitRingType := Eval hnf in [finComUnitRingType of 'I_p].\n\nLemma Zp_nat n : n%:R = inZp n :> 'I_p.\nProof. by apply: val_inj; rewrite [n%:R]Zp_mulrn /= modnMml mul1n. Qed.\n\nLemma natr_Zp (x : 'I_p) : x%:R = x.\nProof. by rewrite Zp_nat valZpK. Qed.\n\nLemma natr_negZp (x : 'I_p) : (- x)%:R = - x.\nProof. by apply: val_inj; rewrite /= Zp_nat /= modn_mod. Qed.\n\nImport GroupScope.\n\nLemma unit_Zp_mulgC : @commutative {unit 'I_p} _ mulg.\nProof. by move=> u v; apply: val_inj; rewrite /= GRing.mulrC. Qed.\n\nLemma unit_Zp_expg (u : {unit 'I_p}) n :\n  val (u ^+ n) = inZp (val u ^ n) :> 'I_p.\nProof.\napply: val_inj => /=; elim: n => [|n IHn] //.\nby rewrite expgS /= IHn expnS modnMmr.\nQed.\n\nEnd ZpRing.\n\nDefinition Zp_trunc p := p.-2.\n\nNotation \"''Z_' p\" := 'I_(Zp_trunc p).+2\n  (at level 8, p at level 2, format \"''Z_' p\") : type_scope.\nNotation \"''F_' p\" := 'Z_(pdiv p)\n  (at level 8, p at level 2, format \"''F_' p\") : type_scope.\n\nSection Groups.\n\nVariable p : nat.\n\nDefinition Zp := if p > 1 then [set: 'Z_p] else 1%g.\nDefinition units_Zp := [set: {unit 'Z_p}].\n\nLemma Zp_cast : p > 1 -> (Zp_trunc p).+2 = p.\nProof. by case: p => [|[]]. Qed.\n\nLemma val_Zp_nat (p_gt1 : p > 1) n : (n%:R : 'Z_p) = (n %% p)%N :> nat.\nProof. by rewrite Zp_nat /= Zp_cast. Qed.\n\nLemma Zp_nat_mod (p_gt1 : p > 1)m : (m %% p)%:R = m%:R :> 'Z_p.\nProof. by apply: ord_inj; rewrite !val_Zp_nat // modn_mod. Qed.\n\nLemma char_Zp : p > 1 -> p%:R = 0 :> 'Z_p.\nProof. by move=> p_gt1; rewrite -Zp_nat_mod ?modnn. Qed.\n\nLemma unitZpE x : p > 1 -> ((x%:R : 'Z_p) \\is a GRing.unit) = coprime p x.\nProof.\nby move=> p_gt1; rewrite qualifE /= val_Zp_nat ?Zp_cast ?coprime_modr.\nQed.\n\nLemma Zp_group_set : group_set Zp.\nProof. by rewrite /Zp; case: (p > 1); apply: groupP. Qed.\nCanonical Zp_group := Group Zp_group_set.\n\nLemma card_Zp : p > 0 -> #|Zp| = p.\nProof.\nrewrite /Zp; case: p => [|[|p']] //= _; first by rewrite cards1.\nby rewrite cardsT card_ord.\nQed.\n\nLemma mem_Zp x : p > 1 -> x \\in Zp. Proof. by rewrite /Zp => ->. Qed.\n\nCanonical units_Zp_group := [group of units_Zp].\n\nLemma card_units_Zp : p > 0 -> #|units_Zp| = totient p.\nProof.\nmove=> p_gt0; transitivity (totient p.-2.+2); last by case: p p_gt0 => [|[|p']].\nrewrite cardsT card_sub -sum1_card big_mkcond /=.\nby rewrite totient_count_coprime big_mkord.\nQed.\n\nLemma units_Zp_abelian : abelian units_Zp.\nProof. by apply/centsP=> u _ v _; apply: unit_Zp_mulgC. Qed.\n\nEnd Groups.\n\n(* Field structure for primes. *)\n\nSection PrimeField.\n\nOpen Scope ring_scope.\n\nVariable p : nat.\n\nSection F_prime.\n\nHypothesis p_pr : prime p.\n\nLemma Fp_Zcast : (Zp_trunc (pdiv p)).+2 = (Zp_trunc p).+2.\nProof. by rewrite /pdiv primes_prime. Qed.\n\nLemma Fp_cast : (Zp_trunc (pdiv p)).+2 = p.\nProof. by rewrite Fp_Zcast ?Zp_cast ?prime_gt1. Qed.\n\nLemma card_Fp : #|'F_p| = p.\nProof. by rewrite card_ord Fp_cast. Qed.\n\nLemma val_Fp_nat n : (n%:R : 'F_p) = (n %% p)%N :> nat.\nProof. by rewrite Zp_nat /= Fp_cast. Qed.\n\nLemma Fp_nat_mod m : (m %% p)%:R = m%:R :> 'F_p.\nProof. by apply: ord_inj; rewrite !val_Fp_nat // modn_mod. Qed.\n\nLemma char_Fp : p \\in [char 'F_p].\nProof. by rewrite !inE -Fp_nat_mod p_pr ?modnn. Qed.\n\nLemma char_Fp_0 : p%:R = 0 :> 'F_p.\nProof. exact: GRing.charf0 char_Fp. Qed.\n\nLemma unitFpE x : ((x%:R : 'F_p) \\is a GRing.unit) = coprime p x.\nProof. by rewrite pdiv_id // unitZpE // prime_gt1. Qed.\n\nEnd F_prime.\n\nLemma Fp_fieldMixin : GRing.Field.mixin_of [the unitRingType of 'F_p].\nProof.\nmove=> x nzx; rewrite qualifE /= prime_coprime ?gtnNdvd ?lt0n //.\ncase: (ltnP 1 p) => [lt1p | ]; last by case: p => [|[|p']].\nby rewrite Zp_cast ?prime_gt1 ?pdiv_prime.\nQed.\n\nDefinition Fp_idomainMixin := FieldIdomainMixin Fp_fieldMixin.\n\nCanonical Fp_idomainType := Eval hnf in IdomainType 'F_p  Fp_idomainMixin.\nCanonical Fp_finIdomainType := Eval hnf in [finIdomainType of 'F_p].\nCanonical Fp_fieldType := Eval hnf in FieldType 'F_p Fp_fieldMixin.\nCanonical Fp_finFieldType := Eval hnf in [finFieldType of 'F_p].\nCanonical Fp_decFieldType :=\n  Eval hnf in [decFieldType of 'F_p for Fp_finFieldType].\n\nEnd PrimeField.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-mathcomp/mathcomp/algebra/zmodp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7115793850814214}}
{"text": "Require Import Crypto.Algebra.Hierarchy.\nRequire Import ZArith Znumtheory.\nRequire Import Lia.\nRequire Import Logic.\nFrom Coqprime Require Import Pmod. \nSection RepSquare.\nContext {T op id} {monoid: @monoid T (@eq T) op id}.\n\nLocal Open Scope nat_scope.\n\nLocal Infix \"*\" := op.\nLocal Infix \"=\" := eq.\n\nFixpoint pow_pos (x : T) (n : positive) : T :=\nmatch n with\n    | xH => x\n    | xO m => (pow_pos (x * x) m)\n    | xI m => (pow_pos (x * x) m) * x\nend.\n\nNotation \"x ^ n\" := (pow_pos x n).\n\nFixpoint pow_nat (x : T) (n : nat) : T :=\nmatch n with\n    | O => id\n    | S m => (pow_nat x m) * x\nend.\n\nNotation \"x ^' n\" := (pow_nat x n) (at level 80).\n\nLtac move_operand_left y H := \n  repeat (rewrite <- (associative y _ _); try (rewrite H; repeat rewrite associative)); repeat rewrite associative; try rewrite H.\n\nLtac apply_comm x y H := repeat rewrite associative; move_operand_left y H; repeat rewrite <- associative;\nmatch goal with\n  | |- (x * ?n1) = (x * ?n2) => assert (n1 = n2) as Haux by (apply_comm x y H); rewrite Haux; auto\n  | _ => auto\nend.\n\nLemma pow_nat_plus: forall x (n m : nat), (x ^' (n + m)) = (x ^' n) * (x ^' m).\nProof.\n    intros x n m. induction m as [| m' IHm'].\n        - rewrite right_identity; auto with zarith.\n        - simpl; rewrite associative; rewrite <- IHm'; rewrite Nat.add_succ_r; auto.\nQed.\n\nLemma pow_pos_odd: forall x n, x ^ (n~1) = x^(n~0) * x.\nProof. auto. Qed.\n\nLemma pow_pos_ev: forall x n, (x^ (n ~0) = x ^ n * x ^ n) /\\ x ^ n * x = x * x ^ n.\nProof.\n    intros x n; generalize dependent x; simpl; induction n as [n' IHn'|n' IHn'|]; intros x; split; simpl; auto;\n    repeat rewrite (proj1 (IHn' (_))); apply_comm x (x ^ n') (proj2 (IHn' x)).\nQed.\n\nLemma pow_pos_com: forall x n, x * x ^ n = x ^ n * x.\nProof. intros x n; symmetry; apply (proj2 (pow_pos_ev x n)). Qed.\n\nLemma pow_pos_distr: forall x n, (x * x) ^ n = x ^ n * x ^ n.\nProof.\n    intros x n; pose proof pow_pos_ev as H; induction n as [n' IHn' |n' IHn' |]; try destruct (H (x * x) n') as [H0 _]; auto.\n        - repeat rewrite pow_pos_odd; destruct (H x n') as [H1 _]; repeat rewrite H0; rewrite H1;\n          repeat rewrite IHn'; apply_comm x (x ^ n') (pow_pos_com x n').\nQed.\n\nLemma repeated_square_correct: forall x n, pow_pos x n = pow_nat x (Pos.to_nat n).\nProof.\n    intros x n; induction n as [n' IHn| |].\n        - rewrite Pos2Nat.inj_xI; simpl; rewrite pow_nat_plus;\n          rewrite Nat.add_0_r; rewrite <- IHn; rewrite pow_pos_distr; auto.\n        - rewrite Pos2Nat.inj_xO; simpl; rewrite Nat.add_0_r; rewrite pow_nat_plus;\n          rewrite <- IHn; apply pow_pos_distr.\n        - simpl; rewrite left_identity; auto. \nQed.\n\nEnd RepSquare.", "meta": {"author": "AU-COBRA", "repo": "AUCurves", "sha": "ea864da1b1e78a86fda16818a9366a96da83cb63", "save_path": "github-repos/coq/AU-COBRA-AUCurves", "path": "github-repos/coq/AU-COBRA-AUCurves/AUCurves-ea864da1b1e78a86fda16818a9366a96da83cb63/src/Theory/Util/RepeatedSquaring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7115793785871893}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) (lf3 : natural) : natural :=\n  mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj83_coqofml_dBXjhT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.7115760843991716}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := mult z (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj214_coqofml_ankqjJ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.7115760746051165}}
{"text": "Require Import Tutorial.\n\n\n(* A specification of what it means to choose a number that is not in a particular list *)\nDefinition notInList (ls : list nat) :=\n  {n : nat | ~In n ls}%comp.\n\n(* We can use a simple property to justify a decomposition of the original spec. *)\nTheorem notInList_decompose : forall ls,\n  refine (notInList ls) (upper <- {upper | forall n, In n ls -> upper >= n};\n                         {beyond | beyond > upper}).\nProof.\n  refines.\n  firstorder.\nQed.\n\n(* A simple traversal will find the maximum list element, which is a good upper bound. *)\nDefinition listMax := fold_right max 0.\n\n(* ...and we can prove it! *)\nTheorem listMax_upperBound : forall init ls,\n  forall n, In n ls -> fold_right max init ls >= n.\nProof.\n  induction ls; simpl; intuition.\n  arithmetic.\n  apply IHls in H0.\n  arithmetic.\nQed.\n\n(* Now we restate that result as a computation refinement. *)\nTheorem listMax_refines : forall ls,\n  refine {upper | forall n, In n ls -> upper >= n} (ret (listMax ls)).\nProof.\n  refines.\n  apply listMax_upperBound.\nQed.\n\n(* An easy way to find a number higher than another: add 1! *)\nTheorem increment_refines : forall n,\n  refine {higher | higher > n} (ret (n + 1)).\nProof.\n  refines.\n  arithmetic.\nQed.\n\n(* Let's derive an efficient implementation. *)\nTheorem implementation : { f : list nat -> Comp nat | forall ls, refine (notInList ls) (f ls) }.\nProof.\n  begin.\n  rewrite notInList_decompose.\n  rewrite listMax_refines.\n  setoid_rewrite increment_refines. (* Different tactic here to let us rewrite under a binder! *)\n  monad_simpl.\n  finish honing.\nDefined.\n\n(* We can extract the program that we found as a standlone, executable Gallina term. *)\nDefinition impl := Eval simpl in projT1 implementation.\nPrint impl.\n\nEval compute in impl (1 :: 7 :: 8 :: 2 :: 13 :: 6 :: nil).\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Examples/Tutorial/NotInList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.7853085834000791, "lm_q1q2_score": 0.7114815784334549}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_congruenceflip.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_extensionunique.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_rightreverse : \n   forall A B C D, \n   Per A B C -> BetS A B D -> Cong A B B D ->\n   Cong A C D C.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists E, (BetS A B E /\\ Cong A B E B /\\ Cong A C E C /\\ neq B C)) by (conclude_def Per );destruct Tf as [E];spliter.\nassert (Cong B D A B) by (conclude lemma_congruencesymmetric).\nassert (Cong B D E B) by (conclude lemma_congruencetransitive).\nassert (Cong B D B E) by (forward_using lemma_congruenceflip).\nassert (eq D E) by (conclude lemma_extensionunique).\nassert (Cong A C D C) by (conclude cn_equalitysub).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_rightreverse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7114395521782476}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj54_coqofml_TzZDDO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7114395335714265}}
{"text": "\nClass Category : Type := {\n  obj : Type;\n  hom : obj -> obj -> Type;\n\n  id : forall {a : obj}, hom a a;\n  compose : forall {a b c : obj}, hom b c -> hom a b -> hom a c;\n\n  compose_assoc :\n    forall {a b c d : obj} (f : hom c d) (g : hom b c) (h : hom a b),\n    compose f (compose g h) = compose (compose f g) h;\n\n  id_unit_left :\n    forall {a b : obj} (f : hom a b),\n    compose id f = f;\n\n  id_unit_right :\n    forall {a b : obj} (f : hom a b),\n    compose f id = f;\n}.\n\n#[refine] Instance TypeCategory : Category := {\n  obj := Type;\n  hom := fun a b => a -> b;\n  id := fun a => fun x : a => x;\n  compose := fun a b c => fun (f : b -> c) (g : a -> b) (x : a) => f (g x);\n}.\nProof. trivial. trivial. trivial. Qed.\n\nRequire Import Coq.Classes.RelationClasses.\n\nProgram Instance EqualityCategory : Category := {\n  obj := Type;\n  hom := fun a b => a = b;\n  id := @eq_refl Type;\n  compose := fun (a b c : Type) (f : b = c) (g : a = b) => eq_trans g f;\n}.\n", "meta": {"author": "Skyb0rg007", "repo": "CategoryTheoryForCoqProgrammers", "sha": "48ecf17667f697c3eabad2836fc5ce0b05d1002d", "save_path": "github-repos/coq/Skyb0rg007-CategoryTheoryForCoqProgrammers", "path": "github-repos/coq/Skyb0rg007-CategoryTheoryForCoqProgrammers/CategoryTheoryForCoqProgrammers-48ecf17667f697c3eabad2836fc5ce0b05d1002d/src/Common/Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7114337582120531}}
{"text": "(** * BagPerm:  Insertion Sort With Bags *)\n\n(** We have seen how to specify algorithms on \"collections\", such as\n    sorting algorithms, using [Permutation]s.  Instead of using\n    permutations, another way to specify these algorithms is to use\n    _bags_ (also called _multisets_), which we introduced in [Lists].\n    A _set_ of values is like a list with no repeats where\n    the order does not matter.  A _multiset_ is like a list, possibly\n    with repeats, where the order does not matter.  Whereas the principal\n    query on a set is whether a given element appears in it, the\n    principal query on a bag is _how many_ times a given element appears \n    in it. *)\n\nFrom Coq Require Import Strings.String. (* for manual grading *)\nFrom Coq Require Import Setoid Morphisms.\nFrom VFA Require Import Perm.\nFrom VFA Require Import Sort.\n\n(** To keep this chapter more self-contained, \nwe restate the critical definitions from [Lists].  *)\nDefinition bag := list nat.\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => 0\n  | h :: t =>\n      (if h =? v then 1 else 0) + count v t\n  end.\n\n(** We will say two bags are _equivalent_ if they have the same number\n    of copies of every possible element. *)\n\nDefinition bag_eqv (b1 b2: bag) : Prop :=\n  forall n, count n b1 = count n b2. \n\n(** **** Exercise: 2 stars, standard (bag_eqv_properties) *)\n\n(* It is easy to prove [bag_eqv] is an equivalence relation. *)\n\nLemma bag_eqv_refl : forall b, bag_eqv b b.\nProof.\n  unfold bag_eqv. intros. reflexivity.\nQed.\n\nLemma bag_eqv_sym: forall b1 b2, bag_eqv b1 b2 -> bag_eqv b2 b1. \nProof.\n  unfold bag_eqv. intros.\n  specialize H with n.\n  symmetry.\n  assumption.\nQed.\n\nLemma bag_eqv_trans: forall b1 b2 b3,\n  bag_eqv b1 b2 -> bag_eqv b2 b3 -> bag_eqv b1 b3.\nProof.\n  unfold bag_eqv. intros.\n  specialize H with n.\n  specialize H0 with n.\n  transitivity (count n b2);\n  assumption.\nQed.\n\n(** The following little lemma is handy in a couple of places. *)\n\nLemma bag_eqv_cons : forall x b1 b2,\n  bag_eqv b1 b2 -> bag_eqv (x::b1) (x::b2).\nProof.\n  unfold bag_eqv. intros.\n  specialize H with n.\n  simpl. rewrite H.\n  reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Correctness *)\n\n(** A sorting algorithm must rearrange the elements into a list that\n    is totally ordered.  But let's say that a different way: the\n    algorithm must produce a list _with the same multiset of values_,\n    and this list must be totally ordered. *)\n\nDefinition is_a_sorting_algorithm' (f: list nat -> list nat) :=\n  forall al, bag_eqv al (f al) /\\ sorted (f al).\n\n(** **** Exercise: 3 stars, standard (insert_bag)\n\n    First, prove the auxiliary lemma [insert_bag], which will be\n    useful for proving [sort_bag] below.  Your proof will be by\n    induction.  *)\n\nLemma insert_bag: forall x l, bag_eqv (x::l) (insert x l).\nProof.\n  intros. induction l.\n  (* nil *) simpl. apply bag_eqv_refl.\n  (* l = a :: l *)\n  simpl.\n  bdestruct (a >=? x).\n  (* a >= x *) apply bag_eqv_refl.\n  (* a < x *)\n  assert (H0: bag_eqv (a :: x :: l) (a :: insert x l))\n    by (apply bag_eqv_cons; assumption).\n  apply bag_eqv_trans with (b2 := a :: x :: l).\n  unfold bag_eqv. intro. simpl. lia.\n  assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (sort_bag)\n\n    Now prove that sort preserves bag contents. *)\nTheorem sort_bag: forall l, bag_eqv l (sort l).\nProof.\n  intro. induction l. unfold bag_eqv. reflexivity.\n  simpl.\n  assert (H1: bag_eqv (a :: (sort l)) (insert a (sort l)))\n    by apply insert_bag.\n  apply bag_eqv_trans with (b2 := a :: (sort l));\n  try apply bag_eqv_cons; assumption.\nQed.\n\n(** [] *)\n\n(** Now we wrap it all up.  *)\n\nTheorem insertion_sort_correct:\n  is_a_sorting_algorithm' sort.\nProof.\n  split. apply sort_bag. apply sort_sorted.\nQed.\n\n(** **** Exercise: 1 star, standard (permutations_vs_multiset)\n\n    Compare your proofs of [insert_perm, sort_perm] with your proofs\n    of [insert_bag, sort_bag].  Which proofs are simpler?\n\n      - [ ] easier with permutations,\n      - [ ] easier with multisets\n      - [ ] about the same.\n\n   Regardless of \"difficulty\", which do you prefer / find easier to\n   think about?\n      - [ ] permutations or\n      - [ ] multisets\n\n   Put an X in one box in each list. *)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_permutations_vs_multiset : option (nat*string) := None.\n(** [] *)\n\n(* ################################################################# *)\n(** * Permutations and Multisets *)\n\n(** The two specifications of insertion sort are equivalent.  One\n    reason is that permutations and multisets are closely related.\n    We're going to prove:\n\n       [Permutation al bl <-> bag_eqv al bl.] *)\n\n(** **** Exercise: 3 stars, standard (perm_bag)\n\n    The forward direction is straighforward, by induction on the evidence for\n    [Permutation]: *)\nLemma perm_bag:\n  forall al bl : list nat,\n   Permutation al bl -> bag_eqv al bl. \nProof.\n  intros. induction H.\n  - (* nil *) apply bag_eqv_refl.\n  - (* skip *) apply bag_eqv_cons. assumption.\n  - (* swap *)\n    unfold bag_eqv. intro. simpl.\n    destruct (y =? n); destruct (x =? n); reflexivity.\n  - (* trans *) apply bag_eqv_trans with (b2 := l'); assumption.\nQed.\n(** [] *)\n\n(** The other direction,\n    [bag_eqv al bl -> Permutation al bl],\n    is surprisingly difficult.  \n    This proof approach is due to Zhong Sheng Hu.\n    The first three lemmas are used to prove the fourth one. *)\n\n(** **** Exercise: 2 stars, advanced (bag_nil_inv) *)\nLemma bag_nil_inv : forall b, bag_eqv [] b -> b = []. \nProof.\n  unfold bag_eqv. intros. induction b.\n  reflexivity.\n  specialize H with a.\n  simpl in H.\n  rewrite Nat.eqb_refl in H.\n  inversion H.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_cons_inv) *)\nLemma bag_cons_inv : forall l x n,\n    S n = count x l ->\n    exists l1 l2,\n      l = l1 ++ x :: l2\n      /\\ count x (l1 ++ l2) = n.\nProof.\n  intros. induction l.\n  - (* nil - contradiction *) inv H.\n  - (* a :: l *)\n    destruct (a =? x) eqn:E; simpl in H.\n    + (* a = x *)\n      rewrite E in H.\n      inv H.\n      exists [], l.\n      apply beq_nat_true in E.\n      subst.\n      auto.\n    + (* a <> x *)\n      rewrite E in H.\n      simpl in H.\n      apply IHl in H as [l1 [l2 [Hl Hc]]].\n      subst.\n      exists (a :: l1), l2.\n      simpl. rewrite E.\n      auto.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (count_insert_other) *)\nLemma count_insert_other : forall l1 l2 x y,\n  y <> x -> count y (l1 ++ x :: l2) = count y (l1 ++ l2).\nProof.\n  intro. induction l1; intros.\n  - (* l1 = nil *)\n    apply Nat.neq_sym in H.\n    apply Nat.eqb_neq in H.\n    simpl.\n    rewrite H.\n    auto.\n  - (* l1 = a :: l1 *)\n    bdestruct (a =? y).\n    + subst.\n      apply (IHl1 l2 x y) in H.\n      simpl.\n      rewrite Nat.eqb_refl.\n      auto.\n    + apply Nat.eqb_neq in H0.\n      simpl.\n      rewrite H0.\n      simpl.\n      apply (IHl1 l2 x y) in H.\n      assumption.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (bag_perm) *)\nLemma bag_perm:\n  forall al bl, bag_eqv al bl -> Permutation al bl.\nProof.\n  intro.\n  induction al.\n  - intros.\n    apply bag_nil_inv in H.\n    subst.\n    constructor.\n  - intros. induction bl as [| b bl].\n    + apply bag_eqv_sym in H.\n      apply bag_nil_inv in H.\n      discriminate.\n    + bdestruct (a =? b).\n      * subst.\n        assert (H0: bag_eqv al bl). {\n          unfold bag_eqv. intro.\n          unfold bag_eqv in H.\n          specialize H with n.\n          simpl in H.\n          bdestruct (b =? n);\n          subst; inv H;\n          reflexivity.\n        }\n        apply IHal in H0.\n        constructor.\n        assumption.\n      * assert (exists l1 l2, al = l1 ++ b :: l2 /\\ count b (l1 ++ l2) = count b bl)\n         as [al1 [al2 [Ha Hcb]]].\n       {\n        assert (S (count b bl) = count b al) as Ha. {\n          unfold bag_eqv in H.\n          specialize H with b.\n          simpl in H.\n          rewrite Nat.eqb_refl in H.\n          apply Nat.eqb_neq in H0 as H1.\n          rewrite H1 in H.\n          simpl in H.\n          auto.\n                 }\n        apply bag_cons_inv in Ha.\n        assumption.\n          }\n\n       assert (exists l1 l2, bl = l1 ++ a :: l2 /\\ count a (l1 ++ l2) = count a al)\n         as [bl1 [bl2 [Hb Hca]]].\n       {\n        assert (S (count a al) = count a bl) as Hb. {\n          unfold bag_eqv in H.\n          specialize H with a.\n          simpl in H.\n          rewrite Nat.eqb_refl in H.\n          apply Nat.neq_sym in H0.\n          apply Nat.eqb_neq in H0 as H2.\n          rewrite H2 in H.\n          simpl in H.\n          auto.\n        }\n        apply bag_cons_inv in Hb.\n        assumption.\n                    }\n\n       assert (forall n, n <> b -> n <> a -> count n al = count n bl) as Hcab.\n       {\n         unfold bag_eqv in H.\n         intros.\n         specialize H with n.\n         simpl in H.\n         bdestruct (b =? n);\n         bdestruct (a =? n);\n         subst;\n         try contradiction.\n         (* b <> a <> n *)\n         simpl in H.\n         assumption.\n       }\n\n       subst.\n\n       assert (count a (al1 ++ al2) = count a (bl1 ++ bl2)). {\n         apply (count_insert_other al1 al2) in H0.\n         rewrite H0 in Hca.\n         symmetry. assumption.\n       }\n\n       assert (count b (al1 ++ al2) = count b (bl1 ++ bl2)). {\n         apply not_eq_sym in H0.\n         apply (count_insert_other bl1 bl2) in H0.\n         rewrite H0 in Hcb.\n         assumption.\n       }\n\n\n\n       (*\n       do 2 rewrite app_comm_cons.\n       apply Permutation_app.\n       *)\n\n\n\nAdmitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * The Main Theorem: Equivalence of Multisets and Permutations *)\nTheorem bag_eqv_iff_perm:\n  forall al bl, bag_eqv al bl <-> Permutation al bl.\nProof.\n  intros. split. apply bag_perm. apply perm_bag.\nQed.\n\n(** Therefore, it doesn't matter whether you prove your sorting\n    algorithm using the Permutations method or the multiset method. *)\n\nCorollary sort_specifications_equivalent:\n    forall sort, is_a_sorting_algorithm sort <->  is_a_sorting_algorithm' sort.\nProof.\n  unfold is_a_sorting_algorithm, is_a_sorting_algorithm'.\n  split; intros;\n  destruct (H al); split; auto;\n  apply bag_eqv_iff_perm; auto.\nQed.\n\n(** $Date$ *)\n\n(* 2021-08-11 15:15 *)\n", "meta": {"author": "luisholanda", "repo": "software-foundations", "sha": "a9c5d7ddb3dca0465dee4ca8519b5de971e482de", "save_path": "github-repos/coq/luisholanda-software-foundations", "path": "github-repos/coq/luisholanda-software-foundations/software-foundations-a9c5d7ddb3dca0465dee4ca8519b5de971e482de/Volume3/BagPerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.8652240860523327, "lm_q1q2_score": 0.7113778465574505}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Annexes.suma.\nRequire Import GeoCoq.Tarski_dev.Ch12_parallel.\n\nSection weak_tarski_s_parallel_postulate_weak_inverse_projection_postulate.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\n(** Formalization of a proof from Bachmann's article \"Zur Parallelenfrage\" *)\n\nLemma  weak_tarski_s_parallel_postulate__weak_inverse_projection_postulate_aux :\n  weak_tarski_s_parallel_postulate ->\n  forall A B C P T,\n    Per A B C -> InAngle T A B C ->\n    P <> T -> CongA P B A P B C -> Per B P T -> Coplanar A B C P ->\n    (exists X, Out B A X /\\ Col T P X) \\/ (exists Y, Out B C Y /\\ Col T P Y).\nProof.\n  intros tora A B C P T HPer HInAngle HPT HCongA HPerP HCop.\n\n  assert (HIn : InAngle P A B C)\n    by (apply conga_cop_inangle_per2__inangle with T; assumption).\n  assert (HAcute : Acute P B A)\n    by (apply acute_sym, conga_inangle_per__acute with C; assumption).\n  assert (HAcute' : Acute P B C) by (apply (acute_conga__acute P B A); assumption).\n  assert_diffs.\n  assert (HPerp : Perp B P P T) by (apply per_perp; auto).\n  assert (HNCol : ~ Col A B C) by (apply per_not_col; auto).\n  assert (HNCol1 : ~ Col B P T) by (apply per_not_col; auto).\n  destruct (col_dec A B T).\n    left; exists T; split; Col.\n    apply l6_6, acute_col_perp__out_1 with P; Col.\n  destruct (tora A B C T) as [U [V [HU [HV HUTV]]]]; trivial.\n  destruct (col_dec P T U) as [HCol|HNCol2].\n    left; exists U; split; Col.\n  destruct (col_dec P T V) as [HCol|HNCol3].\n    right; exists V; split; Col.\n  destruct (cop__one_or_two_sides P T B U) as [HTS|HOS]; Col.\n\n    {\n    assert (Coplanar A B C P) by Cop.\n    assert (Coplanar A B C T) by Cop.\n    assert (Coplanar A B U C) by (apply col__coplanar; assert_cols; Col).\n    CopR.\n    }\n    destruct HTS as [_ [_ [X [HX1 HX2]]]].\n    left; exists X; split; Col.\n    apply l6_7 with U; auto.\n    assert_diffs; apply l6_6, bet_out; auto.\n    intro; subst; apply HNCol1, HX1.\n  assert (HTS : TS P T B V).\n    apply l9_8_2 with U; Side.\n    repeat split; Col.\n    exists T; repeat split; Col.\n  destruct HTS as [_ [_ [Y [HY1 HY2]]]].\n  right; exists Y; split; Col.\n  apply l6_7 with V; auto.\n  assert_diffs; apply l6_6, bet_out; auto.\n  intro; subst; apply HNCol1, HY1.\nQed.\n\nLemma weak_tarski_s_parallel_postulate__weak_inverse_projection_postulate :\n  weak_tarski_s_parallel_postulate -> weak_inverse_projection_postulate.\nProof.\nintro wtpp.\ncut (forall A B C P T,\n       Per A B C -> InAngle T A B C ->\n       P <> T -> CongA P B A P B C -> Coplanar A B C P -> Per B P T ->\n       exists X Y, Out B A X /\\ Col T P X /\\ Out B C Y /\\ Col T P Y).\n\n  {\n  intros rabp A B C D E F P Q HAcute HPerE HSuma HOut HPQ HPerP HCop.\n  assert (HNCol1 : ~ Col A B C).\n    intro; suma.assert_diffs; apply (per_not_col D E F); auto.\n    apply (col2_suma__col A B C A B C); assumption.\n  assert (HNCol2 : ~ Col B P Q) by (assert_diffs; apply per_not_col; auto).\n  assert (HCongA : CongA A B C P B C).\n    assert_diffs; apply out_conga with A C A C; try (apply out_trivial); CongA.\n  assert (HNCol3 : ~ Col P B C) by (apply (ncol_conga_ncol A B C); assumption).\n  assert (HPerp : Perp B P P Q) by (apply per_perp; assert_diffs; auto).\n  apply suma_left_comm in HSuma.\n  destruct HSuma as [J [HJ1 [HJ2 [HJ3 HJ4]]]].\n  assert (HQ' : exists Q', P <> Q' /\\ Col P Q Q' /\\ InAngle Q' C B P).\n  { destruct (cop_not_par_same_side B P Q P P C) as [Q0 [HCol HOS]]; Col.\n\n      {\n      assert (Coplanar A B P C) by Cop.\n      CopR.\n      }\n\n    destruct (one_side_dec B C P Q0).\n      exists Q0; assert_diffs; split; auto; split; Col.\n      apply os2__inangle; assumption.\n    assert (HQ' : exists Q', Col P Q Q' /\\ Col B C Q').\n    { destruct (col_dec B C Q0).\n        exists Q0; Col.\n      assert_diffs.\n      destruct (cop__not_one_side_two_sides B C P Q0) as [_ [_ [Q' [HCol' HBet]]]]; Col; Cop.\n      exists Q'; split; ColR.\n    }\n    destruct HQ' as [Q' [HCol1 HCol2]].\n    exists Q'.\n    assert (P <> Q') by (intro; subst; apply HNCol3; Col).\n    split; auto; split; Col.\n    apply out321__inangle; auto.\n      assert_diffs; auto.\n    apply l6_6, (acute_col_perp__out_1 P); Col.\n      apply (acute_conga__acute A B C); assumption.\n    apply perp_col1 with Q; auto.\n  }\n  destruct HQ' as [Q' [HPQ' [HCol HInangle]]].\n  assert (HInangle' : InAngle Q' C B J).\n  { apply in_angle_trans with P; trivial.\n    apply l11_25 with A C J; try (apply out_trivial; assert_diffs; auto); [|apply l6_6; assumption].\n    apply os_ts__inangle.\n      assert (~ Col A B J) by (apply (ncol_conga_ncol A B C); CongA).\n      assert_diffs; apply cop__not_one_side_two_sides; Col; Cop.\n    assert (~ Col C B J).\n      apply (ncol_conga_ncol D E F); CongA; assert_diffs; apply per_not_col; auto.\n    apply invert_one_side, one_side_symmetry, cop__not_two_sides_one_side; Col.\n      assert_diffs; auto.\n    apply conga_sams_nos__nts with A B C; SumA.\n  }\n  destruct (rabp C B J P Q') as [Y [_ [HY1 [HY2 _]]]]; trivial.\n    apply (l11_17 D E F); CongA.\n    assert_diffs; apply out_conga with A C A J; try (apply out_trivial); CongA.\n    assert (Coplanar A B P C) by Cop.\n    CopR.\n    apply per_col with Q; auto.\n  exists Y; split; ColR.\n  }\n\n  {\n  intros A B C P T HPer HInAngle HPT HCongA HCop HPerP.\n  assert (HNOut : ~ Out B A C) by (intro; assert_diffs; apply (per_not_col A B C); Col).\n  assert (HPerp : Perp B P P T) by (assert_diffs; apply per_perp; auto).\n  destruct (weak_tarski_s_parallel_postulate__weak_inverse_projection_postulate_aux wtpp A B C P T) as [[X [HX1 HX2]]|[Y [HY1 HY2]]]; trivial.\n  - destruct (symmetric_point_construction X P) as [Y HY].\n    assert (X <> Y).\n    { intro; treat_equalities.\n      apply HNOut, l6_7 with P; trivial.\n      apply (l11_21_a P B A); trivial.\n      apply l6_6, HX1.\n    }\n    assert (Out B C Y).\n    { apply conga_cop_out_reflectl__out with A P X; trivial.\n      apply l10_4_spec; split.\n        exists P; Col.\n      left; apply perp_col2_bis with P T; ColR.\n    }\n    exists X, Y; repeat (split; try ColR).\n  - destruct (symmetric_point_construction Y P) as [X HX].\n    assert (X <> Y).\n    { intro; treat_equalities.\n      apply HNOut, l6_7 with P; apply l6_6; trivial.\n      apply (l11_21_a P B C); CongA.\n      apply l6_6, HY1.\n    }\n    assert (Out B A X).\n    { apply conga_cop_out_reflectl__out with C P Y; CongA; Cop.\n        intro HOut; apply HNOut, l6_6, HOut.\n      apply l10_4_spec; split.\n        exists P; Col.\n      left; apply perp_col2_bis with P T; try ColR.\n    }\n    exists X, Y; repeat (split; try ColR).\n  }\nQed.\n\nEnd weak_tarski_s_parallel_postulate_weak_inverse_projection_postulate.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Meta_theory/Parallel_postulates/weak_tarski_s_parallel_postulate_weak_inverse_projection_postulate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8221891305219503, "lm_q1q2_score": 0.7113778447327072}}
{"text": "From Coq Require Import Arith.\nFrom Coq Require Import List.\nFrom StructTact Require Import StructTactics.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nLemma leb_false_lt : forall m n, leb m n = false -> n < m.\nProof.\n  induction m; intros.\n  - discriminate.\n  - simpl in *. break_match; subst; auto with arith.\nQed.\n\nLemma leb_true_le : forall m n, leb m n = true -> m <= n.\nProof.\n  induction m; intros.\n  - auto with arith.\n  - simpl in *. break_match; subst; auto with arith.\n    discriminate.\nQed.\n\nLemma ltb_false_le : forall m n, m <? n = false -> n <= m.\nProof.\n  induction m; intros; destruct n; try discriminate; auto with arith.\nQed.\n\nLemma ltb_true_lt : forall m n, m <? n = true -> m < n.\n  induction m; intros; destruct n; try discriminate; auto with arith.\nQed.\n\nLtac do_bool :=\n  repeat match goal with\n    | [ H : Nat.eqb _ _ = true |- _ ] => apply Nat.eqb_eq in H\n    | [ H : Nat.eqb _ _ = false |- _ ] => apply Nat.eqb_neq in H\n    | [ H : andb _ _ = true |- _ ] => apply Bool.andb_true_iff in H\n    | [ H : andb _ _ = false |- _ ] => apply Bool.andb_false_iff in H\n    | [ H : orb _ _ = true |- _ ] => apply Bool.orb_prop in H\n    | [ H : negb _ = true |- _ ] => apply Bool.negb_true_iff in H\n    | [ H : negb _ = false |- _ ] => apply Bool.negb_false_iff in H\n    | [ H : PeanoNat.Nat.ltb _ _ = true |- _ ] => apply ltb_true_lt in H\n    | [ H : PeanoNat.Nat.ltb _ _ = false |- _ ] => apply ltb_false_le in H\n    | [ H : leb _ _ = true |- _ ] => apply leb_true_le in H\n    | [ H : leb _ _ = false |- _ ] => apply leb_false_lt in H\n    | [ |- andb _ _ = true ]=> apply Bool.andb_true_iff\n    | [ |- andb _ _ = false ] => apply Bool.andb_false_iff\n    | [ |- leb _ _ = true ] => apply leb_correct\n    | [ |-  _ <> false ] => apply Bool.not_false_iff_true\n    | [ |- Nat.eqb _ _ = false ] => apply Nat.eqb_neq\n    | [ |- Nat.eqb _ _ = true ] => apply Nat.eqb_eq\n  end.\n\nDefinition null {A : Type} (xs : list A) : bool :=\n  match xs with\n    | [] => true\n    | _ => false\n  end.\n\nLemma null_sound :\n  forall A (l : list A),\n    null l = true -> l = [].\nProof.\n  destruct l; simpl in *; auto; discriminate.\nQed.\n\nLemma null_false_neq_nil :\n  forall A (l : list A),\n    null l = false -> l <> [].\nProof.\n  destruct l; simpl in *; auto; discriminate.\nQed.\n", "meta": {"author": "uwplse", "repo": "StructTact", "sha": "2f2ff253be29bb09f36cab96d036419b18a95b00", "save_path": "github-repos/coq/uwplse-StructTact", "path": "github-repos/coq/uwplse-StructTact/StructTact-2f2ff253be29bb09f36cab96d036419b18a95b00/theories/BoolUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7113347282713285}}
{"text": "(**\n<<\n  [1] Pottier, Francois. loop (Dec 11, 2014), fpottier. \n         https://github.com/fpottier/loop\n \n>>\n*)\n\n\n\n  Require Import homo.MyLib.\n  Require Import homo.FoldLib.\n  Require Import Recdef.\n  \n  Definition g (s: nat * nat) : option (nat * nat) := \n    let (n, m) := s in\n    match m with \n      | O => None\n      | S m' => Some (n-1, m')\n    end.\n\n  Definition snd_lt (s' s: nat * nat) := (snd s') < (snd s).\n\n  Lemma g_lt: \n    forall s s', \n      g s = Some s' -> snd_lt s' s.\n  Proof. \n    intros.\n    unfold g in H.\n    destruct s as [n m].\n    destruct m as [| m].\n    - inversion H.\n    - inversion H.\n      unfold snd_lt.\n      auto.\n  Defined. \n\n  Require Import Coq.Arith.Wf_nat. \n  Require Import Coq.Wellfounded.Inverse_Image.\n  \n  Lemma snd_lt_wf: well_founded snd_lt.\n  Proof.\n    unfold snd_lt.\n    eapply wf_inverse_image.\n    eapply lt_wf.\n  Defined.\n\n  Definition cr (s: nat * nat) (seed: nat) :=\n    let (n, m) := s in (S n) * seed. \n\n  Infix \"(+)\" := cr (at level 80, right associativity).  \n  \n  Function fact_sep \n             (seed: nat)\n             (s: nat * nat) {wf snd_lt s} : nat:=\n      match (g s) with\n        | None     => seed \n        | Some s' => s' (+) (fact_sep seed s')\n      end. \n  Proof.\n    intros. \n    apply g_lt.\n    exact teq.\n    exact snd_lt_wf.\n  Defined. \n\n  Fixpoint fact (n:nat) :=\n    match n with\n    | O => 1\n    | S n' => n * fact n'\n    end.\n\n  Theorem fact_sep__fact: forall n,\n      fact_sep 1 (n,n) = fact n.\n  Proof. \n    intro n. \n    induction n as [| n]; rewrite fact_sep_equation; auto.\n    simpl.\n    rewrite Nat.sub_0_r.\n    rewrite IHn.\n    reflexivity.\n  Qed.\n  \n\n  (** *** [fact_sep_prog] \n      \n      To run a test for [fact_sep]. \n   *)\n  Fixpoint fact_sep_prog (seed n m: nat) := \n    match m with\n    | O => seed\n    | S m' => n * (fact_sep_prog seed (n-1) m')\n    end.\n\n  Eval compute in (fact_sep_prog 1 5 5).\n  Eval compute in (fact 5).\n    \n  Theorem fact_sep__fact_sep_prog:\n    forall m n seed,\n      n >= m -> \n      fact_sep seed (n,m) = fact_sep_prog seed n m.\n  Proof. \n    intro.\n    induction m; intros;\n      rewrite fact_sep_equation;\n      unfold g; unfold cr. \n    \n    unfold fact_sep_prog. reflexivity.\n    destruct n as [| n]. inversion H.\n    assert(A1: n >= m) by auto with arith. clear H.\n    rewrite IHm.\n    2: omega.\n    simpl.\n    rewrite <- minus_n_O. \n    reflexivity.\n  Qed. \n\n\n  (** ** Splitting \n\n   *)\n  \n  Definition split_nm (n m: nat) :=\n    let m1 := div2 m in\n    let m2 := m - m1 in\n    let n1 := n  in\n    let n2 := n1 - m1 in\n    (n1, m1, n2, m2).\n\n  \n  Definition SplitPred (t1 t2: nat * nat) :=\n    let (n1,m1) := t1 in\n    let (n2,m2) := t2 in\n    n2 = n1 - m1.\n\n  Lemma Associative: \n    forall a b c,\n      cr a (b * c) = cr a b * c.\n  Proof.\n    intros [n m] b c.\n    unfold cr.\n    auto with arith.\n  Qed.\n\n  Lemma Unit:\n    forall (seed : nat), \n      seed = 1 * seed.\n  Proof. \n    auto with arith.\n  Qed. \n\n  Definition scat (s1 s2: nat * nat) := (fst s1, (snd s1) + (snd s2)).\n\n  Lemma Base_Omitted: \n    forall s1 s2, \n      SplitPred s1 s2 -> \n      g s1 = None ->\n      scat s1 s2 = s2.\n  Proof.\n    unfold SplitPred.\n    intros [n1 m1] [n2 m2] Sp * Gs1.\n    unfold scat in *.\n    simpl in *.\n    destruct m1.\n    - rewrite <- minus_n_O in Sp.\n      rewrite plus_0_l.\n      subst n2.\n      reflexivity.\n    - inversion Gs1.\n  Qed.\n\n  Lemma Recursive_Retention_R:\n    forall s1 s2 s : nat * nat,\n      SplitPred s1 s2 ->\n      g s1 = Some s ->\n      g (scat s1 s2) = Some (scat s s2).\n  Proof. \n    intros * H Sp.\n    clear H.\n    unfold SplitPred in Sp.\n    destruct s1 as [n1 m1].\n    destruct s2 as [n2 m2].\n    destruct s as [n1' m1'].\n    unfold scat.\n    simpl.\n    unfold g in Sp.\n    induction m1 as [| m1].\n    inversion Sp.\n    inversion Sp.\n    subst n1' m1'.\n    simpl.\n    reflexivity.\n  Qed. \n\n  Lemma Recursive_Retension_L:\n    forall s1 s2: nat * nat,\n      SplitPred s1 s2 ->\n    forall s : nat * nat,\n      g s1 = Some s -> SplitPred s s2. \n  Proof. \n    intros [n1 m1] [n2 m2] Sp [n3 m3] Gs1.\n    unfold SplitPred; unfold scat in *.\n    simpl in *.\n    destruct m1; inversion Gs1.\n    injection Gs1. intros M1 N3.\n    subst m3.\n    omega. \n  Qed.\n  \n  Lemma Head_Access:\n   forall (s1 s2 : nat * nat),\n     SplitPred s1 s2 ->\n     forall (b : nat),\n     cr (scat s1 s2) b = cr s1 b.\n  Proof.\n    intros [n1 m1] [n2 m2] * Sp.\n    clear Sp.\n    unfold scat in *.\n    simpl in *.\n    reflexivity.\n  Qed.\n\n  \n  Lemma fact_sep_homomorphism: \n    forall t1 t2, \n      SplitPred t1 t2 -> \n      fact_sep 1 (scat t1 t2) = \n      (fact_sep 1 t1) * (fact_sep 1 t2).\n  Proof.\n    Unset Ltac Debug.\n    linU_homomorphism_tac\n      fact_sep_equation\n      Base_Omitted\n      Recursive_Retention_R\n      Head_Access\n      Recursive_Retension_L\n      Unit\n      Associative\n    .     \n  Qed. \n\n  Lemma Head_Access':\n   forall (s1 s2 : nat * nat),\n     SplitPred s1 s2 ->\n     forall (b : nat),\n       cr (scat s1 s2) b = cr s1 b.\n  Proof.\n    intros [n1 m1] [n2 m2] * Sp. \n    unfold scat in *.\n    simpl in *.\n    reflexivity.\n  Qed.\n\n\n\n  Function fact_homo (t: nat * nat) {wf snd_lt t} :=\n    match t with\n      | (n, m) => \n    match m with\n    | O => 1\n    | S O => n \n    | S m' => match split_nm n m with\n              | (n1,m1,n2,m2) =>\n                let v1 := (fact_homo (n1, m1)) in\n                let v2 := (fact_homo (n2, m2)) in\n                v1 * v2\n              end\n    end\n    end.\n\n  Proof. \n    - intros.\n      unfold split_nm in teq2.\n      injection teq2; intros.\n      unfold snd_lt. simpl. subst.\n      case (Nat.div2 n0) eqn: H; auto. \n      omega. \n    - intros.\n      unfold split_nm in teq2.\n      injection teq2; intros. \n      unfold snd_lt. simpl. \n      subst.\n      destruct n0; auto with arith.\n    - apply snd_lt_wf.\n  Defined.\n\n  Definition split_nat (n:nat) := \n    let n1 := div2 n in \n    let n2 := n - n1 in\n    (n1, n2).\n\n  Eval compute in (split_nat 10).\n  Eval compute in (split_nat 0).\n\n\n  Function fact_homo_prog (n m: nat) {measure (fun n: nat => n) m } :=\n    match m with\n      | O => 1\n      | S O => n\n      | S m' =>\n          let (m1, m2) := split_nat m in\n          let v1 := (fact_homo_prog n m1) in\n          let v2 := (fact_homo_prog (n-m1) m2) in\n          v1 * v2\n    end.\n  Proof. \n    - intros. \n      unfold split_nat in teq1.\n      inversion teq1.\n      case (Nat.div2 n0) eqn: DivN0; omega. \n    - intros.\n      unfold split_nat in teq1.\n      inversion teq1.\n      destruct n0; auto with arith.\n  Defined.\n\n  \n  Eval compute in (split_nm 3 3).\n  Eval compute in (fact_homo_prog 4 2).\n\n  \n  \n  Theorem fact_sep__fact_homo:\n    forall n m,\n      n >= m -> \n      fact_sep 1 (n, m) = fact_homo (n,m).\n  Proof.\n    \n    intros n m.\n    name_term t (n, m) T. rewrite <- T.\n    generalize dependent T.\n    generalize dependent m.\n    generalize dependent n.\n    \n    functional induction (fact_homo t); intros * T VT;\n      injection T; clear T; intros; subst m n0.    \n    - rewrite fact_sep_equation; auto.\n    - destruct n as [| n]. inversion VT.\n      rewrite fact_sep_equation; simpl.\n      rewrite fact_sep_equation; simpl.\n      rewrite Nat.sub_0_r.\n      auto with arith.\n    - destruct n as [| n]. inversion VT.\n      assert(VT': n >= m') by auto with arith; clear VT; rename VT' into VT.\n      unfold split_nm in e1;\n        apply invertTupleRewriteRev_test4 in e1 as [N1 [M1 [N2 M2]]].\n      assert (A1: n2 >= m2) by omega. \n      assert (A2: n1 >= m1). \n      {\n        subst.\n        apply le_trans with (m:=S m').\n        apply le_div2.\n        auto with arith.\n      }\n      erewrite <- IHn; auto; clear IHn.\n      erewrite <- IHn0; auto; clear IHn0.\n\n      assert (Sp: SplitPred (n1,m1) (n2,m2)) by (unfold SplitPred; omega).\n      apply fact_sep_homomorphism in Sp.\n\n      rewrite <- Sp.\n      unfold scat. simpl.\n      subst n1.\n      assert (A46: S m' = m1 + m2). {\n        assert (m1 <= m').\n        {\n          subst; simpl.\n          destruct m'; trivial.\n          apply le_n_S.\n          apply le_div2.\n        }\n        omega. \n      } \n    rewrite A46.\n    reflexivity.\n\n  Restart.\n    intros n m.\n    name_term t (n, m) T. rewrite <- T.\n    generalize dependent T.\n    generalize dependent m.\n    generalize dependent n.\n    \n    functional induction (fact_homo t); intros * T VT;\n      injection T; clear T; intros; subst m n0.    \n    - rewrite fact_sep_equation; auto.\n    - destruct n as [| n]. inversion VT.\n      rewrite fact_sep_equation; simpl.\n      rewrite fact_sep_equation; simpl.\n      rewrite Nat.sub_0_r.\n      auto with arith.\n    - destruct n as [| n]. inversion VT.\n      assert(VT': n >= m') by auto with arith; clear VT; rename VT' into VT.\n      unfold split_nm in e1;\n        apply invertTupleRewriteRev_test4 in e1 as [N1 [M1 [N2 M2]]].\n      assert (A1: n2 >= m2) by omega. \n      assert (A2: n1 >= m1). \n      {\n        subst.\n        apply le_trans with (m:=S m').\n        apply le_div2.\n        auto with arith.\n      }\n      erewrite <- IHn; auto; clear IHn.\n      erewrite <- IHn0; auto; clear IHn0.\n\n      assert (Sp: SplitPred (n1,m1) (n2,m2)) by (unfold SplitPred; omega).\n      apply fact_sep_homomorphism in Sp.\n\n      rewrite <- Sp.\n      unfold scat. simpl.\n      subst n1.\n      assert (A46: S m' = m1 + m2). {\n        assert (m1 <= m').\n        {\n          subst; simpl.\n          destruct m'; trivial.\n          apply le_n_S.\n          apply le_div2.\n        }\n        omega. \n      } \n    rewrite A46.\n    reflexivity.\n  \n  \n  \n  Qed.\n\n\n  ", "meta": {"author": "yoy553", "repo": "left-homo", "sha": "5f6a65b298b9eb9a3455899c73998bb8898bef04", "save_path": "github-repos/coq/yoy553-left-homo", "path": "github-repos/coq/yoy553-left-homo/left-homo-5f6a65b298b9eb9a3455899c73998bb8898bef04/homo/Fact/Fact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.711315974956792}}
{"text": "(* Copyright 2012-2015 by Adam Petcher.\t\t\t\t*\n * Use of this source code is governed by the license described\t*\n * in the LICENSE file at the root of the source tree.\t\t*)\n\nSet Implicit Arguments.\n\nRequire Import FCF.FCF.\nRequire Import FCF.CompFold.\nRequire Import FCF.RndListElem.\nRequire Import Permutation.\n\nLocal Open Scope list_scope.\n\nTheorem removeFirst_In_length : \n  forall (A : Set)(eqd : EqDec A)(ls : list A)(a : A),\n    In a ls ->\n    length (removeFirst (EqDec_dec _ ) ls a) = pred (length ls).\n  \n  induction ls; intuition; simpl in *.\n  intuition; subst.\n  destruct (EqDec_dec eqd a0 a0); intuition.\n  \n  destruct (EqDec_dec eqd a0 a); subst.\n  trivial.\n  simpl.\n  rewrite IHls.\n  destruct ls; simpl in *; intuition.\n\n  trivial.\nQed.\n\nFixpoint addInAllLocations(A : Type)(a : A)(ls : list A) :=\n  match ls with\n    | nil =>  (a :: nil) :: nil\n    | a' :: ls' => \n      (a :: ls) :: map (fun x => a' :: x) (addInAllLocations a ls')\n  end.\n\nFixpoint getAllPermutations(A : Type)(ls : list A) :=\n  match ls with\n    | nil => nil :: nil\n    | a :: ls' =>\n      let perms' := getAllPermutations ls' in\n        flatten (map (addInAllLocations a) perms')\n  end.\n\nTheorem addInAllLocations_not_nil : \n  forall (A : Type) l (a : A),\n    addInAllLocations a l = nil -> False.\n\n  induction l; intuition; unfold addInAllLocations in *; simpl in *.\n  inversion H.\n  inversion H.\n\nQed.\n\nTheorem getAllPermutations_not_nil : \n  forall (A : Type)(ls : list A),\n    getAllPermutations ls = nil -> False.\n\n  induction ls; intuition; simpl in *.\n  inversion H.\n\n  case_eq (getAllPermutations ls); intuition.\n  rewrite H0 in H.\n  simpl in *.\n  apply app_eq_nil in H.\n  intuition.\n  eapply addInAllLocations_not_nil; eauto.\nQed.\n  \n\nTheorem addInAllLocations_perm : \n  forall (A : Type) x0 (a : A) ls2,\n    In ls2 (addInAllLocations a x0) ->\n    Permutation ls2 (a :: x0).\n\n  induction x0; intuition; simpl in *.\n  intuition; subst.\n  eapply Permutation_refl.\n  \n  intuition; subst.\n  eapply Permutation_refl.\n\n  eapply in_map_iff in H0.\n  destruct H0.\n  intuition; subst.\n  eapply perm_trans.\n  2:{\n    eapply perm_swap.\n  }\n  eapply perm_skip.\n  eapply IHx0.\n  trivial.\n\nQed.\n\nTheorem getAllPermutations_perms : \n  forall (A : Set)(ls1 ls2 : list A),\n    In ls2 (getAllPermutations ls1) ->\n    Permutation ls1 ls2.\n\n  induction ls1; intuition; simpl in *.\n  intuition.\n  subst.\n  econstructor.\n\n  eapply in_flatten in H.\n  destruct H.\n  intuition.\n  eapply in_map_iff in H0.\n  destruct H0.\n  intuition.\n  subst.\n  eapply addInAllLocations_perm in H1.\n  eapply perm_trans.\n  2:{\n    eapply Permutation_sym.\n    eauto.\n  }\n  eapply perm_skip.\n  eapply IHls1.\n  trivial.\n  \nQed.\n\nSection ShuffleList.\n\n  Variable A : Set.\n  Hypothesis A_EqDec : EqDec A.\n\n  Definition shuffle(ls : list A) :=\n    o <-$ rndListElem _ (getAllPermutations ls);\n    ret \n    match o with\n      | None => nil\n      | Some x => x\n    end.\n      \n  Theorem shuffle_perm : \n    forall (ls1 ls2 : list A),\n      In ls2 (getSupport (shuffle ls1)) ->\n      Permutation ls2 ls1.\n\n    intuition.\n    unfold shuffle in *.\n    repeat simp_in_support.\n    destruct x.\n    eapply Permutation_sym.\n    eapply getAllPermutations_perms.    \n    apply rndListElem_support in H0.\n    trivial.\n\n    apply rndListElem_support_None in H0.\n    exfalso.\n    eapply getAllPermutations_not_nil.\n    eauto.\n\n  Qed.\n\n   Fixpoint permute(ls : list A)(sigma : list nat) : list A :=\n    match sigma with\n      | nil => nil\n      | n :: sigma' => \n        match (nth_error ls n) with\n          | None => nil\n          | Some a => a :: (permute ls sigma')\n        end\n  end.\n\n   Theorem nth_error_not_None : \n     forall (ls : list A)(n : nat),\n       n < length ls ->\n       nth_error ls n = None -> \n       False.\n\n     induction ls; destruct n; intuition; simpl in *.\n     lia.\n     lia.\n     inversion H0.\n     eapply IHls; eauto.\n     lia.\n   Qed.\n\n   Theorem permute_length_eq : \n     forall (sigma : list nat)(ls : list A),\n       (forall n, In n sigma -> n < length ls) ->\n       length (permute ls sigma) = length sigma.\n     \n     induction sigma; intuition; simpl in *.\n     case_eq (nth_error ls a); intuition.\n     simpl.\n     f_equal.\n     eapply IHsigma; intuition.\n     \n\n     exfalso.\n     eapply nth_error_not_None.\n     eapply H.\n     intuition.\n     trivial.\n   Qed.\n   \n   Theorem shuffle_Permutation : \n     forall (ls1 ls2 : list A),\n       In ls2 (getSupport (shuffle ls1)) ->\n       Permutation ls1 ls2.\n     \n     intuition.\n\n     unfold shuffle in *.\n     repeat simp_in_support.\n     destruct x.\n     eapply rndListElem_support in H0.\n     eapply getAllPermutations_perms.\n     trivial.\n\n     eapply rndListElem_support_None in H0.\n     exfalso.\n     eapply getAllPermutations_not_nil.\n     eauto.\n\n    Qed.\n  \n    Theorem shuffle_wf : \n      forall ls,\n        well_formed_comp (shuffle ls).\n\n      intuition.\n      unfold shuffle.\n      wftac.\n      eapply rndListElem_wf.\n\n    Qed.\n\nEnd ShuffleList.\n\nDefinition RndPerm(n : nat) :=\n  shuffle _ (allNatsLt n).\n\nTheorem list_pred_map_both':\n  forall (A B C D : Set) (lsa : list A) (lsb : list B) \n    (P : C -> D -> Prop) (f : A -> C)(g : B -> D),\n  list_pred (fun (a : A) (b : B) => P (f a) (g b)) lsa lsb ->\n  list_pred P (map f lsa) (map g lsb).\n\n  intuition.\n  eapply list_pred_impl.\n  eapply list_pred_map_both.\n  eauto.\n  intuition.\n  destruct H0.\n  destruct H0.\n  intuition; subst.\n  trivial.\n\nQed.\n\nTheorem addInAllLocations_pred : \n  forall (A B : Set) (R : A -> B -> Prop) (a : list A) (b : list B),\n    list_pred R a b ->\n    forall a1 a2,\n      R a1 a2 ->\n  list_pred (list_pred R) (addInAllLocations a1 a) (addInAllLocations a2 b).\n  \n  induction 1; intuition; simpl in *.\n  \n  econstructor.\n  econstructor.\n  trivial.\n  econstructor.\n  econstructor.\n  \n\n  econstructor.\n  repeat econstructor;assumption.\n\n  eapply list_pred_map_both'.\n  eapply list_pred_impl.\n  eauto.\n  intuition.\n  econstructor; assumption.\n\nQed.\n\nTheorem getAllPermutations_pred :\n  forall (A B : Set)(R : A -> B -> Prop)(lsa : list A)(lsb : list B),\n  list_pred R lsa lsb ->\n     list_pred (list_pred R) (getAllPermutations lsa) (getAllPermutations lsb).\n\n  induction 1; intuition; simpl in *.\n  econstructor.\n  econstructor.\n  econstructor.\n\n  eapply list_pred_flatten_both.\n  eapply list_pred_map_both'.\n  eapply list_pred_impl.\n  eauto.\n  intuition.\n  \n  eapply addInAllLocations_pred; intuition.\nQed.\n\nTheorem nth_error_app_Some : \n  forall (A : Set)(ls : list A) n (a a' : A),\n    nth_error ls n = Some a ->\n    nth_error (ls ++ (a' :: nil)) n = Some a.\n\n  induction ls; destruct n; intuition; simpl in *.\n  inversion H.\n  inversion H.\n\n  eapply IHls.\n  trivial.\n\nQed.\n\nTheorem nth_error_app_length : \n  forall (A : Set)(ls : list A) (a : A),\n    nth_error (ls ++ (a :: nil)) (length ls) = Some a.\n\n  induction ls; intuition; simpl in *.\n  \nQed.\n\nTheorem allNats_nth_pred : \n  forall (A : Set)(ls : list A),\n   list_pred (fun (a : A) (b : nat) => nth_error ls b = Some a) ls\n     (allNatsLt (length ls)).\n\n  induction ls using rev_ind; intuition; simpl in *.\n  econstructor.\n \n  rewrite app_length.\n  simpl.\n  rewrite plus_comm.\n  simpl.\n\n  eapply list_pred_app_both.\n  eapply list_pred_impl.\n  eapply IHls.\n  intuition.\n\n\n  eapply nth_error_app_Some; intuition.\n\n  econstructor.\n\n\n  eapply  nth_error_app_length .\n\n  econstructor.\n  \nQed.\n\nTheorem permute_nth_equiv : \n  forall (A : Set)(ls : list A) a b,\n  list_pred (fun (a0 : A) (b0 : nat) => nth_error ls b0 = Some a0) a b ->\n  a = permute ls b.\n\n  induction a; inversion 1; intuition; simpl in *.\n  subst.\n  \n  rewrite H2.\n  f_equal.\n  eapply IHa.\n  trivial.\nQed.\n\nTheorem getAllPerms_permute_eq :\n  forall (A : Set)(ls : list A),\n  list_pred (fun (a : list A) (b : list nat) => a = permute ls b)\n     (getAllPermutations ls) (getAllPermutations (allNatsLt (length ls))).\n\n  intuition.\n\n  generalize (@getAllPermutations_pred _ _ (fun a b => nth_error ls b = Some a) ls (allNatsLt (length ls))) ; intros.\n  eapply list_pred_impl.\n  eapply H.\n\n  eapply allNats_nth_pred.\n\n  intuition.\n\n  eapply permute_nth_equiv.\n  trivial.\n  \nQed.\n\nTheorem list_pred_nth_exists : \n  forall (A B : Set)(P : A -> B -> Prop) lsa lsb,\n    list_pred P lsa lsb ->\n    forall n a, \n      nth_option lsa n = Some a -> exists b, nth_option lsb n = Some b /\\ P a b.\n\n  induction 1; intuition; simpl in *.\n  discriminate.\n\n  destruct n.\n  inversion H1; clear H1; subst.\n  econstructor; intuition.\n\n  edestruct IHlist_pred; eauto.\n\nQed.\n\nTheorem rndListElem_pred : \n  forall (A B : Set)(eqda : EqDec A)(eqdb : EqDec B)(P : A -> B -> Prop)(lsa : list A)(lsb : list B),\n    list_pred P lsa lsb ->\n    comp_spec (fun a b => \n      match a with\n        | None => b = None\n        | Some a' => exists b', b = Some b' /\\ P a' b'\n      end) (rndListElem _ lsa) (rndListElem _ lsb).\n\n\n  intuition.\n  unfold rndListElem in *.\n  case_eq (length lsa); intuition.\n  erewrite <- list_pred_length_eq; eauto.\n  rewrite H0.\n  eapply comp_spec_ret; intuition.\n  \n  erewrite <- list_pred_length_eq; eauto.\n  rewrite H0.\n  comp_skip.\n  apply None.\n  apply None.\n  eapply comp_spec_ret; intuition.\n\n  case_eq (nth_option lsa b); intuition.\n\n  edestruct list_pred_nth_exists; eauto.\n\n  exfalso.\n  eapply nth_option_not_None; eauto.\n  apply RndNat_support_lt in H1.\n  lia.\nQed.\n\nTheorem shuffle_RndPerm_spec : \n  forall (A : Set)(eqd : EqDec A)(ls : list A),\n    comp_spec (fun a b => a = permute ls b)\n    (shuffle eqd ls)\n    (shuffle _ (allNatsLt (length ls))).\n\n  intuition.\n  unfold shuffle in *.\n  \n  comp_skip.\n  eapply rndListElem_pred.\n  eapply getAllPerms_permute_eq.\n  \n  simpl in H1.\n  eapply comp_spec_ret; intuition.\n  destruct a.\n  destruct H1.\n  intuition.\n  subst.\n  trivial.\n\n  subst.\n  simpl.\n  intuition.\nQed.\n\nTheorem shuffle_RndPerm_spec_eq : \n  forall (A : Set)(eqd : EqDec A)(ls : list A),\n    comp_spec eq\n    (shuffle eqd ls)\n    (x <-$ RndPerm (length ls); ret permute ls x).\n\n  intuition.\n  eapply comp_spec_eq_trans.\n  eapply comp_spec_eq_symm.\n  eapply comp_spec_right_ident.\n  comp_skip.\n  eapply shuffle_RndPerm_spec.\n  eapply comp_spec_ret; intuition.\n\nQed.\n\nTheorem RndPerm_In_support : \n  forall n ls, \n    In ls (getSupport (RndPerm n)) ->\n    Permutation (allNatsLt n) ls.\n  \n  intuition.\n  eapply shuffle_Permutation.\n  eapply H.\nQed.\n\n\nTheorem RndPerm_In_support_length :\n  forall n ls,\n    In ls (getSupport (RndPerm n)) ->\n    length ls = n.\n\n  intuition.\n  erewrite Permutation_length.\n  2:{\n    eapply Permutation_sym.\n    eapply RndPerm_In_support.\n    eauto.\n  }\n  eapply allNatsLt_length.\nQed.\n\nTheorem RndPerm_wf : \n  forall n,\n    well_formed_comp (RndPerm n).\n\n  intuition.\n  unfold RndPerm.\n  eapply shuffle_wf.\n\nQed.\n", "meta": {"author": "adampetcher", "repo": "fcf", "sha": "10a39a091eb695daba8175cb59bf481dd85d8ce2", "save_path": "github-repos/coq/adampetcher-fcf", "path": "github-repos/coq/adampetcher-fcf/fcf-10a39a091eb695daba8175cb59bf481dd85d8ce2/src/FCF/RndPerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7111764282702435}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_s_cut :\n\tforall A B C D E,\n\tBetS A E B ->\n\tBetS C E D ->\n\tnCol A B C ->\n\tnCol A B D ->\n\tCut A B C D E.\nProof.\n\tintros A B C D E.\n\tintros BetS_A_E_B.\n\tintros BetS_C_E_D.\n\tintros nCol_A_B_C.\n\tintros nCol_A_B_D.\n\n\tunfold Cut.\n\tsplit.\n\texact BetS_A_E_B.\n\tsplit.\n\texact BetS_C_E_D.\n\tsplit.\n\texact nCol_A_B_C.\n\texact nCol_A_B_D.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_s_cut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7111764250849784}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\nRequire Import QArith.\n\nLemma Qopp_lt_compat: forall p q : Q, p < q -> - q < - p.\nProof. hammer_hook \"Qround\" \"Qround.Qopp_lt_compat\".  \nintros (a1,a2) (b1,b2); unfold Qle, Qlt; simpl.\nrewrite !Z.mul_opp_l; omega.\nQed.\n\nHint Resolve Qopp_lt_compat : qarith.\n\n\n\nLocal Coercion inject_Z : Z >-> Q.\n\nDefinition Qfloor (x:Q) := let (n,d) := x in Z.div n (Zpos d).\nDefinition Qceiling (x:Q) := (-(Qfloor (-x)))%Z.\n\nLemma Qfloor_Z : forall z:Z, Qfloor z = z.\nProof. hammer_hook \"Qround\" \"Qround.Qfloor_Z\".  \nintros z.\nsimpl.\nauto with *.\nQed.\n\nLemma Qceiling_Z : forall z:Z, Qceiling z = z.\nProof. hammer_hook \"Qround\" \"Qround.Qceiling_Z\".  \nintros z.\nunfold Qceiling.\nsimpl.\nrewrite Zdiv_1_r.\nauto with *.\nQed.\n\nLemma Qfloor_le : forall x, Qfloor x <= x.\nProof. hammer_hook \"Qround\" \"Qround.Qfloor_le\".  \nintros [n d].\nsimpl.\nunfold Qle.\nsimpl.\nreplace (n*1)%Z with n by ring.\nrewrite Z.mul_comm.\napply Z_mult_div_ge.\nauto with *.\nQed.\n\nHint Resolve Qfloor_le : qarith.\n\nLemma Qle_ceiling : forall x, x <= Qceiling x.\nProof. hammer_hook \"Qround\" \"Qround.Qle_ceiling\".  \nintros x.\napply Qle_trans with (- - x).\nrewrite Qopp_involutive.\nauto with *.\nchange (Qceiling x:Q) with (-(Qfloor(-x))).\nauto with *.\nQed.\n\nHint Resolve Qle_ceiling : qarith.\n\nLemma Qle_floor_ceiling : forall x, Qfloor x <= Qceiling x.\nProof. hammer_hook \"Qround\" \"Qround.Qle_floor_ceiling\".  \neauto with qarith.\nQed.\n\nLemma Qlt_floor : forall x, x < (Qfloor x+1)%Z.\nProof. hammer_hook \"Qround\" \"Qround.Qlt_floor\".  \nintros [n d].\nsimpl.\nunfold Qlt.\nsimpl.\nreplace (n*1)%Z with n by ring.\nring_simplify.\nreplace (n / ' d * ' d + ' d)%Z with\n(('d * (n / 'd) + n mod 'd) + 'd - n mod 'd)%Z by ring.\nrewrite <- Z_div_mod_eq; auto with*.\nrewrite <- Z.lt_add_lt_sub_r.\ndestruct (Z_mod_lt n ('d)); auto with *.\nQed.\n\nHint Resolve Qlt_floor : qarith.\n\nLemma Qceiling_lt : forall x, (Qceiling x-1)%Z < x.\nProof. hammer_hook \"Qround\" \"Qround.Qceiling_lt\".  \nintros x.\nunfold Qceiling.\nreplace (- Qfloor (- x) - 1)%Z with (-(Qfloor (-x) + 1))%Z by ring.\nchange ((- (Qfloor (- x) + 1))%Z:Q) with (-(Qfloor (- x) + 1)%Z).\napply Qlt_le_trans with (- - x); auto with *.\nrewrite Qopp_involutive.\nauto with *.\nQed.\n\nHint Resolve Qceiling_lt : qarith.\n\nLemma Qfloor_resp_le : forall x y, x <= y -> (Qfloor x <= Qfloor y)%Z.\nProof. hammer_hook \"Qround\" \"Qround.Qfloor_resp_le\".  \nintros [xn xd] [yn yd] Hxy.\nunfold Qle in *.\nsimpl in *.\nrewrite <- (Zdiv_mult_cancel_r xn ('xd) ('yd)); auto with *.\nrewrite <- (Zdiv_mult_cancel_r yn ('yd) ('xd)); auto with *.\nrewrite (Z.mul_comm ('yd) ('xd)).\napply Z_div_le; auto with *.\nQed.\n\nHint Resolve Qfloor_resp_le : qarith.\n\nLemma Qceiling_resp_le : forall x y, x <= y -> (Qceiling x <= Qceiling y)%Z.\nProof. hammer_hook \"Qround\" \"Qround.Qceiling_resp_le\".  \nintros x y Hxy.\nunfold Qceiling.\ncut (Qfloor (-y) <= Qfloor (-x))%Z; auto with *.\nQed.\n\nHint Resolve Qceiling_resp_le : qarith.\n\nAdd Morphism Qfloor with signature Qeq ==> eq as Qfloor_comp.\nProof.\nintros x y H.\napply Z.le_antisymm.\nauto with *.\nsymmetry in H; auto with *.\nQed.\n\nAdd Morphism Qceiling with signature Qeq ==> eq as Qceiling_comp.\nProof.\nintros x y H.\napply Z.le_antisymm.\nauto with *.\nsymmetry in H; auto with *.\nQed.\n\nLemma Zdiv_Qdiv (n m: Z): (n / m)%Z = Qfloor (n / m).\nProof. hammer_hook \"Qround\" \"Qround.Zdiv_Qdiv\".  \nunfold Qfloor. intros. simpl.\ndestruct m as [ | | p]; simpl.\nnow rewrite Zdiv_0_r, Z.mul_0_r.\nnow rewrite Z.mul_1_r.\nrewrite <- Z.opp_eq_mul_m1.\nrewrite <- (Z.opp_involutive (Zpos p)).\nnow rewrite Zdiv_opp_opp.\nQed.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/QArith/Qround.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.711176423908135}}
{"text": "Inductive a_tag : Type :=\n  | Tag : nat -> a_tag.\n\nCheck Tag 3.\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_refl : forall x : nat, true = beq_nat x x.\nProof.\n  intros x.\n  induction x.\n  - (* base *) simpl. reflexivity.\n  - (* i.h. *) simpl. rewrite IHx. reflexivity.\nQed.\n\nDefinition beq_tag (a b : a_tag) : bool :=\n  match a, b with\n  | Tag a', Tag b' => beq_nat a' b'\n  end.\n\nCompute eq 1 2.\n\nCompute beq_tag (Tag 2) (Tag 5).\nCompute beq_tag (Tag 5) (Tag 5).\n\nTheorem beq_tag_refl : forall x, true = beq_tag x x.\nProof.\n  intros x.\n  simpl.\n  unfold beq_tag.\n  case x.\n  - (* match b with Tag b' => beq_nat a' b', but a' = b' because of beq_tag x x *)\n  exact beq_refl.\nQed.\n\nInductive partial_map : Type :=\n  | empty : partial_map\n  | record : a_tag -> nat -> partial_map -> partial_map.\n\nDefinition update (d : partial_map)\n                  (x : a_tag) (value : nat)\n                  : partial_map :=\n  record x value d.\n\nDefinition test  := update empty (Tag 1) 2.\nDefinition test' := update test (Tag 3) 4.\nCompute test'.\n\nInductive natoption : Type :=\n  | None : natoption\n  | Some : nat -> natoption.\n\nFixpoint find (x : a_tag) (d : partial_map) : natoption :=\n  match d with\n  | empty         => None\n  | record y v d' => if beq_tag x y\n                     then Some v\n                     else find x d'\n  end.\n\nCompute find (Tag 1) test'.\nCompute find (Tag 2) test'.\nCompute find (Tag 3) test'.\nCompute find (Tag 4) test'.\nCompute find (Tag 5) test'.\n\n\nTheorem update_eq : forall (d : partial_map) (x : a_tag) (v: nat),\n  find x (update d x v) = Some v.\nProof.\n  intros d x v.\n  simpl.\n  rewrite <- beq_tag_refl.\n  reflexivity.\nQed.\n\n\nTheorem update_neq : forall (d : partial_map) (x y : a_tag) (o: nat),\n    beq_tag x y = false -> find x (update d y o) = find x d.\nProof.\n  intros d x y o.\n  intros beq_tag_x_neq_y.\n  simpl.\n  rewrite beq_tag_x_neq_y.\n  reflexivity.\nQed.\n\nInductive baz : Type :=\n  | Baz1 : baz -> baz\n  | Baz2 : baz -> bool -> baz.\n\n(*\nHow many elements does the type baz have?\nSince the inductive definition does not have a base case, we have 0 elements.\nWe can't construct any elements.\n*)\n\n(*\nFound this after my answer:\nhttps://cs.stackexchange.com/questions/29365/baz-num-elts-exercise-from-software-foundations?answertab=votes#tab-top\n\nThere's a bijection between baz and False.\n*)\n\nDefinition injective : forall {t1 t2}, (t1 -> t2) -> Prop := fun t1 t2 f1 => forall x1 x2, f1 x1 = f1 x2 -> x1 = x2.\nDefinition surjective : forall {t1 t2}, (t1 -> t2) -> Prop := fun t1 t2 f1 => forall x1, exists x2, f1 x2 = x1.\nDefinition bijective : forall {t1 t2}, (t1 -> t2) -> Prop := fun t1 t2 f1 => injective f1 /\\ surjective f1.\n\nTheorem baz_False : baz -> False.\nProof.\n  induction 1. exact IHbaz. exact IHbaz.\nQed.\n\nGoal exists f1 : baz -> False, bijective f1.\nProof.\n  exists baz_False. unfold bijective, injective, surjective. firstorder.\n  assert (H2 := baz_False x1). firstorder.\n  assert (H2 := x1). firstorder.\nQed.\n", "meta": {"author": "FengZiGG", "repo": "coqlf", "sha": "73aea6d263b0e05d8e25c5ce1f6609faf8e3956c", "save_path": "github-repos/coq/FengZiGG-coqlf", "path": "github-repos/coq/FengZiGG-coqlf/coqlf-73aea6d263b0e05d8e25c5ce1f6609faf8e3956c/3_Lists/16_partial_maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7111764172944465}}
{"text": "(* Exercise coq_tree_02 *)\n\n(* Let us start with the definition of a binary tree of\n   natural numbers, from the previous exercise *)\n\nInductive nat_tree : Set :=\n  | leaf : nat_tree\n  | node : nat_tree -> nat -> nat_tree -> nat_tree.\n\nPrint plus.\n\n(* Now define the function 'mirror' that return a mirror\n   image of a tree.\n   For instance:\n   \n               a              a\n             /   \\          /   \\\n   mirror(  b     d   ) =  d     b\n   \t     \\    /\\       /\\   /\n\t      c  e  f     f  e c\n*)\n\nFixpoint mirror (T : nat_tree) : nat_tree :=\n  match T return nat_tree with \n  | leaf => leaf \n  | node l n r => node (mirror r) n (mirror l) \n  end.\n  \n(* Now, let us check this function on the example presented \n   above *)\n   \nLemma mirror_ex : forall a b c d e f,\n  mirror (node\n      (node leaf b (node leaf c leaf)) \n      a\n      (node (node leaf e leaf) d (node leaf f leaf))) =\n  node\n    (node (node leaf f leaf) d (node leaf e leaf))\n    a\n    (node (node leaf c leaf) b leaf).\n\nProof.\nintros.\nunfold mirror.\nreflexivity.\nQed.\n", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_tree_02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.711141141444615}}
{"text": "\nRequire Import Nat.\nRequire Import Arith.\n\n\nModule Export LambdaCalc.\n\n\n(* A lambda calculus term using de Bruijn indices. The nat parameter\n   indicates the number of bound variables. *)\nInductive lambda (n : nat) : Set :=\n  | Var : forall (idx : nat), idx < n -> lambda n\n  | Lambda : lambda (S n) -> lambda n\n  | Apply : lambda n -> lambda n -> lambda n.\n\n\nDefinition raiseIndex {n : nat} (l : lambda n) : lambda (S n).\n  induction l.\n  - apply (Var (S n) idx). constructor. exact l.\n  - apply Lambda. exact IHl.\n  - apply Apply.\n    * exact IHl1.\n    * exact IHl2.\nDefined.\n\n\nDefinition addIndex {n : nat} (depth : nat) (l : lambda n) : lambda (S n).\n  induction l.\n  - destruct (ltb idx depth).\n    * apply raiseIndex. exact (Var n idx l).\n    * apply (Var (S n) (S idx)). apply le_n_S. exact l.\n\n  - apply Lambda. exact IHl.\n\n  - apply Apply. exact IHl1. exact IHl2.\nDefined.\n\n\nFixpoint subst' {n : nat} (depth : nat) (ltD : depth <= n)\n  (l : lambda (S n)) (x : lambda n) : lambda n.\n  destruct l.\n\n  - destruct (gt_dec idx depth).\n    * apply (Var n (pred idx)). unfold gt in g. unfold lt in g.\n      destruct idx.\n      -- exfalso. inversion g.\n      -- simpl. apply le_S_n. exact l.\n    * destruct (lt_dec idx depth).\n      -- pose (ltN := le_trans (S idx) depth n l0 ltD).\n         apply (Var n idx). exact ltN.\n      -- exact x.\n\n  - apply Lambda.\n    exact (subst' (S n) (S depth) (le_n_S depth n ltD) l (addIndex 0 x)).\n\n  - apply Apply.\n    exact (subst' n depth ltD l1 x).\n    exact (subst' n depth ltD l2 x).\nDefined.\n\n(* Substitutes x into l for the de Bruijn index 0. *)\nDefinition subst {n : nat} (l : lambda (S n)) (x : lambda n) : lambda n :=\n  subst' 0 (le_0_n n) l x.\n\n\n\n(* A small step evaluation relationship. *)\nReserved Notation \"t1 '/' n '==>' t2\" (at level 40).\nInductive step (n : nat) : lambda n -> lambda n -> Prop :=\n  | LambdaEval : forall (l l' : lambda (S n)), l / (S n) ==> l'\n      -> Lambda n l / n ==> Lambda n l'\n  | ApplyEval1 : forall (l1 l2 l1' : lambda n), l1 / n ==> l1'\n      -> Apply n l1 l2 / n ==> Apply n l1' l2\n  | ApplyEval2 : forall (l1 l2 l2' : lambda n), l2 / n ==> l2'\n      -> Apply n l1 l2 / n ==> Apply n l1 l2'\n  | ApplyFun : forall (l : lambda (S n)) (x : lambda n),\n      (Apply n (Lambda n l) x) / n ==> subst l x\nwhere \"t1 '/' n '==>' t2\" := (step n t1 t2).\n\nReserved Notation \"t1 '/' n '==>*' t2\" (at level 40).\nInductive steps (n : nat) : lambda n -> lambda n -> Prop :=\n  | EvalRefl : forall (l : lambda n), steps n l l\n  | EvalMany : forall (l1 l2 l3 : lambda n), l1 / n ==> l2\n      -> l2 / n ==>* l3 -> l1 / n ==>* l3\nwhere \"t1 '/' n '==>*' t2\" := (steps n t1 t2).\n\n\nTheorem lift_step {n : nat} {l l' : lambda n} (s : l / n ==> l')\n  : l / n ==>* l'.\nProof.\n  apply (EvalMany n l l' l').\n  exact s.\n  exact (EvalRefl n l').\nQed.\n\nTheorem trans_steps {n : nat} {l1 l2 l3 : lambda n} (evs1 : l1 /n ==>* l2)\n  (evs2 : l2 / n ==>* l3) : l1 / n ==>* l3.\nProof.\n  induction evs1.\n  induction evs2.\n\n  - apply EvalRefl.\n\n  - apply (EvalMany n l1 l2 l3). exact H. exact evs2.\n\n  - apply IHevs1 in evs2. apply (EvalMany n l1 l2 l3). exact H. exact evs2.\nQed.\n\nTheorem lift_lambda {n : nat} {l l' : lambda (S n)}\n  (evs : l / (S n) ==>* l') : Lambda n l / n ==>* Lambda n l'.\nProof.\n  induction evs.\n\n  - apply EvalRefl.\n\n  - apply LambdaEval in H.\n    apply (EvalMany n (Lambda n l1) (Lambda n l2) (Lambda n l3)).\n    exact H.\n    exact IHevs.\nQed.\n\n\nTheorem lift_apply {n : nat} {l1 l1' l2 l2' : lambda n}\n  (evs1 : l1 / n ==>* l1') (evs2 : l2 / n ==>* l2')\n  : Apply n l1 l2 / n ==>* Apply n l1' l2'.\nProof.\n  induction evs1.\n  induction evs2.\n\n  - apply EvalRefl.\n\n  - apply (ApplyEval2 n l l1 l2) in H.\n    apply (EvalMany n (Apply n l l1) (Apply n l l2) (Apply n l l3)).\n    exact H.\n    exact IHevs2.\n\n  - assert (Apply n l1 l2 / n ==> Apply n l0 l2).\n    * apply (ApplyEval1 n l1 l2 l0). exact H.\n    * apply (EvalMany n (Apply n l1 l2) (Apply n l0 l2) (Apply n l3 l2')).\n      exact H0.\n      exact IHevs1.\nQed.\n\nEnd LambdaCalc.", "meta": {"author": "lambda-11235", "repo": "lambda-calc-formalization", "sha": "e95fedf3f0280b049f5c4bccf991e1b80ed4b171", "save_path": "github-repos/coq/lambda-11235-lambda-calc-formalization", "path": "github-repos/coq/lambda-11235-lambda-calc-formalization/lambda-calc-formalization-e95fedf3f0280b049f5c4bccf991e1b80ed4b171/src/LambdaCalc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7111411252181123}}
{"text": "Require Export ZArith.\nRequire Export List.\nRequire Export Arith.\nRequire Export Omega.\nRequire Export Zwf.\nRequire Export Relations.\nRequire Export Inverse_Image.\nRequire Export Transitive_Closure.\nRequire Export Zdiv.\n\nOpen Scope nat_scope.\n\nTheorem verif_divide :\n    forall m p:nat, 0 < m -> 0 < p ->\n    (exists q:nat, m = q*p)->(Z_of_nat m mod Z_of_nat p = 0)%Z.\nProof.\n intros m p Hltm Hltp (q, Heq); rewrite Heq.\n rewrite inj_mult.\n replace (Z_of_nat q * Z_of_nat p)%Z with (0 + Z_of_nat q * Z_of_nat p)%Z;\n    try ring.\n rewrite Z_mod_plus; auto.\n omega.\nQed.\n\nTheorem divisor_smaller :\n    forall m p:nat, 0 < m -> forall q:nat, m = q*p -> q <= m.\nProof.\n intros m p Hlt; case p.\n -  intros q Heq; rewrite Heq in Hlt; rewrite mult_comm in Hlt.\n    elim (lt_irrefl 0);exact Hlt.\n -  intros p' q; case q.\n    +  intros Heq; rewrite Heq in Hlt.\n       elim (lt_irrefl 0);exact Hlt.\n    +  intros q' Heq; rewrite Heq.\n       rewrite mult_comm; simpl; auto with arith.\nQed.\n\nFixpoint check_range (v:Z)(r:nat)(sr:Z){struct r} : bool :=\n  match r with\n    O => true\n  | S r' =>\n    match (v mod sr)%Z with\n      Z0 => false\n    | _ => check_range v r' (Zpred sr)\n    end\n  end.\n\nDefinition check_primality (n:nat) :=\n  check_range (Z_of_nat n)(pred (pred n))(Z_of_nat (pred n)).\n\n(** Tests :\n\nCompute check_primality 2333.\n\nCompute check_primality 2330.\n*)\n\n\nFixpoint check_range' (v:Z)(r:nat){struct r} : bool :=\n  match r with\n    0 => true | 1 => true\n  | S r' =>\n      match (v mod Z_of_nat r)%Z with\n      | 0%Z => false\n      | _ => check_range' v r'\n      end\n  end.\n\nDefinition check_primality' (n:nat) :=\n  check_range' (Zpos (P_of_succ_nat (pred n)))(pred (pred n)).\n\nTheorem Zabs_nat_0 : forall x:Z, Zabs_nat x = 0 -> (x = 0)%Z.\nProof.\n intros x; case x.\n -  simpl; auto.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\nQed.\n\nTheorem Z_to_nat_and_back :\n forall x:Z, (0 <= x)%Z -> (Z_of_nat (Zabs_nat x))=x.\nProof.\n intros x; case x.\n -  auto.\n -  intros p Hd; elim p.\n    +  unfold Zabs_nat; intros p' Hrec; rewrite nat_of_P_xI.\n       rewrite inj_S.\n       rewrite inj_mult.\n       rewrite Zpos_xI.\n       unfold Zsucc.\n       rewrite Hrec.\n       simpl; auto.\n    +  unfold Zabs_nat.\n       intros p' Hrec; rewrite nat_of_P_xO.\n       rewrite inj_mult.\n       rewrite Zpos_xO.\n       unfold Zsucc.\n       rewrite Hrec.\n       simpl; auto.\n    +  simpl; auto.\n - intros p' Hd; elim Hd;auto.\nQed.\n\nTheorem check_range_correct :\n  forall (v:Z)(r:nat)(rz:Z),\n  (0 < v)%Z ->\n  Z_of_nat (S r) = rz -> check_range v r rz = true ->\n  ~ (exists k:nat, k <= (S r) /\\ k <> 1 /\\ \n                       (exists q:nat, Zabs_nat v = q*k)).\nProof.\n intros v r; elim r.\n -  intros rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n   +  intros (Hle, (Hne1, (q, Heq))).\n      rewrite mult_comm in Heq; simpl in Heq.\n      rewrite (Zabs_nat_0 _ Heq) in Hlt.\n      elim (Zlt_irrefl 0); assumption.\n   +  intros k' (Hle, (Hne1, (q, Heq))).\n      inversion Hle.\n      assert (H':k'=0).\n      * assumption.\n      * rewrite H' in Hne1; elim Hne1;auto.\n      * assert (H': S k' <= 0) by  assumption.\n        inversion H'.\n-  intros r' Hrec rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n   +  intros (Hle, (Hne1, (q, Heq))).\n      rewrite mult_comm in Heq; simpl in Heq.\n      rewrite (Zabs_nat_0 _ Heq) in Hlt.\n      elim (Zlt_irrefl 0); assumption.\n   +  intros k' (Hle, (Hne1, (q, Heq))).\n      inversion Hle.\n      rewrite <- H1 in H2. \n      rewrite <- (Z_to_nat_and_back v) in H2.\n      assert (Hmod:(Z_of_nat (Zabs_nat v) mod Z_of_nat (S (S r')) = 0)%Z).\n      *  apply verif_divide.\n         replace 0 with (Zabs_nat 0%Z).\n         apply Zabs_nat_lt.\n         omega.\n         simpl; auto.\n         auto with arith.\n         exists q.\n         assert (H': k' = S r') by assumption.\n         rewrite <- H';auto.\n      *   unfold check_range in H2.\n         rewrite Hmod in H2; discriminate H2.\n      *  omega.\n      *  unfold check_range in H2; fold check_range in H2.\n         case_eq ((v mod rz)%Z).\n         intros Heqmod.\n         rewrite Heqmod in H2.\n         discriminate H2.\n         intros pmod Heqmod; rewrite Heqmod in H2.\n         elim (Hrec (Zpred rz) Hlt).\n         rewrite <- H1.\n         rewrite inj_S.\n         rewrite inj_S.\n         rewrite inj_S.\n         rewrite <- Zpred_succ.\n         auto.\n         assumption.\n         exists (S k').\n         repeat split;auto.\n         exists q; assumption.\n         intros p Hmod.\n         elim (Z_mod_lt v rz).\n         rewrite Hmod.\n         unfold Zle; simpl; intros Hle'; elim Hle';auto.\n         rewrite <- H1.\n         rewrite inj_S.\n         unfold Zsucc.\n         generalize (Zle_0_nat (S r')).\n         intros; omega.\nQed.\n\nTheorem nat_of_P_Psucc : \n forall p:positive, nat_of_P (Psucc p) = S (nat_of_P p).\nProof.\n intros p; elim p.\n -  simpl; intros p'; rewrite nat_of_P_xO.\n    intros Heq; rewrite Heq; rewrite nat_of_P_xI; ring.\n - intros p' Heq; simpl.\n   rewrite nat_of_P_xI.\n   rewrite nat_of_P_xO;auto.\n -  auto.\nQed.\n\nTheorem nat_to_Z_and_back:\n forall n:nat, Zabs_nat (Z_of_nat n) = n.\nProof.\n intros n; elim n.\n -  auto.\n - intros n'; simpl; case n'.\n  + simpl; auto.\n  +  intros n''; simpl; rewrite nat_of_P_Psucc.\n     intros Heq; rewrite Heq; auto.\nQed.\n \n\nTheorem check_correct :\n  forall p:nat, 0 < p -> check_primality p = true ->\n  ~(exists k:nat, k <> 1 /\\ k <> p /\\ (exists q:nat, p = q*k)).\nProof.\n unfold lt; intros p Hle; elim Hle.\n -  intros Hcp (k, (Hne1, (Hne1bis, (q, Heq))));\n   rewrite mult_comm in Heq.\n    assert (Hle' : k < 1).\n   +  elim (le_lt_or_eq k 1); try(intuition; fail).\n      apply divisor_smaller with (2:= Heq); auto.\n   + case_eq k.\n     intros Heq'; rewrite Heq' in Heq; simpl in Heq; discriminate Heq.\n     intros; omega.\n -  intros p' Hlep' Hrec; unfold check_primality.\n    assert (H':(exists p'':nat, p' = (S p''))).\n    +  inversion Hlep'.\n       exists 0; auto.\n       eapply ex_intro;eauto.\n    +  elim H'; intros p'' Hp''; rewrite Hp''.\n       repeat rewrite <- pred_Sn.\n       intros Hcr Hex.\n       elim check_range_correct with (3:= Hcr).\n       rewrite inj_S; generalize (Zle_0_nat (S p'')).\n       intros; omega.\n       auto.\n       elim Hex; intros k (Hne1, (HneSSp'', (q, Heq))); exists k.\n       split.\n       assert (HkleSSp'': k <= S (S p'')).\n       * apply (divisor_smaller (S (S p'')) q).\n         auto with arith.\n         rewrite mult_comm.\n         assumption.\n       *  omega.\n       * split.\n         assumption.\n         exists q; now rewrite nat_to_Z_and_back.\nQed.\n\n\nTheorem prime_2333 :\n ~(exists k:nat, k <> 1 /\\ k <> 2333 /\\ (exists q:nat, 2333 = q*k)).\nProof.\n Time apply check_correct; auto with arith.\n(**Finished transaction in 132. secs (131.01u,0.62s)*)\nTime Qed.\n\n\nTheorem reflection_test :\n forall x y z t u:nat, x+(y+z+(t+u)) = x+y+(z+(t+u)).\nProof.\n intros; repeat rewrite plus_assoc; auto.\nQed.\n\nInductive bin : Set := node : bin->bin->bin | leaf : nat->bin.\n\nFixpoint flatten_aux (t fin:bin){struct t} : bin :=\n  match t with\n  | node t1 t2 => flatten_aux t1 (flatten_aux t2 fin)\n  | x => node x fin\n  end.\n\nFixpoint flatten (t:bin) : bin :=\n  match t with\n  | node t1 t2 => flatten_aux t1 (flatten t2)\n  | x => x\n  end.\n\nCompute \n  flatten\n     (node (leaf 1) (node (node (leaf 2)(leaf 3)) (leaf 4))).\n\nFixpoint bin_nat (t:bin) : nat :=\n  match t with\n  | node t1 t2 => bin_nat t1 + bin_nat t2\n  | leaf n => n\n  end.\n\nEval lazy beta iota delta [bin_nat] in\n (bin_nat\n   (node (leaf 1) (node (node (leaf 2) (leaf 3)) (leaf 4)))).\n\nTheorem flatten_aux_valid :\n forall t t':bin, bin_nat t + bin_nat t' = bin_nat (flatten_aux t t').\nProof.\n intros t; elim t; simpl; auto.\n intros t1 IHt1 t2 IHt2 t'; rewrite <- IHt1; rewrite <- IHt2.\n rewrite plus_assoc; trivial.\nQed.\n\nTheorem flatten_valid : forall t:bin, bin_nat t = bin_nat (flatten t).\nProof.\n intros t; elim t; simpl; auto.\n intros t1 IHt1 t2 IHt2; rewrite <- flatten_aux_valid; rewrite <- IHt2.\n trivial.\nQed.\n\nTheorem flatten_valid_2 :\n  forall t t':bin, bin_nat (flatten t) = bin_nat (flatten t')->\n  bin_nat t = bin_nat t'.\nProof.\n intros; rewrite (flatten_valid t); rewrite (flatten_valid t');\n auto.\nQed.\n\nTheorem reflection_test' :\n forall x y z t u:nat, x+(y+z+(t+u))=x+y+(z+(t+u)).\nProof.\n intros.\n change\n   (bin_nat\n      (node (leaf x)\n         (node (node (leaf y) (leaf z))\n               (node (leaf t)(leaf u)))) =\n    bin_nat\n      (node (node (leaf x)(leaf y))\n         (node (leaf z)\n               (node (leaf t)(leaf u))))).\n apply flatten_valid_2; auto.\nQed.\n\nLtac model v :=\n  match v with\n  | (?X1 + ?X2) =>\n    let r1 := model X1 \n              with r2 := model X2 in constr:(node r1 r2)\n  | ?X1 => constr:(leaf X1)\n  end.\n\nLtac assoc_eq_nat :=\n  match goal with\n  | [ |- (?X1 = ?X2 :>nat) ] =>\n   let term1 := model X1 with term2 := model X2 in\n   (change (bin_nat term1 = bin_nat term2);\n    apply flatten_valid_2;\n    lazy beta iota zeta delta [flatten flatten_aux bin_nat]; \n    auto)\n  end.\n\n\nTheorem reflection_test'' :\n forall x y z t u:nat, x+(y+z+(t+u)) = x+y+(z+(t+u)).\nProof.\n intros; assoc_eq_nat.\nQed.\n\nSection assoc_eq.\nVariables (A : Type)(f : A->A->A)\n  (assoc : forall x y z:A, f x (f y z) = f (f x y) z).\n\nFixpoint bin_A (l:list A)(def:A)(t:bin){struct t} : A :=\n  match t with\n  | node t1 t2 => f (bin_A l def t1)(bin_A l def t2)\n  | leaf n => nth n l def\n  end.\n\nTheorem flatten_aux_valid_A :\n forall (l:list A)(def:A)(t t':bin),\n f (bin_A l def t)(bin_A l def t') = bin_A l def (flatten_aux t t').\nProof.\n intros l def t; elim t; simpl; auto.\n intros t1 IHt1 t2 IHt2 t';  rewrite <- IHt1; rewrite <- IHt2.\n symmetry; apply assoc.\nQed.\n\nTheorem flatten_valid_A :\n forall (l:list A)(def:A)(t:bin),\n   bin_A l def t = bin_A l def (flatten t).\nProof.\n intros l def t; elim t; simpl; trivial.\n intros t1 IHt1 t2 IHt2; rewrite <- flatten_aux_valid_A; now rewrite <- IHt2.\nQed.\n\nTheorem flatten_valid_A_2 :\n forall (t t':bin)(l:list A)(def:A),\n   bin_A l def (flatten t) = bin_A l def (flatten t')->\n   bin_A l def t = bin_A l def t'. \nProof.\n intros t t' l def Heq.\n rewrite (flatten_valid_A l def t); now rewrite (flatten_valid_A l def t').\nQed.\n\nEnd assoc_eq.\n\nLtac term_list f l v :=\n  match v with\n  | (f ?X1 ?X2) =>\n    let l1 := term_list f l X2 in term_list f l1 X1\n  | ?X1 => constr:(cons X1 l)\n  end.\n\nLtac compute_rank l n v :=\n  match l with\n  | (cons ?X1 ?X2) =>\n    let tl := constr:(X2) in\n    match constr:(X1 = v) with\n    | (?X1 = ?X1) => n\n    | _ => compute_rank tl (S n) v\n    end\n  end.\n\nLtac model_aux l f v :=\n  match v with\n  | (f ?X1 ?X2) =>\n    let r1 := model_aux l f X1 with r2 := model_aux l f X2 in\n      constr:(node r1 r2)\n  | ?X1 => let n := compute_rank l 0 X1 in constr:(leaf n)\n  | _ => constr:(leaf 0)\n  end.\n\nLtac model_A A f def v :=\n  let l := term_list f (nil (A:=A)) v in\n  let t := model_aux l f v in\n  constr:(bin_A A f l def t).\n\nLtac assoc_eq A f assoc_thm :=\n  match goal with\n  | [ |- (@eq A ?X1 ?X2) ] =>\n  let term1 := model_A A f X1 X1 \n  with term2 := model_A A f X1 X2 in\n  (change (term1 = term2);\n   apply flatten_valid_A_2 with (1 := assoc_thm); auto)\n  end.\n\nTheorem reflection_test3 :\n forall x y z t u:Z, (x*(y*z*(t*u)) = x*y*(z*(t*u)))%Z.\nProof.\n intros; assoc_eq Z Zmult Zmult_assoc.\nQed.\n\n\nFixpoint nat_le_bool (n m:nat){struct m} : bool :=\n  match n, m with\n  | O, _ => true\n  | S _, O => false\n  | S n, S m => nat_le_bool n m\n  end.\n\nFixpoint insert_bin (n:nat)(t:bin){struct t} : bin :=\n  match t with\n  | leaf m => match nat_le_bool n m with\n              | true => node (leaf n)(leaf m)\n              | false => node (leaf m)(leaf n)\n              end\n  | node (leaf m) t' => match nat_le_bool n m with\n                        | true => node (leaf n) t\n                        | false => \n                            node (leaf m)(insert_bin n t')\n                        end\n  | t => node (leaf n) t\n  end.\n\nFixpoint sort_bin (t:bin) : bin :=\n  match t with\n  | node (leaf n) t' => insert_bin n (sort_bin t')\n  | t => t\n  end.\n\n\n\n\nSection commut_eq.\n(** this section contains some primed versions of previous constructions\n   (for avoiding Reset commands)\n\n*)\n\n Variables (A : Type)(f : A->A->A).\n Hypothesis comm : forall x y:A, f x y = f y x.\n Hypothesis assoc : forall x y z:A, f x (f y z) = f (f x y) z.\n\n Fixpoint bin_A' (l:list A)(def:A)(t:bin){struct t} : A :=\n   match t with\n   | node t1 t2 => f (bin_A' l def t1)(bin_A' l def t2)\n   | leaf n => nth n l def\n   end.\n\n Theorem flatten_aux_valid_A' :\n  forall (l:list A)(def:A)(t t':bin),\n   f (bin_A' l def t)(bin_A' l def t') = bin_A' l def (flatten_aux t t').\n Proof.\n  intros l def t; elim t; simpl; auto.\n  intros t1 IHt1 t2 IHt2 t';  rewrite <- IHt1; rewrite <- IHt2.\n  symmetry; apply assoc.\n Qed.\n\n Theorem flatten_valid_A' :\n  forall (l:list A)(def:A)(t:bin),\n    bin_A' l def t = bin_A' l def (flatten t).\n Proof.\n  intros l def t; elim t; simpl; trivial.\n  intros t1 IHt1 t2 IHt2; rewrite <- flatten_aux_valid_A'; rewrite <- IHt2.\n  trivial.\n Qed.\n\nTheorem flatten_valid_A_2' :\n forall (t t':bin)(l:list A)(def:A),\n   bin_A' l def (flatten t) = bin_A' l def (flatten t')->\n   bin_A' l def t = bin_A' l def t'. \nProof.\n intros t t' l def Heq.\n rewrite (flatten_valid_A' l def t); rewrite (flatten_valid_A' l def t').\n trivial.\nQed.\n\nTheorem insert_is_f : forall (l:list A)(def:A)(n:nat)(t:bin),\n   bin_A' l def (insert_bin n t) = \n   f (nth n l def) (bin_A' l def t).\nProof.\n intros l def n t; elim t.\n intros t1; case t1.\n intros t1' t1'' IHt1 t2 IHt2.\n simpl.\n auto.\n intros n0 IHt1 t2 IHt2.\n simpl.\n case (nat_le_bool n n0).\n simpl.\n auto.\n simpl.\n rewrite IHt2.\n repeat rewrite assoc; rewrite (comm (nth n l def)); auto.\n simpl.\n intros n0; case (nat_le_bool n n0); auto.\n rewrite comm; auto.\nQed.\n\nTheorem sort_eq : forall (l:list A)(def:A)(t:bin),\n    bin_A' l def (sort_bin t) = bin_A' l def t.  \nProof.\n intros l def t; elim t.\n intros t1 IHt1; case t1.\n auto.\n intros n t2 IHt2; simpl; rewrite insert_is_f.\n rewrite IHt2; auto.\n auto.\nQed.\n\n\nTheorem sort_eq_2 :\n forall (l:list A)(def:A)(t1 t2:bin),\n   bin_A' l def (sort_bin t1) = bin_A' l def (sort_bin t2)->\n   bin_A' l def t1 = bin_A' l def t2.  \nProof.\n intros l def t1 t2.\n rewrite <- (sort_eq l def t1); rewrite <- (sort_eq l def t2).\n trivial.\nQed.\n\nEnd commut_eq.\n\n\nLtac term_list' f l v :=\n  match v with\n  | (f ?X1 ?X2) =>\n    let l1 := term_list' f l X2 in term_list' f l1 X1\n  | ?X1 => constr:(cons X1 l)\n  end.\n\nLtac compute_rank' l n v :=\n  match l with\n  | (cons ?X1 ?X2) =>\n    let tl := constr:(X2) in\n    match constr:(X1 = v) with\n    | (?X1 = ?X1) => n\n    | _ => compute_rank' tl (S n) v\n    end\n  end.\n\nLtac model_aux' l f v :=\n  match v with\n  | (f ?X1 ?X2) =>\n    let r1 := model_aux' l f X1 with r2 := model_aux' l f X2 in\n      constr:(node r1 r2)\n  | ?X1 => let n := compute_rank' l 0 X1 in constr:(leaf n)\n  | _ => constr:(leaf 0)\n  end.\n\nLtac comm_eq' A f assoc_thm comm_thm :=\n  match goal with\n  | [ |- (?X1 = ?X2 :>A) ] =>\n    let l := term_list' f (nil (A:=A)) X1 in\n    let term1 := model_aux' l f X1 \n    with term2 := model_aux' l f X2 in\n    (change (bin_A' A f l X1 term1 = bin_A' A f l X1 term2);\n      apply flatten_valid_A_2' with (1 := assoc_thm);\n      apply sort_eq_2 with (1 := comm_thm)(2 := assoc_thm); \n      auto)\n  end.\n\nTheorem reflection_test4 : forall x y z:Z, (x+(y+z) = (z+x)+y)%Z.\nProof.\n intros x y z. comm_eq' Z Zplus Zplus_assoc Zplus_comm.\nQed.\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/ch16_proof_by_reflection/SRC/chap16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7109123043968505}}
{"text": "Module Nats.\n\nFixpoint eqb (n m : nat) : bool :=\n    match n with\n    | O =>  match m with\n            | O => true\n            | S _ => false\n            end\n    | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n    end.\n\nNotation \"x =? y\" := (eqb x y) (at level 70).\n\nEnd Nats.\n\nModule Lists.\n\nImport Nats.\n\nNotation \"x :: xs\" := (cons x xs)(at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) .. ).\nNotation \"x ++ y\" := (app x y) (at level 60, right associativity).\n\nFixpoint rev {X: Type} (l: list X) : list X :=\n    match l with\n    | nil => nil\n    | x::xs => (rev xs) ++ [x]\n    end.\n\nFixpoint nth_err {X: Type} (l: list X) (n: nat) : option X :=\n    match l with\n    | [] => None\n    | x::xs => if n =? 0 then Some x else nth_err xs (pred n)\n    end.\n\nFixpoint split {X Y: Type} (l: list (X * Y))\n    : (list X) * (list Y) :=\n    match l with\n    | nil => (nil, nil)\n    | cons (x, y) ls => match (split ls) with\n                    | (p, q) => (cons x p, cons y q)\n    end\n    end.\n\nEnd Lists.\n", "meta": {"author": "Meowcolm024", "repo": "sf", "sha": "8ec734274600d60b0b7e905bb3d861779031bee8", "save_path": "github-repos/coq/Meowcolm024-sf", "path": "github-repos/coq/Meowcolm024-sf/sf-8ec734274600d60b0b7e905bb3d861779031bee8/lf/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7109122944329235}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Import NAxioms NSub NDiv NGcd.\n\n(** * Least Common Multiple *)\n\n(** Unlike other functions around, we will define lcm below instead of\n  axiomatizing it. Indeed, there is no \"prior art\" about lcm in the\n  standard library to be compliant with, and the generic definition\n  of lcm via gcd is quite reasonable.\n\n  By the way, we also state here some combined properties of div/mod\n  and gcd.\n*)\n\nModule Type NLcmProp\n (Import A : NAxiomsSig')\n (Import B : NSubProp A)\n (Import C : NDivProp A B)\n (Import D : NGcdProp A B).\n\n(** Divibility and modulo *)\n\nLemma mod_divide : forall a b, b~=0 -> (a mod b == 0 <-> (b|a)).\nProof.\n intros a b Hb. split.\n intros Hab. exists (a/b). rewrite mul_comm.\n  rewrite (div_mod a b Hb) at 1. rewrite Hab; now nzsimpl.\n intros (c,Hc). rewrite Hc. now apply mod_mul.\nQed.\n\nLemma divide_div_mul_exact : forall a b c, b~=0 -> (b|a) ->\n (c*a)/b == c*(a/b).\nProof.\n intros a b c Hb H.\n apply mul_cancel_l with b; trivial.\n rewrite mul_assoc, mul_shuffle0.\n assert (H':=H). apply mod_divide, div_exact in H'; trivial.\n rewrite <- H', (mul_comm a c).\n symmetry. apply div_exact; trivial.\n apply mod_divide; trivial.\n now apply divide_mul_r.\nQed.\n\n(** Gcd of divided elements, for exact divisions *)\n\nLemma gcd_div_factor : forall a b c, c~=0 -> (c|a) -> (c|b) ->\n gcd (a/c) (b/c) == (gcd a b)/c.\nProof.\n intros a b c Hc Ha Hb.\n apply mul_cancel_l with c; try order.\n assert (H:=gcd_greatest _ _ _ Ha Hb).\n apply mod_divide, div_exact in H; try order.\n rewrite <- H.\n rewrite <- gcd_mul_mono_l; try order.\n f_equiv; symmetry; apply div_exact; try order;\n  apply mod_divide; trivial; try order.\nQed.\n\nLemma gcd_div_gcd : forall a b g, g~=0 -> g == gcd a b ->\n gcd (a/g) (b/g) == 1.\nProof.\n intros a b g NZ EQ. rewrite gcd_div_factor.\n now rewrite <- EQ, div_same.\n generalize (gcd_nonneg a b); order.\n rewrite EQ; apply gcd_divide_l.\n rewrite EQ; apply gcd_divide_r.\nQed.\n\n(** The following equality is crucial for Euclid algorithm *)\n\nLemma gcd_mod : forall a b, b~=0 -> gcd (a mod b) b == gcd b a.\nProof.\n intros a b Hb. rewrite (gcd_comm _ b).\n rewrite <- (gcd_add_mult_diag_r b (a mod b) (a/b)).\n now rewrite add_comm, mul_comm, <- div_mod.\nQed.\n\n(** We now define lcm thanks to gcd:\n\n    lcm a b = a * (b / gcd a b)\n            = (a / gcd a b) * b\n            = (a*b) / gcd a b\n\n   Nota: [lcm 0 0] should be 0, which isn't garantee with the third\n   equation above.\n*)\n\nDefinition lcm a b := a*(b/gcd a b).\n\nInstance lcm_wd : Proper (eq==>eq==>eq) lcm.\nProof. unfold lcm. solve_proper. Qed.\n\nLemma lcm_equiv1 : forall a b, gcd a b ~= 0 ->\n  a * (b / gcd a b) == (a*b)/gcd a b.\nProof.\n intros a b H. rewrite divide_div_mul_exact; try easy. apply gcd_divide_r.\nQed.\n\nLemma lcm_equiv2 : forall a b, gcd a b ~= 0 ->\n  (a / gcd a b) * b == (a*b)/gcd a b.\nProof.\n intros a b H. rewrite 2 (mul_comm _ b).\n rewrite divide_div_mul_exact; try easy. apply gcd_divide_l.\nQed.\n\nLemma gcd_div_swap : forall a b,\n (a / gcd a b) * b == a * (b / gcd a b).\nProof.\n intros a b. destruct (eq_decidable (gcd a b) 0) as [EQ|NEQ].\n apply gcd_eq_0 in EQ. destruct EQ as (EQ,EQ'). rewrite EQ, EQ'. now nzsimpl.\n now rewrite lcm_equiv1, <-lcm_equiv2.\nQed.\n\nLemma divide_lcm_l : forall a b, (a | lcm a b).\nProof.\n unfold lcm. intros a b. apply divide_factor_l.\nQed.\n\nLemma divide_lcm_r : forall a b, (b | lcm a b).\nProof.\n unfold lcm. intros a b. rewrite <- gcd_div_swap.\n apply divide_factor_r.\nQed.\n\nLemma divide_div : forall a b c, a~=0 -> (a|b) -> (b|c) -> (b/a|c/a).\nProof.\n intros a b c Ha Hb (c',Hc). exists c'.\n now rewrite <- divide_div_mul_exact, Hc.\nQed.\n\nLemma lcm_least : forall a b c,\n (a | c) -> (b | c) -> (lcm a b | c).\nProof.\n intros a b c Ha Hb. unfold lcm.\n destruct (eq_decidable (gcd a b) 0) as [EQ|NEQ].\n apply gcd_eq_0 in EQ. destruct EQ as (EQ,EQ'). rewrite EQ in *. now nzsimpl.\n assert (Ga := gcd_divide_l a b).\n assert (Gb := gcd_divide_r a b).\n set (g:=gcd a b) in *.\n assert (Ha' := divide_div g a c NEQ Ga Ha).\n assert (Hb' := divide_div g b c NEQ Gb Hb).\n destruct Ha' as (a',Ha'). rewrite Ha', mul_comm in Hb'.\n apply gauss in Hb'; [|apply gcd_div_gcd; unfold g; trivial using gcd_comm].\n destruct Hb' as (b',Hb').\n exists b'.\n rewrite mul_shuffle3, <- Hb'.\n rewrite (proj2 (div_exact c g NEQ)).\n rewrite Ha', mul_shuffle3, (mul_comm a a'). f_equiv.\n symmetry. apply div_exact; trivial.\n apply mod_divide; trivial.\n apply mod_divide; trivial. transitivity a; trivial.\nQed.\n\nLemma lcm_comm : forall a b, lcm a b == lcm b a.\nProof.\n intros a b. unfold lcm. rewrite (gcd_comm b), (mul_comm b).\n now rewrite <- gcd_div_swap.\nQed.\n\nLemma lcm_divide_iff : forall n m p,\n  (lcm n m | p) <-> (n | p) /\\ (m | p).\nProof.\n intros. split. split.\n transitivity (lcm n m); trivial using divide_lcm_l.\n transitivity (lcm n m); trivial using divide_lcm_r.\n intros (H,H'). now apply lcm_least.\nQed.\n\nLemma lcm_unique : forall n m p,\n 0<=p -> (n|p) -> (m|p) ->\n (forall q, (n|q) -> (m|q) -> (p|q)) ->\n lcm n m == p.\nProof.\n intros n m p Hp Hn Hm H.\n apply divide_antisym; trivial.\n now apply lcm_least.\n apply H. apply divide_lcm_l. apply divide_lcm_r.\nQed.\n\nLemma lcm_unique_alt : forall n m p, 0<=p ->\n (forall q, (p|q) <-> (n|q) /\\ (m|q)) ->\n lcm n m == p.\nProof.\n intros n m p Hp H.\n apply lcm_unique; trivial.\n apply H, divide_refl.\n apply H, divide_refl.\n intros. apply H. now split.\nQed.\n\nLemma lcm_assoc : forall n m p, lcm n (lcm m p) == lcm (lcm n m) p.\nProof.\n intros. apply lcm_unique_alt. apply le_0_l.\n intros. now rewrite !lcm_divide_iff, and_assoc.\nQed.\n\nLemma lcm_0_l : forall n, lcm 0 n == 0.\nProof.\n intros. apply lcm_unique; trivial. order.\n apply divide_refl.\n apply divide_0_r.\nQed.\n\nLemma lcm_0_r : forall n, lcm n 0 == 0.\nProof.\n intros. now rewrite lcm_comm, lcm_0_l.\nQed.\n\nLemma lcm_1_l : forall n, lcm 1 n == n.\nProof.\n intros. apply lcm_unique; trivial using divide_1_l, le_0_l, divide_refl.\nQed.\n\nLemma lcm_1_r : forall n, lcm n 1 == n.\nProof.\n intros. now rewrite lcm_comm, lcm_1_l.\nQed.\n\nLemma lcm_diag : forall n, lcm n n == n.\nProof.\n intros. apply lcm_unique; trivial using divide_refl, le_0_l.\nQed.\n\nLemma lcm_eq_0 : forall n m, lcm n m == 0 <-> n == 0 \\/ m == 0.\nProof.\n intros. split.\n intros EQ.\n apply eq_mul_0.\n apply divide_0_l. rewrite <- EQ. apply lcm_least.\n  apply divide_factor_l. apply divide_factor_r.\n destruct 1 as [EQ|EQ]; rewrite EQ. apply lcm_0_l. apply lcm_0_r.\nQed.\n\nLemma divide_lcm_eq_r : forall n m, (n|m) -> lcm n m == m.\nProof.\n intros n m H. apply lcm_unique_alt; trivial using le_0_l.\n intros q. split. split; trivial. now transitivity m.\n now destruct 1.\nQed.\n\nLemma divide_lcm_iff : forall n m, (n|m) <-> lcm n m == m.\nProof.\n intros n m. split. now apply divide_lcm_eq_r.\n intros EQ. rewrite <- EQ. apply divide_lcm_l.\nQed.\n\nLemma lcm_mul_mono_l :\n  forall n m p, lcm (p * n) (p * m) == p * lcm n m.\nProof.\n intros n m p.\n destruct (eq_decidable p 0) as [Hp|Hp].\n  rewrite Hp. nzsimpl. rewrite lcm_0_l. now nzsimpl.\n destruct (eq_decidable (gcd n m) 0) as [Hg|Hg].\n  apply gcd_eq_0 in Hg. destruct Hg as (Hn,Hm); rewrite Hn, Hm.\n  nzsimpl. rewrite lcm_0_l. now nzsimpl.\n unfold lcm.\n rewrite gcd_mul_mono_l.\n rewrite mul_assoc. f_equiv.\n now rewrite div_mul_cancel_l.\nQed.\n\nLemma lcm_mul_mono_r :\n forall n m p, lcm (n * p) (m * p) == lcm n m * p.\nProof.\n intros n m p. now rewrite !(mul_comm _ p), lcm_mul_mono_l, mul_comm.\nQed.\n\nLemma gcd_1_lcm_mul : forall n m, n~=0 -> m~=0 ->\n (gcd n m == 1 <-> lcm n m == n*m).\nProof.\n intros n m Hn Hm. split; intros H.\n unfold lcm. rewrite H. now rewrite div_1_r.\n unfold lcm in *.\n apply mul_cancel_l in H; trivial.\n assert (Hg : gcd n m ~= 0) by (red; rewrite gcd_eq_0; destruct 1; order).\n assert (H' := gcd_divide_r n m).\n apply mod_divide in H'; trivial. apply div_exact in H'; trivial.\n rewrite H in H'.\n rewrite <- (mul_1_l m) in H' at 1.\n now apply mul_cancel_r in H'.\nQed.\n\nEnd NLcmProp.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Numbers/Natural/Abstract/NLcm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7109122899837134}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\nFixpoint rotate (rotate_arg0 : natural) (rotate_arg1 : lst) : lst\n           := match rotate_arg0, rotate_arg1 with\n              | Zero, x => x\n              | Succ n, Nil => Nil\n              | Succ n, Cons y x => rotate n (append x (Cons y Nil))\n              end.\n\nLemma append_assoc: forall l1 l2 l3, \n  append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\ninduction l1.\n  - simpl. intros. rewrite IHl1. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem3: forall l, append l Nil = l.\nProof.\ninduction l.\n  - simpl. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (rotate (len x) (append x y)) (append y x).\nProof.\ninduction x.\n- intros. simpl. \n  rewrite <- append_assoc. rewrite IHx. \n  rewrite <- append_assoc. reflexivity.\n- intros. simpl. rewrite lem3. reflexivity.\nQed.\n\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal21.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7109122841378257}}
{"text": "Theorem ch3 :\nforall P Q I O : Prop,\n  (P -> I) ->\n  (Q -> O) ->\n  ((I /\\ O) -> False) ->\n  P ->\n  ~Q.\n(*\n\n前提\n\n  P:詠彦くんは午前六時にイリナちゃんと館内にいた。\n  Q:周防さんが午前六時にイリナちゃんが館外を歩くのを見た。\n  I:イリナちゃんは午前六時に館内にいた。\n  O:イリナちゃんは午前六時に館外にいた。\n\n  P -> I:\n    詠彦くんは午前六時にイリナちゃんと館内にいた　ならば\n    イリナちゃんは午前六時に館内にいた。\n\n  Q -> Q\n    周防さんが午前六時にイリナちゃんが館外を歩くのを見た　ならば\n    イリナちゃんは午前六時に館外にいた。\n\n  (I /\\ O) -> False:\n    イリナちゃんは午前六時に館内にいた　かつ　イリナちゃんは午前六時に館外にいた　ならば\n    矛盾である。\n\n  P:\n    詠彦くんは午前六時にイリナちゃんと館内にいた。\n\n結論\n\n  ~Q:周防さんの証言が偽だった。\n\n*)\nProof.\n  intros P Q I O A1 A2 A3 A4.\n  intro.\n  apply A3.\n  split.\n  -\n    apply A1.\n    apply A4.\n  -\n    apply A2.\n    apply H.\nQed.\n\nFrom mathcomp\nRequire Import ssreflect.\n\nTheorem ch3_ssr :\nforall P Q I O : Prop,\n  (P -> I) ->\n  (Q -> O) ->\n  ((I /\\ O) -> False) ->\n  P ->\n  ~Q.\nProof.\n  move=> P Q I O A1 A2 A3 A4.\n  rewrite /not.\n  move=> Q_is_true.\n  apply: A3.\n  split.\n  -\n    apply: A1.\n    done.\n  -\n    apply: A2.\n    done.\nQed.\n", "meta": {"author": "wakaba2017", "repo": "Love_and_contraindicated_predicate_logic", "sha": "33a25bb685e78a4b431271290de5452f0437a440", "save_path": "github-repos/coq/wakaba2017-Love_and_contraindicated_predicate_logic", "path": "github-repos/coq/wakaba2017-Love_and_contraindicated_predicate_logic/Love_and_contraindicated_predicate_logic-33a25bb685e78a4b431271290de5452f0437a440/lesson3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7109122775288047}}
{"text": "Require Export study04.\nRequire Export study01. (*ないと何故かble_natを認識しない*)\n\nModule st05.\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\nTheorem plus_fact_is_true : plus_fact.\nProof. reflexivity. Qed.\nDefinition strange_prop : Prop :=\n  (2+2=5)->(99+26=42).\nCheck ble_nat.\nDefinition strange_prop2 : Prop :=\n  forall n, (ble_nat n 17 = true) -> (ble_nat n 99 = true).\nDefinition even (n:nat) : Prop :=\n  evenb n = true.\nCheck even.\nCheck even 2.\nCheck even 3.\nDefinition even_n__even_SSn (n:nat) : Prop :=\n  (even n) -> (even (S (S n))).\nDefinition between (n m o: nat) : Prop :=\n  andb (ble_nat n o) (ble_nat o m) = true.\nDefinition teen : nat->Prop := between 13 19.\nDefinition true_for_zero (P:nat->Prop) : Prop :=\n  P 0.\nDefinition true_for_n__true_for_Sn (P:nat->Prop) (n:nat) : Prop :=\n  P n -> P (S n).\nDefinition preserved_by_S (P:nat->Prop) : Prop :=\n  forall n', P n' -> P (S n').\nDefinition true_for_all_numbers (P:nat->Prop) : Prop :=\n  forall n, P n.\nDefinition our_nat_induction (P:nat->Prop) : Prop :=\n     (true_for_zero P) ->\n     (preserved_by_S P) ->\n     (true_for_all_numbers P).\n\nInductive good_day : day -> Prop :=\n  | gd_sat : good_day saturday\n  | gd_sun : good_day sunday.\nTheorem gds : good_day sunday.\nProof. apply gd_sun. Qed.\nInductive day_before : day -> day -> Prop :=\n  | db_tue : day_before tuesday monday\n  | db_wed : day_before wednesday tuesday\n  | db_thu : day_before thursday wednesday\n  | db_fri : day_before friday thursday\n  | db_sat : day_before saturday friday\n  | db_sun : day_before sunday saturday\n  | db_mon : day_before monday sunday.\nInductive fine_day_for_singing : day -> Prop :=\n  | fdfs_any : forall d:day, fine_day_for_singing d.\nTheorem fdfs_wed : fine_day_for_singing wednesday.\nProof. apply fdfs_any. Qed.\n\nDefinition fdfs_wed' : fine_day_for_singing wednesday :=\n  fdfs_any wednesday.\nCheck fdfs_wed.\nCheck fdfs_wed'.\nCheck fdfs_any.\nCheck fdfs_any wednesday.\nCheck fine_day_for_singing wednesday.\n(* \"OK\"な日とは(1)良い日であるか(2)OKな日の前日である*)\nInductive ok_day : day -> Prop :=\n  | okd_gd : forall d,\n      good_day d ->\n      ok_day d\n  | okd_before : forall d1 d2,\n      ok_day d2 ->\n      day_before d2 d1 ->\n      ok_day d1.\nDefinition okdw : ok_day wednesday :=\n  okd_before wednesday thursday\n    (okd_before thursday friday\n       (okd_before friday saturday\n         (okd_gd saturday gd_sat)\n         db_sat)\n       db_fri)\n    db_thu.\nTheorem okdw' : ok_day wednesday.\nProof.\n  apply okd_before with (d2:=thursday).\n    apply okd_before with (d2:=friday).\n      apply okd_before with (d2:=saturday).\n          apply okd_gd. apply gd_sat.\n          apply db_sat.\n      apply db_fri.\n  apply db_thu. \nQed.\nPrint okdw'.\n\nDefinition okd_before2 := forall d1 d2 d3,\n  ok_day d3 ->\n  day_before d2 d1 ->\n  day_before d3 d2 ->\n  ok_day d1.\nTheorem okd_before2_valid : okd_before2.\nProof.\n  unfold okd_before2.\n  intros d1 d2 d3 H1 H2 H3.\n  apply okd_before with (d2:=d2).\n  apply okd_before with (d2:=d3).\n  apply H1. apply H3. apply H2.\nQed.\nPrint okd_before2_valid.\n\nCheck nat_ind.\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind.\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\nCheck rgb_ind.\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\n\nCheck natlist1_ind.\n\nInductive ExSet : Type :=\n  | con1 : bool -> ExSet\n  | con2 : nat -> ExSet -> ExSet.\n\nCheck ExSet_ind.\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nCheck list_ind.\n\nInductive tree (X:Type) : Type :=\n  | leaf : X -> tree X\n  | node : tree X -> tree X -> tree X.\n\nCheck tree_ind.\n\nInductive mytype (X:Type) : Type :=\n  | constr1 : X -> mytype X\n  | constr2 : nat -> mytype X\n  | constr3 : mytype X -> nat -> mytype X.\n\nCheck mytype_ind.\n\nInductive foo (X Y:Type) : Type :=\n  | bar : X -> foo X Y\n  | baz : Y -> foo X Y\n  | quux : (nat -> foo X Y) -> foo X Y.\n\nCheck foo_ind.\n\nInductive foo' (X:Type) : Type :=\n  | C1 : list X -> foo' X -> foo' X\n  | C2 : foo' X.\n\nCheck foo'_ind.\n\nDefinition P_m0r (n:nat) : Prop :=\n  n * 0 = 0.\nDefinition P_m0r' : nat -> Prop :=\n  fun n => n * 0 = 0.\n\nTheorem mult_0_r'' : forall n:nat,\n  P_m0r n.\nProof.\n  apply nat_ind. reflexivity.\n  unfold P_m0r. simpl. intros n' IHn'.\n  apply IHn'.\nQed.\n\nInductive ev : nat -> Prop :=\n  | ev_o : ev 0\n  | ev_SS : forall n:nat, ev n -> ev (S (S n)).\n\nTheorem four_ev' : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_o.\nQed.\nPrint four_ev'.\nDefinition four_ev : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_o).\n\nTheorem ev_plus4' : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. apply ev_SS. apply ev_SS.\n  apply H.\nQed.\nPrint ev_plus4'.\nDefinition ev_plus4 : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) (H : ev n) => ev_SS (S (S n)) \n  (ev_SS n H).\n\nTheorem double_even : forall n,\n  ev (double n).\nProof.\n  induction n. simpl. apply ev_o.\n  simpl. apply ev_SS. apply IHn.\nQed.\n\nTheorem ev_minus2 : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct E as [| n' E'].\n  simpl.\n  apply ev_o.\n  simpl. apply E'.\nQed.\n(*Theorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  destruct n.\n  simpl. apply E.\n  simpl. apply ev_SS.*)\n\nTheorem ev_even : forall n,\n  ev n -> even n.\nProof.\n  intros n E. induction E as [| n' E'].\n  unfold even. reflexivity.\n  unfold even. unfold even in IHE'.\n  simpl. apply IHE'.\nQed.\n\nTheorem ev_sum : forall n m,\n  ev n -> ev m -> ev (n+m).\nProof.\n  intros n m En Em.\n  induction En.\n  apply Em.\n  simpl. apply ev_SS.\n  apply IHEn.\nQed.\n\nTheorem SSev_evn : forall n,\n  ev (S (S n)) -> ev n.\nProof.\n  intros n E.\n  inversion E.\n  apply H0.\nQed.\n(* I が現在のコンテキストにおいて帰納的に宣言された仮定 P を\n参照しているとします。 ここで、inversion I は、Pの\nコンストラクタごとにサブゴールを生成します。 \n各サブゴールにおいて、 コンストラクタが P を証明するのに\n必要な条件によって I が置き換えられます。 サブゴールのうち\nいくつかは矛盾が存在するので、 inversion はそれらを除外します。 \n残っているのは、元のゴールが成り立つことを示すのに必要なサブゴールです。*)\n\nTheorem SSSSev_even : forall n,\n  ev (S (S (S (S n)))) -> ev n.\nProof.\n  intros n E.\n  inversion E.\n  inversion H0.\n  apply H2.\nQed.\n\nTheorem even5_nonsense : \n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros E.\n  inversion E.\n  inversion H0.\n  inversion H2.\nQed.\n\nTheorem ev_minus2' : forall n,\n  ev n -> ev (pred (pred n)).\nProof.\n  intros n E.\n  inversion E.\n  simpl. rewrite <- H in E.\n  apply E.\n  simpl. apply H.\nQed.\n\nTheorem ev_ev_even : forall n m,\n  ev (n+m) -> ev n -> ev m.\nProof.\n  intros n m Enm En.\n  induction En.\n  simpl in Enm. apply Enm.\n  apply IHEn. simpl in Enm.\n  inversion Enm. apply H0.\nQed.\n(*Enm についての帰納法はダメ*)\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 E1 E2.\n  assert (H1:ev((n+n)+(m+p))).\n  replace ((n+n)+(m+p)) with ((n+m)+(n+p)).\n  apply ev_sum with (n:=n+m) (m:=n+p).\n  apply E1. apply E2.\n  replace (n+m+(n+p)) with (n+(m+n)+p).\n  replace (m+n) with (n+m).\n  rewrite plus_assoc. rewrite plus_assoc. \n  reflexivity.\n  rewrite plus_comm. reflexivity.\n  rewrite plus_assoc. rewrite plus_assoc.\n  reflexivity.\n  apply ev_ev_even with (n:=n+n)(m:=m+p) in H1.\n  apply H1.\n  rewrite <- double_plus.\n  apply double_even.\nQed.\n\nInductive MyProp : nat -> Prop :=\n  | MyProp1 : MyProp 4\n  | MyProp2 : forall n:nat, MyProp n -> MyProp (4 + n)\n  | MyProp3 : forall n:nat, MyProp (2 + n) -> MyProp n.\n\nTheorem MyProp_ten : MyProp 10.\nProof.\n  apply MyProp3. simpl.\n  apply MyProp2. apply MyProp2.\n  apply MyProp1.\nQed.\n\nTheorem MyProp_0 : MyProp 0.\nProof.\n  apply MyProp3. apply MyProp3. apply MyProp1.\nQed.\n\nTheorem MyProp_plustwo : forall n:nat, MyProp n\n  -> MyProp (S (S n)).\nProof.\n  intros n E. replace (S (S n)) with (2+n).\n  apply MyProp3. apply MyProp2. apply E.\n  reflexivity.\nQed.\n\nTheorem MyProp_ev : forall n:nat,\n  ev n -> MyProp n.\nProof.\n  intros n E.\n  induction E. apply MyProp_0.\n  apply MyProp_plustwo. apply IHE.\nQed.\n\nTheorem ev_MyProp : forall n:nat,\n  MyProp n -> ev n.\nProof.\n  intros n E.\n  induction E.\n  apply ev_SS. apply ev_SS. apply ev_o.\n  apply ev_SS. apply ev_SS. apply IHE.\n  apply ev_minus2 in IHE. simpl in IHE.\n  apply IHE.\nQed.\n\nAbout MyProp_ev.\nPrint MyProp_ev.\nLocate plus_comm.\n\n\n\n\n\n\n\n\n", "meta": {"author": "elle-et-noire", "repo": "coq", "sha": "fd253f245131883ee55ff9f1824d4bb417b6e7b7", "save_path": "github-repos/coq/elle-et-noire-coq", "path": "github-repos/coq/elle-et-noire-coq/coq-fd253f245131883ee55ff9f1824d4bb417b6e7b7/study05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7108768443671283}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(** \n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** The Coq proof assistant and the Mathematical Components library\n\nObjective: learn the Coq system in the MC library\n\n*** Roadmap\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/lesson1.html\">lesson 1</a>#: Programs\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/exercise1.html\">exercise</a># and #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/exercise1-solution.html\">solution</a>#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/lesson2.html\">lesson 2</a>#: Proofs\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/exercise2.html\">exercise</a># and #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/exercise2-solution.html\">solution</a>#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/lesson3.html\">lesson 3</a>#: Boolean reflection\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/exercise3.html\">exercise</a># and #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/exercise3-solution.html\">solution</a>#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/lesson4.html\">lesson 4</a>#: Libraries\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/exercise4.html\">exercise</a># and #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/exercise4-solution.html\">solution</a>#\n\n*** Teaching material\n\n- Slides and exercises\n  #<a href=\"https://www-sop.inria.fr/teams/marelle/types18/\">https://www-sop.inria.fr/teams/marelle/types18/</a>#\n- Coq (#<a href=\"https://coq.inria.fr/download\">software</a>#\n  and #<a href=\"https://coq.inria.fr/distrib/current/refman/\">user manual</a>#)\n- Mathematical Components\n  (#<a href=\"http://math-comp.github.io/math-comp/\">software</a># and\n  #<a href=\"https://math-comp.github.io/mcb/\">book</a>#)\n\n\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nYou don't need to install Coq in order to follow this\nclass, you just need a recent browser thanks to\n#<a href=\"https://github.com/ejgallego/jscoq\">jsCoq</a>#.\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 1: summary\n\n- functions\n- simple data\n- containers\n- symbolic computations\n- higher order functions and mathematical notations\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Functions\n\nFunctions are built using the [fun .. => ..] syntax.\nThe command [Check] verifies that a term is well typed.\n\n#<div>#\n*)\nCheck (fun n => 1 + n + 1).\n(**\n#</div>#\n\nNotice that the type of [n] was inferred and that\nthe whole term has type [nat -> nat], where [->]\nis the function space.\n\nFunction application is written by writing the function\non the left of the argument (eg, not as in the mathematical\npractice).\n\n#<div>#\n*)\nCheck 2.\nCheck (fun n => 1 + n + 1) 2.\n(**\n#</div>#\n\nNotice how [2] has a type that fits, and hence\nthe type of the function applied to [2] is [nat].\n\nTerms (hence functions) can be given a name using\nthe [Definition] command. The command offers some\nsyntactic sugar for binding the function arguments.\n\n#<div>#\n*)\nDefinition f := (fun n => 1 + n + 1).\n(* Definition f n := 1 + n + 1. *)\n(* Definition f (n : nat) := 1 + n + 1. *)\n(**\n#</div>#\n\nNamed terms can be printed.\n\n#<div>#\n*)\nPrint f.\n(**\n#</div>#\n\nCoq is able to compute with terms, in particular\none can obtain the normal form via the [Eval lazy in]\ncommand.\n\n#<div>#\n*)\nEval lazy in f 2.\n(**\n#</div>#\n\nNotice that \"computation\" is made of many steps.\nIn particular [f] has to be unfolded (delta step)\nand then the variable substituted for the argument\n(beta).\n\n#<div>#\n*)\nEval lazy delta [f] in f 2.\nEval lazy delta [f] beta in f 2.\n(**\n#</div>#\n\nNothing but functions (and their types) are built-in in Coq.\nAll the rest is defined, even [1], [2] and [+] are not primitive.\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 1.1 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Data types\n\nData types can be declared using the [Inductive] command.\n\nMany of them are already available in the Coq library called\n[Prelude] that is automatically loaded. We hence just print\nthem.\n\n[Inductive bool := true | false.]\n\n#<div>#\n*)\nPrint bool.\n(**\n#</div>#\n\nThis command declares a new type [bool] and declares\nhow the terms (in normal form) of this type are built.\nOnly [true] and [false] are canonical inhabitants of\n[bool].\n\nTo use a boolean value Coq provides the [if..then..else..]\nsyntax.\n\n#<div>#\n*)\nDefinition twoVtree (b : bool) := if b then 2 else 3.\nEval lazy in twoVtree true.\nEval lazy delta in twoVtree true.\nEval lazy delta beta in twoVtree true.\nEval lazy delta beta iota in twoVtree true.\n(**\n#</div>#\n\nWe define a few boolean operators that will come in handy\nlater on.\n\n#<div>#\n*)\nDefinition andb (b1 b2 : bool) := if b1 then b2 else false.\nDefinition orb (b1 b2 : bool) := if b1 then true else b2.\n\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nCheck true && false || false.\n(**\n#</div>#\n\nThe [Infix] command lets one declare infix notations.\nPrecendence and associativity is already declared in the\nprelude of Coq, here we just associate the constants\n[andb] and [orb] to these notataions.\n\nNatural numbers are defined similarly to booleans:\n\n[Inductive nat := O | S (n : nat).]\n\n#<div>#\n*)\nPrint nat.\n(**\n#</div>#\n\nCoq provides a special notation for literals, eg [3],\nthat is just sugar for [S (S (S O))].\n\nThe Mathematical Components library adds on top of that\nthe postfix [.+1], [.+2], .. for iterated applications\nof [S] to terms other than [O].\n\n#<div>#\n*)\nCheck 3.\nCheck (fun x => (x + x).+2).\nEval lazy in (fun x => (x + x).+2) 1.\n(**\n#</div>#\n\nIn order to use natural numbers Coq provides two\ntools. An extended [if..then..else..] syntax to\nextract the argument of [S] and the [Fixpoint]\ncommand to define recusrsive functions.\n\n#<div>#\n*)\nDefinition pred (n : nat) :=\n  if n is p.+1 then p else 0.\n\nEval lazy in pred 7.\n(**\n#</div>#\n\nNotice that [p] is a binder. When the [if..then..else..]\nis evaluated, and [n] put in normal form, then if it\nis [S t] the variable [p] takes [t] and the then-branch\nis taken.\n\nNow lets define addition using recursion\n\n#<div>#\n*)\nFixpoint addn n m :=\n  if n is p.+1 then (addn p m).+1 else m.\nInfix \"+\" := addn.\nEval lazy in 3 + 2.\n(**\n#</div>#\n\nThe [if..then..else..] syntax is just sugar for\n[match..with..end].\n\n#<div>#\n*)\nPrint addn.\n(**\n#</div>#\n\nLet's now write the equality test for natural numbers\n\n#<div>#\n*)\nFixpoint eqn n m :=\n  match n, m with\n  | 0, 0 => true\n  | p.+1, q.+1 => eqn p q\n  | _, _ => false\n  end.\nInfix \"==\" := eqn.\nEval lazy in 3 == 4.\n(**\n#</div>#\n\nOther examples are subtraction and order\n\n#<div>#\n*)\nFixpoint subn m n : nat :=\n  match m, n with\n  | p.+1, q.+1 => subn p q\n  | _ , _ => m\n  end.\n\nInfix \"-\" := subn.\n\nEval lazy in 3 - 2.\nEval lazy in 2 - 3. (* truncated *)\n\nDefinition leq m n := m - n == 0.\n\nInfix \"<=\" := leq.\n\nEval lazy in 4 <= 5.\n(**\n#</div>#\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nAll the constants defined in this slide are already\ndefined in Coq's prelude or in Mathematical Components.\nThe main difference is that [==] is not specific to\n[nat] but overloaded (it works for most data types).\nThis topic is to be developed in lesson 4.\n\nThis slide corresponds to\nsection 1.2 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Containers\n\nContainers let one aggregate data, for example to form a\npair or a list.  The interesting characteristic of containers\nis that they are polymorphic: the same container can be used\nto hold terms of many types.\n\n[Inductive seq (A : Type) := nil | cons (hd : A) (tl : seq A).]\n\n#<div>#\n*)\nCheck nil.\nCheck cons 3 [::].\n(**\n#</div>#\n\nWe learn that [[::]] is a notation for the empty sequence\nand that the type parameter [?A] is implicit.\n\n#<div>#\n*)\nCheck 1 :: nil.\nCheck [:: 3; 4; 5 ].\n(**\n#</div>#\n\nThe infix [::] notation stands for [cons]. This one is mostly\nused to pattern match a sequence.\n\nThe notation [[:: .. ; .. ]] can be used to form sequences\nby separating the elements with [;]. When there are no elements\nwhat is left is [[::]] that is the empty seqeunce.\n\nAnd of course we can use sequences with other data types\n\n#<div>#\n*)\nCheck [:: 3; 4; 5 ].\nCheck [:: true; false; true ].\n(**\n#</div>#\n\nLet's now define the [size] function.\n\n#<div>#\n*)\nFixpoint size A (s : seq A) :=\n  if s is _ :: tl then (size tl).+1 else 0.\n\nEval lazy in size [:: 1; 8; 34].\n(**\n#</div>#\n\nGiven that the contents of containers are of an\narbitrary type many common operations are parametrized\nby functions that are specific to the type of the\ncontents.\n\n[[\nFixpoint map A B (f : A -> B) s :=\nif s is e :: tl then f e :: map f tl else nil.\n]]\n\n#<div>#\n*)\nDefinition l := [:: 1; 2; 3].\nEval lazy in [seq x.+1 | x <- l].\n(**\n#</div>#\n\nThe #<a href=\"http://math-comp.github.io/math-comp/htmldoc/mathcomp.ssreflect.seq.html\">seq</a>#\nlibrary of Mathematical Components contains many combinators. Their syntax\nis documented in the header of the file.\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 1.3 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Symbols\n\nThe section mecanism is used to describe a context under\nwhich definitions are made. Coq lets us not only define\nterms, but also compute with them in that context.\n\nWe use this mecanism to talk about symbolic computation.\n\n#<div>#\n*)\nSection symbols.\nVariables x : nat.\n\nEval lazy in pred x.+1 .\nEval lazy in pred x .\n(**\n#</div>#\n\nComputation can take place in presence of variables\nas long as constructors can be consumed. When no\nmore constructors are available computation is\nstuck.\n\nLet's not look at a very common higher order\nfunction.\n\n#<div>#\n*)\n\nFixpoint foldr A T f (a : A) (s : seq T) :=\n  if s is x :: xs then f x (foldr f a xs) else a.\n(**\n#</div>#\n\nThe best way to understand what [foldr] does \nis to postulate a virable [f] and compute. \n\n#<div>#\n*)\n\nVariable f : nat -> nat -> nat.\n\nEval lazy in foldr f    3 [:: 1; 2 ].\n\n(**\n#</div>#\n\nIf we plug [addn] in place of [f] we\nobtain a term that evaluates to a number.\n\n#<div>#\n*)\n\nEval lazy in foldr addn 3 [:: 1; 2 ].\n\nEnd symbols.\n\n(**\n#</div>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsections 1.4 and 1.5 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Higher order functions and mathematical notations\n\nLet's try to write this formula in Coq\n\n#$$ \\sum_{i=1}^n (i * 2 - 1) = n ^ 2 $$#\n\nWe need a bit of infrastruture\n\n#<div>#\n*)\nFixpoint iota m n := if n is u.+1 then m :: iota m.+1 u else [::].\n\nEval lazy in iota 0 5.\n\n(**\n#</div>#\n\nCombining [iota] and [foldr] we can get pretty\nclose to the LaTeX source for the formula above.\n\n#<div>#\n*)\n\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (foldr (fun i a => F + a) 0 (iota m (n-m))).\n\nCheck \\sum_(1 <= x < 5) (x * 2 - 1).\nEval lazy in \\sum_(1 <= x < 5) (x * 2 - 1).\n(**\n#</div>#\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 1.6 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 1: sum up\n\n- [fun .. => ..]\n- [Check]\n- [Definition]\n- [Print]\n- [Eval lazy]\n- [Indcutive] declarations [bool], [nat], [seq].\n- [match .. with .. end] and [if .. is .. then .. else ..]\n- [Fixpoint]\n- [andb] [orb] [eqn] [leq] [addn] [subn] [size] [foldr]\n\n#</div>#\n\n\n*)\n", "meta": {"author": "gares", "repo": "typesschool18", "sha": "c27fe831c750c948245593a5fa52f768dd990cb3", "save_path": "github-repos/coq/gares-typesschool18", "path": "github-repos/coq/gares-typesschool18/typesschool18-c27fe831c750c948245593a5fa52f768dd990cb3/lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8670357615200474, "lm_q1q2_score": 0.7108768428690048}}
{"text": "(* summations on a ring-like (semiring, ring, field) *)\n\nSet Nested Proofs Allowed.\n\nRequire Import Utf8 Arith.\nImport List List.ListNotations.\n\nRequire Import Misc RingLike PermutationFun.\n\nNotation \"'∑' ( i = b , e ) , g\" :=\n  (iter_seq b e (λ c i, (c + g)%L) 0%L)\n  (at level 45, i at level 0, b at level 60, e at level 60,\n   right associativity,\n   format \"'[hv  ' ∑  ( i  =  b ,  e ) ,  '/' '[' g ']' ']'\").\n\nNotation \"'∑' ( i ∈ l ) , g\" :=\n  (iter_list l (λ c i, (c + g)%L) 0%L)\n  (at level 45, i at level 0, l at level 60,\n   right associativity,\n   format \"'[hv  ' ∑  ( i  ∈  l ) ,  '/' '[' g ']' ']'\").\n\nSection a.\n\nContext {T : Type}.\nContext (ro : ring_like_op T).\nContext {rp : ring_like_prop T}.\nContext {Hom : rngl_has_opp_or_subt = true}.\n\nTheorem fold_left_rngl_add_fun_from_0 : ∀ A a l (f : A → _),\n  (fold_left (λ c i, c + f i) l a =\n   a + fold_left (λ c i, c + f i) l 0)%L.\nProof.\nintros.\napply fold_left_op_fun_from_d. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem all_0_rngl_summation_list_0 : ∀ A l (f : A → T),\n  (∀ i, i ∈ l → f i = 0%L)\n  → ∑ (i ∈ l), f i = 0%L.\nProof.\nintros * Hz.\napply iter_list_all_d; [ | | | easy ]. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem all_0_rngl_summation_0 : ∀ b e f,\n  (∀ i, b ≤ i ≤ e → f i = 0%L)\n  → ∑ (i = b, e), f i = 0%L.\nProof.\nintros * Hz.\napply iter_seq_all_d; [ | | | easy ]. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_list_split_first : ∀ A (l : list A) d f,\n  l ≠ []\n  → ∑ (i ∈ l), f i = (f (hd d l) + ∑ (i ∈ tl l), f i)%L.\nProof.\nintros * Hlz.\napply iter_list_split_first; [ | | | easy ]. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_list_split_last : ∀ A (l : list A) d f,\n  l ≠ []\n  → ∑ (i ∈ l), f i = (∑ (i ∈ removelast l), f i + f (last l d))%L.\nProof.\nintros * Hlz.\nnow apply iter_list_split_last.\nQed.\n\nTheorem rngl_summation_list_split : ∀ A (l : list A) f n,\n  ∑ (i ∈ l), f i = (∑ (i ∈ firstn n l), f i + ∑ (i ∈ skipn n l), f i)%L.\nProof.\nintros.\nrewrite <- firstn_skipn with (n := n) (l := l) at 1.\nunfold iter_list.\nrewrite fold_left_app.\nnow rewrite fold_left_rngl_add_fun_from_0.\nQed.\n\nTheorem rngl_summation_split_first : ∀ b k g,\n  b ≤ k\n  → ∑ (i = b, k), g i = (g b + ∑ (i = S b, k), g i)%L.\nProof.\nintros * Hbk.\napply iter_seq_split_first; [ | | | easy ]. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_split_last : ∀ b k g,\n  b ≤ k\n  → (∑ (i = b, k), g i = ∑ (i = S b, k), g (i - 1)%nat + g k)%L.\nProof.\nintros * Hbk.\nnow apply iter_seq_split_last.\nQed.\n\nTheorem rngl_summation_split : ∀ j g b k,\n  b ≤ S j ≤ S k\n  → (∑ (i = b, k), g i = ∑ (i = b, j), g i + ∑ (i = j+1, k), g i)%L.\nProof.\nintros * Hbjk.\napply iter_seq_split; [ | | | easy ]. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_split3 : ∀ j g b k,\n  b ≤ j ≤ k\n  → ∑ (i = b, k), g i =\n       (∑ (i = S b, j), g (i - 1)%nat + g j + ∑ (i = j + 1, k), g i)%L.\nProof.\nintros * Hj.\napply iter_seq_split3; [ | | | easy ]. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_eq_compat : ∀ g h b k,\n  (∀ i, b ≤ i ≤ k → (g i = h i)%L)\n  → (∑ (i = b, k), g i = ∑ (i = b, k), h i)%L.\nProof.\nintros * Hgh.\nnow apply iter_seq_eq_compat.\nQed.\n\nTheorem rngl_summation_list_eq_compat : ∀ A g h (l : list A),\n  (∀ i, i ∈ l → (g i = h i)%L)\n  → (∑ (i ∈ l), g i = ∑ (i ∈ l), h i)%L.\nProof.\nintros * Hgh.\nnow apply iter_list_eq_compat.\nQed.\n\nTheorem rngl_summation_succ_succ : ∀ b k g,\n  (∑ (i = S b, S k), g i = ∑ (i = b, k), g (S i))%L.\nProof.\nintros b k g.\napply iter_seq_succ_succ.\nQed.\n\nTheorem rngl_summation_list_empty : ∀ A g (l : list A),\n  l = [] → ∑ (i ∈ l), g i = 0%L.\nProof.\nintros * Hl.\nnow apply iter_list_empty.\nQed.\n\nTheorem rngl_summation_empty : ∀ g b k,\n  k < b → (∑ (i = b, k), g i = 0)%L.\nProof.\nintros * Hkb.\nnow apply iter_seq_empty.\nQed.\n\nTheorem rngl_summation_list_add_distr :\n  ∀ A g h (l : list A),\n  (∑ (i ∈ l), (g i + h i) =\n  (∑ (i ∈ l), g i) + ∑ (i ∈ l), h i)%L.\nProof.\nintros Hic *.\napply iter_list_distr. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_comm.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_add_distr : ∀ g h b k,\n  (∑ (i = b, k), (g i + h i) =\n   ∑ (i = b, k), g i + ∑ (i = b, k), h i)%L.\nProof.\nintros g h b k.\napply iter_seq_distr. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_comm.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_shift : ∀ s b g k,\n  s ≤ b ≤ k\n  → ∑ (i = b, k), g i = ∑ (i = b - s, k - s), g (s + i)%nat.\nProof.\nintros s b g k Hbk.\nnow apply (iter_shift s).\nQed.\n\nTheorem rngl_summation_rshift : ∀ b e f,\n  ∑ (i = b, e), f i = ∑ (i = S b, S e), f (i - 1)%nat.\nProof.\nintros.\nrewrite rngl_summation_succ_succ.\napply rngl_summation_eq_compat.\nintros i Hi.\nnow rewrite Nat_sub_succ_1.\nQed.\n\nTheorem rngl_opp_summation :\n  rngl_has_opp = true →\n  ∀ b e f, ((- ∑ (i = b, e), f i) = ∑ (i = b, e), (- f i))%L.\nProof.\nintros Hro *.\napply iter_seq_inv. {\n  now apply rngl_opp_0.\n} {\n  intros.\n  rewrite fold_rngl_sub; [ | easy ].\n  rewrite rngl_add_comm.\n  now apply rngl_opp_add_distr.\n}\nQed.\n\nTheorem rngl_summation_rtl : ∀ g b k,\n  (∑ (i = b, k), g i = ∑ (i = b, k), g (k + b - i)%nat)%L.\nProof.\nintros g b k.\napply iter_seq_rtl. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_comm.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem mul_iter_list_distr_l : ∀ A B a (la : list B) f\n    (add mul : A → A → A) d\n    (mul_add_distr_l : ∀ y z, mul a (add y z) = add (mul a y) (mul a z)),\n  mul a (iter_list la (λ c i, add c (f i)) d) =\n  iter_list la (λ c i, add c (mul a (f i))) (mul a d).\nProof.\nintros.\nclear Hom.\nunfold iter_list.\nrevert d.\ninduction la as [| a1]; intros; [ easy | cbn ].\nrewrite IHla.\nf_equal.\napply mul_add_distr_l.\nQed.\n\nTheorem mul_iter_list_distr_r : ∀ A B a (la : list B) f\n    (add mul : A → A → A) d\n    (mul_add_distr_r : ∀ y z, mul (add y z) a = add (mul y a) (mul z a)),\n  mul (iter_list la (λ c i, add c (f i)) d) a =\n  iter_list la (λ c i, add c (mul (f i) a)) (mul d a).\nProof.\nintros.\nclear Hom.\nunfold iter_list.\nrevert d.\ninduction la as [| a1]; intros; [ easy | cbn ].\nrewrite IHla.\nf_equal.\napply mul_add_distr_r.\nQed.\n\nTheorem rngl_mul_summation_list_distr_l : ∀ A a (la : list A) f,\n  (a * (∑ (i ∈ la), f i) = ∑ (i ∈ la), a * f i)%L.\nProof.\nintros.\nrewrite mul_iter_list_distr_l; [ | apply rngl_mul_add_distr_l ].\nnow rewrite rngl_mul_0_r.\nQed.\n\nTheorem rngl_mul_summation_distr_l : ∀ a b e f,\n  (a * (∑ (i = b, e), f i) = ∑ (i = b, e), a * f i)%L.\nProof.\nintros.\napply rngl_mul_summation_list_distr_l.\nQed.\n\nTheorem rngl_mul_summation_list_distr_r : ∀ A a (la : list A) f,\n  ((∑ (i ∈ la), f i) * a = ∑ (i ∈ la), f i * a)%L.\nProof.\nintros.\nrewrite mul_iter_list_distr_r; [ | intros; apply rngl_mul_add_distr_r ].\nnow rewrite rngl_mul_0_l.\nQed.\n\nTheorem rngl_mul_summation_distr_r : ∀ a b e f,\n  ((∑ (i = b, e), f i) * a = ∑ (i = b, e), f i * a)%L.\nProof.\nintros.\napply rngl_mul_summation_list_distr_r.\nQed.\n\nTheorem rngl_summation_list_only_one : ∀ A g (a : A),\n  (∑ (i ∈ [a]), g i = g a)%L.\nProof.\nintros.\nunfold iter_list; cbn.\napply rngl_add_0_l.\nQed.\n\nTheorem rngl_summation_only_one : ∀ g n, ∑ (i = n, n), g i = g n.\nProof.\nintros g n.\napply iter_seq_only_one, rngl_add_0_l.\nQed.\n\nTheorem rngl_summation_list_cons : ∀ A (a : A) la f,\n  (∑ (i ∈ a :: la), f i = f a + ∑ (i ∈ la), f i)%L.\nProof.\nintros.\napply iter_list_cons. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_list_app : ∀ A (la lb : list A) f,\n  ∑ (i ∈ la ++ lb), f i = (∑ (i ∈ la), f i + ∑ (i ∈ lb), f i)%L.\nProof.\nintros.\nrewrite iter_list_app.\nunfold iter_list.\napply fold_left_rngl_add_fun_from_0.\nQed.\n\nTheorem rngl_summation_list_concat : ∀ A (ll : list (list A)) (f : A → T),\n  ∑ (a ∈ concat ll), f a = ∑ (l ∈ ll), ∑ (a ∈ l), f a.\nProof.\nintros.\ninduction ll as [| l]; cbn. {\n  rewrite rngl_summation_list_empty; [ | easy ].\n  now rewrite rngl_summation_list_empty.\n}\nrewrite rngl_summation_list_app.\nrewrite rngl_summation_list_cons.\nf_equal.\napply IHll.\nQed.\n\nTheorem rngl_summation_summation_list_flat_map : ∀ A B la (f : A → list B) g,\n  (∑ (a ∈ la), ∑ (b ∈ f a), g b) = ∑ (b ∈ flat_map f la), g b.\nProof.\nintros.\ninduction la as [| a]; cbn. {\n  now apply rngl_summation_list_empty.\n}\nrewrite rngl_summation_list_cons.\nrewrite rngl_summation_list_app.\nf_equal; apply IHla.\nQed.\n\nTheorem rngl_summation_summation_list_swap : ∀ A B la lb (f : A → B → T),\n  ∑ (a ∈ la), (∑ (b ∈ lb), f a b) =\n  ∑ (b ∈ lb), (∑ (a ∈ la), f a b).\nProof.\nintros.\ninduction la as [| a]. {\n  rewrite rngl_summation_list_empty; [ | easy ].\n  erewrite rngl_summation_list_eq_compat. 2: {\n    intros b Hb.\n    now rewrite rngl_summation_list_empty.\n  }\n  now rewrite all_0_rngl_summation_list_0.\n}\nrewrite rngl_summation_list_cons.\nsymmetry.\nerewrite rngl_summation_list_eq_compat. 2: {\n  intros b Hb.\n  now rewrite rngl_summation_list_cons.\n}\ncbn.\nrewrite rngl_summation_list_add_distr.\nnow f_equal.\nQed.\n\nTheorem rngl_summation_summation_exch : ∀ g k,\n  (∑ (j = 0, k), (∑ (i = 0, j), g i j) =\n   ∑ (i = 0, k), ∑ (j = i, k), g i j)%L.\nProof.\nintros g k.\ninduction k; [ easy | ].\nrewrite rngl_summation_split_last; [ | easy ].\nrewrite rngl_summation_succ_succ.\nerewrite rngl_summation_eq_compat. 2: {\n  intros i Hi.\n  now rewrite Nat_sub_succ_1.\n}\ncbn.\nrewrite IHk.\nsymmetry.\nrewrite rngl_summation_split_last; [ | easy ].\nrewrite rngl_summation_succ_succ.\nerewrite rngl_summation_eq_compat. 2: {\n  intros i Hi.\n  now rewrite Nat_sub_succ_1.\n}\ncbn.\nerewrite rngl_summation_eq_compat. 2: {\n  intros i Hi.\n  rewrite rngl_summation_split_last; [ | flia Hi ].\n  rewrite rngl_summation_succ_succ.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros j Hj.\n    now rewrite Nat_sub_succ_1.\n  }\n  easy.\n}\ncbn.\nrewrite rngl_summation_add_distr.\nrewrite <- rngl_add_assoc.\nf_equal.\nsymmetry.\nrewrite rngl_summation_split_last; [ | easy ].\nrewrite rngl_summation_succ_succ.\nrewrite rngl_summation_only_one.\nf_equal.\napply rngl_summation_eq_compat.\nintros i Hi.\nnow rewrite Nat_sub_succ_1.\nQed.\n\nTheorem fold_left_add_seq_add : ∀ b len i g,\n  fold_left (λ (c : T) (j : nat), (c + g i j)%L)\n    (seq (b + i) len) 0%L =\n  fold_left (λ (c : T) (j : nat), (c + g i (i + j)%nat)%L)\n    (seq b len) 0%L.\nProof.\nintros.\nrevert b i.\ninduction len; intros; [ easy | cbn ].\ndo 2 rewrite rngl_add_0_l.\nrewrite fold_left_rngl_add_fun_from_0; symmetry.\nrewrite fold_left_rngl_add_fun_from_0; symmetry.\nf_equal; [ now rewrite Nat.add_comm | ].\nnow rewrite <- IHlen.\nQed.\n\nTheorem rngl_summation_summation_shift : ∀ g k,\n  (∑ (i = 0, k), (∑ (j = i, k), g i j) =\n   ∑ (i = 0, k), ∑ (j = 0, k - i), g i (i + j)%nat)%L.\nProof.\nintros g k.\napply rngl_summation_eq_compat; intros i Hi.\nunfold iter_seq, iter_list.\nrewrite Nat.sub_0_r.\nrewrite Nat.sub_succ_l; [ | now destruct Hi ].\nnow rewrite <- fold_left_add_seq_add, Nat.add_0_l.\nQed.\n\nTheorem rngl_summation_ub_add_distr : ∀ a b f,\n  (∑ (i = 0, a + b), f i)%L = (∑ (i = 0, a), f i + ∑ (i = S a, a + b), f i)%L.\nProof.\nintros.\nrewrite (rngl_summation_split a); [ | flia ].\nnow rewrite Nat.add_1_r.\nQed.\n\nTheorem rngl_summation_summation_distr : ∀ a b f,\n  (∑ (i = 0, a), ∑ (j = 0, b), f i j)%L =\n  (∑ (i = 0, (S a * S b - 1)%nat), f (i / S b)%nat (i mod S b))%L.\nProof.\nintros.\nrevert b.\ninduction a; intros. {\n  unfold iter_seq at 1, iter_list at 1.\n  cbn - [ \"mod\" \"/\" ].\n  rewrite rngl_add_0_l, Nat.add_sub.\n  apply rngl_summation_eq_compat.\n  intros i Hi.\n  rewrite Nat.div_small; [ | flia Hi ].\n  rewrite Nat.mod_small; [ easy | flia Hi ].\n}\nrewrite rngl_summation_split_last; [ | easy ].\nrewrite rngl_summation_succ_succ.\nerewrite rngl_summation_eq_compat. 2: {\n  intros i Hi.\n  erewrite rngl_summation_eq_compat. 2: {\n    intros j Hj.\n    now rewrite Nat_sub_succ_1.\n  }\n  easy.\n}\nremember (S a) as x.\ncbn - [ \"mod\" \"/\" ]; subst x.\nrewrite IHa.\nrewrite Nat.sub_0_r.\nrewrite (Nat.add_comm b).\nrewrite rngl_summation_ub_add_distr.\nrewrite (rngl_summation_split_last _ (S a * S b)); [ | cbn; flia ].\nsymmetry.\nrewrite (rngl_summation_shift 1); [ | cbn; flia ].\nsymmetry.\nrewrite Nat.sub_diag.\nrewrite <- rngl_add_assoc.\nf_equal. {\n  apply rngl_summation_eq_compat.\n  intros i Hi.\n  now rewrite (Nat.add_comm 1 i), Nat.add_sub.\n} {\n  rewrite Nat.div_mul; [ | easy ].\n  rewrite Nat.mod_mul; [ | easy ].\n  destruct b. {\n    unfold iter_seq at 1, iter_list at 1.\n    cbn - [ \"mod\" \"/\" ].\n    rewrite rngl_add_0_l.\n    rewrite rngl_summation_empty; [ | flia ].\n    now rewrite rngl_add_0_r.\n  }\n  symmetry.\n  rewrite (rngl_summation_shift (S (S a * S (S b)))); [ | flia ].\n  symmetry.\n  rewrite Nat.sub_diag.\n  replace (S a * S (S b) + S b - S (S a * S (S b))) with b. 2: {\n    cbn.\n    rewrite <- Nat.add_succ_l.\n    rewrite Nat.sub_add_distr.\n    now do 2 rewrite Nat.add_sub.\n  }\n  rewrite rngl_summation_split_first; [ | easy ].\n  f_equal.\n  rewrite rngl_summation_succ_succ.\n  apply rngl_summation_eq_compat.\n  intros i Hi.\n  rewrite Nat.add_succ_comm.\n  rewrite Nat.div_add_l; [ | easy ].\n  rewrite (Nat.div_small (S i)); [ | flia Hi ].\n  f_equal; [ symmetry; apply Nat.add_0_r | ].\n  rewrite Nat_mod_add_l_mul_r; [ | easy ].\n  symmetry.\n  apply Nat.mod_small; flia Hi.\n}\nQed.\n\nTheorem rngl_summation_list_permut : ∀ A (eqb : A → _),\n  equality eqb →\n  ∀ (la lb : list A) f,\n  permutation eqb la lb\n  → (∑ (i ∈ la), f i = ∑ (i ∈ lb), f i)%L.\nProof.\nintros * Heqb * Hl.\napply (iter_list_permut Heqb); [ | | | | easy ]. {\n  apply rngl_add_0_l.\n} {\n  apply rngl_add_0_r.\n} {\n  apply rngl_add_comm.\n} {\n  apply rngl_add_assoc.\n}\nQed.\n\nTheorem rngl_summation_seq_summation : ∀ b len f,\n  len ≠ 0\n  → (∑ (i ∈ seq b len), f i = ∑ (i = b, b + len - 1), f i)%L.\nProof.\nintros * Hlen.\nnow apply iter_list_seq.\nQed.\n\nTheorem rngl_summation_list_mul_summation_list :\n  ∀ A B li lj (f : A → T) (g : B → T),\n  ((∑ (i ∈ li), f i) * (∑ (j ∈ lj), g j))%L =\n  ∑ (i ∈ li), (∑ (j ∈ lj), f i * g j).\nProof.\nintros.\ninduction li as [| ai]. {\n  rewrite rngl_summation_list_empty; [ symmetry | easy ].\n  rewrite rngl_summation_list_empty; [ symmetry | easy ].\n  now apply rngl_mul_0_l.\n}\ndo 2 rewrite rngl_summation_list_cons.\nrewrite rngl_mul_add_distr_r.\nrewrite IHli.\nnow rewrite rngl_mul_summation_list_distr_l.\nQed.\n\nTheorem rngl_summation_mul_summation : ∀ bi bj ei ej f g,\n  ((∑ (i = bi, ei), f i) * (∑ (j = bj, ej), g j))%L =\n  ∑ (i = bi, ei), (∑ (j = bj, ej), f i * g j).\nProof.\nintros.\napply rngl_summation_list_mul_summation_list.\nQed.\n\nTheorem rngl_summation_list_map :\n  ∀ A B (f : A → B) (g : B → _) l,\n  ∑ (j ∈ map f l), g j = ∑ (i ∈ l), g (f i).\nProof.\nintros.\nunfold iter_list.\nrewrite List_fold_left_map.\nnow apply rngl_summation_list_eq_compat.\nQed.\n\nTheorem rngl_summation_list_change_var : ∀ A B (l : list A) f g (h : _ → B),\n  (∀ i, i ∈ l → g (h i) = i)\n  → ∑ (i ∈ l), f i = ∑ (i ∈ map h l), f (g i).\nProof.\nintros * Hgh.\nrewrite rngl_summation_list_map.\napply rngl_summation_list_eq_compat.\nintros i Hi.\nnow rewrite Hgh.\nQed.\n\nTheorem rngl_summation_change_var : ∀ A b e f g (h : _ → A),\n  (∀ i, b ≤ i ≤ e → g (h i) = i)\n  → ∑ (i = b, e), f i = ∑ (i ∈ map h (seq b (S e - b))), f (g i).\nProof.\nintros * Hgh.\napply rngl_summation_list_change_var.\nintros i Hi.\napply in_seq in Hi.\napply Hgh.\nflia Hi.\nQed.\n\nTheorem rngl_summation_le_compat :\n  rngl_is_ordered = true →\n  ∀ b e g h,\n  (∀ i, b ≤ i ≤ e → (g i ≤ h i)%L)\n  → (∑ (i = b, e), g i ≤ ∑ (i = b, e), h i)%L.\nProof.\nintros Hor * Hgh.\nunfold iter_seq.\nremember (S e - b) as n eqn:Hn.\nrevert b Hn Hgh.\ninduction n as [| n IHn]; intros; [ now apply rngl_le_refl | ].\nunfold iter_list; cbn.\ndo 2 rewrite rngl_add_0_l.\nrewrite fold_left_rngl_add_fun_from_0.\nremember (g b + _)%L as x.\nrewrite fold_left_rngl_add_fun_from_0.\nsubst x.\napply rngl_add_le_compat; [ easy | apply Hgh; flia Hn | ].\napply IHn; [ flia Hn | ].\nintros i Hbie.\napply Hgh; flia Hbie.\nQed.\n\nTheorem rngl_summation_filter : ∀ A l f (g : A → T),\n  ∑ (a ∈ filter f l), g a = ∑ (a ∈ l), if f a then g a else 0%L.\nProof.\nintros.\ninduction l as [| b]; [ easy | cbn ].\nrewrite rngl_summation_list_cons.\nremember (f b) as fb eqn:Hfb; symmetry in Hfb.\ndestruct fb. {\n  rewrite rngl_summation_list_cons; f_equal.\n  apply IHl.\n} {\n  rewrite rngl_add_0_l.\n  apply IHl.\n}\nQed.\n\nEnd a.\n\nArguments all_0_rngl_summation_0 {T}%type {ro rp} (b e)%nat (f g)%function.\nArguments all_0_rngl_summation_list_0 {T}%type {ro rp} A%type l%list.\nArguments rngl_summation_list_split_first {T}%type {ro rp} A%type l%list.\nArguments rngl_mul_summation_list_distr_l {T ro rp}.\nArguments rngl_mul_summation_list_distr_r {T ro rp}.\nArguments rngl_mul_summation_distr_l {T ro rp} Hom a b e f.\nArguments rngl_mul_summation_distr_r {T ro rp} Hom a b e f.\nArguments rngl_opp_summation {T}%type {ro rp} Hop (b e)%nat.\nArguments rngl_summation_add_distr {T}%type {ro rp} _ _ (b k)%nat.\nArguments rngl_summation_change_var {T ro} A%type (b e)%nat.\nArguments rngl_summation_eq_compat {T ro} _ _ (b k)%nat.\nArguments rngl_summation_filter {T ro rp} A%type l%list.\nArguments rngl_summation_list_app {T}%type {ro rp} A%type (la lb)%list.\nArguments rngl_summation_list_change_var {T ro} (A B)%type l%list.\nArguments rngl_summation_list_concat {T ro rp} A%type ll%list.\nArguments rngl_summation_list_cons {T ro rp} A%type a la%list.\nArguments rngl_summation_list_map {T ro} (_ _)%type.\nArguments rngl_summation_list_mul_summation_list {T ro rp}.\nArguments rngl_summation_list_only_one {T}%type {ro rp} A%type.\nArguments rngl_summation_list_permut {T ro rp} [A]%type _ _ (la lb)%list.\nArguments rngl_summation_list_split {T}%type {ro rp} A%type l%list _ n%nat.\nArguments rngl_summation_mul_summation {T}%type {ro rp} Hom (bi bj ei ej)%nat.\nArguments rngl_summation_only_one {T}%type {ro rp} g%function n%nat.\nArguments rngl_summation_rtl {T}%type {ro rp} _ (b k)%nat.\nArguments rngl_summation_shift {T}%type {ro} (s b)%nat _%function k%nat.\nArguments rngl_summation_split {T}%type {ro rp} j%nat g%function (b k)%nat.\nArguments rngl_summation_split_first {T}%type {ro rp} (b k)%nat.\nArguments rngl_summation_split3 {T}%type {ro rp} j%nat _ (b k)%nat.\nArguments rngl_summation_summation_distr {T}%type {ro rp} (a b)%nat.\nArguments rngl_summation_summation_exch {T ro rp} g k%nat.\nArguments rngl_summation_summation_list_flat_map {T ro rp} (A B)%type la%list.\nArguments rngl_summation_summation_list_swap {T ro rp} (_ _)%type (_ _)%list.\n", "meta": {"author": "roglo", "repo": "coq_sensitivity", "sha": "398291aa86a447f0f35b4918043e94d9eb703c12", "save_path": "github-repos/coq/roglo-coq_sensitivity", "path": "github-repos/coq/roglo-coq_sensitivity/coq_sensitivity-398291aa86a447f0f35b4918043e94d9eb703c12/main/IterAdd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7108223021848602}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Structures.OrdersFacts.\nRequire Import Omega.\nRequire Import Coq.Logic.ClassicalFacts.\n\n(*The recursion tree for quickSort*)\nInductive qs_tree : list nat -> Type :=\n| qs_tree_base : qs_tree nil\n| qs_tree_step : forall ( x: nat) (xs: list nat), \n  qs_tree (filter (fun y => leb y  x) (xs)) -> \n  qs_tree (filter (fun y => negb (leb y x)) (xs)) -> \n    qs_tree (cons x xs).\n\n(*The fixpoint which evaluates a recursion tree*)\nFixpoint qs_helper (l : list nat) (q : qs_tree l) {struct q} : list nat :=\n  match q with\n  | qs_tree_base => nil\n  | qs_tree_step x xs q0 q1 =>\n      (qs_helper (filter (fun y : nat => leb y x) xs) q0) ++ (x ::\n        (qs_helper (filter (fun y : nat => negb (leb y x)) xs) q1))\n  end.\n\nRequire Import Coq.Sorting.Sorted.\n\n(*Create the recursion tree for a given list*)\n  (*Redefine lemmas from libraries to be opaque*)\nLemma leb_correct : forall m n:nat, m <= n -> leb m n = true.\nProof.\n  induction m as [| m IHm]. trivial.\n  destruct n. intro H. elim (le_Sn_O _ H).\n  intros. simpl in |- *. apply IHm. apply le_S_n. assumption.\nDefined.\n\nLemma leb_correct_conv : forall m n:nat, m < n -> leb n m = false.\nProof.\n  intros.\n  generalize (leb_complete n m).\n  destruct (leb n m); auto.\n  intros.\n  elim (lt_irrefl _ (lt_le_trans _ _ _ H (H0 (refl_equal true)))).\nDefined.\n\nLemma not_true_is_false : forall b:bool, b <> true -> b = false.\ndestruct b.\nintros.\nred in H; elim H.\nreflexivity.\nintros abs.\nreflexivity.\nDefined.\n\nLemma gt_leb_conv: forall (a: nat) (a0 : nat),(a > a0) -> (a0 <= a).\nProof.\nintros.\nintuition.\nDefined.\n\n  (*New facts about filters*)\nLemma filter_commutative: forall (xs : list nat) (f1 : nat -> bool) (f2 : nat -> bool),\n   (filter f2 (filter f1 xs))\n= (filter f1 (filter f2 xs)).\nProof.\nintros.\ninduction xs.\nsimpl. (*base case*)\nintuition.\nsimpl. (*step*)\ndestruct (bool_dec (f1 a) true).\ndestruct (bool_dec (f2 a) true).\nrewrite e.\nrewrite e0.\nsimpl.\nrewrite e.\nrewrite e0.\nrewrite IHxs.\nintuition. (*case f1,!f2*)\napply not_true_is_false in n.\nrewrite n; rewrite e.\nsimpl.\nrewrite n.\nintuition. (*case !f1,f2*)\napply not_true_is_false in n.\ndestruct (bool_dec (f2 a) true).\nrewrite n;rewrite e.\nsimpl.\nrewrite n.\nintuition.\napply not_true_is_false in n0.\nrewrite n;rewrite n0.\nintuition.\nDefined.\n\nLemma filter_combine: forall (xs : list nat) (f1 :nat -> bool) (f2 : nat -> bool),\nfilter f1 (filter f2 xs) = filter ( fun x: nat => (f1 x) && f2 x) xs.\nProof.\nintros.\ninduction xs.\nsimpl.\nreflexivity.\nsimpl.\ndestruct (bool_dec (f1 a) true); intros. (*case f1,f2*)\ndestruct (bool_dec (f2 a) true); intros.\nrewrite e; rewrite e0.\nsimpl.\nrewrite e.\nrewrite IHxs.\nintuition. (*case f1,!f2*)\napply not_true_is_false in n as e0.\nrewrite e; rewrite e0.\nsimpl.\nintuition. (*case !f1,f2*)\napply not_true_is_false in n as e.\ndestruct (bool_dec (f2 a) true); intros.\nrewrite e; rewrite e0.\nsimpl.\nrewrite e.\nintuition. (*case !f1,!f2*)\napply not_true_is_false in n0 as e0.\nrewrite e; rewrite e0.\nintuition.\nDefined.\n\n  (*lemma f1 -> f2 then (filter f2 (filter f1 xs)) = filter f2 xs*)\n  (*made specific for convienience*)\nLemma filter_nat_helper_right: forall (a : nat) (b :nat) (xs : list nat), (a>=b)-> \n  (filter (fun x0 : nat => negb(x0 <=? a))) (filter (fun x0 : nat => negb(x0 <=? b)) xs)=\n(filter (fun y : nat => negb(y <=? a)) xs).\nProof.\nintros.\ninduction xs. (*induction xs*)\nsimpl. (*base case*)\nintuition.\nsimpl. (*step*)\ndestruct (le_gt_dec a0 b). (*case a0 <= b*)\napply leb_correct in l as l1.\nrewrite l1; simpl.\napply (le_trans a0 b a) in l.\napply leb_correct in l.\nrewrite l; simpl.\nintuition.\nintuition. \napply leb_correct_conv in g. (*case a0 > b*)\nrewrite g; simpl.\ndestruct (le_gt_dec a0 a).\napply leb_correct in l.\nrewrite l; simpl.\nintuition.\napply leb_correct_conv in g0.\nrewrite g0; simpl.\nrewrite IHxs.\nintuition.\nDefined.\n\nLemma filter_nat_helper_left: forall (xs : list nat) (a:nat) (b:nat),\n  (b > a) -> (filter (fun y : nat => (y <=? a) && (y <=? b)) xs) = filter (fun y : nat => y <=? a) xs.\nProof.\nintros.\ninduction xs.\nsimpl. (*base case*)\nintuition.\nsimpl. (*step*)\ndestruct (le_lt_dec a0 a). (*case a0 <= a*)\napply (gt_le_trans b a a0) in H.\napply leb_correct in l.\nrewrite l.\napply gt_leb_conv in H.\napply leb_correct in H.\nrewrite H.\nrewrite andb_true_l.\nrewrite IHxs.\nintuition.\nintuition. (*case a < a0*)\napply leb_correct_conv in l.\nrewrite l.\nrewrite andb_false_l.\nintuition.\nDefined.\n\n(*Vital lemma: convert list to recursion tree for quickSort*)\nLemma create_qs_tree: forall (l : list nat), (qs_tree l).\nProof.\nintros.\ninduction l. (*induction l*)\nconstructor. (*base*)\nconstructor. (*step*)\ninduction IHl. (*induction on IH : qs_tree*)\nconstructor. (*base*)\nsimpl. (*step left side*)\ndestruct (le_lt_dec x a). (*case x in left branch*)\napply leb_correct in l.\nrewrite l.\nconstructor. (*recurse*)\nrewrite filter_commutative. (*left recursion branch*)\nintuition.\nrewrite filter_commutative. (*right recursion branch*)\nintuition. \napply leb_correct_conv in l as l2. (*if head xs not left*)\nrewrite l2.\napply (filter_nat_helper_left xs a x) in l.\nrewrite filter_combine in IHIHl1.\nrewrite <- l.\nintuition.\ninduction IHl. (*recurse right branch*)\nsimpl.\nconstructor.\nsimpl.\ndestruct (le_gt_dec x a). (*if head xs not in right branch*)\napply leb_correct in l as l0;\nrewrite l0.\nsimpl.\nintuition.\napply (filter_nat_helper_right a x xs) in l.\nrewrite <- l.\nintuition. (*if head xs in right branch*)\napply leb_correct_conv in g.\nrewrite g.\nsimpl.\nconstructor. (*recurse*)\nrewrite filter_commutative.\nintuition.\nrewrite filter_commutative.\nintuition.\nDefined.\n\n(*Definition quickSort creates recursion tree for given list and hands it to qs_helper which executes it*)\nDefinition quickSort (ls :list nat) := qs_helper ls (create_qs_tree ls).\n\n(*Test  quickSort*)\n\nDefinition l := 5 :: 3 :: 0 :: nil.\nEval compute in ((quickSort l)). \n\n(*Proof Correctness quickSort*)\n  (*Note this prove uses that this holds for the recursion tree made by our definition xs*)\nLemma qs_contains : forall (xs : list nat) (x : nat), \n  (In x xs) -> (In x (quickSort xs)).\nProof.\nintros.\nunfold quickSort.\ninduction (create_qs_tree xs). (*induction on recursion tree*)\nintuition. (*base*)\nsimpl.  (*step*)\ndestruct H. (*split x = x0 or x in xs*)\nrewrite <- H. (*case x = x0*)\nsimpl.\nintuition. (*case x in xs*)\napply in_or_app. (*split x left or right after sorting*)\ndestruct (le_gt_dec x x0). \n(*case x <= x0*)\npose proof (filter_In (fun y => leb y  x0) x (xs)) as filter_In.\napply leb_correct in l0.\nintuition.\n(*case x > x0*)\npose proof (filter_In (fun y => negb (leb y  x0)) x (xs)) as filter_In.\napply leb_correct_conv in g.\napply negb_true_iff in g.\nintuition.\nQed.\n\n  (*Note this proof does not use that the recursion tree is made by our definition \n    (This is slightly more powerfull but harder to prove)*)\nLemma qs_maintains : forall (xs : list nat) (x : nat) (conc : qs_tree xs), \n  (In x (qs_helper xs conc))-> (In x xs).\nProof.\nintros.\ninduction conc. (*induction on conc*)\nintuition. (*base*)\nsimpl in H. (*step*)\napply in_app_or in H.\ndestruct H. (*case x is in the left side*)\nintuition.\napply filter_In in H0.\nintuition.\nunfold In in H. (*case x is the pivot*)\ndestruct H.\nunfold In.\nintuition. (*case x is in the right side*)\nintuition.\napply filter_In in H0.\nintuition.\nQed.\n\nLemma qs_In_equiv : forall (xs : list nat) (x : nat), \n  (In x (quickSort xs)) <-> ( In x xs).\nProof.\nintros.\nintuition.\nunfold quickSort in H. \napply (qs_maintains xs x (create_qs_tree xs)).\nintuition.\napply qs_contains.\nintuition.\nQed.\n\n(*Other easier to use definition of HdRel only one way conversion is needed*)\nLemma HdRel_redef : forall (xs : list nat) (a : nat) (f : nat-> nat -> Prop),\n  (forall (x:nat), (In x xs) -> (f a x)) -> (HdRel f a xs).\nProof.\nintros.\ninduction xs.\nconstructor.\nconstructor.\napply H.\nintuition.\nQed. \n\n(*if we have two sorted arrays xls,xrs \n  and every element in xls is smaller then every element in xrs then xls++xrs is sorted*)\nLemma sorted_comb : forall (xls: list nat) (xrs: list nat),\n  (Sorted le xls) -> (Sorted le xrs) -> \n  (forall (x:nat), (In x xls) -> (HdRel le x xrs)) ->\n      Sorted le (xls ++ xrs).\nProof.\nintros.\ninduction xls. (*induction on xls*)\nsimpl. (*base*)\nintuition.\nsimpl. (*step*)\nconstructor. (*prove sorted properties*)\napply Sorted_inv in H. (*tail is sorted / holds by IH*)\nintuition.\napply Sorted_inv in H. (*head is smaller then all elements in tail*)\nintuition.\ndestruct xls. (*case xrs is empty*)\ndestruct xrs. (*case xls is also empty*)\nsimpl.\nconstructor. (*HdRel holds by definition*)\nsimpl. (*get head of nill++xls*)\napply H1.\nconstructor.\nintuition. (*get head of xrs*)\nconstructor.\napply HdRel_inv in H3.\nintuition.\nQed.\n\n(*final goal proof that quickSort sorts a list*)\nLemma qs_sorted : forall (xs: list nat),\n  Sorted le (quickSort xs).\nProof. \nintros.\nunfold quickSort. (*unfold quickSort*)\ninduction (create_qs_tree (xs)). (*induction on recursion tree*)\nsimpl. (*step recursion tree is empty (then by def xs is empty*)\nintuition. (*node recursion tree*)\nsimpl. (*to prove left recursion results appended by right recursion result is sorted*)\napply sorted_comb. (*IH left is sorted*) \nintuition. (*to prove pivot appended right recursion is sorted*) \nconstructor.\nintuition. (*IH right is sorted*)\napply HdRel_redef. (*to prove x is smaller then everything in the right branch*)\nintros.\napply qs_maintains in H. (*use In x xs <-> In x quickSort xs*)\napply filter_In in H. (*effect of filter*) \nintuition.\napply negb_true_iff in H1.\napply leb_complete_conv in H1.\nintuition. \nintuition. (*to prove everything in the right branch is smaller then everything in pivot + left*)\napply HdRel_redef.\nintuition.\napply qs_maintains in H. (*use In x xs <-> In x quickSort xs*)\napply filter_In in H. (*effect of filter*)\napply in_inv in H0. (*trivial clean up basic algebra differences*) \nintuition.\napply leb_complete in H2.\nrewrite <- H.\nintuition.\napply qs_maintains in H.\napply filter_In in H.\nintuition.\napply negb_true_iff in H3.\napply leb_complete in H2.\napply leb_complete_conv in H3.\nintuition.\nQed.", "meta": {"author": "WouterSchols", "repo": "Coq_Quiksort", "sha": "0134e85462c2bb724cf2d66d5c78ef4c1679180d", "save_path": "github-repos/coq/WouterSchols-Coq_Quiksort", "path": "github-repos/coq/WouterSchols-Coq_Quiksort/Coq_Quiksort-0134e85462c2bb724cf2d66d5c78ef4c1679180d/quickSort_def1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.7931059585194574, "lm_q1q2_score": 0.7108223021656928}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.\nRequire Import finfun bigop prime binomial ssralg finset fingroup finalg.\nRequire Import perm zmodp matrix.\n\n(*****************************************************************************)\n(* In this file we develop the rank and row space theory of matrices, based  *)\n(* on an extended Gaussian elimination procedure similar to LUP              *)\n(* decomposition. This provides us with a concrete but generic model of      *)\n(* finite dimensional vector spaces and F-algebras, in which vectors, linear *)\n(* functions, families, bases, subspaces, ideals and subrings are all        *)\n(* represented using matrices. This model can be used as a foundation for    *)\n(* the usual theory of abstract linear algebra, but it can also be used to   *)\n(* develop directly substantial theories, such as the theory of finite group *)\n(* linear representation.                                                    *)\n(*   Here we define the following concepts and notations:                    *)\n(* Gaussian_elimination A == a permuted triangular decomposition (L, U, r)   *)\n(*                   of A, with L a column permutation of a lower triangular *)\n(*                   invertible matrix, U a row permutation of an upper      *)\n(*                   triangular invertible matrix, and r the rank of A, all  *)\n(*                   satisfying the identity L *m pid_mx r *m U = A.         *)\n(*        \\rank A == the rank of A.                                          *)\n(*    row_free A <=> the rows of A are linearly free (i.e., the rank and     *)\n(*                   height of A are equal).                                 *)\n(*    row_full A <=> the row-space of A spans all row-vectors (i.e., the     *)\n(*                   rank and width of A are equal).                         *)\n(*    col_ebase A == the extended column basis of A (the first matrix L      *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*    row_ebase A == the extended row base of A (the second matrix U         *)\n(*                   returned by Gaussian_elimination A).                    *)\n(*     col_base A == a basis for the columns of A: a row-full matrix         *)\n(*                   consisting of the first \\rank A columns of col_ebase A. *)\n(*     row_base A == a basis for the rows of A: a row-free matrix consisting *)\n(*                   of the first \\rank A rows of row_ebase A.               *)\n(*       pinvmx A == a partial inverse for A in its row space (or on its     *)\n(*                   column space, equivalently). In particular, if u is a   *)\n(*                   row vector in the row_space of A, then u *m pinvmx A is *)\n(*                   the row vector of the coefficients of a decomposition   *)\n(*                   of u as a sub of rows of A.                             *)\n(*        kermx A == the row kernel of A : a square matrix whose row space   *)\n(*                   consists of all u such that u *m A = 0 (it consists of  *)\n(*                   the inverse of col_ebase A, with the top \\rank A rows   *)\n(*                   zeroed out). Also, kermx A is a partial right inverse   *)\n(*                   to col_ebase A, in the row space anihilated by A.       *)\n(*      cokermx A == the cokernel of A : a square matrix whose column space  *)\n(*                   consists of all v such that A *m v = 0 (it consists of  *)\n(*                   the inverse of row_ebase A, with the leftmost \\rank A   *)\n(*                   columns zeroed out).                                    *)\n(* eigenvalue g a <=> a is an eigenvalue of the square matrix g.             *)\n(* eigenspace g a == a square matrix whose row space is the eigenspace of    *)\n(*                   the eigenvalue a of g (or 0 if a is not an eigenvalue). *)\n(* We use a different scope %MS for matrix row-space set-like operations; to *)\n(* avoid confusion, this scope should not be opened globally. Note that the  *)\n(* the arguments of \\rank _ and the operations below have default scope %MS. *)\n(*    (A <= B)%MS <=> the row-space of A is included in the row-space of B.  *)\n(*                   We test for this by testing if cokermx B anihilates A.  *)\n(*     (A < B)%MS <=> the row-space of A is properly included in the         *)\n(*                   row-space of B.                                         *)\n(*  (A <= B <= C)%MS == (A <= B)%MS && (B <= C)%MS, and similarly for        *)\n(*                   (A < B <= C)%MS, (A < B <= C)%MS and (A < B < C)%MS.    *)\n(*    (A == B)%MS == (A <= B <= A)%MS (A and B have the same row-space).     *)\n(*   (A :=: B)%MS == A and B behave identically wrt. \\rank and <=. This      *)\n(*                   triple rewrite rule is the Prop version of (A == B)%MS. *)\n(*                   Note that :=: cannot be treated as a setoid-style       *)\n(*                   Equivalence because its arguments can have different    *)\n(*                   types: A and B need not have the same number of rows,   *)\n(*                   and often don't (e.g., in row_base A :=: A).            *)\n(*       <<A>>%MS == a square matrix with the same row-space as A; <<A>>%MS  *)\n(*                   is a canonical representation of the subspace generated *)\n(*                   by A, viewed as a list of row-vectors: if (A == B)%MS,  *)\n(*                   then <<A>>%MS = <<B>>%MS.                               *)\n(*     (A + B)%MS == a square matrix whose row-space is the sum of the       *)\n(*                   row-spaces of A and B; thus (A + B == col_mx A B)%MS.   *)\n(*  (\\sum_i <expr i>)%MS == the \"big\" version of (_ + _)%MS; as the latter   *)\n(*                   has a canonical abelian monoid structure, most generic  *)\n(*                   bigop lemmas apply (the other bigop indexing notations  *)\n(*                   are also defined).                                      *)\n(*   (A :&: B)%MS == a square matrix whose row-space is the intersection of  *)\n(*                   the row-spaces of A and B.                              *)\n(*  (\\bigcap_i <expr i>)%MS == the \"big\" version of (_ :&: _)%MS, which also *)\n(*                   has a canonical abelian monoid structure.               *)\n(*         A^C%MS == a square matrix whose row-space is a complement to the  *)\n(*                   the row-space of A (it consists of row_ebase A with the *)\n(*                   top \\rank A rows zeroed out).                           *)\n(*   (A :\\: B)%MS == a square matrix whose row-space is a complement of the  *)\n(*                   the row-space of (A :&: B)%MS in the row-space of A.    *)\n(*                   We have (A :\\: B := A :&: (capmx_gen A B)^C)%MS, where  *)\n(*                   capmx_gen A B is a rectangular matrix equivalent to     *)\n(*                   (A :&: B)%MS, i.e., (capmx_gen A B == A :&: B)%MS.      *)\n(*    proj_mx A B == a square matrix that projects (A + B)%MS onto A         *)\n(*                   parellel to B, when (A :&: B)%MS = 0 (A and B must also *)\n(*                   be square).                                             *)\n(*     mxdirect S == the sum expression S is a direct sum. This is a NON     *)\n(*                   EXTENSIONAL notation: the exact boolean expression is   *)\n(*                   inferred from the syntactic form of S (expanding        *)\n(*                   definitions, however); both (\\sum_(i | _) _)%MS and     *)\n(*                   (_ + _)%MS sums are recognized. This construct uses a   *)\n(*                   variant of the reflexive (\"quote\") canonical structure, *)\n(*                   mxsum_expr. The structure also recognizes sums of       *)\n(*                   matrix ranks, so that lemmas concerning the rank of     *)\n(*                   direct sums can be used bidirectionally.                *)\n(* The next set of definitions let us represent F-algebras using matrices:   *)\n(*   'A[F]_(m, n) == the type of matrices encoding (sub)algebras of square   *)\n(*                   n x n matrices, via mxvec; as in the matrix type        *)\n(*                   notation, m and F can be omitted (m defaults to n ^ 2). *)\n(*                := 'M[F]_(m, n ^ 2).                                       *)\n(*   (A \\in R)%MS <=> the square matrix A belongs to the linear set of       *)\n(*                    matrices (most often, a sub-algebra) encoded by the    *)\n(*                    row space of R. This is simply notation, so all the    *)\n(*                    lemmas and rewrite rules for (_ <= _)%MS can apply.    *)\n(*                := (mxvec A <= R)%MS.                                      *)\n(*     (R * S)%MS == a square n^2 x n^2 matrix whose row-space encodes the   *)\n(*                   linear set of n x n matrices generated by the pointwise *)\n(*                   product of the sets of matrices encoded by R and S.     *)\n(*       'C(R)%MS == a square matric encoding the centraliser of the set of  *)\n(*                   square matrices encoded by R.                           *)\n(*     'C_S(R)%MS := (S :&: 'C(R))%MS (the centraliser of R in S).           *)\n(*       'Z(R)%MS == the center of R (i.e., 'C_R(R)%MS).                     *)\n(*  left_mx_ideal R S <=> S is a left ideal for R (R * S <= S)%MS.           *)\n(* right_mx_ideal R S <=> S is a right ideal for R (S * R <= S)%MS.          *)\n(*       mx_ideal R S <=> S is a bilateral ideal for R.                      *)\n(*      mxring_id R e <-> e is an identity element for R (Prop predicate).   *)\n(*    has_mxring_id R <=> R has a nonzero identity element (bool predicate). *)\n(*           mxring R <=> R encodes a nontrivial subring.                    *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope.\nImport GRing.Theory.\nOpen Local Scope ring_scope.\n\nReserved Notation \"\\rank A\" (at level 10, A at level 8, format \"\\rank  A\").\nReserved Notation \"A ^C\"    (at level 8, format \"A ^C\").\n\nNotation \"''A_' ( m , n )\" := 'M_(m, n ^ 2)\n  (at level 8, format \"''A_' ( m ,  n )\") : type_scope.\n\nNotation \"''A_' ( n )\" := 'A_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A_' n\" := 'A_(n)\n  (at level 8, n at next level, format \"''A_' n\") : type_scope.\n\nNotation \"''A' [ F ]_ ( m , n )\" := 'M[F]_(m, n ^ 2)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ ( n )\" := 'A[F]_(n ^ 2, n)\n  (at level 8, only parsing) : type_scope.\n\nNotation \"''A' [ F ]_ n\" := 'A[F]_(n)\n  (at level 8, n at level 2, only parsing) : type_scope.\n\nDelimit Scope matrix_set_scope with MS.\n\nNotation Local simp := (Monoid.Theory.simpm, oppr0).\n\n(*****************************************************************************)\n(******************** Rank and row-space theory ******************************)\n(*****************************************************************************)\n\nSection RowSpaceTheory.\n\nVariable F : fieldType.\nImplicit Types m n p r : nat.\n\nLocal Notation \"''M_' ( m , n )\" := 'M[F]_(m, n) : type_scope.\nLocal Notation \"''M_' n\" := 'M[F]_(n, n) : type_scope.\n\n(* Decomposition with double pivoting; computes the rank, row and column  *)\n(* images, kernels, and complements of a matrix.                          *)\n\nFixpoint Gaussian_elimination {m n} : 'M_(m, n) -> 'M_m * 'M_n * nat :=\n  match m, n with\n  | _.+1, _.+1 => fun A : 'M_(1 + _, 1 + _) =>\n    if [pick ij | A ij.1 ij.2 != 0] is Some (i, j) then\n      let a := A i j in let A1 := xrow i 0 (xcol j 0 A) in\n      let u := ursubmx A1 in let v := a^-1 *: dlsubmx A1 in\n      let: (L, U, r) := Gaussian_elimination (drsubmx A1 - v *m u) in\n      (xrow i 0 (block_mx 1 0 v L), xcol j 0 (block_mx a%:M u 0 U), r.+1)\n    else (1%:M, 1%:M, 0%N)\n  | _, _ => fun _ => (1%:M, 1%:M, 0%N)\n  end.\n\nSection Defs.\n\nVariables (m n : nat) (A : 'M_(m, n)).\n\nFact Gaussian_elimination_key : unit. Proof. by []. Qed.\n\nLet LUr := locked_with Gaussian_elimination_key (@Gaussian_elimination) m n A.\n\nDefinition col_ebase := LUr.1.1.\nDefinition row_ebase := LUr.1.2.\nDefinition mxrank := if [|| m == 0 | n == 0]%N then 0%N else LUr.2.\n\nDefinition row_free := mxrank == m.\nDefinition row_full := mxrank == n.\n\nDefinition row_base : 'M_(mxrank, n) := pid_mx mxrank *m row_ebase.\nDefinition col_base : 'M_(m, mxrank) := col_ebase *m pid_mx mxrank.\n\nDefinition complmx : 'M_n := copid_mx mxrank *m row_ebase.\nDefinition kermx : 'M_m := copid_mx mxrank *m invmx col_ebase.\nDefinition cokermx : 'M_n := invmx row_ebase *m copid_mx mxrank.\n\nDefinition pinvmx : 'M_(n, m) :=\n  invmx row_ebase *m pid_mx mxrank *m invmx col_ebase.\n\nEnd Defs.\n\nArguments Scope mxrank [nat_scope nat_scope matrix_set_scope].\nLocal Notation \"\\rank A\" := (mxrank A) : nat_scope.\nArguments Scope complmx [nat_scope nat_scope matrix_set_scope].\nLocal Notation \"A ^C\" := (complmx A) : matrix_set_scope.\n\nDefinition submx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  A *m cokermx B == 0).\nFact submx_key : unit. Proof. by []. Qed.\nDefinition submx := locked_with submx_key submx_def.\nCanonical submx_unlockable := [unlockable fun submx].\n\nArguments Scope submx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits submx.\nLocal Notation \"A <= B\" := (submx A B) : matrix_set_scope.\nLocal Notation \"A <= B <= C\" := ((A <= B) && (B <= C))%MS : matrix_set_scope.\nLocal Notation \"A == B\" := (A <= B <= A)%MS : matrix_set_scope.\n\nDefinition ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  (A <= B)%MS && ~~ (B <= A)%MS.\nArguments Scope ltmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits ltmx.\nLocal Notation \"A < B\" := (ltmx A B) : matrix_set_scope.\n\nDefinition eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  prod (\\rank A = \\rank B)\n       (forall m3 (C : 'M_(m3, n)),\n            ((A <= C) = (B <= C)) * ((C <= A) = (C <= B)))%MS.\nArguments Scope eqmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nLocal Notation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\n\nSection LtmxIdentities.\n\nVariables (m1 m2 n : nat) (A : 'M_(m1, n)) (B : 'M_(m2, n)).\n\nLemma ltmxE : (A < B)%MS = ((A <= B)%MS && ~~ (B <= A)%MS). Proof. by []. Qed.\n\nLemma ltmxW : (A < B)%MS -> (A <= B)%MS. Proof. by case/andP. Qed.\n\nLemma ltmxEneq : (A < B)%MS = (A <= B)%MS && ~~ (A == B)%MS.\nProof. by apply: andb_id2l => ->. Qed.\n\nLemma submxElt : (A <= B)%MS = (A == B)%MS || (A < B)%MS.\nProof. by rewrite -andb_orr orbN andbT. Qed.\n\nEnd LtmxIdentities.\n\n(* The definition of the row-space operator is rigged to return the identity  *)\n(* matrix for full matrices. To allow for further tweaks that will make the   *)\n(* row-space intersection operator strictly commutative and monoidal, we      *)\n(* slightly generalize some auxiliary definitions: we parametrize the         *)\n(* \"equivalent subspace and identity\" choice predicate equivmx by a boolean   *)\n(* determining whether the matrix should be the identity (so for genmx A its  *)\n(* value is row_full A), and introduce a \"quasi-identity\" predicate qidmx     *)\n(* that selects non-square full matrices along with the identity matrix 1%:M  *)\n(* (this does not affect genmx, which chooses a square matrix).               *)\n(*   The choice witness for genmx A is either 1%:M for a row-full A, or else  *)\n(* row_base A padded with null rows.                                          *)\nLet qidmx m n (A : 'M_(m, n)) :=\n  if m == n then A == pid_mx n else row_full A.\nLet equivmx m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  (B == A)%MS && (qidmx B == idA).\nLet equivmx_spec m n (A : 'M_(m, n)) idA (B : 'M_n) :=\n  prod (B :=: A)%MS (qidmx B = idA).\nDefinition genmx_witness m n (A : 'M_(m, n)) : 'M_n :=\n  if row_full A then 1%:M else pid_mx (\\rank A) *m row_ebase A.\nDefinition genmx_def := idfun (fun m n (A : 'M_(m, n)) =>\n   choose (equivmx A (row_full A)) (genmx_witness A) : 'M_n).\nFact genmx_key : unit. Proof. by []. Qed.\nDefinition genmx := locked_with genmx_key genmx_def.\nCanonical genmx_unlockable := [unlockable fun genmx].\nLocal Notation \"<< A >>\" := (genmx A) : matrix_set_scope.\n\n(* The setwise sum is tweaked so that 0 is a strict identity element for      *)\n(* square matrices, because this lets us use the bigop component. As a result *)\n(* setwise sum is not quite strictly extensional.                             *)\nLet addsmx_nop m n (A : 'M_(m, n)) := conform_mx <<A>>%MS A.\nDefinition addsmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if A == 0 then addsmx_nop B else if B == 0 then addsmx_nop A else\n  <<col_mx A B>>%MS : 'M_n).\nFact addsmx_key : unit. Proof. by []. Qed.\nDefinition addsmx := locked_with addsmx_key addsmx_def.\nCanonical addsmx_unlockable := [unlockable fun addsmx].\nArguments Scope addsmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits addsmx.\nLocal Notation \"A + B\" := (addsmx A B) : matrix_set_scope.\nLocal Notation \"\\sum_ ( i | P ) B\" := (\\big[addsmx/0]_(i | P) B%MS)\n  : matrix_set_scope.\nLocal Notation \"\\sum_ ( i <- r | P ) B\" := (\\big[addsmx/0]_(i <- r | P) B%MS)\n  : matrix_set_scope.\n\n(* The set intersection is similarly biased so that the identity matrix is a  *)\n(* strict identity. This is somewhat more delicate than for the sum, because  *)\n(* the test for the identity is non-extensional. This forces us to actually   *)\n(* bias the choice operator so that it does not accidentally map an           *)\n(* intersection of non-identity matrices to 1%:M; this would spoil            *)\n(* associativity: if B :&: C = 1%:M but B and C are not identity, then for a  *)\n(* square matrix A we have A :&: (B :&: C) = A != (A :&: B) :&: C in general. *)\n(* To complicate matters there may not be a square non-singular matrix        *)\n(* different than 1%:M, since we could be dealing with 'M['F_2]_1. We         *)\n(* sidestep the issue by making all non-square row-full matrices identities,  *)\n(* and choosing a normal representative that preserves the qidmx property.    *)\n(* Thus A :&: B = 1%:M iff A and B are both identities, and this suffices for *)\n(* showing that associativity is strict.                                      *)\nLet capmx_witness m n (A : 'M_(m, n)) :=\n  if row_full A then conform_mx 1%:M A else <<A>>%MS.\nLet capmx_norm m n (A : 'M_(m, n)) :=\n  choose (equivmx A (qidmx A)) (capmx_witness A).\nLet capmx_nop m n (A : 'M_(m, n)) := conform_mx (capmx_norm A) A.\nDefinition capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :=\n  lsubmx (kermx (col_mx A B)) *m A.\nDefinition capmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  if qidmx A then capmx_nop B else\n  if qidmx B then capmx_nop A else\n  if row_full B then capmx_norm A else capmx_norm (capmx_gen A B) : 'M_n).\nFact capmx_key : unit. Proof. by []. Qed.\nDefinition capmx := locked_with capmx_key capmx_def.\nCanonical capmx_unlockable := [unlockable fun capmx].\nArguments Scope capmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits capmx.\nLocal Notation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nLocal Notation \"\\bigcap_ ( i | P ) B\" := (\\big[capmx/1%:M]_(i | P) B)\n  : matrix_set_scope.\n\nDefinition diffmx_def := idfun (fun m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) =>\n  <<capmx_gen A (capmx_gen A B)^C>>%MS : 'M_n).\nFact diffmx_key : unit. Proof. by []. Qed.\nDefinition diffmx := locked_with diffmx_key diffmx_def.\nCanonical diffmx_unlockable := [unlockable fun diffmx].\nArguments Scope diffmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits diffmx.\nLocal Notation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\n\nDefinition proj_mx n (U V : 'M_n) : 'M_n := pinvmx (col_mx U V) *m col_mx U 0.\n\nLocal Notation GaussE := Gaussian_elimination.\n\nFact mxrankE m n (A : 'M_(m, n)) : \\rank A = (GaussE A).2.\nProof. by rewrite /mxrank unlock /=; case: m n A => [|m] [|n]. Qed.\n\nLemma rank_leq_row m n (A : 'M_(m, n)) : \\rank A <= m.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma row_leq_rank m n (A : 'M_(m, n)) : (m <= \\rank A) = row_free A.\nProof. by rewrite /row_free eqn_leq rank_leq_row. Qed.\n\nLemma rank_leq_col m n (A : 'M_(m, n)) : \\rank A <= n.\nProof.\nrewrite mxrankE.\nelim: m n A => [|m IHm] [|n] //= A; case: pickP => [[i j] _|] //=.\nby move: (_ - _) => B; case: GaussE (IHm _ B) => [[L U] r] /=.\nQed.\n\nLemma col_leq_rank m n (A : 'M_(m, n)) : (n <= \\rank A) = row_full A.\nProof. by rewrite /row_full eqn_leq rank_leq_col. Qed.\n\nLet unitmx1F := @unitmx1 F.\nLemma row_ebase_unit m n (A : 'M_(m, n)) : row_ebase A \\in unitmx.\nProof.\nrewrite /row_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] /= nzAij | //=]; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uU.\nrewrite unitmxE xcolE det_mulmx (@det_ublock _ 1) det_scalar1 !unitrM.\nby rewrite unitfE nzAij -!unitmxE uU unitmx_perm.\nQed.\n\nLemma col_ebase_unit m n (A : 'M_(m, n)) : col_ebase A \\in unitmx.\nProof.\nrewrite /col_ebase unlock; elim: m n A => [|m IHm] [|n] //= A.\ncase: pickP => [[i j] _|] //=; move: (_ - _) => B.\ncase: GaussE (IHm _ B) => [[L U] r] /= uL.\nrewrite unitmxE xrowE det_mulmx (@det_lblock _ 1) det1 mul1r unitrM.\nby rewrite -unitmxE unitmx_perm.\nQed.\nHint Resolve rank_leq_row rank_leq_col row_ebase_unit col_ebase_unit.\n\nLemma mulmx_ebase m n (A : 'M_(m, n)) :\n  col_ebase A *m pid_mx (\\rank A) *m row_ebase A = A.\nProof.\nrewrite mxrankE /col_ebase /row_ebase unlock.\nelim: m n A => [n A | m IHm]; first by rewrite [A]flatmx0 [_ *m _]flatmx0.\ncase=> [A | n]; first by rewrite [_ *m _]thinmx0 [A]thinmx0.\nrewrite -(add1n m) -?(add1n n) => A /=.\ncase: pickP => [[i0 j0] | A0] /=; last first.\n  apply/matrixP=> i j; rewrite pid_mx_0 mulmx0 mul0mx mxE.\n  by move/eqP: (A0 (i, j)).\nset a := A i0 j0 => nz_a; set A1 := xrow _ _ _.\nset u := ursubmx _; set v := _ *: _; set B : 'M_(m, n) := _ - _.\nmove: (rank_leq_col B) (rank_leq_row B) {IHm}(IHm n B); rewrite mxrankE.\ncase: (GaussE B) => [[L U] r] /= r_m r_n defB.\nhave ->: pid_mx (1 + r) = block_mx 1 0 0 (pid_mx r) :> 'M[F]_(1 + m, 1 + n).\n  rewrite -(subnKC r_m) -(subnKC r_n) pid_mx_block -col_mx0 -row_mx0.\n  by rewrite block_mxA castmx_id col_mx0 row_mx0 -scalar_mx_block -pid_mx_block.\nrewrite xcolE xrowE mulmxA -xcolE -!mulmxA.\nrewrite !(addr0, add0r, mulmx0, mul0mx, mulmx_block, mul1mx) mulmxA defB.\nrewrite addrC subrK mul_mx_scalar scalerA divff // scale1r.\nhave ->: a%:M = ulsubmx A1 by rewrite [_ A1]mx11_scalar !mxE !lshift0 !tpermR.\nrewrite submxK /A1 xrowE !xcolE -!mulmxA mulmxA -!perm_mxM !tperm2 !perm_mx1.\nby rewrite mulmx1 mul1mx.\nQed.\n\nLemma mulmx_base m n (A : 'M_(m, n)) : col_base A *m row_base A = A.\nProof. by rewrite mulmxA -[col_base A *m _]mulmxA pid_mx_id ?mulmx_ebase. Qed.\n\nLemma mulmx1_min_rank r m n (A : 'M_(m, n)) M N :\n  M *m A *m N = 1%:M :> 'M_r -> r <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) mulmxA -mulmxA; move/mulmx1_min. Qed.\nImplicit Arguments mulmx1_min_rank [r m n A].\n\nLemma mulmx_max_rank r m n (M : 'M_(m, r)) (N : 'M_(r, n)) :\n  \\rank (M *m N) <= r.\nProof.\nset MN := M *m N; set rMN := \\rank _.\npose L : 'M_(rMN, m) := pid_mx rMN *m invmx (col_ebase MN).\npose U : 'M_(n, rMN) := invmx (row_ebase MN) *m pid_mx rMN.\nsuffices: L *m M *m (N *m U) = 1%:M by exact: mulmx1_min.\nrewrite mulmxA -(mulmxA L) -[M *m N]mulmx_ebase -/MN.\nby rewrite !mulmxA mulmxKV // mulmxK // !pid_mx_id /rMN ?pid_mx_1.\nQed.\nImplicit Arguments mulmx_max_rank [r m n].\n\nLemma mxrank_tr m n (A : 'M_(m, n)) : \\rank A^T = \\rank A.\nProof.\napply/eqP; rewrite eqn_leq -{3}[A]trmxK -{1}(mulmx_base A) -{1}(mulmx_base A^T).\nby rewrite !trmx_mul !mulmx_max_rank.\nQed.\n\nLemma mxrank_add m n (A B : 'M_(m, n)) : \\rank (A + B)%R <= \\rank A + \\rank B.\nProof.\nby rewrite -{1}(mulmx_base A) -{1}(mulmx_base B) -mul_row_col mulmx_max_rank.\nQed.\n\nLemma mxrankM_maxl m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank A.\nProof. by rewrite -{1}(mulmx_base A) -mulmxA mulmx_max_rank. Qed.\n\nLemma mxrankM_maxr m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank (A *m B) <= \\rank B.\nProof. by rewrite -mxrank_tr -(mxrank_tr B) trmx_mul mxrankM_maxl. Qed.\n\nLemma mxrank_scale m n a (A : 'M_(m, n)) : \\rank (a *: A) <= \\rank A.\nProof. by rewrite -mul_scalar_mx mxrankM_maxr. Qed.\n\nLemma mxrank_scale_nz m n a (A : 'M_(m, n)) :\n   a != 0 -> \\rank (a *: A) = \\rank A.\nProof.\nmove=> nza; apply/eqP; rewrite eqn_leq -{3}[A]scale1r -(mulVf nza).\nby rewrite -scalerA !mxrank_scale.\nQed.\n\nLemma mxrank_opp m n (A : 'M_(m, n)) : \\rank (- A) = \\rank A.\nProof. by rewrite -scaleN1r mxrank_scale_nz // oppr_eq0 oner_eq0. Qed.\n\nLemma mxrank0 m n : \\rank (0 : 'M_(m, n)) = 0%N.\nProof. by apply/eqP; rewrite -leqn0 -(@mulmx0 _ m 0 n 0) mulmx_max_rank. Qed.\n\nLemma mxrank_eq0 m n (A : 'M_(m, n)) : (\\rank A == 0%N) = (A == 0).\nProof.\napply/eqP/eqP=> [rA0 | ->{A}]; last exact: mxrank0.\nmove: (col_base A) (row_base A) (mulmx_base A); rewrite rA0 => Ac Ar <-.\nby rewrite [Ac]thinmx0 mul0mx.\nQed.\n\nLemma mulmx_coker m n (A : 'M_(m, n)) : A *m cokermx A = 0.\nProof.\nby rewrite -{1}[A]mulmx_ebase -!mulmxA mulKVmx // mul_pid_mx_copid ?mulmx0.\nQed.\n\nLemma submxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS = (A *m cokermx B == 0).\nProof. by rewrite unlock. Qed.\n\nLemma mulmxKpV m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> A *m pinvmx B *m B = A.\nProof.\nrewrite submxE !mulmxA mulmxBr mulmx1 subr_eq0 => /eqP defA.\nrewrite -{4}[B]mulmx_ebase -!mulmxA mulKmx //.\nby rewrite (mulmxA (pid_mx _)) pid_mx_id // !mulmxA -{}defA mulmxKV.\nQed.\n\nLemma submxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists D, A = D *m B) (A <= B)%MS.\nProof.\napply: (iffP idP) => [/mulmxKpV | [D ->]]; first by exists (A *m pinvmx B).\nby rewrite submxE -mulmxA mulmx_coker mulmx0.\nQed.\nImplicit Arguments submxP [m1 m2 n A B].\n\nLemma submx_refl m n (A : 'M_(m, n)) : (A <= A)%MS.\nProof. by rewrite submxE mulmx_coker. Qed.\nHint Resolve submx_refl.\n\nLemma submxMl m n p (D : 'M_(m, n)) (A : 'M_(n, p)) : (D *m A <= A)%MS.\nProof. by rewrite submxE -mulmxA mulmx_coker mulmx0. Qed.\n\nLemma submxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A <= B)%MS -> (A *m C <= B *m C)%MS.\nProof. by case/submxP=> D ->; rewrite -mulmxA submxMl. Qed.\n\nLemma mulmx_sub m n1 n2 p (C : 'M_(m, n1)) A (B : 'M_(n2, p)) :\n  (A <= B -> C *m A <= B)%MS.\nProof. by case/submxP=> D ->; rewrite mulmxA submxMl. Qed.\n\nLemma submx_trans m1 m2 m3 n\n                 (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B -> B <= C -> A <= C)%MS.\nProof. by case/submxP=> D ->{A}; exact: mulmx_sub. Qed.\n\nLemma ltmx_sub_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A < B)%MS -> (B <= C)%MS -> (A < C)%MS.\nProof.\ncase/andP=> sAB ltAB sBC; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltAB; exact: submx_trans.\nQed.\n\nLemma sub_ltmx_trans m1 m2 m3 n\n                     (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= B)%MS -> (B < C)%MS -> (A < C)%MS.\nProof.\nmove=> sAB /andP[sBC ltBC]; rewrite ltmxE (submx_trans sAB) //.\nby apply: contra ltBC => sCA; exact: submx_trans sAB.\nQed.\n\nLemma ltmx_trans m n : transitive (@ltmx m m n).\nProof. by move=> A B C; move/ltmxW; exact: sub_ltmx_trans. Qed.\n\nLemma ltmx_irrefl m n : irreflexive (@ltmx m m n).\nProof. by move=> A; rewrite /ltmx submx_refl andbF. Qed.\n\nLemma sub0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) <= A)%MS.\nProof. by rewrite submxE mul0mx. Qed.\n\nLemma submx0null m1 m2 n (A : 'M[F]_(m1, n)) :\n  (A <= (0 : 'M_(m2, n)))%MS -> A = 0.\nProof. by case/submxP=> D; rewrite mulmx0. Qed.\n\nLemma submx0 m n (A : 'M_(m, n)) : (A <= (0 : 'M_n))%MS = (A == 0).\nProof. by apply/idP/eqP=> [|->]; [exact: submx0null | exact: sub0mx]. Qed.\n\nLemma lt0mx m n (A : 'M_(m, n)) : ((0 : 'M_n) < A)%MS = (A != 0).\nProof. by rewrite /ltmx sub0mx submx0. Qed.\n\nLemma ltmx0 m n (A : 'M[F]_(m, n)) : (A < (0 : 'M_n))%MS = false.\nProof. by rewrite /ltmx sub0mx andbF. Qed.\n\nLemma eqmx0P m n (A : 'M_(m, n)) : reflect (A = 0) (A == (0 : 'M_n))%MS.\nProof. by rewrite submx0 sub0mx andbT; exact: eqP. Qed.\n\nLemma eqmx_eq0 m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (A == 0) = (B == 0).\nProof. by move=> eqAB; rewrite -!submx0 eqAB. Qed.\n\nLemma addmx_sub m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= C)%MS -> (B <= C)%MS -> ((A + B)%R <= C)%MS.\nProof.\nby case/submxP=> A' ->; case/submxP=> B' ->; rewrite -mulmxDl submxMl.\nQed.\n\nLemma summx_sub m1 m2 n (B : 'M_(m2, n))\n                I (r : seq I) (P : pred I) (A_ : I -> 'M_(m1, n)) :\n  (forall i, P i -> A_ i <= B)%MS -> ((\\sum_(i <- r | P i) A_ i)%R <= B)%MS.\nProof.\nmove=> leAB; elim/big_ind: _ => // [|A1 A2]; [exact: sub0mx | exact: addmx_sub].\nQed.\n\nLemma scalemx_sub m1 m2 n a (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> (a *: A <= B)%MS.\nProof. by case/submxP=> A' ->; rewrite scalemxAl submxMl. Qed.\n\nLemma row_sub m n i (A : 'M_(m, n)) : (row i A <= A)%MS.\nProof. by rewrite rowE submxMl. Qed.\n\nLemma eq_row_sub m n v (A : 'M_(m, n)) i : row i A = v -> (v <= A)%MS.\nProof. by move <-; rewrite row_sub. Qed.\n\nLemma nz_row_sub m n (A : 'M_(m, n)) : (nz_row A <= A)%MS.\nProof. by rewrite /nz_row; case: pickP => [i|] _; rewrite ?row_sub ?sub0mx. Qed.\n\nLemma row_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall i, row i A <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i|sAB].\n  by apply: submx_trans sAB; exact: row_sub.\nrewrite submxE; apply/eqP/row_matrixP=> i; apply/eqP.\nby rewrite row_mul row0 -submxE.\nQed.\nImplicit Arguments row_subP [m1 m2 n A B].\n\nLemma rV_subP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v <= B)%MS (A <= B)%MS.\nProof.\napply: (iffP idP) => [sAB v Av | sAB]; first exact: submx_trans sAB.\nby apply/row_subP=> i; rewrite sAB ?row_sub.\nQed.\nImplicit Arguments rV_subP [m1 m2 n A B].\n\nLemma row_subPn m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (exists i, ~~ (row i A <= B)%MS) (~~ (A <= B)%MS).\nProof. by rewrite (sameP row_subP forallP) negb_forall; exact: existsP. Qed.\n\nLemma sub_rVP n (u v : 'rV_n) : reflect (exists a, u = a *: v) (u <= v)%MS.\nProof.\napply: (iffP submxP) => [[w ->] | [a ->]].\n  by exists (w 0 0); rewrite -mul_scalar_mx -mx11_scalar.\nby exists a%:M; rewrite mul_scalar_mx.\nQed.\n\nLemma rank_rV n (v : 'rV_n) : \\rank v = (v != 0).\nProof.\ncase: eqP => [-> | nz_v]; first by rewrite mxrank0.\nby apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0; exact/eqP.\nQed.\n\nLemma rowV0Pn m n (A : 'M_(m, n)) :\n  reflect (exists2 v : 'rV_n, v <= A & v != 0)%MS (A != 0).\nProof.\nrewrite -submx0; apply: (iffP idP) => [| [v svA]]; last first.\n  by rewrite -submx0; exact: contra (submx_trans _).\nby case/row_subPn=> i; rewrite submx0; exists (row i A); rewrite ?row_sub.\nQed.\n\nLemma rowV0P m n (A : 'M_(m, n)) :\n  reflect (forall v : 'rV_n, v <= A -> v = 0)%MS (A == 0).\nProof.\nrewrite -[A == 0]negbK; case: rowV0Pn => IH.\n  by right; case: IH => v svA nzv IH; case/eqP: nzv; exact: IH.\nby left=> v svA; apply/eqP; apply/idPn=> nzv; case: IH; exists v.\nQed.\n\nLemma submx_full m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A <= B)%MS.\nProof.\nby rewrite submxE /cokermx =>/eqnP->; rewrite /copid_mx pid_mx_1 subrr !mulmx0.\nQed.\n\nLemma row_fullP m n (A : 'M_(m, n)) :\n  reflect (exists B, B *m A = 1%:M) (row_full A).\nProof.\napply: (iffP idP) => [Afull | [B kA]].\n  by exists (1%:M *m pinvmx A); apply: mulmxKpV (submx_full _ Afull).\nby rewrite [_ A]eqn_leq rank_leq_col (mulmx1_min_rank B 1%:M) ?mulmx1.\nQed.\nImplicit Arguments row_fullP [m n A].\n\nLemma row_full_inj m n p A : row_full A -> injective (@mulmx _ m n p A).\nProof.\ncase/row_fullP=> A' A'K; apply: can_inj (mulmx A') _ => B.\nby rewrite mulmxA A'K mul1mx.\nQed.\n\nLemma row_freeP m n (A : 'M_(m, n)) :\n  reflect (exists B, A *m B = 1%:M) (row_free A).\nProof.\nrewrite /row_free -mxrank_tr.\napply: (iffP row_fullP) => [] [B kA];\n  by exists B^T; rewrite -trmx1 -kA trmx_mul ?trmxK.\nQed.\n\nLemma row_free_inj m n p A : row_free A -> injective ((@mulmx _ m n p)^~ A).\nProof.\ncase/row_freeP=> A' AK; apply: can_inj (mulmx^~ A') _ => B.\nby rewrite -mulmxA AK mulmx1.\nQed.\n\nLemma row_free_unit n (A : 'M_n) : row_free A = (A \\in unitmx).\nProof.\napply/row_fullP/idP=> [[A'] | uA]; first by case/mulmx1_unit.\nby exists (invmx A); rewrite mulVmx.\nQed.\n\nLemma row_full_unit n (A : 'M_n) : row_full A = (A \\in unitmx).\nProof. exact: row_free_unit. Qed.\n  \nLemma mxrank_unit n (A : 'M_n) : A \\in unitmx -> \\rank A = n.\nProof. by rewrite -row_full_unit =>/eqnP. Qed.\n\nLemma mxrank1 n : \\rank (1%:M : 'M_n) = n.\nProof. by apply: mxrank_unit; exact: unitmx1. Qed.\n\nLemma mxrank_delta m n i j : \\rank (delta_mx i j : 'M_(m, n)) = 1%N.\nProof.\napply/eqP; rewrite eqn_leq lt0n mxrank_eq0.\nrewrite -{1}(mul_delta_mx (0 : 'I_1)) mulmx_max_rank.\nby apply/eqP; move/matrixP; move/(_ i j); move/eqP; rewrite !mxE !eqxx oner_eq0.\nQed.\n\nLemma mxrankS m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B.\nProof. by case/submxP=> D ->; rewrite mxrankM_maxr. Qed.\n\nLemma submx1 m n (A : 'M_(m, n)) : (A <= 1%:M)%MS.\nProof. by rewrite submx_full // row_full_unit unitmx1. Qed.\n\nLemma sub1mx m n (A : 'M_(m, n)) : (1%:M <= A)%MS = row_full A.\nProof.\napply/idP/idP; last exact: submx_full.\nby move/mxrankS; rewrite mxrank1 col_leq_rank.\nQed.\n\nLemma ltmx1 m n (A : 'M_(m, n)) : (A < 1%:M)%MS = ~~ row_full A.\nProof. by rewrite /ltmx sub1mx submx1. Qed.\n\nLemma lt1mx m n (A : 'M_(m, n)) : (1%:M < A)%MS = false.\nProof. by rewrite /ltmx submx1 andbF. Qed.\n\nLemma eqmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :=: B)%MS (A == B)%MS.\nProof.\napply: (iffP andP) => [[sAB sBA] | eqAB]; last by rewrite !eqAB.\nsplit=> [|m3 C]; first by apply/eqP; rewrite eqn_leq !mxrankS.\nsplit; first by apply/idP/idP; exact: submx_trans.\nby apply/idP/idP=> sC; exact: submx_trans sC _.\nQed.\nImplicit Arguments eqmxP [m1 m2 n A B].\n\nLemma rV_eqP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (forall u : 'rV_n, (u <= A) = (u <= B))%MS (A == B)%MS.\nProof.\napply: (iffP idP) => [eqAB u | eqAB]; first by rewrite (eqmxP eqAB).\nby apply/andP; split; apply/rV_subP=> u; rewrite eqAB.\nQed.\n\nLemma eqmx_refl m1 n (A : 'M_(m1, n)) : (A :=: A)%MS.\nProof. by []. Qed.\n\nLemma eqmx_sym m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B)%MS -> (B :=: A)%MS.\nProof. by move=> eqAB; split=> [|m3 C]; rewrite !eqAB. Qed.\n\nLemma eqmx_trans m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :=: B)%MS -> (B :=: C)%MS -> (A :=: C)%MS.\nProof. by move=> eqAB eqBC; split=> [|m4 D]; rewrite !eqAB !eqBC. Qed.\n\nLemma eqmx_rank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A == B)%MS -> \\rank A = \\rank B.\nProof. by move/eqmxP->. Qed.\n\nLemma lt_eqmx m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n    (A :=: B)%MS ->\n  forall C : 'M_(m3, n), (((A < C) = (B < C))%MS * ((C < A) = (C < B))%MS)%type.\nProof. by move=> eqAB C; rewrite /ltmx !eqAB. Qed.\n\nLemma eqmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  (A :=: B)%MS -> (A *m C :=: B *m C)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !submxMr ?eqAB. Qed.\n\nLemma eqmxMfull m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_full A -> (A *m B :=: B)%MS.\nProof.\ncase/row_fullP=> A' A'A; apply/eqmxP; rewrite submxMl /=.\nby apply/submxP; exists A'; rewrite mulmxA A'A mul1mx.\nQed.\n\nLemma eqmx0 m n : ((0 : 'M[F]_(m, n)) :=: (0 : 'M_n))%MS.\nProof. by apply/eqmxP; rewrite !sub0mx. Qed.\n\nLemma eqmx_scale m n a (A : 'M_(m, n)) : a != 0 -> (a *: A :=: A)%MS.\nProof.\nmove=> nz_a; apply/eqmxP; rewrite scalemx_sub //.\nby rewrite -{1}[A]scale1r -(mulVf nz_a) -scalerA scalemx_sub.\nQed.\n\nLemma eqmx_opp m n (A : 'M_(m, n)) : (- A :=: A)%MS.\nProof.\nby rewrite -scaleN1r; apply: eqmx_scale => //; rewrite oppr_eq0 oner_eq0.\nQed.\n\nLemma submxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C <= B *m C)%MS = (A <= B)%MS.\nProof.\ncase/row_freeP=> C' C_C'_1; apply/idP/idP=> sAB; last exact: submxMr.\nby rewrite -[A]mulmx1 -[B]mulmx1 -C_C'_1 !mulmxA submxMr.\nQed.\n\nLemma eqmxMfree m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  row_free C -> (A *m C :=: B *m C)%MS -> (A :=: B)%MS.\nProof.\nby move=> Cfree eqAB; apply/eqmxP; move/eqmxP: eqAB; rewrite !submxMfree.\nQed.\n\nLemma mxrankMfree m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  row_free B -> \\rank (A *m B) = \\rank A.\nProof.\nby move=> Bfree; rewrite -mxrank_tr trmx_mul eqmxMfull /row_full mxrank_tr.\nQed.\n\nLemma eq_row_base m n (A : 'M_(m, n)) : (row_base A :=: A)%MS.\nProof.\napply/eqmxP; apply/andP; split; apply/submxP.\n  exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n  by rewrite -{8}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\nexists (col_ebase A *m pid_mx (\\rank A)).\nby rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nQed.\n\nLet qidmx_eq1 n (A : 'M_n) : qidmx A = (A == 1%:M).\nProof. by rewrite /qidmx eqxx pid_mx_1. Qed.\n\nLet genmx_witnessP m n (A : 'M_(m, n)) :\n  equivmx A (row_full A) (genmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /genmx_witness.\ncase fullA: (row_full A); first by rewrite eqxx sub1mx submx1 fullA.\nset B := _ *m _; have defB : (B == A)%MS.\n  apply/andP; split; apply/submxP.\n    exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\n    by rewrite -{3}[A]mulmx_ebase !mulmxA mulmxKV // pid_mx_id.\n  exists (col_ebase A *m pid_mx (\\rank A)).\n  by rewrite mulmxA -(mulmxA _ _ (pid_mx _)) pid_mx_id // mulmx_ebase.\nrewrite defB -negb_add addbF; case: eqP defB => // ->.\nby rewrite sub1mx fullA.\nQed.\n\nLemma genmxE m n (A : 'M_(m, n)) : (<<A>> :=: A)%MS.\nProof.\nby rewrite unlock; apply/eqmxP; case/andP: (chooseP (genmx_witnessP A)).\nQed.\n\nLemma eq_genmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :=: B -> <<A>> = <<B>>)%MS.\nProof.\nmove=> eqAB; rewrite unlock.\nhave{eqAB} eqAB: equivmx A (row_full A) =1 equivmx B (row_full B).\n  by move=> C; rewrite /row_full /equivmx !eqAB.\nrewrite (eq_choose eqAB) (choose_id _ (genmx_witnessP B)) //.\nby rewrite -eqAB genmx_witnessP.\nQed.\n\nLemma genmxP m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (<<A>> = <<B>>)%MS (A == B)%MS.\nProof.\napply: (iffP idP) => eqAB; first exact: eq_genmx (eqmxP _).\nby rewrite -!(genmxE A) eqAB !genmxE andbb.\nQed.\nImplicit Arguments genmxP [m1 m2 n A B].\n\nLemma genmx0 m n : <<0 : 'M_(m, n)>>%MS = 0.\nProof. by apply/eqP; rewrite -submx0 genmxE sub0mx. Qed.\n\nLemma genmx1 n : <<1%:M : 'M_n>>%MS = 1%:M.\nProof.\nrewrite unlock; case/andP: (chooseP (@genmx_witnessP n n 1%:M)) => _ /eqP.\nby rewrite qidmx_eq1 row_full_unit unitmx1 => /eqP.\nQed.\n\nLemma genmx_id m n (A : 'M_(m, n)) : (<<<<A>>>> = <<A>>)%MS.\nProof. by apply: eq_genmx; exact: genmxE. Qed.\n\nLemma row_base_free m n (A : 'M_(m, n)) : row_free (row_base A).\nProof. by apply/eqnP; rewrite eq_row_base. Qed.\n\nLemma mxrank_gen m n (A : 'M_(m, n)) : \\rank <<A>> = \\rank A.\nProof. by rewrite genmxE. Qed.\n\nLemma col_base_full m n (A : 'M_(m, n)) : row_full (col_base A).\nProof.\napply/row_fullP; exists (pid_mx (\\rank A) *m invmx (col_ebase A)).\nby rewrite !mulmxA mulmxKV // pid_mx_id // pid_mx_1.\nQed.\nHint Resolve row_base_free col_base_full.\n\nLemma mxrank_leqif_sup m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (B <= A)%MS.\nProof.\nmove=> sAB; split; first by rewrite mxrankS.\napply/idP/idP=> [| sBA]; last by rewrite eqn_leq !mxrankS.\ncase/submxP: sAB => D ->; rewrite -{-2}(mulmx_base B) mulmxA.\nrewrite mxrankMfree // => /row_fullP[E kE].\nby rewrite -{1}[row_base B]mul1mx -kE -(mulmxA E) (mulmxA _ E) submxMl.\nQed.\n\nLemma mxrank_leqif_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A <= B)%MS -> \\rank A <= \\rank B ?= iff (A == B)%MS.\nProof. by move=> sAB; rewrite sAB; exact: mxrank_leqif_sup. Qed.\n\nLemma ltmxErank m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS = (A <= B)%MS && (\\rank A < \\rank B).\nProof.\nby apply: andb_id2l => sAB; rewrite (ltn_leqif (mxrank_leqif_sup sAB)).\nQed.\n\nLemma rank_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A < B)%MS -> \\rank A < \\rank B.\nProof. by rewrite ltmxErank => /andP[]. Qed.\n\nLemma eqmx_cast m1 m2 n (A : 'M_(m1, n)) e :\n  ((castmx e A : 'M_(m2, n)) :=: A)%MS.\nProof. by case: e A; case: m2 / => A e; rewrite castmx_id. Qed.\n\nLemma eqmx_conform m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (conform_mx A B :=: A \\/ conform_mx A B :=: B)%MS.\nProof.\ncase: (eqVneq m2 m1) => [-> | neqm12] in B *.\n  by right; rewrite conform_mx_id.\nby left; rewrite nonconform_mx ?neqm12.\nQed.\n\nLet eqmx_sum_nop m n (A : 'M_(m, n)) : (addsmx_nop A :=: A)%MS.\nProof.\ncase: (eqmx_conform <<A>>%MS A) => // eq_id_gen.\nexact: eqmx_trans (genmxE A).\nQed.\n\nSection AddsmxSub.\n\nVariable (m1 m2 n : nat) (A : 'M[F]_(m1, n)) (B : 'M[F]_(m2, n)).\n\nLemma col_mx_sub m3 (C : 'M_(m3, n)) :\n  (col_mx A B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof.\nrewrite !submxE mul_col_mx -col_mx0.\nby apply/eqP/andP; [case/eq_col_mx=> -> -> | case; do 2!move/eqP->].\nQed.\n\nLemma addsmxE : (A + B :=: col_mx A B)%MS.\nProof.\nhave:= submx_refl (col_mx A B); rewrite col_mx_sub; case/andP=> sAS sBS.\nrewrite unlock; do 2?case: eqP => [AB0 | _]; last exact: genmxE.\n  by apply/eqmxP; rewrite !eqmx_sum_nop sBS col_mx_sub AB0 sub0mx /=.\nby apply/eqmxP; rewrite !eqmx_sum_nop sAS col_mx_sub AB0 sub0mx andbT /=.\nQed.\n\nLemma addsmx_sub m3 (C : 'M_(m3, n)) :\n  (A + B <= C)%MS = (A <= C)%MS && (B <= C)%MS.\nProof. by rewrite addsmxE col_mx_sub. Qed.\n\nLemma addsmxSl : (A <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmxSr : (B <= A + B)%MS.\nProof. by have:= submx_refl (A + B)%MS; rewrite addsmx_sub; case/andP. Qed.\n\nLemma addsmx_idPr : reflect (A + B :=: B)%MS (A <= B)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS B.\nby rewrite addsmxSr addsmx_sub submx_refl !andbT.\nQed.\n\nLemma addsmx_idPl : reflect (A + B :=: A)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A + B)%MS A.\nby rewrite addsmxSl addsmx_sub submx_refl !andbT.\nQed.\n\nEnd AddsmxSub.\n\nLemma adds0mx m1 m2 n (B : 'M_(m2, n)) : ((0 : 'M_(m1, n)) + B :=: B)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSr /= andbT. Qed.\n\nLemma addsmx0 m1 m2 n (A : 'M_(m1, n)) : (A + (0 : 'M_(m2, n)) :=: A)%MS.\nProof. by apply/eqmxP; rewrite addsmx_sub sub0mx addsmxSl /= !andbT. Qed.\n\nLet addsmx_nop_eq0 m n (A : 'M_(m, n)) : (addsmx_nop A == 0) = (A == 0).\nProof. by rewrite -!submx0 eqmx_sum_nop. Qed.\n\nLet addsmx_nop0 m n : addsmx_nop (0 : 'M_(m, n)) = 0.\nProof. by apply/eqP; rewrite addsmx_nop_eq0. Qed.\n\nLet addsmx_nop_id n (A : 'M_n) : addsmx_nop A = A.\nProof. exact: conform_mx_id. Qed.\n\nLemma addsmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A + B = B + A)%MS.\nProof.\nhave: (A + B == B + A)%MS.\n  by apply/andP; rewrite !addsmx_sub andbC -addsmx_sub andbC -addsmx_sub.\nmove/genmxP; rewrite [@addsmx]unlock -!submx0 !submx0.\nby do 2!case: eqP => [// -> | _]; rewrite ?genmx_id ?addsmx_nop0.\nQed.\n\nLemma adds0mx_id m1 n (B : 'M_n) : ((0 : 'M_(m1, n)) + B)%MS = B.\nProof. by rewrite unlock eqxx addsmx_nop_id. Qed.\n\nLemma addsmx0_id m2 n (A : 'M_n) : (A + (0 : 'M_(m2, n)))%MS = A.\nProof. by rewrite addsmxC adds0mx_id. Qed.\n\nLemma addsmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A + (B + C) = A + B + C)%MS.\nProof.\nhave: (A + (B + C) :=: A + B + C)%MS.\n  by apply/eqmxP/andP; rewrite !addsmx_sub -andbA andbA -!addsmx_sub.\nrewrite {1 3}[in @addsmx m1]unlock [in @addsmx n]unlock !addsmx_nop_id -!submx0.\nrewrite !addsmx_sub ![@addsmx]unlock -!submx0; move/eq_genmx.\nby do 3!case: (_ <= 0)%MS; rewrite //= !genmx_id.\nQed.\n\nCanonical addsmx_monoid n :=\n  Monoid.Law (@addsmxA n n n n) (@adds0mx_id n n) (@addsmx0_id n n).\nCanonical addsmx_comoid n := Monoid.ComLaw (@addsmxC n n n).\n\nLemma addsmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A + B)%MS *m C :=: A *m C + B *m C)%MS.\nProof. by apply/eqmxP; rewrite !addsmxE -!mul_col_mx !submxMr ?addsmxE. Qed.\n\nLemma addsmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                            (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A + B <= C + D)%MS.\nProof.\nmove=> sAC sBD.\nby rewrite addsmx_sub {1}addsmxC !(submx_trans _ (addsmxSr _ _)).\nQed.\n\nLemma addmx_sub_adds m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m, n))\n                               (C : 'M_(m1, n)) (D : 'M_(m2, n)) :\n  (A <= C -> B <= D -> (A + B)%R <= C + D)%MS.\nProof.\nmove=> sAC; move/(addsmxS sAC); apply: submx_trans.\nby rewrite addmx_sub ?addsmxSl ?addsmxSr.\nQed.\n\nLemma addsmx_addKl n m1 m2 (A : 'M_(m1, n)) (B C : 'M_(m2, n)) :\n  (B <= A)%MS -> (A + (B + C)%R :=: A + C)%MS.\nProof.\nmove=> sBA; apply/eqmxP; rewrite !addsmx_sub !addsmxSl.\nby rewrite -{3}[C](addKr B) !addmx_sub_adds ?eqmx_opp.\nQed.\n\nLemma addsmx_addKr n m1 m2 (A B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (B <= C)%MS -> ((A + B)%R + C :=: A + C)%MS.\nProof. by rewrite -!(addsmxC C) addrC; exact: addsmx_addKl. Qed.\n\nLemma adds_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                              (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A + B :=: C + D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !addsmxS ?eqAC ?eqBD. Qed.\n\nLemma genmx_adds m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<(A + B)%MS>> = <<A>> + <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (adds_eqmx (genmxE A) (genmxE B))).\nby rewrite [@addsmx]unlock !addsmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\nQed.\n\nLemma sub_addsmxP m1 m2 m3 n\n                  (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  reflect (exists u, A = u.1 *m B + u.2 *m C) (A <= B + C)%MS.\nProof.\napply: (iffP idP) => [|[u ->]]; last by rewrite addmx_sub_adds ?submxMl.\nrewrite addsmxE; case/submxP=> u ->; exists (lsubmx u, rsubmx u).\nby rewrite -mul_row_col hsubmxK.\nQed.\nImplicit Arguments sub_addsmxP [m1 m2 m3 n A B C].\n\nVariable I : finType.\nImplicit Type P : pred I.\n\nLemma genmx_sums P n (B_ : I -> 'M_n) :\n  <<(\\sum_(i | P i) B_ i)%MS>>%MS = (\\sum_(i | P i) <<B_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_adds n n n) (@genmx0 n n)). Qed.\n\nLemma sumsmx_sup i0 P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  P i0 -> (A <= B_ i0)%MS -> (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\nby move=> Pi0 sAB; apply: submx_trans sAB _; rewrite (bigD1 i0) // addsmxSl.\nQed.\nImplicit Arguments sumsmx_sup [P m n A B_].\n\nLemma sumsmx_subP P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  reflect (forall i, P i -> A_ i <= B)%MS (\\sum_(i | P i) A_ i <= B)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: submx_trans sAB; apply: sumsmx_sup Pi _.\nby elim/big_rec: _ => [|i Ai Pi sAiB]; rewrite ?sub0mx // addsmx_sub sAB.\nQed.\n\nLemma summx_sub_sums P m n (A : I -> 'M[F]_(m, n)) B :\n    (forall i, P i -> A i <= B i)%MS ->\n  ((\\sum_(i | P i) A i)%R <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply: summx_sub => i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma sumsmxS P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i <= B i)%MS ->\n  (\\sum_(i | P i) A i <= \\sum_(i | P i) B i)%MS.\nProof.\nby move=> sAB; apply/sumsmx_subP=> i Pi; rewrite (sumsmx_sup i) ?sAB.\nQed.\n\nLemma eqmx_sums P n (A B : I -> 'M[F]_n) :\n    (forall i, P i -> A i :=: B i)%MS ->\n  (\\sum_(i | P i) A i :=: \\sum_(i | P i) B i)%MS.\nProof. by move=> eqAB; apply/eqmxP; rewrite !sumsmxS // => i; move/eqAB->. Qed.\n\nLemma sub_sumsmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (exists u_, A = \\sum_(i | P i) u_ i *m B_ i)\n          (A <= \\sum_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [| [u_ ->]]; last first.\n  by apply: summx_sub_sums => i _; exact: submxMl. \nelim: {P}_.+1 {-2}P A (ltnSn #|P|) => // b IHb P A.\ncase: (pickP P) => [i Pi | P0 _]; last first.\n  rewrite big_pred0 //; move/submx0null->.\n  by exists (fun _ => 0); rewrite big_pred0.\nrewrite (cardD1x Pi) (bigD1 i) //= => /IHb{b IHb} /= IHi /sub_addsmxP[u ->].\nhave [u_ ->] := IHi _ (submxMl u.2 _).\nexists [eta u_ with i |-> u.1]; rewrite (bigD1 i Pi) /= eqxx; congr (_ + _).\nby apply: eq_bigr => j /andP[_ /negPf->].\nQed.\n\nLemma sumsmxMr_gen P m n A (B : 'M[F]_(m, n)) :\n  ((\\sum_(i | P i) A i)%MS *m B :=: \\sum_(i | P i) <<A i *m B>>)%MS.\nProof.\napply/eqmxP/andP; split; last first.\n  by apply/sumsmx_subP=> i Pi; rewrite genmxE submxMr ?(sumsmx_sup i).\nhave [u ->] := sub_sumsmxP _ _ _ (submx_refl (\\sum_(i | P i) A i)%MS).\nby rewrite mulmx_suml summx_sub_sums // => i _; rewrite genmxE -mulmxA submxMl.\nQed.\n\nLemma sumsmxMr P n (A_ : I -> 'M[F]_n) (B : 'M_n) :\n  ((\\sum_(i | P i) A_ i)%MS *m B :=: \\sum_(i | P i) (A_ i *m B))%MS.\nProof.\nby apply: eqmx_trans (sumsmxMr_gen _ _ _) (eqmx_sums _) => i _; exact: genmxE.\nQed.\n\nLemma rank_pid_mx m n r : r <= m -> r <= n -> \\rank (pid_mx r : 'M_(m, n)) = r.\nProof.\ndo 2!move/subnKC <-; rewrite pid_mx_block block_mxEv row_mx0 -addsmxE addsmx0.\nby rewrite -mxrank_tr tr_row_mx trmx0 trmx1 -addsmxE addsmx0 mxrank1.\nQed.\n\nLemma rank_copid_mx n r : r <= n -> \\rank (copid_mx r : 'M_n) = (n - r)%N.\nProof.\nmove/subnKC <-; rewrite /copid_mx pid_mx_block scalar_mx_block.\nrewrite opp_block_mx !oppr0 add_block_mx !addr0 subrr block_mxEv row_mx0.\nrewrite -addsmxE adds0mx -mxrank_tr tr_row_mx trmx0 trmx1.\nby rewrite -addsmxE adds0mx mxrank1 addKn.\nQed.\n\nLemma mxrank_compl m n (A : 'M_(m, n)) : \\rank A^C = (n - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?rank_copid_mx. Qed.\n\nLemma mxrank_ker m n (A : 'M_(m, n)) : \\rank (kermx A) = (m - \\rank A)%N.\nProof. by rewrite mxrankMfree ?row_free_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma kermx_eq0 n m (A : 'M_(m, n)) : (kermx A == 0) = row_free A.\nProof. by rewrite -mxrank_eq0 mxrank_ker subn_eq0 row_leq_rank. Qed.\n\nLemma mxrank_coker m n (A : 'M_(m, n)) : \\rank (cokermx A) = (n - \\rank A)%N.\nProof. by rewrite eqmxMfull ?row_full_unit ?unitmx_inv ?rank_copid_mx. Qed.\n\nLemma cokermx_eq0 n m (A : 'M_(m, n)) : (cokermx A == 0) = row_full A.\nProof. by rewrite -mxrank_eq0 mxrank_coker subn_eq0 col_leq_rank. Qed.\n\nLemma mulmx_ker m n (A : 'M_(m, n)) : kermx A *m A = 0.\nProof.\nby rewrite -{2}[A]mulmx_ebase !mulmxA mulmxKV // mul_copid_mx_pid ?mul0mx.\nQed.\n\nLemma mulmxKV_ker m n p (A : 'M_(n, p)) (B : 'M_(m, n)) :\n  B *m A = 0 -> B *m col_ebase A *m kermx A = B.\nProof.\nrewrite mulmxA mulmxBr mulmx1 mulmxBl mulmxK //.\nrewrite -{1}[A]mulmx_ebase !mulmxA => /(canRL (mulmxK (row_ebase_unit A))).\nrewrite mul0mx // => BA0; apply: (canLR (addrK _)).\nby rewrite -(pid_mx_id _ _ n (rank_leq_col A)) mulmxA BA0 !mul0mx addr0.\nQed.\n\nLemma sub_kermxP p m n (A : 'M_(m, n)) (B : 'M_(p, m)) :\n  reflect (B *m A = 0) (B <= kermx A)%MS.\nProof.\napply: (iffP submxP) => [[D ->]|]; first by rewrite -mulmxA mulmx_ker mulmx0.\nby move/mulmxKV_ker; exists (B *m col_ebase A).\nQed.\n\nLemma mulmx0_rank_max m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  A *m B = 0 -> \\rank A + \\rank B <= n.\nProof.\nmove=> AB0; rewrite -{3}(subnK (rank_leq_row B)) leq_add2r.\nrewrite -mxrank_ker mxrankS //; exact/sub_kermxP.\nQed.\n\nLemma mxrank_Frobenius m n p q (A : 'M_(m, n)) B (C : 'M_(p, q)) :\n  \\rank (A *m B) + \\rank (B *m C) <= \\rank B + \\rank (A *m B *m C).\nProof.\nrewrite -{2}(mulmx_base (A *m B)) -mulmxA (eqmxMfull _ (col_base_full _)).\nset C2 := row_base _ *m C.\nrewrite -{1}(subnK (rank_leq_row C2)) -(mxrank_ker C2) addnAC leq_add2r. \nrewrite addnC -{1}(mulmx_base B) -mulmxA eqmxMfull //.\nset C1 := _ *m C; rewrite -{2}(subnKC (rank_leq_row C1)) leq_add2l -mxrank_ker.\nrewrite -(mxrankMfree _ (row_base_free (A *m B))).\nhave: (row_base (A *m B) <= row_base B)%MS by rewrite !eq_row_base submxMl.\ncase/submxP=> D defD; rewrite defD mulmxA mxrankMfree ?mxrankS //.\nby apply/sub_kermxP; rewrite -mulmxA (mulmxA D) -defD -/C2 mulmx_ker.\nQed.\n\nLemma mxrank_mul_min m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  \\rank A + \\rank B - n <= \\rank (A *m B).\nProof.\nby have:= mxrank_Frobenius A 1%:M B; rewrite mulmx1 mul1mx mxrank1 leq_subLR.\nQed.\n\nLemma addsmx_compl_full m n (A : 'M_(m, n)) : row_full (A + A^C)%MS.\nProof.\nrewrite /row_full addsmxE; apply/row_fullP.\nexists (row_mx (pinvmx A) (cokermx A)); rewrite mul_row_col.\nrewrite -{2}[A]mulmx_ebase -!mulmxA mulKmx // -mulmxDr !mulmxA.\nby rewrite pid_mx_id ?copid_mx_id // -mulmxDl addrC subrK mul1mx mulVmx.\nQed.\n\nLemma sub_capmx_gen m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= capmx_gen B C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof.\napply/idP/andP=> [sAI | [/submxP[B' ->{A}] /submxP[C' eqBC']]].\n  rewrite !(submx_trans sAI) ?submxMl // /capmx_gen.\n   have:= mulmx_ker (col_mx B C); set K := kermx _.\n   rewrite -{1}[K]hsubmxK mul_row_col; move/(canRL (addrK _))->.\n   by rewrite add0r -mulNmx submxMl.\nhave: (row_mx B' (- C') <= kermx (col_mx B C))%MS.\n  by apply/sub_kermxP; rewrite mul_row_col eqBC' mulNmx subrr.\ncase/submxP=> D; rewrite -[kermx _]hsubmxK mul_mx_row.\nby case/eq_row_mx=> -> _; rewrite -mulmxA submxMl.\nQed.\n\nLet capmx_witnessP m n (A : 'M_(m, n)) : equivmx A (qidmx A) (capmx_witness A).\nProof.\nrewrite /equivmx qidmx_eq1 /qidmx /capmx_witness.\nrewrite -sub1mx; case s1A: (1%:M <= A)%MS => /=; last first.\n  rewrite !genmxE submx_refl /= -negb_add; apply: contra {s1A}(negbT s1A).\n  case: eqP => [<- _| _]; first by rewrite genmxE.\n  by case: eqP A => //= -> A; move/eqP->; rewrite pid_mx_1.\ncase: (m =P n) => [-> | ne_mn] in A s1A *.\n  by rewrite conform_mx_id submx_refl pid_mx_1 eqxx.\nby rewrite nonconform_mx ?submx1 ?s1A ?eqxx //; case: eqP.\nQed.\n\nLet capmx_normP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_norm A).\nProof. by case/andP: (chooseP (capmx_witnessP A)) => /eqmxP defN /eqP. Qed.\n\nLet capmx_norm_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A == B)%MS -> capmx_norm A = capmx_norm B.\nProof.\nmove=> eqABid /eqmxP eqAB.\nhave{eqABid eqAB} eqAB: equivmx A (qidmx A) =1 equivmx B (qidmx B).\n  by move=> C; rewrite /equivmx eqABid !eqAB.\nrewrite {1}/capmx_norm (eq_choose eqAB).\nby apply: choose_id; first rewrite -eqAB; exact: capmx_witnessP.\nQed.\n\nLet capmx_nopP m n (A : 'M_(m, n)) : equivmx_spec A (qidmx A) (capmx_nop A).\nProof.\nrewrite /capmx_nop; case: (eqVneq m n) => [-> | ne_mn] in A *.\n  by rewrite conform_mx_id.\nrewrite nonconform_mx ?ne_mn //; exact: capmx_normP.\nQed.\n\nLet sub_qidmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx B -> (A <= B)%MS.\nProof.\nrewrite /qidmx => idB; apply: {A}submx_trans (submx1 A) _.\nby case: eqP B idB => [-> _ /eqP-> | _ B]; rewrite (=^~ sub1mx, pid_mx_1).\nQed.\n\nLet qidmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx (A :&: B)%MS = qidmx A && qidmx B.\nProof.\nrewrite unlock -sub1mx.\ncase idA: (qidmx A); case idB: (qidmx B); try by rewrite capmx_nopP.\ncase s1B: (_ <= B)%MS; first by rewrite capmx_normP.\napply/idP=> /(sub_qidmx 1%:M).\nby rewrite capmx_normP sub_capmx_gen s1B andbF.\nQed.\n\nLet capmx_eq_norm m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  qidmx A = qidmx B -> (A :&: B)%MS = capmx_norm (A :&: B)%MS.\nProof.\nmove=> eqABid; rewrite unlock -sub1mx {}eqABid.\nhave norm_id m (C : 'M_(m, n)) (N := capmx_norm C) : capmx_norm N = N.\n  by apply: capmx_norm_eq; rewrite ?capmx_normP ?andbb.\ncase idB: (qidmx B); last by case: ifP; rewrite norm_id.\nrewrite /capmx_nop; case: (eqVneq m2 n) => [-> | neqm2n] in B idB *.\n  have idN := idB; rewrite -{1}capmx_normP !qidmx_eq1 in idN idB.\n  by rewrite conform_mx_id (eqP idN) (eqP idB).\nby rewrite nonconform_mx ?neqm2n ?norm_id.\nQed.\n\nLemma capmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B :=: capmx_gen A B)%MS.\nProof.\nrewrite unlock -sub1mx; apply/eqmxP.\nhave:= submx_refl (capmx_gen A B); rewrite !sub_capmx_gen => /andP[sIA sIB].\ncase idA: (qidmx A); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase idB: (qidmx B); first by rewrite !capmx_nopP submx_refl sub_qidmx.\ncase s1B: (1%:M <= B)%MS; rewrite !capmx_normP ?sub_capmx_gen sIA ?sIB //=.\nby rewrite submx_refl (submx_trans (submx1 _)).\nQed.\n\nLemma capmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= A)%MS.\nProof. by rewrite capmxE submxMl. Qed.\n\nLemma sub_capmx m m1 m2 n (A : 'M_(m, n)) (B : 'M_(m1, n)) (C : 'M_(m2, n)) :\n  (A <= B :&: C)%MS = (A <= B)%MS && (A <= C)%MS.\nProof. by rewrite capmxE sub_capmx_gen. Qed.\n\nLemma capmxC m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B = B :&: A)%MS.\nProof.\nhave [eqAB|] := eqVneq (qidmx A) (qidmx B).\n  rewrite (capmx_eq_norm eqAB) (capmx_eq_norm (esym eqAB)).\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbC.\n  by apply/andP; split; rewrite !sub_capmx andbC -sub_capmx.\nby rewrite negb_eqb !unlock => /addbP <-; case: (qidmx A).\nQed.\n\nLemma capmxSr m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :&: B <= B)%MS.\nProof. by rewrite capmxC capmxSl. Qed.\n\nLemma capmx_idPr n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: B)%MS (B <= A)%MS.\nProof.\nhave:= @eqmxP _ _ _ (A :&: B)%MS B.\nby rewrite capmxSr sub_capmx submx_refl !andbT.\nQed.\n\nLemma capmx_idPl n m1 m2 (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B :=: A)%MS (A <= B)%MS.\nProof. by rewrite capmxC; exact: capmx_idPr. Qed.\n\nLemma capmxS m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                           (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A <= C -> B <= D -> A :&: B <= C :&: D)%MS.\nProof.\nby move=> sAC sBD; rewrite sub_capmx {1}capmxC !(submx_trans (capmxSr _ _)).\nQed.\n\nLemma cap_eqmx m1 m2 m3 m4 n (A : 'M_(m1, n)) (B : 'M_(m2, n))\n                             (C : 'M_(m3, n)) (D : 'M_(m4, n)) :\n  (A :=: C -> B :=: D -> A :&: B :=: C :&: D)%MS.\nProof. by move=> eqAC eqBD; apply/eqmxP; rewrite !capmxS ?eqAC ?eqBD. Qed.\n\nLemma capmxMr m1 m2 n p (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(n, p)) :\n  ((A :&: B) *m C <= A *m C :&: B *m C)%MS.\nProof. by rewrite sub_capmx !submxMr ?capmxSl ?capmxSr. Qed.\n\nLemma cap0mx m1 m2 n (A : 'M_(m2, n)) : ((0 : 'M_(m1, n)) :&: A)%MS = 0.\nProof. exact: submx0null (capmxSl _ _). Qed.\n\nLemma capmx0 m1 m2 n (A : 'M_(m1, n)) : (A :&: (0 : 'M_(m2, n)))%MS = 0.\nProof. exact: submx0null (capmxSr _ _). Qed.\n\nLemma capmxT m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full B -> (A :&: B :=: A)%MS.\nProof.\nrewrite -sub1mx => s1B; apply/eqmxP.\nby rewrite capmxSl sub_capmx submx_refl (submx_trans (submx1 A)).\nQed.\n\nLemma capTmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  row_full A -> (A :&: B :=: B)%MS.\nProof. by move=> Afull; apply/eqmxP; rewrite capmxC !capmxT ?andbb. Qed.\n\nLet capmx_nop_id n (A : 'M_n) : capmx_nop A = A.\nProof. by rewrite /capmx_nop conform_mx_id. Qed.\n\nLemma cap1mx n (A : 'M_n) : (1%:M :&: A = A)%MS.\nProof. by rewrite unlock qidmx_eq1 eqxx capmx_nop_id. Qed.\n\nLemma capmx1 n (A : 'M_n) : (A :&: 1%:M = A)%MS.\nProof. by rewrite capmxC cap1mx. Qed.\n\nLemma genmx_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  <<A :&: B>>%MS = (<<A>> :&: <<B>>)%MS.\nProof.\nrewrite -(eq_genmx (cap_eqmx (genmxE A) (genmxE B))).\ncase idAB: (qidmx <<A>> || qidmx <<B>>)%MS.\n  rewrite [@capmx]unlock !capmx_nop_id !(fun_if (@genmx _ _)) !genmx_id.\n  by case: (qidmx _) idAB => //= ->.\ncase idA: (qidmx _) idAB => //= idB; rewrite {2}capmx_eq_norm ?idA //.\nset C := (_ :&: _)%MS; have eq_idC: row_full C = qidmx C.\n  rewrite qidmx_cap idA -sub1mx sub_capmx genmxE; apply/andP=> [[s1A]].\n  by case/idP: idA; rewrite qidmx_eq1 -genmx1 (sameP eqP genmxP) submx1.\nrewrite unlock /capmx_norm eq_idC.\nby apply: choose_id (capmx_witnessP _); rewrite -eq_idC genmx_witnessP.\nQed.\n\nLemma capmxA m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A :&: (B :&: C) = A :&: B :&: C)%MS.\nProof.\nrewrite (capmxC A B) capmxC; wlog idA: m1 m3 A C / qidmx A.\n  move=> IH; case idA: (qidmx A); first exact: IH.\n  case idC: (qidmx C); first by rewrite -IH.\n  rewrite (@capmx_eq_norm n m3) ?qidmx_cap ?idA ?idC ?andbF //.\n  rewrite capmx_eq_norm ?qidmx_cap ?idA ?idC ?andbF //.\n  apply: capmx_norm_eq; first by rewrite !qidmx_cap andbAC.\n  by apply/andP; split; rewrite !sub_capmx andbAC -!sub_capmx.\nrewrite -!(capmxC A) [in @capmx m1]unlock idA capmx_nop_id.\nhave [eqBC |] :=eqVneq (qidmx B) (qidmx C).\n  rewrite (@capmx_eq_norm n) ?capmx_nopP // capmx_eq_norm //.\n  by apply: capmx_norm_eq; rewrite ?qidmx_cap ?capmxS ?capmx_nopP.\nby rewrite !unlock capmx_nopP capmx_nop_id; do 2?case: (qidmx _) => //.\nQed.\n\nCanonical capmx_monoid n :=\n   Monoid.Law (@capmxA n n n n) (@cap1mx n) (@capmx1 n).\nCanonical capmx_comoid n := Monoid.ComLaw (@capmxC n n n).\n\nLemma bigcapmx_inf i0 P m n (A_ : I -> 'M_n) (B : 'M_(m, n)) :\n  P i0 -> (A_ i0 <= B -> \\bigcap_(i | P i) A_ i <= B)%MS.\nProof. by move=> Pi0; apply: submx_trans; rewrite (bigD1 i0) // capmxSl. Qed.\n\nLemma sub_bigcapmxP P m n (A : 'M_(m, n)) (B_ : I -> 'M_n) :\n  reflect (forall i, P i -> A <= B_ i)%MS (A <= \\bigcap_(i | P i) B_ i)%MS.\nProof.\napply: (iffP idP) => [sAB i Pi | sAB].\n  by apply: (submx_trans sAB); rewrite (bigcapmx_inf Pi).\nby elim/big_rec: _ => [|i Pi C sAC]; rewrite ?submx1 // sub_capmx sAB.\nQed.\n\nLemma genmx_bigcap P n (A_ : I -> 'M_n) :\n  (<<\\bigcap_(i | P i) A_ i>> = \\bigcap_(i | P i) <<A_ i>>)%MS.\nProof. exact: (big_morph _ (@genmx_cap n n n) (@genmx1 n)). Qed.\n\nLemma matrix_modl m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (A <= C -> A + (B :&: C) :=: (A + B) :&: C)%MS.\nProof.\nmove=> sAC; set D := ((A + B) :&: C)%MS; apply/eqmxP.\nrewrite sub_capmx addsmxS ?capmxSl // addsmx_sub sAC capmxSr /=.\nhave: (D <= B + A)%MS by rewrite addsmxC capmxSl.\ncase/sub_addsmxP=> u defD; rewrite defD addrC addmx_sub_adds ?submxMl //.\nrewrite sub_capmx submxMl -[_ *m B](addrK (u.2 *m A)) -defD.\nby rewrite addmx_sub ?capmxSr // eqmx_opp mulmx_sub.\nQed.\n\nLemma matrix_modr m1 m2 m3 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) (C : 'M_(m3, n)) :\n  (C <= A -> (A :&: B) + C :=: A :&: (B + C))%MS.\nProof. by rewrite !(capmxC A) -!(addsmxC C); exact: matrix_modl. Qed.\n\nLemma capmx_compl m n (A : 'M_(m, n)) : (A :&: A^C)%MS = 0.\nProof.\nset D := (A :&: A^C)%MS; have: (D <= D)%MS by [].\nrewrite sub_capmx andbC => /andP[/submxP[B defB]].\nrewrite submxE => /eqP; rewrite defB -!mulmxA mulKVmx ?copid_mx_id //.\nby rewrite mulmxA => ->; rewrite mul0mx.\nQed.\n\nLemma mxrank_mul_ker m n p (A : 'M_(m, n)) (B : 'M_(n, p)) :\n  (\\rank (A *m B) + \\rank (A :&: kermx B))%N = \\rank A.\nProof.\napply/eqP; set K := kermx B; set C := (A :&: K)%MS.\nrewrite -(eqmxMr B (eq_row_base A)); set K' := _ *m B.\nrewrite -{2}(subnKC (rank_leq_row K')) -mxrank_ker eqn_add2l.\nrewrite -(mxrankMfree _ (row_base_free A)) mxrank_leqif_sup.\n  rewrite sub_capmx -(eq_row_base A) submxMl. \n  by apply/sub_kermxP; rewrite -mulmxA mulmx_ker.\nhave /submxP[C' defC]: (C <= row_base A)%MS by rewrite eq_row_base capmxSl.\nrewrite defC submxMr //; apply/sub_kermxP.\nby rewrite mulmxA -defC; apply/sub_kermxP; rewrite capmxSr.\nQed.\n\nLemma mxrank_injP m n p (A : 'M_(m, n)) (f : 'M_(n, p)) :\n  reflect (\\rank (A *m f) = \\rank A) ((A :&: kermx f)%MS == 0).\nProof.\nrewrite -mxrank_eq0 -(eqn_add2l (\\rank (A *m f))).\nby rewrite mxrank_mul_ker addn0 eq_sym; exact: eqP.\nQed.\n\nLemma mxrank_disjoint_sum m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :&: B)%MS = 0 -> \\rank (A + B)%MS = (\\rank A + \\rank B)%N.\nProof.\nmove=> AB0; pose Ar := row_base A; pose Br := row_base B.\nhave [Afree Bfree]: row_free Ar /\\ row_free Br by rewrite !row_base_free.\nhave: (Ar :&: Br <= A :&: B)%MS by rewrite capmxS ?eq_row_base.\nrewrite {}AB0 submx0 -mxrank_eq0 capmxE mxrankMfree //.\nset Cr := col_mx Ar Br; set Crl := lsubmx _; rewrite mxrank_eq0 => /eqP Crl0.\nrewrite -(adds_eqmx (eq_row_base _) (eq_row_base _)) addsmxE -/Cr.\nsuffices K0: kermx Cr = 0.\n  by apply/eqP; rewrite eqn_leq rank_leq_row -subn_eq0 -mxrank_ker K0 mxrank0.\nmove/eqP: (mulmx_ker Cr); rewrite -[kermx Cr]hsubmxK mul_row_col -/Crl Crl0.\nrewrite mul0mx add0r -mxrank_eq0 mxrankMfree // mxrank_eq0 => /eqP->.\nexact: row_mx0.\nQed.\n\nLemma diffmxE m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B :=: A :&: (capmx_gen A B)^C)%MS.\nProof. by rewrite unlock; apply/eqmxP; rewrite !genmxE !capmxE andbb. Qed.\n\nLemma genmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (<<A :\\: B>> = A :\\: B)%MS.\nProof. by rewrite [@diffmx]unlock genmx_id. Qed.\n \nLemma diffmxSl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) : (A :\\: B <= A)%MS.\nProof. by rewrite diffmxE capmxSl. Qed.\n\nLemma capmx_diff m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B) :&: B)%MS = 0.\nProof.\napply/eqP; pose C := capmx_gen A B; rewrite -submx0 -(capmx_compl C).\nby rewrite sub_capmx -capmxE sub_capmx andbAC -sub_capmx -diffmxE -sub_capmx.\nQed.\n\nLemma addsmx_diff_cap_eq m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A :\\: B + A :&: B :=: A)%MS.\nProof.\napply/eqmxP; rewrite addsmx_sub capmxSl diffmxSl /=.\nset C := (A :\\: B)%MS; set D := capmx_gen A B.\nsuffices sACD: (A <= C + D)%MS.\n  by rewrite (submx_trans sACD) ?addsmxS ?capmxE.\nhave:= addsmx_compl_full D; rewrite /row_full addsmxE.\ncase/row_fullP=> U /(congr1 (mulmx A)); rewrite mulmx1.\nrewrite -[U]hsubmxK mul_row_col mulmxDr addrC 2!mulmxA.\nset V := _ *m _ => defA; rewrite -defA; move/(canRL (addrK _)): defA => defV.\nsuffices /submxP[W ->]: (V <= C)%MS by rewrite -mul_row_col addsmxE submxMl.\nrewrite diffmxE sub_capmx {1}defV -mulNmx addmx_sub 1?mulmx_sub //.\nby rewrite -capmxE capmxSl.\nQed.\n\nLemma mxrank_cap_compl m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A :&: B) + \\rank (A :\\: B))%N = \\rank A.\nProof.\nrewrite addnC -mxrank_disjoint_sum ?addsmx_diff_cap_eq //.\nby rewrite (capmxC A) capmxA capmx_diff cap0mx.\nQed.\n\nLemma mxrank_sum_cap m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (\\rank (A + B) + \\rank (A :&: B) = \\rank A + \\rank B)%N.\nProof.\nset C := (A :&: B)%MS; set D := (A :\\: B)%MS.\nhave rDB: \\rank (A + B)%MS = \\rank (D + B)%MS.\n  apply/eqP; rewrite mxrank_leqif_sup; first by rewrite addsmxS ?diffmxSl.\n  by rewrite addsmx_sub addsmxSr -(addsmx_diff_cap_eq A B) addsmxS ?capmxSr.\nrewrite {1}rDB mxrank_disjoint_sum ?capmx_diff //.\nby rewrite addnC addnA mxrank_cap_compl.\nQed.\n\nLemma mxrank_adds_leqif m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  \\rank (A + B) <= \\rank A + \\rank B ?= iff (A :&: B <= (0 : 'M_n))%MS.\nProof.\nrewrite -mxrank_sum_cap; split; first exact: leq_addr.\nby rewrite addnC (@eqn_add2r _ 0) eq_sym mxrank_eq0 -submx0.\nQed.\n\n(* Subspace projection matrix *)\n\nLemma proj_mx_sub m n U V (W : 'M_(m, n)) : (W *m proj_mx U V <= U)%MS.\nProof. by rewrite !mulmx_sub // -addsmxE addsmx0. Qed.\n\nLemma proj_mx_compl_sub m n U V (W : 'M_(m, n)) :\n  (W <= U + V -> W - W *m proj_mx U V <= V)%MS.\nProof.\nrewrite addsmxE => sWUV; rewrite mulmxA -{1}(mulmxKpV sWUV) -mulmxBr.\nby rewrite mulmx_sub // opp_col_mx add_col_mx subrr subr0 -addsmxE adds0mx.\nQed.\n\nLemma proj_mx_id m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= U)%MS -> W *m proj_mx U V = W.\nProof.\nmove=> dxUV sWU; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?proj_mx_sub //= -eqmx_opp opprB.\nby rewrite proj_mx_compl_sub // (submx_trans sWU) ?addsmxSl.\nQed. \n\nLemma proj_mx_0 m n U V (W : 'M_(m, n)) :\n  (U :&: V = 0)%MS -> (W <= V)%MS -> W *m proj_mx U V = 0.\nProof.\nmove=> dxUV sWV; apply/eqP; rewrite -submx0 -dxUV.\nrewrite sub_capmx proj_mx_sub /= -[_ *m _](subrK W) addmx_sub // -eqmx_opp.\nby rewrite opprB proj_mx_compl_sub // (submx_trans sWV) ?addsmxSr.\nQed.\n\nLemma add_proj_mx m n U V (W : 'M_(m, n)) :\n    (U :&: V = 0)%MS -> (W <= U + V)%MS ->\n  W *m proj_mx U V + W *m proj_mx V U = W.\nProof.\nmove=> dxUV sWUV; apply/eqP; rewrite -subr_eq0 -submx0 -dxUV.\nrewrite -addrA sub_capmx {2}addrCA -!(opprB W).\nby rewrite !{1}addmx_sub ?proj_mx_sub ?eqmx_opp ?proj_mx_compl_sub // addsmxC.\nQed.\n\nLemma proj_mx_proj n (U V : 'M_n) :\n  let P := proj_mx U V in (U :&: V = 0)%MS -> P *m P = P.\nProof. by move=> P dxUV; rewrite -{-2}[P]mul1mx proj_mx_id ?proj_mx_sub. Qed.\n\n(* Completing a partially injective matrix to get a unit matrix. *)\n\nLemma complete_unitmx m n (U : 'M_(m, n)) (f : 'M_n) :\n  \\rank (U *m f) = \\rank U -> {g : 'M_n | g \\in unitmx & U *m f = U *m g}.\nProof.\nmove=> injfU; pose V := <<U>>%MS; pose W := V *m f.\npose g := proj_mx V (V^C)%MS *m f + cokermx V *m row_ebase W.\nhave defW: V *m g = W.\n  rewrite mulmxDr mulmxA proj_mx_id ?genmxE ?capmx_compl //.\n  by rewrite mulmxA mulmx_coker mul0mx addr0.\nexists g; last first.\n  have /submxP[u ->]: (U <= V)%MS by rewrite genmxE.\n  by rewrite -!mulmxA defW.\nrewrite -row_full_unit -sub1mx; apply/submxP.\nhave: (invmx (col_ebase W) *m W <= V *m g)%MS by rewrite defW submxMl.\ncase/submxP=> v def_v; exists (invmx (row_ebase W) *m (v *m V + (V^C)%MS)).\nrewrite -mulmxA mulmxDl -mulmxA -def_v -{3}[W]mulmx_ebase -mulmxA.\nrewrite mulKmx ?col_ebase_unit // [_ *m g]mulmxDr mulmxA.\nrewrite (proj_mx_0 (capmx_compl _)) // mul0mx add0r 2!mulmxA.\nrewrite mulmxK ?row_ebase_unit // copid_mx_id ?rank_leq_row //.\nrewrite (eqmxMr _ (genmxE U)) injfU genmxE addrC -mulmxDl subrK.\nby rewrite mul1mx mulVmx ?row_ebase_unit.\nQed.\n\n(* Mapping between two subspaces with the same dimension. *)\n\nLemma eq_rank_unitmx m1 m2 n (U : 'M_(m1, n)) (V : 'M_(m2, n)) :\n  \\rank U = \\rank V -> {f : 'M_n | f \\in unitmx & V :=: U *m f}%MS.\nProof.\nmove=> eqrUV; pose f := invmx (row_ebase <<U>>%MS) *m row_ebase <<V>>%MS.\nhave defUf: (<<U>> *m f :=: <<V>>)%MS.\n  rewrite -[<<U>>%MS]mulmx_ebase mulmxA mulmxK ?row_ebase_unit // -mulmxA.\n  rewrite genmxE eqrUV -genmxE -{3}[<<V>>%MS]mulmx_ebase -mulmxA.\n  move: (pid_mx _ *m _) => W; apply/eqmxP.\n  by rewrite !eqmxMfull ?andbb // row_full_unit col_ebase_unit.\nhave{defUf} defV: (V :=: U *m f)%MS.\n  by apply/eqmxP; rewrite -!(eqmxMr f (genmxE U)) !defUf !genmxE andbb.\nhave injfU: \\rank (U *m f) = \\rank U by rewrite -defV eqrUV.\nby have [g injg defUg] := complete_unitmx injfU; exists g; rewrite -?defUg.\nQed.\n\nSection SumExpr.\n\n(* This is the infrastructure to support the mxdirect predicate. We use a     *)\n(* bespoke canonical structure to decompose a matrix expression into binary   *)\n(* and n-ary products, using some of the \"quote\" technology. This lets us     *)\n(* characterize direct sums as set sums whose rank is equal to the sum of the *)\n(* ranks of the individual terms. The mxsum_expr/proper_mxsum_expr structures *)\n(* below supply both the decomposition and the calculation of the rank sum.   *)\n(* The mxsum_spec dependent predicate family expresses the consistency of     *)\n(* these two decompositions.                                                  *)\n(*   The main technical difficulty we need to overcome is the fact that       *)\n(* the \"catch-all\" case of canonical structures has a priority lower than     *)\n(* constant expansion. However, it is undesireable that local abbreviations   *)\n(* be opaque for the direct-sum predicate, e.g., not be able to handle        *)\n(* let S := (\\sum_(i | P i) LargeExpression i)%MS in mxdirect S -> ...).      *)\n(*   As in \"quote\", we use the interleaving of constant expansion and         *)\n(* canonical projection matching to achieve our goal: we use a \"wrapper\" type *)\n(* (indeed, the wrapped T type defined in ssrfun.v) with a self-inserting     *)\n(* non-primitive constructor to gain finer control over the type and          *)\n(* structure inference process. The innermost, primitive, constructor flags   *)\n(* trivial sums; it is initially hidden by an eta-expansion, which has been   *)\n(* made into a (default) canonical structure -- this lets type inference      *)\n(* automatically insert this outer tag.                                       *)\n(*   In detail, we define three types                                         *)\n(*  mxsum_spec S r <-> There exists a finite list of matrices A1, ..., Ak     *)\n(*                     such that S is the set sum of the Ai, and r is the sum *)\n(*                     of the ranks of the Ai, i.e., S = (A1 + ... + Ak)%MS   *)\n(*                     and r = \\rank A1 + ... + \\rank Ak. Note that           *)\n(*                     mxsum_spec is a recursive dependent predicate family   *)\n(*                     whose elimination rewrites simultaneaously S, r and    *)\n(*                     the height of S.                                       *)\n(*   proper_mxsum_expr n == The interface for proper sum expressions; this is *)\n(*                     a double-entry interface, keyed on both the matrix sum *)\n(*                     value and the rank sum. The matrix value is restricted *)\n(*                     to square matrices, as the \"+\"%MS operator always      *)\n(*                     returns a square matrix. This interface has two        *)\n(*                     canonical insances, for binary and n-ary sums.         *)\n(*   mxsum_expr m n == The interface for general sum expressions, comprising  *)\n(*                     both proper sums and trivial sums consisting of a      *)\n(*                     single matrix. The key values are WRAPPED as this lets *)\n(*                     us give priority to the \"proper sum\" interpretation    *)\n(*                     (see below). To allow for trivial sums, the matrix key *)\n(*                     can have any dimension. The mxsum_expr interface has   *)\n(*                     two canonical instances, for trivial and proper sums,  *)\n(*                     keyed to the Wrap and wrap constructors, respectively. *)\n(* The projections for the two interfaces above are                           *)\n(*   proper_mxsum_val, mxsum_val : these are respectively coercions to 'M_n   *)\n(*                     and wrapped 'M_(m, n); thus, the matrix sum for an     *)\n(*                     S : mxsum_expr m n can be written unwrap S.            *)\n(*   proper_mxsum_rank, mxsum_rank : projections to the nat and wrapped nat,  *)\n(*                     respectively; the rank sum for S : mxsum_expr m n is   *)\n(*                     thus written unwrap (mxsum_rank S).                    *)\n(* The mxdirect A predicate actually gets A in a phantom argument, which is   *)\n(* used to infer an (implicit) S : mxsum_expr such that unwrap S = A; the     *)\n(* actual definition is \\rank (unwrap S) == unwrap (mxsum_rank S).            *)\n(*   Note that the inference of S is inherently ambiguous: ANY matrix can be  *)\n(* viewed as a trivial sum, including one whose description is manifestly a   *)\n(* proper sum. We use the wrapped type and the interaction between delta      *)\n(* reduction and canonical structure inference to resolve this ambiguity in   *)\n(* favor of proper sums, as follows:                                          *)\n(*    - The phantom type sets up a unification problem of the form            *)\n(*         unwrap (mxsum_val ?S) = A                                          *)\n(*      with unknown evar ?S : mxsum_expr m n.                                *)\n(*    - As the constructor wrap is also a default Canonical instance for the  *)\n(*      wrapped type, so A is immediately replaced with unwrap (wrap A) and   *)\n(*      we get the residual unification problem                               *)\n(*         mxsum_val ?S = wrap A                                              *)\n(*    - Now Coq tries to apply the proper sum Canonical instance, which has   *)\n(*      key projection wrap (proper_mxsum_val ?PS) where ?PS is a fresh evar  *)\n(*      (of type proper_mxsum_expr n). This can only succeed if m = n, and if *)\n(*      a solution can be found to the recursive unification problem          *)\n(*         proper_mxsum_val ?PS = A                                           *)\n(*      This causes Coq to look for one of the two canonical constants for    *)\n(*      proper_mxsum_val (addsmx or bigop) at the head of A, delta-expanding  *)\n(*      A as needed, and then inferring recursively mxsum_expr structures for *)\n(*      the last argument(s) of that constant.                                *)\n(*    - If the above step fails then the wrap constant is expanded, revealing *)\n(*      the primitive Wrap constructor; the unification problem now becomes   *)\n(*         mxsum_val ?S = Wrap A                                              *)\n(*      which fits perfectly the trivial sum canonical structure, whose key   *)\n(*      projection is Wrap ?B where ?B is a fresh evar. Thus the inference    *)\n(*      succeeds, and returns the trivial sum.                                *)\n(* Note that the rank projections also register canonical values, so that the *)\n(* same process can be used to infer a sum structure from the rank sum. In    *)\n(* that case, however, there is no ambiguity and the inference can fail,      *)\n(* because the rank sum for a trivial sum is not an arbitrary integer -- it   *)\n(* must be of the form \\rank ?B. It is nevertheless necessary to use the      *)\n(* wrapped nat type for the rank sums, because in the non-trivial case the    *)\n(* head constant of the nat expression is determined by the proper_mxsum_expr *)\n(* canonical structure, so the mxsum_expr structure must use a generic        *)\n(* constant, namely wrap.                                                     *)\n\nInductive mxsum_spec n : forall m, 'M[F]_(m, n) -> nat -> Prop :=\n | TrivialMxsum m A\n    : @mxsum_spec n m A (\\rank A)\n | ProperMxsum m1 m2 T1 T2 r1 r2 of\n      @mxsum_spec n m1 T1 r1 & @mxsum_spec n m2 T2 r2\n    : mxsum_spec (T1 + T2)%MS (r1 + r2)%N.\nArguments Scope mxsum_spec [nat_scope nat_scope matrix_set_scope nat_scope].\n\nStructure mxsum_expr m n := Mxsum {\n  mxsum_val :> wrapped 'M_(m, n);\n  mxsum_rank : wrapped nat;\n  _ : mxsum_spec (unwrap mxsum_val) (unwrap mxsum_rank)\n}.\n\nCanonical trivial_mxsum m n A :=\n  @Mxsum m n (Wrap A) (Wrap (\\rank A)) (TrivialMxsum A).\n\nStructure proper_mxsum_expr n := ProperMxsumExpr {\n  proper_mxsum_val :> 'M_n;\n  proper_mxsum_rank : nat;\n  _ : mxsum_spec proper_mxsum_val proper_mxsum_rank\n}.\n\nDefinition proper_mxsumP n (S : proper_mxsum_expr n) :=\n  let: ProperMxsumExpr _ _ termS := S return mxsum_spec S (proper_mxsum_rank S)\n  in termS.\n\nCanonical sum_mxsum n (S : proper_mxsum_expr n) :=\n  @Mxsum n n (wrap (S : 'M_n)) (wrap (proper_mxsum_rank S)) (proper_mxsumP S).\n\nSection Binary.\nVariable (m1 m2 n : nat) (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n).\nFact binary_mxsum_proof :\n  mxsum_spec (unwrap S1 + unwrap S2)\n             (unwrap (mxsum_rank S1) + unwrap (mxsum_rank S2)).\nProof. by case: S1 S2 => [A1 r1 A1P] [A2 r2 A2P]; right. Qed.\nCanonical binary_mxsum_expr := ProperMxsumExpr binary_mxsum_proof.\nEnd Binary.\n\nSection Nary.\nContext J (r : seq J) (P : pred J) n (S_ : J -> mxsum_expr n n).\nFact nary_mxsum_proof :\n  mxsum_spec (\\sum_(j <- r | P j) unwrap (S_ j))\n             (\\sum_(j <- r | P j) unwrap (mxsum_rank (S_ j))).\nProof.\nelim/big_rec2: _ => [|j]; first by rewrite -(mxrank0 n n); left.\nby case: (S_ j); right.\nQed.\nCanonical nary_mxsum_expr := ProperMxsumExpr nary_mxsum_proof.\nEnd Nary.\n\nDefinition mxdirect_def m n T of phantom 'M_(m, n) (unwrap (mxsum_val T)) :=\n  \\rank (unwrap T) == unwrap (mxsum_rank T).\n\nEnd SumExpr.\n\nNotation mxdirect A := (mxdirect_def (Phantom 'M_(_,_) A%MS)).\n\nLemma mxdirectP n (S : proper_mxsum_expr n) :\n  reflect (\\rank S = proper_mxsum_rank S) (mxdirect S).\nProof. exact: eqnP. Qed.\nImplicit Arguments mxdirectP [n S].\n\nLemma mxdirect_trivial m n A : mxdirect (unwrap (@trivial_mxsum m n A)).\nProof. exact: eqxx. Qed.\n\nLemma mxrank_sum_leqif m n (S : mxsum_expr m n) :\n  \\rank (unwrap S) <= unwrap (mxsum_rank S) ?= iff mxdirect (unwrap S).\nProof.\nrewrite /mxdirect_def; case: S => [[A] [r] /= defAr]; split=> //=.\nelim: m A r / defAr => // m1 m2 A1 A2 r1 r2 _ leAr1 _ leAr2.\nby apply: leq_trans (leq_add leAr1 leAr2); rewrite mxrank_adds_leqif.\nQed.\n\nLemma mxdirectE m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) == unwrap (mxsum_rank S)).\nProof. by []. Qed.\n\nLemma mxdirectEgeq m n (S : mxsum_expr m n) :\n  mxdirect (unwrap S) = (\\rank (unwrap S) >= unwrap (mxsum_rank S)).\nProof. by rewrite (geq_leqif (mxrank_sum_leqif S)). Qed.\n\nSection BinaryDirect.\n\nVariables m1 m2 n : nat.\n\nLemma mxdirect_addsE (S1 : mxsum_expr m1 n) (S2 : mxsum_expr m2 n) :\n   mxdirect (unwrap S1 + unwrap S2)\n    = [&& mxdirect (unwrap S1), mxdirect (unwrap S2)\n        & unwrap S1 :&: unwrap S2 == 0]%MS.\nProof.\nrewrite (@mxdirectE n) /=.\nhave:= leqif_add (mxrank_sum_leqif S1) (mxrank_sum_leqif S2).\nmove/(leqif_trans (mxrank_adds_leqif (unwrap S1) (unwrap S2)))=> ->.\nby rewrite andbC -andbA submx0.\nQed.\n\nLemma mxdirect_addsP (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  reflect (A :&: B = 0)%MS (mxdirect (A + B)).\nProof. by rewrite mxdirect_addsE !mxdirect_trivial; exact: eqP. Qed.\n\nEnd BinaryDirect.\n\nSection NaryDirect.\n\nVariables (P : pred I) (n : nat).\n\nLet TIsum A_ i := (A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0 :> 'M_n)%MS.\n\nLet mxdirect_sums_recP (S_ : I -> mxsum_expr n n) :\n  reflect (forall i, P i -> mxdirect (unwrap (S_ i)) /\\ TIsum (unwrap \\o S_) i)\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\nrewrite /TIsum; apply: (iffP eqnP) => /= [dxS i Pi | dxS].\n  set Si' := (\\sum_(j | _) unwrap (S_ j))%MS.\n  have: mxdirect (unwrap (S_ i) + Si') by apply/eqnP; rewrite /= -!(bigD1 i).\n  by rewrite mxdirect_addsE => /and3P[-> _ /eqP].  \nelim: _.+1 {-2 4}P (subxx P) (ltnSn #|P|) => // m IHm Q; move/subsetP=> sQP.\ncase: (pickP Q) => [i Qi | Q0]; last by rewrite !big_pred0 ?mxrank0.\nrewrite (cardD1x Qi) !((bigD1 i) Q) //=.\nmove/IHm=> <- {IHm}/=; last by apply/subsetP=> j /andP[/sQP].\ncase: (dxS i (sQP i Qi)) => /eqnP=> <- TiQ_0; rewrite mxrank_disjoint_sum //.\napply/eqP; rewrite -submx0 -{2}TiQ_0 capmxS //=.\nby apply/sumsmx_subP=> j /= /andP[Qj i'j]; rewrite (sumsmx_sup j) ?[P j]sQP.\nQed.\n\nLemma mxdirect_sumsP (A_ : I -> 'M_n) :\n  reflect (forall i, P i -> A_ i :&: (\\sum_(j | P j && (j != i)) A_ j) = 0)%MS\n          (mxdirect (\\sum_(i | P i) A_ i)).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => dxA i /dxA; first by case.\nby rewrite mxdirect_trivial.\nQed.\n\nLemma mxdirect_sumsE (S_ : I -> mxsum_expr n n) (xunwrap := unwrap) :\n  reflect (and (forall i, P i -> mxdirect (unwrap (S_ i)))\n               (mxdirect (\\sum_(i | P i) (xunwrap (S_ i)))))\n          (mxdirect (\\sum_(i | P i) (unwrap (S_ i)))).\nProof.\napply: (iffP (mxdirect_sums_recP _)) => [dxS | [dxS_ dxS] i Pi].\n  by do [split; last apply/mxdirect_sumsP] => i; case/dxS.\nby split; [exact: dxS_ | exact: mxdirect_sumsP Pi].\nQed.\n\nEnd NaryDirect.\n\nSection SubDaddsmx.\n\nVariables m m1 m2 n : nat.\nVariables (A : 'M[F]_(m, n)) (B1 : 'M[F]_(m1, n)) (B2 : 'M[F]_(m2, n)).\n\nCoInductive sub_daddsmx_spec : Prop :=\n  SubDaddsmxSpec A1 A2 of (A1 <= B1)%MS & (A2 <= B2)%MS & A = A1 + A2\n                        & forall C1 C2, (C1 <= B1)%MS -> (C2 <= B2)%MS ->\n                          A = C1 + C2 -> C1 = A1 /\\ C2 = A2.\n\nLemma sub_daddsmx : (B1 :&: B2 = 0)%MS -> (A <= B1 + B2)%MS -> sub_daddsmx_spec.\nProof.\nmove=> dxB /sub_addsmxP[u defA].\nexists (u.1 *m B1) (u.2 *m B2); rewrite ?submxMl // => C1 C2 sCB1 sCB2.\nmove/(canLR (addrK _)) => defC1.\nsuffices: (C2 - u.2 *m B2 <= B1 :&: B2)%MS.\n  by rewrite dxB submx0 subr_eq0 -defC1 defA; move/eqP->; rewrite addrK.\nrewrite sub_capmx -opprB -{1}(canLR (addKr _) defA) -addrA defC1.\nby rewrite !(eqmx_opp, addmx_sub) ?submxMl.\nQed.\n\nEnd SubDaddsmx.\n\nSection SubDsumsmx.\n\nVariables (P : pred I) (m n : nat) (A : 'M[F]_(m, n)) (B : I -> 'M[F]_n).\n\nCoInductive sub_dsumsmx_spec : Prop :=\n  SubDsumsmxSpec A_ of forall i, P i -> (A_ i <= B i)%MS\n                        & A = \\sum_(i | P i) A_ i\n                        & forall C, (forall i, P i -> C i <= B i)%MS ->\n                          A = \\sum_(i | P i) C i -> {in SimplPred P, C =1 A_}.\n\nLemma sub_dsumsmx :\n    mxdirect (\\sum_(i | P i) B i) -> (A <= \\sum_(i | P i) B i)%MS ->\n  sub_dsumsmx_spec.\nProof.\nmove/mxdirect_sumsP=> dxB /sub_sumsmxP[u defA].\npose A_ i := u i *m B i.\nexists A_ => //= [i _ | C sCB defAC i Pi]; first exact: submxMl.\napply/eqP; rewrite -subr_eq0 -submx0 -{dxB}(dxB i Pi) /=.\nrewrite sub_capmx addmx_sub ?eqmx_opp ?submxMl ?sCB //=.\nrewrite -(subrK A (C i)) -addrA -opprB addmx_sub ?eqmx_opp //.\n  rewrite addrC defAC (bigD1 i) // addKr /= summx_sub // => j Pi'j.\n  by rewrite (sumsmx_sup j) ?sCB //; case/andP: Pi'j.\nrewrite addrC defA (bigD1 i) // addKr /= summx_sub // => j Pi'j.\nby rewrite (sumsmx_sup j) ?submxMl.\nQed.\n\nEnd SubDsumsmx.\n\nSection Eigenspace.\n\nVariables (n : nat) (g : 'M_n).\n\nDefinition eigenspace a := kermx (g - a%:M).\nDefinition eigenvalue : pred F := fun a => eigenspace a != 0.\n\nLemma eigenspaceP a m (W : 'M_(m, n)) :\n  reflect (W *m g = a *: W) (W <= eigenspace a)%MS.\nProof.\nrewrite (sameP (sub_kermxP _ _) eqP).\nby rewrite mulmxBr subr_eq0 mul_mx_scalar; exact: eqP.\nQed.\n\nLemma eigenvalueP a :\n  reflect (exists2 v : 'rV_n, v *m g = a *: v & v != 0) (eigenvalue a).\nProof. by apply: (iffP (rowV0Pn _)) => [] [v]; move/eigenspaceP; exists v. Qed.\n\nLemma mxdirect_sum_eigenspace (P : pred I) a_ :\n  {in P &, injective a_} -> mxdirect (\\sum_(i | P i) eigenspace (a_ i)).\nProof.\nelim: {P}_.+1 {-2}P (ltnSn #|P|) => // m IHm P lePm inj_a.\napply/mxdirect_sumsP=> i Pi; apply/eqP/rowV0P => v.\nrewrite sub_capmx => /andP[/eigenspaceP def_vg].\nset Vi' := (\\sum_(i | _) _)%MS => Vi'v.\nhave dxVi': mxdirect Vi'.\n  rewrite (cardD1x Pi) in lePm; apply: IHm => //.\n  by apply: sub_in2 inj_a => j /andP[].\ncase/sub_dsumsmx: Vi'v => // u Vi'u def_v _.\nrewrite def_v big1 // => j Pi'j; apply/eqP.\nhave nz_aij: a_ i - a_ j != 0.\n  by case/andP: Pi'j => Pj ne_ji; rewrite subr_eq0 eq_sym (inj_in_eq inj_a).\ncase: (sub_dsumsmx dxVi' (sub0mx 1 _)) => C _ _ uniqC.\nrewrite -(eqmx_eq0 (eqmx_scale _ nz_aij)).\nrewrite (uniqC (fun k => (a_ i - a_ k) *: u k)) => // [|k Pi'k|].\n- by rewrite -(uniqC (fun _ => 0)) ?big1 // => k Pi'k; exact: sub0mx.\n- by rewrite scalemx_sub ?Vi'u.\nrewrite -{1}(subrr (v *m g)) {1}def_vg def_v scaler_sumr mulmx_suml -sumrB.\nby apply: eq_bigr => k /Vi'u/eigenspaceP->; rewrite scalerBl.\nQed.\n\nEnd Eigenspace.\n\nEnd RowSpaceTheory.\n\nHint Resolve submx_refl.\nImplicit Arguments submxP [F m1 m2 n A B].\nImplicit Arguments eq_row_sub [F m n v A].\nImplicit Arguments row_subP [F m1 m2 n A B].\nImplicit Arguments rV_subP [F m1 m2 n A B].\nImplicit Arguments row_subPn [F m1 m2 n A B].\nImplicit Arguments sub_rVP [F n u v].\nImplicit Arguments rV_eqP [F m1 m2 n A B].\nImplicit Arguments rowV0Pn [F m n A].\nImplicit Arguments rowV0P [F m n A].\nImplicit Arguments eqmx0P [F m n A].\nImplicit Arguments row_fullP [F m n A].\nImplicit Arguments row_freeP [F m n A].\nImplicit Arguments eqmxP [F m1 m2 n A B].\nImplicit Arguments genmxP [F m1 m2 n A B].\nImplicit Arguments addsmx_idPr [F m1 m2 n A B].\nImplicit Arguments addsmx_idPl [F m1 m2 n A B].\nImplicit Arguments sub_addsmxP [F m1 m2 m3 n A B C].\nImplicit Arguments sumsmx_sup [F I P m n A B_].\nImplicit Arguments sumsmx_subP [F I P m n A_ B].\nImplicit Arguments sub_sumsmxP [F I P m n A B_].\nImplicit Arguments sub_kermxP [F p m n A B].\nImplicit Arguments capmx_idPr [F m1 m2 n A B].\nImplicit Arguments capmx_idPl [F m1 m2 n A B].\nImplicit Arguments bigcapmx_inf [F I P m n A_ B].\nImplicit Arguments sub_bigcapmxP [F I P m n A B_].\nImplicit Arguments mxrank_injP [F m n A f].\nImplicit Arguments mxdirectP [F n S].\nImplicit Arguments mxdirect_addsP [F m1 m2 n A B].\nImplicit Arguments mxdirect_sumsP [F I P n A_].\nImplicit Arguments mxdirect_sumsE [F I P n S_].\nImplicit Arguments eigenspaceP [F n g a m W].\nImplicit Arguments eigenvalueP [F n g a].\n\nArguments Scope mxrank [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope complmx [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope row_full [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope submx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope ltmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope eqmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope addsmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope capmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope diffmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nPrenex Implicits mxrank genmx complmx submx ltmx addsmx capmx.\nNotation \"\\rank A\" := (mxrank A) : nat_scope.\nNotation \"<< A >>\" := (genmx A) : matrix_set_scope.\nNotation \"A ^C\" := (complmx A) : matrix_set_scope.\nNotation \"A <= B\" := (submx A B) : matrix_set_scope.\nNotation \"A < B\" := (ltmx A B) : matrix_set_scope.\nNotation \"A <= B <= C\" := ((submx A B) && (submx B C)) : matrix_set_scope.\nNotation \"A < B <= C\" := (ltmx A B && submx B C) : matrix_set_scope.\nNotation \"A <= B < C\" := (submx A B && ltmx B C) : matrix_set_scope.\nNotation \"A < B < C\" := (ltmx A B && ltmx B C) : matrix_set_scope.\nNotation \"A == B\" := ((submx A B) && (submx B A)) : matrix_set_scope.\nNotation \"A :=: B\" := (eqmx A B) : matrix_set_scope.\nNotation \"A + B\" := (addsmx A B) : matrix_set_scope.\nNotation \"A :&: B\" := (capmx A B) : matrix_set_scope.\nNotation \"A :\\: B\" := (diffmx A B) : matrix_set_scope.\nNotation mxdirect S := (mxdirect_def (Phantom 'M_(_,_) S%MS)).\n\nNotation \"\\sum_ ( <- r | P ) B\" :=\n  (\\big[addsmx/0%R]_(<- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r | P ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i <- r ) B\" :=\n  (\\big[addsmx/0%R]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( m <= i < n ) B\" :=\n  (\\big[addsmx/0%R]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i | P ) B\" :=\n  (\\big[addsmx/0%R]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ i B\" :=\n  (\\big[addsmx/0%R]_i B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i : t | P ) B\" :=\n  (\\big[addsmx/0%R]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i : t ) B\" :=\n  (\\big[addsmx/0%R]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\sum_ ( i < n | P ) B\" :=\n  (\\big[addsmx/0%R]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i < n ) B\" :=\n  (\\big[addsmx/0%R]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A | P ) B\" :=\n  (\\big[addsmx/0%R]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\sum_ ( i 'in' A ) B\" :=\n  (\\big[addsmx/0%R]_(i in A) B%MS) : matrix_set_scope.\n\nNotation \"\\bigcap_ ( <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(<- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r | P ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i <- r ) B\" :=\n  (\\big[capmx/1%:M]_(i <- r) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( m <= i < n ) B\" :=\n  (\\big[capmx/1%:M]_(m <= i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i | P ) B\" :=\n  (\\big[capmx/1%:M]_(i | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ i B\" :=\n  (\\big[capmx/1%:M]_i B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t | P ) B\" :=\n  (\\big[capmx/1%:M]_(i : t | P%B) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i : t ) B\" :=\n  (\\big[capmx/1%:M]_(i : t) B%MS) (only parsing) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n | P ) B\" :=\n  (\\big[capmx/1%:M]_(i < n | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i < n ) B\" :=\n  (\\big[capmx/1%:M]_(i < n) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A | P ) B\" :=\n  (\\big[capmx/1%:M]_(i in A | P%B) B%MS) : matrix_set_scope.\nNotation \"\\bigcap_ ( i 'in' A ) B\" :=\n  (\\big[capmx/1%:M]_(i in A) B%MS) : matrix_set_scope.\n\nSection CardGL.\n\nVariable F : finFieldType.\n\nLemma card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite big_nat_rev big_add1 -triangular_sum expn_sum -big_split /=.\npose fr m := [pred A : 'M[F]_(m, n) | \\rank A == m].\nset m := {-7}n; transitivity #|fr m|.\n  by rewrite cardsT /= card_sub; apply: eq_card => A; rewrite -row_free_unit.\nelim: m (leqnn m : m <= n) => [_|m IHm]; last move/ltnW=> le_mn.\n  rewrite (@eq_card1 _ (0 : 'M_(0, n))) ?big_geq //= => A.\n  by rewrite flatmx0 !inE !eqxx.\nrewrite big_nat_recr -{}IHm //= !subSS mulnBr muln1 -expnD subnKC //.\nrewrite -sum_nat_const /= -sum1_card -add1n.\nrewrite (partition_big dsubmx (fr m)) /= => [|A]; last first.\n  rewrite !inE -{1}(vsubmxK A); move: {A}(_ A) (_ A) => Ad Au Afull.\n  rewrite eqn_leq rank_leq_row -(leq_add2l (\\rank Au)) -mxrank_sum_cap.\n  rewrite {1 3}[@mxrank]lock addsmxE (eqnP Afull) -lock -addnA.\n  by rewrite leq_add ?rank_leq_row ?leq_addr.\napply: eq_bigr => A rAm; rewrite (reindex (col_mx^~ A)) /=; last first.\n  exists usubmx => [v _ | vA]; first by rewrite col_mxKu.\n  by case/andP=> _ /eqP <-; rewrite vsubmxK.\ntransitivity #|~: [set v *m A | v in 'rV_m]|; last first.\n  rewrite cardsCs setCK card_imset ?card_matrix ?card_ord ?mul1n //.\n  have [B AB1] := row_freeP rAm; apply: can_inj (mulmx^~ B) _ => v.\n  by rewrite -mulmxA AB1 mulmx1.\nrewrite -sum1_card; apply: eq_bigl => v; rewrite !inE col_mxKd eqxx.\nrewrite andbT eqn_leq rank_leq_row /= -(leq_add2r (\\rank (v :&: A)%MS)).\nrewrite -addsmxE mxrank_sum_cap (eqnP rAm) addnAC leq_add2r.\nrewrite (ltn_leqif (mxrank_leqif_sup _)) ?capmxSl // sub_capmx submx_refl.\nby congr (~~ _); apply/submxP/imsetP=> [] [u]; exists u.\nQed.\n\n(* An alternate, somewhat more elementary proof, that does not rely on the *)\n(* row-space theory, but directly performs the LUP decomposition.          *)\nLemma LUP_card_GL n : n > 0 ->\n  #|'GL_n[F]| = (#|F| ^ 'C(n, 2) * \\prod_(1 <= i < n.+1) (#|F| ^ i - 1))%N.\nProof.\ncase: n => // n' _; set n := n'.+1; set p := #|F|.\nrewrite cardsT /= card_sub /GRing.unit /= big_add1 /= -triangular_sum -/n.\nelim: {n'}n => [|n IHn].\n  rewrite !big_geq // mul1n (@eq_card _ _ predT) ?card_matrix //= => M.\n  by rewrite {1}[M]flatmx0 -(flatmx0 1%:M) unitmx1.\nrewrite !big_nat_recr /= expnD mulnAC mulnA -{}IHn -mulnA mulnC.\nset LHS := #|_|; rewrite -[n.+1]muln1 -{2}[n]mul1n {}/LHS.\nrewrite -!card_matrix subn1 -(cardC1 0) -mulnA; set nzC := predC1 _.\nrewrite -sum1_card (partition_big lsubmx nzC) => [|A]; last first.\n  rewrite unitmxE unitfE; apply: contra; move/eqP=> v0.\n  rewrite -[A]hsubmxK v0 -[n.+1]/(1 + n)%N -col_mx0.\n  rewrite -[rsubmx _]vsubmxK -det_tr tr_row_mx !tr_col_mx !trmx0.\n  by rewrite det_lblock [0]mx11_scalar det_scalar1 mxE mul0r.\nrewrite -sum_nat_const; apply: eq_bigr; rewrite /= -[n.+1]/(1 + n)%N => v nzv.\ncase: (pickP (fun i => v i 0 != 0)) => [k nza | v0]; last first.\n  by case/eqP: nzv; apply/colP=> i; move/eqP: (v0 i); rewrite mxE.\nhave xrkK: involutive (@xrow F _ _ 0 k).\n  by move=> m A /=; rewrite /xrow -row_permM tperm2 row_perm1.\nrewrite (reindex_inj (inv_inj (xrkK (1 + n)%N))) /= -[n.+1]/(1 + n)%N.\nrewrite (partition_big ursubmx xpredT) //= -sum_nat_const.\napply: eq_bigr => u _; set a : F := v _ _ in nza.\nset v1 : 'cV_(1 + n) := xrow 0 k v.\nhave def_a: usubmx v1 = a%:M.\n  by rewrite [_ v1]mx11_scalar mxE lshift0 mxE tpermL.\npose Schur := dsubmx v1 *m (a^-1 *: u).\npose L : 'M_(1 + n) := block_mx a%:M 0 (dsubmx v1) 1%:M.\npose U B : 'M_(1 + n) := block_mx 1 (a^-1 *: u) 0 B.\nrewrite (reindex (fun B => L *m U B)); last first.\n  exists (fun A1 => drsubmx A1 - Schur) => [B _ | A1].\n    by rewrite mulmx_block block_mxKdr mul1mx addrC addKr.\n  rewrite !inE mulmx_block !mulmx0 mul0mx !mulmx1 !addr0 mul1mx addrC subrK.\n  rewrite mul_scalar_mx scalerA divff // scale1r andbC; case/and3P => /eqP <- _.\n  rewrite -{1}(hsubmxK A1) xrowE mul_mx_row row_mxKl -xrowE => /eqP def_v.\n  rewrite -def_a block_mxEh vsubmxK /v1 -def_v xrkK.\n  apply: trmx_inj; rewrite tr_row_mx tr_col_mx trmx_ursub trmx_drsub trmx_lsub.\n  by rewrite hsubmxK vsubmxK.\nrewrite -sum1_card; apply: eq_bigl => B; rewrite xrowE unitmxE.\nrewrite !det_mulmx unitrM -unitmxE unitmx_perm det_lblock det_ublock.\nrewrite !det_scalar1 det1 mulr1 mul1r unitrM unitfE nza -unitmxE.\nrewrite mulmx_block !mulmx0 mul0mx !addr0 !mulmx1 mul1mx block_mxKur.\nrewrite mul_scalar_mx scalerA divff // scale1r eqxx andbT.\nby rewrite block_mxEh mul_mx_row row_mxKl -def_a vsubmxK -xrowE xrkK eqxx andbT.\nQed.\n\nLemma card_GL_1 : #|'GL_1[F]| = #|F|.-1.\nProof. by rewrite card_GL // mul1n big_nat1 expn1 subn1. Qed.\n\nLemma card_GL_2 : #|'GL_2[F]| = (#|F| * #|F|.-1 ^ 2 * #|F|.+1)%N.\nProof.\nrewrite card_GL // big_ltn // big_nat1 expn1 -(addn1 #|F|) -subn1 -!mulnA.\nby rewrite -subn_sqr.\nQed.\n\nEnd CardGL.\n\nLemma logn_card_GL_p n p : prime p -> logn p #|'GL_n(p)| = 'C(n, 2).\nProof.\nmove=> p_pr; have p_gt1 := prime_gt1 p_pr.\nhave p_i_gt0: p ^ _ > 0 by move=> i; rewrite expn_gt0 ltnW.\nrewrite (card_GL _ (ltn0Sn n.-1)) card_ord Fp_cast // big_add1 /=.\npose p'gt0 m := m > 0 /\\ logn p m = 0%N.\nsuffices [Pgt0 p'P]: p'gt0 (\\prod_(0 <= i < n.-1.+1) (p ^ i.+1 - 1))%N.\n  by rewrite lognM // p'P pfactorK //; case n.\napply big_ind => [|m1 m2 [m10 p'm1] [m20]|i _]; rewrite {}/p'gt0 ?logn1 //.\n  by rewrite muln_gt0 m10 lognM ?p'm1.\nrewrite lognE -if_neg subn_gt0 p_pr /= -{1 2}(exp1n i.+1) ltn_exp2r // p_gt1.\nby rewrite dvdn_subr ?dvdn_exp // gtnNdvd.\nQed.\n\nSection MatrixAlgebra.\n\nVariables F : fieldType.\n\nLocal Notation \"A \\in R\" := (@submx F _ _ _ (mxvec A) R).\n\nLemma mem0mx m n (R : 'A_(m, n)) : 0 \\in R.\nProof. by rewrite linear0 sub0mx. Qed.\n\nLemma memmx0 n A : (A \\in (0 : 'A_n)) -> A = 0.\nProof. by rewrite submx0 mxvec_eq0; move/eqP. Qed.\n\nLemma memmx1 n (A : 'M_n) : (A \\in mxvec 1%:M) = is_scalar_mx A.\nProof.\napply/sub_rVP/is_scalar_mxP=> [[a] | [a ->]].\n  by rewrite -linearZ scale_scalar_mx mulr1 => /(can_inj mxvecK); exists a.\nby exists a; rewrite -linearZ scale_scalar_mx mulr1.\nQed.\n\nLemma memmx_subP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, A \\in R1 -> A \\in R2) (R1 <= R2)%MS.\nProof.\napply: (iffP idP) => [sR12 A R1_A | sR12]; first exact: submx_trans sR12.\nby apply/rV_subP=> vA; rewrite -(vec_mxK vA); exact: sR12.\nQed.\nImplicit Arguments memmx_subP [m1 m2 n R1 R2].\n\nLemma memmx_eqP m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (forall A, (A \\in R1) = (A \\in R2)) (R1 == R2)%MS.\nProof.\napply: (iffP eqmxP) => [eqR12 A | eqR12]; first by rewrite eqR12.\nby apply/eqmxP; apply/rV_eqP=> vA; rewrite -(vec_mxK vA) eqR12.\nQed.\nImplicit Arguments memmx_eqP [m1 m2 n R1 R2].\n\nLemma memmx_addsP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists D, [/\\ D.1 \\in R1, D.2 \\in R2 & A = D.1 + D.2])\n          (A \\in R1 + R2)%MS.\nProof.\napply: (iffP sub_addsmxP) => [[u /(canRL mxvecK)->] | [D []]].\n  exists (vec_mx (u.1 *m R1), vec_mx (u.2 *m R2)).\n  by rewrite /= linearD !vec_mxK !submxMl.\ncase/submxP=> u1 defD1 /submxP[u2 defD2] ->.\nby exists (u1, u2); rewrite linearD /= defD1 defD2.\nQed.\nImplicit Arguments memmx_addsP [m1 m2 n A R1 R2].\n\nLemma memmx_sumsP (I : finType) (P : pred I) n (A : 'M_n) R_ :\n  reflect (exists2 A_, A = \\sum_(i | P i) A_ i & forall i, A_ i \\in R_ i)\n          (A \\in \\sum_(i | P i) R_ i)%MS.\nProof.\napply: (iffP sub_sumsmxP) => [[C defA] | [A_ -> R_A] {A}].\n  exists (fun i => vec_mx (C i *m R_ i)) => [|i].\n    by rewrite -linear_sum -defA /= mxvecK.\n  by rewrite vec_mxK submxMl.\nexists (fun i => mxvec (A_ i) *m pinvmx (R_ i)).\nby rewrite linear_sum; apply: eq_bigr => i _; rewrite mulmxKpV.\nQed.\nImplicit Arguments memmx_sumsP [I P n A R_].\n\nLemma has_non_scalar_mxP m n (R : 'A_(m, n)) : \n    (1%:M \\in R)%MS ->\n  reflect (exists2 A, A \\in R & ~~ is_scalar_mx A)%MS (1 < \\rank R).\nProof.\ncase: (posnP n) => [-> | n_gt0] in R *; set S := mxvec _ => sSR.\n  by rewrite [R]thinmx0 mxrank0; right; case; rewrite /is_scalar_mx ?insubF.\nhave rankS: \\rank S = 1%N.\n  apply/eqP; rewrite eqn_leq rank_leq_row lt0n mxrank_eq0 mxvec_eq0.\n  by rewrite -mxrank_eq0 mxrank1 -lt0n.\nrewrite -{2}rankS (ltn_leqif (mxrank_leqif_sup sSR)).\napply: (iffP idP) => [/row_subPn[i] | [A sAR]].\n  rewrite -[row i R]vec_mxK memmx1; set A := vec_mx _ => nsA.\n  by exists A; rewrite // vec_mxK row_sub.\nby rewrite -memmx1; apply: contra; exact: submx_trans.\nQed.\n\nDefinition mulsmx m1 m2 n (R1 : 'A[F]_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (\\sum_i <<R1 *m lin_mx (mulmxr (vec_mx (row i R2)))>>)%MS.\n\nArguments Scope mulsmx\n  [nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\n\nLocal Notation \"R1 * R2\" := (mulsmx R1 R2) : matrix_set_scope.\n\nLemma genmx_muls m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  <<(R1 * R2)%MS>>%MS = (R1 * R2)%MS.\nProof. by rewrite genmx_sums; apply: eq_bigr => i; rewrite genmx_id. Qed.\n\nLemma mem_mulsmx m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) A1 A2 :\n  (A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R1 * R2)%MS.\nProof.\nmove=> R_A1 R_A2; rewrite -[A2]mxvecK; case/submxP: R_A2 => a ->{A2}.\nrewrite mulmx_sum_row !linear_sum summx_sub // => i _.\nrewrite !linearZ scalemx_sub {a}//= (sumsmx_sup i) // genmxE.\nrewrite -[A1]mxvecK; case/submxP: R_A1 => a ->{A1}.\nby apply/submxP; exists a; rewrite mulmxA mul_rV_lin.\nQed.\n\nLemma mulsmx_subP m1 m2 m n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R : 'A_(m, n)) :\n  reflect (forall A1 A2, A1 \\in R1 -> A2 \\in R2 -> A1 *m A2 \\in R)\n          (R1 * R2 <= R)%MS.\nProof.\napply: (iffP memmx_subP) => [sR12R A1 A2 R_A1 R_A2 | sR12R A].\n  by rewrite sR12R ?mem_mulsmx.\ncase/memmx_sumsP=> A_ -> R_A; rewrite linear_sum summx_sub //= => j _.\nrewrite (submx_trans (R_A _)) // genmxE; apply/row_subP=> i.\nby rewrite row_mul mul_rV_lin sR12R ?vec_mxK ?row_sub.\nQed.\nImplicit Arguments mulsmx_subP [m1 m2 m n R1 R2 R].\n\nLemma mulsmxS m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                            (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 <= R3 -> R2 <= R4 -> R1 * R2 <= R3 * R4)%MS.\nProof.\nmove=> sR13 sR24; apply/mulsmx_subP=> A1 A2 R_A1 R_A2.\nby apply: mem_mulsmx; [exact: submx_trans sR13 | exact: submx_trans sR24].\nQed.\n\nLemma muls_eqmx m1 m2 m3 m4 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n))\n                              (R3 : 'A_(m3, n)) (R4 : 'A_(m4, n)) :\n  (R1 :=: R3 -> R2 :=: R4 -> R1 * R2 = R3 * R4)%MS.\nProof.\nmove=> eqR13 eqR24; rewrite -(genmx_muls R1 R2) -(genmx_muls R3 R4).\nby apply/genmxP; rewrite !mulsmxS ?eqR13 ?eqR24.\nQed.\n\nLemma mulsmxP m1 m2 n A (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n  reflect (exists2 A1, forall i, A1 i \\in R1\n            & exists2 A2, forall i, A2 i \\in R2\n           & A = \\sum_(i < n ^ 2) A1 i *m A2 i)\n          (A \\in R1 * R2)%MS.\nProof.\napply: (iffP idP) => [R_A|[A1 R_A1 [A2 R_A2 ->{A}]]]; last first.\n  by rewrite linear_sum summx_sub // => i _; rewrite mem_mulsmx.\nhave{R_A}: (A \\in R1 * <<R2>>)%MS.\n  by apply: memmx_subP R_A; rewrite mulsmxS ?genmxE.\ncase/memmx_sumsP=> A_ -> R_A; pose A2_ i := vec_mx (row i <<R2>>%MS).\npose A1_ i := mxvec (A_ i) *m pinvmx (R1 *m lin_mx (mulmxr (A2_ i))) *m R1.\nexists (vec_mx \\o A1_) => [i|]; first by rewrite vec_mxK submxMl.\nexists A2_ => [i|]; first by rewrite vec_mxK -(genmxE R2) row_sub.\napply: eq_bigr => i _; rewrite -[_ *m _](mx_rV_lin (mulmxr_linear _ _)).\nby rewrite -mulmxA mulmxKpV ?mxvecK // -(genmxE (_ *m _)) R_A.\nQed.\nImplicit Arguments mulsmxP [m1 m2 n A R1 R2].\n\nLemma mulsmxA m1 m2 m3 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 * R3) = R1 * R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls (_ * _)%MS) -genmx_muls; apply/genmxP; apply/andP; split.\n  apply/mulsmx_subP=> A1 A23 R_A1; case/mulsmxP=> A2 R_A2 [A3 R_A3 ->{A23}].\n  by rewrite !linear_sum summx_sub //= => i _; rewrite mulmxA !mem_mulsmx.\napply/mulsmx_subP=> _ A3 /mulsmxP[A1 R_A1 [A2 R_A2 ->]] R_A3.\nrewrite mulmx_suml linear_sum summx_sub //= => i _.\nby rewrite -mulmxA !mem_mulsmx.\nQed.\n\nLemma mulsmx_addl m1 m2 m3 n\n                 (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  ((R1 + R2) * R3 = R1 * R3 + R2 * R3)%MS.\nProof.\nrewrite -(genmx_muls R2 R3) -(genmx_muls R1 R3) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> _ A3 /memmx_addsP[A [R_A1 R_A2 ->]] R_A3.\nby rewrite mulmxDl linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx_addr m1 m2 m3 n\n                  (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) (R3 : 'A_(m3, n)) :\n  (R1 * (R2 + R3) = R1 * R2 + R1 * R3)%MS.\nProof.\nrewrite -(genmx_muls R1 R3) -(genmx_muls R1 R2) -genmx_muls -genmx_adds.\napply/genmxP; rewrite andbC addsmx_sub !mulsmxS ?addsmxSl ?addsmxSr //=.\napply/mulsmx_subP=> A1 _ R_A1 /memmx_addsP[A [R_A2 R_A3 ->]].\nby rewrite mulmxDr linearD addmx_sub_adds ?mem_mulsmx.\nQed.\n\nLemma mulsmx0 m1 m2 n (R1 : 'A_(m1, n)) : (R1 * (0 : 'A_(m2, n)) = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A1 A0 _.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mulmx0 mem0mx.\nQed.\n\nLemma muls0mx m1 m2 n (R2 : 'A_(m2, n)) : ((0 : 'A_(m1, n)) * R2 = 0)%MS.\nProof.\napply/eqP; rewrite -submx0; apply/mulsmx_subP=> A0 A2.\nby rewrite [A0 \\in 0]eqmx0 => /memmx0->; rewrite mul0mx mem0mx.\nQed.\n\nDefinition left_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R1 * R2 <= R2)%MS.\n\nDefinition right_mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  (R2 * R1 <= R2)%MS.\n\nDefinition mx_ideal m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :=\n  left_mx_ideal R1 R2 && right_mx_ideal R1 R2.\n\nDefinition mxring_id m n (R : 'A_(m, n)) e :=\n  [/\\ e != 0,\n      e \\in R,\n      forall A, A \\in R -> e *m A = A\n    & forall A, A \\in R -> A *m e = A]%MS.\n\nDefinition has_mxring_id m n (R : 'A[F]_(m , n)) :=\n  (R != 0) &&\n  (row_mx 0 (row_mx (mxvec R) (mxvec R))\n    <= row_mx (cokermx R) (row_mx (lin_mx (mulmx R \\o lin_mulmx))\n                                  (lin_mx (mulmx R \\o lin_mulmxr))))%MS.\n\nDefinition mxring m n (R : 'A_(m, n)) :=\n  left_mx_ideal R R && has_mxring_id R.\n\nLemma mxring_idP m n (R : 'A_(m, n)) :\n  reflect (exists e, mxring_id R e) (has_mxring_id R).\nProof.\napply: (iffP andP) => [[nzR] | [e [nz_e Re ideR idRe]]].\n  case/submxP=> v; rewrite -[v]vec_mxK; move/vec_mx: v => e.\n  rewrite !mul_mx_row; case/eq_row_mx => /eqP.\n  rewrite eq_sym -submxE => Re.\n  case/eq_row_mx; rewrite !{1}mul_rV_lin1 /= mxvecK.\n  set u := (_ *m _) => /(can_inj mxvecK) idRe /(can_inj mxvecK) ideR.\n  exists e; split=> // [ | A /submxP[a defA] | A /submxP[a defA]].\n  - by apply: contra nzR; rewrite ideR => /eqP->; rewrite !linear0.\n  - by rewrite -{2}[A]mxvecK defA idRe mulmxA mx_rV_lin -defA /= mxvecK.\n  by rewrite -{2}[A]mxvecK defA ideR mulmxA mx_rV_lin -defA /= mxvecK.\nsplit.\n  by apply: contraNneq nz_e => R0; rewrite R0 eqmx0 in Re; rewrite (memmx0 Re).\napply/submxP; exists (mxvec e); rewrite !mul_mx_row !{1}mul_rV_lin1.\nrewrite submxE in Re; rewrite {Re}(eqP Re).\ncongr (row_mx 0 (row_mx (mxvec _) (mxvec _))); apply/row_matrixP=> i.\n  by rewrite !row_mul !mul_rV_lin1 /= mxvecK ideR vec_mxK ?row_sub.\nby rewrite !row_mul !mul_rV_lin1 /= mxvecK idRe vec_mxK ?row_sub.\nQed.\nImplicit Arguments mxring_idP [m n R].\n\nSection CentMxDef.\n\nVariables (m n : nat) (R : 'A[F]_(m, n)).\n\nDefinition cent_mx_fun (B : 'M[F]_n) := R *m lin_mx (mulmxr B \\- mulmx B).\n\nLemma cent_mx_fun_is_linear : linear cent_mx_fun.\nProof.\nmove=> a A B; apply/row_matrixP=> i; rewrite linearP row_mul mul_rV_lin.\nrewrite /= {-3}[row]lock row_mul mul_rV_lin -lock row_mul mul_rV_lin.\nby rewrite -linearP -(linearP [linear of mulmx _ \\- mulmxr _]).\nQed.\nCanonical cent_mx_fun_additive := Additive cent_mx_fun_is_linear.\nCanonical cent_mx_fun_linear := Linear cent_mx_fun_is_linear.\n\nDefinition cent_mx := kermx (lin_mx cent_mx_fun).\n\nDefinition center_mx := (R :&: cent_mx)%MS.\n\nEnd CentMxDef.\n\nLocal Notation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nLocal Notation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nLemma cent_rowP m n B (R : 'A_(m, n)) :\n  reflect (forall i (A := vec_mx (row i R)), A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP sub_kermxP); rewrite mul_vec_lin => cBE.\n  move/(canRL mxvecK): cBE => cBE i A /=; move/(congr1 (row i)): cBE.\n  rewrite row_mul mul_rV_lin -/A; move/(canRL mxvecK).\n  by move/(canRL (subrK _)); rewrite !linear0 add0r.\napply: (canLR vec_mxK); apply/row_matrixP=> i.\nby rewrite row_mul mul_rV_lin /= cBE subrr !linear0.\nQed.\nImplicit Arguments cent_rowP [m n B R].\n\nLemma cent_mxP m n B (R : 'A_(m, n)) :\n  reflect (forall A, A \\in R -> A *m B = B *m A) (B \\in 'C(R))%MS.\nProof.\napply: (iffP cent_rowP) => cEB => [A sAE | i A].\n  rewrite -[A]mxvecK -(mulmxKpV sAE); move: (mxvec A *m _) => u.\n  rewrite !mulmx_sum_row !linear_sum mulmx_suml; apply: eq_bigr => i _ /=.\n  by rewrite !linearZ -scalemxAl /= cEB.\nby rewrite cEB // vec_mxK row_sub.\nQed.\nImplicit Arguments cent_mxP [m n B R].\n\nLemma scalar_mx_cent m n a (R : 'A_(m, n)) : (a%:M \\in 'C(R))%MS.\nProof. by apply/cent_mxP=> A _; exact: scalar_mxC. Qed.\n\nLemma center_mx_sub m n (R : 'A_(m, n)) : ('Z(R) <= R)%MS.\nProof. exact: capmxSl. Qed.\n\nLemma center_mxP m n A (R : 'A_(m, n)) :\n  reflect (A \\in R /\\ forall B, B \\in R -> B *m A = A *m B)\n          (A \\in 'Z(R))%MS.\nProof.\nrewrite sub_capmx; case R_A: (A \\in R); last by right; case.\nby apply: (iffP cent_mxP) => [cAR | [_ cAR]].\nQed.\nImplicit Arguments center_mxP [m n A R].\n\nLemma mxring_id_uniq m n (R : 'A_(m, n)) e1 e2 :\n  mxring_id R e1 -> mxring_id R e2 -> e1 = e2.\nProof.\nby case=> [_ Re1 idRe1 _] [_ Re2 _ ide2R]; rewrite -(idRe1 _ Re2) ide2R.\nQed.\n\nLemma cent_mx_ideal m n (R : 'A_(m, n)) : left_mx_ideal 'C(R)%MS 'C(R)%MS.\nProof.\napply/mulsmx_subP=> A1 A2 C_A1 C_A2; apply/cent_mxP=> B R_B.\nby rewrite mulmxA (cent_mxP C_A1) // -!mulmxA (cent_mxP C_A2).\nQed.\n\nLemma cent_mx_ring m n (R : 'A_(m, n)) : n > 0 -> mxring 'C(R)%MS.\nProof.\nmove=> n_gt0; rewrite /mxring cent_mx_ideal; apply/mxring_idP.\nexists 1%:M; split=> [||A _|A _]; rewrite ?mulmx1 ?mul1mx ?scalar_mx_cent //.\nby rewrite -mxrank_eq0 mxrank1 -lt0n.\nQed.\n\nLemma mxdirect_adds_center m1 m2 n (R1 : 'A_(m1, n)) (R2 : 'A_(m2, n)) :\n    mx_ideal (R1 + R2)%MS R1 -> mx_ideal (R1 + R2)%MS R2 ->\n    mxdirect (R1 + R2) ->\n  ('Z((R1 + R2)%MS) :=: 'Z(R1) + 'Z(R2))%MS.\nProof.\ncase/andP=> idlR1 idrR1 /andP[idlR2 idrR2] /mxdirect_addsP dxR12.\napply/eqmxP/andP; split.\n  apply/memmx_subP=> z0; rewrite sub_capmx => /andP[].\n  case/memmx_addsP=> z [R1z1 R2z2 ->{z0}] Cz.\n  rewrite linearD addmx_sub_adds //= ?sub_capmx ?R1z1 ?R2z2 /=.\n    apply/cent_mxP=> A R1_A; have R_A := submx_trans R1_A (addsmxSl R1 R2).\n    have Rz2 := submx_trans R2z2 (addsmxSr R1 R2).\n    rewrite -{1}[z.1](addrK z.2) mulmxBr (cent_mxP Cz) // mulmxDl.\n    rewrite [A *m z.2]memmx0 1?[z.2 *m A]memmx0 ?addrK //.\n      by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  apply/cent_mxP=> A R2_A; have R_A := submx_trans R2_A (addsmxSr R1 R2).\n  have Rz1 := submx_trans R1z1 (addsmxSl R1 R2).\n  rewrite -{1}[z.2](addKr z.1) mulmxDr (cent_mxP Cz) // mulmxDl.\n  rewrite mulmxN [A *m z.1]memmx0 1?[z.1 *m A]memmx0 ?addKr //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nrewrite addsmx_sub; apply/andP; split.\n  apply/memmx_subP=> z; rewrite sub_capmx => /andP[R1z cR1z].\n  have Rz := submx_trans R1z (addsmxSl R1 R2).\n  rewrite sub_capmx Rz; apply/cent_mxP=> A0.\n  case/memmx_addsP=> A [R1_A1 R2_A2] ->{A0}.\n  have R_A2 := submx_trans R2_A2 (addsmxSr R1 R2).\n  rewrite mulmxDl mulmxDr (cent_mxP cR1z) //; congr (_ + _).\n  rewrite [A.2 *m z]memmx0 1?[z *m A.2]memmx0 //.\n    by rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\napply/memmx_subP=> z; rewrite !sub_capmx => /andP[R2z cR2z].\nhave Rz := submx_trans R2z (addsmxSr R1 R2); rewrite Rz.\napply/cent_mxP=> _ /memmx_addsP[A [R1_A1 R2_A2 ->]].\nrewrite mulmxDl mulmxDr (cent_mxP cR2z _ R2_A2) //; congr (_ + _).\nhave R_A1 := submx_trans R1_A1 (addsmxSl R1 R2).\nrewrite [A.1 *m z]memmx0 1?[z *m A.1]memmx0 //.\n  by rewrite -dxR12 sub_capmx (mulsmx_subP idlR1) // (mulsmx_subP idrR2).\nby rewrite -dxR12 sub_capmx (mulsmx_subP idrR1) // (mulsmx_subP idlR2).\nQed.\n\nLemma mxdirect_sums_center (I : finType) m n (R : 'A_(m, n)) R_ :\n    (\\sum_i R_ i :=: R)%MS -> mxdirect (\\sum_i R_ i) ->\n    (forall i : I, mx_ideal R (R_ i)) ->\n  ('Z(R) :=: \\sum_i 'Z(R_ i))%MS.\nProof.\nmove=> defR dxR idealR.\nhave sR_R: (R_ _ <= R)%MS by move=> i; rewrite -defR (sumsmx_sup i).\nhave anhR i j A B : i != j -> A \\in R_ i -> B \\in R_ j -> A *m B = 0.\n  move=> ne_ij RiA RjB; apply: memmx0.\n  have [[_ idRiR] [idRRj _]] := (andP (idealR i), andP (idealR j)).\n  rewrite -(mxdirect_sumsP dxR j) // sub_capmx (sumsmx_sup i) //.\n    by rewrite (mulsmx_subP idRRj) // (memmx_subP (sR_R i)).\n  by rewrite (mulsmx_subP idRiR) // (memmx_subP (sR_R j)).\napply/eqmxP/andP; split.\n  apply/memmx_subP=> Z; rewrite sub_capmx => /andP[].\n  rewrite -{1}defR => /memmx_sumsP[z ->{Z} Rz cRz].\n  apply/memmx_sumsP; exists z => // i; rewrite sub_capmx Rz.\n  apply/cent_mxP=> A RiA; have:= cent_mxP cRz A (memmx_subP (sR_R i) A RiA).\n  rewrite (bigD1 i) //= mulmxDl mulmxDr mulmx_suml mulmx_sumr.\n  by rewrite !big1 ?addr0 // => j; last rewrite eq_sym; move/anhR->.\napply/sumsmx_subP => i _; apply/memmx_subP=> z; rewrite sub_capmx.\ncase/andP=> Riz cRiz; rewrite sub_capmx (memmx_subP (sR_R i)) //=.\napply/cent_mxP=> A; rewrite -{1}defR; case/memmx_sumsP=> a -> R_a.\nrewrite (bigD1 i) // mulmxDl mulmxDr mulmx_suml mulmx_sumr.\nrewrite !big1 => [|j|j]; first by rewrite !addr0 (cent_mxP cRiz).\n  by rewrite eq_sym => /anhR->.\nby move/anhR->.\nQed.\n\nEnd MatrixAlgebra.\n\nArguments Scope mulsmx\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope left_mx_ideal\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope right_mx_ideal\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope mx_ideal\n  [_ nat_scope nat_scope nat_scope matrix_set_scope matrix_set_scope].\nArguments Scope mxring_id\n  [_ nat_scope nat_scope ring_scope matrix_set_scope].\nArguments Scope has_mxring_id\n  [_ nat_scope nat_scope ring_scope matrix_set_scope].\nArguments Scope mxring\n  [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope cent_mx\n  [_ nat_scope nat_scope matrix_set_scope].\nArguments Scope center_mx\n  [_ nat_scope nat_scope matrix_set_scope].\n\nPrenex Implicits mulsmx.\n\nNotation \"A \\in R\" := (submx (mxvec A) R) : matrix_set_scope.\nNotation \"R * S\" := (mulsmx R S) : matrix_set_scope.\nNotation \"''C' ( R )\" := (cent_mx R) : matrix_set_scope.\nNotation \"''C_' R ( S )\" := (R :&: 'C(S))%MS : matrix_set_scope.\nNotation \"''C_' ( R ) ( S )\" := ('C_R(S))%MS (only parsing) : matrix_set_scope.\nNotation \"''Z' ( R )\" := (center_mx R) : matrix_set_scope.\n\nImplicit Arguments memmx_subP [F m1 m2 n R1 R2].\nImplicit Arguments memmx_eqP [F m1 m2 n R1 R2].\nImplicit Arguments memmx_addsP [F m1 m2 n R1 R2].\nImplicit Arguments memmx_sumsP [F I P n A R_].\nImplicit Arguments mulsmx_subP [F m1 m2 m n R1 R2 R].\nImplicit Arguments mulsmxP [F m1 m2 n A R1 R2].\nImplicit Arguments mxring_idP [m n R].\nImplicit Arguments cent_rowP [F m n B R].\nImplicit Arguments cent_mxP [F m n B R].\nImplicit Arguments center_mxP [F m n A R].\n\n(* Parametricity for the row-space/F-algebra theory.                         *)\nSection MapMatrixSpaces.\n\nVariables (aF rF : fieldType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\n\nLemma Gaussian_elimination_map m n (A : 'M_(m, n)) :\n  Gaussian_elimination A^f = ((col_ebase A)^f, (row_ebase A)^f, \\rank A).\nProof.\nrewrite mxrankE /row_ebase /col_ebase unlock.\nelim: m n A => [|m IHm] [|n] A /=; rewrite ?map_mx1 //.\nset pAnz := [pred k | A k.1 k.2 != 0].\nrewrite (@eq_pick _ _ pAnz) => [|k]; last by rewrite /= mxE fmorph_eq0.\ncase: {+}(pick _) => [[i j]|]; last by rewrite !map_mx1.\nrewrite mxE -fmorphV  -map_xcol -map_xrow -map_dlsubmx -map_drsubmx.\nrewrite -map_ursubmx -map_mxZ -map_mxM -map_mx_sub {}IHm /=.\ncase: {+}(Gaussian_elimination _) => [[L U] r] /=; rewrite map_xrow map_xcol.\nby rewrite !(@map_block_mx _ _ f 1 _ 1) !map_mx0 ?map_mx1 ?map_scalar_mx.\nQed.\n\nLemma mxrank_map m n (A : 'M_(m, n)) : \\rank A^f = \\rank A.\nProof. by rewrite mxrankE Gaussian_elimination_map. Qed.\n\nLemma row_free_map m n (A : 'M_(m, n)) : row_free A^f = row_free A.\nProof. by rewrite /row_free mxrank_map. Qed.\n\nLemma row_full_map m n (A : 'M_(m, n)) : row_full A^f = row_full A.\nProof. by rewrite /row_full mxrank_map. Qed.\n\nLemma map_row_ebase m n (A : 'M_(m, n)) : (row_ebase A)^f = row_ebase A^f.\nProof. by rewrite {2}/row_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_col_ebase m n (A : 'M_(m, n)) : (col_ebase A)^f = col_ebase A^f.\nProof. by rewrite {2}/col_ebase unlock Gaussian_elimination_map. Qed.\n\nLemma map_row_base m n (A : 'M_(m, n)) :\n  (row_base A)^f = castmx (mxrank_map A, erefl n) (row_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/row_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_row_ebase.\nQed.\n\nLemma map_col_base m n (A : 'M_(m, n)) :\n  (col_base A)^f = castmx (erefl m, mxrank_map A) (col_base A^f).\nProof.\nmove: (mxrank_map A); rewrite {2}/col_base mxrank_map => eqrr.\nby rewrite castmx_id map_mxM map_pid_mx map_col_ebase.\nQed.\n\nLemma map_pinvmx m n (A : 'M_(m, n)) : (pinvmx A)^f = pinvmx A^f.\nProof.\nrewrite !map_mxM !map_invmx map_row_ebase map_col_ebase.\nby rewrite map_pid_mx -mxrank_map.\nQed.\n\nLemma map_kermx m n (A : 'M_(m, n)) : (kermx A)^f = kermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_col_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_cokermx m n (A : 'M_(m, n)) : (cokermx A)^f = cokermx A^f.\nProof.\nby rewrite !map_mxM map_invmx map_row_ebase -mxrank_map map_copid_mx.\nQed.\n\nLemma map_submx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f <= B^f)%MS = (A <= B)%MS.\nProof. by rewrite !submxE -map_cokermx -map_mxM map_mx_eq0. Qed.\n\nLemma map_ltmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f < B^f)%MS = (A < B)%MS.\nProof. by rewrite /ltmx !map_submx. Qed.\n\nLemma map_eqmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (A^f :=: B^f)%MS <-> (A :=: B)%MS.\nProof.\nsplit=> [/eqmxP|eqAB]; first by rewrite !map_submx => /eqmxP.\nby apply/eqmxP; rewrite !map_submx !eqAB !submx_refl.\nQed.\n\nLemma map_genmx m n (A : 'M_(m, n)) : (<<A>>^f :=: <<A^f>>)%MS.\nProof. by apply/eqmxP; rewrite !(genmxE, map_submx) andbb. Qed.\n\nLemma map_addsmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (((A + B)%MS)^f :=: A^f + B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !addsmxE -map_col_mx !map_submx !addsmxE andbb.\nQed.\n\nLemma map_capmx_gen m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  (capmx_gen A B)^f = capmx_gen A^f B^f.\nProof. by rewrite map_mxM map_lsubmx map_kermx map_col_mx. Qed.\n\nLemma map_capmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :&: B)^f :=: A^f :&: B^f)%MS.\nProof.\nby apply/eqmxP; rewrite !capmxE -map_capmx_gen !map_submx -!capmxE andbb.\nQed.\n\nLemma map_complmx m n (A : 'M_(m, n)) : (A^C^f = A^f^C)%MS.\nProof. by rewrite map_mxM map_row_ebase -mxrank_map map_copid_mx. Qed.\n\nLemma map_diffmx m1 m2 n (A : 'M_(m1, n)) (B : 'M_(m2, n)) :\n  ((A :\\: B)^f :=: A^f :\\: B^f)%MS.\nProof.\napply/eqmxP; rewrite !diffmxE -map_capmx_gen -map_complmx.\nby rewrite -!map_capmx !map_submx -!diffmxE andbb.\nQed.\n\nLemma map_eigenspace n (g : 'M_n) a : (eigenspace g a)^f = eigenspace g^f (f a).\nProof. by rewrite map_kermx map_mx_sub ?map_scalar_mx. Qed.\n\nLemma eigenvalue_map n (g : 'M_n) a : eigenvalue g^f (f a) = eigenvalue g a.\nProof. by rewrite /eigenvalue -map_eigenspace map_mx_eq0. Qed.\n\nLemma memmx_map m n A (E : 'A_(m, n)) : (A^f \\in E^f)%MS = (A \\in E)%MS.\nProof. by rewrite -map_mxvec map_submx. Qed.\n\nLemma map_mulsmx m1 m2 n (E1 : 'A_(m1, n)) (E2 : 'A_(m2, n)) :\n  ((E1 * E2)%MS^f :=: E1^f * E2^f)%MS.\nProof.\nrewrite /mulsmx; elim/big_rec2: _ => [|i A Af _ eqA]; first by rewrite map_mx0.\napply: (eqmx_trans (map_addsmx _ _)); apply: adds_eqmx {A Af}eqA.\napply/eqmxP; rewrite !map_genmx !genmxE map_mxM.\napply/rV_eqP=> u; congr (u <= _ *m _)%MS.\nby apply: map_lin_mx => //= A; rewrite map_mxM // map_vec_mx map_row.\nQed.\n\nLemma map_cent_mx m n (E : 'A_(m, n)) : ('C(E)%MS)^f = 'C(E^f)%MS.\nProof.\nrewrite map_kermx //; congr (kermx _); apply: map_lin_mx => // A.\nrewrite map_mxM //; congr (_ *m _); apply: map_lin_mx => //= B.\nby rewrite map_mx_sub ? map_mxM.\nQed.\n\nLemma map_center_mx m n (E : 'A_(m, n)) : (('Z(E))^f :=: 'Z(E^f))%MS.\nProof. by rewrite /center_mx -map_cent_mx; exact: map_capmx. Qed.\n\nEnd MapMatrixSpaces.\n\n\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect1.4_v8.3/theories/mxalgebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7107827219624399}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega.\n\nRequire Import decidable_t.\n\nSet Implicit Arguments.\n\n(** Thanks to a remark of Yannick Forster at ITP 2017,\n    it seems that I rediscovered a result of Coq's \n    standard library (Constructive Epsilon), with\n    similar proofs (although a bit different in \n    presentation).\n   \n    I have to add that the ad-hoc inductive predicate \n    \"before_witness\" which is defined in Section \n    \n      ConstructiveIndefiniteGroundDescription_Direct\n   \n    is in fact a restricted form of Bar inductive predicate \n *)\n\nSection nat_reify.\n\n  (** This is UNBOUNDED minimization when a certificate of termination\n     is provided \n     \n     But in this simpler case, we do not show that the minimum\n     is computed \n     \n  *)\n\n  Variable P : nat -> Prop.\n  Hypothesis HP : forall n, { P n } + { ~ P n }.\n  \n  Let R x y := x = S y /\\ ~ P y.\n  \n  Let P_Acc_R x : P x -> Acc R x.\n  Proof.\n    constructor; intros ? (_ & []); auto.\n  Qed.\n  \n  Let Acc_R_dec x : Acc R (S x) -> Acc R x.\n  Proof.\n    constructor; intros ? (? & _); subst; auto.\n  Qed.\n  \n  Let Acc_R_zero x : Acc R x -> Acc R 0.\n  Proof.\n    induction x; auto.\n  Qed.\n\n  Let Acc_exists_eq x : Acc R x <-> exists i, x <= i /\\ P i.\n  Proof.\n    split.\n    \n    induction 1 as [ x Hx IHx ].\n    destruct (HP x).\n    exists x; auto.\n    destruct IHx with (S x) as (i & ? & ?); \n      [ | exists i ]; split; auto; omega.\n    \n    intros (i & H1 & H2).\n    apply P_Acc_R in H2.\n    revert H2.\n    replace i with ((i-x)+x) by omega.\n    generalize (i-x); clear i H1. \n    intros i; induction i; auto.\n  Qed.\n  \n  (* @Acc_inv x Hx F is a proof of Acc R (S x) which is\n     *structurally simpler* than Hx, the given proof of Acc R x \n   *) \n  \n  Let Acc_inv x (Hx : Acc R x) (F : ~ P x) : Acc R (S x).\n  Proof.\n    refine (match Hx with \n      | Acc_intro _ H => H _ _  (* H : forall y, R y x -> Acc R y *)\n    end).\n    split; trivial.\n  Qed.\n  \n  Let Acc_inv' x (Hx : Acc R x) (F : ~ P x) : Acc R (S x) :=\n    let F' := conj eq_refl F     (* F'  : R (S x) x   *)\n    in match Hx with \n      | Acc_intro _ H => H _ F'  (* H : forall y, R y x -> Acc R y *)\n    end.\n  \n  (* Hence the following fixpoint type-checks \n     with Hx as structurally decreasing argument \n   *)\n  \n  Fixpoint Acc_P x (Hx : Acc R x) : { m | P m } :=\n    match HP x with\n      | left  T => exist _ x T\n      | right F => @Acc_P (S x) (@Acc_inv x Hx F)\n    end.\n  \n  Print Acc_P.\n  \n  Let Acc_P' := fix Acc_P' x (Hx : Acc R x) : { m | P m } :=\n    match HP x with\n      | left  T => exist _ x T\n      | right F => \n        let Hx' := match Hx with \n              Acc_intro _ H => H (S x) (conj eq_refl F) \n        end in Acc_P' (S x) Hx'\n    end.\n    \n  Print Acc_P'.\n\n  Let Acc_P'' : forall x (Hx : Acc R x), { m | P m }.\n  Proof.\n    refine (fix loop x Hx { struct Hx } := _).\n    destruct (@HP x) as [ H | H ].\n    exists x; trivial.\n    destruct (loop (S x)) as (m & H2).\n    destruct Hx as [ Hx ].\n    apply Hx; split; trivial.\n    exists m; trivial.\n  Qed.\n  \n  Print Acc_P''.\n\n  Theorem nat_reify : (exists x, P x) -> { x | P x }.\n  Proof.\n    intros H. \n    apply Acc_P with 0.\n    destruct H as (x & Hx).\n    apply Acc_R_zero with x, P_Acc_R, Hx.\n  Qed.\n\n  (* Same as nat_reif but we show that the computed value\n     is the minimum *)\n     \n  Let Acc_P_min : forall x (Hx : Acc R x), { m | P m /\\ forall y, P y -> y < x \\/ m <= y }.\n  Proof.\n    refine (fix Acc_P_min x Hx { struct Hx } := \n      match HP x with \n        | left T  => exist _ x _\n        | right F => match Acc_P_min (S x) _ with exist _ m H => exist _ m _ end\n      end).\n      \n    split; trivial.\n    intros y _; destruct (le_lt_dec x y); auto.\n    \n    destruct Hx as [ Hx ].\n    apply Hx; red; auto.\n    \n    clear Acc_P_min.  (* we do not want the automatic tactics to use that one *)\n    destruct H as [ H1 H2 ].\n    split; trivial.\n    intros y Hy.\n    destruct (eq_nat_dec x y) as [ | ].\n    subst; contradict F; trivial.\n    specialize (H2 _ Hy); omega.\n  Qed.\n  \n  Print Acc_P_min.\n  \n  Theorem nat_minimizer : (exists x, P x) -> { x | P x /\\ forall y, P y -> x <= y }.\n  Proof.\n    intros H.\n    destruct Acc_P_min with 0 as (m & H1 & H2).\n\n    destruct H as (x & Hx).\n    apply Acc_R_zero with x, P_Acc_R, Hx.\n    \n    exists m; split; auto.\n    intros ? Hy; specialize (H2 _ Hy); omega.\n  Qed.\n  \nEnd nat_reify.\n\nSection nat_reify_t.\n\n  (* The same but with nat -> Type predicates instead of nat -> Prop *)\n\n  Variable P : nat -> Type.\n  Hypothesis HP : forall n, decidable_t (P n).\n  \n  Let R x y := x = S y /\\ ~ inhabited (P y).\n  \n  Let P_Acc_R x : P x -> Acc R x.\n  Proof.\n    intros H.\n    constructor. \n    intros ? (_ & []).\n    exists; auto.\n  Qed.\n  \n  Let Acc_R_dec x : Acc R (S x) -> Acc R x.\n  Proof.\n    constructor; intros ? (? & _); subst; auto.\n  Qed.\n  \n  Let Acc_R_zero x : Acc R x -> Acc R 0.\n  Proof.\n    induction x; auto.\n  Qed.\n  \n  Let Acc_inv x : Acc R x -> (P x -> False) -> Acc R (S x).\n  Proof.\n    intros [ Hx ] F; apply Hx; split.\n    * reflexivity.\n    * intros [ t ]; exact (F t).\n  Defined.\n  \n  Print Acc_inv.\n \n  Let Acc_P := fix Acc_P x (Hx : Acc R x) : sigT P :=\n    match HP x with\n      | inl T => existT _ x T\n      | inr F => @Acc_P (S x) (@Acc_inv x Hx F)\n    end.\n  \n  Theorem nat_reify_t : (exists x, inhabited (P x)) -> { x : nat & P x }.\n  Proof.\n    intros H; apply Acc_P with 0.\n    destruct H as (x & [ Hx ]).\n    apply Acc_R_zero with x, P_Acc_R, Hx.\n  Qed.\n  \nEnd nat_reify_t.\n\nSection functional_countable_decidable_choice.\n\n  Variable (X : Type) (R : X -> nat -> Prop) (HR : forall x n, { R x n } + { ~ R x n }).\n  \n  Theorem FunctionalCountableDecidableChoice : (forall x, exists n, R x n) -> { f | forall x, R x (f x) }.\n  Proof.\n    intros H.\n    set (f x := @nat_reify (R x) (HR x) (H x)).\n    exists (fun x => proj1_sig (f x)).\n    intros x.\n    apply (proj2_sig (f x)).\n  Qed.\n  \nEnd functional_countable_decidable_choice.\n\nCheck FunctionalCountableDecidableChoice.\n\nExtraction \"minimize.ml\" nat_reify nat_minimizer nat_reify_t.\n\n", "meta": {"author": "DmxLarchey", "repo": "Coq-is-total", "sha": "0f3facc9cf06e0b41194fdb0cc952816fb09c39a", "save_path": "github-repos/coq/DmxLarchey-Coq-is-total", "path": "github-repos/coq/DmxLarchey-Coq-is-total/Coq-is-total-0f3facc9cf06e0b41194fdb0cc952816fb09c39a/nat_minimizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7107827113595789}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (x : natural) : natural := mult x lf3.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj146_coqofml_Bcutj9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7107827044587341}}
{"text": "(** Numbers represented as lists of digits. *)\n\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\n\nLocal Open Scope N.\n\nInductive digits : Set :=\n| Zero\n| Digit : digits -> N -> digits\n.\n\nArguments digits : clear implicits.\n\nSection Digits.\n\nContext (base : N).\n\n(** Add two digits and a carry *)\nDefinition adder (d d0 c : N) : N * N :=\n  let s := c + d + d0 in\n  if s <? base then (0, s) else (1, s - base).\n\n(* [2 * n + d0] *)\nFixpoint double_plus (c : N) (n : digits) :=\n  match n with\n  | Zero =>\n    if c =? 0 then Zero else Digit Zero c\n  | Digit n d =>\n    let (c, d) := adder d d c in\n    Digit (double_plus c n) d\n  end.\n\nFixpoint digits_of_pos (p : positive) :=\n  match p with\n  | xH => Digit Zero 1\n  | xI p => double_plus 1 (digits_of_pos p)\n  | xO p => double_plus 0 (digits_of_pos p)\n  end.\n\nDefinition digits_of_N (n : N) :=\n  match n with\n  | N0 => Digit Zero 0\n  | Npos p => digits_of_pos p\n  end.\n\nEnd Digits.\n\nDefinition binary_ascii (n : N) : ascii :=\n  match n with\n  | 0 =>  \"0\"%char\n  | _ =>  \"1\"%char\n  end.\n\nDefinition octal_ascii (n : N) : ascii :=\n  match n with\n  | 2 =>  \"2\"%char\n  | 3 =>  \"3\"%char\n  | 4 =>  \"4\"%char\n  | 5 =>  \"5\"%char\n  | 6 =>  \"6\"%char\n  | 7 =>  \"7\"%char\n  | _ => binary_ascii n\n  end.\n\nDefinition decimal_ascii (n : N) : ascii :=\n  match n with\n  | 8 =>  \"8\"%char\n  | 9 =>  \"9\"%char\n  | _ => octal_ascii n\n  end.\n\nDefinition hex_ascii (n : N) : ascii :=\n  match n with\n  | 10 => \"a\"%char\n  | 11 => \"b\"%char\n  | 12 => \"c\"%char\n  | 13 => \"d\"%char\n  | 14 => \"e\"%char\n  | 15 => \"f\"%char\n  | _  => decimal_ascii n\n  end.\n\nDefinition hex_ascii_upper (n : N) : ascii :=\n  match n with\n  | 10 => \"A\"%char\n  | 11 => \"B\"%char\n  | 12 => \"C\"%char\n  | 13 => \"D\"%char\n  | 14 => \"E\"%char\n  | 15 => \"F\"%char\n  | _  => decimal_ascii n\n  end.\n\nLocal Fixpoint string_of_digits_\n    (digit : N -> ascii)\n    (s : string)\n    (n : digits)\n  : string :=\n  match n with\n  | Zero => s\n  | Digit n d => string_of_digits_ digit (String (digit d) s) n\n  end.\n\nDefinition string_of_digits (digit : N -> ascii) : digits -> string :=\n  string_of_digits_ digit \"\".\n\nDefinition string_of_N (base : N) (digit : N -> ascii) (n : N) : string :=\n  string_of_digits digit (digits_of_N base n).\n\nDefinition binary_string (n : N) :=\n  string_of_N 2 binary_ascii n.\n\nDefinition hex_string (n : N) :=\n  string_of_N 16 hex_ascii n.\n\nDefinition hex_string_upper (n : N) :=\n  string_of_N 16 hex_ascii_upper n.\n\nDefinition octal_string (n : N) :=\n  string_of_N 8 octal_ascii n.\n\nDefinition decimal_string (n : N) :=\n  string_of_N 10 decimal_ascii n.\n", "meta": {"author": "gmalecha", "repo": "coq-printf", "sha": "e8e77a3e9c3bf743c0e21752c58d04fbc16cce6c", "save_path": "github-repos/coq/gmalecha-coq-printf", "path": "github-repos/coq/gmalecha-coq-printf/coq-printf-e8e77a3e9c3bf743c0e21752c58d04fbc16cce6c/theories/Digits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7956581097540518, "lm_q1q2_score": 0.7107688779666782}}
{"text": "(*\nWe present a characterization of the equality in an Indexed W type\nas an Indexed W type of the same shape.\n(assuming function extensionality)\n\nThat is, a path between (sup x children1) and (sup y children2) is\na path p between x and y,\nand a path between each pair of children, lying over p.\n\nI am not aware of this result in any of the literature,\nbut I believe it is an interesting result.\nIn particular, I was surprised not to find it in the HoTT book.\n*)\n\nFrom IWTypes Require Import IWType.\nFrom IWTypes Require Import FunctionExtensionality.\n\n(* We aren't working with nat, and we want to use the * notation for pairs. *)\nClose Scope nat_scope.\n\nSection IWEquality.\nContext {FunExt : FunExt}.\nContext {S : spec}.\n\n(* Postulate an implementation I of S *)\nContext (I : impl S).\n\n(* Define the type of children of a node labeled by x *)\nDefinition children_for (x : Data S) := forall c, carrier I (child_index x c).\n\n(* We claim that equality in T satisfies the following spec: *)\nDefinition Seq : spec := {|\n  Data := {x : Data S & children_for x * children_for x};\n  Children := fun '(existT _ x _) => Children x;\n  Index := {i : Index S & carrier I i * carrier I i};\n  index := fun '(existT _ x (children1, children2)) =>\n    existT _ (index x) (sup I x children1, sup I x children2);\n  child_index := fun '(existT _ x (children1, children2)) c =>\n    existT _ _ (children1 c, children2 c);\n|}.\n\n(* This is the type family we claim satisfies the above spec *)\nDefinition eq_type : Index Seq -> Type\n  := fun '(existT _ i (a, b)) => a = b.\n(* Introduction rule, easy by funext *)\nDefinition eq_sup\n  : forall dat : Data Seq, (forall c, eq_type (child_index dat c)) ->\n    eq_type (index dat)\n  := fun '(existT _ x (children1, children2)) children_eq =>\n     f_equal (sup I x) (funext children_eq).\n\n(* Now we prove that we have the induction rule, and that it computes. *)\nSection induct.\nContext\n  (P : forall iab, eq_type iab -> Type)\n  (IS : forall dat children_eq, (forall c, P _ (children_eq c)) ->\n        P (index dat) (eq_sup dat children_eq)).\n\n(* First we show that P holds for reflexivity *)\nDefinition eq_induct_refl : forall i a, P (existT _ i (a, a)) eq_refl\n  := induct I (fun i a => P (existT _ i (a, a)) eq_refl)\n     (fun x children refl_children_P => eq_rect\n      (funext (happly eq_refl))\n      (fun p' =>\n       P (existT _ (index x) (sup I x children, sup I x children))\n       (f_equal (sup I x) p'))\n      (IS (existT _ x (children, children)) (happly eq_refl)\n       refl_children_P)\n      eq_refl\n      (funext_comp eq_refl)).\n\n(* Then we use path induction to generalize. *)\nDefinition eq_induct\n  : forall iab p, P iab p\n  := fun '(existT _ i (a, b)) (p : a = b) => match p in (_ = b)\n     return P (existT _ i (a, b)) p with eq_refl => eq_induct_refl i a end.\n\n(* Finally, we show that the induction above computes as expected. *)\n\n(* First eq_induct_refl: *)\nDefinition eq_induct_refl_computes\n  x children1\n  : eq_induct_refl (index x) (sup I x children1) =\n    eq_rect (funext (fun c => eq_refl)) _\n      (IS (existT _ x (children1, children1)) (happly eq_refl)\n       (fun c => eq_induct_refl _ (children1 c)))\n      eq_refl (funext_comp eq_refl)\n  := induct_computes I _ _ _ _.\n\n(* Then in general *)\nDefinition eq_induct_computes\n  : forall dat children_eq,\n    eq_induct (index dat) (eq_sup dat children_eq) =\n    IS dat children_eq (fun c => eq_induct _ (children_eq c))\n  := fun '(existT _ x (children1, children2)) =>\n     fun children_eq : forall c, children1 c = children2 c =>\n     eq_trans (eq_trans\n     (match funext children_eq\n      as p' in (_ = children2)\n      return\n        match f_equal (sup I x) p' as p'' in (_ = b)\n        return P (existT _ (index x) (sup I x children1, b)) p''\n        with eq_refl => eq_induct_refl (index x) (sup I x children1) end\n        =\n        eq_rect (funext (happly p'))\n        (fun p'' => P (existT _ _ (_, _)) (f_equal (sup I x) p''))\n        (IS (existT _ x (children1, children2)) (happly p')\n         (fun c => eq_induct (existT _ _ (_, _)) (happly p' c)))\n        p' (funext_comp p')\n      with eq_refl => eq_induct_refl_computes x children1\n      end)\n     (f_equal (eq_rect _ _ _ _) (funext_adjoint children_eq)))\n     (match funext_app children_eq as children_p in (_ = children_eq')\n      return\n        eq_rect _ _ _ _ (f_equal funext children_p) =\n        IS (existT _ x (children1, children2)) children_eq'\n        (fun c => eq_induct (existT _ _ (_, _)) (children_eq' c))\n      with eq_refl => eq_refl end).\nEnd induct.\n\n(* Thus the equality is an inductive family: *)\nDefinition Ieq : impl Seq\n  := Build_impl Seq eq_type eq_sup eq_induct eq_induct_computes.\n\nEnd IWEquality.\nArguments eq_sup {FunExt S I} dat children.\n", "meta": {"author": "jashug", "repo": "IWTypes", "sha": "57b179d313e0061c9116bd03ac143c5bed25680c", "save_path": "github-repos/coq/jashug-IWTypes", "path": "github-repos/coq/jashug-IWTypes/IWTypes-57b179d313e0061c9116bd03ac143c5bed25680c/CharacterizeIWEquality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7107688651726978}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (z : natural) (x : natural) (lf1 : natural)\n  : natural := mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj64_coqofml_KeBrKM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7107392148875046}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := mult z (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj235_coqofml_aYEUOm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7107392066409135}}
{"text": "Require Import ZArith Znumtheory Lia Zpow_facts MyZ.\nRequire Import Hurwitz_def.\n\nSection basic_lemmas.\n\nVariable h1 h2 h3 : Hurwitz.\n\n(* eq *)\n\nLemma Hurwitz_dec : { h1 = h2 } + { h1 <> h2 }.\nProof.\nrepeat decide equality.\nQed.\n\n(* hopp *)\n\nLemma hopp_invol : h- (h- h1) = h1.\nProof.\ndestruct h1 ; simpl ; f_equal ; ring.\nQed.\n\nLemma hopp_hadd_distrib : h- (h1 h+ h2) = h- h1 h+ h- h2.\nProof.\ndestruct h1, h2, h3 ; simpl ; f_equal ; ring.\nQed.\n\nLemma hopp_hadd_hminus : h- h1 h+ h2 = h2 h- h1.\nProof.\ndestruct h1, h2 ; simpl ; f_equal ; ring.\nQed.\n\n(* hadd *)\n\nLemma hadd_comm : h1 h+ h2 = h2 h+ h1.\nProof.\ndestruct h1, h2 ; simpl ; f_equal ; ring.\nQed.\n\nLemma hadd_assoc : h1 h+ h2 h+ h3 = h1 h+ (h2 h+ h3).\nProof.\ndestruct h1, h2, h3 ; simpl ; f_equal ; ring.\nQed.\n\n(* hmul *)\n\nLemma hmul_assoc : forall a b c, hmul a (hmul b c) = hmul (hmul a b) c.\nProof.\nintros [] [] []; intros.\n unfold hmul ; f_equal ; ring.\nQed.\n\nLemma hmul_1_l : hmul (IZH 1) h1 = h1.\nProof.\ndestruct h1 ; intros.\nunfold hmul, IZH.\nf_equal; ring.\nQed.\n\nLemma hmul_1_r : hmul h1 (IZH 1) = h1.\nProof.\ndestruct h1 ; intros.\nunfold hmul, IZH.\nf_equal; ring.\nQed.\n\n(* conjugate *)\n\nLemma hconj_invol : hconj (hconj h1) = h1.\nProof.\ndestruct h1 ; intros ; unfold hconj ; f_equal ; ring.\nQed.\n\nLemma hconj_hopp : hconj (h- h1) = h- (hconj h1).\nunfold hconj, hopp ; destruct h1 ; intros ; f_equal ; ring.\nQed.\n\nLemma hconj_hadd : hconj (h1 h+ h2) = hconj h1 h+ hconj h2.\nProof.\nunfold hconj, hadd ; destruct h1, h2 ; intros ; f_equal ; ring.\nQed.\n\nLemma hconj_hminus : hconj (h1 h- h2) = (hconj h1) h- (hconj h2).\nProof.\nunfold hminus, hadd, hopp, hconj ; destruct h1, h2 ; intros ; f_equal ; ring.\nQed.\n\nLemma hconj_hmul : hconj (h1 h* h2) = (hconj h2) h* (hconj h1).\nProof.\nunfold hmul, hconj ; destruct h1, h2 ; f_equal ; ring.\nQed.\n\n(* norm *)\n\nLemma hnorm2_IZH : forall z, hnorm2 (IZH z) = z ^ 2.\nProof.\nintro z ; unfold hnorm2, hconj, IZH, hmul, i ; ring.\nQed.\n\nLemma hnorm2_hconj : hnorm2 (hconj h1) = hnorm2 h1.\nProof.\ndestruct h1 ; intros ; unfold hnorm2 , hconj , hmul, Hurwitz_def.i ;\n ring.\nQed.\n\nLemma hnorm2_hmul : hnorm2 (h1 h* h2) = hnorm2 h1 * hnorm2 h2.\nProof.\ndestruct h1, h2 ; unfold hnorm2, hconj, hmul, Hurwitz_def.i ;\n ring.\nQed.\n\nLemma real_hnorm2 : is_real (hmul h1 (hconj h1)).\nProof.\ndestruct h1 ; intros; unfold hmul, hconj.\nrepeat split;\n  cbv delta [Hurwitz_def.h Hurwitz_def.i Hurwitz_def.j Hurwitz_def.k];\n  cbv iota beta;\n  ring.\nQed.\n\nLemma Zmult_le_reg_l : forall m n p, 0 < p -> p * m <= p * n -> m <= n.\nProof.\nintros m n p p_pos ; do 2 rewrite (Zmult_comm p) ;\n apply Zmult_le_reg_r, Z.lt_gt ; assumption.\nQed.\n\nLemma hnorm2_pos : 0 <= hnorm2 h1.\nProof.\ndestruct h1 ; intros ; unfold hnorm2, hmul, hconj.\n cbv delta [Hurwitz_def.i] ; cbv beta iota.\n ring_simplify.\n apply Zmult_le_reg_l with 4 ; [lia |].\n transitivity ((h + 2 * i) ^ 2 + (h + 2 * j) ^ 2 + (h + 2 * k) ^ 2 + h ^ 2).\n do 4 rewrite Zpower_2 ; repeat apply Zplus_le_0_compat ; apply Z.ge_le, sqr_pos.\n apply eq_Zle ; ring.\nQed.\n\nLemma h_Zle_hnorm2 : (h h1) ^ 2 <= 4 * hnorm2 h1.\nProof.\ndestruct h1 ; intros ; unfold hnorm2, hmul, hconj.\n cbv delta [Hurwitz_def.h Hurwitz_def.i] ; cbv beta iota.\n apply Zle_0_minus_le ; ring_simplify.\n transitivity ((h + 2 * i) ^ 2 + (h + 2 * j) ^ 2 + (h + 2 * k) ^ 2).\n do 3 rewrite Zpower_2 ; repeat apply Zplus_le_0_compat ; apply Z.ge_le, sqr_pos.\n apply eq_Zle ; ring.\nQed.\n\nEnd basic_lemmas.\n\n(* units *)\n\nLemma H_unit_is_unit : forall x, H_unit x -> is_H_unit x.\nProof.\n  intros x Ux.\n  exists (hconj x).\n  destruct Ux as [[]|[]|[]|[]|[] [] [] []]; auto.\nQed.\n\nLemma is_H_unit_hnorm2_1 : forall x, is_H_unit x -> hnorm2 x = 1.\nProof.\nintros x (y, Ixy).\n assert (H : hnorm2 x  * hnorm2 y = 1).\n  etransitivity ; [symmetry ; eapply hnorm2_hmul |].\n  rewrite Ixy ; apply hnorm2_IZH.\n eapply Zmult_one ; [apply Z.le_ge, hnorm2_pos | eassumption].\nQed.\n\nLemma H_unit_dec : forall x, H_unit x + (H_unit x -> False).\nProof.\nintro h ; pose (np := Z_of_Z_unit Z_one) ; pose (nn := Z_of_Z_unit Z_mone).\n destruct (Hurwitz_dec h (mkHurwitz (2 * np) (- np) (- np) (- np))) as [e | Hnp_1].\n  left ; subst ; apply H_unit_1.\n destruct (Hurwitz_dec h (mkHurwitz (2 * nn) (- nn) (- nn) (- nn))) as [e | Hnn_1].\n  left ; subst ; apply H_unit_1.\n destruct (Hurwitz_dec h (mkHurwitz 0 np 0 0)) as [e | Hnp_i].\n  left ; subst ; apply H_unit_i.\n destruct (Hurwitz_dec h (mkHurwitz 0 nn 0 0)) as [e | Hnn_i].\n  left ; subst ; apply H_unit_i.\n destruct (Hurwitz_dec h (mkHurwitz 0 0 np 0)) as [e | Hnp_j].\n  left ; subst ; apply H_unit_j.\n destruct (Hurwitz_dec h (mkHurwitz 0 0 nn 0)) as [e | Hnn_j].\n  left ; subst ; apply H_unit_j.\n destruct (Hurwitz_dec h (mkHurwitz 0 0 0 np)) as [e | Hnp_k].\n  left ; subst ; apply H_unit_k.\n destruct (Hurwitz_dec h (mkHurwitz 0 0 0 nn)) as [e | Hnn_k].\n  left ; subst ; apply H_unit_k.\n pose (hpp := halfsub Z_one Z_one) ; pose (hpn := halfsub Z_one Z_mone) ;\n pose (hnp := halfsub Z_mone Z_one) ; pose (hnn := halfsub Z_mone Z_mone).\n destruct (Hurwitz_dec h (mkHurwitz np hpp hpp hpp)) as [e | Hh_0].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz np hpp hpp hnp)) as [e | Hh_1].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz np hpp hnp hpp)) as [e | Hh_2].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz np hpp hnp hnp)) as [e | Hh_3].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz np hnp hpp hpp)) as [e | Hh_4].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz np hnp hpp hnp)) as [e | Hh_5].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz np hnp hnp hpp)) as [e | Hh_6].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz np hnp hnp hnp)) as [e | Hh_7].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz nn hpn hpn hpn)) as [e | Hh_8].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz nn hpn hpn hnn)) as [e | Hh_9].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz nn hpn hnn hpn)) as [e | Hh_A].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz nn hpn hnn hnn)) as [e | Hh_B].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz nn hnn hpn hpn)) as [e | Hh_C].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz nn hnn hpn hnn)) as [e | Hh_D].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz nn hnn hnn hpn)) as [e | Hh_E].\n  left ; subst ; apply H_unit_h.\n destruct (Hurwitz_dec h (mkHurwitz nn hnn hnn hnn)) as [e | Hh_F].\n  left ; subst ; apply H_unit_h.\n right ; intros Hf ; inversion Hf.\n  destruct u ; [apply Hnp_1 | apply Hnn_1] ; auto.\n  destruct u ; [apply Hnp_i | apply Hnn_i] ; auto.\n  destruct u ; [apply Hnp_j | apply Hnn_j] ; auto.\n  destruct u ; [apply Hnp_k | apply Hnn_k] ; auto.\n  destruct u ; destruct v ; destruct w ; destruct z ;\n  [ apply Hh_0 | apply Hh_1 | apply Hh_2 | apply Hh_3 | apply Hh_4 |\n    apply Hh_5 | apply Hh_6 | apply Hh_7 | apply Hh_8 | apply Hh_9 |\n    apply Hh_A | apply Hh_B | apply Hh_C | apply Hh_D | apply Hh_E |\n    apply Hh_F ] ; auto.\nQed.\n  \n\nLemma H_unit_characterization : forall x, is_H_unit x -> H_unit x.\nProof.\nintros x Hx ; assert (Nx := is_H_unit_hnorm2_1 _ Hx) ; destruct Hx as [y Ixy].\n assert (Ny : hnorm2 y = 1).\n  apply Zmult_reg_l with 1 ; [lia |] ; rewrite <- Zpower_2,\n   <- hnorm2_IZH, <- Ixy, <- Nx ; symmetry ; apply hnorm2_hmul.\n\n  (* Une fois qu'on a ça, c'est pas si facile. Chez les quaternions\n  on peut borner |a+bi+cj+dk|>=|a|+|b|+|c|+|d| mais comme le changement\n  est dans une base pas trop orthonormée, c'est moins facile, mais c'est\n  possible quand même. *)\n  (*intros [[|p|p] [|q|q] [|r|r] [|s|s]] (y, Uxy).*)\n  \n  (* idée : on peut énumérer les x, y de norme bornée (par 1), et après\n  on peut vérifier que si xy=1 c'est que H_unit x. Peut-être avoir la \n  décidabilité de H_unit aidera. *)\nAbort.\n\n", "meta": {"author": "coq-community", "repo": "coqtail-math", "sha": "be26e1a6a52f2e13e0779c68aba685ddfb4f0535", "save_path": "github-repos/coq/coq-community-coqtail-math", "path": "github-repos/coq/coq-community-coqtail-math/coqtail-math-be26e1a6a52f2e13e0779c68aba685ddfb4f0535/Arith/Hurwitz_prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7107137084274072}}
{"text": "(* Exercise 68 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\n\nTheorem exercise_068 : ~ (exists x : D, P x) -> forall x : D, ~ P x.\nProof.\nimp_i a1.\nall_i a.\nneg_e' (exists x:D, P x) a2.\nhyp a1.\nexi_i a.\nneg_e' (~P a) a3.\nhyp a2.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak11/Taak11_pred068.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896845856298, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7107055357572196}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) (lf2 : natural)\n  : natural := Succ (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj187_coqofml_2fCad3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.7107055162265089}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\nRequire Export ZArith.\nRequire Export ZCmisc.\n\nOpen Local Scope positive_scope.\n\nOpen Local Scope P_scope.\n\n(* [div_eucl a b] return [(q,r)] such that a = q*b + r *)\nFixpoint div_eucl (a b : positive) {struct a} : N * N :=\n  match a with\n  | xH => if 1 ?< b then (0%N, 1%N) else (1%N, 0%N)\n  | xO a' =>\n    let (q, r) := div_eucl a' b in\n    match q, r with\n    | N0, N0 => (0%N, 0%N) (* n'arrive jamais *)\n    | N0, Npos r =>\n      if (xO r) ?< b then (0%N, Npos (xO r))\n      else (1%N,PminusN (xO r) b)\n    | Npos q, N0 => (Npos (xO q), 0%N)\n    | Npos q, Npos r =>\n      if (xO r) ?< b then (Npos (xO q), Npos (xO r))\n      else (Npos (xI q),PminusN (xO r) b)\n    end\n  | xI a' =>\n    let (q, r) := div_eucl a' b in\n    match q, r with\n    | N0, N0 => (0%N, 0%N)                 (* Impossible *)\n    | N0, Npos r =>  \n      if (xI r) ?< b then (0%N, Npos (xI r))\n      else (1%N,PminusN (xI r) b)\n    | Npos q, N0 => if 1 ?< b then (Npos (xO q), 1%N) else (Npos (xI q), 0%N)\n    | Npos q, Npos r => \n      if (xI r) ?< b then (Npos (xO q), Npos (xI r))\n      else (Npos (xI q),PminusN (xI r) b)\n    end\n  end.\nInfix \"/\" := div_eucl : P_scope.\n\nOpen Scope Z_scope.\nOpaque Zmult.\nLemma div_eucl_spec : forall a b, \n          Zpos a = fst (a/b)%P * b + snd (a/b)%P\n       /\\ snd (a/b)%P < b.\nProof with zsimpl;try apply Zlt_0_pos;try ((ring;fail) || omega). \n intros a b;generalize a;clear a;induction a;simpl;zsimpl.\n case IHa; destruct (a/b)%P as [q r].\n   case q; case r; simpl fst; simpl snd.\n     rewrite Zmult_0_l; rewrite Zplus_0_r; intros HH; discriminate HH.\n  intros p H; rewrite H;\n  match goal with \n  | [|- context [ ?xx ?< b ]] => \n    generalize (is_lt_spec xx b);destruct (xx ?< b)\n  | _ => idtac\n  end; zsimpl; simpl; intros H1 H2; split; zsimpl; auto.\n  rewrite PminusN_le...\n  generalize H1; zsimpl; auto.\n  rewrite PminusN_le...\n  generalize H1; zsimpl; auto.\n  intros p H; rewrite H;\n  match goal with \n  | [|- context [ ?xx ?< b ]] => \n    generalize (is_lt_spec xx b);destruct (xx ?< b)\n  | _ => idtac\n  end; zsimpl; simpl; intros H1 H2; split; zsimpl; auto; try ring.\n  ring_simplify.\n  case (Zle_lt_or_eq _ _ H1); auto with zarith.\n  intros p p1 H; rewrite H.\n  match goal with \n  | [|- context [ ?xx ?< b ]] => \n    generalize (is_lt_spec xx b);destruct (xx ?< b)\n  | _ => idtac\n  end; zsimpl; simpl; intros H1 H2; split; zsimpl; auto; try ring.\n  rewrite PminusN_le...\n  generalize H1; zsimpl; auto.\n  rewrite PminusN_le...\n  generalize H1; zsimpl; auto.\n case IHa; destruct (a/b)%P as [q r].\n   case q; case r; simpl fst; simpl snd.\n     rewrite Zmult_0_l; rewrite Zplus_0_r; intros HH; discriminate HH.\n  intros p H; rewrite H;\n  match goal with \n  | [|- context [ ?xx ?< b ]] => \n    generalize (is_lt_spec xx b);destruct (xx ?< b)\n  | _ => idtac\n  end; zsimpl; simpl; intros H1 H2; split; zsimpl; auto.\n  rewrite PminusN_le...\n  generalize H1; zsimpl; auto.\n  rewrite PminusN_le...\n  generalize H1; zsimpl; auto.\n  intros p H; rewrite H; simpl; intros H1; split; auto.\n  zsimpl; ring.\n  intros p p1 H; rewrite H.\n  match goal with \n  | [|- context [ ?xx ?< b ]] => \n    generalize (is_lt_spec xx b);destruct (xx ?< b)\n  | _ => idtac\n  end; zsimpl; simpl; intros H1 H2; split; zsimpl; auto; try ring.\n  rewrite PminusN_le...\n  generalize H1; zsimpl; auto.\n  rewrite PminusN_le...\n  generalize H1; zsimpl; auto.\n  match goal with \n  | [|- context [ ?xx ?< b ]] => \n    generalize (is_lt_spec xx b);destruct (xx ?< b)\n  | _ => idtac\n  end; zsimpl; simpl.\n  split; auto.\n  case (Zle_lt_or_eq 1 b); auto with zarith.\n  generalize (Zlt_0_pos b); auto with zarith.\nQed.\nTransparent Zmult.\n\n(******** Definition du modulo ************)\n\n(* [mod a b] return [a] modulo [b] *)\nFixpoint Pmod (a b : positive) {struct a} : N :=\n  match a with\n  | xH => if 1 ?< b then 1%N else 0%N\n  | xO a' =>\n    let r := Pmod a' b in\n    match r with\n    | N0 => 0%N\n    | Npos r' =>\n      if (xO r') ?< b then Npos (xO r')\n      else PminusN (xO r') b \n    end\n  | xI a' =>\n    let r := Pmod a' b in\n    match r with\n    | N0 => if 1 ?< b then 1%N else 0%N\n    | Npos r' => \n      if (xI r') ?< b then Npos (xI r')\n      else PminusN (xI r') b \n    end\n  end.\n\nInfix \"mod\" := Pmod (at level 40, no associativity) : P_scope.\nOpen Local Scope P_scope.\n\nLemma Pmod_div_eucl : forall a b, a mod b = snd (a/b).\nProof with auto.\n intros a b;generalize a;clear a;induction a;simpl;\n try (rewrite IHa;\n  assert (H1 := div_eucl_spec a b); destruct (a/b) as [q r];\n  destruct q as [|q];destruct r as [|r];simpl in *;\n  match goal with \n   | [|- context [ ?xx ?< b ]] => \n      assert (H2 := is_lt_spec xx b);destruct (xx ?< b)\n  | _ => idtac\n  end;simpl) ...\n destruct H1 as [H3 H4];discriminate H3.\n destruct (1 ?< b);simpl ...\nQed.\n\nLemma mod1: forall a, a mod 1 = 0%N.\nProof. induction a;simpl;try rewrite IHa;trivial. Qed.\n\nLemma mod_a_a_0 : forall a, a mod a = N0.\nProof.\n intros a;generalize (div_eucl_spec a a);rewrite <- Pmod_div_eucl.\n destruct (fst (a / a));unfold Z_of_N at 1.\n rewrite Zmult_0_l;intros (H1,H2);elimtype False;omega.\n assert (a<=p*a).\n  pattern (Zpos a) at 1;rewrite <- (Zmult_1_l a).\n  assert (H1:= Zlt_0_pos p);assert (H2:= Zle_0_pos a);\n   apply Zmult_le_compat;trivial;try omega.\n destruct (a mod a)%P;auto with zarith.\n unfold Z_of_N;assert (H1:= Zlt_0_pos p0);intros (H2,H3);elimtype False;omega.\nQed.\n  \nLemma mod_le_2r : forall (a b r: positive) (q:N),\n                    Zpos a = b*q + r -> b <= a -> r < b -> 2*r <= a.\nProof.\n intros a b r q H0 H1 H2.\n assert (H3:=Zlt_0_pos a). assert (H4:=Zlt_0_pos b). assert (H5:=Zlt_0_pos r). \n destruct q as [|q].  rewrite Zmult_0_r in H0. elimtype False;omega. \n assert (H6:=Zlt_0_pos q).  unfold Z_of_N in H0. \n assert (Zpos r = a - b*q). omega.\n simpl;zsimpl. pattern r at 2;rewrite H.\n assert (b <= b * q). \n  pattern (Zpos b) at 1;rewrite <- (Zmult_1_r b).\n  apply Zmult_le_compat;try omega.\n apply Zle_trans with (a - b * q + b). omega.\n apply Zle_trans with (a - b + b);omega.\nQed.\n\nLemma mod_lt : forall a b r, a mod b = Npos r -> r < b.\nProof.\n intros a b r H;generalize (div_eucl_spec a b);rewrite <- Pmod_div_eucl;\n  rewrite H;simpl;intros (H1,H2);omega.\nQed.\n \nLemma mod_le : forall a b r, a mod b = Npos r -> r <= b.\nProof. intros a b r H;assert (H1:= mod_lt _ _ _ H);omega. Qed.\n\nLemma mod_le_a : forall a b r, a mod b = r -> r <= a.\nProof.\n intros a b r H;generalize (div_eucl_spec a b);rewrite <- Pmod_div_eucl;\n  rewrite H;simpl;intros (H1,H2).\n assert (0 <= fst (a / b) * b). \n  destruct (fst (a / b));simpl;auto with zarith.\n auto with zarith.\nQed.\n\nLemma lt_mod : forall a b, Zpos a < Zpos b -> (a mod b)%P = Npos a.\nProof.\n  intros a b H; rewrite Pmod_div_eucl. case (div_eucl_spec a b).\n  assert (0 <= snd(a/b)). destruct (snd(a/b));simpl;auto with zarith.\n  destruct (fst (a/b)).\n  unfold Z_of_N at 1;rewrite Zmult_0_l;rewrite Zplus_0_l.\n  destruct (snd (a/b));simpl; intros H1 H2;inversion H1;trivial.\n  unfold Z_of_N at 1;assert (b <= p*b).\n  pattern (Zpos b) at 1; rewrite <- (Zmult_1_l (Zpos b)).\n   assert (H1 := Zlt_0_pos p);apply Zmult_le_compat;try omega.\n  apply Zle_0_pos.\n  intros;elimtype False;omega.\nQed.\n\nFixpoint gcd_log2 (a b c:positive) {struct c}: option positive :=\n match a mod b with\n | N0  => Some b\n | Npos r =>\n   match b mod r, c with\n   | N0, _ => Some r\n   | Npos r', xH    => None\n   | Npos r', xO c' => gcd_log2 r r' c'\n   | Npos r', xI c' => gcd_log2 r r' c'\n   end\n end.\n\nFixpoint egcd_log2 (a b c:positive) {struct c}: \n    option (Z * Z * positive) :=\n match a/b with\n |    (_, N0)  => Some (0, 1, b)\n | (q, Npos r) =>\n   match b/r, c with\n   | (_, N0), _ => Some (1, -q, r)\n   | (q', Npos r'), xH    => None\n   | (q', Npos r'), xO c' => \n        match egcd_log2 r r' c' with\n          None => None\n        | Some (u', v', w') =>\n               let u := u' - v' * q' in\n               Some (u, v' - q * u, w')\n        end\n   | (q', Npos r'), xI c' => \n        match egcd_log2 r r' c' with\n          None => None\n        | Some (u', v', w') =>\n               let u := u' - v' * q' in\n               Some (u, v' - q * u, w')\n        end\n   end\n end.\n\nLemma egcd_gcd_log2: forall c a b, \n  match egcd_log2 a b c, gcd_log2 a b c with\n    None, None => True\n  | Some (u,v,r), Some r' => r = r'\n  | _, _ => False\n  end.\ninduction c; simpl; auto; try \n (intros a b; generalize (Pmod_div_eucl a b); case (a/b); simpl;\n  intros q r1 H; subst; case (a mod b); auto;\n  intros r; generalize (Pmod_div_eucl b r); case (b/r); simpl;\n  intros q' r1 H; subst; case (b mod r); auto;\n  intros r'; generalize (IHc r r'); case egcd_log2; auto;\n  intros ((p1,p2),p3); case gcd_log2; auto).\nQed.\n\nLtac rw l := \n  match l with\n   | (?r, ?r1) =>\n       match type of r with\n         True => rewrite <- r1\n      |  _ => rw r; rw r1\n      end \n  | ?r => rewrite r\n  end. \n\nLemma egcd_log2_ok: forall c a b, \n  match egcd_log2 a b c with\n    None => True\n  | Some (u,v,r) => u * a + v * b = r\n  end.\ninduction c; simpl; auto;\n intros a b; generalize (div_eucl_spec a b); case (a/b); \n  simpl fst; simpl snd; intros q r1; case r1; try (intros; ring);\n  simpl; intros r (Hr1, Hr2); clear r1;\n  generalize (div_eucl_spec b r); case (b/r); \n  simpl fst; simpl snd; intros q' r1; case r1; \n    try (intros; rewrite Hr1; ring);\n  simpl; intros r' (Hr'1, Hr'2); clear r1; auto;\n  generalize (IHc r r'); case egcd_log2; auto;\n  intros ((u',v'),w'); case gcd_log2; auto; intros;\n  rw ((I, H), Hr1, Hr'1); ring.\nQed.\n\n\nFixpoint log2 (a:positive) : positive := \n match a with \n | xH => xH\n | xO a => Psucc (log2 a) \n | xI a => Psucc (log2 a) \n end.\n\nLemma gcd_log2_1: forall a c, gcd_log2  a xH c = Some xH.\nProof. destruct c;simpl;try rewrite mod1;trivial. Qed.\n\nLemma log2_Zle :forall a b, Zpos a <= Zpos b -> log2 a <= log2 b.\nProof with zsimpl;try omega.\n induction a;destruct b;zsimpl;intros;simpl ...\n assert (log2 a <= log2 b) ...  apply IHa ...\n assert (log2 a <= log2 b) ...  apply IHa ...\n assert (H1 := Zlt_0_pos a);elimtype False;omega.\n assert (log2 a <= log2 b) ...  apply IHa ...\n assert (log2 a <= log2 b) ...  apply IHa ...\n assert (H1 := Zlt_0_pos a);elimtype False;omega.\n assert (H1 := Zlt_0_pos (log2 b)) ...\n assert (H1 := Zlt_0_pos (log2 b)) ...\nQed.\n\nLemma log2_1_inv : forall a, Zpos (log2 a) = 1 -> a = xH.\nProof.\n destruct a;simpl;zsimpl;intros;trivial.\n assert (H1:= Zlt_0_pos (log2 a));elimtype False;omega.\n assert (H1:= Zlt_0_pos (log2 a));elimtype False;omega.\nQed.\n\nLemma mod_log2 : \n  forall a b r:positive, a mod b = Npos r -> b <= a -> log2 r + 1 <= log2 a.\nProof.\n intros; cut (log2 (xO r) <= log2 a). simpl;zsimpl;trivial.\n apply log2_Zle.\n replace (Zpos (xO r)) with (2 * r)%Z;trivial. \n generalize (div_eucl_spec a b);rewrite <- Pmod_div_eucl;rewrite H.\n rewrite Zmult_comm;intros [H1 H2];apply mod_le_2r with b (fst (a/b));trivial.\nQed.\n\nLemma gcd_log2_None_aux :\n  forall c a b, Zpos b <= Zpos a -> log2 b <= log2 c -> \n   gcd_log2 a b c <> None.\nProof.\n induction c;simpl;intros;\n (CaseEq (a mod b);[intros Heq|intros r Heq];try (intro;discriminate));\n (CaseEq (b mod r);[intros Heq'|intros r' Heq'];try (intro;discriminate)).\n apply IHc. apply mod_le with b;trivial.\n generalize H0 (mod_log2 _ _ _ Heq' (mod_le _ _ _ Heq));zsimpl;intros;omega.\n apply IHc. apply mod_le with b;trivial.\n generalize H0 (mod_log2 _ _ _ Heq' (mod_le _ _ _ Heq));zsimpl;intros;omega.\n assert (Zpos (log2 b) = 1).\n  assert (H1 := Zlt_0_pos (log2 b));omega.\n rewrite (log2_1_inv _ H1) in Heq;rewrite mod1 in Heq;discriminate Heq.\nQed.\n                    \nLemma gcd_log2_None : forall a b, Zpos b <= Zpos a -> gcd_log2 a b b <> None.\nProof. intros;apply gcd_log2_None_aux;auto with zarith. Qed.\n \nLemma gcd_log2_Zle :\n   forall c1 c2 a b, log2 c1 <= log2 c2 -> \n      gcd_log2 a b c1 <> None -> gcd_log2 a b c2 = gcd_log2 a b c1.\nProof with zsimpl;trivial;try omega.\n induction c1;destruct c2;simpl;intros;\n   (destruct (a mod b) as [|r];[idtac | destruct (b mod r)]) ...\n apply IHc1;trivial. generalize H;zsimpl;intros;omega.\n apply IHc1;trivial. generalize H;zsimpl;intros;omega.\n elim H;destruct (log2 c1);trivial.\n apply IHc1;trivial. generalize H;zsimpl;intros;omega.\n apply IHc1;trivial. generalize H;zsimpl;intros;omega.\n elim H;destruct (log2 c1);trivial.\n elim H0;trivial. elim H0;trivial.\nQed.\n\nLemma gcd_log2_Zle_log :\n   forall a b c, log2 b <= log2 c -> Zpos b <= Zpos a ->\n      gcd_log2 a b c = gcd_log2 a b b.\nProof.\n intros a b c H1 H2; apply gcd_log2_Zle; trivial.\n apply gcd_log2_None; trivial.\nQed.\n \nLemma gcd_log2_mod0 : \n  forall a b c, a mod b = N0 -> gcd_log2 a b c = Some b.\nProof. intros a b c H;destruct c;simpl;rewrite H;trivial. Qed.\n\n\nRequire Import Zwf.\n\nLemma Zwf_pos : well_founded (fun x y => Zpos x < Zpos y).\nProof.\n unfold well_founded.\n assert (forall x a ,x = Zpos a -> Acc (fun x y : positive => x < y) a).\n intros x;assert (Hacc := Zwf_well_founded 0 x);induction Hacc;intros;subst x.\n constructor;intros. apply H0 with (Zpos y);trivial.\n split;auto with zarith.\n intros a;apply H with (Zpos a);trivial.\nQed.\n\nOpaque Pmod.\nLemma gcd_log2_mod : forall a b, Zpos b <= Zpos a -> \n  forall r, a mod b = Npos r -> gcd_log2 a b b = gcd_log2 b r r.\nProof.\n intros a b;generalize a;clear a; assert (Hacc := Zwf_pos b).\n induction Hacc; intros a Hle r Hmod.\n rename x into b. destruct b;simpl;rewrite Hmod.\n CaseEq (xI b mod r)%P;intros. rewrite gcd_log2_mod0;trivial.\n assert (H2 := mod_le _ _ _ H1);assert (H3 := mod_lt _ _ _ Hmod);\n  assert (H4 := mod_le _ _ _ Hmod).\n rewrite (gcd_log2_Zle_log r p b);trivial.\n symmetry;apply H0;trivial.\n generalize (mod_log2 _ _ _ H1 H4);simpl;zsimpl;intros;omega.\n CaseEq (xO b mod r)%P;intros. rewrite gcd_log2_mod0;trivial.\n assert (H2 := mod_le _ _ _ H1);assert (H3 := mod_lt _ _ _ Hmod);\n  assert (H4 := mod_le _ _ _ Hmod).\n rewrite (gcd_log2_Zle_log r p b);trivial.\n symmetry;apply H0;trivial.\n generalize (mod_log2 _ _ _ H1 H4);simpl;zsimpl;intros;omega.\n rewrite mod1 in Hmod;discriminate Hmod.\nQed.\n\nLemma gcd_log2_xO_Zle : \n forall a b, Zpos b <= Zpos a -> gcd_log2 a b (xO b) = gcd_log2 a b b.\nProof.\n intros a b Hle;apply gcd_log2_Zle.\n simpl;zsimpl;auto with zarith.\n apply gcd_log2_None_aux;auto with zarith.\nQed.\n\nLemma gcd_log2_xO_Zlt : \n forall a b, Zpos a < Zpos b -> gcd_log2 a b (xO b) = gcd_log2 b a a.\nProof.\n intros a b H;simpl. assert (Hlt := Zlt_0_pos a).\n assert (H0 := lt_mod _ _ H).\n rewrite H0;simpl.\n CaseEq (b mod a)%P;intros;simpl.\n symmetry;apply gcd_log2_mod0;trivial.\n assert (H2 := mod_lt _ _ _ H1).\n rewrite (gcd_log2_Zle_log a p b);auto with zarith.\n symmetry;apply gcd_log2_mod;auto with zarith.\n apply log2_Zle. \n replace (Zpos p) with (Z_of_N (Npos p));trivial.\n apply mod_le_a with a;trivial.\nQed.\n\nLemma gcd_log2_x0 : forall a b, gcd_log2 a b (xO b) <> None.\nProof.\n intros;simpl;CaseEq (a mod b)%P;intros. intro;discriminate.\n CaseEq (b mod p)%P;intros. intro;discriminate.\n assert (H1 := mod_le_a _ _ _ H0). unfold Z_of_N in H1.\n assert (H2 := mod_le _ _ _ H0).\n apply gcd_log2_None_aux. trivial.\n apply log2_Zle. trivial.\nQed.\n\nLemma egcd_log2_x0 : forall a b, egcd_log2 a b (xO b) <> None.\nProof.\nintros a b H; generalize (egcd_gcd_log2 (xO b) a b) (gcd_log2_x0 a b);\n  rw H; case gcd_log2; auto.\nQed.\n\nDefinition gcd a b :=\n  match gcd_log2 a b (xO b) with\n  | Some p => p \n  | None => (* can not appear *) 1%positive\n  end.\n\nDefinition egcd a b :=\n  match egcd_log2 a b (xO b) with\n  | Some p => p \n  | None => (* can not appear *) (1,1,1%positive)\n  end.\n\n\nLemma gcd_mod0 : forall a b, (a mod b)%P = N0 -> gcd a b = b.\nProof.\n intros a b H;unfold gcd.\n pattern (gcd_log2 a b (xO b)) at 1;\n  rewrite (gcd_log2_mod0 _ _ (xO b) H);trivial.\nQed.\n\nLemma gcd1 : forall a, gcd a xH = xH.\nProof. intros a;rewrite gcd_mod0;[trivial|apply mod1]. Qed.\n\nLemma gcd_mod : forall a b r, (a mod b)%P = Npos r ->\n                     gcd a b = gcd b r.\nProof.\n intros a b r H;unfold gcd.\n assert (log2 r <= log2 (xO r)). simpl;zsimpl;omega.\n assert (H1 := mod_lt _ _ _ H).\n pattern (gcd_log2 b r (xO r)) at 1; rewrite gcd_log2_Zle_log;auto with zarith.\n destruct (Z_lt_le_dec a b) as [z|z].\n pattern (gcd_log2 a b (xO b)) at 1; rewrite gcd_log2_xO_Zlt;trivial.\n rewrite (lt_mod _ _ z) in H;inversion H.\n assert  (r <= b). omega. \n generalize (gcd_log2_None _ _ H2).\n destruct (gcd_log2 b r r);intros;trivial. \n assert (log2 b <= log2 (xO b)). simpl;zsimpl;omega.\n pattern (gcd_log2 a b (xO b)) at 1; rewrite gcd_log2_Zle_log;auto with zarith.\n pattern (gcd_log2 a b b) at 1;rewrite (gcd_log2_mod _ _ z _ H).\n assert  (r <= b). omega. \n generalize (gcd_log2_None _ _ H3).\n destruct (gcd_log2 b r r);intros;trivial. \nQed.\n\nRequire Import ZArith.\nRequire Import Znumtheory.\n\nHint Rewrite  Zpos_mult times_Zmult square_Zmult Psucc_Zplus: zmisc.\n\nLtac mauto := \n  trivial;autorewrite with zmisc;trivial;auto with zarith.\n\nLemma gcd_Zis_gcd : forall a b:positive, (Zis_gcd b a (gcd b a)%P).\nProof with mauto.\n intros a;assert (Hacc := Zwf_pos a);induction Hacc;rename x into a;intros.\n generalize (div_eucl_spec b a)...\n rewrite <- (Pmod_div_eucl b a).\n CaseEq (b mod a)%P;[intros Heq|intros r Heq]; intros (H1,H2).\n simpl in H1;rewrite Zplus_0_r in H1.\n rewrite (gcd_mod0 _ _ Heq).\n constructor;mauto.\n apply Zdivide_intro with (fst (b/a)%P);trivial.\n rewrite (gcd_mod _ _ _ Heq).\n rewrite H1;apply Zis_gcd_sym.\n rewrite Zmult_comm;apply Zis_gcd_for_euclid2;simpl in *.\n apply Zis_gcd_sym;auto.\nQed.\n\nLemma egcd_Zis_gcd : forall a b:positive, \n   let (uv,w) := egcd a b in \n   let  (u,v) := uv in \n     u * a + v * b = w /\\ (Zis_gcd b a w).\nProof with mauto.\n intros a b; unfold egcd.\n generalize (egcd_log2_ok (xO b) a b) (egcd_gcd_log2 (xO b) a b) \n            (egcd_log2_x0 a b) (gcd_Zis_gcd b a); unfold egcd, gcd.\n case egcd_log2; try (intros ((u,v),w)); case gcd_log2;\n try (intros; match goal with H: False |- _ => case H end);\n try (intros _ _ H1; case H1; auto; fail).\n intros; subst; split; try apply Zis_gcd_sym; auto.\nQed.\n\nDefinition Zgcd a b := \n  match a, b with\n  | Z0, _ => b\n  | _, Z0 => a\n  | Zpos a, Zneg b => Zpos (gcd a b)\n  | Zneg a, Zpos b => Zpos (gcd a b)\n  | Zpos a, Zpos b => Zpos (gcd a b)\n  | Zneg a, Zneg b => Zpos (gcd a b)\n  end.\n\n\nLemma Zgcd_is_gcd : forall x y, Zis_gcd x y (Zgcd x y).\nProof.\n destruct x;destruct y;simpl.\n apply Zis_gcd_0.\n apply Zis_gcd_sym;apply Zis_gcd_0. \n apply Zis_gcd_sym;apply Zis_gcd_0. \n apply Zis_gcd_0.\n apply gcd_Zis_gcd.\n apply Zis_gcd_sym;apply Zis_gcd_minus;simpl;apply gcd_Zis_gcd.\n apply Zis_gcd_0.\n apply Zis_gcd_minus;simpl;apply Zis_gcd_sym;apply gcd_Zis_gcd.\n apply Zis_gcd_minus;apply Zis_gcd_minus;simpl;apply gcd_Zis_gcd.\nQed.\n\nDefinition Zegcd a b := \n  match a, b with\n  | Z0, Z0 => (0,0,0)\n  | Zpos _, Z0 => (1,0,a)\n  | Zneg _, Z0 => (-1,0,-a)\n  | Z0, Zpos _ => (0,1,b)\n  | Z0, Zneg _ => (0,-1,-b)\n  | Zpos a, Zneg b => \n     match egcd a b with (u,v,w) => (u,-v, Zpos w) end\n  | Zneg a, Zpos b =>\n     match egcd a b with (u,v,w) => (-u,v, Zpos w) end\n  | Zpos a, Zpos b => \n     match egcd a b with (u,v,w) => (u,v, Zpos w) end\n  | Zneg a, Zneg b => \n     match egcd a b with (u,v,w) => (-u,-v, Zpos w) end\n  end.\n\nLemma Zegcd_is_egcd : forall x y, \n  match Zegcd x y with\n   (u,v,w) => u * x + v * y = w /\\ Zis_gcd x y w /\\ 0 <= w\n  end.\nProof.\n assert (zx0: forall x, Zneg x = -x).\n    simpl; auto.\n assert (zx1: forall x, -(-x) = x).\n   intro x; case x; simpl; auto.\n destruct x;destruct y;simpl; try (split; [idtac|split]);\n  auto; try (red; simpl; intros; discriminate);\n try (rewrite zx0; apply Zis_gcd_minus; try rewrite zx1; auto;\n       apply Zis_gcd_minus; try rewrite zx1; simpl; auto);\n try apply Zis_gcd_0; try (apply Zis_gcd_sym;apply Zis_gcd_0);\n generalize (egcd_Zis_gcd p p0); case egcd; intros (u,v) w (H1, H2); \n split; repeat rewrite zx0; try (rewrite <- H1; ring); auto;\n (split; [idtac | red; intros; discriminate]).\n apply Zis_gcd_sym; auto.\n apply Zis_gcd_sym; apply Zis_gcd_minus; rw zx1; \n    apply Zis_gcd_sym; auto.\n apply Zis_gcd_minus; rw zx1; auto.\n apply Zis_gcd_minus; rw zx1; auto.\n apply Zis_gcd_minus; rw zx1; auto.\n apply Zis_gcd_sym; auto.\nQed.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/coqprime/Coqprime/Pmod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7106941729317686}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Chapter 2: Basic Program Syntax\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)\n\nRequire Import Frap.\n(* This [Import] command is for including a library of code, theorems, tactics, etc.\n * Here we just include the standard library of the book.\n * We won't distinguish carefully between built-in Coq features and those provided by that library. *)\n\n(* As a first example, let's look at the syntax of simple arithmetic expressions.\n * We use the Coq feature of modules, which let us group related definitions together.\n * A key benefit is that names can be reused across modules,\n * which is helpful to define several variants of a suite of functionality,\n * within a single source file. *)\nModule ArithWithConstants.\n\n  (* The following definition closely mirrors a standard BNF grammar for expressions.\n   * It defines abstract syntax trees of arithmetic expressions. *)\n  Inductive arith : Set :=\n  | Const (n : nat)\n  | Plus (e1 e2 : arith)\n  | Times (e1 e2 : arith).\n\n  (* Here are a few examples of specific expressions. *)\n  Example ex1 := Const 42.\n  Example ex2 := Plus (Const 1) (Times (Const 2) (Const 3)).\n\n  (* How many nodes appear in the tree for an expression?\n   * Unlike in many programming languages, in Coq,\n   * recursive functions must be marked as recursive explicitly.\n   * That marking comes with the [Fixpoint] command, as opposed to [Definition].\n   * Note also that Coq checks termination of each recursive definition.\n   * Intuitively, recursive calls must be on subterms of the original argument. *)\n  Fixpoint size (e : arith) : nat :=\n    match e with\n    | Const _ => 1\n    | Plus e1 e2 => 1 + size e1 + size e2\n    | Times e1 e2 => 1 + size e1 + size e2\n    end.\n\n  (* Here's how to run a program (evaluate a term) in Coq. *)\n  Compute size ex1.\n  Compute size ex2.\n\n  (* What's the longest path from the root of a syntax tree to a leaf? *)\n  Fixpoint depth (e : arith) : nat :=\n    match e with\n    | Const _ => 1\n    | Plus e1 e2 => 1 + max (depth e1) (depth e2)\n    | Times e1 e2 => 1 + max (depth e1) (depth e2)\n    end.\n\n  Compute depth ex1.\n  Compute depth ex2.\n\n  (* Our first proof!\n   * Size is an upper bound on depth. *)\n  Theorem depth_le_size : forall e, depth e <= size e.\n  Proof.\n    (* Within a proof, we apply commands called *tactics*.\n     * Here's our first one.\n     * Throughout the book's Coq code, we give a brief note documenting each tactic,\n     * after its first use.\n     * Keep in mind that the best way to understand what's going on\n     * is to run the proof script for yourself, inspecting intermediate states! *)\n    induct e.\n    (* [induct x]: where [x] is a variable in the theorem statement,\n     *   structure the proof by induction on the structure of [x].\n     *   You will get one generated subgoal per constructor in the\n     *   inductive definition of [x].  (Indeed, it is required that \n     *   [x]'s type was introduced with [Inductive].) *)\n\n    simplify.\n    (* [simplify]: simplify throughout the goal, applying the definitions of\n     *   recursive functions directly.  That is, when a subterm\n     *   matches one of the [match] cases in a defining [Fixpoint],\n     *   replace with the body of that case, then repeat. *)\n    linear_arithmetic.\n    (* [linear_arithmetic]: a complete decision procedure for linear arithmetic.\n     *   Relevant formulas are essentially those built up from\n     *   variables and constant natural numbers and integers\n     *   using only addition, with equality and inequality\n     *   comparisons on top.  (Multiplication by constants\n     *   is supported, as a shorthand for repeated addition.) *)\n\n    simplify.\n    linear_arithmetic.\n\n    simplify.\n    linear_arithmetic.\n  Qed.\n\n  Theorem depth_le_size_snazzy : forall e, depth e <= size e.\n  Proof.\n    induct e; simplify; linear_arithmetic.\n    (* Oo, look at that!  Chaining tactics with semicolon, as in [t1; t2],\n     * asks to run [t1] on the goal, then run [t2] on *every*\n     * generated subgoal.  This is an essential ingredient for automation. *)\n  Qed.\n\n  (* A silly recursive function: swap the operand orders of all binary operators. *)\n  Fixpoint 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  Compute commuter ex1.\n  Compute commuter ex2.\n\n  (* [commuter] has all the appropriate interactions with other functions (and itself). *)\n\n  Theorem size_commuter : forall e, size (commuter e) = size e.\n  Proof.\n    induct e; simplify; linear_arithmetic.\n  Qed.\n\n  Theorem depth_commuter : forall e, depth (commuter e) = depth e.\n  Proof.\n    induct e; simplify; linear_arithmetic.\n  Qed.\n\n  Theorem commuter_inverse : forall e, commuter (commuter e) = e.\n  Proof.\n    induct e; simplify; equality.\n    (* [equality]: a complete decision procedure for the theory of equality\n     *   and uninterpreted functions.  That is, the goal must follow\n     *   from only reflexivity, symmetry, transitivity, and congruence\n     *   of equality, including that functions really do behave as functions. *)\n  Qed.\n\nEnd ArithWithConstants.\n\n(* Let's shake things up a bit by adding variables to expressions.\n * Note that all of the automated proof scripts from before will keep working\n * with no changes!  That sort of \"free\" proof evolution is invaluable for\n * theorems about real-world compilers, say. *)\nModule ArithWithVariables.\n\n  Inductive arith : Set :=\n  | Const (n : nat)\n  | Var (x : var) (* <-- this is the new constructor! *)\n  | Plus (e1 e2 : arith)\n  | Times (e1 e2 : arith).\n\n  Example ex1 := Const 42.\n  Example ex2 := Plus (Const 1) (Times (Var \"x\") (Const 3)).\n\n  Fixpoint size (e : arith) : nat :=\n    match e with\n    | Const _ => 1\n    | Var _ => 1\n    | Plus e1 e2 => 1 + size e1 + size e2\n    | Times e1 e2 => 1 + size e1 + size e2\n    end.\n\n  Compute size ex1.\n  Compute size ex2.\n\n  Fixpoint depth (e : arith) : nat :=\n    match e with\n    | Const _ => 1\n    | Var _ => 1\n    | Plus e1 e2 => 1 + max (depth e1) (depth e2)\n    | Times e1 e2 => 1 + max (depth e1) (depth e2)\n    end.\n\n  Compute depth ex1.\n  Compute depth ex2.\n\n  Theorem depth_le_size : forall e, depth e <= size e.\n  Proof.\n    induct e; simplify; linear_arithmetic.\n  Qed.\n\n  Fixpoint commuter (e : arith) : arith :=\n    match e with\n    | Const _ => e\n    | Var _ => e\n    | Plus e1 e2 => Plus (commuter e2) (commuter e1)\n    | Times e1 e2 => Times (commuter e2) (commuter e1)\n    end.\n\n  Compute commuter ex1.\n  Compute commuter ex2.\n\n  Theorem size_commuter : forall e, size (commuter e) = size e.\n  Proof.\n    induct e; simplify; linear_arithmetic.\n  Qed.\n\n  Theorem depth_commuter : forall e, depth (commuter e) = depth e.\n  Proof.\n    induct e; simplify; linear_arithmetic.\n  Qed.\n\n  Theorem commuter_inverse : forall e, commuter (commuter e) = e.\n  Proof.\n    induct e; simplify; equality.\n  Qed.\n\n  (* Now that we have variables, we can consider new operations,\n   * like substituting an expression for a variable.\n   * We use an infix operator [==v] for equality tests on strings.\n   * It has a somewhat funny and very expressive type,\n   * whose details we will try to gloss over.\n   * (We later return to them in SubsetTypes.v.) *)\n  Fixpoint substitute (inThis : arith) (replaceThis : var) (withThis : arith) : arith :=\n    match inThis with\n    | Const _ => inThis\n    | Var x => if x ==v replaceThis then withThis else inThis\n    | Plus e1 e2 => Plus (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n    | Times e1 e2 => Times (substitute e1 replaceThis withThis) (substitute e2 replaceThis withThis)\n    end.\n\n  (* An intuitive property about how much [substitute] might increase depth. *)\n  Theorem substitute_depth : forall replaceThis withThis inThis,\n    depth (substitute inThis replaceThis withThis) <= depth inThis + depth withThis.\n  Proof.\n    induct inThis.\n\n    simplify.\n    linear_arithmetic.\n\n    simplify.\n    cases (x ==v replaceThis).\n    (* [cases e]: break the proof into one case for each constructor that might have\n     *   been used to build the value of expression [e].  In the special case where\n     *   [e] essentially has a Boolean type, we consider whether [e] is true or false. *)\n    linear_arithmetic.\n    simplify.\n    linear_arithmetic.\n\n    simplify.\n    linear_arithmetic.\n\n    simplify.\n    linear_arithmetic.\n  Qed.\n\n  (* Let's get fancier about automation, using [match goal] to pattern-match the goal\n   * and decide what to do next!\n   * The [|-] syntax separates hypotheses and conclusion in a goal.\n   * The [context] syntax is for matching against *any subterm* of a term.\n   * The construct [try] is also useful, for attempting a tactic and rolling back\n   * the effect if any error is encountered. *)\n  Theorem substitute_depth_snazzy : forall replaceThis withThis inThis,\n    depth (substitute inThis replaceThis withThis) <= depth inThis + depth withThis.\n  Proof.\n    induct inThis; simplify;\n    try match goal with\n        | [ |- context[if ?a ==v ?b then _ else _] ] => cases (a ==v b); simplify\n        end; linear_arithmetic.\n  Qed.\n\n  (* A silly self-substitution has no effect. *)\n  Theorem substitute_self : forall replaceThis inThis,\n    substitute inThis replaceThis (Var replaceThis) = inThis.\n  Proof.\n    induct inThis; simplify;\n    try match goal with\n        | [ |- context[if ?a ==v ?b then _ else _] ] => cases (a ==v b); simplify\n        end; equality.\n  Qed.\n\n  (* We can do substitution and commuting in either order. *)\n  Theorem substitute_commuter : forall replaceThis withThis inThis,\n    commuter (substitute inThis replaceThis withThis)\n    = substitute (commuter inThis) replaceThis (commuter withThis).\n  Proof.\n    induct inThis; simplify;\n    try match goal with\n        | [ |- context[if ?a ==v ?b then _ else _] ] => cases (a ==v b); simplify\n        end; equality.\n  Qed.\n\n  (* *Constant folding* is one of the classic compiler optimizations.\n   * We repeatedly find opportunities to replace fancier expressions\n   * with known constant values. *)\n  Fixpoint constantFold (e : arith) : arith :=\n    match e with\n    | Const _ => e\n    | Var _ => 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  (* This is supposed to be an *optimization*, so it had better not *increase*\n   * the size of an expression!\n   * There are enough cases to consider here that we skip straight to\n   * the automation.\n   * A new scripting construct is [match] patterns with dummy bodies.\n   * Such a pattern matches *any* [match] in a goal, over any type! *)\n  Theorem size_constantFold : forall e, size (constantFold e) <= size e.\n  Proof.\n    induct e; simplify;\n    repeat match goal with\n           | [ |- context[match ?E with _ => _ end] ] => cases E; simplify\n           end; linear_arithmetic.\n  Qed.\n\n  (* Business as usual, with another commuting law *)\n  Theorem commuter_constantFold : forall e, commuter (constantFold e) = constantFold (commuter e).\n  Proof.\n    induct e; simplify;\n    repeat match goal with\n           | [ |- context[match ?E with _ => _ end] ] => cases E; simplify\n           | [ H : ?f _ = ?f _ |- _ ] => invert H\n           | [ |- ?f _ = ?f _ ] => f_equal\n           end; equality || linear_arithmetic || ring.\n    (* [f_equal]: when the goal is an equality between two applications of\n     *   the same function, switch to proving that the function arguments are\n     *   pairwise equal.\n     * [invert H]: replace hypothesis [H] with other facts that can be deduced\n     *   from the structure of [H]'s statement.  This is admittedly a fuzzy\n     *   description for now; we'll learn much more about the logic shortly!\n     *   Here, what matters is that, when the hypothesis is an equality between\n     *   two applications of a constructor of an inductive type, we learn that\n     *   the arguments to the constructor must be pairwise equal.\n     * [ring]: prove goals that are equalities over some registered ring or\n     *   semiring, in the sense of algebra, where the goal follows solely from\n     *   the axioms of that algebraic structure. *)\n  Qed.\n\n  (* To define a further transformation, we first write a roundabout way of\n   * testing whether an expression is a constant.\n   * This detour happens to be useful to avoid overhead in concert with\n   * pattern matching, since Coq internally elaborates wildcard [_] patterns\n   * into separate cases for all constructors not considered beforehand.\n   * That expansion can create serious code blow-ups, leading to serious\n   * proof blow-ups! *)\n  Definition isConst (e : arith) : option nat :=\n    match e with\n    | Const n => Some n\n    | _ => None\n    end.\n\n  (* Our next target is a function that finds multiplications by constants\n   * and pushes the multiplications to the leaves of syntax trees,\n   * ideally finding constants, which can be replaced by larger constants,\n   * not affecting the meanings of expressions.\n   * This helper function takes a coefficient [multiplyBy] that should be\n   * applied to an expression. *)\n  Fixpoint pushMultiplicationInside' (multiplyBy : nat) (e : arith) : arith :=\n    match e with\n    | Const n => Const (multiplyBy * n)\n    | Var _ => Times (Const multiplyBy) e\n    | Plus e1 e2 => Plus (pushMultiplicationInside' multiplyBy e1)\n                         (pushMultiplicationInside' multiplyBy e2)\n    | Times e1 e2 =>\n      match isConst e1 with\n      | Some k => pushMultiplicationInside' (k * multiplyBy) e2\n      | None => Times (pushMultiplicationInside' multiplyBy e1) e2\n      end\n    end.\n\n  (* The overall transformation just fixes the initial coefficient as [1]. *)\n  Definition pushMultiplicationInside (e : arith) : arith :=\n    pushMultiplicationInside' 1 e.\n\n  (* Let's prove this boring arithmetic property, so that we may use it below. *)\n  Lemma n_times_0 : forall n, n * 0 = 0.\n  Proof.\n    linear_arithmetic.\n  Qed.\n\n  (* A fun fact about pushing multiplication inside:\n   * the coefficient has no effect on depth!\n   * Let's start by showing any coefficient is equivalent to coefficient 0. *)\n  Lemma depth_pushMultiplicationInside'_irrelevance0 : forall e multiplyBy,\n    depth (pushMultiplicationInside' multiplyBy e)\n    = depth (pushMultiplicationInside' 0 e).\n  Proof.\n    induct e; simplify.\n\n    linear_arithmetic.\n\n    linear_arithmetic.\n\n    rewrite IHe1.\n    (* [rewrite H]: where [H] is a hypothesis or previously proved theorem,\n     *  establishing [forall x1 .. xN, e1 = e2], find a subterm of the goal\n     *  that equals [e1], given the right choices of [xi] values, and replace\n     *  that subterm with [e2]. *)\n    rewrite IHe2.\n    linear_arithmetic.\n\n    cases (isConst e1); simplify.\n\n    rewrite IHe2.\n    rewrite n_times_0.\n    linear_arithmetic.\n\n    rewrite IHe1.\n    linear_arithmetic.\n  Qed.\n\n  (* It can be remarkably hard to get Coq's automation to be dumb enough to\n   * help us demonstrate all of the primitive tactics. ;-)\n   * In particular, we can redo the proof in an automated way, without the\n   * explicit rewrites. *)\n  Lemma depth_pushMultiplicationInside'_irrelevance0_snazzy : forall e multiplyBy,\n    depth (pushMultiplicationInside' multiplyBy e)\n    = depth (pushMultiplicationInside' 0 e).\n  Proof.\n    induct e; simplify;\n    try match goal with\n        | [ |- context[match ?E with _ => _ end] ] => cases E; simplify\n        end; equality.\n  Qed.\n\n  (* Now the general corollary about irrelevance of coefficients for depth. *)\n  Lemma depth_pushMultiplicationInside'_irrelevance : forall e multiplyBy1 multiplyBy2,\n    depth (pushMultiplicationInside' multiplyBy1 e)\n    = depth (pushMultiplicationInside' multiplyBy2 e).\n  Proof.\n    simplify.\n    transitivity (depth (pushMultiplicationInside' 0 e)).\n    (* [transitivity X]: when proving [Y = Z], switch to proving [Y = X]\n     * and [X = Z]. *)\n    apply depth_pushMultiplicationInside'_irrelevance0.\n    (* [apply H]: for [H] a hypothesis or previously proved theorem,\n     *   establishing some fact that matches the structure of the current\n     *   conclusion, switch to proving [H]'s own hypotheses.\n     *   This is *backwards reasoning* via a known fact. *)\n    symmetry.\n    (* [symmetry]: when proving [X = Y], switch to proving [Y = X]. *)\n    apply depth_pushMultiplicationInside'_irrelevance0.\n  Qed.\n\n  (* Let's prove that pushing-inside has only a small effect on depth,\n   * considering for now only coefficient 0. *)\n  Lemma depth_pushMultiplicationInside' : forall e,\n    depth (pushMultiplicationInside' 0 e) <= S (depth e).\n  Proof.\n    induct e; simplify.\n\n    linear_arithmetic.\n\n    linear_arithmetic.\n\n    linear_arithmetic.\n\n    cases (isConst e1); simplify.\n\n    rewrite n_times_0.\n    linear_arithmetic.\n\n    linear_arithmetic.\n  Qed.\n\n  Local Hint Rewrite n_times_0.\n  (* Registering rewrite hints will get [simplify] to apply them for us\n   * automatically! *)\n\n  Lemma depth_pushMultiplicationInside'_snazzy : forall e,\n    depth (pushMultiplicationInside' 0 e) <= S (depth e).\n  Proof.\n    induct e; simplify;\n    try match goal with\n        | [ |- context[match ?E with _ => _ end] ] => cases E; simplify\n        end; linear_arithmetic.\n  Qed.\n\n  Theorem depth_pushMultiplicationInside : forall e,\n    depth (pushMultiplicationInside e) <= S (depth e).\n  Proof.\n    simplify.\n    unfold pushMultiplicationInside.\n    (* [unfold X]: replace [X] by its definition. *)\n    rewrite depth_pushMultiplicationInside'_irrelevance0.\n    apply depth_pushMultiplicationInside'.\n  Qed.\n\nEnd ArithWithVariables.\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/BasicSyntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.710694172233835}}
{"text": "(** * A correção do algoritmo de ordenação por inserção *)\n\n(** O objetivo deste arquivo é servir de apoio ao desenvolvimento do projeto deste semestre. Aqui apresentaremos todo o processo de formalização do algoritmo de ordenação por inserção, e este processo deve servir como modelo para o desenvolvimento do seu projeto. *)\n\n(* begin hide *)\nRequire Import Arith List.\n(* end hide *)\n\n(** Inicialmente apresentamos a definição do predicado [sorted] que é o mesmo apresentado no projeto, e por isto não nos preocuparemos em explicar aqui esta definição. *)\n\nInductive sorted :list nat -> Prop :=\n  | nil_sorted : sorted nil\n  | one_sorted: forall n:nat, sorted (n :: nil)\n  | all_sorted : forall (x y: nat) (l:list nat), sorted (y :: l) -> x <= y -> sorted (x :: y :: l).\n\n(** O algoritmo de ordenação por inserção é baseado em na função auxiliar [insert] que definimos a seguir. A função [insert] recebe um natural [x] e uma lista [l] como argumentos, e é definida recursivamente na estrutura de [l]: *)\n\nFixpoint insert (x:nat) (l: list nat) := match l with\n                      | nil => x :: nil\n                      | h :: tl => if x <=? h then (x :: l)\n                                                  else (h :: (insert x tl)) \n                      end.\n\n(** Como podemos observar, quando a lista [l] é a lista vazia, a função retorna a lista unitária contendo o elemento que foi inserido. Quando [l] não é a lista vazia, então ela tem a forma [h::tl], isto é, [l] tem [h] como primeiro elemento, e [tl] como cauda. Para saber onde inserir um elemento [x], comparamos [x] com [h], e quando [x] é menor ou igual a [h] simplesmente inserimos [x] na primeira posição da lista. Caso contrário, a função vai recursivamente encontrar a posição correta para inserir [x]. Assim, temos que a função [insert] é construída de forma a preservar a ordenação da lista recebida como segundo argumento. Este é exatamente o conteúdo do lema a seguir: *)\n\nLemma insert_preserves_sorting: forall l x, sorted l -> sorted (insert x l). \nProof.\n  induction l.\n  - intros x H.\n    simpl.\n    apply one_sorted.\n  - intros x H.\n    simpl.\n    destruct (x <=? a) eqn:Hleq.\n    + apply leb_complete in Hleq.\n      apply all_sorted; assumption.\n    + generalize dependent l.\n      intro l. case l.\n      * intros H1 H2.\n        simpl.\n        apply all_sorted.\n        ** apply one_sorted.\n        ** apply Nat.leb_gt in Hleq.\n           apply Nat.lt_le_incl; assumption.\n      * intros n l' H1 H2.\n        simpl.\n        destruct (x <=? n) eqn:Hleq'.\n        ** apply all_sorted.\n           *** apply all_sorted.\n               **** inversion H2; subst.\n                    assumption.\n               **** apply leb_complete in Hleq'.\n                    assumption.\n           *** apply Nat.leb_gt in Hleq.\n           apply Nat.lt_le_incl; assumption.\n        ** apply all_sorted.\n           *** inversion H2; subst.\n               apply (H1 x) in H3.\n               simpl in H3.\n               rewrite Hleq' in H3.\n               assumption.\n           *** inversion H2; subst.\n               assumption.\nQed.\n\n(** A seguir apresentaremos uma prova alternativa para o lema acima: *)\n\nDefinition le_all x l := forall y, In y l -> x <= y.\nInfix \"<=*\" := le_all (at level 70, no associativity).\n\nLemma le_all_nil: forall a, a <=* nil.\nProof.\n  intro a; unfold le_all.\n  intros y H.\n  inversion H.\nQed.\n\nLemma sublist_sorted: forall l a, sorted (a :: l) -> sorted l.\nProof.\n  intro l.\n  case l.\n  - intros a H.  \n    apply nil_sorted.  \n  - intros n l' a H.  \n    inversion H; subst.\n    assumption.  \nQed.  \n\nLemma le_all_sorted: forall l a, a <=* l -> sorted l -> sorted (a :: l).\nProof.\n(* Replace this line by your proof. *) Admitted.\n\nLemma sorted_le_all: forall l a, sorted(a :: l) -> a <=* l.\nProof.\n(* Replace this line by your proof. *) Admitted.\n\nLemma le_all_cons_part1: forall l a x, a <= x -> a <=* l -> a <=* x :: l.\nProof.\n  induction l.\n  - admit.\n  - Admitted.\n\nLemma le_all_cons_part2: forall l a x, a <=* x :: l -> a <= x /\\ a <=* l.\nProof.\n  induction l.\n  - admit.\n  - Admitted.\n\nLemma le_all_insert: forall l a x, a <= x -> a <=* l -> a <=* insert x l.\nProof.\n  induction l.\n  - intros a x Hleq Hle_all.\n    simpl.\n    apply le_all_cons_part1; assumption.\n  - intros a' x Hleq Hle_all.\n    simpl.\n    destruct (x <=? a) eqn: H.\n    + apply le_all_cons_part1; assumption.\n    + apply le_all_cons_part2  in Hle_all.\n      destruct Hle_all as [H1 H2].\n      apply le_all_cons_part1.\n      * assumption.\n      * apply IHl; assumption.\nQed.\n\nLemma insert_preserves_sorting': forall l x, sorted l -> sorted (insert x l). \nProof.\n  induction l.\n  - intros x H.\n    simpl.\n    apply one_sorted.\n  - intros x H.\n    simpl.\n    destruct (x <=? a) eqn:Hleq.\n    + apply leb_complete in Hleq.\n      apply all_sorted; assumption.\n    + apply le_all_sorted.\n      * apply le_all_insert.\n        ** apply leb_complete_conv in Hleq.\n           apply Nat.lt_le_incl; assumption.\n        ** apply sorted_le_all; assumption.\n      * apply IHl.\n        apply sublist_sorted with a; assumption.\nQed.\n\n(** A função principal do algoritmo é dada a seguir: *)\n\nFixpoint insertion_sort l := match l with\n                             | nil =>l\n                             | h :: tl => insert h (insertion_sort tl)\n                             end.\n\n(** A função [insertion_sort] é  definida recursivamente na estrutura da lista [l] que é dada como argumento. Quando a lista é vazia não há nada a fazer, e caso contrário, a função [insert] é chamada para inserir a cabeça [h] da lista na cauda [tl] onde a função é aplicada recursivamente. O lema a seguir pede para você provar que a função [insertion_sort] retorna uma lista ordenada. *)\n\nLemma insertion_sort_sorts: forall l, sorted (insertion_sort l).\nProof.\n  induction l.\n  - simpl.\n    apply nil_sorted.\n  - simpl insertion_sort.\n    apply insert_preserves_sorting.\n    apply IHl.\nQed.\n\n(** A seguir apresentamos a definição de permutação a partir da contagem do número de ocorrências dos elementos nas listas, assim como apresentada no projeto mergesort deste semestre, e os lemas a seguir nos permitem concluir que o algoritmo [insertion_sort] é correto. *)\n\nFixpoint num_oc n l  :=\n  match l with\n    | nil => 0\n    | h :: tl =>\n      if n =? h then S(num_oc n tl) else  num_oc n tl\n  end.\n\nDefinition perm l l' := forall n:nat, num_oc n l = num_oc n l'.\n\nLemma perm_refl: forall l, perm l l.\nProof.\nintro l. unfold perm. intro. reflexivity.\nQed.\n\nLemma num_oc_insert_neq: forall l n a, n =? a = false -> num_oc n (insert a l) = num_oc n l.\nProof.\nAdmitted.\n\nLemma num_oc_insert: forall l n, num_oc n (insert n l) = S (num_oc n l).\nProof.\nAdmitted.\n\nLemma ord_insercao_perm: forall l, perm l (insertion_sort l).\nProof.\nAdmitted.\n  \nTheorem correcao_ord_insercao: forall l, sorted (insertion_sort l) /\\ perm l (insertion_sort l).\nProof.\nAdmitted.\n  \n(** Extração de código certificado *)\n\nRequire Extraction.\n\nRecursive Extraction insertion_sort.\nExtraction \"insertion_sort.ml\" insertion_sort.\n\n", "meta": {"author": "flaviodemoura", "repo": "aula18", "sha": "541233fdf55311ff87bbc617142d4c21c5589698", "save_path": "github-repos/coq/flaviodemoura-aula18", "path": "github-repos/coq/flaviodemoura-aula18/aula18-541233fdf55311ff87bbc617142d4c21c5589698/lc1-2020-2-aula18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7106941673359974}}
{"text": "(* midterm-project.v *)\n(* FPP 2021 - YSC3236 2021-2022, Sem1 *)\n\n\n(* ********** *)\n\n(* A study of polymorphic lists. *)\n\n(* name:\n   email address:\n   date: \n\n   please upload one .v file and one .pdf file containing a project report\n\n   desiderata:\n   - the file should be readable, i.e., properly indented and using items or {...} for subgoals\n   - each use of a tactic should achieve one proof step\n   - all lemmas should be applied to all their arguments\n   - there should be no occurrences of admit, admitted, and abort\n*)\n\n(* ********** *)\n\n(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name := intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith Bool List.\n\n(* ********** *)\n\nNotation \"A =n= B\" :=\n  (Nat.eqb A B) (at level 70, right associativity).\n\nNotation \"A =b= B\" :=\n  (Bool.eqb A B) (at level 70, right associativity).\n\n(* ********** *)\n\nDefinition eqb_option (V : Type) (eqb_V : V -> V -> bool) (ov1 ov2 : option V) : bool :=\n  match ov1 with\n  | Some v1 =>\n    match ov2 with\n    | Some v2 =>\n      eqb_V v1 v2\n    | None =>\n      false\n    end\n  | None =>\n    match ov2 with\n    | Some v2 =>\n      false\n    | None =>\n      true\n    end\n  end.\n\nNotation \"A =on= B\" :=\n  (eqb_option nat Nat.eqb A B) (at level 70, right associativity).\n\n(* ********** *)\n\nFixpoint eqb_list (V : Type) (eqb_V : V -> V -> bool) (v1s v2s : list V) : bool :=\n  match v1s with\n  | nil =>\n    match v2s with\n    | nil =>\n      true\n    | v2 :: v2s' =>\n      false\n    end\n  | v1 :: v1s' =>\n    match v2s with\n    | nil =>\n      false\n    | v2 :: v2s' =>\n      eqb_V v1 v2 && eqb_list V eqb_V v1s' v2s'\n    end\n  end.\n\nLemma fold_unfold_eqb_list_nil :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool)\n         (v2s : list V),\n    eqb_list V eqb_V nil v2s =\n    match v2s with\n    | nil =>\n      true\n    | v2 :: v2s' =>\n      false\n    end.\nProof.\n  fold_unfold_tactic eqb_list.\nQed.\n\nLemma fold_unfold_eqb_list_cons :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool)\n         (v1 : V)\n         (v1s' v2s : list V),\n    eqb_list V eqb_V (v1 :: v1s') v2s =\n    match v2s with\n    | nil =>\n      false\n    | v2 :: v2s' =>\n      eqb_V v1 v2 && eqb_list V eqb_V v1s' v2s'\n    end.\nProof.\n  fold_unfold_tactic eqb_list.\nQed.\n\n(* Task 1: *)\n(* Proof by induction *)\nTheorem soundness_of_equality_over_lists :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        eqb_V v1 v2 = true -> v1 = v2) ->\n    forall v1s v2s : list V,\n      eqb_list V eqb_V v1s v2s = true ->\n      v1s = v2s.\nProof.\n  intros V eqb_V C_eqb_V v1s.\n  induction v1s as [ | v1 v1s' IHv1s'].\n  - intros [ | v2 v2s'] H_eqb.\n    -- reflexivity.\n    -- rewrite -> (fold_unfold_eqb_list_nil V eqb_V (v2 :: v2s')) in H_eqb.\n       discriminate H_eqb.\n  - intros [ | v2 v2s'] H_eqb.\n    -- rewrite -> (fold_unfold_eqb_list_cons V eqb_V v1 v1s' nil) in H_eqb.\n       discriminate H_eqb.\n    -- rewrite -> (fold_unfold_eqb_list_cons V eqb_V v1 v1s' (v2 :: v2s')) in H_eqb.\n       Search (_ && _ = true -> _ /\\ _).\n       (* andb_prop: forall a b : bool, a && b = true -> a = true /\\ b = true *)\n       destruct (andb_prop (eqb_V v1 v2) (eqb_list V eqb_V v1s' v2s') H_eqb) as [H_eqb_1 H_eqb_2].\n       rewrite -> (IHv1s' v2s' H_eqb_2).\n       rewrite -> (C_eqb_V v1 v2 H_eqb_1).\n       reflexivity.\nQed.\n\n(* Proof by induction *)\nTheorem completeness_of_equality_over_lists :\n  forall (V : Type)\n         (eqb_V : V -> V -> bool),\n    (forall v1 v2 : V,\n        v1 = v2 -> eqb_V v1 v2 = true) ->\n    forall v1s v2s : list V,\n      v1s = v2s ->\n      eqb_list V eqb_V v1s v2s = true.\nProof.\n  intros V eqb_V C_eqb v1s.\n  induction v1s as [ | v1 v1s' IHv1s'].\n  - intros [ | v2 v2s'] H_eq.\n    -- exact (fold_unfold_eqb_list_nil V eqb_V nil).\n    -- discriminate H_eq.\n  - intros [ | v2 v2s'] H_eq.\n    -- discriminate H_eq.\n    -- rewrite (fold_unfold_eqb_list_cons V eqb_V v1 v1s' (v2 :: v2s')).\n       injection H_eq as H_eq_1 H_eq_2.\n       rewrite -> (C_eqb v1 v2 H_eq_1).\n       rewrite -> (IHv1s' v2s' H_eq_2).\n       unfold andb.\n       reflexivity.\nQed.\n\n(* this proof requires light of inductil *)\n\n(* ********** *)\n\n(* A study of the polymorphic length function: *)\n\nDefinition specification_of_length (length : forall V : Type, list V -> nat) :=\n  (forall V : Type,\n      length V nil = 0)\n  /\\\n  (forall (V : Type)\n          (v : V)\n          (vs' : list V),\n     length V (v :: vs') = S (length V vs')).\n\n(* Unit-test function: *)\n\nDefinition test_length (candidate : forall V : Type, list V -> nat) :=\n  (candidate nat nil =n= 0) &&\n  (candidate bool nil =n= 0) &&\n  (candidate nat (1 :: nil) =n= 1) &&\n  (candidate bool (true :: nil) =n= 1) &&\n  (candidate nat (2 :: 1 :: nil) =n= 2) &&\n  (candidate bool (false :: true :: nil) =n= 2) &&\n  (candidate nat (3 :: 2 :: 1 :: nil) =n= 3) &&\n  (candidate nat (3 :: 2 :: nil) =n= 2) &&\n  (candidate nat (3 :: nil) =n= 1) &&\n  (candidate bool (false :: false :: true :: nil) =n= 3).\n\n(* The specification specifies at most one length function: *)\n\n(* Proof by induction *)\nTheorem there_is_at_most_one_length_function :\n  forall (V : Type)\n         (length_1 length_2 : forall V : Type, list V -> nat),\n    specification_of_length length_1 ->\n    specification_of_length length_2 ->\n    forall vs : list V,\n      length_1 V vs = length_2 V vs.\nProof.\n  intros V length_1 length_2.\n  unfold specification_of_length.\n  intros [S_length_1_nil S_length_1_cons]\n         [S_length_2_nil S_length_2_cons]\n         vs.\n  induction vs as [ | v vs' IHvs'].\n\n  - Check (S_length_2_nil V).\n    rewrite -> (S_length_2_nil V).\n    Check (S_length_1_nil V).\n    exact (S_length_1_nil V).\n\n  - Check (S_length_1_cons V v vs').\n    rewrite -> (S_length_1_cons V v vs').\n    rewrite -> (S_length_2_cons V v vs').\n    rewrite -> IHvs'.\n    reflexivity.\nQed.\n\n(* The length function in direct style: *)\n\nFixpoint length_v0 (V : Type) (vs : list V) : nat :=\n  match vs with\n    | nil =>\n      0\n    | v :: vs' =>\n      S (length_v0 V vs')\n  end.\n\nCompute (test_length length_v0).\n\n(* Associated fold-unfold lemmas: *)\n\nLemma fold_unfold_length_v0_nil :\n  forall V : Type,\n    length_v0 V nil =\n    0.\nProof.\n  fold_unfold_tactic length_v0.\nQed.\n\nLemma fold_unfold_length_v0_cons :\n  forall (V : Type)\n         (v : V)\n         (vs' : list V),\n    length_v0 V (v :: vs') =\n    S (length_v0 V vs').\nProof.\n  fold_unfold_tactic length_v0.\nQed.\n\n(* The specification specifies at least one length function: *)\n\nTheorem length_v0_satisfies_the_specification_of_length :\n  specification_of_length length_v0.\nProof.\n  unfold specification_of_length.\n  split.\n  - exact fold_unfold_length_v0_nil.\n  - exact fold_unfold_length_v0_cons.\nQed.\n\n(* ***** *)\n\n(* Task 2: *)\n\n(* Implement the length function using an accumulator. *)\n\nFixpoint length_v1_aux (a : nat) (V : Type) (vs : list V) : nat  :=\n  match vs with\n    | nil =>\n      a\n    | v :: vs' =>\n      length_v1_aux (S a) V vs' \n  end.\n\nDefinition length_v1 (V : Type) (vs : list V) : nat :=\n  length_v1_aux 0 V vs .\n\nCompute (test_length length_v1).\n\nLemma fold_unfold_length_v1_aux_nil :\n  forall (V : Type)\n         (a: nat),\n    length_v1_aux a V nil =\n    a.\nProof.\n  fold_unfold_tactic length_v1_aux.\nQed.\n\nLemma fold_unfold_length_v1_aux_cons :\n  forall (V : Type)\n         (v : V)\n         (vs' : list V)\n         (a: nat),\n    length_v1_aux a V (v :: vs')  =\n    length_v1_aux (S a) V vs'.\nProof.\n  fold_unfold_tactic length_v1_aux.\nQed.\n\n(* prove that length_v1 satisfies the specification *)\n\nLemma about_length_v1_aux :\n  forall (V : Type)\n         (vs : list V)\n         (a: nat),\n    length_v1_aux (S a) V vs  =\n    S (length_v1_aux a V vs).\nProof.\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - intro a.\n    rewrite -> (fold_unfold_length_v1_aux_nil V (S a)).\n    rewrite -> (fold_unfold_length_v1_aux_nil V a).\n    reflexivity.\n  - intro a.\n    rewrite -> (fold_unfold_length_v1_aux_cons V v vs' a).\n    rewrite -> (fold_unfold_length_v1_aux_cons V v vs' (S a)).\n    exact (IHvs' (S a)).\nQed.\n\n(* this proof requires light of inductil *)\n\nTheorem length_v1_aux_O_satisfies_the_specification_of_length :\n    specification_of_length (length_v1_aux 0).\nProof.\n  unfold specification_of_length.\n  split.\n  - intro V.\n    exact (fold_unfold_length_v1_aux_nil V 0).\n  - intros V v vs'.\n    rewrite -> (fold_unfold_length_v1_aux_cons V v vs' 0).\n    exact (about_length_v1_aux V vs' 0).\nQed.\n\nCorollary length_v1_satisfies_the_specification_of_length :\n  specification_of_length length_v1.\nProof.\n  unfold length_v1.\n  exact (length_v1_aux_O_satisfies_the_specification_of_length).\nQed.\n  \n(* ********** *)\n\n(* A study of the polymorphic, left-to-right indexing function: *)\n\n(* ***** *)\n\n(* The indexing function can be specified by induction over the given list: *)\n\nDefinition test_list_nth (candidate : forall V : Type, list V -> nat -> option V) :=\n  ((candidate nat (0 :: 1 :: 2 :: 3 :: nil) 0) =on= (Some 0)) &&\n  ((candidate nat (0 :: 1 :: 2 :: 3 :: nil) 1) =on= (Some 1)) &&\n  ((candidate nat (0 :: 1 :: 2 :: 3 :: nil) 2) =on= (Some 2)) &&\n  ((candidate nat (0 :: 1 :: 2 :: 3 :: nil) 3) =on= (Some 3)) &&\n  ((candidate nat (0 :: 1 :: 2 :: 3 :: nil) 4) =on= None) &&\n  ((candidate nat (0 :: 1 :: 2 :: 3 :: nil) 5) =on= None) &&\n  ((candidate nat (0 :: 1 :: 2 :: 3 :: nil) 6) =on= None) &&\n  ((candidate nat (0 :: 1 :: 2 :: 3 :: nil) 7) =on= None).\n\nFixpoint list_nth (V : Type) (vs : list V) (n : nat) : option V :=\n  match vs with\n  | nil =>\n    None\n  | v :: vs' =>\n    match n with\n    | O =>\n      Some v\n    | S n' =>\n      list_nth V vs' n'\n    end\n  end.\n\nCompute (test_list_nth list_nth).\n\nLemma fold_unfold_list_nth_nil :\n  forall (V : Type)\n         (n : nat),\n    list_nth V nil n =\n    None.\nProof.\n  fold_unfold_tactic list_nth.\nQed.\n\nLemma fold_unfold_list_nth_cons :\n  forall (V : Type)\n         (v : V)\n         (vs' : list V)\n         (n : nat),\n    list_nth V (v :: vs') n =\n    match n with\n    | O =>\n      Some v\n    | S n' =>\n      list_nth V vs' n'\n    end.\nProof.\n  fold_unfold_tactic list_nth.\nQed.\n\n(* ***** *)\n\n(* The indexing function can be specified by induction over the given index: *)\n\nDefinition test_nat_nth (candidate : forall V : Type, nat -> list V -> option V) :=\n  ((candidate nat 0 (0 :: 1 :: 2 :: 3 :: nil)) =on= (Some 0)) &&\n  ((candidate nat 1 (0 :: 1 :: 2 :: 3 :: nil)) =on= (Some 1)) &&\n  ((candidate nat 2 (0 :: 1 :: 2 :: 3 :: nil)) =on= (Some 2)) &&\n  ((candidate nat 3 (0 :: 1 :: 2 :: 3 :: nil)) =on= (Some 3)) &&\n  ((candidate nat 4 (0 :: 1 :: 2 :: 3 :: nil)) =on= None) &&\n  ((candidate nat 5 (0 :: 1 :: 2 :: 3 :: nil)) =on= None) &&\n  ((candidate nat 6 (0 :: 1 :: 2 :: 3 :: nil)) =on= None) &&\n  ((candidate nat 7 (0 :: 1 :: 2 :: 3 :: nil)) =on= None).\n\nFixpoint nat_nth (V : Type) (n : nat) (vs : list V) : option V :=\n  match n with\n  | O =>\n    match vs with\n    | nil =>\n      None\n    | v :: vs' =>\n      Some v\n    end\n  | S n' =>\n    match vs with\n    | nil =>\n      None\n    | v :: vs' =>\n      nat_nth V n' vs'\n    end\n  end.\n\nCompute (test_nat_nth nat_nth).\n\nLemma fold_unfold_nat_nth_O :\n  forall (V : Type)\n         (vs : list V),\n    nat_nth V O vs =\n    match vs with\n    | nil =>\n      None\n    | v :: vs' =>\n      Some v\n    end.\nProof.\n  fold_unfold_tactic nat_nth.\nQed.\n\nLemma fold_unfold_nat_nth_S :\n  forall (V : Type)\n         (n' : nat)\n         (vs : list V),\n    nat_nth V (S n') vs =\n    match vs with\n    | nil =>\n      None\n    | v :: vs' =>\n      nat_nth V n' vs'\n    end.\nProof.\n  fold_unfold_tactic nat_nth.\nQed.\n\n(* ***** *)\n\n(* Task 3: *)\n\n(*\n   a. Both list-indexing functions come with their own unit-test function.\n      Test each implementation with the unit-test function of the other implementation,\n      and verify that it passes this other test.\n*)\n\nDefinition list_nth_for_test_nat_nth (V : Type) (n : nat) (vs : list V) : option V :=\n  list_nth V vs n.\n  \nCompute (test_nat_nth list_nth_for_test_nat_nth).\n(* \n     = true\n     : bool\n *)\n\nDefinition nat_nth_for_test_list_nth (V : Type) (vs : list V) (n : nat) : option V :=\n  nat_nth V n vs.\n\nCompute (test_list_nth nat_nth_for_test_list_nth).\n(* \n     = true\n     : bool\n *)\n\n(*\n   b. Prove by induction on natural numbers that if, given a list and an index, list_nth yields a result,\n      then given this index and this list, nat_nth yields the same result\n*)\n\n(* Proof by induction *)\nProposition list_nth_implies_nat_nth :\n  forall (V : Type)\n         (vs : list V)\n         (n : nat)\n         (ov : option V),\n    list_nth V vs n = ov ->\n    nat_nth V n vs = ov.\nProof.\n  (* proof by induction on natural number *)\n  intros V vs n ov.\n  revert vs.\n  induction n as [ | n' IHn'].\n  - destruct vs as [ | v vs'] eqn:H_vs.\n    -- intro H_list_result.\n       rewrite -> (fold_unfold_nat_nth_O V nil).\n       rewrite -> (fold_unfold_list_nth_nil V 0) in H_list_result.\n       exact (H_list_result).\n    -- intro H_list_result.\n       rewrite -> (fold_unfold_nat_nth_O V (v :: vs')).\n       rewrite -> (fold_unfold_list_nth_cons V v vs' 0) in H_list_result.\n       exact (H_list_result).\n  - destruct vs as [ | v vs'] eqn:H_vs.\n    -- intro H_list_result.\n       rewrite -> (fold_unfold_nat_nth_S V n' nil).\n       rewrite -> (fold_unfold_list_nth_nil V (S n')) in H_list_result.\n       exact (H_list_result).\n    -- intro H_list_result.\n       rewrite -> (fold_unfold_nat_nth_S V n' (v :: vs')) .\n       rewrite -> (fold_unfold_list_nth_cons V v vs' (S n')) in H_list_result.\n       rewrite -> (IHn' vs' H_list_result).\n       reflexivity.\n\n  Restart.\n\n  (* proof by induction on lists *)\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - destruct n as [ | n'].\n    -- rewrite -> (fold_unfold_list_nth_nil V 0).\n       rewrite -> (fold_unfold_nat_nth_O V nil).\n       intros ov H_ov.\n       exact H_ov.\n    -- rewrite -> (fold_unfold_list_nth_nil V (S n')).\n       rewrite -> (fold_unfold_nat_nth_S V n' nil).\n       intros ov H_ov.\n       exact H_ov.\n  - destruct n as [ | n'].\n    -- rewrite -> (fold_unfold_list_nth_cons V v vs' 0).\n       rewrite -> (fold_unfold_nat_nth_O V (v :: vs')).\n       intros ov H_ov.\n       exact H_ov.\n    -- rewrite -> (fold_unfold_list_nth_cons V v vs' (S n')).\n       rewrite -> (fold_unfold_nat_nth_S V n' (v :: vs')).\n       exact (IHvs' n').\nQed.\n\n(* this proof requires light of inductil *)\n\n(* Could you prove this proposition by induction on lists? *)\n\n(*\n   c. Prove by induction on lists that if, given an index and a list, nat_nth yields a result,\n      then given this list and this index, list_nth yields the same result\n *)\n\n(* Proof by induction *)\nProposition nat_nth_implies_list_nth :\n  forall (V : Type)\n         (n : nat)\n         (vs : list V)\n         (ov : option V),\n    nat_nth V n vs = ov ->\n    list_nth V vs n = ov.\nProof.\n  (* proof by induction on list *)\n  intros V n vs ov.\n  revert n.\n  induction vs as [ | v vs' IHvs'].\n  - destruct n as [ | n'] eqn: H_n.\n    -- intro H_nat_result.\n       rewrite -> (fold_unfold_nat_nth_O V nil) in H_nat_result.\n       rewrite -> (fold_unfold_list_nth_nil V 0).\n       exact (H_nat_result).\n    -- intro H_nat_result.\n       rewrite -> (fold_unfold_nat_nth_S V n' nil) in H_nat_result.\n       rewrite -> (fold_unfold_list_nth_nil V (S n')).\n       exact (H_nat_result).\n  - destruct n as [ | n'] eqn: H_n.\n    -- intro H_nat_result.\n       rewrite -> (fold_unfold_nat_nth_O V (v :: vs')) in H_nat_result.\n       rewrite -> (fold_unfold_list_nth_cons V v vs' 0).\n       exact (H_nat_result).\n    -- intro H_nat_result.\n       rewrite -> (fold_unfold_nat_nth_S V n' (v :: vs')) in H_nat_result.\n       rewrite -> (fold_unfold_list_nth_cons V v vs' (S n')).\n       rewrite -> (IHvs' n' H_nat_result).\n       reflexivity.\n\n       Restart.\n\n  (* proof by induction on natural number *)\n  intros V n vs ov.\n  revert vs.\n  induction n as [ | n' IHn'].\n  - destruct vs as [ | v vs'] eqn:H_vs.\n    -- intro H_nat_result.\n       rewrite -> (fold_unfold_nat_nth_O V nil) in H_nat_result.\n       rewrite -> (fold_unfold_list_nth_nil V 0).\n       exact (H_nat_result).\n    -- intro H_nat_result.\n       rewrite -> (fold_unfold_nat_nth_O V (v :: vs')) in H_nat_result.\n       rewrite -> (fold_unfold_list_nth_cons V v vs' 0).\n       exact (H_nat_result).\n  - destruct vs as [ | v vs'] eqn:H_vs.\n    -- intro H_nat_result.\n       rewrite -> (fold_unfold_nat_nth_S V n' nil) in H_nat_result.\n       rewrite -> (fold_unfold_list_nth_nil V (S n')).\n       exact (H_nat_result).\n    -- intro H_nat_result.\n       rewrite -> (fold_unfold_nat_nth_S V n' (v :: vs')) in H_nat_result.\n       rewrite -> (fold_unfold_list_nth_cons V v vs' (S n')).\n       rewrite -> (IHn' vs' H_nat_result).\n       reflexivity.      \nQed.\n\n(* this proof requires light of inductil *)\n\n(*\n   d. What do you conclude?\n      Swapping the argments is indeed all it takes to go from one specification to another.\n*)\n\n(* ********** *)\n\n(* A study of the polymorphic copy function: *)\n\nDefinition specification_of_copy (copy : forall V : Type, list V -> list V) :=\n  (forall V : Type,\n      copy V nil = nil)\n  /\\\n  (forall (V : Type)\n          (v : V)\n          (vs' : list V),\n     copy V (v :: vs') = v :: (copy V vs')).\n\nDefinition test_copy (candidate : forall V : Type, list V -> list V) :=\n  (eqb_list nat Nat.eqb (candidate nat nil) nil) &&\n  (eqb_list bool Bool.eqb (candidate bool nil) nil) &&\n  (eqb_list nat Nat.eqb (candidate nat (1 :: nil)) (1 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (true :: nil)) (true :: nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat (2 :: 1 :: nil)) (2 :: 1 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (false :: true :: nil)) (false :: true :: nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat (3 :: 5 :: 2 :: 1 :: nil)) (3 :: 5 :: 2 :: 1 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (false :: false :: true :: false :: true :: nil))\n            (false :: false :: true :: false :: true :: nil)).\n\n(* Task 4:\n\n   a. expand the unit-test function for copy with a few more tests\n\n   b. implement the copy function in direct style\n*)\n\nFixpoint copy_v0 (V : Type) (vs : list V) : list V :=\n  match vs with\n    | nil => nil\n    | v :: vs' => v :: (copy_v0 V vs')\n  end.\n\nCompute (test_copy copy_v0).\n(*\n     = true\n     : bool\n*)\n\n(*\n   c. state its associated fold-unfold lemmas\n*)\n\nLemma fold_unfold_copy_v0_nil :\n  forall (V : Type),\n    copy_v0 V nil = nil.\nProof.\n  fold_unfold_tactic copy_v0.\nQed.\n \nLemma fold_unfold_copy_v0_cons :\n  forall (V : Type)\n         (v : V)\n         (vs' : list V),\n    copy_v0 V (v :: vs') = v :: (copy_v0 V vs').\nProof.\n  fold_unfold_tactic copy_v0.\nQed.\n\n(*\n   d. prove whether your implementation satisfies the specification.\n*)\n\nTheorem copy_v0_satisfies_the_specification_of_copy :\n  specification_of_copy copy_v0.\nProof.\n  unfold specification_of_copy.\n  split.\n  - exact (fold_unfold_copy_v0_nil).\n  - exact (fold_unfold_copy_v0_cons).\nQed.\n\n(*\n   e. prove whether copy is idempotent\n*)\n\n\nProposition copy_is_idempotent :\n  forall (V : Type)\n         (vs : list V),\n    copy_v0 V (copy_v0 V vs) = copy_v0 V vs.\nProof.\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - exact (fold_unfold_copy_v0_nil V).\n  - rewrite -> (fold_unfold_copy_v0_cons V v vs').\n    rewrite -> (fold_unfold_copy_v0_cons V v (copy_v0 V vs')).\n    rewrite -> (IHvs').\n    reflexivity.\nQed.\n\n(*\n   f. prove whether copying a list preserves its length\n *)\n\n(* Proof by induction *)\nProposition copy_preserves_length :\n  forall (V : Type)\n         (vs : list V)\n         (n : nat),\n    length_v0 V vs = n ->\n    length_v0 V (copy_v0 V vs) = n.\nProof.\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - intros n H_length.\n    rewrite -> (fold_unfold_copy_v0_nil V).\n    exact (H_length).\n  - destruct n as [ | n'].\n    -- intro H_length.\n       rewrite -> (fold_unfold_length_v0_cons V v vs') in H_length.\n       discriminate (H_length).\n    -- intro H_length.\n       rewrite -> (fold_unfold_copy_v0_cons V v vs').\n       rewrite -> (fold_unfold_length_v0_cons V v (copy_v0 V vs')).\n       rewrite -> (fold_unfold_length_v0_cons V v vs') in H_length.\n       Search (S _ = S _).\n       (* eq_add_S: forall n m : nat, S n = S m -> n = m *)\n       apply eq_add_S in H_length.\n       rewrite -> (IHvs' n' H_length).\n       reflexivity.\nQed.\n\n(* this proof requires light of inductil, as we destruct the n *)\n\n(*\n   G. subsidiary question: can you think of a strikingly simple implementation of the copy function?\n      if so, pray show that it satisfies the specification of copy\n*)\n\nDefinition copy_v1 (V : Type) (vs : list V) : list V :=\n  vs.\n\nCompute (test_copy copy_v1).\n(* \n     = true\n     : bool\n*)\n\nTheorem copy_v1_satisfies_the_specification_of_copy :\n  specification_of_copy copy_v1.\nProof.\n  unfold specification_of_copy.\n  split.\n  - intro V.\n    unfold copy_v1.\n    reflexivity.\n  - intros V v vs'.\n    unfold copy_v1.\n    reflexivity.\nQed.\n\n(* ********** *)\n\n(* A study of the polymorphic append function: *)\n\nDefinition specification_of_append (append : forall V : Type, list V -> list V -> list V) :=\n  (forall (V : Type)\n          (v2s : list V),\n      append V nil v2s = v2s)\n  /\\\n  (forall (V : Type)\n          (v1 : V)\n          (v1s' v2s : list V),\n      append V (v1 :: v1s') v2s = v1 :: append V v1s' v2s).\n\n(* Task 5:\n\n   a. define a unit-test function for append\n*)\n\nDefinition test_append (candidate : forall V : Type, list V -> list V -> list V) : bool :=\n  (eqb_list nat beq_nat (candidate nat (2 :: 1 :: nil) (1 :: 0 :: nil)) (2 :: 1 :: 1 :: 0 :: nil)) &&\n  (eqb_list nat beq_nat (candidate nat (9 :: 8 :: nil) (7 :: 6 :: nil)) (9 :: 8 :: 7 :: 6 :: nil)) &&\n  (eqb_list nat beq_nat (candidate nat (10 :: 11 :: nil) (12 :: 13 :: nil)) (10 :: 11 :: 12 :: 13 :: nil)) &&\n  (eqb_list nat beq_nat (candidate nat (2 :: nil) (1 :: 0 :: nil)) (2 :: 1 :: 0 :: nil)) &&\n  (eqb_list nat beq_nat (candidate nat (4 :: nil) (16 :: 9 :: nil)) (4 :: 16 :: 9 :: nil)) &&\n  (eqb_list nat beq_nat (candidate nat (nil) (1 :: 0 :: nil)) (1 :: 0 :: nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat nil nil) nil) &&\n  (eqb_list bool Bool.eqb (candidate bool nil nil) nil) &&\n  (eqb_list nat Nat.eqb (candidate nat (1 :: nil) nil) (1 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (true :: nil) nil) (true :: nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat (2 :: 1 :: nil) (4 :: nil)) (2 :: 1 :: 4 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (false :: true :: nil) (true :: true :: false :: nil))\n            (false :: true :: true :: true :: false :: nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat (3 :: 5 :: nil) (6 :: 7 :: 8 :: nil)) (3 :: 5 :: 6 :: 7 :: 8 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (true :: nil )(false :: false :: true :: false :: true :: nil))\n            (true :: false :: false :: true :: false :: true :: nil)).\n\n(*\n   b. implement the append function in direct style\n*)\n\nFixpoint append_v0 (V : Type) (v1s v2s : list V) : list V :=\n  match v1s with\n    | nil => v2s\n    | v :: vs' => v :: (append_v0 V vs' v2s)\n  end.\n\nCompute test_append append_v0.\n(* \n     = true\n     : bool\n*)\n\n(* c. state its associated fold-unfold lemmas *)\n\nLemma fold_unfold_append_v0_nil :\n  forall (V : Type)\n         (v2s : list V),\n    append_v0 V nil v2s = v2s.\nProof.\n  fold_unfold_tactic append_v0.\nQed.\n\nLemma fold_unfold_append_v0_cons :\n  forall (V : Type)\n         (v1 : V)\n         (v1s' v2s : list V),\n    append_v0 V (v1 :: v1s') v2s = v1 :: (append_v0 V v1s' v2s).\nProof.\n  fold_unfold_tactic append_v0.\nQed.\n\n(*  d. prove that your implementation satisfies the specification *)\n\nTheorem append_v0_satisfies_the_specification_of_append :\n  specification_of_append append_v0.\nProof.\n  unfold specification_of_append.\n  split.\n  - exact (fold_unfold_append_v0_nil).\n  - exact (fold_unfold_append_v0_cons).\nQed.\n\n(*  e. prove whether nil is neutral on the left of append *)\n\nTheorem nil_is_neutral_on_append_v0_left :\n  forall (V : Type)\n         (vs : list V),\n    append_v0 V nil vs = vs.\nProof.\n  intros V vs.\n  exact (fold_unfold_append_v0_nil V vs).\nQed.\n\n(*  f. prove whether nil is neutral on the right of append *)\n\nTheorem nil_is_neutral_on_append_v0_right :\n  forall (V : Type)\n         (vs : list V),\n    append_v0 V vs nil = vs.\nProof.\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - exact (fold_unfold_append_v0_nil V nil).\n  - rewrite -> (fold_unfold_append_v0_cons V v vs' nil).\n    rewrite -> IHvs'.\n    reflexivity.\nQed.\n\n(* g. prove whether append is commutative *)\n\nTheorem append_v0_is_not_commutative :\n  exists (V : Type)\n         (v1s v2s : list V),\n    append_v0 V v1s v2s <> append_v0 V v2s v1s.\nProof.\n  unfold not.\n  exists (nat : Type).\n  exists ((1 :: nil) : list nat).\n  exists ((2 :: nil) : list nat).\n  rewrite -> (fold_unfold_append_v0_cons nat 1 nil (2 :: nil)).\n  rewrite -> (fold_unfold_append_v0_nil nat (2 :: nil)).\n  rewrite -> (fold_unfold_append_v0_cons nat 2 nil (1 :: nil)).\n  rewrite -> (fold_unfold_append_v0_nil nat (1 :: nil)).\n  discriminate.\nQed.\n\n(*  h. prove whether append is associative *)\n\n(* Proof by induction *)\nTheorem append_v0_is_associative :\n  forall (V : Type)\n         (v1s v2s v3s: list V),\n    append_v0 V v1s (append_v0 V v2s v3s) = append_v0 V (append_v0 V v1s v2s) v3s.\nProof.\n  intros V v1s v2s v3s.\n  induction v1s as [ | v1 v1s' IHv1s'].\n  - rewrite -> (fold_unfold_append_v0_nil V (append_v0 V v2s v3s)).\n    rewrite -> (fold_unfold_append_v0_nil V v2s).\n    reflexivity.\n  - rewrite -> (fold_unfold_append_v0_cons V v1 v1s' (append_v0 V v2s v3s)).\n    rewrite -> IHv1s'.\n    rewrite -> (fold_unfold_append_v0_cons V v1 v1s' v2s).\n    rewrite -> (fold_unfold_append_v0_cons V v1 (append_v0 V v1s' v2s) v3s).\n    reflexivity.\nQed.\n\n(* this proof does not require the light of inductil *)\n\n(* i. prove whether appending two lists preserves their length *)\n\n(* Proof by induction *)\nProposition append_preserves_length :\n  forall (V : Type)\n         (v1s v2s : list V)\n         (n1 n2 : nat),\n    length_v0 V v1s = n1 ->\n    length_v0 V v2s = n2 ->\n    length_v0 V (append_v0 V v1s v2s) = n1 + n2.\nProof.\n  intros V v1s.\n  induction v1s as [ | v1 v1s' IHv1s'].\n  - intros v2s n1 n2  H_length_v1s H_length_v2s.\n    rewrite -> (fold_unfold_append_v0_nil V v2s).\n    rewrite -> (fold_unfold_length_v0_nil V) in H_length_v1s.\n    rewrite <- H_length_v1s.\n    rewrite -> (Nat.add_0_l).\n    exact (H_length_v2s).\n  - intros v2s [ | n'] n2 H_length_v1s' H_length_v2s.\n    -- discriminate H_length_v1s'.\n    -- rewrite -> (fold_unfold_append_v0_cons V v1 v1s' v2s).\n       rewrite -> (fold_unfold_length_v0_cons V v1 (append_v0 V v1s' v2s)).\n       rewrite -> (IHv1s' v2s n' n2).\n       --- exact (Nat.add_succ_l n' n2).\n       --- rewrite -> (fold_unfold_length_v0_cons V v1 v1s') in H_length_v1s'.\n           rewrite -> (Nat.succ_inj (length_v0 V v1s') n' H_length_v1s').\n           reflexivity.\n       --- exact (H_length_v2s).\n   (* In this proof, there is an assumption that is not met yet when we did \"rewrite -> (IHv1s' v2s n' n2).\", which adds to the subgoal. We can address this by using injection in the subgoal. *)\n\n   Restart.\n   intros V v1s.\n   induction v1s as [ | v1 v1s' IHv1s'].\n  - intros v2s n1 n2  H_length_v1s H_length_v2s.\n    rewrite -> (fold_unfold_append_v0_nil V v2s).\n    rewrite -> (fold_unfold_length_v0_nil V) in H_length_v1s.\n    rewrite <- H_length_v1s.\n    rewrite -> (Nat.add_0_l).\n    exact (H_length_v2s).\n  - intros v2s [ | n'] n2 H_length_v1s' H_length_v2s.\n    -- discriminate H_length_v1s'.\n    -- rewrite -> (fold_unfold_append_v0_cons V v1 v1s' v2s).\n       rewrite -> (fold_unfold_length_v0_cons V v1 (append_v0 V v1s' v2s)).\n       rewrite -> (fold_unfold_length_v0_cons V v1 v1s') in H_length_v1s'.\n       injection H_length_v1s' as H_length_v1s'.\n       rewrite -> (IHv1s' v2s n' n2 H_length_v1s' H_length_v2s).\n       exact (Nat.add_succ_l n' n2).\nQed.\n\n(* Both proofs require light of inductil *)\n\n(* Proof by induction *)\nProposition append_preserves_length_alt :\n  forall (V : Type)\n         (v1s v2s : list V),\n    length_v0 V (append_v0 V v1s v2s) = length_v0 V v1s + length_v0 V v2s.\nProof.\n  intros V v1s v2s.\n  induction v1s as [ | v1 v1s' IHv1s'].\n  - rewrite -> (fold_unfold_append_v0_nil V v2s).\n    rewrite -> (fold_unfold_length_v0_nil V).\n    rewrite -> (Nat.add_0_l (length_v0 V v2s)).\n    reflexivity.\n  - rewrite -> (fold_unfold_append_v0_cons V v1 v1s' v2s).\n    rewrite -> (fold_unfold_length_v0_cons V v1 (append_v0 V v1s' v2s)).\n    rewrite -> IHv1s'.\n    rewrite -> (fold_unfold_length_v0_cons V v1 v1s').\n    exact (Nat.add_succ_l (length_v0 V v1s') (length_v0 V v2s)).\nQed.\n\n(* this proof does not require light of inductil *)\n\n(* j. prove whether append and copy commute with each other *)\n\n(* Proof by induction *)\nProposition append_and_copy_commute_with_each_other :\n  forall (V : Type)\n         (v1s v2s : list V),\n    copy_v0 V (append_v0 V v1s v2s) = append_v0 V (copy_v0 V v1s) (copy_v0 V v2s).\nProof.\n  intros V v1s v2s.\n  induction v1s as [ | v1 v1s' IHv1s'].\n  - rewrite -> (fold_unfold_append_v0_nil V v2s).\n    rewrite -> (fold_unfold_copy_v0_nil V).\n    rewrite -> (fold_unfold_append_v0_nil V (copy_v0 V v2s)).\n    reflexivity.\n  - rewrite -> (fold_unfold_append_v0_cons V v1 v1s' v2s).\n    rewrite -> (fold_unfold_copy_v0_cons V v1 (append_v0 V v1s' v2s)).\n    rewrite -> IHv1s'.\n    rewrite -> (fold_unfold_copy_v0_cons V v1 v1s').\n    rewrite -> (fold_unfold_append_v0_cons V v1 (copy_v0 V v1s') (copy_v0 V v2s)).\n    reflexivity.\nQed.\n\n(* this proof does not require light of inductil *)\n\n(* ********** *)\n\n(* A study of the polymorphic reverse function: *)\n\nDefinition specification_of_reverse (reverse : forall V : Type, list V -> list V) :=\n  forall append : forall W : Type, list W -> list W -> list W,\n    specification_of_append append ->\n    (forall V : Type,\n        reverse V nil = nil)\n    /\\\n    (forall (V : Type)\n            (v : V)\n            (vs' : list V),\n        reverse V (v :: vs') = append V (reverse V vs') (v :: nil)).\n\n(* Task 6:\n\n   a. Define a unit-test function for an implementation of the reverse function.\n*)\n\nDefinition test_reverse (candidate : forall V : Type, list V -> list V) :=\n  (eqb_list nat beq_nat (candidate nat (2 :: 1 :: nil)) (1 :: 2 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat (1 :: nil)) (1 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat (2 :: 2 :: nil)) (2 :: 2 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat (2 :: 1 :: 9 :: nil)) (9 :: 1 :: 2 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat (4 :: 3 :: 2 :: 1 :: nil)) (1 :: 2 :: 3 :: 4 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat (11 :: 2 ::  nil)) (2 :: 11 :: nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat nil) nil) &&\n  (eqb_list bool Bool.eqb (candidate bool nil) nil) &&\n  (eqb_list nat Nat.eqb (candidate nat (1 :: nil)) (1 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (true :: nil)) (true :: nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat (2 :: 1 :: nil)) (1 :: 2 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (false :: true :: nil)) (true :: false ::  nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat (3 :: 5 :: 2 :: 1 :: nil)) (1 :: 2 :: 5 :: 3 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool (false :: false :: false :: true :: false :: true :: nil))\n            (true :: false :: true :: false :: false :: false :: nil)).\n(*\n   b. Implement the reverse function recursively and in direct style, using append_v0.\n*)\n\nFixpoint reverse_v0 (V : Type) (vs : list V) : list V :=\n  match vs with\n    | nil => nil\n    | v :: vs' => append_v0 V (reverse_v0 V vs') (v :: nil)\n  end.\n\nCompute test_reverse reverse_v0.\n(*\n     = true\n     : bool\n*)\n\n(*\n   c. State the associated fold-unfold lemmas.\n*)\n\nLemma fold_unfold_reverse_v0_nil :\n  forall (V : Type),\n    reverse_v0 V nil = nil.\nProof.\n  fold_unfold_tactic reverse_v0.\nQed.\n\nLemma fold_unfold_reverse_v0_cons :\n  forall (V : Type)\n         (v : V)\n         (vs' : list V),\n    reverse_v0 V (v :: vs') = append_v0 V (reverse_v0 V vs') (v :: nil).\nProof.\n  fold_unfold_tactic reverse_v0.\nQed.\n\n(*\n   d. Prove whether your implementation satisfies the specification.\n*)\n\n(* Proof by induction *)\nLemma equivalence_of_append :\n  forall append: forall W : Type, list W -> list W -> list W,\n    specification_of_append append ->\n    forall (V : Type)\n           (v1s v2s : list V),\n    append_v0 V v1s v2s  = append V v1s v2s.\nProof.\n  intros append [S_append_nil S_append_cons] V v1s v2s.\n  induction v1s as [ | v1 v1s' IHv1s'].\n  - rewrite -> (S_append_nil V v2s).\n    exact (fold_unfold_append_v0_nil V v2s).\n  - rewrite -> (S_append_cons V v1 v1s' v2s).\n    rewrite -> (fold_unfold_append_v0_cons V v1 v1s' v2s).\n    rewrite -> IHv1s'.\n    reflexivity.\nQed.\n\n(* this proof does not require light of inductil *)\n\nTheorem reverse_v0_satisfies_the_specification_of_reverse :\n  specification_of_reverse reverse_v0.\n\nProof.\n  unfold specification_of_reverse.\n  intros append S_append.\n  split.\n  - exact (fold_unfold_reverse_v0_nil).\n  - intros V v vs'.\n    rewrite -> (fold_unfold_reverse_v0_cons V v vs').\n    rewrite -> (equivalence_of_append append S_append V (reverse_v0 V vs') (v :: nil)).\n    reflexivity.\nQed.\n\n(*\n   e. prove whether reverse_v0 is involutory.\n*)\n\n(* Proof by induction *)\nLemma about_reverse_v0 :\n  forall (V : Type)\n         (v : V)\n         (vs : list V),\n    reverse_v0 V (append_v0 V vs (v :: nil)) = v :: reverse_v0 V vs.\nProof.\n  intros V v vs.\n  induction vs as [ | v'' vs'' IHvs''].\n  - rewrite -> (fold_unfold_append_v0_nil V (v :: nil)).\n    rewrite -> (fold_unfold_reverse_v0_cons V v nil).\n    rewrite -> (fold_unfold_reverse_v0_nil V).\n    rewrite -> (fold_unfold_append_v0_nil V (v :: nil)).\n    reflexivity.\n  - rewrite -> (fold_unfold_append_v0_cons V v'' vs'' (v :: nil)).\n    rewrite -> (fold_unfold_reverse_v0_cons V v'' vs'').\n    rewrite -> (fold_unfold_reverse_v0_cons V v'' (append_v0 V vs'' (v :: nil))).\n    rewrite -> (IHvs'').\n    rewrite -> (fold_unfold_append_v0_cons V v (reverse_v0 V vs'') (v'' :: nil)).\n    reflexivity.\nQed.\n\n(* this proof does not require light of inductil *)\n\n(* Proof by induction *)\nProposition reverse_v0_is_involutory :\n  forall (V : Type)\n         (vs : list V),\n    reverse_v0 V (reverse_v0 V vs) = vs.\nProof.\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - rewrite -> (fold_unfold_reverse_v0_nil V).\n    reflexivity.\n  - rewrite -> (fold_unfold_reverse_v0_cons V v vs').\n    rewrite -> (about_reverse_v0 V v (reverse_v0 V vs')).\n    rewrite -> IHvs'.\n    reflexivity.\nQed.\n\n(*\n   f. Prove whether reversing a list preserves its length.\n*)\n\n(* Proof by induction *)\nProposition reverse_v0_preserves_length :\n  forall (V : Type)\n         (vs : list V)\n         (n : nat),\n    length_v0 V vs = n ->\n    length_v0 V (reverse_v0 V vs) = n.\nProof.\n  intro V.\n  induction vs as [ | v vs' IHvs'].\n  - intros n H_length.\n    rewrite -> (fold_unfold_reverse_v0_nil V).\n    exact H_length.\n  - intros [ | n'] H_length.\n    -- discriminate H_length.\n    -- rewrite -> (fold_unfold_reverse_v0_cons V v vs').\n       rewrite -> (append_preserves_length_alt V (reverse_v0 V vs') (v :: nil)).\n       rewrite -> (fold_unfold_length_v0_cons V v nil).\n       rewrite -> (fold_unfold_length_v0_nil V).\n       rewrite -> (fold_unfold_length_v0_cons V v vs') in H_length.\n       injection H_length as H_length. \n       rewrite -> (IHvs' n' H_length).\n       exact (Nat.add_1_r n').\nQed.\n\n(* this proof requires light of inductil *)\n\n(* Proof by induction *)\nProposition reverse_v0_preserves_length_alt :\n  forall (V : Type)\n         (vs : list V),\n    length_v0 V (reverse_v0 V vs) = length_v0 V vs.\nProof.\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - rewrite -> (fold_unfold_reverse_v0_nil V).\n    reflexivity.\n  - rewrite -> (fold_unfold_reverse_v0_cons V v vs').\n    rewrite -> (append_preserves_length_alt V (reverse_v0 V vs') (v :: nil)).\n    rewrite -> (fold_unfold_length_v0_cons V v nil).\n    rewrite -> (fold_unfold_length_v0_nil V).\n    rewrite -> (IHvs').\n    rewrite -> (fold_unfold_length_v0_cons V v vs').\n    exact (Nat.add_1_r (length_v0 V vs')).\nQed.\n\n(* reverse_v0_preserves_length as a corollary of reverse_v0_preserves_length_alt *)\n\nCorollary reverse_v0_preserves_length':\n  forall (V : Type)\n         (vs : list V)\n         (n : nat),\n    length_v0 V vs = n ->\n    length_v0 V (reverse_v0 V vs) = n.\nProof.\n  intros V vs n H_length.\n  rewrite -> (reverse_v0_preserves_length_alt V vs).\n  exact (H_length).\nQed.\n\n(* reverse_v0_preserves_length_alt as a corollary of reverse_v0_preserves_length *)\n\nCorollary reverse_v0_preserves_length_alt' :\n  forall (V : Type)\n         (vs : list V),\n    length_v0 V (reverse_v0 V vs) = length_v0 V vs.\nProof.\n  intros V vs.\n  apply (reverse_v0_preserves_length V vs (length_v0 V vs)).\n  reflexivity.\nQed.\n\n(*\n   g. Do append_v0 and reverse_v0 commute with each other (hint: yes they do) and if so how?\n*)\n\n(* \n   brings back fond memories of commuting diagrams :')\n*)\n\n(* Proof by induction *)\nProposition append_and_reverse_v0_commute_with_each_other :\n  forall (V : Type)\n         (v1s v2s : list V),\n    reverse_v0 V (append_v0 V v1s v2s) = append_v0 V (reverse_v0 V v2s) (reverse_v0 V v1s).\nProof.\n  intros V v1s v2s.\n  induction v1s as [ | v1 v1s' IHv1s']. \n  - rewrite -> (fold_unfold_append_v0_nil V v2s).\n    rewrite -> (fold_unfold_reverse_v0_nil V).\n    rewrite -> (nil_is_neutral_on_append_v0_right V (reverse_v0 V v2s)).\n    reflexivity.\n  - rewrite -> (fold_unfold_append_v0_cons V v1 v1s' v2s).\n    rewrite -> (fold_unfold_reverse_v0_cons V v1 (append_v0 V v1s' v2s)).\n    rewrite -> (IHv1s').\n    rewrite -> (fold_unfold_reverse_v0_cons V v1 v1s').\n    rewrite <- (append_v0_is_associative V (reverse_v0 V v2s) (reverse_v0 V v1s') (v1 :: nil)).\n    reflexivity.\nQed.\n\n(* this proof does not require light of inductil *)\n\n(*\n   h. Implement the reverse function using an accumulator instead of using append_v0.\n*)\n\nFixpoint reverse_v1_aux (V : Type) (vs : list V) (a : list V) : list V :=\n  match vs with\n  | nil => a\n  | v :: vs' => reverse_v1_aux V vs' (v :: a)\n  end.\n\nDefinition reverse_v1 (V : Type) (vs : list V) : list V :=\n  reverse_v1_aux V vs nil.\n\nCompute test_reverse reverse_v1.\n(*\n     = true\n     : bool\n*)\n\nLemma fold_unfold_reverse_v1_aux_nil :\n  forall (V : Type)\n         (a : list V),\n    reverse_v1_aux V nil a =\n    a.\nProof.\n  fold_unfold_tactic reverse_v1_aux.\nQed.\n\nLemma fold_unfold_reverse_v1_aux_cons :\n  forall (V : Type)\n         (v : V)\n         (vs' a : list V),\n    reverse_v1_aux V (v :: vs') a =\n    reverse_v1_aux V vs' (v :: a).\nProof.\n  fold_unfold_tactic reverse_v1_aux.\nQed.\n\n(*\n   i. Revisit the propositions above (involution, preservation of length, commutation with append)\n      and prove whether reverse_v1 satisfies them.\n      Two proof strategies are possible:\n      (1) direct, stand-alone proofs with Eureka lemmas, and\n      (2) proofs that hinge on the equivalence of reverse_v1 and reverse_v0.\n      This subtask is optional.\n *)\n\n(* Proof by induction *)\nLemma about_reverse_v1_aux :\n  forall (V : Type)\n         (vs a: list V),\n    reverse_v1_aux V vs a = append_v0 V (reverse_v1_aux V vs nil) a.\nProof.\n  intro V.\n  induction vs as [ | v vs' IHvs'].\n  - intro a.\n    rewrite -> (fold_unfold_reverse_v1_aux_nil V a).\n    rewrite -> (fold_unfold_reverse_v1_aux_nil V nil).\n    rewrite -> (fold_unfold_append_v0_nil V a).\n    reflexivity.\n  - intro a.\n    rewrite -> (fold_unfold_reverse_v1_aux_cons V v vs' a).\n    rewrite -> (IHvs' (v :: a)).\n    rewrite -> (fold_unfold_reverse_v1_aux_cons V v vs' nil).\n    rewrite -> (IHvs' (v :: nil)).\n    (* try to get the same number of append_v0 on each side of the goal, so that we can compare them *)\n    rewrite <- (nil_is_neutral_on_append_v0_left V a) at 1.\n    rewrite <- (fold_unfold_append_v0_cons V v nil a).\n    exact (append_v0_is_associative V (reverse_v1_aux V vs' nil) (v :: nil) a).\nQed.\n\n(* This proof requires light of inductil *)\n\nLemma reverse_v0_and_reverse_v1_are_equivalent :\n  forall (V : Type)\n         (vs : list V),\n    reverse_v0 V vs = reverse_v1 V vs.\nProof.\n  intros V vs.\n  unfold reverse_v1.\n  induction vs as [ | v vs' IHvs'].\n  - rewrite -> (fold_unfold_reverse_v1_aux_nil).\n    exact (fold_unfold_reverse_v0_nil V).\n  - rewrite -> (fold_unfold_reverse_v0_cons V v vs').\n    rewrite -> (fold_unfold_reverse_v1_aux_cons V v vs' nil).\n    rewrite -> IHvs'.\n    symmetry.\n    exact (about_reverse_v1_aux V vs' (v :: nil)).\nQed.\n\n(* NOTE\nA  methodical way of determining this eureka lemma, because in FPP we prove:\n\n   Proposition reverse_v1_aux_is_involutory:\n        forall (V: Type)\n               (vs : list V),\n          reverse_v1_aux V (reverse_v1_aux V vs nil) nil = vs.\n      Proof.\n        intros V [ | v vs'].\n        - admit.\n        - rewrite -> (fold_unfold_reverse_v1_aux_cons V v vs' nil).\n          (* reverse_v1_aux V (reverse_v1_aux V vs' (v :: nil)) nil = v :: vs' *)\n          destruct vs' as [ | v' vs''].\n          -- admit.\n          -- rewrite -> (fold_unfold_reverse_v1_aux_cons V v' vs'' (v :: nil)).\n             (* reverse_v1_aux V (reverse_v1_aux V vs'' (v' :: v :: nil)) nil =\n        v :: v' :: vs'' *)\n             destruct vs'' as [ | v'' vs'''].\n             --- admit.\n             --- rewrite -> (fold_unfold_reverse_v1_aux_cons V v'' vs''' (v' :: v :: nil)).\n                 (* reverse_v1_aux V (reverse_v1_aux V vs''' (v'' :: v' :: v :: nil)) nil =\n        v :: v' :: v'' :: vs''' *)\n\nTherefore, the eureka lemma is:\n\nreverse_v1_aux V (reverse_v1_aux V vs a) nil =\nappend_v0 V (reverse_v1_aux V a nil) vs\n *)\n\n(* involution *)\n\n(* (1) direct, stand-alone proofs with Eureka lemmas *)\n\nLemma about_reverse_v1_aux_and_involution_direct:\n  forall (V : Type)\n         (vs ws : list V),\n    reverse_v1_aux V (reverse_v1_aux V vs ws) nil =\n    reverse_v1_aux V ws vs.\nProof.\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - intro ws.\n    rewrite -> (fold_unfold_reverse_v1_aux_nil V ws).\n     reflexivity.\n   - intro ws.\n     rewrite -> (fold_unfold_reverse_v1_aux_cons V v vs' ws).\n     Check (IHvs' (v :: ws)).\n     rewrite -> (IHvs' (v :: ws)).\n     exact (fold_unfold_reverse_v1_aux_cons V v ws vs').\nQed.\n\nProposition reverse_v1_is_involutory_direct :\n  forall (V : Type)\n         (vs : list V),\n    reverse_v1 V (reverse_v1 V vs) = vs.\nProof.\n   intros V vs.\n   unfold reverse_v1.\n   Check (about_reverse_v1_aux_and_involution_direct V vs nil).\n   rewrite -> (about_reverse_v1_aux_and_involution_direct V vs nil).\n   exact (fold_unfold_reverse_v1_aux_nil V vs).\nQed.\n\n(* (2) proofs that hinge on the equivalence of reverse_v1 and reverse_v0. *)\nProposition reverse_v1_is_involutory_equivalence :\n  forall (V : Type)\n         (vs : list V),\n    reverse_v1 V (reverse_v1 V vs) = vs.\nProof.\n  intros V vs.\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent V vs).\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent V (reverse_v0 V vs)).\n  exact (reverse_v0_is_involutory V vs).\nQed.\n        \n(* preservation of length *)\n\n(* (1) direct, stand-alone proofs with Eureka lemmas *)\nLemma about_reverse_v1_aux_and_length_direct :\n  forall (V : Type)\n         (vs ws : list V)\n         (n1 n2 : nat),\n    length_v0 V vs = n1 ->\n    length_v0 V ws = n2 ->\n    length_v0 V (reverse_v1_aux V vs ws) = n1 + n2.\nProof.\n  intro V.\n  induction vs as [ | v vs' IHvs'].\n  - intros ws n1 n2 H_length_vs H_length_ws.\n    rewrite -> (fold_unfold_reverse_v1_aux_nil V ws).\n    rewrite -> (fold_unfold_length_v0_nil V) in H_length_vs.\n    rewrite <- H_length_vs.\n    rewrite -> (Nat.add_0_l n2).\n    exact (H_length_ws).\n  - intros ws [ | n1'] n2 H_length_vs H_length_ws.\n    -- discriminate.\n    -- rewrite -> (fold_unfold_reverse_v1_aux_cons V v vs' ws).\n       Search (_ = _ -> S _ = S _) .\n       apply (eq_S (length_v0 V ws) n2) in H_length_ws.\n       rewrite <- (fold_unfold_length_v0_cons V v ws) in H_length_ws.\n       rewrite -> (fold_unfold_length_v0_cons V v vs') in H_length_vs.\n       injection H_length_vs as H_length_vs.\n       rewrite -> (IHvs' (v :: ws) n1' (S n2) H_length_vs H_length_ws).\n       symmetry.\n       exact (Nat.add_succ_comm n1' n2).\nQed.\n\n(* this proof requires light of inductil *)\n\nProposition reverse_v1_preserves_length_direct :\n  forall (V : Type)\n         (vs : list V)\n         (n : nat),\n    length_v0 V vs = n ->\n    length_v0 V (reverse_v1 V vs) = n.\nProof.\n  unfold reverse_v1.\n  intros V vs n H_length.\n  rewrite <- (Nat.add_0_r n).\n  exact (about_reverse_v1_aux_and_length_direct V vs nil n 0 H_length (fold_unfold_length_v0_nil V)).\nQed.\n\nLemma about_reverse_v1_aux_and_length_alt_direct :\n  forall (V : Type)\n         (vs a: list V),\n    length_v0 V (reverse_v1_aux V vs a) = length_v0 V vs + length_v0 V a.\nProof.\n  intros V vs.\n  induction vs as [ | v vs' IHvs'].\n  - intro a.\n    rewrite -> (fold_unfold_reverse_v1_aux_nil V a).\n    rewrite -> (fold_unfold_length_v0_nil V).\n    rewrite -> (Nat.add_0_l (length_v0 V a)).\n    reflexivity.\n  - intro a.\n    rewrite -> (fold_unfold_reverse_v1_aux_cons V v vs' a).\n    rewrite -> (IHvs' (v :: a)).\n    rewrite -> (fold_unfold_length_v0_cons V v a).\n    rewrite -> (fold_unfold_length_v0_cons V v vs').\n    symmetry.\n    exact (Nat.add_succ_comm (length_v0 V vs') (length_v0 V a)).\nQed.\n\n(* this proof requires light of inductil *)\n\nProposition reverse_v1_preserves_length_alt_direct :\n  forall (V : Type)\n         (vs : list V),\n    length_v0 V (reverse_v1 V vs) = length_v0 V vs.\nProof.\n  intros V vs.\n  unfold reverse_v1.\n  rewrite -> (about_reverse_v1_aux_and_length_alt_direct V vs nil).\n  rewrite -> (fold_unfold_length_v0_nil V).\n  exact (Nat.add_0_r (length_v0 V vs)).\nQed.\n\n(* (2) proofs that hinge on the equivalence of reverse_v1 and reverse_v0. *)\nProposition reverse_v1_preserves_length_equivalence :\n  forall (V : Type)\n         (vs : list V)\n         (n : nat),\n    length_v0 V vs = n ->\n    length_v0 V (reverse_v1 V vs) = n.\nProof.\n  intros V vs n H_length_vs.\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent V vs).\n  Check (reverse_v0_preserves_length V vs n H_length_vs).\n  exact (reverse_v0_preserves_length V vs n H_length_vs).\nQed.\n\nProposition reverse_v1_preserves_length_alt_equivalence :\n  forall (V : Type)\n         (vs : list V),\n    length_v0 V (reverse_v1 V vs) = length_v0 V vs.\nProof.\n  intros V vs.\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent V vs).\n  Check (reverse_v0_preserves_length_alt V vs).\n  exact (reverse_v0_preserves_length_alt V vs).\nQed.\n\n(* reverse_v1_preserves_length as a corollary of reverse_v1_preserves_length_alt *)\n\nCorollary reverse_v1_preserves_length' :\n  forall (V : Type)\n         (vs : list V)\n         (n : nat),\n    length_v0 V vs = n ->\n    length_v0 V (reverse_v1 V vs) = n.\nProof.\n  intros V vs n H_length.\n  rewrite -> (reverse_v1_preserves_length_alt_direct V vs).\n  exact (H_length).\nQed.\n\n(* reverse_v1_preserves_length_alt as a corollary of reverse_v0_preserves_length *)\n\nCorollary reverse_v1_preserves_length_alt' :\n  forall (V : Type)\n         (vs : list V),\n    length_v0 V (reverse_v1 V vs) = length_v0 V vs.\nProof.\n  intros V vs.\n  apply (reverse_v1_preserves_length_direct V vs (length_v0 V vs)).\n  reflexivity.\nQed.\n\n(* commutation of append and reverse *)\n\n(* (1) direct, stand-alone proofs with Eureka lemmas *)\nLemma about_commutation_of_append_and_reverse_v1_aux_direct :\n  forall (V : Type)\n         (v1s v2s a : list V),\n    reverse_v1_aux V (append_v0 V v1s v2s) a  = append_v0 V (reverse_v1_aux V v2s nil) (reverse_v1_aux V v1s a).\nProof.\n  intro V.\n  induction v1s as [ | v1 v1s' IHv1s'].\n  - intros v2s a.\n    rewrite -> (fold_unfold_append_v0_nil V v2s).\n    rewrite -> (fold_unfold_reverse_v1_aux_nil V).\n    exact (about_reverse_v1_aux V v2s a).\n  - intros v2s a.\n    rewrite -> (fold_unfold_append_v0_cons V v1 v1s' v2s).\n    rewrite -> (fold_unfold_reverse_v1_aux_cons V v1 (append_v0 V v1s' v2s) a).\n    rewrite -> (IHv1s' v2s (v1 :: a)).\n    rewrite -> (fold_unfold_reverse_v1_aux_cons V v1 v1s' a).\n    reflexivity.\nQed.\n\n(* this proof requires light of inductil *)\n\nProposition append_and_reverse_v1_commute_with_each_other_direct :\n  forall (V : Type)\n         (v1s v2s : list V),\n    reverse_v1 V (append_v0 V v1s v2s) = append_v0 V (reverse_v1 V v2s) (reverse_v1 V v1s).\nProof.\n  intros V v1s v2s.\n  unfold reverse_v1.\n  exact (about_commutation_of_append_and_reverse_v1_aux_direct V v1s v2s nil).\nQed.\n\n(* (2) proofs that hinge on the equivalence of reverse_v1 and reverse_v0. *)\nProposition append_and_reverse_v1_commute_with_each_other_equivalence :\n  forall (V : Type)\n         (v1s v2s : list V),\n    reverse_v1 V (append_v0 V v1s v2s) = append_v0 V (reverse_v1 V v2s) (reverse_v1 V v1s).\nProof.\n  intros V v1s v2s.\n  Check (reverse_v0_and_reverse_v1_are_equivalent V (append_v0 V v1s v2s)).\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent V (append_v0 V v1s v2s)).\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent V v1s).\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent V v2s).\n  Check (append_and_reverse_v0_commute_with_each_other V v1s v2s).\n  exact (append_and_reverse_v0_commute_with_each_other V v1s v2s).\nQed.\n\n(* ********** *)\n\n(* A study of the polymorphic map function: *)\n\nDefinition specification_of_map (map : forall V W : Type, (V -> W) -> list V -> list W) :=\n  (forall (V W : Type)\n          (f : V -> W),\n      map V W f nil = nil)\n  /\\\n  (forall (V W : Type)\n          (f : V -> W)\n          (v : V)\n          (vs' : list V),\n      map V W f (v :: vs') = f v :: map V W f vs').\n\n(* Task 7:\n\n   a. Prove whether the specification specifies at most one map function.\n*)\n\nProposition there_is_at_most_one_map_function :\n  forall map1 map2 : forall V W : Type, (V -> W) -> list V -> list W,\n      specification_of_map map1 ->\n      specification_of_map map2 ->\n      forall (V W : Type)\n             (f : V -> W)\n             (vs : list V),\n        map1 V W f vs = map2 V W f vs.\nProof.\n  intros map1 map2 S_map1 S_map2 V W f vs.\n  induction vs as [ | v vs' IHvs'].\n  - unfold specification_of_map in S_map1.\n    destruct S_map1 as [fold_unfold_map1_nil _].\n    destruct S_map2 as [fold_unfold_map2_nil _].\n    rewrite -> (fold_unfold_map2_nil V W f).\n    exact (fold_unfold_map1_nil V W f).\n  - unfold specification_of_map in S_map1.\n    destruct S_map1 as [_ fold_unfold_map1_cons].\n    destruct S_map2 as [_ fold_unfold_map2_cons].\n    rewrite -> (fold_unfold_map1_cons V W f v vs').\n    rewrite -> (fold_unfold_map2_cons V W f v vs').\n    rewrite -> IHvs'.\n    reflexivity.\nQed.\n\n(*\n   b. Implement the map function in direct style.\n*)\n\nFixpoint map_v0 (V W : Type) (f : V -> W) (vs : list V) : list W :=\n  match vs with\n  | nil =>\n    nil\n  | v :: vs' =>\n    f v :: map_v0 V W f vs'\n  end.\n\n(*\n   c. State the associated fold-unfold lemmas.\n*)\n\nLemma fold_unfold_map_v0_nil :\n  forall (V W : Type)\n         (f : V -> W),\n    map_v0 V W f nil =\n    nil.\nProof.\n  fold_unfold_tactic map_v0.\nQed.\n\nLemma fold_unfold_map_v0_cons :\n  forall (V W : Type)\n         (f : V -> W)\n         (v : V)\n         (vs' : list V),\n    map_v0 V W f (v :: vs') =\n    f v :: map_v0 V W f vs'.\nProof.\n  fold_unfold_tactic map_v0.\nQed.\n\n(*\n   d. Prove whether your implementation satisfies the specification.\n*)\n\nProposition map_v0_satisfies_the_specification_of_map :\n  specification_of_map map_v0.\nProof.\n  unfold specification_of_map.\n  split.\n  - exact fold_unfold_map_v0_nil.\n  - exact fold_unfold_map_v0_cons.\nQed.\n\n(*\n   e. Implement the copy function using map_v0.\n*)\n\nDefinition copy_v2 (V : Type) (vs : list V) : list V :=\n  map_v0 V V (fun x : V  =>  x) vs.\n\nCompute test_copy copy_v2.\n(* \n     = true\n     : bool\n*)\n\n\n(*\nHint: Does copy_v2 satisfy the specification of copy?\n*)\n\nTheorem copy_2_satisfies_the_specification_of_copy :\n  specification_of_copy copy_v2.\nProof.\n  unfold specification_of_copy, copy_v2.\n  split.\n  - intro V.\n    exact (fold_unfold_map_v0_nil V V (fun x : V => x)).\n  - intros V v vs'.\n    exact (fold_unfold_map_v0_cons V V (fun x : V => x) v vs').\nQed.\n\n(*\n   f. Prove whether mapping a function over a list preserves the length of this list.\n *)\n\nProposition map_preserves_length :\n  forall (V W : Type)\n         (f : V -> W)\n         (vs : list V)\n         (n : nat),\n    length_v0 V vs = n ->\n    length_v0 W (map_v0 V W f vs) = n.\nProof.\n  intros V W f.\n  induction vs as [ | v vs' IHvs'].\n  - intros n H_length.\n    rewrite -> (fold_unfold_map_v0_nil V W f).\n    exact H_length.\n  - intros [ | n'] H_length.\n    -- discriminate H_length.\n    -- rewrite -> (fold_unfold_map_v0_cons V W f v vs').\n       rewrite -> (fold_unfold_length_v0_cons W (f v) (map_v0 V W f vs')).\n       Check (IHvs' n'). (*  length_v0 V vs' = n' -> length_v0 W (map_v0 V W f vs') = n' *)\n       rewrite -> (fold_unfold_length_v0_cons V v vs') in H_length.\n       injection H_length as H_length.\n       rewrite -> (IHvs' n' H_length).\n       reflexivity.\nQed.\n\n(* this proof requires light of inductil *)\n\nProposition map_preserves_length_alt :\n  forall (V W : Type)\n         (f : V -> W)\n         (vs : list V),\n    length_v0 W (map_v0 V W f vs) = length_v0 V vs.\nProof.\n  intros V W f.\n  induction vs as [ | v vs' IHvs'].\n  - rewrite -> (fold_unfold_map_v0_nil V W f).\n    reflexivity.\n  - rewrite -> (fold_unfold_map_v0_cons V W f v vs').\n    rewrite -> (fold_unfold_length_v0_cons W (f v) (map_v0 V W f vs')).\n    rewrite -> (IHvs').\n    rewrite -> (fold_unfold_length_v0_cons V v vs').\n    reflexivity.\nQed.\n\n(* this proof does not require light of inductil *)\n\n(*\n   g. Do map_v0 and append_v0 commute with each other and if so how?\n *)\n\nProposition append_v0_and_map_v0_commute_with_each_other :\n  forall (V W : Type)\n         (f : V -> W)\n         (v1s v2s: list V),\n    map_v0 V W f (append_v0 V v1s v2s) = append_v0 W (map_v0 V W f v1s) (map_v0 V W f v2s).\nProof.\n  intros V W f v1s v2s.\n  induction v1s as [ | v1' v1s' IHv1s'].\n  - rewrite -> (fold_unfold_append_v0_nil V v2s).\n    rewrite -> (fold_unfold_map_v0_nil V W f).\n    rewrite -> (fold_unfold_append_v0_nil W (map_v0 V W f v2s)).\n    reflexivity.\n  - rewrite -> (fold_unfold_map_v0_cons V W f v1' v1s').\n    rewrite -> (fold_unfold_append_v0_cons W (f v1') (map_v0 V W f v1s') (map_v0 V W f v2s)).\n    rewrite <- (IHv1s').\n    rewrite -> (fold_unfold_append_v0_cons V v1' v1s' v2s).\n    exact (fold_unfold_map_v0_cons V W f v1' (append_v0 V v1s' v2s)).\nQed.\n\n(* this proof does not require light of inductil *)\n\n(*\n   h. Do map_v0 and reverse_v0 commute with each other and if so how?\n*)\n\nProposition map_v0_reverse_v0_commute_with_each_other :\n  forall (V W : Type)\n         (f : V -> W)\n         (vs: list V),\n    map_v0 V W f (reverse_v0 V vs) = reverse_v0 W (map_v0 V W f vs).\nProof.\n  intros V W f.\n  induction vs as [ | v vs' IHvs'].\n  - rewrite -> (fold_unfold_reverse_v0_nil V).\n    rewrite -> (fold_unfold_map_v0_nil V W f).\n    rewrite -> (fold_unfold_reverse_v0_nil W).\n    reflexivity.\n  - rewrite -> (fold_unfold_map_v0_cons V W f v vs').\n    rewrite -> (fold_unfold_reverse_v0_cons W (f v) (map_v0 V W f vs')).\n    rewrite <- IHvs' .\n    rewrite -> (fold_unfold_reverse_v0_cons V v vs').\n    rewrite <- (fold_unfold_map_v0_nil V W f).\n    rewrite <- (fold_unfold_map_v0_cons V W f v nil).\n    rewrite -> (append_v0_and_map_v0_commute_with_each_other V W f (reverse_v0 V vs') (v :: nil)).\n    reflexivity.\nQed.\n\n(*\n   i. Do map_v0 and reverse_v1 commute with each other and if so how?\n      This subtask is optional.\n*)\n\n(* (1) direct, stand-alone proofs with Eureka lemmas *)\n(* we first write a more general Proposition about reverse_v1 so that the accumulator is also mapped *)\nProposition map_v0_reverse_v1_aux_commute_with_each_other_direct :\n  forall (V W : Type)\n         (f : V -> W)\n         (vs a : list V),\n    map_v0 V W f (reverse_v1_aux V vs a) = reverse_v1_aux W (map_v0 V W f vs) (map_v0 V W f a).\nProof.\n  intros V W f vs.\n  induction vs as [ | v vs' IHvs'].\n  - intro a.\n    rewrite -> (fold_unfold_reverse_v1_aux_nil V a).\n    rewrite -> (fold_unfold_map_v0_nil V W f).\n    rewrite -> (fold_unfold_reverse_v1_aux_nil W (map_v0 V W f a)).\n    reflexivity.\n  - intro a.\n    rewrite -> (fold_unfold_reverse_v1_aux_cons V v vs' a).\n    rewrite -> (fold_unfold_map_v0_cons V W f v vs').\n    rewrite -> (IHvs' (v :: a)).\n    rewrite -> (fold_unfold_reverse_v1_aux_cons W (f v) (map_v0 V W f vs') (map_v0 V W f a)).\n    rewrite -> (fold_unfold_map_v0_cons V W f v a).\n    reflexivity.\nQed.\n\n(* this proof requires light of inductil *)\n\nProposition map_v0_reverse_v1_commute_with_each_other_direct :\n  forall (V W : Type)\n         (f : V -> W)\n         (vs : list V),\n    map_v0 V W f (reverse_v1 V vs) = reverse_v1 W (map_v0 V W f vs).\nProof.\n  intros V W f vs.\n  unfold reverse_v1.\n  Check (map_v0_reverse_v1_aux_commute_with_each_other_direct V W f vs nil).\n  rewrite -> (map_v0_reverse_v1_aux_commute_with_each_other_direct V W f vs nil).\n  rewrite -> (fold_unfold_map_v0_nil V W f).\n  reflexivity.\nQed.\n\n(* (2) proofs that hinge on the equivalence of reverse_v1 and reverse_v0. *)\nProposition map_v0_reverse_v1_commute_with_each_other_equivalence :\n  forall (V W : Type)\n         (f : V -> W)\n         (vs : list V),\n    map_v0 V W f (reverse_v1 V vs) = reverse_v1 W (map_v0 V W f vs).\nProof.\n  intros V W f vs.\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent V vs).\n  rewrite <- (reverse_v0_and_reverse_v1_are_equivalent W (map_v0 V W f vs)).\n  exact (map_v0_reverse_v0_commute_with_each_other V W f vs).\nQed.\n\n(*\n   j. Define a unit-test function for the map function\n      and verify that your implementation satisfies it.\n *)\n\n\nDefinition test_map (candidate : forall V W : Type, (V -> W) -> list V -> list W) : bool :=\n  (eqb_list nat beq_nat (candidate nat nat (fun n => n + 1) (2 :: 1 :: nil)) (3 :: 2 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat nat (fun n => n + n) (2 :: 1 :: nil)) (4 :: 2 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat nat (fun n => n - 1) (4 :: 3 :: 2 :: 1 :: nil)) (3 :: 2 :: 1 :: 0 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat nat (fun n => n - 2) (4 :: 3 :: 2 :: nil)) (2 :: 1 :: 0 :: nil) ) &&\n  (eqb_list nat beq_nat (candidate nat nat (fun n => n + n + n) (2 ::  nil)) (6 ::  nil)) &&\n  (eqb_list nat beq_nat (candidate nat nat (fun n => n) (2 ::  nil)) (2 ::  nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat nat (fun x : nat => x) nil) nil) &&\n  (eqb_list nat Nat.eqb (candidate nat nat (fun x : nat => x) (2 :: 1 :: 0 :: nil)) (2 :: 1 :: 0 :: nil)) &&\n  (eqb_list nat Nat.eqb (candidate nat nat (fun x : nat => 2 * x) (2 :: 1 :: 0 :: nil)) (4 :: 2 :: 0 :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool bool (fun x : bool => x) nil) nil) &&\n  (eqb_list bool Bool.eqb (candidate bool bool (fun x : bool => x) (true :: false :: nil)) (true :: false :: nil)) &&\n  (eqb_list bool Bool.eqb (candidate bool bool (fun x : bool =>\n                                                  match x with\n                                                  | true => false\n                                                  | false => true\n                                                  end) (true :: false :: nil)) (false :: true :: nil)).\n\n\nCompute test_map map_v0.\n(* \n     = true\n     : bool\n*)\n\n(* ********** *)\n\n(* A study of the polymorphic fold-right and fold-left functions: *)\n\nDefinition specification_of_list_fold_right (list_fold_right : forall V W : Type, W -> (V -> W -> W) -> list V -> W) :=\n  (forall (V W : Type)\n          (nil_case : W)\n          (cons_case : V -> W -> W),\n     list_fold_right V W nil_case cons_case nil =\n     nil_case)\n  /\\\n  (forall (V W : Type)\n          (nil_case : W)\n          (cons_case : V -> W -> W)\n          (v : V)\n          (vs' : list V),\n     list_fold_right V W nil_case cons_case (v :: vs') =\n     cons_case v (list_fold_right V W nil_case cons_case vs')).\n\nDefinition specification_of_list_fold_left (list_fold_left : forall V W : Type, W -> (V -> W -> W) -> list V -> W) :=\n  (forall (V W : Type)\n          (nil_case : W)\n          (cons_case : V -> W -> W),\n     list_fold_left V W nil_case cons_case nil =\n     nil_case)\n  /\\\n  (forall (V W : Type)\n          (nil_case : W)\n          (cons_case : V -> W -> W)\n          (v : V)\n          (vs' : list V),\n     list_fold_left V W nil_case cons_case (v :: vs') =\n     list_fold_left V W (cons_case v nil_case) cons_case vs').\n\n(* Task 8:\n\n   a. Implement the fold-right function in direct style.\n*)\n\nFixpoint list_fold_right (V W : Type) (nil_case : W) (cons_case : V -> W -> W) (vs : list V) : W :=\n  match vs with\n  | nil =>\n    nil_case\n  | v :: vs' =>\n    cons_case v (list_fold_right V W nil_case cons_case vs')\n  end.\n\n(*\n   b. Implement the fold-left function in direct style.\n*)\n\nFixpoint list_fold_left (V W : Type) (nil_case : W) (cons_case : V -> W -> W) (vs : list V) : W :=\n  match vs with\n  | nil =>\n    nil_case\n  | v :: vs' =>\n    list_fold_left V W (cons_case v nil_case) cons_case vs'\n  end.\n\n(*\n   c. state the fold-unfold lemmas associated to list_fold_right and to list_fold_left\n*)\n\nLemma fold_unfold_list_fold_right_nil :\n  forall (V W : Type)\n         (nil_case : W)\n         (cons_case : V -> W -> W),\n    list_fold_right V W nil_case cons_case nil =\n    nil_case.\nProof.\n  fold_unfold_tactic list_fold_right.\nQed.\n\nLemma fold_unfold_list_fold_right_cons :\n  forall (V W : Type)\n         (nil_case : W)\n         (cons_case : V -> W -> W)\n         (v : V)\n         (vs' : list V),\n    list_fold_right V W nil_case cons_case (v :: vs') =\n    cons_case v (list_fold_right V W nil_case cons_case vs').\nProof.\n  fold_unfold_tactic list_fold_right.\nQed.\n\nLemma fold_unfold_list_fold_left_nil :\n  forall (V W : Type)\n         (nil_case : W)\n         (cons_case : V -> W -> W),\n    list_fold_left V W nil_case cons_case nil =\n    nil_case.\nProof.\n  fold_unfold_tactic list_fold_left.\nQed.\n\nLemma fold_unfold_list_fold_left_cons :\n  forall (V W : Type)\n         (nil_case : W)\n         (cons_case : V -> W -> W)\n         (v : V)\n         (vs' : list V),\n    list_fold_left V W nil_case cons_case (v :: vs') =\n    list_fold_left V W (cons_case v nil_case) cons_case vs'.\nProof.\n  fold_unfold_tactic list_fold_left.\nQed.\n\n(*\n   d. Prove that each of your implementations satisfies the corresponding specification.\n*)\n\nTheorem list_fold_right_satisfies_specification_of_list_fold_right :\n  specification_of_list_fold_right list_fold_right.\n\nProof.\n  unfold specification_of_list_fold_right.\n  split.\n  - exact (fold_unfold_list_fold_right_nil).\n  - exact (fold_unfold_list_fold_right_cons).\nQed.\n\nTheorem list_fold_left_satisfies_specification_of_list_fold_left :\n  specification_of_list_fold_left list_fold_left.\n\nProof.\n  unfold specification_of_list_fold_left.\n  split.\n  - exact (fold_unfold_list_fold_left_nil).\n  - exact (fold_unfold_list_fold_left_cons).\nQed.\n\n(*\n   e. Which function do foo and bar (defined just below) compute?\n*)\n\n\nDefinition foo (V : Type) (vs : list V) :=\n  list_fold_right V (list V) nil (fun v vs => v :: vs) vs.\n\nCompute foo nat (1 :: 2 :: 3 :: nil).\n(*\n     = 1 :: 2 :: 3 :: nil\n     : list nat\n *)\n\nProposition foo_satisfies_specification_of_copy :\n  specification_of_copy foo.\nProof.\n  unfold specification_of_copy, foo.\n  split.\n  - intro V.\n    Check (fold_unfold_list_fold_right_nil V (list V) nil (fun (v : V) (vs : list V) => v :: vs)).\n    exact (fold_unfold_list_fold_right_nil V (list V) nil (fun (v : V) (vs : list V) => v :: vs)).\n  - intros V v vs'.\n    Check (fold_unfold_list_fold_right_cons V (list V) nil (fun (v0 : V) (vs : list V) => v0 :: vs) v vs').\n    exact (fold_unfold_list_fold_right_cons V (list V) nil (fun (v0 : V) (vs : list V) => v0 :: vs) v vs').\nQed.\n\n(* foo is the identity/copy function for lists *)\n\nDefinition bar (V : Type) (vs : list V) :=\n  list_fold_left V (list V) nil (fun v vs => v :: vs) vs.\n\nCompute bar nat (1 :: 2 :: 3 :: nil).\n(*\n     = 3 :: 2 :: 1 :: nil\n     : list nat\n *)\n\n(*\nLemma bar_satisfies_specification_of_reverse_aux :\n  forall append: forall V : Type, list V -> list V -> list V,\n    specification_of_append append ->\n    forall (V : Type)\n           (cons_case : V -> list V -> list V)\n           (vs : list V),\n      append V (list_fold_left V (list V) nil cons_case vs') vs = list_fold_left V (list V) vs cons_case vs'.\n      \n *)\n\n (*Lemma about_bar : *)\n  \n\n\nProposition bar_satisfies_specification_of_reverse :\n  specification_of_reverse bar.\nProof.\n  unfold specification_of_reverse, bar.\n  intros append spec_append.\n  split.\n  - intros V.\n    Check (fold_unfold_list_fold_left_nil V (list V) nil (fun (v : V) (vs : list V) => v :: vs)).\n    exact (fold_unfold_list_fold_left_nil V (list V) nil (fun (v : V) (vs : list V) => v :: vs)).\n  - intros V v vs'.\n    Check (fold_unfold_list_fold_left_cons V (list V) nil (fun (v0 : V) (vs : list V) => v0 :: vs) v vs').\n    rewrite -> (fold_unfold_list_fold_left_cons V (list V) nil (fun (v0 : V) (vs : list V) => v0 :: vs) v vs').\n    destruct spec_append as [a_0 a_1].\n    revert v.\n    Check fold_unfold_list_fold_left_cons  V (list V) nil (fun (v0 : V) (vs : list V) => v0 :: vs).\n    induction vs' as [ | v' vs'' IHvs'].\n    -- intro v.\n       rewrite -> (fold_unfold_list_fold_left_nil V (list V) (v :: nil)              (fun (v0 : V) (vs : list V) => v0 :: vs)).\n       rewrite -> (fold_unfold_list_fold_left_nil V (list V) (nil)              (fun (v0 : V) (vs : list V) => v0 :: vs)).\n       rewrite -> (a_0 V (v :: nil)).\n       reflexivity.\n    -- rewrite -> (fold_unfold_list_fold_left_cons V (list V) nil (fun (v0 : V) (vs : list V) => v0 :: vs) v' vs'').    \nAdmitted.\n\n(*\n  append : forall W : Type, list W -> list W -> list W\n  H : forall (V : Type) (v2s : list V), append V nil v2s = v2s\n  H0 : forall (V : Type) (v1 : V) (v1s' v2s : list V),\n       append V (v1 :: v1s') v2s = v1 :: append V v1s' v2s\n  V : Type\n  v : V\n  vs' : list V\n  ============================\n  list_fold_left V (list V) (v :: nil)\n    (fun (v0 : V) (vs : list V) => v0 :: vs) vs' =\n  append V\n    (list_fold_left V (list V) nil (fun (v0 : V) (vs : list V) => v0 :: vs)\n       vs') (v :: nil)\n*)\n\n\n(* bar reverse function for lists *)\n\n\n(*\n   f. Implement the length function using either list_fold_right or list_fold_left, and justify your choice.\n*)\n\nDefinition length_v2 (V : Type) (vs : list V) : nat :=\n  list_fold_right V nat 0 (fun _ ih => S (ih)) vs.\n\nCompute test_length length_v2.\n\nDefinition length_v3 (V : Type) (vs : list V) : nat :=\n  list_fold_left V nat 0 (fun _ a => S a) vs.\n\nCompute test_length length_v3.\n\n(* both fold left and fold right work because reversing a list does not change its length,\n   as proved earlier *)\n\n(*\n   g. Implement the copy function using either list_fold_right or list_fold_left, and justify your choice.\n*)\n\nDefinition copy_v3 (V : Type) (vs : list V) : list V :=\n  list_fold_right V (list V) nil (fun v ih => v :: ih) vs.\n\nCompute test_copy copy_v3.\n\n(* list_fold_right is the better choice here,\n   because implementing copy using list_fold_left would be accomplished either by\n   applying list_fold_left to the given list using the same nil and cons case as in copy_v3,\n   and then reversing the result,\n   or, alternatively,\n   reversing the given list\n   and then applying list_fold_left to the result using the same nil and cons case as in copy_v3,\n   both of which are less efficient than simply using list_fold_right *)\n\n(*\n   h. Implement the append function using either list_fold_right or list_fold_left, and justify your choice.\n*)\n\nDefinition append_v1 (V : Type) (v1s v2s : list V) : list V :=\n  list_fold_right V (list V) v2s (fun v ih => v :: ih) v1s.\n\nCompute test_append append_v1.\n\n(* list_fold_right is a better choice,\n   because implementing append using list_fold_left would be accomplished either by\n   applying list_fold_left to the given list and then reversing the result,\n   or, alternatively,\n   reversing the given list\n   and then applying list_fold_left to the result, \n   both of which are less efficient than simply using list_fold_right *)\n\n(*\n   i. Implement the reverse function using either list_fold_right or list_fold_left, and justify your choice.\n*)\n\nDefinition reverse_v2 (V : Type) (vs : list V) : list V :=\n  list_fold_left V (list V) nil (fun v a => v :: a) vs.\n\nCompute test_reverse reverse_v2.\n\n(* list_fold_left is a better choice. *)\n   \n\n(*\n   j. Implement the map function using either list_fold_right or list_fold_left, and justify your choice.\n*)\n\nDefinition map_v2 (V W : Type) (f : V -> W) (vs : list V) : list W :=\n  list_fold_right V (list W) nil (fun v ih  => (f v) :: ih) vs.\n\nCompute test_map map_v2.\n\n(* list_fold_right is a better choice because we are returning a list of the same order as the initial list.\n   Using list_fold_left would require us to reverse the resulting list to get the mapped list. *)\n\n(*\n   k. Relate list_fold_right and list_fold_left using the reverse function.\n*)\n\nDefinition list_fold_right_v1 (V W : Type) (nil_case : W) (cons_case : V -> W -> W) (vs : list V) : W :=\n  list_fold_left V W nil_case cons_case (reverse_v0 V vs).\n\nDefinition list_fold_left_v1 (V W : Type) (nil_case : W) (cons_case : V -> W -> W) (vs : list V) : W :=\n  list_fold_right V W nil_case cons_case (reverse_v0 V vs).\n\n(*\n   l. Implement list_fold_right using list_fold_left, without using the reverse function.\n*)\n\nDefinition list_fold_right_v2 (V W : Type) (nil_case : W) (cons_case : V -> W -> W) (vs : list V) : W :=\n  list_fold_left V\n                 (W -> W)\n                 (fun a => a)\n                 (fun v ih => fun a => ih (cons_case v a))\n                 vs\n                 nil_case.\n\n(*\n   m. Implement list_fold_left using list_fold_right, without using the reverse function.\n*)\n\nDefinition list_fold_left_v2 (V W : Type) (nil_case : W) (cons_case : V -> W -> W) (vs : list V) : W :=\n    list_fold_right V\n                    (W -> W)\n                    (fun a => a)\n                    (fun v ih => fun a => ih (cons_case v a))\n                    vs\n                    nil_case.\n\n(* Testing list_fold_right/left_v1/v2 *)\n\nDefinition length_v4 (V : Type) (l : list V) :=\n  list_fold_right_v1 V nat 0 (fun _ a => S a) l.\n\nDefinition length_v5 (V : Type) (l : list V) :=\n  list_fold_right_v2 V nat 0 (fun _ a => S a) l.\n\nCompute test_length length_v4 && test_length length_v5.\n\nDefinition length_v6 (V : Type) (l : list V) :=\n  list_fold_left_v1 V nat 0 (fun _ a => S a) l.\n\nDefinition length_v7 (V : Type) (l : list V) :=\n  list_fold_left_v2 V nat 0 (fun _ a => S a) l.\n\nCompute test_length length_v6 && test_length length_v7.\n\n\nDefinition append_v4 (V : Type) (l1 l2 : list V) :=\n  list_fold_right_v1 V (list V) l2 (fun v ih => v :: ih) l1.\n\nDefinition append_v5 (V : Type) (l1 l2 : list V) :=\n  list_fold_right_v2 V (list V) l2 (fun v ih => v :: ih) l1.\n\nCompute test_append append_v4 && test_append append_v5.\n\nDefinition append_v6 (V : Type) (l1 l2 : list V) :=\n  list_fold_left_v1 V (list V) (l2) (fun v ih => v :: ih) (reverse_v1 V l1).\n\nDefinition append_v7 (V : Type) (l1 l2 : list V) :=\n  list_fold_left_v2 V (list V) (l2) (fun v ih => v :: ih) (reverse_v1 V l1).\n\nCompute test_append append_v6 && test_append append_v7.\n\n\nDefinition copy_v4 (V : Type) (l : list V) :=\n  list_fold_right_v1 V (list V) nil (fun v ih => v :: ih) l.\n\nDefinition copy_v5 (V : Type) (l : list V) :=\n  list_fold_right_v2 V (list V) nil (fun v ih => v :: ih) l.\n\nCompute test_copy copy_v4 && test_copy copy_v5.\n\nDefinition copy_v6 (V : Type) (l : list V) :=\n  list_fold_left_v1 V (list V) nil (fun v ih => v :: ih) (reverse_v1 V l).\n\nDefinition copy_v7 (V : Type) (l : list V) :=\n  list_fold_left_v2 V (list V) nil (fun v ih => v :: ih) (reverse_v1 V l).\n\nCompute test_copy copy_v6 && test_copy copy_v7.\n\nDefinition copy_v8 (V : Type) (l : list V) := append_v4 V l nil.\n\nDefinition copy_v9 (V : Type) (l : list V) := append_v6 V l nil.\n\nCompute test_copy copy_v8 && test_copy copy_v9.\n\n\nDefinition reverse_v4 (V : Type) (l : list V) :=\n  list_fold_right_v1 V (list V) nil (fun v ih => v :: ih) (reverse_v1 V l).\n\nDefinition reverse_v5 (V : Type) (l : list V) :=\n  list_fold_right_v2 V (list V) nil (fun v ih => v :: ih) (reverse_v1 V l).\n\nCompute test_reverse reverse_v4 && test_reverse reverse_v5.\n\nDefinition reverse_v6 (V : Type) (l : list V) :=\n  list_fold_left_v1 V (list V) nil (fun v ih => v :: ih) l.\n\nDefinition reverse_v7 (V : Type) (l : list V) :=\n  list_fold_left_v2 V (list V) nil (fun v ih => v :: ih) l.\n\nCompute test_reverse reverse_v6 && test_reverse reverse_v7.\n\n                                                \n\n(*\n   n. Show that\n      if the cons case is a function that is left permutative,\n      applying list_fold_left and applying list_fold_right\n      to a nil case, this cons case, and a list\n      give the same result\n*)\n  \nDefinition is_left_permutative (V W : Type) (op2 : V -> W -> W) :=\n  forall (v1 v2 : V)\n         (v3 : W),\n    op2 v1 (op2 v2 v3) = op2 v2 (op2 v1 v3).\n\nLemma about_list_fold_left :\n  forall (V W : Type)\n         (nil_case : W)\n         (cons_case : V -> W -> W)\n         (v : V)\n         (vs' : list V),\n    is_left_permutative V W cons_case ->\n    list_fold_left V W (cons_case v nil_case) cons_case vs' =\n    cons_case v (list_fold_left V W nil_case cons_case vs').\n\nProof.\n  intros V W nil_case cons_case v vs' H_cons_is_left_permutative.\n  revert nil_case.\n  induction vs' as [ | v' vs'' IHvs''].\n  - intro nil_case.\n    rewrite -> (fold_unfold_list_fold_left_nil V W (cons_case v nil_case) cons_case).\n    rewrite -> (fold_unfold_list_fold_left_nil V W nil_case cons_case).\n    reflexivity.\n  - intro nil_case.\n    rewrite -> (fold_unfold_list_fold_left_cons V W (cons_case v nil_case) cons_case v' vs'').\n    rewrite -> (H_cons_is_left_permutative v' v nil_case).\n    rewrite -> (fold_unfold_list_fold_left_cons V W nil_case cons_case v' vs'').\n    rewrite -> (IHvs'' (cons_case v' nil_case)).\n    reflexivity.\nQed.\n\nTheorem the_grand_finale :\n  forall (V W : Type)\n         (cons_case : V -> W -> W),\n    is_left_permutative V W cons_case ->\n    forall (nil_case : W)\n           (vs : list V),\n      list_fold_left  V W nil_case cons_case vs =\n      list_fold_right V W nil_case cons_case vs.\nProof.\n  intros V W cons_case H_cons_case_is_left_permutative nil_case.\n  induction vs as [ | v' vs' IHvs'].\n  - rewrite -> (fold_unfold_list_fold_left_nil V W nil_case cons_case).\n    exact (fold_unfold_list_fold_right_nil V W nil_case cons_case).\n  - rewrite -> (fold_unfold_list_fold_left_cons V W nil_case cons_case v' vs'). \n    rewrite -> (fold_unfold_list_fold_right_cons V W nil_case cons_case v' vs').\n    rewrite -> (about_list_fold_left V W nil_case cons_case v' vs' H_cons_case_is_left_permutative).\n    rewrite -> (IHvs').\n    reflexivity.\nQed.\n\n(*\n   o. Can you think of corollaries of this property?\n*)\n\n\nLemma length_cons_case_is_left_permutative :\n  forall (V : Type),\n    is_left_permutative (V : Type) nat (fun (_ : V) (a : nat) => S a).\nProof.\n  intro V.\n  unfold is_left_permutative.\n  intros e1 e2 n.\n  reflexivity.\nQed.\n\nCorollary length_is_equivalent_if_constructed_with_fold_left_or_fold_right :\n  forall (V : Type) (vs : list V),\n    length_v3 V vs = length_v2 V vs.\nProof.\n  intro V.\n  unfold length_v2, length_v3.\n  Check (the_grand_finale V nat (fun (_ : V) (ih : nat) => S ih)\n                          (length_cons_case_is_left_permutative V) 0).\n  apply (the_grand_finale V nat (fun (_ : V) (ih : nat) => S ih)\n                          (length_cons_case_is_left_permutative V) 0).\nQed.\n\n(*\n   o. Can you think of corollaries of this property?\n*)\n\nLemma plus_is_left_permutative :\n  is_left_permutative nat nat plus.\nProof.\n  unfold is_left_permutative.\n  intros v1 v2 v3.\n  rewrite -> (Nat.add_assoc v1 v2 v3).\n  rewrite -> (Nat.add_comm v1 v2).\n  rewrite <- (Nat.add_assoc v2 v1 v3).\n  reflexivity.\nQed.\n\nCorollary example_for_plus :\n  forall ns : list nat,\n    list_fold_left nat nat 0 plus ns = list_fold_right nat nat 0 plus ns.\nProof.\n  Check (the_grand_finale nat nat plus plus_is_left_permutative 0).\n  exact (the_grand_finale nat nat plus plus_is_left_permutative 0).\nQed.\n\n(* What do you make of this corollary?\nThe corollary makes sense because the sum of the elements of a list is unaffected by their order in the list\nso reversing a list will not change the sum of its elements.\n*)\n\n(*\n   Can you think of more such corollaries?\n*)\n\nLemma mult_is_left_permutative :\n  is_left_permutative nat nat Nat.mul.\nProof.\n  unfold is_left_permutative.\n  intros v1 v2 v3.\n  rewrite -> (Nat.mul_assoc v1 v2 v3).\n  rewrite -> (Nat.mul_comm v1 v2).\n  rewrite <- (Nat.mul_assoc v2 v1 v3).\n  reflexivity.\nQed.\n\nCorollary folding_mult :\n  forall ns : list nat,\n    list_fold_left nat nat 1 Nat.mul ns = list_fold_right nat nat 1 Nat.mul ns.\nProof.\n  Check (the_grand_finale nat nat Nat.mul mult_is_left_permutative 1).\n  exact (the_grand_finale nat nat Nat.mul mult_is_left_permutative 1).\nQed.\n\n(* length is also a corollary *)\n\n(*\n   p. Subsidiary question: does the converse of Theorem the_grand_finale hold?\n*)\n\nTheorem the_grand_finale_converse :\n  forall (V W : Type)\n         (cons_case : V -> W -> W),\n    (forall (nil_case : W)\n            (vs : list V),\n        list_fold_left  V W nil_case cons_case vs =\n        list_fold_right V W nil_case cons_case vs) ->\n    is_left_permutative V W cons_case.\nProof.\n  intros V W cons_case H_equality_of_folding.\n  unfold is_left_permutative.\n  intros v1 v2 w3.\n  Check (H_equality_of_folding w3 (v1 :: v2 :: nil)).\n  assert (ly := H_equality_of_folding w3 (v1 :: v2 :: nil)).\n  rewrite -> (fold_unfold_list_fold_left_cons V W w3 cons_case v1 (v2 :: nil)) in ly.\n  rewrite -> (fold_unfold_list_fold_left_cons V W (cons_case v1 w3) cons_case v2 nil) in ly.\n  rewrite -> (fold_unfold_list_fold_left_nil V W (cons_case v2 (cons_case v1 w3)) cons_case) in ly.\n  rewrite -> (fold_unfold_list_fold_right_cons V W w3 cons_case v1 (v2 :: nil)) in ly.\n  rewrite -> (fold_unfold_list_fold_right_cons V W w3 cons_case v2 nil) in ly.\n  rewrite -> (fold_unfold_list_fold_right_nil V W w3 cons_case) in ly.\n  symmetry.\n  exact ly.\nQed.\n\n(* ********** *)\n\n(* Task 9: *)\n\nFixpoint nat_fold_right (V : Type) (z : V) (s : V -> V) (n : nat) : V :=\n  match n with\n  | O =>\n    z\n  | S n' =>\n    s (nat_fold_right V z s n')\n  end.\n\nLemma fold_unfold_nat_fold_right_O :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V),\n    nat_fold_right V z s O =\n    z.\nProof.\n  fold_unfold_tactic nat_fold_right.\nQed.\n\nLemma fold_unfold_nat_fold_right_S :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V)\n         (n' : nat),\n    nat_fold_right V z s (S n') =\n    s (nat_fold_right V z s n').\nProof.\n  fold_unfold_tactic nat_fold_right.\nQed.\n\n(* ***** *)\n\nFixpoint nat_fold_left (V : Type) (z : V) (s : V -> V) (n : nat) : V :=\n  match n with\n  | O =>\n    z\n  | S n' =>\n    nat_fold_left V (s z) s n'\n  end.\n\nLemma fold_unfold_nat_fold_left_O :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V),\n    nat_fold_left V z s O =\n    z.\nProof.\n  fold_unfold_tactic nat_fold_left.\nQed.\n\nLemma fold_unfold_nat_fold_left_S :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V)\n         (n' : nat),\n    nat_fold_left V z s (S n') =\n    nat_fold_left V (s z) s n'.\nProof.\n  fold_unfold_tactic nat_fold_left.\nQed.\n\n(* ********** *)\n\n(* Task 10: *)\n\nFixpoint nat_parafold_right (V : Type) (zero_case : V) (succ_case : nat -> V -> V) (n : nat) : V :=\n  match n with\n  | O =>\n    zero_case\n  | S n' =>\n    succ_case n' (nat_parafold_right V zero_case succ_case n')\n  end.\n\nLemma fold_unfold_nat_parafold_right_O :\n  forall (V : Type)\n         (zero_case : V)\n         (succ_case : nat -> V -> V),\n    nat_parafold_right V zero_case succ_case O =\n    zero_case.\nProof.\n  fold_unfold_tactic nat_parafold_right.\nQed.\n\nLemma fold_unfold_nat_parafold_right_S :\n  forall (V : Type)\n         (zero_case : V)\n         (succ_case : nat -> V -> V)\n         (n' : nat),\n    nat_parafold_right V zero_case succ_case (S n') =\n    succ_case n' (nat_parafold_right V zero_case succ_case n').\nProof.\n  fold_unfold_tactic nat_parafold_right.\nQed.\n\n(* ***** *)\n\nFixpoint nat_parafold_left (V : Type) (zero_case : V) (succ_case : nat -> V -> V) (n : nat) : V :=\n  match n with\n  | O =>\n    zero_case\n  | S n' =>\n    nat_parafold_left V (succ_case n' zero_case) succ_case n'\n  end.\n\nLemma fold_unfold_nat_parafold_left_O :\n  forall (V : Type)\n         (zero_case : V)\n         (succ_case : nat -> V -> V),\n    nat_parafold_left V zero_case succ_case O =\n    zero_case.\nProof.\n  fold_unfold_tactic nat_parafold_left.\nQed.\n\nLemma fold_unfold_nat_parafold_left_S :\n  forall (V : Type)\n         (zero_case : V)\n         (succ_case : nat -> V -> V)\n         (n' : nat),\n    nat_parafold_left V zero_case succ_case (S n') =\n    nat_parafold_left V (succ_case n' zero_case) succ_case n'.\nProof.\n  fold_unfold_tactic nat_parafold_left.\nQed.\n\n(* ***** *)\n\nDefinition specification_of_fac (fac : nat -> nat) :=\n  (fac 0 = 1)\n  /\\\n  (forall n' : nat,\n    fac (S n') = S n' * fac n').\n\nDefinition test_fac (candidate : nat -> nat) : bool :=\n  (candidate 0 =n= 1)\n  &&\n  (candidate 1 =n= 1 * 1)\n  &&\n  (candidate 2 =n= 2 * 1 * 1)\n  &&\n  (candidate 3 =n= 3 * 2 * 1 * 1)\n  &&\n  (candidate 4 =n= 4 * 3 * 2 * 1 * 1)\n  &&\n  (candidate 5 =n= 5 * 4 * 3 * 2 * 1 * 1).\n\nFixpoint fac_v0 (n : nat) : nat :=\n  match n with\n  | O =>\n    1\n  | S n' =>\n    S n' * fac_v0 n'\n  end.\n\nCompute (test_fac fac_v0).\n\nLemma fold_unfold_fac_v0_O :\n  fac_v0 0 =\n  1.\nProof.\n  fold_unfold_tactic fac_v0.\nQed.\n\nLemma fold_unfold_fac_v0_S :\n  forall n' : nat,\n    fac_v0 (S n') =\n    S n' * fac_v0 n'.\nProof.\n  fold_unfold_tactic fac_v0.\nQed.\n\nDefinition fac_v1 (n : nat) : nat :=\n  nat_parafold_right nat 1 (fun i ih => S i * ih) n.\n\nCompute (test_fac fac_v1).\n\n(* ********** *)\n\n(* end of midterm-project.v *)\n", "meta": {"author": "SamKouteili", "repo": "List-Exploration-wCoq", "sha": "1facb0ef17bfc682d93b850091a8f90f354d3bf0", "save_path": "github-repos/coq/SamKouteili-List-Exploration-wCoq", "path": "github-repos/coq/SamKouteili-List-Exploration-wCoq/List-Exploration-wCoq-1facb0ef17bfc682d93b850091a8f90f354d3bf0/midterm-project2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7106941644539461}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Bool List Relations Wf Eqdep_dec Omega.\n\nSet Implicit Arguments.\n\n(* Notations for subset or subrel set theoretic operators *)\n\nNotation \"X '⊆' Y\" := (forall x, X x -> Y x) (at level 75, format \"X  ⊆  Y\", no associativity).\nNotation \"X '≃' Y\" := (X ⊆ Y /\\ Y ⊆ X) (at level 75, format \"X  ≃  Y\", no associativity).\n\nFact inc1_refl X (A : X -> Prop) : A ⊆ A.\nProof. auto. Qed.\n\nFact inc1_trans X (A B C : X -> Prop) : A ⊆ B -> B ⊆ C -> A ⊆ C.\nProof. intros; auto. Qed.\n\nFact eq1_refl X (A : X -> Prop) : A ≃ A.\nProof. tauto. Qed.\n\nFact eq1_sym X (A B : X -> Prop) : A ≃ B -> B ≃ A.\nProof. tauto. Qed.\n\nFact eq1_trans X (A B C : X -> Prop) : A ≃ B -> B ≃ C -> A ≃ C.\nProof. intros [] [];  split; intros; auto. Qed.\n\nFact equal_eq1 X (A B : X -> Prop) : A = B -> A ≃ B.\nProof. intros []; auto. Qed.\n\n(* intersection *)\n\nNotation \"A '∩' B\" := (fun z => A z /\\ B z) (at level 50, format \"A  ∩  B\", left associativity).\nNotation \"A '∪' B\" := (fun z => A z \\/ B z) (at level 50, format \"A  ∪  B\", left associativity).\n\n(** ⊆ ≃ ∩ ∪ *)\n\nNotation sg := (@eq _).\n\nFact sg_inc1 X (A : X -> Prop) : forall x, A x <-> sg x ⊆ A.\nProof. \n  intros x; split.\n  + intros ? ? []; trivial.\n  + intros H; apply H; auto. \nQed.\n\n", "meta": {"author": "DmxLarchey", "repo": "Coq-Phase-Semantics", "sha": "52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17", "save_path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics", "path": "github-repos/coq/DmxLarchey-Coq-Phase-Semantics/Coq-Phase-Semantics-52f7751ac71ab6d19fbc0a5a5c552a6ddd8e3b17/coq.prop/rel_utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7106941599050746}}
{"text": "Require Export TopologicalSpaces.\nRequire Export WeakTopology.\n\nSection product_topology.\n\nVariable A:Type.\nVariable X:forall a:A, TopologicalSpace.\n\nDefinition product_space_point_set : Type :=\n  forall a:A, point_set (X a).\nDefinition product_space_proj (a:A) : product_space_point_set ->\n                                      point_set (X a) :=\n  fun (x:product_space_point_set) => x a.\n\nDefinition ProductTopology : TopologicalSpace :=\n  WeakTopology product_space_proj.\n\nLemma product_space_proj_continuous: forall a:A,\n  continuous (product_space_proj a) (X:=ProductTopology).\nProof.\napply weak_topology_makes_continuous_funcs.\nQed.\n\nLemma product_net_limit: forall (I:DirectedSet)\n  (x:Net I ProductTopology) (x0:point_set ProductTopology),\n  inhabited (DS_set I) ->\n  (forall a:A, net_limit (fun i:DS_set I => x i a) (x0 a)) ->\n  net_limit x x0.\nProof.\nintros.\napply net_limit_in_projections_impl_net_limit_in_weak_topology;\n  trivial.\nQed.\n\nRequire Export FilterLimits.\n\nLemma product_filter_limit:\n  forall (F:Filter (point_set ProductTopology))\n    (x0:point_set ProductTopology),\n  (forall a:A, filter_limit (filter_direct_image\n                     (product_space_proj a) F) (x0 a)) ->\n  filter_limit F x0.\nProof.\nintros.\nassert (subbasis\n  (weak_topology_subbasis product_space_proj)\n  (X:=ProductTopology)).\napply Build_TopologicalSpace_from_subbasis_subbasis.\nred; intros.\nred; intros U ?.\ndestruct H1.\ndestruct H1 as [U' []].\ncut (In (filter_family F) U').\nintro.\napply filter_upward_closed with U'; trivial.\ndestruct H1.\ndestruct (subbasis_cover _ _ H0 _ _ H3 H1) as\n  [B [? [V [? []]]]].\ncut (In (filter_family F) (IndexedIntersection V)).\nintro.\napply filter_upward_closed with (1:=H8); trivial.\napply filter_finite_indexed_intersection; trivial.\n\nintro b.\npose proof (H5 b).\ninversion H8.\napply H.\nconstructor.\napply open_neighborhood_is_neighborhood.\nconstructor; trivial.\ndestruct H6.\npose proof (H6 b).\nrewrite <- H9 in H11.\ndestruct H11.\nexact H11.\nQed.\n\nRequire Export Compactness.\n\nTheorem TychonoffProductTheorem:\n  (forall a:A, compact (X a)) -> compact ProductTopology.\nProof.\nintro.\napply ultrafilter_limit_impl_compact; intros.\nRequire Import DependentTypeChoice.\ndestruct (choice_on_dependent_type (fun (a:A) (x:point_set (X a)) =>\n  filter_limit (filter_direct_image (product_space_proj a) U) x))\n  as [choice_fun].\nintro.\ndestruct (compact_impl_filter_cluster_point _ (H a)\n  (filter_direct_image (product_space_proj a) U)) as [xa].\nexists xa.\napply ultrafilter_cluster_point_is_limit; trivial.\nred; intros.\ndestruct (H0 (inverse_image (product_space_proj a) S));\n  [left | right]; constructor; try rewrite inverse_image_complement; trivial.\nexists choice_fun.\napply product_filter_limit; trivial.\nQed.\n\nEnd product_topology.\n\nImplicit Arguments ProductTopology [[A]].\nImplicit Arguments product_space_proj [[A] [X]].\n\nLemma product_map_continuous: forall {A:Type}\n  (X:TopologicalSpace) (Y:A->TopologicalSpace)\n  (f:forall a:A, point_set X -> point_set (Y a)) (x:point_set X),\n  (forall a:A, continuous_at (f a) x) ->\n  continuous_at (fun x:point_set X => (fun a:A => f a x)) x\n    (Y:=ProductTopology Y).\nProof.\nintros.\napply func_preserving_net_limits_is_continuous.\nintros.\napply product_net_limit.\ndestruct (H0 Full_set) as [i].\napply open_full.\nconstructor.\nexists; exact i.\nintros.\napply continuous_func_preserves_net_limits; trivial.\nQed.\n\nSection product_topology2.\n\n(* we provide a version of the product topology on X and Y\n   whose underlying set is point_set X * point_set Y, for\n   more convenience as compared with the general definition *)\nVariable X Y:TopologicalSpace.\n\nInductive twoT := | twoT_1 | twoT_2.\nLet prod2_fun (i:twoT) := match i with\n  | twoT_1 => X | twoT_2 => Y end.\nLet prod2 := ProductTopology prod2_fun.\n\nLet prod2_conv1 (p:point_set prod2) : point_set X * point_set Y :=\n  (p twoT_1, p twoT_2).\nLet prod2_conv2 (p : point_set X * point_set Y) : point_set prod2 :=\n  let (x,y):=p in fun i:twoT => match i with\n    | twoT_1 => x | twoT_2 => y\n  end.\n\nLemma prod2_comp1: forall p:point_set prod2,\n  prod2_conv2 (prod2_conv1 p) = p.\nProof.\nintros.\nRequire Import FunctionalExtensionality.\nextensionality i.\ndestruct i; trivial.\nQed.\n\nLemma prod2_comp2: forall p:point_set X * point_set Y,\n  prod2_conv1 (prod2_conv2 p) = p.\nProof.\nintros.\ndestruct p as [x y].\ntrivial.\nQed.\n\nLet prod2_proj := fun i:twoT =>\n  match i return (point_set X * point_set Y ->\n                  point_set (prod2_fun i)) with\n  | twoT_1 => @fst (point_set X) (point_set Y)\n  | twoT_2 => @snd (point_set X) (point_set Y)\n  end.\n\nDefinition ProductTopology2 : TopologicalSpace :=\n  WeakTopology prod2_proj.\n\nLemma prod2_conv1_cont: continuous prod2_conv1 (Y:=ProductTopology2).\nProof.\napply pointwise_continuity.\nintros p.\napply func_preserving_net_limits_is_continuous.\nintros.\napply net_limit_in_projections_impl_net_limit_in_weak_topology.\ndestruct (H Full_set).\napply open_full.\nconstructor.\nexact (inhabits x0).\ndestruct a.\nsimpl.\napply net_limit_in_weak_topology_impl_net_limit_in_projections\n  with (a:=twoT_1) in H.\nexact H.\nsimpl.\napply net_limit_in_weak_topology_impl_net_limit_in_projections\n  with (a:=twoT_2) in H.\nexact H.\nQed.\n\nLemma prod2_conv2_cont: continuous prod2_conv2 (X:=ProductTopology2).\nProof.\napply pointwise_continuity.\ndestruct x as [x y].\napply func_preserving_net_limits_is_continuous.\nintros.\napply net_limit_in_projections_impl_net_limit_in_weak_topology.\ndestruct (H Full_set).\napply open_full.\nconstructor.\nexact (inhabits x1).\ndestruct a.\nunfold product_space_proj.\nsimpl.\nreplace (fun i:DS_set I => prod2_conv2 (x0 i) twoT_1) with\n  (fun i:DS_set I => fst (x0 i)).\napply net_limit_in_weak_topology_impl_net_limit_in_projections\n  with (a:=twoT_1) in H.\nsimpl in H.\ntrivial.\nextensionality i.\ndestruct (x0 i) as [xi yi].\ntrivial.\nunfold product_space_proj.\nsimpl.\nreplace (fun i:DS_set I => prod2_conv2 (x0 i) twoT_2) with\n  (fun i:DS_set I => snd (x0 i)).\napply net_limit_in_weak_topology_impl_net_limit_in_projections\n  with (a:=twoT_2) in H.\nsimpl in H.\ntrivial.\nextensionality i.\ndestruct (x0 i) as [xi yi].\ntrivial.\nQed.\n\nLemma product2_fst_continuous:\n  continuous (@fst (point_set X) (point_set Y))\n    (X:=ProductTopology2).\nProof.\nexact (weak_topology_makes_continuous_funcs\n  _ _ _ prod2_proj twoT_1).\nQed.\n\nLemma product2_snd_continuous:\n  continuous (@snd (point_set X) (point_set Y))\n    (X:=ProductTopology2).\nProof.\nexact (weak_topology_makes_continuous_funcs\n  _ _ _ prod2_proj twoT_2).\nQed.\n\nLemma product2_map_continuous: forall (W:TopologicalSpace)\n  (f:point_set W -> point_set X) (g:point_set W -> point_set Y)\n  (w:point_set W),\n  continuous_at f w -> continuous_at g w ->\n  continuous_at (fun w:point_set W => (f w, g w)) w\n  (Y:=ProductTopology2).\nProof.\nintros.\nreplace (fun w:point_set W => (f w, g w)) with\n  (fun w:point_set W => prod2_conv1\n              (fun i:twoT => match i with\n                | twoT_1 => f w\n                | twoT_2 => g w end)).\napply (@continuous_composition_at W prod2 ProductTopology2\n  prod2_conv1\n  (fun w:point_set W =>\n     fun i:twoT => match i with\n         | twoT_1 => f w | twoT_2 => g w end)).\napply continuous_func_continuous_everywhere.\napply prod2_conv1_cont.\napply product_map_continuous.\ndestruct a; trivial.\nextensionality w0.\ntrivial.\nQed.\n\nInductive ProductTopology2_basis :\n  Family (point_set ProductTopology2) :=\n| intro_product2_basis_elt:\n  forall (U:Ensemble (point_set X))\n         (V:Ensemble (point_set Y)),\n  open U -> open V ->\n  In ProductTopology2_basis\n  [ p:point_set ProductTopology2 |\n    let (x,y):=p in (In U x /\\ In V y) ].\n\nLemma ProductTopology2_basis_is_basis:\n  open_basis ProductTopology2_basis.\nProof.\nRequire Import FiniteIntersections.\nassert (open_basis (finite_intersections (weak_topology_subbasis prod2_proj))\n  (X:=ProductTopology2)) by apply\n  Build_TopologicalSpace_from_open_basis_basis.\napply eq_ind with (1:=H).\napply Extensionality_Ensembles; split; red; intros U ?.\ninduction H0.\nreplace (@Full_set (point_set X * point_set Y)) with\n  [ p:point_set ProductTopology2 |\n    let (x,y):=p in (In Full_set x /\\ In Full_set y) ].\nconstructor; try apply open_full.\napply Extensionality_Ensembles; split; red; intros.\nconstructor.\ndestruct x.\nconstructor; split; constructor.\ndestruct H0.\ndestruct a.\nreplace (inverse_image (prod2_proj twoT_1) V) with\n  [ p:point_set ProductTopology2 |\n    let (x,y):=p in (In V x /\\ In Full_set y) ].\nconstructor; trivial.\napply open_full.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\ndestruct x.\ndestruct H1.\nconstructor.\ntrivial.\ndestruct H1.\ndestruct x.\nconstructor.\nsplit; trivial.\nconstructor.\nreplace (inverse_image (prod2_proj twoT_2) V) with\n  [ p:point_set ProductTopology2 |\n    let (x,y):=p in (In Full_set x /\\ In V y) ].\nconstructor; trivial.\napply open_full.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H1.\ndestruct x.\ndestruct H1.\nconstructor.\ntrivial.\ndestruct H1.\ndestruct x.\nconstructor.\nsplit.\nconstructor.\ntrivial.\n\ndestruct IHfinite_intersections as [U1 V1].\ndestruct IHfinite_intersections0 as [U2 V2].\nreplace (@Intersection (point_set X * point_set Y)\n  [p:point_set ProductTopology2 | let (x,y):=p in In U1 x /\\ In V1 y]\n  [p:point_set ProductTopology2 | let (x,y):=p in In U2 x /\\ In V2 y])\nwith\n  [p:point_set ProductTopology2 | let (x,y):=p in\n   (In (Intersection U1 U2) x /\\ In (Intersection V1 V2) y)].\nconstructor; apply open_intersection2; trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H6.\ndestruct x.\ndestruct H6.\ndestruct H6.\ndestruct H7.\nconstructor.\nconstructor.\nsplit; trivial.\nconstructor.\nsplit; trivial.\ndestruct H6.\ndestruct H6.\ndestruct H7.\ndestruct x.\ndestruct H6.\ndestruct H7.\nconstructor.\nsplit; constructor; trivial.\n\ndestruct H0.\nreplace [p:point_set ProductTopology2 | let (x,y):=p in\n         In U x /\\ In V y] with\n  (Intersection (inverse_image (prod2_proj twoT_1) U)\n                (inverse_image (prod2_proj twoT_2) V)).\nconstructor 3.\nconstructor.\nconstructor; trivial.\nconstructor.\nconstructor; trivial.\napply Extensionality_Ensembles; split; red; intros.\ndestruct H2.\ndestruct H2.\ndestruct H3.\nconstructor.\ndestruct x.\nsplit; trivial.\ndestruct H2.\ndestruct x.\ndestruct H2.\nconstructor; constructor; trivial.\nQed.\n\nEnd product_topology2.\n\nSection two_arg_convenience_results.\n\nVariable X Y Z:TopologicalSpace.\nVariable f:point_set X -> point_set Y -> point_set Z.\n\nDefinition continuous_2arg :=\n  continuous (fun p:point_set X * point_set Y =>\n              let (x,y):=p in f x y)\n  (X:=ProductTopology2 X Y).\nDefinition continuous_at_2arg (x:point_set X) (y:point_set Y) :=\n  continuous_at (fun p:point_set X * point_set Y =>\n                 let (x,y):=p in f x y)  (x, y)\n  (X:=ProductTopology2 X Y).\n\nLemma continuous_2arg_func_continuous_everywhere:\n  continuous_2arg -> forall (x:point_set X) (y:point_set Y),\n                       continuous_at_2arg x y.\nProof.\nintros.\napply continuous_func_continuous_everywhere; trivial.\nQed.\n\nLemma pointwise_continuity_2arg:\n  (forall (x:point_set X) (y:point_set Y),\n   continuous_at_2arg x y) -> continuous_2arg.\nProof.\nintros.\napply pointwise_continuity.\nintros.\ndestruct x as [x y].\napply H.\nQed.\n\nEnd two_arg_convenience_results.\n\nImplicit Arguments continuous_2arg [[X] [Y] [Z]].\nImplicit Arguments continuous_at_2arg [[X] [Y] [Z]].\n\nLemma continuous_composition_at_2arg:\n  forall (W X Y Z:TopologicalSpace)\n    (f:point_set X -> point_set Y -> point_set Z)\n    (g:point_set W -> point_set X) (h:point_set W -> point_set Y)\n    (w:point_set W),\n  continuous_at_2arg f (g w) (h w) ->\n  continuous_at g w -> continuous_at h w ->\n  continuous_at (fun w:point_set W => f (g w) (h w)) w.\nProof.\nintros.\napply (continuous_composition_at\n  (fun p:point_set (ProductTopology2 X Y) =>\n      let (x,y):=p in f x y)\n  (fun w:point_set W => (g w, h w))).\nexact H.\napply product2_map_continuous; trivial.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/ProductTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7106514411874252}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := mult (Succ x) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj82_coqofml_bVqNkn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7106514366960065}}
{"text": "(********************************************************)\n(*    OrderedList.v                                     *)\n(*     Ordered List                                     *)\n(*                               thery@sophia.inria.fr  *)\n(*                                      (2006)          *)\n(********************************************************)\nRequire Import List.\nRequire Import Permutation.\nRequire Import UList.\n\nSection ordered.\n\n(* The type of the elements in the list *)\nVariable A: Set.\n\n(* Comparison values *)\nInductive cmp : Set := lt | eq | gt.\n\n(* Opposite *)\nDefinition opp v := match v with lt => gt | eq => eq | gt => lt end.\n\n(* Weight function *)\nVariable weight : A -> A -> cmp.\n\n(* Transitivity *)\nHypothesis weight_trans : \n  forall a b c, weight a b = weight b c -> weight a c = weight a b.\n\n(* Anti symmetry *)\nHypothesis weight_anti_sym : \n  forall a b, weight b a = opp (weight a b).\n\n(* Reflexivity *)\nTheorem weight_refl a : weight a a = eq.\nProof.\ngeneralize (weight_anti_sym a a); \n  case (weight a a); auto; intros; discriminate.\nQed.\n\n(* Compatibility left *)\nHypothesis weight_compat_l : \n  forall a b c, weight a b = eq -> weight a c = weight b c.\n\n(* Compatibility right *)\nTheorem weight_compat_r a b c : weight a b = eq -> weight c a = weight c b.\nProof.\nintro H; repeat rewrite (fun x => weight_anti_sym x c).\nrewrite weight_compat_l with (b := b); auto.\nQed.\n\n(* No collision *)\nHypothesis weight_exact : forall a b, weight a b = eq -> a = b.\n\nTheorem weight_equiv a b : weight a b = eq <-> a = b.\nProof.\nsplit; intros H; subst; auto.\napply weight_refl.\nQed.\n\nDefinition A_dec (a b : A) : {a = b} + {a <> b}.\nProof.\ngeneralize (weight_equiv a b); \n case (weight a b); intros (H1, H2); auto.\n  right; intros H; generalize (H2 H); intros; discriminate.\nright; intros H; generalize (H2 H); intros; discriminate.\nDefined.\n\n(* Ordered list *)\nInductive olist: list A -> Prop :=\n   olist_nil: olist nil\n|  olist_one: forall a, olist (a :: nil)\n| olist_cons: forall a b l, \n      weight a b = lt -> olist (b::l) -> olist (a::b::l).\n\n(* Removing the first element of an ordered list, the list\n   remains ordered \n *)\nTheorem olist_inv a l : olist (a :: l) -> olist l.\nProof.\ncase l; simpl; auto.\nintros H; apply olist_nil.\nintros a1 l1 H; inversion H; auto.\nQed.\n\n(* Removing the second element of an ordered list, the list\n   remains ordered \n *)\nTheorem olist_skip  a b l : olist (a :: b :: l) -> olist (a :: l).\nProof.\nrevert a b; elim l; simpl; auto.\n  intros; apply olist_one.\nintros a1 l1 Rec a2 b1 H.\nassert (Eq1: weight a2 b1 = lt).\n  inversion H; auto.\nassert (Eq2: weight b1 a1 = lt).\n  inversion_clear H as [| H0 H1|]; auto.\n  inversion_clear H1 ; auto.\napply olist_cons; auto.\n  rewrite weight_trans with (b := b1); auto.\n  apply trans_equal with (1 := Eq1); auto.\ninversion_clear H; auto.\ninversion_clear H1; auto.\nQed.\n\n\n(* All the elements in an ordered list are smaller thant the head *)\nTheorem olist_weight a b l :\n  olist (a :: l) -> In b l -> weight a b = lt.\nProof.\nintro H; generalize a b H; elim l; clear a b l H.\n  intros a b _ H1; case H1.\nsimpl; intros a1 l Rec a b H [H1 | H1]; subst; auto.\n  inversion H; auto.\nassert (Eq1: weight a a1 = lt).\n  inversion H; auto.\nrewrite weight_trans with (b := a1); auto.\nrewrite Eq1; apply sym_equal; apply Rec; auto.\ninversion_clear H; auto.\nQed.\n\n(* An ordered list is unique *)\nTheorem olist_ulist l : olist l -> ulist l.\nProof.\nelim l; simpl; auto.\nintros a l1; case l1; auto.\nintros b l2 Rec H; inversion_clear H as [| H0 H1 |].\napply ulist_cons; auto.\nsimpl; intros [H2 | H2]; subst; auto.\n  rewrite weight_refl in H0; discriminate.\ngeneralize (weight_anti_sym a b); rewrite H0.\nrewrite olist_weight with (l := l2); auto.\nintros; discriminate.\nQed.\n\n(* Check if a literal is in a clause *)\nFixpoint is_in (a: A) (l: list A) {struct l}: bool :=\n  match l with \n    nil => false\n  | b :: l1 => \n     match weight a b with\n       eq => true \n     | lt => false\n     | gt => is_in a l1\n     end\n  end.\n\nTheorem is_in_correct a l : olist l -> if is_in a l then In a l else ~ In a l.\nProof.\nelim l; simpl; auto.\nintros b l1 Rec H.\nassert (F0: olist l1); try (apply olist_inv with (1 := H)).\ncase_eq (weight a b); intros H1; auto.\n- intros [H3 | H3]; subst; auto.\n    rewrite weight_refl in H1; discriminate.\n  generalize (weight_anti_sym b a); rewrite H1.\n  rewrite olist_weight with (l := l1); simpl; intros; auto;\n  discriminate.\n- rewrite weight_exact with (1 := H1); auto.\n- generalize (Rec F0); case (is_in a l1); auto.\n  intros H3 [H4 | H4]; subst; auto.\n  rewrite weight_refl in H1; discriminate.\nQed.\n\n(* Insert an element in an ordered list with duplication *)\nFixpoint insert (a: A) (l: list A) {struct l}: list A :=\n  match l with\n    nil => a :: nil\n  | b :: l1 =>\n      match weight a b with\n        lt => a :: l\n      | eq => l\n      | gt => b :: insert a l1\n      end\n  end.\n\n(* The inserted element is in the result *)\nTheorem insert_in a l : In a (insert a l).\nProof.\nelim l; simpl; auto.\nintros b l1 H; case_eq (weight a b); auto with datatypes.\nintros H1; rewrite weight_exact with (1 := H1); \n  auto with datatypes.\nQed.\n\n(* The initial list is in the result *)\nTheorem insert_incl a l : incl l (insert a l).\nProof.\nelim l; simpl; auto with datatypes.\nintros b l1 H; case_eq (weight a b); auto with datatypes.\nQed.\n\n(* The result contains only the initial list or the inserted element *)\nTheorem insert_inv a b l : In a (insert b l) -> a = b \\/ In a l.\nProof.\nelim l; simpl; auto with datatypes.\n  intuition.\nintros c l1 H; case_eq (weight b c); simpl; auto with datatypes.\n  intuition.\nintuition.\nQed.\n\n(* If the initial list is ordered so is the result *)\nTheorem insert_olist a l : olist l -> olist (insert a l).\nProof.\nelim l; simpl; auto.\n  intros; apply olist_one; auto.\nintros b l1 Rec H; case_eq (weight a b); intros H1; auto.\n  apply olist_cons; auto.\nassert (Eq1: olist l1); try apply olist_inv with (1 := H).\ngeneralize (Rec Eq1).\nassert (Eq2: forall c, In c (insert a l1) -> weight b c = lt).\n  intros c H2.\n  case insert_inv with (1 := H2); auto.\n    intros; subst; rewrite weight_anti_sym; rewrite H1; auto.\n  intros H3; apply olist_weight with (1 := H); auto.\ngeneralize Eq2; case (insert a l1); auto.\n  intros; apply olist_one.\nintros c l2 H2 H3; apply olist_cons; auto with datatypes.\nQed.\n\n(* Insert an element in an ordered list l if needed (a does not \n   occur in l) and then call the continuation f with the tail of l \n *)\nFixpoint insert_cont (f: list A -> list A) (a: A) (l: list A) {struct l}: \n      list A :=\n  match l with\n    nil => a :: f nil\n  | b :: l1 =>\n      match weight a b with\n        lt => a :: f l\n      | eq => a :: f l1\n      | gt => b :: insert_cont f a l1\n      end\n  end.\n\n(* Merge two ordered lists *)\nFixpoint merge (l1 l2: list A) {struct l1}: list A :=\n  match l1 with\n    nil => l2\n  | a :: l3 => insert_cont (merge l3) a l2\n  end.\n\nTheorem merge_incl_l l1 l2 : incl l1 (merge l1 l2).\nProof.\nrevert l2; elim l1; simpl; auto with datatypes; clear l1.\n  intros l2 a H; case H.\nintros a l1 Rec l2 b; simpl; intros [H | H]; subst; auto.\n  elim l2; simpl; auto; clear l2.\n  intros c l2 Rec1; case_eq (weight b c); intros H; auto with datatypes.\nelim l2; simpl; auto; clear l2.\n  right; apply (Rec nil b); auto.\nintros c l2 Rec1; case_eq (weight a c); intros H1; auto with datatypes.\n  simpl; right; apply (Rec (c :: l2) b); auto.\nsimpl; right; apply (Rec l2 b); auto.\nQed.\n\nTheorem merge_incl_r l1 l2 : incl l2 (merge l1 l2).\nProof.\nrevert l2; elim l1; simpl; auto with datatypes.\nintros a l3 Rec l2; elim l2; simpl; auto with datatypes; clear l2.\nintros b l2 Rec1; case_eq (weight a b); intros H; auto with datatypes.\nintro c; simpl; intros [H1 | H1]; subst.\n  left; apply weight_exact; auto.\nright; apply (Rec l2 c); auto.\nQed.\n\nTheorem merge_inv a l1 l2 : In a (merge l1 l2) -> In a l1 \\/ In a l2.\nProof.\nrevert l2; elim l1; simpl; auto; clear l1.\nintros b l1 Rec l2; elim l2; simpl; auto; clear l2.\n  intros [H | H]; auto.\n  case (Rec nil); auto.\nintros c l2 Rec1; case (weight b c); simpl; intros [H | H]; subst; auto.\n- case (Rec (c :: l2)); auto.\n- case (Rec l2); auto.\n- case Rec1; auto.\nQed.\n\n(* Old trick to prove that ordering is preserved we first need\n   to prove something stronger \n *)\nTheorem merge_olist_strong a l1 l2 :\n  olist (a :: l1) -> olist (a :: l2)  -> olist (a :: merge l1 l2).\nrevert a l2; elim l1; simpl; auto; clear l1.\nintros b l1 Rec a l2 H.\nassert (V1: weight a b = lt); try apply olist_weight with (1 := H); auto with datatypes.\nassert (V2: olist (b :: l1)); try apply olist_inv with (1 := H).\ngeneralize a V1; elim l2; simpl; clear a l2 H V1; auto.\n  intros a V1 _; apply olist_cons; auto.\n  apply Rec; auto.\n  apply olist_one; auto.\nintros c l2 Rec1 a V1 H1; case_eq (weight b c); intros H2.\n- apply olist_cons; auto.\n  apply Rec; auto with datatypes.\n  apply olist_cons; auto.\n  apply olist_inv with (1 := H1); auto.\n- apply olist_cons; auto.\n  apply Rec; auto with datatypes.\n  rewrite weight_exact with (1 := H2); auto.\n  apply olist_inv with (1 := H1); auto.\n- apply olist_cons; auto.\n  apply olist_weight with (1 := H1); auto with datatypes.\n  apply Rec1; auto.\n    rewrite weight_anti_sym; rewrite H2; auto.\n  apply olist_inv with (1 := H1); auto.\nQed.\n\n(* merge keeps ordering *)\nTheorem merge_olist l1 l2 : \n  olist l1 -> olist l2  -> olist (merge l1 l2).\nProof.\ncase l1; clear l1; simpl; auto.\nintros a l1; case l2; simpl; auto; clear l2.\n  intros; apply merge_olist_strong; auto.\n  apply olist_one; auto.\nintros b l2 H H1.\ncase_eq (weight a b); intros H2; auto.\n- apply merge_olist_strong; auto.\n  apply olist_cons; auto.\n- apply merge_olist_strong; auto.\n  rewrite weight_exact with (1 := H2); auto.\n- generalize b H H1 H2; elim l2; simpl; auto; clear l2 b H H1 H2.\n  intros b H H1 H2; apply olist_cons; auto.\n  rewrite weight_anti_sym; rewrite H2; auto.\n  apply merge_olist_strong; auto.\n  apply olist_one; auto.\n  intros b l2 Rec c H H1 H2.\n  case_eq (weight a b); intros H3; auto.\n  * apply olist_cons; auto.\n      rewrite weight_anti_sym; rewrite H2; auto.\n    apply merge_olist_strong; auto.\n    apply olist_cons; auto.\n    apply olist_inv with (1 := H1); auto.\n  * apply olist_cons; auto.\n      rewrite weight_anti_sym; rewrite H2; auto.\n    apply merge_olist_strong; auto.\n    rewrite weight_exact with (1 := H3); auto.\n    apply olist_inv with (1 := H1); auto.\n  * apply olist_cons; auto.\n    apply olist_weight with (1 := H1); auto with datatypes.\n    apply Rec; auto.\n    apply olist_inv with (1 := H1); auto.\nQed.\n\n(* Insert an element in an ordered list *)\nFixpoint  ocons (a: A) (l: list A) {struct l}: list A :=\n  match l with\n    nil => a :: nil\n  | b :: l1 =>\n      match weight a b with\n        lt => a :: l\n      | eq => a :: l\n      | gt => b :: ocons a l1\n      end\n  end.\n\n(* ocons always increments the length *)\nTheorem ocons_length a l : length (ocons a l) = S (length l).\nProof.\nelim l; simpl; auto.\nintros b l1 H; case (weight a b); simpl; auto.\nQed.\n\n(* The inserted element is in the result *)\nTheorem ocons_in a l : In a (ocons a l).\nProof.\nelim l; simpl; auto.\nintros b l1 H; case_eq (weight a b); auto with datatypes.\nQed.\n\n(* The initial list is in the result *)\nTheorem ocons_incl a l : incl l (ocons a l).\nProof.\nelim l; simpl; auto with datatypes.\nintros b l1 H; case_eq (weight a b); auto with datatypes.\nQed.\n\n(* The result contains only the initial list or the inserted element *)\nTheorem ocons_inv a b l : In a (ocons b l) -> a = b \\/ In a l.\nProof.\nelim l; simpl; auto with datatypes.\n  intuition.\nintros c l1 H; case_eq (weight b c); simpl; intuition.\nQed.\n\n(* Add an element in an ordered list l with possible duplication\n   and then call the continuation f with the tail of l \n *)\nFixpoint add_cont (f: list A -> list A) (a: A) (l: list A) {struct l}: \n      list A :=\n  match l with\n    nil => a :: f nil\n  | b :: l1 =>\n      match weight a b with\n        lt => a :: f l\n      | eq => a :: f l\n      | gt => b :: add_cont f a l1\n      end\n  end.\n\n(* Add two ordered lists with possible duplication *)\nFixpoint add (l1 l2: list A) {struct l1}: list A :=\n  match l1 with\n    nil => l2\n  | a :: l3 => add_cont (add l3) a l2\n  end.\n\nTheorem add_length l1 l2 : length (add l1 l2) = length l1 + length l2.\nProof.\nrevert l2; elim l1; simpl; auto; clear l1.\nintros a l1 Rec l2; elim l2; simpl; auto; clear l2.\n  rewrite Rec; auto.\nintros b l2 Rec1; case (weight a b); simpl; auto.\n- rewrite Rec; simpl; repeat rewrite <- plus_n_Sm; auto with arith.\n- rewrite Rec; simpl; repeat rewrite <- plus_n_Sm; auto with arith.\n- rewrite Rec1; simpl; repeat rewrite <- plus_n_Sm; auto with arith.\nQed.\n\nTheorem add_incl_l l1 l2 : incl l1 (add l1 l2).\nProof.\nrevert l2; elim l1; simpl; auto with datatypes; clear l1.\n  intros l1 a H; case H.\nintros a l1 Rec l2 b; simpl; intros [H | H]; subst; auto.\n  elim l2; simpl; auto; clear l2.\n  intros c l2 Rec1; case_eq (weight b c); intros H; auto with datatypes.\nelim l2; simpl; auto; clear l2.\n  right; apply (Rec nil b); auto.\nintros c l2 Rec1; case_eq (weight a c); intros H1; auto with datatypes.\n  simpl; right; apply (Rec (c :: l2) b); auto.\nsimpl; right; apply (Rec (c :: l2) b); auto.\nQed.\n\nTheorem add_incl_r l1 l2 : incl l2 (add l1 l2).\nProof.\nrevert l2; elim l1; simpl; auto with datatypes.\nintros a l3 Rec l2; elim l2; simpl; auto with datatypes; clear l2.\nintros b l2 Rec1; case_eq (weight a b); intros H; auto with datatypes.\nQed.\n\nTheorem add_inv a l1 l2 : In a (add l1 l2) -> In a l1 \\/ In a l2.\nProof.\nrevert l2; elim l1; simpl; auto; clear l1.\nintros b l1 Rec l2; elim l2; simpl; auto; clear l2.\n  intros [H | H]; auto.\n  case (Rec nil); auto.\nintros c l2 Rec1; case (weight b c); simpl; intros [H | H]; subst; auto.\n- case (Rec (c :: l2)); auto.\n- case (Rec (c :: l2)); auto.\n- case Rec1; auto.\nQed.\n\n(* Remove an element from the list l if needed and then call\n   the continuation f on the tail of l \n *)\nFixpoint rm_cont (f: list A -> list A) (a: A) (l: list A) {struct l}:\n          list A :=\n  match l with \n    nil => nil\n  | b :: l1 => \n     match weight a b with\n       eq => f l1\n     | lt => f l\n     | gt => b :: rm_cont f a l1\n     end\n  end.\n\n(* Remove all the element of the list l1 from the list l2 *)\nFixpoint rm (l1 l2: list A) {struct l1}: list A :=\n  match l1 with\n    nil => l2\n  | a :: l3 =>\n      rm_cont (rm l3) a l2\n  end.\n\nTheorem rm_incl l1 l2 : incl (rm l1 l2) l2.\nProof.\nrevert l2; elim l1; simpl; auto with datatypes; clear l1.\nintros a l1 Rec l2; elim l2; simpl; auto with datatypes; clear l2.\nintros b l2 H; case_eq (weight a b); auto with datatypes.\nQed.\n\nTheorem rm_not_in (a: A) l1 l2 : olist l1 -> olist l2 ->\n  In a l1 -> ~ In a (rm l1 l2).\nProof.\nrevert l2; generalize a; elim l1; simpl; auto; clear a l1.\nintros b l1 Rec a l2 H1 H2.\nassert (O1: olist l1); try apply olist_inv with (1 := H1).\nintros [H | H]; subst; auto.\n  generalize H2; elim l2; simpl; auto with datatypes; clear l2 H2.\n  intros b l2 Rec1 H2.\n  assert (O2: olist l2); try apply olist_inv with (1 := H2).\n  case_eq (weight a b); auto with datatypes; intros H3.\n  - intros H4; absurd (In a (b :: l2)); auto.\n      simpl; intros [H5 | H5]; subst.\n        rewrite weight_refl in H3; discriminate.\n      rewrite weight_anti_sym in H3; rewrite (olist_weight b a l2) in H3;\n      try discriminate; auto.\n    apply (rm_incl l1 (b :: l2) a); auto.\n  - assert (a = b); subst.\n      apply weight_exact with (1 := H3).\n    intros H4; absurd (In b l2); auto.\n      assert (H5: ulist (b :: l2)); try apply olist_ulist; auto.\n      inversion H5; auto.\n    apply (rm_incl l1 l2 b); auto.\n  - simpl; intros [H4 | H4]; subst.\n      rewrite weight_refl in H3; discriminate.\n    case Rec1; auto.\n  - generalize H2; elim l2; simpl; auto with datatypes; clear l2 H2.\n    intros c l2 Rec1 H2.\n    assert (O2: olist l2); try apply olist_inv with (1 := H2).\n    case_eq (weight b c); auto with datatypes; intros H3.\n    simpl; intros [H4 | H4]; subst.\n      rewrite (olist_weight b a l1) in H3; auto; discriminate.\n    case Rec1; auto.\nQed.\n\nTheorem rm_in (a: A) l1 l2 : olist l1 -> olist l2 ->\n  ~ In a l1 -> In a l2 -> In a (rm l1 l2).\nProof.\nrevert l2; generalize a; elim l1; simpl; auto; clear a l1.\nintros b l1 Rec a l2 H1 H2 H3 H4.\ngeneralize H2 H4; elim l2; simpl; auto; clear l2 H2 H4.\nassert (O1: olist l1); try apply olist_inv with (1 := H1).\n  intros c l3 Rec1 H4 [H5 | H5]; subst.\n  case_eq (weight b a); auto with datatypes; intros H5.\n  case H3; rewrite weight_exact with (1 := H5); auto.\nassert (O2: olist l3); try apply olist_inv with (1 := H4).\ncase_eq (weight b c); auto with datatypes; intros H6.\nQed.\n\nTheorem rm_olist_strong a l1 l2 : \n  olist (a :: l2) -> olist (a :: rm l1 l2).\nProof.\nrevert a l2; elim l1; simpl; auto; clear l1.\nintros a l1 Rec c l2; generalize c; elim l2; simpl; auto; clear c l2.\nintros b l2 Rec1 c H.\ncase_eq (weight a b); intros H1; auto.\n  apply Rec; auto.\n  apply olist_skip with (1 := H); auto.\napply olist_cons; auto.\n  apply olist_weight with (1 := H); auto with datatypes.\napply Rec1; auto.\napply olist_inv with (1 := H); auto.\nQed.\n\nTheorem rm_olist l1 l2 : olist l2 -> olist (rm l1 l2).\nProof.\nrevert l2; elim l1; simpl; auto; clear l1.\nintros a l1 Rec l2; case l2; simpl; auto; clear l2.\nintros b l2 H; case_eq (weight a b); intros H1; auto.\n  apply Rec; auto.\n  apply olist_inv with (1 := H); auto.\ngeneralize b H H1; elim l2; simpl; auto; clear b l2 H H1.\nintros b l2 Rec1 c H H1.\ncase_eq (weight a b); intros H2; auto.\n- apply rm_olist_strong; auto.\n- apply rm_olist_strong; auto.\n  apply olist_skip with (1 := H); auto.\n- apply olist_cons; auto.\n  apply olist_weight with (1 := H); auto with datatypes.\n  apply Rec1; auto.\n  apply olist_inv with (1 := H); auto.\nQed.\n\n(** Lifting the order to a lexico on list *)\n\n(* Lexico on list  *)\nFixpoint lexico (l1 l2: list A) {struct l1}: cmp :=\n  match l1 with\n    nil => match l2 with nil => eq | _ => lt end\n  | a:: l3 =>\n     match l2 with \n       nil => gt \n     | b :: l4 =>\n        match weight a b with\n          eq => lexico l3 l4\n        | X => X\n        end\n     end\n   end.\n\nTheorem lexico_trans a b c :\n  lexico a b = lexico b c -> lexico a c = lexico a b.\nProof.\nrevert b c; elim a; simpl; auto; clear a.\n  intros b; case b; auto; clear b.\n  intros x b c; case c; clear c; simpl; auto.\n  intros; discriminate.\nintros x a Rec; intros b c; case c; case b; clear b c; simpl; \n try (intros; discriminate; fail); auto.\nintros y b z c.\ncase_eq (weight x y); auto; intros H1.\n- case_eq (weight y z); auto; intros H2.\n  * rewrite (weight_trans x y z); rewrite H1; auto.\n  * rewrite <- (weight_compat_r y z x); auto.\n    rewrite H1; auto.\n  * intros; discriminate.\n- rewrite (weight_compat_l x y z); auto.\n  case_eq (weight y z); auto; intros H2.\n- case_eq (weight y z); auto; intros H2.\n  * intros; discriminate.\n  * rewrite <- (weight_compat_r y z x); auto.\n    rewrite H1; auto.\n  * rewrite (weight_trans x y z); auto.\n      rewrite H1; auto.\n    rewrite H1; auto.\nQed.\n\nTheorem lexico_anti_sym a b : lexico b a = opp (lexico a b).\nProof.\nrevert b; elim a; clear a; simpl; auto.\n  intros b; case b; clear b; simpl; auto.\nintros x a Rec b; case b; clear b; simpl; auto.\nintros y b; rewrite (weight_anti_sym x y).\ncase (weight x y); simpl; auto.\nQed.\n\n(* No collision *)\nTheorem lexico_exact a b : lexico a b = eq -> a = b.\nProof.\nrevert b; elim a; simpl; auto; clear a.\n  intros b; case b; auto.\n  intros; discriminate.\nintros x a Rec b; case b; auto; clear b.\n  intros; discriminate.\nintros y b.\ngeneralize (weight_exact x y).\ncase (weight x y); auto.\n- intros; discriminate.\n- intros; eq_tac; auto.\n- intros; discriminate.\nQed.\n\nEnd ordered.\n\n\n(* Computable equality test *)\nDefinition eq_nat: forall x y : nat, {x = y} + {x <> y}.\nProof.\nfix eq_nat 2; intros x y; case x; case y.\n- left; auto.\n- intros y1; right; intros; discriminate.\n- intros x1; right; intros; discriminate.\n- intros y1 x1; case (eq_nat x1 y1); intros H.\n  left; auto.\n  right; contradict H; injection H; auto.\nDefined.\n\n(* Comparison for integers *)\nFixpoint test (n m: nat) {struct n}: cmp :=\n  match n with \n       O => match m with O => eq | _ => lt end\n  | S n1 => match m with O => gt | S m1 => test n1 m1 end\n  end.\n\nTheorem test_trans n1 n2 n3 :\n  test n1 n2 = test n2 n3 -> test n1 n3 = test n1 n2.\nProof.\nrevert n2 n3; elim n1; simpl; auto; clear n1.\n  intros n2; elim n2; simpl; auto; clear n2.\n  intros n2 Rec n3; elim n3; simpl; auto; clear n3.\n  intros; discriminate.\nintros n1 Rec n2; elim n2; clear n2; simpl; auto.\n  intros n3; elim n3; simpl; auto; clear n3.\n  intros; discriminate.\nintros n2 Rec1 n3; elim n3; simpl; auto; clear n3.\nQed.\n\nTheorem test_anti_sym n1 n2 : test n1 n2 = opp (test n2 n1).\nProof.\nrevert n2; elim n1; simpl; auto; clear n1.\n  intros n2; elim n2; simpl; auto; clear n2.\nintros n1 Rec n2; elim n2; simpl; auto; clear n2.\nQed.\n\nTheorem test_exact n1 n2 : test n1 n2 = eq -> n1 = n2.\nProof.\nrevert n2; elim n1; simpl; auto; clear n1.\n  intros n2; elim n2; simpl; auto; clear n2.\n  intros; discriminate.\nintros n1 Rec n2; elim n2; simpl; auto; clear n2.\nintros; discriminate.\nQed.\n\nTheorem test_compat_l a b c : test a b = eq -> test a c = test b c.\nProof.\nrevert b c; elim a; simpl; auto; clear a.\n  intros b; case b; try (intros; discriminate; fail).\n  intros c; case c; auto.\nintros a Rec b; case b; clear b.\n  intros; discriminate.\nintros b c Hb; case c; simpl; auto.\nQed.", "meta": {"author": "thery", "repo": "sudoku", "sha": "7e38b82006a76b54691be3c57f5426b4da750ca6", "save_path": "github-repos/coq/thery-sudoku", "path": "github-repos/coq/thery-sudoku/sudoku-7e38b82006a76b54691be3c57f5426b4da750ca6/OrderedList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7106514325415502}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_collinear2.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_collinear1.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral}.\n\nLemma lemma_collinearorder : \n   forall A B C, \n   Col A B C ->\n   Col B A C /\\ Col B C A /\\ Col C A B /\\ Col A C B /\\ Col C B A.\nProof.\nintros.\nassert (Col B C A) by (conclude lemma_collinear2).\nassert (Col C A B) by (conclude lemma_collinear2).\nassert (Col B A C) by (conclude lemma_collinear1).\nassert (Col A C B) by (conclude lemma_collinear2).\nassert (Col C B A) by (conclude lemma_collinear2).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_collinearorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7106514197412185}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) (y : natural)\n  : natural := mult x (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj297_coqofml_N3njuR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7106326097227612}}
{"text": "Require Import Reals.\nLocal Open Scope R_scope.\nFrom ValidSDP Require Import validsdp.\n\nLet p (x0 x1 x2 : R) :=\n  -x0 + 2/1 * x1 - x2 - 417817267/500000000 * x1 * (1 + x1).\n\nLet b1 (x0 x1 x2 : R) :=\n  (x0 + 5/1) * (5/1 - x0).\n\nLet b2 (x0 x1 x2 : R) :=\n  (x1 + 5/1) * (5/1 - x1).\n\nLet b3 (x0 x1 x2 : R) :=\n  (x2 + 5/1) * (5/1 - x2).\n\nLet lb := -36713/1000.\n\nLet ub := 10439/1000.\n\nTheorem p_ge_lb (x0 x1 x2 : R) :\n  b1 x0 x1 x2 >= 0 ->\n  b2 x0 x1 x2 >= 0 ->\n  b3 x0 x1 x2 >= 0 ->\n  lb <= p x0 x1 x2.\nProof.\nunfold b1, b2, b3, p, lb.\nvalidsdp.\nQed.\n\nTheorem p_le_ub (x0 x1 x2 : R) :\n  b1 x0 x1 x2 >= 0 ->\n  b2 x0 x1 x2 >= 0 ->\n  b3 x0 x1 x2 >= 0 ->\n  p x0 x1 x2 <= ub.\nProof.\nunfold b1, b2, b3, p, ub.\nvalidsdp.\nQed.\n", "meta": {"author": "validsdp", "repo": "validsdp", "sha": "135dd32a2b1166f357df764b469ce14e24711536", "save_path": "github-repos/coq/validsdp-validsdp", "path": "github-repos/coq/validsdp-validsdp/validsdp-135dd32a2b1166f357df764b469ce14e24711536/benchs/global/reaction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7106326078498838}}
{"text": "(*\n\n   Benedikt Ahrens and Régis Spadotti\n\n   Terminal semantics for codata types in intensional Martin-Löf type theory\n\n   http://arxiv.org/abs/1401.1053\n\n*)\n\n(*\n\n  Content of this file:\n\n  definition of the functor [EQ] from sets to setoids, proof that it is strong monoidal\n\n*)\n\nRequire Import Category.Types.\nRequire Import Category.Setoids.\nRequire Import Theory.Category.\nRequire Import Theory.Functor.\nRequire Import Theory.Product.\nRequire Import Theory.Isomorphism.\nRequire Import Theory.ProductPreservingFunctor.\n\n(*------------------------------------------------------------------------------\n  -- ＦＵＮＣＴＯＲ  ＥＱ\n  ----------------------------------------------------------------------------*)\n(** * Functor 𝑬𝑸 : 𝑻𝒚𝒑𝒆 → 𝑺𝒆𝒕𝒐𝒊𝒅 **)\n\n(** ** Definition **)\n\nProgram Definition F : 𝑻𝒚𝒑𝒆 → 𝑺𝒆𝒕𝒐𝒊𝒅 := λ T ∙ Setoids.make  ⦃ Carrier  ≔ T\n                                                            ; Equiv    ≔ eq ⦄.\n\nProgram Definition map {A B} : [ A ⇒ B ⟶ F A ⇒ F B ] :=\n  λ f ↦ Setoids.Morphism.make f.\n(** f-cong **)\nNext Obligation.\n  intros f g eq_fg x y eq_xy; simpl.\n  now rewrite eq_xy.\nQed.\n\nLemma id A : id[ F A ] ≈ map id[ A ].\nProof.\n  intros x y eq_xy; now rewrite eq_xy.\nQed.\n\nLemma map_compose A B C (f : A ⇒ B) (g : B ⇒ C) : map (g ∘ f) ≈ (map g) ∘ (map f).\nProof.\n  intros x y eq_xy. now rewrite eq_xy.\nQed.\n\nDefinition 𝑬𝑸 : Functor 𝑻𝒚𝒑𝒆 𝑺𝒆𝒕𝒐𝒊𝒅 := mkFunctor id map_compose.\n\n\n(*------------------------------------------------------------------------------\n  -- ＥＱ  ＩＳ  ＰＲＥＳＥＶＥＳ  ＰＲＯＤＵＣＴ\n  ----------------------------------------------------------------------------*)\n(** ** 𝑬𝑸 is strong monoidal **)\n\nProgram Instance 𝑬𝑸_PF : ProductPreservingFunctor 𝑬𝑸 :=\n  ProductPreservingFunctor.make ⦃ φ ≔ λ A B ∙ Setoids.Morphism.make (λ x ∙ x) ⦄.\n(** φ-cong **)\nNext Obligation.\n  now f_equal.\nQed.\n(** φ-inverse **)\nNext Obligation.\n  constructor.\n  - (* iso_left *)\n    intros f g eq_fg. exact eq_fg.\n  - (* iso_right *)\n    intros f g eq_fg. simpl in *. destruct f. auto.\nQed.\n\n(*------------------------------------------------------------------------------\n  -- ＦＵＮＣＴＯＲ  ＥＱ-×\n  ----------------------------------------------------------------------------*)\n(** * Functor 𝑬𝑸-× : 𝑻𝒚𝒑𝒆 × 𝑻𝒚𝒑𝒆 → 𝑺𝒆𝒕𝒐𝒊𝒅 **)\n\n(** ** Definition **)\n\n\nProgram Definition 𝑬𝑸_prod : Functor (𝑻𝒚𝒑𝒆 𝘅 𝑻𝒚𝒑𝒆) 𝑺𝒆𝒕𝒐𝒊𝒅 :=\n  Functor.make ⦃ F   ≔ λ A ∙ Setoids.make ⦃ Carrier ≔ fst A ⟨×⟩ snd A\n                                          ; Equiv ≔ eq ⦄\n               ; map ≔ λ A B ∙ λ f ↦ Setoids.Morphism.make (λ x ∙ (fst f (fst x) , snd f (snd x))) ⦄.\n(** equivalence **)\nNext Obligation.\n  eauto with typeclass_instances.\nQed.\n(** map-proper **)\nNext Obligation.\n  intros [? ?] [? ?] [? ?] [? ?] [? ?] eq. injection eq; intros.\n  simpl in *; f_equal; congruence.\nQed.\n\nNotation \"𝑬𝑸-𝘅\" := 𝑬𝑸_prod.\n", "meta": {"author": "rs-", "repo": "Triangles", "sha": "57f10cb6c627c331b2c6e7b344a34ae50838cc67", "save_path": "github-repos/coq/rs--Triangles", "path": "github-repos/coq/rs--Triangles/Triangles-57f10cb6c627c331b2c6e7b344a34ae50838cc67/Category/Types_Setoids.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.7106325933357731}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) (y : natural)\n  : natural := mult x (plus y Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj297_coqofml_NuYbH0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7106325871824267}}
{"text": "(** * RIS.language : Languages. *)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import tools algebra.\n\nSection lang.\n  Context {A : Set}.\n  (** * Definitions *)\n  (** A language is a set of words, i.e. a predicate over lists. *)\n  Definition language := list A -> Prop.\n  (** Two languages are equivalent if they agree on every word. *)\n  Global Instance eq_lang : SemEquiv language := fun l1 l2 => forall w, l1 w <-> l2 w.\n  (** Languages may be ordered by containment. *)\n  Global Instance inf_lang : SemSmaller language := fun l1 l2 => forall w, l1 w -> l2 w.\n\n  Global Instance eq_lang_equiv : Equivalence (@sequiv _ eq_lang).\n  Proof. split;intro;unfold sequiv,eq_lang;firstorder. Qed.\n  Global Instance inf_lang_preorder : PreOrder (@ssmaller _ inf_lang).\n  Proof. split;intro;unfold ssmaller,inf_lang;firstorder. Qed.\n  Global Instance inf_lang_PartialOrder : PartialOrder sequiv (@ssmaller _ inf_lang).\n  Proof.\n    split.\n    - intro e;split;intro w;rewrite (e w);tauto.\n    - intros (h1&h2) w;split.\n      + apply h1.\n      + apply h2.\n  Qed.\n\n  (** The unit language only contains the empty word. *)\n  Global Instance unLang : Un language := (fun w => w=[]).\n  (** The empty language has no elements. *)\n  Global Instance zeroLang : Zero language := fun _ : list A => False.\n  (** From any two languages we may define their union and their concatenation. *)\n  Global Instance joinLang : Join language:= fun l1 l2 w => l1 w \\/ l2 w.\n  Global Instance prodLang : Product language := fun l1 l2 w => exists u v, w = u++v /\\ l1 u /\\ l2 v.\n\n  (** We may iterate the product on a language for any number of times. *)\n  Reserved Notation \" l ^{ n } \" (at level 35).\n  Fixpoint iter_lang n l : language :=\n    match n with\n    | 0 => 𝟭\n    | S n => l · (l ^{n})\n    end\n  where \"l ^{ n }\" := (iter_lang n l).\n\n  (** The Kleene star of a language is the union of its iterates. *)\n  Global Instance starLang : Star language := fun l w => exists n, l^{n} w.\n\n  (** * Compatibily of the operations with the ordering *)\n  (** Applying any of the operations we have defined to equivalent\n  arguments yields equivalent results. *)\n  Global Instance proper_joinLang : Proper (sequiv ==> sequiv ==> sequiv) join.\n  Proof. intros l m I l' m' I' w;unfold join,joinLang;rewrite (I w),(I' w);reflexivity. Qed.\n\n  Global Instance proper_prodLang : Proper (sequiv ==> sequiv ==> sequiv) prod.\n  Proof.\n    intros l m I l' m' I' w;unfold prod,prodLang.\n    setoid_rewrite (I _);setoid_rewrite (I' _);reflexivity. \n  Qed.\n      \n  Global Instance inf_lang_iter_lang n :\n    Proper (sequiv ==> sequiv) (iter_lang n).\n  Proof.\n    intros l1 l2 e;induction n.\n    - reflexivity.\n    - simpl;rewrite IHn,e;reflexivity.\n  Qed.\n\n  Global Instance proper_starLang : Proper (sequiv ==> sequiv) star.\n  Proof.\n    intros l1 l2 e w;split;intros (n&In);exists n;apply (inf_lang_iter_lang n e),In.\n  Qed.\n\n  (** * Algebraic properties *)\n  (** The containment order is the natural order stemming from [∪]. *)\n  Lemma joinOrderLang : relation_equivalence (leqA sequiv) ssmaller.\n  Proof.\n    unfold leqA;intros L M;split;intros I w.\n    - rewrite (I w);intro;now left.\n    - split.\n      + intro h;right;apply h.\n      + intros [h|h];[apply I|];apply h.\n  Qed.\n\n  (** The set of languages is a semi-ring. *)\n  Global Instance lang_Semiring : SemiRing language sequiv prod join un zero.\n  Proof.\n    split.\n    - split.\n      + typeclasses eauto.\n      + intros l1 l2 l3 w';split.\n        * intros (u&v1&->&h1&(v&w&->&h2)).\n          exists (u++v),w;rewrite app_ass;split;[|split].\n          -- reflexivity.\n          -- exists u,v;tauto.\n          -- tauto.\n        * intros (u1&w&->&(u&v&->&h1&h2)&h3).\n          exists u,(v++w);rewrite app_ass;split;[|split].\n          -- reflexivity.\n          -- tauto.\n          -- exists v,w;tauto.\n      + split;intros L w;(split;[intros (u&v&->&h1&h2)|intro h]).\n        * rewrite h1;simpl;tauto.\n        * exists [],w;simpl;split;[|split];tauto||reflexivity.\n        * rewrite h2,app_nil_r;assumption.\n        * exists w,[];rewrite app_nil_r;split;[|split];tauto||reflexivity.\n    - split;simpl.\n      + typeclasses eauto.\n      + intros l1 l2 l3;firstorder.\n      + split;intros l w;firstorder.\n    - intros l1 l2 w;firstorder.\n    - split;intros l w;firstorder.\n    - intros l1 l2 l3 w;split.\n      + intros (u&v&->&h1&[h2|h2]);[left|right];exists u,v;tauto.\n      + intros [h|h];destruct h as (u&v&->&h1&h2);exists u,v;firstorder.\n    - intros l1 l2 l3;split.\n      + intros (u&v&->&[h1|h1]&h2);[left|right];exists u,v;tauto.\n      + intros [h|h];destruct h as (u&v&->&h1&h2);exists u,v;firstorder.\n  Qed.\n  \n  Remark iter_lang_last n l : l^{S n} ≃ l^{n} · l.\n  Proof.\n    induction n;simpl.\n    - rewrite right_unit,left_unit;reflexivity.\n    - rewrite IHn at 1.\n      rewrite (mon_assoc l _ l);reflexivity.\n  Qed.\n\n  (** It is actually a Kleene algebra. *)\n  Global Instance lang_KA : KleeneAlgebra language sequiv.\n  Proof.\n    split.\n    - apply proper_starLang.\n    - apply lang_Semiring.\n    - intros l w;firstorder.\n    - intros L;apply joinOrderLang.\n      intros w [->|(u&v&->&h1&(n&h2))].\n      + exists 0;reflexivity.\n      + exists (S n),u,v;tauto.\n    - intros l1 l2 L.\n      apply joinOrderLang;apply joinOrderLang in L.\n      intros w (u&v&->&(n&h1)&h2).\n      revert u v h1 h2;induction n;intros.\n      + rewrite h1;simpl;assumption.\n      + destruct h1 as (u1&u2&->&h1&h1').\n        rewrite app_ass.\n        apply L.\n        exists u1,(u2++v);firstorder.\n    - intros l1 l2 L.\n      apply joinOrderLang;apply joinOrderLang in L.\n      intros w (u&v&->&h1&(n&h2)).\n      revert u v h1 h2;induction n;intros.\n      + rewrite h2,app_nil_r;assumption.\n      + rewrite (iter_lang_last n _ v) in h2.\n        destruct h2 as (v1&v2&->&h2&h2').\n        rewrite <- app_ass.\n        apply L.\n        exists (u++v1),v2;firstorder.\n  Qed.\n\n  (* begin hide *)\n  Global Instance join_semilattice_Lang : Semilattice language sequiv join := join_semilattice.\n  (* end hide *)\nEnd lang.\n", "meta": {"author": "monstrencage", "repo": "BracketAlgebra", "sha": "98eb06e3b55f9156d08a7ed2fc4eb74b97ee7322", "save_path": "github-repos/coq/monstrencage-BracketAlgebra", "path": "github-repos/coq/monstrencage-BracketAlgebra/BracketAlgebra-98eb06e3b55f9156d08a7ed2fc4eb74b97ee7322/language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.710621088509297}}
{"text": "Require Import CSet.\n\nDefinition nr_max X `{OrderedType X} (x y:X) :=\n  if [_lt x y] then y else x.\n\nArguments nr_max {X} {H} x y.\n\nInstance nr_max_eq_proper X `{OrderedType X}\n  : Proper (_eq ==> _eq ==> _eq) nr_max.\nProof.\n  unfold Proper, respectful; intros.\n  unfold nr_max. repeat cases; eauto.\n  exfalso. eapply NOTCOND. rewrite <- H1, <- H0. eauto.\n  exfalso. eapply NOTCOND. rewrite H1, H0. eauto.\nQed.\n\nLemma nr_max_sym X `{OrderedType X} (x y:X)\n  : nr_max x y === nr_max y x.\nProof.\n  unfold nr_max; repeat cases; eauto.\n  - eapply lt_trans_eq; eauto.\nQed.\n\nLemma nr_max_assoc X `{OrderedType X} (x y z:X)\n  : nr_max x (nr_max y z) === nr_max (nr_max x y) z.\nProof.\n  unfold nr_max.\n  decide (_lt y z); decide (_lt x y).\n  - assert (_lt x z) by (etransitivity; eauto).\n    repeat cases; eauto.\n  - repeat cases; eauto.\n  - repeat cases; eauto.\n    exfalso; eauto.\n  - repeat cases; eauto.\n    exfalso; eauto.\n    eapply le_trans; eauto.\nQed.", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Infra/OrderedTypeMax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7106210842352646}}
{"text": "Theorem plus_id_exercise : forall n m o : nat,\n    n = m -> m = o -> n + m = m + o.\nProof.\n  intros n m o. intros H1 H2.\n  rewrite H1. rewrite <- H2.\n  simpl. reflexivity.\nQed.\n", "meta": {"author": "zant", "repo": "gallina", "sha": "5259a6caf0c6abfb3be3437a74b42e8dee32d831", "save_path": "github-repos/coq/zant-gallina", "path": "github-repos/coq/zant-gallina/gallina-5259a6caf0c6abfb3be3437a74b42e8dee32d831/plus_id_exercise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7106210770788157}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Lia Relations.\n\nFrom Undecidability.Shared.Libs.DLW.Utils\n  Require Import utils_tac utils_list utils_nat finite.\n\nFrom Undecidability.Shared.Libs.DLW.Vec \n  Require Import pos vec.\n\nFrom Undecidability.FOL.TRAKHTENBROT\n  Require Import notations utils fol_ops fo_sig fo_terms fo_logic.\n\nImport fol_notations.\n\nRequire Import Undecidability.Shared.ListAutomation.\nImport ListAutomationHints.\n\nSet Implicit Arguments.\n\nLocal Infix \"∊\" := In (at level 70, no associativity).\nLocal Infix \"⊑\" := incl (at level 70, no associativity). \nLocal Notation ø := vec_nil.\n\n(* * First order theory of congruences *)\n\nSection congruence.\n\n  Variables (Σ : fo_signature) (ls : list (syms Σ)) (lr : list (rels Σ))\n            (X : Type) (M : fo_model Σ X)\n            (R : X -> X -> Prop).\n\n  Infix \"≈\" := R.\n\n  Definition Σ_congruence_wrt :=\n          (forall s, s ∊ ls -> forall v w, (forall p, vec_pos v p ≈ vec_pos w p) \n                                          -> fom_syms M s v ≈ fom_syms M s w)\n       /\\ (forall r, r ∊ lr -> forall v w, (forall p, vec_pos v p ≈ vec_pos w p) \n                                          -> fom_rels M r v <-> fom_rels M r w).\n\nEnd congruence.\n\nSection fol_congruence.\n\n  Variables (Σ : fo_signature) (e : rels Σ) (H_ae : ar_rels _ e = 2)\n            (ls : list (syms Σ)) (lr : list (rels Σ))\n            (He : e ∊ lr). \n\n  Notation 𝕋 := (fol_term Σ).\n  Notation 𝔽 := (fol_form Σ).\n\n  Notation \"x ≡ y\" := (@fol_atom Σ e (cast (x##y##ø) (eq_sym H_ae))) (at level 59).\n\n  Section encode_congruence.\n\n    Variable (X : Type) (M : fo_model Σ X).\n\n    Notation \"x ≈ y\" := (fom_rels M e (cast (x##y##ø) (eq_sym H_ae))).\n\n    Local Fact fol_sem_e x y φ : fol_sem M φ (x ≡ y) = fo_term_sem M φ x ≈ fo_term_sem M φ y.\n    Proof. simpl; f_equal; rewrite H_ae; simpl; auto. Qed.\n\n    Let fol_syms_e x y : fol_syms (x ≡ y) = fo_term_syms x ++ fo_term_syms y.\n    Proof. simpl; rewrite H_ae; simpl; auto; rewrite <- app_nil_end; auto. Qed.\n\n    Let fol_rels_e x y : fol_rels (x ≡ y) = e::nil.\n    Proof. auto. Qed.\n\n    Local Definition fol_vec_equiv n := fol_vec_fa (vec_set_pos (fun p : pos n => £(pos2nat p+n) ≡ £(pos2nat p))).\n\n    Local Fact fol_vec_equiv_syms n : fol_syms (fol_vec_equiv n) ⊑ nil.\n    Proof. \n      unfold fol_vec_equiv.\n      rewrite fol_syms_vec_fa.\n      intros x; rewrite in_flat_map.\n      intros (D & HD & H); revert H.\n      apply vec_list_inv in HD.\n      destruct HD as (p & ->). \n      rew vec; rewrite fol_syms_e; simpl; tauto.\n    Qed.\n\n    Local Fact fol_vec_equiv_rels n : fol_rels (fol_vec_equiv n) ⊑ e::nil.\n    Proof. \n      unfold fol_vec_equiv.\n      rewrite fol_rels_vec_fa.\n      intros x; rewrite in_flat_map.\n      intros (D & HD & H); revert H.\n      apply vec_list_inv in HD.\n      destruct HD as (p & ->); rew vec.\n    Qed.\n\n    Local Fact fol_vec_equiv_sem n φ : \n                fol_sem M φ (fol_vec_equiv n)\n            <-> (forall p : pos n, φ (pos2nat p+n) ≈ φ (pos2nat p)).\n    Proof.\n      unfold fol_vec_equiv.\n      rewrite fol_sem_vec_fa.\n      fol equiv; intros p; rew vec.\n      rewrite fol_sem_e; simpl; tauto.\n    Qed.\n\n    Section congr_syms.\n\n      Variable (s : syms Σ).\n\n      Let n := ar_syms _ s.\n\n      Let A := fol_vec_equiv n.\n      Let f : 𝕋 := in_fot s (vec_set_pos (fun p => £(pos2nat p))).\n      Let g : 𝕋 := in_fot s (vec_set_pos (fun p => £(pos2nat p+n))).\n      Let B := g ≡ f.\n\n      Let HrA : fol_syms A ⊑ nil.     Proof. apply fol_vec_equiv_syms. Qed.\n      Let HsA : fol_rels A ⊑ e::nil.  Proof. apply fol_vec_equiv_rels. Qed.\n\n      Let HrB : fol_syms B ⊑ s::nil.\n      Proof.\n        unfold B; simpl.\n        rewrite H_ae; unfold eq_rect_r.\n        intros x; do 2 (simpl; rewrite in_app_iff).\n        do 2 rewrite in_concat_iff.\n        intros [ | [ (l & Hx & H) | [ | [ (l & Hx & H) | [] ] ] ] ]; try tauto; revert Hx;\n          apply vec_list_inv in H; destruct H as (p & ->); rew vec.\n      Qed.\n\n      Let HsB : fol_rels B ⊑ e::nil.\n      Proof. simpl; cbv; tauto. Qed.\n\n      Local Definition congr_syms : 𝔽 := fol_mquant fol_fa n (fol_mquant fol_fa n (A ⤑  B)).\n\n      Local Fact congr_syms_syms : fol_syms congr_syms ⊑ s::nil.\n      Proof.\n        unfold congr_syms.\n        do 2 rewrite fol_syms_mquant.\n        rewrite fol_syms_bin.\n        apply incl_app; auto.\n      Qed.\n\n      Local Fact congr_syms_rels : fol_rels congr_syms ⊑ e::nil.\n      Proof.\n        unfold congr_syms.\n        do 2 rewrite fol_rels_mquant.\n        rewrite fol_rels_bin.\n        apply incl_app; auto.\n      Qed.\n\n      Local Definition congr_syms_spec φ : \n               fol_sem M φ congr_syms\n           <-> forall v w, (forall p, vec_pos v p ≈ vec_pos w p) -> fom_syms M s v ≈ fom_syms M s w.\n      Proof.\n        unfold congr_syms.\n        rewrite fol_sem_mforall.\n        fol equiv; intros v.\n        rewrite fol_sem_mforall.\n        fol equiv; intros w.\n        rewrite fol_sem_bin_fix.\n        fol equiv imp.\n        + unfold A; rewrite fol_vec_equiv_sem.\n          fol equiv; intros p; rew vec; simpl.\n          fol equiv; repeat f_equal.\n          * rewrite env_vlift_fix1, env_vlift_fix0; auto.\n          * rewrite env_vlift_fix0; auto.\n        + unfold B.\n          rewrite fol_sem_e; simpl. \n          apply fol_equiv_ext; repeat f_equal; \n            apply vec_pos_ext; intros p; rew vec; rew fot.\n          * rewrite env_vlift_fix1, env_vlift_fix0; auto.\n          * rewrite env_vlift_fix0; auto.\n      Qed.\n\n    End congr_syms.\n\n    Section congr_rels.\n\n      Variable (r : rels Σ).\n\n      Let n := ar_rels _ r.\n\n      Let A := fol_vec_equiv n.\n      Let B := @fol_atom Σ r (vec_set_pos (fun p => £(pos2nat p))).\n      Let C := @fol_atom Σ r (vec_set_pos (fun p => £(pos2nat p+n))).\n\n      Let HsA : fol_syms A ⊑ nil.     Proof. apply fol_vec_equiv_syms. Qed.\n      Let HrA : fol_rels A ⊑ e::nil.  Proof. apply fol_vec_equiv_rels. Qed.\n\n      Let HsB : fol_syms B ⊑ nil.\n      Proof.\n        unfold B; simpl.\n        intros x; rewrite in_flat_map.\n        intros (t & H & Ht); revert Ht.\n        apply vec_list_inv in H; destruct H as (p & ->); rew vec.\n      Qed.\n\n      Let HrB : fol_rels B ⊑ r::nil.\n      Proof. simpl; cbv; tauto. Qed.\n\n      Let HsC : fol_syms C ⊑ nil.\n      Proof. \n        unfold C; simpl.\n        intros x; rewrite in_flat_map.\n        intros (t & Ht & H); revert H.\n        apply vec_list_inv in Ht.\n        destruct Ht as (p & ->); rew vec; simpl; tauto.\n      Qed.\n\n      Let HrC : fol_rels C ⊑ e::r::nil.\n      Proof. simpl; cbv; tauto. Qed.\n\n      Local Definition congr_rels : 𝔽 := fol_mquant fol_fa n (fol_mquant fol_fa n (A ⤑  (C ↔ B))).\n\n      Local Fact congr_rels_syms : fol_syms congr_rels ⊑ nil.\n      Proof.\n        unfold congr_rels.\n        do 2 rewrite fol_syms_mquant.\n        repeat rewrite fol_syms_bin.\n        repeat (apply incl_app; auto).\n      Qed.\n\n      Local Fact congr_rels_rels : fol_rels congr_rels ⊑ e::r::nil.\n      Proof.\n        unfold congr_rels.\n        do 2 rewrite fol_rels_mquant.\n        repeat rewrite fol_rels_bin.\n        repeat (apply incl_app; auto).\n        intros x Hx; destruct (HrA _ Hx); try subst x; simpl; tauto.\n      Qed.\n\n      Local Definition congr_rels_spec φ : \n             fol_sem M φ congr_rels\n         <-> forall v w, (forall p, vec_pos v p ≈ vec_pos w p) \n                      -> fom_rels M r v <-> fom_rels M r w.\n      Proof.\n        unfold congr_rels.\n        rewrite fol_sem_mforall.\n        fol equiv; intros v.\n        rewrite fol_sem_mforall.\n        fol equiv; intros w.\n        simpl fol_sem at 1.\n        fol equiv.\n        + unfold A; rewrite fol_vec_equiv_sem.\n          fol equiv; intros p; rew vec; simpl.\n          fol equiv; repeat f_equal.\n          * rewrite env_vlift_fix1, env_vlift_fix0; auto.\n          * rewrite env_vlift_fix0; auto.\n        + fol equiv iff; fol equiv; f_equal;\n            apply vec_pos_ext; intros p; rew vec; rew fot.\n          * rewrite env_vlift_fix1, env_vlift_fix0; auto.\n          * rewrite env_vlift_fix0; auto.\n      Qed.\n\n    End congr_rels.\n\n    Local Definition fol_congruent : 𝔽 :=\n        fol_lconj (map congr_syms ls) \n      ⟑ fol_lconj (map congr_rels lr).\n\n    Local Fact fol_congruent_syms : fol_syms fol_congruent ⊑ ls.\n    Proof.\n      unfold fol_congruent.\n      rewrite fol_syms_bin.\n      repeat rewrite fol_syms_bigop; simpl.\n      repeat apply incl_app; try (cbv; tauto).\n      + intros s; rewrite in_flat_map.\n        intros (A & HA & H); revert HA H.\n        rewrite in_map_iff; intros (x & <- & Hx) H.\n        apply congr_syms_syms in H; revert H.\n        intros [ <- | [] ]; auto.\n      + intros r; rewrite in_flat_map.\n        intros (A & HA & H); revert HA H.\n        rewrite in_map_iff; intros (x & <- & Hx) H.\n        apply congr_rels_syms in H; revert H.\n        intros [].\n    Qed.\n\n    Local Fact fol_congruent_rels : fol_rels fol_congruent ⊑ lr.\n    Proof using He.\n      unfold fol_congruent.\n      rewrite fol_rels_bin.\n      repeat rewrite fol_rels_bigop; simpl.\n      repeat apply incl_app; try (cbv; tauto).\n      + intros s; rewrite in_flat_map.\n        intros (A & HA & H); revert HA H.\n        rewrite in_map_iff; intros (x & <- & Hx) H.\n        apply congr_syms_rels in H; revert H.\n        intros [ <- | [] ]; simpl; auto.\n      + intros x; simpl.\n        rewrite in_flat_map.\n        intros (A & HA & H); revert HA H.\n        rewrite in_map_iff; intros (y & <- & Hy) H.\n        apply congr_rels_rels in H; revert H.\n        intros [ | [ <- | [] ] ]; subst; auto.\n    Qed.\n\n    (* Σ_eq_congruence_spec encodes that ≈ is a congruence wrt to all\n        the symbols in ls and lr *)\n\n    Local Fact fol_congruent_spec φ :\n          fol_sem M φ fol_congruent \n      <-> Σ_congruence_wrt ls lr M (fun x y => x ≈ y).\n    Proof.\n      unfold fol_congruent.\n      rewrite fol_sem_bin_fix.\n      do 2 rewrite fol_sem_lconj.\n      fol equiv conj.\n      + split.\n        * intros H s Hs.\n          apply (congr_syms_spec _ φ), H, in_map_iff.\n          exists s; auto.\n        * intros H f; rewrite in_map_iff.\n          intros (s & <- & Hs).\n          apply congr_syms_spec, H; auto.\n      + split.\n        * intros H r Hr.\n          apply (congr_rels_spec _ φ), H, in_map_iff.\n          exists r; auto.\n        * intros H f; rewrite in_map_iff.\n          intros (r & <- & Hr).\n          apply congr_rels_spec, H; auto.\n    Qed.\n\n    Local Definition fol_equivalence := \n            (∀ £0 ≡ £0)\n          ⟑ (∀∀∀ £2 ≡ £1 ⤑ £1 ≡ £0 ⤑ £2 ≡ £0)\n          ⟑ (∀∀ £1 ≡ £0 ⤑ £0 ≡ £1).\n\n    Local Fact fol_equivalence_syms : fol_syms fol_equivalence = nil.\n    Proof.\n      unfold fol_equivalence.\n      repeat (rewrite fol_syms_bin || rewrite fol_syms_quant).\n      repeat rewrite fol_syms_e; auto.\n    Qed.\n\n    Local Fact fol_equivalence_rels : fol_rels fol_equivalence ⊑ e::nil.\n    Proof. simpl; cbv; tauto. Qed.\n  \n    Fact fol_equiv_spec φ : \n           fol_sem M φ fol_equivalence <-> equiv _ (fun x y => x ≈ y).\n    Proof.\n      unfold fol_equivalence.\n      repeat (rewrite fol_sem_bin_fix).\n      repeat fol equiv conj.\n      + rewrite fol_sem_quant_fix; apply forall_equiv; intro.\n        rewrite fol_sem_e; simpl; tauto.\n      + do 3 (rewrite fol_sem_quant_fix; apply forall_equiv; intro).\n        do 2 rewrite fol_sem_bin_fix.\n        do 3 rewrite fol_sem_e; simpl; tauto.\n      + do 2 (rewrite fol_sem_quant_fix; apply forall_equiv; intro).\n        rewrite fol_sem_bin_fix.\n        do 2 rewrite fol_sem_e; simpl; tauto.\n    Qed.\n\n    (* Σ_eq_congruence encodes the fact that ≈ is a congruence wrt to all\n        the symbols in ls and lr and this formula involve only the symbols\n        of ls and lr, under the assumption that e belongs to lr *)\n\n    Definition fol_congruence := \n          fol_congruent \n        ⟑ fol_equivalence.\n\n    Fact fol_congruence_syms : fol_syms fol_congruence ⊑ ls.\n    Proof.\n      unfold fol_congruence.\n      rewrite fol_syms_bin, fol_equivalence_syms, <- app_nil_end.\n      apply fol_congruent_syms.\n    Qed.\n\n    Fact fol_congruence_rels : fol_rels fol_congruence ⊑ lr.\n    Proof using He.\n      unfold fol_congruence.\n      rewrite fol_rels_bin.\n      apply incl_app.\n      + apply fol_congruent_rels.\n      + intros x Hx.\n        apply fol_equivalence_rels in Hx.\n        destruct Hx as [ | [] ]; subst; auto.\n    Qed.\n\n    Fact fol_sem_congruence φ : \n             fol_sem M φ fol_congruence\n         <-> Σ_congruence_wrt ls lr M (fun x y => x ≈ y)\n          /\\ equiv _ (fun x y => x ≈ y).\n    Proof.\n      fol equiv conj.\n      + apply fol_congruent_spec.\n      + apply fol_equiv_spec.\n    Qed.\n\n  End encode_congruence.\n\nEnd fol_congruence.\n\nArguments fol_congruence { _ _ }.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FOL/TRAKHTENBROT/fo_congruence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7105273970944053}}
{"text": "Set Implicit Arguments.\n\nRequire Import\n        Arith_base\n        Arith.Wf_nat\n        List\n        Omega\n        Wellfounded\n        Tactics.Tactics.\n\nImport ListNotations.\n\nSection STALIN.\n  Variable A : Set.\n  Variable leA : A -> A -> Prop.\n  Variable leA_dec : forall (x y : A), {leA x y} + {~ leA x y}.\n\n  Inductive sorted : list A -> Prop :=\n  | SortedNil : sorted []\n  | SortedSingle : forall x, sorted [x]\n  | SortedCons : forall y y' ys, leA y y' ->\n                            sorted (y' :: ys) ->\n                            sorted (y :: y' :: ys).\n\n  Hint Constructors sorted.\n\n  Inductive In (x : A) : list A -> Prop :=\n  | Here : forall xs, In x (x :: xs)\n  | There : forall ys y, In x ys -> In x (y :: ys).\n\n  Hint Constructors In.\n\n  Definition sub_list xs ys := forall x, In x xs -> In x ys.\n\n  Lemma sub_list_nil : forall ys, sub_list [] ys.\n  Proof.\n    intros ys ; unfold sub_list ; intros x H ; inversion H.\n  Qed.\n\n  Lemma sub_list_refl : forall xs, sub_list xs xs.\n  Proof.\n    intros xs ; unfold sub_list ; intros H ; auto.\n  Qed.\n\n  Lemma sub_list_skip : forall xs ys x, sub_list xs ys -> sub_list (x :: xs) (x :: ys).\n  Proof.\n    intros xs ys x H ; unfold sub_list in * ; intros z Hz.\n    inversion Hz ; clear Hz ; subst ; auto.\n  Qed.\n\n  Hint Resolve sub_list_nil sub_list_refl sub_list_skip.\n\n  Definition length_wf :=\n    @wf_inverse_image (list A) nat lt (@length A) lt_wf.\n\n  Definition stalin (xs : list A) :=\n    {ys | sorted ys /\\ sub_list ys xs}.\n\n  Lemma stalin_nil : stalin [].\n  Proof.\n    unfold stalin ; exists (@nil A) ; splits*.\n  Qed.\n\n  Lemma stalin_single : forall x, stalin [x].\n  Proof.\n    intros x ; unfold stalin ; exists [x] ; splits*.\n  Qed.\n\n  Hint Resolve stalin_nil stalin_single.\n\n  Definition stalin_sort_rec\n    : forall xs, (forall ys, length ys < length xs -> stalin ys) -> stalin xs.\n    refine (fun xs rec =>\n              match xs as xs' return xs = xs' -> stalin xs' with\n              | [] => fun _ => _\n              | [ _ ] => fun _ => _\n              | y :: y' :: ys' => fun _ =>\n                match leA_dec y y' with\n                | left _ =>\n                  match rec (y' :: ys') _ with\n                  | exist _ zs _ => _\n                  end\n                | right _  =>\n                  match rec (y :: ys') _ with\n                  | exist _ zs _ => exist _ zs _\n                  end\n                end\n              end (eq_refl xs)) ; substs* ; crush.\n    -\n      destruct zs ; crush.\n      unfolds ; exists (@nil A) ; crush.\n      unfolds. exists (a :: zs) ; crush.\n      unfolds. intros x H1. inverts* H1.\n    -\n      unfold sub_list in * ; crush.\n      specialize (H0 _ H1). inverts* H0.\n  Defined.\n\n  Definition stalin_sort : forall xs, stalin xs :=\n    (@well_founded_induction _ _ length_wf _ stalin_sort_rec).\n\nEnd STALIN.\n", "meta": {"author": "gustavo-depaula", "repo": "stalin-sort", "sha": "c052afd031b5396856b92c80140e161b66c1d237", "save_path": "github-repos/coq/gustavo-depaula-stalin-sort", "path": "github-repos/coq/gustavo-depaula-stalin-sort/stalin-sort-c052afd031b5396856b92c80140e161b66c1d237/coq/StalinSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.710508829007879}}
{"text": "(* File: QpositiveOrder.v\n * Part 1\n *)\nRequire Import Utf8.\nRequire Export Qpositive_order.\nRequire DecidableOrder.\n\nModule QDecidableOrderSig <: DecidableOrder.Sig.\n\nDefinition A := Qpositive.\nDefinition le := Qpositive_le.\nDefinition le_refl := Qpositive_le_refl.\nDefinition le_antisym := Qpositive_le_antisym.\nDefinition le_trans := Qpositive_le_trans.\nDefinition le_total := Qpositive_le_total.\nInfix \"≤\" := le : Qpos_scope.\nBind Scope Qpos_scope with Qpositive. \nOpen Scope Qpos_scope.\n\nLemma le_dec : ∀ x y, {x ≤ y} + {¬ x ≤ y}.\nProof.\nintros.\nunfold le, Qpositive_le.\ndecide equality.\nDefined.\n\nPrint Qpositive_le_total.\n\nEnd QDecidableOrderSig.", "meta": {"author": "margrit", "repo": "Code", "sha": "b3e89580b33732c23cdf4df8171d6c76ce9186e7", "save_path": "github-repos/coq/margrit-Code", "path": "github-repos/coq/margrit-Code/Code-b3e89580b33732c23cdf4df8171d6c76ce9186e7/Code/ModuleTest/Tutorial/QpositiveOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.8128673223709252, "lm_q1q2_score": 0.7105088270266293}}
{"text": "Require Import base.\n\nLemma swap_hyps {P Q R : Prop} : (P -> Q -> R) -> Q -> P -> R.\nProof. by intros PQR pQ pP; exact (PQR pP pQ). Qed.\n\nLemma hypothetical_syllogism : forall P Q R : Prop, (P -> Q) -> (Q -> R) -> (P -> R).\nProof.\n\tby intros P Q R PQ QR pP; exact (QR (PQ pP)).\nQed.\n\nLemma if_never_then_not_exist {T : Type} (P : T -> Prop)\n : (forall n : T, ~ (P n)) -> ~ (exists n : T, P n).\nProof.\n\tby intros H [n Pn]; exact (H n Pn).\nQed.\nLemma if_exist_then_exists {T : Type} (P : T -> Prop)\n : forall n : T, P n -> (exists n : T, P n).\nProof.\n\tby intros n Pn; exists n; exact Pn.\nQed.\nLemma if_not_exists_then_never {T : Type} (P : T -> Prop)\n : (forall n : T, P n \\/ ~ P n) -> ~ (exists n : T, P n) -> (forall n : T, ~ P n).\nProof.\n\tintros middle_excluded nex n.\n\tdestruct (middle_excluded n) as [Pn | nPn].\n\tby is_false (nex (if_exist_then_exists _ _ Pn)).\n\tby exact nPn.\nQed.\nLemma if_not_never_then_dont_not_exists {T : Type} (P : T -> Prop)\n : ~ (forall n : T, ~ P n) -> ~ ~ (exists n : T, P n).\nProof.\n\tintros nnever nexn.\n\tcontradict nnever.\n\tby intros n Pn; exact (nexn (if_exist_then_exists _ n Pn)).\nQed.\nLemma if_not_exists_then_not_never_false {T : Type} (P : T -> Prop)\n : ~ (exists n : T, P n) -> ~ ~ (forall n : T, ~ P n).\nProof.\n\tintros nex nalnot.\n\tby exact (if_not_never_then_dont_not_exists _ nalnot nex).\nQed.\n\nLemma transform_and_rarrow : forall A B C : Prop, (A /\\ B -> C) -> A -> B -> C.\nProof.\n\tby intros A B C H pA pB; apply H; split; [exact pA | exact pB].\nQed.\nLemma transform_rarrow_and : forall A B C : Prop, (A -> B -> C) -> A /\\ B -> C.\nProof.\n\tby intros A B C H [pA pB]; exact (H pA pB).\nQed.\n\n(* Attempt no 3 at a wlog implementation, pt.1/2 *)\nLemma modus_ponens {P Q : Prop} : P -> (P -> Q) -> Q.\nProof.\n\tby intros pP PQ; exact (PQ pP).\nQed.\nLemma modus_tonens {P Q : Prop} : (~ Q) -> (P -> Q) -> ~ P.\nProof.\n\tby intros nQ PQ pP; exact (nQ (PQ pP)).\nQed.\n\nLemma double_negation_elimination {P : Prop} : (P \\/ ~ P) -> ~ ~ P -> P.\nProof.\n\tby intros [pP | nP] nnP; [exact pP | exfalso; exact (nnP nP)].\nQed.\nLemma double_negation_introduction {P : Prop} : P -> ~ ~ P.\nProof.\n\tby intros pP nP; exact (nP pP).\nQed.\n\nLemma disjunctive_syllogism {P Q : Prop} : (P \\/ Q) -> ~ P -> Q.\nProof.\n\tintros [pP | pQ] nP.\n\tby is_false (nP pP).\n\tby exact pQ.\nQed.\n\n(* proj1 / proj2 *)\nLemma and_l {P Q : Prop} : (P /\\ Q) -> P. Proof. by intros [pP _]; exact pP. Qed.\nLemma and_r {P Q : Prop} : (P /\\ Q) -> Q. Proof. by intros [_ pQ]; exact pQ. Qed.\n\nLemma or_to_impl_l {P Q R : Prop} : (P -> Q) -> (P \\/ R) -> (Q \\/ R).\nProof.\n\tby intros PQ [pP | pR]; [left; apply PQ; exact pP | right; exact pR].\nQed.\nLemma or_to_impl_r {P Q R : Prop} : (P -> R) -> (Q \\/ P) -> (Q \\/ R).\nProof.\n\tby intros PR [pQ | pP]; [left; exact pQ | right; apply PR; exact pP].\nQed.\nLemma or_swap {P Q : Prop} : (P \\/ Q) -> Q \\/ P.\nProof. by intros [pP | pQ]; [right; exact pP | left; exact pQ]. Qed.\n\n(* Attempt no 3 at a wlog implementation, pt.2/2 *)\nTactic Notation \"without\" \"loss\" ident(n) \":\" constr(Q)\n\t:= lazymatch goal with\n\t\t| |- ?H => assert(n : Q)\n\t\t| _ => fail \"Invalid usage of 'without loss'.\"\n\tend.\nTactic Notation \"wlog\" ident(n) \":\" constr(Q)\n\t:= lazymatch goal with\n\t\t| |- ?H => assert(n : Q); swap 1 2\n\t\t| _ => fail \"Invalid usage of 'wlog'.\"\n\tend.\n", "meta": {"author": "rajdakin", "repo": "TIPE-ENS", "sha": "975130dc681a4f4cdeafab0e08e1e25333a63716", "save_path": "github-repos/coq/rajdakin-TIPE-ENS", "path": "github-repos/coq/rajdakin-TIPE-ENS/TIPE-ENS-975130dc681a4f4cdeafab0e08e1e25333a63716/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7105088203977388}}
{"text": "Require Import Frap Modeling Hoare Helpers.\n\n(* This logical formula is a proposition that described what it means\n   for an array to be sorted. The array in question here is\n   stored in the given heap, between indices [startI, endI) *)\nDefinition is_sorted (arr: heap) (startI: nat) (endI: nat): Prop :=\n  forall (i1 i2: nat), (lt startI i1) /\\ (lt i1 i2) /\\ (lt i2 endI) -> (le (arr $! i1) (arr $! i2)).\n\n(* The program for merging two arrays:\n   1. It assumes that two arrays are already provided on the heap, the \n   first between indices [0, len1) and the second between [len1, len1 + len2).\n   2. It writes out a merged sorted array to the end of the heap, so\n   that the first two arrays are not changed, and are followed by the sorted\n   array between indices [len1+len2, 2*(len1+len2) )\n   3. The assertion for the for loop is given as a parameter, to allow you\n   to define it without having to modify this program. The parameters to the\n   assertion will be len1 and len2. *)\nDefinition merge_program (len1 len2: nat) (I: nat -> nat -> assertion): cmd := (\n  (* i will be the current index in the merged resulting array *)\n  \"i\" <- (len1 + len2) ;;\n  \"i1\" <- 0 ;; (* current index in first array *)\n  \"i2\" <- len1 ;; (* current index in the second array *)\n\n  {{ I len1 len2 }} (* you will define this invariant *)\n  _while_ \"i\" < (len1 + len2 + len1 + len2) _loop_\n    (* standard merge: if arr1[i1] < arr2[i2], we add arr[i1] to the \n        end of the merged array and increment i1, if arr1[i1] >= arr[i2],\n        we choose arr[i2]. We must pay attention to special cases where\n        i1 or i2 are out of range. *)\n    _if_ \"i1\" < len1 _then_\n      _if_ \"i2\" < len1 + len2 _then_\n        _if_ *[\"i1\"] < *[\"i2\"] _then_\n          *[\"i\"] <- *[\"i1\"] ;;\n          \"i1\" <- \"i1\" + 1\n        _else_\n          *[\"i\"] <- *[\"i2\"] ;;\n          \"i2\" <- \"i2\" + 1\n        _done_\n      _else_\n        *[\"i\"] <- *[\"i1\"] ;;\n        \"i1\" <- \"i1\" + 1\n      _done_\n    _else_\n      (* i2 must be < len2 *)\n      *[\"i\"] <- *[\"i2\"] ;;\n      \"i2\" <- \"i2\" + 1\n    _done_\n  _done_) % cmd.\n\nModule Type Problem4.\n  (* Start off by proving this simple lemma:\n     if the array starting at startI and ending at endI is sorted,\n     then the sub array starting at startI and ending at endI' is also sorted,\n     where endI' <= endI. *)\n  Axiom is_sorted_smaller: forall (arr: heap) (startI endI endI': nat),\n    is_sorted arr startI endI -> endI' <= endI -> is_sorted arr startI endI'.\n\n  (* You must define the invariant for the while loop of the program above:\n     Remember, the invariant must:\n     1. Be true before the execution of the while loop start.\n     2. Remain true after each execution of the while loop.\n     3. Imply the post condition we desired (defined below) *)\n  Parameter merge_invariant: nat -> nat -> assertion.\n\n  (* The first version of correctness: the resulting array must be sorted,\n     given that the two input arrays are sorted *)\n  (* Helpers.v contain some helpful tactics that will automate a large chunk of\n     this proof, as well as some hints, read the comments there carefully *)\n  (* HINT: At some point in the proof, you will reach the body of the while loop,\n     using [ht1] or [ht] or manually applying the HtIf rule will spit out\n     4 goals for you, this is because we have 4 cases in the body of the loop:\n     1. i1 is out of range\n     2. i2 is out of range\n     3. both in range but the element at i1 < element at i2.\n     4. both in range but the element at i1 >= element at i2.\n     The goals produces at all these cases are very similar, and can be\n     solved by exactly the same proof if written generally enough. Consider\n     using the tactic [first_order] in these proofs! *)\n  (* HINT: In both the manual and automatic version of my solutions, I got a total\n     of 6 proof obligations.\n     1. for showing the invariant of the while loop is initally true.\n     2-5. the proof obligations corresponding to the cases above.\n     6. Obligation for showing that the loop invariant implies the post condition\n        when the loop is done. You will want to use 'is_sorted_smaller' here. *)\n  Axiom merge_correct: forall (len1 len2: nat),\n    {{ fun h v => is_sorted h 0 len1 /\\ is_sorted h len1 (len1 + len2) }}\n    merge_program len1 len2 merge_invariant\n    {{ fun h v => (is_sorted h (len1 + len2) (len1 + len2 + len1 + len2)) }}.\nEnd Problem4.\n\n", "meta": {"author": "KinanBab", "repo": "CS591K1-Labs", "sha": "d4569bf99d20c22cd56721024688cda247d1447f", "save_path": "github-repos/coq/KinanBab-CS591K1-Labs", "path": "github-repos/coq/KinanBab-CS591K1-Labs/CS591K1-Labs-d4569bf99d20c22cd56721024688cda247d1447f/homework1/Problem4/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.7105088150649569}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf3 : natural) (lf2 : natural) : natural :=\n  plus lf1 Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj113_coqofml_VwsWQD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715774, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7104298299382138}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus x (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj258_coqofml_IORYtu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7104298127719927}}
{"text": "(***********************************************************************)\n(**  * Connecting nominal and LN semantics *)\n(***********************************************************************)\n\n(** Our final goal is to show that the abstract nominal machine implements the\n    same semantics as the LN substitution-based small step relation.\n\n    We'll do this by proving that any time the abstract machine takes a step,\n    we can decode the machine configuration before and after the step to LN\n    expressions, and those expressions are either identical or related by the\n    LN step relation.\n\n<<\n                    machine_step\n             (h,t,s)  ------>  (h',t',s')            nominal terms\n                |                  |\n                | decode           | decode\n                v                  v\n                e       - - ->     e'           locally nameless terms\n                      step e e'\n                         or\n                        e = e'\n>>\n\n    This result is the [simulate_step] lemma near the end of this file.\n\n *)\n\nRequire Import String.\nRequire Import Metalib.Metatheory.\n\nRequire Import Stlc.Nominal.\nRequire Import Stlc.Lemmas.\n\nImport StlcNotations.\n\n(***********************************************************************)\n(** ** Translating nominal terms to LN terms *)\n(***********************************************************************)\n\n(** We decode named terms to LN terms through the use of the\n    [close_exp_wrt_exp] function. This function replaces all occurrences of\n    a given atom by a new bound variable.\n\n    This function is defined in the [Stlc.Lemmas] module and can be\n    automatically generated by LNgen.  *)\n\nFixpoint nom_to_exp (ne : n_exp) : exp :=\n  match ne with\n  | n_var x => var_f x\n  | n_app e1 e2 => app (nom_to_exp e1) (nom_to_exp e2)\n  | n_abs x e1 => abs (close_exp_wrt_exp x (nom_to_exp e1))\nend.\n\n(** We also define a translation from machine configurations to LN\n    terms. In this case we must substitute all definitions in the\n    heap through the terms and create all of the applications in\n    the stack. *)\n\nFixpoint apply_heap (h : heap) (e : exp) : exp  :=\n  match h with\n  | nil => e\n  | (x , e') :: h' => apply_heap h' ([x ~> nom_to_exp e'] e)\n  end.\n\n(* Note that the stack could have some heap definitions in it,\n   so we apply the substitutions in the heap there too. *)\n\nFixpoint apply_stack h (s : list frame) (e :exp) : exp :=\n  match s with\n  | nil => e\n  | n_app2 e' :: s' => apply_stack h s' (app e (apply_heap h (nom_to_exp e')))\n  end.\n\n(** The full decode function puts all of these parts together. *)\n\nDefinition decode (c:configuration) : exp  :=\n  match c with\n  | (h,e,s) => apply_stack h s (apply_heap h (nom_to_exp e))\n  end.\n\n\n(** Here's an example translation from the machine step demo. *)\n\nDefinition conf1 := ([(Y,n_var Z)], n_abs X (n_var X), [n_app2 (n_var Y)]).\n\nExample decode1 : decode conf1 = (app (abs (var_b 0)) (var_f Z)).\nProof. (* WORKINCLASS *)\n  default_simp.\n  unfold close_exp_wrt_exp.\n  default_simp.\nQed. (* /WORKINCLASS *)\n\n(***********************************************************************)\n(** ** Connecting free variable functions.                             *)\n(***********************************************************************)\n\n(** Here is the first result about our decoding: that the two free\n    variable functions agree.\n\n    In this part of the file, we will take advantage of automation\n    provided by the Lemmas module. In particular, this module defines a\n    database of rewriting hints (called [lngen]) that can be used to\n    automatically rewrite LN terms into simpler form. *)\n\nLemma fv_nom_fv_exp_eq : forall n,\n    fv_nom n [=] fv_exp (nom_to_exp n).\nProof.\n  induction n; intros; simpl; autorewrite with lngen; fsetdec.\nQed.\n\n(** As we prove new lemmas, we can also extend the hint database with new\n    rewritings. *)\n#[export] Hint Rewrite fv_nom_fv_exp_eq : lngen.\n#[export] Hint Resolve fv_nom_fv_exp_eq : lngen.\n\n\n(** The Metatheory library contains two powerful tactics for simplifying\n    goals:\n\n     - [default_steps]: repeat a bunch of simplifying steps, such as\n       simplifying the goal, inverting simple hypotheses, etc.\n\n     - [default_simp]: above plus case analysis for booleans and other sums\n\n    Below, we modify the behavior of these tactics by updating the following\n    two definitions, so that the [lngen] hint databases will be available.  *)\n\nLtac default_auto        ::= auto with lngen.\nLtac default_autorewrite ::= autorewrite with lngen.\n\n(** We also add a few more rewriting lemmas to the hint database to\n    automate our proofs. *)\n\n#[export] Hint Rewrite subst_exp_open_exp_wrt_exp : lngen.\n#[export] Hint Rewrite swap_size_eq : lngen.\n#[export] Hint Resolve le_S_n : lngen.\n\n(***********************************************************************)\n(** ** Decoded terms are locally closed *)\n(***********************************************************************)\n\n(** Next, we show that our decoding of nominal terms and\n    configurations produces locally closed LN terms.\n\n    Again, these proofs are highly automatable.\n*)\n\nLemma nom_to_exp_lc : forall t, lc_exp (nom_to_exp t).\nProof.\n  induction t; default_steps.\nQed.\n#[export] Hint Resolve nom_to_exp_lc : lngen.\n\nLemma apply_heap_lc : forall h e,\n    lc_exp e -> lc_exp (apply_heap h e).\nProof.\n  alist induction h; default_simp.\nQed.\n#[export] Hint Resolve apply_heap_lc : lngen.\n\n(** *** Exercise: [apply_stack_lc]\n\n    State and prove a lemma called [apply_stack_lc] and add it to the\n    [lngen] hint database so that the proof for [decode_lc] goes\n    through. *)\n\n(* SOLUTION *)\nLemma apply_stack_lc : forall s h e,\n    lc_exp e -> lc_exp (apply_stack h s e).\nProof.\n  induction s; try destruct a; default_simp.\nQed.\n#[export] Hint Resolve apply_stack_lc : lngen.\n(* /SOLUTION *)\n\nLemma decode_lc : forall c, lc_exp (decode c).\nProof.\n  intros [[h e] s]; default_simp.\n  (* ADMITTED *)\nQed. (* /ADMITTED *)\n\n(***********************************************************************)\n(** ** Properties of apply_heap *)\n(***********************************************************************)\n\n(** Since the heap is just an iterated substitution, it inherits\n    properties from [subst_exp].\n\n    Below, [alist induction] is a tactic from the metatheory library for\n    induction over association lists (such as the heap).  *)\n\nLemma apply_heap_abs : forall h e,\n  apply_heap h (abs e) = abs (apply_heap h e).\nProof.\n  alist induction h; default_simp.\nQed.\n\n#[export] Hint Rewrite apply_heap_abs : lngen.\n\nLemma apply_heap_app : forall h e1 e2,\n  apply_heap h (app e1 e2) = app (apply_heap h e1) (apply_heap h e2).\nProof.\n  alist induction h; default_simp.\nQed.\n\n#[export] Hint Rewrite apply_heap_app : lngen.\n\n\n(** *** Exercise: [apply_heap_open]\n\n    This function is the [apply_heap] analogue to\n    [subst_exp_open_exp_wrt_exp], commuting the heap-based\n    substitution with the [open_exp_wrt_exp] operation.\n *)\n\nLemma apply_heap_open : forall h e e0,\n    lc_exp e0 ->\n    apply_heap h (open e e0)  =\n       open (apply_heap h e) (apply_heap h e0).\nProof.\n(* ADMITTED *)\n  alist induction h; intros; default_simp.\nQed. (* /ADMITTED *)\n\n#[export] Hint Rewrite apply_heap_open : lngen.\n\n(** This last lemma \"unsimpl\"s the [apply_heap] function. *)\n\nLemma combine : forall h x e e',\n  apply_heap h ([x ~> nom_to_exp e] e') = (apply_heap ((x,e)::h) e').\nProof.\n  simpl. auto.\nQed.\n\n(***********************************************************************)\n(** ** Stacks as evaluation contexts                                    *)\n(***********************************************************************)\n\n(** Here is a quick lemma that uses the properties defined above.\n    It shows that the stack behaves like an *evaluation context*,\n    lifting a small-step reduction to a larger term.\n *)\n\n\nLemma apply_stack_cong : forall s h e e',\n    step e e' ->\n    step (apply_stack h s e) (apply_stack h s e').\nProof.\n  induction s; intros; try destruct a; default_simp.\nQed.\n\n\n\n(***********************************************************************)\n(** * Connecting \"freshening\" *)\n(***********************************************************************)\n\n\n(** The abstract machine uses the nominal [swap] operation to make sure\n    that the variables in abstractions are \"fresh\".  To be able prove that\n    this machine implements the step relation for LN terms, we need to\n    connect this operation to a LN version of \"freshening\".\n\n    The [swap_spec] lemma below states that connection. If a variable [y]\n    is \"fresh\", then substituting with it (in the LN representation) is the\n    same as swapping with it (in the nominal representation).\n\n<<\nLemma swap_spec : forall  n w y,\n    y `notin` fv_exp (nom_to_exp n) ->\n    w <> y ->\n    [w ~> var_f y] (nom_to_exp n) =\n    nom_to_exp (swap w y n).\n>>\n\n *)\n\n(** *** Exercise [close_exp_wrt_exp_freshen] *)\n\n(** The [swap_spec] proof depends on the following auxiliary lemma about the\n    close operation --- that we can equivalently rename the atom that\n    we are closing with. *)\n(* LATER *)\n(* SCW: Make LNgen generate this? *)\n(* /LATER *)\nLemma close_exp_wrt_exp_freshen : forall x y e,\n    y `notin` fv_exp e ->\n    close_exp_wrt_exp x e =\n    close_exp_wrt_exp y ([x ~> var_f y] e).\nProof.\n(* ADMITTED *)\n  intros x y e.\n  unfold close_exp_wrt_exp.\n  generalize 0 as k.\n  generalize e. clear e.\n  induction e; default_simp.\nQed. (* /ADMITTED *)\n\n(** One difficulty of [swap_spec] is that we need to use the induction\n    not on direct subterms, but on those that have had a swapping applied\n    to them. Swapping preserves the size of a nominal term, so we can\n    prove this result by induction on [m], a bound on the size of the\n    term.\n\n    The difficulty in this proof comes from the [n_abs] case. In this\n    case, the term is is of the form [n_abs x t] for some binding\n    variable [x]. We don't know much about [x]; it could be [w], or [y]\n    or some other variable. The first and last case are straightforward,\n    but the middle case causes difficulty: even though [x] is not free in\n    [n_abs x t], it _is_ free in [t]. Therefore, our induction hypothesis\n    doesn't apply.\n\n    To solve this problem, we need to generate a completely fresh\n    variable [z] for the binder, use the lemma above to replace [y] and\n    [w] with it, and then use the induction hypothesis.\n\n *)\nLemma swap_spec_aux : forall m t w y,\n    size t <= m ->\n    y `notin` fv_exp (nom_to_exp t) ->\n    w <> y ->\n    [w ~> var_f y] (nom_to_exp t) =\n    nom_to_exp (swap w y t).\nProof.\n  induction m; intros t w y SZ;\n  destruct t; simpl in *; try lia;\n  intros.\n  + unfold swap_var; default_simp.\n  + unfold swap_var; default_simp.\n    { (* w is the binder *)\n      rewrite subst_exp_fresh_eq; default_simp.\n      autorewrite with lngen in *.\n      rewrite (close_exp_wrt_exp_freshen w y); try fsetdec.\n      rewrite IHm; default_simp.  }\n    { (* y is the binder *)\n       autorewrite with lngen in *.\n       (* don't know anything about w or y. Either one could\n          appear in n. So our IH is useless now. *)\n       (* Let's pick a fresh variable z and use it with that. *)\n       pick fresh z for (\n              fv_exp (nom_to_exp t) \\u\n              fv_exp (nom_to_exp (swap w y t)) \\u {{w}} \\u {{y}}).\n\n       (* Use the lemma above to change out the closed variables with\n          the fresh one. *)\n       rewrite (close_exp_wrt_exp_freshen y z); auto.\n       rewrite (close_exp_wrt_exp_freshen w z); auto.\n\n       (* Push the outer substitution into the expression *)\n       rewrite subst_exp_close_exp_wrt_exp; auto.\n\n       (* Now use IH three times to rearrange the swaps and substitutions. *)\n       rewrite IHm with (y:=z); default_steps.\n       rewrite IHm with (y:=z); default_steps.\n       rewrite IHm with (y:=y); default_steps.\n\n       rewrite shuffle_swap; auto.\n\n       (* show freshness from last IH *)\n       rewrite <- fv_nom_fv_exp_eq.\n       apply fv_nom_swap.\n       rewrite fv_nom_fv_exp_eq.\n       fsetdec.\n    }\n    { (* neither w or y are binder in the abs case *)\n       rewrite <- IHm; default_steps.\n       autorewrite with lngen in *.\n       fsetdec.\n    }\n  + rewrite IHm; auto; try lia; try fsetdec.\n    rewrite IHm; auto; try lia; try fsetdec.\nQed.\n\nLemma swap_spec : forall t w y,\n    y `notin` fv_exp (nom_to_exp t) ->\n    w <> y ->\n    [w ~> var_f y] (nom_to_exp t) =\n    nom_to_exp (swap w y t).\nProof.\n  intros.\n  eapply swap_spec_aux with (t:=t)(m:=size t); auto.\nQed.\n\n(***********************************************************************)\n(** ** Connection for alpha-equivalence                                 *)\n(***********************************************************************)\n\n(** *** Challenge Exercise: [aeq_nom_to_exp]\n\n    Show that alpha-equivalence for the nominal representation is definitional\n    equality for LN terms.\n\n    This result is not necessary for the simulation lemmas below, but it\n    is another example of the a proof that takes advantage of the\n    [swap_spec] and [close_exp_wrt_exp_freshen] lemmas  above.\n\n    The second proof is much more challenging than the first and requires\n    lemmas from [Lemmas.v].\n\n*)\n\nLemma aeq_nom_to_exp : forall n1 n2, aeq n1 n2 -> nom_to_exp n1 = nom_to_exp n2.\nProof.\n  (* ADMITTED *)\n  induction 1; default_simp;\n  autorewrite with lngen in *.\n  - congruence.\n  - rewrite (close_exp_wrt_exp_freshen y x); auto.\n    rewrite swap_spec; auto.\n    congruence.\nQed. (* /ADMITTED *)\n\nLemma nom_to_exp_eq_aeq : forall n1 n2, nom_to_exp n1 = nom_to_exp n2 -> aeq n1 n2.\nProof.\n  (* ADMITTED *)\n  induction n1; intro n2; destruct n2; default_simp.\n  destruct (x == x0).\n  - subst. eauto with lngen.\n  - assert (FX : x `notin` fv_exp (nom_to_exp n2)).\n    { intro IN.\n      assert (x `in` fv_exp (nom_to_exp (n_abs x0 n2))).\n      { simpl. autorewrite with lngen. fsetdec. }\n      simpl in *.\n      rewrite <- H0 in H.\n      autorewrite with lngen in *.\n      fsetdec. }\n    eapply aeq_abs_diff; auto.\n    + autorewrite with lngen. auto.\n    + eapply IHn1.\n      rewrite <- swap_spec; eauto.\n      rewrite subst_exp_spec.\n      rewrite <- H0.\n      autorewrite with lngen.\n      auto.\nQed. (* /ADMITTED *)\n\n(***********************************************************************)\n(** * Scoped configurations                                            *)\n(***********************************************************************)\n\n(** Not all abstract machine steps simulate small-steps of the\n    substitution-based STLC.\n\n    For example, if the domain of the heap is not unique (i.e. it has\n    multiple definitions for the same variable) then its evaluation may\n    not produce expected results.\n\n    Similarly, if the [avoid] set that we pass to each machine step does\n    not include initial the free variables of the term, then we could\n    capture them in strange ways.\n\n    Therefore, we will restrict our correctness lemmas so that they only\n    apply to _well-scoped_ configurations; as defined below. *)\n\n\n(***********************************************************************)\n(** ** Scoped heaps                                                    *)\n(***********************************************************************)\n\n(** Well-scoped heaps behave \"telescopically\".  Each binding (x,e) added\n    to the heap is for a unique name x and the free variables of e are\n    bound in the remainder of the heap.\n\n    The scoping relation is parameterized by [D], an \"ambient\n    scope\". This will let us reason about the execution of the abstract\n    machine for terms with free variables. *)\n\nInductive scoped_heap (D : atoms) : heap -> Prop :=\n  | scoped_nil  : scoped_heap D nil\n  | scoped_cons : forall x e h,\n      x `notin` dom h \\u D ->\n      fv_exp (nom_to_exp e) [<=] dom h \\u D ->\n      scoped_heap D h ->\n      scoped_heap D ((x,e)::h).\n\n\n(** *** Recommended (Challenge) Exercise [apply_heap_get]\n\n    We can use [get] to look up expressions in the heap. However, to know that\n    we have the right result we need to know that the heap is well-scoped,\n    i.e.  that later bindings do not affect earlier ones.\n\n    State a lemma about the scoping of expressions that appear in the heap and\n    use it to finish the [apply_heap_get] lemma below.  *)\n\n(* SOLUTION *)\nLemma scoped_get : forall h D1 D2 x e,\n  scoped_heap D1 h ->\n  get x h = Some e ->\n  dom h \\u D1 [<=] D2 ->\n  fv_exp (nom_to_exp e) [<=] D2.\nProof.\n  induction 1; intros; default_simp.\n  fsetdec.\n  eapply IHscoped_heap; auto; fsetdec.\nQed.\n(* /SOLUTION *)\n\nLemma apply_heap_get :  forall h D x e,\n    scoped_heap D h ->\n    get x h = Some e ->\n    apply_heap h (var_f x) = apply_heap h (nom_to_exp e).\nProof.\n  induction 1; intros; default_simp.\n  - Case \"x is at the current heap location\".\n    rewrite subst_exp_fresh_eq; auto. fsetdec.\n  - Case \"x is later in the heap\".\n    rewrite subst_exp_fresh_eq; auto.\n    (* ADMITTED *)\n    rewrite scoped_get with (D2:= dom h\\u D ); default_simp; eauto.\nQed. (* /ADMITTED *)\n\n(***********************************************************************)\n(** ** Scoped stacks                                                    *)\n(***********************************************************************)\n\n(** We also care about the free variables that can appear in stacks. (We\n    will use this in the definition of well-scoped configurations below.)\n*)\n\nFixpoint fv_stack s :=\n  match s with\n    nil => {}\n  | n_app2 e :: s => fv_exp (nom_to_exp e) \\u fv_stack s\n  end.\n\n(** Stacks that are well-scoped can discard irrelevant bindings\n    from the heap. *)\n\n(* LATER *)\n(* TODO: how do we get inductive proofs to automatically\n   rewrite with the IH? *)\n(* /LATER *)\nLemma apply_stack_fresh_eq : forall s x e1 h ,\n    x `notin` fv_stack s ->\n    apply_stack ((x, e1) :: h) s = apply_stack h s.\nProof.\n  (* WORKINCLASS *)\n  induction s; intros; try destruct a; default_simp.\n  rewrite IHs; auto.\nQed. (* /WORKINCLASS *)\n\n\n(***********************************************************************)\n(** * Simulation                                                       *)\n(***********************************************************************)\n\n(** A scoped configuration is one where all free variables in terms\n    are either bound in the heap or come from [D] *)\nInductive scoped_conf : atoms -> configuration -> Prop :=\n  scoped_conf_witness : forall D h e s,\n    scoped_heap D h ->\n    fv_exp (nom_to_exp e) [<=] dom h \\u D ->\n    fv_stack s [<=] dom h \\u D  ->\n    scoped_conf D (h,e,s).\n\n(** *** Exercise [simulate_step]\n\n    After stepping through the simulation result below, finish the\n    missing case.\n\n*)\n\n(* Could be zero or one steps! *)\nLemma simulate_step : forall D h e s h' e' s' ,\n    machine_step D (h,e,s) = TakeStep _ (h',e',s') ->\n    scoped_conf D (h,e,s) ->\n    decode (h,e,s) = decode (h',e',s') \\/\n    step (decode (h,e,s)) (decode (h',e',s')).\nProof.\n  intros D h e s h' e' s' STEP SCOPE.\n  inversion SCOPE; subst; clear SCOPE.\n  simpl in *.\n  destruct (isVal e) eqn:?.\n  destruct s.\n  - inversion STEP.\n  - destruct f eqn:?.\n    + destruct e eqn:?; try solve [inversion STEP].\n      right.\n      destruct AtomSetProperties.In_dec.\n      * (* Application case, we need to generate a fresh\n           variable. *)\n\n        destruct atom_fresh.\n        inversion STEP; subst; clear STEP.\n\n        (* simplify the context. *)\n        simpl in *; autorewrite with lngen in *.\n        (* but not too much *)\n        rewrite combine.\n\n        (* x0 is a fresh variable, so we can drop it from\n           the heap in apply_stack. *)\n        rewrite apply_stack_fresh_eq; auto; try fsetdec.\n        (* before and after confs use the same stack. So we can step\n           congruently. *)\n        apply apply_stack_cong.\n\n        simpl.\n\n        (* pull the swap out as a freshening substitution *)\n        assert (x <> x0) by fsetdec.\n        rewrite <- swap_spec; auto; try fsetdec.\n        rewrite (subst_exp_spec _ _ x).\n        autorewrite with lngen; auto with lngen.\n        default_simp.\n        rewrite subst_exp_fresh_eq; autorewrite with lngen; auto.\n\n        (* in the form that matches step beta *)\n        apply step_beta; auto with lngen.\n        rewrite <- apply_heap_abs.\n        eapply apply_heap_lc.\n        auto with lngen.\n\n        rewrite H4. fsetdec.\n      * (* Homework: Application case, the variable in the abstraction\n           is fresh enough. *)\n        (* ADMIT *)\n        inversion STEP; subst; clear STEP;\n          simpl in *;\n          rewrite combine;\n          rewrite apply_stack_fresh_eq; auto; try fsetdec.\n        apply apply_stack_cong;\n          autorewrite with lngen in *;\n          simpl.\n        rewrite subst_exp_spec.\n        rewrite apply_heap_open; auto with lngen.\n\n        apply step_beta; auto with lngen.\n        rewrite <- apply_heap_abs.\n        eapply apply_heap_lc.\n        auto with lngen.\n        (* /ADMIT *)\n  - destruct e eqn:?; try solve [inversion STEP].\n    + (* Expression is a variable, lookup in heap *)\n      destruct (get x h) eqn:?; inversion STEP; subst; clear STEP.\n      left.\n      f_equal.\n      apply apply_heap_get with (D:= D); auto.\n    + (* Expression is an application, push arg on stack *)\n      inversion STEP; subst; clear STEP.\n      left.\n      simpl.\n      rewrite apply_heap_app.\n      auto.\n(* ADMITTED *) Qed. (* /ADMITTED *)\n\n(** *** Exercise [simulate_done]\n\n    Show that if the machine says [Done] then the LN term is a value.\n*)\n\nLemma simulate_done : forall D h e s,\n    machine_step (dom h \\u D) (h,e,s) = Done _ ->\n    scoped_conf D (h,e,s) ->\n    is_value (nom_to_exp e).\nProof. (* ADMITTED *)\n  intros.\n  inversion H0; subst.\n  simpl in *.\n  destruct (isVal e) eqn:?.\n  destruct s eqn:?.\n  - destruct e; simpl in Heqb; inversion Heqb.\n    econstructor; eauto.\n  - destruct f eqn:?.\n     + destruct e eqn:?; simpl; try solve [inversion H].\n       econstructor; eauto.\n  - destruct e; inversion H.\n    simpl in Heqb. destruct (get x h); inversion H.\nQed. (* /ADMITTED *)\n\n\n\n(** *** Challenge exercise [simulate_error]\n\n    Show that if the machine produces an error, the small step relation\n    is stuck.\n\n    This is a challenge exercise because you will need to figure out\n    at least one nontrivial auxiliary lemma.\n\n*)\n\n\n(* SOLUTION *)\nLemma apply_heap_get_none : forall x h,\n    get x h = None ->\n    apply_heap h (var_f x) = var_f x.\nProof.\n  intros.\n  alist induction h; simpl in *; auto.\n  default_simp.\nQed.\n\nLemma no_step_stack : forall s h e0,\n  not (is_value e0) ->\n  not (exists e0', step e0 e0') ->\n  not (exists e1, step (apply_stack h s e0) e1).\nProof.\n  induction s; intros; try destruct a; simpl in *; auto.\n  intros [e1 STEP].\n  assert (K1: not (exists e1', step (app e0 (apply_heap h (nom_to_exp n))) e1')).\n  { intros [e1' SS].\n    inversion SS. subst. simpl in *. contradiction.\n    subst. eauto. }\n  assert (K2: not (is_value (app e0 (apply_heap h (nom_to_exp n))))).\n  { simpl. auto. }\n  pose (K := IHs h _ K2 K1). clearbody K.\n  eauto.\nQed.\n(* /SOLUTION *)\n\nLemma simulate_error : forall D h e s,\n    machine_step (dom h \\u D) (h,e,s) = Error _ ->\n    scoped_conf D (h,e,s) ->\n    not (exists e0, step (decode (h,e,s)) e0).\nProof.\n(* ADMITTED *)\n  intros.\n  simpl in *.\n  destruct (isVal e) eqn:?.\n  destruct s.\n  - destruct e; try solve [inversion H]; simpl in Heqb; inversion Heqb.\n  - destruct f eqn:?.\n    destruct e eqn:?; try solve [inversion H]; simpl in Heqb; inversion Heqb.\n    destruct (AtomSetProperties.In_dec).\n    + destruct atom_fresh. inversion H.\n    + inversion H.\n  - destruct e; try solve [inversion H]; simpl in Heqb; inversion Heqb.\n    destruct (get x h) eqn:?. inversion H.\n    intros [e0 STEP].\n    simpl in *.\n    rewrite apply_heap_get_none in STEP; auto.\n    eapply no_step_stack with (e0 := var_f x); auto.\n       intros [e0' SS]. inversion SS. eauto.\nQed. (* /ADMITTED *)\n\n(***********************************************************************)\n\n(** *** Challenge exercise [machine_is_scoped]\n\n    Show that if the abstract machine is scoped, then any resulting\n    configurations are also scoped. *)\n\nLemma machine_is_scoped: forall D h e s conf',\n    machine_step (dom h \\u D) (h,e,s) = TakeStep _ conf' ->\n    scoped_conf D (h,e,s) ->\n    scoped_conf D conf'.\nProof.\n  (* ADMITTED *)\n  intros.\n  simpl in H.\n  inversion H0. subst.\n  destruct (isVal e) eqn:?.\n  destruct s eqn:?.\n  - inversion H.\n  - destruct f eqn:?.\n     + destruct e eqn:?; try solve [inversion H].\n       destruct AtomSetProperties.In_dec.\n       ++ destruct atom_fresh.\n          inversion H; subst; clear H.\n          simpl in *.\n          econstructor.\n            -- econstructor; eauto. fsetdec.\n            -- assert (x <> x0). fsetdec.\n               autorewrite with lngen in *.\n               rewrite <- swap_spec; try fsetdec.\n               rewrite fv_exp_subst_exp_upper.\n               simpl.\n               fsetdec.\n            -- simpl. fsetdec.\n       ++ inversion H; subst; clear H.\n          simpl in *.\n          autorewrite with lngen in *.\n          econstructor.\n          -- econstructor; eauto. fsetdec.\n          -- simpl.\n             assert ((union (add x (dom h)) D) [=] (add x (union (dom h) D))).\n             fsetdec. rewrite H.\n             rewrite <- H6.\n             eapply FSetDecideTestCases.test_Subset_add_remove.\n          -- simpl. fsetdec.\n  - destruct e eqn:?; try solve [inversion H].\n    destruct (get x h) eqn:?;\n    inversion H; subst; clear H.\n    + split. auto.\n      simpl in *.\n      eapply scoped_get; eauto.\n      fsetdec.\n      auto.\n    + simpl in *.\n    inversion H; subst; clear H.\n    econstructor.\n    auto.\n    fsetdec.\n    simpl. fsetdec.\nQed. (* /ADMITTED *)\n", "meta": {"author": "plclub", "repo": "metalib", "sha": "4ea92d82286cf66e54b4119b2bb2b039827204ab", "save_path": "github-repos/coq/plclub-metalib", "path": "github-repos/coq/plclub-metalib/metalib-4ea92d82286cf66e54b4119b2bb2b039827204ab/Stlc/Connect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7104125574894407}}
{"text": "(**\nThis file verifies some of the logic of Interval.hs from\nbisect-binary. <https://github.com/nomeata/bisect-binary/>\n\nIt is a variant of Proofs.v that uses the Function command to use [deferredFix] in a safer ay and get a nice induction lemma. I stopped after the proof for [union].\n*)\n\n\nRequire Import Intervals.\n\nRequire Import GHC.Base.\nRequire Import GHC.DeferredFix.\n\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.Sets.Powerset_facts.\nRequire Import Ensemble_facts.\nImport ListNotations.\nRequire Import Omega.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nDefinition goodI (i : Interval) : Prop :=\n  match i with I f t => (f < t)%Z end.\n\nFixpoint goodLIs (is : list Interval) (lb : Z) : Prop :=\n  match is with\n    | [] => True\n    | (I f t :: is) => (lb <= f)%Z /\\ (f < t)%Z /\\ goodLIs is t\n  end.\n\nDefinition good is := match is with\n  ival is => exists n, goodLIs is n end.\n\nDefinition range (f t : Z) : Ensemble Z :=\n  (fun z => (f <= z)%Z /\\ (z < t)%Z).\n\nDefinition semI (i : Interval) : Ensemble Z :=\n  match i with I f t => range f t end.\n\nFixpoint semLIs (is : list Interval) : Ensemble Z :=\n  match is with\n    | [] => Empty_set Z\n    | (i :: is) => Union Z (semI i) (semLIs is)\n  end.\n\nDefinition sem is := match is with\n  ival is => semLIs is end.\n  \n(* utils *)\n\nLemma range_empty (z : Z) :\n  (z <= 0)%Z -> range 0 z = Empty_set Z.\nProof.\n  intro H. apply Extensionality_Ensembles. split.\n  * intros z' H2.\n    unfold range, In in *.\n    contradict H2.\n    intuition.\n  * apply Included_Empty.\nQed.\n\nLemma goodLIs_mono : forall is lb lb', (lb' <= lb)%Z -> goodLIs is lb -> goodLIs is lb'.\nProof.\n  intros.\n  induction is.\n  * auto.\n  * destruct a. simpl in *. intuition.\nQed.\n\nLemma good_sem_lb:\n  forall is lb x,\n  goodLIs is lb -> In Z (semLIs is) x -> (lb <= x)%Z.\nProof.\n  intros.\n  unfold In in *.\n  induction is.\n  * simpl in *. exfalso. intuition.\n  * destruct a as [f t]; simpl in *; intuition.\n    destruct H0; unfold In, range in *; intuition.\n    apply IHis.\n    refine (goodLIs_mono _ _ _ _ H3). intuition.\n    auto.\nQed.\n\nLemma Intersection_range_range:\n  forall f1 t1 f2 t2,\n  Intersection Z (range f1 t1) (range f2 t2)\n  = range (Z.max f1 f2) (Z.min t1 t2).\nProof.\n  intros. apply Extensionality_Ensembles. split.\n  * intros x H1. destruct H1. unfold In, range in *.\n    rewrite Z.max_lub_iff.\n    rewrite Z.min_glb_lt_iff.\n    intuition.\n  * intros x H. constructor;\n    unfold In, range in *;\n    rewrite Z.max_lub_iff in *;\n    rewrite Z.min_glb_lt_iff in *;\n    intuition.\nQed.\n\nLemma Intersection_range_range_empty:\n  forall f1 t1 f2 t2,\n  (t1 <= f2)%Z \\/ (t2 <= f1)%Z ->\n  Intersection Z (range f1 t1) (range f2 t2) = Empty_set Z.\nProof.\n  intros. apply Extensionality_Ensembles. split.\n  * intros x H1. destruct H1. unfold In, range in *.\n    exfalso. intuition.\n  * intuition.\nQed.\n\nLemma Included_range_range:\n  forall f1 t1 f2 t2,\n  (f2 <= f1)%Z /\\ (t1 <= t2)%Z ->\n  Included Z (range f1 t1) (range f2 t2).\nProof.\n  intros.\n  intros x H1.\n  unfold In, range in *. intuition.\nQed.\n\nLemma Intersection_range_semLIs_empty:\n  forall f t is lb,\n  goodLIs is lb -> (t <= lb)%Z ->\n  Intersection Z (range f t) (semLIs is) = Empty_set Z.\nProof.\n  induction is; intros.\n  * apply Disjoint_Empty_set_r.\n  * destruct a as [f' t']. simpl in *.\n    rewrite Distributivity.\n    rewrite Intersection_range_range_empty.\n    rewrite Empty_set_zero.\n    apply IHis with (lb := t').\n    intuition.\n    intuition.\n    intuition.\nQed.\n\n(** proofs *)\n\n(** [nullIntervals] *)\n\nTheorem nullIntervals_good : good nullInterval.\nProof.\n  exists 0%Z. constructor.\nQed.\n\nTheorem nullIntervals_spec : sem nullInterval = Empty_set Z.\nProof. reflexivity. Qed.\n\n(** [fullIntervals] *)\n\nTheorem fullIntervals_good : forall z, good (fullIntervals z).\nProof.\n  intros.\n  unfold fullIntervals, mkInterval.\n  unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in *.\n  simpl in *.\n  destruct (Z.ltb_spec 0 z).\n  * exists 0%Z. unfold goodLIs. intuition.\n  * exists 0%Z. unfold goodLIs. intuition.\nQed.\n\nTheorem fullIntervals_spec (z : Z) : sem (fullIntervals z) = range 0 z.\nProof.\n  intros.\n  unfold fullIntervals, mkInterval.\n  unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in *.\n  simpl in *.\n  destruct (Z.ltb_spec 0 z).\n  * simpl. rewrite Union_commutative. rewrite Empty_set_zero. reflexivity.\n  * simpl. rewrite range_empty by assumption. reflexivity.\nQed.\n\n(** [isEmpty] *)\n\nLemma isEmpty_specL (is : list Interval) (lb : Z) (Hgood : goodLIs is lb) :\n  is = [] <-> (semLIs is = Empty_set Z).\nProof.\n  split; intros.\n  * subst. reflexivity.\n  * destruct is; try congruence.\n    destruct i.\n    simpl in *.\n    assert (In Z (range from to) from).\n    - unfold range. intuition.\n    - eapply Union_introl in H0.\n      rewrite H in H0.\n      apply Noone_in_empty in H0.\n      contradict H0.\nQed.\n\nTheorem isEmpty_spec (i : Intervals) (Hgood : good i) :\n  isEmpty i = true <-> (sem i = Empty_set Z).\nProof.\n  destruct i.\n  simpl.\n  simpl in Hgood; destruct Hgood.\n  unfold Foldable.null, Foldable.Foldable__list, Foldable.null__, Foldable.Foldable__list_null.\n  rewrite <- isEmpty_specL by eassumption.\n  destruct l; simpl; intuition; try congruence.\nQed.\n\n(** deferred fix *)\n\n(* Variant of the axiom that is safe to use. *)\nAxiom deferredFix2_safe_eq: forall {a b r} `{Default r} (f : (a -> b -> r) -> (a -> b -> r)) x,\n  f x = x -> deferredFix2 f = f (deferredFix2 f).\n  \n\n(** induction principle *)\n\nDefinition needs_reorder (is1 is2 : list Interval) : bool :=\n  match is1, is2 with\n    | (I f1 t1 :: _), (I f2 t2 :: _) => (t1 <? t2)%Z\n    | _, _ => false\n  end.\n\nDefinition size2 (is1_is2 : list Interval * list Interval) : nat := match is1_is2 with\n  (is1, is2) => (if needs_reorder is1 is2 then 1 else 0) + 2 * length is1 + 2 * length is2 end.\n\n(** Function definitions using Program Fixpoint. We use them only\n  to show that the axiomatized fixpoints in the code exist, and to\n  get a nice termination principle.\n  \n  The code was copied out of the argument to [deferredFix], and case splits pulled out of function arguments.\n  *)\n\nLtac solve_size2 :=\n  intros;\n  try match goal with [ H :  _<_ ?x ?y = true |- _ ] =>\n      unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in H;\n      destruct (Z.ltb_spec x y); try congruence\n  end;\n  repeat match goal with [ i : Interval |- _ ] => destruct i end;\n  match goal with [ |- context [size2 (?is1, ?is2)]] =>\n    try (lazymatch is1 with | _ :: _ => fail | _ => destruct is1 as [|[??]?] end);\n    try (lazymatch is2 with | _ :: _ => fail | _ => destruct is2 as [|[??]?] end)\n  end;\n  unfold size2; simpl in *;\n  repeat rewrite Z.ltb_irrefl;\n  repeat (\n    match goal with [ |- context [if (?x <? ?y)%Z then _ else _] ] => destruct (Z.ltb_spec x y) end\n  );\n  try omega.\n  \nRequire Import Recdef.\n\nFunction union_go_witness' (is1_is2 : list Interval * list Interval)  {measure size2 is1_is2} :list Interval :=\n  match is1_is2 with (arg_25__, arg_26__) =>\n     match arg_25__ with\n     | [] => match arg_26__ with\n             | [] => arg_25__\n             | _ :: _ => arg_26__\n             end\n     | i1 :: is1 =>\n         match arg_26__ with\n         | [] => arg_25__\n         | i2 :: is2 =>\n            if _<_ (to i1) (to i2)\n            then union_go_witness' (i2 :: is2, i1 :: is1)\n            else if _>_ (from i1) (to i2)\n               then i2 :: union_go_witness' (i1 :: is1, is2)\n               else match i1 with | I _ to_29__ =>\n                 union_go_witness' ( I (min (from i1) (from i2)) to_29__ :: is1, is2) end\n         end\n     end\n   end.\nProof. all: solve_size2. Qed.\nDefinition union_go_witness (is1 is2 : list Interval) : list Interval :=\n  union_go_witness' (is1, is2).\n\nDefinition union_go_f :=\n  fun (go : list Interval -> list Interval -> list Interval)\n               (arg_25__ arg_26__ : list Interval) =>\n             match arg_25__ with\n             | [] =>\n                 match arg_26__ with\n                 | [] => arg_25__\n                 | _ :: _ => arg_26__\n                 end\n             | i1 :: is3 =>\n                 match arg_26__ with\n                 | [] => arg_25__\n                 | i2 :: is4 =>\n                     let f' := min (from i1) (from i2) in\n                     let j_32__ :=\n                       go\n                         (match i1 with\n                          | I _ to_29__ => I f' to_29__\n                          end :: is3) is4 in\n                     let j_33__ :=\n                       if _>_ (from i1) (to i2) : bool\n                       then i2 :: go (i1 :: is3) is4\n                       else j_32__ in\n                     if _<_ (to i1) (to i2) : bool\n                     then go (i2 :: is4) (i1 :: is3)\n                     else j_33__\n                 end\n             end.\n\nLemma union_go_eq :\n  deferredFix2 union_go_f = union_go_f (deferredFix2 union_go_f).\nProof.\n  apply deferredFix2_safe_eq with (x := union_go_witness).\n  extensionality is1. extensionality is2.\n  unfold union_go_f.\n  unfold union_go_witness at 4.\n  rewrite union_go_witness'_equation.\n  unfold union_go_witness.\n  repeat (match goal with [ |- context [match ?scrut with | _ => _ end ] ] => destruct scrut end;simpl);\n  reflexivity.\nQed.\n\nDefinition union_go_ind P : _ :=\n  (union_go_witness'_ind (fun is1_is2 _ => match is1_is2 with (is1, is2) => P is1 is2 end)).\n\n\n(** [union] *)\n\nLemma union_good : forall (is1 is2 : Intervals),\n    good is1 -> good is2 -> good (union is1 is2).\nProof.\n  intros.\n  destruct is1 as [is1], is2 as [is2].\n  destruct H as [lb1 H1] , H0 as [lb2 H2].\n  exists (Z.min lb1 lb2).\n  fold union_go_f.\n  apply (goodLIs_mono _ _ _ (Z.le_min_l lb1 lb2)) in H1.\n  apply (goodLIs_mono _ _ _ (Z.le_min_r lb1 lb2)) in H2.\n  generalize dependent (Z.min lb1 lb2). clear lb1 lb2.\n  (* ready for induction *)\n  refine (union_go_ind (fun is1 is2 => forall lb : Z,\n  goodLIs is1 lb -> goodLIs is2 lb -> goodLIs (deferredFix2 union_go_f is1 is2) lb) _ _ _ _ _ _ (is1, is2)); clear is1 is2;\n  intros is1_is2_ is1 is2.\n  * intros ???;subst.\n    intros lb H1 H2.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    simpl. trivial.\n  * intros ?? i2 is2' ?; subst. intros lb H1 H2.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    assumption.\n  * intros ?? i1 is1' ?; subst. intros lb H1 H2.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    assumption.\n  * rename is1 into is1', is2 into is2'.\n    intros ???????? IH lb H1 H2; subst.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    simpl.\n    rewrite e2.\n    unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in *.\n    unfold GHC.Base.op_zg__, Ord_Integer___, op_zg____ in *.\n    apply IH; try assumption.\n  * rename is1 into is1', is2 into is2'.\n    intros ????????? IH lb H1 H2; subst.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    rewrite e2, e3.\n    unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in *.\n    unfold GHC.Base.op_zg__, Ord_Integer___, op_zg____ in *.\n    destruct i1 as [f1 t1], i2 as [f2 t2].\n    simpl in *.\n    repeat match goal with [ H :  (?x <? ?y)%Z = true |- _ ] =>\n      unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in H;\n      destruct (Z.ltb_spec x y); try congruence\n    end.\n    intuition.\n  * rename is1 into is1', is2 into is2'.\n    intros ???????????? IH lb H1 H2; subst.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    rewrite e2, e3.\n    unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in *.\n    unfold GHC.Base.op_zg__, Ord_Integer___, op_zg____ in *.\n    destruct i2 as [f2 t2].\n    simpl in *.\n    repeat match goal with [ H :  (?x <? ?y)%Z = _ |- _ ] =>\n      unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in H;\n      destruct (Z.ltb_spec x y); try congruence\n    end.\n    intuition.\n    apply IH.\n    rewrite Z.min_glb_iff in *. intuition.\n    rewrite  Z.min_lt_iff in *. intuition.\n    refine (goodLIs_mono _ _ _ _ H7). intuition.\nQed.\n\nLemma union_spec : forall (is1 is2 : Intervals),\n    good is1 -> good is2 -> sem (union is1 is2) = Union Z (sem is1) (sem is2).\nProof.\n  intros.\n  destruct is1 as [is1], is2 as [is2].\n  destruct H as [lb1 H1] , H0 as [lb2 H2].\n  unfold union.\n  fold union_go_f.\n  apply (goodLIs_mono _ _ _ (Z.le_min_l lb1 lb2)) in H1.\n  apply (goodLIs_mono _ _ _ (Z.le_min_r lb1 lb2)) in H2.\n  generalize dependent (Z.min lb1 lb2). clear lb1 lb2.\n    \n  (* ready for induction *)\n  refine (union_go_ind (fun is1 is2 => forall lb : Z,\n  goodLIs is1 lb -> goodLIs is2 lb -> semLIs (deferredFix2 union_go_f is1 is2) = Union Z (semLIs is1) (semLIs is2)) _ _ _ _ _ _ (is1, is2)); clear is1 is2;\n  intros is1_is2_ is1' is2'.\n  * intros ??? lb H1 H2;subst.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    simpl.  rewrite Empty_set_zero. reflexivity.\n  * intros ?? i2 is2 ? lb H1 H2; subst.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    simpl in *. intuition.\n  * intros ?? i1 is1 ?; subst. intros lb H1 H2.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    simpl in *. rewrite  Empty_set_zero_l. intuition.\n  * intros ???????? IH lb H1 H2; subst.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    simpl.\n    rewrite e2.\n    unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in *.\n    unfold GHC.Base.op_zg__, Ord_Integer___, op_zg____ in *.\n    rewrite IH with (lb:=lb).\n      + intuition.\n      + assumption.\n      + assumption.\n  * intros ????????? IH lb H1 H2; subst.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    rewrite e2, e3.\n    unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in *.\n    unfold GHC.Base.op_zg__, Ord_Integer___, op_zg____ in *.\n    destruct i1 as [f1 t1], i2 as [f2 t2].\n    simpl in *.\n    repeat match goal with [ H :  (?x <? ?y)%Z = true |- _ ] =>\n      unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in H;\n      destruct (Z.ltb_spec x y); try congruence\n    end.\n    rewrite IH with (lb:=t2).\n    + simpl. intuition.\n      (* reorder Union *)\n      repeat rewrite Union_associative.\n      rewrite Union_commutative.\n      repeat rewrite Union_associative.\n      do 2 f_equal.\n      rewrite Union_commutative.\n      reflexivity.\n    + simpl in *. intuition.\n    + simpl. intuition.\n  * intros ???????????? IH lb H1 H2; subst.\n    rewrite union_go_eq. unfold union_go_f at 1.\n    rewrite e2, e3.\n    unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in *.\n    unfold GHC.Base.op_zg__, Ord_Integer___, op_zg____ in *.\n    destruct i2 as [f2 t2].\n    simpl in *.\n    repeat match goal with [ H :  (?x <? ?y)%Z = _ |- _ ] =>\n      unfold GHC.Base.op_zl__, Ord_Integer___, op_zl____ in H;\n      destruct (Z.ltb_spec x y); try congruence\n    end.\n    rewrite IH with (lb:=lb).\n    + simpl.\n      rewrite union_reorder.\n      rewrite Union_associative.\n      f_equal.\n      (* range and min *)\n      apply Extensionality_Ensembles. split.\n      ** intros z' H3.\n         unfold range, In in *.\n         rewrite Z.min_le_iff in *.\n         intuition.\n         left. unfold In. intuition.\n         destruct (Z.ltb_spec z' t2).\n         right. unfold In. intuition.\n         left. unfold In. intuition.\n      ** intros z' H3.\n         apply Union_inv in H3.\n         unfold range, In in *.\n         rewrite Z.min_le_iff in *.\n         intuition.\n    + simpl. intuition.\n      rewrite Z.min_glb_iff in *. intuition.\n      rewrite  Z.min_lt_iff in *. intuition.\n    + simpl. intuition.\n      refine (goodLIs_mono _ _ _ _ H7). intuition.\nQed.\n\n", "meta": {"author": "antalsz", "repo": "hs-to-coq", "sha": "cd62a35fff22cb6022a8935581746df658264f0f", "save_path": "github-repos/coq/antalsz-hs-to-coq", "path": "github-repos/coq/antalsz-hs-to-coq/hs-to-coq-cd62a35fff22cb6022a8935581746df658264f0f/examples/intervals/Proofs_Function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7104125476619374}}
{"text": "(**\n「リストは自分自身のfoldr関数として定義される」につついて\n=========\n\n2014_05_11 @suharahiromichi\n *)\n\n(**\n# はじめに\n\nTAPL（参考文献1.)には、p.47とp.275の2箇所に渡って、\n「リストは自分自身のfoldr関数として定義される」\nと書かれている。\nしかし、前後の説明を読んでもこの一文の意味することはよくわからなかった。\n\nまた、別なところ（同 p.277）で、\n「(System Fは)fixに頼ることなく純粋な言語でソート関数のようなものが書ける…」\nと極めて重要なことが書いてある。\nこれは、チャーチ数やリストのチャーチ表現がそのような性質を\n持つのであって、System Fはそれらを扱える（型付けをすることができる）\nと理解するべきなのだろう。\n\n以上のことを納得するために、数やリストについて、\n\n1. Inductiveな定義\n2. チャーチ表現\n3. fold関数\n\n\nの関係を調べてみる。証明はCoq SSRefelctで行う。\n*)\n(**\nこの文章のソースコードは、以下にあります。\n\nhttps://github.com/suharahiromichi/coq/blob/master/ssr/ssr_church_number.v\n*)\n\nRequire Import ssreflect ssrbool ssrnat.\n\n(**\n# チャーチ数\n  *)\n\n(**\n## チャーチ数(CNat)\n*)\nDefinition CNat := forall X, (X -> X) -> X -> X.\n\nDefinition C0 : CNat := fun X => fun s : X -> X =>\n                                   fun z : X => z.\nDefinition C1 : CNat := fun X => fun s : X -> X =>\n                                   fun z : X => s z.\nDefinition C2 : CNat := fun X => fun s : X -> X =>\n                                   fun z : X => s (s z).\nDefinition CSucc : CNat -> CNat :=\n  fun n : CNat => fun X =>\n                    fun s : X -> X =>\n                      fun z : X => s (n X s z).\nEval compute in CSucc C0.\n\n(**\n## InductiveなNatの定義\n*)\nInductive Nat : Type :=\n| O\n| S of Nat.\n\n(**\n## CNatとNatの間の変換\n\n### CNatをNatに変換する関数\n*)\nDefinition CNat2Nat (c : CNat) : Nat :=\n  c Nat S O.\n\nEval compute in CNat2Nat C2.\n(**\n= S (S O) : Nat\n\nこれはチャーチ数cに、Sをfoldしているとみることもできる。\n *)\n\n(**\n### Fold関数\n\nInductiveに定義したNatに対しては、Foldを定義しなければならない。\n*)\nFixpoint foldNat (X : Type) (s : X -> X) (z : X) (n : Nat) : X :=\n  match n with\n    | O => z\n    | S n' => s (foldNat X s z n')\n  end.\n\nCheck foldNat.\n(**\n : forall X : Type, (X -> X) -> X -> Nat -> X\n *)\n\n(**\n### NatをCNatに変換する関数\n*)\nDefinition Nat2CNat (n : Nat) : CNat :=\n  fun X =>\n    fun s : X -> X =>\n      fun z : X => foldNat X s z n.\n\nEval compute in Nat2CNat (S (S O)).\n(**\n = fun (X : Type) (s : X -> X) (z : X) => s (s z) : CNat\n\nInductiveに定義された整数nに、sをFoldし、そのsをλ抽象すると、チャーチ数が得られる。\n *)\n\n(**\n## 証明\n\n### C0とOが同じ、CSuccとSの結果が同じになることの証明\n*)\nTheorem CNat_Nat_zero :\n  CNat2Nat C0 = O.\nProof.\n    by [].\nQed.\n\nTheorem CNat_Nat_succ :\n  forall c n,\n    CNat2Nat c = n -> CNat2Nat (CSucc c) = S n.\nProof.\n  rewrite /CNat2Nat /CSucc.\n    by move=> c n ->.\nQed.\n\n(**\n### CNat2NatとNat2CNatで元に戻ることの証明\n*)\nTheorem CNat2Nat_Nat2CNat :\n  forall n : Nat, CNat2Nat(Nat2CNat n) = n.\nProof.\n  rewrite /CNat2Nat /Nat2CNat.\n  elim.\n    by [].\n  by move=> /= n0 ->.\nQed.\n\n(**\n# 自然数のリスト\n\n要素の自然数は、SSReflectのnatの定義を使う。\n*)\n(**\n## チャーチ表現\n*)\nDefinition CListNat := forall R, (nat -> R -> R) -> R -> R.\n\nDefinition CNil : CListNat :=\n  fun R => fun c : nat -> R -> R =>\n             fun n : R => n.                (* [] *)\nDefinition CL1 : CListNat :=\n  fun R => fun c : nat -> R -> R =>\n             fun n : R => c 1 n.            (* [1] *)\nDefinition CL2 : CListNat :=\n  fun R => fun c : nat -> R -> R =>\n             fun n : R => c 1 (c 2 n).      (* [1,2] *)\nDefinition CL3 : CListNat :=\n  fun R => fun c : nat -> R -> R =>\n             fun n : R => c 1 (c 2 (c 3 n)). (* [1,2,3] *)\nDefinition CCons : nat -> CListNat -> CListNat :=\n  fun hd : nat =>\n    fun tl : CListNat =>\n      fun R =>\n        fun c : nat -> R -> R =>\n          fun n : R => c hd (tl R c n).\nEval compute in CCons 1 CNil.\n\n(**\n## Inductiveな定義\n*)\nInductive ListNat : Type :=\n| Nil\n| Cons of nat & ListNat.\n\n(**\n## clistとlistの間の変換\n\n### clistをlistに変換する関数\n*)\nDefinition clist2list (c : CListNat) : ListNat :=\n  c ListNat Cons Nil.\n\nEval compute in clist2list CL2.\n(**\n= Cons 1 (Cons 2 Nil) : ListNat\n\nclist2listは、チャーチ表現のリストcに、Consをfoldrしているとみることもできる。\n *)\n\n(**\n### Foldr関数\n\nInductiveに定義したlistに対しては、Foldを定義しなければならない。\n*)\nFixpoint foldr (R : Type) (c : nat -> R -> R) (n : R) (l : ListNat) : R :=\n  match l with\n    | Nil => n\n    | Cons x l' => c x (foldr R c n l')\n  end.\n\nCheck foldr.\n(**\n : forall R : Type, (nat -> R -> R) -> R -> ListNat -> R\n *)\n\n(**\n### listをclistに変換する関数\n*)\nDefinition list2clist (l : ListNat) : CListNat :=\n  fun R =>\n    fun c : nat -> R -> R =>\n      fun n : R => foldr R c n l.\n\nEval compute in list2clist (Cons 1 (Cons 2 Nil)).\n(**\n = fun (R : Type) (c : nat -> R -> R) (n : R) => c 1 (c 2 n) : CListNat\n\nInductiveに定義されたリストlに、cをFoldrし、そのcをλ抽象すると、\nチャーチ表現で表したリストが得られる。\n *)\n\n(**\n## 証明\n\n### CNilとnilが同じ、CConsとConsの結果が同じになることの証明\n*)\nTheorem clist_list_nil :\n  clist2list CNil = Nil.\nProof.\n    by [].\nQed.\n\nTheorem clist_list_cons :\n  forall c l n,\n    clist2list c = l ->\n    clist2list (CCons n c) = Cons n l.\nProof.\n  rewrite /clist2list /CCons.\n    by move=> c l n ->.\nQed.\n\n(**\n## clist2listとlist2clistで元に戻ることの証明\n*)\n\nTheorem clist2list_list2clist :\n  forall l : ListNat, clist2list(list2clist l) = l.\nProof.\n  rewrite /clist2list /list2clist.\n  elim.\n    by [].\n  by move=> /= n l ->.\nQed.\n\n(**\n# まとめ\n\nわかったこと。\nチャーチ数やリストのチャーチ表現は、それ自身にFoldの機能を持っていること。\nまた、Inductiveに定義したnatやlistは、Fold関数によってチャーチ表現に変換できること。\n\n参考文献2.は、無限大のチャーチ数と不動点演算子の関係をHaskellで\n論じたもので、FoldNatの定義などを参考にさせていただいた。\n*)\n\n(**\n# 参考文献\n\n1. Pierce、住井 監訳「型システム入門 プログラミング言語と型の理論」オーム社\n2. 酒井 「不動点演算子はチャーチ数での無限大?」 http://msakai.jp/d/?date=20100628\n*)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/ssr/ssr_church_number.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895098628499, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7104125409642207}}
{"text": "(* Exercise 65 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\n(* On a finite domain, existence implies a disjunction\n   over different elements; this is less trivial *)\n\nHypothesis Domain : exists x1 : D, exists x2 : D, exists x3 : D,\n  (forall x : D, (x = x1 \\/ x = x2 \\/ x = x3)) /\\ \n  ~(x1 = x2) /\\ ~(x1 = x3) /\\ ~(x2 = x3).\n\nHypothesis P_holds : exists x : D, P x.\n\nTheorem exercise_065 : exists x1 : D, exists x2 : D, exists x3 : D, (P x1 \\/ P x2 \\/ P x3) /\\ ~(x1 = x2)\n  /\\ ~(x1 = x3) /\\ ~(x2 = x3).\nProof.\nexi_e (exists x1 : D, exists x2 : D, exists x3 : D,\n  (forall x : D, (x = x1 \\/ x = x2 \\/ x = x3)) /\\ \n  ~(x1 = x2) /\\ ~(x1 = x3) /\\ ~(x2 = x3)) a a1.\nhyp Domain.\nexi_e (exists x2 : D, exists x3 : D,\n  (forall x : D, (x = a \\/ x = x2 \\/ x = x3)) /\\ \n  ~(a = x2) /\\ ~(a = x3) /\\ ~(x2 = x3)) b a2.\nhyp a1.\nexi_e (exists x3 : D,\n  (forall x : D, (x = a \\/ x = b \\/ x = x3)) /\\ \n  ~(a = b) /\\ ~(a = x3) /\\ ~(b = x3)) c a3.\nhyp a2.\nexi_i a.\nexi_i b.\nexi_i c.\ncon_i.\nexi_e (exists x:D, P x) d a4.\nhyp P_holds.\ndis_e (d = a \\/ d = b \\/ d = c) a5 a5.\nall_e (forall x:D, x = a \\/ x = b \\/ x = c) d.\ncon_e1 (a <> b /\\ a <> c /\\ b <> c).\nhyp a3.\ndis_i1.\nreplace a with d.\nhyp a4.\ndis_e (d = b \\/ d = c) a6 a6.\nhyp a5.\ndis_i2.\ndis_i1.\nreplace b with d.\nhyp a4.\ndis_i2.\ndis_i2.\nreplace c with d.\nhyp a4.\ncon_e2 (forall x:D, x = a \\/ x = b \\/ x = c).\nhyp a3.\nQed.\n\n\n\n\n\n\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred065.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7104096777473583}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nInductive natural : Type :=  Zero : natural| Succ : natural -> natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) : natural\n           := match plus_arg0, plus_arg1 with\n              | Zero, n => n\n              | Succ n, m => Succ (plus n m)\n              end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) : natural\n           := match mult_arg0, mult_arg1 with\n              | Zero, n => Zero\n              | Succ n, m => plus (mult n m) m\n              end.\n\nFixpoint fac (fac_arg0 : natural) : natural\n           := match fac_arg0 with\n              | Zero => Succ Zero\n              | Succ n => mult (fac n) n\n              end.\n\nFixpoint qfac (qfac_arg0 : natural) (qfac_arg1 : natural) : natural\n           := match qfac_arg0, qfac_arg1 with\n              | Zero, n => n\n              | Succ n, m => qfac n (mult m n)\n              end.\n\nLemma plus_succ : forall (x y : natural), plus x (Succ y) = Succ (plus x y).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_assoc : forall (x y z : natural), plus (plus x y) z = plus x (plus y z).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_zero : forall (x : natural), plus x Zero = x.\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma plus_commut : forall (x y : natural), plus x y = plus y x.\nProof.\nintros.\ninduction x.\n- rewrite plus_zero. reflexivity.\n- simpl. rewrite plus_succ. rewrite IHx. reflexivity.\nQed.\n\nLemma mult_zero : forall (x : natural), mult x Zero = Zero.\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma mult_succ : forall (x y : natural), plus (mult x y) x = mult x (Succ y).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite plus_succ. rewrite plus_assoc. rewrite (plus_commut y x). rewrite <- plus_assoc. rewrite IHx. rewrite plus_succ. reflexivity.\nQed.\n\nLemma mult_commut : forall (x y : natural), mult x y = mult y x.\nProof.\nintros.\ninduction x.\n- rewrite mult_zero. reflexivity.\n- simpl. rewrite IHx. rewrite mult_succ. reflexivity.\nQed.\n\nLemma distrib : forall (x y z : natural), mult (plus x y) z = plus (mult x z) (mult y z).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite IHx. rewrite plus_assoc. rewrite (plus_commut (mult y z) z). rewrite <- plus_assoc. reflexivity.\nQed.\n\nLemma mult_assoc : forall (x y z : natural), mult (mult x y) z = mult x (mult y z).\nProof.\nintros.\ninduction x.\n- reflexivity.\n- simpl. rewrite distrib. rewrite IHx. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : natural) (y : natural), eq (mult (fac x) y) (qfac x y).\nProof.\ninduction x.\n- reflexivity.\n- intros. simpl. rewrite <- IHx. lfind. Admitted.\n              \n\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/modifications/quickchick_fails/test186_goal84/lfind_goal84.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7103897657275038}}
{"text": "Require Import QArith. \nRequire Import Arith.\nRequire Import Reals.\nRequire Import Psatz.\nRequire Import QArith.Qminmax.\nRequire Lra.\n\nRequire Import List.\n\nStructure box :=\n{\np1 :Q*Q;\np2 :Q*Q;p3 :Q*Q;p4 :Q*Q;\np1p4 : fst p1 = fst p4;\np1p2 : snd p1 = snd p2;\np2p3 : fst p2 = fst p3;\np3p4 : snd p3 = snd p4;\ncwp1p2 : fst p1 < fst p2;\ncwp3p4 : fst p4 < fst p3;\ncwp1p4 : snd p4 < snd p1;\ncwp2p3 : snd p3 < snd p2;\n}.\n\nDefinition point_in_box (p: Q*Q )( b :box) :=\nfst p < fst (p3 b) /\\ fst p > fst (p1 b)\n/\\ snd p < snd (p1 b) /\\ snd p > snd (p3 b).\n\n(* waybelow relation based on set inclusion*)\nDefinition box_waybelow (A  B : box) :=\n(point_in_box (p1 B) A) /\\ (point_in_box (p3 B) A). \n\nLemma waybelow_point_inclusion: forall A B:box , forall p:Q*Q , \n(box_waybelow A B ) -> (point_in_box p B ) -> (point_in_box p A).\nProof.\nintros.\nunfold box_waybelow in *.\nunfold point_in_box in *.\ndestruct H. destruct H. destruct H2. destruct H3.\ndestruct H1. destruct H5. destruct H6. destruct H0. destruct H8. destruct H9.\nsplit. lra. \nsplit. lra.\nsplit.  lra.  lra.\nQed.\n\nLemma waybelow_trans : forall A B C : box,\nbox_waybelow A B -> box_waybelow B C -> box_waybelow A C.\nProof.\nintros.\nunfold box_waybelow .\ndestruct H0.\nsplit. apply (waybelow_point_inclusion   A B (p1 C)). \n-exact H.\n-exact H0.\n-apply (waybelow_point_inclusion   A B (p3 C)).\n  ++exact H.\n  ++exact H1.\nQed.", "meta": {"author": "mjdavari", "repo": "Convex-Hull", "sha": "a1eb7159140cbe6fc5b937a090f1ae623ce3990a", "save_path": "github-repos/coq/mjdavari-Convex-Hull", "path": "github-repos/coq/mjdavari-Convex-Hull/Convex-Hull-a1eb7159140cbe6fc5b937a090f1ae623ce3990a/PointBox.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.7103897651370157}}
{"text": "From Coq Require Import Relations RelationClasses Setoid.\nRequire Export MoreOrders STDPP_compat.\n\n(* begin snippet ComparableDef *)\nClass Compare (A:Type) := compare : A -> A -> comparison.\n\nClass Comparable {A:Type} (lt: relation A) (cmp : Compare A) :=\n{\n  comparable_sto :> StrictOrder lt;\n  comparable_comp_spec : forall (a b : A), CompSpec eq lt a b (compare a b)\n}.\n(* end snippet ComparableDef *)\n\n#[export] Hint Mode Compare ! : typeclass_instances.\n#[export] Hint Mode Comparable ! - - : typeclass_instances.\n\nSection Comparable.\n\n  Context {A: Type}\n          {lt: relation A}\n          {cmp: Compare A} `{!Comparable lt cmp}.\n  #[local] Notation le := (leq lt). \n\n  #[deprecated(note=\"use StrictOrder_Transitive\")]\n   Notation lt_trans := StrictOrder_Transitive (only parsing).\n\n  #[deprecated(note=\"use StrictOrder_Irreflexive\")] \n   Notation lt_irrefl := StrictOrder_Irreflexive (only parsing).\n  \n  (* Relation Lt *)\n  Lemma lt_not_gt (a b: A): lt a b -> ~lt b a.\n  Proof.\n    intros Hlt Hgt.\n    apply StrictOrder_Irreflexive with a; now transitivity b.\n  Qed.\n\n  Lemma lt_not_ge (a b: A): lt a b -> ~ le b a.\n  Proof.\n    intros Hlt Hle.\n    apply le_lt_eq in Hle as [Hgt | Heq].\n    - now apply lt_not_gt in Hlt.\n    - subst; now apply StrictOrder_Irreflexive in Hlt.\n  Qed.\n  \n  Lemma compare_lt_iff (a b: A):\n    compare a b = Lt <-> lt a b.\n  Proof.\n    pose proof (comparable_comp_spec a b) as [Heq | H | H];\n    split; intro; subst; try easy.\n    - now apply StrictOrder_Irreflexive  in H.\n    - now apply lt_not_gt in H.\n  Qed.\n\n  Lemma compare_lt_trans (a b c: A):\n    compare a b = Lt -> compare b c = Lt -> compare a c = Lt.\n  Proof.\n    intros Hab Hbc.\n    apply compare_lt_iff in Hab, Hbc; apply compare_lt_iff.\n    now transitivity b. \n  Qed.\n\n  Lemma compare_lt_irrefl (a: A): ~compare a a = Lt.\n  Proof.\n    intro H.\n    now apply compare_lt_iff, StrictOrder_Irreflexive in H.\n  Qed.\n\n  Lemma compare_eq_iff (a b: A): compare a b = Eq <-> a = b.\n  Proof.\n    pose proof (comparable_comp_spec a b) as [Heq | H | H];\n    split; intro; subst; try easy;\n    now apply StrictOrder_Irreflexive in H.\n  Qed.\n\n\n  Lemma compare_refl (a: A):\n    compare a a = Eq.\n  Proof.\n    pose proof (comparable_comp_spec a a) as [H | H | H].\n    1: reflexivity.\n    all: now apply StrictOrder_Irreflexive in H.\n  Qed.\n\n  Lemma compare_eq_trans (a b c: A):\n    compare a b = Eq -> compare b c = Eq -> compare a c = Eq.\n  Proof.\n    intros Hab Hbc.\n    apply compare_eq_iff in Hab, Hbc; apply compare_eq_iff.\n    now subst.\n  Qed.\n\n\n  (* Relation Gt *)\n  Lemma compare_gt_iff (a b: A):\n    compare a b = Gt <-> lt b a.\n  Proof.\n    pose proof (comparable_comp_spec a b) as [Heq | Hlt | Hgt];\n    split; intro; subst; try easy.\n    - now apply StrictOrder_Irreflexive in H.\n    - now apply lt_not_gt in H.\n  Qed.\n\n\n  Lemma compare_gt_irrefl (a: A):\n    ~compare a a = Gt.\n  Proof.\n    intros H.\n    now apply compare_gt_iff, StrictOrder_Irreflexive in H.\n  Qed.\n\n  Lemma compare_gt_trans (a b c: A):\n    compare a b = Gt -> compare b c = Gt -> compare a c = Gt.\n  Proof.\n    intros Hab Hbc.\n    apply compare_gt_iff in Hab, Hbc; apply compare_gt_iff.\n    now transitivity b.\n  Qed.\n\n\n  Lemma compare_lt_not_gt (a b: A):\n    compare a b = Lt -> ~ compare a b = Gt.\n  Proof.\n    intros Hlt Hgt.\n    apply compare_lt_iff in Hlt.\n    apply compare_gt_iff in Hgt.\n    now apply lt_not_gt in Hgt.\n  Qed.\n\n\n  Lemma compare_gt_not_lt (a b: A):\n    compare a b = Gt -> ~ compare a b = Lt.\n  Proof.\n    intros Hgt Hlt.\n    apply compare_lt_iff in Hlt.\n    apply compare_gt_iff in Hgt.\n    now apply lt_not_gt in Hgt.\n  Qed.\n\n  Lemma le_refl (a: A): le a a.\n  Proof.\n    apply le_lt_eq; now right.\n  Qed.\n\n  Lemma compare_le_iff_refl (a: A):\n    le a a <-> compare a a = Eq.\n  Proof.\n    split; intros H.\n    - apply compare_refl.\n    - apply le_refl.\n  Qed.\n\n  Lemma compare_le_iff (a b: A):\n    le a b <-> compare a b = Lt \\/ compare a b = Eq.\n  Proof.\n    split; intro H.\n    - apply le_lt_eq in H as [Hlt | Heq].\n      * left; now apply compare_lt_iff.\n      * right; now apply compare_eq_iff.\n    - apply le_lt_eq; destruct H as [Hlt | Heq].\n      * left; now apply compare_lt_iff.\n      * right; now apply compare_eq_iff in Heq.\n  Qed.\n\n\n  Lemma compare_ge_iff (a b: A):\n    le b a <-> compare a b = Gt \\/ compare a b = Eq.\n  Proof.\n    rewrite compare_le_iff, compare_lt_iff, compare_gt_iff, !compare_eq_iff;\n      intuition.\n  Qed.\n\n  Lemma le_trans (a b c: A):\n    le a b -> le b c -> le a c.\n  Proof.\n    rewrite !le_lt_eq.\n    intros [Hlt_ab | Heq_ab] [Hlt_bc | Heq_bc].\n    - left; now transitivity b.\n    - left; now subst.\n    - left; now subst.\n    - right; now subst.\n  Qed.\n\n  Lemma le_lt_trans (a b c: A):\n    le a b -> lt b c -> lt a c.\n  Proof.\n    intros Hle_ab Hlt_bc.\n    apply le_lt_eq in Hle_ab as [Heq_ab | Hlt_ab].\n    - now transitivity b.\n    - now subst.\n  Qed.\n\n\n  Lemma lt_le_trans (a b c: A):\n    lt a b -> le b c -> lt a c.\n  Proof.\n    rewrite le_lt_eq.\n    intros Hlt_ab [Heq_bc | Hlt_bc].\n    - now transitivity b.\n    - now subst.\n  Qed.\n\n  Lemma lt_incl_le (a b: A):\n    lt a b -> le a b.\n  Proof.\n    intro H.\n    apply le_lt_eq; now left.\n  Qed.\n\n  Lemma le_not_gt (a b: A):\n    le a b -> ~ lt b a.\n  Proof.\n    intros Hlt Hle.\n    now apply lt_not_ge in Hlt.\n  Qed.\n\n  (* Max lemmas *)\n  #[using=\"All\"]\n  Definition max (a b : A): A :=\n  match compare a b with\n  | Gt => a\n  | _ => b\n  end.\n\n  Lemma max_dec (a b: A):\n    max a b = a \\/ max a b = b.\n  Proof.\n    unfold max.\n    pose proof (comparable_comp_spec a b) as [Hab | Hab | Hab]; tauto.\n  Qed.\n\n  Lemma max_comm (a b: A):\n    max a b = max b a.\n  Proof.\n    unfold max.\n    pose proof (comparable_comp_spec a b) as [Hab | Hab | Hab];\n    pose proof (comparable_comp_spec b a) as [Hba | Hba | Hba].\n    5,9: now apply lt_not_gt in Hab.\n    all: easy.\n  Qed.\n\n\n  Lemma max_ge_a (a b: A):\n    le b a <-> max a b = a.\n  Proof.\n    unfold max.\n    split; intro H.\n    - apply compare_ge_iff in H as [Hlt | Heq].\n      + now rewrite Hlt.\n      + rewrite Heq. now apply compare_eq_iff in Heq.\n    - pose proof (comparable_comp_spec a b) as [Hab | Hab | Hab].\n      + subst. apply le_refl.\n      + exfalso.\n        apply compare_lt_iff in Hab.\n        rewrite Hab in H; subst; rewrite compare_refl in Hab; discriminate. \n      + now apply lt_incl_le.\n  Qed.\n\n  Lemma max_ge_b (a b: A):\n    le a b <-> max a b = b.\n  Proof.\n    unfold max;\n      rewrite le_lt_eq, <- compare_lt_iff, <- compare_eq_iff.\n    split; intro H.\n    - now destruct H as [-> | ->].\n    - pose proof (comparable_comp_spec a b) as [Hab | Hab | Hab].\n      + now right.\n      + now left.\n      + exfalso.\n        apply compare_gt_iff in Hab.\n        rewrite Hab in H.\n        subst.\n        now apply compare_gt_irrefl in Hab.\n  Qed.\n\n\n  Lemma max_refl (a: A):  max a a = a.\n  Proof.\n    apply max_ge_a, le_refl.\n  Qed.\n\n  Lemma le_max_a (a b: A): le a (max a b).\n  Proof.\n    unfold max.\n    pose proof (comparable_comp_spec a b) as [Heq | Hlt | Hgt].\n    1,3: subst; now apply le_refl.\n    now apply lt_incl_le.\n  Qed.\n\n  Lemma le_max_b (a b: A): le b (max a b).\n  Proof.\n    rewrite max_comm; apply le_max_a.\n  Qed.\n\n  #[global] Instance max_assoc : Assoc eq max. \n  Proof.\n    intros a b c; unfold max. \n    pose proof (comparable_comp_spec a b) as [Hab | Hab | Hab];\n    pose proof (comparable_comp_spec b c) as [Hbc | Hbc | Hbc];\n    pose proof (comparable_comp_spec a c) as [Hac | Hac | Hac];\n    subst; try rewrite compare_refl; try easy.\n    - now apply lt_not_gt in Hbc.\n    - now apply lt_not_gt in Hab.\n    - exfalso.\n      assert (Hca: lt a c) by (now transitivity b). \n      now apply (lt_not_gt _ _  Hac Hca).\n    - now apply compare_lt_iff in Hab as ->.\n    - now apply compare_lt_iff in Hab as ->.\n    - now apply compare_lt_iff in Hab as ->.\n    - now apply lt_not_gt in Hbc.\n    - exfalso.\n      assert (Hca : lt c a) by (now transitivity b). \n      apply lt_not_gt in Hac; now apply Hac. \n    - now apply compare_gt_iff in Hab as ->.\n  Qed.\n\n\n  (* Min lemmas*)\n  #[using=\"All\"]\n  Definition min (a b :A): A :=\n  match compare a b with\n  | Lt => a\n  | _ => b\n  end.\n\n  Lemma min_max_iff (a b: A):\n    min a b = a <-> max a b = b.\n  Proof.\n    unfold min, max.\n    pose proof (comparable_comp_spec a b) as [Hab | Hab | Hab]; subst; easy.\n  Qed.\n\n  Lemma min_comm (a b: A):\n    min a b = min b a.\n  Proof.\n    unfold min.\n    pose proof (comparable_comp_spec a b) as [Hab | Hab | Hab];\n        pose proof (comparable_comp_spec b a) as [Hba | Hba | Hba].\n        5,9: now apply lt_not_gt in Hab.\n        all: easy.\n  Qed.\n\n  Lemma min_dec (a b: A):\n    min a b = a \\/ min a b = b.\n  Proof.\n    rewrite min_max_iff, min_comm, min_max_iff, max_comm.\n    now apply max_dec.\n  Qed.\n\n\n\n  Lemma min_le_ad (a b: A):\n    le a b <-> min a b = a.\n  Proof.\n    rewrite min_max_iff.\n    now apply max_ge_b.\n  Qed.\n\n  Lemma min_le_b (a b: A):\n    le b a <-> min a b = b.\n  Proof.\n    rewrite min_comm, min_max_iff.\n    now apply max_ge_b.\n  Qed.\n\n  Lemma min_refl (a:A):\n    min a a = a.\n  Proof.\n    rewrite min_max_iff.\n    apply max_refl.\n  Qed.\n\n \n\n  Lemma le_min_a (a b: A):\n    le (min a b) a.\n  Proof.\n    unfold min.\n    pose proof (comparable_comp_spec a b) as [Heq | Hlt | Hgt]; subst.\n    1,2: now apply le_refl.\n    now apply lt_incl_le.\n  Qed.\n\n  Lemma le_min_bd (a b: A):\n    le (min a b) b.\n  Proof.\n    rewrite min_comm.\n    apply le_min_a.\n  Qed.\n\n  #[global] Instance  min_assoc: Assoc eq min.\n  Proof.\n    red ; intros a b c;  unfold min.\n    pose proof (comparable_comp_spec a b) as [Hab | Hab | Hab];\n    pose proof (comparable_comp_spec b c) as [Hbc | Hbc | Hbc];\n    pose proof (comparable_comp_spec a c) as [Hac | Hac | Hac];\n    subst; try rewrite compare_refl; try easy.\n    - now apply lt_not_gt in Hbc.\n    - now apply lt_not_gt in Hab.\n    - now apply compare_lt_iff in Hab as ->.\n    - exfalso.\n      apply (StrictOrder_Transitive a b) in Hbc.\n      2: assumption.\n      now apply lt_not_gt in Hbc.\n    - now apply lt_not_gt in Hab.\n    - now apply compare_gt_iff in Hab as ->.\n    - now apply compare_gt_iff in Hab as ->.\n    - now apply compare_gt_iff in Hab as ->.\n    - exfalso.\n      apply (StrictOrder_Transitive  c b) in Hab.\n      2: assumption.\n      now apply lt_not_gt in Hab.\n  Qed.\n\n\n  (* other important lemmas *)\n\n  Lemma compare_trans (a b c: A) (comp_res: comparison):\n    compare a b = comp_res -> compare b c = comp_res -> compare a c = comp_res.\n  Proof.\n    destruct comp_res.\n    - apply compare_eq_trans.\n    - apply compare_lt_trans.\n    - apply compare_gt_trans.\n  Qed.\n\n  Lemma compare_reflect (a b: A):\n    match compare a b with\n    | Lt => lt a b\n    | Eq => a = b\n    | Gt => lt b a\n    end.\n  Proof.\n    pose proof (comparable_comp_spec a b) as [Heq | Hlt | Hgt]; assumption.\n  Qed.\n\n\n  Lemma lt_eq_lt:\n    forall alpha beta, lt alpha  beta \\/ alpha = beta \\/ lt beta alpha.\n  Proof.\n    intros; destruct (comparable_comp_spec alpha beta); auto.\n  Qed.\n\n  Definition lt_eq_lt_dec \n             (alpha beta : A) :\n    {lt alpha  beta} + {alpha = beta} + {lt beta  alpha}.\n    case_eq (compare alpha beta); intro H.\n    - left;right; now rewrite <- compare_eq_iff.\n    - left; left; now rewrite <- compare_lt_iff.\n    - right; now rewrite <- compare_gt_iff.\n  Defined.\n\n\n\n\n  Lemma LimitNotSucc \n        (alpha: A)  :\n    Limit alpha -> forall beta, ~ Successor alpha beta.\n  Proof.\n    intros [[w H] H0] beta [H1 H2].\n    destruct (lt_eq_lt beta w) as [H3 | [H3 | H3]].\n    - apply (H2 w);auto.\n    - subst w;  destruct (H0 _ H1) as [z [H3 H4]]; apply (H2 z);auto.\n    - destruct (H0 beta H1) as [z [H4 H5]]; eauto.\n  Qed.\n\n\n\nEnd Comparable.\n\n#[local] Ltac compare_trans H1 H2 intropattern :=\n  lazymatch type of (H1, H2) with\n  | ((?compare ?a ?b = ?comp_res) * (?compare ?b ?c = ?comp_res))%type =>\n    assert (compare a c = comp_res) as intropattern by\n          (apply compare_trans with b;\n           [ exact H1 | exact H2 ])\n  | ((?compare ?a ?b = ?comp_res) * (?compare ?b ?c = Eq))%type =>\n    assert (compare a c = comp_res) as intropattern by\n          (assert (b = c) as -> by (apply compare_eq_iff; exact H2);\n           exact H1)\n  | ((?compare ?a ?b = Eq) * (?compare ?b ?c = ?comp_res))%type =>\n    assert (compare a c = comp_res) as intropattern by\n          (assert (a = b) as -> by (apply compare_eq_iff; exact H1);\n           exact H2)\n  | ((?compare _ _ = _) * (?compare _ _ = _))%type => fail \"Not a supported case.\"\n  | _ => fail \"Did not find hypotheses talking about compare: did you declare an instance of Comparable?\"\n  end.\n\nTactic Notation \"compare\" \"trans\" constr(H1) constr(H2) \"as\" simple_intropattern(intropattern) :=\n  compare_trans H1 H2 intropattern.\n\nLtac compare_destruct_eqn a b H :=\n  destruct (compare a b) eqn: H;\n  [ apply compare_eq_iff in H as <-\n  | apply compare_lt_iff in H\n  | apply compare_gt_iff in H\n  ].\n\nTactic Notation \"compare\" \"destruct\" constr(a) constr(b) \"as\" ident(H) :=\n  compare_destruct_eqn a b H.\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/Comparable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7103776218556469}}
{"text": "(* --------------------------------------------------------------------\n * Copyright (c) - 2006--2012 - IMDEA Software Institute\n * Copyright (c) - 2006--2012 - Inria\n * Copyright (c) - 2006--2012 - Microsoft Coprporation\n *\n * Distributed under the terms of the CeCILL-B-V1 license\n * -------------------------------------------------------------------- *)\n\n\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    FGroup.v                        \n                                                                     \n    Defintion and properties of finite groups                         \n                                                                     \n    Definition: FGroup              \n  **********************************************************************)\nRequire Import List.\nRequire Import UList.\nRequire Import Tactic.\nRequire Import ZArith.\n\nOpen Scope Z_scope. \n\nSet Implicit Arguments.\n\n(************************************** \n  A finite group is defined for an operation op\n  it has a support  (s)\n  op operates inside the group (internal)\n  op is associative (assoc)\n  it has an element (e) that is neutral (e_is_zero_l e_is_zero_r)\n  it has an inverse operator (i)\n  the inverse operates inside the group (i_internal)\n  it gives an inverse (i_is_inverse_l is_is_inverse_r)\n **************************************)\n \nRecord FGroup (A: Type) (op: A -> A -> A): Type := mkGroup\n  {s : (list A);\n   unique_s: ulist s;\n   internal: forall a b, In a s -> In b s -> In (op a b) s;\n   assoc: forall a b c, In a s -> In b s -> In c s -> op a (op b c) = op (op a b) c;\n   e: A;\n   e_in_s: In e s;\n   e_is_zero_l:  forall a, In a s ->  op e a = a;\n   e_is_zero_r:  forall a, In a s ->  op a e = a;\n   i: A -> A;\n   i_internal: forall a, In a s -> In (i a) s;\n   i_is_inverse_l:  forall a, (In a s) -> op (i a) a = e;\n   i_is_inverse_r:  forall a, (In a s) -> op a (i a) = e\n}.\n\n(************************************** \n   The order of a group is the lengh of the support\n **************************************)\n \nDefinition g_order  (A: Type) (op: A -> A -> A) (g: FGroup op)  := Z_of_nat (length g.(s)).\n\nUnset Implicit Arguments.\n\nHint Resolve unique_s internal e_in_s e_is_zero_l e_is_zero_r i_internal\n  i_is_inverse_l i_is_inverse_r assoc.\n\n\nSection FGroup.\n\nVariable A: Type.\nVariable op: A -> A -> A.\n\n(************************************** \n   Some properties of a finite group\n **************************************)\n\nTheorem g_cancel_l: forall (g : FGroup op), forall a b c, In a g.(s) -> In b g.(s) -> In c g.(s) -> op a b = op a c -> b = c.\nintros g a b c H1 H2 H3 H4; apply trans_equal with (op g.(e) b); sauto.\nreplace (g.(e)) with (op (g.(i) a)  a); sauto.\napply trans_equal with (op (i g a) (op a b)); sauto.\napply sym_equal; apply assoc with g; auto.\nrewrite H4.\napply trans_equal with (op (op  (i g a) a) c); sauto.\napply assoc with g; auto.\nreplace (op (g.(i) a)  a) with g.(e); sauto.\nQed.\n\nTheorem g_cancel_r: forall (g : FGroup op), forall a b c, In a g.(s) -> In b g.(s) -> In c g.(s) -> op b a = op c a -> b = c.\nintros g a b c H1 H2 H3 H4; apply trans_equal with (op b g.(e)); sauto.\nreplace (g.(e)) with (op a (g.(i) a)); sauto.\napply trans_equal with (op (op b  a) (i g a)); sauto.\napply assoc with g; auto.\nrewrite H4.\napply trans_equal with (op c (op  a (i g a))); sauto.\napply sym_equal; apply assoc with g; sauto.\nreplace (op a (g.(i) a)) with g.(e); sauto.\nQed.\n\nTheorem e_unique: forall (g : FGroup op), forall e1, In e1 g.(s) ->  (forall a, In a g.(s) -> op e1 a = a) -> e1 = g.(e). \nintros g e1 He1 H2.\napply trans_equal with (op e1 g.(e)); sauto.\nQed.\n\nTheorem inv_op: forall (g: FGroup op) a b, In a g.(s) -> In b g.(s) ->  g.(i) (op a b) = op (g.(i) b) (g.(i) a).\nintros g a1 b1 H1 H2; apply g_cancel_l with (g := g) (a := op a1 b1); sauto.\nrepeat rewrite g.(assoc); sauto.\napply trans_equal with g.(e); sauto.\nrewrite <- g.(assoc) with (a := a1); sauto.\nrewrite g.(i_is_inverse_r); sauto.\nrewrite g.(e_is_zero_r); sauto.\nQed.\n\nTheorem i_e: forall (g: FGroup op), g.(i) g.(e) = g.(e).\nintro g; apply g_cancel_l with (g:= g) (a := g.(e)); sauto.\napply trans_equal with g.(e); sauto.\nQed.\n\n(************************************** \n   A group has at least one element\n **************************************)\n\nTheorem g_order_pos: forall g: FGroup op, 0 < g_order g.\nintro g; generalize g.(e_in_s); unfold g_order; case g.(s); simpl; auto with zarith.\nintros a l _; red; auto.\nQed.\n\n\n\nEnd FGroup.\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Examples/Indifferentiability/ECurve/PrimalityTest/FGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7103776218556469}}
{"text": "Require Import Arith.\nRequire Import List.\n\nInductive Ty : Set := \n| Bool : Ty\n| Stream : Ty\n| Nat : Ty\n| Arr : Ty -> Ty -> Ty.\n\nNotation \"T ==> S\" := (Arr T S) (at level 30, right associativity).\n\nInductive Term : Set := \n| v : nat -> Term \n| f : nat -> Term\n| succ : Term -> Term\n| zero : Term \n| natcase : Term -> Term -> Term -> Term\n| snil : Term\n| scons : Term -> Term -> Term  \n| streamcase : Term -> Term -> Term -> Term\n| true : Term \n| false : Term\n| boolcase : Term -> Term  -> Term -> Term\n| lam : Ty -> Term -> Term\n| app : Term -> Term -> Term.\n\nFixpoint shiftn (n : nat) (d : nat) (x : Term) {struct x} : Term := \n  match x with\n    | v m => if le_lt_dec d m then v (n+m) else v m\n    | f m => f m\n    | succ t => succ (shiftn n d t)\n    | zero => zero\n    | natcase r s t => natcase (shiftn n d r) (shiftn n d r) (shiftn n (S d) t)\n    | snil => snil\n    | scons h t => scons (shiftn n d h) (shiftn n d t)\n    | streamcase r s t => streamcase (shiftn n d r) (shiftn n d s) (shiftn n (S (S d)) t)\n    | true => true\n    | false => false\n    | boolcase r s t => boolcase (shiftn n d r) (shiftn n d s) (shiftn n d t)\n    | lam ty t => lam ty (shiftn n (S d) t)\n    | app r s => app (shiftn n d r) (shiftn n d s)\n  end.\n\nDefinition shift := shiftn 1 0.\n\nDefinition sub : forall (t : Term) (n : nat) (u : Term), Term.\nProof. \n  refine \n    (fix sub (t : Term) (n : nat) (u : Term) :=\n      match t with\n        | v m => match le_lt_dec n m with \n                   | left p => match eq_nat_dec n m with\n                                 | left _ => u \n                                 | right p' => \n                                   (match m as m' return (m = m' -> Term) with \n                                      | 0 => (fun p'' => False_rec _ _)\n                                      | S m' => (fun _ => v m')\n                                    end) (refl_equal m)\n                               end\n                   | right _ => v m\n                 end\n        | f m => f m\n        | succ t => succ (sub t n u)\n        | zero => zero\n        | natcase r s t => natcase (sub r n u) (sub s n u) (sub t (S n) (shift u))\n        | snil => snil\n        | scons h t => scons (sub h n u) (sub t n u)\n        | streamcase r s t => streamcase (sub r n u) (sub s n u) (sub t (S (S n)) (shiftn 2 0 u))\n        | true => true\n        | false => false\n        | boolcase r s t => boolcase (sub r n u) (sub s n u) (sub t n u)\n        | lam ty t => lam ty (sub t n (shift u))\n        | app r s => app (sub r n u) (sub s n u)\n      end).\n  destruct m. apply le_n_O_eq in p. apply p'. auto. inversion p''.\nDefined.\n\nDefinition Ctx := list Ty.\n\nInductive Holds (G : Ctx) (t : Term) (ty : Ty) : Set := \n| holds : Holds G t ty. \n\nNotation \"G |= t @ ty\" := (Holds G t ty) (at level 40, no associativity).\n\nCheck forall G t ty P, P (G |= t @ ty).\n\nNotation \"[]\" := nil.\nNotation \"[ x ]\" := (cons x nil).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) .. ).\n \nOpen Scope list_scope.\n\n(*  Inductive Chain : (S )  *)\n\nVariable Delta : nat -> Term.\n\nFixpoint idx (n : nat) (G : Ctx) : option Ty := \n  match G with \n    | [] => None\n    | (x::t) => match n with \n                  | O => Some x \n                  | S n' => idx n' t\n                end\n  end.\n\nCoInductive Preproof : list Set -> Set -> Set := \n| VarIntro : forall G n ty, \n  idx n G = Some ty -> Preproof [] (G |= v n @ ty)\n| ImpElim : forall G A B r s, \n  Preproof [(G |= r @ A ==> B) ; (G |= s @ A) ] ( G |= app r s @ B )\n| ImpIntro : forall G A B r, \n  Preproof [ (A::G) |= r @ B ] (G |= lam A r @ A ==> B)\n| BoolIntroTrue : forall G, Preproof [] (G |= true @ Bool) \n| BoolIntroFalse : forall G, Preproof [] (G |= false @ Bool)\n| BoolElim : forall G C r s t, \n  Preproof [( G |= r @ Bool ) ; ( G |= s @ C ) ; ( G |= t @ C ) ] (G |= boolcase r s t @ C)\n| NatIntroZero : forall G, Preproof [] (G |= zero @ Nat) \n| NatIntroSucc : forall G r, Preproof [G |= r @ Nat] (G |= succ r @ Nat) \n| NatElim : forall G C r s t, \n  Preproof [( G |= r @ Nat ) ; (G |= s @ C) ; (G |= t @ C ) ] (G |= natcase r s t @ C)\n| StreamIntroNil : forall G,  Preproof [] ( G |= snil @ Stream ) \n| StreamIntroCons : forall G n s, Preproof [ ( G |= n @ Nat ) ; (G |= s @ Stream) ] (G |= scons n s @ Stream) \n| StreamElim : forall G C r s t, \n  Preproof [( G |= r @ Stream ) ; ( G |= s @ C ) ; ( (Nat::G) |= t @ C )] ( G |= natcase r s t @ C)\n| Unfold : forall G C n,\n  Preproof [G |= f n @ C] (G |= Delta n @ C). \n\nInductive Child : Set -> Set -> Type := \n| ChildStep : forall F G c d, Preproof (F++c::G) d -> Child c d\n| ChildJump : forall F G c d e, Preproof (F++c::G) d -> Child d e ->  Child c e.\n\nInductive FinitePreproof : list Set -> Set -> Type := \n| FPCopy : forall h c, Preproof h c -> FinitePreproof h c\n| FPRepeat : forall c, Child c c -> FinitePreproof [] c.\n\nInductive HasProof : Set -> Type := \n| HasProof_witness : forall G l t A, FinitePreproof l ( G |= t @ A ) -> HasProof ( G |= t @ A ).\n\nFixpoint typecheck : forall G A memo (t : Term) -> option (Preproof (G |= t @ A)) :=\n  match t with \n    | v n => (match idx n G as mty return (idx n G = mty -> option (Preproof (G |= t @ A))) with \n                | None => (fun _ => None)\n                | Some ty => (fun mty => VarIntro G n ty mty)\n              end) (refl (idx n G))\n    | f m => match idx n memo with \n               \n| succ : Term -> Term\n| zero : Term \n| natcase : Term -> Term -> Term -> Term\n| snil : Term\n| scons : Term -> Term -> Term  \n| streamcase : Term -> Term -> Term -> Term\n| true : Term \n| false : Term\n| boolcase : Term -> Term  -> Term -> Term\n| lam : Ty -> Term -> Term\n| app : Term -> Term -> Term.\n\nInductive EvalHNF : Set -> Set -> Set := \n| Eval_app : forall t s, Eval (app (lam t) s) ( \n\n| v : nat -> Term \n| f : nat -> Term\n| succ : Term -> Term\n| zero : Term \n| natcase : Term -> Term -> Term -> Term\n| snil : Term\n| scons : Term -> Term -> Term  \n| streamcase : Term -> Term -> Term -> Term\n| true : Term \n| false : Term\n| boolcase : Term -> Term  -> Term -> Term\n| lam : Ty -> Term -> Term\n| app : Term -> Term -> Term.\n\n\n\n\n", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/PreProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7103776110286057}}
{"text": "From mathcomp Require Import ssreflect.\n\nRequire Import set_notations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import Coq.Sets.Image.\n\n(* R1 斎藤毅   集合と位相 ISBN 978-4-13-062958-4 *)\n(* R2 島内剛一 数学の基礎 *)\n(* R3 斎藤正彦 数学の基礎 ISBN 4-13-062909-3 *)\n\nImport SetNotations.\n\n(* R3 1.2.4 definition *)\nInductive InvIm {U V:Type} (B: Ensemble V) (f:U -> V): Ensemble U :=\n  InvIm_intro: forall (x:U), (f x) ∈ B -> x ∈ (InvIm B f).\n\nDefinition Id (A:Type) : A -> A := fun (x:A) => x.\n\nDefinition Composite {A B C : Type} (g:B -> C) (f:A -> B) : A -> C := fun (x:A) => g (f x).\n\nDefinition surjective {U V:Type} (f:U -> V) := forall y:V, exists x:U, f x = y.\n\nDefinition bijective {U V:Type} (f:U -> V) := injective U V f /\\ surjective f.\n\n(* ℑ:Unicode 2111, 𝔪:Unicode 1D52A *)\nNotation \"ℑ𝔪( f | A )\" := (@Im _ _ A f) (at level 60).\nNotation \"ℑ𝔪^-1( f | A )\" := (InvIm A f) (at level 60).\n(* ∘ : Unicode 2218 *)\nNotation \"g ∘ f\" := (Composite g f) (left associativity, at level 50).\n\nSection ImgExample.\n  Variable U V W:Type.\n\n  Lemma InvIm_def: forall (B: Ensemble V) (f:U -> V) (x:U),\n      x ∈ (InvIm B f) -> (f x) ∈ B.\n  Proof.\n    move => B f x HInvIm.\n    inversion HInvIm as [y HfxB].\n    apply HfxB.\n  Qed.\n\n  Lemma InvIm_inv: forall (B: Ensemble V) (f:U -> V) (x:U),\n      x ∈ (InvIm B f) -> (f x) ∈ B.\n  Proof.\n    move => B f x HInvImB.\n    inversion HInvImB as [y HyB].\n    exact HyB.\n  Qed.\n\n  Lemma Img_Subset: forall (A B:Ensemble U) (f: U -> V),\n      A ⊂ B -> ℑ𝔪( f | A ) ⊂ ℑ𝔪( f | B ).\n  Proof.\n    move => A B f H x.\n    case => s HsA y Hyfs.\n    rewrite Hyfs.\n    apply Im_def.\n    apply H.\n    apply HsA.\n  Qed.\n\n  (* R2 Problem 2.3.8 *)\n  Lemma Img_Union: forall (A B:Ensemble U) (f: U -> V),\n      ℑ𝔪( f | A ∪ B ) = ℑ𝔪( f | A ) ∪ ℑ𝔪( f | B ).\n  Proof.\n    move => A B f.\n    apply /Extensionality_Ensembles.\n    split => x.\n    move => H.\n    inversion H.\n    inversion H0.\n    left.\n    rewrite H1.\n    apply Im_def.\n    apply H3.\n    right.\n    rewrite H1.\n    apply Im_def.\n    apply H3.\n    case => y; case => s H z H0; rewrite H0; apply Im_def.\n    left.\n    apply H.\n    right.\n    apply H.\n  Qed.\n\n  (* R2 Problem 2.3.9 *)\n  Lemma Img_Intersection: forall (A B:Ensemble U) (f: U -> V),\n      ℑ𝔪( f | A ∩ B ) ⊂ ℑ𝔪( f | A ) ∩ ℑ𝔪( f | B ).\n  Proof.\n    move => A B f x.\n    case => s.\n    case => t HA HB y H0.\n    rewrite H0.\n    split; apply Im_def.\n    apply HA.\n    apply HB.\n  Qed.\n\n  (* f[A] \\ f[B] ⊂ f[A \\ B] *)\n  Goal forall (A B:Ensemble U) (f:U -> V),\n      (ℑ𝔪( f | A ) \\ ℑ𝔪( f | B )) ⊂ ℑ𝔪( f | (A \\ B) ).\n  Proof.\n    move => A B f x.\n    case => HImA HnImB.\n    inversion HImA as [a HaA y Hxfa Hxeqy].\n    rewrite Hxfa.\n    apply Im_def.\n    split.\n    apply HaA.\n    unfold not.\n    move => HaB.\n    apply HnImB.\n    rewrite Hxfa.\n    apply Im_def.\n    apply HaB.\n  Qed.\n\n  (* f^-1[C ∪ D] = f^-1[C] ∪ f^-1[D] *)\n  Lemma InvIm_Union:\n    forall (C D: Ensemble V) (f:U->V), ℑ𝔪^-1( f | C ∪ D ) = ℑ𝔪^-1( f | C ) ∪ ℑ𝔪^-1( f | D ).\n  Proof.\n    move => C D f.\n    apply Extensionality_Ensembles.\n    split => y H.\n    inversion H as [x HyCD Hxeqy].\n    inversion HyCD as [v H0|].\n    left.\n    split.\n    apply H0.\n    right.\n    split.\n    apply H0.\n    split; inversion H; inversion H0.\n    left.\n    apply H2.\n    right.\n    apply H2.\n  Qed.\n\n  (* f^-1[C ∩ D] = f^-1[C] ∩ f^-1[D] *)\n  Lemma InvIm_Intersection:\n    forall (C D: Ensemble V) (f:U->V), ℑ𝔪^-1( f | C ∩ D ) = ℑ𝔪^-1( f | C ) ∩ ℑ𝔪^-1( f | D ).\n  Proof.\n    move => C D f.\n    apply Extensionality_Ensembles.\n    split => x H.\n    inversion H; inversion H0 as [y].\n    split; split.\n    apply H2.\n    apply H3.\n    inversion H as [y HC HD].\n    inversion HC as [w].\n    inversion HD as [z].\n    split; split.\n    apply H1.\n    apply H3.\n  Qed.\n\n  (* R2 Problem 2.3.10 *)\n  Goal forall (A:Ensemble U) (f:U->V), A ⊂ ℑ𝔪^-1( f | (ℑ𝔪( f | A ))).\n  Proof.\n    move => A f x HA.\n    split.\n    apply Im_def.\n    apply HA.\n  Qed.\n\n  (* B⊂X -> f(f^-1(B)) ⊂ B ∩ X *)\n  Goal forall (B:Ensemble V) (f:U->V), ℑ𝔪( f | (ℑ𝔪^-1( f | B))) ⊂ (B ∩ (Full_set V)).\n  Proof.\n    move => B f b.\n    case => x H0 y Hyfx.\n    inversion H0.\n    rewrite Hyfx.\n    split.\n    apply H.\n    apply Full_intro.\n  Qed.\n\n  (* h ・ ( g ・ f ) = ( h ・ g ) ・ f *)\n  Lemma compsite_assc: forall (A B C D:Type) (f:A->B) (g:B->C) (h:C->D), h ∘ ( g ∘ f ) = ( h ∘ g ) ∘ f.\n  Proof.\n    move => A B C D f g h.\n    unfold Composite.\n    reflexivity.\n  Qed.\n\n  Goal forall (A B: Type) (f:A->B), id ∘ f = f.\n    move => A B f.\n    unfold Composite.\n    unfold id.\n    reflexivity.\n  Qed.\n\n  (* R3 Problem 1.3.1 (g ・ f)[A] = g[f[A]] *)\n  Goal forall (X Y Z: Type) (A:Ensemble X) (f:X -> Y) (g:Y -> Z),\n      ℑ𝔪( g ∘ f | A ) = ℑ𝔪( g | ℑ𝔪( f | A )).\n  Proof.\n    move => X Y Z A f g.\n    apply /Extensionality_Ensembles.\n    split => z H.\n    inversion H as [x HxA].\n    rewrite H0.\n    apply Im_def.\n    apply Im_def.\n    apply HxA.\n    inversion H.\n    inversion H0.\n    rewrite H1.\n    rewrite H4.\n    have L1: forall a:X, g (f a) = (g ∘ f) a.\n    move => a.\n    unfold Composite.\n    reflexivity.\n    rewrite L1.\n    apply Im_def.\n    apply H3.\n  Qed.\n\n  (* R3 Problem 1.3.2 R ⊂ Z -> (g ・ f)^-1[R] = f^-1 [g^-1 [R]] *)\n  Goal forall (X Y Z: Type) (R:Ensemble Z) (f:X -> Y) (g:Y -> Z),\n      ℑ𝔪^-1( g ∘ f | R ) =  ℑ𝔪^-1( f | ℑ𝔪^-1( g | R )).\n  Proof.\n    move => X Y Z R f g.\n    apply /Extensionality_Ensembles.\n    split => x; move => H; inversion H.\n    split.\n    split.\n    apply H0.\n    inversion H0.\n    split.\n    apply H2.\n  Qed.\n\n  Goal forall (f:U -> V) (g:V -> W), injective U W (g ∘ f) -> injective U V f.\n  Proof.\n    move => f g.\n    unfold injective.\n    move => H.\n    move => x y Hf.\n    apply H.\n    unfold Composite.\n    rewrite Hf.\n    reflexivity.\n  Qed.\n\n  Goal forall (f:U -> V) (g:V -> W), surjective (g ∘ f) -> surjective g.\n  Proof.\n    move => f g.\n    unfold surjective.\n    move => H z.\n    move: (H z) => H0.\n    destruct H0.\n    rewrite -H0.\n    exists (f x).\n    unfold Composite.\n    reflexivity.\n  Qed.\n\n  \n  \nEnd ImgExample.\n\nExport SetNotations.\nExport Coq.Sets.Image.\n", "meta": {"author": "seisyuu-hantatsushi", "repo": "coq_ssreflect_practice", "sha": "96e1d440c8c69673209ae0d86046b6b9305f8bab", "save_path": "github-repos/coq/seisyuu-hantatsushi-coq_ssreflect_practice", "path": "github-repos/coq/seisyuu-hantatsushi-coq_ssreflect_practice/coq_ssreflect_practice-96e1d440c8c69673209ae0d86046b6b9305f8bab/practices/img_example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7103665959104795}}
{"text": "(** * Lists: Data Structures in Coq *)\n\n(* $Date: 2012-01-18 18:28:00 -0500 (Wed, 18 Jan 2012) $ *)\n\n(** The next line imports all of our definitions from the\n    previous chapter. *)\n\nRequire Export Basics.\n\n(** For it to work, you need to use [coqc] to compile [Basics.v]\n    into [Basics.vo].  (This is like making a .class file from a .java\n    file, or a .o file from a .c file.)\n  \n    Here are two ways to compile your code:\n  \n     - CoqIDE:\n   \n         Open Basics.v.\n         In the \"Compile\" menu, click on \"Compile Buffer\".\n   \n     - Command line:\n   \n         Run [coqc Basics.v]\n\n    In this file, we again use the [Module] feature to wrap all of the\n    definitions for pairs and lists of numbers in a module so that,\n    later, we can reuse the same names for improved (generic) versions\n    of the same operations. *)\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.\n  destruct p as (m,n).\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 (m,n).\n  simpl.\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,\n[[\nNotation \"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   (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    |lhd::ltl => match lhd with\n                   |O => nonzeros ltl\n                   |_ => lhd::(nonzeros ltl)\n                 end\n  end.\n\nExample test_nonzeros:            nonzeros [0,1,0,2,3,0,0] = [1,2,3].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nFixpoint oddmembers (l:natlist) : natlist :=\n   match l with\n    |nil => nil\n    |lhd::ltl => if oddb lhd then lhd::(oddmembers ltl) else oddmembers ltl\n  end.\n\nExample test_oddmembers:            oddmembers [0,1,0,2,3,0,0] = [1,3].\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nFixpoint countoddmembers (l:natlist) : nat :=\n  length (oddmembers l).\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: 2 stars (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 way of writing [alternate] will fail to satisfy\n    Coq's requirement that all [Fixpoint] definitions be \"obviously\n    terminating.\"  If you find yourself in this rut, look for a\n    slightly more verbose solution that considers elements of both\n    lists at the same time. *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1, l2 with\n    |nil, l2' =>l2'\n    |l1', nil =>l1'\n    |hd1::tl1, hd2::tl2 => hd1::(hd2::(alternate tl1 tl2))\n  end.\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(* Ex3 (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    |shd::stl => if beq_nat shd v then 1 + (count v stl) else count v stl\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.\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  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  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 := \n  if beq_nat (count v s) O then false else true. \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    |shd::stl => if beq_nat shd v then stl else shd::remove_one v stl\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 :=\n  match s with\n    |nil => nil\n    |shd::stl => if beq_nat shd v \n                 then remove_all v stl \n                 else shd::remove_all v stl\n  end.\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    |nil => true\n    |hd1::tl1 => if member hd1 s2 \n                 then subset tl1 (remove_one hd1 s2) \n                 else false\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, 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*)\nTheorem count_add : forall (v:nat) (b:bag),\n  count v (add v b) = 1 + count v b.\nProof.\n  intros v b.\n  simpl.\n  rewrite <- beq_nat_refl.\n  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.\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[[\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  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[[\n        length (snoc [] n) = S (length []),\n]]\n      which follows directly from the definitions of\n      [length] and [snoc].\n\n    - Next, suppose [l = n'::l'], with\n[[\n        length (snoc l' n) = S (length l').\n]]\n      We must show\n[[\n        length (snoc (n' :: l') n) = S (length (n' :: l')).\n]]\n      By the definitions of [length] and [snoc], this\n      follows from\n[[\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[[\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 (snoc (rev l') n) = S (length l')\n]]\n        which, by the previous lemma, is the same as\n[[\n          S (length (rev l')) = S (length l').\n]]\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[[\n       length (snoc l n) = S (length l)\n]]\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-f]. 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.\n  intros l.\n  induction l as [| lhd ltl].\n  Case \"l = []\".\n      reflexivity.\n  Case \"l = lhd::ltl\".\n      simpl. rewrite -> IHltl. reflexivity.\nQed.\n \nTheorem rev_snoc : forall (n:nat) (l:natlist),\n  rev (snoc l n) = n :: rev l.\nProof.\n  intros n l.\n  induction l as [| lhd ltl].\n  Case \"l = []\".\n      reflexivity.\n  Case \"l = lhd::ltl\".\n      simpl. rewrite -> IHltl. simpl. reflexivity.\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  intros l.\n  induction l as [| lhd ltl].\n  Case \"l = []\".\n      reflexivity.\n  Case \"l = lhd::ltl\".\n      simpl. rewrite -> rev_snoc. rewrite -> IHltl. reflexivity.\nQed.\n \nTheorem app_in_snoc : forall (l1 l2:natlist) (n:nat),\n  snoc (l1 ++ l2) n = l1 ++ snoc l2 n.\nProof.\n  intros l1 l2 n.\n  induction l1 as [| hd1 tl1].\n  Case \"l1 = []\".\n      reflexivity.\n  Case \"l1 = hd1::tl1\".\n      simpl. rewrite -> IHtl1. reflexivity.\nQed.\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 [| hd1 tl1].\n  Case \"l1 = []\".\n      simpl. rewrite -> app_nil_end. reflexivity.\n  Case \"l1 = hd1::tl1\".\n      simpl. rewrite -> IHtl1. rewrite -> app_in_snoc. 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\n\nTheorem snoc_append : forall (l:natlist) (n:nat),\n  snoc l n = l ++ [n].\nProof.\n  intros l n.\n  induction l as [| lhd ltl].\n  Case \"l = []\".\n      reflexivity.\n  Case \"l = lhd::ltl\".\n      simpl. rewrite -> IHltl. reflexivity.\nQed.\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  intros l1 l2.\n  induction l1 as [| hd1 tl1].\n  Case \"l1 = []\".\n      reflexivity.\n  Case \"l1 = hd1::tl1\".\n      destruct hd1 as [| hd1'].\n      SCase \"hd1 = O\".\n          simpl. rewrite -> IHtl1. reflexivity.\n      SCase \"hd1 = S hd1'\".\n          simpl. rewrite -> IHtl1. reflexivity.\nQed.\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\nTheorem cons_snoc_ass : forall (l1 l2:natlist) (n:nat),\n  l1 ++ (n::l2) = snoc l1 n ++ l2.\nProof.\n  intros l1 l2 n.\n  induction l1 as [| hd1 tl1].\n  Case \"l1 = []\".\n      reflexivity.\n  Case \"l1 = hd1::tl1\".\n      simpl. rewrite -> IHtl1. reflexivity.\nQed.\n\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  intros s.\n  simpl.\n  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.\n  induction s as [| shd stl].\n  Case \"s = []\".\n      reflexivity.\n  Case \"s = shd::stl\".\n      simpl.\n      destruct shd as [| shd'].\n      SCase \"shd = O\".\n          simpl. rewrite -> ble_n_Sn. reflexivity.\n      SCase \"shd = S hd'\".\n          simpl. rewrite -> IHstl. 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*)\nTheorem count_sum : forall (l1 l2:bag) (n:nat),\n  count n l1 + count n l2 = count n (sum l1 l2).\nProof.\n  intros l1 l2 n.\n  induction l1 as [| hd1 tl1].\n  Case \"l1 = []\".\n      simpl. reflexivity.\n  Case \"l1 = hd1::tl1\".\n      simpl. destruct (beq_nat hd1 n).\n      SCase \"beq_nat hd1 n = true\".\n          simpl. rewrite -> IHtl1. reflexivity.\n      SCase \"beq_nat hd1 n = false\".\n          rewrite -> IHtl1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (rev_injective) *)\n(** Prove that the [rev] function is injective, that is,\n\n[[\n    forall X (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.\n]]\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 H.\n  rewrite <- rev_involutive. rewrite <- H. rewrite -> rev_involutive.\n  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    |nil => None\n    |lhd::ltl => Some lhd\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: 2 stars, 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 as [| head tail].\n  Case \"l = []\".\n      simpl. reflexivity.\n  Case \"l = head::tail\".\n      simpl. reflexivity.\nQed.\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    |hd1::tl1, hd2::tl2 => if beq_nat hd1 hd2 \n                           then beq_natlist tl1 tl2 \n                           else false\n    |_,_ => 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.\nProof.\n  intros l.\n  induction l as [| lhd ltl].\n  Case \"l = []\".\n      simpl. reflexivity.\n  Case \"l = lhd::ltl\".\n      simpl. rewrite <- IHltl. rewrite <- beq_nat_refl. reflexivity.\nQed.\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. *)\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. rewrite <- beq_nat_refl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star (dictionary_invariant2) *)\n(** Complete the following proof. *)\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.\n  intros H.\n  simpl. rewrite -> H. reflexivity.\nQed.\n(** [] *)\n\nEnd Dictionary.\n\nEnd NatList.\n\n", "meta": {"author": "ismailkuru", "repo": "2012spring", "sha": "297e8f107dbc54262ede62dfe2edb7d3b6fb9c64", "save_path": "github-repos/coq/ismailkuru-2012spring", "path": "github-repos/coq/ismailkuru-2012spring/2012spring-297e8f107dbc54262ede62dfe2edb7d3b6fb9c64/cis500/hw/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.8688267660487573, "lm_q1q2_score": 0.7103305842934727}}
{"text": "(* week-05_folding-left-and-right-over-peano-numbers.v *)\n(* FPP 2020 - YSC3236 2020-2011, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 05 Sep 2020 *)\n\n(* ********** *)\n\n(* Your name: Bobbie Soedirgo\n   Your student ID number: A0181001A\n   Your e-mail address: sram-b@comp.nus.edu.sg\n*)\n\n(* ********** *)\n\n(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name := intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith Bool.\n\n(* ********** *)\n\nDefinition specification_of_power (power : nat -> nat -> nat) :=\n  (forall x : nat,\n      power x 0 = 1)\n  /\\\n  (forall (x : nat)\n          (n' : nat),\n      power x (S n') = x * power x n').\n\n(* ***** *)\n\nProposition there_is_at_most_one_function_satisfying_the_specification_of_power :\n  forall power1 power2 : nat -> nat -> nat,\n    specification_of_power power1 ->\n    specification_of_power power2 ->\n    forall x n : nat,\n      power1 x n = power2 x n.\nProof.\n  intros power1 power2.\n  unfold specification_of_power.\n  intros [S1_O S1_S] [S2_O S2_S] x n.\n  induction n as [ | n' IHn'].\n  - rewrite -> (S2_O x).\n    exact (S1_O x).\n  - rewrite -> (S1_S x n').\n    rewrite -> (S2_S x n').\n    rewrite -> IHn'.\n    reflexivity.\nQed.\n\n(* ***** *)\n\nDefinition test_power (candidate : nat -> nat -> nat) : bool :=\n  (candidate 2 0 =? 1) &&\n  (candidate 10 2 =? 10 * 10) &&\n  (candidate 3 2 =? 3 * 3).\n\n(* ***** *)\n\nFixpoint power_v0_aux (x n : nat) : nat :=\n  match n with\n  | O =>\n    1\n  | S n' =>\n    x * power_v0_aux x n'\n  end.\n\nDefinition power_v0 (x n : nat) : nat :=\n  power_v0_aux x n.\n\nCompute (test_power power_v0).\n\nLemma fold_unfold_power_v0_aux_O :\n  forall x : nat,\n    power_v0_aux x 0 = 1.\nProof.\n  fold_unfold_tactic power_v0_aux.\nQed.\n\nLemma fold_unfold_power_v0_aux_S :\n  forall x n' : nat,\n    power_v0_aux x (S n') = x * power_v0_aux x n'.\nProof.\n  fold_unfold_tactic power_v0_aux.\nQed.\n\nProposition power_v0_safisfies_the_specification_of_power :\n  specification_of_power power_v0.\nProof.\n  unfold specification_of_power, power_v0.\n  split.\n  - exact fold_unfold_power_v0_aux_O.\n  - exact fold_unfold_power_v0_aux_S.\nQed.\n\n(* ***** *)\n\nFixpoint power_v1_aux (x n a : nat) : nat :=\n  match n with\n  | O =>\n    a\n  | S n' =>\n    power_v1_aux x n' (x * a)\n  end.\n\nDefinition power_v1 (x n : nat) : nat :=\n  power_v1_aux x n 1.\n\nCompute (test_power power_v1).\n\nLemma fold_unfold_power_v1_aux_O :\n  forall x a : nat,\n    power_v1_aux x 0 a =\n    a.\nProof.\n  fold_unfold_tactic power_v1_aux.\nQed.\n\nLemma fold_unfold_power_v1_aux_S :\n  forall x n' a : nat,\n    power_v1_aux x (S n') a =\n    power_v1_aux x n' (x * a).\nProof.\n  fold_unfold_tactic power_v1_aux.\nQed.\n\n(* ***** *)\n\n(* Eureka lemma: *)\n\nLemma about_power_v0_aux_and_power_v1_aux :\n  forall x n a : nat,\n    power_v0_aux x n * a = power_v1_aux x n a.\nProof.\n  intros x n.\n  induction n as [ | n' IHn'].\n  - intro a.\n    rewrite -> (fold_unfold_power_v0_aux_O x).\n    rewrite -> (fold_unfold_power_v1_aux_O x a).\n    exact (Nat.mul_1_l a).\n  - intro a.\n    rewrite -> (fold_unfold_power_v0_aux_S x n').\n    rewrite -> (fold_unfold_power_v1_aux_S x n' a).\n    Check (IHn' (x * a)).\n    rewrite <- (IHn' (x * a)).\n    rewrite -> (Nat.mul_comm x (power_v0_aux x n')).\n    Check (Nat.mul_assoc).\n    symmetry.\n    exact (Nat.mul_assoc (power_v0_aux x n') x a).\nQed.\n\nTheorem power_v0_and_power_v1_are_equivalent :\n  forall x n : nat,\n    power_v0 x n = power_v1 x n.\nProof.\n  intros x n.\n  unfold power_v0, power_v1.\n  Check (about_power_v0_aux_and_power_v1_aux x n 1).\n  rewrite <- (Nat.mul_1_r (power_v0_aux x n)).\n  exact (about_power_v0_aux_and_power_v1_aux x n 1).\nQed.\n\n(* ********** *)\n\nFixpoint nat_fold_right (V : Type) (z : V) (s : V -> V) (n : nat) : V :=\n  match n with\n  | O =>\n    z\n  | S n' =>\n    s (nat_fold_right V z s n')\n  end.\n\nLemma fold_unfold_nat_fold_right_O :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V),\n    nat_fold_right V z s O =\n    z.\nProof.\n  fold_unfold_tactic nat_fold_right.\nQed.\n\nLemma fold_unfold_nat_fold_right_S :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V)\n         (n' : nat),\n    nat_fold_right V z s (S n') =\n    s (nat_fold_right V z s n').\nProof.\n  fold_unfold_tactic nat_fold_right.\nQed.\n\n(* ***** *)\n\nFixpoint nat_fold_left (V : Type) (z : V) (s : V -> V) (n : nat) : V :=\n  match n with\n  | O =>\n    z\n  | S n' =>\n    nat_fold_left V (s z) s n'\n  end.\n\nLemma fold_unfold_nat_fold_left_O :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V),\n    nat_fold_left V z s O =\n    z.\nProof.\n  fold_unfold_tactic nat_fold_left.\nQed.\n\nLemma fold_unfold_nat_fold_left_S :\n  forall (V : Type)\n         (z : V)\n         (s : V -> V)\n         (n' : nat),\n    nat_fold_left V z s (S n') =\n    nat_fold_left V (s z) s n'.\nProof.\n  fold_unfold_tactic nat_fold_left.\nQed.\n\n(* ********** *)\n\nDefinition power_v0_alt (x n : nat) : nat :=\n  nat_fold_right nat 1 (fun ih => x * ih) n.\n\nCompute (test_power power_v0_alt).\n\nProposition power_v0_alt_safisfies_the_specification_of_power :\n  specification_of_power power_v0_alt.\nProof.\n  unfold specification_of_power, power_v0_alt.\n  split.\n  - intro x.\n    rewrite -> (fold_unfold_nat_fold_right_O nat 1 (fun ih : nat => x * ih)).\n    reflexivity.\n  - intros x n'.\n    rewrite -> (fold_unfold_nat_fold_right_S nat 1 (fun ih : nat => x * ih) n').\n    reflexivity.\nQed.\n\nCorollary power_v0_and_power_v0_alt_are_equivalent :\n  forall x n : nat,\n    power_v0 x n = power_v0_alt x n.\nProof.\n  intros x n.\n  Check (there_is_at_most_one_function_satisfying_the_specification_of_power\n           power_v0\n           power_v0_alt\n           power_v0_safisfies_the_specification_of_power\n           power_v0_alt_safisfies_the_specification_of_power\n           x\n           n).\n  exact (there_is_at_most_one_function_satisfying_the_specification_of_power\n           power_v0\n           power_v0_alt\n           power_v0_safisfies_the_specification_of_power\n           power_v0_alt_safisfies_the_specification_of_power\n           x\n           n).\nQed.\n\n(* ***** *)\n\nDefinition power_v1_alt (x n : nat) : nat :=\n  nat_fold_left nat 1 (fun ih => x * ih) n.\n\nCompute (test_power power_v1_alt).\n\nLemma power_v1_and_power_v1_alt_are_equivalent_aux :\n  forall x n a : nat,\n    power_v1_aux x n a = nat_fold_left nat a (fun ih : nat => x * ih) n.\nProof.\nAdmitted.\n\nProposition power_v1_and_power_v1_alt_are_equivalent :\n  forall x n : nat,\n    power_v1 x n = power_v1_alt x n.\nProof.\n  intros x n.\n  unfold power_v1, power_v1_alt.\n  exact (power_v1_and_power_v1_alt_are_equivalent_aux x n 1).\nQed.\n\n(* ********** *)\n\nLemma about_nat_fold_left :\n  forall (V : Type) (z : V) (s : V -> V) (n : nat),\n    nat_fold_left V (s z) s n = s (nat_fold_left V z s n).\nProof.\nAdmitted.\n\nLemma about_nat_fold_right :\n  forall (V : Type) (z : V) (s : V -> V) (n : nat),\n    nat_fold_right V (s z) s n = s (nat_fold_right V z s n).\nProof.\n  intros V z s n.\n  induction n as [| n' IHn'].\n  - Check (fold_unfold_nat_fold_right_O V z s).\n    rewrite -> (fold_unfold_nat_fold_right_O V z s).\n    exact (fold_unfold_nat_fold_right_O V (s z) s).\n  - Check fold_unfold_nat_fold_right_S.\n    rewrite -> (fold_unfold_nat_fold_right_S V (s z) s).\n    rewrite -> IHn'.\n    rewrite -> (fold_unfold_nat_fold_right_S V z s).\n    reflexivity.\nQed.\n\nTheorem folding_left_and_right :\n  forall (V : Type) (z : V) (s : V -> V) (n : nat),\n    nat_fold_left V z s n = nat_fold_right V z s n.\nProof.\n  intros V z s n.\n  revert z.\n  induction n as [| n' IHn'].\n  - intro z.\n    rewrite -> (fold_unfold_nat_fold_right_O V z s).\n    exact (fold_unfold_nat_fold_left_O V z s).\n  - intro z.\n    rewrite -> (fold_unfold_nat_fold_left_S V z s).\n    rewrite -> (IHn' (s z)).\n    rewrite -> (fold_unfold_nat_fold_right_S V z s).\n    exact (about_nat_fold_right V z s n').\nQed.\n\n(* ********** *)\n\nCorollary power_v0_and_power_v1_are_equivalent_alt :\n  forall x n : nat,\n    power_v0 x n = power_v1 x n.\nProof.\n  intros x n.\n  rewrite -> (power_v0_and_power_v0_alt_are_equivalent x n).\n  rewrite -> (power_v1_and_power_v1_alt_are_equivalent x n).\n  unfold power_v0_alt, power_v1_alt.\n  symmetry.\n  exact (folding_left_and_right nat 1 (fun ih : nat => x * ih) n).\nQed.\n\n(* ********** *)\n\n(*** Exercise 1 *)\n\nFixpoint add_v0 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => S (add_v0 i' j)\n  end.\n\nLemma fold_unfold_add_v0_O :\n  forall j : nat,\n    add_v0 O j =\n    j.\nProof.\n  fold_unfold_tactic add_v0.\nQed.\n\nLemma fold_unfold_add_v0_S :\n  forall i' j : nat,\n    add_v0 (S i') j =\n    S (add_v0 i' j).\nProof.\n  fold_unfold_tactic add_v0.\nQed.\n\nDefinition add_v0_alt (i j : nat) : nat :=\n  nat_fold_right nat j (fun ih : nat => S ih) i.\n\nProposition add_v0_and_add_v0_alt_are_equivalent :\n  forall i j : nat,\n    add_v0 i j = add_v0_alt i j.\nProof.\n  intros i j.\n  unfold add_v0_alt.\n  revert j.\n  induction i as [| i' IHi'].\n  - intro j.\n    rewrite -> (fold_unfold_nat_fold_right_O nat j (fun ih : nat => S ih)).\n    exact (fold_unfold_add_v0_O j).\n  - intro j.\n    rewrite -> (fold_unfold_nat_fold_right_S nat j (fun ih : nat => S ih) i').\n    rewrite <- (IHi' j).\n    exact (fold_unfold_add_v0_S i' j).\nQed.\n\n(* ***** *)\n\nFixpoint add_v1 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => add_v1 i' (S j)\n  end.\n\nLemma fold_unfold_add_v1_O :\n  forall j : nat,\n    add_v1 O j =\n    j.\nProof.\n  fold_unfold_tactic add_v1.\nQed.\n\nLemma fold_unfold_add_v1_S :\n  forall i' j : nat,\n    add_v1 (S i') j =\n    add_v1 i' (S j).\nProof.\n  fold_unfold_tactic add_v1.\nQed.\n\nDefinition add_v1_alt (i j : nat) : nat :=\n  nat_fold_left nat j (fun ih : nat => S ih) i.\n\nProposition add_v1_and_add_v1_alt_are_equivalent :\n  forall i j : nat,\n    add_v1 i j = add_v1_alt i j.\nProof.\n  unfold add_v1_alt.\n  intro i.\n  induction i as [| i' IHi'].\n  - intro j.\n    rewrite -> (fold_unfold_nat_fold_left_O nat j (fun ih : nat => S ih)).\n    exact (fold_unfold_add_v1_O j).\n  - intro j.\n    rewrite -> (fold_unfold_nat_fold_left_S nat j (fun ih : nat => S ih) i').\n    rewrite <- (IHi' (S j)).\n    exact (fold_unfold_add_v1_S i' j).\nQed.\n\nCorollary add_v0_and_add_v1_are_equivalent :\n  forall i j : nat,\n    add_v0 i j = add_v1 i j.\nProof.\n  intros i j.\n  rewrite -> (add_v0_and_add_v0_alt_are_equivalent i j).\n  rewrite -> (add_v1_and_add_v1_alt_are_equivalent i j).\n  unfold add_v0_alt, add_v1_alt.\n  symmetry.\n  Check folding_left_and_right.\n  exact (folding_left_and_right nat j (fun ih : nat => S ih) i).\nQed.\n\n(* ********** *)\n\n(*** Exercise 2 *)\n\nFixpoint mul_v0_aux (i j : nat) : nat :=\n  match i with\n    | O => 0\n    | S i' => j + (mul_v0_aux i' j)\n  end.\n\nDefinition mul_v0 (i j : nat) : nat :=\n  mul_v0_aux i j.\n\nLemma fold_unfold_mul_v0_aux_O :\n  forall j : nat,\n    mul_v0_aux O j = O.\nProof.\n  fold_unfold_tactic mul_v0_aux.\nQed.\n\nLemma fold_unfold_mul_v0_aux_S :\n  forall i' j : nat,\n    mul_v0_aux (S i') j = j + (mul_v0_aux i' j).\nProof.\n  fold_unfold_tactic mul_v0_aux.\nQed.\n\nDefinition mul_v0_alt (i j : nat) : nat :=\n  nat_fold_right nat O (fun ih : nat => j + ih) i.\n\nProposition mul_v0_and_mul_v0_alt_are_equivalent :\n  forall i j : nat,\n    mul_v0 i j = mul_v0_alt i j.\nProof.\n  unfold mul_v0, mul_v0_alt.\n  intro i.\n  induction i as [| i' IHi'].\n  - intro j.\n    rewrite -> (fold_unfold_nat_fold_right_O nat O (fun ih : nat => j + ih)).\n    exact (fold_unfold_mul_v0_aux_O j).\n  - intro j.\n    rewrite -> (fold_unfold_nat_fold_right_S nat O (fun ih : nat => j + ih) i').\n    rewrite <- (IHi' j).\n    exact (fold_unfold_mul_v0_aux_S i' j).\nQed.\n\n(* ***** *)\n\nFixpoint mul_v1_aux (i j a : nat) : nat :=\n  match i with\n    | O => a\n    | S i' => mul_v1_aux i' j (j + a)\n  end.\n\nDefinition mul_v1 (i j : nat) : nat :=\n  mul_v1_aux i j 0.\n\nLemma fold_unfold_mul_v1_aux_O :\n  forall j a : nat,\n    mul_v1_aux O j a = a.\nProof.\n  fold_unfold_tactic mul_v1_aux.\nQed.\n\nLemma fold_unfold_mul_v1_aux_S :\n  forall i' j a : nat,\n    mul_v1_aux (S i') j a = mul_v1_aux i' j (j + a).\nProof.\n  fold_unfold_tactic mul_v1_aux.\nQed.\n\nDefinition mul_v1_alt (i j : nat) : nat :=\n  nat_fold_left nat O (fun ih : nat => j + ih) i.\n\n(* Unlike for add, this needs a Eureka lemma for some reason. Need to look into why. *)\n(* At a glance, it seems like the induction hypothesis is not strong enough as we need it to paramaterize over the accumulator. So, unintuitively, we need to prove a stronger lemma (the Eureka lemma) and prove this proposition as an instance of it. *)\nLemma about_mul_v1_aux :\n  forall i j a : nat,\n    mul_v1_aux i j a = nat_fold_left nat a (fun ih : nat => j + ih) i.\nProof.\n  intro i.\n  induction i as [| i' IHi'].\n  - intros j a.\n    rewrite -> (fold_unfold_nat_fold_left_O nat a (fun ih : nat => j + ih)).\n    exact (fold_unfold_mul_v1_aux_O j a).\n  - intros j a.\n    rewrite -> (fold_unfold_nat_fold_left_S nat a (fun ih : nat => j + ih) i').\n    rewrite <- (IHi' j (j + a)).\n    exact (fold_unfold_mul_v1_aux_S i' j a).\nQed.\n\nProposition mul_v1_and_mul_v1_alt_are_equivalent :\n  forall i j : nat,\n    mul_v1 i j = mul_v1_alt i j.\nProof.\n  unfold mul_v1, mul_v1_alt.\n  intro i.\n  induction i as [| i' IHi'].\n  - intro j.\n    rewrite -> (fold_unfold_nat_fold_left_O nat O (fun ih : nat => j + ih)).\n    exact (fold_unfold_mul_v1_aux_O j O).\n  - intro j.\n    (* Stuck... *)\n\n  Restart.\n\n  intros i j.\n  exact (about_mul_v1_aux i j O).\nQed.\n\nProposition mul_v0_and_mul_v1_are_equivalent :\n  forall i j : nat,\n    mul_v0 i j = mul_v1 i j.\nProof.\n  intros i j.\n  rewrite -> (mul_v0_and_mul_v0_alt_are_equivalent i j).\n  rewrite -> (mul_v1_and_mul_v1_alt_are_equivalent i j).\n  unfold mul_v0_alt, mul_v1_alt.\n  symmetry.\n  exact (folding_left_and_right nat O (fun ih : nat => j + ih) i).\nQed.\n\n(* ********** *)\n\n(*** Exercise 3 *)\n\nFixpoint odd_v0_aux (n : nat) (a : bool) : bool :=\n  match n with\n    | O => a\n    | S n' => negb (odd_v0_aux n' a)\n  end.\n\nDefinition odd_v0 (n : nat) :=\n  odd_v0_aux n false.\n\nLemma fold_unfold_odd_v0_aux_O :\n  forall a : bool,\n    odd_v0_aux O a = a.\nProof.\n  fold_unfold_tactic odd_v0_aux.\nQed.\n\nLemma fold_unfold_odd_v0_aux_S :\n  forall n' : nat,\n    forall a : bool,\n      odd_v0_aux (S n') a = negb (odd_v0_aux n' a).\nProof.\n  fold_unfold_tactic odd_v0_aux.\nQed.\n\nFixpoint odd_v1_aux (n : nat) (a : bool) : bool :=\n  match n with\n    | O => a\n    | S n' => odd_v1_aux n' (negb a)\n  end.\n\nDefinition odd_v1 (n : nat) : bool :=\n  odd_v1_aux n false.\n\nLemma fold_unfold_odd_v1_aux_O :\n  forall a : bool,\n    odd_v1_aux O a = a.\nProof.\n  fold_unfold_tactic odd_v1_aux.\nQed.\n\nLemma fold_unfold_odd_v1_aux_S :\n  forall n' : nat,\n    forall a : bool,\n      odd_v1_aux (S n') a = odd_v1_aux n' (negb a).\nProof.\n  fold_unfold_tactic odd_v1_aux.\nQed.\n\nProposition odd_v0_aux_and_odd_v1_aux_are_equivalent :\n  forall n : nat,\n    forall a : bool,\n    odd_v0_aux n a = odd_v1_aux n a.\nProof.\n  unfold odd_v1.\n  intro n.\n  induction n as [| n' IHn'].\n  - intro a.\n    rewrite -> (fold_unfold_odd_v1_aux_O a).\n    exact (fold_unfold_odd_v0_aux_O a).\n  - intro a.\n    rewrite -> (fold_unfold_odd_v1_aux_S n' a).\n    rewrite <- (IHn' (negb a)).\n    exact (fold_unfold_odd_v1_aux_S n' a).\n\n(* end of week-05_folding-left-and-right-over-peano-numbers.v *)\n", "meta": {"author": "soedirgo", "repo": "fpp", "sha": "5a43df151c5c8bc3f49d449ffd6f3eac67a16eab", "save_path": "github-repos/coq/soedirgo-fpp", "path": "github-repos/coq/soedirgo-fpp/fpp-5a43df151c5c8bc3f49d449ffd6f3eac67a16eab/w05/week-05_folding-left-and-right-over-peano-numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7103054532600647}}
{"text": "(* The following material is derived from Software Foundations by Benjamin\nPierce et al. Their work is under the following MIT license: *)\n\n(*\nCopyright (c) 2012\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n *)\n\n(* ###################################################################### *)\n(** ** Days of the Week *)\n\nInductive day : Type :=\n| monday : day\n| tuesday : day\n| wednesday : day\n| thursday : day\n| friday : day\n| saturday : day\n| sunday : day\n.\n\nDefinition tomorrow (d: day) : day :=\n  match d with\n  | monday    => tuesday\n  | tuesday   => wednesday\n  | wednesday => thursday\n  | thursday  => friday\n  | friday    => saturday\n  | saturday  => sunday\n  | sunday    => monday\n  end.\n\nTheorem test_tomorrow:\n  tomorrow saturday = sunday.\nProof.\n  simpl. reflexivity.\nQed.\n\n(* ###################################################### *)\n(** ** Lists of Numbers *)\n\nInductive natlist : Type :=\n| nil  : natlist\n| cons : nat -> natlist -> natlist\n.\n\nDefinition empty_list := nil.\n\nDefinition singleton_list := cons 42 nil.\n\nDefinition one_two_three := cons 1 (cons 2 (cons 3 nil)).\n\nFixpoint concat (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (concat t l2)\n  end.\n\nTheorem test_concat1:\n  concat (cons 1 (cons 2 nil))\n         (cons 3 (cons 4 nil))\n  = (cons 1 (cons 2 (cons 3 (cons 4 nil)))).\nProof.\n  simpl. reflexivity.\nQed.\n\n(* ###################################################### *)\n(** * Reasoning About Lists *)\n\nTheorem concat_nil_left : forall l : natlist,\n  concat nil l = l.\nProof.\n  (* FILL IN HERE *)\nQed.\n\nTheorem concat_nil_right : forall l : natlist,\n  concat l nil = l.\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(* In-class exercise! *)\nTheorem concat_associativity : forall l2 l1 l3 : natlist,\n  concat (concat l1 l2) l3 = concat l1 (concat l2 l3).\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(*\n  [snoc] adds an element [v] at the end of the list [l]:\n    snoc (cons 1 (cons 2 nil)) 3 = cons 1 (cons 2 (cons 3 nil))\n*)\nFixpoint snoc (l: natlist) (v: nat) : natlist :=\n  match l with\n  | nil      => cons v nil\n  | cons h t => cons h (snoc t v)\n  end.\n\n(*\n  [rev] reverses a list:\n    rev (cons 1 (cons 2 nil)) = cons 2 (cons 1 nil)\n*)\nFixpoint rev (l: natlist) : natlist :=\n  match l with\n  | nil      => nil\n  | cons h t => snoc (rev t) h\n  end.\n\n(* ###################################################### *)\n(**\n  For each theorem:\n  - Discuss the statement of the theorem with your partner.\n  - Once you understand it, prove the theorem.\n\n  Every time you solve a theorem, switch who uses the keyboard/mouse.\n *)\n\nTheorem rev_snoc : forall x l,\n  rev (snoc l x) = cons x (rev l).\nProof.\n  (* FILL IN HERE *)\nQed.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n  (* FILL IN HERE *)\nQed.\n\nTheorem concat_cons_snoc : forall l1 x l2,\n  concat l1 (cons x l2) = concat (snoc l1 x) l2.\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(* ###################################################### *)\n\nModule LogicExercises.\n\n(* We now use notations from logic:\n  /\\   stands for the logical conjunction (AND) of two propositions\n  \\/   stands for the logical disjunction (OR)  of two propositions\n\n  New tactics: left, right\n\n  When your goal looks like [A \\/ B]\n  You get to pick which of [A] or [B] you will prove.\n  If you believe you can prove [A], use the [left.] tactic.\n  If you believe you can prove [B], use the [right.] tactic.\n\n  Here is an example:\n*)\n\nTheorem goright_example : 0 = 1 \\/ 1 = 1.\nProof. right. reflexivity.\nQed.\n\nTheorem go_somewhere : 0 = 1 \\/ (2 = 2 \\/ 2 = 3).\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(*\n  New tactic: apply\n\n  If you ever have a goal [G]\n  And a hypothesis [H : G] or [H : X -> ... -> G]\n  You can use the tactic [apply H.] to solve your goal in the former case,\n  or turn your goal into subgoal(s) [X], [...] in the latter case.\n*)\n\nTheorem B_is_enough : forall A B : Prop,\n  B ->\n  A \\/ B.\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(*\n  New tactic: split\n\n  When your goal looks like [A /\\ B]\n  You need to prove both [A] and [B].\n  The tactic [split.] lets you split your goal into these two goals.\n\n  Here is an example:\n*)\n\nTheorem two_facts : nil = nil /\\ 42 = 42.\nProof. split. reflexivity. reflexivity.\nQed.\n\nTheorem more_facts : 1 = 2 \\/ (1 = 1 /\\ nil = nil).\nProof.\n  (* FILL IN HERE *)\nQed.\n\nTheorem A_and_B : forall A B : Prop,\n  A ->\n  B ->\n  A /\\ B.\nProof.\n  (* FILL IN HERE *)\nQed.\n\nEnd LogicExercises.\n\n(* ###################################################### *)\n\nTheorem snoc_concat_end : forall (l: natlist) (n: nat),\n  snoc l n = concat l (cons n nil).\nProof.\n  (* FILL IN HERE *)\nQed.\n\nTheorem rev_distributes_over_concat : forall l1 l2 : natlist,\n  rev (concat l1 l2) = concat (rev l2) (rev l1).\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(* ###################################################### *)\n(** We now introduce [map], which applies a function [f] to\n    every element of a list [l].\n*)\n\nFixpoint map (f: nat -> nat) (l: natlist) :=\n  match l with\n  | nil => nil\n  | cons x xs => cons (f x) (map f xs)\n  end.\n\nTheorem map_commutes : forall f g l,\n  (forall x, f (g x) = g (f x)) ->\n  map f (map g l) = map g (map f l).\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(* In this theorem, \"fun x =>\" introduces an anonymous function which receives\n   a parameter [x] and returns the result on the right of the arrow. *)\nTheorem map_fusion : forall f g l,\n  map f (map g l) = map (fun x => f (g x)) l.\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(* ###################################################### *)\n(** We now introduce [fold], which processes a list with an\n    accumulating function [f], starting from an initial value [b].\n*)\nFixpoint fold (f: nat -> natlist -> natlist) (l: natlist) (b: natlist) :=\n  match l with\n  | nil => b\n  | cons x xs => f x (fold f xs b)\n  end.\n\nTheorem fold_snoc : forall f l x b,\n  fold f (snoc l x) b = fold f l (f x b).\nProof.\n  (* FILL IN HERE *)\nQed.\n\nDefinition map' f l := fold (fun x fxs => cons (f x) fxs) l nil.\n\n(* We use [Lemma] instead of [Theorem] here to indicate that this theorem may\n   help you in proving the next theorem. *)\nAxiom map'_unroll : forall f x xs,\n  map' f (cons x xs) = cons (f x) (map' f xs).\n\nAxiom map'_nil : forall f, map' f nil = nil.\n\nTheorem map_map' : forall f l, map f l = map' f l.\nProof.\n  (* FILL IN HERE *)\nQed.\n\nLtac cases H := match type of H with _ \\/ _ => destruct H end.\n\n(*\n  New tactics: cases, contradiction\n\n  When a hypothesis looks like [H : A \\/ B]\n  You have to prove the goal for each case, to do so, use the tactic [cases H.]\n  You will get two goals as a result, one with a [A] hypothesis, one with a [B] hypothesis.\n\n  Finally, if you ever get a hypothesis like [H : False]\n  You have derived a contradiction, and you can indicate this to the system by calling\n  the tactic [contradiction.], which will solve your goal.\n*)\n\nFixpoint In n l :=\n  match l with\n  | nil      => False\n  | cons h t => h = n \\/ In n t\n  end.\n\nTheorem In_cons : forall x h l,\n  In x l ->\n  In x (cons h l).\nProof.\n  (* FILL IN HERE *)\nQed.\n\n(*\n  New tactic: simpl in *\n\n  Sometimes, you might want to simplify things in your hypotheses, the same way things\n  can be simplified in your conclusion.\n*)\n\nTheorem In_concat_left : forall x l1 l2,\n  In x l1 ->\n  In x (concat l1 l2).\nProof.\n  (* FILL IN HERE *)\nQed.\n", "meta": {"author": "Ptival", "repo": "PeaCoq", "sha": "4d186879910a327455e7b7b239d58a9502145680", "save_path": "github-repos/coq/Ptival-PeaCoq", "path": "github-repos/coq/Ptival-PeaCoq/PeaCoq-4d186879910a327455e7b7b239d58a9502145680/web/coq/study-empty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7103054502248155}}
{"text": "Add LoadPath \"C:\\Users\\Jonathan\\source\\repos\\PLT-Coq\\Software Foundations\\Logical Foundations\".\n\nInductive 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\nend.\n\nCompute (next_weekday friday).\n\nCompute (next_weekday (next_weekday saturday)).\n\nExample test_next_weekday:\n  (next_weekday (next_weekday saturday)) = tuesday.\n\nProof. simpl. reflexivity. Qed.\n\n(* Booleans *)\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\nend.\n\nDefinition andb (b_1 : bool) (b_2 : bool) : bool :=\n match b_1 with\n  | true => b_2\n  | false => false\nend.\n\nDefinition orb (b_1: bool) (b_2: bool) : bool :=\n  match b_1 with \n  | true => true\n  | false => b_2\nend.\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\nNotation \"x && y\" := (andb x y).\nNotation \"x || y\" := (orb x y).\n\nExample test_orb5: false || true = true.\nProof. simpl. reflexivity. Qed.\n\n(*Exercise Nandb*)\n\nDefinition nandb (b_1 : bool) (b_2 : bool) : bool :=\n  negb (andb b_1 b_2).\n\nExample test_nandb1 : (nandb true false) = true.\nProof. reflexivity. Qed.\nExample test_nandb2 : (nandb false false) = true.\nProof. reflexivity. Qed.\nExample test_nandb3 : (nandb false true) = true.\nProof. reflexivity. Qed.\nExample test_nandb4 : (nandb true true) = false.\nProof. reflexivity. Qed.\n\n(* Exercise andb3 *)\n\nDefinition andb3 (b_1 : bool) (b_2 : bool) (b_3 : bool) : bool :=\n  andb (andb b_1 b_2) (andb b_2 b_3).\n\nExample test_andb31: (andb3 true true true) = true.\nProof. reflexivity. Qed.\nExample test_andb32: (andb3 false true true) = false.\nProof. reflexivity. Qed.\nExample test_andb33: (andb3 true false true) = false.\nProof. reflexivity. Qed.\nExample test_andb4: (andb3 true true false) = false.\nProof. reflexivity. Qed.\n\n(* Function types *)\nCheck true.\nCheck (negb true).\nCheck negb.\n\n\n(* Compound types *)\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\n\nInductive color : Type :=\n  | black : color\n  | white : color\n  | primary : rgb -> color.\n\nDefinition monochrome (c: color) : bool :=\n  match c with \n  | black => true\n  | white => true\n  | primary p => false\nend.\n\nDefinition isred (c : color) : bool :=\n  match c with\n  | black => false\n  | white => false\n  | primary red => true\n  | primary _ => false\nend.\n\nModule NatPlayground.\n\nInductive nat : Type :=\n  | O : nat\n  | S : nat -> nat.\n\nInductive nat' : Type :=\n  | stop : nat'\n  | tick: nat' -> nat'.\n\nDefinition pred (n: nat) : nat :=\n  match 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'\nend.\n\nCompute (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'\nend.\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 NatPlayground2.\n\nFixpoint plus (n : nat) (m : nat) : nat :=\n  match n with \n  | O => m\n  | S n' => S (plus n' m)\nend.\n\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)\nend.\n\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'\nend.\n\nEnd NatPlayground2.\n\nFixpoint exp (base power : nat) : nat :=\n  match power with\n  | O => S O\n  | S p => mult base (exp base p)\nend.\n\n(* Exercise factorial *)\n\nFixpoint factorial (n: nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => mult n (factorial n')\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\nNotation \"x - y\" := (minus x y)\n                      (at level 50, left associativity)\n                      : nat_scope.\n\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\nend.\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\nend.\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 blt_nat *)\n\nDefinition blt_nat (n m : nat) : bool := andb (leb n m) (negb (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.\n\n(* Proof by Simplification *)\n\nTheorem plus_O_n : forall n : nat, 0 + n = n.\nProof.\n  intros n. simpl. reflexivity. Qed.\n\nTheorem plus_O_n': forall n : nat, 0 + n = n.\nProof. intros n. reflexivity. Qed.\n\nTheorem plus_1_1 : forall n: nat, 1 + n = S n.\nProof. intros n. reflexivity. Qed.\n\nTheorem mult_O_1 : forall n: nat, 0 * n = 0.\nProof. intros n. reflexivity. Qed.\n\n(* Proof by Rewriting *)\nTheorem plus_id_example: forall n m: nat, n = m -> n + m = m + n.\nProof.\n  intros n m.\n  intros H. \n  rewrite -> H.\n  reflexivity. Qed.\n\n(* Exercise plus_id_exercise *)\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 H_1.\n  rewrite -> H_1.\n  intros H_2.\n  rewrite -> H_2.\n  reflexivity. Qed.\n\nTheorem mult_0_plus : forall n m : nat, (0 + n) * m = n * m.\nProof. \n  intros n m. \n  rewrite -> plus_O_n.\n  reflexivity. Qed.\n\n(* Exercise mult_S_1 *)\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 H.\n  rewrite -> H.\n  rewrite <- plus_1_1.\n  reflexivity. Qed.\n\n(* Proof by Case Analysis *)\n\nTheorem plus_1_neq_0_firsttry : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof. \n  intros n.\n  simpl.\nAbort.\n\n\nTheorem plus_1_neq_0 : forall n : nat,\n  beq_nat (n + 1) 0 = false.\nProof. \n  intros n. destruct n as [| n'].\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem negb_involutive : forall b : bool,\n  negb (negb b) = b.\nProof.\n  intros b. destruct b.\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem andb_commtative : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\n  - destruct c.\n    + reflexivity.\n    + reflexivity.\nQed.\n\nTheorem andb_commutative' : forall b c, andb b c = andb c b.\nProof.\n  intros b c. destruct b.\n  { destruct c.\n    { reflexivity. }\n    { reflexivity. } }\n  { destruct c. \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.\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' : forall n : nat, \n  beq_nat (n + 1) 0 = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity. Qed.\n\nTheorem andb_commutative'' : forall b c, andb b c = andb c b.\nProof.\n  intros [] [].\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* Exercise andb_true_elim2 *)\n\nTheorem andb_true_elim2 : forall b c : bool, andb b c = true -> c = true.\nProof.\n  intros b [].\n  - reflexivity.\n  - intros H. rewrite <- H. destruct b.\n   + reflexivity.\n   + reflexivity.\nQed.\n\n(* Exercise zero_nbeq_plus_1 *)\n\nTheorem zero_nbeq_plus_1 : forall n : nat,  beq_nat 0 (n + 1) = false.\nProof.\n  intros [|n].\n  - reflexivity.\n  - reflexivity.\nQed.\n\n(* Notation *)\n\nFixpoint plus' (n: nat) (m : nat) : nat :=\n  match n with\n  | O => m\n  | S n' => S (plus' n' m)\nend.\n\n(* Exercise boolean_functions *)\n\nTheorem identify_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 f H [].\n  - rewrite -> H. rewrite -> H. reflexivity.\n  - rewrite -> H. rewrite -> H. 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 f H [].\n  - rewrite -> H. rewrite -> H. reflexivity.\n  - rewrite -> H. rewrite -> H. reflexivity.\nQed.\n\n(* Exercise andb_eq_orb *)\n\nTheorem andb_eq_orb: \n  forall (b c : bool),\n  (andb b c = orb b c) ->\n  b = c.\nProof.\n  intros [] c.\n  - simpl. intros H. rewrite -> H. reflexivity.\n  - simpl. intros H. rewrite -> H. reflexivity.\nQed.\n\n(* Exercise binary *)\n\nInductive binary : Type :=\n  | Z : binary\n  | N : binary -> binary\n  | D : binary -> binary.\n\nDefinition binincr (n : binary) :=\n  match n with\n  | Z => N Z\n  | N n' => D n'\n  | D n' => N (D n')\nend.\n\nFixpoint bin_to_nat (n : binary) :=\n  match n with\n  | Z => O\n  | N n' => S (bin_to_nat n')\n  | D n' => S (S (bin_to_nat n'))\nend.\n\nExample test_bin_incr1 : binincr Z = N Z.\nProof. reflexivity. Qed.\nExample test_bin_incr2 : binincr (N Z) = D Z.\nProof. reflexivity. Qed.\nExample test_bin_incr3: binincr (N (D (D Z))) = D (D (D Z)).\nProof. reflexivity. Qed.\nExample test_bin2nat_0 : bin_to_nat Z = 0.\nProof. reflexivity. Qed.\nExample test_bin2nat_1: bin_to_nat (binincr (N (D (D Z)))) = 6.\nProof. reflexivity. Qed.\n\n\n\n\n", "meta": {"author": "Ryxai", "repo": "PLT-Coq", "sha": "c8f6670e65cafc933ea67e890ceb6c5c80976816", "save_path": "github-repos/coq/Ryxai-PLT-Coq", "path": "github-repos/coq/Ryxai-PLT-Coq/PLT-Coq-c8f6670e65cafc933ea67e890ceb6c5c80976816/Software Foundations/Logical Foundations/Basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7102747321157855}}
{"text": "(** * Logic: Logic in Coq *)\n\n(* $Date: 2012-07-22 18:36:58 -0400 (Sun, 22 Jul 2012) $ *)\n\nRequire Export \"Prop\".\n\n(** Coq's built-in logic is extremely small: only [Inductive]\n    definitions, universal quantification ([forall]), and\n    implication ([->]) are primitive, while all the other familiar\n    logical connectives -- conjunction, disjunction, negation,\n    existential quantification, even equality -- can be defined using\n    just these. *)\n\n(* ########################################################### *)\n(** * Quantification and Implication *)\n\n(** In fact, [->] and [forall] are the _same_ primitive!  Coq's [->]\n    notation is actually just a shorthand for [forall].  The [forall]\n    notation is more general, because it allows us to _name_ the\n    hypothesis. *)\n\n(** For example, consider this proposition: *)\n\nDefinition funny_prop1 :=\n  forall n, forall (E : beautiful n), beautiful (n+3).\n\n(** If we had a proof term inhabiting this proposition, it would\n    be a function with two arguments: a number [n] and some evidence\n    that [n] is beautiful.  But the name [E] for this evidence is not\n    used in the rest of the statement of [funny_prop1], so it's a bit\n    silly to bother making up a name.  We could write it like this\n    instead, using the dummy identifier [_] in place of a real\n    name: *)\n\nDefinition funny_prop1' :=\n  forall n, forall (_ : beautiful n), beautiful (n+3).\n\n(** Or, equivalently, we can write it in more familiar notation: *)\n\nDefinition funny_prop1'' :=\n  forall n, beautiful n -> beautiful (n+3).\n\n(** This illustrates that \"[P -> Q]\" is just syntactic sugar for\n    \"[forall (_:P), Q]\". *)\n\n(* ########################################################### *)\n(** * Conjunction *)\n\n(** The logical conjunction of propositions [P] and [Q] can be\n    represented using an [Inductive] definition with one\n    constructor. *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\n(** Note that, like the definition of [ev] in the previous\n    chapter, this definition is parameterized; however, in this case,\n    the parameters are themselves propositions, rather than numbers. *)\n\n(** The intuition behind this definition is simple: to\n    construct evidence for [and P Q], we must provide evidence\n    for [P] and evidence for [Q].  More precisely:\n\n    - [conj p q] can be taken as evidence for [and P Q] if [p]\n      is evidence for [P] and [q] is evidence for [Q]; and\n\n    - this is the _only_ way to give evidence for [and P Q] --\n      that is, if someone gives us evidence for [and P Q], we\n      know it must have the form [conj p q], where [p] is\n      evidence for [P] and [q] is evidence for [Q].\n\n   Since we'll be using conjunction a lot, let's introduce a more\n   familiar-looking infix notation for it. *)\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** (The [type_scope] annotation tells Coq that this notation\n    will be appearing in propositions, not values.) *)\n\n(** Consider the \"type\" of the constructor [conj]: *)\n\nCheck conj.\n(* ===>  forall P Q : Prop, P -> Q -> P /\\ Q *)\n\n(** Notice that it takes 4 inputs -- namely the propositions [P]\n    and [Q] and evidence for [P] and [Q] -- and returns as output the\n    evidence of [P /\\ Q]. *)\n\n(** Besides the elegance of building everything up from a tiny\n    foundation, what's nice about defining conjunction this way is\n    that we can prove statements involving conjunction using the\n    tactics that we already know.  For example, if the goal statement\n    is a conjuction, we can prove it by applying the single\n    constructor [conj], which (as can be seen from the type of [conj])\n    solves the current goal and leaves the two parts of the\n    conjunction as subgoals to be proved separately. *)\n\nTheorem and_example :\n  (beautiful 0) /\\ (beautiful 3).\nProof.\n  apply conj.\n  (* Case \"left\". *) apply b_0.\n  (* Case \"right\". *) apply b_3.  Qed.\n\n(** Let's take a look at the proof object for the above theorem. *)\n\nPrint and_example.\n(* ===>  conj (beautiful 0) (beautiful 3) b_0 b_3\n            : beautiful 0 /\\ beautiful 3 *)\n\n(** Note that the proof is of the form\n    conj (beautiful 0) (beautiful 3)\n         (...pf of beautiful 3...) (...pf of beautiful 3...)\n    as you'd expect, given the type of [conj]. *)\n\n(** Just for convenience, we can use the tactic [split] as a shorthand for\n    [apply conj]. *)\n\nTheorem and_example' :\n  (ev 0) /\\ (ev 4).\nProof.\n  split.\n    Case \"left\". apply ev_0.\n    Case \"right\". apply ev_SS. apply ev_SS. apply ev_0.  Qed.\n\n(** Conversely, the [inversion] tactic can be used to take a\n    conjunction hypothesis in the context, calculate what evidence\n    must have been used to build it, and add variables representing\n    this evidence to the proof context. *)\n\nTheorem proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2) *)\nTheorem proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HP HQ].\n  split.\n    (* Case \"left\". *) apply HQ.\n    (* Case \"right\".*) apply HP.  Qed.\n\n(** Once again, we have commented out the [Case] tactics to make the\n    proof object for this theorem easy to understand.  Examining it\n    shows that all that is really happening is taking apart a record\n    containing evidence for [P] and [Q] and rebuilding it in the\n    opposite order: *)\n\nPrint and_commut.\n(* ===>\n   and_commut =\n     fun (P Q : Prop) (H : P /\\ Q) =>\n     let H0 := match H with\n               | conj HP HQ => conj Q P HQ HP\n               end\n     in H0\n     : forall P Q : Prop, P /\\ Q -> Q /\\ P *)\n\n(** **** Exercise: 2 stars (and_assoc) *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [inversion] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, recommended (even__ev) *)\n(** Now we can prove the other direction of the equivalence of [even]\n   and [ev], which we left hanging in chapter [Prop].  Notice that the\n   left-hand conjunct here is the statement we are actually interested\n   in; the right-hand conjunct is needed in order to make the\n   induction hypothesis strong enough that we can carry out the\n   reasoning in the inductive step.  (To see why this is needed, try\n   proving the left conjunct by itself and observe where things get\n   stuck.) *)\n\nTheorem even__ev : forall n : nat,\n  (even n -> ev n) /\\ (even (S n) -> ev (S n)).\nProof.\n  (* Hint: Use induction on [n]. *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (conj_fact) *)\n(** Construct a proof object demonstrating the following proposition. *)\n\nDefinition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n(* ###################################################### *)\n(** ** Iff *)\n\n(** The familiar logical \"if and only if\" is just the\n    conjunction of two implications. *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity) : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n  (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties) *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  (* FILL IN HERE *) Admitted.\n\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beautiful_iff_gorgeous) *)\n\n(** We have seen that the families of propositions [beautiful] and\n    [gorgeous] actually characterize the same set of numbers.\n    Prove that [beautiful n <-> gorgeous n] for all [n].  Just for\n    fun, write your proof as an explicit proof object, rather than\n    using tactics. (_Hint_: if you make use of previously defined\n    theorems, you should only need a single line!) *)\n\nDefinition beautiful_iff_gorgeous :\n  forall n, beautiful n <-> gorgeous n :=\n  (* FILL IN HERE *) admit.\n(** [] *)\n\n(** Some of Coq's tactics treat [iff] statements specially, thus\n    avoiding the need for some low-level manipulation when reasoning\n    with them.  In particular, [rewrite] can be used with [iff]\n    statements, not just equalities. *)\n\n(* ############################################################ *)\n(** * Disjunction *)\n\n(** Disjunction (\"logical or\") can also be defined as an\n    inductive proposition. *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\n(** Consider the \"type\" of the constructor [or_introl]: *)\n\nCheck or_introl.\n(* ===>  forall P Q : Prop, P -> P \\/ Q *)\n\n(** It takes 3 inputs, namely the propositions [P], [Q] and\n    evidence of [P], and returns, as output, the evidence of [P \\/ Q].\n    Next, look at the type of [or_intror]: *)\n\nCheck or_intror.\n(* ===>  forall P Q : Prop, Q -> P \\/ Q *)\n\n(** It is like [or_introl] but it requires evidence of [Q]\n    instead of evidence of [P]. *)\n\n(** Intuitively, there are two ways of giving evidence for [P \\/ Q]:\n\n    - give evidence for [P] (and say that it is [P] you are giving\n      evidence for -- this is the function of the [or_introl]\n      constructor), or\n\n    - give evidence for [Q], tagged with the [or_intror]\n      constructor. *)\n\n(** Since [P \\/ Q] has two constructors, doing [inversion] on a\n    hypothesis of type [P \\/ Q] yields two subgoals. *)\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ.  Qed.\n\n(** From here on, we'll use the shorthand tactics [left] and [right]\n    in place of [apply or_introl] and [apply or_intror]. *)\n\nTheorem or_commut' : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". right. apply HP.\n    Case \"right\". left. apply HQ.  Qed.\n\n(** **** Exercise: 2 stars, optional (or_commut'') *)\n(** Try to write down an explicit proof object for [or_commut] (without\n    using [Print] to peek at the ones we already defined!). *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. inversion H as [HP | [HQ HR]].\n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars, recommended (or_distributes_over_and_2) *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_distributes_over_and) *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################### *)\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] *)\n\n(** We've already seen several places where analogous structures\n    can be found in Coq's computational ([Type]) and logical ([Prop])\n    worlds.  Here is one more: the boolean operators [andb] and [orb]\n    are clearly analogs of the logical connectives [/\\] and [\\/].\n    This analogy can be made more precise by the following theorems,\n    which show how to translate knowledge about [andb] and [orb]'s\n    behaviors on certain inputs into propositional facts about those\n    inputs. *)\n\nTheorem andb_true__and : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n\nTheorem and__andb_true : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\n(** **** Exercise: 2 stars (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem orb_true : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem orb_false : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################### *)\n(** * Falsehood *)\n\n(** Logical falsehood can be represented in Coq as an inductively\n    defined proposition with no constructors. *)\n\nInductive False : Prop := .\n\n(** Intuition: [False] is a proposition for which there is no way\n    to give evidence. *)\n\n(** **** Exercise: 1 star (False_ind_principle) *)\n(** Can you predict the induction principle for falsehood? *)\n\n(* Check False_ind. *)\n(** [] *)\n\n(** Since [False] has no constructors, inverting an assumption\n    of type [False] always yields zero subgoals, allowing us to\n    immediately prove any goal. *)\n\nTheorem False_implies_nonsense :\n  False -> 2 + 2 = 5.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** How does this work? The [inversion] tactic breaks [contra] into\n    each of its possible cases, and yields a subgoal for each case.\n    As [contra] is evidence for [False], it has _no_ possible cases,\n    hence, there are no possible subgoals and the proof is done. *)\n\n(** Conversely, the only way to prove [False] is if there is already\n    something nonsensical or contradictory in the context: *)\n\nTheorem nonsense_implies_False :\n  2 + 2 = 5 -> False.\nProof.\n  intros contra.\n  inversion contra.  Qed.\n\n(** Actually, since the proof of [False_implies_nonsense]\n    doesn't actually have anything to do with the specific nonsensical\n    thing being proved; it can easily be generalized to work for an\n    arbitrary [P]: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from\n    falsehood follows whatever you please.\"  This theorem is also\n    known as the _principle of explosion_. *)\n\n(* #################################################### *)\n(** ** Truth *)\n\n(** Since we have defined falsehood in Coq, one might wonder whether\n    it is possible to define truth in the same way.  We can. *)\n\n(** **** Exercise: 2 stars, optional (True_induction) *)\n(** Define [True] as another inductively defined proposition.  What\n    induction principle will Coq generate for your definition?  (The\n    intution is that [True] should be a proposition for which it is\n    trivial to give evidence.  Alternatively, you may find it easiest\n    to start with the induction principle and work backwards to the\n    inductive definition.) *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** However, unlike [False], which we'll use extensively, [True] is\n    just a theoretical curiosity: it is trivial (and therefore\n    uninteresting) to prove as a goal, and it carries no useful\n    information as a hypothesis. *)\n\n(* #################################################### *)\n(** * Negation *)\n\n(** The logical complement of a proposition [P] is written [not\n    P] or, for shorthand, [~P]: *)\n\nDefinition not (P:Prop) := P -> False.\n\n(** The intuition is that, if [P] is not true, then anything at\n    all (even [False]) follows from assuming [P]. *)\n\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\n(** It takes a little practice to get used to working with\n    negation in Coq.  Even though you can see perfectly well why\n    something is true, it can be a little hard at first to get things\n    into the right configuration so that Coq can see it!  Here are\n    proofs of a few familiar facts about negation to get you warmed\n    up. *)\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.\n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, recommended (double_neg_inf) *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* FILL IN HERE *)\n   []\n*)\n\n(** **** Exercise: 2 stars, recommended (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star (informal_not_PNP) *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\nTheorem five_not_even :\n  ~ ev 5.\nProof.\n  (* WORKED IN CLASS *)\n  unfold not. intros Hev5. inversion Hev5 as [|n Hev3 Heqn].\n  inversion Hev3 as [|n' Hev1 Heqn']. inversion Hev1.  Qed.\n\n(** **** Exercise: 1 star (ev_not_ev_S) *)\n(** Theorem [five_not_even] confirms the unsurprising fact that five\n    is not an even number.  Prove this more interesting fact: *)\n\nTheorem ev_not_ev_S : forall n,\n  ev n -> ~ ev (S n).\nProof.\n  unfold not. intros n H. induction H. (* not n! *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Note that some theorems that are true in classical logic are _not_\n    provable in Coq's (constructive) logic.  E.g., let's look at how\n    this proof gets stuck... *)\n\nTheorem classic_double_neg : forall P : Prop,\n  ~~P -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not in H.\n  (* But now what? There is no way to \"invent\" evidence for [P]. *)\n  Admitted.\n\n(** **** Exercise: 5 stars, optional (classical_axioms) *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop,\n  ~~P -> P.\nDefinition excluded_middle := 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\n(* FILL IN HERE *)\n(** [] *)\n\n(* ########################################################## *)\n(** ** Inequality *)\n\n(** Saying [x <> y] is just the same as saying [~(x = y)]. *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\n(** Since inequality involves a negation, it again requires\n    a little practice to be able to work with it fluently.  Here\n    is one very useful trick.  If you are trying to prove a goal\n    that is nonsensical (e.g., the goal state is [false = true]),\n    apply the lemma [ex_falso_quodlibet] to change the goal to\n    [False].  This makes it easier to use assumptions of the form\n    [~P] that are available in the context -- in particular,\n    assumptions of the form [x<>y]. *)\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n(** **** Exercise: 2 stars, recommended (not_eq_beq_false) *)\nTheorem not_eq_beq_false : forall n n' : nat,\n     n <> n' ->\n     beq_nat n n' = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (beq_false_not_eq) *)\nTheorem beq_false_not_eq : forall n m,\n  false = beq_nat n m -> n <> m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ############################################################ *)\n(** * Existential Quantification *)\n\n(** Another critical logical connective is _existential\n    quantification_.  We can capture what this means with the\n    following 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    For example, consider this existentially quantified proposition: *)\n\nDefinition some_nat_is_even : Prop :=\n  ex nat ev.\n\n(** To prove this proposition, we need to choose a particular number\n    as witness -- say, 4 -- and give some evidence that that number is\n    even. *)\n\nDefinition snie : some_nat_is_even :=\n  ex_intro _ ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\n(** Coq's notation definition facility can be used to introduce\n    more 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(** We can use the same set of tactics as always for\n    manipulating existentials.  For example, if to prove an\n    existential, we [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, again, that we have to explicitly give the witness. *)\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 * n) = 6.\nProof.\n  exists 2.\n  reflexivity.  Qed.\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(** **** 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(** Complete the definition of the following proof object: *)\n\nDefinition p : ex nat (fun n => beautiful (S n)) :=\n(* FILL IN HERE *) admit.\n(** [] *)\n\n(** **** Exercise: 1 star (dist_not_exists) *)\n(** Prove that \"[P] holds for all [x]\" and \"there is no [x] for\n    which [P] does not hold\" are equivalent assertions. *)\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 requires the classical \"law of the excluded\n    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(* Print dist_exists_or. *)\n\n\n\n(* ###################################################### *)\n(** * Equality *)\n\n(** Even Coq's equality relation is not built in.  It has\n    roughly the following inductive definition.  (We enclose the\n    definition in a module to avoid confusion with the standard\n    library equality, which we have used extensively already.) *)\n\nModule MyEquality.\n\nInductive eq (X:Type) : X -> X -> Prop :=\n  refl_equal : forall x, eq X x x.\n\n(** Standard infix notation (using Coq's type argument synthesis): *)\n\nNotation \"x = y\" := (eq _ x y)\n                    (at level 70, no associativity) : type_scope.\n\n(** This is a bit subtle.  The way to think about it is that, given a\n    set [X], it defines a _family_ of propositions \"[x] is equal to\n    [y],\" indexed by pairs of values ([x] and [y]) from [X].  There is\n    just one way of constructing evidence for members of this family:\n    applying the constructor [refl_equal] to a type [X] and a value [x\n    : X] yields evidence that [x] is equal to [x]. *)\n\n(** Here is a slightly different definition -- the one that actually\n    appears in the Coq standard library. *)\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\nNotation \"x =' y\" := (eq' _ x y)\n                     (at level 70, no associativity) : type_scope.\n\n(** **** Exercise: 3 stars, optional (two_defs_of_eq_coincide) *)\n(** Verify that the two definitions of equality are equivalent. *)\n\nTheorem two_defs_of_eq_coincide : forall (X:Type) (x y : X),\n  x = y <-> x =' y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The advantage of the second definition is that the induction\n    principle that Coq derives for it is precisely the familiar\n    principle of _Leibniz equality_: what we mean when we say \"[x] and\n    [y] are equal\" is that every property on [P] that is true of [x]\n    is also true of [y].  *)\n\nCheck eq'_ind.\n(* ===>\n     forall (X : Type) (x : X) (P : X -> Prop),\n       P x -> forall y : X, x =' y -> P y\n\n   ===>  (i.e., after a little reorganization)\n     forall (X : Type) (x : X) forall y : X,\n       x =' y ->\n       forall P : X -> Prop, P x -> P y *)\n\n(** One important consideration remains.  Clearly, we can use\n    [refl_equal] to construct evidence that, for example, [2 = 2].\n    Can we also use it to construct evidence that [1 + 1 = 2]?  Yes:\n    indeed, it is the very same piece of evidence!  The reason is that\n    Coq treats as \"the same\" any two terms that are _convertible_\n    according to a simple set of computation rules.  These rules,\n    which are similar to those used by [Eval simpl], include\n    evaluation of function application, inlining of definitions, and\n    simplification of [match]es.\n\n    In tactic-based proofs of equality, the conversion rules are\n    normally hidden in uses of [simpl] (either explicit or implicit in\n    other tactics such as [reflexivity]).  But you can see them\n    directly at work in the following explicit proof objects: *)\n\nDefinition four : 2 + 2 = 1 + 3 :=\n  refl_equal nat 4.\n\nDefinition singleton : forall (X:Set) (x:X), []++[x] = x::[]  :=\n  fun (X:Set) (x:X) => refl_equal (list X) [x].\n\nEnd MyEquality.\n\n(* ####################################################### *)\n(** ** Inversion, Again *)\n\n(** We've seen [inversion] used with both equality hypotheses and\n    hypotheses about inductively defined propositions.  Now that we've\n    seen that these are actually the same thing, we're in a position\n    to take a closer look at how [inversion] behaves...\n\n    In general, the [inversion] tactic\n\n    - takes a hypothesis [H] whose type [P] is inductively defined,\n      and\n\n    - for each constructor [C] in [P]'s definition,\n\n      - generates a new subgoal in which we assume [H] was\n        built with [C],\n\n      - adds the arguments (premises) of [C] to the context of\n        the subgoal as extra hypotheses,\n\n      - matches the conclusion (result type) of [C] against the\n        current goal and calculates a set of equalities that must\n        hold in order for [C] to be applicable,\n\n      - adds these equalities to the context (and, for convenience,\n        rewrites them in the goal), and\n\n      - if the equalities are not satisfiable (e.g., they involve\n        things like [S n = O]), immediately solves the subgoal. *)\n\n(** _Example_: If we invert a hypothesis built with [or], there are two\n   constructors, so two subgoals get generated.  The\n   conclusion (result type) of the constructor ([P \\/ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.\n\n   _Example_: If we invert a hypothesis built with [and], there is\n   only one constructor, so only one subgoal gets generated.  Again,\n   the conclusion (result type) of the constructor ([P /\\ Q]) doesn't\n   place any restrictions on the form of [P] or [Q], so we don't get\n   any extra equalities in the context of the subgoal.  The\n   constructor does have two arguments, though, and these can be seen\n   in the context in the subgoal.\n\n   _Example_: If we invert a hypothesis built with [eq], there is\n   again only one constructor, so only one subgoal gets generated.\n   Now, though, the form of the [refl_equal] constructor does give us\n   some extra information: it tells us that the two arguments to [eq]\n   must be the same!  The [inversion] tactic adds this fact to the\n   context.  *)\n\n(* ####################################################### *)\n(** * Relations as Propositions *)\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 LeFirstTry.\n\n(** We've already seen an inductive definition of one\n    fundamental relation: equality.  Another useful one is the \"less\n    than or equal to\" 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\nEnd LeFirstTry.\n\n(** This is a reasonable definition of the [<=] relation, but we\n    can streamline it a little by observing that the left-hand\n    argument [n] is the same everywhere in the definition, so we can\n    actually make it a \"general parameter\" to the whole definition,\n    rather than an argument to each constructor.  This is similar to\n    what we did in our second definition of the [eq] relation,\n    above. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle.\n    (The same was true of our second version of [eq].) *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(** By contrast, the induction principle that Coq calculates for the\n    first definition has a lot of extra quantifiers, which makes it\n    messier to work with when proving things by induction.  Here is\n    the induction principle for the first [le]: *)\n\n(* le_ind :\n     forall P : nat -> nat -> Prop,\n     (forall n : nat, P n n) ->\n     (forall n m : nat, le n m -> P n m -> P n (S m)) ->\n     forall n n0 : nat, le n n0 -> P n n0 *)\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)].) *)\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).\nProof.\n  (* WORKED IN CLASS *)\n  intros H. inversion H. inversion H1.  Qed.\n\n(** The \"strictly less than\" relation [n < m] can now be defined\n    in terms of [le]. *)\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, recommended (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: 3 stars, recommended (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(** State and prove an equivalent characterization of the relation\n    [R].  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(** **** Exercise: 3 stars, recommended (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, optional (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, 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, optional (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(** ** Digression: More Facts about [<=] and [<] *)\n\n(** Let's pause briefly to record several facts about the [<=]\n    and [<] relations that we are going to need later in the\n    course.  The proofs make good practice exercises. *)\n\n(** **** Exercise: 2 stars, optional (le_exercises) *)\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\nTheorem Sn_le_Sm__n_le_m : forall n m,\n  S n <= S m -> n <= m.\nProof.\n  intros n m.  generalize dependent n.  induction m.\n  (* FILL IN HERE *) Admitted.\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 (* 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 ble_nat_n_Sn_false : forall n m,\n  ble_nat n (S m) = false ->\n  ble_nat n m = false.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem ble_nat_false : forall n m,\n  ble_nat n m = false -> ~(n <= m).\nProof.\n  (* Hint: Do the right induction! *)\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (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_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_2:  nostutter [].\n(* FILL IN HERE *) Admitted.\n(*\n  Proof. repeat constructor; apply beq_false_not_eq; auto. Qed.\n*)\n\nExample test_nostutter_3:  nostutter [5].\n(* FILL IN HERE *) Admitted.\n(*\n  Proof. repeat constructor; apply beq_false_not_eq; 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, optional (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 this 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 an\n   assignment of items to labels: if there are more items than labels,\n   at least two items must have the same label.  You will almost\n   certainly need to use 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.  intros X l1. induction l1.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ####################################################### *)\n(** * Informal Proofs *)\n\n(** Q: What is the relation between a formal proof of a proposition\n       [P] and an informal proof of the same proposition [P]?\n\n    A: The latter should _teach_ the reader how to produce the\n       former.\n\n    Q: How much detail is needed?\n\n    A: There is no single right answer; rather, there is a range\n       of choices.\n\n      At one end of the spectrum, we can essentially give the\n      reader the whole formal proof (i.e., the informal proof\n      amounts to just transcribing the formal one into words).\n      This gives the reader the _ability_ to reproduce the formal\n      one for themselves, but it doesn't _teach_ them anything.\n\n      At the other end of the spectrum, we can say \"The theorem\n      is true and you can figure out why for yourself if you\n      think about it hard enough.\"  This is also not a good\n      teaching strategy, because usually writing the proof\n      requires some deep insights into the thing we're proving,\n      and most readers will give up before they rediscover all\n      the same insights as we did.\n\n      In the middle is the golden mean -- a proof that includes\n      all of the essential insights (saving the reader the hard\n      part of work that we went through to find the proof in the\n      first place) and clear high-level suggestions for the more\n      routine parts to save the reader from spending too much\n      time reconstructing these parts (e.g., what the IH says and\n      what must be shown in each case of an inductive proof), but\n      not so much detail that the main ideas are obscured.\n\n   Another key point: if we're talking about a formal proof of a\n   proposition P and an informal proof of P, the proposition P doesn't\n   change.  That is, formal and informal proofs are _talking about the\n   same world_ and they _must play by the same rules_. *)\n\n(* ####################################################### *)\n(** ** Informal Proofs by Induction *)\n\n(** Since we've spent much of this chapter looking \"under the hood\" at\n    formal proofs by induction, now is a good moment to talk a little\n    about _informal_ proofs by induction.\n\n    In the real world of mathematical communication, written proofs\n    range from extremely longwinded and pedantic to extremely brief\n    and telegraphic.  The ideal is somewhere in between, of course,\n    but while you are getting used to the style it is better to start\n    out at the pedantic end.  Also, during the learning phase, it is\n    probably helpful to have a clear standard to compare against.\n    With this in mind, we offer two templates below -- one for proofs\n    by induction over _data_ (i.e., where the thing we're doing\n    induction on lives in [Type]) and one for proofs by induction over\n    _evidence_ (i.e., where the inductively defined thing lives in\n    [Prop]).  In the rest of this course, please follow one of the two\n    for _all_ of your inductive proofs. *)\n\n(** *** Induction Over an Inductively Defined Set *)\n\n(** _Template_:\n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_:\n\n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if length [[] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of index.\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n            length l = length (x::l') = S (length l'),\n          it suffices to show that\n            index (S (length l')) l' = None.\n]]\n          But this follows directly from the induction hypothesis,\n          picking [n'] to be length [l'].  [] *)\n\n(** *** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_.\n\n    _Template_:\n\n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n\n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(* ################################################### *)\n(** ** Induction Principles for [/\\] and [\\/] *)\n\n(** The induction principles for conjunction and disjunction are a\n    good illustration of Coq's way of generating simplified induction\n    principles for [Inductive]ly defined propositions, which we\n    discussed in the last chapter.  You try first: *)\n\n(** **** Exercise: 1 star, optional (and_ind_principle) *)\n(** See if you can predict the induction principle for conjunction. *)\n\n(* Check and_ind. *)\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_ind_principle) *)\n(** See if you can predict the induction principle for disjunction. *)\n\n(* Check or_ind. *)\n(** [] *)\n\nCheck and_ind.\n\n(** From the inductive definition of the proposition [and P Q]\n     Inductive and (P Q : Prop) : Prop :=\n       conj : P -> Q -> (and P Q).\n    we might expect Coq to generate this induction principle\n     and_ind_max :\n       forall (P Q : Prop) (P0 : P /\\ Q -> Prop),\n            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->\n            forall a : P /\\ Q, P0 a\n    but actually it generates this simpler and more useful one:\n     and_ind :\n       forall P Q P0 : Prop,\n            (P -> Q -> P0) ->\n            P /\\ Q -> P0\n    In the same way, when given the inductive definition of [or P Q]\n     Inductive or (P Q : Prop) : Prop :=\n       | or_introl : P -> or P Q\n       | or_intror : Q -> or P Q.\n    instead of the \"maximal induction principle\"\n     or_ind_max :\n       forall (P Q : Prop) (P0 : P \\/ Q -> Prop),\n            (forall a : P, P0 (or_introl P Q a)) ->\n            (forall b : Q, P0 (or_intror P Q b)) ->\n            forall o : P \\/ Q, P0 o\n    what Coq actually generates is this:\n     or_ind :\n       forall P Q P0 : Prop,\n            (P -> P0) ->\n            (Q -> P0) ->\n            P \\/ Q -> P0\n]]\n*)\n\n(* ######################################################### *)\n(** ** Explicit Proof Objects for Induction *)\n\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n\n(** Recall the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\n(* Check nat_ind. *)\n(* ===>\n   nat_ind : forall P : nat -> Prop,\n      P 0%nat ->\n      (forall n : nat, P n -> P (S n)) ->\n      forall n : nat, P n  *)\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n\nPrint nat_ind.\n(* ===> (after some manual tidying)\n   nat_ind =\n    fun (P : nat -> Type)\n        (f : P 0)\n        (f0 : forall n : nat, P n -> P (S n)) =>\n          fix F (n : nat) : P n :=\n             match n as n0 return (P n0) with\n            | 0 => f\n            | S n0 => f0 n0 (F n0)\n            end.\n*)\n\n(** We can read this as follows:\n     Suppose we have evidence [f] that [P] holds on 0,  and\n     evidence [f0] that [forall n:nat, P n -> P (S n)].\n     Then we can prove that [P] holds of an arbitrary nat [n] via\n     a recursive function [F] (here defined using the expression\n     form [Fix] rather than by a top-level [Fixpoint]\n     declaration).  [F] pattern matches on [n]:\n      - If it finds 0, [F] uses [f] to show that [P n] holds.\n      - If it finds [S n0], [F] applies itself recursively on [n0]\n         to obtain evidence that [P n0] holds; then it applies [f0]\n         on that evidence to show that [P (S n)] holds.\n    [F] is just an ordinary recursive function that happens to\n    operate on evidence in [Prop] rather than on terms in [Set].\n\n    Aside to those interested in functional programming: You may\n    notice that the [match] in [F] requires an annotation [as n0\n    return (P n0)] to help Coq's typechecker realize that the two arms\n    of the [match] actually return the same type (namely [P n]).  This\n    is essentially like matching over a GADT (generalized algebraic\n    datatype) in Haskell.  In fact, [F] has a _dependent_ type: its\n    result type depends on its argument; GADT's can be used to\n    describe simple dependent types like this.\n\n    We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  Recall our desire to\n    prove that\n\n    [forall n : nat, even n -> ev n].\n\n    Attempts to do this by standard induction on [n] fail, because the\n    induction principle only lets us proceed when we can prove that\n    [even n -> even (S n)] -- which is of course never provable.  What\n    we did earlier in this chapter was a bit of a hack:\n\n    [Theorem even__ev : forall n : nat,\n     (even n -> ev n) /\\ (even (S n) -> ev (S n))].\n\n    We can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n\n *)\n\n Definition nat_ind2 :\n    forall (P : nat -> Prop),\n    P 0 ->\n    P 1 ->\n    (forall n : nat, P n -> P (S(S n))) ->\n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS =>\n          fix f (n:nat) := match n return P n with\n                             0 => P0\n                           | 1 => P1\n                           | S (S n') => PSS n' (f n')\n                          end.\n\n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive (try\n     it!).\n\n     The [induction ... using] tactic gives a convenient way to\n     specify a non-standard induction principle like this. *)\n\nLemma even__ev' : forall n, even n -> ev n.\nProof.\n intros.\n induction n as [ | |n'] using nat_ind2.\n  Case \"even 0\".\n    apply ev_0.\n  Case \"even 1\".\n    inversion H.\n  Case \"even (S(S n'))\".\n    apply ev_SS.\n    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H.\nQed.\n\n(* ######################################################### *)\n(** ** The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is \"why\n    trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard Correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on.\n\n    There are a few additional wrinkles:\n\n    - Since Coq types can themselves be expressions, the checker must\n      normalize these (by using the conversion rules) before\n      comparing them.\n\n    - The checker must make sure that [match] expressions are\n      _exhaustive_.  That is, there must be an arm for every possible\n      constructor.  To see why, consider the following alleged proof\n      object:\n      Definition or_bogus : forall P Q, P \\/ Q -> P :=\n        fun (P Q : Prop) (A : P \\/ Q) =>\n           match A with\n           | or_introl H => H\n           end.\n      All the types here match correctly, but the [match] only\n      considers one of the possible constructors for [or].  Coq's\n      exhaustiveness check will reject this definition.\n\n    - The checker must make sure that each [fix] expression\n      terminates.  It does this using a syntactic check to make sure\n      that each recursive call is on a subexpression of the original\n      argument.  To see why this is essential, consider this alleged\n      proof:\n          Definition nat_false : forall (n:nat), False :=\n             fix f (n:nat) : False := f n.\n      Again, this is perfectly well-typed, but (fortunately) Coq will\n      reject it. *)\n\n(** Note that the soundness of Coq depends only on the correctness of\n    this typechecking engine, not on the tactic machinery.  If there\n    is a bug in a tactic implementation (and this certainly does\n    happen!), that tactic might construct an invalid proof term.  But\n    when you type [Qed], Coq checks the term for validity from\n    scratch.  Only lemmas whose proofs pass the type-checker can be\n    used in further proof developments.  *)\n\n", "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/softwarefoundations/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7102747160248181}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (y : natural) (lf1 : natural)\n  : natural := mult x lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj195_coqofml_rgldij.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7102006442352431}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) (lf1 : natural)\n  : natural := mult lf2 x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj194_coqofml_IQmTrl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7102006413487456}}
{"text": "(* Exercise 101a *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\n(* Double Contrapositive, give a classical proof *)\n\nTheorem exercise_101a : (A -> B) -> (~~A -> ~~B).\nProof.\nimp_i Sigma.\nimp_i first.\nneg_i B second.\nhyp second.\nimp_e A.\nhyp Sigma.\nneg_e' (~A) third.\nhyp first.\nhyp third.\n\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak10/Taak10_prop101a.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7102006384622477}}
{"text": "Require Import Lib.\nRequire Import Relation_Definitions Setoid.\n\nModule Expressions.\n\n  Require Export Heyting.\n  Export HeytingTerms.\n  Export HeytingProps.\n\n(* Expressions, as defined in Kanckos section 5.1 *)\nInductive expr : Set :=\n| E0 : expr\n| E1 : expr\n| Eω : expr\n| EX : Φ -> nat -> expr (* TODO: Phil: A in Φ and i in ℕ instead? *)\n| Eplus : expr -> expr -> expr\n| Epair : expr -> expr -> expr.\n\nNotation \"( e1 , e2 )\" := (Epair e1 e2).\nNotation \"e1 # e2\"     := (Eplus e1 e2) (at level 50, left associativity).\n\nInductive eeq : expr -> expr -> Prop :=\n| eeq_refl  : forall f,     eeq f f                            (* text *)\n| eeq_pluss : forall f g,   eeq (f # g) (g # f)                (* 3 *)\n| eeq_plust : forall f g h, eeq ((f # g) # h) (f # (g # h))    (* 3 *)\n| eeq_id1   : forall f,     eeq (f # E0) f                     (* 5 *)\n| eeq_id2   : forall f g,   eeq (f # g) f -> eeq g E0          (* 5 *)\n| eeq_pr0   : forall f,     eeq (E0, f) f                      (* 12 *)\n| eeq_pair1 : forall f g h, eeq (f, (g # h)) ((f, g) # (f, h)) (* 8 *)\n| eeq_pair2 : forall f g h, eeq (f, (g, h)) ((f # g), h)       (* 13 *)\n| eeq_symm  : forall f g,   eeq f g -> eeq g f                 (* ADDED *)\n| eeq_trans : forall f g h, eeq f g -> eeq g h -> eeq f h      (* ADDED *)\n.\n\nNotation \"e1 == e2\" := (eeq e1 e2) (at level 70).\n\n(* Additional axioms required for rewriting tactics. *)\nAxiom plus_compat : forall f1 f2, f1 == f2 ->\n                    forall g1 g2, g1 == g2 ->\n                    f1 # g1 == f2 # g2.\nAxiom pair_compat : forall f1 f2, f1 == f2 ->\n                    forall g1 g2, g1 == g2 ->\n                    (f1, g1) == (f2, g2).\n\n(* this is blatantly copied without understanding from\n   https://coq.inria.fr/refman/Reference-Manual029.html *)\nAdd Parametric Relation : expr eeq\n    reflexivity proved by eeq_refl\n    symmetry proved by eeq_symm\n    transitivity proved by eeq_trans\n  as eeq_rel.\n\nAdd Parametric Morphism : Eplus with\nsignature eeq ==> eeq ==> eeq as eplus_mor.\nProof.\n  exact plus_compat.\nQed.\n\nAdd Parametric Morphism : Epair with\nsignature eeq ==> eeq ==> eeq as epair_mor.\nProof.\n  exact pair_compat.\nQed.\n\nInductive elt : expr -> expr -> Prop :=\n| elt_01    : elt E0 E1                                        (* 6 *)\n| elt_1ω    : elt E1 Eω                                        (* 6 *)\n| elt_trans : forall f g h, elt f g -> elt g h -> elt f h      (* 1 *)\n| elt_plus  : forall f g h, elt f g -> elt (f # h) (g # h)     (* 4 *)\n| elt_lim   : forall f g, elt f Eω -> elt g Eω\n                          -> elt (f # g) Eω                    (* 7 *)\n| elt_pair1 : forall f g h, elt f g -> elt (h, f) (h, g)       (* 10 *)\n| elt_pair2 : forall f g h, elt f g -> elt E0 h\n                            -> elt (f, h) (g, h)               (* 11 *)\n.\n\nNotation \"e1 ≺ e2\"  := (elt e1 e2) (at level 70).\n\n(* Axiom 2: if f ≺ g then ¬(f == g), doesn't fit in inductive definitions *)\nAxiom elt_neq : forall f g: expr, f ≺ g -> ~(f == g).\n\n(* does this make any difference? should/can I declare it as a partial order? *)\nAdd Parametric Relation : expr elt\n    transitivity proved by elt_trans\n  as elt_rel.\n\nInductive ele : expr -> expr -> Prop :=\n| ele_lt    : forall f g, f ≺ g -> ele f g                     (* text *)\n| ele_eq    : forall f g, f == g -> ele f g                    (* text *)\n| ele_0     : forall f, ele E0 f                               (* 6 *)\n| ele_pair  : forall f g h c, g ≺ c -> h ≺ c\n                              -> ele ((g, f) # (h, f)) (c, f)  (* 9 *)\n.\n\nNotation \"e1 ≼ e2\"  := (ele e1 e2) (at level 70).\n\n(* A basic theorem that should expose the need for axioms that are left\n   implicit in the paper. (Question: is there an easier way here?!) *)\nTheorem ele_eq_lt : forall f g : expr, f ≼ g -> f == g \\/ f ≺ g.\nadmit. Qed.\n(* Proof.\n  intros f g H.\n  induction H as [f g | f g | f | f g h c].\n  Case \"f ≺ g\". right. apply H.\n  Case \"f == g\". left. apply H.\n  Case \"0 ≼ f\". induction f. (* originally I thought I could just destruct f *)\n  SCase \"f == 0\". left. reflexivity.\n  SCase \"f == 1\". right. apply elt_01.\n  SCase \"f == ω\". right. apply elt_trans with (E1). apply elt_01. apply elt_1ω.\n  (* For the next subcases, ;: I want to substitute E0 for f1 and f2\n   * but don't know how to get that from eeq. *)\n  SCase \"f == f1 + f2\". inversion IHf1.\n  inversion IHf2.\n  SSCase \"f == 0 + 0\". left. rewrite <- H. rewrite <- H0. rewrite eeq_id1.\n    reflexivity.\n  SSCase \"f == 0 + <0\". right.\n    (* PROBLEM: can't rewrite, replace wants = not == *)\n    (* maybe need to declare properties of ≺ similar to morphisms # and (,) *)\n    replace (f1) with (E0). replace (E0 # f2) with (f2 # E0).\n    replace (f2 # E0) with f2. apply H0.\n    (* just admitting all the replacements *)\n    admit. admit. admit.\n  (* TODO the rest - presently just admitted *)\n  inversion IHf2.\n  SSCase \"f == >0 + 0\". right. admit. SSCase \"f == <0 + <0\". right. admit.\n  SCase \"f == (f1, f2)\". inversion IHf1.\n  inversion IHf2.\n  SSCase \"f == (0, 0)\". left. admit. SSCase \"f == (0, <0)\". right. admit.\n  inversion IHf2.\n  SSCase \"f == (>0, 0)\". right. admit. SSCase \"f == (<0, <0)\". right. admit.\n  Case \"(g, f) # (h, f)\". admit.\nQed. *)\n\nTheorem elt_eeq_trans : forall f g h: expr, f ≺ g -> g == h -> f ≺ h.\nProof.\nAdmitted. (* TODO *)\n\nTheorem eeq_elt_trans : forall f g h: expr, f == g -> g ≺ h -> f ≺ h.\nProof.\nAdmitted. (* TODO *)\n\nTheorem ele_trans : forall f g h: expr, f ≼ g -> g ≼ h -> f ≼ h.\nProof.\n  intros f g h Hfg Hgh.\n  apply ele_eq_lt in Hfg. apply ele_eq_lt in Hgh.\n  inversion Hfg. inversion Hgh.\n  Case \"f == g == h\".\n    apply ele_eq. apply eeq_trans with (g). apply H. apply H0.\n  Case \"f == g ≺ h\".\n    (* BASED ON TODO *)\n    apply ele_lt. apply eeq_elt_trans with (g). apply H. apply H0.\n  inversion Hgh.\n  Case \"f ≺ g == h\".\n    (* BASED ON TODO *)\n    apply ele_lt. apply elt_eeq_trans with (g). apply H. apply H0.\n  Case \"f ≺ g ≺ h\". apply ele_lt. apply elt_trans with (g). apply H. apply H0.\nQed.\n\n\n(* A theorem stated at the end of section 5.1. Not sure about its use, but\n * but it's a good start at using these axioms. *)\n\nTheorem th51 : forall f g h,\n                 E0 ≺ f -> E0 ≺ h -> (f, g) # h ≺ (f, g # h).\nProof.\n  intros f g h H1 H2.\n  (* TODO make the rewriting rules work. *)\n  (* rewrite eeq_pair1. *)\nAbort.\n\n(* 5.2 Vectors *)\nDefinition Vect := list expr. (* 0 -> n *)\n\n(* point-wise vector addition on page 5 *)\nFixpoint vect_add (l r : Vect) : Vect :=\n  match l,r with\n    | nil, r => r\n    | l, nil => l\n    | cons x l', cons y r' => cons (Eplus x y) (vect_add l' r')\n  end.\n\n(* access vector l at index i *)\nFixpoint vect_at (l : Vect) (i : nat): expr :=\n  match l with\n    | cons h t => match i with\n                    | S i' => vect_at t i'\n                    | O => h\n                  end\n    | nil => E0\n  end.\n\n\n(* vector of variables, page 5 *)\n\nFixpoint level φ :=\n  match φ with\n    | bot        => 0\n    | top        => 0\n    | teq _ _    => 0\n    | Disj φ₁ φ₂ => max (level φ₁) (level φ₂)\n    | Conj φ₁ φ₂ => max (level φ₁) (level φ₂)\n    | Imp φ₁ φ₂  => max (S (level φ₁)) (level φ₂)\n    | Ex _ φ'    => level φ'\n    | All _ φ'   => level φ'\n  end.\n\nFixpoint vect_x_rev (A: Φ) (n: nat): Vect :=\n  match n with\n    | 0 => cons (EX A 0) nil\n    | S n' => cons (EX A n) (vect_x_rev A n')\n  end.\nDefinition vect_x (A: Φ): Vect := rev (vect_x_rev A (level A)).\n\nInductive expr_has_var: expr -> Prop :=\n| x_has_var: forall A i, expr_has_var (EX A i)\n| plus_has_var_l: forall f g, expr_has_var f -> expr_has_var (Eplus f g)\n| plus_has_var_r: forall f g, expr_has_var g -> expr_has_var (Eplus f g)\n| pair_has_var_l: forall f g, expr_has_var f -> expr_has_var (Epair f g)\n| pair_has_var_r: forall f g, expr_has_var g -> expr_has_var (Epair f g).\n\n(* Definition 5.3 *)\nInductive expr_class: expr -> nat -> Prop :=\n| expr_class_no_x: forall h i, ~ (expr_has_var h) -> expr_class h i\n| expr_class_form: forall A i, expr_class (EX A i) i\n| expr_class_plus: forall f g i, expr_class f i -> expr_class g i -> expr_class (Eplus f g) i\n| expr_class_pair: forall f g i, expr_class f (S i) -> expr_class g i -> expr_class (Epair f g) i.\n\n(* Definition of ℂ right below 5.3 *)\nFixpoint well_classed_from (i: nat) (hs: Vect): Prop :=\n  match hs with\n    | nil => True\n    | cons h hs' => expr_class h i /\\ well_classed_from (S i) hs'\n  end.\n\nDefinition well_classed (hs: Vect): Prop := well_classed_from 0 hs.\n\n(* 5.4 box operation *)\nFixpoint box (fs gs: Vect): Vect :=\n  match fs, gs with\n    | nil, gs => gs\n    | fs, nil => fs\n    | cons f fs', cons g gs' =>\n      match box fs' gs' with\n        | nil                => cons (Eplus f g) nil\n        | (cons h hs') as hs => cons (Epair h (Eplus f g)) hs\n      end\n  end.\n\n(* TODO 5.5 delta operation *)\n\n(* vector restriction *)\nFixpoint restrict_vector (fs: Vect) (n: nat): Vect :=\n  match fs with\n    | nil => nil\n    | cons f fs' => match n with\n                      | 0 => nil\n                      | S n' => cons f (restrict_vector fs' n')\n                    end\n  end.\n\n(* vector assignment *)\nDefinition vect_add_1 (fs: Vect): Vect := map (fun f => Eplus f E1) fs.\nFixpoint assign (d: deriv): Vect. admit.\n(*\nmatch d with\n(* 1 *)\n| asm A => vect_x A\n(* 2 *)\n| teq _ _ => cons E0 nil\n(* 3 *)\n| arith_imp p _ => assign p\n(* 4 *)\n| intro_conj A B => Eplus (assign A) (assign B) (* TODO: wtf is `TR`? *)\n(* 5 *)\n| elim_conj_l AB => vect_add_1 (assign AB)\n| elim_conj_r AB => vect_add_1 (assign AB)\n(* 6 *)\n| intro_disj_l A => vect_add_1 (assign A)\n| intro_disj_r B => vect_add_1 (assign B)\n(* 7 TODO A, B? *)\n| elim_disj AB AC BC =>\n  box (assign AB) (vect_add (delta A (assign AC)) (delta B (assign BC))) \n(* 8 *)\n| intro_imp AB => delta A (assign AB) (* TODO A? *)\n(* 9 *)\n| elim_imp AB A => box (assign AB) (assign A)\n(* 10 *)\n| intro_all A' _ => assign A'\n(* 11 *)\n| elim_all A => vect_add_1 (assign A)\n(* 12 *)\n| intro_ex A' => assign A'\n(* 13 TODO A'? *)\n| elim_ex A AC => box (assign A) (delta A' (assign AC))\n(* 14 *)\n| elim_bot bot => vect_add_1 (assign bot)\n(* 15 WTF *)\n.\nend.\n*)\n\n\n\nEnd Expressions.\n", "meta": {"author": "philnguyen", "repo": "630-project", "sha": "1c2b3755aec090b3e4164400edb10af8638f7d52", "save_path": "github-repos/coq/philnguyen-630-project", "path": "github-repos/coq/philnguyen-630-project/630-project-1c2b3755aec090b3e4164400edb10af8638f7d52/coq/Expressions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.7102006319215687}}
{"text": "Require Import ZArith.\nRequire Import ZPolS.\nRequire Import PolSBase.\nRequire Import PolFBase.\nRequire Import PolAux.\nRequire Import PolAuxList.\nRequire Import ZSignTac.\n\n\nDefinition Zfactor :=\n  factor Z Zplus Zmult Z.opp 0%Z 1%Z is_Z1 is_Z0 is_Zpos is_Zdiv Z.div Zgcd.\n\nDefinition Zfactor_minus :=\n  factor_sub Z Zplus Zmult Z.opp 0%Z 1%Z is_Z1 is_Z0 is_Zpos is_Zdiv Z.div Zgcd.\n\nDefinition Zget_delta :=\n  get_delta Z Zplus Zmult Z.opp 0%Z 1%Z is_Z1 is_Z0 is_Zpos is_Zdiv Z.div Zgcd.\n\n\nLtac Zfactor_term term1 term2 :=\n  let term := constr:(Zminus term1 term2) in\n  let rfv := FV ZCst Zplus Zmult Zminus Z.opp term (@nil Z) in\n  let fv := Trev rfv in\n  let expr1 := mkPolexpr Z ZCst Zplus Zmult Zminus Z.opp term1 fv in\n  let expr2 := mkPolexpr Z ZCst Zplus Zmult Zminus Z.opp term2 fv in\n  let re := (eval vm_compute in (Zfactor_minus (PEsub expr1 expr2))) in\n  let factor := match re with (PEmul ?X1 _) => X1 end in\n  let expr3 := match re with (PEmul _ (PEsub ?X1 _)) => X1 end in\n  let expr4 := match re with (PEmul _ (PEsub _ ?X1 )) => X1 end in\n  let re1' :=\n      (eval\n         unfold\n         Zconvert_back, convert_back, pos_nth, jump,\n       hd, tl in (Zconvert_back (PEmul factor expr3) fv))\n  in\n  let re1'' := (eval lazy beta in re1') in\n  let re2' :=\n      (eval\n         unfold\n         Zconvert_back, convert_back, pos_nth, jump,\n       hd, tl in (Zconvert_back (PEmul factor expr4) fv))\n  in\n  let re2'' := (eval lazy beta in re2') in\n  replace2_tac term1 term2 re1'' re2''; [idtac | ring | ring].\n\nLtac zpolf :=\n  try match goal with\n      | |- (?X1 = ?X2)%Z => Zfactor_term X1 X2\n      | |- (?X1 <> ?X2)%Z => Zfactor_term X1 X2\n      | |- Z.lt ?X1 ?X2 => Zfactor_term X1 X2\n      | |- Z.gt ?X1 ?X2 => Zfactor_term X1 X2\n      | |- Z.le ?X1 ?X2 => Zfactor_term X1 X2\n      | |- Z.ge ?X1 ?X2 => Zfactor_term X1 X2\n      | _ => fail end;\n  try zsign_tac; try repeat (rewrite Zmult_1_l || rewrite Zmult_1_r).\n\nLtac hyp_zpolf H :=\n  progress\n    (generalize H;\n     try match type of H with\n         | (?X1 = ?X2)%Z => Zfactor_term X1 X2\n         | (?X1 <> ?X2)%Z => Zfactor_term X1 X2\n         | Z.lt ?X1 ?X2 => Zfactor_term X1 X2\n         | Z.gt ?X1 ?X2 => Zfactor_term X1 X2\n         | Z.le ?X1 ?X2 => Zfactor_term X1 X2\n         | Z.ge ?X1 ?X2 => Zfactor_term X1 X2\n         | _ => fail end);\n  clear H; intros H;\n  try hyp_zsign_tac H; try repeat rewrite Zmult_1_l.\n", "meta": {"author": "thery", "repo": "PolTac", "sha": "cb5e530fdd8a1c72882d33b49146d397363103f2", "save_path": "github-repos/coq/thery-PolTac", "path": "github-repos/coq/thery-PolTac/PolTac-cb5e530fdd8a1c72882d33b49146d397363103f2/ZPolF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7102006282673876}}
{"text": "(** * カリーハワード対応とCoqのあいだ - Show Proof で学ぶ Coq のしくみ -\n\nCoq はカリーハワード対応を利用して\n証明をプログラムによって表現しているというのはよく知られています。\n\nカリーハワード対応というのは、\n命題と型、証明とプログラムが同じ構造になっているという話です。\n\nしかし、Coq の proof editing mode で証明をしていると、\n証明項（プログラムのことですが、あまりプログラムとしては意識しないので証明項と呼びましょう）\nがどのようなものか意識することは少ないのではないでしょうか。\n\nたとえば、intros H がなにをする（どんな証明項を構築する）のか\nわかるでしょうか。\n\nここでは Coq のいろいろなコマンドがなにをするものなのか、また、\nそれをどうやって調べるのか説明します。\n\n*)\n\n(**\n\n- 自動証明\n  - % auto % # <a href=\"auto.html\">auto</a> #\n- 証明項を直接指定する\n  - % exact % # <a href=\"exact.html\">exact</a> #\n  - refine\n- 関数抽象を構築する\n  - % intro % # <a href=\"intro.html\">intro</a> #\n  - % move=> % # <a href=\"ssr_intro.html\">move=&gt;</a> # (SSReflect)\n  - % Section % # <a href=\"section.html\">Section</a> #\n- 関数適用とその引数部分を構築する\n  - % revert % # <a href=\"revert.html\">revert</a> #\n  - % generalize % # <a href=\"generalize.html\">generalize</a> #\n  - % move:% # <a href=\"ssr_discharge.html\">move:</a> # (SSReflect)\n- 関数適用とその関数部分を構築する\n  - % apply % # <a href=\"apply.html\">apply</a> #\n- let 式を構築する\n  - % pose, set % # <a href=\"set.html\">pose, set</a> #\n  - % specialize % # <a href=\"specialize.html\">specialize</a> #\n  - have @var (SSReflect)\n- eq_refl で等式を証明する\n  - % reflexivity % # <a href=\"reflexivity.html\">reflexivity</a> #\n- eq_ind_r で等式による書き換えを行う\n  - % rewrite % # <a href=\"rewrite.html\">rewrite</a> #\n  - % rewrite % # <a href=\"ssr_rewrite.html\">rewrite</a> # (SSReflect)\n- match 式を構築する\n  - % destruct % # <a href=\"destruct.html\">destruct</a> #\n  - % case % # <a href=\"ssr_case.html\">case</a> # (SSReflect)\n- simpl change unfold fold pattern\n- clear rename move_after\n- 数学的帰納法を適用する\n  - % induction % # <a href=\"induction.html\">induction</a> #\n  - elim (SSReflect)\n- f_equal\n  congr (SSReflect)\n- assert\n  have (SSReflect)\n- wlog (SSReflect)\n  suff (SSReflect)\n- replace\n- unlock\n- injection case_eq\n- now\n- discriminate\n- assumption\n- contradiction\n- inversion\n- subst\n\n*)\n\n(**\nURL:\n% https://akr.github.io/coq-curry-howard/curry_howard.html %\n# <a href=\"https://akr.github.io/coq-curry-howard/curry_howard.html\">https://akr.github.io/coq-curry-howard/curry_howard.html</a> #\n\nリポジトリ:\n% https://github.com/akr/coq-curry-howard %\n# <a href=\"https://github.com/akr/coq-curry-howard\">https://github.com/akr/coq-curry-howard</a> #\n*)\n", "meta": {"author": "akr", "repo": "coq-curry-howard", "sha": "37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5", "save_path": "github-repos/coq/akr-coq-curry-howard", "path": "github-repos/coq/akr-coq-curry-howard/coq-curry-howard-37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5/theories/curry_howard.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7101369326721996}}
{"text": "Require Import List.\nImport ListNotations.\n\n(** *Bibliothèque standard *)\n\nPrint nat.\nLocate \"+\".\nPrint Nat.add.\nLocate \"*\".\nPrint Nat.mul.\n\nPrint list.\nLocate \"++\".\nPrint app.\n\nPrint True.\n\nPrint False.\n\nPrint or.\nLocate \"\\/\".\n\nPrint and.\nLocate \"/\\\".\n\nPrint not.\nLocate \"~\".\n\n(** *Logique : le tiers exclu *)\n\n(* Axiomes possibles pour la logique classique *)\n\nDefinition tiersExclu : Prop := forall P : Prop, P \\/ ~P. \nDefinition involutionNegation : Prop := forall P : Prop, ~~P -> P. \nDefinition implicationMaterielle : Prop := forall P Q : Prop, (P -> Q) -> (~P \\/ Q). \nDefinition reciproqueContraposition : Prop := forall P Q : Prop, (~Q -> ~P) -> (P -> Q). \n(* Indication pour la suite : si besoin, utiliser la tactique \"unfold\" pour déplier\n   la définition d'une des propositions précédentes. *)\n\n(* Réciproques valides *)\n\n(*\n  Indication :\n  - la négation *~P* est définie comme *P -> False*.            \n *)\nProposition reciproqueInvolutionNegation :\n  forall P : Prop, P -> ~~P.\nProof.\n  intros P H non.\n  apply non.\n  apply H.\nQed.\n\n(*\n  Indication :\n  - décomposer la disjonction en hypothèse,\n  - lorsque les hypothèses entrainent une contradiction,\n  utiliser la tactique exfalso.\n *)\nProposition reciproqueImplicationMaterielle :\n  forall P Q : Prop, (~P \\/ Q) -> P -> Q.\nProof.\n intros P Q H_ou.\n  case H_ou.\n  - intros H2 p.\n    exfalso.\n    apply H2.\n    apply p.\n  - intros H1 H2.\n    apply H1.\nQed.\n\n\nProposition contraposition :\n  forall P Q : Prop, (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H H0 H1.\n  apply H0.\n  apply H.\n  exact H1.\nQed.\n\n(* Equivalence des axiomes *)\n\n(*\n  Indication :\n  - décomposer le tiers exclu appliqué à la proposition.\n *)\nProposition tiersExcluVersInvolutionNegation :\n  tiersExclu -> involutionNegation.\nProof.\n  intros H_ou.\n  intros P.\n  case (H_ou P).\n  - intros xP H2.\n    exact xP.\n  - intros H2.\n  intros H3.\n  exfalso.\n  apply H3.\n  exact H2.\nQed.\n(*\n  Indication :\n  - appliquer l'involution de la négation à (P \\/ ~P),\n  - utiliser le fait que (~(P \\/ ~P)) entraine ~P,\n  - utiliser les tactiques \"left\" et \"right\" pour prouver une disjonction. \n *)\nProposition involutionNegationVersTiersExclu :\n  involutionNegation -> tiersExclu.\nProof.\n    intros InvolutionNegation P.\n    apply(InvolutionNegation (P \\/ ~ P)).\n    intro H_nega_ou_non.\n    apply H_nega_ou_non.\n    right.\n    intro p'.\n    apply H_nega_ou_non.\n    left.\n    exact p'.\nQed.\n\n\n(*\n  Indication :\n  - décomposer la preuve de la disjonction (P \\/ ~P) obtenue en appliquant\n  le lemme involutionNegationVersTiersExclu à la proposition P.\n *)\nProposition involutionNegationVersImplicationMaterielle :\n  involutionNegation -> implicationMaterielle.\nProof.\n intros H1 P Q.\n  intros H2.\n  apply involutionNegationVersTiersExclu in H1.\n  case (H1 P).\n  - intros P'.\n    right.\n    apply H2.\n    exact P'.\n  - intros H3.\n    left.\n    exact H3.\nQed.\nCheck or_comm.\n(*\n  Indication :\n  - utiliser la proposition or_comm exprimant la commutativité de la disjonction (or).\n *)\nProposition implicationMaterielleVersTiersExclu :\n  implicationMaterielle -> tiersExclu.\nProof.\n  intros H1 P1.\n  apply or_comm.\n  apply H1.\n  intro P2.\n  exact P2.\n  apply P2.\nQed.\n(*\n  Indication :\n  - utiliser deux propositions déjà montrées.\n *)\nProposition implicationMaterielleVersInvolutionNegation :\n  implicationMaterielle -> involutionNegation.\nProof.\n  unfold implicationMaterielle.\n  unfold involutionNegation.\n  intro h.\n  apply tiersExcluVersInvolutionNegation.\n  apply implicationMaterielleVersTiersExclu.\n  exact h.\nDefined.\n(*\n  Indication :\n  - utiliser l'involution de la négation.\n *)\nProposition implicationMaterielleVersReciproqueContraposition :\n  implicationMaterielle -> reciproqueContraposition.\nProof.\n  intros IM P Q.\n  intros n_q_n_p p.\n  apply implicationMaterielleVersInvolutionNegation.\n  assumption.\n  intro n_q.\n  apply n_q_n_p.\n  apply  n_q.\n  exact p.\nQed.\n\n(*\n  Indication :\n  - appliquer la réciproque de la contraposition à True et P.\n *)\nProposition reciproqueContrapositionVersInvolutionNegation :\n  reciproqueContraposition -> involutionNegation.\nProof.\n  unfold reciproqueContraposition.\n  unfold involutionNegation.\n  intros.\n  apply (H True P)\n  intros P' H'.\n  apply H0.\n  exact P'.\n  exact I\nAdmitted.\n\n(** *Définitions inductives - La croissance de listes *)\n\nInductive EstCroissante : list nat -> Prop :=\n| videCroissante : EstCroissante []\n| singletonCroissante : forall a, EstCroissante [a]\n| consConsCroissante :\n    forall a b l, (a <= b)\n             -> EstCroissante (b :: l) -> EstCroissante( a :: b :: l).\n\n(*\n  --------- [precVide]\n  Prec m []\n  \n  (t : nat)  (r : list nat)  (m <= t)\n  ----------------------------------- [precCons]\n  Prec m (t :: r)\n *)\nInductive Prec(m : nat) : list nat -> Prop :=\n|precVide : Prec m []\n|precCons : forall t r, (m<=t) -> Prec m(t::r).\n\n(* à compléter\n   \n----------------- [videCroissante2]\n\n\n(t: nat) (r: list nat) (precCons t r) /\\ EstCroissante2\n--------------------------------------------------------- [consCroissante2]\nEstCroissante2(t::r)\n *)\n\nInductive EstCroissante2 : list nat -> Prop :=\n|videCroissante2: EstCroissante2 []\n|consCroissante2 : forall (t:nat) (r: list nat), (Prec t r) /\\ EstCroissante2 r -> EstCroissante2(t::r).\n\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (EstCroissante2 l) ;\n  dans le cas d'une liste non vide, décomposer par cas la preuve\n  du prédicat Prec.\n *)\nProposition adequation_estCroissante2 : forall l,\n    EstCroissante2 l -> EstCroissante l.\nProof.\n  intros.\n  induction H as [| t r h h2 h3 ].\n  - apply videCroissante.\n  - case h as [| t2 r2 h1].\n    + apply singletonCroissante.\n    + apply consConsCroissante.\n  exact h1.\n  exact h3.\nDefined.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (EstCroissante l).\n *)\nProposition completude_estCroissante2 : forall l,\n    EstCroissante l -> EstCroissante2 l.\nProof.\n  intros.\n  induction H.\n  - exact videCroissante2.\n  - apply consCroissante2.\n    + exact (precVide a).\n    + exact videCroissante2.\n  - apply consCroissante2.\n    + apply precCons.\n      exact H.\n    + exact IHEstCroissante.\nDefined.\n\n(** *Définitions inductives - Facteurs d'une liste *)\n\nProposition associativite_concatenation :\n  forall T : Type,\n  forall l1 l2 l3 : list T,\n    l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\n  intros T l1 l2 l3.\n  induction l1 as [|pn].\n  - simpl. reflexivity.\n  - cbn.\n    rewrite <- IHl1.\n    reflexivity.\nQed.\n\n\n(* à compléter \n  Prefixe k l \n------------------ [facteurPrefixe]\n  Facteur k l\n\nFacteur k l \n-------------------------------- [facteurInterne]\nFacteur k a::l\n *)\n\nInductive Facteur{A : Type}(k : list A) : list A -> Prop :=\n| facteurPrefixe : forall l, Facteur k (k++l) \n| facteurInterne : forall l1 l2, Facteur k l2 -> Facteur k (l1++l2).\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de *Facteur k l*,\n  - pour prouver l'existence, utiliser la tactique \"exists w\", où w est le terme\n  montrant l'existence.\n *)\nLemma adequation_Facteur :\n  forall A, forall k l : list A, Facteur k l -> exists k' k'', k' ++ k ++ k'' = l.\nProof.\n  intros A k l H.\n  induction H.\n  - exists nil.\n    exists l.\n    cbn.\n    reflexivity.\n  - case IHFacteur as [k' eg].\n    exists ( l1 ++ k' ).\n    cbn.\n    case eg as [k'' egg].\n    exists k''.\n    case egg.\n    simpl.\n    rewrite <- associativite_concatenation.\n    reflexivity.\nQed.\n\n(*\n  Indication :\n  - utiliser directement les constructeurs de Facteur.\n *)\nLemma completude_Facteur :\n  forall A, forall k' k k'' l : list A, k' ++ k ++ k'' = l -> Facteur k l.\nProof.\n  intros A k' k k'' l HSomme.\n  induction HSomme.\n  apply facteurInterne.\n  apply facteurPrefixe.\nQed.  \n\n(** *Entiers naturels - Des fonctions et des propositions utiles *)\n\n(* Addition et ordre *)\n\nLemma neutraliteDroite_addition :\n  forall n : nat, n = n + 0.\nProof.\n  intros n.\n  induction n.\n  - simpl.\n    reflexivity.\n  - simpl.\n    case IHn.\n    reflexivity.\nQed.\n\nLemma sommeSuccesseurs :\n  forall n m : nat,\n    S n + S m = S (S (n + m)).\nProof.\n  intros n m.\n  induction n.\n  - simpl.\n    reflexivity.\n  - simpl.\n    case IHn.\n    reflexivity.\nQed.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (n2 <= n3).\n *)\nProposition transitivite_le :\n  forall n1 n2 n3, n1 <= n2 -> n2 <= n3 -> n1 <= n3.\nProof.\n  intros n1 n2 n3 H0 H1.\n  case H1.\n  - apply H0.\n  - intros.\n    apply le_S.\n    rewrite H0.\n    apply H.\nQed.  \n    \nProposition zeroMin_le :\n  forall n, 0 <= n.\nProof.\n  intro n.\n  induction n.\n  - apply le_n.\n  - apply le_S.\n    apply IHn.\nQed.\n\nLemma successeurCroissant_le :\n  forall m n, m <= n -> S m <= S n.\nProof.\nintros n m H.\n    induction H as [|pn HR].\n    apply le_n.\n    apply le_S.\n    apply IHHR.\nQed.\n\n(*\n  Indication :\n  - procéder par induction sur m,\n  - utiliser successeurCroissant_le.\n *)\nLemma compatibiliteAdditionGauche_le : \n  forall m n1 n2, n1 <= n2 -> (m + n1) <= (m + n2).\nProof.\n  intros m n1 n2 H.\n  induction m.\n  - simpl.\n    apply H.\n  - simpl.\n    apply successeurCroissant_le.\n    apply IHm.\nQed.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (m1 <= m2),\n  - utiliser compatibiliteAdditionGauche_le.\n *)\nProposition compatibiliteAddition_le :\n  forall m1 m2 n1 n2, m1 <= m2 -> n1 <= n2 -> (m1 + n1) <= (m2 + n2).\nProof.\n  intros m1 m2 n1 n2 H0 H1.\n  induction H0.\n  - cbn.\n    apply compatibiliteAdditionGauche_le.\n    apply H1.\n  - simpl.\n    apply le_S.\n    apply IHle.\nQed.\n\n(*\n  Indication :\n  - utiliser compatibiliteAddition_le.\n *)\nProposition compatibiliteAddition_zeroMinDroite_le :\n  forall m1 m2 n, m1 <= m2 -> m1 <= (m2 + n).\nProof.\n  intros m1 m2 n H.\n  case n.\n  - rewrite <- neutraliteDroite_addition.\n    apply H.\n  - intros.\n  Admitted.\n\n\n(* Maximum et puissance *)\n\nFixpoint max(m n : nat) : nat.\n  exact (Nat.max m n). (* à modifier *)\nDefined.\n\n(*\n  Indication :\n  - procéder par induction sur m, avec une hypothèse de récurrence\n  quantifiée universellement sur n. \n *)\nProposition commutativite_max :\n  forall m n, max m n = max n m.\nProof.\n  intros m.\n  induction m.\n  - intros n.\n    case n.\n    + cbn.\n      reflexivity.\n    + cbn.\n      reflexivity.\n  - intros n.\n    Admitted.\n\nProposition idempotence_max :\n  forall n, n = max n n.\nProof.\n  intros n.\n  case n.\n  - simpl.\n    reflexivity.\n  - intro m.\n    cbn.\nAdmitted.\n\n(*\n  Indication :\n  - procéder par induction sur m, avec une hypothèse de récurrence\n  quantifiée universellement sur n. \n *)\nProposition majorantGauche_max :\n  forall m n, m <= max m n.\nProof.\n  intros m.\n  induction m.\n  - intro n.\n    simpl.\n    apply zeroMin_le.\n  - intro n.\nAdmitted.\n\n(*\n  Indication :\n  - utiliser la commutativité.\n *)\nProposition majorantDroite_max :\n  forall m n, n <= max m n.\nProof.\n  intros m n.\n  rewrite commutativite_max.\n  apply majorantGauche_max.\nQed.\n\nFixpoint puissance(m n : nat) : nat.\n  exact (Nat.pow m n). (* à modifier *)\nDefined.\n\n(*\n  Indication :\n  - procéder par induction sur la preuve de (n1 <= n2).\n *)\nProposition croissance_puissance :\n  forall (m n1 n2 : nat),\n    n1 <= n2 -> puissance (S m) n1 <= puissance (S m) n2.\nProof.\n  intros n1 n2 m H.\n  induction H.\n  - reflexivity.\n  - \n  Admitted.\n\n(** *Arbres binaires - Un encadrement de la taille    *)\n\n(* à compléter\n\n-------  [arbreVide]\nvide : Arbre T \n\nt: T, g : Arbre T, d: Arbre t\n-----------------------  [arbreCons]\ncons t g d : Arbre T\n*)\n \nInductive Arbre(T : Type) : Type :=\n  |arbreVide : Arbre T\n  |arbreCons : T -> (Arbre T) -> (Arbre T) -> (Arbre T)\n.\n\nProposition principeInductif_Arbre : \n  forall (T : Type) (P : Arbre T -> Prop),\n    (* à compléter *)\n    forall (a : Arbre T), P a.\nProof.\n  intros T P H.\nAdmitted.\n\n\nFixpoint hauteur{T : Type}(a : Arbre T) : nat.\n  exact 0. (* à modifier *)\nDefined.\n\nFixpoint taille{T : Type}(a : Arbre T) : nat.\n  exact 0. (* à modifier *)\nDefined.\n\nDefinition unArbre : Arbre nat.\nAdmitted.\n\n\nExample hauteurArbre : hauteur (unArbre) = 3.\nAdmitted.\n\nExample tailleArbre : taille (unArbre) = 5.\nAdmitted.\n\n(*\n  Indication :\n  - procéder par induction sur l'arbre,\n  - utiliser les propositions démontrées sur les entiers naturels.\n *)\nProposition majorationTaille_Arbre :\n  forall T : Type,\n  forall a : Arbre T,\n    S (taille a) <= (puissance 2 (hauteur a)). \nProof.\nAdmitted.\n\n(*\n  Indication :\n  - décomposer la preuve de (inhabited T) en hypothèse \n  pour obtenir un élément de T,            \n  - procéder par induction sur n,\n  - utiliser les propositions démontrées sur les entiers naturels,\n  - pour prouver une conjonction, utiliser \"split\".\n *)\nPrint inhabited.\nProposition majorationOptimaleTaille_Arbre :\n  forall T : Type,\n    inhabited T ->\n    forall n : nat,\n    exists a : Arbre T,\n      hauteur a = n\n      /\\\n      S (taille a) = (puissance 2 (hauteur a)). \nProof.\nAdmitted.\n", "meta": {"author": "Naedri", "repo": "Coq-lessons", "sha": "de4a20047a4255f43fcf6486ea2733dd6d6afabe", "save_path": "github-repos/coq/Naedri-Coq-lessons", "path": "github-repos/coq/Naedri-Coq-lessons/Coq-lessons-de4a20047a4255f43fcf6486ea2733dd6d6afabe/Exam/coq_logic_another_answer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.8354835452961425, "lm_q1q2_score": 0.7101369280627514}}
{"text": "(** 1 optional exercise attempted and 1 completed *)\n\n(** Exercise 1 (dist_not_exists) *)\nTheorem dist_not_exists : forall (X:Type) (P : X -> Prop),\n  (forall x, P x) -> ~ (exists x, ~ P x).\nProof.\n  intros. unfold not. intros. inversion H0.\n    apply H1. apply H.\nQed.\n\n\n(** Exercise 2 (dist_exists_or) *)\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. intros. inversion H. inversion H0.\n  Case \"L\".\n    left. exists witness. apply H1.\n    right. exists witness. apply H1.\n  Case \"R\".\n   intros. inversion H.\n     inversion H0. exists witness. left. apply H1.\n     inversion H0. exists witness. right. apply H1.\nQed.\n\n(** Exercise 3 (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  intros.\n  unfold override'.\n  destruct (eq_nat_dec k1 k2).\n    reflexivity.\n    reflexivity.\nQed.\n\n(** Exercise 4 (all_forallb) *)\nInductive all {X : Type} (P : X -> Prop) : list X -> Prop :=\n  | a_nil : all P []\n  | a_cons h t : P h -> all P t -> all P (h :: t).\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  \nTheorem forallb_spec :\n  forall X (test : X -> bool) (l : list X),\n    forallb test l = true <-> all (fun x => test x = true) l.\nProof.\n  intros. split. intros. induction l as [|h t].\n    Case \"1\".\n      apply a_nil.\n    Case \"2\".\n      apply a_cons.\n      simpl in H.\n      destruct (test h). reflexivity. apply H.\n      apply IHt. simpl in H.\n      destruct (test h). apply H. inversion H.\n   Case \"3\".\n    intros.\n    induction H.\n      reflexivity.\n      simpl. rewrite H. simpl. apply IHall.\nQed.\n\n\n(** Exercise 5 (nostutter) *)\nInductive nostutter:  list nat -> Prop :=\n  ns_nil : nostutter []\n| ns_one : forall x, nostutter [x]\n| ns_two : forall x y l, x <> y -> nostutter (y :: l) -> nostutter (x :: (y :: l)).\nExample test_nostutter_1:      nostutter [3;1;4;1;5;6].\n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n\n\nExample test_nostutter_2:  nostutter [].\n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n\n\nExample test_nostutter_3:  nostutter [5]. \n  Proof. repeat constructor; apply beq_nat_false; auto. Qed.\n\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 H1; auto. Qed.\n  \n\n(Exercise 6 (optional (not_exists_dist) )*)\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  unfold excluded_middle. intros HEM X P. unfold not. intros HNE x.\n  assert (P x \\/ ~ P x). apply HEM.\n  inversion H.\n    apply H0.\n    apply ex_falso_quodlibet. apply HNE. unfold not in H0. exists x. apply H0.\nQed.\n\n", "meta": {"author": "surenz20", "repo": "CS6463", "sha": "2325abfb1d5c18104c05d4d29bf9fe1bd7de0558", "save_path": "github-repos/coq/surenz20-CS6463", "path": "github-repos/coq/surenz20-CS6463/CS6463-2325abfb1d5c18104c05d4d29bf9fe1bd7de0558/MoreLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7101369182306304}}
{"text": "Require Import List Logic Nat Arith Bool Omega Classical.\nRequire Import Compare_dec EqNat Decidable ListDec FinFun. \nRequire Fin. \nImport ListNotations.\nFrom Block   \nRequire Import lib definitions.\n\nDefinition Ramsey_of {X : Type} (r s : nat) (H_r : r > 0) (H_s : s > 0) (rk : nat) (d : X) :=\n  forall l : list X, length l = rk ->\n                forall f : X -> X -> bool,\n                (exists bl : list X, length bl = r /\\ subseq bl l /\\\n                               forall i j : nat, i < j < r ->\n                                          f (nth i bl d) (nth j bl d) = true)\n                \\/ (exists bl : list X, length bl = s /\\ subseq bl l /\\ \n                                  forall i j : nat, i < j < s ->\n                                             f (nth i bl d) (nth j bl d) = false). \n\nDefinition Ramsey_of_prop {X : Type} (r s : nat) (H_r : r > 0) (H_s : s > 0) (rk : nat) (d : X) :=\n  forall l : list X, length l = rk ->\n                forall P : X -> X -> Prop,\n                (exists bl : list X, length bl = r /\\ subseq bl l /\\\n                               forall i j : nat, i < j < r ->\n                                          P (nth i bl d) (nth j bl d))\n                \\/ (exists bl : list X, length bl = s /\\ subseq bl l /\\ \n                                  forall i j : nat, i < j < s ->\n                                             ~ P (nth i bl d) (nth j bl d)). \n\nLemma one : 1 > 0. Proof. omega. Qed. \n\nTheorem Ramsey_of_one {X : Type} :\n  forall (k : nat) (H_k : k > 0) (d : X),\n    Ramsey_of 1 k one H_k 1 d /\\\n    Ramsey_of k 1 H_k one 1 d.\nProof.\n  intros k H_k d; split; red; repeat split; try omega; intros l H_l f. \n  - left. exists l. split. assumption.\n    split. apply subseq_refl. intros. omega. \n  - right. exists l. split. assumption.\n    split. apply subseq_refl. intros. omega.\nQed.\n\nTheorem Ramsey_of_one_prop {X : Type} :\n  forall (k : nat) (H_k : k > 0) (d : X),\n    Ramsey_of_prop 1 k one H_k 1 d /\\\n    Ramsey_of_prop k 1 H_k one 1 d.\nProof.\n  intros k H_k d; split; red; repeat split; try omega; intros l H_l f. \n  - left. exists l. split. assumption.\n    split. apply subseq_refl. intros. omega. \n  - right. exists l. split. assumption.\n    split. apply subseq_refl. intros. omega.\nQed.\n\nTheorem Ramsey_inductive_step {X : Type} :\n  forall (r s : nat) (H_r : r > 0) (H_s : s > 0) (d : X),\n  exists rk : nat,\n    Ramsey_of r s H_r H_s rk d.\nProof.\n  intros r s.\n  remember (r + s) as k.\n  revert r s Heqk. \n  induction k as [|k IHk] using strong_induction; intros.\n  - symmetry in Heqk; apply plus_is_O in Heqk.\n    destruct Heqk; subst. inversion H_r.\n  - destruct r as [|r]. inversion H_r.\n    destruct s as [|s]. inversion H_s.\n    destruct r as [|r].\n    (* Pseudo base case, when r = 1 *) \n    exists 1. \n    apply (Ramsey_of_one (S s) H_s d).\n    (* Pseudo base case, when s = 1 *)\n    destruct s as [|s].\n    exists 1. \n    apply (Ramsey_of_one (S (S r)) H_r d).\n    (* Finally, everything is big enough *) \n    destruct k. omega. destruct k. omega. \n    (* Both (S r) and (S s) are greater than or equal to 1, \n       and therefore (S (S k)) is greater than or equal to two *)\n    (* Reminder : r = S r, s = S s, k = S (S k) *) \n    spec IHk (S k). \n    spec IHk. omega.\n    assert (IHk_copy := IHk).\n    spec IHk (S r) (S (S s)).\n    spec IHk_copy (S (S r)) (S s).\n    spec IHk. omega. spec IHk_copy. omega.\n    assert (H_pre1 : S r > 0) by omega.\n    spec IHk H_pre1 H_s.\n    spec IHk_copy H_r.\n    assert (H_pre2 : S s > 0) by omega.\n    spec IHk_copy H_pre2.\n    spec IHk d. spec IHk_copy d.\n    destruct IHk as [rk1 IHk1].\n    destruct IHk_copy as [rk2 IHk2].\n    exists (rk1 + rk2); red; intros l H_l f. \n    red in IHk1, IHk2.\n    destruct l as [|v l_rest]. \n    (* Inversioning the base case list *)\n    + unfold length in H_l. symmetry in H_l.\n      apply plus_is_O in H_l. destruct H_l; subst.\n      spec IHk1 ([] : list X).\n      spec IHk1. reflexivity.\n      spec IHk1 f. destruct IHk1;\n      destruct H as [bl_absurd [absurd_length [absurd_subseq _]]];\n      assert (bl_absurd = []) by (apply (subseq_nil_nil); assumption);\n      subst; simpl in absurd_length; inversion absurd_length.\n    + (* Now we have a pivot vertex *)\n      remember (filter (fun n => f v n) l_rest) as M. \n      remember (filter (fun n => negb (f v n)) l_rest) as N.\n      assert (length M + length N = length l_rest).\n      { subst; apply filter_length. }\n      simpl in H_l.\n      assert (length M >= rk1 \\/ length N >= rk2) by omega. \n      destruct H0 as [red | blue]. \n      * (* In the case that M has a red K_(S s) *)\n        clear IHk2.\n        assert (H_get := get_subseq M rk1 red).\n        assert (H_trans : subseq M l_rest) by (subst M; apply (filter_subseq_correct')).\n        destruct H_get as [red_list [H_red_length H_red_subseq]].\n        spec IHk1 red_list H_red_length f. \n        destruct IHk1 as [left | right].\n        ** destruct left as [bl [bl_length [bl_subseq bl_color]]].\n           left. exists (v :: bl). repeat split.\n           simpl; omega. apply subseq_hm.\n           do 2 (eapply subseq_trans; eauto).\n           (* Boom! *) \n           intros.\n           destruct j. \n           omega. destruct i.\n           (* When we're looking at the head, i.e. v *) \n           { simpl. subst M.\n             assert (subseq bl (filter (fun n => f v n) l_rest)). \n             eapply subseq_trans; eauto.\n             apply subseq_incl in H1. spec H1 (nth j bl d).\n             spec H1. apply nth_In. omega.\n             apply filter_In in H1. destruct H1 as [_ goal].\n             exact goal. } \n           spec bl_color i j.\n           spec bl_color. omega.\n           simpl. assumption.\n        ** destruct right as [bl [bl_length [bl_subseq bl_color]]].\n           right. exists bl. repeat split.\n           assumption. apply subseq_hn.\n           do 2 (eapply subseq_trans; eauto).\n           assumption.\n      * (* In the case that N has a blue K_r *)\n        clear IHk1.\n        assert (H_get := get_subseq N rk2 blue).\n        assert (H_trans : subseq N l_rest) by (subst N; apply (filter_subseq_correct')).\n        destruct H_get as [blue_list [H_blue_length H_blue_subseq]].\n        spec IHk2 blue_list H_blue_length f.\n        destruct IHk2 as [left | right].\n        ** destruct left as [bl [bl_length [bl_subseq bl_color]]].\n           left. exists bl. repeat split.\n           assumption. apply subseq_hn.\n           do 2 (eapply subseq_trans; eauto).\n           assumption.\n        ** destruct right as [bl [bl_length [bl_subseq bl_color]]].\n           right. exists (v :: bl). repeat split.\n           simpl; omega. apply subseq_hm.\n           do 2 (eapply subseq_trans; eauto).\n           (* Boom! *) \n           intros.\n           destruct j. \n           omega. destruct i. simpl. subst M.\n           { simpl. subst N.\n             assert (subseq bl (filter (fun n => negb (f v n)) l_rest)). \n             eapply subseq_trans; eauto.\n             apply subseq_incl in H1. spec H1 (nth j bl d).\n             spec H1. apply nth_In. omega.\n             apply filter_In in H1. destruct H1 as [_ goal].\n             apply negb_true_iff in goal. exact goal. }\n           spec bl_color i j.\n           spec bl_color. omega.\n           simpl. assumption.\nQed.\n\nPrint Assumptions Ramsey_inductive_step. \n(* This requires no additional axioms *) \n\n(* Ramsey in Prop *) \nLemma filterprop_vanilla : forall X (P : X -> Prop) (L : list X),\n    exists L',\n      forall x, In x L' <-> (In x L /\\ P x).\nProof.\n  induction L. exists nil. split. inversion 1. intros [? _]. inversion H.\n  destruct IHL as [L' ?]. destruct (classic (P a)).\n  exists (a :: L'). split; intros. destruct H1. split. left. assumption. subst. assumption.\n  split. right. apply H in H1. destruct H1. assumption.\n  apply H in H1. destruct H1. assumption.\n  destruct H1. destruct H1. left. assumption.\n  right. apply H. split; assumption.\n  exists L'. split; intros.\n  apply H in H1. destruct H1. split. right. assumption. assumption.\n  apply H. destruct H1. destruct H1. subst. contradiction.\n  split; assumption.\nQed.\n\nLemma filterprop_armed : forall X (P : X -> Prop) (L : list X),\n    forall (Q : list X -> Prop)\n      (f : list X -> list X)\n      (H_correct : forall l : list X, Q (f l) /\\ (forall w, In w (f l) <-> In w l)), \n    exists L', Q L' /\\ \n          forall x, In x L' <-> (In x L /\\ P x). \nProof. \n  intros.\n  destruct (filterprop_vanilla X P L) as [L_vanilla about_L_vanilla].\n  exists (f L_vanilla).\n  spec H_correct L_vanilla. \n  destruct H_correct.\n  split. assumption.\n  intro; split; intro. apply about_L_vanilla.\n  apply H0. assumption. apply about_L_vanilla in H1.\n  spec H0 x. apply H0. assumption.\nQed.\n\nLemma filterprop_vanilla_dep : forall X (D : X -> Prop) (P : {x | D x} -> Prop) (L : list {x | D x}),\n    exists L', (* sublist L' L /\\ *)\n      forall x, In x L' <-> (In x L /\\ P x).\nProof.\n  induction L. exists nil. split. inversion 1. intros [? _]. inversion H.\n  destruct IHL as [L' ?]. destruct (classic (P a)).\n  exists (a :: L'). split; intros. destruct H1. split. left. assumption. subst. assumption.\n  split. right. apply H in H1. destruct H1. assumption.\n  apply H in H1. destruct H1. assumption.\n  destruct H1. destruct H1. left. assumption.\n  right. apply H. split; assumption.\n  exists L'. split; intros.\n  apply H in H1. destruct H1. split. right. assumption. assumption.\n  apply H. destruct H1. destruct H1. subst. contradiction.\n  split; assumption.\nQed.\n\n\nTheorem filterprop_subseq_both :\n   forall (X : Type) (P : X -> Prop) (L : list X),\n   exists L' L'': list X, length L' + length L'' = length L /\\\n                     subseq L' L /\\ subseq L'' L /\\\n                     (forall x : X, In x L' <-> In x L /\\ P x) /\\\n                     (forall x : X, In x L'' <-> In x L /\\ ~ P x). \nProof.\n  induction L as [|hd tl IHL].\n  + exists nil, nil. repeat split.\n    apply subseq_nil.\n    apply subseq_nil.\n    inversion H.\n    inversion H.\n    intros [absurd _]; inversion absurd.\n    inversion H.\n    inversion H.\n    intros [absurd _]; inversion absurd.\n  + destruct IHL as [L' [L'' [H_length [H_subseq' [H_subseq'' [H_in1 H_in2]]]]]].\n    destruct (classic (P hd)).\n    * exists (hd :: L'), L''. repeat split.\n      simpl; omega.\n      now apply subseq_hm.\n      now apply subseq_hn.\n      destruct H0 as [H_eq | H_tl]. \n      subst. apply in_eq.\n      apply H_in1 in H_tl. destruct H_tl as [goal _].\n      right; assumption.\n      destruct H0 as [H_eq | H_tl].\n      subst; assumption.\n      apply H_in1 in H_tl. destruct H_tl as [_ goal]; assumption.\n      intro. destruct H0 as [[H_eq | H_tl] H_P].\n      subst. apply in_eq.\n      right. apply H_in1. split; assumption.\n      apply H_in2 in H0. destruct H0 as [goal _]; right; assumption.\n      apply H_in2 in H0; destruct H0 as [_ goal]; assumption.\n      intros [H_in H_notP]. apply H_in2.\n      destruct H_in as [H_eq | H_tl].\n      subst. contradiction.\n      split; assumption.\n    * exists L', (hd :: L''). repeat split.\n      simpl; omega.\n      now apply subseq_hn.\n      now apply subseq_hm.\n      apply H_in1 in H0.\n      destruct H0 as [goal _]; right; assumption.\n      apply H_in1 in H0. destruct H0 as [_ goal]; assumption.\n      intros [H_in H_P].\n      destruct H_in as [H_eq | H_tl]. \n      subst. contradiction.\n      apply H_in1. split; assumption.\n      destruct H0 as [H_eq | H_tl].\n      subst. apply in_eq. apply H_in2 in H_tl.\n      destruct H_tl as [goal _]; right; assumption.\n      destruct H0 as [H_eq | H_tl].\n      subst. assumption.\n      apply H_in2 in H_tl.\n      destruct H_tl as [_ goal]; assumption.\n      intros [H_in H_notP]. destruct H_in as [H_eq | H_tl].\n      subst. apply in_eq. right. apply H_in2.\n      tauto. \nQed.\n\nTheorem Ramsey_inductive_step_prop {X : Type} :\n  forall (r s : nat) (H_r : r > 0) (H_s : s > 0) (d : X),\n  exists rk : nat,\n    Ramsey_of_prop r s H_r H_s rk d.\nProof.\n  intros r s.\n  remember (r + s) as k.\n  revert r s Heqk. \n  induction k as [|k IHk] using strong_induction; intros.\n  - symmetry in Heqk; apply plus_is_O in Heqk.\n    destruct Heqk; subst. inversion H_r.\n  - destruct r as [|r]. inversion H_r.\n    destruct s as [|s]. inversion H_s.\n    destruct r as [|r].\n    (* Pseudo base case, when r = 1 *) \n    exists 1. \n    apply (Ramsey_of_one_prop (S s) H_s d).\n    (* Pseudo base case, when s = 1 *)\n    destruct s as [|s].\n    exists 1. \n    apply (Ramsey_of_one_prop (S (S r)) H_r d).\n    (* Finally, everything is big enough *) \n    destruct k. omega. destruct k. omega. \n    (* Both (S r) and (S s) are greater than or equal to 1, \n       and therefore (S (S k)) is greater than or equal to two *)\n    (* Reminder : r = S r, s = S s, k = S (S k) *) \n    spec IHk (S k). \n    spec IHk. omega.\n    assert (IHk_copy := IHk).\n    spec IHk (S r) (S (S s)).\n    spec IHk_copy (S (S r)) (S s).\n    spec IHk. omega. spec IHk_copy. omega.\n    assert (H_pre1 : S r > 0) by omega.\n    spec IHk H_pre1 H_s.\n    spec IHk_copy H_r.\n    assert (H_pre2 : S s > 0) by omega.\n    spec IHk_copy H_pre2.\n    spec IHk d. spec IHk_copy d.\n    destruct IHk as [rk1 IHk1].\n    destruct IHk_copy as [rk2 IHk2].\n    exists (rk1 + rk2); red; intros l H_l f. \n    red in IHk1, IHk2.\n    destruct l as [|v l_rest]. \n    (* Inversioning the base case list *)\n    + unfold length in H_l. symmetry in H_l.\n      apply plus_is_O in H_l. destruct H_l; subst.\n      spec IHk1 ([] : list X).\n      spec IHk1. reflexivity.\n      spec IHk1 f. destruct IHk1;\n      destruct H as [bl_absurd [absurd_length [absurd_subseq _]]];\n      assert (bl_absurd = []) by (apply (subseq_nil_nil); assumption);\n      subst; simpl in absurd_length; inversion absurd_length.\n    + (* Now we have a pivot vertex *)\n      assert (H_list := filterprop_subseq_both _ (f v) l_rest).\n      destruct H_list as [M [N [MN_length [M_subseq [N_subseq [H_trans H_trans']]]]]]. \n      simpl in H_l.  \n      assert (length M >= rk1 \\/ length N >= rk2) by omega. \n      destruct H as [red | blue]. \n      * (* In the case that M has a red K_(S s) *)\n        clear IHk2.\n        assert (H_get := get_subseq M rk1 red).\n        destruct H_get as [red_list [H_red_length H_red_subseq]].\n        spec IHk1 red_list H_red_length f. \n        destruct IHk1 as [left | right].\n        ** destruct left as [bl [bl_length [bl_subseq bl_color]]].\n           left. exists (v :: bl). repeat split.\n           simpl; omega. apply subseq_hm.\n           do 2 (eapply subseq_trans; eauto).\n           (* Boom! *) \n           intros.\n           destruct j. \n           omega. destruct i. \n           (* When we're looking at the head, i.e. v *) \n           { simpl. apply H_trans. \n             apply subseq_incl in H_red_subseq.\n             spec H_red_subseq (nth j bl d).\n             apply H_red_subseq.\n             apply subseq_incl in bl_subseq.\n             spec bl_subseq (nth j bl d).\n             apply bl_subseq. apply nth_In. omega. }\n           spec bl_color i j.\n           spec bl_color. omega.\n           simpl. assumption.\n        ** destruct right as [bl [bl_length [bl_subseq bl_color]]].\n           right. exists bl. repeat split.\n           assumption. apply subseq_hn.\n           do 2 (eapply subseq_trans; eauto).\n           assumption.\n      * (* In the case that N has a blue K_r *)\n        clear IHk1.\n        assert (H_get := get_subseq N rk2 blue).\n        destruct H_get as [blue_list [H_blue_length H_blue_subseq]].\n        spec IHk2 blue_list H_blue_length f.\n        destruct IHk2 as [left | right].\n        ** destruct left as [bl [bl_length [bl_subseq bl_color]]].\n           left. exists bl. repeat split.\n           assumption. apply subseq_hn.\n           do 2 (eapply subseq_trans; eauto).\n           assumption.\n        ** destruct right as [bl [bl_length [bl_subseq bl_color]]].\n           right. exists (v :: bl). repeat split.\n           simpl; omega. apply subseq_hm.\n           do 2 (eapply subseq_trans; eauto).\n           (* Boom! *) \n           intros.\n           destruct j. \n           omega. destruct i. simpl. \n           { simpl. \n             apply H_trans'.\n             apply subseq_incl in H_blue_subseq.\n             spec H_blue_subseq (nth j bl d).\n             apply H_blue_subseq.\n             apply subseq_incl in bl_subseq.\n             spec bl_subseq (nth j bl d).\n             apply bl_subseq. apply nth_In. omega. }\n           spec bl_color i j.\n           spec bl_color. omega.\n           simpl. assumption.\nQed.\n\nTheorem Ramsey_single :\n  forall (k : nat),\n    k > 0 -> \n    exists rk : nat, rk >= k /\\ \n              forall l : list nat, length l = rk ->\n                            forall f : nat -> nat -> bool,\n                              (exists bl : list nat, length bl = k /\\ subseq bl l /\\\n                                              forall i j : nat, i < j < k ->\n                                                         f (nth i bl d) (nth j bl d) = true)\n                              \\/ (exists bl : list nat, length bl = k /\\ subseq bl l /\\ \n                                                forall i j : nat, i < j < k ->\n                                                           f (nth i bl d) (nth j bl d) = false). \nProof.\n  intros k H_gt_zero. \n  assert (H_one := @Ramsey_of_one nat).\n  assert (H_step := @Ramsey_inductive_step nat).\n  spec H_one k H_gt_zero d. \n  specialize (H_step k k H_gt_zero H_gt_zero d).\n  destruct k. inversion H_gt_zero.\n  destruct k.\n  destruct H_one as [rk H_one].\n  exists 1.\n  split. omega.\n  exact H_one. destruct H_step as [rk H_step].\n  assert (rk >= S (S k) \\/ rk < S (S k)) by omega. \n  destruct H as [yes | no].\n  exists rk. split.\n  assumption. assumption.\n  exists rk. clear H_one.\n  red in H_step.\n  spec H_step (iota 0 rk). spec H_step.\n  apply length_iota. spec H_step (fun i j : nat => true).\n  destruct H_step. destruct H.\n  destruct H. destruct H0.\n  apply short_subseq_inversion in H0. inversion H0.\n  rewrite H. rewrite length_iota. assumption.\n  destruct H. destruct H.\n  destruct H0. apply short_subseq_inversion in H0.\n  inversion H0. rewrite H. rewrite length_iota; assumption.\nQed.\n\nTheorem Ramsey_single_prop :\n  forall (k : nat),\n    k > 0 -> \n    exists rk : nat, rk >= k /\\ \n              forall l : list nat, length l = rk ->\n                            forall f : nat -> nat -> Prop,\n                              (exists bl : list nat, length bl = k /\\ subseq bl l /\\\n                                              forall i j : nat, i < j < k ->\n                                                         f (nth i bl d) (nth j bl d))\n                              \\/ (exists bl : list nat, length bl = k /\\ subseq bl l /\\ \n                                                forall i j : nat, i < j < k ->\n                                                           ~ f (nth i bl d) (nth j bl d)). \nProof.\n  intros k H_gt_zero. \n  assert (H_one := @Ramsey_of_one_prop nat).\n  assert (H_step := @Ramsey_inductive_step_prop nat).\n  spec H_one k H_gt_zero d.\n  specialize (H_step k k H_gt_zero H_gt_zero d).\n  destruct k. inversion H_gt_zero.\n  destruct k. exists 1. \n  split. omega.\n  destruct H_one. assumption. \n  destruct H_step as [rk H_step].\n  assert (rk >= S (S k) \\/ rk < S (S k)) by omega.\n  destruct H as [yes | no].\n  exists rk. split.\n  assumption. assumption.\n  exists rk. clear H_one.\n  red in H_step.\n  spec H_step (iota 0 rk). spec H_step.\n  apply length_iota. spec H_step (fun i j : nat => True).\n  destruct H_step. destruct H.\n  destruct H. destruct H0.\n  apply short_subseq_inversion in H0. inversion H0.\n  rewrite H. rewrite length_iota. assumption.\n  destruct H. destruct H.\n  destruct H0. apply short_subseq_inversion in H0.\n  inversion H0. rewrite H. rewrite length_iota; assumption.\nQed.   \n\nTheorem Theorem_of_Ramsey_duo :\n  forall (k : block_pumping_constant),\n    exists rk : block_pumping_constant, rk >= k /\\ \n      forall w : word,\n      forall bps : breakpoint_set rk w,\n      forall (P : nat -> nat -> Prop)\n        (f : nat -> nat -> bool)\n        (H : forall i j, (f i j = true <-> P i j) /\\\n                    (f i j = false <-> ~ P i j)),\n        exists bps' : breakpoint_set k w,\n          sublist bps' bps /\\\n          ((forall bp1 bp2 : breakpoint bps',\n              bp1 < bp2 -> (P bp1 bp2))\n          \\/  (forall bp1 bp2 : breakpoint bps',\n                 bp1 < bp2 -> ~ (P bp1 bp2))).\nProof.\n  intro k. \n  assert (H_ramsey := Ramsey_single k).\n  destruct k as [k about_k]; unfold p_predicate in about_k. \n  spec H_ramsey. simpl; omega.\n  destruct H_ramsey as [rk [rk_fact H_ramsey]].\n  simpl in rk_fact. \n  assert (about_rk : rk >= 2). omega. \n  exists (exist p_predicate rk about_rk).\n  split. simpl. assumption.\n  intros w bps P f f_correct.\n  destruct bps as [bps [bps_length [bps_incr bps_last]]].\n  simpl in *. \n  spec H_ramsey bps bps_length f.\n  destruct H_ramsey as [yes | no]. \n  - destruct yes as [bps_yes [bps_yes_length [bps_yes_subseq yes]]]. \n    assert (breakpoint_set_predicate bps_yes w (exist _ k about_k)).\n    { repeat split. simpl. assumption.\n      now apply (subseq_incr bps).\n      assert (H_trans := about_subseq_last bps_yes bps d).\n      spec H_trans. rewrite bps_yes_length; omega.\n      spec H_trans. rewrite bps_length; omega.\n      spec H_trans. assumption.\n      spec H_trans. exact bps_yes_subseq.\n      now apply (le_trans (last bps_yes d) (last bps d) (length w)). }\n      exists (exist _ bps_yes H); simpl in *.\n      split.\n      apply subseq_incl in bps_yes_subseq. \n      assumption.\n      left. intros.\n      destruct bp1 as [bp1 about_bp1]; \n        destruct bp2 as [bp2 about_bp2]; \n        unfold breakpoint_predicate in *. \n      simpl in *. \n      apply (In_nth _ _ d) in about_bp1.\n      apply (In_nth _ _ d) in about_bp2.\n      destruct about_bp1 as [i [i_pos i_eq]].\n      destruct about_bp2 as [j [j_pos j_eq]].\n      spec yes i j. spec yes.\n      rewrite bps_yes_length in i_pos, j_pos.\n      split.\n     eapply increasing_nth_lt.\n     destruct H as [_ [bps_yes_incr bps_yes_last]].\n     exact bps_yes_incr. rewrite bps_yes_length; assumption.\n     rewrite bps_yes_length; assumption.\n     rewrite i_eq, j_eq.  assumption. assumption.\n     spec f_correct (nth i bps_yes d) (nth j bps_yes d).\n     rewrite <- i_eq. rewrite <- j_eq.\n    destruct f_correct as [f_correct _].\n    apply f_correct. assumption.\n  - destruct no as [bps_no [bps_no_length [bps_no_subseq no]]]. \n    assert (breakpoint_set_predicate bps_no w (exist _ k about_k)).\n    { repeat split. simpl. assumption.\n      now apply (subseq_incr bps).\n      assert (H_trans := about_subseq_last bps_no bps d).\n      spec H_trans. rewrite bps_no_length; omega.\n      spec H_trans. rewrite bps_length; omega.\n      spec H_trans. assumption.\n      spec H_trans. exact bps_no_subseq.\n      now apply (le_trans (last bps_no d) (last bps d) (length w)). }\n    exists (exist _ bps_no H); simpl in *.\n    split.\n    apply subseq_incl in bps_no_subseq. \n    assumption.\n    right. intros.\n    destruct bp1 as [bp1 about_bp1]; \n      destruct bp2 as [bp2 about_bp2]; \n      unfold breakpoint_predicate in *. \n    simpl in *. \n    apply (In_nth _ _ d) in about_bp1.\n    apply (In_nth _ _ d) in about_bp2.\n    destruct about_bp1 as [i [i_pos i_eq]].\n    destruct about_bp2 as [j [j_pos j_eq]].\n    spec no i j. spec no.\n    rewrite bps_no_length in i_pos, j_pos.\n    split.\n    eapply increasing_nth_lt.\n    destruct H as [_ [bps_no_incr bps_no_last]].\n    exact bps_no_incr. rewrite bps_no_length; assumption.\n    rewrite bps_no_length; assumption.\n    rewrite i_eq, j_eq.  assumption. assumption.\n    spec f_correct (nth i bps_no d) (nth j bps_no d).\n    rewrite <- i_eq. rewrite <- j_eq.\n    destruct f_correct as [_ f_correct].\n    apply f_correct. assumption.\nQed. \n\n\nTheorem Theorem_of_Ramsey_duo_prop :\n  forall (k : block_pumping_constant),\n    exists rk : block_pumping_constant, rk >= k /\\ \n      forall w : word,\n      forall bps : breakpoint_set rk w,\n      forall (P : nat -> nat -> Prop),\n        exists bps' : breakpoint_set k w,\n          sublist bps' bps /\\\n          ((forall bp1 bp2 : breakpoint bps',\n              bp1 < bp2 -> (P bp1 bp2))\n          \\/  (forall bp1 bp2 : breakpoint bps',\n                 bp1 < bp2 -> ~ (P bp1 bp2))).\nProof.\n  intro k. \n  assert (H_ramsey := Ramsey_single_prop k).\n  destruct k as [k about_k]; unfold p_predicate in about_k. \n  spec H_ramsey. simpl; omega.\n  destruct H_ramsey as [rk [rk_fact H_ramsey]].\n  simpl in rk_fact. \n  assert (about_rk : rk >= 2). omega. \n  exists (exist p_predicate rk about_rk).\n  split. simpl. assumption.\n  intros w bps P.\n  destruct bps as [bps [bps_length [bps_incr bps_last]]].\n  simpl in *. \n  spec H_ramsey bps bps_length P.\n  destruct H_ramsey as [yes | no]. \n  - destruct yes as [bps_yes [bps_yes_length [bps_yes_subseq yes]]]. \n    assert (breakpoint_set_predicate bps_yes w (exist _ k about_k)).\n    { repeat split. simpl. assumption.\n      now apply (subseq_incr bps).\n      assert (H_trans := about_subseq_last bps_yes bps d).\n      spec H_trans. rewrite bps_yes_length; omega.\n      spec H_trans. rewrite bps_length; omega.\n      spec H_trans. assumption.\n      spec H_trans. exact bps_yes_subseq.\n      now apply (le_trans (last bps_yes d) (last bps d) (length w)). }\n      exists (exist _ bps_yes H); simpl in *.\n      split.\n      apply subseq_incl in bps_yes_subseq. \n      assumption.\n      left. intros.\n      destruct bp1 as [bp1 about_bp1]; \n        destruct bp2 as [bp2 about_bp2]; \n        unfold breakpoint_predicate in *. \n      simpl in *. \n      apply (In_nth _ _ d) in about_bp1.\n      apply (In_nth _ _ d) in about_bp2.\n      destruct about_bp1 as [i [i_pos i_eq]].\n      destruct about_bp2 as [j [j_pos j_eq]].\n      spec yes i j. spec yes.\n      rewrite bps_yes_length in i_pos, j_pos.\n      split.\n     eapply increasing_nth_lt.\n     destruct H as [_ [bps_yes_incr bps_yes_last]].\n     exact bps_yes_incr. rewrite bps_yes_length; assumption.\n     rewrite bps_yes_length; assumption.\n     rewrite i_eq, j_eq.  assumption. assumption.\n     rewrite <- i_eq. rewrite <- j_eq.\n     apply yes. \n  - destruct no as [bps_no [bps_no_length [bps_no_subseq no]]]. \n    assert (breakpoint_set_predicate bps_no w (exist _ k about_k)).\n    { repeat split. simpl. assumption.\n      now apply (subseq_incr bps).\n      assert (H_trans := about_subseq_last bps_no bps d).\n      spec H_trans. rewrite bps_no_length; omega.\n      spec H_trans. rewrite bps_length; omega.\n      spec H_trans. assumption.\n      spec H_trans. exact bps_no_subseq.\n      now apply (le_trans (last bps_no d) (last bps d) (length w)). }\n    exists (exist _ bps_no H); simpl in *.\n    split.\n    apply subseq_incl in bps_no_subseq. \n    assumption.\n    right. intros.\n    destruct bp1 as [bp1 about_bp1]; \n      destruct bp2 as [bp2 about_bp2]; \n      unfold breakpoint_predicate in *. \n    simpl in *. \n    apply (In_nth _ _ d) in about_bp1.\n    apply (In_nth _ _ d) in about_bp2.\n    destruct about_bp1 as [i [i_pos i_eq]].\n    destruct about_bp2 as [j [j_pos j_eq]].\n    spec no i j. spec no.\n    rewrite bps_no_length in i_pos, j_pos.\n    split.\n    eapply increasing_nth_lt.\n    destruct H as [_ [bps_no_incr bps_no_last]].\n    exact bps_no_incr. rewrite bps_no_length; assumption.\n    rewrite bps_no_length; assumption.\n    rewrite i_eq, j_eq.  assumption. assumption.\n    rewrite <- i_eq. rewrite <- j_eq.\n    apply no.\nQed. \n\n", "meta": {"author": "atufchoice", "repo": "blockpump", "sha": "678917d1177dd7cac9fc715d89ef28102a076654", "save_path": "github-repos/coq/atufchoice-blockpump", "path": "github-repos/coq/atufchoice-blockpump/blockpump-678917d1177dd7cac9fc715d89ef28102a076654/ramsey.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7101192310015667}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2020 - Pset 2 *)\n\n(*\nAuthor: Samuel Gruetter <gruetter@mit.edu>\n\nThis PSet will introduce you to one of the major applications of formal reasoning\nabout programs: proving that an optimized program behaves the same as a simple program.\n\nImagine you're writing a program which needs a some function F. You know how to implement\nF naively, but as you run your program, you notice that it spends a lot of time in\nthe function F. You find a library which claims to provide a very efficient implementation\nof F, but looking at its source code, you don't really understand why this code should\ncalculate F, and you've seen some bug reports against previous versions of the library,\nso you can't really know whether this library implements F correctly.\nSince you care a lot about writing a correct program, you finally decide to keep using\nyour naive slow implementation.\nFormal reasoning about programs to the rescue! If the authors of the library want to\nincrease the user's trust in their library, they can include the naive but simple-to-\nunderstand version of F in their library as well, and write a proof that for all possible\ninputs, the optimized version of F returns the same value as the simple version of F.\nIf that proof is in a machine-checkable format (e.g. in a Coq file), the library users do\nnot need to understand the implementation of the optimized F, nor the body of the proof,\nbut can still use the optimized F and be sure that it does the same as the simple\nimplementation, as long as they trust the proof checker.\n\nIn this PSet, we will put you in the role of the library author who writes a naive\nversion of F, an optimized implementation of F, and a proof that the two of them behave\nthe same.\n*)\n\n\nRequire Import Coq.NArith.NArith. Open Scope N_scope.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.micromega.Lia.\nRequire Import Frap.Frap.\nRequire Import Pset2Sig.\n(* Set Default Goal Selector \"!\". *)\n\n(* Each of the exercises below is worth some number of points.\n   If you just want to enjoy the proof hacking without getting distracted by points,\n   feel free to ignore these points. On the other hand, if you want to know how\n   many points each exercise earns you, you can find the points in Pset2Sig.v. *)\n\n\n(* Recursive functions *)\n(* ******************* *)\n\n(* We will need some recursive functions in this PSet. Defining recursive functions in Coq can be\n   a bit tricky, because Coq only accepts recursive functions for which it believes that they always\n   terminate.\n   For natural numbers represented as \"nat\", and for data structures like the abstract syntax trees\n   we saw in class, recursive functions can usually be defined using \"Fixpoint\", because each\n   recursive call is with an argument which is a subterm of the original argument, which is required\n   for Coq to be convinced that the recursive function terminates.\n   In this pset, however, we will use the binary representation of natural numbers, which is\n   called \"N\" in Coq. If we wanted to use a Fixpoint and call it with, e.g. the binary number\n   11001101, we could only make recursive calls with 1001101.\n   What we want in this Pset, however, is to make recursive calls with the one less than the argument,\n   i.e. with 11001100 in this example.\n   For this kind of recursion, which does not follow the structure of the data, we use the\n   following pattern: *)\n\nDefinition fact: N -> N :=\n  recurse by cases\n  | 0 => 1\n  | n + 1 => (n + 1) * recurse\n  end.\n\n(* This pattern can only define functions recursing over a natural number with base case 0, and\n   one recursive case where the recursive call is for one less than the argument.\n   The above function implements factorial, i.e. \"fact n = 1 * 2 * ... * n\".\n   In the recursive case, you can use the word \"recurse\" to refer to the result of the recursive\n   call. *)\n\n(* Let's compute the first few values of fact: *)\nCompute fact 0.\nCompute fact 1.\nCompute fact 2.\nCompute fact 3.\nCompute fact 4.\n\n(* Aside: If you don't like the above Notation and want to see the real definition, you can do this:\nClose Scope N_recursion_scope.\nPrint fact.\n*)\n\n(* Instead of writing \"(fact x)\" all the time, it's more convenient to just write \"x!\",\n   so we make a Notation for this: *)\nLocal Notation \"x !\" := (fact x) (at level 12, format \"x !\").\n(* Exercise: Define a simple exponentiation function in the same style,\n   so that \"exp base n\" equals \"base^n\". *)\n\n(*\nDefinition flip {A B C} (f : A -> B -> C) x y := f y x.\nDefinition exp: N -> N -> N :=\n    flip (recurse by cases\n    | 0 => (fun x => 1)\n    | cheese + 1 => fun x => x * recurse x \n    end).\n*)\nDefinition exp: N -> N -> N :=\n  fun x =>\n    recurse by cases\n    | 0 => 1\n    | _ + 1 => x * recurse\n    end.\n\n\n\n(* Once you define \"exp\", you can replace \"Admitted.\" below by \"Proof. equality. Qed.\" *)\nLemma test_exp_2_3: exp 2 3 = 8. Proof. equality. Qed. \nLemma test_exp_3_2: exp 3 2 = 9. Proof. equality. Qed. \nLemma test_exp_4_1: exp 4 1 = 4. Proof. equality. Qed. \nLemma test_exp_5_0: exp 5 0 = 1. Proof. equality. Qed. \nLemma test_exp_1_3: exp 1 3 = 1. Proof. equality. Qed. \n\n(* Here's another recursive function defined in the same style to apply a function f to\n   a range of values:\n   \"seq f len start\" computes the list [f start; f (start+1); ... f (start+len-1)] *)\nDefinition seq(f: N -> N): N -> N -> list N :=\n  recurse by cases\n  | 0 => fun start => []\n  | n + 1 => fun start => f start :: recurse (start + 1)\n  end.\n\nCompute (seq (fun x => x * x) 4 0).\n\n(* \"ith i l\" returns the i-th element of the list l.\n   To understand the recursion, note that \"ith i\" returns a function which takes a list and,\n   depending on whether i was 0 or not, returns the head of the list or the (i-1)-th element\n   of the tail.\n   If the index is out of bounds, it returns the default value 0. *)\nDefinition ith: N -> list N -> N :=\n  recurse by cases\n  | 0 => fun (l: list N) => match l with\n                            | h :: t => h\n                            | nil => 0\n                            end\n  | i + 1 => fun (l: list N) => match l with\n                                | h :: t => recurse t \n                                | nil => 0\n                                end\n  end.\n\n(* The standard library already contains a function called \"length\": *)\nCheck length.\n(* However, it returns a \"nat\", i.e., the representation of natural numbers using O and S,\n   which is very inefficient: To represent the number n, it needs roughly c*n bytes of RAM,\n   where c is some constant, whereas \"N\", the binary representation of natural numbers,\n   only used c*log(n) bytes of RAM.\n   Therefore, we redefine our own length function which returns an N: *)\nFixpoint len(l: list N): N :=\n  match l with\n  | [] => 0\n  | h :: t => 1 + len t\n  end.\n(* Note that since the recursion follows the structure of the data (the list) here,\n   we use Fixpoint instead of \"recurse by cases\". *)\n\n(* Here's a simple lemma: If we tell \"seq\" to return a list of length \"count\", it indeed does: *)\nLemma seq_len: forall f count start, len (seq f count start) = count.\nProof.\n  induct count; simplify.\n  - (* base case: count = 0 *)\n    equality.\n  - (* recursive case: assuming the statement holds for some \"count\", show that it\n       also holds for \"count + 1\".\n       This goal contains \"seq f (count + 1) start\", so we know that we're in the\n       recursive case of \"seq\", so we'd like to replace \"seq f (count + 1) start\"\n       by the recursive case we wrote in its definition.\n       Unfortunately, neither \"unfold seq\" nor \"simplify\" can do this, but the\n       tactic \"unfold_recurse F k\", where F is the function in question, and k\n       its argument, does the job: *)\n    unfold_recurse (seq f) count.\n    (* And here's a hint you'll need later: Sometimes, your goal won't exactly contain\n       (seq f (count + 1) start), but maybe (seq f someOtherExpression start), but you\n       still know that someOtherExpression is strictly greater than 0.\n       In such cases, if you want to use \"unfold_recurse\", you first have to run\n\n       replace someOtherExpression with (someOtherExpression - 1 + 1) by linear_arithmetic.\n\n       Note that if someOtherExpression could be 0, this won't work, because subtraction\n       on natural numbers in Coq returns 0 if the result is negative, so \"0 - 1 + 1\"\n       equals 1 in Coq's natural numbers, and linear_arithmetic can't prove \"0 = 1\"\n       for you! *)\n\n    simplify. rewrite IHcount. linear_arithmetic.\nQed.\n\n(* An here's another general hint: You don't always need induction.\n   Some lemmas in this pset can be solved using induction, but don't actually require it,\n   and are simpler to solve if you don't use induction, so before doing induction,\n   try to think where/if you would need an inductive hypothesis. *)\n\nCompute ith 2 (seq (fun x => x * x) 4 0).\nCompute (fun x => x * x)(0 + 2).\nCompute (fun x => x *x)(1) :: seq (fun x => x*x) 3 (1+1).\nCompute seq (fun x => x *x) 3 1.\n(* (i=1, count =2, start 2).*)\n\nCompute ith (1 + 1) (seq (fun x => x *x) (2 + 1) 2) = (fun x => x *x) (2 + (1 + 1)).\nCompute ith (1 + 1) ((fun x => x *x) 2 :: seq (fun x => x *x) 2 (2 + 1)) = ith 1 (seq (fun x => x *x) 2 (2 + 1)).\n(* Exercise: Prove that the i-th element of seq has the value we'd expect. *)\n\nLemma first_element: forall l a, ith 0 (a::l) = a.\nProof.\n  simplify.\n  equality.\nQed.\n\nLemma j: forall  i a l, i < len l -> ith (i + 1) (a :: l) = ith i (l).\ninduct i.\nsimplify.\nequality.\nsimplify.\nunfold_recurse (ith) (i+1).\nequality.\nQed.\n\nLemma a: forall f count i start, i < count -> ith (i + 1) (f start :: seq f count (start + 1)) = ith i (seq f count (start + 1)).\nProof.\n induct i.\n  simplify.\n  equality.\n  simplify.\n  apply j.\n  rewrite  seq_len.\n  assumption.\nQed.\nLemma seq_spec: forall f count i start, i < count -> ith i (seq f count start) = f (start + i).\nProof.\n  induct count; simplify. \n  apply N.nlt_0_r in H.\n  equality.\n  induct i.\n  unfold_recurse (seq f) (count).\n  simplify.\n   f_equal. linear_arithmetic.\n\n\n   assert(H2: (i + 1 < count + 1) <-> i < count).\n   linear_arithmetic.\n   apply H2 in H. \n   unfold_recurse (seq f) (count).\n   rewrite a.\n\n\n   rewrite   IHcount.\n   f_equal.\n   linear_arithmetic.\n   assumption.\n   assumption.\nQed.\n\n\n\nLemma concat: forall a l, len(a :: l) = 1 + len(l).\nProof.\n  induct l; simplify; equality.\nQed.\n\nLemma empty: forall l, len l <= 0 -> l = [].\nProof.\n  induct l.\n  simplify.\n  equality.\n  rewrite concat.\n  intros.\n  cases l.\n  simplify.\n  linear_arithmetic.\n  linear_arithmetic.\nQed.\n(* Exercise: Prove that if the index is out of bounds, \"ith\" returns 0. *)\nLemma ith_out_of_bounds_0: forall i l, len l <= i -> ith i l = 0.\nProof.\ninduct i.\nintros.\napply empty in H.\nsimplify.\nrewrite H.\nequality.\nsimplify.\ninduct l.\nsimplify.\nunfold_recurse (ith) (i).\nequality.\nrewrite concat in H.\n\nassert(H2: (1 + len l <= i + 1) -> len l <= i). \nsimplify.\nlinear_arithmetic.\napply H2 in H.\n\napply IHi in H.\nunfold_recurse (ith) (i).\nassumption.\nQed.\n(* Binomial coefficients *)\n(* ********************* *)\n\n(* You might remember binomial coefficients from you math classes, which appear in many combinatorics\n   problems, and form the coefficients of the expansion of the polynomial (x + y)^n.\n   In math notation, they are defined as follows:\n\n      / n \\        n!\n      |   |  = ---------\n      \\ k /    (n-k)! k!\n\n   We can transcribe this to Coq as follows: *)\n\nDefinition C(n k: N): N := n! / ((n - k)! * k!).\n\n(* If we want to know how many ways there are to pick 2 items out of 4 items, we can compute this in Coq: *)\nCompute C 4 2.\n\n(* And here are the coefficients of the expansion of (x + y)^3: *)\nCompute [C 3 0; C 3 1; C 3 2; C 3 3].\n\n(* For larger numbers, however, this way of computing C becomes quite slow: If I do\n\nCompute C 1000 100.\n\n   it takes about 2 seconds on my computer. You can measure the time by putting \"Time\" in front of any command:\n\nTime Compute C 1000 100.\n\n   In the fraction defining C, there are many factors which appear both in the numerator and in the\n   denominator, so it seems that we should be able to cancel these out and write a more efficient\n   implementation of C. Here is one candidate: *)\n\nDefinition bcoeff(n: N): N -> N :=\n  recurse by cases\n  | 0 => 1\n  | k + 1 => recurse * (n - k) / (k + 1)\n  end.\n\n(* Now if we do\n\nTime Compute bcoeff 1000 100.\n\n   it only takes about 0.02 seconds on my computer, so we got a 100x speed improvement, yay!\n   But how do we know whether it's correct?\n   We could do some quick tests: *)\n\nCompute [bcoeff 3 0; bcoeff 3 1; bcoeff 3 2; bcoeff 3 3].\n\n(* This test produces the same values as for C, but we want to be sure that bcoeff will *always* produce\n   the same values as C, so let's prove it, i.e. let's show that\n\n   forall n k, k <= n -> bcoeff n k = C n k\n\n   We will do so further below, but we first need a few helper lemmas and techniques:\n\n   Many arithmetic goals in this Pset are linear, i.e. we there are only multiplications by\n   constants, but no multiplications of two variables.\n   For these linear arithmetic goals, the linear_arithmetic tactic works just fine, but for\n   some non-linear goals which will appear in this Pset, you can try the tactic \"nia\"\n   (which stands for \"non-linear integer arithmetic\"), but it does not always work, so\n   sometimes you will have to search for appropriate lemmas to apply manually.\n   For instance, to prove the following: *)\nGoal forall n m, n <> 0 -> m <> 0 -> n * m <> 0.\nProof.\n  simplify.\n  (* you could use the \"Search\" command with a pattern: *)\n  Search (_ * _ <> 0).\n  (* which outputs the name of a handy lemma we can apply: *)\n  apply N.neq_mul_0.\n  split; assumption.\n  (* (note that in this case \"nia\" would have worked as well, but in any case, it's good to know\n     the \"Search\" command. *)\nQed.\n\n(* Here's another example of how to use the \"Search\" command:\n   Suppose you have the goal *)\nGoal forall n, n <> 0 -> n / n = 1.\nProof.\n  simplify.\n  (* If we do \"Search (_ / _)\" we get a very long list, but if we do *)\n  Search (?x / ?x).\n  (* we force the two numbers on both sides of the / to be the same, and we only get the lemma we need: *)\n  apply N.div_same.\n  assumption.\nQed.\n\n(* Now we're ready to prove a few simple facts: *)\n\nLemma peal_fact: forall n, (n + 1)! = n! * (n+1).\nProof.\n  simplify.\n  unfold_recurse (fact) (n).\n  apply N.mul_comm.\nQed.\n\nLemma fact_nonzero: forall n, n! <> 0.\nProof.\n  induct n; simplify; try(equality).\n  rewrite peal_fact.\n  Search (_ * _ <> 0).\n  apply N.neq_mul_0.\n  split.\n  apply IHn.\n  linear_arithmetic.\nQed.\n\nLemma Cn0: forall n, C n 0 = 1.\nProof.\n  induct n.\n  compute.\n  equality.\n  Print C.\n  unfold C.\n  Search (?x - 0 = ?x).\n  rewrite N.sub_0_r.\n  assert(0! = 1).\n  compute.\n  equality.\n  rewrite H.\n  rewrite N.mul_1_r.\n  apply N.div_same.\n  apply fact_nonzero.\nQed.\n\nLemma Cnn: forall n, C n n = 1.\nProof.\n  induct n.\n  compute.\n  equality.\n  unfold C.\n  simplify.\n  Search (?x - ?x = 0).\n  rewrite N.sub_diag.\n  assert(0! = 1).\n  compute.\n  equality.\n  rewrite H.\n  Search (1 * ?x = ?x).\n  rewrite N.mul_1_l.\n  apply N.div_same.\n  apply fact_nonzero.\nQed.\n(* It's somewhat surprising that in the definition of C(n, k),\n\n      n!\n  -----------\n  (n - k)! k!\n\n  the denominator always divides the numerator.\n  The following lemma proves it. Note that \"(a | b)\" means \"a divides b\".\n  We provide the solution for you, so that you can step through it and use it as a\n  source of useful strategies you can apply in the exercises below.\n  Make sure to step through it and to understand each proof step! *)\nLemma C_is_integer: forall n k, k <= n ->\n    (((n - k)! * k!) | n!).\nProof.\n  induct n.\n  - simplify.\n    replace k with 0 by linear_arithmetic.\n    simplify.\n(* How can we prove that 1 divides 1? Probably it follows immediately from the definition of\n   divisibility, so let's try to unfold it:\n\n    unfold \"|\".\n\n   Unfortunately that fails (reported at https://github.com/coq/coq/issues/11420), but we can do\n\n    Locate \"|\".\n\n   The output of this command shows us all notations involving \"|\", and the last one (N.divide) is the one\n   we want. So we just unfold that one: *)\n    unfold N.divide.\n    exists 1. equality.\n  - simplify. unfold N.divide in *.\n    assert (k = 0 \\/ k = n + 1 \\/ 1 <= k <= n) as C by linear_arithmetic. cases C.\n    + subst.\n      replace (n + 1 - 0) with (n + 1) by linear_arithmetic.\n      replace (0!) with 1 by equality.\n      exists 1.\n      linear_arithmetic.\n    + subst.\n      replace (n + 1 - (n + 1)) with 0 by linear_arithmetic.\n      replace (0!) with 1 by equality.\n      exists 1. linear_arithmetic.\n    + pose proof (IHn k) as IH1.\n      assert (k <= n) as A by linear_arithmetic. specialize (IH1 A). invert IH1.\n      pose proof (IHn (k - 1)) as IH2.\n      assert (k - 1 <= n) as B by linear_arithmetic. specialize (IH2 B). invert IH2.\n      replace (n - (k - 1)) with (n - k + 1) in H1 by linear_arithmetic.\n      unfold_recurse fact n.\n      replace (k!) with ((k - 1 + 1)!) in *.\n      2: { f_equal. linear_arithmetic. }\n      unfold_recurse fact (k - 1).\n      replace (k - 1 + 1) with k in * by linear_arithmetic.\n      apply N.mul_cancel_r with (p := n - k + 1) in H0. 2: linear_arithmetic.\n      apply N.mul_cancel_r with (p := k) in H1. 2: linear_arithmetic.\n      assert (forall l1 r1 l2 r2, l1 = r1 -> l2 = r2 -> l1 + l2 = r1 + r2) as E. {\n        simplify. linear_arithmetic.\n      }\n      specialize E with (1 := H0) (2 := H1).\n      replace (n! * (n - k + 1) + n! * k) with ((n + 1) * n!) in E by nia.\n      rewrite E.\n      replace (n + 1 - k) with (n - k + 1) by linear_arithmetic.\n      unfold_recurse fact (n - k).\n      remember ((n - k)!) as F1.\n      remember ((k - 1)!) as F2.\n      remember (n - k + 1) as F3.\n      remember k as F4.\n      exists (x + x0).\n      nia.\nQed.\n\n(* Now we're ready to prove correctness of our optimized implementation bcoeff.\n   Since this is not a class about math, we're providing a paper proof of each proof step\n   of the inductive case:\n\n  C(n, k + 1)\n\n             n!\n= -----------------------\n  (n - (k + 1))! (k + 1)!\n\n             n!\n= -----------------------\n  (n - k - 1)! k! (k + 1)\n\n         n! (n - k)\n= -------------------------------\n  (n - k - 1)! (n - k) k! (k + 1)\n\n               n! (n - k)\n= ---------------------------------------\n  (n - k - 1)! (n - k - 1 + 1) k! (k + 1)\n\n          n! (n - k)\n= ---------------------------\n  (n - k - 1 + 1)! k! (k + 1)\n\n      n! (n - k)\n= -------------------\n  (n - k)! k! (k + 1)\n\n  n! (n - k)\n= ----------- / (k + 1)\n  (n - k)! k!\n\n      n!\n= ----------- * (n - k) / (k + 1)\n  (n - k)! k!\n\n= C(n, k) * (n - k) / (k + 1)\n\n= bcoeff(n, k) * (n - k) / (k + 1)\n\n= bcoeff(n, k + 1)\n\nYour task is to translate this proof into Coq!\n\nPotentially useful hint:\nNote that multiplication and division have the same operator priority, and both are left-associative, so\n   \"a / b * c / d\" is \"((a / b) * c) / d\", NOT \"(a / b) * (c / d)\"\n\nHere we go: *)\nLemma bcoeff_correct: forall n k, k <= n -> bcoeff n k = C n k.\nProof.\n  induct k.\n  simplify.\n  rewrite Cn0.\n  equality.\n\n  simplify.\n  symmetry.\n  unfold C.\n\n  rewrite peal_fact.\n  Search ((?c * _ )/ (?c * _)).\n  (* N.div_mul_cancel_l. *)\n  assert (H2 : (n-k) * (n!) / ((n-k) * ((n - (k + 1))! * (k! * (k + 1)))) = (n! / ((n - (k + 1))! * (k! * (k + 1)))) ).\n  assert (H3: (n - k) <> 0).\n  linear_arithmetic.\n  rewrite  N.div_mul_cancel_l with (c:= (n - k)).\n  equality.\n  Search (_ * _ <> 0).\n  apply N.neq_mul_0.\n  split.\n  apply fact_nonzero with (n:= (n - (k + 1))).\n  apply N.neq_mul_0.\n  split.\n  apply fact_nonzero.\n  linear_arithmetic.\n  assumption.\n  rewrite <- H2.\n\n\n  assert((n - k) * (n - (k + 1))! = (n - k)!).\n  assert( n - (k + 1) = n - k - 1) by linear_arithmetic.\n  rewrite H0.\n  replace (n - k)  with ((n - k - 1 + 1))  by linear_arithmetic.\n  replace (n - k - 1 + 1 - 1) with (n- k - 1) by linear_arithmetic.\n  symmetry.\n  Search (?a * ?b = ?b * ?a).\n  rewrite <- N.mul_comm.\n  apply  peal_fact with (n := (n - k - 1)).\n  rewrite N.mul_comm.\n  replace ((n - k) * ((n - (k + 1))! * (k! * (k + 1)))) with ((n - k) * (n - (k + 1))! * (k! * (k + 1))) by linear_arithmetic. \n  rewrite H0.\n  replace ((n - k)! * (k! * (k + 1))) with ((n - k)! * k! * (k + 1)) by linear_arithmetic.\n  replace ((n - k)! * k! * (k + 1))with (((n - k)! * k!) * (k + 1)) by linear_arithmetic.\n  rewrite N.mul_comm.\n  \n  assert (H3: ((n - k) * n! / ((n - k)! * k! * (k + 1))) = ((n - k) * n! / ((n - k)! * k!) / (k + 1))).\n  rewrite <-  N.div_div.\n  equality.\n  apply N.neq_mul_0;split;apply fact_nonzero.\n  linear_arithmetic.\n  rewrite H3.\n\n\n\nrewrite N.divide_div_mul_exact with (c:= (n - k)) (a:= n!) (b:=((n - k)! * k!)). \nreplace  ((n! / ((n - k)! * k!))) with (C n k) by equality.\nrewrite N.mul_comm.\nrewrite <- IHk.\nunfold_recurse (bcoeff n) (k).\nequality.\nlinear_arithmetic.\napply N.neq_mul_0;split;apply fact_nonzero. \napply C_is_integer.\nlinear_arithmetic.\nQed.\n\n\n(* All binomial coefficients for a given n *)\n(* *************************************** *)\n\n(* In some applications, we need to know all binomal coefficients C(n,k) for a fixed n.\n   For instance, if we want to symbolically evaluate (x + y)^4, the result is\n\n   C(4,0)*x^4 + C(4,1)*x^3*y + C(4,2)*x^2*y^2 + C(4,3)*x*y^3 + C(4,4)*y^4\n\n   The simplest way to compute such lists would be to just use the C we defined above: *)\n\nDefinition all_coeffs_slow1(n: N): list N :=\n  (recurse by cases\n   | 0 => [1]\n   | k + 1 => C n (k + 1) :: recurse\n   end) n.\n\nCompute C 4 2.\nCompute all_coeffs_slow1 0.\nCompute all_coeffs_slow1 1.\nCompute all_coeffs_slow1 2.\nCompute all_coeffs_slow1 3.\nCompute all_coeffs_slow1 4.\nCompute all_coeffs_slow1 5.\nCompute all_coeffs_slow1 15.\n(* However, this is not very efficient:\n\nTime Compute all_coeffs_slow1 100.\n\ntakes 0.8s on my machine *)\n\n(* We could use our more efficient bcoeff from above: *)\nDefinition all_coeffs_slow2(n: N): list N :=\n  (recurse by cases\n   | 0 => [1]\n   | k + 1 => bcoeff n (k + 1) :: recurse\n   end) n.\n\nCompute all_coeffs_slow2 5.\nCompute all_coeffs_slow2 15.\n(* This is faster:\n\n   Time Compute all_coeffs_slow2 100.\n\ntakes 0.2s on my machine and\n\n  Time Compute all_coeffs_slow2 200.\n\ntakes 1.7 s on my machine.\n\nBut we can do even better by using Pascal's triangle:\n\n      1\n     1 1\n    1 2 1\n   1 3 3 1\n  1 4 6 4 1\n\nYou can observe that the i-th row of this triangle is the result of \"all_coeffs_slow1 i\",\nand that each value not at the boundary of the triangle is the sum of the values to\nits upper left and its upper right. For instance, the 6 in the last row is the sum of the\ntwo 3s above it.\nMore formally, we can state this as follows: *)\nDefinition Pascal's_rule: Prop := forall n k,\n    1 <= k <= n ->\n    C (n+1) k = C n (k - 1) + C n k.\n(* Note that the above is only a definition which gives a name to this proposition,\n   but not a lemma.\n   We don't ask you to prove it, but it's a fun optional exercise, have a look at the\n   end of this file if you're interested! *)\n\n(* The following function takes in a line of Pascal's triangle and computes the line below it: *)\nDefinition nextLine(l: list N): list N :=\n  1 :: seq (fun k => ith (k - 1) l + ith k l) (len l) 1.\n\nCompute nextLine [1; 3; 3; 1].\nCompute nextLine (nextLine [1; 3; 3; 1]).\n\n(* This allows us to define a faster all_coeffs function: *)\nDefinition all_coeffs_fast: N -> list N :=\n  recurse by cases\n  | 0 => [1]\n  | n + 1 => nextLine recurse\n  end.\n\n(* Time Compute all_coeffs_fast 200. takes 0.35s on my computer *)\n\n\nLemma helper_len: forall a l, len(a::l) = 1 + len l.\ninduct l; simplify; equality.\nQed.\n\nLemma length_all_coeffs: forall n, len(all_coeffs_fast(n)) = n + 1.\n\ninduct n.\nsimplify.\nlinear_arithmetic.\nsimplify.\nunfold_recurse all_coeffs_fast n.\nunfold nextLine.\nrewrite helper_len.\nrewrite seq_len.\nrewrite IHn.\nlinear_arithmetic.\nQed.\n\nHint Rewrite Cnn.\nHint Rewrite length_all_coeffs.\nHint Rewrite helper_len.\nHint Rewrite seq_len.\nLtac hammer:= repeat (simplify; try linear_arithmetic; simplify; try equality; simplify).\n\n(* Exercise: Let's prove that all_coeffs_fast is correct.\n   Note that you can assume Pascal's rule to prove this. *)\nLemma all_coeffs_fast_correct:\n  Pascal's_rule ->\n  forall n k,\n    k <= n ->\n    ith k (all_coeffs_fast n) = C n k.\nProof.\ninduct n.\nsimplify.\ncases k.\nequality.\nlinear_arithmetic.\n\n\nsimplify.\nunfold_recurse all_coeffs_fast n.\nunfold nextLine.\n\ninduct k.\nrewrite first_element.\nrewrite Cn0.\nequality.\n\nclear IHk.\nassert(k <= n) by linear_arithmetic.\n\nrewrite j; hammer.\nrewrite seq_spec; hammer.\nreplace (1 + k - 1) with k  by linear_arithmetic.\nreplace (1 + k) with (k + 1) by linear_arithmetic.\nrewrite IHn; hammer.\nunfold Pascal's_rule in H.\nassert (k < n \\/ k = n) by linear_arithmetic.\ncases H2.\nrewrite IHn; hammer.\nrewrite H; hammer.\nreplace (k + 1 - 1) with k  by linear_arithmetic.\nequality.\nrewrite ith_out_of_bounds_0; hammer.\nrewrite H2; hammer.\nQed.\n\n(* ----- THIS IS THE END OF PSET2 ----- All exercises below this line are optional. *)\n(* Optional exercise: Let's prove that Pascal's rule holds.\n   On paper, this can be proved as follows, but feel free to ignore this if you want\n   the full challenge!\n\n   C(n, k-1) + C(n, k)\n\n           n!                 n!\n= --------------------- + -----------\n  (n - k + 1)! (k - 1)!   (n - k)! k!\n\n              n!                          n!\n= ----------------------------- + -------------------\n  (n - k)! (n - k + 1) (k - 1)!   (n - k)! k (k - 1)!\n\n               n! k                          n! (n - k + 1)\n= ------------------------------- + -------------------------------\n  (n - k)! (n - k + 1) (k - 1)! k   (n - k)! k (k - 1)! (n - k + 1)\n\n         n! (k + n - k + 1)\n= -------------------------------\n  (n - k)! (n - k + 1) (k - 1)! k\n\n    (n + 1)!\n= ---------------\n  (n - k + 1)! k!\n\n= C(n+1, k)\n*)\nLemma Pascal's_rule_holds: Pascal's_rule.\nProof.\n  unfold Pascal's_rule.\n\n  (* Note: Proving\n       a     b     a+b\n      --- + --- =  ---\n       c     c      c\n     is a bit trickier than you might expect, because we're using integer division here.\n     So, for instance,\n      1     3                                                              1+3\n     --- + ---   equals 0 + 1 in round-down integer division, which is not ---\n      2     2                                                               2\n     To make sure this rule holds, we must also require that c and b both divide a: *)\n  assert (forall a b c, c <> 0 -> (c | a) -> (c | b) -> a / c + b / c = (a + b) / c)\n    as add_fractions. {\n    clear.\n    simplify.\n    unfold N.divide in *. invert H0. invert H1.\n    rewrite N.div_mul by assumption.\n    rewrite N.div_mul by assumption.\n    replace (x * c + x0 * c) with ((x + x0) * c) by nia.\n    rewrite N.div_mul by assumption.\n    reflexivity.\n  }\n\nAdmitted.\n\n\n(* Optional exercise:\n   all_coeffs_fast is still not as fast as it could be, because nextLine uses ith\n   to access the elements of the previous line, and each invocation of ith takes\n   linear time in i.\n   It would be more efficient to implement nextLine as a recursive function\n   which iterates through the previous line just once and computes the next line\n   on the fly.\n   Define such a nextLine' function, and then use it to define all_coeffs_faster,\n   observe how it's even faster than all_coeffs_fast, and finally, prove that\n   it's correct. *)\n\nDefinition nextLine'(l: list N): list N. Admitted.\n\nDefinition all_coeffs_faster: N -> list N. Admitted.\n\nLemma all_coeffs_faster_correct: forall n k,\n    k <= n ->\n    ith k (all_coeffs_faster n) = C n k.\nProof.\nAdmitted.\n", "meta": {"author": "nicolas3355", "repo": "FormalReasoningAboutProgramsSpring2020", "sha": "85a908b07ea5b95212979ce224f902ad23497208", "save_path": "github-repos/coq/nicolas3355-FormalReasoningAboutProgramsSpring2020", "path": "github-repos/coq/nicolas3355-FormalReasoningAboutProgramsSpring2020/FormalReasoningAboutProgramsSpring2020-85a908b07ea5b95212979ce224f902ad23497208/pset02_BinomialCoefficients/Pset2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.8840392893839086, "lm_q1q2_score": 0.7100372005131141}}
{"text": "Require Import Coq.Relations.Relations.\n\nSection SubsetDef.\n\nContext `{U : Type}.\n\n(*Definition 1.3*)\nDefinition subset (A : U -> Prop) (B : U -> Prop) :=\n  forall x, A x -> B x.\nDefinition nonempty (A : U -> Prop) :=\n  exists x, A x.\n\nEnd SubsetDef.\n\nNotation \"A ⊂ B\" := (subset A B) (at level 50) : subset_scope.\nNotation \"A == B\" := (subset A B /\\ subset B A) (at level 50) : subset_scope.\n\nSection OrderDef.\n\nContext `{U : Type}.\n\n(*Definition 1.5*)\nClass Order : Type :=\n  {\n    ord : relation U;\n    O_prop1 : forall x y,\n      (ord x y /\\ ~(x = y) /\\ ~(ord y x)) \\/\n      (~(ord x y) /\\ x = y /\\ ~(ord y x)) \\/\n      (~(ord x y) /\\ ~(x = y) /\\ ord y x);\n    O_prop2 : forall x y z, ord x y -> ord y z -> ord x z;\n  }.\n\nEnd OrderDef.\n\nNotation \"x < y\" := (ord x y) : ord_scope.\nNotation \"x < y < z\" := ((ord x y) /\\ (ord y z)) : ord_scope.\nNotation \"x ≤ y\" := (ord x y \\/ x = y) (at level 50) : ord_scope.\n\nSection OrderBounds.\n\nVariable U : Type.\n\nOpen Scope ord_scope.\n\nDefinition order_trich_contr : forall (O: @Order U) x y,\n  x ≤ y /\\ y < x -> False.\nProof.\n  intros.\n  destruct H.\n  destruct (O_prop1 x y).\n  apply H1 in H0. apply H0.\n  destruct H1.\n  apply H1 in H0. apply H0.\n  destruct H.\n  apply H1 in H. apply H.\n  apply H1 in H. apply H.\nQed.\n\nDefinition order_trich_split : forall (O: @Order U) x y,\n  x ≤ y \\/ y < x.\nProof.\n  intros.\n  destruct (O_prop1 x y).\n  left. left. apply H.\n  destruct H.\n  left. right. apply H.\n  right. apply H.\nQed.\n\n(*Definition 1.6*)\n\n\n(*Definition 1.7*)\nDefinition upper_bound (O : Order) (E : U -> Prop) (beta : U) :=\n  forall x, E x -> x ≤ beta.\n\nDefinition lower_bound (O : Order) (E : U -> Prop) (beta : U) :=\n  forall x, E x -> beta ≤ x.\n\n(*Definition 1.8*)\nDefinition least_upper_bound (O : Order) (E : U -> Prop) (alpha : U) :=\n  upper_bound O E alpha /\\\n  (forall gamma, gamma < alpha -> ~(upper_bound O E gamma)).\n\nDefinition greatest_lower_bound (O : Order) (E : U -> Prop) (alpha : U) :=\n  lower_bound O E alpha /\\\n  (forall gamma, alpha < gamma -> ~(lower_bound O E gamma)).\n\n\n\n(* Definition 1.10 *)\n(*<sup> is the a supreme function that assigns a supreme to sets.\n  In other words, \"lub_prop O sup\" holds if sup works as expected.\n  One could argue that sup needs to be defined only for sets that \n  are nonempty and bounded above. However, this complicates a lot\n  the typing.\n*)\nDefinition lub_property (O : Order)\n  (sup : (U -> Prop) -> U) : Prop :=\n  forall (E : U -> Prop)\n  (x_E : U) (beta_E : U),\n  E x_E -> upper_bound O E beta_E ->\n  least_upper_bound O E (sup E).\n\nDefinition glb_property (O : Order)\n  (inf : (U -> Prop) -> U) : Prop :=\n  forall (E : U -> Prop)\n  (x_E : U) (beta_E : U),\n  E x_E -> lower_bound O E beta_E ->\n  greatest_lower_bound O E (inf E).\n\n(*Theorem 1.11*)\nTheorem Th_1_11 (O : Order) (sup : (U -> Prop) -> U) (B : U -> Prop)\n  (x_B : U) (beta_B : U) :\n  lub_property O sup -> B x_B -> lower_bound O B beta_B ->\n  let L := fun x => (lower_bound O B x) in\n    exists alpha, least_upper_bound O L alpha /\\ greatest_lower_bound O B alpha.\nProof.\n  intros.\n  exists (sup L).\n  assert (least_upper_bound O L (sup L)).\n  { apply (H _ beta_B x_B).\n    - unfold L. intros x H2. apply H1. apply H2.\n    - intros x H2. apply H2. apply H0. }\n  split.\n  - apply H2.\n  - split.\n    + intros x H3. destruct (O_prop1 (sup L) x) as [H4 | [H4 | H4]].\n      * left. apply H4.\n      * right. apply H4.\n      * destruct H2.\n        assert False. unfold not in H5.\n        apply (H5 x). apply H4.\n        intros y H6. apply H6. apply H3.\n        contradiction.\n    + intros gamma H3 H4.\n      destruct H2.\n      assert (~(L gamma)).\n      { intros H6. destruct (O_prop1 (sup L) gamma) as [H7 | [H7 | H7]].\n        - destruct (H2 gamma H6) as [H8 | H8].\n          * apply H7 in H8. apply H8.\n          * destruct H7 as [H9 [H10 H11]]. apply H10. symmetry. apply H8.\n        - apply H7 in H3. apply H3.\n        - apply H7 in H3. apply H3. }\n      * apply H6 in H4. apply H4.\nQed.\n\nClose Scope ord_scope.\n\nEnd OrderBounds.\n\n\n", "meta": {"author": "bdiehs", "repo": "CoqAnalysis", "sha": "d89d792276aa2753f220dced5eec954cb3566b47", "save_path": "github-repos/coq/bdiehs-CoqAnalysis", "path": "github-repos/coq/bdiehs-CoqAnalysis/CoqAnalysis-d89d792276aa2753f220dced5eec954cb3566b47/Order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8031737987125613, "lm_q1q2_score": 0.7100371856772693}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nFrom Coq Require Import Eqdep.\n\n(*************************************************************)\n(************ Some useful facts about sequences **************)\n(*************************************************************)\n\nFixpoint remove_elem (xs : seq (nat * nat * seq nat)) e :=\n  match xs with\n  | x :: xs => if x == e then xs else x :: (remove_elem xs e)\n  | [::] => [::]\n  end.\n\nLemma remove_elem_all xs p e :\n  all p xs -> all p (remove_elem xs e).\nProof.\nelim:xs=>//x xs Hi/=/andP[H1 H2].\nby case B: (x==e)=>//=; rewrite H1 (Hi H2).\nQed.  \n\nLemma remove_elem_in xs e :\n  if e \\in xs\n  then perm_eq (e :: (remove_elem xs e)) xs = true\n  else (remove_elem xs e) = xs.\nProof.\nelim: xs=>//x xs Hi.\nrewrite inE; case: ifP=>/=; last first.\n- case/negbT/norP=>/negbTE; rewrite eq_sym=>->/negbTE Z.\n  by rewrite Z in Hi; rewrite Hi.\ncase/orP.\n- by move/eqP=>Z; subst e; rewrite eqxx; apply: perm_refl.\nmove=>Z; rewrite Z in Hi; case: ifP=>X. \n- by move/eqP: X=>?; subst e; apply: perm_refl.\nrewrite -cat1s -[x::_]cat1s-[x::xs]cat0s -[x::xs]cat1s.\napply/permPl.\nmove: (perm_catCA [::e] [::x] (remove_elem xs e))=>/permPl H1.\nrewrite !cat1s in H1.\nrewrite  -(perm_cons x (e :: remove_elem xs e) xs) in Hi.\nrewrite !cat1s !cat0s; apply/permPl.\nby apply: (perm_trans H1 Hi).\nQed.\n\n", "meta": {"author": "DistributedComponents", "repo": "disel", "sha": "88dc15450394a5963f513d220001b49389c6b52f", "save_path": "github-repos/coq/DistributedComponents-disel", "path": "github-repos/coq/DistributedComponents-disel/disel-88dc15450394a5963f513d220001b49389c6b52f/theories/Examples/SeqLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7100371853059481}}
{"text": "(*\n  This is exercises for <Software Foundations> CH8.\n  Author : Brethland, Late 2019.\n*)\n\nRequire Import Coq.Arith.Arith. \nRequire Import Coq.Bool.Bool. \nRequire Export Coq.Strings.String. \nRequire Import Coq.Logic.FunctionalExtensionality. \nRequire Import Coq.Lists.List.\nRequire Import Unicode.Utf8.\nRequire Import Setoid.\n\nDefinition beq_string x y :=   if string_dec x y then true else false. \n\nTheorem beq_string_refl : ∀ s, true = beq_string s s. \nProof. \n  intros s. unfold beq_string. destruct (string_dec s s) as [|Hs]. \n  - reflexivity.   \n  - destruct Hs. reflexivity. \nQed.\n\nTheorem beq_string_true_iff : ∀ x y : string,   beq_string x y = true ↔ x = y. \nProof. \n  intros x y. \n  unfold beq_string. \n  destruct (string_dec x y) as [|Hs]. \n  - subst. split. auto. auto.\n  - split. \n    + intros contra. inversion contra.\n    + intros H. destruct Hs. auto.\nQed.\n\nTheorem beq_string_false_iff : ∀ x y : string,   beq_string x y = false   ↔ x ≠ y. \nProof. \n  intros x y. rewrite <- beq_string_true_iff. \n  rewrite not_true_iff_false. reflexivity. \nQed.\n\nTheorem false_beq_string : ∀ x y : string, x ≠ y → beq_string x y = false. \nProof. \n  intros x y. rewrite beq_string_false_iff. \n  intros H. apply H. \nQed.\n\nDefinition total_map (A:Type) := string → A.\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=   (fun _ => v).\n\nDefinition t_update {A:Type} (m : total_map A) (x : string) (v : A) := \n  fun x' => if beq_string x x' then v else m x'.\n\nNotation \"'_' '!->' v\" := (t_empty v)\n  (at level 100, right associativity).\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n                              (at level 100, v at next level, right associativity).\n\nAxiom functional_extensionality : ∀ {X Y: Type} {f g : X → Y}, (∀ (x:X), f x = g x) → f = g.\n\nLemma t_apply_empty: ∀ (A:Type) (x: string) (v: A), (_ !-> v) x = v.\nProof.\n  intros.\n  unfold t_empty. auto.\nQed.\n\nLemma t_update_eq : ∀(A : Type) (m : total_map A) x v,\n    (x !-> v ; m) x = v.\nProof.\n  intros. unfold t_update. rewrite <- beq_string_refl.\n  auto.\nQed.\n\nTheorem t_update_neq : ∀(A : Type) (m : total_map A) x1 x2 v,\n    x1 ≠ x2 →\n    (x1 !-> v ; m) x2 = m x2.\nProof.\n  intros.\n  unfold t_update. apply beq_string_false_iff in H.\n  rewrite H. auto.\nQed.\n\nLemma t_update_shadow : ∀(A : Type) (m : total_map A) x v1 v2,\n    (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\n  intros.\n  apply functional_extensionality.\n  intros. unfold t_update.\n  destruct (beq_string x x0) eqn:HE.\n  - auto.\n  - auto.\nQed.\n\nLemma beq_stringP : ∀ x y, reflect (x = y) (beq_string x y).\nProof.\n  intros. destruct (beq_string x y) eqn:HS.\n  - apply ReflectT. apply beq_string_true_iff. auto.\n  - apply ReflectF. apply beq_string_false_iff. auto.\nQed.\n\nTheorem t_update_same : ∀(A : Type) (m : total_map A) x,\n    (x !-> m x ; m) = m.\nProof.\n  intros. apply functional_extensionality.\n  intros. unfold t_update.\n  destruct (beq_stringP x x0).\n  - rewrite e. auto.\n  - auto.\nQed.\n\nTheorem t_update_permute : ∀(A : Type) (m : total_map A)\n                                  v1 v2 x1 x2,\n    x2 ≠ x1 →\n    (x1 !-> v1 ; x2 !-> v2 ; m)\n    =\n    (x2 !-> v2 ; x1 !-> v1 ; m).\nProof.\n  intros.\n  apply functional_extensionality.\n  intros. unfold t_update.\n  destruct (beq_stringP x1 x).\n  - destruct (beq_stringP x2 x).\n    + rewrite e,e0 in H. unfold not in H.\n      destruct H. auto.\n    + auto.\n  - destruct (beq_stringP x2 x).\n    + auto.\n    + auto.\nQed.\n\nDefinition partial_map (A : Type) := total_map (option A).\nDefinition empty {A : Type} : partial_map A :=\n  t_empty None.\nDefinition update {A : Type} (m : partial_map A)\n           (x : string) (v : A) :=\n  (x !-> Some v ; m).\n\nNotation \"x '⊢>' v ';' m\" := (update m x v)\n  (at level 100, v at next level, right associativity).\nNotation \"x '⊢>' v\" := (update empty x v)\n  (at level 100).\n ", "meta": {"author": "Brethland", "repo": "LEARNING-STUFF", "sha": "eb2cef0556efb9a4ce11783f8516789ea48cc344", "save_path": "github-repos/coq/Brethland-LEARNING-STUFF", "path": "github-repos/coq/Brethland-LEARNING-STUFF/LEARNING-STUFF-eb2cef0556efb9a4ce11783f8516789ea48cc344/Coq/Coq15.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7100371783158188}}
{"text": "Require Export Coq.Sets.Multiset.\nRequire Export Pig.Schema.\n\n\nInductive relation (s: schema_ty) : Type := \n| Relation: multiset (support s) -> relation s.\n\n\nDefinition relation_data (s: schema_ty) (r: relation s) : multiset (support s) :=\n  match r with\n  | Relation _ mset => mset\n  end.\n\n\nDefinition relation_eq (s: schema_ty) (r1 r2: relation s) : Prop :=\n  meq (relation_data s r1) (relation_data s r2).\n\n\nDefinition relation_multiplicity (s: schema_ty) (r: relation s) (tup: support s) :=\n  multiplicity (relation_data s r) tup.\n\n\n(* TODO *)\n(* Definition relation_proj (s: schema_ty) (r: relation s) (c: col) := ??? *)\n\n(* An example schema with just one column: a nat column: *)\n\nExample nat_schema : schema_ty := ( CTyNat *** ).\nExample nat_tuple : support nat_schema := 1.\nExample empty_nat_relation : relation nat_schema :=\n  Relation nat_schema (EmptyBag nat).\n\n(* Can be used to generate various example singleton relations for various\n   schema using the `SingletonBag` definition. *)\nExample singleton_relation (s: schema_ty) :=\n  (SingletonBag (support_eq s) (support_eq_dec s)).\n\n\n(* TODO: Finish this example. *)\n(*\nExample singleton_nat_relation : relation nat_schema :=\n  Relation nat_schema (singleton_relation nat_schema 5).\nExample singleton_nat_relation' : relation nat_schema :=\n  Relation nat_schema (Bag (fun (n: nat) => match n with\n                                            | 5 => 1\n                                            | _ => 0\n                                            end)).\nLemma two_singletons_are_eq : relation_eq nat_schema singleton_nat_relation singleton_nat_relation'.\n  unfold relation_eq. simpl.\n  unfold meq. simpl.\n  intro. induction a.\n  - (* a = O *) admit.\n  - (* a = S a *) admit.\nAdmitted.\n*)\n\n(* An example schema with just one column: a bag (of nat): *)\nExample bag_schema := (CTyBag (CTyNat ***) ***).\nExample bag_tuple : support bag_schema := EmptyBag nat.\nExample bag_relation : relation bag_schema := Relation bag_schema (EmptyBag (multiset nat)).\n\n(* An example schema with two cols: nat and bag of nat. *)\nExample nat_bag_schema : schema_ty := CTyNat *** CTyBag (CTyNat ***) ***.\nExample nat_bag_tuple : support nat_bag_schema :=  (1, (EmptyBag nat)).\nExample nat_bag_relation : relation nat_bag_schema := Relation nat_bag_schema (EmptyBag (nat * (multiset nat))).\n", "meta": {"author": "isu-cs641s16-axum", "repo": "axum", "sha": "cf441c47f4ba5d85c869c5a425193bfdc02b5982", "save_path": "github-repos/coq/isu-cs641s16-axum-axum", "path": "github-repos/coq/isu-cs641s16-axum-axum/axum-cf441c47f4ba5d85c869c5a425193bfdc02b5982/Relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7100371745221484}}
{"text": "(* Practica 1 *)\n\nSection P1.\nVariables A B C:Prop.\n\n(*Ej 3.1 *)\nTheorem e31: A->A->A.\nProof.\nintros.\nexact H.\nQed.\n\n(*Ej 3.1 b *)\nTheorem e31b: A->A->A.\nProof.\nintros.\nexact H0.\nQed.\n\n(* Ej 3.2 *)\nTheorem e32: (A->B->C)->A->(A->C)->B->C.\nProof.\nintros.\napply H;assumption.\nQed.\n\n(* Ej 3.2b *)\nTheorem e32b: (A->B->C)->A->(A->C)->B->C.\nProof.\nintros.\nexact (H H0 H2).\nQed.\n\n(* Ej 4.1 *)\nTheorem e41: A -> ~~A.\nProof.\nunfold not.\nintros.\nexact (H0 H).\nQed.\n\n(* Ej 4.2 *)\nTheorem e42: A -> B -> (A /\\ B).\nProof.\nintros.\nsplit;assumption.\nQed.\n\n(* Ej 4.3 *)\nTheorem e43: (A->B->C) -> (A/\\B->C).\nProof.\nintros.\nelim H0.\nassumption.\nQed.\n\n(* Ej 4.4 *)\nTheorem e44: A->(A\\/B).\nProof.\nleft.\nassumption.\nQed.\n\n(* Ej 4.5 *)\nTheorem e45: B->(A\\/B).\nProof.\nright.\nassumption.\nQed.\n\n(* Ej 4.6 *)\nTheorem e46: (A \\/ B) -> (B \\/ A).\nProof.\nintro.\nelim H; intro; [right | left]; assumption.\nQed.\n\n(* Ej 4.7 *)\nTheorem e47: (A->C)->(B->C)->A\\/B->C.\nProof.\nintros.\nelim H1; assumption.\nQed.\n\n(* Ej 4.8 *)\nTheorem e48: False->A.\nProof.\nintro.\nelim H.\nQed.\n\n(* Ej 6.1 *)\nTheorem e61: (A\\/B) -> ~(~A/\\~B).\nProof.\nunfold not.\nintros.\nelim H0.\nintros.\nelim H; assumption.\nQed.\n\n(* Ej 6.2 *)\nTheorem e62: A\\/B <-> B\\/A.\nProof.\nsplit; intro; elim H;\nintro; [right | left | right | left]; assumption.\nQed.\n\n(* Ej 6.3 *)\nTheorem e63: A\\/B -> ((A->B)->B).\nProof.\nintros.\nelim H; intro; [exact (H0 H1) | assumption].\nQed.\n\nEnd P1.\n\nSection Logica_Clasica.\nVariables A B C: Prop.\n\nRequire Import Classical.\nCheck classic.\n\n(* Ej 8.1 *)\nTheorem e81: ~~A->A.\nProof.\nintro.\nelim (classic A); intro; [ | elim H]; assumption.\nQed.\n\n(* Ej 8.2 *)\nTheorem e82: (A->B)\\/(B ->A).\nProof.\nelim (classic A); intro.\n  right.\n  intro.\n  assumption.\n\n  left.\n  intro.\n  elim H.\n  assumption.\nQed.\n\n(* Ej 8.3 *)\nTheorem e83: ~(A/\\B)-> ~A \\/ ~B.\nProof.\nunfold not.\nintro.\nelim (classic A); intro.\n  right.\n  intro.\n  apply H.\n  split; assumption.\n\n  left.\n  intro.\n  elim H0.\n  assumption.\nQed.\n\nEnd Logica_Clasica.\n\nSection ejercicio11.\n\n(* Ej 11 *)\n(* Definiciones *)\nVariable PF:Prop. (*el paciente tiene fiebre*)\nVariable PA:Prop. (*el paciente tiene piel amarillenta*)\nVariable PH:Prop. (*el paciente tiene hepatitis*)\nVariable PR:Prop. (*el paciente tiene rubeola*)\n\nHypothesis Regla1: PF \\/ PA -> PH \\/ PR.\nHypothesis Regla2: PR -> PF.\nHypothesis Regla3: PH /\\ ~PR -> PA.\n\nTheorem ej11: (~PA /\\ PF) -> PR.\nProof.\nintro.\nelim H.\nintros.\nelim (classic PR); intro.\n  assumption.\n\n  elim Regla1; [intro; elim H0; apply Regla3; split | intro | left]; assumption.\nQed.\n\nEnd ejercicio11.", "meta": {"author": "nicodelpiano", "repo": "coq", "sha": "06344cda6995cdd9c5d44c52880b49a7ec280ebd", "save_path": "github-repos/coq/nicodelpiano-coq", "path": "github-repos/coq/nicodelpiano-coq/coq-06344cda6995cdd9c5d44c52880b49a7ec280ebd/TP1/NicolasDelPiano.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040851, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7099532399814282}}
{"text": "(** **** Exercise: (basic_induction)  *)\n(** Prove os seguintes teoremas. Será necessário\n    buscar por resultados previamente provados. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros. induction n as [| n' IHn'].\n  - simpl. 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. Print Nat.add. induction n.\n  - Print Nat.add. simpl. reflexivity.\n  - simpl. rewrite IHn. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  intros. 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. induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\n(** **** Exercise: (mult_comm)  *)\n(** Use [assert] para ajudar na prova. Não é\n    necessário usar indução. *)\n\nTheorem plus_swap : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros.\n  rewrite plus_assoc. rewrite plus_assoc.\n  assert(H: n + m = m + n).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat,\n  m * n = n * m.\nProof.\n  intros n m. induction n.\n  - simpl. rewrite <- mult_n_O. reflexivity.\n  - Search mult. rewrite <- mult_n_Sm. simpl. rewrite plus_comm. rewrite IHn. reflexivity.\nQed.", "meta": {"author": "emmanuel-carreira", "repo": "coq", "sha": "90778be9e0b936838cf2a2fc790a87a0b100fa92", "save_path": "github-repos/coq/emmanuel-carreira-coq", "path": "github-repos/coq/emmanuel-carreira-coq/coq-90778be9e0b936838cf2a2fc790a87a0b100fa92/class05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8519528019683106, "lm_q1q2_score": 0.7099532239251868}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Reals.Rbasic_fun.\nRequire BuiltIn.\nRequire real.Real.\n\nImport Rbasic_fun.\n\n(* Why3 comment *)\n(* abs is replaced with (Reals.Rbasic_fun.Rabs x) by the coq driver *)\n\n(* Why3 goal *)\nLemma abs_def : forall (x:R), ((0%R <= x)%R ->\n  ((Reals.Rbasic_fun.Rabs x) = x)) /\\ ((~ (0%R <= x)%R) ->\n  ((Reals.Rbasic_fun.Rabs x) = (-x)%R)).\nsplit ; intros H.\napply Rabs_right.\nnow apply Rle_ge.\napply Rabs_left.\nnow apply Rnot_le_lt.\nQed.\n\n(* Why3 goal *)\nLemma Abs_le : forall (x:R) (y:R), ((Reals.Rbasic_fun.Rabs x) <= y)%R <->\n  (((-y)%R <= x)%R /\\ (x <= y)%R).\nintros x y.\nunfold Rabs.\ncase Rcase_abs ; intros H ; (split ; [intros H0;split | intros (H0,H1)]).\nrewrite <- (Ropp_involutive x).\nnow apply Ropp_le_contravar.\napply Rlt_le.\napply Rlt_le_trans with (1 := H).\napply Rle_trans with (2 := H0).\nrewrite <- Ropp_0.\napply Ropp_le_contravar.\nnow apply Rlt_le.\nrewrite <- (Ropp_involutive y).\nnow apply Ropp_le_contravar.\napply Rge_le in H.\napply Rle_trans with (2 := H).\napply Rle_trans with (Ropp x).\nnow apply Ropp_le_contravar.\nrewrite <- Ropp_0.\nnow apply Ropp_le_contravar.\nexact H0.\nexact H1.\nQed.\n\n(* Why3 goal *)\nLemma Abs_pos : forall (x:R), (0%R <= (Reals.Rbasic_fun.Rabs x))%R.\nexact Rabs_pos.\nQed.\n\n(* Why3 goal *)\nLemma Abs_sum : forall (x:R) (y:R),\n  ((Reals.Rbasic_fun.Rabs (x + y)%R) <= ((Reals.Rbasic_fun.Rabs x) + (Reals.Rbasic_fun.Rabs y))%R)%R.\nexact Rabs_triang.\nQed.\n\n(* Why3 goal *)\nLemma Abs_prod : forall (x:R) (y:R),\n  ((Reals.Rbasic_fun.Rabs (x * y)%R) = ((Reals.Rbasic_fun.Rabs x) * (Reals.Rbasic_fun.Rabs y))%R).\nexact Rabs_mult.\nQed.\n\n(* Why3 goal *)\nLemma triangular_inequality : forall (x:R) (y:R) (z:R),\n  ((Reals.Rbasic_fun.Rabs (x - z)%R) <= ((Reals.Rbasic_fun.Rabs (x - y)%R) + (Reals.Rbasic_fun.Rabs (y - z)%R))%R)%R.\nintros x y z.\nreplace (x - z)%R with ((x - y) + (y - z))%R by ring.\napply Rabs_triang.\nQed.\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/real/Abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7099532221619063}}
{"text": "Require Import GeoCoq.Axioms.continuity_axioms.\nRequire Import GeoCoq.Tarski_dev.Definitions.\n\nRequire Import Logic.ChoiceFacts.\n\nSection first_order.\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\n(** Dedekind's axiom of continuity implies the Tarski's axiom schema of continuity *)\n\nLemma dedekind__fod : dedekind_s_axiom -> first_order_dedekind.\nProof.\n  intros dedekind Alpha Beta HAlpha HBeta HA.\n  apply dedekind, HA.\nQed.\n\n(** This is a type whose members describe first-order formulas *)\n\nInductive tFOF :=\n  eq_fof1 : Tpoint -> Tpoint -> tFOF\n| bet_fof1 : Tpoint -> Tpoint -> Tpoint -> tFOF\n| cong_fof1 : Tpoint -> Tpoint -> Tpoint -> Tpoint -> tFOF\n| not_fof1 : tFOF -> tFOF\n| and_fof1 : tFOF -> tFOF -> tFOF\n| or_fof1 : tFOF -> tFOF -> tFOF\n| implies_fof1 : tFOF -> tFOF -> tFOF\n| forall_fof1 : (Tpoint -> tFOF) -> tFOF\n| exists_fof1 : (Tpoint -> tFOF) -> tFOF.\n\n(** This function interperts tFOF elements as Prop *)\n\nFixpoint fof1_prop (F:tFOF) := match F with\n  eq_fof1 A B => A = B\n| bet_fof1 A B C => Bet A B C\n| cong_fof1 A B C D => Cong A B C D\n| not_fof1 F1 => ~ fof1_prop F1\n| and_fof1 F1 F2 => fof1_prop F1 /\\ fof1_prop F2\n| or_fof1 F1 F2 => fof1_prop F1 \\/ fof1_prop F2\n| implies_fof1 F1 F2 => fof1_prop F1 -> fof1_prop F2\n| forall_fof1 P => forall A, fof1_prop (P A)\n| exists_fof1 P => exists A, fof1_prop (P A) end.\n\n(** Every first-order formula is equivalent to a Prop built with fof1_prop *)\n\nLemma fof__fof1 : FunctionalChoice_on Tpoint tFOF ->\n  forall F, FOF F -> exists F1,  F <-> fof1_prop F1 .\nProof.\n  intros choice F HFOF.\n  induction HFOF.\n  - exists (eq_fof1 A B); intuition.\n  - exists (bet_fof1 A B C); intuition.\n  - exists (cong_fof1 A B C D); intuition.\n  - destruct IHHFOF as [F1]. exists (not_fof1 F1). simpl; intuition.\n  - destruct IHHFOF1 as [F1]; destruct IHHFOF2 as [F2]; exists (and_fof1 F1 F2); simpl; intuition.\n  - destruct IHHFOF1 as [F1]; destruct IHHFOF2 as [F2]; exists (or_fof1 F1 F2); simpl; intuition.\n  - destruct IHHFOF1 as [F1]; destruct IHHFOF2 as [F2]; exists (implies_fof1 F1 F2); simpl; intuition.\n  - destruct (choice (fun A => (fun F1 => P A <-> fof1_prop F1)) H0) as [f].\n    exists (forall_fof1 f); simpl.\n    split; intros HH A; apply H1, HH.\n  - destruct (choice (fun A => (fun F1 => P A <-> fof1_prop F1)) H0) as [f].\n    exists (exists_fof1 f); simpl.\n    split; intros [A HA]; exists A; apply H1, HA.\nQed.\n\n(** Every Prop built with fof1_prop is a first-order formula *)\n\nLemma fof1__fof : forall F1, FOF (fof1_prop F1).\nProof.\n  induction F1; constructor; assumption.\nQed.\n\nEnd first_order.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Meta_theory/Continuity/first_order.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7098711942142284}}
{"text": "(**\nCoq/SSReflect/MathComp による定理証明\n\n第4章 MathComp ライブラリの基本ファイル\n\n4.4 seq.v --- リスト、seq 型のライブラリ\n\n======\n\n2018_12_05 @suharahiromichi\n *)\n\nFrom mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(**\n# はじめに\n\n本節はテキストを参照しながら、MathComp のソースコードに沿って説明していきます。\nソースコードが手元にあるならば、それも参照してください。\nopamでインストールしている場合は、ssrbool.v のソースは、たとえば以下にあります。\n\n~/.opam/4.07.1/lib/coq/user-contrib/mathcomp/ssreflect/seq.v\n*)\n\n(**\n# seq\n\nseq はpolymorphicな型である。\n\nStandard Coqのlistをリネーム (Definiton seq := list) したものであるので、\nCICに基づく帰納法の原理は、list_indである。seq_indではない。\n *)\nCheck list_ind\n  : forall (A : Type) (P : seq A -> Prop),\n    P [::]                                  (* 帰納法に基底 *)\n    ->\n    (forall (a : A) (l : seq A), P l        (* 帰納法の仮定 *)\n                                 ->\n                                 P (a :: l)) (* 証明するべきもの *)\n    ->\n    forall l : seq A, P l.                  (* 結論 *)\n\n(**\n# rcons\n\nrcons は再帰的に定義されている。\n\nFixpoint rcons s z := if s is x :: s' then x :: rcons s' z else [:: z].\n\n教科書にあるような、リストの後ろにcat (++, append) する定義とは異なる。\n *)\nSection RconsQ.\n  Variable T : Type.\n  \n  Definition rcons' (T : Type) (s : seq T) (z : T) : seq T := s ++ [:: z].\n\n(**\n（演習）両者が同値であることを証明してください。\n*)\n  Goal forall (s : seq T) (z : T), rcons s z = rcons' s z.\n  Proof.\n  Admitted.                                 (* 演習問題 *)\n\nEnd RconsQ.\n\n(**\n# head と last\n\n- head は最初の要素をとりだす（空なら第1引数）。behead はその残りの要素（空なら空）。\n- last は最後の要素をとりだす（空なら第1引数）。belast は？\n\n## ``belast' [::] = [::]`` の定義を使う例\n\nsee. csm_4_4_x_seq_head_last.v\n\n## ``ohead``\n\nohead は最初の要素を option型（Some なんとか) で取り出す（空ならNONE）。\n*)\n\nCompute ohead [::].                         (* None *)\nCompute ohead [:: 1; 2; 3].                 (* Some 1 *)\n\n\n(**\n# size (seq の寸法）\n *)\nSection Size.\n  \n  Variable T : Type.\n\n(**\n## size_cons\n\n自明であるが x :: s の寸法は、sの寸法の.+1である。\n *)\n  Lemma size_cons (x : T) (s : seq T) : size (x :: s) = (size s).+1.\n  Proof.\n    done.\n  Qed.\n\n(*\n## size に関する補題\n\n大抵の関数に関するsizeの補題が証明されているので、使うべきである。\n *)\n  Check size_cat\n    : forall (T : Type) (s1 s2 : seq T), size (s1 ++ s2) = size s1 + size s2.\n  Check size_rcons\n    : forall (T : Type) (s : seq T) (x : T), size (rcons s x) = (size s).+1.\n  Check size_drop\n    : forall (n0 : nat) (T : Type) (s : seq T), size (drop n0 s) = size s - n0.\n  Check size_rev : forall (T : Type) (s : seq T), size (rev s) = size s.\n  Check size_behead  : forall (T : Type) (s : seq T), size (behead s) = (size s).-1.\n(**\nこのうち、size_behead は直観に反している。``0.-1 = 0`` であることに注意してください。\n*)\nEnd Size.\n\n(**\n## 空リストとサイズの関係\n\n以下の ``0 < size s`` を ``1 <= size s`` にしても同じ。\n「<」は「<=」で定義されているため。\n *)\nLocate \"_ < _\".                            (* \"m < n\" := leq m.+1 n *)\n\nSection Size1.\n(**\n重要な補題：寸法0と空リストの関係を示す。\n *)\n  Variable T : eqType.\n  \n  Check size_eq0 : forall (T : eqType) (s : seq T), (size s == 0) = (s == [::]).\n  \n(**\nこれの否定を証明しておく。\n *)\n  Lemma size_not_eq0 (s : seq T) : (size s != 0) = (s != [::]).\n  Proof.\n(**\ns は 本当は seq_eqType なので「==」と「!=」が使える。\nまた、右辺は ``~~ (s == [::])`` なので、右辺の書き換えで証明できる。\n *)\n      by rewrite size_eq0.\n  Qed.\n\n(**\n使い方。寸法に関する命題と空リストか判定する命題とを相互に書き換えできる。\n\nsplitしているので煩瑣だが、実際の証明では、どちらかの「->」だけを証明することになる。\n*)\n  Goal forall (s : seq T), (1 <= size s) <-> (s <> [::]).\n  Proof.\n    move=> s.\n    Check lt0n : forall n : nat, (0 < n) = (n != 0). (* 覚えておくとよい。 *)\n    rewrite lt0n.\n    split=> H.\n    - apply/eqP.\n        by rewrite -size_not_eq0.\n    - move/eqP in H.\n        by rewrite size_not_eq0.\n  Qed.\n  \n(**\nnilp s は size s == 0 で定義されている。これのリフレクション補題が証明されている。\n*)\n  Print nilp. (*= fun (T : Type) (s : seq T) => size s == 0 *)\n  Check @nilP : forall T s, reflect (s = [::]) (nilp s).\n\n(**\n使い方。寸法に関する命題と空リストか判定する命題とを相互に変換（リフレクト）できる。\n\napply/nilP または move/nilP で、相互に変換できるので便利であろう。\n*)\n  Goal forall (s : seq T), (1 <= size s) <-> (s <> [::]).\n  Proof.\n    move=> s.\n    Check lt0n : forall n : nat, (0 < n) = (n != 0). (* 覚えておくとよい。 *)\n    rewrite lt0n.\n    split=> H.\n    - by apply/nilP.\n    - by apply/nilP.\n  Qed.\nEnd Size1.\n\n(**\n# cat (++, append) \n\n## cat に関する補題\n*)\n\nLocate \"_ ++ _\". (* := cat x y : seq_scope (default interpretation) *)\n\nCheck cat0s : forall (T : Type) (s : seq T), [::] ++ s = s.\nCheck cats0 : forall (T : Type) (s : seq T), s ++ [::] = s.\nCheck cat1s : forall (T : Type) (x : T) (s : seq T), [:: x] ++ s = x :: s.\nCheck cats1\n  : forall (T : Type) (s : seq T) (z : T), s ++ [:: z] = rcons s z.\nCheck catA\n  : forall (T : Type) (s1 s2 s3 : seq T), s1 ++ s2 ++ s3 = (s1 ++ s2) ++ s3.\nCheck cat_cons\n  : forall (T : Type) (x : T) (s1 s2 : seq T), (x :: s1) ++ s2 = x :: s1 ++ s2.\nCheck cat_nseq\n  : forall (T : Type) (n : nat) (x : T) (s : seq T), nseq n x ++ s = ncons n x s.\nCheck cat_rcons\n  : forall (T : Type) (x : T) (s1 s2 : seq T), rcons s1 x ++ s2 = s1 ++ x :: s2.\nCheck cat_take_drop\n  : forall (n0 : nat) (T : Type) (s : seq T), take n0 s ++ drop n0 s = s.\n\n(**\n## Inductive に定義した append と cat の同値を証明する。\n*)\nSection Append.\n  Variable A : Type.\n\n  Inductive append : seq A -> seq A -> seq A -> Prop :=\n  | append_nil (b : seq A) : append [::] b b\n  | append_cons (h : A) (a b c : seq A) :\n      append a b c -> append (h :: a) b (h :: c).\n  Hint Constructors append.\n  \n  Lemma append_cat (a b c : seq A) : append a b c <-> a ++ b = c.\n  Proof.\n    split.\n    - elim=> b'' //= a' b' c' H IH.\n        by rewrite IH.\n    - elim: a b c => //= [b c -> // | n' a' IH b' c' <-].\n      apply: append_cons.\n        by apply: IH.\n  Qed.\n(**\n補足： <-> のかたちの補題を適用するときは、apply/V を使う。\n*)\nEnd Append.\n\n(**\n# rev\n\n## 説明\n\nrev は catrev (末尾再帰) を使って定義されている。\n *)\nPrint rev.\n(* Definition rev := catrev ^~ [::] *)\n(* Definition rev s := catrev s [::] *)\nPrint catrev.\n(**\nfun T : Type =>\nfix catrev (s1 s2 : seq T) {struct s1} : seq T :=\n  match s1 with\n  | [::] => s2\n  | x :: s1' => catrev s1' (x :: s2)\n  end\n*)\n\nSection Lists2.\n  Variable A : Type.\n\n(**\n## （演習）末尾再帰ではない reverse と rev の同値を証明する。\n *)\n  Fixpoint reverse (xs : seq A) :=\n  match xs with\n  | nil => nil\n  | x :: xs' =>\n    reverse xs' ++ [:: x] (* rcons にしてもよいが、証明がかなり変わる *)\n  end.\n  \n  Goal forall (s : seq A), rev s = reverse s.\n  Proof.\n  Admitted.                                 (* 演習問題 *)\n  \n(**\n## Inductive に定義した isreverse と rev の同値を証明する。\n*)\n  Inductive isreverse : seq A -> seq A -> Prop :=\n  | reverse_nil (s : seq A) : isreverse [::] [::]\n  | reverse_cons (x : A) (s t : seq A) :\n      isreverse s t -> isreverse (x :: s) (t ++ [:: x]).\n(**\nisreverse (x :: s)  (rcons t x) とすると、証明は少し変わる。\nいずれにせよ、Inductiveな定義の中に、複雑な関数を書いてもかまわない。\n *)\n  Hint Constructors isreverse.\n\n(**\n自明な補題を証明しておく。\n*)\n  Lemma rev0 : @rev A [::] = [::].\n  Proof. done. Qed.\n  \n  Lemma rev1 (x : A) : @rev A [:: x] = [:: x].\n  Proof. done. Qed.\n  \n  Lemma rev_catrev (s t : seq A) : isreverse s t <-> rev s = t.\n  Proof.\n    split.\n    - elim=> [s' | x s' t' /= H IH].\n      + by rewrite /rev.\n      + rewrite -IH.\n        rewrite -rev1 -rev_cat /=.\n        done.\n    - elim: s t => //= [t <- | x s IH t' <-].\n      + rewrite rev0.\n          by apply: reverse_nil.\n      + rewrite rev_cons -cats1.\n        apply: reverse_cons.\n          by apply: IH.\n  Qed.\n  \n(**\n## Inductive に定義した isreverse と reverse の同値を証明する。\n*)\n  Lemma rev_reverse (s t : seq A) : isreverse s t <-> reverse s = t.\n  Proof.\n    split.\n    - elim=> [s' | x s' t' H IHs /=].\n      + done.\n      + rewrite IHs.\n          by rewrite cats1.\n    - elim: s t => [s' /= H | x s' IHs /= H1 H2].\n      + rewrite -H.\n          by apply: reverse_nil.\n      + rewrite -H2.\n        apply reverse_cons.\n          by apply: IHs.\n  Qed.\nEnd Lists2.\n\n(**\n## rev に関する補題\n *)\nCheck catrev_catl\n  : forall (T : Type) (s t u : seq T), catrev (s ++ t) u = catrev t (catrev s u).\nCheck catrev_catr\n  : forall (T : Type) (s t u : seq T), catrev s (t ++ u) = catrev s t ++ u.\nCheck catrevE : forall (T : Type) (s t : seq T), catrev s t = rev s ++ t.\nCheck cat_uniq\n  : forall (T : eqType) (s1 s2 : seq T),\n    uniq (s1 ++ s2) = [&& uniq s1, ~~ has (mem s1) s2 & uniq s2].\nCheck rev_cons\n  : forall (T : Type) (x : T) (s : seq T), rev (x :: s) = rcons (rev s) x.\nCheck size_rev\n  : forall (T : Type) (s : seq T), size (rev s) = size s.\nCheck rev_cat\n  : forall (T : Type) (s t : seq T), rev (s ++ t) = rev t ++ rev s.\nCheck rev_rcons\n  : forall (T : Type) (s : seq T) (x : T), rev (rcons s x) = x :: rev s.\n\nCheck revK : involutive rev. (* rev (rev s) = s 、 覚えておくこと。 *)\n\nCheck nth_rev\n  : forall (T : Type) (x0 : T) (n : nat) (s : seq T),\n    n < size s -> nth x0 (rev s) n = nth x0 s (size s - n.+1).\nCheck filter_rev\n  : forall (T : Type) (a : pred T) (s : seq T),\n    [seq x <- rev s | a x] = rev [seq x <- s | a x].\nCheck count_rev\n  : forall (T : Type) (a : pred T) (s : seq T), count a (rev s) = count a s.\nCheck has_rev\n  : forall (T : Type) (a : pred T) (s : seq T), has a (rev s) = has a s.\nCheck all_rev\n  : forall (T : Type) (a : pred T) (s : seq T), all a (rev s) = all a s.\n\n(**\n# has と all\n\n## 説明\n\nリストのある要素、または、すべての要素に対して、条件が成立する。\n *)\n\nCompute has odd [:: 1; 2; 3].               (* true *)\nCompute has odd [:: 2; 4; 6].               (* false *)\n\nCompute all odd [:: 1; 2; 3].               (* false *)\nCompute all odd [:: 1; 3; 5].               (* true *)\n\n(**\n## forall（∀）や exists（∃）を使った定義\n\nhas や all は再帰関数として定義されているが、exists や forall を使った同値な命題もある。\nそれとのリフレクションが定義されている。\n *)\n\nCheck @hasP : forall (eT : eqType) (a : pred eT) (s : seq eT),\n    reflect (exists2 x : eT, x \\in s & a x) (has a s).\n\nCheck @allP : forall (eT : eqType) (a : pred eT) (s : seq eT),\n    reflect (forall x : eT, x \\in s -> a x) (all a s).\n\n(**\nなお、exists2 は、論理式をふたつとれる「∃」。\nMathComp ぽい命名だが、バニラCoqで定義されている。\n*)\nPrint ex2.\n(**\nInductive ex2 (A : Type) (P Q : A -> Prop) : Prop :=\n    ex_intro2 : forall x : A, P x -> Q x -> exists2 x : A, P x & Q x\n*)\nCheck forall eT a s, exists2 x : eT, x \\in s & a x.\nCheck forall eT a s, ex2 (fun x : eT => x \\in s) (fun x : eT => a x).\n\n(**\n参考。普通のexists。\n\n「Coq/SSReflect/MathComp による定理証明」 p.77\n*)\nPrint ex.\n(**\nInductive ex (A : Type) (P : A -> Prop) : Prop :=\n    ex_intro : forall x : A, P x -> exists y, P y\n*)\nCheck forall eT a s, exists x : eT, a x.\nCheck forall eT a s, ex (fun x : eT => a x).\n\n(**\n## Standard Coq の 命題\n\nStandard Coq の List.v には、インダクティブな命題として、\nExists と Forall が定義されている。それとのリフレクションを定義した例：\n\nhttps://github.com/suharahiromichi/coq/blob/master/pearl/ssr_list_1.v\n *)\n\n(**\n## has と all についての補題\n*)\n\nCheck has_nil : forall (T : Type) (a : pred T), has a [::] = false. (* hasの定義から *)\nCheck has_seq1 : forall (T : Type) (a : pred T) (x : T), has a [:: x] = a x.\nCheck has_cat : forall (T : Type) (a : pred T) (s1 s2 : seq T),\n    has a (s1 ++ s2) = has a s1 || has a s2.\nCheck has_rcons : forall (T : Type) (a : pred T) (s : seq T) (x : T),\n    has a (rcons s x) = a x || has a s.\n\nCheck all_nil : forall (T : Type) (a : pred T), all a [::] = true. (* allの定義から *)\nCheck all_seq1 : forall (T : Type) (a : pred T) (x : T), all a [:: x] = a x.\nCheck all_cat : forall (T : Type) (a : pred T) (s1 s2 : seq T),\n    all a (s1 ++ s2) = all a s1 && all a s2.\nCheck all_rcons : forall (T : Type) (a : pred T) (s : seq T) (x : T),\n    all a (rcons s x) = a x && all a s.\n\n(**\n# nth\n *)\n\n(**\n## nth についての補題\n*)\n\n(**\n# take と drop\n *)\n\n(**\n## take と drop についての補題\n*)\n\n(**\n# == と \\in について （seq_eqType と seq_predType は polymorphicな型）\n *)\n\n(**\n## (seq_eqType T_eqType) ... 「==」 が使える\n\neqType 型クラス（インターフェース）のインスタンスとして seq_eqType を定義している。\nすると、seq eT 型 (ただし eT は、eqType のインスタンス） は、== の左右に書けるようになる。\n*)\nCheck [:: 1; 2] : seq nat.\nCheck [:: 1; 2] : seq_eqType nat_eqType.\nCompute [:: 1; 2] == [:: 3; 4].             (* false *)\n\n(**\n== の定義として eqseq が使われる。\n*)\nCheck @eqseq : forall T : eqType, seq T -> seq T -> bool.\n\n(*\n## (seq_predType T_eqTYpe) ... 「\\in」 が使える\n\npredType 型クラス（インターフェース）のインスタンスとして seq_predType を定義している。\nすると、seq eT 型 (ただし eT は、eqType のインスタンス） は、\\in の右に書けるようになる。\n*)\nCheck [:: 1; 2] : seq_predType nat_eqType.\nCompute 1 \\in [:: 1; 2].                    (* true *)\n\n(**\nStandard Coq の List.v には、インダクティブな命題として、\nIn が定義されている。それとのリフレクションを定義した例：\n\nhttps://github.com/suharahiromichi/coq/blob/master/pearl/ssr_list_1.v\n *)\n(**\n\\in の定義として mem_seq が使われる。\n*)\nCheck @mem_seq : forall T : eqType, seq T -> T -> bool.\n\n(**\n## 任意の eqType について\n *)\nSection In.\n  Variable eT : eqType.\n  Variable a b c : eT.\n\n  Check [:: a; b; c] : seq eT.\n  Check [:: a; b; c] : seq_eqType eT.\n\n  Goal [:: a] == [:: a].\n  Proof.\n    rewrite eqseq_cons.\n    apply/andP.\n    done.\n  Qed.\n  \n  Goal a \\in [:: a; b; c].\n  Proof.\n    rewrite !in_cons.\n    apply/orP/or_introl.\n    done.\n  Qed.\nEnd In.\n\n(**\n## \\in についての補題\n *)\n\nCheck in_cons : forall (T : eqType) (y : T) (s : seq T) (x : T),\n    (x \\in y :: s) = (x == y) || (x \\in s).\nCheck in_nil : forall (T : eqType) (x : T), (x \\in [::]) = false.\n\nCheck @mem_seq1 : forall (T : eqType) (x y : T),\n    (x \\in [:: y]) = (x == y).\nCheck mem_cat : forall (T : eqType) (x : T) (s1 s2 : seq T),\n    (x \\in s1 ++ s2) = (x \\in s1) || (x \\in s2).\nCheck mem_head : forall (T : eqType) (x : T) (s : seq T), x \\in x :: s.\nCheck mem_last : forall (T : eqType) (x : T) (s : seq T), last x s \\in x :: s.\n\nCheck mem_nth : forall (T : eqType) (x0 : T) (s : seq T) (n : nat),\n    n < size s -> nth x0 s n \\in s.\nCheck mem_take : forall (n0 : nat) (T : eqType) (s : seq T) (x : T),\n    x \\in take n0 s -> x \\in s.\nCheck mem_drop : forall (n0 : nat) (T : eqType) (s : seq T) (x : T),\n    x \\in drop n0 s -> x \\in s.\n\n(**\n# map と filter\n\n## 説明\n*)\n\nCompute map succn [::  1; 2; 3].            (* [:: 2; 3; 4] *)\nCompute [seq succn x | x <- [:: 1; 2; 3]].  (* [:: 2; 3; 4] *)\n\nCompute filter odd [:: 1; 2; 3].            (* [:: 1 3] *)\nCompute [seq x <- [:: 1;2;3] | odd x].      (* [:: 1 3] *)\n\n\n(**\nラムダ式を書かなくてすむ。\n *)\nCompute map (fun x => x + 2) [::  1; 2; 3]. (* [:: 3; 4; 5] *)\nCompute [seq x + 2 | x <- [:: 1; 2; 3]].    (* [:: 3; 4; 5] *)\n\nCompute filter (fun x => ~~ odd x) [:: 1; 2; 3]. (* [:: 2] *)\nCompute [seq x <- [:: 1;2;3] | ~~ odd x].        (* [:: 2] *)\n\n\n(**\nまとめてひとつの [seq ... ] で書けるわけではないので、ネストさせる必要がある。\nネストした例：\n *)\nCompute [seq x <- [seq succn x | x <- [:: 1; 2; 3]]  | odd x]. (* [:: 3] *)\nCompute [seq succn x | x <- [seq x <- [:: 1;2;3] | odd x]]. (* [:: 2; 4] *)\n\n\n(**\n## map と filter の補題\n\nmap と filter についてのいくつかの補題が証明されている。かなり便利である。\n *)\nCheck map_cons\n  : forall (T1 T2 : Type) (f : T1 -> T2) (x : T1) (s : seq T1),\n    [seq f i | i <- x :: s] = f x :: [seq f i | i <- s].\nCheck map_cat\n  : forall (T1 T2 : Type) (f : T1 -> T2) (s1 s2 : seq T1),\n    [seq f i | i <- s1 ++ s2] = [seq f i | i <- s1] ++ [seq f i | i <- s2].\nCheck map_rcons\n  : forall (T1 T2 : Type) (f : T1 -> T2) (s : seq T1) (x : T1),\n    [seq f i | i <- rcons s x] = rcons [seq f i | i <- s] (f x).\n      \n(**\n使用例：\n\nhttps://github.com/suharahiromichi/coq/blob/master/egison/ssr_egison_map.v\n *)\n\n(* filter_cons がないので、自分で証明してみる。 *)\nLemma filter_cons (T : Type) (a : pred T) (x : T) (s : seq T) :\n  [seq x <- x :: s | a x] =\n  (if a x then x :: [seq x <- s | a x] else [seq x <- s | a x]).\nProof.\n    by elim : s => //.\nQed.\n\nCheck filter_cat\n  : forall (T : Type) (a : pred T) (s1 s2 : seq T),\n    [seq x <- s1 ++ s2 | a x] = [seq x <- s1 | a x] ++ [seq x <- s2 | a x].\nCheck filter_rcons\n  : forall (T : Type) (a : pred T) (s : seq T) (x : T),\n    [seq x <- rcons s x | a x] =\n    (if a x then rcons [seq x <- s | a x] x else [seq x <- s | a x]).\n                                                       \n(**\n# foldl と foldr\n\nOCamil と引数の順番が異なることに注意してください。\n *)\nCheck @foldl : forall T R : Type, (R -> T -> R) -> R -> seq T -> R.\nCheck @foldr : forall T R : Type, (T -> R -> R) -> R -> seq T -> R.\n\n(**\n## foldl と foldr についての補題\n*)\nCheck foldr_cat : forall (T2 R : Type) (f : T2 -> R -> R) (z0 : R) (s1 s2 : seq T2),\n    foldr f z0 (s1 ++ s2) = foldr f (foldr f z0 s2) s1.\nCheck foldl_cat : forall (T R : Type) (f : R -> T -> R) (z : R) (s1 s2 : seq T),\n    foldl f z (s1 ++ s2) = foldl f (foldl f z s1) s2.\n(**\nfoldl と foldr は、rev すると同じになる。\n*)\nCheck foldl_rev : forall (T R : Type) (f : R -> T -> R) (z : R) (s : seq T),\n    foldl f z (rev s) = foldr (fun (x : T) (y : R) => f y x) z s.\n\n(**\n# 場合分け\n *)\nSection Case.\n  Variable T : Type.\n  \n(**\n## ディフォルトの場合分け\n\nゴールを ``[::]`` と ``x :: s`` に分ける。\n*)\n\n(**\nまず、リストの先頭の要素を取り除いた残りを返す関数 tail を定義する。\nnilならnilを返すものとする。\n*)\n  Definition tail (s : seq T) : seq T :=\n    match s with\n    | _ :: b => b\n    | [::] => [::]\n    end.\n  \n(**\n補題として、cons x s に対して、上記の関数を適用すると s が得られることを証明する。\n *)\n  Lemma tail_cons x s : tail (x :: s) = s.\n  Proof.\n    done.\n  Qed.\n  \n(**\n``size (tail s) < size s`` を証明したい。\n\ns = [::] だと ``size (tail s) = size s`` になるので、``1 <= size s`` の条件をつける。\n証明は、s を [::] と x :: s に場合分けして、前者の場合は前提矛盾で成立とする。\n*)\n  Lemma size_tail_1 s : 1 <= size s -> size (tail s) < size s.\n  Proof.\n    case: s => [| x s] Hs.          (* [::] と x :: s に分ける。 *)\n    \n    (* Hs : 0 < size [::] *)\n    (* Goal : size (tail [::]) < size [::]  ..... これは使わない。 *)\n    - rewrite /= in Hs.\n      done.        (* 前提 Hs は矛盾で、ゴールは無条件の成立する。  *)\n      \n    (* Hs : 0 < size (x :: s) ..... これは使わない。 *)\n    (* Goal : size (tail (x :: s)) < size (x :: s) *)\n    - rewrite tail_cons.                    (* 単に /= でもよい。 *)\n      rewrite size_cons.                    (* 単に /= でもよい。 *)\n      (* size s < (size s).+1 *)\n      done.\n  Qed.\n\n(**\n## 自然数について類似な例\n\n``n / n = 1`` を証明したいが、n = 0 なら ``0 / 0 = 0`` で成立しないので、\n``0 < n`` の条件をつける。\n *)\n  Lemma divNN (n : nat) : 0 < n -> n %/ n = 1.\n  Proof.\n    case: n => [| n ] Hn.\n    (* Hn : 0 < 0 *)\n    - done.                                 (* 前提矛盾 *)\n      \n    (* Hn : 0 < n.+1 *)\n    (* n.+1 %/ n.+1 = 1 *)\n    - rewrite -{1}[n.+1]mul1n.\n      rewrite -[1 * n.+1]addn0.\n      (* Goal : (1 * n.+1 + 0) %/ n.+1 = 1 *)\n      Check divnMDl : forall q m d : nat, 0 < d -> (q * d + m) %/ d = q + m %/ d.\n      rewrite divnMDl.\n      (* Goal : 1 + 0 %/ n.+1 = 1 *)\n      + done.\n      (* Goal : 0 < n.+1 *)\n      + done.                           (* 前提 Hn を使う。 *)        \n  Qed.\n  \n(**\n## lastP\n\nゴールを ``[::]`` と ``rcons s x`` に分ける。\n *)\n  \n(**\nまず、リストの最後の要素を取り除いた残りを返す関数 init を定義する。\nnilならnilを返すものとする。\n*)\n  Definition init (s : seq T) : (seq T) := rev (tail (rev s)).\n  \n(**\n補題として、rcons s x に対して、上記の関数を適用すると s が得られることを証明する。\n *)\n  Lemma init_rcons s x : init (rcons s x) = s.\n  Proof.\n      by rewrite /init rev_rcons /tail revK.\n  Qed.\n  \n(**\n``size (init s) < size s`` を証明したい。\n\ns = [::] だと ``size (init s) = size s`` になるので、``1 <= size s`` の条件をつける。\n証明は、s を [::] と rocns s x に場合分けして、前者の場合は前提矛盾で成立とする。\n*)\n  Lemma size_init_1 s : 1 <= size s -> size (init s) < size s.\n  Proof.\n    case/lastP: s => [| s x] Hs.    (* [::] と rcons s x に分ける。 *)\n\n    (* Hs : 0 < size [::] *)\n    (* Goal : size (init [::]) < size [::]   ..... これは使わない。 *)\n    - rewrite /= in Hs.                     (*  *)\n      done.        (* 前提 Hs は矛盾で、ゴールは無条件の成立する。  *)\n      \n    (* Hs : 0 < size (rcons s x) ..... これは使わない。 *)\n    (* Goal : size (init (rcons s x)) < size (rcons s x) *)\n    - rewrite init_rcons.\n      rewrite size_rcons.\n      (* size s < (size s).+1 *)\n      done.\n  Qed.\n  \n(**\n## 補足 : init' を直接定義した場合、カスタムインダクションを使う\n*)\n  Require Import Recdef.                      (* Function コマンド *)\n  Function init' (s : seq T) : (seq T) :=\n    match s with\n    | [::] => [::]\n    | [:: x] => [::]\n    | x' :: s => x' :: init' s\n    end.\n  Check init'_ind.\n  Check init'_equation.\n  \n  Lemma size_init'_1 s : 1 <= size s -> size (init' s) < size s.\n  Proof.\n    functional induction (init' s).\n    - done.\n    - done.\n    - move=> Hs /=.\n      (* Hs : 0 < size s0 -> size (init' s0) < size s0 *)\n      (* Goal : (size (init' s0)).+1 < (size s0).+1 *)\n      Check ltnS : forall m n : nat, (m < n.+1) = (m <= n).\n      (* ここで、 m := m.+1 のとき、 (m.+1 < n.+1) = (m.+1 <= n) = (m < n) となる。 *)\n      (* ltnSのマジックは、csm_4_3_x_eq0.v を参照のこと。 *)\n      rewrite ltnS.\n      (* Goal : size (init' s0) < size s0 *)\n      apply: IHl.\n      case: s0 y Hs.\n      + done.                               (* s0 が [::] *)\n      + move=> x s _ Hs.                    (* s0 が x :: s *)\n        done.\n  Qed.\nEnd Case.\n\nCompute tail [::].                          (* [::] *)\nCompute tail [:: 1; 2; 3].                  (* [:: 2; 3] *)\n\nCompute init [::].                          (* [::] *)\nCompute init [:: 1; 2; 3].                  (* [:: 1; 2] *)\n\nCompute init' [::].\nCompute init' [:: 1; 2; 3].\n\n(**\n# 特別な帰納法\n *)\n\n(**\n## last_ind\n\nrcons でする帰納法である。\n*)\nCheck last_ind\n  : forall (T : Type) (P : seq T -> Type),\n    P [::]                                  (* 帰納法の基底 *)\n    ->\n    (forall (s : seq T) (x : T), P s        (* 帰納法の仮定 *)\n                                 ->\n                                 P (rcons s x)) (* 証明するべきもの *)\n    ->\n    forall s : seq T, P s.                  (* 結論 *)\n\nSection FoldLeft.\n  Variables (T R : Type) (f : R -> T -> R).\n  \n(**\nfoldl と foldr が rev で、同じ結果になることを証明する。\n  *)\n  Lemma foldl_rev (z : R) (s : seq T) :\n    foldl f z (rev s) = foldr (fun x z => f z x) z s.\n  Proof.\n    (* elim/last_ind : s z => [| s x IHs] z. *)\n    move: s z.\n    apply: last_ind => [| s x IHs] z.\n    \n(*\nGoal : foldl f z (rev [::]) = foldr (fun z x => f x z) z [::]\n *)\n    - rewrite /=.                        (* 第3引数が [::] である。 *)\n      done.\n      \n    (* \nIHs : forall z : R, foldl f z (rev s) = foldr (fun z x => f x z) z s.\nGoal : foldl f z (rev (rcons s x)) = foldr (fun z x => f x z) z (rcons s x)\n\n``foldl f z (rev s) = ... `` であると仮定して、証明したいのは、\n``foldl f z (rev (rcons s x)) = ...`` であるが、左辺の x を第3引数の外に出すと、\n``foldl (f z x) s = ... `` となる。これが成立することを証明する。\n     *)\n    (* ゴールの左辺 *)\n    rewrite rev_rcons.\n    rewrite [LHS]/=.\n    (* ゴールの右辺 *)\n    rewrite -cats1.\n    rewrite foldr_cat.\n    rewrite [RHS]/=.\n    rewrite -IHs.\n    done.\n  Qed.\nEnd FoldLeft.\n\n(**\n## map2 の帰納法\n\nふたつのリストを引数にとる場合の帰納法である。\n*)\nCheck @seq_ind2\n  : forall (S T : Type) (P : seq S -> seq T -> Type),\n    P [::] [::]                             (* 帰納法の基底 *)\n    ->\n    (forall (x : S) (y : T) (s : seq S) (t : seq T), (* 帰納法の仮定 *)\n        size s = size t -> P s t\n        (* ^^^^^^^^^^^  *)\n        ->\n        P (x :: s) (y :: t))                (* 証明するべきもの *)\n    ->\n    forall (s : seq S) (t : seq T), size s = size t -> P s t. (* 結論 *)\n\n(**\n古い版では seq2_ind だった。\nseq_ind2 になったときに帰納法の仮定に寸法が追加され、「弱まった」が使い易くなった。\nただし、今回は仮定は使っていません。\n *)\nLemma seq2_ind T1 T2 (P : seq T1 -> seq T2 -> Type) :\n  P [::] [::] -> (forall x1 x2 s1 s2, P s1 s2 -> P (x1 :: s1) (x2 :: s2)) ->\n  forall s1 s2, size s1 = size s2 -> P s1 s2.\nProof.\n    by move=> Pnil Pcons; elim=> [|x s IHs] [] //= x2 s2 [] /IHs/Pcons.\n\n  Restart.\n  move=> Pnil Pcons s1 s2.\n  elim: s1 s2 => [|x s IHs].\n  - move=> [] //=.\n  - move=> [] //=.\n    move=> x2 s2 [].\n    move/IHs/Pcons.                  (* スタックトップにapplyする。 *)\n    done.\nQed.\n\nLemma seq2_ind T1 T2 (P : seq T1 -> seq T2 -> Type) :\n  P [::] [::] -> (forall x1 x2 s1 s2, P s1 s2 -> P (x1 :: s1) (x2 :: s2)) ->\n  forall s1 s2, size s1 = size s2 -> P s1 s2.\nProof. by move=> Pnil Pcons; elim=> [|x s IHs] [] //= x2 s2 [] /IHs/Pcons. Qed.\n\nSection Map2_Mask.\n  Variable T : Type.\n(**\n### mask 関数の証明\n\nseq bool で seq T をマスクする mask 関数に関する証明に使う。\n *)\n  Compute mask [:: true; false; true] [:: 1; 2; 3]. (* [:: 1; 3] *)\n  \n(**\n#### size_mask\n*)\n  Goal forall (m : seq bool) (s : seq T),   (* size_mask *)\n      size m = size s -> size (mask m s) = count id m. (* true の数を数える。 *)\n  Proof.\n    apply: seq_ind2 => // x m s t /= Hs IHs.\n    rewrite -IHs.\n    case: ifP => Hx /=.\n    - rewrite IHs.\n      done.\n    - rewrite add0n.\n      done.\n  Qed.\n\n(**\n#### mask_cat.\n*)\n  Goal forall (m1 m2 : seq bool) (s1 s2 : seq T), (* mask_cat *)\n      size m1 = size s1 -> mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2.\n  Proof.\n    move=> m1 m2 s1 s2.\n    move: m1 s1.\n    (* ゴールのスタックに、m1 s1 と size を残すことに注意！ *)\n    apply: seq_ind2.\n    - by move=> /=.\n    - move=> /=.\n      move=> x y m s /= Hs IHs.\n      (* ``if x then .... else ...`` の then と else で場合分けする。  *)\n      case: ifP => Hx.\n      + rewrite IHs.                        (* x = true の場合 *)\n        done.\n      + rewrite IHs.                        (* x = false の場合 *)\n        done.\n  Qed.\nEnd Map2_Mask.\n\n(**\n## map2 関数の定義\n\nMathComp には map2 はないので定義してみる。\n*)\nSection Map2_Def.\n  Variable T : Type.\n  \n  Fixpoint map2 op (s1 s2 : seq T) : seq T :=\n    match s1, s2 with\n    | [::], _ => [::]\n    | _, [::] => [::]\n    | (x1 :: s1), (x2 :: s2) => (op x1 x2) :: map2 op s1 s2\n    end.\nEnd Map2_Def.\n\nCheck map2 addn.\nCompute map2 addn [:: 0; 1; 1; 2; 3; 5; 8] [:: 1; 1; 2; 3; 5; 8].\n\nSection Map2_Lemma.\n  Variable T : Type.\n(**\n### map2_cons\n*)  \n  Lemma map2_cons f (x1 x2 : T) (s1 s2 : seq T) :\n    map2 f (x1 :: s1) (x2 :: s2) = f x1 x2 :: map2 f s1 s2.\n  Proof.\n      by [].\n  Qed.\n  \n(**\n### map2_cat\n*)  \n  Lemma map2_cat f (s11 s12 s21 s22 : seq T) :\n    size s11 = size s21 -> \n    map2 f (s11 ++ s12) (s21 ++ s22) = map2 f s11 s21 ++ map2 f s12 s22.\n  Proof.\n    move: s11 s21.\n    (* ゴールのスタックに、s11 s21 と size を残すことに注意！ *)\n    apply: seq_ind2.\n    - move=> /=.\n      done.\n    - move=> /=.\n      move=> x1 x2 s11 s21 Hsize IHs.\n      rewrite IHs.\n      done.\n  Qed.    \nEnd Map2_Lemma.\n\n(**\n## alt_list_ind\n\nhttps://github.com/suharahiromichi/coq/blob/master/ssr/ssr_palindrome.v\n\n回文の証明で使用した cons と rcons でする帰納法の例：\n\nalt_list_ind : \n    P [::] ->\n    (forall (x : X), P [:: x]) ->\n    (forall (l : seq X), P l -> forall (x y : X), P (x :: (l ++ [:: y]))) ->\n    forall (ln : seq X), P ln.\n*)\n\n(**\n# 演習の答え\n*)\n\nSection RconsA.\n  Variable T : Type.\n  \n(**\n（演習）両者が同値であることを証明してください。\n*)\n  Goal forall (s : seq T) (z : T), rcons s z = rcons' s z.\n  Proof.\n    move=> s z.\n    elim: s => //.\n    move=> a s IH /=.\n      by rewrite IH /rcons' /=.\n\n    Restart.\n    move=> s z.\n      by rewrite /rcons' cats1.             (* 実はMathCompに補題がある。*)\n  Qed.\nEnd RconsA.\n\nSection ReverseA.\n  Variable A : Type.\n\n(**\n## （演習）末尾再帰ではない reverseと rev の同値を証明する。\n *)\n  Goal forall (s : seq A), rev s = reverse s.\n  Proof.\n    elim => // a s IHs /=.\n    rewrite -IHs.\n    rewrite -rev1 -rev_cat /=.\n    done.\n  Qed.\n\n(**\n## rcons を使使って reverse' を定義する場合：\n *)\n  Fixpoint reverse' (xs : seq A) :=\n  match xs with\n  | nil => nil\n  | x :: xs' =>\n    rcons (reverse' xs') x\n  end.\n  \n  Goal forall (s : seq A), rev s = reverse' s.\n  Proof.\n    elim/last_ind => // a s IHs.\n    (* rev の中に rcons が出現するので、この場合が簡単にならない。 *)\n    Undo 1.\n    \n    elim => // a s IHs /=.\n    rewrite -IHs.\n    rewrite /rev.\n    rewrite !catrevE !rev_cons !cats0.\n    done.\n  Qed.\nEnd ReverseA.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/csm/csm_4_4_seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064587, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7098711885716289}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (x : natural) (y : natural)\n  : natural := mult x (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj226_coqofml_9aQ4Bn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7098206762148299}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf2 : natural) : natural :=\n  plus y (plus (Succ x) lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj182_coqofml_ShYgQZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7098201162521462}}
{"text": "(* Author: Christian Doczkal *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq fintype bigop path choice finset fingraph.\nRequire Import Relations.\nRequire Import tactics.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** * A least fixed point operator for finType *)\n\nLemma iter_fix T (F : T -> T) x k n : \n  iter k F x = iter k.+1 F x -> k <= n -> iter n F x = iter n.+1 F x.\nProof.\n  move => e. elim: n. rewrite leqn0. by move/eqP<-.\n  move => n IH. rewrite leq_eqVlt; case/orP; first by move/eqP<-.\n  move/IH => /= IHe. by rewrite -!IHe.\nQed.\n\nSection FixPoint.\n  Variable T :finType.\n  Definition set_op := {set T} -> {set T}.\n  Definition mono (F : set_op)  := forall p q : {set T} , p \\subset q -> F p \\subset F q.\n\n  Variable F : {set T} -> {set T}.\n  Hypothesis monoF : mono F.\n\n  Definition lfp := iter #|T|.+1 F set0.\n\n  Lemma lfp_ind (P : {set T} -> Type) : P set0 -> (forall s , P s -> P (F s)) -> P lfp.\n  Proof.\n    move => P0 Pn. rewrite /lfp. set n := #|T|.+1. elim: n => //= n. exact: Pn.\n  Qed.\n\n  Lemma iterFsub n : iter n F set0 \\subset iter n.+1 F set0.\n  Proof.\n    elim: n => //=; first by rewrite sub0set.\n    move => n IH /=. by apply: monoF.\n  Qed.\n\n  Lemma iterFsubn m n : m <= n -> iter m F set0 \\subset iter n F set0.\n  Proof.\n    elim : n; first by rewrite leqn0 ; move/eqP->.\n    move => n IH. rewrite leq_eqVlt; case/orP; first by move/eqP<-.\n    move/IH => /= IHe. apply: subset_trans; first apply IHe. exact:iterFsub.\n  Qed.\n \n  Lemma lfpE : lfp = F lfp.\n  Proof.\n    have: ~~ [ forall m : 'I_#|T|.+1 , iter m F set0 \\proper iter m.+1 F set0 ].\n      apply/negP => /forallP H.\n      have P : forall n : 'I_#|T|.+1 , exists x : T , x \\in iter n.+1 F set0 :\\: iter n F set0.\n        move => n ; move : (H n). case/properP => _ [x x1 x2]. exists x. by rewrite in_setD x1 x2.\n      pose i (o : 'I_#|T|.+1) : T := xchoose (P o).\n      have inj_i : injective i. \n        move => o o'. rewrite /i => e. move : (xchooseP (P o)) (xchooseP (P o')).\n        rewrite e {e}. set x := xchoose _. move : o o' x => [n pn] [m pm] x.\n        rewrite !in_setD /=. case/andP => Hn1 Hn2. case/andP => Hm1 Hm2.\n        case (ltngtP n m); last by move/eqP => e'; apply/eqP.\n        - move => /iterFsubn /subsetP /(_ x Hn2). by rewrite (negbTE Hm1).\n        - move => /iterFsubn /subsetP /(_ x Hm2). by rewrite (negbTE Hn1).\n      move : (max_card (fun x => x \\in codom i)). by rewrite (card_codom inj_i) /= !card_ord ltnn. \n    rewrite negb_forall. case/existsP => x H.\n    have A : iter x F set0 = iter x.+1 F set0. \n      apply/eqP. by rewrite eqEproper iterFsub /= H.\n    apply : iter_fix; first apply A. by case:x {H A} => *; auto.\n  Qed.\nEnd FixPoint.\n\n", "meta": {"author": "YaccConstructor", "repo": "YC_in_Coq", "sha": "d94a9ec10d532b86ae4f48871c38369f9ce5f1d8", "save_path": "github-repos/coq/YaccConstructor-YC_in_Coq", "path": "github-repos/coq/YaccConstructor-YC_in_Coq/YC_in_Coq-d94a9ec10d532b86ae4f48871c38369f9ce5f1d8/aut/base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7098069017425107}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom hanoi Require Import ghanoi gdist.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(******************************************************************************)\n(*                                                                            *)\n(*              Generalised Hanoi Problem with only 4 pegs                    *)\n(*                                                                            *)\n(******************************************************************************)\n\n\nSection GHanoi4.\n\n(*****************************************************************************)\n(*  The pegs are the four elements of 'I_4                                   *)\n(*****************************************************************************)\n\nImplicit Type p : peg 4.\n\nLet peg0 : peg 4 := ord0.\nLet peg1 : peg 4 := inord 1.\nLet peg2 : peg 4 := inord 2.\nLet peg3 : peg 4 := inord 3.\n\nLemma peg4E p : [\\/ p = peg0, p = peg1, p = peg2 | p = peg3].\nProof.\nby case: p => [] [|[|[|[|]]]] // H; \n   [apply: Or41|apply: Or42|apply: Or43|apply: Or44];\n   apply/val_eqP; rewrite //= inordK.\nQed.\n\nLtac comp2_tac peg2 peg3 :=\n let p := fresh \"p\" in\n exists peg2; exists peg3; repeat split; \n      try (by apply/eqP/val_eqP; rewrite /= !inordK);\n    move=> p; case: (peg4E p)=>->;\n    ((by apply/Or41/val_eqP; rewrite /= ?inordK) ||\n     (by apply/Or42/val_eqP; rewrite /= ?inordK) ||\n     (by apply/Or43/val_eqP; rewrite /= ?inordK) ||\n     (by apply/Or44/val_eqP; rewrite /= ?inordK)).\n     \n\nLemma peg4comp2 p1 p2 :\n  p1 != p2 -> exists p3, exists p4,\n    [/\\ [/\\ p4 != p3, p4 != p2 & p4 != p1],\n        [/\\ p3 != p2 & p3 != p1] & \n        (forall p, [\\/ p = p1, p = p2, p = p3 | p = p4])].\nProof.\ncase: (peg4E p1)=>->; case: (peg4E p2)=>->; rewrite ?eqxx // => _.\ncomp2_tac peg2 peg3. \ncomp2_tac peg1 peg3.\ncomp2_tac peg1 peg2.\ncomp2_tac peg2 peg3.\ncomp2_tac peg0 peg3.\ncomp2_tac peg0 peg2.\ncomp2_tac peg1 peg3.\ncomp2_tac peg0 peg3.\ncomp2_tac peg0 peg1.\ncomp2_tac peg1 peg2.\ncomp2_tac peg0 peg2.\ncomp2_tac peg0 peg1.\nQed.\n\nLtac comp3_tac peg0 :=\nlet p := fresh \"p\" in\nexists peg0; (repeat split) => [|||p];\n     try (apply/eqP/val_eqP; rewrite /= ?inordK //);\ncase: (peg4E p)=>->;\n    ((by apply/Or41/val_eqP; rewrite /= ?inordK) ||\n     (by apply/Or42/val_eqP; rewrite /= ?inordK) ||\n     (by apply/Or43/val_eqP; rewrite /= ?inordK) ||\n     (by apply/Or44/val_eqP; rewrite /= ?inordK)).\n\nLemma peg4comp3 p1 p2 p3 :\n  p1 != p2 -> p1 != p3 -> p2 != p3 -> \n  exists p4, [/\\ p4 != p3, p4 != p2 & p4 != p1] /\\\n        (forall p, [\\/ p = p1, p = p2, p = p3 | p = p4]).\nProof.\ncase: (peg4E p1)=>->; case: (peg4E p2)=>->; \ncase: (peg4E p3)=>->; rewrite ?eqxx // => _ _ _;\n(comp3_tac peg0 || comp3_tac peg1 || comp3_tac peg2 || comp3_tac peg3).\nQed.\n\nEnd GHanoi4.", "meta": {"author": "thery", "repo": "hanoi", "sha": "257788b06e7a724e023e2aee2122cb1dcc5c702d", "save_path": "github-repos/coq/thery-hanoi", "path": "github-repos/coq/thery-hanoi/hanoi-257788b06e7a724e023e2aee2122cb1dcc5c702d/ghanoi4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7098068832139381}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Lia Wellfounded List Extraction.\n\nFrom Undecidability.Shared.Libs.DLW.Wf Require Import acc_irr.\n\nSet Implicit Arguments.\n\nSection measure_rect.\n\n  Variable (X : Type) (m : X -> nat) (P : X -> Type).\n\n  Hypothesis F : forall x, (forall x', m x' < m x -> P x') -> P x.\n\n  Arguments F : clear implicits.\n\n  Let R x y := m x < m y.\n\n  (* R is WF when all elements are accessible *)\n\n  Let Rwf : forall x : X, Acc R x.\n  Proof.\n    apply wf_inverse_image with (f := m), lt_wf.\n  Qed.\n\n  (* Structural decrease on the Acc predicate and no \n      singleton elimination here because the Acc predicated\n      is pattern matched (by destruct) in Prop context *)\n\n  Let Fix_F : forall x : X, Acc R x -> P x.\n  Proof.\n    refine(\n      fix Fix_F x (H : Acc R x) { struct H } := \n         F x (fun x' (H' : R x' x) => Fix_F x' _)\n    ).\n    destruct H as [ G ].\n    apply G. (* structural decrease here *)\n    trivial. \n  Defined.\n\n  (* To evaluate @Fix_F x A, the recursive argument must reduce to a\n      term headed with an inductive constructor *)\n\n  Let Fix_F_fix x A :\n        @Fix_F x A = F x (fun y H => Fix_F (Acc_inv A H)).\n  Proof. destruct A; reflexivity. Qed.\n\n  Definition measure_rect x : P x := Fix_F (Rwf x).\n\n  (* To establish the fixpoint equation for measure_rect, we need\n      to assume that the functional F is extensional because we do not\n      use the FunExt axiom *)\n\n  Hypothesis F_ext : forall x f g, (forall y H, f y H = g y H) -> F x f = F x g.\n\n  (* Another proof method here that in StdLib, using the characterisation\n      of Acc irrelevant functionals *)\n\n  Let Fix_F_Acc_irr : forall x f g, @Fix_F x f = Fix_F g.\n  Proof using F_ext.\n    apply Acc_irrelevance.\n    intros; apply F_ext; auto.\n  Qed.\n\n  Theorem measure_rect_fix x : \n          measure_rect x = @F x (fun y _ => measure_rect y).\n  Proof using F_ext.\n    unfold measure_rect; rewrite Fix_F_fix.\n    apply F_ext.\n    intros; apply Fix_F_Acc_irr.\n  Qed.\n\nEnd measure_rect.\n\nTactic Notation \"induction\" \"on\" hyp(x) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n   pattern x; revert x; apply measure_rect with (m := fun x => f); intros x IH.\n\nExtraction Inline measure_rect.\n\nSection measure_double_rect.\n\n  Variable (X Y : Type) (m : X -> Y -> nat) (P : X -> Y -> Type).\n\n  Hypothesis F : (forall x y, (forall x' y', m x' y' < m x y -> P x' y') -> P x y).\n\n  Let m' (c : X * Y) := match c with (x,y) => m x y end.\n\n  Let R c d := m' c < m' d.\n\n  Let Rwf : well_founded R.\n  Proof.\n    apply wf_inverse_image with (f := m'), lt_wf.\n  Qed.\n\n  Section measure_double_rect_paired.\n\n    Let Q c := match c with (x,y) => P x y end.\n\n    Theorem measure_double_rect_paired x y : P x y.\n    Proof using F.\n      change (Q (x,y)).\n      generalize (x,y); clear x y; intros c.\n\n      induction on c as IH with measure (m' c).\n      destruct c as (x,y); apply F.\n      intros ? ?; apply (IH (_,_)). \n    Defined.\n\n  End measure_double_rect_paired.\n\n  Section measure_double_rect.\n\n    Let Fix_F_2 : forall x y, Acc R (x,y) -> P x y.\n    Proof.\n      refine (fix Fix_F_2 x y H { struct H } := \n           @F x y (fun x' y' H' => Fix_F_2 x' y' _)\n      ).\n      destruct H as [ H ]; unfold R in H at 1. \n      apply H. (* structural decrease here *)\n      apply H'. \n    Defined.\n\n    Let Fix_F_2_fix x y H :\n        @Fix_F_2 x y H = F (fun x' y' H' => Fix_F_2 (@Acc_inv _ _ _ H (x',y') H')).\n    Proof. destruct H; reflexivity. Qed.\n\n    Definition measure_double_rect x y : P x y := Fix_F_2 (Rwf (_,_)).\n\n    Hypothesis F_ext : forall x y f g, (forall x' y' H, f x' y' H = g x' y' H) \n                                      -> @F x y f = F g.\n\n    Let Fix_F_2_paired c (A : Acc R c) : P (fst c) (snd c).\n    Proof. destruct c; simpl; apply Fix_F_2; trivial. Defined.\n\n    Let Fix_F_2_paired_Acc_irr : forall c f g, @Fix_F_2_paired c f \n                                              = Fix_F_2_paired   g.\n    Proof.\n       apply Acc_irrelevance.\n       intros (x,y) f g IH; apply F_ext.\n       intros x' y' ?; apply (@IH (x',y')).\n    Qed.\n\n    Let Fix_F_2_Acc_irr x y f g : @Fix_F_2 x y f = Fix_F_2 g.\n    Proof.\n      intros; apply (@Fix_F_2_paired_Acc_irr (x,y)); trivial.\n    Qed.\n\n    Theorem measure_double_rect_fix x y : \n             measure_double_rect x y = @F x y (fun x' y' _ => measure_double_rect x' y').\n    Proof using F_ext.\n      unfold measure_double_rect; rewrite Fix_F_2_fix.\n      apply F_ext.\n      intros; apply Fix_F_2_Acc_irr.\n    Qed.\n\n  End measure_double_rect.\n\nEnd measure_double_rect.\n\nTactic Notation \"paired\" \"induction\" \"on\" hyp(x) hyp(y) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n   pattern x, y; revert x y; apply measure_double_rect_paired with (m := fun x y => f); intros x y IH.\n\nTactic Notation \"induction\" \"on\" hyp(x) hyp(y) \"as\" ident(IH) \"with\" \"measure\" uconstr(f) :=\n   pattern x, y; revert x y; apply measure_double_rect with (m := fun x y => f); intros x y IH.\n\nExtraction Inline measure_double_rect measure_double_rect_paired.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/Shared/Libs/DLW/Wf/measure_ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7098068798278631}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrfun ssrbool eqtype.\nRequire Import BinNat.\nRequire BinPos Ndec.\nRequire Export Ring.\n\n(******************************************************************************)\n(* A version of arithmetic on nat (natural numbers) that is better suited to  *)\n(* small scale reflection than the Coq Arith library. It contains an          *)\n(* extensive equational theory (including, e.g., the AGM inequality), as well *)\n(* as support for the ring tactic, and congruence tactics.                    *)\n(*   The following operations and notations are provided:                     *)\n(*                                                                            *)\n(*   successor and predecessor                                                *)\n(*     n.+1, n.+2, n.+3, n.+4 and n.-1, n.-2                                  *)\n(*     this frees the names \"S\" and \"pred\"                                    *)\n(*                                                                            *)\n(*   basic arithmetic                                                         *)\n(*     m + n, m - n, m * n                                                    *)\n(*   Important: m - n denotes TRUNCATED subtraction: m - n = 0 if m <= n.     *)\n(*   The definitions use the nosimpl tag to prevent undesirable computation   *)\n(*   computation during simplification, but remain compatible with the ones   *)\n(*   provided in the Coq.Init.Peano prelude.                                  *)\n(*     For computation, a module NatTrec rebinds all arithmetic notations     *)\n(*   to less convenient but also less inefficient tail-recursive functions;   *)\n(*   the auxiliary functions used by these versions are flagged with %Nrec.   *)\n(*     Also, there is support for input and output of large nat values.       *)\n(*       Num 3 082 241 inputs the number 3082241                              *)\n(*         [Num of n]  outputs the value n                                    *)\n(*   There are coercions num >-> BinNat.N >-> nat; ssrnat rebinds the scope   *)\n(*   delimiter for BinNat.N to %num, as it uses the shorter %N for its own    *)\n(*   notations (Peano notations are flagged with %coq_nat).                   *)\n(*                                                                            *)\n(*   doubling, halving, and parity                                            *)\n(*      n.*2, n./2, odd n, uphalf n,  with uphalf n = n.+1./2                 *)\n(*   bool coerces to nat so we can write, e.g., n = odd n + n./2.*2.          *)\n(*                                                                            *)\n(*   iteration                                                                *)\n(*             iter n f x0  == f ( .. (f x0))                                 *)\n(*             iteri n g x0 == g n.-1 (g ... (g 0 x0))                        *)\n(*         iterop n op x x0 == op x (... op x x) (n x's) or x0 if n = 0       *)\n(*                                                                            *)\n(*   exponentiation, factorial                                                *)\n(*        m ^ n, n`!                                                          *)\n(*        m ^ 1 is convertible to m, and m ^ 2 to m * m                       *)\n(*                                                                            *)\n(*   comparison                                                               *)\n(*      m <= n, m < n, m >= n, m > n, m == n, m <= n <= p, etc.,              *)\n(*   comparisons are BOOLEAN operators, and m == n is the generic eqType      *)\n(*   operation.                                                               *)\n(*     Most compatibility lemmas are stated as boolean equalities; this keeps *)\n(*   the size of the library down. All the inequalities refer to the same     *)\n(*   constant \"leq\"; in particular m < n is identical to m.+1 <= n.           *)\n(*                                                                            *)\n(*   conditionally strict inequality `leqif'                                  *)\n(*      m <= n ?= iff condition   ==   (m <= n) and ((m == n) = condition)    *)\n(*   This is actually a pair of boolean equalities, so rewriting with an      *)\n(*   `leqif' lemma can affect several kinds of comparison. The transitivity   *)\n(*   lemma for leqif aggregates the conditions, allowing for arguments of     *)\n(*   the form ``m <= n <= p <= m, so equality holds throughout''.             *)\n(*                                                                            *)\n(*   maximum and minimum                                                      *)\n(*      maxn m n, minn m n                                                    *)\n(*   Note that maxn m n = m + (m - n), due to the truncating subtraction.     *)\n(*   Absolute difference (linear distance) between nats is defined in the int *)\n(*   library (in the int.IntDist sublibrary), with the syntax `|m - n|. The   *)\n(*   '-' in this notation is the signed integer difference.                   *)\n(*                                                                            *)\n(*   countable choice                                                         *)\n(*     ex_minn : forall P : pred nat, (exists n, P n) -> nat                  *)\n(*   This returns the smallest n such that P n holds.                         *)\n(*     ex_maxn : forall (P : pred nat) m,                                     *)\n(*        (exists n, P n) -> (forall n, P n -> n <= m) -> nat                 *)\n(*   This returns the largest n such that P n holds (given an explicit upper  *)\n(*   bound).                                                                  *)\n(*                                                                            *)\n(*  This file adds the following suffix conventions to those documented in    *)\n(* ssrbool.v and eqtype.v:                                                    *)\n(*   A (infix) -- conjunction, as in                                          *)\n(*      ltn_neqAle : (m < n) = (m != n) && (m <= n).                          *)\n(*   B -- subtraction, as in subBn : (m - n) - p = m - (n + p).               *)\n(*   D -- addition, as in mulnDl : (m + n) * p = m * p + n * p.               *)\n(*   M -- multiplication, as in expnMn : (m * n) ^ p = m ^ p * n ^ p.         *)\n(*   p (prefix) -- positive, as in                                            *)\n(*      eqn_pmul2l : m > 0 -> (m * n1 == m * n2) = (n1 == n2).                *)\n(*   P  -- greater than 1, as in                                              *)\n(*      ltn_Pmull : 1 < n -> 0 < m -> m < n * m.                              *)\n(*   S -- successor, as in addSn : n.+1 + m = (n + m).+1.                     *)\n(*   V (infix) -- disjunction, as in                                          *)\n(*      leq_eqVlt : (m <= n) = (m == n) || (m < n).                           *)\n(*   X - exponentiation, as in lognX : logn p (m ^ n) = logn p m * n in       *)\n(*         file prime.v (the suffix is not used in ths file).                 *)\n(* Suffixes that abbreviate operations (D, B, M and X) are used to abbreviate *)\n(* second-rank operations in equational lemma names that describe left-hand   *)\n(* sides (e.g., mulnDl); they are not used to abbreviate the main operation   *)\n(* of relational lemmas (e.g., leq_add2l).                                    *)\n(*   For the asymmetrical exponentiation operator expn (m ^ n) a right suffix *)\n(* indicates an operation on the exponent, e.g., expnM : m ^ (n1 * n2) = ...; *)\n(* a trailing \"n\" is used to indicate the left operand, e.g.,                 *)\n(* expnMn : (m1 * m2) ^ n = ... The operands of other operators are selected  *)\n(* using the l/r suffixes.                                                    *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Declare legacy Arith operators in new scope. *)\n\nDelimit Scope coq_nat_scope with coq_nat.\n\nNotation \"m + n\" := (plus m n) : coq_nat_scope.\nNotation \"m - n\" := (minus m n) : coq_nat_scope.\nNotation \"m * n\" := (mult m n) : coq_nat_scope.\nNotation \"m <= n\" := (le m n) : coq_nat_scope.\nNotation \"m < n\" := (lt m n) : coq_nat_scope.\nNotation \"m >= n\" := (ge m n) : coq_nat_scope.\nNotation \"m > n\" := (gt m n) : coq_nat_scope.\n\n(* Rebind scope delimiters, reserving a scope for the \"recursive\",     *)\n(* i.e., unprotected version of operators.                             *)\n\nDelimit Scope N_scope with num.\nDelimit Scope nat_scope with N.\nDelimit Scope nat_rec_scope with Nrec.\n\n(* Postfix notation for the successor and predecessor functions.  *)\n(* SSreflect uses \"pred\" for the generic predicate type, and S as *)\n(* a local bound variable.                                        *)\n\nNotation succn := Datatypes.S.\nNotation predn := Peano.pred.\n\nNotation \"n .+1\" := (succn n) (at level 2, left associativity,\n  format \"n .+1\") : nat_scope.\nNotation \"n .+2\" := n.+1.+1 (at level 2, left associativity,\n  format \"n .+2\") : nat_scope.\nNotation \"n .+3\" := n.+2.+1 (at level 2, left associativity,\n  format \"n .+3\") : nat_scope.\nNotation \"n .+4\" := n.+2.+2 (at level 2, left associativity,\n  format \"n .+4\") : nat_scope.\n\nNotation \"n .-1\" := (predn n) (at level 2, left associativity,\n  format \"n .-1\") : nat_scope.\nNotation \"n .-2\" := n.-1.-1 (at level 2, left associativity,\n  format \"n .-2\") : nat_scope.\n\nLemma succnK : cancel succn predn. Proof. by []. Qed.\nLemma succn_inj : injective succn. Proof. by move=> n m []. Qed.\n\n(* Predeclare postfix doubling/halving operators. *)\n\nReserved Notation \"n .*2\" (at level 2, format \"n .*2\").\nReserved Notation \"n ./2\" (at level 2, format \"n ./2\").\n\n(* Canonical comparison and eqType for nat.                                *)\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\nLemma eqnP : Equality.axiom eqn.\nProof.\nmove=> n m; apply: (iffP idP) => [|<-]; last by elim n.\nby elim: n m => [|n IHn] [|m] //= /IHn->.\nQed.\n\nCanonical nat_eqMixin := EqMixin eqnP.\nCanonical nat_eqType := Eval hnf in EqType nat nat_eqMixin.\n\nArguments eqn !m !n.\nArguments eqnP {x y}.\n\nLemma eqnE : eqn = eq_op. Proof. by []. Qed.\n\nLemma eqSS m n : (m.+1 == n.+1) = (m == n). Proof. by []. Qed.\n\nLemma nat_irrelevance (x y : nat) (E E' : x = y) : E = E'.\nProof. exact: eq_irrelevance. Qed.\n\n(* Protected addition, with a more systematic set of lemmas.                *)\n\nDefinition addn_rec := plus.\nNotation \"m + n\" := (addn_rec m n) : nat_rec_scope.\n\nDefinition addn := nosimpl addn_rec.\nNotation \"m + n\" := (addn m n) : nat_scope.\n\nLemma addnE : addn = addn_rec. Proof. by []. Qed.\n\nLemma plusE : plus = addn. Proof. by []. Qed.\n\nLemma add0n : left_id 0 addn.            Proof. by []. Qed.\nLemma addSn m n : m.+1 + n = (m + n).+1. Proof. by []. Qed.\nLemma add1n n : 1 + n = n.+1.            Proof. by []. Qed.\n\nLemma addn0 : right_id 0 addn. Proof. by move=> n; apply/eqP; elim: n. Qed.\n\nLemma addnS m n : m + n.+1 = (m + n).+1. Proof. by elim: m. Qed.\n\nLemma addSnnS m n : m.+1 + n = m + n.+1. Proof. by rewrite addnS. Qed.\n\nLemma addnCA : left_commutative addn.\nProof. by move=> m n p; elim: m => //= m; rewrite addnS => <-. Qed.\n\nLemma addnC : commutative addn.\nProof. by move=> m n; rewrite -{1}[n]addn0 addnCA addn0. Qed.\n\nLemma addn1 n : n + 1 = n.+1. Proof. by rewrite addnC. Qed.\n\nLemma addnA : associative addn.\nProof. by move=> m n p; rewrite (addnC n) addnCA addnC. Qed.\n\nLemma addnAC : right_commutative addn.\nProof. by move=> m n p; rewrite -!addnA (addnC n). Qed.\n\nLemma addnACA : interchange addn addn.\nProof. by move=> m n p q; rewrite -!addnA (addnCA n). Qed.\n\nLemma addn_eq0 m n : (m + n == 0) = (m == 0) && (n == 0).\nProof. by case: m; case: n. Qed.\n\nLemma eqn_add2l p m n : (p + m == p + n) = (m == n).\nProof. by elim: p. Qed.\n\nLemma eqn_add2r p m n : (m + p == n + p) = (m == n).\nProof. by rewrite -!(addnC p) eqn_add2l. Qed.\n\nLemma addnI : right_injective addn.\nProof. by move=> p m n Heq; apply: eqP; rewrite -(eqn_add2l p) Heq eqxx. Qed.\n\nLemma addIn : left_injective addn.\nProof. move=> p m n; rewrite -!(addnC p); apply addnI. Qed.\n\nLemma addn2 m : m + 2 = m.+2. Proof. by rewrite addnC. Qed.\nLemma add2n m : 2 + m = m.+2. Proof. by []. Qed.\nLemma addn3 m : m + 3 = m.+3. Proof. by rewrite addnC. Qed.\nLemma add3n m : 3 + m = m.+3. Proof. by []. Qed.\nLemma addn4 m : m + 4 = m.+4. Proof. by rewrite addnC. Qed.\nLemma add4n m : 4 + m = m.+4. Proof. by []. Qed.\n\n(* Protected, structurally decreasing subtraction, and basic lemmas.  *)\n(* Further properties depend on ordering conditions.                  *)\n\nDefinition subn_rec := minus.\nNotation \"m - n\" := (subn_rec m n) : nat_rec_scope.\n\nDefinition subn := nosimpl subn_rec.\nNotation \"m - n\" := (subn m n) : nat_scope.\n\nLemma subnE : subn = subn_rec. Proof. by []. Qed.\nLemma minusE : minus = subn.   Proof. by []. Qed.\n\nLemma sub0n : left_zero 0 subn.    Proof. by []. Qed.\nLemma subn0 : right_id 0 subn.   Proof. by case. Qed.\nLemma subnn : self_inverse 0 subn. Proof. by elim. Qed.\n\nLemma subSS n m : m.+1 - n.+1 = m - n. Proof. by []. Qed.\nLemma subn1 n : n - 1 = n.-1.          Proof. by case: n => [|[]]. Qed.\nLemma subn2 n : (n - 2)%N = n.-2.      Proof. by case: n => [|[|[]]]. Qed.\n\nLemma subnDl p m n : (p + m) - (p + n) = m - n.\nProof. by elim: p. Qed.\n\nLemma subnDr p m n : (m + p) - (n + p) = m - n.\nProof. by rewrite -!(addnC p) subnDl. Qed.\n\nLemma addKn n : cancel (addn n) (subn^~ n).\nProof. by move=> m; rewrite /= -{2}[n]addn0 subnDl subn0. Qed.\n\nLemma addnK n : cancel (addn^~ n) (subn^~ n).\nProof. by move=> m; rewrite /= (addnC m) addKn. Qed.\n\nLemma subSnn n : n.+1 - n = 1.\nProof. exact (addnK n 1). Qed.\n\nLemma subnDA m n p : n - (m + p) = (n - m) - p.\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma subnAC : right_commutative subn.\nProof. by move=> m n p; rewrite -!subnDA addnC. Qed.\n\nLemma subnS m n : m - n.+1 = (m - n).-1.\nProof. by rewrite -addn1 subnDA subn1. Qed.\n\nLemma subSKn m n : (m.+1 - n).-1 = m - n.\nProof. by rewrite -subnS. Qed.\n\n(* Integer ordering, and its interaction with the other operations.       *)\n\nDefinition leq m n := m - n == 0.\n\nNotation \"m <= n\" := (leq m n) : nat_scope.\nNotation \"m < n\"  := (m.+1 <= n) : nat_scope.\nNotation \"m >= n\" := (n <= m) (only parsing) : nat_scope.\nNotation \"m > n\"  := (n < m) (only parsing)  : nat_scope.\n\n(* For sorting, etc. *)\nDefinition geq := [rel m n | m >= n].\nDefinition ltn := [rel m n | m < n].\nDefinition gtn := [rel m n | m > n].\n\nNotation \"m <= n <= p\" := ((m <= n) && (n <= p)) : nat_scope.\nNotation \"m < n <= p\" := ((m < n) && (n <= p)) : nat_scope.\nNotation \"m <= n < p\" := ((m <= n) && (n < p)) : nat_scope.\nNotation \"m < n < p\" := ((m < n) && (n < p)) : nat_scope.\n\nLemma ltnS m n : (m < n.+1) = (m <= n). Proof. by []. Qed.\nLemma leq0n n : 0 <= n.                 Proof. by []. Qed.\nLemma ltn0Sn n : 0 < n.+1.              Proof. by []. Qed.\nLemma ltn0 n : n < 0 = false.           Proof. by []. Qed.\nLemma leqnn n : n <= n.                 Proof. by elim: n. Qed.\nHint Resolve leqnn : core.\nLemma ltnSn n : n < n.+1.               Proof. by []. Qed.\nLemma eq_leq m n : m = n -> m <= n.     Proof. by move->. Qed.\nLemma leqnSn n : n <= n.+1.             Proof. by elim: n. Qed.\nHint Resolve leqnSn : core.\nLemma leq_pred n : n.-1 <= n.           Proof. by case: n => /=. Qed.\nLemma leqSpred n : n <= n.-1.+1.        Proof. by case: n => /=. Qed.\n\nLemma ltn_predK m n : m < n -> n.-1.+1 = n.\nProof. by case: n. Qed.\n\nLemma prednK n : 0 < n -> n.-1.+1 = n.\nProof. exact: ltn_predK. Qed.\n\nLemma leqNgt m n : (m <= n) = ~~ (n < m).\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma ltnNge m n : (m < n) = ~~ (n <= m).\nProof. by rewrite leqNgt. Qed.\n\nLemma ltnn n : n < n = false.\nProof. by rewrite ltnNge leqnn. Qed.\n\nLemma leqn0 n : (n <= 0) = (n == 0).           Proof. by case: n. Qed.\nLemma lt0n n : (0 < n) = (n != 0).             Proof. by case: n. Qed.\nLemma lt0n_neq0 n : 0 < n -> n != 0.           Proof. by case: n. Qed.\nLemma eqn0Ngt n : (n == 0) = ~~ (n > 0).       Proof. by case: n. Qed.\nLemma neq0_lt0n n : (n == 0) = false -> 0 < n. Proof. by case: n. Qed.\nHint Resolve lt0n_neq0 neq0_lt0n : core.\n\nLemma eqn_leq m n : (m == n) = (m <= n <= m).\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma anti_leq : antisymmetric leq.\nProof. by move=> m n; rewrite -eqn_leq => /eqP. Qed.\n\nLemma neq_ltn m n : (m != n) = (m < n) || (n < m).\nProof. by rewrite eqn_leq negb_and orbC -!ltnNge. Qed.\n\nLemma gtn_eqF m n : m < n -> n == m = false.\nProof. by rewrite eqn_leq (leqNgt n) => ->. Qed.\n\nLemma ltn_eqF m n : m < n -> m == n = false.\nProof. by move/gtn_eqF; rewrite eq_sym. Qed.\n\nLemma leq_eqVlt m n : (m <= n) = (m == n) || (m < n).\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma ltn_neqAle m n : (m < n) = (m != n) && (m <= n).\nProof. by rewrite ltnNge leq_eqVlt negb_or -leqNgt eq_sym. Qed.\n\nLemma leq_trans n m p : m <= n -> n <= p -> m <= p.\nProof. by elim: n m p => [|i IHn] [|m] [|p] //; apply: IHn m p. Qed.\n\nLemma leq_ltn_trans n m p : m <= n -> n < p -> m < p.\nProof. by move=> Hmn; apply: leq_trans. Qed.\n\nLemma ltnW m n : m < n -> m <= n.\nProof. exact: leq_trans. Qed.\nHint Resolve ltnW : core.\n\nLemma leqW m n : m <= n -> m <= n.+1.\nProof. by move=> le_mn; apply: ltnW. Qed.\n\nLemma ltn_trans n m p : m < n -> n < p -> m < p.\nProof. by move=> lt_mn /ltnW; apply: leq_trans. Qed.\n\nLemma leq_total m n : (m <= n) || (m >= n).\nProof. by rewrite -implyNb -ltnNge; apply/implyP; apply: ltnW. Qed.\n\n(* Link to the legacy comparison predicates. *)\n\nLemma leP m n : reflect (m <= n)%coq_nat (m <= n).\nProof.\napply: (iffP idP); last by elim: n / => // n _ /leq_trans->.\nelim: n => [|n IHn]; first by case: m.\nby rewrite leq_eqVlt ltnS => /predU1P[<- // | /IHn]; right.\nQed.\nArguments leP {m n}.\n\nLemma le_irrelevance m n le_mn1 le_mn2 : le_mn1 = le_mn2 :> (m <= n)%coq_nat.\nProof.\nelim: {n}n.+1 {-1}n (erefl n.+1) => // n IHn _ [<-] in le_mn1 le_mn2 *.\npose def_n2 := erefl n; transitivity (eq_ind _ _ le_mn2 _ def_n2) => //.\nmove def_n1: {1 4 5 7}n le_mn1 le_mn2 def_n2 => n1 le_mn1.\ncase: n1 / le_mn1 def_n1 => [|n1 le_mn1] def_n1 [|n2 le_mn2] def_n2.\n- by rewrite [def_n2]eq_axiomK.\n- by move/leP: (le_mn2); rewrite -{1}def_n2 ltnn.\n- by move/leP: (le_mn1); rewrite {1}def_n2 ltnn.\ncase: def_n2 (def_n2) => ->{n2} def_n2 in le_mn2 *.\nby rewrite [def_n2]eq_axiomK /=; congr le_S; apply: IHn.\nQed.\n\nLemma ltP m n : reflect (m < n)%coq_nat (m < n).\nProof. exact leP. Qed.\nArguments ltP {m n}.\n\nLemma lt_irrelevance m n lt_mn1 lt_mn2 : lt_mn1 = lt_mn2 :> (m < n)%coq_nat.\nProof. exact: (@le_irrelevance m.+1). Qed.\n\n(* Comparison predicates. *)\n\nVariant leq_xor_gtn m n : bool -> bool -> Set :=\n  | LeqNotGtn of m <= n : leq_xor_gtn m n true false\n  | GtnNotLeq of n < m  : leq_xor_gtn m n false true.\n\nLemma leqP m n : leq_xor_gtn m n (m <= n) (n < m).\nProof.\nby rewrite ltnNge; case le_mn: (m <= n); constructor; rewrite // ltnNge le_mn.\nQed.\n\nVariant ltn_xor_geq m n : bool -> bool -> Set :=\n  | LtnNotGeq of m < n  : ltn_xor_geq m n false true\n  | GeqNotLtn of n <= m : ltn_xor_geq m n true false.\n\nLemma ltnP m n : ltn_xor_geq m n (n <= m) (m < n).\nProof. by rewrite -(ltnS n); case: leqP; constructor. Qed.\n\nVariant eqn0_xor_gt0 n : bool -> bool -> Set :=\n  | Eq0NotPos of n = 0 : eqn0_xor_gt0 n true false\n  | PosNotEq0 of n > 0 : eqn0_xor_gt0 n false true.\n\nLemma posnP n : eqn0_xor_gt0 n (n == 0) (0 < n).\nProof. by case: n; constructor. Qed.\n\nVariant compare_nat m n :\n   bool -> bool -> bool -> bool -> bool -> bool -> Set :=\n  | CompareNatLt of m < n : compare_nat m n true false true false false false\n  | CompareNatGt of m > n : compare_nat m n false true false true false false\n  | CompareNatEq of m = n : compare_nat m n true true false false true true.\n\nLemma ltngtP m n : compare_nat m n (m <= n) (n <= m) (m < n)\n                                   (n < m) (n == m) (m == n).\nProof.\nrewrite !ltn_neqAle [_ == m]eq_sym; case: ltnP => [mn|].\n  by rewrite ltnW // gtn_eqF //; constructor.\nrewrite leq_eqVlt; case: ltnP; rewrite ?(orbT, orbF) => //= lt_nm eq_mn.\n  by rewrite ltn_eqF //; constructor.\nby rewrite eq_mn; constructor; apply/eqP.\nQed.\n\n(* Monotonicity lemmas *)\n\nLemma leq_add2l p m n : (p + m <= p + n) = (m <= n).\nProof. by elim: p. Qed.\n\nLemma ltn_add2l p m n : (p + m < p + n) = (m < n).\nProof. by rewrite -addnS; apply: leq_add2l. Qed.\n\nLemma leq_add2r p m n : (m + p <= n + p) = (m <= n).\nProof. by rewrite -!(addnC p); apply: leq_add2l. Qed.\n\nLemma ltn_add2r p m n : (m + p < n + p) = (m < n).\nProof. exact: leq_add2r p m.+1 n. Qed.\n\nLemma leq_add m1 m2 n1 n2 : m1 <= n1 -> m2 <= n2 -> m1 + m2 <= n1 + n2.\nProof.\nby move=> le_mn1 le_mn2; rewrite (@leq_trans (m1 + n2)) ?leq_add2l ?leq_add2r.\nQed.\n\nLemma leq_addr m n : n <= n + m.\nProof. by rewrite -{1}[n]addn0 leq_add2l. Qed.\n\nLemma leq_addl m n : n <= m + n.\nProof. by rewrite addnC leq_addr. Qed.\n\nLemma ltn_addr m n p : m < n -> m < n + p.\nProof. by move/leq_trans=> -> //; apply: leq_addr. Qed.\n\nLemma ltn_addl m n p : m < n -> m < p + n.\nProof. by move/leq_trans=> -> //; apply: leq_addl. Qed.\n\nLemma addn_gt0 m n : (0 < m + n) = (0 < m) || (0 < n).\nProof. by rewrite !lt0n -negb_and addn_eq0. Qed.\n\nLemma subn_gt0 m n : (0 < n - m) = (m < n).\nProof. by elim: m n => [|m IHm] [|n] //; apply: IHm n. Qed.\n\nLemma subn_eq0 m n : (m - n == 0) = (m <= n).\nProof. by []. Qed.\n\nLemma leq_subLR m n p : (m - n <= p) = (m <= n + p).\nProof. by rewrite -subn_eq0 -subnDA. Qed.\n\nLemma leq_subr m n : n - m <= n.\nProof. by rewrite leq_subLR leq_addl. Qed.\n\nLemma subnKC m n : m <= n -> m + (n - m) = n.\nProof. by elim: m n => [|m IHm] [|n] // /(IHm n) {2}<-. Qed.\n\nLemma subnK m n : m <= n -> (n - m) + m = n.\nProof. by rewrite addnC; apply: subnKC. Qed.\n\nLemma addnBA m n p : p <= n -> m + (n - p) = m + n - p.\nProof. by move=> le_pn; rewrite -{2}(subnK le_pn) addnA addnK. Qed.\n\nLemma addnBAC m n p : n <= m -> m - n + p = m + p - n.\nProof. by move=> le_nm; rewrite addnC addnBA // addnC. Qed.\n\nLemma addnBCA m n p : p <= m -> p <= n -> m + (n - p) = n + (m - p).\nProof. by move=> le_pm le_pn; rewrite !addnBA // addnC. Qed.\n\nLemma addnABC m n p : p <= m -> p <= n -> m + (n - p) = m - p + n.\nProof. by move=> le_pm le_pn; rewrite addnBA // addnBAC. Qed.\n\nLemma subnBA m n p : p <= n -> m - (n - p) = m + p - n.\nProof. by move=> le_pn; rewrite -{2}(subnK le_pn) subnDr. Qed.\n\nLemma subKn m n : m <= n -> n - (n - m) = m.\nProof. by move/subnBA->; rewrite addKn. Qed.\n\nLemma subSn m n : m <= n -> n.+1 - m = (n - m).+1.\nProof. by rewrite -add1n => /addnBA <-. Qed.\n\nLemma subnSK m n : m < n -> (n - m.+1).+1 = n - m.\nProof. by move/subSn. Qed.\n\nLemma leq_sub2r p m n : m <= n -> m - p <= n - p.\nProof.\nby move=> le_mn; rewrite leq_subLR (leq_trans le_mn) // -leq_subLR.\nQed.\n\nLemma leq_sub2l p m n : m <= n -> p - n <= p - m.\nProof.\nrewrite -(leq_add2r (p - m)) leq_subLR.\nby apply: leq_trans; rewrite -leq_subLR.\nQed.\n\nLemma leq_sub m1 m2 n1 n2 : m1 <= m2 -> n2 <= n1 -> m1 - n1 <= m2 - n2.\nProof. by move/(leq_sub2r n1)=> le_m12 /(leq_sub2l m2); apply: leq_trans. Qed.\n\nLemma ltn_sub2r p m n : p < n -> m < n -> m - p < n - p.\nProof. by move/subnSK <-; apply: (@leq_sub2r p.+1). Qed.\n\nLemma ltn_sub2l p m n : m < p -> m < n -> p - n < p - m.\nProof. by move/subnSK <-; apply: leq_sub2l. Qed.\n\nLemma ltn_subRL m n p : (n < p - m) = (m + n < p).\nProof. by rewrite !ltnNge leq_subLR. Qed.\n\n(* Eliminating the idiom for structurally decreasing compare and subtract. *)\nLemma subn_if_gt T m n F (E : T) :\n  (if m.+1 - n is m'.+1 then F m' else E) = (if n <= m then F (m - n) else E).\nProof.\nby case: leqP => [le_nm | /eqnP-> //]; rewrite -{1}(subnK le_nm) -addSn addnK.\nQed.\n\n(* Max and min. *)\n\nDefinition maxn m n := if m < n then n else m.\n\nDefinition minn m n := if m < n then m else n.\n\nLemma max0n : left_id 0 maxn.  Proof. by case. Qed.\nLemma maxn0 : right_id 0 maxn. Proof. by []. Qed.\n\nLemma maxnC : commutative maxn.\nProof. by move=> m n; rewrite /maxn; case ltngtP. Qed.\n\nLemma maxnE m n : maxn m n = m + (n - m).\nProof. by rewrite /maxn addnC; case: leqP => [/eqnP->|/ltnW/subnK]. Qed.\n\nLemma maxnAC : right_commutative maxn.\nProof. by move=> m n p; rewrite !maxnE -!addnA !subnDA -!maxnE maxnC. Qed.\n\nLemma maxnA : associative maxn.\nProof. by move=> m n p; rewrite !(maxnC m) maxnAC. Qed.\n\nLemma maxnCA : left_commutative maxn.\nProof. by move=> m n p; rewrite !maxnA (maxnC m). Qed.\n\nLemma maxnACA : interchange maxn maxn.\nProof. by move=> m n p q; rewrite -!maxnA (maxnCA n). Qed.\n\nLemma maxn_idPl {m n} : reflect (maxn m n = m) (m >= n).\nProof. by rewrite -subn_eq0 -(eqn_add2l m) addn0 -maxnE; apply: eqP. Qed.\n\nLemma maxn_idPr {m n} : reflect (maxn m n = n) (m <= n).\nProof. by rewrite maxnC; apply: maxn_idPl. Qed.\n\nLemma maxnn : idempotent maxn.\nProof. by move=> n; apply/maxn_idPl. Qed.\n\nLemma leq_max m n1 n2 : (m <= maxn n1 n2) = (m <= n1) || (m <= n2).\nProof.\nwithout loss le_n21: n1 n2 / n2 <= n1.\n  by case/orP: (leq_total n2 n1) => le_n12; last rewrite maxnC orbC; apply.\nby rewrite (maxn_idPl le_n21) orb_idr // => /leq_trans->.\nQed.\nLemma leq_maxl m n : m <= maxn m n. Proof. by rewrite leq_max leqnn. Qed.\nLemma leq_maxr m n : n <= maxn m n. Proof. by rewrite maxnC leq_maxl. Qed.\n\nLemma gtn_max m n1 n2 : (m > maxn n1 n2) = (m > n1) && (m > n2).\nProof. by rewrite !ltnNge leq_max negb_or. Qed.\n\nLemma geq_max m n1 n2 : (m >= maxn n1 n2) = (m >= n1) && (m >= n2).\nProof. by rewrite -ltnS gtn_max. Qed.\n\nLemma maxnSS m n : maxn m.+1 n.+1 = (maxn m n).+1.\nProof. by rewrite !maxnE. Qed.\n\nLemma addn_maxl : left_distributive addn maxn.\nProof. by move=> m1 m2 n; rewrite !maxnE subnDr addnAC. Qed.\n\nLemma addn_maxr : right_distributive addn maxn.\nProof. by move=> m n1 n2; rewrite !(addnC m) addn_maxl. Qed.\n\nLemma min0n : left_zero 0 minn. Proof. by case. Qed.\nLemma minn0 : right_zero 0 minn. Proof. by []. Qed.\n\nLemma minnC : commutative minn.\nProof. by move=> m n; rewrite /minn; case ltngtP. Qed.\n\nLemma addn_min_max m n : minn m n + maxn m n = m + n.\nProof. by rewrite /minn /maxn; case: ltngtP => // [_|->] //; apply: addnC. Qed.\n\nLemma minnE m n : minn m n = m - (m - n).\nProof. by rewrite -(subnDl n) -maxnE -addn_min_max addnK minnC. Qed.\n\nLemma minnAC : right_commutative minn.\nProof.\nby move=> m n p; rewrite !minnE -subnDA subnAC -maxnE maxnC maxnE subnAC subnDA.\nQed.\n\nLemma minnA : associative minn.\nProof. by move=> m n p; rewrite minnC minnAC (minnC n). Qed.\n\nLemma minnCA : left_commutative minn.\nProof. by move=> m n p; rewrite !minnA (minnC n). Qed.\n\nLemma minnACA : interchange minn minn.\nProof. by move=> m n p q; rewrite -!minnA (minnCA n). Qed.\n\nLemma minn_idPl {m n} : reflect (minn m n = m) (m <= n).\nProof.\nrewrite (sameP maxn_idPr eqP) -(eqn_add2l m) eq_sym -addn_min_max eqn_add2r.\nexact: eqP.\nQed.\n\nLemma minn_idPr {m n} : reflect (minn m n = n) (m >= n).\nProof. by rewrite minnC; apply: minn_idPl. Qed.\n\nLemma minnn : idempotent minn.\nProof. by move=> n; apply/minn_idPl. Qed.\n\nLemma leq_min m n1 n2 : (m <= minn n1 n2) = (m <= n1) && (m <= n2).\nProof.\nwlog le_n21: n1 n2 / n2 <= n1.\n  by case/orP: (leq_total n2 n1) => ?; last rewrite minnC andbC; auto.\nby rewrite /minn ltnNge le_n21 /= andbC; case: leqP => // /leq_trans->.\nQed.\n\nLemma gtn_min m n1 n2 : (m > minn n1 n2) = (m > n1) || (m > n2).\nProof. by rewrite !ltnNge leq_min negb_and. Qed.\n\nLemma geq_min m n1 n2 : (m >= minn n1 n2) = (m >= n1) || (m >= n2).\nProof. by rewrite -ltnS gtn_min. Qed.\n\nLemma geq_minl m n : minn m n <= m. Proof. by rewrite geq_min leqnn. Qed.\nLemma geq_minr m n : minn m n <= n. Proof. by rewrite minnC geq_minl. Qed.\n\nLemma addn_minr : right_distributive addn minn.\nProof. by move=> m1 m2 n; rewrite !minnE subnDl addnBA ?leq_subr. Qed.\n\nLemma addn_minl : left_distributive addn minn.\nProof. by move=> m1 m2 n; rewrite -!(addnC n) addn_minr. Qed.\n\nLemma minnSS m n : minn m.+1 n.+1 = (minn m n).+1.\nProof. by rewrite -(addn_minr 1). Qed.\n\n(* Quasi-cancellation (really, absorption) lemmas *)\nLemma maxnK m n : minn (maxn m n) m = m.\nProof. exact/minn_idPr/leq_maxl. Qed.\n\nLemma maxKn m n : minn n (maxn m n) = n.\nProof. exact/minn_idPl/leq_maxr. Qed.\n\nLemma minnK m n : maxn (minn m n) m = m.\nProof. exact/maxn_idPr/geq_minl. Qed.\n\nLemma minKn m n : maxn n (minn m n) = n.\nProof. exact/maxn_idPl/geq_minr. Qed.\n\n(* Distributivity. *)\nLemma maxn_minl : left_distributive maxn minn.\nProof.\nmove=> m1 m2 n; wlog le_m21: m1 m2 / m2 <= m1.\n  move=> IH; case/orP: (leq_total m2 m1) => /IH //.\n  by rewrite minnC [in R in _ = R]minnC.\nrewrite (minn_idPr le_m21); apply/esym/minn_idPr.\nby rewrite geq_max leq_maxr leq_max le_m21.\nQed.\n\nLemma maxn_minr : right_distributive maxn minn.\nProof. by move=> m n1 n2; rewrite !(maxnC m) maxn_minl. Qed.\n\nLemma minn_maxl : left_distributive minn maxn.\nProof.\nby move=> m1 m2 n; rewrite maxn_minr !maxn_minl -minnA maxnn (maxnC _ n) !maxnK.\nQed.\n\nLemma minn_maxr : right_distributive minn maxn.\nProof. by move=> m n1 n2; rewrite !(minnC m) minn_maxl. Qed.\n\n(* Getting a concrete value from an abstract existence proof. *)\n\nSection ExMinn.\n\nVariable P : pred nat.\nHypothesis exP : exists n, P n.\n\nInductive acc_nat i : Prop := AccNat0 of P i | AccNatS of acc_nat i.+1.\n\nLemma find_ex_minn : {m | P m & forall n, P n -> n >= m}.\nProof.\nhave: forall n, P n -> n >= 0 by [].\nhave: acc_nat 0.\n  case exP => n; rewrite -(addn0 n); elim: n 0 => [|n IHn] j; first by left.\n  by rewrite addSnnS; right; apply: IHn.\nmove: 0; fix find_ex_minn 2 => m IHm m_lb; case Pm: (P m); first by exists m.\napply: find_ex_minn m.+1 _ _ => [|n Pn]; first by case: IHm; rewrite ?Pm.\nby rewrite ltn_neqAle m_lb //; case: eqP Pm => // -> /idP[].\nQed.\n\nDefinition ex_minn := s2val find_ex_minn.\n\nInductive ex_minn_spec : nat -> Type :=\n  ExMinnSpec m of P m & (forall n, P n -> n >= m) : ex_minn_spec m.\n\nLemma ex_minnP : ex_minn_spec ex_minn.\nProof. by rewrite /ex_minn; case: find_ex_minn. Qed.\n\nEnd ExMinn.\n\nSection ExMaxn.\n\nVariables (P : pred nat) (m : nat).\nHypotheses (exP : exists i, P i) (ubP : forall i, P i -> i <= m).\n\nLemma ex_maxn_subproof : exists i, P (m - i).\nProof. by case: exP => i Pi; exists (m - i); rewrite subKn ?ubP. Qed.\n\nDefinition ex_maxn := m - ex_minn ex_maxn_subproof.\n\nVariant ex_maxn_spec : nat -> Type :=\n  ExMaxnSpec i of P i & (forall j, P j -> j <= i) : ex_maxn_spec i.\n\nLemma ex_maxnP : ex_maxn_spec ex_maxn.\nProof.\nrewrite /ex_maxn; case: ex_minnP => i Pmi min_i; split=> // j Pj.\nhave le_i_mj: i <= m - j by rewrite min_i // subKn // ubP.\nrewrite -subn_eq0 subnBA ?(leq_trans le_i_mj) ?leq_subr //.\nby rewrite addnC -subnBA ?ubP.\nQed.\n\nEnd ExMaxn.\n\nLemma eq_ex_minn P Q exP exQ : P =1 Q -> @ex_minn P exP = @ex_minn Q exQ.\nProof.\nmove=> eqPQ; case: ex_minnP => m1 Pm1 m1_lb; case: ex_minnP => m2 Pm2 m2_lb.\nby apply/eqP; rewrite eqn_leq m1_lb (m2_lb, eqPQ) // -eqPQ.\nQed.\n\nLemma eq_ex_maxn (P Q : pred nat) m n exP ubP exQ ubQ :\n  P =1 Q -> @ex_maxn P m exP ubP = @ex_maxn Q n exQ ubQ.\nProof.\nmove=> eqPQ; case: ex_maxnP => i Pi max_i; case: ex_maxnP => j Pj max_j.\nby apply/eqP; rewrite eqn_leq max_i ?eqPQ // max_j -?eqPQ.\nQed.\n\nSection Iteration.\n\nVariable T : Type.\nImplicit Types m n : nat.\nImplicit Types x y : T.\n\nDefinition iter n f x :=\n  let fix loop m := if m is i.+1 then f (loop i) else x in loop n.\n\nDefinition iteri n f x :=\n  let fix loop m := if m is i.+1 then f i (loop i) else x in loop n.\n\nDefinition iterop n op x :=\n  let f i y := if i is 0 then x else op x y in iteri n f.\n\nLemma iterSr n f x : iter n.+1 f x = iter n f (f x).\nProof. by elim: n => //= n <-. Qed.\n\nLemma iterS n f x : iter n.+1 f x = f (iter n f x). Proof. by []. Qed.\n\nLemma iter_add n m f x : iter (n + m) f x = iter n f (iter m f x).\nProof. by elim: n => //= n ->. Qed.\n\nLemma iteriS n f x : iteri n.+1 f x = f n (iteri n f x).\nProof. by []. Qed.\n\nLemma iteropS idx n op x : iterop n.+1 op x idx = iter n (op x) x.\nProof. by elim: n => //= n ->. Qed.\n\nLemma eq_iter f f' : f =1 f' -> forall n, iter n f =1 iter n f'.\nProof. by move=> eq_f n x; elim: n => //= n ->; rewrite eq_f. Qed.\n\nLemma eq_iteri f f' : f =2 f' -> forall n, iteri n f =1 iteri n f'.\nProof. by move=> eq_f n x; elim: n => //= n ->; rewrite eq_f. Qed.\n\nLemma eq_iterop n op op' : op =2 op' -> iterop n op =2 iterop n op'.\nProof. by move=> eq_op x; apply: eq_iteri; case. Qed.\n\nEnd Iteration.\n\nLemma iter_succn m n : iter n succn m = m + n.\nProof. by elim: n => //= n ->. Qed.\n\nLemma iter_succn_0 n : iter n succn 0 = n.\nProof. exact: iter_succn. Qed.\n\nLemma iter_predn m n : iter n predn m = m - n.\nProof. by elim: n m => /= [|n IHn] m; rewrite ?subn0 // IHn subnS. Qed.\n\n(* Multiplication. *)\n\nDefinition muln_rec := mult.\nNotation \"m * n\" := (muln_rec m n) : nat_rec_scope.\n\nDefinition muln := nosimpl muln_rec.\nNotation \"m * n\" := (muln m n) : nat_scope.\n\nLemma multE : mult = muln.     Proof. by []. Qed.\nLemma mulnE : muln = muln_rec. Proof. by []. Qed.\n\nLemma mul0n : left_zero 0 muln.          Proof. by []. Qed.\nLemma muln0 : right_zero 0 muln.         Proof. by elim. Qed.\nLemma mul1n : left_id 1 muln.            Proof. exact: addn0. Qed.\nLemma mulSn m n : m.+1 * n = n + m * n.  Proof. by []. Qed.\nLemma mulSnr m n : m.+1 * n = m * n + n. Proof. exact: addnC. Qed.\n\nLemma mulnS m n : m * n.+1 = m + m * n.\nProof. by elim: m => // m; rewrite !mulSn !addSn addnCA => ->. Qed.\nLemma mulnSr m n : m * n.+1 = m * n + m.\nProof. by rewrite addnC mulnS. Qed.\n\nLemma iter_addn m n p : iter n (addn m) p = m * n + p.\nProof. by elim: n => /= [|n ->]; rewrite ?muln0 // mulnS addnA. Qed.\n\nLemma iter_addn_0 m n : iter n (addn m) 0 = m * n.\nProof. by rewrite iter_addn addn0. Qed.\n\nLemma muln1 : right_id 1 muln.\nProof. by move=> n; rewrite mulnSr muln0. Qed.\n\nLemma mulnC : commutative muln.\nProof.\nby move=> m n; elim: m => [|m]; rewrite (muln0, mulnS) // mulSn => ->.\nQed.\n\nLemma mulnDl : left_distributive muln addn.\nProof. by move=> m1 m2 n; elim: m1 => //= m1 IHm; rewrite -addnA -IHm. Qed.\n\nLemma mulnDr : right_distributive muln addn.\nProof. by move=> m n1 n2; rewrite !(mulnC m) mulnDl. Qed.\n\nLemma mulnBl : left_distributive muln subn.\nProof.\nmove=> m n [|p]; first by rewrite !muln0.\nby elim: m n => // [m IHm] [|n] //; rewrite mulSn subnDl -IHm.\nQed.\n\nLemma mulnBr : right_distributive muln subn.\nProof. by move=> m n p; rewrite !(mulnC m) mulnBl. Qed.\n\nLemma mulnA : associative muln.\nProof. by move=> m n p; elim: m => //= m; rewrite mulSn mulnDl => ->. Qed.\n\nLemma mulnCA : left_commutative muln.\nProof. by move=> m n1 n2; rewrite !mulnA (mulnC m). Qed.\n\nLemma mulnAC : right_commutative muln.\nProof. by move=> m n p; rewrite -!mulnA (mulnC n). Qed.\n\nLemma mulnACA : interchange muln muln.\nProof. by move=> m n p q; rewrite -!mulnA (mulnCA n). Qed.\n\nLemma muln_eq0 m n : (m * n == 0) = (m == 0) || (n == 0).\nProof. by case: m n => // m [|n] //=; rewrite muln0. Qed.\n\nLemma muln_eq1 m n : (m * n == 1) = (m == 1) && (n == 1).\nProof. by case: m n => [|[|m]] [|[|n]] //; rewrite muln0. Qed.\n\nLemma muln_gt0 m n : (0 < m * n) = (0 < m) && (0 < n).\nProof. by case: m n => // m [|n] //=; rewrite muln0. Qed.\n\nLemma leq_pmull m n : n > 0 -> m <= n * m.\nProof. by move/prednK <-; apply: leq_addr. Qed.\n\nLemma leq_pmulr m n : n > 0 -> m <= m * n.\nProof. by move/leq_pmull; rewrite mulnC. Qed.\n\nLemma leq_mul2l m n1 n2 : (m * n1 <= m * n2) = (m == 0) || (n1 <= n2).\nProof. by rewrite {1}/leq -mulnBr muln_eq0. Qed.\n\nLemma leq_mul2r m n1 n2 : (n1 * m <= n2 * m) = (m == 0) || (n1 <= n2).\nProof. by rewrite -!(mulnC m) leq_mul2l. Qed.\n\nLemma leq_mul m1 m2 n1 n2 : m1 <= n1 -> m2 <= n2 -> m1 * m2 <= n1 * n2.\nProof.\nmove=> le_mn1 le_mn2; apply (@leq_trans (m1 * n2)).\n  by rewrite leq_mul2l le_mn2 orbT.\nby rewrite leq_mul2r le_mn1 orbT.\nQed.\n\nLemma eqn_mul2l m n1 n2 : (m * n1 == m * n2) = (m == 0) || (n1 == n2).\nProof. by rewrite eqn_leq !leq_mul2l -orb_andr -eqn_leq. Qed.\n\nLemma eqn_mul2r m n1 n2 : (n1 * m == n2 * m) = (m == 0) || (n1 == n2).\nProof. by rewrite eqn_leq !leq_mul2r -orb_andr -eqn_leq. Qed.\n\nLemma leq_pmul2l m n1 n2 : 0 < m -> (m * n1 <= m * n2) = (n1 <= n2).\nProof. by move/prednK=> <-; rewrite leq_mul2l. Qed.\nArguments leq_pmul2l [m n1 n2].\n\nLemma leq_pmul2r m n1 n2 : 0 < m -> (n1 * m <= n2 * m) = (n1 <= n2).\nProof. by move/prednK <-; rewrite leq_mul2r. Qed.\nArguments leq_pmul2r [m n1 n2].\n\nLemma eqn_pmul2l m n1 n2 : 0 < m -> (m * n1 == m * n2) = (n1 == n2).\nProof. by move/prednK <-; rewrite eqn_mul2l. Qed.\nArguments eqn_pmul2l [m n1 n2].\n\nLemma eqn_pmul2r m n1 n2 : 0 < m -> (n1 * m == n2 * m) = (n1 == n2).\nProof. by move/prednK <-; rewrite eqn_mul2r. Qed.\nArguments eqn_pmul2r [m n1 n2].\n\nLemma ltn_mul2l m n1 n2 : (m * n1 < m * n2) = (0 < m) && (n1 < n2).\nProof. by rewrite lt0n !ltnNge leq_mul2l negb_or. Qed.\n\nLemma ltn_mul2r m n1 n2 : (n1 * m < n2 * m) = (0 < m) && (n1 < n2).\nProof. by rewrite lt0n !ltnNge leq_mul2r negb_or. Qed.\n\nLemma ltn_pmul2l m n1 n2 : 0 < m -> (m * n1 < m * n2) = (n1 < n2).\nProof. by move/prednK <-; rewrite ltn_mul2l. Qed.\nArguments ltn_pmul2l [m n1 n2].\n\nLemma ltn_pmul2r m n1 n2 : 0 < m -> (n1 * m < n2 * m) = (n1 < n2).\nProof. by move/prednK <-; rewrite ltn_mul2r. Qed.\nArguments ltn_pmul2r [m n1 n2].\n\nLemma ltn_Pmull m n : 1 < n -> 0 < m -> m < n * m.\nProof. by move=> lt1n m_gt0; rewrite -{1}[m]mul1n ltn_pmul2r. Qed.\n\nLemma ltn_Pmulr m n : 1 < n -> 0 < m -> m < m * n.\nProof. by move=> lt1n m_gt0; rewrite mulnC ltn_Pmull. Qed.\n\nLemma ltn_mul m1 m2 n1 n2 : m1 < n1 -> m2 < n2 -> m1 * m2 < n1 * n2.\nProof.\nmove=> lt_mn1 lt_mn2; apply (@leq_ltn_trans (m1 * n2)).\n  by rewrite leq_mul2l orbC ltnW.\nby rewrite ltn_pmul2r // (leq_trans _ lt_mn2).\nQed.\n\nLemma maxn_mulr : right_distributive muln maxn.\nProof. by case=> // m n1 n2; rewrite /maxn (fun_if (muln _)) ltn_pmul2l. Qed.\n\nLemma maxn_mull : left_distributive muln maxn.\nProof. by move=> m1 m2 n; rewrite -!(mulnC n) maxn_mulr. Qed.\n\nLemma minn_mulr : right_distributive muln minn.\nProof. by case=> // m n1 n2; rewrite /minn (fun_if (muln _)) ltn_pmul2l. Qed.\n\nLemma minn_mull : left_distributive muln minn.\nProof. by move=> m1 m2 n; rewrite -!(mulnC n) minn_mulr. Qed.\n\n(* Exponentiation. *)\n\nDefinition expn_rec m n := iterop n muln m 1.\nNotation \"m ^ n\" := (expn_rec m n) : nat_rec_scope.\nDefinition expn := nosimpl expn_rec.\nNotation \"m ^ n\" := (expn m n) : nat_scope.\n\nLemma expnE : expn = expn_rec. Proof. by []. Qed.\n\nLemma expn0 m : m ^ 0 = 1. Proof. by []. Qed.\nLemma expn1 m : m ^ 1 = m. Proof. by []. Qed.\nLemma expnS m n : m ^ n.+1 = m * m ^ n. Proof. by case: n; rewrite ?muln1. Qed.\nLemma expnSr m n : m ^ n.+1 = m ^ n * m. Proof. by rewrite mulnC expnS. Qed.\n\nLemma iter_muln m n p : iter n (muln m) p = m ^ n * p.\nProof. by elim: n => /= [|n ->]; rewrite ?mul1n // expnS mulnA. Qed.\n\nLemma iter_muln_1 m n : iter n (muln m) 1 = m ^ n.\nProof. by rewrite iter_muln muln1. Qed.\n\nLemma exp0n n : 0 < n -> 0 ^ n = 0. Proof. by case: n => [|[]]. Qed.\n\nLemma exp1n n : 1 ^ n = 1.\nProof. by elim: n => // n; rewrite expnS mul1n. Qed.\n\nLemma expnD m n1 n2 : m ^ (n1 + n2) = m ^ n1 * m ^ n2.\nProof. by elim: n1 => [|n1 IHn]; rewrite !(mul1n, expnS) // IHn mulnA. Qed.\n\nLemma expnMn m1 m2 n : (m1 * m2) ^ n = m1 ^ n * m2 ^ n.\nProof. by elim: n => // n IHn; rewrite !expnS IHn -!mulnA (mulnCA m2). Qed.\n\nLemma expnM m n1 n2 : m ^ (n1 * n2) = (m ^ n1) ^ n2.\nProof.\nelim: n1 => [|n1 IHn]; first by rewrite exp1n.\nby rewrite expnD expnS expnMn IHn.\nQed.\n\nLemma expnAC m n1 n2 : (m ^ n1) ^ n2 = (m ^ n2) ^ n1.\nProof. by rewrite -!expnM mulnC. Qed.\n\nLemma expn_gt0 m n : (0 < m ^ n) = (0 < m) || (n == 0).\nProof.\nby case: m => [|m]; elim: n => //= n IHn; rewrite expnS // addn_gt0 IHn.\nQed.\n\nLemma expn_eq0 m e : (m ^ e == 0) = (m == 0) && (e > 0).\nProof. by rewrite !eqn0Ngt expn_gt0 negb_or -lt0n. Qed.\n\nLemma ltn_expl m n : 1 < m -> n < m ^ n.\nProof.\nmove=> m_gt1; elim: n => //= n; rewrite -(leq_pmul2l (ltnW m_gt1)) expnS.\nby apply: leq_trans; apply: ltn_Pmull.\nQed.\n\nLemma leq_exp2l m n1 n2 : 1 < m -> (m ^ n1 <= m ^ n2) = (n1 <= n2).\nProof.\nmove=> m_gt1; elim: n1 n2 => [|n1 IHn] [|n2] //; last 1 first.\n- by rewrite !expnS leq_pmul2l ?IHn // ltnW.\n- by rewrite expn_gt0 ltnW.\nby rewrite leqNgt (leq_trans m_gt1) // expnS leq_pmulr // expn_gt0 ltnW.\nQed.\n\nLemma ltn_exp2l m n1 n2 : 1 < m -> (m ^ n1 < m ^ n2) = (n1 < n2).\nProof. by move=> m_gt1; rewrite !ltnNge leq_exp2l. Qed.\n\nLemma eqn_exp2l m n1 n2 : 1 < m -> (m ^ n1 == m ^ n2) = (n1 == n2).\nProof. by move=> m_gt1; rewrite !eqn_leq !leq_exp2l. Qed.\n\nLemma expnI m : 1 < m -> injective (expn m).\nProof. by move=> m_gt1 e1 e2 /eqP; rewrite eqn_exp2l // => /eqP. Qed.\n\nLemma leq_pexp2l m n1 n2 : 0 < m -> n1 <= n2 -> m ^ n1 <= m ^ n2.\nProof. by case: m => [|[|m]] // _; [rewrite !exp1n | rewrite leq_exp2l]. Qed.\n\nLemma ltn_pexp2l m n1 n2 : 0 < m -> m ^ n1 < m ^ n2 -> n1 < n2.\nProof. by case: m => [|[|m]] // _; [rewrite !exp1n | rewrite ltn_exp2l]. Qed.\n\nLemma ltn_exp2r m n e : e > 0 -> (m ^ e < n ^ e) = (m < n).\nProof.\nmove=> e_gt0; apply/idP/idP=> [|ltmn].\n  rewrite !ltnNge; apply: contra => lemn.\n  by elim: e {e_gt0} => // e IHe; rewrite !expnS leq_mul.\nby elim: e e_gt0 => // [[|e] IHe] _; rewrite ?expn1 // ltn_mul // IHe.\nQed.\n\nLemma leq_exp2r m n e : e > 0 -> (m ^ e <= n ^ e) = (m <= n).\nProof. by move=> e_gt0; rewrite leqNgt ltn_exp2r // -leqNgt. Qed.\n\nLemma eqn_exp2r m n e : e > 0 -> (m ^ e == n ^ e) = (m == n).\nProof. by move=> e_gt0; rewrite !eqn_leq !leq_exp2r. Qed.\n\nLemma expIn e : e > 0 -> injective (expn^~ e).\nProof. by move=> e_gt1 m n /eqP; rewrite eqn_exp2r // => /eqP. Qed.\n\n(* Factorial. *)\n\nFixpoint fact_rec n := if n is n'.+1 then n * fact_rec n' else 1.\n\nDefinition factorial := nosimpl fact_rec.\n\nNotation \"n `!\" := (factorial n) (at level 2, format \"n `!\") : nat_scope.\n\nLemma factE : factorial = fact_rec. Proof. by []. Qed.\n\nLemma fact0 : 0`! = 1. Proof. by []. Qed.\n\nLemma factS n : (n.+1)`!  = n.+1 * n`!. Proof. by []. Qed.\n\nLemma fact_gt0 n : n`! > 0.\nProof. by elim: n => //= n IHn; rewrite muln_gt0. Qed.\n\n(* Parity and bits. *)\n\nCoercion nat_of_bool (b : bool) := if b then 1 else 0.\n\nLemma leq_b1 (b : bool) : b <= 1. Proof. by case: b. Qed.\n\nLemma addn_negb (b : bool) : ~~ b + b = 1. Proof. by case: b. Qed.\n\nLemma eqb0 (b : bool) : (b == 0 :> nat) = ~~ b. Proof. by case: b. Qed.\n\nLemma eqb1 (b : bool) : (b == 1 :> nat) = b. Proof. by case: b. Qed.\n\nLemma lt0b (b : bool) : (b > 0) = b. Proof. by case: b. Qed.\n\nLemma sub1b (b : bool) : 1 - b = ~~ b. Proof. by case: b. Qed.\n\nLemma mulnb (b1 b2 : bool) : b1 * b2 = b1 && b2.\nProof. by case: b1; case: b2. Qed.\n\nLemma mulnbl (b : bool) n : b * n = (if b then n else 0).\nProof. by case: b; rewrite ?mul1n. Qed.\n\nLemma mulnbr (b : bool) n : n * b = (if b then n else 0).\nProof. by rewrite mulnC mulnbl. Qed.\n\nFixpoint odd n := if n is n'.+1 then ~~ odd n' else false.\n\nLemma oddb (b : bool) : odd b = b. Proof. by case: b. Qed.\n\nLemma odd_add m n : odd (m + n) = odd m (+) odd n.\nProof. by elim: m => [|m IHn] //=; rewrite -addTb IHn addbA addTb. Qed.\n\nLemma odd_sub m n : n <= m -> odd (m - n) = odd m (+) odd n.\nProof.\nby move=> le_nm; apply: (@canRL bool) (addbK _) _; rewrite -odd_add subnK.\nQed.\n\nLemma odd_opp i m : odd m = false -> i <= m -> odd (m - i) = odd i.\nProof. by move=> oddm le_im; rewrite (odd_sub (le_im)) oddm. Qed.\n\nLemma odd_mul m n : odd (m * n) = odd m && odd n.\nProof. by elim: m => //= m IHm; rewrite odd_add -addTb andb_addl -IHm. Qed.\n\nLemma odd_exp m n : odd (m ^ n) = (n == 0) || odd m.\nProof. by elim: n => // n IHn; rewrite expnS odd_mul {}IHn orbC; case odd. Qed.\n\n(* Doubling. *)\n\nFixpoint double_rec n := if n is n'.+1 then n'.*2%Nrec.+2 else 0\nwhere \"n .*2\" := (double_rec n) : nat_rec_scope.\n\nDefinition double := nosimpl double_rec.\nNotation \"n .*2\" := (double n) : nat_scope.\n\nLemma doubleE : double = double_rec. Proof. by []. Qed.\n\nLemma double0 : 0.*2 = 0. Proof. by []. Qed.\n\nLemma doubleS n : n.+1.*2 = n.*2.+2. Proof. by []. Qed.\n\nLemma addnn n : n + n = n.*2.\nProof. by apply: eqP; elim: n => // n IHn; rewrite addnS. Qed.\n\nLemma mul2n m : 2 * m = m.*2.\nProof. by rewrite mulSn mul1n addnn. Qed.\n\nLemma muln2 m : m * 2 = m.*2.\nProof. by rewrite mulnC mul2n. Qed.\n\nLemma doubleD m n : (m + n).*2 = m.*2 + n.*2.\nProof. by rewrite -!addnn -!addnA (addnCA n). Qed.\n\nLemma doubleB m n : (m - n).*2 = m.*2 - n.*2.\nProof. by elim: m n => [|m IHm] []. Qed.\n\nLemma leq_double m n : (m.*2 <= n.*2) = (m <= n).\nProof. by rewrite /leq -doubleB; case (m - n). Qed.\n\nLemma ltn_double m n : (m.*2 < n.*2) = (m < n).\nProof. by rewrite 2!ltnNge leq_double. Qed.\n\nLemma ltn_Sdouble m n : (m.*2.+1 < n.*2) = (m < n).\nProof. by rewrite -doubleS leq_double. Qed.\n\nLemma leq_Sdouble m n : (m.*2 <= n.*2.+1) = (m <= n).\nProof. by rewrite leqNgt ltn_Sdouble -leqNgt. Qed.\n\nLemma odd_double n : odd n.*2 = false.\nProof. by rewrite -addnn odd_add addbb. Qed.\n\nLemma double_gt0 n : (0 < n.*2) = (0 < n).\nProof. by case: n. Qed.\n\nLemma double_eq0 n : (n.*2 == 0) = (n == 0).\nProof. by case: n. Qed.\n\nLemma doubleMl m n : (m * n).*2 = m.*2 * n.\nProof. by rewrite -!mul2n mulnA. Qed.\n\nLemma doubleMr m n : (m * n).*2 = m * n.*2.\nProof. by rewrite -!muln2 mulnA. Qed.\n\n(* Halving. *)\n\nFixpoint half (n : nat) : nat := if n is n'.+1 then uphalf n' else n\nwith   uphalf (n : nat) : nat := if n is n'.+1 then n'./2.+1 else n\nwhere \"n ./2\" := (half n) : nat_scope.\n\nLemma doubleK : cancel double half.\nProof. by elim=> //= n ->. Qed.\n\nDefinition half_double := doubleK.\nDefinition double_inj := can_inj doubleK.\n\nLemma uphalf_double n : uphalf n.*2 = n.\nProof. by elim: n => //= n ->. Qed.\n\nLemma uphalf_half n : uphalf n = odd n + n./2.\nProof. by elim: n => //= n ->; rewrite addnA addn_negb. Qed.\n\nLemma odd_double_half n : odd n + n./2.*2 = n.\nProof.\nby elim: n => //= n {3}<-; rewrite uphalf_half doubleD; case (odd n).\nQed.\n\nLemma half_bit_double n (b : bool) : (b + n.*2)./2 = n.\nProof. by case: b; rewrite /= (half_double, uphalf_double). Qed.\n\nLemma halfD m n : (m + n)./2 = (odd m && odd n) + (m./2 + n./2).\nProof.\nrewrite -{1}[n]odd_double_half addnCA -{1}[m]odd_double_half -addnA -doubleD.\nby do 2!case: odd; rewrite /= ?add0n ?half_double ?uphalf_double.\nQed.\n\nLemma half_leq m n : m <= n -> m./2 <= n./2.\nProof. by move/subnK <-; rewrite halfD addnA leq_addl. Qed.\n\nLemma half_gt0 n : (0 < n./2) = (1 < n).\nProof. by case: n => [|[]]. Qed.\n\nLemma odd_geq m n : odd n -> (m <= n) = (m./2.*2 <= n).\nProof.\nmove=> odd_n; rewrite -{1}[m]odd_double_half -[n]odd_double_half odd_n.\nby case: (odd m); rewrite // leq_Sdouble ltnS leq_double.\nQed.\n\nLemma odd_ltn m n : odd n -> (n < m) = (n < m./2.*2).\nProof. by move=> odd_n; rewrite !ltnNge odd_geq. Qed.\n\nLemma odd_gt0 n : odd n -> n > 0. Proof. by case: n. Qed.\n\nLemma odd_gt2 n : odd n -> n > 1 -> n > 2.\nProof. by move=> odd_n n_gt1; rewrite odd_geq. Qed.\n\n(* Squares and square identities. *)\n\nLemma mulnn m : m * m = m ^ 2.\nProof. by rewrite !expnS muln1. Qed.\n\nLemma sqrnD m n : (m + n) ^ 2 = m ^ 2 + n ^ 2 + 2 * (m * n).\nProof.\nrewrite -!mulnn mul2n mulnDr !mulnDl (mulnC n) -!addnA.\nby congr (_ + _); rewrite addnA addnn addnC.\nQed.\n\nLemma sqrn_sub m n : n <= m -> (m - n) ^ 2 = m ^ 2 + n ^ 2 - 2 * (m * n).\nProof.\nmove/subnK=> def_m; rewrite -{2}def_m sqrnD -addnA addnAC.\nby rewrite -2!addnA addnn -mul2n -mulnDr -mulnDl def_m addnK.\nQed.\n\nLemma sqrnD_sub m n : n <= m -> (m + n) ^ 2 - 4 * (m * n) = (m - n) ^ 2.\nProof.\nmove=> le_nm; rewrite -[4]/(2 * 2) -mulnA mul2n -addnn subnDA.\nby rewrite sqrnD addnK sqrn_sub.\nQed.\n\nLemma subn_sqr m n : m ^ 2 - n ^ 2 = (m - n) * (m + n).\nProof. by rewrite mulnBl !mulnDr addnC (mulnC m) subnDl !mulnn. Qed.\n\nLemma ltn_sqr m n : (m ^ 2 < n ^ 2) = (m < n).\nProof. by rewrite ltn_exp2r. Qed.\n\nLemma leq_sqr m n : (m ^ 2 <= n ^ 2) = (m <= n).\nProof. by rewrite leq_exp2r. Qed.\n\nLemma sqrn_gt0 n : (0 < n ^ 2) = (0 < n).\nProof. exact: (ltn_sqr 0). Qed.\n\nLemma eqn_sqr m n : (m ^ 2 == n ^ 2) = (m == n).\nProof. by rewrite eqn_exp2r. Qed.\n\nLemma sqrn_inj : injective (expn ^~ 2).\nProof. exact: expIn. Qed.\n\n(* Almost strict inequality: an inequality that is strict unless some    *)\n(* specific condition holds, such as the Cauchy-Schwartz or the AGM      *)\n(* inequality (we only prove the order-2 AGM here; the general one       *)\n(* requires sequences).                                                  *)\n(*   We formalize the concept as a rewrite multirule, that can be used   *)\n(* both to rewrite the non-strict inequality to true, and the equality   *)\n(* to the specific condition (for strict inequalities use the ltn_neqAle *)\n(* lemma); in addition, the conditional equality also coerces to a       *)\n(* non-strict one.                                                       *)\n\nDefinition leqif m n C := ((m <= n) * ((m == n) = C))%type.\n\nNotation \"m <= n ?= 'iff' C\" := (leqif m n C) : nat_scope.\n\nCoercion leq_of_leqif m n C (H : m <= n ?= iff C) := H.1 : m <= n.\n\nLemma leqifP m n C : reflect (m <= n ?= iff C) (if C then m == n else m < n).\nProof.\nrewrite ltn_neqAle; apply: (iffP idP) => [|lte]; last by rewrite !lte; case C.\nby case C => [/eqP-> | /andP[/negPf]]; split=> //; apply: eqxx.\nQed.\n\nLemma leqif_refl m C : reflect (m <= m ?= iff C) C.\nProof. by apply: (iffP idP) => [-> | <-] //; split; rewrite ?eqxx. Qed.\n\nLemma leqif_trans m1 m2 m3 C12 C23 :\n  m1 <= m2 ?= iff C12 -> m2 <= m3 ?= iff C23 -> m1 <= m3 ?= iff C12 && C23.\nProof.\nmove=> ltm12 ltm23; apply/leqifP; rewrite -ltm12.\ncase eqm12: (m1 == m2).\n  by rewrite (eqP eqm12) ltn_neqAle !ltm23 andbT; case C23.\nby rewrite (@leq_trans m2) ?ltm23 // ltn_neqAle eqm12 ltm12.\nQed.\n\nLemma mono_leqif f : {mono f : m n / m <= n} ->\n  forall m n C, (f m <= f n ?= iff C) = (m <= n ?= iff C).\nProof. by move=> f_mono m n C; rewrite /leqif !eqn_leq !f_mono. Qed.\n\nLemma leqif_geq m n : m <= n -> m <= n ?= iff (m >= n).\nProof. by move=> lemn; split=> //; rewrite eqn_leq lemn. Qed.\n\nLemma leqif_eq m n : m <= n -> m <= n ?= iff (m == n).\nProof. by []. Qed.\n\nLemma geq_leqif a b C : a <= b ?= iff C -> (b <= a) = C.\nProof. by case=> le_ab; rewrite eqn_leq le_ab. Qed.\n\nLemma ltn_leqif a b C : a <= b ?= iff C -> (a < b) = ~~ C.\nProof. by move=> le_ab; rewrite ltnNge (geq_leqif le_ab). Qed.\n\nLemma leqif_add m1 n1 C1 m2 n2 C2 :\n    m1 <= n1 ?= iff C1 -> m2 <= n2 ?= iff C2 ->\n  m1 + m2 <= n1 + n2 ?= iff C1 && C2.\nProof.\nrewrite -(mono_leqif (leq_add2r m2)) -(mono_leqif (leq_add2l n1) m2).\nexact: leqif_trans.\nQed.\n\nLemma leqif_mul m1 n1 C1 m2 n2 C2 :\n    m1 <= n1 ?= iff C1 -> m2 <= n2 ?= iff C2 ->\n  m1 * m2 <= n1 * n2 ?= iff (n1 * n2 == 0) || (C1 && C2).\nProof.\ncase: n1 => [|n1] le1; first by case: m1 le1 => [|m1] [_ <-] //.\ncase: n2 m2 => [|n2] [|m2] /=; try by case=> // _ <-; rewrite !muln0 ?andbF.\nhave /leq_pmul2l-/mono_leqif<-: 0 < n1.+1 by [].\nby apply: leqif_trans; have /leq_pmul2r-/mono_leqif->: 0 < m2.+1.\nQed.\n\nLemma nat_Cauchy m n : 2 * (m * n) <= m ^ 2 + n ^ 2 ?= iff (m == n).\nProof.\nwithout loss le_nm: m n / n <= m.\n  by case: (leqP m n); auto; rewrite eq_sym addnC (mulnC m); auto.\napply/leqifP; case: ifP => [/eqP-> | ne_mn]; first by rewrite mulnn addnn mul2n.\nby rewrite -subn_gt0 -sqrn_sub // sqrn_gt0 subn_gt0 ltn_neqAle eq_sym ne_mn.\nQed.\n\nLemma nat_AGM2 m n : 4 * (m * n) <= (m + n) ^ 2 ?= iff (m == n).\nProof.\nrewrite -[4]/(2 * 2) -mulnA mul2n -addnn sqrnD; apply/leqifP.\nby rewrite ltn_add2r eqn_add2r ltn_neqAle !nat_Cauchy; case: ifP => ->.\nQed.\n\n(* Support for larger integers. The normal definitions of +, - and even  *)\n(* IO are unsuitable for Peano integers larger than 2000 or so because   *)\n(* they are not tail-recursive. We provide a workaround module, along    *)\n(* with a rewrite multirule to change the tailrec operators to the       *)\n(* normal ones. We handle IO via the NatBin module, but provide our      *)\n(* own (more efficient) conversion functions.                            *)\n\nModule NatTrec.\n\n(*   Usage:                                             *)\n(*     Import NatTrec.                                  *)\n(*        in section definining functions, rebinds all  *)\n(*        non-tail recursive operators.                 *)\n(*     rewrite !trecE.                                  *)\n(*        in the correctness proof, restores operators  *)\n\nFixpoint add m n := if m is m'.+1 then m' + n.+1 else n\nwhere \"n + m\" := (add n m) : nat_scope.\n\nFixpoint add_mul m n s := if m is m'.+1 then add_mul m' n (n + s) else s.\n\nDefinition mul m n := if m is m'.+1 then add_mul m' n n else 0.\n\nNotation \"n * m\" := (mul n m) : nat_scope.\n\nFixpoint mul_exp m n p := if n is n'.+1 then mul_exp m n' (m * p) else p.\n\nDefinition exp m n := if n is n'.+1 then mul_exp m n' m else 1.\n\nNotation \"n ^ m\" := (exp n m) : nat_scope.\n\nLocal Notation oddn := odd.\nFixpoint odd n := if n is n'.+2 then odd n' else eqn n 1.\n\nLocal Notation doublen := double.\nDefinition double n := if n is n'.+1 then n' + n.+1 else 0.\nNotation \"n .*2\" := (double n) : nat_scope.\n\nLemma addE : add =2 addn.\nProof. by elim=> //= n IHn m; rewrite IHn addSnnS. Qed.\n\nLemma doubleE : double =1 doublen.\nProof. by case=> // n; rewrite -addnn -addE. Qed.\n\nLemma add_mulE n m s : add_mul n m s = addn (muln n m) s.\nProof. by elim: n => //= n IHn in m s *; rewrite IHn addE addnCA addnA. Qed.\n\nLemma mulE : mul =2 muln.\nProof. by case=> //= n m; rewrite add_mulE addnC. Qed.\n\nLemma mul_expE m n p : mul_exp m n p = muln (expn m n) p.\nProof.\nby elim: n => [|n IHn] in p *; rewrite ?mul1n //= expnS IHn mulE mulnCA mulnA.\nQed.\n\nLemma expE : exp =2 expn.\nProof. by move=> m [|n] //=; rewrite mul_expE expnS mulnC. Qed.\n\nLemma oddE : odd =1 oddn.\nProof.\nmove=> n; rewrite -{1}[n]odd_double_half addnC.\nby elim: n./2 => //=; case (oddn n).\nQed.\n\nDefinition trecE := (addE, (doubleE, oddE), (mulE, add_mulE, (expE, mul_expE))).\n\nEnd NatTrec.\n\nNotation natTrecE := NatTrec.trecE.\n\nLemma eq_binP : Equality.axiom N.eqb.\nProof.\nmove=> p q; apply: (iffP idP) => [|<-]; last by case: p => //; elim.\nby case: q; case: p => //; elim=> [p IHp|p IHp|] [q|q|] //=; case/IHp=> ->.\nQed.\n\nCanonical bin_nat_eqMixin := EqMixin eq_binP.\nCanonical bin_nat_eqType := Eval hnf in EqType N bin_nat_eqMixin.\n\nArguments N.eqb !n !m.\n\nSection NumberInterpretation.\n\nImport BinPos.\n\nSection Trec.\n\nImport NatTrec.\n\nFixpoint nat_of_pos p0 :=\n  match p0 with\n  | xO p => (nat_of_pos p).*2\n  | xI p => (nat_of_pos p).*2.+1\n  | xH   => 1\n  end.\n\nEnd Trec.\n\nLocal Coercion nat_of_pos : positive >-> nat.\n\nCoercion nat_of_bin b := if b is Npos p then p : nat else 0.\n\nFixpoint pos_of_nat n0 m0 :=\n  match n0, m0 with\n  | n.+1, m.+2 => pos_of_nat n m\n  | n.+1,    1 => xO (pos_of_nat n n)\n  | n.+1,    0 => xI (pos_of_nat n n)\n  |    0,    _ => xH\n  end.\n\nDefinition bin_of_nat n0 := if n0 is n.+1 then Npos (pos_of_nat n n) else 0%num.\n\nLemma bin_of_natK : cancel bin_of_nat nat_of_bin.\nProof.\nhave sub2nn n : n.*2 - n = n by rewrite -addnn addKn.\ncase=> //= n; rewrite -{3}[n]sub2nn.\nby elim: n {2 4}n => // m IHm [|[|n]] //=; rewrite IHm // natTrecE sub2nn.\nQed.\n\nLemma nat_of_binK : cancel nat_of_bin bin_of_nat.\nProof.\ncase=> //=; elim=> //= p; case: (nat_of_pos p) => //= n [<-].\n  by rewrite natTrecE !addnS {2}addnn; elim: {1 3}n.\nby rewrite natTrecE addnS /= addnS {2}addnn; elim: {1 3}n.\nQed.\n\nLemma nat_of_succ_gt0 p : Pos.succ p = p.+1 :> nat.\nProof. by elim: p => //= p ->; rewrite !natTrecE. Qed.\n\nLemma nat_of_addn_gt0 p q : (p + q)%positive = p + q :> nat.\nProof.\napply: @fst _ (Pplus_carry p q = (p + q).+1 :> nat) _.\nelim: p q => [p IHp|p IHp|] [q|q|] //=; rewrite !natTrecE //;\n  by rewrite ?IHp ?nat_of_succ_gt0 ?(doubleS, doubleD, addn1, addnS).\nQed.\n\nLemma nat_of_add_bin b1 b2 : (b1 + b2)%num = b1 + b2 :> nat.\nProof. by case: b1 b2 => [|p] [|q] //=; apply: nat_of_addn_gt0. Qed.\n\nLemma nat_of_mul_bin b1 b2 : (b1 * b2)%num = b1 * b2 :> nat.\nProof.\ncase: b1 b2 => [|p] [|q] //=; elim: p => [p IHp|p IHp|] /=;\n  by rewrite ?(mul1n, nat_of_addn_gt0, mulSn) //= !natTrecE IHp doubleMl.\nQed.\n\nLemma nat_of_exp_bin n (b : N) : n ^ b = pow_N 1 muln n b.\nProof.\nby case: b; last (elim=> //= p <-; rewrite natTrecE mulnn -expnM muln2 ?expnS).\nQed.\n\nEnd NumberInterpretation.\n\n(* Big(ger) nat IO; usage:                              *)\n(*     Num 1 072 399                                    *)\n(*        to create large numbers for test cases        *)\n(* Eval compute in [Num of some expression]             *)\n(*        to display the resut of an expression that    *)\n(*        returns a larger integer.                     *)\n\nRecord number : Type := Num {bin_of_number :> N}.\n\nDefinition extend_number (nn : number) m := Num (nn * 1000 + bin_of_nat m).\n\nCoercion extend_number : number >-> Funclass.\n\nCanonical number_subType := [newType for bin_of_number].\nDefinition number_eqMixin := Eval hnf in [eqMixin of number by <:].\nCanonical number_eqType := Eval hnf in EqType number number_eqMixin.\n\nNotation \"[ 'Num' 'of' e ]\" := (Num (bin_of_nat e))\n  (at level 0, format \"[ 'Num'  'of'  e ]\") : nat_scope.\n\n(* Interface to ring/ring_simplify tactics *)\n\nLemma nat_semi_ring : semi_ring_theory 0 1 addn muln (@eq _).\nProof. exact: mk_srt add0n addnC addnA mul1n mul0n mulnC mulnA mulnDl. Qed.\n\nLemma nat_semi_morph :\n  semi_morph 0 1 addn muln (@eq _) 0%num 1%num Nplus Nmult pred1 nat_of_bin.\nProof.\nby move: nat_of_add_bin nat_of_mul_bin; split=> //= m n; move/eqP->.\nQed.\n\nLemma nat_power_theory : power_theory 1 muln (@eq _) nat_of_bin expn.\nProof. by split; apply: nat_of_exp_bin. Qed.\n\n(* Interface to the ring tactic machinery. *)\n\nFixpoint pop_succn e := if e is e'.+1 then fun n => pop_succn e' n.+1 else id.\n\nLtac pop_succn e := eval lazy beta iota delta [pop_succn] in (pop_succn e 1).\n\nLtac nat_litteral e :=\n  match pop_succn e with\n  | ?n.+1 => constr: (bin_of_nat n)\n  |     _ => NotConstant\n  end.\n\nLtac succn_to_add :=\n  match goal with\n  | |- context G [?e.+1] =>\n    let x := fresh \"NatLit0\" in\n    match pop_succn e with\n    | ?n.+1 => pose x := n.+1; let G' := context G [x] in change G'\n    | _ ?e' ?n => pose x := n; let G' := context G [x + e'] in change G'\n    end; succn_to_add; rewrite {}/x\n  | _ => idtac\n  end.\n\nAdd Ring nat_ring_ssr : nat_semi_ring (morphism nat_semi_morph,\n   constants [nat_litteral], preprocess [succn_to_add],\n   power_tac nat_power_theory [nat_litteral]).\n\n(* A congruence tactic, similar to the boolean one, along with an .+1/+  *)\n(* normalization tactic.                                                 *)\n\n\nLtac nat_norm :=\n  succn_to_add; rewrite ?add0n ?addn0 -?addnA ?(addSn, addnS, add0n, addn0).\n\nLtac nat_congr := first\n [ apply: (congr1 succn _)\n | apply: (congr1 predn _)\n | apply: (congr1 (addn _) _)\n | apply: (congr1 (subn _) _)\n | apply: (congr1 (addn^~ _) _)\n | match goal with |- (?X1 + ?X2 = ?X3) =>\n     symmetry;\n     rewrite -1?(addnC X1) -?(addnCA X1);\n     apply: (congr1 (addn X1) _);\n     symmetry\n   end ].\n", "meta": {"author": "palmskog", "repo": "mathcomp-experiment", "sha": "67a6e83c025784b1e6f646a30dde38e0f33060eb", "save_path": "github-repos/coq/palmskog-mathcomp-experiment", "path": "github-repos/coq/palmskog-mathcomp-experiment/mathcomp-experiment-67a6e83c025784b1e6f646a30dde38e0f33060eb/ssreflect/ssrnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.709739174827468}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Binary relations                                                        *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic LibBool LibLogic LibProd LibSum.\nRequire Export LibOperation.\n\n\n(* ********************************************************************** *)\n(** * Generalities on binary relations *)\n\nDefinition binary (A : Type) := A -> A -> Prop.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inhabited *)\n\nInstance binary_inhab : forall A, Inhab (binary A).\nProof. intros. apply (prove_Inhab (fun _ _ => True)). Qed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Extensionality *)\n\nLemma binary_extensional : forall A (R1 R2:binary A),\n  (forall x y, R1 x y <-> R2 x y) -> R1 = R2.\nProof. intros_all. apply~ prop_ext_2. Qed.\n\nInstance binary_extensional_inst : forall A, Extensional (binary A).\nProof. intros. apply (Build_Extensional _ (@binary_extensional A)). Defined.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nSection Properties.\nVariables (A:Type).\nImplicit Types x y z : A.\nImplicit Types R : binary A.\n\n(** Reflexivity, irreflexivity, transitivity, symmetry, totality, definedness, functionality *)\n\nDefinition refl R := \n  forall x, R x x.\nDefinition irrefl R := \n  forall x, ~ (R x x).\nDefinition trans R := \n  forall y x z, R x y -> R y z -> R x z.\nDefinition sym R := \n  forall x y, R x y -> R y x.\nDefinition asym R := \n  forall x y, R x y -> ~ R y x.\nDefinition total R :=\n  forall x y, R x y \\/ R y x.\nDefinition defined R :=\n  forall x, exists y, R x y.\n  (* I would have liked to call this [total R], but this already\n     means something else... *)\nDefinition functional R :=\n  forall x y z, R x y -> R x z -> y = z.\n\n(** Antisymmetry with respect to an equivalence relation, \n    antisymmetry with respect to Leibnitz equality,\n     i.e. [forall x y, R x y -> R y x -> x = y] *)\n\nDefinition antisym_wrt (E:binary A) R :=\n  forall x y, R x y -> R y x -> E x y.\nDefinition antisym := \n  antisym_wrt (@eq A).\n\n(** Inclusion between relations *)\n\nDefinition incl R1 R2 :=\n  forall x y, R1 x y -> R2 x y.\n\n(** Equality between relations *)\n\n(* TODO move further down in the file *)\n(* TODO already called binary_extensional above? *)\nLemma rel_eq_intro : forall R1 R2,\n  (forall x y, R1 x y <-> R2 x y) -> R1 = R2.\nProof. intros. extens*. Qed.\n\nLemma rel_eq_elim : forall R1 R2,\n  R1 = R2 -> (forall x y, R1 x y <-> R2 x y).\nProof. intros. subst*. Qed.\n\nEnd Properties.\n\n\n(** Inclusion between a function and a relation. *)\n(* TODO: maybe use longer name? *)\n\nDefinition incl_fr A B (f : A -> B) (R : A -> B -> Prop) :=\n  forall x, R x (f x).\nDefinition incl_rf A B (R : A -> B -> Prop) (f : A -> B) :=\n  forall x y, R x y -> y = f x.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Constructions *)\n\nSection Constructions.\nVariable (A : Type).\nImplicit Types R : binary A.\nImplicit Types x y z : A.\n\n(** The empty relation *)\n\nDefinition empty : binary A :=\n  fun x y => False.\n\n(** Swap (i.e. symmetric, converse, or transpose) of a relation *)\n \nDefinition flip R : binary A := \n  fun x y => R y x.\n\n(** Complement of a relation *)\n \nDefinition compl R : binary A := \n  fun x y => ~ R y x.\n\n(** Union of two relations *)\n\nDefinition union R1 R2 : binary A :=\n  fun x y => R1 x y \\/ R2 x y.\n\n(** Strict order associated with an order, wrt Leibnitz' equality *)\n\nDefinition strict R : binary A :=\n  fun x y => R x y /\\ x <> y.\n\n(** Large order associated with an order, wrt Leibnitz' equality *)\n\nDefinition large R : binary A :=\n  fun x y => R x y \\/ x = y.\n\nEnd Constructions.\n\n(** Inverse image *)\n\nDefinition inverse_image (A B:Type) (R:binary B) (f:A->B) : binary A :=\n  fun x y => R (f x) (f y).\n\n(** Composition of two relations, usually written [R1; R2]. *)\n\nDefinition sequence (A B C:Type) (R1:A->B->Prop) (R2:B->C->Prop) : A->C->Prop :=\n  fun x z => exists y, R1 x y /\\ R2 y z.\n\n(** Pointwise product *)\n\nDefinition prod2 (A1 A2:Type) \n (R1:binary A1) (R2:binary A2) : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => match p1,p2 with (x1,x2),(y1,y2) => \n    R1 x1 y1 /\\ R2 x2 y2 end.\n\nDefinition prod3 (A1 A2 A3:Type) \n (R1:binary A1) (R2:binary A2) (R3:binary A3) \n : binary (A1*A2*A3) := \n  prod2 (prod2 R1 R2) R3.\n\nDefinition prod4 (A1 A2 A3 A4:Type) \n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4) \n : binary (A1*A2*A3*A4) := \n  prod2 (prod3 R1 R2 R3) R4.\n\nTactic Notation \"unfold_prod\" :=\n  unfold prod4, prod3, prod2.\n\nTactic Notation \"unfolds_prod\" :=\n  unfold prod4, prod3, prod2 in *.\n\n(** Lexicographical order *)\n\nDefinition lexico2 {A1 A2} (R1:binary A1) (R2:binary A2)\n  : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => let (x1,x2) := p1 in let (y1,y2) := p2 in\n  (R1 x1 y1) \\/ (x1 = y1) /\\ (R2 x2 y2).\n\nDefinition lexico3 {A1 A2 A3} \n (R1:binary A1) (R2:binary A2) (R3:binary A3) : binary (A1*A2*A3) :=\n  lexico2 (lexico2 R1 R2) R3.\n\nDefinition lexico4 {A1 A2 A3 A4}\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4) \n : binary (A1*A2*A3*A4) :=\n  lexico2 (lexico3 R1 R2 R3) R4.\n\nTactic Notation \"unfold_lexico\" :=\n  unfold lexico4, lexico3, lexico2.\n\nTactic Notation \"unfolds_lexico\" :=\n  unfold lexico4, lexico3, lexico2 in *.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of constructions *)\n\nSection ConstructionsProp.\nVariable (A : Type).\nImplicit Types R : binary A.\nImplicit Types x y z : A.\n\nLemma refl_elim : forall x y R,\n  refl R -> x = y -> R x y.\nProof. intros_all. subst~. Qed.\n\nLemma sym_elim : forall x y R,\n  sym R -> R x y -> R y x.\nProof. introv Sy R1. apply* Sy. Qed.\n\nLemma antisym_elim : forall x y R,\n  antisym R -> R x y -> R y x -> x <> y -> False.\nProof. intros_all*. Qed.\n\nLemma irrefl_neq : forall R,\n  irrefl R -> \n  forall x y, R x y -> x <> y. \nProof. introv H P E. subst. apply* H. Qed.\n\nLemma irrefl_elim : forall R,\n  irrefl R -> \n  forall x, R x x -> False. \nProof. introv H P. apply* H. Qed.\n\nLemma sym_to_eq : forall R,\n  sym R -> \n  forall x y, R x y = R y x.\nProof. introv H. intros. apply prop_ext. split; apply H. Qed.\n\nLemma sym_flip : forall R,\n  sym R -> flip R = R.\nProof. intros. unfold flip. apply* prop_ext_2. Qed.\n\nLemma trans_strict : forall R,\n  trans R -> antisym R -> trans (strict R).\nProof. \n  introv T S. unfold strict. introv [H1 H2] [H3 H4]. split. \n    apply* T.\n    intros K. subst. apply H2. apply~ S.\nQed.\n\nLemma flip_flip : forall R, \n  flip (flip R) = R.\nProof. intros. apply* prop_ext_2. Qed.\n\nLemma flip_refl : forall R,\n  refl R -> refl (flip R).\nProof. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_trans : forall R,\n  trans R -> trans (flip R).\nProof. intros_all. unfolds flip. eauto. Qed.\n\nLemma flip_antisym : forall R,\n  antisym R -> antisym (flip R).\nProof. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_asym : forall R,\n  asym R -> asym (flip R).\nProof. intros_all. unfolds flip. apply* H. Qed.\n\nLemma flip_total : forall R,\n  total R -> total (flip R).\nProof. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_strict : forall R,\n  flip (strict R) = strict (flip R).\nProof. intros. unfold flip, strict. apply* prop_ext_2. Qed.\n\nLemma flip_large : forall R,\n  flip (large R) = large (flip R).\nProof. intros. unfold flip, large. apply* prop_ext_2. Qed.\n\nLemma large_refl : forall R,\n  refl (large R).\nProof. unfold large. intros_all~. Qed.\n\nLemma large_trans : forall R,\n  trans R -> trans (large R).\nProof. unfold large. introv Tr [H1|E1] [H2|E2]; subst*. Qed.\n\nLemma large_antisym : forall R,\n  antisym R -> antisym (large R).\nProof. introv T. introv H1 H2. (* todo: bug introv *)\n  unfolds large. destruct H1; destruct H2; auto. Qed.\n\nLemma large_total : forall R,\n  total R -> total (large R).\nProof. unfold large. intros_all~. destruct* (H x y). Qed.\n\nLemma strict_large : forall R,\n  irrefl R -> strict (large R) = R.\nProof.\n  intros. unfold large, strict. apply prop_ext_2.\n  intros_all. split; intros K.\n  autos*.\n  split. left*. apply* irrefl_neq. \nQed.\n\nLemma large_strict : forall R,\n  refl R -> large (strict R) = R.\nProof. \n  intros. unfold large, strict. apply prop_ext_2. \n  intros_all. split; intros K.\n  destruct K. autos*. subst*.\n  destruct (classic (x1 = x2)). subst. right*. left*.\n  (* todo: cases *)\nQed.\n\nLemma double_incl : forall R1 R2,\n  incl R1 R2 -> incl R2 R1 -> R1 = R2.\nProof. unfolds incl. intros. apply* prop_ext_2. Qed. \n\nLemma rel_incl_trans : forall R1 R2 R3,\n  incl R1 R2 -> incl R2 R3 -> incl R1 R3.\nProof.\n  unfold incl. eauto.\nQed.\n\nLemma flip_injective : injective (@flip A).\nProof.\n  intros R1 R2 E. apply prop_ext_2. intros x y.\n  unfolds flip. rewrite* (func_same_2 y x E).\nQed.\n\nLemma eq_by_flip_l : forall R1 R2,\n  R1 = flip R2 -> flip R1 = R2.\nProof. intros. apply flip_injective. rewrite~ flip_flip. Qed.\n\nLemma eq_by_flip_r : forall R1 R2,\n  flip R1 = R2 -> R1 = flip R2.\nProof. intros. apply flip_injective. rewrite~ flip_flip. Qed.\n\n(* TODO: do we really need this extensional version? *)\n\nLemma flip_flip_applied : forall R x y, \n  (flip (flip R)) x y = R x y.\nProof. auto. Qed.\n\nEnd ConstructionsProp.\n\nLemma trans_elim : forall A (y x z : A) R,\n  trans R -> R x y -> R y z -> R x z.\nProof. introv Tr R1 R2. apply* Tr. Qed.\n\nLemma trans_sym : forall A (y x z : A) R,\n  trans R -> sym R -> R z y -> R y x -> R x z.\nProof. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_1 : forall A (y x z : A) R,\n  trans R -> sym R -> R y x -> R y z -> R x z.\nProof. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_2 : forall A (y x z : A) R,\n  trans R -> sym R -> R x y -> R z y -> R x z.\nProof. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nImplicit Arguments trans_elim [A x z R].\nImplicit Arguments trans_sym [A x z R].\nImplicit Arguments trans_sym_1 [A x z R].\nImplicit Arguments trans_sym_2 [A x z R].\n\n(** Other forms of transitivity *)\n\nLemma large_strict_trans : forall A y x z (R:binary A),\n  trans R -> large R x y -> R y z -> R x z.\nProof. introv T [E|H] H'; subst*. Qed.\n\nLemma strict_large_trans : forall A y x z (R:binary A),\n  trans R -> R x y -> large R y z -> R x z.\nProof. introv T H [E|H']; subst*. Qed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties about [functional] *)\n\n(* A relation [R] is functional if and only if [flip R] composed\n   with [R] is a subset of the diagonal relation [eq]. *)\n\nLemma functional_characterization : forall A (R : binary A),\n  functional R <->\n  incl (sequence (flip R) R) eq.\nProof.\n  unfold functional, incl, sequence, flip.\n  split.\n    introv ? [ ? [ ? ? ]]. eauto.\n    eauto.\nQed.\n\n(* The empty relation is functional. *)\n\nLemma functional_empty : forall A,\n  functional (@empty A).\nProof.\n  unfold empty. repeat intro. tauto.\nQed.\n\n(* TODO: a tactic \"functional_exploit R\" that looks for two distinct\n   assumptions in the goal of the form [R ?x ?y] and produces [functional R]\n   as subgoal. *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties about [union] *)\n\n(* TODO: rename lemmas *)\n\nLemma prove_rel_union_left : forall A (R1 R2 : binary A) x y,\n  R1 x y ->\n  union R1 R2 x y.\nProof.\n  unfold union. eauto.\nQed.\n\nLemma prove_rel_union_right : forall A (R1 R2 : binary A) x y,\n  R2 x y ->\n  union R1 R2 x y.\nProof.\n  unfold union. eauto.\nQed.\n\nLemma union_covariant : forall A (R1 R2 S1 S2 : binary A),\n  incl R1 S1 ->\n  incl R2 S2 ->\n  incl (union R1 R2) (union S1 S2).\nProof.\n  unfold incl, union. intuition eauto.\nQed.\n\nLemma union_refl_left : forall A (R S : binary A),\n  refl R ->\n  refl (union R S).\nProof.\n  unfold refl, union. eauto.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of inclusion *)\n\n(* TODO change hypothesis names in proofs *)\n(* TODO decide whether to use a tactic exploit functional *)\n\n(* TODO there is something by the same name in [LibBag]. *)\nLemma incl_refl : forall A (R:binary A), incl R R.\nProof. unfolds incl. auto. Qed.\n\nHint Resolve incl_refl. \n\nLemma lexico2_incl : forall A1 A2\n (R1 R1':binary A1) (R2 R2':binary A2),\n  incl R1 R1' -> incl R2 R2' -> incl (lexico2 R1 R2) (lexico2 R1' R2').\nProof. \n  introv I1 I2. intros [x1 x2] [y1 y2] [H1|[H1 H2]].\n  left~. subst. right~.\nQed.\n\n(* If [R] is defined, [S] is functional, and [R] is a subset of [S],\n   then [R] equals [S]. In that case, [R] and [S] represent the graph\n   of a total function. *)\n\nLemma defined_incl_functional:\n  forall (A : Type) (R S : binary A),\n  defined R ->\n  functional S ->\n  incl R S ->\n  R = S.\nProof.\n  introv hdef hfun hincl. eapply binary_extensional. intros v w. split; intros H; eauto.\n  forwards [ w' M1 ]: hdef v.\n  forwards M2: hincl. eauto.\n  forwards: hfun H M2. subst*.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion between a function and a relation. *)\n\n(* If the relation [R] is functional and if [f] is included in [R],\n   then [R] is included in [f], i.e., they coincide. *)\n\n(* TODO: currently limited to the case where B = A, but it shouldn't be *)\n\nLemma incl_fr_functional:\n  forall A (f : A -> A) (R : A -> A -> Prop),\n  incl_fr f R ->\n  functional R ->\n  incl_rf R f.\nProof.\n  introv h1 h2. intros a b H. forwards M: h1 a. forwards*: h2 H M.\nQed.\n\n(* Note: [incl_fr f R] implies [defined R]\n         [incl_rf R f] implies [functional R] *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of lexicographical composition *)\n\nSection LexicoApp.\nVariables (A1 A2 A3 A4:Type). \nVariables (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4). \n\nLemma lexico2_app_1 : forall x1 x2 y1 y2,\n  R1 x1 y1 -> \n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof. intros. left~. Qed.\n\nLemma lexico2_app_2 : forall x1 x2 y1 y2,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof. intros. right~. Qed.\n\nLemma lexico3_app_1 : forall x1 x2 x3 y1 y2 y3,\n  R1 x1 y1 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof. intros. left. left~. Qed.\n\nLemma lexico3_app_2 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof. intro. left. right~. Qed.\n\nLemma lexico3_app_3 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 -> x2 = y2 -> R3 x3 y3 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof. intros. right~. Qed.\n\nLemma lexico4_app_1 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  R1 x1 y1 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof. intros. left. left. left~. Qed.\n\nLemma lexico4_app_2 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof. intros. left. left. right~. Qed.\n\nLemma lexico4_app_3 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> x2 = y2 -> R3 x3 y3 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof. intros. left. right~. Qed.\n\nLemma lexico4_app_4 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> x2 = y2 -> x3 = y3 -> R4 x4 y4 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof. intros. right~. Qed.\n\nEnd LexicoApp.\n\n(** Transitivity *)\n\nLemma lexico2_trans : forall A1 A2 \n (R1:binary A1) (R2:binary A2),\n  trans R1 -> trans R2 -> trans (lexico2 R1 R2).\nProof.\n  introv Tr1 Tr2. intros [x1 x2] [y1 y2] [z1 z2] Rxy Ryz.\n  simpls. destruct Rxy as [L1|[Eq1 L1]]; \n   destruct Ryz as [M2|[Eq2 M2]]; subst*.\nQed.\n\nLemma lexico3_trans : forall A1 A2 A3 \n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  trans R1 -> trans R2 -> trans R3 -> trans (lexico3 R1 R2 R3).\nProof.\n  introv Tr1 Tr2 Tr3. applys~ lexico2_trans. applys~ lexico2_trans.\nQed.\n\nLemma lexico4_trans : forall A1 A2 A3 A4 \n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  trans R1 -> trans R2 -> trans R3 -> trans R4 -> trans (lexico4 R1 R2 R3 R4).\nProof.\n  introv Tr1 Tr2 Tr3. applys~ lexico3_trans. applys~ lexico2_trans.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Equivalence relations *)\n\nRecord equiv A (R:binary A) :=\n { equiv_refl : refl R;\n   equiv_sym : sym R;\n   equiv_trans : trans R }. \n\n(** Equality is an equivalence *)\n\nLemma eq_equiv : forall A, equiv (@eq A).\nProof. intros. constructor; intros_all; subst~. Qed.\n\nHint Resolve eq_equiv.\n\n(** Symmetric of an equivalence is an equivalence *)\n\nLemma flip_equiv : forall A (E:binary A),\n  equiv E -> equiv (flip E).\nProof.\n  introv Equi. unfold flip. constructor; intros_all; \n    intuition eauto.\nQed.\n\n(** Product of two equivalences is an equivalence *)\n\nLemma prod2_equiv : forall A1 A2 (E1:binary A1) (E2:binary A2),\n  equiv E1 -> equiv E2 -> equiv (prod2 E1 E2).\nProof.\n  introv Equi1 Equi2. constructor.\n  intros [x1 x2]. simpl. intuition.\n  intros [x1 x2] [y1 y2]. simpl. intuition.\n  intros [x1 x2] [y1 y2] [z1 z2]. simpl. intuition eauto.\nQed.\n(* NEWCOQ: clean above *)\n\n(* todo: other arities of Prod *)\n\n\n(**************************************************************************)\n(* * Closures *)\n\n(* TODO: eliminate the use of the section variable R *)\n\nSection Closures.\nVariables (A : Type) (R : binary A).\n\n(* ---------------------------------------------------------------------- *)\n(** ** Constructions *)\n\n(** Reflexive-transitive closure ( R* ) *)\n\nInductive rtclosure : binary A :=\n  | rtclosure_refl : forall x,\n      rtclosure x x\n  | rtclosure_step : forall y x z,\n      R x y -> rtclosure y z -> rtclosure x z.\n\n(** Transitive closure ( R+ ) *)\n\nInductive tclosure : binary A :=\n  | tclosure_intro : forall x y z,\n     R x y -> rtclosure y z -> tclosure x z.\n\n(** Another definition of transitive closure ( R+ ) *)\n\nInductive tclosure' : binary A :=\n  | tclosure'_step : forall x y,  \n     R x y -> tclosure' x y\n  | tclosure'_trans : forall y x z,\n     tclosure' x y -> tclosure' y z -> tclosure' x z.\n\n(** Symmetric-transitive closure *)\n\nInductive stclosure (A:Type) (R:binary A) : binary A :=\n  | stclosure_step : forall x y,\n      R x y -> stclosure R x y\n  | stclosure_sym : forall x y, \n      stclosure R x y -> stclosure R y x\n  | stclosure_trans : forall y x z,\n      stclosure R x y -> stclosure R y z -> stclosure R x z.\n\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nHint Constructors tclosure rtclosure equiv.\n\nLemma rtclosure_once : forall x y,\n  R x y -> rtclosure x y.\nProof. autos*. Qed.\n\nHint Resolve rtclosure_once.\n\nLemma rtclosure_trans : trans rtclosure.  \nProof. introv R1 R2. induction* R1. Qed.\n\nLemma rtclosure_last : forall y x z,\n  rtclosure x y -> R y z -> rtclosure x z.\nProof. introv R1 R2. induction* R1. Qed.\n\nHint Resolve rtclosure_trans.\n\nLemma tclosure_once : forall x y,\n  R x y -> tclosure x y.  \nProof. eauto. Qed.\n\nLemma tclosure_rtclosure : forall x y,\n  tclosure x y -> rtclosure x y.  \nProof. intros. destruct* H. Qed.\n\nHint Resolve tclosure_once tclosure_rtclosure.\n\nLemma tclosure_rtclosure_step : forall x y z,\n  rtclosure x y -> R y z -> tclosure x z.\nProof. intros. induction* H. Qed.\n\nLemma tclosure_step_rtclosure : forall x y z,\n  R x y -> rtclosure y z -> tclosure x z.\nProof. intros. gen x. induction* H0. Qed.\n\nLemma tclosure_step_tclosure : forall x y z,\n  R x y -> tclosure y z -> tclosure x z.\nProof. intros. inverts* H0. Qed.\n\nHint Resolve tclosure_rtclosure_step tclosure_step_rtclosure.\n\nLemma tclosure_rtclosure_tclosure : forall y x z,\n  rtclosure x y -> tclosure y z -> tclosure x z.  \nProof. intros. gen z. induction* H. Qed.\n\nLemma tclosure_tclosure_rtclosure : forall y x z,\n  tclosure x y -> rtclosure y z -> tclosure x z.  \nProof. intros. induction* H. Qed. \n\nLemma tclosure_trans : trans tclosure.\nProof. intros_all. autos* tclosure_tclosure_rtclosure. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Induction *)\n\n(** Star induction principle with transitivity hypothesis *)\n\nLemma rtclosure_ind_trans : forall (P : A -> A -> Prop),\n  (forall x : A, P x x) ->\n  (forall x y : A, R x y -> P x y) ->\n  (forall y x z : A, rtclosure x y -> P x y -> rtclosure y z -> P y z -> P x z) ->\n  forall x y : A, rtclosure x y -> P x y.\nProof.\n  introv Hrefl Hstep Htrans S. induction S.\n  auto. apply~ (@Htrans y).\nQed.\n\n(** Star induction principle with steps at the end *)\n\nLemma rtclosure_ind_right : forall (P : A -> A -> Prop),\n  (forall x : A, P x x) ->\n  (forall y x z : A, rtclosure x y -> P x y -> R y z -> P x z) ->\n  forall x y : A, rtclosure x y -> P x y.\nProof.\n  introv Hrefl Hlast. apply rtclosure_ind_trans. \n  auto.\n  intros. apply~ (Hlast x).\n  introv S1 P1 S2 _. gen x. induction S2; introv S1 P1.\n     auto.\n     apply IHS2. eauto. apply~ (Hlast x). \nQed.\n\nEnd Closures.\n\n(** Star induction principle with transitivity hypothesis *)\n\nLemma tclosure_ind_trans : forall A (R:binary A) (P : A -> A -> Prop),\n  (forall x y : A, R x y -> P x y) ->\n  (forall y x z : A, tclosure R x y -> P x y -> tclosure R y z -> P y z -> P x z) ->\n  forall x y : A, tclosure R x y -> P x y.\nProof.\n  Hint Resolve tclosure_once.\n  introv Hstep Htrans S. inverts S as HR S. gen x. induction S; introv HR.\n    autos*.\n    applys* Htrans. constructors*.\nQed.\n\nHint Resolve rtclosure_refl rtclosure_step rtclosure_once : rtclosure.\n(* TODO: should rename and complete the [closure] database *)\n(* TODO: should not need to re-export the following version *)\n\nLemma incl_tclosure_self : forall A (R:binary A), \n   incl R (tclosure R).\nProof. unfolds incl. intros. apply~ tclosure_once. Qed.\nHint Resolve incl_tclosure_self. \n\n(* TODO: sort and complete the following *)\n\nHint Resolve stclosure_step stclosure_sym stclosure_trans.\n\nLemma stclosure_le : forall A (R1 R2 : binary A),\n  incl R1 R2 -> incl (stclosure R1) (stclosure R2).\nProof. unfolds incl. introv Le H. induction* H. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Additional definitions *)\n\n(* TODO: move above once section has been eliminated *)\n(* A theory of [rstclosure]. *)\n\nInductive rstclosure (A : Type) (R : binary A) : binary A :=\n  | rstclosure_step : forall x y,\n      R x y -> rstclosure R x y\n  | rstclosure_refl : forall x,\n      rstclosure R x x\n  | rstclosure_sym : forall x y, \n      rstclosure R x y -> rstclosure R y x\n  | rstclosure_trans : forall y x z,\n      rstclosure R x y -> rstclosure R y z -> rstclosure R x z.\n\n(** Symmetric closure *)\n\nDefinition sclosure (A:Type) (R:binary A) : binary A :=\n  fun x y => R x y \\/ R y x.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Hints *)\n\nHint Constructors tclosure : tclosure.\nHint Constructors rstclosure : rstclosure.\nHint Constructors stclosure : stclosure.\nHint Unfold sclosure : sclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Additional properties *)\n\n(* TODO: check name of lemmas below, and sort lemmas *)\n\nLemma rtclosure_refl_contrapositive : forall A (R : binary A) x y,\n  ~ rtclosure R x y ->\n  x <> y.\nProof.\n  intros. intro. subst. eauto using rtclosure_refl.\nQed.\n\nLemma rtclosure_rstclosure : forall A (R : binary A) x y,\n  rtclosure R x y -> rstclosure R x y.\nProof.\n  induction 1; eauto with rstclosure.\nQed.\n\nLemma stclosure_rstclosure : forall A (R : binary A) x y,\n  stclosure R x y -> rstclosure R x y.\nProof.\n  induction 1; eauto with rstclosure.\nQed.\n\nLemma stclosure_is_rstclosure : forall A (R : binary A),\n  refl R ->\n  stclosure R = rstclosure R.\nProof.\n  intros. eapply binary_extensional. intros x y.\n  split; eauto using stclosure_rstclosure.\n  gen x y. induction 1; eauto with stclosure.\nQed.\n\nLemma refl_rstclosure : forall A (R : binary A),\n  refl (rstclosure R).\nProof.\n  unfold refl. eauto with rstclosure.\nQed.\n\nLemma rstclosure_covariant : forall A (R S : binary A),\n  incl R S ->\n  incl (rstclosure R) (rstclosure S).\nProof.\n  unfold incl. induction 2; eauto with rstclosure.\nQed.\n\nLemma rstclosure_inflationary: forall A (R : binary A),\n  incl R (rstclosure R).\nProof.\n  unfold incl. eauto with rstclosure.\nQed.\n\nLemma prove_rstclosure_incl : forall A (R S : binary A),\n  incl R (rstclosure S) ->\n  incl (rstclosure R) (rstclosure S).\nProof.\n  unfold incl. induction 2; eauto with rstclosure.\nQed.\n\nLemma rstclosure_union : forall A (R S : binary A),\n  incl (union (rstclosure R) (rstclosure S))\n       (rstclosure (union R S)).\nProof.\n  unfold incl, union. intros ? ? ? x y H. \n  destruct H; gen x y;\n  induction 1; eauto with rstclosure.\nQed.\n\n\nLemma sym_sclosure : forall A (R : binary A),\n  sym (sclosure R).\nProof.\n  unfold sym, sclosure. tauto.\nQed.\n\nLemma sclosure_is_a_closure_operator : forall A (R1 R2 : binary A),\n  incl R1 (sclosure R2) ->\n  incl (sclosure R1) (sclosure R2).\nProof.\n  unfold sclosure, incl. introv h. introv H.\n  destruct H.\n  { eauto. }\n  { forwards M: h. eauto. destruct M; tauto. }\nQed.\n\nLemma sclosure_covariant : forall A (R1 R2 : binary A),\n  incl R1 R2 ->\n  incl (sclosure R1) (sclosure R2).\nProof.\n  unfold sclosure, incl. introv M H. destruct H; eauto.\nQed.\n\nLemma rtclosure_covariant : forall A (R1 R2 : binary A),\n  incl R1 R2 ->\n  incl (rtclosure R1) (rtclosure R2).\nProof.\n  unfold incl. induction 2; eauto with rtclosure.\nQed.\n\nLemma tclosure_covariant : forall A (R1 R2 : binary A),\n  incl R1 R2 ->\n  incl (tclosure R1) (tclosure R2).\nProof.\n  unfold incl. inversion 2; subst. econstructor.\n  eauto.\n  eapply rtclosure_covariant; eauto.\nQed.\n\nLemma tclosure_last : forall A (R : binary A) y x z,\n  tclosure R x y -> R y z -> tclosure R x z.\nProof.\n  inversion 1; intros; subst.\n  eauto using rtclosure_last with tclosure.\nQed.\n\n(* If a relation is symmetric, then so is its transitive closure. *)\n\nLemma sym_rtclosure : forall A (R : binary A),\n  sym R ->\n  sym (rtclosure R).\nProof.\n  unfold sym. induction 2; eauto using rtclosure_last with rtclosure.\nQed.\n\nLemma sym_tclosure : forall A (R : binary A),\n  sym R ->\n  sym (tclosure R).\nProof.\n  unfold sym. inversion 2; subst. \n  eapply tclosure_rtclosure_step.\n  eapply sym_rtclosure; eauto.\n  eauto.\nQed.\n\nLemma sclosure_incl_stclosure : forall A (R : binary A),\n  incl (sclosure R) (stclosure R).\nProof.\n  unfold incl. inversion 1; eauto with stclosure.\nQed.\n\nLemma tclosure_incl_stclosure : forall A (R1 R2 : binary A),\n  incl R1 (stclosure R2) ->\n  incl (tclosure R1) (stclosure R2).\nProof.\n  introv H M. induction M using tclosure_ind_trans.\n  applys* H.\n  applys* stclosure_trans.\nQed.\n\nLemma stclosure_is_tclosure_sclosure : forall A (R : binary A),\n  stclosure R = tclosure (sclosure R).\nProof.\n  extens. intros x y. split.\n  { gen x y. induction 1.\n    { eauto with tclosure sclosure rtclosure. }\n    { eapply sym_tclosure. eapply sym_sclosure. eauto. }\n    { eapply tclosure_trans; eauto. }\n  }\n  { intros.\n    eapply tclosure_incl_stclosure; [ | eassumption ].\n    eapply sclosure_incl_stclosure. }\nQed.", "meta": {"author": "Blaisorblade", "repo": "knot-esop-2017-case-study", "sha": "cf541cb38a483a514474f4c948bf005bc49b1e6f", "save_path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study", "path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study/knot-esop-2017-case-study-cf541cb38a483a514474f4c948bf005bc49b1e6f/poplmark_comparison/chargueraud/tlc/LibRelation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7097236520058754}}
{"text": "Require Import Relation_Operators.\nRequire Import Relation_Definitions.\nRequire Import Coq.Structures.Equalities.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.Plus.\nRequire Import Coq.Arith.Lt.\nRequire Import Omega.\n\nRequire Import Untyped.\nRequire Import Subst.\nRequire Import Rels.\nRequire Import Beta.\nRequire Import Eta.\n\n(** * Postponement theorem in Untyped Lambda Calculus *)\n\nModule Export Postpone.\n\n(** This module contains a formalised proof of the ($\\eta$#η#-)Postponement\n    Theorem for the untyped lambda calculus.\n\n    The formalisation is based on an ``informal'' proof due to Masako Takahashi\n    in ``Parallel Reductions in Lambda-calculus'' (Information and Computation,\n    Volume 118, 1995).\n\n    Except for the gymnastics related to working with de Bruijn indices, the\n    translation of the Takashi's proof is rather straightforward.\n**)\n\n(** ** Preliminaries *)\n\n(** We at first prove various properties about the relation between [beta_par]\n    and the eta-expansion [lam_k]. (This is Lemma 3.3 in Takahashi).\n\n    We however do it in in a slightly different order than in the paper,\n    because the cases of the lemma actually depend on each other in a slightly\n    differently order than the one stated in the paper.\n**)\n\n(** Firstly, an application of a [k]-fold eta-expansion of a lambda\n    abstraction can be reduced simply to a substitution via\n    parallel beta.\n**)\nLemma lam_k_beta_subst:\n  forall k, forall M M' N N',\n    beta_par M M' -> beta_par N N' ->\n      beta_par (App (lam_k k (Lam M)) N) (subst 0 N' M').\nProof.\n  induction k.\n  (* k := 0 *)\n  intros.\n  simpl. apply beta_par_base; assumption.\n  (* k := (S k) *)\n  intros.\n  simpl.\n  apply beta_par_base. rewrite shift_0_lam_commute.\n  unfold shift. simpl.\n  replace M' with (subst 0 (Var 0) (shift 1 M')).\n  apply IHk.\n  apply beta_par_shift. assumption. apply beta_par_refl.\n  apply subst_k_shift_S_k. assumption.\nQed.\n\n(** Similarly, a [k]-fold eta-expansion of a lambda abstraction can be reduced\n    to a single lambda abstraction via parallel beta reduction. **)\n\nLemma lam_k_beta_lam:\n  forall k, forall M M',\n    beta_par M M' -> beta_par (lam_k k (Lam M)) (Lam M').\nProof.\n  induction k.\n  (* k := 0 *)\n  intros. simpl. apply beta_par_lam. assumption.\n  (* k := (S k) *)\n  intros.\n  remember H as HH. clear HeqHH. apply IHk in H.\n  simpl.\n  constructor.\n  rewrite shift_0_lam_commute.\n  unfold shift. simpl.\n  replace M' with (subst 0 (Var 0) (shift 1 M')).\n  apply lam_k_beta_subst.\n  apply beta_par_shift. assumption.\n  apply beta_par_refl.\n  apply subst_k_shift_S_k.\nQed.\n\n(** In case of an application, we can also contract the whole eta-expansion of\n    the applied term via parallel beta reduction *)\n\nLemma lam_k_beta_app:\n  forall k, forall M M' N N',\n    beta_par M M' -> beta_par N N' ->\n      beta_par (App (lam_k k M) N) (App M' N').\nProof.\n  induction k.\n  (* k := 0 *)\n  intros. simpl. apply beta_par_app. assumption. assumption.\n  (* k := (S k) *)\n  intros.\n  rewrite lam_k_alt.\n  replace (App M' N') with (subst 0 N' (App (shift 0 M') (Var 0))).\n  apply lam_k_beta_subst.\n  constructor. apply beta_par_shift. assumption. apply beta_par_refl.\n      assumption.\n  simpl. rewrite lift_0_ident. rewrite subst_shift_ident. reflexivity.\nQed.\n\n(** Finally, [k+1] eta-expansions can always be contracted to only one\n    eta-expansion via parallel beta reduction. **)\nLemma lam_S_k_beta:\n  forall k, forall M M',\n    beta_par M M' ->\n      beta_par (lam_k (S k) M) (lam_k 1 M').\nProof.\n  induction k.\n  (* k := 0 *)\n  intros. simpl.\n  constructor. constructor. apply beta_par_shift. assumption.\n  apply beta_par_refl.\n  (* k := (S k) *)\n  intros.\n  rewrite lam_k_alt.\n  apply lam_k_beta_lam.\n  constructor. apply beta_par_shift. assumption. apply beta_par_refl.\nQed.\n\n\n(** It now remains to prove the crucial Lemma 3.4 from Takahashi, stating that\n    postponement holds for the case of parallel beta and eta reductions.\n\n    Before we can do that, we need one auxiliary fact:\n**)\n\n(** Parallel beta is closed under eta-expansion. **)\n\nLemma beta_par_lam_k_closed:\n  forall k, forall M N,\n    beta_par M N -> beta_par (lam_k k M) (lam_k k N).\nProof.\n  induction k.\n  intros.\n  simpl. assumption.\n  intros.\n  simpl. constructor. constructor. apply beta_par_shift. apply IHk. assumption.\n  apply beta_par_refl.\nQed.\n\n(** We can now prove the postponement theorem for the specific case of parallel\n    reductions. This is Lemma 3.4 in Takahashi. **)\n\nLemma postpone_par:\n  forall M P N,\n    eta_par M P -> beta_par P N ->\n        (exists P', beta_par M P' /\\ eta_par P' N).\nProof.\n  intros.\n  generalize dependent M.\n  rename H0 into H.\n  dependent induction H.\n  (* [P = (Var n) = N] *)\n      intros.\n      exists M. split.\n      apply beta_par_refl.\n      assumption.\n  (* [P = (Lam P1)] *)\n      intro K.\n      intros.\n      rename M' into N1.\n      rename M into P.\n      rename K into M.\n      apply eta_par_lam_k_lam in H0.\n      do 3 destruct H0.\n      rewrite H1; clear H1; clear M.\n      apply IHbeta_par in H0.\n      do 2 destruct H0.\n      exists (Lam x1).\n      split.\n      apply lam_k_beta_lam. assumption.\n      constructor. assumption.\n\n   (* App case *)\n      intros MM HH.\n      apply eta_par_lam_k_app in HH.\n      destruct HH. do 3 destruct H1.\n      destruct H2.\n      rewrite H3; clear H3; clear MM.\n      apply IHbeta_par1 in H1.\n      apply IHbeta_par2 in H2.\n      do 2 destruct H1.\n      do 2 destruct H2.\n      (* This feels like a weird choice, but seems to work. *)\n      exists (lam_k x (App x2 x3)).\n      split.\n      Focus 2.\n      induction x.\n      simpl. constructor; assumption.\n      simpl. apply eta_par_base with (lam_k x (App x2 x3)).\n      reflexivity. assumption.\n      induction x.\n      simpl. constructor; assumption.\n      simpl. constructor. constructor.\n      apply beta_par_shift. assumption. apply beta_par_refl.\n\n   (* subst case *)\n      intros.\n      apply eta_par_lam_k_app in H1.\n      do 4 destruct H1. destruct H2.\n      rewrite H3. clear H3. clear M0.\n      apply eta_par_lam_k_lam in H1.\n      do 3 destruct H1. rewrite H3. clear H3. clear x0.\n      apply IHbeta_par1 in H1.\n      apply IHbeta_par2 in H2.\n      do 2 destruct H1.\n      do 2 destruct H2.\n      exists (lam_k x (subst 0 x4 x0)).\n      split.\n\n      apply beta_par_lam_k_closed.\n      apply lam_k_beta_subst. assumption. assumption.\n\n      apply lam_k_eta_red.\n      apply eta_par_subst_closed.\n      assumption.\n      assumption.\nQed.\n\n(** We now define the beta-eta relation and its reflexive-transitive closure\n**)\n\nDefinition beta_eta := union lterm bred eta.\nDefinition beta_eta_star := clos_refl_trans lterm beta_eta.\n\n(** We need a couple of auxiliary statements about the relationships\n    between the parallel and reflexive-transitive versions of\n    beta and eta reductions which appear in the conclusions of the\n    postponement theorem.\n\n    They make it more convenient to do the rewriting while proving the main\n    result.\n**)\n\n(** Firstly, since the reflexive-transitive closures are equivalent\n    to the transitive closures of the parallel relations, the following holds:\n**)\n\nLemma star_exists_iff_par_exists:\n  forall M N,\n  (exists P, bstar M P /\\ eta_star P N) <->\n  (exists P, beta_par_trans M P /\\ eta_par_trans P N).\nProof.\n  split; intros;\n  do 2 destruct H;\n  exists x; split;\n  do 2 (try\n          apply bstar_eq_closure_of_beta_par ||\n          apply eta_star_eq_closure_of_eta_par;\n       assumption).\nQed.\n\n(** Also, it is obviously sufficient to show this to hold for parallel beta,\n    in order for it to also hold for the transitive closure: *)\n\nLemma par_impl_par_trans:\n  forall M N,\n    (exists P, beta_par M P /\\ eta_par P N) ->\n    (exists P, beta_par_trans M P /\\ eta_par_trans P N).\nProof.\n  intros. destruct H. destruct H as [H1 H2].\n  exists x.\n  split; constructor; assumption.\nQed.\n\n(** Finally, a couple of \"one-sided\" rewrites for convenience within the proof.\n**)\n\nLemma rewrite_existential_eta:\n  forall M N,\n  (exists P, beta_par M P /\\ eta_star P N) <->\n  (exists P, beta_par M P /\\ eta_par_trans P N).\nProof.\n  split; intros;\n  do 2 destruct H;\n  exists x; split;\n  do 2 (try\n          apply bstar_eq_closure_of_beta_par ||\n          apply eta_star_eq_closure_of_eta_par;\n       assumption).\nQed.\n\nLemma rewrite_existential_beta:\n  forall M N,\n  (exists P, bstar M P /\\ eta_par P N) <->\n  (exists P, beta_par_trans M P /\\ eta_par P N).\nProof.\n  split; intros;\n  do 2 destruct H;\n  exists x; split;\n  do 2 (try\n          apply bstar_eq_closure_of_beta_par ||\n          apply eta_star_eq_closure_of_eta_par;\n       assumption).\nQed.\n\n(** We now build up to the full postponement lemma by proving a series of\n    simpler lemmas **)\n\n(** Here we consider the case where we postpone [eta_star] in the presence\n    of only a parallel beta. **)\n\nLemma eta_baby_postpone_eta:\n  forall M P N,\n    eta_star M P -> beta_par P N ->\n      (exists P', beta_par M P' /\\ eta_star P' N).\nProof.\n  intros ? ? ? H1 H2.\n  apply rewrite_existential_eta.\n  generalize dependent N.\n  dependent induction H1.\n  intros.\n  assert (HH: exists P', beta_par x P' /\\ eta_par P' N).\n  apply eta_imp_eta_par in H.\n  apply postpone_par with y; assumption.\n  destruct HH. destruct H0.\n  exists x0. split. assumption. constructor. assumption.\n\n  intros. exists N.\n  split. assumption. constructor. apply eta_par_refl.\n\n  intros.\n\n  fold eta_star in H1_, H1_0.\n  apply IHclos_refl_trans2 in H2.\n  destruct H2. destruct H.\n  apply IHclos_refl_trans1 in H.\n  destruct H. destruct H.\n  exists x1.\n  split. assumption.\n  apply t_trans with x0; assumption.\nQed.\n\n(** Similarly, here we consider only the postponement of [eta_par] in the\n    presence [bstar]: **)\n\nLemma eta_baby_postpone_beta:\n  forall M P N,\n    eta_par M P -> bstar P N ->\n      (exists P', bstar M P' /\\ eta_par P' N).\nProof.\n  intros ? ? ? H1 H2.\n  apply rewrite_existential_beta.\n  generalize dependent M.\n  dependent induction H2.\n  intros.\n  assert (HH: exists P', beta_par M P' /\\ eta_par P' y).\n  apply bred_imp_beta_par in H.\n  apply postpone_par with x; assumption.\n  destruct HH. destruct H0.\n  exists x0. split. constructor. assumption. assumption.\n\n  intros. exists M.\n  split. constructor. apply beta_par_refl. assumption.\n\n  intros.\n\n  fold bstar in H2_, H2_0.\n  apply IHclos_refl_trans1 in H1.\n  destruct H1. destruct H.\n  apply IHclos_refl_trans2 in H0.\n  destruct H0. destruct H0.\n  exists x1.\n  split. apply t_trans with x0; assumption. assumption.\nQed.\n\n(** We now combine all the previous lemmas to prove a simplified version of the\n    eta-postponement where we consider separate [eta_star] and [bstar] reductions,\n    rather than a single reduction of their union. **)\n\nTheorem eta_postponement_basic:\n  forall M N P,\n    eta_star M P -> bstar P N -> (exists P', bstar M P' /\\ eta_star P' N).\nProof.\n  intros.\n  rewrite eta_star_eq_closure_of_eta_par in *.\n  rewrite bstar_eq_closure_of_beta_par in *.\n  rewrite star_exists_iff_par_exists.\n  generalize dependent M.\n  dependent induction H0.\n  intros.\n  assert (HH:\n            (exists P, beta_par M P /\\ eta_star P y) ->\n            (exists P, beta_par_trans M P /\\ eta_par_trans P y)).\n  intros.\n  destruct H1. destruct H1.\n  apply beta_par_imp_bstar in H1.\n  apply bstar_eq_closure_of_beta_par in H1.\n  apply eta_star_eq_closure_of_eta_par in H2.\n  exists x0.\n  split; assumption.\n\n  assert (HH2:\n            (exists P, beta_par M P /\\ eta_star P y)).\n\n  apply eta_baby_postpone_eta with x.\n  apply eta_star_eq_closure_of_eta_par. assumption. assumption.\n  apply HH. assumption.\n\n  fold beta_par_trans in H0_, H0_0.\n  intros.\n  apply IHclos_trans1 in H.\n  destruct H. destruct H.\n  apply IHclos_trans2 in H0.\n  destruct H0. destruct H0.\n\n  exists x1.\n  split. apply t_trans with x0; assumption. assumption.\nQed.\n\n(** * The eta postponement theorem **)\n(** Finally, we prove the full eta-postponement theorem using the\n    separate reduction version in [eta_postponement_basic].\n**)\n\nTheorem eta_postponement:\n  forall M N,\n    beta_eta_star M N -> (exists P, bstar M P /\\ eta_star P N).\nProof.\n  intros.\n  dependent induction H.\n\n  destruct H.\n    exists y. split. constructor. assumption. apply rt_refl.\n    exists x. split. apply rt_refl. constructor. assumption.\n\n  exists x. split. apply rt_refl. apply rt_refl.\n\n  rename H into H1. rename H0 into H2.\n  fold beta_eta_star in H1, H2.\n\n  destruct IHclos_refl_trans1 as [xy]. destruct H as [A1 A2].\n  destruct IHclos_refl_trans2 as [yz]. destruct H as [B1 B2].\n\n\n  assert (H: exists xyz, bstar xy xyz /\\ eta_star xyz yz).\n  apply eta_postponement_basic with y; assumption.\n\n  do 2 destruct H.\n  exists x0.\n\n  split. apply rt_trans with xy; assumption.\n  apply rt_trans with yz; assumption.\nQed.\n\nEnd Postpone.\n", "meta": {"author": "knuton", "repo": "la-girafe-sportive", "sha": "3aaead03aa1cd62acb064d5b7115c25e706bbb47", "save_path": "github-repos/coq/knuton-la-girafe-sportive", "path": "github-repos/coq/knuton-la-girafe-sportive/la-girafe-sportive-3aaead03aa1cd62acb064d5b7115c25e706bbb47/src/Postpone.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7097236334661654}}
{"text": "Require Import String.\nRequire Import Ascii.\nRequire Import Arith.\nRequire Import OrderedType.\nRequire Import OrderedTypeEx.\n\nRequire Import StructTact.StructTactics.\n\nInductive lex_lt: string -> string -> Prop :=\n| lex_lt_lt : forall (c1 c2 : ascii) (s1 s2 : string),\n    nat_of_ascii c1 < nat_of_ascii c2 ->\n    lex_lt (String c1 s1) (String c2 s2)\n| lex_lt_eq : forall (c : ascii) (s1 s2 : string),\n    lex_lt s1 s2 ->\n    lex_lt (String c s1) (String c s2)\n| lex_lt_empty : forall (c : ascii) (s : string),\n    lex_lt EmptyString (String c s).\n\nInductive lex_order : string -> string -> Prop :=\n| lex_order_empty :\n    lex_order EmptyString EmptyString\n| lex_order_char_lt :\n    forall (c1 c2: ascii) (s1 s2: string),\n      nat_of_ascii c1 < nat_of_ascii c2 ->\n      lex_order (String c1 s1) (String c2 s2)\n| lex_order_char_eq :\n    forall (c: ascii) (s1 s2: string),\n      lex_order s1 s2 ->\n      lex_order (String c s1) (String c s2)\n| lex_order_empty_string :\n    forall s, lex_order EmptyString s.\n\nDefinition lex_le (s1 s2 : string) : Prop := lex_lt s1 s2 \\/ s1 = s2.\n\nLemma lex_le_in_lex_order : forall (s1 s2 : string),\n    lex_order s1 s2 -> lex_le s1 s2.\nProof.\n  intros s1 s2 H.\n  induction H.\n  - right.\n    reflexivity.\n  - left.\n    apply lex_lt_lt.\n    assumption.\n  - case IHlex_order; intro H_le.\n    * left.\n      apply lex_lt_eq.\n      assumption.\n    * rewrite H_le.\n      right.\n      reflexivity.\n  - case s.\n    * right.\n      reflexivity.\n    * intros c s0.\n      left.\n      apply lex_lt_empty.\nQed.\n\nLemma lex_order_refl : forall (s : string), lex_order s s.\nProof.\n  induction s.\n  * apply lex_order_empty_string.\n  * intros.\n    apply lex_order_char_eq.\n    assumption.\nQed.\n  \nLemma lex_order_lex_le : forall (s1 s2 : string),\n    lex_le s1 s2 -> lex_order s1 s2.\nintros s1 s2 H_le.\ncase H_le; intro H_le'.\n- induction H_le'.\n  * apply lex_order_char_lt.\n    assumption.\n  * apply lex_order_char_eq.\n    apply IHH_le'.\n    left.\n    assumption.\n  * apply lex_order_empty_string.\n- rewrite <- H_le'.\n  apply lex_order_refl.\nQed.\n\nTheorem lex_lt_trans : forall s0 s1 s2,\n    lex_lt s0 s1 -> lex_lt s1 s2 -> lex_lt s0 s2.\nProof.\ninduction s0.\n- intros.  \n  inversion H; subst.\n  inversion H0; subst.\n  * apply lex_lt_empty.\n  * apply lex_lt_empty.\n- intros.\n  inversion H; subst; inversion H0; subst.\n  * apply lex_lt_lt.\n    eauto with arith.\n  * apply lex_lt_lt.\n    assumption.\n  * apply lex_lt_lt.\n    assumption.\n  * apply lex_lt_eq.\n    eapply IHs0; eauto.\nQed.\n\nTheorem lex_lt_not_eq : forall s0 s1,\n    lex_lt s0 s1 -> s0 <> s1.\nProof.\n  induction s0.\n  - intros.\n    inversion H; subst.\n    congruence.\n  - intros.\n    inversion H; subst.\n    * intro H_eq.\n      find_injection.\n      contradict H3.\n      auto with arith.\n    * intro H_eq.\n      find_injection.\n      specialize (IHs0 s3).\n      concludes.\n      auto.\nQed.\n\nLemma nat_of_ascii_injective:\n  forall c1 c2, nat_of_ascii c1 = nat_of_ascii c2 -> c1 = c2.\nProof.\n  intros; simpl.\n  assert (ascii_of_nat (nat_of_ascii c1) =\n          ascii_of_nat (nat_of_ascii c2))\n      as Hinvol. auto.\n  repeat rewrite ascii_nat_embedding in Hinvol.\n  trivial.\nQed.\n\nFixpoint string_compare_lex_compat (s0 s1 : string) : Compare lex_lt eq s0 s1.\nrefine\n  (match s0 as ss0, s1 as ss1 return (_ = ss0 -> _ = ss1 -> _) with\n   | EmptyString, EmptyString => fun H_eq H_eq' => EQ _\n   | EmptyString, String c' s'1 => fun H_eq H_eq' => LT _\n   | String c s'0, EmptyString => fun H_eq H_eq' => GT _\n   | String c s'0, String c' s'1 => fun H_eq H_eq' =>\n     match Nat.compare (nat_of_ascii c) (nat_of_ascii c') as cmp return (_ = cmp -> _) with\n     | Lt => fun H_eq_cmp => LT _\n     | Eq => fun H_eq_cmp =>\n       match string_compare_lex_compat s'0 s'1 with\n       | LT H_lt => LT _\n       | EQ H_eq_lex => EQ _\n       | GT H_gt => GT _\n       end\n     | Gt => fun H_eq_cmp => GT _\n     end (refl_equal _)\n   end (refl_equal _) (refl_equal _)); try (rewrite H_eq; rewrite H_eq'); auto.\n- apply lex_lt_empty.\n- apply lex_lt_empty.\n- apply nat_compare_eq in H_eq_cmp.\n  apply nat_of_ascii_injective in H_eq_cmp.\n  rewrite H_eq_cmp.\n  apply lex_lt_eq.\n  assumption.\n- apply nat_compare_eq in H_eq_cmp.\n  apply nat_of_ascii_injective in H_eq_cmp.\n  subst.\n  reflexivity.\n- apply nat_compare_eq in H_eq_cmp.\n  apply nat_of_ascii_injective in H_eq_cmp.\n  rewrite H_eq_cmp.\n  apply lex_lt_eq.\n  assumption.\n- apply nat_compare_lt in H_eq_cmp.\n  apply lex_lt_lt.\n  assumption.\n- apply nat_compare_gt in H_eq_cmp.\n  apply lex_lt_lt.\n  auto with arith.\nDefined.\n\nModule string_lex_as_OT_compat <: UsualOrderedType.\n  Definition t := string.\n  Definition eq := @eq string.\n  Definition lt := lex_lt.\n  Definition eq_refl := @eq_refl string.\n  Definition eq_sym := @eq_sym string.\n  Definition eq_trans := @eq_trans string.\n  Definition lt_trans := lex_lt_trans.\n  Definition lt_not_eq := lex_lt_not_eq.\n  Definition compare := string_compare_lex_compat.\n  Definition eq_dec := string_dec.\nEnd string_lex_as_OT_compat.\n\nRequire Import Orders.\n\nLemma lex_lt_irrefl : Irreflexive lex_lt.\nProof.\n  intros s0 H_lt.\n  apply lex_lt_not_eq in H_lt.\n  auto.\nQed.\n\nTheorem lex_lt_strorder : StrictOrder lex_lt.\nProof.\n  exact (Build_StrictOrder _ lex_lt_irrefl lex_lt_trans).\nQed.\n\nTheorem lex_lt_lt_compat : Proper (eq ==> eq ==> iff) lex_lt.\nProof.\nintros s0 s1 H_eq s2 s3 H_eq'.\nsplit; intro H_imp; subst; auto.\nQed.\n\nFixpoint string_compare_lex (s0 s1 : string) : { cmp : comparison | CompSpec eq lex_lt s0 s1 cmp }.\nrefine\n  (match s0 as ss0, s1 as ss1 return (_ = ss0 -> _ = ss1 -> _) with\n   | EmptyString, EmptyString => fun H_eq H_eq' => exist _ Eq _\n   | EmptyString, String c' s'1 => fun H_eq H_eq' => exist _ Lt _\n   | String c s'0, EmptyString => fun H_eq H_eq' => exist _ Gt _\n   | String c s'0, String c' s'1 => fun H_eq H_eq' =>\n     match Nat.compare (nat_of_ascii c) (nat_of_ascii c') as cmp0 return (_ = cmp0 -> _)  with\n     | Lt => fun H_eq_cmp0 => exist _ Lt _\n     | Eq => fun H_eq_cmp0 =>\n       match string_compare_lex s'0 s'1 with\n       | exist _ cmp H_cmp' =>\n         match cmp as cmp1 return (cmp = cmp1 -> _) with\n         | Lt => fun H_eq_cmp1 => exist _ Lt _\n         | Eq => fun H_eq_cmp1 => exist _ Eq _\n         | Gt => fun H_eq_cmp1 => exist _ Gt _\n         end (refl_equal _)\n       end\n     | Gt => fun H_eq_cmp0 => exist _ Gt _\n     end (refl_equal _)\n   end (refl_equal _) (refl_equal _)); try (rewrite H_eq; rewrite H_eq').\n- apply CompEq; auto.\n- apply CompLt.\n  apply lex_lt_empty.\n- apply CompGt.\n  apply lex_lt_empty.\n- apply nat_compare_eq in H_eq_cmp0.\n  apply nat_of_ascii_injective in H_eq_cmp0.\n  rewrite H_eq_cmp1 in H_cmp'.\n  inversion H_cmp'; subst.\n  apply CompEq.\n  reflexivity.\n- apply nat_compare_eq in H_eq_cmp0.\n  apply nat_of_ascii_injective in H_eq_cmp0.\n  rewrite H_eq_cmp1 in H_cmp'.\n  inversion H_cmp'.\n  subst.\n  apply CompLt.\n  apply lex_lt_eq.\n  assumption.\n- apply nat_compare_eq in H_eq_cmp0.\n  apply nat_of_ascii_injective in H_eq_cmp0.\n  rewrite H_eq_cmp1 in H_cmp'.\n  subst.\n  inversion H_cmp'.\n  apply CompGt.\n  apply lex_lt_eq.\n  assumption.\n- apply nat_compare_lt in H_eq_cmp0.\n  apply CompLt.\n  apply lex_lt_lt.\n  assumption.\n- apply nat_compare_gt in H_eq_cmp0.\n  apply CompGt.\n  apply lex_lt_lt.\n  auto with arith.\nDefined.\n\nModule string_lex_as_OT <: UsualOrderedType.\n  Definition t := string.\n  Definition eq := @eq string.\n  Definition eq_equiv := @eq_equivalence string.\n  Definition lt := lex_lt.\n  Definition lt_strorder := lex_lt_strorder.\n  Definition lt_compat := lex_lt_lt_compat.\n  Definition compare := fun x y => proj1_sig (string_compare_lex x y).\n  Definition compare_spec := fun x y => proj2_sig (string_compare_lex x y).\n  Definition eq_dec := string_dec.\nEnd string_lex_as_OT.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/StructTact/StringOrders.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7097209923253561}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_supplementsymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_ABCequalsCBA.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_equalanglestransitive.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_RTsymmetric : \n   forall A B C D E F, \n   RT A B C D E F ->\n   RT D E F A B C.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists a b c d e, (Supp a b c d e /\\ CongA A B C a b c /\\ CongA D E F d b e)) by (conclude_def RT );destruct Tf as [a[b[c[d[e]]]]];spliter.\nassert (Supp e b d c a) by (conclude lemma_supplementsymmetric).\nassert (nCol d b e) by (conclude lemma_equalanglesNC).\nassert (CongA d b e e b d) by (conclude lemma_ABCequalsCBA).\nassert (nCol a b c) by (conclude lemma_equalanglesNC).\nassert (CongA a b c c b a) by (conclude lemma_ABCequalsCBA).\nassert (CongA D E F e b d) by (conclude lemma_equalanglestransitive).\nassert (CongA A B C c b a) by (conclude lemma_equalanglestransitive).\nassert (RT D E F A B C) by (conclude_def RT ).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_RTsymmetric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7096628484349172}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus Zero (plus y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj2910_coqofml_EV93Yi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7096553476557559}}
{"text": "Require Import List ZArith.\n\n(* RSMachine definition *)\n\nInductive rsReg : Set :=\n| RS0\n| RS1.\n\nDefinition beq_rsReg (r0 r1 : rsReg) : bool :=\n  match r0, r1 with\n    | RS0, RS0 => true\n    | RS1, RS1 => true\n    | _, _ => false\n  end.\n\nInductive rsArg : Set :=\n| RSArg : nat -> rsArg.\n\nInductive rsBop : Set :=\n| RSAdd : rsBop\n| RSSub : rsBop\n| RSMul : rsBop.\n\nInductive rsInstr : Set :=\n| PushReg : rsReg -> rsInstr\n| PushArg : rsArg -> rsInstr\n| Pop : rsReg -> rsInstr\n| RSBinop : rsBop -> rsReg -> rsReg -> rsInstr.\n\nRecord rsMachine :=\n  {\n    rsRegValMap : rsReg -> Z;\n    rsArgValMap : rsArg -> Z;\n    rsStk : list Z\n  }.\n\nDefinition rsProgram := list rsInstr.\n\n(* RSMachine program evaluation *)\n\nOpen Scope Z_scope.\n\nDefinition evalRSBop (b : rsBop) (v0 v1 : Z) :=\n  match b with\n    | RSAdd => v0 + v1\n    | RSSub => v0 - v1\n    | RSMul => v0 * v1\n  end.\n\nInductive rsBopEvalR : rsBop-> Z -> Z -> Z -> Prop :=\n| RSBopEvalR : forall b v0 v1, rsBopEvalR b v0 v1 (evalRSBop b v0 v1).\n\nInductive rsInstrEvalR : rsMachine -> rsInstr -> rsMachine -> Prop :=\n| RSInstrEvalR_pushReg :\n    forall r rvm ram stk,\n      rsInstrEvalR\n        (Build_rsMachine rvm ram stk)\n        (PushReg r)\n        (Build_rsMachine rvm ram (rvm r :: stk))\n| RSInstrEvalR_pushArg :\n    forall a rvm ram stk,\n      rsInstrEvalR\n        (Build_rsMachine rvm ram stk)\n        (PushArg a)\n        (Build_rsMachine rvm ram (ram a :: stk))\n| RSInstrEvalR_pop :\n    forall v r rvm ram stk,\n      rsInstrEvalR\n        (Build_rsMachine rvm ram (v :: stk))\n        (Pop r)\n        (Build_rsMachine\n           (fun x => if beq_rsReg x r then v else rvm x) ram stk)\n| RSInstrEvalR_rsBinop :\n    forall r0 r1 b rvm ram stk r,\n      rsBopEvalR b (rvm r1) (rvm r0) r ->\n      rsInstrEvalR\n        (Build_rsMachine rvm ram stk)\n        (RSBinop b r0 r1)\n        (Build_rsMachine\n           (fun x => if beq_rsReg x r1 then r else rvm x)\n           ram\n           stk).\n\n", "meta": {"author": "dillonhuff", "repo": "CertArith3", "sha": "a21b46002df3346a024c11131095c86e8aa5666f", "save_path": "github-repos/coq/dillonhuff-CertArith3", "path": "github-repos/coq/dillonhuff-CertArith3/CertArith3-a21b46002df3346a024c11131095c86e8aa5666f/RSMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7096553454920748}}
{"text": "From mathcomp Require Import all_ssreflect fingroup ssralg poly ssrnum.\nRequire Import signed.\n\n(******************************************************************************)\n(* This file equips the product of two normedZmodTypes with a canonical       *)\n(* normedZmodType structure. It is a short file that has been added here for  *)\n(* convenience during the rebase of MathComp-Analysis on top of MathComp 1.1. *)\n(* The contents is likely to be moved elsewhere.                              *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\nImport Order.TTheory GRing.Theory Num.Theory.\n\nModule ProdNormedZmodule.\nSection ProdNormedZmodule.\nContext {R : numDomainType} {U V : normedZmodType R}.\n\nDefinition norm (x : U * V) : R := Num.max `|x.1| `|x.2|.\n\nLemma normD x y : norm (x + y) <= norm x + norm y.\nProof.\nrewrite /norm num_le_maxl !(le_trans (ler_norm_add _ _)) ?ler_add//;\nby rewrite comparable_le_maxr ?lexx ?orbT// real_comparable.\nQed.\n\nLemma norm_eq0 x : norm x = 0 -> x = 0.\nProof.\ncase: x => x1 x2 /eqP; rewrite eq_le num_le_maxl 2!normr_le0 -andbA/=.\nby case/and3P => /eqP -> /eqP ->.\nQed.\n\nLemma normMn x n : norm (x *+ n) = (norm x) *+ n.\nProof. by rewrite /norm pairMnE -mulr_natl maxr_pmulr ?mulr_natl ?normrMn. Qed.\n\nLemma normrN x : norm (- x) = norm x.\nProof. by rewrite /norm/= !normrN. Qed.\n\nDefinition normedZmodMixin :\n  @Num.normed_mixin_of R [zmodType of U * V] (Num.NumDomain.class R) :=\n  @Num.NormedMixin _ _ _ norm normD norm_eq0 normMn normrN.\n\nCanonical normedZmodType := NormedZmodType R (U * V) normedZmodMixin.\n\nLemma prod_normE (x : normedZmodType) : `|x| = Num.max `|x.1| `|x.2|.\nProof. by []. Qed.\n\nEnd ProdNormedZmodule.\n\nModule Exports.\nCanonical normedZmodType.\nDefinition prod_normE := @prod_normE.\nEnd Exports.\n\nEnd ProdNormedZmodule.\nExport ProdNormedZmodule.Exports.\n", "meta": {"author": "math-comp", "repo": "analysis", "sha": "ee12aba894e8949a32daa9d2ee72b3a440c0609f", "save_path": "github-repos/coq/math-comp-analysis", "path": "github-repos/coq/math-comp-analysis/analysis-ee12aba894e8949a32daa9d2ee72b3a440c0609f/theories/prodnormedzmodule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7096553387954492}}
{"text": "Require Import Arith.\nImport Nat.\n\n\nLoad hoare.\n\n\n(*\neuclid(a, b):\n  while a != b do\n    if a > b then\n      a := a - b\n    else\n      b := b - a\n *)\n\nDefinition gt01 n m := if gt_dec n m then 1 else 0.\nDefinition ne01 n m := if eq_dec n m then 0 else 1.\n\nNotation \"[ e1 `-` e2 ]\" := (expr_op e1 sub e2).\nNotation \"[ e1 `>` e2 ]\" := (expr_op e1 gt01 e2).\nNotation \"[ e1 `!=` e2 ]\" := (expr_op e1 ne01 e2).\n\n\nDefinition euclid_cmd :=\n  while [expr_var a `!=` expr_var b]\n        (if_then_else [expr_var a `>` expr_var b]\n                      (assign a [expr_var a `-` expr_var b])\n                      (assign b [expr_var b `-` expr_var a])).\n\n\n(* Definition of divisibility + some syntactic sugar *)\nDefinition divides a b := exists k, a * k = b.\nNotation \"( a | b )\" := (divides a b).\n\n\nModule MainProof.\n\n  Definition c := if_then_else [expr_var a `>` expr_var b]\n                               (assign a [expr_var a `-` expr_var b])\n                               (assign b [expr_var b `-` expr_var a]).\n\n  Definition linv a0 b0 :=\n    fun s => forall z, (z | a0) /\\ (z | b0) <-> (z | s a) /\\ (z | s b).\n\n  (* Control the behavior of `simpl` to allow more unfoldings. *)\n  Arguments subst P v e /.\n  Arguments set s v / z.\n  Arguments var_eq_dec !v1 !v2.\n  Arguments gt01 n m / : simpl nomatch.\n  Arguments ne01 n m / : simpl nomatch.\n\n  Require Import Omega.\n  \n  Lemma gt0_le x y : gt01 x y = 0 <-> x <= y.\n  Proof.\n    unfold gt01.\n    destruct (gt_dec x y); firstorder.\n  Qed.\n\n  Lemma gt1_gt x y : gt01 x y <> 0 <-> x > y.\n  Proof.\n    unfold gt01.\n    destruct (gt_dec x y); firstorder.\n  Qed.\n\n  Lemma div_sub a b z : (z | a) -> (z | b) -> (z | a - b).\n  Proof.\n    firstorder. exists (x1 - x0).\n    rewrite Nat.mul_sub_distr_l.\n    firstorder.\n  Qed.\n\n  Lemma sub_div1 a b z : a >= b -> (z | a) -> (z | a - b) -> (z | b).\n  Proof.\n    firstorder. exists (x1 - x0).\n    rewrite Nat.mul_sub_distr_l.\n    firstorder.\n  Qed.\n\n  Lemma sub_div2 a b z : a >= b -> (z | b) -> (z | a - b) -> (z | a).\n  Proof.\n    firstorder. exists (x0 + x1).\n    rewrite Nat.mul_add_distr_l.\n    firstorder.\n  Qed.\n\n\n  Lemma warm_up a0 b0 : hoare (fun s => s a = a0 /\\ s b = b0)\n                              (assign a [expr_var a `-` expr_var b])\n                              (fun s => s a = a0 - b0).\n  Proof.\n    eapply hoare_weaken_l.\n    2: constructor.\n    intros s [H1 H2].\n    simpl. firstorder.\n  Qed.\n\n  Lemma aux1 a0 b0 a b: (forall z, (z | a0) /\\ (z | b0) <-> (z | a) /\\ (z | b)) ->\n                        a > b ->\n                        forall z, (z | a0) /\\ (z | b0) <-> (z | a - b) /\\ (z | b).\n  Admitted.\n\n  Lemma aux2 a0 b0 a b: (forall z, (z | a0) /\\ (z | b0) <-> (z | a) /\\ (z | b)) ->\n                        a < b ->\n                        forall z, (z | a0) /\\ (z | b0) <-> (z | a) /\\ (z | b - a).\n  Admitted.\n                                                     \n  Lemma euclid_inv a0 b0 : hoare (fun s => linv a0 b0 s /\\ s a <> s b)\n                                 c\n                                 (linv a0 b0).\n  Proof.\n    constructor.\n    - eapply hoare_weaken_l.        (* \"then\" branch -- a > b *)\n      2: constructor.\n      unfold linv; simpl.\n      intros; apply aux1.\n      + firstorder.\n      + firstorder. apply gt1_gt. assumption.\n      (*\n      firstorder.\n      + apply div_sub.\n        * apply H. firstorder.\n        * apply H. firstorder.\n      + apply H. split.\n        * { eapply sub_div2 with (b:=s b).\n            - apply gt1_gt in H0. omega.\n            - firstorder.\n            - firstorder.\n          }\n        * eexists; eassumption.\n      + apply H. split. (* identical to previous branch *)\n        * { eapply sub_div2 with (b:=s b).\n            - apply gt1_gt in H0. omega.\n            - firstorder.\n            - firstorder.\n          }\n        * eexists; eassumption.\n      *)\n    - eapply hoare_weaken_l.        (* \"else\" branch -- a < b *)\n      2: constructor.\n      unfold linv; simpl.\n      intros; apply aux2.\n      + firstorder.\n      + firstorder.\n        apply le_neq.\n        firstorder using gt0_le.\n      (*\n      intros s [[H0 H1] H2].  (* can be a bit more economical by *)\n      split.                  (* postponing use of firstorder    *)\n      + split.\n        * apply H0. assumption.\n        * apply div_sub; firstorder.\n      + intro; apply H0. split.\n        * firstorder.\n        * { eapply sub_div2.\n            - apply gt0_le. eassumption.\n            - firstorder.\n            - firstorder.\n          }\n      *)\n  Qed.\n\n  Theorem euclid_post a0 b0 : hoare (fun s => s a = a0 /\\ s b = b0)\n                                    euclid_cmd\n                                    (fun s => forall z, (z | a0) /\\ (z | b0) <-> (z | s a)).\n  Proof.\n    eapply hoare_weaken.\n    Focus 2.\n    {\n      apply hoare_while with (P:=linv a0 b0).\n      eapply hoare_weaken_l.\n      2: apply euclid_inv.\n      unfold linv; simpl. firstorder.\n      unfold ne01 in H0.\n      destruct (eq_dec (s a) (s b)).\n      - firstorder.\n      - firstorder.\n    }\n    Unfocus.\n    - unfold linv. intros s [A B]. subst; firstorder.\n    - unfold linv; simpl. intros s [H1 H2].\n      unfold ne01 in H2; destruct (eq_dec (s a) (s b)).\n      + split; intro; apply H1.\n        firstorder.\n        split. assumption. rewrite <- e; assumption.\n      + firstorder.\n  Qed.\n  \nEnd MainProof.\n", "meta": {"author": "corwin-of-amber", "repo": "various-proofs", "sha": "e7c19549f1d573487f9fb3ebd5d6b80b2c52184b", "save_path": "github-repos/coq/corwin-of-amber-various-proofs", "path": "github-repos/coq/corwin-of-amber-various-proofs/various-proofs-e7c19549f1d573487f9fb3ebd5d6b80b2c52184b/ssar-class/hoare-euclid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7096032913012837}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Eqdep_dec.\n\nFrom Undecidability.Shared Require Import DLW.Utils.utils DLW.Vec.vec DLW.Vec.pos.\nFrom Undecidability.MuRec.Util Require Import recalg.\n\nSet Implicit Arguments.\n\nReserved Notation \"  '[' f ';' v ']' '-[' n '>>' x \" (at level 70).\n\n(* The intuitive meaning of [f;v] -[n>> x is\n   \n      There is a computation of f(v) which costs n and results in x\n    \n    We define it in such a way that \n      1/ the cost is never 0, \n      2/ the cost of compound computation is greater than\n         the sum of the costs of its sub-computations\n      3/ the cost and the result are unique (if they exist) \n      \n **)\n   \nInductive ra_ca : forall k, recalg k -> vec nat k -> nat -> nat -> Prop := \n    | in_ra_ca_cst  : forall n v,             [ra_cst n;        v] -[ 1           >> n\n    | in_ra_ca_zero : forall v,               [ra_zero;         v] -[ 1           >> 0\n    | in_ra_ca_succ : forall v,               [ra_succ;         v] -[ 1           >> S (vec_head v)\n    | in_ra_ca_proj : forall k v j,           [@ra_proj k j;    v] -[ 1           >> vec_pos v j \n    \n    | in_ra_ca_comp : forall k i f (gj : vec (recalg i) k) v q w p x,\n                                   (forall j, [vec_pos gj j;    v] -[ vec_pos q j >> vec_pos w j)\n                               ->             [f;               w] -[ p           >> x\n                               ->             [ra_comp f gj;    v] -[1+p+vec_sum q>> x\n\n    | in_ra_ca_rec_0 : forall k f (g : recalg (S (S k))) v n x,    \n                                              [f;               v] -[ n           >> x \n                               ->             [ra_rec f g;   0##v] -[ S n         >> x\n\n    | in_ra_ca_rec_S : forall k f (g : recalg (S (S k))) v n p x q y,          \n                                              [ra_rec f g;   n##v] -[ p           >> x\n                               ->             [g;         n##x##v] -[ q           >> y\n                               ->             [ra_rec f g; S n##v] -[ 1+p+q       >> y\n                               \n    | in_ra_ca_min : forall k (f : recalg (S k)) v x p w q , \n                           (forall j : pos x, [f;    pos2nat j##v] -[ vec_pos q j >> S (vec_pos w j)) \n                               ->             [f;            x##v] -[ p           >> 0\n                               ->             [ra_min f;        v] -[1+p+vec_sum q>> x\nwhere \" [ f ; v ] -[ n >> x \" := (@ra_ca _ f v n x).\n\nSection inversion_lemmas.\n\n  (* The inversion tactic won't work for the dependent predicate ra_ca so\n      we build the inversion lemma by hand.\n\n      Notice the presence of type-castings (eq_rect ...) which disappear\n      when we instanciate that lemma on the individual cases \n      (the lemmas ra_ca_*_inv below)\n\n      The statement of the lemma is complicated but the proof is trivial !!\n  *)\n\n  Lemma ra_ca_inv k (f : recalg k) v n x : \n    [f;v] -[n>> x -> (n = 1 /\\ exists (H : k = 0), eq_rect _ _ f _ H = ra_cst x)\n                  \\/ (n = 1 /\\ x = 0 /\\ exists (H : k = 1), eq_rect _ _ f _ H = ra_zero)\n                  \\/ (n = 1 /\\ exists (H : k = 1), x = S (vec_head (eq_rect _ _ v _ H)) /\\ eq_rect _ _ f _ H = ra_succ)\n                  \\/ (n = 1 /\\ exists p, x = vec_pos v p /\\ f = ra_proj p)\n                  \\/ (exists i (h : recalg i) gj w q m, n = 1+q+vec_sum m /\\ [h;w] -[q>> x \n                              /\\ (forall p, [vec_pos gj p;v] -[vec_pos m p>> vec_pos w p)\n                              /\\ f = ra_comp h gj) \n                  \\/ (exists k' (H : k = S k') (h : recalg k') g m, \n                                 n = S m \n                              /\\ vec_head (eq_rect _ _ v _ H) = 0\n                              /\\ [h;vec_tail (eq_rect _ _ v _ H)] -[m>> x \n                              /\\ eq_rect _ _ f _ H = ra_rec h g) \n                  \\/ (exists k' (H : k = S k') m y (h : recalg k') g p q, \n                                 vec_head (eq_rect _ _ v _ H) = S m\n                              /\\ n = 1+p+q\n                              /\\ [ra_rec h g; m##vec_tail (eq_rect _ _ v _ H)] -[p>> y                             \n                              /\\ [g; m##y##vec_tail (eq_rect _ _ v _ H)] -[q>> x  \n                              /\\ eq_rect _ _ f _ H = ra_rec h g) \n                  \\/ (exists (g : recalg (S k)) (m w : vec _ x) q,\n                                 n = 1+q+vec_sum m\n                              /\\ (forall p, [g; pos2nat p##v] -[vec_pos m p>> S (vec_pos w p))  \n                              /\\ [g; x##v] -[q>> 0\n                              /\\ f = ra_min g)  \n                 .\n  Proof.\n    induction 1 as [ | | \n                   | k v j \n                   | k i f gj v q w p x \n                   | k f g v n x \n                   | k f g v n p x q y\n                   | k f v x p w q\n                   ].\n    do 0 right; left; split; auto; exists eq_refl; auto.\n    do 1 right; left; do 2 (split; auto); exists eq_refl; auto.\n    do 2 right; left; split; auto; exists eq_refl; split; simpl; auto.\n    do 3 right; left; split; auto; exists j; auto.\n    do 4 right; left; exists k, f, gj, w, p, q; auto.\n    do 5 right; left; exists k, eq_refl, f, g, n; auto.\n    do 6 right; left; exists k, eq_refl, n, x, f, g, p, q; auto.\n    do 7 right; exists f, q, w, p; auto.\n  Qed.\n\n  (* The next proofs by hand are long but not complicated ... we simply have to\n     discard all the unnecessary cases generated by the general\n     inversion lemma using the discriminate tactic *)\n\n  (* Automation is our friend here *)\n\n  (* This is to destruct the inversion lemma \n\n     This lemma creates variables which are partly hard coded ...\n     this is not ideal and could be improved\n   *)\n     \n  Local Ltac myinv := \n    let H := fresh in\n    intros H;\n    apply ra_ca_inv in H;   \n    destruct H as   [ (? & ? & ?) \n                  | [ (? & ? & ? & ?)\n                  | [ (? & ? & ? & ?)\n                  | [ (? & ? & ? & ?)\n                  | [ (? & ? & ? & w' & q' & m' & ? & ? & ? & ?) \n                  | [ (? & ? & ? & ? & m' & ? & ? & ? & ?)\n                  | [ (? & ? & ? & y' & ? & ? & p' & q' & ? & ? & ? & ? & ?) \n                    | (? & m' & w' & q' & ? & ? & ? & ?) \n                    ] ] ] ] ] ] ].\n\n  Ltac injc H := injection H; clear H;\n                 repeat match goal with \n                          |- _ = _ -> _ => \n                          intro; subst end.\n\n  Ltac eqgoal := \n    match goal with \n      |- ?a -> ?b => replace a with b; auto \n    end.\n  \n  Ltac inst H :=\n    let K := fresh in\n    match goal with \n    | [ G : ?x -> _ |- _ ] => \n      match G with \n        H => assert (x) as K; [ clear H | specialize (H K); clear K ]\n      end \n    end.\n\n  Fact eq_gen { X } (P : X -> Type) x : (forall y, y = x -> P y) -> P x.\n  Proof. intros H; apply H, eq_refl. Qed.\n  \n  Ltac gen_eq t := apply eq_gen with (x := t).\n\n  Fact eq_nat_pirr (n m : nat) (H1 H2 : n = m) : H1 = H2.\n  Proof. apply UIP_dec, eq_nat_dec. Qed.\n\n  (* Remove identities of the form H : n = n :> nat and eliminates H \n   by replacing it with eq_refl *)\n\n  Ltac natid :=\n    repeat\n      match goal with \n      |  [ H: ?x = ?x :> nat |- _ ]  => let G := fresh \n                                    in generalize (@eq_nat_pirr _ _ H eq_refl); \n                                       intros G; subst H \n      end;\n    simpl eq_rect in * |- *.\n\n  Local Ltac natSimpl :=\n    repeat match goal with [ H : S _ = S _ |- _ ] => let G := fresh in injection H; intro G; subst; natid end.\n    \n  Local Ltac mydiscr :=     \n     repeat match goal with \n            | H : _ = _ :> nat      |- _  => discriminate H; fail\n            | H : _ = _ :> recalg _ |- _  => discriminate H; fail\n            end.  \n\n  Local Ltac myauto := myinv; subst; natid; natSimpl; mydiscr; auto.\n  \n  Lemma ra_ca_cst_inv i v n x : [ra_cst i;v] -[n>> x -> n = 1 /\\ x = i.\n  Proof. inversion_clear 1; auto. Qed.\n\n  Lemma ra_ca_zero_inv v n x : [ra_zero;v] -[n>> x -> n = 1 /\\ x = 0.\n  Proof. inversion_clear 1; auto. Qed.\n\n  Lemma ra_ca_succ_inv v n x : [ra_succ;v] -[n>> x -> n = 1 /\\ x = S (vec_head v).\n  Proof. myauto. Qed.\n  \n  Local Ltac ra_inj := \n    match goal with \n       | H : ra_proj _   = ra_proj _   |- _ => apply ra_proj_inj in H\n       | H : ra_comp _ _ = ra_comp _ _ |- _ => apply ra_comp_inj in H; destruct H as (? & ? & ?) \n       | H : ra_rec _ _  = ra_rec _ _  |- _ => apply ra_rec_inj in H; destruct H\n       | H : ra_min _    = ra_min _    |- _ => apply ra_min_inj in H\n    end; subst; simpl in * |- *.\n\n  Lemma ra_ca_proj_inv k (p : pos k) v n x : [ra_proj p;v] -[n>> x -> n = 1 /\\ x = vec_pos v p.\n  Proof.\n    myauto; ra_inj; auto.\n  Qed.\n  \n  (* These 4 proofs use variable names which are hard coded\n     in the tactic myinv ... they should not conflict with\n     other variables names but be warned that this is not \n     an ideal situation for the stability of those proofs\n   *)\n\n  Lemma ra_ca_comp_inv k i f (gj : vec (recalg i) k) v n x : \n     [ra_comp f gj;v] -[n>> x -> exists p w q,\n                                   n = 1+p+vec_sum q \n                                /\\ (forall j, [vec_pos gj j;v] -[vec_pos q j>> vec_pos w j)\n                                /\\ [f;w] -[p>> x.\n  Proof.\n    myauto; ra_inj. \n    exists q', w', m'; auto.\n  Qed.\n  \n  Lemma ra_ca_rec_0_inv k f g v n x : \n    [@ra_rec k f g; 0##v] -[n>> x -> exists m, n = S m /\\ [f;v] -[m>> x.\n  Proof.\n    myauto; ra_inj.\n    exists m'; auto.\n  Qed.\n\n  Lemma ra_ca_rec_S_inv k f g v i n x : \n     [@ra_rec k f g; S i##v] -[n>> x -> exists y p q, \n                                          n = 1+q+p\n                                       /\\ [ra_rec f g; i##v] -[q>> y\n                                       /\\ [g; i##y##v] -[p>> x.\n  Proof.\n    myauto; ra_inj; natSimpl.\n    exists y', q', p'; auto.\n  Qed.\n\n  Lemma ra_ca_min_inv k f v n x : \n     [@ra_min k f;v] -[n>> x -> exists p w q,\n                                 n = 1+p+vec_sum q\n                              /\\ [f;x##v] -[p>> 0\n                              /\\ forall j, [f;pos2nat j##v] -[vec_pos q j>> S (@vec_pos _ x w j). \n  Proof.\n    myauto; ra_inj.\n    exists q', w', m'; auto.\n  Qed.\n\nEnd inversion_lemmas.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/MuRec/Util/ra_ca.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7096032812119145}}
{"text": "Set Implicit Arguments.\n\nDefinition myTrue : Prop := forall P:Prop, P->P. (* impredicative definition : refers to itself *)\n\nDefinition myFalse: Prop := forall P:Prop, P.    (* impredicative definition *)\n(* It can be shown that no proof of myFalse exists from empty context *)\n\n\nTheorem myTrue_holds: myTrue.\nProof.\n  intros P p; assumption.\nQed.\n\nTheorem myFalse_ind: forall P:Prop, myFalse -> P.\nProof.\n  intros P H. apply H.   \nQed.\n\nDefinition myNot (P:Prop) : Prop := P->myFalse.\n\nLemma L1 : myNot myFalse.\nProof.\n  unfold myNot. intro H. exact H.\nQed.\n\n\nDefinition myAnd (P Q:Prop) :=\n  forall R:Prop, (P->Q->R)->R.\n\nDefinition myOr (P Q:Prop) :=\n  forall R:Prop, (P->R)->(Q->R)->R.\n\nDefinition myEx (A:Type)(P: A->Prop) :=\n  forall R:Prop, (forall x:A, P x -> R)->R.\n\nLemma L2 : forall P Q:Prop, myAnd P Q -> P.\nProof.\n  intros P Q H. unfold myAnd in H. apply H. intros p q. exact p.\nQed.\n\nLemma L3 : forall P Q:Prop, myAnd P Q -> Q.\nProof.\n  intros P Q H. unfold myAnd in H. apply H. intros p q. exact q.\nQed.\n\nCheck and_ind. (* forall A B P : Prop, (A -> B -> P) -> A /\\ B -> P *)\nLemma myAnd_ind : forall P Q R : Prop, (P->Q->R)-> myAnd P Q -> R.\nProof.\n  intros P Q R H and. unfold myAnd in and. apply and. exact H.\nQed.\n\nLemma L4 : forall P Q: Prop, P-> myOr P Q.\nProof.\n  intros P Q p. unfold myOr. intros R Hp Hq. apply Hp. exact p.\nQed.\n\n\nLemma L5 : forall P Q: Prop, Q-> myOr P Q.\nProof.\n  intros P Q q. unfold myOr. intros R Hp Hq. apply Hq. exact q.\nQed.\n\nCheck or_ind. (* forall A B P : Prop, (A -> P) -> (B -> P) -> A \\/ B -> P *)\nLemma myOr_ind : forall P Q R: Prop, (P->R) -> (Q->R) -> myOr P Q -> R.\nProof.\n  intros P Q R Hp Hq H. apply H. exact Hp. exact Hq. \nQed.\n\nLemma L6 : forall P:Prop, myOr P myFalse -> P.\nProof.\n  intros P H. unfold myOr in H. apply H. intro p. exact p. apply myFalse_ind.\nQed.\n\nLemma L7 : forall P Q:Prop, myOr P Q -> myOr Q P.\nProof.\n  intros P Q H. unfold myOr in H. apply H. \n  apply L5 with (Q:=P)(P:=Q). apply L4 with (Q:=P)(P:=Q).\nQed.\n\nCheck ex_ind. (* forall (A : Type) (P : A -> Prop) (P0 : Prop),\n                (forall x : A, P x -> P0) -> (exists x, P x) -> P0 *)\n\nCheck ex_intro. (* forall (A : Type) (P : A -> Prop) (x : A), P x -> exists x, P x *) \n\nLemma myEX_intro : forall (A:Type)(P:A->Prop)(a:A), P a -> myEx P.\nProof.\n  intros A P a H. unfold myEx. intros R All. apply All with (x:=a). exact H.\nQed.\n\nLemma L8 : forall (A:Type)(P:A->Prop),\n  myNot (myEx P) -> forall a:A, myNot (P a).\nProof.\n  intros A P H a. unfold myNot. unfold myNot in H. intro Pa. apply H. unfold myEx.\n  intros R all. apply all with (x:=a). exact Pa.\nQed.\n\nDefinition myLe (n p:nat) :=\n  forall P:nat->Prop, P n -> (forall q:nat, P q -> P (S q)) -> P p.\n\nCheck le_n. (* forall n : nat, n <= n *)\n\nLemma myLe_n : forall n:nat, myLe n n.\nProof.\n  unfold myLe. intros n P H0 H1. exact H0.\nQed.\n\nCheck le_S. (* forall n m : nat, n <= m -> n <= S m *)\n\nLemma myLe_S : forall n m:nat, myLe n m -> myLe n (S m).\nProof.\n  intros n m H. unfold myLe in H. apply H. unfold myLe.\n  intros P Pn Stable. apply Stable. exact Pn. intros q H0.\n  unfold myLe. intros P Pn Stable. unfold myLe in H0. apply Stable.\n  apply H0. exact Pn. exact Stable.\nQed.\n\nLemma myLe_le : forall n m:nat, myLe n m -> n <=  m.\nProof.\n  intros n m H. unfold myLe in H. apply H. apply le_n.\n  intros q H0. apply le_S. exact H0.\nQed.\n\nCheck nat_ind. (* forall P : nat -> Prop,\n       P 0 -> (forall n : nat, P n -> P (S n)) -> forall n : nat, P n *)\n\nLemma le_myLe : forall n m: nat, n <= m -> myLe n m.\nAbort.\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/impredicative.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7096032770000696}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Core logical definitions (all imported from the Prelude)                *\n**************************************************************************)\n\nSet Implicit Arguments.\n\n\n(* ********************************************************************** *)\n(** * Basic logical connectives *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [True] *)\n\n(** From Prelude:\n\n    Inductive True : Prop :=\n      | I : True.\n\n    Hint Constructors True : core.\n\n  Remark: [constructor] should be renamed to [True_intro].\n  Single-letter variable names should be reserved to the user.\n\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [False] *)\n\n(** From Prelude:\n\n    Inductive False : Prop := .\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [not] *)\n\n(** From Prelude:\n\n  Definition not (P : Prop) := P -> False.\n\n  Notation \"~ x\" := (not x) : type_scope.\n\n  Hint Unfold not : core.\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [and] *)\n\n(** From Prelude:\n\n    Inductive and (P Q : Prop) : Prop :=\n      | conj : P -> Q -> and P Q.\n\n    Notation \"P /\\ Q\" := (and P Q) : type_scope.\n\n    Hint Constructors and : core.\n\n    Lemma proj1 : forall (P Q : Prop), P /\\ Q -> P.\n    Proof using. autos*. Qed.\n\n    Lemma proj2 : forall (P Q : Prop), P /\\ Q -> Q.\n    Proof using. autos*. Qed.\n\n  Remark: to follow conventions, [conj] should be renamed to [and_intro].\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [or] *)\n\n(** From Prelude:\n\n    Inductive or (P Q : Prop) : Prop :=\n      | or_introl : P -> or P Q\n      | or_intror : Q -> or P Q.\n\n    Notation \"A \\/ B\" := (or A B) : type_scope.\n\n    Hint Constructors or : core.\n\n  Remark: to follow conventions, constructors should be [or_l] and [or_r].\n\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [iff] *)\n\n(** From Prelude:\n\n      Definition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\n      Notation \"P <-> Q\" := (iff P Q) : type_scope.\n\n      Hint Unfold iff.\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [eq] *)\n\n(** From Prelude:\n\n      Inductive eq (A:Type) (x:A) : A -> Prop :=\n        | eq_refl : eq x y.\n\n      Notation \"x = y :> A\" := (@eq A x y) : type_scope.\n      Notation \"x = y\" := (eq x y) : type_scope.\n      Notation \"x <> y :> A\" := (~ @eq A x y) : type_scope.\n      Notation \"x <> y\" := (~ eq x y) : type_scope.\n\n      Arguments eq_ind [A].\n      Arguments eq_rec [A].\n      Arguments eq_rect [A].\n\n      Hint Constructors eq : core.\n\n  Remark : to follow conventions, constructors should be named [eq_intro],\n  or [refl_eq].\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [exists x, P] *)\n\n(** From Prelude:\n\n    Inductive ex (A : Type) (P : A->Prop) : Prop :=\n      | ex_intro : forall x, P x -> ex P.\n\n    Notation \"'exists' x , p\" := (ex (fun x => p))\n      (at level 200, x ident, right associativity) : type_scope.\n    Notation \"'exists' x : t , p\" := (ex (fun x:t => p))\n      (at level 200, x ident, right associativity,\n        format \"'[' 'exists'  '/  ' x  :  t ,  '/  ' p ']'\")\n      : type_scope.\n\n    Hint Constructors ex : core.\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [forall x, P] and [P -> Q] *)\n\n(** [forall] and [->] are builtin in the logic.\n    [P -> Q] is short for [forall (_:P), Q]. *)\n\n(** From Prelude:\n\n    Definition all (A : Type) (P : A->Prop) := forall (x:A), P x.\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [{x | P}] (subset type) *)\n\n(** From Prelude:\n\n    Inductive sig (A : Type) (P : A->Prop) : Type :=\n      | exist : forall x, P x -> sig P.\n\n    Notation \"{ x | P }\" := (sig (fun x => P)) : type_scope.\n    Notation \"{ x : A | P }\" := (sig (fun x:A => P)) : type_scope.\n    Add Printing Let sig.\n\n  Remark : to follow conventions, constructor should be named [sig_intro].\n\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definition of [{x & P}] (subset type in Type) *)\n\n(** From Prelude:\n\n    Inductive sigT (A : Type) (P : A -> Type) : Type :=\n      | existT : forall x, P x -> sigT P.\n\n    Notation \"{ x & P }\" := (sigT (fun x:A => P)) : type_scope.\n    Notation \"{ x : A & P }\" := (sigT (fun x:A => P)) : type_scope.\n    Add Printing Let sigT.\n\n  Remark : to follow conventions, constructor should be named [sigT_intro].\n\n*)\n\n\n", "meta": {"author": "charguer", "repo": "tlc", "sha": "590c8c8d80442376b8ac19198b7ed446cebc6934", "save_path": "github-repos/coq/charguer-tlc", "path": "github-repos/coq/charguer-tlc/tlc-590c8c8d80442376b8ac19198b7ed446cebc6934/src/LibLogicCore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7095984860078622}}
{"text": "Definition divides (n m : nat) := exists p : nat, p*n = m.\n\nRequire Import Arith.\nRequire Import Omega.\n\nTheorem divides_0 : forall n : nat, divides n 0.\nProof.\n  intros n. unfold divides. exists 0. auto with arith.\nQed.\n\nTheorem divides_plus : forall n m : nat, divides n m -> divides n (n + m).\nProof.\n  intros n m H; elim H; intros p H'; exists (S p). simpl. auto with arith.\nQed.\n\nTheorem not_divides_plus : forall n m : nat, ~divides n m -> ~divides n (n + m).\nProof.\n  intros n m H; unfold not; intros H'; elim H'; intros x.\n  case x; simpl.\n  intros H''; apply H.\n  cut (m=0).\n  intros H'''; rewrite H'''; apply divides_0.\n  omega.\n  intros n0 H''; apply H.\n  unfold divides; exists n0.\n  omega.\nQed.\n\nTheorem not_divides_tl : forall n m : nat, 0 < m -> m < n -> ~ divides n m.\nProof.\n  intros n m H H0 H1.\n  elim H1; intros x H2.\n  rewrite <- H2 in H.\n  rewrite <- H2 in H0.\n  generalize H H0.\n  case x.\n  intros H'; absurd (0 < 0 * n); auto with arith.\n  intros n0. simpl.\n  intros H3 H4.\n  absurd (n <= n + n0 * n); auto with arith.\nQed.\n\nTheorem not_lt_2_divides :\n  forall n m : nat, n <> 1 -> n < 2 -> 0 < m ->\n                    ~ divides n m.\nProof.\n  intros n m h h0.\n  cut (n = 0).\n  intros h1.\n  rewrite h1.\n  case m.\n  intros h2; absurd (0 < 0); [auto with arith | trivial].\n  intros n0 h3 h4. elim h4.\n  intros n1. omega.\n  omega.\nQed.\n\nTheorem  le_plus_minus : forall n m:nat, le n m -> m = n+(m-n).\nProof.  intros n m h.  omega. Qed.\n\nTheorem  lt_lt_or_eq : forall n m:nat, n < S m ->  n<m \\/  n=m.\nProof.  intros n m. omega. Qed.\n  \n                                             \n (*\nZpos_xI  : forall p:positive, Zpos (xI p) = (2 * Zpos p + 1)%Z\nZpos_xO  : forall p:positive, Zpos (xO p) = (2 * Zpos p)%Z\n  *)\n\nLtac repeat_rewrite :=\n  match goal with\n    |- context [Zpos (xO ?p)] =>\n    match p with\n      | xH => fail 1\n      | ?x2 => rewrite (Zpos_xO x2); repeat_rewrite\n    end\n  | |- context [Zpos (xI ?p)] =>\n    match p with\n    | xH => fail 1\n    | ?x2 => rewrite (Zpos_xI x2); repeat_rewrite\n    end\n  | |- _ => idtac\n  end.\n\n", "meta": {"author": "Ablach", "repo": "CoqArt_exercises", "sha": "a2c38b095b6972e57a3c152ec22f3100475b6186", "save_path": "github-repos/coq/Ablach-CoqArt_exercises", "path": "github-repos/coq/Ablach-CoqArt_exercises/CoqArt_exercises-a2c38b095b6972e57a3c152ec22f3100475b6186/ch7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7095984830213459}}
{"text": "      \n(* \n  Some experiments with equality.\n  1. About the definitionand the usual properties of equality.\n  2. The Axiom of Extensionality for equality.\n*)\n\nPrint eq.\n\nEval simpl in (eq 2 2).   (* 2=2:Prop *)\n\nEval simpl in 1=2 /\\ 2=2.\n\n(* Coq out-of-the-box example first *)\n\nLemma coq_equality_is_transitive : forall (T : Type) (x y z: T), \n x = y /\\ y = z -> x = z.\nProof. \n  intros T x y z H. \n  inversion H as [Hx Hy]. \n  rewrite -> Hx.\n  rewrite -> Hy.\n  reflexivity.\nQed.\n\n(* similarly,  = is transitive   *)\n\nModule My_Equality.  (* equality test kitchen *)\n\n(* Print eql. *)   (* not defined *)\n\nInductive eql {T : Type} (x : T) : T -> Prop :=\n  eql_refl : eql x x.\n\nPrint eq.\nPrint eql.\n\nLemma eql_is_transitive_trans : forall (T : Type) (x y z: T), \n eql x y /\\ eql y z -> eql x z.\nProof.\n  intros T x y z H.\n  inversion H as [Hx Hy].\n  (* rewrite -> Hx.  NO!  *)\n  induction Hx.\n  induction Hy.\n  (* reflexivity.  NO! *)\n  apply eql_refl.\nQed.\n\n\nLemma eql_is_symmetric : forall (T : Type) (x y : T), \n eql x y -> eql y x.\nProof.\n  intros X x y H.  (* i.e. call T X *)\n  induction H.\n  (* reflexivity.  NO! *)\n  apply eql_refl.\nQed.\n\n\nLemma eql_is_leibniz_equality : forall (T : Type) (x y: T), \n eql x y -> forall P : T -> Prop, P x -> P y.\nProof.  (* same as for builtin Coq = *)\nintros X x y H.\ninduction H.\nintros P H. apply H.\nQed.\n\n(* eql has same definition as eq so, of course ... *)\nTheorem eql_is_eq : forall (T: Type) (x y : T),\n   eql x y <-> x = y.\nProof.\nintros T x y. \nsplit. \n(* -> *) \nintros H. induction H. reflexivity. \n(* <- *)\nintros H. subst.\napply eql_refl. \nQed.\n\n(* extensionality for our eql *)\nAxiom eql_extensionality : \n  forall {X Y: Type} {f g : X -> Y},\n    (forall (x: X), f x = g x) ->  eql f g.\n\nDefinition f (m : nat) : nat := m+1.\nDefinition g (n : nat) : nat := 1+n.\nDefinition h (o : nat) : nat := o+1.\n\nLemma plus_comm : forall n m : nat,\n  n + m = m + n.\nProof.\n  (* known *) Admitted.\n\nLemma a : eql f g.\nProof. apply eql_extensionality.\n(* work from inside out *)\nintros.  unfold f. unfold g. apply plus_comm.\nQed.\n\nLemma b : f = h.\nProof. reflexivity.  (* definitions of f and h unify *)\nQed.\n\nLemma c : f = g.\nProof. (* error reflexivity. *) \nunfold f. unfold g. (* STUCK  *)\nAbort. (* because = has no extensionality axiom *)\n\nEnd My_Equality.\n", "meta": {"author": "gf4t47", "repo": "coq", "sha": "420c6322eb340e0a0299f5ac07a2a6f495ffc72d", "save_path": "github-repos/coq/gf4t47-coq", "path": "github-repos/coq/gf4t47-coq/coq-420c6322eb340e0a0299f5ac07a2a6f495ffc72d/Equality_Experiments2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7095984809661315}}
{"text": "(* proplogicST.v - ver 0.1 - Steven Tschantz - 2/3/22*)\n(* Laguage, sematics, and proofs for proposition logic *)\n(* Lukasiewicz axiom system with countably many variables *)\n(* PL = Propositional Logic *)\n\nRequire Import List.\nRequire Import Arith.\n\n\n\nSection PL_options.\n\n(* Index variables by nat.  Or switch? *)\n\nDefinition PL_VarIndex : Type := nat.\n\nTheorem PL_decidableVarIndex : forall {x y : PL_VarIndex}, {x = y} + {~ x = y}.\nProof.\ndecide equality.\nQed.\n\nDefinition PL_varO := O.\n\nDefinition PL_varS := S.\n\nDefinition PL_varle := le.\n\nDefinition PL_varlt := lt.\n\nDefinition PL_varmax := max.\n\n(* Take valuations in type bool.  For now? *)\n\nDefinition PL_Value : Type := bool.\n\nDefinition PL_neg_interpretation (b : PL_Value) : PL_Value :=  negb b.\n\nDefinition PL_imp_interpretation (b c : PL_Value) : PL_Value := orb (negb b) c.\n\nDefinition PL_top_interpretation : PL_Value := true.\n\nDefinition PL_bot_interpretation : PL_Value := false.\n\nEnd PL_options.\n\n\n\nSection PL_language.\n\n(* We give an inductive definition of formulas *)\nInductive PL_Formula: Type :=\n| PL_var : PL_VarIndex->PL_Formula\n| PL_neg : PL_Formula->PL_Formula\n| PL_imp : PL_Formula->PL_Formula->PL_Formula\n.\n\nDefinition PL_and (A B : PL_Formula) : PL_Formula :=\nPL_neg (PL_imp A (PL_neg B)).\n\nDefinition PL_or (A B : PL_Formula) : PL_Formula :=\nPL_imp (PL_neg A) B.\n\nDefinition PL_iff (A B : PL_Formula) : PL_Formula :=\nPL_and (PL_imp A B) (PL_imp B A).\n\nDefinition PL_top : PL_Formula := PL_imp (PL_var 0) (PL_var 0).\n\nDefinition PL_bot : PL_Formula := PL_neg PL_top.\n\nDefinition PL_listor (S : list PL_Formula) : PL_Formula :=\n  fold_right PL_or PL_bot S.\n\nDefinition PL_listand (S : list PL_Formula) : PL_Formula :=\n  fold_right PL_and PL_top S.\n\nDefinition PL_decidableFormula (A B : PL_Formula) : {A = B} + {~ A = B}.\nProof.\ndecide equality.\napply PL_decidableVarIndex.\nDefined.\n\nDefinition PL_SubstFunction : Type := PL_VarIndex -> PL_Formula.\n\nFixpoint PL_subst (s : PL_SubstFunction) (A : PL_Formula) : PL_Formula :=\nmatch A with\n| PL_var n => s n\n| PL_neg X => PL_neg (PL_subst s X)\n| PL_imp X Y => PL_imp (PL_subst s X) (PL_subst s Y)\nend.\n\nDefinition PL_subst1 (A : PL_Formula) : PL_SubstFunction :=\nfun (n : nat) => \nmatch n with \n| O => A\n| _ => PL_var n\nend.\n\nDefinition PL_subst2 (A B : PL_Formula) : PL_SubstFunction :=\nfun (n : nat) => \nmatch n with \n| O => A\n| 1 => B\n| _ => PL_var n\nend.\n\nDefinition PL_subst3 (A B C : PL_Formula) : PL_SubstFunction :=\nfun (n : nat) => \nmatch n with \n| O => A\n| 1 => B\n| 2 => C\n| _ => PL_var n\nend.\n\nDefinition PL_subst_compose (s t : PL_SubstFunction) : PL_SubstFunction :=\nfun (n : PL_VarIndex) => PL_subst s (t n).\n\nTheorem PL_subst_subst :\nforall (s t : PL_SubstFunction) (A : PL_Formula),\n  PL_subst (PL_subst_compose s t) A = PL_subst s (PL_subst t A).\nProof.\nintros s t A.\ninduction A as [n | A H1 | A H2 B H3].\nreflexivity.\nsimpl.\nrewrite H1.\nreflexivity.\nsimpl.\nrewrite H2.\nrewrite H3.\nreflexivity.\nQed.\n\n(* Important formulas as examples *)\n\nDefinition PL_axiom1prototype : PL_Formula :=\n(PL_imp (PL_var 0) (PL_imp (PL_var 1) (PL_var 0))).\n\nDefinition PL_axiom2prototype : PL_Formula :=\nPL_imp\n (PL_imp (PL_var 0) (PL_imp (PL_var 1) (PL_var 2)))\n (PL_imp (PL_imp (PL_var 0) (PL_var 1)) (PL_imp (PL_var 0) (PL_var 2))).\n\nDefinition PL_axiom3prototype : PL_Formula :=\nPL_imp \n  (PL_imp (PL_neg (PL_var 0)) (PL_neg (PL_var 1)))\n  (PL_imp (PL_var 1) (PL_var 0)).\n\nDefinition PL_axiom1instance (A B : PL_Formula) : PL_Formula :=\nPL_subst (PL_subst2 A B) PL_axiom1prototype.\n\nDefinition PL_axiom2instance (A B C : PL_Formula) : PL_Formula :=\nPL_subst (PL_subst3 A B C) PL_axiom2prototype.\n\nDefinition PL_axiom3instance (A B : PL_Formula) : PL_Formula :=\nPL_subst (PL_subst2 A B) PL_axiom3prototype.\n\nEnd PL_language.\n\n\n\nSection PL_semantics.\n\n(* These are the \"models\" *)\nDefinition PL_Valuation : Type := PL_VarIndex -> PL_Value.\n\n(* This is the interpretation of a formula in a \"model\" *)\nFixpoint PL_interpretation (f : PL_Valuation) (A : PL_Formula) : PL_Value :=\nmatch A with\n| PL_var n => f n\n| PL_neg X => PL_neg_interpretation (PL_interpretation f X)\n| PL_imp X Y => PL_imp_interpretation (PL_interpretation f X) (PL_interpretation f Y)\nend.\n\n(* This is then $f\\models A$ *)\nDefinition PL_models (f : PL_Valuation) (A : PL_Formula) : Prop :=\nPL_interpretation f A = PL_top_interpretation.\n\n(* We start with only finite lists of assumptions.  We might like to generalize this. *)\n(* This is when a (finite) set of formulas semantically entails a formula, $S\\models A$ *)\nDefinition PL_list_models (S : list PL_Formula) (A : PL_Formula) : Prop :=\nforall (f : PL_Valuation),\n  Forall (PL_models f) S -> PL_models f A.\n\nTheorem PL_sublist_models :\nforall (S T : list PL_Formula) (A : PL_Formula),\n  incl S T -> PL_list_models S A -> PL_list_models T A.\nProof.\nintros S T A H1 H2 f H3.\napply H2.\napply incl_Forall with T.\nassumption.\nassumption.\nQed.\n\nDefinition PL_valid (A : PL_Formula) : Prop := PL_list_models nil A.\n\nTheorem PL_valid_list_models:\nforall (S : list PL_Formula) (A : PL_Formula),\n  PL_valid A -> PL_list_models S A.\nProof.\nintros S A.\napply PL_sublist_models.\napply incl_nil_l.\nQed.\n\nDefinition PL_valuation_subst (f : PL_Valuation) (s : PL_SubstFunction) : PL_Valuation :=\nfun (n : PL_VarIndex) => PL_interpretation f (s n).\n\nTheorem PL_interpretation_subst :\nforall (f : PL_Valuation) (s : PL_SubstFunction) (A : PL_Formula),\n  PL_interpretation f (PL_subst s A) = PL_interpretation (PL_valuation_subst f s) A.\nProof.\nintros f s A.\ninduction A as [n|X H1|X H2 Y H3].\nreflexivity.\nsimpl.\nrewrite H1.\nreflexivity.\nsimpl.\nrewrite H2.\nrewrite H3.\nreflexivity.\nQed.\n\nTheorem PL_models_subst :\nforall (f : PL_Valuation) (s : PL_SubstFunction) (A : PL_Formula),\n  PL_models f (PL_subst s A) <-> PL_models (PL_valuation_subst f s) A.\nProof.\nintros f s A.\nunfold PL_models.\nrewrite PL_interpretation_subst.\ntauto.\nQed.\n\nTheorem PL_valid_subst_valid : \nforall (s : PL_SubstFunction) (A : PL_Formula),\n  PL_valid A -> PL_valid (PL_subst s A).\nProof.\nintros s A H1 f H2.\nassert (H3 : PL_models (PL_valuation_subst f s) A).\napply H1.\nauto.\nrewrite PL_models_subst.\nassumption.\nQed.\n\nTheorem PL_axiom1prototypevalid : PL_valid PL_axiom1prototype.\nProof.\nintros f H.\nvm_compute.\ndestruct (f 0); destruct (f 1); reflexivity.\nQed.\n \nTheorem PL_axiom2prototypevalid : PL_valid PL_axiom2prototype.\nProof.\nintros f H.\nvm_compute.\ndestruct (f 0); destruct (f 1); destruct (f 2); reflexivity.\nQed.\n \nTheorem PL_axiom3prototypevalid : PL_valid PL_axiom3prototype.\nProof.\nintros f H.\nvm_compute.\ndestruct (f 0); destruct (f 1); reflexivity.\nQed.\n\nTheorem PL_axiom1instancevalid : \nforall (A B : PL_Formula), PL_valid (PL_axiom1instance A B).\nProof.\nintros A B.\nunfold PL_axiom1instance.\napply PL_valid_subst_valid.\napply PL_axiom1prototypevalid.\nQed.\n\nTheorem PL_axiom2instancevalid : \nforall (A B C : PL_Formula), PL_valid (PL_axiom2instance A B C).\nProof.\nintros A B C.\nunfold PL_axiom2instance.\napply PL_valid_subst_valid.\napply PL_axiom2prototypevalid.\nQed.\n\nTheorem PL_axiom3instancevalid : \nforall (A B : PL_Formula), PL_valid (PL_axiom3instance A B).\nProof.\nintros A B.\nunfold PL_axiom3instance.\napply PL_valid_subst_valid.\napply PL_axiom3prototypevalid.\nQed.\n\nTheorem PL_MPvalid :\nforall (S : list PL_Formula) (A B : PL_Formula),\n  PL_list_models S A -> PL_list_models S (PL_imp A B) -> PL_list_models S B.\nProof.\nintros S A B H1 H2 f H3.\nassert (H4 := H2 f H3).\nrevert H4.\nassert (H5 := H1 f H3).\nrevert H5.\nunfold PL_models.\nsimpl.\ndestruct (PL_interpretation f A);\ndestruct (PL_interpretation f B);\nauto.\nQed.\n\nEnd PL_semantics.\n\n\n\nSection PL_decidable_semantics.\n\n(* We don't acutally need arbitrary functions on all variables to decide truth. *)\n(* Only finitely many variables occur in any list of formulas. *)\n(* Consider then funtions that are eventually constant. *)\n\nFixpoint PL_formula_var_bound (b : PL_VarIndex) (A : PL_Formula) : Prop :=\nmatch A with\n| PL_var n => PL_varlt n b\n| PL_neg X => PL_formula_var_bound b X\n| PL_imp X Y => PL_formula_var_bound b X /\\ PL_formula_var_bound b Y\nend.\n\nDefinition PL_formula_list_var_bound (b : PL_VarIndex) (S : list PL_Formula) : Prop :=\nForall (PL_formula_var_bound b) S.\n\nTheorem PL_formula_list_var_bound_nil_iff :\nforall (b : PL_VarIndex), PL_formula_list_var_bound b nil <-> True.\nProof.\nunfold PL_formula_list_var_bound.\nintros b. split.\ntauto.\nintros H1.\napply Forall_nil.\nQed.\n\nTheorem PL_formula_list_var_bound_cons_iff :\nforall (b : PL_VarIndex) (S : list PL_Formula) (A : PL_Formula),\n  PL_formula_list_var_bound b (A::S) <-> \n  PL_formula_var_bound b A /\\ PL_formula_list_var_bound b S.\nProof.\nunfold PL_formula_list_var_bound.\nintros b. split.\nintros H1.\nsplit.\napply (Forall_inv H1).\napply (Forall_inv_tail H1).\nintros [H2 H3].\napply Forall_cons.\nassumption.\nassumption.\nQed.\n\nFixpoint PL_formula_var_max (A : PL_Formula) : PL_VarIndex :=\nmatch A with\n| PL_var n => PL_varS n\n| PL_neg X => PL_formula_var_max X\n| PL_imp X Y => PL_varmax (PL_formula_var_max X) (PL_formula_var_max Y)\nend.\n\nDefinition PL_formula_list_var_max (S : list PL_Formula) : PL_VarIndex :=\nfold_right PL_varmax PL_varO (map PL_formula_var_max S).\n\nTheorem PL_formula_list_var_max_nil_eq :\nPL_formula_list_var_max nil = PL_varO.\nProof.\nreflexivity.\nQed.\n\nTheorem PL_formula_list_var_max_cons_eq :\nforall (S : list PL_Formula) (A : PL_Formula),\n  PL_formula_list_var_max (A::S) = \n  PL_varmax (PL_formula_var_max A) (PL_formula_list_var_max S).\nProof.\nunfold PL_formula_list_var_max.\nintros S A.\nreflexivity.\nQed.\n\nTheorem PL_formula_var_bound_monotonic :\nforall (m n : PL_VarIndex) (A : PL_Formula),\n  PL_varle m n -> PL_formula_var_bound m A -> PL_formula_var_bound n A.\nProof.\nintros m n.\ninduction A as [k|X H1|X H2 Y H3].\nvm_compute. intros. apply le_trans with m; assumption.\nsimpl. assumption.\nsimpl. tauto.\nQed.\n\nTheorem PL_formula_list_var_bound_monotonic :\nforall (m n : PL_VarIndex) (S : list PL_Formula),\n  PL_varle m n -> PL_formula_list_var_bound m S -> PL_formula_list_var_bound n S.\nProof.\nunfold PL_formula_list_var_bound.\nintros m n S H1 H2. induction H2 as [|A T H3 H4 H5].\napply Forall_nil.\napply Forall_cons.\napply PL_formula_var_bound_monotonic with m.\nassumption.\nassumption.\nassumption.\nQed.\n\nTheorem PL_formula_var_bound_max :\nforall (A : PL_Formula),\n  PL_formula_var_bound (PL_formula_var_max A) A.\nProof.\ninduction A as [n|X H1|X H2 Y H3].\nvm_compute. apply le_n.\nsimpl. assumption.\nsimpl. split.\napply PL_formula_var_bound_monotonic with (PL_formula_var_max X).\napply Nat.le_max_l. assumption.\napply PL_formula_var_bound_monotonic with (PL_formula_var_max Y).\napply Nat.le_max_r. assumption.\nQed.\n\nTheorem PL_formula_list_var_bound_max :\nforall (S : list PL_Formula),\n  PL_formula_list_var_bound (PL_formula_list_var_max S) S.\nProof.\ninduction S as [|A T H1].\napply Forall_nil.\nrewrite PL_formula_list_var_bound_cons_iff.\nsplit.\napply PL_formula_var_bound_monotonic with (PL_formula_var_max A).\nunfold PL_formula_list_var_max. simpl.\napply Nat.le_max_l.\napply PL_formula_var_bound_max.\napply PL_formula_list_var_bound_monotonic with (PL_formula_list_var_max T).\napply Nat.le_max_r.\nassumption.\nQed.\n\nTheorem PL_formula_var_max_list_var_max :\n  forall (B : PL_Formula) (S : list PL_Formula),\n  In B S -> le (PL_formula_var_max B) (PL_formula_list_var_max S).\nProof.\nintros B S.\ninduction S as [|B1 S1 H1].\nintros H2.\nexfalso.\nrevert H2.\napply in_nil.\nunfold PL_formula_list_var_max.\nsimpl fold_right. simpl In. \nintros [H3|H4].\nrewrite <- H3.\napply Nat.le_max_l.\napply le_trans with (PL_formula_list_var_max S1).\napply H1.\nassumption.\napply Nat.le_max_r.\nQed.\n\nDefinition PL_valuations_eq_before (b : PL_VarIndex) (f g : PL_Valuation) : Prop :=\nforall (n : PL_VarIndex), PL_varlt n b -> f n = g n.\n\nTheorem PL_interpretations_eq_before :\nforall (b : PL_VarIndex) (f g : PL_Valuation) (A : PL_Formula),\n  PL_valuations_eq_before b f g ->\n  PL_formula_var_bound b A ->\n  PL_interpretation f A = PL_interpretation g A.\nProof.\nintros b f g A H1. revert A.\ninduction A as [n|X H2|X H3 Y H4].\nsimpl. apply H1.\nsimpl. intros H5. assert (H6 := H2 H5). \ndestruct (PL_interpretation f X); destruct (PL_interpretation g X);\ntry (reflexivity); discriminate H6.\nsimpl. intros [H7 H8]. assert (H9 := H3 H7). assert (H10 := H4 H8).\ndestruct (PL_interpretation f X); destruct (PL_interpretation g X);\ndestruct (PL_interpretation f Y); destruct (PL_interpretation g Y);\ntry (reflexivity); try (discriminate H9); discriminate H10.\nQed.\n\nTheorem PL_models_eq_before :\nforall (b : PL_VarIndex) (f g : PL_Valuation) (A : PL_Formula),\n  PL_valuations_eq_before b f g ->\n  PL_formula_var_bound b A ->\n  PL_models f A <-> PL_models g A.\nProof.\nintros b f g A H1 H2.\nunfold PL_models.\nsplit.\nintros H3.\nrewrite <- (PL_interpretations_eq_before b f _ _ H1 H2).\nassumption.\nintros H4.\nrewrite (PL_interpretations_eq_before b f _ _ H1 H2).\nassumption.\nQed.\n\nTheorem PL_models_list_eq_before :\nforall (b : PL_VarIndex) (f g : PL_Valuation) (S : list PL_Formula),\n  PL_valuations_eq_before b f g ->\n  PL_formula_list_var_bound b S ->\n  Forall (PL_models f) S <-> Forall (PL_models g) S.\nProof.\nintros b f g S H1.\nunfold PL_formula_list_var_bound.\ndo 3 rewrite Forall_forall.\nunfold PL_models.\nintros H2.\nsplit.\nintros H3 A H4.\nrewrite <- (PL_interpretations_eq_before b f _ _ H1 (H2 A H4)).\napply H3.\nassumption.\nintros H5 A H6.\nrewrite (PL_interpretations_eq_before b f _ _ H1 (H2 A H6)).\napply H5.\nassumption.\nQed.\n\nDefinition PL_valuation_shift_down (f : PL_Valuation) : PL_Valuation :=\nfun (n : PL_VarIndex) => f (S n).\n\nTheorem PL_valuations_eq_before_S_iff :\nforall (b : PL_VarIndex) (f g : PL_Valuation),\n  PL_valuations_eq_before (S b) f g <->\n  f PL_varO = g PL_varO /\\\n  PL_valuations_eq_before b (PL_valuation_shift_down f) (PL_valuation_shift_down g).\nProof.\nintros b f g.\nsplit.\nintros H1.\nsplit.\napply (H1 0).\napply le_n_S.\napply le_O_n.\nintros n H2.\nunfold PL_valuation_shift_down.\napply H1.\napply le_n_S.\nassumption.\nintros [H3 H4] n H5.\ndestruct n as [|n1].\napply H3.\napply H4.\napply le_S_n.\nassumption.\nQed.\n\n\nDefinition PL_valuation_top : PL_Valuation := fun (n : PL_VarIndex) => PL_top_interpretation.\n\nDefinition PL_valuation_bot : PL_Valuation := fun (n : PL_VarIndex) => PL_bot_interpretation.\n\nDefinition PL_valuation_shift_up_top (f : PL_Valuation) : PL_Valuation :=\nfun (n : PL_VarIndex) =>\n  match n with\n  | O => PL_top_interpretation\n  | S n1 => f n1\n  end.\n\nDefinition PL_valuation_shift_up_bot (f : PL_Valuation) : PL_Valuation :=\nfun (n : PL_VarIndex) =>\n  match n with\n  | O => PL_bot_interpretation\n  | S n1 => f n1\n  end.\n\nFixpoint PL_test_valuations (n : PL_VarIndex) : list (PL_Valuation) :=\nmatch n with\n| O => PL_valuation_top :: PL_valuation_bot :: nil\n| S n1 => (map PL_valuation_shift_up_top (PL_test_valuations n1)) ++ \n          (map PL_valuation_shift_up_bot (PL_test_valuations n1))\nend.\n\n(* A test\nEval compute in (map (fun (f:PL_Valuation)=>f 0 :: f 1 :: f 2 ::nil) (PL_test_valuations 2)).\n*)\n\nLemma PL_shift_up_top_shift_down:\nforall (f : PL_Valuation),\n  f 0 = PL_top_interpretation ->\n  forall (n : PL_VarIndex),\n    f n = PL_valuation_shift_up_top (PL_valuation_shift_down f) n.\nProof.\nintros f H1 n.\ndestruct n as [|n1].\nassumption.\nreflexivity.\nQed.\n\nLemma PL_shift_up_bot_shift_down:\nforall (f : PL_Valuation),\n  f 0 = PL_bot_interpretation ->\n  forall (n : PL_VarIndex),\n    f n = PL_valuation_shift_up_bot (PL_valuation_shift_down f) n.\nProof.\nintros f H1 n.\ndestruct n as [|n1].\nassumption.\nreflexivity.\nQed.\n\nLemma PL_shift_back_top :\nforall (b : PL_VarIndex) (f g : PL_Valuation),\n  f O = PL_top_interpretation ->\n  PL_valuations_eq_before b (PL_valuation_shift_down f) g ->\n  PL_valuations_eq_before (S b) f (PL_valuation_shift_up_top g).\nProof.\nintros b f g H1 H2 n H3.\ndestruct n as [|n1].\nassumption.\nrewrite (PL_shift_up_top_shift_down f H1).\nsimpl.\napply H2.\napply le_S_n.\nassumption.\nQed.\n\nLemma PL_shift_back_bot :\nforall (b : PL_VarIndex) (f g : PL_Valuation),\n  f O = PL_bot_interpretation ->\n  PL_valuations_eq_before b (PL_valuation_shift_down f) g ->\n  PL_valuations_eq_before (S b) f (PL_valuation_shift_up_bot g).\nProof.\nintros b f g H1 H2 n H3.\ndestruct n as [|n1].\nassumption.\nrewrite (PL_shift_up_bot_shift_down f H1).\nsimpl.\napply H2.\napply le_S_n.\nassumption.\nQed.\n\nTheorem PL_bounded_valuations_listed :\nforall (b : PL_VarIndex) (f : PL_Valuation),\n  exists (g : PL_Valuation), In g (PL_test_valuations b) /\\ PL_valuations_eq_before b f g.\nProof.\ninduction b as [|b1 H1].\nintros f. exists PL_valuation_top.\nsplit.\nsimpl.\nauto.\nintros n H2.\nexfalso.\napply (le_Sn_O _ H2).\nintros f.\ndestruct (H1 (PL_valuation_shift_down f)) as [g1 [H3 H4]].\ndestruct (f O) eqn: H5.\nexists (PL_valuation_shift_up_top g1).\nsplit.\nsimpl PL_test_valuations.\napply in_or_app.\nleft.\napply in_map.\nassumption.\nrewrite PL_valuations_eq_before_S_iff.\nsplit.\nassumption.\napply H4.\nexists (PL_valuation_shift_up_bot g1).\nsplit.\nsimpl PL_test_valuations.\napply in_or_app.\nright.\napply in_map.\nassumption.\nrewrite PL_valuations_eq_before_S_iff.\nsplit.\nassumption.\napply H4.\nQed.\n\nDefinition PL_list_models_b (S : list PL_Formula) (A : PL_Formula) : bool :=\nforallb \n  (fun (f : PL_Valuation) => \n     PL_imp_interpretation (forallb (PL_interpretation f) S) (PL_interpretation f A))\n  (PL_test_valuations (PL_varmax (PL_formula_list_var_max S) (PL_formula_var_max A))).\n\nDefinition PL_list_models_b_reflects_PL_list_models:\nforall (S : list PL_Formula) (A : PL_Formula),\n  PL_list_models_b S A = true <-> PL_list_models S A.\nProof.\nintros S A.\nset (b := PL_varmax (PL_formula_list_var_max S) (PL_formula_var_max A)).\nset (test := PL_test_valuations b).\nsplit.\nintros H1 f H2.\ndestruct (PL_bounded_valuations_listed b f) as [g [H3 H4]].\nassert (H5 : Forall (PL_models g) S).\nrewrite <- (PL_models_list_eq_before b f g S).\nassumption.\nassumption.\nunfold b.\napply PL_formula_list_var_bound_monotonic with (PL_formula_list_var_max S).\napply Nat.le_max_l.\napply PL_formula_list_var_bound_max.\nrewrite Forall_forall in H5.\nunfold PL_models in H5.\nunfold PL_list_models_b in H1.\nrewrite forallb_forall in H1.\nunfold PL_models.\nrewrite (PL_interpretations_eq_before b f g).\nassert (H6 := H1 g H3).\ndestruct (PL_interpretation g A) eqn: H7; \ndestruct (forallb (PL_interpretation g) S) eqn: H8;\ntry reflexivity; try discriminate H6.\nassert (H9 := (forallb_forall (PL_interpretation g) S)).\ndestruct H9 as [H10 H11].\nrewrite H11 in H8.\ndiscriminate H8.\nassumption.\nassumption.\nunfold b.\napply PL_formula_var_bound_monotonic with (PL_formula_var_max A).\napply Nat.le_max_r.\napply PL_formula_var_bound_max.\nunfold PL_list_models, PL_models.\nunfold PL_list_models_b.\nrewrite forallb_forall.\nintros H12 g H13.\ndestruct (forallb (PL_interpretation g) S) eqn: H14;\ndestruct (PL_interpretation g A) eqn: H15;\ntry reflexivity.\nrewrite H12 in H15.\ndiscriminate H15.\nrewrite Forall_forall.\nrewrite forallb_forall in H14.\nassumption.\nDefined.\n\nDefinition PL_list_models_decidable (S : list PL_Formula) (A : PL_Formula) :\n  {PL_list_models S A} + {~ PL_list_models S A}.\nProof.\ndestruct (PL_list_models_b S A) eqn: H1.\nleft.\napply PL_list_models_b_reflects_PL_list_models.\nassumption.\nright.\nrewrite <- PL_list_models_b_reflects_PL_list_models.\nintros H2.\nrewrite H2 in H1.\ndiscriminate H1.\nDefined.\n\nDefinition PL_valid_decidable (A : PL_Formula) :\n  {PL_valid A} + {~ PL_valid A}.\nProof.\napply PL_list_models_decidable.\nDefined.\n\nEnd PL_decidable_semantics.\n\n\nSection PL_proofs.\n\nInductive PL_list_proof (S : list PL_Formula) : PL_Formula -> Type :=\n| PL_assumption : forall (A : PL_Formula), In A S -> PL_list_proof S A\n| PL_axiom1 : forall (A B : PL_Formula), PL_list_proof S (PL_axiom1instance A B)\n| PL_axiom2 : forall (A B C : PL_Formula), PL_list_proof S (PL_axiom2instance A B C)\n| PL_axiom3 : forall (A B : PL_Formula), PL_list_proof S (PL_axiom3instance A B)\n| PL_MP : forall (A B : PL_Formula), \n    PL_list_proof S A -> PL_list_proof S (PL_imp A B) -> PL_list_proof S B\n.\n\nDefinition PL_list_proves (S : list PL_Formula) (A : PL_Formula) :=\n  inhabited (PL_list_proof S A).\n\nDefinition PL_list_proof_weaken (S T : list PL_Formula)\n  (subsetST : forall (X : PL_Formula), In X S -> In X T) (A : PL_Formula) \n  (p : PL_list_proof S A) : PL_list_proof T A.\nProof.\ninduction p as [A0 H1|A1 B1|A2 B2 C2|A3 B3|A4 B4 H2 H3 H4 H5].\napply PL_assumption.\napply subsetST.\nassumption.\napply PL_axiom1.\napply PL_axiom2.\napply PL_axiom3.\napply (PL_MP _ A4).\nassumption.\nassumption.\nQed.\n\nDefinition PL_subst_proof (s : PL_SubstFunction) (S : list PL_Formula) (A : PL_Formula)\n  (p : PL_list_proof S A) : PL_list_proof (map (PL_subst s) S) (PL_subst s A).\nProof.\ninduction p as [A0 H1|A1 B1|A2 B2 C2|A3 B3|A4 B4 H2 H3 H4 H5].\napply PL_assumption.\napply in_map_iff.\nexists A0.\nsplit.\nreflexivity.\nassumption.\nunfold PL_axiom1instance.\nrewrite <- PL_subst_subst.\napply PL_axiom1.\nunfold PL_axiom2instance.\nrewrite <- PL_subst_subst.\napply PL_axiom2.\nunfold PL_axiom3instance.\nrewrite <- PL_subst_subst.\napply PL_axiom3.\napply (PL_MP _ (PL_subst s A4)).\nassumption.\nassumption.\nDefined.\n\nDefinition PL_lemma1 : PL_Formula := PL_imp (PL_var 0) (PL_var 0).\n\nDefinition PL_lemma1_proof : PL_list_proof nil PL_lemma1.\nProof.\napply (PL_MP _ (PL_subst (PL_subst2 (PL_var 0) (PL_var 0)) PL_axiom1prototype)).\napply PL_axiom1.\napply (PL_MP _ (PL_subst (PL_subst2 (PL_var 0) PL_lemma1) PL_axiom1prototype)).\napply PL_axiom1.\napply PL_axiom2.\nDefined.\n\nDefinition PL_deduction_thm_forward_proof (S : list PL_Formula) (A B : PL_Formula)\n  (p : PL_list_proof S (PL_imp A B)) : PL_list_proof (A :: S) B.\nProof.\napply (PL_MP _ A).\napply PL_assumption.\napply in_eq.\napply (PL_list_proof_weaken S).\nintros X.\napply in_cons.\nassumption.\nDefined.\n\nDefinition PL_deduction_thm_reverse_proof (S : list PL_Formula) (A B : PL_Formula)\n  (p : PL_list_proof (A :: S) B) : PL_list_proof S (PL_imp A B).\nProof.\ninduction p as [A0 H1|A1 B1|A2 B2 C2|A3 B3|A4 B4 H2 H3 H4 H5].\ndestruct (PL_decidableFormula A A0) as [H6|H7].\nrewrite H6.\napply (PL_list_proof_weaken nil).\nintros X H8.\nexfalso.\nrevert H8.\napply in_nil.\napply (PL_subst_proof (PL_subst1 A0) _ _ PL_lemma1_proof).\napply (PL_MP S A0).\napply PL_assumption.\ndestruct H1 as [H1a|H1b].\ncontradiction H7.\nassumption.\napply (PL_axiom1 S A0 A).\napply (PL_MP _ (PL_axiom1instance A1 B1)).\napply PL_axiom1.\napply PL_axiom1.\napply (PL_MP _ (PL_axiom2instance A2 B2 C2)).\napply PL_axiom2.\napply PL_axiom1.\napply (PL_MP _ (PL_axiom3instance A3 B3)).\napply PL_axiom3.\napply PL_axiom1.\napply (PL_MP _ (PL_imp A A4)).\nassumption.\napply (PL_MP _ (PL_imp A (PL_imp A4 B4))).\nassumption.\napply PL_axiom2.\nDefined.\n\nTheorem PL_deduction_thm :\nforall (S : list PL_Formula) (A B : PL_Formula),\n  PL_list_proves S (PL_imp A B) <-> PL_list_proves (A :: S) B.\nProof.\nintros S A B.\nsplit.\nintros H1.\ndestruct H1 as [p1].\nexists.\napply PL_deduction_thm_forward_proof.\nassumption.\nintros H2.\ndestruct H2 as [p2].\nexists.\napply PL_deduction_thm_reverse_proof.\nassumption.\nQed.\n\n\nDefinition PL_lemma2 : PL_Formula := \n  PL_imp (PL_neg (PL_var 0)) (PL_imp (PL_var 0) (PL_var 1)).\n\nDefinition PL_lemma2_proof : PL_list_proof nil PL_lemma2.\nProof.\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_imp (PL_neg (PL_var 1)) (PL_neg (PL_var 0)))).\napply (PL_MP _ (PL_neg (PL_var 0))).\napply PL_assumption.\napply in_eq.\napply PL_axiom1.\napply PL_axiom3.\nDefined.\n\n\nDefinition PL_lemma3 : PL_Formula := PL_imp (PL_neg (PL_neg (PL_var 0))) (PL_var 0).\n\nDefinition PL_lemma3_proof : PL_list_proof nil PL_lemma3.\nProof.\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_neg (PL_neg (PL_var 0)))).\napply PL_assumption.\napply in_eq.\napply (PL_MP _ (PL_imp (PL_neg (PL_var 0)) (PL_neg (PL_neg (PL_neg (PL_var 0)))))).\napply (PL_MP _ (PL_imp (PL_neg (PL_neg (PL_neg (PL_neg (PL_var 0))))) \n  (PL_neg (PL_neg (PL_var 0))))).\napply (PL_MP _ (PL_neg (PL_neg (PL_var 0)))).\napply PL_assumption.\napply in_eq.\napply PL_axiom1.\napply PL_axiom3.\napply PL_axiom3.\nDefined.\n\nDefinition PL_lemma4 : PL_Formula := PL_imp (PL_var 0) (PL_neg (PL_neg (PL_var 0))).\n\nDefinition PL_lemma4_proof : PL_list_proof nil PL_lemma4.\nProof.\napply (PL_MP _ (PL_imp (PL_neg (PL_neg (PL_neg (PL_var 0)))) (PL_neg (PL_var 0)))).\napply (PL_subst_proof (PL_subst1 (PL_neg (PL_var 0))) _ _ PL_lemma3_proof).\napply PL_axiom3.\nDefined.\n\nDefinition PL_lemma5 : PL_Formula := \n  PL_imp (PL_imp (PL_var 0) (PL_var 1)) (PL_imp (PL_neg (PL_var 1)) (PL_neg (PL_var 0))).\n\nDefinition PL_lemma5_proof : PL_list_proof nil PL_lemma5.\nProof.\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_imp (PL_neg (PL_neg (PL_var 0))) (PL_neg (PL_neg (PL_var 1))))).\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_var 1)).\napply (PL_MP _ (PL_var 0)).\napply (PL_MP _ (PL_neg (PL_neg (PL_var 0)))).\napply PL_assumption.\napply in_eq.\napply PL_list_proof_weaken with nil.\nintros X H1.\nexfalso.\nrevert H1.\napply in_nil.\napply PL_lemma3_proof.\napply PL_assumption.\napply in_cons.\napply in_eq.\napply PL_list_proof_weaken with nil.\nintros X H1.\nexfalso.\nrevert H1.\napply in_nil.\napply (PL_subst_proof (PL_subst1 (PL_var 1)) _ _ PL_lemma4_proof).\napply PL_axiom3.\nDefined.\n\nDefinition PL_lemma6 : PL_Formula := \n  PL_imp (PL_var 0) (PL_imp (PL_neg (PL_var 1)) (PL_neg (PL_imp (PL_var 0) (PL_var 1)))).\n\nDefinition PL_lemma6_proof : PL_list_proof nil PL_lemma6.\nProof.\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_imp (PL_imp (PL_var 0) (PL_var 1)) (PL_var 1))).\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_var 0)).\napply PL_assumption.\napply in_cons.\napply in_eq.\napply PL_assumption.\napply in_eq.\napply PL_list_proof_weaken with nil.\nintros X H1.\nexfalso.\nrevert H1.\napply in_nil.\napply (PL_subst_proof (PL_subst2 _ _) _ _ PL_lemma5_proof).\nDefined.\n\nDefinition PL_lemma7 : PL_Formula :=\n  PL_imp (PL_imp (PL_neg (PL_var 0)) (PL_var 0)) (PL_var 0).\n\nDefinition PL_lemma7_proof : PL_list_proof nil PL_lemma7.\nProof.\napply (PL_MP _ \n  (PL_imp (PL_neg (PL_var 0)) (PL_neg (PL_imp (PL_neg (PL_var 0)) (PL_var 0))))).\napply PL_deduction_thm_reverse_proof.\napply PL_list_proof_weaken with ((PL_neg (PL_var 0))::(PL_neg (PL_var 0))::nil).\nintros X H1.\ndestruct (in_inv H1) as [H2|H3].\nrewrite <- H2.\napply in_eq.\ndestruct (in_inv H3) as [H4|H5].\nrewrite <- H4.\napply in_eq.\nexfalso.\nrevert H5.\napply in_nil.\napply PL_deduction_thm_forward_proof.\napply (PL_MP _ (PL_imp (PL_imp (PL_neg (PL_var 0)) (PL_var 0)) (PL_var 0))).\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_neg (PL_var 0))).\napply PL_assumption.\napply in_cons.\napply in_eq.\napply PL_assumption.\napply in_eq.\napply PL_list_proof_weaken with nil.\nintros X H6.\nexfalso.\nrevert H6.\napply in_nil.\napply (PL_subst_proof (PL_subst2 _ _) _ _ PL_lemma5_proof).\napply PL_axiom3.\nDefined.\n\nDefinition PL_lemma8 : PL_Formula := \n  PL_imp (PL_imp (PL_neg (PL_var 1)) (PL_var 0)) \n    (PL_imp (PL_imp (PL_var 1) (PL_var 0)) (PL_var 0)).\n\nDefinition PL_lemma8_proof : PL_list_proof nil PL_lemma8.\nProof.\napply PL_deduction_thm_reverse_proof.\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_imp (PL_neg (PL_var 0)) (PL_neg (PL_var 1)))).\napply (PL_MP _ (PL_imp (PL_var 1) (PL_var 0))).\napply PL_assumption.\napply in_eq.\napply PL_list_proof_weaken with nil.\nintros X H1.\nexfalso.\nrevert H1.\napply in_nil.\napply (PL_subst_proof (PL_subst2 _ _) _ _ PL_lemma5_proof).\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_imp (PL_neg (PL_var 0)) (PL_var 0))).\napply PL_deduction_thm_reverse_proof.\napply (PL_MP _ (PL_neg (PL_var 1))).\napply (PL_MP _ (PL_neg (PL_var 0))).\napply PL_assumption.\napply in_eq.\napply PL_assumption.\napply in_cons.\napply in_eq.\napply PL_assumption.\napply in_cons.\napply in_cons.\napply in_cons.\napply in_eq.\napply PL_list_proof_weaken with nil.\nintros X H2.\nexfalso.\nrevert H2.\napply in_nil.\napply PL_lemma7_proof.\nDefined.\n\nEnd PL_proofs.\n\n\n\nSection PL_soundness.\n\nTheorem PL_soundness :\nforall (S : list PL_Formula) (A : PL_Formula),\n  PL_list_proves S A -> PL_list_models S A.\nProof.\nintros S A H1.\ndestruct H1 as [P1].\nintros f H2.\ninduction P1 as [A H3|A B|A B C|A B|A B PA H4 PAB H5].\nrewrite Forall_forall in H2.\napply H2.\nassumption.\napply PL_axiom1instancevalid.\napply Forall_nil.\napply PL_axiom2instancevalid.\napply Forall_nil.\napply PL_axiom3instancevalid.\napply Forall_nil.\nunfold PL_models in H4,H5|-*.\nsimpl in H5.\ndestruct (PL_interpretation f A); destruct (PL_interpretation f B);\ntry reflexivity; try (discriminate H4); discriminate H5.\nQed.\n\nEnd PL_soundness.\n\n\nSection PL_completeness.\n\nDefinition PL_one_case_proof (f : PL_Valuation) (b : PL_VarIndex) (S : list PL_Formula) \n  (varvalues : forall (n : PL_VarIndex), PL_varlt n b ->\n     (f n = true -> In (PL_var n) S) /\\ (f n = false -> In (PL_neg (PL_var n)) S))\n  (A : PL_Formula) (varbound : PL_varle (PL_formula_var_max A) b) :\n  if (PL_interpretation f A) then (PL_list_proof S A) else (PL_list_proof S (PL_neg A)).\nProof.\nrevert varbound.\ninduction A as [n1|A H1|A H2 B H3].\nintros varbound.\ndestruct (PL_interpretation f (PL_var n1)) eqn: H4.\napply PL_assumption.\napply varvalues.\napply Nat.lt_le_trans with (PL_formula_var_max (PL_var n1)).\napply le_n.\nassumption.\nassumption.\napply PL_assumption.\napply varvalues.\napply Nat.lt_le_trans with (PL_formula_var_max (PL_var n1)).\napply le_n.\nassumption.\nassumption.\nintros varbound.\nsimpl.\ndestruct (PL_interpretation f A) eqn: H5.\napply (PL_MP _ A).\napply H1.\nassumption.\napply PL_list_proof_weaken with nil.\nintros X H6.\nexfalso.\nrevert H6.\napply in_nil.\napply (PL_subst_proof (PL_subst1 A) _ _ PL_lemma4_proof).\napply H1.\nassumption.\nsimpl.\nintros H7.\nsimpl.\ndestruct (PL_interpretation f A) eqn: H8.\ndestruct (PL_interpretation f B) eqn: H9.\nsimpl.\napply (PL_MP _ B).\napply H3.\napply le_trans with (PL_varmax (PL_formula_var_max A) (PL_formula_var_max B)).\napply Nat.le_max_r.\nassumption.\napply PL_axiom1.\napply (PL_MP _ (PL_neg B)).\napply H3.\napply le_trans with (PL_varmax (PL_formula_var_max A) (PL_formula_var_max B)).\napply Nat.le_max_r.\nassumption.\napply (PL_MP _ A).\napply H2.\napply le_trans with (PL_varmax (PL_formula_var_max A) (PL_formula_var_max B)).\napply Nat.le_max_l.\nassumption.\napply PL_list_proof_weaken with nil.\nintros X H10.\nexfalso.\nrevert H10.\napply in_nil.\napply (PL_subst_proof (PL_subst2 A B) _ _ PL_lemma6_proof).\nsimpl.\napply (PL_MP _ (PL_neg A)).\napply H2.\napply le_trans with (PL_varmax (PL_formula_var_max A) (PL_formula_var_max B)).\napply Nat.le_max_l.\nassumption.\napply PL_list_proof_weaken with nil.\nintros X H11.\nexfalso.\nrevert H11.\napply in_nil.\napply (PL_subst_proof (PL_subst2 A B) _ _ PL_lemma2_proof).\nDefined.\n\nDefinition PL_merge_case_proof (S : list PL_Formula) (A B : PL_Formula)\n  (p1 : PL_list_proof (B :: S) A) (p2 : PL_list_proof ((PL_neg B) :: S) A) :\n  PL_list_proof S A.\nProof.\napply (PL_MP _ (PL_imp B A)).\napply PL_deduction_thm_reverse_proof.\nassumption.\napply (PL_MP _ (PL_imp (PL_neg B) A)).\napply PL_deduction_thm_reverse_proof.\nassumption.\napply PL_list_proof_weaken with nil.\nintros X H1.\nexfalso.\nrevert H1.\napply in_nil.\napply (PL_subst_proof (PL_subst2 _ _) _ _ PL_lemma8_proof).\nDefined.\n\nDefinition PL_valuation_k_to_top (k : PL_VarIndex) (f : PL_Valuation) : PL_Valuation :=\nfun (n : PL_VarIndex) =>\nmatch eq_nat_dec k n with\n| left _ => PL_top_interpretation\n| right _ => f n\nend.\n\nDefinition PL_valuation_k_to_bot (k : PL_VarIndex) (f : PL_Valuation) : PL_Valuation :=\nfun (n : PL_VarIndex) =>\nmatch eq_nat_dec k n with\n| left _ => PL_bot_interpretation\n| right _ => f n\nend.\n\nFixpoint PL_test_valuations2 (b : PL_VarIndex) : list PL_Valuation :=\nmatch b with\n| O => PL_valuation_bot :: nil\n| S b1 => concat\n  (map \n    (fun (f : PL_Valuation) => \n      (PL_valuation_k_to_top b1 f) :: (PL_valuation_k_to_bot b1 f) :: nil) \n     (PL_test_valuations2 b1))\nend.\n\nTheorem PL_bounded_valuations2_listed :\nforall (b : PL_VarIndex) (f : PL_Valuation),\n  exists (g : PL_Valuation), In g (PL_test_valuations2 b) /\\ PL_valuations_eq_before b f g.\nProof.\ninduction b as [|b1 H1].\nintros f.\nexists PL_valuation_bot.\nsplit.\napply in_eq.\nintros n H2.\nexfalso.\nrevert H2.\napply le_Sn_0.\nintros f.\ndestruct (H1 f) as [g1 [H3 H4]].\ndestruct (f b1) eqn: H5.\nexists (PL_valuation_k_to_top b1 g1).\nsplit.\napply in_concat.\nexists ((PL_valuation_k_to_top b1 g1) :: (PL_valuation_k_to_bot b1 g1) :: nil).\nsplit.\napply in_map_iff.\nexists g1.\nsplit.\nreflexivity.\nassumption.\napply in_eq.\nintros n H6.\nunfold PL_valuation_k_to_top.\ndestruct (eq_nat_dec b1 n) as [H7|H8].\nrewrite <- H7.\nassumption.\napply H4.\nunfold PL_varlt, lt in H6.\nrewrite Nat.le_lteq in H6.\ndestruct H6 as [H9|H10].\napply le_S_n.\nassumption.\nexfalso.\napply H8.\ninversion H10 as [H11].\nreflexivity.\nexists (PL_valuation_k_to_bot b1 g1).\nsplit.\napply in_concat.\nexists ((PL_valuation_k_to_top b1 g1) :: (PL_valuation_k_to_bot b1 g1) :: nil).\nsplit.\napply in_map_iff.\nexists g1.\nsplit.\nreflexivity.\nassumption.\napply in_cons.\napply in_eq.\nintros n H6.\nunfold PL_valuation_k_to_bot.\ndestruct (eq_nat_dec b1 n) as [H7|H8].\nrewrite <- H7.\nassumption.\napply H4.\nunfold PL_varlt, lt in H6.\nrewrite Nat.le_lteq in H6.\ndestruct H6 as [H9|H10].\napply le_S_n.\nassumption.\nexfalso.\napply H8.\ninversion H10 as [H11].\nreflexivity.\nQed.\n\nFixpoint PL_prepend_var_for_valuation \n  (k : PL_VarIndex) (f : PL_Valuation) (S : list PL_Formula) : list PL_Formula :=\nmatch k with\n| O => S\n| S k1 => (if (f k1) then (PL_var k1) else (PL_neg (PL_var k1))) :: \n  (PL_prepend_var_for_valuation k1 f S)\nend.\n\nFixpoint PL_completeness_lemma_prod_type \n  (k : PL_VarIndex) (S : list PL_Formula) (A : PL_Formula) (F : list PL_Valuation) : Type :=\nmatch F with\n| nil => True\n| f1 :: F1 => PL_list_proof (PL_prepend_var_for_valuation k f1 S) A * \n  PL_completeness_lemma_prod_type k S A F1\nend.\n\nDefinition PL_models_lemma (f : PL_Valuation) (S : list PL_Formula) (A : PL_Formula)\n  (H : PL_list_models S A) : \n  {B : PL_Formula & In B S /\\ PL_interpretation f B = false} + \n  (PL_interpretation f A = true).\nProof.\nassert (Hf := H f).\nclear H.\ninduction S as [|B1 S1 H1].\nright.\napply Hf.\napply Forall_nil.\ndestruct (PL_interpretation f B1) eqn: H2.\nassert (H3 : Forall (PL_models f) S1 -> PL_models f A).\nintros H3.\napply Hf.\napply Forall_cons.\nassumption.\nassumption.\ndestruct (H1 H3) as [[B2 [H4 H5]]|H6].\nleft.\nexists B2.\nsplit.\napply in_cons.\nassumption.\nassumption.\nright.\nassumption.\nleft.\nexists B1.\nsplit.\napply in_eq.\nassumption.\nDefined.\n\nTheorem PL_prepend_var_for_valuation_lemma2 :\nforall (f : PL_Valuation) (B : PL_Formula) (S : list PL_Formula),\n  In B S -> forall (k : PL_VarIndex), In B (PL_prepend_var_for_valuation k f S).\nProof.\nintros f B S H k.\ninduction k as [|k1 H1].\nassumption.\napply in_cons.\nassumption.\nQed.\n\nTheorem PL_prepend_var_for_valuation_lemma3 :\n  forall (f : PL_Valuation) (S : list PL_Formula) (b n : PL_VarIndex),\n    PL_varlt n b ->\n    (f n = true -> In (PL_var n) (PL_prepend_var_for_valuation b f S)) /\\ \n    (f n = false -> In (PL_neg (PL_var n)) (PL_prepend_var_for_valuation b f S)).\nProof.\nintros f S b.\ninduction b as [|b1 H1].\nintros n H1.\nexfalso.\nrevert H1.\napply le_Sn_0.\nintros n H2.\nunfold PL_varlt, lt in H2.\nrewrite Nat.le_lteq in H2.\ndestruct H2 as [H3|H4].\nassert (H5 : n < b1).\napply le_S_n.\nassumption.\ndestruct (H1 n H5) as [H6 H7].\ndestruct (f n) eqn: H8.\nsplit.\nintros H9.\napply in_cons.\napply H6.\nassumption.\nintros H10.\napply in_cons.\napply H7.\nassumption.\nsplit.\nintros H9.\napply in_cons.\napply H6.\nassumption.\nintros H10.\napply in_cons.\napply H7.\nassumption.\nrewrite <- H4.\nsimpl PL_prepend_var_for_valuation.\ndestruct (f n) eqn: H11.\nsplit.\nintros H12.\napply in_eq.\nintros H13.\ndiscriminate H13.\nsplit.\nintros H14.\ndiscriminate H14.\nintros H15.\napply in_eq.\nQed.\n\nDefinition PL_completeness_lemma1 (S : list PL_Formula) (A : PL_Formula)\n  (H : PL_list_models S A) (F : list PL_Valuation) :\n  PL_completeness_lemma_prod_type (max (PL_formula_list_var_max S) (PL_formula_var_max A)) \n    S A F.\nProof.\ninduction F as [|f1 F1 H1].\nexact I.\nsplit.\ndestruct (PL_models_lemma f1 _ _ H) as [[B1 [H2 H3]]|H4].\nassert (H5 := PL_one_case_proof f1 \n  (Init.Nat.max (PL_formula_list_var_max S) (PL_formula_var_max A))\n  (PL_prepend_var_for_valuation\n     (Init.Nat.max (PL_formula_list_var_max S) (PL_formula_var_max A)) f1 S)\n  (PL_prepend_var_for_valuation_lemma3 f1 S _)\n  B1\n  ).\nrewrite H3 in H5.\napply (PL_MP _ B1).\napply PL_assumption.\napply PL_prepend_var_for_valuation_lemma2.\nassumption.\napply (PL_MP _ (PL_neg B1)).\napply H5.\napply le_trans with (PL_formula_list_var_max S).\napply PL_formula_var_max_list_var_max.\nassumption.\napply Nat.le_max_l.\napply PL_list_proof_weaken with nil.\nintros X H6.\nexfalso.\nrevert H6.\napply in_nil.\napply (PL_subst_proof (PL_subst2 _ _) _ _ PL_lemma2_proof).\nassert (H7 := PL_one_case_proof f1 \n  (Init.Nat.max (PL_formula_list_var_max S) (PL_formula_var_max A))\n  (PL_prepend_var_for_valuation\n     (Init.Nat.max (PL_formula_list_var_max S) (PL_formula_var_max A)) f1 S)\n  (PL_prepend_var_for_valuation_lemma3 f1 S _)\n  A\n  ).\nrewrite H4 in H7.\napply H7.\napply Nat.le_max_r.\nassumption.\nDefined.\n\nTheorem PL_prepend_var_for_valuation_lemma4 :\nforall (v : PL_Value) (f : PL_Valuation) (S : list PL_Formula) (k m : PL_VarIndex),\n  le k m ->\n  PL_prepend_var_for_valuation k\n    (fun (n : PL_VarIndex) => if Nat.eq_dec m n then v else f n) S =\n  PL_prepend_var_for_valuation k f S.\nProof.\nintros v f S k.\ninduction k as [|k1 H1].\nintros m H2.\nreflexivity.\nintros m H3.\nsimpl.\ndestruct (Nat.eq_dec m k1) as [H4|H5].\nexfalso.\nrevert H3.\nrewrite H4.\napply le_Sn_n.\nrewrite H1.\nreflexivity.\napply le_trans with (Datatypes.S k1).\napply le_n_Sn.\nassumption.\nDefined.\n\nDefinition PL_completeness_lemma2 (k : PL_VarIndex) (S : list PL_Formula) (A : PL_Formula) \n  (F : list PL_Valuation)\n  (p : PL_completeness_lemma_prod_type (Datatypes.S k) S A\n    (concat (map \n      (fun (f : PL_Valuation) => \n        (PL_valuation_k_to_top k f) :: (PL_valuation_k_to_bot k f) :: nil) \n      F))) :\n  PL_completeness_lemma_prod_type k S A F.\nProof.\ninduction F as [|f1 F1 p1].\nexact I.\nsplit.\nassert (p2 := fst p).\nassert (p3 := fst (snd p)).\nsimpl in p2, p3.\nunfold PL_valuation_k_to_top in p2.\nunfold PL_valuation_k_to_bot in p3.\ndestruct (Nat.eq_dec k k) as [H1|H2].\nsimpl in p2, p3.\nrewrite PL_prepend_var_for_valuation_lemma4 in p2.\nrewrite PL_prepend_var_for_valuation_lemma4 in p3.\napply (PL_merge_case_proof _ _ _ p2 p3).\napply le_n.\napply le_n.\nexfalso.\napply H2.\nreflexivity.\napply p1.\napply (snd (snd p)).\nDefined.\n\nDefinition PL_completeness_lemma3 (S : list PL_Formula) (A : PL_Formula)\n  (p : PL_completeness_lemma_prod_type 0 S A (PL_test_valuations2 0)) :\n  PL_list_proof S A.\nProof.\ndestruct p.\nassumption.\nDefined.\n\nDefinition PL_completeness_proof_induction (S : list PL_Formula) (A : PL_Formula)\n  (H : PL_list_models S A) (k : PL_VarIndex) :\n  PL_completeness_lemma_prod_type k S A (PL_test_valuations2 k) -> PL_list_proof S A.\nProof.\ninduction k as [|k1 H1].\napply PL_completeness_lemma3.\nintros p1.\napply H1.\napply PL_completeness_lemma2.\nassumption.\nDefined. \n\nDefinition PL_completeness_proof (S : list PL_Formula) (A : PL_Formula) \n  (H : PL_list_models S A) : PL_list_proof S A.\nProof.\napply PL_completeness_proof_induction with \n  (max (PL_formula_list_var_max S) (PL_formula_var_max A)).\nassumption.\napply PL_completeness_lemma1.\nassumption.\nDefined.\n\nTheorem PL_completeness :\nforall (S : list PL_Formula) (A : PL_Formula),\n  PL_list_models S A -> PL_list_proves S A.\nProof.\nintros S A H.\nexists.\napply PL_completeness_proof.\nassumption.\nQed.\n\nEnd PL_completeness.\n\n\n\n\nSection PL_decidable_proofs.\n\nDefinition PL_list_proves_decidable (S : list PL_Formula) (A : PL_Formula) :\n  {PL_list_proves S A} + {~ PL_list_proves S A}.\nProof.\ndestruct (PL_list_models_decidable S A) as [H1|H2].\nleft.\napply PL_completeness.\nassumption.\nright.\nintros H3.\napply H2.\napply PL_soundness.\nassumption.\nDefined.\n\nEnd PL_decidable_proofs.\n", "meta": {"author": "siraben", "repo": "proplogic", "sha": "12c326d18605e8275a02642254626bb943f84dd4", "save_path": "github-repos/coq/siraben-proplogic", "path": "github-repos/coq/siraben-proplogic/proplogic-12c326d18605e8275a02642254626bb943f84dd4/proplogicST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7095766815194259}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) : natural :=\n  plus x y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj263_coqofml_Rwzguo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.7095766796133398}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) : natural := plus Zero (mult y z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj186_coqofml_1NikpL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7879312031126511, "lm_q1q2_score": 0.7095555220215239}}
{"text": "Require Import Arith.\nRequire Export Coq.Lists.List.\nRequire Import Coq.Logic.JMeq.\nRequire Import Coq.Classes.Morphisms.\nRequire Export Coq.Sorting.Permutation.\n\nImport ListNotations. Open Scope list_scope.\n\nSection Forall.\n\n  Variable A : Type.\n  Variable P : A -> Prop.\n\n  Theorem map_isFunctorial : forall {A B C : Type} (l : list A) (f1 : B -> C) (f2 : A -> B), map f1 (map f2 l) = map (fun x => f1 (f2 x)) l.\n  Proof.\n    induction l; simpl; intros; auto.\n    f_equal.\n    auto.\n  Qed.\n    \n  Theorem map_preservesIn : forall {A B : Type} (l : list A) (f : A -> B) (tb : B), In tb (map f l) -> exists ta, (In ta l) /\\ (tb = f ta).\n  Proof.\n    induction l; simpl; intros; auto.\n    - inversion H.\n    - destruct H; subst; eauto.\n      destruct (IHl f tb H).\n      destruct H0.\n      subst.\n      exists x; eauto.      \n  Qed.\n\n  Theorem Forall_append : forall (l1 l2 : list A),\n    Forall P (l1 ++ l2) <-> Forall P l1 /\\ Forall P l2.\n  Proof.\n    intros l1 l2; split; intro H.\n    - split; apply Forall_forall; intros x H0;\n        rewrite Forall_forall in H; apply H; apply in_or_app; [left | right]; auto.\n    - destruct H as [H1 H2]; rewrite Forall_forall in H1; rewrite Forall_forall in H2;\n        rewrite Forall_forall; intros x H0; rewrite in_app_iff in H0; destruct H0;\n          [apply H1 | apply H2]; auto.\n  Qed.\n\n  Definition Forall_inv_car := Forall_inv.\n  Theorem Forall_inv_cdr : forall (a : A) (l : list A), Forall P (a :: l) -> Forall P l.\n  Proof.\n    intros a l H; inversion H; auto.\n  Qed.\n\nEnd Forall.\n\nFixpoint list_insert {A : Type} (a : A) (n : nat) (l : list A) {struct l} : list A :=\n    match n with\n    | 0 => a :: l\n    | S n' =>\n      match l with\n      | [] => []\n      | x :: l' => x :: (list_insert a n' l')\n      end\n    end.\n\nTheorem list_insert_nth : forall {A : Type} (a : A) (n : nat) (l : list A),\n    nth n (list_insert a n l) a = a.\nProof.\n  intros A a n l; generalize n; clear n.\n  induction l; intro n; destruct n; simpl; auto.\nQed.\n\nTheorem list_insert_nth_len : forall {A : Type} (x a : A) (n : nat) (l : list A),\n    n <= length l -> nth n (list_insert a n l) x = a.\nProof.\n  intros A x a n l H; generalize dependent n.\n  induction l; intros n H; simpl in H; inversion H; simpl.\n  - reflexivity.\n  - apply IHl; reflexivity. \n  - destruct n; simpl; [reflexivity | apply IHl; apply Le.le_Sn_le; auto].\nQed.\n\nTheorem mth_list_insert_lt : forall {A : Type} (x a : A) (n m : nat) (l : list A),\n    m < n -> nth m (list_insert a n l) x = nth m l x.\nProof.\n  intros A x a n m l H.\n  generalize dependent m; generalize dependent n; induction l; intros n m H; simpl in H.\n  - destruct m; destruct n; simpl; auto; inversion H.\n  - destruct n; [inversion H | destruct m; auto; simpl; apply Lt.lt_S_n in H; apply IHl; auto].\nQed.\n\nTheorem mth_list_insert_gt : forall {A : Type} (x a : A) (l : list A) (n m : nat),\n    n < m -> nth m (list_insert a n l) x = nth (m - 1) l x.\nProof.\n  intros A x a l.\n  induction l; intros n m H; simpl in H.\n  - destruct m; destruct n; simpl; auto; inversion H; simpl; auto;\n      rewrite PeanoNat.Nat.sub_0_r; [reflexivity | destruct m; simpl; reflexivity].\n  - destruct n; simpl. repeat (destruct m; inversion H; simpl; auto).\n    destruct m; inversion H; simpl.\n    -- rewrite H1;\n         assert (n = m - 1) by (rewrite <- H1; simpl; rewrite PeanoNat.Nat.sub_0_r; reflexivity);\n         rewrite H0 at 2; apply IHl; apply Lt.lt_S_n; auto.\n    -- rewrite PeanoNat.Nat.sub_0_r.\n       destruct m; simpl. inversion H1.\n       assert (m = S m - 1) by (simpl; symmetry; apply PeanoNat.Nat.sub_0_r).\n       rewrite H2 at 2. apply IHl. apply Lt.lt_S_n; auto.\nQed.\n\nProgram Fixpoint ExceptNth {A : Type} (n : nat) (l : list A) : list A :=\n  match l with\n  | [] => []\n  | (x :: xs) => match n with\n                | 0 => xs\n                | S n' => x :: ExceptNth n' xs\n                end\n  end.\n\nTheorem rev_app_to_cons : forall {A : Type} {l : list A} {a : A},\n    exists b l', rev l ++ [a] = b :: l'.\nProof.\n  intros A l; induction l as [| c l]; intro a.\n  - simpl; exists a; exists []; auto.\n  - simpl; destruct (IHl c) as [x Hx]; destruct Hx as [l'' Hxl''];\n      exists x; exists (l'' ++ [a]); rewrite Hxl''; simpl; auto.\nQed.\n\nTheorem ReverseNil : forall {A : Type} {l : list A}, rev l = [] -> l = [].\nProof.\n  intros A l Hl; destruct l;\n  [ auto\n  | simpl in Hl; exfalso; apply in_nil with (a := a);\n    rewrite <- Hl; apply in_or_app; right; simpl; left; auto\n  ].\nQed.\n\nLemma ReverseNilIff : forall {A : Type} {l : list A}, rev l = [] <-> l = [].\nProof.\n  intros A l; split; intro H; [apply ReverseNil; auto | rewrite H; auto].\nQed.\n\nLemma ReverseNilIff' : forall {A : Type} {l : list A}, rev l <> [] <-> l <> [].\nProof.\n  intros A l; split; intros H H'; apply H; apply ReverseNilIff; auto.\nQed.\n\nTheorem RevApp : forall {A : Type} (l l' : list A),\n    rev (l ++ l') = rev l' ++ rev l.\nProof.\n  intros A l; induction l;\n    [ intros l'; simpl; rewrite <- app_nil_end; reflexivity\n    | intros l'; simpl; rewrite IHl; rewrite app_assoc; reflexivity\n    ].\nQed.\n\nLemma RevConsIsApp : forall {A : Type} (l l' : list A) {a : A},\n    rev l = a :: l' -> l = rev l' ++ [a].\nProof.\n  intros A l; induction l.\n  - intros l' a H; simpl in H; inversion H.\n  - simpl; intros l' b H.\n    destruct (rev l) as [| c l''] eqn:e.\n    simpl in H; inversion H; simpl; rewrite @ReverseNil with (l := l); auto.\n    inversion H; simpl in H; rewrite <- H2 in H; simpl; rewrite RevApp; simpl;\n      assert (l = rev l'' ++ [b]) by (apply IHl; inversion H; auto).\n    rewrite H0. auto.\nQed.\n\nLemma ForallRev : forall {A : Type} {P : A -> Prop} {l : list A},\n    Forall P l -> Forall P (rev l).\nProof.\n  intros A P l H.\n  induction l; [simpl; apply Forall_nil|].\n  pose proof (Forall_inv_car A P _ _ H).\n  pose proof (Forall_inv_cdr A P _ _ H).\n  simpl; apply Forall_append; split; auto.\nQed.  \n\n\nLemma RemoveLastApp1 : forall {A : Type} (l : list A) (a : A),\n    removelast (l ++ [a]) = l.\nProof.\n  intros A l; induction l as [| b l']; intro a; simpl.\n  auto.\n  destruct (l' ++ [a]) eqn:e.\n  - exfalso; apply in_nil with (a := a); rewrite <- e; apply in_or_app; right; simpl; left; auto.\n  - rewrite <- e; rewrite IHl'; reflexivity.\nQed.\n\nLemma InRemoveLast : forall {A : Type} (l : list A) (a : A),\n    In a (removelast l) -> In a l.\nProof.\n  intros A l a H.\n  induction l; [simpl in H; destruct H | idtac]. \n  simpl in H. destruct l. destruct H. \n  simpl in H; destruct H. simpl; left; auto. \n  simpl; right; fold In.  simpl in IHl. apply IHl; auto.\nQed.\n\nLemma App1NonEmpty : forall {A : Type} (l : list A) (a : A),\n    l ++ [a] <> [].\nProof.\n  intros A l a; intro H; apply in_nil with (a := a);\n    rewrite <- H; apply in_or_app; right; simpl; auto.\nQed.\n\nDefinition InBool : forall {A : Type} (ADec : forall a b : A, {a = b} + {a <> b}), A -> list A -> bool :=\n  fun A ADec a l =>\n      match (@in_dec A ADec a l) with\n      | left _ => true\n      | right _ => false\n      end.\n\nTheorem InBoolSpec : forall {A : Type} {ADec : forall a b : A, {a = b} + {a <> b}}\n                       {a : A} {l : list A},\n    InBool ADec a l = true <-> In a l.\nProof.\n  intros A ADec a l.\n  unfold InBool; (destruct in_dec); split; intro H; auto.\n  inversion H.\nQed.\n\nTheorem InBoolSpec' : forall {A : Type} {ADec : forall a b : A, {a = b} + {a <> b}}\n                        {a : A} {l : list A},\n    InBool ADec a l = false <-> ~ In a l.\nProof.\n  intros A ADec a l; split; intro H.\n  intro Hcontra. rewrite <- @InBoolSpec with (ADec := ADec) in Hcontra.\n  pose proof (eq_trans (eq_sym H) Hcontra); inversion H0.\n  destruct (InBool ADec a l) eqn:e.\n  exfalso; rewrite InBoolSpec in e; apply H; auto.\n  auto.\nQed.\n\nTheorem InBoolSubset : forall {A : Type} {ADec : forall a b : A, {a = b} + {a <> b}}\n                         {a : A} {l1 l2 : list A},\n    InBool ADec a l1 = true -> (forall b : A, In b l1 -> In b l2) -> InBool ADec a l2 = true.\nProof.\n  intros A ADec a l1 l2 H H0.\n  rewrite InBoolSpec. rewrite InBoolSpec in H.\n  apply H0; auto.\nQed.\n\nDefinition InBoolCons : forall {A : Type} {ADec : forall a b : A, {a = b} + {a <> b}}\n                       {a b : A} {l : list A},\n    InBool ADec a (b :: l) = true -> {a = b} + {InBool ADec a l = true}.\nProof.\n  intros A ADec a b l H.\n  unfold InBool in H.\n  destruct (ADec a b).\n  left; auto.\n  right.\n  destruct (in_dec ADec a (b :: l)); [| inversion H].\n  destruct i as [e | i0]; [exfalso; apply n; symmetry; apply e |].\n  rewrite InBoolSpec; auto.\nDefined.\n\nLemma InCons: forall {A:Type} {ADec : forall a b : A, {a = b} + {a <> b}} (l:A) m a , In a (l :: m) -> {a = l} + {In a m}.\nProof.\n  intros A ADec l m a H.\n  eapply InBoolSpec in H.\n  eapply InBoolCons in H.\n  destruct H; auto.\n  right.\n  eapply InBoolSpec; eauto.\n  Unshelve.\n  apply ADec.\nQed.\n\nProgram Definition EqNil {A : Type} (l : list A) : {l = []} + {l <> []} :=\n  match l with\n  | [] => left _\n  | _ => right _\n  end.\n\nLtac EqNilDestruct l :=\n  let e := fresh \"e\" in\n  let n := fresh \"n\" in\n  match l with\n  | [] => destruct (EqNil l) as [e | n];\n         [clear e | exfalso; apply n; auto]\n  | _ =>\n    match goal with\n    | [ H : l = [] |- _  ] =>\n      destruct (EqNil l) as [e | n];\n      [| exfalso; apply n; exact H]\n    | [ H : [] = l |- _ ] =>\n      destruct (EqNil l) as [e | n];\n      [| exfalso; apply n; exact (eq_sym H)]\n    | [ H : l <> [] |- _ ] =>\n      destruct (EqNil l) as [e | n];\n      [ exfalso; apply H; exact e |]\n    | [ H : [] <> l |- _ ] =>\n      destruct (EqNil l) as [e | n];\n      [exfalso; apply H; exact (eq_sym e) |]\n    | [ H : l = _ :: _ |- _ ] =>\n      destruct (EqNil l) as [e | n];\n      [rewrite e in H; inversion H |]\n    | [ H : _ :: _ = l |- _ ] =>\n      destruct (EqNil l) as [e | n];\n      [rewrite e in H; inversion H |]\n    | _ => destruct (EqNil l) as [e | n]\n    end\n  end.\n\nInductive Path {A : Set} : A -> list A -> Set :=\n| Here : forall (a : A) (l : list A), Path a (a :: l)\n| There : forall {a : A} (b : A) {l : list A}, Path a l -> Path a (b :: l).\n\nInductive MaybePath {A : Set} : A -> list A -> Set :=\n| IsPath : forall {a : A} {l : list A}, Path a l -> MaybePath a l\n| NoPath : forall {a : A} {l : list A}, (Path a l -> False) -> MaybePath a l.\n\nProgram Fixpoint FindPath {A : Set} {AEq : forall a b : A, {a = b} + {a <> b}} (a : A) (l : list A) \n  : MaybePath a l :=\n  match l with\n  | [] => NoPath (fun p => _)\n  | b :: l' => match (AEq a b) with\n              | left e => eq_rec_r (fun a0 : A => MaybePath a0 (b :: l')) (IsPath (Here b l')) e\n              | right n => let m := @FindPath A AEq a l' in\n                          match m in (MaybePath y l0) return (y <> b -> MaybePath y (b :: l0)) with\n                          | @IsPath _ a0 l0 p => _\n                          | @NoPath _ a0 l0 f => _\n                          end n\n              end\n  end.\nNext Obligation.\n  inversion p.\nDefined.\nNext Obligation.\n  apply IsPath; apply There; auto.\nDefined.\nNext Obligation.\n  apply NoPath. intro p. inversion p.\n  - apply H; auto.\n  - apply f; auto.\nDefined.\n\nTheorem InPathDoubleNeg : forall {A : Set} {AEq : forall a b : A, {a = b} + {a <> b}} (a : A) (l : list A),\n    In a l -> (Path a l -> False) -> False.\nProof.\n  intros A AEq a l H H0.\n  induction l.\n  inversion H.\n  destruct H.\n  rewrite H in H0; apply (H0 (Here a l)).\n  apply IHl; auto. \n  intro p. apply H0. apply There; auto.\nQed.\n\nProgram Definition InToPath {A :Set} (AEq : forall a b : A, {a = b} + {a <> b}) {a : A} {l : list A} : \n  In a l -> Path a l :=\n  fun H => match @FindPath A AEq a l with\n        | IsPath pi => pi\n        | NoPath npi => _\n        end.\nNext Obligation.\n  apply JMeq_eq in Heq_l; clear Heq_anonymous; rewrite Heq_l in npi.\n  exfalso; apply @InPathDoubleNeg with (a := a) (l := l); auto.\nDefined.\n\nFixpoint PathToIndex {A : Set} {a : A} {l : list A} (pi : Path a l) {struct pi} : nat :=\n  match pi with\n  | Here _ _ => 0\n  | There _ pi' => 1 + PathToIndex pi'\n  end.\n\nLemma PathToIndex0_Here : forall {A : Set} {a b : A} {l : list A} (pth : Path a (b :: l)),\n    PathToIndex pth = 0 -> a = b /\\ JMeq pth (Here a l).\nProof.\n  intros A a b l pth H.\n  remember (b :: l). destruct pth eqn:e.\n  inversion Heql0. split; auto.\n  simpl in H. inversion H.\nQed.\n\nLemma PathToIndexS_There : forall {A : Set} {a : A} {l : list A} (pth : Path a l) (n : nat),\n    PathToIndex pth = S n -> exists b l' (pth' : Path a l'), l = b :: l' /\\ JMeq pth (@There A a b l' pth').\nProof.\n  intros A a l pth n H.\n  destruct pth eqn:e. inversion H.\n  exists b; exists l; exists p; auto.\nQed.\n\n\nProgram Fixpoint nth_known_correct {A : Type} (n : nat) (l : list A) (n_corr : n < length l) : A :=\n  match n with\n  | O => match l with\n        | [] => _\n        | a :: _ => a\n        end\n  | S m => match l with\n          | [] => _\n          | _ :: l' => @nth_known_correct A m l' _\n          end\n  end.\nNext Obligation.\n  simpl in n_corr; exfalso; eapply PeanoNat.Nat.nlt_0_r; eauto.\nDefined.\nNext Obligation.\n  simpl in n_corr; exfalso; eapply PeanoNat.Nat.nlt_0_r; eauto.\nDefined.\nNext Obligation.\n  simpl in n_corr; apply Lt.lt_S_n; auto.\nDefined.\n\nLemma nth_known_correct_pf_irr : forall {A : Type} (n : nat) (l : list A) (pf pf' : n < length l),\n    @nth_known_correct A n l pf = @nth_known_correct A n l pf'.\nProof.\n  intros A n l pf pf'.\n  generalize dependent n.\n  induction l; intros n pf pf'; [simpl in pf; exfalso; eapply PeanoNat.Nat.nlt_0_r; eauto|].\n  destruct n; [simpl; reflexivity |].\n  simpl. apply IHl.\nQed.\n\nLemma PathToIndexGivesValidIndex : forall {A : Set} {a : A} {l : list A} (pi : Path a l),\n    PathToIndex pi < length l.\nProof.\n  intros A a l pi; induction pi; [simpl; apply PeanoNat.Nat.lt_0_succ | simpl; apply Lt.lt_n_S; auto].\nQed.\n\nLemma ItemAtPathToIndex : forall {A : Set} {a : A} {l : list A} {pi : Path a l},\n    @nth_known_correct A (PathToIndex pi) l (PathToIndexGivesValidIndex pi) = a.\nProof.\n  intros A a l pi.\n  induction pi; simpl; [auto | erewrite nth_known_correct_pf_irr; exact IHpi].\nQed.\n\nLemma ItemAtPathToIndex' :forall {A : Set} {a : A} {l : list A} {pi : Path a l}\n                            (H : PathToIndex pi < length l),\n    nth_known_correct (PathToIndex pi) l H = a.\nProof.\n  intros A a l pi.\n  induction pi; intro H; simpl; simpl in H; [auto| apply IHpi].\nQed.\n\nProgram Fixpoint IndexToPath {A : Set} (n : nat) (l : list A) (pf : n < length l) :\n  Path (@nth_known_correct A n l pf) l :=\n  match n with\n  | 0 => match l with\n        | [] => _\n        | a :: l' => Here a l'\n        end\n  | S m => match l with\n          | [] => _\n          | a :: l' => @There _ _ a l' (@IndexToPath _ m l' _)\n          end\n  end.\nNext Obligation.\n  simpl in pf; exfalso; eapply PeanoNat.Nat.nlt_0_r; eauto.\nDefined.\nNext Obligation.\n  simpl in pf; exfalso; eapply PeanoNat.Nat.nlt_0_r; eauto.\nDefined.\nNext Obligation.\n  simpl in pf; apply Lt.lt_S_n; auto.\nDefined.\n\nLemma IndexToPathToIndexId : forall {A : Set} (n : nat) (l : list A) (pf : n < length l),\n    PathToIndex (@IndexToPath A n l pf) = n.\nProof.\n  intros A n l pf.\n  generalize dependent n; induction l; intros n pf;\n    [simpl in pf; exfalso; eapply PeanoNat.Nat.nlt_0_r; eauto|].\n  simpl in pf.  \n  destruct n; simpl; [reflexivity |].\n  apply f_equal. apply IHl.\nQed.\n\nLemma PathToIn : forall {A : Set} {a : A} {l : list A}, Path a l -> In a l.\nProof.\n  intros A a l H; induction H; [left | right]; auto.\nQed.\n\nLtac ClearLTZero :=\n  match goal with\n  | [ H : _ < length [] |- _ ] =>\n    exfalso; eapply Nat.nlt_0_r; eauto\n  | [ H : _ < 0 |- _ ] =>\n    exfalso; eapply Nat.nlt_0_r; eauto\n  | _ => idtac\n  end.\n\nDefinition _add_one_corr_cons : forall {A : Type} i a (l : list A), i < length l -> (i + 1) < length (a :: l).\nProof.\n  intros A i a l Hi.\n  rewrite Nat.add_comm; simpl.\n  apply Lt.lt_n_S; auto.\nQed.\n  \n\nLemma nth_known_correct_cons : forall {A : Type} i a (l : list A) (Hi : i < length l),\n    nth_known_correct i l Hi = nth_known_correct (i + 1) (a :: l) (_add_one_corr_cons i a l Hi).\nProof.\n  intros A i a l Hi;\n    generalize dependent i; generalize dependent a; induction l; intros b i Hi; ClearLTZero; simpl; simpl in Hi; auto.\n  destruct i; simpl; auto.\n  rewrite IHl with (a := a).\n  apply nth_known_correct_pf_irr.\nQed.  \n\nLemma nth_known_correct_cons' : forall {A : Type} i a (l : list A) (Hi : i < length l) (Hj : i + 1 < length (a :: l)),\n    nth_known_correct i l Hi = nth_known_correct (i + 1) (a :: l) Hj.\nProof.\n  intros A i a l Hi Hj;\n    generalize dependent i; generalize dependent a; induction l; intros b i Hi Hj; ClearLTZero; simpl;\n      simpl in Hi; simpl in Hj; auto.\n  destruct i; simpl; auto.\nQed.\n\nLemma nth_known_correct_error : forall {A : Type} i (l : list A) (Hi : i < length l),\n    nth_error l i = Some (nth_known_correct i l Hi).\nProof.\n  intros A i l Hi.\n  generalize dependent i; induction l; intros i Hi; ClearLTZero; simpl.\n  destruct i; [simpl; auto|].\n  simpl. apply IHl.\nQed.\n\nLemma nth_error_some_if_known_correct : forall {A : Type} (l : list A) i (Hi : i < length l),\n    exists a, nth_error l i = Some a.\nProof.\n  intros A l; induction l; intros i Hi; ClearLTZero; simpl; simpl in Hi.\n  destruct i; simpl. exists a; auto.\n  assert (i < length l) by (apply Lt.lt_S_n; auto). specialize (IHl i H).\n  auto.\nQed.\n\nLemma nth_known_correct_eq : forall {A : Type} i j (l : list A) (Hi : i < length l) (Hj : j < length l),\n    i = j -> nth_known_correct i l Hi = nth_known_correct j l Hj.\nProof.\n  intros A i j l Hi Hj H.\n  assert (nth_error l i = nth_error l j) by (rewrite H; auto).\n  pose (nth_error_some_if_known_correct l i Hi) as e;\n    destruct e as [a Ha];\n    pose proof Ha as Ha';\n    rewrite nth_known_correct_error with (Hi0 := Hi) in Ha'; inversion Ha'.\n  pose (nth_error_some_if_known_correct l j Hj);\n    destruct e as [b Hb];\n    pose proof Hb as Hb';\n    rewrite nth_known_correct_error with (Hi0 := Hj) in Hb'; inversion Hb'.\n  assert (Some a = Some b)\n    by (transitivity (nth_error l i); [symmetry; auto | transitivity (nth_error l j); auto]).\n  inversion H1. \n  rewrite H2. rewrite H3. auto.\nQed.\n\nProgram Fixpoint MoveToFront {A : Type} (AEq : forall a b : A, {a = b} + {a <> b})\n        (l : list A) (a : A) : list A :=\n  match l with\n  | [] => []\n  | x :: l' => if AEq a x\n              then x :: l'\n              else match MoveToFront AEq l' a with\n                   | [] => x :: []\n                   | y :: l'' =>\n                     if AEq y a\n                     then y :: x :: l''\n                     else l\n                   end\n  end.\n\nDefinition InFront {A : Type} (l : list A) (a : A) : Prop :=\n  match l with\n  | [] => False\n  | x :: _ => a = x\n  end.\n\nLemma MoveToFrontInFront : forall {A : Type} AEq (l : list A) (a : A),\n    In a l -> InFront (MoveToFront AEq l a) a.\nProof.\n  intros A AEq l a aINl.\n  induction l; [inversion aINl|].\n  simpl; simpl in aINl. destruct aINl.\n  rewrite H; simpl; destruct (AEq a a) as [e | n]; [clear e; simpl | exfalso; apply n]; auto.\n  destruct (AEq a a0) as [e | n]; simpl; auto.\n  destruct (MoveToFront AEq l a) eqn: e; [destruct (IHl H) | ].\n  simpl in IHl; simpl.\n  destruct (AEq a1 a). simpl; auto. exfalso; apply n0; symmetry; apply IHl; auto.\nQed.\n\nLemma MoveToFrontEq : forall {A : Type} AEq (l : list A) (a : A),\n    ~In a l -> l = MoveToFront AEq l a.\nProof.\n  intros A AEq l; induction l as [| b l']; intros a n; simpl; auto.\n  destruct (AEq a b); auto.\n  destruct (MoveToFront AEq l' a) eqn:e.\n  rewrite (IHl' a); [rewrite e; auto | intro Hcontra; apply n; right; auto].\n  destruct (AEq a0 a); auto.\n  exfalso; apply n; right;\n    rewrite IHl' with (a := a); [ rewrite e; left; auto | intro Hcontra; apply n; right; auto].\nQed.  \n\n\nLemma MoveToFrontPermuation : forall {A : Type} AEq (l : list A) (a : A),\n    Permutation l (MoveToFront AEq l a).\nProof.\n  intros A AEq l a.\n  induction l; [simpl; auto|].\n  simpl. destruct (AEq a a0); [auto|].\n  destruct (MoveToFront AEq l a) eqn:e.\n  inversion IHl; auto.\n  destruct (AEq a1 a); auto.\n  transitivity (a0 :: a1 :: l0); constructor; auto; fail.\nQed.\n\nLemma MoveToFrontLength : forall {A : Type} AEq (l : list A) (a : A),\n    length l = length (MoveToFront AEq l a).\nProof.\n  intros A AEq l a; apply Permutation_length; exact (MoveToFrontPermuation AEq l a).\nQed.\n\n\nLemma OnlyNNumbersLessThanN : forall (n : nat) (l : list nat),\n    (forall m, In m l -> m < n) -> length l > n -> ~ NoDup l.\nProof.\n  intros n. induction n; intros l all_below length_above nodup.\n  destruct l; simpl in length_above. eapply Gt.gt_irrefl; eauto.\n  eapply Nat.nlt_0_r; apply all_below; left; eauto.\n  remember (MoveToFront Nat.eq_dec l n).\n  pose proof (MoveToFrontPermuation Nat.eq_dec l n).\n  rewrite <- Heql0 in H.\n  pose proof (Permutation_NoDup H nodup) as nodupl0.\n  destruct (ListDec.In_dec Nat.eq_dec n l).\n  - assert (InFront l0 n) as nInFrontOfl by (rewrite Heql0; apply MoveToFrontInFront; auto).\n    destruct l0; simpl in nInFrontOfl; [inversion nInFrontOfl |].\n    apply (IHn l0).\n    -- intros m mINl0.\n       assert (In m l) as mINl\n         by (apply Permutation_in with (l := (n0 :: l0)); [symmetry; auto| right; auto]).\n       pose proof (Lt.lt_n_Sm_le m n (all_below m mINl)) as mLEn.\n       destruct (Lt.le_lt_or_eq m n mLEn); auto.\n       exfalso; inversion nodupl0; apply H3; rewrite <- nInFrontOfl; rewrite <- H0; auto.\n    -- assert (length l = length (n0 :: l0)) by (apply Permutation_length; auto);\n         rewrite H0 in length_above; simpl in length_above; apply Lt.lt_S_n; auto.\n    --inversion nodupl0; auto.\n  - apply (IHn l).\n    -- intros m H0.\n       pose proof (Lt.lt_n_Sm_le m n (all_below m H0)).\n       destruct (Lt.le_lt_or_eq m n H1); auto.\n       exfalso; apply n0; rewrite <- H2; auto.\n    -- apply Gt.gt_trans with (m := S n); auto.\n    -- auto.\nQed.\n\nTheorem NoDupFilter : forall {A : Type} (l : list A) (f : A -> bool),\n    NoDup l -> NoDup (filter f l).\nProof.\n  intros A l f H.\n  induction l; simpl; auto.\n  destruct (f a).\n  constructor. inversion H.\n  intro Hcontra; apply H2.\n  pose proof (proj1 (filter_In f a l)).\n  specialize (H4 Hcontra).\n  destruct H4; auto.\n  all: apply IHl; inversion H; auto.\nQed.  \n\nFixpoint FilterLTs (l : list nat) (n : nat) : list nat :=\n  match l with\n  | [] => []\n  | m :: l' =>\n    let fltd := FilterLTs l' n in\n    if andb (m <? n) (negb (InBool Nat.eq_dec m fltd))\n              then m :: fltd\n              else fltd\n  end.\n\nTheorem FilterLTs_lt : forall (l : list nat) (n m : nat),\n    In m (FilterLTs l n) -> m < n.\nProof.\n  intros l n m H.\n  induction l.\n  inversion H.\n  simpl in H.\n  destruct ((a <? n) && negb (InBool Nat.eq_dec a (FilterLTs l n)))%bool eqn:e.\n  apply andb_prop in e; destruct e as [e1 e2].\n  assert (a < n) by (rewrite Nat.ltb_lt in e1; auto).\n  assert (~ In a (FilterLTs l n)) by (rewrite Bool.negb_true_iff in e2; rewrite InBoolSpec' in e2; auto).\n  destruct H; [rewrite <- H; auto | apply IHl; auto].\n  apply IHl; auto.\nQed.\n\nTheorem FilterLTs_length1 : forall (l : list nat) (n : nat),\n    length (FilterLTs l n) <= length l.\nProof.\n  intros l n.\n  induction l; simpl; auto.\n  destruct (((a <? n) && negb (InBool Nat.eq_dec a (FilterLTs l n)))%bool).\n  simpl. apply le_n_S; auto.\n  transitivity (length l); auto.\nQed.  \n\nTheorem FilterLTs_NoDup : forall (l : list nat) (n : nat),\n    NoDup (FilterLTs l n).\nProof.\n  intros l n.\n  induction l; simpl; try (constructor; auto; fail); auto.\n  destruct ((a <? n) && negb (InBool Nat.eq_dec a (FilterLTs l n)))%bool eqn:e; auto.\n  apply andb_prop in e; destruct e as [e1 e2].\n  assert (a < n) by (rewrite Nat.ltb_lt in e1; auto).\n  assert (~ In a (FilterLTs l n)) by (rewrite Bool.negb_true_iff in e2; rewrite InBoolSpec' in e2; auto).\n  constructor; auto.\nQed.\n\nTheorem FilterLTs_in : forall (l : list nat) (n m : nat),\n    In m (FilterLTs l n) -> In m l.\nProof.\n  intros l n m H.\n  induction l. simpl in H; inversion H.\n  simpl in H. destruct ((a <? n) && negb (InBool Nat.eq_dec a (FilterLTs l n)))%bool.\n  destruct H; [left | right; apply IHl]; auto.\n  right; apply IHl; auto.\nQed.\n\nTheorem InFilterLTs : forall (l : list nat) (n m : nat),\n    In m l ->  m < n -> In m (FilterLTs l n).\nProof.\n  intros l n m H H0; induction l; simpl in H; [inversion H|]; destruct H; simpl;\n    destruct ((a <? n) && negb (InBool Nat.eq_dec a (FilterLTs l n)))%bool eqn:e; simpl;\n      try (match goal with\n           | [ H : ?P |- ?P \\/ _ ] => left; auto\n           | [ H : ?P, IH : ?P -> ?Q |- _ \\/ ?Q] => right; apply IH; auto\n           | [ H : ?P, IH : ?P -> ?Q |- ?Q ] => apply IH; auto\n           end).\n  destruct (Bool.andb_false_elim _ _ e).  \n  exfalso; apply Nat.ltb_nlt in e0; apply e0; rewrite H; auto. \n  rewrite Bool.negb_false_iff in e0; rewrite InBoolSpec in e0; rewrite H in e0; auto.\nQed.\n\nFixpoint AllBelow (n : nat) : list nat :=\n  match n with\n  | 0 => []\n  | S n => AllBelow n ++ [n]\n  end.\n\nTheorem InAllBelow : forall (n m : nat),\n    m < n <-> In m (AllBelow n).\nProof.\n  intros n; induction n; intros m; split; intro H.\n  - inversion H.\n  - simpl in H; inversion H.\n  - simpl; apply in_or_app; apply Lt.lt_n_Sm_le in H; apply Lt.le_lt_or_eq in H; destruct H.\n    left; rewrite <- IHn; auto.\n    right; rewrite H; left; auto.\n  - simpl in H. apply in_app_or in H. destruct H.\n    rewrite <- IHn in H; auto.\n    destruct H; [rewrite H; auto | inversion H].\nQed.\n\nTheorem AllBelowLength : forall (n : nat),\n    length (AllBelow n) = n.\nProof.\n  intros n; induction n; simpl; auto.\n  rewrite app_length; simpl; rewrite IHn; rewrite Nat.add_comm; simpl; reflexivity.\nQed.  \n\nProgram Fixpoint ListDifference {A : Type} (AEq : forall a b : A, {a = b} + {a <> b}) (l1 l2 : list A)\n  : list A :=\n  match l1 with\n  | [] => []\n  | a :: l1' => if InBool AEq a l2\n               then ListDifference AEq l1' l2\n               else a :: ListDifference AEq l1' l2\n  end.\n\nTheorem ListDifference_length1 : forall {A : Type} (AEq : forall a b : A, {a = b} + {a <> b}) (l1 l2 : list A),\n    length (ListDifference AEq l1 l2) <= length l1.\nProof.\n  intros A AEq l1 l2.\n  induction l1; simpl; auto.\n  destruct (InBool AEq a l2) eqn:e.\n  transitivity (length l1); auto.\n  simpl; apply le_n_S; auto.\nQed.\n  \nTheorem SubsetListLength : forall {A : Type} (AEq : forall a b : A, {a = b} + {a <> b}) (l1 l2 : list A),\n    (forall a, In a l1 -> In a l2) -> NoDup l1 -> length l1 <= length l2.\nProof.\n  intros A AEq l1.\n  induction l1; intros l2 H H0.\n  - simpl; apply le_0_n.\n  - simpl.\n    pose proof (MoveToFrontInFront AEq l2 a (H a (or_introl eq_refl))).\n    destruct (MoveToFront AEq l2 a) eqn:e; [inversion H1|].\n    pose proof (MoveToFrontLength AEq l2 a).\n    rewrite e in H2. simpl in H2.\n    rewrite H2. apply Le.le_n_S. apply IHl1; [| inversion H0; auto].\n    intros a1 H3.\n    specialize (H a1 (or_intror H3)).\n    apply Permutation_in with (l' := (MoveToFront AEq l2 a)) in H; [| apply MoveToFrontPermuation].\n    rewrite e in H; destruct H; auto; inversion H0;\n      exfalso; apply H6; simpl in H1; rewrite H1; rewrite H; auto.\nQed.       \n\n\nTheorem FilterLTs_length2 : forall (l : list nat) (n : nat),\n    length (FilterLTs l n) <= n.\nProof.\n  intros l n.\n  rewrite <- AllBelowLength.\n  apply SubsetListLength; [apply Nat.eq_dec| |apply FilterLTs_NoDup].\n  intros a H; apply FilterLTs_lt in H; apply InAllBelow; auto.\nQed.\nLemma FilterLTsZero : forall (l : list nat),\n    FilterLTs l 0 = [].\nProof.\n  intros l; induction l; simpl; auto.\nQed.\n\nLtac DestructFilterLTs :=\n  repeat match goal with\n         | [ |- context [if ?b then _ else _] ] =>\n           let e := fresh \"e\" in\n           destruct b eqn: e\n         | [ H : context [if ?b then _ else _] |- _ ] =>\n           let e := fresh \"e\" in\n           destruct b eqn:e\n         | [ H1 : ?P |- ?P ] => exact H1\n         | [ H1 : ?P, H2 : ~?P |- _ ] => exfalso; apply H2; exact H1\n         | [ H : (?a <? ?b) = true |- _ ] =>\n           match goal with\n           | [ _ : a < b |- _ ] => fail 1\n           | _ => assert (a < b) by (rewrite Nat.ltb_lt in H; auto)\n           end\n         | [ H : (?a <? ?b) = false |- _ ] =>\n           match goal with\n           | [ _ : ~ a < b |- _ ] => fail 1\n           | _ => assert (~ a < b) by (rewrite Nat.ltb_nlt in H; auto)\n           end\n         | [H : (?a =? ?b) = true |- _ ] =>\n           match goal with\n           | [_ : a = b |- _ ]=> fail 1\n           | _ => assert (a = b) by (rewrite Nat.eqb_eq in H; auto)\n           end\n         | [H : (?a =? ?b) = false |- _ ] =>\n           match goal with\n           | [_ : a <> b |- _ ] => fail 1\n           | _ => assert (a <> b) by (rewrite Nat.eqb_neq in H; auto)\n           end\n         | [H : andb ?a ?b = true |- _ ] =>\n           match goal with\n           | [_ : a = true, _ : b = true |- _ ] => fail 1\n           | _ => assert (a = true) by (rewrite Bool.andb_true_iff in H; destruct H; auto);\n                 assert (b = true) by (apply Bool.andb_true_iff in H; destruct H; auto)\n           end\n         | [H : andb ?a ?b = false |- _ ] =>\n           match goal with\n           | [ _ : a = false |- _ ] => fail 1\n           | [ _ : b = false |- _ ] => fail 1\n           | _ => let H' := fresh in\n                 assert (a = false \\/ b = false) as H'\n                     by (rewrite Bool.andb_false_iff in H; auto);\n                 destruct H'\n           end\n         | [H : negb ?a = true |- _ ] =>\n           match goal with\n           | [_ : a = false |- _ ] => fail 1\n           | _ => assert (a = false) by (rewrite Bool.negb_true_iff in H; auto)\n           end\n         | [H : negb ?a = false |- _ ] =>\n           match goal with\n           | [_ : a = true |- _ ] => fail 1\n           | _ => assert (a = true) by (rewrite Bool.negb_false_iff in H; auto)\n           end\n         | [H : InBool _ ?a ?l = true |- _ ] =>\n           match goal with\n           | [ _ : In a l |- _ ] => fail 1\n           | _ => assert (In a l) by (rewrite InBoolSpec in H; auto)\n           end\n         | [H : InBool _ ?a ?l = false |- _ ] =>\n           match goal with\n           | [_ : ~(In a l) |- _ ] => fail 1\n           | _ => assert (~In a l) by (rewrite InBoolSpec' in H; auto)\n           end\n         end.\n\nLemma FilterLTs_length_NotInZero : forall (l : list nat) (n : nat),\n    ~ In 0 l ->\n    length (FilterLTs (map (fun x => x - 1) l) n) = length (FilterLTs l (S n)).\nProof.\n  intros l; induction l; intros n ni; simpl; auto.\n  DestructFilterLTs.\n  - simpl. simpl.\n    rewrite IHl; auto. intro Hcontra; apply ni; right; auto.\n  - exfalso; apply H3; destruct a; [apply Nat.lt_0_succ |].\n    simpl in H1; rewrite Nat.sub_0_r in H1; apply Lt.lt_n_S; auto.\n  - exfalso. pose proof (FilterLTs_lt _ _ _ H5).\n    pose proof (FilterLTs_in _ _ _ H5).\n    apply H6. apply InFilterLTs. pose proof (in_map (fun x => x - 1) _ _ H8).\n    simpl in H9. auto.\n    destruct a; [exfalso; apply ni; left; auto | simpl; rewrite Nat.sub_0_r; apply Lt.lt_S_n; auto].\n  - exfalso; apply H3; destruct a.\n    exfalso; apply ni; left; auto.\n    simpl; rewrite Nat.sub_0_r; apply Lt.lt_S_n; auto.\n  - apply FilterLTs_in in H5. apply map_preservesIn in H5.\n    destruct H5 as [b Hb]; destruct Hb.\n    assert (a = b)\n      by (destruct a; [exfalso; apply ni; left; auto |]; destruct b;[exfalso; apply ni; right; auto|];\n          simpl in H7; rewrite Nat.sub_0_r in H7; rewrite Nat.sub_0_r in H7; rewrite H7; auto).\n    exfalso; apply H6; apply InFilterLTs; [rewrite H8 |]; auto.\n  - apply IHl; intro Hcontra; apply ni; right; auto.\n  - destruct a; [exfalso; apply ni; left; auto|].\n    simpl in H3. rewrite Nat.sub_0_r in H3. apply FilterLTs_lt in H3.\n    exfalso; apply H0; apply Lt.lt_n_S; auto.\n  - apply IHl; intro Hcontra; apply ni; right; auto.\n  - apply IHl; intro Hcontra; apply ni; right; auto.\nQed.\n\n\nLemma FilterLTs_remove_zeros : forall (l : list nat) (n : nat),\n    FilterLTs (RemoveZeros l) n = RemoveZeros (FilterLTs l n).\nProof.\n  intros l n. induction l.\n  simpl. auto.\n  simpl; DestructFilterLTs; simpl; DestructFilterLTs.\n  - rewrite IHl; auto.\n  - exfalso. rewrite IHl in H7. apply InRemoveZeros in H7. destruct H7. apply H4; auto.\n  - exfalso. apply H7. rewrite IHl. apply InRemoveZeros'; auto.\nQed.\n\nLemma FilterLTs_length_remove_zeros : forall (l : list nat) (n : nat),\n    In 0 l -> length (FilterLTs (RemoveZeros l) n) = length (FilterLTs l n) - 1.\nProof.\n  intros l n H.\n  rewrite FilterLTs_remove_zeros.\n  induction l; simpl; auto.\n  simpl; DestructFilterLTs.\n  simpl. DestructFilterLTs.\n  - rewrite Nat.sub_0_r; rewrite RemoveZerosWithoutZerosInv; [auto | rewrite H5 in H4; auto].\n  - simpl. destruct H; [exfalso; apply H5; auto | ]. rewrite IHl; auto. apply Minus.minus_Sn_m.\n    clear IHl H3 H1 H4 e e0 H0. induction l; [inversion H | simpl; auto].\n    DestructFilterLTs; simpl.\n    -- simpl. apply OneLES.\n    -- destruct H.\n       exfalso; apply H1; rewrite H; destruct n; [inversion H2 | apply Nat.lt_0_succ].\n       apply IHl; auto.\n    -- destruct (FilterLTs l n); [inversion H3 | simpl; apply OneLES].\n  - destruct H; [| apply IHl; auto].\n    destruct n; [rewrite FilterLTsZero; simpl; auto\n                | exfalso; apply H1; rewrite H; apply Nat.lt_0_succ].\n  - destruct H; [apply FilterLTs_in in H2; apply IHl; rewrite <- H; auto |apply IHl; auto].\nQed.\n\nLemma FilterLTs_length_S_InZero : forall (l : list nat) (n : nat),\n    In 0 l ->\n    length (FilterLTs (map (fun x => x - 1) (RemoveZeros l)) n) = length (FilterLTs l (S n)) - 1.\nProof.\n  intros l n H.\n  pose proof (FilterLTs_length_NotInZero (RemoveZeros l) n (ZeroNotInRemoveZeros l)).\n  rewrite H0.\n  apply FilterLTs_length_remove_zeros; auto.\nQed.\n\nFixpoint AllBelowMinusZero (n : nat) : list nat :=\n  match n with\n  | 0 => []\n  | 1 => []\n  | S n => (AllBelowMinusZero n) ++ [n]\n  end.\n\nLemma InAllBelowMinusZero : forall (n m : nat),\n    m < n -> m <> 0 -> In m (AllBelowMinusZero n).\nProof.\n  intros n; induction n; intros m H H0.\n  inversion H.\n  simpl; destruct n.\n  destruct m; [exfalso; apply H0; auto | apply Lt.lt_S_n in H; inversion H].\n  inversion H; apply in_or_app.\n  right; left; auto.\n  left. apply IHn; auto.\nQed.\n\nLemma AllBelowMinusZeroLength : forall (n : nat),\n    length (AllBelowMinusZero n) = n - 1.\nProof.\n  intros n; induction n; simpl; auto.\n  destruct n. simpl. auto.\n  rewrite app_length; rewrite IHn; simpl; rewrite Nat.sub_0_r; rewrite Nat.add_comm; simpl; auto.\nQed.\n\nLemma FilterLTs_everything : forall (l : list nat) (n : nat),\n    length (FilterLTs l (S n)) = (S n) -> In 0 (FilterLTs l (S n)).\nProof.\n  intros l n H.\n  destruct (ListDec.In_dec Nat.eq_dec 0 (FilterLTs l (S n))); auto.\n  assert (forall x, In x (FilterLTs l (S n)) -> In x (AllBelowMinusZero (S n))).\n  intros x H0. pose proof (FilterLTs_in _ _ _ H0). pose proof (FilterLTs_lt _ _ _ H0).\n  apply InAllBelowMinusZero; auto.\n  intro Hcontra; apply n0; apply InFilterLTs; [rewrite <- Hcontra; auto | apply Nat.lt_0_succ].\n  assert (NoDup (FilterLTs l (S n))) by apply FilterLTs_NoDup.\n  pose proof (SubsetListLength Nat.eq_dec _ _ H0 H1).\n  rewrite AllBelowMinusZeroLength in H2. simpl in H2. rewrite Nat.sub_0_r in H2.\n  rewrite H in H2. exfalso; eapply Nat.nle_succ_diag_l; eauto.\nQed.\n\n\nFixpoint nub {A : Type} (ADec : forall a b : A, {a = b} + {a <> b}) (l : list A) : list A :=\n  match l with\n  | [] => []\n  | x :: xs => if InBool ADec x xs\n              then nub ADec xs\n              else x :: (nub ADec xs)\n  end.\n\nLemma nub_In : forall {A : Type} ADec (l : list A) (a : A),\n    In a l <-> In a (nub ADec l).\nProof.\n  intros A ADec l a.\n  induction l. simpl; split; auto.\n  simpl. destruct (InBool ADec a0 l) eqn:e.\n  split; intro H; auto.\n  destruct H; [rewrite H in e; rewrite InBoolSpec in e|]; apply IHl; auto.\n  right; apply IHl; auto.\n  simpl. split; intro H.\n  all: destruct H; [left; auto| right; apply IHl; auto].\nQed.\n\nLemma nub_count_occ_01 : forall {A : Type} ADec (l : list A) (a : A),\n    count_occ ADec (nub ADec l) a = 1 \\/ count_occ ADec (nub ADec l) a = 0.\nProof.\n  intros A ADec l a.\n  induction l; simpl. right; auto.\n  destruct (InBool ADec a0 l) eqn:e; auto.\n  simpl. destruct (ADec a0 a); auto.\n  assert (~ In a0 (nub ADec l))\n    by (intro H; rewrite InBoolSpec' in e; apply e; rewrite nub_In; exact H).\n  left; rewrite e0 in H; pose proof (proj1 (count_occ_not_In ADec (nub ADec l) a) H);\n    rewrite H0; auto.\nQed.\n  \nLemma nub_count_occ: forall {A : Type} ADec (l : list A) (a : A),\n    In a l <-> count_occ ADec (nub ADec l) a = 1.\nProof.\n  intros A ADec l a; split; intro H.\n  - destruct (nub_count_occ_01 ADec l a); auto; exfalso.\n    rewrite (nub_In ADec) in H.\n    pose proof ((proj1 (count_occ_In ADec (nub ADec l) a)) H).\n    rewrite H0 in H1; inversion H1.\n  - rewrite (nub_In ADec); rewrite (count_occ_In ADec); rewrite H; auto.\nQed.  \n  \nProgram Fixpoint WithoutPath {A : Set}\n        {a : A} (l : list A) (p : Path a l) {struct p}: list A :=\n  match p with\n  | Here _ l => l\n  | There b pth' => b :: (WithoutPath _ pth')\n  end.\n\nInductive PathToSamePlace {A : Set} : forall (l1 l2 : list A) (a b : A),\n    Path a l1 -> Path b l2 -> Prop :=\n| BothHere : forall (l : list A) (a : A), PathToSamePlace (a :: l) (a :: l) a a (Here a l) (Here a l)\n| BothThere : forall (l1 l2 : list A) (a b c : A) (p1 : Path b l1) (p2 : Path c l2),\n    PathToSamePlace l1 l2 b c p1 p2 -> PathToSamePlace (a :: l1) (a :: l2) b c (There a p1) (There a p2).\n\nLemma PathToSamePlaceSameA : forall {A : Set} (l1 l2 : list A) (a b : A)\n                               (p1 : Path a l1) (p2 : Path b l2),\n    PathToSamePlace l1 l2 a b p1 p2 -> a = b.\nProof.\n  intros A l1 l2 a b p1 p2 H.\n  induction H; auto.\nQed.\n  \nLemma PathToSamePlaceSameL : forall {A : Set} (l1 l2 : list A) (a b : A)\n                               (p1 : Path a l1) (p2 : Path b l2),\n    PathToSamePlace l1 l2 a b p1 p2 -> l1 = l2.\nProof.\n  intros A l1 l2 a b p1 p2 H.\n  induction H; auto.\n  rewrite IHPathToSamePlace; auto.\nQed.\n\nLemma PathToSamePlaceRefl : forall {A : Set} (l : list A) (a : A) (p : Path a l),\n    PathToSamePlace l l a a p p.\nProof.\n  intros A l a p.\n  induction p; try (constructor; auto; fail).\nQed.\n\nLemma PathToSamePlaceIndexEq : forall {A : Set} (l1 l2 : list A) (a b : A)\n                                 (p1 : Path a l1) (p2 : Path b l2),\n    PathToSamePlace l1 l2 a b p1 p2 -> PathToIndex p1 = PathToIndex p2.\nProof.\n  intros A l1 l2 a b p1 p2 ptsp.\n  induction ptsp; simpl; auto.\nQed.\n\nLemma PathToIndexEqToSamePlace : forall {A : Set} (l : list A) (a b : A)\n                                 (p1 : Path a l) (p2 : Path b l),\n    PathToIndex p1 = PathToIndex p2 -> PathToSamePlace l l a b p1 p2.\nProof.\n  intros A l a b p1 p2 indexEq.\n  induction p1 eqn:e; simpl in *.\n  - destruct (PathToIndex0_Here p2 (eq_sym indexEq)).\n    generalize dependent p2. rewrite H. intros p2 indexEq H0.\n    apply JMeq_eq in H0. rewrite H0. constructor.\n  - remember (PathToIndexS_There p2 (PathToIndex p) (eq_sym indexEq)).\n    clear Heqe0. destruct e0 as [b1 e0]; destruct e0 as [l' e0]; destruct e0 as [pth' H];\n                   destruct H as [e1 e2].\n    inversion e1. clear e1. generalize dependent p2.\n    rewrite H0. generalize dependent pth'. rewrite <- H1.\n    intros pth' p2 indexEq e2.\n    apply JMeq_eq in e2. rewrite e2. constructor.\n    apply IHp with (p1 := p). reflexivity. rewrite e2 in indexEq. simpl in indexEq.\n    inversion indexEq; auto.\nQed.\n\nLemma PathToSamePlaceRecursive :\n  forall {A : Set} (l l' : list A) (a b c d : A)  (p1 : Path a l) (p2 : Path b l')\n    (Adec : forall a b : A, {a = b} + {a <> b}),\n    PathToSamePlace (c :: l) (d :: l') a b (There c p1) (There d p2) ->\n    PathToSamePlace l l' a b p1 p2.\nProof.\n  intros A l l' a b c d p1 p2 Adec p3.\n  inversion p3.\n  apply Eqdep_dec.inj_pair2_eq_dec in H6; auto.\n  apply Eqdep_dec.inj_pair2_eq_dec in H6; [| apply list_eq_dec; auto].\n  apply Eqdep_dec.inj_pair2_eq_dec in H7; auto.\n  apply Eqdep_dec.inj_pair2_eq_dec in H7; [| apply list_eq_dec; auto].\n  rewrite <- H6. rewrite <- H7. exact H5.\nQed.\n  \nProgram Fixpoint PathToSamePlaceDec\n  {A : Set} {l1 l2 : list A} {a b : A} (p1 : Path a l1) (p2 : Path b l2) (Adec : forall x y : A, {x = y} + {x <> y})\n  : {PathToSamePlace l1 l2 a b p1 p2} + {~ PathToSamePlace l1 l2 a b p1 p2} :=\n  match p1 with\n  | Here x l1' => match p2 with\n                 | Here y l2' =>\n                   match Adec x y with\n                   | left e => \n                     match list_eq_dec Adec l1' l2' with\n                     | left e => left _\n                     | right n => right _\n                     end\n                   | right n => right _\n                   end\n                 | There _ _ => right _\n                 end\n  | There x p1' => match p2 with\n                | Here _ _ => right _\n                | There y p2' =>\n                  match (Adec x y) with\n                  | left e => \n                    match (PathToSamePlaceDec p1' p2' Adec) with\n                    | left e' => left _\n                    | right n => right _\n                    end\n                  | right n => right _\n                  end\n                                        \n                  end\n  end.\nNext Obligation.\n  constructor.\nDefined.\nNext Obligation.\n  intro H; apply n. apply PathToSamePlaceSameL in H.\n  inversion H; auto.\nDefined.\nNext Obligation.\n  intro H; apply n. eapply PathToSamePlaceSameA; exact H.\nDefined.\nNext Obligation.\n  intro H; inversion H.\nDefined.\nNext Obligation.\n  intro H; inversion H.\nDefined.\nNext Obligation.\n  constructor; auto.\nDefined.\nNext Obligation.\n  intro H. apply PathToSamePlaceRecursive in H; auto.\nDefined.\nNext Obligation.\n  intro H. apply PathToSamePlaceSameL in H. inversion H. apply n; auto.\nDefined.\n\n  Lemma withoutLiftPath : forall {A : Set} (l : list A) (a b : A) (pth : Path a l), Path b (WithoutPath l pth) -> Path b l. \n  Proof.\n    induction pth; simpl; intros.\n    apply There; auto.\n    inversion H; subst.\n    apply Here.\n    apply There; auto.\n  Qed.\n\n  Program Fixpoint RemoveIndex {A : Set} (l : list A) (n : nat) (corr : n < length l) : list A :=\n    match n with\n    | 0 => match l with\n          | [] => _\n          | _ :: l' => l'\n          end\n    | S m => match l with\n            | [] => _\n            | a :: l' => a :: (RemoveIndex l' m _)\n            end\n    end.\n  Next Obligation.\n    exfalso; inversion corr.\n  Defined.\n  Next Obligation.\n    exfalso; inversion corr.\n  Defined.\n  Next Obligation.\n    simpl in corr; apply Lt.lt_S_n; auto.\n  Defined.\n\n  Definition Reindex (n m : nat) : nat :=\n    if n <? m\n    then m - 1\n    else m.\n\n  Fixpoint RemoveIndex' {A : Set} (l : list A) (n : nat) : list A :=\n    match l with\n    | [] => []\n    | a :: l' => match n with\n               | 0 => l'\n               | S m => a :: (RemoveIndex' l' m)\n               end\n    end.\n\n  Theorem RemoveIndexWhenCorr : forall {A : Set} (l : list A) (n : nat) (corr : n < length l),\n      RemoveIndex l n corr = RemoveIndex' l n.\n  Proof.\n    intros A l n corr.\n    generalize dependent n.\n    induction l; intros. inversion corr.\n    destruct n. simpl. reflexivity.\n    simpl. rewrite IHl. reflexivity.\n  Qed.\n\n  Theorem RemoveIndex'Nil : forall {A : Set} (n : nat),\n      @RemoveIndex' A [] n = [].\n  Proof.\n    auto.\n  Qed.    \n  \n  Theorem RemoveIndexNil : forall (A : Set) (n : nat) (corr : n < 0),\n      @RemoveIndex A [] n corr = [].\n  Proof.\n    intros A n corr.\n    inversion corr.\n  Qed.\n\n  Theorem Reindex'_correct_m_lt : forall {A : Set} (l : list A) (n m : nat),\n      m < n -> nth_error l m = nth_error (RemoveIndex' l n) (Reindex n m).\n  Proof.\n    intros A l n m H.\n    unfold Reindex. destruct (n <? m) eqn: n_lt_m.\n    apply Nat.ltb_lt in n_lt_m.\n    exfalso. eapply Nat.lt_asymm; [exact H | exact n_lt_m].\n    apply Nat.ltb_nlt in n_lt_m.\n    generalize dependent m. generalize dependent n.\n    induction l; intros n m H n_lt_m.\n    - simpl. reflexivity.\n    - simpl. destruct n. inversion H.\n      destruct m. simpl. reflexivity.\n      simpl; apply IHl;\n        [apply Lt.lt_S_n; exact H| intro H'; apply n_lt_m; apply Lt.lt_n_S; exact H'].\n  Qed.      \n\nProgram Fixpoint RepathWithoutPath {A : Set} {a1 a2 : A}\n        {l : list A} (p1 : Path a1 l) (p2 : Path a2 l)\n  (n : ~ PathToSamePlace l l a1 a2 p1 p2) : Path a2 (WithoutPath l p1) :=\n  match p1 with\n  | Here b l =>\n    match p2 with\n    | Here _ _ => _\n    | There c pth' => pth'\n    end\n  | There b pth' =>\n    match p2 with\n    | Here _ l' => Here a2 (WithoutPath l' pth')\n    | There c pth'' => There b (RepathWithoutPath pth' pth'' _)\n    end\n  end.\nNext Obligation.\n  exfalso; apply n; clear n.\n  apply JMeq_eq in Heq_l0.\n  apply JMeq_eq in Heq_l.\n  pose proof (eq_trans Heq_l0 (eq_sym Heq_l)) as e.\n  inversion e.\n  assert (PathToIndex p1 = 0)\n  by (clear Heq_p2 Heq_l p2 H1 e H0 a2;\n      generalize dependent p1;\n      rewrite <- Heq_l0; intros p1 Heq_p1; apply JMeq_eq in Heq_p1;\n      rewrite <- Heq_p1; simpl; reflexivity).\n  assert (PathToIndex p2 = 0)\n    by (clear Heq_p1 Heq_l0 p1 H1 e H0 a1 H;\n        generalize dependent p2;\n        rewrite <- Heq_l;\n        intros p2 Heq_p2; apply JMeq_eq in Heq_p2;\n        rewrite <- Heq_p2; simpl; reflexivity).\n  apply PathToIndexEqToSamePlace; rewrite H; rewrite H2; reflexivity.\nDefined.\nNext Obligation.\n  apply JMeq_eq in Heq_l0.\n  apply JMeq_eq in Heq_l.\n  pose (eq_trans Heq_l0 (eq_sym Heq_l)).\n  inversion e; auto.\nDefined.\nNext Obligation.\n  apply JMeq_eq in Heq_l0.\n  apply JMeq_eq in Heq_l.\n  pose (eq_trans Heq_l0 (eq_sym Heq_l)).\n  inversion e; auto.\nDefined.\nNext Obligation.\n  unfold eq_rect; simpl.\n  destruct (RepathWithoutPath_obligation_3 A a1 a2 l p1 p2 a1 b wildcard'0 pth' eq_refl\n                                            Heq_l0 Heq_p1 a2 l' eq_refl Heq_l Heq_p2).\n  apply JMeq_eq in Heq_l0. apply JMeq_eq in Heq_l.\n  pose proof (eq_trans Heq_l0 (eq_sym Heq_l)) as e.\n  inversion e. reflexivity.\nDefined.\nNext Obligation.\n  apply JMeq_eq in Heq_l0. apply JMeq_eq in Heq_l.\n  pose proof (eq_trans Heq_l0 (eq_sym Heq_l)) as e. inversion e; reflexivity.\nDefined.\nNext Obligation.\n  destruct (RepathWithoutPath_obligation_6 A a1 a2 l p1 p2 a1 b wildcard'2 pth' eq_refl\n                                           Heq_l0 Heq_p1 a2 c wildcard'0 pth'' eq_refl Heq_l Heq_p2).\n  simpl.\n  assert (PathToIndex p2 = S (PathToIndex pth''))\n    by (clear Heq_p1 Heq_l0 n b p1 pth';\n        generalize dependent p2; apply JMeq_eq in Heq_l; rewrite <- Heq_l;\n        intros p2 Heq_p2; apply JMeq_eq in Heq_p2; rewrite <- Heq_p2; simpl; reflexivity).\n  assert (PathToIndex p1 = S (PathToIndex pth'))\n    by (clear Heq_p2 Heq_l n c p2 pth'' H;\n        generalize dependent p1; apply JMeq_eq in Heq_l0; rewrite <- Heq_l0;\n        intros p1 Heq_p1; apply JMeq_eq in Heq_p1; rewrite <- Heq_p1; simpl; reflexivity).\n  intro Hsame. apply PathToSamePlaceIndexEq in Hsame.\n  apply n. apply PathToIndexEqToSamePlace.\n  transitivity (S (PathToIndex pth')); auto.\n  rewrite Hsame. symmetry; auto.\nDefined.\n\nLemma PathToFront : forall {A : Set} {a : A} {l : list A} (pth : Path a l),\n    Permutation l (a :: WithoutPath l pth).\nProof.\n  intros A a l pth.\n  induction pth; simpl. apply Permutation_refl.\n  apply perm_trans with (l' := b :: a :: WithoutPath l pth);\n    [apply perm_skip; auto | apply perm_swap].\nQed.\n  \nLemma combine_nil_l : forall {A : Type} {B : Type} (l : list B), @combine A B [] l = [].\nProof.\n  intros A B l; reflexivity.\nQed.\nLemma combine_nil_r : forall {A : Type} {B : Type} (l : list A), @combine A B l [] = [].\nProof.\n  intros A B l; induction l; reflexivity.\nQed.\n", "meta": {"author": "FLAFOL", "repo": "flafol-coq", "sha": "1803453d86ba8be103b513f2300a377aaf84326b", "save_path": "github-repos/coq/FLAFOL-flafol-coq", "path": "github-repos/coq/FLAFOL-flafol-coq/flafol-coq-1803453d86ba8be103b513f2300a377aaf84326b/Base/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.709555519779278}}
{"text": "Require Import Arith Div2 Wf_nat Omega.\n\nHint Constructors Even.even Even.odd.\n\nLemma sqrt2 : forall n p, n * n = 2 * p * p -> p = 0.\nProof.\n  intros n.\n  induction n as [[| n] IHn] using (well_founded_induction lt_wf);\n    intros p H.\n  - destruct p; simpl in *; inversion H; auto.\n  - destruct (Even.even_odd_dec (S n)).\n    + replace (S n) with (double (div2 (S n))) in H\n        by (rewrite even_double; eauto).\n      rewrite NPeano.double_twice in *.\n      apply f_equal with (f := div2) in H.\n      repeat rewrite <- mult_assoc in H.\n      repeat rewrite div2_double in H.\n      replace (div2 (S n) * (2 * div2 (S n)))\n        with (2 * div2 (S n) * div2 (S n)) in H by apply mult_comm.\n      destruct (Even.even_odd_dec p).\n      * { replace p with (double (div2 p)) in H\n            by (rewrite even_double; eauto).\n          rewrite NPeano.double_twice in *.\n          replace (div2 (S n) * (2 * div2 (S n)))\n            with (2 * div2 (S n) * div2 (S n)) in H by apply mult_comm.\n          repeat rewrite <- mult_assoc in H.\n          apply f_equal with (f := div2) in H.\n          repeat rewrite div2_double in H.\n          replace (div2 p * (2 * div2 p))\n            with (2 * div2 p * div2 p) in H by apply mult_comm.\n          assert (div2 p = 0).\n          - eapply IHn.\n            + apply lt_div2.\n              omega.\n            + eauto.\n          - destruct p; eauto.\n            rewrite even_div2 in H0 by eauto.\n            simpl in *.\n            congruence. }\n      * exfalso.\n        assert (Even.odd (p * p)) by (apply Even.odd_mult; eauto).\n        assert (Even.even (2 * div2 (S n) * div2 (S n)))\n          by (rewrite <- mult_assoc; apply Even.even_mult_l; eauto).\n        rewrite H in *.\n        eapply Even.not_even_and_odd; eauto.\n    + exfalso.\n      assert (Even.odd (S n * S n)) by (apply Even.odd_mult; eauto).\n      assert (Even.even (2 * p * p)) by (rewrite <- mult_assoc; apply Even.even_mult_l; eauto).\n      rewrite H in *.\n      eapply Even.not_even_and_odd; eauto.\nQed.\n\n\n\n      \n            \n", "meta": {"author": "fetburner", "repo": "Misc", "sha": "c48f9166e922dee111c98157d6da45b77cda5ea6", "save_path": "github-repos/coq/fetburner-Misc", "path": "github-repos/coq/fetburner-Misc/Misc-c48f9166e922dee111c98157d6da45b77cda5ea6/sqrt2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7095554981896705}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2015   --   INRIA - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire Reals.Rfunctions.\nRequire BuiltIn.\nRequire int.Int.\nRequire real.Real.\nRequire real.RealInfix.\n\nRequire Import Exponentiation.\nImport Rfunctions.\n\n(* Why3 comment *)\n(* power is replaced with (Reals.Rfunctions.powerRZ x x1) by the coq driver *)\n\nLemma power_is_exponentiation :\n  forall x n, (0 <= n)%Z -> powerRZ x n = Exponentiation.power _ R1 Rmult x n.\nProof.\nintros x [|n|n] H.\neasy.\n2: now elim H.\nunfold Exponentiation.power, powerRZ.\nsimpl.\ninduction (nat_of_P n).\neasy.\nsimpl.\nnow rewrite IHn0.\nQed.\n\n(* Why3 goal *)\nLemma Power_0 : forall (x:R), ((Reals.Rfunctions.powerRZ x 0%Z) = 1%R).\nProof.\nintros x.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Power_s : forall (x:R) (n:Z), (0%Z <= n)%Z ->\n  ((Reals.Rfunctions.powerRZ x (n + 1%Z)%Z) = (x * (Reals.Rfunctions.powerRZ x n))%R).\nProof.\nintros x n h1.\nrewrite 2!power_is_exponentiation by auto with zarith.\nnow apply Power_s.\nQed.\n\n(* Why3 goal *)\nLemma Power_s_alt : forall (x:R) (n:Z), (0%Z < n)%Z ->\n  ((Reals.Rfunctions.powerRZ x n) = (x * (Reals.Rfunctions.powerRZ x (n - 1%Z)%Z))%R).\nintros x n h1.\nrewrite <- Power_s.\nf_equal; omega.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Power_1 : forall (x:R), ((Reals.Rfunctions.powerRZ x 1%Z) = x).\nProof.\nexact Rmult_1_r.\nQed.\n\n(* Why3 goal *)\nLemma Power_sum : forall (x:R) (n:Z) (m:Z), (0%Z <= n)%Z -> ((0%Z <= m)%Z ->\n  ((Reals.Rfunctions.powerRZ x (n + m)%Z) = ((Reals.Rfunctions.powerRZ x n) * (Reals.Rfunctions.powerRZ x m))%R)).\nProof.\nintros x n m h1 h2.\nrewrite 3!power_is_exponentiation by auto with zarith.\napply Power_sum ; auto with real.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult : forall (x:R) (n:Z) (m:Z), (0%Z <= n)%Z -> ((0%Z <= m)%Z ->\n  ((Reals.Rfunctions.powerRZ x (n * m)%Z) = (Reals.Rfunctions.powerRZ (Reals.Rfunctions.powerRZ x n) m))).\nProof.\nintros x n m h1 h2.\nrewrite 3!power_is_exponentiation by auto with zarith.\napply Power_mult ; auto with real.\nQed.\n\n(* Why3 goal *)\nLemma Power_mult2 : forall (x:R) (y:R) (n:Z), (0%Z <= n)%Z ->\n  ((Reals.Rfunctions.powerRZ (x * y)%R n) = ((Reals.Rfunctions.powerRZ x n) * (Reals.Rfunctions.powerRZ y n))%R).\nProof.\nintros x y n h1.\nrewrite 3!power_is_exponentiation by auto with zarith.\napply Power_mult2 ; auto with real.\nQed.\n\n(* Why3 goal *)\nLemma Pow_ge_one : forall (x:R) (n:Z), ((0%Z <= n)%Z /\\ (1%R <= x)%R) ->\n  (1%R <= (Reals.Rfunctions.powerRZ x n))%R.\nintros x n (h1,h2).\ngeneralize h1.\npattern n; apply Z_lt_induction; auto.\nclear n h1; intros n Hind h1.\nassert (h: (n = 0 \\/ 0 < n)%Z) by omega.\ndestruct h.\nsubst n; rewrite Power_0; auto with *.\nreplace n with ((n-1)+1)%Z by omega.\nrewrite Power_s; auto with zarith.\nassert (h : (1 <= powerRZ x (n-1))%R).\napply Hind; omega.\nreplace 1%R with (1*1)%R by auto with real.\napply Rmult_le_compat; auto with real.\nQed.\n\n", "meta": {"author": "ssaavedra", "repo": "why3", "sha": "e28f4cda05925849c1c203f56b9f9b49e4bfe5b4", "save_path": "github-repos/coq/ssaavedra-why3", "path": "github-repos/coq/ssaavedra-why3/why3-e28f4cda05925849c1c203f56b9f9b49e4bfe5b4/lib/coq/real/PowerInt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7093955147766959}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nModule Lesson6.\n\nLemma addC : commutative addn.\nProof.\nelim => [| x' IHx] y.\n  by rewrite addn0.\nSearch (_ + _.+1).\nby rewrite addSn IHx addnS.\nQed.\n\nLemma addC2 : commutative addn.\nProof.\nelim => [| x' IHx] y; first by rewrite addn0.\nby rewrite addSn IHx addnS.\nQed.\n\nLocate \"`!\".\nPrint factorial.\nPrint nosimpl.\nPrint fact_rec.\n\n(* /=  - simpl *)\n\nFixpoint factorial_helper n acc :=\n  if n is n'.+1 then factorial_helper n' (n * acc) else acc.\n\nDefinition my_factorial n := factorial_helper n 1.\n\nCompute (my_factorial 5).\n\nLemma my_factorial_correct: forall n, my_factorial n = n`!.\nProof.\nelim => [|n' IHn] //.\nrewrite /my_factorial /factorial /= muln1.\nrewrite /my_factorial /factorial in IHn.\nrewrite -{}IHn.       (* {}  - remove hypotesis from context *)\nrewrite /factorial_helper /=.\ncase: n'; first by done.\nAbort.\n\nLemma factorial_helper_correct:\n  forall n a, factorial_helper n a = n`! * a.\nProof.\nelim => [| n' IHn] a /=.\n  by rewrite /factorial /= mul1n.\nrewrite {}IHn.\nby rewrite factS mulnCA mulnA.\nQed.\n\nLemma my_factorial_correct: forall n, my_factorial n = n`!.\nProof.\nrewrite /my_factorial => n.\nby rewrite factorial_helper_correct muln1.\nQed.\n\nSearch (_ * 1).\nSearch left_id muln.\nSearch right_id muln.\n\n\nFixpoint fib (n: nat) :=\n  if n is (n''.+1 as n').+1 \n    then fib n'' + fib n'\n    else n.\n\nLemma tst1 n: fib n.+2 = 0.\nProof. move=> /=. Abort.\n\nArguments fib n : simpl nomatch. (* don't simpl unti matches *)\n\nLemma tst1 n: fib n.+2 = 0.\nProof. move=> /=. Abort.\n\n\nFixpoint fib_iter n f0 f1 :=\n  if n is n'.+1 then fib_iter n' f1 (f0 + f1) else f0.\nArguments fib_iter n : simpl nomatch.\n\nLemma fib_iterS n f0 f1: fib_iter (n.+1) f0 f1 = fib_iter n f1 (f0 + f1).\nProof. done. Qed.\n\nLemma fib_iter_sum n f0 f1:\n  fib_iter n.+2 f0 f1 = fib_iter n f0 f1 + fib_iter n.+1 f0 f1.\nProof.\nelim: n f0 f1 => [//| n' IHn] f0 f1. (* :  - generalize n f0 f1 and then elim top (n) *)\n(* : n f0 f1 = gen f1, gen f0, gen n *)\nrewrite fib_iterS {}IHn.\ndone.\nQed.\n\n\nLemma fib_iter_correct n:\n  fib_iter n 0 1 = fib n.\nProof.\nelim: n => [//|n' IHn].\nrewrite fib_iterS.\nAbort.\n\nLemma nat_ind2 (P: nat -> Prop) :\n  P 0 ->\n  P 1 ->\n  (forall n, P n -> P n.+1 -> P n.+2) ->\n  (forall n, P n).\nProof.\nmove=> p0 p1 pstep n.\nhave: P n /\\ P n.+1; last by case.\nelim: n => [//| n' [IHn' IHSn']].\nsplit=> //.\napply (pstep n' IHn' IHSn').\nQed.\n\nLemma nat_ind2' (P: nat -> Prop) :\n  P 0 ->\n  P 1 ->\n  (forall n, P n -> P n.+1 -> P n.+2) ->\n  (forall n, P n).\nProof.\nmove=> p0 p1 pstep n.\nsuff: P n /\\ P n.+1 by case. (* like have but swaps goals *)\nelim: n => [//| n' [IHn' IHSn']].\nsplit=> //.\napply (pstep n' IHn' IHSn').\nQed.\n\n\nLemma nat_ind3' (P: nat -> Prop) :\n  P 0 ->\n  P 1 ->\n  (forall n, P n -> P n.+1 -> P n.+2) ->\n  (forall n, P n).\nProof.\nmove=> p0 p1 pstep n.\nsuff: P n /\\ P n.+1 by case. (* like have but swaps goals *)\nelim: n => // n.\ncase.\nmove /pstep. (* Apply something to head *)\nmove => p12.\nmove /[dup].\nmove /p12.\ndone.\nQed.\n\nLemma fib_iter_correct n:\n  fib_iter n 0 1 = fib n.\nProof.\n(*elim/nat_ind2: n => [//|//| n' IHn1 IHn2].*)\nelim/nat_ind2: n => // n' IHn1 IHn2.\nrewrite fib_iter_sum {}IHn1 {}IHn2.\ndone.\nQed.\n\nAbout ltn_ind.\n\nLemma fib_iter_correct' n:\n  fib_iter n 0 1 = fib n.\nProof.\nelim/ltn_ind: n => n IHn.\nFail case: n. (* IHn depends on n *)\ncase: n IHn => // n IHn.\ncase: n IHn => // n IHn.\nrewrite fib_iter_sum.\n(*case n' => // n.*)\nrewrite !IHn. (* ! - repeat *)\n- done.\n- done.\ndone.\nRestart.\nelim/ltn_ind: n => [] // [] // [] // n IHn.\nby rewrite fib_iter_sum !IHn.\nQed.\n\n(* {1}<-  - rewrite first entry backwards *)\n\nEnd Lesson6.\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/comp_sci_club-formal_verif_2021/Lesson6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.9032942106088968, "lm_q1q2_score": 0.7093646946574005}}
{"text": "\n\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\n\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint len (len_arg0 : lst) : natural\n           := match len_arg0 with\n              | Nil => Zero\n              | Cons x y => Succ (len y)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nLemma lem : forall l1 l2 n, Succ (len (append l1 l2)) = len (append l1 (Cons n l2)).\nProof.\n  induction l1.\n  - intros. simpl. f_equal. apply IHl1.\n  - intros. reflexivity.\nQed.\n\nLemma lem2 : forall l, len l = len (append l Nil).\nProof.\n  induction l.\n  - simpl. f_equal. apply IHl.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (len (rev x)) (len x).\nProof.\ninduction x.\n  - simpl. rewrite <- IHx. rewrite <- (lem (rev x) Nil n). \n    rewrite <- lem2. reflexivity.\n  - reflexivity.\nQed.\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7093646920406267}}
{"text": "Require Import Arith Nat Lia List Extraction.\n\nSet Implicit Arguments.\n\nFixpoint list_snoc_rect {X:Type} (P:list X -> Type)\n     (HP0 : P nil) \n     (HP1 : forall l x,  P l -> P (l++x::nil))\n     l : P l.\nProof.\n  destruct l as [ | x l ].\n  + apply HP0.\n  + apply list_snoc_rect with (P := fun l => P (x::l)) (l := l).\n    * apply (HP1 nil), HP0.\n    * intros; apply (HP1 (x::_)); auto.\nQed.\n \nInductive pos3 := ZZ | OO | TT.\n\nDefinition pos3_nat p :=\n  match p with\n    | ZZ => 0\n    | OO => 1\n    | TT => 2\n  end.\n\nFact pos3_nat_le p : pos3_nat p <= 2.\nProof. destruct p; auto. Qed.\n\n(*\n\n1 2 3 4 5 6 7 8 9 a b c d e f\n  1   2   3   4   5   6   7\n      1       2       3   \n              1\n\nN []   = 1 \nN l++x = 2*N l + (x-1)\n\n*)\n\nFixpoint N_rec a l :=\n  match l with\n    | nil  => a \n    | x::l => N_rec (2*a+(pos3_nat x)-1) l\n  end.\n\nDefinition N l := N_rec 1 l.\n\nFact N_nil : N nil = 1.\nProof. trivial. Qed.\n\nFixpoint N_app a l m : N_rec a (l++m) = N_rec (N_rec a l) m.\nProof. destruct l; simpl; auto. Qed.\n  \nFact N_snoc l x : N (l++x::nil) = 2*N l+pos3_nat x-1.\nProof.\n  unfold N; rewrite N_app; simpl; auto.\nQed.\n\nFact N_bound l : 1 <= N l <= 2^(1+length l)-1.\nProof.\n  induction l as [ | l x IHl ] using list_snoc_rect.\n  + rewrite N_nil; simpl; lia.\n  + rewrite N_snoc, app_length; simpl length.\n    generalize (pos3_nat_le x).\n    replace (1+(length l+1)) with (S (1+length l)) by lia.\n    rewrite Nat.pow_succ_r'.\n    lia.\nQed.\n\nEval compute in N (ZZ::OO::TT::nil).\nEval compute in N (TT::TT::TT::nil).\n\nFact N_ZZ l : N (ZZ::l) < 2*2^(length l).\nProof.\n  induction l as [ | l x IHl ] using list_snoc_rect.\n  + cbv; auto.\n  + change (ZZ::l++x::nil) with ((ZZ::l)++x::nil).\n    rewrite N_snoc, app_length.\n    simpl length.\n    rewrite Nat.pow_add_r.\n    revert IHl.\n    generalize (pos3_nat x) (N (ZZ::l)) (2^length l) (pos3_nat_le x).\n    intros a b c H1 H2; simpl; lia.\nQed.\n\nFact N_OO l : 2^(length l) < N (OO::l) < 3*2^(length l).\nProof.\n  induction l as [ | l x IHl ] using list_snoc_rect.\n  + cbv; auto.\n  + change (OO::l++x::nil) with ((OO::l)++x::nil).\n    rewrite N_snoc, app_length.\n    simpl length.\n    rewrite Nat.pow_add_r.\n    revert IHl.\n    generalize (pos3_nat x) (N (OO::l)) (2^length l) (pos3_nat_le x).\n    intros a b c H1 H2; simpl; lia.\nQed.\n\nFact N_TT l : 2*2^(length l) < N (TT::l).\nProof.\n  induction l as [ | l x IHl ] using list_snoc_rect.\n  + cbv; auto.\n  + change (TT::l++x::nil) with ((TT::l)++x::nil).\n    rewrite N_snoc, app_length.\n    simpl length.\n    rewrite Nat.pow_add_r.\n    revert IHl.\n    generalize (pos3_nat x) (N (TT::l)) (2^length l) (pos3_nat_le x).\n    intros a b c H1 H2; simpl; lia.\nQed.\n\nCoInductive stream := lcons : pos3 -> stream -> stream.\n\nCoFixpoint lcst x := lcons x (lcst x).\n\nFixpoint prefix n s := \n  match n, s with \n    | 0  , _         => nil\n    | S n, lcons x s => x::prefix n s\n  end.\n\nFixpoint ltail n s :=\n  match n, s with \n    | 0  , s         => s\n    | S n, lcons x s => ltail n s\n  end.\n\nFixpoint lapp l s :=\n  match l with\n    | nil  => s\n    | x::l => lcons x (lapp l s)\n  end.\n\nFact ltail_cst n x : ltail n (lcst x) = lcst x.\nProof.\n  induction n; auto.\nQed.\n\nFact prefix_ltail n s : lapp (prefix n s) (ltail n s) = s.\nProof.\n  revert s; induction n as [ | n IHn ]; intros s; auto.\n  destruct s as [ x s ]; simpl; f_equal; auto.\nQed.\n\nFact prefix_add n m s : prefix (n+m) s = prefix n s ++ prefix m (ltail n s).\nProof.\n  revert s; induction n as [ | n IHn ]; intros s; auto.\n  destruct s; simpl; f_equal; auto.\nQed.\n\nFact prefix_length n s : length (prefix n s) = n.\nProof.\n  revert s; induction n as [ | n IHn ]; intros []; simpl; f_equal; auto.\nQed.\n\nFact pow2_ge_1 n : 1 <= 2^n.\nProof.\n  change 1 with (2^0).\n  apply Nat.pow_le_mono_r_iff; simpl; lia.\nQed.\n\nEval compute in N (prefix 3 (lcst TT)).\n\nFact N_ZZZ n : N (prefix n (lcst ZZ)) = 1.\nProof.\n  induction n; auto.\nQed.\n\nFact N_OOO n : N (prefix n (lcst OO)) = 2^n.\nProof.\n  induction n as [ | n IHn ]; auto.\n  replace (S n) with (n+1) by lia.\n  rewrite prefix_add, ltail_cst.\n  simpl prefix; rewrite N_snoc, IHn.\n  simpl pos3_nat.\n  rewrite Nat.pow_add_r; simpl; lia.\nQed.\n\nFact N_TTT n : N (prefix n (lcst TT)) = 2*2^n-1.\nProof.\n  induction n as [ | n IHn ]; auto.\n  replace (S n) with (n+1) by lia.\n  rewrite prefix_add, ltail_cst.\n  simpl prefix; rewrite N_snoc, IHn.\n  simpl pos3_nat.\n  rewrite Nat.pow_add_r.\n  generalize (2^n) (pow2_ge_1 n).\n  intros; simpl; lia.\nQed.\n\n(** Every stream s represents a real which is the limit \n    of fun n => N (prefix n s) / 2*2^n) \n\n    ZZZ = lcst ZZ ~~~> 0\n    OOO = lcst OO ~~~> 1/2\n    TTT = lcst TT ~~~> 1\n\n*)\n\n(** Looking at the first value in the stream s allows to\n    position s either in [ 0 .. 3/4 ] or in [ 1/4 .. 1 ] *)\n\nTheorem stream_choose s : { m : _ & (forall n, m <= n -> N (prefix n s) <= 3*2^(n-1))\n                                  + (forall n, m <= n -> 2^(n-1) <= N (prefix n s))  }%type.\nProof.\n  destruct s as [ [] s ].\n  + exists 1; left; intros n Hn.\n    replace n with (1+(n-1)) at 1 by lia. \n    generalize (n-1); intros a; clear n Hn.\n    simpl prefix.\n    generalize (N_ZZ (prefix a s)).\n    rewrite prefix_length; lia.\n  + exists 1; left; intros n Hn.\n    replace n with (1+(n-1)) at 1 by lia. \n    generalize (n-1); intros a; clear n Hn.\n    simpl prefix.\n    generalize (N_OO (prefix a s)).\n    rewrite prefix_length; lia.\n  + exists 1; right; intros n Hn.\n    replace n with (1+(n-1)) at 2 by lia. \n    generalize (n-1); intros a; clear n Hn.\n    simpl prefix.\n    generalize (N_TT (prefix a s)).\n    rewrite prefix_length; lia.\nQed.\n\nRecursive Extraction stream_choose.\n\nSection on_the_fly_update.\n\n  Variable f : pos3 * pos3 * pos3 -> pos3 * pos3 * pos3.\n\n  CoFixpoint otf_update s := \n    match s with lcons a (lcons b (lcons c s)) => \n      match f (a,b,c) with\n        | (x,y,z) =>  lcons x (otf_update (lcons y (lcons z s)))\n      end\n    end.\n\nEnd on_the_fly_update.\n\nRecursive Extraction otf_update.\n\n\n\n\n\n\n", "meta": {"author": "DmxLarchey", "repo": "PC19", "sha": "0481befc4f7b57679000a0d6ae29940532f55026", "save_path": "github-repos/coq/DmxLarchey-PC19", "path": "github-repos/coq/DmxLarchey-PC19/PC19-0481befc4f7b57679000a0d6ae29940532f55026/co_ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7093646870520258}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus Zero (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj257_coqofml_NTIuS8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7093646829631665}}
{"text": "Require Import HoTT.\nFrom GR.groupoid.grpd_bicategory Require Import\n     grpd_bicategory.\n\n(** ** Some equational theory for groupoids *)\n(** [e⁻¹ = e] *)\nDefinition inv_e\n           {G : groupoid}\n           (a : G)\n  : inv (e a) = e a\n  := (grpd_left_identity (inv (e a)))^ @ grpd_right_inverse (e a).\n\n(** [(g⁻¹)⁻¹ = g] *)\nDefinition inv_involutive\n           {G : groupoid}\n           {a₁ a₂ : G}\n           (g : G a₁ a₂)\n  : inv (inv g) = g.\nProof.\n  refine ((grpd_right_identity (inv (inv g)))^ @ _).\n  refine (ap (fun p => _ ● p) (grpd_left_inverse g)^ @ _).\n  refine (grpd_right_assoc _ _ _ @ _).\n  refine (ap (fun p => p ● _) (grpd_left_inverse _) @ _).\n  apply grpd_left_identity.\nDefined.\n\n(** [(g h)⁻¹ = h⁻¹ g ⁻¹] *)\nDefinition inv_prod\n           {G : groupoid}\n           {a₁ a₂ a₃ : G}\n           (g₁ : G a₁ a₂)\n           (g₂ : G a₂ a₃)\n  : inv (g₁ ● g₂) = inv g₂ ● inv g₁.\nProof.\n  refine (_ @ (grpd_right_identity (inv g₂ ● inv g₁))).\n  refine (_ @ ap (fun p => _ ● p) (grpd_right_inverse (g₁ ● g₂))).\n  refine (_ @ grpd_left_assoc _ _ _).\n  refine (_ @ ap (fun p => p ● _) (grpd_right_assoc (inv g₂ ● inv g₁) g₁ g₂)^).\n  refine (_ @ ap (fun p => (p ● _) ● _) (grpd_right_assoc (inv g₂) (inv g₁) g₁)).\n  refine (_ @ (ap (fun p => ((_ ● p) ● _) ● _) (grpd_left_inverse _))^).\n  refine (_ @ (ap (fun p => (p ● _) ● _) (grpd_right_identity _))^).\n  refine (_ @ (ap (fun p => p ● _) (grpd_left_inverse _))^).\n  exact (grpd_left_identity _)^.\nDefined.", "meta": {"author": "nmvdw", "repo": "groupoids", "sha": "dd54321b2589c7cf31f379bd63b4a86cf9052792", "save_path": "github-repos/coq/nmvdw-groupoids", "path": "github-repos/coq/nmvdw-groupoids/groupoids-dd54321b2589c7cf31f379bd63b4a86cf9052792/groupoid/grpd_bicategory/grpd_laws.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.7092712201794933}}
{"text": "(***************************************************************************************)\n(**                                 Diagonalization.v                                 **)\n(**                                                                                   **)\n(** Defining and proving facts about Hermitian and diagonalizable matrices, including **)\n(** on the exponentiation of diagonalizable matrices.                                 **)\n(**                                                                                   **)\n(***************************************************************************************)\n\n(* \n*)\nRequire Import Reals.\nRequire Import QWIRE.Matrix.\nRequire Import MatrixExponential.\nRequire Import Init.Tauto.\n\n(**********************************)\n(** Linear Algebraic Definitions **)\n(**********************************)\n\n(* Element-wise definition of Hermitian *)\nDefinition Herm {n : nat} (A : Square n) : Prop :=\n  forall i j, (A i j) = Cconj (A j i).\n\n(* Adjoint definition of Hermitian *)\nDefinition Herm_alternate {n : nat} (A : Square n) :=\n  A = A †.\n\n(* D is a diagonal matrix if the following conditions are met *)\nDefinition Diagonal {n : nat} (D : Square n) :=\n  forall i j, i <> j ->  D i j = 0.\n\n(* Tinv × D × T is a diagonalization of M if the following conditions are met *)\nDefinition Diagonalization {n : nat} (Tinv D T M : Square n) : Prop :=\n  Diagonal D /\\ Minv T Tinv /\\ M = Tinv × D × T /\\\n  WF_Matrix Tinv /\\ WF_Matrix D /\\ WF_Matrix T. \n\nDefinition Diagonalizable {n : nat} (A : Square n) :=\n  exists (Tinv D T : Square n),\n    Diagonalization Tinv D T A.\n\n(* Element-wise exponentiation of a diagonal matrix *)\nDefinition exp_diag {n : nat} (D : Square n) :=\n  (fun i j => if (i <? n) && (i =? j) then exp (fst (D i j)) else 0).\n\n(* Exponentiation of a diagonalizable matrix *)\nDefinition is_exp_diag {n : nat} (M M_exp : Square n) : Prop :=\n  exists (Tinv D T : Square n),\n    Diagonalization Tinv D T M /\\ Diagonalization Tinv (exp_diag D) T M_exp.\n\n(* Two matrices are simultaneously diagonalizable if the following conditions are met *)\nDefinition Sim_diag {n : nat} (A B : Square n) :=\n  exists (T Tinv M1 M2 : Square n),\n    Diagonalization Tinv A T M1 /\\ Diagonalization Tinv B T M2.\n\n(* Definition of matrix commutation *)\nDefinition Mat_commute {n : nat} (A B : Square n) :=\n  A × B = B × A.\n\n\n\n(************************************************)\n(** Lemmas on properties of Hermitian matrices **)\n(************************************************)\n\n(* Element-wise and matrix definitions of Hermitian are equivalent *)\nLemma herm_defs_equivalent {n : nat} (A : Square n) :\n  WF_Matrix A -> Herm A <-> Herm_alternate A.\nProof.\n  intros HWF. split; intros H; unfold Herm, Herm_alternate in *.\n  - apply mat_equiv_eq; auto.\n    + apply WF_adjoint; auto.\n    + intros i j Hi Hj.\n      unfold adjoint. apply H.\n  - intros i j. unfold adjoint in H.\n    remember (equal_f (equal_f H i) j) as E. clear HeqE.\n    rewrite E. reflexivity.\nQed.\n\n(* Helper lemma for herm_diag_real *)\nLemma real_neg_neq : forall (x : R), x <> 0 -> x <> Ropp x.\nProof.\n  intros. intros H1.\n  destruct (Rlt_dec x 0).\n  - assert (H2 : Ropp x > 0). {\n      apply Ropp_gt_lt_0_contravar in r. assumption. }\n    rewrite <- H1 in H2.\n    apply Rlt_le in r. apply Rle_not_gt in r. contradiction.\n  - apply Rnot_lt_ge in n. apply Rge_le in n.\n    assert (H2 : 0 >= Ropp x). {\n      apply Ropp_0_le_ge_contravar in n. assumption. }\n    assert (H3 : 0 < x). {\n      inversion n. assumption. symmetry in H0. contradiction. }\n    rewrite <- H1 in H2. apply Rge_not_lt in H2.\n    contradiction.\nQed.\n\n(* Hermitian matrices have real elements on the main diagonal *)\nLemma herm_diag_real {n : nat} (A : Square n) :\n  forall (i : nat) (x : C), Herm A -> (i < n)%nat -> A i i = x -> snd x = 0.\nProof.\n  intros. unfold Herm in H. unfold Cconj in H.\n  remember (H i i) as H2.\n  clear HeqH2. rewrite surjective_pairing in H1.\n  rewrite H1 in H2. inversion H2.\n  destruct (Req_dec (snd x) 0).\n  - assumption.\n  - apply real_neg_neq in H3. contradiction.\nQed.\n\n(* Zero matrix is Hermitian *)\nLemma herm_Zero {n : nat} : Herm (@Zero n n).\nProof.\n  intros i j. unfold Cconj. unfold Zero. simpl.\n  rewrite Ropp_0. reflexivity.\nQed.\n\n(* Identity matrix is Hermitian *)\nLemma herm_I {n : nat} : Herm (I n).\nProof.\n  unfold Herm. unfold Cconj. unfold I.\n  intros i j. rewrite <- (Nat.eqb_sym i j).\n  destruct (i =? j) eqn:E.\n  - assert (Hij : i = j). apply Nat.eqb_eq. assumption. subst.\n    destruct (j <? n); simpl; rewrite Ropp_0; reflexivity.\n  - simpl. rewrite Ropp_0; reflexivity.\nQed.\n\n(* Real scalar times Hermitian matrix is Hermitian *)\nLemma herm_scale {n : nat} : forall (M : Square n) (r : R),\n    Herm M -> Herm (r .* M).\nProof.\n  intros M r H. unfold \".*\". unfold Herm in *.\n  intros i j. rewrite Cconj_mult_distr.\n  rewrite <- H. rewrite Cconj_R.\n  reflexivity.\nQed.\n\n(* Sum of Hermitian matrices is Hermitian *)\nLemma herm_plus {n : nat} : forall (A B : Square n), Herm A -> Herm B -> Herm (A .+ B).\nProof.\n  intros. unfold Herm in *. intros i j.\n  unfold \".+\". rewrite Cconj_plus_distr.\n  rewrite <- H. rewrite <- H0. reflexivity.\nQed.\n\n(* Product of Hermitian matrices is Hermitian if they commute *)\n(* The converse of this is also true *)\nLemma herm_mult {n : nat} : forall (A B : Square n),\n    WF_Matrix A -> WF_Matrix B ->\n    Herm A -> Herm B ->\n    Mat_commute A B ->\n    Herm (A × B).\nProof.\n  intros A B WFA WFB HA HB Hcomm. rewrite herm_defs_equivalent.\n  - unfold Herm_alternate. rewrite Mmult_adjoint.\n    rewrite herm_defs_equivalent in HA, HB; auto.\n    rewrite <- HA. rewrite <- HB. apply Hcomm.\n  - apply WF_mult; auto.\nQed.\n\n(* Kronecker product of Hermitian matrices is Hermitian *)\nLemma herm_kron {n m : nat} : forall (A : Square n) (B : Square m),\n    Herm A -> Herm B -> Herm (A ⊗ B).\nProof.\n  intros A B HA HB.\n  unfold Herm in *. intros i j.\n  unfold kron. rewrite Cconj_mult_distr.\n  rewrite <- (HA (i / m)%nat (j / m)%nat).\n  rewrite <- (HB (i mod m)%nat (j mod m)%nat).\n  reflexivity.\nQed.\n\n(* Kronecker product of many Hermitian matrices is Hermitian *)\nLemma herm_big_kron {n : nat} : forall (L : list (Square n)),\n    Forall Herm L -> Herm (⨂ L).\nProof.\n  intros L H.\n  induction L as [|A L'].\n  - apply herm_I.\n  - simpl. apply herm_kron.\n    + apply Forall_inv in H. assumption.\n    + apply IHL'. apply Forall_inv_tail with A. assumption.\nQed.\n\n(* Hermitian matrices are diagonalizable *)\n(* Tricky proof because it involves eigenvalues and eigenvectors; ran out of time to \n   support these *)\nTheorem herm_diagonalizable {n : nat} (A : Square n) :\n  Herm A -> Diagonalizable A.\nProof.\nAdmitted.\n\n\n\n(*******************************************)\n(** Lemmas on diagonalization of matrices **)\n(*******************************************)\n\n(* Scalar times diagonal matrix is diagonal *)\nLemma diagonal_scale {n : nat} : forall (M : Square n) (c : C),\n    Diagonal M -> Diagonal (c .* M).\nProof. \n  intros. unfold Diagonal in *. intros i j Hij.\n  unfold \".*\". assert (H1 : M i j = 0). apply H. apply Hij.\n  rewrite H1. apply Cmult_0_r.\nQed.\n\n(* Scalar times diagonalizable matrix is diagonalizable *)\nLemma diag_scale {n : nat} : forall (M : Square n) (c : C),\n    Diagonalizable M -> Diagonalizable (c .* M).\nProof.\n  intros. unfold Diagonalizable in *.\n  destruct H as [Tinv [D [T [H1 [H2 [H3 [H4 [H5 H6]]]]]]]].\n  exists Tinv, (c .* D), T. unfold Diagonalization.\n  repeat (split; try tauto).\n  - apply diagonal_scale. auto.\n  - rewrite Mscale_mult_dist_r. rewrite Mscale_mult_dist_l.\n    rewrite <- H3. reflexivity.\n  - apply WF_scale. auto.\nQed.\n\n(* Commuting diagonalizable matrices are simultaneously diagonalizable *)\n(* This proof is currently not needed so we have not attempted to prove it; however, we \n   expect to need it in the future *)\nTheorem Commute_sim_diag {n : nat} :\n  forall (A B : Square n),\n  Mat_commute A B ->\n  Diagonalizable A ->\n  Diagonalizable B ->\n  (* We might need the explicit diagonalizations for the proof :\n  forall TAinv TBinv DA DB TA TB\n  Diagonalization TAinv DA TA A ->\n  Diagonalization TBinv DB TB B ->\n  *)\n  Sim_diag A B.\nProof.\n  (* This is gonna be tricky *)\n  Admitted.\n\n(* If a matrix M is diagonalizable as M = T^t * D * T, then e^M = T^t * e^D * T *)\n(* This fact is true, but difficult to show because matrix_exponential is defined in terms \n   of an infinite sum. This theorem was crucial however in simplifying many other proofs\n   involving matrix exponentials *)\nTheorem exp_diag_correct {n : nat} (M M_exp : Square n) :\n    Diagonalizable M -> matrix_exponential M M_exp <-> is_exp_diag M M_exp.\nProof. Admitted.\n(* We only really need to show the -> direction *)\n\n(* e^D for diagonal matrix D is well-formed *)\nLemma exp_diag_preserves_WF {n : nat} :\n  forall (D : Square n), WF_Matrix D -> Diagonal D -> @WF_Matrix n n (exp_diag D).\nProof.\n  intros D HWF HD i j H. unfold exp_diag.\n  destruct (i =? j) eqn:E.\n  - apply beq_nat_true in E. subst. destruct (j <? n) eqn:F.\n    + exfalso. apply Nat.ltb_lt in F. lia.\n    + auto.\n  - rewrite andb_false_r. auto.\nQed.\n\n(* e^D for diagonal matrix D is diagonal *)\nLemma exp_diag_preserves_diag {n : nat} :\n  forall (D : Square n), Diagonal D -> @Diagonal n (exp_diag D).\nProof.\n  intros D H i j Hij. unfold exp_diag. apply eqb_neq in Hij.\n  rewrite Hij. rewrite andb_false_r. reflexivity.\nQed.\n\n(* 2 diagonalizations of the same matrix represent the same matrix *)\nLemma equivalent_diagonalizations {n : nat}:\n  forall (T1inv D1 T1 T2inv D2 T2 M : Square n),\n    Diagonalization T1inv D1 T1 M ->\n    Diagonalization T2inv D2 T2 M ->\n    T1inv × D1 × T1 = T2inv × D2 × T2.\nProof.\n  intros T1inv D1 T1 T2inv D2 T2 M Hd1 Hd2.\n  destruct Hd1 as [_ [_ [H1 _]]].\n  destruct Hd2 as [_ [_ [H2 _]]].\n  subst. auto.\nQed.\n\n(* T1inv × D1 × T1 = T2inv × D2 × T2 implies T1inv × e^D1 × T1 = T2inv × e^D2 × T2 *)\nLemma exp_diag_preserves_equality {n : nat} :\n  forall (T1inv D1 T1 T2inv D2 T2 M : Square n),\n    Diagonalization T1inv D1 T1 M -> Diagonalization T2inv D2 T2 M ->\n    T1inv × (exp_diag D1) × T1 = T2inv × (exp_diag D2) × T2.\nProof.\n  intros T1inv D1 T1 T2inv D2 T2 M H1 H2.\n  remember (equivalent_diagonalizations T1inv D1 T1 T2inv D2 T2 M H1 H2) as H. clear HeqH.\nAdmitted.\n\n\n\n(***********************************)\n(** Main diagonalization theorems **)\n(***********************************)\n\n(* For any diagonalizable matrix M, there is at least one matrix Mexp s.t. e^M = Mexp *)\nTheorem mat_exp_well_defined_diag {n : nat} : forall (M : Square n),\n    Diagonalizable M -> exists (Mexp : Square n), matrix_exponential M Mexp.\nProof.\n  intros M H. remember H as Hd. clear HeqHd.\n  unfold Diagonalizable in Hd.\n  destruct Hd as [Tinv [D [T [H1 [H2 [H3 [H4 [H5 H6]]]]]]]].\n  exists (Tinv × (exp_diag D) × T).\n  rewrite exp_diag_correct; auto.\n  unfold is_exp_diag.\n  exists Tinv. exists D. exists T. split.\n  - unfold Diagonalization; tauto.\n  - unfold Diagonalization. repeat (try split; try tauto).\n    + apply exp_diag_preserves_diag; auto.\n    + apply exp_diag_preserves_WF; auto.\nQed.\n\nCorollary mat_exp_well_defined_herm {n : nat} : forall (M : Square n),\n    Herm M -> exists (Mexp : Square n), matrix_exponential M Mexp.\nProof.\n  intros M H. apply mat_exp_well_defined_diag. apply herm_diagonalizable. auto.\nQed.\n\n(* For any diagonalizable matrix M, there is at most one matrix Mexp s.t. e^M = Mexp *)\nTheorem mat_exp_unique_diag {n : nat} : forall (M Mexp1 Mexp2 : Square n),\n    Diagonalizable M ->\n    matrix_exponential M Mexp1 ->\n    matrix_exponential M Mexp2 ->\n    Mexp1 = Mexp2.\nProof.\n  intros M Mexp1 Mexp2 Hdiag H1 H2.\n  rewrite (exp_diag_correct M Mexp1) in H1; auto.\n  destruct H1 as [T1inv [D1 [T1 [HD1 HeD1]]]].\n  rewrite (exp_diag_correct M Mexp2) in H2; auto.\n  destruct H2 as [T2inv [D2 [T2 [HD2 HeD2]]]].\n  assert (H : T1inv × D1 × T1 = T2inv × D2 × T2). {\n    apply equivalent_diagonalizations with M; assumption.\n  }\n  destruct HeD1 as [_ [_ [H2 [_ [_ _]]]]].\n  destruct HeD2 as [_ [_ [H3 [_ [_ _]]]]].\n  rewrite H2. rewrite H3.\n  apply exp_diag_preserves_equality with M; unfold Diagonalization in *; tauto.\nQed.\n\nCorollary mat_exp_unique_herm {n : nat} : forall (M Mexp1 Mexp2 : Square n) (c : C),\n    Herm M ->\n    matrix_exponential (c .* M) Mexp1 ->\n    matrix_exponential (c .* M) Mexp2 ->\n    Mexp1 = Mexp2.\nProof.\n  intros M Mexp1 Mexp2 c Hdiag H1 H2.\n  apply mat_exp_unique_diag with (c .* M); auto.\n  apply diag_scale. apply herm_diagonalizable. apply Hdiag.\nQed.\n\n(* For any diagonalizable matrix M, e^M is well-formed *)\nTheorem mat_exp_WF_diag {n : nat} : forall (M Mexp : Square n),\n    Diagonalizable M -> matrix_exponential M Mexp -> WF_Matrix M -> WF_Matrix Mexp.\nProof.\n  intros M Mexp Hherm HM H_WF.\n  rewrite (exp_diag_correct M Mexp) in HM.\n  - destruct HM as [Tinv [D [T [HD HeD]]]].\n    destruct HD as  [H1 [H2 [H3 [H4 [H5 H6]]]]].\n    destruct HeD as [H7 [H8 [H9 [H10 [H11 H12]]]]].\n    rewrite H9. apply WF_mult; auto.\n    apply WF_mult; auto.\n  - auto.\nQed.\n\nCorollary mat_exp_WF_herm {n : nat} : forall (M Mexp : Square n) (c : C),\n    Herm M -> matrix_exponential (c .* M) Mexp -> WF_Matrix M -> WF_Matrix Mexp.\nProof.\n  intros M Mexp c Hherm HM H_WF.\n  apply mat_exp_WF_diag with (c .* M); auto.\n  - apply diag_scale. apply herm_diagonalizable. auto.\n  - apply WF_scale. auto.\nQed.\n\n(* For any diagonalizable matrices M and N, if M and N commute then e^M × e^N = e^{M+N} *)\nTheorem mat_exp_commute_add_diag {n : nat} : forall (M N SM SN SMN : Square n),\n    Diagonalizable M ->\n    Diagonalizable N ->\n    matrix_exponential M SM ->\n    matrix_exponential N SN ->\n    matrix_exponential (M .+ N) SMN ->\n    Mat_commute M N ->\n    SM × SN = SMN.\nProof. Admitted.\n  (* This theorem statement is mathematically true, but it is currently not provable using \n     the lemmas we have so far, because Diagonalizable (M + N) is not true in general.\n  \n  intros M N SM SN SMN HM HN HSM HSN HSMN Hcomm.\n  rewrite (exp_diag_correct M SM) in HSM; auto.\n  rewrite (exp_diag_correct N SN) in HSN; auto.\n  rewrite (exp_diag_correct (M .+ N) SMN) in HSMN. try (apply diag_plus; auto).  \n  destruct HSM as [TMinv [DM [TM [HDM [HeDM [_ [_ _]]]]]]].\n  destruct HSN as [TNinv [DN [TN [HDN [HeDN [_ [_ _]]]]]]].\n  destruct HSMN as [TMNinv [DMN [TMN [HDMN [HeDMN [_ [_ _]]]]]]].\n  Admitted.\n*)\n\n", "meta": {"author": "ethanlee515", "repo": "Hamiltonian-simulation-formalization", "sha": "29caa0b1aa72a3425eccd9289659a44346703afa", "save_path": "github-repos/coq/ethanlee515-Hamiltonian-simulation-formalization", "path": "github-repos/coq/ethanlee515-Hamiltonian-simulation-formalization/Hamiltonian-simulation-formalization-29caa0b1aa72a3425eccd9289659a44346703afa/src/Diagonalization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7092365000242009}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import Recdef.\nRequire Import List.\nRequire Import Program.Tactics.\nImport ListNotations.\n\nSection Lecture6.\n\n  (* True iff the list’s elements are in decreasing order *)\n  Inductive Dec : list nat -> Prop :=\n  | DNil : Dec []\n  | DCons : forall a l,\n      (forall b, In b l -> a <= b) ->\n      Dec l ->\n      Dec (a :: l).\n  Hint Constructors Dec.\n\n  (* True iff the list’s elements are in INcreasing order *)\n  Inductive Inc : list nat -> Prop :=\n  | INil : Inc []\n  | ICons : forall a l,\n      (forall b, In b l -> b <= a) ->\n      Inc l ->\n      Inc (a :: l).\n  Hint Constructors Inc.\n\n  (* A fact about appending increasing lists *)\n  Lemma Inc_app xs ys:\n    Inc xs -> Inc ys ->\n    (forall x y, In x xs -> In y ys -> y <= x) ->\n    Inc (xs ++ ys).\n  Admitted.\n\n\n  Lemma Dec_rev xs: Dec (rev xs) -> Inc xs.\n  Abort.\n\nEnd Lecture6.\n", "meta": {"author": "readablesystems", "repo": "cs260r-17", "sha": "6275e4e7007b7a6af6f1031e80994a3043521256", "save_path": "github-repos/coq/readablesystems-cs260r-17", "path": "github-repos/coq/readablesystems-cs260r-17/cs260r-17-6275e4e7007b7a6af6f1031e80994a3043521256/l06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.7091386914520936}}
{"text": "(** * Reasoning About Distributions *)\n\nRequire Export Intervals.\n\nInductive dist T:Type : Type :=\n  | Unit : T -> dist T\n  | Combine : forall (p:R), 0 < p < 1 -> dist T -> dist T -> dist T.\n\nArguments Unit {T} _.\nArguments Combine {T} p v d1 d2.\n\nNotation \"~ X\" := (fun t => negb (X t)). \nNotation \"X1 && X2 \" := (fun t => andb (X1 t) (X2 t)).\nNotation \"X1 || X2 \" := (fun t => orb (X1 t) (X2 t)).\n\nFixpoint probability {T:Type} (d:dist T) (X: T -> bool): R :=\n  match d with\n  | Unit t => if X t then 1 else 0\n  | Combine p v d1 d2 =>\n    p * (probability d1 X) + (1-p) * (probability d2 X)\n  end.\n\nNotation \"'Pr' X 'in' d\"  := (probability d X) (at level 40).\n\n(** ** Basic Theorems of Probability Theory *)\n\n(** Lemma 2.4: Normality *)\nTheorem pr_normality : forall {T:Type} (d : dist T) X,\n  0 <= Pr X in d <= 1.\nProof.\n  intros.\n  induction d as [t |].\n  + simpl.\n    destruct (X t); lra.\n  + simpl.\n    apply in_0_1_closed. assumption.\n    apply IHd1.\n    apply IHd2.\nQed.\n\n(** Lemma 2.5: Tautology *)\nLemma pr_tautology : forall {T:Type} (d : dist T) X,\n  (forall t, X t = true) ->\n  Pr X in d = 1.\nProof.\n  intros.\n  induction d as [t |].\n  + simpl.\n    rewrite H.\n    reflexivity.\n  + simpl in *.\n    rewrite IHd1, IHd2.\n    lra.\nQed.\n\n(** Lemma 2.6: Contradiction *)\nLemma pr_contradiction : forall {T:Type} (d : dist T) X,\n  (forall t, X t = false) ->\n  Pr X in d = 0.\nProof.\n  intros.\n  induction d as [t |].\n  + simpl.\n    rewrite H.\n    reflexivity.\n  + simpl in *.\n    rewrite IHd1, IHd2.\n    lra.\nQed.\n\n(** Lemma 2.7 Equivalence *)\nLemma pr_equivalence: forall {T:Type} (d : dist T) X X',\n  (forall t, X t = X' t) ->\n  Pr X in d = Pr X' in d.\nProof. \n  intros.\n  induction d.\n  simpl.\n  rewrite H.\n  reflexivity.\n  simpl.\n  rewrite IHd1, IHd2.\n  reflexivity.\nQed.\n\nLemma pr_totality : forall {T:Type} (d : dist T) X, \n  probability d X + probability d (~X) = 1.\nProof.\n  intros.\n  induction d.\n  + simpl. \n    destruct (X t); simpl; lra.\n  + simpl in *.\n    rewrite <- Rplus_assoc.\n    rewrite Rplus_assoc with (r1 := p * (Pr X in d1)) \n                             (r2 := (1 - p) * (Pr X in d2)) \n                             (r3 := p * (Pr ~X in d1)).\n    rewrite Rplus_comm with (r1 := (1 - p) * (Pr X in d2)) \n                            (r2 := p * (Pr ~X in d1)).\n    rewrite <- Rplus_assoc.\n    rewrite Rplus_assoc.\n    rewrite <- Rmult_plus_distr_l.\n    rewrite <- Rmult_plus_distr_l.\n    rewrite IHd1.\n    rewrite IHd2.\n    lra.\nQed.\n\n(** Lemma 2.8: Complement *)\nLemma pr_complement : forall {T:Type} (d : dist T) X, \n  Pr (~X) in d = 1 - Pr X in d.\nProof.\n  intros.\n  specialize (pr_totality d X). intros Eq.\n  lra.\nQed.\n\n(** Lemma 2.9: Disjunction *)\nLemma pr_disjunction : forall {T:Type} (d : dist T) X1 X2, \n  Pr (X1 || X2) in d = Pr X1 in d + Pr X2 in d - Pr (X1 && X2) in d.\nProof.\n  induction d; intros.\n  + simpl in *.\n    destruct (X1 t), (X2 t); simpl; lra. \n  + simpl in *.\n    rewrite IHd1; trivial.\n    rewrite IHd2; trivial.\n    lra.\nQed.  \n\nLemma pr_addition : forall {T:Type} (d : dist T) X1 X2, \n  (forall t, (X1 && X2) t = false) ->\n  Pr (X1 || X2) in d = Pr X1 in d + Pr X2 in d.\nProof.\n  intros.\n  rewrite <- Rminus_0_r. \n  replace 0 with (Pr (X1 && X2) in d).\n  Focus 2.  apply pr_contradiction. assumption.\n  apply pr_disjunction.\nQed.\n\n(** ** Rules for Bounding Probabilities *)\n\nLemma pr_union_bound : forall {T:Type} (d : dist T) X1 X2, \n  Pr (X1 || X2) in d <= Pr X1 in d + Pr X2 in d.\nProof.\n  intros.\n  specialize (pr_disjunction d X1 X2); intros.\n  specialize (pr_normality d (X1 && X2)); intros.\n  lra.\nQed.\n\nLemma pr_weaken : forall {T:Type} (d : dist T) X X', \n  (forall t, X t = true -> X' t = true) ->\n  Pr X in d <= Pr X' in d.  \nProof.\n  intros.\n  induction d.\n  + simpl.\n    specialize (H t).\n    destruct (X t), (X' t); try lra.\n    assert (false=true) as contra by (apply H; reflexivity).\n    inversion contra.\n  + simpl.\n    apply Rmult_le_compat_l with (r:=p) in IHd1; try lra.\n    apply Rmult_le_compat_l with (r:=(1-p)) in IHd2; lra.\nQed.    \n\nLemma pr_strengthen : forall {T:Type} (d : dist T) X X', \n  (forall t, X' t = true -> X t = true) ->\n  Pr X in d >= Pr X' in d.  \nProof.\n  intros.\n  induction d.\n  + simpl.\n    specialize (H t).\n    destruct (X t), (X' t); try lra.\n    assert (false=true) as contra by (apply H; reflexivity).\n    inversion contra.\n  + simpl.\n    apply Rmult_ge_compat_l with (r:=p) in IHd1; try lra.\n    apply Rmult_ge_compat_l with (r:=(1-p)) in IHd2; lra.\nQed.   \n\nLemma pr_disj_ge_l : forall {T:Type} (d : dist T) X1 X2,\n  Pr (X1 || X2) in d >= Pr X1 in d.\nProof.\n  intros; simpl.\n  apply pr_strengthen.\n  simpl; intros.\n  destruct (X1 t), (X2 t); trivial; inversion H.\nQed.\n\nLemma pr_disj_ge_r : forall {T:Type} (d : dist T) X1 X2,\n  Pr (X1 || X2) in d >= Pr X2 in d.\nProof.\n  intros; simpl.\n  apply pr_strengthen.\n  simpl; intros.\n  destruct (X1 t), (X2 t); trivial; inversion H.\nQed.\n\n\nLemma pr_conj_le_l : forall {T:Type} (d : dist T) X1 X2,\n  Pr (X1 && X2) in d <= Pr X1 in d.\nProof.\n  intros; simpl.\n  apply pr_weaken.\n  simpl; intros.\n  destruct (X1 t), (X2 t); trivial; inversion H.\nQed.\n\nLemma pr_conj_le_r : forall {T:Type} (d : dist T) X1 X2,\n  Pr (X1 && X2) in d <= Pr X2 in d.\nProof.\n  intros; simpl.\n  apply pr_weaken.\n  simpl; intros.\n  destruct (X1 t), (X2 t); trivial; inversion H.\nQed.\n\nLemma pr_ge_bound : forall {T:Type} (d : dist T) X1 X2 p1 p2,\n  (forall t, (X1 && X2) t = false) ->\n  Pr X1 in d >= p1 ->\n  Pr X2 in d >= p2 ->\n  p1 + p2 = 1 ->\n  Pr X1 in d = p1 /\\ Pr X2 in d = p2.\nProof. \n  intros.\n  specialize (pr_addition d X1 X2 H); intros.\n  assert (Pr (X1 || X2) in d >= p1 + p2) by lra.\n  specialize (pr_normality d (X1 || X2)). intros.\n  lra.\nQed.\n\n(** *** The base states are deterministic *)\n\nTheorem pr_unit : forall {T:Type} (t:T) X,\n  Pr X in (Unit t) = 0 \\/ Pr X in (Unit t) = 1.\nProof.\n  intros.\n  simpl.\n  destruct (X t); lra.\nQed.\n\n(** *** Combining and Splitting Distributions *)\n\n(** Lemma 2.10: Combine *)\nLemma pr_combine : forall {T:Type} (d1 d2 : dist T) X p v r,\n  Pr X in d1 = r -> \n  Pr X in d2 = r ->\n  Pr X in Combine p v d1 d2 = r.\nProof.\n  intros.\n  simpl in *.\n  rewrite H, H0.\n  lra.\nQed.\n\n(** Lemma 2.11: Split (0) *)\nLemma pr_split_0 : forall {T:Type} (d1 d2 : dist T) X p v,\n  Pr X in Combine p v d1 d2 = 0 ->\n  Pr X in d1 = 0 /\\ Pr X in d2 = 0.  \nProof.\n  intros.\n  apply sum_to_0 with (p:=p); trivial; try apply pr_normality.\nQed.  \n\n(** Lemma 2.11: Split (1) *)\nLemma pr_split_1 : forall {T:Type} (d1 d2 : dist T) X p v,\n  Pr X in Combine p v d1 d2 = 1 ->\n  Pr X in d1 = 1 /\\ Pr X in d2 = 1.  \nProof.\n  intros.\n  apply sum_to_1 with (p:=p); trivial; try apply pr_normality.\nQed.  \n\n\n(** *** Useful Rules for Zero and One *)\n\nLemma pr_complement_1 : forall {T:Type} (d : dist T) X, \n  Pr X in d = 1 <-> Pr (~X) in d = 0.\nProof. intros. rewrite pr_complement. lra. Qed.\n\nLemma pr_complement_0 : forall {T:Type} (d : dist T) X, \n  Pr X in d = 0 <-> Pr (~X) in d = 1.\nProof. intros. rewrite pr_complement. lra. Qed.\n\nLemma pr_weaken_1: forall {T:Type} (d : dist T) X X',\n  (forall t, X t = true -> X' t = true) ->\n  Pr X in d = 1 ->\n  Pr X' in d = 1.  \nProof.\n  intros.\n  induction d. \n  + simpl in *.\n    destruct (X t) eqn:Eqx, (X' t) eqn:Eqx'; trivial.\n    apply H in Eqx. rewrite Eqx in Eqx'. inversion Eqx'. \n  + apply pr_split_1 in H0 as (H1 & H2).\n    simpl. rewrite IHd1, IHd2; trivial. lra.\nQed.\n\nLemma pr_strengthen_0: forall {T:Type} (d : dist T) X X',\n  (forall t, X' t = true -> X t = true) ->\n  Pr X in d = 0 ->\n  Pr X' in d = 0.  \nProof.\n  intros.\n  induction d. \n  + simpl in *.\n    destruct (X t) eqn:Eqx, (X' t) eqn:Eqx'; trivial.\n    apply H in Eqx'. rewrite Eqx in Eqx'. inversion Eqx'. \n  + apply pr_split_0 in H0 as (H1 & H2).\n    simpl. rewrite IHd1, IHd2; trivial. lra.\nQed.\n\nLemma pr_conj_0_l : forall {T:Type} (d : dist T) X1 X2, \n  Pr X1 in d = 0 -> Pr (X1 && X2) in d = 0. \nProof.\n  intros.\n  specialize (pr_conj_le_l d X1 X2).\n  specialize (pr_normality d (X1 && X2)).\n  intros.\n  lra.\nQed.\n\nLemma pr_conj_0_r : forall {T:Type} (d : dist T) X1 X2, \n  Pr X2 in d = 0 -> Pr (X1 && X2) in d = 0. \nProof.\n  intros.\n  specialize (pr_conj_le_r d X1 X2).\n  specialize (pr_normality d (X1 && X2)).\n  intros.\n  lra.\nQed.\n\nLemma pr_conj_1_l : forall {T:Type} (d : dist T) X1 X2, \n  Pr X1 in d = 1 -> Pr (X1 && X2) in d = Pr X2 in d. \nProof.\n  intros.\n  induction d.\n  + simpl in *.\n    destruct (X1 t), (X2 t); trivial; lra. \n  + simpl.\n    simpl in H.\n    apply sum_to_1 in H; trivial; try apply pr_normality. \n    destruct H.\n    rewrite IHd1, IHd2; trivial.\nQed.\n\nLemma pr_conj_1_r : forall {T:Type} (d : dist T) X1 X2, \n  Pr X2 in d = 1 -> Pr (X1 && X2) in d = Pr X1 in d. \nProof.\n  intros.\n  rewrite pr_equivalence with (X' := (X2 && X1)).\n  apply pr_conj_1_l. assumption.\n  intros.\n  destruct (X1 t), (X2 t); reflexivity.\nQed.\n\nLemma pr_conj_1 : forall {T:Type} (d : dist T) X1 X2, \n  Pr X1 in d = 1 -> \n  Pr X2 in d = 1 ->\n  Pr (X1 && X2) in d = 1. \nProof.\n  intros.\n  rewrite <- H.\n  apply pr_conj_1_r.\n  assumption.\nQed.\n\n\n\n\n\n", "meta": {"author": "rnrand", "repo": "VPHL", "sha": "db939e605c2ed5ac9693558b3ad3b79d49edf26a", "save_path": "github-repos/coq/rnrand-VPHL", "path": "github-repos/coq/rnrand-VPHL/VPHL-db939e605c2ed5ac9693558b3ad3b79d49edf26a/Distributions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7091270024427774}}
{"text": "Require Import List NArith.\nImport N.\n\nLocal Open Scope list_scope.\nLocal Open Scope N_scope.\n\n\nModule BV.\n\n  Definition t := (list bool * N)%type.\n\n  Definition empty : t := (nil, 0).\n\n  Definition concat (b1 b2 : t) : t :=\n    let (b1, n1) := b1 in\n    let (b2, n2) := b2 in\n    (b1 ++ b2, n1 + n2).\n\n  Definition bvnot (bv1 : t) : t :=\n    let (b1, n1) := bv1 in\n    (List.map negb b1, n1).\n\n  (* how to ensure they have same N? *)\n  Fixpoint bl_map2 (l1 : list bool) (l2 : list bool)\n                   (f : bool -> bool -> bool) : list bool :=\n    match l1 with\n      | nil => nil\n      | cons b1 tl1 =>\n        match l2 with\n          | nil => nil\n          | cons b2 tl2 => cons (f b1 b2) (bl_map2 tl1 tl2 f)\n        end\n    end.\n\n  Definition bvand (bv1 : t) (bv2 : t) : t :=\n    let (b1, n1) := bv1 in\n    let (b2, n2) := bv2 in\n    (bl_map2 b1 b2 andb, n1).\n\n  Definition bvor (bv1 : t) (bv2 : t) : t :=\n    let (b1, n1) := bv1 in\n    let (b2, n2) := bv2 in\n    (bl_map2 b1 b2 orb, n1).\n\n  Definition bvxor (bv1 : t) (bv2 : t) : t :=\n    let (b1, n1) := bv1 in\n    let (b2, n2) := bv2 in\n    (bl_map2 b1 b2 xorb, n1).\n\n  Definition bvlow (bv1 : t) : bool :=\n    let (b1, n1) := bv1 in\n    match b1 with\n      | nil => false\n      | x :: _ => x\n    end.\n\n  Definition bvhigh (bv1 : t) : bool :=\n    let (b1, n1) := bv1 in\n    (List.last b1 false).\n\n  Definition bvshiftleft (bv1 : t) : t :=\n    let (b1, n1) := bv1 in\n    (cons false (List.removelast b1), n1).\n\n  Definition bvshiftright (bv1 : t) : t :=\n    let (b1, n1) := bv1 in\n    ((List.tl b1) ++ (cons false nil), n1).\n\n  Fixpoint bvshiftleft_n (bv1 : t) (n1 : nat) : t :=\n    match n1 with\n      | O => bv1\n      | S n2 => bvshiftleft_n (bvshiftleft bv1) n2\n    end.\n\n  Fixpoint bvshiftright_n (bv1 : t) (n1 : nat) : t :=\n    match n1 with\n      | O => bv1\n      | S n2 => bvshiftright_n (bvshiftright bv1) n2\n    end.\n\n  Fixpoint bl2n (l : list bool) (c : N) (c2 : N) : N :=\n    match l with\n      | nil => c\n      | cons true l2 => bl2n l2 (c + c2) (c2 + c2)\n      | cons false l2 => bl2n l2 c (c2 + c2)\n    end.\n\n  Definition bv2n (bv1 : t) : N :=\n    let (b1, n1) := bv1 in\n    (bl2n b1 0 1).\n\n  Fixpoint nb2bl (n : positive) : list bool :=\n    match n with\n      | xO p => false :: nb2bl p\n      | xI p => true :: nb2bl p\n      | xH => true :: nil\n    end.\n\n  Definition n2bl (n : N) : list bool :=\n    match n with\n      | 0 => cons false nil\n      | 1 => cons true nil\n      | pos p => nb2bl p\n    end.\n\n  Definition bvadd (bv1 : t) (bv2 : t) : t :=\n    let (b1, n1) := bv1 in\n    let (b2, n2) := bv2 in\n    let n3 := (bv2n bv1) in\n    let n4 := (bv2n bv2) in\n    let n5 := (n3 + n4) in\n    let b3 := (n2bl n5) in\n    (b3, n1).\n\n  Definition bvsub (bv1 : t) (bv2 : t) : t :=\n    let (b1, n1) := bv1 in\n    let (b2, n2) := bv2 in\n    let n3 := (bv2n bv1) in\n    let n4 := (bv2n bv2) in\n    let n5 := (n3 - n4) in\n    let b3 := (n2bl n5) in\n    (b3, n1).\n\n  Definition bvmul (bv1 : t) (bv2 : t) : t :=\n    let (b1, n1) := bv1 in\n    let (b2, n2) := bv2 in\n    let n3 := (bv2n bv1) in\n    let n4 := (bv2n bv2) in\n    let n5 := (n3 * n4) in\n    let b3 := (n2bl n5) in\n    (b3, n1).\n\n  Definition bvneg (bv1 : t) (n : N) : t :=\n    let (b1, n1) := bv1 in\n    let n2 := 2 ^ n in\n    let n3 := (bv2n bv1) in\n    let n4 := n2 - n3 in\n    ((n2bl n4), n).\n\n  Definition bvudiv (bv1 : t) (bv2 : t) : t :=\n    let (b1, n1) := bv1 in\n    let (b2, n2) := bv2 in\n    let n4 := (bv2n bv2) in\n    match n4 with\n      | 0 => (nil, 0)\n      | _ =>\n      let n3 := (bv2n bv1) in\n      ((n2bl (n3 / n4)), n1)\n    end.\n\n  Definition bvurem (bv1 : t) (bv2 : t) : t :=\n    let (b1, n1) := bv1 in\n    let (b2, n2) := bv2 in\n    let n4 := (bv2n bv2) in\n    match n4 with\n      | 0 => (nil, 0)\n      | _ =>\n      let n3 := (bv2n bv1) in\n      ((n2bl (n3 mod n4)), n1)\n    end.\n\n  Definition bvult (bv1 : t) (bv2 : t) :=\n    let n1 := (bv2n bv1) in\n    let n2 := (bv2n bv2) in\n    (n1 < n2).\n\n  Fixpoint drop_n (l : list bool) (n : nat) : list bool :=\n    match n with\n      | O => l\n      | S n2 => drop_n (@List.tl bool l) n2\n    end.\n\n  Fixpoint first_n (l : list bool) (n : nat) : list bool :=\n    match n with\n      | O => nil\n      | S n2 =>\n      match l with\n        | nil => nil\n        | x :: l2 => x :: (first_n l2 n2)\n      end\n    end.\n\n  Definition extract (l : list bool) (i : nat) (j : nat) : list bool :=\n    let l2 := drop_n l i in\n    (first_n l2 j).\n\n  (* Check nth. *)\n  Definition bb_nth (i : nat) (bv1 : t) : bool :=\n    let (b1, n1) := bv1 in\n    nth i b1 false.\n\nEnd BV.\n\n\n\nModule BVProof.\n\n  Import BV.\n\n  Definition bitof (bv : t)(m : nat) :=\n    bb_nth m bv.\n\n  Definition bblt_len (bv : t) :=\n    let (b, n) := bv in\n    n.\n\n\n\n\n  Definition wf (bv:t) : Prop :=\n     let (b,n) := bv in N.of_nat (length b) = n.\n\n  Check N.of_nat.\n  Print N.of_nat.\n  SearchAbout N.of_nat.\n  Search (N.of_nat (_ + _) = (N.of_nat _) + (N.of_nat _)).\n\n  Lemma concat_wf : forall (bv1 bv2:t), wf bv1 -> wf bv2 -> wf (concat bv1 bv2).\n  Proof.\n    intros [b1 n1] [b2 n2] H1 H2.\n    simpl.\n    Search ((length (_ ++ _)) = ((length _) + (length _))%nat).\n    SearchAbout length.\n    rewrite app_length.\n    rewrite Nat2N.inj_add.\n    simpl in H1. simpl in H2.\n    rewrite H1. rewrite H2.\n    reflexivity.\n  Qed.\n\n  Lemma nth_append1 : forall A (l1 l2:list A) (i:nat) (d:A),\n    (i < length l1)%nat -> nth i (l1 ++ l2) d = nth i l1 d.\n  Proof.\n    intros A. induction l1.\n    - simpl. Search (~ ((_ < 0)%nat)).\n      intros l2 i d H. elim (Lt.lt_n_0 _ H).\n    - simpl. intros l2 [ |i] d Hi.\n      * reflexivity.\n      * apply IHl1. apply Lt.lt_S_n. assumption.\n  Qed.\n\n  Lemma of_nat_lt : forall i j,\n    (of_nat i < of_nat j) -> (i < j)%nat.\n  Admitted.\n\n  Check nth.\n  Lemma nth_wf : forall(bv1 bv2:t) (i : nat),\n   let (b1, n1) := bv1 in\n   wf bv1 -> wf bv2 -> (of_nat i < n1) -> bb_nth i (concat bv1 bv2) = bb_nth i bv1.\n  Proof.\n   intros [b1 n1] [b2 n2]. simpl. intros i H1 H2 Hi.\n   rewrite nth_append1.\n     - reflexivity.\n     - rewrite <- H1 in Hi.\n       apply of_nat_lt.\n       assumption.\n  Qed.\n\n\n(* term *)\nDefinition formula := Type.\nDefinition sort := Type.\nDefinition term := sort -> Type.\n\nDefinition BitVec := nat -> sort.\n\nInductive bit :=\n| b0\n| b1.\n\n(*\nDefinition const_bv := Type.\nDefinition bvn := const_bv.\nDefinition bvc := (bool * const_bv)\n*)\n\nInductive const_bv :=\n| bvn : const_bv\n| bvc : bit -> const_bv ->const_bv.\n\nDefinition toBV (n : nat) (v : const_bv) :=\n  (term (BitVec n)).\n(* SC := n = bv_len v *)\n\nDefinition concat (t1 :term) (t2 :term) :=\n  let (term (BitVec n)) := t1 in\n  let (term (BitVec m)) := t2 in\n  let m' := n + m in\n  (term (BitVec m')).\n\nInductive bblt :=\n| bbltn : bblt\n| bbltc : formula -> bblt ->bblt.\n\nDefinition bblast_term := nat -> term -> bblt -> Type.\n\nDefinition var_bv := Type.\n\nDefinition bitof := var_bv -> nat -> formula.\n\nDefinition a_var_bv (n :nat) :=\n  (term (BitVec n)).\n\nFixpoint bblt_len (v :bblt) : nat :=\n  match v with\n  | bbltn => 0\n  | bbltc b v' => (bblt_len v') + 1\n  end.\n\nDefinition decl_bblast (n :nat) (b : bblt)\n  (t : term (BitVec n)) (bb : bblast_term) :=\n  match (bblt_len b) with\n  | n => (* (bblast_term n t b)?? *) abort\n  | _ => abort\n  end.\n\nDefinition bblast_var (x : var_bv) (n :nat) : bblt :=\n  (bbltc (bitof x n) (bblast_var x (n - 1))).\n\nDefinition bv_bbl_var (n : nat)(x : var_bv)(f : bblt) :=\n  match (bblast_var x (n - 1)) with\n  | f => (bblast_term n (a_var_bv n x) f)\n  | _ => abort\n  end.\n\nDefinition bblast_bvand (x : bblt) (y : bblt) : bblt :=\n  match x with\n  | bbltn =>\n    match y with\n    | bbltn => bbltn\n    | bbltc y''' y'' => abort\n    end\n  | bbltc bx x' =>\n    match y with\n    | bbltn => abort\n    | bbltc by y' => (bbltc (and bx by) (bblast_bvand x' y'))\n    end\n  end.\n\nDefinition bv_bbl_bvand (n : nat) (x : (term (BitVec n))) (y : (term (BitVec n)))\n  (xb : bblt) (yb : bblt) (rb : bblt)\n  (xbb : (bblast_term n x xb)) (ybb : (bblast_term n y yb)) :=\n  match (bblast_bvadd xb yb) with\n  | rb => (bblast_term n (bvadd n x y) rb)\n  | _ => abort\n  end.\n\nFixpoint bblt_bvand_carry (a : bblt) (b : bblt) (c : formula) : formula :=\n  match a with\n  | bbltn =>\n    match b with\n    | bbltn => c\n    | _ => abort\n    end\n  | bbltc ai a' =>\n    match b with\n    | bbltn => abort\n    | bbltc bi b' => (or (and ai bi) (and xor ai bi) (bblt_bvand_carry a' b' c))\n    end\n  end.\n\nFixpoint bblast_bvand (a : bblt) (b : bblt) (carry : formula) : bblt :=\n  match a with\n  | bbltn =>\n    match b with\n    | bbltn => bbltn\n    | _ => abort\n    end\n  | bbltc ai a' =>\n    match b with\n    | bbltn => abort\n    | bbltc bi b' =>\n      (bbltc (xor ai (xor bi (bblt_bvadd_carry a' b' carry))) (bblast_bvadd a' b' carry))\n    end\n  end.\n\nDefinition bv_bbl_bvadd (n : nat) (x : (term (BitVec n))) (y : (term (BitVec n)))\n  (xb : bblt) (yb : bblt) (rb : bblt)\n  (xbb : (bblast_term n x xb)) (ybb : (bblast_term n y yb)) :=\n  match (bblast_bvadd xb yb) with\n  | rb => (bblast_term n (bvadd n x y) rb)\n  | _ => abort\n  end.\n\nEnd BVProof.\n", "meta": {"author": "smtcoq", "repo": "cvc4coq", "sha": "0424541aecc0750d5081187518a4ac539cef91f9", "save_path": "github-repos/coq/smtcoq-cvc4coq", "path": "github-repos/coq/smtcoq-cvc4coq/cvc4coq-0424541aecc0750d5081187518a4ac539cef91f9/Code/Bit-vectors/bv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7091180472476747}}
{"text": "Add LoadPath \"C:\\Users\\21692\\ParcoursRecherche\\dossier_final\\coq_parcours_recherche\\znaidi22\\dev\\final\" as lp.\n\n\nLoad Verbose ordreNat.\n\n\n\nRequire Import Arith Bool Decidable PeanoNat Coq.Arith.Peano_dec.\n\n\n(** * Division euclidienne *)\n\n(* division euclidienne\n                  \n -------------    \n 0 = 0 * d + 0\n\n n = q * d + r     d = r + 1    n = q * d + r     d ≠ r + 1\n ---------------------------    ---------------------------\n    S n = (q + 1) * d + 0          S n = q * d + (r + 1)            \n*)\nFixpoint divisionEuclidienne(n d : nat) : nat * nat.\nProof.\n  case n as [ | pn].\n  - exact (0, 0).\n  - case (divisionEuclidienne pn d) as [q r].\n    case (d =? (S r)) as [ | ].\n    -- exact (S q, 0).\n    -- exact (q, S r).\nDefined.\n\nPrint divisionEuclidienne.\n\nExample divisionEuclidienne_13_5 : divisionEuclidienne 13 5 = (2, 3).\ncbn.\nreflexivity.\nQed.\n\nExample divisionEuclidienne_14_5 : divisionEuclidienne 14 5 = (2, 4).\ncbn.\nreflexivity.\nQed.\n\nExample divisionEuclidienne_15_5 : divisionEuclidienne 15 5 = (3, 0).\ncbn.\nreflexivity.\nQed.\n\nExample divisionEuclidienne_13_0 : divisionEuclidienne 13 0 = (0, 13).\ncbn.\nreflexivity.\nQed.\n\n\nDefinition quotient(n d : nat) : nat.\n  case (divisionEuclidienne n d) as [q _].\n  exact q.\nDefined.\n\nPrint quotient.\n\nDefinition reste(n d : nat) : nat.\n  case (divisionEuclidienne n d) as [_ r].\n  exact r.\nDefined.\n\nPrint reste.\n\nProposition divEuclidienne_decomposition :\n  forall n d, n = (quotient n d) * d + (reste n d).\nProof.\n  unfold quotient, reste.\n  fix HR 1.\n  intros n d.\n  case n as [ | pn].\n  - cbn.\n    reflexivity.\n  - cbn.\n    case (divisionEuclidienne pn d) as [q r] eqn:divE.\n    case (d =? (S r)) as [ | ] eqn:egReste.\n    -- rewrite (HR pn d).\n       rewrite divE.\n       rewrite (beq_nat_true _ _ egReste).\n       ring.\n    -- rewrite (HR pn d).\n       rewrite divE.\n       ring.\nQed.\n(* Un cas particulier : d = 0. Reste. *)\nProposition divEuclidienne_resteDivParZero : forall n, (reste n 0 = n).\nProof.\n  intro n.\n  rewrite (divEuclidienne_decomposition n 0) at 2.\n  ring.\nQed.\n(* Un cas particulier : d = 0. Quotient. *)\nProposition divEuclidienne_quotientDivParZero : forall n, (quotient n 0 = 0).\nProof.\n  unfold quotient.\n  fix HR 1.\n  intro n.\n  case n as [ | pn].\n  - cbn.\n    reflexivity.\n  - cbn.\n    case (divisionEuclidienne pn 0) as [q r] eqn:eqDiv.\n    pose (hr := HR pn).\n    rewrite eqDiv in hr.\n    assumption.\nQed.\n\n(* Cas général : d > 0.\n   Majoration du reste : strictement par d.\n                  \n----------------------    \n0 = 0 * d + 0 => 0 < d\n\nn = q * d + r     d = r + 1    \n------------------------------    \nS n = (q + 1) * d + 0 => 0 < d \n\nn = q * d + r     d ≠ r + 1  HR : r < d\n----------------------------------------------------------- \nS n = q * d + (r + 1) => r + 1 <= d, d ≠ r + 1 => r + 1 < d           \n*)\nProposition divEuclidienne_majorationReste :\n  forall n d, (0 < d) -> (reste n d) < d.\nProof.\n  unfold reste.\n  fix HR 1.\n  intros n d dPos.\n  case n as [ | pn].\n  - cbn.\n    assumption.\n  - cbn.\n    case (divisionEuclidienne pn d) as [q r] eqn:eqDiv.\n    case (d =? S r) as [ | ] eqn:eqD.\n    -- assumption.\n    -- apply inferieurStrict_lt.\n       split.\n       --- pose (hr := HR pn d).\n           rewrite eqDiv in hr.\n           apply hr.\n           assumption.\n       --- intro abs.\n           Search((_ =? _ = false) -> ~(_ = _)).\n           apply (beq_nat_false _ _ eqD).\n           symmetry.\n           assumption.\nQed.\n\n(* Cas général : d > 0. Unicité de la décomposition euclidienne.\n\n(q1 * d + r1) = (q2 * d + r2)  (r1 < d)  (r2 < d)\n------------------------------------------------\n      (q1 = q2) ∧ (r1 = r2)\n\nInduction sur q1, décomposition de q2\n- q1 = 0, q2 = 0 : trivial\n- q1 = 0, q2 = S p2 : r1 = d + ..., r1 < d, absurde.\n- q1 = S p1, q2 = 0 : absurde aussi.\n- q1 = S p1, q2 = S p2 : HR / p1, p2 r1, r2 *)\nLemma decompositionEuclidienne_unicite :\n  forall d, (0 < d) -> forall q1 r1 q2 r2,\n      ((q1 * d + r1) = (q2 * d + r2))\n      -> (r1 < d) -> (r2 < d)\n      -> (q1 = q2) /\\ (r1 = r2). \nProof.\n  intros d dPos.\n  fix HR 1.\n  intros q1 r1 q2 r2 egDec maj1 maj2.\n  case q1 as [ | p1].\n  - case q2 as [ | p2].\n    + split.\n      * reflexivity.\n      * cbn in egDec.\n        assumption.\n    + exfalso.\n      cbn in egDec.\n      Search(_ <= _ + _). (* Nat.le_add_r *)\n      Search(_ <= _ -> _ <= _ -> _ = _). (* Nat.le_antisymm *)\n      assert (d <= r1) as oppMaj1.\n      {\n        rewrite egDec.\n        Search(_ + (_ + _)).\n        rewrite plus_assoc_reverse.\n        apply Nat.le_add_r.\n      }\n      Search (S _ <= _).\n      apply (Nat.nle_succ_diag_l r1).\n      transitivity d; assumption.\n  - case q2 as [ | p2].\n    + exfalso.\n      cbn in egDec.\n      assert (d <= r2) as oppMaj2.\n      {\n        rewrite <- egDec.\n        Search(_ + (_ + _)).\n        rewrite plus_assoc_reverse.\n        apply Nat.le_add_r.\n      }\n      apply (Nat.nle_succ_diag_l r2).\n      transitivity d; assumption.      \n    + cbn in egDec.\n      assert(p1 * d + r1 = p2 * d + r2) as egDec'.\n      {\n        Search(_ + _ = _ + _).\n        rewrite plus_assoc_reverse in egDec.\n        rewrite plus_assoc_reverse in egDec.\n        apply (plus_reg_l _ _ d) in egDec.\n        assumption.\n      }\n      pose (hr := HR p1 r1 p2 r2 egDec' maj1 maj2).\n      case hr as [egQ egR].\n      split.\n      * rewrite egQ.\n        reflexivity.\n      * assumption.\nQed.\n\n(* Cas général : d > 0. Caractérisation du quotient et du reste\n   par décomposition euclidienne. *)\nProposition divEuclidienne_caracterisation :\n  forall d, (0 < d) ->\n       forall n q r, (n = q * d + r) -> (r < d)\n                -> ((quotient n d = q) /\\ (reste n d = r)).\nProof.\n  intros d dPos n q r egN majR.\n  rewrite (divEuclidienne_decomposition n d) in egN.\n  apply decompositionEuclidienne_unicite with d.\n  - assumption.\n  - assumption.\n  - apply divEuclidienne_majorationReste.\n    assumption.\n  - assumption.\nQed.\n\n\nProposition divEuclidienne_caracterisationReste :\n  forall d, (0 < d) ->\n       forall n q r, (n = q * d + r) -> (r < d)\n                -> (reste n d = r).\nProof.\n  intros d dPos n q r eqN majR.\n  case (divEuclidienne_caracterisation d dPos n q r eqN majR) as [_ eqR].\n  assumption.\nQed.\n\n\n(* Premières applications de la caractérisation par décomposition du reste :\n   le caractère cyclique et l'idempotence. *)\nProposition reste_cycle :\n  forall d, reste d d = 0.\nProof.\n  intro d.\n  case d as [ | pd].\n  - reflexivity.\n  - apply divEuclidienne_caracterisationReste with 1.\n    -- Search(0 < S _).\n       apply Nat.lt_0_succ.\n    -- ring.\n    -- apply Nat.lt_0_succ.\nQed.\n \n\nProposition reste_idempotence :\n  forall d n, reste (reste n d) d = reste n d.\nProof.\n  intros d n.\n  case d as [ | pd].\n  - rewrite divEuclidienne_resteDivParZero.\n    reflexivity.\n  - apply divEuclidienne_caracterisationReste with 0.\n    -- Search(0 < S _).\n       apply Nat.lt_0_succ.\n    -- reflexivity.\n    -- apply divEuclidienne_majorationReste.\n       apply Nat.lt_0_succ.\nQed.\n\n(* Une seconde application de la caractérisation par décomposition :\n   le calcul du reste d'une somme *)\nProposition reste_preMorphismeAdditif :\n  forall d m n, reste (m + n) d = reste ((reste m d) + (reste n d)) d.\nProof.\n  intros d m n.\n  case d as [ | pd].\n  - (* cas 'd = 0' *)\n    repeat (rewrite divEuclidienne_resteDivParZero).\n    reflexivity.\n  - (* cas 'd = S pd' *)\n    pose (qm := quotient m (S pd)).\n    pose (qn := quotient n (S pd)).\n    pose (rm := reste m (S pd)).\n    pose (rn := reste n (S pd)).\n    pose (q_rmrn := quotient (rm + rn) (S pd)).\n    pose (r_rmrn := reste (rm + rn) (S pd)).\n    (* m + n = (qm + qn + q_rmrn) * d + r_rmrn *)\n    fold rm.\n    fold rn.\n    fold r_rmrn.\n    apply divEuclidienne_caracterisationReste with (qm + qn + q_rmrn).\n    -- Search(0 < S _).\n       apply Nat.lt_0_succ.\n    -- rewrite (divEuclidienne_decomposition m (S pd)).\n       rewrite (divEuclidienne_decomposition n (S pd)).\n       fold qm qn rm rn.    \n       transitivity (qm * S pd + qn * S pd + (rm + rn)).\n       ring.\n       rewrite (divEuclidienne_decomposition (rm + rn) (S pd)).\n       fold q_rmrn r_rmrn.    \n       ring.\n    -- apply divEuclidienne_majorationReste.\n       Search(0 < S _).\n       apply Nat.lt_0_succ.\nQed.\n\n(* Définition de l'équivalence modulo d. *)\nDefinition modulo_egalite(d m n: nat) : Prop.\n  exact (reste m d = reste n d).\nDefined.  \n\nProposition modulo_egalite_reflexivite : forall d n, modulo_egalite d n n.\nProof.\n  intros d n.\n  unfold modulo_egalite.\n  reflexivity.\nQed.\n\nProposition modulo_egalite_symetrie : forall d m n, modulo_egalite d m n -> modulo_egalite d n m.\nProof.\n  intros d m n.\n  unfold modulo_egalite.\n  intro h.\n  symmetry.\n  assumption.\nQed.\n\nProposition modulo_egalite_transitivite :\n  forall d n1 n2 m, modulo_egalite d n1 m -> modulo_egalite d m n2 -> modulo_egalite d n1 n2.\nProof.\n  unfold modulo_egalite.\n  intros d n1 n2 m eg1 eg2.\n  transitivity (reste m d); assumption.\nQed.\n(* Compatibilité avec l'addition de l'équivalence modulo. *)\nProposition modulo_egalite_compatibiliteAddition :\n  forall d, forall m1 n1 m2 n2,\n    modulo_egalite d m1 m2\n    -> modulo_egalite d n1 n2\n    -> modulo_egalite d (m1 + n1) (m2 + n2).\nProof.\n  intros d m1 n1 m2 n2 egM egN.\n  unfold modulo_egalite.\n  rewrite (reste_preMorphismeAdditif d m1 n1).\n  rewrite (reste_preMorphismeAdditif d m2 n2).\n  rewrite egM.\n  rewrite egN.\n  reflexivity.\nQed.  \n\nPrint Nat.sub.\n\n(* Définition d'un opposé modulo. *)\nDefinition modulo_oppose(n d : nat) : nat.\n  exact (reste (Nat.sub d (reste n d)) d).\nDefined.\n\n(* Correction de l'opposé : (n modulo d) + (opposé modulo d de n) = 0 modulo d.\n- (n%d + (d - n%d)%d)%d = 0 ?\n- (n%d + (d - n%d)%d)%d\n  = ((n%d)%d + (d - n%d)%d)%d  idempotence\n  = (n%d + (d - n%d))%d        pré-morphisme additif\n  = d%d                        (0 < d) -> (n%d < d)              \n  = 0\n*)\nProposition modulo_oppose_correction :\n  forall n d, (0 < d) -> modulo_egalite d ((reste n d) + (modulo_oppose n d)) 0.\nProof.\n  intros n d dPos.\n  unfold modulo_egalite.\n  unfold modulo_oppose.\n  rewrite <- (reste_idempotence d n) at 1.\n  rewrite <- (reste_preMorphismeAdditif d).\n  Search(_ + (_ - _)). (* le_plus_minus_r *)\n  assert(reste n d <= d) as majR.\n  {\n    Search(_ < _ -> _ <= _).\n    apply Nat.lt_le_incl.\n    apply divEuclidienne_majorationReste.\n    assumption.\n  }\n  erewrite (le_plus_minus_r _ _ majR).\n  apply  divEuclidienne_caracterisationReste with (S 0).\n  assumption.\n  cbn.\n  ring.\n  cbn.\n  assumption.\nQed.\n\n(** * Vers une représentation canonique ?\n\nAvertissement : ci-dessous '(S d)' correspond à 'd' utilisé au dessus.\nOn exclut ainsi le cas particulier de la relation modulo zéro.\n\nIl est possible de représenter le quotient de nat par l'égalité modulo\n(S d) par restriction de nat : on considère l'ensemble '{v : nat & v\n<= d}' ou encore '{v : nat & ∃h, v + h = d}'.  Un inconvénient de\ncette définition est de recourir à une proposition, autrement dit une\npartie non calculatoire.\n\nIl est cependant possible de transformer cette définition en utilisant\nune double définition inductive :\n- la première vise à décrire les couples '(h, v)' tels que 'v + h = d',\n- la seconde vise à décrire leur réunion.\n\nCette approche présente des difficultés : certaines démonstrations sont difficiles\npour des questions techniques liées aux définitions inductives.\n\nEn résumé : 'Modulo d' (pour représenter les classes de la relation modulo '(S d)') :\n'{(d, 0), ..., (0, d)}' formé de couples '(h, v)',\navec 'v' la valeur et 'h' le complémentaire. Invariant : 'h + v = d'.\n\nConstruction en deux temps.\n\n1. 'ModuloBrut(d : nat) : nat -> Type' - paramétrisation par 'd' et\nindexation par 'h'\n\n                                (ModuloBrut d (S h))\n---------------- [mb_zero]      -------------------- [mb_succ]\n(ModuloBrut d d)                   (ModuloBrut d h)\n\nInterprétation :\n- 'ModuloBrut d h' est le type singleton '{(h, v)}', avec 'h + v = d',\nla valeur 'v' étant donnée par '(mb_succ^v mb_zero)'.\n- La structure des termes est identique à celle des preuves de 'd >= h' (cf. supra).\n\n2. 'Modulo (d : nat)' : somme des singletons '(ModuloBrut d h)'\n\nModulo(d : nat) : Type.\n\n(h : nat) (ModuloBrut d h)\n-------------------------- [modulo]\n       Modulo d\n\nInterprétation :\n- 'Modulo d = {(d, 0), ..., (0, d)}' - 'nat' modulo '(S d)'\n*)\n\nInductive ModuloBrut(d : nat) : nat -> Type :=\n| mb_zero : ModuloBrut d d\n| mb_succ : forall h, ModuloBrut d (S h) -> ModuloBrut d h.\n\nFixpoint moduloBrut_valeur(d h : nat)(mb : ModuloBrut d h) : nat.\nProof.\n  case mb as [ | h pmb].\n  - exact 0. (* mb_zero évalué en 0 *)\n  - exact (S (moduloBrut_valeur _ _ pmb)). (* mb_succ évalué en S *)\nDefined.\n\n(* La structure des termes de 'ModuloBrut d h'\ncorrespond exactement à celle des preuves de 'SuperieurOuEgal d h'. *)\nProposition moduloBrut_majoration :\n  forall (d h : nat)(mb : ModuloBrut d h), SuperieurOuEgal d h.\nProof.\n  fix HR 3.\n  intros d h mb.\n  case mb as [ | h pmb].\n  - apply diagonale.\n  - apply descenteVerticale.\n    exact (HR _ _ pmb).\nDefined.\n\n(* L'invariant est bien vérifié. *)\nProposition moduloBrut_invariant :\n  forall d h, forall (mb : ModuloBrut d h),\n    (moduloBrut_valeur d h mb) + h = d. \nProof.\n  fix HR 3.\n  intros d h mb.\n  case mb as [ | h pmb].\n  - cbn.\n    reflexivity.\n  - cbn.\n    pose (hr := HR d (S h) pmb).\n    Search(_ + S _).\n    rewrite <- plus_n_Sm in hr.\n    assumption.\nQed.\n\n(* Somme (réuniondisjointe) des singletons 'ModuloBrut d h'\n\n  h : nat   m : ModuloBrut d h\n  ----------------------------\n      modulo m  : Modulo d\n*)\nInductive Modulo(d : nat) : Type :=\n| modulo : forall h, ModuloBrut d h -> Modulo d.\n\n(* Valeur et complémentaire :\n   - V (v, h) = v\n   - C (v, h) = h\n   - invariant : V (v, h) + C (v, h) = d *)\nDefinition modulo_valeur{d : nat}(m : Modulo d) : nat.\nProof.\n  case m as [h mb].\n  exact (moduloBrut_valeur _ _ mb).\nDefined.\n\nDefinition modulo_complementaire{d : nat}(m : Modulo d) : nat.\nProof.\n  case m as [h mb].\n  exact h.\nDefined.\n\nProposition modulo_invariant :\n  forall d, forall (m : Modulo d),\n    (modulo_valeur m) + (modulo_complementaire m) = d. \nProof.\n  intros d m.\n  case m as [h mb].\n  cbn.\n  apply moduloBrut_invariant.\nQed.\n\nProposition modulo_valeur_majoration :\n  forall d, forall (m : Modulo d),\n    (modulo_valeur m) < S d.\nProof.\n  intros d m.\n  Search(_ <= _ -> _ < S _).\n  apply le_lt_n_Sm.\n  transitivity ((modulo_valeur m) + (modulo_complementaire m)).\n  Search(_ <= _ + _).\n  apply Nat.le_add_r.\n  rewrite (modulo_invariant d m).\n  constructor.\nQed.  \n  \n(* Structure algébrique de 'Modulo d'\n- algèbre sur la signature (0, S) :\n  - une constante correspondant à '0',\n  - une fonction correspondant au successeur 'S'. \n- groupe additif commutatif :\n  - loi additive associative et commutative,\n  - élément neutre '0',\n  - opposé (de valeur égale au reste du successeur du complémentaire).\n- anneau commutatif (non traité, mais pourrait l'être) :\n  - loi multiplicative associative et commutative,\n  - élément neutre '1',\n  - pas d'inverse en général, l'inversibilité étant équivalente au fait\n    d'être premier avec 'S d' (par application du théorème de Bézout\n    https://fr.wikipedia.org/wiki/Th%C3%A9or%C3%A8me_de_Bachet-B%C3%A9zout). *)\n\n(* Modulo d : algèbre sur la signature (0, S). *)\n\nDefinition modulo_zero(d : nat) : Modulo d := modulo _ _ (mb_zero d).\n\nDefinition moduloBrut_succ{d h : nat}(mb : ModuloBrut d h) : Modulo d.\nProof.\n  case h as [ | ph].\n  + exact (modulo_zero d).\n  + exact (modulo _ _ (mb_succ _ _ mb)).\nDefined.\n\nDefinition modulo_succ{d : nat}(m : Modulo d) : Modulo d.\nProof.\n  case m as [h mb].\n  exact (moduloBrut_succ mb).\nDefined.\n\n(* Morphisme d'algèbre sur la signature '(0, S)', de 'nat' vers 'Modulo d' (noté M).\n   - M 0 = 0\n   - M(S n) = S (M n)\n   (0 et S étant interprétés de deux manières différentes dans l'algèbre du domaine,\n   'nat', et dans l'algèbre image, 'Modulo d') *) \nFixpoint modulo_morphismeNat(d : nat)(n : nat) : Modulo d.\nProof.\n  case n as [ | pn].\n  - exact (modulo_zero d).\n  - exact (modulo_succ (modulo_morphismeNat d pn)).\nDefined.\n\n(* Valeur : pré_inverse du morphisme\n\n'V (M n) = R n', où 'R' calcule le reste modulo '(S d)'.\nInduction sur 'n'\n- n = 0 : V (M 0) = 0 = R 0 \n- n = S pn : analyse suivant 'M pn'\n  - M pn = (0, v) : par l'invariant, v = d.\n    - V (M (S pn)) = V (S (0, d)) = V (d, 0) = 0\n    - R (S pn) = 0 car HR : V (M pn) = d = R pn\n  - M pn = (S h, v) : par l'invariant, v + (S h) = d\n    - V (M (S pn)) = V (S (S h, v)) = V (h, S v) = S v\n    - R (S pn) = S (R pn) car (HR : v = R pn) et (R pn) < d. *) \nLemma modulo_morphismeNat_valeur :\n  forall d, forall n,\n    modulo_valeur (modulo_morphismeNat d n) = reste n (S d).\nProof.\n  fix HR 2.\n  intros d n.\n  case n as [ | pn].\n  - cbn.\n    reflexivity.\n  - cbn.\n    case (modulo_morphismeNat d pn) as [h mb] eqn:egMorphPn.\n    cbn.\n    case h as [ | ph].\n    + cbn.\n      pose (hr := HR d pn).\n      rewrite egMorphPn in hr.\n      assert(reste pn (S d) = d) as egRestPn.\n      {\n        rewrite <- hr.\n        rewrite <- (modulo_invariant d (modulo d 0 mb)) at 3.\n        cbn.\n        ring.\n      }\n      symmetry.\n      apply divEuclidienne_caracterisationReste with (S (quotient pn (S d))).\n      Search(0 < S _).\n      apply Nat.lt_0_succ.\n      assert(pn = quotient pn (S d) * S d + d) as egPn.\n      {\n        rewrite <- egRestPn at 3.\n        apply divEuclidienne_decomposition.\n      }\n      rewrite egPn at 1.\n      ring.\n      apply Nat.lt_0_succ.\n    + cbn.\n      pose (hr := HR d pn).\n      rewrite egMorphPn in hr.\n      cbn in hr.\n      rewrite hr.\n      symmetry.\n      apply divEuclidienne_caracterisationReste with (quotient pn (S d)).\n      Search(0 < S _).\n      apply Nat.lt_0_succ.\n      assert(pn = quotient pn (S d) * S d + (reste pn (S d))) as egPn.\n      {\n        apply divEuclidienne_decomposition.\n      }\n      rewrite egPn at 1.\n      ring.\n      Search(S _ < S _).\n      apply lt_n_S.\n      assert (S(reste pn (S d)) + ph = d) as invRpn.\n      {\n        transitivity ((reste pn (S d)) + (S ph)).\n        ring.\n        rewrite <- hr.\n        apply moduloBrut_invariant.\n      }\n      Search (_ <= _). (* Nat.le_add_r: forall n m : nat, n <= n + m *)\n      rewrite <- invRpn at 2.\n      apply Nat.le_add_r.\nQed.      \n\n(* Vers la compatibilité avec le morphisme de l'égalité modulo\n- M n = M (R n)\n\nInduction sur n\n- n = 0 : M 0 = M (R 0) \n- n = S pn : analyse suivant (M pn)\n  - M pn = (0, v) : par l'invariant, v = d.\n    - M (S pn) = S (M pn) = (d, 0)\n    - R (S pn) = V (M (S pn)) (en utilisant la proposition préc.)\n               = V (d, O) = 0 \n      - M (R (S pn)) = M 0 =  (d, 0)\n  - M pn = (S h, v) : par l'invariant, v + (S h) = d\n    - HR : M pn = M (R pn), avec (R pn) = V (M pn) = v\n    - M (S pn) = S (M pn) = (h, S v) \n    - R (S pn) = V (M (S pn)) = V (h, S v) = S v = S (R pn)\n      - M (R (S pn)) = M (S (R pn)) = S (M (R pn)) = S (M pn) par HR *)\nLemma modulo_morphismeNat_calculParReste :\n  forall d, forall n,\n    modulo_morphismeNat d n = modulo_morphismeNat d (reste n (S d)).\nProof.\n  fix HR 2.\n  intros d n.\n  case n as [ | pn].\n  - cbn.\n    reflexivity.\n  - cbn.\n    case (modulo_morphismeNat d pn) as [h mb] eqn:egMorphPn.\n    cbn.\n    case h as [ | ph].\n    + rewrite <- modulo_morphismeNat_valeur.\n      cbn.\n      rewrite egMorphPn.\n      cbn.\n      reflexivity.\n    + assert(reste (S pn) (S d) = S (reste pn (S d))) as egR.\n      {\n        rewrite <- modulo_morphismeNat_valeur.\n        cbn.\n        rewrite egMorphPn.\n        cbn.\n        f_equal.\n        rewrite <- modulo_morphismeNat_valeur.\n        rewrite egMorphPn.\n        cbn.\n        reflexivity.\n      }\n      rewrite egR.\n      cbn.\n      rewrite <- (HR d pn).\n      rewrite egMorphPn.\n      cbn.\n      reflexivity.\nQed.\n\n(* Compatibilité de l'égalité modulo avec le morphisme *)\nProposition modulo_egalite_compatibiliteMorphismeNat :\n  forall d, forall m n,\n    modulo_egalite (S d) m n\n    -> modulo_morphismeNat d m = modulo_morphismeNat d n.\nProof.\n  intros d m n equiv_m_n.\n  unfold modulo_egalite.\n  rewrite (modulo_morphismeNat_calculParReste d m).\n  rewrite (modulo_morphismeNat_calculParReste d n).\n  rewrite equiv_m_n.\n  reflexivity.\nQed.  \n\nDefinition zeroMod3 := modulo_morphismeNat 2 3.\nPrint zeroMod3.\nCompute zeroMod3.\n\nDefinition unMod3 := modulo_morphismeNat 2 1.\nPrint unMod3.\nCompute unMod3.\n\nDefinition deuxMod3 := modulo_morphismeNat 2 2.\nPrint deuxMod3.\nCompute deuxMod3.\n\nExample identite_valeur_2_mod3 :\n  modulo_morphismeNat 2 (modulo_valeur deuxMod3) = deuxMod3.\nreflexivity.\nQed.\n\n(* L'inversibilité antérieure entraîne la surjectivité. *)\nProposition moduloBrut_morphismeNat_inversibiliteAnterieure :\n  forall d h (mb : ModuloBrut d h),\n    modulo_morphismeNat d (moduloBrut_valeur _ _ mb) = modulo _ _ mb.\nProof.\n  fix HR 3.\n  intros d h mb.\n  case mb as [ | h pmb].\n  - cbn.\n    reflexivity.\n  - cbn.\n    pose (hr := HR _ _ pmb).\n    cbn in hr.\n    rewrite hr.\n    reflexivity.\nQed.\n\nProposition modulo_morphismeNat_inversibiliteAnterieure :\n  forall d (m : Modulo d),\n    modulo_morphismeNat d (modulo_valeur m) = m.\nProof.\n  intros d m.\n  case m as [h mb].\n  apply moduloBrut_morphismeNat_inversibiliteAnterieure.\nQed.\n\n(* Surjectivité du morphisme *)\nProposition modulo_morphismeNat_surjectivite :\n  forall d (m : Modulo d), exists n, modulo_morphismeNat d n = m.\nProof.\n  intros d m.\n  exists (modulo_valeur m).\n  apply modulo_morphismeNat_inversibiliteAnterieure.\nQed.\n\n(* L'inversibilité postérieure entraîne l'injectivité (modulo (S d)). *)\nProposition modulo_morphismeNat_inversibilitePosterieure :\n  forall d n,\n    modulo_egalite (S d)\n      (modulo_valeur (modulo_morphismeNat d n)) \n      n.\nProof.\n  intros d n.\n  unfold modulo_egalite.\n  rewrite (modulo_morphismeNat_valeur d).\n  rewrite (reste_idempotence (S d)).\n  reflexivity.    \nQed.\n\n(* Injectivité du morphisme modulo *)\nProposition modulo_morphismeNat_injectivite :\n  forall d n1 n2,\n    (modulo_morphismeNat d n1) = (modulo_morphismeNat d n2)\n    -> modulo_egalite (S d) n1 n2.\nProof.\n  intros d n1 n2 egIm.\n  apply modulo_egalite_transitivite with (modulo_valeur (modulo_morphismeNat d n1)).\n  apply modulo_egalite_symetrie.\n  apply modulo_morphismeNat_inversibilitePosterieure.\n  rewrite egIm.\n  apply modulo_morphismeNat_inversibilitePosterieure.\nQed.\n\n\n(* Groupe additif commutatif *)\n\nFixpoint moduloBrut_somme{d h : nat}(mb : ModuloBrut d h)(n : Modulo d){struct mb} : Modulo d.\nProof.\n  case mb as [ | h pmb].\n  - exact n.\n  - exact (modulo_succ (moduloBrut_somme _ _ pmb n)).\nDefined.\n\nDefinition modulo_somme{d : nat}(m n : Modulo d) : Modulo d.\nProof.\n  case m as [h mb].\n  exact (moduloBrut_somme mb n).\nDefined.  \n\nExample somme_12_13_mod25 :\n  modulo_somme (modulo_morphismeNat 24 12) (modulo_morphismeNat 24 13) = modulo_morphismeNat 24 0.\nreflexivity.\nQed.\n\nExample somme_1_2_mod3 : modulo_somme unMod3 deuxMod3 = zeroMod3.\nreflexivity.\nQed.\n\nExample somme_2_2_mod3 : modulo_somme deuxMod3 deuxMod3 = unMod3.\nreflexivity.\nQed.\n\nProposition modulo_somme_neutraliteGauche :\n  forall d (n : Modulo d),\n    modulo_somme (modulo_zero d) n = n.\nProof.\n  intros d n.\n  cbn.\n  reflexivity.\nQed.\n\nLemma moduloBrut_somme_neutraliteDroite :\n  forall d h (nb : ModuloBrut d h),\n    moduloBrut_somme nb (modulo_zero d) = modulo _ _ nb.\nProof.\n  fix HR 3.\n  intros d h nb.\n  case nb as [ | h pnb].\n  - cbn.\n    reflexivity.\n  - cbn.\n    rewrite (HR _ _ pnb).\n    cbn.\n    reflexivity.\nQed.\n\n(* n + 0 = n *)\nProposition modulo_somme_neutraliteDroite :\n  forall d (n : Modulo d),\n    modulo_somme n (modulo_zero d) = n.\nProof.\n  intros d n.\n  case n as [h nb].    \n  cbn.\n  apply moduloBrut_somme_neutraliteDroite.\nQed.\n\nLemma moduloBrut_somme_successionDroite :\n  forall d h (mb : ModuloBrut d h) (n : Modulo d),\n    moduloBrut_somme mb (modulo_succ n) =\n      modulo_succ (moduloBrut_somme mb n).\nProof.\n  fix HR 3.\n  intros d h mb n.\n  case mb as [ | h pmb].\n  - cbn.\n    reflexivity.\n  - cbn.\n    rewrite (HR _ _ pmb _).\n    reflexivity.\nQed.\n\nProposition modulo_somme_successionDroite :\n  forall d (m n : Modulo d),\n    modulo_somme m (modulo_succ n)\n    = modulo_succ (modulo_somme m n).\nProof.\n  intros d m n.\n  case m as [h mb].    \n  cbn.\n  apply moduloBrut_somme_successionDroite.\nQed.\n\n\nLemma moduloBrut_somme_commutativite :\n  forall d h (mb : ModuloBrut d h) k (nb : ModuloBrut d k),\n    moduloBrut_somme mb (modulo _ _ nb)\n    = moduloBrut_somme nb (modulo _ _ mb).\nProof.\n  intro d.\n  fix HR 2.\n  intros h mb k nb.\n  case mb as [ | h pmb].\n  - cbn.\n    rewrite moduloBrut_somme_neutraliteDroite.\n    reflexivity.\n  - cbn.\n    fold (moduloBrut_succ pmb).\n    fold (modulo_succ (modulo _ _ pmb)).\n    rewrite moduloBrut_somme_successionDroite.\n    rewrite (HR (S h) pmb k nb).\n    reflexivity.\nQed.\n\n(* m + n = n + m *)\nProposition modulo_somme_commutativite :\n  forall d (m n : Modulo d),\n    modulo_somme m n = modulo_somme n m.\nProof.\n  intro d.\n  intros m n.\n  case m as [h mb].\n  case n as [k nb].\n  apply moduloBrut_somme_commutativite.\nQed.\n\n(* démonstration directe pénible ! *)\n(* Lemma moduloBrut_somme_successionGauche :\n  forall d h (mb : ModuloBrut d h) (n : Modulo d),\n    modulo_somme (moduloBrut_succ mb) n =\n      modulo_succ (moduloBrut_somme mb n).\nProof.\n  fix HR 3.\n  intros d h mb n.\n  case mb as [ | h pmb].\n  - cbn.\n    Print moduloBrut_succ.\n    Check (mb_zero d).\n    (* oblige à décomposer d ! *)\nAbort. *)\n\n(* Démonstration utilisant la commutativité *)\nProposition modulo_somme_successionGauche :\n  forall d (m n : Modulo d),\n    modulo_somme (modulo_succ m) n\n    = modulo_succ (modulo_somme m n).\nProof.\n  intros d m n.\n  rewrite modulo_somme_commutativite.\n  rewrite modulo_somme_successionDroite.\n  rewrite modulo_somme_commutativite.\n  reflexivity.\nQed.\n\n(* Compatibilité du morphisme avec l'addition\n- M (m + n) = (M m) + (M n)\n\nInduction sur m\n- m = 0\n  - M (0 + n) = M n\n  - (M 0) + (M n) = (d, 0) + (M n) = M n\n- m = S pm\n  - M ((S pm) + n) = M (S (pm + n)) = S (M (pm + n)) =[HR] S ((M pm) + (M n))\n  - (M (S pm)) + (M n) = (S (M pm)) + (M n) =[succ gauche] S ((M pm) + (M n))\n *)\nProposition modulo_morphismeNat_compatibiliteAddition :\n  forall d m n,  \n    modulo_morphismeNat d (m + n)\n    = modulo_somme (modulo_morphismeNat d m) (modulo_morphismeNat d n).\nProof.\n  fix HR 2.\n  intros d m n.\n  case m as [ | pm].\n  - cbn.\n    reflexivity.\n  - cbn.\n    rewrite (HR d pm n).\n    rewrite modulo_somme_successionGauche.\n    reflexivity.\nQed.\n\n(* Associativité de la somme *)\nLemma moduloBrut_somme_associativite_droiteAGauche :\n  forall d h (mb : ModuloBrut d h) (n1 n2 : Modulo d),\n    moduloBrut_somme mb (modulo_somme n1 n2)\n    = modulo_somme (moduloBrut_somme mb n1) n2.\nProof.\n  intro d.\n  fix HR 2.\n  intros h mb n1 n2.\n  case mb as [ | h pmb].\n  - cbn.\n    reflexivity.\n  - cbn.\n    rewrite modulo_somme_successionGauche.\n    rewrite (HR _ pmb n1 n2).\n    reflexivity.\nQed.\n\n(* m + (n1 + n2) = (m + n1) + n2 *)\nProposition modulo_somme_associativite_droiteAGauche :\n  forall d (m n1 n2 : Modulo d),\n    modulo_somme m (modulo_somme n1 n2)\n    = modulo_somme (modulo_somme m n1) n2.\nProof.\n  intros d m n1 n2.\n  case m as [h mb].\n  apply moduloBrut_somme_associativite_droiteAGauche.\nQed.\n\n(* (m + n1) + n2 = m + (n1 + n2) *)\nProposition modulo_somme_associativite_gaucheADroite :\n  forall d (m n1 n2 : Modulo d),\n    modulo_somme (modulo_somme m n1) n2\n    = modulo_somme m (modulo_somme n1 n2).\nProof.\n  intros d m n1 n2.\n  symmetry.\n  apply modulo_somme_associativite_droiteAGauche.\nQed.\n\nDefinition moduloBrut_opposeSomme{d h : nat}(mb : ModuloBrut d h) : Modulo d.\nProof.\n  exact (modulo_morphismeNat d (S h)).\nDefined.\n\nDefinition modulo_opposeSomme{d : nat}(m : Modulo d) : Modulo d.\nProof.\n  case m as [h mb].\n  exact (moduloBrut_opposeSomme mb).\nDefined.  \n\n(* m + (- m) = 0 *)\nProposition modulo_opposeSomme_correction :\n  forall d (m : Modulo d),\n    modulo_somme m (modulo_opposeSomme m) = modulo_zero d.\nProof.\n  intros d m.\n  rewrite <- (modulo_morphismeNat_inversibiliteAnterieure d m) at 1.\n  case m as [h mb].\n  cbn.\n  rewrite modulo_somme_successionDroite.\n  rewrite <- modulo_morphismeNat_compatibiliteAddition.\n  assert(moduloBrut_valeur d h mb + h = d) as inv.\n  {\n    replace h with (modulo_complementaire (modulo _ _ mb)) at 2.\n    apply (modulo_invariant d (modulo _ _ mb)).\n    reflexivity.\n  }\n  rewrite inv.\n  transitivity (modulo_morphismeNat d (S d)).\n  - reflexivity.\n  - rewrite (modulo_morphismeNat_calculParReste).\n    rewrite reste_cycle.\n    reflexivity.\nQed.\n\n(* Complément : sur l'unicité de la représentation. Démonstrations difficiles. *)\n\n(* Objectif : démontrer que chaque type 'ModuloBrut d h' est un singleton.\n Première tentative. *)\n(* Proposition moduloBrut_typesSingletons :\n  forall (d h : nat)(mb1 mb2 : ModuloBrut d h),\n    mb1 = mb2.\nProof.\n  fix HR 3.\n  intros d h mb1 mb2.\n  case mb1 as [ | h pmb1].\n  - admit. (* On aurait besoin d'un lemme. *)\n  - case mb2 as [ | h pmb2].\n    * exfalso.\n      apply moduloBrut_majoration in pmb1 as majAbs.\n      apply superieurOuEgal_adequation in majAbs.\n      Search(S _ <= _).\n      apply (Nat.nle_succ_diag_l d).\n      assumption.\n    * f_equal.\n      apply HR.\nAbort. *)\n\n(* Essayons de démontrer ce lemme. *)\n(* Lemma moduloBrut_singleton_casZero :  forall d (mb : ModuloBrut d d),\n    mb = mb_zero d.\nProof.\n  intros d mb.\n  (* case mb as [ | h pmb].\n     Error: Cannot instantiate metavariable P of type\n     \"forall n : nat, ModuloBrut d n -> Prop\"\n     with abstraction \"fun (d : nat) (mb : ModuloBrut d d) => mb = mb_zero d\"\n     of incompatible type \"forall d : nat, ModuloBrut d d -> Prop\".\n\n   Explication :\n\n   - Système d'inférence\n                                   (ModuloBrut d (S h))\n   ---------------- [mb_zero]      -------------------- [mb_succ]\n   (ModuloBrut d d)                   (ModuloBrut d h)\n\n   - Règle d'inférence pour la tactique 'case' (en première approximation)\n   (d : nat) ⊢ mb_zero d = mb_zero d\n         (d : nat), (h : nat), (pmb : ModuloBrut d (S h)) ⊢\n            (mb = mb_zero d)[mb := mb_succ d h pmb] // Mal typé !\n   -------------------------------------------------------------- [case mb]\n   (d : nat), (mb :  ModuloBrut d d) ⊢ mb = mb_zero d \n  *)\nAbort.*)\n\n\n(* Pour permettre une décomposition par 'case', il devient nécessaire de modifier\n   la formulation de la proposition, en distinguant 'd' du complémentaire 'h'.\n   Pour typer, on utilise un foncteur qui transforme :\n   - / objets : un 'h : nat' en un type 'ModuloBrut d h',\n   - / flèches : une égalité 'eg : h1 = h2' en une fonction\n     'conversion eg : ModuloBrut d h1 -> ModuloBrut d h2'. *)\n\n(* Conversion : foncteur catégorique - voir egalite_preuves_singletonSiDecidable. *)\nDefinition conversion{d h1 h2 : nat}(eg : h1 = h2) : ModuloBrut d h1 -> ModuloBrut d h2. \n  case eg. (* 'eg' serait remplacé par 'eq_refl h1', et 'h2' est récrit en 'h1'. *)\n  exact (fun mb => mb). (* La conversion devient l'identité. *)\nDefined.\n\n(* On reformule le lemme en utilisant la conversion.  *)\n(*\nLemma moduloBrut_singleton_casZeroModuloConversion :\n  forall d h (mb : ModuloBrut d h)(eg : h = d), \n    conversion eg mb = mb_zero d.   \nProof.\n  intros d h mb.\n  intro eg.\n  case mb as [ | h pmb].  \n  - Print eq. (* Définition de l'égalité. *)\n    Print conversion.\n    (* Pour simplifier la conversion, il est nécessaire de transformer 'eg' en 'eq_refl'. *)\n    (* case eg. Erreur ! *)\n    (* Error: Cannot instantiate metavariable P of type\n       \"forall a : nat, d = a -> Prop\" with abstraction\n       \"fun (d : nat) (eg : d = d) => conversion eg (mb_zero d) = mb_zero d\"\n       of incompatible type \"forall d : nat, d = d -> Prop\".\n\n       Explication\n       - Système d'inférence pour l'égalité 'eq' (notée '=')\n\n       eq(T : Type)(x : T) : T -> Prop // Paramétrisation par 'T' et 'x',\n                                          indexation par un 'T'\n\n       ----- [eq_refl]\n       x = x           // L'index 'x' doit être égal, c'est-à-dire identique,\n                       // au paramètre 'x'.\n\n       - Règle d'inférence pour la tactique 'case'\n\n       La règle pour la tactique 'case' pourrait être la suivante :\n\n       (d : nat) ⊢ (conversion eg (mb_zero d) = mb_zero d)[eg := @eq_refl nat d]\n       ------------------------------------------------------------------------- [case eg]\n       (d : nat), (eg : d = d) ⊢ conversion eg (mb_zero d) = mb_zero d\n\n       Dans ce cas, on aurait bien le sous-but souhaité :\n       - (d : nat) ⊢ mb_zero d = mb_zero d\n\n       Cependant, la règle pour la tactique 'case' réalise aussi\n       une abstraction de l'index, car il n'est pas possible de résoudre\n       en général les contraintes induites par les index qui peuvent varier librement\n       dans les conclusions des règles du type inductif, contrairement aux paramètres.\n\n       (d : nat) ⊢ ...[y := d, egX := @eq_refl nat d]\n       -------------------------------------------------------------------------- [case eg]\n       (d : nat), (eg : d = d)\n          ⊢ (conversion egX (mb_zero d) = mb_zero d)[y := d, egX : (d = y) := eg]\n            // égalité mal typée : '(ModuloBrut d y) / (ModuloBrut d d)'\n\n       Ainsi Coq interdit l'usage de la tactique 'case'. La solution ici est de\n       démontrer que 'eg' est égal à '@eq_refl nat d' (abrégé en 'eq_refl'). C'est le cas\n       pour tous les types pour lesquels l'égalité est décidable, comme 'nat'. \n     *)\nAbort.*)\n \n(* Nouvel essai : au lieu de la tactique 'case', on utilise le fait\nque toute égalité sur 'nat' est le constructeur 'eq_refl'. *)\nLemma moduloBrut_singleton_casZeroModuloConversion :\n  forall d h (mb : ModuloBrut d h)(eg : h = d), \n    conversion eg mb = mb_zero d.   \nProof.\n  intros d h mb.\n  intro eg.\n  case mb as [ | h pmb].\n  - (* Pour simplifier la conversion, il est nécessaire de transformer 'eg' en 'eq_refl'.\n       On peut montrer que 'eg' est égal à 'eq_refl', grâce à la décidabilité\n       de l'égalité sur 'nat'. C'est un résultat dans la bibliothèqe standard. *)\n    assert(eg = eq_refl) as eqPreuves.\n    {\n      Check UIP_nat.\n      apply UIP_nat. \n    }\n    rewrite eqPreuves.\n    cbn.\n    reflexivity.\n  - (* cas absurde : 'S h <= d' et 'h = d' impossibles. *)\n    exfalso.\n    apply moduloBrut_majoration in pmb as majAbs.\n    apply superieurOuEgal_adequation in majAbs.\n    Search(S _ <= _).\n    apply (Nat.nle_succ_diag_l d).\n    rewrite eg in majAbs.\n    assumption.\nQed.\n(* On déduit le lemme en instantiant l'égalité par 'eq_refl' :\nla conversion est alors l'identité. *)\nLemma moduloBrut_singleton_casZero :  forall d (mb : ModuloBrut d d),\n    mb = mb_zero d.\nProof.\n  intros d mb.\n  transitivity (conversion eq_refl mb).\n  - reflexivity.\n  - apply moduloBrut_singleton_casZeroModuloConversion.\nQed.\n\n\n(* On peut conclure en reprenant la démonstration interrompue.\nLes types 'ModuloBrut'sont des types singletons. *)\nProposition moduloBrut_typesSingletons :\n  forall (d h : nat)(mb1 mb2 : ModuloBrut d h),\n    mb1 = mb2.\nProof.\n  fix HR 3.\n  intros d h mb1 mb2.\n  case mb1 as [ | h pmb1].\n  - symmetry.\n    apply moduloBrut_singleton_casZero.\n  - case mb2 as [ | h pmb2].\n    * exfalso.\n      apply moduloBrut_majoration in pmb1 as majAbs.\n      apply superieurOuEgal_adequation in majAbs.\n      Search(S _ <= _).\n      apply (Nat.nle_succ_diag_l d).\n      assumption.\n    * f_equal.\n      apply HR.\nQed.\n  \n", "meta": {"author": "dhiaZnaidi", "repo": "Coq-Proof-Assistant-Project", "sha": "35ad59373469f5db249fa87e3d5dcd91c48ec1a7", "save_path": "github-repos/coq/dhiaZnaidi-Coq-Proof-Assistant-Project", "path": "github-repos/coq/dhiaZnaidi-Coq-Proof-Assistant-Project/Coq-Proof-Assistant-Project-35ad59373469f5db249fa87e3d5dcd91c48ec1a7/dev/final/modulo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7091026760726665}}
{"text": "Require Import Compare_dec.\nRequire Import PeanoNat.\n\nRequire Import Top.Terms.Term.\nRequire Import Top.Terms.VecUtils.\n\nSet Implicit Arguments.\n\nSection term_at.\n  Variable L : lType.\n\n  (** The [term_at] function is an analogue of [nth_error] on lists. *)\n  Fixpoint term_at (pos : list nat) (t : Term L) : option (Term L) :=\n    match pos with\n    | nil => Some t\n    | cons i pos' =>\n      match t with\n      | varTerm _ _ => None\n      | funTerm f ts =>\n        match lt_dec i (Term.a L f) with\n        | left ltH => term_at pos' (VectorDef.nth_order ts ltH)\n        | right _ => None\n        end\n      end\n    end.\n\n  Lemma term_at_cons_fun i pos f ts (ltH : i < Term.a L f)\n    : term_at (cons i pos) (funTerm f ts) =\n      term_at pos (VectorDef.nth_order ts ltH).\n  Proof.\n    simpl; destruct (lt_dec i (Term.a L f)) as [ ltH' | ]; try contradiction.\n    unfold VectorDef.nth_order.\n    rewrite (Fin.of_nat_ext ltH ltH'); auto.\n  Qed.\n\n  Lemma term_height_term_at t t' pos\n    : term_at pos t = Some t' ->\n      term_height t >= length pos + term_height t'.\n  Proof.\n    revert t; induction pos as [ | i pos IH ]; intro t; simpl.\n    - injection 1; intro tH; rewrite tH; auto.\n    - destruct t as [ | f ts ]; try discriminate.\n      destruct (lt_dec i (Term.a L f)) as [ ltH | ]; try discriminate.\n      intro someH; simpl.\n      unfold ge. apply le_n_S.\n      apply (Nat.le_trans _ (term_height (VectorDef.nth_order ts ltH))).\n      + exact (IH _ someH).\n      + exact (vec_max_at_ge_nth_order (term_height (L := L)) ts ltH).\n  Qed.\nEnd term_at.\n", "meta": {"author": "rswarbrick", "repo": "eder84", "sha": "682fa4d81ba690a88ea9b6eedee655901c8189b6", "save_path": "github-repos/coq/rswarbrick-eder84", "path": "github-repos/coq/rswarbrick-eder84/eder84-682fa4d81ba690a88ea9b6eedee655901c8189b6/Terms/TermAt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7091026652819826}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_lessthantransitive.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_midpointunique : \n   forall A B C D, \n   Midpoint A B C -> Midpoint A D C ->\n   eq B D.\nProof.\nintros.\nassert ((BetS A B C /\\ Cong A B B C)) by (conclude_def Midpoint ).\nassert ((BetS A D C /\\ Cong A D D C)) by (conclude_def Midpoint ).\nassert (Cong A B A B) by (conclude cn_congruencereflexive).\nassert (~ BetS C D B).\n {\n intro.\n assert (BetS B D C) by (conclude axiom_betweennesssymmetry).\n assert (BetS A B D) by (conclude axiom_innertransitivity).\n assert (Lt A B A D) by (conclude_def Lt ).\n assert (Cong A D C D) by (forward_using lemma_congruenceflip).\n assert (Lt A B C D) by (conclude lemma_lessthancongruence).\n assert (BetS C D B) by (conclude axiom_betweennesssymmetry).\n assert (Cong C D C D) by (conclude cn_congruencereflexive).\n assert (Lt C D C B) by (conclude_def Lt ).\n assert (Lt A B C B) by (conclude lemma_lessthantransitive).\n assert (Cong C B B C) by (conclude cn_equalityreverse).\n assert (Lt A B B C) by (conclude lemma_lessthancongruence).\n assert (Cong B C A B) by (conclude lemma_congruencesymmetric).\n assert (Lt A B A B) by (conclude lemma_lessthancongruence).\n let Tf:=fresh in\n assert (Tf:exists E, (BetS A E B /\\ Cong A E A B)) by (conclude_def Lt );destruct Tf as [E];spliter.\n assert (~ Cong A E A B) by (conclude lemma_partnotequalwhole).\n contradict.\n }\nassert (~ BetS C B D).\n {\n intro.\n assert (BetS D B C) by (conclude axiom_betweennesssymmetry).\n assert (BetS A D B) by (conclude axiom_innertransitivity).\n assert (Cong A D A D) by (conclude cn_congruencereflexive).\n assert (Lt A D A B) by (conclude_def Lt ).\n assert (Cong A B C B) by (forward_using lemma_congruenceflip).\n assert (Lt A D C B) by (conclude lemma_lessthancongruence).\n assert (BetS C B D) by (conclude axiom_betweennesssymmetry).\n assert (Cong C B C B) by (conclude cn_congruencereflexive).\n assert (Lt C B C D) by (conclude_def Lt ).\n assert (Lt A D C D) by (conclude lemma_lessthantransitive).\n assert (Cong C D D C) by (conclude cn_equalityreverse).\n assert (Lt A D D C) by (conclude lemma_lessthancongruence).\n assert (Cong D C C D) by (conclude lemma_congruencesymmetric).\n assert (Lt A D C D) by (conclude lemma_lessthancongruence).\n assert (Cong D C A D) by (conclude lemma_congruencesymmetric).\n assert (Cong C D A D) by (forward_using lemma_congruenceflip).\n assert (Lt A D A D) by (conclude lemma_lessthancongruence).\n let Tf:=fresh in\n assert (Tf:exists F, (BetS A F D /\\ Cong A F A D)) by (conclude_def Lt );destruct Tf as [F];spliter.\n assert (~ Cong A F A D) by (conclude lemma_partnotequalwhole).\n contradict.\n }\nassert (BetS C D A) by (conclude axiom_betweennesssymmetry).\nassert (BetS C B A) by (conclude axiom_betweennesssymmetry).\nassert (eq B D) by (conclude axiom_connectivity).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_midpointunique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7091026647453385}}
{"text": "(** Exercise 7.1 **)\n\n(* Given *)\n\nDefinition divides (n m:nat) :=\n  exists p:nat, p * n = m.\n\n(* To do *)\n\nLemma divides_0: forall n:nat, divides n 0.\nProof.\n  unfold divides.\n  intros n.\n  exists 0; simpl; reflexivity.\nQed.\n\nLemma divides_plus:\n  forall n m:nat,\n  divides n m -> divides n (n + m).\nProof.\n  unfold divides.\n  intros n m H1.\n  destruct H1 as [p H1].\n  exists (S p); simpl.\n  rewrite H1; reflexivity.\nQed.\n\nLemma sum_zero_implies_zero:\n  forall n m:nat, n + m = 0 -> n = 0.\nProof.\n  intros n m H.\n  induction n.\n  reflexivity.\n  discriminate.\nQed.\n\nLemma sum_comm:\n  forall n m:nat, n + m = m + n.\nProof.\n  intros n m.\n  induction n.\n  simpl; apply plus_n_O.\n  rewrite <-plus_n_Sm with (m := n).\n  simpl; apply f_equal; exact IHn.\nQed.\n\nLemma succ_pred_identity:\n  forall n:nat, n<>0 -> n = S (pred n).\nProof.\n  intros n H1.\n  induction n.\n  assert (0 = 0) as H2.\n  reflexivity.\n  contradiction.\n  simpl.\n  reflexivity.\nQed.\n\nLemma sum_cancel:\n  forall n m p:nat, n + p = m + p -> n = m.\nProof.\n  induction p.\n  repeat rewrite <-plus_n_O.\n  intro H; exact H.\n  repeat rewrite <-plus_n_Sm.\n  intro H.\n  apply IHp.\n  apply eq_add_S; exact H.\nQed.\n\nLemma not_divides_plus:\n  forall n m:nat,\n  ~divides n m -> ~divides n (n + m).\nProof.\n  unfold divides.\n  intros n m H1 H2.\n  destruct H2 as [q H2].\n  assert (exists p: nat, p * n = m).\n  exists (pred q).\n  assert (q <> 0) as H3.\n  intros H4.\n  assert (q * n = 0) as H5.\n  rewrite H4; simpl; reflexivity.\n  assert (m = 0) as H6.\n  apply sum_zero_implies_zero with (n := m) (m := n).\n  symmetry.\n  rewrite sum_comm.\n  rewrite <-H5; exact H2.\n  assert (exists p: nat, p * n = m) as H7.\n  exists 0.\n  simpl; rewrite H6; reflexivity.\n  contradiction.\n  assert (q = S (pred q)) as H4.\n  apply succ_pred_identity; exact H3.\n  assert (S (pred q) * n = n + m) as H5.\n  rewrite <-H4; exact H2.\n  assert (S (pred q) * n =\n    pred q * n + n) as H6.\n  simpl.\n  rewrite sum_comm; reflexivity.\n  rewrite H6 in H5.\n  apply sum_cancel with (p := n).\n  assert (m + n = n + m) as H7.\n  apply sum_comm.\n  rewrite H7; exact H5.\n  contradiction.\nQed.\n\n(* Now I use the 'Arith' module, otherwise I\n   would get lost proving auxiliary lemmas *)\nRequire Import Arith.\n\nLemma not_divides_lt:\n  forall n m:nat,\n  0 < m -> m < n -> ~divides n m.\nProof.\n  unfold divides.\n  intros n m H1 H2 H3.\n  destruct H3 as [p H3].\n  assert (0 < n) as H4.\n  apply lt_trans with (m := m); assumption.\n  assert (0 < p) as H5.\n  assert (0 <> p) as H6.\n  intro H7.\n  rewrite <-H7 in H3.\n  simpl in H3.\n  rewrite <-H3 in H1.\n  apply lt_irrefl with (n:=0); exact H1.\n  apply neq_0_lt; exact H6.\n  assert (m * p < n * p) as H6.\n  apply mult_lt_compat_r with (n := m).\n  exact H2.\n  exact H5.\n  rewrite mult_comm in H3.\n  rewrite H3 in H6.\n  assert (1 <= p) as H7.\n  apply H5.\n  assert (1 * m <= p * m) as H8.\n  apply mult_le_compat_r; exact H7.\n  rewrite mult_1_l in H8.\n  rewrite mult_comm in H8.\n  apply le_not_lt with (n := m) (m := m * p).\n  exact H8.\n  exact H6.\nQed.\n\nLemma not_lt_2_divides:\n  forall n m:nat,\n  n <> 1 -> n < 2 -> 0 < m -> ~divides n m.\nProof.\n  unfold divides.\n  induction n.\n  intros m H1 H2 H3 H4.\n  destruct H4 as [p H4].\n  rewrite mult_0_r in H4.\n  rewrite H4 in H3.\n  apply lt_irrefl with (n := m).\n  exact H3.\n  intros m H1 H2 H3 H4.\n  unfold lt in H2.\n  assert (S n = 1) as H5.\n  apply f_equal.\n  symmetry.\n  apply le_n_0_eq.\n  do 2 apply le_S_n; exact H2.\n  contradiction.\nQed.\n\nLemma le_plus_minus:\n  forall n m:nat, n <= m -> m = n + (m - n).\nProof.\n  intros n m H.\n  induction n.\n  simpl; rewrite <-minus_n_O; reflexivity.\n  rewrite plus_Sn_m.\n  rewrite plus_n_Sm.\n  rewrite minus_Sn_m.\n  simpl.\n  apply IHn.\n  apply le_Sn_le.\n  exact H.\n  exact H.\nQed.\n\nLemma lt_lt_or_eq:\n  forall n m:nat, n < S m -> n < m \\/ n = m.\nProof.\n  unfold lt.\n  intros n m H.\n  inversion H.\n  right; reflexivity.\n  left; exact H1.\nQed.", "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-ch7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.709102663304654}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) : natural := mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj51_coqofml_cgaebg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7090842427007333}}
{"text": "(** * Post Correspondence problem PCP *)\n\n(* Definitions of variants of the Post correspondence problem. *)\n\nRequire Import List.\nImport ListNotations.\n\n\n(* A string is a list of symbols. *)\nNotation string := list.\n\n(* A card a is a pair of the upper string x and the lower string y. *)\nNotation card := (fun X => string X * string X)%type.\n\n(* A stack is a list of cards. *)\nDefinition stack X := list (card X).\n\n(* The upper trace tau1 of a stack A \n  is the concatenation of the upper strings of A. *)\nFixpoint tau1 {X : Type} (A : stack X) : string X :=\n  match A with\n  | [] => []\n  | (x, y) :: A => x ++ tau1 A\n  end.\n\n(* The lower trace tau2 of a stack A \n  is the concatenation of the lower strings of A. *)\nFixpoint tau2 {X : Type} (A : stack X) : string X :=\n  match A with\n  | [] => []\n  | (x, y) :: A => y ++ tau2 A\n  end.\n\n(* The Post correspondence problem PCP is \n  given a stack P of cards to determine \n  whether there is a non-empty stack A of cards from P (with possible repetition)\n  such that the upper trace of A is equal to the lower trace of A. *)\nDefinition PCPX {X : Type}: stack X -> Prop :=\n  fun P => exists A, incl A P /\\ A <> [] /\\ tau1 A = tau2 A.\n\nDefinition PCP : stack nat -> Prop := @PCPX nat.\n\n(* PCPb is PCP restricted to cards with binary strings. *)\nDefinition PCPb : stack bool -> Prop := @PCPX bool.\n\n(* The indexed upper trace itau1 of indices A from a stack P\n  is the concatenation of the upper strings of P each with index from A. *)\nFixpoint itau1 {X : Type} (P : stack X) (A : list nat) : string X :=\n  match A with\n    | [] => []\n    | i :: A => fst (nth i P ([], [])) ++ itau1 P A\n  end.\n\n(* The indexed lower trace itau1 of indices A from a stack P\n  is the concatenation of the upper strings of P each with index from A. *)\nFixpoint itau2 {X : Type} (P : stack X) (A : list nat) : string X :=\n  match A with\n    | [] => []\n    | i :: A => snd (nth i P ([], [])) ++ itau2 P A\n  end.\n\n(* iPCPb is a different presentation of PCPb based on index lists. *)\nDefinition iPCPb : stack bool -> Prop :=\n  fun P => exists (A : list nat), \n    (forall a, In a A -> a < length P) /\\ A <> [] /\\ itau1 P A = itau2 P A.\n\n(* A pair of words is derivable from a stack P \n  if it can be build by concatenation of upper and lower strings of cards from P. *)\nInductive derivable {X : Type} (P : stack X) : string X -> string X -> Prop :=\n  | der_sing x y : In (x, y) P -> derivable P x y\n  | der_cons x y u v : In (x, y) P -> derivable P u v -> derivable P (x ++ u) (y ++ v).\n\n(* dPCPb is a different presentation of inductive presentation of PCP. *)\nDefinition dPCP {X : Type} : stack X -> Prop :=\n  fun P => exists u, @derivable X P u u.\n\n(* dPCPb is a different presentation of PCPb based in index derivability. *)\nDefinition dPCPb : stack bool -> Prop := @dPCP bool.\n\n(* Binary PCP inductively defined (cf Trakhtenbrot IJCAR 2020) *)\n\nInductive BPCP (P : stack bool) : Prop := \n  | cBPCP : forall u, derivable P u u -> BPCP P.\n\n(* The modified Post correspondence problem MPCP is \n  given a card x/y and stack P of cards to determine \n  whether there is a stack A of cards from x/y, P (with possible repetition)\n  such that the upper trace of x/y, A is equal to the lower trace of x/y,A. *)\nDefinition MPCP : card nat * stack nat -> Prop :=\n  fun '((x, y), P) => exists (A : stack nat), \n    incl A ((x, y) :: P) /\\ x ++ tau1 A = y ++ tau2 A.\n\n(* MPCPb is MPCP restricted to cards with binary strings. *)\nDefinition MPCPb : card bool * stack bool -> Prop :=\n  fun '((x, y), P) => exists (A : stack bool), \n    incl A ((x, y) :: P) /\\ x ++ tau1 A = y ++ tau2 A.", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/PCP/PCP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7090842419531579}}
{"text": "Require Import SepTypes.OrderedType SepTypes.OFuns SepTypes.Functor SepTypes.PChain.\n\nOpen Scope ofun_scope.\n\n\n(** A simple inductive type for binary trees with an order relation\n    and an fmap operation. *)\nSection tree.\n  Inductive Tree A :=\n  | Leaf : A -> Tree A\n  | Node : Tree A -> Tree A -> Tree A.\n\n  Global Arguments Leaf {_}.\n  Global Arguments Node {_}.\n\n  Inductive tree_oleq {A} `{OType A} : Tree A -> Tree A -> Prop :=\n  | tree_oleq_Leaf : forall x y,\n      x <o= y ->\n      tree_oleq (Leaf x) (Leaf y)\n  | tree_oleq_Node : forall t1 t2 t1' t2',\n      tree_oleq t1 t1' ->\n      tree_oleq t2 t2' ->\n      tree_oleq (Node t1 t2) (Node t1' t2').\n\n  Global Instance Reflexive_tree_oleq {A} `{OType A} : Reflexive tree_oleq.\n  Proof. intro x; induction x; constructor; auto; reflexivity. Qed.\n\n  Global Instance Transitive_tree_oleq {A} `{OType A} : Transitive tree_oleq.\n  Proof.\n    intros x y z Hxy Hyz; revert x z Hxy Hyz.\n    induction y; intros; destruct x, z;\n      inversion Hxy; inversion Hyz; subst.\n    - constructor; etransitivity; eauto.\n    - constructor.\n      + apply IHy1; auto.\n      + apply IHy2; auto.\n  Qed.\n\n  Global Program Instance OTtree A `(OType A) : OType (Tree A) :=\n    {| oleq := tree_oleq |}.\n  Next Obligation.\n    constructor.\n    - apply Reflexive_tree_oleq.\n    - apply Transitive_tree_oleq.\n  Qed.\n\n  Inductive isLeaf {A} : Tree A -> Prop :=\n  | isLeafLeaf : forall x, isLeaf (Leaf x).\n\n  Inductive isNode {A} : Tree A -> Prop :=\n  | isNodeNode : forall t1 t2, isNode (Node t1 t2).\n\n  Definition isLeafb {A} (t : Tree A) : bool :=\n    match t with\n    | Leaf _ => true\n    | Node _ _ => false\n    end.\n\n  Definition isNodeb {A} (t : Tree A) : bool :=\n    match t with\n    | Leaf _ => false\n    | Node _ _ => true\n    end.\n\n  Lemma isLeaf_isLeafb A (t : Tree A) :\n    isLeaf t <-> isLeafb t = true.\n  Proof.\n    split; intros H; inversion H; auto; destruct t.\n    - constructor.\n    - simpl in H; congruence.\n  Qed.\n\n  Lemma isNode_isNodeb A (t : Tree A) :\n    isNode t <-> isNodeb t = true.\n  Proof.\n    split; intros H; inversion H; auto; destruct t.\n    - simpl in H; congruence.\n    - constructor.\n  Qed.\n\n  (* tree_oleq is reflexive wrt equivalence. *)\n  Lemma Reflexive'_tree_oleq A `{OType A} t1 t2 :\n    t1 =o= t2 ->\n    tree_oleq t1 t2.\n  Proof. firstorder. Qed.\n\n  Global Instance Proper_tree_oleq' A `{OType A} :\n    Proper (oeq ==> oeq ==> oleq) tree_oleq.\n  Proof.\n    intros x y Hleq1 z w Hleq2 Hleq3.\n    rewrite <- Hleq1.\n    etransitivity; eauto.\n    apply Reflexive'_tree_oleq; auto.\n  Qed.\n\n  Global Instance Proper_Leaf {A} `{OType A} :\n    Proper (oleq ==> oleq) Leaf.\n  Proof. constructor; auto. Qed.\n\n  Global Instance Proper_Node {A} `{OType A} :\n    Proper (oleq ==> oleq ==> oleq) Node.\n  Proof. constructor; auto. Qed.\n\n  (* Plain-old fmap for trees. *)\n  Fixpoint tree_fmap {A B} `{OType A} `{OType B} (f : A -o> B)\n           (t : Tree A) : Tree B :=\n    match t with\n    | Leaf x => Leaf (f @@ x)\n    | Node t1 t2 => Node (tree_fmap f t1) (tree_fmap f t2)\n    end.\n\n  Global Instance Proper_tree_fmap {A B} `{OType A} `{OType B} (f : A -o> B) :\n    Proper (oleq ==> oleq) (tree_fmap f).\n  Proof.\n    intros x y Hleq; induction Hleq; simpl.\n    + rewrite H1; reflexivity.\n    + constructor; auto.\n  Qed.\n\n  (* OFun version of fmap. *)\n  Program Definition Tree_fmap {A B} `{OType A} `{OType B} (f : A -o> B)\n    : Tree A -o> Tree B :=\n    {| ofun_app := fun t => tree_fmap f t |}.\n  Next Obligation.\n    intros t1 t2 Hleq; induction Hleq; simpl.\n    - rewrite H1; reflexivity.\n    - constructor; auto.\n  Qed.\n\n  Global Instance Proper_Tree_fmap {A B} `{OType A} `{OType B} :\n    Proper (@oleq (A -o> B) _ ==> oleq) (Tree_fmap).\n  Proof.\n    intros ? ? ? ? ? Hleq2; induction Hleq2; constructor; auto.\n  Qed.\n\n  Global Instance Proper_Tree_fmap' {A B} `{OType A} `{OType B} :\n    Proper (@oeq (A -o> B) _ ==> oeq) (Tree_fmap).\n  Proof. intros ? ? Heq; split; apply Proper_Tree_fmap; apply Heq. Qed.\n\n  (* tree_fmap satisfies the functor laws. *)\n  Lemma tree_fmap_id A `{OType A} x :\n    tree_fmap id_ofun x =o= x.\n  Proof.\n    induction x.\n    - reflexivity.\n    - simpl; rewrite IHx1, IHx2; reflexivity.\n  Qed.\n\n  Lemma Tree_fmap_id A `{OType A} :\n    Tree_fmap id_ofun =o= id_ofun.\n  Proof.\n    generalize (tree_fmap_id A); intros H0; split;\n      intros t1 t2 Hleq; simpl; rewrite H0; auto.\n  Qed.\n\n  Lemma Tree_fmap_comp A B C `{OType A} `{OType B} `{OType C}\n        (f : A -o> B) (g : B -o> C) :\n    Tree_fmap (g ∘ f) =o= Tree_fmap g ∘ Tree_fmap f.\n  Proof.\n    split; intros t1 t2 Hleq; unfold oleq; simpl;\n      induction Hleq; constructor; auto; rewrite H2; reflexivity.\n  Qed.\n\n  (* Get the element out of a leaf. If the argument isn't a leaf, just\n     recurse to the left until one is found. *)\n  Fixpoint unLeaf {A} (t : Tree A) : A :=\n    match t with\n    | Leaf x => x\n    | Node t1 _ => unLeaf t1 (* shouldn't happen *)\n    end.\n\n  Global Instance Proper_unLeaf {A} `{OType A} :\n    Proper (oleq ==> oleq) unLeaf.\n  Proof. intros ? ? Heq; induction Heq; auto. Qed.\n\n  Lemma leaf_unleaf A (t : Tree A) :\n    isLeaf t ->\n    Leaf (unLeaf t) = t.\n  Proof. intros Hleaf; inversion Hleaf; auto. Qed.\n\n  (* OFun version of unLeaf *)\n  Definition unLeaf' {A} `{OType A} : Tree A -o> A :=\n    {| ofun_app := unLeaf; ofun_Proper := Proper_unLeaf |}.\n\n  (* Get the left subtree of a tree. If the argument is a leaf, just\n     return it unchanged. *)\n  Fixpoint unNodeLeft {A} (t : Tree A) : Tree A :=\n    match t with\n    | Leaf _ => t (* shouldn't happen *)\n    | Node t1 _ => t1\n    end.\n\n  Global Instance Proper_unNodeLeft {A} `{OType A} :\n    Proper (oleq ==> oleq) unNodeLeft.\n  Proof.\n    intros ? ? Heq; induction Heq; auto; simpl; rewrite H0; reflexivity.\n  Qed.\n\n  (* OFun version of unNodeLeft *)\n  Definition unNodeLeft' {A} `{OType A} : Tree A -o> Tree A :=\n    {| ofun_app := unNodeLeft; ofun_Proper := Proper_unNodeLeft |}.\n\n  (* Get the right subtree of a tree. If the argument is a leaf, just\n     return it unchanged. *)\n  Fixpoint unNodeRight {A} (t : Tree A) : Tree A :=\n    match t with\n    | Leaf _ => t (* shouldn't happen *)\n    | Node _ t2 => t2\n    end.\n\n  Global Instance Proper_unNodeRight {A} `{OType A} :\n    Proper (oleq ==> oleq) unNodeRight.\n  Proof.\n    intros ? ? Heq; induction Heq; auto; simpl; rewrite H0; reflexivity.\n  Qed.\n\n  (* OFun version of unNodeRight *)\n  Definition unNodeRight' {A} `{OType A} : Tree A -o> Tree A :=\n    {| ofun_app := unNodeRight; ofun_Proper := Proper_unNodeRight |}.\nEnd tree.\n\n\n(** The tree functor. *)\nSection treeFunctor.\n  Context F {oF : OTypeF F} {fm : FMap F} {func : Functor F}\n          {uF : UnfoldTypeF F} {uOF : UnfoldOTypeF F}\n          {fF : FoldF F} {ufF : UnfoldF F}\n          {cFunc : ContinuousFunctor F}.\n\n  Definition TreeF : TypeF := fun X oX => Tree (F X oX).\n\n  Global Instance TreeOTypeF : OTypeF TreeF := fun _ _ => _.\n\n  Global Instance TreeFMap : FMap TreeF :=\n    fun _ _ _ _ => fun f => Tree_fmap (fmap f).\n\n  Global Program Instance TreeFunctor : Functor TreeF.\n  Next Obligation.\n    unfold fmap, TreeFMap; destruct func.\n    rewrite fmap_id; apply Tree_fmap_id.\n  Qed.\n  Next Obligation.\n    unfold fmap, TreeFMap; destruct func.\n    rewrite fmap_comp; apply Tree_fmap_comp.\n  Qed.\nEnd treeFunctor.\n\n\n(** Operations and proofs related to chains of trees. *)\nSection treePChain.\n  Definition treeDiag f `{PDiagram f} := typeSequenceMap f (TreeF IdentityF).\n\n  Program Definition unLeafPChain {f} `{PDiagram f}\n  : PChain (treeDiag f) -o> PChain f := pChainMap (treeDiag f) f\n              (fun _ => {| ofun_app := fun x => unLeaf' @@ x |}) _.\n  Next Obligation.\n    unfold oeq, oleq; split; simpl; intros ? ? Heq;\n      induction Heq; simpl; auto; rewrite H0; reflexivity.\n  Qed.\n\n  Program Definition unNodeLeftPChain {f} `{PDiagram f}\n    : PChain (treeDiag f) -o> PChain (treeDiag f) :=\n    pChainMap (treeDiag f) (treeDiag f)\n              (fun _ => {| ofun_app := fun x => unNodeLeft' @@ x |}) _.\n  Next Obligation.\n    split; simpl; intros c1 c2 Hleq; induction Hleq;\n      try apply Proper_tree_fmap; auto; constructor;\n        rewrite H0; reflexivity.\n  Qed.\n\n  Program Definition unNodeRightPChain {f} `{PDiagram f}\n    : PChain (treeDiag f) -o> PChain (treeDiag f) :=\n    pChainMap (treeDiag f) (treeDiag f)\n              (fun _ => {| ofun_app := fun x => unNodeRight' @@ x |}) _.\n  Next Obligation.\n    split; simpl; intros c1 c2 Hleq; induction Hleq;\n      try apply Proper_tree_fmap; auto; constructor;\n        rewrite H0; reflexivity.\n  Qed.\n\n  Lemma unNodeLeftPChain_oleq {f} `{PDiagram f} (c1 c2 : PChain (treeDiag f)) :\n    c1 <o= c2 ->\n    unNodeLeftPChain @@ c1 <o= unNodeLeftPChain @@ c2.\n  Proof.\n    intros Hleq n; simpl; specialize (Hleq n);\n      destruct (chain c1 n), (chain c2 n);\n      inversion Hleq; subst; auto.\n  Qed.\n\n  Lemma unNodeRightPChain_oleq {f} `{PDiagram f} (c1 c2 : PChain (treeDiag f)) :\n    c1 <o= c2 ->\n    unNodeRightPChain @@ c1 <o= unNodeRightPChain @@ c2.\n  Proof.\n    intros Hleq n; simpl; specialize (Hleq n);\n      destruct (chain c1 n), (chain c2 n);\n      inversion Hleq; subst; auto.\n  Qed.\n\n  Program Definition treeFold {f} `{PDiagram f} :\n    Tree (PChain f) -o> PChain (treeDiag f) :=\n    {| ofun_app :=\n         fun t =>\n           {| chain := fun n => Tree_fmap (chainProj n) @@ t |} |}.\n  Next Obligation.\n    induction t; simpl.\n    - destruct a; apply (Proper_oeq_oleq_op1 _ _ _ Proper_Leaf);\n        apply chainCondition.\n    - apply (Proper_oeq_oleq_op2 _ _ _ _ Proper_Node); auto.\n  Qed.\n  Next Obligation.\n    intros x y Heq n. simpl.\n    induction Heq; simpl in *.\n    - specialize (H0 n). apply Proper_Leaf; auto.\n    - apply Proper_Node; auto.\n  Qed.\n\n  Fixpoint treeUnfold_f_aux {f} `{PDiagram f}\n           (c : PChain (treeDiag f))\n           (t : Tree (f 0))\n    : Tree (PChain f) :=\n    match t with\n    | Leaf _ => Leaf (unLeafPChain @@ c)\n    | Node t1 t2 => Node (treeUnfold_f_aux (unNodeLeftPChain @@ c) t1)\n                        (treeUnfold_f_aux (unNodeRightPChain @@ c) t2)\n    end.\n\n  Global Instance Proper_treeUnfold_f_aux f `{PDiagram f} :\n    Proper (oeq ==> oeq ==> oeq) treeUnfold_f_aux.\n  Proof.\n    intros c1 c2 Heq1 x y Heq2.\n    split; unfold oleq; simpl.\n    - destruct Heq2 as [Heq2 _].\n      revert c1 c2 Heq1.\n      induction Heq2; intros.\n      + constructor; intros n; destruct Heq1; simpl;\n          rewrite (H1 n); reflexivity.\n      + constructor.\n        * apply IHHeq2_1; destruct Heq1 as [Heq1 Heq2]; split;\n            unfold oleq; simpl; intros n; try rewrite (Heq1 n);\n              try rewrite (Heq2 n); reflexivity.\n        * apply IHHeq2_2; destruct Heq1 as [Heq1 Heq2]; split;\n            unfold oleq; simpl; intros n; try rewrite (Heq1 n);\n              try rewrite (Heq2 n); reflexivity.\n    - destruct Heq2 as [_ Heq2].\n      revert c1 c2 Heq1.\n      induction Heq2; intros.\n      + constructor; intros n; destruct Heq1; simpl;\n          rewrite (H2 n); reflexivity.\n      + constructor.\n        * apply IHHeq2_1; destruct Heq1 as [Heq1 Heq2]; split;\n            unfold oleq; simpl; intros n; try rewrite (Heq1 n);\n              try rewrite (Heq2 n); reflexivity.\n        * apply IHHeq2_2; destruct Heq1 as [Heq1 Heq2]; split;\n            unfold oleq; simpl; intros n; try rewrite (Heq1 n);\n              try rewrite (Heq2 n); reflexivity.\n  Qed.\n\n  Definition treeUnfold_f {f} `{PDiagram f}\n           (c : PChain (treeDiag f))\n    : Tree (PChain f) :=\n    treeUnfold_f_aux c (chain c 0).\n\n  Global Instance Proper_treeUnfold_f {f} `{PDiagram f} :\n    Proper (oleq ==> oleq) treeUnfold_f.\n  Proof.\n    intros c1 c2 Hleq.\n    unfold oleq in *. simpl in *.\n    unfold treeUnfold_f.\n    pose proof Hleq as Hleq'.\n    specialize (Hleq' 0).\n    remember (chain c1 0) as x.\n    remember (chain c2 0) as y.\n    revert Heqx Heqy. revert c1 c2 Hleq.\n    induction Hleq'; intros.\n    - simpl. constructor. intros ?. simpl.\n      rewrite Hleq. reflexivity.\n    - simpl. constructor.\n      + assert (H0: t1 = chain (unNodeLeftPChain @@ c1) 0).\n        { simpl; destruct (chain c1 0); inversion Heqx; auto. }\n        assert (H1: t1' = chain (unNodeLeftPChain @@ c2) 0).\n        { simpl; destruct (chain c2 0); inversion Heqy; auto. }\n        specialize (IHHleq'1 (unNodeLeftPChain @@ c1)\n                             (unNodeLeftPChain @@ c2)\n                             (unNodeLeftPChain_oleq _ _ Hleq) H0 H1).\n        etransitivity. apply IHHleq'1.\n        apply Reflexive'_tree_oleq. reflexivity.\n      + assert (H0: t2 = chain (unNodeRightPChain @@ c1) 0).\n        { simpl; destruct (chain c1 0); inversion Heqx; auto. }\n        assert (H1: t2' = chain (unNodeRightPChain @@ c2) 0).\n        { simpl; destruct (chain c2 0); inversion Heqy; auto. }\n        specialize (IHHleq'2 (unNodeRightPChain @@ c1)\n                             (unNodeRightPChain @@ c2)\n                             (unNodeRightPChain_oleq _ _ Hleq) H0 H1).\n        etransitivity. apply IHHleq'2.\n        apply Reflexive'_tree_oleq. reflexivity.\n  Qed.\n\n  Definition treeUnfold {f} `{PDiagram f}\n    : PChain (treeDiag f) -o> Tree (PChain f) :=\n    {| ofun_app := treeUnfold_f |}.\n\n  Lemma isLeaf_oleq A `{OType A} (t1 t2 : Tree A) :\n    isLeaf t1 -> t1 <o= t2 -> isLeaf t2.\n  Proof.\n    intros Hleaf Hleq; inversion Hleq; subst;\n      try constructor; inversion Hleaf.\n  Qed.\n\n  Lemma isNode_oleq A `{OType A} (t1 t2 : Tree A) :\n    isNode t1 -> t1 <o= t2 -> isNode t2.\n  Proof.\n    intros Hnode Hleq; inversion Hleq; subst;\n      try constructor; inversion Hnode.\n  Qed.\n\n  Lemma isLeaf_fmap {A B} `{OType A} `{OType B} (t : Tree A) (f : A -o> B) :\n    isLeaf (tree_fmap f t) -> isLeaf t.\n  Proof.\n    intros Hleaf; destruct t. constructor. inversion Hleaf.\n  Qed.\n\n  Lemma isNode_fmap {A B} `{OType A} `{OType B} (t : Tree A) (f : A -o> B) :\n    isNode (tree_fmap f t) -> isNode t.\n  Proof.\n    intros Hnode. destruct t. inversion Hnode. constructor.\n  Qed.\n\n  Lemma isLeaf_chain f `{PDiagram f} (c : PChain (treeDiag f)) n :\n    isLeaf (chain c 0) -> isLeaf (chain c n).\n  Proof.\n    intros Hleaf; inversion Hleaf.\n    destruct c; simpl in *.\n    induction n.\n    - rewrite <- H1; constructor.\n    - specialize (chainCondition n).\n      generalize (isLeaf_oleq _ (chain n)\n                              (tree_fmap (proj n) (chain (S n)))\n                              IHn (proj1 chainCondition)); intros Hleaf'.\n      apply isLeaf_fmap in Hleaf'; auto.\n  Qed.\n\n  Lemma isNode_chain f `{PDiagram f} (c : PChain (treeDiag f)) n :\n    isNode (chain c 0) -> isNode (chain c n).\n  Proof.\n    intros Hnode; inversion Hnode.\n    destruct c; simpl in *.\n    induction n.\n    - rewrite <- H1; constructor.\n    - specialize (chainCondition n).\n      generalize (isNode_oleq _ (chain n)\n                              (tree_fmap (proj n) (chain (S n)))\n                              IHn (proj1 chainCondition)); intros Hnode'.\n      apply isNode_fmap in Hnode'; auto.\n  Qed.\n\n  Lemma tree_fold_unfold f `{PDiagram f} :\n    treeFold ∘ treeUnfold =o= id_ofun.\n  Proof.\n    split; simpl.\n    - intros c1 c2 Hleq n. unfold oleq; simpl.\n      unfold treeUnfold_f.\n      transitivity (chain c1 n).\n      + clear Hleq c2; remember (chain c1 0) as m; revert c1 Heqm.\n        induction m; intros; simpl.\n        * assert (isLeaf (chain c1 n)).\n          { apply isLeaf_chain; rewrite <- Heqm; constructor. }\n          rewrite leaf_unleaf; auto; reflexivity.\n        * assert (isNode (chain c1 n)).\n          { apply isNode_chain; rewrite <- Heqm; constructor. }\n          inversion H0; subst; constructor.\n          -- assert (H1: m1 = chain (unNodeLeftPChain @@ c1) 0).\n             { simpl; destruct (chain c1 0); inversion Heqm; auto. }\n             specialize (IHm1 (unNodeLeftPChain @@ c1) H1).\n             etransitivity. apply IHm1.\n             simpl; rewrite <- H2; reflexivity.\n          -- assert (H1: m2 = chain (unNodeRightPChain @@ c1) 0).\n            { simpl; destruct (chain c1 0); inversion Heqm; auto. }\n            specialize (IHm2 (unNodeRightPChain @@ c1) H1).\n            etransitivity. apply IHm2.\n            simpl; rewrite <- H2; reflexivity.\n      + apply Hleq.\n    - intros c1 c2 Hleq n. unfold oleq; simpl.\n      transitivity (chain c2 n).\n      + apply Hleq.\n      + clear Hleq c1; unfold treeUnfold_f; remember (chain c2 0) as m.\n        revert c2 Heqm; induction m; intros; simpl.\n        * assert (isLeaf (chain c2 n)).\n          { apply isLeaf_chain; rewrite <- Heqm; constructor. }\n          rewrite leaf_unleaf; auto; reflexivity.\n        * assert (isNode (chain c2 n)).\n          { apply isNode_chain; rewrite <- Heqm; constructor. }\n          inversion H0; subst; constructor.\n          -- assert (H1: m1 = chain (unNodeLeftPChain @@ c2) 0).\n             { simpl; destruct (chain c2 0); inversion Heqm; auto. }\n             specialize (IHm1 (unNodeLeftPChain @@ c2) H1).\n             transitivity (chain (unNodeLeftPChain @@ c2) n).\n             { simpl. rewrite <- H2. simpl. reflexivity. }\n             etransitivity; eauto. reflexivity.\n          -- assert (H1: m2 = chain (unNodeRightPChain @@ c2) 0).\n             { simpl; destruct (chain c2 0); inversion Heqm; auto. }\n             specialize (IHm2 (unNodeRightPChain @@ c2) H1).\n             transitivity (chain (unNodeRightPChain @@ c2) n).\n             { simpl. rewrite <- H2. simpl. reflexivity. }\n             etransitivity; eauto. reflexivity.\n  Qed.\n\n  Lemma tree_unfold_fold f `{PDiagram f} :\n    treeUnfold ∘ treeFold =o= id_ofun.\n  Proof.\n    split; unfold oleq; simpl.\n    - intros t1 t2 Hleq. unfold oleq; simpl.\n      induction Hleq; simpl in *.\n      + constructor; auto.\n      + unfold treeUnfold_f in *. simpl in *.\n        constructor.\n        * match goal with\n          | [ _ : tree_oleq ?x t1' |- _ ] => transitivity x\n          end; auto;\n          apply Reflexive'_tree_oleq;\n          apply Proper_treeUnfold_f_aux;\n          split; simpl; unfold oleq; simpl; reflexivity;\n          reflexivity.\n        * match goal with\n          | [ _ : tree_oleq ?x t2' |- _ ] => transitivity x\n          end; auto.\n          apply Reflexive'_tree_oleq.\n          apply Proper_treeUnfold_f_aux.\n          split; simpl; unfold oleq; simpl; reflexivity.\n          reflexivity.\n    - intros t1 t2 Hleq.\n      induction Hleq; simpl in *.\n      + transitivity (Leaf y). constructor; auto.\n        apply Reflexive'_tree_oleq.\n        split; constructor; unfold oleq; simpl; reflexivity.\n      + constructor; etransitivity; try apply IHHleq1;\n          try apply IHHleq2; apply Reflexive'_tree_oleq;\n            unfold treeUnfold_f; simpl; apply Proper_treeUnfold_f_aux;\n              split; unfold oleq; simpl; reflexivity.\n  Qed.\nEnd treePChain.\n\n\n(** The tree continuous functor. *)\nSection continuousTreeFunctor.\n  Context F {oF : OTypeF F} {fm : FMap F} {func : Functor F}\n          {uF : UnfoldTypeF F} {uOF : UnfoldOTypeF F}\n          {fF : FoldF F} {ufF : UnfoldF F}\n          {cFunc : ContinuousFunctor F}.\n\n  Global Instance TreeUnfoldTypeF : UnfoldTypeF (TreeF F) :=\n  fun f _ _ => Tree (@unfoldTypeF F uF f _ _).\n  Global Instance TreeUnfoldOTypeF : UnfoldOTypeF (TreeF F) := fun _ _ _ => _.\n  Global Instance TreeFoldF : FoldF (TreeF F) :=\n    fun f _ _ => treeFold ∘ Tree_fmap (foldF f).\n  Global Instance TreeUnfoldF : UnfoldF (TreeF F) :=\n    fun f _ _ => Tree_fmap (unfoldF f) ∘ treeUnfold.\n  Global Instance TreeContinuousFunctor : ContinuousFunctor (TreeF F).\n  Proof.\n    constructor.\n    - intros f o G.\n      unfold unfoldF, TreeUnfoldF, foldF, TreeFoldF.\n      rewrite compose_ofun_assoc_4.\n      rewrite tree_unfold_fold.\n      rewrite id_compose_ofun.\n      match goal with\n      | [ |- Tree_fmap ?f ∘ Tree_fmap ?g =o= _ ] =>\n        transitivity (Tree_fmap (f ∘ g))\n      end.\n      symmetry.\n      apply Tree_fmap_comp.\n      destruct cFunc. rewrite unfold_fold_id.\n      apply Tree_fmap_id.\n    - intros f o G.\n      unfold unfoldF, TreeUnfoldF, foldF, TreeFoldF.\n      rewrite compose_ofun_assoc_4.\n      rewrite compose_ofun_middle_id.\n      apply tree_fold_unfold.\n      match goal with\n      | [ |- Tree_fmap ?f ∘ Tree_fmap ?g =o= _ ] =>\n        transitivity (Tree_fmap (f ∘ g))\n      end.\n      symmetry; apply Tree_fmap_comp.\n      destruct cFunc. rewrite fold_unfold_id.\n      apply Tree_fmap_id.\n  Qed.\nEnd continuousTreeFunctor.\n", "meta": {"author": "eddywestbrook", "repo": "separation-types", "sha": "a1d53ec10049802934617201b733a7f8a8f80c83", "save_path": "github-repos/coq/eddywestbrook-separation-types", "path": "github-repos/coq/eddywestbrook-separation-types/separation-types-a1d53ec10049802934617201b733a7f8a8f80c83/theories/Tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8080672227971212, "lm_q1q2_score": 0.7090602255511574}}
{"text": "Load \"Utils\".\n\nFixpoint pad_list {A} r default (l : list A) :=\n  match r, l with\n  | 0, _ => []\n  | _, [] => List.repeat default r\n  | _, x :: l'  => x :: pad_list (pred r) default l'\n  end.\n\nLemma pad_list_length :\n  forall {A} r default (l : list A),\n  length (pad_list r default l) = r.\nProof.\n  intros ? ? ? ?. generalize dependent r. induction l; intros ?.\n  - destruct r.\n    + auto.\n    + simpl. f_equal. apply List.repeat_length.\n  - destruct r.\n    + auto.\n    + simpl. f_equal. apply IHl.\nQed.\n\nDefinition indexes_list_of_index r d i :=\n  List.rev (pad_list d 0 (to_digits r i)).\n\nFixpoint indexes_list_to_index r d il :=\n  match il with\n  | [] => 0\n  | i :: il' => Nat.pow r (pred d) * i + indexes_list_to_index r (pred d) il'\n  end.\n\nSection Example.\n\nCompute indexes_list_of_index 2 8 10.\nCompute indexes_list_to_index 2 8 [0; 0; 0; 0; 1; 0; 1; 0].\n\nEnd Example.\n\nLemma indexes_list_of_index_length :\n  forall r d i,\n  length (indexes_list_of_index r d i) = d.\nProof.\n  intros ? ? ?. unfold indexes_list_of_index. rewrite List.rev_length. apply pad_list_length.\nQed.\n\nLemma indexes_list_to_indexes_list_rev_cons :\n  forall r d i il,\n  length il = d ->\n  indexes_list_to_index r (S d) (List.rev (i :: il)) =\n  indexes_list_to_index r d (List.rev il) * r + i.\nProof.\n  intros ? ? ? ?. remember (List.rev il) as l0. generalize dependent il.\n  generalize dependent d. generalize dependent i. induction l0; intros ? ? ? ? ?.\n  - simpl. destruct il.\n    + simpl in H. subst d. simpl. lia.\n    + simpl in Heql0. symmetry in Heql0. apply List.app_eq_nil in Heql0. intuition discriminate.\n  - simpl. destruct d.\n    + simpl. destruct il; discriminate.\n    + rewrite <- List.rev_involutive in Heql0 at 1. simpl in Heql0.\n      apply list_rev_injective in Heql0. subst il. simpl.\n      rewrite PeanoNat.Nat.mul_add_distr_r. rewrite <- PeanoNat.Nat.add_assoc.\n      simpl in IHl0. rewrite <- (IHl0 _ _ (List.rev l0)); clear IHl0.\n      * replace [i] with (List.rev [i]) at 1 by auto. rewrite List.rev_app_distr. simpl. lia.\n      * symmetry. apply List.rev_involutive.\n      * rewrite List.app_length in H. simpl in H. lia.\nQed.\n\nLemma indexes_list_to_indexes_list_rev_list_repeat_0 :\n  forall r d,\n  indexes_list_to_index r d (List.rev (List.repeat 0 d)) = 0.\nProof.\n  intros ? ?. induction d.\n  - auto.\n  - simpl List.repeat. rewrite indexes_list_to_indexes_list_rev_cons.\n    + lia.\n    + apply List.repeat_length.\nQed.\n\nTheorem indexes_list_to_of_correct :\n  forall r d i,\n  r > 1 ->\n  i < Nat.pow r d ->\n  indexes_list_to_index r d (indexes_list_of_index r d i) = i.\nProof.\n  intros ? ? ? ?. generalize dependent i. unfold indexes_list_of_index. induction d; intros ? ?.\n  - simpl in H0. destruct i; try lia. rewrite to_digits_red_any_zero. simpl. auto.\n  - destruct (PeanoNat.Nat.eqb_spec i 0).\n    + clear IHd. subst i. rewrite to_digits_red_any_zero. simpl pad_list.\n      rewrite indexes_list_to_indexes_list_rev_cons.\n      * rewrite indexes_list_to_indexes_list_rev_list_repeat_0. auto.\n      * apply List.repeat_length.\n    + assert (Nat.div i r < Nat.pow r d). {\n        simpl in H0. destruct (PeanoNat.Nat.eqb_spec (Nat.div i r) (Nat.pow r d)).\n        - apply PeanoNat.Nat.div_lt_upper_bound; lia.\n        - unfold lt in H0. apply Le.le_Sn_le in H0. apply PeanoNat.Nat.div_le_mono with (c := r) in H0; try lia.\n          rewrite PeanoNat.Nat.mul_comm in H0. rewrite PeanoNat.Nat.div_mul in H0; try lia.\n      }\n      specialize (IHd (Nat.div i r) H1); clear H1. rewrite to_digits_red_any_nonzero; try lia.\n      simpl pad_list. rewrite indexes_list_to_indexes_list_rev_cons.\n      * rewrite IHd; clear IHd. symmetry. rewrite PeanoNat.Nat.mul_comm. apply PeanoNat.Nat.div_mod_eq.\n      * apply pad_list_length.\nQed.\n\nTheorem indexes_list_of_index_upper_bound :\n  forall r d i,\n  r > 1 ->\n  list_forall (fun i => i < r) (indexes_list_of_index r d i).\nProof.\n  intros ? ? ? ?. unfold indexes_list_of_index.\n  rewrite list_forall_equiv. apply List.Forall_rev. rewrite <- list_forall_equiv.\n  generalize dependent i. induction d; intros ?.\n  - remember (pad_list 0 0 (to_digits r i)) as l. rewrite (proj1 (List.length_zero_iff_nil l)).\n    + simpl. auto.\n    + subst l. apply pad_list_length.\n  - destruct (PeanoNat.Nat.eqb_spec i 0).\n    + clear IHd. subst i. rewrite to_digits_red_any_zero. simpl. split; try lia. induction d.\n      * simpl. auto.\n      * simpl. intuition lia.\n    + rewrite to_digits_red_any_nonzero; try lia. simpl. split.\n      * apply PeanoNat.Nat.mod_upper_bound. lia.\n      * auto.\nQed.\n\nTheorem indexes_list_to_index_upper_bound :\n  forall r d il,\n  length il = d ->\n  list_forall (fun i => i < r) il ->\n  indexes_list_to_index r d il < Nat.pow r d.\nProof.\n  intros ? ? ?. generalize dependent d. induction il; intros ? ? ?.\n  - simpl. simpl in H. subst d. simpl. auto.\n  - simpl. simpl in H. destruct H0 as (? & ?). specialize (IHil (pred d) ltac:(lia) H1); clear H1. destruct d.\n    + lia.\n    + simpl. simpl in IHil. nia.\nQed.\n", "meta": {"author": "afdw", "repo": "digital_list", "sha": "ddadc0735f1240d4b62e962a42edf66bd1612adb", "save_path": "github-repos/coq/afdw-digital_list", "path": "github-repos/coq/afdw-digital_list/digital_list-ddadc0735f1240d4b62e962a42edf66bd1612adb/theories/NonDep/Indexes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7090602246456086}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf3 : natural) (lf2 : natural) : natural :=\n  plus (Succ lf3) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj113_coqofml_y0A8pv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7090318714902278}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (x : natural) (y : natural)\n  : natural := plus Zero (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj226_coqofml_zgTifa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229959153748, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7089978459685279}}
{"text": "From Coq Require Import Sets.Ensembles.\nFrom Coq Require Import Relations_1.\nFrom Coq Require Import Bool.\nSection Groups.\nVariable U : Type.\n\n(*Binary operation.*)\nDefinition binop :=U->U->U.\n\nDefinition Group (G : Ensemble U) (star : binop) : Prop:=\n(\n    (forall (a b c: U), In U G a /\\ In U G b /\\ In U G c->\n    In U G (star a b)) (*Being closed under operator*)\n    /\\\n    (forall (a b c: U), In U G a /\\ In U G b /\\ In U G c->\n    star a (star b c) = star (star a b) c) (*Associativity*)\n    /\\\n    exists e: U, In U G e /\\ (forall d: U, In U G d -> star e d = d /\\ star d e = d) (*Existence of identity*)\n    /\\\n    forall d: U, In U G d -> (exists d': U, In U G d' /\\ star d d'= e /\\ star d' d = e) (*Invertibality*)\n).\n(*More Variables:*)\nVariable G : Ensemble U.\nVariable star : binop.\n\n\nNotation \"x ** y\" := (star x y) (at level 40, left associativity).\n\n(*Associativiy:*)\nLemma assoc:\nGroup G star -> (forall (a b c: U), In U G a /\\ In U G b /\\ In U G c-> a ** (b ** c) = star (star a b) c).\nProof.\n    intros H a b c H1. apply H. apply H1.\n    Qed.\n\n(*Identity element:*)\nVariable e : U.\nDefinition Group_iden G star e : Prop :=\n    Group G star /\\ In U G e -> forall d : U, In U G d -> d**e=d /\\ e**d=d.\n\nLemma iden_l : \nGroup G star -> In U G e -> Group_iden G star e ->\n    forall d :U, In U G d -> e**d = d.\n    Proof.\n        intros H H0 H1 d H2. apply H1. +split. ++apply H.\n        ++apply H0. +apply H2.\n    Qed.\nLemma iden_r : \nGroup G star -> In U G e -> Group_iden G star e ->\n    forall d :U, In U G d -> d**e = d.\n    Proof.\n        intros H H0 H1 d H2. apply H1. +split. ++apply H.\n        ++apply H0. +apply H2.\n    Qed.\n\n(*Inverse element:*)\nDefinition inv_prop (a a' : U) : Prop :=\n    Group G star -> Group_iden G star e -> In U G a -> In U G a' -> a ** a' = e /\\ a'**a = e.\n\nLemma inv_l:\n    Group G star -> Group_iden G star e -> \n    forall a a':U, In U G a -> In U G a' -> inv_prop a a' -> a' ** a = e.\n    Proof.\n        intros H H1 a a' H2 H3 H4. apply H4.\n        +apply H. +apply H1. +apply H2. +apply H3.\n    Qed. \nLemma inv_r:\n    Group G star -> Group_iden G star e -> \n    forall a a':U, In U G a -> In U G a' -> inv_prop a a' -> a ** a' = e.\n    Proof.\n        intros H H1 a a' H2 H3 H4. apply H4.\n        +apply H. +apply H1. +apply H2. +apply H3.\n    Qed.\n    \n\n(*Multiplying an element on two sides of an equality:*)\nLemma eq_mul_l : \nGroup G star -> forall (a b c:U), b = c -> star a b = star a c.\nProof. \n    intros H a b c H1. rewrite -> H1. reflexivity.\n    Qed.\n\nLemma eq_mul_r : \nGroup G star -> forall (a b c:U), b = c -> b ** a = c **a.\nProof. \n    intros H a b c H1. rewrite -> H1. reflexivity.\n    Qed.\n\n\n(*(*Cancellation laws:*)\nLemma cancel_l : \nGroup G star -> forall (a b c:U),\nIn U G a /\\ In U G b /\\ In U G c ->\nstar a b = star a c -> b = c.\nProof.\n    intros H a b c H1 H2. unfold Group in H. destruct H.\n    destruct H0. destruct H3. destruct H3. destruct H4.\n    assert (H12: exists a', In U G a' -> a ** a' = e /\\ a' ** a = e).\n    +destruct H1. apply H5 in H1. destruct H1. \n    exists x0. intros H54. split. ++apply H1.\n    rewrite -> eq_mul_l with (a:=a'). *)\n\n\n\n\nEnd Groups.\n\n\n\n\n\n\n\n\n\n\nDefinition add (a b:bool):=a || b.\nDefinition adib : binop bool := add. \nTheorem disj_group: forall (G : Ensemble bool) , (forall (n:bool), In bool G n)\n->Group bool G adib.\nProof.\n    intros G H. unfold Group. split.\n    +intros a b c H0. apply H. +split.\n    ++intros a b c H0. unfold adib. unfold add. apply orb_assoc. \n    ++exists false. split. +++apply H. +++split.\n    ++++intros d H1. split. +++++unfold adib. unfold add. simpl. reflexivity.\n    +++++unfold adib. unfold add. rewrite -> orb_commutative.  \n\nQed.\n\n\n\n", "meta": {"author": "senmorta13", "repo": "abstract-algebra-coq", "sha": "165290894ad165d129e5358ca95fb73783261e5d", "save_path": "github-repos/coq/senmorta13-abstract-algebra-coq", "path": "github-repos/coq/senmorta13-abstract-algebra-coq/abstract-algebra-coq-165290894ad165d129e5358ca95fb73783261e5d/main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7089230073426352}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := plus Zero (plus y x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj275_coqofml_70YDls.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7089230038980093}}
{"text": "Require Import List.\nRequire Import Nat.\nRequire Import Tactics.\nRequire Import Program.\nRequire Import Setoid.\nRequire Import SetoidClass.\nRequire Import Relation_Definitions.\nRequire Import Specif.\n\n(** * Parametric types **)\n\n(** Type syntax. T,U,V *)\nInductive type :=\n| TyUnit : type\n| TyZero : type (* Empty. *)\n| TyArr  : type -> type -> type (* Functions. *)\n| TyProduct : type -> type -> type\n| TySum : type -> type -> type\n| TyAlpha : type. (* A single type parameter. *)\n\nInfix \":->\" := TyArr (at level 30, right associativity) : type_scope.\n\nDefinition t := TyAlpha :-> TyAlpha.\nDefinition t2 := TyProduct (TyAlpha :-> TyAlpha) TyAlpha.\nPrint t2.\n\n(** Interpretation of a type as a Set,\n    parameterized by the interpretation of Alpha. *)\nFixpoint sem (K : Set) (T : type) : Set :=\n  match T with\n  | TyAlpha => K\n  | TyProduct T1 T2 => sem K T1 * sem K T2\n  | TySum T1 T2 => sem K T1 + sem K T2\n  | T :-> U => sem K T -> sem K U\n  | TyUnit => unit\n  | TyZero => Empty_set\n  end.\n\n(*\nRecord Setoid : Type :=\n  mkSetoid\n    { carrier : Type;\n      rel : relation carrier;\n      equiv : equivalence carrier rel }.\n *)\n\nInstance unit_setoid : Setoid unit :=\n  { equiv := fun _ _ => True }.\nProof.\n  split; intro; auto.\nQed.\n\nInstance empty_setoid : Setoid Empty_set :=\n  { equiv := fun _ _ => False }.\nProof.\n  split; intro; auto.\n  destruct x.\nQed.\n\nPrint equiv.\n\nInstance pair_setoid A B `(a : Setoid A) `(b : Setoid B)\n  : Setoid (A * B) :=\n  { equiv :=\n      fun x y =>\n        let (a1, b1) := x in\n        let (a2, b2) := y in\n        a1 == a2 /\\ b1 == b2 }.\nProof.\n  split; intro.\n  - destruct x.\n    split.\n    + apply a.\n    + apply b.\n  - intros y H; destruct x, y.\n    split.\n    + apply a. apply H.\n    + apply b; apply H.\n  - intros y z H I. destruct x as [x1 x2], y as [y1 y2], z as [z1 z2].\n    split.\n    + apply (@setoid_trans _ a x1 y1 z1).\n      * apply H. * apply I.\n    + apply (@setoid_trans _ b x2 y2 z2).\n      * apply H. * apply I.\nQed.\n\nInstance sum_setoid A1 A2 `(a1 : Setoid A1) `(a2 : Setoid A2)\n  : Setoid (A1 + A2) :=\n  { equiv :=\n      fun x y =>\n        match x, y with\n        | inl x1, inl y1 => x1 == y1\n        | inr x2, inr y2 => x2 == y2\n        | _, _ => False\n        end }.\nProof.\n  split.\n  - intro x; destruct x.\n    + apply a1.\n    + apply a2.\n  - intros x y.\n    destruct x as [x1 | x2], y as [y1 | y2]; auto.\n    + apply a1; apply H.\n    + apply a2; apply H.\n  - intros x y z Hx Hy.\n    destruct x as [x1 | x2], y as [y1 | y2], z as [z1 | z2]; auto.\n    + apply (@setoid_trans _ _ x1 y1 z1).\n      * apply Hx. * apply Hy.\n    + destruct Hx.\n    + destruct Hx.\n    + apply (@setoid_trans _ _ x2 y2 z2).\n      * apply Hx. * apply Hy.\nQed.\n\nRecord smorph (A : Type) (B : Type)\n       `{S_A : Setoid A} `{S_B : Setoid B}\n  : Type :=\n  mksmorph\n    { smorph_f : A -> B;\n      smorph_equiv : forall a1 a2, a1 == a2 -> smorph_f a1 == smorph_f a2 }.\n\nInstance smorph_setoid A B `(S_A : Setoid A) `(S_B : Setoid B) : Setoid (smorph A B) :=\n  { equiv :=\n      fun f g =>\n        forall a, smorph_f _ _ f a == smorph_f _ _ g a}.\nProof.\n  split.\n  - intros f a.\n    apply S_B.\n  - intros f g H a.\n    apply S_B. apply H.\n  - intros f g h Hf Hg a.\n    apply (@setoid_trans _ S_B (smorph_f _ _ f a) (smorph_f _ _ g a) (smorph_f _ _ h a)).\n    + apply Hf.\n    + apply Hg.\nQed.\n\nPrint existT.\n\nLocate \"*\".\n\nFixpoint sem_eq (K : Set) `{K_S : Setoid K} (T : type) : { S : Set & `(Setoid S) } :=\n  match T with\n  | TyUnit => existT _ unit unit_setoid\n  | TyZero => existT _ Empty_set empty_setoid\n  | T :-> U =>\n    match sem_eq K T, sem_eq K U with\n    | existT _ KT KT_S, existT _ KU KU_S =>\n      existT _ (@smorph KT KU KT_S KU_S) (smorph_setoid KT KU KT_S KU_S)\n    end\n  | TyProduct T1 T2 =>\n    match sem_eq K T1, sem_eq K T2 with\n    | existT _ KT1 KT1_S, existT _ KT2 KT2_S =>\n      existT _ (prod KT1 KT2) (pair_setoid KT1 KT2 KT1_S KT2_S)\n    end\n  | TySum T1 T2 =>\n    match sem_eq K T1, sem_eq K T2 with\n    | existT _ KT1 KT1_S, existT _ KT2 KT2_S =>\n      existT _ (sum KT1 KT2) (sum_setoid KT1 KT2 KT1_S KT2_S)\n    end\n  | TyAlpha =>\n    existT _ K K_S\n  end.\n\nInstance sem_eq_setoid (K : Set) `(K_S : Setoid K) T : Setoid (projT1 (sem_eq K T)) :=\n  projT2 (sem_eq K T).\n\n\n\n\n\n     match T with\n  | TyUnit => tt\n  | TyZero =>\n  | T :-> U =>\n    fun x y =>\n      forall r s, sem_eq K R T r r -> sem_eq K R T s s -> sem_eq K R T r s -> sem_eq K R U (x r) (y s)\n  | TyProduct T1 T2 =>\n    fun x y =>\n      let (x1, x2) := x in\n      let (y1, y2) := y in\n      sem_eq K R T1 x1 y1 /\\ sem_eq K R T2 x2 y2\n  | TySum T1 T2 =>\n    fun x y =>\n      match x, y with\n      | inl x1, inl y1 => sem_eq K R T1 x1 y1\n      | inr x2, inr y2 => sem_eq K R T2 x2 y2\n      | _, _ => False\n      end\n  | TyAlpha => R\n  end.\n\nLemma\n  sem_eq_sym\n  (K : Set) (R : K -> K -> Prop) (R_sym : forall x y, R x y -> R y x)\n  (T : type)\n  : forall x y, sem_eq K R T x y -> sem_eq K R T y x.\nProof.\n  induction T; intros x y H; auto.\n  - intros r s Hr Hs I.\n    apply IHT2, H, IHT1.\n    + apply Hs.\n    + apply Hr.\n    + apply I.\n  - destruct x; destruct y; split.\n    + apply IHT1.\n      destruct H; apply H.\n    + apply IHT2.\n      destruct H.\n      apply H0.\n  - destruct x; destruct y; auto.\n    + apply IHT1.\n      apply H.\n    + apply IHT2.\n      apply H.\n  - apply R_sym, H.\nQed.\n\nLemma\n  sem_eq_trans\n  (K : Set) (R : K -> K -> Prop)\n  (R_trans : forall x y z, R x y -> R y z -> R x z)\n  (T : type)\n  : forall x y z, sem_eq K R T x y -> sem_eq K R T y z -> sem_eq K R T x z.\nProof.\n  induction T; intros x y z Hx Hy; auto.\n  - intros r s Hr Hs I.\n    apply IHT2 with (y := y r).\n    apply Hx.\n    + apply Hr.\n    + apply Hr.\n    + apply Hr.\n    + apply Hy.\n      * apply Hr.\n      * apply Hs.\n      * apply I.\n  - destruct x, y as [y1 y2], z.\n    split.\n    + apply IHT1 with (y := y1).\n      * destruct Hx.\n        apply H.\n      * destruct Hy.\n        apply H.\n    + apply IHT2 with (y := y2).\n      * destruct Hx; auto.\n      * destruct Hy; auto.\n  - destruct x, z; inversion y as [y1 | y2]; auto.\n    + apply IHT1 with (y := y1); auto.\n    + apply IHT1. with (y := y). auto.\n\n\n        (*\nInductive sem_eq (K : Set) (R : K -> K -> Prop)\n  : forall (T : type), sem K T -> sem K T -> Prop :=\n| SEqAlpha : forall x y, R x y -> sem_eq K R TyAlpha x y\n| SEqProduct : forall T1 T2 x1 x2 y1 y2,\n    sem_eq K R T1 x1 y1 ->\n    sem_eq K R T2 x2 y2 ->\n    sem_eq K R (TyProduct T1 T2) (x1, x2) (y1, y2)\n| SEqLeft : forall T1 T2 x1 y1,\n    sem_eq K R T1 x1 y1 ->\n    sem_eq K R (TySum T1 T2) (inl x1) (inl y1)\n| SEqRight : forall T1 T2 x2 y2,\n    sem_eq K R T2 x2 y2 ->\n    sem_eq K R (TySum T1 T2) (inr x2) (inr y2)\n| SEqFun : forall T U x y,\n    (forall r s, sem_eq K R T r s -> sem_eq K R U (x r) (y s)) ->\n    sem_eq K R (T :-> U) x y.\n *)\n\n(** * Paths in values\n\n    We will define a type of \"paths\" that, given a value of\n    type T, leads to a leaf of type alpha.\n    We actually do this on the semantic level:\n    given a value of type sem K T, a path leads to a leaf of\n    type K. *)\n\n(** Choices. C\n\n    To make sure paths remain valid, we must restrict values\n    of sum types. A \"choice\" chooses one alternative for\n    every occurence of a sum type. *)\nInductive choice\n          {K : Set}\n  : type -> Set :=\n| CAlpha : choice TyAlpha\n| CProduct : forall {T1} {T2},\n    choice T1 -> choice T2 -> choice (TyProduct T1 T2)\n| CLeft : forall {T1 T2}, choice T1 -> choice (TySum T1 T2)\n| CRight : forall {T1 T2}, choice T2 -> choice (TySum T1 T2)\n| CUnit : choice TyUnit\n| CArrow : forall {T U}, (sem K T -> choice U) -> choice (T :-> U).\n  (* For functions, we make one choice for every argument. *)\n\n(* Paths. p *)\nInductive path\n          (K : Set)\n  : forall (T : type), choice T -> Set :=\n\n(* We're at a leaf. *)\n| PHere : path K TyAlpha CAlpha\n\n(* Given a pair, a path goes into either component. *)\n| PFst : forall T1 T2 (C1 : choice T1) (C2 : choice T2),\n    path K T1 C1 -> path K (TyProduct T1 T2) (CProduct C1 C2)\n| PSnd : forall T1 T2 (C1 : choice T1) (C2 : choice T2),\n    path K T2 C2 -> path K (TyProduct T1 T2) (CProduct C1 C2)\n\n(* For sums, the choice allows only one alternative. *)\n| PLeft : forall T1 T2 (C1 : choice T1),\n    path K T1 C1 -> path K (TySum T1 T2) (CLeft C1)\n| PRight : forall T1 T2 (C2 : choice T2),\n    path K T2 C2 -> path K (TySum T1 T2) (CRight C2)\n\n(* A path in a function specifies an argument to continue. *)\n| PFun : forall T U (c : sem K T -> choice U),\n    forall (t : sem K T), path K U (c t) -> path K (T :-> U) (CArrow c).\n\nArguments PHere [K].\nArguments PFst [K T1 T2 C1 C2] _.\nArguments PSnd [K T1 T2 C1 C2] p.\nArguments PLeft [K T1 T2 C1] p.\nArguments PRight [K T1 T2 C2] p.\nArguments PFun [K T U c] t p.\n\n(** Isomorphism between A and B. *)\nInductive iso (A : Set) (B : Set) : Set :=\n| Iso : forall (constr : B -> A) (destr : A -> B),\n    (forall a, constr (destr a) = a) ->\n    (forall b, destr (constr b) = b) ->\n    iso A B.\n\nDefinition to {A} {B} (i : iso A B) : A -> B :=\n  match i with\n  | Iso _ _ _ destr _ _ => destr\n  end.\n\nDefinition from {A} {B} (i : iso A B) : B -> A :=\n  match i with\n  | Iso _ _ constr _ _ _ => constr\n  end.\n\n(** We want to interpret [T] at the type of its own paths.\n    But it seems unlikely that we can have literally\n    [K = path K T C]; isomorphism is the next best thing.\n\n    The poorly chosen name of [initial] refers to the fact\n    that this somehow corresponds to an initial algebra\n    construction. *)\nDefinition initial (K : Set) (T : type) (C : choice T) : Type :=\n  iso K (path K T C).\n\n(** The predicate [chosen T C x] states that\n    a value [x : sem K T] matches the given [choice]. *)\nInductive chosen\n          {K : Set}\n  : forall (T : type), choice T -> sem K T -> Set :=\n| ChUnit : chosen TyUnit CUnit tt\n| ChProduct : forall T1 T2 C1 C2 x1 x2,\n    chosen T1 C1 x1 -> chosen T2 C2 x2 -> chosen (TyProduct T1 T2) (CProduct C1 C2) (x1, x2)\n| ChLeft : forall T1 T2 C1 x1,\n    chosen T1 C1 x1 -> chosen (TySum T1 T2) (CLeft C1) (inl x1)\n| ChRight : forall T1 T2 C2 x2,\n    chosen T2 C2 x2 -> chosen (TySum T1 T2) (CRight C2) (inr x2)\n| ChArrow : forall T U c x,\n    (forall t, chosen U (c t) (x t)) -> chosen (T :-> U) (CArrow c) x\n| ChAlpha : forall x, chosen TyAlpha CAlpha x.\n\nArguments ChProduct [K T1 T2 C1 C2 x1 x2] _ _.\nArguments ChLeft [K T1 T2 C1 x1] _.\nArguments ChRight [K T1 T2 C2 x2] _.\nArguments ChArrow [K T U c x] _.\nArguments ChAlpha [K] _.\n\n(** Given a path [p : path K T C] and a (chosen) value [x : sem K T],\n    we can follow the path to a leaf of type [K]. *)\nFixpoint index {K : Set} {T : type} {C : choice T} {x : sem K T} (k : chosen T C x) (p : path K T C) : K :=\n  match p in path _ T C return forall x, chosen T C x -> K with\n  | PHere =>\n    fun _ k =>\n      match\n        k in chosen _ CAlpha x\n        return K\n      with\n      | ChAlpha x => x\n      end\n  | PFun t p1 =>\n    fun _ k =>\n      match\n        k in chosen _ (@CArrow _ T U c) r\n        return forall t, path K U (c t) -> K\n      with\n      | ChArrow k1 => fun t p1 => index (k1 t) p1\n      end t p1\n  | @PFst _ T1 _ C1 _ p1 =>\n    fun _ k1 =>\n      match\n        k1 in chosen _ (@CProduct _ T1 _ C1 _) r\n        return path _ T1 C1 -> K\n      with\n      | ChProduct k1 _ => fun p1 => index k1 p1\n      end p1\n  | @PSnd _ _ T2 _ C2 p2 =>\n    fun _ k =>\n      match\n        k in chosen _ (@CProduct _ _ T2 _ C2) r\n        return path K T2 C2 -> K\n      with\n      | ChProduct _ k2 =>\n        fun p2 => index k2 p2\n      end p2\n  | @PLeft _ T1 _ C1 p1 =>\n    fun _ k =>\n      match\n        k in chosen _ (@CLeft _ T1 _ C1) r\n        return path K T1 C1 -> K\n      with\n      | ChLeft k1 => fun p1 => index k1 p1\n      end p1\n  | @PRight _ _ T2 C2 p2 =>\n    fun _ k =>\n      match\n        k in chosen _ (@CRight _ _ T2 C2) r\n        return path K T2 C2 -> K\n      with\n      | ChRight k2 => fun p2 => index k2 p2\n      end p2\n  end x k.\n\n(** A property that should be satisfied by values produced\n    by our generator (to be defined): every leaf encodes\n    the path to itself. *)\nDefinition generates {K : Set} {T : type} {C : choice T} (i : initial K T C) (x : sem K T) (k : chosen T C x) :=\n  forall (p : path K T C), index k p = from i p.\n\nInductive variance : Set :=\n| CO : variance\n| CONTRA : variance.\n\nDefinition covary (co : variance) : variance :=\n  match co with\n  | CO => CONTRA\n  | CONTRA => CO\n  end.\n\nInductive variant : variance -> type -> Set :=\n| VAlpha : variant CO TyAlpha\n| VUnit : forall co, variant co TyUnit\n| VZero : forall co, variant co TyZero\n| VProduct : forall co {T1 T2},\n    variant co T1 -> variant co T2 -> variant co (TyProduct T1 T2)\n| VSum : forall co {T1 T2},\n    variant co T1 -> variant co T2 -> variant co (TySum T1 T2)\n| VArrow : forall co {T U},\n    variant (covary co) T ->\n    variant co U ->\n    variant co (T :-> U).\n\nDefinition switch {U : Type} (co : variance) (K : U) (H : U) :=\n  match co with\n  | CO => K\n  | CONTRA => H\n  end.\n\nLemma switch_covary :\n  forall {U : Type} (co : variance),\n    switch (covary co) = (fun (K H : U) => switch co H K).\nProof.\n  intros.\n  destruct co; auto.\nQed.\n\nFixpoint map_co\n         {K H : Set} {T : type} {co : variance}\n         (v : variant co T) (f : K -> H)\n  : sem (switch co K H) T ->\n    sem (switch co H K) T :=\n  match\n    v in variant co T\n    return sem (switch co K H) T -> sem (switch co H K) T\n  with\n  | VAlpha => f\n  | VUnit _ => fun x => x\n  | VZero _ => fun x => x\n  | VProduct _ v1 v2 =>\n    fun x =>\n      match x with\n      | (x1, x2) => (map_co v1 f x1, map_co v2 f x2)\n      end\n  | VSum _ v1 v2 =>\n    fun x =>\n      match x with\n      | inl x1 => inl (map_co v1 f x1)\n      | inr x2 => inr (map_co v2 f x2)\n      end\n  | @VArrow co T U v1 v2 =>\n    fun x =>\n      let comap := eq_rect\n                     (switch (covary co))\n                     (fun sw => sem (sw K H) T -> sem (sw H K) T)\n                     (map_co v1 f)\n                     (fun K H => switch co H K)\n                     (switch_covary co)\n      in fun t => map_co v2 f (x (comap t))\n  end.\n\nDefinition covariant := variant CO.\n\nInductive project\n          {K : Set} {B : Set} (f : K -> B)\n  : forall (T : type) (C : @choice K T),\n    (path K T C -> B) ->\n    sem K T ->\n    sem B T ->\n    Set :=\n| ProjAlpha : forall x y, project f TyAlpha CAlpha (fun PHere => y) x y\n| ProjUnit : project f TyUnit CUnit (fun p => match p with end) tt tt\n| ProjProduct : forall T1 T2 C1 C2 g1 g2 x1 x2 y1 y2,\n    project f T1 C1 g1 x1 y1 -> project f T2 C2 g2 x2 y2 ->\n    project f (TyProduct T1 T2) (CProduct C1 C2)\n            (fun p =>\n               match\n                 p in path _ _ (@CProduct _ T1 T2 C1 C2)\n                 return forall A,\n                   (path _ T1 C1 -> A) -> (path _ T2 C2 -> A) -> A\n               with\n               | PFst p1 => fun _ g1 _ => g1 p1\n               | PSnd p2 => fun _ _ g2 => g2 p2\n               end _ g1 g2) (x1, x2) (y1, y2)\n| ProjLeft : forall T1 T2 C1 g1 x1 y1,\n    project f T1 C1 g1 x1 y1 ->\n    project f (TySum T1 T2) (CLeft C1)\n            (fun p =>\n               match\n                 p in path _ _ (@CLeft _ T1 _ C1)\n                 return forall A, (path _ T1 C1 -> A) -> A\n               with\n               | PLeft p1 => fun _ g1 => g1 p1\n               end _ g1) (inl x1) (inl y1)\n| ProjRight : forall T1 T2 C2 g2 x2 y2,\n    project f T2 C2 g2 x2 y2 ->\n    project f (TySum T1 T2) (CRight C2)\n            (fun p =>\n               match\n                 p in path _ _ (@CRight _ _ T2 C2)\n                 return forall A, (path _ T2 C2 -> A) -> A\n               with\n               | PRight p2 => fun _ g2 => g2 p2\n               end _ g2) (inr x2) (inr y2)\n| ProjArrow : forall T U c g x y (v : covariant T),\n    (forall (t : sem K T),\n        project f U (c t) (g t) (x t) (y (map_co v f t))) ->\n    project f (T :-> U) (CArrow c)\n            (fun p =>\n               match\n                 p in path _ _ (@CArrow _ T U c)\n                 return forall A, (forall t, path _ U (c t) -> A) -> A\n               with\n               | PFun t pf => fun _ g => g t pf\n               end _ g) x y.\n\n(** * Properties of test case generators *)\n\n(** Ordering between individual inputs.\n    [x] subsumes [y] if [x] distinguishes polymorphic functions\n    better than [y]. *)\nDefinition\n  subsumes {K H : Set} {T : type} (S : Set -> Set)\n  (x : sem K T) (y : sem H T) : Prop :=\n  forall (f g : forall {L}, sem L T -> S L), f x = g x -> f y = g y.\n\n(** Completeness.\n    Every possible input [y] is subsumed\n    by a generated test case [x]. *)\nDefinition\n  complete (T : type) (S : Set -> Set)\n  (Generated : forall K, sem K T -> Prop) : Prop :=\n  forall H (y : sem H T), exists K x, Generated K x /\\ subsumes S x y.\n\n(** Canonicity properties. *)\n\n(** Optimality of a test case.\n    Every generated test case [x] is as general as possible:\n    if another [y] subsumes [x], then [x] also subsumes [y]. *)\nDefinition\n  optimality (T : type) (S : Set -> Set)\n  (Generated : forall K, sem K T -> Prop) : Prop :=\n  forall K x, Generated K x -> forall H (y : sem H T), subsumes S x y -> subsumes S y x.\n\n(** Non-redundancy.\n    Generated test cases don't subsume each other. *)\nDefinition\n  non_redundant (T : type) (S : Set -> Set)\n  (Generated : forall K, sem K T -> Prop) : Prop :=\n  forall K x H y, Generated K x -> Generated H y -> subsumes S x y -> JMeq x y.\n\n(*  \nInductive generate (K : Set) (T : type) (C : choice T) (x : \n*)\n", "meta": {"author": "Lysxia", "repo": "pelican", "sha": "b6f3bd90b38f5b7480151afdaec0f7622b5384e2", "save_path": "github-repos/coq/Lysxia-pelican", "path": "github-repos/coq/Lysxia-pelican/pelican-b6f3bd90b38f5b7480151afdaec0f7622b5384e2/pelican.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7088663213692147}}
{"text": "Section C2_1.\n\n  Parameter (A : Type) (R : A -> A -> Prop) (f : A -> A) (a : A).\n\n  Hypothesis Hf : forall x y, R x y -> R x (f y).\n  Hypothesis R_refl : forall x, R x x.\n\n  (* Variables x : A. *)\n\n  Lemma Lf : forall x, R x (f (f (f x))).\n  Proof.\n(*    intro x.\n    apply Hf.\n    apply Hf.\n    apply Hf.\n    apply R_refl. *)\n    intro; repeat apply Hf; apply R_refl.\n  Qed.\n\nEnd C2_1.\n\nRequire Import Arith.\n\nSection C2_2.\n\n  Check lt_n_Sn.\n  Check lt_trans.\n\n  Lemma lt_n_SSn : forall i, i < S (S i).\n  Proof.\n    intro i.\n    do 1 apply lt_trans with (2 := lt_n_Sn _). \n    apply lt_n_Sn.\n  Qed.\n\n  Lemma greater : forall n, exists p, n < p.\n  Proof.\n    intros n.\n    exists (S (S n)).\n    apply lt_n_SSn.\n  Qed.\n\n  Print greater.\n\n  Section absurd.\n\n    Hypothesis H : exists n, forall p, p < n.\n  \n    Lemma absurd : False.\n    Proof.\n      destruct H as [ m Hm ].\n      apply (lt_irrefl m).\n      apply Hm.\n    Qed.\n\n  End absurd.\n\n  Lemma L36 : 9 * 4 = 3 * 12.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Variable (A : Type).\n\n  Lemma eq_trans_on_A (x y z : A) : x = y -> y = z -> x = z.\n  Proof.\n    intros H1 H2.\n    (* rewrite H1, <- H2; reflexivity. *)\n    (* now rewrite H1. (* is the same as rewrite H1; easy. *) *)\n    (* subst; reflexivity. *)\n    (* symmetry; transitivity y; symmetry; trivial. *)\n    replace z with y; trivial.\n  Qed.\n\n  Lemma L1 : forall x y : nat,\n       x = S (S y) -> 2 <= x * x.\n  Proof.\n    intros x y H.\n    pattern x at 1.\n    rewrite H.\n  Admitted.\n\nEnd C2_2.\n\nSection C2_3.\n\n  Variable f : nat -> nat -> nat.\n\n  Hypothesis f_comm : forall x y, f x y = f y x.\n\n  Lemma L : forall x y z, f (f x y) z = f z (f y x).\n  Proof.\n    intros x y z.\n    rewrite (f_comm x y).\n    rewrite (f_comm _ z).\n    reflexivity.\n  Qed.\n\nEnd C2_3.\n\nRequire Import Omega Lia.\n\nLemma L' : forall n, n < 2 -> n = 0 \\/ n = 1.\nProof.\n  intros; lia.\nQed.\n\nLemma L2 : forall i, i < 2 -> i*i = i.\nProof.\n  intros i H.\n  destruct L' with (1 := H); subst i; trivial.\nQed.\n\nLemma or_comm : forall P Q : Prop, P \\/ Q -> Q \\/ P.\nProof.\n  intros ? ? []; [ right | left ]; assumption.\nQed.\n\nLemma not_ex_all_not : forall (A : Type) (P : A -> Prop),\n  (~ exists a:A, P a) -> forall a, ~ P a.\nProof.\n  intros A P H a H1.\n  unfold not in *.\n  apply H.\n  exists a.\n  trivial.\nQed.\n\nLemma all_not_not_ex (A : Type) (P : A -> Prop) :\n  (forall a, ~ P a) -> ~ exists a:A, P a.\nProof.\n  intros H (x & Hx).\n  apply (H x), Hx.\nQed.\n  \nLemma test_students : exists P : nat -> Prop, P 0 /\\ ~ P 1.\nProof.\n (*  exists (fun x => x < 1); lia. *)\n\n  exists (fun x : nat => 0 = x); lia.\n (* split.\n  + reflexivity.\n  + discriminate. *)\nQed.\n\nFixpoint factorial n :=\n  match n with\n    | 0 => 1\n    | S n => (S n) * factorial n\n  end.\n\nLemma factorial_prop n : forall p, 0 < p <= n -> exists q, factorial n = q * p.\nProof.\n  induction n as [ | n IHn ].\nAdmitted. \n\nLemma exf : exists f : nat -> nat,\n  forall n p, 0 < p -> p <= n -> exists q, f n = q * p.\nProof.\n  exists (fun _ => 0).\n  intros n p _ _.\n  exists 0.\n  simpl.\n  reflexivity.\nQed.\n  \nSection HO.\n\n  Variables (A : Type) (f : A -> A)\n            (f_self_inverse : forall a, f (f a) = a).\n  \n  Lemma f_onto : forall b, exists a, b = f a.\n  Proof.\n    intros b.\n    exists (f b).\n    rewrite f_self_inverse.\n    reflexivity.\n  Qed.\n\nEnd HO.\n\nRequire Import ZArith Ring.\n\nOpen Scope Z_scope.\n\nSection Z_sect.\n\n  Variable f : Z -> Z -> Z -> Z.\n\n  Goal forall x y z, f (x+y) z 0 = f (y+x+0) (z*(1+0)) (x-x).\n  Proof.\n    intros x y z.\n    f_equal; ring.\n    (*  \n      replace (x+y) with (y+x+0).\n      replace z with (z*(1+0)) at 1.\n      replace 0 with (x-x) at 3.\n      reflexivity. *)\n  Qed.\n\nEnd Z_sect.\n\nRequire Import Setoid.\n\nSection rewrite_equivalence.\n\n  Variable (A : Type) (P Q : A -> Prop).\n  Hypothesis E : forall a : A, P a <-> ~ Q a.\n\n  Goal (exists a, P a) -> ~ (forall x, Q x).\n  Proof.\n    intros (x & Hx) H1.\n    rewrite E in Hx.\n    apply Hx, H1.\n  Qed.\n  \n  \n\n\n\nPrint L2.\n\n\n\n\n  Check N.\n\n\n  Print Lf.", "meta": {"author": "DmxLarchey", "repo": "Introduction-to-Coq", "sha": "c2924b5284ef87143def1850520a25984dc0e724", "save_path": "github-repos/coq/DmxLarchey-Introduction-to-Coq", "path": "github-repos/coq/DmxLarchey-Introduction-to-Coq/Introduction-to-Coq-c2924b5284ef87143def1850520a25984dc0e724/C2_ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.70886631558837}}
{"text": "Require Import bool.\nRequire Import nat.\nRequire Import syntax.\nRequire Import eval.\nRequire Import state.\nRequire Import dictionary.\nRequire Import equiv.\n\nDefinition atrans_sound (atrans:aexp -> aexp) : Prop :=\n    forall (a:aexp), aequiv a (atrans a).\n\nDefinition btrans_sound (btrans:bexp -> bexp) : Prop :=\n    forall (b:bexp), bequiv b (btrans b).\n\nDefinition ctrans_sound (ctrans:com -> com) : Prop :=\n    forall (c:com), cequiv c (ctrans c).\n\nFixpoint btrans (fa:aexp -> aexp) (b:bexp) : bexp :=\n    match b with\n    | BTrue         => BTrue\n    | BFalse        => BFalse\n    | BEq a1 a2     =>\n        match (fa a1, fa a2) with\n        | (ANum n1, ANum n2)        => if eqb n1 n2 then BTrue else BFalse\n        | (a1', a2')                => BEq a1' a2'\n        end\n    | BLe a1 a2     =>\n        match (fa a1, fa a2) with\n        | (ANum n1, ANum n2)        => if leb n1 n2 then BTrue else BFalse\n        | (a1', a2')                => BLe a1' a2'\n        end\n    | BNot b1       =>\n        match (btrans fa b1) with\n        | BTrue     => BFalse\n        | BFalse    => BTrue\n        | b1'       => BNot b1'\n        end\n    | BAnd b1 b2    =>\n        match (btrans fa b1, btrans fa b2) with\n        | (BTrue, BTrue)    => BTrue\n        | (BTrue, BFalse)   => BFalse\n        | (BFalse, BTrue)   => BFalse\n        | (BFalse, BFalse)  => BFalse\n        | (b1', b2')        => BAnd b1' b2'\n        end\n    end.\n\nFixpoint ctrans (fa:aexp -> aexp)(fb:bexp -> bexp)(c:com) : com :=\n    match c with\n    | SKIP          => SKIP\n    | k ::= a       => k ::= (fa a)\n    | c1 ;; c2      => (ctrans fa fb c1) ;; (ctrans fa fb c2)\n    | CIf b c1 c2   => match (fb b) with\n                       | BTrue      => ctrans fa fb c1\n                       | BFalse     => ctrans fa fb c2\n                       | b'         => CIf b' (ctrans fa fb c1)\n                                              (ctrans fa fb c2)\n                       end\n    | CWhile b c1   => match (fb b) with\n                       | BTrue      => CWhile BTrue SKIP (* oo-loop all the same *)\n                       | BFalse     => SKIP\n                       | b'         => CWhile b' (ctrans fa fb c1)\n                       end\n    end.\n\nTheorem ctrans_is_sound : forall (fa:aexp -> aexp) (fb:bexp -> bexp), \n    atrans_sound fa -> btrans_sound fb -> ctrans_sound (ctrans fa fb).\nProof.\n    intros fa fb Ha Hb. unfold ctrans_sound. intros c. induction c;\n    try (apply refl_cequiv);\n    try (apply CAss_congruence; apply Ha);\n    try (apply CSeq_congruence; assumption).\n    - destruct (fb b) eqn:E; simpl;\n        try (rewrite E; apply CIf_congruence; \n                try (assumption);\n                try (rewrite <- E; apply Hb)\n            ).\n        + apply trans_cequiv with c1.\n            { apply if_true. rewrite <- E. apply Hb. }\n            { rewrite E. assumption. }\n        + apply trans_cequiv with c2.\n            { apply if_false. rewrite <- E. apply Hb. }\n            { rewrite E. assumption. }\n    - destruct (fb b) eqn:E; simpl; rewrite E;\n        try ( apply CWhile_congruence; try (assumption);\n              rewrite <- E; apply Hb\n            ).\n        + apply while_true. rewrite <- E. apply Hb.\n        + apply while_false. rewrite <- E. apply Hb.\nQed.\n\n\nTheorem btrans_is_sound : forall (fa:aexp -> aexp), \n    atrans_sound fa -> btrans_sound (btrans fa).\nProof.\n    intros fa Ha b e. induction b; \n    try (reflexivity).\n    - simpl; rename a into a1; rename a0 into a2;\n      destruct (fa a1) eqn:E1, (fa a2) eqn:E2;\n      try (rewrite <- E1, <- E2, (Ha a1), (Ha a2); reflexivity).\n      rewrite (Ha a1), (Ha a2), E1, E2; simpl; destruct (eqb n n0); reflexivity.\n    - simpl; rename a into a1; rename a0 into a2;\n      destruct (fa a1) eqn:E1, (fa a2) eqn:E2;\n      try (rewrite <- E1, <- E2, (Ha a1), (Ha a2); reflexivity).\n      rewrite (Ha a1), (Ha a2), E1, E2; simpl; destruct (leb n n0); reflexivity.\n    - simpl. destruct (btrans fa b); rewrite IHb; reflexivity.\n    - simpl. destruct (btrans fa b1), (btrans fa b2); rewrite IHb1, IHb2;\n        reflexivity.\nQed.\n\n\nLemma compose_aexp_sound : forall (f g:aexp -> aexp),\n    atrans_sound f -> atrans_sound g -> atrans_sound (fun x => g (f x)).\nProof.\n    intros f g Hf Hg. unfold atrans_sound, aequiv. intros a e.\n    apply eq_trans with (aeval e (f a)).\n    - apply Hf.\n    - apply Hg.\nQed.\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/sf/transform.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8175744739711884, "lm_q1q2_score": 0.7088663108524377}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Max Omega Wellfounded Bool.\n\nRequire Import list_focus utils_tac utils_list.\n\nSet Implicit Arguments.\n\nFact interval_dec a b i : { a <= i < b } + { i < a \\/ b <= i }.\nProof.\n  destruct (le_lt_dec b i).\n  right; omega.\n  destruct (le_lt_dec a i).\n  left; omega.\n  right; omega.\nQed.\n\nDefinition lsum := fold_right plus 0.\nDefinition lmax := fold_right max 0.\n\nFact lsum_app l r : lsum (l++r) = lsum l+lsum r.\nProof.\n  induction l as [ | x l IHl ]; simpl; auto; rewrite IHl; omega.\nQed.\n\nSection new.\n\n  Definition nat_new l := S (lmax l).\n\n  Fact nat_new_spec l : ~ In (nat_new l) l.\n  Proof.\n    assert (forall x, In x l -> x < nat_new l) as H.\n      induction l as [ | x l IHl ].\n      intros _ [].\n      intros y [ [] | Hy ]; apply le_n_S;\n        [ apply le_max_l | ].\n      apply IHl, le_S_n in Hy.\n      apply le_trans with (1 := Hy), le_max_r.\n    intros C; apply H in C; omega.\n  Qed.\n\nEnd new.\n\nLocal Notation Zero := false.\nLocal Notation One  := true.\n\nFixpoint div2 n : nat * bool :=\n  match n with\n    | 0 => (0,Zero)\n    | 1 => (0,One)\n    | S (S n) => let (p,b) := div2 n in (S p,b)\n  end.\n\nFact div2_spec n : match div2 n with \n                     | (p,One)  => n = 2*p+1 \n                     | (p,Zero) => n = 2*p\n                   end.\nProof.\n  induction n as [ [ | [ | n ] ] IHn ] using (well_founded_induction lt_wf); simpl; auto.\n  specialize (IHn n).\n  destruct (div2 n) as (p,[]); simpl in * |- *; omega.\nQed.\n\nFixpoint div2_2p1 p : div2 (2*p+1) = (p,One).\nProof.\n  destruct p as [ | p ].\n  simpl; auto.\n  replace (2*S p+1) with (S (S (2*p+1))) by omega.\n  unfold div2; fold div2; rewrite div2_2p1; auto.\nQed.\n\nFixpoint div2_2p0 p : div2 (2*p) = (p,Zero).\nProof.\n  destruct p as [ | p ].\n  simpl; auto.\n  replace (2*S p) with (S (S (2*p))) by omega.\n  unfold div2; fold div2; rewrite div2_2p0; auto.\nQed.\n\nFixpoint pow2 p := \n  match p with \n    | 0   => 1\n    | S p => 2*pow2 p\n  end.\n\nSection pow2_bound.\n\n  Let loop := fix loop x n :=\n    match n with \n      | 0 => 0\n      | S n => match div2 x with \n                 | (0,_) => 0\n                 | (p,_) => S (loop p n)\n               end\n    end.\n\n  Let loop_prop n : forall x, x < n -> x < pow2 (S (loop x n)).\n  Proof.\n    induction n as [ | n IHn ]; intros x Hx.\n    omega.\n    unfold loop; fold loop.\n    generalize (div2_spec x).\n    destruct (div2 x) as ([ | p ],[]); intros H.\n    simpl; omega.\n    simpl; omega.\n    specialize (IHn (S p)); spec in IHn.\n    omega.\n    simpl in IHn |- *; omega.\n    specialize (IHn (S p)); spec in IHn.\n    omega.\n    simpl in IHn |- *; omega.\n  Qed.\n\n  Definition find_pow2 x := S (loop (pred x) x).\n\n  Fact find_pow2_geq x : 1 <= find_pow2 x.\n  Proof. unfold find_pow2; omega. Qed.\n\n  Fact find_pow2_prop x : x <= pow2 (find_pow2 x).\n  Proof.\n    unfold find_pow2; destruct x.\n    simpl; omega.\n    apply loop_prop; auto. \n  Qed.\n\nEnd pow2_bound.\n\nSection nat_sorted.\n   \n  Definition nat_sorted ll := forall l a m b r, ll = l ++ a :: m ++ b :: r -> a < b.\n  \n  Fact in_nat_sorted_0 : nat_sorted nil.\n  Proof. intros [] ? ? ? ? ?; discriminate. Qed.\n  \n  Fact in_nat_sorted_1 x : nat_sorted (x::nil).\n  Proof. intros [ | ? [] ] ? [] ? ? ?; discriminate. Qed.\n  \n  Fact in_nat_sorted_2 x y ll : x < y -> nat_sorted (y::ll) -> nat_sorted (x::y::ll).\n  Proof.\n    intros H1 H2 l a m b r H3.\n    destruct l as [ | u l ].\n    inversion H3; subst.\n    destruct m as [ | v m ].\n    inversion H4; subst; auto.\n    inversion H4; subst.\n    apply lt_trans with (1 := H1), (H2 nil _ m _ r); auto.\n    inversion H3; subst.\n    apply (H2 l _ m _ r); auto.\n  Qed.\n  \n  Fact in_nat_sorted_3 x ll : Forall (lt x) ll -> nat_sorted ll -> nat_sorted (x::ll).\n  Proof.\n    induction 1 as [ | y ll Hll IHl ].\n    intro; apply in_nat_sorted_1.\n    intros H.\n    apply in_nat_sorted_2; auto.\n  Qed.\n  \n  Fact nat_sorted_cons_inv x ll : nat_sorted (x::ll) -> nat_sorted ll.\n  Proof. intros H l a m b r ?; apply (H (x::l) _ m _ r); subst; solve list eq. Qed.\n  \n  Fact nat_sorted_Forall x ll : nat_sorted (x::ll) -> Forall (lt x) ll.\n  Proof. \n    rewrite Forall_forall; intros H y Hy.\n    apply in_split in Hy.\n    destruct Hy as (l & r & ?); subst.\n    apply (H nil _ l _ r); auto.\n  Qed.\n  \n  Fact nat_sorted_head_inv x y ll : nat_sorted (x::y::ll) -> x < y.\n  Proof. intros H; apply (H nil _ nil _ ll); solve list eq. Qed.\n\n  Variable P : list nat -> Type.\n  \n  Hypothesis (HP0 : P nil).\n  Hypothesis (HP1 : forall x, P (x::nil)).\n  Hypothesis (HP2 : forall x y l, x < y -> P (y::l) -> P (x::y::l)).\n  \n  Theorem nat_sorted_rect l : nat_sorted l -> P l.\n  Proof.\n    induction l as [ [ | x [ | y l ] ] IHl ] using (measure_rect (@length _)).\n    intro; apply HP0.\n    intro; apply HP1.\n    intros H; apply HP2. \n    revert H; apply nat_sorted_head_inv.\n    apply IHl.\n    rew length; omega.\n    revert H; apply nat_sorted_cons_inv.\n  Qed.\n  \nEnd nat_sorted.\n\nFact nat_sorted_injective ll : nat_sorted ll -> list_injective ll.\nProof.\n  intros H l a m b r E; generalize (H _ _ _ _ _  E); omega.\nQed.\n\nFixpoint nat_list_insert x l :=\n  match l with\n    | nil  => x::nil\n    | y::l => if x <? y then x::y::l else\n              if y <? x then y::nat_list_insert x l else y::l\n  end.\n\nFact nat_list_insert_length x l : length (nat_list_insert x l) <= S (length l).\nProof.\n  induction l as [ | y l IHl ]; simpl.\n  omega.\n  destruct (x <? y); simpl; try omega.\n  destruct (y <? x); simpl; omega.\nQed.\n  \nFact nat_list_insert_incl x l : incl (nat_list_insert x l) (x::l)\n                             /\\ incl (x::l) (nat_list_insert x l).\nProof.\n  split. \n  \n  induction l as [ | y l IHl ]; simpl.\n  intro; auto.\n  destruct (x <? y); destruct (y <? x).\n  intro; auto.\n  intro; auto.\n  intros ? [ [] | H ]; simpl; auto.\n  apply IHl in H; simpl in H; tauto.\n  intro; simpl; tauto.\n\n  induction l as [ | y l IHl ]; simpl.\n  intro; auto.\n  generalize (Nat.ltb_lt x y) (Nat.ltb_lt y x).\n  destruct (x <? y); destruct (y <? x); intros H1 H2 z; auto.\n  intros [ Hz | [ Hz | Hz ] ]; subst.\n  right; apply IHl; left; auto.\n  left; auto.\n  right; apply IHl; right; auto.\n  destruct (lt_eq_lt_dec x y) as [ [ H | ] | H ].\n  apply H1 in H; discriminate.\n  2: apply H2 in H; discriminate.\n  intros [ Hz | [ Hz | Hz ] ]; subst; auto.\n  left; auto.\n  left; auto.\n  right; auto.\nQed.\n  \nFact nat_list_insert_Forall (P : nat -> Prop) x l : \n      P x -> Forall P l -> Forall P (nat_list_insert x l).\nProof.\n  do 2 rewrite Forall_forall; intros H1 H2 y Hy.\n  apply nat_list_insert_incl in Hy.\n  destruct Hy; subst; auto.\nQed.\n  \nFact nat_list_insert_sorted x l : nat_sorted l -> nat_sorted (nat_list_insert x l).\nProof.\n  induction l as [ | y l IHl ]; simpl.\n  intro; apply in_nat_sorted_1.\n  intros H.\n  generalize (Nat.ltb_lt x y) (Nat.ltb_lt y x).\n  destruct (x <? y); destruct (y <? x); intros H1 H2.\n  apply proj1 in H1; spec in H1; auto.\n  apply proj1 in H2; spec in H2; auto.\n  omega.\n  apply in_nat_sorted_2; auto; tauto.\n  apply in_nat_sorted_3.\n  apply nat_list_insert_Forall.\n  tauto.\n  apply nat_sorted_Forall; auto.\n  apply IHl; revert H; apply nat_sorted_cons_inv.\n  auto.\nQed.\n\nDefinition nat_sort := fold_right (nat_list_insert) nil.\n\nFact nat_sort_length l : length (nat_sort l) <= length l.\nProof.\n  induction l as [ | x l IHl ]; simpl.\n  omega.\n  apply le_trans with (1 := nat_list_insert_length _ _); omega.\nQed.\n\nFact nat_sort_eq l : incl (nat_sort l) l /\\ incl l (nat_sort l).\nProof.\n  induction l as [ | x l IHl ]; simpl; split; intros y Hy; auto.\n  apply nat_list_insert_incl in Hy; simpl.\n  destruct Hy as [ | Hy ]; auto; right; apply IHl; auto.\n  apply nat_list_insert_incl.\n  destruct Hy; [ left | right ]; auto.\n  apply IHl; auto.\nQed.\n\nFact nat_sort_sorted l : nat_sorted (nat_sort l).\nProof.\n  induction l as [ | x l IHl ].\n  apply in_nat_sorted_0.\n  simpl; apply nat_list_insert_sorted; auto.\nQed.\n\nFact nat_sinc (f : nat -> nat) a b : \n      (forall x, a <= x < b -> f x < f (S x)) \n   -> (forall x y, a <= x < y /\\ y <= b -> f x < f y).\nProof.\n  intros H1.\n  assert (forall n m, n <= m <= b - a -> f (a+n) <= f (a+m)) as H2.\n    intros n m (H2 & H3); revert H2 H3.\n    induction 1 as [ | m Hm IH ]; auto.\n    intros H. spec in IH. omega.\n    apply le_trans with (1 := IH).\n    replace (a+S m) with (S (a+m)) by omega.\n    apply lt_le_weak, H1; omega.\n  assert (forall n m, n < m <= b - a -> f (a+n) < f (a+m)) as H3.\n    unfold lt at 1; intros n m H.\n    specialize (H1 (a+n)).\n    spec in H1.\n    omega.\n    apply lt_le_trans with (1 := H1).\n    replace (S (a+n)) with (a+S n) by omega.\n    apply H2; auto.\n  intros x y H4.\n  replace x with (a+(x-a)) by omega.\n  replace y with (a+(y-a)) by omega.\n  apply H3.\n  omega.\nQed.\n\nFact nat_sinc_inj f a b : \n      (forall x y,  a <= x < y /\\ y <= b -> f x < f y) \n   -> (forall x y,  a <= x <= b -> a <= y <= b -> f x = f y -> x = y).\nProof.\n  intros H0 x y Hx Hy.\n  destruct Hx; destruct Hy.\n  destruct (lt_eq_lt_dec x y) as [ [ ? | ? ] | ? ]; auto.\n  specialize (H0 x y).\n  spec in H0; repeat split; auto; intro; omega.\n  specialize (H0 y x).\n  spec in H0; repeat split; auto; intro; omega.\nQed.\n\n", "meta": {"author": "uds-psl", "repo": "ill-undecidability", "sha": "0bfda1a33cb3411c8f2c0263e15d5c85c090721d", "save_path": "github-repos/coq/uds-psl-ill-undecidability", "path": "github-repos/coq/uds-psl-ill-undecidability/ill-undecidability-0bfda1a33cb3411c8f2c0263e15d5c85c090721d/coq/Utils/utils_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7088663078805768}}
{"text": "(* Based on the imp example in coind,\n   extracted to a single-file.\n *)\n(* Developed with Coq 8.9.1 *)\n\nRequire Import String.\nRequire Import ZArith.\nRequire Import List.\n\nSet Implicit Arguments.\n\nLocal Open Scope Z.\nImport List.ListNotations.\nLocal Open Scope list.\nLocal Open Scope string.\n\n(** * The syntax of IMP programs *)\n\nInductive AExp :=\n  | var : string -> AExp\n  | con : Z -> AExp\n  | div : AExp -> AExp -> AExp\n  | plus : AExp -> AExp -> AExp\n  .\n\nInductive BExp :=\n  | bcon : bool -> BExp\n  | le : AExp -> AExp -> BExp\n  | not : BExp -> BExp\n  | and : BExp -> BExp -> BExp\n  .\n\nInductive Stmt :=\n  | assign : string -> AExp -> Stmt\n  | cond : BExp -> Stmt -> Stmt -> Stmt\n  | while : BExp -> Stmt -> Stmt\n  | seq : Stmt -> Stmt -> Stmt\n  | skip : Stmt\n  .\n\nInductive Pgm :=\n    pgm : list string -> Stmt -> Pgm.\n\n(** Here is the sum program *)\nDefinition sum_pgm N : Pgm :=\n pgm [\"n\"; \"sum\"]\n(seq (assign \"n\" (con N))\n(seq (assign \"sum\" (con 0))\n     (while (not (le (var \"n\") (con 0)))\n     (seq (assign \"sum\" (plus (var \"sum\") (var \"n\")))\n          (assign \"n\" (plus (var \"n\") (con (-1)))))))).\n\n(** * The semantics of IMP programs *)\n\nDefinition Env := list (string * Z).\nDefinition empty_env : Env := [].\nFixpoint get x (env:Env) :=\n  match env with\n  | [] => None\n  | (x',v)::env' =>\n    if string_dec x x' then Some v else get x env'\n  end.\nFixpoint set x v (env:Env) :=\n  match env with\n  | [] => []\n  | (x',v')::env' =>\n    if string_dec x x' then (x,v)::env' else (x',v')::set x v env'\n  end.\n  (* \"simpl\" should reduce set if concrete values are given for both variables *)\n\n(* ** These \"step\" types together define single execution steps  *)\nInductive step_e : (AExp * Env) -> (AExp * Env) -> Prop :=\n  | step_var: forall v x env, get v env = Some x ->\n      step_e (var v, env) (con x, env)\n  | step_plus: forall x y env,\n      step_e (plus (con x) (con y), env) (con (Z.add x y), env)\n  | step_div: forall x y env,\n      y <> 0%Z ->\n      step_e (div (con x) (con y), env) (con (Z.div x y), env)\n  | cong_plus_r: forall e1 e2 e2' env env',\n      step_e (e2, env) (e2', env') ->\n      step_e (plus e1 e2, env) (plus e1 e2', env')\n  | cong_plus_l: forall e2 e1 e1' env env',\n      step_e (e1, env) (e1', env') ->\n      step_e (plus e1 e2, env) (plus e1' e2, env')\n  | cong_div_r: forall e1 e2 e2' env env',\n      step_e (e2, env) (e2', env') ->\n      step_e (div e1 e2, env) (div e1 e2', env')\n  | cong_div_l: forall e2 e1 e1' env env',\n      step_e (e1, env) (e1', env') ->\n      step_e (div e1 e2, env) (div e1' e2, env')\n  .\n\n(* These abbreviations capture the pattern of the congruence rules *)\nNotation cong_l op R1 R2 :=\n  (forall a env a' env', R1 (a,env) (a',env') ->\n   forall b, R2 (op a b, env) (op a' b, env')).\nNotation cong_r op nf R1 R2 :=\n  (forall b env b' env', R1 (b,env) (b',env') ->\n   forall a, R2 (op (nf a) b, env) (op (nf a) b', env')).\nNotation cong_1 op R1 R2 :=\n  (forall a env a' env', R1 (a,env) (a',env') -> R2 (op a, env) (op a', env')).\n\nInductive step_b : (BExp * Env) -> (BExp * Env) -> Prop :=\n  | eval_le : forall v1 v2 env,\n      step_b (le (con v1) (con v2), env) (bcon (Z.leb v1 v2), env)\n  | eval_not : forall b env,\n      step_b (not (bcon b), env) (bcon (negb b), env)\n  | eval_and : forall b e env,\n      step_b (and (bcon b) e, env) (if b then e else bcon false, env)\n  | cong_le_r : cong_r le con step_e step_b\n  | cong_le_l : cong_l le step_e step_b\n  | cong_not : cong_1 not step_b step_b\n  | cong_and : cong_l and step_b step_b\n  .\n\nInductive step_s : (Stmt * Env) -> (Stmt * Env) -> Prop :=\n  | exec_assign : forall x v v0 env,  get x env = Some v0 ->\n      step_s (assign x (con v),env) (skip, set x v env)\n  | cong_assign : forall x,\n      cong_1 (assign x) step_e step_s\n  | exec_seq : forall s env,\n      step_s (seq skip s,env) (s,env)\n  | cong_seq : cong_l seq step_s step_s\n  | exec_cond : forall b s1 s2 env,\n      step_s (cond (bcon b) s1 s2, env) (if b then s1 else s2, env)\n  | cong_cond : forall b b' env env' s1 s2, step_b (b,env) (b',env') ->\n      step_s (cond b s1 s2,env) (cond b' s1 s2,env')\n  | exec_while : forall b s env,\n      step_s (while b s,env) (cond b (seq s (while b s)) skip, env)\n  .\n\nInductive step_p : (Pgm * Env) -> (Pgm * Env) -> Prop :=\n  | exec_init: forall x xs s env,\n      step_p (pgm (x::xs) s,env) (pgm xs s, (x,0)::env)\n  | exec_body: forall s env s' env',\n      step_s (s, env) (s', env') ->\n      step_p (pgm nil s, env) (pgm nil s', env')\n  .\n\n(** Now we verify the program *)\nRequire Import proof_system.\n\n(** The claim about the loop says that running the loop in any enviroment\n    with a non-negative n finishes with n set to zero, and sum increased\n    from it's original value by the sum of numbers 0+1+...+n.\n *)\nInductive sum_spec : Spec (Pgm * Env) :=\n | sum_claim: forall n, 0 <= n ->\n   sum_spec\n     (pgm [\"n\"; \"sum\"]\n       (seq (assign \"n\" (con n))\n       (seq (assign \"sum\" (con 0))\n            (while (not (le (var \"n\") (con 0)))\n            (seq (assign \"sum\" (plus (var \"sum\") (var \"n\")))\n                 (assign \"n\" (plus (var \"n\") (con (-1))))))))\n     ,[])\n     (fun cfg' => cfg' = (pgm [] skip, [(\"sum\",((n + 1) * n)/2);(\"n\",0)]))\n | sum_loop_claim : forall env n, get \"n\" env = Some n -> 0 <= n ->\n                    forall s, get \"sum\" env = Some s ->\n      sum_spec\n         (pgm []\n           (while (not (le (var \"n\") (con 0)))\n             (seq (assign \"sum\" (plus (var \"sum\") (var \"n\")))\n                  (assign \"n\" (plus (var \"n\") (con (-1))))))\n         ,env)\n      (fun cfg' => fst cfg' = pgm [] skip /\\\n         snd cfg' = set \"n\" 0 (set \"sum\" (s + ((n + 1) * n)/2) env)).\n\n(* Some lemmas about enviroment stuff *)\nLtac env_ind_tac env :=\n  induction env as [|[]];try reflexivity;simpl;\n  repeat match goal with\n  | [ |- context [string_dec ?a ?b]] => destruct (string_dec a b);simpl;try congruence\n  end.\n\nLemma env_set_id: forall x v env,\n    get x env = Some v ->\n    set x v env = env.\nProof.\n  env_ind_tac env.\n  intro. f_equal. tauto.\nQed.\n\nLemma env_set_eq:\n  forall x v1 v2 env,\n    set x v1 (set x v2 env) = set x v1 env.\nProof. env_ind_tac env. Qed.\n\nLemma env_set_ne_comm:\n  forall x1 x2, x1 <> x2 ->\n  forall v1 v2 env,\n    set x1 v1 (set x2 v2 env) = set x2 v2 (set x1 v1 env).\nProof. env_ind_tac env. Qed.\n\nLemma env_set_set: forall x1 x2 v1 v2 env,\n    set x1 v1 (set x2 v2 env) =\n    if string_dec x1 x2\n    then set x1 v1 env\n    else set x2 v2 (set x1 v1 env).\nProof. env_ind_tac env. Qed.\n\nDefinition env_has x env: bool :=\n  match get x env with\n  | Some _ => true\n  | None => false\n  end.\n\nLemma env_has_get x v env:\n  get x env = Some v ->\n  env_has x env = true.\nProof.\n  unfold env_has;intros ->;reflexivity.\nQed.\n\nLemma env_get_set x x' v env:\n  get x (set x' v env) =\n  if string_dec x x'\n  then if env_has x env then Some v else None\n  else get x env.\nProof. unfold env_has; env_ind_tac env. Qed.\n\nLemma env_has_set x x' v env:\n  env_has x (set x' v env) = env_has x env.\nProof.\n  unfold env_has.\n  rewrite env_get_set.\n  unfold env_has.\n  destruct (string_dec x x');[|reflexivity].\n  destruct (get x env);reflexivity.\nQed.\n\nLtac step_tac :=\n  match goal with\n  | [ |- step_p _ _] => econstructor;step_tac\n  | [ |- step_s _ _] => econstructor;step_tac\n  | [ |- step_b _ _] => econstructor;step_tac\n  | [ |- step_e _ _] => econstructor;step_tac\n  | [ |- get _ _ = _] => rewrite ?env_get_set;(reflexivity || eassumption)\n  end.\n\nLtac run := repeat first[\n   eapply dtrans;[constructor|]\n  |eapply ddone;simpl;split;[reflexivity|]\n  |eapply dstep;[step_tac|]].\n\nRequire Import Recdef.\nFunction sum_to (n:Z) { wf (fun x y => 0 <= x < y) n } : Z :=\n  if Z_lt_ge_dec 0 n then n + sum_to (n - 1) else 0.\nintros;omega.\nexact (Z.lt_wf 0).\nDefined.\n\nLemma sum_algebra: forall s n, 0 < n ->\n  s + n + (n + -1 + 1) * (n + -1) / 2\n           = s + (n + 1) * n / 2.\nProof.\n  intros s n H.\n  rewrite <- Z.add_assoc.\n  f_equal.\n  rewrite <- Z.add_assoc, Z.add_0_r.\n  rewrite <- Z.div_add_l by omega.\n  f_equal.\n  rewrite Z.mul_add_distr_r, Z.mul_add_distr_l.\n  omega.\nQed.\n\nLemma sum_ok : sound step_p sum_spec.\napply proved_sound;destruct 1.\n\n{ (* Overall claim, easily proved with loop claim *)\n  eapply sstep;[solve[step_tac]|].\n  run;[reflexivity || assumption ..|].\n  destruct k';simpl.\n  destruct 1 as [-> ->].\n  apply ddone.\n  reflexivity.\n}\n\n\neapply sstep;[solve[step_tac]|].\nrun.\ndestruct (Z.leb_spec n 0);simpl.\n\n(* when n = 0, loop exits.\n   To conclude, need to prove that the initial\n   environment env is an acceptable result *)\nrun.\nreplace n with 0 in H |- * by auto with zarith.\nrewrite (env_set_id \"sum\") by (rewrite H1;f_equal;auto with zarith).\nrewrite (env_set_id \"n\") by assumption.\nreflexivity.\n\n(* when n > 0, execution goes through the loop body,\n   then sum_loop_claim is applied by transitivity,\n   which takes us to a state satisfying the goal *)\nrun.\n{ rewrite env_get_set, ?env_has_set.\n  simpl.\n  erewrite env_has_get by eassumption;reflexivity. }\n  omega.\n{ rewrite !env_get_set.\n  simpl.\n  erewrite env_has_get by eassumption;reflexivity. }\ndestruct k';simpl;intros [-> ->].\n\nrun.\nrewrite (env_set_set \"sum\" \"n\"). simpl.\nrewrite 2 env_set_eq.\nf_equal.\nf_equal.\napply sum_algebra.\nassumption.\nQed.", "meta": {"author": "runtimeverification", "repo": "k-vs-coq-language-frameworks", "sha": "c11b58199fd21015ff8b3cba36acb90ee07941a4", "save_path": "github-repos/coq/runtimeverification-k-vs-coq-language-frameworks", "path": "github-repos/coq/runtimeverification-k-vs-coq-language-frameworks/k-vs-coq-language-frameworks-c11b58199fd21015ff8b3cba36acb90ee07941a4/coq/imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7088663004985368}}
{"text": "Variables A B C : Prop.\nLemma ex6 : ((A -> B) /\\ (A -> C)) -> A -> (B /\\ C).\nProof.\n  intro HaImpliesHb_and_HaImpliesHc.\n  destruct HaImpliesHb_and_HaImpliesHc as [Ha_implies_Hb Ha_implies_Hc].\n  intro Ha.\n  split.\n    +\n      apply Ha_implies_Hb.\n      assumption.\n    +\n      apply Ha_implies_Hc.\n      assumption.\nQed.", "meta": {"author": "alvarofpp", "repo": "course-coq", "sha": "64dc0d9a2e6564f9fa5df508fa946a137901feee", "save_path": "github-repos/coq/alvarofpp-course-coq", "path": "github-repos/coq/alvarofpp-course-coq/course-coq-64dc0d9a2e6564f9fa5df508fa946a137901feee/logica_proposicional_e_predicados/conjuncao/exercicio_06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.7577943822145997, "lm_q1q2_score": 0.7088003360448767}}
{"text": "Require Export P02.\n\n\n\n(** ** Exercise: Power Series *)\n\n(** **** Exercise: 4 stars, optional (dpow2_down)  *)\n(** Here is a program that computes the series:\n    [1 + 2 + 2^2 + ... + 2^m = 2^(m+1) - 1]\n\n  X ::= 0;;\n  Y ::= 1;;\n  Z ::= 1;;\n  WHILE X <> m DO\n    Z ::= 2 * Z;;\n    Y ::= Y + Z;;\n    X ::= X + 1\n  END\n\nI = > Y = 2^X - 1 + Z /\\ Z = 2^X                                    \n\n    {{ True }} ->>\n    {{ I [X |-> 0] [Y |-> 1] [Z |-> 1] }} // {{ 1 = 1 /\\ 1 = 1}}\n  X ::= 0;;\n    {{ I [Y |-> 1] [Z |-> 2 * Z] }} // {{ 1 = 2^X /\\ 1 = 2^X}}\n  Y ::= 1;;\n    {{ I [Z |-> 1] }} // {{ Y = 2^X /\\ 1 = 2^X }}\n  Z ::= 1;;\n    {{ I }} // {{ Y = 2^X - 1 + Z /\\ Z = 2^X }}\n  WHILE X <> m DO\n      {{ I /\\ X <> m}} ->>\n      {{ I [Z |-> 2 * Z] [Y |-> Y + Z] [X |-> X + 1] }} // {{ Y + 2 * Z = 2^(X+1) - 1 + 2 * Z /\\ 2 * Z = 2^(X+1) }}\n    Z ::= 2 * Z;;\n      {{ I [Y |-> Y + Z] [X |-> X + 1] }} // {{ Y + Z = 2^(X+1) - 1 + Z /\\ Z = 2^(X+1) }}\n    Y ::= Y + Z;;\n      {{ I [X |-> X + 1] }} // {{ Y = 2^(X+1) - 1 + Z /\\ Z = 2^(X+1) }}\n    X ::= X + 1\n      {{ I }} // {{ Y = 2^X - 1 + Z /\\ Z = 2^X }}\n  END;;\n    {{ I /\\ X = m}} ->>  // {{ Y = 2^X - 1 + Z /\\ Z = 2^X /\\ X = m }}\n    {{ Y = 2^(m+1) - 1 }}\n\n    Write a decorated program for this. *)\n\nLemma pow_2_S : forall n,\n    pow 2 (S n) = 2 * pow 2 n.\nProof.\n  intros. simpl. reflexivity.\nQed.\n\nLemma pow_2_plus1 : forall n,\n    pow 2 (n + 1) = 2 * pow 2 n.\nProof.\n  intros. rewrite (Nat.add_1_r n). apply pow_2_S.\nQed.\n\nTheorem dopw2_down_correct: forall m,\n  {{ fun st => True }}                                   \n  X ::= ANum 0;;\n  Y ::= ANum 1;;\n  Z ::= ANum 1;;\n  WHILE BNot (BEq (AId X) (ANum m)) DO\n    Z ::= AMult (ANum 2) (AId Z);;\n    Y ::= APlus (AId Y) (AId Z);;\n    X ::= APlus (AId X) (ANum 1)\n  END\n  {{ fun st => st Y = pow 2 (S m) - 1 }}.\nProof.\n  intros m. apply hoare_consequence with (P' := fun st => 1 = 1 /\\ 1 = 1) (Q' := fun st => st Y = pow 2 (st X) - 1 + st Z /\\ st Z = pow 2 (st X) /\\  st X = m).\n  - apply hoare_seq with (Q := fun st => 1 = pow 2 (st X) /\\ 1 = pow 2 (st X)).\n    apply hoare_seq with (Q := fun st => st Y = pow 2 (st X) /\\ 1 = pow 2 (st X)).\n    apply hoare_seq with (Q := fun st => st Y = pow 2 (st X) - 1 + st Z /\\ st Z = pow 2 (st X)).\n    + eapply hoare_consequence_post. apply hoare_while.\n      * apply hoare_consequence_pre with (P' := fun st => st Y + 2 * (st Z) = pow 2 (st X + 1) - 1 + 2 * st Z /\\ 2 * st Z = pow 2 (st X + 1)).\n        apply hoare_seq with (Q := fun st => st Y + st Z = pow 2 (st X + 1) - 1 + st Z /\\ st Z = pow 2 (st X + 1)).\n        apply hoare_seq with (Q := fun st => st Y = pow 2 (st X + 1) - 1 + st Z /\\ st Z = pow 2 (st X + 1)).\n        { eapply hoare_consequence_pre. apply hoare_asgn.\n          - unfold assert_implies, assn_sub. intros st H. simpl.\n            rewrite t_update_eq. rewrite t_update_neq. rewrite t_update_neq. assumption.\n            unfold not. intros Hcontra. inversion Hcontra.\n            unfold not. intros Hcontra. inversion Hcontra. }\n        { eapply hoare_consequence_pre. apply hoare_asgn.\n          - unfold assert_implies, assn_sub. intros st H. simpl.\n            rewrite t_update_eq. rewrite t_update_neq. rewrite t_update_neq. assumption.\n            unfold not. intros Hcontra. inversion Hcontra.\n            unfold not. intros Hcontra. inversion Hcontra. }\n        { eapply hoare_consequence_pre. apply hoare_asgn.\n          - unfold assert_implies, assn_sub. intros st H. simpl.\n            rewrite t_update_eq. rewrite t_update_neq. rewrite t_update_neq. assumption.\n            unfold not. intros Hcontra. inversion Hcontra.\n            unfold not. intros Hcontra. inversion Hcontra. }\n        { unfold assert_implies. intros st [[H HZ] HX]. split.\n          - rewrite pow_2_plus1. rewrite H. rewrite HZ. omega.\n          - rewrite pow_2_plus1. rewrite HZ. reflexivity. }\n      * unfold assert_implies. intros st [[H HZ] HX]. split.\n        { assumption. }\n        { split.\n          - assumption.\n          - unfold not, bassn in HX. simpl in HX. rewrite negb_true_iff in HX.\n            apply eq_false_true_abs in HX. apply beq_nat_true in HX. omega. }\n    + unfold hoare_triple. intros st st' HZ [HY H]. inversion HZ. subst. simpl. split.\n      * rewrite t_update_neq. rewrite t_update_neq. rewrite t_update_eq. omega.\n        unfold not. intros Hcontra. inversion Hcontra.\n        unfold not. intros Hcontra. inversion Hcontra.\n      * rewrite t_update_eq. rewrite t_update_neq. assumption.\n        unfold not. intros Hcontra. inversion Hcontra.\n    + unfold hoare_triple. intros st st' HZ [HY H]. inversion HZ. subst. simpl. split.\n      * rewrite t_update_eq. rewrite t_update_neq. assumption.\n        unfold not. intros Hcontra. inversion Hcontra.\n      * rewrite t_update_neq. assumption.\n        unfold not. intros Hcontra. inversion Hcontra.\n    + unfold hoare_triple. intros st st' H _. inversion H. subst. split.\n      * rewrite t_update_eq. reflexivity.\n      * rewrite t_update_eq. reflexivity.\n  - unfold assert_implies. intros. split. reflexivity. reflexivity.\n  - unfold assert_implies. intros st [HY [HZ HX]]. rewrite pow_2_S. subst. simpl. rewrite <- plus_n_O. omega.    \nQed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/09/P03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7087600388204341}}
{"text": "(** * Indu\\u00e7\\u00e3o em Coq *)\n\nAdd LoadPath \"/Users/marcosmonteiro/desktop/coq\".\nRequire Export aula05_inducao.\nModule NatList.\n\n(* ############################################### *)\n(** * Pares de n\\u00fameros *)\n\n(** A seguinte declara\\u00e7\\u00e3o pode ser lida como\n    \"s\\u00f3 existe uma maneira de construir um\n    par de n\\u00fameros, que \\u00e9 aplicando o construtor\n    [pair] a dois argumentos do tipo [nat]\" *)\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\n\nCheck (pair 3 5).\n\n(** Definindo fun\\u00e7\\u00f5es para pares.\n    Observe o casamento de padr\\u00e3o. *)\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(* Definindo uma nota\\u00e7\\u00e3o mais conveniente. *)\n\nNotation \"( x , y )\" := (pair x y).\n\nCompute (fst (3,5)).\n\n(* Observe que \\u00e9 poss\\u00edvel, inclusive,\n   usar esta sintaxe no casamento de padr\\u00f5es. *)\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(** Algumas provas associadas a pares. *)\n\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  intros. simpl. reflexivity.\nQed.\n\n(** Observe que o pr\\u00f3ximo teorema representa\n    o mesmo fato, mas [reflexivity] n\\u00e3o\n    \\u00e9 suficiente para concluir esta prova. *)\n\nTheorem surjective_pairing_stuck :\n  forall (p : natprod),\n    p = (fst p, snd p).\nProof.\n  simpl. (* Doesn't reduce anything! *)\nAbort.\n\n(** \\u00c9 preciso expor a estrutura de [p], tal\n    que [simpl] possa realizar casamento de\n    padr\\u00e3o. [destruct] permite fazer isto. *)\n\nTheorem surjective_pairing : forall (p : natprod),\n  p = (fst p, snd p).\nProof.\n  intros p. destruct p as [n m].\n  simpl. reflexivity.\nQed.\n\n(** **** Exercise: (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(** * Lista de n\\u00fameros *)\n\n(** Defini\\u00e7\\u00e3o de uma lista de n\\u00fameros. *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\n\n(** Exemplo de uma lista com 3 elementos. *)\n\nDefinition mylist := cons 1 (cons 2 (cons 3 nil)).\n\n(** Definindo uma nota\\u00e7\\u00e3o mais conveniente. *)\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(** As defini\\u00e7\\u00f5es a seguir s\\u00e3o equivalentes. *)\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\n\n(** Definindo fun\\u00e7\\u00f5es para listas. *)\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nExample test_repeat1 :\n  repeat 5 3\n  = [5;5;5].\nProof. simpl. reflexivity. Qed.\n\nFixpoint length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\n\nNotation \"x ++ y\" := (app x y)\n                     (right associativity, at level 60).\n\nExample test_app1:\n[1;2;3] ++ [4;5] = [1;2;3;4;5].\nProof. simpl. reflexivity. Qed.\nExample test_app2:\nnil ++ [4;5] = [4;5].\nProof. reflexivity. Qed.\nExample test_app3:\n[1;2;3] ++ nil = [1;2;3].\nProof. simpl. reflexivity. Qed.\n\n(** Na defini\\u00e7\\u00e3o a seguir, observe o\n    valor [default]. *)\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:\nhd 0 [1;2;3] = 1.\nProof. reflexivity. Qed.\nExample test_hd2:\nhd 0 [] = 0.\nProof. reflexivity. Qed.\nExample test_tl:\ntl [1;2;3] = [2;3].\nProof. simpl. reflexivity. Qed.\n\n(** **** Exercise: (list_funs)  *)\n(** Complete as defini\\u00e7\\u00f5es de [nonzeros],\n    [oddmembers] e [countoddmembers]. Os testes\n    mostram o comportamento esperado. *)\n\nFixpoint nonzeros (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t =>\n     match h with\n     | O => 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].\nProof. simpl. 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:\n  oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof. simpl. reflexivity. Qed.\n\nDefinition countoddmembers (l:natlist) : nat\n(* SUBSTITUA COM \":= _sua_defini\\u00e7\\u00e3o_ .\" *). Admitted.\n\nExample test_countoddmembers1:\n  countoddmembers [1;0;3;1;4;5] = 4.\n(* COMPLETE AQUI *) Admitted.\n\nExample test_countoddmembers2:\n  countoddmembers [0;2;4] = 0.\n(* COMPLETE AQUI *) Admitted.\n\nExample test_countoddmembers3:\n  countoddmembers nil = 0.\n(* COMPLETE AQUI *) Admitted.\n\n(* ############################################### *)\n(** * Representando multiconjuntos como listas *)\n\nDefinition bag := natlist.\n\n(** **** Exercise: (bag_functions)  *)\n(** Complete as defini\\u00e7\\u00f5es de: [count], [sum],\n    [add], e [member] para multiconjuntos (bags).\n    Os testes mostram o comportamento esperado. *)\n\nFixpoint count (v:nat) (s:bag) : nat :=\n  match s with\n  | nil => O\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\nExample test_count1:\n  count 1 [1;2;3;1;4;1] = 3.\nProof. simpl. reflexivity. Qed.\n\nExample test_count2:\n  count 6 [1;2;3;1;4;1] = 0.\nProof. simpl. reflexivity. Qed.\n\n(** A opera\\u00e7\\u00e3o [sum] em multiconjuntos \\u00e9 similar\n    ao conceito de [union] de conjuntos: [sum a b]\n    cont\\u00e9m todos os elementos de [a] e [b].\n\n    Observe que a pr\\u00f3xima defini\\u00e7\\u00e3o n\\u00e3o possui\n    nome para os par\\u00e2metros, mas somente seus tipos.\n    Al\\u00e9m disto, a defini\\u00e7\\u00e3o n\\u00e3o \\u00e9 recursiva. Portanto,\n    [sum] precisa ser definida em fun\\u00e7\\u00e3o de defini\\u00e7\\u00f5es\n    passadas. *)\n\nDefinition sum : bag -> bag -> bag := app.\n\nExample test_sum1:\n  count 1 (sum [1;2;3] [1;4;1]) = 3.\nProof. simpl. reflexivity. Qed.\n\nDefinition add (v:nat) (s:bag) : bag := v :: s.\n\nExample test_add1:\n  count 1 (add 1 [1;4;1]) = 3. \nProof. simpl. reflexivity. Qed.\n\nExample test_add2:\n  count 5 (add 1 [1;4;1]) = 0.\nProof. simpl. reflexivity. Qed.\n\n(** Observe que a pr\\u00f3xima defini\\u00e7\\u00e3o\n    tamb\\u00e9m n\\u00e3o \\u00e9 recursiva. *)\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:\n  member 1 [1;4;1] = true.\nProof. simpl. reflexivity. Qed.\n\nExample test_member2:\n  member 2 [1;4;1] = false.\nProof. simpl. reflexivity. Qed.\n\n(** **** Exercise: (bag_theorem)  *)\n(** Prove o seguinte teorema. Talvez voc\\u00ea\n    precise provar um teorema auxiliar. *)\n\n\n\nTheorem bag_theorem :\n  forall (v : nat) (b : bag),\n    (count v (add v b)) = (1 + (count v b)).\nProof.\n  intros. simpl. Admitted.\n\n\n(* ############################################### *)\n(** * Raciocinando sobre listas *)\n\n(** Algumas propriedades podem ser provadas\n    somente com [reflexivity]. *)\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof.\n  Print app. simpl. reflexivity.\nQed.\n\n(** \\u00c0s vezes, ser\\u00e1 preciso fazer an\\u00e1lise de casos. *)\n\nTheorem tl_length_pred : forall l:natlist,\n  pred (length l) = length (tl l).\nProof.\n  (* Observe a quantidade de elementos\n     da segunda lista do destruct. *)\n  intros l. destruct l as [| n l'].\n  - (* l = nil *)\n    simpl. reflexivity.\n  - (* l = cons n l' *)\n    Print length. simpl. reflexivity.\nQed.\n\n(** \\u00c0s vezes, ser\\u00e1 preciso fazer indu\\u00e7\\u00e3o. *)\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. reflexivity.\n  - (* l1 = cons n l1' *)\n    Print app. simpl.\n    rewrite -> IHl1'. reflexivity.\nQed.\n\n(** Considere a seguinte defini\\u00e7\\u00e3o de [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:\n  rev [1;2;3] = [3;2;1].\nProof. simpl. reflexivity.  Qed.\nExample test_rev2:\n  rev nil = nil.\nProof. reflexivity.  Qed.\n\n(** Vamos tentar provar a seguinte afirma\\u00e7\\u00e3o.\n    Observe que ficamos \"travados\" no segundo caso. *) \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    simpl. reflexivity.\n  - (* l = n :: l' *)\n    Print rev. simpl. rewrite <- IHl'.\n    (* Como continuar a partir daqui? *)\nAbort.\n\n(** Vamos definir um teorema auxiliar a partir\n    do ponto em que ficamos \"travados\" no\n    teorema anterior. Contudo, vamos tornar\n    o teorema auxiliar o mais geral poss\\u00edvel:\n    [l1] e [l2] no lugar de [rev l'] e [n]. *)\n\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  intros l1 l2. induction l1 as [| n l1' IHl1'].\n  - simpl. (* l1 = nil *)\n    reflexivity.\n  - (* l1 = cons *)\n    simpl. rewrite -> IHl1'. reflexivity.\nQed.\n\n(** Agora concluimos a prova de [rev_length]. *)\n\nTheorem rev_length : forall l : natlist,\n  length (rev l) = length l.\nProof.\n  intros l. induction l as [| n l' IHl'].\n  - simpl. (* l = nil *)\n    reflexivity.\n  - (* l = cons *)\n    (* Observe o rewrite  com duas t\\u00e1ticas *)\n    simpl. rewrite -> app_length, plus_comm.\n    simpl. rewrite -> IHl'. reflexivity.\nQed.\n\n(** **** Exercise: (list_exercises)  *)\n(** Prove os seguintes teoremas. *)\n\nTheorem app_nil_r : forall l : natlist,\n  l ++ [] = l.\nProof.\n  intros. induction l.\n  - simpl. 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(* COMPLETE AQUI *) Admitted.\n\nTheorem rev_involutive : forall l : natlist,\n  rev (rev l) = l.\nProof.\n(* COMPLETE AQUI *) Admitted.\n\nLemma nonzeros_app : forall l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof.\n  intros. induction l1.\n  - simpl. reflexivity.\n  - destruct n.\n    + simpl. rewrite IHl1. reflexivity.\n    + simpl. rewrite IHl1. reflexivity.\nQed.\n\n(** **** Exercise: (beq_natlist)  *)\n(** Complete a defini\\u00e7\\u00e3o de [beq_natlist], que\n    compara listas de n\\u00fameros. Veja os exemplos.\n    Em seguida, prove o teorema [beq_natlist_refl]. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1, l1 with\n  | [], [] => true\n  | _, [] => false\n  | [], _ => false\n  | h1 :: t1, h2 :: t2 => \n    match beq_nat h1 h2 with\n    | true => beq_natlist t1 t2\n    | false => false\n    end\n  end.\n\n\nExample test_beq_natlist1 :\n  (beq_natlist nil nil = true).\n(* COMPLETE AQUI *) Admitted.\n\nExample test_beq_natlist2 :\n  beq_natlist [1;2;3] [1;2;3] = true.\n(* COMPLETE AQUI *) Admitted.\n\nExample test_beq_natlist3 :\n  beq_natlist [1;2;3] [1;2;4] = false.\n(* COMPLETE AQUI *) Admitted.\n\nTheorem beq_natlist_refl : forall l:natlist,\n  true = beq_natlist l l.\nProof.\n  intros. induction l.\n  - simpl. reflexivity.\nAbort.\n\n(* ############################################### *)\n(** * Options *)\n\n(** Considere a seguinte implementa\\u00e7\\u00e3o de uma\n    fun\\u00e7\\u00e3o que retorna o i-\\u00e9simo elemento\n    de uma lista. *)\n\nFixpoint nth_bad (l:natlist) (n:nat) : nat :=\n  match l with\n  | nil => 42  (* um valor arbitr\\u00e1rio! *)\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(** Outra alternativa seria considerar um\n    elemento padr\\u00e3o -- ver defini\\u00e7\\u00e3o de [hd].\n\n    Uma melhor solu\\u00e7\\u00e3o \\u00e9 definir um \"option\".\n    Similar ao conceito de \"maybe\" em Haskell. *)\n\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n(** Veja agora a fun\\u00e7\\u00e3o [nth_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 :\n  nth_error [4;5;6;7] 0 = Some 4.\nProof. simpl. reflexivity. Qed.\nExample test_nth_error2 :\n  nth_error [4;5;6;7] 3 = Some 7.\nProof. simpl. reflexivity. Qed.\nExample test_nth_error3 :\n  nth_error [4;5;6;7] 9 = None.\nProof. simpl. reflexivity. Qed.\n\n(** A seguir, uma outra possibilidade de\n    implementa\\u00e7\\u00e3o de [nth_error] usando \"if\". *)\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(** No entanto, cuidado com o \"if\". *)\n\nInductive tipo : Type :=\n  | cons1 : tipo\n  | cons2 : tipo.\n\nDefinition beq_tipo (n m : nat) : tipo :=\n  if beq_nat n m then cons2 else cons1.\n\nDefinition teste_if (n m : nat) : bool :=\n  if beq_tipo n m then true\n  else false.\n\nCompute (teste_if 2 2).\n\n(** O \"if\" s\\u00f3 pode ser aplicado a tipos\n    indutivos com dois construtores. *)\n\n(** A fun\\u00e7\\u00e3o a seguir retira o [nat] encapsulado\n    no [natoption]. Observe aqui o uso do default. *)\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: (hd_error)  *)\n(** Use a ideia do \"option\" e atualize\n    a defini\\u00e7\\u00e3o da fun\\u00e7\\u00e3o [hd]. *)\n\nDefinition hd_error (l : natlist) : natoption :=\n  match l with\n  | nil => None\n  | h :: t => Some h\n  end.\n\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(** **** Exercise: (option_elim_hd)  *)\n(** Prove o seguinte teorema relacionando\n    [hd_error] com [hd]. *)\n\nTheorem option_elim_hd : forall (l:natlist) (default:nat),\n  hd default l = option_elim default (hd_error l).\nProof.\n  Print hd. Print option_elim.\n  intros. destruct l.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n\nEnd NatList.\n\n(* ############################################### *)\n(** * Mapeamentos parciais *)\n\n(** Veja a seguinte defini\\u00e7\\u00e3o de mapeamentos parciais,\n    similar aos tipos map ou dictionary das\n    principais linguagens de programa\\u00e7\\u00e3o.\n\n    Inicialmente, definimos a \"chave\": o [id]. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\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: (beq_id_refl)  *)\nTheorem beq_id_refl :\n  forall x, true = beq_id x x.\nProof.\n  intros. destruct x. simpl. induction n.\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHn. reflexivity.\nQed.\n\n(** Agora, o tipo de mapeamentos parciais *)\n\nModule PartialMap.\nExport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\n\n(** Logo, existem duas maneiras de construir\n    [partial_map]: usando o construtor [empty],\n    representando o mapeamento vazio; usando\n    o construtor [record], passando uma chave,\n    um n\\u00famero e um mapeamento existente.\n\n    A fun\\u00e7\\u00e3o [update] atualiza um mapeamento.\n    Observe que, conceitualmente, o valor antigo,\n    caso exista, \\u00e9 mantido no mapeamento. O\n    primeiro valor ser\\u00e1 o mais recente. *)\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\n\nExample test_partial_map1 :\n  (update empty (Id 0) 3)\n  = (record (Id 0) 3 empty).\nProof.\n    simpl. reflexivity.\nQed.\n\nExample test_partial_map2 :\n  (update (record (Id 0) 2 empty) (Id 0) 3)\n  = (record (Id 0) 3 (record (Id 0) 2 empty)).\nProof.\n    simpl. reflexivity.\nQed.\n\n(** A fun\\u00e7\\u00e3o [find] procura por um valor em\n    um mapeamento. Se houver m\\u00faltiplos mapeamentos,\n    retorna o primeiro. *)\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(** **** Exercise: (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(* COMPLETE AQUI *) Admitted.\n\n(** **** Exercise: (update_neq)  *)\nTheorem update_neq :\n  forall (d : partial_map) (x y : id) (o: nat),\n    beq_id x y = false ->\n    find x (update d y o) = find x d.\nProof.\n(* COMPLETE AQUI *) Admitted.\n\nEnd PartialMap.\n\n(** Veja a diferen\\u00e7a entre os dois pr\\u00f3ximos\n    comandos. O segundo garante que a\n    express\\u00e3o \\u00e0 direita da igualdade\n    seja igual (sintaticamente) ao\n    segundo operando da soma. *)\n\nSearch (_ + _ = _).\nSearch (_ + ?x = ?x).\n\n(* ############################################### *)\n(** * Leitura sugerida *)\n\n(** Software Foundations: volume 1\n  - Lists\n  https://softwarefoundations.cis.upenn.edu/lf-current/Lists.html\n*)\n", "meta": {"author": "marcosmmb", "repo": "coq_examples", "sha": "d68ad92d5cc39656a061f8a4d335bbd4515d7c22", "save_path": "github-repos/coq/marcosmmb-coq_examples", "path": "github-repos/coq/marcosmmb-coq_examples/coq_examples-d68ad92d5cc39656a061f8a4d335bbd4515d7c22/aula06_listas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.7087429336799556}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Arith.\nRequire Import Metrics.UltraMetric.\nRequire Import Essentials.Omega.\nRequire Import Essentials.Facts_Tactics.\n\nLocal Open Scope order_scope.\nLocal Open Scope lattice_scope.\nLocal Open Scope metric_scope.\n\n(** Limit of a sequence in an ultra metric space. *)\nSection Limit.\n  Context {L : MLattice} {U : UltraMetric L} (Seq : Sequence U).\n\n  (** The limit of a sequence is an element whose distance from elements of the sequence\ndecreases below any positive distance as the sequence progresses. *)\n  Record Limit : Type :=\n    {\n      Lim :> U;\n      Lim_limit :\n        ∀ (ε : (ApprType L)),\n          {N : nat | ∀ (n : nat), N ≤ n →\n              δ(Seq n, Lim) ⊏ (projT1 ε)}\n    }.\n\n  Theorem Limit_unique (l l' : Limit) : l = l' :> U.\n  Proof.\n    destruct (ML_bottom_dichotomy L) as [dicht|dicht].\n    {\n      apply UM_zero_dist_eq.\n      apply ML_appr_dominate_pos.\n      intros y H1.\n      destruct (dicht _ H1) as [y' Hd1 [Hd2 Hd3]].\n      destruct (Lim_limit l (existT _ _ Hd1)) as [Nl Hl].\n      destruct (Lim_limit l' (existT _ _ Hd1)) as [Nl' Hl'].\n      eapply LE_LT_Trans; [apply (UM_ineq L U l l' (Seq (max Nl Nl'))) |].\n      eapply LE_LT_Trans; [|apply Hd3].\n      apply lub_lst; intros [|].\n      + rewrite UM_dist_sym.\n        apply Hl.\n        apply l_le_max.\n      + apply Hl'.     \n        apply r_le_max.\n    }\n    {\n      destruct dicht as [ab Hd1 Hd2].\n      destruct (Lim_limit l (existT _ _ Hd1)) as [Nl Hl].\n      destruct (Lim_limit l' (existT _ _ Hd1)) as [Nl' Hl'].\n      apply UM_zero_dist_eq.\n      apply LE_Bottom_Bottom.\n      eapply PO_Trans; [apply (UM_ineq L U l l' (Seq (max Nl Nl'))) |].\n      apply lub_lst; intros [|].\n      + rewrite UM_dist_sym.\n        specialize (Hl (max Nl Nl') (l_le_max _ _)).\n        apply Hd2 in Hl; rewrite Hl; trivial.\n      + specialize (Hl' (max Nl Nl') (r_le_max _ _)).\n        apply Hd2 in Hl'; rewrite Hl'; trivial.\n    }\n  Qed.\n     \nEnd Limit.\n\nSection Eq_Seq_Eq_Limits.\n  Context {L : MLattice}\n          {U : UltraMetric L}\n          (Seq Seq' : Sequence U)\n          (l : Limit Seq)\n          (l' : Limit Seq')\n  .\n\n  Theorem Eq_Seq_Eq_Limits : Seq = Seq' → l = l' :> U.\n  Proof.\n    intros H.\n    destruct H.\n    apply Limit_unique.\n  Qed.    \n\nEnd Eq_Seq_Eq_Limits.\n  \nArguments Lim {_ _ _} _.\nArguments Lim_limit {_ _ _} _ _.\n\nSection Limit_of_SubSeq.\n  Context {L : MLattice} {U : UltraMetric L}.\n\n  Program Definition Limit_of_SubSeq {Seq : Sequence U} (l : Limit Seq) (m : nat) :\n    Limit (fun n => Seq (m + n)) :=\n    {|\n      Lim := l\n    |}.\n\n  Next Obligation.\n  Proof.\n    destruct (Lim_limit l ε) as [N H].\n    exists (m + N).\n    intros n H2.\n    apply H.\n    abstract omega.\n  Defined.\n\n  Theorem Limit_of_SubSeq_equal_1 {Seq : Sequence U} (l : Limit Seq) (l' : Limit (fun n => Seq (S n))) : l = l' :> U.\n  Proof.\n    cut (∀ (ε : (ApprType L)),\n            {N : nat | ∀ (n : nat),\n                N ≤ n →\n                δ(Seq n, l') ⊏ (projT1 ε)}\n        ).\n    {\n      intros H.\n      transitivity ({|Lim := l'; Lim_limit := H|}); trivial.\n      apply Limit_unique.\n    }\n    {    \n      intros ε.\n      destruct (Lim_limit l' ε) as [m H'].\n      exists (S m).\n      intros n H1.\n      destruct n; [omega|].\n      cut (m ≤ n); auto; omega.\n    }\n  Qed.\n\n  Theorem Limit_of_SubSeq_equal {Seq : Sequence U} (l : Limit Seq) (m : nat) (l' : Limit (fun n => Seq (m + n))) : l = l' :> U.\n  Proof.\n    induction m.\n    + apply Limit_unique.\n    + rewrite ((IHm (Limit_of_SubSeq l m))).\n      set (W := Limit_of_SubSeq_equal_1 (Limit_of_SubSeq l m)).\n      cbn in W.\n      replace (fun n : nat => Seq (m + S n)) with (fun n : nat => Seq (S m + n)) in W\n        by (abstract (FunExt; apply f_equal; omega)).\n      apply W.\n  Qed.\n      \nEnd Limit_of_SubSeq.\n\nSection Limit_of_ConstSeq.\n  Context {L : MLattice} {U : UltraMetric L} (A : U).\n\n  Program Definition Limit_of_ConstSeq :\n    Limit (fun _ => A) :=\n    {|\n      Lim := A\n    |}.\n\n  Next Obligation.\n  Proof.\n    exists 0.\n    intros ? ?.\n    rewrite UM_eq_zero_dist.\n    apply ML_appr_pos.\n    apply (projT2 ε).\n  Qed.    \n  \n  Theorem Limit_of_ConstSeq_equal (l : Limit (fun _ => A)) : l = A :> U.\n  Proof.\n    change A with (Lim Limit_of_ConstSeq).\n    apply Limit_unique.\n  Qed.\n  \nEnd Limit_of_ConstSeq.\n  \nSection Distance_of_Limits.\n  Context {L : MLattice} {U : UltraMetric L} (Seq Seq' : Sequence U).\n\n  Theorem Distance_of_Limits (δ : L) (l : Limit Seq) (l' : Limit Seq') :\n    ⊥ ⊏ δ → (∀ n, δ(Seq n, Seq' n) ⊑ δ) → δ(l, l') ⊑ δ.\n  Proof.\n    intros H1 H2.\n    destruct (ML_all_approximatable _ _ H1) as [δ' H3 H4].\n    destruct (Lim_limit l (existT _ _ H4)) as [m H5].\n    destruct (Lim_limit l' (existT _ _ H4)) as [m' H6].\n    eapply PO_Trans; [apply UM_ineq|].\n    apply lub_lst; intros [].\n    {\n      rewrite UM_dist_sym.\n      eapply PO_Trans; [|apply H3].\n      apply (H5 (max m m') (l_le_max _ _)).\n    }\n    {\n      eapply PO_Trans; [apply UM_ineq|].\n      apply lub_lst; intros [].\n      {\n        apply H2.\n      }\n      {\n        eapply PO_Trans; [|apply H3].\n        apply (H6 (max m m') (r_le_max _ _)).\n      }\n    }\n  Qed.\n\nEnd Distance_of_Limits.", "meta": {"author": "amintimany", "repo": "CTDT", "sha": "91e390152e09c554126b13fd953c905d16bfed5f", "save_path": "github-repos/coq/amintimany-CTDT", "path": "github-repos/coq/amintimany-CTDT/CTDT-91e390152e09c554126b13fd953c905d16bfed5f/Metrics/Limit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7086670880468204}}
{"text": "(* ================================ *)\n(* ========== CH01_ccw.v ========== *)\n(* ================================ *)\n\nRequire Export Del13.\n\nOpen Scope R_scope.\n\n(* ================================ *)\n(* ========== ########## ========== *)\n(* ================================ *)\n\nDefinition det (p q r : point) : R :=\n  (fst p * snd q) - (fst q * snd p) - (fst p * snd r) + (fst r * snd p) +\n  (fst q * snd r) - (fst r * snd q).\n\nLemma eq_det : forall (p q r : point),\n  det p q r = det q r p.\nProof.\nintros p q r.\nunfold det; ring.\nQed.\n\nLemma neq_det : forall (p q r : point),\n  det p q r = - det p r q.\nProof.\nintros p q r.\nunfold det; ring.\nQed.\n\n(* ================================ *)\n(* ========== ########## ========== *)\n(* ================================ *)\n\nDefinition ccw (p q r : point) : Prop :=\n  (det p q r > 0).\n\nLemma ccw_dec : forall (p q r : point),\n  {ccw p q r} + {~ ccw p q r}.\nProof.\nintros p q r.\nunfold ccw; apply Rgt_dec.\nQed.\n\n(* ================================ *)\n\nDefinition align (p q r : point) : Prop :=\n  (det p q r = 0).\n\nLemma align_dec : forall (p q r : point),\n  {align p q r} + {~align p q r}.\nProof.\nintros p q r.\nunfold align.\ngeneralize (total_order_T (det p q r) 0).\ngeneralize (Rlt_dichotomy_converse (det p q r) 0).\ntauto.\nQed.\n\n(* ================================ *)\n(* ========== ########## ========== *)\n(* ================================ *)\n\nLemma Rle_neq_lt : forall (r1 r2 : R),\n  r1 <= r2 -> r1 <> r2 -> r1 < r2.\nProof.\nintros r1 r2 H1 H2.\nelim (Rdichotomy r1 r2).\ntrivial.\ngeneralize (Rle_not_lt r2 r1).\ntauto.\nassumption.\nQed.\n\nLemma R_gt_0_plus : forall (r1 r2 : R),\n  r1 > 0 -> r2 > 0 -> r1 + r2 > 0.\nProof.\nintros r1 r2 H1 H2.\napply Rgt_trans with r1.\n pattern r1 at 2; rewrite <- (Rplus_0_r r1).\n apply Rplus_gt_compat_l; assumption.\nassumption.\nQed.\n\nLemma R_gt_0_mult : forall (r1 r2 : R),\n  r1 > 0 -> r2 > 0 -> r1 * r2 > 0.\nProof.\napply Rmult_gt_0_compat.\nQed.\n\nLemma R_gt_0_div : forall (r1 r2 : R),\n  r1 > 0 -> r2 > 0 -> r1 * / r2 > 0.\nProof.\nintros r1 r2 H1 H2.\napply R_gt_0_mult.\n assumption.\n unfold Rgt in *; auto with real.\nQed.\n\nLemma R_mult_div : forall (r1 r2 r3 : R),\n  r1 = r2 * r3 -> r2 > 0 -> r1 * / r2 = r3.\nProof.\nintros r1 r2 r3 H1 H2.\nsubst r1; auto with real.\nQed.\n\n(* ================================ *)\n(* ========== ########## ========== *)\n(* ================================ *)\n\nLemma axiom_orientation_1 :\n  forall (A:point)(B:point)(C:point),\n  ccw A B C -> ccw B C A.\nProof.\nintros A B C.\nunfold ccw; rewrite eq_det; trivial.\nQed.\n\nLemma axiom_orientation_2 :\n  forall (A:point)(B:point)(C:point),\n  align A B C -> align B C A.\nProof.\nintros A B C.\nunfold align; rewrite eq_det; trivial.\nQed.\n\nLemma axiom_orientation_3 :\n  forall (A:point)(B:point)(C:point),\n  align A B C -> align A C B.\nProof.\nintros A B C.\nunfold align; rewrite neq_det.\ngeneralize (Rplus_opp_r (det A C B)).\ngeneralize (Rplus_0_l (det A C B)).\nintros H1 H2 H3.\nrewrite H3 in H2; clear H3.\nrewrite Rplus_comm in H1.\nrewrite H1 in H2; clear H1.\nassumption.\nQed.\n\nHint Resolve axiom_orientation_1 axiom_orientation_2 axiom_orientation_3 : myorientation.\n\n(* ================================ *)\n\nLemma axiom_orientation_4 :\n  forall (A:point)(B:point)(C:point),\n  ccw A B C -> ~ ccw A C B.\nProof.\nintros A B C.\nunfold ccw; rewrite neq_det.\ngeneralize (Ropp_gt_lt_contravar (- det A C B) 0).\nrewrite Ropp_involutive; rewrite Ropp_0.\nintro H1; generalize (Rlt_le (det A C B) 0).\nintro H2; generalize (Rle_not_lt 0 (det A C B)).\nintro H3; tauto.\nQed.\n\nLemma axiom_orientation_5 :\n  forall (A:point)(B:point)(C:point),\n  ccw A B C -> ~ align A B C.\nProof.\nintros A B C.\nunfold ccw, align in *.\napply Rgt_not_eq; assumption.\nQed.\n\nLemma axiom_orientation_6 :\n  forall (A:point)(B:point)(C:point),\n  align A B C -> ~ ccw A B C.\nProof.\nintros A B C.\nunfold ccw, align in *.\nintro H1; rewrite H1.\nunfold not; intro H2.\napply Rgt_not_eq in H2; tauto.\nQed.\n\nHint Resolve axiom_orientation_4 axiom_orientation_5 axiom_orientation_6 : myorientation.\n\n(* ================================ *)\n\nLemma axiom_orientation_7 :\n  forall (A:point)(B:point)(C:point),\n  ~ ccw A B C -> ccw A C B \\/ align A B C.\nProof.\nintros A B C H.\nelim (ccw_dec A C B).\n intro H1; left; assumption.\n intro H1; right.\n unfold ccw, align in *.\n rewrite neq_det in H1.\n apply Rle_antisym.\n  apply Rnot_gt_le; assumption.\n  apply Rnot_gt_le; auto with real.\nQed.\n\nLemma axiom_orientation_8 :\n  forall (A:point)(B:point)(C:point),\n  ~ align A B C -> ccw A B C \\/ ccw A C B.\nProof.\nintros A B C H.\nelim (ccw_dec A B C).\n intro H0; left; assumption.\n intro H0; right.\n apply axiom_orientation_7 in H0.\n elim H0; [trivial|contradiction].\nQed.\n\nHint Resolve axiom_orientation_7 axiom_orientation_8 : myorientation.\n\n(* ================================ *)\n(* ========== ########## ========== *)\n(* ================================ *)\n\nLemma ccw_axiom_1 : forall (p q r : point),\n  ccw p q r -> ccw q r p.\nProof.\nauto with myorientation.\nQed.\n\nLemma ccw_axiom_2 : forall (p q r : point),\n  ccw p q r -> ~ ccw p r q.\nProof.\nauto with myorientation.\nQed.\n\nLemma ccw_axiom_3 : forall (p q r : point),\n  ~ align p q r -> (ccw p q r) \\/ (ccw p r q).\nProof.\nauto with myorientation.\nQed.\n\nLemma ccw_axiom_4 : forall (p q r t : point),\n  (ccw t q r) -> (ccw p t r) -> (ccw p q t) -> (ccw p q r).\nProof.\nintros p q r t H1 H2 H3.\nunfold ccw in *.\nassert (det t q r + det p t r + det p q t = det p q r).\nunfold det; ring.\nrewrite <- H.\napply R_gt_0_plus; [apply R_gt_0_plus; assumption | assumption].\nQed.\n\nLemma ccw_axiom_5 : forall (p q r s t : point),\n  (ccw t s p) -> (ccw t s q) -> (ccw t s r) -> (ccw t p q) -> (ccw t q r) -> \n  (ccw t p r).\nProof.\nintros p q r s t H1 H2 H3 H4 H5.\nunfold ccw in *.\nreplace (det t p r) with ((det t p q * det t s r + det t q r * det t s p) * / (det t s q)).\napply R_gt_0_div.\n apply R_gt_0_plus.\n  apply R_gt_0_mult; assumption.\n  apply R_gt_0_mult; assumption.\n assumption.\napply R_mult_div.\n unfold det; ring.\n assumption.\nQed.\n\nLemma ccw_axiom_5_bis : forall (p q r s t : point),\n  (ccw s t p) -> (ccw s t q) -> (ccw s t r) -> (ccw t p q) -> (ccw t q r) -> \n  (ccw t p r).\nProof.\nintros p q r s t H1 H2 H3 H4 H5.\nunfold ccw in *.\nreplace (det t p r) with ((det t p q * det s t r + det t q r * det s t p) * / (det s t q)).\napply R_gt_0_div.\n apply R_gt_0_plus.\n  apply R_gt_0_mult; assumption.\n  apply R_gt_0_mult; assumption.\n assumption.\napply R_mult_div.\n unfold det; ring.\n assumption.\nQed.\n", "meta": {"author": "magaud", "repo": "ConvexHullV2", "sha": "de52a48028e4538cd2b2c07f5230ab2065d8dfa0", "save_path": "github-repos/coq/magaud-ConvexHullV2", "path": "github-repos/coq/magaud-ConvexHullV2/ConvexHullV2-de52a48028e4538cd2b2c07f5230ab2065d8dfa0/CH01_ccw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539553, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.7086670880468204}}
{"text": "(** * Rel: Properties of Relations *)\n\n(* $Date: 2011-03-21 10:44:46 -0400 (Mon, 21 Mar 2011) $ *)\n\n\n(** This short chapter develops some basic definitions that will be\n    needed when we come to working with small-step operational\n    semantics in [Smallstep.v].  It can be postponed until just before\n    [Smallstep.v], but it is also a good source of good exercises for\n    developing facility with Coq's basic reasoning facilities, so it\n    may be useful to look at it just after [Logic.v]. *)\n\nRequire Export Logic.\n\n(** A _relation_ is just a parameterized proposition.  As you know\n    from your undergraduate discrete math course, there are a lot of\n    ways of discussing and describing relations _in general_ -- ways\n    of classifying relations (are they reflexive, transitive, etc.),\n    theorems that can be proved generically about classes of\n    relations, constructions that build one relation from another,\n    etc.  Let us pause here to review a few that will be useful in\n    what follows. *)\n\n(** A relation _on_ a set [X] is a proposition parameterized by two\n    [X]s -- i.e., it is a logical assertion involving two values from\n    the set [X].  *)\n\nDefinition relation (X: Type) := X->X->Prop.\n\n(** Somewhat confusingly, the Coq standard library hijacks the generic\n    term \"relation\" for this specific instance. To maintain\n    consistency with the library, we will do the same.  So, henceforth\n    the Coq identifier [relation] will always refer to a binary\n    relation between some set and itself, while the English word\n    \"relation\" can refer either to the specific Coq concept or the\n    more general concept of a relation between any number of possibly\n    different sets.  The context of the discussion should always make\n    clear which is meant. *)\n\n(* ######################################################### *)\n(** * Basic Properties of Relations *)\n\n(** A relation [R] on a set [X] is a _partial function_ if, for every\n    [x], there is at most one [y] such that [R x y] -- i.e., if [R x\n    y1] and [R x y2] together imply [y1 = y2]. *)\n\nDefinition partial_function {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2. \n\n(** For example, the [next_nat] relation defined in Logic.v is a\n    partial function. *)\n\nTheorem next_nat_partial_function : \n   partial_function next_nat.\nProof. \n  unfold partial_function.\n  intros x y1 y2 P Q. \n  inversion P. inversion Q.\n  reflexivity.  Qed.\n\n(** However, the [<=] relation on numbers is not a partial function.\n\n    This can be shown by contradiction.  In short: Assume, for a\n    contradiction, that [<=] is a partial function.  But then, since\n    [0 <= 0] and [0 <= 1], it follows that [0 = 1].  This is nonsense,\n    so our assumption was contradictory. *)\n\nTheorem le_not_a_partial_function :\n  ~ (partial_function le).\nProof.\n  unfold not. unfold partial_function. intros H.\n  assert (0 = 1) as Nonsense.\n   Case \"Proof of assertion\".\n   apply H with 0. \n     apply le_n. \n     apply le_S. apply le_n. \n  inversion Nonsense.   Qed.\n\n(** **** Exercise: 2 stars, optional *)\n(** Show that the [total_relation] defined in Logic.v is not a partial\n    function. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\n(** Show that the [empty_relation] defined in Logic.v is a partial\n    function. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** A _reflexive_ relation on a set [X] is one that holds for every\n    element of [X]. *)\n\nDefinition reflexive {X: Type} (R: relation X) :=\n  forall a : X, R a a.\n\nTheorem le_reflexive :\n  reflexive le.\nProof. \n  unfold reflexive. intros n. apply le_n.  Qed.\n\n(** A relation [R] is _transitive_ if [R a c] holds whenever [R a b]\n    and [R b c] do. *)\n\nDefinition transitive {X: Type} (R: relation X) :=\n  forall a b c : X, (R a b) -> (R b c) -> (R a c).\n\nTheorem le_trans :\n  transitive le.\nProof.\n  intros n m o Hnm Hmo.\n  induction Hmo.\n  Case \"le_n\". apply Hnm.\n  Case \"le_S\". apply le_S. apply IHHmo.  Qed.\n\nTheorem lt_trans:\n  transitive lt.\nProof. \n  unfold lt. unfold transitive. \n  intros n m o Hnm Hmo.\n  apply le_S in Hnm. \n  apply le_trans with (a := (S n)) (b := (S m)) (c := o).\n  apply Hnm.\n  apply Hmo. Qed.\n\n(** **** Exercise: 2 stars, optional *)\n(** We can also prove [lt_trans] more laboriously by induction,\n    without using le_trans.  Do this.*)\n\nTheorem lt_trans' :\n  transitive lt.\nProof.\n  (* Prove this by induction on evidence that [m] is less than [o]. *)\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction Hmo as [| m' Hm'o].\n    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\n(** Prove the same thing again by induction on [o]. *)\n\nTheorem lt_trans'' :\n  transitive lt.\nProof.\n  unfold lt. unfold transitive.\n  intros n m o Hnm Hmo.\n  induction o as [| o'].\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** The transitivity of [le], in turn, can be used to prove some facts\n    that will be useful later (e.g., for the proof of antisymmetry\n    below)... *)\n\nTheorem le_Sn_le : forall n m, S n <= m -> n <= m.\nProof. \n  intros n m H. apply le_trans with (S n).\n    apply le_S. apply le_n.\n    apply H.  Qed.\n\n(** **** Exercise: 1 star, optional *)\nTheorem le_S_n : forall n m,\n  (S n <= S m) -> (n <= m).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (le_Sn_n_inf) *)\n(** Provide an informal proof of the following theorem:\n \n    Theorem: For every [n], [~(S n <= n)]\n \n    A formal proof of this is an optional exercise below, but try\n    the informal proof without doing the formal proof first.\n \n    Proof:\n    (* FILL IN HERE *)\n    []\n *)\n\n(** **** Exercise: 1 star, optional *)\nTheorem le_Sn_n : forall n,\n  ~ (S n <= n).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Reflexivity and transitivity are the main concepts we'll need for\n    later chapters, but, for a bit of additional practice working with\n    relations in Coq, here are a few more common ones.\n\n   A relation [R] is _symmetric_ if [R a b] implies [R b a]. *)\n\nDefinition symmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a).\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_not_symmetric :\n  ~ (symmetric le).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** A relation [R] is _antisymmetric_ if [R a b] and [R b a] together\n    imply [a = b] -- that is, if the only \"cycles\" in [R] are trivial\n    ones. *)\n\nDefinition antisymmetric {X: Type} (R: relation X) :=\n  forall a b : X, (R a b) -> (R b a) -> a = b.\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_antisymmetric :\n  antisymmetric le.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional *)\nTheorem le_step : forall n m p,\n  n < m ->\n  m <= S p ->\n  n <= p.\nProof. \n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** A relation is an _equivalence_ if it's reflexive, symmetric, and\n    transitive.  *)\n\nDefinition equivalence {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (symmetric R) /\\ (transitive R).\n\n(** A relation is a _partial order_ when it's reflexive,\n    _anti_-symmetric, and transitive.  In the Coq standard library\n    it's called just \"order\" for short. *)\n\nDefinition order {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (antisymmetric R) /\\ (transitive R).\n\n(** A preorder is almost like a partial order, but doesn't have to be\n    antisymmetric. *)\n\nDefinition preorder {X:Type} (R: relation X) :=\n  (reflexive R) /\\ (transitive R).\n\nTheorem le_order :\n  order le.\nProof.\n  unfold order. split. \n    Case \"refl\". apply le_reflexive.\n    split. \n      Case \"antisym\". apply le_antisymmetric. \n      Case \"transitive.\". apply le_trans.  Qed.\n\n(* ########################################################### *)\n(** * Reflexive, Transitive Closure *)\n\n(** The _reflexive, transitive closure_ of a relation [R] is the\n    smallest relation that contains [R] and that is both reflexive and\n    transitive.  Formally, it is defined like this in the Relations\n    module of the Coq standard library: *)\n\nInductive clos_refl_trans {A: Type} (R: relation A) : relation A :=\n    | rt_step : forall x y, R x y -> clos_refl_trans R x y\n    | rt_refl : forall x, clos_refl_trans R x x\n    | rt_trans : forall x y z,\n          clos_refl_trans R x y -> clos_refl_trans R y z -> clos_refl_trans R x z.\n\n(** For example, the reflexive and transitive closure of the\n    [next_nat] relation coincides with the [le] relation. *)\n\nTheorem next_nat_closure_is_le : forall n m,\n  (n <= m) <-> ((clos_refl_trans next_nat) n m).\nProof.\n  intros n m. split.\n    Case \"->\".\n      intro H. induction H. \n         apply rt_refl.\n         apply rt_trans with m. apply IHle. apply rt_step. apply nn.\n    Case \"<-\".\n      intro H. induction H.\n        SCase \"rt_step\".  inversion H. apply le_S.  apply le_n. \n        SCase \"rt_refl\". apply le_n. \n        SCase \"rt_trans\". \n           apply le_trans with y.  \n           apply IHclos_refl_trans1. \n           apply IHclos_refl_trans2.  Qed.\n\n(** The above definition of reflexive, transitive closure is\n    natural -- it says, explicitly, that the reflexive and transitive\n    closure of [R] is the least relation that includes [R] and that is\n    closed under rules of reflexivity and transitivity.  But it turns\n    out that this definition is not very convenient for doing\n    proofs -- the \"nondeterminism\" of the rt_trans rule can sometimes\n    lead to tricky inductions.\n \n    Here is a more useful definition... *)\n\nInductive refl_step_closure {X:Type} (R: relation X) \n                            : X -> X -> Prop :=\n  | rsc_refl  : forall (x : X),\n                 refl_step_closure R x x\n  | rsc_step : forall (x y z : X),\n                    R x y ->\n                    refl_step_closure R y z ->\n                    refl_step_closure R x z.\n\n(** (The following [Tactic Notation] definitions are explained in\n    Imp.v.  You can ignore them if you haven't read that chapter\n    yet.) *)\n\nTactic Notation \"rt_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"rt_step\" | Case_aux c \"rt_refl\" \n  | Case_aux c \"rt_trans\" ].\n\nTactic Notation \"rsc_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"rsc_refl\" | Case_aux c \"rsc_step\" ].\n\n(** Our new definition of reflexive, transitive closure \"bundles\"\n    the [rtc_R] and [rtc_trans] rules into the single rule step.\n    The left-hand premise of this step is a single use of [R],\n    leading to a much simpler induction principle.\n \n    Before we go on, we should check that the two definitions do\n    indeed define the same relation...\n    \n    First, we prove two lemmas showing that [rsc] mimics the behavior\n    of the two \"missing\" [rtc] constructors.  *)\n\nTheorem rsc_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> refl_step_closure R x y.\nProof.\n  intros X R x y r.\n  apply rsc_step with y. apply r. apply rsc_refl.   Qed.\n\n(** **** Exercise: 2 stars, optional (rsc_trans) *)\nTheorem rsc_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      refl_step_closure R x y  ->\n      refl_step_closure R y z ->\n      refl_step_closure R x z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Then we use these facts to prove that the two definitions of\n    reflexive, transitive closure do indeed define the same\n    relation. *)\n\n(** **** Exercise: 3 stars, optional (rtc_rsc_coincide) *)\nTheorem rtc_rsc_coincide : \n         forall (X:Type) (R: relation X) (x y : X),\n  clos_refl_trans R x y <-> refl_step_closure R x y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n", "meta": {"author": "Blaisorblade", "repo": "Software-Foundations", "sha": "aeb1b49fd922a346b774b330694fe6c16caf9626", "save_path": "github-repos/coq/Blaisorblade-Software-Foundations", "path": "github-repos/coq/Blaisorblade-Software-Foundations/Software-Foundations-aeb1b49fd922a346b774b330694fe6c16caf9626/Rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7086473960425056}}
{"text": "Require Import List Arith Lia. \nImport ListNotations.\nFrom Undecidability.HOU Require Import std.tactics std.lists.basics std.decidable. \n\nSet Default Proof Using \"Type\".\n\n(* nth *)\nNotation nth := nth_error. \nSection Nth.\n\n  Variable (X Y: Type).\n\n  Lemma nth_error_map_option n (f: X -> Y) (A: list X):\n    nth_error (map f A) n = option_map f (nth_error A n).\n  Proof.\n    destruct (nth_error A n) eqn: H1.\n    + eapply map_nth_error in H1. rewrite H1. reflexivity.\n    + eapply nth_error_None in H1.\n      eapply nth_error_None. now rewrite map_length. \n  Qed.\n\n\n\n  Lemma nth_error_lt_Some Z m (L: list Z):\n    m < length L -> exists a, nth L m = Some a.\n  Proof.\n    intros H % nth_error_Some.\n    destruct nth; intuition. now (exists z).\n  Qed.\n\n  Lemma nth_error_Some_lt Z m a (L: list Z):\n    nth L m = Some a -> m < length L.\n  Proof.\n    intros H; eapply nth_error_Some; rewrite H; discriminate. \n  Qed.    \n\nEnd Nth.\n\n\n(* nats *)\nSection Nats.\n\n  Fixpoint nats (n: nat) :=\n    match n with\n    | 0 => nil\n    | S n => 0 :: map S (nats n)\n    end.\n\n  Lemma nats_lt: forall k i, i ∈ nats k -> i < k.\n  Proof.\n    induction k; cbn; intuition. lia.\n    eapply in_map_iff in H0. destruct H0; intuition; subst.\n    specialize (IHk x H1); lia.\n  Qed.\n\n  Lemma nth_nats m k:\n    m < k -> nth (nats k) m = Some m.\n  Proof.\n    induction k in m |-*.\n    - lia.\n    - intros; destruct m; cbn in *; eauto.\n      erewrite map_nth_error; eauto.\n      eapply IHk; lia.\n  Qed.\n  \n  Lemma lt_nats x k:\n    x < k -> x ∈ nats k.\n  Proof.\n    now intros H % nth_nats % nth_error_In. \n  Qed.\n\n  Lemma incl_nats I k:\n    I ⊆ nats k -> forall i, i ∈ I -> i < k.\n  Proof.\n    firstorder using nats_lt.\n  Qed.\n\n  Lemma nats_incl I k:\n    (forall i, i ∈ I -> i < k) -> I ⊆ nats k.\n  Proof.\n    firstorder using lt_nats.\n  Qed.\n\n\n  Lemma length_nats k: length (nats k) = k.\n  Proof.\n    induction k; cbn; lsimpl; congruence.\n  Qed.\n\nEnd Nats.\nGlobal Hint Rewrite length_nats : listdb.\n\n\n\n(* tabulate *)\nSection Tabulate.\n  Implicit Type  X: Type.\n\n  Fixpoint tab {X} (f: nat -> X) k  :=\n    match k with\n    | 0 => nil\n    | S n => tab f n ++ [f n]\n    end.\n  \n  Lemma tab_length X (f: nat -> X) k: length (tab f k) = k.\n  Proof.\n    induction k; cbn; lsimpl; cbn; lsimpl; lia. \n  Qed.\n\n  Lemma tab_map X Y (f: nat -> X) (g: X -> Y) k:\n    map g (tab f k) = tab (fun x => g (f x)) k.\n  Proof.\n    induction k; cbn; eauto; lsimpl; now rewrite IHk.\n  Qed.\n\n  Lemma tab_S X (f: nat -> X) n:\n    tab f (S n) = f 0 :: tab (fun k => f (S k)) n.\n  Proof.\n    induction n; cbn; eauto.\n    cbn in *; now rewrite IHn.\n  Qed.\n   \n  Lemma tab_plus X (f: nat -> X) n m:\n    tab f (n + m) = tab f n ++ tab (fun k => f (n + k)) m.\n  Proof.\n    induction n in f |-*; eauto.  \n    cbn [plus]; now rewrite tab_S, IHn, tab_S.\n  Qed.\n\n  Lemma tab_map_nats X k (f: nat -> X): tab f k = map f (nats k).\n  Proof.\n    induction k in f |-*; eauto.\n    cbn [nats map]; now rewrite tab_S, IHk, map_map.\n  Qed.\n\n  Lemma tab_id_nats k: tab id k = nats k.\n  Proof.\n    rewrite tab_map_nats; now lsimpl. \n  Qed.\n\n\n  Lemma tab_nth {X} n m (f: nat -> X):\n    n < m -> nth (tab f m) n = Some (f n).\n  Proof.\n    induction 1; cbn.\n    + rewrite nth_error_app2, tab_length, Nat.sub_diag; cbn; eauto.\n      rewrite tab_length; eauto.\n    + rewrite nth_error_app1; eauto.\n      now rewrite tab_length. \n  Qed.\n\n\n  Lemma tab_ext {X} (f g: nat -> X) n: (forall x, f x = g x) -> tab f n = tab g n.\n  Proof.\n    rewrite !tab_map_nats. intros; now apply map_ext.\n  Qed.\n\n\n\n\nEnd Tabulate.\nGlobal Hint Rewrite tab_length tab_id_nats : listdb. \n\n\n\n\n\n(* Repeated *)\nSection Repeated.\n  Variable (X Y: Type).\n  Implicit Types (x y: X) (n m: nat) (f: X -> Y). \n\n  Lemma repeated_in x n y: y ∈ repeat x n -> x = y.\n  Proof.\n    induction n; cbn; firstorder.\n  Qed.\n\n  Lemma repeated_plus n m x:\n    repeat x (n + m) = repeat x n ++ repeat x m.\n  Proof.\n    induction n; cbn; congruence.\n  Qed.\n  \n  Lemma repeated_rev n x: rev (repeat x n) = repeat x n.\n  Proof.\n    induction n; cbn; eauto.\n    rewrite IHn. change [x] with (repeat x 1).\n    rewrite <-repeated_plus.\n    rewrite plus_comm. reflexivity.\n  Qed.\n\n  Lemma repeated_map n x f:\n    map f (repeat x n) = repeat (f x) n.\n  Proof.\n    induction n; cbn; congruence.\n  Qed.\n  \n  Lemma repeated_length n x: length (repeat x n) = n.\n  Proof.\n    induction n; cbn; congruence.\n  Qed.\n  \n\n  Lemma repeated_equal n y A:\n    (forall x, x ∈ A -> x = y) -> length A = n -> repeat y n = A.\n  Proof.\n    induction A in n |-*; destruct n; cbn; eauto; try discriminate.\n    injection 2. rewrite IHA; eauto.\n    intros. erewrite <-H; intuition.\n  Qed.\n\n  Lemma repeated_incl x n A:\n    x ∈ A -> repeat x n ⊆ A.\n  Proof.\n    intros ? ? ? % repeated_in; subst; eauto.\n  Qed.\n\n  \n  Lemma repeated_tab (x: X) n:\n    repeat x n = tab (Basics.const x) n.\n  Proof.\n    induction n; eauto; cbn [tab].\n    replace (S n) with (n + 1) by lia.\n    rewrite repeated_plus; cbn.\n    rewrite IHn; reflexivity. \n  Qed.\n\n\n\n  Lemma nth_error_repeated (x: X) n k :\n    k < n -> nth (repeat x n) k = Some x.\n  Proof.\n    intros H.\n    erewrite repeated_tab, tab_map_nats, map_nth_error; eauto.\n    now eapply nth_nats.\n  Qed.\n\n\n  Lemma repeated_app_inv n x A B:\n    repeat x n = A ++ B ->\n    n = length A + length B /\\\n    A = repeat x (length A) /\\\n    B = repeat x (length B).\n  Proof.\n    induction n in A, B |-*.\n    - cbn; destruct A, B; try discriminate. intuition.\n    - destruct A; cbn; try discriminate.\n      + destruct B; try discriminate. \n        injection 1. intuition. cbn; now rewrite <-H0, repeated_length.\n        subst. cbn; now rewrite repeated_length.\n      + injection 1; intros; edestruct IHn; eauto. \n        intuition. f_equal; eauto. \n  Qed.         \n\nEnd Repeated.\n\n\nGlobal Hint Rewrite  repeated_length repeated_map repeated_plus repeated_rev: listdb.\n\n\n\n\n\n\n\n(* select *)\nSection Select.\n\n  Context {X: Type}.\n\n  Fixpoint select (A: list nat) (B: list X)  :=\n    match A with\n    | nil => nil\n    | i :: A => match nth B i with\n               | Some x => x :: select A B\n               | None => select A B \n               end\n    end.\n  \n  Lemma select_nil I:\n    select I nil = nil.\n  Proof.\n    induction I; cbn.\n    - reflexivity.\n    - destruct nth eqn: H; eauto.\n      eapply nth_error_In in H; cbn in H; intuition.\n  Qed.\n\n  Lemma select_S I (x: X) A:\n    select (map S I) (x :: A) = select I A.\n  Proof.\n    induction I.\n    - reflexivity.\n    - cbn. rewrite IHI. reflexivity. \n  Qed.\n  \n\n  Lemma select_nats k A:\n    select (nats k) A = firstn k A.\n  Proof.\n    induction k in A |-*.\n    - reflexivity.\n    - destruct A.\n      + rewrite select_nil; reflexivity.\n      + cbn. rewrite select_S, IHk. reflexivity.\n  Qed.\n\n\n  Lemma select_repeated n I x:\n    I ⊆ nats n -> select I (repeat x n) = repeat x (length I).\n  Proof.\n    induction I; cbn; eauto; intros.\n    rewrite IHI; eauto with listdb.\n    edestruct (nth_error_lt_Some) as [y H']; try rewrite H'.\n    eapply nats_lt; lsimpl; firstorder.\n    now eapply nth_error_In, repeated_in in H'; subst.\n  Qed.\n\n  Lemma select_incl I A: select I A ⊆ A.\n  Proof.\n    induction I; cbn; intuition.\n    destruct nth eqn: H1; intuition.\n    eapply nth_error_In in H1. intuition.\n  Qed.\n\n  Lemma incl_select A B: A ⊆ B -> exists I, I ⊆ nats (length B) /\\ select I B = A.\n  Proof.\n    induction A.\n     + exists nil. lauto.\n     + intros; destruct IHA as [I []]; lauto. specialize (H a). mp H; lauto.\n        eapply In_nth_error in H as [i].\n        exists (i::I). cbn. rewrite H, H1. split; lauto.\n        eapply nth_error_Some_lt, lt_nats in H; lauto.\n  Qed.\nEnd Select.\n\n\nLemma select_map X Y (f: X -> Y) I A:\n  map f (select I A) = select I (map f A).\nProof.\n  induction I in A |-*; cbn; eauto.\n  rewrite nth_error_map_option.\n  destruct nth; cbn; now rewrite IHI.\nQed.\n    \n\n\n\n\n\n(* find *)\nSection Find.\n  \n  Context {X: Type}.\n  Context {D: Dis X}.\n\n  Fixpoint find (x: X) (A: list X) : option nat :=\n    match A with\n    | nil => None\n    | y :: A => if x == y then Some 0 else option_map S (find x A)\n    end.\n\n  Lemma find_Some x A n:\n    find x A = Some n -> nth A n = Some x.\n  Proof.\n    induction A in n |-*; cbn.\n    - discriminate.\n    - destruct (x == a).\n      injection 1; intros; subst. reflexivity.\n      destruct find; try discriminate.\n      cbn; injection 1; intros; subst.\n      cbn. now rewrite IHA.\n  Qed.\n\n\n  Lemma find_in x A:\n    x ∈ A -> exists n, find x A = Some n.\n  Proof.\n    induction A; cbn; intuition.  \n    - exists 0. destruct (x == a); subst; intuition.\n    - destruct (x == a).\n      + subst; exists 0; intuition.\n      + destruct H as [m]; exists (S m); intuition.\n        rewrite H; reflexivity.\n  Qed.\n\n  Lemma find_Some_nth x A n:\n    nth A n = Some x -> exists k, find x A = Some k. \n  Proof.\n    now intros ? % nth_error_In % find_in. \n  Qed.\n      \n\n  Lemma find_not_in x A:\n    find x A = None -> ~ x ∈ A.\n  Proof.\n    intros H [n H'] % find_in; rewrite H in H'; discriminate.\n  Qed.\n\n\n  Lemma find_map f A n x:\n    find x A = Some n -> exists m, find (f x) (map f A) = Some m.\n  Proof.\n    induction A in n |-*; cbn; try discriminate.\n    destruct eq_dec; intuition; subst.\n    - exists 0; destruct eq_dec; intuition.\n    - destruct (find x A); try discriminate.\n      edestruct IHA as [m]; eauto.\n      destruct eq_dec; eauto.\n      exists (S m). now rewrite H0.\n  Qed.\n\n\n\n\nEnd Find.\n\nLemma find_map_inv X Y {D1: Dis X} {D2: Dis Y} y (f: X -> Y) (A: list X) (n: nat):\n  find y (map f A) = Some n -> exists x, f x = y /\\ find x A = Some n.\nProof.\n  induction A in y, n  |-*; cbn; intuition; try discriminate.\n  destruct eq_dec.\n  + injection H as ?; subst; exists a; intuition. destruct eq_dec; intuition.\n  + destruct find eqn: H1; try discriminate. injection H as ?; subst.\n    eapply IHA in H1 as []; intuition; subst.\n    exists x. intuition; destruct eq_dec; cbn; try congruence. now rewrite H1.\nQed.\n\nSection Remove.\n\n  Variable (X: Type) (D: Dis X).\n\n  Lemma remove_remain  (x y: X) A:\n    x ∈ A -> x <> y -> x ∈ remove eq_dec y A.\n  Proof.\n    induction A; cbn; intuition; subst.\n    - destruct (y == x); subst; intuition.\n    - destruct (y == a); subst; intuition.\n  Qed.\n\n\n  Lemma remove_prev (x y: X) (A: list X):\n    y ∈ remove eq_dec x A -> y ∈ A.\n  Proof.\n    induction A; intuition.\n    cbn in H. destruct (x == a); subst; intuition.\n    cbn in *; intuition.\n  Qed.\n\nEnd Remove.\n\n\nSection FlatMap.\n\n  Variable (X Y: Type).\n  Implicit Types (A B: list X) (f: X -> list Y).\n\n  Lemma flat_map_app f A B:\n    flat_map f (A ++ B) = flat_map f A ++ flat_map f B.\n  Proof.\n    induction A; cbn; eauto; now rewrite IHA, app_assoc.\n  Qed.\n\n  Lemma flat_map_incl (f: X -> list Y) A B:\n    A ⊆ B -> flat_map f A ⊆ flat_map f B.\n  Proof.\n    intros H x [y []] % in_flat_map.\n    eapply in_flat_map; exists y; intuition.\n  Qed.\n\n  Lemma flat_map_in_incl f a A:\n    a ∈ A -> f a ⊆ flat_map f A.\n  Proof.\n    revert A; eapply in_ind; cbn; intuition.\n  Qed.\n\nEnd FlatMap.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/HOU/std/lists/advanced.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339636614178, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7086473826794167}}
{"text": "(** * Logic: Logic in Coq *)\n\nRequire Export MoreCoq.\n\n(** * Proofs and Evidence *)\n\n(** ** Implications _are_ functions *)\n\n(** * Conjunction (Logical \"and\") *)\n\nInductive and (P Q : Prop) : Prop :=\n  conj : P -> Q -> (and P Q).\n\nNotation \"P /\\ Q\" := (and P Q) : type_scope.\n\n(** ** \"Eliminating\" conjunctions *)\n\nTheorem proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, optional (proj2) *)\nTheorem proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HP HQ].\n  apply H.\nQed.\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HP HQ].\n  split.\n    Case \"left\". apply HQ.\n    Case \"right\". apply HP.  Qed.\n\n\n(** **** Exercise: 2 stars (and_assoc) *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [inversion] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop,\n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  inversion H as [HP [HQ HR]].\n  split.\n    split.\n      apply HP.\n      apply HQ.\n    apply HR.\nQed.\n\n(** * Iff *)\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nTheorem iff_implies : forall P Q : Prop,\n  (P <-> Q) -> P -> Q.\nProof.\n  intros P Q H.\n  inversion H as [HAB HBA]. apply HAB.  Qed.\n\nTheorem iff_sym : forall P Q : Prop,\n  (P <-> Q) -> (Q <-> P).\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H.\n  inversion H as [HAB HBA].\n  split.\n    Case \"->\". apply HBA.\n    Case \"<-\". apply HAB.  Qed.\n\n(** **** Exercise: 1 star, optional (iff_properties) *)\n(** Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros P.\n  split.\n    intros HP. apply HP.\n    intros HP. apply HP.\nQed.\n\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R HPQ HQR.\n  inversion HPQ as [HAB HBA].\n  inversion HQR as [HBC HCB].\n  split.\n    Case \"P -> R\".\n      intros HP.\n      apply HAB in HP. apply HBC. apply HP.\n    Case \"R -> P\".\n      intros HR.\n      apply HCB in HR. apply HBA. apply HR.\nQed.\n(** Hint: If you have an iff hypothesis in the context, you can use\n    [inversion] to break it into two separate implications.  (Think\n    about why this works.) *)\n\n(** * Disjunction (Logical \"or\") *)\n\n(** ** Implementing Disjunction *)\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nNotation \"P \\/ Q\" := (or P Q) : type_scope.\n\nTheorem or_commut : forall P Q : Prop,\n  P \\/ Q  -> Q \\/ P.\nProof.\n  intros P Q H.\n  inversion H as [HP | HQ].\n    Case \"left\". apply or_intror. apply HP.\n    Case \"right\". apply or_introl. apply HQ.  Qed.\n\nTheorem or_distributes_over_and_1 : forall P Q R : Prop,\n  P \\/ (Q /\\ R) -> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R. intros H. inversion H as [HP | [HQ HR]].\n    Case \"left\". split.\n      SCase \"left\". left. apply HP.\n      SCase \"right\". left. apply HP.\n    Case \"right\". split.\n      SCase \"left\". right. apply HQ.\n      SCase \"right\". right. apply HR.  Qed.\n\n(** **** Exercise: 2 stars (or_distributes_over_and_2) *)\nTheorem or_distributes_over_and_2 : forall P Q R : Prop,\n  (P \\/ Q) /\\ (P \\/ R) -> P \\/ (Q /\\ R).\nProof.\n  intros P Q R H.\n  inversion H as [[HP1 | HQ] [HP2 | HR]].\n  Case \"P1 and P2\".\n    left. apply HP1.\n  Case \"P1 and R\".\n    left. apply HP1.\n  Case \"Q and P2\".\n    left. apply HP2.\n  Case \"Q and R\".\n    right. split. apply HQ. apply HR.\nQed.\n\n(** **** Exercise: 1 star, optional (or_distributes_over_and) *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n    Case \"->\". apply or_distributes_over_and_1.\n    Case \"<-\". apply or_distributes_over_and_2.\nQed.\n\n(** ** Relating [/\\] and [\\/] with [andb] and [orb] (advanced) *)\n\nTheorem andb_prop : forall b c,\n  andb b c = true -> b = true /\\ c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". apply conj. reflexivity. reflexivity.\n      SCase \"c = false\". inversion H.\n    Case \"b = false\". inversion H.  Qed.\n\nTheorem andb_true_intro : forall b c,\n  b = true /\\ c = true -> andb b c = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros b c H.\n  inversion H.\n  rewrite H0. rewrite H1. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, optional (bool_prop) *)\nTheorem andb_false : forall b c,\n  andb b c = false -> b = false \\/ c = false.\nProof.\n  intros b c H. destruct b.\n    Case \"b = true\". destruct c.\n      SCase \"c = true\". inversion H.\n      SCase \"c = false\". right. reflexivity.\n    Case \"b = false\". left. reflexivity.\nQed.\n\nTheorem orb_prop : forall b c,\n  orb b c = true -> b = true \\/ c = true.\nProof.\n  intros b c H. destruct b.\n    Case \"b = true\". left. reflexivity.\n    Case \"b = false\". destruct c.\n      SCase \"c = true\". right. reflexivity.\n      SCase \"c = false\". inversion H.\nQed.\n\nTheorem orb_false_elim : forall b c,\n  orb b c = false -> b = false /\\ c = false.\nProof.\n  intros b c H. destruct b.\n    Case \"b = true\". inversion H.\n    Case \"b = false\". destruct c.\n      inversion H.\n      apply conj. reflexivity. reflexivity.\nQed.\n\n(** * Falsehood *)\n\nInductive False : Prop := .\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  inversion contra.  Qed.\n\n(** ** Truth *)\n\n(** **** Exercise: 2 stars, advanced (True) *)\n(** Define [True] as another inductively defined proposition.  (The\n    intuition is that [True] should be a proposition for which it is\n    trivial to give evidence.) *)\n\nInductive True : Prop := true : True.\n\n(** * Negation *)\n\nDefinition not (P:Prop) := P -> False.\n\nNotation \"~ x\" := (not x) : type_scope.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. inversion H.  Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q H. inversion H as [HP HNA]. unfold not in HNA.\n  apply HNA in HP. inversion HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf) *)\n(** Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P].\n\n   _Proof_:\n(* TODO *)\n   []\n*)\n\n(** **** Exercise: 2 stars (contrapositive) *)\nTheorem contrapositive : forall P Q : Prop,\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q H1 H2. unfold not. unfold not in H2. intros H.\n  apply H2. apply H1. apply H.\nQed.\n\n(** **** Exercise: 1 star (not_both_true_and_false) *)\nTheorem not_both_true_and_false : forall P : Prop,\n  ~ (P /\\ ~P).\nProof.\n  intros P. unfold not. intros H. inversion H. apply H1. apply H0.\nQed.\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP) *)\n(** Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* TODO *)\n(** [] *)\n\n(** *** Constructive logic *)\n\n(** **** Exercise: 5 stars, advanced, optional (classical_axioms) *)\n(** For those who like a challenge, here is an exercise\n    taken from the Coq'Art book (p. 123).  The following five\n    statements are often considered as characterizations of\n    classical logic (as opposed to constructive logic, which is\n    what is \"built in\" to Coq).  We can't prove them in Coq, but\n    we can consistently add any one of them as an unproven axiom\n    if we wish to work in classical logic.  Prove that these five\n    propositions are equivalent. *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\nDefinition classic := forall P:Prop,\n  ~~P -> P.\nDefinition excluded_middle := 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\nModule ex_classical_axioms.\n\n(* Theorem th1eq2 : forall P Q : Prop, *)\n(*   ((P->Q)->P)->P <-> ~~P -> P. *)\n(* Proof. *)\n(*   intros P Q. split. *)\n(*   Case \"->\". intros H0. unfold not. intros H1. apply H0. *)\n(*   intros H2. apply contrapositive in H2. unfold not in H2. *)\n(*   apply H1 in H2. inversion H2. *)\n(*   unfold not. intros HQ. apply H1. intros HP. apply double_neg.  *)\n(** [] *)\n\nEnd ex_classical_axioms.\n\n(** **** Exercise: 3 stars (excluded_middle_irrefutable) *)\n(** This theorem implies that it is always safe to add a decidability\naxiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].\nWhy? Because we cannot prove the negation of such an axiom; if we could,\nwe would have both [~ (P \\/ ~P)] and [~ ~ (P \\/ ~P)], a contradiction. *)\n\nTheorem excluded_middle_irrefutable : forall (P : Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  intros P. unfold not. intros H0. apply H0.\n  right. intros HP. apply H0. left. apply HP.\nQed.\n\n(** ** Inequality *)\n\nNotation \"x <> y\" := (~ (x = y)) : type_scope.\n\nTheorem not_false_then_true : forall b : bool,\n  b <> false -> b = true.\nProof.\n  intros b H. destruct b.\n  Case \"b = true\". reflexivity.\n  Case \"b = false\".\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.   Qed.\n\n(** **** Exercise: 2 stars (false_beq_nat) *)\nTheorem false_beq_nat : forall n m : nat,\n     n <> m ->\n     beq_nat n m = false.\nProof.\n  intros n.\n  induction n as [| n'].\n  Case \"n = 0\".\n    intros m H. unfold not in H. destruct m as [| m'].\n    SCase \"m = 0\".\n      simpl. apply ex_falso_quodlibet. apply H. reflexivity.\n    SCase \"m = S m'\".\n      simpl. reflexivity.\n  Case \"n = S n'\".\n    intros m H. destruct m as [| m'].\n    SCase \"m = 0\".\n      simpl. reflexivity.\n    SCase \"m = S m'\".\n      apply IHn'.\n      unfold not. unfold not in H. intros H0.\n      apply H. apply f_equal. apply H0.\nQed.\n\n(** **** Exercise: 2 stars, optional (beq_nat_false) *)\nTheorem beq_nat_false : forall n m,\n  beq_nat n m = false -> n <> m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    intros m H. destruct m as [| m'].\n    SCase \"m = 0\".\n      unfold not. inversion H.\n    SCase \"m = S m'\". intros H0. inversion H0.\n  Case \"n = S n'\".\n    intros m H. destruct m as [| m'].\n    SCase \"m = 0\".\n      unfold not. intro H0. inversion H0.\n    SCase \"m = S m'\".\n      apply IHn' in H. unfold not. unfold not in H.\n      intros H0. apply H. apply eq_add_S. apply H0.\nQed.\n", "meta": {"author": "kmiya", "repo": "software_foundations", "sha": "af69f496f643ce93b1dc90a8f69b8c61b4a0b88f", "save_path": "github-repos/coq/kmiya-software_foundations", "path": "github-repos/coq/kmiya-software_foundations/software_foundations-af69f496f643ce93b1dc90a8f69b8c61b4a0b88f/ex_Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7085782782882198}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := plus x (plus y Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_commut/goal33conj2910_coqofml_bjOrtk.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7085138902043471}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) : natural := plus y (plus Zero x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj2910_coqofml_g57vFG.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7905303211371899, "lm_q1q2_score": 0.7085138858229683}}
{"text": "Require Import Orders. \n\n(**** Aliases ****)\nDefinition dlink {A: Type} := @list A. (* \"Doubly Linked List\". *)\nDefinition dmerge {A: Type} := @app A. \nDefinition dsingle {A: Type} (x: A) := cons x nil. \nDefinition dempty {A: Type} := @nil A. \nDefinition dlength {A: Type} := @length A. \nDefinition dmin {A: Type} (d : @dlink A) := (* TO DO *)\n  match d with\n  | nil => None\n  | cons hd tl => Some hd\n  end.\nDefinition drest {A: Type} (d: @dlink A) : @dlink A := (* TO DO *)\n  (* Removes the minimum element, and returns the rest of the dlink. *)\n  @nil A. \nDefinition dconsolidate {A N: Type} (* TO DO *)\n           (key: A -> N) (link: A -> A -> A) (d: @dlink A): @dlink A :=\n  (* A generic consolidation function. See the `consolidate` procedure of CLRS. *)\n  dempty. \n\n\n\n(**************** Definition ****************)\nModule Ops (X: OrderedType).\n  Definition lt (a b: X.t) : bool :=\n    match X.compare a b with\n    | Eq => false\n    | Lt => true\n    | Gt => false\n    end.\n  Local Notation \"a < b\" := (lt a b). \n\n  (* Definition of a Fibonacci Heap. Notable aspects\n     - There is no \"Node\" type. Nodes are themselves fheaps. *)\n  Inductive fheap :=\n  | Leaf : fheap \n  | Atop : X.t -> fheap -> fheap\n  | Ptr : @dlink fheap -> fheap.\n\n  (**** Helpers ****)\n  Definition extractdl (H : fheap) : (@dlink fheap) :=\n    match H with\n    | Leaf => dempty\n    | Atop x _ => dsingle H\n    | Ptr d => d\n    end.\n\n  Definition singleton (x: X.t) :=\n    Atop x Leaf.\n    \n  Definition top (H : fheap) :=\n    match H with\n    | Leaf => None\n    | Atop x _ => Some x\n    | Ptr _ => None\n    end.\n  \n  Definition degree (H : fheap) : nat :=\n    match H with\n    | Leaf => 0\n    | Atop x H' =>\n      match H' with\n      | Leaf => 0\n      | _ => 1\n      end\n    | Ptr d =>\n      dlength d\n    end.\n\n  Definition minimum_t (H: fheap) : option X.t :=\n    (* \"Minimum temporary\". Needed as a helper function, but is also one of the\n       core operations of an fheap. Identical to `minimum` as of Sun Apr  7 23:28:54\n       EDT 2019 *)\n    match H with\n    | Leaf => None\n    | Atop x _ => Some x\n    | Ptr d =>\n      match (dmin d) with\n      | None => None (* Should not happen *)\n      | Some H' => top H'\n      end\n    end.\n\n  Definition link (H1 H2: fheap) : fheap :=\n    (* The `fib-heap-link` procedure of CLRS. Links two fheaps constructed using\n    `Atop`. *)\n    match H1, H2 with\n    | Atop x1 H1', Atop x2 H2' =>\n      if (x1 < x2) then\n        Atop x1 (Ptr (dmerge\n                        (extractdl H1')\n                        (extractdl H2)))\n      else\n        Atop x2 (Ptr (dmerge\n                        (extractdl H1)\n                        (extractdl H2')))\n    | _, _ => Leaf (* Should not happen *)\n    end. \n\n  Definition consolidate (H: fheap) : fheap :=\n    (* The `consolidate` procedure of CLRS. To achieve the required amortized\n    time bounds, needs to run in time linear to the number of nodes in the root list. *)\n    Ptr (dconsolidate degree link (extractdl H)). \n      \n\n  (**************** Mergeable heap operations ****************)\n  (* As defined in CLRS, a mergeable heap has 5 fundamental operations:\n   * Make-heap()\n   * Insert(H, x)\n   * Minimum(H)\n   * Extract-min(H)\n   * Union(H1, H2)\n   In addition, their implementation of a fibonacci heap has two additional *)\n  (* operations:\n   * Decrease-key(H, x, k)\n   * Delete(H, x) *)\n\n  Definition make_heap := Leaf. \n\n  Fixpoint union (H1 H2: fheap) : fheap :=\n    match H1, H2 with\n    | Leaf, _ => H2\n    | _, Leaf => H1 (* I believe these are necessary for efficiency reasons --\n                       so we don't get long pointers of leaves *)      \n    | _, _ => Ptr (dmerge (extractdl H1) (extractdl H2))\n    end. \n      \n  Definition insert (x: X.t) (H: fheap) : fheap :=\n    union (singleton x) H.\n\n  Definition minimum : fheap -> option X.t := minimum_t. \n\n  (* Unlike imperative implementations, doesn't return the minimum\n  element. Rather, returns the fheap with the element removed. *)\n  Definition extract_min (H: fheap) : option fheap :=\n    match H with\n    | Leaf => None\n    | Atop _ H' => Some H'\n    | Ptr d =>\n      match (dmin d) with\n      | None => None (* Should not happen *)\n      | Some H' =>\n        match H' with\n        | Leaf => None (* Should not happen *)\n        | Ptr _ => None (* Should not happen *)\n        | Atop x H'' => Some (consolidate (union H'' (Ptr (drest d))))\n        end\n      end\n    end.\n      \nEnd Ops. ", "meta": {"author": "johnmwu", "repo": "coq-fibheap", "sha": "13a348faf1791f4d21715a6e7614f560c9a8fdb6", "save_path": "github-repos/coq/johnmwu-coq-fibheap", "path": "github-repos/coq/johnmwu-coq-fibheap/coq-fibheap-13a348faf1791f4d21715a6e7614f560c9a8fdb6/fibheap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7085138835698057}}
{"text": "Require Import List.\nImport ListNotations.\n\n(** ** Traditional Definition *)\n\nDefinition symbol := nat.\nDefinition string X := list X.\nDefinition card X : Type := string X * string X.\nDefinition stack X := list (card X).\nDefinition SRS := stack nat.\nDefinition BSRS := stack bool.\n\nNotation \"x / y\" := (x,y).\n\nFixpoint tau1 {X : Type} (A : stack X) : string X :=\n  match A with\n  | [] => []\n  | (x / y) :: A => x ++ (tau1 A)\n  end.\n\nFixpoint tau2 {X : Type} (A : stack X) : string X :=\n  match A with\n  | [] => []\n  | (x / y) :: A => y ++ tau2 A\n  end.\n\n(* Post correspondence problem *)\nDefinition PCP P := exists A : SRS, incl A P /\\ A <> [] /\\ tau1 A = tau2 A.\n\n(* Modified Post correspondence problem *)\nDefinition MPCP '((x,y), P) := exists A : SRS, incl A (x/y :: P) /\\ x ++ tau1 A = y ++ tau2 A.\n\n\n(*\n  Problem:\n    Binary modified Post correspondence problem (BMPCP)\n\n  BMPCP:\n    Given a pair (x, y) of binary strings and \n    a list P of pairs of binary strings,\n    is there a list A = [(x₁, y₁),...,(xₙ, yₙ)] of pairs of binary strings such that\n    x ++ x₁ ++ ... ++ xₙ = y ++ y₁ ++ ... yₙ?\n    \n*)\nDefinition BMPCP '((x,y), P) := exists A : BSRS, incl A (x/y :: P) /\\ x ++ tau1 A = y ++ tau2 A.\n", "meta": {"author": "uds-psl", "repo": "2020-types-propositional-calculi", "sha": "87d61951f216881ccb45984349031915b2f842ee", "save_path": "github-repos/coq/uds-psl-2020-types-propositional-calculi", "path": "github-repos/coq/uds-psl-2020-types-propositional-calculi/2020-types-propositional-calculi-87d61951f216881ccb45984349031915b2f842ee/PCP/PCP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7085138813791163}}
{"text": "\n\n\n\n\n(* --------- COMREHENSIVE EXAM ITP READING COURSE 2020-21 2ND SEM --------\n\n             Remove all the Admitted from this file by completing the proofs.\n\nNote that before trying to work with this file you should compile the following files in the \ngiven order:\n 1. GenReflect.v and \n 2. SetSpecs.v \nMore precisely open terminal and go to the folder containing these files and type,\ncoqc GenReflect.v (press enter)\ncoqc SetSpecs.v   (press enter)  \n\n\n--- Following is an overview of the functions and predicates defined in this file ----\n\n-- In this file we would like to formalize the concept of sorting in a list.  We consider \n   lists of elements (on an arbitrary type A) with a boolean comparison operator \n   (lr: A-> A-> bool). Most of  the results in this file assumes only   \n   1. reflexive, \n   2. transitive and \n   3. comparable \n   nature of the boolean operator lr. \n   Only the last result (equality of head) assumes the antisymmetric\n   property of lr (i.e the comparison operator). \n\n   Following are the concepts formalized in this file: \n\n   Sorted l      <==> A Proposition to specify that l is sorted w.r.t comp operator lr \n   putin a l      ==> puts the element a into a sorted list at its correct position w.r.t lr\n   sort l         ==> a function that sorts the list l w.r.t the comp operator lr \n\n   Some of the useful results in this file are:\n\n   Lemma putin_correct (H_trans: transitive lr)(H_comp: comparable lr):\n    forall (a:A) (l: list A), Sorted l -> Sorted (putin a l).\n\n   Lemma nodup_putin (a:A)(l:list A): NoDup (a::l)-> NoDup (putin a l).\n\n   Lemma sort_correct (H_trans: transitive lr)(H_comp: comparable lr):\n    forall(l: list A), Sorted (sort l).\n\n   Lemma sort_equal (l: list A): Equal l (sort l).\n\n   Lemma nodup_sort (l: list A): NoDup l -> NoDup (sort l). ------------------  *)\n\n\n\nRequire Export Lists.List.\nRequire Export GenReflect SetSpecs.\nRequire Export Omega.\n\nSet Implicit Arguments.\n\nSection Sorting.\n  Context {A: Type }.\n\n  Variable lr: A->A-> bool.\n  Notation \" a <=r b\":= (lr a b)(at level 70, no associativity).\n  \n (* ------------- sorting a list of elements by lr relation ------------------------------*)\n  \n  Inductive  Sorted : list A-> Prop:=\n  | nil_Sorted: Sorted nil\n  | cons_Sorted (a:A)(l: list A): Sorted l -> (forall x, (In x l -> (a <=r x))) -> Sorted (a::l).  \n\n  Lemma Sorted_intro (a:A)(b:A)(l: list A)(Htrans: transitive lr):\n    a <=r b -> Sorted (b::l)-> Sorted (a::b::l).\n  Proof. intros H1 H2. apply cons_Sorted .  \n- apply H2. \n- intros x H3 . inversion H2 . subst .  inversion H3 . rewrite <- H . apply H1. \nassert (H_e : b <=r x ) . apply H5 . apply H .\napply (Htrans b ) .\n+ apply H1 .\n+ apply H_e . Qed .\n  Lemma Sorted_elim1 (a:A) (b:A) (l: list A): (Sorted (a::b::l)) -> (a <=r b).\n  Proof. intros H . inversion H . subst . apply H3 . simpl . left . reflexivity . Qed .\n  Lemma Sorted_elim4 (a:A) (l:list A): Sorted (a::l) ->(forall x, In x l -> a <=r x).\n  Proof. intros . inversion H . subst . apply H4 . apply H0 . Qed .\n  Lemma Sorted_elim2 (a:A) (l:list A)(Hrefl: reflexive lr):\n    Sorted (a::l) ->(forall x, In x (a::l) -> a <=r x).\n  Proof. intros H x H1. inversion H . subst . destruct H1 . rewrite <- H0 . apply ( Hrefl ) .\napply H4 . apply H0 . Qed .\n  Lemma Sorted_elim3 (a:A) (l:list A): (Sorted (a::l)) -> Sorted l.\n  Proof. intros H . inversion H . subst . apply H2 . Qed .\n  Lemma Sorted_single (a:A) : (Sorted (a::nil)).\n  Proof. apply cons_Sorted .\n- apply nil_Sorted .\n- intros  . destruct H . Qed .\n  Hint Resolve Sorted_elim1 Sorted_elim2 Sorted_elim3 Sorted_elim4\n       Sorted_single Sorted_intro: core.\n\n     \n  Fixpoint putin (a: A) (l: list A) : list A:=\n    match l with\n    |nil=> a::nil\n    |b::l1 => match a <=r b with\n             |true => a::l\n             |false => b::(putin a l1)\n                    end\n    end.\n\n  Lemma putin_intro (a:A) (l: list A): forall x, In x l -> In x (putin a l).\n  Proof. intros x H . induction l  as [| b] .\n- destruct H .\n- simpl . case_eq ( a<=r b) .\n+ intros . simpl . simpl in H . auto .\n+ intros . simpl . simpl in H . destruct H .\n++ auto .\n++ right . apply IHl . apply H . Qed .        \n  Lemma putin_intro1 (a:A) (l: list A): In a (putin a l).\n  Proof. induction l . simpl . left .  reflexivity .\nsimpl . case_eq ( a <=r a0 ) .\n+ intros . simpl  . left . reflexivity .\n+ intros . simpl . right . apply IHl . Qed .\n  Lemma putin_elim (a:A) (l: list A): forall x, In x (putin a l) -> (x=a)\\/(In x l).\n  Proof.  intros  x H. induction l .\nsimpl in H. simpl . intuition . simpl in H. simpl . destruct lr in H .\n+ simpl in H . intuition .\n+ simpl in H . destruct  H .\n++ auto .\n++ destruct IHl . apply H . auto . auto . Qed . \n  Definition comparable (lr: A->A-> bool) := forall x y, lr x y=false -> lr y x.\n \n  Lemma putin_correct (H_trans: transitive lr)(H_comp: comparable lr):\n    forall (a:A) (l: list A), Sorted l -> Sorted (putin a l).\n  Proof. intros a l H. induction l . simpl . auto . simpl . inversion H . subst .\ncase_eq ( a <=r a0 ) .\n+ intros . apply cons_Sorted . apply H . intros . destruct H1 . rewrite <- H1 . apply H0 .\napply ( H_trans a0 ) . apply H0 . apply H3 . apply H1 .\n+ intros H4 . apply cons_Sorted . apply IHl . apply H2 . intros . apply putin_elim in H0 .\napply H_comp in H4 . destruct H0 . rewrite H0 . apply H4 . apply H3 . apply H0 . \n Qed .\n  \n  Lemma nodup_putin (a:A)(l:list A): NoDup (a::l)-> NoDup (putin a l).\n  Proof.  { revert a. induction l.\n          { simpl. auto. }\n          { intros a0 H. assert (Ha: NoDup (a::l)).  eauto. \n            simpl. destruct (a0 <=r a) eqn: H1. auto.\n            constructor.\n            { intro H2. assert ( H2a: a=a0 \\/ In a l). eauto using putin_elim.\n              destruct H2a. subst a. inversion H. eauto.  inversion Ha; contradiction. }\n            apply IHl. inversion H. constructor; eauto.  } } Qed.\n\n  Lemma putin_card (a:A)(l: list A): | putin a l | = S (|l|).\n  Proof. { induction l.\n         { simpl;auto. }\n         { simpl. case (a <=r a0) eqn:H.\n           simpl; auto. simpl; rewrite IHl; auto. } } Qed.\n  \n  \n  Hint Resolve putin_intro putin_intro1 putin_elim putin_correct nodup_putin: core.\n\n\n   Fixpoint sort (l: list A): list A:=\n    match l with\n    |nil => nil\n    |a::l1 => putin a (sort l1)\n    end.\n  \n  \n  Lemma sort_intro (l: list A): forall x, In x l -> In x (sort l).\n  Proof.  intros . induction l . destruct H . simpl in H .\ndestruct H . simpl . rewrite <- H . apply putin_intro1 . simpl . apply putin_intro . apply IHl . apply H .\nQed .\n\n  Lemma sort_elim (l: list A): forall x, In x (sort l) -> In x l.\n  Proof. intros  . induction l . simpl in H . simpl . apply H .\n simpl . simpl in H . apply putin_elim in H . destruct H . auto . right . auto . Qed .\n  Lemma sort_correct (H_trans: transitive lr)(H_comp: comparable lr):\n    forall(l: list A), Sorted (sort l).\n  Proof. intros . induction l . simpl . apply nil_Sorted .\n simpl . apply putin_correct . auto . auto . auto . Qed .\n  Hint Resolve sort_elim sort_intro sort_correct: core.\n  \n  \n\n  (*--upto this point only reflexive, transitive and comparable property of <=r is needed--- *)\n\n \n  (* ---------------------head in Sorted lists l and l'-------------------------- *)\n\n   Definition empty: list A:= nil.\n  \n  Lemma empty_equal_nil_l (l: list A): l [=] empty -> l = empty.\n  Proof. { case l. auto. intros s l0. unfold \"[=]\". intro H. \n           destruct H as [H1 H2]. absurd (In s empty). all: eauto. } Qed.\n\n\n  \n   (*-------- antisymmetric requirement is only needed in the following lemma--------*)\n  Lemma head_equal_l (a b: A)(l s: list A)(Href: reflexive lr)(Hanti: antisymmetric lr):\n    Sorted (a::l)-> Sorted (b::s)-> Equal (a::l) (b::s)-> a=b.\n  Proof. { intros H H1 H2. \n         assert(H3: In b (a::l)).\n         unfold \"[=]\" in H2. apply H2. auto.\n         assert (H3A: a <=r b). eapply Sorted_elim2;eauto.\n         assert(H4: In a (b::s)).\n         unfold \"[=]\" in H2. apply H2. auto.\n         assert (H4A: b <=r a). eapply Sorted_elim2;eauto.\n         eapply Hanti. split_;auto. } Qed.  \n\nEnd Sorting. \n\n\n\n(*\n Definition l := 12::42::12::11::20::0::3::30::20::0::nil.\n Eval compute in (sort (fun x y => Nat.ltb y x) l).\n Eval compute in (sort (fun x y => ~~ (Nat.ltb x y)) l).\n*)\n \n\n", "meta": {"author": "muriel-kunal", "repo": "RC_assignment", "sha": "f273cea4fe68089edea7e02489454946d9972b48", "save_path": "github-repos/coq/muriel-kunal-RC_assignment", "path": "github-repos/coq/muriel-kunal-RC_assignment/RC_assignment-f273cea4fe68089edea7e02489454946d9972b48/KunalRC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7084890173856168}}
{"text": "\nSection star_rel.\n\nUnset Implicit Arguments.\n\nVariable X : Set.\nVariable R : X -> X -> Prop.\n\nInductive star : X -> X -> Prop :=\n  |star_refl : forall x, star x x\n  |star_R    : forall x y z, star x y -> R y z -> star x z.\n\nLemma R_to_star : forall x y, R x y -> star x y.\nProof.\n  intros.\n  apply (star_R _ x _).\n  apply star_refl.\n  exact H.\nQed.\n\nLemma star_trans : forall x y z, star x y -> star y z -> star x z.\nProof.\n  intros.\n  induction H0.\n  exact H.\n  apply (star_R _ y _).\n  apply IHstar.\n  exact H.\n  exact H1.\nQed.\n\nEnd star_rel.\n\nSet Implicit Arguments.\n\nSection commuting_rels.\n\nVariable X : Set.\n\nDefinition commute (R S : X -> X -> Prop) :=\n  forall x y z, R x y -> S x z -> exists w, S y w /\\ R z w.\n\nDefinition diamond(R : X -> X -> Prop) :=\n commute R R.\n\nDefinition confluent(R : X -> X -> Prop) :=\n  diamond (star X R).\n\nDefinition subrel(R S : X -> X -> Prop) := forall x y, R x y -> S x y.\n\nEnd commuting_rels.\n\nSection diamond_confluence.\n\nVariable X : Set.\nVariables R S : X -> X -> Prop.\n\nVariable subRS : subrel R S.\nVariable subSRst : subrel S (star X R).\nVariable dS : diamond S.\n\nLemma diamond_strip : commute S (star X R).\nProof.\n  intros x y z Hxy Hxz.\n  induction Hxz.\n  exists y.\n  split.\n  apply star_refl.\n  exact Hxy.\n  destruct (IHHxz Hxy) as [w [Hw1 Hw2]].\n  destruct (dS Hw2 (subRS H)) as [u [Hu1 Hu2]].\n  exists u.\n  split.\n  apply (star_trans X _ _ w _).\n  exact Hw1.\n  apply subSRst.\n  exact Hu1.\n  exact Hu2.\nQed.\n\nLemma diamond_confluence : confluent R.\nProof.\n  intros x y z Hxy Hxz.\n  induction Hxy.\n  exists z.\n  split.\n  exact Hxz.\n  apply star_refl.\n  destruct (IHHxy Hxz) as [w [Hw1 Hw2]].\n  destruct (diamond_strip (subRS H) Hw1) as [u [Hu1 Hu2]].\n  exists u.\n  split.\n  exact Hu1.\n  apply (star_trans X _ _ w _).\n  exact Hw2.\n  apply subSRst.\n  exact Hu2.\nQed.\n\nEnd diamond_confluence.\n\n", "meta": {"author": "emarzion", "repo": "combinator-confluence", "sha": "4d1a81197fa0d781569f2fe33be4a183f2e6bac9", "save_path": "github-repos/coq/emarzion-combinator-confluence", "path": "github-repos/coq/emarzion-combinator-confluence/combinator-confluence-4d1a81197fa0d781569f2fe33be4a183f2e6bac9/Rels.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7084890172486435}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Test for matrix.\n  author    : ZhengPu Shi\n  date      : 2021.12\n *)\n\nFrom FCS Require Export MatrixAll.\n\n\nModule Test_Mat_R_MLL.\n  Import MatrixAllR.MLL.\n  Open Scope R.\n\n  Check T.\n  Check 3 : T.\n  \n  Parameter m1 : mat 3 4.\n  Parameter m2 : mat 3 4.\n  Check m1 == m2.\n  \n  (* build concrete matrix *)\n  Definition ex_m_1_1 : mat 1 1 := mat_1_1 2.\n  Definition ex_m_3_3 : mat 3 3 := mat_3_3 1 2 3 4 5 6 7 8 9.\n  Compute ex_m_1_1.\n  Compute ex_m_3_3.\n  \n  (* zero matrix, identity matrix *)\n  Compute mat0 3 4.\n  Compute mat1 3.\n  \n  (* matrix mapping *)\n  Compute mmap (fun x => x * 2) (ex_m_3_3).\n  Compute mmap2 (Rminus) ex_m_3_3 ex_m_3_3.\n  \n  (* matrix addition *)\n  Check madd m1 m2.\n  Compute madd ex_m_3_3 ex_m_3_3.\n  Example ex_madd : forall r c (m1 m2 : mat r c), madd m1 m2 == madd m2 m1.\n  intros. apply madd_comm. Qed.\n  \n  (* matrix subtraction *)\n  Compute msub ex_m_3_3 (mat1 3).\n  \n  (* matrix scalar multiplication *)\n  Compute mcmul 3 ex_m_3_3.\n  Compute mmulc ex_m_3_3 3.\n  \n  (* matrix transpose *)\n  Compute mtrans ex_m_3_3.\n  \n  (* matrix multiplication *)\n  Compute mmul ex_m_3_3 (mtrans ex_m_3_3).\n  Compute mmul ex_m_3_3 ex_m_3_3.\n\n  (* Example for coordinate transform *)\n  \n  (*   Import List.\n  Import ListNotations. *)\n  \n  Section coordinate_transform_test.\n    Variable θ ψ φ : R.\n    Definition Rx (α : R) : mat 3 3 :=\n      mat_3_3\n        1         0           0\n        0         (cos α)     (sin α)\n        0         (-sin α)    (cos α).\n\n    Definition Ry (β : R) : mat 3 3 :=\n      mat_3_3\n        (cos β)   0           (-sin β)\n        0         1           0\n        (sin β)   0           (cos β).\n\n    Definition Rz (γ : R) : mat 3 3 :=\n      mat_3_3 \n        (cos γ)   (sin γ)   0\n        (-sin γ)  (cos γ)   0\n        0         0         1.\n    \n    Definition R_b_e_direct : mat 3 3 :=\n      mat_3_3\n        (cos θ * cos ψ) \n        (cos ψ * sin θ * sin φ - sin ψ * cos φ)\n        (cos ψ * sin θ * cos φ + sin φ * sin ψ)\n        \n        (cos θ * sin ψ) \n        (sin ψ * sin θ * sin φ + cos ψ * cos φ)\n        (sin ψ * sin θ * cos φ - cos ψ * sin φ)\n        \n        (-sin θ)\n        (sin φ * cos θ)\n        (cos φ * cos θ).\n    \n    Open Scope M.\n    Opaque cos sin.\n    \n    Lemma Rx_Ry_Rz_eq_Rbe : (Rz ψ)⊤ × (Ry θ)⊤ × (Rx φ)⊤ == R_b_e_direct.\n    Proof.\n      lma.\n    Qed.\n    \n  End coordinate_transform_test.\n  \nEnd Test_Mat_R_MLL.\n", "meta": {"author": "zhengpushi", "repo": "CoqMatrix", "sha": "28fa5f96e38a07659cfd373e09b0e75c24c22bfd", "save_path": "github-repos/coq/zhengpushi-CoqMatrix", "path": "github-repos/coq/zhengpushi-CoqMatrix/CoqMatrix-28fa5f96e38a07659cfd373e09b0e75c24c22bfd/CoqMatrix/MatrixTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7084890084431795}}
{"text": "(** * Logic: Logic in Coq *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Tactics.\nCheck 3 = 3.\n(* ===> Prop *)\nCheck forall n m : nat, n + m = m + n.\n(* ===> Prop *)\nCheck 2 = 2.\n(* ===> Prop *)\nCheck forall n : nat, n = 2.\n(* ===> Prop *)\nCheck 3 = 4.\n(* ===> Prop *)\n\nTheorem plus_2_2_is_4 :\n  2 + 2 = 4.\nProof. reflexivity.  Qed.\n\nDefinition plus_fact : Prop := 2 + 2 = 4.\nCheck plus_fact.\n(* ===> plus_fact : Prop *)\n\nTheorem plus_fact_is_true :\n  plus_fact.\nProof. reflexivity.  Qed.\n\nDefinition is_three (n : nat) : Prop :=\n  n = 3.\nCheck is_three.\n(* ===> nat -> Prop *)\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  intros n m H. injection H as H1. apply H1.\nQed.\n\nCheck @eq.\n(* ===> forall A : Type, A -> A -> Prop *)\n\n(* ################################################################# *)\n(** * Logical Connectives *)\n\n(** ** Conjunction *)\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  split;reflexivity.\nQed.\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof.\n  intros A B HA HB. split.\n  - apply HA.\n  - apply HB.\nQed.\nExample and_example' : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof.\n  apply and_intro;reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, standard (and_exercise)  *)\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m.\n  split.\n  -destruct n.\n    +reflexivity.\n    +discriminate H.\n  -destruct m.\n    +reflexivity.\n    +destruct n.\n      *simpl in H. discriminate H.\n      *discriminate H.\nQed.\n(** [] *)\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m H.\n  destruct H as [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2' :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [Hn Hm].\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example2'' :\n  forall n m : nat, n = 0 -> m = 0 -> n + m = 0.\nProof.\n  intros n m Hn Hm.\n  rewrite Hn. rewrite Hm.\n  reflexivity.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m H.\n  assert (H' : n = 0 /\\ m = 0).\n  { apply and_exercise. apply H. }\n  destruct H' as [Hn Hm].\n  rewrite Hn. reflexivity.\nQed.\n\nLemma proj1 : forall P Q : Prop,\n  P /\\ Q -> P.\nProof.\n  intros P Q [HP HQ].\n  apply HP.  Qed.\n\n(** **** Exercise: 1 star, standard, optional (proj2)  *)\nLemma proj2 : forall P Q : Prop,\n  P /\\ Q -> Q.\nProof.\n  intros P Q.\n  intros [HP HQ].\n  apply HQ.\nQed.\n(** [] *)\n\nTheorem and_commut : forall P Q : Prop,\n  P /\\ Q -> Q /\\ P.\nProof.\n  intros P Q [HP HQ].\n  split.\n    - apply HQ.\n    - apply HP.  Qed.\n\n(** **** Exercise: 2 stars, standard (and_assoc) *)\n\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.\n  -split.\n    +apply HP.\n    +apply HQ.\n  -apply HR.\nQed.\n(** [] *)\nCheck and.\n(* ===> and : Prop -> Prop -> Prop *)\n\n(* ================================================================= *)\n(** ** Disjunction *)\n\nLemma or_example :\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\nLemma or_intro : forall A B : Prop, A -> A \\/ B.\nProof.\n  intros A B HA.\n  left.\n  apply HA.\nQed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  (* WORKED IN CLASS *)\n  intros [|n].\n  - left. reflexivity.\n  - right. reflexivity.\nQed.\n\n(** **** Exercise: 1 star, standard (mult_eq_0)  *)\nLemma mult_eq_0 :\n  forall n m, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m.\n  destruct n.\n  -left. reflexivity.\n  - destruct m.\n    +right. reflexivity.\n    +intros H. simpl in H. discriminate H.\nQed.\n(** [] *)\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 [HP | HQ].\n  -right. apply HP.\n  -left. apply HQ.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Falsehood and Negation **)\n\nModule MyNot.\nDefinition not (P:Prop) := P -> False.\nNotation \"~ x\" := (not x) : type_scope.\n\nCheck not.\n(* ===> Prop -> Prop *)\n\nEnd MyNot.\n\n(** Since [False] is a contradictory proposition, the principle of\n    explosion also applies to it. If we get [False] into the proof\n    context, we can use [destruct] on it to complete any goal: *)\n\nTheorem ex_falso_quodlibet : forall (P:Prop),\n  False -> P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P contra.\n  destruct contra.  Qed.\n\n(** The Latin _ex falso quodlibet_ means, literally, \"from falsehood\n    follows whatever you like\"; this is another common name for the\n    principle of explosion. *)\n\n(** **** Exercise: 2 stars, standard, optional (not_implies_our_not)  \n\n    Show that Coq's definition of negation implies the intuitive one\n    mentioned above: *)\n\nFact not_implies_our_not : forall (P:Prop),\n  ~ P -> (forall (Q:Prop), P -> Q).\nProof.\n  intros P H Q.\n  unfold not in H.\n  intros H1.\n  apply H in H1.\n  destruct H1.\nQed.\n(** [] *)\n\nTheorem zero_not_one : 0 <> 1.\nProof.\n  unfold not.\n  intros contra.\n  discriminate contra.\nQed.\n\nTheorem not_False :\n  ~ False.\nProof.\n  unfold not. intros H. destruct H. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n  (P /\\ ~P) -> Q.\nProof.\n  (* WORKED IN CLASS *)\n  intros P Q [HP HNA]. unfold not in HNA.\n  apply HNA in HP. destruct HP.  Qed.\n\nTheorem double_neg : forall P : Prop,\n  P -> ~~P.\nProof.\n  (* WORKED IN CLASS *)\n  intros P H. unfold not. intros G. apply G. apply H.  Qed.\n\n(** **** Exercise: 2 stars, advanced (double_neg_inf)  \n\n    Write an informal proof of [double_neg]:\n\n   _Theorem_: [P] implies [~~P], for any proposition [P]. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_double_neg_inf : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (contrapositive)  *)\nTheorem contrapositive : forall (P Q : Prop),\n  (P -> Q) -> (~Q -> ~P).\nProof.\n  intros P Q.\n  intros H.\n  unfold not.\n  intros H1 H2.\n  apply H in H2. apply H1 in H2.\n  apply H2.\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  intros P.\n  unfold not.\n  intros [HP nHP].\n  apply nHP in HP.\n  apply HP.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (informal_not_PNP)  \n\n    Write an informal proof (in English) of the proposition [forall P\n    : Prop, ~(P /\\ ~P)]. *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_not_PNP : option (nat*string) := None.\n(** [] *)\n\nTheorem not_true_is_false : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    apply ex_falso_quodlibet.\n    apply H. reflexivity.\n  - (* b = false *)\n    reflexivity.\nQed.\n\nTheorem not_true_is_false' : forall b : bool,\n  b <> true -> b = false.\nProof.\n  intros [] H.\n  - (* b = true *)\n    unfold not in H.\n    exfalso.                (* <=== *)\n    apply H. reflexivity.\n  - (* b = false *) reflexivity.\nQed.\n\n(* ================================================================= *)\n(** ** Truth *)\n\n(** Besides [False], Coq's standard library also defines [True], a\n    proposition that is trivially true. To prove it, we use the\n    predefined constant [I : True]: *)\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\n(* ================================================================= *)\n(** ** Logical Equivalence *)\n\n(** The handy \"if and only if\" connective, which asserts that two\n    propositions have the same truth value, is just the conjunction of\n    two implications. *)\n\nModule MyIff.\n\nDefinition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\nNotation \"P <-> Q\" := (iff P Q)\n                      (at level 95, no associativity)\n                      : type_scope.\n\nEnd MyIff.\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.  Qed.\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\n(** **** Exercise: 1 star, standard, optional (iff_properties)  \n\n    Using the above proof that [<->] is symmetric ([iff_sym]) as\n    a guide, prove that it is also reflexive and transitive. *)\n\nTheorem iff_refl : forall P : Prop,\n  P <-> P.\nProof.\n  intros P. split.\n  -intros H. apply H.\n  -intros H. apply H.\nQed.\nTheorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R.\n  intros [HP HQ1].\n  intros [HQ2 HR].\n  split.\n  -intros H. apply HP in H. apply HQ2 in H. apply H.\n  -intros H. apply HR in H. apply HQ1 in H. apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (or_distributes_over_and)  *)\nTheorem or_distributes_over_and : forall P Q R : Prop,\n  P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n  -intros [HP | [HQ HR]].\n   +split.\n     *left. apply HP.\n     *left. apply HP.\n   +split.\n     *right. apply HQ.\n     *right. apply HR.\n  -intros [[HP1 | HQ] [HP2 | HR]].\n   +left. apply HP1.\n   +left. apply HP1.\n   +left. apply HP2.\n   +right. split.\n    *apply HQ.\n    *apply HR.\nQed.\n(** [] *)\n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma mult_0 : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  split.\n  - apply mult_eq_0.\n  - apply or_example.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. 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 mult_0_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p.\n  rewrite mult_0. rewrite mult_0. rewrite or_assoc.\n  reflexivity.\nQed.\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof.\n  intros n m H. apply mult_0. apply H.\nQed.\n\n(* ================================================================= *)\n(** ** Existential Quantification *)\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof.\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, recommended (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.\n  unfold not.\n  intros [x H0].\n  apply H0.\n  apply H.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (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  intros X P Q.\n  split.\n  -intros H. destruct H as [x [HP | HQ]].\n   +left. exists x. apply HP.\n   +right. exists x. apply HQ.\n  -intros H. destruct H as [HP | HQ].\n   +destruct HP as [x PX].\n    exists x. left. apply PX.\n   +destruct HQ as [x QX].\n    exists x. right. apply QX.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Programming with Propositions *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x' = x \\/ In x l'\n  end.\n\n(** When [In] is applied to a concrete list, it expands into a\n    concrete sequence of nested disjunctions. *)\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof.\n  (* WORKED IN CLASS *)\n  simpl. right. right. right. left. reflexivity.\nQed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] ->\n  exists n', n = 2 * n'.\nProof.\n  (* WORKED IN CLASS *)\n  simpl.\n  intros n [H | [H | []]].\n  - exists 1. rewrite <- H. reflexivity.\n  - exists 2. rewrite <- H. reflexivity.\nQed.\n(** (Notice the use of the empty pattern to discharge the last case\n    _en passant_.) *)\n\n(** We can also prove more generic, higher-level lemmas about [In].\n\n    Note, in the next, how [In] starts out applied to a variable and\n    only gets expanded when we do case analysis on this variable: *)\n\nLemma 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.\n  induction l as [|x' l' IHl'].\n  - (* l = nil, contradiction *)\n    simpl. intros [].\n  - (* l = x' :: l' *)\n    simpl. intros [H | H].\n    + rewrite H. left. reflexivity.\n    + right. apply IHl'. apply H.\nQed.\n\n(** This way of defining propositions recursively, though convenient\n    in some cases, also has some drawbacks.  In particular, it is\n    subject to Coq's usual restrictions regarding the definition of\n    recursive functions, e.g., the requirement that they be \"obviously\n    terminating.\"  In the next chapter, we will see how to define\n    propositions _inductively_, a different technique with its own set\n    of strengths and limitations. *)\n\n(** **** Exercise: 2 stars, standard (In_map_iff)  *)\nLemma 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.\n  split.\n  -induction l.\n   +simpl. intros contra. destruct contra.\n   +simpl. intros [H1 | H2].\n    * exists x. split.\n     {apply H1. }\n     {left. reflexivity. }\n    * apply IHl in H2. destruct H2 as [z [H3 H4]].\n      exists z. split.\n      {apply H3. }\n      {right. apply H4. }\n  -intros [x [H1 H2]].\n   rewrite <- H1. apply In_map. apply H2.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (In_app_iff)  *)\nLemma In_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a.\n  split.\n  -intros H. induction l.\n    +simpl. simpl in H. right. apply H.\n    +simpl. simpl in H. destruct H as [H1 | H2].\n     *left. unfold In. left. apply H1.\n     *apply IHl in H2. destruct H2 as [H3 | H4].\n      {left. right. apply H3. }\n      {right. apply H4. }\n  -intros H. induction l.\n    + simpl in H. destruct H.\n      *destruct H.\n      *simpl. apply H.\n    + simpl in H. apply or_assoc in H. simpl. destruct H as [H1 | H2].\n      *left. apply H1.\n      *apply IHl in H2. right. apply H2.\nQed.\n    \n(** [] *)\n\n(** **** Exercise: 3 stars, standard, recommended (All)  *)\n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n  |[] => True\n  |h::t => (P h)/\\(All P t)\n  end.\n\nLemma 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 T P l .\n  split.\n  -intros H.\n    induction l.\n    +simpl. reflexivity.\n    +simpl. simpl in H. split.\n      *apply H. left. reflexivity.\n      *apply IHl. intros y. intros H1. apply H. right. apply H1.\n  -intros H.\n    induction l.\n     +intros y. intros H1. simpl in H1. destruct H1.\n     +simpl. intros x0 H'.\n      destruct H'.\n      *simpl in H. destruct H as [H1 H2]. rewrite <- H0. apply H1.\n      *simpl in H. destruct H as [H1 H2]. apply IHl. apply H2. apply H0.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (combine_odd_even) *)\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop:=\n  fun (n:nat) => if oddb n then Podd n else Peven n.  \n\n(** To test your definition, prove the following 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.\n  destruct (oddb n) eqn:H0.\n  -unfold combine_odd_even. rewrite H0. intros H1 H2.\n   apply H1. reflexivity.\n  -unfold combine_odd_even. rewrite H0. intros H1 H2.\n   apply H2. 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 Podd Peven n H1 H2.\n  unfold combine_odd_even in H1.\n  rewrite H2 in H1.\n  apply H1.\nQed.\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.\n  apply H1.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Applying Theorems to Arguments *)\n\nCheck plus_comm.\n(* ===> forall n m : nat, n + m = m + n *)\n\nLemma plus_comm3_take2 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  assert (H : y + z = z + y).\n  { rewrite plus_comm. reflexivity. }\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma plus_comm3_take3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite (plus_comm y z).\n  reflexivity.\nQed.\n\nLemma in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros A x l H. unfold not. intro Hl. destruct l.\n  - simpl in H. destruct H.\n  - discriminate Hl.\nQed.\n\nLemma in_not_nil_42_take2 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil with (x := 42).\n  apply H.\nQed.\n\n(* [apply ... in ...] *)\nLemma in_not_nil_42_take3 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply in_not_nil in H.\n  apply H.\nQed.\n\n(* Explicitly apply the lemma to the value for [x]. *)\nLemma in_not_nil_42_take4 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil nat 42).\n  apply H.\nQed.\n\n(* Explicitly apply the lemma to a hypothesis. *)\nLemma in_not_nil_42_take5 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  intros l H.\n  apply (in_not_nil _ _ _ H).\nQed.\n\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) ->\n    n = 0.\nProof.\n  intros n ns H.\n  destruct (proj1 _ _ (In_map_iff _ _ _ _ _) H)\n           as [m [Hm _]].\n  rewrite mult_0_r in Hm. rewrite <- Hm. reflexivity.\nQed.\n\n(** We will see many more examples in later chapters. *)\n\n(* ################################################################# *)\n(** * Coq vs. Set Theory *)\n(* ================================================================= *)\n(** ** Functional Extensionality *)\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. reflexivity. Qed.\n\nAxiom functional_extensionality : forall {X Y: Type}\n                                    {f g : X -> Y},\n  (forall (x:X), f x = g x) -> f = g.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun x => plus 1 x).\nProof.\n  apply functional_extensionality. intros x.\n  apply plus_comm.\nQed.\n\nPrint Assumptions function_equality_ex2.\n(* ===>\n     Axioms:\n     functional_extensionality :\n         forall (X Y : Type) (f g : X -> Y),\n                (forall x : X, f x = g x) -> f = g *)\n\n(** **** Exercise: 4 stars, standard (tr_rev_correct) *)\n\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\nLemma tr_rev_lemma : forall X  (l1 l2 : list X), \n  rev_append l1 l2 = (rev l1)++l2.\nProof.\n  intros X l1.\n  induction l1.\n  -intros l2. simpl. reflexivity.\n  -intros l2. simpl. rewrite <- app_assoc. simpl. apply IHl1.\nQed.\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\nProof.\n  intros X.\n  apply functional_extensionality.\n  unfold tr_rev.\n  intros x.\n  rewrite tr_rev_lemma.\n  apply app_nil_r.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Propositions and Booleans *)\n\n(** ... that [evenb n] evaluates to [true]... *)\nExample even_42_bool : evenb 42 = true.\nProof. reflexivity. Qed.\n\n(** ... or that there exists some [k] such that [n = double k]. *)\nExample even_42_prop : exists k, 42 = double k.\nProof. exists 21. reflexivity. Qed.\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.\n  induction n.\n  - simpl. exists 0. reflexivity.\n  - destruct (evenb n) eqn: H.\n    + rewrite evenb_S. rewrite H. simpl. destruct IHn as [k E]. exists k. rewrite E.\n      reflexivity.\n    + rewrite evenb_S. rewrite H. simpl. destruct IHn as [k E]. exists (S k). rewrite E.\n      reflexivity.\nQed.\n  (* Hint: Use the [evenb_S] lemma from [Induction.v]. *)\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\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\nFail Definition is_even_prime n :=\n  if n = 2 then true\n  else false.\n  \nExample even_1000 : exists k, 1000 = double k.\nProof. exists 500. reflexivity. Qed.\n\nExample even_1000' : evenb 1000 = true.\nProof. reflexivity. Qed.\n\nExample even_1000'' : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\nExample not_even_1001 : evenb 1001 = false.\nProof.\n  (* WORKED IN CLASS *)\n  reflexivity.\nQed.\n\n(** In contrast, propositional negation may be more difficult\n    to grasp. *)\n\nExample not_even_1001' : ~(exists k, 1001 = double k).\nProof.\n  (* WORKED IN CLASS *)\n  rewrite <- even_bool_prop.\n  unfold not.\n  simpl.\n  intro H.\n  discriminate H.\nQed.\n\nLemma plus_eqb_example : forall n m p : nat,\n    n =? m = true -> n + p =? m + p = true.\nProof.\n  (* WORKED IN CLASS *)\n  intros n m p H.\n    rewrite eqb_eq in H.\n  rewrite H.\n  rewrite eqb_eq.\n  reflexivity.\nQed.\n\nLemma andb_true_iff : forall b1 b2:bool,\n  b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2. split.\n  -intros H. unfold andb in H. split.\n    +destruct b1.\n      *reflexivity.\n      *destruct H. reflexivity.\n    +destruct b2.\n      *reflexivity.\n      *destruct H. destruct b1.\n        {reflexivity. }\n        {reflexivity. }\n  -intros [HA HB].\n    unfold andb. rewrite HA.\n    rewrite HB. reflexivity.\nQed.\nLemma orb_true_iff : forall b1 b2,\n  b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2. split.\n  -intros H. destruct b1.\n   + left. reflexivity.\n   + simpl in H. right. apply H.\n  -intros [HA | HB].\n    +rewrite HA. reflexivity.\n    +rewrite HB. destruct b1.\n      *reflexivity.\n      *reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 1 star, standard (eqb_neq) *)\n\nTheorem eqb_neq : forall x y : nat,\n  x =? y = false <-> x <> y.\nProof.\n  intros x y. split.\n  - intros H. unfold not. destruct (x=?y) eqn: H1.\n    + discriminate H.\n    + intros H2. rewrite H2 in H1. rewrite<- eqb_refl in H1. discriminate H1.\n  - intros H. unfold not in H. destruct (x=?y) eqn: H1.\n    +apply eqb_eq in H1. apply H in H1. destruct H1.\n    +reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (eqb_list) *)\n\nFixpoint eqb_list {A : Type} (eqb : A -> A -> bool)\n                  (l1 l2 : list A) : bool :=\n  match l1, l2 with \n  |[],[] =>true\n  |[], h::t => false\n  |h::t, [] => false\n  |h1::t1, h2::t2 => match (eqb h1 h2) with\n        |true => eqb_list eqb t1 t2\n        |false => false\n  end\nend.\n\nLemma 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.\n  intros H.\n  split.\n  -revert l2. induction l1.\n    +intros l2. destruct l2 eqn: H1. \n      *reflexivity.\n      *intros H2. discriminate H2.\n    +simpl. intros l2. destruct l2 eqn: H3.\n      *intros H4. discriminate H4.\n      *destruct (eqb x x0) eqn:H6.\n       {intros H5. apply H in H6. apply IHl1 in H5. rewrite H6. rewrite H5. reflexivity. } \n       {intros H5. discriminate H5. }\n  Abort.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (All_forallb)  \n\n    Recall the function [forallb], from the exercise\n    [forall_exists_challenge] in chapter [Tactics]: *)\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(** Prove the theorem below, which relates [forallb] to the [All]\n    property of the above exercise. *)\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 X test l.\n  split.\n  -intros H. induction l.\n    + reflexivity.\n    + simpl. simpl in H. apply andb_true_iff in H. destruct H as [H1 H2].\n      apply IHl in H2. \n      split.\n      *apply H1.\n      *apply H2.\n  -intros H. induction l.\n    + reflexivity.\n    + simpl. simpl in H. destruct H as [H1 H2]. apply IHl in H2.\n      apply andb_true_iff.\n      split.\n      *apply H1.\n      *apply H2.\nQed.\n\n(** Are there any important properties of the function [forallb] which\n    are not captured by this specification? *)\n\n(* FILL IN HERE \n\n    [] *)\n\n(* ================================================================= *)\n(** ** Classical vs. Constructive Logic *)\nDefinition excluded_middle := forall P : Prop,\n  P \\/ ~ P.\n\nTheorem restricted_excluded_middle : forall P b,\n  (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros contra. discriminate contra.\nQed.\n\nTheorem restricted_excluded_middle_eq : forall (n m : nat),\n  n = m \\/ n <> m.\nProof.\n  intros n m.\n  apply (restricted_excluded_middle (n = m) (n =? m)).\n  symmetry.\n  apply eqb_eq.\nQed.\n\n(** **** Exercise: 3 stars, standard (excluded_middle_irrefutable) *)\n\nTheorem excluded_middle_irrefutable: forall (P:Prop),\n  ~ ~ (P \\/ ~ P).\nProof.\n  intros P.\n  unfold not.\n  intros H1. apply H1.\n  right. intros H2. apply H1. left. apply H2.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (not_exists_dist)*)\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  intros e_m X P H x.\n  unfold not in H.\n  assert(H1: P x\\/~P x). {apply e_m. }\n  destruct H1 as [H3 | H4].\n  - apply H3.\n  - unfold not in H4. apply ex_falso_quodlibet. apply H.\n    exists x. apply H4.\nQed.\n(** [] *)\n\n(** **** Exercise: 5 stars, standard, optional (classical_axioms) *)\n\nDefinition peirce := forall P Q: Prop,\n  ((P->Q)->P)->P.\n\nDefinition double_negation_elimination := forall P:Prop,\n  ~~P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q:Prop,\n  ~(~P /\\ ~Q) -> P\\/Q.\n\nDefinition implies_to_or := forall P Q:Prop,\n  (P->Q) -> (~P\\/Q).\n\n\nLemma em_pe: excluded_middle->peirce.\nProof.\n  intros em P Q.\n  assert(H1: P\\/~P). {apply em. }\n  assert(H2: Q\\/~Q). {apply em. }\n  destruct H1 as [HP | nHP].\n  -intros H'. apply HP.\n  -intros. unfold not in nHP. destruct H2 as [HQ | nHQ].\n    +assert(H': P->Q). {intros. apply HQ. }\n    apply H in H'. apply H'.\n    +assert(H': P->Q). {intros. apply nHP in H0. inversion H0. }\n    apply H in H'. apply H'.\nQed.\n   \nLemma pe_dne: peirce -> double_negation_elimination.\nProof.\n  intros pe P nP.\n  unfold not in nP.\n  assert(H:((P->False)->P)->P). {apply pe. }\n  apply H.\n  intros H1.\n  apply nP in H1.\n  destruct H1.\nQed.\nLemma dne_dmnan: double_negation_elimination->de_morgan_not_and_not.\nProof. \n  intros dne P Q H.\n  assert(H1:~~(P\\/Q) ->(P\\/Q)). {apply dne. }\n  apply H1.\n  unfold not. \n  unfold not in H.\n  intros. apply H.\n  split.\n  -intros. assert(H': P\\/Q). { left. apply H2. }\n   apply H0 in H'. apply H'.\n  -intros. assert(H': P\\/Q). { right. apply H2. }\n   apply H0 in H'. apply H'.\nQed.\nLemma dmnan_ito : de_morgan_not_and_not->implies_to_or.\nProof.\n  intros dmnan P Q H.\n  unfold not.\n  assert(H1:~(~(P->False) /\\ ~Q) ->(P->False)\\/Q). {apply dmnan. }\n  apply H1.\n  unfold not.\n  intros.\n  destruct H0 as [H2 H3].\n  apply H2. intros.\n  apply H in H0.\n  apply H3 in H0.\n  apply H0.\nQed.\nLemma ito_em: implies_to_or ->excluded_middle.\nProof.\n  intros ito. \n  unfold excluded_middle.\n  intros P.\n  assert(H:(P->P)-> (~P\\/P)). {apply ito. }\n  assert(H':P->P). {intro. apply H0. }\n  apply H in H'.\n  destruct H' as [H1 | H2].\n  -right. apply H1.\n  -left. apply H2.\nQed.\n  \n(* Wed Jan 9 12:02:45 EST 2019 *)\n", "meta": {"author": "sjxer723", "repo": "Software-fundations", "sha": "8d18a6e695ac7c897d8b717a7870f91ed2794fee", "save_path": "github-repos/coq/sjxer723-Software-fundations", "path": "github-repos/coq/sjxer723-Software-fundations/Software-fundations-8d18a6e695ac7c897d8b717a7870f91ed2794fee/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7084631100123463}}
{"text": "Require Import HoTT Coq.Init.Peano.\n\nDefinition Book_1_1 := (fun (A B C : Type) (f : A -> B) (g : B -> C) => g o f).\n\nTheorem Book_1_1_refl : forall (A B C D : Type) (f : A -> B) (g : B -> C) (h : C -> D),\n                          h o (g o f) = (h o g) o f.\nProof.\n  reflexivity.\nDefined.\n\nDefinition Book_1_2_prod_lib := @HoTT.Types.Prod.equiv_uncurry.\nSection Book_1_2_prod.\n  Variable A B : Type.\n\n  (** Recursor with projection functions instead of pattern-matching. *)\n  Let prod_rec_proj C (g : A -> B -> C) (p : A * B) : C :=\n    g (fst p) (snd p).\n  Definition Book_1_2_prod := prod_rec_proj.\n\n  Proposition Book_1_2_prod_fst : fst = prod_rec_proj A (fun a b => a).\n  Proof.\n    reflexivity.\n  Defined.\n\n  Proposition Book_1_2_prod_snd : snd = prod_rec_proj B (fun a b => b).\n  Proof.\n    reflexivity.\n  Defined.\nEnd Book_1_2_prod.", "meta": {"author": "artagnon", "repo": "proofsauce", "sha": "9465e197d95c1dfb22ff8f52bd74e66b0ce2f48e", "save_path": "github-repos/coq/artagnon-proofsauce", "path": "github-repos/coq/artagnon-proofsauce/proofsauce-9465e197d95c1dfb22ff8f52bd74e66b0ce2f48e/theories/Category/Commutative.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.708445790666494}}
{"text": "Require Import Arith Arith.Even Arith.Div2.\nRequire Import Braun.common.util Omega.\nSet Implicit Arguments.\n\n(* START: bin_tree *)\nInductive bin_tree {A:Set} : Set :=\n| bt_mt   : bin_tree\n| bt_node : A -> bin_tree -> bin_tree -> bin_tree.\n(* STOP: bin_tree *)\nHint Constructors bin_tree.\n\n(* START: Braun *)\nInductive Braun {A:Set} : (@bin_tree A) -> nat -> Prop :=\n| B_mt   : Braun bt_mt 0\n| B_node : forall (x:A) s s_size t t_size,\n  t_size <= s_size <= t_size+1 ->\n  Braun s s_size -> Braun t t_size ->\n  Braun (bt_node x s t) (s_size+t_size+1).\n(* STOP: Braun *)\nHint Constructors Braun.\n\nLemma braun_node_construction:\n  forall (A:Set) (x:A) n s t,\n    Braun s (div2 (n+1)) ->\n    Braun t (div2 n) ->\n    Braun (bt_node x s t) (S n).\nProof.\n  intros.\n  replace (S n) with (div2 (n+1) + div2 n + 1).\n  constructor; auto.\n  apply (ind_0_1_SS (fun n => div2 n <= div2 (n+1) <= div2 n + 1));\n    try (intros;simpl;omega).\n  rewrite div_ceil_floor_sum. \n  replace (S n + 1) with (S (S n));[|omega].\n  replace (div2 (S (S n))) with (S (div2 n));[|simpl;reflexivity].\n  replace (n+1) with (S n);[|omega].\n  omega.\nQed.\nHint Resolve braun_node_construction.\n", "meta": {"author": "rfindler", "repo": "395-2013", "sha": "afaeb6f4076a1330bbdeb4537417906bbfab5119", "save_path": "github-repos/coq/rfindler-395-2013", "path": "github-repos/coq/rfindler-395-2013/395-2013-afaeb6f4076a1330bbdeb4537417906bbfab5119/common/braun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7084457881011874}}
{"text": "Require Import Relations.Relation_Definitions.\n\nInductive Process :=\n  | Nil : Process\n  | Input : nat -> (nat -> Process) -> Process\n  | Output : nat -> Process -> Process\n  | Sum : Process -> Process -> Process\n  | Res : nat -> Process -> Process.\n\nDefinition small_step : relation Process :=\n  fun p1 p2 =>\n    match p1 with\n    | Input x f =>\n      exists v, p2 = f v\n    | Output x p =>\n      p2 = p\n    | Sum p1' p2' =>\n      p2 = Sum p1' p2' \\/ p2 = Sum p1 p2'\n    | Res x p =>\n      exists y, p2 = Res y p /\\ x <> y\n    | _ => False\n    end.\n\nInductive multi_step : relation Process :=\n  | refl : forall p, multi_step p p\n  | step : forall p1 p2 p3, small_step p1 p2 -> multi_step p2 p3 -> multi_step p1 p3.\n\nInductive bisim : relation Process :=\n  | bisim_refl : forall p, bisim p p\n  | bisim_trans : forall p1 p2 p3, bisim p1 p2 -> small_step p2 p3 -> bisim p1 p3\n  | bisim_symm : forall p1 p2, bisim p1 p2 -> bisim p2 p1.\n\nDefinition bisimulation (R : relation Process) :=\n  forall p q, R p q -> (forall p', small_step p p' -> exists q', R p' q' /\\ small_step q q') /\\\n                (forall q', small_step q q' -> exists p', R p' q' /\\ small_step p p').\n\nDefinition bisimilarity (R : relation Process) :=\n  forall p q, R p q -> exists q', bisim q q' /\\ multi_step p q'.\n", "meta": {"author": "l3r8yJ", "repo": "phi-reducer", "sha": "5bcb75d101d672506f030d1f7c3226752891070d", "save_path": "github-repos/coq/l3r8yJ-phi-reducer", "path": "github-repos/coq/l3r8yJ-phi-reducer/phi-reducer-5bcb75d101d672506f030d1f7c3226752891070d/src/theorems/phi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.7084457793639419}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (x : natural) : natural := plus Zero (mult x z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj2810_coqofml_rSjZIe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7879312006227323, "lm_q1q2_score": 0.7084457777783363}}
{"text": "Require Import Logic.Class.Eq.\nRequire Import Logic.Lam.Syntax.\n\n\n(* If equality on v is decidable, then so is equality on T v                    *) \nLemma eqDecidable : forall (v:Type) (e:Eq v), \n    forall (s t:T v), {s = t} + {s <> t}.\nProof.\n    intros v e s t. revert s t.\n    induction s as [x|s1 IH1 s2 IH2|x s1 IH1];\n    destruct t as [y|t1 t2|y t1].\n    - destruct (eqDec x y) as [E|E].\n        + subst. left. reflexivity.\n        + right. intros H. inversion H. subst. apply E. reflexivity.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - destruct (IH1 t1) as [E1|E1], (IH2 t2) as [E2|E2].\n        + subst. left. reflexivity.\n        + right. intros H. inversion H. subst. apply E2. reflexivity.\n        + right. intros H. inversion H. subst. apply E1. reflexivity.\n        + right. intros H. inversion H. subst. apply E1. reflexivity.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - right. intros H. inversion H.\n    - destruct (eqDec x y) as [E|E], (IH1 t1) as [E1|E1].\n        + subst. left. reflexivity.\n        + right. intros H. inversion H. subst. apply E1. reflexivity.\n        + right. intros H. inversion H. subst. apply E.  reflexivity.\n        + right. intros H. inversion H. subst. apply E.  reflexivity.\nDefined.\n\nArguments eqDecidable {v} {e}.\n\nInstance EqT (v:Type) (e:Eq v) : Eq (T v) := { eqDec := eqDecidable }.\n", "meta": {"author": "possientis", "repo": "Prog", "sha": "0144f74338b9d35a2983e8956f10e615ed26b8cb", "save_path": "github-repos/coq/possientis-Prog", "path": "github-repos/coq/possientis-Prog/Prog-0144f74338b9d35a2983e8956f10e615ed26b8cb/coq/Logic/Lam/Eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7084457733008579}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** Maps (or dictionaries) are ubiquitous data structures, both in\n    software construction generally and in the theory of programming\n    languages in particular; we're going to need them in many places\n    in the coming chapters.  They also make a nice case study using\n    ideas we've seen in previous chapters, including building data\n    structures out of higher-order functions (from [Basics] and\n    [Poly]) and the use of reflection to streamline proofs (from\n    [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which return an [option] to\n    indicate success or failure.  The latter is defined in terms of\n    the former, using [None] as the default element. *)\n\n(* ###################################################################### *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we start.\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (and, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** Documentation for the standard library can be found at\n    http://coq.inria.fr/library/.  \n\n    The [SearchAbout] command is a good way to look for theorems \n    involving objects of specific types. *)\n\n(* ###################################################################### *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our\n    maps.  For this purpose, we again use the type [id] from the\n    [Lists] chapter.  To make this chapter self contained, we repeat\n    its definition here, together with the equality comparison\n    function for [id]s and its fundamental property. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id id1 id2 :=\n  match id1,id2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall id, true = beq_id id id.\nProof.\n  intros [n]. simpl. rewrite <- beq_nat_refl.\n  reflexivity. Qed.\n\n(** The following useful property of [beq_id] follows from an\n    analogous lemma about numbers: *)\n\nTheorem beq_id_true_iff : forall id1 id2 : id,\n  beq_id id1 id2 = true <-> id1 = id2.\nProof.\n   intros [n1] [n2].\n   unfold beq_id.\n   rewrite beq_nat_true_iff.\n   split.\n   - (* -> *) intros H. rewrite H. reflexivity.\n   - (* <- *) intros H. inversion H. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This useful variant follows just by rewriting: *)\n\nTheorem false_beq_id : forall x y : id,\n   x <> y\n   -> beq_id x y = false.\nProof.\n  intros x y. rewrite beq_id_false_iff.\n  intros H. apply H. Qed.\n\n(* ###################################################################### *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about their behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps.\n\n    We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A:Type) := id -> A.\n\n(** Intuitively, a total map over an element type [A] _is_ just a\n    function that can be used to look up [id]s, yielding [A]s.\n\n    The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any id. *)\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : id) (v : A) :=\n  fun x' => if beq_id x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming.\n    The [t_update] function takes a _function_ [m] and yields a new\n    function [fun x' => ...] that behaves like the desired map.\n\n    For example, we can build a map taking [id]s to [bool]s, where [Id\n    3] is mapped to [true] and every other key is mapped to [false],\n    like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) (Id 1) false)\n           (Id 3) true.\n\n(** This completes the definition of total maps.  Note that we don't\n    need to define a [find] operation because it is just function\n    application! *)\n\nExample update_example1 : examplemap (Id 0) = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap (Id 1) = false.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap (Id 2) = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap (Id 3) = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental\n    facts about how they behave.  Even if you don't work the following\n    exercises, make sure you thoroughly understand the statements of\n    the lemmas!  (Some of the proofs require the functional\n    extensionality axiom discussed in the [Logic] chapter, which is\n    also included in the standard library.) *)\n\n(** **** Exercise: 2 stars, optional (t_update_eq)  *)\n(** First, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall A (m: total_map A) x v,\n  (t_update m x v) x = v.\nProof.\n  intros. unfold t_update.\n  rewrite <- beq_id_refl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_neq)  *)\n(** On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (X:Type) v x1 x2\n                         (m : total_map X),\n  x1 <> x2 ->\n  (t_update m x1 v) x2 = m x2.\nProof.\n  intros. unfold t_update.\n  apply false_beq_id in H. rewrite H. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_shadow)  *)\n(** If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    t_update (t_update m x v1) x v2\n  = t_update m x v2.\nProof.\n  intros. unfold t_update.\n  apply functional_extensionality. intros.\n  destruct (beq_id x x0).\n  - reflexivity.\n  - reflexivity.\nQed.\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n    the reflection idioms introduced in chapter [IndProp].  We begin\n    by proving a fundamental _reflection lemma_ relating the equality\n    proposition on [id]s with the boolean function [beq_id]. *)\n\n(** **** Exercise: 2 stars (beq_idP)  *)\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma beq_idP : forall x y, reflect (x = y) (beq_id x y).\nProof.\n  intros x y.\n  apply iff_reflect. rewrite beq_id_true_iff. reflexivity.\nQed.\n(** [] *)\n\n(** Now, given [id]s [x1] and [x2], we can use the [destruct (beq_idP\n    x1 x2)] to simultaneously perform case analysis on the result of\n    [beq_id x1 x2] and generate hypotheses about the equality (in the\n    sense of [=]) of [x1] and [x2]. *)\n\n(** **** Exercise: 2 stars (t_update_same)  *)\n(** Using the example in chapter [IndProp] as a template, use\n    [beq_idP] to prove the following theorem, which states that if we\n    update a map to assign key [x] the same value as it already has in\n    [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall X x (m : total_map X),\n  t_update m x (m x) = m.\nProof.\n  intros. unfold t_update.\n  apply functional_extensionality. intros.\n  destruct (beq_idP x x0) as [H | H'].\n  - rewrite H. reflexivity.\n  - reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (t_update_permute)  *)\n(** Use [beq_idP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n    (t_update (t_update m x2 v2) x1 v1)\n  = (t_update (t_update m x1 v1) x2 v2).\nProof.\n  intros. unfold t_update.\n  apply functional_extensionality. intros.\n  destruct (beq_idP x1 x).\n  - destruct (beq_idP x2 x).\n    * destruct H. rewrite e. rewrite e0. reflexivity.\n    * reflexivity.\n  - destruct (beq_idP x2 x).\n    * reflexivity.\n    * reflexivity.\nQed.\n(** [] *)\n\n(* ###################################################################### *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A:Type} (m : partial_map A)\n                  (x : id) (v : A) :=\n  t_update m x (Some v).\n\n(** We can now lift all of the basic lemmas about total maps to\n    partial maps.  *)\n\nLemma update_eq : forall A (m: partial_map A) x v,\n  (update m x v) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (X:Type) v x1 x2\n                       (m : partial_map X),\n  x2 <> x1 ->\n  (update m x2 v) x1 = m x1.\nProof.\n  intros X v x1 x2 m H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall A (m: partial_map A) v1 v2 x,\n  update (update m x v1) x v2 = update m x v2.\nProof.\n  intros A m v1 v2 x1. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall X v x (m : partial_map X),\n  m x = Some v ->\n  update m x v = m.\nProof.\n  intros X v x m H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (X:Type) v1 v2 x1 x2\n                                (m : partial_map X),\n  x2 <> x1 ->\n    (update (update m x2 v2) x1 v1)\n  = (update (update m x1 v1) x2 v2).\nProof.\n  intros X v1 v2 x1 x2 m. unfold update.\n  apply t_update_permute.\nQed.\n\n(** $Date: 2015-12-11 17:17:29 -0500 (Fri, 11 Dec 2015) $ *)\n\n", "meta": {"author": "colinmccabe", "repo": "software-foundations", "sha": "d581e89d47978ed9acc9e2a64ba6209a614fd9f1", "save_path": "github-repos/coq/colinmccabe-software-foundations", "path": "github-repos/coq/colinmccabe-software-foundations/software-foundations-d581e89d47978ed9acc9e2a64ba6209a614fd9f1/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.8991213684847577, "lm_q1q2_score": 0.7084457659433137}}
{"text": "(*\n  Nombre : Taller 2 Logica proposicional\n  Autor : Guido Salazar\n  Fecha : 11/09/2020\n*)\n\n(*Definición de LP*)\n\n(*Punto 1*)\n\n(*Definiciòn de los conectivos l+ogicos*)\nInductive con : Type :=\n  |and : con\n  |or : con\n  |imp : con.\n\n(*Definición de LP*)\nInductive LP : Set :=\n  | p: LP\n  | q: LP\n  | neg: LP -> LP\n  | phi: LP -> con -> LP -> LP.\n\n(*Punto 2*)\n\n(*El conjunto LP es inductivo, ya que usa la recurrencia para poder definirse a si mismo apartir de un caso base.\n  Es decir, que parte desde un conjunto muy basico y a partir de reglas ir creando un conjunto mas grandes.\n  Especificamente en este caso se usa la inducción estructural, donde el caso base son los atomos, y hay dos casos\n  inductivos, la negación y la composición binaria que toma dos LP y los junto con un conector binario.*)\n\n\n(*Punto 3*)\n\n(*La función parentesis devuelve la cantidad de parentesis que tiene una formula phi, para esto se asume que\n  la negación no agrega un parentesis. Por ejemplo si phi pertenece a L Sigma, entonces ~phi tambien pertenece a L Sigma,\n  no se escribe ~(phi).*)\nFixpoint parentesis (lp : LP) : nat :=\n  match lp with\n    | p => 0\n    | q => 0\n    | neg PHI => 0 + parentesis PHI\n    | phi PHI1 _ PHI2 => 2 + (parentesis PHI1) + (parentesis PHI2)\n  end.\n\n(*Punto 4*)\n\n(*Esta función me devuelve la cantidad de negaciones en una formula propocicional*)\nFixpoint simbolos_neg (lp : LP) : nat :=\n  match lp with\n    | p => 0\n    | q => 0\n    | neg PHI => 1 + simbolos_neg PHI\n    | phi PHI1 _ PHI2 => 0 + (simbolos_neg PHI1) + (simbolos_neg PHI2)\n  end.\n\n(*Punto 5*)\n\n(*Esta función me devuelve la cantidad de atomos proposicionales en una formula propocicional*)\nFixpoint num_var_LP (lp : LP) : nat :=\n  match lp with\n    | p => 1\n    | q => 1\n    | neg PHI => 0 + num_var_LP PHI\n    | phi PHI1 _ PHI2 => 0 + (num_var_LP PHI1) + (num_var_LP PHI2)\n  end.\n\n(*Pruebas definición de LP*)\n\nDefinition lp1 := p.\nDefinition lp2 := q.\nDefinition lp3 := phi lp1 or lp2.\nDefinition lp4 := neg (phi (phi lp3 and lp2) or (neg lp1)).\n\nCompute lp1.\nCompute lp2.\nCompute lp3.\nCompute lp4.\n\nCompute parentesis lp3.\nCompute parentesis lp4.\nCompute simbolos_neg lp4.\nCompute num_var_LP lp4.\n\n(*Definicion de cadenas de numero*)\n\n(*Punto 1*)\n(*Definición de una cadena de numeros*)\nInductive cadena : Set :=\n  | Vacio : cadena\n  | Nodo : nat -> cadena -> cadena.\n\n\n(*Punto 2*)\n\n(*Función que me dice si una cadena esta vacia o no*)\nDefinition cadena_vacia (c : cadena) : bool :=\n  match c with\n    | Vacio => true\n    | Nodo _ _ => false\n  end.\n\n(*Punto 3*)\n\n(*Función que retorna la longitud de una cadena*)\nFixpoint longitud (c : cadena) : nat :=\n  match c with\n    | Vacio => 0\n    | Nodo _ c1 => 1 + (longitud c1)\n  end.\n\n(*Punto 4*)\n\n(*Función que suma el valor de cada elemento en una cadena*)\nFixpoint suma_cadena (c : cadena) : nat :=\n  match c with\n    | Vacio => 0\n    | Nodo n c1 => n + (suma_cadena c1)\n  end.\n\n(*Punto 5*)\n\n(*Función auxiliar que concatena dos cadenas*)\nFixpoint concatenar (c1 c2 : cadena) : cadena :=\n  match c1 with\n    | Vacio => c2\n    | Nodo n c => Nodo n (concatenar c c2)\n  end.\n\n(*Función que recibe una cadena y retorna la misma cadena invertida*)\nFixpoint invertir (c : cadena) : cadena :=\n    match c with\n    | Vacio => Vacio\n    | Nodo n c1 => concatenar (invertir c1) (Nodo n Vacio)\n  end.\n\n(*Pruebas Definición Cadena*)\nDefinition c0 := Vacio.\nDefinition c1 := Nodo 3 Vacio.\nDefinition c2 := Nodo 5 (Nodo 45 Vacio).\n\nCompute c0.\nCompute c1.\nCompute c2.\n\nDefinition c3 := concatenar c2 c1.\n\nCompute c3.\n\nCompute cadena_vacia c0.\nCompute cadena_vacia c1.\nCompute longitud c2.\nCompute longitud c3.\nCompute suma_cadena c3.\nCompute invertir c3.\n  \n\n\n\n\n\n\n", "meta": {"author": "GAOV13", "repo": "Logica-Computacional", "sha": "384ef4fac3f9a02a16f0655f95e16215c41e6cc3", "save_path": "github-repos/coq/GAOV13-Logica-Computacional", "path": "github-repos/coq/GAOV13-Logica-Computacional/Logica-Computacional-384ef4fac3f9a02a16f0655f95e16215c41e6cc3/Taller 2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7084211590176918}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import all_algebra.\nFrom elpi Require Import elpi.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* SB木のInductiveによる表現 *)\nInductive sbtree : nat -> nat -> nat -> nat -> Prop :=\n  sbtInit  : sbtree 0 1 1 0\n| sbtLeft  : forall m n m' n',\n               sbtree m n m' n' -> sbtree m n (m + m') (n + n')\n| sbtRight : forall m n m' n',\n               sbtree m n m' n' -> sbtree (m + m') (n + n') m' n'.\n\n(* (m+m')/(n+n')を作る関数 *)\nDefinition calc_sbnode (m n m' n' : nat) : (nat * nat) := (m + m', n + n').\nEval compute in calc_sbnode 0 1 1 0. (* = (1, 1) : nat * nat 1/1のつもり *)\nEval compute in calc_sbnode 0 1 1 1. (* = (1, 2) : nat * nat 1/2のつもり *)\nEval compute in calc_sbnode 0 1 1 2. (* = (1, 3) : nat * nat 1/3のつもり *)\nEval compute in calc_sbnode 1 3 1 2. (* = (2, 5) : nat * nat 2/5のつもり *)\nEval compute in calc_sbnode 2 5 1 2. (* = (3, 7) : nat * nat 3/7のつもり *)\n\nCheck @sbtLeft 0 1 1 0 sbtInit. (* = 1/1 *)\nCheck (sbtLeft (sbtLeft sbtInit)). (* = 1/3 *)\n\n(*\n  sbtree a b c d が成り立つ場合に、その証明手順を調べるElpiプログラム\n    (いずれはsbtree専用autoタクティクみたいなものを作れたらと思います。)\n*)\nElpi Program check_sbtree lp:{{\n\n  pred check_sbtree o:int, o:int, o:int, o:int.\n\n  check_sbtree 0 1 1 0 :- coq.say \"apply: sbtInit. (sbtree 0 1 1 0 → No more subgoals)\".\n\n  check_sbtree A B C D :- X = A, Y = B, Z is (C - A), W is (D - B),\n                          X >= 0, Y >= 0, Z >= 0, W >= 0,\n                          coq.say \"apply: sbtLeft. (sbtree\" A B C D \"→ sbtree\" X Y Z W \")\",\n                 \t        check_sbtree X Y Z W.\n\n  check_sbtree A B C D :- X is (A - C), Y is (B - D), Z = C, W = D,\n                          X >= 0, Y >= 0, Z >= 0, W >= 0,\n                          coq.say \"apply: sbtRight. (sbtree\" A B C D \"→ sbtree\" X Y Z W \")\",\n                          check_sbtree X Y Z W.\n\n}}.\n\n(* (0+1)/(1+0) = 1/1 がSB木のノードかどうかの確認 *)\nElpi Query lp:{{ check_sbtree 0 1 1 0. }}.\n(*\n  apply: sbtInit. (sbtree 0 1 1 0 → No more subgoals)\n*)\n\n(* (0+1)/(1+1) = 1/2 がSB木のノードかどうかの確認 *)\nElpi Query lp:{{ check_sbtree 0 1 1 1. }}.\n(*\n  apply: sbtLeft. (sbtree 0 1 1 1 → sbtree 0 1 1 0 )\n  apply: sbtInit. (sbtree 0 1 1 0 → No more subgoals)\n*)\n\n(* (0+1)/(1+1) = 1/2 がSB木のノードであることの証明 *)\nGoal sbtree 0 1 1 1. (* 0/1, 1/1 -> (0+1)/(1+1) = 1/2 *)\nProof.\n  apply: sbtLeft.\n  by apply: sbtInit.\nQed.\n\n(* (2+1)/(5+2) = 3/7 がSB木のノードかどうかの確認 *)\nElpi Query lp:{{ check_sbtree 2 5 1 2. }}.\n(*\n  apply: sbtRight. (sbtree 2 5 1 2 → sbtree 1 3 1 2 )\n  apply: sbtRight. (sbtree 1 3 1 2 → sbtree 0 1 1 2 )\n  apply: sbtLeft. (sbtree 0 1 1 2 → sbtree 0 1 1 1 )\n  apply: sbtLeft. (sbtree 0 1 1 1 → sbtree 0 1 1 0 )\n  apply: sbtInit. (sbtree 0 1 1 0 → No more subgoals)\n*)\n\n(* (2+1)/(5+2) = 3/7 がSB木のノードであることの証明 *)\nGoal sbtree 2 5 1 2. (* 2/5, 1/2 -> (2+1)/(5+2) = 3/7 *)\nProof.\n  apply: (@sbtRight 1 3 1 2). (* 1/3, 1/2 -> (1+1)/(3+2) = 2/5 *)\n  apply: (@sbtRight 0 1 1 2). (* 0/1, 1/2 -> (0+1)/(1+2) = 1/3 *)\n  apply: (@sbtLeft 0 1 1 1). (* 0/1, 1/1 -> (0+1)/(1+1) = 1/2 *)\n  apply: (@sbtLeft 0 1 1 0). (* 0/1, 1/0 -> (0+1)/(1+0) = 1/1 *)\n  by apply: sbtInit.\nQed.\n\nEval compute in 1 * 3 - 2 * 4. (* m' * n - m * n' = 0 *)\nEval compute in 1 * 5 - 2 * 2. (* m' * n - m * n' = 1 *)\nElpi Query lp:{{ check_sbtree 2 3 1 4. }}.\n(*\n  The elpi command check_sbtree failed without giving a specific error message.\n  Please report this inconvenience to the authors of the program.\n\n  SB木のノードでなかった場合に、エラーメッセージを表示して終了させる方法が不明です。\n  (elpiで実行すれば、Failureが返ります。)\n*)\n", "meta": {"author": "wakaba2017", "repo": "ProofCafe", "sha": "f2dd32225e2a9ed38577621e228d0adc1e1cd0b5", "save_path": "github-repos/coq/wakaba2017-ProofCafe", "path": "github-repos/coq/wakaba2017-ProofCafe/ProofCafe-f2dd32225e2a9ed38577621e228d0adc1e1cd0b5/sb_elpi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7083698144513194}}
{"text": "(**  Injection from the set of  ordinal terms in Cantor normal form\n  into the set of Schutte's countable ordinal numbers stricly less than\n  epsilon0.\n\n  Pierre Castéran, Univ. Bordeaux and LaBRI\n\n   This is intented to be a validation of main constructions and functions \n   designed for the type [T1].\n\n*)\n\n(*  Pierre Casteran \n    LaBRI, Université Bordeaux 1\n*)\n\n\n\nFrom hydras Require Import Epsilon0.Epsilon0 ON_Generic. \nFrom hydras Require Import Schutte_basics  Schutte.Addition  AP CNF.\n\n\nImport List  PartialFun Ensembles.\n\n(* begin snippet injectDef *)\n\nFixpoint inject (t:T1) : Ord :=\n  match t with\n  | T1.zero => zero\n  | T1.cons a n b => AP._phi0 (inject a) * S n + inject b\n  end.\n\n(* end snippet injectDef *)\n\nLemma inject_of_finite_pos : forall n, inject (\\F (S n)) = F (S n).\nProof.\n induction n;simpl.\n -  rewrite phi0_zero.\n    rewrite alpha_plus_zero; auto with schutte.\n - clear IHn.  induction n; simpl ; auto.\n    + repeat rewrite phi0_zero.\n      rewrite alpha_plus_zero; auto with schutte.\n      * rewrite <- succ_is_plus_1.\n             f_equal. \n    + rewrite alpha_plus_zero. \n     *  rewrite alpha_plus_zero in IHn.\n        rewrite IHn. \n        replace (AP._phi0 zero) with (F 1).\n        rewrite <- succ_is_plus_1; auto with schutte.\n        symmetry; auto with schutte. \n        apply phi0_zero. \nQed.\n\n\n\n(* begin snippet commutationLemmas *)\n\n(*| .. coq:: no-out |*)\n\nTheorem inject_of_zero : inject T1.zero = zero.\nProof. reflexivity. Qed.\n\n\nTheorem inject_of_finite (n : nat):\n  inject (\\F n) =  n.\n(*||*) (*| .. coq:: none |*)\nProof.\n  destruct n.\n  - apply inject_of_zero.\n  - apply inject_of_finite_pos.\nQed.\n(*||*)\n\n\nTheorem inject_of_omega :\n  inject T1omega = Schutte_basics._omega. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n simpl; repeat rewrite alpha_plus_zero.\n rewrite phi0_zero;  generalize omega_second_AP; destruct 1.\n red in H; unfold Ensembles.In in H0; now rewrite omega_eqn.\nQed.\n(*||*)\n\n\nTheorem inject_of_phi0 (alpha : T1):\n  inject (T1.phi0 alpha) = AP._phi0 (inject alpha). (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  simpl; now rewrite alpha_plus_zero.\nQed.\n\n(*||*)\n(* end snippet commutationLemmas *)\n\n(* begin hide *)\n\nLemma phi0_mult_lt_phi0 (alpha beta : Ord) :\n    alpha < beta ->\n    forall n,  (AP._phi0 alpha) * S n  < AP._phi0 beta.\nProof.\n  induction n;simpl;auto.\n  -  apply phi0_mono;auto.\n  -  apply AP_plus_closed; trivial.\n    + apply AP_phi0.\n    + apply phi0_mono;auto.\nQed.\n\nLemma phi0_mult_plus_lt_phi0 alpha beta n gamma :\n  alpha < gamma -> beta < AP._phi0 gamma ->\n  mult_Sn (AP._phi0 alpha) n  + beta < AP._phi0 gamma.\nProof.\n  intros;apply AP_plus_closed ; auto with schutte.\n  -  apply AP_phi0.\n  -  apply  phi0_mult_lt_phi0;auto.\nQed.\n\nLemma phi0_mult_plus_lt_phi0R alpha beta n gamma :\n  mult_Sn (AP._phi0 alpha) n  + beta < AP._phi0 gamma ->\n  alpha < gamma /\\ beta < AP._phi0 gamma.\nProof.\n  split.\n  - assert (H0 : AP._phi0 alpha < AP._phi0 gamma).\n    {  eapply le_lt_trans.\n       2:eexact H.\n       apply le_trans with  (mult_Sn (AP._phi0 alpha) n).\n       clear H; induction n.\n       simpl;auto with schutte.\n       simpl;   apply le_plus_r.\n       apply le_plus_l;auto with schutte.\n    }\n    apply phi0_mono_R;auto.\n   -   eapply le_lt_trans.\n       2:eexact H.\n       apply le_plus_r;auto with schutte.\nQed.\n\nLemma zero_lt alpha n beta : \n  zero < mult_Sn (AP._phi0 alpha) n + beta.\nProof.\n apply lt_le_trans with (AP._phi0 alpha).\n -  apply phi0_positive;auto.\n - apply le_trans with ( mult_Sn (AP._phi0 alpha) n).\n  induction n; simpl; auto with schutte.\n   +  apply le_plus_r;auto.\n   +  apply  le_plus_l;auto with schutte.\nQed.\n \n\nLemma head_lt :  forall a a' n n' b b',\n    a  < a' -> b < AP._phi0 a'  ->\n    mult_Sn (AP._phi0 a) n + b < mult_Sn (AP._phi0 a') n' + b'.\nProof.\n intros.\n apply lt_le_trans with (AP._phi0 a').\n - apply phi0_mult_plus_lt_phi0;auto.\n -  apply le_trans with (mult_Sn (AP._phi0 a') n').\n  + induction n';simpl;auto.\n   *  left; auto.\n   *  apply le_plus_r;auto with schutte.\n  +  apply le_plus_l;auto with schutte.\nQed.\n\n\nLemma coeff_lt : forall a  n n' b b',\n    b < AP._phi0 a  ->(n < n')%nat ->\n    mult_Sn (AP._phi0 a) n + b < mult_Sn (AP._phi0 a) n' + b'.\nProof.\n intros;  apply lt_le_trans with (mult_Sn (AP._phi0 a) n').\n -  apply lt_le_trans with (mult_Sn (AP._phi0 a) n + AP._phi0 a).\n   +  apply plus_mono_r; auto.\n   +  apply mult_Sn_mono3; auto.\n     *  apply  phi0_positive; auto. \n - apply le_plus_l. \nQed. \n\nLemma inject_mono_0 : forall alpha,\n    T1.nf alpha ->\n    forall beta gamma, \n      T1.lt  beta gamma -> \n      T1.lt gamma alpha ->\n      T1.nf beta -> T1.nf gamma ->\n      (inject beta < inject gamma)%sch.\nProof with eauto with T1.\n  intros alpha;  T1.transfinite_induction alpha.\n  intros x Indx Nx;  induction beta; destruct gamma.\n  {  intros H H0;  T1.T1_inversion H. }\n  { intros H H0 H1 H2;  simpl; \n      apply lt_le_trans with (AP._phi0 (inject gamma1))%sch.\n    -  apply phi0_positive;auto with schutte.\n    - eapply le_trans. \n      2:eapply le_plus_l; auto with schutte.\n      apply le_a_mult_Sn_a; auto with schutte.\n  }\n  intros H H0 H1 H2;  T1.T1_inversion H.\n  intros H H0 H1 H2; simpl;  destruct (T1.lt_inv H).\n  -   apply head_lt.    \n      +  eapply IHbeta1 ...\n\n         * apply T1.lt_trans with  (T1.cons gamma1 n0 gamma2) ...\n      +  apply lt_trans with (inject (T1.phi0 beta1)). \n         *   eapply IHbeta2 ...\n             apply T1.nf_helper_phi0.\n             apply T1.nf_helper_intro with n; auto. \n             apply Comparable.le_lt_trans with (T1.cons beta1 n beta2); auto with T1.\n             apply T1.le_phi0 ; eauto with T1.\n             eapply T1.lt_trans ...\n         * simpl; rewrite alpha_plus_zero.\n           apply phi0_mono,  IHbeta1; auto. \n           apply T1.lt_trans with (T1.cons gamma1 n0 gamma2) ...\n           eauto with T1.\n           eauto with T1.\n  -     decompose [or and] H3.\n        subst;  apply coeff_lt. \n        + replace  (AP._phi0 (inject gamma1)) with (inject (T1.phi0 gamma1)).\n          *  apply IHbeta2.\n             apply T1.nf_helper_phi0.\n             eapply T1.nf_helper_intro; eauto.\n             apply Comparable.le_lt_trans with (T1.cons gamma1 n0 gamma2); auto. \n             destruct n0.\n             apply T1.le_tail ...\n             apply Comparable.lt_incl_le.\n             apply T1.coeff_lt; auto with arith.\n             eauto with T1.\n             eapply T1.nf_phi0; eauto with T1.\n          * cbn; rewrite alpha_plus_zero ...\n        +  auto.\n        +  subst; apply plus_mono_r.\n           apply IHbeta2; eauto with schutte T1.\n           eapply T1.lt_trans.\n           2: eapply H0.\n           auto with T1.\n           apply T1.tail_lt_cons; auto.\nQed. \n\n(* end hide *)\n\nTheorem inject_mono (beta gamma : T1) :\n  T1.lt  beta gamma -> \n  T1.nf beta -> T1.nf gamma -> \n  inject beta < inject gamma.\nProof.  \n  intros H H0 H1; apply inject_mono_0 with (T1.succ gamma);auto.\n  -  apply T1.succ_nf;auto.\n  -  apply T1.lt_succ;auto.\nQed.\n\nTheorem inject_injective (beta gamma : T1) : nf beta -> nf gamma ->\n                                             inject beta = inject gamma -> beta = gamma.\nProof.\n  intros H H0 H1. \n  destruct (LT_eq_LT_dec H H0) as [[H2 | H2] | H2]; auto.\n  destruct H2 as [H3 [H4 H5]].   apply inject_mono in H4; auto.    \n  rewrite H1 in H4; auto.\n  destruct (lt_irrefl H4); auto.\n  destruct H2 as [H3 [H4 H5]].   apply inject_mono in H4; auto.    \n  rewrite H1 in H4; auto.\n  destruct (lt_irrefl H4); auto.\nQed.\n\nTheorem inject_monoR (beta gamma : T1) : \n  T1.nf beta -> T1.nf gamma -> \n  inject beta < inject gamma -> \n  (beta  t1< gamma)%t1.\nProof.  \n  intros H H0 H1; \n  destruct (T1.lt_eq_lt_dec beta gamma) as [[H2 | H2] | H2].\n  -  now split.  \n  -  subst ;  case (lt_irrefl  H1).\n  -  destruct (@lt_irrefl (inject beta)).\n     eapply lt_trans with (inject gamma); auto.\n     now apply inject_mono.\nQed.\n\n(* begin snippet injectLtEpsilon0 *)\n\nTheorem inject_lt_epsilon0 (alpha : T1):\n  inject alpha < epsilon0. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  assert (Ap := epsilon0_AP); induction alpha; simpl.\n  - rewrite <- epsilon0_fxp; apply phi0_positive.\n  - apply AP_plus_closed; auto.\n    apply AP_mult_Sn_closed; auto.\n    now apply phi0_lt_epsilon0.\nQed.\n(*||*)\n(* end snippet injectLtEpsilon0 *)\n\n\n(* begin hide *)\n\n\n\n\nSection Equations_for_addition.\n\n  Lemma plus_alpha_mult_phi0 (alpha beta : Ord)  (H: alpha < AP._phi0 beta)\n        (n : nat) : alpha + mult_Sn (AP._phi0 beta) n = mult_Sn (AP._phi0 beta) n.\n  Proof.\n    induction n.\n    - simpl;    destruct (AP_phi0 beta ) as [ _ H1];   apply  (H1 _ H).  \n    - simpl;  rewrite plus_assoc; now rewrite IHn.\n  Qed.\n\n  Lemma mult_Sn_dist (alpha : Ord) (n p : nat) :\n    mult_Sn alpha (S (n + p)) = mult_Sn alpha p + mult_Sn alpha n.\n  Proof.\n    induction n; simpl.\n    - reflexivity. \n    - rewrite  plus_assoc;  f_equal.\n      now   rewrite <- IHn.\n  Qed. \n\n\n\n  (*\n\n  Quoted from Epsilon0.T1\n\n  Fixpoint plus (alpha beta : T1) :T1 :=\n  match alpha,beta with\n  |  zero, y  => y\n |  x, zero  => x\n |  cons a n b, cons c p d =>\n    (match compare a c with\n     | Lt => cons c p d\n     | Gt => (cons a n (plus b (cons c p d)))\n     | Eq  => (cons a (S (n+p)) d)\n     end)\n  end\nwhere \"alpha + beta\" := (plus alpha beta) : t1_scope.\n   *)\n\n  \n\n  Variables (a b c d : Ord) (n p : nat).\n\n  Hypotheses (Hnfa : b < AP._phi0 a)\n             (Hnfc : d < AP._phi0 c).\n  Let alpha := mult_Sn  (AP._phi0 a) n + b.\n  Let beta := mult_Sn  (AP._phi0 c) p + d.\n  Section case1.\n    Hypothesis Hac: a < c.\n\n\n    Lemma case_lt : alpha + beta = beta.\n    Proof.\n      unfold alpha, beta.\n      rewrite <-\n              (plus_assoc (mult_Sn (AP._phi0 a) n)\n                          b\n                          (mult_Sn (AP._phi0 c) p + d)).\n      assert (b < AP._phi0 c).\n      { apply lt_trans with (AP._phi0 a); auto with schutte.\n        now apply phi0_mono.\n      }   \n      rewrite (plus_assoc b (mult_Sn (AP._phi0 c) p) d).\n      rewrite (plus_alpha_mult_phi0 _ _ H p).\n      rewrite  plus_assoc .\n      rewrite plus_alpha_mult_phi0.\n      auto.\n      apply AP_mult_Sn_closed.\n      apply AP_phi0.\n      now apply phi0_mono.\n    Qed.\n\n    \n  End case1.\n\n  Section case2.\n    Hypothesis Hac : c < a.\n\n    Lemma case_gt : alpha + beta = mult_Sn (AP._phi0 a) n +\n                                   (b + beta). \n    Proof. \n      unfold alpha;  now  rewrite plus_assoc.\n    Qed.\n\n  End case2.\n\n  Section case3.\n\n    Hypothesis Hac : a = c.\n\n    Lemma case_Eq : alpha + beta = mult_Sn (AP._phi0 a) (S (n + p)) + d.\n    Proof.\n      unfold alpha, beta; subst c; rewrite <- plus_assoc.\n      rewrite (plus_assoc b (mult_Sn (AP._phi0 a) p) d).\n      rewrite (plus_alpha_mult_phi0 _ _ Hnfa).\n      rewrite plus_assoc;  f_equal.\n      rewrite Nat.add_comm; now  rewrite mult_Sn_dist.\n    Qed.\n\n  End case3.\n\nEnd Equations_for_addition.\n\n\n(* end hide *)\n\nLemma inject_rw (a b: T1) n : inject (T1.cons a n b) =\n                              mult_Sn (AP._phi0 (inject a)) n + inject b.\nProof. reflexivity. Qed.\n\n(* begin snippet injectPlus *)\n\nTheorem inject_plus (alpha beta : T1):\n  nf alpha -> nf beta ->\n  inject (alpha + beta)%t1 = inject alpha + inject beta. (* .no-out *)\n(*| .. coq:: none |*)\nProof with eauto with T1.\n  induction alpha.\n  - simpl;  now rewrite zero_plus_alpha.\n  -  intros H H0;  destruct beta.\n     + simpl (inject (T1.cons  alpha1 n alpha2));\n         rewrite <- plus_assoc; simpl (inject T1.zero); \n           now rewrite alpha_plus_zero.\n\n     + repeat rewrite inject_rw.\n       simpl.\n       destruct (compare alpha1 beta1) eqn:H1;\n       repeat rewrite inject_rw.\n       * apply compare_eq_iff in H1 as <-.\n          rewrite <- (case_Eq (inject alpha1) (inject alpha2)\n                              (inject alpha1) (inject  beta2) n n0) ...\n          -- assert (H1 : (alpha2 t1< T1.phi0  alpha1)%t1). \n             {  rewrite nf_LT_iff in H;  tauto. }\n          rewrite <- inject_of_phi0.\n          apply inject_mono ...\n          -- rewrite <- inject_of_phi0; apply inject_mono ...\n             rewrite nf_LT_iff in H0 ...\n             decompose [and] H0 ... \n        * rewrite compare_lt_iff in H1.\n          { repeat rewrite inject_rw; rewrite case_lt; auto.\n            rewrite <- inject_of_phi0;  apply inject_mono ...\n            -  rewrite nf_LT_iff in H; decompose [and] H ...\n            -  apply inject_mono; eauto with T1.\n          }  \n        * rewrite compare_gt_iff in H1.\n          repeat rewrite inject_rw; rewrite case_gt.\n          f_equal; rewrite IHalpha2 ...\nQed.\n(*||*)\n(* end snippet injectPlus *)\n\n\n(* begin snippet injectMultFinR *)\n\nTheorem inject_mult_fin_r (alpha : T1)  :\n  nf alpha ->\n  forall n:nat,\n    inject (alpha *  n)%t1 =  inject alpha * n. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  induction n.\n  - simpl.\n    destruct alpha; simpl; auto.\n    destruct alpha1; simpl; auto.\n  -  destruct n.\n     +  simpl (inject alpha * 1).\n        simpl (alpha * 1)%t1.\n        destruct alpha; auto.\n        destruct alpha1.\n        *   f_equal;  destruct n; simpl; auto.\n            assert (alpha2 = T1.zero).  \n            {  eapply nf_of_finite; eauto. }\n            -- subst. f_equal; ring.\n            -- assert (alpha2 = T1.zero).  \n            {  eapply nf_of_finite; eauto. }\n            subst.\n            replace (n * 1)%nat with n; auto with arith.\n*  replace (n * 1)%nat with n; auto with arith.\n     +   change ((S (S n)):T1) with  (FS (S n)); rewrite mult_Sn_add.\n         replace (S (S n)) with (S (S (n + 0)))%nat.\n         simpl mult_fin_r;  rewrite inject_plus; auto with arith.\n         *  replace (alpha * (FS n))%t1 with (alpha * (S n))%t1.\n            --  rewrite IHn;  replace (n+0)%nat with n.\n                reflexivity.\n                auto with arith.\n            -- reflexivity.\n         * \n           { \n             clear IHn; induction n; simpl.\n             destruct alpha;  auto.\n             destruct alpha1.\n             apply nf_of_finite in H; subst; apply nf_FS.\n             replace (n * 1)%nat with n; auto with arith.\n             destruct alpha; auto with T1.\n             destruct alpha1.\n              apply nf_of_finite in H; subst; apply nf_FS.\n             eapply nf_coeff_irrelevance. eauto. \n           }\n         *   auto with arith.\n         * auto.\nQed. \n(*||*)\n(* end snippet injectMultFinR *)\n\n\nLemma inject_lt_epsilon0_ex_cnf  (alpha : Ord) :\n  forall (H  : alpha < epsilon0)\n         (l: list Ord),  is_cnf_of alpha l ->\n                         exists t: T1,  nf t /\\ inject t = eval l.\nProof.\n  pattern alpha; apply well_founded_induction with (R:=lt).\n  { exact all_ord_acc. }\n  { clear alpha; intros alpha IHalpha H. \n    destruct l.\n    -  exists T1.zero;  simpl;   unfold nf; split; auto.\n    - inversion_clear   1.\n      pose (H3 := IHalpha o).\n      assert (H0 : o < alpha).\n      { simpl in H2; \n          subst alpha; apply lt_le_trans with (AP._phi0 o).\n        - apply lt_phi0; apply le_lt_trans with (AP._phi0 o).\n          + apply le_phi0.\n          +  apply le_lt_trans with (2:= H); apply le_plus_l.\n        -   apply le_plus_l.\n      }\n      assert (H4 : o < epsilon0).\n      { apply lt_trans with alpha; auto. }\n      specialize (H3 H0 H4);  destruct (cnf_exists o) as [x H5].\n      specialize (IHalpha (eval l)).\n      assert (H6 : eval l < alpha). {\n        simpl in H2;   subst alpha;   apply sorted_lt;  auto. }\n      assert (H7 : eval l < epsilon0).\n      { apply lt_trans with alpha; auto. }\n      destruct (H3 _ H5) as [x0 H8].\n      destruct H8 as [H8 H9]; specialize  (IHalpha H6 H7).\n      + destruct (IHalpha l).\n        * split; trivial.\n          eapply sorted_tail; eauto.\n        *   destruct H10 as [H10 H11];  exists (T1.phi0 x0 + x1)%t1.\n            split.    \n            -- apply plus_nf ; eauto with T1.\n            -- simpl eval;  rewrite <- H11;  rewrite inject_plus; auto with T1.\n               simpl (inject (T1.phi0 x0)); rewrite H9;  destruct H5.\n               rewrite <- H12;  rewrite alpha_plus_zero; auto.\n  }\nQed.\n\n\nTheorem inject_lt_epsilon0_ex  (alpha : Ord) (H  : alpha < epsilon0) :\n  exists t: T1,  nf t /\\ inject t = alpha.\nProof.\n  destruct (cnf_exists alpha) as [l Hl].\n  destruct (inject_lt_epsilon0_ex_cnf alpha H l Hl) as [t [H1 H2]].\n  exists t; split ; [trivial | ].\n  destruct Hl; congruence.\nQed.\n\n\nTheorem inject_lt_epsilon0_ex_unique  (alpha : Ord) (H : alpha < epsilon0) :\n  exists! t: T1,  nf t /\\ inject t =  alpha.\nProof.\n  destruct (inject_lt_epsilon0_ex alpha H ) as [t [H0 H1]].\n  exists t; split.\n  - now split.\n  - intros t' [H2 H3].\n    rewrite <- H3 in H1;  now apply inject_injective.\nQed.\n\n(* begin snippet embedding *)\n\nTheorem embedding : fun_bijection (nf: Ensemble T1)\n                                  (members epsilon0)\n                                  inject. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  split.\n  -   intros x Hx; apply inject_lt_epsilon0.\n  -  intros y Hy; destruct (inject_lt_epsilon0_ex y Hy) as [x [Hx Hx1]];\n       exists x; auto.\n  -  intros x x' Hx Hx' H; apply inject_injective; auto.\nQed.\n(*||*)\n(* end snippet embedding *)\n\n(* begin snippet Epsilon0Correct *)\n\n#[ global ] Instance Epsilon0_correct :\n  ON_correct epsilon0 Epsilon0  (fun alpha => inject (cnf alpha)). (* .no-out *)\n(* end snippet Epsilon0Correct *)\n\nProof.\n  split.\n  - intro a; apply embedding; red; apply cnf_ok.\n  - intros; destruct (inject_lt_epsilon0_ex_unique _ H) as [x [[H0 H1] H2]].\n    exists (mkord H0);now cbn.\n  - intros a b; destruct (compare_correct a b).\n   + now subst.\n   + apply inject_mono;destruct H; tauto.\n   + apply inject_mono;  destruct H; tauto.\nQed.\n\n\n\n\n(** Correctness of E0.plus *)\n\nTheorem  E0_plus_correct :  ON_op_ok  E0add plus.\nProof.\n  red; destruct x,y; cbn.\n  rewrite inject_plus; auto.\nQed.\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/Schutte/Correctness_E0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7083698055054324}}
{"text": "Require Import Classical_Prop.\n\nRecord subset (X : Type) := as_subset { pred :> X -> Prop }.\nNotation \"x : A\" := ((pred _ A) x) (at level 70, no associativity) : type_scope.\n\n\n\n(*Definition eqv_pred {X : Type} {P : X -> Prop} (x : X) :\n  (pred (as_subset X P)) x <-> P x.\nProof. reflexivity. Qed.\n#[export] Hint Resolve eqv_pred : subsets.*)\n\nRequire Import Reals.\nRequire Import Lra.\nOpen Scope R_scope.\n\nVariable P : R -> Prop.\nDefinition A := as_subset R P.\n\nVariable x : R.\nCheck (x : A).\nCheck (is_lub A).\n\n\nNotation \"[ a , b ]\" := (as_subset R (fun x => (a <= x <= b))).\n\nCheck (x : [0,1]).\n\n\nGoal is_upper_bound [0,1] 1.\nProof.\n  unfold is_upper_bound.\n  intro a.\n  intro a_in_interval.\n  assert (0 <= a <= 1) by auto.\n  lra.\nQed.\n\nGoal 1/2 : [0,1].\nProof.\n  enough (0 <= 1/2 <= 1) by auto.\n  lra.\nQed.\n\n\n\n\n(* (Bad) alternative *)\n(* Clashes with default x : A notation on forall or exists statements. *)\nNotation \"x ∈ A\" := ((pred _ A) x) (at level 70, no associativity) : type_scope.\nCheck (x ∈ [0,1]).\n\n", "meta": {"author": "impermeable", "repo": "coq-waterproof", "sha": "a32bad4e44fedb4038065d2b55660cd967c2d1fd", "save_path": "github-repos/coq/impermeable-coq-waterproof", "path": "github-repos/coq/impermeable-coq-waterproof/coq-waterproof-a32bad4e44fedb4038065d2b55660cd967c2d1fd/waterproof/experiments/subset_notation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7083698013506253}}
{"text": "Require Import Nat Arith.\n\nInductive Nat : Type := succ : Nat -> Nat |  zero : Nat.\n\nInductive Lst : Type := cons : Nat -> Lst -> Lst |  nil : Lst.\n\nInductive Tree : Type := node : Nat -> Tree -> Tree -> Tree |  leaf : Tree.\n\nInductive Pair : Type := mkpair : Nat -> Nat -> Pair\nwith ZLst : Type := zcons : Pair -> ZLst -> ZLst |  znil : ZLst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : Lst) : Lst\n           := match rev_arg0 with\n              | nil => nil\n              | cons x y => append (rev y) (cons x nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : Lst) (qreva_arg1 : Lst) : Lst\n           := match qreva_arg0, qreva_arg1 with\n              | nil, x => x\n              | cons z x, y => qreva x (cons z y)\n              end.\n\nTheorem append_nil: forall (l: Lst), append l nil = l.\nProof.\n  induction l.\n  { simpl. f_equal. assumption. }\n  { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n  forall (l1 l2 l3: Lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n  induction l1; induction l2; induction l3; try (simpl; reflexivity).\n  { simpl. rewrite <- IHl1. f_equal. }\n  { simpl. rewrite 2 append_nil. reflexivity. }\n  { simpl. rewrite append_nil.  reflexivity. }\n  { simpl. rewrite 2 append_nil. reflexivity. }\nQed.\n\nTheorem qreva_append : forall (x y : Lst), (qreva x y) = (append (rev x) y).\nProof.\n  induction x; induction y; simpl; try reflexivity.\n  { rewrite IHx.\n    rewrite <- append_assoc.\n    f_equal. }\n  { rewrite IHx.\n    rewrite append_nil.\n    reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : Lst), eq (rev x) (qreva x nil).\nProof.\n  intros.\n  rewrite qreva_append.\n  rewrite append_nil.\n  reflexivity.\nQed.\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/CLAM/goal27.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7083473532003702}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_equalanglestransitive.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_supplements.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral_ruler_compass}.\n\nLemma lemma_supplements2 : \n   forall A B C D E F J K L P Q R, \n   RT A B C P Q R -> CongA A B C J K L -> RT J K L D E F ->\n   CongA P Q R D E F /\\ CongA D E F P Q R.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists a b c d e, (Supp a b c d e /\\ CongA A B C a b c /\\ CongA P Q R d b e)) by (conclude_def RT );destruct Tf as [a[b[c[d[e]]]]];spliter.\nlet Tf:=fresh in\nassert (Tf:exists j k l m n, (Supp j k l m n /\\ CongA J K L j k l /\\ CongA D E F m k n)) by (conclude_def RT );destruct Tf as [j[k[l[m[n]]]]];spliter.\nassert (CongA a b c A B C) by (conclude lemma_equalanglessymmetric).\nassert (CongA a b c J K L) by (conclude lemma_equalanglestransitive).\nassert (CongA a b c j k l) by (conclude lemma_equalanglestransitive).\nassert (CongA d b e m k n) by (conclude lemma_supplements).\nassert (CongA P Q R m k n) by (conclude lemma_equalanglestransitive).\nassert (CongA m k n D E F) by (conclude lemma_equalanglessymmetric).\nassert (CongA P Q R D E F) by (conclude lemma_equalanglestransitive).\nassert (CongA D E F P Q R) by (conclude lemma_equalanglessymmetric).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_supplements2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7083473456930542}}
{"text": "Require Export Elementary_Set.\n\nModule Ord.\n\n(* WELL ORDERING *)\n\n(* 81 Definition  x r y if and only [x,y] ∈ r. *)\n\nDefinition Rrelation x r y : Prop := [x,y] ∈ r.\n\nHint Unfold Rrelation : set.\n\n\n(* 82 Definition  r connects x if and only if when u and v belong to x either\n   u r v or v r u or v = u. *)\n\nDefinition Connect r x : Prop := \n  forall u v, u∈x /\\ v∈x -> (Rrelation u r v) \\/ (Rrelation v r u) \\/ (u=v).\n\nHint Unfold Connect : set.\n\n\n(* 83 Definition  r is transitive in x if and only if, when u, v, and w\n   are members of x and u r v and v r w, then u r w. *)\n\nDefinition Transitive r x : Prop :=\n  forall u v w, (u∈x /\\ v∈x /\\ w∈x /\\ Rrelation u r v /\\  Rrelation v r w) ->\n  Rrelation u r w.\n\nHint Unfold Transitive: set.\n\n\n(* 84 Definition  r is asymmetric in x if and only if, when u and v are\n   members of x and u r v, then it is not true that v r u. *)\n\nDefinition Asymmetric r x : Prop := \n  forall u v, (u ∈ x /\\ v ∈ x /\\ Rrelation u r v) -> ~ Rrelation v r u.\n\nCorollary Property_Asy : forall r x u,\n  Asymmetric r x -> u ∈ x -> ~ Rrelation u r u.\nProof.\n  intros; intro. \n  unfold Asymmetric in H; eapply H; eauto.\nQed.\n\nHint Unfold Asymmetric: set.\nHint Resolve Property_Asy: set.\n\n\n(* 85 Definition Inequality (x y:Class) := ~ (x = y) . *)\n\n(* Notation \"x ≠ y\" := (Inequality x y) (at level 70). *)\n\n\n(* 86 Definition  z is an r-first member of x if and only if z∈x and if y∈x,\n   then it is false that y r z. *)\n\nDefinition FirstMember z r x : Prop :=\n  z ∈ x /\\ (forall y, y ∈ x -> ~ Rrelation y r z).\n\nHint Unfold FirstMember : set.\n\n\n(* 87 Definition  r well-orders x if and only if r connects x and if y⊂x and\n   y ≠ Φ, then there is an r-first member of y. *)\n\nDefinition WellOrdered r x : Prop :=\n  Connect r x /\\ (forall y, y ⊂ x /\\ y ≠ Φ -> exists z, FirstMember z r y).\n\nHint Unfold WellOrdered : set.\n\n\n(* 88 Theorem  If r well-orders x, then r is transitive in x and r is\n   asymmetric in x. *)\n\nLemma Lemma88 : forall x u v w,\n  Ensemble u -> Ensemble v -> Ensemble w -> \n  x ∈ ([u] ∪ [v] ∪ [w]) -> x = u \\/ x= v \\/ x = w.\nProof.\n  intros.\n  apply Theorem19 in H; apply Theorem19 in H0; apply Theorem19 in H1.\n  apply Axiom_Scheme in H2; destruct H2, H3.\n  - left; apply Axiom_Scheme in H3; destruct H3; auto.\n  - apply Axiom_Scheme in H3; destruct H3, H4.\n    + right; left; apply Axiom_Scheme in H4; destruct H4; auto.\n    + right; right; apply Axiom_Scheme in H4; destruct H4; auto.\nQed.\n\nTheorem Theorem88 : forall r x,\n  WellOrdered r x -> Transitive r x /\\ Asymmetric r x .\nProof.\n  intros; generalize H; intro.\n  unfold WellOrdered in H0; destruct H0.\n  assert (Asymmetric r x).\n  { unfold Asymmetric; intros.\n    destruct H2, H3; AssE u; AssE v.\n    assert (([u | v] ⊂ x) /\\ ([u | v] ≠ Φ)).\n    { split.\n      - unfold Subclass; intros; apply Axiom_Scheme in H7; destruct H7, H8.\n        + apply Theorem19 in H5; apply Axiom_Scheme in H8.\n          destruct H8; rewrite H9; auto.\n        + apply Theorem19 in H6; apply Axiom_Scheme in H8.\n          destruct H8; rewrite H9; auto.\n      - apply Lemma35; exists u; apply Axiom_Scheme; split; auto;\n        left; apply Axiom_Scheme; split; auto. }\n  apply H1 in H7; destruct H7; unfold FirstMember in H7; destruct H7.\n  apply Theorem46 in H7; auto; destruct H7; subst x0.\n  - apply H8; apply Axiom_Scheme; split; auto; right; apply Axiom_Scheme; split; auto.\n  - intro; apply H8 with u; auto.\n    apply Axiom_Scheme; split; auto; left; apply Axiom_Scheme; split; auto. }\n  split; auto; unfold Transitive; intros.\n  - destruct H3, H4, H5, H6; unfold Connect in H0; specialize H0 with w u.\n    destruct H0 as [H0 | [H0 | H0]]; try split; auto.\n    * assert (([u] ∪ [v] ∪ [w] ⊂ x) /\\ ([u] ∪ [v] ∪ [w] ≠ Φ)).\n      { split.\n        - unfold Subclass; intros; apply Axiom_Scheme in H8.\n          destruct H8 as [_ H8]; destruct H8.\n          + AssE u; apply Theorem19 in H9; apply Axiom_Scheme in H8.\n            destruct H8; rewrite H10; auto.\n          + apply Axiom_Scheme in H8; destruct H8 as [_ H8]; destruct H8.\n            * AssE v; apply Theorem19 in H9; apply Axiom_Scheme in H8.\n              destruct H8; rewrite H10; auto.\n            * AssE w; apply Theorem19 in H9; apply Axiom_Scheme in H8.\n              destruct H8; rewrite H10; auto.\n        - intro; generalize (Theorem16 u); intro.\n          apply H9; rewrite <- H8; apply Axiom_Scheme; split; Ens.\n          left; apply Axiom_Scheme; split; intros; auto; Ens. }\n      apply H1 in H8; destruct H8.\n      unfold FirstMember in H8; destruct H8.\n      assert (u ∈ ([u] ∪ [v] ∪ [w])).\n      { apply Theorem4; left; apply Axiom_Scheme; split; Ens. }\n      assert (v ∈ ([u] ∪ [v] ∪ [w])).\n      { apply Theorem4; right; apply Axiom_Scheme; split; Ens.\n        left; apply Axiom_Scheme; split; Ens. }\n      assert (w ∈ ([u] ∪ [v] ∪ [w])).\n      { apply Theorem4; right; apply Axiom_Scheme; split; Ens. \n        right; apply Axiom_Scheme; split; Ens. }\n      apply Lemma88 in H8; Ens; destruct H8 as [H8|[H8|H8]]; subst x0.\n      + apply H9 in H12; contradiction.\n      + apply H9 in H10; contradiction.\n      + apply H9 in H11; contradiction.\n    * subst w; unfold Asymmetric in H2; absurd (Rrelation u r v); auto.\nQed.\n\nHint Resolve Theorem88: set.\n\n\n(* 89 Definition  y is an r-section of x if and only if y⊂x, r well-orders x,\n   and for each u and v such that u∈x, v∈y, and u r v it is true that u∈y. *)\n\nDefinition Section y r x : Prop :=\n  y ⊂ x /\\ WellOrdered r x /\\\n  (forall u v, (u ∈ x /\\ v ∈ y /\\ Rrelation u r v) -> u ∈ y).\n\nHint Unfold Section : set.\n\n\n(* 90 Theorem  If n ≠ Φ and each member of n is an r-section of x, then ∪n and\n   ∩n are r-sections of x. *)\n\nTheorem Theorem90 : forall n x r,\n  n ≠ Φ /\\ (forall y, y ∈ n -> Section y r x) -> \n  Section (∩ n) r x /\\ Section (∪ n) r x.\nProof.\n  intros; destruct H; double H.\n  apply Lemma35 in H; destruct H; double H; apply H0 in H.\n  red in H; destruct H, H3; split; unfold Section; intros.\n  - split; try split; auto; intros.\n    + unfold Subclass; intros; apply Axiom_Scheme in H5.\n      destruct H5; apply H6 in H2; auto.\n    + destruct H5, H6; apply Axiom_Scheme; split; intros; Ens.\n      apply Axiom_Scheme in H6; destruct H6; double H8; apply H0 in H8.\n      unfold Section in H8; eapply H8; split; eauto.\n  - split; try split; auto; intros.\n    + unfold Subclass; intros; apply Axiom_Scheme in H5; destruct H5, H6, H6.\n      apply H0 in H7; unfold Section in H7; destruct H7 as [H7 _]; auto.\n    + destruct H5, H6; apply Axiom_Scheme; split; intros; Ens.\n      apply Axiom_Scheme in H6; destruct H6, H8, H8.\n      double H9; apply H0 in H9; unfold Section in H9; destruct H9, H11.\n      exists x1; split; auto; eapply H12; split; eauto.\nQed.\n\nHint Resolve Theorem90 : set.\n\n\n(* 91 Theorem  If y is an r-section of x an y≠x, then y = {u : u∈x and u r v}\n   for some v in x. *)\n\nTheorem Theorem91 : forall x y r,\n  Section y r x /\\ y≠x ->\n  (exists v, v ∈ x /\\ y = \\{ λ u, u ∈ x /\\ Rrelation u r v \\}).\nProof.\n  intros; destruct H.\n  assert (exists v0, FirstMember v0 r (x ~ y)).\n  { unfold Section in H; destruct H, H1; unfold WellOrdered in H1; destruct H1.\n    assert ((x ~ y) ⊂ x).\n    { unfold Subclass; intros; apply Axiom_Scheme in H4; tauto. }\n    generalize (classic (x ~ y = Φ)); intro; destruct H5.\n    - apply Property_Φ in H; apply H in H5.\n      apply Property_Ineq in H0; contradiction.\n    - apply H3; split; auto. }\n  destruct H1; unfold FirstMember in H1; destruct H1.\n  exists x0; apply Axiom_Scheme in H1; destruct H1, H3.\n  split; auto; apply Axiom_Extent; split; intros.\n  unfold Section in H; destruct H, H6.\n  - apply Axiom_Scheme; repeat split; Ens; assert (z ∈ x); auto.\n    unfold WellOrdered in H6; destruct H6 as [H6 _]; unfold Connect in H6.\n    specialize H6 with x0 z; destruct H6 as [H6 | [H6 | H6]]; auto.\n    + assert (x0 ∈ y). { apply H7 with z; repeat split; auto. }\n      apply Axiom_Scheme in H4; destruct H4; contradiction.\n    + apply Axiom_Scheme in H4; destruct H4; subst x0; contradiction.\n  - apply Axiom_Scheme in H5; destruct H5, H6.\n    generalize (classic (z ∈ (x ~ y))); intro; destruct H8.\n    + apply H2 in H8; contradiction.\n    + generalize (classic (z ∈ y)); intro; destruct H9; auto.\n      elim H8; apply Axiom_Scheme.\n      repeat split; auto; apply Axiom_Scheme; tauto.\nQed.\n\nHint Resolve Theorem91 : set.\n\n\n(* 92 Theorem  If x and y are r-sections of z, then x⊂y or y⊂x. *)\n\nTheorem Theorem92 : forall x y z r,\n  Section x r z /\\ Section y r z -> x ⊂ y \\/ y ⊂ x.\nProof.\n  intros; destruct H.\n  generalize (classic (x = z)); intro; destruct H1.\n  - right; red in H0; subst z; tauto.\n  - generalize (classic (y = z)); intro; destruct H2.\n    + left; red in H; subst z; tauto.\n    + apply Lemma_xy with (x:= (Section x r z)) in H1; auto.\n      apply Lemma_xy with (x:= (Section y r z)) in H2; auto.\n      apply Theorem91 in H1; destruct H1, H1.\n      apply Theorem91 in H2; destruct H2, H2.\n      unfold Section in H; destruct H as [_ [H _]].\n      unfold WellOrdered in H; destruct H as [H _].\n      unfold Section in H0; destruct H0, H5.\n      apply Theorem88 in H5; destruct H5; unfold Transitive in H5.\n      assert ((x0 ∈ z) /\\ (x1 ∈ z)); try split; auto.\n      unfold Connect in H; generalize (H _ _ H8); intros.\n      destruct H9 as [H9 | [H9 | H9]].\n      * left; unfold Subclass; intros; rewrite H3 in H10.\n        apply Axiom_Scheme in H10; destruct H10, H11; rewrite H4.\n        apply Axiom_Scheme.\n        repeat split; auto; apply H5 with x0; auto.\n      * right; unfold Subclass; intros; rewrite H4 in H10.\n        apply Axiom_Scheme in H10; destruct H10, H11.\n        rewrite H3; apply Axiom_Scheme.\n        repeat split; auto; apply H5 with x1; auto.\n      * right; subst x0; rewrite H3, H4; unfold Subclass; intros; auto.\nQed.\n\nHint Resolve Theorem92 : set.\n\n\n(* 93 Definition  f is r-s order preserving if and only if f is a function,\n   r well-orders domain f, s well-orders range f, and f[u] s f[v] whenever u\n   and v are members of domain f such that u r v. *)\n\nDefinition Order_Pr f r s : Prop := \n  Function f /\\ WellOrdered r dom(f) /\\ WellOrdered s ran(f) /\\\n  (forall u v, u ∈ dom(f) /\\ v ∈ dom(f) /\\ Rrelation u r v ->\n  Rrelation f[u] s f[v]).\n\nHint Unfold Order_Pr : set.\n\n\n(* 94 Theorem  If x is an r-section of y and f is an r-r order-preserving\n   function on x to y, then for each u in x it is false that f[u] r u. *)\n\nTheorem Theorem94 : forall x r y f,\n  Section x r y /\\ Order_Pr f r r /\\ On f x /\\ To f y -> \n  (forall u, u ∈ x -> ~ Rrelation f[u] r u).\nProof.\n  intros; destruct H, H1, H2.\n  unfold Order_Pr in H1; destruct H1, H4, H5.\n  unfold On in H2; destruct H2 as [H2 H7].\n  unfold To in H3; destruct H3 as [_ H3].\n  generalize (classic (\\{ λ u, u ∈ x /\\ Rrelation (Value f u) r u \\} = Φ)).\n  intros; destruct H8.\n  - intro.\n    assert (u ∈ Φ). { rewrite <- H8; apply Axiom_Scheme; repeat split; Ens. }\n    generalize (Theorem16 u); intro; contradiction.\n  - unfold Section in H; destruct H, H9.\n    assert (\\{ λ u, u ∈ x /\\ Rrelation f [u] r u \\} ⊂ y).\n    { red; intros; apply Axiom_Scheme in H11; destruct H11, H12; auto. }\n    unfold WellOrdered in H9; destruct H9.\n    add (\\{ λ u, u ∈ x /\\ Rrelation f [u] r u \\} ≠ Φ) H11.\n    apply H12 in H11; destruct H11; unfold FirstMember in H11; destruct H11.\n    apply Axiom_Scheme in H11; destruct H11, H14.\n    assert (f[x0] ∈ ran( f)).\n    { rewrite <- H7 in H14; apply Property_Value in H14; auto.\n      apply Property_ran in H14; auto. }\n    assert (f [x0] ∈ y); auto; subst x.\n    assert (f [x0] ∈ \\{ λ u, u ∈ dom( f) /\\ Rrelation f [u] r u \\}).\n    { apply Axiom_Scheme; repeat split; try Ens.\n      apply H6; repeat split; auto; apply H10 with x0; split; auto. }\n    apply H13 in H7; contradiction.\nQed.\n\nHint Resolve Theorem94 : set.\n\n\n(* 95 Definition  f is a 1_1 function iff both f and f⁻¹ are functions. *)\n\nDefinition Function1_1 f : Prop := Function f /\\ Function (f⁻¹).\n\nHint Unfold Function1_1 : set.\n\n\n(* 96 Theorem  If f is r-s order preserving, then f is a 1_1 function and\n   f ⁻¹ is s-r order preserving. *)\n\nLemma Lemma96 : forall f, dom( f) = ran( f⁻¹ ).\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H; destruct H, H0; apply Axiom_Scheme; split; auto.\n    exists x; apply Axiom_SchemeP; split; auto; apply Lemma61; Ens.\n  - apply Axiom_Scheme in H; destruct H, H0; apply Axiom_Scheme.\n    split; auto; exists x; apply Axiom_SchemeP in H0; tauto.\nQed.\n\nLemma Lemma96' : forall f, ran( f) = dom( f⁻¹ ).\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H; destruct H, H0; apply Axiom_Scheme; split; auto.\n    exists x; apply Axiom_SchemeP; split; auto; apply Lemma61; Ens.\n  - apply Axiom_Scheme in H; destruct H, H0; apply Axiom_Scheme.\n    split; auto; exists x; apply Axiom_SchemeP in H0; tauto.\nQed.\n\nLemma Lemma96'' : forall f u,\n  Function f -> Function f⁻¹ -> u ∈ ran(f) ->  (f⁻¹)[u] ∈ dom(f).\nProof.\n  intros; rewrite Lemma96' in H1; apply Property_Value in H1; auto.\n  apply Axiom_SchemeP in H1; destruct H1; apply Property_dom in H2; auto.\nQed.\n\nLemma Lemma96''' : forall f u,\n  Function f -> Function f⁻¹ -> u ∈ ran(f) -> u = f[(f⁻¹)[u]].\nProof.\n  intros; generalize (Lemma96'' _ _ H H0 H1); intro.\n  apply Property_Value in H2; auto; rewrite Lemma96' in H1.\n  apply Property_Value in H1; auto; apply Axiom_SchemeP in H1.\n  destruct H1; red in H; destruct H; eapply H4; eauto.\nQed.\n\nTheorem Theorem96 : forall f r s,\n  Order_Pr f r s -> Function1_1 f /\\ Order_Pr (f⁻¹) s r.\nProof.\n  intros; unfold Order_Pr in H; destruct H, H0, H1.\n  assert (Function1_1 f).\n  { unfold Function1_1; split; auto; unfold Function; split; intros.\n    - red; intros; PP H3 a b; Ens.\n    - destruct H3; rename y into u; rename z into v.\n      apply Axiom_SchemeP in H3; destruct H3; apply Axiom_SchemeP in H4.\n      destruct H4; double H5; double H6.\n      apply Property_dom in H5; apply Property_dom in H6.\n      double H7; double H8; apply Property_dom in H7.\n      apply Property_dom in H8; rewrite Theorem70 in H9; auto.\n      apply Axiom_SchemeP in H9; destruct H9 as [_ H9].\n      rewrite Theorem70 in H10; auto.\n      apply Axiom_SchemeP in H10; destruct H10 as [_ H10].\n      rewrite H10 in H9; symmetry in H9; clear H10.\n      apply Property_Value in H7; apply Property_Value in H8; auto.\n      apply Property_ran in H7; apply Property_ran in H8.\n      double H0; double H1; apply Theorem88 in H11; destruct H11.\n      unfold WellOrdered in H1; destruct H1 as [H1 _].\n      unfold Connect in H1; specialize H1 with f [u] f [v].\n      unfold WellOrdered in H0; destruct H0.\n      unfold Connect in H0; specialize H0 with u v.\n      destruct H0 as [H0 | [H0 | H0]]; try split; auto.\n      + assert (Rrelation f [u] s f [v]); try apply H2; try tauto.\n        rewrite H9 in H14; generalize (Property_Asy _ _ _ H12 H8).\n        intro; contradiction.\n      + assert (Rrelation f [v] s f [u]); try apply H2; try tauto.\n        rewrite H9 in H14; generalize (Property_Asy _ _ _ H12 H8).\n        intro; contradiction. }\n  split; auto.\n  - unfold Function1_1 in H3; destruct H3 as [_ H3]; unfold Order_Pr; intros.\n    repeat rewrite <- Lemma96; repeat rewrite <- Lemma96'; split; auto.\n    split; auto; split; intros; auto; destruct H4, H5.\n    assert ((f⁻¹) [u] ∈ dom(f)); try apply Lemma96''; auto.\n    assert ((f⁻¹) [v] ∈ dom(f)); try apply Lemma96''; auto.\n    unfold WellOrdered in H0; destruct H0 as [H0 _]; unfold Connect in H0.\n    specialize H0 with (f⁻¹) [u] (f⁻¹) [v].\n    destruct H0 as [H0 | [H0 | H0]]; try split; auto.\n    + assert (Rrelation f  [(f⁻¹) [v]] s f [(f⁻¹) [u]] ); auto.\n      rewrite <- Lemma96''' in H9; rewrite <- Lemma96''' in H9; auto.\n      apply Theorem88 in H1; destruct H1; unfold Asymmetric in H10.\n      generalize (Lemma_xy _ _ H5 (Lemma_xy _ _ H4 H9)); intro.\n      generalize (H10 _ _ H11); intro; contradiction.\n    + assert (f [(f⁻¹) [u]] = f [(f⁻¹) [v]]); rewrite H0; auto.\n      rewrite <- Lemma96''' in H9; rewrite <- Lemma96''' in H9; auto.\n      apply Theorem88 in H1; destruct H1.\n      rewrite H9 in H6; apply Property_Asy with (r:=s) in H5; tauto.\nQed.\n\nHint Resolve Theorem96 : set.\n\n\n(* 97 Theorem  If f and g are r-s order preserving, domain f and domain g are\n   r-sections of x and range f and range g are s-sections of y, then f⊂g or\n   g⊂f. *)\n\nLemma Lemma97 : forall y r x,\n  WellOrdered r x -> y ⊂ x -> WellOrdered r y.\nProof.\n  intros; unfold WellOrdered in H; destruct H.\n  unfold WellOrdered; intros; split; intros.\n  - red; intros.\n    apply H; destruct H2; split; auto.\n  - specialize H1 with y0.\n    apply H1; destruct H2.\n    split; auto; eapply Theorem28; eauto.\nQed.\n\nLemma Lemma97' :  forall f g u r s v x y,\n  Order_Pr f r s /\\ Order_Pr g r s -> \n  FirstMember u r (\\{ λ a ,a ∈ (dom( f) ∩ dom( g)) /\\ f [a] ≠ g [a] \\}) ->\n  g[v] ∈ ran( g) -> Section ran( f) s y -> Section dom( f) r x -> \n  Section dom( g) r x -> Rrelation g [v] s g [u] -> \n  f[u] = g[v] -> f ⊂ g \\/ g ⊂ f.\nProof.\n  intros.\n  unfold FirstMember in H0; destruct H0.\n  apply Axiom_Scheme in H0; destruct H0, H8.\n  apply Axiom_Scheme in H8; destruct H8 as [_ [H8 H10]].\n  destruct H; unfold Order_Pr in H, H11.\n  apply Property_Value in H8; apply Property_Value in H10; try tauto.\n  apply Property_ran in H8; apply Property_ran in H10; auto.\n  assert (Rrelation v r u).\n  { elim H11; intros; clear H13.\n    apply Theorem96 in H11; destruct H11 as [_ H11].\n    red in H11; destruct H11 as [H11 [_ [_ H13]]].\n    double H1; double H10; rewrite Lemma96' in H14, H15.\n    apply Property_Value' in H10; auto; apply Property_dom in H10.\n    rewrite Lemma96 in H10; apply Property_Value' in H1; auto.\n    apply Property_dom in H1; rewrite Lemma96 in H1.\n    rewrite Lemma96''' with (f:=g⁻¹); try (rewrite Theorem61; apply H12); auto.\n    pattern v; rewrite Lemma96''' with (f:=(g⁻¹));\n    try rewrite Theorem61; try apply H11; try apply H12; auto. }\n  assert (v ∈ \\{ λ a, a ∈ (dom(f) ∩ dom(g)) /\\ f [a] ≠ g [a] \\}).\n  { apply Property_Value' in H1; try tauto; apply Property_dom in H1.\n    apply Property_Value' in H8; try tauto; apply Property_dom in H8.\n    apply Axiom_Scheme; repeat split; try Ens.\n    - apply Axiom_Scheme; repeat split; try Ens.\n      apply H3 with u; repeat split; auto.\n      unfold Section in H4; apply H4; auto.\n    - intro.\n      assert (v ∈ dom(f)).\n      { apply H3 with u; repeat split; auto; apply H4 in H1; auto. }\n      assert (Rrelation f [v] s f [u]).\n      { apply H; repeat split; auto. }\n      rewrite H13 in H15; unfold Section in H2; destruct H2, H16.\n      generalize (Lemma97 _ _ _ H16 H2); intro.\n      apply Theorem88 in H18; destruct H18.\n      rewrite <- H13 in H15; rewrite H6 in H15; rewrite <- H13 in H15.\n      apply Property_Value in H14; try tauto; apply Property_ran in H14.\n      generalize (Property_Asy _ _ _ H19 H14); intro; contradiction. }\n  apply H7 in H13; contradiction.\nQed.\n\nLemma Lemma97'' : forall f g,\n  \\{ λ a, a ∈ (dom(f) ∩ dom(g)) /\\ f[a] ≠ g[a] \\} =\n  \\{ λ a, a ∈ (dom(g) ∩ dom(f)) /\\ g[a] ≠ f[a] \\}.\nProof.\n  intros.\n  apply Axiom_Extent; split; intros; rewrite Theorem6'; apply Axiom_Scheme in H;\n  apply Axiom_Scheme; repeat split; try tauto; apply Property_Ineq; tauto.\nQed.\n\nLemma Lemma97''' : forall f g,\n  f ⊂ g \\/ g ⊂ f <-> g ⊂ f \\/ f ⊂ g.\nProof.\n  intros; split; intros; destruct H; tauto.\nQed.\n\nTheorem Theorem97 : forall f g r s x y,\n  Order_Pr f r s /\\ Order_Pr g r s -> \n  Section dom(f) r x /\\ Section dom(g) r x -> \n  Section ran(f) s y /\\ Section ran(g) s y -> f ⊂ g \\/ g ⊂ f.\nProof.\n  intros; destruct H, H0, H1.\n  assert (Order_Pr (g ⁻¹) s r).\n  { apply Theorem96 in H2; tauto. }\n  generalize (classic (\\{ λ a, a ∈ (dom(f) ∩ dom(g)) /\\ f[a] ≠ g[a] \\} = Φ)).\n  intro; destruct H6.\n  - generalize (Lemma_xy _ _ H0 H3); intro.\n    unfold Order_Pr in H; destruct H; unfold Order_Pr in H2; destruct H2.\n    generalize (Theorem92 _ _ _ _ H7); intro; destruct H10.\n    + left; unfold Subclass; intros.\n      rewrite Theorem70 in H11; auto; PP H11 a b; double H12.\n      rewrite <- Theorem70 in H12; auto; apply Property_dom in H12.\n      apply Axiom_SchemeP in H13; destruct H13.\n      rewrite Theorem70; auto; apply Axiom_SchemeP; split; auto; rewrite H14.\n      generalize (classic (f[a] = g[a])); intro; destruct H15; auto.\n      assert (a ∈ \\{ λ a, a ∈ (dom( f) ∩ dom( g)) /\\ f [a] ≠ g [a] \\}).\n      { apply Axiom_Scheme; split; Ens; split; auto.\n        apply Theorem30 in H10; rewrite H10; auto. }\n      eapply Axiom_Extent in H6; apply H6 in H16.\n      generalize (Theorem16 a); contradiction.\n    + right; unfold Subclass; intros.\n      rewrite Theorem70 in H11; auto; PP H11 a b; double H12.\n      rewrite <- Theorem70 in H12; auto; apply Property_dom in H12.\n      apply Axiom_SchemeP in H13; destruct H13.\n      rewrite Theorem70; auto; apply Axiom_SchemeP; split; auto; rewrite H14.\n      generalize (classic (f[a] = g[a])); intro; destruct H15; auto.\n      assert (a ∈ \\{ λ a, a ∈ (dom( f) ∩ dom( g)) /\\ f [a] ≠ g [a] \\}).\n      { apply Axiom_Scheme; split; Ens; split; auto. apply Theorem30 in H10.\n        rewrite Theorem6' in H10; rewrite H10; auto. }\n      eapply Axiom_Extent in H6; apply H6 in H16.\n      generalize (Theorem16 a); contradiction.\n  - assert (\\{ λ a, a ∈ (dom( f) ∩ dom( g)) /\\ f [a] ≠ g [a] \\} ⊂ dom(f)).\n    { unfold Subclass; intros; apply Axiom_Scheme in H7; destruct H7, H8.\n      apply Theorem4' in H8; tauto. }\n    double H2; double H; unfold Order_Pr in H9; destruct H9, H10, H11.\n    unfold WellOrdered in H10; destruct H10.\n    generalize (Lemma_xy _ _ H7 H6); intro.\n    apply H13 in H14; destruct H14 as [u H14].\n    double H14; unfold FirstMember in H15; destruct H15.\n    apply Axiom_Scheme in H15; destruct H15, H17.\n    unfold Order_Pr in H2; destruct H2 as [H19 [_ [H2 _]]].\n    apply Axiom_Scheme in H17; destruct H17 as [_ [H17 H20]].\n    double H17; double H20.\n    apply Property_Value in H17; apply Property_Value in H20; auto.\n    apply Property_ran in H17; apply Property_ran in H20.\n    generalize (Lemma_xy _ _ H1 H4); intro.\n    apply Theorem92 in H23; auto; destruct H23.\n    + apply H23 in H17; double H17.\n      apply Axiom_Scheme in H17; destruct H17 as [_ [v H17]].\n      rewrite Theorem70 in H17; auto; apply Axiom_SchemeP in H17.\n      destruct H17; rewrite H25 in H24.\n      generalize (Lemma_xy _ _ H24 H20); intro.\n      unfold WellOrdered in H2; destruct H2 as [H2 _].\n      unfold Connect in H2; apply H2 in H26.\n      destruct H26 as [H26 | [H26 | H26]].\n      * apply (Lemma97' f g u r s v x y); auto.\n      * rewrite <- H25 in H26.\n        assert (g [u] ∈ ran( f)).\n        { unfold Section in H4; apply H4 in H20.\n          unfold Section in H1; apply H1 with f[u]; repeat split; auto.\n          apply Property_ran with u; apply Property_Value; auto. }\n        double H27; apply Axiom_Scheme in H27; destruct H27 as [_ [v1 H27]].\n        rewrite Theorem70 in H27; auto.\n        apply Axiom_SchemeP in H27; destruct H27 as [_H27].\n        rewrite H27 in H26, H28; rewrite Lemma97'' in H14; apply Lemma97'''.\n        apply (Lemma97' g f u r s v1 x y); try tauto.\n      * rewrite H26 in H25; contradiction.\n    + apply H23 in H20; double H20.\n      apply Axiom_Scheme in H20; destruct H20 as [_ [v H20]].\n      rewrite Theorem70 in H20; auto.\n      apply Axiom_SchemeP in H20; destruct H20; rewrite H25 in H24.\n      generalize (Lemma_xy _ _ H17 H24); intro.\n      unfold WellOrdered in H11; destruct H11 as [H11 _].\n      unfold Connect in H11; apply H11 in H26.\n      destruct H26 as [H26 | [H26 | H26]]; try contradiction.\n      * rewrite <- H25 in H26.\n        assert (f [u] ∈ ran( g)).\n        { unfold Section in H1; apply H1 in H17.\n          unfold Section in H4; eapply H4; repeat split; eauto.\n          apply Property_ran with u; apply Property_Value; auto. }\n        double H27; apply Axiom_Scheme in H27; destruct H27 as [_ [v1 H27]].\n        rewrite Theorem70 in H27; auto; apply Axiom_SchemeP in H27.\n        destruct H27 as [_H27]; rewrite H27 in H26, H28.\n        apply (Lemma97' f g u r s v1 x y); try tauto.\n      * rewrite Lemma97'' in H14; apply Lemma97'''.\n        apply (Lemma97' g f u r s v x y); try tauto.\n      * rewrite <- H25 in H26; contradiction.\nQed.\n\nHint Resolve Theorem97 : set.\n\n\n(* 98 Definition  f is r-s order preserving in x and y if and only if r\n   well-orders x, s well-orders y, f is r-s order preserving, domain f is an\n   r-section of x, and range f is an s-section of y. *)\n\nDefinition Order_PXY f x y r s : Prop :=\n  WellOrdered r x /\\ WellOrdered s y /\\ Order_Pr f r s /\\\n  Section dom(f) r x /\\ Section ran(f) s y.\n\nHint Unfold Order_PXY : set.\n\n\n(* 99 Theorem  If r well-orders x and s well-orders y, then there is a function\n   f which is r-s order preserving in x and y such that either domain f = x or\n   range f = y. *)\n\nDefinition En_f x y r s := \n  \\{\\ λ u v, u ∈ x /\\ (exists g, Function g /\\ Order_PXY g x y r s /\\\n  u ∈ dom(g) /\\ [u,v] ∈ g ) \\}\\.\n\nLemma Lemma99 : forall y r x,\n  WellOrdered r x -> Section y r x -> WellOrdered r y.\nProof.\n  intros; red in H0; eapply Lemma97; eauto; tauto.\nQed.\n\nLemma Lemma99' : forall a b f z,\n  ~ a ∈ dom(f) -> Ensemble a -> Ensemble b ->\n  (z ∈ dom(f) -> (f ∪ [[a,b]]) [z] = f [z]).\nProof.\n  intros; apply Axiom_Extent; split; intros; apply Axiom_Scheme in H3; destruct H3;\n  apply Axiom_Scheme; split; intros; auto.\n  - apply H4; apply Axiom_Scheme in H5; destruct H5; apply Axiom_Scheme; split; auto.\n    apply Axiom_Scheme; split; Ens.\n  - apply H4; apply Axiom_Scheme in H5; destruct H5.\n    apply Axiom_Scheme in H6; destruct H6, H7; apply Axiom_Scheme; auto.\n    assert ([a, b] ∈ μ). { apply Theorem19; apply Theorem49; tauto. }\n    apply Axiom_Scheme in H7; destruct H7; apply H9 in H8.\n    apply Theorem55 in H8; destruct H8; Ens.\n    rewrite H8 in H2; contradiction.\nQed.\n\nLemma Lemma99'' : forall a b f z,\n  ~ a ∈ dom(f) -> Ensemble a -> Ensemble b ->\n  (z=a -> (f ∪ [[a,b]]) [z] = b).\nProof.\n  intros; apply Axiom_Extent; split; intros; subst z.\n  - apply Axiom_Scheme in H3; destruct H3; apply H3; apply Axiom_Scheme; split; auto.\n    apply Axiom_Scheme; split; try apply Theorem49; try tauto.\n    right; apply Axiom_Scheme; split; try apply Theorem49; try tauto.\n  - apply Axiom_Scheme; split; intros; Ens.\n    apply Axiom_Scheme in H2; destruct H2; apply Axiom_Scheme in H4; destruct H4, H5.\n    + apply Property_dom in H5; contradiction.\n    + apply Axiom_Scheme in H5; destruct H5.\n      assert ([a, b] ∈ μ). { apply Theorem19; apply Theorem49; tauto. }\n      generalize (H6 H7); intro; apply Theorem55 in H8;\n      apply Theorem49 in H4; auto; destruct H8; rewrite H9; auto.\nQed.\n\nLemma Lemma99''' : forall y r x a b,  \n  Section y r x -> a ∈ y -> ~ b ∈ y -> b ∈ x -> Rrelation a r b.\nProof.\n  intros; unfold Section in H; destruct H, H3.\n  unfold WellOrdered in H3; destruct H3; unfold Connect in H3.\n  assert (a ∈ x); auto; generalize (Lemma_xy _ _ H2 H6); intro.\n  apply H3 in H7; destruct H7 as [H7 | [H7 | H7]]; auto.\n  - assert (b ∈ y). { eapply H4; eauto. } contradiction.\n  - rewrite H7 in H1; contradiction.\nQed.\n\nTheorem Theorem99 : forall r s x y,\n  WellOrdered r x /\\ WellOrdered s y ->\n  exists f, Function f /\\ Order_PXY f x y r s /\\((dom(f) = x) \\/ (ran(f) = y)).\nProof.\n  intros.\n  assert (Function (En_f x y r s)).\n  { unfold Function; split; intros.\n    - unfold Relation; intros; PP H0 a b; eauto.\n    - destruct H0; apply Axiom_SchemeP in H0; destruct H0, H2, H3, H3, H4, H5.\n      unfold Order_PXY in H4; destruct H4 as [_ [_ [H4 [H7 H8]]]].\n      apply Axiom_SchemeP in H1; destruct H1, H9, H10, H10, H11, H12.\n      unfold Order_PXY in H11; destruct H11 as [_ [_ [H11 [H14 H15]]]].\n      assert (x1 ⊂ x2 \\/ x2 ⊂ x1). { apply (Theorem97 x1 x2 r s x y); tauto. }\n      destruct H16.\n      + apply H16 in H6; eapply H10; eauto.\n      + apply H16 in H13; eapply H3; eauto. }\n  exists (En_f x y r s); split; auto.\n  assert (Section (dom(En_f x y r s)) r x).\n  { unfold Section; split.\n    - unfold Subclass; intros; apply Axiom_Scheme in H1; destruct H1, H2.\n      apply Axiom_SchemeP in H2; tauto.\n    - split; try tauto; intros; destruct H1, H2.\n      apply Axiom_Scheme in H2; destruct H2, H4.\n      apply Axiom_SchemeP in H4; destruct H4, H5, H6; apply Axiom_Scheme; split; Ens.\n      exists ((En_f x y r s)[u]); apply Property_Value; auto.\n      apply Axiom_Scheme; split; Ens.\n      assert (u ∈ dom( x1)).\n      { destruct H6, H7; unfold Order_PXY in H7; destruct H7, H9, H10, H11.\n        unfold Section in H11; destruct H11, H13; apply H14 with v.\n        destruct H8; tauto. }\n      exists (x1[u]); apply Axiom_SchemeP; repeat split; auto.\n      + apply Theorem49; split; Ens.\n        apply Theorem19; apply Theorem69; try tauto.\n      + exists x1; split; try tauto; split; try tauto; split; auto.\n        apply Property_Value; try tauto. }\n  assert (Section (ran(En_f x y r s)) s y).\n  { unfold Section; split.\n    - unfold Subclass; intros; apply Axiom_Scheme in H2; destruct H2, H3.\n      apply Axiom_SchemeP in H3; destruct H3, H4, H5, H5, H6, H7.\n      unfold Order_PXY in H6; destruct H6 as [_ [_ [_ [_ H6]]]].\n      unfold Section in H6; destruct H6 as [H6 _].\n      apply Property_ran in H8; auto.\n    - split; try tauto; intros; destruct H2, H3.\n      apply Axiom_Scheme in H3; destruct H3, H5.\n      apply Axiom_SchemeP in H5; destruct H5, H6, H7.\n      apply Axiom_Scheme; split; Ens; exists (x1⁻¹[u]).\n      apply Axiom_SchemeP; destruct H7 as [H7 [H8 [H9 H10]]]; double H8.\n      unfold Order_PXY in H8; destruct H8 as [_ [_ [H12 [H13 H8]]]].\n      generalize H11 as H20; intro.\n      unfold Order_PXY in H11; destruct H11 as [H11 [_ H19]].\n      unfold Section in H8; destruct H8 as [H8 [_ H15]].\n      assert (u ∈ ran( x1)).\n      { apply Property_ran in H10; apply H15 with v; tauto. }\n      generalize H14 as H21; intro; apply Theorem96 in H12; destruct H12.\n      unfold Function1_1 in H12; destruct H12; apply Lemma96'' in H14; auto.\n      repeat split; auto.\n      + apply Theorem49; split; Ens.\n      + apply Property_Value in H14; auto. rewrite <- Lemma96''' in H14; auto.\n        apply Property_dom in H14; destruct H19 as [_ [[H19 _] _]]; auto.\n      + exists x1; split; try tauto; split; try tauto; split; auto.\n        apply Property_Value in H14; auto; rewrite <- Lemma96''' in H14; auto. }\n  assert (Order_PXY (En_f x y r s) x y r s).\n  { unfold Order_PXY; split; try tauto; split; try tauto.\n    split; [idtac | tauto]; unfold Order_Pr; split; auto.\n    destruct H; split; try eapply Lemma99; eauto.\n    split; intros; try eapply Lemma99; eauto.\n    destruct H4, H5; double H4; double H5.\n    apply Property_Value in H4; apply Property_Value in H5; auto.\n    apply Axiom_SchemeP in H4; apply Axiom_SchemeP in H5.\n    destruct H4 as [H4 [H9 [g1 [H10 [H11 [H12 H13]]]]]].\n    destruct H5 as [H5 [H14 [g2 [H15 [H16 [H17 H18]]]]]].\n    rewrite Theorem70 in H13; rewrite Theorem70 in H18; auto.\n    apply Axiom_SchemeP in H13; destruct H13 as [_ H13].\n    apply Axiom_SchemeP in H18; destruct H18 as [_ H18].\n    rewrite H13, H18; clear H13 H18.\n    unfold Order_PXY in H11; destruct H11 as [_ [_ [H11 [H13 H18]]]].\n    unfold Order_PXY in H16; destruct H16 as [_ [_ [H16 [H19 H20]]]].\n    generalize (Lemma_xy _ _ H11 H16); intro.\n    apply (Theorem97 g1 g2 r s x y) in H21; auto.\n    apply Property_Value in H12; apply Property_Value in H17; auto.\n    destruct H21.\n    - apply H21 in H12; double H12; rewrite Theorem70 in H12; auto.\n      apply Axiom_SchemeP in H12; destruct H12 as [_ H12]; rewrite H12.\n      apply Property_dom in H22; apply Property_dom in H17; apply H16; tauto.\n    - apply H21 in H17; double H17; rewrite Theorem70 in H17; auto.\n      apply Axiom_SchemeP in H17; destruct H17 as [_ H17]; rewrite H17.\n      apply Property_dom in H12; apply Property_dom in H22; apply H11; tauto. }\n  split; auto; apply NNPP; intro; apply not_or_and in H4; destruct H4.\n  assert (exists u, FirstMember u r (x ~ dom( En_f x y r s))).\n  { unfold Section in H1; destruct H1, H6.\n    assert ((x ~ dom( En_f x y r s)) ⊂ x).\n    { red; intros; apply Axiom_Scheme in H8; tauto. }\n    assert ((x ~ dom( En_f x y r s)) <> Φ).\n    { intro; apply Property_Φ in H1; apply H1 in H9; apply H4; auto. }\n    generalize (Lemma97 _ _ _ H6 H8); intro.\n    apply H10; repeat split; auto; red; auto. }\n  assert (exists v, FirstMember v s (y ~ ran( En_f x y r s))).\n  { unfold Section in H2; destruct H2, H7.\n    assert ((y ~ ran( En_f x y r s)) ⊂ y).\n    { red; intros; apply Axiom_Scheme in H9; tauto. }\n    assert ((y ~ ran( En_f x y r s)) <> Φ).\n    { intro; apply Property_Φ in H2; apply H2 in H10; apply H5; auto. }\n    generalize (Lemma97 _ _ _ H7 H9); intro.\n    apply H11; repeat split; auto; red; auto. }\n  destruct H6 as [u H6]; destruct H7 as [v H7].\n  unfold FirstMember in H6; unfold FirstMember in H7; destruct H6, H7.\n  apply Axiom_Scheme in H6; destruct H6 as [_ [H6 H10]].\n  apply Axiom_Scheme in H10; destruct H10 as [_ H10].\n  apply H10; apply Axiom_Scheme; split; Ens.\n  exists v; apply Axiom_SchemeP.\n  split; try apply Theorem49; split; try Ens.\n  exists ((En_f x y r s) ∪ [[u,v]]).\n  assert (Function (En_f x y r s ∪ [[u, v]])).\n  { assert ([u, v] ∈ μ) as H18.\n    { apply Theorem19; apply Theorem49; split; try Ens. }\n    unfold Function; split; intros.\n    - unfold Relation; intros.\n      apply Axiom_Scheme in H11; destruct H11 as [H11 [H12 | H12]].\n      + PP H12 a b; eauto.\n      + apply Axiom_Scheme in H12; exists u,v; apply H12; auto.\n    - destruct H11; apply Axiom_Scheme in H11; apply Axiom_Scheme in H12.\n      destruct H11 as [H11 [H13 | H13]], H12 as [H12 [H14 | H14]].\n      + unfold Function in H0; eapply H0; eauto.\n      + apply Property_dom in H13; apply Axiom_Scheme in H14; destruct H14.\n        apply Theorem55 in H15; apply Theorem49 in H12; auto.\n        destruct H15; rewrite H15 in H13; contradiction.\n      + apply Property_dom in H14; apply Axiom_Scheme in H13; destruct H13.\n        apply Theorem55 in H15; apply Theorem49 in H11; auto.\n        destruct H15; rewrite H15 in H14; contradiction.\n      + apply Axiom_Scheme in H13; destruct H13; apply Theorem55 in H15;\n        apply Theorem49 in H13; auto.\n        apply Axiom_Scheme in H14; destruct H14; apply Theorem55 in H16; \n        apply Theorem49 in H12; auto.\n        destruct H15, H16; rewrite H17; auto. }\n  split; auto.\n  assert (Section (dom(En_f x y r s ∪ [[u, v]])) r x).\n  { unfold Section; split.\n    - unfold Subclass; intros; apply Axiom_Scheme in H12; destruct H12, H13.\n      apply Axiom_Scheme in H13; destruct H13, H14.\n      + apply Property_dom in H14; unfold Section in H1; apply H1; auto.\n      + apply Axiom_Scheme in H14; destruct H14.\n        assert ([u, v] ∈ μ).\n        { apply Theorem19; apply Theorem49; split; try Ens. }\n        apply H15 in H16; apply Theorem55 in H16; apply Theorem49 in H13; auto.\n        destruct H16; rewrite H16; auto.\n    - split; try tauto; intros; destruct H12, H13.\n      apply Axiom_Scheme in H13; destruct H13, H15.\n      apply Axiom_Scheme in H15; destruct H15, H16.\n      + apply Axiom_Scheme; split; Ens.\n        assert ([u0, (En_f x y r s) [u0]] ∈ (En_f x y r s)).\n        { apply Property_dom in H16; apply Property_Value; auto.\n          apply H1 with v0; repeat split; auto. }\n        exists (En_f x y r s) [u0]; apply Axiom_Scheme; split; Ens.\n      + apply Axiom_Scheme in H16; destruct H16.\n        assert ([u,v] ∈ μ). { apply Theorem19; apply Theorem49; split; Ens. }\n        apply H17 in H18; apply Theorem55 in H18;\n        apply Theorem49 in H16; auto; destruct H18; subst v0.\n        assert ([u0, (En_f x y r s) [u0]] ∈ (En_f x y r s)).\n        { apply Property_Value; auto.\n          generalize (classic (u0 ∈ dom( En_f x y r s))); intro.\n          destruct H18; auto; absurd (Rrelation u0 r u); auto.\n          apply H8; apply Axiom_Scheme; repeat split; Ens.\n          apply Axiom_Scheme; split; Ens. }\n        apply Axiom_Scheme; split; Ens.\n        exists ((En_f x y r s)[u0]); apply Axiom_Scheme; split; Ens. }\n  assert (Section (ran(En_f x y r s ∪ [[u, v]])) s y).\n  { unfold Section; split.\n    - unfold Subclass; intros; apply Axiom_Scheme in H13; destruct H13, H14.\n      apply Axiom_Scheme in H7; destruct H7 as [_ [H7 _]] .\n      apply Axiom_Scheme in H14; destruct H14, H15.\n      + apply Property_ran in H15; unfold Section in H2; apply H2; auto.\n      + apply Axiom_Scheme in H15; destruct H15.\n        assert ([u, v] ∈ μ).\n        { apply Theorem19; apply Theorem49; split; try Ens. }\n        apply H16 in H17; apply Theorem55 in H17;\n        apply Theorem49 in H14; auto; destruct H17; rewrite H18; auto.\n    - split; try tauto; intros; destruct H13, H14.\n      apply Axiom_Scheme in H14; destruct H14, H16.\n      unfold Order_PXY in H3; destruct H3 as [_ [_ [H3 _]]].\n      apply Theorem96 in H3; destruct H3 as [[_ H3] _].\n      apply Axiom_Scheme in H16; destruct H16, H17.\n      + apply Axiom_Scheme; split; Ens.\n        assert ([((En_f x y r s) ⁻¹) [u0], u0] ∈ (En_f x y r s)).\n        { assert (u0 ∈ ran( En_f x y r s)).\n          { apply Property_ran in H17; apply H2 with v0; repeat split; auto. }\n          pattern u0 at 2; rewrite Lemma96''' with (f:=(En_f x y r s)); auto.\n          apply Property_Value'; auto; rewrite <- Lemma96'''; auto. }\n        exists ((En_f x y r s) ⁻¹) [u0]; apply Axiom_Scheme; split; Ens.\n      + apply Axiom_Scheme in H17; destruct H17.\n        assert ([u,v] ∈ μ). { apply Theorem19; apply Theorem49; split; Ens. }\n        apply H18 in H19; apply Theorem55 in H19;\n        apply Theorem49 in H16; auto; destruct H19; subst v0.\n        assert ([((En_f x y r s) ⁻¹) [u0], u0] ∈ (En_f x y r s)).\n        { generalize (classic (u0 ∈ ran( En_f x y r s))); intro; destruct H20.\n          - pattern u0 at 2; rewrite Lemma96''' with (f:=(En_f x y r s)); auto.\n            apply Property_Value'; auto; rewrite <- Lemma96'''; auto.\n          - absurd (Rrelation u0 s v); auto.\n            apply H9; apply Axiom_Scheme; repeat split; Ens.\n            apply Axiom_Scheme; split; Ens. }\n        apply Axiom_Scheme; split; Ens.\n        exists ((En_f x y r s) ⁻¹) [u0]; apply Axiom_Scheme; split; Ens. }\n  split.\n  - unfold Order_PXY; split; try tauto.\n    split; try tauto; split; [idtac | tauto].\n    unfold Order_Pr; intros; split; auto.\n    split; try eapply Lemma99; eauto; try apply H.\n    split; try eapply Lemma99; eauto; try apply H; intros.\n    destruct H14, H15; apply Axiom_Scheme in H14; destruct H14, H17.\n    apply Axiom_Scheme in H17; destruct H17 as [_ H17].\n    apply Axiom_Scheme in H15; destruct H15, H18.\n    apply Axiom_Scheme in H18; destruct H18 as [_ H18].\n    assert ([u,v] ∈ μ) as H20.\n    { apply Theorem19; apply Theorem49; split; Ens. }\n    destruct H17, H18.\n    + apply Property_dom in H17; apply Property_dom in H18;\n      repeat rewrite Lemma99'; auto; Ens.\n      unfold Order_PXY in H3; destruct H3 as [_ [_ [H3 _]]].\n      unfold Order_Pr in H3; eapply H3; eauto.\n    + apply Property_dom in H17; rewrite Lemma99'; auto; Ens.\n      apply Axiom_Scheme in H18; destruct H18.\n      apply H19 in H20;  apply Theorem55 in H20; destruct H20;\n      apply Theorem49 in H18; auto; rewrite Lemma99''; auto; Ens.\n      apply Lemma99''' with (y:=(ran( En_f x y r s))) (x:=y); auto.\n      * apply Property_Value in H17; auto.\n        double H17; apply Property_ran in H17.\n        apply Axiom_Scheme; split; Ens; exists u0; apply Axiom_Scheme; split; Ens.\n      * apply Axiom_Scheme in H7; destruct H7, H22; apply Axiom_Scheme in H23; tauto.\n      * apply Axiom_Scheme in H7; tauto.\n    + apply Property_dom in H18.\n      pattern ((En_f x y r s ∪ [[u, v]]) [v0]); rewrite Lemma99'; Ens.\n      assert (u0 ∈ dom( En_f x y r s)).\n      { unfold Section in H1; apply H1 with v0; split; auto.\n        apply Axiom_Scheme in H17; destruct H17; apply H19 in H20.\n        apply Theorem55 in H20; apply Theorem49 in H17; auto.\n        destruct H20; rewrite H20; auto. }\n      rewrite Lemma99'; Ens; unfold Order_PXY in H3.\n      destruct H3 as [_ [_ [H3 _]]]; unfold Order_Pr in H3; eapply H3; eauto.\n    + double H20; apply Axiom_Scheme in H17; destruct H17; apply H21 in H19.\n      apply Axiom_Scheme in H18; destruct H18; apply H22 in H20.\n      apply Theorem55 in H20; destruct H20; apply Theorem49 in H18; auto.\n      apply Theorem55 in H19; destruct H19; apply Theorem49 in H17; auto.\n      subst u0 v0; destruct H as [H _]; apply Theorem88 in H.\n      destruct H as [_ H]; apply Property_Asy with (u:=u) in H; auto.\n      contradiction.\n  - assert (Ensemble ([u,v])). { apply Theorem49; split; Ens. } split.\n    + apply Axiom_Scheme; split; Ens; exists v; apply Axiom_Scheme; split; Ens.\n      right; apply Axiom_Scheme; split; auto.\n    + apply Axiom_Scheme; split; Ens; right; apply Axiom_Scheme; split; auto.\nQed.\n\nHint Resolve Theorem99 : set.\n\n\n(* 100 Theorem  If r well-orders x, s well-orders y, x is a set, and y is not\n   a set, then there is a unique r-s order-preserving function in x and y whose\n   domain is x. *)\n\nTheorem Theorem100 : forall r s x y,\n  WellOrdered r x /\\ WellOrdered s y -> Ensemble x -> ~ Ensemble y ->\n  exists f, Function f /\\ Order_PXY f x y r s /\\ dom( f) = x.\nProof.\n  intros; destruct H.\n  generalize (Lemma_xy _ _ H H2); intro.\n  apply Theorem99 in H3; destruct H3, H3, H4.\n  exists x0; split; auto; split; auto; destruct H5; auto.\n  unfold Order_PXY in H4; destruct H4 as [_ [_ [_ [H4 _]]]].\n  unfold Section in H4; destruct H4; apply Theorem33 in H4; auto.\n  apply Axiom_Substitution in H4; auto; rewrite H5 in H4; contradiction.\nQed.\n\nTheorem Theorem100' : forall r s x y,\n  WellOrdered r x /\\ WellOrdered s y -> Ensemble x -> ~ Ensemble y ->\n  forall f, Function f /\\ Order_PXY f x y r s /\\ dom(f) = x ->\n  forall g, Function g /\\ Order_PXY g x y r s /\\ dom(g) = x -> f = g.\nProof.\n  intros; destruct H, H2, H5, H3, H7; unfold Order_PXY in H5, H7.\n  destruct H5 as [_ [_ H5]], H5, H9, H7 as [_ [_ H7]], H7, H11.\n  generalize (Lemma_xy _ _ H5 H7); intro.\n  apply (Theorem97 f g r s x y) in H13; auto; destruct H13.\n  - apply Theorem27; split; auto; unfold Subclass; intros.\n    rewrite Theorem70; rewrite Theorem70 in H14; auto.\n    PP H14 a b; double H15; rewrite <- Theorem70 in H15; auto.\n    apply Axiom_SchemeP in H16; destruct H16.\n    apply Axiom_SchemeP; split; auto; rewrite H17 in *.\n    assert ([a,f[a]] ∈ f).\n    { apply Property_Value; auto; subst x.\n      apply Property_dom in H15; rewrite <- H8; auto. }\n    apply H13 in H18; eapply H3; eauto.\n  - apply Theorem27; split; auto; unfold Subclass; intros.\n    rewrite Theorem70; rewrite Theorem70 in H14; auto.\n    PP H14 a b; double H15; rewrite <- Theorem70 in H15; auto.\n    apply Axiom_SchemeP in H16; destruct H16.\n    apply Axiom_SchemeP; split; auto; rewrite H17 in *.\n    assert ([a,g[a]] ∈ g).\n    { apply Property_Value; auto; subst x.\n      apply Property_dom in H15; rewrite H8; auto. }\n    apply H13 in H18; eapply H2; eauto.\nQed.\n\nHint Resolve Theorem100 Theorem100' : set.\n\n\n(* ORDINALS *)\n\n(* VII Axiom of regularity : If x ≠ Φ there is a member y of x such x∩y = Φ. *)\n\nAxiom Axiom_Regularity : forall x, x ≠ Φ -> exists y, y ∈ x /\\ x ∩ y = Φ.\n\nHint Resolve Axiom_Regularity : set.\n\n\n(* 101 Theorem101  x ∉ x. *)\n\nTheorem Theorem101 : forall x, x ∉ x.\nProof.\n  intros; intro.\n  assert ([x] ≠ Φ).\n  { apply Lemma35; exists x; apply Axiom_Scheme; split; Ens. }\n  apply Axiom_Regularity in H0; destruct H0, H0.\n  assert (x0 = x).\n  { apply Axiom_Scheme in H0; destruct H0; apply H2; apply Theorem19; Ens. }\n  subst x0; assert (x ∈ ([x] ∩ x)). { apply Axiom_Scheme; repeat split; Ens. }\n  rewrite H1 in H2; generalize (Theorem16 x); intro; contradiction.\nQed.\n\nHint Resolve Theorem101 : set.\n\n\n(* 102 Theorem  It is false that x∈y and y∈x. *)\n\nTheorem Theorem102 : forall x y, ~ (x ∈ y /\\ y ∈ x).\nProof.\n  intros; intro; destruct H.\n  assert (\\{ λ z, z = x \\/ z =y \\} ≠ Φ).\n  { apply Lemma35; exists x; apply Axiom_Scheme; split; Ens. }\n  apply Axiom_Regularity in H1; destruct H1, H1; apply Axiom_Scheme in H1.\n  destruct H1, H3; subst x0.\n  + assert (y ∈ (\\{ λ z, z = x \\/ z = y \\} ∩ x)).\n    { apply Axiom_Scheme; repeat split; Ens; apply Axiom_Scheme; split; Ens. }\n    rewrite H2 in H3; generalize (Theorem16 y); intro; contradiction.\n  + assert (x ∈ (\\{ λ z, z = x \\/ z = y \\} ∩ y)).\n    { apply Axiom_Scheme; repeat split; Ens; apply Axiom_Scheme; split; Ens. }\n    rewrite H2 in H3; generalize (Theorem16 x); intro; contradiction.\nQed.\n\nHint Resolve Theorem102 : set.\n\n\n(* 103 Definition  E = { [x,y] : x∈y}. *)\n\nDefinition E : Class := \\{\\ λ x y, x ∈ y \\}\\.\n\nHint Unfold E : set.\n\n\n(* 104 Theorem  E is not a set. *)\n\nLemma Lemma104 : forall a b c, a ∈ b -> b ∈ c -> c ∈ a -> False.\nProof.\n  intros.\n  assert (\\{ λ x, x = a \\/ x =b \\/ x = c \\} ≠ Φ).\n  { apply Lemma35; exists a; apply Axiom_Scheme; split; Ens. }\n  apply Axiom_Regularity in H2; destruct H2, H2; apply Axiom_Scheme in H2; destruct H2.\n  destruct H4 as [H4 | [H4 | H4]]; subst x.\n  + assert (c ∈ (\\{ λ x, x = a \\/ x =b \\/ x = c \\} ∩ a)).\n    { apply Axiom_Scheme; repeat split; Ens; apply Axiom_Scheme; split; Ens. }\n    rewrite H3 in H4; generalize (Theorem16 c); intro; contradiction.\n  + assert (a ∈ (\\{ λ x, x = a \\/ x =b \\/ x = c \\} ∩ b)).\n    { apply Axiom_Scheme; repeat split; Ens; apply Axiom_Scheme; split; Ens. }\n    rewrite H3 in H4; generalize (Theorem16 a); intro; contradiction.\n  + assert (b ∈ (\\{ λ x, x = a \\/ x =b \\/ x = c \\} ∩ c)).\n    { apply Axiom_Scheme; repeat split; Ens; apply Axiom_Scheme; split; Ens. }\n    rewrite H3 in H4; generalize (Theorem16 b); intro; contradiction.\nQed.\n\nTheorem Theorem104 : ~ Ensemble E.\nProof.\n  intro; generalize (Theorem42 _ H); intro.\n  assert (E ∈ [E]). { apply Axiom_Scheme; split; auto. }\n  assert ([E, [E]] ∈ E).\n  { apply Axiom_SchemeP; split; auto; apply Theorem49; tauto. }\n  assert ([E] ∈ [E, [E]]).\n  { apply Axiom_Scheme; split; Ens; left; apply Axiom_Scheme; split; auto. }\n  eapply Lemma104; eauto.\nQed.\n\nHint Resolve Theorem104 : set.\n\n\n(* 105 Definition  x is full iff each member of x is a subset of x. *)\n\nDefinition full x : Prop := forall m, m∈x -> m⊂x.\n\nCorollary Property_Full : forall x, \n  full x <-> (forall u v : Class, v ∈ x /\\ u ∈ v -> u ∈ x).\nProof.\n  intros; split; intros.\n  - unfold full in H; destruct H0; apply H in H0; auto.\n  - unfold full; intros; unfold Subclass; intros; apply H with m; tauto.\nQed.\n\nHint Unfold full : set.\nHint Resolve Property_Full : set.\n\n\n(* 106 Definition  x is an ordinal iff E connects x and x is full. *)\n\nDefinition Ordinal x : Prop := Connect E x /\\ full x.\n\nHint Unfold Ordinal : set.\n\n\n(* 107 Theorem  If x is an ordinal E well-orders x. *)\n\nTheorem Theorem107 : forall x, \n  Ordinal x -> WellOrdered E x.\nProof.\n  intros.\n  unfold Ordinal in H; destruct H; unfold WellOrdered.\n  intros; split; auto; intros; destruct H1.\n  apply Axiom_Regularity in H2; destruct H2, H2.\n  exists x0; unfold FirstMember; intros.\n  split; auto; intros; intro.\n  unfold Rrelation in H5; apply Axiom_SchemeP in H5; destruct H5.\n  assert (y0 ∈ (y ∩ x0)). { apply Axiom_Scheme; split; Ens. }\n  rewrite H3 in H7; generalize (Theorem16 y0); intro; contradiction.\nQed.\n\nHint Resolve Theorem107 : set.\n\n\n(* 108 Theorem  If x is an ordinal, y⊂x, y≠x, and y is full, then y∈x. *)\n\nTheorem Theorem108 : forall x y, \n  Ordinal x -> y ⊂ x -> y≠x -> full y -> y ∈ x.\nProof.\n  intros.\n  assert (Section y E x).\n  { apply Theorem107 in H; unfold Section; intros.\n    split; auto; split; auto; intros; destruct H3, H4.\n    unfold Rrelation in H5; apply Axiom_SchemeP in H5; destruct H5.\n    unfold full in H2; apply H2 in H4; auto. }\n  generalize (Lemma_xy _ _ H3 H1); intro.\n  apply Theorem91 in H4; destruct H4, H4.\n  assert (x0 = \\{ λ u : Class,u ∈ x /\\ Rrelation u E x0 \\}).\n  { apply Axiom_Extent; split; intros; AssE z.\n    - apply Axiom_Scheme; split; auto.\n      unfold Ordinal in H; destruct H.\n      double H4; unfold full in H8; apply H8 in H4.\n      split; auto; apply Axiom_SchemeP; split; auto.\n      apply Theorem49; split; Ens.\n    - apply Axiom_Scheme in H6; destruct H6, H8.\n      unfold Rrelation in H9; apply Axiom_SchemeP in H9; tauto. }\n  rewrite <- H6 in H5; subst x0; auto.\nQed.\n\nHint Resolve Theorem108 : set.\n\n\n(* 109 Theorem  If x is an ordinal an y is an ordinal, then x⊂y or y⊂x. *)\n\nLemma Lemma109 : forall x y,\n  Ordinal x /\\ Ordinal y -> full (x ∩ y).\nProof.\n  intros; destruct H; unfold Ordinal in H, H0; destruct H, H0.\n  unfold full in *; intros; apply Axiom_Scheme in H3; destruct H3, H4.\n  apply H1 in H4; apply H2 in H5.\n  unfold Subclass; intros; apply Axiom_Scheme; repeat split; Ens.\nQed.\n\nLemma Lemma109' : forall x y,\n  Ordinal x /\\ Ordinal y -> ((x ∩ y) = x) \\/ ((x ∩ y) ∈ x).\nProof.\n  intros.\n  generalize (classic ((x ∩ y) = x)); intro; destruct H0; try tauto.\n  assert ((x ∩ y) ⊂ x).\n  { unfold Subclass; intros; apply Theorem4' in H1; tauto. }\n  elim H; intros; apply Lemma109 in H.\n  eapply Theorem108 in H2; eauto.\nQed.\n\nTheorem Theorem109 : forall x y,\n  Ordinal x /\\ Ordinal y -> x ⊂ y \\/ y ⊂ x.\nProof.\n  intros; elim H; intros; generalize (Lemma_xy _ _ H1 H0); intro.\n  apply Lemma109' in H; apply Lemma109' in H2; destruct H.\n  - apply Theorem30 in H; tauto.\n  - destruct H2.\n    + apply Theorem30 in H2; tauto.\n    + assert ((x ∩ y) ∈ (x ∩ y)).\n      { rewrite Theorem6' in H2; apply Axiom_Scheme; repeat split; Ens. }\n      apply Theorem101 in H3; elim H3.\nQed.\n\nHint Resolve Theorem109 : set.\n\n\n(* 110 Theorem  If x is an ordinal an y is an ordinal, then x∈y or y∈x or\n   x = y. *)\n\nTheorem Theorem110 : forall x y,\n  Ordinal x /\\ Ordinal y -> x ∈ y \\/ y ∈ x \\/ x = y.\nProof.\n  intros; generalize (classic (x = y)); intro; destruct H0; try tauto.\n  elim H; intros; apply Theorem109 in H; destruct H.\n  - left; unfold Ordinal in H1; destruct H1; eapply Theorem108; eauto.\n  - right; left; unfold Ordinal in H2; destruct H2.\n    eapply Theorem108; eauto; intro; auto.\nQed.\n\nHint Resolve Theorem110 : set.\n\n\n(* 111 Theorem  If x is an ordinal and y∈x, then y is an ordinal. *)\n\nTheorem Theorem111 : forall x y, Ordinal x /\\ y ∈ x -> Ordinal y.\nProof.\n  intros; destruct H; double H; unfold Ordinal in H; destruct H.\n  assert (Connect E y).\n  { unfold Connect; intros; unfold Ordinal in H1; apply H1 in H0.\n    unfold Connect in H; destruct H3; apply H; auto. }\n  unfold Ordinal; split; auto.\n  unfold full; intros; unfold Subclass; intros.\n  apply Theorem107 in H1; unfold Ordinal in H1.\n  assert (y ⊂ x); auto; assert (m ∈ x); auto.\n  assert (m ⊂ x); auto; assert (z ∈ x); auto.\n  apply Theorem88 in H1; destruct H1.\n  unfold Transitive in H1; specialize H1 with z m y.\n  assert (Rrelation z E y).\n  { apply H1; repeat split; Ens.\n    - unfold Rrelation; apply Axiom_SchemeP; split; auto.\n      apply Theorem49; split; Ens.\n    - unfold Rrelation; apply Axiom_SchemeP; split; auto.\n      apply Theorem49; split; Ens. }\n  unfold Rrelation in H11; apply Axiom_SchemeP in H11; tauto.\nQed.\n\nHint Resolve Theorem111 : set.\n\n\n(* 112 Definition  R = { x : x is an ordinal }. *)\n\nDefinition R : Class := \\{ λ x, Ordinal x \\}.\n\nHint Unfold R : set.\n\n\n(* 113 Theorem  R is an ordinal and R is not a set. *)\n\nLemma Lemma113 :forall u v,\n  Ensemble u -> Ensemble v -> Ordinal u /\\ Ordinal v ->\n  (Rrelation u E v \\/ Rrelation v E u \\/ u = v) .\nProof.\n  intros; apply Theorem110 in H1; repeat split.\n  destruct H1 as [H1 | [H1 | H1]].\n  - left; unfold Rrelation; apply Axiom_SchemeP; split; Ens.\n    apply Theorem49; auto.\n  - right; left; apply Axiom_SchemeP; split; Ens.\n    apply Theorem49; auto.\n  - right; right; auto.\nQed.\n\nTheorem Theorem113 : Ordinal R /\\ ~ Ensemble R.\nProof.\n  intros.\n  assert (Ordinal R).\n  { unfold Ordinal; intros; split.\n    - unfold Connect; intros; destruct H.\n      apply Axiom_Scheme in H; destruct H; apply Axiom_Scheme in H0; destruct H0.\n      generalize (Lemma_xy _ _ H1 H2); intro; apply Lemma113; auto.\n    - unfold full; intros; apply Axiom_Scheme in H; destruct H.\n      unfold Subclass; intros; apply Axiom_Scheme; split; Ens.\n      eapply Theorem111; eauto. }\n  split; auto; intro.\n  assert (R ∈ R). { apply Axiom_Scheme; split; auto. }\n  apply Theorem101 in H1; auto.\nQed.\n\nHint Resolve Theorem113 : set.\n\n\n(* 114 Theorem  Each E-section of R is an ordinal. *)\n\nTheorem Theorem114 : forall x, Section x E R -> Ordinal x.\nProof.\n  intros.\n  generalize (classic (x = R)); intro; destruct H0.\n  - rewrite H0; apply Theorem113.\n  - generalize (Lemma_xy _ _ H H0); intro.\n    apply Theorem91 in H1; destruct H1, H1.\n    assert (x0 = \\{ λ u, u ∈ R /\\ Rrelation u E x0 \\}).\n    { apply Axiom_Extent; split; intros.\n      - apply Axiom_Scheme; repeat split; Ens.\n        + apply Axiom_Scheme in H1; destruct H1.\n          apply Axiom_Scheme; split; Ens; eapply Theorem111; eauto.\n        + unfold Rrelation; apply Axiom_SchemeP; split; auto.\n          apply Theorem49; Ens.\n      - apply Axiom_Scheme in H3; destruct H3, H4.\n        unfold Rrelation in H5; apply Axiom_SchemeP in H5; tauto. }\n    subst x; rewrite H3 in H1; apply Axiom_Scheme in H1; tauto.\nQed.\n\nCorollary Property114 : forall x, Ordinal x -> Section x E R.\nProof.\n  intros; unfold Section; split.\n  - unfold Subclass; intros; apply Axiom_Scheme; split; try Ens.\n    eapply Theorem111; eauto.\n  - split; intros; try apply Theorem107; try apply Theorem113.\n    destruct H0, H1; unfold Ordinal in H2; apply Axiom_SchemeP in H2.\n    destruct H2; unfold Ordinal in H; destruct H; apply H4 in H1; auto.\nQed.\n\n\nHint Resolve Theorem114 : set.\n\n\n(* 115 Definition  x is an ordinal number iff x ∈ R. *)\n\nDefinition Ordinal_Number x : Prop := x ∈ R.\n\nHint Unfold Ordinal_Number : set.\n\n\n(* 116 Definition  x ≺ y if and only if x ∈ y. *)\n\nDefinition Less x y : Prop := x ∈ y.\n\nNotation \"x ≺ y\" := (Less x y)(at level 67, left associativity).\n\nHint Unfold Less : set.\n\n\n(* 117 Definition  x ≼ y if and only if x ∈ y or x = y. *)\n\nDefinition LessEqual x y := x ∈ y \\/ x=y.\n\nNotation \"x ≼ y\" := (LessEqual x y)(at level 67, left associativity).\n\n\n(* 118 Theorem  If x and y are ordinals, then x ≼ y if and only if x ⊂ y. *)\n\nTheorem Theorem118 : forall x y,\n  Ordinal x /\\ Ordinal y -> (x ⊂ y <-> x ≼ y).\nProof.\n  intros; destruct H; split; intros.\n  - unfold LessEqual.\n    generalize (classic (x = y)); intro; destruct H2; try tauto.\n    unfold Ordinal in H; destruct H.\n    left; apply Theorem108; auto.\n  - unfold LessEqual in H1; destruct H1.\n    + unfold Ordinal in H0; destruct H0; auto.\n    + rewrite H1; auto; unfold Subclass; intros; auto.\nQed.\n\nHint Resolve Theorem118 : set.\n\n\n(* 119 Theorem  If x is an ordinal, then x = { y : y ∈ R /\\ y ≺ x }. *)\n\nTheorem Theorem119 : forall x,\n  Ordinal x -> x = \\{ λ y, y ∈ R /\\ y ≺ x \\}.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme; repeat split; Ens.\n    apply Axiom_Scheme; split; Ens; eapply Theorem111; eauto.\n  - apply Axiom_Scheme in H0; destruct H0, H1; auto.\nQed.\n\nHint Resolve Theorem119 : set.\n\n\n(* 120 Theorem  If x ⊂ R, then ∪x is an ordinal. *)\n\nTheorem Theorem120 : forall x, x ⊂ R -> Ordinal (∪ x).\nProof.\n  intros; red; split.\n  - unfold Connect; intros; destruct H0; apply Axiom_Scheme in H0.\n    apply Axiom_Scheme in H1; destruct H0, H2, H2, H1, H4, H4.\n    apply H in H3; apply H in H5; apply Axiom_Scheme in H3.\n    destruct H3; apply Axiom_Scheme in H5; destruct H5.\n    assert (Ordinal u). { eapply Theorem111; eauto. }\n    assert (Ordinal v). { eapply Theorem111; eauto. }\n    generalize (Lemma_xy _ _ H8 H9); intro; apply Lemma113; auto.\n  - apply Property_Full; intros; destruct H0.\n    apply Axiom_Scheme in H0; destruct H0, H2, H2.\n    apply Axiom_Scheme; split; Ens; exists x0; split; auto.\n    apply H in H3; apply Axiom_Scheme in H3; destruct H3 as [_ H3].\n    unfold Ordinal in H3; destruct H3; apply H4 in H2; auto.\nQed.\n\nHint Resolve Theorem120 : set.\n\n\n(* 121 Theorem  If x ⊂ R and x ≠ Φ, then ∩x ∈ x. *)\n\nLemma Lemma121 : forall x, x ⊂ R /\\ x ≠ Φ -> FirstMember (∩ x) E x.\nProof.\n  intros; destruct H.\n  generalize (Theorem113); intro; destruct H1.\n  apply Theorem107 in H1; unfold WellOrdered in H1; destruct H1.\n  generalize (Lemma_xy _ _ H H0); intro; apply H3 in H4; destruct H4.\n  double H4; unfold FirstMember in H4; destruct H4.\n  assert ((∩ x) = x0).\n  { apply Axiom_Extent; split; intros.\n    - apply Axiom_Scheme in H7; destruct H7; apply H8; auto.\n    - apply Axiom_Scheme; split; Ens; intros.\n      assert (~ Rrelation y E x0); auto.\n      assert (Ordinal x0). { apply H in H4; apply Axiom_Scheme in H4; tauto. }\n      assert (Ordinal y). { apply H in H8; apply Axiom_Scheme in H8; tauto. }\n      generalize (Lemma_xy _ _ H10 H11); intro; apply Theorem110 in H12.\n      destruct H12 as [H12 | [H12 | H12]].\n      + apply H in H8; apply Axiom_Scheme in H8; destruct H8 as [_ H8].\n        unfold Ordinal in H8; destruct H8; generalize (Property_Full y); intro.\n        destruct H14; eapply H14; eauto.\n      + elim H9; unfold Rrelation; apply Axiom_SchemeP; split; auto.\n        apply Theorem49; Ens.\n      + subst x0; auto. }\n  rewrite H7 ; auto.\nQed.\n\nTheorem Theorem121 : forall x, x ⊂ R /\\ x ≠ Φ -> (∩ x) ∈ x.\nProof.\n  intros; apply Lemma121 in H.\n  unfold FirstMember in H; tauto.\nQed.\n\nHint Resolve Theorem121 : set.\n\n\n(* 122 Definition  x + 1 = x ∪ {x}. *)\n\nDefinition PlusOne x := x ∪ [x].\n\nHint Unfold PlusOne: set.\n\n\n(* 123 Theorem  If x∈R, then x+1 is the E-first member of {y : y∈R and x≺y}. *)\n\nLemma Lemma123 : forall x, x ∈ R -> (PlusOne x) ∈ R.\nProof.\n  intros; apply Axiom_Scheme; split.\n  - apply Axiom_Union; split; Ens; apply Theorem42; Ens.\n  - unfold Connect; split.\n    + unfold Connect; intros; destruct H0.\n      apply Axiom_Scheme in H0; apply Axiom_Scheme in H1; destruct H0, H1, H2, H3.\n      * apply Axiom_Scheme in H; destruct H as [_ H].\n        assert (Ordinal u). { eapply Theorem111; eauto. }\n        assert (Ordinal v). { eapply Theorem111; eauto. }\n        generalize (Lemma_xy _ _ H4 H5); intro; apply Lemma113; auto.\n      * apply Axiom_Scheme in H3; destruct H3.\n        AssE x; apply Theorem19 in H5; apply H4 in H5; subst v.\n        left; unfold Rrelation; apply Axiom_SchemeP; split; auto.\n        apply Theorem49; tauto.\n      * apply Axiom_Scheme in H2; destruct H2.\n        AssE x; apply Theorem19 in H5; apply H4 in H5; subst u.\n        right; left; unfold Subclass; apply Axiom_SchemeP; split; auto.\n        apply Theorem49; tauto.\n      * AssE x; apply Theorem19 in H4; double H4.\n        apply Axiom_Scheme in H2; destruct H2; apply H6 in H4.\n        apply Axiom_Scheme in H3; destruct H3; apply H7 in H5.\n        subst u; subst v; tauto.\n    + unfold full; intros; unfold Subclass; intros.\n      apply Axiom_Scheme in H; apply Axiom_Scheme in H0; destruct H, H0.\n      apply Axiom_Scheme; split; Ens; destruct H3.\n      * unfold Ordinal in H2; destruct H2.\n        unfold full in H4; left; eapply H4; eauto.\n      * apply Axiom_Scheme in H3; destruct H3.\n        apply Theorem19 in H; apply H4 in H; subst m; tauto.\nQed.\n\nTheorem Theorem123 : forall x,\n  x ∈ R -> FirstMember (PlusOne x) E (\\{ λ y, (y ∈ R /\\ Less x y) \\}).\nProof.\n  intros; unfold FirstMember; split; intros.\n  - apply Axiom_Scheme; repeat split.\n    + unfold Ensemble; exists R; apply Lemma123; auto.\n    + apply Lemma123; auto.\n    + unfold Less; intros; apply Axiom_Scheme; split; Ens.\n      right; apply Axiom_Scheme; split; Ens.\n  - intro; apply Axiom_Scheme in H0; destruct H0, H2.\n    unfold Rrelation in H1; apply Axiom_SchemeP in H1; destruct H1.\n    apply Axiom_Scheme in H4; destruct H4; unfold Less in H3; destruct H5.\n    + eapply Theorem102; eauto.\n    + AssE x; apply Theorem19 in H6; apply Axiom_Scheme in H5; destruct H5.\n      apply H7 in H6; subst y; eapply Theorem101; eauto.\nQed.\n\nHint Resolve Theorem123 : set.\n\n\n(* 124 Theorem  If x ∈ R, then ∪(x+1) = x. *)\n\nTheorem Theorem124 : forall x, \n  x ∈ R -> ∪ PlusOne x = x.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H0; destruct H0, H1, H1.\n    apply Axiom_Scheme in H2; destruct H2, H3.\n    + apply Axiom_Scheme in H; destruct H, H4.\n      generalize (Property_Full x); intro; destruct H6.\n      apply H6 with (u:=z) (v:=x0) in H5; tauto.\n    + apply Axiom_Scheme in H3; destruct H3.\n      rewrite <- H4; auto; try (apply Theorem19; Ens).\n  - apply Axiom_Scheme; split; Ens; exists x; split; auto.\n    apply Axiom_Scheme; split; Ens; right; apply Axiom_Scheme; Ens.\nQed.\n\nHint Resolve Theorem124 : set.\n\n\n(* 125 Definition  f|x = f ∩ (x × μ). *)\n\nDefinition Restriction f x : Class := f ∩ (x × μ).\n\nNotation \"f | ( x )\" := (Restriction f x)(at level 30).\n\nHint Unfold Restriction: set.\n\n\n(* 126 Theorem  If f is a function, f|x is a function whose domain is\n   x ∩ (domain f) and (f|x)[y] = f[y] for each y in domain f|x. *)\n\nTheorem Theorem126 : forall f x,\n  Function f -> Function (f|(x)) /\\ dom(f|(x)) = x ∩ dom( f) /\\\n  (forall y, y ∈ dom(f|(x)) -> (f|(x)) [y] = f [y]).\nProof.\n  intros; repeat split; intros.\n  - unfold Relation; intros; apply Axiom_Scheme in H0; destruct H0, H1.\n    PP H2 a b; eauto.\n  - destruct H0; apply Axiom_Scheme in H0; destruct H0 as [_ [H0 _]].\n    apply Axiom_Scheme in H1; destruct H1 as [_ [H1 _]].\n    unfold Function in H; eapply H; eauto.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H0; destruct H0, H1.\n      apply Axiom_Scheme in H1; destruct H1, H2.\n      apply Property_dom in H2; apply Axiom_SchemeP in H3.\n      apply Axiom_Scheme; split; tauto.\n    + apply Axiom_Scheme in H0; destruct H0, H1.\n      apply Axiom_Scheme; split; auto.\n      apply Property_Value in H2; auto.\n      exists f[z]; apply Axiom_Scheme; repeat split; Ens.\n      apply Axiom_SchemeP; repeat split; Ens; apply Theorem19.\n      apply Property_ran in H2; Ens.\n  - apply Axiom_Extent; split; intros.\n    + apply Axiom_Scheme in H1; destruct H1.\n      apply Axiom_Scheme in H0; destruct H0, H3.\n      apply Axiom_Scheme in H3; destruct H3, H4.\n      apply Property_dom in H4; apply H2.\n      assert (Ensemble f[y]). { apply Theorem19; apply Theorem69; auto. }\n      apply Axiom_Scheme; split; Ens; apply Axiom_Scheme; repeat split.\n      * apply Theorem49; auto.\n      * apply Property_Value in H4; auto.\n      * apply Axiom_SchemeP in H5; apply Theorem19 in H6.\n        apply Axiom_SchemeP; repeat split; try tauto; try apply Theorem49; Ens.\n    + apply Axiom_Scheme in H1; destruct H1.\n      apply Axiom_Scheme; split; auto; intros.\n      apply Axiom_Scheme in H3; destruct H3; apply Axiom_Scheme in H4.\n      apply H2; apply Axiom_Scheme; split; tauto.\nQed.\n\nHint Resolve Theorem126 : set.\n\n\n(* 127 Theorem  Let f be a function such that domain f is an ordinal and\n   f[u] = g[f|u] for u in domain f. If h is also a function such that domain h\n   is an ordinal and h[u] = g[h|u] for u in domain h, then h ⊂ f or f ⊂ h. *)\n\nTheorem Lemma127 : forall f h,\n  dom( f) ⊂ dom( h) -> Function f -> Function h ->\n  \\{ λ a,a ∈ (dom( f) ∩ dom( h)) /\\ f [a] ≠ h [a] \\} = Φ -> f ⊂ h.\nProof.\n  intros.\n  unfold Subclass; intros; rewrite Theorem70 in H3; auto; PP H3 a b.\n  double H4; rewrite <- Theorem70 in H4; auto; apply Property_dom in H4.\n  apply Axiom_SchemeP in H5; destruct H5.\n  rewrite Theorem70; auto; apply Axiom_SchemeP; split; auto; rewrite H6.\n  generalize (classic (f[a] = h[a])); intro; destruct H7; auto.\n  assert (a ∈ \\{ λ a, a ∈ (dom(f) ∩ dom(h)) /\\ f[a] ≠ h[a] \\}).\n  { apply Theorem30 in H; rewrite H; apply Axiom_Scheme; split; Ens. }\n  rewrite H2 in H8; generalize (Theorem16 a); contradiction.\nQed.\n\nTheorem Theorem127 : forall f h g,\n  Function f -> Ordinal dom(f) ->\n  (forall u0, u0 ∈ dom(f) -> f[u0] = g[f|(u0)]) ->\n  Function h -> Ordinal dom(h) ->\n  (forall u1, u1 ∈ dom(h) -> h[u1] = g [h|(u1)]) -> h ⊂ f \\/ f ⊂ h.\nProof.\n  intros.\n  generalize (Lemma_xy _ _ H0 H3); intro; apply Theorem109 in H5.\n  generalize (classic (\\{ λ a, a ∈ (dom(f) ∩ dom(h)) /\\ f[a] ≠ h[a] \\} = Φ));\n  intro; destruct H6.\n  - destruct H5.\n    + right; apply Lemma127; auto.\n    + left; rewrite Lemma97'' in H6; apply Lemma127; auto.\n  - assert (exists u, FirstMember u E \\{λ a, a∈(dom(f)∩dom(h))/\\f[a]≠h[a]\\}).\n    { apply Theorem107 in H0; unfold WellOrdered in H0; apply H0; split; auto.\n      unfold Subclass; intros; apply Axiom_Scheme in H7; destruct H7, H8.\n      apply Axiom_Scheme in H8; tauto. }\n    destruct H7 as [u H7]; unfold FirstMember in H7; destruct H7.\n    apply Axiom_Scheme in H7; destruct H7, H9.\n    apply Axiom_Scheme in H9; destruct H9 as [_[H9 H11]].\n    generalize (H1 _ H9); generalize (H4 _ H11); intros.\n    assert ((h | (u)) = (f | (u))).\n    { apply Axiom_Extent; intros; split; intros.\n      - apply Axiom_Scheme in H14; destruct H14, H15.\n        apply Axiom_Scheme; repeat split; auto; PP H16 a b.\n        apply Axiom_SchemeP in H17; destruct H17 ,H18.\n        generalize H15 as H22; intro; apply Property_dom in H22.\n        rewrite Theorem70 in H15; auto; rewrite Theorem70; auto.\n        apply Axiom_SchemeP in H15; destruct H15.\n        apply Axiom_SchemeP; split; auto.\n        rewrite H20; symmetry.\n        generalize (classic (f [a] = h [a])); intro; destruct H21; auto.\n        assert (a ∈ \\{ λ a, a ∈ (dom(f) ∩ dom(h)) /\\ f[a] ≠ h[a] \\}).\n        { apply Axiom_Scheme.\n          repeat split; Ens; apply Axiom_Scheme; repeat split; Ens.\n          unfold Ordinal in H0; destruct H0; apply H23 in H9; auto. }\n        apply H8 in H23; elim H23; unfold Rrelation, E.\n        apply Axiom_SchemeP; split; auto; apply Theorem49; split; Ens.\n      - apply Axiom_Scheme in H14; destruct H14, H15.\n        apply Axiom_Scheme; repeat split; auto; PP H16 a b.\n        apply Axiom_SchemeP in H17; destruct H17 ,H18.\n        generalize H15 as H22; intro; apply Property_dom in H22.\n        rewrite Theorem70 in H15; auto; rewrite Theorem70; auto.\n        apply Axiom_SchemeP in H15; destruct H15.\n        apply Axiom_SchemeP; split; auto.\n        rewrite H20; symmetry.\n        generalize (classic (f[a] = h[a])); intro; destruct H21; auto.\n        assert (a ∈ \\{ λ a, a ∈ (dom(f) ∩ dom(h)) /\\ f[a] ≠ h[a] \\}).\n        { apply Axiom_Scheme.\n          repeat split; Ens; apply Axiom_Scheme; repeat split; Ens.\n          unfold Ordinal in H3; destruct H3; apply H23 in H11; auto. }\n        apply H8 in H23; elim H23; unfold Rrelation, E.\n        apply Axiom_SchemeP; split; auto; apply Theorem49; split; Ens. }\n  rewrite <- H14 in H13; rewrite <- H12 in H13; contradiction.\nQed.\n\nHint Resolve Theorem127 : set.\n\n\n(* 128 Theorem  For each g there is a unique function f such that domain f is\n   an ordinal and f[x] = g[f|x] for each ordinal number x. *)\n\nDefinition En_f' g := \\{\\ λ u v, u ∈ R /\\ (exists h, Function h /\\\n  Ordinal dom(h) /\\ (forall z, z ∈ dom(h) -> h[z] = g [h | (z)] ) /\\\n  [u,v] ∈ h ) \\}\\.\n\nLemma Lemma128 : forall u v w,\n  Ordinal u -> v ∈ u -> w ∈ v -> w ∈ u.\nProof.\n  intros; unfold Ordinal in H; destruct H.\n  unfold full in H2; eapply H2; eauto.\nQed.\n\nLemma Lemma128' : forall f x,\n  Function f -> Ordinal dom(f) -> Ordinal_Number x ->\n  ~ x ∈ dom(f) -> f | (x) = f .\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H3; tauto.\n  - apply Axiom_Scheme; split; Ens; split; auto.\n    unfold Function, Relation in H; destruct H as [H _].\n    double H3; apply H in H4; destruct H4 as [a [b H4]]; rewrite H4 in *.\n    clear H H4; apply Axiom_SchemeP; split; Ens; split.\n    + unfold Ordinal in H1; apply Axiom_Scheme in H1; destruct H1.\n      assert (Ordinal dom(f) /\\ Ordinal x); auto.\n      apply Theorem110 in H4; apply Property_dom in H3; auto.\n      destruct H4 as [H4 | [H4 | H4]]; try contradiction.\n      * eapply Lemma128; eauto.\n      * rewrite H4 in H3; auto.\n    + apply Property_ran in H3; apply Theorem19; Ens.\nQed.\n\nTheorem Theorem128 :  forall g,\n  exists f, Function f /\\ Ordinal dom(f) /\\\n  (forall x, Ordinal_Number x -> f [x] = g [f | (x)]).\nProof.\n  intros; exists (En_f' g).\n  assert (Function (En_f' g)).\n  { unfold Function; intros; split; intros.\n    - unfold Relation; intros; PP H a b; eauto.\n    - destruct H; apply Axiom_SchemeP in H; apply Axiom_SchemeP in H0.\n      destruct H, H1, H2, H2, H3, H4, H0, H6, H7, H7, H8, H9.\n      generalize (Theorem127 _ _ _ H2 H3 H4 H7 H8 H9); intro; destruct H11.\n      + apply H11 in H10; eapply H2; eauto.\n      + apply H11 in H5; eapply H7; eauto. }\n  split; auto.\n  - assert (Ordinal dom(En_f' g)).\n    { apply Theorem114; unfold Section; intros; split.\n      - unfold Subclass; intros; apply Axiom_Scheme in H0.\n        destruct H0, H1; apply Axiom_SchemeP in H1; tauto.\n      - split; intros.\n        + apply Theorem107; apply Theorem113.\n        + destruct H0, H1; apply Axiom_Scheme in H1; destruct H1, H3.\n          apply Axiom_SchemeP in H3; destruct H3, H4, H5, H5, H6, H7.\n          apply Axiom_SchemeP in H2; destruct H2.\n          apply Theorem49 in H2; destruct H2.\n          apply Axiom_Scheme; split; auto; apply Property_dom in H8.\n          assert (u ∈ dom( x0)). { eapply Lemma128; eauto. }\n          exists (x0[u]); apply Axiom_SchemeP.\n          split; try apply Theorem49; split; auto.\n          * apply Theorem19; apply Theorem69; auto.\n          * exists x0; split; auto; split; auto; split; auto.\n            apply Property_Value; auto. }\n    split; intros; auto.\n    generalize (classic (x ∈ dom(En_f' g))); intro; destruct H2.\n    + apply Axiom_Scheme in H2; destruct H2, H3; apply Axiom_SchemeP in H3.\n      destruct H2, H3, H4, H5 as [h [H5 [H6 [H7 H8]]]].\n      assert (h ⊂ En_f' g).\n      { double H5; unfold Subclass; intros; unfold Function, Relation in H9.\n        destruct H9 as [H9 _]; double H10; apply H9 in H11.\n        destruct H11 as [a [b H11]]; rewrite H11 in *; clear H9 H11 z.\n        apply Axiom_SchemeP; split; try Ens.\n        double H10; apply Property_dom in H9.\n        split; try apply Axiom_Scheme; Ens; split; Ens.\n        eapply Theorem111; eauto. }\n      double H8; apply H9 in H10; double H8.\n      apply Property_dom in H11; apply H7 in H11.\n      double H8; apply Property_dom in H12; apply Property_dom in H8.\n      apply Property_Value in H8; auto; apply Property_dom in H10.\n      apply Property_Value in H10; auto; apply H9 in H8.\n      assert (h [x] = (En_f' g) [x]). { eapply H; eauto. }\n      rewrite <- H13; clear H13.\n      assert (h | (x) = En_f' g | (x)).\n      { apply Axiom_Extent.\n        split; intros; apply Axiom_Scheme in H13; destruct H13, H14.\n        - apply Axiom_Scheme; repeat split; auto.\n        - apply Axiom_Scheme; repeat split; auto; rewrite Theorem70; auto.\n          PP H15 a b; apply Axiom_SchemeP in H16.\n          apply Axiom_SchemeP; split; auto.\n          destruct H16, H17; assert (a ∈ dom(h)). { eapply Lemma128; eauto. }\n          apply Property_Value in H19; auto; apply H9 in H19; eapply H; eauto. }\n      rewrite <- H13; auto.\n    + generalize H2; intro; apply Theorem69 in H2; auto.\n      rewrite (Lemma128' _ _ H H0 H1 H3).\n      generalize (classic (En_f' g ∈ dom(g))); intro; destruct H4.\n      * generalize Theorem113; intro; destruct H5 as [H5 _].\n        apply Theorem107 in H5; unfold WellOrdered in H5; destruct H5.\n        assert ((R ~ dom(En_f' g)) ⊂ R /\\ (R ~ dom(En_f' g)) ≠ Φ).\n        { split; try (red; intros; apply Axiom_Scheme in H7; tauto).\n          intro; generalize (Property114 _ H0); intro.\n          unfold Section in H8; destruct H8.\n          apply Property_Φ in H8; apply H8 in H7.\n          rewrite <- H7 in H3; contradiction. }\n        apply H6 in H7; destruct H7 as [y H7].\n        assert (((En_f' g) ∪ [[y,g[En_f' g]]]) ⊂ (En_f' g)).\n        { unfold Subclass; intros.\n          apply Axiom_Scheme in H8; destruct H8, H9; auto.\n          assert (Ensemble ([y, g [En_f' g]])).\n          { destruct H7; AssE y; apply Theorem69 in H4.\n            apply Theorem19 in H4; apply Theorem49; tauto. }\n          apply Axiom_Scheme in H9; destruct H9.\n          rewrite H11; try apply Theorem19; auto.\n          apply Axiom_SchemeP; split; auto; split.\n          - unfold FirstMember in H7; destruct H7.\n            apply Axiom_Scheme in H7; tauto.\n          - exists ((En_f' g) ∪ [[y,g[En_f' g]]]).\n            assert (Function (En_f' g ∪ [[y, g [En_f' g]]])).\n            { unfold Function; split; intros.\n              - unfold Relation; intros; apply Axiom_Scheme in H12.\n                destruct H12, H13; try PP H13 a b; eauto.\n                apply Axiom_Scheme in H13; destruct H13; apply Theorem19 in H10.\n                apply H14 in H10; eauto.\n              - destruct H12; apply Axiom_Scheme in H12.\n                destruct H12 as [_ H12].\n                apply Axiom_Scheme in H13; destruct H13 as [_ H13].\n                unfold FirstMember in H7; destruct H7.\n                apply Axiom_Scheme in H7; destruct H7 as [_ [_ H7]].\n                apply Axiom_Scheme in H7; destruct H7, H12, H13.\n                + eapply H; eauto.\n                + apply Axiom_Scheme in H13; destruct H13.\n                  apply Theorem19 in H10.\n                  apply H16 in H10; apply Theorem55 in H10;\n                  destruct H10; try apply Theorem49; auto; rewrite H10 in H12.\n                  apply Property_dom in H12; contradiction.\n                + apply Axiom_Scheme in H12; destruct H12.\n                  apply Theorem19 in H10.\n                  apply H16 in H10; apply Theorem55 in H10; destruct H10;\n                  try apply Theorem49; auto; rewrite H10 in H13.\n                  apply Property_dom in H13; contradiction.\n                + double H12; apply Axiom_Scheme in H12.\n                  apply Axiom_Scheme in H13.\n                  destruct H12, H13; double H10.\n                  apply Theorem19 in H10; apply H17 in H10.\n                  apply Theorem19 in H19; apply H18 in H19.\n                  apply Theorem55 in H10; destruct H10;\n                  apply Theorem49 in H12; auto.\n                  apply Theorem55 in H19; destruct H19;\n                  apply Theorem49 in H13; auto.\n                  rewrite H20, H21; auto. }\n            split; auto; split.\n            + apply Theorem114; unfold Section; intros; split.\n              * unfold Subclass; intros.\n                apply Axiom_Scheme in H13; destruct H13, H14.\n                apply Axiom_Scheme in H14; destruct H14, H15.\n                -- apply Property_dom in H15; apply Axiom_Scheme.\n                   split; Ens; eapply Theorem111; eauto.\n                -- apply Axiom_Scheme in H15; destruct H15.\n                   apply Theorem19 in H10.\n                   apply H16 in H10; apply Theorem55 in H10; destruct H10;\n                   try apply Theorem49; auto; destruct H7.\n                   apply Axiom_Scheme in H7; rewrite H10; tauto.\n              * split; try (apply Theorem107; apply Theorem113); intros.\n                destruct H13, H14; apply Axiom_Scheme in H14; destruct H14, H16.\n                apply Axiom_Scheme in H16; destruct H16, H17.\n                -- apply Axiom_Scheme; split; Ens.\n                   assert ([u, (En_f' g) [u]] ∈ (En_f' g)).\n                   { apply Property_Value; auto; apply Property_dom in H17.\n                     unfold Rrelation in H15; apply Axiom_SchemeP in H15.\n                     destruct H15; eapply Lemma128; eauto. }\n                   exists ((En_f' g) [u]); apply Axiom_Scheme; split; Ens.\n                -- assert ([u, (En_f' g) [u]] ∈ (En_f' g)).\n                   { apply Property_Value; auto.\n                     apply Axiom_Scheme in H17; destruct H17.\n                     apply Theorem19 in H10; apply H18 in H10.\n                     apply Theorem55 in H10;\n                     destruct H10; try apply Theorem49; auto.\n                     subst v; unfold FirstMember in H7; destruct H7.\n                     generalize (classic (u ∈ dom( En_f' g))); intro.\n                     destruct H20; auto.\n                     absurd (Rrelation u E y); auto; try apply H10.\n                     apply Axiom_Scheme; repeat split; Ens.\n                     apply Axiom_Scheme; split; Ens. }\n                   apply Axiom_Scheme; split; Ens; exists ((En_f' g) [u]).\n                   apply Axiom_Scheme; split; Ens.\n            + split; intros.\n              * apply Property_Value in H13; auto.\n                apply Axiom_Scheme in H13; destruct H13, H14.\n                -- apply Axiom_SchemeP in H14; destruct H14, H15.\n                   destruct H16 as [h [H16 [H17 [H18 H19]]]].\n                   double H19; apply Property_dom in H20.\n                   rewrite Theorem70 in H19; auto.\n                   apply Axiom_SchemeP in H19; destruct H19.\n                   assert (h ⊂ En_f' g).\n                   { unfold Subclass; intros; double H16.\n                     unfold Function, Relation in H23; destruct H23 as [H23 _].\n                     double H22; apply H23 in H24; destruct H24 as [a [b H24]].\n                     rewrite H24 in *; clear H23 H24; apply Axiom_SchemeP.\n                     split; try Ens; double H22; apply Property_dom in H23.\n                     split; try apply Axiom_Scheme; Ens.\n                     split; try Ens; eapply Theorem111; eauto. }\n                   assert ((En_f' g ∪ [[y, g[En_f' g]]])|(z0) = En_f' g|(z0)).\n                   { unfold Restriction; rewrite Theorem6'; rewrite Theorem8.\n                     assert ((z0) × μ ∩ [[y, g [En_f' g]]] = Φ).\n                     { apply Axiom_Extent; split; intros.\n                       - apply Axiom_Scheme in H23; destruct H23, H24; auto.\n                         PP H24 a b; apply Axiom_SchemeP in H26.\n                         destruct H26, H27.\n                         apply Axiom_Scheme in H25; destruct H25.\n                         apply Theorem19 in H10; apply H29 in H10.\n                         apply Theorem55 in H10; apply Theorem49 in H25; auto.\n                         destruct H10; rewrite H10 in H27.\n                         assert (y ∈ dom( h)).   { eapply Lemma128; eauto. }\n                         apply Property_Value in H31; auto.\n                         apply H22 in H31; apply Property_dom in H31.\n                         unfold FirstMember in H7; destruct H7.\n                         apply Axiom_Scheme in H7; destruct H7, H33.\n                         apply Axiom_Scheme in H34; destruct H34; contradiction.\n                       - generalize (Theorem16 z1); contradiction. }\n                     rewrite H23, Theorem6, Theorem17; apply Theorem6'. }\n                   rewrite H21, H23.\n                   assert (h | (z0) = En_f' g | (z0)).\n                   { apply Axiom_Extent; split; intros.\n                     - apply Axiom_Scheme in H24; destruct H24, H25.\n                       apply Axiom_Scheme; repeat split; auto.\n                     - apply Axiom_Scheme in H24; destruct H24, H25.\n                       apply Axiom_Scheme.\n                       repeat split; auto; rewrite Theorem70; auto.\n                       PP H26 a b; apply Axiom_SchemeP in H27.\n                       apply Axiom_SchemeP.\n                       split; auto; destruct H27 as [_ [H27 _]].\n                       assert (a ∈ dom(h)). { eapply Lemma128; eauto. }\n                       apply Property_Value in H28; auto; apply H22 in H28.\n                       eapply H; eauto. }\n                   rewrite <- H24; auto.\n                -- apply Axiom_Scheme in H14; destruct H14.\n                   double H10; apply Theorem19 in H10; apply H15 in H10.\n                   apply Theorem55 in H10; apply Theorem49 in H13; auto.\n                   destruct H10; subst z0; rewrite H17.\n                   assert ((En_f' g ∪ [[y, g [En_f' g]]])|(y) = En_f' g|(y)).\n                   { apply Axiom_Extent; split; intros.\n                     - apply Axiom_Scheme in H10; destruct H10, H18.\n                       apply Axiom_Scheme in H18; destruct H18, H20.\n                       + apply Axiom_Scheme; tauto.\n                       + PP H19 a b; apply Axiom_SchemeP in H21.\n                         destruct H21, H22.\n                         apply Axiom_Scheme in H20; destruct H20.\n                         apply Theorem19 in H16; apply H24 in H16.\n                         apply Theorem55 in H16; apply Theorem49 in H21; auto.\n                         destruct H16; rewrite H16 in H22.\n                         generalize (Theorem101 y); intro; contradiction.\n                     - unfold Restriction; rewrite Theorem6', Theorem8.\n                       apply Axiom_Scheme.\n                       split; Ens; left; rewrite Theorem6'; Ens. }\n                   rewrite H10; unfold FirstMember in H7; destruct H7.\n                   apply Axiom_Scheme in H7; destruct H7, H19.\n                   apply Axiom_Scheme in H20; destruct H20.\n                   rewrite Lemma128'; auto.\n              * apply Axiom_Scheme; split; Ens; right.\n                apply Axiom_Scheme; split; Ens. }\n        unfold FirstMember in H7; destruct H7.\n        assert (y ∈ dom(En_f' g ∪ [[y, g [En_f' g]]])).\n        { apply Axiom_Scheme; split; Ens; exists g [En_f' g].\n          assert (Ensemble ([y, g [En_f' g]])).\n          { apply Theorem49; split; Ens.\n            apply Theorem69 in H4; apply Theorem19; auto. }\n          apply Axiom_Scheme; split; Ens; right; apply Axiom_Scheme; auto. }\n        apply Axiom_Scheme in H7; destruct H7, H11; apply Axiom_Scheme in H12.\n        destruct H12; elim H13; apply Axiom_Scheme in H10; destruct H10, H14.\n        apply H8 in H14; apply Property_dom in H14; auto.\n      * apply Theorem69 in H4; rewrite H2, H4; auto.\nQed.\n\nLemma Lemma128'' : forall f h,\n  Function f -> Function h -> h ⊂ f -> f | (dom(h)) = h.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H2; destruct H2, H3.\n    PP H4 a b; apply Axiom_SchemeP in H5; destruct H5, H6; double H3.\n    rewrite Theorem70; rewrite Theorem70 in H3; auto.\n    apply Axiom_SchemeP in H3; destruct H3.\n    apply Axiom_SchemeP; split; Ens; rewrite H9 in *.\n    apply Property_Value in H6; auto.\n    apply H1 in H6; eapply H; eauto.\n  - apply Axiom_Scheme; repeat split; Ens.\n    rewrite Theorem70 in H2; auto.\n    PP H2 a b; rewrite <- Theorem70 in H3; auto.\n    apply Axiom_SchemeP; repeat split; Ens.\n    + apply Property_dom in H3; auto.\n    + AssE [a,b]; apply Theorem49 in H4.\n      apply Theorem19; tauto.\nQed.\n\nLemma Lemma128''' : forall h, Function h -> h | (dom(h)) = h.\nProof.\n  intros; apply Axiom_Extent; split; intros.\n  - apply Axiom_Scheme in H0; tauto.\n  - apply Axiom_Scheme; repeat split; Ens.\n    rewrite Theorem70 in H0; auto.\n    PP H0 a b; rewrite <- Theorem70 in H1; auto.\n    apply Axiom_SchemeP; repeat split; Ens.\n    + apply Property_dom in H1; auto.\n    + AssE [a,b]; apply Theorem49 in H2.\n      apply Theorem19; tauto.\nQed.\n\nLemma Lemma128'''' : forall f g h,\n  Function f -> Function h -> Ordinal dom(f) ->\n  Ordinal dom( h)-> (forall x, Ordinal_Number x -> f [x] = g [f | (x)]) ->\n  (forall x, Ordinal_Number x -> h [x] = g [h | (x)]) -> h ⊂ f -> h = f.\nProof.\n  intros.\n  generalize (Theorem110 _ _ (Lemma_xy _ _ H1 H2)); intro.\n  destruct H6 as [H8 | [H6 | H6]].\n  - apply Property_Value in H8; auto.\n    apply H5 in H8; apply Property_dom in H8.\n    apply Theorem101 in H8; elim H8.\n  - assert (Ordinal_Number dom(h)).\n    { unfold Ordinal_Number; apply Axiom_Scheme; split; Ens. }\n    double H7; apply H3 in H7; apply H4 in H8.\n    rewrite Lemma128'' in H7; rewrite Lemma128''' in H8; auto.\n    apply Theorem69 in H6; rewrite H7 in H6.\n    generalize (Theorem101 dom(h)); intro.\n    apply Theorem69 in H9; rewrite H8 in H9.\n    rewrite H9 in H6; apply Theorem101 in H6; elim H6.\n  - apply Theorem27; split; auto.\n    unfold Subclass; intros.\n    rewrite Theorem70; rewrite Theorem70 in H7; auto.\n    PP H7 a b; double H8; rewrite <- Theorem70 in H8; auto.\n    apply Axiom_SchemeP in H9; destruct H9.\n    apply Axiom_SchemeP; split; auto; rewrite H10 in *.\n    assert ([a,h[a]] ∈ h).\n    { apply Property_Value; auto.\n      apply Property_dom in H8; rewrite <- H6; auto. }\n    apply H5 in H11; eapply H; eauto.\nQed.\n\nTheorem Theorem128' :  forall g,\n  forall f, Function f /\\ Ordinal dom(f) /\\\n  (forall x, Ordinal_Number x -> f [x] = g [f | (x)]) ->\n  forall h, Function h /\\ Ordinal dom(h) /\\\n  (forall x, Ordinal_Number x -> h [x] = g [h | (x)]) -> f = h.\nProof.\n  intros; destruct H, H0, H1, H2.\n  assert (forall u, u ∈ dom(f) -> f [u] = g [f | (u)]); intros.\n  { apply H3; unfold Ordinal_Number; apply Axiom_Scheme; split; Ens.\n    apply Theorem111 with (x:= dom(f)); auto. }\n  assert (forall u, u ∈ dom(h) -> h [u] = g [h | (u)]); intros.\n  { apply H4; unfold Ordinal_Number; apply Axiom_Scheme; split; Ens.\n    apply Theorem111 with (x:= dom(h)); auto. }\n  generalize (Theorem127 f h g H H1 H5 H0 H2 H6); intro; destruct H7.\n  - symmetry; eapply Lemma128''''; eauto.\n  - eapply Lemma128''''; eauto.\nQed.\n\nHint Resolve Theorem128 : set.\n\n\nEnd Ord.\n\nExport Ord.\n\n", "meta": {"author": "styzystyzy", "repo": "Transfinite_Induction", "sha": "f512bdae24d9fdc9d815246b613a305d4869743c", "save_path": "github-repos/coq/styzystyzy-Transfinite_Induction", "path": "github-repos/coq/styzystyzy-Transfinite_Induction/Transfinite_Induction-f512bdae24d9fdc9d815246b613a305d4869743c/theories/Ordinals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7083473454775746}}
{"text": "From CoqAlgs Require Export Sorting.Sort.\nFrom CoqAlgs Require Import Ord.\n\nSet Implicit Arguments.\n\nFunction extractMin {A : Ord} (l : list A) : option (A * list A) :=\nmatch l with\n    | [] => None\n    | h :: t =>\n        match extractMin t with\n            | None => Some (h, [])\n            | Some (m, l') =>\n                if h ≤? m then Some (h, m :: l') else Some (m, h :: l')\n        end\nend.\n\nFunction ss {A : Ord} (l : list A) {measure length l} : list A :=\nmatch extractMin l with\n    | None => []\n    | Some (m, l') => m :: ss l'\nend.\nProof.\n  induction l as [| h t]; cbn; intros.\n    inv teq.\n    destruct (extractMin t) eqn: Heq.\n      destruct p0. trich; inv teq; cbn; rewrite <- Nat.succ_lt_mono; eapply IHt; eauto.\n      inv teq. cbn. apply le_n_S, Nat.le_0_l.\nDefined.\n\nLemma Permutation_extractMin :\n  forall (A : Ord) (l l' : list A) (m : A),\n    extractMin l = Some (m, l') -> Permutation (m :: l') l.\nProof.\n  intros A l. functional induction extractMin l; cbn; inv 1.\n    destruct t; cbn in e0.\n      reflexivity.\n      destruct (extractMin t).\n        destruct p. 1-2: trich.\n    rewrite Permutation.perm_swap. auto.\nQed.\n\nLemma Permutation_ss :\n  forall (A : Ord) (l : list A),\n    Permutation (ss A l) l.\nProof.\n  intros. functional induction @ss A l.\n    destruct l; cbn in e.\n      reflexivity.\n      destruct (extractMin l); try destruct p; trich.\n    apply Permutation_extractMin in e. rewrite <- e, IHl0. reflexivity.\nQed.\n\nLemma extractMin_spec :\n  forall (A : Ord) (l l' : list A) (m : A),\n    extractMin l = Some (m, l') -> forall x : A, In x l' -> m ≤ x.\nProof.\n  intros A l.\n  functional induction extractMin l;\n  inv 1; inv 1; trich.\n    specialize (IHo _ _ e0 _ H0). trich.\n    specialize (IHo _ _ e0 _ H0). trich.\nQed.\n\nLemma Sorted_ss :\n  forall (A : Ord) (l : list A),\n    Sorted trich_le (ss A l).\nProof.\n  intros. functional induction @ss A l.\n    destruct l; trich.\n    apply Sorted_cons.\n      intros. assert (In x l').\n        apply Permutation_in with (ss A l').\n          apply Permutation_ss.\n          assumption.\n        eapply extractMin_spec; eauto.\n      assumption.\nQed.\n\n(** Da ultimate selection sort! *)\n\nFunction mins'\n  {A : Ord} (l : list A) : list A * list A :=\nmatch l with\n    | [] => ([], [])\n    | h :: t =>\n        let\n          (mins, rest) := mins' t\n        in\n          match mins with\n              | [] => ([h], rest)\n              | m :: ms =>\n                  match h <?> m with\n                      | Lt => ([h], mins ++ rest)\n                      | Eq => (h :: mins, rest)\n                      | Gt => (mins, h :: rest)\n                  end\n          end\nend.\n\nLemma mins'_nil :\n  forall (A : Ord) (l rest : list A),\n    mins' l = ([], rest) -> rest = [].\nProof.\n  intros. functional induction mins' l; inv H.\nQed.\n\nLemma mins'_length :\n  forall (A : Ord) (l mins rest : list A),\n    mins' l = (mins, rest) -> length l = length mins + length rest.\nProof.\n  intros A l. functional induction mins' l; inv 1; cbn in *.\n    destruct t; cbn in e0.\n      inv e0.\n      destruct (mins' t), l.\n        inv e0.\n        destruct (c <?> c0); inv e0.\n    1-3: f_equal; rewrite (IHp _ _ e0), ?app_length; cbn; lia.\nQed.\n\nFunction ss_mins'\n  {A : Ord} (l : list A) {measure length l} : list A :=\nmatch mins' l with\n    | ([], _) => []\n    | (mins, rest) => mins ++ ss_mins' rest\nend.\nProof.\n  intros. functional induction mins' l; inv teq; cbn in *.\n    apply mins'_nil in e0. subst. cbn. apply le_n_S, Nat.le_0_l.\n    all: apply mins'_length in e0; cbn in e0;\n      rewrite e0, ?app_length; lia.\nDefined.\n\n(** Time to prove something *)\n\nClass Select (A : Ord) : Type :=\n{\n    select : list A -> list A * list A * list A;\n    select_mins :\n      forall l mins rest maxes : list A,\n        select l = (mins, rest, maxes) ->\n          forall x y : A, In x mins -> In y l -> x ≤ y;\n    select_maxes :\n      forall l mins rest maxes : list A,\n        select l = (mins, rest, maxes) ->\n          forall x y : A, In x l -> In y maxes -> x ≤ y;\n    select_Permutation :\n      forall l mins rest maxes : list A,\n        select l = (mins, rest, maxes) ->\n          Permutation l (mins ++ rest ++ maxes);\n    select_length_rest :\n      forall l mins rest maxes : list A,\n        select l = (mins, rest, maxes) ->\n          mins = [] /\\ rest = [] /\\ maxes = [] \\/\n          lt (length rest) (length l);\n}.\n\nCoercion select : Select >-> Funclass.\n\nSet Warnings \"-unused-pattern-matching-variable\". (* Line 166 - bug in Coq? *)\nFunction gss\n  {A : Ord} (s : Select A) (l : list A)\n  {measure length l} : list A :=\nmatch select l with\n    | ([], [], []) => []\n    | (mins, rest, maxes) =>\n        mins ++ gss s rest ++ maxes\nend.\nProof.\n  all: intros; subst;\n  apply select_length_rest in teq;\n  decompose [and or] teq; clear teq;\n  try congruence; try assumption.\nDefined.\nSet Warnings \"unused-pattern-matching-variable\".\n\nLemma Permutation_gss :\n  forall (A : Ord) (s : Select A) (l : list A),\n    Permutation (gss s l) l.\nProof.\n  intros. functional induction @gss A s l.\n    apply select_Permutation in e. cbn in e. symmetry. assumption.\n    rewrite IHl0. symmetry. apply select_Permutation. assumption.\nQed.\n\nLemma select_In :\n  forall (A : Ord) (s : Select A) (l mins rest maxes : list A) (x : A),\n    select l = (mins, rest, maxes) ->\n      In x mins \\/ In x rest \\/ In x maxes -> In x l.\nProof.\n  intros. eapply Permutation_in.\n    symmetry. apply select_Permutation. eassumption.\n    apply in_or_app. decompose [or] H0; clear H0.\n      left. assumption.\n      right. apply in_or_app. left. assumption.\n      right. apply in_or_app. right. assumption.\nQed.\n\nLemma select_mins_maxes :\n  forall (A : Ord) (s : Select A) (l mins rest maxes : list A),\n    select l = (mins, rest, maxes) ->\n      forall x y : A, In x mins -> In y maxes -> x ≤ y.\nProof.\n  intros. eapply select_mins; try eassumption.\n  eapply select_In; eauto.\nQed.\n\nLemma select_mins_same :\n  forall (A : Ord) (s : Select A) (l mins rest maxes : list A),\n    select l = (mins, rest, maxes) ->\n      forall x y : A, In x mins -> In y mins -> x = y.\nProof.\n  intros. apply trich_le_antisym.\n    eapply select_mins; eauto. eapply select_In; eauto.\n    eapply select_mins; eauto. eapply select_In; eauto.\nQed.\n\nLemma select_maxes_same :\n  forall (A : Ord) (s : Select A) (l mins rest maxes : list A),\n    select l = (mins, rest, maxes) ->\n      forall x y : A, In x maxes -> In y maxes -> x = y.\nProof.\n  intros. apply trich_le_antisym.\n    eapply select_maxes; eauto. eapply select_In; eauto.\n    eapply select_maxes; eauto. eapply select_In; eauto.\nQed.\n\nLemma same_Sorted :\n  forall (A : Ord) (x : A) (l : list A),\n    (forall y : A, In y l -> x = y) ->\n      Sorted trich_le l.\nProof.\n  intros A x.\n  induction l as [| h t]; cbn; intros.\n    constructor.\n    specialize (IHt ltac:(auto)). change (Sorted trich_le ([h] ++ t)).\n      apply Sorted_app.\n        constructor.\n        assumption.\n        assert (x = h) by auto; subst. inv 1.\n          intro. right. apply H. auto.\n          inv H1.\nQed.\n\nLemma Sorted_select_mins :\n  forall (A : Ord) (s : Select A) (l mins rest maxes : list A),\n    select l = (mins, rest, maxes) -> Sorted trich_le mins.\nProof.\n  destruct mins; intros.\n    constructor.\n    apply same_Sorted with c. intros. eapply select_mins_same.\n      exact H.\n      left. reflexivity.\n      assumption.\nQed.\n\nLemma Sorted_select_maxes :\n  forall (A : Ord) (s : Select A) (l mins rest maxes : list A),\n    select l = (mins, rest, maxes) -> Sorted trich_le maxes.\nProof.\n  destruct maxes; intros.\n    constructor.\n    apply same_Sorted with c. intros. eapply select_maxes_same.\n      exact H.\n      left. reflexivity.\n      assumption.\nQed.\n\nLemma gss_In :\n  forall (A : Ord) (s : Select A) (x : A) (l : list A),\n    In x (gss s l) <-> In x l.\nProof.\n  intros. split; intros.\n    eapply Permutation_in.\n      apply Permutation_gss.\n      assumption.\n    eapply Permutation_in.\n      symmetry. apply Permutation_gss.\n      assumption.\nQed.\n\nLemma gSorted_ss :\n  forall (A : Ord) (s : Select A) (l : list A),\n    Sorted trich_le (gss s l).\nProof.\n  intros. functional induction @gss A s l; try clear y.\n    constructor.\n    apply Sorted_app.\n      eapply Sorted_select_mins. eassumption.\n      apply Sorted_app.\n        assumption.\n        eapply Sorted_select_maxes. eassumption.\n        intros. rewrite gss_In in H. eapply select_maxes; eauto.\n          eapply select_In; eauto.\n      intros. apply in_app_or in H0. destruct H0.\n        rewrite gss_In in H0. eapply select_mins; try eassumption.\n          eapply select_In; eauto.\n        eapply select_mins_maxes; eauto.\nQed.\n\n#[refine]\n#[export]\nInstance Sort_gss (A : Ord) (s : Select A) : Sort trich_le :=\n{\n    sort := gss s;\n    Sorted_sort := gSorted_ss s;\n}.\nProof.\n  intros. apply Permutation_gss.\nDefined.\n\nLemma min_dflt_spec :\n  forall (A : Ord) (x h : A) (t : list A),\n    In x (h :: t) -> min_dflt A h t ≤ x.\nProof.\n  intros until t. revert x h.\n  induction t as [| h' t']; simpl in *.\n    inv 1; trich.\n    destruct 1 as [H1 | [H2 | H3]]; subst.\n      trich. specialize (IHt' x x ltac:(left; reflexivity)). trich.\n      trich. specialize (IHt' x x ltac:(left; reflexivity)). trich.\n      trich. pose (IH1 := IHt' h h ltac:(auto)). pose (IH2 := IHt' x h ltac:(auto)). trich.\nQed.\n\n(*\nLemma min_In :\n  forall (A : Ord) (m : A) (l : list A),\n    trich_min l = Some m -> In m l.\nProof.\n  intros. functional induction min l; cbn; inv H.\nQed.\n\nLemma lengthOrder_removeFirst_min :\n  forall (A : Ord) (m : A) (l : list A),\n    min l = Some m -> lengthOrder (removeFirst m l) l.\nProof.\n  intros. functional induction min l; inv H; trich; red; cbn; try lia.\n    rewrite <- Nat.succ_lt_mono. apply IHo. assumption.\nQed.\n\n#[refine]\n#[export]\nInstance Select_min (A : Ord) : Select A :=\n{\n    select l :=\n      match min l with\n          | None => ([], [], [])\n          | Some m => ([m], removeFirst m l, [])\n      end;\n}.\nProof.\n  all: intros; destruct (min l) eqn: Hc; inv H.\n    inv H0. eapply min_spec; eauto.\n    rewrite app_nil_r. cbn.\n      apply perm_Permutation, removeFirst_In_perm, min_In, Hc.\n    destruct l; cbn in *.\n      reflexivity.\n      destruct (min l); inv Hc.\n    right. apply lengthOrder_removeFirst_min. assumption.\nDefined.\n*)", "meta": {"author": "wkolowski", "repo": "coq-algs", "sha": "ee6c656314e3d93e3029dd5f845cfb5352c1b089", "save_path": "github-repos/coq/wkolowski-coq-algs", "path": "github-repos/coq/wkolowski-coq-algs/coq-algs-ee6c656314e3d93e3029dd5f845cfb5352c1b089/Sorting/SelectionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7083018993523784}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(*i $Id: Sumbool.v 14641 2011-11-06 11:59:10Z herbelin $ i*)\n\n(** Here are collected some results about the type sumbool (see INIT/Specif.v)\n   [sumbool A B], which is written [{A}+{B}], is the informative\n   disjunction \"A or B\", where A and B are logical propositions.\n   Its extraction is isomorphic to the type of booleans. *)\n\n(** A boolean is either [true] or [false], and this is decidable *)\n\nDefinition sumbool_of_bool : forall b:bool, {b = true} + {b = false}.\n  destruct b; auto.\nDefined.\n\nHint Resolve sumbool_of_bool: bool.\n\nDefinition bool_eq_rec :\n  forall (b:bool) (P:bool -> Set),\n    (b = true -> P true) -> (b = false -> P false) -> P b.\n  destruct b; auto.\nDefined.\n\nDefinition bool_eq_ind :\n  forall (b:bool) (P:bool -> Prop),\n    (b = true -> P true) -> (b = false -> P false) -> P b.\n  destruct b; auto.\nDefined.\n\n\n(** Logic connectives on type [sumbool] *)\n\nSection connectives.\n\n  Variables A B C D : Prop.\n\n  Hypothesis H1 : {A} + {B}.\n  Hypothesis H2 : {C} + {D}.\n\n  Definition sumbool_and : {A /\\ C} + {B \\/ D}.\n    case H1; case H2; auto.\n  Defined.\n\n  Definition sumbool_or : {A \\/ C} + {B /\\ D}.\n    case H1; case H2; auto.\n  Defined.\n\n  Definition sumbool_not : {B} + {A}.\n    case H1; auto.\n  Defined.\n\nEnd connectives.\n\nHint Resolve sumbool_and sumbool_or: core.\nHint Immediate sumbool_not : core.\n\n(** Any decidability function in type [sumbool] can be turned into a function\n    returning a boolean with the corresponding specification: *)\n\nDefinition bool_of_sumbool :\n  forall A B:Prop, {A} + {B} -> {b : bool | if b then A else B}.\n  intros A B H.\n  elim H; intro; [exists true | exists false]; assumption.\nDefined.\nImplicit Arguments bool_of_sumbool.", "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/theories/Bool/Sumbool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579722, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7083018891486978}}
{"text": "(* Code for Software Foundations, Chapter 7: Logic: Logic in Coq *)\n\nRequire Import Arith.\nRequire Import Arith.Even.\nRequire Import List.\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Poly.\nRequire Import Tactics.\n\n(* and_exercise *)\n\nExample and_exercise :\n  forall n m : nat, n + m = O -> n = O /\\ m = O.\nProof.\n  induction n, m.\n  + simpl; intros; split; assumption.\n  + simpl; intros; split; [reflexivity | assumption].\n  + simpl; inversion 1.\n  + simpl; inversion 1.\nQed.\n\n(* and_assoc *)\n\nTheorem and_assoc :\n  forall P Q R : Prop, P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [p [q r]].\n  repeat split; assumption.\nQed.\n\n(* mult_eq_O *)\n\nTheorem mult_eq_O :\n  forall n m, n * m = O -> n = 0 \\/ m = 0.\nProof.\n  induction n, m.\n  + simpl; left; reflexivity.\n  + simpl; left; reflexivity.\n  + simpl; right; reflexivity.\n  + simpl; inversion 1.\nQed.\n\n(* or_commut *)\n\nTheorem or_commut :\n  forall P Q, P \\/ Q -> Q \\/ P.\nProof.\n  intros P Q [p | q].\n  + right; assumption.\n  + left; assumption.\nQed.\n\n(* ex_falso_quodlibet *)\n\nTheorem ex_falso_quodlibet :\n  forall P : Prop, False -> P.\nProof.\n  intros P false.\n  apply False_ind; assumption. (* or: \"elim false.\" *)\nQed.\n\n(* not_implies_our_not *)\n\nFact not_implies_our_not :\n  forall P, ~ P -> (forall Q, P -> Q).\nProof.\n  intros P negp Q p.\n  elim negp; apply p.\nQed.\n\n(* zero_not_one *)\n\nTheorem zero_not_one :\n  ~ (0 = 1).\nProof.\n  intros contradiction.\n  inversion contradiction.\nQed.\n\n(* double_neg_inf *)\n\nTheorem double_neg_inf :\n  forall P : Prop, P -> ~ ~ P.\nProof.\n  intros P p negp.\n  elim negp; apply p.\nQed.\n\n(* contrapositive *)\n\nTheorem contrapositive :\n  forall P Q : Prop, (P -> Q) -> (~ Q -> ~ P).\nProof.\n  intros P Q h1 h2 h3.\n  elim h2.\n  apply h1; apply h3.\nQed.\n\n(* not_both_true_and_false *)\n\nTheorem not_both_true_and_false :\n  forall P : Prop, ~ (P /\\ ~ P).\nProof.\n  intros P contradiction.\n  inversion contradiction as [p negp].\n  elim negp; apply p.\nQed.\n\n(* iff_properties *)\n\nTheorem iff_refl :\n  forall P : Prop, P <-> P.\nProof.\n  reflexivity.\nQed.\n\nTheorem iff_trans :\n  forall P Q R : Prop, (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros P Q R h1 h2.\n  split.\n  + intros p.\n    apply h2; apply h1; assumption.\n  + intros r.\n    apply h1; apply h2; assumption.\nQed.\n\n(* or_distributes_over_and *)\n\nTheorem or_distributes_over_and :\n  forall P Q R : Prop, P \\/ (Q /\\ R) <-> (P \\/ Q) /\\ (P \\/ R).\nProof.\n  intros P Q R.\n  split.\n  + intros [p | [q r]].\n    * split; left; assumption.\n    * split; right; assumption.\n  + intros [[p1 | q] [p2 | r]]. (* Important !! *)\n    * left; assumption.\n    * left; assumption.\n    * left; assumption.\n    * right; split; assumption.\nQed.\n\n(* dist_not_exists *)\n\nTheorem dist_not_exists :\n  forall (X : Type) (P : X -> Prop), (\n    forall x, P x) -> ~ (\n      exists x, ~ P x).\nProof.\n  intros X P h1 h2.\n  elim h2.\n  intros x h3.\n  elim h3.\n  apply h1.\nQed.\n\n(* dist_exists_or *)\n\nTheorem dist_exists_or :\n  forall (X : Type) (P Q : X -> Prop), (\n    exists x, P x \\/ Q x) <-> (\n      exists x, P x) \\/ (\n        exists x, Q x).\nProof.\n  intros X P Q.\n  split.\n  + intros h1.\n    elim h1.\n    intros x [hp | hq].\n    - left; exists x; assumption.\n    - right; exists x; assumption.\n  + intros [hp | hq].\n    - elim hp.\n      intros x p.\n      exists x; left; assumption.\n    - elim hq.\n      intros x p.\n      exists x; right; assumption.\nQed.\n\n(* in_application *)\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n    | nil   => False\n    | t::ts => x = t \\/ In x ts\n  end.\n\n(* in_map_iff *)\n\nLemma in_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l -> In (f x) (map f l).\nProof.\n  induction l.\n  + simpl; trivial.\n  + simpl.\n    intros x [hx_eq_a | hx_in_l].\n    - left; rewrite hx_eq_a; reflexivity.\n    - right; apply IHl; assumption.\nQed.\n\nLemma 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.\n  split.\n  + intros h1.\n    induction l as [|x l].\n    - simpl in h1.\n      elim h1.\n    - induction h1 as [|h1].\n      * exists x.\n        split;\n          [ rewrite H\n          | simpl; left\n          ]; reflexivity.\n      * apply IHl in h1.\n        destruct h1 as [x' h1].\n        exists x'.\n        split;\n          [ apply h1\n          | simpl; right; apply h1\n          ].\n  + intros [x [h1 h2]].\n    simpl.\n    induction l as [|a l].\n    - simpl.\n      inversion h2.\n    - simpl in h2.\n      destruct h2 as [h2l | h2r].\n      * simpl.\n        rewrite h2l in h1.\n        rewrite h1.\n        left; reflexivity.\n      * simpl.\n        right; apply IHl; apply h2r.\nQed.\n\n(* in_app_iff *)\n\nLemma logic_or_comm :\n  forall A B C D : Prop, A \\/ B \\/ C \\/ D -> (A \\/ B) \\/ C \\/ D.\nProof.\n  intros A B C D [a | [b | [c | d]]].\n  + left; left; assumption.\n  + left; right; assumption.\n  + right; left; assumption.\n  + right; right; assumption.\nQed.\n\nLemma in_app_iff :\n  forall A l l' (a : A), In a (l ++ l') <-> In a l \\/ In a l'.\nProof.\n  split; induction l, l'.\n  + simpl. inversion 1.\n  + simpl.\n    intros h1.\n    right; assumption.\n  + simpl.\n    intros [h1 | h2].\n    * left; left; assumption.\n    * apply IHl in h2.\n      destruct h2 as [h3 | h4].\n      - left; right; assumption.\n      - inversion h4.\n  + simpl.\n    simpl in IHl.\n    intros [h1 | h2].\n    * left; left; assumption.\n    * apply IHl in h2.\n      destruct h2 as [h3 | [h4 | h5]].\n      - left; right; assumption.\n      - right; left; assumption.\n      - right; right; assumption.\n  + intros [h1 | h2].\n    * inversion h1.\n    * inversion h2.\n  + simpl.\n    intros [h1 | [h2 | h3]].\n    * inversion h1.\n    * left; assumption.\n    * right; assumption.\n  + simpl.\n    intros [[h1 | h2] | h3].\n    * left; assumption.\n    * right; rewrite app_nil_r; assumption.\n    * inversion h3.\n  + simpl.\n    intros [[h1 | h2] | [h3 | h4]].\n    * left; assumption.\n    * right.\n      apply IHl.\n      left; assumption.\n    * right.\n      apply IHl.\n      simpl.\n      right; left; assumption.\n    * right.\n      apply IHl.\n      simpl.\n      right; right; assumption.\nQed.\n\n(* all *)\n\nFixpoint All {T} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n    | nil   => True\n    | x::xs => P x /\\ All P xs\n  end.\n\nLemma All_In :\n  forall T (P : T -> Prop) (l : list T), (\n    forall x, In x l -> P x) <-> All P l.\nProof.\n  split; induction l as [|a l].\n  + intros h1.\n    simpl; trivial.\n  + simpl.\n    intros h1.\n    split.\n    - apply h1.\n      left; reflexivity.\n    - apply IHl.\n      intros x h2.\n      apply h1.\n      right; assumption.\n  + intros h1 x h2.\n    inversion h2.\n  + simpl.\n    intros [h1 h2] x [h3 | h4].\n    - rewrite h3; assumption.\n    - apply IHl; assumption.\nQed.\n\n(* combine_odd_even *)\n\nDefinition combine_odd_even (P Q : nat -> Prop) : nat -> Prop :=\n  fun (x : nat) => match Nat.even x with\n    | true  => P x\n    | false => Q x\n  end.\n\nTheorem combine_odd_even_intro :\n  forall (P Q : nat -> Prop) (n : nat),\n    (Nat.even n = true -> P n)\n      -> (Nat.even n = false -> Q n)\n        -> combine_odd_even P Q n.\nProof.\n  intros P Q n h1 h2.\n  unfold combine_odd_even.\n  destruct (Nat.even n).\n  + apply h1; reflexivity.\n  + apply h2; reflexivity.\nQed.\n\nTheorem combine_odd_even_elim_odd :\n  forall (P Q : nat -> Prop) (n : nat),\n    combine_odd_even P Q n -> Nat.even n = true -> P n.\nProof.\n  intros P Q n h1 h2.\n  unfold combine_odd_even in h1.\n  destruct (Nat.even n).\n  + assumption.\n  + inversion h2.\nQed.\n\nTheorem combine_odd_even_elim_even :\n  forall (P Q : nat -> Prop) (n : nat),\n    combine_odd_even P Q n -> Nat.even n = false -> Q n.\nProof.\n  intros P Q n h1 h2.\n  unfold combine_odd_even in h1.\n  destruct (Nat.even n).\n  + inversion h2.\n  + assumption.\nQed.\n\n(* tr_rev *)\n\nFixpoint tr_rev_aux {X} (l1 l2 : list X) : list X :=\n  match l1 with\n    | nil    => l2\n    | x::l1' => tr_rev_aux l1' (x::l2)\n  end.\n\nDefinition tr_rev {X} (l : list X) : list X :=\n  tr_rev_aux l nil.\n\nLemma tr_rev_aux_correct :\n  forall (X : Type) (l1 l2 : list X), tr_rev_aux l1 l2 = tr_rev_aux l1 nil ++ l2.\nProof.\n  induction l1 as [|a l1].\n  + simpl; reflexivity.\n  + intros l2.\n    simpl.\n    rewrite (IHl1 (a::nil)).\n    rewrite (IHl1 (a::l2)).\n    rewrite <- app_assoc.\n    simpl; reflexivity.\nQed.\n\nTheorem tr_rev_correct :\n  forall X, @tr_rev X = @rev X.\nProof.\n  intros X.\n  apply functional_extensionality.\n  unfold tr_rev.\n  induction x as [|x l].\n  + simpl; reflexivity.\n  + simpl.\n    rewrite <- IHl.\n    apply tr_rev_aux_correct.\nQed.\n\n(* evenb_double *)\n\nLemma succ_transfer :\n  forall n : nat, n + S (S n) = S n + S n.\nProof.\n  induction n as [|n].\n  + reflexivity.\n  + simpl.\n    rewrite Nat.add_succ_r.\n    reflexivity.\nQed.\n\nTheorem evenb_double :\n  forall k, Nat.even (Nat.double k) = true.\nProof.\n  induction k as [|k].\n  + reflexivity.\n  + simpl.\n    destruct k as [|k'] eqn:k_ind.\n    - simpl; reflexivity.\n    - simpl.\n      rewrite succ_transfer.\n      apply IHk.\nQed.\n\n(* evenb_double_conv *)\n\nTheorem evenb_double_conv :\n  forall n,\n    exists k, n = if Nat.even n\n      then Nat.double k\n      else S (Nat.double k).\nProof.\n  induction n as [|n].\n  + exists O; reflexivity.\n  + rewrite Nat.even_succ. (* The KEY step. *)\n    destruct IHn as [x IHx].\n    destruct (Nat.even n) eqn:x_odd_even.\n    - exists x.\n      rewrite <- IHx.\n      assert (n_odd_even : Nat.even n = true -> Nat.odd n = false).\n      * unfold Nat.odd; intros h1; rewrite h1; reflexivity.\n      * rewrite n_odd_even;\n          [ reflexivity\n          | assumption\n          ].\n    - exists (S x).\n      assert (n_odd_even : Nat.even n = false -> Nat.odd n = true).\n      * unfold Nat.odd; intros h1; rewrite h1; reflexivity.\n      * { rewrite n_odd_even.\n          + rewrite IHx; unfold Nat.double.\n            simpl.\n            apply eq_S; rewrite Nat.add_succ_r; reflexivity.\n          + assumption.\n        }\nQed.\n\n(* even_bool_prop *)\n\nTheorem even_bool_prop :\n  forall n, Nat.even n = true <->\n    exists k, n = Nat.double k.\nProof.\n  intros n.\n  split.\n  + intros h1.\n    destruct (evenb_double_conv n) as [k Hk]. (* The KEY step. *)\n    rewrite Hk.\n    exists k.\n    rewrite h1; reflexivity.\n  + intros [k Hk].\n    rewrite Hk.\n    apply evenb_double.\nQed.\n\n(* beq_nat_true_iff *)\n\nTheorem beq_nat_true_iff :\n  forall n1 n2, beq_nat n1 n2 = true <-> n1 = n2.\nProof.\n  split.\n  + apply beq_nat_true.\n  + intros h1.\n    rewrite h1.\n    rewrite <- beq_nat_refl; reflexivity.\nQed.\n\n(* logical_connectives *)\n\nTheorem andb_true_iff :\n  forall b1 b2 : bool, andb b1 b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  split.\n  + induction b1, b2.\n    - simpl; split; reflexivity.\n    - simpl; split; [reflexivity | assumption].\n    - simpl; split; [assumption | reflexivity].\n    - simpl; split; assumption.\n  + intros [h1 h2].\n    rewrite h1; rewrite h2; simpl; reflexivity.\nQed.\n\nTheorem orb_true_iff :\n  forall b1 b2 : bool, orb b1 b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  split.\n  + induction b1, b2.\n    - simpl; left; reflexivity.\n    - simpl; left; reflexivity.\n    - simpl; right; reflexivity.\n    - inversion 1.\n  + intros [h1 | h2].\n    - rewrite h1; reflexivity.\n    - rewrite h2.\n      destruct b1.\n      * reflexivity.\n      * reflexivity.\nQed.\n\n(* beq_nat_false_iff *)\n\nTheorem beq_nat_false_iff :\n  forall x y : nat, beq_nat x y = false <-> x <> y.\nProof.\n  intros x y.\n  split.\n  + intros h1 h2.\n    rewrite h2 in h1.\n    rewrite <- beq_nat_refl in h1.\n    inversion h1.\n  + intros h1.\n    destruct (beq_nat x y) eqn:x_eq_y.\n    - apply beq_nat_true in x_eq_y.\n      elim h1; assumption.\n    - reflexivity.\nQed.\n\n(* beq_list *)\n\nFixpoint beq_list {A : Type} (beq : A -> A -> bool) (l1 l2 : list A) : bool :=\n  match l1, l2 with\n    | nil, nil       => true\n    | x::l1', y::l2' => beq x y && beq_list beq l1' l2'\n    | _, _           => false\n  end.\n\nTheorem beq_list_true_iff :\n  forall (A : Type) (beq : A -> A -> bool), (\n    forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->\n      forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.\nProof.\n  intros A beq h1.\n  induction l1 as [|a l1].\n  + induction l2 as [|b l2].\n    - split; reflexivity.\n    - split; intros h2; inversion h2.\n  + induction l2 as [|b l2].\n    - split; inversion 1.\n    - simpl; split.\n      * intros h2.\n        apply andb_true_iff in h2.\n        destruct h2 as [h2 h3].\n        apply h1 in h2.\n        apply IHl1 in h3.\n        rewrite h2; rewrite h3; reflexivity.\n      * intros h2.\n        apply andb_true_iff.\n        injection h2 as h2 h3.\n        rewrite h2; rewrite <- h3.\n        split; [apply h1 | apply IHl1]; reflexivity.\nQed.\n\n(* All_forallb *)\n\nFixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=\n  match l with\n    | nil   => true\n    | x::l' => test x && forallb test l'\n  end.\n\nTheorem forallb_true_iff :\n  forall X test (l : list X), forallb test l = true <-> All (fun x => test x = true) l.\nProof.\n  induction l.\n  + simpl; split; [ trivial | reflexivity ].\n  + simpl; split.\n    * intros h1; apply andb_true_iff in h1; destruct h1 as [h1 h2]; split.\n      - assumption.\n      - apply IHl; assumption.\n    * intros [h1 h2].\n      apply andb_true_iff.\n      split.\n      - assumption.\n      - apply IHl in h2; assumption.\nQed.\n\n(* restricted_excluded_middle *)\n\nDefinition excluded_middle := forall P : Prop, P \\/ ~ P.\n\nTheorem restricted_excluded_middle :\n  forall P b, (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P b h1.\n  destruct b eqn:b_value.\n  - left; apply h1; reflexivity.\n  - right; rewrite h1; inversion 1.\nQed.\n\n(* excluded_middle_irrefutable *)\n\nTheorem excluded_middle_irrefutable :\n  forall P : Prop, ~ ~ (P \\/ ~ P).\nProof.\n  unfold not; intros P h1.\n  apply h1.\n  right. intros p. apply h1.\n  left; apply p.\nQed.\n\n(* not_exist_dist *)\n\nTheorem not_exist_dist :\n  excluded_middle ->\n    forall (X : Type) (P : X -> Prop), ~ (\n      exists x, ~ P x) -> (\n        forall x, P x).\nProof.\n  unfold excluded_middle.\n  intros em X P h1 x.\n  destruct (em (P x)) as [p | negp].\n  + assumption.\n  + elim h1.\n    exists x; assumption.\nQed.\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/software-foundations/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7083018891486978}}
{"text": "(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>\n  * Chapter 8: Lambda Calculus and Simple Type Soundness\n  * Author: Adam Chlipala\n  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)\n\nRequire Import Frap.\n\n(* The last few chapters have focused on small programming languages that are\n * representative of the essence of the imperative languages.  We now turn to\n * lambda-calculus, the usual representative of functional languages. *)\n\nModule Ulc.\n  Inductive exp : Set :=\n  | Var (x : var)\n  | Abs (x : var) (body : exp)\n  | App (e1 e2 : exp).\n\n  Fixpoint subst (rep : exp) (x : var) (e : exp) : exp :=\n    match e with\n    | Var y => if y ==v x then rep else Var y\n    | Abs y e1 => Abs y (if y ==v x then e1 else subst rep x e1)\n    | App e1 e2 => App (subst rep x e1) (subst rep x e2)\n    end.\n\n\n  (** * Big-step semantics *)\n\n  Inductive eval : exp -> exp -> Prop :=\n  | BigAbs : forall x e,\n    eval (Abs x e) (Abs x e)\n  | BigApp : forall e1 x e1' e2 v2 v,\n    eval e1 (Abs x e1')\n    -> eval e2 v2\n    -> eval (subst v2 x e1') v\n    -> eval (App e1 e2) v.\n\n  Inductive value : exp -> Prop :=\n  | Value : forall x e, value (Abs x e).\n\n  Hint Constructors eval value.\n\n  Theorem value_eval : forall v,\n    value v\n    -> eval v v.\n  Proof.\n    invert 1; eauto.\n  Qed.\n\n  Hint Resolve value_eval.\n\n  Theorem eval_value : forall e v,\n    eval e v\n    -> value v.\n  Proof.\n    induct 1; eauto.\n  Qed.\n\n  Hint Resolve eval_value.\n\n  (* Some notations, to let us write more normal-looking lambda terms *)\n  Coercion Var : var >-> exp.\n  Notation \"\\ x , e\" := (Abs x e) (at level 50).\n  Infix \"@\" := App (at level 49, left associativity).\n\n  (* Believe it or not, this is a Turing-complete language!  Here's an example\n   * nonterminating program. *)\n  Example omega := (\\\"x\", \"x\" @ \"x\") @ (\\\"x\", \"x\" @ \"x\").\n\n\n  (** * Church Numerals, everyone's favorite example of lambda terms in\n      * action *)\n\n  (* Here are two curious definitions. *)\n  Definition zero := \\\"f\", \\\"x\", \"x\".\n  Definition plus1 := \\\"n\", \\\"f\", \\\"x\", \"f\" @ (\"n\" @ \"f\" @ \"x\").\n\n  (* We can build up any natural number [n] as [plus1^n @ zero].  Let's prove\n   * that, in fact, these definitions constitute a workable embedding of the\n   * natural numbers in lambda-calculus. *)\n\n  (* A term [plus^n @ zero] evaluates to something very close to what this\n   * function returns. *)\n  Fixpoint canonical' (n : nat) : exp :=\n    match n with\n    | O => \"x\"\n    | S n' => \"f\" @ ((\\\"f\", \\\"x\", canonical' n') @ \"f\" @ \"x\")\n    end.\n\n  (* This missing piece is this wrapper. *)\n  Definition canonical n := \\\"f\", \\\"x\", canonical' n.\n\n  (* Let's formalize our definition of what it means to represent a number. *)\n  Definition represents (e : exp) (n : nat) :=\n    eval e (canonical n).\n\n  (* Zero passes the test. *)\n  Theorem zero_ok : represents zero 0.\n  Proof.\n    unfold zero, represents, canonical.\n    simplify.\n    econstructor.\n  Qed.\n\n  (* So does our successor operation. *)\n  Theorem plus1_ok : forall e n, represents e n\n                                 -> represents (plus1 @ e) (S n).\n  Proof.\n    unfold plus1, represents, canonical; simplify.\n    econstructor.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n  Qed.\n\n  (* What's basically going on here?  The representation of number [n] is [N]\n   * such that, for any function [f]:\n   *   N(f) = f^n\n   * That is, we represent a number as its repeated-composition operator.\n   * So, given a number, we can use it to repeat any operation.  In particular,\n   * to implement addition, we can just repeat [plus1]! *)\n  Definition add := \\\"n\", \\\"m\", \"n\" @ plus1 @ \"m\".\n\n  (* Our addition works properly on this test case. *)\n  Example add_1_2 : exists v,\n      eval (add @ (plus1 @ zero) @ (plus1 @ (plus1 @ zero))) v\n      /\\ eval (plus1 @ (plus1 @ (plus1 @ zero))) v.\n  Proof.\n    eexists; propositional.\n    repeat (econstructor; simplify).\n    repeat econstructor.\n  Qed.\n\n  (* By the way: since [canonical'] doesn't mention variable \"m\", substituting\n   * for \"m\" has no effect.  This fact will come in handy shortly. *)\n  Lemma subst_m_canonical' : forall m n,\n    subst m \"m\" (canonical' n) = canonical' n.\n  Proof.\n    induct n; simplify; equality.\n  Qed.\n\n  (* This inductive proof is the workhorse for the next result, so let's skip\n   * ahead there. *)\n  Lemma add_ok' : forall m n,\n      eval\n        (subst (\\ \"f\", (\\ \"x\", canonical' m)) \"x\"\n               (subst (\\ \"n\", (\\ \"f\", (\\ \"x\", \"f\" @ ((\"n\" @ \"f\") @ \"x\")))) \"f\"\n                      (canonical' n))) (canonical (n + m)).\n  Proof.\n    induct n; simplify.\n\n    econstructor.\n\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    simplify.\n    eassumption.\n\n    simplify.\n    econstructor.\n  Qed.\n\n  (* [add] properly encodes the usual addition. *)\n  Theorem add_ok : forall n ne m me,\n      represents ne n\n      -> represents me m\n      -> represents (add @ ne @ me) (n + m).\n  Proof.\n    unfold represents; simplify.\n\n    econstructor.\n    econstructor.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    rewrite subst_m_canonical'.\n    apply add_ok'.\n  Qed.\n\n  (* Let's repeat the same exercise for multiplication. *)\n\n  Definition mult := \\\"n\", \\\"m\", \"n\" @ (add @ \"m\") @ zero.\n\n  Example mult_1_2 : exists v,\n      eval (mult @ (plus1 @ zero) @ (plus1 @ (plus1 @ zero))) v\n      /\\ eval (plus1 @ (plus1 @ zero)) v.\n  Proof.\n    eexists; propositional.\n    repeat (econstructor; simplify).\n    repeat econstructor.\n  Qed.\n\n  Lemma mult_ok' : forall m n,\n      eval\n        (subst (\\ \"f\", (\\ \"x\", \"x\")) \"x\"\n               (subst\n                  (\\ \"m\",\n                   ((\\ \"f\", (\\ \"x\", canonical' m)) @\n                                                   (\\ \"n\", (\\ \"f\", (\\ \"x\", \"f\" @ ((\"n\" @ \"f\") @ \"x\"))))) @ \"m\")\n                  \"f\" (canonical' n))) (canonical (n * m)).\n  Proof.\n    induct n; simplify.\n\n    econstructor.\n\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    simplify.\n    eassumption.\n\n    simplify.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    rewrite subst_m_canonical'.\n    apply add_ok'. (* Note the recursive appeal to correctness of [add]. *)\n  Qed.\n\n  Theorem mult_ok : forall n ne m me,\n      represents ne n\n      -> represents me m\n      -> represents (mult @ ne @ me) (n * m).\n  Proof.\n    unfold represents; simplify.\n\n    econstructor.\n    econstructor.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n    eassumption.\n    simplify.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    econstructor.\n    simplify.\n    econstructor.\n    simplify.\n    econstructor.\n    econstructor.\n    simplify.\n    rewrite subst_m_canonical'.\n    apply mult_ok'.\n  Qed.\n\n\n  (** * Small-step semantics with evaluation contexts *)\n\n  Inductive context : Set :=\n  | Hole : context\n  | App1 : context -> exp -> context\n  | App2 : exp -> context -> context.\n\n  Inductive plug : context -> exp -> exp -> Prop :=\n  | PlugHole : forall e,\n    plug Hole e e\n  | PlugApp1 : forall c e1 e2 e,\n    plug c e1 e\n    -> plug (App1 c e2) e1 (App e e2)\n  | PlugApp2 : forall c e1 e2 e,\n    value e1\n    -> plug c e2 e\n    -> plug (App2 e1 c) e2 (App e1 e).\n\n  Inductive step : exp -> exp -> Prop :=\n  | ContextBeta : forall c x e v e1 e2,\n    value v\n    -> plug c (App (Abs x e) v) e1\n    -> plug c (subst v x e) e2\n    -> step e1 e2.\n\n  Hint Constructors plug step.\n\n  (* Here we now go through a proof of equivalence between big- and small-step\n   * semantics, though we won't spend any further commentary on it. *)\n\n  Lemma step_eval'' : forall v c x e e1 e2 v0,\n    value v\n    -> plug c (App (Abs x e) v) e1\n    -> plug c (subst v x e) e2\n    -> eval e2 v0\n    -> eval e1 v0.\n  Proof.\n    induct c; invert 2; invert 1; simplify; eauto.\n    invert H0; eauto.\n    invert H0; eauto.\n  Qed.\n\n  Hint Resolve step_eval''.\n\n  Lemma step_eval' : forall e1 e2,\n    step e1 e2\n    -> forall v, eval e2 v\n      -> eval e1 v.\n  Proof.\n    invert 1; simplify; eauto.\n  Qed.\n\n  Hint Resolve step_eval'.\n\n  Theorem step_eval : forall e v,\n    step^* e v\n    -> value v\n    -> eval e v.\n  Proof.\n    induct 1; eauto.\n  Qed.\n\n  Lemma plug_functional : forall C e e1,\n      plug C e e1\n      -> forall e2, plug C e e2\n                    -> e1 = e2.\n  Proof.\n    induct 1; invert 1; simplify; try f_equal; eauto.\n  Qed.\n\n  Lemma plug_mirror : forall C e e', plug C e e'\n    -> forall e1, exists e1', plug C e1 e1'.\n  Proof.\n    induct 1; simplify; eauto.\n\n    specialize (IHplug e0); first_order; eauto.\n\n    specialize (IHplug e0); first_order; eauto.\n  Qed.\n\n  Fixpoint compose (C1 C2 : context) : context :=\n    match C2 with\n    | Hole => C1\n    | App1 C2' e => App1 (compose C1 C2') e\n    | App2 v C2' => App2 v (compose C1 C2')\n    end.\n\n  Lemma compose_ok : forall C1 C2 e1 e2 e3,\n      plug C1 e1 e2\n      -> plug C2 e2 e3\n      -> plug (compose C1 C2) e1 e3.\n  Proof.\n    induct 2; simplify; eauto.\n  Qed.\n\n  Hint Resolve compose_ok.\n\n  Lemma step_plug : forall e1 e2,\n    step e1 e2\n    -> forall C e1' e2', plug C e1 e1'\n                         -> plug C e2 e2'\n                         -> step e1' e2'.\n  Proof.\n    invert 1; simplify; eauto.\n  Qed.\n\n  Lemma stepStar_plug : forall e1 e2,\n    step^* e1 e2\n    -> forall C e1' e2', plug C e1 e1'\n                         -> plug C e2 e2'\n                         -> step^* e1' e2'.\n  Proof.\n    induct 1; simplify.\n\n    assert (e1' = e2') by (eapply plug_functional; eassumption).\n    subst.\n    constructor.\n\n    assert (exists y', plug C y y') by eauto using plug_mirror.\n    invert H3.\n    eapply step_plug in H.\n    econstructor.\n    eassumption.\n    eapply IHtrc.\n    eassumption.\n    assumption.\n    eassumption.\n    assumption.\n  Qed.\n\n  Hint Resolve stepStar_plug eval_value.\n\n  Theorem eval_step : forall e v,\n    eval e v\n    -> step^* e v.\n  Proof.\n    induct 1; eauto.\n\n    eapply trc_trans.\n    eapply stepStar_plug with (e1 := e1) (e2 := Abs x e1') (C := App1 Hole e2); eauto.\n    eapply trc_trans.\n    eapply stepStar_plug with (e1 := e2) (e2 := v2) (C := App2 (Abs x e1') Hole); eauto.\n    eauto.\n  Qed.\nEnd Ulc.\n\n\nModule Stlc.\n  Inductive exp : Set :=\n  | Var (x : var)\n  | Const (n : nat)\n  | Plus (e1 e2 : exp)\n  | Abs (x : var) (e1 : exp)\n  | App (e1 e2 : exp).\n\n  Inductive value : exp -> Prop :=\n  | VConst : forall n, value (Const n)\n  | VAbs : forall x e1, value (Abs x e1).\n\n  Fixpoint subst (e1 : exp) (x : string) (e2 : exp) : exp :=\n    match e2 with\n      | Var y => if y ==v x then e1 else Var y\n      | Const n => Const n\n      | Plus e2' e2'' => Plus (subst e1 x e2') (subst e1 x e2'')\n      | Abs y e2' => Abs y (if y ==v x then e2' else subst e1 x e2')\n      | App e2' e2'' => App (subst e1 x e2') (subst e1 x e2'')\n    end.\n\n  Inductive context : Set :=\n  | Hole : context\n  | Plus1 : context -> exp -> context\n  | Plus2 : exp -> context -> context\n  | App1 : context -> exp -> context\n  | App2 : exp -> context -> context.\n\n  Inductive plug : context -> exp -> exp -> Prop :=\n  | PlugHole : forall e, plug Hole e e\n  | PlugPlus1 : forall e e' C e2,\n    plug C e e'\n    -> plug (Plus1 C e2) e (Plus e' e2)\n  | PlugPlus2 : forall e e' v1 C,\n    value v1\n    -> plug C e e'\n    -> plug (Plus2 v1 C) e (Plus v1 e')\n  | PlugApp1 : forall e e' C e2,\n    plug C e e'\n    -> plug (App1 C e2) e (App e' e2)\n  | PlugApp2 : forall e e' v1 C,\n    value v1\n    -> plug C e e'\n    -> plug (App2 v1 C) e (App v1 e').\n\n  Inductive step0 : exp -> exp -> Prop :=\n  | Beta : forall x e v,\n    value v\n    -> step0 (App (Abs x e) v) (subst v x e)\n  | Add : forall n1 n2,\n    step0 (Plus (Const n1) (Const n2)) (Const (n1 + n2)).\n\n  Inductive step : exp -> exp -> Prop :=\n  | StepRule : forall C e1 e2 e1' e2',\n    plug C e1 e1'\n    -> plug C e2 e2'\n    -> step0 e1 e2\n    -> step e1' e2'.\n\n  Definition trsys_of (e : exp) := {|\n    Initial := {e};\n    Step := step\n  |}.\n\n\n  Inductive type :=\n  | Nat                  (* Numbers *)\n  | Fun (dom ran : type) (* Functions *).\n\n  Inductive hasty : fmap var type -> exp -> type -> Prop :=\n  | HtVar : forall G x t,\n    G $? x = Some t\n    -> hasty G (Var x) t\n  | HtConst : forall G n,\n    hasty G (Const n) Nat\n  | HtPlus : forall G e1 e2,\n    hasty G e1 Nat\n    -> hasty G e2 Nat\n    -> hasty G (Plus e1 e2) Nat\n  | HtAbs : forall G x e1 t1 t2,\n    hasty (G $+ (x, t1)) e1 t2\n    -> hasty G (Abs x e1) (Fun t1 t2)\n  | HtApp : forall G e1 e2 t1 t2,\n    hasty G e1 (Fun t1 t2)\n    -> hasty G e2 t1\n    -> hasty G (App e1 e2) t2.\n\n  Hint Constructors value plug step0 step hasty.\n\n  (* Some notation to make it more pleasant to write programs *)\n  Infix \"-->\" := Fun (at level 60, right associativity).\n  Coercion Const : nat >-> exp.\n  Infix \"^+^\" := Plus (at level 50).\n  Coercion Var : var >-> exp.\n  Notation \"\\ x , e\" := (Abs x e) (at level 51).\n  Infix \"@\" := App (at level 49, left associativity).\n\n  (* Some examples of typed programs *)\n\n  Example one_plus_one : hasty $0 (1 ^+^ 1) Nat.\n  Proof.\n    repeat (econstructor; simplify).\n  Qed.\n\n  Example add : hasty $0 (\\\"n\", \\\"m\", \"n\" ^+^ \"m\") (Nat --> Nat --> Nat).\n  Proof.\n    repeat (econstructor; simplify).\n  Qed.\n\n  Example eleven : hasty $0 ((\\\"n\", \\\"m\", \"n\" ^+^ \"m\") @ 7 @ 4) Nat.\n  Proof.\n    repeat (econstructor; simplify).\n  Qed.\n\n  Example seven_the_long_way : hasty $0 ((\\\"x\", \"x\") @ (\\\"x\", \"x\") @ 7) Nat.\n  Proof.\n    repeat (econstructor; simplify).\n  Qed.\n\n\n  (** * Let's prove type soundness. *)\n\n  Definition unstuck e := value e\n    \\/ (exists e' : exp, step e e').\n\n  Lemma progress : forall e t,\n    hasty $0 e t\n    -> value e\n    \\/ (exists e' : exp, step e e').\n  Proof.\n    induct 1; simplify; try equality.\n\n    left.\n    constructor.\n\n    propositional.\n\n    right.\n    match goal with\n    | [ H1 : value e1, H2 : hasty $0 e1 _ |- _ ] => invert H1; invert H2\n    end.\n    match goal with\n    | [ H1 : value e2, H2 : hasty $0 e2 _ |- _ ] => invert H1; invert H2\n    end.\n    exists (Const (n + n0)).\n    eapply StepRule with (C := Hole).\n    eauto.\n    eauto.\n    constructor.\n\n    match goal with\n    | [ H : exists x, _ |- _ ] => invert H\n    end.\n    match goal with\n    | [ H : step _ _ |- _ ] => invert H\n    end.\n    right.\n    eauto.\n\n    match goal with\n    | [ H : exists x, _ |- _ ] => invert H\n    end.\n    match goal with\n    | [ H : step _ _ |- _ ] => invert H\n    end.\n    right.\n    eauto.\n\n    match goal with\n    | [ H : exists x, step e1 _ |- _ ] => invert H\n    end.\n    match goal with\n    | [ H : step _ _ |- _ ] => invert H\n    end.\n    right.\n    exists (Plus x e2).\n    eapply StepRule with (C := Plus1 C e2).\n    eauto.\n    eauto.\n    assumption.\n\n    left.\n    constructor.\n\n    propositional.\n\n    right.\n    match goal with\n    | [ H1 : value e1, H2 : hasty $0 e1 _ |- _ ] => invert H1; invert H2\n    end.\n    exists (subst e2 x e0).\n    eapply StepRule with (C := Hole).\n    eauto.\n    eauto.\n    constructor.\n    assumption.\n\n    match goal with\n    | [ H : exists x, _ |- _ ] => invert H\n    end.\n    match goal with\n    | [ H : step _ _ |- _ ] => invert H\n    end.\n    right.\n    eauto.\n\n    match goal with\n    | [ H : exists x, _ |- _ ] => invert H\n    end.\n    match goal with\n    | [ H : step _ _ |- _ ] => invert H\n    end.\n    right.\n    eauto.\n\n    match goal with\n    | [ H : exists x, step e1 _ |- _ ] => invert H\n    end.\n    match goal with\n    | [ H : step _ _ |- _ ] => invert H\n    end.\n    right.\n    exists (App x e2).\n    eapply StepRule with (C := App1 C e2).\n    eauto.\n    eauto.\n    assumption.\n  Qed.\n\n  (* Replacing a typing context with an equal one has no effect (useful to guide\n   * proof search as a hint). *)\n  Lemma hasty_change : forall G e t,\n    hasty G e t\n    -> forall G', G' = G\n      -> hasty G' e t.\n  Proof.\n    induct 1; simplify; constructor || econstructor.\n    rewrite H0, H; equality.\n    rewrite H1. assumption.\n    rewrite H1. assumption.\n    rewrite H0. assumption.\n    rewrite H1. eassumption.\n    rewrite H1. eassumption.\n  Qed.\n\n  Hint Resolve hasty_change.\n\n  Lemma weakening : forall G e t,\n    hasty G e t\n    -> forall G', (forall x t, G $? x = Some t -> G' $? x = Some t)\n      -> hasty G' e t.\n  Proof.\n    induct 1; simplify.\n    constructor. apply H0, H.\n    constructor.\n    constructor; apply IHhasty1 || apply IHhasty2; assumption.\n    constructor. apply IHhasty. simplify. cases (x ==v x0); simplify; eauto.\n    econstructor; apply IHhasty1 || apply IHhasty2; assumption.\n  Qed.\n\n  (* Replacing a variable with a properly typed term preserves typing. *)\n  Lemma substitution : forall G x t' e t e',\n    hasty (G $+ (x, t')) e t\n    -> hasty $0 e' t'\n    -> hasty G (subst e' x e) t.\n  Proof.\n    induct 1; simplify.\n    - cases (x0 ==v x); simplify.\n      * invert H. apply weakening with (G := $0); auto.\n      * constructor. assumption.\n    - constructor.\n    - constructor; (eapply IHhasty1 || eapply IHhasty2); eauto.\n    - constructor. cases (x0 ==v x).\n      * eapply weakening.\n        + eassumption.\n        + simplify. rewrite e. cases (x ==v x1); simplify; assumption.\n      * eapply IHhasty; eauto.\n    - econstructor.\n      * eapply IHhasty1; eauto.\n      * eapply IHhasty2; eauto.\n  Qed.\n\n  Lemma preservation0 : forall e1 e2,\n    step0 e1 e2\n    -> forall t, hasty $0 e1 t\n      -> hasty $0 e2 t.\n  Proof.\n    invert 1; simplify.\n    - invert H.\n      invert H4.\n      eapply substitution; eassumption.\n    - invert H.\n      constructor.\n  Qed.\n\n  Lemma generalize_plug : forall e1 C e1',\n    plug C e1 e1'\n    -> forall e2 e2', plug C e2 e2'\n      -> (forall t, hasty $0 e1 t -> hasty $0 e2 t)\n      -> (forall t, hasty $0 e1' t -> hasty $0 e2' t).\n  Proof.\n    induct 1; simplify.\n\n    - invert H. auto.\n    - invert H0.\n      invert H2.\n      constructor.\n      + eapply IHplug; eassumption.\n      + assumption.\n    - invert H1.\n      invert H3.\n      constructor; try assumption.\n      + eapply IHplug; eassumption.\n    - invert H0.\n      invert H2.\n      econstructor.\n      + eapply IHplug; eassumption.\n      + assumption.\n    - invert H1.\n      invert H3.\n      econstructor.\n      + eassumption.\n      + eapply IHplug; eassumption.\n  Qed.\n\n  Lemma preservation : forall e1 e2,\n    step e1 e2\n    -> forall t, hasty $0 e1 t\n      -> hasty $0 e2 t.\n  Proof.\n    invert 1; simplify.\n    eapply generalize_plug with (e1' := e1).\n    - eassumption.\n    - eassumption.\n    - simplify.\n      eapply preservation0; eassumption.\n    - assumption.\n  Qed.\n\n  Theorem safety : forall e t, hasty $0 e t\n    -> invariantFor (trsys_of e) unstuck.\n  Proof.\n    simplify.\n\n    (* Step 1: strengthen the invariant.  In particular, the typing relation is\n     * exactly the right stronger invariant!  Our progress theorem proves the\n     * required invariant inclusion. *)\n    apply invariant_weaken with (invariant1 := fun e' => hasty $0 e' t).\n\n    (* Step 2: apply invariant induction, whose induction step turns out to match\n     * our preservation theorem exactly! *)\n    apply invariant_induction; simplify.\n    equality.\n\n    eapply preservation.\n    eassumption.\n    assumption.\n\n    simplify.\n    eapply progress.\n    eassumption.\n  Qed.\nEnd Stlc.\n", "meta": {"author": "samtay", "repo": "uw-programming-languages", "sha": "8904613423bddfc295834741fbce7c50ab5dac5d", "save_path": "github-repos/coq/samtay-uw-programming-languages", "path": "github-repos/coq/samtay-uw-programming-languages/uw-programming-languages-8904613423bddfc295834741fbce7c50ab5dac5d/notes/frap-10-lambda-calculus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276107, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.708295827815311}}
{"text": "Require Import study03.\n\nModule study04.\n\nTheorem double_injective : forall n m,\n  double n = double m -> n = m.\nProof. \n  induction n. simpl. induction m. reflexivity.\n  simpl. intros H. inversion H.\n  simpl. induction m. simpl. intros H.\n  inversion H. simpl. intros H.\n  inversion H. apply IHn in H1.\n  rewrite H1. reflexivity.\nQed.\n\nTheorem double_injective_take2 : forall n m,\n  double n = double m -> n = m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m. simpl. induction n.\n  reflexivity. simpl. intros H.\n  inversion H. simpl. induction n.\n  simpl. intros H. inversion H.\n  simpl. intros H. inversion H.\n  apply IHm in H1. rewrite H1.\n  reflexivity.\nQed.\nTheorem plus_n_n_injective_take2 : forall n m,\n     n + n = m + m -> n = m.\nProof.\n  intros n m.\n  generalize dependent n.\n  induction m. induction n.\n  reflexivity. intros H. inversion H.\n  simpl. induction n. intros H.\n  inversion H. simpl. intros H.\n  inversion H. rewrite plus_comm in H1.\n  assert (m+S m=S m+m). apply plus_comm.\n  rewrite H0 in H1. simpl in H1.\n  inversion H1. apply IHm in H3.\n  rewrite H3. reflexivity.\nQed.\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : ImplicitTest.llist X),\nImplicitTest.llength' l = n -> ImplicitTest.lindex' (S n) l = ImplicitTest.lNone'.\nProof.\n  intros n X l.\n  generalize dependent n.\n  induction l. reflexivity.\n  simpl. induction n. intros H.\n  inversion H. intros H.\n  inversion H. rewrite H1.\n  apply IHl. apply H1.\nQed.\nLemma lapp_lcons_lsnoc : forall (X:Type) (l:ImplicitTest.llist X) (v:X),\nImplicitTest.lapp' l (ImplicitTest.lcons' v ImplicitTest.lnil')\n  =ImplicitTest.lsnoc' l v.\nProof.\n  intros X l v. induction l. reflexivity.\n  simpl. rewrite IHl. reflexivity.\nQed. \nTheorem length_snoc''' : forall (n : nat) (X : Type)\n                              (v : X) (l : ImplicitTest.llist X),\n     ImplicitTest.llength' l = n -> ImplicitTest.llength' (ImplicitTest.lsnoc' l v) = S n.\nProof.\n  intros n X v l.\n  generalize dependent n.\n  induction l. simpl.\n  induction n. reflexivity.\n  intros H. inversion H.\n  simpl. induction n.\n  intros H. inversion H.\n  intros H. inversion H.\n  rewrite H1. \n  apply ImplicitTest.study03'.eq_remove_S.\n  rewrite lapp_lcons_lsnoc.\n  apply IHl. apply H1.\nQed.\nNotation \"x :: y\" := (ImplicitTest.lcons' x y) (at level 60, right associativity).\nNotation \"[ ]\" := ImplicitTest.lnil'.\nNotation \"[ x , .. , y ]\" := (ImplicitTest.lcons' x .. (ImplicitTest.lcons' y []) ..).\nNotation \"x ++ y\" := (ImplicitTest.lapp' x y) (at level 60, right associativity).\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : ImplicitTest.llist X)\n                                  (x : X) (n : nat),\n     ImplicitTest.llength' (l1 ++ (x :: l2)) = n ->\n     S (ImplicitTest.llength' (l1 ++ l2)) = n.\nProof.\n  intros X l1 l2 x n.\n  generalize dependent n.\n  generalize dependent l2.\n  induction l1. intros l2 n H.\n  rewrite <- H. reflexivity.\n  simpl. induction n.\n  intros H. inversion H.\n  intros H. inversion H.\n  apply ImplicitTest.study03'.eq_remove_S.\n  rewrite H1. apply IHl1.\n  apply H1.\nQed.\nTheorem app_length_cons_inv : forall (X : Type) (l1 l2 : ImplicitTest.llist X)\n                                  (x : X) (n : nat),\n     S (ImplicitTest.llength' (l1 ++ l2)) = n -> \n     ImplicitTest.llength' (l1 ++ (x :: l2)) = n.\nProof.\n  intros X l1 l2 x n.\n  generalize dependent n.\n  generalize dependent l2.\n  induction l1. intros l2 n H.\n  rewrite <- H. reflexivity.\n  simpl. induction n.\n  intros H. inversion H.\n  intros H. inversion H.\n  apply ImplicitTest.study03'.eq_remove_S.\n  rewrite H1. apply IHl1. apply H1.\nQed.\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:ImplicitTest.llist X),\n  ImplicitTest.llength' l = n -> ImplicitTest.llength' (l ++ l) = n + n.\nProof.\n  intros X n l. generalize dependent n.\n  induction l. simpl. intros n H.\n  rewrite <- H. reflexivity.\n  simpl. induction n.\n  intros H. inversion H.\n  simpl. intros H. inversion H.\n  apply ImplicitTest.study03'.eq_remove_S.\n  rewrite H1. rewrite plus_comm. simpl. \n  apply app_length_cons_inv.\n  apply ImplicitTest.study03'.eq_remove_S.\n  apply IHl. apply H1.\nQed.\n  \nEnd study04.\n  \n", "meta": {"author": "elle-et-noire", "repo": "coq", "sha": "fd253f245131883ee55ff9f1824d4bb417b6e7b7", "save_path": "github-repos/coq/elle-et-noire-coq", "path": "github-repos/coq/elle-et-noire-coq/coq-fd253f245131883ee55ff9f1824d4bb417b6e7b7/study04.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7082958100704935}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) : natural := mult z (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_assoc_108_distrib/goal33conj186_coqofml_D6SfNF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7082860597630252}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := mult y (Succ x).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj62_coqofml_8kwJcE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7082860358159683}}
{"text": "(* *)\nRequire Import Arith.\nRequire Import Omega.\nSet Implicit Arguments.\n\n(*\nSection BinTree.\n\nVariable A : Set.\n\nInductive bintree (A : Set) : Set :=\n  | Leaf : bintree A\n  | Node : bintree A -> nat -> A -> bintree A -> bintree A.\n*)\n\n\n\n(* Dependent types, a type holds a theorem -> Curry Howard Isomorphism *)\nInductive order (x y : nat) : Set :=\n  | LT : x < y -> order x y\n  | EQ : x = y -> order x y\n  | GT : x > y -> order x y.\n\nLemma order_correct :\n  forall m n,\n    order m n -> order (S m) (S n).\n\n  intros.\n  destruct H.\n  apply LT. omega.\n  apply EQ. omega.\n  apply GT. omega.\nQed.\n\n\nFixpoint  compare (m n : nat) : order m n :=\n  match m, n with\n    | 0, 0 => EQ eq_refl\n    | S m', S n' => order_correct (compare m' n')\n    | S _, 0 => GT (gt_Sn_O _)\n    | 0, S _ => LT (lt_0_Sn _)\n  end.\n\n\n", "meta": {"author": "nimishgupta", "repo": "CPDT", "sha": "ce92051b376041833f06327705cf9e5586a3d94c", "save_path": "github-repos/coq/nimishgupta-CPDT", "path": "github-repos/coq/nimishgupta-CPDT/CPDT-ce92051b376041833f06327705cf9e5586a3d94c/Coq/class_30_01_2014.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7082689418978148}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (z : natural) (lf2 : natural) (lf1 : natural)\n  : natural := mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj33_coqofml_jzamUI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7081640134253054}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) (lf2 : natural)\n  : natural := plus Zero (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj187_coqofml_k6f459.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7081611372113451}}
{"text": "(** * MoreCoq: More About Coq *)\n\nRequire Export Poly.\n\n(** This chapter introduces several more proof strategies and tactics that,\n    together, allow us to prove theorems about the functional\n    programs we have been writing. In particular, we'll reason about  \n    functions that work with natural numbers and lists.\n\n    In particular, we will see:\n\n    - how to use auxiliary lemmas, in both forwards and backwards reasoning\n    - how to reason about data constructors, which are injective and disjoint\n    - how to create a strong induction hypotheses (and when strengthening is required)\n    - how to reason by case analysis \n *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  (* At this point, we could finish with \n     \"[rewrite -> eq2. reflexivity.]\" as we have \n     done several times above. But we can achieve the\n     same effect in a single step by using the \n     [apply] tactic instead: *)\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2. \n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\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 H H1. apply H1. Qed.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal _exactly_ -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\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  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since \n            [apply] will perform simplification first. *)\n  apply H.  Qed.         \n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** Hint: you can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend. *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  Are there situations where both can usefully be\n    applied?\n  (* FILL IN HERE *)\n*)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might\n    abstract it out as a lemma recording once and for all\n    the fact that equality is transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. \n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to\n    prove the above example.  However, to do this we need\n    a slight refinement of the [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  (* If we simply tell Coq [apply trans_eq] at this point,\n     it can tell (by matching the goal against the\n     conclusion of the lemma) that it should instantiate [X]\n     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].\n     However, the matching process doesn't determine an\n     instantiation for [m]: we have to supply one explicitly\n     by adding [with (m:=[c,d])] to the invocation of\n     [apply]. *)\n  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.\n\n(**  Actually, we usually don't have to include the name [m]\n    in the [with] clause; Coq is often smart enough to\n    figure out which instantiation we're giving. We could\n    instead write: [apply trans_eq with [c,d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o). \nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [inversion] tactic *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is clear from this definition that every number has one of two\n    forms: either it is the constructor [O] or it is built by applying\n    the constructor [S] to another number.  But there is more here than\n    meets the eye: implicit in the definition (and in our informal\n    understanding of how datatype declarations work in other\n    programming languages) are two other facts:\n\n    - The constructor [S] is _injective_.  That is, the only way we can\n      have [S n = S m] is if [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor is\n    injective and [nil] is different from every non-empty list.  For\n    booleans, [true] and [false] are unequal.  (Since neither [true]\n    nor [false] take any arguments, their injectivity is not an issue.) *)\n\n(** Coq provides a tactic called [inversion] that allows us to exploit\n    these principles in proofs.\n \n    The [inversion] tactic is used like this.  Suppose [H] is a\n    hypothesis in the context (or a previously proven lemma) of the\n    form\n      c a1 a2 ... an = d b1 b2 ... bm\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] instructs Coq to \"invert\" this\n    equality to extract the information it contains about these terms:\n\n    - If [c] and [d] are the same constructor, then we know, by the\n      injectivity of this constructor, that [a1 = b1], [a2 = b2],\n      etc.; [inversion H] adds these facts to the context, and tries\n      to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory.  That is, a false assumption has crept\n      into the context, and this means that any goal whatsoever is\n      provable!  In this case, [inversion H] marks the current goal as\n      completed and pops it off the goal stack. *)\n\n(** The [inversion] tactic is probably easier to understand by\n    seeing it in action than from general descriptions like the above.\n    Below you will find example theorems that demonstrate the use of\n    [inversion] and exercises to test your understanding. *)\n\nTheorem eq_add_S : forall (n m : nat),\n     S n = S m ->\n     n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.  Qed.\n\nTheorem silly4 : forall (n m : nat),\n     [n] = [m] ->\n     n = m.\nProof.\n  intros n o eq. inversion eq. reflexivity.  Qed.\n\n(** As a convenience, the [inversion] tactic can also\n    destruct equalities between complex values, binding\n    multiple variables as it goes. *)\n\nTheorem silly5 : forall (n m o : nat),\n     [n;m] = [o;o] ->\n     [n] = [m].\nProof.\n  intros n m o eq. inversion eq. reflexivity. Qed.\n\n(** **** Exercise: 1 star (sillyex1)  *) \nExample sillyex1 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof.\n  intros X x y z l j H1 H2. inversion H1. inversion H2. rewrite H0. reflexivity. Qed.\n(** [] *)\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n  intros n m contra. inversion contra.  Qed.\n\n(** **** Exercise: 1 star (sillyex2)  *)\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = [] ->\n     y :: l = z :: j ->\n     x = z.\nProof.\n  intros X x y z l j H1 H2. inversion H1. Qed.\n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    [forall (n m : nat), S n = S m -> n = m], the reverse direction of\n    the implication is an instance of a more general fact about\n    constructors and functions, which we will often find useful: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A), \n    x = y -> f x = f y. \nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed. \n\n\n\n\n(** **** Exercise: 2 stars, optional (practice)  *)\n(** A couple more nontrivial but not-too-complicated proofs to work\n    together in class, or for you to work as exercises. *)\n \n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem beq_nat_0_r : forall n,\n   beq_nat n 0 = true -> n = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b. \nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, the tactic [apply L in H] matches some\n    conditional statement [L] (of the form [L1 -> L2], say) against a\n    hypothesis [H] in the context.  However, unlike ordinary\n    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),\n    [apply L in H] matches [H] against [L1] and, if successful,\n    replaces it with [L2].\n \n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\" -- from [L1 -> L2] and a hypothesis matching [L1], it\n    gives us a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\" -- it says that if we know [L1->L2] and we\n    are trying to prove [L2], it suffices to prove [L1].  \n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\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  symmetry in H. apply eq in H. symmetry in H. \n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, Coq tends to favor backward reasoning, but in some\n    situations the forward style can be easier to use or to think\n    about.  *)\n\n(** **** Exercise: 3 stars (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise. *)\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  Case \"n = 0\".\n    destruct m as [| m'].\n    reflexivity. intros. inversion H.\n  Case \"n = S n'\".\n    destruct m as [| m'].\n    simpl. intros. inversion H.\n    simpl. rewrite <- plus_n_Sm. rewrite<- plus_n_Sm.\n    intros. apply f_equal. apply IHn'. inversion H. reflexivity. Qed.\n(** [] *)\n\n(* ###################################################### *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose \n    we want to show that the [double] function is injective -- i.e., \n    that it always maps different arguments to different results:  \n    Theorem double_injective: forall n m, double n = double m -> n = m. \n    The way we _start_ this proof is a little bit delicate: if we \n    begin it with\n      intros n. induction n.\n]] \n    all is well.  But if we begin it with\n      intros n m. induction n.\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = O\". simpl. intros eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". intros eq. destruct m as [| m'].\n    SCase \"m = O\". inversion eq.\n    SCase \"m = S m'\".  apply f_equal. \n      (* Here we are stuck.  The induction hypothesis, [IHn'], does\n         not give us [n' = m'] -- there is an extra [S] in the\n         way -- so the goal is not provable. *)\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context -- \n    intuitively, we have told Coq, \"Let's consider some particular\n    [n] and [m]...\" and we now have to prove that, if [double n =\n    double m] for _this particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove that\n    the proposition\n\n      - [P n]  =  \"if [double n = double m], then [n = m]\"\n\n    holds for all [n] by showing\n\n      - [P O]              \n\n         (i.e., \"if [double O = double m] then [O = m]\")\n\n      - [P n -> P (S n)]  \n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help with proving [R]!  (If we\n    tried to prove [R] from [Q], we would say something like \"Suppose\n    [double (S n) = 10]...\" but then we'd be stuck: knowing that\n    [double (S n)] is [10] tells us nothing about whether [double n]\n    is [10], so [Q] is useless at this point.) *)\n\n(** To summarize: Trying to carry out this proof by induction on [n]\n    when [m] is already in the context doesn't work because we are\n    trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = O\". simpl. intros m eq. destruct m as [| m'].\n    SCase \"m = O\". reflexivity.\n    SCase \"m = S m'\". inversion eq. \n  Case \"n = S n'\". \n    (* Notice that both the goal and the induction\n       hypothesis have changed: the goal asks us to prove\n       something more general (i.e., to prove the\n       statement for _every_ [m]), but the IH is\n       correspondingly more flexible, allowing us to\n       choose any [m] we like when we apply the IH.  *)\n    intros m eq.\n    (* Now we choose a particular [m] and introduce the\n       assumption that [double n = double m].  Since we\n       are doing a case analysis on [n], we need a case\n       analysis on [m] to keep the two \"in sync.\" *)\n    destruct m as [| m'].\n    SCase \"m = O\". \n      (* The 0 case is trivial *)\n      inversion eq.  \n    SCase \"m = S m'\".  \n      apply f_equal. \n      (* At this point, since we are in the second\n         branch of the [destruct m], the [m'] mentioned\n         in the context at this point is actually the\n         predecessor of the one we started out talking\n         about.  Since we are also in the [S] branch of\n         the induction, this is perfect: if we\n         instantiate the generic [m] in the IH with the\n         [m'] that we are talking about right now (this\n         instantiation is performed automatically by\n         [apply]), then [IHn'] gives us exactly what we\n         need to finish the proof. *)\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What this teaches us is that we need to be careful about using\n    induction to try to prove something too specific: If we're proving\n    a property of [n] and [m] by induction on [n], we may need to\n    leave [m] generic. *)\n\n(** The proof of this theorem (left as an exercise) has to be treated similarly: *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    intros. destruct m as [| m'].\n    reflexivity.\n    simpl in H. inversion H.\n  Case \"n = S n'\".\n    intros. destruct m as [| m'].\n    simpl in H. inversion H.\n    simpl in H. apply f_equal. apply IHn'. apply H. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** The strategy of doing fewer [intros] before an [induction] doesn't\n    always work directly; sometimes a little _rearrangement_ of\n    quantified variables is needed.  Suppose, for example, that we\n    wanted to prove [double_injective] by induction on [m] instead of\n    [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  Case \"m = O\". simpl. intros eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq. \n  Case \"m = S m'\". intros eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\".  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce\n    [n] for us!)   *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    will work, but it's not nice: We don't want to have to mangle the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them -- we want to state them in the most clear and\n    natural way. *)\n\n(**  What we can do instead is to first introduce all the\n    quantified variables and then _re-generalize_ one or more of\n    them, taking them out of the context and putting them back at\n    the beginning of the goal.  The [generalize dependent] tactic\n    does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. \n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  Case \"m = O\". simpl. intros n eq. destruct n as [| n'].\n    SCase \"n = O\". reflexivity.\n    SCase \"n = S n'\". inversion eq.\n  Case \"m = S m'\". intros n eq. destruct n as [| n'].\n    SCase \"n = O\". inversion eq.\n    SCase \"n = S n'\". apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n_Theorem_: For any nats [n] and [m], if [double n = double m], then\n  [n = m].\n\n_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n  any [n], if [double n = double m] then [n = m].\n\n  - First, suppose [m = 0], and suppose [n] is a number such\n    that [double n = double m].  We must show that [n = 0].\n\n    Since [m = 0], by the definition of [double] we have [double n =\n    0].  There are two cases to consider for [n].  If [n = 0] we are\n    done, since this is what we wanted to show.  Otherwise, if [n = S\n    n'] for some [n'], we derive a contradiction: by the definition of\n    [double] we would have [double n = S (S (double n'))], but this\n    contradicts the assumption that [double n = 0].\n\n  - Otherwise, suppose [m = S m'] and that [n] is again a number such\n    that [double n = double m].  We must show that [n = S m'], with\n    the induction hypothesis that for every number [s], if [double s =\n    double m'] then [s = m'].\n \n    By the fact that [m = S m'] and the definition of [double], we\n    have [double n = S (S (double m'))].  There are two cases to\n    consider for [n].\n\n    If [n = 0], then by definition [double n = 0], a contradiction.\n    Thus, we may assume that [n = S n'] for some [n'], and again by\n    the definition of [double] we have [S (S (double n')) = S (S\n    (double m'))], which implies by inversion that [double n' = double\n    m'].\n\n    Instantiating the induction hypothesis with [n'] thus allows us to\n    conclude that [n' = m'], and it follows immediately that [S n' = S\n    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted\n    to show. [] *)\n\n\n\n(** Here's another illustration of [inversion] and using an\n    appropriately general induction hypothesis.  This is a slightly\n    roundabout way of stating a fact that we have already proved\n    above.  The extra equalities force us to do a little more\n    equational reasoning and exercise some of the tactics we've seen\n    recently. *)\n\nTheorem length_snoc' : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l. induction l as [| v' l'].\n\n  Case \"l = []\". \n    intros n eq. rewrite <- eq. reflexivity.\n\n  Case \"l = v' :: l'\". \n    intros n eq. simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.\n\n(** It might be tempting to start proving the above theorem\n    by introducing [n] and [eq] at the outset.  However, this leads\n    to an induction hypothesis that is not strong enough.  Compare\n    the above to the following (aborted) attempt: *)\n\nTheorem length_snoc_bad : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l n eq. induction l as [| v' l'].\n\n  Case \"l = []\". \n    rewrite <- eq. reflexivity.\n\n  Case \"l = v' :: l'\". \n    simpl. destruct n as [| n'].\n    SCase \"n = 0\". inversion eq.\n    SCase \"n = S n'\".\n      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)\n\n\n(** As in the double examples, the problem is that by\n    introducing [n] before doing induction on [l], the induction\n    hypothesis is specialized to one particular natural number, namely\n    [n].  In the induction case, however, we need to be able to use\n    the induction hypothesis on some other natural number [n'].\n    Retaining the more general form of the induction hypothesis thus\n    gives us more flexibility.\n\n    In general, a good rule of thumb is to make the induction hypothesis\n    as general as possible. *)\n\n(** **** Exercise: 3 stars (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     index n l = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal)  *)\n(** Write an informal proof corresponding to your Coq proof\n    of [index_after_last]:\n \n     _Theorem_: For all sets [X], lists [l : list X], and numbers\n      [n], if [length l = n] then [index n l = None].\n \n     _Proof_:\n     (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (gen_dep_practice_more)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem length_snoc''' : forall (n : nat) (X : Type) \n                              (v : X) (l : list X),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (app_length_cons)  *)\n(** Prove this by induction on [l1], without using [app_length]\n    from [Lists]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X) \n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice)  *)\n(** Prove this by induction on [l], without using app_length. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars, optional (double_induction)  *)\n(** Prove the following principle of induction over two naturals. *)\n\nTheorem double_induction: forall (P : nat -> nat -> Prop), \n  P 0 0 ->\n  (forall m, P m 0 -> P (S m) 0) ->\n  (forall n, P 0 n -> P 0 (S n)) ->\n  (forall m n, P m n -> P (S m) (S n)) ->\n  forall m n, P m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where the [destruct] tactic is\n    used to perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun. \n  destruct (beq_nat n 3).\n    Case \"beq_nat n 3 = true\". reflexivity.\n    Case \"beq_nat n 3 = false\". destruct (beq_nat n 5).\n      SCase \"beq_nat n 5 = true\". reflexivity.\n      SCase \"beq_nat n 5 = false\". reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,\n    either [n] is equal to [3] or it isn't, so we use [destruct\n    (beq_nat n 3)] to let us reason about the two cases. \n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c].\n\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(** **** Exercise: 3 stars, optional (combine_split)  *)\n(** Complete the proof below *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Sometimes, doing a [destruct] on a compound expression (a\n    non-variable) will erase information we need to complete a proof. *)\n(** For example, suppose\n    we define a function [sillyfun1] like this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** And suppose that we want to convince Coq of the rather\n    obvious observation that [sillyfun1 n] yields [true] only when [n]\n    is odd.  By analogy with the proofs we did with [sillyfun] above,\n    it is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution peformed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that since, in this branch of the case\n    analysis, [beq_nat n 3 = true], it must be that [n = 3], from\n    which it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation (with whatever\n    name we choose). *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got stuck\n    above, except that the context contains an extra equality\n    assumption, which is exactly what we need to make progress. *)\n    Case \"e3 = true\". apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    Case \"e3 = false\".\n     (* When we come to the second equality test in the body of the\n       function we are reasoning about, we can use [eqn:] again in the\n       same way, allow us to finish the proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5. \n        SCase \"e5 = true\".\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        SCase \"e5 = false\". inversion eq.  Qed.\n\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  intros f b. destruct b.\n    Case \"b = true\".\n      destruct (f true) eqn:Ha.\n        rewrite -> Ha. apply Ha.\n      destruct (f false) eqn:Hb.\n        rewrite -> Ha. reflexivity.\n        rewrite -> Hb. reflexivity.\n    Case \"b = false\".\n      destruct (f false) eqn:Hc.\n        destruct (f true) eqn:Hd.\n          rewrite -> Hd. reflexivity.\n          rewrite -> Hc. reflexivity.\n        rewrite -> Hc. rewrite -> Hc. reflexivity.\n  Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars (override_same)  *)\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 Hx1.\n  unfold override.\n  destruct (beq_nat k1 k2) eqn:Hk1k2.\n  Case \"k1 = k2\".\n    apply beq_nat_true in Hk1k2.\n    rewrite <- Hx1.\n    rewrite -> Hk1k2. reflexivity.\n  Case \"k1 != k2\".\n    reflexivity. Qed.\n(** [] *)\n\n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen a bunch of Coq's fundamental tactics.  We'll\n    introduce a few more as we go along through the coming lectures,\n    and later in the course we'll introduce some more powerful\n    _automation_ tactics that make Coq do more of the low-level work\n    in many cases.  But basically we've got what we need to get work\n    done.\n\n    Here are the ones we've seen:\n\n      - [intros]: \n        move hypotheses/variables from goal to context \n\n      - [reflexivity]:\n        finish the proof (when the goal looks like [e = e])\n\n      - [apply]:\n        prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: \n        apply a hypothesis, lemma, or constructor to a hypothesis in\n        the context (forward reasoning)\n\n      - [apply... with...]:\n        explicitly specify values for variables that cannot be\n        determined by pattern matching\n\n      - [simpl]:\n        simplify computations in the goal \n\n      - [simpl in H]:\n        ... or a hypothesis \n\n      - [rewrite]:\n        use an equality hypothesis (or lemma) to rewrite the goal \n\n      - [rewrite ... in H]:\n        ... or a hypothesis \n\n      - [symmetry]:\n        changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]:\n        changes a hypothesis of the form [t=u] into [u=t]\n\n      - [unfold]:\n        replace a defined constant by its right-hand side in the goal \n\n      - [unfold... in H]:\n        ... or a hypothesis  \n\n      - [destruct... as...]:\n        case analysis on values of inductively defined types \n\n      - [destruct... eqn:...]:\n        specify the name of an equation to be added to the context,\n        recording the result of the case analysis\n\n      - [induction... as...]:\n        induction on values of inductively defined types \n\n      - [inversion]:\n        reason by injectivity and distinctness of constructors\n\n      - [assert (e) as H]:\n        introduce a \"local lemma\" [e] and call it [H] \n\n      - [generalize dependent x]:\n        move the variable [x] (and anything else that depends on it)\n        from the context back to an explicit hypothesis in the goal\n        formula \n*)\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We have just proven that for all lists of pairs, [combine] is the\n    inverse of [split].  How would you formalize the statement that\n    [split] is the inverse of [combine]? When is this property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)\n\nDefinition split_combine_statement : Prop :=\n(* FILL IN HERE *) admit.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars (override_permute)  *)\nTheorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),\n  beq_nat k2 k1 = false ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your IH. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n  \n      forallb evenb [0;2;4;5] = false\n  \n      forallb (beq_nat 5) [] = true\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n      existsb (beq_nat 5) [0;2;3;6] = false\n \n      existsb (andb true) [true;true;false] = true\n \n      existsb oddb [1;0;0;0;0;3] = true\n \n      existsb evenb [] = false\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n \n    Prove that [existsb'] and [existsb] have the same behavior.\n*)\n\n(* FILL IN HERE *)\n(** [] *)\n\n(* $Date: 2014-10-02 08:04:07 +0900 (2014年10月02日 (木)) $ *)\n\n\n\n", "meta": {"author": "tyage", "repo": "coq-practice", "sha": "bb6e60c7cbd87bebea786abc58821d22ce822eba", "save_path": "github-repos/coq/tyage-coq-practice", "path": "github-repos/coq/tyage-coq-practice/coq-practice-bb6e60c7cbd87bebea786abc58821d22ce822eba/task/MoreCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.8872045929715078, "lm_q1q2_score": 0.7081549752597199}}
{"text": "(* Exercise 16 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* Tertium non datur inverted *)\n\nTheorem exercise_016 : ~A \\/ A.\nProof.\nneg_e' (~A) first.\nneg_i (~A \\/ A) second.\nhyp first.\ndis_i1.\nhyp second.\nneg_i (~A \\/ A) second.\nhyp first.\ndis_i2.\nhyp second.\n(* It says 'benbcl_proof' instead of 'benb_proof' because\n   you are not allowed to use LEM in this proof. *)\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak10/Taak10_prop016.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7081549647050289}}
{"text": "Require Export Basics.\n\nTheorem plus_n_O_firsttry : forall n:nat, n = n + 0.\nProof.\n  intros n.\n  simpl. (* Does nothing! *)\nAbort.\n\nTheorem plus_n_O_secondtry : forall n:nat, 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\n", "meta": {"author": "anindoasaha", "repo": "software_foundations", "sha": "74d227d5d3eb41b1ce69b2786adfa2cddbefb44f", "save_path": "github-repos/coq/anindoasaha-software_foundations", "path": "github-repos/coq/anindoasaha-software_foundations/software_foundations-74d227d5d3eb41b1ce69b2786adfa2cddbefb44f/logical_foundations/Induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7080360455962343}}
{"text": "Require Import Omega Program.Basics.\n\n(* ***** UNARY  ***** *)\n\n(* Countdown worker function *)\nFixpoint cdn_wkr (f : nat -> nat) (a n k : nat) : nat :=\n  match k with\n  | 0    => 0\n  | S k' => if (n <=? a) then 0 else\n              S (cdn_wkr f a (f n) k')\n  end.\n\n(* Countdown *)\nDefinition countdown_to f a n := cdn_wkr f a n n.\n\n(* Two parameters Inverse Ackerman worker function *)\nFixpoint two_params_inv_ack_wkr (f : nat -> nat) (n k b : nat) : nat :=\n  match b with\n  | 0    => 0\n  | S b' => if (n <=? k) then 0\n              else let g := (countdown_to f 1) in\n                   S (two_params_inv_ack_wkr (compose g f) (g n) k b')\n  end.\n\n(* Two parameters Inverse Ackermann function *)\nDefinition two_params_inv_ack (m n : nat) : nat :=\n  let f := (fun x => x - 2) in\n    let n' := (Nat.log2_up n) in\n      1 + two_params_inv_ack_wkr f (f n') (m / n) n'.\n\n(* Inverse Ackermann worker function *)\nFixpoint inv_ack_wkr (f : nat -> nat) (n k b : nat) : nat :=\n  match b with\n  | 0      => k\n  | S b' => if (n <=? k) then k\n              else let g := (countdown_to f 1) in\n                   inv_ack_wkr (compose g f) (g n) (S k) b'\n  end.\n\n(* Inverse Ackermann function *)\n(* Definition by hard-coding up to the second bin_alpha level, runtime O(n) *)\nDefinition inv_ack_linear n :=\n  match n with\n  | 0 | 1 => 0\n  | _     => let f := (fun x => x - 2) in inv_ack_wkr f (f n) 1 (n - 1)\n  end.\n\n\n\n(* ***** BINARY ***** *)\n\nOpen Scope N_scope.\n\n(* Supporting function - Use to compute the budget for bin_cdn_wkr and inv_ack_wrk\n   Returns length of the binary representation in type \"nat\" *)\nDefinition nat_size (n : N) : nat :=\n  match n with\n  | 0 => 0%nat\n  | Npos p => let fix nat_pos_size (x : positive) : nat :=\n                  match x with\n                  | xH => 1%nat\n                  | xI y | xO y => S (nat_pos_size y) end\n                  in nat_pos_size p\n  end.\n\n(* Countdown worker function *)\nFixpoint bin_cdn_wkr (f : N -> N) (a n : N) (b : nat) : N :=\n  match b with\n  | O    => 0\n  | S b' => if (n <=? a) then 0\n             else 1 + bin_cdn_wkr f a (f n) b'\n  end.\n\n(* Countdown *)\nDefinition bin_countdown_to (f : N -> N) (a n : N) : N :=\n  bin_cdn_wkr f a n (nat_size (n - a)).\n\n(* Two parameters Binary Inverse Ackerman worker function *)\nFixpoint two_params_bin_inv_ack_wkr (f : N -> N) (n k : N) (b : nat) : N :=\n  match b with\n  | 0%nat => 0\n  | S b'  => if (n <=? k) then 0\n              else let g := (bin_countdown_to f 1) in\n                   N.succ (two_params_bin_inv_ack_wkr (compose g f) (g n) k b')\n  end.\n\n(* Two parameters Binary Inverse Ackermann function *)\nDefinition two_params_bin_inv_ack (m n : N) : N :=\n  let n' := (N.log2_up n) in\n    let m' := m / n in\n      if (n' - 2 <=? m') then 1\n        else if (N.div2 (n' - 2) <=? m') then 2\n          else let f := (fun x => N.log2 (x + 2) - 2) in\n            3 + two_params_bin_inv_ack_wkr f (f n') m' (nat_size n).\n\n(* Inverse Ackermann worker function *)\nFixpoint bin_inv_ack_wkr (f : N -> N) (n k : N) (b : nat) : N :=\n  match b with\n  | 0%nat  => k\n  | S b' =>\n    if n <=? k then k\n      else let g := (bin_countdown_to f 1) in\n      bin_inv_ack_wkr (compose g f) (g n) (N.succ k) b'\n  end.\n\n(* Inverse Ackermann function. \n * Definition by hard-coding up to the fourth bin_alpha level, \n * runtime O(log n) up to the magnitude of n \n * equivalent to O(b) where b = bitsize of n \n *)\nDefinition bin_inv_ack n :=\n  if (n <=? 1) then 0\n  else if (n <=? 3) then 1\n  else if (n <=? 7) then 2\n  else let f := (fun x => N.log2 (x + 2) - 2) in\n       bin_inv_ack_wkr f (f n) 3 (nat_size n).\n\nClose Scope N_scope.\n\n(* Please see inv_ack_test.v for a brief demonstration of the time bounds. *)", "meta": {"author": "inv-ack", "repo": "inv-ack", "sha": "195209ba895061fc51368c3c46c1d8760f05df50", "save_path": "github-repos/coq/inv-ack-inv-ack", "path": "github-repos/coq/inv-ack-inv-ack/inv-ack-195209ba895061fc51368c3c46c1d8760f05df50/inv_ack_standalone.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.708036041572274}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  plus y (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj257_coqofml_OJ5LlI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7080360384360852}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Crypto.Util.ZUtil.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\n\nLocal Open Scope Z_scope.\n\nLocal Notation stabilizes_after x l := (exists b, forall n, l < n -> Z.testbit x n = b).\n\nLemma stabilizes_after_Proper x\n  : Proper (Z.le ==> Basics.impl) (fun l => stabilizes_after x l).\nProof.\n  intros ?? H [b H']; exists b.\n  intros n H''; apply (H' n); omega.\nQed.\n\nLemma stabilization_time (x:Z) : stabilizes_after x (Z.max (Z.log2 (Z.pred (- x))) (Z.log2 x)).\nProof.\n  destruct (Z_lt_le_dec x 0); eexists; intros;\n    [ eapply Z.bits_above_log2_neg | eapply Z.bits_above_log2]; lia.\nQed.\n\nLemma stabilization_time_weaker (x:Z) : stabilizes_after x (Z.log2_up (Z.abs x)).\nProof.\n  eapply stabilizes_after_Proper; try apply stabilization_time.\n  repeat match goal with\n         | [ |- context[Z.abs _ ] ] => apply Zabs_ind; intro\n         | [ |- context[Z.log2 ?x] ]\n           => rewrite (Z.log2_nonpos x) by omega\n         | [ |- context[Z.log2_up ?x] ]\n           => rewrite (Z.log2_up_nonpos x) by omega\n         | _ => rewrite Z.max_r by auto with zarith\n         | _ => rewrite Z.max_l by auto with zarith\n         | _ => etransitivity; [ apply Z.le_log2_log2_up | omega ]\n         | _ => progress Z.replace_all_neg_with_pos\n         | [ H : 0 <= ?x |- _ ]\n           => assert (x = 0 \\/ x = 1 \\/ 1 < x) by omega; clear H; destruct_head' or; subst\n         | _ => omega\n         | _ => simpl; omega\n         | _ => rewrite Z.log2_up_eqn by assumption\n         | _ => progress change (Z.log2_up 1) with 0\n         end.\nQed.\n\nLemma land_stabilizes (a b la lb:Z) (Ha:stabilizes_after a la) (Hb:stabilizes_after b lb) : stabilizes_after (Z.land a b) (Z.max la lb).\nProof.\n  destruct Ha as [ba Hba]. destruct Hb as [bb Hbb].\n  exists (andb ba bb); intros n Hn.\n  rewrite Z.land_spec, Hba, Hbb; trivial; lia.\nQed.\n\nLemma lor_stabilizes (a b la lb:Z) (Ha:stabilizes_after a la) (Hb:stabilizes_after b lb) : stabilizes_after (Z.lor a b) (Z.max la lb).\nProof.\n  destruct Ha as [ba Hba]. destruct Hb as [bb Hbb].\n  exists (orb ba bb); intros n Hn.\n  rewrite Z.lor_spec, Hba, Hbb; trivial; lia.\nQed.\n\nLocal Arguments Z.pow !_ !_.\nLocal Arguments Z.log2_up !_.\nLocal Arguments Z.add !_ !_.\nLemma testbit_nonneg_iff x\n  : (exists l, 0 <= l /\\ forall n : Z, l < n -> Z.testbit x n = false) <-> 0 <= x.\nProof.\n  split; intro H.\n  { destruct H as [l [Hl H]].\n    edestruct Z_lt_le_dec; [ | eassumption ].\n    pose proof (fun pf n => Z.bits_above_log2_neg x n pf) as H'.\n    specialize_by (omega || assumption).\n    specialize (H (1 + Z.max l (Z.log2 (Z.pred (- x))))).\n    specialize (H' (1 + Z.max l (Z.log2 (Z.pred (- x))))).\n    specialize_by (apply Z.max_case_strong; omega).\n    congruence. }\n  { pose proof (fun n => Z.bits_above_log2 x n H) as Hf.\n    eexists; split; [ | eapply Hf ]; auto with zarith. }\nQed.\n\nLemma stabilizes_bounded_pos (x l:Z) (H:stabilizes_after x l) (Hl : 0 <= l) (Hx : 0 < x)\n  : x <= 2^(l + 1) - 1.\nProof.\n  assert (Hlt : forall l n, l < n <-> l + 1 <= n) by (intros; omega).\n  destruct H as [b H].\n  destruct (proj2 (testbit_nonneg_iff x)) as [l' [H0' H1']]; [ omega | ].\n  pose proof (Z.testbit_false_bound x (l' + 1)) as Hf.\n  pose proof (Z.testbit_false_bound x (l + 1)) as Hf'.\n  pose proof (fun pf n => Z.bits_above_log2 x n pf) as Hf''.\n  pose proof (fun pf n => Z.log2_lt_pow2 x n pf) as Hlg.\n  specialize_by omega.\n  setoid_rewrite <- Z.le_ngt in Hf.\n  setoid_rewrite <- Z.le_ngt in Hf'.\n  setoid_rewrite <- Hlt in Hf; setoid_rewrite <- Hlt in Hf'; clear Hlt.\n  setoid_rewrite <- Hlg in Hf''; clear Hlg.\n  destruct b; specialize_by (omega || assumption); [ | omega ].\n  specialize (H (1 + Z.max l l')).\n  specialize (H1' (1 + Z.max l l')).\n  specialize_by (apply Z.max_case_strong; omega).\n  congruence.\nQed.\n\nLemma stabilizes_bounded (x l:Z) (H:stabilizes_after x l) (Hl : 0 <= l) : Z.abs x <= 2^(1 + l).\nProof.\n  assert (Hlt : forall l n, l < n <-> l + 1 <= n) by (intros; omega).\n  rewrite Z.add_comm.\n  destruct (Z_zerop x); subst; simpl.\n  { cut (0 < 2^(l + 1)); auto with zarith. }\n  apply Zabs_ind; intro.\n  { etransitivity; [ apply stabilizes_bounded_pos; eauto | ]; omega. }\n  { Z.replace_all_neg_with_pos.\n    destruct (Z.eq_dec x 1); subst.\n    { assert (1 < 2^(l+1)) by auto with zarith.\n      omega. }\n    { assert (H' : stabilizes_after (Z.pred x) l).\n      { destruct H as [b H]; exists (negb b).\n        do 2 let x := fresh in intro x; specialize (H x).\n        rewrite Z.bits_opp in H by omega.\n        destruct b; rewrite ?Bool.negb_true_iff, ?Bool.negb_false_iff in H; assumption. }\n      clear H.\n      apply stabilizes_bounded_pos in H'; auto; omega. } }\nQed.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Util/ZUtil/Stabilization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7080360384360852}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Z.BitOps.\nRequire Import coqutil.Z.bitblast.\n\nLocal Open Scope Z_scope.\nLocal Open Scope bool_scope.\n\nLemma mod0_divisible_modulo: forall a m n,\n    0 < n ->\n    0 < m ->\n    Z.divide n m ->\n    a mod m = 0 ->\n    a mod n = 0.\nProof.\n  intros.\n  unfold Z.divide in H1. destruct H1 as [z H1].\n  assert (z < 0 \\/ z = 0 \\/ 0 < z) as C by blia. destruct C as [C | [ C | C] ].\n  - exfalso. Lia.nia.\n  - exfalso. Lia.nia.\n  - rewrite Z.mul_comm in H1. subst m.\n    rewrite Z.rem_mul_r in H2 by blia.\n    assert (a mod n < 0 \\/ a mod n = 0 \\/ 0 < a mod n) as D by blia. destruct D as [D | [D | D ] ].\n    + exfalso. pose proof (Z.mod_pos_bound a n H). blia.\n    + assumption.\n    + pose proof (Z.mod_pos_bound (a / n) z C). exfalso. Lia.nia.\nQed.\n\nLemma mod_mod_remove_outer: forall a m n,\n    0 < m < n ->\n    n mod m = 0 ->\n    (a mod m) mod n = a mod m.\nProof.\n  intros *. intros [A B] C. apply Z.mod_small.\n  pose proof (Z.mod_pos_bound a m A). blia.\nQed.\n\nLemma mod_mod_remove_inner: forall a m n,\n    0 < n < m ->\n    m mod n = 0 ->\n    (a mod m) mod n = a mod n.\nProof.\n  intros. rewrite <- Znumtheory.Zmod_div_mod; try blia.\n  unfold Z.divide.\n  apply Zmod_divides in H0; [|blia].\n  destruct H0. subst m.\n  exists x. blia.\nQed.\n\nLemma div_mul_same: forall a b,\n    b <> 0 ->\n    a / b * b = a - a mod b.\nProof.\n  intros.\n  pose proof (Zmod_eq_full a b H).\n  blia.\nQed.\n\nLemma sub_mod_exists_q: forall v m,\n    0 < m ->\n    exists q, v - v mod m = m * q.\nProof.\n  intros.\n  apply (Zmod_divides (v - v mod m) m); [blia|].\n  rewrite <- Zminus_mod_idemp_l.\n  rewrite Z.sub_diag.\n  rewrite Z.mod_0_l; blia.\nQed.\n\nLemma shiftr_spec'': forall a n m : Z,\n    Z.testbit (Z.shiftr a n) m = (0 <=? m) &&  Z.testbit a (m + n).\nProof.\n  intros.\n  destruct (Z.leb_spec 0 m).\n  - apply Z.shiftr_spec. assumption.\n  - rewrite Z.testbit_neg_r; trivial.\nQed.\n\nLemma shiftr_spec': forall a n m : Z,\n    Z.testbit (Z.shiftr a n) m = negb (m <? 0) &&  Z.testbit a (m + n).\nProof.\n  intros.\n  destruct (Z.ltb_spec m 0).\n  - rewrite Z.testbit_neg_r; trivial.\n  - apply Z.shiftr_spec. assumption.\nQed.\n\nDefinition mask(x start eend: Z): Z :=\n  (x - x mod 2 ^ start) mod 2 ^ eend.\n\nLemma mask_app_plus: forall v i j k,\n    0 <= i ->\n    i <= j ->\n    j <= k ->\n    mask v i j + mask v j k = mask v i k.\nProof.\n  intros. unfold mask.\n  do 2 rewrite <- div_mul_same by (apply Z.pow_nonzero; blia).\n  rewrite <-! Z.land_ones by blia.\n  rewrite <-! Z.shiftl_mul_pow2 by blia.\n  rewrite <- or_to_plus; Z.bitblast.\nQed.\n\nLtac simpl_pow2_products :=\n  repeat match goal with\n         | |- context [ 2 ^ ?a * 2 ^ ?b ] =>\n           match isZcst a with true => idtac end;\n           match isZcst b with true => idtac end;\n           let c := eval cbv in (a + b) in change (2 ^ a * 2 ^ b) with (2 ^ c)\n         end.\n\nLtac simpl_Zcsts :=\n  repeat match goal with\n         | |- context [?op ?a ?b] =>\n           match isZcst a with true => idtac end;\n           match isZcst b with true => idtac end;\n           match op with\n           | Z.add => idtac\n           | Z.sub => idtac\n           | Z.mul => idtac\n           end;\n           let r := eval cbv in (op a b) in change (op a b) with r\n         end.\n", "meta": {"author": "mit-plv", "repo": "bedrock2", "sha": "7f2d764ed79f394fe715505a04301d0fb502407f", "save_path": "github-repos/coq/mit-plv-bedrock2", "path": "github-repos/coq/mit-plv-bedrock2/bedrock2-7f2d764ed79f394fe715505a04301d0fb502407f/compiler/src/compiler/ZLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7080360289382878}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (x : natural) (y : natural)\n  : natural := mult x (plus y Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj226_coqofml_lqC12E.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7080268206751622}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus lf2 (plus z Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj255_coqofml_Au2qMU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072387, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7080140920274247}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf1 : natural) (lf2 : natural)\n  : natural := plus z (plus lf2 Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj125_coqofml_R1KtRZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7080140846269665}}
{"text": "(* week-04_exercises.v *)\n(* FPP 2020 - YSC3236 2020-2011, Sem1 *)\n\n(* ********** *)\n\n(* \nYour name:\nBernard Boey\nTristan Koh\n\nYour e-mail address:\nbernard@u.yale-nus.edu.sg\ntristan.koh@u.yale-nus.edu.sg\n\nYour student number:\nA0191234L\nA0191222R\n\n*)\n\n(* ********** *)\n\n(* Exercise 9 *)\n\nProposition foo :\n  forall P Q R1 R2 : Prop,\n    P -> (P -> Q) -> (Q -> R1) /\\ (Q -> R2) -> R1 /\\ R2.\nProof.\n  (* Backwards proof *)\n  intros P Q R1 R2.\n  intros H_P H_P_implies_Q [H_Q_implies_R1 H_Q_implies_R2].\n  split.\n  - apply H_Q_implies_R1.\n    apply H_P_implies_Q.\n    apply H_P.\n  - apply H_Q_implies_R2.\n    apply H_P_implies_Q.\n    apply H_P.\n\n    Restart.\n    \n  (* Forwards proof *)\n  intros P Q R1 R2.\n  intros H_P H_P_implies_Q [H_Q_implies_R1 H_Q_implies_R2].\n  assert (H_Q := H_P_implies_Q H_P).\n  assert (H_R1 := H_Q_implies_R1 H_Q).\n  assert (H_R2 := H_Q_implies_R2 H_Q).\n  Check (conj H_R1 H_R2).\n  exact (conj H_R1 H_R2).\nQed.\n\n(* Exercise 10 *)\n\n\nProposition bar :\n  forall P1 P2 Q R1 R2 T1 T2 : Prop,\n    P1 -> (P1 -> P2) -> (P2 -> Q) -> (Q -> R1) -> (R1 -> T1) -> (Q -> R2) -> (R2 -> T2) -> T1 /\\ T2.\nProof.\n\n  (* Split as early as possible *)\n  intros P1 P2 Q R1 T1 R2 T2.\n  intros H_P1 H_P1_implies_P2 H_P2_implies_Q H_Q_implies_R1 H_R1_implies_R2 H_Q_implies_T1 H_T1_implies_T2.\n  split.\n  - apply H_R1_implies_R2.\n    apply H_Q_implies_R1.\n    apply H_P2_implies_Q.\n    apply H_P1_implies_P2.\n    apply H_P1.\n  - apply H_T1_implies_T2.\n    apply H_Q_implies_T1.\n    apply H_P2_implies_Q.\n    apply H_P1_implies_P2.\n    apply H_P1.\n\n  Restart.\n\n  (* Split as late as possible *)\n  intros P1 P2 Q R1 T1 R2 T2.\n  intros H_P1 H_P1_implies_P2 H_P2_implies_Q H_Q_implies_R1 H_R1_implies_R2 H_Q_implies_T1 H_T1_implies_T2.\n  assert (H_P2 := H_P1_implies_P2 H_P1).\n  assert (H_Q := H_P2_implies_Q H_P2).\n  assert (H_R1 := H_Q_implies_R1 H_Q).\n  assert (H_R2 := H_R1_implies_R2 H_R1).\n  assert (H_T1 := H_Q_implies_T1 H_Q).\n  assert (H_T2 := H_T1_implies_T2 H_T1).\n  split.\n  - exact H_R2.\n  - exact H_T2.\n\n  Restart.\n\n  (* Without splitting at all *)\n  intros P1 P2 Q R1 T1 R2 T2.\n  intros H_P1 H_P1_implies_P2 H_P2_implies_Q H_Q_implies_R1 H_R1_implies_R2 H_Q_implies_T1 H_T1_implies_T2.\n  assert (H_P2 := H_P1_implies_P2 H_P1).\n  assert (H_Q := H_P2_implies_Q H_P2).\n  assert (H_R1 := H_Q_implies_R1 H_Q).\n  assert (H_R2 := H_R1_implies_R2 H_R1).\n  assert (H_T1 := H_Q_implies_T1 H_Q).\n  assert (H_T2 := H_T1_implies_T2 H_T1).\n  exact (conj H_R2 H_T2).\nQed.\n\n\n(* Exercise 11 *)\n\n\nProposition baz :\n  forall P Q R T U1 U2 : Prop,\n    P -> (P -> Q) -> (Q -> R) -> (R -> T) -> (T -> U1) -> (T -> U2) -> U1 /\\ U2.\nProof.\n\n  (* Using split as early as possible *)\n  \n  intros P Q R T U1 U2.\n  intros H_P H_P_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U1 H_T_implies_U2.\n  split.\n  - apply H_T_implies_U1.\n    apply H_R_implies_T.\n    apply H_Q_implies_R.\n    apply H_P_implies_Q.\n    apply H_P.\n  - apply H_T_implies_U2.\n    apply H_R_implies_T.\n    apply H_Q_implies_R.\n    apply H_P_implies_Q.\n    apply H_P.\n\n  Restart.\n\n  (* Using split as late as possible *)\n    \n  intros P Q R T U1 U2.\n  intros H_P H_P_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U1 H_T_implies_U2.\n  assert (H_Q := H_P_implies_Q H_P).\n  assert (H_R := H_Q_implies_R H_Q).\n  assert (H_T := H_R_implies_T H_R).\n  assert (H_U1 := H_T_implies_U1 H_T).\n  assert (H_U2 := H_T_implies_U2 H_T).\n  split.\n  - exact H_U1.\n  - exact H_U2.\nQed.\n\n\n(* Exercise 12 *)\n\n(* Part a *)\nProposition baz_dual_early :\n  forall P1 P2 Q R T U : Prop,\n    (P1 \\/ P2) -> (P1 -> Q) -> (P2 -> Q) -> (Q -> R) -> (R -> T) -> (T -> U) -> U.\nProof.\n  intros P1 P2 Q R T U.\n  intros H_P1_or_P2 H_P1_implies_Q H_P2_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U.\n  destruct H_P1_or_P2 as [H_P1 | H_P2].\n  - assert (H_Q := H_P1_implies_Q H_P1).\n    assert (H_R := H_Q_implies_R H_Q).\n    assert (H_T := H_R_implies_T H_R).\n    assert (H_U := H_T_implies_U H_T).\n    exact H_U.\n  - assert (H_Q := H_P2_implies_Q H_P2).\n    assert (H_R := H_Q_implies_R H_Q).\n    assert (H_T := H_R_implies_T H_R).\n    assert (H_U := H_T_implies_U H_T).\n    exact H_U.\nQed.\n\n(* Part b *)\n\nProposition baz_dual_late :\n  forall P1 P2 Q R T U : Prop,\n    (P1 \\/ P2) -> (P1 -> Q) -> (P2 -> Q) -> (Q -> R) -> (R -> T) -> (T -> U) -> U.\nProof.\n  intros P1 P2 Q R T U.\n  intros H_P1_or_P2 H_P1_implies_Q H_P2_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U.\n  apply H_T_implies_U.\n  apply H_R_implies_T.\n  apply H_Q_implies_R.\n  destruct H_P1_or_P2 as [H_P1 | H_P2].\n  - apply (H_P1_implies_Q).\n    apply H_P1.\n  - apply (H_P2_implies_Q).\n    apply H_P2.\nQed.\n\n\n(* Part d *)\nProposition baz_dual_early_or_late :\n  forall P1 P2 Q R T U : Prop,\n    (P1 \\/ P2) -> (P1 -> Q) -> (P2 -> Q) -> (Q -> R) -> (R -> T) -> (T -> U) -> U.\nProof.\n  intros P1 P2 Q R T U.\n  intros [H_P1 | H_P2] H_P1_implies_Q H_P2_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U.\n  - assert (H_Q := H_P1_implies_Q H_P1).\n    assert (H_R := H_Q_implies_R H_Q).\n    assert (H_T := H_R_implies_T H_R).\n    assert (H_U := H_T_implies_U H_T).\n    exact H_U.\n  - assert (H_Q := H_P2_implies_Q H_P2).\n    assert (H_R := H_Q_implies_R H_Q).\n    assert (H_T := H_R_implies_T H_R).\n    assert (H_U := H_T_implies_U H_T).\n    exact H_U.\nQed.\n\n\n\n(* Exercise 13 *)\nProposition ladidah :\n  forall P1 P2 P3 P4 Q R T U : Prop,\n    (P1 \\/ P2) \\/ (P3 \\/ P4) -> (P1 -> Q) -> (P2 -> Q) -> (P3 -> Q) -> (P4 -> Q) -> (Q -> R) -> (R -> T) -> (T -> U) -> U.\n\n  (* Backward proof *)\n  intros P1 P2 P3 P4 Q R T U.\n  intros H_P1_or_P2_or_P3_or_P4 H_P1_implies_Q H_P2_implies_Q H_P3_implies_Q H_P4_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U.\n  apply H_T_implies_U.\n  apply H_R_implies_T.\n  apply H_Q_implies_R.\n  destruct H_P1_or_P2_or_P3_or_P4 as [[H_P1 | H_P2] | [H_P3 | H_P4]].\n  - exact (H_P1_implies_Q H_P1).\n  - exact (H_P2_implies_Q H_P2).\n  - exact (H_P3_implies_Q H_P3).\n  - exact (H_P4_implies_Q H_P4).\n    \n    Restart.\n\n    (* Forward proof *)\n    intros P1 P2 P3 P4 Q R T U.\n    intros H_P1_or_P2_or_P3_or_P4 H_P1_implies_Q H_P2_implies_Q H_P3_implies_Q H_P4_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U.\n    destruct H_P1_or_P2_or_P3_or_P4 as [[H_P1 | H_P2] | [H_P3 | H_P4]].\n  - assert (H_Q := H_P1_implies_Q H_P1).\n    assert (H_R := H_Q_implies_R H_Q).\n    assert (H_T := H_R_implies_T H_R).\n    assert (H_U := H_T_implies_U H_T).\n    exact H_U.\n  -  assert (H_Q := H_P2_implies_Q H_P2).\n     assert (H_R := H_Q_implies_R H_Q).\n     assert (H_T := H_R_implies_T H_R).\n     assert (H_U := H_T_implies_U H_T).\n     exact H_U.\n  -  assert (H_Q := H_P3_implies_Q H_P3).\n     assert (H_R := H_Q_implies_R H_Q).\n     assert (H_T := H_R_implies_T H_R).\n     assert (H_U := H_T_implies_U H_T).\n     exact H_U.\n  -  assert (H_Q := H_P4_implies_Q H_P4).\n     assert (H_R := H_Q_implies_R H_Q).\n     assert (H_T := H_R_implies_T H_R).\n     assert (H_U := H_T_implies_U H_T).\n     exact H_U.\nQed.\n\n\nProposition toodeloo :\n  forall P Q R T U1 U2 U3 U4: Prop,\n    P -> (P -> Q) -> (Q -> R) -> (R -> T) -> (T -> U1) -> (T -> U2) -> (T -> U3) -> (T -> U4) -> (U1 /\\ U2) /\\ (U3 /\\ U4).\nProof.\n\n  (* Forward proof *)\n  intros P Q R T U1 U2 U3 U4.\n  intros H_P H_P_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U1 H_T_implies_U2 H_T_implies_U3 H_T_implies_U4.\n  assert (H_Q := H_P_implies_Q H_P).\n  assert (H_R := H_Q_implies_R H_Q).\n  assert (H_T := H_R_implies_T H_R).\n  assert (H_U1 := H_T_implies_U1 H_T).\n  assert (H_U2 := H_T_implies_U2 H_T).\n  assert (H_U3 := H_T_implies_U3 H_T).\n  assert (H_U4 := H_T_implies_U4 H_T).\n  split.\n  - exact (conj H_U1 H_U2).\n  - exact (conj H_U3 H_U4).\n    \n    Restart.\n\n    (* Backwards proof *)\n    intros P Q R T U1 U2 U3 U4.\n    intros H_P H_P_implies_Q H_Q_implies_R H_R_implies_T H_T_implies_U1 H_T_implies_U2 H_T_implies_U3 H_T_implies_U4.\n    split.\n  - split.\n    -- apply H_T_implies_U1.\n       apply H_R_implies_T.\n       apply H_Q_implies_R.\n       apply H_P_implies_Q.\n       apply H_P.\n    -- apply H_T_implies_U2.\n       apply H_R_implies_T.\n       apply H_Q_implies_R.\n       apply H_P_implies_Q.\n       apply H_P.\n  - split.\n    -- apply H_T_implies_U3.\n       apply H_R_implies_T.\n       apply H_Q_implies_R.\n       apply H_P_implies_Q.\n       apply H_P.\n    -- apply H_T_implies_U4.\n       apply H_R_implies_T.\n       apply H_Q_implies_R.\n       apply H_P_implies_Q.\n       apply H_P.\nQed.\n\n\n(* Equational reasoning about arithmetic functions *)\n\n(* Paraphernalia: *)\n\nLtac fold_unfold_tactic name := intros; unfold name; fold name; reflexivity.\n\nRequire Import Arith Bool.\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\n(* ********** *)\n\n(* Two implementations of the addition function *)\n\n(* ***** *)\n\n(* Unit tests *)\n\nDefinition test_add (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 1)\n  &&\n  (candidate 1 0 =n= 1)\n  &&\n  (candidate 1 1 =n= 2)\n  &&\n  (candidate 1 2 =n= 3)\n  &&\n  (candidate 2 1 =n= 3)\n  &&\n  (candidate 2 2 =n= 4)\n  (* etc. *)\n  .\n\n(* ***** *)\n\n(* Recursive implementation of the addition function *)\n\nFixpoint add_v1 (i j : nat) : nat :=\n  match i with\n  | O =>\n    j\n  | S i' =>\n    S (add_v1 i' j)\n  end.\n\nCompute (test_add add_v1).\n\nLemma fold_unfold_add_v1_O :\n  forall j : nat,\n    add_v1 O j =\n    j.\nProof.\n  fold_unfold_tactic add_v1.\nQed.\n\nLemma fold_unfold_add_v1_S :\n  forall i' j : nat,\n    add_v1 (S i') j =\n    S (add_v1 i' j).\nProof.\n  fold_unfold_tactic add_v1.\nQed.\n\n(* ***** *)\n\n(* Tail-recursive implementation of the addition function *)\n\nFixpoint add_v2 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => add_v2 i' (S j)\n  end.\n\nCompute (test_add add_v2).\n\nLemma fold_unfold_add_v2_O :\n  forall j : nat,\n    add_v2 O j =\n    j.\nProof.\n  fold_unfold_tactic add_v2.\nQed.\n\nLemma fold_unfold_add_v2_S :\n  forall i' j : nat,\n    add_v2 (S i') j =\n    add_v2 i' (S j).\nProof.\n  fold_unfold_tactic add_v2.\nQed.\n\n(* ********** *)\n\n(* Equivalence of add_v1 and add_v2 *)\n\n(* ***** *)\n\n(* The master lemma: *)\n\nLemma about_add_v2 :\n  forall i j : nat,\n    add_v2 i (S j) = S (add_v2 i j).\nProof.\n  intro i.\n  induction i as [ | i' IHi'].\n\n  - intro j.\n    rewrite -> (fold_unfold_add_v2_O j).\n    exact (fold_unfold_add_v2_O (S j)).\n\n  - intro j.\n    rewrite -> (fold_unfold_add_v2_S i' (S j)).\n    rewrite -> (fold_unfold_add_v2_S i' j).\n    Check (IHi' (S j)).\n    exact (IHi' (S j)).\nQed.\n\n(* ***** *)\n\n(* The main theorem: *)\n\nTheorem equivalence_of_add_v1_and_add_v2 :\n  forall i j : nat,\n    add_v1 i j = add_v2 i j.\nProof.\n  intro i.\n  induction i as [ | i' IHi'].\n\n  - intro j.\n    rewrite -> (fold_unfold_add_v2_O j).\n    exact (fold_unfold_add_v1_O j).\n\n  - intro j.\n    rewrite -> (fold_unfold_add_v1_S i' j).\n    rewrite -> (fold_unfold_add_v2_S i' j).\n    rewrite -> (IHi' j).\n    symmetry.\n    exact (about_add_v2 i' j).\nQed.\n\n(* ********** *)\n\n(* Neutral (identity) element for addition *)\n\n(* Exercise 17 *)\n\nProperty O_is_left_neutral_wrt_add_v1 :\n  forall y : nat,\n    add_v1 0 y = y.\nProof.\n  exact (fold_unfold_add_v1_O).\nQed.\n\n(* Exercise 18 *)\n\nProperty O_is_left_neutral_wrt_add_v2 :\n  forall y : nat,\n    add_v2 0 y = y.\nProof.\n  exact (fold_unfold_add_v2_O).\nQed.\n\n(* Exercise 19 *)\n\nProperty O_is_right_neutral_wrt_add_v1 :\n  forall x : nat,\n    add_v1 x 0 = x.\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n  - exact (fold_unfold_add_v1_O 0).\n  - rewrite -> (fold_unfold_add_v1_S x' 0).\n    rewrite -> IHx'.\n    reflexivity.\nQed.\n\n(* Exercise 20 *)\n\nProperty O_is_right_neutral_wrt_add_v2 :\n  forall x : nat,\n    add_v2 x 0 = x.\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n  - exact (fold_unfold_add_v2_O 0).\n  - rewrite -> (fold_unfold_add_v2_S x' 0).\n    rewrite -> (about_add_v2 x' 0).\n    rewrite -> IHx'.\n    reflexivity.\nQed.\n\n\n(* ********** *)\n\n(* Associativity of addition *)\n\n(* Exercise 21 *)\n\nProperty add_v1_is_associative :\n  forall x y z : nat,\n    add_v1 x (add_v1 y z) = add_v1 (add_v1 x y) z.\nProof.\n  intros x y z.\n  induction x as [ | x' IHx'].\n  - rewrite -> (fold_unfold_add_v1_O (add_v1 y z)).\n    rewrite -> (fold_unfold_add_v1_O y).\n    reflexivity.\n  - rewrite -> (fold_unfold_add_v1_S x' (add_v1 y z)).\n    rewrite -> (fold_unfold_add_v1_S x' y).\n    rewrite -> (fold_unfold_add_v1_S (add_v1 x' y) z).\n    rewrite -> IHx'.\n    reflexivity.\nQed.\n\n(* Exercise 22 *)\n\nProperty add_v2_is_associative :\n  forall x y z : nat,\n    add_v2 x (add_v2 y z) = add_v2 (add_v2 x y) z.\nProof.\n  intros x y z.\n  induction x as [ | x' IHx'].\n  - rewrite -> (fold_unfold_add_v2_O (add_v2 y z)).\n    rewrite -> (fold_unfold_add_v2_O y).\n    reflexivity.\n  - rewrite -> (fold_unfold_add_v2_S x' (add_v2 y z)).\n    rewrite -> (fold_unfold_add_v2_S x' y).\n    rewrite -> (about_add_v2 x' (add_v2 y z)).\n    rewrite -> (about_add_v2 x' y).\n    rewrite -> (fold_unfold_add_v2_S (add_v2 x' y) z).\n    rewrite -> (about_add_v2 (add_v2 x' y) z).\n    rewrite -> IHx'.\n    reflexivity.\nQed.\n\n(* ********** *)\n\n(* Commutativity of addition *)\n\n(* Exercise 23 *)\n\nLemma about_add_v1 :\n  forall x y : nat,\n    add_v1 x (S y) = S (add_v1 x y).\nProof.\n  intros x y.\n  induction x as [ | x' IHx'].\n  - rewrite -> (fold_unfold_add_v1_O y).\n    exact (fold_unfold_add_v1_O (S y)).\n  - rewrite -> (fold_unfold_add_v1_S x' (S y)).\n    rewrite -> (fold_unfold_add_v1_S x' y).\n    rewrite -> IHx'.\n    reflexivity.\nQed.\n    \nProperty add_v1_is_commutative :\n  forall x y : nat,\n    add_v1 x y = add_v1 y x.\nProof.\n  intros x y.\n  induction x as [ | x' IHx'].\n  - rewrite -> (O_is_right_neutral_wrt_add_v1 y).\n    exact (fold_unfold_add_v1_O y).\n  - rewrite -> (fold_unfold_add_v1_S x' y).\n    rewrite -> (about_add_v1 y x').\n    rewrite -> IHx'.\n    reflexivity.\nQed.\n\n(* Exercise 24 *)\n\nProperty add_v2_is_commutative :\n  forall x y : nat,\n    add_v2 x y = add_v2 y x.\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n  - intro y.\n    rewrite -> (O_is_right_neutral_wrt_add_v2 y).\n    exact (fold_unfold_add_v2_O y).\n  - intro y.\n    rewrite -> (fold_unfold_add_v2_S x' y).\n    rewrite -> (IHx' (S y)).\n    rewrite -> (fold_unfold_add_v2_S y x').\n    reflexivity.\nQed.\n\n(* ********** *)\n\n(* Four implementations of the multiplication function *)\n\n(* ***** *)\n\n(* Unit tests *)\n\nDefinition test_mul (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 0)\n  &&\n  (candidate 1 0 =n= 0)\n  &&\n  (candidate 1 1 =n= 1)\n  &&\n  (candidate 1 2 =n= 2)\n  &&\n  (candidate 2 1 =n= 2)\n  &&\n  (candidate 2 2 =n= 4)\n  &&\n  (candidate 2 3 =n= 6)\n  &&\n  (candidate 3 2 =n= 6)\n  &&\n  (candidate 6 4 =n= 24)\n  &&\n  (candidate 4 6 =n= 24)\n  (* etc. *)\n  .\n\n(* ***** *)\n\n(* Recursive implementation of the multiplication function, using add_v1 *)\n\nFixpoint mul_v11 (x y : nat) : nat :=\n  match x with\n  | O =>\n    O\n  | S x' =>\n    add_v1 (mul_v11 x' y) y\n  end.\n\nCompute (test_mul mul_v11).\n\nLemma fold_unfold_mul_v11_O :\n  forall y : nat,\n    mul_v11 O y =\n    O.\nProof.\n  fold_unfold_tactic mul_v11.\nQed.\n\nLemma fold_unfold_mul_v11_S :\n  forall x' y : nat,\n    mul_v11 (S x') y =\n    add_v1 (mul_v11 x' y) y.\nProof.\n  fold_unfold_tactic mul_v11.\nQed.\n\n(* ***** *)\n\n(* Recursive implementation of the multiplication function, using add_v2 *)\n\nFixpoint mul_v12 (x y : nat) : nat :=\n  match x with\n  | O =>\n    O\n  | S x' =>\n    add_v2 (mul_v12 x' y) y\n  end.\n\nCompute (test_mul mul_v11).\n\nLemma fold_unfold_mul_v12_O :\n  forall y : nat,\n    mul_v12 O y =\n    O.\nProof.\n  fold_unfold_tactic mul_v12.\nQed.\n\nLemma fold_unfold_mul_v12_S :\n  forall x' y : nat,\n    mul_v12 (S x') y =\n    add_v2 (mul_v12 x' y) y.\nProof.\n  fold_unfold_tactic mul_v12.\nQed.\n\n(* ***** *)\n\n(* Exercise 27 *)\n\n(* Tail-recursive implementation of the multiplication function, using add_v1 *)\n\nFixpoint mul_v21_aux (x y a : nat) : nat :=\n  match x with\n  | O =>\n    a\n  | S x' =>\n    mul_v21_aux x' y (add_v1 y a)\n  end.\n\nDefinition mul_v21 (x y : nat) : nat :=\n  mul_v21_aux x y 0.\n\nCompute (test_mul mul_v21).\n\nLemma fold_unfold_mul_v21_aux_O :\n  forall y a : nat,\n    mul_v21_aux 0 y a =\n    a.\nProof.\n  fold_unfold_tactic mul_v21_aux.\nQed.\n\nLemma fold_unfold_mul_v21_aux_S :\n  forall x' y a : nat,\n    mul_v21_aux (S x') y a =\n    mul_v21_aux x' y (add_v1 y a).\nProof.\n  fold_unfold_tactic mul_v21_aux.\nQed.\n\n(* ***** *)\n\n(* Exercise 28 *)\n\n(* Tail-recursive implementation of the multiplication function, using add_v2 *)\n\nFixpoint mul_v22_aux (x y a : nat) : nat :=\n  match x with\n  | O =>\n    a\n  | S x' =>\n    mul_v22_aux x' y (add_v2 y a)\n  end.\n\nDefinition mul_v22 (x y : nat) : nat :=\n  mul_v22_aux x y 0.\n\nCompute (test_mul mul_v22).\n\nLemma fold_unfold_mul_v22_aux_O :\n  forall y a : nat,\n    mul_v22_aux 0 y a =\n    a.\nProof.\n  fold_unfold_tactic mul_v22_aux.\nQed.\n\nLemma fold_unfold_mul_v22_aux_S :\n  forall x' y a : nat,\n    mul_v22_aux (S x') y a =\n    mul_v22_aux x' y (add_v2 y a).\nProof.\n  fold_unfold_tactic mul_v22_aux.\nQed.\n\n(* ********** *)\n\n(* Exercise 29 *)\n\n(* Equivalence of mul_v11, mul_v12, mul_v21, and mul_v22 *)\n\n(* ***** *)\n\nTheorem equivalence_of_mul_v11_and_mul_v12 :\n  forall i j : nat,\n    mul_v11 i j = mul_v12 i j.\nProof.\n  intros i j.               \n  induction i as [ | i' IHi'].\n  - rewrite -> (fold_unfold_mul_v12_O j).\n    exact (fold_unfold_mul_v11_O j).\n  - rewrite -> (fold_unfold_mul_v11_S i' j).\n    rewrite -> (fold_unfold_mul_v12_S i' j).\n    rewrite -> IHi'.\n    rewrite -> (equivalence_of_add_v1_and_add_v2 (mul_v12 i' j) j).\n    reflexivity.\nQed.\n    \n(* ***** *)\n\nLemma about_mul_v21_and_add_v1 :\n  forall x y a n : nat,\n    add_v1 (mul_v21_aux x y a) n = mul_v21_aux x y (add_v1 n a).\nProof.\n  intros x.\n  induction x as [ | x' IHx'].\n  - intros y a n.\n    rewrite -> (fold_unfold_mul_v21_aux_O y a).\n    rewrite -> (fold_unfold_mul_v21_aux_O y (add_v1 n a)).\n    exact (add_v1_is_commutative a n).\n  - intros y a n.\n    rewrite -> (fold_unfold_mul_v21_aux_S x' y a).\n    rewrite -> (fold_unfold_mul_v21_aux_S x' y (add_v1 n a)).\n    rewrite -> (IHx' y (add_v1 y a) n).\n    rewrite -> (add_v1_is_associative n y a).\n    rewrite -> (add_v1_is_associative y n a).\n    rewrite -> (add_v1_is_commutative n y).\n    reflexivity.\nQed.\n\nTheorem equivalence_of_mul_v11_and_mul_v21 :\n  forall i j : nat,\n    mul_v11 i j = mul_v21 i j.\nProof.\n  intros i j.\n  unfold mul_v21.\n  induction i as [ | i' IHi'].\n  - rewrite -> (fold_unfold_mul_v21_aux_O j 0).\n    exact (fold_unfold_mul_v11_O j).\n  - rewrite -> (fold_unfold_mul_v11_S i' j).\n    rewrite -> (fold_unfold_mul_v21_aux_S i' j).\n    rewrite -> IHi'.\n    Check (about_mul_v21_and_add_v1 i' j 0 j).\n    exact (about_mul_v21_and_add_v1 i' j 0 j).\nQed.\n\n(* ***** *)\n\nLemma equivalence_of_mul_v21_aux_and_mul_v22_aux :\n  forall i j a : nat,\n    mul_v21_aux i j a = mul_v22_aux i j a.\nProof.\n  intros i j.\n  induction i as [ | i' IHi'].\n  - intro a.\n    rewrite -> (fold_unfold_mul_v22_aux_O j a).\n    exact (fold_unfold_mul_v21_aux_O j a).\n  - intro a.\n    rewrite -> (fold_unfold_mul_v22_aux_S i' j a).\n    rewrite -> (fold_unfold_mul_v21_aux_S i' j a).\n    rewrite -> (equivalence_of_add_v1_and_add_v2 j a).\n    exact (IHi' (add_v2 j a)).\nQed.    \n\nTheorem equivalence_of_mul_v21_and_mul_v22 :\n  forall i j : nat,\n    mul_v21 i j = mul_v22 i j.\nProof.\n  intros i j.\n  unfold mul_v21.\n  unfold mul_v22.\n  exact (equivalence_of_mul_v21_aux_and_mul_v22_aux i j 0).\nQed.\n\n(* ***** *)\n\nLemma about_mul_v22_and_add_v2 :\n  forall x y a n : nat,\n    add_v2 (mul_v22_aux x y a) n = mul_v22_aux x y (add_v2 n a).\nProof.\n  intros x.\n  induction x as [ | x' IHx'].\n  - intros y a n.\n    rewrite -> (fold_unfold_mul_v22_aux_O y a).\n    rewrite -> (fold_unfold_mul_v22_aux_O y (add_v2 n a)).\n    exact (add_v2_is_commutative a n).\n  - intros y a n.\n    rewrite -> (fold_unfold_mul_v22_aux_S x' y a).\n    rewrite -> (fold_unfold_mul_v22_aux_S x' y (add_v2 n a)).\n    rewrite -> (IHx' y (add_v2 y a) n).\n    rewrite -> (add_v2_is_associative n y a).\n    rewrite -> (add_v2_is_associative y n a).\n    rewrite -> (add_v2_is_commutative n y).\n    reflexivity.\nQed.\n\n\nTheorem equivalence_of_mul_v11_and_mul_v22 :\n  forall i j : nat,\n    mul_v11 i j = mul_v22 i j.\nProof.\n  intros i j.\n  unfold mul_v22.\n  induction i as [ | i' IHi'].\n  - rewrite -> (fold_unfold_mul_v22_aux_O j 0).\n    exact (fold_unfold_mul_v11_O j).\n  - rewrite -> (fold_unfold_mul_v11_S i' j).\n    rewrite -> (fold_unfold_mul_v22_aux_S i' j).\n    rewrite -> IHi'.\n    rewrite -> (equivalence_of_add_v1_and_add_v2 (mul_v22_aux i' j 0) j).\n    exact (about_mul_v22_and_add_v2 i' j 0 j).\n\n  Restart.\n\n  intros i j.\n  rewrite -> (equivalence_of_mul_v11_and_mul_v21 i j).\n  exact (equivalence_of_mul_v21_and_mul_v22 i j).\nQed.\n\n\n(* ***** *)\n\nTheorem equivalence_of_mul_v12_and_mul_v21 :\n  forall i j : nat,\n    mul_v12 i j = mul_v21 i j.\nProof.\n  intros i j.\n  unfold mul_v21.\n  induction i as [ | i' IHi'].\n  - rewrite -> (fold_unfold_mul_v21_aux_O j 0).\n    exact (fold_unfold_mul_v12_O j).\n  - rewrite -> (fold_unfold_mul_v12_S i' j).\n    rewrite -> (fold_unfold_mul_v21_aux_S i' j).\n    rewrite -> IHi'.\n    rewrite <- (equivalence_of_add_v1_and_add_v2 (mul_v21_aux i' j 0) j).\n    exact (about_mul_v21_and_add_v1 i' j 0 j).\n\n  Restart.\n\n  intros i j.\n  rewrite <- (equivalence_of_mul_v11_and_mul_v12 i j).\n  exact (equivalence_of_mul_v11_and_mul_v21 i j).\nQed.\n\n\n(* ***** *)\n\nTheorem equivalence_of_mul_v12_and_mul_v22 :\n  forall i j : nat,\n    mul_v12 i j = mul_v22 i j.\nProof.\n  intros i j.\n  unfold mul_v22.\n  induction i as [ | i' IHi'].\n  - rewrite -> (fold_unfold_mul_v12_O j).\n    rewrite -> (fold_unfold_mul_v22_aux_O j 0).\n    reflexivity.\n  - rewrite -> (fold_unfold_mul_v12_S i' j).\n    rewrite -> (fold_unfold_mul_v22_aux_S i' j).\n    rewrite -> IHi'.\n    exact (about_mul_v22_and_add_v2 i' j 0 j).\n\n  Restart.\n\n  intros i j.\n  rewrite <- (equivalence_of_mul_v11_and_mul_v12 i j).\n  rewrite -> (equivalence_of_mul_v11_and_mul_v21 i j).\n  exact (equivalence_of_mul_v21_and_mul_v22 i j).\nQed.\n\n(* ********** *)\n\n(* 1 is left neutral with respect to multiplication *)\n\nLemma mul_v12_aux :\n  forall x y': nat,\n  mul_v12 x (S y') = add_v2 (mul_v12 x y') x.\nProof.\n  intros x y'.\n  induction x as [ | x' IHx'].\n  - rewrite -> (fold_unfold_mul_v12_O (S y')).\n    rewrite -> (fold_unfold_mul_v12_O y').\n    rewrite -> (fold_unfold_add_v2_O 0).\n    reflexivity.\n  - rewrite -> (fold_unfold_mul_v12_S x' (S y')).\n    rewrite -> (fold_unfold_mul_v12_S x' y').\n    rewrite -> IHx'.\n    rewrite -> (about_add_v2 (add_v2 (mul_v12 x' y') x') y').\n    rewrite -> (about_add_v2 (add_v2 (mul_v12 x' y') y') x').\n    rewrite <- (add_v2_is_associative (mul_v12 x' y') x' y').\n    rewrite <- (add_v2_is_associative (mul_v12 x' y') y' x').\n    rewrite <- (add_v2_is_commutative x' y').\n    reflexivity.\nQed.\n  \nProperty SO_is_left_neutral_wrt_mul_v12 :\n  forall y : nat,\n    mul_v12 1 y = y.\nProof.\n  intro y.\n  induction y as [ | y' IHy'].\n  - exact (fold_unfold_mul_v12_O 1).\n  - rewrite -> (mul_v12_aux 1 y').\n    rewrite -> IHy'.\n    rewrite -> (about_add_v2 y' 0).\n    rewrite -> (O_is_right_neutral_wrt_add_v2 y').\n    reflexivity.\nQed.\n\n(* ********** *)\n\n(* Multiplication is right-distributive over addition *)\n\n(* Exercise 34 *)\n\nProperty mul_v11_is_right_distributive_over_add_v1 :\n  forall x y z : nat,\n    mul_v11 (add_v1 x y) z = add_v1 (mul_v11 x z) (mul_v11 y z).\nProof.\n  intros x y z.\n  induction x as [ | x' IHx'].\n  - rewrite -> (fold_unfold_add_v1_O y).\n    rewrite -> (fold_unfold_mul_v11_O z).\n    rewrite -> (fold_unfold_add_v1_O (mul_v11 y z)).\n    reflexivity.\n  - rewrite -> (fold_unfold_add_v1_S x' y).\n    rewrite -> (fold_unfold_mul_v11_S x' z).\n    rewrite -> (fold_unfold_mul_v11_S (add_v1 x' y) z).\n    rewrite -> IHx'.\n    rewrite <- (add_v1_is_associative (mul_v11 x' z) (mul_v11 y z) z).\n    rewrite -> (add_v1_is_commutative (mul_v11 y z) z).\n    Check (add_v1_is_associative (mul_v11 x' z) z (mul_v11 y z)).\n    exact (add_v1_is_associative (mul_v11 x' z) z (mul_v11 y z)).\nQed.\n\n(* ***** *)\n\nLemma about_mul_v12 :\n  forall x y : nat,\n    mul_v12 (S x) y = add_v2 (mul_v12 x y) y.\nProof.\n  intro x.\n  induction x as [ | x' IHx'].\n  - intro y.\n    rewrite -> (fold_unfold_mul_v12_O y).\n    rewrite -> (fold_unfold_add_v2_O y).\n    exact (SO_is_left_neutral_wrt_mul_v12 y).\n  - intro y.\n    rewrite -> (fold_unfold_mul_v12_S (S x') y).\n    reflexivity.    \nQed.\n\nProperty mul_v12_is_right_distributive_over_add_v2 :\n  forall x y z : nat,\n    mul_v12 (add_v2 x y) z = add_v2 (mul_v12 x z) (mul_v12 y z).\nProof.\n  intros x.\n  induction x as [ | x' IHx'].\n  - intros y z.\n    rewrite -> (fold_unfold_add_v2_O y).\n    rewrite -> (fold_unfold_mul_v12_O z).\n    rewrite -> (fold_unfold_add_v2_O (mul_v12 y z)).\n    reflexivity.\n  - intros y z.\n    rewrite -> (fold_unfold_add_v2_S x' y).\n    rewrite -> (IHx' (S y) z).\n    rewrite -> (about_mul_v12 y z).\n    rewrite -> (about_mul_v12 x' z).\n    rewrite -> (add_v2_is_commutative (mul_v12 y z) z).\n    Check (add_v2_is_associative (mul_v12 x' z) z (mul_v12 y z)).\n    exact (add_v2_is_associative (mul_v12 x' z) z (mul_v12 y z)).\n\n  Restart.\n\n  intros x y z.\n  rewrite <- (equivalence_of_add_v1_and_add_v2).\n  rewrite <- (equivalence_of_add_v1_and_add_v2).\n  rewrite <- (equivalence_of_mul_v11_and_mul_v12).\n  rewrite <- (equivalence_of_mul_v11_and_mul_v12).\n  rewrite <- (equivalence_of_mul_v11_and_mul_v12).\n  exact (mul_v11_is_right_distributive_over_add_v1 x y z).\nQed.\n\n\nProperty mul_v21_is_right_distributive_over_add_v1 :\n  forall x y z : nat,\n    mul_v21 (add_v1 x y) z = add_v1 (mul_v21 x z) (mul_v21 y z).\nProof.\n  intros x y z.\n  unfold mul_v21.\n  induction x as [ | x' IHx'].\n  - rewrite -> (fold_unfold_add_v1_O y).\n    rewrite -> (fold_unfold_mul_v21_aux_O z 0).\n    rewrite -> (fold_unfold_add_v1_O (mul_v21_aux y z 0)).\n    reflexivity.\n  - rewrite -> (fold_unfold_add_v1_S x' y).\n    rewrite -> (fold_unfold_mul_v21_aux_S x' z).\n    rewrite -> (fold_unfold_mul_v21_aux_S (add_v1 x' y) z).\n    rewrite <- (about_mul_v21_and_add_v1 (add_v1 x' y) z 0 z).\n    rewrite <- (about_mul_v21_and_add_v1 x' z 0 z).\n    rewrite -> IHx'.\n    rewrite <- (add_v1_is_associative (mul_v21_aux x' z 0) (mul_v21_aux y z 0) z).\n    rewrite <- (add_v1_is_associative (mul_v21_aux x' z 0) z (mul_v21_aux y z 0)).\n    rewrite -> (add_v1_is_commutative (mul_v21_aux y z 0) z).\n    reflexivity.\n    \n  Restart.\n\n  intros x y z.\n  rewrite <- (equivalence_of_mul_v11_and_mul_v21).\n  rewrite <- (equivalence_of_mul_v11_and_mul_v21).\n  rewrite <- (equivalence_of_mul_v11_and_mul_v21).\n  exact (mul_v11_is_right_distributive_over_add_v1 x y z).\nQed.\n\nProperty mul_v22_is_right_distributive_over_add_v2 :\n  forall x y z : nat,\n    mul_v22 (add_v2 x y) z = add_v2 (mul_v22 x z) (mul_v22 y z).\nProof.\n  intros x y z.\n  unfold mul_v22.\n  induction x as [ | x' IHx'].\n  - rewrite -> (fold_unfold_add_v2_O y).\n    rewrite -> (fold_unfold_mul_v22_aux_O z 0).\n    rewrite -> (fold_unfold_add_v2_O (mul_v22_aux y z 0)).\n    reflexivity.\n  - rewrite -> (fold_unfold_add_v2_S x' y).\n    rewrite -> (fold_unfold_mul_v22_aux_S x' z).\n    rewrite -> (about_add_v2 x' y).\n    rewrite -> (fold_unfold_mul_v22_aux_S (add_v2 x' y) z).\n    rewrite <- (about_mul_v22_and_add_v2 (add_v2 x' y) z 0 z).\n    rewrite <- (about_mul_v22_and_add_v2 x' z 0 z).\n    rewrite -> IHx'.\n    rewrite <- (add_v2_is_associative (mul_v22_aux x' z 0) (mul_v22_aux y z 0) z).\n    rewrite <- (add_v2_is_associative (mul_v22_aux x' z 0) z (mul_v22_aux y z 0)).\n    rewrite -> (add_v2_is_commutative (mul_v22_aux y z 0) z).\n    reflexivity.\n    \n  Restart.\n\n  intros x y z.\n  rewrite <- (equivalence_of_add_v1_and_add_v2).\n  rewrite <- (equivalence_of_add_v1_and_add_v2).\n  rewrite <- (equivalence_of_mul_v11_and_mul_v22).\n  rewrite <- (equivalence_of_mul_v11_and_mul_v22).\n  rewrite <- (equivalence_of_mul_v11_and_mul_v22).\n  exact (mul_v11_is_right_distributive_over_add_v1 x y z).\nQed.\n\n\n(* end of week-04_exercises.v *)\n", "meta": {"author": "TristanKoh", "repo": "FPP", "sha": "bb22748fed28f6b300add2525e15f5cdcedce59b", "save_path": "github-repos/coq/TristanKoh-FPP", "path": "github-repos/coq/TristanKoh-FPP/FPP-bb22748fed28f6b300add2525e15f5cdcedce59b/week-04_exercises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.7078890330651441}}
{"text": "Require Import init.\n\nRequire Import list_perm.\n\nRequire Import equivalence.\n\nLocal Instance list_perm_reflexive U : Reflexive _ := {\n    refl := @list_perm_refl U\n}.\nLocal Instance list_perm_symmetric U : Symmetric _ := {\n    sym := @list_perm_sym U\n}.\nLocal Instance list_perm_transitive U : Transitive _ := {\n    trans := @list_perm_trans U\n}.\n\nDefinition ulist_equiv U := make_equiv _\n    (list_perm_reflexive U) (list_perm_symmetric U) (list_perm_transitive U).\nNotation \"'ulist' U\" := (equiv_type (ulist_equiv U)) (at level 1).\n\nDefinition ulist_end {U} := to_equiv (ulist_equiv U) list_end.\n\nLemma uadd_wd U : ∀ (a : U) l1 l2,\n    list_permutation l1 l2 → list_permutation (a ꞉ l1) (a ꞉ l2).\nProof.\n    intros a l1 l2 l_perm.\n    apply list_perm_skip.\n    exact l_perm.\nQed.\nDefinition ulist_add {U} (a : U)\n    := unary_op (unary_self_wd (E := ulist_equiv U) (uadd_wd U a)).\n(** Like with list_add, this is NOT a colon!  It is actually U+02D0,\nmodifier letter triangular colon.  I have it mapped to \\uadd in ibus. *)\nInfix \"ː\" := ulist_add (at level 49, right associativity) : list_scope.\n(** These are \\llbracket and \\rrbracket, U+27E6 and U+27E7. *)\nNotation \"⟦⟧\" := ulist_end : list_scope.\nNotation \"⟦ a ⟧\" := (a ː ⟦⟧) : list_scope.\nNotation \"⟦ x ; y ; .. ; z ⟧\" :=\n    (x ː (y ː .. (z ː ⟦⟧) ..))\n    (format \"⟦ '[' x ; '/' y ; '/' .. ; '/' z ']' ⟧\") : list_scope.\n\nTheorem ulist_induction {U} : ∀ S : ulist U → Prop,\n    S ⟦⟧ → (∀ a l, S l → S (a ː l)) → ∀ l, S l.\nProof.\n    intros S S_end S_add l.\n    equiv_get_value l.\n    induction l.\n    -   exact S_end.\n    -   assert (to_equiv (ulist_equiv U) (a ꞉ l) =\n            a ː (to_equiv (ulist_equiv U) l)) as eq.\n        {\n            unfold ulist_add; equiv_simpl.\n            apply list_perm_refl.\n        }\n        rewrite eq.\n        apply S_add.\n        exact IHl.\nQed.\n\nTheorem ulist_destruct {U} : ∀ S : ulist U → Prop,\n    S ⟦⟧ → (∀ a l, S (a ː l)) → ∀ l, S l.\nProof.\n    intros S S_end S_ind l.\n    induction l using ulist_induction.\n    -   exact S_end.\n    -   apply S_ind.\nQed.\n\nTheorem ulist_end_neq {U} : ∀ (a : U) l, a ː l ≠ ⟦⟧.\nProof.\n    intros a l contr.\n    equiv_get_value l.\n    unfold ulist_add, ulist_end in contr; equiv_simpl in contr.\n    apply list_perm_sym in contr.\n    apply list_perm_nil_eq in contr.\n    inversion contr.\nQed.\n\nTheorem ulist_single_eq {U} : ∀ (a b : U), ⟦a⟧ = ⟦b⟧ → a = b.\nProof.\n    intros a b eq.\n    unfold ulist_add, ulist_end in eq; equiv_simpl in eq.\n    pose proof (list_perm_single eq) as eq2.\n    inversion eq2.\n    reflexivity.\nQed.\n\nLemma uconc_wd U : ∀ al1 al2 bl1 bl2 : list U,\n    list_permutation al1 al2 → list_permutation bl1 bl2 →\n    list_permutation (al1 + bl1) (al2 + bl2).\nProof.\n    intros al1 al2 bl1 bl2 eq1 eq2.\n    pose proof (list_perm_rpart al1 eq2).\n    pose proof (list_perm_lpart bl2 eq1).\n    exact (list_perm_trans H H0).\nQed.\nGlobal Instance ulist_plus U : Plus (ulist U) := {\n    plus := binary_op (binary_self_wd (E := ulist_equiv U) (uconc_wd U))\n}.\n\nTheorem ulist_add_conc_add {U} : ∀ (a : U) l1 l2,\n    a ː (l1 + l2) = (a ː l1) + l2.\nProof.\n    intros a l1 l2.\n    equiv_get_value l1 l2.\n    unfold plus, ulist_add; equiv_simpl.\n    apply list_perm_refl.\nQed.\n\nTheorem ulist_add_conc {U} : ∀ (a : U) l, a ː l = (⟦a⟧) + l.\nProof.\n    intros a l.\n    equiv_get_value l.\n    unfold ulist_end, ulist_add, plus; equiv_simpl.\n    apply list_perm_refl.\nQed.\n\nGlobal Instance ulist_zero U : Zero (ulist U) := {\n    zero := ⟦⟧\n}.\n\nGlobal Instance ulist_plus_comm U : PlusComm (ulist U).\nProof.\n    split.\n    intros a b.\n    equiv_get_value a b.\n    unfold plus; equiv_simpl.\n    apply list_perm_conc.\nQed.\n\nGlobal Instance ulist_plus_lid U : PlusLid (ulist U).\nProof.\n    split.\n    intros l.\n    equiv_get_value l.\n    unfold ulist_end, plus, zero; equiv_simpl.\n    apply list_perm_refl.\nQed.\n\nTheorem ulist_conc_lid {U} : ∀ l : ulist U, ⟦⟧ + l = l.\nProof.\n    exact plus_lid.\nQed.\n\nTheorem ulist_conc_rid {U} : ∀ l : ulist U, l + ⟦⟧ = l.\nProof.\n    exact plus_rid.\nQed.\n\nGlobal Instance ulist_plus_assoc U : PlusAssoc (ulist U).\nProof.\n    split.\n    intros a b c.\n    equiv_get_value a b c.\n    unfold plus; equiv_simpl.\n    rewrite plus_assoc.\n    apply list_perm_refl.\nQed.\n\nTheorem ulist_swap {U} : ∀ (a b : U) l, a ː b ː l = b ː a ː l.\nProof.\n    intros a b l.\n    equiv_get_value l.\n    unfold ulist_add; equiv_simpl.\n    apply list_perm_swap.\nQed.\n\nTheorem ulist_skip {U} : ∀ (a : U) l1 l2, a ː l1 = a ː l2 → l1 = l2.\nProof.\n    intros a l1 l2.\n    equiv_get_value l1 l2.\n    unfold ulist_add; equiv_simpl.\n    apply list_perm_add_eq.\nQed.\n\nGlobal Instance ulist_plus_lcancel U : PlusLcancel (ulist U).\nProof.\n    split.\n    intros l1 l2 l3.\n    equiv_get_value l1 l2 l3.\n    unfold plus; equiv_simpl.\n    apply list_perm_conc_lcancel.\nQed.\n\nUnset Keyed Unification.\n\nTheorem list_image_perm {U V} : ∀ al bl (f : U → V),\n    list_permutation al bl →\n    list_permutation (list_image f al) (list_image f bl).\nProof.\n    intros al bl f albli x.\n    revert bl albli.\n    induction al as [|a al]; intros.\n    -   apply list_perm_nil_eq in albli.\n        subst bl.\n        rewrite list_image_end.\n        cbn.\n        reflexivity.\n    -   assert (in_list (a ꞉ al) a) as a_in by (left; reflexivity).\n        apply (list_perm_in albli) in a_in.\n        apply in_list_split in a_in as [l1 [l2 eq]]; subst bl.\n        pose proof (list_perm_split l1 l2 a) as eq.\n        pose proof (list_perm_trans albli eq) as eq2.\n        apply list_perm_add_eq in eq2.\n        specialize (IHal _ eq2).\n        rewrite list_image_conc.\n        do 2 rewrite list_image_add.\n        rewrite list_count_conc.\n        do 2 rewrite list_count_add.\n        rewrite IHal.\n        rewrite list_image_conc, list_count_conc.\n        do 2 rewrite plus_assoc.\n        apply rplus.\n        apply plus_comm.\nQed.\n\nLemma ulist_image_wd A B : ∀ (f : A → B) a b, list_permutation a b →\n    to_equiv (ulist_equiv B) (list_image f a) =\n    to_equiv (ulist_equiv B) (list_image f b).\nProof.\n    intros a b f ab.\n    equiv_simpl.\n    apply list_image_perm.\n    exact ab.\nQed.\nDefinition ulist_image {A B} (f : A → B) :=\n    unary_op (E := ulist_equiv A) (ulist_image_wd A B f).\n\nTheorem ulist_image_end {A B : Type} : ∀ f : A → B,\n    ulist_image f ⟦⟧ = ⟦⟧.\nProof.\n    intros f.\n    unfold ulist_end, ulist_image; equiv_simpl.\n    apply list_perm_refl.\nQed.\n\nTheorem ulist_image_add {A B : Type} : ∀ a l (f : A → B),\n    ulist_image f (a ː l) = f a ː ulist_image f l.\nProof.\n    intros a l f.\n    equiv_get_value l.\n    unfold ulist_image, ulist_add; equiv_simpl.\n    apply list_perm_refl.\nQed.\n\nTheorem ulist_image_conc {A B : Type} : ∀ a b (f : A → B),\n    ulist_image f (a + b) = ulist_image f a + ulist_image f b.\nProof.\n    intros a b f.\n    equiv_get_value a b.\n    unfold ulist_image, plus; equiv_simpl.\n    rewrite list_image_conc.\n    apply list_perm_refl.\nQed.\n\nTheorem ulist_image_comp {A B C : Type} :\n    ∀ (l : ulist A) (f : A → B) (g : B → C),\n    ulist_image g (ulist_image f l) = ulist_image (λ x, g (f x)) l.\nProof.\n    intros l f g.\n    equiv_get_value l.\n    unfold ulist_image; equiv_simpl.\n    rewrite list_image_comp.\n    apply list_perm_refl.\nQed.\n", "meta": {"author": "sudgy", "repo": "math-from-nothing", "sha": "5a80be4f6ca3818a76d0a38836c14fb0ecd1042e", "save_path": "github-repos/coq/sudgy-math-from-nothing", "path": "github-repos/coq/sudgy-math-from-nothing/math-from-nothing-5a80be4f6ca3818a76d0a38836c14fb0ecd1042e/src/List/unordered_list_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7078890321474721}}
{"text": "Inductive last (A: Set) (a : A) : list A -> Prop :=\n| last_single : last A a (cons a nil)\n| last_step : forall (y:A) (l:list A), last A a l -> last A a (cons y l).\n\nPrint option.\nPrint list.\nFixpoint last_fun {A: Set} (l : list A) : option A := match l with\n        | nil => None\n        | cons a nil => Some a\n        | cons a b => last_fun b\nend.\n\n\nFixpoint append {A : Set} (l1 l2 : list A): list A :=\n        match l1 with\n        | nil => l2\n        | cons a b => cons a (append b l2)\n        end.\n\nInductive palindrome (A:Set) : list A -> Prop :=\n| palin_nil : palindrome A nil\n| palin_single : forall x, palindrome A (cons x nil)\n| palin_nnil : forall (x:A) (l:list A), palindrome A l -> palindrome A (cons x (append l (cons x nil))).\n\nTheorem last_step_add:\n        forall (A:Set) (a x y: A) (l:list A), last A a (x::y::l)%list -> last A a (y::l).\n       Proof.\n              intros A a x y l h1.\n             inversion h1.  apply H0.\n       Qed.\n\nTheorem p2138p1:\n        forall (A: Set)(a: A)(l: list A),last _ ((fun c => match c with Some b => b | None => a  end) (last_fun (cons a l))) (cons a l).\n       Proof.\n           intros A a l.\n           change( last A (match (last_fun (a :: l)) with |Some b => b | None => a end) (a :: l)). \n           elim l. simpl; apply last_single.\n           intros a0 l0 h1. destruct l0. simpl. apply last_step. apply last_single. change (last A match last_fun (a :: (a1 :: l0)%list) with |Some b => b |None => a end (a :: (a0 :: a1 :: l0)%list)).\n           apply last_step. apply last_step. eapply last_step_add. apply h1.\n       Qed.\n\nDefinition relation (A: Type) := A -> A -> Prop. \n\nInductive sorted {A:Set} (R: A-> A -> Prop): list A -> Prop :=\n| sorted0 : sorted R nil\n| sorted1 : forall (x: A), sorted R (cons x nil)\n| sorted2 : forall (x y:A) (l:list A),\n                R x y -> sorted R (cons y l) -> sorted R (cons x (cons y l)).\n\nHint Resolve sorted0 sorted1 sorted2 : sorted_base.\n\nTheorem sorted_nat_123 : sorted le ((1 :: 2 :: 3 :: nil)%list).\nProof.\n        auto with sorted_base.\nQed.\n\nTheorem xy_ord :\n        forall x y:nat, le x y -> sorted le (x::y::nil)%list.\nProof.\n        auto with sorted_base.\nQed.\n\nRequire Import Arith.\n\nTheorem zero_cons_ord :\n        forall l:list nat, sorted le l -> sorted le (cons 0 l).\nProof.\n        induction l; auto with sorted_base arith.\nQed.\n\nTheorem sorted1_inv :\n        forall (A:Set) (le:A->A->Prop) (x:A) (l:list A),\n                sorted le (cons x l) -> sorted le l.\nProof.\n        intros A r x l h1; inversion h1; auto with sorted_base.\nQed.\n\nTheorem sorted2_inv :\n        forall (A:Set) (le:A -> A -> Prop) (x y :A) (l:list A),\n                sorted le (cons x (cons y l)) -> le x y.\n        Proof.\n                inversion 1; auto with sorted_base.\n        Qed.\n\n\nInductive cons_trans {A:Type} : nat -> list A -> list A -> Prop :=\n| cont0 : forall (l:list A), cons_trans   0 l l\n| cont1 :forall (n:nat) (x:A) (l1 l2:list A), cons_trans n l1 l2 -> cons_trans n (x::l1)%list (x::l2)%list\n| cont2 : forall (n:nat) (x y:A) (l1 l2:list A), cons_trans n l1 l2 -> cons_trans (S n) (x::y::l1)%list (y::x::l2)%list \n|cont3 : forall (n m:nat) (l1 l2 l3: list A), (cons_trans n l1 l2) -> (cons_trans m l2 l3) -> (cons_trans (n+m) l1 l3).\n\nDefinition permutation {A:Type} (x y: list A) : Prop := exists n : nat, cons_trans n x y.\n\nRequire Import Relations.\n\n\nHint Resolve cont0 cont1 cont2: perm_base.\nTheorem perm_refl:\n        forall (A:Type), reflexive (list A) permutation.\nProof.\n        unfold reflexive; unfold permutation.\n        intros A x. elim x. exists 0; auto with perm_base.\n        intros a l h1; inversion h1. exists x0; auto with perm_base.\nQed.\n\nTheorem perm_symm:\n        forall (A:Type), symmetric (list A) permutation.\nProof.\n        unfold symmetric; unfold permutation.\n        intros A. induction 1. induction H. exists 0; auto with perm_base.\n        inversion IHcons_trans. exists x0; auto with perm_base. inversion IHcons_trans. exists (S x0); auto with perm_base. inversion IHcons_trans1. inversion IHcons_trans2. exists (x0 + x); eapply cont3. apply H2. apply H1.\nQed.\n\n\nHint Resolve perm_refl perm_symm : perm_base.\n\nTheorem perm_tran:\n        forall (A:Type), transitive (list A) permutation.\nProof.\n        unfold transitive; unfold permutation.\n        intros A x y z h1 h2. inversion h1. inversion h2. exists (x0 + x1); eapply cont3; [apply H | trivial].\nQed.\n\nHint Resolve perm_tran : perm_base.        \nTheorem perm_equiv:\n        forall (A:Type), equiv (list A) permutation.\n        unfold equiv. intro A; auto with perm_base.\nQed.\n\nInductive par : Set := open | close.\n\nInductive wp : list par -> Prop:=\n| wp0 : wp nil\n| wp1 : forall (l1 l2 : list par), wp l1-> wp l2 -> wp (cons open (app l1 (cons close l2))).\n\nHint Resolve wp0 wp1 : wp_base.\n\n\nTheorem wp_oc : wp (cons open (cons close nil)).\nProof.\n        change (wp (open :: (app nil (close :: nil)%list))).\n        auto with wp_base.\nQed.\n\nTheorem wp_o_head_c :\n        forall l1 l2 : list par, wp l1 -> wp l2 -> wp (cons open (app l1 (cons close l2))).\nProof.\n        auto with wp_base.\nQed.\n\nRequire Import List.\nSearchRewrite (_ ++ (_ ++ _))%list.\n\nHint Resolve app_assoc:wp_base.\n\nTheorem wp_o_tail_c:\n        forall l1 l2:list par, wp l1 -> wp l2 ->\n                wp (app l1 (cons open (app l2 (cons close nil)))).\nProof.\n        induction 1; simpl; auto with wp_base.\n        intros. simpl. rewrite <- app_assoc. \n        change (wp ((open :: l1 ++ (close :: (l0 ++ (open :: l2 ++ close :: nil))))%list)).\n        auto with wp_base.\nQed.\n\nHint Resolve wp_o_tail_c : wp_base.\n\nInductive bin : Set := L : bin | N' : bin -> bin -> bin.\n\nFixpoint bin_to_string (t:bin) : list par :=\n        match t with\n        | L => nil\n        | N' u v => cons open (app (bin_to_string u) (cons close (bin_to_string v)))\n        end.\n\nTheorem wp_bin_to_string :\n        forall (t : bin), wp (bin_to_string t).\nProof.\n        induction t; simpl ; auto with wp_base.\nQed.\n\nFixpoint bin_to_string'  (t:bin) : list par:=\n        match t with\n        | L => nil\n        | N' u v => app (bin_to_string' u) (cons open (app (bin_to_string' v) (cons close nil)))\n        end.\n\nTheorem wp_bin_to_string' :\n        forall (t:bin), wp (bin_to_string' t).\nProof.\n        induction t; simpl; auto with wp_base.\nQed.\n\nRequire Import JMeq.\n\nTheorem JMEQHELPER1:\n        forall (x y : nat), JMeq x y -> JMeq (S x) (S y).\nProof.\n        intros.\n        elim H. trivial.\nQed.\n\n\nGoal forall (x y z:nat), JMeq (x+(y+z)) ((x+y)+z).\nProof.\n        induction x. simpl. auto. intros. simpl. apply JMEQHELPER1. trivial.\nQed.\n\nInductive even : nat -> Prop :=\n| even0 : even 0\n| even1 : forall (n:nat), even n -> even (S (S n)).\n\n\n\nTheorem even_double :\n        forall (x:nat), even x -> exists n:nat, x = 2*n.\nProof.\n        intros. induction H. exists 0;trivial.\n        inversion IHeven. exists (S x). rewrite -> H0. simpl; trivial. rewrite -> plus_assoc. rewrite -> plus_comm. simpl. pattern (x+0). rewrite -> plus_comm. simpl. pattern (x + S x). rewrite -> plus_comm. simpl. trivial.\nQed.\n\nTheorem double_even:\n        forall (x:nat), even (2 * x).\nProof.\n        intros. induction x. simpl; apply even0. simpl. pattern (x+0). rewrite -> plus_comm. simpl. rewrite -> plus_comm. simpl. apply even1. assert (forall x, x + x = 2 * x). induction x0;simpl; auto. rewrite -> H; trivial.\nQed.\n\nRequire Import Omega.\n\nOpen Scope Z_scope.\nInductive Pfact : Z -> Z -> Prop :=\n        pfact0 : Pfact 0 1\n        | pfact1 : forall n v: Z, n <> 0 -> Pfact (n-1) v -> Pfact n (n*v).\n\nGoal Pfact 3 6.\napply (pfact1 3 2).\ndiscriminate.\napply (pfact1 2 1).\ndiscriminate.\napply (pfact1 1 1).\ndiscriminate. \napply pfact0.\nQed.\n\nTheorem fact_dom : forall x y: Z, Pfact x y -> 0 <= x.\nProof.\n        intros. elim H. omega.\n        intros. omega.\nQed.\n\nRequire Import ZArith.\nRequire Import Zwf.\nCheck Zwf_well_founded.\n\nTheorem dom_fact_ex :\n        forall x: Z, 0<=x -> exists y : Z, Pfact x y.\nProof.\n        intro x0.\n        Check well_founded_ind.\n        elim x0 using (well_founded_ind (Zwf_well_founded 0)).\n        intros. elim (Zle_lt_or_eq _ _ H0). intros . elim (H (x-1)). intros. exists (x*x1). apply pfact1. omega. trivial. unfold Zwf. omega. omega. intros. exists 1. rewrite <- H1. apply pfact0.\nQed.\n\n\n\n\nPrint N.\nPrint bin.\nInductive parse_rel : list par -> list par -> bin -> Prop:=\n| parse_node : forall (l1 l2 l3:list par) (t1 t2 : bin), parse_rel l1 (cons close l2) t1 -> parse_rel l2 l3 t2 -> parse_rel (cons open l1) l3 (N' t1 t2)\n| parse_leaf_nil : parse_rel nil nil L\n| parse_leaf_close :\n                forall l:list par, parse_rel (cons close l) (cons close l) L.\n\nSearchRewrite (_ ++_)%list.\n\nTheorem parse_rel_sound_anx :\n        forall (l1 l2:list par) (t:bin),\n        parse_rel l1 l2 t -> l1 = app (bin_to_string t) l2.\nProof.\n        induction 1. simpl. rewrite <- app_assoc. pattern ((close :: bin_to_string t2) ++ l3). rewrite <- app_comm_cons. rewrite <- IHparse_rel2. rewrite <- IHparse_rel1. trivial. simpl;trivial. simpl;trivial.\nQed.\n\nTheorem parse_rel_sound :\n        forall l: list par, (exists t:bin, parse_rel l nil t) -> wp l.\nProof.\n        inversion 1. assert (l = app (bin_to_string x) nil). apply parse_rel_sound_anx. trivial. rewrite <- app_nil_end in H1. rewrite -> H1. apply wp_bin_to_string.\nQed.\n\n\nSection little_semantics.\nVariables Var aExp bExp : Set.\nInductive inst : Set :=\n| Skip : inst\n| Assign : Var -> aExp -> inst\n| Sequence : inst -> inst -> inst\n| WhileDo : bExp -> inst -> inst.\n\nVariables\n (state : Set)\n (update : state -> Var-> Z -> option state)\n (evalA : state -> aExp -> option Z)\n (evalB : state -> bExp -> option bool).\n\nInductive exec : state -> inst -> state -> Prop :=\n| execSkip : forall s:state, exec s Skip s\n| execAssign :\n    forall (s s1:state)(v:Var)(n:Z)(a:aExp),\n    evalA s a = Some n -> update s v n = Some s1 -> exec s (Assign v a) s1\n| execSequence :\n    forall (s s1 s2:state)(i1 i2:inst),\n    exec s i1 s1 -> exec s1 i2 s2 -> exec s (Sequence i1 i2) s2\n| execWhileFalse :\n    forall (s :state) (e: bExp)(i:inst),\n    evalB s e = Some false -> exec s (WhileDo e i) s\n| execWhileTrue :\n    forall (s s1 s2 : state)(i:inst) (e:bExp),\n    evalB s e = Some true -> exec s i s1 ->  exec s1 (WhileDo e i) s2 -> exec s (WhileDo e i) s2.\n\nTheorem some_true:\n        forall x:option bool, x = Some true \\/ x = Some false \\/ x = None.\nProof.\n        intro x; destruct x; try tauto. destruct b; try tauto.\nQed.\n\n\nTheorem HoareWhileRule_1:\n        forall (P:state -> Prop) (b:bExp)(i:inst)(s s':state),\n        (forall s1 s2:state, P s1 -> evalB s1 b = Some true -> exec s1 i s2 -> P s2) -> P s -> exec s (WhileDo b i) s' -> P s' /\\ evalB s' b = Some false.\nProof.\n        intros P b i s s' H.\n        cut (forall i',exec s i' s' -> i' = WhileDo b i -> P s -> P s' /\\ evalB s' b = Some false).\n        eauto.\n        intros i' h. elim h; try (intros; discriminate).\n        intros. injection H1. intros. rewrite <- H4. split; trivial.\n        intros. injection H5. intros. assert (h2 : P s1). rewrite -> H8 in H0; rewrite -> H7 in H1. apply (H s0 s1 H6 H0 H1). apply H4; trivial.\nQed.\n\nTheorem NeverHalt:\n        forall (s s': state) (b:bExp),\n        exec s (WhileDo b Skip) s' -> evalB s b = Some true -> False.\nProof.\n        cut (forall (s s':state) (b:bExp) (i:inst), exec s i s' -> i = WhileDo b Skip -> evalB s b = Some true -> False). intro. eauto.\n        intros s s' b i h1. elim h1; try (intros; discriminate).\n        intros. injection H0. intros. rewrite <-H3 in H1. rewrite -> H1 in H. discriminate.\n        intros. injection H4; intros. rewrite -> H6 in H0; inversion H0. rewrite -> H10 in H5. apply H3; trivial.\nQed.\n\n\nTheorem HoareSeqRule:\n        forall (P: state -> Prop) (i1 i2:inst),\n        (forall (s s':state), P s -> exec s i1 s' -> P s') -> (forall (s s':state),P s -> exec s i2 s' -> P s') -> (forall (s1 s2:state), P s1 -> exec s1 (Sequence i1 i2) s2 -> P s2).\nProof.\n        intros. inversion H2.\n        apply (H0 s0 s2);trivial.\n        apply (H s1 s0);trivial.\nQed.\n\nEnd little_semantics.\n\n\nClose Scope Z_scope.\n\nGoal ~sorted le ((1::3::2::nil)%list).\nunfold not.\nintros.\ninversion H. inversion H4. \ninversion H7. inversion H11. inversion H13.\nQed.\n\nGoal ~(even 1).\nunfold not; intros.\ngeneralize (eq_refl 1). pattern 1 at -2. \nelim H. intros; discriminate.\nintros; discriminate.\nQed.\n\nInductive stampprice : nat -> Prop:=\n| sp0 : stampprice 3\n| sp1 : stampprice 5\n| sp2 : forall (n m:nat), stampprice n -> stampprice m -> stampprice (n+m).\n\nHint Resolve sp0 sp1 sp2: sp_base.\n\nTheorem StrongInd:\n        forall (P:nat -> Prop),\n        P 0 ->\n        (forall m:nat, (forall n:nat, n < m -> P n) -> P m) -> (forall m:nat, P m).\nProof.\n        intros.\n        assert (forall n, (forall m, m < n -> P m)).\n        intro. induction n. intros. inversion H1.\n        intros. inversion H1. apply H0. apply IHn.\n        apply IHn. omega.\n        generalize m. clear m. intros m. induction m; trivial. apply H1 with (n:= S (S m)). omega.\nQed.\n\nGoal forall n, n >= 8 -> stampprice n. \nintro. pattern n. elim n using StrongInd. intros; omega.\nintros.inversion H0. change (stampprice (3+5)). auto with sp_base arith. inversion H1. change (stampprice (3 + 3 + 3)). auto with sp_base arith. inversion H3. change (stampprice (5 + 5)). auto with sp_base arith. change (stampprice (3 + m2)). apply sp2. apply sp0. apply H; omega.\nQed.\n\n\n\n\n\n\n\n\n", "meta": {"author": "DKXXXL", "repo": "Coq-Art-Exercises", "sha": "139d1dbf85204f1106f4afe5d15f1f2aee1b48df", "save_path": "github-repos/coq/DKXXXL-Coq-Art-Exercises", "path": "github-repos/coq/DKXXXL-Coq-Art-Exercises/Coq-Art-Exercises-139d1dbf85204f1106f4afe5d15f1f2aee1b48df/8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7078431866371768}}
{"text": "Require Import Nijn.Prelude.\nRequire Import Nijn.Syntax.Signature.\nRequire Import Nijn.Syntax.Signature.RewriteLemmas.\n\nImport AFSNotation.\n\n(** * Strong normalization *)\n\n(** An AFS is strongly normalizing if the rewriting relation is well-founded *)\nDefinition isSN\n           {B F : Type}\n           (X : afs B F)\n  : Prop\n  := forall (C : con B) (A : ty B), Wf (fun (t1 t2 : tm X C A) => t1 ∼> t2).\n\n(** A type is said to be strongly normalizing if the rewrite relations of terms on that type is strongly normalizing *)\nDefinition Ty_isSN\n           {B F : Type}\n           (X : afs B F)\n           (A : ty B)\n  : Prop\n  := forall (C : con B), Wf (fun (t1 t2 : tm X C A) => t1 ∼> t2).\n\n(** We show that if one type is strongly normalizing, then all types are. Hence, it is sufficient to check for strong normalization in just one type. *)\nDefinition map_Tm\n           {B F : Type}\n           {X : afs B F}\n           {C : con B}\n           (A : ty B)\n           {A' : ty B}\n           (t : tm X C A')\n  : tm X (A' ⟶ A ,, C) A\n  := TmVar Vz · wkTm t (Drop _ (idWk C)).\n\nDefinition Rew_map_Tm\n           {B F : Type}\n           {X : afs B F}\n           {C : con B}\n           {A A' : ty B}\n           {t1 t2 : tm X C A'}\n           (p : t1 ∼> t2)\n  : map_Tm A t1 ∼> map_Tm A t2.\nProof.\n  unfold map_Tm.\n  apply rew_App_r.\n  apply Rew_Wk.\n  exact p.\nQed.\n\nTheorem SN_if_TySN\n        {B F : Type}\n        (X : afs B F)\n        (A : ty B)\n        (H : Ty_isSN X A)\n  : isSN X.\nProof.\n  intros C A'.\n  simple refine (fiber_Wf (H ((A' ⟶ A) ,, C)) _ _).\n  - exact (map_Tm _).\n  - intros t1 t2.\n    exact Rew_map_Tm.\nQed.    \n", "meta": {"author": "nmvdw", "repo": "Nijn", "sha": "9bd88a93cdf0ab521536249fe628e9e63341f473", "save_path": "github-repos/coq/nmvdw-Nijn", "path": "github-repos/coq/nmvdw-Nijn/Nijn-9bd88a93cdf0ab521536249fe628e9e63341f473/Code/Syntax/StrongNormalization/SN.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7078431827766971}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. You may distribute   *)\n(* under the terms of either the CeCILL-B License or the CeCILL        *)\n(* version 2 License, as specified in the README file.                 *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice fintype.\nRequire Import div paths bigops finset.\n\n(*****************************************************************************)\n(* This file defines the main interface for finite groups :                  *)\n(*          finGroupType == the structure for finite types with a group law  *)\n(*           {group gT}  == type of groups with elements of type gT          *)\n(* If gT implements finGroupType, then we can form {set gT}, the type of     *)\n(* finite sets with elements of type gT (as finGroupType extends finType).   *)\n(* The group law extends pointwise to {set gT}, which thus implements a sub- *)\n(* interface baseFinGroupType of finGroupType. To be consistent with the     *)\n(* predType interface, this is done by coercion to FinGroup.arg_sort, an     *)\n(* alias for FinGroup.sort. Accordingly, all pointwise group operations      *)\n(* below have arguments of type (FinGroup.arg_sort) gT and return results    *)\n(* of type FinGroup.sort gT.                                                 *)\n(*   The notations below are declared in two scopes:                         *)\n(*      group_scope (delimiter %g) for point operations and set constructs   *)\n(*   subgroup_scope (delimiter %G) for explicit {group gT} structures        *)\n(* These scopes should not be opened globally, athough group_scope is often  *)\n(* opened locally in group-theory files (via Import GroupScope).             *)\n(*  {group gT} is an interface structure for {set gT} (as well as a subtype) *)\n(* so the fact that a given G : {set gT} is a group can (and usually should) *)\n(* be inferred by type inference with Canonical Structures. This means that  *)\n(* all \"group\" constructions (e.g., the normaliser 'N_G(H)) actually define  *)\n(* sets with a canonical {group gT} structure; the %G delimiter can be used  *)\n(* to specify the actual {group gT} structure (e.g., 'N_G(H)%G).             *)\n(*  Operations on elements of a group                                        *)\n(*            x * y     == internal group operation                          *)\n(*            x ^+ n    == power operation                                   *)\n(*            x^-1      == inverse group operation                           *)\n(*            x ^- n    == inverse power operation                           *)\n(*            1         == unit element                                      *)\n(*           x ^ y      == the conjugate of x by y                           *)\n(*  \\prod_(i ...) x i   == product of the x i (order-sensitive)              *)\n(*         commute x y  <=> x and y commute                                  *)\n(*      centralises x A <=> x centralises A                                  *)\n(*           'C[x]      == the set of elements that commutes with x          *)\n(*           'C_G[x]    == the set of elements of G that commutes with x     *)\n(*            <[x]>     == cyclic subgroup generated by the element x        *)\n(*            #[x]      == order of the element x                            *)\n(*     [~ x1, ..., xn]  == commutator of x1, ..., xn                         *)\n(*  Operations on sets of a finite group                                     *)\n(*            H * G     == {xy | x \\in H, y \\in G}                           *)\n(*   1 or [1] or [1 gT] == the unit group                                    *)\n(* [setT]%G or [setT gT]%G == the group of all x : gT (in subgroup_scope)    *)\n(*            subg_of G == the subtype of all x \\in G                        *)\n(*                         if G is a group, subg_of G is a finGroupType      *)\n(*          subg, sgval == projection into, injection from subg_of G         *)\n(*             [subg G] == the set (or group) of all u : subg_of G           *)\n(*            H^#       == the set H minus the unit element                  *)\n(*            repr H    == some element of H if 1 \\notin H != set0, else 1   *)\n(*          x *: H      == left coset of H by x                              *)\n(*          lcosets H G == the set of the left cosets of H by elements of G  *)\n(*          H :* x      == right coset of H by x                             *)\n(*          rcosets H G == the set of the right cosets of H by elements of G *)\n(*           #|G : H|   == the index of H in G                               *)\n(*            H :^ x    == the conjugate of H by x                           *)\n(*            x ^: H    == the conjugate class of x in H                     *)\n(*            G :^: H   == the set of all conjugate classes                  *)\n(*    class_support G H == {x ^ y | x \\in G, y \\in H}                        *)\n(*     [~: H1, ..., Hn] == commutator subgroup of H1, ..., Hn                *)\n(*{in G, centralised H} <=> G centralises H                                  *)\n(* {in G, normalised H} <=> G normalises H                                   *)\n(*                      <=> forall x, x \\in G -> H :^ x = H                  *)\n(*            'N(H)     == the normaliser of H                               *)\n(*            'N_G(H)   == the normaliser of H in G                          *)\n(*             H <| G   <=> H is normal in G                                 *)\n(*            'C(H)     == the centraliser of H                              *)\n(*            'C_G(H)   == the centraliser of H in G                         *)\n(*             <<H>>    == subgroup generated by the set H                   *)\n(*            H <*> G   == subgroup generated by H * G                       *)\n(* (\\prod_(i ...) H i)%G  == group generated by the H i                      *)\n(*           abelian H  <=> H is abelian                                     *)\n(*       [max G | P G ] <=> G is the largest group such that P holds         *)\n(*  [max H of G | P G ] <=> H is the largest group such that P holds         *)\n(*       [min G | P G ] <=> G is the smallest group such that P holds        *)\n(*  [min H of G | P G ] <=> H is the smallest group such that P holds        *)\n(*****************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nDelimit Scope group_scope with g.\nDelimit Scope subgroup_scope with G.\n\n(* This module can be imported to open the scope for group element *)\n(* operations locally to a file, without exporing the Open to      *)\n(* clients of that file (as Open would do).                        *)\nModule GroupScope.\nOpen Scope group_scope.\nEnd GroupScope.\nImport GroupScope.\n\nModule FinGroup.\n\n(* We split the group axiomatisation in two. We define a  *)\n(* class of \"base groups\", which are basically monoids    *)\n(* with an involutive antimorphism, from which we derive  *)\n(* the class of groups proper. This allows use to reuse   *)\n(* much of the group notation and algebraic axioms for    *)\n(* group subsets, by defining a base group class on them. *)\n(*   We use class/mixins here rather than telescopes to   *)\n(* be able to interoperate with the type coercions.       *)\n(* Another potential benefit (not exploited here) would   *)\n(* be to define a class for infinite groups, which could  *)\n(* share all of the algebraic laws.                       *)\nRecord mixin_of (T : Type) : Type := BaseMixin {\n  mul : T -> T -> T;\n  one : T;\n  inv : T -> T;\n  _ : associative mul;\n  _ : left_id one mul;\n  _ : involutive inv;\n  _ : {morph inv : x y / mul x y >-> mul y x}\n}.\n\nStructure base_type : Type := PackBase {\n  sort : Type;\n   _ : mixin_of sort;\n   _ : Finite.class_of sort\n}.\n\n(* We want to use sort as a coercion class, both to infer         *)\n(* argument scopes properly, and to allow groups and cosets to    *)\n(* coerce to the base group of group subsets.                     *)\n(*   However, the return type of group operations should NOT be a *)\n(* coercion class, since this would trump the real (head-normal)  *)\n(* coercion class for concrete group types, thus spoiling the     *)\n(* coercion of A * B to pred_sort in x \\in A * B, or rho * tau to *)\n(* ffun and Funclass in (rho * tau) x, when rho tau : perm T.     *)\n(*   Therefore we define an alias of sort for argument types, and *)\n(* make it the default coercion FinGroup.base_class >-> Sortclass *)\n(* so that arguments of a functions whose parameters are of type, *)\n(* say, gT : finGroupType, can be coerced to the coercion class   *)\n(* of arg_sort. Care should be taken, however, to declare the     *)\n(* return type of functions and operators as FinGroup.sort gT     *)\n(* rather than gT, e.g., mulg : gT -> gT -> FinGroup.sort gT.     *)\n(* Note that since we do this here and in normal.v for all the    *)\n(* basic functions, the inferred return type should generally be  *)\n(* correct.                                                       *)\nCoercion arg_sort := sort.\n(* Declaring sort as a Coercion is clearly redundant; it only     *)\n(* serves the purpose of eliding FinGroup.sort in the display of  *)\n(* return types. The warning could be eliminated by using the     *)\n(* functor trick to replace Sortclass by a dummy target.          *)\nCoercion sort : base_type >-> Sortclass.\n\nCoercion mixin T :=\n  let: PackBase _ m _ := T return mixin_of (sort T) in m.\n\nDefinition finClass T :=\n  let: PackBase _ _ m := T return Finite.class_of (sort T) in m.\n\nStructure type : Type := Pack {\n  base :> base_type;\n  _ : left_inverse (one base) (inv base) (mul base)\n}.\n\n(* We only need three axioms to make a true group. *)\n\nSection Mixin.\n\nVariables (T : Type) (one : T) (mul : T -> T -> T) (inv : T -> T).\n\nHypothesis mulA : associative mul.\nHypothesis mul1 : left_id one mul.\nHypothesis mulV : left_inverse one inv mul.\nNotation \"1\" := one.\nInfix \"*\" := mul.\nNotation \"x ^-1\" := (inv x).\n\nLemma mk_invgK : involutive inv.\nProof.\nhave mulV21: forall x, x^-1^-1 * 1 = x.\n  by move=> x; rewrite -(mulV x) mulA mulV mul1.\nby move=> x; rewrite -[_ ^-1]mulV21 -(mul1 1) mulA !mulV21.\nQed.\n\nLemma mk_invMg : {morph inv : x y / x * y >-> y * x}.\nProof.\nhave mulxV: forall x, x * x^-1 = 1 by move=> x; rewrite -{1}[x]mk_invgK mulV.\nmove=> x y /=; rewrite -[y^-1 * _]mul1 -(mulV (x * y)) -2!mulA (mulA y).\nby rewrite mulxV mul1 mulxV -(mulxV (x * y)) mulA mulV mul1.\nQed.\n\nDefinition Mixin := BaseMixin mulA mul1 mk_invgK mk_invMg.\n\nEnd Mixin.\n\nDefinition pack_base := let k T c m := PackBase m c in Finite.unpack k.\n\nDefinition repack_base gT :=\n  let: PackBase _ m c := gT return {type of PackBase for sort gT} -> _ in\n  fun k => k m c.\n\nDefinition repack gT :=\n  let: Pack c ax := gT return {type of Pack for gT} -> _ in fun k => k ax.\n\nDefinition repack_arg gT of phant (sort gT) := @Pack gT.\n\nEnd FinGroup.\n\nBind Scope group_scope with FinGroup.sort.\nBind Scope group_scope with FinGroup.arg_sort.\n\nNotation baseFinGroupType := FinGroup.base_type.\nNotation BaseFinGroupType := FinGroup.pack_base.\n\nSection InheritedClasses.\n\nVariable T : baseFinGroupType.\nNotation c := (FinGroup.finClass T).\nNotation rT := (FinGroup.sort T).\n\nCanonical Structure finGroup_eqType := Equality.Pack c rT.\nCanonical Structure finGroup_choiceType := Choice.Pack c rT.\nCanonical Structure finGroup_countType := Countable.Pack c rT.\nCanonical Structure finGroup_finType := Finite.Pack c rT.\nCanonical Structure finGroup_arg_eqType := Eval hnf in [eqType of T].\nCanonical Structure finGroup_arg_choiceType := Eval hnf in [choiceType of T].\nCanonical Structure finGroup_arg_countType := Eval hnf in [countType of T].\nCanonical Structure finGroup_arg_finType := Eval hnf in [finType of T].\n\nEnd InheritedClasses.\n\nCoercion finGroup_arg_finType : baseFinGroupType >-> finType.\n\nNotation \"[ 'baseFinGroupType' 'of' T ]\" :=\n    (FinGroup.repack_base (fun m => @FinGroup.PackBase T m))\n  (at level 0, format \"[ 'baseFinGroupType'  'of'  T ]\") : form_scope.\n\nNotation finGroupType := FinGroup.type.\nNotation FinGroupType := FinGroup.Pack.\n\nNotation \"[ 'finGroupType' 'of' T ]\" :=\n    (FinGroup.repack (FinGroup.repack_arg (Phant T)))\n  (at level 0, format \"[ 'finGroupType'  'of'  T ]\") : form_scope.\n\nSection ElementOps.\n\nVariable T : baseFinGroupType.\nNotation rT := (FinGroup.sort T).\n\nDefinition oneg : rT := FinGroup.one T.\nDefinition mulg : T -> T -> rT := FinGroup.mul T.\nDefinition invg : T -> rT := FinGroup.inv T.\nDefinition expgn_rec (x : T) n : rT := iterop n mulg x oneg.\n\nEnd ElementOps.\n\nDefinition expgn := nosimpl expgn_rec.\n\nNotation \"1\" := (oneg _) : group_scope.\nNotation \"x1 * x2\" := (mulg x1 x2) : group_scope.\nNotation \"x ^-1\" := (invg x) : group_scope.\nNotation \"x ^+ n\" := (expgn x n) : group_scope.\nNotation \"x ^- n\" := (x ^+ n)^-1 : group_scope.\n\n(* Arguments of conjg are restricted to true groups to avoid an *)\n(* improper interpretation of A ^ B with A and B sets, namely:  *)\n(*       {x^-1 * (y * z) | y \\in A, x, z \\in B}                 *)\nDefinition conjg (T : finGroupType) (x y : T) := y^-1 * (x * y).\nNotation \"x1 ^ x2\" := (conjg x1 x2) : group_scope.\n\nDefinition commg (T : finGroupType) (x y : T) := x^-1 * x ^ y.\nNotation \"[ ~ x1 , x2 , .. , xn ]\" := (commg .. (commg x1 x2) .. xn)\n  (at level 0,\n   format  \"'[ ' [ ~  x1 , '/'  x2 , '/'  .. , '/'  xn ] ']'\") : group_scope.\n\nPrenex Implicits mulg invg expgn conjg commg.\n\nNotation \"\\prod_ ( <- r | P ) F\" :=\n  (\\big[mulg/1]_(<- r | P%B) F%g) : group_scope.\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[mulg/1]_(i <- r | P%B) F%g) : group_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[mulg/1]_(i <- r) F%g) : group_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[mulg/1]_(m <= i < n | P%B) F%g) : group_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[mulg/1]_(m <= i < n) F%g) : group_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[mulg/1]_(i | P%B) F%g) : group_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[mulg/1]_i F%g) : group_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[mulg/1]_(i : t | P%B) F%g) (only parsing) : group_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[mulg/1]_(i : t) F%g) (only parsing) : group_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[mulg/1]_(i < n | P%B) F%g) : group_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[mulg/1]_(i < n) F%g) : group_scope.\nNotation \"\\prod_ ( i \\in A | P ) F\" :=\n  (\\big[mulg/1]_(i \\in A | P%B) F%g) : group_scope.\nNotation \"\\prod_ ( i \\in A ) F\" :=\n  (\\big[mulg/1]_(i \\in A) F%g) : group_scope.\n\nSection PreGroupIdentities.\n\nVariable T : baseFinGroupType.\nImplicit Types x y z : T.\n\nLemma mulgA : @associative T mulg.  Proof. by case: T => ? []. Qed.\nLemma mul1g : @left_id T 1 mulg.  Proof. by case: T => ? []. Qed.\nLemma invgK : @involutive T invg.   Proof. by case: T => ? []. Qed.\nLemma invMg : forall x y, (x * y)^-1 = y^-1 * x^-1.\nProof. by case: T => ? []. Qed.\n\nLemma invg_inj : @injective T T invg. Proof. exact: can_inj invgK. Qed.\n\nLemma eq_invg_sym : forall x y, (x^-1 == y :> T) = (x == y^-1).\nProof. by move=> x y; exact: (inv_eq invgK). Qed.\n\nLemma invg1 : 1^-1 = 1 :> T.\nProof. by apply: invg_inj; rewrite -{1}[1^-1]mul1g invMg invgK mul1g. Qed.\n\nLemma eq_invg1 : forall x, (x^-1 == 1 :> T) = (x == 1).\nProof. by move=> x; rewrite eq_invg_sym invg1. Qed.\n\nLemma mulg1 : @right_id T 1 mulg.\nProof. by move=> x; apply: invg_inj; rewrite invMg invg1 mul1g. Qed.\n\nCanonical Structure finGroup_law := Monoid.Law mulgA mul1g mulg1.\n\nLemma expgnE : forall x n, x ^+ n = expgn_rec x n. Proof. by []. Qed.\n\nLemma expg0 : forall x, x ^+ 0 = 1. Proof. by []. Qed.\nLemma expg1 : forall x, x ^+ 1 = x. Proof. by []. Qed.\n\nLemma expgS : forall x n, x ^+ n.+1 = x * x ^+ n.\nProof. by move=> x [|n]; rewrite ?mulg1. Qed.\n\nLemma exp1gn : forall n, 1 ^+ n = 1 :> T.\nProof. by elim=> // n IHn; rewrite expgS mul1g. Qed.\n\nLemma expgn_add : forall x n m, x ^+ (n + m) = x ^+ n * x ^+ m.\nProof. by move=> x; elim=> [|n IHn] m; rewrite ?mul1g // !expgS IHn mulgA. Qed.\n\nLemma expgSr : forall x n, x ^+ n.+1 = x ^+ n * x.\nProof. by move=> x n; rewrite -addn1 expgn_add expg1. Qed.\n\nLemma expgn_mul : forall x n m, x ^+ (n * m) = x ^+ n ^+ m.\nProof.\nmove=> x n; elim=> [|m IHm]; first by rewrite muln0 expg0.\nby rewrite mulnS expgn_add IHm expgS.\nQed.\n\nDefinition commute x y := x * y = y * x.\n\nLemma commute_refl : forall x, commute x x.\nProof. by []. Qed.\n\nLemma commute_sym : forall x y, commute x y -> commute y x.\nProof. by []. Qed.\n\nLemma commute1 : forall x, commute x 1.\nProof. by move=> x; rewrite /commute mulg1 mul1g. Qed.\n\nLemma commuteM : forall x y z,\n  commute x y ->  commute x z ->  commute x (y * z).\nProof. by move=> x y z cxy cxz; rewrite /commute -mulgA -cxz !mulgA cxy. Qed.\n\nLemma commuteX : forall x y n, commute x y ->  commute x (y ^+ n).\nProof.\nrewrite /commute => x y n cxy.\nby elim: n => [|n IHn]; rewrite ?commute1 // !expgS commuteM.\nQed.\n\nLemma commuteX2 : forall x y m n, commute x y ->  commute (x ^+ m) (y ^+ n).\nProof. move=> *; apply: commuteX; apply: commute_sym; exact: commuteX. Qed.\n\nLemma expVgn : forall x n, x^-1 ^+ n = x ^- n.\nProof.\nby move=> x; elim=> [|n IHn]; rewrite ?invg1 // expgSr expgS invMg IHn.\nQed.\n\nLemma expMgn : forall x y n, commute x y -> (x * y) ^+ n  = x ^+ n * y ^+ n.\nProof.\nmove=> x y n cxy; elim: n => [| n IHn]; first by rewrite mulg1.\nby rewrite !expgS IHn -mulgA (mulgA y) (commuteX _ (commute_sym cxy)) !mulgA.\nQed.\n\nEnd PreGroupIdentities.\n\nHint Resolve commute1.\nImplicit Arguments invg_inj [T].\nPrenex Implicits commute invgK invg_inj.\n\nSection GroupIdentities.\n\nVariable T : finGroupType.\nImplicit Types x y z : T.\n\nLemma mulVg : @left_inverse T 1 invg mulg.\nProof. by case T. Qed.\n\nLemma mulgV : @right_inverse T 1 invg mulg.\nProof. by move=> x; rewrite -{1}(invgK x) mulVg. Qed.\n\nLemma mulKg : forall x, cancel (mulg x) (mulg x^-1).\nProof. by move=> x y; rewrite mulgA mulVg mul1g. Qed.\n\nLemma mulKVg : forall x, cancel (mulg x^-1) (mulg x).\nProof. by move=> x y; rewrite mulgA mulgV mul1g. Qed.\n\nLemma mulgI : forall x, injective (mulg x).\nProof. move=> x; exact: can_inj (mulKg x). Qed.\n\nLemma mulgK : forall x, cancel (mulg^~ x) (mulg^~ x^-1).\nProof. by move=> x y; rewrite -mulgA mulgV mulg1. Qed.\n\nLemma mulgKV : forall x, cancel (mulg^~ x^-1) (mulg^~ x).\nProof. by move=> x y; rewrite -mulgA mulVg mulg1. Qed.\n\nLemma mulIg : forall x, injective (mulg^~ x).\nProof. move=> x; exact: can_inj (mulgK x). Qed.\n\nLemma eq_invg_mul : forall x y, (x^-1 == y :> T) = (x * y == 1 :> T).\nProof. by move=> x y; rewrite -(inj_eq (@mulgI x)) mulgV eq_sym. Qed.\n\nLemma eq_mulgV1 : forall x y, (x == y) = (x * y^-1 == 1 :> T).\nProof. by move=> x y; rewrite -(inj_eq invg_inj) eq_invg_mul. Qed.\n\nLemma eq_mulVg1 : forall x y, (x == y) = (x^-1 * y == 1 :> T).\nProof. by move=> x y; rewrite -eq_invg_mul invgK. Qed.\n\nLemma commuteV : forall x y, commute x y -> commute x y^-1.\nProof.\nby move=> x y cxy; apply: (@mulIg y); rewrite mulgKV -mulgA cxy mulKg.\nQed.\n\nLemma conjgE : forall x y, x ^ y = y^-1 * (x * y). Proof. by []. Qed.\n\nLemma conjgC : forall x y, x * y = y * x ^ y.\nProof. by move=> x y; rewrite mulKVg. Qed.\n\nLemma conjgCV : forall x y, x * y = y ^ x^-1 * x.\nProof. by move=> x y; rewrite -mulgA mulgKV invgK. Qed.\n\nLemma conjg1 : forall x, x ^ 1 = x.\nProof. by move=> x; rewrite conjgE commute1 mulKg. Qed.\n\nLemma conj1g : forall x, 1 ^ x = 1.\nProof. by move=> x; rewrite conjgE mul1g mulVg. Qed.\n\nLemma conjMg : forall x y z, (x * y) ^ z = x ^ z * y ^ z.\nProof. by move=> x y z; rewrite !conjgE !mulgA mulgK. Qed.\n\nLemma conjgM : forall x y z, x ^ (y * z) = (x ^ y) ^ z.\nProof. by move=> x y z; rewrite !conjgE invMg !mulgA. Qed.\n\nLemma conjVg : forall x y, x^-1 ^ y = (x ^ y)^-1.\nProof. by move=> x y; rewrite !conjgE !invMg invgK mulgA. Qed.\n\nLemma conjJg : forall x y z, (x ^ y) ^ z = (x ^ z) ^ y ^ z.\nProof. by move=> x y z; rewrite 2!conjMg conjVg. Qed.\n\nLemma conjXg : forall x y n, (x ^+ n) ^ y = (x ^ y) ^+ n.\nProof.\nby move=> x y; elim=> [|n IHn]; rewrite ?conj1g // !expgS conjMg IHn.\nQed.\n\nLemma conjgK : forall y, cancel (conjg^~ y) (conjg^~ y^-1).\nProof. by move=> y x; rewrite -conjgM mulgV conjg1. Qed.\n\nLemma conjgKV : forall y, cancel (conjg^~ y^-1) (conjg^~ y).\nProof. by move=> y x; rewrite -conjgM mulVg conjg1. Qed.\n\nLemma conjg_inj : forall y, injective (conjg^~ y).\nProof. move=> y; exact: can_inj (conjgK y). Qed.\n\nLemma commgEl : forall x y, [~ x, y] = x^-1 * x ^ y. Proof. by []. Qed.\n\nLemma commgEr : forall x y, [~ x, y] = y^-1 ^ x * y.\nProof. by move=> x y; rewrite -!mulgA. Qed.\n\nLemma commgC : forall x y, x * y = y * x * [~ x, y].\nProof. by move=> x y; rewrite -mulgA !mulKVg. Qed.\n\nLemma commgCV : forall x y, x * y = [~ x^-1, y^-1] * (y * x).\nProof. by move=> x y; rewrite commgEl !mulgA !invgK !mulgKV. Qed.\n\nLemma conjRg : forall x y z, [~ x, y] ^ z = [~ x ^ z, y ^ z].\nProof. by move=> x y z; rewrite !conjMg !conjVg. Qed.\n\nLemma invg_comm : forall x y, [~ x, y]^-1 = [~ y, x].\nProof. by move=> x y; rewrite commgEr conjVg invMg invgK. Qed.\n\nLemma commgP : forall x y, reflect (commute x y) ([~ x, y] == 1 :> T).\nProof.\nmove=> x y; rewrite [[~ x, y]]mulgA -invMg -eq_mulVg1 eq_sym; exact: eqP.\nQed.\n\nLemma conjg_fixP : forall x y, reflect (x ^ y = x) ([~ x, y] == 1 :> T).\nProof. move=> x y; rewrite -eq_mulVg1 eq_sym; exact: eqP. Qed.\n\nLemma commg1_sym : forall x y, ([~ x, y] == 1 :> T) = ([~ y, x] == 1 :> T).\nProof. by move=> x y; rewrite -invg_comm (inv_eq invgK) invg1. Qed.\n\nLemma commg1 : forall x, [~ x, 1] = 1.\nProof. by move=> x; apply/eqP; apply/commgP. Qed.\n\nLemma comm1g : forall x, [~ 1, x] = 1.\nProof. by move=> x; rewrite -invg_comm commg1 invg1. Qed.\n\nLemma commgg : forall x, [~ x, x] = 1.\nProof. by move=> x; apply/eqP; apply/commgP. Qed.\n\nLemma commgXg : forall x n, [~ x, x ^+ n] = 1.\nProof. by move=> x n; apply/eqP; apply/commgP; exact: commuteX. Qed.\n\nLemma commgVg : forall x, [~ x, x^-1] = 1.\nProof. by move=> x; apply/eqP; apply/commgP; exact: commuteV. Qed.\n\nLemma commgXVg : forall x n, [~ x, x ^- n] = 1.\nProof.\nmove=> x n;  apply/eqP; apply/commgP; apply: commuteV; exact: commuteX.\nQed.\n\n(* Other commg identities should slot in here. *)\n\nEnd GroupIdentities.\n\nHint Rewrite mulg1 mul1g invg1 mulVg mulgV (@invgK) mulgK mulgKV\n             invMg mulgA : gsimpl.\n\nLtac gsimpl := autorewrite with gsimpl; try done.\n\nDefinition gsimp := (mulg1 , mul1g, (invg1, @invgK), (mulgV, mulVg)).\nDefinition gnorm := (gsimp, (mulgK, mulgKV, (mulgA, invMg))).\n\nImplicit Arguments mulgI [T].\nImplicit Arguments mulIg [T].\nImplicit Arguments conjg_inj [T].\nImplicit Arguments commgP [T x y].\nImplicit Arguments conjg_fixP [T x y].\nPrenex Implicits conjg_fixP commgP.\n\nSection SetMulDef.\n\nVariable gT : finGroupType.\nNotation Local sT := {set gT}.\nImplicit Types A B : sT.\nImplicit Type x y : gT.\n\n(* Plucking a set representative. *)\n\nDefinition repr A :=\n  if 1 \\in A then 1 else if [pick x \\in A] is Some x then x else 1.\n\nLemma mem_repr : forall x A, x \\in A -> repr A \\in A.\nProof.\nrewrite /repr => x A; case: ifP => // _.\nby case: pickP => [//|A0]; rewrite [x \\in A]A0.\nQed.\n\nLemma card_mem_repr : forall A, #|A| > 0 -> repr A \\in A.\nProof. by move=> A; rewrite lt0n; case/existsP=> x; exact: mem_repr. Qed.\n\nLemma repr_set1 : forall x : gT, repr [set x] = x.\nProof. by move=> x; apply/set1P; apply: card_mem_repr; rewrite cards1. Qed.\n\nLemma repr_set0 : repr set0 = 1.\nProof. by rewrite /repr; case: pickP => [x|_]; rewrite !inE. Qed.\n\n(* Set-lifted group operations. *)\n\nDefinition set_mulg A B := mulg @2: (A, B).\nDefinition set_invg A := invg @^-1: A.\n\nDefinition lcoset A x := mulg x @: A.\nDefinition rcoset A x := mulg^~ x @: A.\nDefinition lcosets A B := lcoset A @: B.\nDefinition rcosets A B := rcoset A @: B.\nDefinition indexg B A := #|rcosets A B|.\n\nDefinition conjugate A x := conjg^~ x @: A.\nDefinition conjugates A B := conjugate A @: B.\nDefinition class x B := conjg x @: B.\nDefinition classes A := class^~ A @: A.\nDefinition class_support A B := conjg @2: (A, B).\n\nDefinition commg_set A B := commg @2: (A, B).\n\n(* These will only be used later, but are defined here so that we can *)\n(* keep all the Notation together.                                    *)\nDefinition normaliser A := [set x | conjugate A x \\subset A].\nDefinition centraliser A := \\bigcap_(x \\in A) normaliser [set x].\nDefinition abelian A := A \\subset centraliser A.\nDefinition normal A B := (A \\subset B) && (B \\subset normaliser A).\n\n(* \"normalised\" and \"centralise[s|d]\" are intended to be used with   *)\n(* the {in ...} form, as in abelian below.                           *)\nDefinition normalised A := forall x, conjugate A x = A.\nDefinition centralises x A := forall y, y \\in A -> commute x y.\nDefinition centralised A := forall x, centralises x A.\n\n(* The pre-group structure of group subsets. *)\n\nLemma set_mul1g : left_id [set 1] set_mulg.\nProof.\nmove=> A; apply/setP=> y; apply/imset2P/idP=> [[x1 x] | Ay].\n  by move/set1P=> -> Ax ->; rewrite mul1g.\nby exists (1 : gT) y; rewrite ?(set11, mul1g).\nQed.\n\nLemma set_mulgA : associative set_mulg.\nProof.\nmove=> A B C; apply/setP=> y; apply/imset2P/imset2P=> [[x1 z Ax1] | [z x3]].\n  case/imset2P=> x2 x3 Bx2 Cx3 -> ->.\n  by exists (x1 * x2) x3; rewrite ?mulgA //; apply/imset2P; exists x1 x2.\ncase/imset2P=> x1 x2 Ax1 Bx2 -> Cx3 ->.\nby exists x1 (x2 * x3); rewrite ?mulgA //; apply/imset2P; exists x2 x3.\nQed.\n\nLemma set_invgK : involutive set_invg.\nProof. by move=> A; apply/setP=> x; rewrite !inE invgK. Qed.\n\nLemma set_invgM : {morph set_invg : A B / set_mulg A B >-> set_mulg B A}.\nProof.\nmove=> A B; apply/setP=> z; rewrite inE.\napply/imset2P/imset2P=> [[x y Ax By] | [y x]]; last first.\n  by rewrite !inE => By1 Ax1 ->; exists x^-1 y^-1; rewrite ?invMg.\nby move/(canRL invgK)->; exists y^-1 x^-1; rewrite ?invMg // inE invgK.\nQed.\n\nDefinition group_set_baseGroupMixin : FinGroup.mixin_of (set_type _) :=\n  FinGroup.BaseMixin set_mulgA set_mul1g set_invgK set_invgM.\n\nCanonical Structure group_set_baseGroupType :=\n  Eval hnf in BaseFinGroupType group_set_baseGroupMixin.\n\nCanonical Structure group_set_of_baseGroupType :=\n  Eval hnf in [baseFinGroupType of {set gT}].\n\nEnd SetMulDef.\n\n(* Time to open the bag of dirty tricks. When we define groups down below *)\n(* as a subtype of {set gT}, we need them to be able to coerce to sets in *)\n(* both set-style contexts (x \\in G) and monoid-style contexts (G * H),   *)\n(* and we need the coercion function to be EXACTLY the structure          *)\n(* projection in BOTH cases -- otherwise the canonical unification breaks.*)\n(*   Alas, Coq doesn't let us use the same coercion function twice, even  *)\n(* when the targets are convertible. Our workaround (ab)uses the module   *)\n(* system to declare two different identity coercions on an alias class.  *)\n\nModule GroupSet.\nDefinition sort (gT : finGroupType) := {set gT}.\nIdentity Coercion of_sort : sort >-> set_of.\nEnd GroupSet.\n\nModule Type GroupSetBaseGroupSig.\nDefinition sort gT := group_set_of_baseGroupType gT : Type.\nEnd GroupSetBaseGroupSig.\n\nModule MakeGroupSetBaseGroup (Gset_base : GroupSetBaseGroupSig).\nIdentity Coercion of_sort : Gset_base.sort >-> FinGroup.arg_sort.\nEnd MakeGroupSetBaseGroup.\n\nModule GroupSetBaseGroup := MakeGroupSetBaseGroup GroupSet.\n\nCanonical Structure group_set_eqType gT :=\n  Eval hnf in [eqType of GroupSet.sort gT].\nCanonical Structure group_set_choiceType gT :=\n  Eval hnf in [choiceType of GroupSet.sort gT].\nCanonical Structure group_set_countType gT :=\n  Eval hnf in [countType of GroupSet.sort gT].\nCanonical Structure group_set_finType gT :=\n  Eval hnf in [finType of GroupSet.sort gT].\n\nArguments Scope conjugate [_ group_scope group_scope].\nArguments Scope class [_ group_scope group_scope].\nArguments Scope conjugates [_ group_scope group_scope].\nArguments Scope rcosets [_ group_scope group_scope].\nArguments Scope rcoset [_ group_scope group_scope].\nArguments Scope lcosets [_ group_scope group_scope].\nArguments Scope lcoset [_ group_scope group_scope].\nArguments Scope class_support [_ group_scope group_scope].\nArguments Scope normalised [_ group_scope].\nArguments Scope normaliser [_ group_scope].\nArguments Scope normal [_ group_scope group_scope].\nArguments Scope centralised [_ group_scope].\nArguments Scope centraliser [_ group_scope].\nArguments Scope centralises [_ group_scope group_scope].\nArguments Scope abelian [_ group_scope].\n\nNotation \"[ 1 gT ]\" := (1 : {set gT})\n  (at level 0, format \"[ 1  gT ]\") : group_scope.\nNotation \"[ 1 ]\" := [1 FinGroup.sort _]\n  (at level 0, format \"[ 1 ]\") : group_scope.\n\nNotation \"A ^#\" := (A :\\ 1) (at level 2, format \"A ^#\") : group_scope.\n\nNotation \"x *: A\" := ([set x%g] * A) (at level 40) : group_scope.\nNotation \"A :* x\" := (A * [set x%g]) (at level 40) : group_scope.\nNotation \"A :^ x\" := (conjugate A x) (at level 35) : group_scope.\nNotation \"x ^: B\" := (class x B) (at level 35) : group_scope.\nNotation \"A :^: B\" := (conjugates A B) (at level 35) : group_scope.\n\nNotation \"#| B : A |\" := (indexg B A)\n  (at level 0, B, A at level 99, format \"#| B  :  A |\") : group_scope.\n\n(* No notation for lcoset and rcoset, which are to be used mostly  *)\n(* in curried form; x *: B and A :* 1 denote singleton products,   *)\n(* so thus we can use mulgA, mulg1, etc, on, say, A :* 1 * B :* x. *)\n(* No notation for the set commutator generator set set_commg.     *)\n\nNotation \"''N' ( A )\" := (normaliser A)\n  (at level 8, format \"''N' ( A )\") : group_scope.\nNotation \"''N_' G ( A )\" := (G%g :&: 'N(A))\n  (at level 8, G at level 2, format \"''N_' G ( A )\") : group_scope.\nNotation \"A <| B\" := (normal A B)\n  (at level 70) : group_scope.\nNotation \"''C' ( A )\" := (centraliser A)\n  (at level 8, format \"''C' ( A )\") : group_scope.\nNotation \"''C_' G ( A )\" := (G%g :&: 'C(A))\n  (at level 8, G at level 2, format \"''C_' G ( A )\") : group_scope.\nNotation \"''C' [ x ]\" := 'N([set x%g])\n  (at level 8, format \"''C' [ x ]\") : group_scope.\nNotation \"''C_' G [ x ]\" := 'N_G([set x%g])\n  (at level 8, G at level 2, format \"''C_' G [ x ]\") : group_scope.\n\nPrenex Implicits repr lcoset rcoset lcosets rcosets.\nPrenex Implicits conjugate conjugates class classes class_support.\nPrenex Implicits commg_set normalised centralised abelian.\n\nImplicit Arguments mem_repr [gT A].\n\nSection SmulProp.\n\nVariable gT : finGroupType.\nNotation sT := {set gT}.\nImplicit Types A B C D : sT.\nImplicit Type x y z : gT.\n\n(* Set product. We already have all the pregroup identities, so we *)\n(* only need to add the monotonicity rules.                        *)\n\nLemma mulsgP : forall A B x,\n  reflect (imset2_spec mulg (mem A) (fun _ => mem B) x) (x \\in A * B).\nProof. move=> A B x; exact: imset2P. Qed.\n\nLemma mem_mulg : forall A B x y, x \\in A -> y \\in B -> x * y \\in A * B.\nProof. by move=> A B x y Ax By; apply/mulsgP; exists x y. Qed.\n\nLemma mulSg : forall A B C, A \\subset B -> A * C \\subset B * C.\nProof. move=> A B C; exact: imset2Sl. Qed.\n\nLemma mulgS : forall A B C, B \\subset C -> A * B \\subset A * C.\nProof. move=> A B C; exact: imset2Sr. Qed.\n\nLemma mulgSS : forall A B C D,\n  A \\subset B -> C \\subset D -> A * C \\subset B * D.\nProof. move=> A B C D; exact: imset2S. Qed.\n\nLemma mulg_subl : forall A B, 1 \\in B -> A \\subset A * B.\nProof. by move=> A B B1; rewrite -{1}(mulg1 A) mulgS ?sub1set. Qed.\n\nLemma mulg_subr : forall A B, 1 \\in A -> B \\subset A * B.\nProof. by move=> A B A1; rewrite -{1}(mul1g B) mulSg ?sub1set. Qed.\n\nLemma mulUg : forall A B C, (A :|: B) * C = (A * C) :|: (B * C).\nProof. move=> A B C; exact: imset2Ul. Qed.\n\nLemma mulgU : forall A B C, A * (B :|: C) = (A * B) :|: (A * C).\nProof. move=> A B C; exact: imset2Ur. Qed.\n\n(* Set (pointwise) inverse. *)\n\nLemma invUg : forall A B, (A :|: B)^-1 = A^-1 :|: B^-1.\nProof. by move=> A B; exact: preimsetU. Qed.\n\nLemma invIg : forall A B, (A :&: B)^-1 = A^-1 :&: B^-1.\nProof. by move=> A B; exact: preimsetI. Qed.\n\nLemma invDg : forall A B, (A :\\: B)^-1 = A^-1 :\\: B^-1.\nProof. by move=> A B; exact: preimsetD. Qed.\n\nLemma invCg : forall A, (~: A)^-1 = ~: A^-1.\nProof. by move=> A; exact: preimsetC. Qed.\n\nLemma invSg : forall A B, (A^-1 \\subset B^-1) = (A \\subset B).\nProof.\nby move=> A B; rewrite !(sameP setIidPl eqP) -invIg (inj_eq invg_inj).\nQed.\n\nLemma mem_invg : forall x A, (x \\in A^-1) = (x^-1 \\in A).\nProof. by move=> x A; rewrite inE. Qed.\n\nLemma memV_invg : forall x A, (x^-1 \\in A^-1) = (x \\in A).\nProof. by move=> x A; rewrite inE invgK. Qed.\n\nLemma card_invg : forall A, #|A^-1| = #|A|.\nProof. move=> A; apply: card_preimset; exact: invg_inj. Qed.\n\n(* Product with singletons. *)\n\nLemma set1gE : 1 = [set 1] :> sT. Proof. by []. Qed.\n\nLemma set1gP : forall x : gT, reflect (x = 1) (x \\in [1]).\nProof. move=> x; exact: set1P. Qed.\n\nLemma mulg_set1 : forall x y, [set x] :* y = [set x * y].\nProof. by move=> x y; rewrite [_ * _]imset2_set1l imset_set1. Qed.\n\nLemma invg_set1 : forall x, [set x]^-1 = [set x^-1].\nProof. move=> x; apply/setP=> y; rewrite !inE inv_eq //; exact: invgK. Qed.\n\n(* Cosets, left and right. *)\n\nLemma lcosetE : forall A x, lcoset A x = x *: A.\nProof. by move=> A x; rewrite [_ * _]imset2_set1l. Qed.\n\nLemma card_lcoset : forall A x, #|x *: A| = #|A|.\nProof. by move=> A x; rewrite -lcosetE (card_imset _ (mulgI _)). Qed.\n\nLemma mem_lcoset : forall A x y, (y \\in x *: A) = (x^-1 * y \\in A).\nProof.\nby move=> A x y; rewrite -lcosetE [_ x](can_imset_pre _ (mulKg _)) inE.\nQed.\n\nLemma lcosetP : forall A x y,\n  reflect (exists2 a, a \\in A & y = x * a) (y \\in x *: A).\nProof. move=> A x y; rewrite -lcosetE; exact: imsetP. Qed.\n\nLemma lcosetsP : forall A B C,\n  reflect (exists2 x, x \\in B & C = x *: A) (C \\in lcosets A B).\nProof.\nmove=> A B C.\nby apply: (iffP imsetP) => [] [x Bx ->]; exists x; rewrite ?lcosetE.\nQed.\n\nLemma lcosetM : forall A x y, (x * y) *: A = x *: (y *: A).\nProof. by move=> A x y; rewrite -mulg_set1 mulgA. Qed.\n\n(* On to the right, adding some algebraic lemmas *)\n\nLemma rcosetE : forall A x, rcoset A x = A :* x.\nProof. by move=> A x; rewrite [_ * _]imset2_set1r. Qed.\n\nLemma card_rcoset : forall A x, #|A :* x| = #|A|.\nProof. by move=> A x; rewrite -rcosetE (card_imset _ (mulIg _)). Qed.\n\nLemma mem_rcoset : forall A x y, (y \\in A :* x) = (y * x^-1 \\in A).\nProof.\nby move=> A x y; rewrite -rcosetE  [_ x](can_imset_pre A (mulgK _)) inE.\nQed.\n\nLemma rcosetP : forall A x y,\n  reflect (exists2 a, a \\in A & y = a * x) (y \\in A :* x).\nProof. move=> A x y; rewrite -rcosetE; exact: imsetP. Qed.\n\nLemma rcosetsP : forall A B C,\n  reflect (exists2 x, x \\in B & C = A :* x) (C \\in rcosets A B).\nProof.\nmove=> A B C.\nby apply: (iffP imsetP) => [] [x Bx ->]; exists x; rewrite ?rcosetE.\nQed.\n\nLemma rcosetM : forall A x y, A :* (x * y) = A :* x :* y.\nProof. by move=> A x y; rewrite -mulg_set1 mulgA. Qed.\n\n(* Probably redundant *)\nLemma rcoset1 : forall A, A :* 1 = A.\nProof. exact: mulg1. Qed.\n\nLemma rcosetK : forall x, cancel (fun A => A :* x) (fun A => A :* x^-1).\nProof. by move=> x A; rewrite -rcosetM mulgV mulg1. Qed.\n\nLemma rcosetKV : forall x, cancel (fun A => A :* x^-1) (fun A => A :* x).\nProof. by move=> x A; rewrite -rcosetM mulVg mulg1. Qed.\n\nLemma rcoset_inj : forall x, injective (fun A => A :* x).\nProof. by move=> x; exact: can_inj (rcosetK x). Qed.\n\n(* Inverse map lcosets to rcosets *)\n\nLemma lcosets_invg : forall A B, lcosets A^-1 B^-1 = invg @^-1: rcosets A B.\nProof.\nmove=> A B; apply/setP=> C; rewrite inE.\napply/imsetP/imsetP=> [] [a]; rewrite -memV_invg ?invgK => Aa;\n  try move/(canRL invgK); move->; exists a^-1;\n  by rewrite // lcosetE rcosetE invMg invg_set1 ?invgK.\nQed.\n\n(* Conjugates. *)\n\nLemma conjg_preim : forall A x, A :^ x = (conjg^~ x^-1) @^-1: A.\nProof. move=> A x; exact: can_imset_pre (conjgK _). Qed.\n\nLemma conjIg : forall A B x, (A :&: B) :^ x = A :^ x :&: B :^ x.\nProof. by move=> A B x; rewrite !conjg_preim preimsetI. Qed.\n\nLemma conjUg : forall A B x, (A :|: B) :^ x = A :^ x :|: B :^ x.\nProof. by move=> A B x; rewrite !conjg_preim preimsetU. Qed.\n\nLemma cardJg : forall A x, #|A :^ x| = #|A|.\nProof. by move=> A x; rewrite (card_imset _ (conjg_inj x)). Qed.\n\nLemma mem_conjg : forall A x y, (y \\in A :^ x) = (y ^ x^-1 \\in A).\nProof. by move=> A x y; rewrite conjg_preim inE. Qed.\n\nLemma mem_conjgV : forall A x y, (y \\in A :^ x^-1) = (y ^ x \\in A).\nProof. by move=> A x y; rewrite mem_conjg invgK. Qed.\n\nLemma memJ_conjg : forall A x y, (y ^ x \\in A :^ x) = (y \\in A).\nProof. by move=> A x y; rewrite mem_conjg conjgK. Qed.\n\nLemma conjsgE : forall A x, A :^ x = x^-1 *: (A :* x).\nProof.\nby move=> A x; apply/setP=> y; rewrite mem_lcoset mem_rcoset -mulgA mem_conjg.\nQed.\n\nLemma conjsg1 : forall A, A :^ 1 = A.\nProof. by move=> A; rewrite conjsgE invg1 mul1g mulg1. Qed.\n\nLemma conjsgM : forall A x y, A :^ (x * y) = (A :^ x) :^ y.\nProof. by move=> A x y; rewrite !conjsgE invMg -!mulg_set1 !mulgA. Qed.\n\nLemma conjsgK : forall x, cancel (fun A => A :^ x) (fun A => A :^ x^-1).\nProof. by move=> x A; rewrite -conjsgM mulgV conjsg1. Qed.\n\nLemma conjsgKV : forall x, cancel (fun A => A :^ x^-1) (fun A => A :^ x).\nProof. by move=> x A; rewrite -conjsgM mulVg conjsg1. Qed.\n\nLemma conjsg_inj : forall x, injective (fun A => A :^ x).\nProof. by move=> x; exact: can_inj (conjsgK x). Qed.\n\nLemma conjSg : forall A B x, (A :^ x \\subset B :^ x) = (A \\subset B).\nProof.\nmove=> A B x.\nby rewrite !(sameP setIidPl eqP) -conjIg (inj_eq (@conjsg_inj x)).\nQed.\n\nLemma sub_conjg : forall A B x, (A :^ x \\subset B) = (A \\subset B :^ x^-1).\nProof. by move=> A B x; rewrite -(conjSg A _ x) conjsgKV. Qed.\n\nLemma sub_conjgV : forall A B x, (A :^ x^-1 \\subset B) = (A \\subset B :^ x).\nProof. by move=> A B x; rewrite -(conjSg _ B x) conjsgKV. Qed.\n\nLemma conjg_set1 : forall x y, [set x] :^ y = [set x ^ y].\nProof. by move=> x y; rewrite [_ :^ _]imset_set1. Qed.\n\nLemma conjs1g : forall x, 1 :^ x = 1.\nProof. by move=> x; rewrite conjg_set1 conj1g. Qed.\n\nLemma conjsMg : forall A B x, (A * B) :^ x = A :^ x * B :^ x.\nProof. by move=> A B x; rewrite !conjsgE !mulgA rcosetK. Qed.\n\n(* Classes; not much for now. *)\n\nLemma memJ_class : forall x y A, y \\in A -> x ^ y \\in x ^: A.\nProof. by move=> x y A Ay; apply/imsetP; exists y. Qed.\n\nLemma classS : forall x A B, A \\subset B -> x ^: A \\subset x ^: B.\nProof. move=> x A B; exact: imsetS. Qed.\n\nLemma class_set1 : forall x y,  x ^: [set y] = [set x ^ y].\nProof. by move=> x y; exact: imset_set1. Qed.\n\nLemma class1g : forall x A, x \\in A -> 1 ^: A = 1.\nProof.\nmove=> x A Ax; apply/setP=> y.\nby apply/imsetP/set1P=> [[a Aa]|] ->; last exists x; rewrite ?conj1g.\nQed.\n\nLemma class_supportM : forall A B C,\n  class_support A (B * C) = class_support (class_support A B) C.\nProof.\nmove=> A B C; apply/setP=> x; apply/imset2P/imset2P=> [[a y Aa] | [y c]].\n  case/mulsgP=> b c Bb Cc -> ->{x y}.\n  by exists (a ^ b) c; rewrite ?(mem_imset2, conjgM).\ncase/imset2P=> a b Aa Bb -> Cc ->{x y}.\nby exists a (b * c); rewrite ?(mem_mulg, conjgM).\nQed.\n\nLemma class_support_set1l : forall A x, class_support [set x] A = x ^: A.\nProof. move=> A x; exact: imset2_set1l. Qed.\n\nLemma class_support_set1r : forall A x, class_support A [set x] = A :^ x.\nProof. move=> A x; exact: imset2_set1r. Qed.\n\nLemma classM : forall x A B, x ^: (A * B) = class_support (x ^: A) B.\nProof. by move=> x A B; rewrite -!class_support_set1l class_supportM. Qed.\n\nLemma class_lcoset : forall x y A, x ^: (y *: A) = (x ^ y) ^: A.\nProof. by move=> x y A; rewrite classM class_set1 class_support_set1l. Qed.\n\nLemma class_rcoset : forall x A y, x ^: (A :* y) = (x ^: A) :^ y.\nProof. by move=> x A y; rewrite -class_support_set1r classM. Qed.\n\n(* Conjugate set. *)\n\nLemma conjugatesS : forall A B C, B \\subset C -> A :^: B \\subset A :^: C.\nProof. by move=> A B C; exact: imsetS. Qed.\n\nLemma conjugates_set1 : forall A x, A :^: [set x] = [set A :^ x].\nProof. by move=> A x; exact: imset_set1. Qed.\n\nLemma class_supportEl : forall A B,\n  class_support A B = \\bigcup_(x \\in A) x ^: B.\nProof. move=> A B; exact: curry_imset2l. Qed.\n\nLemma class_supportEr : forall A B,\n  class_support A B = \\bigcup_(x \\in B) A :^ x.\nProof. move=> A B; exact: curry_imset2r. Qed.\n\n(* Groups (at last!) *)\n\nDefinition group_set A := (1 \\in A) && (A * A \\subset A).\n\nLemma group_setP : forall A,\n  reflect (1 \\in A /\\ {in A & A, forall x y, x * y \\in A}) (group_set A).\nProof.\nmove=> A; apply: (iffP andP) => [] [A1 AM]; split=> {A1}//.\n  by move=> x y Ax Ay; apply: (subsetP AM); rewrite mem_mulg.\napply/subsetP=> z; case/mulsgP=> [x y Ax Ay ->]; exact: AM.\nQed.\n\nStructure group_type : Type := Group {\n  gval :> GroupSet.sort gT;\n  _ : group_set gval\n}.\n\nDefinition group_of of phant gT : predArgType := group_type.\nNotation Local groupT := (group_of (Phant gT)).\nIdentity Coercion type_of_group : group_of >-> group_type.\n\nCanonical Structure group_subType :=\n  Eval hnf in [subType for gval by group_type_rect].\nDefinition group_eqMixin := Eval hnf in [eqMixin of group_type by <:].\nCanonical Structure group_eqType := Eval hnf in EqType group_eqMixin.\nDefinition group_choiceMixin := [choiceMixin of group_type by <:].\nCanonical Structure group_choiceType :=\n  Eval hnf in ChoiceType group_choiceMixin.\nDefinition group_countMixin := [countMixin of group_type by <:].\nCanonical Structure group_countType := Eval hnf in CountType group_countMixin.\nCanonical Structure group_subCountType :=\n  Eval hnf in [subCountType of group_type].\nDefinition group_finMixin := [finMixin of group_type by <:].\nCanonical Structure group_finType := Eval hnf in FinType group_finMixin.\nCanonical Structure group_subFinType := Eval hnf in [subFinType of group_type].\n\n(* No predType or baseFinGroupType structures, as these would hide the *)\n(* group-to-set coercion and thus spoil unification.                  *)\n\nCanonical Structure group_of_subType := Eval hnf in [subType of groupT].\nCanonical Structure group_of_eqType := Eval hnf in [eqType of groupT].\nCanonical Structure group_of_choiceType := Eval hnf in [choiceType of groupT].\nCanonical Structure group_of_countType := Eval hnf in [countType of groupT].\nCanonical Structure group_of_subCountType :=\n  Eval hnf in [subCountType of groupT].\nCanonical Structure group_of_finType := Eval hnf in [finType of groupT].\nCanonical Structure group_of_subFinType := Eval hnf in [subFinType of groupT].\n\nDefinition group (A : {set gT}) gA : groupT := @Group A gA.\n\nDefinition repack_group G :=\n  let: Group _ gP := G return {type of Group for G} -> groupT in fun k => k gP.\n\nLemma group_inj : injective gval. Proof. exact: val_inj. Qed.\nLemma groupP : forall G : groupT, group_set G. Proof. by case. Qed.\n\nLemma congr_group : forall H K : groupT, H = K -> H :=: K.\nProof. exact: congr1. Qed.\n\nLemma isgroupP : forall A, reflect (exists G : groupT, A = G) (group_set A).\nProof.\nby move=> A; apply: (iffP idP) => [gA | [[B gB] -> //]]; exists (Group gA).\nQed.\n\nLemma group_set_one : group_set 1.\nProof. by rewrite /group_set set11 mulg1 subxx. Qed.\n\nCanonical Structure one_group := group group_set_one.\nCanonical Structure set1_group := @group [set 1] group_set_one.\n\nLemma group_setT : group_set setT.\nProof. apply/group_setP; split=> [|x y _ _]; exact: in_setT. Qed.\n\nCanonical Structure setT_group := group group_setT.\n\n(* These definitions come early so we can establish the Notation. *)\nDefinition generated A := \\bigcap_(G : groupT | A \\subset G) G.\nDefinition mulgen A B := generated (A :|: B).\nDefinition commutator A B := generated (commg_set A B).\nDefinition cycle x := generated [set x].\nDefinition order x := #|cycle x|.\n\nEnd SmulProp.\n\nImplicit Arguments mulsgP [gT A B x].\nImplicit Arguments set1gP [gT x].\nImplicit Arguments lcosetP [gT A x y].\nImplicit Arguments lcosetsP [gT A B C].\nImplicit Arguments rcosetP [gT A x y].\nImplicit Arguments rcosetsP [gT A B C].\nImplicit Arguments group_setP [gT A].\nPrenex Implicits group_set mulsgP set1gP.\nPrenex Implicits lcosetP lcosetsP rcosetP rcosetsP group_setP.\n\nArguments Scope commutator [_ group_scope group_scope].\nArguments Scope mulgen [_ group_scope group_scope].\nArguments Scope generated [_ group_scope].\n\nNotation \"{ 'group' gT }\" := (group_of (Phant gT))\n  (at level 0, format \"{ 'group'  gT }\") : type_scope.\n\nNotation \"[ 'group' 'of' G ]\" := (repack_group (fun gP => @group _ G gP))\n  (at level 0, format \"[ 'group'  'of'  G ]\") : form_scope.\n\nBind Scope subgroup_scope with group_type.\nBind Scope subgroup_scope with group_of.\nNotation \"1\" := (one_group _) : subgroup_scope.\nNotation \"[ 1 gT ]\" := (1%G : {group gT})\n  (at level 0, format \"[ 1  gT ]\") : subgroup_scope.\nNotation \"[ 'setT' ]\" := (setT_group _)\n  (at level 0, format \"[ 'setT' ]\") : subgroup_scope.\nNotation \"[ 'setT' gT ]\" := ([setT]%G : {group gT})\n  (at level 0, format \"[ 'setT'  gT ]\") : subgroup_scope.\n\nNotation \"<< A >>\"  := (generated A)\n  (at level 0, format \"<< A >>\") : group_scope.\n\nNotation \"<[ x ] >\"  := (cycle x)\n  (at level 0, format \"<[ x ] >\") : group_scope.\n\nNotation \"#[ x ]\"  := (order x) (at level 0, format \"#[ x ]\") : group_scope.\n\nNotation \"A <*> B\" := (mulgen A B) (at level 40) : group_scope.\n\nNotation \"[ ~: A1 , A2 , .. , An ]\" := (commutator .. (commutator A1 A2) .. An)\n  (at level 0,\n  format \"[ ~: '['  A1 , '/'  A2 , '/'  .. , '/'  An ']' ]\") : group_scope.\n\nPrenex Implicits order cycle.\n\nSection GroupProp.\n\nVariable gT : finGroupType.\nNotation sT := {set gT}.\nImplicit Types A B C D : sT.\nImplicit Types x y z : gT.\nImplicit Types G H K : {group gT}.\n\nSection OneGroup.\n\nVariable G : {group gT}.\n\nLemma valG : val G = G. Proof. by []. Qed.\n\n(* Non-triviality. *)\n\nLemma group1 : 1 \\in G. Proof. by case/group_setP: (valP G). Qed.\nHint Resolve group1.\n\n(* Loads of silly variants to placate the incompleteness of trivial. *)\n(* An alternative would be to upgrade done, pending better support   *)\n(* in the ssreflect ML code.                                         *)\nNotation gTr := (FinGroup.sort gT).\nNotation Gcl := (pred_of_set G : pred gTr).\nLemma group1_class1 : (1 : gTr) \\in G. Proof. by []. Qed.\nLemma group1_class2 : 1 \\in Gcl. Proof. by []. Qed.\nLemma group1_class12 : (1 : gTr) \\in Gcl. Proof. by []. Qed.\nLemma group1_eqType : (1 : gT : eqType) \\in G. Proof. by []. Qed.\nLemma group1_finType : (1 : gT : finType) \\in G. Proof. by []. Qed.\n\nLemma sub1G : [1 gT] \\subset G. Proof. by rewrite sub1set. Qed.\nLemma subG1 : (G \\subset [1]) = (G :==: 1).\nProof. by rewrite eqEsubset sub1G andbT. Qed.\n\nLemma repr_group : repr G = 1. Proof. by rewrite /repr group1. Qed.\n\nLemma cardG_gt0 : 0 < #|G|.\nProof. by rewrite lt0n; apply/existsP; exists (1 : gT). Qed.\n\nLemma indexg_gt0 : forall A, 0 < #|G : A|.\nProof.\nmove=> A; rewrite lt0n; apply/existsP; exists A.\nrewrite -{2}[A]mulg1 -rcosetE; exact: mem_imset.\nQed.\n\nLemma trivgP : reflect (G :=: 1) (G \\subset [1]).\nProof. by rewrite subG1; exact: eqP. Qed.\n\nLemma trivGP : reflect (G = 1%G) (G \\subset [1]).\nProof. by rewrite subG1; exact: eqP. Qed.\n\nLemma proper1G : ([1] \\proper G) = (G :!=: 1).\nProof. by rewrite properEneq sub1G andbT eq_sym. Qed.\n\nLemma trivgPn : reflect (exists2 x, x \\in G & x != 1) (G :!=: 1).\nProof.\nrewrite -subG1.\nby apply: (iffP subsetPn) => [] [x Gx x1]; exists x; rewrite ?inE in x1 *.\nQed.\n\nLemma trivg_card_le1 : (G :==: 1) = (#|G| <= 1).\nProof. by rewrite eq_sym eqEcard cards1 sub1G. Qed.\n\nLemma trivg_card1 : (G :==: 1) = (#|G| == 1%N).\nProof. by rewrite trivg_card_le1 eqn_leq cardG_gt0 andbT. Qed.\n\nLemma card_le1_trivg : #|G| <= 1 -> G :=: 1.\nProof. by rewrite -trivg_card_le1; move/eqP. Qed.\n\nLemma card1_trivg : #|G| = 1%N -> G :=: 1.\nProof. by move=> G1; rewrite card_le1_trivg ?G1. Qed.\n\n(* Inclusion and product. *)\n\nLemma mulG_subl : forall A, A \\subset A * G.\nProof. move=> A; exact: mulg_subl group1. Qed.\n\nLemma mulG_subr : forall A, A \\subset G * A.\nProof. move=> A; exact: mulg_subr group1. Qed.\n\nLemma mulGid : G * G = G.\nProof.\nby apply/eqP; rewrite eqEsubset mulG_subr andbT; case/andP: (valP G).\nQed.\n\nLemma mulGS : forall A B, (G * A \\subset G * B) = (A \\subset G * B).\nProof.\nmove=> A B; apply/idP/idP; first exact: subset_trans (mulG_subr A).\nby move/(mulgS G); rewrite mulgA mulGid.\nQed.\n\nLemma mulSG : forall A B, (A * G \\subset B * G) = (A \\subset B * G).\nProof.\nmove=> A B; apply/idP/idP; first exact: subset_trans (mulG_subl A).\nby move/(mulSg G); rewrite -mulgA mulGid.\nQed.\n\nLemma mul_subG : forall A B, A \\subset G -> B \\subset G -> A * B \\subset G.\nProof. by move=> A B sAG sBG; rewrite -mulGid mulgSS. Qed.\n\n(* Membership lemmas *)\n\nLemma groupM : forall x y, x \\in G -> y \\in G -> x * y \\in G.\nProof. by case/group_setP: (valP G). Qed.\n\nLemma groupX : forall x n, x \\in G -> x ^+ n \\in G.\nProof.\nby move=> x n Gx; elim: n => [|n IHn]; rewrite ?group1 // expgS groupM.\nQed.\n\nLemma groupVr : forall x, x \\in G -> x^-1 \\in G.\nProof.\nmove=> x Gx; rewrite -(mul1g x^-1) -mem_rcoset ((G :* x =P G) _) //.\nby rewrite eqEcard card_rcoset leqnn mul_subG ?sub1set.\nQed.\n\nLemma groupVl : forall x, x^-1 \\in G -> x \\in G.\nProof. by move=> x; move/groupVr; rewrite invgK. Qed.\n\nLemma groupV : forall x, (x^-1 \\in G) = (x \\in G).\nProof. by move=> x; apply/idP/idP; [exact: groupVl | exact: groupVr]. Qed.\n\nLemma groupMl : forall x y, x \\in G -> (x * y \\in G) = (y \\in G).\nProof.\nmove=> x y Gx; apply/idP/idP=> Gy; last exact: groupM.\nrewrite -(mulKg x y); exact: groupM (groupVr _) _.\nQed.\n\nLemma groupMr : forall x y, x \\in G -> (y * x \\in G) = (y \\in G).\nProof. by move=> x y Gx; rewrite -[_ \\in G]groupV invMg groupMl groupV. Qed.\n\nDefinition in_group := (group1, groupV, (groupMl, groupX)).\n\nLemma groupJ : forall x y, x \\in G -> y \\in G -> x ^ y \\in G.\nProof. by move=> x y Gx Gy; rewrite !in_group. Qed.\n\nLemma groupJr : forall x y, y \\in G -> (x ^ y \\in G) = (x \\in G).\nProof. by move=> x y Gy; rewrite groupMl (groupMr, groupV). Qed.\n\nLemma groupR : forall x y, x \\in G -> y \\in G -> [~ x, y] \\in G.\nProof. by move=> x y Gx Gy; rewrite !in_group. Qed.\n\n(* Inverse is an anti-morphism. *)\n\nLemma invGid : G^-1 = G. Proof. by apply/setP=> x; rewrite inE groupV. Qed.\n\nLemma inv_subG : forall A, (A^-1 \\subset G) = (A \\subset G).\nProof. by move=> A; rewrite -{1}invGid invSg. Qed.\n\nLemma invg_lcoset : forall x, (x *: G)^-1 = G :* x^-1.\nProof. by move=> x; rewrite invMg invGid invg_set1. Qed.\n\nLemma invg_rcoset : forall x, (G :* x)^-1 = x^-1 *: G.\nProof. by move=> x; rewrite invMg invGid invg_set1. Qed.\n\nLemma memV_lcosetV : forall x y, (y^-1 \\in x^-1 *: G) = (y \\in G :* x).\nProof. by move=> x y; rewrite -invg_rcoset memV_invg. Qed.\n\nLemma memV_rcosetV : forall x y, (y^-1 \\in G :* x^-1) = (y \\in x *: G).\nProof. by move=> x y; rewrite -invg_lcoset memV_invg. Qed.\n\n(* Product idempotence *)\n\nLemma mulSgGid : forall A x, x \\in A -> A \\subset G -> A * G = G.\nProof.\nmove=> A x Ax sAG; apply/eqP; rewrite eqEsubset -{2}mulGid mulSg //=.\napply/subsetP=> y Gy; rewrite -(mulKVg x y) mem_mulg // groupMr // groupV.\nexact: (subsetP sAG).\nQed.\n\nLemma mulGSgid : forall A x, x \\in A -> A \\subset G -> G * A = G.\nProof.\nmove=> A x; rewrite -memV_invg -invSg invGid => Ax sAG.\nby apply: invg_inj; rewrite invMg invGid (mulSgGid Ax).\nQed.\n\n(* Left cosets *)\n\nLemma lcoset_refl : forall x, x \\in x *: G.\nProof. by move=> x; rewrite mem_lcoset mulVg group1. Qed.\n\nLemma lcoset_sym : forall x y, (x \\in y *: G) = (y \\in x *: G).\nProof. by move=> x y; rewrite !mem_lcoset -groupV invMg invgK. Qed.\n\nLemma lcoset_transl : forall x y, x \\in y *: G -> x *: G = y *: G.\nProof.\nmove=> x y Gyx; apply/setP=> u; rewrite !mem_lcoset in Gyx *.\nby rewrite -{2}(mulKVg x u) mulgA (groupMl _ Gyx).\nQed.\n\nLemma lcoset_transr : forall x y z,\n  x \\in y *: G -> (x \\in z *: G) = (y \\in z *: G).\nProof. by move=> x y z Gyx; rewrite -2!(lcoset_sym z) (lcoset_transl Gyx). Qed.\n\nLemma lcoset_trans : forall x y z,\n  x \\in y *: G -> y \\in z *: G -> x \\in z *: G.\nProof. by move=> x y z; move/lcoset_transr->. Qed.\n\nLemma lcoset_id : forall x, x \\in G -> x *: G = G.\nProof. move=> x; rewrite -{-2}(mul1g G); exact: lcoset_transl. Qed.\n\n(* Right cosets, with an elimination form for repr. *)\n\nLemma rcoset_refl : forall x, x \\in G :* x.\nProof. by move=> x; rewrite mem_rcoset mulgV group1. Qed.\n\nLemma rcoset_sym : forall x y, (x \\in G :* y) = (y \\in G :* x).\nProof. by move=> x y; rewrite -!memV_lcosetV lcoset_sym. Qed.\n\nLemma rcoset_transl : forall x y, x \\in G :* y -> G :* x = G :* y.\nProof.\nmove=> x y Gyx; apply: invg_inj; rewrite !invg_rcoset.\nby apply: lcoset_transl; rewrite memV_lcosetV.\nQed.\n\nLemma rcoset_transr : forall x y z,\n  x \\in G :* y -> (x \\in G :* z) = (y \\in G :* z).\nProof. by move=> x y z Gyx; rewrite -2!(rcoset_sym z) (rcoset_transl Gyx). Qed.\n\nLemma rcoset_trans : forall x y z,\n  y \\in G :* x -> z \\in G :* y -> z \\in G :* x.\nProof. by move=> x y z; move/rcoset_transl->. Qed.\n\nLemma rcoset_id : forall x, x \\in G -> G :* x = G.\nProof. move=> x; rewrite -{-2}(mulg1 G); exact: rcoset_transl. Qed.\n\n(* Elimination form. *)\n\nCoInductive rcoset_repr_spec x : gT -> Type :=\n  RcosetReprSpec g : g \\in G -> rcoset_repr_spec x (g * x).\n\nLemma mem_repr_rcoset : forall x, repr (G :* x) \\in G :* x.\nProof. move=> x; exact: mem_repr (rcoset_refl x). Qed.\n\n(* This form sometimes fails because ssreflect 1.1 delegates matching to the *)\n(* (weaker) primitive Coq algorithm for general (co)inductive type families. *)\nLemma repr_rcosetP : forall x, rcoset_repr_spec x (repr (G :* x)).\nProof.\nmove=> x; rewrite -[repr _](mulgKV x).\nby split; rewrite -mem_rcoset mem_repr_rcoset.\nQed.\n\nLemma rcoset_repr : forall x, G :* (repr (G :* x)) = G :* x.\nProof.\nmove=> x; apply: rcoset_transl; exact: mem_repr (rcoset_refl x).\nQed.\n\n(* Coset spaces. *)\n\nLemma mem_lcosets : forall A x, (x *: G \\in lcosets G A) = (x \\in A * G).\nProof.\nmove=> A x; apply/imsetP/mulsgP=> [[a Aa eqxaG] | [a g Aa Gg ->{x}]].\n  exists a (a^-1 * x); rewrite ?mulKVg //.\n  by rewrite -mem_lcoset -lcosetE -eqxaG lcoset_refl.\nby exists a; rewrite // lcosetM lcosetE lcoset_id.\nQed.\n\nLemma mem_rcosets : forall A x, (G :* x \\in rcosets G A) = (x \\in G * A).\nProof.\nmove=> A x; rewrite -memV_invg invMg invGid -mem_lcosets.\nby rewrite -{4}invGid lcosets_invg inE invg_lcoset invgK.\nQed.\n\n(* Conjugates. *)\n\nLemma group_set_conjG : forall x, group_set (G :^ x).\nProof.\nmove=> x; apply/group_setP; split=> [|y z]; rewrite !mem_conjg.\n  by rewrite conj1g group1.\nrewrite conjMg; exact: groupM.\nQed.\n\nCanonical Structure conjG_group x := group (group_set_conjG x).\n\nLemma conjGid : {in G, normalised G}.\nProof. by move=> x Gx; apply/setP=> y; rewrite mem_conjg groupJr ?groupV. Qed.\n\nLemma conj_subG : forall x A, x \\in G -> A \\subset G -> A :^ x \\subset G.\nProof. by move=> x A Gx sAG; rewrite -(conjGid Gx) conjSg. Qed.\n\n(* Classes *)\n\nLemma class1G : 1 ^: G = 1. Proof. exact: class1g group1. Qed.\n\nLemma classGidl : forall x y, y \\in G -> (x ^ y) ^: G = x ^: G.\nProof. by move=> x y Gy; rewrite -class_lcoset lcoset_id. Qed.\n\nLemma classGidr : forall x, {in G, normalised (x ^: G)}.\nProof. by move=> x y Gy; rewrite -class_rcoset rcoset_id. Qed.\n\nLemma class_refl : forall x, x \\in x ^: G.\nProof. by move=> x; apply/imsetP; exists (1 : gT); rewrite ?conjg1. Qed.\nHint Resolve class_refl.\n\nLemma class_transr : forall x y, x \\in y ^: G -> x ^: G = y ^: G.\nProof. by move=> x y; case/imsetP=> z Gz ->; rewrite classGidl. Qed.\n\nLemma class_sym : forall x y, (x \\in y ^: G) = (y \\in x ^: G).\nProof. by move=> x y; apply/idP/idP; move/class_transr->. Qed.\n\nLemma class_transl : forall x y z,\n   x \\in y ^: G -> (x \\in z ^: G) = (y \\in z ^: G).\nProof. by move=> x y z; rewrite -!(class_sym z); move/class_transr->. Qed.\n\nLemma class_trans : forall x y z,\n   x \\in y ^: G -> y \\in z ^: G -> x \\in z ^: G.\nProof. by move=> x y z; move/class_transl->. Qed.\n\nLemma repr_class : forall x, {y | y \\in G & repr (x ^: G) = x ^ y}.\nProof.\nmove=> x; set z := repr _; have: #|[set y \\in G | z == x ^ y]| > 0.\n  have: z \\in x ^: G by exact: (mem_repr x).\n  by case/imsetP=> y Gy ->; rewrite (cardD1 y) inE Gy eqxx.\nmove/card_mem_repr; move: (repr _) => y; rewrite inE; case/andP=> Gy.\nby move/eqP; exists y.\nQed.\n\nLemma class_subG : forall x A, x \\in G -> A \\subset G -> x ^: A \\subset G.\nProof.\nmove=> x A Gx sAG; apply/subsetP=> yx; case/imsetP=> y Ay ->{yx}.\nby rewrite groupJ // (subsetP sAG).\nQed.\n\nLemma class_supportGidl : forall A x,\n  x \\in G -> class_support (A :^ x) G = class_support A G.\nProof.\nby move=> A x Gx; rewrite -class_support_set1r -class_supportM lcoset_id.\nQed.\n\nLemma class_supportGidr : forall A, {in G, normalised (class_support A G)}.\nProof.\nby move=> A x Gx; rewrite -class_support_set1r -class_supportM rcoset_id.\nQed.\n\n(* Subgroup Type construction. *)\n(* We only expect to use this for abstract groups, so we don't project *)\n(* the argument to a set.                                              *)\n\nInductive subg_of : predArgType := Subg x & x \\in G.\nDefinition sgval u := let: Subg x _ := u in x.\nCanonical Structure subg_subType :=\n  Eval hnf in [subType for sgval by subg_of_rect].\nDefinition subg_eqMixin := Eval hnf in [eqMixin of subg_of by <:].\nCanonical Structure subg_eqType := Eval hnf in EqType subg_eqMixin.\nDefinition subg_choiceMixin := [choiceMixin of subg_of by <:].\nCanonical Structure subg_choiceType := Eval hnf in ChoiceType subg_choiceMixin.\nDefinition subg_countMixin := [countMixin of subg_of by <:].\nCanonical Structure subg_countType := Eval hnf in CountType subg_countMixin.\nCanonical Structure subg_subCountType := Eval hnf in [subCountType of subg_of].\nDefinition subg_finMixin := [finMixin of subg_of by <:].\nCanonical Structure subg_finType := Eval hnf in FinType subg_finMixin.\nCanonical Structure subg_subFinType := Eval hnf in [subFinType of subg_of].\n\nLemma subgP : forall u, sgval u \\in G.\nProof. exact: valP. Qed.\nLemma subg_inj : injective sgval.\nProof. exact: val_inj. Qed.\nLemma congr_subg : forall u v, u = v -> sgval u = sgval v.\nProof. exact: congr1. Qed.\n\nDefinition subg_one := Subg group1.\nDefinition subg_inv u := Subg (groupVr (subgP u)).\nDefinition subg_mul u v := Subg (groupM (subgP u) (subgP v)).\nLemma subg_oneP : left_id subg_one subg_mul.\nProof. move=> u; apply: val_inj; exact: mul1g. Qed.\nLemma subg_invP : left_inverse subg_one subg_inv subg_mul.\nProof. move=> u; apply: val_inj; exact: mulVg. Qed.\nLemma subg_mulP : associative subg_mul.\nProof. move=> u v w; apply: val_inj; exact: mulgA. Qed.\n\nDefinition subFinGroupMixin := FinGroup.Mixin subg_mulP subg_oneP subg_invP.\nCanonical Structure subBaseFinGroupType :=\n  Eval hnf in BaseFinGroupType subFinGroupMixin.\nCanonical Structure subFinGroupType := FinGroupType subg_invP.\n\nLemma sgvalM : {in setT &, {morph sgval : x y / x * y}}. Proof. by []. Qed.\nLemma valgM : {in setT &, {morph val : x y / (x : subg_of) * y >-> x * y}}.\nProof. by []. Qed.\n\nDefinition subg : gT -> subg_of := insubd (1 : subg_of).\nLemma subgK : forall x, x \\in G -> val (subg x) = x.\nProof. by move=> x Gx; rewrite insubdK. Qed.\nLemma sgvalK : cancel sgval subg.\nProof. case=> x Gx; apply: val_inj; exact: subgK. Qed.\nLemma subg_default : forall x, (x \\in G) = false -> val (subg x) = 1.\nProof. by move=> x Gx; rewrite val_insubd Gx. Qed.\nLemma subgM : {in G &, {morph subg : x y / x * y}}.\nProof. by move=> x y Gx Gy; apply: val_inj; rewrite /= !subgK ?groupM. Qed.\n\nEnd OneGroup.\n\nHint Resolve group1.\n\nLemma invMG : forall G H, (G * H)^-1 = H * G.\nProof. by move=> G H; rewrite invMg !invGid. Qed.\n\nLemma mulSGid : forall G H, H \\subset G -> H * G = G.\nProof. move=> G H; exact: mulSgGid (group1 H). Qed.\n\nLemma mulGSid : forall G H, H \\subset G -> G * H = G.\nProof. move=> G H; exact: mulGSgid (group1 H). Qed.\n\nLemma comm_group_setP : forall G H, reflect (commute G H) (group_set (G * H)).\nProof.\nmove=> G H; rewrite /group_set (subsetP (mulG_subl _ _)) ?group1 // andbC.\nhave <-: #|G * H| <= #|H * G| by rewrite -invMG card_invg.\nrewrite -mulgA mulGS mulgA mulSG -eqEcard eq_sym; exact: eqP.\nQed.\n\nLemma card_lcosets : forall G H, #|lcosets H G| = #|G : H|.\nProof.\nmove=> G H; rewrite -[#|G : H|](card_preimset _ invg_inj).\nby rewrite -lcosets_invg !invGid.\nQed.\n\n(* Group Modularity equations *)\n\nLemma group_modl : forall A B G, A \\subset G -> A * (B :&: G) = A * B :&: G.\nProof.\nmove=> A B G sAG; apply/eqP; rewrite eqEsubset subsetI mulgS ?subsetIl //.\nrewrite -{2}mulGid mulgSS ?subsetIr //; apply/subsetP => x.\ncase/setIP; case/mulsgP=> a b Aa Bb ->{x} Gab; rewrite mem_mulg // inE Bb.\nby rewrite -(groupMl _ (subsetP sAG _ Aa)).\nQed.\n\nLemma group_modr : forall A B G, B \\subset G -> (G :&: A) * B = G :&: A * B.\nProof.\nmove=> A B G sBG; apply: invg_inj; rewrite !(invMg, invIg) invGid !(setIC G).\nby rewrite group_modl // -invGid invSg.\nQed.\n\nEnd GroupProp.\n\nHint Resolve group1 group1_class1 group1_class12 group1_class12.\nHint Resolve group1_eqType group1_finType.\nHint Resolve cardG_gt0 indexg_gt0.\n\nNotation \"G :^ x\" := (conjG_group G x) : subgroup_scope.\n\nNotation \"[ 'subg' G ]\" := (@finset.setT (subg_finType G))\n  (at level 0, format \"[ 'subg'  G ]\") : group_scope.\nNotation \"[ 'subg' G ]\" := (setT_group (subFinGroupType G)) : subgroup_scope.\n\nPrenex Implicits subg sgval subg_of.\n\nImplicit Arguments trivgP [gT G].\nImplicit Arguments trivGP [gT G].\nImplicit Arguments comm_group_setP [gT G H].\nPrenex Implicits trivgP trivGP comm_group_setP.\n\nSection GroupInter.\n\nVariable gT : finGroupType.\nImplicit Types A B : {set gT}.\nImplicit Types G H : {group gT}.\n\nLemma group_setI : forall G H, group_set (G :&: H).\nProof.\nmove=> G H; apply/group_setP; split=> [|x y]; rewrite !inE ?group1 //.\nby case/andP=> Gx Hx; rewrite !groupMl.\nQed.\n\nCanonical Structure setI_group G H := group (group_setI G H).\n\nSection Nary.\n\nVariables (I : finType) (P : pred I) (F : I -> {group gT}).\n\nLemma group_set_bigcap : group_set (\\bigcap_(i | P i) F i).\nProof.\napply: (@big_prop _ [eta group_set])=> [|G H gG gH|G _]; try exact: groupP.\nexact: (@group_setI (group gG) (group gH)).\nQed.\n\nCanonical Structure bigcap_group := group group_set_bigcap.\n\nEnd Nary.\n\nCanonical Structure generated_group A : {group _} :=\n  Eval hnf in [group of <<A>>].\nCanonical Structure commutator_group A B : {group _} :=\n  Eval hnf in [group of [~: A, B]].\nCanonical Structure mulgen_group A B : {group _} :=\n  Eval hnf in [group of A <*> B].\nCanonical Structure cycle_group x : {group _} :=\n  Eval hnf in [group of <[x]>].\n\nLemma order_gt0 : forall x : gT, 0 < #[x].\nProof. by move=> x; exact: cardG_gt0. Qed.\nCanonical Structure order_pos_nat x := PosNat (order_gt0 x).\n\nEnd GroupInter.\n\nHint Resolve order_gt0.\n\nDefinition mulGen (gT : finGroupType) (G H : {group gT}) :=\n  nosimpl (mulgen_group G H).\n\nArguments Scope generated_group [_ group_scope].\n\nNotation \"G :&: H\" := (setI_group G H) : subgroup_scope.\nNotation \"<< A >>\"  := (generated_group A) : subgroup_scope.\nNotation \"<[ x ] >\"  := (cycle_group x) : subgroup_scope.\nNotation \"[ ~: A1 , A2 , .. , An ]\" :=\n  (commutator_group .. (commutator_group A1 A2) .. An) : subgroup_scope.\nNotation \"G <*> H\" := (mulGen G H) : subgroup_scope.\nPrenex Implicits mulGen.\n\nNotation \"\\prod_ ( <- r | P ) F\" :=\n  (\\big[mulGen/1%G]_(<- r | P%B) F%G) : subgroup_scope.\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[mulGen/1%G]_(i <- r | P%B) F%G) : subgroup_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[mulGen/1%G]_(i <- r) F%G) : subgroup_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[mulGen/1%G]_(m <= i < n | P%B) F%G) : subgroup_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[mulGen/1%G]_(m <= i < n) F%G) : subgroup_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[mulGen/1%G]_(i | P%B) F%G) : subgroup_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[mulGen/1%G]_i F%G) : subgroup_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[mulGen/1%G]_(i : t | P%B) F%G) (only parsing) : subgroup_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[mulGen/1%G]_(i : t) F%G) (only parsing) : subgroup_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[mulGen/1%G]_(i < n | P%B) F%G) : subgroup_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[mulGen/1%G]_(i < n) F%G) : subgroup_scope.\nNotation \"\\prod_ ( i \\in A | P ) F\" :=\n  (\\big[mulGen/1%G]_(i \\in A | P%B) F%G) : subgroup_scope.\nNotation \"\\prod_ ( i \\in A ) F\" :=\n  (\\big[mulGen/1%G]_(i \\in A) F%G) : subgroup_scope.\n\nSection LaGrange.\n\nVariable gT : finGroupType.\nImplicit Types G H K : {group gT}.\n\nLemma LaGrangeI : forall G H, (#|G :&: H| * #|G : H|)%N = #|G|.\nProof.\nmove=> G H; rewrite -[#|G|]sum1_card (partition_big_imset (rcoset H)) /=.\nrewrite mulnC -sum_nat_const; apply: eq_bigr=> A; case/rcosetsP=> x Gx ->{A}.\nrewrite -(card_rcoset _ x) -sum1_card; apply: eq_bigl => y.\nrewrite rcosetE eqEcard mulGS !card_rcoset leqnn andbT.\nby rewrite group_modr sub1set // inE.\nQed.\n\nLemma divgI : forall G H, #|G| %/ #|G :&: H| = #|G : H|.\nProof. by move=> G H; rewrite -(LaGrangeI G H) mulKn ?cardG_gt0. Qed.\n\nLemma divg_index : forall G H, #|G| %/ #|G : H| = #|G :&: H|.\nProof. by move=> G H; rewrite -(LaGrangeI G H) mulnK. Qed.\n\nLemma dvdn_indexg : forall G H, #|G : H| %| #|G|.\nProof. by move=> G H; rewrite -(LaGrangeI G H) dvdn_mull. Qed.\n\nTheorem LaGrange : forall G H, H \\subset G -> (#|H| * #|G : H|)%N = #|G|.\nProof. by move=> G H; move/setIidPr=> sHG; rewrite -{1}sHG LaGrangeI. Qed.\n\nLemma cardSg : forall G H, H \\subset G -> #|H| %| #|G|.\nProof. by move=> G H; move/LaGrange <-; rewrite dvdn_mulr. Qed.\n\nLemma divgS : forall G H, H \\subset G -> #|G| %/ #|H| = #|G : H|.\nProof. by move=> G H; move/LaGrange <-; rewrite mulKn. Qed.\n\nLemma indexJg : forall G H x, #|G :^ x : H :^ x| = #|G : H|.\nProof. by move=> G H x; rewrite -!divgI -conjIg !cardJg. Qed.\n\nLemma indexgg : forall G, #|G : G| = 1%N.\nProof. by move=> G; rewrite -divgS // divnn cardG_gt0. Qed.\n\nLemma LaGrange_index : forall G H K,\n  H \\subset G -> K \\subset H -> (#|G : H| * #|H : K|)%N = #|G : K|.\nProof.\nmove=> G H K sHG sKH; apply/eqP; rewrite mulnC -(eqn_pmul2l (cardG_gt0 K)).\nby rewrite mulnA !LaGrange // (subset_trans sKH).\nQed.\n\nLemma indexgI : forall G H, #|G : G :&: H| = #|G : H|.\nProof. by move=> G H; rewrite -divgI divgS ?subsetIl. Qed.\n\nLemma indexgS : forall G H K, H \\subset K -> #|G : K| %| #|G : H|.\nProof.\nmove=> G H K sHK; rewrite -(@dvdn_pmul2l #|G :&: K|) ?cardG_gt0 // LaGrangeI.\nby rewrite -(LaGrange (setIS G sHK)) mulnAC LaGrangeI dvdn_mulr.\nQed.\n\nLemma indexSg : forall G H K,\n  H \\subset K -> K \\subset G -> #|K : H| %| #|G : H|.\nProof.\nmove=> G H K sHK sKG; rewrite -(@dvdn_pmul2l #|H|) ?cardG_gt0 //.\nby rewrite !LaGrange ?(cardSg, subset_trans sHK).\nQed.\n\nLemma index1g : forall G H,  H \\subset G -> #|G : H| = 1%N -> H = G.\nProof.\nmove=> G H Hsub Hi; apply:val_inj; apply/eqP; rewrite eqEcard Hsub /=.\nby rewrite -(LaGrange Hsub) Hi muln1.\nQed.\n\nLemma indexg1 : forall G, #|G : 1| = #|G|.\nProof. by move=> G; rewrite -divgS ?sub1G // cards1 divn1. Qed.\n\nLemma mul_cardG : forall G H, (#|G| * #|H| = #|G * H|%g * #|G :&: H|)%N.\nProof.\nmove=> G H; rewrite -(LaGrangeI H G) mulnA mulnAC setIC; congr (_ * _)%N.\nsymmetry; rewrite mulnC -sum_nat_const /= -sum1_card.\nrewrite (partition_big (fun x => G :* x) (mem (rcosets G H))) /=; last first.\n  by move=> x; rewrite mem_rcosets.\napply: eq_bigr => Gy; case/imsetP=> y Hy ->{Gy}.\nrewrite -(card_rcoset G y) -sum1_card; apply: eq_bigl => x.\nrewrite rcosetE eqEcard !card_rcoset leqnn andbT mulGS sub1set.\nby rewrite -in_setI (setIidPr _) ?mulgS ?sub1set.\nQed.\n\nLemma TI_cardMg : forall G H, G :&: H = 1 -> #|G * H| = (#|G| * #|H|)%N.\nProof. by move=> G H trGH; rewrite mul_cardG trGH cards1 muln1. Qed.\n\nLemma cardMg_TI : forall G H, #|G| * #|H| <= #|G * H| -> G :&: H = 1.\nProof.\nmove=> G H leGH; apply: card_le1_trivg.\nrewrite -(@leq_pmul2l #|G * H|); first by rewrite -mul_cardG muln1.\nby apply: leq_trans leGH; rewrite muln_gt0 !cardG_gt0.\nQed.\n\nLemma coprime_TIg : forall G H, coprime #|G| #|H| -> G :&: H = 1.\nProof.\nmove=> G H coGH; apply/eqP; rewrite trivg_card1 -dvdn1 -{}(eqnP coGH).\nby rewrite dvdn_gcd /= {2}setIC !cardSg ?subsetIl.\nQed.\n\nLemma coprime_cardMg : forall G H,\n  coprime #|G| #|H| -> #|G * H| = (#|G| * #|H|)%N.\nProof. by move=> G H coGH; rewrite TI_cardMg ?coprime_TIg. Qed.\n\nEnd LaGrange.\n\nSection GeneratedGroup.\n\nVariable gT : finGroupType.\nNotation sT := {set gT}.\nImplicit Types x y z : gT.\nImplicit Types A B C D : sT.\nImplicit Types G H K : {group gT}.\n\nLemma subset_gen : forall A, A \\subset <<A>>.\nProof. move=> A; exact/bigcapsP. Qed.\n\nLemma sub_gen : forall A B, A \\subset B -> A \\subset <<B>>.\nProof. move=> A B sAB; exact: subset_trans (subset_gen B). Qed.\n\nLemma mem_gen : forall x A, x \\in A -> x \\in <<A>>.\nProof. move=> x A; exact: subsetP (subset_gen A) x. Qed.\n\nLemma generatedP : forall x A,\n  reflect (forall G, A \\subset G -> x \\in G) (x \\in <<A>>).\nProof. move=> x A; exact: bigcapP. Qed.\n\nLemma gen_subG : forall A G, (<<A>> \\subset G) = (A \\subset G).\nProof.\nmove=> A G; apply/idP/idP=> [|sAG]; first exact: subset_trans (subset_gen A).\nby apply/subsetP=> x; move/generatedP; apply.\nQed.\n\nLemma genGid : forall G, <<G>> = G.\nProof.\nby move=> G; apply/eqP; rewrite eqEsubset gen_subG subset_gen andbT.\nQed.\n\nLemma genGidG : forall G, <<G>>%G = G.\nProof. by move=> G; apply: val_inj; exact: genGid. Qed.\n\nLemma gen_set_id : forall A, group_set A -> <<A>> = A.\nProof. by move=> A gA; exact: (genGid (group gA)). Qed.\n\nLemma genS : forall A B, A \\subset B -> <<A>> \\subset <<B>>.\nProof. by move=> A B sAB; rewrite gen_subG sub_gen. Qed.\n\nLemma gen0 : <<set0>> = 1 :> {set gT}.\nProof. by apply/eqP; rewrite eqEsubset sub1G gen_subG sub0set. Qed.\n\nLemma genD : forall A B, A \\subset <<A :\\: B>> -> <<A :\\: B>> = <<A>>.\nProof.\nby move=> A B sAB; apply/eqP; rewrite eqEsubset genS (subsetDl, gen_subG).\nQed.\n\nLemma genV : forall A, <<A^-1>> = <<A>>.\nProof.\nmove=> A; apply/eqP; rewrite eqEsubset !gen_subG -!(invSg _ <<_>>) invgK.\nby rewrite !invGid !subset_gen.\nQed.\n\nLemma genJ : forall A z,  <<A :^z>> = <<A>> :^ z.\nProof.\nmove=> A z; apply/eqP; rewrite eqEsubset sub_conjg.\nby rewrite !gen_subG conjSg -?sub_conjg !subset_gen.\nQed.\n\nLemma genD1 : forall A x, x \\in <<A :\\ x>> -> <<A :\\ x>> = <<A>>.\nProof.\nmove=> A x gA'x; apply/eqP; rewrite eqEsubset genS; last by rewrite subsetDl.\nrewrite gen_subG; apply/subsetP=> y Ay.\nby case: (y =P x) => [-> //|]; move/eqP=> nyx; rewrite mem_gen // !inE nyx.\nQed.\n\nNotation mulgenT := (@mulgen gT) (only parsing).\nNotation mulGenT := (@mulGen gT) (only parsing).\n\nLemma mulgenE : forall A B, A <*> B = <<A :|: B>>. Proof. by []. Qed.\n\nLemma mulGenE : forall G H, (G <*> H)%G :=: G <*> H. Proof. by []. Qed.\n\nLemma mulgenC : commutative mulgenT.\nProof. by move=> A B; rewrite /mulgen setUC. Qed.\n\nLemma mulgen_idr : forall A B, A <*> <<B>> = A <*> B.\nProof.\nmove=> A B; apply/eqP; rewrite eqEsubset gen_subG subUset gen_subG /=.\nby rewrite -subUset subset_gen genS // setUS // subset_gen.\nQed.\n\nLemma mulgen_idl : forall A B, <<A>> <*> B = A <*> B.\nProof. by move=> A B; rewrite -!(mulgenC B) mulgen_idr. Qed.\n\nLemma mulgen_subl : forall A B, A \\subset A <*> B.\nProof. by move=> A B; rewrite sub_gen ?subsetUl. Qed.\n\nLemma mulgen_subr : forall A B, B \\subset A <*> B.\nProof. by move=> A B; rewrite sub_gen ?subsetUr. Qed.\n\nLemma mulgen_subG : forall A B G,\n  (A <*> B \\subset G) = (A \\subset G) && (B \\subset G).\nProof. by move=> A B G; rewrite gen_subG subUset. Qed.\n\nLemma genDU : forall A B C,\n  A \\subset C -> <<C :\\: A>> = <<B>> -> <<A :|: B>> = <<C>>.\nProof.\nmove=> A B C sAC; rewrite -mulgenE -mulgen_idr => <- {B}.\nrewrite mulgen_idr; congr <<_>>.\nrewrite setDE setUIr setUCr setIT; exact/setUidPr.\nQed.\n\nLemma mulgenA : associative mulgenT.\nProof. by move=> A B C; rewrite mulgen_idl mulgen_idr /mulgen setUA. Qed.\n\nLemma mulgen1G : forall G, 1 <*> G = G.\nProof. by move=> G; rewrite -gen0 mulgen_idl /mulgen set0U genGid. Qed.\n\nLemma mulgenG1 : forall G, G <*> 1 = G.\nProof. by move=> G; rewrite mulgenC mulgen1G. Qed.\n\nLemma genM_mulgen : forall G H, <<G * H>> = G <*> H.\nProof.\nmove=> G H; apply/eqP; rewrite eqEsubset gen_subG /= -{1}[G <*> H]mulGid.\nrewrite genS; last by rewrite subUset mulG_subl mulG_subr.\nby rewrite mulgSS ?(sub_gen, subsetUl, subsetUr).\nQed.\n\nLemma trivMg : forall G H, (G * H == 1) = (G :==: 1) && (H :==: 1).\nProof.\nmove=> G H; rewrite !eqEsubset -{2}[1]mulGid mulgSS ?sub1G // !andbT.\nby rewrite -gen_subG genM_mulgen gen_subG subUset.\nQed.\n\nLemma comm_mulgenE : forall G H, commute G H -> G <*> H = G * H.\nProof.\nmove=> G H; move/comm_group_setP=> gGH; rewrite -genM_mulgen.\nexact: (genGid (group gGH)).\nQed.\n\nLemma mulGenC : commutative mulGenT.\nProof. by move=> G H; apply: val_inj; exact: mulgenC. Qed.\n\nLemma mulGenA : associative mulGenT.\nProof. by move=> G H K; apply: val_inj; exact: mulgenA. Qed.\n\nLemma mulGen1G : left_id 1%G mulGenT.\nProof. by move=> G; apply: val_inj; exact: mulgen1G. Qed.\n\nLemma mulGenG1 : right_id 1%G mulGenT.\nProof. by move=> G; apply: val_inj; exact: mulgenG1. Qed.\n\nCanonical Structure mulGen_law := Monoid.Law mulGenA mulGen1G mulGenG1.\nCanonical Structure mulGen_abelaw := Monoid.ComLaw mulGenC.\n\nLemma bigprodGEgen : forall I r (P : pred I) (F : I -> {set gT}),\n  (\\prod_(i <- r | P i) <<F i>>)%G :=: << \\bigcup_(i <- r | P i) F i >>.\nProof.\nmove=> I r P F; pose R := [fun G A => @gval gT G = <<A>>].\napply: (big_rel R) => //= [|_ A _ B -> ->]; first by rewrite gen0.\nby rewrite mulgen_idl mulgen_idr.\nQed.\n\nLemma bigprodGE : forall I r (P : pred I) (F : I -> {group gT}),\n  (\\prod_(i <- r | P i) F i)%G :=: << \\bigcup_(i <- r | P i) F i >>.\nProof.\nmove=> I r P F; rewrite -bigprodGEgen /=; apply: congr_group.\nby apply: eq_bigr => i _; rewrite genGidG.\nQed.\n\nLemma mem_commg : forall A B x y, x \\in A -> y \\in B -> [~ x, y] \\in [~: A, B].\nProof. by move=> A B x y Ax By; rewrite mem_gen ?mem_imset2. Qed.\n\nLemma commSg : forall A B C, A \\subset B -> [~: A, C] \\subset [~: B, C].\nProof. by move=> A B C sAC; rewrite genS ?imset2S. Qed.\n\nLemma commgS : forall A B C, B \\subset C -> [~: A, B] \\subset [~: A, C].\nProof. by move=> A B C sBC; rewrite genS ?imset2S. Qed.\n\nLemma commgSS : forall A B C D,\n  A \\subset B -> C \\subset D -> [~: A, C] \\subset [~: B, D].\nProof. by move=> A B C D sAB sCD; rewrite genS ?imset2S. Qed.\n\nLemma der1_subG : forall G, [~: G, G] \\subset G.\nProof.\nmove=> G; rewrite gen_subG; apply/subsetP=> z; case/imset2P=> x y Gx Gy ->{z}.\nexact: groupR.\nQed.\n\nLemma comm_subG : forall A B G,\n  A \\subset G -> B \\subset G -> [~: A, B] \\subset G.\nProof.\nmove=> A B G sAG sBG; apply: subset_trans (der1_subG G); exact: commgSS.\nQed.\n\nLemma commGC : forall A B, [~: A, B] = [~: B, A].\nProof.\nmove=> A B; rewrite -[[~: A, B]]genV; congr <<_>>; apply/setP=> z; rewrite inE.\nby apply/imset2P/imset2P=> [] [x y Ax Ay]; last rewrite -{1}(invgK z);\n  rewrite -invg_comm; move/invg_inj->; exists y x.\nQed.\n\nLemma conjsRg : forall A B x, [~: A, B] :^ x = [~: A :^ x, B :^ x].\nProof.\nsuffices subJ: forall A B x, [~: A, B] :^ x \\subset [~: A :^ x, B :^ x].\n  move=> A B x; apply/eqP; rewrite eqEsubset subJ /= -sub_conjgV.\n  by rewrite -{2}(conjsgK x A) -{2}(conjsgK x B).\nmove=> A B x; rewrite -genJ gen_subG.\napply/subsetP=> yzx; case/imsetP=> yz; case/imset2P=> y z Ay Bz -> -> {yz yzx}.\nby rewrite conjRg mem_commg ?memJ_conjg.\nQed.\n\nEnd GeneratedGroup.\n\nSection Cycles.\n\n(* Elementary properties of cycles and order, needed in perm.v.  *)\n(* More advanced results on the structure of cyclic groups will  *)\n(* be given in cyclic.v.                                         *)\n\nVariable gT : finGroupType.\nImplicit Types x y : gT.\nImplicit Types G : {group gT}.\n\nImport Monoid.Theory.\n\nLemma cycle1 : <[1]> = [1 gT].\nProof. exact: genGid. Qed.\n\nLemma order1 : #[1 : gT] = 1%N.\nProof. by rewrite /order cycle1 cards1. Qed.\n\nLemma cycle_id : forall x, x \\in <[x]>.\nProof. by move=> x; rewrite mem_gen // set11. Qed.\n\nLemma mem_cycle : forall x i, x ^+ i \\in <[x]>.\nProof. by move=> x i; rewrite groupX // cycle_id. Qed.\n\nLemma cycle_subG : forall x G, (<[x]> \\subset G) = (x \\in G).\nProof. by move=> x G; rewrite gen_subG sub1set. Qed.\n\nLemma cycle_traject : forall x, <[x]> =i traject (mulg x) 1 #[x].\nProof.\nmove=> x; set t := traject _ _; apply/subset_eqP.\nhave tP: forall n y, y \\in t n -> exists2 i, i < n & y = x ^+ i.\n  by move=> n y; case/trajectP=> i lt_i ->; rewrite -iteropE; exists i.\nhave stx: t _ \\subset <[x]>.\n  by move=> n; apply/subsetP=> xi; case/tP=> i _ ->{xi}; exact: mem_cycle.\nrewrite stx andbT -(eq_subset_r (in_set _)); set G := finset _.\nhave Gx: x ^+ _ \\in G.\n  move=> i; rewrite inE [x ^+ _]iteropE; move: i; apply/loopingP.\n  apply/idPn; rewrite -looping_uniq; move/card_uniqP => cardG.\n  by have:= subset_leq_card (stx #[x].+1); rewrite cardG size_traject ltnn.\nrewrite -[G]gen_set_id; first by rewrite cycle_subG mem_gen ?(Gx 1%N).\napply/group_setP; split=> [|xi xj]; first exact: (Gx 0).\nby rewrite 2!inE; case/tP => i _ ->; case/tP => j _ ->; rewrite -expgn_add Gx.\nQed.\n\nLemma cyclePmin : forall x y,\n  reflect (exists2 i, i < #[x] & y = x ^+ i) (y \\in <[x]>).\nProof.\nmove=> x y; rewrite cycle_traject.\nby apply: (iffP trajectP) => [] [i lt_i_x ->]; exists i; rewrite -?iteropE.\nQed.\n\nLemma cycleP : forall x y, reflect (exists i, y = x ^+ i) (y \\in <[x]>).\nProof.\nmove=> x y; apply: (iffP idP) => [|[i ->]]; last exact: mem_cycle.\nby case/cyclePmin=> i _; exists i.\nQed.\n\nLemma expg_order : forall x, x ^+ #[x] = 1.\nProof.\nmove=> x; have: uniq (traject (mulg x) 1 #[x]).\n  by apply/card_uniqP; rewrite size_traject -(eq_card (cycle_traject x)).\ncase/cyclePmin: (mem_cycle x #[x]) => [] [//|i] ltix.\nrewrite -(subnKC ltix) addSnnS /= expgn_add; move: (_ - _) => j x_j1.\ncase/andP; case/trajectP; exists j; first exact: leq_addl.\nby apply: (mulgI (x ^+ i.+1)); rewrite -iterSr iterS -iteropE -expgS mulg1.\nQed.\n\nLemma expg_mod_order : forall x i, x ^+ (i %% #[x]) = x ^+ i.\nProof.\nmove=> x i; rewrite {2}(divn_eq i #[x]) expgn_add mulnC expgn_mul.\nby rewrite expg_order exp1gn mul1g.\nQed.\n\nLemma invg_expg : forall x, x^-1 = x ^+ #[x].-1.\nProof.\nby move=> x; apply/eqP; rewrite eq_invg_mul -expgS prednK ?expg_order.\nQed.\n\nLemma cycleX : forall x i, <[x ^+ i]> \\subset <[x]>.\nProof. move=> x i; rewrite cycle_subG; exact: mem_cycle. Qed.\n\nLemma cycleV : forall x, <[x^-1]> = <[x]>.\nProof.\nmove=> x; symmetry; apply/eqP; rewrite eqEsubset.\nby rewrite !cycle_subG groupV -groupV !cycle_id.\nQed.\n\nLemma orderV : forall x, #[x^-1] = #[x].\nProof. by move=> x; rewrite /order cycleV. Qed.\n\nLemma cycleJ : forall x y, <[x ^ y]> = <[x]> :^ y.\nProof. by move=> x y; rewrite -genJ conjg_set1. Qed.\n\nLemma orderJ : forall x y, #[x ^ y] = #[x].\nProof. by move=> x y; rewrite /order cycleJ cardJg. Qed.\n\nEnd Cycles.\n\nSection Normaliser.\n\nVariable gT : finGroupType.\nNotation sT := {set gT}.\nImplicit Types x y z : gT.\nImplicit Types A B C D : sT.\nImplicit Type G H K : {group gT}.\n\nLemma normP : forall x A, reflect (A :^ x = A) (x \\in 'N(A)).\nProof.\nmove=> x A; suff ->: (x \\in 'N(A)) = (A :^ x == A) by exact: eqP.\nby rewrite eqEcard cardJg leqnn andbT inE.\nQed.\nImplicit Arguments normP [x A].\n\nLemma group_set_normaliser : forall A, group_set 'N(A).\nProof.\nmove=> A; apply/group_setP; split=> [|x y Nx Ny]; rewrite inE ?conjsg1 //.\nby rewrite conjsgM !(normP _).\nQed.\n\nCanonical Structure normaliser_group A := group (group_set_normaliser A).\n\nLemma normsP : forall A B, reflect {in A, normalised B} (A \\subset 'N(B)).\nProof.\nmove=> A B; apply: (iffP subsetP) => nBA x Ax; last by rewrite inE nBA //.\nby apply/normP; exact: nBA.\nQed.\nImplicit Arguments normsP [A B].\n\nLemma memJ_norm : forall x y A, x \\in 'N(A) -> (y ^ x \\in A) = (y \\in A).\nProof. by move=> x y A Nx; rewrite -{1}(normP Nx) memJ_conjg. Qed.\n\nLemma norm1 : 'N(1) =  setT :> {set gT}.\nProof. by apply/setP=> x; rewrite !inE conjs1g subxx. Qed.\n\nLemma norms1 : forall A, A \\subset 'N(1).\nProof. rewrite norm1; exact: subsetT. Qed.\n\nLemma normG : forall G, G \\subset 'N(G).\nProof. move=> G; apply/normsP; exact: conjGid. Qed.\n\nLemma normsG : forall A G, A \\subset G -> A \\subset 'N(G).\nProof. move=> A G sAG; exact: subset_trans (normG G). Qed.\n\nLemma normC : forall A B, A \\subset 'N(B) -> commute A B.\nProof.\nmove=> A B; move/subsetP=> nBA; apply/setP => u.\napply/mulsgP/mulsgP=> [[x y Ax By] | [y x By Ax]] -> {u}.\n  by exists (y ^ x^-1) x; rewrite -?conjgCV // memJ_norm // groupV nBA.\nby exists x (y ^ x); rewrite -?conjgC // memJ_norm // nBA.\nQed.\n\nLemma norm_mulgenEl : forall G H, G \\subset 'N(H) -> G <*> H = G * H.\nProof. by move=> G H; move/normC; move/comm_mulgenE. Qed.\n\nLemma norm_mulgenEr : forall G H, H \\subset 'N(G) -> G <*> H = G * H.\nProof. by move=> G H; move/normC=> cHG; exact: comm_mulgenE. Qed.\n\nLemma norm_rlcoset : forall G x, x \\in 'N(G) -> G :* x = x *: G.\nProof. by move=> G x; rewrite -sub1set; move/normC. Qed.\n\nLemma rcoset_mul : forall G x y,\n  x \\in 'N(G) -> (G :* x) * (G :* y) = G :* (x * y).\nProof.\nmove=> G x y; move/norm_rlcoset=> GxxG.\nby rewrite mulgA -(mulgA _ _ G) -GxxG mulgA mulGid -mulgA mulg_set1.\nQed.\n\nLemma normJ : forall A x, 'N(A :^ x) = 'N(A) :^ x.\nProof.\nmove=> A x; apply/setP=> y.\nby rewrite mem_conjg !inE -conjsgM conjgCV conjsgM conjSg.\nQed.\n\nLemma norm_gen : forall A, 'N(A) \\subset 'N(<<A>>).\nProof. by move=> A; apply/normsP=> x Nx; rewrite -genJ (normP Nx). Qed.\n\nLemma norm_class : forall x G, G \\subset 'N(x ^: G).\nProof. by move=> x G; apply/normsP=> y; exact: classGidr. Qed.\n\nSection norm_trans.\n\nVariables A B C : {set gT}.\nHypotheses (nBA : A \\subset 'N(B)) (nCA : A \\subset 'N(C)).\n\nLemma norms_gen : A \\subset 'N(<<B>>).\nProof. exact: subset_trans nBA (norm_gen B). Qed.\n\nLemma norms_norm : A \\subset 'N('N(B)).\nProof. by apply/normsP=> x Ax; rewrite -normJ (normsP nBA). Qed.\n\nLemma normsI : A \\subset 'N(B :&: C).\nProof. by apply/normsP=> x Ax; rewrite conjIg !(normsP _ x Ax). Qed.\n\nLemma normsM : A \\subset 'N(B * C).\nProof. by apply/normsP=> x Ax; rewrite conjsMg !(normsP _ x Ax). Qed.\n\nLemma norms_mulgen : A \\subset 'N(B <*> C).\nProof. by apply/normsP=> x Ax; rewrite -genJ conjUg !(normsP _ x Ax). Qed.\n\nLemma normsR : A \\subset 'N([~: B, C]).\nProof. by apply/normsP=> x Ax; rewrite conjsRg !(normsP _ x Ax). Qed.\n\nEnd norm_trans.\n\nLemma normalP : forall A B,\n  reflect (A \\subset B /\\ {in B, normalised A}) (A <| B).\nProof. by move=> A B; apply: (iffP andP)=> [] [sAB]; move/normsP. Qed.\n\nLemma normal_norm : forall A B, A <| B -> B \\subset 'N(A).\nProof. by move=> A B; case/andP. Qed.\n\nLemma normal_sub : forall A B, A <| B -> A \\subset B.\nProof. by move=> A B; case/andP. Qed.\n\nLemma normalS : forall G H K,\n  K \\subset H -> H \\subset G -> K <| G -> K <| H.\nProof.\nmove=> G H K sKH sHG; case/andP=> _ nKG.\nby rewrite /(K <| _) sKH (subset_trans sHG).\nQed.\n\nLemma normal1 : forall G, 1 <| G.\nProof. by move=> G; rewrite /normal sub1set group1 norms1. Qed.\n\nLemma normal_refl : forall G, G <| G.\nProof. by move=> G; rewrite /(G <| _) normG subxx. Qed.\n\nLemma normalG : forall G, G <| 'N(G).\nProof. by move=> G; rewrite /(G <| _) normG subxx. Qed.\n\nLemma normalSG : forall G H, H \\subset G -> H <| 'N_G(H).\nProof.\nmove=> G H sHG; rewrite /(H <| _) subsetI sHG normG subIset //.\nby rewrite subxx orbT.\nQed.\n\nLemma normalM : forall G H K, H <| G -> K <| G -> H * K <| G.\nProof.\nmove=> G H K; case/andP=> sHG nHG; case/andP=> sKG nKG.\nby rewrite /normal mul_subG ?normsM.\nQed.\n\nLemma normal_subnorm : forall G H, (H <| 'N_G(H)) = (H \\subset G).\nProof. by move=> G H; rewrite /normal subsetIr subsetI normG !andbT. Qed.\n\nLemma cent1P : forall x y, reflect (commute x y) (x \\in 'C[y]).\nProof.\nmove=> x y; rewrite inE conjg_set1 sub1set inE (sameP eqP conjg_fixP).\nrewrite commg1_sym; exact: commgP.\nQed.\n\nCanonical Structure centraliser_group A : {group _} :=\n  Eval hnf in [group of 'C(A)].\n\nLemma cent_set1 : forall x, 'C([set x]) = 'C[x].\nProof. by move=> x; apply: big_pred1 => y /=; rewrite inE. Qed.\n\nLemma centP : forall A x, reflect (centralises x A) (x \\in 'C(A)).\nProof.\nby move=> A x; apply: (iffP bigcapP) => cxA y; move/cxA; move/cent1P.\nQed.\n\nLemma centsP : forall A B, reflect {in A, centralised B} (A \\subset 'C(B)).\nProof.\nby move=> A B; apply: (iffP subsetP) => cAB x; move/cAB; move/centP.\nQed.\n\nLemma centsC : forall A B, (A \\subset 'C(B)) = (B \\subset 'C(A)).\nProof.\nby move=> A B; apply/centsP/centsP=> cAB x ? y ?; rewrite /commute -cAB.\nQed.\n\nLemma cents1 : forall A, A \\subset 'C(1).\nProof. by move=> A; rewrite centsC sub1G. Qed.\n\nLemma cent1T : 'C(1) = setT :> {set gT}.\nProof. by apply/eqP; rewrite -subTset cents1. Qed.\n\nLemma cent11T : 'C[1] = setT :> {set gT}.\nProof. by rewrite -cent_set1 cent1T. Qed.\n\nLemma cent_sub : forall A, 'C(A) \\subset 'N(A).\nProof.\nmove=> A; apply/subsetP=> x; move/centP=> cAx; rewrite inE.\nby apply/subsetP=> yx; case/imsetP=> y Ay ->; rewrite /conjg -cAx ?mulKg.\nQed.\n\nLemma cents_norm : forall A B, A \\subset 'C(B) -> A \\subset 'N(B).\nProof. move=> A B cAB; exact: subset_trans (cent_sub B). Qed.\n\nLemma centC : forall A B, A \\subset 'C(B) -> commute A B.\nProof. move=> A B cAB; exact: normC (cents_norm cAB). Qed.\n\nLemma cent_mulgenEl : forall G H, G \\subset 'C(H) -> G <*> H = G * H.\nProof. move=> G H cGH; exact: norm_mulgenEl (cents_norm cGH). Qed.\n\nLemma cent_mulgenEr : forall G H, H \\subset 'C(G) -> G <*> H = G * H.\nProof. move=> G H cGH; exact: norm_mulgenEr (cents_norm cGH). Qed.\n\nLemma centJ : forall A x, 'C(A :^ x) = 'C(A) :^ x.\nProof.\nmove=> A x; apply/setP=> y; rewrite mem_conjg; apply/centP/centP=> cAy z Az.\n  by apply: (conjg_inj x); rewrite 2!conjMg conjgKV cAy ?memJ_conjg.\nby apply: (conjg_inj x^-1); rewrite 2!conjMg cAy -?mem_conjg.\nQed.\n\nLemma cent_norm : forall A, 'N(A) \\subset 'N('C(A)).\nProof. by move=> A; apply/normsP=> x nCx; rewrite -centJ (normP nCx). Qed.\n\nLemma norms_cent : forall A B, A \\subset 'N(B) -> A \\subset 'N('C(B)).\nProof. move=> A B nBA; exact: subset_trans nBA (cent_norm B). Qed.\n\nLemma cent_normal : forall A, 'C(A) <| 'N(A).\nProof. by move=> A; rewrite /(_ <| _) cent_sub cent_norm. Qed.\n\nLemma centS : forall A B, B \\subset A -> 'C(A) \\subset 'C(B).\nProof. by move=> A B sAB; rewrite centsC (subset_trans sAB) 1?centsC. Qed.\n\nLemma centsS : forall A B C, A \\subset B -> C \\subset 'C(B) -> C \\subset 'C(A).\nProof. by move=> A B C sAB cCB; exact: subset_trans cCB (centS sAB). Qed.\n\nLemma centSS : forall A B C D,\n  A \\subset C -> B \\subset D -> C \\subset 'C(D) -> A \\subset 'C(B).\nProof. move=> A B C D sAC sBD cCD; exact: subset_trans (centsS sBD cCD). Qed.\n\nLemma centI : forall A B, 'C(A) <*> 'C(B) \\subset 'C(A :&: B).\nProof.\nby move=> A B; rewrite gen_subG subUset !centS ?(subsetIl, subsetIr).\nQed.\n\nLemma centU : forall A B, 'C(A :|: B) = 'C(A) :&: 'C(B).\nProof.\nmove=> A B; apply/eqP.\nrewrite eqEsubset subsetI 2?centS ?(subsetUl, subsetUr) //=.\nby rewrite centsC subUset -centsC subsetIl -centsC subsetIr.\nQed.\n\nLemma cent_gen : forall A, 'C(<<A>>) = 'C(A).\nProof.\nmove=> A; apply/eqP; rewrite eqEsubset centS ?subset_gen //=.\nby rewrite -centsC gen_subG centsC.\nQed.\n\nLemma cent_mulgen : forall A B, 'C(A <*> B) = 'C(A) :&: 'C(B).\nProof. by move=> G H; rewrite cent_gen centU. Qed.\n\nLemma centM : forall G H, 'C(G * H) = 'C(G) :&: 'C(H).\nProof. by move=> G H; rewrite -cent_gen genM_mulgen cent_mulgen. Qed.\n\nLemma cent_classP : forall x G, reflect (x ^: G = [set x]) (x \\in 'C(G)).\nProof.\nmove=> x G; apply: (iffP (centP _ _)) => [Cx | Cx1 y Gy].\n  apply/eqP; rewrite eqEsubset sub1set class_refl andbT.\n  by apply/subsetP=> xy; case/imsetP=> y Gy ->; rewrite inE conjgE Cx ?mulKg.\napply/commgP; apply/conjg_fixP; apply/set1P.\nby rewrite -Cx1; apply/imsetP; exists y.\nQed.\n\nLemma commG1P : forall A B, reflect ([~: A, B] = 1) (A \\subset 'C(B)).\nProof.\nmove=> A B; apply: (iffP (centsP A B)) => [cAB | cAB1 x Ax y By].\n  apply/trivgP; rewrite gen_subG; apply/subsetP=> xy.\n  by case/imset2P=> x y Ax Ay ->{xy}; rewrite inE; apply/commgP; exact: cAB.\nby apply/commgP; rewrite -in_set1 -[[set 1]]cAB1 mem_commg.\nQed.\n\nLemma abelianE : forall A, abelian A = (A \\subset 'C(A)). Proof. by []. Qed.\n\nLemma abelian1 : abelian [1 gT]. Proof. exact: sub1G. Qed.\n\nLemma abelianS : forall A B, A \\subset B -> abelian B -> abelian A.\nProof. move=> A B sAB; exact: centSS. Qed.\n\nLemma abelianJ : forall A x, abelian (A :^ x) = abelian A.\nProof. by move=> A x; rewrite /abelian centJ conjSg. Qed.\n\nEnd Normaliser.\n\nImplicit Arguments normP [gT x A].\nImplicit Arguments centP [gT x A].\nImplicit Arguments normsP [gT A B].\nImplicit Arguments cent1P [gT x y].\nImplicit Arguments normalP [gT A B].\nImplicit Arguments centsP [gT A B].\nImplicit Arguments commG1P [gT A B].\n\nPrenex Implicits normP normsP cent1P normalP centP centsP commG1P.\n\nArguments Scope normaliser_group [_ group_scope].\nArguments Scope centraliser_group [_ group_scope].\n\nNotation \"''N' ( A )\" := (normaliser_group A) : subgroup_scope.\nNotation \"''C' ( A )\" := (centraliser_group A) : subgroup_scope.\nNotation \"''C' [ x ]\" := ('N([set x%g]))%G : subgroup_scope.\nNotation \"''N_' G ( A )\" := (G :&: 'N(A))%G : subgroup_scope.\nNotation \"''C_' G ( A )\" := (G :&: 'C(A))%G : subgroup_scope.\nNotation \"''C_' G [ x ]\" := ('N_G([set x%g]))%G : subgroup_scope.\n\nHint Resolve normal_refl.\n\nSection MinMaxGroup.\n\nVariable gT : finGroupType.\nVariable gP : pred {group gT}.\nArguments Scope gP [subgroup_scope].\n\nDefinition maxgroup := maxset (fun A => group_set A && gP <<A>>).\nDefinition mingroup := minset (fun A => group_set A && gP <<A>>).\n\nLemma ex_maxgroup : (exists G, gP G) -> {G : {group gT} | maxgroup G}.\nProof.\nmove=> exP; have [A maxA]: {A | maxgroup A}.\n  apply: ex_maxset; case: exP => G gPG.\n  by exists (G : {set gT}); rewrite groupP genGidG.\nby exists <<A>>%G; rewrite /= gen_set_id; case/andP: (maxsetp maxA).\nQed.\n\nLemma ex_mingroup : (exists G, gP G) -> {G : {group gT} | mingroup G}.\nProof.\nmove=> exP; have [A minA]: {A | mingroup A}.\n  apply: ex_minset; case: exP => G gPG.\n  by exists (G : {set gT}); rewrite groupP genGidG.\nby exists <<A>>%G; rewrite /= gen_set_id; case/andP: (minsetp minA).\nQed.\n\nVariable G : {group gT}.\n\nLemma mingroupP :\n  reflect (gP G /\\ forall H, gP H -> H \\subset G -> H :=: G) (mingroup G).\nProof.\napply: (iffP minsetP); rewrite /= groupP genGidG /=; case=> -> minG.\n  by split=> // H gPH sGH; apply: minG; rewrite // groupP genGidG.\nsplit=> // A; case/andP=> gA gPA; rewrite -(gen_set_id gA); exact: minG.\nQed.\n\nLemma maxgroupP :\n  reflect (gP G /\\ forall H, gP H -> G \\subset H -> H :=: G) (maxgroup G).\nProof.\napply: (iffP maxsetP); rewrite /= groupP genGidG /=; case=> -> maxG.\n  by split=> // H gPH sGH; apply: maxG; rewrite // groupP genGidG.\nsplit=> // A; case/andP=> gA gPA; rewrite -(gen_set_id gA); exact: maxG.\nQed.\n\nLemma maxgroupp : maxgroup G -> gP G. Proof. by case/maxgroupP. Qed.\n\nLemma mingroupp : mingroup G -> gP G. Proof. by case/mingroupP. Qed.\n\nHypothesis gPG : gP G.\n\nLemma maxgroup_exists : {H : {group gT} | maxgroup H & G \\subset H}.\nProof.\nhave [A maxA sGA]: {A | maxgroup A & G \\subset A}.\n  by apply: maxset_exists; rewrite groupP genGidG.\nby exists <<A>>%G; rewrite /= gen_set_id; case/andP: (maxsetp maxA).\nQed.\n\nLemma mingroup_exists : {H : {group gT} | mingroup H & H \\subset G}.\nProof.\nhave [A maxA sGA]: {A | mingroup A & A \\subset G}.\n  by apply: minset_exists; rewrite groupP genGidG.\nby exists <<A>>%G; rewrite /= gen_set_id; case/andP: (minsetp maxA).\nQed.\n\nEnd MinMaxGroup.\n\nNotation \"[ 'max' A 'of' G | gP ]\" := (maxgroup (fun G : {group _} => gP) A)\n  (at level 0, format \"[ 'max'  A  'of'  G  |  gP ]\") : group_scope.\n\nNotation \"[ 'max' G | gP ]\" := [max gval G of G | gP]\n  (at level 0, format \"[ 'max'  G  |  gP ]\") : group_scope.\n\nNotation \"[ 'min' A 'of' G | gP ]\" := (mingroup (fun G : {group _} => gP) A)\n  (at level 0, format \"[ 'min'  A  'of'  G  |  gP ]\") : group_scope.\n\nNotation \"[ 'min' G | gP ]\" := [min gval G of G | gP]\n  (at level 0, format \"[ 'min'  G  |  gP ]\") : group_scope.\n\nImplicit Arguments mingroupP [gT gP G].\nImplicit Arguments maxgroupP [gT gP G].\nPrenex Implicits mingroupP maxgroupP.", "meta": {"author": "Wassasin", "repo": "ssreflect", "sha": "45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4", "save_path": "github-repos/coq/Wassasin-ssreflect", "path": "github-repos/coq/Wassasin-ssreflect/ssreflect-45cf056aa48bec1e7e2bbb77cb4458d4bddf43e4/theories/groups.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7078431803304628}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nDefinition beq_string (x y:string) := if string_dec x y then true else false.\n\nTheorem beq_string_refl : forall s:string, beq_string s s=true.\nintro s.\nunfold beq_string.\ndestruct (string_dec s s).\n(* Case equal => true *) reflexivity.\n(* Case not equal => s <> s => impossible *) contradiction.\nQed.\n\nTheorem beq_string_true_iff: forall x y : string, beq_string x y = true <-> x=y.\nintros x y.\nunfold beq_string.\ndestruct (string_dec x y);split.\nintro;assumption.\nintro;reflexivity.\nintro h;inversion h.\nintro;subst y;contradiction.\nQed.\n\nTheorem beq_string_false_iff: forall x y : string, beq_string x y = false <-> x<>y.\nintros x y.\nunfold beq_string.\ndestruct (string_dec x y);split.\nintro h;inversion h.\nintro h;subst y;contradiction.\nintro;assumption.\nintro;reflexivity.\nQed.\n\nTheorem false_beq_string : forall x y, x<>y -> beq_string x y = false.\nintros x y.\nrewrite beq_string_false_iff.\nintro;assumption.\nQed.\n\nDefinition total_map (A:Type) := string -> A.\n\nDefinition t_empty {A:Type} (v:A) : total_map A := fun _ => v.\n\nDefinition t_update {A:Type} (m:total_map A) (x:string) (v:A) := fun y => if beq_string x y then v else m y.\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A := t_empty None.\n\nDefinition update {A:Type} (m:partial_map A) (x:string) (v:A) := t_update m x (Some v).\n\nDefinition update_commute {A:Type} (m:partial_map A) (x y:string) (v1 v2:A) := forall s, update( update m x v1) y v2 s = update (update m y v2) x v1 s.\n\n(* Two consecutive updates commute when the update are performed on different identifiers *)\nTheorem commute : forall (A:Type) (m:partial_map A) (x y : string) (v1 v2:A),\nx<>y -> update_commute m x y v1 v2.\nProof.\nunfold update_commute.\nintros.\nunfold update.\nunfold t_update.\nunfold beq_string.\ndestruct (string_dec x s);destruct (string_dec y s).\nsubst y. subst x. contradiction.\nreflexivity.\nreflexivity.\nreflexivity.\nQed.\n\n(* Two consecutive updates do not commute when performed on same identifier with different values *)\nTheorem not_commute : forall (A:Type) (m:partial_map A) (x y : string) (v1 v2:A),\nx=y /\\ v1<>v2 -> not (update_commute m x y v1 v2).\nProof.\nintros A m x y v1 v2.\nintros [xyeq v1v2neq].\nsubst y.\nunfold not.\nunfold update_commute.\nintro h.\nunfold not in v1v2neq.\napply v1v2neq.\nspecialize (h x).\nunfold update in h.\nunfold t_update in h.\nunfold beq_string in h.\ndestruct (string_dec x x).\ninversion h. reflexivity.\ncontradiction.\nQed.\n\n(* If two consecutive updates commute and the values are different, then the identifiers are different *)\nTheorem commute_inv : forall (A:Type) (m:partial_map A) (x y : string) (v1 v2:A),\n(v1<>v2 /\\ update_commute m x y v1 v2)\n-> x<>y.\nintros A m x y a b.\nintros [ha hb].\nintro xyeq. subst y.\napply ha.\nunfold update_commute in hb.\nunfold update in hb.\nunfold t_update in hb.\nunfold beq_string in hb.\nspecialize (hb x).\ndestruct (string_dec x x).\ninversion hb. reflexivity.\ncontradiction.\nQed.\n\n(* If two consecutive updates do not commute and the identifier are the same, then the values are different *)\nTheorem not_commute_inv : forall (A:Type) (m:partial_map A) (x y : string) (v1 v2:A), (x=y /\\\nnot (update_commute m x y v1 v2)) -> v1<>v2.\nintros A m x y v1 v2.\nintros [ha hb].\nintro hc.\napply hb. clear hb.\nsubst v2 y.\nrename v1 into v.\nunfold update_commute. intro s.\nreflexivity.\nQed.\n\n(* If two consecutive updates commute, then the values are identical or the variables are different *)\nTheorem commute_then : forall (A:Type) (m:partial_map A) (x y : string) (v1 v2:A),\nupdate_commute m x y v1 v2 -> x<>y \\/ v1=v2.\nintros A m x y a b.\nunfold update_commute. unfold update. unfold t_update. unfold beq_string.\nintro h.\nspecialize (h x).\ndestruct (string_dec y x);destruct (string_dec x x).\nsubst y. inversion h. subst b. right. reflexivity.\ncontradiction.\nleft. intro eq. subst y. contradiction.\ncontradiction.\nQed.\n\n(* If two consecutives update do not commute, then the values are different *)\nTheorem not_commute_then : forall (A:Type) (m:partial_map A) (x y : string) (v1 v2:A),\nnot(update_commute m x y v1 v2) -> v1<>v2.\nintros A m x y v1 v2.\nunfold update_commute. unfold update. unfold t_update. unfold beq_string. unfold not.\nintro h.\nintro heq.\napply h.\nintro s.\nsubst v2. rename v1 into v.\ndestruct (string_dec y s);destruct (string_dec x s);reflexivity.\nQed.\n\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/sf/V1/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7078431733357559}}
{"text": "Require Import FinTypes.\n\nDefinition Cardinality (F: finType) := | elem F |.\n\n(** Dupfreeness *)\n(* Proofs about dupfreeness *)\n\n\nLemma dupfree_countOne (X: eqType) (A: list X) : (forall x, count A x <= 1) -> dupfree A.\nProof.\n  induction A.\n  - constructor.\n  - intro H. constructor.\n    + cbn in H.  specialize (H a). deq a. assert (count A a = 0) by omega. now apply countZero.\n    + apply IHA. intro x. specialize (H x). cbn in H. dec; omega.\nQed.\n\nLemma dupfree_elements (X: finType) : dupfree (elem X).\nProof.\n  destruct X as [X [A AI]]. assert (forall x, count A x <= 1) as H'.\n  {\n    intro x. specialize (AI x). omega.\n  }\n  now apply dupfree_countOne.  \nQed.\n\nLemma dupfree_length (X: finType) (A: list X) : dupfree A -> |A| <= Cardinality X.\nProof.\n  unfold Cardinality.  intros D.\n  rewrite <- (dupfree_card D). rewrite <- (dupfree_card (dupfree_elements X)).\n  apply card_le. apply allSub.\nQed.\n\nLemma disjoint_concat X (A: list (list X)) (B: list X) : (forall C, C el A -> disjoint B C) -> disjoint B (concat A).\nProof.\n  intros H. induction A.\n  - cbn. auto.\n  - cbn. apply disjoint_symm. apply disjoint_app. split; auto using disjoint_symm.\nQed.\n\nLemma dupfree_concat (X: Type) (A: list (list X)) : (forall B, B el A -> dupfree B) /\\ (forall B C, B <> C -> B el A -> C el A -> disjoint B C) -> dupfree A -> dupfree (concat A).\nProof.\n  induction A.\n  - constructor.\n  - intros [H H'] D. cbn. apply dupfree_app.\n    + apply disjoint_concat. intros C E. apply H'; auto. inv D. intro G; apply H2. now subst a.\n    + now apply H.\n    + inv D; apply IHA; auto.\nQed.     \n\n(* (** Proofs about Cardinality *) *)\n\n(* Lemma Card_positiv (X: finType) (x:X) : Cardinality X > 0. *)\n(* Proof. *)\n(*   pose proof (elem_spec x).  unfold Cardinality.  destruct (elem X). *)\n(*   - contradiction H. *)\n(*   - cbn. omega. *)\n(* Qed.  *)\n\n(* Lemma Cardinality_card_eq (X: finType): card (elem X) = Cardinality X. *)\n(* Proof. *)\n(*   apply dupfree_card. apply dupfree_elements. *)\n(* Qed. *)\n\n(* Lemma card_upper_bound (X: finType) (A: list X): card A <= Cardinality X. *)\n(* Proof. *)\n(*  rewrite <-  Cardinality_card_eq. apply card_le. apply allSub. *)\n(* Qed.   *)\n\n\n(* Lemma injective_dupfree (X: finType) (Y: Type) (A: list X) (f: X -> Y) : injective f -> dupfree (getImage f). *)\n(* Proof. *)\n(*   intro inj. unfold injective in inj. *)\n(*   unfold getImage. apply dupfree_map. *)\n(*   - firstorder. *)\n(*   - apply dupfree_elements. *)\n(* Qed. *)\n\n(* Theorem pidgeonHole_inj (X Y: finType) (f: X -> Y) (inj: injective f): Cardinality X <= Cardinality Y. *)\n(* Proof. *)\n(*   rewrite <- (getImage_length f). apply dupfree_length. apply (injective_dupfree (elem X) inj). *)\n(* Qed. *)\n\n(* Lemma surj_sub (X Y: finType) (f: X -> Y) (surj: surjective f): elem Y <<= getImage f. *)\n(* Proof. *)\n(* intros y E. specialize (surj y). destruct surj as [x H]. subst y. apply getImage_in. *)\n(* Qed. *)\n\n(* Theorem pidgeonHole_surj (X Y: finType) (f: X -> Y) (surj: surjective f): Cardinality X >= Cardinality Y. *)\n(* Proof. *)\n(*   rewrite <- (getImage_length f). rewrite <- Cardinality_card_eq. *)\n(*     pose proof (card_le (surj_sub surj)) as H. pose proof (card_length_leq (getImage f)) as H'. omega. *)\n(* Qed. *)\n\n(* Lemma eq_iff (x y: nat) : x >= y /\\ x <= y -> x = y. *)\n(* Proof. *)\n(*   omega. *)\n(* Qed. *)\n\n(* Corollary pidgeonHole_bij (X Y: finType) (f: X -> Y) (bij: bijective f): *)\n(*   Cardinality X = Cardinality Y. *)\n(* Proof. *)\n(*   destruct bij as [inj surj]. apply eq_iff. split. *)\n(*   - now eapply pidgeonHole_surj. *)\n(*   - eapply pidgeonHole_inj; eauto. *)\n(* Qed.     *)\n\n(* Lemma Prod_Card (X Y: finType) : Cardinality (X (x) Y) = Cardinality X * Cardinality Y. *)\n(* Proof. *)\n(*   cbn.  unfold prodLists. unfold Cardinality. induction (elem X).  *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite app_length. rewrite IHl. f_equal. apply map_length. *)\n(* Qed.     *)\n\n(* Lemma Option_Card (X: finType) : Cardinality (? X) = S(Cardinality X). *)\n(* Proof. *)\n(*   cbn. now rewrite map_length. *)\n(* Qed. *)\n\n(* Lemma SumCard (X Y: finType) : Cardinality (finType_sum X Y) = Cardinality X + Cardinality Y. *)\n(* Proof. *)\n(*   unfold Cardinality. cbn. rewrite app_length. unfold toSumList1, toSumList2. now  repeat rewrite map_length. *)\n(* Qed. *)\n\n(* Lemma extPow_length X Y L P: |@extensionalPower X Y L P| = | L |. *)\n(* Proof. *)\n(*   induction L. *)\n(*   -  reflexivity. *)\n(*   - simpl. f_equal. apply IHL. *)\n(* Qed. *)\n\n\n(* Lemma concat_map_length (X: Type) (A: list X) (B: list (list X)) : *)\n(* | concat (map (fun x => map (cons x) B) A) |= |A| * |B|. *)\n(* Proof. *)\n(*   induction A. *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite app_length. rewrite map_length. congruence. *)\n(* Qed.     *)\n  \n(* Lemma images_length Y (A: list Y) n : |images A n| = (|A| ^ n)%nat. *)\n(* Proof. *)\n(*   induction n. *)\n(*   - reflexivity. *)\n(*   - cbn. rewrite concat_map_length.  now rewrite IHn. *)\n(* Qed. *)\n\n(* Lemma Vector_Card (X Y: finType): Cardinality (Y ^ X) = (Cardinality Y ^ (Cardinality X ))%nat. *)\n(* Proof. *)\n(*   cbn. rewrite extPow_length. now rewrite images_length. *)\n(* Qed. *)\n\n", "meta": {"author": "uds-psl", "repo": "cbv-lambda-calculus-reasonable", "sha": "4f12b7c8ce2816cdd771d22d04943e0fa81c63fd", "save_path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable", "path": "github-repos/coq/uds-psl-cbv-lambda-calculus-reasonable/cbv-lambda-calculus-reasonable-4f12b7c8ce2816cdd771d22d04943e0fa81c63fd/Base/FiniteTypes/Cardinality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7078414190916165}}
{"text": "Require Export D.\n\n\n\n(** 2 stars (and_assoc)  *)\n(** In the following proof, notice how the _nested pattern_ in the\n    [destruct] breaks the hypothesis [H : P /\\ (Q /\\ R)] down into\n    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)\n\nTheorem and_assoc : forall P Q R : Prop, \n  P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R H.\n  destruct H as [HP [HQ HR]].\n  apply conj. apply conj. apply HP. apply HQ. apply HR.\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/05/P02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7078414100305188}}
{"text": "(** The following axiom systems are used to formalize\n    Euclid's proofs of Euclid's Elements.OriginalProofs.statements. *)\n\n(** First, we define an axiom system for neutral geometry,\n    i.e. geometry without continuity axioms nor parallel postulate.\n *)\n\nClass euclidean_neutral :=\n{\n  Point : Type;\n  Circle : Type;\n  Cong : Point -> Point -> Point -> Point -> Prop;\n  BetS : Point -> Point -> Point -> Prop;\n  PA : Point;\n  PB : Point;\n  PC : Point;\n  CI : Circle -> Point -> Point -> Point -> Prop;\n  eq := @eq Point;\n  neq A B := ~ eq A B;\n  TE A B C := ~ (neq A B /\\ neq B C /\\ ~ BetS A B C);\n  nCol A B C := neq A B /\\ neq A C /\\ neq B C /\\ ~ BetS A B C /\\ ~ BetS A C B /\\ ~ BetS B A C;\n  Col A B C := (eq A B \\/ eq A C \\/ eq B C \\/ BetS B A C \\/ BetS A B C \\/ BetS A C B);\n  Cong_3 A B C a b c := Cong A B a b /\\ Cong B C b c /\\ Cong A C a c;\n  TS P A B Q := exists X, BetS P X Q /\\ Col A B X /\\ nCol A B P;\n  Triangle A B C := nCol A B C;\n\n  OnCirc B J := exists X Y U, CI J U X Y /\\ Cong U B X Y;\n  InCirc P J := exists X Y U V W, CI J U V W /\\ (eq P U \\/ (BetS U Y X /\\ Cong U X V W /\\ Cong U P U Y));\n  OutCirc P J := exists X U V W, CI J U V W /\\ BetS U X P /\\ Cong U X V W;\n\n  cn_congruencetransitive :\n   forall B C D E P Q, Cong P Q B C -> Cong P Q D E -> Cong B C D E;\n  cn_congruencereflexive :\n   forall A B, Cong A B A B;\n  cn_equalityreverse :\n   forall A B, Cong A B B A;\n  cn_sumofparts :\n   forall A B C a b c, Cong A B a b -> Cong B C b c -> BetS A B C -> BetS a b c -> Cong A C a c;\n  cn_stability :\n   forall A B, ~ neq A B -> eq A B;\n  axiom_circle_center_radius :\n   forall A B C J P, CI J A B C -> OnCirc P J -> Cong A P B C;\n  axiom_lower_dim : nCol PA PB PC;\n  axiom_betweennessidentity :\n   forall A B, ~ BetS A B A;\n  axiom_betweennesssymmetry :\n   forall A B C, BetS A B C -> BetS C B A;\n  axiom_innertransitivity :\n   forall A B C D,\n    BetS A B D -> BetS B C D -> BetS A B C;\n  axiom_connectivity :\n   forall A B C D,\n    BetS A B D -> BetS A C D -> ~ BetS A B C -> ~ BetS A C B ->\n    eq B C;\n  axiom_nocollapse :\n   forall A B C D, neq A B -> Cong A B C D -> neq C D;\n  axiom_5_line :\n   forall A B C D a b c d,\n    Cong B C b c -> Cong A D a d -> Cong B D b d ->\n    BetS A B C -> BetS a b c -> Cong A B a b ->\n    Cong D C d c;\n  postulate_Pasch_inner :\n   forall A B C P Q,\n    BetS A P C -> BetS B Q C -> nCol A C B ->\n    exists X, BetS A X Q /\\ BetS B X P;\n  postulate_Pasch_outer :\n   forall A B C P Q,\n    BetS A P C -> BetS B C Q -> nCol B Q A ->\n    exists X, BetS A X Q /\\ BetS B P X;\n  postulate_Euclid2 : forall A B, neq A B -> exists X, BetS A B X;\n  postulate_Euclid3 : forall A B, neq A B -> exists X, CI X A A B;\n}.\n\n(** Second, we enrich the axiom system with line-circle\n     and circle-circle continuity axioms.\n    Those two axioms state that we allow ruler and compass\n    constructions.\n*)\n\nClass euclidean_neutral_ruler_compass `(Ax : euclidean_neutral) :=\n{\n  postulate_line_circle :\n   forall A B C K P Q,\n    CI K C P Q -> InCirc B K -> neq A B ->\n    exists X Y, Col A B X /\\ BetS A B Y /\\ OnCirc X K /\\ OnCirc Y K /\\ BetS X B Y;\n  postulate_circle_circle :\n   forall C D F G J K P Q R S,\n    CI J C R S -> InCirc P J ->\n    OutCirc Q J -> CI K D F G ->\n    OnCirc P K -> OnCirc Q K ->\n    exists X, OnCirc X J /\\ OnCirc X K\n}.\n\n(** Third, we introduce the famous fifth postulate of Euclid,\n    which ensures that the geometry is\n    Euclidean (i.e. not hyperbolic).\n *)\n\nClass euclidean_euclidean `(Ax : euclidean_neutral_ruler_compass) :=\n{\n  postulate_Euclid5 :\n   forall a p q r s t,\n    BetS r t s -> BetS p t q -> BetS r a q ->\n    Cong p t q t -> Cong t r t s -> nCol p q s ->\n    exists X, BetS p a X /\\ BetS s q X\n}.\n\n(** Last, we enrich the axiom system with axioms for equality of areas. *)\n\nClass area `(Ax : euclidean_euclidean) :=\n{\n  EF : Point -> Point -> Point -> Point -> Point -> Point -> Point -> Point -> Prop;\n  ET : Point -> Point -> Point -> Point -> Point -> Point -> Prop;\n  axiom_congruentequal :\n   forall A B C a b c, Cong_3 A B C a b c -> ET A B C a b c;\n  axiom_ETpermutation :\n   forall A B C a b c,\n    ET A B C a b c ->\n    ET A B C b c a /\\\n    ET A B C a c b /\\\n    ET A B C b a c /\\\n    ET A B C c b a /\\\n    ET A B C c a b;\n  axiom_ETsymmetric :\n   forall A B C a b c, ET A B C a b c -> ET a b c A B C;\n  axiom_EFpermutation :\n   forall A B C D a b c d,\n   EF A B C D a b c d ->\n     EF A B C D b c d a /\\\n     EF A B C D d c b a /\\\n     EF A B C D c d a b /\\\n     EF A B C D b a d c /\\\n     EF A B C D d a b c /\\\n     EF A B C D c b a d /\\\n     EF A B C D a d c b;\n  axiom_halvesofequals :\n   forall A B C D a b c d, ET A B C B C D ->\n                           TS A B C D -> ET a b c b c d ->\n                           TS a b c d -> EF A B D C a b d c -> ET A B C a b c;\n  axiom_EFsymmetric :\n   forall A B C D a b c d, EF A B C D a b c d ->\n                           EF a b c d A B C D;\n  axiom_EFtransitive :\n   forall A B C D P Q R S a b c d,\n     EF A B C D a b c d -> EF a b c d P Q R S ->\n     EF A B C D P Q R S;\n  axiom_ETtransitive :\n   forall A B C P Q R a b c,\n    ET A B C a b c -> ET a b c P Q R -> ET A B C P Q R;\n  axiom_cutoff1 :\n   forall A B C D E a b c d e,\n    BetS A B C -> BetS a b c -> BetS E D C -> BetS e d c ->\n    ET B C D b c d -> ET A C E a c e ->\n    EF A B D E a b d e;\n  axiom_cutoff2 :\n   forall A B C D E a b c d e,\n    BetS B C D -> BetS b c d -> ET C D E c d e -> EF A B D E a b d e ->\n    EF A B C E a b c e;\n  axiom_paste1 :\n   forall A B C D E a b c d e,\n    BetS A B C -> BetS a b c -> BetS E D C -> BetS e d c ->\n    ET B C D b c d -> EF A B D E a b d e ->\n    ET A C E a c e;\n  axiom_deZolt1 :\n   forall B C D E, BetS B E D -> ~ ET D B C E B C;\n  axiom_deZolt2 :\n   forall A B C E F,\n    Triangle A B C -> BetS B E A -> BetS B F C ->\n  ~ ET A B C E B F;\n  axiom_paste2 :\n   forall A B C D E M a b c d e m,\n    BetS B C D -> BetS b c d -> ET C D E c d e ->\n    EF A B C E a b c e ->\n    BetS A M D -> BetS B M E ->\n    BetS a m d -> BetS b m e ->\n    EF A B D E a b d e;\n  axiom_paste3 :\n   forall A B C D M a b c d m,\n    ET A B C a b c -> ET A B D a b d ->\n    BetS C M D ->\n    (BetS A M B \\/ eq A M \\/ eq M B) ->\n    BetS c m d ->\n    (BetS a m b \\/ eq a m \\/ eq m b) ->\n    EF A C B D a c b d;\n  axiom_paste4 :\n   forall A B C D F G H J K L M P e m,\n    EF A B m D F K H G -> EF D B e C G H M L ->\n    BetS A P C -> BetS B P D -> BetS K H M -> BetS F G L ->\n    BetS B m D -> BetS B e C -> BetS F J M -> BetS K J L ->\n    EF A B C D F K M L;\n}.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Axioms/euclidean_axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7076970948848282}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (lf2 : natural) (lf1 : natural) : natural :=\n  plus lf1 Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj22_coqofml_nbDV7I.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7076970909750693}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export InteriorsClosures.\n\nDefinition open_neighborhood {X:TopologicalSpace}\n  (U:Ensemble (point_set X)) (x:point_set X) :=\n  open U /\\ In U x.\n\nDefinition neighborhood {X:TopologicalSpace}\n  (N:Ensemble (point_set X)) (x:point_set X) :=\n  exists U:Ensemble (point_set X),\n    open_neighborhood U x /\\ Included U N.\n\nLemma open_neighborhood_is_neighborhood: forall {X:TopologicalSpace}\n  (U:Ensemble (point_set X)) (x:point_set X),\n  open_neighborhood U x -> neighborhood U x.\nProof.\nintros.\nexists U; auto with sets.\nQed.\n\nLemma neighborhood_interior: forall {X:TopologicalSpace}\n  (N:Ensemble (point_set X)) (x:point_set X),\n  neighborhood N x -> In (interior N) x.\nProof.\nintros.\ndestruct H.\ndestruct H.\ndestruct H.\nassert (Included x0 (interior N)).\napply interior_maximal; trivial.\nauto with sets.\nQed.\n\nLemma interior_neighborhood: forall {X:TopologicalSpace}\n  (N:Ensemble (point_set X)) (x:point_set X),\n  In (interior N) x -> neighborhood N x.\nProof.\nintros.\nexists (interior N).\nrepeat split.\napply interior_open.\nassumption.\napply interior_deflationary.\nQed.\n", "meta": {"author": "dschepler", "repo": "coq-topology", "sha": "462b0777da71e8b860fcd67879278e919b295266", "save_path": "github-repos/coq/dschepler-coq-topology", "path": "github-repos/coq/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/Neighborhoods.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7076970863348958}}
{"text": "(* include libraries and notations *)\nRequire Import Arith Lia List String.\nImport ListNotations.\nOpen Scope string.\n\nSet Implicit Arguments.\n\nDefinition eq_dec (A : Type) :=\n  forall (x : A),\n    forall (y : A),\n      {x = y} + {x <> y}.\n\nNotation var := string.\nDefinition var_eq : eq_dec var := string_dec.\n\nDefinition valuation := list (var * nat).\n\nFixpoint lookup (x : var) (v : valuation) : option nat :=\n  match v with\n  | [] => None\n  | (y, n) :: v' =>\n    if var_eq x y\n    then Some n\n    else lookup x v'\n  end.\n\nInductive arith : Set :=\n| Const (n : nat)\n| Var (x : var)\n| Plus (e1 e2 : arith)\n| Minus (e1 e2 : arith)\n| Times (e1 e2 : arith).\n\nFixpoint eval_arith (e : arith) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x =>\n    match lookup x v with\n    | None => 0\n    | Some n => n\n    end\n  | Plus  e1 e2 => eval_arith e1 v + eval_arith e2 v\n  | Minus e1 e2 => eval_arith e1 v - eval_arith e2 v\n  | Times e1 e2 => eval_arith e1 v * eval_arith e2 v\n  end.\n\nDeclare Scope arith_scope.\nCoercion Const : nat >-> arith.\nCoercion Var : var >-> arith.\nInfix \"+\" := Plus : arith_scope.\nInfix \"-\" := Minus : arith_scope.\nInfix \"*\" := Times : arith_scope.\nDelimit Scope arith_scope with arith.\nBind Scope arith_scope with arith.\n\n(*\nIf you could use a refresher on any of these definitions, please check out\nthe code from Week04 where they're discussed in detail:\n    https://gitlab.cs.washington.edu/cse505-23wi/cse505-23wi/-/blob/main/week04/Week04.v\n*)\n\n(* Copied from Week04.v *)\nInductive trc {A} (R : A -> A -> Prop) : A -> A -> Prop :=\n| trc_refl :\n    forall x,\n      trc R x x\n| trc_front :\n    forall x y z,\n      R x y ->\n      trc R y z ->\n      trc R x z.\n\nRecord trsys state :=\n  { Init : state -> Prop\n  ; Step : state -> state -> Prop }.\n\nDefinition is_invariant {state} (sys : trsys state) (P : state -> Prop) :=\n  forall s0,\n    sys.(Init) s0 ->\n    forall sN,\n      trc sys.(Step) s0 sN ->\n      P sN.\n\nDefinition initially_holds {state} (sys : trsys state) (P : state -> Prop) :=\n  forall s,\n    sys.(Init) s ->\n    P s.\n\nDefinition closed_under_step {state} (sys : trsys state) (P : state -> Prop) :=\n  forall s1,\n    P s1 ->\n    forall s2,\n      sys.(Step) s1 s2 ->\n      P s2.\n\nLemma closed_under_step_trc :\n  forall {state} (sys : trsys state) (P : state -> Prop) s0 sN,\n    trc sys.(Step) s0 sN ->\n    closed_under_step sys P ->\n    P s0 ->\n    P sN.\nProof.\n  unfold closed_under_step.\n  intros state sys P s0 sN Htrc.\n  induction Htrc; intros Hclosed HP0.\n  - assumption.\n  - apply IHHtrc; auto.\n    eapply Hclosed; eauto.\nQed.\n\nTheorem invariant_induction :\n  forall {state} (sys : trsys state) (P : state -> Prop),\n    initially_holds sys P ->\n    closed_under_step sys P ->\n    is_invariant sys P.\nProof.\n  unfold is_invariant. intros.\n  eapply closed_under_step_trc; eauto.\nQed.\n\nLemma invariant_implies :\n  forall {state} (sys : trsys state) (P Q : state -> Prop),\n    is_invariant sys P ->\n    (forall s, P s -> Q s) ->\n    is_invariant sys Q.\nProof.\n  unfold is_invariant.\n  eauto.\nQed.\n\nLtac unfold_predicate P :=\n  match P with\n  | ?head _ => unfold_predicate head\n  | _ => try unfold P\n  end.\n\nLtac invariant_induction_boilerplate :=\n  intros;\n  apply invariant_induction; [\n    unfold initially_holds; simpl;\n    match goal with\n    | [ |- forall _, ?P _ -> ?Q _ ] =>\n      unfold_predicate P;\n      unfold_predicate Q;\n      intros s Hinit;\n      try subst\n    end\n  |\n    unfold closed_under_step; simpl;\n    match goal with\n    | [ |- forall _, ?P _ -> forall _, ?Q _ _ -> _ ] =>\n      unfold_predicate P;\n      unfold_predicate Q;\n      intros s1 IH s2 Hstep\n    end\n  ].\n(* End of copied stuff *)\n\nModule Imp.\n\n(*\nCREDITS: This formalization also follows the development from Chlipala's\nexcellent FRAP textbook: http://adam.chlipala.net/frap/\n*)\n\n(* Syntax of Imp. *)\nInductive cmd :=\n| Skip\n| Assign (x : var) (e : arith)\n| Sequence (c1 c2 : cmd)\n| If (e : arith) (then_ else_ : cmd) (* new this week (but nothing fundamental) *)\n| While (e : arith) (body : cmd). (* new this week (and fundamentally different!) *)\n\nNotation \"x <- e\" := (Assign x e%arith) (at level 75).\nInfix \";;\" := Sequence (at level 76). (* ;; instead of ; because it interferes\n                                         with record syntax *)\nNotation \"'when' e 'then' then_ 'else' else_ 'done'\" :=\n  (If e%arith then_ else_) (at level 75, e at level 0).\nNotation \"'while' e 'loop' body 'done'\" :=\n  (While e%arith body) (at level 75).\n\n(* Translate our long horizontal lines to an inductive definition. *)\nInductive step : valuation * cmd -> valuation * cmd -> Prop :=\n| StepAssign :\n    forall v x e v',\n      v' = (x, eval_arith e v) :: v ->\n      (* --------------------------- *)\n      step (v, Assign x e) (v', Skip)\n| StepSeqLStep :\n    forall v c1 c2 v' c1',\n      step (v, c1) (v', c1') ->\n      step (v, Sequence c1 c2) (v', Sequence c1' c2)\n| StepSeqLDone :\n    forall v c2,\n      step (v, Sequence Skip c2) (v, c2)\n| StepIfTrue :\n    forall v e then_ else_,\n      eval_arith e v <> 0 ->\n      step (v, If e then_ else_) (v, then_)\n| StepIfFalse :\n    forall v e then_ else_,\n      eval_arith e v = 0 ->\n      step (v, If e then_ else_) (v, else_)\n| StepWhileTrue :\n    forall v e body,\n      eval_arith e v <> 0 ->\n      (* -------------- *)\n      step (v, While e body) (v, Sequence body (While e body))\n| StepWhileFalse :\n    forall v e body,\n      eval_arith e v = 0 ->\n      step (v, While e body) (v, Skip).\n\nDefinition counter :=\n  \"x\" <- 5;;\n  while 1 loop\n    \"x\" <- \"x\" + 1\n  done.\n\nExample counter_steps_10_times :\n  exists v,\n    trc step ([], counter) (v, while 1 loop\n                                  \"x\" <- \"x\" + 1\n                               done) /\\\n    lookup \"x\" v = Some 15.\nProof.\nAdmitted.\n\n(* Here's our old friend the factorial program. *)\nDefinition factorial : cmd :=\n  \"n\" <- \"input\";;\n  \"acc\" <- 1;;\n  while \"n\" loop\n    \"acc\" <- \"acc\" * \"n\";;\n    \"n\" <- \"n\" - 1\n  done;;\n  \"output\" <- \"acc\".\n\nPrint factorial.\n\nExample factorial_4 :\n  forall v1,\n    lookup \"input\" v1 = Some 4 ->\n    exists v2,\n      trc step (v1, factorial) (v2, Skip) /\\\n      lookup \"output\" v2 = Some 24.\nProof.\n  intros v1 Hv1.\n  eexists.\n  split.\n  - unfold factorial.\n\n    Print trc.\n    eapply trc_front.\n    eapply StepSeqLStep.\n    eapply StepSeqLStep.\n    eapply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n\n    eapply trc_front.\n    eapply StepSeqLStep.\n    eapply StepSeqLStep.\n    apply StepSeqLDone.\n\nRestart.\n\n\n\n  intros v1 H.\n  eexists.\n  split.\n  - eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    (* Now we are left with a Skip out front of our Seq. Get rid of it. *)\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    (* Time for the next assignment statement... *)\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    (* Now we're at the top of the loop. *)\n    cbn. rewrite H.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepWhileTrue. (* Try to enter the loop. *)\n    cbn. lia. (* Prove that we actually do enter the loop. *)\n    (* Now execute the body of the loop. *)\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    (* We're back at the top of the loop. Time for the next iteration. *)\n    cbn.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepWhileTrue.\n    cbn. lia.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    (* next iteration *)\n    cbn.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepWhileTrue.\n    cbn. lia.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    (* next iteration *)\n    cbn.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepWhileTrue.\n    cbn. lia.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLStep.\n    apply StepAssign.\n    reflexivity.\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepSeqLDone.\n    cbn.\n    (* Finally n is 0. Try to exit the loop. *)\n    eapply trc_front.\n    apply StepSeqLStep.\n    apply StepWhileFalse.\n    cbn. lia. (* Prove we actually do exit the loop. *)\n    (* Just a few more steps left after the loop. *)\n    eapply trc_front.\n    apply StepSeqLDone.\n    eapply trc_front.\n    apply StepAssign.\n    reflexivity.\n    cbn.\n    (* Finally, we end the proof of trc using trc_refl. If you look carefully at\n       the goal here, you can \"see\" the actual v2 that gets plugged in for our\n       placeholder. Yikes! *)\n    apply trc_refl.\n  - (* All that's left is to show *)\n    cbn.\n    reflexivity.\nQed. (* Nailed it, only 130 ish tactics. Lots of copy paste! *)\n\n(* like econstructor, but avoid StepWhileTrue b/c infinite tactic loops *)\nLtac step_easy :=\n  repeat (\n    apply StepSeqLDone ||\n    eapply StepSeqLStep ||\n    (apply StepWhileFalse; cbn; reflexivity) ||\n    (apply StepAssign; reflexivity)\n  ); cbn.\n\n\nExample factorial_4_again :\n  forall v1,\n    lookup \"input\" v1 = Some 4 ->\n    exists v2,\n      trc step (v1, factorial) (v2, Skip) /\\\n      lookup \"output\" v2 = Some 24.\nProof.\n  intros v1 H.\n  eexists.\n  split.\n  - econstructor.\n    step_easy.\n    cbn. rewrite H.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    apply StepWhileTrue.\n    cbn. lia.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    apply StepWhileTrue.\n    cbn. lia.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    apply StepWhileTrue.\n    cbn. lia.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    apply StepWhileTrue.\n    cbn. lia.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    econstructor.\n    step_easy.\n    cbn.\n    econstructor.\n  - reflexivity. (* ok that only took half as many tactics *)\n  Restart.\n  (* We can do even better with more tactics. *)\n  Ltac trc_easy :=\n    eapply trc_front; [solve [step_easy]|]; cbn.\n\n  Ltac trc_enter_loop :=\n    eapply trc_front; [step_easy; apply StepWhileTrue; cbn; try lia|]; cbn.\n\n  intros v1 H.\n  eexists.\n  split.\n  - trc_easy. rewrite H.\n    repeat trc_easy. (* Executes as many assignments/skips as possible. *)\n    trc_enter_loop.\n    repeat trc_easy.\n    trc_enter_loop.\n    repeat trc_easy.\n    trc_enter_loop.\n    repeat trc_easy.\n    trc_enter_loop.\n    repeat trc_easy.\n    (* exited the loop *)\n    apply trc_refl.\n  - reflexivity.\nQed.\n\nDefinition cmd_init (v : valuation) (c : cmd) (s : valuation * cmd) : Prop :=\n  s = (v, c).\n\nDefinition cmd_to_trsys (v : valuation) (c : cmd) : trsys (valuation * cmd) :=\n  {| Init := cmd_init v c\n   ; Step := step\n   |}.\n\n\nDefinition counter_sys : trsys (valuation * cmd) :=\n  cmd_to_trsys [] counter.\n\nDefinition counter_ge_5_attempt (s : valuation * cmd) :=\n  let (v, c) := s in\n  exists x,\n    lookup \"x\" v = Some x /\\\n    x >= 5.\n\nTheorem counter_ge_5_attempt_invariant :\n  is_invariant counter_sys counter_ge_5_attempt.\nProof.\n  invariant_induction_boilerplate.\n  (* Uh oh, this just isn't true initially! x is not mapped to anything yet. *)\nAbort.\n\nDefinition counter_ge_5 (s : valuation * cmd) :=\n  let (v, c) := s in\n  c = counter \\/\n  exists x,\n    lookup \"x\" v = Some x /\\\n    x >= 5.\n\nTheorem counter_ge_5_invariant :\n  is_invariant counter_sys counter_ge_5.\nProof.\n  invariant_induction_boilerplate.\n  - auto.\n  - destruct s1 as [v1 c1], s2 as [v2 c2].\n    destruct IH as [IH|IH].\n    + subst. unfold counter in *.\n      inversion Hstep; subst; clear Hstep.\n      inversion H0; subst; clear H0.\n      cbn. eauto.\n    +\nAbort.\n\n(*\n\nDefinition counter :=\n  \"x\" <- 5;;\n  while 1 loop\n    \"x\" <- \"x\" + 1\n  done.\n\n  Skip;;\n  while 1 loop\n    \"x\" <- \"x\" + 1\n  done.  \n\n  while 1 loop\n    \"x\" <- \"x\" + 1\n  done. \n\n  \"x\" <- \"x\" + 1;;\n  while 1 loop\n    \"x\" <- \"x\" + 1\n  done.\n *)\n\n\n\n\n\n\nDefinition counter_programs (s : valuation * cmd) :=\n  let (v, c) := s in\n  c = counter \\/\n  c = (Skip;;\n       while 1 loop\n         \"x\" <- \"x\" + 1\n       done) \\/\n  c = (while 1 loop\n         \"x\" <- \"x\" + 1\n       done) \\/\n  c = (\"x\" <- \"x\" + 1;;\n       while 1 loop\n         \"x\" <- \"x\" + 1\n       done) \\/\n  c = Skip.\n\nTheorem counter_programs_invariant :\n  is_invariant counter_sys counter_programs.\nProof.\n  invariant_induction_boilerplate.\n  - auto.\n  - destruct s1 as [v1 c1], s2 as [v2 c2].\n    intuition; subst; inversion Hstep; subst; clear Hstep; auto.\n    + inversion H0; subst; clear H0. auto.\n    + inversion H0; subst; clear H0.\n    + inversion H0; subst; clear H0. auto.\nQed.\n\nDefinition counter_valuation_x_ge_5 (v : valuation) :=\n  exists x,\n    lookup \"x\" v = Some x /\\\n    x >= 5.\n\nDefinition counter_programs_x_ge_5 (s : valuation * cmd) :=\n  let (v, c) := s in\n  c = counter \\/\n  (c = (Skip;;\n        while 1 loop\n          \"x\" <- \"x\" + 1\n        done) /\\ counter_valuation_x_ge_5 v) \\/\n  (c = (while 1 loop\n          \"x\" <- \"x\" + 1\n        done) /\\ counter_valuation_x_ge_5 v) \\/\n  (c = (\"x\" <- \"x\" + 1;;\n        while 1 loop\n          \"x\" <- \"x\" + 1\n        done) /\\ counter_valuation_x_ge_5 v).\n\n\nLemma counter_programs_x_ge_5_invariant :\n  is_invariant counter_sys counter_programs_x_ge_5.\nProof.\n  invariant_induction_boilerplate.\n  - auto.\n  - destruct s1 as [v1 c1], s2 as [v2 c2].\n    unfold counter_valuation_x_ge_5 in *.\n    intuition; subst; inversion Hstep; subst; clear Hstep; auto.\n    + inversion H0; subst; clear H0. cbn. eauto 10.\n    + inversion H0; subst; clear H0.\n    + simpl in *. discriminate.\n    + inversion H0; subst; clear H0.\n    destruct H1 as [x [Hlook Hx]]. cbn. rewrite Hlook. right. left.\n    split; auto. eexists. split; auto. lia.\n\nQed.\n\nTheorem counter_ge_5_invariant :\n  is_invariant counter_sys counter_ge_5.\nProof.\n  apply invariant_implies with (P := counter_programs_x_ge_5).\n  - apply counter_programs_x_ge_5_invariant.\n  - unfold counter_programs_x_ge_5, counter_ge_5.\n    intros [v c] Hinv.\n    intuition.\nQed.\n\nDefinition factorial_sys (input : nat) : trsys (valuation * cmd) :=\n  cmd_to_trsys [(\"input\", input)] factorial.\n\nFixpoint fact (n : nat) : nat :=\n  match n with\n  | O => 1\n  | S n' => fact n' * S n'\n  end.\n\nDefinition factorial_safe (input : nat) (s : valuation * cmd) : Prop :=\n  let (v, c) := s in\n  c = Skip ->\n  lookup \"output\" v = Some (fact input).\n\nTheorem factorial_safe_invariant :\n  forall input,\n    is_invariant (factorial_sys input) (factorial_safe input).\nProof.\nAbort.\n\nDefinition factorial_after_step_one :=\n  Skip;;\n  \"acc\" <- 1;;\n  while \"n\" loop\n    \"acc\" <- \"acc\" * \"n\";;\n    \"n\" <- \"n\" - 1\n  done;;\n  \"output\" <- \"acc\".\n\nDefinition factorial_after_step_two :=\n  \"acc\" <- 1;;\n  while \"n\" loop\n    \"acc\" <- \"acc\" * \"n\";;\n    \"n\" <- \"n\" - 1\n  done;;\n  \"output\" <- \"acc\".\n\nDefinition factorial_after_step_three :=\n  Skip;;\n  while \"n\" loop\n    \"acc\" <- \"acc\" * \"n\";;\n    \"n\" <- \"n\" - 1\n  done;;\n  \"output\" <- \"acc\".\n\nDefinition factorial_top_of_loop :=\n  while \"n\" loop\n    \"acc\" <- \"acc\" * \"n\";;\n    \"n\" <- \"n\" - 1\n  done;;\n  \"output\" <- \"acc\".\n\nDefinition factorial_body_start :=\n  \"acc\" <- \"acc\" * \"n\";;\n  \"n\" <- \"n\" - 1;;\n  while \"n\" loop\n    \"acc\" <- \"acc\" * \"n\";;\n    \"n\" <- \"n\" - 1\n  done;;\n  \"output\" <- \"acc\".\n\nDefinition factorial_body_after_step_one :=\n  Skip;;\n  \"n\" <- \"n\" - 1;;\n  while \"n\" loop\n    \"acc\" <- \"acc\" * \"n\";;\n    \"n\" <- \"n\" - 1\n  done;;\n  \"output\" <- \"acc\".\n\nDefinition factorial_body_after_step_two :=\n  \"n\" <- \"n\" - 1;;\n  while \"n\" loop\n    \"acc\" <- \"acc\" * \"n\";;\n    \"n\" <- \"n\" - 1\n  done;;\n  \"output\" <- \"acc\".\n\nDefinition factorial_after_loop :=\n  Skip;;\n  \"output\" <- \"acc\".\n\nDefinition factorial_last_step :=\n  \"output\" <- \"acc\".\n\nDefinition factorial_loop_invariant input v :=\n  exists n acc,\n    lookup \"n\" v = Some n /\\\n    lookup \"acc\" v = Some acc /\\\n    fact n * acc = fact input.\n\nDefinition factorial_body_invariant input v :=\n  exists n acc,\n    lookup \"n\" v = Some (S n) /\\\n    lookup \"acc\" v = Some acc /\\\n    fact (S n) * acc = fact input.\n\nDefinition factorial_body_invariant_after_step input v :=\n  exists n acc,\n    lookup \"n\" v = Some (S n) /\\\n    lookup \"acc\" v = Some acc /\\\n    fact n * acc = fact input.\n\nDefinition factorial_inv (input : nat) (s : valuation * cmd) : Prop :=\n  let (v, c) := s in\n  (c = factorial /\\ lookup \"input\" v = Some input) \\/\n  (c = factorial_after_step_one /\\ lookup \"n\" v = Some input) \\/\n  (c = factorial_after_step_two /\\ lookup \"n\" v = Some input) \\/\n  (c = factorial_after_step_three /\\ factorial_loop_invariant input v) \\/\n  (c = factorial_top_of_loop /\\ factorial_loop_invariant input v) \\/\n  (c = factorial_body_start /\\ factorial_body_invariant input v) \\/\n  (c = factorial_body_after_step_one /\\ factorial_body_invariant_after_step input v) \\/\n  (c = factorial_body_after_step_two /\\ factorial_body_invariant_after_step input v) \\/\n  (c = factorial_after_loop /\\ lookup \"acc\" v = Some (fact input)) \\/\n  (c = factorial_last_step /\\ lookup \"acc\" v = Some (fact input)) \\/\n  (c = Skip /\\ lookup \"output\" v = Some (fact input)).\n\nLtac invc H := inversion H; subst; clear H.\n\nLemma factorial_inv_invariant :\n  forall input,\n    is_invariant (factorial_sys input) (factorial_inv input).\nProof.\n  invariant_induction_boilerplate.\n  - auto.\n  - unfold factorial_loop_invariant, factorial_body_invariant.\n    unfold factorial_body_invariant_after_step.\n    destruct s1 as [v1 c1], s2 as [v2 c2].\n    intuition idtac; subst.\n    + invc Hstep. invc H0. invc H2. invc H0.\n      cbn [eval_arith].\n      rewrite H1.\n      auto.\n    + invc Hstep. invc H0. invc H2. invc H0. auto.\n    + invc Hstep. invc H0. invc H2.\n      right. right. right. left. split; [reflexivity|].\n      exists input, 1.\n      cbn. split; auto. split; auto. lia.\n    + destruct H1 as [n [acc [? []]]].\n      invc Hstep. invc H3. invc H4.\n      eauto 20.\n    + destruct H1 as [n [acc [? []]]].\n      invc Hstep. invc H3.\n      -- right. right. right. right. right. left. split; [reflexivity|].\n         cbn in *. rewrite H in *.\n         destruct n; [congruence|]. (* note: destruct before exists *)\n         eauto.\n      -- right. right. right. right. right. right. right. right. left. split; [reflexivity|].\n         cbn in *. rewrite H in *. subst n.\n         cbn in *. rewrite H0, <- H1. f_equal. lia.\n    + destruct H1 as [n [acc [? []]]].\n      invc Hstep. invc H3. invc H4. invc H3.\n      right. right. right. right. right. right. left. split; [reflexivity|].\n      cbn. rewrite H, H0. eexists. eexists. split; eauto. split; eauto.\n      rewrite <- H1. cbn. lia.\n    + destruct H1 as [n [acc [? []]]].\n      invc Hstep. invc H3. invc H4. invc H3.\n      eauto 15.\n    + destruct H1 as [n [acc [? []]]].\n      invc Hstep. invc H3. invc H4.\n      right. right. right. left. split; [reflexivity|].\n      cbn. rewrite H. cbn. rewrite Nat.sub_0_r. eauto.\n    + invc Hstep. invc H1. invc H0.\n      auto 20.\n    + invc Hstep.\n      right. right. right. right. right. right. right. right. right. right.\n      split; auto.\n      cbn. rewrite H1. auto.\n    + invc Hstep.\nQed.\n\nLtac invert_one_step :=\n  match goal with\n  | [ H : step _ _ |- _ ] => invc H\n  end.\n\nLtac invert_steps :=\n  repeat invert_one_step.\n\nLtac magic_select_case :=\n  repeat match goal with\n  | [ |- _ \\/ _ ] => (left; split; [reflexivity|]) || right\n  | _ => try split; [reflexivity|]\n  end.\n\nLtac break_up_hyps :=\n  repeat match goal with\n  | [ H : exists _, _ |- _ ] => destruct H\n  | [ H : _ /\\ _ |- _ ] => destruct H\n  end.\n\nLtac find_rewrites :=\n  repeat match goal with\n  | [ H : _ = _ |- _ ] => rewrite H in *\n  end.\n\nLemma factorial_inv_invariant_again :\n  forall input,\n    is_invariant (factorial_sys input) (factorial_inv input).\nProof.\n  invariant_induction_boilerplate.\n  - auto.\n  - destruct s1 as [v1 c1], s2 as [v2 c2].\n    fold (factorial_inv input (v2, c2)).\n    intuition; subst; invert_steps;\n    unfold factorial_inv;\n    unfold factorial_loop_invariant, factorial_body_invariant in *;\n    unfold factorial_body_invariant_after_step in *;\n    magic_select_case;\n    break_up_hyps;\n    cbn in *;\n    find_rewrites;\n    eauto 20.\n    + eexists. eexists.\n      split; eauto. split; eauto. lia.\n    + destruct x; [congruence|]. (* note: destruct before exists *)\n      eauto.\n    + subst.\n      cbn in *. rewrite <- H1. f_equal. lia.\n    + eexists. eexists. split; eauto. split; eauto.\n      rewrite <- H1. cbn. lia.\n    + eexists. eexists. split; eauto. split; eauto.\n      cbn. rewrite <- H1. f_equal. f_equal. lia.\nQed.\n\nTheorem factorial_safe_invariant :\n  forall input,\n    is_invariant (factorial_sys input) (factorial_safe input).\nProof.\n  intros input.\n  apply invariant_implies with (P := factorial_inv input).\n  - apply factorial_inv_invariant.\n  - unfold factorial_inv, factorial_safe.\n    intros [v c] Hinv Hfinal.\n    subst.\n    intuition; discriminate.\nQed.\n\nLemma decompose_sequence_execution :\n  forall v v' c1 c2 c',\n    trc step (v, c1;; c2) (v', c') ->\n    exists v1' c1',\n      trc step (v, c1) (v1', c1') /\\\n      (c' = (c1';; c2) \\/\n        (c1' = Skip /\\ trc step (v1', c2) (v', c'))).\nProof.\n  intros v v' c1 c2 c' Hstep.\n  induction Hstep.\n  - (* wait... what is x??? *)\n  Restart.\n  intros v v' c1 c2 c' Hstep.\n  remember (v, c1;;c2) as s.\n  remember (v', c') as s'.\n  revert v c1 c2 v' c' Heqs Heqs'.\n  induction Hstep; intros v c1 c2 v' c' ? ?; subst.\n  - invc Heqs'. eexists. eexists. split. constructor. auto.\n  - invc H.\n    + specialize (IHHstep v'0 c1' c2 v' c' eq_refl eq_refl).\n      destruct IHHstep as [v1' [c1'0 [Hstep' Hc']]].\n      eexists. eexists.\n      split. eapply trc_front; eauto.\n      intuition.\n    + eexists. eexists. split. apply trc_refl.\n      auto.\nQed.\n\nLemma trc_seq_l_trc :\n  forall v1 c1 v2 c2 c3,\n    trc step (v1, c1) (v2, c2) ->\n    trc step (v1, c1;;c3) (v2, c2;;c3).\nProof.\n  intros v1 c1 v2 c2 c3 Hstep.\n  remember (v1, c1) as s1.\n  remember (v2, c2) as s2.\n  revert v1 c1 v2 c2 c3 Heqs1 Heqs2.\n  induction Hstep; intros v1 c1 v2 c2 c3 ? ?; subst.\n  - invc Heqs2. econstructor.\n  - destruct y as [v1' c1'].\n    specialize (IHHstep v1' c1' v2 c2 c3 eq_refl eq_refl).\n    eapply trc_front. apply StepSeqLStep. eauto. eauto.\nQed.\n\nInductive trc_backward {A} (R : A -> A -> Prop) : A -> A -> Prop :=\n| trcb_refl :\n    forall x,\n      trc_backward R x x\n| trcb_back :\n    forall x y z,\n      trc_backward R x y ->\n      R y z ->\n      trc_backward R x z.\n\nLemma trc_back :\n  forall {A} (R : A -> A -> Prop) x y,\n    trc R x y ->\n    forall z,\n      R y z ->\n      trc R x z.\nProof.\n  (* On HW3 *)\nAdmitted.\n\nLemma trcb_front :\n  forall {A} (R : A -> A -> Prop) y z,\n    trc_backward R y z ->\n    forall x,\n      R x y ->\n      trc_backward R x z.\nProof.\n  (* Very similar to previous lemma. *)\nAdmitted.\n\nLemma trc_implies_trc_backward :\n  forall A (R : A -> A -> Prop) x y,\n    trc R x y ->\n    trc_backward R x y.\nProof.\n  intros A R x y Htrc.\n  induction Htrc.\n  - constructor.\n  - eapply trcb_front; eauto.\nQed.\n\nLemma trc_backward_implies_trc :\n  forall A (R : A -> A -> Prop) x y,\n    trc_backward R x y ->\n    trc R x y.\nProof.\n  intros A R x y Htrcb.\n  induction Htrcb.\n  - constructor.\n  - eapply trc_back; eauto.\nQed.\n\n\nLemma trc_reverse_ind :\n  forall A (R : A -> A -> Prop) (P : A -> A -> Prop),\n    (forall x, P x x) ->\n    (forall x y z, trc R x y -> R y z -> P x y -> P x z) ->\n    forall x y,\n      trc R x y ->\n      P x y.\nProof.\n  intros A R P Hbase Hind x y H.\n  apply trc_implies_trc_backward in H.\n  induction H.\n  - apply Hbase.\n  - eapply Hind; eauto.\n    apply trc_backward_implies_trc.\n    auto.\nQed.\n\nDefinition loop_runs_to (e : arith) (c : cmd) (v1 v2 : valuation) :=\n  eval_arith e v1 <> 0 /\\\n  trc step (v1, c) (v2, Skip).\n\nLtac prepare_induct_step H :=\n  match type of H with\n  | step (?v, ?c) (?v', ?c') =>\n    let s := fresh \"s\" in\n    let Heqs := fresh \"Heqs\" in\n    let s' := fresh \"s'\" in\n    let Heqs' := fresh \"Heqs'\" in\n    remember (v, c) as s eqn:Heqs;\n    remember (v', c') as s' eqn:Heqs';\n    revert Heqs Heqs';\n    try revert c';\n    try revert v';\n    try revert c;\n    try revert v\n  end.\n\nLtac induct_step H :=\n  prepare_induct_step H;\n  induction H; intros; subst.\n\nLtac prepare_induct_trc_step H :=\n  match type of H with\n  | trc step (?v, ?c) (?v', ?c') =>\n    let s := fresh \"s\" in\n    let Heqs := fresh \"Heqs\" in\n    let s' := fresh \"s'\" in\n    let Heqs' := fresh \"Heqs'\" in\n    remember (v, c) as s eqn:Heqs;\n    remember (v', c') as s' eqn:Heqs';\n    revert Heqs Heqs';\n    try revert c';\n    try revert v';\n    try revert c;\n    try revert v\n  end.\n\nLtac induct_trc_step H :=\n  prepare_induct_trc_step H;\n  induction H; intros; subst.\n\nLemma decompose_while_execution :\n  forall v v' e c c',\n    trc step (v, while e loop c done) (v', c') ->\n    exists v1,\n      trc (loop_runs_to e c) v v1 /\\\n      ((c' = Skip /\\ v' = v1 /\\ eval_arith e v' = 0) \\/\n       (c' = (while e loop c done) /\\ v' = v1) \\/\n       (eval_arith e v1 <> 0 /\\ exists c1', trc step (v1, c) (v', c1') /\\ c' = (c1' ;; while e loop c done))).\nProof.\n  intros v v' e c c' Htrc.\n  prepare_induct_trc_step Htrc.\n  revert e c.\n  induction Htrc using trc_reverse_ind; intros v e c v' c' ? ?; subst.\n  - invc Heqs'. (* eexists. split.\n    + apply trc_refl.\n    + auto.  *)\n    eauto 10 using trc_refl.\n  - destruct y as [v2 c2].\n    specialize (IHHtrc v e c v2 c2 eq_refl eq_refl).\n    destruct IHHtrc as [v1 [Htrc1 IH]].\n    destruct IH as [[? [? He]]|[[? ?]|[He [c1' [Hc ?]]]]]; subst.\n    + invc H.\n    + invc H.\n      * eexists. split; eauto.\n        right. right. split; auto.\n        eexists. split; eauto. constructor.\n      * eauto 10.\n    + invc H.\n      * eexists. split; eauto.\n        right. right. split; auto.\n        eexists. split; [|reflexivity].\n        eapply trc_back; eauto.\n      * exists v'. split.\n        -- eapply trc_back; eauto. split; auto.\n        -- auto.\nQed.\n\n\nFixpoint strength_reduction (e : arith) : arith :=\n  match e with\n  | Const _ => e\n  | Var _ => e\n  | Plus e1 e2 => Plus (strength_reduction e1) (strength_reduction e2)\n  | Minus e1 e2 => Minus (strength_reduction e1) (strength_reduction e2)\n  | Times (Const 2) e2 =>\n    let e2' := strength_reduction e2 in\n    Plus e2' e2'\n  | Times e1 e2 => Times (strength_reduction e1) (strength_reduction e2)\n  end.\n\nFixpoint cmd_xform_arith (f : arith -> arith) (c : cmd) : cmd :=\n  match c with\n  | Skip => Skip\n  | Assign x e => Assign x (f e)\n  | Sequence c1 c2 => Sequence (cmd_xform_arith f c1) (cmd_xform_arith f c2)\n  | If e c1 c2 => If (f e) (cmd_xform_arith f c1) (cmd_xform_arith f c2)\n  | While e c => While (f e) (cmd_xform_arith f c)\n  end.\n\nLemma cmd_xform_arith_equiv_step :\n  forall f,\n    (forall e v, eval_arith (f e) v = eval_arith e v) ->\n    forall v c v' c',\n      step (v, c) (v', c') ->\n      step (v, cmd_xform_arith f c) (v', cmd_xform_arith f c').\nProof.\n  intros f Hf v c v' c' Hstep.\n  induct_step Hstep; invc Heqs; invc Heqs'; simpl; constructor;\n   try rewrite Hf; auto.\nQed.\n\nTheorem cmd_xform_arith_equiv :\n  forall f,\n    (forall e v, eval_arith e v = eval_arith (f e) v) ->\n    forall v c v' c',\n      trc step (v, c) (v', c') ->\n      trc step (v, cmd_xform_arith f c) (v', cmd_xform_arith f c').\nProof.\n  intros f Hf v c v' c' Htrc.\n  induct_trc_step Htrc.\n  - invc Heqs'. constructor.\n  - destruct y as [v1 c1].\n    eapply cmd_xform_arith_equiv_step in H; eauto.\n    econstructor; eauto.\nQed.\n\nEnd Imp.\n", "meta": {"author": "SharmaAjay19", "repo": "CSEP-505", "sha": "0a27b36dccac1f0308c1860303e6a2f8a61d3c8a", "save_path": "github-repos/coq/SharmaAjay19-CSEP-505", "path": "github-repos/coq/SharmaAjay19-CSEP-505/CSEP-505-0a27b36dccac1f0308c1860303e6a2f8a61d3c8a/TestSamples/W5D1PM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7076947548392395}}
{"text": "Require Import List.\nImport ListNotations.\n\nFrom CoqAlgs Require Export Sorting.Sort.\n\nSet Implicit Arguments.\n\nClass ISArgs : Type :=\n{\n    A : Type;\n    S : Type;\n\n    empty  : S;\n    insert : A -> S -> S;\n\n    toList : S -> list A;\n\n    R : A -> A -> Prop;\n\n    Sorted_toList :\n      forall s : S, Sorted R (toList s);\n\n    countS : (A -> bool) -> S -> nat;\n\n    countS_empty :\n      forall p : A -> bool,\n        countS p empty = 0;\n\n    countS_insert :\n      forall (p : A -> bool) (x : A) (s : S),\n        countS p (insert x s) =\n          (if p x then 1 else 0) + countS p s;\n\n    countS_toList :\n      forall (p : A -> bool) (s : S),\n        countS p s = count p (toList s);\n}.\n\nFixpoint fromList (args : ISArgs) (l : list A) : S :=\nmatch l with\n    | [] => empty\n    | h :: t => insert h (fromList args t)\nend.\n\nDefinition insSort (args : ISArgs) (l : list A) : list A := toList (fromList args l).\n\nLemma countS_fromList :\n  forall (args : ISArgs) (p : A -> bool) (l : list A),\n    countS p (fromList args l) = count p l.\nProof.\n  induction l as [| h t]; cbn.\n    rewrite countS_empty. reflexivity.\n    rewrite countS_insert, IHt. reflexivity.\nQed.\n\nLemma perm_insSort :\n  forall (args : ISArgs) (l : list A),\n    perm (insSort args l) l.\nProof.\n  unfold perm, insSort. intros.\n  rewrite <- countS_toList, <- countS_fromList.\n  reflexivity.\nQed.\n\n", "meta": {"author": "wkolowski", "repo": "coq-algs", "sha": "ee6c656314e3d93e3029dd5f845cfb5352c1b089", "save_path": "github-repos/coq/wkolowski-coq-algs", "path": "github-repos/coq/wkolowski-coq-algs/coq-algs-ee6c656314e3d93e3029dd5f845cfb5352c1b089/Sorting/GeneralizedInsertionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7076947540067134}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import maps.\nRequire Import imp.\nRequire Import rel.\n\nInductive tm : Type :=\n  | C : nat -> tm \n  | P : tm -> tm -> tm.\n\nFixpoint evalF (t : tm) : nat :=\n  match t with\n  | C n => n\n  | P a1 a2 => evalF a1 + evalF a2\n  end.\n\nReserved Notation \" t '\\\\' n \" (at level 50, left associativity).\n\nInductive eval : tm -> nat -> Prop :=\n  | E_Const : forall n,\n      C n \\\\ n\n  | E_Plus : forall t1 t2 n1 n2,\n      t1 \\\\ n1 ->\n      t2 \\\\ n2 ->\n      P t1 t2 \\\\ (n1 + n2)\n\n  where \" t '\\\\' n \" := (eval t n).\n\nModule SimpleArith1.\n\nReserved Notation \" t '==>' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_PlusConstConst : forall n1 n2,\n      P (C n1) (C n2) ==> C (n1 + n2)\n  | ST_Plus1 : forall t1 t1' t2,\n      t1 ==> t1' ->\n      P t1 t2 ==> P t1' t2\n  | ST_Plus2 : forall n1 t2 t2',\n      t2 ==> t2' ->\n      P (C n1) t2 ==> P (C n1) t2'\n\n  where \" t '==>' t' \" := (step t t').\n\nExample test_step_1 :\n      P(P (C 0)(C 3))(P (C 2) (C 4))\n      ==>P(C (0 + 3))(P (C 2) (C 4)).\nProof.\napply ST_Plus1.\napply ST_PlusConstConst.\nQed.\n\nExample test_step_2 :\nP (C 0) (P (C 2) (P (C 0) (C 3)))\n==> P (C 0) (P (C 2) (C (0 + 3))).\nProof.\napply ST_Plus2.\nsimpl.\napply ST_Plus2. \napply ST_PlusConstConst.\nQed.\nEnd SimpleArith1.\n\nDefinition deterministic {X: Type} (R: relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\nModule SimpleArith2.\nImport SimpleArith1.\nTheorem step_deterministic:\ndeterministic step.\nProof.\nunfold deterministic.\nintros x y1 y2 Hy1 Hy2.\ngeneralize dependent y2.\ninduction Hy1. intros y2 Hy2.\nAdmitted.\n\nEnd SimpleArith2.\n\nLtac solve_by_inverts n :=\n  match goal with | H : ?T |- _ => \n  match type of T with Prop =>\n    solve [ \n      inversion H; \n      match n with S (S (?n')) => subst; solve_by_inverts (S n') end ]\n  end end.\n\nLtac solve_by_invert :=\n  solve_by_inverts 1.\n\nModule SimpleArith3.\nImport SimpleArith1.\nTheorem step_deterministic_alt: deterministic step.\nProof.\n  intros x y1 y2 Hy1 Hy2.\n  generalize dependent y2.\n  induction Hy1; intros y2 Hy2;\n    inversion Hy2; subst; try solve_by_invert.\n  - (* ST_PlusConstConst *) reflexivity.\n  - (* ST_Plus1 *)\n    apply IHHy1 in H2. rewrite H2. reflexivity.\n  - (* ST_Plus2 *)\n    apply IHHy1 in H2. rewrite H2. reflexivity.\nQed.\nEnd SimpleArith3.\n\nInductive value : tm -> Prop :=\n  | v_const : forall n, value (C n).\n\nReserved Notation \" t '==>' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_PlusConstConst : forall n1 n2,\n          P (C n1) (C n2)\n      ==> C (n1 + n2)\n  | ST_Plus1 : forall t1 t1' t2,\n        t1 ==> t1' ->\n        P t1 t2 ==> P t1' t2\n  | ST_Plus2 : forall v1 t2 t2',\n        value v1 -> (* <----- n.b. *)\n        t2 ==> t2' ->\n        P v1 t2 ==> P v1 t2'\n\n  where \" t '==>' t' \" := (step t t').\n\nTheorem step_deterministic :\n  deterministic step.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem strong_progress : forall t,\n  value t \\/ (exists t', t ==> t').\nProof.\nintros.\ninduction t.\n- left. apply v_const.\n- right. inversion IHt1.\n  + inversion IHt2. inversion H0.\nAdmitted.\n\nDefinition normal_form {X:Type} (R:relation X) (t:X) : Prop :=\n  ~ exists t', R t t'.\n\nLemma value_is_nf : forall v,\n  value v -> normal_form step v.\nProof.\nunfold normal_form.\nintros.\nunfold not.\ninversion H.\nintros c.\ninversion c.\ninversion H1.\nQed.\n\nLemma nf_is_value : forall t,\n  normal_form step t -> value t.\nProof.\nunfold normal_form.\nintros t H.\nassert ( G: value t \\/ exists t', t==>t').\n{ apply strong_progress. }\ninversion G.\n+ assumption.\n+ exfalso. apply H. assumption.\nQed.\n\nCorollary nf_same_as_value : forall t,\n  normal_form step t <-> value t.\nProof.\nsplit.\napply nf_is_value.\napply value_is_nf.\nQed.\n\n(** some good exercises are left **)\n\nInductive multi {X:Type} (R: relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nNotation \" t '==>*' t' \" := (multi step t t') (at level 40).\n\nTheorem multi_R : forall (X:Type) (R:relation X) (x y : X),\n       R x y -> (multi R) x y.\nProof.\nintros.\napply multi_step with y.\nassumption.\napply multi_refl.\nQed.\n\nTheorem multi_trans :\n  forall (X:Type) (R: relation X) (x y z : X),\n      multi R x y ->\n      multi R y z ->\n      multi R x z.\nProof.\nintros X R x y z H1 H2.\ninduction H1.\nassumption. \napply multi_step with y.\nassumption. apply IHmulti. apply H2.\nQed.\n\nLemma test_multistep_1:\nP(P (C 0) (C 3))(P (C 2) (C 4))==>*C ((0 + 3) + (2 + 4)).\nProof.\napply multi_step with (P (C (0 + 3))\n               (P (C 2) (C 4))).\napply ST_Plus1.\napply ST_PlusConstConst.\napply multi_step with (P (C (0 + 3))\n                (C (2 + 4))).\napply ST_Plus2.\napply v_const.\napply ST_PlusConstConst.\napply multi_step with (C (0 + 3 + (2 + 4))).\napply ST_PlusConstConst.\napply multi_refl.\nQed.\n\nLemma test_multistep_1':\nP(P (C 0) (C 3))(P (C 2) (C 4))\n==>* C ((0 + 3) + (2 + 4)).\nProof.\neapply multi_step.\napply ST_Plus1. apply ST_PlusConstConst.\n  eapply multi_step. apply ST_Plus2. apply v_const.\n  apply ST_PlusConstConst.\n  eapply multi_step. apply ST_PlusConstConst.\n  apply multi_refl. Qed.\n\nLemma test_multistep_2:\n  C 3 ==>* C 3.\nProof.\napply multi_refl.\nQed.\n\nLemma test_multistep_3:\n      P (C 0) (C 3)\n   ==>*\n      P (C 0) (C 3).\nProof.\napply multi_refl.\nQed.\n\nLemma test_multistep_4:\nP(C 0)(P(C 2) (P (C 0) (C 3)))\n  ==>*P(C 0)(C (2 + (0 + 3))).\nProof.\napply multi_step with (P(C 0)(P(C 2)(C (0 + 3)))).\napply ST_Plus2.\napply v_const.\napply ST_Plus2.\napply v_const.\napply ST_PlusConstConst.\napply multi_step with (P(C 0)(C (2 + (0 + 3)))).\napply ST_Plus2.\napply v_const.\napply ST_PlusConstConst.\napply multi_refl.\nQed.\n\nDefinition step_normal_form := normal_form step.\nDefinition normal_form_of (t t' : tm) :=\n  (t ==>* t' /\\ step_normal_form t').\n\nTheorem normal_forms_unique:\n  deterministic normal_form_of.\nProof.\nunfold deterministic.\nunfold normal_form_of.\nintros.\ninversion H as [P1 P2]. clear H.\n- inversion H0 as [P3 P4]. clear H0.\ngeneralize dependent y2.\nAdmitted.\n\nDefinition normalizing {X:Type} (R:relation X) :=\n  forall t, exists t',\n    (multi R) t t' /\\ normal_form R t'.\n\nLemma multistep_congr_1 : forall t1 t1' t2,\n     t1 ==>* t1' ->\n     P t1 t2 ==>* P t1' t2.\nProof.\nintros. induction H .\napply multi_refl.\napply multi_step with (P y t2).\napply ST_Plus1. apply H.\nassumption.\nQed.\n\nLemma multistep_congr_2 : forall t1 t2 t2',\n     value t1 ->\n     t2 ==>* t2' ->\n     P t1 t2 ==>* P t1 t2'.\nProof.\nintros.\ninduction H0.\n- apply multi_refl.\n- apply multi_step with (P t1 y).\napply ST_Plus2.\napply H. apply H0. apply IHmulti.\nQed.\n\nTheorem step_normalizing :\n  normalizing step.\nProof.\nunfold normalizing.\ninduction t.\n- exists (C n).\nsplit. apply multi_refl.  \napply nf_same_as_value. apply v_const.\n- destruct IHt1 as [t1' [H11 H12]].\n  destruct IHt2 as [t2' [H21 H22]].\nrewrite nf_same_as_value in H12.\nrewrite nf_same_as_value in H22.\ninversion H12 as [n1 H]. \ninversion H22 as [n2 H'].\nAdmitted.\n\nTheorem eval__multistep : forall t n,\n  t \\\\ n -> t ==>* C n.\nProof.\nintros.\n  induction H. constructor.\n  eapply multi_trans.\n  assert(P t1 t2 ==>* P (C n1) t2).\n    apply multistep_congr_1; assumption.\n    apply H1.\n  eapply multi_trans.\n    apply multistep_congr_2. constructor.\n    apply IHeval2.\n  econstructor; constructor.\n  Qed.\n\nDefinition manual_grade_for_eval__multistep_inf : option (prod nat string) := None.\n\nLemma step__eval : forall t t' n,\n     t ==> t' ->\n     t' \\\\ n ->\n     t \\\\ n.\nProof.\nintros t t' n Hs. generalize dependent n.\ninduction Hs.\n- intros. inversion H; subst. \nconstructor. constructor. constructor.\n- intros. inversion H; subst. \nconstructor. apply IHHs. assumption.\nassumption.\n- intros. inversion H0; subst.\nconstructor. assumption. apply IHHs.\nassumption.\nQed.\n\nTheorem multistep__eval : forall t t',\n  normal_form_of t t' -> \n  exists n, t' = C n /\\ t \\\\ n.\nProof.\nintros. unfold normal_form_of in H.\ninversion H.\ninduction H0.\n- assert (value x).\n + apply nf_is_value. apply H1.\n + inversion H0.  exists n. split.\nreflexivity. constructor.\n- assert(exists n : nat, z = C n /\\ y \\\\ n).\napply IHmulti. split.\nassumption. assumption. assumption.\ninversion H3 as [n [H6 H7]].\nexists n. split. assumption.\neapply step__eval. apply H0. \napply H7.\nQed.\n\nTheorem evalF_eval : forall t n,\n  evalF t = n <-> t \\\\ n.\nProof.\nintros.\nsplit. generalize dependent n.\n-  induction t.\n + intros. subst. \nconstructor.\n + intros. simpl in H. rewrite <-H.\nconstructor.\n apply IHt1. reflexivity.\napply IHt2. reflexivity.\n- intros. induction H.\nconstructor. simpl.\nsubst. reflexivity.\nQed.\n\nModule Combined.\nInductive tm : Type :=\n  | C : nat -> tm\n  | P : tm -> tm -> tm\n  | ttrue : tm\n  | tfalse : tm\n  | tif : tm -> tm -> tm -> tm.\nInductive value : tm -> Prop :=\n  | v_const : forall n, value (C n)\n  | v_true : value ttrue\n  | v_false : value tfalse.\nReserved Notation \" t '==>' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_PlusConstConst : forall n1 n2,\n      P (C n1) (C n2) ==> C (n1 + n2)\n  | ST_Plus1 : forall t1 t1' t2,\n      t1 ==> t1' ->\n      P t1 t2 ==> P t1' t2\n  | ST_Plus2 : forall v1 t2 t2',\n      value v1 ->\n      t2 ==> t2' ->\n      P v1 t2 ==> P v1 t2'\n  | ST_IfTrue : forall t1 t2,\n      tif ttrue t1 t2 ==> t1\n  | ST_IfFalse : forall t1 t2,\n      tif tfalse t1 t2 ==> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 ==> t1' ->\n      tif t1 t2 t3 ==> tif t1' t2 t3\n\n  where \" t '==>' t' \" := (step t t'). \n\nEnd Combined.\nDefinition manual_grade_for_combined_properties : option (prod nat string) := None.\n\nInductive aval : aexp -> Prop :=\n  | av_num : forall n, aval (ANum n).\n\nReserved Notation \" t '/' st '==>a' t' \"\n                  (at level 40, st at level 39).\nInductive astep : state -> aexp -> aexp -> Prop :=\n  | AS_Id : forall st i,\n      AId i / st ==>a ANum (st i)\n  | AS_Plus : forall st n1 n2,\n      APlus (ANum n1) (ANum n2) / st ==>a ANum (n1 + n2)\n  | AS_Plus1 : forall st a1 a1' a2,\n      a1 / st ==>a a1' ->\n      (APlus a1 a2) / st ==>a (APlus a1' a2)\n  | AS_Plus2 : forall st v1 a2 a2',\n      aval v1 ->\n      a2 / st ==>a a2' ->\n      (APlus v1 a2) / st ==>a (APlus v1 a2')\n  | AS_Minus : forall st n1 n2,\n      (AMinus (ANum n1) (ANum n2)) / st ==>a (ANum (minus n1 n2))\n  | AS_Minus1 : forall st a1 a1' a2,\n      a1 / st ==>a a1' ->\n      (AMinus a1 a2) / st ==>a (AMinus a1' a2)\n  | AS_Minus2 : forall st v1 a2 a2',\n      aval v1 ->\n      a2 / st ==>a a2' ->\n      (AMinus v1 a2) / st ==>a (AMinus v1 a2')\n  | AS_Mult : forall st n1 n2,\n      (AMult (ANum n1) (ANum n2)) / st ==>a (ANum (mult n1 n2))\n  | AS_Mult1 : forall st a1 a1' a2,\n      a1 / st ==>a a1' ->\n      (AMult a1 a2) / st ==>a (AMult a1' a2)\n  | AS_Mult2 : forall st v1 a2 a2',\n      aval v1 ->\n      a2 / st ==>a a2' ->\n      (AMult v1 a2) / st ==>a (AMult v1 a2')\n\n    where \" t '/' st '==>a' t' \" := (astep st t t').\nReserved Notation \" t '/' st '==>b' t' \"\n                  (at level 40, st at level 39).\nInductive bstep : state -> bexp -> bexp -> Prop :=\n| BS_Eq : forall st n1 n2,\n    (BEq (ANum n1) (ANum n2)) / st ==>b\n    (if (beq_nat n1 n2) then BTrue else BFalse)\n| BS_Eq1 : forall st a1 a1' a2,\n    a1 / st ==>a a1' ->\n    (BEq a1 a2) / st ==>b (BEq a1' a2)\n| BS_Eq2 : forall st v1 a2 a2',\n    aval v1 ->\n    a2 / st ==>a a2' ->\n    (BEq v1 a2) / st ==>b (BEq v1 a2')\n| BS_LtEq : forall st n1 n2,\n    (BLe (ANum n1) (ANum n2)) / st ==>b\n             (if (leb n1 n2) then BTrue else BFalse)\n| BS_LtEq1 : forall st a1 a1' a2,\n    a1 / st ==>a a1' ->\n    (BLe a1 a2) / st ==>b (BLe a1' a2)\n| BS_LtEq2 : forall st v1 a2 a2',\n    aval v1 ->\n    a2 / st ==>a a2' ->\n    (BLe v1 a2) / st ==>b (BLe v1 a2')\n| BS_NotTrue : forall st,\n    (BNot BTrue) / st ==>b BFalse\n| BS_NotFalse : forall st,\n    (BNot BFalse) / st ==>b BTrue\n| BS_NotStep : forall st b1 b1',\n    b1 / st ==>b b1' ->\n    (BNot b1) / st ==>b (BNot b1')\n| BS_AndTrueTrue : forall st,\n    (BAnd BTrue BTrue) / st ==>b BTrue\n| BS_AndTrueFalse : forall st,\n    (BAnd BTrue BFalse) / st ==>b BFalse\n| BS_AndFalse : forall st b2,\n    (BAnd BFalse b2) / st ==>b BFalse\n| BS_AndTrueStep : forall st b2 b2',\n    b2 / st ==>b b2' ->\n    (BAnd BTrue b2) / st ==>b (BAnd BTrue b2')\n| BS_AndStep : forall st b1 b1' b2,\n    b1 / st ==>b b1' ->\n    (BAnd b1 b2) / st ==>b (BAnd b1' b2)\n\nwhere \" t '/' st '==>b' t' \" := (bstep st t t').\n\nReserved Notation \" t '/' st '==>' t' '/' st' \"\n                  (at level 40, st at level 39, t' at level 39).\nInductive cstep : (com * state) -> (com * state) -> Prop :=\n  | CS_AssStep : forall st i a a',\n      a / st ==>a a' ->\n      (i ::= a) / st ==> (i ::= a') / st\n  | CS_Ass : forall st i n,\n      (i ::= (ANum n)) / st ==> SKIP / (st & { i --> n })\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      c1 / st ==> c1' / st' ->\n      (c1 ;; c2) / st ==> (c1' ;; c2) / st'\n  | CS_SeqFinish : forall st c2,\n      (SKIP ;; c2) / st ==> c2 / st\n  | CS_IfTrue : forall st c1 c2,\n      IFB BTrue THEN c1 ELSE c2 FI / st ==> c1 / st\n  | CS_IfFalse : forall st c1 c2,\n      IFB BFalse THEN c1 ELSE c2 FI / st ==> c2 / st\n  | CS_IfStep : forall st b b' c1 c2,\n      b / st ==>b b' ->\n          IFB b THEN c1 ELSE c2 FI / st \n      ==> (IFB b' THEN c1 ELSE c2 FI) / st\n  | CS_While : forall st b c1,\n          (WHILE b DO c1 END) / st\n      ==> (IFB b THEN (c1;; (WHILE b DO c1 END)) ELSE SKIP FI) / st\n\n  where \" t '/' st '==>' t' '/' st' \" := (cstep (t,st) (t',st')).\n\nModule CImp.\nInductive com : Type :=\n  | CSkip : com\n  | CAss : string -> aexp -> com\n  | CSeq : com -> com -> com\n  | CIf : bexp -> com -> com -> com\n  | CWhile : bexp -> com -> com\n  (* New: *)\n  | CPar : com -> com -> com.\nNotation \"'SKIP'\" :=\n  CSkip.\nNotation \"x '::=' a\" :=\n  (CAss x a) (at level 60).\nNotation \"c1 ;; c2\" :=\n  (CSeq c1 c2) (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (CWhile b c) (at level 80, right associativity).\nNotation \"'IFB' b 'THEN' c1 'ELSE' c2 'FI'\" :=\n  (CIf b c1 c2) (at level 80, right associativity).\nNotation \"'PAR' c1 'WITH' c2 'END'\" :=\n  (CPar c1 c2) (at level 80, right associativity).\nInductive cstep : (com * state) -> (com * state) -> Prop :=\n    (* Old part *)\n  | CS_AssStep : forall st i a a',\n      a / st ==>a a' ->\n      (i ::= a) / st ==> (i ::= a') / st\n  | CS_Ass : forall st i n,\n      (i ::= (ANum n)) / st ==> SKIP / st & { i --> n }\n  | CS_SeqStep : forall st c1 c1' st' c2,\n      c1 / st ==> c1' / st' ->\n      (c1 ;; c2) / st ==> (c1' ;; c2) / st'\n  | CS_SeqFinish : forall st c2,\n      (SKIP ;; c2) / st ==> c2 / st\n  | CS_IfTrue : forall st c1 c2,\n      (IFB BTrue THEN c1 ELSE c2 FI) / st ==> c1 / st\n  | CS_IfFalse : forall st c1 c2,\n      (IFB BFalse THEN c1 ELSE c2 FI) / st ==> c2 / st\n  | CS_IfStep : forall st b b' c1 c2,\n      b /st ==>b b' ->\n          (IFB b THEN c1 ELSE c2 FI) / st \n      ==> (IFB b' THEN c1 ELSE c2 FI) / st\n  | CS_While : forall st b c1,\n          (WHILE b DO c1 END) / st \n      ==> (IFB b THEN (c1;; (WHILE b DO c1 END)) ELSE SKIP FI) / st\n    (* New part: *)\n  | CS_Par1 : forall st c1 c1' c2 st',\n      c1 / st ==> c1' / st' ->\n      (PAR c1 WITH c2 END) / st ==> (PAR c1' WITH c2 END) / st'\n  | CS_Par2 : forall st c1 c2 c2' st',\n      c2 / st ==> c2' / st' ->\n      (PAR c1 WITH c2 END) / st ==> (PAR c1 WITH c2' END) / st'\n  | CS_ParDone : forall st,\n      (PAR SKIP WITH SKIP END) / st ==> SKIP / st\n  where \" t '/' st '==>' t' '/' st' \" := (cstep (t,st) (t',st')).\nDefinition cmultistep := multi cstep.\nNotation \" t '/' st '==>*' t' '/' st' \" :=\n   (multi cstep (t,st) (t',st'))\n   (at level 40, st at level 39, t' at level 39).\n\nDefinition par_loop : com :=\n  PAR\n    Y ::= 1\n  WITH\n    WHILE Y = 0 DO\n      X ::= X + 1\n    END\n  END.\n\nExample par_loop_example_0:\n  exists st',\n       par_loop / { --> 0 } ==>* SKIP / st'\n    /\\ st' X = 0.\nProof.\neapply ex_intro. split.\neapply multi_step. apply CS_Par1.\napply CS_Ass. eapply multi_step.\napply CS_Par2. apply CS_While.\neapply multi_step. eapply CS_Par2.\napply CS_IfStep. apply BS_Eq1.\napply AS_Id. eapply multi_step.\napply CS_Par2. apply CS_IfStep.\napply BS_Eq. simpl.\n  eapply multi_step. apply CS_Par2. apply CS_IfFalse.\n  eapply multi_step. apply CS_ParDone.\n  eapply multi_refl.\n  reflexivity. Qed.\n\nExample par_loop_example_2:\n  exists st',\n       par_loop / { --> 0 } ==>* SKIP / st'\n    /\\ st' X = 2.\nProof.\nAdmitted.\n\nTheorem par_loop_any_X:\n  forall n, exists st',\n    par_loop / { --> 0 } ==>* SKIP / st'\n    /\\ st' X = n.\nProof.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/small.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.707680069678738}}
{"text": "(* First, let us look at some example : *)\n\nLemma P3Q : forall P Q : Prop, (((P->Q)->Q)->Q) -> P -> Q.\nProof.\n intros P Q H p.\n apply H. \n intro H0. \n apply H0. \n assumption. \nQed.\n\nLemma triple_neg : forall P:Prop, ~~~P -> ~P.\nProof.\n  intros P.\n  unfold not.\n  apply P3Q.\nQed.\n\n\nLemma all_perm :\n forall (A:Type) (P:A -> A -> Prop),\n   (forall x y:A, P x y) -> forall x y:A, P y x.\nProof.\n  intros.\n  apply (H y x).\nQed.\n\nLemma resolution :\n forall (A:Type) (P Q R S:A -> Prop),\n   (forall a:A, Q a -> R a -> S a) ->\n   (forall b:A, P b -> Q b) -> \n   forall c:A, P c -> R c -> S c.\nProof.\n  intros.\n  apply H.\n  * apply H0.\n    apply H1.\n  * apply H2.\nQed.\n\nLemma not_ex_forall_not : forall (A: Type) (P: A -> Prop),\n                      ~(exists x, P x) <-> forall x, ~ P x.\nProof.\n  intros.\n  split.\n  * intro.\n    intro.\n    unfold not in H.\n    unfold not.\n    intro.\n    apply H.\n    exists x.\n    assumption.\n  * intro.\n    unfold not.\n    intro.\n    unfold not in H.\n    destruct H0.\n    apply (H x).\n    assumption.\nQed.\n\nLemma ex_not_forall_not : forall (A: Type) (P: A -> Prop),\n                       (exists x, P x) -> ~ (forall x, ~ P x).\nProof.\n  intros.\n  unfold not.\n  destruct H.\n  intro.\n  apply (H0 x).\n  assumption.\nQed.\n\n\nLemma diff_sym : forall (A:Type) (a b : A), a <> b -> b <> a.\nProof.\n  intros.\n  unfold not.\n  unfold not in H.\n  intro.\n  apply H.\n  symmetry.\n  assumption.\nQed.\n\nLemma fun_diff :  forall (A B:Type) (f : A -> B) (a b : A), \n                       f a <> f b -> a <> b.\nProof.\n  intros.\n  unfold not.\n  intro.\n  unfold not in H.\n  apply H.\n  rewrite H0.\n  trivial.\nQed.\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/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597265050901, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7076800677053764}}
{"text": "Require Export GeoCoq.Tarski_dev.Ch04_col.\nRequire Import GeoCoq.Utils.all_equiv.\n\nSection Equivalence_between_decidability_properties_of_basic_relations.\n\nContext `{Tn:Tarski_neutral_dimensionless}.\n\nLemma cong_dec_eq_dec :\n  (forall A B C D, Cong A B C D \\/ ~ Cong A B C D) ->\n  (forall A B:Tpoint, A=B \\/ A<>B).\nProof.\n    intros H A B.\n    elim (H A B A A); intro HCong.\n      left; apply cong_identity with A; assumption.\n    right; intro; subst; apply HCong.\n    apply cong_pseudo_reflexivity.\nQed.\n\nLemma eq_dec_implies_l2_11 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C A' B' C',\n  Bet A B C -> Bet A' B' C' -> Cong A B A' B' -> Cong B C B' C' -> Cong A C A' C'.\nProof.\nintro eq_dec; intros.\ninduction (eq_dec A B).\nsubst B.\nassert (A' = B') by (apply (cong_identity A' B' A); Cong).\nsubst; Cong.\napply cong_commutativity; apply (five_segment A A' B B' C C' A A'); Cong.\nQed.\n\nLemma eq_dec_implies_construction_uniqueness :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall Q A B C X Y,\n  Q <> A -> Bet Q A X -> Cong A X B C -> Bet Q A Y -> Cong A Y B C -> X=Y.\nProof.\nintro eq_dec; intros.\nassert (Cong A X A Y) by eCong.\nassert (Cong Q X Q Y) by (apply (eq_dec_implies_l2_11 eq_dec Q A X Q A Y);Cong).\nassert(OFSC Q A X Y Q A X X) by (unfold OFSC;repeat split;Cong).\napply five_segment_with_def in H6; try assumption.\napply cong_identity with X; Cong.\nQed.\n\nLemma eq_dec_implies_outer_transitivity_between2 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C D, Bet A B C -> Bet B C D -> B<>C -> Bet A C D.\nProof.\nintro eq_dec; intros.\nprolong A C x C D.\nassert (x = D) by (apply (eq_dec_implies_construction_uniqueness eq_dec B C C D); try apply (between_exchange3 A B C x); Cong).\nsubst x;assumption.\nQed.\n\nLemma eq_dec_implies_between_exchange4 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C D, Bet A B C -> Bet A C D -> Bet A B D.\nProof.\nintro eq_dec; intros.\ninduction (eq_dec B C); [subst; auto|].\napply between_symmetry;\napply eq_dec_implies_outer_transitivity_between2 with C; eBetween.\nQed.\n\nLemma eq_dec_implies_two_distinct_points :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  exists X, exists Y: Tpoint, X <> Y.\nProof.\nintro eq_dec.\nassert (ld:=lower_dim_ex).\nex_elim ld A.\nex_elim H B.\nex_elim H0 C.\ninduction (eq_dec A B).\nsubst A; exists B; exists C; Between.\nexists A; exists B; assumption.\nQed.\n\nLemma eq_dec_implies_point_construction_different :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B, exists C, Bet A B C /\\ B <> C.\nProof.\nintro eq_dec; intros.\nassert (tdp := eq_dec_implies_two_distinct_points eq_dec).\nex_elim tdp x.\nex_elim H y.\nprolong A B F x y.\nexists F.\nshow_distinct B F.\nintuition.\nintuition.\nQed.\n\nLemma eq_dec_implies_l4_2 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C D A' B' C' D', IFSC A B C D A' B' C' D' -> Cong B D B' D'.\nProof.\nunfold IFSC.\nintro eq_dec; intros.\nspliter.\n\ninduction (eq_dec A C).\n\ntreat_equalities;assumption.\n\nassert (exists E, Bet A C E /\\ C <> E)\n by (apply eq_dec_implies_point_construction_different; auto).\nex_and H6 E.\nprolong A' C' E' C E.\n\nassert  (Cong E D E' D')\n by (\n  apply (five_segment_with_def A C E D A' C' E' D');[\n  unfold OFSC;  repeat split;Cong|\n  assumption]).\n\napply (five_segment_with_def E C B D E' C' B' D').\nunfold OFSC.\nrepeat split; try solve [eBetween| Cong ].\nauto.\nQed.\n\nLemma eq_dec_implies_l4_5 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C A' C',\n  Bet A B C -> Cong A C A' C' ->\n  exists B', Bet A' B' C' /\\ Cong_3 A B C A' B' C'.\nProof.\nintro eq_dec; intros.\nunfold Cong_3.\n\nassert (exists D', Bet C' A' D' /\\ A' <> D')\n by (apply eq_dec_implies_point_construction_different; auto).\nex_and H1 x'.\nprolong x' A' B' A B.\nprolong x' B' C'' B C.\n\nassert (Bet A' B' C'') by eBetween.\n\nassert (C'' = C').\neapply (eq_dec_implies_construction_uniqueness eq_dec x' A' ).\n\nauto.\n\napply eq_dec_implies_between_exchange4 with B'; auto.\n\napply (eq_dec_implies_l2_11 eq_dec A' B' C'' A B C);Between.\n\neBetween.\nCong.\n\nsubst C''.\nexists B'.\nrepeat split;Cong.\nQed.\n\nLemma eq_dec_implies_l4_6 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C A' B' C', Bet A B C -> Cong_3 A B C A' B' C' -> Bet A' B' C'.\nProof.\nunfold Cong_3.\nintro eq_dec; intros.\nassert (exists B'', Bet A' B'' C' /\\ Cong_3 A B C A' B'' C')\n  by (eapply eq_dec_implies_l4_5;intuition).\nex_and H1 x.\nunfold Cong_3 in *;spliter.\n\nassert (Cong_3 A' x C' A' B' C')\n by (unfold Cong_3;repeat split;eCong).\nunfold Cong_3 in H7;spliter.\n\nassert (IFSC A' x C' x  A' x C' B')\n by (unfold IFSC;repeat split;Cong).\nassert (Cong x x x B')\n by (eapply eq_dec_implies_l4_2; try apply H10; auto).\nBetween.\nQed.\n\nLemma eq_dec_implies_l4_16 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C D A' B' C' D',\n  FSC A B C D A' B' C' D' -> A<>B -> Cong C D C' D'.\nProof.\nunfold FSC.\nunfold Col.\nintro eq_dec; intros.\ndecompose [or and] H; clear H.\nassert (Bet A' B' C') by (eapply eq_dec_implies_l4_6;eauto).\nunfold Cong_3 in *; spliter.\nassert(OFSC A B C D A' B' C' D') by (unfold OFSC;repeat split; assumption).\neapply five_segment_with_def; eauto.\nassert(Bet B' C' A') by (apply (eq_dec_implies_l4_6 eq_dec B C A B' C' A'); Cong;auto with cong3).\napply (eq_dec_implies_l4_2 eq_dec B C A D B' C' A' D').\nunfold IFSC; unfold Cong_3 in *; spliter; repeat split;Between;Cong.\nassert (Bet C' A' B') by (eapply (eq_dec_implies_l4_6 eq_dec C A B C' A' B'); auto with cong3).\neapply (five_segment_with_def B A C D B' A'); unfold OFSC; unfold Cong_3 in *; spliter; repeat split; Between; Cong.\nQed.\n\nLemma eq_dec_implies_l4_17 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C P Q,\n  A<>B -> Col A B C -> Cong A P A Q -> Cong B P B Q -> Cong C P C Q.\nProof.\nintros.\nassert (FSC A B C P A B C Q) by (unfold FSC; unfold Cong_3; repeat split;Cong).\neapply eq_dec_implies_l4_16; eauto.\nQed.\n\nLemma eq_dec_implies_l5_1 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C D,\n  A<>B -> Bet A B C -> Bet A B D -> Bet A C D \\/ Bet A D C.\nProof.\nintro eq_dec; intros.\nprolong A D C' C D.\nprolong A C D' C D.\nprolong A C' B' C B.\nprolong A D' B'' D B.\nassert (Cong B C' B'' C).\napply (eq_dec_implies_l2_11 eq_dec B D C' B'' D' C).\napply between_exchange3 with A; Between.\napply between_inner_transitivity with A; Between.\nCong.\napply cong_transitivity with C D; Cong.\nassert (Cong B B' B'' B).\n  {\n  apply (eq_dec_implies_l2_11 eq_dec B C' B' B'' C B); Cong.\n\n    {\n    assert (Bet A B C'); [|eBetween].\n    induction (eq_dec B D); [treat_equalities; auto|].\n    apply between_symmetry.\n    apply eq_dec_implies_outer_transitivity_between2 with D; eBetween.\n    }\n\n    {\n    induction (eq_dec C D'); [treat_equalities; eBetween|].\n    apply eq_dec_implies_outer_transitivity_between2 with D'; eBetween.\n    }\n  }\nassert(B'' =  B').\napply (eq_dec_implies_construction_uniqueness eq_dec A B B B''); try Cong.\napply eq_dec_implies_between_exchange4 with D'; Between;\napply eq_dec_implies_between_exchange4 with C; Between.\napply eq_dec_implies_between_exchange4 with C'; Between;\napply eq_dec_implies_between_exchange4 with D; Between.\nsubst B''.\nassert (FSC B C D' C' B' C' D C).\nunfold FSC.\nrepeat split; unfold Col; try Cong.\nleft; apply between_exchange3 with A; Between.\napply (eq_dec_implies_l2_11 eq_dec B C D' B' C' D); Cong.\napply between_exchange3 with A; assumption.\napply between_symmetry.\napply between_exchange3 with A; assumption.\napply cong_transitivity with C D; Cong.\napply cong_transitivity with C D; Cong.\ninduction (eq_dec B C).\nsubst C; auto.\nassert (Cong D' C' D C) by (eapply eq_dec_implies_l4_16; try apply H12; assumption).\nassert (exists E, Bet C E C' /\\ Bet D E D') by (apply inner_pasch with A; Between).\nex_and H15 E.\nassert (IFSC D E D' C D E D' C') by (unfold IFSC; repeat split; Cong; apply cong_transitivity with C D; Cong).\nassert (IFSC C E C' D C E C' D') by (unfold IFSC; repeat split; Cong; apply cong_transitivity with C D; Cong).\nassert (Cong E C E C') by (eapply eq_dec_implies_l4_2; try apply H17; auto).\nassert (Cong E D E D') by (eapply eq_dec_implies_l4_2; try apply H18; auto).\ninduction (eq_dec C C').\nsubst C'; right; assumption.\nshow_distinct C D'; intuition.\nprolong C' C P C D'.\nprolong D' C R C E.\nprolong P R Q R P.\nassert (FSC D' C R P P C E D').\nunfold FSC.\nunfold Cong_3.\nassert_cols.\nrepeat split; Cong.\napply eq_dec_implies_l2_11 with C C; Cong.\napply between_inner_transitivity with C'; Between.\nassert (Cong R P E D') by (eauto using eq_dec_implies_l4_16).\nassert (Cong R Q E D).\neapply cong_transitivity.\napply cong_transitivity with R P; Cong.\napply cong_transitivity with E D'; Cong.\nassert (FSC D' E D C P R Q C).\nunfold FSC.\nrepeat split; Cong.\nunfold Col; Between.\neapply (eq_dec_implies_l2_11 eq_dec D' E D P R Q); Between; Cong.\nassert (Cong D C Q C).\ninduction (eq_dec D' E).\nunfold FSC, IFSC, Cong_3 in *; spliter; treat_equalities; Cong.\napply eq_dec_implies_l4_16 with D' E P R; assumption.\nassert (Cong C P C Q).\nunfold FSC in *;unfold Cong_3 in *.\nspliter.\napply cong_transitivity with C D.\napply cong_transitivity with C D'; Cong.\nCong.\nshow_distinct R C.\nintuition.\nassert (Cong D' P D' Q) by (apply (eq_dec_implies_l4_17 eq_dec R C); unfold Col; Between; Cong).\nassert (Cong B P B Q).\napply eq_dec_implies_l4_17 with C D'; try assumption.\nunfold Col; right;right.\napply between_exchange3 with A; assumption.\nassert (Cong B' P B' Q).\neapply (eq_dec_implies_l4_17 eq_dec C D'); Cong.\nunfold Col; left.\napply between_exchange3 with A; assumption.\nassert (Cong C' P C' Q).\ninduction(eq_dec B B').\nsubst B'.\nunfold IFSC,FSC, Cong_3 in *.\nspliter.\nclean_duplicated_hyps.\nclean_trivial_hyps.\napply eq_dec_implies_l4_17 with C D'; try assumption.\nunfold Col; left.\napply between_exchange3 with A; try assumption.\napply eq_dec_implies_between_exchange4 with B; try assumption.\napply eq_dec_implies_between_exchange4 with D; assumption.\neapply eq_dec_implies_l4_17 with B B'; Cong.\nunfold Col; right; left.\napply between_symmetry.\napply between_exchange3 with A; try assumption.\napply eq_dec_implies_between_exchange4 with D; assumption.\nassert (Cong P P P Q).\napply eq_dec_implies_l4_17 with C C'; try assumption.\nunfold Col; right; right.\napply between_symmetry; assumption.\nunfold IFSC,FSC, Cong_3 in *; spliter.\ntreat_equalities.\nBetween.\nQed.\n\nLemma eq_dec_implies_l5_2 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C D,\n  A<>B -> Bet A B C -> Bet A B D -> Bet B C D \\/ Bet B D C.\nProof.\nintros.\nassert (Bet A C D \\/ Bet A D C) by (eapply eq_dec_implies_l5_1; eauto).\ninduction H3.\nleft; eBetween.\nright; eBetween.\nQed.\n\nLemma eq_dec_implies_segment_construction_2 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A Q B C, A<>Q -> exists X, (Bet Q A X \\/ Bet Q X A) /\\ Cong Q X B C.\nProof.\nintro eq_dec; intros.\nprolong A Q A' A Q.\nprolong A' Q X B C.\nexists X.\nshow_distinct A' Q.\nsolve [intuition].\nsplit; try assumption.\neapply (eq_dec_implies_l5_2 eq_dec A' Q); Between.\nQed.\n\nLemma eq_dec_implies_between_cong :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B C, Bet A C B -> Cong A C A B -> C=B.\nProof.\nintros.\nassert (Bet A B C).\neapply eq_dec_implies_l4_6 with A C B; unfold Cong_3; repeat split; Cong.\neapply between_equality; eBetween.\nQed.\n\nLemma eq_dec_cong_dec :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  (forall A B C D, Cong A B C D \\/ ~ Cong A B C D).\nProof.\nintro eq_dec; intros.\nelim (eq_dec A B); intro; subst; elim (eq_dec C D); intro; subst.\nleft; Cong.\nright; intro; apply H; apply cong_identity with B; Cong.\nright; intro; apply H; apply cong_identity with D; Cong.\nelim (eq_dec_implies_segment_construction_2 eq_dec B A C D).\nintros D' HD'.\nspliter.\nelim (eq_dec B D');intro.\nsubst; left; assumption.\nright; intro.\nassert (Cong A D' A B) by eCong.\nelim H1; intro; clear H1.\nassert (B = D') by (apply (eq_dec_implies_between_cong eq_dec A D' B); Cong).\nsubst;intuition.\nassert (D'=B) by (apply (eq_dec_implies_between_cong eq_dec A B D');assumption).\nsubst;intuition.\nintuition.\nQed.\n\nLemma bet_dec_eq_dec :\n  (forall A B C, Bet A B C \\/ ~ Bet A B C) ->\n  (forall A B:Tpoint, A=B \\/ A<>B).\nProof.\nintros.\ninduction (H A B A).\nleft; apply between_identity; assumption.\nright; intro; subst; apply H0;  apply between_trivial.\nQed.\n\nLemma eq_dec_implies_between_cong_3 :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  forall A B D E, A <> B -> Bet A B D -> Bet A B E -> Cong B D B E -> D = E.\nProof.\nintro eq_dec; intros.\nassert (T:=eq_dec_implies_l5_2 eq_dec A B D E H H0 H1).\nelim T; intro; clear T.\napply eq_dec_implies_between_cong with B; Cong.\nsymmetry; apply eq_dec_implies_between_cong with B; Cong.\nQed.\n\nLemma eq_dec_bet_dec :\n  (forall A B:Tpoint, A=B \\/ A<>B) ->\n  (forall A B C, Bet A B C \\/ ~ Bet A B C).\nProof.\nintro eq_dec; intros.\nelim (segment_construction A B B C); intros C' HC'.\nspliter.\nelim (eq_dec C C'); intro.\nsubst; tauto.\nelim (eq_dec A B);intro.\nleft; subst; Between.\nright; intro; apply H1; apply eq_dec_implies_between_cong_3 with A B; Cong.\nQed.\n\nDefinition decidability_of_equality_of_points := forall A B:Tpoint, A=B \\/ A<>B.\n\nDefinition decidability_of_congruence_of_points := forall A B C D:Tpoint,\n  Cong A B C D \\/ ~ Cong A B C D.\n\nDefinition decidability_of_betweenness_of_points := forall A B C:Tpoint,\n  Bet A B C \\/ ~ Bet A B C.\n\nTheorem equivalence_between_decidability_properties_of_basic_relations :\n  all_equiv  (decidability_of_equality_of_points::\n              decidability_of_congruence_of_points::\n              decidability_of_betweenness_of_points::nil).\nProof.\nunfold all_equiv.\nsimpl.\nintros.\nassert (P:=cong_dec_eq_dec).\nassert (Q:=eq_dec_cong_dec).\nassert (R:=bet_dec_eq_dec).\nassert (S:=eq_dec_bet_dec).\ndecompose [or] H;clear H;decompose [or] H0;clear H0;subst; tauto.\nQed.\n\nEnd Equivalence_between_decidability_properties_of_basic_relations.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/GeoCoq/Meta_theory/Decidability/equivalence_between_decidability_properties_of_basic_relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.8128673087708698, "lm_q1q2_score": 0.7076800667818832}}
{"text": "\n\n\n(***************************** LIFLF - TPNOTE *********************************)\n(************* Evaluation pratique en temps limité : 30' **********************)\n\n(************************ SUJET D'ENTRAINEMENT ********************************)\n(* Ce sujet est représentatif de celui qui vous sera donné à réaliser en temps \nlimité. Les fonctions lemmes demandés ici sont tout à fait classiques.\n*)\nRequire Import Utf8.\n\n\n(******************************************************************************)\n(* Logique propositionnelle *)\n(******************************************************************************)\nSection PL.\n\nContext (P Q : Prop).\n\n(* EXERCICE : prouver la propriété suivante SANS UTILISER UNE TACTIQUE AUTOMATIQUE *)\nLemma de_morgan : (~P \\/ ~Q) -> ~(P /\\ Q).\nProof.\nunfold not.\nintros.\ndestruct H.\napply H.\ndestruct H0.\nassumption.\napply H.\ndestruct H0.\nassumption.\nQed.\n\nEnd PL. \n\n(******************************************************************************)\n(* Les listes *)\n(******************************************************************************)\n\nPrint length. (* la longueur de listes *)\n\n(* EXERCICE :  énoncer le lemme \"mystere\" en langue naturelle *)\nLemma mystere A:  forall l : list A, length l = 0 <-> l = nil.\nProof.\ninduction l; split.\n- simpl. reflexivity.\n- simpl. reflexivity.\n- intros. discriminate H.\n- simpl. intros. discriminate H.\nQed.\n\nGoal 1 = 0 -> 42 = 3.\nProof.\nintros.\ndiscriminate H.\nQed.\n\n\n\n(* EXERCICE :  prouver le lemme \"mystere\"  SANS UTILISER \"Require Import List.\" *)", "meta": {"author": "KevinFroissart", "repo": "coqTP", "sha": "f050bf832a49be9262aea70f4844a7394d112817", "save_path": "github-repos/coq/KevinFroissart-coqTP", "path": "github-repos/coq/KevinFroissart-coqTP/coqTP-f050bf832a49be9262aea70f4844a7394d112817/liflc/LIFLC_TPC_ex_tp_note.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.707680052380228}}
{"text": "Require Import Arith.\n\nGoal forall m n : nat, (n * 10) + m = (10 * n) + m.\nProof.\n  intros.\n  apply NPeano.Nat.add_cancel_r.\n  apply mult_comm.\nQed.", "meta": {"author": "odanado", "repo": "coq", "sha": "6524eb11b64fc6703af806e94b5405279d099ef2", "save_path": "github-repos/coq/odanado-coq", "path": "github-repos/coq/odanado-coq/coq-6524eb11b64fc6703af806e94b5405279d099ef2/coqex2014/2/kadai2_8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.7075144722841564}}
{"text": "Require Import MapProofs.Common.\nSet Bullet Behavior \"Strict Subproofs\".\nRequire Import MapProofs.Bounds.\nRequire Import MapProofs.Tactics.\n\nSection WF.\nContext {e : Type} {a : Type} {HEq : Eq_ e} {HOrd : Ord e} {HEqLaws : EqLaws e}  {HOrdLaws : OrdLaws e}.\n\n(** ** Verification of [lookup] *)\n\nLemma lookup_spec:\n forall (s: Map e a) lb ub i, Bounded s lb ub -> lookup i s = sem s i.\nProof.\n  intros ???? HB.\n  induction HB.\n  * simpl. reflexivity.\n  * subst; simpl.\n    destruct (compare i x) eqn:?.\n    + replace (i == x) with true by order_Bounds e.\n      rewrite (sem_outside_above HB1) by order_Bounds e.\n      reflexivity.\n    + replace (i == x) with false by order_Bounds e.\n      rewrite IHHB1.\n      rewrite (sem_outside_below HB2) by order_Bounds e.\n      simpl_options.\n      reflexivity.\n    + replace (i == x) with false by order_Bounds e.\n      rewrite IHHB2.\n      rewrite (sem_outside_above HB1) by order_Bounds e.\n      simpl_options.\n      reflexivity.\nQed.\n\n(** ** Verification of [member] *)\n\nLemma member_spec:\n forall (s: Map e a) lb ub i, Bounded s lb ub -> member i s = true <-> exists v, sem s i = Some v.\nProof.\n  intros. induction H.\n  - simpl. split. intros. discriminate H. intros. destruct H. discriminate H.\n  - subst. simpl. destruct (compare i x) eqn: ?; split; intros.\n    + replace (i==x) with true by order_Bounds e.\n      rewrite (sem_outside_above H) by order_Bounds e.\n      simpl. exists v. reflexivity.\n    + reflexivity.\n    + replace (i==x) with false by order_Bounds e.\n      rewrite (sem_outside_below H0) by order_Bounds e.\n      simpl_options. apply IHBounded1 in H3. destruct H3. exists x0. assumption.\n    + assert (sem s2 i = None). { eapply sem_outside_below. apply H0. unfold isLB.\n      order_Bounds e. }\n      rewrite H5 in H3. assert (i == x = false). { rewrite compare_Lt in Heqc.\n      apply lt_not_eq. assumption. } rewrite H6 in H3. simpl in H3. simpl_options.\n      apply IHBounded1. destruct H3. exists x0. assumption.\n    + replace (i==x) with false by order_Bounds e.\n      rewrite (sem_outside_above H) by order_Bounds e.\n      simpl. apply IHBounded2 in H3. destruct H3. exists x0. assumption.\n    + assert (sem s1 i = None). { eapply sem_outside_above. apply H. order_Bounds e. }\n      rewrite H5 in H3. rewrite compare_Gt in Heqc. apply gt_not_eq in Heqc. rewrite Heqc in H3.\n      simpl_options. destruct H3. apply IHBounded2. exists x0. assumption.\nQed.\n\n(** ** Verification of [notMember] *)\n\nLemma notMember_spec:\n forall (s: Map e a) lb ub i, Bounded s lb ub -> notMember i s = true <-> sem s i = None.\nProof.\n  intros ???? HB.\n  unfold notMember, op_zd__. split; intros.\n  pose proof (@member_spec s lb ub i). apply H0 in HB. destruct HB. apply contrapositive in H2.\n  unfold not in H2. destruct (sem s i). destruct H2. exists a0. reflexivity. reflexivity.\n  rewrite negb_true_iff in H. intro. rewrite H3 in H. inversion H.\n  pose proof (@member_spec s lb ub i). apply H0 in HB. destruct HB. apply contrapositive in H1.\n  rewrite negb_true_iff. destruct (member i s). contradiction. reflexivity. intro.\n  destruct H3. rewrite H3 in H. inversion H.\nQed.\n\n(** ** Verification of [findWithDefault] *)\nLemma findWithDefault_spec:\n  forall (m: Map e a) lb ub i v, Bounded m lb ub ->\n  Some (findWithDefault v i m) = sem m i ||| Some v.\nProof.\n  intros. induction H.\n  - simpl. reflexivity.\n  - simpl. destruct (compare i x) eqn : ?.\n    + assert (sem s1 i = None). { eapply sem_outside_above. eassumption. solve_Bounds e. }\n      rewrite H5. assert (i == x = true) by (order e). rewrite H6. reflexivity.\n    + assert (i == x = false) by (order e). assert (sem s2 i = None). { eapply sem_outside_below.\n      eassumption. solve_Bounds e. } rewrite H5. rewrite H6. simpl. rewrite oro_None_r.\n      rewrite oro_None_r. apply IHBounded1.\n    + assert (i == x = false) by (order e). assert (sem s1 i = None). { eapply sem_outside_above.\n      eassumption. solve_Bounds e. } rewrite H5. rewrite H6. simpl. apply IHBounded2.\nQed.\n(** ** Verification of [lookupLT] *)\nFixpoint goJustLT k  (k1: e) v1 (m : Map e a) : option (e * a) :=\n  match m with\n  | Tip => Some (k1, v1)\n  | Bin sz k2 v2 l r => if (_GHC.Base.<=_ k k2) then goJustLT k k1 v1 l else\n    goJustLT k k2 v2 r\n  end.\nFixpoint lookupLT' k (m : Map e a) :=\n  match m with\n  | Tip => None\n  | Bin sz k1 v1 l r => if (_GHC.Base.<=_ k k1) then lookupLT' k l else goJustLT k k1 v1 r\n  end.\n\nLemma lookupLT_equiv:\n  forall m k,\n  lookupLT' k m = lookupLT k m.\nProof.\n  intros. unfold lookupLT'. unfold lookupLT. unfold goJustLT. reflexivity.\nQed.\n\nLemma goJustLT_pres_smaller: forall k k1 v1 m k2 v2 lb ub,\n  Bounded m lb ub ->\n  _GHC.Base.<_ k1 k = true ->\n  goJustLT k k1 v1 m = Some (k2, v2) ->\n  _GHC.Base.<_ k2 k = true.\nProof.\n  intros. generalize dependent k1. revert v1 v2 k2 k. induction H; intros.\n  - simpl in H1. inversion H1; subst. assumption.\n  - simpl in H6. destruct (_GHC.Base.<=_ k x) eqn : ?.\n   + eapply IHBounded1. eassumption. eassumption.\n   + assert (_GHC.Base.<_ x k = true) by (order e). eapply IHBounded2. apply H7.\n      apply H6.\nQed.\n\nLemma goJustLT_bounded: forall k k1 v1 m k2 v2 lb ub l u,\n  Bounded m lb ub ->\n  _GHC.Base.<_ k1 k = true ->\n  goJustLT k k1 v1 m = Some (k2, v2) ->\n  (lb = Some l /\\ _GHC.Base.<=_ l k1 = true -> _GHC.Base.<=_ l k2 = true )\n  /\\ (ub = Some u /\\ _GHC.Base.<=_ k1 u = true -> _GHC.Base.<=_ k2 u = true).\nProof.\n  intros. generalize dependent k1. revert k v1 k2 v2 u l. induction H; intros.\n  - simpl in H1. inversion H1; subst. split; intros; subst; solve_Bounds e.\n  - simpl in H6. destruct (_GHC.Base.<=_ k x) eqn : ?.\n    + split; intros; subst.  specialize (IHBounded1 _ _ _ _ u l _ H5 H6). destruct IHBounded1.\n       apply H3. apply H7. specialize (IHBounded1 _ _ _ _ x l  _ H5 H6). destruct IHBounded1.\n        destruct H7; subst. assert (Some x = Some x /\\ _GHC.Base.<=_ k1 x = true).\n        split. reflexivity. order e. apply H8 in H7.  assert (compare x u = Lt) by (solve_Bounds e).\n        order e.\n    + assert (_GHC.Base.<_ x k = true) by (order e).  split; intros; subst.\n      specialize (IHBounded2  _ _ _ _ u x _ H7 H6). destruct IHBounded2.\n      destruct H8; subst. assert (_GHC.Base.<=_ x k2 = true). apply H3. split. reflexivity.\n      order e. assert (_GHC.Base.<_ l x = true) by (solve_Bounds e). order e.\n      specialize (IHBounded2 _ _ _ _ u l _ H7 H6). destruct IHBounded2. apply H9.\n      split. apply H8. destruct H8. subst. solve_Bounds e.\nQed.\n\nLemma goJustLT_nothing_between: forall k k1 v1 m lb ub k2 v2,\n  Bounded m lb ub ->\n  _GHC.Base.<_ k1 k = true ->\n  goJustLT k k1 v1 m = Some (k2, v2) ->\n  (forall i, compare k2 i = Lt /\\ compare i k = Lt ->\n  sem m i = None).\nProof.\n  intros. generalize dependent i. generalize dependent k2. generalize dependent k1.\n  revert k v1 v2.\n  induction H; intros.\n  - reflexivity.\n  - simpl. simpl in H6. destruct ( _GHC.Base.<=_ k x) eqn : ?.\n    + assert (i == x = false) by (order e). rewrite H8. assert (sem s2 i = None). {\n      eapply sem_outside_below. eassumption. solve_Bounds e. } rewrite H9.\n      simpl. repeat(rewrite oro_None_r). eapply IHBounded1. apply H5. apply H6.\n      assumption.\n    + assert (_GHC.Base.<_ x k = true) by (order e).\n      pose proof goJustLT_bounded. specialize (H9 _ _ _ _ _ _ _ _ x k H0 H8 H6).\n      destruct H9. assert (_GHC.Base.<=_ x k2 = true). apply H9. split. reflexivity.\n      order e. assert (_GHC.Base.<_ x i = true). order e. assert (sem s1 i = None).\n      eapply sem_outside_above. eassumption. solve_Bounds e. rewrite H13.\n      assert (i == x = false) by (order e). rewrite H14. simpl. eapply IHBounded2.\n      apply H8. apply H6. apply H7.\nQed.\n\nLemma goJustLT_finds_upper_bound: forall k k1 v1 m lb ub k2 v2,\n  Bounded m lb ub ->\n  _GHC.Base.<_ k1 k = true ->\n  goJustLT k k1 v1 m = Some (k2, v2) ->\n   (_GHC.Base.<_  k2 k = true) /\\\n  (forall k3, (_GHC.Base.<_  k3 k = true) /\\ (k2 == k3 = false) /\\\n  sem m k3 <> None -> (_GHC.Base.<_  k3 k2 = true)).\nProof.\n  intros. pose proof (goJustLT_nothing_between k k1 v1 m lb ub k2 v2 H H0 H1).\n  split. eapply goJustLT_pres_smaller. apply H. apply H0. apply H1. intros.\n  specialize (H2 k3). destruct H3. destruct H4.\n  destruct (_GHC.Base.<_ k3 k2 ) eqn : ?.\n  - reflexivity.\n  - assert (sem m k3 = None). apply H2. split. order e. order e. contradiction.\nQed.\n\nLemma goJustLt_val_in_map: forall k k1 v1 m lb ub k2 v2,\n  Bounded m lb ub ->\n  goJustLT k k1 v1 m = Some (k2, v2) ->\n  sem m k2 = Some v2 \\/ ((k2 == k1 = true) /\\ v2 = v1).\nProof.\n  intros. generalize dependent k2. revert k k1 v1 v2. induction H; intros.\n  - simpl in H0. inversion H0; subst. right. split. apply Eq_Reflexive. reflexivity.\n  - simpl. simpl in H5. destruct (_GHC.Base.<=_ k x) eqn : ?.\n    + specialize (IHBounded1 k k1 v1 v2 k2 H5). destruct IHBounded1.\n      * rewrite H6. simpl. left. reflexivity.\n      * right. apply H6.\n    + assert (_GHC.Base.<_ x k = true) by (order e).\n      pose proof goJustLT_bounded. specialize (H7 k x v s2 k2 v2 (Some x) ub x k H0 H6 H5).\n      destruct H7. assert (_GHC.Base.<=_ x k2 = true). apply H7. split. reflexivity. order e.\n      assert (sem s1 k2 = None). eapply sem_outside_above. eassumption. solve_Bounds e. rewrite H10.\n      simpl. specialize (IHBounded2 k x v v2 k2 H5). destruct IHBounded2.\n      * assert (k2 == x = false) by (solve_Bounds e). rewrite H12. simpl. left.\n        assumption.\n      * destruct H11.  left. rewrite H11. simpl. subst. reflexivity.\nQed.\n\nLemma goJustLt_never_none: forall k k1 v1 m,\n  goJustLT k k1 v1 m <> None.\nProof.\n  intros. revert k k1 v1. induction m; intros.\n  - simpl. destruct (_GHC.Base.<=_ k0 k ). apply IHm1. apply IHm2.\n  - simpl. intro contra. discriminate contra.\nQed.\n\n(*Part 1 of the spec: If lookupLT returns a k1, v1 pair, then (k1, v1) is in the map\n  and k1 is the largest key smaller than k*)\nLemma lookupLT_spec_Some:\n  forall (m: Map e a) lb ub k (k1: e) v1, Bounded m lb ub ->\n  lookupLT k m = Some (k1, v1) ->\n  sem m k1 = Some v1 /\\ (_GHC.Base.<_  k1 k = true) /\\\n  (forall k2, (_GHC.Base.<_  k2 k = true) /\\ (k1 == k2 = false) /\\\n  sem m k2 <> None -> (_GHC.Base.<_  k2 k1 = true)).\nProof.\n  intros. rewrite <- lookupLT_equiv in H0. generalize dependent k. revert k1 v1. induction H; intros; split; intros.\n  - inversion H0.\n  - inversion H0.\n  - simpl in H5. simpl. destruct (_GHC.Base.<=_  k x) eqn : ?.\n    + apply IHBounded1 in H5. destruct H5. rewrite H5. simpl. reflexivity.\n    + assert ( _GHC.Base.<_ x k = true) by (order e).\n      pose proof (goJustLT_finds_upper_bound k x v s2 (Some x) ub k1 v1 H0 H6 H5).\n      destruct H7. specialize (H8 x).\n      pose proof (goJustLt_val_in_map k x v s2 (Some x) ub k1 v1 H0 H5).\n      pose proof goJustLT_bounded. specialize (H10 k x v s2 k1 v1 (Some x) ub x k H0 H6 H5).\n      destruct H10. assert (_GHC.Base.<=_ x k1 = true). apply H10. split. reflexivity. order e.\n      assert (sem s1 k1 = None). eapply sem_outside_above. eassumption. solve_Bounds e.\n      rewrite H13. simpl. destruct H9.\n      * assert (k1 == x = false) by (solve_Bounds e). rewrite H14. simpl. assumption.\n      * destruct H9. subst. rewrite H9. reflexivity.\n  - simpl in H5. destruct (_GHC.Base.<=_ k x) eqn : ?.\n    + simpl. specialize (IHBounded1 k1 v1 k H5). destruct IHBounded1. destruct H7. split.\n      assumption. intros. apply H8. destruct H9. destruct H10.\n      split. assumption. split. assumption. assert (k2 == x = false) by (order e).\n      assert (sem s2 k2 = None). eapply sem_outside_below. eassumption. solve_Bounds e.\n      rewrite H13 in H11. rewrite H12 in H11. simpl in H11. repeat (rewrite oro_None_r in H11).\n      assumption.\n    + assert (_GHC.Base.<_ x k = true) by (order e). split. eapply goJustLT_pres_smaller. apply H0.\n      apply H6. apply H5. intros. destruct H7. destruct H8. simpl in H9.\n      pose proof goJustLT_bounded. specialize (H10 k x v s2 k1 v1 (Some x) ub x k H0 H6 H5).\n      destruct H10. assert (_GHC.Base.<=_ x k1 = true). apply H10. split. reflexivity.\n      order e. destruct (compare k2 k1) eqn : ?.\n      order e.\n      order e.\n      assert (k2 == x = false) by (order e). rewrite H13 in H9. simpl in H9.\n      assert (sem s1 k2 = None). eapply sem_outside_above. eassumption. solve_Bounds e.\n      rewrite H14 in H9. simpl in H9. eapply goJustLT_finds_upper_bound.\n       apply H0. apply H6. apply H5. split; try(assumption); split; assumption.\nQed.\n\n(*Part 2: If lookupLT returns None, then every key in the map is smaller than k*)\nLemma lookupLT_spec_None:\n  forall (m: Map e a) lb ub k, Bounded m lb ub ->\n  lookupLT k m = None ->\n  (forall k2 v2, sem m k2 = Some v2 -> _GHC.Base.<=_ k k2 = true).\nProof.\n  intros. generalize dependent k2. generalize dependent k. revert v2. induction H; intros.\n  - inversion H1.\n  - rewrite <- lookupLT_equiv in H5. simpl in H5. destruct (_GHC.Base.<=_ k x) eqn : ?.\n    simpl in H6. destruct (sem s1 k2) eqn : ?.\n    * simpl in H6; inversion H6; subst. eapply IHBounded1. apply H5. apply Heqo.\n    * simpl in H6. destruct (k2 == x) eqn : ?.\n      -- order e.\n      -- simpl in H6. solve_Bounds e.\n    * assert (goJustLT k x v s2 <> None). apply goJustLt_never_none. rewrite H5 in H7.\n      contradiction.\nQed.\n\n(** ** Verification of [lookupLE] *)\nFixpoint goJustLE k (k1: e) v1 (m : Map e a) : option (e * a) :=\n  match m with\n  | Tip => Some (k1, v1)\n  | Bin sz k2 v2 l r => match compare k k2 with\n                        | Lt => goJustLE k k1 v1 l\n                        | Eq => Some (k2, v2)\n                        | Gt => goJustLE k k2 v2 r\n                        end\n  end.\n\nFixpoint lookupLE' k (m : Map e a) :=\n  match m with\n  | Tip => None\n  | Bin sz k1 v1 l r => match compare k k1 with\n                        | Lt => lookupLE' k l\n                        | Eq => Some (k1, v1)\n                        | Gt => goJustLE k k1 v1 r\n                        end\n  end.\n\nLemma lookupLE_equiv:\n  forall m k,\n  lookupLE' k m = lookupLE k m.\nProof.\n  intros. unfold lookupLE'. unfold lookupLE. unfold goJustLE. reflexivity.\nQed.\n\nLemma goJustLE_pres_smaller: forall k k1 v1 m k2 v2 lb ub,\n  Bounded m lb ub ->\n  _GHC.Base.<_ k1 k = true ->\n  goJustLE k k1 v1 m = Some (k2, v2) ->\n  _GHC.Base.<=_ k2 k = true.\nProof.\n  intros. generalize dependent k1. revert v1 v2 k2 k. induction H; intros.\n  - simpl in H1. inversion H1; subst. order e.\n  - simpl in H6. destruct (compare k x) eqn : ?.\n    + inversion H6; subst. order e.\n    + eapply IHBounded1. eassumption. eassumption.\n    + assert (_GHC.Base.<_ x k = true) by (order e). eapply IHBounded2. apply H7.\n      apply H6.\nQed.\n\nLemma goJustLE_bounded: forall k k1 v1 m k2 v2 lb ub l u,\n  Bounded m lb ub ->\n  _GHC.Base.<_ k1 k = true ->\n  goJustLE k k1 v1 m = Some (k2, v2) ->\n  (lb = Some l /\\ _GHC.Base.<=_ l k1 = true -> _GHC.Base.<=_ l k2 = true )\n  /\\ (ub = Some u /\\ _GHC.Base.<=_ k1 u = true -> _GHC.Base.<=_ k2 u = true).\nProof.\n  intros. generalize dependent k1. revert k v1 k2 v2 u l. induction H; intros.\n  - simpl in H1. inversion H1; subst. split; intros; subst; solve_Bounds e.\n  - simpl in H6. destruct (compare k x) eqn : ?.\n    + inversion H6; subst. split; intros. order e. destruct H3. subst. solve_Bounds e.\n    + split; intros; subst.  specialize (IHBounded1 _ _ _ _ u l _ H5 H6). destruct IHBounded1.\n       apply H3. apply H7. specialize (IHBounded1 _ _ _ _ x l  _ H5 H6). destruct IHBounded1.\n        destruct H7; subst. assert (Some x = Some x /\\ _GHC.Base.<=_ k1 x = true).\n        split. reflexivity. order e. apply H8 in H7.  assert (compare x u = Lt) by (solve_Bounds e).\n        order e.\n    + assert (_GHC.Base.<_ x k = true) by (order e).  split; intros; subst.\n      specialize (IHBounded2  _ _ _ _ u x _ H7 H6). destruct IHBounded2.\n      destruct H8; subst. assert (_GHC.Base.<=_ x k2 = true). apply H3. split. reflexivity.\n      order e. assert (_GHC.Base.<_ l x = true) by (solve_Bounds e). order e.\n      specialize (IHBounded2 _ _ _ _ u l _ H7 H6). destruct IHBounded2. apply H9.\n      split. apply H8. destruct H8. subst. solve_Bounds e.\nQed.\n\nLemma goJustLE_nothing_between: forall k k1 v1 m lb ub k2 v2,\n  Bounded m lb ub ->\n  _GHC.Base.<_ k1 k = true ->\n  goJustLE k k1 v1 m = Some (k2, v2) ->\n  (forall i, compare k2 i = Lt /\\ compare i k = Lt ->\n  sem m i = None).\nProof.\n  intros. generalize dependent i. generalize dependent k2. generalize dependent k1.\n  revert k v1 v2.\n  induction H; intros.\n  - reflexivity.\n  - simpl. simpl in H6. destruct (compare k x) eqn : ?.\n    + assert (i == x = false) by (order e). rewrite H8. assert (sem s2 i = None). {\n      eapply sem_outside_below. eassumption. solve_Bounds e. } rewrite H9.\n      simpl. repeat(rewrite oro_None_r). inversion H6; subst. eapply sem_outside_above.\n      eassumption. solve_Bounds e.\n    + assert (i == x = false) by (order e). rewrite H8. assert (sem s2 i = None). {\n      eapply sem_outside_below. eassumption. solve_Bounds e. } rewrite H9.\n      simpl. repeat(rewrite oro_None_r).  eapply IHBounded1. apply H5. apply H6.\n      assumption.\n    + assert (_GHC.Base.<_ x k = true) by (order e).\n      pose proof goJustLE_bounded. specialize (H9 _ _ _ _ _ _ _ _ x k H0 H8 H6).\n      destruct H9. assert (_GHC.Base.<=_ x k2 = true). apply H9. split. reflexivity.\n      order e. assert (_GHC.Base.<_ x i = true). order e. assert (sem s1 i = None).\n      eapply sem_outside_above. eassumption. solve_Bounds e. rewrite H13.\n      assert (i == x = false) by (order e). rewrite H14. simpl. eapply IHBounded2.\n      apply H8. apply H6. apply H7.\nQed.\n\nLemma goJustLE_finds_upper_bound: forall k k1 v1 m lb ub k2 v2,\n  Bounded m lb ub ->\n  _GHC.Base.<_ k1 k = true ->\n  goJustLE k k1 v1 m = Some (k2, v2) ->\n   (_GHC.Base.<=_  k2 k = true) /\\\n  (forall k3, (_GHC.Base.<_  k3 k = true) /\\ (k2 == k3 = false) /\\\n  sem m k3 <> None -> (_GHC.Base.<_  k3 k2 = true)).\nProof.\n  intros. pose proof (goJustLE_nothing_between k k1 v1 m lb ub k2 v2 H H0 H1).\n  split. eapply goJustLE_pres_smaller. apply H. apply H0. apply H1. intros.\n  specialize (H2 k3). destruct H3. destruct H4.\n  destruct (_GHC.Base.<_ k3 k2 ) eqn : ?.\n  - reflexivity.\n  - assert (sem m k3 = None). apply H2. split. order e. order e. contradiction.\nQed.\n\nLemma goJustLE_val_in_map: forall k k1 v1 m lb ub k2 v2,\n  Bounded m lb ub ->\n  goJustLE k k1 v1 m = Some (k2, v2) ->\n  sem m k2 = Some v2 \\/ ((k2 == k1 = true) /\\ v2 = v1).\nProof.\n  intros. generalize dependent k2. revert k k1 v1 v2. induction H; intros.\n  - simpl in H0. inversion H0; subst. right. split. apply Eq_Reflexive. reflexivity.\n  - simpl. simpl in H5. destruct (compare k x) eqn : ?.\n    + inversion H5; subst. assert (sem s1 k2 = None). eapply sem_outside_above.\n      eassumption. solve_Bounds e. rewrite H3. rewrite Eq_Reflexive. simpl.\n      left. reflexivity.\n    + specialize (IHBounded1 k k1 v1 v2 k2 H5). destruct IHBounded1.\n      * rewrite H6. simpl. left. reflexivity.\n      * right. apply H6.\n    + assert (_GHC.Base.<_ x k = true) by (order e).\n      pose proof goJustLE_bounded. specialize (H7 k x v s2 k2 v2 (Some x) ub x k H0 H6 H5).\n      destruct H7. assert (_GHC.Base.<=_ x k2 = true). apply H7. split. reflexivity. order e.\n      assert (sem s1 k2 = None). eapply sem_outside_above. eassumption. solve_Bounds e. rewrite H10.\n      simpl. specialize (IHBounded2 k x v v2 k2 H5). destruct IHBounded2.\n      * assert (k2 == x = false) by (solve_Bounds e). rewrite H12. simpl. left.\n        assumption.\n      * destruct H11.  left. rewrite H11. simpl. subst. reflexivity.\nQed.\n\nLemma goJustLE_never_none: forall k k1 v1 m,\n  goJustLE k k1 v1 m <> None.\nProof.\n  intros. revert k k1 v1. induction m; intros.\n  - simpl. destruct (compare k0 k) eqn : ?.\n    + intro contra. discriminate contra.\n    + apply IHm1.\n    + apply IHm2.\n  - simpl. intro contra. discriminate contra.\nQed.\n\n(*Part 1 of the spec: If lookupLT returns a k1, v1 pair, then (k1, v1) is in the map\n  and k1 is the largest key less than or equal to than k*)\nLemma lookupLE_spec_Some:\n  forall (m: Map e a) lb ub k (k1: e) v1, Bounded m lb ub ->\n  lookupLE k m = Some (k1, v1) ->\n  sem m k1 = Some v1 /\\ (_GHC.Base.<=_  k1 k = true) /\\\n  (forall k2, (_GHC.Base.<_  k2 k = true) /\\ (k1 == k2 = false) /\\\n  sem m k2 <> None -> (_GHC.Base.<_  k2 k1 = true)).\nProof.\n  intros. rewrite <- lookupLE_equiv in H0. generalize dependent k. revert k1 v1. induction H; intros; split; intros.\n  - inversion H0.\n  - inversion H0.\n  - simpl in H5. simpl. destruct (compare k x) eqn : ?.\n    + inversion H5; subst. assert (sem s1 k1 = None). eapply sem_outside_above. eassumption.\n      solve_Bounds e. rewrite H3. rewrite Eq_Reflexive. reflexivity.\n    + apply IHBounded1 in H5. destruct H5. rewrite H5. simpl. reflexivity.\n    + assert ( _GHC.Base.<_ x k = true) by (order e).\n      pose proof (goJustLE_finds_upper_bound k x v s2 (Some x) ub k1 v1 H0 H6 H5).\n      destruct H7. specialize (H8 x).\n      pose proof (goJustLE_val_in_map k x v s2 (Some x) ub k1 v1 H0 H5).\n      pose proof goJustLE_bounded. specialize (H10 k x v s2 k1 v1 (Some x) ub x k H0 H6 H5).\n      destruct H10. assert (_GHC.Base.<=_ x k1 = true). apply H10. split. reflexivity. order e.\n      assert (sem s1 k1 = None). eapply sem_outside_above. eassumption. solve_Bounds e.\n      rewrite H13. simpl. destruct H9.\n      * assert (k1 == x = false) by (solve_Bounds e). rewrite H14. simpl. assumption.\n      * destruct H9. subst. rewrite H9. reflexivity.\n  - simpl in H5. destruct (compare k x ) eqn : ?.\n    + inversion H5; subst. split. order e. intros. order e.\n    + simpl. specialize (IHBounded1 k1 v1 k H5). destruct IHBounded1. destruct H7. split.\n      assumption. intros. apply H8. destruct H9. destruct H10.\n      split. assumption. split. assumption. assert (k2 == x = false) by (order e).\n      assert (sem s2 k2 = None). eapply sem_outside_below. eassumption. solve_Bounds e.\n      rewrite H13 in H11. rewrite H12 in H11. simpl in H11. repeat (rewrite oro_None_r in H11).\n      assumption.\n    + assert (_GHC.Base.<_ x k = true) by (order e). split. eapply goJustLE_pres_smaller. apply H0.\n      apply H6. apply H5. intros. destruct H7. destruct H8. simpl in H9.\n      pose proof goJustLE_bounded. specialize (H10 k x v s2 k1 v1 (Some x) ub x k H0 H6 H5).\n      destruct H10. assert (_GHC.Base.<=_ x k1 = true). apply H10. split. reflexivity.\n      order e. destruct (compare k2 k1) eqn : ?.\n      order e.\n      order e.\n      assert (k2 == x = false) by (order e). rewrite H13 in H9. simpl in H9.\n      assert (sem s1 k2 = None). eapply sem_outside_above. eassumption. solve_Bounds e.\n      rewrite H14 in H9. simpl in H9. eapply goJustLE_finds_upper_bound.\n       apply H0. apply H6. apply H5. split; try(assumption); split; assumption.\nQed.\n\nLemma goJustLE_spec_eq: forall m lb ub k v k' v',\n  Bounded m lb ub ->\n  sem m k = Some v ->\n  (exists k1, k1 == k = true /\\ goJustLE k k' v' m = Some (k1, v)).\nProof.\n  intros. generalize dependent k. revert v k' v'. induction H; intros.\n  - inversion H0.\n  - simpl in H5. simpl. destruct (sem s1 k) eqn : ?.\n    + assert (compare k x = Lt) by (solve_Bounds e).\n      rewrite H6. apply IHBounded1. simpl in H5. inversion H5; subst. assumption.\n    + simpl in H5. destruct (k == x) eqn : ?. assert (compare k x = Eq) by (order e).\n      * rewrite H6. exists x. split. order e. inversion H5. reflexivity.\n      * simpl in H5. assert (compare k x = Gt) by (solve_Bounds e). rewrite H6.\n        apply IHBounded2. assumption.\nQed.\n\n(*Part 2: If the value is in the map, lookupLE returns it*)\nLemma lookupLE_spec_eq: forall (m: Map e a) lb ub k v,\n  Bounded m lb ub ->\n  sem m k = Some v ->\n  (exists k1, k1 == k = true /\\ lookupLE k m = Some (k1, v)).\nProof.\n  intros. generalize dependent k. revert v. induction H; intros.\n  - inversion H0.\n  - simpl in H5. rewrite <- lookupLE_equiv. simpl.\n    destruct (sem s1 k) eqn : ?.\n    + assert (compare k x = Lt) by (solve_Bounds e). rewrite H6. apply IHBounded1.\n      simpl in H5. inversion H5; subst. assumption.\n    + simpl in H5. destruct (k == x) eqn : ?.\n      * simpl in H5. exists x. split. order e. assert (compare k x = Eq) by (order e).\n        rewrite H6. inversion H5; subst. reflexivity.\n      * simpl in H5. assert (compare k x = Gt) by (solve_Bounds e). rewrite H6.\n        eapply goJustLE_spec_eq. eassumption. assumption.\nQed.\n\n(*Part 3: If lookupLT returns None, then every key in the map is smaller than k*)\nLemma lookupLE_spec_None:\n  forall (m: Map e a) lb ub k, Bounded m lb ub ->\n  lookupLE k m = None ->\n  (forall k2 v2, sem m k2 = Some v2 -> _GHC.Base.<_ k k2 = true).\nProof.\n  intros. generalize dependent k2. generalize dependent k. revert v2. induction H; intros.\n  - inversion H1.\n  - rewrite <- lookupLE_equiv in H5. simpl in H5. destruct (compare k x) eqn : ?.\n    + simpl in H6. order e.\n    + simpl in H6. destruct (sem s1 k2) eqn : ?.\n      * simpl in H6; inversion H6; subst. eapply IHBounded1. apply H5. apply Heqo.\n      * simpl in H6. destruct (k2 == x) eqn : ?.\n      -- order e.\n      -- simpl in H6. solve_Bounds e.\n    + assert (goJustLE k x v s2 <> None). apply goJustLE_never_none. rewrite H5 in H7.\n      contradiction.\nQed.\n\nEnd WF.\n", "meta": {"author": "antalsz", "repo": "hs-to-coq", "sha": "cd62a35fff22cb6022a8935581746df658264f0f", "save_path": "github-repos/coq/antalsz-hs-to-coq", "path": "github-repos/coq/antalsz-hs-to-coq/hs-to-coq-cd62a35fff22cb6022a8935581746df658264f0f/examples/containers/theories/MapProofs/LookupProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7074331350144198}}
{"text": "\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\n(** **** Exercise: 2 stars (double_plus) *)\nLemma double_plus : forall n, double n = n + n .\nProof.\n  intros n. induction n as [| n'].\n     simpl. reflexivity.\n    simpl. rewrite -> IHn'. rewrite <- plus_n_Sm.\n    reflexivity. Qed.\n(** [] *)\n", "meta": {"author": "jaredly", "repo": "coqdocs", "sha": "318eaa2bff51aa0946d448c497afbc347ed8ca36", "save_path": "github-repos/coq/jaredly-coqdocs", "path": "github-repos/coq/jaredly-coqdocs/coqdocs-318eaa2bff51aa0946d448c497afbc347ed8ca36/small.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7074331341377896}}
{"text": "Module Nats.\n\nFixpoint eqb (n m : nat) : bool :=\n    match n with\n    | O =>  match m with\n            | O => true\n            | S _ => false\n            end\n    | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n    end.\n\nNotation \"x =? y\" := (eqb x y) (at level 70).\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\nEnd Nats.\n\nModule Lists.\n\nImport Nats.\n\nNotation \"x :: xs\" := (cons x xs)(at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) .. ).\nNotation \"x ++ y\" := (app x y) (at level 60, right associativity).\n\nFixpoint rev {X: Type} (l: list X) : list X :=\n    match l with\n    | nil => nil\n    | x::xs => (rev xs) ++ [x]\n    end.\n\nFixpoint nth_err {X: Type} (l: list X) (n: nat) : option X :=\n    match l with\n    | [] => None\n    | x::xs => if n =? 0 then Some x else nth_err xs (pred n)\n    end.\n\nFixpoint filter {X: Type} (test: X -> bool) (l: list X) : list X :=\n    match l with\n    | [] => []\n    | x::xs => if test x \n               then x :: (filter test xs)\n               else filter test xs\n    end.\n\nEnd Lists.\n\nImport Lists.\nImport Nats.\n\nTheorem inj_ex1: forall (n m o: nat),\n    [n;m] = [o;o] -> [n] = [m].\nProof.\n    intros n m o H.\n    injection H.\n    intros H1 H2.\n    rewrite H1.\n    rewrite H2.\n    reflexivity.\nQed.\n\nFixpoint eqb (n m : nat) : bool :=\n    match n with\n    | O =>  match m with\n            | O => true\n            | S _ => false\n            end\n    | S n' => match m with\n            | O => false\n            | S m' => eqb n' m'\n            end\n    end.\n\nLemma eqs: forall n m: nat,\n    eqb (S n) (S m) = eqb n m.\nProof.\n      reflexivity.\nQed.\n\nTheorem eqbt: forall n m, eqb n m = true -> n = m.\nProof.\n    intro n. induction n as [|n' IHn'].\n    - intros m eq. destruct m as [| m'].\n      reflexivity.\n      discriminate eq.\n    - intros m eq. destruct m as [| m'].\n      discriminate eq.\n      rewrite -> eqs in eq.\n      rewrite -> IHn' with m'.\n      reflexivity.\n      apply eq.\nQed.\n\nTheorem nea: forall (n: nat) (X: Type) (l: list X),\n    length l = n -> nth_err l n = None.\nProof.\n    intros n X l.\n    generalize dependent n.\n    induction l as [|x xs IHxs].\n    - intro n. destruct n as [| n'].\n      + reflexivity.\n      + intro H.\n        discriminate H.\n    - intro n. destruct n as [| n'].\n      + intro H.\n        discriminate H.\n      + simpl. intro H.\n        inversion H.\n        apply IHxs.\n        reflexivity.\nQed.\n\nFixpoint combine {X Y: Type} (lx: list X) (ly: list Y)\n    : list (X * Y) :=\n    match lx, ly with\n    | [], _ => []\n    | _, [] => []\n    | x::tx, y::ty => (x, y) :: (combine tx ty)\n    end.\n\nFixpoint split {X Y: Type} (l: list (X * Y))\n    : (list X) * (list Y) :=\n    match l with\n    | [] => ([], [])\n    | (x, y) :: ls => match (split ls) with\n                    | (p, q) => (x :: p, y :: q)\n    end\n    end.\n\nLemma feq: forall {X Y: Type} (x y : X) (f: X -> Y),\n    x = y -> f x = f y. Admitted.\n\nLemma rmcons: forall {X: Type} (lx ly: list X) (x: X),\n    lx = ly -> x::lx = x::ly. Admitted.\n\nTheorem comb_sp: forall X Y (l: list (X * Y)) l1 l2,\n    split l = (l1, l2) ->\n    combine l1 l2 = l.\nProof.\n    intros X Y l.\n    induction l as [| x xs IHx].\n    - intros l1 l2.\n      intro H.\n      inversion H.\n      reflexivity.\n    - destruct x as [a b].\n      simpl.\n      destruct (split xs) as [lx ly].\n      intros l1 l2 H.\n      injection H as H1 H2.\n      rewrite <- H1.\n      rewrite <- H2.\n      simpl.\n      apply rmcons.\n      apply IHx.\n      reflexivity.\nQed.\n\nDefinition sillyfun1 (n: nat) : bool :=\n    if n =? 3 then true\n    else if n =? 5 then true\n    else false.\n\nLemma eqb_true: forall (n m: nat), n =? m = true -> n = m. Admitted.\n\nTheorem sillyfun1_odd: forall (n: nat),\n    sillyfun1 n = true -> oddb n = true.\nProof.\n    intros n eq.\n    unfold sillyfun1 in eq.\n    destruct (n =? 3) eqn: Heqe3.\n    - apply eqb_true in Heqe3.\n      rewrite -> Heqe3.\n      reflexivity.\n    - destruct (n =? 5) eqn: Heqe5.\n      + apply eqb_true in Heqe5.\n        rewrite -> Heqe5.\n        reflexivity.\n      + discriminate eq.\nQed.\n\nTheorem eqbsym: forall (n m: nat),\n    (n =? m) = (m =? n).\nProof.\n    intros n.\n    induction n as [| n' IHn].\n    - destruct m.\n      reflexivity.\n      reflexivity.\n    - destruct m.\n      reflexivity.\n      simpl.\n      apply IHn.\nQed.\n\nLemma eqt: forall n: nat, n =? n = true.\nProof.\n    intro n.\n    induction n as [| n' IHn].\n    reflexivity.\n    simpl.\n    apply IHn.\nQed.\n\nTheorem eqb_trans: forall n m p,\n    n =? m = true ->\n    m =? p = true ->\n    n =? p = true.\nProof.\n    intros n m p.\n    intros eq1 eq2.\n    apply eqb_true in eq1.\n    apply eqb_true in eq2.\n    rewrite -> eq1.\n    rewrite -> eq2.\n    apply eqt.\nQed.\n\nTheorem filter_exe: forall (X: Type) (test: X -> bool) (x: X) (l lf: list X),\n    filter test l = x::lf ->\n    test x = true.\nProof.\n    intros.\n    generalize dependent x.\n    generalize dependent lf.\n    induction l as [| y ys IHy].\n    - intros. induction lf.\n      + discriminate H.\n      + discriminate H.\n    - intros.\n      inversion H.\n      destruct (test y) eqn: P.\n      + injection H1 as Ha Hb.\n        rewrite <- Ha.\n        apply P.\n      + apply IHy in H1.\n        apply H1.\nQed.\n", "meta": {"author": "Meowcolm024", "repo": "sf", "sha": "8ec734274600d60b0b7e905bb3d861779031bee8", "save_path": "github-repos/coq/Meowcolm024-sf", "path": "github-repos/coq/Meowcolm024-sf/sf-8ec734274600d60b0b7e905bb3d861779031bee8/exercises/exe3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7074331274749002}}
{"text": "Require Import Coquelicot.Coquelicot.\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Import Coq.Reals.Rbase.\nRequire Import Coq.Reals.Rfunctions.\nRequire Import List.\nRequire Import EquivDec Nat Omega Lra.\n\nRequire Import LibUtils ListAdd RealAdd.\nImport ListNotations.\n\nLocal Open Scope R.\n(* The standard library defines sum_f_R0 as an inclusive sum from 0.\n   It then defines infinite_sum in terms of it.\n   \n   Inclusive ranges are much harder to reason about formulate lemmas than exclusive (end) ranges,       \n   since they don't allow for empty ranges.\n\n   infinite summations don't really care, so we formulate the nicer version here,\n   along with an alternative infinite_sum that is proven identical to the original\n *)\n\nSection sum'.\n  Fixpoint sum_f_R0' (f : nat -> R) (N : nat) {struct N} : R :=\n    match N with\n    | 0%nat => 0%R\n    | S i => sum_f_R0' f i + f i\n    end.\n\n  Lemma sum_f_R0_sum_f_R0' f N :\n    sum_f_R0 f N = sum_f_R0' f (S N).\n  Proof.\n    induction N; simpl.\n    - lra.\n    - rewrite IHN.\n      simpl; trivial.\n  Qed.\n\n  Lemma sum_f_R0'_ext (f1 f2:nat->R) n :\n    (forall x, (x < n)%nat -> f1 x = f2 x) ->\n    sum_f_R0' f1 n = sum_f_R0' f2 n.\n  Proof.\n    intros eqq.\n    induction n; simpl.\n    - trivial. \n    - rewrite eqq by omega.\n      rewrite IHn; trivial.\n      intros; apply eqq.\n      omega.\n  Qed.\n\n  Lemma sum_f_R0'_split f n m :\n    (m <= n)%nat ->\n    sum_f_R0' f n =\n    sum_f_R0' f m +\n    sum_f_R0' (fun x => f (x+m)%nat) (n-m).\n  Proof.\n    intros lem.\n    induction n; simpl.\n    - assert (m = 0)%nat by omega.\n      subst; simpl; lra.\n    - destruct (m == S n); unfold equiv, complement in *.\n      + subst.\n        simpl.\n        rewrite Rplus_assoc.\n        f_equal.\n        replace (n - n)%nat with 0%nat by omega.\n        simpl.\n        lra.\n      + rewrite IHn by omega.\n        rewrite Rplus_assoc.\n        f_equal.\n        destruct m; simpl.\n        * replace (n-0)%nat with n by omega.\n          replace (n+0)%nat with n by omega.\n          trivial.\n        * replace (n - m)%nat with (S (n - S m))%nat by omega.\n          simpl.\n          f_equal.\n          f_equal.\n          omega.\n  Qed.\n\n  Lemma sum_f_R0'_split_on f n m :\n    (m < n)%nat ->\n    sum_f_R0' f n =\n    sum_f_R0' f m +\n    f m + \n    sum_f_R0' (fun x => f (x+S m)%nat) (n- S m).\n  Proof.\n    intros ltm.\n    rewrite (sum_f_R0'_split f n (S m) ltm).\n    simpl; trivial.\n  Qed.\n\n  Lemma sum_f_R0_peel f n :\n    sum_f_R0 f (S n) = sum_f_R0 f n + f (S n).\n  Proof.\n    simpl; trivial.\n  Qed.\n\n  Lemma sum_f_R0_ext (f1 f2:nat->R) n :\n    (forall x, (x <= n)%nat -> f1 x = f2 x) ->\n    sum_f_R0 f1 n = sum_f_R0 f2 n.\n  Proof.\n    intros eqq.\n    induction n; simpl.\n    - apply eqq; omega.\n    - rewrite eqq by omega.\n      rewrite IHn; trivial.\n      intros; apply eqq.\n      omega.\n  Qed.\n\n  Lemma sum_f_R0_split f n m:\n    (m < n)%nat ->\n    sum_f_R0 f n =\n    sum_f_R0 f m +\n    sum_f_R0 (fun x => f (x+S m))%nat (n-S m).\n  Proof.\n    intros ltm.\n    induction n; simpl.\n    - omega.\n    - destruct (m == n); unfold equiv, complement in *.\n      + subst.\n        rewrite Nat.sub_diag; simpl; trivial.\n      + rewrite IHn by omega.\n        rewrite Rplus_assoc.\n        f_equal.\n        replace (n - m)%nat with (S (n - S m))%nat by omega.\n        simpl.\n        f_equal.\n        f_equal.\n        omega.\n  Qed.\n\n  Lemma sum_f_R0_split_on f n m:\n    (S m < n)%nat ->\n    sum_f_R0 f n =\n    sum_f_R0 f m +\n    f (S m) + \n    sum_f_R0 (fun x => f (x+S (S m)))%nat (n-S (S m)).\n  Proof.\n    intros ltm.\n    rewrite (sum_f_R0_split f n m) by omega.\n    repeat rewrite Rplus_assoc.\n    f_equal.\n    rewrite (sum_f_R0_split  (fun x : nat => f (x + S m)%nat) (n - S m) 0) by omega.\n    simpl.\n    f_equal.\n    replace (n - S (S m))%nat with (n - S m - 1)%nat by omega.\n    apply sum_f_R0_ext.\n    intros.\n    f_equal.\n    omega.\n  Qed.\n\n  Lemma sum_f_R0'_chisel f N n :\n  (n < N)%nat ->\n  sum_f_R0' f N = sum_f_R0'  (fun x : nat => if equiv_dec x n then 0 else f x) N + (f n).\nProof.\n  Proof.\n    intros ltm.\n    repeat rewrite (sum_f_R0'_split_on _ N n ltm).\n    destruct (n == n); unfold equiv, complement in *; subst; [| intuition].\n    rewrite Rplus_0_r.\n    rewrite Rplus_comm.\n    repeat rewrite <- Rplus_assoc.\n    f_equal.\n    rewrite Rplus_comm.\n    f_equal.\n    + apply sum_f_R0'_ext; intros.\n      destruct (x == n);  unfold equiv, complement in *; subst; [| intuition].\n      omega.\n    + apply sum_f_R0'_ext; intros.\n      destruct (x + S n == n)%nat;  unfold equiv, complement in *; subst; [| intuition].\n      omega.\n  Qed.\n\n  Lemma sum_f_R0'_const c n: sum_f_R0' (fun _ : nat => c) n = (c * INR n)%R.\n  Proof.\n    induction n; simpl.\n    - lra.\n    - rewrite IHn.\n      destruct n; simpl; lra.\n  Qed.\n\n    \n  Lemma sum_f'_as_fold_right f (n:nat) s :\n    sum_f_R0' (fun x : nat => f (x + s)%nat) n = fold_right (fun a b => f a + b) 0 (seq s n).\n  Proof.\n    revert s.\n    induction n; simpl; trivial.\n    intros.\n    rewrite (IHn s).\n    destruct n; [simpl; lra | ].\n    replace (seq s (S n)) with ([s]++seq (S s) n) by (simpl; trivial).\n    rewrite seq_Sn.\n    repeat rewrite fold_right_app.\n    simpl.\n    rewrite (fold_right_plus_acc _ (f (S (s + n)) + 0)).\n    rewrite Rplus_assoc.\n    f_equal.\n    f_equal.\n    rewrite Rplus_0_r.\n    f_equal.\n    omega.\n  Qed.\n\n  Lemma sum_f_R0'_as_fold_right f (n:nat) :\n    sum_f_R0' f n = fold_right (fun a b => f a + b) 0 (seq 0 n).\n  Proof.\n    generalize (sum_f'_as_fold_right f n 0); simpl; intros HH.\n    rewrite <- HH.\n    apply sum_f_R0'_ext.\n    intros.\n    f_equal.\n    omega.\n  Qed.\n\n  Lemma sum_f_R0'_plus f1 f2 n :\n    sum_f_R0' (fun x => f1 x + f2 x) n = sum_f_R0' f1 n + sum_f_R0' f2 n.\n  Proof.\n    induction n; simpl; [lra | ].\n    rewrite IHn.\n    lra.\n  Qed.\n\n  Lemma sum_f_R0'_mult_const f1 n c :\n    sum_f_R0' (fun x => c * f1 x) n = c * sum_f_R0' f1 n.\n  Proof.\n    induction n; simpl; [lra | ].\n    rewrite IHn.\n    lra.\n  Qed.\n\n  Lemma sum_f_R0'_le f n :\n    (forall n, (0 <= f n)) ->\n    0 <= sum_f_R0' f n.\n  Proof.\n    intros fpos.\n    induction n; simpl.\n    - lra.\n    - specialize (fpos n).\n      lra.\n  Qed.\n\n  Lemma sum_f_R0'_plus_n f n1 n2 : sum_f_R0' f (n1 + n2) =\n                                   sum_f_R0' f n1 +\n                                   sum_f_R0' (fun x => f (n1+x))%nat n2.\n  Proof.\n    repeat rewrite sum_f_R0'_as_fold_right.\n    rewrite seq_plus.\n    rewrite fold_right_app.\n    rewrite fold_right_plus_acc.\n    simpl.\n    rewrite (seq_shiftn_map n1).\n    rewrite fold_right_map.\n    trivial.\n  Qed.\n\n  Lemma sum_f_R0'_le_f (f g:nat->R) n :\n    (forall i, (i < n)%nat -> f i <= g i) ->\n    sum_f_R0' f n <= sum_f_R0' g n.\n  Proof.\n    induction n; simpl.\n    - lra.\n    - intros fa.\n      apply Rplus_le_compat; auto.\n  Qed.        \n\nEnd sum'.\n\nSection inf_sum'.\n\n  Definition infinite_sum' (s : nat -> R) (l : R) : Prop\n    := forall eps : R,\n      eps > 0 ->\n      exists N : nat,\n        forall n : nat,\n          (n >= N)%nat ->\n          R_dist (sum_f_R0' s n) l < eps.\n\n  Theorem infinite_sum_infinite_sum' (s : nat -> R) (l : R) :\n    infinite_sum s l <-> infinite_sum' s l.\n  Proof.\n    unfold infinite_sum, infinite_sum'.\n    split; intros H.\n    - intros eps epsgt.\n      destruct (H eps epsgt) as [N Nconv].\n      exists (S N); intros n ngt.\n      destruct n.\n      + omega.\n      + rewrite <- sum_f_R0_sum_f_R0'.\n        apply Nconv.\n        omega.\n    - intros eps epsgt.\n      destruct (H eps epsgt) as [N Nconv].\n      exists N; intros n ngt.\n      rewrite sum_f_R0_sum_f_R0'.\n      apply Nconv.\n      omega.\n  Qed.\n\n  Lemma infinite_sum'_ext (s1 s2 : nat -> R) (l : R) :\n    (forall x, s1 x = s2 x) ->\n    infinite_sum' s1 l <-> infinite_sum' s2 l.\n  Proof.\n    intros eqq.\n    unfold infinite_sum'.\n    split; intros H eps eps_gt\n    ; destruct (H eps eps_gt) as [N Nconv]\n    ; exists N; intros n0 n0_ge\n    ; specialize (Nconv n0 n0_ge)\n    ; erewrite sum_f_R0'_ext; eauto.\n  Qed.    \n    \n\n  Lemma infinite_sum'_prefix s l n :\n    infinite_sum' s (l + (sum_f_R0' s n)) <->\n    infinite_sum' (fun x => s (x + n))%nat l.\n  Proof.\n    unfold infinite_sum'.\n    split; intros H\n    ; intros eps eps_gt\n    ; specialize (H eps eps_gt)\n    ; destruct H as [N Nconv].\n    - exists N\n      ; intros n0 n0_ge.\n      specialize (Nconv (n + n0)%nat).\n      cut_to Nconv; [ | omega].\n      replace (R_dist (sum_f_R0' (fun x : nat => s (x + n)%nat) n0) l) with\n            ( R_dist (sum_f_R0' s (n + n0)) (l + sum_f_R0' s n)); trivial.\n      unfold R_dist.\n      rewrite (sum_f_R0'_split s (n+n0) n) by omega.\n      replace ((n + n0 - n)%nat) with n0 by omega.\n      f_equal.\n      lra.\n    - exists (N+n)%nat\n      ; intros n0 n0_ge.\n      specialize (Nconv (n0-n)%nat).\n      cut_to Nconv; [ | omega].\n      replace (R_dist (sum_f_R0' s n0) (l + sum_f_R0' s n))\n                      with (R_dist (sum_f_R0' (fun x : nat => s (x + n)%nat) (n0 - n)) l); trivial.\n      unfold R_dist.\n      rewrite (sum_f_R0'_split s n0 n) by omega.\n      f_equal.\n      lra.\n  Qed.\n    \n    Lemma infinite_sum'_split n s l :\n      infinite_sum' s l <->\n      infinite_sum' (fun x => s (x + n))%nat (l - (sum_f_R0' s n)).\n    Proof.\n      rewrite <- (infinite_sum'_prefix s (l - (sum_f_R0' s n)) n).\n      replace (l - sum_f_R0' s n + sum_f_R0' s n) with l by lra.\n      tauto.\n    Qed.\n\n    (*\n    Lemma infinite_sum'_unique_half f l1 l2 :\n      infinite_sum' f l1 ->\n      infinite_sum' f l2 ->\n      l2 <= l1 ->\n      l1 = l2.\n    Proof.\n      unfold infinite_sum'; intros inf1 inf2 le.\n      destruct (Req_dec (l1 - l2) 0); [lra | ].\n      assert (gt0:(l1 - l2) / 2 > 0) by lra.\n      specialize (inf1 _ gt0).\n      destruct inf1 as [N1 inf1].\n      specialize (inf2 _ gt0).\n      destruct inf2 as [N2 inf2].\n      specialize (inf1 (max N1 N2)).\n      specialize (inf2 (max N1 N2)).\n\n      l2 - x < (l1 - l2) / 2\n                         l1 - x < (l1 - l2) / 2k\n      \n     *)\n\n    Lemma R_dist_too_small_impossible_lt r l1 l2 :\n      l1 < l2 ->\n      R_dist r l1 < R_dist l1 l2 / 2 ->\n      R_dist r l2 < R_dist l1 l2 / 2 -> False.\n    Proof.\n      intros ltl inf1 inf2.\n      generalize (Rplus_lt_compat _ _ _ _ inf1 inf2); intros ltt.\n      replace (R_dist l1 l2 / 2 + R_dist l1 l2 / 2) with (R_dist l1 l2) in ltt by lra.\n      rewrite (R_dist_sym r l1) in ltt.\n      generalize (R_dist_tri l1 l2 r); intros.\n      lra.\n    Qed.\n             \n    Lemma R_dist_too_small_impossible_neq r l1 l2 :\n      l1 <> l2 ->\n      R_dist r l1 < R_dist l1 l2 / 2 ->\n      R_dist r l2 < R_dist l1 l2 / 2 -> False.\n    Proof.\n      intros neq inf1 inf2.\n      destruct (Rlt_le_dec l1 l2).\n      - eapply R_dist_too_small_impossible_lt; eauto.\n      - destruct r0.\n        + rewrite (R_dist_sym l1 l2) in * .\n          eapply R_dist_too_small_impossible_lt; eauto.\n        + intuition.\n    Qed.\n                                                     \n    Lemma infinite_sum'_unique {f l1 l2} :\n      infinite_sum' f l1 ->\n      infinite_sum' f l2 ->\n      l1 = l2.\n    Proof.\n      unfold infinite_sum'; intros inf1 inf2.\n      destruct (Req_dec (l1 - l2) 0); [lra | ].\n      generalize (Rabs_pos_lt _ H); intros gt0.\n      apply Rlt_gt in gt0.\n      assert (gt02:R_dist l1  l2 / 2 > 0) by (unfold R_dist; lra).\n      specialize (inf1 _ gt02).\n      specialize (inf2 _ gt02).\n      destruct inf1 as [N1 inf1].\n      destruct inf2 as [N2 inf2].\n      specialize (inf1 (max N1 N2)).\n      specialize (inf2 (max N1 N2)).\n      cut_to inf1; [ | apply Nat.le_max_l].\n      cut_to inf2; [ | apply Nat.le_max_r].\n      revert inf1 inf2.\n      generalize (sum_f_R0' f (max N1 N2)); intros.\n      eelim R_dist_too_small_impossible_neq; try eapply inf1; eauto.\n      lra.\n    Qed.\n\n    Lemma infinite_sum'_const_shift {c d} :\n      infinite_sum' (fun _ => c) d ->\n      (infinite_sum' (fun _ => c) (d+c)).\n    Proof.\n      intros.\n      apply (infinite_sum'_split 1  (fun _ => c) (d+c)).\n      simpl.\n      replace (d + c - (0 + c)) with d; trivial.\n      lra.\n    Qed.\n\n    Lemma infinite_sum'_const0 {d} :\n      infinite_sum' (fun _ : nat => 0) d ->\n      d = 0.\n    Proof.\n      unfold infinite_sum'; intros HH.\n      destruct (Req_dec d 0); trivial.\n      assert (gt0:Rabs d/2>0).\n      {\n        generalize (Rabs_pos_lt d H).\n        lra.\n      }\n      specialize (HH _ gt0).\n      destruct HH as [N Nconv].\n      specialize (Nconv N).\n      cut_to Nconv; [ | left; trivial].\n      rewrite sum_f_R0'_const in Nconv.\n      unfold R_dist in Nconv.\n      replace (0 * INR N - d) with (- d) in Nconv by lra.\n      rewrite Rabs_Ropp in Nconv.\n      lra.\n    Qed.\n\n    Lemma infinite_sum'_const1 {c d} :\n      infinite_sum' (fun _ => c) d -> c = 0.\n    Proof.\n      intros inf1.\n      generalize (infinite_sum'_const_shift inf1); intros inf2.\n      generalize (infinite_sum'_unique inf1 inf2); intros eqq.\n      lra.\n    Qed.\n\n    Lemma infinite_sum'_const {c d} :\n      infinite_sum' (fun _ => c) d -> c = 0 /\\ d = 0.\n    Proof.\n      intros inf1.\n      generalize (infinite_sum'_const1 inf1); intros; subst.\n      generalize (infinite_sum'_const0 inf1); intros; subst.\n      tauto.\n    Qed.\n\n    Lemma infinite_sum'_const2 {c d} :\n      infinite_sum' (fun _ => c) d -> d = 0.\n    Proof.\n      intros inf1.\n      generalize (infinite_sum'_const inf1); tauto.\n    Qed.\n\n  Hint Resolve Nat.le_max_l Nat.le_max_r : arith.\n    \n  Lemma infinite_sum'_plus {f1 f2} {sum1 sum2} :\n    infinite_sum' f1 sum1 ->\n    infinite_sum' f2 sum2 ->\n    infinite_sum' (fun x => f1 x + f2 x) (sum1 + sum2).\n  Proof.\n    intros inf1 inf2 ε εpos.\n    destruct (inf1 (ε/2)) as [N1 H1]\n    ; [lra | ].\n    destruct (inf2 (ε/2)) as [N2 H2]\n    ; [lra | ].\n\n    exists (max N1 N2).\n    intros n ngt.\n\n    specialize (H1 n).\n    cut_to H1; [ | apply (le_trans _ (max N1 N2)); auto with arith].\n    specialize (H2 n).\n    cut_to H2; [ | apply (le_trans _ (max N1 N2)); auto with arith].\n\n    rewrite sum_f_R0'_plus.\n    generalize (R_dist_plus (sum_f_R0' f1 n) sum1 (sum_f_R0' f2 n) sum2); intros.\n    lra.\n  Qed.\n\n  Lemma infinite_sum'0 : infinite_sum' (fun _ : nat => 0) 0.\n  Proof.\n    intros ε εgt.\n    exists 0%nat.\n    intros.\n    rewrite sum_f_R0'_const.\n    replace (0 * INR n) with 0 by lra.\n    rewrite R_dist_eq.\n    lra.\n  Qed.\n        \n  Lemma infinite_sum'_mult_const {f1} {sum1} c :\n    infinite_sum' f1 sum1 ->\n    infinite_sum' (fun x => c * f1 x) (c * sum1).\n  Proof.\n    intros inf1.\n    destruct (Req_dec c 0).\n    - subst.\n      rewrite (infinite_sum'_ext _ (fun _ => 0)) by (intros; lra).\n      replace (0 * sum1) with 0 by lra.\n      apply infinite_sum'0.\n    - intros ε εpos.\n      assert (Rabs c > 0) by (apply Rabs_pos_lt; trivial).\n      destruct (inf1 (ε/ (Rabs c))) as [N1 H1].\n      + apply Rdiv_lt_0_compat; lra.\n      + exists N1.\n        intros n ngt.\n        specialize (H1 n ngt).\n        rewrite sum_f_R0'_mult_const.\n        rewrite R_dist_mult_l.\n        apply (Rmult_lt_compat_l (Rabs c)) in H1; [ | lra].\n        replace ( Rabs c * (ε / Rabs c)) with ε in H1; trivial.\n        unfold Rdiv.\n        rewrite Rmult_comm.\n        rewrite Rmult_assoc.\n        rewrite (Rmult_comm (/ Rabs c)).\n        rewrite <- Rmult_assoc.\n        rewrite Rinv_r_simpl_l; trivial.\n        lra.\n  Qed.\n     \n  Lemma Rabs_pos_plus_lt x y :\n    x > 0 ->\n    y > 0 ->\n    y < Rabs (x + y).\n  Proof.\n    intros.\n    rewrite Rabs_right; lra.\n  Qed.\n\n  Lemma infinite_sum'_pos f sum :\n    infinite_sum' f sum ->\n    (forall n, (0 <= f n)) ->\n    0 <= sum.\n  Proof.\n    intros inf fpos.\n    destruct (Rge_dec sum 0); [ lra | ].\n    red in inf.\n    apply Rnot_ge_lt in n.\n    destruct (inf (- sum)); [ lra | ].\n    specialize (H x).\n    cut_to H; [ | omega].\n    unfold R_dist in H.\n    destruct (Req_dec (sum_f_R0' f x) 0).\n    - rewrite H0 in H.\n      replace (0 - sum) with (- sum) in H by lra.\n      rewrite Rabs_right in H by lra.\n      lra.\n    - generalize (Rabs_pos_plus_lt (sum_f_R0' f x ) (- sum)); intros HH.\n      cut_to HH.\n      + eelim Rlt_irrefl.\n        eapply Rlt_trans; eauto.\n      + generalize (sum_f_R0'_le f x fpos); intros HH2.\n        lra.\n      + lra.\nQed.\n\n  Lemma infinite_sum'_le f1 f2 sum1 sum2 :\n    infinite_sum' f1 sum1 ->\n    infinite_sum' f2 sum2 ->\n    (forall n, (f1 n <= f2 n)) ->\n    sum1 <= sum2.\n  Proof.\n    intros inf1 inf2 fle.\n\n    generalize (infinite_sum'_mult_const (-1)%R inf1); intros ninf1.\n    generalize (infinite_sum'_plus inf2 ninf1); intros infm.\n    apply infinite_sum'_pos in infm.\n    - lra.\n    - intros.\n      specialize (fle n).\n      lra.\n  Qed.    \n  \nEnd inf_sum'.\n\nSection harmonic.\n\n  Lemma pow_le1 n : (1 <= 2 ^ n)%nat.\n  Proof.\n    induction n; simpl; omega.\n  Qed.\n\n  Lemma Sle_mult_gt1 a n :\n    (n > 0)%nat ->\n    (a > 1)%nat ->\n    (S n <= a * n)%nat.\n  Proof.\n    destruct a; try omega.\n    destruct a; try omega.\n    intros.\n    simpl.\n    destruct n; simpl; try omega.\n    apply le_n_S.\n    rewrite plus_comm.\n    apply le_n_S.\n    fold add.\n    rewrite <- plus_assoc.\n    apply Nat.le_add_r.\n  Qed.\n\n  Lemma pow_exp_gt a b :\n    (a > 1)%nat ->\n    (a ^ b > b)%nat.\n  Proof.\n    intros neq.\n    induction b; simpl.\n    - omega.\n    - apply gt_n_S in IHb.\n      eapply le_gt_trans; try eassumption.\n      apply Sle_mult_gt1; omega. \n  Qed.      \n  Lemma sum_f_R0'_eq2 n :\n    sum_f_R0' (fun _:nat => 1 / INR (2^(S n))) (2^n)%nat = 1/2.\n  Proof.\n    intros.\n    rewrite sum_f_R0'_const.\n    replace (2 ^ S n)%nat with (2 * 2 ^ n)%nat by reflexivity.\n    rewrite mult_INR.\n    unfold Rdiv.\n    rewrite Rinv_mult_distr.\n    - repeat rewrite Rmult_assoc.\n      rewrite <- Rinv_l_sym.\n      + simpl; lra.\n      + apply INR_nzero_eq.\n        apply Nat.pow_nonzero.\n        omega.\n    - simpl; lra.\n    - apply INR_nzero_eq.\n      apply Nat.pow_nonzero.\n      omega.\n  Qed.\n  \n  Lemma sum_f_R0'_bound2 (n:nat) : sum_f_R0' (fun i:nat => 1 / INR (S i)) (2^n)%nat >= 1+(INR n)/2.\n  Proof.\n    intros.\n    induction n.\n    - simpl; lra.\n    - rewrite S_INR.\n      simpl pow.\n      rewrite sum_f_R0'_plus_n.\n      replace ( 1 + (INR n + 1) / 2) with ( 1 + INR n / 2 + 1 / 2) by lra.\n      apply Rplus_ge_compat; trivial.\n      rewrite Nat.add_0_r.\n      clear.\n      eapply Rge_trans; [ | right; apply (sum_f_R0'_eq2 n)].\n      apply Rle_ge.\n      apply sum_f_R0'_le_f; intros.\n      unfold Rdiv.\n      apply Rmult_le_compat_l; [ lra | ].\n      apply Rinv_le_contravar.\n      + apply INR_zero_lt.\n        omega.\n      + apply le_INR.\n        simpl.\n        omega.\n  Qed.\n\n  Lemma harmonic_diverges' l : ~ infinite_sum' (fun i:nat => 1 / INR (S i)) l.\n  Proof.\n    intros inf.\n    specialize (inf 1).\n    cut_to inf; try lra.\n    destruct inf as [N Npf].\n    specialize (Npf (2^(2*(N + Z.to_nat (up l))))%nat).\n    cut_to Npf.\n    - generalize (sum_f_R0'_bound2 (2 * (N + Z.to_nat (up l)))); intros sle.\n      rewrite mult_INR in sle.\n      unfold Rdiv in sle.\n      rewrite Rinv_r_simpl_m in sle by (simpl; lra).\n      unfold R_dist in Npf.\n      apply Rabs_def2 in Npf.\n      destruct Npf as [Npf1 Npf2].\n      assert (oops:INR (N + Z.to_nat (up l)) < l) by lra.\n      rewrite plus_INR in oops.\n      assert (lgt:l > 0).\n      { eapply Rle_lt_trans; try eapply oops.\n        apply Rplus_le_le_0_compat\n        ; apply pos_INR.\n      }\n      rewrite INR_up_pos in oops by lra.\n      destruct (archimed l).\n      generalize (pos_INR N).\n      lra.\n    - rewrite Nat.pow_mul_r.\n      simpl.\n      rewrite NPeano.Nat.pow_add_r.\n      unfold ge.\n      replace N with (N * 1)%nat at 1 by omega.\n      apply mult_le_compat.\n      + generalize (pow_exp_gt 4 N)\n        ; omega.\n      + generalize (Z.to_nat (up l)); intros n.\n        destruct n; simpl.\n        * omega.\n        * generalize (pow_exp_gt 4 n); omega.\n  Qed.\n\n  \n  Definition diverges (f:nat->R)\n    := forall l, ~ infinite_sum f l.\n  \n  Theorem harmonic_diverges : diverges (fun i:nat => 1 / INR (S i)).\n  Proof.\n    intros l inf.\n    apply infinite_sum_infinite_sum' in inf.\n    eapply harmonic_diverges'; eauto.\n  Qed.\n\nEnd harmonic.\n\nSection coquelicot.\nLemma infinite_sum_is_lim_seq (f:nat->R) (l:R) : is_lim_seq (fun i => sum_f_R0 f i) l <-> infinite_sum f l.\nProof.\n  split; intros HH.\n  - apply Series.is_series_Reals.\n    unfold Series.is_series.\n    red in HH.\n    eapply filterlim_ext; try eapply HH.\n    intros; simpl.\n    rewrite sum_n_Reals.\n    reflexivity.\n  - apply Series.is_series_Reals in HH.\n    unfold Series.is_series in HH.\n    red.\n    eapply filterlim_ext; try eapply HH.\n    intros; simpl.\n    rewrite sum_n_Reals.\n    reflexivity.\nQed.\nEnd coquelicot.\n", "meta": {"author": "CertRL", "repo": "CertRLanon", "sha": "ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec", "save_path": "github-repos/coq/CertRL-CertRLanon", "path": "github-repos/coq/CertRL-CertRLanon/CertRLanon-ba50abfb13c9c49abda8ffaad23fe76dcd4bf6ec/coq/utils/Sums.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7074331221269555}}
{"text": "(* Useful properties of our Simple.v specification *)\nRequire Import Simple.\n\n(* Dominates is transitive *)\nTheorem dom_trans {D : Domain} :\n        forall {s1 s2 s3},\n               Dominates s1 s2 -> Dominates s2 s3 -> Dominates s1 s3.\n  (* Break apart our Dominates arguments *)\n  intros. destruct H. destruct H0. refine (conj _ _).\n\n  (* Compose their parts *)\n  intuition. intuition.\nQed.\n\n(* NoWorse is reflexive *)\nTheorem no_worse_refl {D : Domain} :\n        forall {s}, NoWorse s s.\n  intro. exact (or_intror eq_refl).\nQed.\n\n(* NoWorse is transitive *)\nTheorem no_worse_trans {D : Domain} :\n        forall {s1 s2 s3},\n               NoWorse s1 s2 -> NoWorse s2 s3 -> NoWorse s1 s3.\n  (* Destruct our NoWorse arguments and solve each case *)\n  intros. destruct H. destruct H0.\n\n  (* Dominates s1 s2 /\\ Dominates s2 s3 *)\n  exact (or_introl (dom_trans H H0)).\n\n  (* Dominates s1 s2 /\\ s2 = s3 *)\n  rewrite <- H0. exact (or_introl H).\n\n  (* s1 = s2 /\\ NoWorse s2 s3 *)\n  rewrite H. exact H0.\nQed.\n\n(* The next Solver in a NoWorseStream is NoWorse than the previous *)\nFixpoint nws_no_worse {D : Domain} {s}\n                       n (nws : NoWorseStream s)\n      :  NoWorse (get_solver (S n) nws)\n                 (get_solver    n  nws)\n      := match n,    nws with\n             | 0,    nwsCons _ _ p _    => p\n             | S n', nwsCons _ _ _ nws' => nws_no_worse n' nws'\n         end.\n\n(* All Solvers in a NoWorseStream s are NoWorse than s *)\nTheorem get_solver_no_worse {D : Domain} :\n        forall s n (nws : NoWorseStream s),\n               NoWorse (get_solver n nws)\n                        s.\n  intros. induction n. destruct nws. simpl.\n  exact (no_worse_refl).\n  assert (no_worse_next := nws_no_worse n nws).\n  apply (no_worse_trans no_worse_next IHn).\nQed.\n", "meta": {"author": "Warbo", "repo": "powerplay", "sha": "8792220032f8a277b775d52e46225ab58ddb6928", "save_path": "github-repos/coq/Warbo-powerplay", "path": "github-repos/coq/Warbo-powerplay/powerplay-8792220032f8a277b775d52e46225ab58ddb6928/SimpleTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7073851165745919}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(*** Universal\n     quantifier *)\n\n(** * Motivation *)\n\n(** Suppose we wrote two functions: a simple (a.k.a. gold) implementation\n    and its optimized version.\n    How do we go about specifying their equivalence?\n *)\n\nSection Motivation.\nVariables A B : Type.\n\nVariables fgold fopt : A -> B.\n\nLemma fopt_equiv_fgold :\n  forall x : A, fgold x = fopt x.\nAbort.\n\nEnd Motivation.\n\n\n\n(** * Dependently typed functions *)\n\n(** ** Dependently typed predecessor function *)\n\nDefinition Pred n := if n is S n' then nat else unit.\n\n(** the value of [unit] type plays the role of a placeholder *)\nPrint unit.\n\nDefinition predn_dep : forall n, Pred n :=\n  fun n => if n is S n' then n' else tt.\n\nCheck erefl : predn_dep 7 = 6.\nFail Check erefl : predn_dep 0 = 0.\nCheck erefl : predn_dep 0 = tt.\nCheck predn_dep 0 : unit.\nCheck erefl : Pred 0 = unit.\nCheck predn_dep 7 : nat.\n\n\n(** ** Annotations for dependent pattern matching *)\n\n(** Type inference is undecidable *)\nFail Check (fun n => if n is S n' then n' else tt).\n\nCheck (fun n =>\n  if n is S n' as n0 return Pred n0 then n' else tt).\n\n(**\nGeneral form of pattern matching construction:\n[match expr as T in (deptype A B) return exprR].\n\n- [return exprR] denotes the dependent type of the expression\n- [as T] is needed when we are matching on complex expressions,\n  not just variables\n*)\n\n\n\n(** * Functional type is just a notation\n      for a special case of [forall]  *)\n\nLocate \"->\".\n\nCheck predn : nat -> nat.\nCheck predn : forall x : nat, nat.\nCheck predn : forall x : nat, (fun _ => nat) x.\n\n\n(** * Usage of [forall] in standalone expressions *)\n\n(* courtesy of Mathcomp book *)\nSection StandardPredicates.\nVariable T : Type.\nImplicit Types (op add : T -> T -> T).\n\nDefinition associative op :=\n  forall x y z, op x (op y z) = op (op x y) z.\n\nDefinition left_distributive op add :=\n  forall x y z, op (add x y) z = add (op x z) (op y z).\n\nDefinition left_id e op :=\n  forall x, op e x = x.\n\nEnd StandardPredicates.\n\n\n\n(** * Case study: the dual Frobenius rule *)\n\n(* Due to Andrej Bauer:\nhttps://github.com/andrejbauer/Homotopy/blob/8474551e28ceeeba4910370326dc3ffd5e340f09/OberwolfachTutorial/frobenius.v#L53-L58 *)\n\nDefinition LEM :=\n  forall P : Prop, P \\/ ~ P.\n\nDefinition Frobenius2 :=\n  forall (A : Type) (P : A -> Prop) (Q : Prop),\n    (forall x, Q \\/ P x) <-> (Q \\/ forall x, P x).\n\nLemma lem_implies_Frobenius2 : LEM -> Frobenius2.\nProof.\nrewrite /LEM /Frobenius2.\nmove=> lem.\nmove=> A P Q.\nsplit.\n- move=> all_qpx.\n  case: (lem Q); first by move=> q; left.\n  move=> nq. right. move=> x.\n  case: (all_qpx x); first by move/nq.\n  by [].\ncase; first by move=> q x; left.\nby move=> all_px x; right.\n\nRestart.\n\nmove=> Lem A P Q.\ncase: (Lem Q)=> [q | not_q]; first by split=> _; left.\nsplit=> [H | [//|x px]]; last by right.\nby right=> x; case: (H x).\nQed.\n\nLemma Frobenius2_lem : Frobenius2 -> LEM.\nProof.\nrewrite /Frobenius2=> frob.\nmove=> P.\ncase: (frob P (fun _ => False) P).\nmove=> H _; move: H.\nby apply=> p; left.\nQed.\n\n\n(*** Existential\n     quantifier *)\nModule MyExistential.\n\nInductive ex_my (A : Type) (P : A -> Prop) : Prop :=\n| ex_intro (x : A) (proof : P x).\n\n(** Simplified notation *)\nNotation \"’exists’ x : A , p\" := (ex (fun x : A => p))\n                                   (at level 200, right associativity).\n\n(** Full-blown notation: multiple binders *)\nNotation \"'exists' x .. y , p\" :=\n  (ex_my (fun x => .. (ex_my (fun y => p)) ..))\n  (at level 200, x binder, right associativity,\n   format \"'[' 'exists'  '/  ' x  ..  y ,  '/  ' p ']'\")\n  : type_scope.\nEnd MyExistential.\n\n\nLemma exists_not_forall A (P : A -> Prop) :\n  (exists x, P x) -> ~ (forall x, ~ P x).\nProof.\ncase=> x px.\nmove=> all.\nexact: (all x px).\nQed.\n\n(** Currying for dependent pair *)\nDefinition curry {A B C : Type} :\n  (A * B -> C) -> (A -> B -> C).\nmove=> f a b.\nexact: (f (pair a b)).\nDefined.\n\nLemma curry_dep A (P : A -> Prop) Q :\n  ((exists x, P x) -> Q) -> (forall x, P x -> Q).\nProof.\nmove=> f x px.\nexact: (f (ex_intro _ x px)).\nQed.\n\n\nSection Symmetric_Transittive_Relation.\n\nVariables (D : Type) (R : D -> D -> Prop).\n\n(* [Hypothesis] is a different syntax for [Variable] *)\nHypothesis Rsym :\n  forall x y, R x y -> R y x.\n\nHypothesis Rtrans :\n  forall x y z, R x y -> R y z -> R x z.\n\nLemma refl_if :\n  forall x : D, (exists y, R x y) -> R x x.\nProof.\nmove=> x.\ncase=> y rxy.\nmove: (Rsym rxy); move: rxy.\nby apply: Rtrans.\nQed.\n\nEnd Symmetric_Transittive_Relation.\n\n\n\n(*** Empty types,\n     again *)\n\nLemma exfalso_quodlibet :\n  False -> forall P : Prop, P.\nProof. by []. Qed.\n\n(** Let's write down a proof term manually *)\nDefinition exfalso_quodlibet_term :\n  False -> forall P : Prop, P\n:=\n  fun f =>\n    match f with end.\n\n(** A special case of exfalso. *)\n(** Why does this typecheck at all? *)\nLemma False_implies_false :\n  False -> false.\nProof. by case. Qed.\n\n\n(** * Disjointness of constructors *)\n\n(** Going in the other direction... *)\nLemma false_implies_False :\n  false -> False.\nProof. by []. Qed.\n\n(** What's going on here? Let's write a proof term *)\nCheck I : True.\n\nDefinition false_implies_False_term :\n  false -> False\n:=\n  fun     eq :  false = true =>\n    match eq in (_    = b)\n             return (if b then False else True)\n    with\n    | erefl => I\n    end.\n\n\n(** * Injectivity of constructors *)\n\n(** While we are at it,\n    constructors are also injective *)\nLemma succ_inj n m :\n  S n = S m -> n = m.\nProof.\ncase. (* special case for [case] *)\nShow Proof.\ndone.\nQed.\n\nLemma pair_inj A B (a1 a2 : A) (b1 b2 : B) :\n  (a1, b1) = (a2, b2) -> (a1 = a2) /\\ (b1 = b2).\nProof. by case=> ->->. Qed.\n\n\n\n(*** Induction *)\n\nLemma addnA :\n  associative addn.\nProof.\nby move=> x y z; elim: x=> // x IH; rewrite addSn IH.\nQed.\n\nLemma add0n :\n  left_id 0 addn.\nProof. by []. Qed.\n\nLemma addn0 :\n  right_id 0 addn.\nProof. by elim=> // x IH; rewrite addSn IH. Qed.\n\nLemma addSnnS m n :\n  m.+1 + n = m + n.+1.\nProof. by elim: m=> // m IH; rewrite addSn IH. Qed.\n\nLemma addnC :\n  commutative addn.\nProof.\nmove=> x y.\nelim: x; first by rewrite addn0.\nby move=> x IH; rewrite addSn IH -addSnnS.\nQed.\n\n(** * How does induction work? *)\n\nCheck nat_ind.\n\nDefinition nat_ind_my\n  : forall P : nat -> Prop,\n    P 0 ->\n    (forall n : nat, P n -> P n.+1) ->\n    forall n : nat, P n\n:=\n  fun P p0 step =>\n    fix rec n :=\n      if n is n'.+1 then step n' (rec n')\n      else p0.\n\n(** Induction is just recursion! *)\n", "meta": {"author": "anton-trunov", "repo": "coq-lecture-notes", "sha": "e012addae82da6d8d03f6e789e43f35140dcdfea", "save_path": "github-repos/coq/anton-trunov-coq-lecture-notes", "path": "github-repos/coq/anton-trunov-coq-lecture-notes/coq-lecture-notes-e012addae82da6d8d03f6e789e43f35140dcdfea/code/lecture03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.70738510988744}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Arith.Wf_nat.\nRequire Import Recdef.\n\nOpen Scope nat_scope.\n\n\nDefinition max (a b : nat) :=\n    match nat_compare a b with\n    | Lt => b\n    | _  => a\n    end.\n\n\nInductive tree :=\n    | Tip : tree\n    | Bin : nat -> tree -> tree -> tree.\n\nDefinition ht (t : tree) :=\n    match t with\n    | Tip       => 0\n    | Bin n _ _ => n\n    end.\n\n\nDefinition join (x y : tree) : tree := Bin (max (ht x) (ht y) + 1) x y.\n\nFunction step (t : tree) (xs : list tree) {measure length xs} : list tree :=\n    match xs with\n    | nil      => t :: nil\n    | u :: nil =>\n        match nat_compare (ht t) (ht u) with\n        | Lt => t :: u :: nil\n        | _  => (join t u) :: nil\n        end\n    | u :: v :: ts =>\n        match nat_compare (ht t) (ht u) with\n        | Lt => t :: u :: v :: ts\n        | _  =>\n            match nat_compare (ht t) (ht v) with\n            | Lt => step (join t u) (v :: ts)\n            | _  => (* step t *) (step (join u v) ts) \n                    (* step t (step (join u v) ts) is required, but not allowed *)\n            end\n        end\n    end.\nProof.\n    intros t xs u l v ts L X C1 C2. simpl. apply le_lt_SS. apply le_n.\n    intros t xs u l v ts L X C1 C2. simpl. apply Lt.lt_n_Sn. \n    intros t xs u l v ts L X C1 C2. simpl. apply le_lt_SS. apply le_n.\n    intros t xs u l v ts L X C1 C2. simpl. apply le_lt_SS. apply le_n. \n    intros t xs u l v ts L X C1 C2. simpl. apply Lt.lt_n_Sn.\n    intros t xs u l v ts L X C1 C2. simpl. apply le_lt_SS. apply le_n. \nQed.\n\n", "meta": {"author": "ltbinsbe", "repo": "INFODTP", "sha": "2995a6503d4b8028f83a0907e83bcd85dd417d48", "save_path": "github-repos/coq/ltbinsbe-INFODTP", "path": "github-repos/coq/ltbinsbe-INFODTP/INFODTP-2995a6503d4b8028f83a0907e83bcd85dd417d48/coq/Function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7073582172657404}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** _Maps_ (or _dictionaries_) are ubiquitous data structures both\n\t\tgenerally and in the theory of programming languages in\n\t\tparticular; we're going to need them in many places in the coming\n\t\tchapters.  They also make a nice case study using ideas we've seen\n\t\tin previous chapters, including building data structures out of\n\t\thigher-order functions (from [Basics] and [Poly]) and the use of\n\t\treflection to streamline proofs (from [IndProp]).\n\n\t\tWe'll define two flavors of maps: _total_ maps, which include a\n\t\t\"default\" element to be returned when a key being looked up\n\t\tdoesn't exist, and _partial_ maps, which return an [option] to\n\t\tindicate success or failure.  The latter is defined in terms of\n\t\tthe former, using [None] as the default element. *)\n\n(* ################################################################# *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we begin...\n\n\t\tUnlike the chapters we have seen so far, this one does not\n\t\t[Require Import] the chapter before it (and, transitively, all the\n\t\tearlier chapters).  Instead, in this chapter and from now, on\n\t\twe're going to import the definitions and theorems we need\n\t\tdirectly from Coq's standard library stuff.  You should not notice\n\t\tmuch difference, though, because we've been careful to name our\n\t\town definitions and theorems the same as their counterparts in the\n\t\tstandard library, wherever they overlap. *)\n\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nRequire Export Coq.Strings.String.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\n\n(** Documentation for the standard library can be found at\n\t\thttp://coq.inria.fr/library/.\n\n\t\tThe [Search] command is a good way to look for theorems involving\n\t\tobjects of specific types.  Take a minute now to experiment with it. *)\n\n(* ################################################################# *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our\n\t\tmaps.  In [Lists.v] we introduced a fresh type [id] for a similar\n\t\tpurpose; here and for the rest of _Software Foundations_ we will\n\t\tuse the [string] type from Coq's standard library. *)\n\n(** To compare strings, we define the function [eqb_string], which\n\t\tinternally uses the function [string_dec] from Coq's string\n\t\tlibrary. *)\n\nDefinition eqb_string (x y : string) : bool :=\n\tif string_dec x y then true else false.\n\n(** (The function [string_dec] comes from Coq's string library.\n\t\tIf you check the result type of [string_dec], you'll see that it\n\t\tdoes not actually return a [bool], but rather a type that looks\n\t\tlike [{x = y} + {x <> y}], called a [sumbool], which can be\n\t\tthought of as an \"evidence-carrying boolean.\"  Formally, an\n\t\telement of [sumbool] is either a proof that two things are equal\n\t\tor a proof that they are unequal, together with a tag indicating\n\t\twhich.  But for present purposes you can think of it as just a\n\t\tfancy [bool].) *)\n\n(** Now we need a few basic properties of string equality... *)\nTheorem eqb_string_refl : forall s : string, true = eqb_string s s.\nProof.\n\tintros s. unfold eqb_string. destruct (string_dec s s) as [|Hs].\n\t- reflexivity.\n\t- unfold not in Hs. destruct Hs. reflexivity.\nQed.\n\n(** The following useful property follows from an analogous\n\t\tlemma about strings: *)\n\nTheorem eqb_string_true_iff : forall x y : string,\n\teqb_string x y = true <-> x = y.\nProof.\n\tintros x y.\n\tunfold eqb_string.\n\tdestruct (string_dec x y) as [|Hs].\n\t- subst. split. reflexivity. reflexivity.\n\t- split.\n\t\t+ intros contra. discriminate contra.\n\t\t+ intros H. rewrite H in Hs. destruct Hs. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem eqb_string_false_iff : forall x y : string,\n\teqb_string x y = false <-> x <> y.\nProof.\n\tintros x y. rewrite <- eqb_string_true_iff.\n\trewrite not_true_iff_false. reflexivity. Qed.\n\n(** This handy variant follows just by rewriting: *)\n\nTheorem false_eqb_string : forall x y : string,\n\tx <> y -> eqb_string x y = false.\nProof.\n\tintros x y. rewrite eqb_string_false_iff.\n\tintros H. apply H. Qed.\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n\t\tpartial maps that is similar in behavior to the one we saw in the\n\t\t[Lists] chapter, plus accompanying lemmas about its behavior.\n\n\t\tThis time around, though, we're going to use _functions_, rather\n\t\tthan lists of key-value pairs, to build maps.  The advantage of\n\t\tthis representation is that it offers a more _extensional_ view of\n\t\tmaps, where two maps that respond to queries in the same way will\n\t\tbe represented as literally the same thing (the very same function),\n\t\trather than just \"equivalent\" data structures.  This, in turn,\n\t\tsimplifies proofs that use maps. *)\n\n(** We build partial maps in two steps.  First, we define a type of\n\t\t_total maps_ that return a default value when we look up a key\n\t\tthat is not present in the map. *)\n\nDefinition total_map (A : Type) := string -> A.\n\n(** Intuitively, a total map over an element type [A] is just a\n\t\tfunction that can be used to look up [string]s, yielding [A]s. *)\n\n(** The function [t_empty] yields an empty total map, given a default\n\t\telement; this map always returns the default element when applied\n\t\tto any string. *)\n\nDefinition t_empty {A : Type} (v : A) : total_map A :=\n\t(fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n\t\ta map [m], a key [x], and a value [v] and returns a new map that\n\t\ttakes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A : Type} (m : total_map A)\n\t\t\t\t\t\t\t\t\t\t(x : string) (v : A) :=\n\tfun x' => if eqb_string x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming:\n\t\t[t_update] takes a _function_ [m] and yields a new function\n\t\t[fun x' => ...] that behaves like the desired map. *)\n\n(** For example, we can build a map taking [string]s to [bool]s, where\n\t\t[\"foo\"] and [\"bar\"] are mapped to [true] and every other key is\n\t\tmapped to [false], like this: *)\n\nDefinition examplemap :=\n\tt_update (t_update (t_empty false) \"foo\" true)\n\t\t\t\t\t \"bar\" true.\n\n(** Next, let's introduce some new notations to facilitate working\n\t\twith maps. *)\n\n(** First, we will use the following notation to create an empty\n\t\ttotal map with a default value. *)\nNotation \"'_' '!->' v\" := (t_empty v)\n\t(at level 100, right associativity).\n\nExample example_empty := (_ !-> false).\n\n(** We then introduce a convenient notation for extending an existing\n\t\tmap with some bindings. *)\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(at level 100, v at next level, right associativity).\n\n(** The [examplemap] above can now be defined as follows: *)\n\nDefinition examplemap' :=\n\t( \"bar\" !-> true;\n\t\t\"foo\" !-> true;\n\t\t_     !-> false\n\t).\n\n(** This completes the definition of total maps.  Note that we\n\t\tdon't need to define a [find] operation because it is just\n\t\tfunction application! *)\n\nExample update_example1 : examplemap' \"baz\" = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap' \"foo\" = true.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap' \"quux\" = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap' \"bar\" = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental\n\t\tfacts about how they behave. *)\n\n(** Even if you don't work the following exercises, make sure\n\t\tyou thoroughly understand the statements of the lemmas! *)\n\n(** (Some of the proofs require the functional extensionality axiom,\n\t\twhich is discussed in the [Logic] chapter.) *)\n\n(** **** Exercise: 1 star, standard, optional (t_apply_empty)\n\n\t\tFirst, the empty map returns its default element for all keys: *)\n\nLemma t_apply_empty : forall (A : Type) (x : string) (v : A),\n\t(_ !-> v) x = v.\nProof.\n\tintros. unfold t_empty. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_eq)\n\n\t\tNext, if we update a map [m] at a key [x] with a new value [v]\n\t\tand then look up [x] in the map resulting from the [update], we\n\t\tget back [v]: *)\n\nLemma t_update_eq : forall (A : Type) (m : total_map A) x v,\n\t(x !-> v ; m) x = v.\nProof.\n\tintros. unfold t_update. destruct (eqb_string x x) eqn:e.\n\t- reflexivity.\n\t- rewrite <- eqb_string_refl in e. discriminate e.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_neq)\n\n\t\tOn the other hand, if we update a map [m] at a key [x1] and then\n\t\tlook up a _different_ key [x2] in the resulting map, we get the\n\t\tsame result that [m] would have given: *)\n\nTheorem t_update_neq : forall (A : Type) (m : total_map A) x1 x2 v,\n\tx1 <> x2 ->\n\t(x1 !-> v ; m) x2 = m x2.\nProof.\n\tintros. unfold t_update. destruct (eqb_string x1 x2) eqn:E.\n\t- apply false_eqb_string in H. rewrite H in E. discriminate E.\n\t- reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_shadow)\n\n\t\tIf we update a map [m] at a key [x] with a value [v1] and then\n\t\tupdate again with the same key [x] and another value [v2], the\n\t\tresulting map behaves the same (gives the same result when applied\n\t\tto any key) as the simpler map obtained by performing just\n\t\tthe second [update] on [m]: *)\n\nLemma t_update_shadow : forall (A : Type) (m : total_map A) x v1 v2,\n\t(x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\n\tintros A m x v1 v2. unfold t_update. apply functional_extensionality.\n\tintros y. destruct (eqb_string x y) eqn:E.\n\t- reflexivity.\n\t- reflexivity.\nQed.\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n\t\tthe reflection idioms introduced in chapter [IndProp].  We begin\n\t\tby proving a fundamental _reflection lemma_ relating the equality\n\t\tproposition on [id]s with the boolean function [eqb_id]. *)\n\n(** **** Exercise: 2 stars, standard, optional (eqb_stringP)\n\n\t\tUse the proof of [eqbP] in chapter [IndProp] as a template to\n\t\tprove the following: *)\n\nLemma eqb_stringP : forall x y : string,\n\treflect (x = y) (eqb_string x y).\nProof.\n\tintros. apply iff_reflect. rewrite eqb_string_true_iff. reflexivity.\nQed.\n(** [] *)\n\n(** Now, given [string]s [x1] and [x2], we can use the tactic\n\t\t[destruct (eqb_stringP x1 x2)] to simultaneously perform case\n\t\tanalysis on the result of [eqb_string x1 x2] and generate\n\t\thypotheses about the equality (in the sense of [=]) of [x1]\n\t\tand [x2]. *)\n\n(** **** Exercise: 2 stars, standard (t_update_same)\n\n\t\tWith the example in chapter [IndProp] as a template, use\n\t\t[eqb_stringP] to prove the following theorem, which states that\n\t\tif we update a map to assign key [x] the same value as it already\n\t\thas in [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall (A : Type) (m : total_map A) x,\n\t(x !-> m x ; m) = m.\nProof.\n\tintros. unfold t_update. apply functional_extensionality.\n\tintros y. destruct (eqb_stringP x y) as [H | H].\n\t- rewrite H. reflexivity.\n\t- reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, recommended (t_update_permute)\n\n\t\tUse [eqb_stringP] to prove one final property of the [update]\n\t\tfunction: If we update a map [m] at two distinct keys, it doesn't\n\t\tmatter in which order we do the updates. *)\n\nTheorem t_update_permute: forall (A : Type) (m : total_map A) v1 v2 x1 x2,\n\tx2 <> x1 ->\n\t(x1 !-> v1 ; x2 !-> v2 ; m)\n\t=\n\t(x2 !-> v2 ; x1 !-> v1 ; m).\nProof.\n\tintros. unfold t_update. apply functional_extensionality.\n\tintros. destruct (eqb_string x1 x) as [H1 | H1] eqn:X1.\n\t- destruct (eqb_string x2 x) as [H2 | H2] eqn:X2.\n\t\t+ rewrite eqb_string_true_iff in X1. rewrite eqb_string_true_iff in X2.\n\t\t\tsubst. destruct H. reflexivity.\n\t\t+ reflexivity.\n\t- destruct (eqb_string x2 x) as [H2 | H2] eqn:X2.\n\t\t+ reflexivity.\n\t\t+ reflexivity.\nQed.\n\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n\t\tmap with elements of type [A] is simply a total map with elements\n\t\tof type [option A] and default element [None]. *)\n\nDefinition partial_map (A : Type) := total_map (option A).\n\nDefinition empty {A : Type} : partial_map A := t_empty None.\n\nDefinition update {A : Type} (m : partial_map A) (x : string) (v : A) :=\n\t(x !-> Some v ; m).\n\n(** We introduce a similar notation for partial maps: *)\nNotation \"x '|->' v ';' m\" := (update m x v)\n\t(at level 100, v at next level, right associativity).\n\n(** We can also hide the last case when it is empty. *)\nNotation \"x '|->' v\" := (update empty x v)\n\t(at level 100).\n\nExample examplepmap :=\n\t(\"Church\" |-> true ; \"Turing\" |-> false).\n\n(** We now straightforwardly lift all of the basic lemmas about total\n\t\tmaps to partial maps.  *)\n\nLemma apply_empty : forall (A : Type) (x : string),\n\t@empty A x = None.\nProof.\n\tintros. unfold empty. rewrite t_apply_empty.\n\treflexivity.\nQed.\n\nLemma update_eq : forall (A : Type) (m : partial_map A) x v,\n\t(x |-> v ; m) x = Some v.\nProof.\n\tintros. unfold update. rewrite t_update_eq.\n\treflexivity.\nQed.\n\nTheorem update_neq : forall (A : Type) (m : partial_map A) x1 x2 v,\n\tx2 <> x1 ->\n\t(x2 |-> v ; m) x1 = m x1.\nProof.\n\tintros A m x1 x2 v H.\n\tunfold update. rewrite t_update_neq. reflexivity.\n\tapply H.\nQed.\n\nLemma update_shadow : forall (A : Type) (m : partial_map A) x v1 v2,\n\t(x |-> v2 ; x |-> v1 ; m) = (x |-> v2 ; m).\nProof.\n\tintros A m x v1 v2. unfold update. rewrite t_update_shadow.\n\treflexivity.\nQed.\n\nTheorem update_same : forall (A : Type) (m : partial_map A) x v,\n\tm x = Some v ->\n\t(x |-> v ; m) = m.\nProof.\n\tintros A m x v H. unfold update. rewrite <- H.\n\tapply t_update_same.\nQed.\n\nTheorem update_permute: forall (A : Type) (m : partial_map A) x1 x2 v1 v2,\n\tx2 <> x1 ->\n\t(x1 |-> v1 ; x2 |-> v2 ; m) = (x2 |-> v2 ; x1 |-> v1 ; m).\nProof.\n\tintros A m x1 x2 v1 v2. unfold update.\n\tapply t_update_permute.\nQed.\n\n(* Wed Jan 9 12:02:45 EST 2019 *)\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/LF/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303137346446, "lm_q2_score": 0.8947894738180211, "lm_q1q2_score": 0.7073582034638177}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq               *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later              *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup finalg matrix.\nRequire Import Reals Lra.\nFrom mathcomp Require Import Rstruct.\nRequire Import ssrR Reals_ext logb ssr_ext ssralg_ext bigop_ext Rbigop fdist.\nRequire Import proba jfdist_cond entropy.\n\n(******************************************************************************)\n(* Example 2.2.1 of T. M. Cover and J. A. Thomas. Elements of information     *)\n(* theory. Wiley, 2006. 2nd edition                                           *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope R_scope.\nLocal Open Scope fdist_scope.\nLocal Open Scope proba_scope.\n\nModule conditional_entropy_example.\n\nDefinition zero : 'I_4 := ord0.\nDefinition one : 'I_4 := @Ordinal 4 1 isT.\nDefinition two : 'I_4 := @Ordinal 4 2 isT.\nDefinition three : 'I_4 := @Ordinal 4 3 isT.\n\nDefinition f := [ffun x : 'I_4 * 'I_4 => [eta (fun=>0) with\n(zero, zero) |-> (1/8), (zero, one) |-> (1/16), (zero, two) |-> (1/16), (zero, three) |-> (1/4),\n(one, zero) |-> (1/16), (one, one) |-> (1/8), (one, two) |-> (1/16), (one, three) |-> 0,\n(two, zero) |-> (1/32), (two, one) |-> (1/32), (two, two) |-> (1/16), (two, three) |-> 0,\n(three, zero) |-> (1/32), (three, one) |-> (1/32), (three, two) |-> (1/16), (three, three) |-> 0] x].\n\nLemma f0 : forall x, 0 <= f x.\nProof.\nmove=> x; rewrite ffunE; move: x.\ncase => -[ [? [[|[|[|[|[]//]]]]]\n  | [? [[|[|[|[|[]//]]]]]\n  | [? [[|[|[|[|[]//]]]]]\n  | [? [[|[|[|[|[]//]]]]] | []//]]]]]; rewrite /f /=; try lra.\nQed.\n\nLemma f1 : \\sum_(x in {: 'I_4 * 'I_4}) f x = 1.\nProof.\nrewrite (eq_bigr (fun x => f (x.1, x.2))); last by case.\nrewrite -(pair_bigA _ (fun x1 x2 => f (x1, x2))) /=.\nrewrite !big_ord_recl !big_ord0 /f /= !ffunE /=; field.\nQed.\n\nDefinition d : {fdist 'I_4 * 'I_4} := locked (FDist.make f0 f1).\n\nLemma dE x : d x = f x.\nProof. by rewrite /d; unlock. Qed.\n\nLemma conditional_entropyE : cond_entropy d = 11/8.\nProof.\nrewrite /cond_entropy /=.\nrewrite !big_ord_recl big_ord0 !fdist_sndE /=.\nrewrite !big_ord_recl !big_ord0 !dE /f /=.\nrewrite /cond_entropy1 /=.\nrewrite !big_ord_recl !big_ord0 /jcPr /Pr !(big_setX,big_set1) !dE /f /=.\nrewrite !fdist_sndE /=.\nrewrite !big_ord_recl !big_ord0 !dE /f !ffunE /=.\nrewrite !(addR0,add0R,div0R,mul0R).\nrepeat (rewrite logDiv; try lra).\nrewrite !log1 !sub0R !log4 !log8 !log16 !log32.\nrewrite [X in log X](_ : _ = 1/4); last lra.\nrewrite !div1R logV; last lra.\nrewrite !log4.\nrewrite [X in log X](_ : _ = 1/4); last lra.\nrewrite !div1R logV; last lra.\nrewrite !log4.\nrewrite [X in log X](_ : _ = 1/4); last lra.\nrewrite !div1R logV; last lra.\nrewrite !log4.\nfield.\nQed.\n\nEnd conditional_entropy_example.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/toy_examples/conditional_entropy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7073581995824324}}
{"text": "(** * Computing the length of paths from [alpha] to [zero] \n\n After Wainer, Ketonen, Solovay, etc .\n\n    Pierre Casteran, LaBRI, University of  Bordeaux *)\n\nFrom hydras Require Import  Hprime  E0  Canon Paths\n     Large_Sets.\nFrom hydras Require Import  Simple_LexProd Iterates .\nFrom Coq Require Import ArithRing Lia.\n(* begin snippet LDef *)\n\nFrom Equations Require Import Equations.\nImport RelationClasses Relations.\n\n#[global] Instance Olt : WellFounded E0lt := E0lt_wf.\n#[global] Hint Resolve Olt : E0.\n\n(** Using Coq-Equations for building a function which satisfies \n    [Large_sets.L_spec] *)\n\nEquations  L_ (alpha: E0) (i:nat) : nat by wf alpha E0lt :=\n  L_ alpha  i with E0_eq_dec alpha E0zero :=\n    { | left _zero => i ;\n      | right _nonzero\n          with Utils.dec (E0limit alpha) :=\n          { | left _limit =>  L_ (Canon alpha i)  (S i) ;\n            | right _successor =>  L_ (E0pred alpha) (S i)}}.\n\n(*| .. coq:: in messages |*)\nSolve All Obligations with auto with E0. \n\n(*||*)\n(* end snippet LDef *)\n\n(* begin snippet AboutLEquation1 *)\n\nAbout L__equation_1.\n(* end snippet AboutLEquation1 *)\n\n(** Paraphrase of equations generated by coq-equations *)\n\n(* begin snippet Paraphrasesa:: no-out *)\n\nLemma L_zero_eqn : forall i, L_ E0zero i = i.\nProof. intro i; now rewrite L__equation_1. Qed.\n\nLemma L_eq2 alpha i :\n  E0is_succ alpha -> L_ alpha i = L_ (E0pred alpha) (S i).\n(* end snippet Paraphrasesa *)\n\nProof.\n  intros; rewrite L__equation_1;  destruct (E0_eq_dec alpha E0zero).\n  - subst; discriminate.\n  - cbn; destruct (Utils.dec (E0limit alpha)) .\n    apply Succ_not_T1limit in H; destruct H; auto.\n    now cbn.\nQed.\n\n(* begin snippet Paraphrasesb:: no-out *)\nLemma L_succ_eqn alpha i :\n  L_ (E0succ alpha) i = L_ alpha (S i).\n(* end snippet Paraphrasesb *)\n\nProof.\n  intros;rewrite L_eq2;\n    [autorewrite with E0_rw using trivial | auto with E0].\nQed.\n\n\nHint Rewrite L_zero_eqn L_succ_eqn : L_rw.\n\n(* begin snippet Paraphrasesc:: no-out *)\nLemma L_lim_eqn alpha i :\n  E0limit alpha ->\n  L_ alpha i = L_ (Canon alpha i) (S i).\n(* end snippet Paraphrasesc *)\n\nProof.\n  intros;rewrite L__equation_1.\n  destruct (E0_eq_dec alpha E0zero).\n  - subst; discriminate.\n  - cbn;  destruct (Utils.dec (E0limit alpha)) .\n    + now cbn.    \n    + red in H; rewrite e in H; discriminate.\nQed.\n\n\n(* begin snippet LFiniteOmega *)\n\nLemma L_finite : forall i k :nat,  L_ i k = (i+k)%nat. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  induction i.\n  - simpl E0fin; intro; now rewrite L_zero_eqn.\n  - simpl; rewrite FinS_Succ_eq; intro k; autorewrite with E0_rw L_rw.\n    rewrite IHi.\n   + abstract lia.\nQed.\n(*||*)\n\nLemma L_omega : forall k, L_ E0omega k = S (2 * k)%nat. (* .no-out *)\n(*| .. coq:: none |*)\nProof.\n  intro k; rewrite L_lim_eqn.\n  - replace (Canon  E0omega  k) with (E0fin k).\n    + rewrite L_finite; abstract lia.\n    +  cbn; unfold Canon; cbn.\n       apply E0_eq_intro.\n       destruct k;  reflexivity.\n  - now cbn.\nQed.\n(*||*)\n(* end snippet LFiniteOmega *)\n\nLemma L_ge_id alpha : forall i,  i <= L_ alpha i.\nProof  with auto with E0.\n     pattern alpha; apply well_founded_induction with E0lt ...\n   clear alpha; intros alpha IHalpha.\n  destruct (Zero_Limit_Succ_dec alpha).\n  -  destruct s.\n   +  subst alpha. intro; rewrite L_zero_eqn. auto with arith. \n   +   intros  k;  rewrite L_lim_eqn; auto.\n     *  specialize (IHalpha (Canon alpha k)).\n        destruct k;  simpl Canon.\n        --  autorewrite with L_rw; auto. auto with arith.\n        -- transitivity (S (S k)); [lia | apply IHalpha ]...\n     -  destruct s as [beta e];  destruct (E0_eq_dec beta E0zero).\n        +  subst  beta alpha.\n           intros  k; autorewrite with L_rw; auto. \n        +   subst alpha; intros k; autorewrite with L_rw ...\n              transitivity (S k); [lia |] ...\nQed.\n\n\n(* begin snippet LGeS *)\n\nLemma L_ge_S alpha :\n  alpha <> E0zero -> S <<= L_ alpha. (* .no-out *)\n(*| .. coq:: none |*)\nProof  with auto with E0.\n     pattern alpha; apply well_founded_induction with E0lt ...\n   clear alpha; intros alpha IHalpha.\n  destruct (Zero_Limit_Succ_dec alpha).\n  -  destruct s.\n   +  intro; contradiction. \n   +   intros H k;  rewrite L_lim_eqn; auto.\n     *  specialize (IHalpha (Canon alpha k)).\n        destruct k;  simpl Canon.\n        apply L_ge_id.\n        apply L_ge_id. \n     -  destruct s as [beta e];  destruct (E0_eq_dec beta E0zero).\n        +  subst  beta alpha.\n           intros H k; autorewrite with L_rw; auto. \n        +   subst alpha; intros H k; autorewrite with L_rw ...\n              transitivity (S (S k)); [lia |] ...\n              apply IHalpha ...\nQed.\n(*||*)\n(* end snippet LGeS *)\n\nLemma L_succ_ok  beta f :\n  nf beta -> S <<= f -> L_spec beta f ->\n  L_spec (succ beta)  (fun k =>  f (S k)).\nProof.\n  intros; apply Large_Sets.L_succ_ok; auto.\nQed.\n\n\n(** [L_] is correct w.r.t. its specification *)\n\nSection L_correct_proof.\n\n  Let P alpha :=  L_spec (cnf alpha) (L_ alpha).\n\n  Lemma L_ok0 : P E0zero.\n  Proof. red; simpl. left. intro k; now rewrite L_zero_eqn. Qed.\n\n  Lemma L_ok_succ beta  : P beta -> P (E0succ beta).\n  Proof with auto with E0.\n    intro H; red;  rewrite Succ_rw.\n    destruct (E0_eq_dec beta E0zero).\n    -  subst; simpl; generalize (L_fin_ok 1); unfold L_fin.\n       replace one with (T1nat 1); [simpl | trivial].\n       intro; eapply L_spec_compat;  eauto.\n       intros; rewrite L_eq2; auto with E0.\n       rewrite E0pred_of_Succ, L_zero_eqn; trivial.\n    -  apply L_spec_compat  with (L_succ (L_ beta));\n         auto.\n       + apply L_succ_ok; auto.\n         * apply cnf_ok; auto.\n         * intro k; apply L_ge_S; auto.\n       + unfold L_succ; intro n0; now autorewrite with L_rw.\n  Qed. \n\n  Lemma L_ok_lim  alpha  :\n    (forall beta,  (beta o< alpha)%e0 -> P beta) ->\n    E0limit alpha -> P alpha.\n  Proof with eauto with E0.\n    unfold P; intros.\n    apply L_spec_compat with (fun k =>  L_ (Canon alpha k) (S k)).\n    -   generalize L_lim_ok; intro H1; unfold L_lim in H1.\n       assert (H2 : T1limit (cnf alpha)) by (now destruct alpha). \n       specialize (H1 (cnf alpha) cnf_ok H2 (fun k i => L_ (Canon alpha k) i)).\n       apply H1; intro k; specialize (H (Canon alpha  (S k))).\n       assert  (H3: (Canon alpha (S k) o< alpha)%e0 ).\n       { apply CanonS_lt;  now apply Limit_not_Zero. }\n       apply H in H3; apply L_spec_compat with (L_ (Canon alpha (S k))); auto.\n    - intro n; rewrite (L_lim_eqn alpha); trivial.\n  Qed.\n\n  \n  \n  Lemma L_ok (alpha: E0) : P alpha.\n  Proof with eauto with E0.\n    apply well_founded_induction with E0lt ...\n    clear alpha; intros alpha IHalpha.\n    destruct (Zero_Limit_Succ_dec alpha) as [[H | H] | H].\n    - subst; apply L_ok0.\n    - apply L_ok_lim; auto.\n    - destruct H as [beta Hbeta]; subst; apply L_ok_succ.\n      apply IHalpha; auto with E0.\n  Qed.\n\n  \nEnd L_correct_proof.\n\n(* begin snippet LCorrect *)\n\nTheorem L_correct alpha : L_spec (cnf alpha) (L_ alpha). (* .no-out *)\n(*| .. coq:: none |*)\nProof. apply L_ok. Qed.\n(*||*)\n(* end snippet LCorrect *)\n\n(** Comparison with Hardy's function H  *)\n\n(* begin snippet HprimeL *)\n\nTheorem H'_L_ alpha :\n  forall i:nat,  (H'_ alpha i <= L_ alpha (S i))%nat. (* .no-out *)\n(* end snippet HprimeL *)\n\nProof with auto with E0.\n  pattern alpha ; apply well_founded_induction with E0lt ...\n  clear alpha; intros alpha IHalpha i.\n  destruct (Zero_Limit_Succ_dec alpha) as [[H | H] | H].\n  - subst; rewrite H'_eq1, L_zero_eqn. abstract lia.\n  - rewrite H'_eq3, L_lim_eqn ...\n    apply Nat.lt_le_incl;\n      apply Nat.lt_le_trans with (H'_ (Canon alpha (S i)) (S i)).\n    apply H'_alpha_mono; auto with arith ...\n    apply IHalpha ...\n  -  destruct H as [beta e]; subst alpha;\n       rewrite H'_eq2, L_succ_eqn ...\nQed.\n\nRequire Import Extraction.\n\nRecursive Extraction L_.\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/Epsilon0/L_alpha.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7073581929286288}}
{"text": "Require Import Problem PeanoNat Omega.\n\nTheorem solution : task.\nProof.\n  unfold task.\n  intros.\n  do 2 (try destruct m; try destruct n; try omega).\n  simpl in H.\n  rewrite Nat.add_comm in H.\n  inversion H.\nQed.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/026/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.7073486136765903}}
{"text": "Require Export Fin.\n\n\nFixpoint fin_lift1 {n} (m : Fin.t n) : Fin.t (S n) := \n    match m with\n    | @Fin.F1 n   => @Fin.F1 (S n)\n    |  Fin.FS m => Fin.FS (fin_lift1 m)\n    end.\n\nFixpoint fin_to_nat {n} (m : Fin.t n):= \n    match m with\n    | Fin.F1   => 0\n    | Fin.FS m => S (fin_to_nat m)\n    end.\n\nCoercion fin_lift1  : Fin.t >-> Fin.t.\nCoercion fin_to_nat : Fin.t >-> nat.", "meta": {"author": "klara-zielinska", "repo": "refocusing2", "sha": "f741a1bdb746b53d34435c61298261b846e6be38", "save_path": "github-repos/coq/klara-zielinska-refocusing2", "path": "github-repos/coq/klara-zielinska-refocusing2/refocusing2-f741a1bdb746b53d34435c61298261b846e6be38/Lib/Fin2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.7073486066599878}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) : natural := mult lf2 x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj196_coqofml_tnOc9K.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7073221335380289}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype choice.\nFrom mathcomp Require Import ssralg ssrnum ssrint fintype bigop order matrix interval.\nFrom mathcomp  Require Import boolp reals posnum.\nFrom mathcomp Require Import classical_sets topology prodnormedzmodule  posnum topology normedtype landau forms sequences.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Order.TTheory GRing.Theory Num.Theory Num.Def.\nLocal Open Scope ring_scope.\nLocal Open Scope classical_set_scope.\n\n\nSection Close_Ball.\nDefinition close_ball_ (R : numDomainType) (V: zmodType) (norm : V -> R) (x : V) (e :R) :=\n[set y | (norm (x- y) <=e)%O ] .\nDefinition close_ball (R : realType) (M : completeNormedModType R) (x : M) (e : R) :=\n  close_ball_ normr x e.\n\nLemma closed_close_ball (R : realType) (M : completeNormedModType R) (x : M) (e : R) :\n  closed (close_ball x e).\nProof.\n  Search _ closed.\n  pose f := fun y => normr ( x - y).\n  have : close_ball x e  = f @^-1` [set x | (x<= e)%O] by rewrite /close_ball /close_ball_ /preimage.\n  move ->.\n  apply (@closed_comp _ _ (f : M -> R^o) _).\n  have H : forall x : M , x \\in (~` f @^-1` (fun x : R => (x<=e)%O))  -> {for x, continuous ( f : M -> R^o)}.\n   move => y Hy.  \n   apply  (@continuous_comp _ _ _ (fun y : M => (x-y)) (normr : M -> R^o) y) .\n    apply: continuousB.\n     by apply: cst_continuous.\n     by [].\n    by apply : norm_continuous.\n   move=> a.\n   exact (H a).\n  by apply: closed_le.\nQed.\n\nVariable (K : realType).\n\n\nLemma neighBall (U : completeNormedModType K) (y : U) (A : set U) :\n  open_nbhs y A -> exists (r : {posnum K}), ball y r%:num `<=` A.\nProof.\n  by move=> /open_nbhs_nbhs /(@nbhs_ballP _ _ y A) /exists2P [r [supr prop]]; exists (PosNum supr).\nQed.\n\n\nLemma closeNeigh_ball (U : completeNormedModType K) (y : U) (A : set U) :\n  open_nbhs y A -> exists (r : {posnum K}), close_ball y r%:num `<=` A.\nProof.\n  move=> H.\n  have [r Hr] : (exists r : {posnum K}, ball y r%:num `<=` A).\n    by apply: neighBall.\n  have Hrr : r%:num / 2 > 0.\n    by [].\n  exists (PosNum Hrr).\n  apply (@subset_trans  _ (ball y r%:num) _ _).\n  rewrite -?ball_normE;  move=> a Ha;\n  apply (@le_lt_trans _ _  (PosNum Hrr)%:num (`| y - a|) r%:num); rewrite ?(@ltr_pdivr_mulr _ 2 r%:num r%:num);\n  by rewrite -?(@ltr_pdivr_mull _ r%:num 2 r%:num) //= mulrC mulfV ?ltr1n.\n  by [].  \nQed.\n\nLemma close_ball_center (U :completeNormedModType K) (x : U) (r : {posnum K}) :\n  close_ball x r%:num x.\nProof.\n  by rewrite /close_ball /close_ball_ //= subrr normr0.\nQed.\n\nLemma close_neigh_ball (U : completeNormedModType K) (x : U) (r : {posnum K}) :\n  open_nbhs x (close_ball x r%:num)^°.\nProof.\n  split.\n    by apply: open_interior.\n    apply: nbhs_singleton; apply: nbhs_interior; apply /nbhs_ballP; exists r%:num.\n    by [].\n    by rewrite -ball_normE; move=> a; apply/ltW.\nQed.\n\n\nLemma close_ball_ler (U : completeNormedModType K) (x : U) (e1 e2 : K) :\n  (e1 <= e2)%O -> close_ball x e1 `<=` close_ball x e2.\n  by move=> H e Y; apply: (@le_trans _ _ e1 (`|x-e|) e2). \nQed.\n\nEnd Close_Ball.\n\nSection Baire.\nVariable (K: realType). \nDefinition dense (U : completeNormedModType K) (S : U  -> Prop) :=\n  forall (O : set U), (exists y, O y) -> open O ->  exists x, (setI O S) x.\n\n(*Definition dense_ (U : completeNormedModType K) (S : U -> Prop) :=\n  forall O, (O <> set0) -> open O -> ((setI O S) <> set0).\n\nDefinition dense_alt (U : completeNormedModType K) (S : U -> Prop) :=\n  closure S = setT.\nDefinition dense_altbis ( U : completeNormedModType K) (S : U -> Prop) :=\n  forall x, exists O , (neigh x) O -> (O `&` S) <> set0.\n\nLemma densityEbis  (U : completeNormedModType K) (S : U -> Prop) :\n  dense S <-> dense_ S.\nAdmitted.\n\nLemma densityE (U : completeNormedModType K) (S : U -> Prop) :\n  dense S <-> dense_alt S.\nAdmitted.*)\nLemma floor_nat_comp (M :K) : (0 <= M) -> (M < `|Rtoint(floor M + 1%:~R)|%:R).\n       move=> Hyp.\n       set n:= (X in ( M < X)).\n       have ->  : n = (floor M + 1).\n       rewrite {}/n.\n       have /RintP [z Hmz] := isint_floor M.\n       rewrite Hmz -intrD Rtointz.\n       have S : z +  1 = Posz (  `|(z+1)%R|%N).\n       rewrite gez0_abs.\n       by [].\n       rewrite -(@ler_int K 0 (z+1)) intrD -Hmz (@le_trans _ _ M 0 (floor M + 1)).\n       by [].\n       by [].\n       by apply/ltW; apply: floorS_gtr.\n       by rewrite  S.       \n       by apply: floorS_gtr.\nQed. \n\nLemma minr_le1 (x y : K) : (x >= minr x y ).\nProof.\n  case : (@lerP _ x y).\n  by [].\n  by apply: ltW.\nQed.\n\nLemma minr_le2 ( x y : K) : ( y >= minr x y).\nProof.\n  by case : (@lerP _ x y).\nQed.\nLemma lt_inv (x y : K) : (x > 0) -> (y > 0) -> (x^-1 < y^-1) = (y < x).\nProof.\n by move => supx supy; rewrite -(mulr1 x^-1) ltr_pdivr_mull ?ltr_pdivl_mulr ?(mulrC 1 y) ?(mulr1 y).\nQed.\n\nDefinition Baire (U : completeNormedModType K) :=\n  forall (F: nat -> (set U)), (forall i, open (F i) /\\  dense (F i))  ->\n                      dense (\\bigcap_(i : nat) (F i)).\n\n(* Definition Baire (U : completeNormedModType K) :=\n  forall (F: nat -> (set U)), (forall i, open (F i) /\\  dense (F i))  ->\n                      dense (\\bigcap_(i : nat) (F i)). *)\n\nTheorem DeBaire  (U : completeNormedModType K) : Baire U.\nProof.\nmove=> F Hf D Dy  OpenD.\nhave [H /(_ D  Dy OpenD) [a0 DF0a0 ] ] : open (F 0%nat) /\\ dense (F 0%nat)\n  by apply Hf.\nhave openIDF0 : open (D `&` F 0%N) by apply: openI.\nhave neigh_a0 : open_nbhs a0 (D `&` F 0%N) by [].\nmove: (@closeNeigh_ball _ _   a0 (D `&` F 0%N) neigh_a0)\n         {DF0a0 openIDF0} => [ r0 Ball_a0] {neigh_a0} . \npose P (m: nat) (arn : U * {posnum K}) (arm : U * {posnum K}) :=\n  close_ball arm.1 (arm.2%:num)\n                  `<=` ((close_ball (arn).1 ((arn).2%:num))^°\n   `&` (F m)) /\\ (arm.2%:num < ((S(m))%:R^-1)).\nhave Ar: forall na : nat * (U * {posnum K}), exists b : (U * {posnum K}) , P (S(na.1)) na.2 b.\n  move=> [n [an rn]].\n  move: (Hf ((S n)%N))=> [ openFn denseFn ].\n  have [an1 B0Fn2an1]: exists x, ((close_ball an (numpos K rn))^° `&` F (S n)%N) x .\n  move: (close_neigh_ball an rn)=> [h1 h2]; apply: denseFn.\n   - by exists an.\n   - by [].\nsimpl in (type of an1).\nhave openIB0Fn1 : open ((close_ball an (numpos K rn))^° `&` F (S n)%N).\n  apply: openI; last by [].\n  by apply: open_interior.\nhave neigh_an1 : open_nbhs an1 ((close_ball an (numpos K rn))^° `&` F (S n)%N) by [].\nmove: (@closeNeigh_ball _ _ an1  ((close_ball an (numpos K rn))^° `&` F (S n)%N) neigh_an1)\n        {B0Fn2an1 openIB0Fn1 openFn denseFn} => [rn01 Ball_an1].\npose a := ((n.+3)%:R^-1 : K).\nhave asup: a > 0 by [].\npose abis := PosNum asup.\npose rn1b := minr abis%:num rn01%:num.\nhave majr : rn1b > 0 by apply min_pos_gt0.\npose rn1 := PosNum majr.\nexists (an1,rn1); split.\n   - have temp : close_ball an1 rn1b `<=` close_ball an1 rn01%:num\n     by apply : close_ball_ler; apply: minr_le2.\n     by apply:  (@subset_trans _ (close_ball an1 rn01%:num) _ _).\n   - apply: (@le_lt_trans _ _ (n.+3%:R^-1) rn1b (n.+2%:R^-1)).\n     by apply: minr_le1.\n     by rewrite lt_inv ?ltr_nat.\nmove: (choice Ar) => [f Pf].\npose fix ar (n: nat):= match n with\n                     | 0 => (a0,r0)\n                     | S p => (f (p,(ar p)))\n                     end .\npose a := fun n => (ar n).1 .\npose r := fun n => (ar n).2 .\nhave Suite_ball : forall (n m :nat) , (n <= m)%N -> close_ball (a m) (r m)%:num\n                                            `<=` close_ball (a n) (r n)%:num.\n move=> n m.\n elim m=> [| k iHk].\n  by rewrite leqn0; move=> /eqP ->.\n move=> iHk2. \n have step : close_ball (a k.+1) (r k.+1)%:num `<=` close_ball (a k) (r k)%:num.\n have [Htemp _]: P k.+1 (a k, r k)   (a (k.+1), r (k.+1)) by apply: (Pf (k, ar k)).\n move: Htemp ; rewrite subsetI.\n move=> [tempbis _].\n apply: (@subset_trans _ (close_ball (a k, r k).1 (numpos K (a k, r k).2))^° _ _).\n   by [].\n   by apply : interior_subset.  \n rewrite leq_eqVlt in iHk2.\n have : (n==k.+1) \\/ (n<k.+1)%N by apply /orP.\n case.\n - by move=> /eqP ->.\n - move => temp.\n   have: (n<= k)%N by []. \n   move  => /iHk final.\n   by apply : (@subset_trans _ (close_ball (a k) (numpos K (r k))) _ _).   \nhave cauchyexa: (cauchy_ex (a @ \\oo )).\n move => e e0.\n rewrite /fmapE -ball_normE /ball_.\n have [n Hn]: exists n : nat , 2*(r n)%:num < e.\n pose eps := e/2.\n have [n Hn]: exists n : nat , ((n.+1)%:R^-1 < eps).\n exists `|Rtoint (floor eps^-1 + 1%:~R)|%N.\n have He : (eps^-1 < `|Rtoint(floor eps^-1 + 1%:~R)|%:R)\n   by apply : floor_nat_comp;rewrite invr_ge0 ler_pdivl_mulr ?(mulrC 0 2) ?(mulr0 2) ?ltW.\n have : (eps^-1 < `|Rtoint(floor eps^-1 + 1%:~R)|%:R) by [].\n rewrite -(mulr1 eps^-1) ltr_pdivr_mull.\n rewrite mulrC -ltr_pdivr_mull mulr1.\n    rewrite mulr1; move=> Ht; apply (@lt_trans _ _ (`|Rtoint (floor eps^-1 + 1%:~R)|%:R^-1) _ _).\n    rewrite lt_inv //=.\n      by rewrite ltr_nat //=.\n      by rewrite (@lt_trans _ _ eps^-1 _ _) ?invr_gt0  ?ltr_pdivl_mulr ?(mulrC 0 2) ?(mulr0 2) //=.\n      by [].\n      by rewrite (@lt_trans _ _ eps^-1 _ _) ?invr_gt0  ?ltr_pdivl_mulr ?(mulrC 0 2) ?(mulr0 2) //=.\n      by rewrite ltr_pdivl_mulr ?(mulrC 0 2) ?(mulr0 2).\n exists (n.+1).\n have: (r n.+1)%:num < n.+1%:R^-1. \n have: P n.+1 (a n, r n)   (a (n.+1), r (n.+1)) by apply: (Pf (n, ar n)).\n by move=> [_ B]; apply: (@lt_trans _ _ (n.+2%:R^-1) _ _);  rewrite ?lt_inv ?ltr_nat .\n  move=> temp; apply: (@lt_trans _ _ (2* n.+1%:R^-1) _ _);\n  by rewrite -ltr_pdivl_mull ?mulrA ?(mulrC 2^-1 2) ?mulfV ?(mulrC 2^-1 e) ?div1r.\n exists (a n); exists n; first by [].\n move =>  m nsupm.\n apply: (@lt_trans _ _ (2*(r n)%:num) (`|a n - a m|) e); last first. by [].\n have : (close_ball (a n) (r n)%:num) (a m).\n move : (Suite_ball n m nsupm).\n have : close_ball (a m) (r m)%:num (a m) by apply: close_ball_center.\n by move=> temp1 Ha; move : (Ha (a m) temp1).\n by move=> temp; rewrite (@le_lt_trans _ _ (r n)%:num (`|a n - a m|) (2*(r n)%:num)) -?ltr_pdivr_mulr ?mulfV ?ltr1n.\nhave cauchya : (cauchy (a @ \\oo)) by apply: cauchy_exP.\nhave : cvg (a @ \\oo) by apply: cauchy_cvg. \nrewrite cvg_ex //=.\nmove=> [l Hl] {Hf Dy OpenD H cauchya cauchyexa}.\nexists l.\nhave partie1 : D l.\n have Hinter : (close_ball a0 r0%:num) l.\n  apply: (@closed_cvg _ _ \\oo eventually_filter a); first by [].\n  move=> m.\n  have temp:  (0 <= m)%N by apply: leq0n.\n    move : (Suite_ball 0%N m temp).\n    have : close_ball (a m) (r m)%:num (a m) by apply: close_ball_center.\n  by move=> temp1 Ha; move : (Ha (a m) temp1).\n by apply: closed_close_ball.\nhave : close_ball a0 r0%:num `<=` D by move: Ball_a0; rewrite subsetI; apply:  proj1.\nby move=>  Htemp; move : (Htemp l Hinter).\nhave partie2 : (\\bigcap_i F i) l.\nmove=> i _.\n have : close_ball (a i) (r i)%:num l.\n  rewrite -(@cvg_shiftn i _ a l) in Hl.\n  simpl in Hl.\n  have partiecvg:  forall n : nat, close_ball (a i) (r i)%:num (a (n + i)%N).\n   move=> n.\n   have temp : (i <= (n +i)%N)%N by apply: leq_addl.\n   have temp2 : close_ball (a (n+i)%N) (r (n+i)%N)%:num (a (n+i)%N) by apply: close_ball_center.\n   by move : (Suite_ball i (n +i)%N temp (a (n+i)%N) temp2).\n  apply (@closed_cvg _ _ \\oo eventually_filter (fun n : nat => a (n+i)%N)).  \n  by [].\n  by [].  \n  by apply :  closed_close_ball.\ncase i.\nby rewrite subsetI in Ball_a0; move: Ball_a0; move=> [_ p] la0; move : (p l la0).\nmove=> n.\nhave [temp _] : P n.+1 (a n, r n) (a n.+1, r n.+1) by apply : (Pf (n , ar n)).\nby rewrite subsetI in temp; move : temp; move=> [_ p] lan1; move: (p l lan1). \nby [].  \nQed.\n\n\nEnd Baire.\n\nSection banach_steinhauss.\nVariable (K: realType).\nVariable (V: completeNormedModType K)  (W: normedModType K).\n(*Theorem banach_steinhauss *)\n\nCheck bounded_on.\nPrint bounded_on.\n\n(*Definition bounded_alt (f: V -> W) :=\n  bounded_on f (locally (0:V)).*)\n\nDefinition bounded (f: V -> W) := forall r, exists M,\n      forall x, (`|x| <= r) -> (`|(f x)| <= M).\n\n(*Lemma bounded_ballE (f: V -> W) : bounded f <-> bounded_alt f.\nProof.\nAdmitted.*)\n\nDefinition pointwise_bounded (F: (V -> W) -> Prop) := forall x, exists M,\n      forall f , F f ->  (`|f x| <= M)%O.\n\nDefinition uniform_bounded (F: (V -> W) -> Prop) := forall r, exists M,\n      forall f, F f -> forall x, (`|x| <= r)  -> (`|f x| <= M)%O.\n\nLemma bounded_landau (f :{linear V->W}) :\n  bounded f <-> ((f : V -> W) =O_ (0:V) cst (1 : K^o)).\nProof.\n  split.\n  - rewrite eqOP => bf.\n    move: (bf 1) => [M bm]. \n    rewrite !nearE /=; exists M; split. by  apply : num_real.\n    move => x Mx; rewrite nearE nbhs_normP /=. \n    exists 1; first by [].\n    move => y /=. rewrite -ball_normE /ball_ sub0r normrN /cst normr1 mulr1 => y1.\n    apply: (@le_trans _ _ M _ _).\n    apply: (bm y); by apply: ltW.\n    by apply: ltW.\n  - rewrite eqOP !nearE /+oo /cst normr1; move=> [M [Mr Bf]] r.\n    move: (Bf (2*M)); rewrite nearE /=.\n    have: M < 2 * M by admit.\n    move=> lem /(_ lem) {lem} //=; rewrite nbhs_normP /cst -mulrA mulr1 .\n    move=> [R oR] BR; exists (R^-1 * r * 2 * 2 * M)  => x xr.\n    case: (EM (0 < `|x|)). (*ameliorer*)\n     - move => x0.\n       have r0 : 0 < r by apply: (@lt_le_trans _ _ (`|x|)). \n       move: (BR ((R * (2 * r)^-1) *: x)); simpl. rewrite -ball_normE /ball_ sub0r normrN.\n       have R2r10 : (0 < R/(2*r)) by rewrite divr_gt0 ?mulr_gt0 //=.\n       have: (`|(R / (2 * r)) *: x| < R)%O by rewrite normmZ gtr0_norm //= -mulrA -ltr_pdivl_mull //= mulVf;\n         rewrite ?lt0r_neq0 //= ltr_pdivr_mull ?mulr1 ?mulr_gt0 //= (@le_lt_trans _ _ r) //=;\n         rewrite -ltr_pdivr_mulr //= divff ?lt0r_neq0 //= ltr1n //=.\n       move=> lem /(_ lem) {lem}.\n       rewrite linearZZ normmZ gtr0_norm //= (mulrC R) -(mulrA (2*r)^-1) ler_pdivr_mull ?mulr_gt0 //= (mulrC 2 r).\n       by rewrite -ler_pdivl_mull //= !mulrA.\n     - move => x0.\n       have -> :  x = 0.\n        have : ~~ (0%R < `|x|)%O by apply /negP.\n        by rewrite -leNgt normrE; apply: eqP.\n       have M0 : 0 <= M.\n        have temp : (PosNum oR)%:num = R by [].\n        rewrite -temp in BR; move:  (BR 0 (@ball_center _ _ 0 (PosNum oR))).\n        by rewrite linear0 normr0 -ler_pdivr_mull ?mulr0 //=.        \n       have r0 : 0 <= r by apply: (@le_trans _ _ (`|x|)); rewrite ?normr_ge0 //=.\n       rewrite linear0 normr0 !mulr_ge0 //= ?invr_ge0 ?ltW //=.\n       \nAdmitted.\n\nLemma bounded_imply_landau (f :{linear V->W}) :\n  bounded f -> ((f : V->W) =O_ (0:V) cst (1 : K^o)).\nProof.\n  rewrite eqOP => bf.\n    move: (bf 1) => [M bm]. \n    rewrite !nearE /=; exists M; split. by  apply : num_real.\n    move => x Mx; rewrite nearE nbhs_normP /=. \n    exists 1; first by [].\n    move => y /=. rewrite -ball_normE /ball_ sub0r normrN /cst normr1 mulr1 => y1.\n    apply: (@le_trans _ _ M _ _).\n    apply: (bm y); by apply: ltW.\n    by apply: ltW.\nQed.\n\nLemma denseNE (S : set V) : (not(dense S)) -> (exists O, ( exists x, (open_nbhs x) O) /\\ (O `&` S = set0)).\nProof.\n  rewrite /dense /open_nbhs => /existsNP [X /not_implyP [[x Xx] /not_implyP [ Ox /forallNP A ]]].\n  exists X; split; first by exists x; split.\n  by rewrite -subset0; apply/A => y.\nQed.\n\n\nLemma setIsubset (A B : set V) : A `&` B = set0 -> A `<=` ~` B.\nProof.\n  by rewrite -setD_eq0; move <-; rewrite setDE setCK.\nQed.\n\nLemma linearsub  (a b : V) (f : V -> W ) :\n  linear f -> (f (a-b) = f(a) - f(b)).\nProof.\n  by rewrite addrC -scaleN1r; move ->; rewrite addrC scaleN1r.\nQed.\n\nLemma not_and_or : forall P Q : Prop , ~(P /\\ Q) -> ~ P \\/ ~ Q.\nProof.\n  by move => P Q H; apply: or_asboolP; rewrite !asbool_neg -negb_and -asbool_and; apply /asboolPn.  \nQed.\n\nTheorem Banach_Steinhauss (F: set ((V -> W))):\n  (forall f, (F f) -> bounded f /\\ linear f) ->\n  pointwise_bounded F -> uniform_bounded F.\nProof.\n  move=> Propf.\n  move=> BoundedF.\n  set O := (fun n :nat => \\bigcup_(f in F) ((normr \\o f)@^-1` [set y | y > n%:R])).\n  have O_open: forall n : nat, open ( O n ).\n   - move=>n.\n     apply: open_bigU.\n     move=> i App.\n     apply: (@open_comp _ _ ((normr : W -> K^o) \\o i) [set y | y > n%:R]).\n     have Ci : continuous i.\n     + have Li : linear i by apply Propf.\n       have Bi : bounded i by apply Propf.\n       have Landaui : i =O_ (0:V) cst (1:K^o) by apply (@bounded_imply_landau (Linear Li)).\n       by apply: (@linear_continuous K V W (Linear Li)).\n     move=> x Hx ; apply: continuous_comp.\n       + by apply: Ci.\n       + by apply: norm_continuous.\n      by apply: open_gt.     \n  set O_inf := (\\bigcap_i ( O i)).\n  have  O_infempty : O_inf = set0.\n     rewrite -subset0 => x //=.\n     move: (BoundedF x) => [M HMx].\n     rewrite /O_inf  /O //=  /bigsetI /bigsetU //=.\n     case  /(_ (`|Rtoint (floor M + 1%:~R)|%N)).\n     -  by rewrite /setT.\n     - move=> f  Hf abs; move : (HMx f Hf) => abs2.\n     have: (`|Rtoint (floor M + 1%:~R)|%:R < M) by  apply: (@lt_le_trans _ _ (`|f x|)).\n     have : (M < `|Rtoint(floor M + 1%:~R)|%:R) by apply : floor_nat_comp; apply:  (@le_trans _ _ `|f x|).       \n     by apply : lt_nsym.\n  have BaireV : Baire V by apply : DeBaire.\n  have ContraBaire : exists i : nat, not (dense (O i)).\n   - unfold Baire in BaireV.\n     have BaireO : (forall i : nat, open(O i) /\\ dense (O i)) -> dense (O_inf) by apply (BaireV O).\n     apply contrap  in BaireO.\n     + move: BaireO => /asboolPn /existsp_asboolPn [n /and_asboolP /nandP Hn].\n       by exists n ; case : Hn => /asboolPn.\n    + rewrite /dense O_infempty ; apply /existsNP.\n       exists setT. elim.\n       * by move=> x; rewrite setI0.\n       * by exists point.\n       * by apply: openT.\n  have BaireContra : exists n :nat , exists x : V,\n               exists r : {posnum K}, (ball x r%:num) `<=` (~` (O n)).\n    - move: ContraBaire =>\n      [ i /(denseNE) [ O0 [ [ x /(neighBall) [ r H1 ] ]\n      /((@subsetI_eq0 _ (ball x r%:num) O0 (O i) (O i)) )  ]  ] /(_ H1) ] H2. \n       by exists i; exists x; exists r;apply: setIsubset; apply H2.\n  move: BaireContra => [n [x0 [ r H ] ] k]; exists ((n%:R + n%:R) * k * 2 /r%:num); move=> f Hf y Hx.\n  move: (Propf f Hf) => [ _ linf].\n  case: (eqVneq y 0) => [-> | Zeroy]; last first. \n  - have  majballi : forall f, forall x, F f -> (ball x0 r%:num) x -> (`|f x | <= n%:R)%O.\n    move=> g x Fg Bx; move: (H x Bx).\n    rewrite /O //= /bigsetU //= /setC exists2P -forallNP.\n    move /(_  g).  case /not_and_or ; first by [].\n    by move=> /(@negP ((n%:R < `|g x|)%O)); rewrite -leNgt .\n    have majball : forall f, forall x, F f -> (ball x0 r%:num) x -> (`|f (x - x0) | <= (n%:R + n%:R))%O.\n    move=> g x Fg; move: (Propf g Fg) => [Bg Lg].\n    have Ling : g(x - x0) = g(x) - g(x0) by apply: (@linearsub x x0 g).\n    rewrite Ling.\n    move=> Ballx.\n    move: (majballi g x Fg Ballx) => Majx.\n    move: (majballi g x0 Fg   (ball_center x0 r)) => Majx0.\n    have Majf : `| g x | + `|g x0| <= n%:R + n%:R\n      by apply: (@ler_add _ `|g x| n%:R `|g x0| n%:R).\n    apply: (@le_trans _ _ (`|g x| + `|g x0|) (`|g x - g x0|) (n%:R + n%:R)).\n    - by apply: ler_norm_sub.\n    - by [].\n    have ballprop : ball x0 r%:num (2^-1  * (r%:num / `|y|) *: y  + x0).\n      rewrite -ball_normE /ball_ opprD. \n      rewrite addrC -addrA (@addrC _ (-x0) x0) addrN addr0 normrN normmZ.\n      rewrite R_normZ R_normZ -mulrA -mulrA  -(@normr_id _ _ y) -R_normZ normr_id.\n      rewrite /GRing.scale //= mulVf; last by rewrite normr_eq0. \n      rewrite normr1  mulr1 gtr0_norm; last by rewrite invr_gt0. \n      by rewrite gtr0_norm //=  gtr_pmull //= invf_lt1 //= ltr1n. \n    move: (majball f (2^-1 * (r%:num/`|y|)*:y + x0) Hf ballprop). \n    rewrite -addrA addrN linf.\n    have -> : f 0 =0 by rewrite -(linear0  (Linear linf)). \n    rewrite addr0 normmZ !R_normZ -ler_pdivl_mull //=.\n    rewrite !gtr0_norm //= ; last by rewrite invr_gt0 normr_gt0.\n    rewrite mulrA mulrC invf_div mulrA (@mulrC _ (2^-1) _) invf_div mulrA.\n    move=> Currentmaj {Propf BoundedF O O_open O_inf O_infempty BaireV ContraBaire H majball majballi}.\n    rewrite (@le_trans  _ _ ((n%:R + n%:R) * `|y| * 2 / r%:num)) //= => {Currentmaj}.    \n    rewrite (mulrC (n%:R + n%:R)) -ler_pdivl_mulr //=.\n    rewrite invrK -(mulrC r%:num) -(mulrC r%:num^-1) (mulrA r%:num) mulfV //=. \n    rewrite (mulrC 1) mulr1 -ler_pdivl_mulr //=.  \n    rewrite -(mulrC 2) -(mulrC 2^-1) (mulrA 2^-1) mulVf //= (mulrC 1) mulr1.\n    case: n. \n    - by rewrite addr0 mulr0 (mulrC 0) mulr0.\n    - move => n. \n      rewrite -ler_pdivl_mulr //= -mulrC mulrA mulVf //=.\n      by rewrite (mulrC 1) mulr1. \n    rewrite mulr_gt0 ?invr_gt0 ?normr_gt0 //=. \n    rewrite mulr_gt0 ?invr_gt0 ?normr_gt0 //=. \n    by rewrite invr_neq0; rewrite ?normrE. \n    have -> : f 0 =0 by rewrite -(linear0  (Linear linf)).\n    rewrite normr0 !mulr_ge0 //=.\n    by rewrite (@le_trans _ _ `|y| _ _).\nQed.\n\nEnd banach_steinhauss.\n", "meta": {"author": "tvignon", "repo": "StageL3", "sha": "f419b4fd446d0bc27d56c2de99888c89ecf1c2ba", "save_path": "github-repos/coq/tvignon-StageL3", "path": "github-repos/coq/tvignon-StageL3/StageL3-f419b4fd446d0bc27d56c2de99888c89ecf1c2ba/steinhauss.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7073221315387047}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) : natural :=\n  plus Zero lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj43_coqofml_gdYI7l.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.707322131381462}}
{"text": "Require Import Classical.\nRequire Export Ensembles.\nRequire Import EnsemblesImplicit.\nRequire Export Relation_Definitions.\nRequire Import Relation_Definitions_Implicit.\nRequire Import EnsemblesSpec.\n\nSection MinimalElements.\n\nVariable T:Type.\nVariable R:relation T.\n\n(* R is well-founded if and only if every nonempty subset of\n   T has a minimal element *)\n\nDefinition minimal_element_property : Prop :=\n  forall S:Ensemble T, Inhabited S -> exists x:T, In S x /\\\n    forall y:T, In S y -> ~ R y x.\n\nLemma WF_implies_MEP: well_founded R -> minimal_element_property.\nProof.\nunfold well_founded.\nunfold minimal_element_property.\nintros WF S Hinh.\ndestruct Hinh.\nrevert x H.\napply (@well_founded_ind T R WF\n (fun x:T =>\n  In S x -> exists y:T, In S y /\\ (forall z:T, In S z -> ~ R z y))).\nintros.\ncase (classic (forall y:T, In S y -> ~ R y x)).\nexists x.\nsplit.\nassumption.\nassumption.\n\nintro.\napply not_all_ex_not in H1.\ndestruct H1.\napply imply_to_and in H1.\ndestruct H1.\napply H with x0.\napply NNPP.\nassumption.\nassumption.\nQed.\n\nLemma MEP_implies_WF: minimal_element_property -> well_founded R.\nProof.\nunfold well_founded.\nunfold minimal_element_property.\nintro MEP.\napply NNPP.\nintuition.\napply not_all_ex_not in H.\ndestruct H.\nassert (Inhabited [x:T | ~ Acc R x]).\nexists x.\nconstructor; assumption.\napply MEP in H0.\ndestruct H0.\ndestruct H0.\ndestruct H0.\ncontradict H0.\nconstructor.\nintros.\napply NNPP.\nintuition.\napply H1 with y.\nconstructor; assumption.\nassumption.\nQed.\n\nEnd MinimalElements.\n\nRequire Import ClassicalChoice.\n\nSection DecreasingSequences.\n\n(* R is well-founded if and only if there is no infinite strictly\n   decreasing sequence of elements of T *)\n\nVariable T:Type.\nVariable R:relation T.\n\nDefinition decreasing_sequence_property :=\n  forall a:nat->T, exists n:nat, ~ R (a (S n)) (a n).\n\nLemma WF_implies_DSP: well_founded R -> decreasing_sequence_property.\nProof.\nunfold decreasing_sequence_property.\nintros WF a.\nremember (a 0) as a0.\nrevert a0 a Heqa0.\napply (well_founded_ind WF (fun x:T =>\n  forall a:nat->T, x = a 0 -> exists n:nat, ~ R (a (S n)) (a n))).\nintros.\ncase (classic (R (a 1) (a 0))).\nintro.\npose (b := fun n:nat => a (S n)).\nassert (exists n:nat, ~ R (b (S n)) (b n)).\napply H with (a 1).\nrewrite H0.\nassumption.\ntrivial.\ndestruct H2.\nexists (S x0).\nunfold b in H2.\nassumption.\n\nexists 0.\nassumption.\nQed.\n\nLemma DSP_implies_WF: decreasing_sequence_property -> well_founded R.\nProof.\nunfold decreasing_sequence_property.\nintro DSP.\napply MEP_implies_WF.\nunfold minimal_element_property.\nintro S0.\nintros.\napply NNPP.\nintuition.\nassert (forall x:T, In S0 x -> exists y:T, In S0 y /\\ R y x).\nintros.\napply NNPP.\nintuition.\nassert (forall y:T, ~(In S0 y /\\ R y x)).\napply not_ex_all_not.\nassumption.\napply H0.\nexists x.\nsplit.\nassumption.\nintros.\napply H3 with y.\ntauto.\n\npose (S_type := {x:T | In S0 x}).\nassert (exists f:S_type -> S_type, forall x:S_type,\n  R (proj1_sig (f x)) (proj1_sig x)).\napply choice with (R:=fun x y:S_type => R (proj1_sig y) (proj1_sig x)).\nintro.\ndestruct x.\nsimpl.\npose proof (H1 x i).\ndestruct H2.\ndestruct H2.\nexists (exist (fun x:T => In S0 x) x0 H2).\nsimpl.\nassumption.\n\ndestruct H2 as [f Hf].\n\ndestruct H.\npose (b := nat_rect (fun n:nat => S_type)\n  (exist (fun x:T => In S0 x) x H)\n  (fun (n:nat) (x:S_type) => f x)).\nsimpl in b.\npose (a := fun n:nat => (proj1_sig (b n))).\nassert (forall n:nat, R (a (S n)) (a n)).\nunfold a.\nintro.\nsimpl.\napply Hf.\n\ncontradict DSP.\napply ex_not_not_all.\nexists a.\napply all_not_not_ex.\nauto.\nQed.\n\nEnd DecreasingSequences.\n", "meta": {"author": "coq-community", "repo": "zorns-lemma", "sha": "aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8", "save_path": "github-repos/coq/coq-community-zorns-lemma", "path": "github-repos/coq/coq-community-zorns-lemma/zorns-lemma-aaf46b0c5f7857ce9211cbaaf36f184ca810e0e8/Classical_Wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.707322129067652}}
{"text": "Require Export XR_plus_IZR_NEG_POS.\n\nLocal Open Scope R_scope.\n\nArguments Z.add _ _ : simpl nomatch.\n\nLemma plus_IZR : forall n m:Z, IZR (n + m) = IZR n + IZR m.\nProof.\n  intros n.\n  destruct n as [ | n | n ].\n  {\n    intro m.\n    simpl.\n    rewrite Rplus_0_l.\n    reflexivity.\n  }\n  {\n    intro m.\n    simpl.\n    destruct m as [ | m | m ].\n    {\n      simpl.\n      rewrite Rplus_0_r.\n      reflexivity.\n    }\n    {\n      simpl.\n      rewrite Pos2Nat.inj_add.\n      rewrite plus_INR.\n      reflexivity.\n    }\n    {\n      rewrite plus_IZR_NEG_POS.\n      simpl.\n      reflexivity.\n    }\n  }\n  {\n    simpl.\n    intro m.\n    destruct m.\n    {\n      simpl.\n      rewrite Rplus_0_r.\n      reflexivity.\n    }\n    {\n      rewrite Z.add_comm.\n      rewrite plus_IZR_NEG_POS.\n      simpl.\n      rewrite Rplus_comm.\n      reflexivity.\n    }\n    {\n      simpl.\n      rewrite Pos2Nat.inj_add.\n      rewrite plus_INR.\n      rewrite Ropp_plus_distr.\n      reflexivity.\n    }\n  }\nQed.\n\n\n\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_plus_IZR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7073221225979509}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** _Maps_ (or _dictionaries_) are ubiquitous data structures both in\n    ordinary programming and in the theory of programming languages;\n    we're going to need them in many places in the coming chapters.\n\n    They also make a nice case study using ideas we've seen in\n    previous chapters, including building data structures out of\n    higher-order functions (from [Basics] and [Poly]) and the use of\n    reflection to streamline proofs (from [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which instead return an\n    [option] to indicate success or failure.  The latter is defined in\n    terms of the former, using [None] as the default element. *)\n\n(* ################################################################# *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we begin...\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (nor, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Datatypes.\nRequire Export Coq.Strings.String.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\n\n(** Documentation for the standard library can be found at\n    https://coq.inria.fr/library/.\n\n    The [Search] command is a good way to look for theorems involving\n    objects of specific types. See [Lists] for a reminder of how\n    to use it. *)\n\n(** If you want to find out how or where a notation is defined, the\n    [Locate] command is useful.  For example, where is the natural\n    addition operation defined in the standard library? *)\n\nLocate \"+\".\n\n(** (There are several uses of the [+] notation, but only one for\n    naturals.) *)\n\nPrint Init.Nat.add.\n\n(** We'll see some more uses of [Locate] in the [Imp] chapter. *)\n\n(* ################################################################# *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we will use to index into\n    our maps.  In [Lists.v] we introduced a fresh type [id] for a\n    similar purpose; here and for the rest of _Software Foundations_\n    we will use the [string] type from Coq's standard library. *)\n\n(** To compare strings, we use the function [eqb] from the [String]\n    module in the standard library. *)\n\nCheck String.eqb_refl :\n  forall x : string, (x =? x)%string = true.\n\n(** We will often use a few basic properties of string equality... *)\nCheck String.eqb_eq :\n  forall n m : string, (n =? m)%string = true <-> n = m.\nCheck String.eqb_neq :\n  forall n m : string, (n =? m)%string = false <-> n <> m.\nCheck String.eqb_spec :\n  forall x y : string, reflect (x = y) (String.eqb x y).\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about its behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more \"extensional\" view of\n    maps: two maps that respond to queries in the same way will be\n    represented as exactly the same function, rather than just as\n    \"equivalent\" list structures.  This, in turn, simplifies proofs\n    that use maps. *)\n\n(** We build up to partial maps in two steps.  First, we define a type\n    of _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A : Type) := string -> A.\n\n(** Intuitively, a total map over an element type [A] is just a\n    function that can be used to look up [string]s, yielding [A]s. *)\n\n(** The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any string. *)\n\nDefinition t_empty {A : Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the map-updating function, which (as always)\n    takes a map [m], a key [x], and a value [v] and returns a new map\n    that takes [x] to [v] and takes every other key to whatever [m]\n    does.  The novelty here is that we achieve this effect by wrapping\n    a new function around the old one. *)\n\nDefinition t_update {A : Type} (m : total_map A)\n                    (x : string) (v : A) :=\n  fun x' => if String.eqb x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming:\n    [t_update] takes a _function_ [m] and yields a new function\n    [fun x' => ...] that behaves like the desired map. *)\n\n(** For example, we can build a map taking [string]s to [bool]s, where\n    [\"foo\"] and [\"bar\"] are mapped to [true] and every other key is\n    mapped to [false], like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) \"foo\" true)\n           \"bar\" true.\n\n(** Next, let's introduce some notations to facilitate working with\n    maps. *)\n\n(** First, we use the following notation to represent an empty total\n    map with a default value. *)\nNotation \"'_' '!->' v\" := (t_empty v)\n  (at level 100, right associativity).\n\nExample example_empty := (_ !-> false).\n\n(** We next introduce a convenient notation for extending an existing\n    map with a new binding. *)\nNotation \"x '!->' v ';' m\" := (t_update m x v)\n                              (at level 100, v at next level, right associativity).\n\n(** The [examplemap] above can now be defined as follows: *)\n\nDefinition examplemap' :=\n  ( \"bar\" !-> true;\n    \"foo\" !-> true;\n    _     !-> false\n  ).\n\n(** This completes the definition of total maps.  Note that we\n    don't need to define a [find] operation on this representation of\n    maps because it is just function application! *)\n\nExample update_example1 : examplemap' \"baz\" = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap' \"foo\" = true.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap' \"quux\" = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap' \"bar\" = true.\nProof. reflexivity. Qed.\n\n(** When we use maps in later chapters, we'll need several fundamental\n    facts about how they behave. *)\n\n(** Even if you don't bother to work the following exercises,\n    make sure you thoroughly understand the statements of the\n    lemmas! *)\n\n(** (Some of the proofs require the functional extensionality axiom,\n    which was discussed in the [Logic] chapter.) *)\n\n(** **** Exercise: 1 star, standard, optional (t_apply_empty)\n\n    First, the empty map returns its default element for all keys: *)\n\nLemma t_apply_empty : forall (A : Type) (x : string) (v : A),\n  (_ !-> v) x = v.\nProof.\n  reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_eq)\n\n    Next, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall (A : Type) (m : total_map A) x v,\n  (x !-> v ; m) x = v.\nProof.\n  intros. unfold t_update. rewrite eqb_refl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_neq)\n\n    On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (A : Type) (m : total_map A) x1 x2 v,\n  x1 <> x2 ->\n  (x1 !-> v ; m) x2 = m x2.\nProof.\n  intros A m x1 x2 v H.\n  unfold t_update. destruct (eqb_spec x1 x2). exfalso. apply H. apply e. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (t_update_shadow)\n\n    If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall (A : Type) (m : total_map A) x v1 v2,\n  (x !-> v2 ; x !-> v1 ; m) = (x !-> v2 ; m).\nProof.\n  intros A m x v1 v2.\n  apply functional_extensionality. intros x'.\n  unfold t_update.\n  destruct (eqb_spec x x') as [_ | _]. reflexivity. reflexivity.\nQed.\n(** [] *)\n(** **** Exercise: 2 stars, standard (t_update_same)\n\n    Given [string]s [x1] and [x2], we can use the tactic\n    [destruct (eqb_spec x1 x2)] to simultaneously perform case\n    analysis on the result of [String.eqb x1 x2] and generate\n    hypotheses about the equality (in the sense of [=]) of [x1] and\n    [x2].  With the example in chapter [IndProp] as a template,\n    use [String.eqb_spec] to prove the following theorem, which states\n    that if we update a map to assign key [x] the same value as it\n    already has in [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall (A : Type) (m : total_map A) x,\n  (x !-> m x ; m) = m.\nProof.\n  intros A m x.\n  apply functional_extensionality.\n  intros x'.\n  unfold t_update.\n  destruct (eqb_spec x x') as [H | _]. rewrite H. reflexivity. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard, especially useful (t_update_permute)\n\n    Similarly, use [String.eqb_spec] to prove one final property of\n    the [update] function: If we update a map [m] at two distinct\n    keys, it doesn't matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (A : Type) (m : total_map A)\n                                  v1 v2 x1 x2,\n  x2 <> x1 ->\n  (x1 !-> v1 ; x2 !-> v2 ; m)\n  =\n  (x2 !-> v2 ; x1 !-> v1 ; m).\nProof.\n  intros A m v1 v2 x1 x2 H.\n  apply functional_extensionality.\n  intros x'.\n  unfold t_update.\n  destruct (eqb_spec x1 x') as [H1 | H1].\n  - destruct (eqb_spec x2 x') as [H2 | _].\n    + exfalso. apply H. rewrite H1. rewrite H2. reflexivity.\n    + reflexivity.\n  - destruct (eqb_spec x2 x') as [H2 | H2].\n    + reflexivity.\n    + reflexivity.\nQed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Lastly, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A : Type) := total_map (option A).\n\nDefinition empty {A : Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A : Type} (m : partial_map A)\n           (x : string) (v : A) :=\n  (x !-> Some v ; m).\n\n(** We introduce a similar notation for partial maps: *)\nNotation \"x '|->' v ';' m\" := (update m x v)\n  (at level 100, v at next level, right associativity).\n\n(** We can also hide the last case when it is empty. *)\nNotation \"x '|->' v\" := (update empty x v)\n  (at level 100).\n\nDefinition examplepmap :=\n  (\"Church\" |-> true ; \"Turing\" |-> false).\n\n(** We now straightforwardly lift all of the basic lemmas about total\n    maps to partial maps.  *)\n\nLemma apply_empty : forall (A : Type) (x : string),\n  @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall (A : Type) (m : partial_map A) x v,\n  (x |-> v ; m) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (A : Type) (m : partial_map A) x1 x2 v,\n  x2 <> x1 ->\n  (x2 |-> v ; m) x1 = m x1.\nProof.\n  intros A m x1 x2 v H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall (A : Type) (m : partial_map A) x v1 v2,\n  (x |-> v2 ; x |-> v1 ; m) = (x |-> v2 ; m).\nProof.\n  intros A m x v1 v2. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall (A : Type) (m : partial_map A) x v,\n  m x = Some v ->\n  (x |-> v ; m) = m.\nProof.\n  intros A m x v H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (A : Type) (m : partial_map A)\n                                x1 x2 v1 v2,\n  x2 <> x1 ->\n  (x1 |-> v1 ; x2 |-> v2 ; m) = (x2 |-> v2 ; x1 |-> v1 ; m).\nProof.\n  intros A m x1 x2 v1 v2. unfold update.\n  apply t_update_permute.\nQed.\n\n(** One last thing: For partial maps, it's convenient to introduce a\n    notion of map inclusion, stating that all the entries in one map\n    are also present in another: *)\n\nDefinition includedin {A : Type} (m m' : partial_map A) :=\n  forall x v, m x = Some v -> m' x = Some v.\n\n(** We can then show that map update preserves map inclusion -- that is: *)\n\nLemma includedin_update : forall (A : Type) (m m' : partial_map A)\n                                 (x : string) (vx : A),\n  includedin m m' ->\n  includedin (x |-> vx ; m) (x |-> vx ; m').\nProof.\n  unfold includedin.\n  intros A m m' x vx H.\n  intros y vy.\n  destruct (eqb_spec x y) as [Hxy | Hxy].\n  - rewrite Hxy.\n    rewrite update_eq. rewrite update_eq. intro H1. apply H1.\n  - rewrite update_neq. rewrite update_neq.\n    + apply H.\n    + apply Hxy.\n    + apply Hxy.\nQed.\n\n(** This property is quite useful for reasoning about languages with\n    variable binding -- e.g., the Simply Typed Lambda Calculus, which\n    we will see in _Programming Language Foundations_, where maps are\n    used to keep track of which program variables are defined in a\n    given scope. *)\n\n(* 2022-08-08 17:13 *)\n", "meta": {"author": "marshall-lee", "repo": "software_foundations", "sha": "d45ee7466f45de8d836692a3455742764ed58b83", "save_path": "github-repos/coq/marshall-lee-software_foundations", "path": "github-repos/coq/marshall-lee-software_foundations/software_foundations-d45ee7466f45de8d836692a3455742764ed58b83/lf/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059560743422, "lm_q2_score": 0.8918110540642805, "lm_q1q2_score": 0.7073006586713181}}
{"text": "Example auto_example_1' : forall (P Q R: Prop),\n  (P -> Q) -> (Q -> R) -> P -> R.\nProof.\n  auto.\nQed.\n\nExample auto_example_2 : forall P Q R S T U : Prop,\n  (P -> Q) ->\n  (P -> R) ->\n  (T -> R) ->\n  (S -> T -> U) ->\n  ((P->Q) -> (P->S)) ->\n  T ->\n  P ->\n  U.\nProof. auto. Qed.\n\n\nExample auto_example_3 : forall (P Q R S T U: Prop),\n  (P -> Q) ->\n  (Q -> R) ->\n  (R -> S) ->\n  (S -> T) ->\n  (T -> U) ->\n  P ->\n  U.\nProof.\n  (* 当 auto 无法解决此目标时，它就什么也不做 *)\n  auto.\n  (* 可选的参数用来控制它的搜索深度（默认为 5） *)\n  auto 6.\nQed.\n\nExample auto_example_5: 2 = 2.\nProof.\n  info_auto.\nQed.\nFrom Coq Require Import omega.Omega.\nLemma le_antisym : forall n m: nat, (n <= m /\\ m <= n) -> n = m.\nProof. intros. omega. Qed.\n\nExample auto_example_6 : forall n m p : nat,\n  (n <= p -> (n <= m /\\ m <= n)) ->\n  n <= p ->\n  n = m.\nProof.\n  info_auto using le_antisym.\nQed.", "meta": {"author": "pzzp", "repo": "sf", "sha": "d60708e408a4f9342142cb8de51d0d4d75f144f9", "save_path": "github-repos/coq/pzzp-sf", "path": "github-repos/coq/pzzp-sf/sf-d60708e408a4f9342142cb8de51d0d4d75f144f9/auto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.7073006430074287}}
{"text": "Inductive gcd: nat -> nat -> nat -> Prop :=\n  | gcd_O n : gcd n O n\n  | gcd_step n m p : gcd m n p -> gcd (n + m) n p\n  | gcd_swap n m p : gcd m n p -> gcd n m p.\n\nExample gcd_ex1 : gcd 6 4 2.\nProof.\n  apply gcd_step with (n := 4).\n  apply gcd_swap.\n  apply gcd_step with (n := 2).\n  apply gcd_step with (n := 2).\n  apply gcd_swap.\n  apply gcd_O.\nQed.\n\nDefinition task := forall n, gcd n (n + 1) 1.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/016/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.707270572490939}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (z : natural) (x : natural)\n  : natural := mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj275_coqofml_VlpSVO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.707217859752483}}
{"text": "(* permutations of sequences of natural numbers between 0 and n-1 *)\n\nSet Nested Proofs Allowed.\nSet Implicit Arguments.\n\nRequire Import Utf8 Arith Bool.\nImport List List.ListNotations.\nImport Init.Nat.\n\nRequire Import Misc PermutationFun SortingFun SortRank.\nRequire Import IterAnd.\nRequire Import Pigeonhole.\n\nDefinition comp {A B C} (f : B → C) (g : A → B) x := f (g x).\nDefinition comp_list (la lb : list nat) := map (λ i, nth i la 0) lb.\n\nNotation \"σ₁ ° σ₂\" := (comp_list σ₁ σ₂) (at level 40, left associativity).\n\n(* Permutations of {0, 1, 2, ... n-1} *)\n\nDefinition permut_seq l := permutation Nat.eqb l (seq 0 (length l)).\nDefinition permut_seq_with_len n f := permut_seq f ∧ length f = n.\n\nTheorem permut_seq_NoDup : ∀ l, permut_seq l → NoDup l.\nProof.\nintros * Hp.\nunfold permut_seq in Hp.\napply (permutation_sym Nat.eqb_eq) in Hp.\napply (permutation_NoDup Nat.eqb_eq Hp (seq_NoDup _ _)).\nQed.\n\nTheorem permut_seq_ub : ∀ l, permut_seq l → AllLt l (length l).\nProof.\nintros * Hp.\nunfold permut_seq in Hp.\nspecialize (permutation_in_iff Nat.eqb_eq Hp) as H1.\nintros i Hi.\napply H1 in Hi.\nnow apply in_seq in Hi.\nQed.\n\nTheorem permut_seq_iff : ∀ l,\n  permut_seq l ↔ AllLt l (length l) ∧ NoDup l.\nProof.\nintros.\nsplit; intros Hl. {\n  now split; [ apply permut_seq_ub | apply permut_seq_NoDup ].\n}\ndestruct Hl as (Hp1, Hp2).\nunfold permut_seq.\nremember (length l) as len eqn:Hlen; symmetry in Hlen.\nrevert l Hlen Hp1 Hp2.\ninduction len; intros. {\n  now apply length_zero_iff_nil in Hlen; subst l.\n}\nrewrite seq_S; cbn.\nunfold AllLt in Hp1.\nassert (H : len ∈ l). {\n  destruct (equality_in_dec Nat.eqb_eq len l) as [H1| H1]; [ easy | exfalso ].\n  specialize (pigeonhole_list len l) as H2.\n  rewrite Hlen in H2.\n  assert (H : len < S len) by easy.\n  specialize (H2 H); clear H.\n  assert (H : ∀ i, i ∈ l → i < len). {\n    intros i Hi.\n    specialize (Hp1 _ Hi).\n    destruct (Nat.eq_dec i len) as [Hil| Hil]; [ | flia Hp1 Hil ].\n    now subst i.\n  }\n  specialize (H2 H); clear H.\n  remember (pigeonhole_comp_list l) as xx eqn:Hxx.\n  symmetry in Hxx.\n  destruct xx as (i, j).\n  specialize (H2 _ _ eq_refl).\n  destruct H2 as (Hil & Hj & H & Hij).\n  apply H; clear H.\n  rewrite <- Hlen in Hil, Hj.\n  now apply (NoDup_nth l 0).\n}\napply in_split in H.\ndestruct H as (l1 & l2 & Hl); subst l.\napply (permutation_elt Nat.eqb_eq).\nrewrite app_nil_r.\napply IHlen. {\n  rewrite app_length in Hlen; cbn in Hlen.\n  rewrite Nat.add_succ_r in Hlen.\n  apply Nat.succ_inj in Hlen.\n  now rewrite <- app_length in Hlen.\n} {\n  intros i Hi.\n  specialize (Hp1 i) as H1.\n  assert (H : i ∈ l1 ++ len :: l2). {\n    apply in_app_or in Hi; apply in_or_app.\n    destruct Hi as [Hi| Hi]; [ now left | now right; right ].\n  }\n  specialize (H1 H); clear H.\n  destruct (Nat.eq_dec i len) as [H2| H2]; [ | flia H1 H2 ].\n  subst i; clear H1.\n  apply NoDup_app_iff in Hp2.\n  destruct Hp2 as (H1 & H2 & H4).\n  apply NoDup_cons_iff in H2.\n  destruct H2 as (H2 & H3).\n  apply in_app_or in Hi.\n  destruct Hi as [Hi| Hi]; [ | easy ].\n  specialize (H4 _ Hi).\n  now exfalso; apply H4; left.\n} {\n  apply NoDup_app_iff in Hp2.\n  apply NoDup_app_iff.\n  destruct Hp2 as (H1 & H2 & H3).\n  apply NoDup_cons_iff in H2.\n  split; [ easy | ].\n  split; [ easy | ].\n  intros i Hi.\n  specialize (H3 _ Hi).\n  intros H4; apply H3.\n  now right.\n}\nQed.\n\nTheorem comp_list_app_distr_l : ∀ la lb lc,\n  la ° (lb ++ lc) = la ° lb ++ la ° lc.\nProof.\nintros.\nunfold \"°\".\nnow rewrite map_app.\nQed.\n\n(* *)\n\nTheorem NoDup_nat : ∀ l,\n  NoDup l\n  → (∀ i j, i < length l → j < length l → nth i l 0 = nth j l 0 → i = j).\nProof.\nintros * Hnd.\nnow apply NoDup_nth.\nQed.\nArguments NoDup_nat : clear implicits.\n\nTheorem nat_NoDup : ∀ l,\n  (∀ i j, i < length l → j < length l → nth i l 0 = nth j l 0 → i = j)\n  → NoDup l.\nProof.\nintros * Hnd.\nnow apply NoDup_nth in Hnd.\nQed.\n\nTheorem permut_list_without : ∀ n l,\n  permut_seq l\n  → n < length l\n  → (∀ i, i < length l → nth i l 0 ≠ n)\n  → False.\nProof.\nintros * Hp Hn Hnn.\nspecialize (pigeonhole_list (length l) (n :: l)) as H1.\nspecialize (H1 (Nat.lt_succ_diag_r _)).\nassert (H : ∀ x, x ∈ n :: l → x < length l). {\n  intros z Hz.\n  destruct Hz as [Hz| Hz]; [ now subst z | now apply permut_seq_ub ].\n}\nspecialize (H1 H); clear H.\nremember (pigeonhole_comp_list (n :: l)) as xx eqn:Hxx.\nsymmetry in Hxx.\ndestruct xx as (x, x').\nspecialize (H1 x x' eq_refl).\ndestruct H1 as (Hxl & Hx'l & Hxx' & Hnxx).\ndestruct x. {\n  destruct x'; [ easy | cbn in Hnxx ].\n  cbn in Hx'l; apply Nat.succ_lt_mono in Hx'l.\n  specialize (Hnn x' Hx'l).\n  now symmetry in Hnxx.\n} {\n  cbn in Hxl; apply Nat.succ_lt_mono in Hxl.\n  destruct x'. {\n    cbn in Hnxx.\n    now specialize (Hnn x Hxl).\n  }\n  cbn in Hnxx.\n  cbn in Hx'l; apply Nat.succ_lt_mono in Hx'l.\n  specialize (permut_seq_NoDup Hp) as Hp2.\n  specialize (NoDup_nat _ Hp2 x x' Hxl Hx'l Hnxx) as H1.\n  now destruct H1.\n}\nQed.\n\nTheorem nat_decidable_not_forall_exists_not : ∀ (P : nat → _) n,\n  (∀ i, Decidable.decidable (P i))\n  → ¬ (∀ i, i < n → P i)\n  → ∃ i, i < n ∧ ¬ P i.\nProof.\nintros * Hdec Hin.\ninduction n; [ now exfalso; apply Hin | ].\ndestruct (Hdec n) as [Hn| Hn]; [ | now exists n ].\nassert (H : ¬ (∀ i, i < n → P i)). {\n  intros H2.\n  apply Hin.\n  intros k Hk.\n  destruct (Nat.eq_dec k n) as [Hkn| Hkn]; [ now subst k | ].\n  apply H2.\n  flia Hk Hkn.\n}\nspecialize (IHn H); clear H.\ndestruct IHn as (k & Hkn & Hpk).\nexists k.\nsplit; [ | easy ].\nflia Hkn.\nQed.\n\nTheorem permut_list_surj : ∀ n l,\n  permut_seq l\n  → n < length l\n  → ∃ i, i < length l ∧ nth i l 0 = n.\nProof.\nintros * Hp Hn.\nspecialize (permut_list_without Hp Hn) as H1.\nspecialize nat_decidable_not_forall_exists_not as H2.\nspecialize (H2 (λ i, nth i l 0 ≠ n)).\ncbn in H2.\nenough (H : ∃ i, i < length l ∧ ¬ nth i l 0 ≠ n). {\n  destruct H as (i & Hil & Hni).\n  exists i; split; [ easy | ].\n  now destruct (Nat.eq_dec (nth i l 0) n).\n}\napply H2; [ | easy ].\nintros i.\nnow destruct (Nat.eq_dec (nth i l 0) n) as [H| H]; [ right | left ].\nQed.\n\nTheorem permut_comp_assoc : ∀ n f g h,\n  length g = n\n  → length h = n\n  → permut_seq h\n  → f ° (g ° h) = (f ° g) ° h.\nProof.\nintros * Hg Hh Hph.\nunfold \"°\", comp_list; cbn.\nrewrite map_map.\napply map_ext_in.\nintros i Hi.\nrewrite (List_map_nth' 0); [ easy | ].\nrewrite Hg, <- Hh.\nnow apply permut_seq_ub.\nQed.\n\nArguments permut_comp_assoc n%nat [f g h]%list.\n\n(*\n   Canonical Symmetric Group.\n\n   In set theory, there is one only symmetric group of order n.\n\n   Here, a symmetric group (of order n) is a list of n! permutations,\n   which can be ordered in any order. There are actually n!! (factorial\n   of factorial n) possible orders.\n\n   There is one that we call \"canonical\" because the generated permutation\n   are in alphabetic order.\n\n   The canonical symmetric group is built this way. The k-th permutation\n   is a vector of size n where\n   - the first value is k/fact(n-1)\n   - the rest is the (k mod fact(n-1))-th permutation of n-1 values\n     (from 0 to n-2) where\n     * all values less than the first value (k/fact(n-1)) are unchanged\n     * all values greater or equal to it are increased by 1\n   Example. For n=4 and k=0\n   - first value: 0\n   - rest: shift of 0;1;2 by 1, i.e. 1;2;3\n   Result : 0;1;2;3\n   Other example. For n=4 and k=13\n   - first value: 13/3! = 13/6 = 2\n   - rest: k' = 13 mod 3! = 13 mod 6 = 1 for n'=3, resulting 0;2;1\n     0 and 1 are not shifted (both < 2), 2 is shifted, resulting 0;3;1\n     final result: 2;0;3;1\n  *)\n\nDefinition succ_when_ge k a := a + Nat.b2n (k <=? a).\n\n(* k-th canonic permutation of order n *)\nFixpoint canon_sym_gr_list n k : list nat :=\n  match n with\n  | 0 => []\n  | S n' =>\n      k / n'! ::\n      map (succ_when_ge (k / n'!)) (canon_sym_gr_list n' (k mod n'!))\n  end.\n\n(* all canonic permutations of \"seq 0 n\" *)\nDefinition canon_sym_gr_list_list n : list (list nat) :=\n  map (canon_sym_gr_list n) (seq 0 n!).\n\n(* all permutations of a list of anything *)\nDefinition all_permut {A} (l : list A) : list (list A) :=\n  match l with\n  | [] => [[]]\n  | d :: _ =>\n      map (λ p, map (λ i, nth i l d) p) (canon_sym_gr_list_list (length l))\n  end.\n\nDefinition is_sym_gr_list n (ll : list (list nat)) :=\n  (∀ i, i < length ll →\n   length (nth i ll []) = n ∧\n   permut_seq (nth i ll [])) ∧\n  (∀ i j, i < length ll → j < length ll →\n   nth i ll [] = nth j ll [] → i = j) ∧\n  (∀ l, permut_seq_with_len n l → l ∈ ll).\n\nTheorem comp_length : ∀ la lb,\n  length (la ° lb) = length lb.\nProof.\nintros.\nunfold \"°\"; cbn.\nnow rewrite map_length.\nQed.\n\nTheorem comp_isort_rank_r : ∀ rel l,\n  l ° isort_rank rel l = isort rel l.\nProof.\nintros.\napply List_eq_iff.\nrewrite comp_length, isort_rank_length, isort_length.\nsplit; [ easy | ].\nintros d i.\ndestruct (lt_dec i (length l)) as [Hil| Hil]. 2: {\n  apply Nat.nlt_ge in Hil.\n  rewrite nth_overflow; [ | now rewrite comp_length, isort_rank_length ].\n  rewrite nth_overflow; [ easy | now rewrite isort_length ].\n}\nrewrite nth_indep with (d' := 0). 2: {\n  now rewrite comp_length, isort_rank_length.\n}\nsymmetry.\nrewrite nth_indep with (d' := 0); [ | now rewrite isort_length ].\nsymmetry.\nunfold \"°\".\nrewrite (List_map_nth' 0); [ | now rewrite isort_rank_length ].\nspecialize (isort_isort_rank rel 0 l) as H1.\napply (f_equal (λ l, nth i l 0)) in H1.\nrewrite (List_map_nth' 0) in H1; [ | now rewrite isort_rank_length ].\neasy.\nQed.\n\n(* *)\n\nTheorem perm_assoc_permut_seq : ∀ A (eqb : A → _),\n  equality eqb →\n  ∀ la lb,\n  permutation eqb la lb\n  → permut_seq (permutation_assoc eqb la lb).\nProof.\nintros * Heqb * Hpab.\nunfold permut_seq.\nrewrite (permutation_assoc_length Heqb); [ | easy ].\nnow apply (permutation_permutation_assoc Heqb).\nQed.\n\nTheorem permut_seq_permutation : ∀ n la lb,\n  permut_seq_with_len n la\n  → permut_seq_with_len n lb\n  → permutation Nat.eqb la lb.\nProof.\nintros * Ha Hb.\ndestruct Ha as (Ha, Hal).\ndestruct Hb as (Hb, Hbl).\nunfold permut_seq in Ha, Hb.\neapply (permutation_trans Nat.eqb_eq); [ apply Ha | ].\nrewrite Hal, <- Hbl.\nnow apply (permutation_sym Nat.eqb_eq).\nQed.\n\nTheorem permutation_permut : ∀ la lb,\n  permutation Nat.eqb la lb\n  → permut_seq la\n  → permut_seq lb.\nProof.\nintros * Hpab Ha.\nunfold permut_seq in Ha |-*.\neapply (permutation_trans Nat.eqb_eq). {\n  apply (permutation_sym Nat.eqb_eq), Hpab.\n}\nnow rewrite (permutation_length Hpab) in Ha.\nQed.\n\n(* *)\n\nTheorem permut_seq_app_max : ∀ l,\n  permut_seq (l ++ [length l])\n  → permut_seq l.\nProof.\nintros * Hp.\nunfold permut_seq in Hp |-*.\nrewrite app_length in Hp; cbn in Hp.\nrewrite Nat.add_1_r, seq_S in Hp; cbn in Hp.\napply (permutation_app_inv Nat.eqb_eq) in Hp.\nnow do 2 rewrite app_nil_r in Hp.\nQed.\n\nTheorem sorted_permut : ∀ l,\n  permut_seq l\n  → sorted Nat.leb l\n  → l = seq 0 (length l).\nProof.\nintros * Hl Hs.\nunfold permut_seq in Hl.\napply (sorted_sorted_permuted Nat.eqb_eq Nat_leb_antisym); [ | easy | | ]. {\n  apply Nat_leb_trans.\n} {\n  apply sorted_nat_ltb_leb_incl, sorted_seq.\n}\neasy.\nQed.\n\n(* *)\n\nTheorem permut_isort_leb : ∀ l,\n  permut_seq l\n  → isort Nat.leb l = seq 0 (length l).\nProof.\nintros * Hp.\nspecialize (sorted_isort Nat_leb_total_relation l) as Hbs.\nspecialize (permuted_isort Nat.leb Nat.eqb_eq l) as Hps.\nremember (isort Nat.leb l) as l'; clear Heql'.\nspecialize permutation_permut as Hpl'.\nspecialize (Hpl' l l' Hps Hp).\nmove l' before l; move Hpl' before Hp.\nreplace (length l) with (length l'). 2: {\n  now apply permutation_length in Hps.\n}\nclear l Hp Hps.\nrename l' into l.\nnow apply sorted_permut.\nQed.\n\nTheorem permut_comp_isort_rank_r : ∀ l,\n  permut_seq l\n  → l ° isort_rank Nat.leb l = seq 0 (length l).\nProof.\nintros * Hp.\nrewrite comp_isort_rank_r.\nnow apply permut_isort_leb.\nQed.\n\nTheorem permut_isort_permut : ∀ i l,\n  permut_seq l\n  → i < length l\n  → nth (nth i l 0) (isort_rank Nat.leb l) 0 = i.\nProof.\nintros * Hp Hil.\nspecialize (permut_comp_isort_rank_r Hp) as H1.\napply List_eq_iff in H1.\ndestruct H1 as (_, H1).\nspecialize (H1 0).\nunfold \"°\" in H1.\nassert\n  (H2 : ∀ j, j < length l → nth (nth j (isort_rank Nat.leb l) 0) l 0 = j). {\n  intros j Hj.\n  specialize (H1 j).\n  rewrite (List_map_nth' 0) in H1; [ | now rewrite isort_rank_length ].\n  now rewrite seq_nth in H1.\n}\nclear H1.\nspecialize (H2 (nth i l 0)) as H2.\nassert (H : nth i l 0 < length l). {\n  apply permut_seq_ub; [ easy | now apply nth_In ].\n}\nspecialize (H2 H); clear H.\napply NoDup_nat in H2; [ easy | now apply permut_seq_NoDup | | easy ].\napply isort_rank_ub.\nnow intros H; subst l.\nQed.\n\nTheorem permut_comp_isort_rank_l : ∀ l,\n  permut_seq l\n  → isort_rank Nat.leb l ° l = seq 0 (length l).\nProof.\nintros * Hp.\napply List_eq_iff.\nrewrite comp_length, seq_length.\nsplit; [ easy | ].\nintros d i.\ndestruct (lt_dec i (length l)) as [Hil| Hil]. 2: {\n  apply Nat.nlt_ge in Hil.\n  rewrite nth_overflow; [ | now rewrite comp_length ].\n  rewrite nth_overflow; [ easy | now rewrite seq_length ].\n}\nrewrite seq_nth; [ | easy ].\nrewrite nth_indep with (d' := 0); [ | now rewrite comp_length ].\nclear d.\nunfold \"°\".\nrewrite (List_map_nth' 0); [ | easy ].\nnow apply permut_isort_permut.\nQed.\n\nTheorem permut_permut_isort : ∀ i l,\n  permut_seq l\n  → i < length l\n  → nth (nth i (isort_rank Nat.leb l) 0) l 0 = i.\nProof.\nintros * Hp Hil.\nspecialize (permut_comp_isort_rank_l Hp) as H1.\napply List_eq_iff in H1.\ndestruct H1 as (_, H1).\nspecialize (H1 0).\nunfold \"°\" in H1.\nassert\n  (H2 : ∀ j, j < length l → nth (nth j l 0) (isort_rank Nat.leb l) 0 = j). {\n  intros j Hj.\n  specialize (H1 j).\n  rewrite (List_map_nth' 0) in H1; [ | easy ].\n  now rewrite seq_nth in H1.\n}\nclear H1.\nspecialize (H2 (nth i (isort_rank Nat.leb l) 0)) as H2.\nassert (H : nth i (isort_rank Nat.leb l) 0 < length l). {\n  apply isort_rank_ub.\n  now intros H; subst l.\n}\nspecialize (H2 H); clear H.\nspecialize (NoDup_isort_rank Nat.leb l) as H3.\napply (NoDup_nat _ H3) in H2; [ easy | | ]. 2: {\n  now rewrite isort_rank_length.\n}\nrewrite isort_rank_length.\napply permut_seq_ub; [ easy | ].\napply nth_In.\napply isort_rank_ub.\nnow intros H; subst l.\nQed.\n\n(* transposition *)\n\nDefinition transposition i j k :=\n  if k =? i then j else if k =? j then i else k.\n\nDefinition list_swap_elem {A} d (l : list A) i j :=\n  map (λ k, nth (transposition i j k) l d) (seq 0 (length l)).\n\nTheorem fold_transposition : ∀ i j k,\n  (if k =? i then j else if k =? j then i else k) = transposition i j k.\nProof. easy. Qed.\n\nTheorem transposition_lt : ∀ i j k n,\n  i < n\n  → j < n\n  → k < n\n  → transposition i j k < n.\nProof.\nintros * Hi Hj Hk.\nunfold transposition.\ndo 2 rewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec k i); [ easy | ].\nnow destruct (Nat.eq_dec k j).\nQed.\n\nTheorem transposition_involutive : ∀ p q i,\n  transposition p q (transposition p q i) = i.\nProof.\nintros.\nunfold transposition.\ndo 4 rewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec i p) as [Hip| Hip]. {\n  destruct (Nat.eq_dec q p) as [Hqp| Hqp]; [ congruence | ].\n  destruct (Nat.eq_dec q q) as [H| H]; [ congruence | easy ].\n}\ndestruct (Nat.eq_dec i q) as [Hiq| Hiq]. {\n  destruct (Nat.eq_dec p p) as [H| H]; [ congruence | easy ].\n}\ndestruct (Nat.eq_dec i p) as [H| H]; [ easy | clear H ].\ndestruct (Nat.eq_dec i q) as [H| H]; [ easy | clear H ].\neasy.\nQed.\n\nTheorem list_swap_elem_length : ∀ A (d : A) l p q,\n  length (list_swap_elem d l p q) = length l.\nProof.\nintros.\nunfold list_swap_elem.\nnow rewrite map_length, seq_length.\nQed.\n\nTheorem list_swap_elem_involutive : ∀ A (d : A) l i j,\n  i < length l\n  → j < length l\n  → list_swap_elem d (list_swap_elem d l i j) i j = l.\nProof.\nintros * Hi Hj.\nunfold list_swap_elem.\nrewrite map_length, seq_length.\nerewrite map_ext_in. 2: {\n  intros k Hk; apply in_seq in Hk.\n  rewrite (List_map_nth' 0). 2: {\n    now rewrite seq_length; apply transposition_lt.\n  }\n  rewrite seq_nth; [ | now apply transposition_lt ].\n  rewrite Nat.add_0_l.\n  now rewrite transposition_involutive.\n}\nsymmetry.\napply List_map_nth_seq.\nQed.\n\nTheorem transposition_out : ∀ i j k, k ≠ i → k ≠ j → transposition i j k = k.\nProof.\nintros * Hi Hj.\nunfold transposition.\ndo 2 rewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec k i) as [H| H]; [ easy | clear H ].\nnow destruct (Nat.eq_dec k j).\nQed.\n\nTheorem transposition_1 : ∀ i j, transposition i j i = j.\nProof.\nintros.\nunfold transposition.\nnow rewrite Nat.eqb_refl.\nQed.\n\nTheorem transposition_2 : ∀ i j, transposition i j j = i.\nProof.\nintros.\nunfold transposition.\nrewrite Nat.eqb_refl.\nrewrite if_eqb_eq_dec.\nnow destruct (Nat.eq_dec j i).\nQed.\n\nTheorem transposition_id : ∀ i j, transposition i i j = j.\nProof.\nintros.\nunfold transposition.\ndo 2 rewrite if_eqb_eq_dec.\nnow destruct (Nat.eq_dec j i).\nQed.\n\nTheorem transposition_comm : ∀ i j k, transposition i j k = transposition j i k.\nProof.\nintros.\nunfold transposition.\ndo 4 rewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec k i) as [Hki| Hki]. {\n  destruct (Nat.eq_dec k j) as [Hkj| Hkj]; [ congruence | easy ].\n} {\n  destruct (Nat.eq_dec k j) as [Hkj| Hkj]; [ congruence | easy ].\n}\nQed.\n\nTheorem list_swap_elem_permut_seq : ∀ σ p q,\n  p < length σ\n  → q < length σ\n  → permut_seq σ\n  → permut_seq (list_swap_elem 0 σ p q).\nProof.\nintros * Hp Hq Hσ.\napply permut_seq_iff.\nunfold list_swap_elem.\nrewrite map_length, seq_length.\nsplit; cbn. {\n  intros i Hi.\n  apply in_map_iff in Hi.\n  destruct Hi as (j & Hji & Hj).\n  apply in_seq in Hj.\n  rewrite <- Hji.\n  apply permut_seq_ub; [ easy | ].\n  apply nth_In.\n  now apply transposition_lt.\n} {\n  apply nat_NoDup.\n  rewrite List_map_seq_length.\n  intros i j Hi Hj Hij.\n  rewrite (List_map_nth' 0) in Hij; [ | now rewrite seq_length ].\n  rewrite (List_map_nth' 0) in Hij; [ | now rewrite seq_length ].\n  rewrite seq_nth in Hij; [ | easy ].\n  rewrite seq_nth in Hij; [ | easy ].\n  do 2 rewrite Nat.add_0_l in Hij.\n  unfold transposition in Hij.\n  do 4 rewrite if_eqb_eq_dec in Hij.\n  apply permut_seq_NoDup in Hσ.\n  destruct (Nat.eq_dec i p) as [Hip| Hip]. {\n    subst i.\n    destruct (Nat.eq_dec j p) as [Hjp| Hjp]; [ congruence | ].\n    destruct (Nat.eq_dec j q) as [Hjq| Hjq]. {\n      now subst j; apply (NoDup_nat σ).\n    }\n    apply Nat.neq_sym in Hjq.\n    now exfalso; apply Hjq, (NoDup_nat σ).\n  }\n  destruct (Nat.eq_dec i q) as [Hiq| Hiq]. {\n    destruct (Nat.eq_dec j p) as [Hjp| Hjp]. {\n      now subst i j; apply (NoDup_nat σ).\n    }\n    destruct (Nat.eq_dec j q) as [Hjq| Hjq]; [ congruence | ].\n    apply Nat.neq_sym in Hjp; exfalso; apply Hjp.\n    now apply (NoDup_nat σ).\n  }\n  destruct (Nat.eq_dec j p) as [Hjp| Hjp]. {\n    now exfalso; apply Hiq, (NoDup_nat σ).\n  }\n  destruct (Nat.eq_dec j q) as [Hjq| Hjq]. {\n    now exfalso; apply Hip, (NoDup_nat σ).\n  }\n  now apply (NoDup_nat σ).\n}\nQed.\n\nTheorem list_swap_elem_permut_seq_with_len : ∀ n σ p q,\n  p < n\n  → q < n\n  → permut_seq_with_len n σ\n  → permut_seq_with_len n (list_swap_elem 0 σ p q).\nProof.\nintros * Hp Hq Hσ.\nsplit; [ | now rewrite list_swap_elem_length; destruct Hσ ].\ndestruct Hσ as (H1, H2).\nrewrite <- H2 in Hp, Hq.\nnow apply list_swap_elem_permut_seq.\nQed.\n\n(* *)\n\nDefinition sym_gr_inv (sg : list (list nat)) σ :=\n  let j := List_rank (list_eqv Nat.eqb σ) sg in\n  if j =? length sg then 0 else j.\n\nTheorem sym_gr_inv_inj : ∀ n sg la lb,\n  is_sym_gr_list n sg\n  → permut_seq_with_len n la\n  → permut_seq_with_len n lb\n  → sym_gr_inv sg la = sym_gr_inv sg lb\n  → la = lb.\nProof.\nintros * Hsg Hna Hnb Hab.\nunfold sym_gr_inv, unsome in Hab.\nremember (List_rank (list_eqv Nat.eqb la) sg) as x eqn:Hx.\nremember (List_rank (list_eqv Nat.eqb lb) sg) as y eqn:Hy.\nmove y before x.\nsymmetry in Hx, Hy.\nrewrite if_eqb_eq_dec in Hab.\ndestruct (Nat.eq_dec x (length sg)) as [Hxg| Hxg]. 2: {\n  apply (List_rank_if []) in Hx.\n  destruct Hx as (Hbefx, Hx).\n  destruct Hx as [Hx| Hx]; [ | easy ].\n  destruct Hx as (Hxs & Hx).\n  apply (list_eqb_eq Nat.eqb_eq) in Hx.\n  rewrite if_eqb_eq_dec in Hab.\n  destruct (Nat.eq_dec y (length sg)) as [Hyg| Hyg]. 2: {\n    apply (List_rank_if []) in Hy.\n    destruct Hy as (Hbefy & Hy).\n    destruct Hy as [Hy| Hy]; [ | easy ].\n    destruct Hy as (Hys & Hy).\n    apply (list_eqb_eq Nat.eqb_eq) in Hy.\n    congruence.\n  }\n  specialize (List_rank_if [] _ _ Hy) as H1.\n  destruct H1 as (H1, _).\n  rewrite Hyg in H1.\n  destruct Hsg as (Hsg & Hsg_inj & Hsg_surj).\n  specialize (Hsg_surj lb Hnb) as H2.\n  apply In_nth with (d := []) in H2.\n  destruct H2 as (k & Hk & Hkb).\n  specialize (H1 k Hk).\n  apply (list_eqb_neq Nat.eqb_eq) in H1.\n  now symmetry in Hkb.\n}\nspecialize (List_rank_if [] _ _ Hx) as H1; cbn.\ndestruct H1 as (H1, _).\nrewrite Hxg in H1.\ndestruct Hsg as (Hsg & Hsg_inj & Hsg_surj).\nspecialize (Hsg_surj la Hna) as H2.\napply In_nth with (d := []) in H2.\ndestruct H2 as (k & Hk & Hka).\nspecialize (H1 k Hk).\napply (list_eqb_neq Nat.eqb_eq) in H1.\nnow symmetry in Hka.\nQed.\n\nTheorem seq_permut_seq : ∀ n, permut_seq (seq 0 n).\nProof.\nintros.\nunfold permut_seq.\nrewrite seq_length.\napply (permutation_refl Nat.eqb_eq).\nQed.\n\nTheorem seq_permut_seq_with_len : ∀ n, permut_seq_with_len n (seq 0 n).\nProof.\nintros.\nsplit; [ | apply seq_length ].\napply seq_permut_seq.\nQed.\n\nTheorem sym_gr_inv_lt : ∀ n sg v,\n  n ≠ 0\n  → is_sym_gr_list n sg\n  → sym_gr_inv sg v < length sg.\nProof.\nintros * Hnz Hsg.\nunfold sym_gr_inv.\nrewrite if_eqb_eq_dec.\nremember (List_rank _ _) as i eqn:Hi; symmetry in Hi.\ndestruct (Nat.eq_dec _ _) as [Hrl| Hrl]. 2: {\n  apply (List_rank_if []) in Hi.\n  destruct Hi as (_, H1).\n  now destruct H1.\n}\ndestruct (lt_dec 0 (length sg)) as [Hs| Hs]; [ easy | ].\napply Nat.nlt_ge in Hs; exfalso.\napply Nat.le_0_r in Hs.\napply length_zero_iff_nil in Hs; subst sg.\ndestruct Hsg as (_ & _ & Hsurj).\ncbn in Hsurj.\napply (Hsurj (seq 0 n)).\napply seq_permut_seq_with_len.\nQed.\n\nTheorem nth_sym_gr_inv_sym_gr : ∀ sg l n,\n  is_sym_gr_list n sg\n  → permut_seq_with_len n l\n  → nth (sym_gr_inv sg l) sg [] = l.\nProof.\nintros * Hsg (Hp, Hs).\nunfold sym_gr_inv, unsome.\nrewrite if_eqb_eq_dec.\nremember (List_rank _ _) as i eqn:Hi; symmetry in Hi.\ndestruct (Nat.eq_dec _ _) as [His| His]. 2: {\n  apply (List_rank_if []) in Hi.\n  destruct Hi as (Hji, H1).\n  destruct H1 as [H1| H1]; [ | easy ].\n  clear His.\n  destruct H1 as (His & Hi).\n  now apply (list_eqb_eq Nat.eqb_eq) in Hi.\n}\nassert (H : l ∉ sg). {\n  intros H.\n  apply In_nth with (d := []) in H.\n  destruct H as (j & Hj & Hjv).\n  specialize (List_rank_if [] _ _ Hi) as H.\n  rewrite His in H.\n  destruct H as (H, _).\n  specialize (H _ Hj).\n  apply (list_eqb_neq Nat.eqb_eq) in H.\n  now symmetry in Hjv.\n}\nexfalso; apply H; clear H.\nnow apply Hsg.\nQed.\n\nTheorem sym_gr_inv_list_el : ∀ n sg i,\n  n ≠ 0\n  → is_sym_gr_list n sg\n  → i < length sg\n  → sym_gr_inv sg (nth i sg []) = i.\nProof.\nintros * Hnz Hsg Hi.\nunfold sym_gr_inv, unsome.\nremember (List_rank _ _) as j eqn:Hj; symmetry in Hj.\nrewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec j (length sg)) as [Hjs| Hjs]. 2: {\n  apply (List_rank_if []) in Hj.\n  destruct Hj as (Hji, Hj).\n  destruct Hj as [Hj| Hj]; [ clear Hjs | easy ].\n  destruct Hj as (Hjs, Hj).\n  apply (list_eqb_eq Nat.eqb_eq) in Hj.\n  destruct Hsg as (Hsg & Hinj & Hsurj).\n  now apply Hinj.\n}\nspecialize (List_rank_if [] _ _ Hj) as H1.\ndestruct H1 as (H1, _).\nrewrite Hjs in H1.\nspecialize (H1 _ Hi).\nnow apply (list_eqb_neq Nat.eqb_eq) in H1.\nQed.\n\nTheorem length_of_empty_sym_gr : ∀ sg,\n  is_sym_gr_list 0 sg → length sg = 1.\nProof.\nintros * Hsg.\ndestruct Hsg as (Hsg & Hinj & Hsurj).\nassert (H : permut_seq_with_len 0 []) by easy.\nspecialize (Hsurj _ H) as H1; clear H.\napply (In_nth _ _ []) in H1.\ndestruct H1 as (i & Hil & Hi).\ndestruct (Nat.eq_dec (length sg) 0) as [Hvz| Hvz]. {\n  now rewrite Hvz in Hil.\n}\ndestruct (Nat.eq_dec (length sg) 1) as [Hv1| Hv1]; [ easy | ].\nspecialize (Hsg 0) as H1.\nspecialize (Hsg 1) as H2.\nspecialize (Hinj 0 1) as H3.\nassert (H : 0 < length sg) by flia Hvz.\nspecialize (H1 H); specialize (H3 H); clear H.\nassert (H : 1 < length sg) by flia Hvz Hv1.\nspecialize (H2 H); specialize (H3 H); clear H.\ndestruct H1 as (H4, H5).\ndestruct H2 as (H6, H7).\nenough (H : nth 0 sg [] = nth 1 sg []). {\n  rewrite H in H3.\n  now specialize (H3 eq_refl).\n}\napply length_zero_iff_nil in H4, H6.\ncongruence.\nQed.\n\nFixpoint canon_sym_gr_inv_elem n k (j : nat) :=\n  match n with\n  | 0 => 0\n  | S n' =>\n      if lt_dec j (k / n'!) then\n        S (canon_sym_gr_inv_elem n' (k mod n'!) j)\n      else if lt_dec (k / n'!) j then\n        S (canon_sym_gr_inv_elem n' (k mod n'!) (j - 1))\n      else 0\n  end.\n\nDefinition canon_sym_gr_inv_list n k : list nat :=\n  map (canon_sym_gr_inv_elem n k) (seq 0 n).\n\nTheorem canon_sym_gr_list_length : ∀ k n,\n  length (canon_sym_gr_list n k) = n.\nProof.\nintros.\nrevert k.\ninduction n; intros; [ easy | cbn ].\nf_equal; rewrite map_length.\napply IHn.\nQed.\n\nTheorem canon_sym_gr_list_ub : ∀ n k i,\n  k < n!\n  → i < n\n  → nth i (canon_sym_gr_list n k) 0 < n.\nProof.\nintros * Hkn Hi.\nrevert i k Hkn Hi.\ninduction n; intros; [ easy | cbn ].\ndestruct i. {\n  apply Nat.div_lt_upper_bound; [ apply fact_neq_0 | ].\n  now rewrite Nat.mul_succ_r, Nat.add_comm, Nat.mul_comm.\n}\napply Nat.succ_lt_mono in Hi.\nrewrite (List_map_nth' 0); [ | now rewrite canon_sym_gr_list_length ].\nunfold succ_when_ge.\nrewrite <- Nat.add_1_r.\napply Nat.add_lt_le_mono; [ | apply Nat_b2n_upper_bound ].\nnow apply IHn.\nQed.\n\nTheorem canon_sym_gr_inv_list_ub : ∀ n k j,\n  k < n!\n  → j < n\n  → nth j (canon_sym_gr_inv_list n k) 0 < n.\nProof.\nintros * Hkn Hjn.\nunfold canon_sym_gr_inv_list.\nrewrite (List_map_nth' 0); [ | now rewrite seq_length ].\nrewrite seq_nth; [ cbn | easy ].\nrevert k j Hkn Hjn.\ninduction n; intros; [ easy | cbn ].\ndestruct (lt_dec j (k / fact n)) as [Hjkn| Hjkn]. {\n  apply -> Nat.succ_lt_mono.\n  destruct n. {\n    cbn in Hkn.\n    apply Nat.lt_1_r in Hkn; subst k.\n    easy.\n  }\n  destruct (Nat.eq_dec j (S n)) as [Hjsn| Hjsn]. {\n    subst j.\n    clear Hjn.\n    exfalso; apply Nat.nle_gt in Hjkn; apply Hjkn; clear Hjkn.\n    rewrite Nat_fact_succ in Hkn.\n    rewrite Nat.mul_comm in Hkn.\n    apply Nat.lt_succ_r.\n    apply Nat.div_lt_upper_bound; [ | easy ].\n    apply fact_neq_0.\n  } {\n    apply IHn; [ easy | flia Hjn Hjsn ].\n  }\n} {\n  apply Nat.nlt_ge in Hjkn.\n  destruct (lt_dec (k / fact n) j) as [Hknj| Hknj]; [ | easy ].\n  apply -> Nat.succ_lt_mono.\n  destruct n. {\n    now apply Nat.lt_1_r in Hjn; subst j.\n  }\n  apply IHn; [ easy | flia Hjn Hknj ].\n}\nQed.\n\nTheorem canon_sym_gr_inv_sym_gr : ∀ n k i,\n  k < n!\n  → i < n\n  → nth (nth i (canon_sym_gr_list n k) 0)  (canon_sym_gr_inv_list n k) 0 = i.\nProof.\nintros * Hkn Hi.\nunfold canon_sym_gr_inv_list.\nrewrite (List_map_nth' 0). 2: {\n  rewrite seq_length.\n  now apply canon_sym_gr_list_ub.\n}\nrewrite seq_nth; [ | now apply canon_sym_gr_list_ub ].\nrewrite Nat.add_0_l.\nrevert k i Hi Hkn.\ninduction n; intros; [ easy | cbn ].\ndestruct i. {\n  do 2 rewrite <- if_ltb_lt_dec.\n  now rewrite Nat.ltb_irrefl.\n}\napply Nat.succ_lt_mono in Hi.\nrewrite (List_map_nth' 0); [ | now rewrite canon_sym_gr_list_length ].\nunfold succ_when_ge.\nunfold Nat.b2n.\nrewrite if_leb_le_dec.\ndestruct (le_dec (k / n!) _) as [H1| H1]. {\n  destruct (lt_dec _ (k / n!)) as [H| H]; [ flia H1 H | clear H ].\n  destruct (lt_dec (k / n!) _) as [H| H]; [ clear H | flia H1 H ].\n  f_equal; rewrite Nat.add_sub.\n  now apply IHn.\n} {\n  rewrite Nat.add_0_r.\n  destruct (lt_dec _ (k / n!)) as [H| H]; [ clear H | flia H1 H ].\n  f_equal.\n  now apply IHn.\n}\nQed.\n\nTheorem canon_sym_gr_inv_elem_ub : ∀ n k i,\n  k < n!\n  → i < n\n  → canon_sym_gr_inv_elem n k i < n.\nProof.\nintros * Hkn Hi.\nrevert i k Hkn Hi.\ninduction n; intros; [ easy | cbn ].\ndestruct (lt_dec i (k / n!)) as [Hikn| Hikn]. {\n  apply -> Nat.succ_lt_mono.\n  destruct (Nat.eq_dec i n) as [Hin| Hin]. {\n    exfalso.\n    subst i; clear Hi.\n    rewrite Nat_fact_succ in Hkn.\n    assert (Hkns : k / n! < S n). {\n      apply Nat.div_lt_upper_bound; [ apply fact_neq_0 | ].\n      now rewrite Nat.mul_comm.\n    }\n    flia Hikn Hkns.\n  }\n  apply IHn; [ easy | flia Hi Hin ].\n}\ndestruct (lt_dec (k / n!) i) as [Hkni| Hkni]; [ | easy ].\napply -> Nat.succ_lt_mono.\napply IHn; [ easy | flia Hi Hkni ].\nQed.\n\nTheorem canon_sym_gr_sym_gr_inv : ∀ n k i,\n  k < n!\n  → i < n\n  → nth (nth i (canon_sym_gr_inv_list n k) 0) (canon_sym_gr_list n k) 0 = i.\nProof.\nintros * Hkn Hi.\nunfold canon_sym_gr_inv_list.\nrewrite (List_map_nth' 0); [ | now rewrite seq_length ].\nrewrite seq_nth; [ | easy ].\nrewrite Nat.add_0_l.\nrevert k i Hi Hkn.\ninduction n; intros; [ easy | cbn ].\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  subst n.\n  now apply Nat.lt_1_r in Hkn, Hi; subst k i.\n}\napply Nat.neq_0_lt_0 in Hnz.\ndestruct i. {\n  destruct (lt_dec 0 (k / n!)) as [Hzkn| Hzkn]. {\n    unfold succ_when_ge.\n    rewrite (List_map_nth' 0). 2: {\n      rewrite canon_sym_gr_list_length.\n      now apply canon_sym_gr_inv_elem_ub.\n    }\n    rewrite IHn; [ | easy | easy ].\n    unfold Nat.b2n.\n    rewrite if_leb_le_dec.\n    destruct (le_dec (k / n!) 0) as [Hknz| Hknz]; [ | easy ].\n    now apply Nat.nlt_ge in Hknz.\n  }\n  apply Nat.nlt_ge in Hzkn.\n  apply Nat.le_0_r in Hzkn.\n  now rewrite Hzkn; cbn.\n}\napply Nat.succ_lt_mono in Hi.\ndestruct (lt_dec (S i) (k / n!)) as [Hsikn| Hsikn]. {\n  destruct (Nat.eq_dec (S i) n) as [Hsin| Hsin]. {\n    rewrite Hsin in Hsikn.\n    rewrite Nat_fact_succ in Hkn.\n    assert (Hkns : k / n! < S n). {\n      apply Nat.div_lt_upper_bound; [ apply fact_neq_0 | ].\n      now rewrite Nat.mul_comm.\n    }\n    flia Hsikn Hkns.\n  }\n  rewrite (List_map_nth' 0). 2: {\n    rewrite canon_sym_gr_list_length.\n    apply canon_sym_gr_inv_elem_ub; [ easy | flia Hi Hsin ].\n  }\n  rewrite IHn; [ | flia Hi Hsin | easy ].\n  unfold succ_when_ge, Nat.b2n.\n  apply Nat.nle_gt in Hsikn.\n  apply Nat.leb_nle in Hsikn.\n  now rewrite Hsikn, Nat.add_0_r.\n}\napply Nat.nlt_ge in Hsikn.\ndestruct (lt_dec (k / n!) (S i)) as [Hknsi| Hknsi]; [ | flia Hsikn Hknsi ].\nrewrite Nat_sub_succ_1.\nrewrite (List_map_nth' 0).  2: {\n  rewrite canon_sym_gr_list_length.\n  now apply canon_sym_gr_inv_elem_ub.\n}\nrewrite IHn; [ | easy | easy ].\nunfold succ_when_ge.\nunfold Nat.b2n.\nrewrite if_leb_le_dec.\ndestruct (le_dec (k / n!) i) as [Hkni| Hkni]; [ apply Nat.add_1_r | ].\nnow apply Nat.succ_le_mono in Hknsi.\nQed.\n\nTheorem nth_canon_sym_gr_list_inj1 : ∀ n k i j,\n  k < fact n\n  → i < n\n  → j < n\n  → nth i (canon_sym_gr_list n k) 0 = nth j (canon_sym_gr_list n k) 0\n  → i = j.\nProof.\nintros * Hk Hi Hj Hij.\nrewrite <- canon_sym_gr_inv_sym_gr with (n := n) (k := k); [ | easy | easy ].\nsymmetry.\nrewrite <- canon_sym_gr_inv_sym_gr with (n := n) (k := k); [ | easy | easy ].\nsymmetry.\nnow rewrite Hij.\nQed.\n\nTheorem nth_canon_sym_gr_list_inj2 : ∀ n i j,\n  i < n!\n  → j < n!\n  → (∀ k, k < n →\n     nth k (canon_sym_gr_list n i) 0 = nth k (canon_sym_gr_list n j) 0)\n  → i = j.\nProof.\nintros * Hin Hjn Hij.\nrevert i j Hin Hjn Hij.\ninduction n; intros; [ apply Nat.lt_1_r in Hin, Hjn; congruence | ].\ndestruct (Nat.eq_dec (i / n!) (j / n!)) as [Hijd| Hijd]. 2: {\n  now specialize (Hij 0 (Nat.lt_0_succ _)).\n}\ndestruct (Nat.eq_dec (i mod n!) (j mod n!)) as [Hijm| Hijm]. {\n  specialize (Nat.div_mod i n! (fact_neq_0 _)) as Hi.\n  specialize (Nat.div_mod j n! (fact_neq_0 _)) as Hj.\n  congruence.\n}\nexfalso; apply Hijm; clear Hijm.\napply IHn. {\n  apply Nat.mod_upper_bound, fact_neq_0.\n} {\n  apply Nat.mod_upper_bound, fact_neq_0.\n}\nintros k Hk.\ncbn - [ fact nth ] in Hij |-*.\nspecialize (Hij (S k)) as H1.\nassert (H : S k < S n) by flia Hk.\nspecialize (H1 H); clear H.\ncbn - [ fact ] in H1.\nrewrite Hijd in H1.\nrewrite (List_map_nth' 0) in H1; [ | now rewrite canon_sym_gr_list_length ].\nrewrite (List_map_nth' 0) in H1; [ | now rewrite canon_sym_gr_list_length ].\nunfold succ_when_ge, Nat.b2n in H1.\ndo 2 rewrite if_leb_le_dec in H1.\ndestruct (le_dec (j / n!) _) as [H2| H2]. {\n  destruct (le_dec (j / n!) _) as [H3| H3]; [ | flia H1 H2 H3 ].\n  now apply Nat.add_cancel_r in H1.\n}\ndestruct (le_dec (j / n!) _) as [H3| H3]; [ flia H1 H2 H3 | flia H1 ].\nQed.\n\nTheorem canon_sym_gr_inv_list_length : ∀ n i,\n  length (canon_sym_gr_inv_list n i) = n.\nProof.\nintros.\nunfold canon_sym_gr_inv_list.\napply List_map_seq_length.\nQed.\n\nTheorem NoDup_canon_sym_gr_inv_list : ∀ n i,\n  i < n!\n  → NoDup (canon_sym_gr_inv_list n i).\nProof.\nintros * Hi.\napply nat_NoDup.\nrewrite canon_sym_gr_inv_list_length.\nintros j k Hj Hk Hjk.\napply (f_equal (λ m, nth m (canon_sym_gr_list n i) 0)) in Hjk.\nrewrite canon_sym_gr_sym_gr_inv in Hjk; [ | easy | easy ].\nrewrite canon_sym_gr_sym_gr_inv in Hjk; [ | easy | easy ].\neasy.\nQed.\n\nTheorem in_canon_sym_gr_list : ∀ n k i,\n  k < n! → i ∈ canon_sym_gr_list n k → i < n.\nProof.\nintros * Hkn Hi.\napply (In_nth _ _ 0) in Hi.\ndestruct Hi as (j & Hj & Hi); subst i.\nrewrite canon_sym_gr_list_length in Hj.\nnow apply canon_sym_gr_list_ub.\nQed.\n\n(* *)\n\nDefinition sub_canon_permut_list (l : list nat) :=\n  map (λ a, a - Nat.b2n (hd 0 l <? a)) (tl l).\n\nFixpoint canon_sym_gr_list_inv n (l : list nat) : nat :=\n  match n with\n  | 0 => 0\n  | S n' =>\n      hd 0 l * n'! +\n      canon_sym_gr_list_inv n' (sub_canon_permut_list l)\n  end.\n\nTheorem sub_canon_permut_list_elem_ub : ∀ l i,\n  permut_seq l\n  → S i < length l\n  → nth i (sub_canon_permut_list l) 0 < length l - 1.\nProof.\nintros * Hp Hin.\napply permut_seq_iff in Hp.\ndestruct Hp as (Hvn, Hn).\ndestruct l as [| a]; [ easy | ].\ncbn - [ \"<?\" ] in Hin |-*.\nrewrite Nat.sub_0_r.\napply Nat.succ_lt_mono in Hin.\nrewrite (List_map_nth' 0); [ | easy ].\nunfold Nat.b2n.\nrewrite if_ltb_lt_dec.\ndestruct (lt_dec a (nth i l 0)) as [Hal| Hal]. {\n  enough (H : nth i l 0 < S (length l)) by flia Hal H.\n  now apply Hvn; right; apply nth_In.\n}\napply Nat.nlt_ge in Hal.\nrewrite Nat.sub_0_r.\ndestruct (Nat.eq_dec (nth i l 0) a) as [Hia| Hia]. {\n  rewrite Hia.\n  apply Nat.succ_lt_mono in Hin.\n  symmetry in Hia.\n  now specialize (NoDup_nat _ Hn 0 (S i) (Nat.lt_0_succ _) Hin Hia).\n}\nspecialize (Hvn a (or_introl eq_refl)); cbn in Hvn.\nflia Hvn Hal Hia.\nQed.\n\nTheorem sub_canon_sym_gr_elem_inj1 : ∀ l i j,\n  permut_seq l\n  → S i < length l\n  → S j < length l\n  → nth i (sub_canon_permut_list l) 0 = nth j (sub_canon_permut_list l) 0\n  → i = j.\nProof.\nintros * Hp Hin Hjn Hij.\napply permut_seq_iff in Hp.\ndestruct Hp as (Hvn, Hn).\ndestruct l as [| a]; [ easy | ].\ncbn - [ \"<?\" ] in Hin, Hjn, Hij.\napply Nat.succ_lt_mono in Hin, Hjn.\nrewrite (List_map_nth' 0) in Hij; [ | easy ].\nrewrite (List_map_nth' 0) in Hij; [ | easy ].\nunfold Nat.b2n in Hij.\ndo 2 rewrite if_ltb_lt_dec in Hij.\ndestruct (lt_dec a (nth i l 0)) as [Hai| Hai]. {\n  destruct (lt_dec a (nth j l 0)) as [Haj| Haj]. {\n    apply Nat.succ_inj.\n    apply Nat.succ_lt_mono in Hin, Hjn.\n    apply (NoDup_nat _ Hn); [ easy | easy | ].\n    cbn; flia Hai Haj Hij.\n  }\n  apply Nat.nlt_ge in Haj.\n  rewrite Nat.sub_0_r in Hij.\n  apply Nat.succ_lt_mono in Hjn.\n  specialize (NoDup_nat _ Hn 0 (S j) (Nat.lt_0_succ _) Hjn) as H1.\n  cbn in H1.\n  replace (nth j l 0) with a in H1 by flia Hai Haj Hij.\n  now specialize (H1 eq_refl).\n}\napply Nat.nlt_ge in Hai.\nrewrite Nat.sub_0_r in Hij.\ndestruct (lt_dec a (nth j l 0)) as [Haj| Haj]. {\n  apply Nat.succ_lt_mono in Hin.\n  specialize (NoDup_nat _ Hn (S i) 0 Hin (Nat.lt_0_succ _)) as H1.\n  cbn in H1.\n  replace (nth i l 0) with a in H1 by flia Hai Haj Hij.\n  now specialize (H1 eq_refl).\n}\nrewrite Nat.sub_0_r in Hij.\napply Nat.succ_inj.\napply Nat.succ_lt_mono in Hin, Hjn.\nnow apply (NoDup_nat _ Hn).\nQed.\n\nTheorem sub_canon_permut_list_length : ∀ l,\n  length (sub_canon_permut_list l) = length l - 1.\nProof.\nintros.\ndestruct l as [| a]; [ easy | ].\nnow cbn; rewrite map_length, Nat.sub_0_r.\nQed.\n\nTheorem canon_sym_gr_list_inv_ub : ∀ n l,\n  permut_seq_with_len n l\n  → canon_sym_gr_list_inv n l < n!.\nProof.\nintros * (Hp, Hln).\napply permut_seq_iff in Hp.\ndestruct Hp as (Hvn, Hn).\nrevert l Hvn Hn Hln.\ninduction n; intros; cbn; [ easy | ].\nrewrite Nat.add_comm.\napply Nat.add_lt_le_mono. {\n  apply IHn. {\n    intros i Hi.\n    apply (In_nth _ _ 0) in Hi.\n    destruct Hi as (j & Hj & Hji).\n    rewrite <- Hji.\n    rewrite sub_canon_permut_list_length in Hj |-*.\n    apply sub_canon_permut_list_elem_ub; [ | flia Hj ].\n    now apply permut_seq_iff.\n  } {\n    apply nat_NoDup.\n    intros i j Hi Hj.\n    rewrite sub_canon_permut_list_length in Hi, Hj.\n    apply sub_canon_sym_gr_elem_inj1; [ | flia Hi | flia Hj ].\n    now apply permut_seq_iff.\n  }\n  now rewrite sub_canon_permut_list_length, Hln, Nat_sub_succ_1.\n}\napply Nat.mul_le_mono_r.\nspecialize (Hvn (hd 0 l)).\nassert (H : hd 0 l ∈ l) by now apply List_hd_in; rewrite Hln.\nspecialize (Hvn H); clear H.\nrewrite Hln in Hvn.\nnow apply Nat.succ_le_mono in Hvn.\nQed.\n\nTheorem sub_canon_permut_list_permut_seq_with_len : ∀ l,\n  permut_seq l\n  → permut_seq (sub_canon_permut_list l).\nProof.\nintros * Hl.\napply permut_seq_iff.\nsplit. {\n  intros i Hi.\n  apply (In_nth _ _ 0) in Hi.\n  destruct Hi as (j & Hj & Hji).\n  rewrite <- Hji.\n  rewrite sub_canon_permut_list_length in Hj |-*.\n  apply sub_canon_permut_list_elem_ub; [ easy | flia Hj ].\n} {\n  apply nat_NoDup.\n  intros i j Hi Hj Hij.\n  rewrite sub_canon_permut_list_length in Hi, Hj.\n  apply sub_canon_sym_gr_elem_inj1 in Hij; [ easy | easy | | ]. {\n    flia Hi.\n  } {\n    flia Hj.\n  }\n}\nQed.\n\nTheorem canon_sym_gr_list_canon_sym_gr_list_inv : ∀ n l,\n  permut_seq_with_len n l\n  → canon_sym_gr_list n (canon_sym_gr_list_inv n l) = l.\nProof.\nintros * (Hp, Hln).\napply permut_seq_iff in Hp.\ndestruct Hp as (Hvn, Hn).\nrevert l Hvn Hn Hln.\ninduction n; intros; [ now apply length_zero_iff_nil in Hln | cbn ].\ndestruct l as [| a]; [ easy | ].\nf_equal. {\n  cbn - [ sub_canon_permut_list ].\n  rewrite Nat.div_add_l; [ | apply fact_neq_0 ].\n  rewrite <- Nat.add_0_r; f_equal.\n  apply Nat.div_small.\n  apply canon_sym_gr_list_inv_ub.\n  split. {\n    apply sub_canon_permut_list_permut_seq_with_len.\n    now apply permut_seq_iff.\n  } {\n    cbn; rewrite map_length.\n    now cbn in Hln; apply Nat.succ_inj in Hln.\n  }\n} {\n  cbn in Hln.\n  apply Nat.succ_inj in Hln.\n  rewrite Nat.div_add_l; [ | apply fact_neq_0 ].\n  rewrite Nat_mod_add_l_mul_r; [ | apply fact_neq_0 ].\n  rewrite Nat.mod_small. 2: {\n    apply canon_sym_gr_list_inv_ub.\n    split. {\n      apply sub_canon_permut_list_permut_seq_with_len.\n      now apply permut_seq_iff.\n    } {\n      rewrite sub_canon_permut_list_length; cbn.\n      now rewrite Hln, Nat.sub_0_r.\n    }\n  }\n  rewrite IHn; cycle 1. {\n    intros i Hi.\n    apply (In_nth _ _ 0) in Hi.\n    destruct Hi as (j & Hj & Hji).\n    rewrite <- Hji.\n    apply permut_seq_ub; [ | now apply nth_In ].\n    apply sub_canon_permut_list_permut_seq_with_len.\n    now apply permut_seq_iff.\n  } {\n    apply nat_NoDup.\n    intros i j Hi Hj.\n    rewrite sub_canon_permut_list_length in Hi, Hj.\n    cbn in Hi, Hj.\n    rewrite Nat.sub_0_r in Hi, Hj.\n    apply sub_canon_sym_gr_elem_inj1; [ | cbn; flia Hi | cbn; flia Hj ].\n    now apply permut_seq_iff.\n  } {\n    rewrite sub_canon_permut_list_length; cbn.\n    now rewrite Nat.sub_0_r.\n  }\n  cbn - [ sub_canon_permut_list ].\n  unfold succ_when_ge.\n  remember (canon_sym_gr_list_inv _ _) as x.\n  cbn - [ \"<=?\" ]; subst x.\n  rewrite map_map.\n  rewrite List_map_map_seq with (d := 0).\n  rewrite List_map_nth_seq with (d := 0).\n  apply map_ext_in_iff.\n  intros i Hi; apply in_seq in Hi.\n  unfold Nat.b2n.\n  rewrite if_ltb_lt_dec.\n  destruct (lt_dec a (nth i l 0)) as [Hai| Hai]. {\n    rewrite if_leb_le_dec.\n    destruct (le_dec _ _) as [H1| H1]; [ apply Nat.sub_add; flia Hai | ].\n    exfalso.\n    apply H1; clear H1.\n    rewrite Nat.div_small; [ flia Hai | ].\n    apply canon_sym_gr_list_inv_ub.\n    split; [ | now cbn; rewrite map_length ].\n    apply sub_canon_permut_list_permut_seq_with_len.\n    now apply permut_seq_iff.\n  }\n  apply Nat.nlt_ge in Hai.\n  rewrite Nat.sub_0_r.\n  rewrite Nat.div_small. 2: {\n    apply canon_sym_gr_list_inv_ub.\n    split. {\n      apply sub_canon_permut_list_permut_seq_with_len.\n      now apply permut_seq_iff.\n    } {\n      rewrite sub_canon_permut_list_length; cbn; rewrite Hln.\n      apply Nat.sub_0_r.\n    }\n  }\n  rewrite Nat.add_0_r, if_leb_le_dec.\n  destruct (le_dec _ _) as [H1| H1]; [ | apply Nat.add_0_r ].\n  exfalso.\n  apply Nat.le_antisymm in H1; [ symmetry in H1 | easy ].\n  specialize (NoDup_nat _ Hn 0 (S i) (Nat.lt_0_succ _)) as H2.\n  assert (H : S i < length (a :: l)) by (cbn; flia Hi).\n  now specialize (H2 H H1); clear H.\n}\nQed.\n\nTheorem canon_sym_gr_list_permut_seq : ∀ n k,\n  k < n!\n  → permut_seq (canon_sym_gr_list n k).\nProof.\nintros * Hkn.\napply permut_seq_iff.\nsplit. {\n  intros i Hi.\n  rewrite canon_sym_gr_list_length.\n  apply (In_nth _ _ 0) in Hi.\n  destruct Hi as (j & Hj & Hji).\n  rewrite canon_sym_gr_list_length in Hj.\n  rewrite <- Hji.\n  now apply canon_sym_gr_list_ub.\n} {\n  apply nat_NoDup.\n  intros * Hi Hj Hij.\n  rewrite canon_sym_gr_list_length in Hi, Hj.\n  now apply nth_canon_sym_gr_list_inj1 in Hij.\n}\nQed.\n\nTheorem canon_sym_gr_list_permut_seq_with_len : ∀ n k,\n  k < n!\n  → permut_seq_with_len n (canon_sym_gr_list n k).\nProof.\nintros * Hkn.\nsplit; [ now apply canon_sym_gr_list_permut_seq | ].\napply canon_sym_gr_list_length.\nQed.\n\nTheorem canon_sym_gr_sub_canon_permut_list : ∀ n k,\n  canon_sym_gr_list n (k mod n!) =\n  sub_canon_permut_list (canon_sym_gr_list (S n) k).\nProof.\nintros.\ndestruct n; intros; [ easy | ].\ncbn - [ \"<?\" fact ].\nf_equal. {\n  unfold succ_when_ge.\n  rewrite <- Nat.add_sub_assoc. 2: {\n    unfold Nat.b2n.\n    rewrite if_leb_le_dec, if_ltb_lt_dec.\n    destruct (le_dec _ _) as [H| H]; [ destruct (lt_dec _ _); cbn; flia | ].\n    rewrite Nat.add_0_r.\n    apply Nat.nle_gt in H.\n    destruct (lt_dec _ _) as [Hqr| Hqr]; [ flia H Hqr | easy ].\n  }\n  symmetry; rewrite <- Nat.add_0_r; f_equal.\n  unfold Nat.b2n.\n  rewrite if_leb_le_dec, if_ltb_lt_dec.\n  destruct (le_dec _ _) as [H1| H1]; [ | easy ].\n  destruct (lt_dec _ _) as [H2| H2]; [ easy | flia H1 H2 ].\n}\nrewrite map_map.\nrewrite map_map.\napply map_ext_in.\nintros i Hi.\nremember (succ_when_ge (_ mod _ / _) _) as x eqn:Hx.\nunfold succ_when_ge, Nat.b2n.\nrewrite if_leb_le_dec, if_ltb_lt_dec.\nrewrite <- Nat.add_sub_assoc. 2: {\n  destruct (le_dec _ _) as [H| H]; [ destruct (lt_dec _ _); cbn; flia | ].\n  rewrite Nat.add_0_r.\n  apply Nat.nle_gt in H.\n  destruct (lt_dec _ _) as [Hqr| Hqr]; [ flia H Hqr | easy ].\n}\nsymmetry; rewrite <- Nat.add_0_r; f_equal.\ndestruct (le_dec _ _) as [H1| H1]; [ | easy ].\ndestruct (lt_dec _ _) as [H2| H2]; [ easy | flia H1 H2 ].\nQed.\n\nTheorem canon_sym_gr_list_inv_canon_sym_gr_list : ∀ n k,\n  k < n!\n  → canon_sym_gr_list_inv n (canon_sym_gr_list n k) = k.\nProof.\nintros * Hkn.\nrevert k Hkn.\ninduction n; intros; [ now apply Nat.lt_1_r in Hkn | ].\ncbn - [ canon_sym_gr_list ].\nremember (sub_canon_permut_list _) as x; cbn; subst x.\nspecialize (Nat.div_mod k (fact n) (fact_neq_0 _)) as H1.\nrewrite Nat.mul_comm in H1.\nreplace (k / fact n * fact n) with (k - k mod fact n) by flia H1.\nrewrite <- Nat.add_sub_swap; [ | apply Nat.mod_le, fact_neq_0 ].\napply Nat.add_sub_eq_r; f_equal.\nclear H1.\nrewrite <- (IHn (k mod fact n)) at 1; [ | easy ].\nf_equal.\napply canon_sym_gr_sub_canon_permut_list.\nQed.\n\nTheorem rank_in_sym_gr_of_rank_in_canon_sym_gr_prop : ∀ n sg,\n  is_sym_gr_list n sg\n  → ∀ k : fin_t n!,\n      (sym_gr_inv sg\n         (nth (proj1_sig k) (canon_sym_gr_list_list n) []) <? length sg) =\n      true.\nProof.\nintros * Hsg k.\napply Nat.ltb_lt.\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  subst n.\n  destruct k as (k, pk); cbn.\n  apply Nat.ltb_lt, Nat.lt_1_r in pk; subst k.\n  specialize (length_of_empty_sym_gr Hsg) as Hs.\n  destruct sg as [| v]; [ easy | ].\n  destruct sg; [ clear Hs | easy ].\n  destruct Hsg as (Hsg & _ & _).\n  specialize (Hsg 0 Nat.lt_0_1); cbn in Hsg.\n  destruct Hsg as (H1, H2).\n  apply length_zero_iff_nil in H1; subst v.\n  apply Nat.lt_0_1.\n}\nnow apply sym_gr_inv_lt with (n := n).\nQed.\n\nTheorem rank_in_canon_sym_gr_of_rank_in_sym_gr_prop : ∀ n sg,\n  is_sym_gr_list n sg\n  → ∀ k : fin_t (length sg),\n      (canon_sym_gr_list_inv n (nth (proj1_sig k) sg []) <? n!)\n      = true.\nProof.\nintros * Hsg k.\ndestruct Hsg as (Hsg & Hinj & Hsurj).\napply Nat.ltb_lt.\ndestruct k as (k, pk); cbn.\napply Nat.ltb_lt in pk.\nspecialize (Hsg k pk).\nnow apply canon_sym_gr_list_inv_ub.\nQed.\n\nDefinition rank_in_sym_gr_of_rank_in_canon_sym_gr n sg\n    (Hsg : is_sym_gr_list n sg) (k : fin_t n!) : fin_t (length sg) :=\n  exist (λ a : nat, (a <? length sg) = true)\n    (sym_gr_inv sg\n      (nth (proj1_sig k) (canon_sym_gr_list_list n) []))\n    (rank_in_sym_gr_of_rank_in_canon_sym_gr_prop Hsg k).\n\nDefinition rank_in_canon_sym_gr_of_rank_in_sym_gr  n sg\n    (Hsg : is_sym_gr_list n sg) (k : fin_t (length sg)) : fin_t n! :=\n  exist (λ a : nat, (a <? n!) = true)\n    (canon_sym_gr_list_inv n (nth (proj1_sig k) sg []))\n    (rank_in_canon_sym_gr_of_rank_in_sym_gr_prop Hsg k).\n\nTheorem rank_in_sym_gr_of_rank_in_canon_sym_gr_of_its_inverse : ∀ n sg\n    (Hsg : is_sym_gr_list n sg) k,\n  rank_in_sym_gr_of_rank_in_canon_sym_gr Hsg\n    (rank_in_canon_sym_gr_of_rank_in_sym_gr Hsg k) = k.\nProof.\nintros.\ndestruct k as (k, pk); cbn - [ \"<?\" ].\napply eq_exist_uncurried.\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  subst n; cbn.\n  specialize (length_of_empty_sym_gr Hsg) as Hs.\n  specialize (proj1 (Nat.ltb_lt _ _) pk) as Hk.\n  rewrite Hs in Hk.\n  apply Nat.lt_1_r in Hk; subst k.\n  assert (p : sym_gr_inv sg [] = 0). {\n    unfold sym_gr_inv, unsome; cbn.\n    destruct sg as [| v]; [ easy | ].\n    destruct sg; [ cbn | easy ].\n    destruct Hsg as (Hsg & _ & _).\n    specialize (Hsg 0 Nat.lt_0_1); cbn in Hsg.\n    destruct Hsg as (H1, H2).\n    now apply length_zero_iff_nil in H1; subst v.\n  }\n  exists p.\n  apply (Eqdep_dec.UIP_dec Bool.bool_dec).\n}  \ncbn.\nassert\n  (p :\n   sym_gr_inv sg\n     (nth (canon_sym_gr_list_inv n (nth k sg []))\n        (canon_sym_gr_list_list n) []) = k). {\n  apply Nat.ltb_lt in pk.\n  destruct Hsg as (Hsg & Hinj & Hsurj).\n  specialize (Hsg k pk) as H1.\n  unfold canon_sym_gr_list_list.\n  rewrite (List_map_nth' 0). 2: {\n    rewrite seq_length.\n    now apply canon_sym_gr_list_inv_ub.\n  }\n  rewrite seq_nth; [ | now apply canon_sym_gr_list_inv_ub ].\n  rewrite Nat.add_0_l.\n  rewrite canon_sym_gr_list_canon_sym_gr_list_inv; [ | easy ].\n  now apply sym_gr_inv_list_el with (n := n).\n}\nexists p.\napply (Eqdep_dec.UIP_dec Bool.bool_dec).\nQed.\n\nTheorem rank_in_canon_sym_gr_of_rank_in_sym_gr_of_its_inverse : ∀ n sg\n    (Hsg : is_sym_gr_list n sg) k,\n  rank_in_canon_sym_gr_of_rank_in_sym_gr Hsg\n    (rank_in_sym_gr_of_rank_in_canon_sym_gr Hsg k) = k.\nProof.\nintros.\ndestruct k as (k, pk); cbn - [ \"<?\" ].\napply eq_exist_uncurried; cbn.\nassert\n  (p :\n   canon_sym_gr_list_inv n\n     (nth (sym_gr_inv sg (nth k (canon_sym_gr_list_list n) []))\n        sg []) = k). {\n  specialize (proj1 (Nat.ltb_lt _ _) pk) as Hkn.\n  unfold canon_sym_gr_list_list.\n  rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n  rewrite seq_nth; [ cbn | easy ].\n  rewrite (@nth_sym_gr_inv_sym_gr _ _ n); cycle 1. {\n    easy.\n  } {\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  }\n  now apply canon_sym_gr_list_inv_canon_sym_gr_list.\n}\nexists p.\napply (Eqdep_dec.UIP_dec Bool.bool_dec).\nQed.\n\nTheorem sym_gr_size : ∀ n sg, is_sym_gr_list n sg → length sg = n!.\nProof.\nintros * Hsg.\napply (bijective_fin_t _ _ (rank_in_canon_sym_gr_of_rank_in_sym_gr Hsg)).\nexists (rank_in_sym_gr_of_rank_in_canon_sym_gr Hsg).\nsplit. {\n  intros x.\n  apply rank_in_sym_gr_of_rank_in_canon_sym_gr_of_its_inverse.\n} {\n  intros y.\n  apply rank_in_canon_sym_gr_of_rank_in_sym_gr_of_its_inverse.\n}\nQed.\n\n(* *)\n\nRecord sym_gr_list n :=\n  { sg_list : list (list nat);\n    sg_prop : is_sym_gr_list n sg_list }.\n\nTheorem canon_sym_gr_list_inj : ∀ n i j,\n  i < fact n\n  → j < fact n\n  → canon_sym_gr_list n i = canon_sym_gr_list n j\n  → i = j.\nProof.\nintros * Hi Hj Hij.\napply (f_equal (@canon_sym_gr_list_inv n)) in Hij.\nrewrite canon_sym_gr_list_inv_canon_sym_gr_list in Hij; [ | easy ].\nrewrite canon_sym_gr_list_inv_canon_sym_gr_list in Hij; [ | easy ].\neasy.\nQed.\n\nTheorem rank_of_permut_in_canon_gr_list_inj : ∀ n la lb,\n  permut_seq_with_len n la\n  → permut_seq_with_len n lb\n  → canon_sym_gr_list_inv n la =\n    canon_sym_gr_list_inv n lb\n  → la = lb.\nProof.\nintros * (Hla, Han) (Hlb, Hbn) Hrr.\napply (f_equal (canon_sym_gr_list n)) in Hrr.\nrewrite canon_sym_gr_list_canon_sym_gr_list_inv in Hrr; [ | easy ].\nrewrite canon_sym_gr_list_canon_sym_gr_list_inv in Hrr; [ | easy ].\neasy.\nQed.\n\nTheorem isort_rank_inj : ∀ l,\n  permut_seq l\n  → ∀ i j, i < length l → j < length l\n  → nth i (isort_rank Nat.leb l) 0 = nth j (isort_rank Nat.leb l) 0\n  → i = j.\nProof.\nintros * Hp * Hi Hj Hij.\nrewrite <- (isort_rank_length Nat.leb) in Hi, Hj.\nnow apply (NoDup_nat _ (NoDup_isort_rank _ _)) in Hij.\nQed.\n\nTheorem isort_rank_leb_seq : ∀ n, isort_rank Nat.leb (seq 0 n) = seq 0 n.\nProof.\nintros.\nrewrite (eq_sorted_isort_rank_seq Nat_leb_trans). {\n  now rewrite seq_length.\n}\napply sorted_nat_ltb_leb_incl.\napply sorted_seq.\nQed.\n\nTheorem isort_rank_ltb_seq : ∀ n, isort_rank Nat.ltb (seq 0 n) = seq 0 n.\nProof.\nintros.\nrewrite (eq_sorted_isort_rank_seq Nat_ltb_trans). {\n  now rewrite seq_length.\n}\napply sorted_seq.\nQed.\n\n(* to be completed\n   and put in SortRank.v\n   and prove isort_rank_permut_seq_with_len with that\nTheorem permutation_isort_rank : ∀ A (rel : A → _) la,\n  permutation Nat.eqb (isort_rank rel la) (seq 0 (length la)).\nProof.\nintros.\ninduction la as [| a]; [ easy | ].\ncbn - [ nth seq ].\nSearch (permutation _ (isort_insert _ _ _)).\nSearch (permutation _ (isort_rank_insert _ _ _ _)).\nPrint isort_rank_insert.\n...\nintros.\napply (permut_if_isort Nat.ltb Nat.eqb_eq).\nrewrite isort_isort_rank with (d := 0).\nrewrite isort_isort_rank with (d := 0).\napply List_eq_iff.\ndo 2 rewrite map_length.\ndo 3 rewrite isort_rank_length.\nrewrite seq_length.\nsplit; [ easy | ].\nintros d i.\ndestruct (lt_dec i (length la)) as [Hila| Hila]. 2: {\n  apply Nat.nlt_ge in Hila.\n  rewrite nth_overflow. 2: {\n    rewrite map_length.\n    now do 2 rewrite isort_rank_length.\n  }\n  rewrite nth_overflow. 2: {\n    now rewrite map_length, isort_rank_length, seq_length.\n  }\n  easy.\n}\nrewrite (List_map_nth' 0); [ | now do 2 rewrite isort_rank_length ].\nrewrite (List_map_nth' 0); [ | now rewrite isort_rank_length, seq_length ].\nrewrite seq_nth. 2: {\n  specialize (isort_rank_ub Nat.ltb) as H1.\n  specialize (H1 (seq 0 (length la)) i).\n  rewrite seq_length in H1.\n  apply H1; intros H2.\n  apply List_seq_eq_nil in H2.\n  now rewrite H2 in Hila.\n}\ncbn.\n(**)\nCompute (\nlet la := [3;9;7;9;5;5;2] in\nlet rel := Nat.ltb in\nmap (λ i,\n  nth (nth i (isort_rank Nat.ltb (isort_rank rel la)) 0) (isort_rank rel la) 0 =\n  nth i (isort_rank Nat.ltb (seq 0 (length la))) 0) (seq 0 (length la))\n).\n(**)\nrewrite isort_rank_ltb_seq.\nrewrite seq_nth; [ | easy ].\nCompute (\nlet la := [3;9;7;9;5;5;2] in\nlet rel := λ i j, false in\nmap (λ i,\n  nth (nth i (isort_rank Nat.ltb (isort_rank rel la)) 0) (isort_rank rel la) 0 = 0 + i\n) (seq 0 (length la))\n).\nremember (isort_rank rel la) as lb eqn:Hlb.\nassert (H : i < length lb) by now rewrite Hlb, isort_rank_length.\nassert (Hp : permutation Nat.ltb lb (seq 0 (length lb))).\nrewrite Hlb.\nrewrite isort_rank_length.\nSearch (permutation _ _ (isort_rank _ _)).\nSearch (permutation _ (isort_rank _ _)).\n...\nclear d la Hila Hlb.\nrename lb into la; rename H into Hla; cbn.\nSearch (nth _ (isort_rank _ _)).\nCompute (\nmap (λ la,\nmap (λ i,\n  nth (nth i (isort_rank Nat.ltb la) 0) la 0 = i\n) (seq 0 (length la))\n) (all_permut (seq 0 4))\n).\nrewrite nth_nth_isort_rank; [ | now rewrite isort_rank_length ].\nSearch (nth _ (isort _ _)).\nSearch (isort _ _ = seq _ _).\nrewrite permut_isort_leb.\n...\nrewrite isort_isort_rank with (d := 0).\nrewrite (List_map_nth' 0); [ | now do 2 rewrite isort_rank_length ].\n...\nCompute (\nlet la := [3;9;7;9;5;5;2] in\nlet rel := λ i j, Nat.leb j i in\nmap (λ i,\n  nth i (isort Nat.ltb (isort_rank rel la)) 0 = 0 + i\n) (seq 0 (length la))\n).\nrewrite isort_isort_rank with (d := 0).\nrewrite (List_map_nth' 0); [ | now do 2 rewrite isort_rank_length ].\nrewrite nth_nth_isort_rank.\n  ============================\n  nth i (isort Nat.ltb (isort_rank rel la)) 0 = 0 + i\n\n...\nrewrite nth_nth_isort_rank.\n...\nrewrite isort_rank_seq.\n...\nrewrite isort_rank_seq.\nnow rewrite seq_nth.\n...\nintros.\nremember (length la) as len eqn:Hlen; symmetry in Hlen.\nrevert la Hlen.\ninduction len; intros; [ now apply length_zero_iff_nil in Hlen; subst la | ].\nrewrite seq_S; cbn.\neapply (permutation_trans Nat.eqb_eq). 2: {\n  apply (permutation_cons_append Nat.eqb_eq).\n}\napply (permutation_sym Nat.eqb_eq).\napply permutation_cons_l_iff.\nremember (extract _ _) as lxl eqn:Hlxl; symmetry in Hlxl.\ndestruct lxl as [((bef, x), aft)| ]. 2: {\n  specialize (proj1 (extract_None_iff _ _) Hlxl) as H1.\n  specialize (pigeonhole_list len (isort_rank rel la)) as H2.\n  rewrite isort_rank_length, Hlen in H2.\n  assert (H : len < S len) by easy.\n  specialize (H2 H); clear H.\n  assert (H : ∀ i, i ∈ isort_rank rel la → i < len). {\n    intros i Hi.\n    destruct (Nat.eq_dec i len) as [Hil| Hil]. {\n      subst i; apply H1 in Hi.\n      now rewrite Nat.eqb_refl in Hi.\n    }\n    apply in_isort_rank in Hi; rewrite Hlen in Hi.\n    flia Hi Hil.\n  }\n  specialize (H2 H); clear H.\n  remember (pigeonhole_comp_list (isort_rank rel la)) as xx eqn:Hxx.\n  symmetry in Hxx.\n  destruct xx as (i, j).\n  specialize (H2 _ _ eq_refl).\n  destruct H2 as (Hil & Hjl & H & Hij).\n  apply H; clear H.\n  rewrite <- Hlen in Hil, Hjl.\n  apply (NoDup_nth (isort_rank rel la) 0); [ | | | easy ]. {\n    apply NoDup_isort_rank.\n  } {\n    now rewrite isort_rank_length.\n  } {\n    now rewrite isort_rank_length.\n  }\n}\napply extract_Some_iff in Hlxl.\ndestruct Hlxl as (Hbef & H & Haft).\napply Nat.eqb_eq in H; subst x.\nCheck permutation_elt.\n...\n  destruct la as [| a]; [ easy | ].\n  cbn in Hlen.\n...\n  assert (H : len ∈ isort_rank rel la). {\nSearch (_ ∈ isort_rank _ _).\n...\nCheck permut_seq_iff.\nPrint permut_seq.\n...\n*)\n\nTheorem isort_rank_permut_seq_with_len : ∀ A (rel : A → _) n l,\n  length l = n\n  → permut_seq_with_len n (isort_rank rel l).\nProof.\nintros.\nsubst n.\nsplit. {\n  apply permut_seq_iff.\n  split. {\n    intros i Hi.\n    rewrite isort_rank_length.\n    apply (In_nth _ _ 0) in Hi.\n    rewrite isort_rank_length in Hi.\n    destruct Hi as (ia & Hial & Hia).\n    rewrite <- Hia.\n    apply isort_rank_ub.\n    now intros H; rewrite H in Hial.\n  } {\n    apply NoDup_isort_rank.\n  }\n}\napply isort_rank_length.\nQed.\n\nArguments isort_rank_permut_seq_with_len {A} rel n%nat [l]%list.\n\nTheorem isort_rank_permut_seq : ∀ A (rel : A → _) l,\n  permut_seq (isort_rank rel l).\nProof.\nintros.\nnow apply (isort_rank_permut_seq_with_len _ (length l)).\nQed.\n\nTheorem permutation_isort_rank : ∀ A (rel : A → _) la,\n  permutation Nat.eqb (isort_rank rel la) (seq 0 (length la)).\nProof.\nintros.\nspecialize (isort_rank_permut_seq rel la) as H1.\nunfold permut_seq in H1.\nnow rewrite isort_rank_length in H1.\nQed.\n\n(* *)\n\nTheorem nth_canon_sym_gr_list_ub : ∀ d i n k,\n  i < n\n  → k < n!\n  → nth i (canon_sym_gr_list n k) d < n.\nProof.\nintros * Hin Hkn.\nrevert i k Hin Hkn.\ninduction n; intros; [ easy | cbn ].\ndestruct i. {\n  apply Nat.div_lt_upper_bound; [ apply fact_neq_0 | ].\n  rewrite Nat.mul_comm.\n  now rewrite <- Nat_fact_succ.\n}\napply Nat.succ_lt_mono in Hin.\nrewrite (List_map_nth' 0); [ | now rewrite canon_sym_gr_list_length ].\nunfold succ_when_ge.\nspecialize (IHn i (k mod n!) Hin) as H1.\nassert (H : k mod n! < n!) by apply Nat.mod_upper_bound, fact_neq_0.\nspecialize (H1 H); clear H.\nrewrite <- Nat.add_1_l, Nat.add_comm.\nrewrite nth_indep with (d' := 0) in H1. 2: {\n  now rewrite canon_sym_gr_list_length.\n}\napply Nat.add_le_lt_mono; [ | easy ].\napply Nat_b2n_upper_bound.\nQed.\n\nTheorem permutation_in_all_permut : ∀ la lb,\n  permutation eqb la lb → la ∈ all_permut lb.\nProof.\nintros * Hpab.\ndestruct lb as [| d]. {\n  apply permutation_nil_r in Hpab; subst la.\n  now left.\n}\nunfold all_permut.\nremember (d :: lb) as l eqn:Hl.\nclear lb Hl.\nrename l into lb.\nerewrite map_ext_in. 2: {\n  intros lc Hlc.\n  erewrite map_ext_in. 2: {\n    intros i Hi.\n    rewrite nth_indep with (d' := 0). 2: {\n      apply in_map_iff in Hlc.\n      destruct Hlc as (b & H & Hlc); subst lc.\n      apply (In_nth _ _ 0) in Hi.\n      rewrite canon_sym_gr_list_length in Hi.\n      destruct Hi as (j & Hjb & Hi).\n      subst i.\n      apply in_seq in Hlc.\n      now apply nth_canon_sym_gr_list_ub.\n    }\n    easy.\n  }\n  easy.\n}\nclear d.\napply in_map_iff.\nunfold canon_sym_gr_list_list.\nexists (permutation_assoc eqb la lb).\nsplit. {\n  symmetry.\n  now apply (map_permutation_assoc Nat.eqb_eq).\n}\napply in_map_iff.\nremember (length lb) as n eqn:Hlb; symmetry in Hlb.\nremember (permutation_assoc eqb la lb) as p eqn:Hp.\nexists (canon_sym_gr_list_inv n p).\nrewrite canon_sym_gr_list_canon_sym_gr_list_inv. 2: {\n  subst p.\n  split; [ now apply (perm_assoc_permut_seq Nat.eqb_eq) | ].\n  generalize Hpab; intros H.\n  apply permutation_length in H.\n  rewrite <- Hlb, <- H.\n  now apply (permutation_assoc_length Nat.eqb_eq).\n}\nsplit; [ easy | ].\napply in_seq.\nsplit; [ easy | ].\napply canon_sym_gr_list_inv_ub.\nrewrite Hp.\nsplit; [ now apply (perm_assoc_permut_seq Nat.eqb_eq) | ].\ngeneralize Hpab; intros H.\napply permutation_length in H.\nrewrite <- Hlb, <- H.\nnow apply (permutation_assoc_length Nat.eqb_eq).\nQed.\n\nTheorem in_all_permut_permutation : ∀ la lb,\n  la ∈ all_permut lb → permutation eqb la lb.\nProof.\nintros * Hla.\nrevert la Hla.\ninduction lb as [| b]; intros. {\n  destruct la; [ easy | now destruct Hla ].\n}\ncbn - [ canon_sym_gr_list nth fact ] in Hla.\napply in_map_iff in Hla.\ndestruct Hla as (lc & Hla & H).\nunfold canon_sym_gr_list_list in H.\napply in_map_iff in H.\ndestruct H as (d & Hlc & Hd).\napply in_seq in Hd.\ndestruct Hd as (_, Hd); rewrite Nat.add_0_l in Hd.\ncbn in Hlc.\nremember (d / (length lb)!) as a eqn:Ha.\nremember (map (succ_when_ge a) _) as le eqn:Hle.\nsubst lc; rename le into lc.\ncbn - [ nth ] in Hla.\ndestruct (lt_dec d (length lb)!) as [Hdb| Hdb]. {\n  rewrite Nat.div_small in Ha; [ | easy ].\n  rewrite Nat.mod_small in Hle; [ | easy ].\n  subst a.\n  rewrite List_nth_0_cons in Hla.\n  subst la.\n  apply permutation_skip; [ now intros a; apply Nat.eqb_eq | ].\n  apply IHlb.\n  unfold succ_when_ge in Hle.\n  erewrite map_ext_in in Hle. 2: {\n    intros a Ha.\n    now cbn; rewrite Nat.add_1_r.\n  }\n  subst lc.\n  rewrite map_map.\n  erewrite map_ext_in; [ | now intros; cbn ].\n  apply permutation_in_all_permut.\n  apply (permutation_sym Nat.eqb_eq).\n  specialize (permutation_refl Nat.eqb_eq lb) as H.\n  rewrite (map_permutation_assoc Nat.eqb_eq b H) at 1.\n  apply (permutation_map Nat.eqb_eq Nat.eqb_eq); clear H.\n  eapply (permutation_trans Nat.eqb_eq). {\n    apply (permutation_permutation_assoc Nat.eqb_eq).\n    apply (permutation_refl Nat.eqb_eq).\n  }\n  specialize (canon_sym_gr_list_length d (length lb)) as H1.\n  rewrite <- H1 at 1.\n  apply (permutation_sym Nat.eqb_eq).\n  now apply canon_sym_gr_list_permut_seq.\n}\napply Nat.nlt_ge in Hdb.\nrename a into i.\napply (permutation_sym Nat.eqb_eq).\napply permutation_cons_l_iff.\nremember (extract (Nat.eqb b) la) as lxl eqn:Hlxl.\nsymmetry in Hlxl.\nremember (length lb) as n eqn:Hn.\nassert (Hdm : d mod n! < n!) by (apply Nat.mod_upper_bound, fact_neq_0).\ndestruct lxl as [((bef, x), aft)| ]. 2: {\n  specialize (proj1 (extract_None_iff _ _) Hlxl) as H1.\n  rewrite <- Hla in H1.\n  destruct i. {\n    rewrite List_nth_0_cons in H1.\n    specialize (H1 _ (or_introl eq_refl)).\n    now rewrite Nat.eqb_refl in H1.\n  }\n  rewrite List_nth_succ_cons in H1.\n  destruct (lt_dec i n) as [Hilb| Hilb]. 2: {\n    apply Nat.nlt_ge in Hilb.\n    specialize (H1 b).\n    rewrite nth_overflow in H1; [ | now rewrite <- Hn ].\n    specialize (H1 (or_introl eq_refl)).\n    now rewrite (equality_refl Nat.eqb_eq) in H1.\n  }\n  specialize (H1 b).\n  assert (H : b ∈ map (λ i, nth i (b :: lb) b) lc). {\n    apply in_map_iff.\n    exists 0.\n    split; [ easy | ].\n    rewrite Hle.\n    apply in_map_iff.\n    exists 0.\n    unfold succ_when_ge.\n    split; [ easy | ].\n    specialize canon_sym_gr_list_permut_seq as H2.\n    specialize (H2 n (d mod n!) Hdm).\n    specialize permut_list_surj as H3.\n    specialize (H3 0 _ H2).\n    rewrite canon_sym_gr_list_length in H3.\n    assert (H : 0 < n) by flia Hilb.\n    specialize (H3 H); clear H.\n    destruct H3 as (j & Hjn & Hj).\n    rewrite <- Hj.\n    apply nth_In.\n    now rewrite canon_sym_gr_list_length.\n  }\n  specialize (H1 (or_intror H)).\n  now rewrite (equality_refl Nat.eqb_eq) in H1.\n}\napply extract_Some_iff in Hlxl.\ndestruct Hlxl as (Hbef & H & Hlb).\napply Nat.eqb_eq in H; subst x.\napply (permutation_sym Nat.eqb_eq).\nrewrite <- Hla in Hlb.\ndestruct i. {\n  symmetry in Ha.\n  apply Nat.div_small_iff in Ha; [ | apply fact_neq_0 ].\n  now apply Nat.nle_gt in Ha.\n}\nrewrite List_nth_succ_cons in Hlb.\nclear la Hla.\nassert (Hin : i < n). {\n  apply Nat.succ_lt_mono.\n  rewrite Ha.\n  apply Nat.div_lt_upper_bound; [ apply fact_neq_0 | ].\n  now rewrite Nat.mul_comm, <- Nat_fact_succ.\n}\nsubst lc.\nrewrite nth_indep with (d' := 0) in Hlb; [ | now rewrite <- Hn ].\nerewrite map_ext_in in Hlb. 2: {\n  intros j Hj.\n  apply in_map_iff in Hj.\n  destruct Hj as (k & Hk & Hj).\n  rewrite nth_indep with (d' := 0). 2: {\n    rewrite <- Hk.\n    unfold succ_when_ge.\n    apply in_canon_sym_gr_list in Hj; [ | easy ].\n    cbn - [ \"<=?\" ].\n    rewrite Nat.add_comm.\n    unfold Nat.b2n.\n    destruct (S i <=? k); flia Hn Hj.\n  }\n  easy.\n}\nrewrite map_map in Hlb.\nerewrite map_ext_in in Hlb. 2: {\n  intros j Hj.\n  replace (nth _ _ _) with (nth j (b :: butn i lb) 0). 2: {\n    destruct j; [ easy | cbn ].\n    now rewrite nth_butn.\n  }\n  easy.\n}\napply (permutation_cons_inv Nat.eqb_eq) with (a := b).\neapply (permutation_trans Nat.eqb_eq). {\n  apply (permutation_middle Nat.eqb_eq).\n}\nrewrite <- Hlb.\nassert (H : lb = firstn i lb ++ nth i lb 0 :: skipn (S i) lb). {\n  rewrite <- (firstn_skipn i lb) at 1.\n  f_equal.\n  apply List_skipn_is_cons.\n  now rewrite <- Hn.\n}\napply (permutation_sym Nat.eqb_eq).\nrewrite H at 1; clear H.\napply (permutation_sym Nat.eqb_eq).\nrewrite app_comm_cons.\neapply (permutation_trans Nat.eqb_eq). 2: {\n  apply (permutation_middle Nat.eqb_eq).\n}\napply permutation_skip; [ now intros a; apply Nat.eqb_eq | ].\ncbn - [ nth skipn ].\nrewrite fold_butn.\nrewrite List_map_nth_seq with (d := 0).\napply (permutation_map Nat.eqb_eq Nat.eqb_eq).\ncbn - [ seq ].\nrewrite butn_length.\ngeneralize Hin; intros H.\napply Nat.ltb_lt in H.\nrewrite Hn in H; rewrite H; clear H.\nrewrite <- Hn.\nrewrite <- Nat.sub_succ_l; [ | cbn; flia Hin ].\nrewrite Nat_sub_succ_1.\nrewrite Hn.\neapply (permutation_trans Nat.eqb_eq). {\n  apply canon_sym_gr_list_permut_seq.\n  apply Nat.mod_upper_bound, fact_neq_0.\n}\nrewrite canon_sym_gr_list_length.\napply (permutation_refl Nat.eqb_eq).\nQed.\n\nTheorem in_all_permut_iff : ∀ la lb,\n  la ∈ all_permut lb ↔ isort Nat.leb la = isort Nat.leb lb.\nProof.\nintros.\nsplit; intros Hab. {\n  apply in_all_permut_permutation in Hab.\n  apply (isort_when_permuted Nat.eqb_eq); [ | | | easy ]. {\n    apply Nat_leb_antisym.\n  } {\n    apply Nat_leb_trans.\n  } {\n    apply Nat_leb_total_relation.\n  }\n} {\n  apply permutation_in_all_permut.\n  now apply (permut_if_isort Nat.leb Nat.eqb_eq).\n}\nQed.\n\nTheorem NoDup_all_permut : ∀ A (la : list A),\n  NoDup la → NoDup (all_permut la).\nProof.\nintros * Hnd.\ndestruct la as [| d]. {\n  constructor; [ easy | constructor ].\n}\nunfold all_permut.\nremember (d :: la) as lb eqn:Hlb.\nclear la Hlb.\nrename lb into la.\napply (NoDup_map_iff []).\nunfold canon_sym_gr_list_list.\nrewrite List_map_seq_length.\nintros * Hi Hj Hij.\nrewrite (List_map_nth' 0) in Hij; [ | now rewrite seq_length ].\nrewrite (List_map_nth' 0) in Hij; [ | now rewrite seq_length ].\nrewrite seq_nth in Hij; [ | easy ].\nrewrite seq_nth in Hij; [ | easy ].\ndo 2 rewrite Nat.add_0_l in Hij.\napply List_eq_iff in Hij.\ndestruct Hij as (_, Hij).\nspecialize (Hij d).\nremember (∀ k, _) as x in Hij; subst x.\nassert\n  (H : ∀ k,\n   nth (nth k (canon_sym_gr_list (length la) i) 0) la d =\n   nth (nth k (canon_sym_gr_list (length la) j) 0) la d). {\n  intros.\n  specialize (Hij k).\n  destruct (lt_dec k (length la)) as [Hka| Hka]. 2: {\n    apply Nat.nlt_ge in Hka.\n    rewrite nth_overflow with (n := k). 2: {\n      now rewrite canon_sym_gr_list_length.\n    }\n    rewrite nth_overflow with (n := k). 2: {\n      now rewrite canon_sym_gr_list_length.\n    }\n    easy.\n  }\n  rewrite (List_map_nth' 0) in Hij. 2: {\n    now rewrite canon_sym_gr_list_length.\n  }\n  rewrite (List_map_nth' 0) in Hij. 2: {\n    now rewrite canon_sym_gr_list_length.\n  }\n  easy.\n}\nclear Hij; rename H into Hij.\napply nth_canon_sym_gr_list_inj2 with (n := length la); [ easy | easy | ].\nintros k Hk.\nspecialize (Hij k).\nremember (nth k (canon_sym_gr_list (length la) i) 0) as i' eqn:Hi'.\nremember (nth k (canon_sym_gr_list (length la) j) 0) as j' eqn:Hj'.\nspecialize (proj1 (NoDup_nth la d) Hnd) as H1.\napply H1; [ | | easy ]. {\n  now rewrite Hi'; apply canon_sym_gr_list_ub.\n} {\n  now rewrite Hj'; apply canon_sym_gr_list_ub.\n}\nQed.\n\nArguments nth_canon_sym_gr_list_inj2 n%nat [i j]%nat.\n", "meta": {"author": "roglo", "repo": "coq_sensitivity", "sha": "398291aa86a447f0f35b4918043e94d9eb703c12", "save_path": "github-repos/coq/roglo-coq_sensitivity", "path": "github-repos/coq/roglo-coq_sensitivity/coq_sensitivity-398291aa86a447f0f35b4918043e94d9eb703c12/main/PermutSeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7071971423746908}}
{"text": "(** This file contains some lemmas you will have to prove, i.e. replacing\n   the \"Admitted\" joker with a sequence of tactic calls, terminated with a \n   \"Qed\" command.\n\n   Each lemma could be proved several times using various combinations\n   of tactics.\n\n   Notice that, if you want to keep all solutions, you may use various \n   identifiers like in the given example : imp_dist, imp_dist' share\n   the same statement, with different interactive proofs.\n\n*)\n\n(* Une seule étoile *)\n\nSection Minimal_propositional_logic.\n\n  (** Propositional Intuitionistic logic restricted to the [->] fragment *)\n\n  Variables P Q R S : Prop.\n\n  (* Prove the lemmas using the following tactics \n\n      intro[s], exact, apply, assumption, trivial\n\n  *)\n\n  (** The I combinator *)\n  Proposition I_P : P -> P.\n  Proof. \n    intro p.\n    exact p. (* assumption or trivial *) \n  Qed.\n\n  Check I_P.\n\n  Print I_P.\n\n  (** The K combinator *)\n  Lemma K_PQ : P -> Q -> P. \n  Proof.\n    intros p q.\n    exact p.\n    (* intros; trivial or trivial or auto *)\n  Qed.\n\n  Print K_PQ.    \n\n  (** The S combinator *)\n  Lemma S_PQR : (P -> Q -> R) -> (P -> Q) -> P -> R.\n  Proof.\n    intros H1 H2 H3.\n    apply H1.\n    + apply H3.\n    + apply H2, H3.\n(*\n    apply H1; try apply H2; apply H3.\n\nor\n\n    apply H1; [ apply H3 | apply H2, H3 ].\n\nor \n\n    apply H1; repeat (apply H2 || apply H3).\n\n*)\n  Qed.\n\n  Print S_PQR.\n\n  (** The B combinator *)\n  Lemma B_PQR : (Q -> R) -> (P -> Q) -> P -> R.\n  Proof.\n    intros H1 H2 ?.\n    apply H1, H2; assumption. \n  Qed.\n\n  (** The C combinator *)\n  Lemma C_PQR : (P -> Q -> R) -> Q -> P -> R.\n  Proof.\n    intros H ? ?.\n    apply H; assumption.\n  Qed.\n\n  Lemma imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\n  Proof.\n    intros H1 H2 H3.\n    apply H2, H1, H3.\n  Qed.\n\n  Lemma ignore_Q : (P -> R) -> P -> Q -> R.\n  Proof.\n  (*  intros ? H _; revert H; assumption. *)\n    intros H1 H2 H3.\n    clear H3.\n  (*  apply H1, H2. *)\n    revert H2.\n    assumption.\n  Qed.\n\n  Print ignore_Q.\n\n  Definition delta_imp : (P -> P -> Q) -> P -> Q.\n  Proof.\n    intros H ?; apply H; assumption.\n(*    refine (fun H1 H2 => H1 H2 _);  trivial. *)\n  Qed.\n\n  Lemma delta_impR : (P -> Q) -> P -> P -> Q.\n  Proof.\n    intros H a b.\n    apply H, a.\n  Qed.\n\n  Print delta_impR.\n\n  Lemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> S) -> P -> S.\n  Proof.\n    intros H1 H2 H3 H4.\n    apply H3; [ apply H1 | apply H2 ]; apply H4.\n(*\n    apply H3.\n    + apply H1, H4.\n    + apply H2, H4. *)\n  Qed.\n\n  Lemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\n  Proof.\n    intros H; apply H.\n    intros H1; apply H1.\n    intros H2; apply H.\n    intros _; apply H2.\n  Qed.\n\n  Print weak_peirce.\n\n  Lemma natural_number : (P -> P) -> (P -> P).\n  Proof.\n    intros H p.\n    do 8 apply H.\n    exact p.\n  Qed.\n\n  Print natural_number.\n\nEnd Minimal_propositional_logic.\n\nSection propositional_logic.\n\n  (** Propositional Intuitionistic logic *)\n\n  Variables P Q R S T : Prop.\n\n  (* Prove the lemmas using the following tactics \n\n      intro[s], exact, apply, assumption, trivial\n      destruct, left/right, split\n\n      try use tactic composition\n\n  *)\n\n  Lemma and_assoc : P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\n  Proof.\n    intros [ p [ q r ] ].\n    split.\n    + split.\n      * exact p.\n      * exact q.\n    + exact r.\n  (*  intro H. destruct H as (p & [ q r ]). *)\n (*   destruct H as [ p qr ].\n    destruct qr as [ q r ]. *)\n (*   destruct H as [ p [ q r ] ]. *)\n  Qed.\n \n  Print and_assoc.\n\n  Lemma and_imp_dist : (P -> Q) /\\ (R -> S) -> P /\\ R -> Q /\\ S.\n  Proof.\n    intros (H1 & H2) (H3 & H4).\n    split.\n    + apply H1, H3.\n    + apply H2, H4.\n  Qed.\n\n  \n\n  (* ~P (not P) is defined as P -> False *)\n\n  Lemma not_contrad :  (P /\\ (P -> Q)) -> Q.\n  Proof.\n    (* unfold not *)\n    intros (p & np).\n    apply np, p.\n  Qed.\n\n  Lemma not_contrad' :  ~(P /\\ ~P).\n  Proof.\n    intros (p & np).\n    destruct np.\n    exact p.\n  Qed.\n\n  Print not_contrad.\n  Print not_contrad'.\n\n  Print True.\n \n  Lemma or_and_not : (P \\/ Q) /\\ ~P -> Q.\n  Proof.\n  (*\n    intros ([ H | H ] & np).\n    + destruct np.\n      exact H.\n    + exact H. *)\n    intros ([|] & np); [ destruct np | idtac ]; assumption. \n(*   intros (pq & np).\n    destruct pq as [ p | q ]. *)\n  Admitted.\n\n  Lemma not_not_exm : ~ ~ (P \\/ ~ P).\n  Proof.\n    intros H.\n    apply H.\n    right.\n    intros p.\n    apply H.\n    left.\n    exact p.\n  Qed.\n\n  Lemma de_morgan_1 : ~(P \\/ Q) -> ~P /\\ ~Q.\n  Proof.\n    intros H.\n    split.\n    + contradict H.\n      left.\n      assumption.\n    + intros q.\n      apply H.\n      right.\n      assumption.\n  Qed.\n \n  Lemma de_morgan_2 : ~P /\\ ~Q -> ~(P \\/ Q).\n  Proof.\n    intros (np & nq) [ p | q ].\n    + apply np, p.\n    + apply nq, q.\n  Qed.\n\n  Lemma de_morgan_3 : ~P \\/ ~Q -> ~(P /\\ Q).\n  Proof.\n    intros [ np | nq ] (p & q).\n    + apply np, p.\n    + apply nq, q.\n  Qed.\n\n  Lemma or_to_imp : P \\/ Q -> ~ P -> Q.\n  Proof.\n    intros [ p | q ] np.\n    + destruct np.\n      apply p.\n    + apply q.\n  Qed.\n\n  Lemma destruct_before_left_right : (P \\/ Q) -> (P -> R) -> (Q -> T) -> R \\/ T.\n  Proof.\n    intros [ p | q ] H1 H2.\n    + left.\n      apply H1, p.\n    + right.\n      apply H2, q.\n  Qed.\n\n  Lemma imp_to_not_not_or : (P -> Q) -> ~~(~P \\/ Q).\n  Proof.\n    intros H1 H2.\n    assert (~ Q) as H3. (** State intermediate lemma *)\n    + contradict H2; right; assumption.\n    + apply H2.\n      left.\n      intros H4.\n      apply H3, H1, H4.\n  Qed.\n\n  Lemma contraposition : (P -> Q) -> (~Q -> ~P).\n  Proof.\n    intros H1 H2. \n    contradict H2.\n    apply H1, H2.\n  Qed.\n\n  (** A <-> B is defined as (A -> B) /\\ (B -> A) *)\n\n  Lemma contraposition' : (~P -> ~Q) <-> (~~Q -> ~~P).\n  Proof.\n    (* unfold iff. *)\n    split.\n    + intros H1 H2. \n      contradict H2.\n      apply H1, H2.\n    + intros H1 H2 H3.\n      apply H1; trivial.\n      intros C; apply C, H3.\n  Qed.\n\n  Lemma contraposition'' : (~P -> ~Q) <-> ~~(Q -> P).\n  Proof.\n    split.\n    + intros H1 H2.\n      apply H2.\n      intros H3.\n      destruct H1.\n      * contradict H2; intros _; assumption.\n      * assumption.\n    + intros H1 H2 H3.\n      apply H1.\n      intros H4.\n      apply H2, H4, H3.\n  Qed.\n \n  Section weak_XM.\n\n   Hypothesis H0 : P -> R.\n   Hypothesis H1 : ~P -> R.\n\n   Lemma weak_XM : ~~R.\n   Proof.\n     intros nr.\n     apply nr, H1.\n     intros p.\n     apply nr, H0, p.\n   Qed.\n\n   Check weak_XM.\n\n  End weak_XM.\n\n  Check weak_XM.\n\n  (* Now, you may invent and solve your own exercises ! \n     Note that you can trust the tactic tauto, based on \n     Dyckhoff's LJT calculus: if it fails, then your formula\n     is probably not (intuitionnistically) provable *)\n\n  Lemma contraposition''' : (~P -> ~Q) <-> (Q -> P).\n  Proof.\n    (* tauto. *) (* Not provable in Intuitionistic Logic *)\n  Admitted.\n\nEnd propositional_logic.\n", "meta": {"author": "DmxLarchey", "repo": "Introduction-to-Coq", "sha": "c2924b5284ef87143def1850520a25984dc0e724", "save_path": "github-repos/coq/DmxLarchey-Introduction-to-Coq", "path": "github-repos/coq/DmxLarchey-Introduction-to-Coq/Introduction-to-Coq-c2924b5284ef87143def1850520a25984dc0e724/lab1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7071971375271642}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) : natural := mult z (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_commut/goal33conj286_coqofml_LFSeWw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529791457032, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7071937816259503}}
{"text": "Require Import Axiom_Extensionality.\nRequire Import Axiom_ProofIrrelevance.\nRequire Import Category.\n\nLemma eq_Category : forall (A:Type) (c c':Category A),\n    (forall f:A, source c f = source c' f) ->\n    (forall f:A, target c f = target c' f) ->\n    (forall f g:A, compose c f g = compose c' f g) -> c = c'. \nProof.\n    intros A c1 c2 Hs Ht Hc. \n    destruct c1 as [s1 t1 cmp1 pss1 pts1 ptt1 pst1 pd1 ps1 pt1 pl1 pr1 pa1].\n    destruct c2 as [s2 t2 cmp2 pss2 pts2 ptt2 pst2 pd2 ps2 pt2 pl2 pr2 pa2].\n    simpl in Hs. simpl in Ht. simpl in Hc.\n    apply extensionality  in Hs.\n    apply extensionality  in Ht.\n    apply extensionality2 in Hc.\n    revert pss1 pts1 ptt1 pst1 pd1 ps1 pt1 pl1 pr1 pa1.\n    rewrite Hs, Ht, Hc.\n    intros pss1 pts1 ptt1 pst1 pd1 ps1 pt1 pl1 pr1 pa1.\n    rewrite (proof_irrelevance _ pss1 pss2).\n    rewrite (proof_irrelevance _ pts1 pts2).\n    rewrite (proof_irrelevance _ ptt1 ptt2).\n    rewrite (proof_irrelevance _ pst1 pst2).\n    rewrite (proof_irrelevance _ pd1 pd2).\n    rewrite (proof_irrelevance _ ps1 ps2).\n    rewrite (proof_irrelevance _ pt1 pt2).\n    rewrite (proof_irrelevance _ pl1 pl2).\n    rewrite (proof_irrelevance _ pr1 pr2).\n    rewrite (proof_irrelevance _ pa1 pa2).\n    reflexivity.\nQed.\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/cat/Eq_Category.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7071937771011103}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf2 : natural) : natural :=\n  mult y lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj205_coqofml_SsSnJg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7071937729082387}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  Succ (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj208_coqofml_YzXHTL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7071937725762705}}
{"text": "Require Import msl.msl_standard.\n(* Orders & Boolean algebras *) \n\n(* Orders *)\nDelimit Scope ord with ord.\nOpen Scope ord.\n\nClass Ord (A : Type) : Type :=\n  { ord : A -> A -> Prop;\n    ord_refl : forall x, ord x x;\n    ord_trans : forall x y z, ord x y -> ord y z -> ord x z;\n    ord_antisym : forall x y, ord x y -> ord y x -> x = y\n    }.\nNotation \"x <= y\" := (ord x y) (at level 70, no associativity) : ord.\nNotation \"x <= y <= z\" := ((x <= y) /\\ (y <= z)) (at level 70, y at next level) : ord.\n\nAdd Parametric Relation {A} `{Ord A} : A ord\n  reflexivity proved by ord_refl\n  transitivity proved by ord_trans\n  as ord_rel.\n\nImplicit Arguments ord_refl [[A] [Ord]].\nImplicit Arguments ord_trans [[A] [Ord]].\nImplicit Arguments ord_antisym [[A] [Ord]].\n\nHint Resolve @ord_refl @ord_antisym @ord_trans : ord.\n\nClass TOrd (A : Type) `{O: Ord A} : Type :=\n  tord_total : forall x y : A, (x <= y) \\/ (y <= x).\nImplicit Arguments TOrd [[O]].\n\nDefinition sord {A} `{Ord A} (a1 a2 : A) : Prop :=\n  ord a1 a2 /\\ a1 <> a2.\nNotation \"x < y\" := (sord x y) (at level 70, no associativity) : ord.\n\nLemma sord_trans {A} `{Ord A}: forall (x y z : A), x < y -> y < z -> x < z.\nProof.\n  intros ? ? ? [? ?] [? ?].\n  split. eauto with ord.\n  intro. subst x. eauto with ord.\nQed.\n\nAdd Parametric Relation {A} `{Ord A} : A sord \n  transitivity proved by sord_trans\n  as sord_rel.\n\nLemma sord_neq {A} `{Ord A} : forall x y : A, (x < y) -> ~ x = y.\nProof.\n  intros. destruct H0. trivial.\nQed.\n\nLemma sord_leq {A} `{Ord A} : forall x y : A, (x < y) -> (x <= y).\nProof.\n  intros. destruct H0. trivial.\nQed.\n\nHint Resolve @sord_neq @sord_leq : ord.\n\n(* Examples of orders *)\n\nInstance nat_ord : Ord nat := \n {| ord := le ; ord_refl := le_refl ; ord_trans := le_trans ; ord_antisym := le_antisym |}.\n\nInstance nat_tord : TOrd nat.\nProof.\n  intros x y. unfold ord. simpl. omega.\nQed.\n\n(* improved version of what is in msl/sepalg.v *)\nLemma join_sub_antisym' {A} `{J: Join A} `{PA: @Perm_alg A J} `{SA: @Sep_alg A J} : forall x y,\n  join_sub x y ->\n  join_sub y x ->\n  x = y.\nProof.\n  intros. unfold join_sub in *. destruct H. destruct H0.\n  apply (join_positivity H H0).\nQed.\n\nInstance join_ord {A} `{J: Join A} `{PA: @Perm_alg A J} `{SA: @Sep_alg A J}: Ord A :=\n {| ord := join_sub; ord_refl := join_sub_refl; ord_trans := join_sub_trans; ord_antisym := join_sub_antisym' |}.\n\n(* Boolean algebras *)\n\nClass BA (A : Type) `{O : Ord  A} : Type := \n  { top : A;\n    bot : A;\n    lub : A -> A -> A;\n    glb : A -> A -> A;\n    comp : A -> A;\n    lub_upper1 : forall x y, x <= lub x y;\n    lub_upper2 : forall x y, y <= lub x y;\n    lub_least : forall x y z, x <= z -> y <= z -> lub x y <= z;\n    glb_lower1 : forall x y, (glb x y) <= x;\n    glb_lower2 : forall x y, (glb x y) <= y;\n    glb_greatest : forall x y z, z <= x -> z <= y -> z <= (glb x y);\n    top_correct : forall x, x <= top;\n    bot_correct : forall x, bot <= x;\n    distrib1 : forall x y z, glb x (lub y z) = lub (glb x y) (glb x z);\n    comp1 : forall x, lub x (comp x) = top;\n    comp2 : forall x, glb x (comp x) = bot;\n    nontrivial : top <> bot\n}.\nImplicit Arguments top [A O BA].\nImplicit Arguments bot [A O BA].\nImplicit Arguments lub [A O BA].\nImplicit Arguments glb [A O BA].\nImplicit Arguments comp [A O BA].\nImplicit Arguments lub_upper1 [A O BA].\nImplicit Arguments lub_upper2 [A O BA].\nImplicit Arguments lub_least [A O BA].\nImplicit Arguments glb_lower1 [A O BA].\nImplicit Arguments glb_lower2 [A O BA].\nImplicit Arguments glb_greatest [A O BA].\nImplicit Arguments top_correct [A O BA].\nImplicit Arguments bot_correct [A O BA].\nImplicit Arguments distrib1 [A O BA].\nImplicit Arguments comp1 [A O BA].\nImplicit Arguments comp2 [A O BA].\nImplicit Arguments nontrivial [A O BA].\n\nHint Resolve @lub_upper1 @lub_upper2 @lub_least\n             @glb_lower1 @glb_lower2 @glb_greatest \n             @top_correct @bot_correct\n             @ord_trans : ord.\n\n(* Rob's lemmas *)\n\nLemma ord_spec1 {A} `{O : Ord A} `{@BA A O}: forall x y, x <= y <-> x = glb x y.\nProof.\n  split; intros.\n  eauto with ord.\n  rewrite H0. auto with ord.\nQed.\n\nLemma ord_spec2 {A} `{O : Ord A} `{@BA A O}: forall x y, x <= y <-> lub x y = y.\nProof.\n  intros; split; intros.\n  eauto with ord.\n  rewrite <- H0; auto with ord.\nQed.\n\nLemma lub_idem {A} `{O : Ord A} `{@BA A O}: forall x, lub x x = x.\nProof. eauto with ord. Qed.\n\nLemma glb_idem {A} `{O : Ord A} `{@BA A O}: forall x, glb x x = x.\nProof. eauto with ord. Qed.\n\nLemma lub_commute {A} `{O : Ord A} `{@BA A O}: forall x y, lub x y = lub y x.\nProof. eauto with ord. Qed.\n\nLemma glb_commute {A} `{O : Ord A} `{@BA A O}: forall x y, glb x y = glb y x.\nProof. eauto with ord. Qed.\n\nLemma lub_absorb {A} `{O : Ord A} `{@BA A O}: forall x y, lub x (glb x y) = x.\nProof. eauto with ord. Qed.\n\nLemma glb_absorb {A} `{O : Ord A} `{@BA A O}: forall x y, glb x (lub x y) = x.\nProof. eauto with ord. Qed.\n\nLemma lub_assoc {A} `{O : Ord A} `{@BA A O}: forall x y z, lub (lub x y) z = lub x (lub y z).\nProof.\n  intros; apply ord_antisym; eauto with ord.\nQed.\n\nLemma glb_assoc {A} `{O : Ord A} `{@BA A O}: forall x y z, glb (glb x y) z = glb x  (glb y z).\nProof.\n  intros; apply ord_antisym; eauto with ord.\nQed.\n\nLemma glb_bot {A} `{O : Ord A} `{@BA A O}: forall x, glb x bot = bot.\nProof. eauto with ord. Qed.\n\nLemma lub_top {A} `{O : Ord A} `{@BA A O}: forall x, lub x top = top.\nProof. eauto with ord. Qed.\n\nLemma lub_bot {A} `{O : Ord A} `{@BA A O}: forall x, lub x bot = x.\nProof. eauto with ord. Qed.\n\nLemma glb_top {A} `{O : Ord A} `{@BA A O}: forall x, glb x top = x.\nProof. eauto with ord. Qed.\n\nLemma distrib2 {A} `{O : Ord A} `{@BA A O}: forall x y z,\n  lub x (glb y z) = glb (lub x y) (lub x z).\nProof.\n  intros.\n  apply ord_antisym.\n  apply lub_least.\n  rewrite distrib1. eauto with ord. eauto with ord.\n  rewrite distrib1. \n  apply lub_least. eauto with ord.\n  rewrite glb_commute.\n  rewrite distrib1.\n  apply lub_least;\n  eauto with ord. \nQed.\n\nLemma distrib_spec {A} `{O : Ord A} `{@BA A O}: forall x y1 y2,\n  lub x y1 = lub x y2 ->\n  glb x y1 = glb x y2 ->\n  y1 = y2.\nProof.\n  intros.\n  rewrite <- (lub_absorb y2 x).\n  rewrite glb_commute.\n  rewrite <- H1.\n  rewrite distrib2.\n  rewrite lub_commute.\n  rewrite <- H0.\n  rewrite (lub_commute x y1).\n  rewrite (lub_commute y2 y1).\n  rewrite <- distrib2.\n  rewrite <- H1.\n  rewrite glb_commute.\n  rewrite lub_absorb.\n  auto.\nQed.\n\nLemma comp_inv {A} `{O : Ord A} `{@BA A O}: forall x, comp (comp x) = x.\nProof.\n  intro x.\n  apply distrib_spec with (comp x).\n  rewrite comp1.\n  rewrite lub_commute.\n  rewrite comp1.\n  auto.\n  rewrite comp2.\n  rewrite glb_commute.\n  rewrite comp2.\n  auto.\nQed.\n\nLemma demorgan1 {A} `{O : Ord A} `{@BA A O}: forall x y, comp (lub x y) = glb (comp x) (comp y).\nProof.\n  intros x y.\n  apply distrib_spec with (lub x y).\n  rewrite comp1.\n  rewrite distrib2.\n  rewrite (lub_assoc x y (comp y)).\n  rewrite comp1.\n  rewrite lub_top.\n  rewrite glb_top.\n  rewrite (lub_commute x y).\n  rewrite lub_assoc.\n  rewrite comp1.\n  rewrite lub_top.\n  auto.\n  rewrite comp2.\n  rewrite glb_commute.\n  rewrite distrib1.\n  rewrite (glb_commute (comp x) (comp y)).\n  rewrite glb_assoc.\n  rewrite (glb_commute (comp x) x).\n  rewrite comp2.\n  rewrite glb_bot.\n  rewrite lub_commute.\n  rewrite lub_bot.\n  rewrite (glb_commute (comp y) (comp x)).\n  rewrite glb_assoc.\n  rewrite (glb_commute (comp y) y).\n  rewrite comp2.\n  rewrite glb_bot.\n  auto.\nQed.\n\nLemma demorgan2 {A} `{O : Ord A} `{@BA A O}: forall x y, comp (glb x y) = lub (comp x) (comp y).\nProof.\n  intros x y.\n  apply distrib_spec with (glb x y).\n  rewrite comp1.\n  rewrite lub_commute.\n  rewrite distrib2.\n  rewrite (lub_commute (comp x) (comp y)).\n  rewrite lub_assoc.\n  rewrite (lub_commute (comp x) x).\n  rewrite comp1.\n  rewrite lub_top.\n  rewrite glb_commute.\n  rewrite glb_top.\n  rewrite (lub_commute (comp y) (comp x)).\n  rewrite lub_assoc.\n  rewrite (lub_commute (comp y) y).\n  rewrite comp1.\n  rewrite lub_top.\n  auto.\n  rewrite comp2.\n  rewrite distrib1.\n  rewrite (glb_commute x y).\n  rewrite glb_assoc.\n  rewrite comp2.\n  rewrite glb_bot.\n  rewrite lub_commute.\n  rewrite lub_bot.\n  rewrite (glb_commute y x).\n  rewrite glb_assoc.\n  rewrite comp2.\n  rewrite glb_bot.\n  auto.\nQed.\n\n(* Aquinas's lemmas *)\n\nLemma lub_leq {A} `{O : Ord A} `{@BA A O}: forall l1 l2 u1 u2 : A,\n  l1 <= u1 ->\n  l2 <= u2 ->\n  lub l1 l2 <= lub u1 u2.\nProof. eauto with ord. Qed.\n\n(*\n  intros.\n  apply Share.lub_least.\n  transitivity u1...\n  apply sh.lub_upper1.\n  transitivity u2...\n  apply sh.lub_upper2.\nQed.\n*)\n\nLemma glb_leq {A} `{O : Ord A} `{@BA A O}: forall l1 l2 u1 u2 : A,\n  l1 <= u1 ->\n  l2 <= u2 ->\n  glb l1 l2 <= glb u1 u2.\nProof. eauto with ord. Qed.\n\n(*\n with auto.\n  intros.\n  apply sh.glb_greatest.\n  transitivity l1...\n  apply sh.glb_lower1.\n  transitivity l2...\n  apply sh.glb_lower2.\nQed.\n*)\n\nLemma leq_top {A} `{O : Ord A} `{@BA A O}: forall s : A,\n  top <= s ->\n  s = top.\nProof. eauto with ord. Qed.\n(*\n  intros.\n  apply ord_antisym.\n  apply sh.top_top.\n  trivial.\nQed.\n*)\n\nLemma leq_bot {A} `{O : Ord A} `{@BA A O}: forall s : A,\n  s <= bot ->\n  s = bot.\nProof. eauto with ord. Qed.\n(*\n  intros.\n  apply ord_antisym.\n  trivial.\n  apply sh.bot_bot.\nQed.\n*)\n\nLemma comp_leq {A} `{O : Ord A} `{@BA A O}: forall l u : A,\n  l <= u ->\n  comp u <= comp l.\nProof with (eauto with ord).\n  intros.\n  assert (lub l (comp l) <= lub u (comp l)) by (eauto with ord).\n  rewrite comp1 in H1.\n  apply leq_top in H1.\n  assert (glb (comp u) (lub u (comp l)) = glb (comp u) top) by congr.\n  rewrite glb_top in H2.\n  rewrite distrib1 in H2.\n  rewrite (glb_commute _ u) in H2.\n  rewrite comp2 in H2.\n  rewrite lub_commute in H2.\n  rewrite lub_bot in H2.\n  rewrite <- H2...\nQed.\n\nLemma lub_leq_comp {A} `{O : Ord A} `{@BA A O}: forall l u : A,\n  l <= u ->\n  lub (comp l) u = top.\nProof with (eauto with ord).\n  intros.\n  apply comp_leq in H0.\n  assert (lub u (comp u) <= lub u (comp l)) by (eauto with ord).\n  rewrite comp1 in H1.\n  apply leq_top...\nQed.\n\nLemma comp_bot {A} `{O : Ord A} `{@BA A O}: comp bot = top.\nProof with (auto with ord).\n  apply ord_antisym...\n  rewrite <- (comp_inv top).\n  apply comp_leq...\nQed.\n\nLemma comp_top {A} `{O : Ord A} `{@BA A O}: comp top = bot.\nProof with (auto with ord).\n  apply ord_antisym...\n  rewrite <- (comp_inv bot).\n  apply comp_leq...\nQed.\n\nLemma glb_comp_leq {A} `{O : Ord A} `{@BA A O}: forall l u,\n  l <= u ->\n  glb l (comp u) = bot.\nProof with (eauto with ord).\n  intros.\n  apply ord_antisym. 2: apply bot_correct.\n  transitivity (glb u (comp u)).\n  apply glb_leq...\n  rewrite comp2...\nQed.\n\nLemma lub_comp_leq {A} `{O : Ord A} `{@BA A O}: forall l u,\n  l <= u ->\n  lub (comp l) u = top.\nProof with (auto with ord).\n  intros.\n  apply ord_antisym...\n  transitivity (lub l (comp l)).\n  rewrite comp1...\n  rewrite (lub_commute l).\n  apply lub_leq...\nQed.\n\nLemma leq_comp_join {A} `{O : Ord A} `{@BA A O}: forall a b,\n  glb a b = bot -> \n  a <= comp b.\nProof with (auto with ord).\n  intros.\n  transitivity (glb a (lub b (comp b))).\n  rewrite comp1...\n  rewrite distrib1, H0...\nQed.\n\nLemma lub_sub {A} `{O : Ord A} `{@BA A O}: forall a b,\n  glb (lub a b) (comp b) <= a.\nProof with (auto with ord).\n  intros.\n  rewrite glb_commute, distrib1, (glb_commute _ b), comp2...\nQed.\n\nLemma neg_tighten {A} `{O : Ord A} `{@BA A O}: forall l u l' u' : A,\n  ~(l <= u) ->\n  ~(lub l l' <= glb u u').\nProof with (auto with ord).\n  repeat intro. apply H0.\n  transitivity (glb u u')...\n  transitivity (lub l l')...\nQed.\n\n(* Connect the BA structure in shares to the BA typeclass *)\n\nInstance share_ba : BA share.\n  exists Share.top Share.bot Share.lub Share.glb Share.comp;\n  simpl; intros;\n  try rewrite <- leq_join_sub in *;\n  auto with ba.\n  apply Share.distrib1.\n  apply Share.comp1.\n  apply Share.comp2.\n  apply Share.nontrivial.\nDefined.\n\nClose Scope ord.\n", "meta": {"author": "lexuanbach", "repo": "certified-permission-procedure", "sha": "f0ac470d8096b106ea03c22e95950bae684bcc86", "save_path": "github-repos/coq/lexuanbach-certified-permission-procedure", "path": "github-repos/coq/lexuanbach-certified-permission-procedure/certified-permission-procedure-f0ac470d8096b106ea03c22e95950bae684bcc86/borders.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7071937683833989}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) (lf1 : natural) : natural :=\n  Succ (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj257_coqofml_400m63.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7071937680514305}}
{"text": "From HB Require Import structures.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype choice order.\nFrom mathcomp Require Import ssrnat bigop.\nRequire Import HB_wrappers.\n\n(******************************************************************************)\n(* The algebraic structures of semi-rings and dioids, as described in:        *)\n(*   Michel Minoux, Michel Gondran.                                           *)\n(*   'Graphs, Dioids and Semirings. New Models and Algorithms.'               *)\n(*   Springer, 2008                                                           *)\n(*                                                                            *)\n(* This file defines for each structure (SemiRing, Dioid, etc...) its type,   *)\n(* its packers and its canonical properties:                                  *)\n(*                                                                            *)\n(*   * SemiRing (non commutative semi-rings):                                 *)\n(*         SemiRing.type == interface type for semi-ring structure            *)\n(* SemiRing_of_WrapChoice.Build T addA addC add0l mulA mul1l mul1r mulDl      *)\n(*     mulDr mul0l mul0r == builds a SemiRing structure from the algebraic    *)\n(*                          properties of its operations.                     *)\n(*                          The carrier type T must have a WrapChoice         *)\n(*                          canonical structure (see HB_wrappers.v).          *)\n(*                     0 == the zero element (aditive identity)               *)\n(*                     1 == the unit element (multiplicative identity)        *)\n(*                 x + y == the addition of x and y in a semiRing             *)\n(*                 x * y == the multiplication of x and y in a semiRing       *)\n(*         addd_closed S <-> collective predicate S is closed under           *)\n(*                          finite sums (0 and x + y in S, for x, y in S)     *)\n(*         muld_closed S <-> collective predicate S is closed under finite    *)\n(*                          multiplication (0 and x * y in S, for x, y in S)  *)\n(*     semiring_closed S <-> collective predicate S is closed under finite    *)\n(*                          addition and multiplication. This property        *)\n(*                          coerces to addd_closed and muld_closed.           *)\n(*          AddPred addS == packs addS : addd_closed S into an addPred S      *)\n(*                          interface structure associating this property to  *)\n(*                          the canonical pred_key S, i.e the k for wich S    *)\n(*                          has a Canonical keyed_pred k structure.           *)\n(*                          (see file ssrbool.v)                              *)\n(*          MulPred mulS == packs mulS : muld_closed S into a mulPred S       *)\n(*                          interface structure associating this property to  *)\n(*                          the canonical pred_key S                          *)\n(*     SemiRingPred mulS == packs mulS : muld_closed S into a semiringPred S  *)\n(*                          interface structure associating the               *)\n(*                          semiring_closed property to the canonical         *)\n(*                          pred_key S (see above), wich must already be an   *)\n(*                          AddPred.                                          *)\n(* [SemiRing of U by <:] == semiRingType mixin for a subType whose base type  *)\n(*                          is a semiRingType and whose predicate's canonical *)\n(*                          pred_key is a semiRingPred.                       *)\n(*                                                                            *)\n(*   * ComSemiRing (multiplication is commutative):                           *)\n(*      ComSemiRing.type == interface type for commutative semi ring          *)\n(*                          structure                                         *)\n(* ComSemiRing_of_SemiRing.Build R mulC                                       *)\n(*                       == packs mulC into a comSemiRing; the carrier type R *)\n(*                          must have a SemiRing canonical structure.         *)\n(* ComSemiRing_of_WrapChoice.Build T addA addC add0l mulA mulC mul1l mulDl    *)\n(*                 mul0l == builds a ComSemiRing structure using the          *)\n(*                          commutativity to reduce the number of proof       *)\n(*                          obligations.                                      *)\n(*                          The carrier type T must have a WrapChoice         *)\n(*                          canonical structure (see HB_wrappers.v).          *)\n(* [ComSemiRing of R by <:] == commutativity mixin axiom for R when it is a   *)\n(*                          subType of a commutative semi-ring.               *)\n(*                                                                            *)\n(*   * Dioid (idempotent semi-rings):                                         *)\n(*            Dioid.type == interface type for dioid structure.               *)\n(* Dioid_of_SemiRing_and_WrapPOrder.build D addxx le_def                      *)\n(*                       == packs addxx into a Dioid; the carrier type R must *)\n(*                          have both a SemiRing and a WrapPOrder canonical   *)\n(*                          structure.                                        *)\n(* Dioid_of_WrapPOrder.Build D addA addC add0l addxx mulA mul1l mul1r mulDl   *)\n(*   mulDr mul0l mul0r addxx le_def                                           *)\n(*                       == build a Dioid structure from the algebraic        *)\n(*                          properties of its operations.                     *)\n(*                          The carrier type T must have a WrapPOrder         *)\n(*                          canonical structure (see HB_wrappers.v).          *)\n(* Dioid_of_WrapChoice.Build D addA addC add0l addxx mulA mul1l mul1r mulDl   *)\n(*   mulDr mul0l mul0r addxx == build a Dioid structure from the algebraic    *)\n(*                          properties of its operations.                     *)\n(*                          The carrier type T must have a WrapChoice         *)\n(*                          canonical structure (see HB_wrappers.v).          *)\n(*    [Dioid of R by <:] == idempotent mixin axiom for R when it is a         *)\n(*                          subType of a dioid.                               *)\n(*                                                                            *)\n(*   * ComDioid:                                                              *)\n(*         ComDioid.yype == interface type for commutative dioid structure    *)\n(* ComDioid_of_Dioid.Build D mulC == packs mulC into a ComDioidType; the      *)\n(*                          carrier type D must have a Dioid canonical        *)\n(*                          structure.                                        *)\n(* ComDioid_of_ComSemiRing_and_WrapPOrder.Build D addxx le_def                *)\n(*                       == packs addxx into a ComDioid; the carrier type D   *)\n(*                          must have both a Dioid and a WrapPOrder canonical *)\n(*                          structure.                                        *)\n(* ComDioid_of_WrapPOrder.Build D addA addC add0l addxx mulA mulC mul1l mulDl *)\n(*          mul0l le_def == builds a ComDioid structure using the             *)\n(*                          commutativity to reduce the number of proof       *)\n(*                          obligations.                                      *)\n(*                          The carrier type T must have a WrapPOrder         *)\n(*                          canonical structure (see HB_wrappers.v).          *)\n(* ComDioid_of_WrapChoice.Build D addA addC add0l addxx mulA mulC mul1l mulDl *)\n(*                 mul0l == builds a ComDioid structure using the             *)\n(*                          commutativity to reduce the number of proof       *)\n(*                          obligations.                                      *)\n(*                          The carrier type T must have a WrapChoice         *)\n(*                          canonical structure (see HB_wrappers.v).          *)\n(* [ComDioid of D by <:] == commutativity mixin axiom for S when it is a      *)\n(*                          subType of a commutative dioid.                   *)\n(*                                                                            *)\n(* --> After declaring an instance of (Com)Dioid on T using                   *)\n(*     (Com)Dioid_of_WrapChoice.Build the new porderType instance must be     *)\n(*     made canonical by hand:                                                *)\n(*     <<                                                                     *)\n(*     Canonical T_porderType := [porderType of T for T_is_a_WrapPOrder].     *)\n(*     >>                                                                     *)\n(*   Notations are defined in scope dioid_scope (delimiter %D).               *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDeclare Scope dioid_scope.\nDelimit Scope dioid_scope with D.\nLocal Open Scope dioid_scope.\n\nImport Order.Theory.\n\nHB.mixin Record SemiRing_of_WrapChoice R of WrapChoice R := {\n  zero : R;\n  one : R;\n  add : R -> R -> R;\n  mul : R -> R -> R;\n  adddA : associative add;\n  adddC : commutative add;\n  add0d : left_id zero add;\n  muldA : associative mul;\n  mul1d : left_id one mul;\n  muld1 : right_id one mul;\n  muldDl : left_distributive mul add;\n  muldDr : right_distributive mul add;\n  mul0d : left_zero zero mul;\n  muld0 : right_zero zero mul;\n}.\n\nHB.structure Definition SemiRing :=\n  { R of WrapChoice R & SemiRing_of_WrapChoice R }.\n\nCoercion SemiRing_to_Equality (T : SemiRing.type) :=\n  Eval hnf in [eqType of T for T].\nCanonical SemiRing_to_Equality.\nCoercion SemiRing_to_Choice (T : SemiRing.type) :=\n  Eval hnf in [choiceType of T for T].\nCanonical SemiRing_to_Choice.\n\nSection SemiRingTheory.\n\nVariables R : SemiRing.type.\n\nLemma addd0 : right_id (@zero R) add.\nProof. by move=> x; rewrite adddC add0d. Qed.\n\nCanonical add_monoid := Monoid.Law adddA add0d addd0.\nCanonical add_comoid := Monoid.ComLaw adddC.\nCanonical mul_monoid := @Monoid.Law R _ _ muldA mul1d muld1.\nCanonical muloid := @Monoid.MulLaw R _ _ mul0d muld0.\nCanonical addoid := Monoid.AddLaw muldDl muldDr.\n\nLocal Notation \"0\" := zero : dioid_scope.\nLocal Notation \"1\" := one : dioid_scope.\nLocal Notation \"+%D\" := (@add _) : dioid_scope.\nLocal Infix \"+\" := (@add _) : dioid_scope.\nLocal Infix \"*\" := (@mul _) : dioid_scope.\n\nLemma adddAC : right_commutative (S := R) +%D.\nProof. by move=> x y z; rewrite -adddA (adddC y) adddA. Qed.\n\nLemma adddCA : left_commutative (S := R) +%D.\nProof. by move=> x y z; rewrite adddC -adddA (adddC x). Qed.\n\nLemma adddACA : interchange (S := R) +%D +%D.\nProof. by move=> a b c d; rewrite adddAC adddA -adddA (adddC d). Qed.\n\nSection ClosedPredicates.\n\nVariable S : predPredType R.\n\nDefinition addd_closed := 0 \\in S /\\ {in S &, forall u v, u + v \\in S}.\nDefinition muld_closed := 1 \\in S /\\ {in S &, forall u v, u * v \\in S}.\nDefinition semiring_closed := addd_closed /\\ muld_closed.\n\nLemma semiring_closedA : semiring_closed -> addd_closed.\nProof. by case. Qed.\nLemma semiring_closedM : semiring_closed -> muld_closed.\nProof. by case. Qed.\n\nEnd ClosedPredicates.\n\nEnd SemiRingTheory.\n\nHB.mixin Record ComSemiRing_of_SemiRing R of SemiRing R := {\n  muldC : @commutative R _ mul;\n}.\n\nHB.structure Definition ComSemiRing :=\n  { R of ComSemiRing_of_SemiRing R & SemiRing R }.\n\nHB.factory Record ComSemiRing_of_WrapChoice R of WrapChoice R := {\n  zero : R;\n  one : R;\n  add : R -> R -> R;\n  mul : R -> R -> R;\n  adddA : associative add;\n  adddC : commutative add;\n  add0d : left_id zero add;\n  muldA : associative mul;\n  muldC : commutative mul;\n  mul1d : left_id one mul;\n  muldDl : left_distributive mul add;\n  mul0d : left_zero zero mul;\n}.\n\nHB.builders Context R (f : ComSemiRing_of_WrapChoice R).\n\n  Lemma muld1 : right_id one mul.\n  Proof. by move=> x; rewrite muldC mul1d. Qed.\n\n  Lemma muldDr : right_distributive mul add.\n  Proof. by move=> x y z; rewrite muldC muldDl !(muldC x). Qed.\n\n  Lemma muld0 : right_zero zero mul.\n  Proof. by move=> x; rewrite muldC mul0d. Qed.\n\n  HB.instance Definition to_SemiRing_of_WrapChoice :=\n    SemiRing_of_WrapChoice.Build\n      R adddA adddC add0d\n      muldA mul1d muld1 muldDl muldDr mul0d muld0.\n\n  HB.instance Definition to_ComSemiRing_of_SemiRing :=\n    ComSemiRing_of_SemiRing.Build R muldC.\n\nHB.end.\n\nCoercion ComSemiRing_to_Equality (T : ComSemiRing.type) :=\n  Eval hnf in [eqType of T for T].\nCanonical ComSemiRing_to_Equality.\nCoercion ComSemiRing_to_Choice (T : ComSemiRing.type) :=\n  Eval hnf in [choiceType of T for T].\nCanonical ComSemiRing_to_Choice.\n\nSection ComSemiRingTheory.\n\nVariables R : ComSemiRing.type.\n\nLocal Notation \"*%D\" := (@mul _) : dioid_scope.\nLocal Infix \"*\" := (@mul _) : dioid_scope.\n\nLemma muldAC : right_commutative (S := R) *%D.\nProof. by move=> x y z; rewrite -muldA (muldC y) muldA. Qed.\n\nLemma muldCA : left_commutative (S := R) *%D.\nProof. by move=> x y z; rewrite muldC -muldA (muldC x). Qed.\n\nLemma muldACA : interchange (S := R) *%D *%D.\nProof. by move=> a b c d; rewrite muldAC muldA -muldA (muldC d). Qed.\n\nEnd ComSemiRingTheory.\n\nHB.mixin Record Dioid_of_SemiRing_and_WrapPOrder D\n         of SemiRing D & WrapPOrder D := {\n  adddd : @idempotent D add;\n  le_def : forall (a b : D),\n      (Order.POrder.le wrap_porderMixin a b)\n      = (Equality.op wrap_eqMixin (add a b) b);\n}.\n\nHB.structure Definition Dioid :=\n  { D of Dioid_of_SemiRing_and_WrapPOrder D & SemiRing D & WrapPOrder D }.\n\nHB.factory Record Dioid_of_WrapPOrder D of WrapPOrder D := {\n  zero : D;\n  one : D;\n  add : D -> D -> D;\n  mul : D -> D -> D;\n  adddA : associative add;\n  adddC : commutative add;\n  add0d : left_id zero add;\n  adddd : idempotent add;\n  muldA : associative mul;\n  mul1d : left_id one mul;\n  muld1 : right_id one mul;\n  muldDl : left_distributive mul add;\n  muldDr : right_distributive mul add;\n  mul0d : left_zero zero mul;\n  muld0 : right_zero zero mul;\n  le_def : forall (a b : D),\n      (Order.POrder.le wrap_porderMixin a b)\n      = (Equality.op wrap_eqMixin (add a b) b);\n}.\n\nHB.builders Context D (f : Dioid_of_WrapPOrder D).\n\n  HB.instance Definition to_SemiRing_of_WrapChoice :=\n    SemiRing_of_WrapChoice.Build\n      D adddA adddC add0d\n      muldA mul1d muld1 muldDl muldDr mul0d muld0.\n\n  HB.instance Definition to_Dioid_of_SemiRing_and_WrapPOrder :=\n    Dioid_of_SemiRing_and_WrapPOrder.Build D adddd le_def.\n\nHB.end.\n\nHB.factory Record Dioid_of_WrapChoice D of WrapChoice D := {\n  zero : D;\n  one : D;\n  add : D -> D -> D;\n  mul : D -> D -> D;\n  adddA : associative add;\n  adddC : commutative add;\n  add0d : left_id zero add;\n  adddd : idempotent add;\n  muldA : associative mul;\n  mul1d : left_id one mul;\n  muld1 : right_id one mul;\n  muldDl : left_distributive mul add;\n  muldDr : right_distributive mul add;\n  mul0d : left_zero zero mul;\n  muld0 : right_zero zero mul;\n}.\n\nHB.builders Context D (f : Dioid_of_WrapChoice D).\n\n  HB.instance Definition to_SemiRing_of_WrapChoice :=\n    SemiRing_of_WrapChoice.Build\n      D adddA adddC add0d\n      muldA mul1d muld1 muldDl muldDr mul0d muld0.\n\n  Canonical D_is_a_eqType := [eqType of D for D_is_a_WrapChoice].\n\n  Definition le_dioid a b := add a b == b.\n\n  Definition lt_dioid a b := (b != a) && le_dioid a b.\n\n  Lemma lt_def_dioid a b : lt_dioid a b = (b != a) && le_dioid a b.\n  Proof. by []. Qed.\n\n  Lemma le_refl_dioid : reflexive le_dioid.\n  Proof. by move=> a; rewrite /le_dioid adddd. Qed.\n\n  Lemma le_anti_dioid : antisymmetric le_dioid.\n  Proof.\n  by move=> a b /andP[]; rewrite /le => /eqP ? /eqP; rewrite adddC => <-.\n  Qed.\n\n  Lemma le_trans_dioid : transitive le_dioid.\n  Proof.\n  move=> a b c; rewrite /le_dioid => /eqP H /eqP <-.\n  by rewrite -[in X in _ == X]H adddA.\n  Qed.\n\n  Definition dioid_porderMixin :=\n    LePOrderMixin lt_def_dioid le_refl_dioid le_anti_dioid le_trans_dioid.\n\n  HB.instance Definition to_WrapPOrder_of_WrapChoice :=\n    WrapPOrder_of_WrapChoice.Build D dioid_porderMixin.\n\n  Lemma le_def (a b : D) :\n    Order.POrder.le wrap_porderMixin a b =\n    Equality.op wrap_eqMixin (SemiRing.Exports.add a b) b.\n  Proof. by []. Qed.\n\n  HB.instance Definition to_Dioid_of_SemiRing_and_WrapPOrder :=\n    Dioid_of_SemiRing_and_WrapPOrder.Build D adddd le_def.\n\nHB.end.\n\nCoercion Dioid_to_Equality (T : Dioid.type) :=\n  Eval hnf in [eqType of T for T].\nCanonical Dioid_to_Equality.\nCoercion Dioid_to_Choice (T : Dioid.type) :=\n  Eval hnf in [choiceType of T for T].\nCanonical Dioid_to_Choice.\nCoercion Dioid_to_POrder (T : Dioid.type) :=\n  Eval hnf in [porderType of T for T].\nCanonical Dioid_to_POrder.\n\nSection DioidTheory.\n\nVariables D : Dioid.type.\n\nImplicit Type a b c : D.\n\nLocal Notation \"0\" := zero : dioid_scope.\nLocal Notation \"1\" := one : dioid_scope.\nLocal Notation \"+%D\" := (@add _) : dioid_scope.\nLocal Notation \"*%D\" := (@mul _) : dioid_scope.\nLocal Infix \"+\" := (@add _) : dioid_scope.\nLocal Infix \"*\" := (@mul _) : dioid_scope.\nLocal Infix \"<=\" := (@Order.le _ _) : dioid_scope.\nLocal Notation \"a <= b :> T\" := ((a : T) <= (b : T)) (only parsing) : dioid_scope.\n\nLemma le_def a b : (a <= b) = (a + b == b).\nProof. by rewrite /Order.le le_def. Qed.\n\nLemma le0d a : 0 <= a :> D.\nProof. by rewrite le_def add0d. Qed.\n\nLemma led_add2r c : {homo +%D^~ c : a b / a <= b }.\nProof.\nmove => a b; rewrite !le_def => /eqP H.\nby rewrite adddCA -adddA adddd adddA (adddC b) H.\nQed.\n\nLemma led_add2l c : {homo +%D c : a b / a <= b }.\nProof. move=> a b; rewrite !(adddC c); exact: led_add2r. Qed.\n\nLemma led_add a b c d : a <= c -> b <= d -> a + b <= c + d.\nProof. move=> Hac Hbd; exact/(le_trans (led_add2r _ Hac)) /led_add2l. Qed.\n\nLemma led_addl a b : a <= b + a.\nProof. by rewrite le_def adddCA adddd. Qed.\n\nLemma led_addr a b : a <= a + b.\nProof. by rewrite le_def adddA adddd. Qed.\n\nLemma led_add_eqv a b c :  (b + c <= a) = ((b <= a) && (c <= a)).\nProof.\napply/idP/idP => [Ha | /andP[]].\n- apply/andP; split.\n  + exact/(le_trans _ Ha) /led_addr.\n  + exact/(le_trans _ Ha) /led_addl.\n- rewrite 2!le_def => /eqP <- /eqP <-.\n  by rewrite adddCA adddA led_addr.\nQed.\n\nLemma led_mul2l c : {homo *%D c : a b / a <= b }.\nProof. by move=> a b; rewrite le_def => /eqP <-; rewrite muldDr led_addr. Qed.\n\nLemma led_mul2r c : {homo *%D^~ c : a b / a <= b }.\nProof. by move=> a b; rewrite le_def => /eqP <-; rewrite muldDl led_addr. Qed.\n\nLemma led_mul a b c d : a <= c -> b <= d -> a * b <= c * d.\nProof. move=> Hac Hbd; exact/(le_trans (led_mul2r _ Hac)) /led_mul2l. Qed.\n\nEnd DioidTheory.\n\nHB.structure Definition ComDioid :=\n  { D of ComSemiRing_of_SemiRing D & Dioid D }.\n\nHB.factory Record ComDioid_of_WrapPOrder D of WrapPOrder D := {\n  zero : D;\n  one : D;\n  add : D -> D -> D;\n  mul : D -> D -> D;\n  adddA : associative add;\n  adddC : commutative add;\n  add0d : left_id zero add;\n  adddd : idempotent add;\n  muldA : associative mul;\n  muldC : commutative mul;\n  mul1d : left_id one mul;\n  muldDl : left_distributive mul add;\n  mul0d : left_zero zero mul;\n  le_def : forall (a b : D),\n      (Order.POrder.le wrap_porderMixin a b)\n      = (Equality.op wrap_eqMixin (add a b) b);\n}.\n\nHB.builders Context D (f : ComDioid_of_WrapPOrder D).\n\n  Lemma muld1 : right_id one mul.\n  Proof. by move=> x; rewrite muldC mul1d. Qed.\n\n  Lemma muldDr : right_distributive mul add.\n  Proof.\n  Proof. by move=> x y z; rewrite muldC muldDl !(muldC x). Qed.\n\n  Lemma muld0 : right_zero zero mul.\n  Proof. by move=> x; rewrite muldC mul0d. Qed.\n\n  HB.instance Definition to_Dioid_of_WrapPOrder :=\n    Dioid_of_WrapPOrder.Build\n      D adddA adddC add0d adddd\n      muldA mul1d muld1 muldDl muldDr mul0d muld0 le_def.\n\n  HB.instance Definition to_ComDioid_of_Dioid :=\n    ComSemiRing_of_SemiRing.Build D muldC.\n\nHB.end.\n\nHB.factory Record ComDioid_of_WrapChoice D of WrapChoice D := {\n  zero : D;\n  one : D;\n  add : D -> D -> D;\n  mul : D -> D -> D;\n  adddA : associative add;\n  adddC : commutative add;\n  add0d : left_id zero add;\n  adddd : idempotent add;\n  muldA : associative mul;\n  muldC : commutative mul;\n  mul1d : left_id one mul;\n  muldDl : left_distributive mul add;\n  mul0d : left_zero zero mul;\n}.\n\nHB.builders Context D (f : ComDioid_of_WrapChoice D).\n\n  Lemma muld1 : right_id one mul.\n  Proof. by move=> x; rewrite muldC mul1d. Qed.\n\n  Lemma muldDr : right_distributive mul add.\n  Proof.\n  Proof. by move=> x y z; rewrite muldC muldDl !(muldC x). Qed.\n\n  Lemma muld0 : right_zero zero mul.\n  Proof. by move=> x; rewrite muldC mul0d. Qed.\n\n  HB.instance Definition to_Dioid_of_WrapChoice :=\n    Dioid_of_WrapChoice.Build\n      D adddA adddC add0d adddd\n      muldA mul1d muld1 muldDl muldDr mul0d muld0.\n\n  HB.instance Definition to_ComDioid_of_Dioid :=\n    ComSemiRing_of_SemiRing.Build D muldC.\n\nHB.end.\n\nCoercion ComDioid_to_Equality (T : ComDioid.type) :=\n  Eval hnf in [eqType of T for T].\nCanonical ComDioid_to_Equality.\nCoercion ComDioid_to_Choice (T : ComDioid.type) :=\n  Eval hnf in [choiceType of T for T].\nCanonical ComDioid_to_Choice.\nCoercion ComDioid_to_POrder (T : ComDioid.type) :=\n  Eval hnf in [porderType of T for T].\nCanonical ComDioid_to_POrder.\n\n(* Interface structures for algebraically closed predicates. *)\nModule Pred.\n\nStructure add V S := Add {add_key : pred_key S; _ : @addd_closed V S}.\nStructure mul R S := Mul {mul_key : pred_key S; _ : @muld_closed R S}.\nStructure semiring R S :=\n  SemiRing {semiring_add : add S; _ : @muld_closed R S}.\n\nSection Subtyping.\n\nFact semiring_mulr R S : @semiring R S -> muld_closed S.\nProof. by case. Qed.\n\nDefinition semiring_mul R S (ringS : @semiring R S) :=\n  Mul (add_key (semiring_add ringS)) (semiring_mulr ringS).\n\nEnd Subtyping.\n\nSection Extensionality.\n(* This could be avoided by exploiting the Coq 8.4 eta-convertibility.        *)\n\nLemma add_ext (U : SemiRing.type) S k (kS : @keyed_pred U S k) :\n  addd_closed kS -> addd_closed S.\nProof.\nby case=> S0 addS; split=> [|x y]; rewrite -!(keyed_predE kS) //; apply: addS.\nQed.\n\nLemma mul_ext (R : SemiRing.type) S k (kS : @keyed_pred R S k) :\n  muld_closed kS -> muld_closed S.\nProof.\nby case=> S1 mulS; split=> [|x y]; rewrite -!(keyed_predE kS) //; apply: mulS.\nQed.\n\nEnd Extensionality.\n\nModule Exports.\n\nNotation addd_closed := addd_closed.\nNotation muld_closed := muld_closed.\nNotation semiring_closed := semiring_closed.\n\nCoercion semiring_closedA : semiring_closed >-> addd_closed.\nCoercion semiring_closedM : semiring_closed >-> muld_closed.\nCoercion add_key : add >-> pred_key.\nCoercion mul_key : mul >-> pred_key.\nCoercion semiring_add : semiring >-> add.\nCoercion semiring_mul : semiring >-> mul.\nCanonical semiring_mul.\n\nNotation addPred := add.\nNotation mulPred := mul.\nNotation semiringPred := semiring.\n\nDefinition AddPred U S k kS DkS := Add k (@add_ext U S k kS DkS).\nDefinition MulPred R S k kS MkS := Mul k (@mul_ext R S k kS MkS).\nDefinition SemiRingPred R S k kS MkS := SemiRing k (@mul_ext R S k kS MkS).\n\nEnd Exports.\n\nEnd Pred.\nImport Pred.Exports.\n\nSection SemiRingPred.\n\nVariables (V : SemiRing.type) (S : predPredType V).\n\nSection Add.\n\nVariables (addS : addPred S) (kS : keyed_pred addS).\n\nLemma rpred0D : addd_closed kS.\nProof. split=> [|x y]; rewrite !keyed_predE; case: addS=> _ [_]//; exact. Qed.\n\nLemma rpred0 : (@zero V) \\in kS.\nProof. by case: rpred0D. Qed.\n\nLemma rpredD : {in kS &, forall u v, (@add V u v) \\in kS}.\nProof. by case: rpred0D. Qed.\n\nEnd Add.\n\nSection Mul.\n\nVariables (mulS : mulPred S) (kS : keyed_pred mulS).\n\nLemma rpred1M : muld_closed kS.\nProof.\nsplit=> [ | x y]; rewrite !keyed_predE; case: mulS => _ [_] //; exact.\nQed.\n\nLemma rpred1 : (@one V) \\in kS.\nProof. by case: rpred1M. Qed.\n\nLemma rpredM : {in kS &, forall u v, (@mul V u v) \\in kS}.\nProof. by case: rpred1M. Qed.\n\nEnd Mul.\n\nEnd SemiRingPred.\n\nModule SubType.\n\nSection SemiRing.\n\nVariables (V : SemiRing.type) (S : predPredType V).\nVariables (subS : semiringPred S) (kS : keyed_pred subS).\nVariable U : subType (mem kS).\n\nLet inU v Sv : U := Sub v Sv.\nLet zeroU := inU (rpred0 kS).\nLet oneU := inU (rpred1 kS).\nLet addU (u1 u2 : U) := inU (rpredD (valP u1) (valP u2)).\nLet mulU (u1 u2 : U) := inU (rpredM (valP u1) (valP u2)).\n\nFact adddA : associative addU.\nProof. by move=> a b c; apply: val_inj; rewrite !SubK adddA. Qed.\n\nFact adddC : commutative addU.\nProof. by move=> a b; apply: val_inj; rewrite !SubK adddC. Qed.\n\nFact add0d : left_id zeroU addU.\nProof. by move=> a; apply: val_inj; rewrite !SubK add0d. Qed.\n\nFact muldA : associative mulU.\nProof. by move=> a b c; apply: val_inj; rewrite !SubK muldA. Qed.\n\nFact mul1d : left_id oneU mulU.\nProof. by move=> a; apply: val_inj; rewrite !SubK mul1d. Qed.\n\nFact muld1 : right_id oneU mulU.\nProof. by move=> a; apply: val_inj; rewrite !SubK muld1. Qed.\n\nFact muldDl : @left_distributive U U mulU addU.\nProof. by move=> a b c; apply: val_inj; rewrite !SubK muldDl. Qed.\n\nFact muldDr : right_distributive mulU addU.\nProof. by move=> a b c; apply: val_inj; rewrite !SubK muldDr. Qed.\n\nLemma mul0d : left_zero zeroU mulU.\nProof. by move=> a; apply: val_inj; rewrite !SubK mul0d. Qed.\n\nLemma muld0 : right_zero zeroU mulU.\nProof. by move=> a; apply: val_inj; rewrite !SubK muld0. Qed.\n\nDefinition semiRingMixin of phant U :=\n  SemiRing_of_WrapChoice.Build\n    _ adddA adddC add0d muldA mul1d muld1 muldDl muldDr mul0d muld0.\n\nEnd SemiRing.\n\nLemma comSemiRingMixin (R : ComSemiRing.type) (T : SemiRing.type) (f : T -> R) :\nphant T -> injective f -> {morph f : x y / mul x y} -> commutative (@mul T).\nProof. by move=> _ inj_f fM x y; apply: inj_f; rewrite !fM muldC. Qed.\n\nLemma dioidMixin (R : Dioid.type) (T : SemiRing.type) (f : T -> R) :\nphant T -> injective f -> {morph f : x y / add x y} -> @idempotent T add.\nProof. by move=> _ inj_f fM x; apply: inj_f; rewrite !fM adddd. Qed.\n\nLemma dioidMixin' (R : Dioid.type) (T : SemiRing.type) (f : T -> R)\n  (_ : phant T) (eM : Equality.mixin_of T) (oM : @Order.POrder.mixin_of T eM) :\ninjective f -> {morph f : x y / add x y} ->\n{mono f : x y / Equality.op eM x y >-> x == y} ->\n{mono f : x y / Order.POrder.le oM x y >-> (x <= y)%O} ->\nforall (a b : T), (Order.POrder.le oM a b) = (Equality.op eM (add a b) b).\nProof. by move=> inj_f fM fM' fM'' x y; rewrite -fM'' le_def -fM fM'. Qed.\n\nLemma comDioidMixin (R : ComDioid.type) (T : Dioid.type) (f : T -> R) :\nphant T -> injective f -> {morph f : x y / mul x y} -> commutative (@mul T).\nProof. by move=> _ inj_f fM x y; apply: inj_f; rewrite !fM muldC. Qed.\n\nModule Exports.\n\nNotation \"[ 'SemiRing' 'of' U 'by' <: ]\" := (semiRingMixin (Phant U))\n  (at level 0, format \"[ 'SemiRing' 'of' U 'by' <: ]\") : form_scope.\n\nNotation \"[ 'ComSemiRing' 'of' R 'by' <: ]\" :=\n  (ComSemiRing_of_SemiRing.Build\n     _ (comSemiRingMixin (Phant R) val_inj (rrefl _)))\n  (at level 0, format \"[ 'ComSemiRing' 'of' R 'by' <: ]\") : form_scope.\n\nNotation \"[ 'Dioid' 'of' R 'by' <: ]\" :=\n  (Dioid_of_SemiRing_and_WrapPOrder.Build\n     R%type (dioidMixin (Phant R) val_inj (rrefl _))\n     (@dioidMixin' _ _ _ (Phant R) wrap_eqMixin wrap_porderMixin\n                  val_inj (rrefl _) (rrefl _) (rrefl _)))\n  (at level 0, format \"[ 'Dioid' 'of' R 'by' <: ]\") : form_scope.\n\nNotation \"[ 'ComDioid' 'of' R 'by' <: ]\" :=\n  (ComSemiRing_of_SemiRing.Build _ (comDioidMixin (Phant R) val_inj (rrefl _)))\n  (at level 0, format \"[ 'ComDioid' 'of' R 'by' <: ]\") : form_scope.\n\nEnd Exports.\n\nEnd SubType.\n\nExport Pred.Exports SubType.Exports.\n\nNotation \"0\" := zero : dioid_scope.\nNotation \"1\" := one : dioid_scope.\nNotation \"+%D\" := (@add _) : dioid_scope.\nNotation \"*%D\" := (@mul _) : dioid_scope.\nInfix \"+\" := (@add _) : dioid_scope.\nInfix \"*\" := (@mul _) : dioid_scope.\n\nNotation led := (@Order.le dioid_display _) (only parsing).\nNotation \"@ 'led' R\" :=\n  (@Order.le dioid_display R) (at level 10, R at level 8, only parsing).\nNotation ltd := (@Order.lt dioid_display _) (only parsing).\nNotation \"@ 'ltd' R\" :=\n  (@Order.lt dioid_display R) (at level 10, R at level 8, only parsing).\nNotation ged := (@Order.ge dioid_display _) (only parsing).\nNotation \"@ 'ged' R\" :=\n  (@Order.ge dioid_display R) (at level 10, R at level 8, only parsing).\nNotation gtd := (@Order.gt dioid_display _) (only parsing).\nNotation \"@ 'gtd' R\" :=\n  (@Order.gt dioid_display R) (at level 10, R at level 8, only parsing).\n\nNotation \"<=%D\" := led : dioid_scope.\nNotation \">=%D\" := ged : dioid_scope.\nNotation \"<%D\" := ltd : dioid_scope.\nNotation \">%D\" := gtd : dioid_scope.\n\nNotation \"<= b\" := (ged b) : dioid_scope.\nNotation \"<= b :> T\" := (<= (b : T)) (only parsing) : dioid_scope.\nNotation \">= b\" := (led b) : dioid_scope.\nNotation \">= b :> T\" := (>= (b : T)) (only parsing) : dioid_scope.\n\nNotation \"< b\" := (gtd b) : dioid_scope.\nNotation \"< b :> T\" := (< (b : T)) (only parsing) : dioid_scope.\nNotation \"> b\" := (ltd b) : dioid_scope.\nNotation \"> b :> T\" := (> (b : T)) (only parsing) : dioid_scope.\n\nNotation \"a <= b\" := (led a b) : dioid_scope.\nNotation \"a <= b :> T\" := ((a : T) <= (b : T)) (only parsing) : dioid_scope.\nNotation \"a >= b\" := (b <= a) (only parsing) : dioid_scope.\nNotation \"a >= b :> T\" := ((a : T) >= (b : T)) (only parsing) : dioid_scope.\n\nNotation \"a < b\" := (ltd a b) : dioid_scope.\nNotation \"a < b :> T\" := ((a : T) < (b : T)) (only parsing) : dioid_scope.\nNotation \"a > b\" := (b < a) (only parsing) : dioid_scope.\nNotation \"a > b :> T\" := ((a : T) > (b : T)) (only parsing) : dioid_scope.\n\nNotation \"a <= b <= c\" := ((led a b) && (led b c)) : dioid_scope.\nNotation \"a < b <= c\"  := ((ltd a b) && (led b c)) : dioid_scope.\nNotation \"a <= b < c\"  := ((led a b) && (ltd b c)) : dioid_scope.\nNotation \"a < b < c\"   := ((ltd a b) && (ltd b c)) : dioid_scope.\n", "meta": {"author": "math-comp", "repo": "dioid", "sha": "ec66c1c3990e433ebcb3d9a1989ed0532413ed36", "save_path": "github-repos/coq/math-comp-dioid", "path": "github-repos/coq/math-comp-dioid/dioid-ec66c1c3990e433ebcb3d9a1989ed0532413ed36/dioid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7071481351978472}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nLemma append_assoc: forall l1 l2 l3, \n  append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\ninduction l1.\n  - simpl. intros. rewrite IHl1. reflexivity.\n  - reflexivity.\nQed.\n\nLemma lem3: forall l, append l Nil = l.\nProof.\ninduction l.\n  - simpl. rewrite IHl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (rev (append (rev x) y)) (append (rev y) x).\nProof.\ninduction x.\n  - intros. simpl. rewrite <- append_assoc. rewrite IHx. simpl. \n    rewrite <- append_assoc. simpl. reflexivity.\n  - intros. simpl. rewrite lem3. reflexivity.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7071481291204987}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf3 : natural) (z : natural) (lf2 : natural)\n  : natural := mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj133_coqofml_6LJNXD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990283, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7070932564049304}}
{"text": "Require Export TopologicalSpaces.\nRequire Export Neighborhoods.\nFrom ZornsLemma Require Export InverseImage.\nRequire Export OpenBases.\nRequire Export NeighborhoodBases.\nRequire Export Subbases.\n\nSection continuity.\n\nVariable X Y:TopologicalSpace.\nVariable f:X -> Y.\n\nDefinition continuous : Prop :=\n  forall V:Ensemble Y, open V ->\n  open (inverse_image f V).\n\nDefinition continuous_at (x:X) : Prop :=\n  forall V:Ensemble Y,\n  neighborhood V (f x) -> neighborhood (inverse_image f V) x.\n\nLemma continuous_at_open_neighborhoods:\n  forall x:X,\n  (forall V:Ensemble Y,\n  open_neighborhood V (f x) -> neighborhood (inverse_image f V) x) ->\n  continuous_at x.\nProof.\nintros.\nred; intros.\ndestruct H0 as [V' [? ?]].\npose proof (H V' H0).\ndestruct H2 as [U' [? ?]].\nexists U'; split; trivial.\napply (inverse_image_increasing f) in H1; auto with sets.\nQed.\n\nLemma pointwise_continuity :\n  (forall x:point_set X, continuous_at x) -> continuous.\nProof.\nintros.\nred; intros.\nreplace (inverse_image f V) with (interior (inverse_image f V)).\n{ apply interior_open. }\napply Extensionality_Ensembles; split.\n{ apply interior_deflationary. }\nred; intros.\ndestruct H1.\nassert (neighborhood V (f x)).\n{ exists V; repeat split; auto with sets. }\npose proof (H x V H2).\ndestruct H3 as [U].\ndestruct H3.\ndestruct H3.\nassert (Included U (interior (inverse_image f V))).\n{ apply interior_maximal; trivial. }\nauto.\nQed.\n\nLemma continuous_func_continuous_everywhere:\n  continuous -> forall x:point_set X, continuous_at x.\nProof.\nintros.\napply continuous_at_open_neighborhoods.\nintros.\napply open_neighborhood_is_neighborhood.\ndestruct H0; split; try constructor; auto.\nQed.\n\nLemma continuous_at_neighborhood_basis:\n  forall (x:X) (NB:Family Y),\n  neighborhood_basis NB (f x) ->\n  (forall V:Ensemble Y,\n  In NB V -> neighborhood (inverse_image f V) x) ->\n  continuous_at x.\nProof.\nintros.\nred; intros.\ndestruct H.\napply neighborhood_basis_cond in H1.\ndestruct H1 as [N [? ?]].\npose proof (H0 N H).\ndestruct H2 as [U [? ?]].\nexists U; split; trivial.\nassert (Included (inverse_image f N) (inverse_image f V));\n  auto with sets.\nQed.\n\nLemma continuous_open_basis:\n  forall (B:Family Y), open_basis B ->\n  (forall V:Ensemble Y,\n    In B V -> open (inverse_image f V)) -> continuous.\nProof.\nintros.\napply pointwise_continuity.\nintro.\npose proof (open_basis_to_open_neighborhood_basis B (f x) H).\napply open_neighborhood_basis_is_neighborhood_basis in H1.\napply (continuous_at_neighborhood_basis _ _ H1).\nintros.\ndestruct H2 as [[? ?]].\napply open_neighborhood_is_neighborhood.\nsplit; try constructor; auto.\nQed.\n\nLemma continuous_subbasis:\n  forall (SB:Family Y), subbasis SB ->\n  (forall V:Ensemble Y,\n     In SB V -> open (inverse_image f V)) -> continuous.\nProof.\nintros.\napply (continuous_open_basis _\n  (finite_intersections_of_subbasis_form_open_basis _ _ H)).\nintros.\ndestruct H1.\ndestruct H1 as [A [? [V' []]]].\nrewrite H3.\nrewrite inverse_image_indexed_intersection.\napply open_finite_indexed_intersection; trivial.\nintros.\napply H0.\napply H2.\nQed.\n\nLemma continuous_closed :\n  continuous <-> forall U, closed U -> closed (inverse_image f U).\nProof.\n  split.\n  - intros. red.\n    rewrite <- inverse_image_complement.\n    apply H. assumption.\n  - intros.\n    red. intros.\n    apply closed_complement_open.\n    rewrite <- inverse_image_complement.\n    apply H. red. rewrite Complement_Complement.\n    assumption.\nQed.\n\nLemma continuous_interior :\n  continuous <->\n  forall A, Included (inverse_image f (interior A))\n                (interior (inverse_image f A)).\nProof.\nsplit.\n- intros. red; intros.\n  assert (open (inverse_image f (interior A))).\n  { apply H. apply interior_open. }\n  apply (interior_maximal _ _ H1).\n  + intros ? ?.\n    destruct H2. constructor.\n    apply interior_deflationary. assumption.\n  + assumption.\n- intros. red; intros.\n  specialize (H V).\n  rewrite interior_fixes_open in H; auto.\n  assert (inverse_image f V = interior (inverse_image f V)).\n  { apply Extensionality_Ensembles. split.\n    - assumption.\n    - apply interior_deflationary.\n  }\n  rewrite H1.\n  apply interior_open.\nQed.\n\nLemma continuous_closure :\n  continuous <->\n  (forall A, Included (Im (closure A) f)\n                 (closure (Im A f))).\nProof.\nrewrite continuous_closed.\nsplit.\n- intros.\n  remember (inverse_image f (closure (Im A f))) as B.\n  assert (closed B).\n  { subst B. apply H. apply closure_closed. }\n  assert (Included (closure A) B).\n  { subst B. apply closure_minimal; auto.\n    intros ? ?.\n    constructor. apply closure_inflationary.\n    exists x; auto.\n  }\n  intros ? ?.\n  destruct H2; subst.\n  apply H1 in H2.\n  destruct H2.\n  assumption.\n- intros.\n  assert (inverse_image f U = closure (inverse_image f U)).\n  2: { rewrite H1. apply closure_closed. }\n  apply Extensionality_Ensembles; split.\n  { apply closure_inflationary. }\n  specialize (H (inverse_image f U)).\n  assert (Included (Im (closure (inverse_image f U)) f) U).\n  + apply (Inclusion_is_transitive _ _ (closure (Im (inverse_image f U) f)));\n      auto.\n    apply closure_fixes_closed in H0.\n    rewrite <- H0 at 2.\n    apply closure_increasing.\n    apply image_inverse_image_included.\n  + apply (inverse_image_increasing f) in H1.\n    apply (Inclusion_is_transitive\n             _ _ (inverse_image f (Im (closure (inverse_image f U)) f)));\n      auto.\n    apply inverse_image_image_included.\nQed.\n\nEnd continuity.\n\nArguments continuous {X} {Y}.\nArguments continuous_at {X} {Y}.\n\nLemma continuous_composition_at: forall {X Y Z:TopologicalSpace}\n  (f:Y -> Z) (g:X -> Y)\n  (x:X),\n  continuous_at f (g x) -> continuous_at g x ->\n  continuous_at (fun x:X => f (g x)) x.\nProof.\nintros.\nred; intros.\nrewrite inverse_image_composition.\nauto.\nQed.\n\nLemma continuous_composition: forall {X Y Z:TopologicalSpace}\n  (f:Y -> Z) (g:X -> Y),\n  continuous f -> continuous g ->\n  continuous (fun x:X => f (g x)).\nProof.\nintros.\nred; intros.\nrewrite inverse_image_composition.\nauto.\nQed.\n\nLemma continuous_identity: forall (X:TopologicalSpace),\n  continuous (fun x:X => x).\nProof.\nintros.\nred; intros.\nrewrite inverse_image_id.\nassumption.\nQed.\n\nLemma continuous_constant: forall (X Y:TopologicalSpace)\n  (y0:Y), continuous (fun x:X => y0).\nProof.\nintros.\npose (f := fun _:X => y0).\nfold f.\nred; intros.\ndestruct (classic (In V y0)).\n- replace (inverse_image f V) with (@Full_set X).\n  { apply open_full. }\n  apply Extensionality_Ensembles; split; red; intros.\n  + constructor; trivial.\n  + constructor.\n- replace (inverse_image f V) with (@Empty_set X).\n  { apply open_empty. }\n  apply Extensionality_Ensembles; split; auto with sets;\n    red; intros.\n  destruct H1.\n  contradiction H0.\nQed.\n\nLemma continuous_at_is_local: forall (X Y:TopologicalSpace)\n  (x0:X) (f g:X -> Y)\n  (N:Ensemble X),\n  neighborhood N x0 -> (forall x:point_set X, In N x -> f x = g x) ->\n  continuous_at f x0 -> continuous_at g x0.\nProof.\nintros.\nred; intros.\ndestruct H as [U1 [[]]].\nrewrite <- H0 in H2.\n2: { auto. }\napply H1 in H2.\ndestruct H2 as [U2 [[]]].\nexists (Intersection U1 U2).\nrepeat split; trivial.\n- apply open_intersection2; trivial.\n- destruct H7.\n  rewrite <- H0.\n  + apply H6 in H8.\n    destruct H8; trivial.\n  + auto.\nQed.\n\nLemma dense_image_surjective {X Y : TopologicalSpace} {f : X -> point_set Y}\n  (S : Ensemble X) :\n  continuous f ->\n  surjective f ->\n  dense S ->\n  dense (Im S f).\nProof.\nintros.\napply Extensionality_Ensembles.\nsplit; red; intros; constructor.\nintros U [[? H4]].\ndestruct (H0 x) as [x0 H5].\nassert (In (closure S) x0) as H6 by now rewrite H1.\ndestruct H6.\nrewrite <- H5.\napply in_inverse_image, H6.\nrepeat split.\n- red.\n  rewrite <- inverse_image_complement.\n  auto.\n- apply H4.\n  now econstructor; trivial.\nQed.\n\n(* This fact is trivial, given function-extensionality. But in the usual\n  \"setoid-hell\" and \"constructive math\" sense, it can be useful instead of\n  doing rewrites. *)\nLemma continuous_funext {X Y : TopologicalSpace} (f g : X -> Y) :\n  (forall x, f x = g x) ->\n  continuous f -> continuous g.\nProof.\n  intros Hfg Hf U HU.\n  replace (inverse_image g U) with (inverse_image f U);\n    auto.\n  extensionality_ensembles; constructor;\n    rewrite Hfg in *; assumption.\nQed.\n", "meta": {"author": "coq-community", "repo": "topology", "sha": "f784257d0b9c316601440e4f02256bd6068e4f94", "save_path": "github-repos/coq/coq-community-topology", "path": "github-repos/coq/coq-community-topology/topology-f784257d0b9c316601440e4f02256bd6068e4f94/theories/Topology/Continuity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7070932520925087}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_3_6a.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_betweennotequal : \n   forall A B C, \n   BetS A B C ->\n   neq B C /\\ neq A B /\\ neq A C.\nProof.\nintros.\nassert (~ eq B C).\n {\n intro.\n assert (BetS A C B) by (conclude cn_equalitysub).\n assert (BetS B C B) by (conclude lemma_3_6a).\n assert (~ BetS B C B) by (conclude axiom_betweennessidentity).\n contradict.\n }\nassert (~ eq A B).\n {\n intro.\n assert (BetS B A C) by (conclude cn_equalitysub).\n assert (BetS A B A) by (conclude axiom_innertransitivity).\n assert (~ BetS A B A) by (conclude axiom_betweennessidentity).\n contradict.\n }\nassert (~ eq A C).\n {\n intro.\n assert (BetS A B A) by (conclude cn_equalitysub).\n assert (~ BetS A B A) by (conclude axiom_betweennessidentity).\n contradict.\n }\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_betweennotequal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.7070932354053197}}
{"text": "Require Export a_base Bool.\nExport ListNotations.\nSet Implicit Arguments.\n\nModule Type sound_mod (X: base_mod).\nImport X.\n\n\n(** * Definitions \n\ndefinition of Propositional Formulas*)\nInductive PropF : Set :=\n | Var : PropVars -> PropF\n | Bot : PropF\n | Conj : PropF -> PropF -> PropF\n | Disj : PropF -> PropF -> PropF\n | Impl : PropF -> PropF -> PropF\n.\n\nNotation \"# P\" := (Var P) (at level 1) : My_scope.\nNotation \"A ∨ B\" := (Disj A B) (at level 15, right associativity) : My_scope.\nNotation \"A ∧ B\" := (Conj A B) (at level 15, right associativity) : My_scope.\nNotation \"A → B\" := (Impl A B) (at level 16, right associativity) : My_scope.\nNotation \"⊥\" := Bot (at level 0)  : My_scope.\nDefinition Neg A := A → ⊥.\nNotation \"¬ A\" := (Neg A) (at level 5) : My_scope.\nDefinition Top := ¬⊥.\nNotation \"⊤\" := Top (at level 0) : My_scope.\nDefinition BiImpl A B := (A→B)∧(B→A).\nNotation \"A ↔ B\" := (BiImpl A B) (at level 17, right associativity) : My_scope.\n\n(** Validness *)\n\n(** Valuations are maps PropVars -> bool sending ⊥ to false*)\nFixpoint TrueQ v A : bool := match A with\n | # P   => v P\n | ⊥     => false\n | B ∨ C => (TrueQ v B) || (TrueQ v C)\n | B ∧ C => (TrueQ v B) && (TrueQ v C)\n | B → C => (negb (TrueQ v B)) || (TrueQ v C)\nend.\nDefinition Satisfies v Γ := forall A, In A Γ -> Is_true (TrueQ v A).\nDefinition Models Γ A := forall v,Satisfies v Γ->Is_true (TrueQ v A).\nNotation \"Γ ⊨ A\" := (Models Γ A) (at level 80).\nDefinition Valid A := [] ⊨ A.\n\n(** Provability *)\n\nReserved Notation \"Γ ⊢ A\" (at level 80).\nInductive Nc : list PropF-> PropF->Prop :=\n| Nax   : forall Γ A  ,    In A Γ                           -> Γ ⊢ A\n| ImpI  : forall Γ A B,  A::Γ ⊢ B                           -> Γ ⊢ A → B\n| ImpE  : forall Γ A B,     Γ ⊢ A → B -> Γ ⊢ A              -> Γ ⊢ B\n| BotC  : forall Γ A  , ¬A::Γ ⊢ ⊥                              -> Γ ⊢ A\n| AndI  : forall Γ A B,     Γ ⊢ A     -> Γ ⊢ B              -> Γ ⊢ A∧B\n| AndE1 : forall Γ A B,     Γ ⊢ A∧B                        -> Γ ⊢ A\n| AndE2 : forall Γ A B,     Γ ⊢ A∧B                        -> Γ ⊢ B\n| OrI1  : forall Γ A B,     Γ ⊢ A                           -> Γ ⊢ A∨B\n| OrI2  : forall Γ A B,     Γ ⊢ B                           -> Γ ⊢ A∨B\n| OrE   : forall Γ A B C,   Γ ⊢ A∨B -> A::Γ ⊢ C -> B::Γ ⊢ C -> Γ ⊢ C\nwhere \"Γ ⊢ A\" := (Nc Γ A) : My_scope.\n\nDefinition Provable A := [] ⊢ A.\n\n(**The Theorems we are going to prove*)\nDefinition Prop_Soundness := forall A,Provable A->Valid A.\nDefinition Prop_Completeness := forall A,Valid A->Provable A.\n\n(** * Theorems *)\n\nLtac mp := eapply ImpE.\nLtac AddnilL := match goal with \n| |- _ ?Γ _ => change Γ with ([]++Γ)\nend.\nLtac in_solve := intros;repeat \n (eassumption\n||match goal with \n   | H:In _ (_::_) |- _ => destruct H;[subst;try discriminate|]\n   | H:In _ (_++_) |- _ => apply in_app_iff in H as [];subst\n   | |- In _ (_++_) => apply in_app_iff;(left;in_solve;fail)||(right;in_solve;fail) \n  end\n||(once constructor;reflexivity)\n||constructor 2).\nLtac is_ass := once econstructor;in_solve.\n\nLtac case_bool v A := let HA := fresh \"H\" in\n(case_eq (TrueQ v A);intro HA;try rewrite HA in *;simpl in *;try trivial;try contradiction).\n\nLocal Ltac prove_satisfaction :=\nintros ? K;destruct K;[subst;simpl;\nmatch goal with\n| [ H : TrueQ _ _ = _  |-  _ ] => rewrite H\nend;exact I|auto].\n\nLemma PropFeq_dec : forall (x y : PropF), {x = y}+{x <> y}.\ninduction x;destruct y;try (right;discriminate);\n try (destruct (IHx1 y1);[destruct (IHx2 y2);[left;f_equal;assumption|]|];\n  right;injection;intros;contradiction).\n destruct (Varseq_dec p p0).\n   left;f_equal;assumption.\n   right;injection;intro;contradiction.\n left;reflexivity.\nQed.\n\nLemma Excluded_Middle : forall Γ A, Γ ⊢ A∨¬A.\nintros;apply BotC;mp;[is_ass|apply OrI2;apply ImpI;mp;[is_ass|apply OrI1;is_ass]].\nQed.\n\nLemma weakening2 : forall Γ A, Γ ⊢ A -> forall Δ, (forall B, In B Γ -> In B Δ) -> Δ ⊢ A.\ninduction 1;[constructor|constructor 2|econstructor 3|constructor 4|constructor 5|econstructor 6\n|econstructor 7|constructor 8|constructor 9|econstructor 10];try eauto;\n[apply IHNc..|apply IHNc2|try apply IHNc3];intros;in_solve;eauto.\nQed.\n\nLemma weakening : forall Γ Δ A, Γ ⊢ A -> Γ++Δ ⊢ A.\nintros;eapply weakening2;[eassumption|in_solve].\nQed.\n\nLemma deduction : forall Γ A B, Γ ⊢ A → B -> A::Γ ⊢ B.\nintros;eapply ImpE with A;[eapply weakening2;[eassumption|in_solve]|is_ass].\nQed.\n\nLemma prov_impl : forall A B, Provable (A → B)->forall Γ, Γ ⊢ A -> Γ ⊢ B.\nintros. mp. \n  AddnilL;apply weakening. apply H.\n  assumption. \nQed.\n\n(* This tactic applies prov_impl in IH (apply prov_impl in IH doesn't work, because I want to keep the Γ quantified)*)\nLtac prov_impl_in IH := let H := fresh \"K\" in\ntry (remember (prov_impl IH) as H eqn:HeqH;clear IH HeqH).\n\n(** Soundness *)\n\nTheorem Soundness_general : forall A Γ, Γ ⊢ A -> Γ ⊨ A.\nintros A Γ H0 v;induction H0;simpl;intros;auto;\n try simpl in IHNc;try simpl in IHNc1;try simpl in IHNc2;\n  case_bool v A;try (case_bool v B;fail);\n   try (apply IHNc||apply IHNc2;prove_satisfaction);\n    case_bool v B;apply IHNc3;prove_satisfaction.\nQed.\n\nTheorem Soundness : Prop_Soundness.\nintros ? ? ? ?;eapply Soundness_general;eassumption.\nQed.\n\nEnd sound_mod.\n", "meta": {"author": "coq-contribs", "repo": "propcalc", "sha": "b68586c079a71ebab3235a636e50c083b23d4f25", "save_path": "github-repos/coq/coq-contribs-propcalc", "path": "github-repos/coq/coq-contribs-propcalc/propcalc-b68586c079a71ebab3235a636e50c083b23d4f25/b_soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7070191441347453}}
{"text": "(** This module contains a set of basic definitions\n    that will be of use but do not depend upon the  \n    specifics of the problem at hand.               *)\n(** ---- *)\n\n\nRequire Import List Arith.\nRequire Import FSets FSetAVL FSetFacts FSetEqProperties FSetProperties.\n\n(** * Tactics *)\nLtac blast := solve [ auto |  discriminate | contradiction ].\nLtac cauto := try blast.\n\n(** * Sets *)\n\nModule Nat <: OrderedType.\n  Definition t := nat.\n  Definition eq (a b : t) := a=b.\n  Definition lt (a b : t) := a<b.\n\n  Lemma eq_refl : forall x : t, eq x x.\n  Proof.\n    intro; unfold eq; auto.\n  Qed.\n\n  Lemma eq_sym : forall x y : t, eq x y -> eq y x.\n  Proof.\n    intro;unfold eq;auto.\n  Qed.\n\n  Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n  Proof.\n    intros x y z h h';unfold eq in *; rewrite h in *;auto.\n  Qed.\n\n  Definition lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z :=\n    lt_trans.\n\n  Definition lt_not_eq : forall x y : t, lt x y -> ~ eq x y :=\n    NPeano.Nat.lt_neq.\n  \n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    SearchAbout ({ _ } +  { _ } + { _ } ).\n    intros x y; case (lt_eq_lt_dec x y) as [[h|h]|h];\n    [apply LT\n    |apply EQ\n    |apply GT];auto.\n  Qed.\n  Definition eq_dec := eq_nat_dec.\nEnd Nat.\n\nModule NSet := FSetAVL.Make(Nat).\nModule NF := FSetFacts.Facts NSet.\nModule NP := FSetProperties.Properties NSet.\n\nLemma Equal_add : forall x s s', NSet.eq s s' ->\n                                 NSet.eq (NSet.add x s) (NSet.add x s').\nProof.\n  intros x s s' he.\n  apply NP.Add_Equal;simpl; intro y;\n  case (eq_nat_dec x y) as [->|h];split;intro h';\n  [left\n  |apply NSet.add_1\n  |right;apply he;apply NSet.add_3 in h'\n  |case h' as [->|h'];\n    [absurd (y = y)\n    |apply NSet.add_2;apply he]\n  ]; auto.\nQed.\n\n(** * Lists *)\nLemma strong_induction :\n  forall n P,\n    P 0 -> (forall n, (forall m, m<n -> P m) -> P n)\n    -> P n.\nProof.\n  cut (forall n P, (forall k, k <= 0 -> P k) ->\n                   (forall n, (forall m, m <= n -> P m)\n                              -> (forall m, m<= S n -> P m))\n                ->  (forall m, m<= n -> P m)).\n  intros h n P p0 hind.\n  apply (h n);auto.\n  intros k hk;apply le_n_0_eq in hk as <-;auto.\n  intros m hind2 k hk.\n  apply hind;intros l hl.\n  apply hind2;\n  apply lt_n_Sm_le;apply (lt_le_trans _ k);auto.\n  \n  intros n P p0 hind.\n  induction n.\n  intros;auto.\n  apply hind;auto.\nQed.\n\nLemma strong_induction_list {A}  :\n  forall f (P : A -> Prop), (forall l, f l = 0 -> P l) ->\n            (forall l, (forall m, f m < f l -> P m) -> P l)\n            -> forall l, P l.\nProof.\n  intros f P h0 hind l; set (ln := f l);\n  assert (f l = ln) as hln; auto.\n  cut (forall l, f l = ln -> P l).\n  intros h1;auto.\n  apply (strong_induction ln).\n  apply h0.\n  intros n hi m hm.\n  apply hind.\n  intros k hk; apply (hi (f k)).\n  rewrite <- hm;auto.\n  auto.\nQed.\n\nLemma app_prop_dec {A} :\n  forall (u : list A) P,\n  (forall u1 u2, Decidable.decidable (P u1 u2)) ->\n    Decidable.decidable (exists u1 u2, u = u1 ++ u2 /\\ P u1 u2).\nProof. \n  induction u;intros P hd.\n  case (hd nil nil) as [h|h].\n  left;exists nil;exists nil;auto.\n  right;intros (u1 & u2 & hu & hp).\n  destruct u1;destruct u2; cauto.\n  case (IHu (fun u1 u2 => P (a::u1) u2)) as [(u1 & u2 & hu & hp)|h].  \n  intros u1 u2;apply hd.\n  left;exists (a::u1); exists u2;split.\n  simpl;f_equal;auto.\n  auto.\n  case (hd nil (a::u)) as [hnil|hnil].\n  left;exists nil;exists (a::u);split;auto.\n  right;intros (u1 & u2 & hu & hp).\n  destruct u1;simpl in *.\n  rewrite hu in *;cauto.\n  apply h;exists u1;exists u2.\n  inversion hu;auto.\nQed.\n\n(** A mesure is just a list homomorphism. *)\nDefinition mesure {A} mes :=\n  (forall u1 u2 : list A, mes (u1 ++ u2) = mes u1 + mes u2).\n\n(** Usefull thing *)\nLemma inv_rev {A} (u1 u2 : list A) (o1 o2 : A) :\n  u1++o1::nil = u2++o2::nil -> u1 = u2 /\\ o1 = o2.\nProof.\n  intro h.\n  assert (rev (u1++o1::nil) = rev (u2++o2::nil)) as hr.\n  rewrite h;auto.\n  repeat rewrite rev_unit in hr;inversion hr.\n  rewrite <- (rev_involutive u1);\n  rewrite <- (rev_involutive u2);rewrite H1;auto.\nQed.\n\nLemma decomposition {A} : forall u1 u2 u3 u4 : list A, u1++u2 = u3++u4 -> \nexists u5, (u1=u3++u5 /\\ u4=u5++u2) \\/ (u3=u1++u5 /\\ u2=u5++u4).\nProof.\ninduction u1.\nintros; exists u3; right;split; simpl; auto.\ndestruct u3.\nintros; exists (a::u1); left;split; simpl; auto.\nintros.\nrepeat rewrite<- app_comm_cons in *.\ninversion H.\nrewrite<- H1 in *.\napply IHu1 in H2.\ndestruct H2.\nexists x; case H0;intros;destruct H2;\n[left|right]; rewrite H2;rewrite H3; auto.\nQed.\n\nLtac decomp h :=\nlet x := fresh \"u\" in\nlet h0 :=fresh \"h\" in\nlet h1 := fresh \"h\" in\nlet h2 := fresh \"h\" in\ncase (decomposition _ _ _ _ h); intros x h0; case h0; clear h0; intro h1;\ndestruct h1 as (h1,h2); rewrite h1 in *;rewrite h2 in *;\nsimpl in *;clear h.\n\n\nLemma app_inv_tail {A} u v w (x : A) :\n  u ++ v = w ++ x :: nil\n  -> v <> nil\n  -> exists z, w = u ++ z /\\ v = z ++ x::nil.\nProof.\n  intros h hv.\n  decomp h.\n  destruct u0;simpl in *.\n  exists nil; \n  repeat rewrite<- app_nil_end in *; simpl;\n    rewrite<- h2 in *;auto.\n  inversion h2;\n  symmetry in H1;apply app_eq_nil in H1;destruct H1;cauto.\n  exists u0;split;auto.\nQed.", "meta": {"author": "aubrhe", "repo": "omafac", "sha": "0c40b2e5c9f928c4ddbaa076f08643902d2a9fc2", "save_path": "github-repos/coq/aubrhe-omafac", "path": "github-repos/coq/aubrhe-omafac/omafac-0c40b2e5c9f928c4ddbaa076f08643902d2a9fc2/Tools.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.7069235476605497}}
{"text": "(*\n   We would like to define the notion of an algebra with given operations satisfying given\n   equations. For example, a group has of three operations (unit, multiplication, inverse)\n   and five equations (associativity, unit left, unit right, inverse left, inverse right).\n*)\n\n(* We start by defining operation signatures. These describe the operations\n   of an algebra.\n\n   The main trick is that the arity of an operation is *not* a number\n   but rather a type. For instance, the arity of a binary operation\n   is a type with two elements. (And nothing prevents us from having\n   an infinite type as arity.)\n *)\n\n(*the following libraries are important to manipualte algebras more easily in our proofs, and allow rewrite tactics*)\nRequire Import Setoid.\nRequire Import Morphisms.\n\n\n(*the signature is a set of operation names with an arity function*)\nRecord OpSignature :=\n  {\n    operation : Type ; (* (Names of) operations. *)\n    arity : operation -> Type (* Each operation has an arity. *)\n  }.\n\nArguments arity {_} _.\n\n(* We shall consider algebras with given operations, but without equations.\n   We call these \"operation algebras\". *)\n\nRecord OpAlgebra (S : OpSignature) :=\n  {\n    carrier :> Type ;\n    op : forall o : operation S, (arity o -> carrier) -> carrier;\n    (* no equations *)\n  }.\n\n\nArguments op {_} _ _ _.\n\nCheck op.\n\n(*then we define inductively the type of terms : it takes on argument an OpSignature and a type for the base case (infered_generator) *)\n\nInductive Tree (S : OpSignature) (X : Type) : Type :=\n  | generator : X -> Tree S X\n  | node : forall (o : operation S), (arity o -> Tree S X) -> Tree S X.\n\nArguments generator {_} {_} _.\nArguments node {_} {_} _.\n\n \n(* Now given some operations, described by an operation signature S,\n   we can define an equation signature which specifies some equations.       \n*)\nRecord EqSignature (S : OpSignature) :=\n  { \n  equ :> Type ; (* (names of) equations *)\n  X : Type ;\n\n    (* Next we specify the equations. Note that they are polymorphic in the underlying algebra. *)\n  lhs : equ -> Tree S X ; (* left-hand sides *)\n  rhs : equ -> Tree S X ; (* right-hand sides *)\n  }.\n\n \nArguments lhs {_} _ _.\nArguments rhs {_} _ _.\n\n(* We define how to interpret trees as elements of A *)\nFixpoint inter {S : OpSignature} {A : OpAlgebra S} {X : Type} (val : X -> A) (t : Tree S X) :=\n  match t with\n  | generator x => val x\n  | node o args => op A o (fun x => inter val (args x))\n  end.\n\n(* We define the congruence relation used for the algebras *)\nRecord CongRelation {S : OpSignature} (A : OpAlgebra S) :=\n  {\n    cong_rel :> A -> A -> Prop; (* the equality relation *)\n    cong_rel_refl : forall x, cong_rel x x;\n    cong_rel_sym : forall x y, cong_rel x y -> cong_rel y x;\n    cong_rel_trans : forall x y z, cong_rel x y -> cong_rel y z -> cong_rel x z;\n    cong_rel_cong : forall (o : operation S) (args1 args2 : arity o -> A), (forall (n : arity o), cong_rel (args1 n) (args2 n)) -> cong_rel (op A o args1) (op A o args2);\n}.\n\n\n(* We can now define what it means to have an algebra for a signature S satisfying\n   equations E. *)\nRecord Algebra (S : OpSignature) (E : EqSignature S) :=\n  {\n  M :> OpAlgebra S ;\n  equal : CongRelation M;\n  equations : forall (e : E) (val : X S E -> M), equal (inter val (lhs E e)) (inter val (rhs E e)) \n  }.\n\n\n(* We define the type of homomorphism between algebras A and B. *)\n\nRecord Hom {S : OpSignature} {E : EqSignature S} (A : Algebra S E) (B : Algebra S E)  :=\n  { \n    map :> A -> B ; (* The underlying map *)\n    (* The underlying map commutes with operations: *)\n    op_respect : forall (x y : A), (equal S E A) x y -> (equal S E B) (map x) (map y);  \n    op_commute : forall (o : operation S) (args : arity o -> A),\n                   (equal S E B) (map (op A o args)) (op B o (fun x => map (args x)))\n  }.\n\nDefinition isomorphic {S : OpSignature} {E : EqSignature S} (A B : Algebra S E) :=\nexists (f: Hom A B) (g : Hom B A), (forall x : A, (equal S E A) (g (f x))  x) /\\ (forall x : B, (equal S E B) (f (g x)) x).\n\n\n(*finally, a useful lemma*)\nLemma equal_setoid {S : OpSignature} {E : EqSignature S} (A : Algebra S E) : Setoid_Theory A (equal S E A).\nProof.\nunfold Setoid_Theory.\nsplit.\nunfold Reflexive.\napply (cong_rel_refl (M S E A) (equal S E A)).\nunfold Symmetric.\napply (cong_rel_sym (M S E A) (equal S E A)).\nunfold Transitive.\napply (cong_rel_trans (M S E A) (equal S E A)).\nQed.\n\n\nSection free_is_unique.\n(* in this section we are going to define what is freeness and to proove that 2 free object over the same type are isomorphic*)\n\n(*the commuting property*)\n\n\n(*we then say that an algebra A is free over (X, q) relatively to an algebra B and a function f iff there is only one f_tilde \nin HOM(A, B) such that it makes the diagramm commute :\n\n           f\n       X ----->B\n       |      /\n       |     /\n      q|    /f_tilde\n       |   /\n       |  /\n       | /\n       A \n\n*)\n\nDefinition commute {S : OpSignature} {E : EqSignature S} (A B : Algebra S E) (X : Type) (q : X -> A) (f : X -> B) (f_tilde : Hom A B)  :=\nforall (x : X), (equal S E B) (((map A B) f_tilde) (q x)) (f x).\n\nRecord free_relative {S : OpSignature} {E : EqSignature S} (A B : Algebra S E) (X : Type) (q : X -> A) (f : X -> B) :=\n{ f_tilde : Hom A B ; \n  it_commutes : commute A B X q f f_tilde ; \n  uniqueness  : forall (g : Hom A B), commute A B X q f g /\\ commute A B X q f f_tilde -> (forall (x  : A), (equal S E B) (f_tilde x) (g x)) }.\n\n(*then, we define free : an Algebra is free over (X, q) if for all algebra B and function f X -> B, we have the relative freeness*)\nDefinition free {S : OpSignature} {E : EqSignature S} (A: Algebra S E) (X : Type) (q : X -> A) :=\n forall (B : Algebra S E) (f : X -> B), free_relative A B X q f. \n\n\nDefinition identite {S : OpSignature} {E : EqSignature S} (A : Algebra S E) : Hom A A.\nProof.\nsplit with (fun (x : A) => x).\nintros.\nauto.\nintros.\nassert (args = fun x => args x).\nauto.\nrewrite H.\napply (cong_rel_cong A).\nintros n ; apply (cong_rel_refl A).\nDefined.\n\nDefinition composition {S : OpSignature} {E : EqSignature S} (A B C: Algebra S E) (f : Hom A B) (g : Hom B C) : Hom A C.\nProof.\nsplit with (fun x => g (f x)).\nintros.\napply ((op_respect B C) g).\napply ((op_respect A B) f).\nauto.\nintros. \napply (cong_rel_trans) with (y := g (op B o (fun x => f (args x)))).\napply ((op_respect B C) g).\napply ((op_commute A B) f).\napply (op_commute).\nDefined. \n\n(*rewrite using specialize tactic*)\n\nLemma uniqueness_of_free (X : Type) {S : OpSignature} {E : EqSignature S} (A B : Algebra S E) (q : X -> A) (q' : X -> B) :\nfree A X q -> free B X q' -> isomorphic A B.\nintros.\nunfold isomorphic.\nassert (free_relative A B X q q').\napply X0.\nassert (free_relative B A X q' q).\napply X1.\nexists ((f_tilde A B X q q') X2).\nexists ((f_tilde B A X q' q) X3).\nremember ((f_tilde A B X q q') X2) as f_hom.\nremember ((f_tilde B A X q' q) X3) as g_hom.\nsplit.\n+\nintros.\nassert (free_relative A A X q q).\napply X0.\nassert ((forall (x  : A), (equal S E A) ((f_tilde A A X q q X4) x) (identite A x))).\napply (uniqueness A A X q q X4).\nsplit.\nunfold commute.\nintros.\nsimpl.\napply (cong_rel_refl A).\napply (it_commutes A A X q q X4).\nassert (forall (x : A), (equal S E A) ((f_tilde A A X q q X4) x) ((((composition A B A) f_hom g_hom)) x)).\napply (uniqueness A A X q q X4).\nsplit.\nunfold commute.\nintros.\nassert (commute A B X q q' f_hom).\nrewrite Heqf_hom.\napply ((it_commutes A B X q q') X2).\nunfold commute in H0.\nassert (commute B A X q' q g_hom).\nrewrite Heqg_hom.\napply ((it_commutes B A X q' q) X3).\nunfold commute in H1.\nassert (forall x0, (equal S E A) (g_hom (f_hom (q x0))) (g_hom (q' x0))).\nintros.\napply (op_respect).\nauto.\nsimpl.\napply (cong_rel_trans A) with (y := g_hom (q' x0)).\nauto.\nauto.\napply (it_commutes).\napply (cong_rel_trans A) with (y := f_tilde A A X q q X4 x).\napply (cong_rel_sym A).\nsimpl in H0.\nauto.\nsimpl in H.\nauto.\n+\nintros.\nassert (free_relative B B X q' q').\napply X1.\nassert ((forall (x  : B), (equal S E B) ((f_tilde B B X q' q' X4) x) (identite B x))).\napply (uniqueness B B X q' q' X4).\nsplit.\nunfold commute.\nintros.\nsimpl.\napply (cong_rel_refl B).\napply (it_commutes B B X q' q' X4).\nassert (forall (x : B), (equal S E B) ((f_tilde B B X q' q' X4) x) ((((composition B A B) g_hom f_hom)) x)).\napply (uniqueness B B X q' q' X4).\nsplit.\nunfold commute.\nintros.\nassert (commute B A X q' q g_hom).\nrewrite Heqg_hom.\napply ((it_commutes B A X q' q) X3).\nunfold commute in H0.\nassert (commute A B X q q' f_hom).\nrewrite Heqf_hom.\napply ((it_commutes A B X q q') X2).\nunfold commute in H1.\nassert (forall x0, (equal S E B) (f_hom (g_hom (q' x0))) (f_hom (q x0))).\nintros.\napply (op_respect).\nauto.\nsimpl.\napply (cong_rel_trans B) with (y := f_hom (q x0)).\nauto.\nauto.\napply (it_commutes).\napply (cong_rel_trans B) with (y := f_tilde B B X q' q' X4 x).\napply (cong_rel_sym B).\nsimpl in H0.\nauto.\nsimpl in H.\nauto.\nQed.\nEnd free_is_unique.\n\n\n(*this section is about the definition and properties of the term algebra*)\nSection TermAlgebra_definition.\n(*we contextualise the object in this section : to use the definitions here outside of this section, \nwe will need to provie an OpSignature S and an E an EqSignature over S**) \nContext (S : OpSignature).\nContext (E : EqSignature S).\nCheck generator.\nDefinition infered_generator:= X S E.\nCheck infered_generator.\n\n\n(*propagation of the substition in a tree : it is to use the substition rule in a tree*)\nFixpoint application_subst (T : Tree S infered_generator) (theta : infered_generator -> Tree S infered_generator) : Tree S infered_generator :=\nmatch T with\n|generator x => theta x\n|node o args => node o (fun x => \n application_subst (args x) (theta))\nend.\n\n(*the A |- p = q relation : this will be the equality (i.e the CongRelation here) over the terms\n(i.e trees) here, and this will define a setoid, as we will proove it later *)\n\n(*changer le type de cong relation de type to prop*)\n\nInductive quotient_relation : Tree S infered_generator -> Tree S infered_generator -> Prop :=\n|cas_base : forall (e : E), quotient_relation (lhs E e) (rhs E e)\n|cas_refl : forall (T : Tree S infered_generator), quotient_relation T T\n|cas_sym : forall (T T': Tree S infered_generator), quotient_relation T' T -> quotient_relation T T'\n|cas_trans : forall (T T' T'' : Tree S infered_generator), quotient_relation T T' -> quotient_relation T' T'' -> quotient_relation T T''\n|cas_passage_contexte : forall (op : operation S) (args args' : arity op -> Tree S infered_generator),\n(forall (n : arity op), quotient_relation (args n) (args' n)) -> quotient_relation (node op (fun i => args i)) (node op (fun i => args' i))\n|cas_subst : forall (T T' : Tree S infered_generator ) (theta : infered_generator -> Tree S infered_generator), \nquotient_relation T T' -> quotient_relation (application_subst T theta) (application_subst T' theta). \n\n\n\n(*we are going to declare the type of trees with quotient relation as a setoid. We need to provide a proof \nthat quotient_relation is indeed an equivalence relation *)\nLemma tree_setoid : Setoid_Theory (Tree S infered_generator ) quotient_relation.\nProof.\nunfold Setoid_Theory.\nsplit.\nunfold Reflexive.\napply cas_refl.\nunfold Symmetric.\nintros.\napply cas_sym.\nexact H.\nunfold Transitive.\nintros.\napply cas_trans with (T := x) (T' := y) (T'' := z).\nauto. auto.\nQed.\n\nAdd Setoid (Tree S infered_generator ) quotient_relation tree_setoid as setoid_term_algebra.\n\n(*then, the term algebra is simply the OpAlgebra with carrier the type of trees and the interpretation of an \noperation is the associated node*)\n\n\nDefinition Term_algebra : OpAlgebra S :=\n{|carrier := Tree S infered_generator  ; \nop := (fun (o : operation S) => (fun (args : arity o -> Tree S infered_generator ) => node o args))|}.\n\n(*we then need, in order to build an algebra, to define a CongRelation over the Term_algebra. We are going to use quotient_relation *)\n\nDefinition eqtree : CongRelation Term_algebra.\nsplit with (quotient_relation).\napply cas_refl.\nintros ;  rewrite H ; apply cas_refl.\nintros. rewrite H. exact H0.\nintros. apply cas_passage_contexte with (op := o) (args := args1) (args' := args2).\nauto.\nDefined.\n\n(*We need this lemma, it will maybe be redone in the future, but as for now, I will keep it :\nan amelioration would be to define substition directly by using inter, but it makes things less clear thatn defining \nproperly substition and then showging that indeed it is the same thing*)\n\nLemma egalité_utile : forall (T : Tree S infered_generator ) (theta : infered_generator -> Tree S infered_generator ), \nquotient_relation (application_subst T theta) (inter (A := Term_algebra) theta T).\nProof.\nintros.\ninduction T.\nsimpl ; reflexivity.\nsimpl.\napply cas_passage_contexte.\nexact H.\nQed.\n\n(*now, lets show that the term algebra, with the congrelation eqtree (built over quotient_relation) is \nan algebra of the equationnal theory E*)\n\nDefinition Term_algebra_model : Algebra S E.\nsplit with Term_algebra eqtree.\nintros.\nsimpl.\nrewrite <- ? egalité_utile.\napply cas_subst.\napply cas_base.\nDefined.\n\n\n(*indeed, the term algebra is a model of what it is supposed to represent*)\n\n\n(*now let's show that the term algebra is free *)\n\nContext  (A : Algebra S E).\nContext (f : infered_generator -> A).\n\n(*To manipulate more easily the definitions, we decalre A equal S E A as a setoid*)\nCheck cong_rel_refl.\n\n\nAdd Setoid A (equal S E A) (equal_setoid A) as A_is_setoid.\n\n\n(*what we want is a function q (that does not depend of f) called the free map and \nan unique homomorphism f_tilde that makes this diagramm commute :\n\n\n                     f  \ninfered_generator ------> A\n       |                 /\n       |                /\n      q|               /f_tilde\n       |              /\n       |             /\n       |            /\n      term_algebra \n                  *)\n\n(*we define q*)\nDefinition q (x : infered_generator) : Term_algebra := \ngenerator x.\n\n(*we define now the function that is an homomorphism from term_algebra to A by induction over the terms*)\n\nFixpoint f_tilde_term (t : Term_algebra) : A := match t with \n|generator x => f x\n|node operation args => ((op A) operation) (fun x => f_tilde_term (args x))\nend.\n\nLemma lemme_utile_2 : forall (x : Term_algebra),  (equal S E A) (f_tilde_term x) (inter f x).\nProof.\nintros.\ninduction x.\nsimpl.\nreflexivity.\nsimpl.\napply (cong_rel_cong A).\nintros.\napply H.\nQed.\n\n\n\nLemma is_the_same : forall (T : Term_algebra) (f : infered_generator -> A) (theta : infered_generator -> Tree S infered_generator), \nequal S E A (inter f (application_subst T theta)) (inter (fun x => inter f (theta x)) T).\nProof.\nintros.\ninduction T.\nsimpl.\nreflexivity.\nintros.\nsimpl.\napply (cong_rel_cong).\nexact H.\nQed.\n\nLemma equal_is_equal : forall (x y : Term_algebra)(f : infered_generator -> A), \nquotient_relation x y -> (equal S E A) (inter f x) (inter f y).\nProof.\nintros.\ngeneralize dependent f0.\ninduction H.\nintros.\napply (equations S E A) with (e := e) (val := f0).\nintros.\napply cong_rel_refl.\nintros.\napply cong_rel_sym.\nauto.\nintros.\napply cong_rel_trans with (y := inter f0 T').\nauto.\nauto.\nintros. \nsimpl.\napply (cong_rel_cong).\nintros.\nauto.\nintros.\nrewrite 2 is_the_same.\napply IHquotient_relation with (f0 := fun x => inter f0 (theta x)).\nQed.\n\n\nDefinition is_an_homomorphism : Hom (Term_algebra_model) A.\nProof.\nexists f_tilde_term.\nintros. \n+\nrewrite ? lemme_utile_2.\napply equal_is_equal.\nauto.\n+\nintros.\nsimpl.\napply cong_rel_cong.\nintros.\napply reflexivity.\nDefined.\n\n\nLemma makes_the_diagramm_commute : forall (x : infered_generator ), (equal S E A) (f x) (f_tilde_term (q x)).\nProof.\nintros.\nsimpl.\nreflexivity.\nQed.\n\n\n\n\nLemma unicité : forall (f' g' : Hom Term_algebra_model A), \n(forall (x : infered_generator ), (equal S E A) (f' (generator x)) (g' (generator x)))-> (forall (t : Term_algebra), (equal S E A) (f' t) (g' t)).\nProof.\nintros.\ninduction t.\nauto.\nassert ((equal S E A) (f' (node o t)) (op A o (fun x => f' (t x)))).\napply (op_commute Term_algebra_model A). \nassert ((equal S E A) (g' (node o t)) (op A o (fun x => g' (t x)))).\napply (op_commute Term_algebra_model A ).\napply (cong_rel_trans A (equal S E  A)) with (x :=  (f' (node o t))) (y := (op A o (fun x : arity o => f' (t x)))) (z := (g' (node o t))).\nauto.\napply (cong_rel_trans A (equal S E A)) with (x := (op A o (fun x : arity o => f' (t x)))) (y := (op A o (fun x : arity o => g' (t x)))) (z := (g' (node o t))).\napply (cong_rel_cong A (equal S E A)).\nauto.\nsymmetry.\nauto.\nQed.\n\nEnd TermAlgebra_definition.\n\nSection TermALgebra_is_free.\nContext (S : OpSignature).\nContext (E : EqSignature S).\nCheck Term_algebra.\nCheck f_tilde_term.\n\n\nDefinition is_free_term_algebra : free (Term_algebra_model S E) (X S E) (fun x => generator x).\nProof.\nunfold free.\nintros.\nsplit with (is_an_homomorphism S E B f).\nunfold commute.\nintro.\nsimpl.\napply (cong_rel_sym).\nunfold is_an_homomorphism.\napply (cong_rel_refl).\nintros.\napply unicité.\nintros.\nunfold is_an_homomorphism.\nsimpl.\ndestruct H.\nunfold commute in H.\nunfold commute in H0.\napply (cong_rel_trans B) with (y := is_an_homomorphism S E B f (generator x0)).\napply (cong_rel_sym B).\nauto.\napply (cong_rel_trans B) with (y := f x0).\nauto.\napply (cong_rel_sym B).\nauto.\nDefined.\n\nEnd TermALgebra_is_free.\n\nSection iso_caracterisation.\nContext (S : OpSignature).\nContext (E : EqSignature S).\nContext (A B : Algebra S E).\n\nDefinition injective (f : Hom A B) : Type := forall (x y : A), (equal S E B) (f x) (f y) -> (equal S E A) x y.\n\nDefinition surjective (f : Hom A B) : Type := forall x, {t | f t = x}.\n\n\n\nContext (f : Hom A B).\nHypothesis injectf : injective f.\nHypothesis surjectf : surjective f.\n\n\nDefinition f_inv (x : B) :  A.\nProof.\nunfold surjective in surjectf.\npose proof surjectf x.\ndestruct X0.\nexact x0.\nDefined.\n\nPrint f_inv.\n\n\nLemma un_sens: forall (x : A), (equal S E A) (f_inv (f x)) x.\nProof.\nintros.\nunfold surjective in surjectf.\nunfold injective in injectf.\nunfold f_inv.\ndestruct (surjectf (f x)) as [x0 H].\napply injectf.\nrewrite H.\napply cong_rel_refl.\nQed.\n\nLemma autre_sens : forall (x : B), (equal S E B) (f (f_inv x)) x.\nProof.\nintros.\nunfold surjective in surjectf.\nunfold injective in injectf.\nunfold f_inv.\ndestruct (surjectf x) as [x0 e].\nrewrite e.\napply cong_rel_refl.\nQed.\n\nLemma respect_rel : forall (x y : B), (equal S E B) x y -> (equal S E A) (f_inv x) (f_inv y).\nProof.\nintros.\nunfold f_inv.\nunfold surjective in surjectf.\ndestruct (surjectf x) as [x0 e].\ndestruct (surjectf y) as [x1 e'].\nunfold injective in injectf.\napply injectf.\nrewrite e.\nrewrite e'.\nauto.\nQed.\n\nDefinition iso_back : Hom B A.\nProof.\nsplit with (f_inv).\nintros.\napply respect_rel.\nauto.\nintros.\napply cong_rel_trans with (y := f_inv (op B o (fun x => f (f_inv (args x))))).\napply respect_rel.\napply cong_rel_cong.\nintros.\napply cong_rel_sym.\napply autre_sens with (x := args n).\napply cong_rel_trans with (y := f_inv (f (op A o (fun x => f_inv (args x))))).\napply respect_rel.\napply cong_rel_sym.\napply op_commute.\napply un_sens.\nQed.\n", "meta": {"author": "slechenne-dev", "repo": "Stage-CoQ", "sha": "1ee91236a452ceb07f7693adf40b16e8bad2e61c", "save_path": "github-repos/coq/slechenne-dev-Stage-CoQ", "path": "github-repos/coq/slechenne-dev-Stage-CoQ/Stage-CoQ-1ee91236a452ceb07f7693adf40b16e8bad2e61c/universal_algebra_generality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7069235465928544}}
{"text": "(**  Well ordered sets (after Schutte) *)\n\n(**  Pierre Casteran LaBRI, Universite de Bordeaux  *)\n\n\nFrom Coq Require Import Relations  Classical  Classical_sets RelationClasses\n     Wf_nat.\n\nFrom hydras Require Import PartialFun.\nImport MoreEpsilonIota.\n\nArguments In [U].\nArguments Included [U].\n\nSet Implicit Arguments.\n#[global] Hint Unfold In : core.\n\n\nSection the_context.\n\n  (* begin snippet MDecl *)\n  Variables (M:Type)\n            (Lt : relation M).\n\n  Definition Le (a b:M) :=  a = b \\/ Lt a b.\n  \n  Definition least_member  (X:Ensemble M) (a:M) :=\n    In X a /\\ forall x,  In X x -> Le a x.\n  (* end snippet MDecl *)\n  \n  Definition least_fixpoint (f : M -> M) (x:M) :=\n    f x = x /\\ forall y: M,  f y = y -> Le x y.\n  \n  (** Well Ordering *)\n  \n  (* begin snippet WODef *)\n  Class WO : Type:=\n    {\n    Lt_trans : Transitive  Lt;\n    Lt_irreflexive : forall a:M, ~ Lt a a;\n    well_order : forall (X:Ensemble M)(a:M),\n        In X a ->\n        exists a0:M, least_member  X a0\n    }.\n  (* end snippet WODef *)\n  \n  (* Some derived properties of well ordered sets *)\n  \n  Section About_WO.\n    Context (Wo : WO).\n    \n    Lemma  Lt_connect : forall a b,  Lt a b \\/ a = b \\/ Lt b a.\n    Proof.\n      intros a b ; generalize (well_order  (Couple _ a b) a ).\n      destruct 1 as [ c H1].\n      - left. \n      -  destruct H1  as [H2 H3].\n         destruct H2.  \n         +  destruct (H3 b);auto; now right.\n         +  destruct (H3 a);auto; now left.       \n    Qed.\n    \n    Lemma Le_refl : forall x:M, Le x x.\n    Proof.\n      red;unfold Le;auto.\n    Qed.\n\n    Lemma Le_antisym : forall a b,  Le a b -> Le b a -> a = b.\n    Proof.\n      intros a b  H H'; case H; case H' ; try tauto.\n      - symmetry; tauto.\n      - intros;case (Lt_irreflexive (a:=a)); eapply (Lt_trans );eauto. \n    Qed.\n\n    #[global] Instance  Le_trans : Transitive  Le. \n    Proof.\n      unfold Transitive, Le;intros.\n      case H;case H0.\n      - intros; left ; congruence.   \n      -  intros H1 H2; right;subst x;auto.\n      -  intros H1 H3; right ; subst y; auto.\n      -  right;apply Lt_trans with y;eauto.\n    Qed.\n\n\n    Lemma Le_Lt_trans : forall x y z, Le x y -> Lt y z -> Lt x z.\n    Proof.\n      intros x y z Hxy Hyz; case Hxy;intros.\n      -  now subst y.\n      - eapply Lt_trans; eauto.\n    Qed.\n    \n    Lemma Lt_Le_trans : forall x y z, Lt x y -> Le y z -> Lt x z.\n    Proof.\n      intros x y z Hxy Hyz; destruct Hyz as [H0 | H].\n      - now subst.\n      -  eapply Lt_trans; eauto.\n    Qed.\n\n    Lemma Lt_not_Gt : forall x y,  Lt x y -> ~ Lt y x.\n    Proof.\n      intros x y  H H'; case (Lt_irreflexive (a:=x)).\n      eapply Lt_trans; eauto.\n    Qed.\n    \n    Lemma least_member_lower_bound : forall X a,\n        least_member  X a -> forall b, In X b ->  Le a b.\n    Proof.\n      intros X a H; case H.\n      unfold In; intuition.\n    Qed.\n    \n    Lemma least_member_glb :\n      forall X a,\n        least_member  X a -> \n        forall b, (forall c, In X c ->  Le b c) ->\n                  Le b a.\n    Proof.\n      intros X a H b H0; case H;intros H1 H2;  apply H0; auto.\n    Qed.\n\n    \n    Theorem least_member_unicity : forall  X a b, \n        least_member  X a -> least_member  X b -> a = b.\n    Proof.\n      intros X a b H H0;  case H;case H0;intros.\n      - apply Le_antisym;auto.\n    Qed.\n    \n    \n    Theorem least_member_ex_unique :\n      forall   X  x \n               (inhX: In X x), \n      exists! a,  least_member  X a.\n    Proof.\n      intros;destruct (well_order X x); auto.\n      exists x0; split; auto.\n      intros; eapply least_member_unicity;eauto.\n    Qed.\n    \n    \n    Theorem least_member_of_eq : forall (X Y : Ensemble M) a b ,\n        Included X Y -> Included Y X ->\n        least_member  X a ->\n        least_member  Y b ->\n        a = b.\n    Proof.\n      intros X Y a b H H0  [H3 H4 ] [H6 H7].  apply Le_antisym;auto.\n    Qed.\n\n  End About_WO.\n  \nEnd the_context.\n\n(* begin snippet theLeast *)\n\nDefinition the_least {M: Type} {Lt}\n           {inh : InH M} {WO: WO Lt} (X: Ensemble M)  : M :=\n  the (least_member Lt X ).\n\n(* end snippet theLeast *)\n\nLemma  the_least_unicity {M: Type} {Lt}\n       {inh : InH M} {WO: WO Lt} (X: Ensemble M)\n       (HX: Inhabited _ X ) \n  : exists! l , least_member   Lt X l.\nProof.\n  destruct HX as [x Hx].\n  case  WO; intros.\n  destruct (well_order0 X x Hx) as [x0 H0].\n  exists x0; split; auto.\n  intros; eapply least_member_unicity;eauto . \nQed.\n\n\n\n\n#[ global ] Instance WO_nat : WO Peano.lt.\nsplit.\n- red. intros; now  transitivity y.\n- intros; apply PeanoNat.Nat.lt_irrefl.\n-  intros X a; pattern a; apply well_founded_induction with Peano.lt.\n   + apply lt_wf.\n   + intros;\n       destruct (classic (least_member lt X x)).\n     * exists x; auto.\n     * unfold least_member in H1;     destruct (not_and_or _ _ H1).\n       contradiction.\n       destruct (not_all_ex_not _ _ H2).     \n       destruct (imply_to_and _ _ H3).\n       assert (lt x0 x). {\n         destruct (Compare_dec.lt_eq_lt_dec x0 x).\n         - destruct s; auto.\n           + subst x0; unfold Le in H5.\n             destruct H5; auto.\n         - destruct H5; now right.\n       }\n       destruct (H x0 H6 H4);  exists x1;  auto.\nQed.\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/Schutte/Well_Orders.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7069235408963772}}
{"text": "Require Import ZArith.\nRequire Import Classical.\nRequire Import List.\n\nOpen Scope list_scope.\nOpen Scope Z_scope.\n\nDp_debug.\nDp_timeout 3.\nRequire Export zenon.\n\nDefinition neg (z:Z) : Z := match z with\n  | Z0 => Z0\n  | Zpos p => Zneg p\n  | Zneg p => Zpos p\n  end.\n\nGoal forall z, neg (neg z) = z.\n  Admitted.\n\nOpen Scope nat_scope.\nPrint plus.\n\nGoal forall x, x+0=x.\n  induction x; ergo.\n  (* simplify resoud le premier, pas le second *)\n  Admitted.\n\nGoal 1::2::3::nil = 1::2::(1+2)::nil.\n  zenon.\n  Admitted.\n\nDefinition T := nat.\nParameter fct : T -> nat.\nGoal fct O = O.\n Admitted.\n\nFixpoint even (n:nat) : Prop :=\n  match n with\n  O => True\n  | S O => False\n  | S (S p) => even p\n  end.\n\nGoal even 4%nat.\n  try zenon.\n  Admitted.\n\nDefinition p (A B:Set) (a:A) (b:B) : list (A*B) := cons (a,b) nil.\n\nDefinition head :=\nfun (A : Set) (l : list A) =>\nmatch l with\n| nil => None (A:=A)\n| x :: _ => Some x\nend.\n\nGoal forall x, head _ (p _ _ 1 2) = Some x -> fst x = 1.\n\nAdmitted.\n\n(*\nBUG avec head prédéfini : manque eta-expansion sur A:Set\n\nGoal forall x, head _ (p _ _ 1 2) = Some x -> fst x = 1.\n\nPrint value.\nPrint Some.\n\nzenon.\n*)\n\nInductive IN (A:Set) : A -> list A -> Prop :=\n  | IN1 : forall x l, IN A x (x::l)\n  | IN2: forall x l, IN A x l -> forall y, IN A x (y::l).\nImplicit Arguments IN [A].\n\nGoal forall x, forall (l:list nat), IN x l -> IN x (1%nat::l).\n  zenon.\nPrint In.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/plugins/dp/test2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7069235368893672}}
{"text": "Require Coq.extraction.Extraction.\nExtraction Language OCaml.\n\nInductive term : Type :=\n| Var : nat -> term\n| Abs : term -> term\n| App : term -> term -> term.\n\nNotation beta_ShiftNum := 0.\n\nFixpoint shift (d c: nat) (t: term) : term :=\n  match t with\n  | Var k =>\n    if Nat.leb c k then\n      match d with\n      | beta_ShiftNum => Var (k - 1)\n      | _ => Var (k + d)\n      end\n    else Var k\n  | Abs t1 => Abs (shift d (c + 1) t1)\n  | App t1 t2 => App (shift d c t1) (shift d c t2)\n  end.\n\nDefinition up (n: nat) (t: term) : term := shift n 0 t.\n\nCompute ( up 2 (Abs (Abs (App (Var 1) (App (Var 0) (Var 2) ))))). (* = Abs (Abs (App (Var 1) (App (Var 0) (Var 4)))) *)\nCompute ( up 2 (Abs (App (Var 0) (App (Var 1)(Abs (App (Var 0)(App (Var 1)(Var 2)))))))). (* = Abs (App (Var 0) (App (Var 3) (Abs (App (Var 0) (App (Var 1) (Var 4)))))) *)\n\nFixpoint subst (j: nat) (s t: term) : term :=\n  match t with\n  | Var k =>\n    if Nat.eqb j k then s else Var k\n  | Abs t1 =>\n    Abs (subst (j + 1) (up 1 s) t1)\n  | App t1 t2 =>\n    App (subst j s t1) (subst j s t2)\n  end.\n\nCompute (subst 0 (Var 1) (App (Var 0) (Abs(Abs (Var 2))))).  (* = App (Var 1) (Abs (Abs (Var 3))) *)\nCompute (subst 0 (App (Var 1) (Abs (Var 2))) (App (Var 0) (Abs (Var 1)))). (* = App (App (Var 1) (Abs (Var 2))) (Abs (App (Var 2) (Abs (Var 3)))) *)\n\nReserved Notation \" t '-->' t' \" (at level 40).\n\nInductive value : term -> Prop :=\n  | v_abs : forall n,\n      value (Abs n).\n\nNotation \"'[' x ':=' s ']' t\" := (subst x s t) (at level 20).\n\nInductive eval : term -> term -> Prop :=\n  | E_App1 : forall t1 t1' t2,\n      t1 --> t1' ->\n      App t1 t2 --> App t1' t2\n  | E_App2 : forall v1 t2 t2',\n      value v1 ->\n      t2 --> t2' ->\n      App v1 t2 --> App v1 t2'\n  | E_AppAbs : forall t1 v2,\n      value v2 ->\n      App (Abs t1) v2 -->\n          up beta_ShiftNum ([0 := up 1 (v2)] t1)\n\n  where \" t '-->' t' \" := (eval t t').\n\nDefinition relation (X : Type) := X -> X -> Prop.\n\nInductive multi {X : Type} (R : relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nNotation multieval := (multi eval).\nNotation \"t1 '-->*' t2\" := (multieval t1 t2) (at level 40).\n\nDefinition vb (t: term) :=\n  match t with\n  | Abs _ => true\n  | _ => false\n  end.\n\nLemma vbValue : forall t,\n    vb t = true <-> value t.\nProof.\n  destruct t; split; intros; inversion H; auto.\n  apply v_abs.\nQed.\n\nInductive optiont : Type :=\n| Some (t: term)\n| None.\n\nFixpoint step (t: term) : optiont :=\n  match t with\n  | App t1 t2 =>\n    match t1 with\n    | Abs t3 =>\n      if vb t2 then\n        Some (up beta_ShiftNum ([0 := up 1 (t2)] t3)) else\n        match step t2 with\n        | Some t2' => Some (App t1 t2')\n        | None => None\n        end\n    | _ =>\n      match step t1 with\n      | Some t1' =>\n        Some (App t1' t2)\n      | None => None\n      end\n    end\n  | _ => None\n  end.\nExtraction \"ocaml/chap6/src/eval.ml\" step.\n\nLemma stepeval : forall t t',\n    t --> t' <-> step t = Some t'.\nProof.\n  split; intros.\n  -\n    induction H.\n    +\n      simpl. destruct t1. inversion H. inversion H.\n      rewrite IHeval. reflexivity.\n    +\n      simpl. inversion H; subst. destruct t2. inversion H0. inversion H0. rewrite IHeval. simpl. reflexivity.\n    +\n      inversion H; subst. simpl. reflexivity.\n  -\n    generalize dependent t'.\n    induction t; intros. inversion H. inversion H.\n    simpl in H.\n    destruct t1. inversion H. destruct (vb t2) eqn:IH2. inversion H. apply E_AppAbs. apply vbValue; auto.\n    destruct (step t2) eqn:IHH. inversion H.\n    apply E_App2. apply v_abs. apply IHt2. reflexivity.\n    inversion H.\n    destruct (step (App t1_1 t1_2)). inversion H. apply E_App1. apply IHt1. reflexivity.\n    inversion H.\nQed.\n\n\n(*評価の一意性*)\nLemma determine : forall t t' t'',\n    t --> t' -> t --> t'' -> t' = t''.\nProof.\n  intros; generalize dependent t''. induction H; intros.\n  -\n    inversion H0; subst.\n    apply IHeval in H4. rewrite H4; reflexivity.\n    inversion H3; subst. inversion H.\n    inversion H.\n  -\n    inversion H1; subst. inversion H; subst; inversion H5.\n    apply IHeval in H6. rewrite H6; reflexivity.\n    inversion H5; subst; inversion H0.\n  -\n    inversion H; inversion H0; subst.\n    inversion H5. inversion H6.\n    reflexivity.\nQed.\n\nFixpoint size (t: term) : nat :=\n  match t with\n  | Var _ => 1\n  | Abs t1 => 1 + (size t1)\n  | App t1 t2 => (size t1) + (size t2)\n  end.\n\nFixpoint eqb_nat (n1 n2: nat) :=\n  match n1 with\n  | 0 =>\n    match n2 with\n    | 0 => true\n    | _ => false\n    end\n  | S n1' =>\n    match n2 with\n    | 0 => false\n    | S n2' => eqb_nat n1' n2'\n    end\n  end.\n\nLemma eqb_eq : forall n1 n2,\n    eqb_nat n1 n2 = true <-> eq n1 n2.\nProof.\n  split. generalize dependent n2.\n  induction n1; induction n2; intros; auto. inversion H. inversion H.\n\n  generalize dependent n2; induction n1; induction n2; intros; auto; simpl.\n  inversion H. inversion H. apply IHn1. inversion H. auto.\nQed.\n\nFixpoint leb (n1 n2: nat) :=\n  if eqb_nat n1 n2 then true else\n    match n2 with\n    | 0 => false\n    | S n2' => leb n1 n2'\n    end.\n\nFixpoint fv_card (t: term) (n: nat) :=\n  match t with\n  | Var n1 =>\n    if leb n n1 then 1 else 0\n  | Abs t1 =>\n    fv_card (t1) (n + 1)\n  | App t1 t2 =>\n    (fv_card t1 n) + (fv_card t2 n)\n  end.\n\nLemma leb_le : forall n1 n2,\n    n1 <= n2 -> leb n1 n2 = true.\nProof.\n  intros. induction H; simpl.\n  -\n    induction n1; auto. simpl.\n    assert (eqb_nat n1 n1 = true). apply eqb_eq. auto.\n    rewrite H. reflexivity.\n  -\n    destruct (eqb_nat n1 (S m)); auto.\nQed.\n\nLemma le_leb : forall n1 n2,\n    leb n1 n2 = true -> n1 <= n2.\nProof.\n  destruct n1; intros.\n  apply le_0_n.\n  induction n2. inversion H. inversion H.\n  destruct (eqb_nat n1 n2) eqn: IH1. apply eqb_eq in IH1. rewrite IH1; auto.\n  apply IHn2 in H1. apply le_S. apply H1.\nQed.\n\nLemma le_trance : forall n1 n2 n3,\n    n1 <= n2 -> n2 <= n3 -> n1 <= n3.\nProof.\n  intros. generalize dependent n3. induction H; intros; auto.\n  destruct H0. apply IHle. apply le_S. apply le_n.\n  apply IHle. apply le_S. apply le_S_n. apply le_S. apply H0.\nQed.\n\nFrom Coq Require Import Strings.String.\n\nLemma fv_le : forall t n,\n  fv_card t (n + 1) <= fv_card t n.\nProof.\n  induction t; intros; simpl; auto.\n  destruct (leb n0 n) eqn:IH1; destruct (leb (n0 + 1) n) eqn:IH2; auto.\n  apply le_leb in IH2. rewrite PeanoNat.Nat.add_1_r in IH2. apply Le.le_Sn_le in IH2. apply leb_le in IH2. rewrite IH1 in IH2. inversion IH2.\n  apply PeanoNat.Nat.add_le_mono; auto.\nQed.\n\nLemma e5_3_3 : forall t,\n    fv_card t 0 <= (size (t)).\nProof.\n  induction t; simpl; auto.\n  -\n    destruct (leb 0 n); auto.\n  -\n    apply le_trance with (fv_card t 0); auto. apply (fv_le t 0).\n  -\n    apply PeanoNat.Nat.add_le_mono; auto.\nQed.\n", "meta": {"author": "NeM-T", "repo": "Formalizing-TaPL", "sha": "2a4dba29d0850a7494c7fd52c0daf4bbb3879691", "save_path": "github-repos/coq/NeM-T-Formalizing-TaPL", "path": "github-repos/coq/NeM-T-Formalizing-TaPL/Formalizing-TaPL-2a4dba29d0850a7494c7fd52c0daf4bbb3879691/untype_lambda/chap6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7069235306590426}}
{"text": "\n\n\n\n(* This file contains boolean functions corresponding to the different predicates\n   commonly used in reasoning about sets. These boolean functions are connected to\n   the corresponding predicates using the reflection lemmas (similar to ssreflect).\n   The type of elements in the set (or lists) are from eqType.\n\n\n  Following are the boolean functions and their corresponding predicated  \n \n  Propositions                        Boolean functions      Connecting Lemma \n  In a l                       <->    memb a l                membP\n  IN a b l                     <->    memb2 a b l             memb2p\n  NoDup l                      <->    noDup l                nodupP\n  Empty l                      <->    is_empty l             emptyP\n  Subset s s'                  <->    subset s s'            subsetP\n  Equal s s'                   <->    equal s s'             equalP\n  Exists P l                   <->    existsb f l            ExistsP\n  exists x, (In x l /\\ P x)    <->    existsb f l            existsP\n  exists x, (In x l /\\ f x)    <->    existsb f l            existsbP\n  Forall P l                   <->    forallb f l            ForallP\n  forall x, (In x l -> P x)    <->    forallb f l            forallP\n  forall x, (In x l -> f x)    <->    forallb f l            forallbP \n\n  We also define index function (idx a l), which returns the location of an element\n  a in the list l. \n\n  forall_em_exists f: (forall x, In x l -> f x) \\/ (exists x, In x l /\\ ~ f x).  \n  exists_em_forall f: (exists x, In x l /\\ f x) \\/ (forall x, In x l -> ~ f x).\n\n  Definition forall_xyb g l := forallb (fun x => (forallb ( fun y=> g x y) l)) l.\n  Definition forall_yxb g l := forallb (fun y => (forallb ( fun x=> g x y) l)) l.\n\n  forall_xyP g l: reflect (forall x y, In x l-> In y l-> g x y) (forall_xyb g l).\n  forall_yxP g l: reflect (forall x y, In x l-> In y l-> g x y) (forall_yxb g l).\n\n   ------------*)\n\n\nFrom Coq Require Export ssreflect  ssrbool Lists.List.\nRequire Export SetSpecs GenReflect DecType.\nSet Implicit Arguments.\n\nSection SetReflections.\nContext { A:eqType }. (* to declare A as implicit for all functions in this section *)\nLemma decA: forall x y:A, {x=y}+{x<>y}.\nProof. eauto. Qed.\n\n\n\n  (*--------- set_mem (boolean function)  and its specification ---------*)\n  Fixpoint memb (a:A)(l: list A){struct l}: bool:=\n    match l with\n    | nil =>false\n    | a1::l1 => (a== a1) ||  memb a l1\n    end.\n  \n  (* fix In (a : A) (l : list A) {struct l} : Prop :=\n  match l with\n  | nil => False\n  | b :: m => b = a \\/ In a m\n  end *)\n\n  Lemma set_memb_correct1: forall (a:A)(l:list A), memb a l -> In a l.\n  Proof. { intros a l. induction l.\n         { simpl;auto. }\n         { simpl.  move /orP. intro H; destruct H.\n           move /eqP in H;symmetry in H; left;auto.\n           right; auto.  } } Qed.\n  Lemma set_memb_correct2: forall (a:A)(l:list A), In a l ->  memb a l.\n  Proof. { intros a l. induction l.\n         { simpl;auto. }\n         { simpl.  intro H. apply /orP. destruct H.\n           left; apply /eqP; symmetry; auto. \n           right; auto.  } } Qed. \n  \n  Lemma membP a l: reflect (In a l) (memb  a l).\n  Proof. apply reflect_intro. split.\n         apply set_memb_correct2. apply set_memb_correct1. Qed.\n  \n  Hint Resolve membP : core.\n  Hint Immediate set_memb_correct1 set_memb_correct2: core.\n\n  Lemma memb_prop1 (a:A)(l s: list A): l [<=] s -> In a l -> memb a l = memb a s.\n  Proof. intros H H1. assert (H2: In a s); auto. Qed.\n  Lemma memb_prop2 (a:A)(l s: list A): l [<=] s -> ~ In a s -> memb a l = memb a s.\n  Proof. intros H H1. assert (H2: ~ In a l); auto. Qed.\n  Lemma memb_prop3 (a:A)(l s: list A): l [=] s -> memb a l = memb a s.\n  Proof. { intro h. destruct h as [h1 h2]. cut (In a l \\/ ~ In a l).\n         intro h3.  destruct h3 as [h3 | h3].\n         apply memb_prop1;auto. apply memb_prop2;auto.\n         eapply reflect_EM;auto. } Qed.\n\n  Hint Resolve memb_prop1 memb_prop2 memb_prop3: core.\n  \n\nLemma In_EM: forall (a:A) (x: list A), In a x \\/ ~ In a x.\nProof. eauto.  Qed.\n\nDefinition IN := fun (x:A)(y:A)(l:list A) => In x l /\\ In y l.\nDefinition memb2 x y l := memb  x l && memb y l.\n\nLemma memb2P a b x : reflect (IN a b x) (memb2 a b x).\nProof. { apply reflect_intro. split.\n       { unfold IN; unfold memb2. intro H; destruct H.\n         apply /andP. split; apply /membP; auto. }\n       { unfold IN; unfold memb2. move /andP.\n         intro H; split; apply /membP; tauto. } } Qed.\n\nLemma memb2_comute (x y: A)(l: list A): memb2 x y l = memb2 y x l.\nProof. unfold memb2. case (memb  x l);case (memb y l); simpl;auto. Qed.\n\nHint Resolve memb2P: core.\nLemma IN_EM: forall (a b:A)(x:list A), IN a b x \\/ ~ IN a b x.\nProof.  eauto. Qed.\n\nLemma memb_prop4 (x y: A)(l s: list A): l [=] s -> memb2 x y l = memb2 x y s.\nProof. intro h. assert (h1: s [=] l). auto. unfold memb2.\n       replace (memb x s) with (memb x l). replace (memb y s) with (memb y l).\n       auto. all: auto. Qed.\nLemma memb2_elim (x y: A)(l: list A): memb2 x y l = false -> (~ In x l \\/ ~ In y l).\nProof. { intro h7. unfold memb2 in h7.\n       destruct (memb x l) eqn:h7x; destruct (memb y l) eqn:h7y; simpl in h7;\n           move /membP in h7x; move /membP in h7y.\n       inversion h7. right;auto. all: left;auto. } Qed.\n\n\n\n(*---------- noDup  (boolean function) and its specification ---------*)\nFixpoint noDup (x: list A): bool:=\n  match x with\n    |nil => true\n    |h :: x1 => if memb h x1 then false else noDup x1\n  end.\nLemma NoDup_iff_noDup l: NoDup l <-> noDup l. \nProof. { split. \n       { induction l.  auto.\n       intro H; inversion H;  simpl.\n       replace (memb a l) with false; auto. } \n       { induction l. constructor.\n       simpl. case (memb a l) eqn: H1. discriminate.  intro H2.\n       constructor. move /membP.  rewrite H1.  auto. tauto. }  } Qed.\nLemma noDup_intro l: NoDup l -> noDup l.\nProof. apply NoDup_iff_noDup. Qed.\nLemma noDup_elim l: noDup l -> NoDup l.\nProof. apply NoDup_iff_noDup. Qed.\n\nHint Immediate noDup_elim noDup_intro: core.\n\nLemma nodupP l: reflect (NoDup l) (noDup l).\nProof. {cut (NoDup l <-> noDup l). eauto. apply NoDup_iff_noDup. } Qed.\n\nHint Resolve nodupP : core.\n\nLemma NoDup_EM: forall l:list A, NoDup l \\/ ~ NoDup l.\nProof. eauto. Qed.\nLemma NoDup_dec: forall l:list A, {NoDup l} + { ~ NoDup l}.\nProof. eauto. Qed.\n\nLemma nodup_spec: forall l:list A, NoDup (nodup decA l).\nProof. intros. eapply NoDup_nodup. Qed.\n\n\n(*---------- is_empty (boolean function) and its specification -----------------*)\nDefinition is_empty (x:list A) : bool := match x with\n                                 | nil => true\n                                 | _ => false\n                                      end.\n\n\nLemma emptyP l : reflect (Empty l) (is_empty l).\nProof. { destruct l eqn:H. simpl.  constructor. unfold Empty; auto.\n       simpl. constructor. unfold Empty.  intro H1. specialize (H1 e).\n       apply H1. auto.  } Qed. \nHint Resolve emptyP : core.\nLemma Empty_EM (l:list A): Empty l \\/ ~ Empty l.\n  Proof. solve_EM. Qed.  \nLemma Empty_dec (l: list A): {Empty l} + {~Empty l}.\nProof. solve_dec. Qed.\nLemma empty_intro l : Empty l -> is_empty l.\nProof. move /emptyP. auto. Qed.\nLemma empty_elim l: is_empty l -> Empty l.\nProof. move /emptyP. auto. Qed.\n\nHint Immediate empty_elim empty_intro: core.\n\n(*----------- subset (boolean function) and its specification--------------------*)\nFixpoint subset (s s': list A): bool:=\n  match s with\n  |nil => true\n  | a1 :: s1=> memb a1 s' && subset s1 s'\n  end.\n\nLemma subsetP s s': reflect (Subset s s') (subset s s').\nProof. { induction s. simpl. constructor. intro. intros  H. absurd (In a nil); auto.\n       apply reflect_intro. split.\n       { intro H.  cut (In a s' /\\ Subset s s'). Focus 2. split; eauto. simpl.\n         intro H1; destruct H1 as [H1 H2].\n         apply /andP. split. apply /membP;auto. apply /IHs;auto.  }\n       { simpl.  move /andP. intro H; destruct H as [H1 H2]. unfold Subset.\n         intros a0 H3. cut (a0= a \\/ In a0 s). intro H4; destruct H4 as [H4 | H5].\n         rewrite H4. apply /membP;auto. cut (Subset s s'). intro H6. auto. apply /IHs;auto.\n         eauto.   }  } Qed.\n\nHint Resolve subsetP: core.\nLemma Subset_EM (s s': list A): Subset s s' \\/ ~ Subset s s'.\nProof. solve_EM. Qed.\nLemma Subset_dec (s s': list A): {Subset s s'} + {~ Subset s s'}.\nProof. solve_dec. Qed.\n\nLemma subset_intro s s': Subset s s' -> subset s s'.\nProof. move /subsetP. auto. Qed.\nLemma subset_elim s s': subset s s' -> Subset s s'.\nProof. move /subsetP. auto. Qed.\n\nHint Immediate subset_intro subset_elim: core.\n\n(*----------- equal (boolean function) and its specifications--------------------*)\nDefinition equal (s s':list A): bool:= subset s s' && subset s' s.\nLemma equalP s s': reflect (Equal s s') (equal s s').\nProof. { apply reflect_intro.  split.\n       { intro H. cut (Subset s s'/\\ Subset s' s).\n       Focus 2. auto. intro H1. unfold equal.\n       apply /andP. split; apply /subsetP; tauto. }\n       { unfold equal. move /andP. intro H. apply Equal_intro; apply /subsetP; tauto. }\n       } Qed.\n\nHint Resolve equalP: core.\nLemma Equal_EM (s s': list A): Equal s s' \\/ ~ Equal s s'.\nProof. solve_EM. Qed.\nLemma Equal_dec (s s': list A): {Equal s s'} + {~ Equal s s'}.\nProof. solve_dec. Qed.\n\nLemma equal_intro s s': Equal s s' -> equal s s'.\nProof. move /equalP. auto. Qed.\nLemma equal_elim s s': equal s s' -> Equal s s'.\nProof. move /equalP. auto. Qed.\n\nHint Immediate equal_elim equal_intro: core.\n\n\n(*----------- existsb (boolean function) and its specifications-------------------*)\n  \n  (* fix existsb (l : list A) : bool :=\n  match l with\n  | nil => false\n  | a :: l0 => f a || existsb l0\n  end *)\n  \n  (* Inductive Exists (A : Type) (P : A -> Prop) : list A -> Prop :=\n    Exists_cons_hd : forall (x : A) (l : list A), P x -> Exists P (x :: l)\n  | Exists_cons_tl : forall (x : A) (l : list A), Exists P l -> Exists P (x :: l) *)\n\n  Lemma ExistsP P f l: (forall x:A, reflect (P x) (f x) ) -> reflect (Exists P l) (existsb f l).\n  Proof.  { intro H. eapply reflect_intro.\n         induction l. simpl. constructor; intro H1; inversion H1.\n         split.\n         { intro H1.  inversion H1. simpl. apply /orP; left; apply /H;auto.\n           simpl. apply /orP; right; apply /IHl; auto. }\n         { simpl. move /orP. intro H1; destruct H1 as [H1| H2]. constructor. apply /H; auto.\n           eapply Exists_cons_tl. apply /IHl; auto.  } } Qed.\n  \n  Hint Resolve ExistsP: core.      \n  \n  (* Exists_dec\n     : forall (A : Type) (P : A -> Prop) (l : list A),\n       (forall x : A, {P x} + {~ P x}) -> {Exists P l} + {~ Exists P l} *)\n  \n   Lemma Exists_EM P l:(forall x:A, P x \\/ ~ P x )-> Exists P l \\/ ~ Exists P l.\n  Proof. { intros H. induction l. right. intro H1.  inversion H1.\n         cut( P a \\/ ~ P a).  intro Ha. cut (Exists P l \\/ ~ Exists P l). intro Hl.\n         { destruct Ha as [Ha1 | Ha2]; destruct Hl as [Hl1 | Hl2].\n           left. constructor;auto. left; constructor;auto.\n           left.  apply Exists_cons_tl;auto.\n           right. intro H1. inversion H1. all:contradiction. }\n         all: auto.  } Qed.\n  \n  \n  (* Exists_exists\n     : forall (A : Type) (P : A -> Prop) (l : list A),\n       Exists P l <-> (exists x : A, In x l /\\ P x) *)\n  \n  Lemma existsP P f l: (forall x:A, reflect (P x)(f x))-> reflect (exists x, In x l /\\ P x)(existsb f l).\n  Proof. { intro H. eapply iffP with (P:= Exists P l). eapply ExistsP. apply H.\n           all: apply Exists_exists. } Qed.\n  Hint Resolve existsP: core.\n  Lemma existsbP (f:A->bool) l: reflect (exists x, In x l /\\ f x)(existsb f l).\n  Proof. apply existsP. intros. apply idP. Qed.\n  \n  Lemma exists_dec P l:\n    (forall x:A, {P x} + {~ P x})-> { (exists x, In x l /\\ P x) } + { ~ exists x, In x l /\\ P x}.\n  Proof. { intros. cut({Exists P l}+{ ~ Exists P l}). intro H;destruct H as [Hl |Hr].\n         left. apply Exists_exists;auto.\n         right;intro H1; apply Hr; apply Exists_exists;auto.\n         eapply Exists_dec;auto.  } Qed.\n  \n  Lemma exists_EM P l:\n     (forall x:A, P x \\/ ~ P x) ->  (exists x, In x l /\\ P x) \\/  ~ (exists x, In x l /\\ P x) .\n  Proof. { intro H. cut(Exists P l \\/ ~ Exists P l).\n         intro H1; destruct H1 as [H1l| H1r]. left. eapply Exists_exists;auto.\n         right; intro H2;apply H1r; apply Exists_exists;auto. eapply Exists_EM;auto. } Qed. \n  \n    \n(*----------- forallb ( boolean function) and its specifications----------------- *)\n \n (* fix forallb (l : list A) : bool :=\n    match l with\n     | nil => true\n     | a :: l0 => f a && forallb l0\n    end *)\n \n (* Inductive Forall (A : Type) (P : A -> Prop) : list A -> Prop :=\n    Forall_nil : Forall P nil\n  | Forall_cons : forall (x : A) (l : list A), P x -> Forall P l -> Forall P (x :: l) *)\n\n Lemma ForallP P f l: (forall x:A, reflect (P x) (f x) ) -> reflect (Forall P l) (forallb f l).\n Proof.   { intro H. eapply reflect_intro.\n         induction l. simpl. constructor; intro H1; inversion H1; auto.\n         split.\n         { intro H1.  inversion H1. simpl. apply /andP. split.  apply /H;auto.\n           apply /IHl; auto. }\n         { simpl. move /andP. intro H1; destruct H1 as [H1 H2]. constructor. apply /H; auto.\n           apply /IHl; auto. } } Qed.\n \n Hint Resolve ForallP: core.\n Lemma Forall_EM P l:(forall x:A, P x \\/ ~ P x ) -> Forall P l \\/ ~ Forall P l.\n Proof.  { intros H. induction l. left. constructor. \n         cut( P a \\/ ~ P a).  intro Ha. cut (Forall P l \\/ ~ Forall P l). intro Hl.\n         { destruct Ha as [Ha1 | Ha2]; destruct Hl as [Hl1 | Hl2].\n           left. constructor;auto.\n           right; intro H1;apply Hl2; inversion H1;auto.\n           right; intro H1; apply Ha2; inversion H1; auto.\n           right. intro H1. apply Ha2. inversion H1;auto.  }\n         all: auto.  } Qed.\n Lemma forallP P f l: (forall x:A, reflect (P x) (f x) ) -> reflect (forall x, In x l -> P x) (forallb f l).\n Proof. { intro H. eapply iffP with (P:= Forall P l). eapply ForallP. apply H.\n          all: apply Forall_forall. } Qed.\n\n Lemma forallbP (f: A->bool) (l: list A): reflect (forall x:A, In x l -> (f x)) (forallb f l).\n Proof. apply forallP. intros. apply idP. Qed.\n \n Lemma forall_dec P  l:\n   (forall x:A, {P x} + { ~ P x}) -> { (forall x, In x l -> P x) } + { ~ forall x, In x l -> P x}.\n Proof. { intros. cut({Forall P l} + {~ Forall P l}).\n          intro H;destruct H as [Hl |Hr].\n          left. apply Forall_forall;auto.\n          right;intro H1; apply Hr; apply Forall_forall;auto.\n          eapply Forall_dec; auto.  } Qed.\n Lemma forall_EM P l:\n   (forall x:A, P x \\/ ~ P x )->  (forall x, In x l -> P x)  \\/  ~ (forall x, In x l -> P x).\n Proof. { intros H. cut(Forall P l \\/ ~ Forall P l).\n          intro H1; destruct H1 as [H1l| H1r]. left. eapply Forall_forall;auto.\n          right; intro H2;apply H1r; apply Forall_forall;auto. eapply Forall_EM;auto. } Qed. \n \n Lemma forall_exists_EM P l:\n   (forall x:A, P x \\/ ~ P x) -> (forall x, In x l -> P x) \\/ (exists x, In x l /\\ ~ P x).\n Proof. { intros. cut(Forall P l \\/ ~ Forall P l).  \n        Focus 2. eapply Forall_EM. auto.\n        intro H1; destruct H1 as [Hl | Hr].\n        left. apply Forall_forall. auto. right.\n        cut(Exists (fun x : A => ~ P x) l). eapply Exists_exists.\n        apply Exists_Forall_neg. all:auto. } Qed. \n Lemma exists_forall_EM P l:\n   (forall x:A, P x \\/ ~ P x)-> (exists x, In x l /\\ P x) \\/ (forall x, In x l ->  ~ P x).\n   Proof.  { intros. cut(Exists P l \\/ ~ Exists P l).  \n        Focus 2. eapply Exists_EM. auto.\n        intro H1; destruct H1 as [Hl | Hr].\n        left. apply Exists_exists. auto. right.\n        cut(Forall (fun x : A => ~ P x) l). eapply Forall_forall.\n        apply Forall_Exists_neg. all:auto. } Qed.\n   Lemma forall_em_exists (f: A-> bool) (l: list A): (forall x, In x l -> f x) \\/ (exists x, In x l /\\ ~ f x).\n   Proof. apply forall_exists_EM; intro x;destruct (f x); auto. Qed.\n   Lemma exists_em_forall (f: A-> bool) (l: list A): (exists x, In x l /\\ f x) \\/ (forall x, In x l ->  ~ f x).\n   Proof. apply exists_forall_EM; intro x; destruct (f x); auto. Qed.\n     \nEnd SetReflections.\n\n \n\nHint Resolve membP memb2P nodupP emptyP subsetP equalP\n     existsP existsbP ExistsP ForallP forallP forallbP memb2_comute: core.\nHint Resolve forall_exists_EM exists_forall_EM: core.\nHint Resolve forall_em_exists exists_em_forall: core.\n\nHint Immediate set_memb_correct1 set_memb_correct2  memb2_elim: core.\nHint Resolve memb_prop1 memb_prop2 memb_prop3 memb_prop4: core.\nHint Immediate noDup_elim noDup_intro: core.\nHint Immediate empty_elim empty_intro: core.\nHint Immediate subset_intro subset_elim: core.\nHint Immediate equal_elim equal_intro: core.\n\n\n\n\nSection MoreReflection.\n  Context { A:eqType }.\n\n  Definition forall_xyb (g:A->A->bool)(l:list A):=  (forallb (fun x=> (forallb (fun y => g x y) l )) l).\n  Definition forall_yxb (g:A->A->bool)(l:list A) :=  (forallb (fun y=> (forallb (fun x => g x y) l )) l).\n  \n  Lemma forall_xyP (g:A->A->bool) (l:list A):\n    reflect (forall x y, In x l-> In y l-> g x y)  (forall_xyb g l).\n  Proof. eapply iffP with (P:= (forall x, In x l -> (forall y, In y l -> g x y))).\n         unfold forall_xyb; auto. all: auto. Qed.\n  Lemma forall_yxP (g:A->A->bool) (l:list A):\n    reflect (forall x y, In x l-> In y l-> g x y)  (forall_yxb g l).\n  Proof. eapply iffP with (P:= (forall y, In y l -> (forall x, In x l -> g x y))).\n         unfold forall_yxb; auto. all: auto. Qed.\n  \nEnd MoreReflection.\n\nHint Resolve forall_xyP forall_yxP: core.\n\n\n", "meta": {"author": "Abhishek-TIFR", "repo": "List-Set", "sha": "f22e828ca348c8317a5235491e7e1dac848a691f", "save_path": "github-repos/coq/Abhishek-TIFR-List-Set", "path": "github-repos/coq/Abhishek-TIFR-List-Set/List-Set-f22e828ca348c8317a5235491e7e1dac848a691f/SetReflect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7069096008959139}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Export IndProp.\nRequire Export Logic.\nRequire Coq.omega.Omega.\n\nPrint ev.\n\nCheck ev_SS.\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nPrint ev_4.\n\nCheck (ev_SS 2 (ev_SS 0 ev_0)).\n\nTheorem ev_4' : ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\nDefinition ev_4''' : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\nPrint ev_4.\n\nPrint ev_4'.\n\nPrint ev_4''.\n\nPrint ev_4'''.\n\nTheorem ev_8 : ev 8.\nProof.\n  repeat apply ev_SS. apply ev_0.\nQed.\n\nDefinition ev_8' : ev 8 :=\n  ev_SS 6 (ev_SS 4 (ev_SS 2 (ev_SS 0 ev_0))).\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\nDefinition ev_plus4'' (n : nat) (H : ev n)\n  : ev (4 + n) :=\n  ev_SS (S (S n)) (ev_SS n H).\n\nCheck ev_plus4''.\n\n\nDefinition ev_plus2 : Prop :=\n  forall n, forall (E : ev n), ev (n + 2).\n\nDefinition ev_plus2' : Prop :=\n  forall n, forall (_ : ev n), ev (n + 2).\n\nDefinition ev_plus2'' : Prop :=\n  forall n, ev n -> ev (n + 2).\n\nDefinition add1 : nat -> nat.\nintro n.\nShow Proof.\napply S.\nShow Proof.\napply n.\nDefined.\n\nPrint add1.\n\nCompute add1 2.\n\nModule Props.\n\nModule And.\n\nInductive and (P Q : Prop) : Prop :=\n  | conj : P -> Q -> and P Q.\n\nEnd And.\n\nPrint prod.\n\n\nLemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\nProof.\n  intros P Q. split.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\n  - intros [HP HQ]. split.\n    + apply HQ.\n    + apply HP.\nQed.\n\nDefinition and_comm'_aux P Q (H : P /\\ Q) :=\n  match H with\n  | conj HP HQ => conj HQ HP\n  end.\n\nDefinition and_comm' P Q : P /\\ Q <-> Q /\\ P :=\n  conj (and_comm'_aux P Q) (and_comm'_aux Q P).\n\nDefinition conj_fact_aux P R (H : P /\\ R) :=\n  match H with\n  | conj HP HQ => conj HP HQ\n  end.\n\nDefinition conj_fact : \n  forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R := \n  fun P => fun Q => fun R => fun PQ => fun QR =>\n   match PQ with\n   | conj P Q => match QR with\n                  | conj Q R => conj P R\n                  end\n   end.\n\nModule Or.\n\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n\nEnd Or.\n\nDefinition or_comm : forall P Q, P \\/ Q -> Q \\/ P :=\n  fun _ => fun _ => fun PQ => \n      match PQ with\n      | or_introl P => or_intror P\n      | or_intror Q => or_introl Q\n      end.\n\nModule Ex.\n\nInductive ex { A : Type } (P : A -> Prop) : Prop :=\n  | ex_intro : forall x : A, P x -> ex P.\n\nEnd Ex.\n\nCheck ex (fun n => ev n).\n\nDefinition some_nat_is_even : exists n, ev n :=\n  ex_intro ev 4 (ev_SS 2 (ev_SS 0 ev_0)).\n\nDefinition ex_ev_Sn : ex (fun n => ev (S n)) :=\n  ex_intro (fun n => ev (S n)) 1 (ev_SS 0 ev_0).\n\nInductive True : Prop :=\n  | I : True.\n\nInductive False : Prop :=.\n\nEnd Props.\n\nModule MyEquality.\n\nInductive eq { X : Type } : X -> X -> Prop :=\n  | eq_refl : forall x, eq x x.\n\nNotation \"x = y\" := (eq x y)\n                    (at level 70, no associativity)\n                    : type_scope.\n\n\nLemma four : 2 + 2 = 1 + 3.\nProof.\n  apply eq_refl.\nQed.\n\nDefinition four' : 2 + 2 = 1 + 3 :=\n  eq_refl 4.\n\nDefinition singleton : forall (X : Type) (x : X),\n  [] ++ [x] = x :: [] :=\n  fun (X : Type) (x : X) => eq_refl [x].\n\nEnd MyEquality.\n\nLemma equality__leibniz_equality :\n  forall (X : Type) (x y : X),\n  x = y -> forall P : X -> Prop, P x -> P y.\nProof.\n  intros X x y H1 P H2. rewrite -> H1 in H2.\n  apply H2.\nQed.\n\n\n", "meta": {"author": "yanhick", "repo": "coq-exercises", "sha": "75cacdb3bf7d1e2f4a2dd6b8fe87b02041cf345d", "save_path": "github-repos/coq/yanhick-coq-exercises", "path": "github-repos/coq/yanhick-coq-exercises/coq-exercises-75cacdb3bf7d1e2f4a2dd6b8fe87b02041cf345d/LF/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.706909575682988}}
{"text": "Require Export ZArith.\nRequire Export Arith.\nRequire Import Lia.\n\nFixpoint check_range (v:Z)(r:nat)(sr:Z){struct r} : bool :=\n  match r with\n    O => true\n  | S r' =>\n    match (v mod sr)%Z with\n      Z0 => false\n    | _ => check_range v r' (Z.pred sr)\n    end\n  end.\n\nDefinition check_primality (n:nat) :=\n  check_range (Z_of_nat n)(pred (pred n))(Z_of_nat (pred n)).\n\nTheorem verif_divide :\n    forall m p:nat, 0 < m -> 0 < p ->\n    (exists q:nat, m = q*p) -> (Z_of_nat m mod Z_of_nat p = 0)%Z.\nProof.\n intros m p Hltm Hltp (q, Heq); rewrite Heq.\n rewrite inj_mult.\n replace (Z_of_nat q * Z_of_nat p)%Z with (0 + Z_of_nat q * Z_of_nat p)%Z;\n    try ring.\n rewrite Z_mod_plus; auto.\n lia.\nQed.\n\nTheorem divisor_smaller :\n    forall m p:nat, 0 < m -> forall q:nat, m = q*p -> q <= m.\nProof.\n intros m p Hlt; case p.\n -  intros q Heq; rewrite Heq in Hlt; rewrite mult_comm in Hlt.\n     elim (lt_irrefl 0);exact Hlt.\n -  intros p' q; case q.\n    +  intros Heq; rewrite Heq in Hlt.\n       elim (lt_irrefl _ Hlt).\n    + intros q' Heq; rewrite Heq.\n      rewrite mult_comm; simpl; auto with arith.\nQed.\n\nTheorem Zabs_nat_0 : forall x:Z, Z.abs_nat x = 0 -> (x = 0)%Z.\nProof.\n intros x; case x.\n -  simpl; auto.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\n -  intros p Heq; elim (lt_irrefl 0).\n    pattern 0 at 2; rewrite <- Heq.\n    simpl; apply lt_O_nat_of_P.\nQed.\n\nTheorem Z_to_nat_and_back :\n forall x:Z, (0 <= x)%Z -> (Z.of_nat (Z.abs_nat x))=x.\nProof.\n intros x; case x.\n - reflexivity. \n -  intros p Hd; elim p.\n   +  unfold Z.abs_nat; intros p' Hrec; rewrite nat_of_P_xI.\n      rewrite inj_S,  inj_mult,  Zpos_xI.\n      unfold Z.succ; rewrite Hrec;  simpl; auto.\n   +  unfold Z.abs_nat; intros p' Hrec; rewrite nat_of_P_xO.\n      rewrite inj_mult,  Zpos_xO.\n      unfold Z.succ; rewrite Hrec; simpl; auto.\n   +  simpl; auto.\n \n -  intros p' Hd; elim Hd;auto.\nQed.\n\nTheorem  check_range_correct :\n  forall (v:Z)(r:nat)(rz:Z),\n  (0 < v)%Z -> Z_of_nat (S r) = rz -> check_range v r rz = true ->\n  ~(exists k:nat, k <= S r /\\ k <> 1 /\\ \n                       (exists q:nat, Z.abs_nat v = q*k)).\nProof.\n intros v r; elim r.\n -  intros rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n   +  intros (Hle, (Hne1, (q, Heq))).\n      rewrite mult_comm in Heq; simpl in Heq.\n      rewrite (Zabs_nat_0 _ Heq) in Hlt.\n      elim (Z.lt_irrefl 0); assumption.\n \n   + intros k' (Hle, (Hne1, (q, Heq))).\n     inversion Hle.\n     *  assert (H':k'=0) by  assumption.\n        rewrite H' in Hne1; elim Hne1;auto.\n     *  assert (H': S k' <= 0) by  assumption.\n        inversion H'.\n\n -  intros r' Hrec rz Hlt H1 H2 Hex; case Hex; intros k; case k.\n    intros (Hle, (Hne1, (q, Heq))).\n    rewrite mult_comm in Heq; simpl in Heq.\n    rewrite (Zabs_nat_0 _ Heq) in Hlt.\n    elim (Z.lt_irrefl 0); assumption.\n    intros k' (Hle, (Hne1, (q, Heq))).\n    inversion Hle.\n    rewrite <- H1 in H2. \n    rewrite <- (Z_to_nat_and_back v) in H2.\n    assert (Hmod:(Z.of_nat (Z.abs_nat v) mod Z.of_nat (S (S r')) = 0)%Z).\n    +  apply verif_divide.\n       replace 0 with (Z.abs_nat 0%Z).\n       apply Zabs_nat_lt.\n       lia.\n       simpl; auto.\n       auto with arith.\n       exists q.\n       assert (H': k' = S r') by  assumption.\n       rewrite <- H'.\n       assumption.\n    +  unfold check_range in H2.\n       rewrite Hmod in H2.\n       discriminate H2.\n      + lia.\n      + unfold check_range in H2; fold check_range in H2.\n        case_eq ((v mod rz)%Z).\n        *  intros Heqmod; rewrite Heqmod in H2; discriminate H2.\n        *  intros pmod Heqmod; rewrite Heqmod in H2;  elim (Hrec (Z.pred rz) Hlt).\n           rewrite <- H1; repeat rewrite inj_S;  rewrite <- Zpred_succ; auto. \n          assumption.\n          exists (S k'); repeat split;auto.\n          exists q; assumption.\n\n        * intros p Hmod; elim (Z_mod_lt v rz).\n          rewrite Hmod; unfold Z.le; simpl; intros Hle'; elim Hle';auto.\n          rewrite <- H1; rewrite inj_S; unfold Z.succ;\n            generalize (Zle_0_nat (S r')).\n          intros; lia.\nQed.\n\nTheorem nat_of_P_Psucc : \n forall p:positive, nat_of_P (Pos.succ p) = S (nat_of_P p).\nProof.\n intros p; elim p.\n - simpl; intros p'; rewrite nat_of_P_xO.\n   intros Heq; rewrite Heq.\n   rewrite nat_of_P_xI; ring.\n- intros p' Heq; simpl; rewrite nat_of_P_xI; rewrite nat_of_P_xO;auto.\n-  auto.\nQed.\n\nTheorem nat_to_Z_and_back:\n forall n:nat, Z.abs_nat (Z_of_nat n) = n.\nProof.\n intros n; elim n.\n -  auto.\n - intros n'; simpl; case n'.\n  +  simpl; auto.\n  +  intros n''; simpl; rewrite nat_of_P_Psucc; intros Heq; rewrite Heq; auto.\nQed.\n\nTheorem check_correct :\n  forall p:nat, 0 < p -> check_primality p = true ->\n  ~(exists k:nat, k <> 1 /\\ k <> p /\\ (exists q:nat, p = q*k)).\nProof.\n unfold lt; intros p Hle; elim Hle.\n -  intros Hcp (k, (Hne1, (Hne1bis, (q, Heq)))); rewrite mult_comm in Heq.\n    assert (Hle' : k < 1).\n    +  elim (le_lt_or_eq k 1); try(intuition; fail).\n       apply divisor_smaller with (2:= Heq); auto.\n    +  case_eq k.\n       *  intros Heq'; rewrite Heq' in Heq; simpl in Heq; discriminate Heq.\n       *  intros; lia.\n -  intros p' Hlep' Hrec; unfold check_primality.\n    assert (H':(exists p'':nat, p' = (S p''))).\n   +  inversion Hlep'.  \n      *     exists 0; auto.\n      *  eapply ex_intro;eauto.\n   +  elim H'; intros p'' Hp''; rewrite Hp''.\n      repeat rewrite <- pred_Sn.\n      intros Hcr Hex;  elim check_range_correct with (3:= Hcr).\n     *  rewrite inj_S; generalize (Zle_0_nat (S p'')).\n        intros; lia.\n     *  auto.\n     *  elim Hex; intros k (Hne1, (HneSSp'', (q, Heq))); exists k.\n       split.\n       assert (HkleSSp'': k <= S (S p'')).\n       apply (divisor_smaller (S (S p'')) q); auto with arith.\n       rewrite mult_comm; assumption.\n       lia.\n       split.\n       assumption.\n       exists q; now  rewrite nat_to_Z_and_back.\nQed.\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch16_proof_by_reflection/SRC/verif_divide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7068993480833146}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\nRequire Import List Compare_dec EqNat Decidable ListDec. Require Fin.\nSet Implicit Arguments.\n\n\n\nDefinition Injective {A B} (f : A->B) :=\nforall x y, f x = f y -> x = y.\n\nDefinition Surjective {A B} (f : A->B) :=\nforall y, exists x, f x = y.\n\nDefinition Bijective {A B} (f : A->B) :=\nexists g:B->A, (forall x, g (f x) = x) /\\ (forall y, f (g y) = y).\n\n\n\nDefinition Full {A:Type} (l:list A) := forall a:A, In a l.\nDefinition Finite (A:Type) := exists (l:list A), Full l.\n\n\n\nDefinition Listing {A:Type} (l:list A) := NoDup l /\\ Full l.\nDefinition Finite' (A:Type) := exists (l:list A), Listing l.\n\nLemma Finite_alt A (d:decidable_eq A) : Finite A <-> Finite' A.\nProof. hammer_hook \"FinFun\" \"FinFun.Finite_alt\".  \nsplit.\n- intros (l,F). destruct (uniquify d l) as (l' & N & I).\nexists l'. split; trivial.\nintros x. apply I, F.\n- intros (l & _ & F). now exists l.\nQed.\n\n\n\nLemma Injective_map_NoDup A B (f:A->B) (l:list A) :\nInjective f -> NoDup l -> NoDup (map f l).\nProof. hammer_hook \"FinFun\" \"FinFun.Injective_map_NoDup\".  \nintros Ij. induction 1 as [|x l X N IH]; simpl; constructor; trivial.\nrewrite in_map_iff. intros (y & E & Y). apply Ij in E. now subst.\nQed.\n\nLemma Injective_list_carac A B (d:decidable_eq A)(f:A->B) :\nInjective f <-> (forall l, NoDup l -> NoDup (map f l)).\nProof. hammer_hook \"FinFun\" \"FinFun.Injective_list_carac\".  \nsplit.\n- intros. now apply Injective_map_NoDup.\n- intros H x y E.\ndestruct (d x y); trivial.\nassert (N : NoDup (x::y::nil)).\n{ repeat constructor; simpl; intuition. }\nspecialize (H _ N). simpl in H. rewrite E in H.\ninversion_clear H; simpl in *; intuition.\nQed.\n\nLemma Injective_carac A B (l:list A) : Listing l ->\nforall (f:A->B), Injective f <-> NoDup (map f l).\nProof. hammer_hook \"FinFun\" \"FinFun.Injective_carac\".  \nintros L f. split.\n- intros Ij. apply Injective_map_NoDup; trivial. apply L.\n- intros N x y E.\nassert (X : In x l) by apply L.\nassert (Y : In y l) by apply L.\napply In_nth_error in X. destruct X as (i,X).\napply In_nth_error in Y. destruct Y as (j,Y).\nassert (X' := map_nth_error f _ _ X).\nassert (Y' := map_nth_error f _ _ Y).\nassert (i = j).\n{ rewrite NoDup_nth_error in N. apply N.\n- rewrite <- nth_error_Some. now rewrite X'.\n- rewrite X', Y'. now f_equal. }\nsubst j. rewrite Y in X. now injection X.\nQed.\n\n\n\nLemma Surjective_list_carac A B (f:A->B):\nSurjective f <-> (forall lB, exists lA, incl lB (map f lA)).\nProof. hammer_hook \"FinFun\" \"FinFun.Surjective_list_carac\".  \nsplit.\n- intros Su.\ninduction lB as [|b lB IH].\n+ now exists nil.\n+ destruct (Su b) as (a,E).\ndestruct IH as (lA,IC).\nexists (a::lA). simpl. rewrite E.\nintros x [X|X]; simpl; intuition.\n- intros H y.\ndestruct (H (y::nil)) as (lA,IC).\nassert (IN : In y (map f lA)) by (apply (IC y); now left).\nrewrite in_map_iff in IN. destruct IN as (x & E & _).\nnow exists x.\nQed.\n\nLemma Surjective_carac A B : Finite B -> decidable_eq B ->\nforall f:A->B, Surjective f <-> (exists lA, Listing (map f lA)).\nProof. hammer_hook \"FinFun\" \"FinFun.Surjective_carac\".  \nintros (lB,FB) d. split.\n- rewrite Surjective_list_carac.\nintros Su. destruct (Su lB) as (lA,IC).\ndestruct (uniquify_map d f lA) as (lA' & N & IC').\nexists lA'. split; trivial.\nintro x. apply IC', IC, FB.\n- intros (lA & N & FA) y.\ngeneralize (FA y). rewrite in_map_iff. intros (x & E & _).\nnow exists x.\nQed.\n\n\n\nLemma Endo_Injective_Surjective :\nforall A, Finite A -> decidable_eq A ->\nforall f:A->A, Injective f <-> Surjective f.\nProof. hammer_hook \"FinFun\" \"FinFun.Endo_Injective_Surjective\".  \nintros A F d f. rewrite (Surjective_carac F d). split.\n- apply (Finite_alt d) in F. destruct F as (l,L).\nrewrite (Injective_carac L); intros.\nexists l; split; trivial.\ndestruct L as (N,F).\nassert (I : incl l (map f l)).\n{ apply NoDup_length_incl; trivial.\n- now rewrite map_length.\n- intros x _. apply F. }\nintros x. apply I, F.\n- clear F d. intros (l,L).\nassert (N : NoDup l). { apply (NoDup_map_inv f), L. }\nassert (I : incl (map f l) l).\n{ apply NoDup_length_incl; trivial.\n- now rewrite map_length.\n- intros x _. apply L. }\nassert (L' : Listing l).\n{ split; trivial.\nintro x. apply I, L. }\napply (Injective_carac L'), L.\nQed.\n\n\n\nDefinition EqDec (A:Type) := forall x y:A, {x=y}+{x<>y}.\n\n\n\n\n\nLemma Finite_Empty_or_not A :\nFinite A -> (A->False) \\/ exists a:A,True.\nProof. hammer_hook \"FinFun\" \"FinFun.Finite_Empty_or_not\".  \nintros (l,F).\ndestruct l.\n- left; exact F.\n- right; now exists a.\nQed.\n\nLemma Surjective_inverse :\nforall A B, Finite A -> EqDec B ->\nforall f:A->B, Surjective f ->\nexists g:B->A, forall x, f (g x) = x.\nProof. hammer_hook \"FinFun\" \"FinFun.Surjective_inverse\".  \nintros A B F d f Su.\ndestruct (Finite_Empty_or_not F) as [noA | (a,_)].\n-\nassert (noB : B -> False). { intros y. now destruct (Su y). }\nexists (fun y => False_rect _ (noB y)).\nintro y. destruct (noB y).\n-\ndestruct F as (l,F).\nset (h := fun x k => if d (f k) x then true else false).\nset (get := fun o => match o with Some y => y | None => a end).\nexists (fun x => get (List.find (h x) l)).\nintros x.\ncase_eq (find (h x) l); simpl; clear get; [intros y H|intros H].\n* apply find_some in H. destruct H as (_,H). unfold h in H.\nnow destruct (d (f y) x) in H.\n* exfalso.\ndestruct (Su x) as (y & Y).\ngeneralize (find_none _ l H y (F y)).\nunfold h. now destruct (d (f y) x).\nQed.\n\n\n\nLemma Injective_Surjective_Bijective :\nforall A B, Finite A -> EqDec B ->\nforall f:A->B, Injective f -> Surjective f -> Bijective f.\nProof. hammer_hook \"FinFun\" \"FinFun.Injective_Surjective_Bijective\".  \nintros A B F d f Ij Su.\ndestruct (Surjective_inverse F d Su) as (g, E).\nexists g. split; trivial.\nintros y. apply Ij. now rewrite E.\nQed.\n\n\n\n\nLemma Fin_Finite n : Finite (Fin.t n).\nProof. hammer_hook \"FinFun\" \"FinFun.Fin_Finite\".  \ninduction n.\n- exists nil.\nred;inversion a.\n- destruct IHn as (l,Hl).\nexists (Fin.F1 :: map Fin.FS l).\nintros a. revert n a l Hl.\nrefine (@Fin.caseS _ _ _); intros.\n+ now left.\n+ right. now apply in_map.\nQed.\n\n\n\nDefinition bFun n (f:nat->nat) := forall x, x < n -> f x < n.\n\nDefinition bInjective n (f:nat->nat) :=\nforall x y, x < n -> y < n -> f x = f y -> x = y.\n\nDefinition bSurjective n (f:nat->nat) :=\nforall y, y < n -> exists x, x < n /\\ f x = y.\n\n\n\nModule Fin2Restrict.\n\nNotation n2f := Fin.of_nat_lt.\nDefinition f2n {n} (x:Fin.t n) := proj1_sig (Fin.to_nat x).\nDefinition f2n_ok n (x:Fin.t n) : f2n x < n := proj2_sig (Fin.to_nat x).\nDefinition n2f_f2n : forall n x, n2f (f2n_ok x) = x := @Fin.of_nat_to_nat_inv.\nDefinition f2n_n2f x n h : f2n (n2f h) = x := f_equal (@proj1_sig _ _) (@Fin.to_nat_of_nat x n h).\nDefinition n2f_ext : forall x n h h', n2f h = n2f h' := @Fin.of_nat_ext.\nDefinition f2n_inj : forall n x y, f2n x = f2n y -> x = y := @Fin.to_nat_inj.\n\nDefinition extend n (f:Fin.t n -> Fin.t n) : (nat->nat) :=\nfun x =>\nmatch le_lt_dec n x with\n| left _ => 0\n| right h => f2n (f (n2f h))\nend.\n\nDefinition restrict n (f:nat->nat)(hf : bFun n f) : (Fin.t n -> Fin.t n) :=\nfun x => let (x',h) := Fin.to_nat x in n2f (hf _ h).\n\nLtac break_dec H :=\nlet H' := fresh \"H\" in\ndestruct le_lt_dec as [H'|H'];\n[elim (Lt.le_not_lt _ _ H' H)\n|try rewrite (n2f_ext H' H) in *; try clear H'].\n\nLemma extend_ok n f : bFun n (@extend n f).\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.extend_ok\".  \nintros x h. unfold extend. break_dec h. apply f2n_ok.\nQed.\n\nLemma extend_f2n n f (x:Fin.t n) : extend f (f2n x) = f2n (f x).\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.extend_f2n\".  \ngeneralize (n2f_f2n x). unfold extend, f2n, f2n_ok.\ndestruct (Fin.to_nat x) as (x',h); simpl.\nbreak_dec h.\nnow intros ->.\nQed.\n\nLemma extend_n2f n f x (h:x<n) : n2f (extend_ok f h) = f (n2f h).\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.extend_n2f\".  \ngeneralize (extend_ok f h). unfold extend in *. break_dec h. intros h'.\nrewrite <- n2f_f2n. now apply n2f_ext.\nQed.\n\nLemma restrict_f2n n f hf (x:Fin.t n) :\nf2n (@restrict n f hf x) = f (f2n x).\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.restrict_f2n\".  \nunfold restrict, f2n. destruct (Fin.to_nat x) as (x',h); simpl.\napply f2n_n2f.\nQed.\n\nLemma restrict_n2f n f hf x (h:x<n) :\n@restrict n f hf (n2f h) = n2f (hf _ h).\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.restrict_n2f\".  \nunfold restrict. generalize (f2n_n2f h). unfold f2n.\ndestruct (Fin.to_nat (n2f h)) as (x',h'); simpl. intros ->.\nnow apply n2f_ext.\nQed.\n\nLemma extend_surjective n f :\nbSurjective n (@extend n f) <-> Surjective f.\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.extend_surjective\".  \nsplit.\n- intros hf y.\ndestruct (hf _ (f2n_ok y)) as (x & h & Eq).\nexists (n2f h).\napply f2n_inj. now rewrite <- Eq, <- extend_f2n, f2n_n2f.\n- intros hf y hy.\ndestruct (hf (n2f hy)) as (x,Eq).\nexists (f2n x).\nsplit.\n+ apply f2n_ok.\n+ rewrite extend_f2n, Eq. apply f2n_n2f.\nQed.\n\nLemma extend_injective n f :\nbInjective n (@extend n f) <-> Injective f.\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.extend_injective\".  \nsplit.\n- intros hf x y Eq.\napply f2n_inj. apply hf; try apply f2n_ok.\nnow rewrite 2 extend_f2n, Eq.\n- intros hf x y hx hy Eq.\nrewrite <- (f2n_n2f hx), <- (f2n_n2f hy). f_equal.\napply hf.\nrewrite <- 2 extend_n2f.\ngeneralize (extend_ok f hx) (extend_ok f hy).\nrewrite Eq. apply n2f_ext.\nQed.\n\nLemma restrict_surjective n f h :\nSurjective (@restrict n f h) <-> bSurjective n f.\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.restrict_surjective\".  \nsplit.\n- intros hf y hy.\ndestruct (hf (n2f hy)) as (x,Eq).\nexists (f2n x).\nsplit.\n+ apply f2n_ok.\n+ rewrite <- (restrict_f2n h), Eq. apply f2n_n2f.\n- intros hf y.\ndestruct (hf _ (f2n_ok y)) as (x & hx & Eq).\nexists (n2f hx).\napply f2n_inj. now rewrite restrict_f2n, f2n_n2f.\nQed.\n\nLemma restrict_injective n f h :\nInjective (@restrict n f h) <-> bInjective n f.\nProof. hammer_hook \"FinFun\" \"FinFun.Fin2Restrict.restrict_injective\".  \nsplit.\n- intros hf x y hx hy Eq.\nrewrite <- (f2n_n2f hx), <- (f2n_n2f hy). f_equal.\napply hf.\nrewrite 2 restrict_n2f.\ngeneralize (h x hx) (h y hy).\nrewrite Eq. apply n2f_ext.\n- intros hf x y Eq.\napply f2n_inj. apply hf; try apply f2n_ok.\nnow rewrite <- 2 (restrict_f2n h), Eq.\nQed.\n\nEnd Fin2Restrict.\nImport Fin2Restrict.\n\n\n\nLemma bInjective_bSurjective n (f:nat->nat) :\nbFun n f -> (bInjective n f <-> bSurjective n f).\nProof. hammer_hook \"FinFun\" \"FinFun.bInjective_bSurjective\".  \nintros h.\nrewrite <- (restrict_injective h), <- (restrict_surjective h).\napply Endo_Injective_Surjective.\n- apply Fin_Finite.\n- intros x y. destruct (Fin.eq_dec x y); [left|right]; trivial.\nQed.\n\nLemma bSurjective_bBijective n (f:nat->nat) :\nbFun n f -> bSurjective n f ->\nexists g, bFun n g /\\ forall x, x < n -> g (f x) = x /\\ f (g x) = x.\nProof. hammer_hook \"FinFun\" \"FinFun.bSurjective_bBijective\".  \nintro hf.\nrewrite <- (restrict_surjective hf). intros Su.\nassert (Ij : Injective (restrict hf)).\n{ apply Endo_Injective_Surjective; trivial.\n- apply Fin_Finite.\n- intros x y. destruct (Fin.eq_dec x y); [left|right]; trivial. }\nassert (Bi : Bijective (restrict hf)).\n{ apply Injective_Surjective_Bijective; trivial.\n- apply Fin_Finite.\n- exact Fin.eq_dec. }\ndestruct Bi as (g & Hg & Hg').\nexists (extend g).\nsplit.\n- apply extend_ok.\n- intros x Hx. split.\n+ now rewrite <- (f2n_n2f Hx), <- (restrict_f2n hf), extend_f2n, Hg.\n+ now rewrite <- (f2n_n2f Hx), extend_f2n, <- (restrict_f2n hf), Hg'.\nQed.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/stdlib/Logic/FinFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7068993438316667}}
{"text": "Require Import Coq.Program.Program Coq.Program.Equality.\n\nGoal forall (H: forall n m : nat, n = m -> n = 0) x, x = tt.\nintros.\ndependent destruction x.\nreflexivity.\nQed.\n\nVariable A : Set.\n\nInductive vector : nat -> Type := vnil : vector 0 | vcons : A -> forall {n}, vector n -> vector (S n).\n\nGoal forall n, forall v : vector (S n), vector n.\nProof.\n  intros n H.\n  dependent destruction H.\n  assumption.\nQed.\n\nRequire Import ProofIrrelevance.\n\nGoal forall n, forall v : vector (S n), exists v' : vector n, exists a : A, v = vcons a v'.\nProof.\n  intros n v.\n  dependent destruction v.\n  exists v ; exists a.\n  reflexivity.\nQed.\n\n(* Extraction Unnamed_thm. *)\n\nInductive type : Type :=\n| base : type\n| arrow : type -> type -> type.\n\nNotation \" t --> t' \" := (arrow t t') (at level 20, t' at next level).\n\nInductive ctx : Type :=\n| empty : ctx\n| snoc : ctx -> type -> ctx.\n\nBind Scope context_scope with ctx.\nDelimit Scope context_scope with ctx.\n\nArguments snoc _%context_scope.\n\nNotation \" Γ , τ \" := (snoc Γ τ) (at level 25, τ at next level, left associativity) : context_scope.\n\nFixpoint conc (Δ Γ : ctx) : ctx :=\n  match Δ with\n    | empty => Γ\n    | snoc Δ' x => snoc (conc Δ' Γ) x\n  end.\n\nNotation \" Γ  ; Δ \" := (conc Δ Γ) (at level 25, left associativity) : context_scope.\n\nReserved Notation \" Γ ⊢ τ \" (at level 30, no associativity).\n\nGeneralizable All Variables.\n\nInductive term : ctx -> type -> Type :=\n| ax : `(Γ, τ ⊢ τ)\n| weak : `{Γ ⊢ τ -> Γ, τ' ⊢ τ}\n| abs : `{Γ, τ ⊢ τ' -> Γ ⊢ τ --> τ'}\n| app : `{Γ ⊢ τ --> τ' -> Γ ⊢ τ -> Γ ⊢ τ'}\n\nwhere \" Γ ⊢ τ \" := (term Γ τ) : type_scope.\n\nHint Constructors term : lambda.\n\nLocal Open Scope context_scope.\n\nLtac eqns := subst ; reverse ; simplify_dep_elim ; simplify_IH_hyps.\n\nLemma weakening : forall Γ Δ τ, Γ ; Δ ⊢ τ ->\n  forall τ', Γ , τ' ; Δ ⊢ τ.\nProof with simpl in * ; eqns ; eauto with lambda.\n  intros Γ Δ τ H.\n\n  dependent induction H.\n\n  destruct Δ as [|Δ τ'']...\n\n  destruct Δ as [|Δ τ'']...\n\n  destruct Δ as [|Δ τ'']...\n    apply abs.\n    specialize (IHterm Γ (Δ, τ'', τ))...\n\n  intro. eapply app...\nDefined.\n\nLemma weakening_ctx : forall Γ Δ τ, Γ ; Δ ⊢ τ ->\n  forall Δ', Γ ; Δ' ; Δ ⊢ τ.\nProof with simpl in * ; eqns ; eauto with lambda.\n  intros Γ Δ τ H.\n\n  dependent induction H.\n\n  destruct Δ as [|Δ τ'']...\n  induction Δ'...\n\n  destruct Δ as [|Δ τ'']...\n  induction Δ'...\n\n  destruct Δ as [|Δ τ'']...\n    apply abs.\n    specialize (IHterm Γ (empty, τ))...\n\n    apply abs.\n    specialize (IHterm Γ (Δ, τ'', τ))...\n\n  intro. eapply app...\nDefined.\n\nLemma exchange : forall Γ Δ α β τ, term (Γ, α, β ; Δ) τ -> term (Γ, β, α ; Δ) τ.\nProof with simpl in * ; eqns ; eauto.\n  intros until 1.\n  dependent induction H.\n\n  destruct Δ ; eqns.\n    apply weak ; apply ax.\n\n    apply ax.\n\n  destruct Δ...\n    pose (weakening Γ (empty, α))...\n\n    apply weak...\n\n  apply abs...\n    specialize (IHterm Γ (Δ, τ))...\n\n  eapply app...\nDefined.\n\n\n\n(** Example by Andrew Kenedy, uses simplification of the first component of dependent pairs. *)\n\nSet Implicit Arguments.\n\nInductive Ty :=\n | Nat : Ty\n | Prod : Ty -> Ty -> Ty.\n\nInductive Exp : Ty -> Type :=\n| Const : nat -> Exp Nat\n| Pair : forall t1 t2, Exp t1 -> Exp t2 -> Exp (Prod t1 t2)\n| Fst : forall t1 t2, Exp (Prod t1 t2) -> Exp t1.\n\nInductive Ev : forall t, Exp t -> Exp t -> Prop :=\n| EvConst   : forall n, Ev (Const n) (Const n)\n| EvPair    : forall t1 t2 (e1:Exp t1) (e2:Exp t2) e1' e2',\n               Ev e1 e1' -> Ev e2 e2' -> Ev (Pair e1 e2) (Pair e1' e2')\n| EvFst     : forall t1 t2 (e:Exp (Prod t1 t2)) e1 e2,\n               Ev e (Pair e1 e2) ->\n               Ev (Fst e) e1.\n\nLemma EvFst_inversion : forall t1 t2 (e:Exp (Prod t1 t2)) e1, Ev (Fst e) e1 -> exists e2, Ev e (Pair e1 e2).\nintros t1 t2 e e1 ev. dependent destruction ev. exists e2 ; assumption.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/success/dependentind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7068993368869841}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Setoid.\n\nSection plus_minus_mult.\n\n  Print nat.\n \n  Check 1.\n\n  Reserved Notation \"a ⊕ b\" (at level 50, left associativity).\n  Reserved Notation \"a ⊖ b\" (at level 50, left associativity).\n  Reserved Notation \"a ⊗ b\" (at level 40, left associativity).\n\n  (* We redefine plus as myplus denote with ⊕ to\n     avoid the conflicts with the Init module\n     that contains parts of the Arith library \n\n     Notice that we import the inductive definition of nat\n\n   *)\n\n  Print nat.\n\n  Fixpoint myplus (a b : nat) { struct a } :=\n    match a with\n      | 0   => b\n      | S a' => S (a' ⊕ b)\n    end\n  where \"a ⊕ b\" := (myplus a b).\n\n  Print myplus.\n\n  (* 0, 1, 2 is a notation of S (S ... O) \n     in particular, 0 is identical to O \n   *)\n\n  Fact plus_0_l n : 0 ⊕ n = n.\n  Proof.\n    simpl.\n    trivial.\n  Qed.\n\n  Fact plus_1_l n : 1 ⊕ n = S n.\n  Proof.\n    simpl.\n    trivial.\n  Qed.\n  \n  Fact plus_0_r n : n ⊕ 0 = n.\n  Proof.\n    simpl.\n    induction n.\n    + simpl; trivial.\n    + simpl.\n      f_equal.\n      exact IHn.\n  Qed.\n\n  Fact plus_a_Sb a b : a ⊕ S b = S (a ⊕ b).\n  Proof. (* induction a; simpl; f_equal; trivial. *)\n    induction a as [ | a IHa ].\n    + simpl; trivial.\n    + simpl; f_equal; assumption.\n  Qed.\n \n  Hint Resolve plus_0_r plus_a_Sb : core.\n\n  Fact plus_comm a b : a ⊕ b = b ⊕ a.\n  Proof.\n    induction a as [ | a IHa ].\n    + simpl; trivial. (* using Hint plus_0_r *)\n    + simpl.\n      rewrite IHa. \n      trivial.\n  Qed.\n\n  Fact plus_assoc a b c : (a ⊕ b) ⊕ c = a ⊕ (b ⊕ c).\n  Proof. (* induction a; simpl; f_equal; trivial. *)\n    induction a as [ | a IHa ].\n    + simpl; trivial.\n    + simpl; f_equal.\n      trivial.\n  Qed.\n\n  Fixpoint myminus (a b : nat) { struct a } :=\n    match a, b with\n      | 0, _     => 0\n      | S a, 0   => S a \n      | S a, S b => a ⊖ b\n    end\n  where \"a ⊖ b\" := (myminus a b).\n\n  Print myminus.\n\n  Fact minus_0 a : a ⊖ 0 = a.\n  Proof. (* induction a; simpl; trivial. *)\n    induction a as [ | a IHa ].\n    + simpl; trivial.\n    + simpl; trivial.\n  Qed.\n\n  Hint Resolve minus_0 : core.\n\n  Fact plus_minus a b : (a ⊕ b) ⊖ a = b.\n  Proof.\n    induction a as [ | a IHa ].\n    + simpl; trivial.\n    + simpl; trivial.\n  Qed.\n\n  Fact minus_diag a : a ⊖ a = 0.\n  Proof.\n    rewrite <- (plus_minus a 0).\n    f_equal.\n    trivial.\n  Qed.\n\n  Hint Resolve minus_diag : core.\n\n  (* a ⊖ b ⊕ b <> a *)\n\n  Eval compute in 1 ⊖ 3 ⊕ 3.\n\n  Fact minus_plus_assoc a b c : a ⊖ b ⊖ c = a ⊖ (b ⊕ c).\n  Proof.\n    (* induction a as [ | a IHa ].\n    + simpl; trivial.\n    + simpl.\n      destruct b; simpl.\n      * trivial.\n      * \n      destruct c; auto. FAIL *)\n\n  (*  revert b; induction a; simpl; trivial; intros []; simpl; trivial. *)\n    revert b. \n    induction a as [ | a IHa ]. \n    + intros b.\n      simpl; trivial.\n    + intros [ | b ].\n      * simpl.\n        trivial.\n      * simpl.\n        apply IHa.\n  Qed.\n\n  Fact minus_eq a b : a = b <-> (a ⊖ b = 0 /\\ b ⊖ a = 0).\n  Proof.\n    split.\n    + (* intros E; split; rewrite E, minus_diag; reflexivity. *)\n      (* intros E; rewrite -> E; clear E. *)\n      intros ->; auto.\n    + intros [ H1 H2 ].\n      revert a b H1 H2.\n      induction a.\n      * simpl. \n        intros b. \n        rewrite minus_0.\n        auto.\n      * simpl. \n        intros [ | b ].\n        - trivial.\n        - simpl.\n          intros.\n          f_equal.\n          apply IHa; trivial.\n  Qed.\n\n  Fact plus_cancel_l a b c : a ⊕ b = a ⊕ c -> b = c.\n  Proof.\n    intros E.\n    apply f_equal with (f := fun x => x ⊖ a) in E.\n    rewrite !plus_minus in E.\n    trivial.\n  Qed.\n\n  Fact plus_cancel_r a b c : a ⊕ c = b ⊕ c -> a = b.\n  Proof.\n    rewrite !(plus_comm _ c).\n    apply plus_cancel_l.\n  Qed.\n\n  Fact discriminate n : S n = O -> False.\n  Proof.\n    (* discriminate. *)\n    intros H.\n    set (f n := match n with 0 => False | S  _ => True end).\n    change (f 0).\n    rewrite <- H.\n    simpl.\n    trivial.\n  Qed. \n\n  Fact plus_eq_0 a b : a ⊕ b = 0 <-> a = 0 /\\ b = 0.\n  Proof.\n    split.\n    + destruct a.\n      * simpl.\n        intros ->; auto.\n      * simpl.\n        intros C.\n        exfalso.\n        discriminate.\n    + intros (-> & ->).\n      trivial.\n  Qed.\n\n  Fixpoint mymult a b :=\n    match a with \n      | 0   => 0\n      | S a => b ⊕ a ⊗ b\n    end\n  where \"a ⊗ b\" := (mymult a b).\n\n  Fact mult_0_l b : 0 ⊗ b = 0.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Fact mult_0_r a : a ⊗ 0 = 0.\n  Proof.\n    induction a as [ | a IHa ].\n    + trivial.\n    + unfold mymult; fold mymult.\n      simpl; trivial.\n  Qed.\n\n  Hint Resolve plus_comm mult_0_r : core.\n\n  Fact mult_a_Sb a b : a ⊗ S b = a ⊕ a ⊗ b.\n  Proof.\n    induction a as [ | a IHa ].\n    + simpl; trivial.\n    + simpl.\n      f_equal.\n      rewrite IHa.\n      (* generalize (a ⊗ b); intros c. *)\n      Check plus_assoc.\n      rewrite <- !plus_assoc.\n      f_equal.\n      apply plus_comm.\n  Qed.\n\n  Fact mult_comm a b : a ⊗ b = b ⊗ a.\n  Proof.\n    induction a as [ | a IHa ].\n    + simpl; auto.\n    + simpl.\n      rewrite mult_a_Sb.\n      f_equal; trivial.\n  Qed.\n \n  Fact plus_mult_distr_l a b c : (a ⊕ b) ⊗ c = a ⊗ c ⊕ b ⊗ c.\n  Proof.\n    induction a as [ | a IHa ]; simpl; trivial.\n    rewrite IHa, plus_assoc; trivial.\n  Qed.\n\n  Hint Resolve plus_mult_distr_l : core.\n\n  Fact plus_mult_distr_r a b c : c ⊗ (a ⊕ b)  = c ⊗ a ⊕ c ⊗ b.\n  Proof.\n  Admitted.\n\n  Fact mult_assoc a b c : a ⊗ b ⊗ c = a ⊗ (b ⊗ c).\n  Proof.\n    induction a as [ | a IHa ]; simpl; trivial.\n  Admitted.\n\n  Fact mult_1_l a : 1 ⊗ a = a.\n  Proof.\n  Admitted.\n\n  Hint Resolve mult_1_l : core.\n\n  Fact mult_1_r a : a ⊗ 1 = a.\n  Proof.\n  Admitted.\n\n  Hint Resolve mult_1_r : core.\n\n  Fact mult_minus a b c : a ⊗ (b ⊖ c) = a ⊗ b ⊖ a ⊗ c.\n  Proof.\n    rewrite !(mult_comm a).\n    revert c; induction b as [ | b IHb ]; intros c.\n  Admitted.\n\n  Fact mult_eq_0 a b : a ⊗ b = 0 <-> a = 0 \\/ b = 0.\n  Proof.\n  Admitted.\n\n  Fact mult_cancel_0 a b c : a ⊗ b = a ⊗ c -> a = 0 \\/ b = c.\n  Proof.\n    intros E.\n    rewrite minus_eq in E.\n    rewrite <- !mult_minus in E.\n    rewrite !mult_eq_0 in E.\n    rewrite (minus_eq b c).\n    destruct E as [ [] [] ]; auto.\n  Qed.\n\n  Fact mult_cancel_l a b c : S a ⊗ b = S a ⊗ c -> b = c.\n  Proof.\n    intros E.\n    apply mult_cancel_0 in E.\n    destruct E; trivial.\n    discriminate.\n  Qed.\n\n  Fact mult_cancel_r a b c : a ⊗ S c = b ⊗ S c -> a = b.\n  Proof.\n    rewrite !(mult_comm _ (S _)).\n    apply mult_cancel_l.\n  Qed.\n\nEnd plus_minus_mult.\n\nRequire Import Arith Lia Ring Omega. (* In day to day practice with nat, Z *)\n\nFact test (a b c : nat) : a <= b -> a+b <= b*3.\nProof. lia. Qed.\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Introduction-to-Coq", "sha": "c2924b5284ef87143def1850520a25984dc0e724", "save_path": "github-repos/coq/DmxLarchey-Introduction-to-Coq", "path": "github-repos/coq/DmxLarchey-Introduction-to-Coq/Introduction-to-Coq-c2924b5284ef87143def1850520a25984dc0e724/lab3_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7068633849910714}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export ProofObjects.\n\n\n\n\n\n\nCheck nat_ind.\n\n\n\n\nTheorem mult_0_r' : forall n:nat,\nn * 0 = 0.\nProof. hammer_hook \"IndPrinciples\" \"IndPrinciples.mult_0_r'\".\napply nat_ind.\n-  reflexivity.\n-  simpl. intros n' IHn'. rewrite -> IHn'.\nreflexivity.  Qed.\n\n\n\n\n\nTheorem plus_one_r' : forall n:nat,\nn + 1 = S n.\nProof. hammer_hook \"IndPrinciples\" \"IndPrinciples.plus_one_r'\".\nAdmitted.\n\n\n\n\nInductive yesno : Type :=\n| yes\n| no.\n\nCheck yesno_ind.\n\n\n\n\nInductive rgb : Type :=\n| red\n| green\n| blue.\nCheck rgb_ind.\n\n\n\n\nInductive natlist : Type :=\n| nnil\n| ncons (n : nat) (l : natlist).\n\nCheck natlist_ind.\n\n\n\n\nInductive natlist1 : Type :=\n| nnil1\n| nsnoc1 (l : natlist1) (n : nat).\n\n\n\n\n\n\n\nInductive byntree : Type :=\n| bempty\n| bleaf (yn : yesno)\n| nbranch (yn : yesno) (t1 t2 : byntree).\n\n\n\n\nInductive ExSet : Type :=\n\n.\n\n\n\n\n\n\n\n\n\nInductive tree (X:Type) : Type :=\n| leaf (x : X)\n| node (t1 t2 : tree X).\nCheck tree_ind.\n\n\n\n\n\n\n\n\n\n\nInductive foo' (X:Type) : Type :=\n| C1 (l : list X) (f : foo' X)\n| C2.\n\n\n\n\n\n\n\n\n\n\nDefinition P_m0r (n:nat) : Prop :=\nn * 0 = 0.\n\n\n\nDefinition P_m0r' : nat->Prop :=\nfun n => n * 0 = 0.\n\n\n\nTheorem mult_0_r'' : forall n:nat,\nP_m0r n.\nProof. hammer_hook \"IndPrinciples\" \"IndPrinciples.mult_0_r''\".\napply nat_ind.\n-  reflexivity.\n-\n\nintros n IHn.\nunfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n\n\n\n\n\n\n\nTheorem plus_assoc' : forall n m p : nat,\nn + (m + p) = (n + m) + p.\nProof. hammer_hook \"IndPrinciples\" \"IndPrinciples.plus_assoc'\".\n\nintros n m p.\n\ninduction n as [| n'].\n-  reflexivity.\n-\n\nsimpl. rewrite -> IHn'. reflexivity.  Qed.\n\n\n\nTheorem plus_comm' : forall n m : nat,\nn + m = m + n.\nProof. hammer_hook \"IndPrinciples\" \"IndPrinciples.plus_comm'\".\ninduction n as [| n'].\n-  intros m. rewrite <- plus_n_O. reflexivity.\n-  intros m. simpl. rewrite -> IHn'.\nrewrite <- plus_n_Sm. reflexivity.  Qed.\n\n\n\nTheorem plus_comm'' : forall n m : nat,\nn + m = m + n.\nProof. hammer_hook \"IndPrinciples\" \"IndPrinciples.plus_comm''\".\n\ninduction m as [| m'].\n-  simpl. rewrite <- plus_n_O. reflexivity.\n-  simpl. rewrite <- IHm'.\nrewrite <- plus_n_Sm. reflexivity.  Qed.\n\n\n\n\n\n\n\n\n\n\nCheck even_ind.\n\n\n\n\n\n\n\nTheorem ev_ev' : forall n, even n -> even' n.\nProof. hammer_hook \"IndPrinciples\" \"IndPrinciples.ev_ev'\".\napply even_ind.\n-\napply even'_0.\n-\nintros m Hm IH.\napply (even'_sum 2 m).\n+ apply even'_2.\n+ apply IH.\nQed.\n\n\n\n\n\n\n\nInductive le (n:nat) : nat -> Prop :=\n| le_n : le n n\n| le_S m (H : le n m) : le n (S m).\n\nNotation \"m <= n\" := (le m n).\n\n\n\nCheck le_ind.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/sf/IndPrinciples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7068357378627641}}
{"text": "(* Copyright (c) 2008-2012, 2015, Adam Chlipala\n * \n * This work is licensed under a\n * Creative Commons Attribution-Noncommercial-No Derivative Works 3.0\n * Unported License.\n * The license text is available at:\n *   http://creativecommons.org/licenses/by-nc-nd/3.0/\n *)\n\n(* begin hide *)\nRequire Import Arith List.\n\nRequire Import Cpdt.CpdtTactics.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n(* end hide *)\n\n\n(** %\\chapter{Dependent Data Structures}% *)\n\n(** Our red-black tree example from the last chapter illustrated how dependent types enable static enforcement of data structure invariants.  To find interesting uses of dependent data structures, however, we need not look to the favorite examples of data structures and algorithms textbooks.  More basic examples like length-indexed and heterogeneous lists come up again and again as the building blocks of dependent programs.  There is a surprisingly large design space for this class of data structure, and we will spend this chapter exploring it. *)\n\nSection ilist.\n  Variable A : Set.\n\n  Inductive ilist : nat -> Set :=\n  | Nil : ilist 0\n  | Cons : forall n, A -> ilist n -> ilist (S n).\n\n  Inductive fin : nat -> Set :=\n  | Find : forall n, fin (S n)\n  | Next : forall n, fin n -> fin (S n).\n\n  Fixpoint get n (ls : ilist n) : fin n -> A :=\n    match ls with\n    | Nil =>\n      fun f =>\n        match f in (fin n') return (match n' with\n                                    | 0 => A\n                                    | _ => unit\n                                    end) with\n        | Find _ => tt\n        | Next _ _ => tt\n        end\n    | Cons n1 x ls' => \n      fun f =>\n        (match f in (fin n') return ((fin (pred n') -> A) -> A) with\n         | Find _ => fun _ => x\n         | Next _ f' => fun new_f => new_f f'\n         end) (get ls')\n    end.\nEnd ilist.\n\nArguments Nil [A].\nArguments Find [n].\n\nCheck Cons 0 (Cons 1 (Cons 2 Nil)).\n\nEval simpl in get (Cons 0 (Cons 1 (Cons 2 Nil))) Find.\nEval simpl in get (Cons 0 (Cons 1 (Cons 2 Nil))) (Next Find).\nEval simpl in get (Cons 0 (Cons 1 (Cons 2 Nil))) (Next (Next Find)).\n\n\nSection ilist_map.\n  Variables A B : Set.\n\n  Variable f : A -> B.\n\n  Fixpoint ilist_map n (ls : ilist A n) : ilist B n :=\n    match ls in (ilist _ n) return (ilist B n) with\n    | Nil => Nil\n    | Cons n x ls' => Cons (f x) (ilist_map ls')                           \n    end.\n\n  Theorem get_imap : forall n (ls : ilist A n) (fdx : fin n),\n      get (ilist_map ls) fdx = f (get ls fdx).\n    induction ls.\n    -\n      intros; simpl. inversion fdx.\n    -\n      simpl; intros; dep_destruct fdx.\n      reflexivity. apply IHls.\n  Qed.\nEnd ilist_map.                                       \n\nSection hlist.\n  Variable A : Type.\n  Variable B : A -> Type.\n\n  Inductive hlist : list A -> Type :=\n  | HNil : hlist nil\n  | HCons : forall x ls, B x -> hlist ls -> hlist (x :: ls).\n\n  Variable elem : A.\n\n  Inductive member : list A -> Type :=\n  | HFirst : forall ls, member (elem :: ls)\n  | HNext : forall x ls, member ls -> member (x :: ls).\n\n  Fixpoint hget (ls : list A) (hls : hlist ls) : member ls -> B elem :=\n    match hls with\n    | HNil =>\n      fun memb =>\n        match memb in (member ls') return (match ls' with\n                                           | nil => B elem\n                                           | _ => unit\n                                           end) with\n        | HFirst _ => tt\n        | _ => tt\n        end\n    | HCons _ _ val rem_ls =>\n      fun memb =>\n        (match memb in (member ls') return (match ls' with\n                                            | nil => Empty_set\n                                            | x' :: ls'' =>\n                                              B x' -> (member ls'' -> B elem) -> B elem\n                                            end) with\n         | HFirst _ => fun x _ => x\n         | HNext _ _ memb' => fun _ recur => recur memb'\n         end) val (hget rem_ls)\n    end.\nEnd hlist.\n\nArguments HNil [A B].\nArguments HCons [A B x ls] _ _.\n\nArguments HFirst [A elem ls].\nArguments HNext [A elem x ls] _.\n\nDefinition someTypes : list Set := nat :: bool :: nil.\n\nExample someValues : hlist (fun T : Set =>  T) someTypes :=\n  HCons 5 (HCons true HNil).\n\nEval simpl in (hget someValues HFirst).\n\nEval simpl in (hget someValues (HNext HFirst)).\n\nExample somePairs : hlist (fun T : Set => T * T)%type someTypes :=\n  HCons (1, 2) (HCons (true, false) HNil).\n\n                                                  \n(** ** A Lambda Calculus Interpreter *)\n\n(** Heterogeneous lists are very useful in implementing %\\index{interpreters}%interpreters for functional programming languages.  Using the types and operations we have already defined, it is trivial to write an interpreter for simply typed lambda calculus%\\index{lambda calculus}%.  Our interpreter can alternatively be thought of as a denotational semantics (but worry not if you are not familiar with such terminology from semantics).\n\n   We start with an algebraic datatype for types. *)\n\nInductive type : Set :=\n| Unit : type\n| Arrow : type -> type -> type.\n\n(** Now we can define a type family for expressions.  An [exp ts t] will stand for an expression that has type [t] and whose free variables have types in the list [ts].  We effectively use the de Bruijn index variable representation%~\\cite{DeBruijn}%.  Variables are represented as [member] values; that is, a variable is more or less a constructive proof that a particular type is found in the type environment. *)\n\nInductive exp : list type -> type -> Set :=\n| Const : forall ts, exp ts Unit\n(* begin thide *)\n| Var : forall ts t, member t ts -> exp ts t\n| App : forall ts dom ran, exp ts (Arrow dom ran) -> exp ts dom -> exp ts ran\n| Abs : forall ts dom ran, exp (dom :: ts) ran -> exp ts (Arrow dom ran).\n(* end thide *)\n\nArguments Const [ts].\n\n(** We write a simple recursive function to translate [type]s into [Set]s. *)\n\nFixpoint typeDenote (t : type) : Set :=\n  match t with\n    | Unit => unit\n    | Arrow t1 t2 => typeDenote t1 -> typeDenote t2\n  end.\n\n(** Now it is straightforward to write an expression interpreter.  The type of the function, [expDenote], tells us that we translate expressions into functions from properly typed environments to final values.  An environment for a free variable list [ts] is simply an [hlist typeDenote ts].  That is, for each free variable, the heterogeneous list that is the environment must have a value of the variable's associated type.  We use [hget] to implement the [Var] case, and we use [HCons] to extend the environment in the [Abs] case. *)\n\n(* EX: Define an interpreter for [exp]s. *)\n\n(* begin thide *)\nFixpoint expDenote ts t (e : exp ts t) : hlist typeDenote ts -> typeDenote t :=\n  match e with\n    | Const _ => fun _ => tt\n\n    | Var _ _ mem => fun s => hget s mem\n    | App _ _ _ e1 e2 => fun s => (expDenote e1 s) (expDenote e2 s)\n    | Abs _ _ _ e' => fun s => fun x => expDenote e' (HCons x s)\n  end.\n\n(** Like for previous examples, our interpreter is easy to run with [simpl]. *)\n\nEval simpl in expDenote Const HNil.\n(** %\\vspace{-.15in}% [[\n    = tt\n     : typeDenote Unit\n]]\n*)\n\nEval simpl in expDenote (Abs (dom := Unit) (Var HFirst)) HNil.\n(** %\\vspace{-.15in}% [[\n     = fun x : unit => x\n     : typeDenote (Arrow Unit Unit)\n]]\n*)\n\nEval simpl in expDenote (Abs (dom := Unit)\n  (Abs (dom := Unit) (Var (HNext HFirst)))) HNil.\n(** %\\vspace{-.15in}% [[\n     = fun x _ : unit => x\n     : typeDenote (Arrow Unit (Arrow Unit Unit))\n]]\n*)\n\nEval simpl in expDenote (Abs (dom := Unit) (Abs (dom := Unit) (Var HFirst))) HNil.\n(** %\\vspace{-.15in}% [[\n     = fun _ x0 : unit => x0\n     : typeDenote (Arrow Unit (Arrow Unit Unit))\n]]\n*)\n\nEval simpl in expDenote (App (Abs (Var HFirst)) Const) HNil.\n(** %\\vspace{-.15in}% [[\n     = tt\n     : typeDenote Unit\n]]\n*)\n\n(* end thide *)\n\n(** We are starting to develop the tools behind dependent typing's amazing advantage over alternative approaches in several important areas.  Here, we have implemented complete syntax, typing rules, and evaluation semantics for simply typed lambda calculus without even needing to define a syntactic substitution operation.  We did it all without a single line of proof, and our implementation is manifestly executable.  Other, more common approaches to language formalization often state and prove explicit theorems about type safety of languages.  In the above example, we got type safety, termination, and other meta-theorems for free, by reduction to CIC, which we know has those properties. *)\n\n\n(** * Recursive Type Definitions *)\n\n(** %\\index{recursive type definition}%There is another style of datatype definition that leads to much simpler definitions of the [get] and [hget] definitions above.  Because Coq supports \"type-level computation,\" we can redo our inductive definitions as _recursive_ definitions.  Here we will preface type names with the letter [f] to indicate that they are based on explicit recursive _function_ definitions. *)\n\n(* EX: Come up with an alternate [ilist] definition that makes it easier to write [get]. *)\n\nSection filist.\n  Variable A : Set.\n\n  Fixpoint filist (n : nat) : Set :=\n    match n with\n    | O => unit\n    | S n' => A * (filist n')\n    end %type.\n\n  Fixpoint ffin (n : nat) : Set :=\n    match n with\n    | O => Empty_set\n    | S n' => option (ffin n')\n    end %type.\n\n  Fixpoint fget (n : nat) : filist n -> ffin n -> A :=\n    match n with\n    | O => fun _ fdx => match fdx with end\n    | S n' =>\n      fun ls fdx =>\n        match fdx with\n        | Some fdx' => fget n' (snd ls) fdx'\n        | None => fst ls\n        end\n    end.\nEnd filist.\n\n(** Heterogeneous lists are a little trickier to define with recursion, but we then reap similar benefits in simplicity of use. *)\n\n(* EX: Come up with an alternate [hlist] definition that makes it easier to write [hget]. *)\n\nSection fhlist.\n  Variable A : Type.\n  Variable B : A -> Type.\n\n  Fixpoint fhlist (ls : list A) : Type :=\n    match ls with\n    | nil => unit\n    | x :: ls' => (B x) * (fhlist ls')\n    end.\n\n  Variable elem : A.\n  \n  Fixpoint fmember (ls : list A) : Type :=\n    match ls with\n    | nil => Empty_set\n    | x :: ls' => (x = elem) + (fmember ls')\n    end.\n\n  Fixpoint fhget (ls : list A) : fhlist ls -> fmember ls -> B elem :=\n    match ls with\n    | nil => fun _ fdx => match fdx with end\n    | x :: ls' =>\n      fun fls fdx =>\n        match fdx with\n        | inl eqp => match eqp with\n                     | eq_refl => fst fls\n                     end\n        | inr fdx' => fhget ls' (snd fls) fdx'\n        end\n    end.\nEnd fhlist.\n      \n\nArguments fhget [A B elem ls] _ _.\n\n(** How does one choose between the two data structure encoding strategies we have presented so far?  Before answering that question in this chapter's final section, we introduce one further approach. *)\n\n\n(** * Data Structures as Index Functions *)\n\n(** %\\index{index function}%Indexed lists can be useful in defining other inductive types with constructors that take variable numbers of arguments.  In this section, we consider parameterized trees with arbitrary branching factor. *)\n\n(* begin hide *)\nDefinition red_herring := O.\n(* working around a bug in Coq 8.5! *)\n(* end hide *)\n\nSection tree.\n  Variable A : Set.\n\n  Inductive tree : Set :=\n  | Leaf : A -> tree\n  | Node : forall n, ilist tree n -> tree.\nEnd tree.\n\n(** Every [Node] of a [tree] has a natural number argument, which gives the number of child trees in the second argument, typed with [ilist].  We can define two operations on trees of naturals: summing their elements and incrementing their elements.  It is useful to define a generic fold function on [ilist]s first. *)\n\nSection ifoldr.\n  Variables A B : Set.\n  Variable f : A -> B -> B.\n  Variable i : B.\n\n  Fixpoint ifoldr n (ls : ilist A n) : B :=\n    match ls with\n      | Nil => i\n      | Cons _ x ls' => f x (ifoldr ls')\n    end.\nEnd ifoldr.\n\nFixpoint sum (t : tree nat) : nat :=\n  match t with\n    | Leaf n => n\n    | Node _ ls => ifoldr (fun t' n => sum t' + n) O ls\n  end.\n\nFixpoint inc (t : tree nat) : tree nat :=\n  match t with\n    | Leaf n => Leaf (S n)\n    | Node _ ls => Node (imap inc ls)\n  end.\n\n(** Now we might like to prove that [inc] does not decrease a tree's [sum]. *)\n\nTheorem sum_inc : forall t, sum (inc t) >= sum t.\n(* begin thide *)\n  induction t; crush.\n  (** [[\n  n : nat\n  i : ilist (tree nat) n\n  ============================\n   ifoldr (fun (t' : tree nat) (n0 : nat) => sum t' + n0) 0 (imap inc i) >=\n   ifoldr (fun (t' : tree nat) (n0 : nat) => sum t' + n0) 0 i\n \n   ]]\n\n   We are left with a single subgoal which does not seem provable directly.  This is the same problem that we met in Chapter 3 with other %\\index{nested inductive type}%nested inductive types. *)\n\n  Check tree_ind.\n  (** %\\vspace{-.15in}% [[\n  tree_ind\n     : forall (A : Set) (P : tree A -> Prop),\n       (forall a : A, P (Leaf a)) ->\n       (forall (n : nat) (i : ilist (tree A) n), P (Node i)) ->\n       forall t : tree A, P t\n]]\n\nThe automatically generated induction principle is too weak.  For the [Node] case, it gives us no inductive hypothesis.  We could write our own induction principle, as we did in Chapter 3, but there is an easier way, if we are willing to alter the definition of [tree]. *)\n\nAbort.\n\nReset tree.\n(* begin hide *)\nReset red_herring.\n(* working around a bug in Coq 8.5! *)\n(* end hide *)\n\n(** First, let us try using our recursive definition of [ilist]s instead of the inductive version. *)\n\nSection tree.\n  Variable A : Set.\n\n  (** %\\vspace{-.15in}% [[\n  Inductive tree : Set :=\n  | Leaf : A -> tree\n  | Node : forall n, filist tree n -> tree.\n]]\n\n<<\nError: Non strictly positive occurrence of \"tree\" in\n \"forall n : nat, filist tree n -> tree\"\n>>\n\n  The special-case rule for nested datatypes only works with nested uses of other inductive types, which could be replaced with uses of new mutually inductive types.  We defined [filist] recursively, so it may not be used in nested inductive definitions.\n\n  Our final solution uses yet another of the inductive definition techniques introduced in Chapter 3, %\\index{reflexive inductive type}%reflexive types.  Instead of merely using [fin] to get elements out of [ilist], we can _define_ [ilist] in terms of [fin].  For the reasons outlined above, it turns out to be easier to work with [ffin] in place of [fin]. *)\n\n  Inductive tree : Set :=\n  | Leaf : A -> tree\n  | Node : forall n, (ffin n -> tree) -> tree.\n\n  (** A [Node] is indexed by a natural number [n], and the node's [n] children are represented as a function from [ffin n] to trees, which is isomorphic to the [ilist]-based representation that we used above. *)\n\nEnd tree.\n\nArguments Node [A n] _.\n\n(** We can redefine [sum] and [inc] for our new [tree] type.  Again, it is useful to define a generic fold function first.  This time, it takes in a function whose domain is some [ffin] type, and it folds another function over the results of calling the first function at every possible [ffin] value. *)\n\nSection rifoldr.\n  Variables A B : Set.\n  Variable f : A -> B -> B.\n  Variable i : B.\n\n  Fixpoint rifoldr (n : nat) : (ffin n -> A) -> B :=\n    match n with\n      | O => fun _ => i\n      | S n' => fun get => f (get None) (rifoldr n' (fun idx => get (Some idx)))\n    end.\nEnd rifoldr.\n\nArguments rifoldr [A B] f i [n] _.\n\nFixpoint sum (t : tree nat) : nat :=\n  match t with\n    | Leaf n => n\n    | Node _ f => rifoldr plus O (fun idx => sum (f idx))\n  end.\n\nFixpoint inc (t : tree nat) : tree nat :=\n  match t with\n    | Leaf n => Leaf (S n)\n    | Node _ f => Node (fun idx => inc (f idx))\n  end.\n\n(** Now we are ready to prove the theorem where we got stuck before.  We will not need to define any new induction principle, but it _will_ be helpful to prove some lemmas. *)\n\nLemma plus_ge : forall x1 y1 x2 y2,\n  x1 >= x2\n  -> y1 >= y2\n  -> x1 + y1 >= x2 + y2.\n  crush.\nQed.\n\nLemma sum_inc' : forall n (f1 f2 : ffin n -> nat),\n  (forall idx, f1 idx >= f2 idx)\n  -> rifoldr plus O f1 >= rifoldr plus O f2.\n  Hint Resolve plus_ge.\n\n  induction n; crush.\nQed.\n\nTheorem sum_inc : forall t, sum (inc t) >= sum t.\n  Hint Resolve sum_inc'.\n\n  induction t; crush.\nQed.\n\n(* end thide *)\n\n(** Even if Coq would generate complete induction principles automatically for nested inductive definitions like the one we started with, there would still be advantages to using this style of reflexive encoding.  We see one of those advantages in the definition of [inc], where we did not need to use any kind of auxiliary function.  In general, reflexive encodings often admit direct implementations of operations that would require recursion if performed with more traditional inductive data structures. *)\n\n(** ** Another Interpreter Example *)\n\n(** We develop another example of variable-arity constructors, in the form of optimization of a small expression language with a construct like Scheme's <<cond>>.  Each of our conditional expressions takes a list of pairs of boolean tests and bodies.  The value of the conditional comes from the body of the first test in the list to evaluate to [true].  To simplify the %\\index{interpreters}%interpreter we will write, we force each conditional to include a final, default case. *)\n\nInductive type' : Type := Nat | Bool.\n\nInductive exp' : type' -> Type :=\n| NConst : nat -> exp' Nat\n| Plus : exp' Nat -> exp' Nat -> exp' Nat\n| Eq : exp' Nat -> exp' Nat -> exp' Bool\n\n| BConst : bool -> exp' Bool\n(* begin thide *)\n| Cond : forall n t, (ffin n -> exp' Bool)\n  -> (ffin n -> exp' t) -> exp' t -> exp' t.\n(* end thide *)\n\n(** A [Cond] is parameterized by a natural [n], which tells us how many cases this conditional has.  The test expressions are represented with a function of type [ffin n -> exp' Bool], and the bodies are represented with a function of type [ffin n -> exp' t], where [t] is the overall type.  The final [exp' t] argument is the default case.  For example, here is an expression that successively checks whether [2 + 2 = 5] (returning 0 if so) or if [1 + 1 = 2] (returning 1 if so), returning 2 otherwise. *)\n\nExample ex1 := Cond 2\n  (fun f => match f with\n              | None => Eq (Plus (NConst 2) (NConst 2)) (NConst 5)\n              | Some None => Eq (Plus (NConst 1) (NConst 1)) (NConst 2)\n              | Some (Some v) => match v with end\n            end)\n  (fun f => match f with\n              | None => NConst 0\n              | Some None => NConst 1\n              | Some (Some v) => match v with end\n            end)\n  (NConst 2).\n\n(** We start implementing our interpreter with a standard type denotation function. *)\n\nDefinition type'Denote (t : type') : Set :=\n  match t with\n    | Nat => nat\n    | Bool => bool\n  end.\n\n(** To implement the expression interpreter, it is useful to have the following function that implements the functionality of [Cond] without involving any syntax. *)\n\n(* begin thide *)\nSection cond.\n  Variable A : Set.\n  Variable default : A.\n\n  Fixpoint cond (n : nat) : (ffin n -> bool) -> (ffin n -> A) -> A :=\n    match n with\n      | O => fun _ _ => default\n      | S n' => fun tests bodies =>\n        if tests None\n          then bodies None\n          else cond n'\n            (fun idx => tests (Some idx))\n            (fun idx => bodies (Some idx))\n    end.\nEnd cond.\n\nArguments cond [A] default [n] _ _.\n(* end thide *)\n\n(** Now the expression interpreter is straightforward to write. *)\n\n(* begin thide *)\nFixpoint exp'Denote t (e : exp' t) : type'Denote t :=\n  match e with\n    | NConst n => n\n    | Plus e1 e2 => exp'Denote e1 + exp'Denote e2\n    | Eq e1 e2 =>\n      if eq_nat_dec (exp'Denote e1) (exp'Denote e2) then true else false\n\n    | BConst b => b\n    | Cond _ _ tests bodies default =>\n      cond\n      (exp'Denote default)\n      (fun idx => exp'Denote (tests idx))\n      (fun idx => exp'Denote (bodies idx))\n  end.\n(* begin hide *)\nReset exp'Denote.\n(* end hide *)\n(* end thide *)\n\n(* begin hide *)\nFixpoint exp'Denote t (e : exp' t) : type'Denote t :=\n  match e with\n    | NConst n => n\n    | Plus e1 e2 => exp'Denote e1 + exp'Denote e2\n    | Eq e1 e2 =>\n      if eq_nat_dec (exp'Denote e1) (exp'Denote e2) then true else false\n\n    | BConst b => b\n    | Cond _ _ tests bodies default =>\n(* begin thide *)\n      cond\n      (exp'Denote default)\n      (fun idx => exp'Denote (tests idx))\n      (fun idx => exp'Denote (bodies idx))\n(* end thide *)\n  end.\n(* end hide *)\n\n(** We will implement a constant-folding function that optimizes conditionals, removing cases with known-[false] tests and cases that come after known-[true] tests.  A function [cfoldCond] implements the heart of this logic.  The convoy pattern is used again near the end of the implementation. *)\n\n(* begin thide *)\nSection cfoldCond.\n  Variable t : type'.\n  Variable default : exp' t.\n\n  Fixpoint cfoldCond (n : nat)\n    : (ffin n -> exp' Bool) -> (ffin n -> exp' t) -> exp' t :=\n    match n with\n      | O => fun _ _ => default\n      | S n' => fun tests bodies =>\n        match tests None return _ with\n          | BConst true => bodies None\n          | BConst false => cfoldCond n'\n            (fun idx => tests (Some idx))\n            (fun idx => bodies (Some idx))\n          | _ =>\n            let e := cfoldCond n'\n              (fun idx => tests (Some idx))\n              (fun idx => bodies (Some idx)) in\n            match e in exp' t return exp' t -> exp' t with\n              | Cond n _ tests' bodies' default' => fun body =>\n                Cond\n                (S n)\n                (fun idx => match idx with\n                              | None => tests None\n                              | Some idx => tests' idx\n                            end)\n                (fun idx => match idx with\n                              | None => body\n                              | Some idx => bodies' idx\n                            end)\n                default'\n              | e => fun body =>\n                Cond\n                1\n                (fun _ => tests None)\n                (fun _ => body)\n                e\n            end (bodies None)\n        end\n    end.\nEnd cfoldCond.\n\nArguments cfoldCond [t] default [n] _ _.\n(* end thide *)\n\n(** Like for the interpreters, most of the action was in this helper function, and [cfold] itself is easy to write. *)\n\n(* begin thide *)\nFixpoint cfold t (e : exp' t) : exp' t :=\n  match e with\n    | NConst n => NConst n\n    | Plus e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold e2 in\n      match e1', e2' return exp' Nat with\n        | NConst n1, NConst n2 => NConst (n1 + n2)\n        | _, _ => Plus e1' e2'\n      end\n    | Eq e1 e2 =>\n      let e1' := cfold e1 in\n      let e2' := cfold e2 in\n      match e1', e2' return exp' Bool with\n        | NConst n1, NConst n2 => BConst (if eq_nat_dec n1 n2 then true else false)\n        | _, _ => Eq e1' e2'\n      end\n\n    | BConst b => BConst b\n    | Cond _ _ tests bodies default =>\n      cfoldCond\n      (cfold default)\n      (fun idx => cfold (tests idx))\n      (fun idx => cfold (bodies idx))\n  end.\n(* end thide *)\n\n(* begin thide *)\n(** To prove our final correctness theorem, it is useful to know that [cfoldCond] preserves expression meanings.  The following lemma formalizes that property.  The proof is a standard mostly automated one, with the only wrinkle being a guided instantiation of the quantifiers in the induction hypothesis. *)\n\nLemma cfoldCond_correct : forall t (default : exp' t)\n  n (tests : ffin n -> exp' Bool) (bodies : ffin n -> exp' t),\n  exp'Denote (cfoldCond default tests bodies)\n  = exp'Denote (Cond n tests bodies default).\n  induction n; crush;\n    match goal with\n      | [ IHn : forall tests bodies, _, tests : _ -> _, bodies : _ -> _ |- _ ] =>\n        specialize (IHn (fun idx => tests (Some idx)) (fun idx => bodies (Some idx)))\n    end;\n    repeat (match goal with\n              | [ |- context[match ?E with NConst _ => _ | _ => _ end] ] =>\n                dep_destruct E\n              | [ |- context[if ?B then _ else _] ] => destruct B\n            end; crush).\nQed.\n\n(** It is also useful to know that the result of a call to [cond] is not changed by substituting new tests and bodies functions, so long as the new functions have the same input-output behavior as the old.  It turns out that, in Coq, it is not possible to prove in general that functions related in this way are equal.  We treat this issue with our discussion of axioms in a later chapter.  For now, it suffices to prove that the particular function [cond] is _extensional_; that is, it is unaffected by substitution of functions with input-output equivalents. *)\n\nLemma cond_ext : forall (A : Set) (default : A) n (tests tests' : ffin n -> bool)\n  (bodies bodies' : ffin n -> A),\n  (forall idx, tests idx = tests' idx)\n  -> (forall idx, bodies idx = bodies' idx)\n  -> cond default tests bodies\n  = cond default tests' bodies'.\n  induction n; crush;\n    match goal with\n      | [ |- context[if ?E then _ else _] ] => destruct E\n    end; crush.\nQed.\n\n(** Now the final theorem is easy to prove. *)\n(* end thide *)\n\nTheorem cfold_correct : forall t (e : exp' t),\n  exp'Denote (cfold e) = exp'Denote e.\n(* begin thide *)\n  Hint Rewrite cfoldCond_correct.\n  Hint Resolve cond_ext.\n\n  induction e; crush;\n    repeat (match goal with\n              | [ |- context[cfold ?E] ] => dep_destruct (cfold E)\n            end; crush).\nQed.\n(* end thide *)\n\n(** We add our two lemmas as hints and perform standard automation with pattern-matching of subterms to destruct. *)\n\n(** * Choosing Between Representations *)\n\n(** It is not always clear which of these representation techniques to apply in a particular situation, but I will try to summarize the pros and cons of each.\n\n   Inductive types are often the most pleasant to work with, after someone has spent the time implementing some basic library functions for them, using fancy [match] annotations.  Many aspects of Coq's logic and tactic support are specialized to deal with inductive types, and you may miss out if you use alternate encodings.\n\n   Recursive types usually involve much less initial effort, but they can be less convenient to use with proof automation.  For instance, the [simpl] tactic (which is among the ingredients in [crush]) will sometimes be overzealous in simplifying uses of functions over recursive types.  Consider a call [get l f], where variable [l] has type [filist A (S n)].  The type of [l] would be simplified to an explicit pair type.  In a proof involving many recursive types, this kind of unhelpful \"simplification\" can lead to rapid bloat in the sizes of subgoals.  Even worse, it can prevent syntactic pattern-matching, like in cases where [filist] is expected but a pair type is found in the \"simplified\" version.  The same problem applies to applications of recursive functions to values in recursive types: the recursive function call may \"simplify\" when the top-level structure of the type index but not the recursive value is known, because such functions are generally defined by recursion on the index, not the value.\n\n   Another disadvantage of recursive types is that they only apply to type families whose indices determine their \"skeletons.\"  This is not true for all data structures; a good counterexample comes from the richly typed programming language syntax types we have used several times so far.  The fact that a piece of syntax has type [Nat] tells us nothing about the tree structure of that syntax.\n\n   Finally, Coq type inference can be more helpful in constructing values in inductive types.  Application of a particular constructor of that type tells Coq what to expect from the arguments, while, for instance, forming a generic pair does not make clear an intention to interpret the value as belonging to a particular recursive type.  This downside can be mitigated to an extent by writing \"constructor\" functions for a recursive type, mirroring the definition of the corresponding inductive type.\n\n   Reflexive encodings of data types are seen relatively rarely.  As our examples demonstrated, manipulating index values manually can lead to hard-to-read code.  A normal inductive type is generally easier to work with, once someone has gone through the trouble of implementing an induction principle manually with the techniques we studied in Chapter 3.  For small developments, avoiding that kind of coding can justify the use of reflexive data structures.  There are also some useful instances of %\\index{co-inductive types}%co-inductive definitions with nested data structures (e.g., lists of values in the co-inductive type) that can only be deconstructed effectively with reflexive encoding of the nested structures. *)\n", "meta": {"author": "duanjp8617", "repo": "cpdt", "sha": "de9529388da34632c540ef6f6def1960c6780d67", "save_path": "github-repos/coq/duanjp8617-cpdt", "path": "github-repos/coq/duanjp8617-cpdt/cpdt-de9529388da34632c540ef6f6def1960c6780d67/src/DataStruct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7068357275138556}}
{"text": "Require Import Ltac.\n(*Definitions of Logical Constants in Propect Calculus.*)\nNotation \"x '->' y\" := (forall (_ : x), y) (at level 99, right associativity, y at level 200). \nDefinition False : Prop := forall x:Prop, x.\nNotation \"⊥\" := False. \nDefinition not : Prop -> Prop := fun P:Prop => P->⊥.\nNotation \"¬ x\" := (not x) (at level 75, right associativity).\nDefinition and : Prop->Prop->Prop := fun P Q:Prop => forall x:Prop, (P -> Q -> x) -> x.\nNotation \"x ∧ y\" := (and x y) (at level 80, right associativity).\nTheorem and_intro : forall (P Q : Prop), P -> Q -> P ∧ Q.\nProof fun _ _ p q _ f => f p q.\nNotation \"'andi'\" := (and_intro _ _).\nTheorem and_elim1 : forall (P Q:Prop) (f:P∧Q), P.\nProof fun P Q:Prop => fun f:P∧Q => f P (fun p:P => fun q:Q => p).\nNotation \"'ande1'\" := (and_elim1 _ _).\nTheorem and_elim2 : forall (P Q:Prop) (f:P∧Q), Q.\nProof fun P Q:Prop => fun f:P∧Q => f Q (fun p:P => fun q:Q => q).\nNotation \"'ande2'\" := (and_elim2 _ _).\nDefinition or : Prop->Prop->Prop := fun P Q:Prop => forall x:Prop, (P->x)->(Q->x)->x.\nNotation \"x ∨ y\" := (or x y) (at level 85, right associativity).\nTheorem or_intro1 : forall P Q:Prop, P->P∨Q.\nProof fun P Q:Prop => fun p:P => fun x:Prop => fun f:P->x => fun g:Q->x => f p.\nNotation \"'ori1'\" := (or_intro1 _ _).\nTheorem or_intro2 : forall P Q:Prop, Q->P∨Q.\nProof fun P Q:Prop => fun q:Q => fun x:Prop => fun f:P->x => fun g:Q->x => g q.\nNotation \"'ori2'\" := (or_intro2 _ _).\nDefinition iff : Prop->Prop->Prop := fun P Q:Prop => (P->Q)∧(Q->P).\nNotation \"x ⇔ y\" := (iff x y) (at level 95, right associativity).\nTheorem iff_intro : forall P Q:Prop, (P->Q)->(Q->P)->P⇔Q.\nProof fun P Q:Prop => fun f:P->Q => fun g:Q->P => andi f g.\nNotation \"'iffi'\" := (iff_intro _ _).\nTheorem iff_elim1 : forall P Q:Prop, P⇔Q->P->Q.\nProof fun P Q:Prop => fun f:P⇔Q => fun p:P => (ande1 f) p.\nNotation \"'iffe1'\" := (iff_elim1 _ _).\nTheorem iff_elim2 : forall P Q:Prop, P⇔Q->Q->P.\nProof fun P Q:Prop => fun f:P⇔Q => fun q:Q => (ande2 f) q.\nNotation \"'iffe2'\" := (iff_elim2 _ _).\nDefinition eq (T:Type) : T->T->Prop := fun x y:T => forall P:T->Prop, P x->P y.\nNotation \"x = y\" := (eq _ x y) (at level 70).\nNotation \"x ≠ y\" := (¬ x = y) (at level 70). \nTheorem eq_intro (T:Type) : forall x:T, x=x.\nProof fun (x:T) (P:T->Prop) (f:P x) => f.\nNotation \"'eqi'\" := (eq_intro _).\nDefinition ex (T:Type) (P:T->Prop) : Prop := forall x:Prop, (forall t:T, P t->x)->x.\nNotation \"'∃' t ':' T ',' p\" := (ex T (fun t:T => p))  (at level 200, t name, right associativity). \nTheorem ex_intro (T:Type) (P:T->Prop) : forall t:T, P t->∃t:T, P t.\nProof fun t:T => fun p: P t => fun x:Prop => fun f:(forall t:T, P t->x) => f t p. \nNotation \"'exi'\" := (ex_intro _ _).\nTheorem ex_elim (T:Type) (P:T->Prop) (Q:T->Prop) : (∃t:T, P t)->(forall t:T, P t->Q t)->∃t:T, Q t.\nProof fun f:∃t:T, P t => fun g: forall t:T, P t->Q t => f (∃t:T, Q t) (fun t:T => fun h:P t => ex_intro _ _ _ (g t h)).\nNotation \"'exe'\" := (ex_elim _ _ _).\nDefinition exu (T:Type) (P:T->Prop) : Prop := (∃t:T, P t)∧forall t0 t1:T, P t0->P t1->t0=t1.\nNotation \"'∃!' t ':' T ',' p\" := (exu T (fun t:T => p))  (at level 200, t name, right associativity). \nTheorem exu_intro (T:Type) (P:T->Prop) : (∃t:T, P t)->(forall t0 t1:T, P t0->P t1->t0=t1)->∃!t:T, P t.\nProof fun (h:∃t:T, P t) (h1:forall t0 t1:T, P t0->P t1->t0=t1) => andi h h1.\nNotation \"'exui'\" := (exu_intro _ _).\nTheorem exu_elim1 (T:Type) (P:T->Prop) : (∃!t:T, P t)->∃t:T, P t.\nProof fun h:∃!t:T, P t => ande1 h.\nNotation \"'exue1'\" := (exu_elim1 _ _).\nTheorem exu_elim2 (T:Type) (P:T->Prop) : (∃!t:T, P t)->forall t0 t1:T, P t0->P t1->t0=t1.\nProof fun h:∃!t:T, P t => ande2 h.\nNotation \"'exue2'\" := (exu_elim2 _ _).\nParameter hilberts_epsilon : forall (T:Type) (P:T->Prop), (∃t:T, P t)->T.\nNotation \"'eps' x\" := (hilberts_epsilon _ _ x) (at level 100).\nAxiom definition : forall (T:Type) (P:T->Prop) (p:∃t:T, P t), P (eps p).\nNotation \"'def' x\" := (definition _ _ x) (at level 100).\n\n\n\n\n\n\n\n\n", "meta": {"author": "sudhirking2", "repo": "Projects-encoding-ToB-in-CoQ-", "sha": "8d0805d0d7e2bc8729c9a5130eec5c9284f822e6", "save_path": "github-repos/coq/sudhirking2-Projects-encoding-ToB-in-CoQ-", "path": "github-repos/coq/sudhirking2-Projects-encoding-ToB-in-CoQ-/Projects-encoding-ToB-in-CoQ--8d0805d0d7e2bc8729c9a5130eec5c9284f822e6/Foundations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664175, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7068357238580759}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Binary relations                                                        *\n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import LibTactics LibLogic LibBool LibLogic LibProd LibSum.\nRequire Export LibOperation.\n\n\n(* ********************************************************************** *)\n(** * Generalities on binary relations *)\n\nDefinition binary (A : Type) := A -> A -> Prop.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inhabited *)\n\nInstance binary_inhab : forall A, Inhab (binary A).\nProof. intros. apply (prove_Inhab (fun _ _ => True)). Qed.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Extensionality *)\n\nLemma binary_extensional : forall A (R1 R2:binary A),\n  (forall x y, R1 x y <-> R2 x y) -> R1 = R2.\nProof. intros_all. apply~ prop_ext_2. Qed.\n\nInstance binary_extensional_inst : forall A, Extensional (binary A).\nProof. intros. apply (Build_Extensional _ (@binary_extensional A)). Defined.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nSection Properties.\nVariables (A:Type).\nImplicit Types x y z : A.\nImplicit Types R : binary A.\n\n(** Reflexivity, irreflexivity, transitivity, symmetry, totality *)\n\nDefinition refl R := \n  forall x, R x x.\nDefinition irrefl R := \n  forall x, ~ (R x x).\nDefinition trans R := \n  forall y x z, R x y -> R y z -> R x z.\nDefinition sym R := \n  forall x y, R x y -> R y x.\nDefinition asym R := \n  forall x y, R x y -> ~ R y x.\nDefinition total R :=\n  forall x y, R x y \\/ R y x.\n\n(** Antisymmetry with respect to an equivalence relation, \n    antisymmetry with respect to Leibnitz equality,\n     i.e. [forall x y, R x y -> R y x -> x = y] *)\n\nDefinition antisym_wrt (E:binary A) R :=\n  forall x y, R x y -> R y x -> E x y.\nDefinition antisym := \n  antisym_wrt (@eq A).\n\n(** Inclusion between relations *)\n\nDefinition incl R1 R2 :=\n  forall x y, R1 x y -> R2 x y.\n\n(** Equality between relations *)\n\nLemma rel_eq_intro : forall R1 R2,\n  (forall x y, R1 x y <-> R2 x y) -> R1 = R2.\nProof. intros. extens*. Qed.\n\nLemma rel_eq_elim : forall R1 R2,\n  R1 = R2 -> (forall x y, R1 x y <-> R2 x y).\nProof. intros. subst*. Qed.\n\nEnd Properties.\n\n(* ---------------------------------------------------------------------- *)\n(** ** Constructions *)\n\nSection Constructions.\nVariable (A : Type).\nImplicit Types R : binary A.\nImplicit Types x y z : A.\n\n(** The empty relation *)\n\nDefinition empty : binary A :=\n  fun x y => False.\n\n(** Swap (i.e. symmetric, converse, or transpose) of a relation *)\n \nDefinition flip R : binary A := \n  fun x y => R y x.\n\n(** Complement of a relation *)\n \nDefinition compl R : binary A := \n  fun x y => ~ R y x.\n\n(** Union of two relations *)\n\nDefinition union R1 R2 : binary A :=\n  fun x y => R1 x y \\/ R2 x y.\n\n(** Strict order associated with an order, wrt Leibnitz' equality *)\n\nDefinition strict R : binary A :=\n  fun x y => R x y /\\ x <> y.\n\n(** Large order associated with an order, wrt Leibnitz' equality *)\n\nDefinition large R : binary A :=\n  fun x y => R x y \\/ x = y.\n\nEnd Constructions.\n\n(** Inverse image *)\n\nDefinition inverse_image (A B:Type) (R:binary B) (f:A->B) : binary A :=\n  fun x y => R (f x) (f y).\n\n(** Pointwise product *)\n\nDefinition prod2 (A1 A2:Type) \n (R1:binary A1) (R2:binary A2) : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => match p1,p2 with (x1,x2),(y1,y2) => \n    R1 x1 y1 /\\ R2 x2 y2 end.\n\nDefinition prod3 (A1 A2 A3:Type) \n (R1:binary A1) (R2:binary A2) (R3:binary A3) \n : binary (A1*A2*A3) := \n  prod2 (prod2 R1 R2) R3.\n\nDefinition prod4 (A1 A2 A3 A4:Type) \n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4) \n : binary (A1*A2*A3*A4) := \n  prod2 (prod3 R1 R2 R3) R4.\n\nTactic Notation \"unfold_prod\" :=\n  unfold prod4, prod3, prod2.\n\nTactic Notation \"unfolds_prod\" :=\n  unfold prod4, prod3, prod2 in *.\n\n(** Lexicographical order *)\n\nDefinition lexico2 {A1 A2} (R1:binary A1) (R2:binary A2)\n  : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => let (x1,x2) := p1 in let (y1,y2) := p2 in\n  (R1 x1 y1) \\/ (x1 = y1) /\\ (R2 x2 y2).\n\nDefinition lexico3 {A1 A2 A3} \n (R1:binary A1) (R2:binary A2) (R3:binary A3) : binary (A1*A2*A3) :=\n  lexico2 (lexico2 R1 R2) R3.\n\nDefinition lexico4 {A1 A2 A3 A4}\n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4) \n : binary (A1*A2*A3*A4) :=\n  lexico2 (lexico3 R1 R2 R3) R4.\n\nTactic Notation \"unfold_lexico\" :=\n  unfold lexico4, lexico3, lexico2.\n\nTactic Notation \"unfolds_lexico\" :=\n  unfold lexico4, lexico3, lexico2 in *.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of constructions *)\n\nSection ConstructionsProp.\nVariable (A : Type).\nImplicit Types R : binary A.\nImplicit Types x y z : A.\n\nLemma refl_elim : forall x y R,\n  refl R -> x = y -> R x y.\nProof. intros_all. subst~. Qed.\n\nLemma sym_elim : forall x y R,\n  sym R -> R x y -> R y x.\nProof. introv Sy R1. apply* Sy. Qed.\n\nLemma antisym_elim : forall x y R,\n  antisym R -> R x y -> R y x -> x <> y -> False.\nProof. intros_all*. Qed.\n\nLemma irrefl_neq : forall R,\n  irrefl R -> \n  forall x y, R x y -> x <> y. \nProof. introv H P E. subst. apply* H. Qed.\n\nLemma irrefl_elim : forall R,\n  irrefl R -> \n  forall x, R x x -> False. \nProof. introv H P. apply* H. Qed.\n\nLemma sym_to_eq : forall R,\n  sym R -> \n  forall x y, R x y = R y x.\nProof. introv H. intros. apply prop_ext. split; apply H. Qed.\n\nLemma sym_flip : forall R,\n  sym R -> flip R = R.\nProof. intros. unfold flip. apply* prop_ext_2. Qed.\n\nLemma trans_strict : forall R,\n  trans R -> antisym R -> trans (strict R).\nProof. \n  introv T S. unfold strict. introv [H1 H2] [H3 H4]. split. \n    apply* T.\n    intros K. subst. apply H2. apply~ S.\nQed.\n\nLemma flip_flip : forall R, \n  flip (flip R) = R.\nProof. intros. apply* prop_ext_2. Qed.\n\nLemma flip_refl : forall R,\n  refl R -> refl (flip R).\nProof. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_trans : forall R,\n  trans R -> trans (flip R).\nProof. intros_all. unfolds flip. eauto. Qed.\n\nLemma flip_antisym : forall R,\n  antisym R -> antisym (flip R).\nProof. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_asym : forall R,\n  asym R -> asym (flip R).\nProof. intros_all. unfolds flip. apply* H. Qed.\n\nLemma flip_total : forall R,\n  total R -> total (flip R).\nProof. intros_all. unfolds flip. auto. Qed.\n\nLemma flip_strict : forall R,\n  flip (strict R) = strict (flip R).\nProof. intros. unfold flip, strict. apply* prop_ext_2. Qed.\n\nLemma flip_large : forall R,\n  flip (large R) = large (flip R).\nProof. intros. unfold flip, large. apply* prop_ext_2. Qed.\n\nLemma large_refl : forall R,\n  refl (large R).\nProof. unfold large. intros_all~. Qed.\n\nLemma large_trans : forall R,\n  trans R -> trans (large R).\nProof. unfold large. introv Tr [H1|E1] [H2|E2]; subst*. Qed.\n\nLemma large_antisym : forall R,\n  antisym R -> antisym (large R).\nProof. introv T. introv H1 H2. (* todo: bug introv *)\n  unfolds large. destruct H1; destruct H2; auto. Qed.\n\nLemma large_total : forall R,\n  total R -> total (large R).\nProof. unfold large. intros_all~. destruct* (H x y). Qed.\n\nLemma strict_large : forall R,\n  irrefl R -> strict (large R) = R.\nProof.\n  intros. unfold large, strict. apply prop_ext_2.\n  intros_all. split; intros K.\n  auto*.\n  split. left*. apply* irrefl_neq. \nQed.\n\nLemma large_strict : forall R,\n  refl R -> large (strict R) = R.\nProof. \n  intros. unfold large, strict. apply prop_ext_2. \n  intros_all. split; intros K.\n  destruct K. auto*. subst*.\n  destruct (classic (x1 = x2)). subst. right*. left*.\n  (* todo: cases *)\nQed.\n\nLemma double_incl : forall R1 R2,\n  incl R1 R2 -> incl R2 R1 -> R1 = R2.\nProof. unfolds incl. intros. apply* prop_ext_2. Qed. \n\nLemma flip_injective : injective (@flip A).\nProof.\n  intros R1 R2 E. apply prop_ext_2. intros x y.\n  unfolds flip. rewrite* (func_same_2 y x E).\nQed.\n\nLemma eq_by_flip_l : forall R1 R2,\n  R1 = flip R2 -> flip R1 = R2.\nProof. intros. apply flip_injective. rewrite~ flip_flip. Qed.\n\nLemma eq_by_flip_r : forall R1 R2,\n  flip R1 = R2 -> R1 = flip R2.\nProof. intros. apply flip_injective. rewrite~ flip_flip. Qed.\n\n(* TODO: do we really need this extensional version? *)\n\nLemma flip_flip_applied : forall R x y, \n  (flip (flip R)) x y = R x y.\nProof. auto. Qed.\n\nEnd ConstructionsProp.\n\nLemma trans_elim : forall A (y x z : A) R,\n  trans R -> R x y -> R y z -> R x z.\nProof. introv Tr R1 R2. apply* Tr. Qed.\n\nLemma trans_sym : forall A (y x z : A) R,\n  trans R -> sym R -> R z y -> R y x -> R x z.\nProof. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_1 : forall A (y x z : A) R,\n  trans R -> sym R -> R y x -> R y z -> R x z.\nProof. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_2 : forall A (y x z : A) R,\n  trans R -> sym R -> R x y -> R z y -> R x z.\nProof. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nImplicit Arguments trans_elim [A x z R].\nImplicit Arguments trans_sym [A x z R].\nImplicit Arguments trans_sym_1 [A x z R].\nImplicit Arguments trans_sym_2 [A x z R].\n\n(** Other forms of transitivity *)\n\nLemma large_strict_trans : forall A y x z (R:binary A),\n  trans R -> large R x y -> R y z -> R x z.\nProof. introv T [E|H] H'; subst*. Qed.\n\nLemma strict_large_trans : forall A y x z (R:binary A),\n  trans R -> R x y -> large R y z -> R x z.\nProof. introv T H [E|H']; subst*. Qed.\n\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of inclusion *)\n\nLemma incl_refl : forall A (R:binary A), incl R R.\nProof. unfolds incl. auto. Qed.\n\nHint Resolve incl_refl. \n\nLemma lexico2_incl : forall A1 A2\n (R1 R1':binary A1) (R2 R2':binary A2),\n  incl R1 R1' -> incl R2 R2' -> incl (lexico2 R1 R2) (lexico2 R1' R2').\nProof. \n  introv I1 I2. intros [x1 x2] [y1 y2] [H1|[H1 H2]].\n  left~. subst. right~.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of lexicographical composition *)\n\nSection LexicoApp.\nVariables (A1 A2 A3 A4:Type). \nVariables (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4). \n\nLemma lexico2_app_1 : forall x1 x2 y1 y2,\n  R1 x1 y1 -> \n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof. intros. left~. Qed.\n\nLemma lexico2_app_2 : forall x1 x2 y1 y2,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof. intros. right~. Qed.\n\nLemma lexico3_app_1 : forall x1 x2 x3 y1 y2 y3,\n  R1 x1 y1 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof. intros. left. left~. Qed.\n\nLemma lexico3_app_2 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof. intro. left. right~. Qed.\n\nLemma lexico3_app_3 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 -> x2 = y2 -> R3 x3 y3 -> \n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof. intros. right~. Qed.\n\nLemma lexico4_app_1 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  R1 x1 y1 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof. intros. left. left. left~. Qed.\n\nLemma lexico4_app_2 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> R2 x2 y2 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof. intros. left. left. right~. Qed.\n\nLemma lexico4_app_3 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> x2 = y2 -> R3 x3 y3 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof. intros. left. right~. Qed.\n\nLemma lexico4_app_4 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 -> x2 = y2 -> x3 = y3 -> R4 x4 y4 -> \n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof. intros. right~. Qed.\n\nEnd LexicoApp.\n\n(** Transitivity *)\n\nLemma lexico2_trans : forall A1 A2 \n (R1:binary A1) (R2:binary A2),\n  trans R1 -> trans R2 -> trans (lexico2 R1 R2).\nProof.\n  introv Tr1 Tr2. intros [x1 x2] [y1 y2] [z1 z2] Rxy Ryz.\n  simpls. destruct Rxy as [L1|[Eq1 L1]]; \n   destruct Ryz as [M2|[Eq2 M2]]; subst*.\nQed.\n\nLemma lexico3_trans : forall A1 A2 A3 \n (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  trans R1 -> trans R2 -> trans R3 -> trans (lexico3 R1 R2 R3).\nProof.\n  introv Tr1 Tr2 Tr3. applys~ lexico2_trans. applys~ lexico2_trans.\nQed.\n\nLemma lexico4_trans : forall A1 A2 A3 A4 \n (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  trans R1 -> trans R2 -> trans R3 -> trans R4 -> trans (lexico4 R1 R2 R3 R4).\nProof.\n  introv Tr1 Tr2 Tr3. applys~ lexico3_trans. applys~ lexico2_trans.\nQed.\n\n\n\n(* ********************************************************************** *)\n(** * Equivalence relations *)\n\nRecord equiv A (R:binary A) :=\n { equiv_refl : refl R;\n   equiv_sym : sym R;\n   equiv_trans : trans R }. \n\n(** Equality is an equivalence *)\n\nLemma eq_equiv : forall A, equiv (@eq A).\nProof. intros. constructor; intros_all; subst~. Qed.\n\nHint Resolve eq_equiv.\n\n(** Symmetric of an equivalence is an equivalence *)\n\nLemma flip_equiv : forall A (E:binary A),\n  equiv E -> equiv (flip E).\nProof.\n  introv Equi. unfold flip. constructor; intros_all*.\nQed.\n\n(** Product of two equivalences is an equivalence *)\n\nLemma prod2_equiv : forall A1 A2 (E1:binary A1) (E2:binary A2),\n  equiv E1 -> equiv E2 -> equiv (prod2 E1 E2).\nProof.\n  introv Equi1 Equi2. constructor.\n  intros [x1 x2]. simple*.\n  intros [x1 x2] [y1 y2]. simple*.\n  intros [x1 x2] [y1 y2] [z1 z2]. simple*.\nQed.\n\n(* todo: other arities of Prod *)\n\n\n(**************************************************************************)\n(* * Closures *)\n\nSection Closures.\nVariables (A : Type) (R : binary A).\n\n(* ---------------------------------------------------------------------- *)\n(** ** Constructions *)\n\n(** Reflexive-transitive closure ( R* ) *)\n\nInductive rtclosure : binary A :=\n  | rtclosure_refl : forall x,\n      rtclosure x x\n  | rtclosure_step : forall y x z,\n      R x y -> rtclosure y z -> rtclosure x z.\n\n(** Transitive closure ( R+ ) *)\n\nInductive tclosure : binary A :=\n  | tclosure_intro : forall x y z,\n     R x y -> rtclosure y z -> tclosure x z.\n\n(** Another definition of transitive closure ( R+ ) *)\n\nInductive tclosure' : binary A :=\n  | tclosure'_step : forall x y,  \n     R x y -> tclosure' x y\n  | tclosure'_trans : forall y x z,\n     tclosure' x y -> tclosure' y z -> tclosure' x z.\n\n(** Symmetric-transitive closure *)\n\nInductive stclosure (A:Type) (R:binary A) : binary A :=\n  | stclosure_step : forall x y,\n      R x y -> stclosure R x y\n  | stclosure_sym : forall x y, \n      stclosure R x y -> stclosure R y x\n  | stclosure_trans : forall y x z,\n      stclosure R x y -> stclosure R y z -> stclosure R x z.\n\n(* TODO Reflexive-symmetric-transitive closure ( R== ) \n\nInductive equiv : binary A :=\n  | equiv_step : forall x y,\n      R x y -> equiv x y\n  | equiv_refl : forall x,\n      equiv x x\n  | equiv_sym : forall x y, \n      equiv x y -> equiv y x\n  | equiv_trans : forall y x z,\n      equiv x y -> equiv y z -> equiv x z.\n*)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties *)\n\nHint Constructors tclosure rtclosure equiv.\n\nLemma rtclosure_once : forall x y,\n  R x y -> rtclosure x y.\nProof. auto*. Qed.\n\nHint Resolve rtclosure_once.\n\nLemma rtclosure_trans : trans rtclosure.  \nProof. introv R1 R2. induction* R1. Qed.\n\nLemma rtclosure_last : forall y x z,\n  rtclosure x y -> R y z -> rtclosure x z.\nProof. introv R1 R2. induction* R1. Qed.\n\nHint Resolve rtclosure_trans.\n\nLemma tclosure_once : forall x y,\n  R x y -> tclosure x y.  \nProof. eauto. Qed.\n\nLemma tclosure_rtclosure : forall x y,\n  tclosure x y -> rtclosure x y.  \nProof. intros. destruct* H. Qed.\n\nHint Resolve tclosure_once tclosure_rtclosure.\n\nLemma tclosure_rtclosure_step : forall x y z,\n  rtclosure x y -> R y z -> tclosure x z.\nProof. intros. induction* H. Qed.\n\nLemma tclosure_step_rtclosure : forall x y z,\n  R x y -> rtclosure y z -> tclosure x z.\nProof. intros. gen x. induction* H0. Qed.\n\nLemma tclosure_step_tclosure : forall x y z,\n  R x y -> tclosure y z -> tclosure x z.\nProof. intros. inverts* H0. Qed.\n\nHint Resolve tclosure_rtclosure_step tclosure_step_rtclosure.\n\nLemma tclosure_rtclosure_tclosure : forall y x z,\n  rtclosure x y -> tclosure y z -> tclosure x z.  \nProof. intros. gen z. induction* H. Qed.\n\nLemma tclosure_tclosure_rtclosure : forall y x z,\n  tclosure x y -> rtclosure y z -> tclosure x z.  \nProof. intros. induction* H. Qed. \n\nLemma tclosure_trans : trans tclosure.\nProof. intros_all. auto* tclosure_tclosure_rtclosure. Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Induction *)\n\n(** Star induction principle with transitivity hypothesis *)\n\nLemma rtclosure_ind_trans : forall (P : A -> A -> Prop),\n  (forall x : A, P x x) ->\n  (forall x y : A, R x y -> P x y) ->\n  (forall y x z : A, rtclosure x y -> P x y -> rtclosure y z -> P y z -> P x z) ->\n  forall x y : A, rtclosure x y -> P x y.\nProof.\n  introv Hrefl Hstep Htrans S. induction S.\n  auto. apply~ (@Htrans y).\nQed.\n\n(** Star induction principle with steps at the end *)\n\nLemma rtclosure_ind_right : forall (P : A -> A -> Prop),\n  (forall x : A, P x x) ->\n  (forall y x z : A, rtclosure x y -> P x y -> R y z -> P x z) ->\n  forall x y : A, rtclosure x y -> P x y.\nProof.\n  introv Hrefl Hlast. apply rtclosure_ind_trans. \n  auto.\n  intros. apply~ (Hlast x).\n  introv S1 P1 S2 _. gen x. induction S2; introv S1 P1.\n     auto.\n     apply IHS2. eauto. apply~ (Hlast x). \nQed.\n\nEnd Closures.\n\nHint Resolve rtclosure_refl rtclosure_step rtclosure_once : rtclosure.\n(* TODO: should rename and complete the [closure] database *)\n(* TODO: should not need to re-export the following version *)\n\nLemma incl_tclosure_self : forall A (R:binary A), \n   incl R (tclosure R).\nProof. unfolds incl. intros. apply~ tclosure_once. Qed.\nHint Resolve incl_tclosure_self. \n\n(* TODO: sort and complete the following *)\n\nHint Resolve stclosure_step stclosure_sym stclosure_trans.\n\nLemma stclosure_le : forall A (R1 R2 : binary A),\n  incl R1 R2 -> incl (stclosure R1) (stclosure R2).\nProof. unfolds incl. introv Le H. induction* H. Qed.\n", "meta": {"author": "Ayertienna", "repo": "IS5", "sha": "3bfd1b8510f269071d59d77818f8936d194364bc", "save_path": "github-repos/coq/Ayertienna-IS5", "path": "github-repos/coq/Ayertienna-IS5/IS5-3bfd1b8510f269071d59d77818f8936d194364bc/lib/tlc/LibRelation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7068357191110424}}
{"text": "(* 2.6 Realizing Specifications *)\nRequire Import Arith ZArith Bool.\nOpen Scope Z_scope.\n\nSection realization.\n  Variables (A B : Set).\n  Let spec: Set := (((A -> B) -> B) -> B) -> A -> B.\n  Let realization : spec := fun f a => f (fun g => g a).\n  Print realization.\n  (* realization : spec :=\n     fun (f : ((A -> B) -> B) -> B) (a : A)\n         => f (fun g : A -> B => g a) *)\n\n  Example spec_proof : spec.\n  Proof using A B.\n    intros f a. apply f. intro g. apply g, a.\n  Qed.\n\n  Print spec_proof.\n  (* spec_proof : spec =\n     fun (f : ((A -> B) -> B) -> B) (a : A)\n         => f (fun g : A -> B => g a) *)\n\nEnd realization.\n\nDefinition nat_fun_to_Z_fun : Set := (nat -> nat) -> Z -> Z.\n\nDefinition absolute_fun : nat_fun_to_Z_fun\n  := fun f z => Z_of_nat (f (Z.abs_nat z)).\n\nDefinition always_O : nat_fun_to_Z_fun\n  := fun _ _ => 0%Z.\n\nDefinition to_marignan : nat_fun_to_Z_fun\n  := fun _ _ => 1515%Z.\n\nDefinition ignore_f : nat_fun_to_Z_fun\n  := fun _ z => z.\n\nDefinition from_marignan : nat_fun_to_Z_fun\n  := fun f _ => Z_of_nat (f 1515%nat).\n", "meta": {"author": "anton0xf", "repo": "coq-art", "sha": "eed9782f0b62b4aaa9b33c2270931230ebb09ae6", "save_path": "github-repos/coq/anton0xf-coq-art", "path": "github-repos/coq/anton0xf-coq-art/coq-art-eed9782f0b62b4aaa9b33c2270931230ebb09ae6/ch02/2.6_realizing_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7068357171649465}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf3 : natural) (lf2 : natural) : natural :=\n  plus (plus lf3 z) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_assoc/goal33conj163_coqofml_w0m0wy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7067578974533532}}
{"text": "(**\n   Bounded join-semilattices over natural numbers.\n\n   Logic and Lattices in Distributed Programming\n   by Conway, Marczak, Alvaro, Hellerstein, Maier.\n   http://db.cs.berkeley.edu/papers/UCB-lattice-tr.pdf\n**)\n\nRequire Export Max.\nRequire Export Min.\nRequire Export Sets.Ensembles.\n\nModule JoinSemiLattice.\n\n(* Boolean lattice, values advance from false -> true *)\nInductive lbool : Type :=\n  | LBoolValue  : bool -> lbool.\n\nHint Constructors lbool.\n\nDefinition lbool_reveal lb :=\n  match lb with\n    | LBoolValue b => b\n  end.\n\nDefinition lbool_merge lb1 lb2 :=\n  match (lb1, lb2) with\n    | (LBoolValue b1, LBoolValue b2) => (LBoolValue (orb b1 b2))\n  end.\n\n(* Proofs regarding the merge operation follows ACI *)\nTheorem lbool_merge_assoc : forall (lb1 lb2 lb3 : lbool),\n  lbool_merge (lbool_merge lb1 lb2) lb3 =\n    lbool_merge lb3 (lbool_merge lb1 lb2).\nProof with eauto.\n  destruct lb1; destruct lb2; destruct lb3...\n    destruct b; destruct b0; destruct b1...\nQed.\n\nTheorem lbool_merge_comm : forall (lb1 lb2 : lbool),\n  lbool_merge lb1 lb2 = lbool_merge lb2 lb1.\nProof with eauto.\n  induction lb1; induction lb2...\n    destruct b; destruct b0...\nQed.\n\nTheorem lbool_merge_idemp : forall (lb : lbool),\n  lbool_merge lb lb = lb.\nProof with eauto.\n  induction lb... destruct b...\nQed.\n\n(* Max-value lattice, values monotonically advance upwards. *)\nInductive lmax_nat : Type :=\n  | LMaxNatValue  : forall (n : nat), lmax_nat.\n\nHint Constructors lmax_nat.\n\nDefinition lmax_nat_reveal lm :=\n  match lm with\n    | LMaxNatValue n => n\n  end.\n\nDefinition lmax_nat_merge lm1 lm2 :=\n  match (lm1, lm2) with\n    | (LMaxNatValue n1, LMaxNatValue n2) => (LMaxNatValue (max n1 n2))\n  end.\n\n(* Proofs regarding the merge operation follows ACI *)\nTheorem lmax_nat_merge_assoc : forall (lm1 lm2 lm3 : lmax_nat),\n  lmax_nat_merge (lmax_nat_merge lm1 lm2) lm3 =\n    lmax_nat_merge lm3 (lmax_nat_merge lm1 lm2).\nProof with eauto.\n  destruct lm1; destruct lm2; destruct lm3; eauto;\n    unfold lmax_nat_merge; rewrite max_comm...\nQed.\n\nTheorem lmax_nat_merge_comm : forall (lm1 lm2 : lmax_nat),\n  lmax_nat_merge lm1 lm2 = lmax_nat_merge lm2 lm1.\nProof with eauto.\n  destruct lm1; destruct lm2...\n    try unfold lmax_nat_merge; rewrite max_comm...\nQed.\n\nTheorem lmax_nat_merge_idemp : forall (lm : lmax_nat),\n  lmax_nat_merge lm lm = lm.\nProof with eauto.\n  destruct lm; unfold lmax_nat_merge...\n    rewrite max_idempotent...\nQed.\n\n(* Min-value lattice, values monotonically advance downwards. *)\nInductive lmin_nat : Type :=\n  | LMinNatValue  : forall (n : nat), lmin_nat.\n\nHint Constructors lmin_nat.\n\nDefinition lmin_nat_reveal lm :=\n  match lm with\n    | LMinNatValue n => n\n  end.\n\nDefinition lmin_nat_merge lm1 lm2 :=\n  match (lm1, lm2) with\n    | (LMinNatValue n1, LMinNatValue n2) => (LMinNatValue (min n1 n2))\n  end.\n\n(* Proofs regarding the merge operation follows ACI *)\nTheorem lmin_nat_merge_assoc : forall (lm1 lm2 lm3 : lmin_nat),\n  lmin_nat_merge (lmin_nat_merge lm1 lm2) lm3 =\n    lmin_nat_merge lm3 (lmin_nat_merge lm1 lm2).\nProof with eauto.\n  destruct lm1; destruct lm2; destruct lm3; eauto;\n    unfold lmin_nat_merge; rewrite min_comm...\nQed.\n\nTheorem lmin_nat_merge_comm : forall (lm1 lm2 : lmin_nat),\n  lmin_nat_merge lm1 lm2 = lmin_nat_merge lm2 lm1.\nProof with eauto.\n  destruct lm1; destruct lm2...\n    try unfold lmin_nat_merge; rewrite min_comm...\nQed.\n\nTheorem lmin_nat_merge_idemp : forall (lm : lmin_nat),\n  lmin_nat_merge lm lm = lm.\nProof with eauto.\n  destruct lm; unfold lmin_nat_merge...\n    rewrite min_idempotent...\nQed.\n\nEnd JoinSemiLattice.\n", "meta": {"author": "cmeiklejohn", "repo": "distributed-data-structures", "sha": "53a03c3b526d6daf12cbf4b318d7d1f2d6e14605", "save_path": "github-repos/coq/cmeiklejohn-distributed-data-structures", "path": "github-repos/coq/cmeiklejohn-distributed-data-structures/distributed-data-structures-53a03c3b526d6daf12cbf4b318d7d1f2d6e14605/JoinSemiLattice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958426, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7067578919202747}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import lex_order.\nSection IS.\nVariable V : nat. (* The number of vertices *)\nVariable E : list (nat*nat).\n\nVariable NoSelfEdges : forall x : nat, ~ In (x,x) E.\nVariable Edges_lt_V : forall x y, In (x, y) E -> x < V.\nVariable EdgesBidirectional : \n  forall x y : nat, In (x,y) E -> In (y,x) E.\n\nDefinition ValidSet (X : list nat) :=\n  forall x : nat, In x X -> x < V.\n\nDefinition Independent (X : list nat) :=\n  forall x y, In x X -> In y X -> ~ In (x,y) E.\n\nInductive IndSet (X : list nat) : Prop :=\n| defIndSet : ValidSet X -> Independent X -> IndSet X.\n\nInductive MaximalIndSet (X : list nat) : Prop :=\n| defMaximalIndSet :\n    IndSet X ->\n    (forall x, IndSet (x::X) -> In x X) ->\n      MaximalIndSet X.\n\nInductive MaximalIndSet_contrapos (X : list nat) : Prop :=\n| defMaximalIndSet_contrapos :\n    IndSet X ->\n    (forall x, ~ In x X -> ~ IndSet (x::X)) ->\n      MaximalIndSet_contrapos X.\n\nTheorem MaximalIndSet_eq : forall X, MaximalIndSet X <-> MaximalIndSet_contrapos X.\nProof.\n  split; intros; constructor; intros. inversion H. auto.\n  inversion H. intros Hcontra. apply H0. apply H2. auto.\n  inversion H. auto. inversion H. destruct (in_dec eq_nat_dec x X).\n  auto. apply H2 in n. contradiction.\nQed.\n  \n\nTheorem validSetRecr : \n  forall (x : nat) (X : list nat), ValidSet (x::X) -> ValidSet X.\nProof.\n  intros. intros y H0.\n  apply H. right. auto.\nQed.\n\nTheorem ValidSet_dec :\n  forall X : list nat, {ValidSet X}+{~ValidSet X}.\nProof.\n  intros. induction X.\n  left. intros x H. inversion H.\n  destruct IHX. assert ( {V <= a} + {a < V}).\n  apply le_lt_dec. destruct H. \n  right. intros H0. \n  assert (In a (a::X)). left. auto.\n  apply H0 in H. omega. left.\n  intros b H. destruct H. omega.\n  apply v in H. auto. right.\n  intros H. apply validSetRecr in H.\n  auto.\nDefined.\n\nTheorem edgeEqDec : forall X Y : (nat*nat), {X=Y} + {X<>Y}.\nProof.\n  intros.\n  destruct X.\n  destruct Y.\n  assert ({n=n1}+{n<>n1}).\n  apply eq_nat_dec.\n  assert ({n0= n2}+{n0<>n2}).\n  apply eq_nat_dec.\n  destruct H.\n  destruct H0.\n  left. intuition.\n  right.\n  intuition. inversion H.\n  intuition.\n  right.\n  unfold not. intros.\n  inversion H.\n  intuition.\nDefined.\n \n\nTheorem inEdgeDec : forall X : (nat*nat), {In X E}+{~In X E}.\nProof.\n  intros.\n  clear NoSelfEdges Edges_lt_V EdgesBidirectional.\n  induction E.\n  right. unfold not. intros. inversion H.\n  destruct IHl.\n  left. intuition.\n  assert ({X =a}+{~X=a}).\n  apply edgeEqDec.\n  destruct H.\n  left. intuition.\n  simpl.\n  left. intuition.\n  right. simpl.\n  unfold not. intros.\n  intuition.\nDefined.  \n\nFixpoint vertexConnected (v : nat) (S : list nat) : bool :=\n  match S with\n  | nil => false\n  | cons s S' => if inEdgeDec (v,s) then true else vertexConnected v S'\n  end.\n\nTheorem vertexConnected_spec :\nforall (v : nat) (S: list nat),\n    vertexConnected v S = true <-> exists (v' : nat), In v' S /\\ In (v,v') E. \nProof.\n  split; intros;\n  induction S.\n  simpl in H.\n  inversion H.\n  simpl vertexConnected in H.\n  destruct inEdgeDec in H.\n  exists a.\n  split; intuition.\n  apply IHS in H.\n  destruct H.\n  exists x. split; intuition.\n  destruct H.\n  destruct H.\n  inversion H.\n  simpl.\n  destruct inEdgeDec.\n  intuition.\n  destruct H.\n  destruct H.\n  apply IHS.\n  exists x.\n  simpl in H.\n  destruct H.\n  replace x in H0.\n  intuition.\n  intuition.\nQed.\n\nTheorem vertexConnected_spec_neg :\nforall (v : nat) (S: list nat),\n  vertexConnected v S = false <-> ~ exists (v' : nat), In v' S /\\ In (v,v') E.\nProof.\n  split.\n  unfold not.\n  intros.\n  apply vertexConnected_spec in H0.\n  replace (vertexConnected v S) with false in H0.\n  intuition.\n  intros.\n  unfold not in H.\n  assert ({vertexConnected v S = true} + {vertexConnected v S = false}).\n  destruct vertexConnected; intuition.\n  destruct H0.\n  apply vertexConnected_spec in e.\n  intuition.\n  intuition.\nQed.  \n\nFixpoint independent (X :  list nat) :=\n  match X with\n  | nil => true\n  | x::X' => if vertexConnected x X then false else independent X'\n  end.\n\nTheorem independent_spec :\nforall X : list nat,\n  independent X = true <-> Independent X. \nProof.\n  unfold Independent. split. \n  intros. induction X. inversion H0.\n  simpl In in H0. simpl In in H1.\n  destruct H0; destruct H1;\n  repeat subst. inversion H.\n  destruct inEdgeDec in H1.\n  inversion H1. assumption.  \n  inversion H. destruct inEdgeDec in H2.\n  inversion H2. remember (vertexConnected x X).\n  destruct b. inversion H2.\n  symmetry in Heqb. apply vertexConnected_spec_neg in Heqb.\n  intros H3. apply Heqb. exists y; split; assumption.\n  inversion H. destruct inEdgeDec in H2.\n  inversion H2. remember (vertexConnected y X).\n  destruct b. inversion H2.\n  symmetry in Heqb. apply vertexConnected_spec_neg in Heqb.\n  intros H3. apply Heqb. exists x; split; try assumption.\n  apply EdgesBidirectional. auto. apply IHX; try auto.\n  inversion H. destruct inEdgeDec. inversion H3.\n  destruct vertexConnected. inversion H3.\n  reflexivity. intros. induction X. auto.\n  simpl independent. destruct inEdgeDec.\n  apply False_rec. specialize (H a a).\n  apply H; try (left; auto). assumption.\n  remember (vertexConnected a X).\n  destruct b. symmetry in Heqb.\n  apply vertexConnected_spec in Heqb.\n  destruct Heqb as [v' [H0 H1]].\n  apply False_rec. apply H with (x :=  a) (y := v');\n  auto. left. auto. right. auto.\n  apply IHX. intros. symmetry in Heqb.\n  apply H; right; auto.\nQed.\n\nTheorem Independent_dec : forall X, {Independent X} + {~ Independent X}.\nProof.\n  intros X. remember (independent X).\n  destruct b; [left | right]. apply independent_spec.\n  auto. intros H. apply independent_spec in H.\n  rewrite <- Heqb in H. inversion H.\nDefined.\n\nTheorem IndSetDec : forall X : list nat, {IndSet X} + {~IndSet X}.\n  intros. destruct (ValidSet_dec X);\n  [destruct (Independent_dec X) | right].\n  left; constructor; auto.\n  right. intros H. inversion H. auto.\n  intros H. inversion H. auto.\nDefined.\n\nTheorem MaximalBound :\nforall (x : nat) (X : list nat),\n  x >= V -> ~ MaximalIndSet (x::X).\nProof.\n  unfold not. intros.\n  inversion H0. subst.\n  inversion H1. subst.\n  assert (In x (x::X)).\n  left. auto. apply H3 in H5.\n  omega.\nQed.\n\nFixpoint StepMaximalIndSet (X : list nat) (n : nat) :=\n  match n with\n  | O => if (IndSetDec (n::X)) then (n::X) else X\n  | S m => if IndSetDec (n::(StepMaximalIndSet X m))\n             then (n::(StepMaximalIndSet X m))\n             else StepMaximalIndSet X m\n  end.\n\nDefinition MkMaximalIndSet (S : list nat) : list nat :=\n  StepMaximalIndSet S (pred V). \n\nTheorem StepMaximalIndSet_spec : forall (n : nat) (X : list nat), IndSet X -> IndSet (StepMaximalIndSet X n).\nProof.\n  intros.\n  induction n.\n  unfold StepMaximalIndSet.\n  case IndSetDec; intuition.\n  simpl.\n  case IndSetDec;\n  intuition.\nQed.\n\nTheorem ConnectedApp :\n  forall (X X' : list nat) (n : nat), vertexConnected n X = true -> vertexConnected n (X'++ X) = true.\nProof.\n  intros.\n  apply vertexConnected_spec in H.\n  apply vertexConnected_spec.\n  destruct H.\n  destruct H.\n  exists x.\n  intuition.\nQed.\n\nTheorem TrivialIndSet : V = 0 -> forall X, MaximalIndSet X -> X = nil.\nProof.\n  intros. inversion H0. inversion H1.\n  destruct X. auto.\n  assert (In n (n::X)) as H5.\n  left. auto. apply H3 in H5.\n  omega.\nQed.\n\nTheorem nilIndSet : IndSet nil.\nProof.\n  constructor. unfold ValidSet. intros x H0.\n  inversion H0. unfold Independent. intros.\n  inversion H.\nQed.\n\nTheorem IndCons : forall (x : nat) (X : list nat), Independent (x::X) -> Independent X.\nProof.\n  intros. unfold Independent in *.\n  intros. apply H; right; auto.\nQed.\n\nTheorem IndSetCons :\n  forall (x : nat) (X : list nat), IndSet (x::X) -> IndSet X.\nProof.\n  intros. inversion H.\n  constructor. intros y H2.\n  apply H0. right. auto.\n  apply IndCons in H1. auto.\nQed.\n\nTheorem IndSetApp :\n  forall (x : nat) (X X': list nat),\n    IndSet X ->\n    ~ IndSet (x::X) -> ~ IndSet (x::(X' ++ X)).\nProof.\n  intros. intros H1. apply H0.\n  constructor. intros y H2. inversion H1.\n  apply H3. destruct H2 as [H2 | H2].\n  left. auto. right. apply in_or_app.\n  auto. unfold Independent.\n  intros y z H2 H3. inversion H1.\n  apply H5. destruct H2. left. auto.\n  right. apply in_or_app. right. auto.\n  destruct H3. left. auto.\n  right. apply in_or_app. right. auto.\nQed.\n  \nTheorem MkMaximalIndSet_spec1 : forall X, IndSet X -> IndSet(MkMaximalIndSet X).\nProof.\n  intros. induction X. simpl.\n  unfold MkMaximalIndSet. destruct V.\n  simpl. case IndSetDec;\n  intuition. apply StepMaximalIndSet_spec.\n  assumption. unfold MkMaximalIndSet in *.\n  destruct V. simpl.\n  case IndSetDec;\n  intuition.\n  apply StepMaximalIndSet_spec.\n  intuition.\nQed.\n\nTheorem StepMaximalIndSet_decons :\n  forall (n : nat)(X : list nat),\n    IndSet X -> exists (X' : list nat), StepMaximalIndSet X n = X' ++ X.\nProof.\n  intros.\n  induction n.\n  unfold StepMaximalIndSet.\n  destruct IndSetDec.\n  exists (cons 0 nil).\n  intuition.\n  exists nil.\n  intuition.\n  simpl StepMaximalIndSet.\n  destruct IHn.\n  destruct IndSetDec.\n  replace (StepMaximalIndSet X n).\n  exists (S n :: x).\n  intuition.\n  replace (StepMaximalIndSet X n).\n  exists x.\n  intuition.\nQed.\n\nTheorem MkMIS_to_StepMIS :\n  forall X, exists n, MkMaximalIndSet X = StepMaximalIndSet X n.\nProof.\n  intros. \n  remember V.\n  induction n;\n  unfold MkMaximalIndSet;\n  replace V;\n  [exists 0 | exists n];\n  induction X;\n  intuition.\nQed.\n\nTheorem MkMaximalIndSet_deapp :\n  forall X, IndSet X -> exists X', MkMaximalIndSet X = X'++X.\nProof.\n  intros.\n  assert (exists n : nat, MkMaximalIndSet X = StepMaximalIndSet X n).\n  apply MkMIS_to_StepMIS.\n  destruct H0.\n  replace (MkMaximalIndSet X).\n  apply (StepMaximalIndSet_decons).\n  intuition.\nQed.\n\nTheorem IndSet_destr :\n  forall (X : list nat) (m : nat), IndSet X -> m < V -> ~ IndSet (m::X) -> vertexConnected m X = true.\nProof.\n  intros.\n  induction X.\n  assert (IndSet (m::nil)).\n  constructor.\n  unfold ValidSet.\n  simpl In.\n  intros. destruct H2;\n  intuition. unfold Independent.\n  intros.\n  destruct H2, H3; auto.\n  repeat subst. apply NoSelfEdges.\n  auto.\n  simpl vertexConnected.\n  destruct inEdgeDec. auto.\n  apply IHX. apply IndSetCons in H.\n  auto. intros H2. apply H1.\n  constructor. inversion H2.\n  intros y H5. destruct H5 as [H5 | [H5| H5]];\n  subst. apply H2. left. auto. apply H. left. auto.\n  apply H3. right. auto. intros y z H3 H4.\n  destruct H3 as [H3 | H3];\n  destruct H4 as [H4 | H4]; repeat subst.\n  apply NoSelfEdges. destruct H4 as [H4 | H4].\n  subst. auto. apply H2. left. auto.\n  right. auto. destruct H3 as [H3 | H3].\n  subst. intros n'. apply n.\n  apply EdgesBidirectional. auto.\n  apply H2. right. auto. left. auto.\n  apply H; auto.\nQed.\n\n(*show that for everything less than n, this has to either contain that value or there's an edge between the constructed set. *)\nTheorem IndSetConstraint :\n  forall (X : list nat) (m : nat),\n    IndSet X ->\n    m < V ->\n    ~ In m (StepMaximalIndSet X m) ->\n      vertexConnected m (StepMaximalIndSet X m) = true.\nProof.\n  intros.\n  induction m.\n  simpl StepMaximalIndSet in *.\n  destruct IndSetDec.\n  assert False.\n  apply H1.\n  intuition.\n  intuition.\n  apply IndSet_destr;\n  intuition.\n  simpl StepMaximalIndSet in *.\n  destruct IndSetDec.\n  assert False.\n  apply H1.\n  intuition.\n  intuition.\n  apply IndSet_destr.\n  apply StepMaximalIndSet_spec.\n  intuition.\n  intuition.\n  exact n.\nQed.\n\nTheorem StepMaximalIndSet_decomp : \n  forall (X : list nat) (n m: nat),\n    m <= n -> exists (X' : list nat), (StepMaximalIndSet X n) = X'++(StepMaximalIndSet X m) /\\\n                                      forall y : nat, In y X' -> y > m.\nProof.\n  intros.\n  induction n.\n  assert (m = 0).\n  omega.\n  replace m.\n  exists nil.\n  intuition. inversion H1.\n  assert (m <= n \\/ m = S n).\n  omega.\n  destruct H0.\n  assert (m <= n) as i.\n  intuition.\n  apply IHn in H0.\n  destruct H0.\n  destruct H0.\n  simpl StepMaximalIndSet.\n  destruct IndSetDec.\n  exists (S n :: x).\n  replace (StepMaximalIndSet X n).\n  intuition.\n  simpl In in H3.\n  destruct H3.\n  omega.\n  intuition.\n  exists x.\n  intuition.\n  replace m.\n  exists nil.\n  intuition. inversion H1.\nQed.\n\nTheorem IndSetConstraint_gen :\n  forall (X : list nat ) (n m : nat),\n    IndSet X ->\n    n < V ->\n    m <= n ->\n    ~ In m (StepMaximalIndSet X n) ->\n      vertexConnected m (StepMaximalIndSet X n) = true.\nProof.\n  intros.\n  assert (exists (X' : list nat),\n            (StepMaximalIndSet X n) = X'++(StepMaximalIndSet X m) /\\\n            forall y : nat, In y X' -> y > m).\n  apply StepMaximalIndSet_decomp; intuition.\n  destruct H3.\n  destruct H3.\n  replace (StepMaximalIndSet X n) in *.\n  apply ConnectedApp.\n  assert (~ In m (StepMaximalIndSet X m)).\n  unfold not.\n  intros.\n  apply H2.\n  apply in_or_app.\n  intuition.\n  induction m.\n  simpl StepMaximalIndSet in *.\n  destruct IndSetDec.\n  intuition.\n  apply IndSet_destr;\n  intuition.\n  simpl StepMaximalIndSet in *.\n  destruct IndSetDec.\n  intuition.\n  apply IndSet_destr; intuition.\n  apply StepMaximalIndSet_spec.\n  intuition.\nQed.\n\nTheorem MkMaximalIndSet_red : forall (X : list nat) (n : nat), V = S n -> MkMaximalIndSet X = StepMaximalIndSet X n.\nProof.\n  intros.\n  unfold MkMaximalIndSet;\n  intros.\n  replace V;\n  induction X; intuition.\nQed.\n\n (*Find a limit on expanding the S' in the proof below *)\nTheorem MkMaximalIndSet_spec2 : forall X, IndSet X -> MaximalIndSet (MkMaximalIndSet X).\nProof.\n  intros. apply MaximalIndSet_eq. constructor.\n  apply MkMaximalIndSet_spec1. auto.\n  intros. assert (x < V \\/ x >= V).\n  omega.\n  destruct H1.\n  assert ( {m : nat | S m = V} + {0 = V}).\n  apply O_or_S.\n  destruct H2.\n  destruct s. \n  assert ( MkMaximalIndSet X = StepMaximalIndSet X x0).\n  apply MkMaximalIndSet_red. auto. rewrite -> H2 in H0.\n  assert (vertexConnected x (StepMaximalIndSet X x0) = true).\n  apply IndSetConstraint_gen;\n  auto; omega.\n  apply vertexConnected_spec in H3.\n  intros H4. destruct H3 as [v' [H3 H3']].\n  apply H4 in H3'; auto. left. auto.\n  rewrite -> H2. right. auto.\n  unfold MkMaximalIndSet in H0.\n  rewrite <- e in H0. simpl in H0.\n  destruct IndSetDec. inversion i.\n  unfold ValidSet in H2. assert (In 0 (0::X)) as H4.\n  left. auto. apply H2 in H4. omega. \n  omega. intros H2. inversion H2.\n  assert (In x (x::(MkMaximalIndSet X))).\n  left. auto. apply H3 in H5. omega.\nQed.\n\nTheorem MIS_nil_iff_0 : MaximalIndSet nil <-> V = 0.\nProof.\n  rewrite -> MaximalIndSet_eq. split.\n  (* -> *)\n  intros H0.\n  assert ( {V <= 0} + {0 < V} ) as H1. apply le_lt_dec.\n  destruct H1 as [H1 | H1].\n    (* V <= 0 *)\n    omega.\n    (* 0 < v *)\n    inversion H0.\n    apply False_rec.\n    specialize (H2 0).\n    apply H2. intros H3. inversion H3.\n    constructor. intros x H3. inversion H3.\n    omega. inversion H4.\n    intros x y H3 H4. destruct H3;\n    destruct H4; repeat subst.\n    apply NoSelfEdges. inversion H4.\n    inversion H3. inversion H3.\n  intros. constructor. apply nilIndSet.\n  intros x H0 H1. inversion H1.\n  specialize (H2 x). assert (In x (x::nil)) as H4.\n  left. auto. apply H2 in H4. omega.\nQed.\n\nTheorem IndSet_cons : forall (l : list nat) (x : nat), ~IndSet l -> ~ IndSet (x::l).\nProof.\n  intros l x H0 H1.\n  apply H0. apply IndSetCons in H1.\n  auto.\nQed. \n\nTheorem IndSet_lift_spec : forall (l : list nat) (x : nat),\n  MaximalIndSet l -> x < V -> IndSet (x::l) -> In x l.\nProof.\n  intros. rewrite -> MaximalIndSet_eq in H. destruct H as [[H2 H3] H4].\n  assert ( {In x l}+{~In x l} ) as H5 by (apply in_dec; apply (eq_nat_dec)).\n  destruct H5 as [H5 | H5]. assumption.\n  apply False_rec. apply H4 in H5. contradiction.\nQed.\n\n\nTheorem IndSet_order : forall X Y : list nat, IndSet (X++Y) -> IndSet (Y ++ X).\nProof.\n  intros X Y H0. inversion H0. constructor.\n  unfold ValidSet. intros x H2. apply H0.\n  apply in_or_app. apply in_app_or in H2.\n  destruct H2 as [H2 | H2]; [right | left]; auto.\n  intros x y H2 H3. apply H1;\n  apply in_or_app; apply in_app_or in H2;\n  apply in_app_or in H3; destruct H2 as [H2 | H2];\n  destruct H3 as [H3 | H3]; auto.\nQed.\n    \nTheorem VertexConnected_order :\n  forall (x : nat) (X Y : list nat),\n    vertexConnected x (X++Y) = vertexConnected x (Y++X).\n  intros x X Y.\n    assert ({vertexConnected x (X++Y) = true} + {vertexConnected x (X++Y) = false}).\n      destruct (vertexConnected x (X++Y)); intuition.  \n    assert ({vertexConnected x (Y++X) = true} + {vertexConnected x (Y++X) = false}).\n      destruct (vertexConnected x (Y++X)); intuition.\n    destruct H; destruct H0.\n      rewrite -> e. intuition.\n      apply vertexConnected_spec in e.\n        apply vertexConnected_spec_neg in e0.\n        assert False as F. apply e0. destruct e as [e [H0 H1]].\n        exists e. split.\n          apply in_app_or in H0. apply in_or_app. intuition.\n          apply H1.\n        inversion F.\n      apply vertexConnected_spec in e0.\n        apply vertexConnected_spec_neg in e.\n        assert False as F. apply e. destruct e0 as [e0 [H0 H1]].\n        exists e0. split.\n          apply in_app_or in H0. apply in_or_app. intuition.\n          apply H1.\n        inversion F.\n      rewrite -> e. intuition.\nQed.\n    \nTheorem MaximalIndSet_order : forall ( X Y : list nat), MaximalIndSet (X ++ Y) -> MaximalIndSet (Y ++ X).\nProof. \n  intros X Y H0. rewrite -> MaximalIndSet_eq in *. inversion H0. constructor. apply IndSet_order. auto.\n  intros x H2 H3. assert (~ In x (X++Y)) as H4.\n  intros H4. apply H2. apply in_app_or in H4.\n  apply in_or_app. destruct H4 as [H4 | H4]; auto.\n  apply H1 in H4. apply H4.\n  constructor. intros. intros y H5.\n  destruct H5 as [H5 | H5]. apply H3.\n  left. auto. apply H0. auto.\n  intros y z H5 H6. apply H3.\n  destruct H5 as [H5 | H5].\n  left. auto. right. apply in_app_or in H5.\n  destruct H5 as [H5 | H5];\n  apply in_or_app; auto.\n  destruct H6 as [H6 | H6].\n  left. auto. right. apply in_app_or in H6.\n  destruct H6 as [H6 | H6];\n  apply in_or_app; auto.\nQed.\n\nTheorem neg_incl_witness : forall X Y : list nat, ~ incl Y X -> exists n : nat, In n Y /\\ ~ In n X.\nProof.\n  intros. induction Y.\n    assert (incl nil X). unfold incl. intros a H0. inversion H0. apply H in H0. destruct H0.\n    unfold incl in H.\n    assert ({In a X} + {~In a X}).\n      apply in_dec. apply eq_nat_dec.\n    destruct H0 as [H0 | H0].\n    assert (~ incl Y X).\n      intros H1.\n      unfold incl in H1.\n      assert (forall a0 : nat, In a0 (a :: Y) -> In a0 X).\n        intros a0 H2. specialize (H1 a0). simpl In in H2. destruct H2 as [H2 | H2].\n          rewrite <- H2. apply H0.\n          apply H1 in H2. apply H2.\n      apply H in H2.\n      apply H2.\n    apply IHY in H1.\n    destruct H1 as [n0 [H1 H2]].\n    exists n0.\n    split.\n      simpl. right. apply H1.\n      apply H2.\n    exists a. split.\n      simpl. left. reflexivity.\n      apply H0.\nQed. \n\n\nTheorem MaximalIndSet_subs : forall X Y : list nat, incl X Y -> MaximalIndSet X -> MaximalIndSet Y -> list_eq X Y.\nProof.\n  intros X Y H0 H1 H2. rewrite -> MaximalIndSet_eq in *.\n  unfold incl in H0. unfold list_eq. intros x. split; intros H3.\n  (* -> *)\n  apply H0 in H3. apply H3.\n  (* <- *)\n  assert ({In x X} + {~ In x X}) as H4. apply in_dec. apply eq_nat_dec.\n  destruct H4 as [H4| H4]. apply H4.\n  (*We're now in a contradictory state *)\n  assert (False).\n  assert (~IndSet (x::X)) as H5. destruct H1 as [H1 H5]. apply H5. apply H4.\n  apply H5. constructor. intros y H6.\n  destruct H6 as [H6 | H6]. apply H2.\n  subst. auto. apply H1. auto.\n  intros y z H6 H7. apply H2.\n  destruct H6 as [H6 | H6].\n  subst. auto. auto. destruct H7 as [H7 | H7].\n  subst. auto. apply H0. auto. inversion H.\nQed.\n\n\nTheorem StepMaximalIndSet_in : forall n x X, In x (StepMaximalIndSet X n) -> In x X \\/ x <= n.\nProof.\n  intros n. induction n; intros x X H0.\n  (* n = 0 *)\n  simpl in H0. destruct IndSetDec in H0.\n    (* IndSet *)\n      simpl In in H0. intuition. left. intuition.\n    (* ~ INdSet *)\n      simpl in H0. destruct IndSetDec. simpl In in H0. intuition. apply IHn in H. intuition omega.  \n  (* n = S n' *)\n  apply IHn in H0. intuition omega.\nQed.  \n\nLemma MkMaximalIndSet_spec3_help : forall X Y : list nat,\n  IndSet X -> MaximalIndSet Y -> incl X Y -> \n    forall x : nat, delta_min (MkMaximalIndSet X) Y = Some x ->\n    forall y : nat, delta_min Y (MkMaximalIndSet X) = Some y ->\n      x < y.\nProof.\n  intros X Y H0 H1 H2 x H3 y H4.\n  assert (exists n : nat, n = V) as H5. exists V. reflexivity.\n  destruct H5 as [n H5].\n  destruct n.\n  (*V = 0*)\n    assert (MkMaximalIndSet X = nil).\n      assert (MaximalIndSet (MkMaximalIndSet X)). apply MkMaximalIndSet_spec2. apply H0.\n      destruct (MkMaximalIndSet X).\n        reflexivity. inversion H.\n        inversion H. assert (In n (n::l)).\n        left. auto. apply H6 in H10. omega.\n        rewrite -> H in H3. rewrite -> delta_min_r_nil in H3. inversion H3.\n  (* V = S n *)\n    assert (MaximalIndSet (MkMaximalIndSet X)) as H6. apply MkMaximalIndSet_spec2.\n    apply H0.\n    assert (MkMaximalIndSet X = StepMaximalIndSet X n) as H7.\n    apply MkMaximalIndSet_red. rewrite -> H5. reflexivity.\n    assert ( y < V ) as H8.\n      destruct H1 as [[H0' H1'] H2']. apply H0'. apply (delta_min_in y Y (MkMaximalIndSet X) H4).\n    assert ( ~ In y (MkMaximalIndSet X)) as H9.\n      apply ((delta_min_neg_in y Y (MkMaximalIndSet X) )H4).        \n    assert (y <= n) as H10. omega.\n    assert (exists X' : list nat, StepMaximalIndSet X n = X' ++ (StepMaximalIndSet X y) /\\\n                                  forall z : nat, In z X' -> z > y) as H11.\n      apply StepMaximalIndSet_decomp. apply H10.\n      destruct H11 as [X' [H11 H12]].\n    assert (vertexConnected y (StepMaximalIndSet X y) = true) as H13. apply IndSetConstraint_gen.\n      apply H0. apply H8. omega. rewrite -> H7 in H9. rewrite -> H11 in H9. intros H13. apply H9. apply in_or_app. right. apply H13.\n    apply vertexConnected_spec in H13. destruct H13 as [z [H13 H14]].\n    assert (In z (StepMaximalIndSet X n)) as H15. rewrite -> H11. apply in_or_app. right. apply H13.\n    assert (z < y) as H16. assert (z <= y) as H0'.\n      apply StepMaximalIndSet_in in H13. destruct H13 as [H13 | H13].\n        (* Left *)\n          assert (In z Y) as H1'. apply H2. apply H13.\n          inversion H1. inversion H. apply False_rec.\n          apply (H18 y z). apply (delta_min_in _ _ _ H4).\n          apply H1'. apply H14. auto. \n        (* Right *)\n      assert (z <> y) as H16. intros H1'. rewrite H1' in H14. apply NoSelfEdges in H14. apply H14. omega.\n      assert (delta_min (MkMaximalIndSet X) Y = None \\/\n             (exists p : nat,\n               delta_min (MkMaximalIndSet X) Y = Some p /\\\n               In p (MkMaximalIndSet X) /\\\n               ~ In p Y /\\\n               (forall q : nat, In q (MkMaximalIndSet X) -> ~ In q Y -> p <= q))) as H17.\n     apply delta_min_dec.\n     destruct H17 as [H17 | H17]. rewrite -> H3 in H17. inversion H17.\n     destruct H17 as [p [H0' [H1' [H2' H3']]]].\n     assert (p = x) as H17. rewrite H3 in H0'. inversion H0'. reflexivity.\n     assert (x <= z) as H18.\n       rewrite <- H17. apply H3'. rewrite -> H7. apply H15.\n       inversion H1. inversion H.\n       specialize (H20 y z). intros H21. apply H20.\n         apply (delta_min_in _ _ _ H4). auto. auto. omega.\nQed.    \n\nTheorem MkMaximalIndSet_spec3 : forall X Y : list nat,\n  IndSet X -> MaximalIndSet Y -> incl X Y ->\n    dec_order (MkMaximalIndSet X) Y = lt_list \\/ dec_order (MkMaximalIndSet X) Y = eq_list.\nProof.\n  intros X Y H0 H1 H2. rewrite -> MaximalIndSet_eq in H1.\n  assert ( {dec_order (MkMaximalIndSet X) Y = lt_list} +\n           {dec_order (MkMaximalIndSet X) Y = eq_list} +\n           {dec_order (MkMaximalIndSet X) Y = gt_list}) as H5.\n  apply dec_order_dec.\n  destruct H5 as [[H5 | H5] | H5].\n  (* Let's eliminate the trivial cases *)\n    intuition. intuition. (*add in an ability to reorder/rename nodes? *)\n  (* Now we're in the contradictory cases -> @H5 *)\n  (* Let's set up some basic facts about the lists here *)\n  assert (dec_order Y (MkMaximalIndSet X) = lt_list) as H6.\n    apply dec_order_dual_spec. apply H5.\n  assert (MaximalIndSet (MkMaximalIndSet X)) as H12.\n    apply MkMaximalIndSet_spec2. apply H0.\n  (* Let's introduce some facts about dec_order *)\n  assert ( delta_min (MkMaximalIndSet X) Y = None \\/ (exists x : nat,\n    delta_min (MkMaximalIndSet X) Y = Some x /\\\n    In x (MkMaximalIndSet X) /\\ ~ In x Y /\\ (forall y : nat, In y (MkMaximalIndSet X) -> ~ In y Y -> x <= y))) as H7.\n    apply delta_min_dec.\n  assert ( delta_min Y (MkMaximalIndSet X) = None \\/ (exists x : nat,\n    delta_min Y (MkMaximalIndSet X) = Some x /\\\n    In x Y /\\ ~ In x (MkMaximalIndSet X) /\\ (forall y : nat, In y Y -> ~ In y (MkMaximalIndSet X) -> x <= y))) as H8.\n    apply delta_min_dec.\n  destruct H7 as [H7 | H7]; destruct H8 as [H8 | H8].\n  (* delta_mins : None None *)\n    right. unfold dec_order. destruct (MkMaximalIndSet X);\n    rewrite -> H7; rewrite -> H8; reflexivity.\n  (* delta_mins : None Some *)\n    destruct H8 as [x [H8 [H9 [H10 H11]]]].\n    assert (forall a : nat, In a (MkMaximalIndSet X) -> In a Y) as H13.\n      apply delta_min_subs. apply H7.\n    assert (~ IndSet(x::(MkMaximalIndSet X))) as H14.\n       destruct H12 as [H12 H14]. intros H15.\n      apply H14 in H15. contradiction.\n    assert ({ValidSet (x::(MkMaximalIndSet X))} + {~ ValidSet (x::(MkMaximalIndSet X))}) as H15.\n      apply ValidSet_dec. \n    assert ( {independent (x :: MkMaximalIndSet X) = true} + {independent (x :: MkMaximalIndSet X) = false} ) as H16.\n      intuition.\n    destruct H15 as [H15 | H15]; destruct H16 as [H16 | H16]; assert False.\n      apply H14. constructor. intuition. apply independent_spec. auto. inversion H.\n      apply H14. constructor. apply H15. unfold Independent. intros a b  H0' H1'.\n        destruct H1 as [H1 H17].\n        destruct H1 as [H1 H18]. assert (forall x y : nat, In x Y -> In y Y -> ~ In (x, y) E) as H2'.\n        apply H18. specialize (H2' a b). apply H2'.\n          simpl in H0'. destruct H0' as [H0' | H0']. rewrite -> H0' in H9. apply H9. apply H13. apply H0'.\n          simpl in H1'. destruct H1' as [H1' | H1']. rewrite -> H1' in H9. apply H9. apply H13. apply H1'.\n        inversion H.\n      apply H15. unfold ValidSet. intros a H0'. simpl In in H0'. destruct H0' as [H0' | H0'].\n        destruct H1 as [H1 H1']. destruct H1 as [H1 H2'].\n        unfold ValidSet in H1. apply H1. rewrite -> H0' in H9. apply H9. \n        destruct H12 as [H12 H1']. destruct H12 as [H12 H2']. apply H12. apply H0'. inversion H.\n      apply H15. unfold ValidSet. intros a H0'. simpl In in H0'. destruct H0' as [H0' | H0'].\n         destruct H1 as [H1 H1']. destruct H1 as [H1 H2'].\n        unfold ValidSet in H1. apply H1. rewrite -> H0' in H9. apply H9. \n        destruct H12 as [H12 H1'].\n        unfold ValidSet in H12. destruct H12 as [H12 H2']. apply H12. apply H0'. inversion H.\n  (* delta_mins : Some None *)\n    destruct H7 as [x [H7 [H9 [H10 H11]]]]. left.\n    unfold dec_order. destruct (MkMaximalIndSet X);\n    rewrite -> H7; rewrite -> H8; reflexivity.\n  (* Some Some *)\n    destruct H7 as [x [H7 [H9 [H10 H11]]]].\n    destruct H8 as [y [H8 [H13 [H14 H15]]]].    \n    assert (y < x) as H0'.\n      unfold dec_order in H6; destruct Y; rewrite -> H7 in H6; rewrite -> H8 in H6;\n      destruct lt_dec; try (apply l); try inversion H6.\n    assert (x < y) as H1'.\n    apply (MkMaximalIndSet_spec3_help X Y).\n      apply H0. rewrite -> MaximalIndSet_eq. apply H1. apply H2. \n      destruct H12 as [H0'' H1'']. apply H7. apply H8.\n    omega.\nQed.\n\n\nTheorem independent_dec : forall X : list nat, {independent X = true} + {independent X = false}.\nProof. intuition. Qed.\n\nTheorem IndSet_dec : forall (X : list nat), {IndSet X} + {~ IndSet X}.\nProof.\n  intros X.\n    assert ({ValidSet X} + {~ValidSet X}) as H0. apply ValidSet_dec.\n    assert ({Independent X} + {~Independent X }) as H1. apply Independent_dec.\n    destruct H0 as [H0 | H0]; destruct H1 as [H1 | H1]; [left | right | right | right]; intuition.\n    constructor; auto. inversion H. auto. inversion H. auto. inversion H. auto.\nQed.\n\nTheorem Independent_spec_neg :\n  forall F : list nat,\n    independent F = false <-> (exists x y, In x F /\\ In y F /\\ In (x, y) E).\nProof.\n  split; intros; induction F. inversion H.\n  {\n    simpl in H. destruct inEdgeDec.\n    apply NoSelfEdges in i. inversion i. remember (vertexConnected a F) as b.\n    destruct b. symmetry in Heqb. apply vertexConnected_spec in Heqb.\n    destruct Heqb as [v' [H0 H1]]. exists a. exists v'. repeat split.\n    left. reflexivity. right. assumption. assumption. apply IHF in H.\n    destruct H as [v [v' [H0 [H1 H2]]]]. exists v. exists v'. repeat split;\n    try right; assumption. \n  }\n  destruct H as [x [y [H0 H1]]]. inversion H0.\n  {\n    destruct H as [x [y [H0 [H1 H2]]]].\n    destruct H0 as [H0 | H0]; destruct H1 as [H1 | H1]; repeat subst.\n    apply NoSelfEdges in H2. inversion H2. simpl.\n    destruct inEdgeDec. reflexivity. remember (vertexConnected x F) as b.\n    destruct b. reflexivity. symmetry in Heqb.\n    apply vertexConnected_spec_neg in Heqb. apply False_rec.\n    apply Heqb. exists y. split; assumption. simpl.\n    destruct inEdgeDec. reflexivity. remember (vertexConnected y F) as b.\n    destruct b. reflexivity. symmetry in Heqb.\n    apply vertexConnected_spec_neg in Heqb. apply False_rec.\n    apply Heqb. apply EdgesBidirectional in H2. exists x. split; assumption.\n    simpl. destruct inEdgeDec. reflexivity. destruct vertexConnected.\n    reflexivity. apply IHF. exists x. exists y.\n    repeat split; try assumption.\n  }\nQed.\n\nTheorem eq_preserves_MIS : forall X Y: list nat, list_eq X Y -> MaximalIndSet X -> MaximalIndSet Y.\nProof.\n  intros X Y H0 H1. rewrite -> MaximalIndSet_eq in *.\n  unfold list_eq in H0. inversion H1. constructor. constructor.\n  intros z H3. apply H1. apply H0. auto. intros a b H3 H4.  apply H1.\n  apply H0. auto. apply H0. auto. intros x H3 H4.\n  apply (H2 x). intros H5. apply H3. apply H0. auto.\n  constructor. intros y H5. apply H4.  inversion H5.\n  left. auto. right. apply H0. auto. intros y z H5 H6.\n  apply H4. inversion H5. left. auto. right. apply H0.\n  auto. inversion H6. left. auto. right. apply H0. auto.\nQed.\n\nTheorem MIS_MKMIS : forall X : list nat, IndSet X -> (list_eq X (MkMaximalIndSet X) -> MaximalIndSet X).\nProof.\n  intros X H0 H2.\n  eapply eq_preserves_MIS.\n    { apply list_eq_symmetric in H2. apply H2. }\n    { apply MkMaximalIndSet_spec2. apply H0. }\nQed.\n\nEnd IS.\n", "meta": {"author": "merten-samuel", "repo": "allMIS", "sha": "46b9d52b0eeabc1b6372a50dce65dae85b67198f", "save_path": "github-repos/coq/merten-samuel-allMIS", "path": "github-repos/coq/merten-samuel-allMIS/allMIS-46b9d52b0eeabc1b6372a50dce65dae85b67198f/graphs_nondep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7066656388482683}}
{"text": "From Ordinal Require Import sflib Basics.\nFrom Ordinal Require Export Ordinal.\n\nRequire Import Coq.Classes.RelationClasses Coq.Classes.Morphisms. (* TODO: Use Morphisms *)\n\nSet Implicit Arguments.\nSet Primitive Projections.\n\nModule OrdArith.\n  Section ARITHMETIC.\n    Let flip A B C (f: A -> B -> C): B -> A -> C := fun b a => f a b.\n\n    Section ADD.\n      Definition add (o0: Ord.t): forall (o1: Ord.t), Ord.t := Ord.orec o0 Ord.S.\n\n      Let _S_le o: Ord.le o (Ord.S o).\n      Proof.\n        eapply Ord.S_le.\n      Qed.\n\n      Let _le_S o0 o1 (LE: Ord.le o0 o1): Ord.le (Ord.S o0) (Ord.S o1).\n      Proof.\n        apply Ord.le_S. auto.\n      Qed.\n\n      Lemma add_base_l o0 o1: Ord.le o0 (add o0 o1).\n      Proof.\n        eapply Ord.orec_le_base; auto.\n      Qed.\n\n      Lemma add_base_r o0 o1: Ord.le o1 (add o0 o1).\n      Proof.\n        transitivity (Ord.orec Ord.O Ord.S o1).\n        { eapply Ord.orec_of_S. }\n        { eapply Ord.orec_mon; auto. eapply Ord.O_bot. }\n      Qed.\n\n      Lemma add_O_r o: Ord.eq (add o Ord.O) o.\n      Proof.\n        eapply (@Ord.orec_O o Ord.S); auto.\n      Qed.\n\n      Lemma add_S o0 o1: Ord.eq (add o0 (Ord.S o1)) (Ord.S (add o0 o1)).\n      Proof.\n        eapply (@Ord.orec_S o0 Ord.S); auto.\n      Qed.\n\n      Lemma add_join o A (os: A -> Ord.t):\n        Ord.eq (add o (Ord.join os)) (Ord.union o (Ord.join (fun a => add o (os a)))).\n      Proof.\n        eapply (@Ord.orec_join o Ord.S); eauto.\n      Qed.\n\n      Lemma add_join_inhabited o A (os: A -> Ord.t)\n            (INHABITED: inhabited A):\n        Ord.eq (add o (Ord.join os)) (Ord.join (fun a => add o (os a))).\n      Proof.\n        eapply (@Ord.orec_join_inhabited o Ord.S); eauto.\n      Qed.\n\n      Lemma add_build o A (os: A -> Ord.t)\n        :\n          Ord.eq (add o (Ord.build os)) (Ord.union o (Ord.join (fun a => Ord.S (add o (os a))))).\n      Proof.\n        eapply Ord.orec_build.\n      Qed.\n\n      Lemma add_union o0 o1 o2\n        :\n          Ord.eq (add o0 (Ord.union o1 o2)) (Ord.union (add o0 o1) (add o0 o2)).\n      Proof.\n        eapply Ord.orec_union; auto.\n      Qed.\n\n      Lemma le_add_r o0 o1 o2 (LE: Ord.le o1 o2)\n        :\n          Ord.le (add o0 o1) (add o0 o2).\n      Proof.\n        eapply Ord.le_orec; auto.\n      Qed.\n\n      Lemma lt_add_r o0 o1 o2 (LT: Ord.lt o1 o2)\n        :\n          Ord.lt (add o0 o1) (add o0 o2).\n      Proof.\n        eapply Ord.S_supremum in LT.\n        eapply Ord.lt_le_lt.\n        2: { eapply le_add_r. eapply LT. }\n        eapply Ord.lt_eq_lt.\n        { eapply add_S. }\n        eapply Ord.S_lt.\n      Qed.\n\n      Lemma eq_add_r o0 o1 o2 (EQ: Ord.eq o1 o2)\n        :\n          Ord.eq (add o0 o1) (add o0 o2).\n      Proof.\n        split.\n        - eapply le_add_r; eauto. eapply EQ.\n        - eapply le_add_r; eauto. eapply EQ.\n      Qed.\n\n      Lemma le_add_l o0 o1 o2 (LE: Ord.le o0 o1)\n        :\n          Ord.le (add o0 o2) (add o1 o2).\n      Proof.\n        eapply (@Ord.orec_mon o0 Ord.S o1 Ord.S); auto.\n      Qed.\n\n      Lemma eq_add_l o0 o1 o2 (EQ: Ord.eq o0 o1)\n        :\n          Ord.eq (add o0 o2) (add o1 o2).\n      Proof.\n        split.\n        - eapply le_add_l; eauto. eapply EQ.\n        - eapply le_add_l; eauto. eapply EQ.\n      Qed.\n\n      Lemma add_O_l o: Ord.eq (add Ord.O o) o.\n      Proof.\n        induction o. etransitivity.\n        { eapply add_build. }\n        { split.\n          - eapply Ord.union_spec.\n            + eapply Ord.O_bot.\n            + eapply Ord.join_supremum. i. eapply Ord.S_supremum.\n              eapply Ord.eq_lt_lt.\n              * eapply H.\n              * eapply Ord.build_upperbound.\n          - eapply Ord.build_supremum. i.\n            eapply (@Ord.lt_le_lt (Ord.join (fun a0 => Ord.S (Ord.orec Ord.O Ord.S (os a0))))).\n            2: { eapply Ord.union_r. }\n            eapply Ord.eq_lt_lt.\n            { symmetry. eapply H. }\n            eapply Ord.lt_le_lt.\n            { eapply Ord.S_lt. }\n            { eapply (@Ord.join_upperbound _ (fun a0 => Ord.S (Ord.orec Ord.O Ord.S (os a0)))). }\n        }\n      Qed.\n\n      Lemma add_assoc o0 o1 o2: Ord.eq (add (add o0 o1) o2) (add o0 (add o1 o2)).\n      Proof.\n        revert o0 o1. induction o2. i. etransitivity.\n        { eapply add_build. } etransitivity.\n        2: {\n          eapply eq_add_r; auto.\n          { symmetry. eapply add_build. }\n        }\n        etransitivity.\n        2: { symmetry. eapply add_union; auto. }\n        split.\n        { eapply Ord.union_spec.\n          { eapply Ord.union_l. }\n          { eapply Ord.join_supremum. i. etransitivity.\n            { apply Ord.le_S. eapply H. }\n            etransitivity.\n            2: { eapply Ord.union_r. }\n            etransitivity.\n            2: {\n              eapply le_add_r.\n              eapply (@Ord.join_upperbound _ (fun a0 : A => Ord.S (add o1 (os a0))) a).\n            }\n            eapply add_S.\n          }\n        }\n        { eapply Ord.union_spec.\n          { eapply Ord.union_l. }\n          etransitivity.\n          { eapply add_join. }\n          eapply Ord.union_spec.\n          { etransitivity.\n            { eapply add_base_l. }\n            { eapply Ord.union_l. }\n          }\n          etransitivity.\n          2: { eapply Ord.union_r. }\n          eapply Ord.le_join. i. exists a0.\n          etransitivity.\n          { eapply add_S. }\n          { apply Ord.le_S. eapply H. }\n        }\n      Qed.\n\n      Lemma add_lt_l o0 o1 (LT: Ord.lt Ord.O o1): Ord.lt o0 (add o0 o1).\n      Proof.\n        eapply Ord.S_supremum in LT. eapply (@Ord.lt_le_lt (add o0 (Ord.S Ord.O))).\n        { eapply Ord.lt_eq_lt.\n          { eapply add_S. }\n          eapply Ord.lt_le_lt.\n          { eapply Ord.S_lt. }\n          eapply Ord.le_S. eapply add_base_l.\n        }\n        { eapply le_add_r. auto. }\n      Qed.\n    End ADD.\n\n    Section RECAPP.\n      Variable D: Type.\n      Variable next: D -> D.\n      Variable djoin: forall (A: Type) (ds: A -> D), D.\n\n      Variable dle: D -> D -> Prop.\n      Variable wf: D -> Prop.\n\n      Hypothesis dle_reflexive: forall d (WF: wf d), dle d d.\n      Hypothesis dle_transitive: forall d1 d0 d2 (WF0: wf d0) (WF1: wf d1) (WF2: wf d2) (LE0: dle d0 d1) (LE1: dle d1 d2),\n          dle d0 d2.\n\n      Hypothesis djoin_upperbound: forall A (ds: A -> D) (a: A) (WF: forall a, wf (ds a)), dle (ds a) (djoin ds).\n      Hypothesis djoin_supremum: forall A (ds: A -> D) (d: D) (WF: forall a, wf (ds a)) (WFD: wf d) (LE: forall a, dle (ds a) d), dle (djoin ds) d.\n      Hypothesis djoin_wf: forall A (ds: A -> D) (WF: forall a, wf (ds a)), wf (djoin ds).\n\n      Hypothesis next_wf: forall d (WF: wf d), wf (next d).\n\n      Hypothesis next_le: forall d (WF: wf d), dle d (next d).\n      Hypothesis next_mon: forall d0 d1 (WF0: wf d0) (WF1: wf d1) (LE: dle d0 d1), dle (next d0) (next d1).\n\n      Let deq: D -> D -> Prop :=\n        fun d0 d1 => dle d0 d1 /\\ dle d1 d0.\n\n      Let dunion (d0 d1: D): D := djoin (fun b: bool => if b then d0 else d1).\n\n      Let dunion_l d0 d1 (WF0: wf d0) (WF1: wf d1): dle d0 (dunion d0 d1).\n      Proof.\n        eapply (@djoin_upperbound _ (fun b: bool => if b then d0 else d1) true). i. destruct a; auto.\n      Qed.\n\n      Let dunion_r d0 d1 (WF0: wf d0) (WF1: wf d1): dle d1 (dunion d0 d1).\n      Proof.\n        eapply (@djoin_upperbound _ (fun b: bool => if b then d0 else d1) false). i. destruct a; auto.\n      Qed.\n\n      Let dunion_supremum d0 d1 u (WF0: wf d0) (WF1: wf d1) (WFU: wf u) (LE0: dle d0 u) (LE1: dle d1 u):\n        dle (dunion d0 d1) u.\n      Proof.\n        eapply djoin_supremum; auto.\n        { i. destruct a; auto. }\n        { i. destruct a; auto. }\n      Qed.\n\n      Let dunion_wf d0 d1 (WF0: wf d0) (WF1: wf d1): wf (dunion d0 d1).\n      Proof.\n        eapply djoin_wf. i. destruct a; auto.\n      Qed.\n\n      Let drec_wf base (WF: wf base) o: wf (Ord.rec base next djoin o).\n      Proof.\n        eapply (Ord.rec_wf base next djoin dle wf); auto.\n      Qed.\n\n      Let drec_rec_wf base (WF: wf base) o0 o1:\n        wf (Ord.rec (Ord.rec base next djoin o0) next djoin o1).\n      Proof.\n        eapply (Ord.rec_wf _ next djoin dle wf); auto.\n      Qed.\n\n      Let djoin_le A (ds0 ds1: A -> D)\n          (WF0: forall a, wf (ds0 a))\n          (WF1: forall a, wf (ds1 a))\n          (LE: forall a, dle (ds0 a) (ds1 a))\n        :\n          dle (djoin ds0) (djoin ds1).\n      Proof.\n        eapply djoin_supremum; auto.\n        i. eapply (@dle_transitive (ds1 a)); auto.\n      Qed.\n\n      Let djoin_eq A (ds0 ds1: A -> D)\n          (WF0: forall a, wf (ds0 a))\n          (WF1: forall a, wf (ds1 a))\n          (EQ: forall a, deq (ds0 a) (ds1 a))\n        :\n          deq (djoin ds0) (djoin ds1).\n      Proof.\n        split.\n        { eapply djoin_le; auto. i. eapply EQ. }\n        { eapply djoin_le; auto. i. eapply EQ. }\n      Qed.\n\n      Let dunion_le dl0 dl1 dr0 dr1\n          (WFL0: wf dl0) (WFL1: wf dl1) (WFR0: wf dr0) (WFR1: wf dr1)\n          (LEL: dle dl0 dl1) (LER: dle dr0 dr1):\n        dle (dunion dl0 dr0) (dunion dl1 dr1).\n      Proof.\n        eapply djoin_le.\n        { i. destruct a; auto. }\n        { i. destruct a; auto. }\n        { i. destruct a; auto. }\n      Qed.\n\n      Let next_eq d0 d1\n          (WF0: wf d0) (WF1: wf d1) (EQ: deq d0 d1)\n        :\n          deq (next d0) (next d1).\n      Proof.\n        split; eapply next_mon; auto; apply EQ.\n      Qed.\n\n      Let dunion_eq dl0 dl1 dr0 dr1\n          (WFL0: wf dl0) (WFL1: wf dl1) (WFR0: wf dr0) (WFR1: wf dr1)\n          (EQL: deq dl0 dl1) (EQR: deq dr0 dr1):\n        deq (dunion dl0 dr0) (dunion dl1 dr1).\n      Proof.\n        eapply djoin_eq; auto.\n        { i. destruct a; auto. }\n        { i. destruct a; auto. }\n        { i. destruct a; auto. }\n      Qed.\n\n      Let deq_transitive: forall d1 d0 d2 (WF0: wf d0) (WF1: wf d1) (WF2: wf d2) (LE0: deq d0 d1) (LE1: deq d1 d2),\n          deq d0 d2.\n      Proof.\n        i. inv LE0. inv LE1. split; eauto.\n      Qed.\n\n      Let drec_red base A (os: A -> Ord.t):\n        Ord.rec base next djoin (Ord.build os) =\n        dunion base (djoin (fun a => next (Ord.rec base next djoin (os a)))).\n      Proof.\n        eapply Ord.rec_red.\n      Qed.\n\n      Lemma rec_app base o0 o1 (WF: wf base):\n        deq (Ord.rec base next djoin (add o0 o1)) (Ord.rec (Ord.rec base next djoin o0) next djoin o1).\n      Proof.\n        Local Transparent Ord.rec Ord.union.\n        induction o1.\n\n        eapply (@deq_transitive (dunion (Ord.rec base next djoin o0) (dunion base (djoin (fun a => next (Ord.rec (Ord.rec base next djoin o0) next djoin (os a))))))); auto.\n        { eapply dunion_wf; auto. }\n        { eapply (@deq_transitive (Ord.rec base next djoin (Ord.union o0 (Ord.join (fun a : A => Ord.S (add o0 (os a))))))); auto.\n          { eapply dunion_wf; auto. }\n          { eapply (@Ord.eq_rec _ base next djoin dle wf); auto.\n            symmetry. eapply add_build. }\n          eapply (@deq_transitive (dunion (Ord.rec base next djoin o0) (Ord.rec base next djoin (Ord.join (fun a : A => Ord.S (add o0 (os a))))))); auto.\n          { eapply dunion_wf; auto. }\n          { eapply (Ord.rec_union base next djoin dle wf); auto. }\n          eapply dunion_eq; auto.\n          { split; apply dle_reflexive; auto. }\n          { eapply (@deq_transitive (dunion base (djoin (fun a : A => Ord.rec base next djoin ((fun a0 : A => Ord.S (add o0 (os a0))) a))))); auto.\n            { eapply (Ord.rec_join base next djoin dle wf); auto. }\n            { eapply dunion_eq; auto.\n              { split; auto. }\n              { eapply djoin_eq; auto. i.\n                eapply (@deq_transitive (next (Ord.rec base next djoin (add o0 (os a))))); auto.\n                eapply (Ord.rec_S base next djoin dle wf); auto.\n              }\n            }\n          }\n        }\n\n        rewrite drec_red. split.\n        { eapply dunion_supremum; auto.\n          eapply dunion_supremum; auto.\n          eapply (@dle_transitive (Ord.rec base next djoin o0)); auto.\n          eapply (Ord.rec_le_base base next djoin dle wf); auto.\n        }\n        { eapply dunion_le; auto. }\n      Qed.\n    End RECAPP.\n\n    Section ORECAPP.\n      Variable next: Ord.t -> Ord.t.\n      Hypothesis next_le: forall o, Ord.le o (next o).\n      Hypothesis next_mon: forall o0 o1 (LE: Ord.le o0 o1), Ord.le (next o0) (next o1).\n\n      Lemma orec_app base o0 o1:\n        Ord.eq (Ord.orec base next (add o0 o1)) (Ord.orec (Ord.orec base next o0) next o1).\n      Proof.\n        eapply (rec_app next Ord.join Ord.le (fun _ => True)); auto.\n        { i. reflexivity. }\n        { i. transitivity d1; auto. }\n        { i. eapply Ord.join_upperbound. }\n        { i. eapply Ord.join_supremum. auto. }\n      Qed.\n    End ORECAPP.\n\n\n    Section MULT.\n      Definition mult (o0: Ord.t): forall (o1: Ord.t), Ord.t := Ord.orec Ord.O (flip add o0).\n\n      Lemma mult_gen_le o0 o1: Ord.le o1 (flip add o0 o1).\n      Proof.\n        eapply add_base_l.\n      Qed.\n      Let _mult_gen_le := mult_gen_le.\n\n      Lemma mult_gen_mon o o0 o1 (LE: Ord.le o0 o1): Ord.le (flip add o o0) (flip add o o1).\n      Proof.\n        eapply le_add_l. auto.\n      Qed.\n      Let _mult_gen_mon := mult_gen_mon.\n\n      Lemma mult_O_r o: Ord.eq (mult o Ord.O) Ord.O.\n      Proof.\n        eapply (@Ord.orec_O Ord.O (flip add o)); auto.\n      Qed.\n\n      Lemma mult_S o0 o1: Ord.eq (mult o0 (Ord.S o1)) (add (mult o0 o1) o0).\n      Proof.\n        eapply (@Ord.orec_S Ord.O (flip add o0)); auto.\n      Qed.\n\n      Lemma mult_join o A (os: A -> Ord.t):\n        Ord.eq (mult o (Ord.join os)) (Ord.join (fun a => mult o (os a))).\n      Proof.\n        transitivity (Ord.union Ord.O (Ord.join (fun a => mult o (os a)))).\n        { eapply (@Ord.orec_join Ord.O (flip add _)); eauto. }\n        { eapply Ord.union_max. eapply Ord.O_bot. }\n      Qed.\n\n      Lemma mult_build o A (os: A -> Ord.t)\n        :\n          Ord.eq (mult o (Ord.build os)) (Ord.join (fun a => add (mult o (os a)) o)).\n      Proof.\n        transitivity (Ord.union Ord.O (Ord.join (fun a => add (mult o (os a)) o))).\n        { eapply (@Ord.orec_build Ord.O (flip add _)); eauto. }\n        { eapply Ord.union_max. eapply Ord.O_bot. }\n      Qed.\n\n      Lemma mult_union o0 o1 o2\n        :\n          Ord.eq (mult o0 (Ord.union o1 o2)) (Ord.union (mult o0 o1) (mult o0 o2)).\n      Proof.\n        eapply Ord.orec_union; auto.\n      Qed.\n\n      Lemma le_mult_r o0 o1 o2 (LE: Ord.le o1 o2)\n        :\n          Ord.le (mult o0 o1) (mult o0 o2).\n      Proof.\n        eapply Ord.le_orec; auto.\n      Qed.\n\n      Lemma eq_mult_r o0 o1 o2 (EQ: Ord.eq o1 o2)\n        :\n          Ord.eq (mult o0 o1) (mult o0 o2).\n      Proof.\n        split.\n        - eapply le_mult_r; eauto. eapply EQ.\n        - eapply le_mult_r; eauto. eapply EQ.\n      Qed.\n\n      Lemma le_mult_l o0 o1 o2 (LE: Ord.le o0 o1)\n        :\n          Ord.le (mult o0 o2) (mult o1 o2).\n      Proof.\n        eapply (@Ord.orec_mon Ord.O (flip add o0) Ord.O (flip add o1)); auto.\n        { reflexivity. }\n        { i. unfold flip. transitivity (add o4 o0).\n          { eapply le_add_l; auto. }\n          { eapply le_add_r; auto. }\n        }\n      Qed.\n\n      Lemma eq_mult_l o0 o1 o2 (EQ: Ord.eq o0 o1)\n        :\n          Ord.eq (mult o0 o2) (mult o1 o2).\n      Proof.\n        split.\n        - eapply le_mult_l; eauto. eapply EQ.\n        - eapply le_mult_l; eauto. eapply EQ.\n      Qed.\n\n      Lemma lt_mult_r o0 o1 o2 (LT: Ord.lt o1 o2) (POS: Ord.lt Ord.O o0)\n        :\n          Ord.lt (mult o0 o1) (mult o0 o2).\n      Proof.\n        eapply Ord.S_supremum in LT.\n        eapply Ord.lt_le_lt.\n        2: { eapply le_mult_r. eapply LT. }\n        eapply Ord.lt_eq_lt.\n        { eapply mult_S. }\n        eapply add_lt_l. auto.\n      Qed.\n\n      Lemma mult_O_l o: Ord.eq (mult Ord.O o) Ord.O.\n      Proof.\n        induction o. etransitivity.\n        { eapply mult_build. }\n        { split.\n          - eapply Ord.join_supremum. i.\n            transitivity (mult Ord.O (os a)); auto.\n            { eapply add_O_r. }\n            { eapply H. }\n          - eapply Ord.O_bot. }\n      Qed.\n\n      Lemma mult_1_r o: Ord.eq (mult o (Ord.S Ord.O)) o.\n      Proof.\n        etransitivity.\n        { eapply mult_S. }\n        etransitivity.\n        { eapply eq_add_l. eapply mult_O_r. }\n        eapply add_O_l.\n      Qed.\n\n      Lemma mult_1_l o: Ord.eq (mult (Ord.S Ord.O) o) o.\n      Proof.\n        transitivity (Ord.orec Ord.O Ord.S o).\n        2: { symmetry. eapply Ord.orec_of_S. }\n        split.\n        { eapply Ord.orec_mon.\n          { reflexivity. }\n          { i. unfold flip. etransitivity.\n            { eapply add_S. }\n            { apply Ord.le_S. transitivity o0; auto.\n              eapply add_O_r.\n            }\n          }\n        }\n        { eapply Ord.orec_mon.\n          { reflexivity. }\n          { i. unfold flip. etransitivity.\n            { apply Ord.le_S. eapply LE. }\n            transitivity (Ord.S (add o1 Ord.O)); auto.\n            { apply Ord.le_S. eapply add_O_r. }\n            { eapply add_S. }\n          }\n        }\n      Qed.\n\n      Lemma mult_dist o0 o1 o2: Ord.eq (mult o0 (add o1 o2)) (add (mult o0 o1) (mult o0 o2)).\n      Proof.\n        revert o0 o1. induction o2. i. etransitivity.\n        { eapply eq_mult_r. eapply add_build. }\n        etransitivity.\n        2: { eapply eq_add_r. symmetry. eapply mult_build. }\n        etransitivity.\n        { eapply mult_union. }\n        etransitivity.\n        { eapply Ord.eq_union.\n          { reflexivity. }\n          { eapply mult_join. }\n        }\n        etransitivity.\n        2: { symmetry. eapply add_join. }\n        eapply Ord.eq_union.\n        { reflexivity. } split.\n        { eapply Ord.le_join. i. exists a0.\n          etransitivity.\n          { eapply mult_S. }\n          etransitivity.\n          { eapply eq_add_l. symmetry. eapply H. }\n          eapply add_assoc.\n        }\n        { eapply Ord.le_join. i. exists a0.\n          etransitivity.\n          { eapply add_assoc. }\n          etransitivity.\n          { eapply eq_add_l. eapply H. }\n          eapply mult_S.\n        }\n      Qed.\n\n      Lemma mult_assoc o0 o1 o2: Ord.eq (mult (mult o0 o1) o2) (mult o0 (mult o1 o2)).\n      Proof.\n        revert o0 o1. induction o2. i. etransitivity.\n        { eapply mult_build. } etransitivity.\n        2: {\n          eapply eq_mult_r; auto.\n          { symmetry. eapply mult_build. }\n        }\n        etransitivity.\n        2: { symmetry. eapply mult_join. }\n        split.\n        { eapply Ord.le_join. i. exists a0.\n          etransitivity.\n          { eapply le_add_l. eapply H. }\n          { eapply mult_dist. }\n        }\n        { eapply Ord.le_join. i. exists a0.\n          etransitivity.\n          { eapply mult_dist. }\n          { eapply le_add_l. eapply H. }\n        }\n      Qed.\n\n      Lemma mult_le_l o0 o1 (POS: Ord.lt Ord.O o0): Ord.le o1 (mult o1 o0).\n      Proof.\n        eapply Ord.S_supremum in POS. etransitivity.\n        2: { eapply le_mult_r in POS. eauto. }\n        eapply mult_1_r.\n      Qed.\n\n      Lemma mult_lt_l o0 o1 (POS: Ord.lt Ord.O o1)\n            (TWO: Ord.lt (Ord.S Ord.O) o0): Ord.lt o1 (mult o1 o0).\n      Proof.\n        eapply Ord.S_supremum in TWO. eapply (@Ord.lt_le_lt (mult o1 (Ord.S (Ord.S Ord.O)))).\n        { eapply Ord.lt_eq_lt.\n          { eapply mult_S. }\n          eapply Ord.lt_eq_lt.\n          { eapply eq_add_l. eapply mult_S. }\n          eapply Ord.lt_eq_lt.\n          { eapply add_assoc. }\n          eapply Ord.lt_le_lt.\n          2: { eapply add_base_r. }\n          eapply add_lt_l. apply POS.\n        }\n        { eapply le_mult_r. auto. }\n      Qed.\n\n    End MULT.\n\n\n    Section EXPN.\n      Definition expn (o0: Ord.t): forall (o1: Ord.t), Ord.t := Ord.orec (Ord.S Ord.O) (flip mult o0).\n\n      Let expn_gen_mon o o0 o1 (LE: Ord.le o0 o1):\n        Ord.le (flip mult o o0) (flip mult o o1).\n      Proof.\n        eapply le_mult_l. auto.\n      Qed.\n\n      Section BASE.\n        Variable base: Ord.t.\n\n        Lemma expn_O o: Ord.eq (expn o Ord.O) (Ord.S Ord.O).\n        Proof.\n          eapply Ord.orec_O; auto.\n        Qed.\n\n        Lemma expn_pos o: Ord.lt Ord.O (expn base o).\n        Proof.\n          eapply Ord.lt_le_lt.\n          { eapply Ord.S_lt. }\n          { eapply Ord.orec_le_base. auto. }\n        Qed.\n\n        Section POSITIVE.\n          Hypothesis POS: Ord.lt Ord.O base.\n\n          Let expn_gen_le o: Ord.le o (flip mult base o).\n          Proof.\n            eapply mult_le_l; auto.\n          Qed.\n\n          Lemma expn_S o:\n            Ord.eq (expn base (Ord.S o)) (mult (expn base o) base).\n          Proof.\n            eapply Ord.orec_S; auto.\n          Qed.\n\n          Lemma le_expn_r o0 o1 (LE: Ord.le o0 o1):\n            Ord.le (expn base o0) (expn base o1).\n          Proof.\n            eapply Ord.le_orec; auto.\n          Qed.\n\n          Lemma eq_expn_r o0 o1 (EQ: Ord.eq o0 o1):\n            Ord.eq (expn base o0) (expn base o1).\n          Proof.\n            eapply Ord.eq_orec; auto.\n          Qed.\n\n          Lemma expn_join A (os: A -> Ord.t):\n            Ord.eq (expn base (Ord.join os)) (Ord.union (Ord.S Ord.O) (Ord.join (fun a => expn base (os a)))).\n          Proof.\n            eapply Ord.orec_join; auto.\n          Qed.\n\n          Lemma expn_join_inhabited A (os: A -> Ord.t)\n                (INHABITED: inhabited A):\n            Ord.eq (expn base (Ord.join os)) (Ord.join (fun a => expn base (os a))).\n          Proof.\n            eapply Ord.orec_join_inhabited; auto.\n          Qed.\n\n          Lemma expn_build A (os: A -> Ord.t):\n            Ord.eq (expn base (Ord.build os)) (Ord.union (Ord.S Ord.O) (Ord.join (fun a => mult (expn base (os a)) base))).\n          Proof.\n            eapply Ord.orec_build.\n          Qed.\n\n          Lemma expn_union o0 o1\n            :\n              Ord.eq (expn base (Ord.union o0 o1)) (Ord.union (expn base o0) (expn base o1)).\n          Proof.\n            eapply Ord.orec_union; auto.\n          Qed.\n\n          Lemma expn_1_r: Ord.eq (expn base (Ord.S Ord.O)) base.\n          Proof.\n            etransitivity.\n            { eapply expn_S. }\n            etransitivity.\n            { eapply eq_mult_l. eapply expn_O. }\n            eapply mult_1_l.\n          Qed.\n\n          Lemma expn_add o0 o1:\n            Ord.eq (expn base (add o0 o1)) (mult (expn base o0) (expn base o1)).\n          Proof.\n            revert o0. induction o1. i. etransitivity.\n            { eapply eq_expn_r. eapply add_build. }\n            etransitivity.\n            { eapply expn_union. }\n            etransitivity.\n            2: { eapply eq_mult_r. symmetry. eapply expn_build. }\n            etransitivity.\n            2: { symmetry. eapply mult_union. }\n            etransitivity.\n            { eapply Ord.eq_union.\n              { reflexivity. }\n              eapply expn_join.\n            }\n            etransitivity.\n            { eapply Ord.union_assoc. }\n            eapply Ord.eq_union.\n            { etransitivity.\n              { eapply Ord.union_comm. }\n              { etransitivity.\n                2: { symmetry. eapply mult_1_r. }\n                { eapply Ord.union_max. eapply Ord.S_supremum. eapply expn_pos. }\n              }\n            }\n            etransitivity.\n            2: { symmetry. eapply mult_join. }\n            eapply Ord.eq_join. i.\n            etransitivity.\n            { eapply expn_S. }\n            etransitivity.\n            2: { eapply mult_assoc. }\n            eapply eq_mult_l.\n            eapply H.\n          Qed.\n        End POSITIVE.\n\n        Lemma lt_expn_r (TWO: Ord.lt (Ord.S Ord.O) base) o0 o1 (LT: Ord.lt o0 o1):\n          Ord.lt (expn base o0) (expn base o1).\n        Proof.\n          assert (POS: Ord.lt Ord.O base).\n          { eapply Ord.le_lt_lt; eauto. eapply Ord.S_le. }\n          eapply (@Ord.lt_le_lt (expn base (Ord.S o0))).\n          { eapply Ord.lt_eq_lt.\n            { eapply expn_S. auto. }\n            { eapply mult_lt_l; auto. eapply expn_pos. }\n          }\n          { eapply le_expn_r. eapply Ord.S_supremum. auto. }\n        Qed.\n      End BASE.\n\n      Lemma expn_1_l o: Ord.eq (expn (Ord.S Ord.O) o) (Ord.S Ord.O).\n      Proof.\n        induction o. etransitivity.\n        { eapply expn_build. }\n        etransitivity.\n        { eapply Ord.union_comm. }\n        eapply Ord.union_max. eapply Ord.join_supremum.\n        i. eapply Ord.eq_le_le.\n        { eapply mult_1_r. }\n        eapply H.\n      Qed.\n\n      Lemma le_expn_l o0 o1 o2 (LE: Ord.le o0 o1):\n        Ord.le (expn o0 o2) (expn o1 o2).\n      Proof.\n        eapply Ord.orec_mon.\n        { reflexivity. }\n        { i. transitivity (mult o3 o1).\n          { eapply le_mult_r. auto. }\n          { eapply le_mult_l. auto. }\n        }\n      Qed.\n\n      Lemma eq_expn_l o0 o1 o2 (EQ: Ord.eq o0 o1):\n        Ord.eq (expn o0 o2) (expn o1 o2).\n      Proof.\n        split; eapply le_expn_l; apply EQ.\n      Qed.\n\n      Lemma expn_mult o0 (POS: Ord.lt Ord.O o0) o1 o2:\n        Ord.eq (expn o0 (mult o1 o2)) (expn (expn o0 o1) o2).\n      Proof.\n        induction o2.\n        etransitivity.\n        { eapply eq_expn_r. eapply mult_build. }\n        etransitivity.\n        { eapply expn_join. auto. }\n        etransitivity.\n        2: { symmetry. eapply expn_build. }\n        eapply Ord.eq_union.\n        { reflexivity. }\n        eapply Ord.eq_join. i.\n        etransitivity.\n        { eapply expn_add. auto. }\n        eapply eq_mult_l. auto.\n      Qed.\n    End EXPN.\n\n    Section PROPER.\n      Global Program Instance add_eq_proper: Proper (Ord.eq ==> Ord.eq ==> Ord.eq) (add).\n      Next Obligation.\n        ii.\n        etransitivity.\n        - eapply eq_add_l; eauto.\n        - eapply eq_add_r; eauto.\n      Qed.\n\n      Global Program Instance add_le_proper: Proper (Ord.le ==> Ord.le ==> Ord.le) (add).\n      Next Obligation.\n        ii.\n        etransitivity.\n        - eapply le_add_l; eauto.\n        - eapply le_add_r; eauto.\n      Qed.\n\n      Global Program Instance mult_eq_proper: Proper (Ord.eq ==> Ord.eq ==> Ord.eq) (mult).\n      Next Obligation.\n        ii.\n        etransitivity.\n        - eapply eq_mult_l; eauto.\n        - eapply eq_mult_r; eauto.\n      Qed.\n\n      Global Program Instance mult_le_proper: Proper (Ord.le ==> Ord.le ==> Ord.le) (mult).\n      Next Obligation.\n        ii.\n        etransitivity.\n        - eapply le_mult_l; eauto.\n        - eapply le_mult_r; eauto.\n      Qed.\n\n      Global Program Instance expn_eq_proper: Proper (Ord.eq ==> Ord.eq ==> Ord.eq) (expn).\n      Next Obligation.\n        ii.\n        etransitivity.\n        - eapply eq_expn_l; eauto.\n        - eapply eq_expn_r; eauto.\n      Qed.\n\n      Global Program Instance expn_le_proper: Proper (Ord.le ==> Ord.le ==> Ord.le) (expn).\n      Next Obligation.\n        ii.\n        etransitivity.\n        - eapply le_expn_l; eauto.\n        - eapply le_expn_r; eauto.\n      Qed.\n    End PROPER.\n\n    Section FROMNAT.\n      Lemma le_from_nat n0 n1 (LE: Peano.le n0 n1):\n        Ord.le n0 n1.\n      Proof.\n        induction LE.\n        { reflexivity. }\n        { etransitivity; eauto. ss. eapply Ord.S_le. }\n      Qed.\n\n      Lemma lt_from_nat n0 n1 (LT: Peano.lt n0 n1):\n        Ord.lt n0 n1.\n      Proof.\n        eapply Ord.lt_le_lt.\n        2: { eapply le_from_nat. eapply LT. }\n        { ss. eapply Ord.S_lt. }\n      Qed.\n\n      Lemma add_from_nat n0 n1:\n        Ord.eq (n0 + n1) (add (Ord.from_nat n0) (Ord.from_nat n1)).\n      Proof.\n        Local Transparent Ord.from_nat.\n        induction n1; ss.\n        { rewrite PeanoNat.Nat.add_0_r.\n          symmetry. eapply add_O_r. }\n        { rewrite PeanoNat.Nat.add_succ_r. ss.\n          etransitivity.\n          { eapply Ord.eq_S. eapply IHn1. }\n          symmetry. eapply add_S.\n        }\n      Qed.\n\n      Lemma mult_from_nat n0 n1:\n        Ord.eq (Ord.from_nat (n0 * n1)) (mult (Ord.from_nat n0) (Ord.from_nat n1)).\n      Proof.\n        induction n1; ss.\n        { rewrite PeanoNat.Nat.mul_0_r.\n          symmetry. eapply mult_O_r. }\n        { rewrite PeanoNat.Nat.mul_succ_r.\n          etransitivity.\n          { eapply add_from_nat. }\n          etransitivity.\n          { eapply eq_add_l. eapply IHn1. }\n          symmetry. eapply mult_S.\n        }\n      Qed.\n\n      Lemma expn_from_nat n0 (POS: 0 < n0) n1:\n        Ord.eq (Ord.from_nat (Nat.pow n0 n1)) (expn (Ord.from_nat n0) (Ord.from_nat n1)).\n      Proof.\n        induction n1; ss.\n        { symmetry. eapply expn_O. }\n        { etransitivity.\n          { rewrite PeanoNat.Nat.mul_comm. eapply mult_from_nat. }\n          etransitivity.\n          { eapply eq_mult_l. eapply IHn1. }\n          symmetry. eapply expn_S.\n          eapply (@lt_from_nat 0 n0). auto.\n        }\n      Qed.\n    End FROMNAT.\n  End ARITHMETIC.\nEnd OrdArith.\n\n\nGlobal Opaque OrdArith.add OrdArith.mult OrdArith.expn.\n\nInfix \"+\" := OrdArith.add : ord_scope.\nInfix \"*\" := OrdArith.mult : ord_scope.\nInfix \"^\" := OrdArith.expn : ord_scope.\n", "meta": {"author": "minkiminki", "repo": "Ordinal", "sha": "225f2f2b18ec8d65a637d964839528eeeb1829ce", "save_path": "github-repos/coq/minkiminki-Ordinal", "path": "github-repos/coq/minkiminki-Ordinal/Ordinal-225f2f2b18ec8d65a637d964839528eeeb1829ce/src/Arithmetic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7066656249480371}}
{"text": "(* Exercise 20 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_020 :\n  (exists x : D, P x /\\ Q x)\n->\n  (exists x : D, P x) /\\ (exists x : D, Q x).\nProof.\nimp_i a1.\ncon_i.\nexi_e (exists x:D, P x /\\ Q x) a a2.\nhyp a1.\nexi_i a.\ncon_e1 (Q a).\nhyp a2.\nexi_e (exists x:D, P x /\\ Q x) a a2.\nhyp a1.\nexi_i a.\ncon_e2 (P a).\nhyp a2.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak11/Taak11_pred020.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7066656229681566}}
{"text": "Require Export FiniteTypes.\nRequire Import InfiniteTypes.\nRequire Import CSB.\nRequire Import DecidableDec.\nRequire Export Relation_Definitions.\nRequire Import Relation_Definitions_Implicit.\nRequire Import Description.\nRequire Import Proj1SigInjective.\nRequire Import DependentTypeChoice.\n\nSet Asymmetric Patterns.\n\nInductive CountableT (X:Type) : Prop :=\n  | intro_nat_injection: forall f:X->nat, injective f -> CountableT X.\n\nLemma CountableT_is_FiniteT_or_countably_infinite:\n  forall X:Type, CountableT X ->\n      {FiniteT X} + {exists f:X->nat, bijective f}.\nProof.\nintros.\napply exclusive_dec.\nred; intro.\ndestruct H0 as [? [f ?]].\ncontradiction nat_infinite.\napply bij_finite with _ f; trivial.\napply bijective_impl_invertible; trivial.\n\ncase (classic (FiniteT X)).\nleft; trivial.\nright.\napply infinite_nat_inj in H0.\ndestruct H.\ndestruct H0 as [g].\napply CSB with f g; trivial.\nQed.\n\nLemma countable_nat_product: CountableT (nat*nat).\nProof.\npose (sum_1_to_n := fix sum_1_to_n n:nat := match n with\n  | O => O\n  | S m => (sum_1_to_n m) + n\nend).\nexists (fun p:nat*nat => let (m,n):=p in\n  (sum_1_to_n (m+n)) + n).\nassert (forall m n:nat, m<n ->\n  sum_1_to_n m + m < sum_1_to_n n).\nintros.\ninduction H.\nsimpl.\nauto with arith.\napply lt_trans with (sum_1_to_n m0).\nassumption.\nsimpl.\nassert (0 < S m0); auto with arith.\nassert (sum_1_to_n m0 + 0 < sum_1_to_n m0 + S m0); auto with arith.\nassert (sum_1_to_n m0 + 0 = sum_1_to_n m0); auto with arith.\nrewrite H2 in H1; assumption.\n\nred; intros.\ndestruct x1 as [x1 y1].\ndestruct x2 as [x2 y2].\nRequire Import Compare_dec.\ncase (lt_eq_lt_dec (x1+y1) (x2+y2)); intro.\ncase s; intro.\nassert (sum_1_to_n (x1+y1) + y1 < sum_1_to_n (x2+y2) + y2).\napply le_lt_trans with (sum_1_to_n (x1+y1) + (x1+y1)).\nassert (sum_1_to_n (x1+y1) + (x1+y1) =\n  (sum_1_to_n (x1+y1) + y1) + x1).\nRequire Import ArithRing.\nring.\nauto with arith.\napply lt_le_trans with (sum_1_to_n (x2+y2)).\napply H; trivial.\nauto with arith.\nrewrite H0 in H1.\ncontradict H1.\nauto with arith.\n\nassert (y1=y2).\nrewrite e in H0.\nRequire Import Arith.\napply plus_reg_l in H0.\nassumption.\nf_equal; trivial.\nrewrite H1 in e.\nrewrite plus_comm in e.\nrewrite (plus_comm x2 y2) in e.\napply plus_reg_l in e.\nassumption.\n\nassert (sum_1_to_n (x2+y2) + y2 < sum_1_to_n (x1+y1) + y1).\napply le_lt_trans with (sum_1_to_n (x2+y2) + (x2+y2)).\nauto with arith.\napply lt_le_trans with (sum_1_to_n (x1+y1)); auto with arith.\nrewrite H0 in H1.\ncontradict H1.\nauto with arith.\nQed.\n\nLemma countable_sum: forall X Y:Type,\n  CountableT X -> CountableT Y -> CountableT (X+Y).\nProof.\nintros.\ndestruct H as [f].\ndestruct H0 as [g].\ndestruct countable_nat_product as [h].\nexists (fun s:X+Y => match s with\n  | inl x => h (0, f x)\n  | inr y => h (1, g y)\nend).\nred; intros s1 s2 ?.\ndestruct s1 as [x1|y1]; destruct s2 as [x2|y2];\n  apply H1 in H2; try discriminate H2;\n  intros; f_equal; (apply H || apply H0); injection H2; trivial.\nQed.\n\nLemma countable_product: forall X Y:Type,\n  CountableT X -> CountableT Y -> CountableT (X*Y).\nProof.\nintros.\ndestruct H as [f].\ndestruct H0 as [g].\npose (fg := fun (p:X*Y) => let (x,y):=p in (f x, g y)).\ndestruct countable_nat_product as [h].\nexists (fun p:X*Y => h (fg p)).\nred; intros.\napply H1 in H2.\ndestruct x1 as [x1 y1].\ndestruct x2 as [x2 y2].\nunfold fg in H2.\ninjection H2; intros.\napply H0 in H3.\napply H in H4.\nf_equal; trivial.\nQed.\n\nRequire Import FunctionalExtensionality.\n\nLemma countable_exp: forall X Y:Type,\n  FiniteT X -> CountableT Y -> CountableT (X->Y).\nProof.\nintros.\ninduction H.\nexists (fun _ => 0).\nred; intros.\nextensionality f.\ndestruct f.\n\ndestruct (countable_product (T->Y) Y); trivial.\n\nexists (fun (g:option T->Y) =>\n  f (fun x:T => g (Some x), g None)).\nred; intros g1 g2 ?.\napply H1 in H2.\nextensionality o.\ndestruct o.\ninjection H2; intros.\npose proof (equal_f H4).\nsimpl in H5.\napply H5.\ninjection H2; trivial.\n\ndestruct H1.\ndestruct IHFiniteT.\nexists (fun (h:Y0->Y) => f0 (fun x:X => h (f x))).\nred; intros h1 h2 ?.\napply H3 in H4.\npose proof (equal_f H4).\nsimpl in H5.\nextensionality y.\nrewrite <- (H2 y).\napply H5.\nQed.\n\nDefinition Countable {X:Type} (S:Ensemble X) : Prop :=\n  CountableT {x:X | In S x}.\n\nLemma inj_countable: forall {X Y:Type} (f:X->Y),\n  CountableT Y -> injective f -> CountableT X.\nProof.\nintros.\ndestruct H as [g].\nexists (fun x:X => g (f x)).\nred; intros; auto.\nQed.\n\nLemma surj_countable: forall {X Y:Type} (f:X->Y),\n  CountableT X -> surjective f -> CountableT Y.\nProof.\nintros.\nRequire Import ClassicalChoice.\n\npose proof (choice (fun (y:Y) (x:X) => f x = y)).\ndestruct H1 as [finv].\nexact H0.\n\napply inj_countable with finv.\nassumption.\nred; intros.\ncongruence.\nQed.\n\nLemma countable_downward_closed: forall {X:Type} (S T:Ensemble X),\n  Countable T -> Included S T -> Countable S.\nProof.\nintros.\ndestruct H.\nexists (fun x:{x:X | In S x} => match x with\n  | exist x0 i => f (exist _ x0 (H0 _ i))\n  end).\nred; intros.\ndestruct x1 as [x1].\ndestruct x2 as [x2].\napply H in H1.\ninjection H1; intros.\ndestruct H2.\ndestruct (proof_irrelevance _ i i0).\ntrivial.\nQed.\n\nLemma countable_img: forall {X Y:Type} (f:X->Y) (S:Ensemble X),\n  Countable S -> Countable (Im S f).\nProof.\nintros.\nassert (forall x:X, In S x -> In (Im S f) (f x)).\nauto with sets.\npose (fS := fun x:{x:X | In S x} =>\n  match x return {y:Y | In (Im S f) y} with\n  | exist x0 i => exist _ (f x0) (H0 x0 i)\n  end).\napply surj_countable with fS; trivial.\nred; intros.\ndestruct y.\ndestruct i.\nexists (exist _ x i).\nsimpl.\ngeneralize (H0 x i); intro.\ngeneralize (Im_intro X Y S f x i y e); intro.\ndestruct e.\ndestruct (proof_irrelevance _ i0 i1).\ntrivial.\nQed.\n\nLemma countable_type_ensemble: forall {X:Type} (S:Ensemble X),\n  CountableT X -> Countable S.\nProof.\nintros.\nred.\napply inj_countable with (@proj1_sig _ (fun x:X => In S x)).\nassumption.\nred; intros.\napply proj1_sig_injective.\nassumption.\nQed.\n\nLemma FiniteT_impl_CountableT: forall X:Type,\n  FiniteT X -> CountableT X.\nProof.\nintros.\ninduction H.\nexists (False_rect nat).\nred; intros.\ndestruct x1.\ndestruct IHFiniteT.\nexists (fun x:option T => match x with\n  | Some x0 => S (f x0)\n  | None => 0\nend).\nred; intros.\ndestruct x1; destruct x2; try (injection H1 || discriminate H1); trivial.\nintro.\napply H0 in H2.\ndestruct H2; trivial.\n\ndestruct IHFiniteT as [g].\ndestruct H0 as [finv].\nexists (fun y:Y => g (finv y)).\nred; intros y1 y2 ?.\napply H1 in H3.\ncongruence.\nQed.\n\nLemma Finite_impl_Countable: forall {X:Type} (S:Ensemble X),\n  Finite _ S -> Countable S.\nProof.\nintros.\napply FiniteT_impl_CountableT.\napply Finite_ens_type; trivial.\nQed.\n\nRequire Export ZArith.\n\nLemma positive_countable: CountableT positive.\nProof.\nexists nat_of_P.\nred; intros.\napply nat_of_P_inj; trivial.\nQed.\n\nLemma Z_countable: CountableT Z.\nProof.\ndestruct (countable_nat_product) as [f].\ndestruct positive_countable as [g].\nexists (fun n:Z => match n with\n  | Z0 => f (0, 0)\n  | Zpos p => f (1, g p)\n  | Zneg p => f (2, g p)\nend).\nred; intros n1 n2 ?.\ndestruct n1 as [|p1|p1]; destruct n2 as [|p2|p2]; apply H in H1;\n  try discriminate H1.\ntrivial.\ninjection H1; intro; f_equal; auto.\ninjection H1; intro; f_equal; auto.\nQed.\n\nRequire Export QArith.\n\nLemma Q_countable: CountableT Q.\nProof.\ndestruct countable_nat_product as [f].\ndestruct positive_countable as [g].\ndestruct Z_countable as [h].\nexists (fun q:Q => match q with\n  n # d => f (h n, g d)\nend).\nred; intros q1 q2 ?.\ndestruct q1 as [n1 d1]; destruct q2 as [n2 d2].\napply H in H2.\ninjection H2; intros.\nf_equal; auto.\nQed.\n\nRequire Export IndexedFamilies.\n\nLemma countable_union: forall {X A:Type}\n  (F:IndexedFamily A X), CountableT A ->\n    (forall a:A, Countable (F a)) ->\n    Countable (IndexedUnion F).\nProof.\nintros.\ndestruct (choice_on_dependent_type (fun (a:A)\n                               (f:{x:X | In (F a) x} -> nat) =>\n  injective f)) as [choice_fun_inj].\nintro.\ndestruct (H0 a).\nexists f; trivial.\n\ndestruct (choice (fun (x:{x:X | In (IndexedUnion F) x}) (a:A) =>\n  In (F a) (proj1_sig x))) as [choice_fun_a].\ndestruct x as [x [a]].\nexists a.\nassumption.\n\ndestruct countable_nat_product as [g].\ndestruct H as [h].\nexists (fun x:{x:X | In (IndexedUnion F) x} =>\n  g (h (choice_fun_a x), choice_fun_inj (choice_fun_a x)\n                                   (exist _ (proj1_sig x) (H2 x)))).\nred; intros.\napply H3 in H4.\ninjection H4; intros.\napply H in H6.\nrevert H5.\ngeneralize (H2 x1).\ngeneralize (H2 x2).\nrewrite H6.\nintros.\napply H1 in H5.\ninjection H5.\napply proj1_sig_injective.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/zorns-lemma/CountableTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7066323983845415}}
{"text": "(** * Decide: Programming with Decision Procedures *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom VFA Require Import Perm.\n\n(* ################################################################# *)\n(** * Using [reflect] to characterize decision procedures *)\n\n(** Thus far in _Verified Functional Algorithms_ we have been using\n   - propositions ([Prop]) such as [a<b] (which is Notation for [lt a b])\n   - booleans ([bool]) such as [a<?b] (which is Notation for [ltb a b]). *)\n\nCheck Nat.lt.  (* : nat -> nat -> Prop *)\nCheck Nat.ltb.  (* : nat -> nat -> bool *)\n\n(** The [Perm] chapter defined a tactic called [bdestruct] that\n    does case analysis on (x <? y) while giving you hypotheses (above\n    the line) of the form (x<y).   This tactic is built using the [reflect] \n    type and the [ltb_reflect] theorem. *)\n\nPrint reflect.\n(* Inductive reflect (P : Prop) : bool -> Set :=\n    | ReflectT : P -> reflect P true \n    | ReflectF : ~ P -> reflect P false  *)\n\nCheck ltb_reflect.  (* : forall x y, reflect (x<y) (x <? y) *)\n\n(** The name [reflect] for this type is a reference to _computational\n   reflection_,  a technique in logic.  One takes a logical formula, or \n   proposition, or predicate,  and designs a syntactic embedding of \n   this formula as an \"object value\" in the logic.  That is, _reflect_ the\n   formula back into the logic. Then one can design computations \n   expressible inside the logic that manipulate these syntactic object \n   values.  Finally, one proves that the computations make transformations\n   that are equivalent to derivations (or equivalences) in the logic.\n\n   The first use of computational reflection was by Goedel, in 1931:\n   his syntactic embedding encoded formulas as natural numbers, a \n   \"Goedel numbering.\"  The second and third uses of reflection were\n   by Church and Turing, in 1936: they encoded (respectively) \n   lambda-expressions and Turing machines.\n\n   In Coq it is easy to do reflection, because the Calculus of Inductive\n   Constructions (CiC) has Inductive data types that can easily encode \n   syntax trees.  We could, for example, take some of our propositional \n   operators such as [and], [or], and make an [Inductive] type that is an \n   encoding of these, and build a computational reasoning system for\n   boolean satisfiability.\n\n   But in this chapter I will show something much simpler.  When \n   reasoning about less-than comparisons on natural numbers, we have\n   the advantage that [nat] already an inductive type; it is \"pre-reflected,\"\n   in some sense.  (The same for [Z], [list], [bool], etc.)  *)\n\n(** Now, let's examine how [reflect] expresses the coherence between\n  [lt] and [ltb]. Suppose we have a value [v] whose type is \n  [reflect (3<7) (3<?7)].  What is [v]?  Either it is\n  - ReflectT [P] (3<?7), where [P] is a proof of [3<7],  and [3<?7] is [true], or\n  - ReflectF [Q] (3<?7), where [Q] is a proof of [~(3<7)], and [3<?7] is [false].\n  In the case of [3,7], we are well advised to use [ReflectT], because\n   (3<?7) cannot match the [false] required by [ReflectF]. *)\n\nGoal (3<?7 = true). Proof. reflexivity. Qed.\n\n(** So [v] cannot be [ReflectF Q (3<?7)] for any [Q], because that would\n   not type-check.  Now, the next question:  must there exist a value\n   of type [reflect (3<7) (3<?7)]  ?  The answer is yes; that is the\n   [ltb_reflect] theorem.  The result of [Check ltb_reflect], above, says that\n   for any [x,y], there does exist a value (ltb_reflect x y) whose type\n   is exactly [reflect (x<y)(x<?y)].     So let's look at that value!  That is,\n   examine what [H], and [P], and [Q] are equal to at \"Case 1\" and \"Case 2\": *)\n\nTheorem three_less_seven_1: 3<7.\nProof.\nassert (H := ltb_reflect 3 7).\nremember (3<?7) as b.\ndestruct H as [P|Q] eqn:?.\n* (* Case 1: H = ReflectT (3<7) P *)\napply P.\n* (* Case 2: H = ReflectF (3<7) Q *)\ncompute in Heqb.\ninversion Heqb.\nQed.\n\n(** Here is another proof that uses [inversion] instead of [destruct].\n   The [ReflectF] case is eliminated automatically by [inversion]\n   because [3<?7] does not match [false]. *)\n\nTheorem three_less_seven_2: 3<7.\nProof.\nassert (H := ltb_reflect 3 7).\ninversion H as [P|Q].\napply P.\nQed.\n\n(** The [reflect] inductive data type is a way of relating a _decision\n   procedure_ (a function from X to [bool]) with a predicate (a function\n   from X to [Prop]).   The convenience of [reflect], in the verification\n   of functional programs, is that we can do [destruct (ltb_reflect a b)],\n   which relates [a<?b] (in the program) to the [a<b] (in the proof).\n   That's just how the [bdestruct] tactic works; you can go back\n   to [Perm.v] and examine how it is implemented in the [Ltac]\n   tactic-definition language. *)\n\n(* ################################################################# *)\n(** * Using [sumbool] to Characterize Decision Procedures *)\n\nModule ScratchPad.\n\n(** An alternate way to characterize decision procedures,\n   widely used in Coq, is via the inductive type [sumbool].\n\n   Suppose [Q]  is a proposition, that is, [Q: Prop].  We say [Q] is\n   _decidable_ if there is an algorithm for computing a proof of\n   [Q] or [~Q].  More generally, when [P] is a predicate (a function \n   from some type [T] to [Prop]), we say [P] is decidable when \n   [forall x:T, decidable(P)].\n\n   We represent this concept in Coq by an inductive datatype: *)\n\nInductive sumbool (A B : Prop) : Set :=\n | left : A -> sumbool A B\n | right : B -> sumbool A B.\n\n(** Let's consider [sumbool] applied to two propositions: *)\n\nDefinition t1 := sumbool (3<7) (3>2).\nLemma less37: 3<7. Proof. omega. Qed.\nLemma greater23: 3>2. Proof. omega. Qed.\n\nDefinition v1a: t1 := left (3<7) (3>2) less37.\nDefinition v1b: t1 := right (3<7) (3>2) greater23.\n\n(** A value of type [sumbool (3<7) (3>2)] is either one of:\n  - [left] applied to a proof of (3<7), or\n  - [right] applied to a proof of (3>2).   *)\n\n(** Now let's consider: *)\n\nDefinition t2 := sumbool (3<7) (2>3).\nDefinition v2a: t2 := left (3<7) (2>3) less37.\n\n(** A value of type [sumbool (3<7) (2>3)] is either one of:\n  - [left] applied to a proof of (3<7), or\n  - [right] applied to a proof of (2>3).\n  But since there are no proofs of 2>3, only [left] values (such as [v2a])\n  exist.  That's OK. *)\n\n(** [sumbool] is in the Coq standard library, where there is [Notation] \n   for it:  the expression [ {A}+{B} ] means [sumbool A B]. *)\n\nNotation \"{ A } + { B }\" := (sumbool A B) : type_scope.\n\n(** A very common use of [sumbool] is on a proposition and its negation.\n   For example, *)\n\nDefinition t4 := forall a b, {a<b}+{~(a<b)}.\n\n(** That expression, [forall a b, {a<b}+{~(a<b)}], says that for any \n natural numbers [a] and [b], either [a<b] or [a>=b].  But it is _more_\n than that!  Because [sumbool] is an Inductive type with two constructors\n [left] and [right], then given the [{3<7}+{~(3<7)}] you can pattern-match\n on it and learn _constructively_ which thing is true.  *)\n\nDefinition v3: {3<7}+{~(3<7)} := left _ _ less37.\n\nDefinition is_3_less_7:  bool :=\n match v3 with\n | left _ _ _ => true\n | right _ _ _ => false\n end.\n\nEval compute in is_3_less_7. (* = true : bool *)\n\nPrint t4.  (* = forall a b : nat, {a < b} + {~ a < b} *)\n\n(** Suppose there existed a value [lt_dec] of type [t4].  That would be a \n  _decision procedure_ for the less-than function on natural numbers.\n  For any nats [a] and [b], you could calculate [lt_dec a b], which would\n  be either [left ...] (if [a<b] was provable) or [right ...] (if [~(a<b)] was\n  provable).\n\n  Let's go ahead and implement [lt_dec].  We can base it on the function\n  [ltb: nat -> nat -> bool] which calculates whether [a] is less than [b],\n  as a boolean.  We already have a theorem that this function on booleans\n  is related to the proposition [a<b]; that theorem is called [ltb_reflect]. *)\n\nCheck ltb_reflect.  (* : forall x y, reflect (x<y) (x<?y) *)\n\n(** It's not too hard to use [ltb_reflect] to define [lt_dec] *)\n\nDefinition lt_dec (a: nat) (b: nat) : {a<b}+{~(a<b)} :=\nmatch ltb_reflect a b with\n| ReflectT _ P => left (a < b) (~ a < b) P\n| ReflectF _ Q => right (a < b) (~ a < b) Q\nend.\n\n(** Another, equivalent way to define [lt_dec] is to use \n     definition-by-tactic: *)\n\nDefinition lt_dec' (a: nat) (b: nat) : {a<b}+{~(a<b)}.\n  destruct (ltb_reflect a b) as [P|Q]. left. apply P.  right. apply Q.\nDefined.\n\nPrint lt_dec.\nPrint lt_dec'.\n\nTheorem lt_dec_equivalent: forall a b, lt_dec a b = lt_dec' a b.\nProof.\nintros.\nunfold lt_dec, lt_dec'.\nreflexivity.\nQed.\n\n(** Warning: these definitions of [lt_dec] are not as nice as the\n  definition in the Coq standard library, because these are not\n  fully computable.  See the discussion below. *)\n\nEnd ScratchPad.\n\n(* ================================================================= *)\n(** ** [sumbool] in the Coq Standard Library *)\n\nModule ScratchPad2.\nLocate sumbool. (* Coq.Init.Specif.sumbool *)\nPrint sumbool.\n\n(** The output of [Print sumbool] explains that the first two arguments \n   of [left] and [right] are implicit.  We use them as follows (notice that\n   [left] has only one explicit argument [P]:  *)\n\nDefinition lt_dec (a: nat) (b: nat) : {a<b}+{~(a<b)} :=\nmatch ltb_reflect a b with\n| ReflectT _ P => left P\n| ReflectF _ Q => right Q\nend.\n\nDefinition le_dec (a: nat) (b: nat) : {a<=b}+{~(a<=b)} :=\nmatch leb_reflect a b with\n| ReflectT _ P => left P\n| ReflectF _ Q => right Q\nend.\n\n(** Now, let's use [le_dec] directly in the implementation of insertion\n   sort, without mentioning [ltb] at all. *)\n\nFixpoint insert (x:nat) (l: list nat) := \n  match l with\n  | nil => x::nil\n  | h::t => if le_dec x h then x::h::t else h :: insert x t\n end.\n\nFixpoint sort (l: list nat) : list nat :=\n  match l with\n  | nil => nil\n  | h::t => insert h (sort t)\nend.\n\nInductive sorted: list nat -> Prop := \n| sorted_nil:\n    sorted nil\n| sorted_1: forall x,\n    sorted (x::nil)\n| sorted_cons: forall x y l,\n   x <= y -> sorted (y::l) -> sorted (x::y::l).\n\n(** **** Exercise: 2 stars, standard (insert_sorted_le_dec)  *)\nLemma insert_sorted:\n  forall a l, sorted l -> sorted (insert a l).\nProof.\n  intros a l H.\n  induction H.\n  - constructor.\n  - unfold insert.\n    destruct (le_dec a x) as [ Hle | Hgt].\n\n   (** Look at the proof state now.  In the first subgoal, we have\n      above the line, [Hle: a <= x].  In the second subgoal, we have\n      [Hgt: ~ (a < x)].  These are put there automatically by the \n      [destruct (le_dec a x)].  Now, the rest of the proof can proceed\n      as it did in [Sort.v], but using [destruct (le_dec _ _)] instead of\n      [bdestruct (_ <=? _)]. *)\n\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Decidability and Computability *)\n\n(** Before studying the rest of this chapter, it is helpful to study the\n   [ProofObjects] chapter of _Software Foundations volume 1_ if you\n   have not done so already.\n\n   A predicate [P: T->Prop] is _decidable_ if there is a computable\n   function [f: T->bool] such that, forall [x:T], [f x = true <-> P x].\n   The second and most famous example of an _undecidable_ predicate\n   is the Halting Problem (Turing, 1936): [T] is the type of Turing-machine\n   descriptions, and [P(x)] is, Turing machine [x] halts.  The first, and not\n   as famous, example is due to Church, 1936 (six months earlier): test\n   whether a lambda-expression has a normal form.  In 1936-37, as a \n   first-year PhD student before beginning his PhD thesis work, Turing\n   proved these two problems are equivalent.\n\n   Classical logic contains the axiom [forall P, P \\/ ~P].  This is not provable\n   in core Coq, that is, in the bare Calculus of Inductive Constructions.  But\n   its negation is not provable either.   You could add this axiom to Coq\n   and the system would still be consistent (i.e., no way to prove [False]).\n\n   But [P \\/ ~P] is a weaker statement than [ {P}+{~P} ], that is,\n   [sumbool P (~P)].  From [ {P}+{~P} ] you can actually _calculate_ or\n   [compute] either [left (x:P)] or [right(y: ~P)].     From [P \\/ ~P] you cannot \n   [compute] whether [P] is true.  Yes, you can [destruct] it in a proof, \n   but not in a calculation.  \n\n   For most purposes its unnecessary to add the axiom [P \\/ ~P] to Coq,\n   because for specific predicates there's a specific way to prove [P \\/ ~P]\n   as a theorem.  For example,  less-than on natural numbers is decidable,\n   and the existence of [ltb_reflect] or [lt_dec] (as a theorem, not as an axiom)\n   is a demonstration of that.\n\n   Furthermore, in this \"book\" we are interested in _algorithms_.  An axiom\n   [P \\/ ~P] does not give us an algorithm to compute whether P is true.  As\n   you saw in the definition of [insert] above, we can use [lt_dec] not only as\n   a theorem that either [3<7] or [~(3<7)], we can use it as a function to\n   compute whether [3<7].  In Coq, you can't compute with axioms!\n   Let's try it: *)\n\nAxiom lt_dec_axiom_1:  forall i j: nat, i<j \\/ ~(i<j).\n\n(** Now, can we use this axiom to compute with?  *)\n\n(* Uncomment and try this: \nDefinition max (i j: nat) : nat :=\n   if lt_dec_axiom_1 i j then j else i.\n*)\n\n(** That doesn't work, because an [if] statement requires an [Inductive]\n  data type with exactly two constructors; but [lt_dec_axiom_1 i j] has\n  type [i<j \\/ ~(i<j)],  which is not Inductive.  But let's try a different axiom: *)\n\nAxiom lt_dec_axiom_2:  forall i j: nat, {i<j} + {~(i<j)}.\n\nDefinition max_with_axiom (i j: nat) : nat :=\n   if lt_dec_axiom_2 i j then j else i.\n\n(** This typechecks, because [lt_dec_axiom_2 i j]  belongs to type\n     [sumbool (i<j) (~(i<j))]   (also written [ {i<j} + {~(i<j)} ]), which does have\n     two constructors.\n\n     Now, let's use this function: *)\n\nEval compute in max_with_axiom 3 7.\n  (*  = if lt_dec_axiom_2 3 7 then 7 else 3\n     : nat *)\n\n(** This [compute] didn't compute very much!  Let's try to evaluate it\n    using [unfold]: *)\n\nLemma prove_with_max_axiom:   max_with_axiom 3 7 = 7.\nProof.\nunfold max_with_axiom.\ntry reflexivity.  (* does not do anything, reflexivity fails *)\n(* uncomment this line and try it: \n   unfold lt_dec_axiom_2.\n*)\ndestruct (lt_dec_axiom_2 3 7).\nreflexivity.\ncontradiction n. omega.\nQed.\n\n(** It is dangerous to add Axioms to Coq: if you add one that's inconsistent,\n   then it leads to the ability to prove [False].  While that's a convenient way\n   to get a lot of things proved, it's unsound; the proofs are useless.  \n\n   The Axioms above, [lt_dec_axiom_1] and [lt_dec_axiom_2], are safe enough:\n   they are consistent.  But they don't help in computation.  Axioms are not\n   useful here. *)\n\nEnd ScratchPad2.\n\n(* ################################################################# *)\n(** * Opacity of [Qed] *)\n\n(** This lemma [prove_with_max_axiom] turned out to be _provable_, but the proof\n    could not go by _computation_.  In contrast, let's use [lt_dec], which was built\n    without any axioms: *)\n\nLemma compute_with_lt_dec:  (if ScratchPad2.lt_dec 3 7 then 7 else 3) = 7.\nProof.\ncompute.\n(* uncomment this line and try it:\n   unfold ltb_reflect.\n*)\nAbort.\n\n(** Unfortunately, even though [ltb_reflect] was proved without any axioms, it\n    is an _opaque theorem_  (proved with [Qed] instead of with [Defined]), and\n    one cannot compute with opaque theorems.  Not only that, but it is proved with\n    other opaque theorems such as [iff_sym] and [Nat.ltb_lt].  If we want to\n    compute with an implementation of [lt_dec] built from [ltb_reflect], then\n    we will have to rebuild [ltb_reflect] without using [Qed] anywhere, only [Defined].\n\n    Instead, let's use the version of [lt_dec] from the Coq standard library,\n    which _is_ carefully built without any opaque ([Qed]) theorems.\n*)\n\nLemma compute_with_StdLib_lt_dec:  (if lt_dec 3 7 then 7 else 3) = 7.\nProof.\ncompute.\nreflexivity.\nQed.\n\n(** The Coq standard library has many decidability theorems.  You can\n   examine them by doing the following [Search] command. The results\n   shown here are only for the subset of the library that's currently\n   imported (by the [Import] commands above); there's even more out there. *)\n\nSearch ({_}+{~_}).\n(*\nreflect_dec: forall (P : Prop) (b : bool), reflect P b -> {P} + {~ P}\nlt_dec: forall n m : nat, {n < m} + {~ n < m}\nlist_eq_dec:\n  forall A : Type,\n  (forall x y : A, {x = y} + {x <> y}) ->\n  forall l l' : list A, {l = l'} + {l <> l'}\nle_dec: forall n m : nat, {n <= m} + {~ n <= m}\nin_dec:\n  forall A : Type,\n  (forall x y : A, {x = y} + {x <> y}) ->\n  forall (a : A) (l : list A), {In a l} + {~ In a l}\ngt_dec: forall n m : nat, {n > m} + {~ n > m}\nge_dec: forall n m : nat, {n >= m} + {~ n >= m}\neq_nat_decide: forall n m : nat, {eq_nat n m} + {~ eq_nat n m}\neq_nat_dec: forall n m : nat, {n = m} + {n <> m}\nbool_dec: forall b1 b2 : bool, {b1 = b2} + {b1 <> b2}\nZodd_dec: forall n : Z, {Zodd n} + {~ Zodd n}\nZeven_dec: forall n : Z, {Zeven n} + {~ Zeven n}\nZ_zerop: forall x : Z, {x = 0%Z} + {x <> 0%Z}\nZ_lt_dec: forall x y : Z, {(x < y)%Z} + {~ (x < y)%Z}\nZ_le_dec: forall x y : Z, {(x <= y)%Z} + {~ (x <= y)%Z}\nZ_gt_dec: forall x y : Z, {(x > y)%Z} + {~ (x > y)%Z}\nZ_ge_dec: forall x y : Z, {(x >= y)%Z} + {~ (x >= y)%Z}\n*)\n\n(** The type of [list_eq_dec] is worth looking at.  It says that if you\n     have  a decidable equality for an element type [A], then\n    [list_eq_dec] calculates for you a decidable equality for type [list A].\n    Try it out: *)\n\nDefinition list_nat_eq_dec: \n    (forall al bl : list nat, {al=bl}+{al<>bl}) :=\n  list_eq_dec eq_nat_dec.\n\nEval compute in if list_nat_eq_dec [1;3;4] [1;4;3] then true else false.\n (* = false : bool *)\n\nEval compute in if list_nat_eq_dec [1;3;4] [1;3;4] then true else false.\n (* = true : bool *)\n\n(** **** Exercise: 2 stars, standard (list_nat_in) \n\n    Use [in_dec] to build this function. *)\n\nDefinition list_nat_in: forall (i: nat) (al: list nat), {In i al}+{~ In i al}\n (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *). Admitted.\n\nExample in_4_pi:  (if list_nat_in 4  [3;1;4;1;5;9;2;6] then true else false) = true.\nProof.\nsimpl.\n(* reflexivity. *)\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** In general, beyond [list_eq_dec] and [in_dec], one can construct a\n     whole programmable calculus of decidability, using the\n     programs-as-proof  language of Coq.  But is it a good idea?  Read on! *)\n\n(* ################################################################# *)\n(** * Advantages and Disadvantages of [reflect] Versus [sumbool] *)\n\n(** I have shown two ways to program decision procedures in Coq,\n    one using [reflect] and the other using [{_}+{~_}], i.e., [sumbool].\n\n   - With [sumbool], you define _two_ things: the operator in [Prop]\n      such as [lt: nat -> nat -> Prop] and the decidability \"theorem\"\n      in [sumbool], such as [lt_dec: forall i j, {lt i j}+{~ lt i j}].  I say\n      \"theorem\" in quotes because it's not _just_ a theorem, it's also\n      a (nonopaque) computable function.\n\n   - With [reflect], you define _three_ things:  the operator in [Prop],\n      the operator in [bool] (such as [ltb: nat -> nat -> bool], and the\n      theorem that relates them (such as [ltb_reflect]).  \n\n   Defining three things seems like more work than defining two.\n   But it may be easier and more efficient.  Programming in [bool],\n   you may have more control over how your functions are implemented,\n   you will have fewer difficult uses of dependent types, and you\n   will run into fewer difficulties with opaque theorems.\n\n   However, among Coq programmers, [sumbool] seems to be more\n   widely used, and it seems to have better support in the Coq standard\n   library.  So you may encounter it, and it is worth understanding what\n   it does.   Either of these two methods is a reasonable way of programming\n   with proof.  *)\n\n(* 2020-08-07 17:08 *)\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/vfa/Decide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7066323974004459}}
{"text": "Require Export XR_R.\nRequire Export XR_Rlt.\nRequire Export XR_Rlt_not_eq.\n\nImplicit Type r : R.\nLocal Open Scope R_scope.\n\nLemma Rlt_dichotomy_converse : forall r1 r2, r1 < r2 \\/ r2 < r1 -> r1 <> r2.\nProof.\n  intros x y.\n  intros [ hxy | hyx ].\n  {\n    apply Rlt_not_eq.\n    exact hxy.\n  }\n  {\n    apply not_eq_sym.\n    apply Rlt_not_eq.\n    exact hyx.\n  }\nQed.\n\n\n\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rlt_dichotomy_converse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7066323855777801}}
{"text": "Require Import Arith List TheoryList.\n\nDefinition var := nat.\n\nInductive exp : Set :=\n  | Num : nat -> exp\n  | Bool : bool -> exp\n\n  | Var : var -> exp\n\n  | Plus : exp -> exp -> exp\n  | Minus : exp -> exp -> exp\n\n  | Eq : exp -> exp -> exp.\n\nDefinition env := var -> exp.\n\nInductive isValue : exp -> Prop :=\n  | ValueNum : forall n, isValue (Num n)\n  | ValueBool : forall n, isValue (Bool n).\n\nDefinition nat_eq n1 n2 :=\n  if eq_nat_dec n1 n2\n    then true\n    else false.\n\nInductive step (G : env) : exp -> exp -> Prop :=\n  | StepVar : forall x, step G (Var x) (G x)\n\n  | StepPlus : forall n1 n2,\n    step G (Plus (Num n1) (Num n2)) (Num (n1 + n2))\n  | StepPlus1 : forall e1 e2 e1',\n    step G e1 e1'\n    -> step G (Plus e1 e2) (Plus e1' e2)\n  | StepPlus2 : forall e1 e2 e2',\n    isValue e1\n    -> step G e2 e2'\n    -> step G (Plus e1 e2) (Plus e1 e2')\n\n  | StepMinus : forall n1 n2,\n    step G (Minus (Num n1) (Num n2)) (Num (n1 - n2))\n  | StepMinus1 : forall e1 e2 e1',\n    step G e1 e1'\n    -> step G (Minus e1 e2) (Minus e1' e2)\n  | StepMinus2 : forall e1 e2 e2',\n    isValue e1\n    -> step G e2 e2'\n    -> step G (Minus e1 e2) (Minus e1 e2')\n\n  | StepEq_False : forall n1 n2,\n    step G (Eq (Num n1) (Num n2)) (Bool (nat_eq n1 n2))\n  | StepEq1 : forall e1 e2 e1',\n    step G e1 e1'\n    -> step G (Eq e1 e2) (Eq e1' e2)\n  | StepEq2 : forall e1 e2 e2',\n    isValue e1\n    -> step G e2 e2'\n    -> step G (Eq e1 e2) (Eq e1 e2').\n\nInductive type : Set :=\n  | TyNum : type\n  | TyBool : type.\n\nSection typing.\n  Variable Gtypes : var -> type.\n\n  Inductive hasType : exp -> type -> Prop :=\n    | HT_Num : forall n,\n      hasType (Num n) TyNum\n    | HT_Bool : forall b,\n      hasType (Bool b) TyBool\n\n    | HT_Var : forall x,\n      hasType (Var x) (Gtypes x)\n\n    | HT_Plus : forall e1 e2,\n      hasType e1 TyNum\n      -> hasType e2 TyNum\n      -> hasType (Plus e1 e2) TyNum\n    | HT_Minus : forall e1 e2,\n      hasType e1 TyNum\n      -> hasType e2 TyNum\n      -> hasType (Minus e1 e2) TyNum\n    | HT_Eq : forall e1 e2,\n      hasType e1 TyNum\n      -> hasType e2 TyNum\n      -> hasType (Eq e1 e2) TyBool.\n\n  Variable G : env.\n\n  Hypothesis vars_values : forall x, isValue (G x).\n  Hypothesis vars_typed : forall x, hasType (G x) (Gtypes x).\n\n  Hint Constructors hasType isValue step.\n\n  Ltac ics H := inversion H; clear H; subst.\n\n  Ltac my_inversion :=\n    match goal with\n      | [ H : isValue (Var _) |- _ ] => inversion H\n      | [ H : isValue (Plus _ _) |- _ ] => inversion H\n      | [ H : isValue (Minus _ _) |- _ ] => inversion H\n      | [ H : isValue (Eq _ _) |- _ ] => inversion H\n\n      | [ H : hasType (Num _) _ |- _ ] => ics H\n      | [ H : hasType (Bool _) _ |- _ ] => ics H\n      | [ H : hasType (Var _) _ |- _ ] => ics H\n      | [ H : hasType (Plus _ _) _ |- _ ] => ics H\n      | [ H : hasType (Minus _ _) _ |- _ ] => ics H\n      | [ H : hasType (Eq _ _) _ |- _ ] => ics H\n\n      | [ H : hasType _ TyNum |- _ ] => ics H\n      | [ H : hasType _ TyBool |- _ ] => ics H\n    end.\n\n  Ltac magic_solver := firstorder; repeat (eauto; my_inversion).\n\n  Theorem progress : forall e t,\n    hasType e t\n    -> isValue e\n    \\/ exists e', step G e e'.\n    induction 1; magic_solver.\n  Qed.\n\n  Theorem preservation : forall e e',\n    step G e e'\n    -> forall t, hasType e t\n      -> hasType e' t.\n    induction 1; magic_solver.\n  Qed.\nEnd typing.\n", "meta": {"author": "SatyendraBanjare", "repo": "itp", "sha": "80831ac497c7e000e964587eb0233adb7382ee88", "save_path": "github-repos/coq/SatyendraBanjare-itp", "path": "github-repos/coq/SatyendraBanjare-itp/itp-80831ac497c7e000e964587eb0233adb7382ee88/lecture_codes/Lect6/tsafe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7065529467206404}}
{"text": "Require Import\n  Coq.Classes.RelationClasses Coq.Classes.Morphisms Coq.Program.Program\n  MathClasses.interfaces.universal_algebra MathClasses.interfaces.canonical_names MathClasses.theory.ua_subalgebra.\n\n(* In theory/ua_subalgebra.v we defined closed proper subsets and showed that\nthey yield subalgebras. We now expand on this result and show that they\nalso yield subvarieties (by showing that the laws still hold in the subalgebra). *)\n\nSection contents.\n  Context `{InVariety et A} `{@ClosedSubset et A _ _ P}. (* todo: why so ugly? *)\n\n  Definition Pvars (vars: Vars et (carrier P) nat): Vars et A nat\n    := λ s n, ` (vars s n).\n\n  (* To prove that the laws still hold in the subalgebra, we first prove that evaluation in it\n   is the same as evaluation in the original: *)\n\n  Program Fixpoint heq {o}: op_type (carrier P) o → op_type A o → Prop :=\n    match o with\n    | ne_list.one _ => λ a b, `a = b\n    | ne_list.cons _ _ => λ a b, ∀ u, heq (a u) (b u)\n    end.\n\n  Instance heq_proper: Proper ((=) ==> (=) ==> iff) (@heq o).\n  Proof with intuition.\n   intros o x y U x0 y0 K.\n   induction o; simpl in *.\n    destruct x, y.\n    change (x = x1) in U.\n    simpl in *.\n    split; intro.\n     transitivity x...\n     transitivity x0...\n    transitivity x1...\n    transitivity y0...\n   assert (∀ u, x u = y u). intros. apply U...\n   split; repeat intro.\n    apply -> (IHo (x u) (y u) (H1 u) (x0 (proj1_sig u)))...\n    apply K...\n   apply <- (IHo (x u) (y u) (H1 u) (x0 (proj1_sig u)))...\n   apply K...\n  Qed.\n\n  Lemma heq_eval vars {o} (t: T et o): heq (eval et vars t) (eval et (Pvars vars) t).\n  Proof with intuition.\n   induction t; simpl...\n     unfold Pvars...\n    simpl in IHt1.\n    generalize (IHt1 (eval et vars t3)). clear IHt1.\n    apply heq_proper.\n     pose proof (@eval_proper et (carrier P) _ _ _ nat (ne_list.cons y t1)).\n     apply H1; try intro...\n    pose proof (@eval_proper et A _ _ _ nat (ne_list.cons y t1)).\n    apply H1...\n    unfold heq in IHt2. (* todo: this wasn't needed in a previous Coq version *)\n    rewrite IHt2.\n    apply (@eval_proper et A _ _ _ nat (ne_list.one y))...\n   unfold impl, algebra_op.\n   generalize (subset_closed P o).\n   unfold algebra_op.\n   generalize (AlgebraOps0 o).\n   intros.\n   induction (et o); simpl in *...\n  Qed.\n\n  Lemma heq_eval_const vars {o} (t: T et (ne_list.one o)): ` (eval et vars t) = eval et (Pvars vars) t.\n  Proof. apply (heq_eval vars t). Qed.\n    (* todo: this specialization wasn't needed in a previous Coq version *)\n\n  Lemma laws s: et_laws et s → ∀ vars: ∀ a, nat → carrier P a, eval_stmt et vars s.\n  Proof with intuition.\n   intros.\n   generalize (@variety_laws et A _ _ _ s H1 (Pvars vars)). clear H1.\n   destruct s as [x [? [t t0]]].\n   induction x as [A| [x1 [t1 t2]]]; simpl in *; intros.\n    unfold equiv, sig_equiv.\n    rewrite (heq_eval_const vars t).\n    rewrite (heq_eval_const vars t0)...\n   apply IHx, H1.\n   rewrite <- (heq_eval_const vars t1).\n   rewrite <- (heq_eval_const vars t2)...\n  Qed.\n\n  (* Which gives us our variety: *)\n\n  Global Instance: InVariety et (carrier P) := { variety_laws := laws }.\n\nEnd contents.\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/math-classes/theory/ua_subvariety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7065529438676331}}
{"text": "Require Import Coq.Arith.Div2.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.ZArith.ZArith.\nRequire Import bbv.N_Z_nat_conversions.\nRequire Export bbv.Nomega.\n\nSet Implicit Arguments.\n\nFixpoint mod2 (n : nat) : bool :=\n  match n with\n    | 0 => false\n    | 1 => true\n    | S (S n') => mod2 n'\n  end.\n\nLtac rethink :=\n  match goal with\n    | [ H : ?f ?n = _ |- ?f ?m = _ ] => replace m with n; simpl; auto\n  end.\n\nTheorem mod2_S_double : forall n, mod2 (S (2 * n)) = true.\n  induction n; simpl; intuition; rethink.\nQed.\n\nTheorem mod2_double : forall n, mod2 (2 * n) = false.\n  induction n; simpl; intuition; rewrite <- plus_n_Sm; rethink.\nQed.\n\nTheorem div2_double : forall n, div2 (2 * n) = n.\n  induction n; simpl; intuition; rewrite <- plus_n_Sm; f_equal; rethink.\nQed.\n\nTheorem div2_S_double : forall n, div2 (S (2 * n)) = n.\n  induction n; simpl; intuition; f_equal; rethink.\nQed.\n\nNotation pow2 := (Nat.pow 2).\n\nFixpoint Npow2 (n : nat) : N :=\n  match n with\n    | O => 1\n    | S n' => 2 * Npow2 n'\n  end%N.\n\nTheorem untimes2 : forall n, n + (n + 0) = 2 * n.\n  auto.\nQed.\n\nSection strong.\n  Variable P : nat -> Prop.\n\n  Hypothesis PH : forall n, (forall m, m < n -> P m) -> P n.\n\n  Lemma strong' : forall n m, m <= n -> P m.\n    induction n; simpl; intuition; apply PH; intuition.\n    elimtype False; omega.\n  Qed.\n\n  Theorem strong : forall n, P n.\n    intros; eapply strong'; eauto.\n  Qed.\nEnd strong.\n\nTheorem div2_odd : forall n,\n  mod2 n = true\n  -> n = S (2 * div2 n).\n  induction n as [n] using strong; simpl; intuition.\n\n  destruct n as [|n]; simpl in *; intuition.\n    discriminate.\n  destruct n as [|n]; simpl in *; intuition.\n  do 2 f_equal.\n  replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto.\nQed.\n\nTheorem div2_even : forall n,\n  mod2 n = false\n  -> n = 2 * div2 n.\n  induction n as [n] using strong; simpl; intuition.\n\n  destruct n as [|n]; simpl in *; intuition.\n  destruct n as [|n]; simpl in *; intuition.\n    discriminate.\n  f_equal.\n  replace (div2 n + S (div2 n + 0)) with (S (div2 n + (div2 n + 0))); auto.\nQed.\n\nTheorem drop_mod2 : forall n k,\n  2 * k <= n\n  -> mod2 (n - 2 * k) = mod2 n.\n  induction n as [n] using strong; intros.\n\n  do 2 (destruct n; simpl in *; repeat rewrite untimes2 in *; intuition).\n\n  destruct k; simpl in *; intuition.\n\n  destruct k; simpl; intuition.\n  rewrite <- plus_n_Sm.\n  repeat rewrite untimes2 in *.\n  simpl; auto.\n  apply H; omega.\nQed.\n\nTheorem div2_minus_2 : forall n k,\n  2 * k <= n\n  -> div2 (n - 2 * k) = div2 n - k.\n  induction n as [n] using strong; intros.\n\n  do 2 (destruct n; simpl in *; intuition; repeat rewrite untimes2 in *).\n  destruct k; simpl in *; intuition.\n\n  destruct k; simpl in *; intuition.\n  rewrite <- plus_n_Sm.\n  apply H; omega.\nQed.\n\nTheorem div2_bound : forall k n,\n  2 * k <= n\n  -> k <= div2 n.\n  intros ? n H; case_eq (mod2 n); intro Heq.\n\n  rewrite (div2_odd _ Heq) in H.\n  omega.\n\n  rewrite (div2_even _ Heq) in H.\n  omega.\nQed.\n\nLemma two_times_div2_bound: forall n, 2 * Nat.div2 n <= n.\nProof.\n  eapply strong. intros n IH.\n  destruct n.\n  - constructor.\n  - destruct n.\n    + simpl. constructor. constructor.\n    + simpl (Nat.div2 (S (S n))).\n      specialize (IH n). omega.\nQed.\n\nLemma div2_compat_lt_l: forall a b, b < 2 * a -> Nat.div2 b < a.\nProof.\n  induction a; intros.\n  - omega.\n  - destruct b.\n    + simpl. omega.\n    + destruct b.\n      * simpl. omega.\n      * simpl. apply lt_n_S. apply IHa. omega.\nQed.\n\n(* otherwise b is made implicit, while a isn't, which is weird *)\nArguments div2_compat_lt_l {_} {_} _.\n\nLemma pow2_add_mul: forall a b,\n  pow2 (a + b) = (pow2 a) * (pow2 b).\nProof.\n  induction a; destruct b; firstorder; simpl.\n  repeat rewrite Nat.add_0_r.\n  rewrite Nat.mul_1_r; auto.\n  repeat rewrite Nat.add_0_r.\n  rewrite IHa.\n  simpl.\n  repeat rewrite Nat.add_0_r.\n  rewrite Nat.mul_add_distr_r; auto.\nQed.\n\nLemma mult_pow2_bound: forall a b x y,\n  x < pow2 a -> y < pow2 b -> x * y < pow2 (a + b).\nProof.\n  intros.\n  rewrite pow2_add_mul.\n  apply Nat.mul_lt_mono_nonneg; omega.\nQed.\n\nLemma mult_pow2_bound_ex: forall a c x y,\n  x < pow2 a -> y < pow2 (c - a) -> c >= a -> x * y < pow2 c.\nProof.\n  intros.\n  replace c with (a + (c - a)) by omega.\n  apply mult_pow2_bound; auto.\nQed.\n\nLemma lt_mul_mono' : forall c a b,\n  a < b -> a < b * (S c).\nProof.\n  induction c; intros.\n  rewrite Nat.mul_1_r; auto.\n  rewrite Nat.mul_succ_r.\n  apply lt_plus_trans.\n  apply IHc; auto.\nQed.\n\nLemma lt_mul_mono : forall a b c,\n  c <> 0 -> a < b -> a < b * c.\nProof.\n  intros.\n  replace c with (S (c - 1)) by omega.\n  apply lt_mul_mono'; auto.\nQed.\n\nLemma zero_lt_pow2 : forall sz, 0 < pow2 sz.\nProof.\n  induction sz; simpl; omega.\nQed.\n\nLemma one_lt_pow2:\n  forall n,\n    1 < pow2 (S n).\nProof.\n  intros.\n  induction n.\n  simpl; omega.\n  remember (S n); simpl.\n  omega.\nQed.\n\nLemma one_le_pow2 : forall sz, 1 <= pow2 sz.\nProof.\n  intros. pose proof (zero_lt_pow2 sz). omega.\nQed.\n\nLemma pow2_ne_zero: forall n, pow2 n <> 0.\nProof.\n  intros.\n  pose proof (zero_lt_pow2 n).\n  omega.\nQed.\n\nLemma mul2_add : forall n, n * 2 = n + n.\nProof.\n  induction n; firstorder.\nQed.\n\nLemma pow2_le_S : forall sz, (pow2 sz) + 1 <= pow2 (sz + 1).\nProof.\n  induction sz; simpl; auto.\n  repeat rewrite Nat.add_0_r.\n  rewrite pow2_add_mul.\n  repeat rewrite mul2_add.\n  pose proof (zero_lt_pow2 sz).\n  omega.\nQed.\n\nLemma pow2_bound_mono: forall a b x,\n  x < pow2 a -> a <= b -> x < pow2 b.\nProof.\n  intros.\n  replace b with (a + (b - a)) by omega.\n  rewrite pow2_add_mul.\n  apply lt_mul_mono; auto.\n  pose proof (zero_lt_pow2 (b - a)).\n  omega.\nQed.\n\nLemma pow2_inc : forall n m,\n  0 < n -> n < m ->\n    pow2 n < pow2 m.\nProof.\n  intros.\n  generalize dependent n; intros.\n  induction m; simpl.\n  intros. inversion H0.\n  unfold lt in H0.\n  rewrite Nat.add_0_r.\n  inversion H0.\n  apply Nat.lt_add_pos_r.\n  apply zero_lt_pow2.\n  apply Nat.lt_trans with (pow2 m).\n  apply IHm.\n  exact H2.\n  apply Nat.lt_add_pos_r.\n  apply zero_lt_pow2.\nQed.\n\nLemma pow2_S: forall x, pow2 (S x) = 2 * pow2 x.\nProof. intros. reflexivity. Qed.\n\nLemma mod2_S_S : forall n,\n  mod2 (S (S n)) = mod2 n.\nProof.\n  intros.\n  destruct n; auto; destruct n; auto.\nQed.\n\nLemma mod2_S_not : forall n,\n  mod2 (S n) = if (mod2 n) then false else true.\nProof.\n  intros.\n  induction n; auto.\n  rewrite mod2_S_S.\n  destruct (mod2 n); replace (mod2 (S n)); auto.\nQed.\n\nLemma mod2_S_eq : forall n k,\n  mod2 n = mod2 k ->\n  mod2 (S n) = mod2 (S k).\nProof.\n  intros.\n  do 2 rewrite mod2_S_not.\n  rewrite H.\n  auto.\nQed.\n\nTheorem drop_mod2_add : forall n k,\n  mod2 (n + 2 * k) = mod2 n.\nProof.\n  intros.\n  induction n.\n  simpl.\n  rewrite Nat.add_0_r.\n  replace (k + k) with (2 * k) by omega.\n  apply mod2_double.\n  replace (S n + 2 * k) with (S (n + 2 * k)) by omega.\n  apply mod2_S_eq; auto.\nQed.\n\nLemma mod2sub: forall a b,\n  b <= a ->\n  mod2 (a - b) = xorb (mod2 a) (mod2 b).\nProof.\n  intros. remember (a - b) as c. revert dependent b. revert a. revert c.\n  change (forall c,\n    (fun c => forall a b, b <= a -> c = a - b -> mod2 c = xorb (mod2 a) (mod2 b)) c).\n  apply strong.\n  intros c IH a b AB N.\n  destruct c.\n  - assert (a=b) by omega. subst. rewrite Bool.xorb_nilpotent. reflexivity.\n  - destruct c.\n    + assert (a = S b) by omega. subst a. simpl (mod2 1). rewrite mod2_S_not.\n      destruct (mod2 b); reflexivity.\n    + destruct a; [omega|].\n      destruct a; [omega|].\n      simpl.\n      apply IH; omega.\nQed.\n\nTheorem mod2_pow2_twice: forall n,\n  mod2 (pow2 n + (pow2 n + 0)) = false.\nProof.\n  intros.\n  replace (pow2 n + (pow2 n + 0)) with (2 * pow2 n) by omega.\n  apply mod2_double.\nQed.\n\nTheorem div2_plus_2 : forall n k,\n  div2 (n + 2 * k) = div2 n + k.\nProof.\n  induction n; intros.\n  simpl.\n  rewrite Nat.add_0_r.\n  replace (k + k) with (2 * k) by omega.\n  apply div2_double.\n  replace (S n + 2 * k) with (S (n + 2 * k)) by omega.\n  destruct (Even.even_or_odd n).\n  - rewrite <- even_div2.\n    rewrite <- even_div2 by auto.\n    apply IHn.\n    apply Even.even_even_plus; auto.\n    apply Even.even_mult_l; repeat constructor.\n\n  - rewrite <- odd_div2.\n    rewrite <- odd_div2 by auto.\n    rewrite IHn.\n    omega.\n    apply Even.odd_plus_l; auto.\n    apply Even.even_mult_l; repeat constructor.\nQed.\n\nLemma pred_add:\n  forall n, n <> 0 -> pred n + 1 = n.\nProof.\n  intros; rewrite pred_of_minus; omega.\nQed.\n\nLemma pow2_zero: forall sz, (pow2 sz > 0)%nat.\nProof.\n  induction sz; simpl; auto; omega.\nQed.\n\nSection omega_compat.\n\nLtac omega ::= lia.\n\nTheorem Npow2_nat : forall n, nat_of_N (Npow2 n) = pow2 n.\n  induction n as [|n IHn]; simpl; intuition.\n  rewrite <- IHn; clear IHn.\n  case_eq (Npow2 n); intuition.\nQed.\n\nEnd omega_compat.\n\nTheorem pow2_N : forall n, Npow2 n = N.of_nat (pow2 n).\nProof.\n  intro n. apply nat_of_N_eq. rewrite Nat2N.id. apply Npow2_nat.\nQed.\n\nLemma Z_of_N_Npow2: forall n, Z.of_N (Npow2 n) = (2 ^ Z.of_nat n)%Z.\nProof.\n  intros.\n  rewrite pow2_N.\n  rewrite nat_N_Z.\n  rewrite Nat2Z.inj_pow.\n  reflexivity.\nQed.\n\nLemma pow2_S_z:\n  forall n, Z.of_nat (pow2 (S n)) = (2 * Z.of_nat (pow2 n))%Z.\nProof.\n  intros.\n  replace (2 * Z.of_nat (pow2 n))%Z with\n      (Z.of_nat (pow2 n) + Z.of_nat (pow2 n))%Z by omega.\n  simpl.\n  repeat rewrite Nat2Z.inj_add.\n  ring.\nQed.\n\nLemma pow2_le:\n  forall n m, (n <= m)%nat -> (pow2 n <= pow2 m)%nat.\nProof.\n  intros.\n  assert (exists s, n + s = m) by (exists (m - n); omega).\n  destruct H0; subst.\n  rewrite pow2_add_mul.\n  pose proof (pow2_zero x).\n  replace (pow2 n) with (pow2 n * 1) at 1 by omega.\n  apply mult_le_compat_l.\n  omega.\nQed.\n\nLemma Zabs_of_nat:\n  forall n, Z.abs (Z.of_nat n) = Z.of_nat n.\nProof.\n  unfold Z.of_nat; intros.\n  destruct n; auto.\nQed.\n\nLemma Npow2_not_zero:\n  forall n, Npow2 n <> 0%N.\nProof.\n  induction n; simpl; intros; [discriminate|].\n  destruct (Npow2 n); auto.\n  discriminate.\nQed.\n\nLemma Npow2_S:\n  forall n, Npow2 (S n) = (Npow2 n + Npow2 n)%N.\nProof.\n  simpl; intros.\n  destruct (Npow2 n); auto.\n  rewrite <-Pos.add_diag.\n  reflexivity.\nQed.\n\nLemma Npow2_pos: forall a,\n    (0 < Npow2 a)%N.\nProof.\n  intros.\n  destruct (Npow2 a) eqn: E.\n  - exfalso. apply (Npow2_not_zero a). assumption.\n  - constructor.\nQed.\n\nLemma minus_minus: forall a b c,\n  c <= b <= a ->\n  a - (b - c) = a - b + c.\nProof. intros. omega. Qed.\n\nLemma even_odd_destruct: forall n,\n  (exists a, n = 2 * a) \\/ (exists a, n = 2 * a + 1).\nProof.\n  induction n.\n  - left. exists 0. reflexivity.\n  - destruct IHn as [[a E] | [a E]].\n    + right. exists a. omega.\n    + left. exists (S a). omega.\nQed.\n\nLemma mul_div_undo: forall i c,\n    c <> 0 ->\n    c * i / c = i.\nProof.\n  intros.\n  pose proof (Nat.div_mul_cancel_l i 1 c) as P.\n  rewrite Nat.div_1_r in P.\n  rewrite Nat.mul_1_r in P.\n  apply P; auto.\nQed.\n\nLemma mod_add_r: forall a b,\n    b <> 0 ->\n    (a + b) mod b = a mod b.\nProof.\n  intros. rewrite <- Nat.add_mod_idemp_r by omega.\n  rewrite Nat.mod_same by omega.\n  rewrite Nat.add_0_r.\n  reflexivity.\nQed.\n\nLemma mod2_cases: forall (n: nat), n mod 2 = 0 \\/ n mod 2 = 1.\nProof.\n  intros.\n  assert (n mod 2 < 2). {\n    apply Nat.mod_upper_bound. congruence.\n  }\n  omega.\nQed.\n\nLemma div_mul_undo: forall a b,\n    b <> 0 ->\n    a mod b = 0 ->\n    a / b * b = a.\nProof.\n  intros.\n  pose proof Nat.div_mul_cancel_l as A. specialize (A a 1 b).\n  replace (b * 1) with b in A by omega.\n  rewrite Nat.div_1_r in A.\n  rewrite mult_comm.\n  rewrite <- Nat.divide_div_mul_exact; try assumption.\n  - apply A; congruence.\n  - apply Nat.mod_divide; assumption.\nQed.\n\nLemma Smod2_1: forall k, S k mod 2 = 1 -> k mod 2 = 0.\nProof.\n  intros k C.\n  change (S k) with (1 + k) in C.\n  rewrite Nat.add_mod in C by congruence.\n  pose proof (Nat.mod_upper_bound k 2).\n  assert (k mod 2 = 0 \\/ k mod 2 = 1) as E by omega.\n  destruct E as [E | E]; [assumption|].\n  rewrite E in C. simpl in C. discriminate.\nQed.\n\nLemma mod_0_r: forall (m: nat),\n    m mod 0 = 0.\nProof.\n  intros. reflexivity.\nQed.\n\nLemma sub_mod_0: forall (a b m: nat),\n    a mod m = 0 ->\n    b mod m = 0 ->\n    (a - b) mod m = 0.\nProof.\n  intros. assert (m = 0 \\/ m <> 0) as C by omega. destruct C as [C | C].\n  - subst. apply mod_0_r.\n  - assert (a - b = 0 \\/ b < a) as D by omega. destruct D as [D | D].\n    + rewrite D. apply Nat.mod_0_l. assumption.\n    + apply Nat2Z.inj. simpl.\n      rewrite Zdiv.mod_Zmod by assumption.\n      rewrite Nat2Z.inj_sub by omega.\n      rewrite Zdiv.Zminus_mod.\n      rewrite <-! Zdiv.mod_Zmod by assumption.\n      rewrite H. rewrite H0.\n      apply Z.mod_0_l.\n      omega.\nQed.\n\nLemma mul_div_exact: forall (a b: nat),\n    b <> 0 ->\n    a mod b = 0 ->\n    b * (a / b) = a.\nProof.\n  intros. edestruct Nat.div_exact as [_ P]; [eassumption|].\n  specialize (P H0). symmetry. exact P.\nQed.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/bbv/theories/NatLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7065529343421064}}
{"text": "Require Import Coq.Classes.Morphisms Coq.Program.Program Coq.Unicode.Utf8.\n\n(* First, two ways to do quoting in the naive scenario without\n holes/variables in the expression: *)\n\nModule simple.\n  (* An example term language and evaluation: *)\n  Inductive Expr := Plus (a b: Expr) | Mult (a b: Expr) | Zero | One.\n\n  Fixpoint eval (e: Expr): nat :=\n    match e with\n    | Plus a b => eval a + eval b\n    | Mult a b => eval a * eval b\n    | Zero => 0\n    | One => 1\n    end.\n\n  (* First up is the simplest approach I can think of. *)\n  Module approach_A.\n    Class Quote (n: nat) := quote: Expr.\n\n    Implicit Arguments quote [[Quote]].\n\n    Section instances.\n\n      Context n m `{Quote n} `{Quote m}.\n\n      Global Instance: Quote 0 := Zero.\n      Global Instance: Quote 1 := One.\n      Global Instance: Quote (n + m) := Plus (quote n) (quote m).\n      Global Instance: Quote (n * m) := Mult (quote n) (quote m).\n\n    End instances.\n\n    Ltac do_quote :=\n      match goal with\n      |- (?a = ?b) => change (eval (quote a) = eval (quote b))\n      end.\n\n    Lemma example: (1 + 0 + 1) * (1 + 1) = (1 + 1) + (1 + 1).\n     do_quote.\n    Admitted.\n  End approach_A.\n\n  (* This works, but there's something unsatisfying about this quotation, because\n  the actual Quote instances are not validated until we get to the [change] tactic,\n  which validates the quotation by requiring convertibility.\n\n  Next, we show an alternative implementation where the Quote instances\n  are all proved locally correct at their definition: *)\n\n  Module approach_B.\n    Class Quote (n: nat) := { quote: Expr; eval_quote: n = eval quote  }.\n\n    Implicit Arguments quote [[Quote]].\n    Implicit Arguments eval_quote [[Quote]].\n\n    Section instances.\n\n      Context n m `{Quote n} `{Quote m}.\n\n      Global Program Instance: Quote 0 := { quote := Zero }.\n      Global Program Instance: Quote 1 := { quote := One }.\n\n      Global Instance: Quote (n + m) := { quote := Plus (quote n) (quote m) }.\n      Proof. simpl. do 2 rewrite <- eval_quote. reflexivity. Qed.\n\n      Global Instance: Quote (n * m) := { quote := Mult (quote n) (quote m) }.\n      Proof. simpl. do 2 rewrite <- eval_quote. reflexivity. Qed.\n\n    End instances.\n\n    Lemma do_quote {n m} `{Quote n} `{Quote m}: eval (quote n) = eval (quote m) → n = m.\n    Proof. intros. rewrite (eval_quote n), (eval_quote m). assumption. Qed.\n\n    Lemma example: (1 + 0 + 1) * (1 + 1) = (1 + 1) + (1 + 1).\n     apply do_quote.\n    Admitted.\n  End approach_B.\nEnd simple.\n\n(* So far so good, but the variable-less scenario isn't really interesting. We now rework approach B\n to include quotation of holes/variables, including recognition of syntactically identical ones. *)\n\nModule with_vars.\n(* Some random utilities: *)\n\nLemma sum_assoc {A B C}: (A+B)+C → A+(B+C). intuition. Defined.\nLemma bla {A B C}: (A+B) → A+(B+C). intuition. Defined.\nLemma monkey {A B}: False + A → A + B. intuition. Defined.\n\nSection obvious.\n  Class Obvious (T: Type) := obvious: T.\n\n  Context (A B C: Type).\n\n  Global Instance: Obvious (A → A) := id.\n  Global Instance: Obvious (False → A) := False_rect _.\n  Global Instance: Obvious (A → A + B) := inl.\n  Global Instance: Obvious (A → B + A) := inr.\n  Global Instance obvious_sum_src  `{Obvious (A → C)} `{Obvious (B → C)}: Obvious (A+B → C). repeat intro. intuition. Defined.\n  Global Instance obvious_sum_dst_l `{Obvious (A → B)}: Obvious (A → B+C). repeat intro. intuition. Defined.\n  Global Instance obvious_sum_dst_r `{Obvious (A → B)}: Obvious (A → C+B). repeat intro. intuition. Defined.\nEnd obvious.\n\n(* Again our example term language, this time without plus/one (they're boring), but with Var\n added: *)\n\nInductive Expr (V: Type) := Mult (a b: Expr V) | Zero | Var (v: V).\n\nImplicit Arguments Var [[V]].\nImplicit Arguments Zero [[V]].\nImplicit Arguments Mult [[V]].\n\n(*\nRequire Import monads canonical_names.\n\nInstance: MonadReturn Expr := fun _ => Var.\n\nInstance expr_bind: MonadBind Expr := fun A B =>\n  fix F (m: Expr A) (f: A → Expr B): Expr B :=\n    match m with\n    | Zero => Zero\n    | Mult x y => Mult (F x f) (F y f)\n    | Var v => f v\n    end.\n\nSection eqs.\n\n  Context `{e: Equiv A} `{Equivalence _ e}.\n\n  Global Instance expr_eq: Equiv (Expr A) :=\n    fix F (x y: Expr A) :=\n      match x, y with\n      | Var v, Var w => v = w\n      | Mult v w, Mult p q => F v p ∧ F w q\n      | Zero, Zero => True\n      | _, _ => False\n      end.\n\n  Instance: Reflexive expr_eq.\n  Proof. intro. induction x; simpl; intuition. Qed.\n\n  Instance: Symmetric expr_eq.\n  Proof. intro. induction x; destruct y; simpl in *; intuition. Qed.\n\n  Instance: Transitive expr_eq.\n  Admitted.\n\n  Global Instance expr_equivalence: Equivalence expr_eq.\n\nEnd eqs.\n\nInstance: ∀ `{Equiv A}, Proper ((=) ==> (=)) (ret Expr).\n repeat intro.\n assumption.\nQed.\n\nInstance bind_proper: ∀ `{Equiv A} `{Equiv B},\n Proper ((=) ==> pointwise_relation A (=) ==> (=)) (@expr_bind A B).\nProof.\n intros A H B H0 x y E.\n(*\n induction x.\n  destruct y; intuition.\n  intros f g E'.\n  simpl.\n  red.\n  simpl.\n  split.\n   red in E.\n   simpl in E.\n\n   apply IHx2.\n\n  simpl in *.\n\n unfold expr_bind.\n\n simpl.\n*)\nAdmitted.\n\n\nInstance: Monad Expr.\n  *)\n\n\n\n(* The expression type is parameterized over the set of variable indices. Hence, we diverge\n from Claudio, who uses nat indices for variables, thereby introducing bounds problems and\n dummy variables and other nastiness. *)\n\n(* An expression is only meaningful in the context of a variable assignment: *)\n\nDefinition Value := nat.\nDefinition Vars V := V → Value.\n\nFixpoint eval {V} (vs: Vars V) (e: Expr V): Value :=\n  match e with\n  | Zero => 0\n  | Mult a b => eval vs a * eval vs b\n  | Var v => vs v\n  end.\n\nInstance eval_proper V: Proper (pointwise_relation _ eq ==> eq ==> eq) (@eval V).\nProof.\n repeat intro. subst.\n induction y0; simpl.\n   congruence.\n  reflexivity.\n apply H.\nQed.\n\n(* Some simple combinators for variable packs: *)\n\nDefinition novars: Vars False := False_rect _.\nDefinition singlevar (x: Value): Vars unit := fun _ => x.\nDefinition merge {A B} (a: Vars A) (b: Vars B): Vars (A+B) :=\n  fun i => match i with inl j => a j | inr j => b j end.\n\n(* These last two combinators are the \"constructors\" of an implicitly defined subset of\n Gallina terms (representing Claudio's \"heaps\") for which we implement syntactic\n lookup with type classes: *)\n\nSection Lookup.\n  (* Given a heap and value, Lookup instances give the value's index in the heap: *)\n\n  Class Lookup {A} (x: Value) (f: Vars A) := { lookup: A; lookup_correct: f lookup = x }.\n\n  Global Implicit Arguments lookup [[A] [Lookup]].\n\n  Context (x: Value) {A B} (va: Vars A) (vb: Vars B).\n\n  (* If the heap is a merge of two heaps and we can find the value's index in the left heap,\n   we can access it by indexing the merged heap: *)\n\n  Global Instance lookup_left `{!Lookup x va}: Lookup x (merge va vb)\n    := { lookup := inl (lookup x va) }.\n  Proof. apply lookup_correct. Defined.\n\n  (* And vice-versa: *)\n\n  Global Instance lookup_right `{!Lookup x vb}: Lookup x (merge va vb)\n    := { lookup := inr (lookup x vb) }.\n  Proof. apply lookup_correct. Defined.\n\n  (* If the heap is just a singlevar, we can easily index it. *)\n\n  Global Program Instance: Lookup x (singlevar x) := { lookup := tt }.\n\n  (* Note that we don't have any fallback/default instances at this point. We /will/ introduce\n  such an instance for our Quote class later on, which will add a new variable to the heap\n  if another Quote instance that relies on Lookup into the \"current\" heap fails. *)\nEnd Lookup.\n\n(* One useful operation we need before we get to Quote relates to variables and expression\n evaluation. As its name suggests, map_var maps an expression's variable indices. *)\n\nDefinition map_var {V W: Type} (f: V → W): Expr V → Expr W :=\n  fix F (e: Expr V): Expr W :=\n    match e with\n    | Mult a b => Mult (F a) (F b)\n    | Zero => Zero\n    | Var v => Var (f v)\n    end.\n\n(* An obvious identity is: *)\n\nLemma eval_map_var {V W} (f: V → W) v e:\n  eval v (map_var f e) = eval (v ∘ f) e.\nProof.\n induction e; simpl; try reflexivity.\n rewrite IHe1, IHe2.\n reflexivity.\nQed.\n\n(* Finally, Quote itself: *)\n\nSection Quote.\n  (* In Quote, the idea is that V, l, and n are all \"input\" variables, while V' and r are \"output\"\n  variables (in the sense that we will rely on unification to generate them. V and l represent\n  the \"current heap\", n represents the value we want to quote, and V' and r' represent the\n  heap of newly encountered variables during the quotation.\n    This explains the type of quote: it is an expression that refers either to variables from\n  the old heap, or to newly encountered variables.\n    eval_quote is the usual correctness property, which now merges the two heaps. *)\n\n  Class Quote {V} (l: Vars V) (n: Value) {V'} (r: Vars V') :=\n    { quote: Expr (V + V')\n    ; eval_quote: @eval (V+V') (merge l r) quote = n }.\n\n  Implicit Arguments quote [[V] [l] [V'] [r] [Quote]].\n\n  (* Our first instance for Zero is easy. The \"novars\" in the result type reflects the fact that no new\n   variables are encountered. The correctness proof is easy enough for Program. *)\n\n  Global Program Instance quote_zero V (v: Vars V): Quote v 0 novars := { quote := Zero }.\n\n  (* The instance for multiplication is a bit more complex. The first line is just boring\n   variable declarations. The second line is important. \"Quote x y z\" must be read as\n   \"quoting y with existing heap x generates new heap z\", so the second line\n   basically just shuffles heaps around.\n     The third line has some ugly map_var's in it because the heap shuffling must be reflected\n   in the variable indices, but apart from that it's just constructing a Mult\n   term with quoted subterms. *)\n\n  Global Program Instance quote_mult V (v: Vars V) n V' (v': Vars V') m V'' (v'': Vars V'')\n    `{!Quote v n v'} `{!Quote (merge v v') m v''}: Quote v (n * m) (merge v' v'') :=\n      { quote := Mult (map_var bla (quote n)) (map_var sum_assoc (quote m)) }.\n\n  Next Obligation. Proof with auto.\n   destruct Quote0, Quote1.\n   subst. simpl.\n   do 2 rewrite eval_map_var.\n   f_equal; apply eval_proper; auto; intro; intuition.\n  Qed.\n\n  (* Now follows the instance where we recognize values that are already in the heap. This\n   is expressed by the Lookup requirement, which will only be fulfilled if the Lookup instances\n   defined above can find the value in the heap. The novars in the [Quote v x novars] result\n   reflects that this quotation does not generate new variables. *)\n\n  Global Program Instance quote_old_var V (v: Vars V) x {i: Lookup x v}:\n    Quote v x novars | 8 := { quote := Var (inl (lookup x v)) }.\n  Next Obligation. Proof. apply lookup_correct. Qed.\n\n  (* Finally, the instance for new variables. We give this lower priority so that it is only\n   used if Lookup fails. *)\n\n  Global Program Instance quote_new_var V (v: Vars V) x: Quote v x (singlevar x) | 9\n    := { quote := Var (inr tt) }.\nEnd Quote.\n\n(* Note: Explicitly using dynamically configured variable index sets instead of plain lists\n not only removes the need for an awkward dummy value to cope with out-of-bounds\n accesses, but also means that we can prove the correctness class fields in\n Lookup/Quote without having to take the potential for out-of-bounds indexing into\n account (which would be a nightmare). *)\n\n(* When quoting something from scratch we will want to start with an empty heap.\n To avoid having to mention this, we define quote' and eval_quote': *)\n\nDefinition quote': ∀ x {V'} {v: Vars V'} {d: Quote novars x v}, Expr _ := @quote _ _.\n\nDefinition eval_quote': ∀ x {V'} {v: Vars V'} {d: Quote novars x v},\n  eval (merge novars v) quote = x\n    := @eval_quote _ _ .\n\nImplicit Arguments quote' [[V'] [v] [d]].\nImplicit Arguments eval_quote' [[V'] [v] [d]].\n\n(* Time for some tests! *)\n\nGoal ∀ x y (P: Value → Prop), P ((x * y) * (x * 0)).\n  intros.\n  rewrite <- (eval_quote' _).\n    (* turns the goal into\n         P (eval some_variable_pack_composed_from_combinators quote)\n    *)\n  simpl quote.\nAdmitted.\n\n(* We can also inspect quotations more directly: *)\n\nSection inspect.\n  Variables x y: Value.\n  (* Eval compute in quote' ((x * y) * (x * 0)). *)\n    (* = Mult (Mult (Var (inr (inl (inl ())))) (Var (inr (inl (inr ())))))\n           (Mult (Var (inr (inl (inl ())))) Zero)\n       : Expr (False + (() + () + (False + False))) *)\n\n  (* The second occurrence of (Var (inr (inl (inl ())))) means\n   the quoting has successfully noticed that it's the same\n   expression. *)\n\n  (* The two units in the generated variable index type reflect the\n   fact that the expression contains two variables. *)\n\n  (* I think adding some additional Quote instances might let us\n   get rid of the False's, but at the moment I see little reason to. *)\nEnd inspect.\n\n(* If we want to quote an equation between two expressions we should make\n sure that the both sides refer to the same variable pack, and for that we write a\n little utility function. It does the same kind of shuffling that the mult\n Quote instance did. *)\n\nLemma quote_equality {V} {v: Vars V} {V'} {v': Vars V'} (l r: Value) `{!Quote novars l v} `{!Quote v r v'}:\n  let heap := (merge v v') in\n  eval heap (map_var monkey quote) = eval heap quote → l = r.\nProof with intuition.\n destruct Quote0 as [lq []].\n destruct Quote1 as [rq []].\n intros heap H.\n subst heap. simpl in H.\n rewrite <- H, eval_map_var.\n apply eval_proper... intro...\nQed.\n\nGoal ∀ x y, x * y = y * x.\n intros.\n apply (quote_equality _ _).\n simpl quote.\n unfold map_var, monkey, sum_rect.\nAdmitted.\n\nEnd with_vars.\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/math-classes/quote/classquote.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7065529308998957}}
{"text": "Require Export Families.\nRequire Export Image.\nRequire Import ImageImplicit.\n\nSet Implicit Arguments.\n\nSection IndexedFamilies.\n\nVariable A T:Type.\nDefinition IndexedFamily := A -> Ensemble T.\nVariable F:IndexedFamily.\n\nInductive IndexedUnion : Ensemble T :=\n  | indexed_union_intro: forall (a:A) (x:T),\n    In (F a) x -> In IndexedUnion x.\n\nInductive IndexedIntersection : Ensemble T :=\n  | indexed_intersection_intro: forall (x:T),\n    (forall a:A, In (F a) x) -> In IndexedIntersection x.\n\nEnd IndexedFamilies.\n\nSection IndexedFamilyFacts.\n\n(* unions and intersections over subsets of the index set *)\nLemma sub_indexed_union: forall {A B T:Type} (f:A->B)\n  (F:IndexedFamily B T),\n  let subF := (fun a:A => F (f a)) in\n    Included (IndexedUnion subF) (IndexedUnion F).\nProof.\nunfold Included.\nintros.\ndestruct H.\napply indexed_union_intro with (f a).\nassumption.\nQed.\n\nLemma sub_indexed_intersection: forall {A B T:Type} (f:A->B)\n  (F:IndexedFamily B T),\n  let subF := (fun a:A => F (f a)) in\n    Included (IndexedIntersection F) (IndexedIntersection subF).\nProof.\nunfold Included.\nintros.\nconstructor.\ndestruct H.\nintro.\napply H.\nQed.\n\nLemma empty_indexed_intersection: forall {T:Type}\n  (F:IndexedFamily False T),\n  IndexedIntersection F = Full_set.\nProof.\nintros.\napply Extensionality_Ensembles; red; split; red; intros;\n  auto with sets.\nconstructor.\nconstructor.\ndestruct a.\nQed.\n\nLemma empty_indexed_union: forall {T:Type}\n  (F:IndexedFamily False T),\n  IndexedUnion F = Empty_set.\nProof.\nintros.\napply Extensionality_Ensembles; red; split; red; intros.\ndestruct H.\ndestruct a.\ndestruct H.\nQed.\n\nEnd IndexedFamilyFacts.\n\nSection IndexedFamilyToFamily.\n\n(* relation to families of subsets of T *)\nVariable T:Type.\nVariable A:Type.\nVariable F:IndexedFamily A T.\n\nDefinition ImageFamily : Family T :=\n  Im Full_set F.\n\nLemma indexed_to_family_union: IndexedUnion F = FamilyUnion ImageFamily.\nProof.\napply Extensionality_Ensembles.\nunfold Same_set.\nunfold Included.\nintuition.\ndestruct H.\napply family_union_intro with (F a).\napply Im_intro with a.\nconstructor.\nreflexivity.\nassumption.\n\ndestruct H.\ndestruct H.\napply indexed_union_intro with x0.\nrewrite <- H1.\nassumption.\nQed.\n\nLemma indexed_to_family_intersection:\n  IndexedIntersection F = FamilyIntersection ImageFamily.\nProof.\napply Extensionality_Ensembles.\nunfold Same_set.\nunfold Included.\nintuition.\nconstructor.\nintros.\ndestruct H.\ndestruct H0.\nrewrite H1.\napply H.\n\nconstructor.\nintro.\ndestruct H.\napply H.\napply Im_intro with a.\nconstructor.\nreflexivity.\nQed.\n\nEnd IndexedFamilyToFamily.\n", "meta": {"author": "dschepler", "repo": "coq-zorns-lemma", "sha": "4ad354c50f73758c094f43da5fc0f2c6dd8e3da2", "save_path": "github-repos/coq/dschepler-coq-zorns-lemma", "path": "github-repos/coq/dschepler-coq-zorns-lemma/coq-zorns-lemma-4ad354c50f73758c094f43da5fc0f2c6dd8e3da2/IndexedFamilies.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7065529276695873}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Import Orders Rbase Rbasic_fun ROrderedType GenericMinMax.\n\n(** * Maximum and Minimum of two real numbers *)\n\nLocal Open Scope R_scope.\n\n(** The functions [Rmax] and [Rmin] implement indeed\n    a maximum and a minimum *)\n\nLemma Rmax_l : forall x y, y<=x -> Rmax x y = x.\nProof.\n unfold Rmax. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmax_r : forall x y, x<=y -> Rmax x y = y.\nProof.\n unfold Rmax. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmin_l : forall x y, x<=y -> Rmin x y = x.\nProof.\n unfold Rmin. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nLemma Rmin_r : forall x y, y<=x -> Rmin x y = y.\nProof.\n unfold Rmin. intros.\n destruct Rle_dec as [H'|H']; [| apply Rnot_le_lt in H' ];\n  unfold Rle in *; intuition.\nQed.\n\nModule RHasMinMax <: HasMinMax R_as_OT.\n Definition max := Rmax.\n Definition min := Rmin.\n Definition max_l := Rmax_l.\n Definition max_r := Rmax_r.\n Definition min_l := Rmin_l.\n Definition min_r := Rmin_r.\nEnd RHasMinMax.\n\nModule R.\n\n(** We obtain hence all the generic properties of max and min. *)\n\nInclude UsualMinMaxProperties R_as_OT RHasMinMax.\n\n(** * Properties specific to the [R] domain *)\n\n(** Compatibilities (consequences of monotonicity) *)\n\nLemma plus_max_distr_l : forall n m p, Rmax (p + n) (p + m) = p + Rmax n m.\nProof.\n intros. apply max_monotone.\n intros x y. apply Rplus_le_compat_l.\nQed.\n\nLemma plus_max_distr_r : forall n m p, Rmax (n + p) (m + p) = Rmax n m + p.\nProof.\n intros. rewrite (Rplus_comm n p), (Rplus_comm m p), (Rplus_comm _ p).\n apply plus_max_distr_l.\nQed.\n\nLemma plus_min_distr_l : forall n m p, Rmin (p + n) (p + m) = p + Rmin n m.\nProof.\n intros. apply min_monotone.\n intros x y. apply Rplus_le_compat_l.\nQed.\n\nLemma plus_min_distr_r : forall n m p, Rmin (n + p) (m + p) = Rmin n m + p.\nProof.\n intros. rewrite (Rplus_comm n p), (Rplus_comm m p), (Rplus_comm _ p).\n apply plus_min_distr_l.\nQed.\n\n(** Anti-monotonicity swaps the role of [min] and [max] *)\n\nLemma opp_max_distr : forall n m : R, -(Rmax n m) = Rmin (- n) (- m).\nProof.\n intros. symmetry. apply min_max_antimonotone.\n do 3 red. intros; apply Rge_le. apply Ropp_le_ge_contravar; auto.\nQed.\n\nLemma opp_min_distr : forall n m : R, - (Rmin n m) = Rmax (- n) (- m).\nProof.\n intros. symmetry. apply max_min_antimonotone.\n do 3 red. intros; apply Rge_le. apply Ropp_le_ge_contravar; auto.\nQed.\n\nLemma minus_max_distr_l : forall n m p, Rmax (p - n) (p - m) = p - Rmin n m.\nProof.\n unfold Rminus. intros. rewrite opp_min_distr. apply plus_max_distr_l.\nQed.\n\nLemma minus_max_distr_r : forall n m p, Rmax (n - p) (m - p) = Rmax n m - p.\nProof.\n unfold Rminus. intros. apply plus_max_distr_r.\nQed.\n\nLemma minus_min_distr_l : forall n m p, Rmin (p - n) (p - m) = p - Rmax n m.\nProof.\n unfold Rminus. intros. rewrite opp_max_distr. apply plus_min_distr_l.\nQed.\n\nLemma minus_min_distr_r : forall n m p, Rmin (n - p) (m - p) = Rmin n m - p.\nProof.\n unfold Rminus. intros. apply plus_min_distr_r.\nQed.\n\nEnd R.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Reals/Rminmax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7065529238500758}}
{"text": "Require Import Arith.\nRequire Import Lia.\n\n\nLemma minus_plus_commut:\nforall m n q, m >= n -> m - n + q = m + q - n.\nProof.\n  intros.\n  assert (m = n + (m - n)).\n  apply le_plus_minus; auto.\n  rewrite H0.\n  assert (n + (m - n) + q = n + ((m-n) + q)). lia.\n  rewrite H1. assert (n + (m - n + q) - n = m - n + q).\n  apply minus_plus. rewrite H2.\n  assert (n + (m - n) - n = m - n).\n  apply minus_plus. rewrite H3. auto.\nQed.\nHint Resolve minus_plus_commut.\n\nLemma sp_P2_N2:\nforall sp, sp + 2 - 2 = sp.\nProof.\n  intro.\n  assert (sp + 2 = 2 + sp). auto with arith.\n  rewrite H. auto with arith.\nQed.\nHint Resolve sp_P2_N2.\n\nLemma sp_P4_N2:\nforall sp, sp + 4 - 2 = sp + 2.\nProof.\n  intro sp.\n  lia.\nQed.\nHint Resolve sp_P4_N2.\n\nLemma sp_P2_P2:\nforall sp, sp + 2 + 2 = sp + 4.\nProof.\n  intro sp. lia.\nQed.\nHint Resolve sp_P2_P2.\n\nLemma sp_P4_N2_N2:\nforall sp, sp + 4 - 2 - 2 = sp.\nProof.\n  intro sp. lia.\nQed.\nHint Resolve sp_P4_N2_N2.\n\n\nLemma ge_trans:\n  forall a b c, a >= b -> b >= c -> a >= c.\nProof.\n  intros.\n  assert (c <= a).\n  apply le_trans with b; auto with arith.\n  auto with arith.\nQed.\n\n\nLemma sp_P4_P2:\nforall sp, sp + 4 + 2 = sp + 6.\nProof.\n  intro. lia.\nQed.\nHint Resolve sp_P4_P2.\n\nLemma sp_P4_N6:\nforall sp, sp + 4 - 6 = sp - 2.\nProof.\n  intro sp.\n  lia.\nQed.\nHint Resolve sp_P4_N6.\n\nLemma sp_P6_N2:\nforall sp, sp + 6 - 2 = sp + 4.\nProof.\n  intro sp. lia.\nQed.\nHint Resolve sp_P6_N2.\n\nLemma sp_N2_P2:\nforall sp, sp >= 2 -> sp - 2 + 2 = sp.\nProof.\n  intros.\n  assert (sp - 2 + 2 = sp + 2 - 2). auto.\n  rewrite H0. auto.\nQed.\nHint Resolve sp_N2_P2.\n\nLemma sp_N2_P4:\nforall sp, sp >= 2 -> sp - 2 + 4 = sp + 2.\nProof.\n  intros.\n  assert (sp - 2 + 4 = sp + 4 - 2). auto.\n  assert (sp +  4 - 2 = sp + 2); auto.\n  rewrite H1 in H0. rewrite H0. auto.\nQed.\nHint Resolve sp_N2_P4.\n\nLemma sp_N2_P6:\nforall sp, sp >= 2 -> sp - 2 + 6 = sp + 4.\nProof.\n  intros.\n  assert (sp - 2 + 6 = sp + 6 - 2).\n  auto. rewrite H0.\n  lia.\nQed.\nHint Resolve sp_N2_P6.\n\nLemma sp_P2_P1:\nforall sp, \n    sp + 2 + 1 = sp + 3.\nProof.\n  intro sp. lia.\nQed.\nHint Resolve sp_P2_P1.\n\n", "meta": {"author": "mithrao", "repo": "Coq-assembly-verification", "sha": "c3ab9fea02cc7f94331888604231923069a01334", "save_path": "github-repos/coq/mithrao-Coq-assembly-verification", "path": "github-repos/coq/mithrao-Coq-assembly-verification/Coq-assembly-verification-c3ab9fea02cc7f94331888604231923069a01334/final-aim/Arith_Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7064628283427996}}
{"text": "(* https://coq.inria.fr/refman/Reference-Manual027.html *)\n(* PROGRAM-ing Finger Trees in COQ *)\n\nRequire Import Omega.\nRequire Import List.\nRequire Import Arith.\nRequire Import Arith.Even.\nRequire Import Program.\nRequire Import Cpdt.CpdtTactics Cpdt.Coinductive.\n\nSet Implicit Arguments.\n\nProgram Definition id (n : nat) : { x : nat | x = n } :=\n  if dec (leb n 0) then\n    0\n  else\n    S (pred n).\nObligation 1.\nProof.                                      (* n <= 0 -> n = 0 *)\n  destruct n.\n  - now auto.                               (* n = 0 *)\n  - now inversion H.                        (* n >= 1 矛盾 *)\n\n  Restart.\n  now destruct n.\nDefined.\nObligation 2.\nProof.\n  now destruct n.\nDefined.\n\n\n(* DIV2 *)\nProgram Fixpoint div2 (n : nat) {measure n} :\n  { x : nat | n = 2 * x \\/ n = 2 * x + 1 } :=\n  match n with\n  | S (S p) => S (div2 p)\n  | _ => O\n  end.\nObligation 2.\nProof.\n  remember (div2 _ _).\n  destruct s as [n H]; simpl.\n  omega.\nDefined.\nObligation 3.\nProof.\n  destruct n as [| n].\n  - now left.                               (* n = 0 *)\n  - destruct n as [| n].\n    + now right.                            (* n = 1 *)\n    + induction (H n).\n      reflexivity.                          (* n >= 2 *)\n      \n  Restart.\n  destruct n as [| n]; try auto.\n  destruct n as [| n]; try auto.\n  induction (H n); auto.\nDefined.\n\n(* measure なしの場合 *)\nProgram Fixpoint div2' (n : nat) :\n  { x : nat | n = 2 * x \\/ n = 2 * x + 1 } :=\n  match n with\n  | S (S p) => S (div2' p)\n  | _ => O\n  end.\nObligation 1.\nProof.\n  omega.\nDefined.\nObligation 2.\nProof.\n  destruct n as [| n].\n  - now left.                               (* n = 0 *)\n  - destruct n as [| n].\n    + now right.                            (* n = 1 *)\n    + induction (H n).\n      reflexivity.                          (* n >= 2 *)\n      \n  Restart.\n  destruct n as [| n]; try auto.\n  destruct n as [| n]; try auto.\n  induction (H n); auto.\nDefined.\n\n(* 証明なし *)\nFixpoint div2'' (n : nat) : nat :=\n  match n with\n  | S (S p) => S (div2'' p)\n  | _ => O\n  end.\n\n(* **** *)\n(* Even *)\n(* **** *)\n(* Hint Constructos even odd with arith *)\n\nLemma not_odd_and_even n : odd n -> even n -> False.\nProof.\n  induction n.\n  - now intros Ho He.\n  - intros Ho He.\n    inversion Ho.\n    inversion He.\n    now auto.\n    \n  Restart.\n  intros Ho He.\n  generalize He Ho.\n  now apply not_even_and_odd.\nQed.\n\nLemma not_odd_2 x : odd (x + x) -> False.\nProof.\n  apply not_even_and_odd.\n  cutrewrite (x + x = 2 * x).\n  - now apply even_mult_l; auto with arith.\n  - omega.\nQed.\n\nLemma not_even_2_1 x : even (x + x + 1) -> False.\nProof.\n  apply not_odd_and_even.\n  apply odd_plus_r.\n  - cutrewrite (x + x = 2 * x).\n    + now apply even_mult_l; auto with arith.\n    + omega.\n  - now auto with arith.\nQed.\n\nLemma even_2 x : even (x * 2).\nProof.\n  apply even_mult_r.\n  now auto with arith.\nQed.\nHint Resolve even_2.\n\nProgram Definition div2_2' (n : nat) :\n  { m : nat | even m } :=\n  div2 n * 2.\n(* Obligation なし。 *)\n\nProgram Definition div2_2 (n : nat) :\n  { m : nat | (even n -> n = m) /\\ (odd n -> n - 1 = m) } :=\n  div2 n * 2.\nObligation 1.\nProof.\n  remember (div2 _).\n  remember (_ * 2).\n  destruct s as [m H].                      (* 証明のないdiv2'' だと s が出てこない。 *)\n  destruct H as [H1 | H2]; simpl in *.\n  - split.\n    + omega.\n    + clear Heqs.\n      rewrite <- plus_n_O in H1.\n      intro H.\n      rewrite H1 in H.\n      now apply not_odd_2 in H.\n  - split.\n    + clear Heqs.\n      rewrite <- plus_n_O in H2.\n      intro H.\n      rewrite H2 in H.\n      now apply not_even_2_1 in H.\n    + omega.\nDefined.\n\nEval compute in  ` (div2_2 4).              (* 4 *)\nEval compute in  ` (div2_2 5).              (* 4 *)\n\n(* 次にやること。 *)\n(* div2 の末尾再帰版をつくる。 *)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/prog/coq_div.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7064476366864275}}
{"text": "(* by Evelyne Contejean *)\n\n(** * Some additional properties for the Coq lists. *)\n\nSet Implicit Arguments.\n\nRequire Import List.\nRequire Import Arith.\n\n(** ** Relations between length, map, append, In and nth. *)\n\nLemma map_map :\n  forall (A B C : Set) (l : (list A)) (f : B -> C) (g : A ->B),\n  map f (map g l) = map (fun x => f (g x)) l.\nProof.\nintros A B C l f g; induction l as [ | x l].\ntrivial.\nsimpl; rewrite IHl; trivial.\nQed.\n\nLemma list_app_length :\n forall A, forall l1 l2 : list A, length (l1 ++ l2) = length l1 + length l2.\nProof.\ninduction l1 as [ | a1 l1 ]; trivial.\nintros; simpl; rewrite IHl1; trivial.\nQed.\n\nLemma length_map :\n forall (A B : Set) (f : A -> B) (l : list A), length (map f l) = length l.\nProof.\nintros; induction l as [ | a l ]; trivial.\nsimpl; rewrite IHl; trivial.\nQed.\n\nLemma map_app :\n forall (A B : Set) (f : A -> B) l1 l2, map f (l1 ++ l2) = (map f l1) ++ (map f l2).\nProof.\ninduction l1 as [ | a1 l1 ]; trivial.\nintros; simpl; rewrite IHl1; trivial.\nQed.\n\n\nLemma in_in_map :\n  forall (A B : Set) (f : A -> B) a l, In a l -> In (f a) (map f l).\nProof.\nintros A B f a l; induction l as [ | b l ]; trivial.\nintro In_a; elim In_a; clear In_a; intro In_a.\nsubst; left; trivial.\nright; apply IHl; trivial.\nQed.\n\nLemma in_map_in :\n  forall (A B : Set) (f : A -> B) b l, In b (map f l) ->\n  exists a, In a l /\\ f a = b.\nProof.\nintros A B f b l; induction l as [ | a l ].\ncontradiction.\nintro In_b; elim In_b; clear In_b; intro In_b.\nexists a; split; trivial; left; trivial.\nelim (IHl In_b); intros a' [H1 H2]; exists a'; split; trivial; right; trivial.\nQed.\n\nLemma nth_error_map :\n  forall (A B : Set) (f : A -> B) (l : list A) i,\n  match nth_error (map f l) i with\n  | Some f_li => \n           match nth_error l i with\n            | Some li => f_li = f li\n            | None => False\n            end\n  | None =>\n            match nth_error l i with\n            | Some li => False\n            | None => True\n            end\nend.\nProof.\ninduction l as [ | a l ]; \nintro i; destruct i as [ | i ]; simpl; trivial.\napply IHl; trivial.\nQed.\n\n(** ** A measure on lists based on a measure on elements. *)\n\nFixpoint list_size (A : Set) (size : A -> nat) (l : list A) {struct l} : nat :=\n  match l with\n  | nil => 0\n  | h :: tl => size h + list_size size tl\n  end.\n\nLemma list_size_tl_compat :\n  forall (A : Set) (size : A -> nat) a b l, size a < size b -> \n    list_size size (a :: l) < list_size size (b :: l).\nProof.\nintros A size a b l H; simpl; apply plus_lt_compat_r; trivial.\nQed.\n\nLemma list_size_app:\n forall (A : Set) (size : A -> nat) l1 l2,\n list_size size (l1 ++ l2) = list_size size l1 + list_size size l2.  \nProof. \ninduction l1 as [ | a1 l1 ]; trivial.\nintros; simpl; rewrite IHl1; auto with arith.\nQed.\n\nLemma list_size_fold :\n  forall (A : Set) (size : A -> nat) l n,\n  fold_left (fun (size_acc : nat) (a : A) => size_acc + size a) l n =\n  n + list_size size l.\nProof.\nintros A size l; induction l; trivial.\nintro n; simpl; rewrite plus_assoc; apply IHl.\nQed.\n\nLemma list_size_size_eq :\n  forall (A : Set) (size1 : A -> nat) (size2 : A -> nat) l,\n (forall a, In a l -> size1 a = size2 a) -> list_size size1 l = list_size size2 l.\nProof.\nintros A size1 size2 l; induction l as [ | a l]; simpl; trivial.\nintros size1_eq_size2.\nrewrite (size1_eq_size2 a (or_introl _ (refl_equal _))).\napply (f_equal (fun n => size2 a + n)); apply IHl;\nintros; apply size1_eq_size2; right; trivial.\nQed.\n\n(** ** Induction principles for list. \n Induction on the length. *)\nDefinition list_rec2 :\n  forall A, forall P : list A -> Type,\n    (forall (n:nat) (l : list A), length l <= n -> P l) -> \n    forall l : list A, P l.\nProof.\nintros A P H l; apply (H (length l) l); apply le_n.\nDefined.\n\nDefinition o_length (A : Set) (l1 l2 : list A) : Prop := length l1 < length l2.\n\nTheorem well_founded_length : forall A, well_founded (o_length (A := A)).\nProof.\nintro A; assert (Acc_nil : Acc (o_length (A:=A)) (@nil A)).\napply Acc_intro; intros l H; absurd (o_length l nil); trivial; \nunfold o_length; simpl; auto with arith.\n\nunfold well_founded, o_length; \nintros l; pattern l; apply list_rec2; clear l;\ninduction n; intro l; destruct l; intros H; trivial.\nsimpl in H; absurd (S (length l) <= 0); trivial; auto with arith.\napply Acc_intro; intros l' H'; apply IHn;\napply le_trans with (length l);\nsimpl in H; simpl in H'; auto with arith.\nDefined.\n\n(** Induction on the the size. *)\nDefinition list_rec3 (A : Set) (size : A -> nat) :\n  forall P : list A -> Type,\n    (forall (n:nat) (l : list A), list_size size l <= n -> P l) -> \n    forall l : list A, P l.\nProof.\nintros P H l; apply (H (list_size size l) l); apply le_n.\nDefined.\n\n(** ** How to remove an element in a list, whenever it is present. *)\nFixpoint split_list (A : Set)\n  (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (l : list A) (t : A) {struct l} : list A * list A :=\n  match l with\n  | nil => (nil, nil)\n  | a :: l' =>\n      if eqA t a\n      then (nil, l')\n      else let (l1,l2) := split_list eqA l' t in (a :: l1, l2)\n  end.\n\nLemma split_list_app_cons :\n forall (A : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) t l,\n   In t l -> let (l1, l2) := split_list eqA l t in l = l1 ++ t :: l2.\nProof.\ninduction l as [ | a l ].\ncontradiction.\nsimpl; elim (eqA t a); intro eq_t_a.\nintros _; subst; trivial.\nintros [eq_t_a' | In_t].\nabsurd (t = a); auto.\ngeneralize (IHl In_t); destruct (split_list eqA l t); intro; subst; auto.\nDefined.\n\nFixpoint remove (A : Set) (eqA : forall a1 a2 : A, {a1=a2}+{a1<>a2}) \n  (a : A) (l : list A) {struct l} : (option (list A)) :=\n  match l with\n  | nil => None \n  | h :: tl =>\n    if eqA a h\n    then Some tl\n    else \n      match remove eqA a tl with\n      | Some rmv => Some (h :: rmv)\n      | None => None \n      end\n  end.\n\nLemma in_remove :\n  forall (A : Set) (eqA : forall a1 a2 : A, {a1=a2}+{a1<>a2}) a l,  \n  match remove eqA a l with\n  | None => ~In a l\n  | Some l' => In a l /\\ let (l1, l2) := split_list eqA l a in l' = l1 ++ l2\n  end.\nProof.\ninduction l as [ | a1 l]; simpl; auto;\nelim (eqA a a1); intro eq_a_a1; intuition.\ndestruct (remove eqA a l) as [ rmv |  ]; intuition; \ndestruct (split_list eqA l a); subst; auto.\nQed.\n\nFixpoint remove_list (A : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n(la l : list A) {struct l} : option (list A) :=\n  match la with\n  | nil => Some l\n  | a :: la' => \n\tmatch l with \n\t| nil => None\n\t| b :: l' => \n\t   if eqA a b\n\t   then remove_list eqA la' l'\n\t   else \n\t     match remove_list eqA la l' with\n\t     | None => None\n\t     | Some rmv => Some (b :: rmv)\n\t     end\n        end\n  end.\n\n\n(** ** Iterators. *) \nFixpoint fold_left2 (A B C : Set) (f : A -> B -> C -> A) (a : A) (l1 : list B) (l2 : list C)  \n  {struct l1} : option A :=\n  match l1, l2 with\n  | nil, nil => Some a\n  | b :: t1, c :: t2 => fold_left2 f (f a b c) t1 t2\n  | _, _ => None\n  end.\n\n(** ** more properties on the nth element. *)\nLemma nth_error_ok_in :\n  forall (A : Set) n (l : list A) (a : A),\n  nth_error l n = Some a -> In a l.\nProof.\nintros A n l; generalize n; clear n; induction l as [ | a' l].\nintros [ | n] a; simpl; discriminate.\nintros [ | n] a; simpl.\nintro H; injection H; subst; left; trivial.\nintro; right; apply IHl with n; trivial.\nQed.\n\n(** ** Association lists. \n*** find. *)\nFixpoint find (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n(a : A) (l : list (A * B)) {struct l} : option (B) :=\n match l with\n | nil => None\n | (a1,b1) :: l =>\n     if eqA a a1\n     then Some b1\n     else find eqA a l\n  end.\n\nLemma find_not_mem :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  (a : A) (b : B) (l : list (A * B)) (dom : list A),\n  ~In a dom -> (forall a', In a' dom -> find eqA a' ((a,b) :: l) = find eqA a' l).\nProof.\nintros A B eqA a b l dom a_not_in_dom a' a'_in_dom; simpl;\ndestruct (eqA a' a) as [a'_eq_a | a'_diff_a].\nsubst a'; absurd (In a dom); trivial.\ntrivial.\nQed.\n\n(** *** number of occurences of the first element of a pair. *)\nFixpoint nb_occ (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  (a : A) (l : list (A * B)) {struct l} : nat :=\n  match l with\n  | nil => 0\n  | (a',_) :: tl =>\n     if (eqA a a') then S (nb_occ eqA a tl) else nb_occ eqA a tl\n  end.\n\nLemma none_nb_occ_O :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  (a : A) (l : list (A * B)),\n  find eqA a l = None -> nb_occ eqA a l = 0.\nProof.\nintros A B eqA a l; induction l as [ | [a1 b1] l]; trivial; simpl.\ndestruct (eqA a a1) as [a_eq_a1 | a_diff_a1]; intros.\ndiscriminate.\napply IHl; trivial.\nQed.\n\nLemma some_nb_occ_Sn :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  (a : A) (l : list (A * B)) b,\n  find eqA a l = Some b -> 1 <= nb_occ eqA a l.\nProof.\nintros A B eqA a l; induction l as [ | [a1 b1] l].\nintros; discriminate.\nintro b; simpl; destruct (eqA a a1) as [_ | _].\nauto with arith.\nintros; apply IHl with b; trivial.\nQed.\n\nLemma nb_occ_app :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2})\n  a (l1 l2 : list (A * B)), \n  nb_occ eqA a (l1++l2) = nb_occ eqA a l1 + nb_occ eqA a l2.\nProof.\nintros A B eqA a l1; induction l1 as [ | [a1 b1] l1]; simpl; trivial.\nintro l2; rewrite IHl1; destruct (eqA a a1) as [_ | _]; trivial.\nQed.\n\nLemma reduce_assoc_list :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}),\n  forall (l : list (A * B)), exists l', \n (forall a, nb_occ eqA a l' <= 1) /\\ (forall a, find eqA a l = find eqA a l').\nProof.\nintros A B eqA l; induction l as [ | [a1 b1] l].\nexists (nil : list (A * B)); split; trivial; auto.\nelim IHl; intros l' [H1 H2].\nassert (In_a1 : forall a, a = a1 -> find eqA a l' = find eqA a1 l').\nintros; subst; trivial.\ndestruct (find eqA a1 l') as [ b | ]; \ngeneralize (In_a1 _ (refl_equal _)); clear In_a1; intro In_a1.\nassert (In_a1' : exists l1, exists  l2, l' = l1 ++ (a1,b) :: l2).\nclear H1 H2; induction l' as [ | [a' b'] l'].\ndiscriminate.\nsimpl in In_a1; destruct (eqA a1 a') as [a1_eq_a' | _].\nsubst; inversion In_a1; exists (nil : list (A * B)); exists l'; simpl; trivial.\nelim (IHl' In_a1); intros l1 [l2 H]; \nexists ((a',b') :: l1); exists l2; subst; trivial.\nelim In_a1'; intros l1 [l2 H]; exists ((a1,b1) :: l1 ++ l2); split.\nintro a; generalize (H1 a); subst l'; rewrite nb_occ_app; \nsimpl; destruct (eqA a a1) as [a_eq_a1 | _]; subst; rewrite nb_occ_app;\n[ rewrite plus_comm; simpl; rewrite plus_comm | idtac ]; trivial.\nintro a; simpl; destruct (eqA a a1) as [a_eq_a1 | a_diff_a1]; trivial.\nrewrite H2; subst l'; clear H1 H2 In_a1 In_a1'; \ninduction l1 as [ | [a1' b1'] l1]; simpl.\ndestruct (eqA a a1); trivial; absurd (a = a1); trivial.\nrewrite IHl1; trivial.\nexists ((a1,b1) :: l'); split; trivial; intro a; simpl.\ndestruct (eqA a a1) as [a_eq_a1 | a_diff_a1]; trivial.\nrewrite none_nb_occ_O; subst; trivial.\nrewrite (H2 a); trivial.\nQed.\n\n(** map_without_repetition applies a function to the elements of a list,\nbut only a single time when there are several consecutive occurences of the\nsame element. Moreover, the function is supposed to return an option as a result,\nin order to simulate exceptions, and the abnormal results are discarted.\n*)\nFixpoint map_without_repetition (A B : Set) \n  (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (f : A -> option B) (l : list A) {struct l} : list B :=\n    match l with\n    | nil => (nil : list B)\n    | h :: nil => \n      match f h with\n      | None => nil\n      | Some f_h => f_h :: nil\n      end\n    | h1 :: ((h2 :: tl) as l1) =>\n    if (eqA h1 h2)\n    then map_without_repetition eqA f l1\n    else \n      match f h1 with\n      | None => map_without_repetition eqA f l1\n      | Some f_h1 => f_h1 :: (map_without_repetition eqA f l1)\n      end\nend.\n\nLemma prop_map_without_repetition :\n forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (P : B -> Prop) f l,\n  (forall a, In a l -> \n   match f a with \n   | None => True \n   | Some f_a => P f_a\n   end) ->\n   (forall b, In b (map_without_repetition eqA f l) -> P b).\nProof.\ninduction l as [ | a1 l].\ncontradiction.\nassert (In_a1 : In a1 (a1 :: l)).\nleft; trivial.\nintros H; generalize (H a1 In_a1); simpl; destruct l as [ | a2 l].\ndestruct (f a1) as [ f_a1 |  ]; simpl; intuition; subst; trivial.\nelim (eqA a1 a2); intro eq_a1_a2.\nintros; apply IHl; trivial; intros; apply H; right; trivial.\ndestruct (f a1) as [ f_a1 |  ].\nintros P_f_a1 b [eq_f_a1_b | In_b].\nsubst; apply P_f_a1; left; trivial.\napply IHl; trivial; intros; apply H; right; trivial.\nintros; apply IHl; trivial; intros; apply H; right; trivial.\nQed.\n\nLemma exists_map_without_repetition :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (P : B -> Prop) f l,\n  (exists a,  In a l /\\ match f a with \n                        | None => False\n                        | Some f_a => P f_a\n                        end) ->\n  (exists b, In b (map_without_repetition eqA f l) /\\ P b).\nProof.\nintros A B eqA P f.\nassert (In_map_right : forall b a l, \nIn b (map_without_repetition eqA f l) ->\nIn b (map_without_repetition eqA f (a :: l))).\nintros b a1 l In_b; simpl; destruct l as [ | a2 l].\ncontradiction.\nelim (eqA a1 a2); trivial;\ndestruct (f a1) as [ b1 | ]; trivial; intros _; right; trivial.\ninduction l as [ | a1 l].\nintros [a [In_a _]]; contradiction.\nintros [a [[Eq_a_a1 | In_a] P_f_a]].\nsimpl; subst a1; destruct l as [ | a2 l]; intuition.\ndestruct (f a) as [b | ]; [ exists b; intuition | contradiction ].\nelim (eqA a a2).\nintro; subst a; apply IHl; exists a2; intuition.\nintros _; \ndestruct (f a) as [ b | ]; [exists b; intuition | contradiction].\nassert (H: exists b : B, In b (map_without_repetition eqA f l) /\\ P b).\napply IHl; exists a; intuition.\ngeneralize H; intros [b H_b]; exists b; intuition.\nQed.\n\n(** map12_without_repetition is similar to map_without_repetition, but the \napplied function returns two optional results instead of one.\n*)\n\nFixpoint map12_without_repetition (A B : Set) \n  (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (f : A -> option B * option B) (l : list A) {struct l} : list B :=\n    match l with\n    | nil => (nil : list B)\n    | h :: nil => \n      match f h with\n      | (None, None) => nil\n      | (Some f_h1, None) => f_h1 :: nil\n      | (None, Some f_h1) => f_h1 :: nil\n      | (Some f_h1, Some f_h2) => f_h1 :: f_h2 :: nil\n      end\n    | h :: ((h' :: tl) as l1) =>\n    if (eqA h h')\n    then map12_without_repetition eqA f l1\n    else \n      match f h with\n      | (None, None) => map12_without_repetition eqA f l1\n      | (Some f_h1, None) => f_h1 :: (map12_without_repetition eqA f l1)\n      | (None, Some f_h1) => f_h1 :: (map12_without_repetition eqA f l1)\n      | (Some f_h1, Some f_h2) => f_h2 :: f_h1 :: (map12_without_repetition eqA f l1)\n      end\nend.\n\nLemma prop_map12_without_repetition :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (P : B -> Prop) f l,\n  (forall a, In a l -> \n   match f a with \n   | (None, None) => True \n   | (Some f1_a, None) => P f1_a\n   | (None, Some f2_a) => P f2_a\n   | (Some f1_a, Some f2_a) => P f1_a /\\ P f2_a\n   end) ->\n (forall b, In b (map12_without_repetition eqA f l) -> P b).\nProof.\nintros A B eqA P f; induction l as [ | a1 l].\ncontradiction.\nassert (In_a1 : In a1 (a1 :: l)).\nleft; trivial.\nintros H b; \nassert (Hrec : \nforall b : B, In b (map12_without_repetition eqA f l) -> P b).\nintros; apply IHl; trivial; intros; apply H; right; trivial.\nclear IHl; simpl; generalize (H a1 In_a1).\ndestruct l as [ | a2 l].\ndestruct (f a1) as [o1 o2]; \ndestruct o1 as [ f1_a1 | ];\ndestruct o2 as [ f2_a1 | ];\n[ intros [P_f1_a1 P_f2_a1] | intros P_f1_a1 | intros P_f2_a1 | idtac].\nintros [Eq_b_f1_a1 | [Eq_b_f2_a1 | In_b]]; subst; trivial; contradiction.\nintros [Eq_b_f1_a1 | In_b]; subst; trivial; contradiction.\nintros [Eq_b_f2_a1 | In_b]; subst; trivial; contradiction.\ncontradiction.\nelim (eqA a1 a2).\nintros; apply Hrec; trivial.\ndestruct (f a1) as [o1 o2]; \ndestruct o1 as [ f1_a1 | ];\ndestruct o2 as [ f2_a1 | ];\n[ intros _ [P_f1_a1 P_f2_a1] \n| intros _ P_f1_a1 | intros _ P_f2_a1 | intros _].\nintros [Eq_b_f1_a1 | [Eq_b_f2_a1 | In_b]]; \nsubst; trivial; apply Hrec; trivial.\nintros [Eq_b_f1_a1 | In_b]; subst; trivial; apply Hrec; trivial.\nintros [Eq_b_f2_a1 | In_b]; subst; trivial; apply Hrec; trivial.\nintros; apply Hrec; trivial.\nQed.\n\nLemma exists_map12_without_repetition :\n  forall (A B : Set) (eqA : forall (a1 a2 : A), {a1=a2}+{a1<>a2}) \n  (P : B -> Prop) f l,\n  ((exists a, In a l /\\ match f a with \n                        | (None, None) => False\n                        | (None, Some f2_a) => P f2_a\n                        | (Some f1_a, None) => P f1_a\n                        | (Some f1_a, Some f2_a) => P f1_a \\/ P f2_a\n                        end) ->\n  (exists b, In b (map12_without_repetition eqA f l) /\\ P b)).\nProof.\nintros A B eqA P f; induction l as [ | a1 l].\nintros [a [In_a _]]; contradiction.\ndestruct l as [ | a2 l].\nintros [a [[Eq_a_a1 | In_a] P_f_a]]; simpl.\nsubst a; destruct (f a1) as [o1 o2];\ndestruct o1 as [f1_a1 | ];\ndestruct o2 as [f2_a1 | ].\ngeneralize P_f_a; clear P_f_a; intros [P_f1_a1 | P_f2_a1].\nexists f1_a1; intuition.\nexists f2_a1; intuition.\nexists f1_a1; intuition.\nexists f2_a1; intuition.\ncontradiction.\ncontradiction.\nintros [a [[Eq_a_a1 | In_a] P_f_a]].\nsubst a; simpl; elim (eqA a1 a2).\nintro; subst a1; apply IHl; exists a2; intuition.\ndestruct (f a1) as [o1 o2];\ndestruct o1 as [f1_a1 | ];\ndestruct o2 as [f2_a1 | ].\ngeneralize P_f_a; clear P_f_a; intros [P_f1_a1 | P_f2_a1].\nexists f1_a1; intuition.\nexists f2_a1; intuition.\nexists f1_a1; intuition.\nexists f2_a1; intuition.\ncontradiction.\nassert (Hrec : exists b : B, \nIn b (map12_without_repetition eqA f (a2 :: l)) /\\ P b).\napply IHl; exists a; split; trivial.\ngeneralize Hrec; intros [b [In_b P_b]]; exists b; split; trivial.\nsimpl; elim (eqA a1 a2).\nintro; subst a1; trivial.\nintros _; destruct (f a1) as [o1 o2];\ndestruct o1 as [P_f1_a1 | ];\ndestruct o2 as [P_f2_a1 | ].\nright; right; trivial.\nright; trivial.\nright; trivial.\ntrivial.\nQed.\n", "meta": {"author": "aarondroidbryce", "repo": "cyclic_peano", "sha": "fb0a713eb8ada20402c62a5953e1ccc800860605", "save_path": "github-repos/coq/aarondroidbryce-cyclic_peano", "path": "github-repos/coq/aarondroidbryce-cyclic_peano/cyclic_peano-fb0a713eb8ada20402c62a5953e1ccc800860605/theories/Casteran/more_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7064476258292703}}
{"text": "Require Import EqNat.\nRequire Import List.\nRequire Import ListSet.\nRequire Import Coq.Bool.BoolEq.\nRequire Import Arith.Peano_dec.\n\nSection background.\n\n  (********** Atoms **********)\n\n  Inductive atomic :=\n  | A : nat -> atomic. \n  \n  Definition beq_atomic (a : atomic) (b : atomic) :=\n    match a, b with\n      | A n, A m => beq_nat n m\n    end.\n\n  (* This is needed to use ListSet *)\n  Definition atomic_eq : \n    forall a b : atomic, {a = b} + {a <> b}.\n    decide equality.\n    apply eq_nat_dec.\n  Defined.\n\n  (********** Formulae **********)\n\n  Inductive formula :=\n  | Atom : atomic -> formula \n  | Negation : formula -> formula\n  | Disjunction : formula -> formula -> formula.\n  \n  Notation \"A_[ i ]\" :=\n    (Atom (A i))\n      (at level 200, right associativity).\n  Check (Atom (A 1)).\n\n  Notation \"'Conjunction' A B \" := \n    (Negation (Disjunction (Negation A) (Negation B)))\n      (at level 80, left associativity).\n  Check (Negation (Disjunction (Negation (A_[1])) (Negation (A_[2])))).\n\n  Notation \"'Implies' A B\" :=\n    (Disjunction (Negation A) B)\n      (at level 60, left associativity).\n  Check (Disjunction (Negation (A_[1])) (A_[2])).\n\n  Fixpoint get_all_atoms_formula (f : formula) : set atomic :=\n    match f with\n      | Atom foo => set_add atomic_eq foo (@empty_set atomic)\n      | Negation foo => get_all_atoms_formula foo\n      | Disjunction foo bar => set_union atomic_eq (get_all_atoms_formula foo) (get_all_atoms_formula bar)\n    end.\n\n  Fixpoint in_formula (a : atomic) (f : formula) : Prop :=\n    match f with\n      | Atom atm => match atomic_eq atm a with\n                        | left _ => True\n                        | right _ => False\n                    end\n      | Negation f' => in_formula a f'\n      | Disjunction f' f'' => in_formula a f' \\/ in_formula a f''\n    end.\n\n  Theorem in_formula_in_all_atoms:\n    forall f a,\n      In a (get_all_atoms_formula f) <-> in_formula a f.\n  Proof. \n    split; induction f; simpl; intros; try (inversion H); \n      try (destruct (atomic_eq a0 a));\n      try (trivial).\n    + unfold not in n.\n      apply n.\n      apply H0.\n    + apply IHf in H.\n      apply H.\n    + left. \n      apply IHf1.\n      (* need to relate set union and append in H *)\n\n\n      \n  Theorem in_formula_disjunction_commute: \n    forall a f g, \n      in_formula a (Disjunction f g) <-> in_formula a (Disjunction g f).\n  Proof. \n    split; unfold in_formula; intros; induction f; destruct g; fold in_formula; \n     try (apply or_comm; apply H);\n     try (destruct (atomic_eq a0 a)).\n  Qed.\n\n  Theorem in_formula_disjunction_add:\n    forall a f g,\n      in_formula a f -> in_formula a (Disjunction f g).\n  Proof.\n    intros.\n    simpl.\n    left. \n    apply H.\n  Qed.\n\n  (********** Assignments & Suitability  **********)\n\n  Definition assignment : Set := list (atomic * bool).\n  \n  Fixpoint generate_all_assignments (a : list atomic) : (list assignment) :=\n    let f := fun atm v assign => (atm, v)::assign in\n    match a with\n         | nil => nil::nil\n         | h::t => let f' := f h\n                   in (map (f' true) (generate_all_assignments t))\n                        ++ (map (f' false) (generate_all_assignments t))\n       end.\n\n  Fixpoint in_assignment (a : atomic) (ays : assignment) : Prop :=\n    match ays with\n      | nil => False\n      | (h,_)::t =>  match atomic_eq a h with\n                       | left _ => True\n                       | right _ => in_assignment a t\n                     end\n    end.\n\n  Definition suitable (f : formula) (ays : assignment) : Prop := \n    forall a, \n      in_formula a f -> in_assignment a ays.\n\n  Theorem generated_assignments_are_suitable:\n    forall f ays,\n      In ays (generate_all_assignments (get_all_atoms_formula f)) -> suitable f ays.\n  Proof.\n    unfold suitable; intros; induction ays; destruct f; simpl in H; try (inversion H); simpl. \n    + inversion H1.\n    + inversion H1; inversion H2.\n    + unfold In in H.\n      unfold generate_all_assignments in H.\n      unfold get_all_atoms_formula in H.\n\n  Theorem suitable_negation_invariant: \n    forall f ays, \n      suitable f ays <-> suitable (Negation f) ays.\n  Proof. \n    split; intros; unfold suitable; unfold suitable in H; intros; apply H; simpl in H0.\n    + apply H0.\n    + simpl; apply H0.\n  Qed.\n\n  Theorem suitable_disjunction_invariant:\n    forall f g ays,\n    suitable (Disjunction f g) ays -> suitable f ays /\\ suitable g ays.\n  Proof. \n    unfold suitable; intros.\n    split.\n    + intros.\n      apply in_formula_disjunction_add with (g:=g) in H0.\n      generalize H0.\n      apply H.\n    + intros.\n      apply in_formula_disjunction_add with (g:=f) in H0.\n      apply in_formula_disjunction_commute in H0.\n      generalize H0.\n      apply H.\n  Qed.\n    \n  Lemma in_empty : forall a, in_assignment a nil -> False.\n    intros; compute in H; apply H.\n  Qed.\n\n  (* Thanks to @arjunguha *)\n  Lemma in_partition : forall (a k : atomic) (tv : bool) (ays : assignment),\n                         in_assignment a ((k,tv)::ays) ->\n                         a <> k ->\n                         in_assignment a ays.\n  Proof with auto using list.\n    intros; induction ays; simpl in H; destruct (atomic_eq a k); try contradiction.\n    simpl. apply H.\n  Qed.\n  \n  Fixpoint find_assignment a (ays : assignment) { struct ays }: in_assignment a ays -> bool.\n  refine (match ays with\n            | nil => _\n            | (h,tv)::t => \n              match atomic_eq a h with\n                | left eq_proof => fun _ => tv\n                | right neq_proof => fun pf => find_assignment a t (@in_partition a h tv t pf neq_proof)\n              end\n          end).\n  Proof.\n    + intros.\n      apply in_empty in H.\n      inversion H.\n  Qed.\n\n  (********** Truth Tables **********)\n  \n  Definition truth_table_entry := (bool * assignment)%type.\n  \n  (* Truth tables are tied to evaluation *)\n  Fixpoint eval_formula (phi : formula) (ays : assignment) : suitable phi ays -> bool.\n  refine (match phi with\n            | Atom atm => fun _ => find_assignment atm ays _\n            | Negation phi' => fun _ => negb (eval_formula phi' ays _)\n            | Disjunction phi' phi'' => fun _ => orb (eval_formula phi' ays _)\n                                                      (eval_formula phi'' ays _)\n          end).\n  Proof. \n    intros; unfold suitable in _H; apply _H; simpl.\n    destruct (atomic_eq atm atm); trivial.\n    + unfold not in n; apply n; trivial.\n    + apply suitable_negation_invariant; apply _H.\n    + apply suitable_disjunction_invariant in _H; inversion _H.\n      apply H.\n    + apply suitable_disjunction_invariant in _H; inversion _H.\n      apply H0.\n  Qed.\n\n  Definition generate_truth_table (f : formula) : list truth_table_entry :=\n    let atoms := (get_all_atoms_formula f) in\n    let assignments := (generate_all_assignments atoms) in\n    map (fun assignment =>  \n           let pf := suitable f assignment in\n           ((eval_formula f assignment pf), assignment))\n        assignments.\n\n\n  Fixpoint atoms_equal (f_atoms g_atoms : set atomic) : bool :=\n    match f_atoms, g_atoms with\n      | nil, nil  => true\n      | nil, _ | _, nil => false\n      | h::t, _ => if set_mem atomic_eq h g_atoms\n                   then atoms_equal t (set_remove atomic_eq h g_atoms)\n                   else false\n    end.\n\n  \n (********** Formula Equality **********)\n  \n  Fixpoint beq_formula (f g : formula) : bool :=\n    let f_atoms := get_all_atoms_formula f in\n    let g_atoms := get_all_atoms_formula g in\n    if atoms_equal f_atoms g_atoms \n    then     \n      let f_assignments := generate_all_assignments f_atoms in\n      let g_assignments := generate_all_assignments g_atoms in\n      \n    else false.\n\n    \n\n  Definition formula_eq : forall f g : formula, \n                            {f = g} + {f <> g}.\n    decide equality.\n    apply atomic_eq.\n  Defined.\n\n  (* Later when we have truth tables, we can use those to define another, better  equality function. *)\n\n\n  Theorem disjunction_commute : forall f g, \n                                  Disjunction f g = Disjunction g f.\n\n\n  Inductive eq_formula : formula -> formula -> Prop :=\n  | atom_eq : forall a1 a2, a1 = a2 -> eq_formula (Atom a1) (Atom a2)\n  | neg_eq : forall f g, eq_formula f g -> eq_formula (Negation f) (Negation g)\n  | disj_eq : forall f g h, eq_formula f g -> eq_formula (Disjunction f h) (Disjunction g h).\n\n  Proof. \n    induction f; simpl.\n    destruct g.\n    \n\n\n  Fixpoint bsub_formula (F : formula) (G : formula) : bool :=\n    if beq_formula F G\n    then true\n    else match G with\n           | Atom _ => false\n           | Negation foo => bsub_formula F foo\n           | Disjunction foo bar => orb (bsub_formula F foo) (bsub_formula F bar)\n         end.\n\n  Inductive sub_formula: formula -> formula -> Prop :=\n  | base_subf : forall f g, eq_formula f g -> sub_formula f g\n  | neg_subf : forall f g, sub_formula f g -> sub_formula f (Negation g)\n  | disj_subf : forall f g h, sub_formula f g -> sub_formula f (Disjunction g h).\n\n  \n\n\n  Fixpoint count_atoms (a : atomic) (lst : list atomic) :=\n    match lst with\n      | nil => 0\n      | h::tl => if (beq_atomic h a)\n                 then 1 + (count_atoms a tl)\n                 else count_atoms a tl\n    end.\n\n\n  Definition min (F G : option bool) : option bool :=\n    match F, G with \n      | _ , None | None, _ => None\n      | _, Some false | Some false, _ => Some false\n      | _, _ => Some true\n    end.\n\n  (* This doesn't solve the problem we had before with defining things in terms of option types.\n     It just temporarily commutes the problem. We will need to get dependent types working in order\n     to really prove things in a way that looks like \"informal\" proofs. *)\n  (* Inductive truth_value := *)\n  (* | Top : True -> truth_value *)\n  (* | TV : bool -> truth_value *)\n  (* | Bot : False -> truth_value. *)\n  \n\n  (* Inductive in_assignment (a : atomic) : assignment -> Prop := *)\n  (*   | asgn_found : forall h tv ays ays', *)\n  (*                    h = a -> in_assignment a (ays'++(h,tv)::ays). *)\n\n  Fixpoint in_assignment_bool (a : atomic) (ays : assignment) : bool :=\n    match ays with\n      | nil => false\n      | (h,_)::t => if beq_atomic h a\n                    then true\n                    else in_assignment_bool a t\n    end.\n\n  Fixpoint in_assignment_prop (a : atomic) (ays : assignment) : Prop :=\n    match ays with\n      | nil => False\n      | (h, _)::t => if beq_atomic h a \n                     then True\n                     else in_assignment_prop a t\n    end.\n\n  Theorem in_assignment_bool_eq_in_assignment_prop : forall a ays, \n                                                       in_assignment_bool a ays = true <-> in_assignment_prop a ays.\n  Proof.\n    split.\n    (* in_assignment_bool a ays = true -> in_assignment_prop a ays *)\n    induction ays; intros.\n    simpl in H; inversion H.    \n    destruct a0.\n    simpl.\n    remember (beq_atomic a0 a) as hcmp.\n    destruct hcmp.\n    apply I.\n    simpl in H.\n    rewrite <- Heqhcmp in H.\n    generalize H.\n    apply IHays.\n    (* in_assignment_prop a ays -> in_assignment_bool a ays = true *)\n    induction ays; intros.\n    simpl in H; inversion H.\n    destruct a0.\n    simpl.\n    remember (beq_atomic a0 a) as hcmp.\n    destruct hcmp.\n    reflexivity.\n    simpl in H.\n    rewrite <- Heqhcmp in H.\n    generalize H.\n    apply IHays.\n  Qed.\n\n  (* Fixpoint in_assignment (a : atomic) (ays : assignment) : Prop := *)\n  (*   match ays with *)\n  (*     | nil => False *)\n  (*     | (h,_)::t => if beq_atomic h a *)\n  (*               then True *)\n  (*               else in_assignment a t *)\n  (*   end. *)\n\n  Definition in_empty : forall a, in_assignment_prop a nil -> False.\n    intros.\n    inversion H.\n  Qed.\n\n  Lemma index_atomic_equal : forall n m,\n                               n = m -> A n = A m.\n    intros. rewrite H. reflexivity.\n  Qed.\n\n  Lemma beq_atomic_true : forall a,\n                            beq_atomic a a = true.\n    destruct a.\n    simpl. apply beq_nat_true_iff. reflexivity.\n  Qed.\n\n  Lemma eq_beq_atomic_true : forall a b,\n                               a = b -> beq_atomic a b = true.\n    intros.\n    rewrite H. apply beq_atomic_true.\n  Qed.                          \n\n  (* Lemma atomic_index_equal : forall n m, *)\n  (*                              A n = A m -> n = m. *)\n  (*   intros; induction n; remember m; destruct m as [|foo]. *)\n  (*   rewrite Heqn. *)\n  (*   reflexivity. *)\n  (*   apply eq_beq_atomic_true in H.  *)\n  (*   simpl in H. *)\n  (*   rewrite Heqn in H. *)\n  (*   inversion H. *)\n  (*   rewrite Heqn0. *)\n  (*   rewrite Heqn0 in H. *)\n  (*   rewrite Heqn0 in IHn. *)\n    \n\n  (* Lemma in_assignment_head_or_tail: forall a t h tv, *)\n  (*                                     in_assignment_prop a ((h,tv)::t) -> *)\n  (*                                     a = h \\/ in_assignment_prop a t. *)\n  (*   intros. *)\n  (*   unfold in_assignment_prop in H. *)\n  (*   remember (beq_atomic h a). *)\n  (*   destruct b. *)\n  (*   destruct a; destruct h. *)\n  (*   simpl in Heqb. *)\n  (*   left. *)\n\n\n\n\n  Lemma in_assignment_additive: forall a t h P,\n                                  in_assignment_prop a t -> P -> (in_assignment_prop a (h::t) -> P).\n    (* need to prive in_assignment_head_or_tail first *)\n  Admitted.\n\n\n  (* I think what we need here is to somehow provide a proof that \n     in_assignment_prop a t -> boolin_assignment_prop a t -> bool\n     implies \n     in_assignment_prop a ((h, tv) :: t) -> bool *)\n  Fixpoint find_assignment (a : atomic) (ays : assignment) : in_assignment_prop a ays -> bool :=\n    match ays with\n      | nil => fun pf => match (in_empty a) pf with end\n      | (h,tv)::t => if beq_atomic a h\n                     then fun _ => tv\n                     else in_assignment_additive a t (h,tv) bool (find_assignment a t) \n    end.\n\n  Definition get_first_atom_in_assignment (ays : assignment) :=\n    match ays with\n      | nil => None\n      | (h,_)::t => Some h\n    end.\n\n  (* Lemma in_assignment_head_or_rest : forall a b ays, *)\n  (*                                      in_assignment a ays -> *)\n  (*                                      get_first_atom_in_assignment ays = Some a  *)\n  (*                                      \\/ in_assignment a (b::ays). *)\n  (*   intros. *)\n    \n    \n\n\n  (* Lemma in_assignment_additive : forall a h ays, *)\n  (*                                  in_assignment a ays -> in_assignment a (h::ays). *)\n  (*   induction ays. *)\n  (*   intros. *)\n  (*   apply in_empty in H. *)\n  (*   inversion H. *)\n  (*   intros. *)\n    \n    \n\n  (* Fixpoint find_assignment (a : atomic) (ays : assignment) : in_assignment a ays -> bool := *)\n  (*   match ays with *)\n  (*     | nil => fun pf => match (in_empty a) pf with end *)\n  (*     | (h, tv)::t => if beq_atomic a h *)\n  (*                     then fun _ => tv *)\n  (*                     else (fun _ => find_assignment a t) (find_assignment a ays) *)\n  (*   end. *)\n                              \n\n  Fixpoint find_assignment (a : atomic) (ays : assignment) : option bool :=\n    match ays with \n      | nil => None\n      | (h,tv)::t => if beq_atomic h a\n                     then Some tv\n                     else find_assignment a t\n    end.\n\n\n  (* Fixpoint find_assignment (a : atomic) (ays : { x : assignment | in_assignment a x }) : bool := *)\n  (*   (* (sig (fun x => in_assignment a x)) *) *)\n  (*   match ays with *)\n  (*     | exist nil pf => match (in_empty a) pf with end *)\n  (*     | exist ((h, tv)::t) pf  => if beq_atomic a h *)\n  (*                                 then tv *)\n  (*                                 else find_assignment a (exist (in_assignment a) t pf) *)\n  (*   end. *)\n\n\n\n  Fixpoint get_all_atoms_assignment (a : assignment) : set atomic :=\n    (* assignment is not a set; new assignments shadow others. we only return teh newest *)\n    match a with\n      | nil => @empty_set atomic\n      | (h, _)::t => match find_assignment h t with\n                       | None => set_add atomic_eq h (get_all_atoms_assignment t)\n                       | _ =>  get_all_atoms_assignment t\n                     end\n    end.\n  \n\n  (* this thing is totally wrong; will think about it more later *)\n  (* Definition none_found : forall a ays, find_assignment (Atom a) ays = None -> False. *)\n  (*   (* we need something like this to be able to run eval_formula using dependent types*) *)\n  (* Admitted. *)\n\n  (* in progress *)\n  \n  Definition formula_eq : forall F G a, \n                            { eval_formula F a = eval_formula G a } + { eval_formula F a <> eval_formula G a}.\n    decide equality.\n    apply eq_dec with (beq:=fun a b => (orb (andb a b) (andb (negb a) (negb b)))).\n    intros. destruct x. simpl. reflexivity.\n    simpl. reflexivity.\n    destruct x; destruct y; simpl; try (intros; reflexivity); try (intros; inversion H).\n  Defined.\n\n  Lemma assignment_atomic_eq : forall a1 a2 ays,\n                                 find_assignment a1 ays = find_assignment a2 ays -> a1 = a2.\n    intros.\n    induction ays; destruct a1; destruct a2.\n    simpl in H.\n\n\n\n  Definition eval_formula_eq : forall F G a,\n                                 eval_formula F a = eval_formula G a -> F = G.\n    induction F; destruct G; intros.\n    simpl in H.\n    unfold find_assignment in H.\n    \n\n\n\n  Theorem disjunction_commute : forall F G,\n                                  Disjunction F G = Disjunction G F.\n  Proof. \n    induction F; destruct G.\n    apply formula_eq.\n    \n  (*Definition suitable (f : formula) (a : assignment) := eval_formula f a <> None. *)\n\n  Lemma get_all_atoms_negation_invariant : forall F,\n                                             get_all_atoms_formula F = get_all_atoms_formula (Negation F).\n    induction F; simpl; reflexivity.\n  Qed.    \n\n  Lemma suitable_negation_invariant : forall F a,\n                                        suitable F a <-> suitable (Negation F) a.\n    intros. split; unfold suitable; intros. \n    rewrite <- get_all_atoms_negation_invariant; apply H.\n    rewrite <- get_all_atoms_negation_invariant in H; apply H.\n  Qed.\n\n  Lemma suitable_disjunction_constituants : forall F G a,\n                                              suitable (Disjunction F G) a -> \n\n  Lemma suitable_disjunction_constituants : forall F G a,\n                                              ~ suitable F a -> ~ suitable (Disjunction F G) a.\n    induction F as [atm |F' IHF'| F1 IHF1 F2 IHF2].\n    unfold not; unfold suitable; simpl.\n    intros.\n    apply H.\n    destruct (set_mem atomic_eq atm (get_all_atoms_assignment a)).\n    compute. reflexivity.\n    compute. \n\n\n  Lemma empty_assignment_not_suitable : forall F,\n                                          eval_formula F nil = None -> ~ suitable F nil.\n  Proof.\n    induction F as [|F' IHF| F1 IHF1 F2 IHF2]; simpl; intros; try (unfold not); try (unfold suitable); simpl.\n    (* atomic *)\n    compute; intros; inversion H0.\n    (* negation *)\n    destruct (eval_formula F' nil) as [somebool|].\n    inversion H.\n    apply IHF in H. unfold not in H. unfold suitable in H. simpl in H. apply H.\n    (* disjunction *)\n    destruct (eval_formula F1 nil) as [abool|]; destruct (eval_formula F2 nil) as [bbool|].\n    inversion H.\n    apply IHF2 in H.\n\n  Definition models (f : formula) (a : assignment) := eval_formula f a = Some true.\n  \n  Definition satisfiable (f : formula) := exists a,\n                                            suitable f a -> eval_formula f a = Some true.\n\n  Definition unsatisfiable (f : formula) := forall a,\n                                              suitable f a -> eval_formula f a = Some false.\n\n  Definition valid (f : formula) := forall a,\n                                      suitable f a -> eval_formula f a = Some true.\n\n  Definition form_equiv (F G : formula) a b :=\n                          eval_formula F a = b <-> eval_formula G a = b.\n                          \n\n      \n\n  Qed.\n\nLemma  suitable_invariant_negation : forall F a,\n                                       suitable F a <-> suitable (Negation F) a.\nProof. \n  intros. split.\n  + induction F; unfold suitable; unfold not; intros;  simpl in H; simpl in H0.\n    (* atomic *)\n    destruct (find_assignment a0 a).\n    inversion H0.\n    (* negation *)\n    apply H; apply H0.\n    destruct (eval_formula F a).\n    inversion H0.\n    (* disjunction *)\n    apply H; apply H0.\n    destruct (eval_formula F1 a).\n    destruct (eval_formula F2 a).\n    inversion H0.\n    apply H; apply H0.\n    apply H; apply H0.\n  + induction F; unfold suitable; unfold not; intros.\n    (* atomic *)\n    simpl in H0.\n    destruct (find_assignment a0 a) eqn:stuff.\n    inversion H0.\n    apply H.\n    simpl.\n    rewrite stuff. \n    reflexivity.\n    (* negation *)\n    simpl in H0.\n    destruct (eval_formula F a) eqn:stuff.\n    inversion H0.\n    apply H. \n    simpl.\n    rewrite stuff.\n    reflexivity.\n    (* disjunction *)\n    simpl in H. simpl in H0.\n    destruct (eval_formula F1 a) eqn:stuff1.\n    destruct (eval_formula F2 a) eqn:stuff2.\n    inversion H0.\n    apply H; apply H0.\n    apply H; apply H0.\nQed.\n\n\nLemma atom_eq : forall a b,\n                  beq_atomic a b = true -> a = b.\nProof. \n  intros.\n  induction a. destruct b.\n  inversion H. \n  apply beq_nat_true_iff in H1.\n  rewrite H1. reflexivity.\nQed.  \n\nLemma eq_nat_beq : forall n m,\n                     n = m -> beq_nat n m = true.\nProof. \n  intros. rewrite H. symmetry. apply beq_nat_refl.\nQed.  \n\nLemma eval_Negation: forall (b:bool) (F:formula) (a:assignment), suitable F a -> ((eval_formula F a = Some b) <-> (eval_formula (Negation F) a = Some (negb b))).  \nProof.\n  intros.\n  split.\n  unfold suitable in H. intros.\n  destruct F.\n  (* atom *)\n  simpl. simpl in H0. rewrite H0. destruct b; simpl; reflexivity.\n  (* negation *)\n  simpl. simpl in H0. simpl in H. \n    destruct (eval_formula F a). \n     destruct b. simpl. \n      destruct b0. simpl. rewrite <- H0; simpl. reflexivity. simpl. reflexivity.\n      destruct b0. simpl. reflexivity. simpl. rewrite <- H0. simpl. reflexivity.\n     inversion H0. \n  (* disjunction *)\n  simpl. simpl in H. simpl in H0. \n    destruct (eval_formula F1 a).\n     destruct (eval_formula F2 a).\n      destruct b.\n       simpl. destruct b0. simpl. reflexivity. simpl. simpl in H0. destruct b1. simpl. reflexivity. simpl. rewrite H0. reflexivity.\n       simpl. destruct b0. simpl. simpl in H0. rewrite H0. reflexivity. simpl. simpl in H0. destruct b1. simpl. rewrite H0. reflexivity. simpl. reflexivity.\n      inversion H0.\n      inversion H0.\n  simpl. unfold suitable in H.\n  intros.\n  destruct (eval_formula F a).\n   destruct b. \n    destruct b0. reflexivity. simpl in H0. rewrite H0. reflexivity. \n    destruct b0. simpl in H0. rewrite H0. reflexivity. reflexivity.\n   inversion H0.\nQed.\n\nTheorem tautology : forall F,\n                      valid F <-> unsatisfiable (Negation F).\nProof. \n  intros.  \n  split.\n  (* -> *)\n  unfold unsatisfiable.\n  unfold valid.\n  intros.\n  destruct F;\n    unfold eval_formula;\n    unfold eval_formula in H;\n    rewrite <- suitable_invariant_negation in H0;\n    apply H in H0;\n    rewrite H0;\n    simpl; reflexivity.\n  (* <- *)\n  unfold unsatisfiable.\n  unfold valid.\n  intros.\n  rewrite suitable_invariant_negation in H0.\n  apply H in H0.\n  rewrite eval_Negation.\n  rewrite H0.\n  simpl.\n  reflexivity.\n  rewrite suitable_invariant_negation.\n  unfold suitable.\n  rewrite H0.\n  unfold not.\n  intros.\n  inversion H1.\nQed.\n", "meta": {"author": "etosch", "repo": "logic", "sha": "40e1f1c26bd89fed3a814d90166995cc44568ef5", "save_path": "github-repos/coq/etosch-logic", "path": "github-repos/coq/etosch-logic/logic-40e1f1c26bd89fed3a814d90166995cc44568ef5/src/PropLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7063980629003918}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus (mult y z) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj285_coqofml_QQqFxF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7063980579211805}}
{"text": "(*****************************************************************\n\n Posets\n\n In this file, we give some constructions on posets.\n\n Contents\n 1. Accessors\n 2. The unit poset\n 3. The product of posets\n 4. Monotone functions\n 5. Examples of monotone functions\n 6. The poset of monotone functions\n 7. The equalizer of posets\n 8. Type indexed products of posets\n\n *****************************************************************)\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\n\n(**\n 1. Accessors\n *)\nProposition trans_PartialOrder\n            {X : hSet}\n            (R : PartialOrder X)\n            {x₁ x₂ x₃ : X}\n            (p : R x₁ x₂)\n            (q : R x₂ x₃)\n  : R x₁ x₃.\nProof.\n  exact (pr112 R _ _ _ p q).\nQed.\n\nProposition refl_PartialOrder\n            {X : hSet}\n            (R : PartialOrder X)\n            (x : X)\n  : R x x.\nProof.\n  exact (pr212 R x).\nQed.\n\nProposition antisymm_PartialOrder\n            {X : hSet}\n            (R : PartialOrder X)\n            {x y : X}\n            (p : R x y)\n            (q : R y x)\n  : x = y.\nProof.\n  exact (pr22 R _ _ p q).\nQed.\n\n(**\n 2. The unit poset\n *)\nDefinition unit_PartialOrder\n  : PartialOrder unitset.\nProof.\n  use make_PartialOrder.\n  - exact (λ _ _, htrue).\n  - repeat split.\n    intros x y p q.\n    apply isapropunit.\nDefined.\n\n(**\n 3. The product of posets\n *)\nSection ProdOrder.\n  Context {X₁ X₂ : hSet}\n          (R₁ : PartialOrder X₁)\n          (R₂ : PartialOrder X₂).\n\n  Let R : hrel (X₁ × X₂)%set := λ x y, R₁ (pr1 x) (pr1 y) ∧ R₂ (pr2 x) (pr2 y).\n\n  Proposition prod_PartialOrderLaws\n    : isPartialOrder R.\n  Proof.\n    simple refine ((_ ,, _) ,, _).\n    - refine (λ x y z p q, _ ,, _).\n      + exact (trans_PartialOrder R₁ (pr1 p) (pr1 q)).\n      + exact (trans_PartialOrder R₂ (pr2 p) (pr2 q)).\n    - refine (λ x, _ ,, _).\n      + exact (refl_PartialOrder R₁ (pr1 x)).\n      + exact (refl_PartialOrder R₂ (pr2 x)).\n    - refine (λ x y p q, _).\n      use pathsdirprod.\n      + exact (antisymm_PartialOrder R₁ (pr1 p) (pr1 q)).\n      + exact (antisymm_PartialOrder R₂ (pr2 p) (pr2 q)).\n  Qed.\n\n  Definition prod_PartialOrder\n    : PartialOrder (X₁ × X₂)%set.\n  Proof.\n    use make_PartialOrder.\n    - exact R.\n    - exact prod_PartialOrderLaws.\n  Defined.\nEnd ProdOrder.\n\n(**\n 4. Monotone functions\n *)\nDefinition is_monotone\n           {X₁ X₂ : hSet}\n           (R₁ : PartialOrder X₁)\n           (R₂ : PartialOrder X₂)\n           (f : X₁ → X₂)\n  : UU\n  := ∏ (x₁ x₂ : X₁), R₁ x₁ x₂ → R₂ (f x₁) (f x₂).\n\nProposition isaprop_is_monotone\n            {X₁ X₂ : hSet}\n            (R₁ : PartialOrder X₁)\n            (R₂ : PartialOrder X₂)\n            (f : X₁ → X₂)\n  : isaprop (is_monotone R₁ R₂ f).\nProof.\n  repeat (use impred ; intro).\n  apply (pr1 R₂).\nQed.\n\nDefinition monotone_function\n           {X₁ X₂ : hSet}\n           (R₁ : PartialOrder X₁)\n           (R₂ : PartialOrder X₂)\n  : UU\n  := ∑ (f : X₁ → X₂), is_monotone R₁ R₂ f.\n\nDefinition  monotone_function_to_function\n            {X₁ X₂ : hSet}\n            {R₁ : PartialOrder X₁}\n            {R₂ : PartialOrder X₂}\n            (f : monotone_function R₁ R₂)\n  : X₁ → X₂\n  := pr1 f.\n\nCoercion monotone_function_to_function : monotone_function >-> Funclass.\n\nProposition eq_monotone_function\n            {X₁ X₂ : hSet}\n            {R₁ : PartialOrder X₁}\n            {R₂ : PartialOrder X₂}\n            (f g : monotone_function R₁ R₂)\n            (p : ∏ (x : X₁), f x = g x)\n  : f = g.\nProof.\n  use subtypePath.\n  {\n    intro.\n    apply isaprop_is_monotone.\n  }\n  use funextsec.\n  exact p.\nQed.\n\nDefinition monotone_function_hSet\n           {X₁ X₂ : hSet}\n           (R₁ : PartialOrder X₁)\n           (R₂ : PartialOrder X₂)\n  : hSet.\nProof.\n  use make_hSet.\n  - exact (monotone_function R₁ R₂).\n  - use isaset_total2.\n    + use funspace_isaset.\n      exact (pr2 X₂).\n    + intro f.\n      apply isasetaprop.\n      apply isaprop_is_monotone.\nDefined.\n\n(**\n 5. Examples of monotone functions\n *)\nProposition idfun_is_monotone\n            {X : hSet}\n            (R : PartialOrder X)\n  : is_monotone R R (idfun X).\nProof.\n  exact (λ x₁ x₂ p, p).\nQed.\n\nProposition comp_is_monotone\n            {X₁ X₂ X₃ : hSet}\n            {R₁ : PartialOrder X₁}\n            {R₂ : PartialOrder X₂}\n            {R₃ : PartialOrder X₃}\n            {f : X₁ → X₂}\n            {g : X₂ → X₃}\n            (Hf : is_monotone R₁ R₂ f)\n            (Hg : is_monotone R₂ R₃ g)\n  : is_monotone R₁ R₃ (λ z, g(f z)).\nProof.\n  exact (λ x₁ x₂ p, Hg _ _ (Hf _ _ p)).\nQed.\n\nProposition dirprod_pr1_is_monotone\n            {X₁ X₂ : hSet}\n            (R₁ : PartialOrder X₁)\n            (R₂ : PartialOrder X₂)\n  : is_monotone (prod_PartialOrder R₁ R₂) R₁ pr1.\nProof.\n  exact (λ x₁ x₂ p, pr1 p).\nQed.\n\nProposition dirprod_pr2_is_monotone\n            {X₁ X₂ : hSet}\n            (R₁ : PartialOrder X₁)\n            (R₂ : PartialOrder X₂)\n  : is_monotone (prod_PartialOrder R₁ R₂) R₂ pr2.\nProof.\n  exact (λ x₁ x₂ p, pr2 p).\nQed.\n\nProposition prodtofun_is_monotone\n            {W X₁ X₂ : hSet}\n            {RW : PartialOrder W}\n            {R₁ : PartialOrder X₁}\n            {R₂ : PartialOrder X₂}\n            {f : W → X₁}\n            {g : W → X₂}\n            (Hf : is_monotone RW R₁ f)\n            (Hg : is_monotone RW R₂ g)\n  : is_monotone RW (prod_PartialOrder R₁ R₂) (prodtofuntoprod (f,, g)).\nProof.\n  exact (λ x y p, Hf _ _ p ,, Hg _ _ p).\nQed.\n\n(**\n 6. The poset of monotone functions\n *)\nSection FunctionOrder.\n  Context {X Y : hSet}\n          (RX : PartialOrder X)\n          (RY : PartialOrder Y).\n\n  Definition monotone_function_order\n    : hrel (monotone_function_hSet RX RY).\n  Proof.\n    intros f g ; cbn in *.\n    use make_hProp.\n    - exact (∏ (x : X), RY (f x) (g x)).\n    - abstract\n        (use impred ; intro ;\n         apply (pr1 RY)).\n  Defined.\n\n  Proposition monotone_function_isPartialOrder\n    : isPartialOrder monotone_function_order.\n  Proof.\n    simple refine ((_ ,, _) ,, _).\n    - exact (λ f g h p q x, trans_PartialOrder RY (p x) (q x)).\n    - exact (λ f x, refl_PartialOrder RY (pr1 f x)).\n    - intros f g p q.\n      use eq_monotone_function.\n      intro x.\n      exact (antisymm_PartialOrder RY (p x) (q x)).\n  Qed.\n\n  Definition monotone_function_PartialOrder\n    : PartialOrder (monotone_function_hSet RX RY).\n  Proof.\n    use make_PartialOrder.\n    - exact monotone_function_order.\n    - exact monotone_function_isPartialOrder.\n  Defined.\n\n  Definition eval_monotone_function\n    : monotone_function\n        (prod_PartialOrder RX monotone_function_PartialOrder)\n        RY.\n  Proof.\n    simple refine (_ ,, _) ; cbn.\n    - exact (λ xf, pr2 xf (pr1 xf)).\n    - abstract\n        (intros xf yg pq ;\n         induction xf as [ x f ] ;\n         induction yg as [ y g ] ;\n         induction pq as [ p q ] ;\n         cbn in * ;\n         exact (trans_PartialOrder RY (q x) (pr2 g x y p))).\n  Defined.\n\n  Definition lam_monotone_function\n             {Z : hSet}\n             {RZ : PartialOrder Z}\n             (f : monotone_function (prod_PartialOrder RX RZ) RY)\n    : monotone_function RZ monotone_function_PartialOrder.\n  Proof.\n    simple refine (_ ,, _) ; cbn.\n    - intro z.\n      simple refine (_ ,, _).\n      + exact (λ x, f (x ,, z)).\n      + abstract\n          (intros x₁ x₂ p ;\n           apply f ; cbn ;\n           refine (p ,, _) ;\n           apply refl_PartialOrder).\n    - abstract\n        (intros z₁ z₂ p x ; cbn ;\n         apply f ; cbn ;\n         exact (refl_PartialOrder RX x ,, p)).\n  Defined.\nEnd FunctionOrder.\n\n(**\n 7. The equalizer of posets\n *)\nSection Equalizer.\n  Context {X : hSet}\n          (RX : PartialOrder X)\n          (Y : hSet)\n          (f g : X → Y).\n\n  Let Eq : hSet\n    := (∑ (x : X), f x = g x) ,, isaset_total2 _ (pr2 X) (λ _, isasetaprop (pr2 Y _ _)).\n\n  Definition Equalizer_order\n    : PartialOrder Eq.\n  Proof.\n    simple refine (_ ,, ((_ ,, _) ,, _)).\n    - exact (λ x y, RX (pr1 x) (pr1 y)).\n    - abstract\n        (exact (λ x y z p q, trans_PartialOrder RX p q)).\n    - abstract\n        (exact (λ x, refl_PartialOrder RX (pr1 x))).\n    - abstract\n        (intros x y p q ;\n         use subtypePath ; [ intro ; apply (pr2 Y) | ] ;\n         exact (antisymm_PartialOrder RX p q)).\n  Defined.\n\n  Proposition Equalizer_pr1_monotone\n    : is_monotone\n        Equalizer_order\n        RX\n        (λ z, pr1 z).\n  Proof.\n    intros x y p.\n    exact p.\n  Qed.\n\n  Proposition Equalizer_map_monotone\n              {W : hSet}\n              (RW : PartialOrder W)\n              {h : W → X}\n              (Rh : is_monotone RW RX h)\n              (p : ∏ (w : W), f(h w) = g(h w))\n    : is_monotone\n        RW\n        Equalizer_order\n        (λ w, h w ,, p w).\n  Proof.\n    intros w₁ w₂ q.\n    apply Rh.\n    exact q.\n  Qed.\nEnd Equalizer.\n\n(**\n 8. Type indexed products of posets\n *)\nDefinition depfunction_poset\n           {X : UU}\n           (Y : X → hSet)\n           (RY : ∏ (x : X), PartialOrder (Y x))\n  : PartialOrder (forall_hSet Y).\nProof.\n  use make_PartialOrder.\n  - exact (λ f g, ∀ (x : X), RY x (f x) (g x)).\n  - repeat split.\n    + abstract\n        (intros f g h p q x ;\n         exact (trans_PartialOrder (RY x) (p x) (q x))).\n    + abstract\n        (intros f x ;\n         exact (refl_PartialOrder (RY x) (f x))).\n    + abstract\n        (intros f g p q ;\n         use funextsec ;\n         intro x ;\n         exact (antisymm_PartialOrder (RY x) (p x) (q x))).\nDefined.\n\nProposition is_monotone_depfunction_poset_pr\n            {X : UU}\n            (Y : X → hSet)\n            (RY : ∏ (x : X), PartialOrder (Y x))\n            (x : X)\n  : is_monotone (depfunction_poset Y RY) (RY x) (λ f, f x).\nProof.\n  intros f g p.\n  exact (p x).\nQed.\n\nProposition is_monotone_depfunction_poset_pair\n            {W : hSet}\n            {X : UU}\n            {Y : X → hSet}\n            {RW : PartialOrder W}\n            {RY : ∏ (x : X), PartialOrder (Y x)}\n            (fs : ∏ (x : X), W → Y x)\n            (Hfs : ∏ (x : X), is_monotone RW (RY x) (fs x))\n  : is_monotone RW (depfunction_poset Y RY) (λ w x, fs x w).\nProof.\n  intros w₁ w₂ p x.\n  exact (Hfs x _ _ p).\nQed.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Combinatorics/Posets.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7063131497893658}}
{"text": "\nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type := Cons : natural -> lst -> lst |  Nil : lst.\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nTheorem append_nil: forall (l: lst), append l Nil = l.\nProof.\n   induction l.\n   { simpl. f_equal. assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem append_assoc:\n   forall (l1 l2 l3: lst), append l1 (append l2 l3) = append (append l1 l2) l3.\nProof.\n   induction l1; induction l2; induction l3; try (simpl; reflexivity).\n   { simpl. rewrite <- IHl1. f_equal. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\n   { simpl. rewrite append_nil.  reflexivity. }\n   { simpl. rewrite 2 append_nil. reflexivity. }\nQed.\n\nTheorem append_rev_cons:\n   forall (l1 l2: lst) (x: natural),\n   rev (append l1 (Cons x l2)) = append (rev l2) (Cons x (rev l1)).\nProof.\n   induction l1; induction l2; try (simpl; reflexivity).\n   { intro. simpl. rewrite IHl1. simpl. rewrite <- append_assoc.\n   f_equal. }\n   { intro. simpl. rewrite IHl1. simpl. reflexivity. }\nQed.\n\nTheorem rev_append: forall (l1 l2: lst), rev (append l1 l2) = append (rev l2) (rev l1).\nProof.\n   induction l1.\n   { induction l2.\n   { simpl. rewrite append_rev_cons.\n      rewrite <- 2 append_assoc.\n      f_equal. }\n   { simpl. rewrite append_nil. reflexivity. }\n   }\n   { intro. simpl. rewrite append_nil. reflexivity. }\nQed.\n\nTheorem rev_involutive : forall (x : lst), eq (rev (rev x)) x.\nProof.\n   induction x.\n   { simpl. rewrite rev_append. simpl. f_equal.\n   assumption. }\n   { simpl. reflexivity. }\nQed.\n\nTheorem theorem0 : forall (x : lst), eq (rev (append (rev x) Nil)) x.\nProof.\n   intro.\n   rewrite append_nil.\n   apply rev_involutive.\nQed.\n\n", "meta": {"author": "artifactanon", "repo": "lfind_benchmarks_pldi22", "sha": "7bf78a4e51fede5a63911e82a38f86e61cef2aec", "save_path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22", "path": "github-repos/coq/artifactanon-lfind_benchmarks_pldi22/lfind_benchmarks_pldi22-7bf78a4e51fede5a63911e82a38f86e61cef2aec/clam/goal30.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.706216726977218}}
{"text": "Require Import QArith.\nRequire Import QArith.Qcanon.\n\nOpen Scope Qc_scope.\n\nFrom F4 Require Export misc.\n\nInductive Triple :=\n  | triple : forall (x y z : Qc), Triple.\n\nDefinition isNotZero t :=\n  match t with\n  | triple x y z => x <> 0 \\/ y <> 0 \\/ z <> 0\n  end.\n\nDefinition isOrthogonal_b (t t' : Triple) :=\n  match t, t' with\n  | triple x y z, triple x' y' z' => Qc_eq_bool (x*x' + y*y' + z*z') 0\n  end.\n\nLemma isOrthogonal_b_symmetric : forall (t t' : Triple),\n  isOrthogonal_b t t' = isOrthogonal_b t' t.\nProof.\n  intros [x y z] [x' y' z']. unfold isOrthogonal_b.\n  rewrite -> (Qcmult_comm x x').\n  rewrite -> (Qcmult_comm y y').\n  rewrite -> (Qcmult_comm z z').\n  reflexivity.\nDefined.\n\nDefinition polar (t1 t2 : Triple) : Triple :=\n  match t1, t2 with\n  | triple x1 y1 z1, triple x2 y2 z2 => triple (det2 y1 z1 y2 z2) (det2 z1 x1 z2 x2) (det2 x1 y1 x2 y2)\n  end.\n\nLemma polar_is_orthogonal : forall t t' : Triple,\n  isOrthogonal_b t (polar t t') = true /\\ isOrthogonal_b t' (polar t t') = true.\nProof.\n  intros [x y z] [x' y' z'].\n  unfold polar. unfold isOrthogonal_b. unfold det2.\n  (* It's a bit gross / brittle being so explicit with H1, H2 below. Maybe should factor through general det3 results. *)\n  assert (H1 : x * (y * z' - z * y') + y * (z * x' - x * z') + z * (x * y' - y * x') = 0). { ring. } rewrite -> H1.\n  assert (H2 : x' * (y * z' - z * y') + y' * (z * x' - x * z') + z' * (x * y' - y * x') = 0). { ring. } rewrite -> H2.\n  split; reflexivity.\nDefined.\n\nDefinition eqt_b (t1 t2 : Triple) : bool :=\n  match polar t1 t2 with\n  | triple x y z => (Qc_eq_bool x 0) && (Qc_eq_bool y 0) && (Qc_eq_bool z 0)\n  end.\n\nDefinition eqt (t1 t2 : Triple) := eqt_b t1 t2 = true.\n\nLemma eqt_refl : forall t1 t2 : Triple,\n  eqt_b t1 t2 = true <-> eqt t1 t2.\nProof. intros. unfold eqt. apply iff_refl. Defined.\n\nLemma isNotZero_equiv : forall (x y z : Qc),\n  isNotZero (triple x y z) <-> ~(x = 0 /\\ y = 0 /\\ z = 0).\nProof.\n  unfold isNotZero. intros x y z. split.\n  - intros [Hx | [Hy | Hz]]; unfold not; intros [Hx' [Hy' Hz']]; contradiction.\n  - intros H.\n    assert (Hx : x = 0 \\/ x <> 0). { apply Qc_eq_zero_dec. }\n    assert (Hy : y = 0 \\/ y <> 0). { apply Qc_eq_zero_dec. }\n    assert (Hz : z = 0 \\/ z <> 0). { apply Qc_eq_zero_dec. }\n    destruct Hx.\n    + destruct Hy.\n      * destruct Hz.\n        -- subst. exfalso. apply H. split; [reflexivity | split; reflexivity].\n        -- right. right. assumption.\n      * right. left. assumption.\n    + left. assumption.\nDefined.\n\nLemma polar_not_zero : forall t1 t2 : Triple,\n  isNotZero t1 -> isNotZero t2 -> ~eqt t1 t2 -> isNotZero (polar t1 t2).\nProof.\n  intros [x1 y1 z1] [x2 y2 z2] ev1 ev2 Hne.\n  unfold polar. rewrite -> isNotZero_equiv. unfold not. intros [Hx [Hy Hz]].\n  unfold not in Hne. apply Hne. unfold eqt. unfold eqt_b. unfold polar.\n  rewrite -> Hx. rewrite -> Hy. rewrite -> Hz.\n  reflexivity.\nDefined.\n\nLemma eqt_spec: forall (x y z x' y' z' : Qc) (ev : isNotZero (triple x y z)) (ev' : isNotZero (triple x' y' z')),\n  eqt (triple x y z) (triple x' y' z') <-> exists t, t<>0 /\\ x' = t*x /\\ y' = t*y /\\ z' = t*z.\nProof.\n  intros. subst. unfold eqt. unfold eqt_b. unfold polar. split.\n  - intros Heq. repeat (rewrite -> andb_true_iff in Heq). destruct Heq as [[Hyz Hzx] Hxy].\n    rewrite -> det2_vanish_bool in Hyz.\n    rewrite -> det2_vanish_bool in Hzx.\n    rewrite -> det2_vanish_bool in Hxy.\n    (* Alternative proof (relies on Qc having a norm via its ordering) uses:\n    exists (x*x' + y*y' + z*z' / (x*x + y*y + z*z)). *)\n    destruct (Qc_eq_bool z 0) eqn:Hz0.\n    + apply Qc_eq_bool_correct in Hz0. subst.\n      rewrite -> Qcmult_0_l in Hzx. apply symmetry in Hzx. apply Qcmult_integral in Hzx.\n      rewrite -> Qcmult_0_l in Hyz. apply Qcmult_integral in Hyz.\n      destruct (Qc_eq_bool y 0) eqn:Hy0.\n      * apply Qc_eq_bool_correct in Hy0. subst.\n        rewrite -> Qcmult_0_l in Hxy. apply Qcmult_integral in Hxy.\n        assert (Hx : x <> 0). {\n          unfold isNotZero in ev.\n          destruct ev as [H | [H | H]]; [assumption | contradiction | contradiction].\n        }\n        exists (x'/x). rewrite -> Qcmult_0_r. split.\n        -- assert (Hy' : y' = 0). { destruct Hxy; [contradiction | assumption]. }\n           assert (Hz' : z' = 0). { destruct Hzx; [contradiction | assumption]. }\n           assert (Hx' : x' <> 0). { destruct ev' as [H | [H | H]]; [assumption | contradiction | contradiction]. }\n           apply Qc_quot_non_zero; assumption.\n        -- split.\n           ++ rewrite -> (test_field x' x Hx). reflexivity.\n           ++ split.\n              ** destruct Hxy; [contradiction | assumption].\n              ** destruct Hzx; [contradiction | assumption].\n      * exists (y'/y).\n        assert (Hyn0: y <>0). { apply Qc_eq_bool_correct'. assumption. } split.\n        -- apply (Qc_quot_non_zero y' y Hyn0). destruct (Qc_eq_zero_dec y') as [Hy'|Hy']; try assumption.\n           exfalso. subst. rewrite -> Qcmult_0_r in Hxy. apply symmetry in Hxy. apply Qcmult_integral in Hxy.\n           assert (Hx' : x' = 0). { destruct Hxy; [contradiction | assumption]. }\n           assert (Hz' : z' = 0). { destruct Hyz; [contradiction | assumption]. }\n           subst. destruct ev' as [H | [H | H]]; contradiction.\n        -- split.\n           ++ apply symmetry in Hxy. apply solve_det2; assumption.\n           ++ split.\n              ** rewrite -> (test_field y' y Hyn0). reflexivity.\n              ** rewrite -> Qcmult_0_r. destruct Hyz; [contradiction | assumption].\n    + exists (z'/z).\n      assert (Hzn0: z<>0). { apply Qc_eq_bool_correct'. assumption. } split.\n      * apply (Qc_quot_non_zero z' z Hzn0). destruct (Qc_eq_zero_dec z') as [Hz'|Hz']; try assumption.\n        exfalso. subst.\n        rewrite -> Qcmult_0_r in Hzx. apply Qcmult_integral in Hzx.\n        assert (Hx' : x' = 0). { destruct Hzx; [contradiction | assumption]. }\n        rewrite -> Qcmult_0_r in Hyz. apply symmetry in Hyz. apply Qcmult_integral in Hyz.\n        assert (Hy' : y' = 0). { destruct Hyz; [contradiction | assumption]. }\n        subst. destruct ev' as [H | [H | H]]; contradiction.\n      * split.\n        -- apply solve_det2; assumption.\n        -- split.\n           ** apply symmetry in Hyz. apply solve_det2; assumption.\n           ** rewrite -> (test_field z' z Hzn0). reflexivity.\n  - intros [t [Ht0 [Htx [Hty Htz]]]]. subst. unfold det2.\n    repeat (apply andb_true_intro; (try split)); rewrite -> Qc_eq_bool_correct'''; ring.\nDefined.\n\nInductive Point :=\n  | point : forall t : Triple, isNotZero t -> Point.\n\nInductive Line :=\n  | line : forall t : Triple, isNotZero t -> Line.\n\nDefinition eqp_b (p1 p2 : Point) :=\n  match p1, p2 with\n  | point t1 _, point t2 _ => eqt_b t1 t2\n  end.\n\nDefinition eqp (p1 p2 : Point) := eqp_b p1 p2 = true.\n\nDefinition eql_b (l1 l2 : Line) :=\n  match l1, l2 with\n  | line t1 _, line t2 _ => eqt_b t1 t2\n  end.\n\nDefinition eql (l1 l2 : Line) := eql_b l1 l2 = true.\n\nLemma eql_refl : forall l1 l2 : Line,\n  eql_b l1 l2 = true <-> eql l1 l2.\nProof. intros. unfold eql. apply iff_refl. Defined.\n\nLemma eqt_b_symmetric : forall t t' : Triple,\n  eqt_b t t' = eqt_b t' t.\nProof.\n  intros [x y z] [x' y' z']. unfold eqt_b. simpl.\n  rewrite -> (det2_vanishing_symmetry y z y' z').\n  rewrite -> (det2_vanishing_symmetry z x z' x').\n  rewrite -> (det2_vanishing_symmetry x y x' y').\n  reflexivity.\nDefined.\n\nCorollary eqp_symmetric : forall p p' : Point,\n  eqp p p' <-> eqp p' p.\nProof.\n  intros [t ev] [t' ev']. unfold eqp. unfold eqp_b. rewrite -> eqt_b_symmetric. reflexivity.\nDefined.\n\nCorollary eql_symmetric : forall l l' : Line,\n  eql l l' <-> eql l' l.\nProof.\n  intros [t ev] [t' ev']. unfold eql. unfold eql_b. rewrite -> eqt_b_symmetric. reflexivity.\nDefined.\n\nLemma eqt_transitive : forall (t t' t'' : Triple) (ev : isNotZero t) (ev' : isNotZero t') (ev'' : isNotZero t''),\n  eqt t t' -> eqt t' t'' -> eqt t t''.\nProof.\n  intros [x y z] [x' y' z'] [x'' y'' z''] ev ev' ev'' Heq Heq'.\n  rewrite -> (eqt_spec _ _ _ _ _ _ ev ev') in Heq.\n  rewrite -> (eqt_spec _ _ _ _ _ _ ev' ev'') in Heq'.\n  rewrite -> (eqt_spec _ _ _ _ _ _ ev ev'').\n  destruct Heq as [t [Ht [Hx [Hy Hz]]]].\n  destruct Heq' as [t' [Ht' [Hx' [Hy' Hz']]]].\n  exists (t' * t).\n  repeat split.\n  - unfold not. intros contra. apply Qcmult_integral in contra. destruct contra; contradiction.\n  - rewrite <- Qcmult_assoc. rewrite <- Hx. assumption.\n  - rewrite <- Qcmult_assoc. rewrite <- Hy. assumption.\n  - rewrite <- Qcmult_assoc. rewrite <- Hz. assumption.\nDefined.\n\nCorollary eql_transitive : forall l l' l'' : Line,\n  eql l l' -> eql l' l'' -> eql l l''.\nProof.\n  intros [t ev] [t' ev'] [t'' ev'']. unfold eql. unfold eql_b. repeat (rewrite -> eqt_refl). apply eqt_transitive; assumption.\nDefined.\n\nDefinition isPointOnLine_b (p : Point) (l : Line) : bool :=\n  match p, l with\n  | point t _, line t' _ => isOrthogonal_b t t'\n  end.\n\nDefinition isPointOnLine (p : Point) (l : Line) := isPointOnLine_b p l = true.\n\nLemma isPointOnLine_refl : forall (p : Point) (l : Line),\n  isPointOnLine_b p l = true <-> isPointOnLine p l.\nProof. intros. unfold isPointOnLine. apply iff_refl. Defined.\n\nLemma incidence_equality_compatible : forall t1 t1' t2 : Triple,\n  isNotZero t1 -> isNotZero t1' -> eqt t1 t1' -> isOrthogonal_b t1 t2 = true -> isOrthogonal_b t1' t2 = true.\nProof.\n  intros [x y z] [x' y' z'] [u v w] Hn0 Hn0' Heq Hinc.\n  rewrite -> (eqt_spec x y z x' y' z' Hn0 Hn0') in Heq.\n  destruct Heq as [t [Ht [Hx [Hy Hz]]]]. subst.\n  simpl in Hinc. apply Qc_eq_bool_correct in Hinc.\n  simpl. assert (H : t * x * u + t * y * v + t * z * w = t * (x * u + y * v + z * w)). { ring. }\n  rewrite -> H. rewrite -> Hinc. rewrite Qcmult_0_r. reflexivity.\nDefined.\n\nCorollary equal_points_on_line : forall (p p' : Point) (l : Line),\n  eqp p p' -> isPointOnLine p l -> isPointOnLine p' l.\nProof.\n  intros [t1 evT1] [t1' evT1'] [t2 evT2] Heq Hinc.\n  unfold eqp in Heq. unfold isPointOnLine in Hinc. unfold isPointOnLine_b in Hinc.\n  unfold isPointOnLine. unfold isPointOnLine_b.\n  apply (incidence_equality_compatible t1 t1' t2 evT1 evT1' Heq Hinc).\nDefined.\n\nCorollary equal_lines_contain_same_points : forall (l l' : Line) (p : Point),\n  eql l l' -> isPointOnLine p l -> isPointOnLine p l'.\nProof.\n  intros [t1 evT1] [t1' evT1'] [t2 evT2] Heq Hinc.\n  unfold eql in Heq. unfold isPointOnLine in Hinc. unfold isPointOnLine_b in Hinc.\n  unfold isPointOnLine. unfold isPointOnLine_b.\n  rewrite isOrthogonal_b_symmetric in Hinc.  rewrite isOrthogonal_b_symmetric.\n  apply (incidence_equality_compatible t1 t1' t2 evT1 evT1' Heq Hinc).\nDefined.\n\nCorollary line_pair_distinct_point : forall (p : Point) (l l' : Line),\n  isPointOnLine p l -> ~isPointOnLine p l' -> ~eql l l'.\nProof.\n  unfold not. intros p l l' H H' Heq. apply H'. apply (equal_lines_contain_same_points l l' p Heq H).\nDefined.\n\nInductive LinePair :=\n  | linePair : forall (l l' : Line), ~eql l l' -> LinePair.\n\nInductive PointPair :=\n  | pointPair : forall (p p' : Point), ~eqp p p' -> PointPair.\n\nDefinition linePairIntersection (lp : LinePair) : Point :=\n  match lp with\n  | linePair (line t evT) (line t' evT') evLp => point (polar t t') (polar_not_zero t t' evT evT' evLp)\n  end.\n\nDefinition pointPairLine (pp : PointPair) : Line :=\n  match pp with\n  | pointPair (point t evT) (point t' evT') evPp => line (polar t t') (polar_not_zero t t' evT evT' evPp)\n  end.\n\nLemma intersection_on_lines : forall (l l' : Line) (ev : ~eql l l'),\n  isPointOnLine (linePairIntersection (linePair l l' ev)) l /\\\n  isPointOnLine (linePairIntersection (linePair l l' ev)) l'.\nProof.\n  intros [t evT] [t' evT'] Hne.\n  unfold linePairIntersection. unfold isPointOnLine. unfold isPointOnLine_b.\n  rewrite (isOrthogonal_b_symmetric _ t). rewrite (isOrthogonal_b_symmetric _ t').\n  apply polar_is_orthogonal.\nDefined.\n\nLemma end_points_on_line : forall (p p' : Point) (ev : ~eqp p p'),\n  isPointOnLine p (pointPairLine (pointPair p p' ev)) /\\\n  isPointOnLine p' (pointPairLine (pointPair p p' ev)).\nProof.\n  intros [t evT] [t' evT'] Hne.\n  unfold pointPairLine. unfold isPointOnLine. unfold isPointOnLine_b. apply polar_is_orthogonal.\nDefined.\n\nLemma two_points_characterise_line' : forall (l : Line) (p q : Point) (evDistinct : ~eqp p q),\n  isPointOnLine p l -> isPointOnLine q l -> eql l (pointPairLine (pointPair p q evDistinct)).\nProof.\n  intros [[x y z] evl] [[u v w] ev] [[u' v' w'] ev'] evDistinct evInc evInc'.\n  unfold isPointOnLine in evInc. simpl in evInc. apply Qc_eq_bool_correct in evInc.\n  unfold isPointOnLine in evInc'. simpl in evInc'. apply Qc_eq_bool_correct in evInc'.\n  unfold pointPairLine. unfold polar. unfold eql. unfold eql_b. unfold eqt_b. unfold polar. unfold det2.\n  assert (Hx : y * (u*v' - v*u') - z * (w*u' - u*w') = u * (u'*x + v'*y + w'*z) - u' * (u*x + v*y + w*z)). { ring. }\n  assert (Hy : z * (v*w' - w*v') - x * (u*v' - v*u') = v * (u'*x + v'*y + w'*z) - v' * (u*x + v*y + w*z)). { ring. }\n  assert (Hz : x * (w*u' - u*w') - y * (v*w' - w*v') = w * (u'*x + v'*y + w'*z) - w' * (u*x + v*y + w*z)). { ring. }\n  rewrite -> Hx. rewrite -> Hy. rewrite -> Hz. rewrite -> evInc. rewrite -> evInc'.\n  repeat (rewrite -> Qcmult_0_r). repeat (rewrite -> Qcmult_0_l). reflexivity.\nDefined.\n\nCorollary two_points_characterise_line : forall (l l' : Line) (p q : Point) (evDistinct : ~eqp p q),\n  isPointOnLine p l -> isPointOnLine q l -> isPointOnLine p l' -> isPointOnLine q l' -> eql l l'.\nProof.\n  intros l l' p q Hpq Hp Hq Hp' Hq'.\n  assert (Hl := two_points_characterise_line' l p q Hpq Hp Hq).\n  assert (Hl' := two_points_characterise_line' l' p q Hpq Hp' Hq'). rewrite -> eql_symmetric in Hl'.\n  apply (eql_transitive l _ l' Hl Hl').\nDefined.\n\nDefinition isAffine_b p :=\n  match p with\n  | point (triple x y z) _ => negb (Qc_eq_bool z 0)\n  end.\n\nDefinition isAffine p := isAffine_b p = true.\n\nInductive LineSeg :=\n  | lineSeg : forall (p q : Point), ~eqp p q -> isAffine p -> isAffine q -> LineSeg.\n\nDefinition lineFromLineSeg (ls : LineSeg) :=\n  match ls with\n  | lineSeg p p' evDistinct evAff evAff' => pointPairLine (pointPair p p' evDistinct)\n  end.\n\nDefinition dotProd2 (x1 y1 x2 y2 : Qc) := x1*x2 + y1*y2.\n\nDefinition isPointOnLineSeg_b (p : Point) (l : LineSeg) : bool :=\n  match (isAffine_b p && isPointOnLine_b p (lineFromLineSeg l)) with\n  | false => false\n  | true => match p, l with\n    | point (triple x y z) _, lineSeg (point (triple x1 y1 z1) _) (point (triple x2 y2 z2) _) _ _ _ =>\n      let u := x/z - x1/z1 in\n      let v := y/z - y1/z1 in\n      let u' := x2/z2 - x1/z1 in\n      let v' := y2/z2 - y1/z1 in\n      let t := dotProd2 u v u' v' / (dotProd2 u' v' u' v') in\n        (Qc_lt_bool 0 t) && (Qc_lt_bool t 1)\n    end\n  end.\n\nDefinition isPointOnLineSeg (p : Point) (l : LineSeg) := isPointOnLineSeg_b p l = true.\n\nLemma isPointOnLineSeg_refl : forall (p : Point) (l : LineSeg),\n  isPointOnLineSeg_b p l = true <-> isPointOnLineSeg p l.\nProof. intros. unfold isPointOnLineSeg. apply iff_refl. Defined.\n\nDefinition det3pt p q r :=\n  match p, q, r with\n  | point (triple a b c) _,\n    point (triple d e f) _,\n    point (triple g h i) _ =>\n      det3 a b c\n           d e f\n           g h i\n  end.\n\nLemma det3pt_permute : forall p q r : Point,\n  det3pt p q r = det3pt r p q.\nProof.\n  intros [[x1 y1 z1] ev1] [[x2 y2 z2] ev2] [[x3 y3 z3] ev3].\n  simpl. unfold det3. unfold det2. ring.\nDefined.\n\nLemma det3pt_permute_sign : forall p q r : Point,\n  det3pt p q r = -det3pt p r q.\nProof.\n  intros [[x1 y1 z1] ev1] [[x2 y2 z2] ev2] [[x3 y3 z3] ev3].\n  unfold det3pt. unfold det3. unfold det2. ring.\nDefined.\n\nLemma point_on_line_seg_det : forall (p1 p2 p3 : Point) (evL : ~eqp p2 p3),\n  det3pt p1 p2 p3 = 0 <-> isPointOnLine p1 (pointPairLine (pointPair p2 p3 evL)).\nProof.\n  intros [[x1 y1 z1] ev1] [[x2 y2 z2] ev2] [[x3 y3 z3] ev3] evL.\n  unfold isPointOnLine. unfold isPointOnLine_b. unfold pointPairLine. unfold isOrthogonal_b. unfold polar. unfold det3pt.\n  rewrite -> Qc_eq_bool_correct'''. unfold det3. apply iff_refl.\nDefined.\n\nDefinition lineSegMeetsLine_b ls l (evLp : ~eql (lineFromLineSeg ls) l) :=\n  let lp := linePair (lineFromLineSeg ls) l evLp in\n    isPointOnLineSeg_b (linePairIntersection lp) ls.\n\nDefinition lineSegMeetsLineSeg_b (l m : LineSeg) : bool.\nrefine (\n  let sameLine := eql_b (lineFromLineSeg l) (lineFromLineSeg m) in\n    match sameLine as sameLine' return (sameLine = sameLine' -> _) with\n    | true => fun _ => false\n    | false => fun evDistinct => (lineSegMeetsLine_b l (lineFromLineSeg m) _) && (lineSegMeetsLine_b m (lineFromLineSeg l) _)\n    end (eq_refl sameLine)\n);\n  [| rewrite eql_symmetric];\n  unfold not; intros contra; rewrite <- eql_refl in contra;\n  unfold sameLine in evDistinct; rewrite -> evDistinct in contra;\n  inversion contra.\nDefined.\n\nDefinition lineSegMeetsLineSegClosed_b (l m : LineSeg) :=\n  match l, m with\n  | lineSeg p q _ _ _, lineSeg p' q' _ _ _ =>\n    lineSegMeetsLineSeg_b l m ||\n    isPointOnLineSeg_b p m || isPointOnLineSeg_b q m ||\n    isPointOnLineSeg_b p' l || isPointOnLineSeg_b q' l ||\n    eqp_b p p' || eqp_b p q' || eqp_b q p' || eqp_b q q'\n  end.\n\nDefinition flipLineSeg (l : LineSeg) : LineSeg.\nrefine (\n  match l with\n  | lineSeg p p' evNe evAff evAff' => lineSeg p' p _ evAff' evAff\n  end\n).\n  rewrite eqp_symmetric. assumption.\nDefined.\n\nLemma flipped_line_seg_same_line : forall l : LineSeg,\n  eql (lineFromLineSeg (flipLineSeg l)) (lineFromLineSeg l).\nProof.\n  intros [[[x y z] evT] [[x' y' z'] evT'] evNe evAff evAff'].\n  unfold flipLineSeg. unfold lineFromLineSeg. unfold pointPairLine.\n  unfold eql. unfold eql_b. unfold eqt_b. unfold polar.\n  repeat (rewrite andb_true_iff; split); apply Qc_eq_bool_correct'''; unfold det2; ring.\nDefined.\n", "meta": {"author": "ocfnash", "repo": "Closed-Fences", "sha": "84774b5c1e114f4197f265f1dba592a991f827ae", "save_path": "github-repos/coq/ocfnash-Closed-Fences", "path": "github-repos/coq/ocfnash-Closed-Fences/Closed-Fences-84774b5c1e114f4197f265f1dba592a991f827ae/coq/geometry.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7905303137346444, "lm_q1q2_score": 0.7061881695210838}}
{"text": "Module StandardLib.\n\nDefinition comp {A B C} (f: B -> C) (g: A -> B) := fun x => f (g x).\nDefinition id {A:Type} : A -> A := fun a => a.\n\nDefinition curry {A B C} : (A -> B -> C) -> (A * B) -> C :=\n  fun f '(a, b) => f a b.\nDefinition uncurry {A B C} : (A * B -> C) -> A -> B -> C :=\n  fun f a b => f (a, b).\n\nDefinition fun_eq {A B} (f g: A -> B) := forall a, f a = g a.\n\nNotation \"f \\o g\" := (comp f g)\n  (at level 50, left associativity).\n\nNotation \"f =1 g\" := (fun_eq f g) (at level 50).\n\nEnd StandardLib.\n\nModule StandardCat.\nImport StandardLib.\n\nDefinition iso {A B} (f: A -> B) :=\n  exists g, f \\o g =1 id /\\ exists h, h \\o f =1 id.\n\nDefinition eiso A B := exists f, @iso A B f.\n\nEnd StandardCat.", "meta": {"author": "mxxun", "repo": "coq-drabbles", "sha": "4e686bc7664977d4612d029a62c6b27bb42fea71", "save_path": "github-repos/coq/mxxun-coq-drabbles", "path": "github-repos/coq/mxxun-coq-drabbles/coq-drabbles-4e686bc7664977d4612d029a62c6b27bb42fea71/monads/StdLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7061603557175856}}
{"text": "Require Import XR_R.\nRequire Import XR_Rle.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rmin.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rmin_case_strong : forall r1 r2 (P:R -> Type), \n  (r1 <= r2 -> P r1) -> (r2 <= r1 -> P r2) -> P (Rmin r1 r2).\nProof.\n  intros x y p px py.\n  unfold Rmin.\n  destruct (Rle_dec x y) as [ hminl | hminr ].\n  {\n    apply px.\n    exact hminl.\n  }\n  {\n    apply py.\n    left.\n    apply Rnot_le_lt.\n    exact hminr.\n  }\nQed.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rmin_case_strong.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.7061603484764878}}
{"text": "(** Coq coding by choukh, July 2022 **)\n\nRequire Export Meta.\nRequire Import Setoid.\n\nClass 等价关系 (T : Type) := {\n  R : T → T → Prop;\n  R等价 : Equivalence R\n}.\n\nArguments R _ {_} _ _.\nGlobal Existing Instance R等价.\n\nNotation \"a ≡{ T } b\" := (@R T _ a b) (format \"a  ≡{ T }  b\", at level 70).\n\nGlobal Instance 自然数同一性 : 等价关系 ℕ := {| R := eq |}.\n\nGlobal Instance 布尔值同一性 : 等价关系 bool := {| R := eq |}.\n\nGlobal Instance 命题外延 : 等价关系 Prop := {| R := iff |}.\n\nGlobal Instance 函数外延 {A B} `{等价关系 B} : 等价关系 (A → B).\nProof.\n  exists (λ f g : A → B, ∀ x, f x ≡{B} g x). split.\n  - intros f x. reflexivity.\n  - intros f g fg x. now symmetry.\n  - intros f g h fg gh x. now transitivity (g x).\nDefined.\n\nGlobal Instance 共值域 {A B} : 等价关系 (A → B?).\nProof.\n  exists (λ f g, ∀ x, (∃ n, f n = Some x) ↔ (∃ n, g n = Some x)). split.\n  - intros f x. reflexivity.\n  - intros f g fg x. now symmetry.\n  - intros f g h fg gh x. now transitivity (∃ n : A, g n = Some x).\nDefined.\n\nNotation \"f ≡{ran} g\" := (@R _ 共值域 f g) (format \"f  ≡{ran}  g\", at level 80).\n", "meta": {"author": "choukh", "repo": "ReverseMaths", "sha": "e005fea24e0ab28aecf5bb41078a72c3436e7a4f", "save_path": "github-repos/coq/choukh-ReverseMaths", "path": "github-repos/coq/choukh-ReverseMaths/ReverseMaths-e005fea24e0ab28aecf5bb41078a72c3436e7a4f/Preliminaries/Equivalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7060976558362606}}
{"text": "(** Context: verification of cryptographic protocols using formal methods\n    Goals: 1. define -in a nice way- the term algebra used to model messages\n             exchanged by protocols.\n             -> Basically a \\Sigma-algebra equipped with an equational theory\n                NOT necessarily convergent (e.g., xor is assoc+comm).\n           2. define the notion of *static equivalence* (crucial in security)\n              -> Basically a symetric predicate over sequences S1 S2 of terms\n                 saying that S1 S2 have same length and we cannot build two\n                 terms M M' whose atoms are positions in S1 such that\n                 M S1 = M S1 but M S2 \\neq M' S2 (modulo the equational theory).\n           3. prove some static equivalences and non-equivalences \n           4. see what can be automatized using tactics. *)                 \n\n(**  ======= Σ-ALGEBRA ========\nDefinition of a specific \\Sigma-algebra (Σ = {hash/1;xor/2}):\n   Var : countably many variables\n   Name : countably many names (intuitively terms that look random and not\n          known from the attacker)\n   Const : countably many constants (on paper function symbols of arity 0)\n           (intuitively terms that are publicly known)\n   N : neutral of xor (same as above)\n   Xor : intuitively eXclusive OR on bistrings\n   Hash : basically a one-way function *)\nRequire Import Setoid Morphisms.\n\n(* [NOTE] ici il faut faire un choix entre un ensemble de constante fini ou\n   infini. Dans le cas fini, le plus propre serait de définir un\n    Inductive cst := blank | ok.\n   et l'utiliser dans term. Je garde les nat car *)\nDefinition cst := nat.          (* moralement csts. 1,2,3 ... *)\nDefinition var := nat.\nDefinition name := nat.\nInductive term :=\n  | Var : var -> term\n  | Name : name -> term\n  | Const : cst -> term\n  | Hash : term -> term\n  | Xor : term -> term -> term\n  | N : term.\n(* Notations *)\nInfix \"xor\" := Xor (at level 70).\nNotation \"'h' X\" := (Hash X) (at level 60).\n(* Some keys *)\nNotation \"'k'\" := (Name 0).\nNotation \"'k1'\" := (Name 1).\nNotation \"'k2'\" := (Name 2).\n(* Some nonces (Number ONCE ~ random values) *)\nNotation \"'n'\" := (Name 3).\nNotation \"'n1'\" := (Name 4).\nNotation \"'n2'\" := (Name 5).\n(* Some constants  *)\nNotation \"'ok'\" := (Const 1).\nNotation \"'no'\" := (Const 2).\nNotation \"'error'\" := (Const 3).\nNotation \"'blank'\" := (Const 0).  (* garbage (for later) *)\n\n(**\nEquations from which the equational theory will be defined.\n(On paper, equations is a finite relation over terms without names.) *)\nInductive EqualE : term -> term -> Prop :=\n| xorAssoc : forall t1 t2 t3: term, EqualE ((t1 xor t2) xor t3) (t1 xor (t2 xor t3))\n| xorComm : forall t1 t2: term, EqualE (t1 xor t2) (t2 xor t1)\n| xorI : forall t, EqualE (t xor N) t\n| xorN : forall t, EqualE (t xor t) N.\n\n(**\nThe main equivalence relation =E we build on EqualE is (on paper):\nthe least equivalence relation containing EqualE that is stable by application\nof a constructor (ui =E vi implies f (ui ) =E f (vi) for any f ∈ Σ) and stable by substitution\n(i.e., u =E v implies uσ =E vσ for any substitution σ = {t\\x} for some variable x and term t). *)\nInductive EqE : term -> term -> Prop :=\n| Base : forall t1 t2, EqualE t1 t2 -> EqE t1 t2\n| EHash : Proper (EqE ==> EqE) Hash\n| EXor : Proper (EqE ==> EqE ==> EqE) Xor\n| Trans : forall t1 t2 t3, EqE t1 t2 -> EqE t2 t3 -> EqE t1 t3\n| Refl : forall t, EqE t t\n| Sym : forall t1 t2, EqE t1 t2 -> EqE t2 t1.\n(* <HINTS> We help Coq to understand how to deal with rewrite on EqE. *)\nExisting Instance EHash.\nExisting Instance EXor.\nInstance EqE_todo : subrelation EqualE EqE.\nProof. constructor;auto. Qed.\nInstance EqE_equivalence: Equivalence EqE.\nProof. constructor.\nintro;apply Refl.\nintro; apply Sym.\nintro;apply Trans.\nQed.\n\nInfix \"==E\" := EqualE (at level 80).\nInfix \"=E\" := EqE (at level 81).\n\n(* Small example *)\nLemma ex1 : ((Var 3 xor h(Var 6)) xor h(Var 6)) =E (Var 3).\n  transitivity  (Var 3 xor (h(Var 6) xor h(Var 6))).\n  rewrite xorAssoc;reflexivity.\n  rewrite (xorN).\n  rewrite xorI. reflexivity.\nQed.\n\n\n(** ====== STATIC EQUIVALENCE =======\nWe define what a frame is. On paper a frame is a substitution from (preserved and fresh)\n'handles' (like variables) to terms. Handles are kinds of pointers to positions in the frame.\nIntuitively, handles are used for referring to previously output terms.\nOn paper, we would define recipes on frames that are terms whose atoms are handles \n(positions in the frame) plus subsitution [recipe frame] gives a term.\nHere, we use (nat -> term) for frames (positions to terms) and define a predicate \n[subR frame recipe term] saying that [recipe frame] gives [term]. Our recipes are\nterms but subR interpret [Var n] as positions [n]. *)\nDefinition frame := nat -> term.\nInductive subR : frame -> term -> term -> Prop :=\n| Atom : forall f : frame, forall atom:nat,\n           subR f (Var atom) (f atom)\n| SConst : forall f i, subR f (Const i) (Const i)\n| SHash : forall f t1 t2, subR f t1 t2 -> subR f (h t1) (h t2) \n| SXor : forall f t11 t12 t21 t22, \n           subR f t11 t12 -> \n           subR f t21 t22 -> \n           subR f (t11 xor t21) (t12 xor t22).\n\n(**\nWe now turns to the main property we would like to prove for some frames: static equivalence.\n *)\nDefinition EqS (f1 f2 : frame) : Prop :=\n          (forall m1 m2, forall f1t1 f1t2 f2t1 f2t2,\n             subR f1 m1 f1t1 ->        (* [m1 f1 =E f1t1] *)\n             subR f1 m2 f1t2 ->        (* [m2 f1 =E f1t2] *)\n             subR f2 m1 f2t1 ->        (* [m1 f2 =E f2t1] *)\n             subR f2 m2 f2t2 ->        (* [m2 f2 =E f2t2] *)\n             ((f1t1 =E f1t2) <-> (f2t1 =E f2t2))). (* [m1 f1 =E m2 f1 <-> m1 f2 =E m2 f2] *)\n\nInfix \"~~\" := EqS (at level 80).\n\nLemma EqS_sym : forall f1 f2, EqS f1 f2 -> EqS f2 f1.\nProof.\n  admit.                        (* TODO *)\nAdmitted.\n\n(* Let's see examples of static equ. *)\nLoad data.\n(* frame1 = {k1}\n   frame1 = {k2}  *)\nDefinition NeS (f1 f2 : frame) :=\n  (forall m, forall f1t1 f2t1,\n     subR f1 m f1t1 ->        (* [m1 f1 =E f1t1] *)\n     subR f2 m f2t1 ->        (* [m1 f2 =E f2t1] *)\n     ((f1t1 =E N) <-> (f2t1 =E N))). (* [m1 f1 =E m2 f1 <-> m1 f2 =E m2 f2] *)\nLemma ex2_b : NeS frame1 frame2.\nProof.\ninduction m.\n- (* VAR *)\n  intros; split. intros H1.\n  assert (H3: v=0 \\/ not (v=0)) by admit;destruct H3 as [Hb | Hnb].\n  rewrite Hb in *.\n  inversion H;simpl in *.\n  inversion H0;simpl in *.\n  rewrite <-H3 in *.\n  rewrite <-H6 in *.\n  clear H2 H3 H4 f0 atom0 H5 H6 H7 atom f Hb.\n  Print EqE.\n  inversion H1.\n  inversion H2.\n  (* je pars dans une boucle à cause de la transitivité: induction sur les pas inductifs ....\n      MASSE DE CHOSES relous *)\n  inversion H1.\n  unfold EqE in *.  \n- (* Name *)    (* facile *)\n- (* Hash *)\n- (* Cst *)\n\n\nLemma ex2: frame1 ~~ frame2.    (* very easy one *)\nProof.\n  do 6 intro; intros S11 S12 S21 S22.\n  split; intro Eq.\n  induction m1.\n  - (* VAR *)\n    assert (H: v=0 \\/ not (v=0)) by admit;destruct H as [Hb | Hnb].\n    + (* VAR 0 =ki *)\n      rewrite Hb in *.\n      inversion S11.\n      simpl in *.\n      rewrite <-H0 in Eq.\n      clear f atom H H1 Hb H0.\n      (* ICI on veut f1t2 sous une forme 'normale' = k1.\n         Induction sur m2 sous une forme 'normale': Const, hash -> absurde.\n         xor: montrer le lemme décrit plus bas -> absurde\n         Var n ->  n=1. Et tout va bien de l'autre côté. *)\n      admit.\n    + assert (f1t1 = blank) by admit. (* devrait être OK *)\n      rewrite H in *.\n      admit. (* ici on fait comme dans le cas Var 0: 1. xor hash impossible\n                2. cas Const -> OK mais alors du côté f2 aussi\n                3. cas Var v: v=0 contredit Eq, v<>0 -> OK côté f2 aussi  *)\n  - (* NAME *)\n    inversion S11.              (* impossible (vient du fait que l'on a surchargé recettes et messages *)\n  - (* CONST *)\n    assert (c<>0) by admit.      (* le cas blank par un lemme? *)\n    assert (Const c <> blank) by admit.   \n    assert (H2: f1t1 = Const c) by admit; rewrite H2 in *; clear H2.\n    assert (H2: f2t1 = Const c) by admit; rewrite H2 in *; clear H2.\n    (* Ici encore j'ai envie de dire que Eq => f1t2 pris dans sa forme 'normale' est = Const c.\n       S12 => *)\n    admit.\n\nLemma ex2: f1 ~~ f2.\nProof.\n  apply eqS.\n  do 6 intro. intros S11 S12 S21 S22.\n  split; intro Eq.                        (* TWO SYMETRIC CASES *)\n  - \n(* Idea if the proof:\ninduction sur m1 (avec quantification sur tout le reste!): \nJe vais supposer que je peux toujours prendre des recettes sous une forme \"normale\" (attention ma théorie eq.\nne sera pas toujours orientable et convergente!). \nIci une espèce de \\xor_i (t_i) tel que t_i\\neq t_j si i\\neq j et t_i\\neq xor(_,_).\nOn a aussi la prop cruciale: t ss cette forme avec i > 1 implique que\nt \\neq_E t' pour tout t' atomique (Var ou Name).\n+ [m1 = Const i] => f1t1 = Const i\n  ===> m2 = Const i (deux cas (m1 = blank ou pas))\n  ======> f2t1 = f2t2 = Const i\n+ [m1 = Name] => impossible de dériver S11 -> absurde\n+ [m1 = Var atom] alors 4 cas selon que f1t1 = k1, h(k1 xor n1), ok ou blank\n  détaillons le cas f1t1 = h(k1 xor n1). On a donc f1t2 =E = h(k1 xor n1)\n  ==> On montre que [m2 = Var atom] en distinguant les cas sur m2 plus deux lemmes:\n      L1: h(X) =E h(Y) -> x =E Y\n      L2: not (exists m t, subR frame1 m t /\\ t =E k1 xor n1)\n+ [m1 = h(m1')] alors on distingue deux cas sur f1t1 qui est soit égal à h(k1 xor n2) soit pas.\n  Si c'est le cas alors [m1' frame =E k1 xor n2] on montre que c'est absurde.\n  Si ce n'est pas le cas alors m2 ne peut pas = Var i donc on peut montrer que m2 = h(m2') et\n  on récure sur m1'.\n+ [m1 = m11 xor m12]  => dans ce cas f1t1 est aussi un \"vrai xor\". m2 ne peut pas être un var car\n  pas de xor dans frame1. De cette façon on a que m2 a la même structure XOR que m1 on se ramène donc\n  aux atomes et hash déjà traités. \n *)\n\nAdmitted.\n", "meta": {"author": "yurug", "repo": "coqepit", "sha": "3a305c888d3e909b4525e18a16a6b5127f583e1b", "save_path": "github-repos/coq/yurug-coqepit", "path": "github-repos/coq/yurug-coqepit/coqepit-3a305c888d3e909b4525e18a16a6b5127f583e1b/projects/lhirschi/less_naive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7060976558362606}}
{"text": "(***************************************************************************)\n(* Formalization of the Chou, Gao and Zhang's decision procedure.          *)\n(* Julien Narboux (Julien@narboux.fr)                                      *)\n(* LIX/INRIA FUTURS 2004-2006                                              *)\n(* University of Strasbourg 2008                                           *)\n(***************************************************************************)\n\nRequire  Import area_method.\n\n(** Transitivity of the parallel predicate expressed constructively *)\n\nTheorem parallel_transitivity :\n forall A B C D E F : Point,\n A <> B ->\n on_parallel C D A B ->\n on_parallel E F C D ->\n parallel A B E F.\nProof.\narea_method.\nQed.\n\n(** Pseudo-transitivity of the parallel predicate expressed constructively *)\n\nTheorem parallel_pseudo_transitivity :\n forall A B C D E F : Point,\n A <> B ->\n on_parallel C D A B ->\n on_parallel E F A B ->\n parallel C D E F.\nProof.\narea_method.\nQed.\n\n(** If AB and CD are two parallel and congruent segments then\nAC is parallel to BD *)\n\nTheorem parallellogram_second_parallel :\n forall A B C D : Point,\n on_parallel_d D C A B 1 ->\n parallel A C B D.\nProof.\narea_method.\nQed.\n\n(** The construction of a parallelogram using the fact that the diagonals intersect\nin the midpoint *)\n\nTheorem parallellogram_construction :\n forall A B C D I : Point,\n is_midpoint I A C ->\n on_line_d D I B (-(1)) ->\n parallel C D A B.\nProof.\narea_method.\nQed.\n\n(** An example where a complex sequence of constructions is compiled \ninto higher level constructions to ease the elimination process *)\n\nLemma example_construction_simplification: \nforall A B C D E F G Line_3_b Line_6_b, \n on_line C A B -> \n on_parallel Line_3_b C A D -> \n inter_ll E C Line_3_b B D -> \n on_parallel Line_6_b C F A ->\n inter_ll G C Line_6_b F B  -> \n parallel E G D F.\nProof.\narea_method.\nQed.\n\nTheorem parallellogram_construction_2 :\n forall A B C D I : Point,\n is_midpoint I A C ->\n on_line_d D I B (-(1)) ->\n parallel C D A B /\\ parallel A D B C.\nProof.\narea_method.\nQed.\n\n(** We show that the diagonals of a parallelogram intersect in the midpoint *)\n\nTheorem parallelogram_midpoint : \n  forall A B C D I : Point,\n  on_parallel_d D C A B (0-1) ->\n  inter_ll  I A C B D ->\n  A<>C ->\n  A<>I -> \n  parallel A I A C ->\n  A ** I / A**C = 1 / 2.\nProof.\nam_before_field.\nintuition.\nFfield.\nQed.\n\nTheorem Prop51Hartsshornebis :\n  forall A B C D E : Point,\n  ~ Col D A C ->\n  ~ Col A B C ->\n  is_midpoint D A B ->\n  is_midpoint E A C ->\n  parallel D E B C -> \n  B <> C -> \n  D ** E / B ** C = 1 / 2.\nProof.\narea_method.\nQed.\n\n\n\n\n", "meta": {"author": "coq-contribs", "repo": "area-method", "sha": "84cab885dd166ba80049973590a1080524fd9306", "save_path": "github-repos/coq/coq-contribs-area-method", "path": "github-repos/coq/coq-contribs-area-method/area-method-84cab885dd166ba80049973590a1080524fd9306/examples_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7060976536593886}}
{"text": "Require Import Coq.Program.Basics.\n\nRequire Import Coq.Setoids.Setoid.\n\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Relations.Relation_Definitions.\n\nRequire Import Graph.\n\nDefinition incl {A} (R: relation (Graph A)) (x y : Graph A) : Prop := R (Overlay x y) y.\n\nLemma incl_antisymmetry A R `(EqG A R) x y: incl R x y -> incl R y x -> R x y.\nProof.\n  intros r r'.\n  unfold incl in r; unfold incl in r'.\n  rewrite (symmetry r).\n  rewrite (symmetry r') at 1.\n  rewrite EqG_PlusCommut.\n  reflexivity.\nQed.\n\nLemma incl_transitivity A R `(EqG A R): forall x y z, incl R x y -> incl R y z -> incl R x z.\nProof.\n  intros x y z r r'.\n  unfold incl; unfold incl in r; unfold incl in r'.\n  rewrite (symmetry r').\n  rewrite (symmetry r).\n  rewrite EqG_PlusAssoc.\n  rewrite ((EqG_PlusAssoc x x y)).\n  rewrite (plus_Idempotence x).\n  reflexivity.\nQed.\n\nLemma incl_ov_in_connect A R `(EqG A R): forall x y, incl R (Overlay x y) (Connect x y).\nProof.\n  intros x y.\n  unfold incl.\n  rewrite EqG_PlusCommut.\n  rewrite EqG_PlusAssoc.\n  rewrite (symmetry (containmentLeft x y)).\n  rewrite (symmetry (containmentRight x y)).\n  reflexivity.\nQed.\n\nLemma incl_overlay_right_cong A R `(EqG A R): forall x y z, incl R x y -> incl R (Overlay x z) (Overlay y z).\nProof.\n  intros x y z r.\n  unfold incl.\n  rewrite EqG_PlusAssoc.\n  rewrite EqG_PlusCommut.\n  rewrite EqG_PlusAssoc.\n  rewrite EqG_PlusCommut.\n  rewrite (EqG_PlusCommut z (Overlay x z)).\n  rewrite (symmetry (EqG_PlusAssoc x z z)).\n  rewrite (plus_Idempotence z).\n  unfold incl in r.\n  rewrite EqG_PlusAssoc.\n  rewrite (EqG_PlusCommut y x).\n  rewrite r.\n  reflexivity.\nQed.\n\nLemma incl_overlay_left_cong A R `(EqG A R): forall x y z, incl R x y -> incl R (Overlay z x) (Overlay z y).\nProof.\n  intros x y z r.\n  unfold incl.\n  rewrite EqG_PlusAssoc.\n  rewrite (EqG_PlusCommut (Overlay z x) z).\n  rewrite (EqG_PlusAssoc z z x).\n  rewrite (plus_Idempotence z).\n  unfold incl in r.\n  rewrite (symmetry (EqG_PlusAssoc z x y)).\n  rewrite r.\n  reflexivity.\nQed.\n\nAdd Parametric Morphism A (R: relation (Graph A)) `(EqG A R) : Overlay\n  with signature incl R ==> incl R ==> incl R\n    as overlay_incl_morph.\nProof.\n  intros x y r x' y' r'.\n  apply (incl_overlay_left_cong A R H x' y' x) in r'.\n  apply (incl_overlay_right_cong A R H x y y') in r.\n  apply (incl_transitivity A R H (Overlay x x') (Overlay x y') (Overlay y y')).\n  exact r'.\n  exact r.\nQed.\n\nLemma incl_connect_right_cong A R `(EqG A R): forall x y z, incl R x y -> incl R (Connect x z) (Connect y z).\nProof.\n  intros x y z r.\n  unfold incl.\n  rewrite (symmetry (EqG_RightDistributivity x y z)).\n  unfold incl in r.\n  rewrite r.\n  reflexivity.\nQed.\n\nLemma incl_connect_left_cong A R `(EqG A R): forall x y z, incl R x y -> incl R (Connect z x) (Connect z y).\nProof.\n  intros x y z r.\n  unfold incl.\n  rewrite (symmetry (EqG_LeftDistributivity z x y)).\n  unfold incl in r.\n  rewrite r.\n  reflexivity.\nQed.\n\nAdd Parametric Morphism A (R: relation (Graph A)) `(EqG A R) : Connect\n  with signature incl R ==> incl R ==> incl R\n    as connect_incl_morph.\nProof.\n  intros x y r x' y' r'.\n  apply (incl_connect_left_cong A R H x' y' x) in r'.\n  apply (incl_connect_right_cong A R H x y y') in r.\n  apply (incl_transitivity A R H (Connect x x') (Connect x y') (Connect y y')).\n  exact r'.\n  exact r.\nQed.\n\nLemma incl_least_elem A R `(EqG A R) : forall x, incl R Empty x.\nProof.\n  intro x.\n  unfold incl.\n  rewrite EqG_PlusCommut.\n  rewrite (id_Plus x).\n  reflexivity.\nQed.\n\nLemma ov_incl A R `(EqG A R) : forall x y z, incl R (Overlay x y) z -> incl R x z.\nProof.\n  intros x y z r.\n  unfold incl in r.\n  unfold incl.\n  rewrite (symmetry r).\n  rewrite EqG_PlusAssoc.\n  rewrite (EqG_PlusAssoc x x y).\n  rewrite (plus_Idempotence x).\n  reflexivity.\nQed.\n\nLemma co_incl_left A R `(EqG A R) : forall x y z, incl R (Connect x y) z -> incl R x z.\nProof.\n  intros x y z r.\n  unfold incl in r.\n  unfold incl.\n  rewrite (symmetry r).\n  rewrite EqG_PlusAssoc.\n  rewrite (EqG_PlusCommut x (Connect x y)).\n  rewrite (symmetry (containmentLeft x y)).\n  reflexivity.\nQed.\n\nLemma co_incl_right A R `(EqG A R) : forall x y z, incl R (Connect x y) z -> incl R y z.\nProof.\n  intros x y z r.\n  unfold incl in r.\n  unfold incl.\n  rewrite (symmetry r).\n  rewrite EqG_PlusAssoc.\n  rewrite (EqG_PlusCommut y (Connect x y)).\n  rewrite (symmetry (containmentRight x y)).\n  reflexivity.\nQed.", "meta": {"author": "nobrakal", "repo": "coq-alga", "sha": "a8d45e3b96d39b8cf79f259540ec29204ede7e5c", "save_path": "github-repos/coq/nobrakal-coq-alga", "path": "github-repos/coq/nobrakal-coq-alga/coq-alga-a8d45e3b96d39b8cf79f259540ec29204ede7e5c/src/Incl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7060976355858879}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := plus Zero (mult x y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_91_mult_succ/goal33conj86_coqofml_VQ6rxr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7060877415930575}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  mult y x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj259_coqofml_18jO9g.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7060877370752944}}
{"text": "\nSet Implicit Arguments.\n\nRequire Import FCF.\nRequire Import CompFold.\nRequire Import RndListElem.\nRequire Import Permutation.\n\nLocal Open Scope list_scope.\n\nTheorem removeFirst_In_length : \n  forall (A : Set)(eqd : EqDec A)(ls : list A)(a : A),\n    In a ls ->\n    length (removeFirst (EqDec_dec _ ) ls a) = pred (length ls).\n  \n  induction ls; intuition; simpl in *.\n  intuition; subst.\n  destruct (EqDec_dec eqd a0 a0); intuition.\n  \n  destruct (EqDec_dec eqd a0 a); subst.\n  trivial.\n  simpl.\n  rewrite IHls.\n  destruct ls; simpl in *; intuition.\n\n  trivial.\nQed.\n\nFixpoint addInAllLocations(A : Type)(a : A)(ls : list A) :=\n  match ls with\n    | nil =>  (a :: nil) :: nil\n    | a' :: ls' => \n      (a :: ls) :: map (fun x => a' :: x) (addInAllLocations a ls')\n  end.\n\nFixpoint getAllPermutations(A : Type)(ls : list A) :=\n  match ls with\n    | nil => nil :: nil\n    | a :: ls' =>\n      let perms' := getAllPermutations ls' in\n        flatten (map (addInAllLocations a) perms')\n  end.\n\nTheorem addInAllLocations_not_nil : \n  forall (A : Type) l (a : A),\n    addInAllLocations a l = nil -> False.\n\n  induction l; intuition; unfold addInAllLocations in *; simpl in *.\n  inversion H.\n  inversion H.\n\nQed.\n\nTheorem getAllPermutations_not_nil : \n  forall (A : Type)(ls : list A),\n    getAllPermutations ls = nil -> False.\n\n  induction ls; intuition; simpl in *.\n  inversion H.\n\n  case_eq (getAllPermutations ls); intuition.\n  rewrite H0 in H.\n  simpl in *.\n  apply app_eq_nil in H.\n  intuition.\n  eapply addInAllLocations_not_nil; eauto.\nQed.\n  \n\nTheorem addInAllLocations_perm : \n  forall (A : Type) x0 (a : A) ls2,\n    In ls2 (addInAllLocations a x0) ->\n    Permutation ls2 (a :: x0).\n\n  induction x0; intuition; simpl in *.\n  intuition; subst.\n  eapply Permutation_refl.\n  \n  intuition; subst.\n  eapply Permutation_refl.\n\n  eapply in_map_iff in H0.\n  destruct H0.\n  intuition; subst.\n  eapply perm_trans.\n  Focus 2.\n  eapply perm_swap.\n  eapply perm_skip.\n  eapply IHx0.\n  trivial.\n\nQed.\n\nTheorem getAllPermutations_perms : \n  forall (A : Set)(ls1 ls2 : list A),\n    In ls2 (getAllPermutations ls1) ->\n    Permutation ls1 ls2.\n\n  induction ls1; intuition; simpl in *.\n  intuition.\n  subst.\n  econstructor.\n\n  eapply in_flatten in H.\n  destruct H.\n  intuition.\n  eapply in_map_iff in H0.\n  destruct H0.\n  intuition.\n  subst.\n  eapply addInAllLocations_perm in H1.\n  eapply perm_trans.\n  Focus 2.\n  eapply Permutation_sym.\n  eauto.\n  eapply perm_skip.\n  eapply IHls1.\n  trivial.\n  \nQed.\n\nSection ShuffleList.\n\n  Variable A : Set.\n  Hypothesis A_EqDec : EqDec A.\n\n  Definition shuffle(ls : list A) :=\n    o <-$ rndListElem _ (getAllPermutations ls);\n    ret \n    match o with\n      | None => nil\n      | Some x => x\n    end.\n      \n  Theorem shuffle_perm : \n    forall (ls1 ls2 : list A),\n      In ls2 (getSupport (shuffle ls1)) ->\n      Permutation ls2 ls1.\n\n    intuition.\n    unfold shuffle in *.\n    repeat simp_in_support.\n    destruct x.\n    eapply Permutation_sym.\n    eapply getAllPermutations_perms.    \n    apply rndListElem_support in H0.\n    trivial.\n\n    apply rndListElem_support_None in H0.\n    exfalso.\n    eapply getAllPermutations_not_nil.\n    eauto.\n\n  Qed.\n\n   Fixpoint permute(ls : list A)(sigma : list nat) : list A :=\n    match sigma with\n      | nil => nil\n      | n :: sigma' => \n        match (nth_error ls n) with\n          | None => nil\n          | Some a => a :: (permute ls sigma')\n        end\n  end.\n\n   Theorem permute_length_eq : \n     forall (sigma : list nat)(ls : list A),\n       (forall n, In n sigma -> n < length ls) ->\n       length (permute ls sigma) = length sigma.\n     \n     induction sigma; intuition; simpl in *.\n     case_eq (nth_error ls a); intuition.\n     simpl.\n     f_equal.\n     eapply IHsigma; intuition.\n     \n     Theorem nth_error_not_None : \n       forall (ls : list A)(n : nat),\n         n < length ls ->\n         nth_error ls n = None -> \n         False.\n\n       induction ls; destruct n; intuition; simpl in *.\n       omega.\n       omega.\n       inversion H0.\n       eapply IHls; eauto.\n       omega.\n     Qed.\n\n     exfalso.\n     eapply nth_error_not_None.\n     eapply H.\n     intuition.\n     trivial.\n   Qed.\n   \n   Theorem shuffle_Permutation : \n     forall (ls1 ls2 : list A),\n       In ls2 (getSupport (shuffle ls1)) ->\n       Permutation ls1 ls2.\n     \n     intuition.\n\n     unfold shuffle in *.\n     repeat simp_in_support.\n     destruct x.\n     eapply rndListElem_support in H0.\n     eapply getAllPermutations_perms.\n     trivial.\n\n     eapply rndListElem_support_None in H0.\n     exfalso.\n     eapply getAllPermutations_not_nil.\n     eauto.\n\n    Qed.\n  \n    Theorem shuffle_wf : \n      forall ls,\n        well_formed_comp (shuffle ls).\n\n      intuition.\n      unfold shuffle.\n      wftac.\n      eapply rndListElem_wf.\n\n    Qed.\n\nEnd ShuffleList.\n\nDefinition RndPerm(n : nat) :=\n  shuffle _ (allNatsLt n).\n\nTheorem list_pred_map_both':\n  forall (A B C D : Set) (lsa : list A) (lsb : list B) \n    (P : C -> D -> Prop) (f : A -> C)(g : B -> D),\n  list_pred (fun (a : A) (b : B) => P (f a) (g b)) lsa lsb ->\n  list_pred P (map f lsa) (map g lsb).\n\n  intuition.\n  eapply list_pred_impl.\n  eapply list_pred_map_both.\n  eauto.\n  intuition.\n  destruct H0.\n  destruct H0.\n  intuition; subst.\n  trivial.\n\nQed.\n\nTheorem addInAllLocations_pred : \n  forall (A B : Set) (R : A -> B -> Prop) (a : list A) (b : list B),\n    list_pred R a b ->\n    forall a1 a2,\n      R a1 a2 ->\n  list_pred (list_pred R) (addInAllLocations a1 a) (addInAllLocations a2 b).\n  \n  induction 1; intuition; simpl in *.\n  \n  econstructor.\n  econstructor.\n  trivial.\n  econstructor.\n  econstructor.\n  \n\n  econstructor.\n  repeat econstructor;assumption.\n\n  eapply list_pred_map_both'.\n  eapply list_pred_impl.\n  eauto.\n  intuition.\n  econstructor; assumption.\n\nQed.\n\nTheorem getAllPermutations_pred :\n  forall (A B : Set)(R : A -> B -> Prop)(lsa : list A)(lsb : list B),\n  list_pred R lsa lsb ->\n     list_pred (list_pred R) (getAllPermutations lsa) (getAllPermutations lsb).\n\n  induction 1; intuition; simpl in *.\n  econstructor.\n  econstructor.\n  econstructor.\n\n  eapply list_pred_flatten_both.\n  eapply list_pred_map_both'.\n  eapply list_pred_impl.\n  eauto.\n  intuition.\n  \n  eapply addInAllLocations_pred; intuition.\nQed.\n\nTheorem allNats_nth_pred : \n  forall (A : Set)(ls : list A),\n   list_pred (fun (a : A) (b : nat) => nth_error ls b = Some a) ls\n     (allNatsLt (length ls)).\n\n  induction ls using rev_ind; intuition; simpl in *.\n  econstructor.\n \n  rewrite app_length.\n  simpl.\n  rewrite plus_comm.\n  simpl.\n\n  eapply list_pred_app_both.\n  eapply list_pred_impl.\n  eapply IHls.\n  intuition.\n\n  Theorem nth_error_app_Some : \n    forall (A : Set)(ls : list A) n (a a' : A),\n      nth_error ls n = Some a ->\n      nth_error (ls ++ (a' :: nil)) n = Some a.\n\n    induction ls; destruct n; intuition; simpl in *.\n    inversion H.\n    inversion H.\n\n    eapply IHls.\n    trivial.\n\n  Qed.\n\n  eapply nth_error_app_Some; intuition.\n\n  econstructor.\n\n  Theorem nth_error_app_length : \n    forall (A : Set)(ls : list A) (a : A),\n      nth_error (ls ++ (a :: nil)) (length ls) = Some a.\n\n    induction ls; intuition; simpl in *.\n    \n  Qed.\n\n  eapply  nth_error_app_length .\n\n  econstructor.\n  \nQed.\n\nTheorem permute_nth_equiv : \n  forall (A : Set)(ls : list A) a b,\n  list_pred (fun (a0 : A) (b0 : nat) => nth_error ls b0 = Some a0) a b ->\n  a = permute ls b.\n\n  induction a; inversion 1; intuition; simpl in *.\n  subst.\n  \n  rewrite H2.\n  f_equal.\n  eapply IHa.\n  trivial.\nQed.\n\nTheorem getAllPerms_permute_eq :\n  forall (A : Set)(ls : list A),\n  list_pred (fun (a : list A) (b : list nat) => a = permute ls b)\n     (getAllPermutations ls) (getAllPermutations (allNatsLt (length ls))).\n\n  intuition.\n\n  generalize (@getAllPermutations_pred _ _ (fun a b => nth_error ls b = Some a) ls (allNatsLt (length ls))) ; intros.\n  eapply list_pred_impl.\n  eapply H.\n\n  eapply allNats_nth_pred.\n\n  intuition.\n\n  eapply permute_nth_equiv.\n  trivial.\n  \nQed.\n\nTheorem rndListElem_pred : \n  forall (A B : Set)(eqda : EqDec A)(eqdb : EqDec B)(P : A -> B -> Prop)(lsa : list A)(lsb : list B),\n    list_pred P lsa lsb ->\n    comp_spec (fun a b => \n      match a with\n        | None => b = None\n        | Some a' => exists b', b = Some b' /\\ P a' b'\n      end) (rndListElem _ lsa) (rndListElem _ lsb).\n\n\n  intuition.\n  unfold rndListElem in *.\n  case_eq (length lsa); intuition.\n  erewrite <- list_pred_length_eq; eauto.\n  rewrite H0.\n  eapply comp_spec_ret; intuition.\n  \n  erewrite <- list_pred_length_eq; eauto.\n  rewrite H0.\n  comp_skip.\n  apply None.\n  apply None.\n  eapply comp_spec_ret; intuition.\n\n  case_eq (nth_option lsa b); intuition.\n\n  Theorem list_pred_nth_exists : \n    forall (A B : Set)(P : A -> B -> Prop) lsa lsb,\n      list_pred P lsa lsb ->\n      forall n a, \n        nth_option lsa n = Some a -> exists b, nth_option lsb n = Some b /\\ P a b.\n\n    induction 1; intuition; simpl in *.\n    discriminate.\n\n    destruct n.\n    inversion H1; clear H1; subst.\n    econstructor; intuition.\n\n    edestruct IHlist_pred; eauto.\n\n  Qed.\n\n  edestruct list_pred_nth_exists; eauto.\n\n  exfalso.\n  eapply nth_option_not_None; eauto.\n  apply RndNat_support_lt in H1.\n  omega.\nQed.\n\nTheorem shuffle_RndPerm_spec : \n  forall (A : Set)(eqd : EqDec A)(ls : list A),\n    comp_spec (fun a b => a = permute ls b)\n    (shuffle eqd ls)\n    (shuffle _ (allNatsLt (length ls))).\n\n  intuition.\n  unfold shuffle in *.\n  \n  comp_skip.\n  eapply rndListElem_pred.\n  eapply getAllPerms_permute_eq.\n  \n  simpl in H1.\n  eapply comp_spec_ret; intuition.\n  destruct a.\n  destruct H1.\n  intuition.\n  subst.\n  trivial.\n\n  subst.\n  simpl.\n  intuition.\nQed.\n\nTheorem shuffle_RndPerm_spec_eq : \n  forall (A : Set)(eqd : EqDec A)(ls : list A),\n    comp_spec eq\n    (shuffle eqd ls)\n    (x <-$ RndPerm (length ls); ret permute ls x).\n\n  intuition.\n  eapply comp_spec_eq_trans.\n  eapply comp_spec_eq_symm.\n  eapply comp_spec_right_ident.\n  comp_skip.\n  eapply shuffle_RndPerm_spec.\n  eapply comp_spec_ret; intuition.\n\nQed.\n\nTheorem RndPerm_In_support : \n  forall n ls, \n    In ls (getSupport (RndPerm n)) ->\n    Permutation (allNatsLt n) ls.\n  \n  intuition.\n  eapply shuffle_Permutation.\n  eapply H.\nQed.\n\n\nTheorem RndPerm_In_support_length :\n  forall n ls,\n    In ls (getSupport (RndPerm n)) ->\n    length ls = n.\n\n  intuition.\n  erewrite Permutation_length.\n  Focus 2.\n  eapply Permutation_sym.\n  eapply RndPerm_In_support.\n  eauto.\n  eapply allNatsLt_length.\nQed.\n\nTheorem RndPerm_wf : \n  forall n,\n    well_formed_comp (RndPerm n).\n\n  intuition.\n  unfold RndPerm.\n  eapply shuffle_wf.\n\nQed.", "meta": {"author": "FreeAndFair", "repo": "RLA", "sha": "4295e4bb700ebbfe69affeb35dda7ed42273c3a1", "save_path": "github-repos/coq/FreeAndFair-RLA", "path": "github-repos/coq/FreeAndFair-RLA/RLA-4295e4bb700ebbfe69affeb35dda7ed42273c3a1/src/fcf/RndPerm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7060877352246746}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Rsequence_def.\nRequire Import Rsequence_base_facts Rsequence_sums_facts.\nRequire Import Rsequence_rewrite_facts.\nRequire Import Lra.\nRequire Import MyRIneq.\t\n\nOpen Scope R_scope.\nOpen Scope Rseq_scope.\n\n(** * Boundedness compatibility. *)\n\nSection Rseq_bound_compatibilities.\n\nVariables (Un Vn : Rseq) (lu lv : R).\nHypothesis (Un_bd : Rseq_bound Un lu) (Vn_bd : Rseq_bound Vn lv).\n\nLemma Rseq_bound_eq : forall Wn, Un == Wn ->\n  Rseq_bound Wn lu.\nProof.\nintros Wn Heq n ; rewrite <- Heq ; apply Un_bd.\nQed.\n\nLemma Rseq_bound_opp : Rseq_bound (- Un) lu.\nProof.\nintro n ; unfold Rseq_opp ; rewrite Rabs_Ropp ; apply Un_bd.\nQed.\n\nLemma Rseq_bound_plus : Rseq_bound (Un + Vn) (lu + lv).\nProof.\nintro n ; unfold Rseq_plus ;\n apply Rle_trans with (Rabs (Un n) + Rabs (Vn n))%R ;\n [apply Rabs_triang | apply Rplus_le_compat ; auto].\nQed.\n\nLemma Rseq_bound_minus : Rseq_bound (Un - Vn) (lu + lv).\nProof.\nintro n ; unfold Rseq_minus, Rminus ;\n apply Rle_trans with (Rabs (Un n) + Rabs (- Vn n))%R ;\n [apply Rabs_triang | rewrite Rabs_Ropp ; apply Rplus_le_compat ; auto].\nQed.\n\nLemma Rseq_bound_mult : Rseq_bound (Un * Vn) (lu * lv).\nProof.\nintro n ; unfold Rseq_mult ; rewrite Rabs_mult ;\n apply Rmult_le_compat ; (apply Rabs_pos || auto).\nQed.\n\nLemma Rseq_bound_sum : Rseq_bound (Rseq_sum Un / Rseq_shift INR) lu.\nProof.\nintro n ; induction n ; unfold Rseq_div, Rseq_shift, Rdiv.\n simpl ; rewrite Rinv_1, Rmult_1_r ; apply Un_bd.\n rewrite Rabs_mult, Rabs_Rinv ; [| apply not_0_INR ; omega].\n apply Rmult_Rinv_le_compat ; [apply Rabs_pos_lt ; apply not_0_INR ; omega |].\n rewrite (Rabs_pos_eq (INR (S (S n)))), Rseq_sum_simpl, S_INR,\n Rmult_plus_distr_r, Rmult_1_l ; [| apply pos_INR].\n eapply Rle_trans ; [eapply Rabs_triang |] ; apply Rplus_le_compat.\n rewrite <- (Rabs_pos_eq (INR (S n))) ; [| apply pos_INR].\n apply Rmult_Rinv_le_compat_contravar ; [apply Rabs_pos_lt ; apply not_0_INR ; omega |].\n rewrite <- Rabs_Rinv, <- Rabs_mult ; [apply IHn | apply not_0_INR ; omega].\n apply Un_bd.\nQed.\n\nEnd Rseq_bound_compatibilities.\n\nLemma Rseq_bound_prod : forall (Un Vn : Rseq) (lu lv : R),\n  Rseq_bound Un lu -> Rseq_bound Vn lv ->\n  Rseq_bound ((Un # Vn) / Rseq_shift INR) (lu * lv).\nProof.\nintros Un Vn lu lv Un_bd Vn_bd n ; unfold Rseq_prod, Rseq_div ;\n apply Rseq_bound_sum ; apply Rseq_bound_mult ;\n [apply Un_bd | intro p ; apply Vn_bd].\nQed.", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/src/Reals/Rsequence/Rsequence_bound_facts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7060877280397679}}
{"text": "(*|\n#################################################\nHow can I read Coq's definition of ``proj1_sig``?\n#################################################\n\n:Link: https://stackoverflow.com/q/41461247\n|*)\n\n(*|\nQuestion\n********\n\nIn Coq, ``sig`` is defined as\n|*)\n\nPrint sig. (* .unfold .messages *)\n\n(*|\nWhich I read as\n\n    ``A sig P`` is a type, where ``P`` is a function taking an ``A``\n    and returning a ``Prop``. The type is defined such that an element\n    ``x`` of type ``A`` is of type ``sig P`` if ``P x`` holds.\n\n``proj1_sig`` is defined as\n|*)\n\nPrint proj1_sig. (* .unfold .messages *)\n\n(*|\nI'm not sure what to make of that. Could somebody provide a more\nintuitive understanding?\n\n----\n\n**A:** This `question\n<http://stackoverflow.com/questions/38777736/how-do-i-read-the-definition-of-ex-intro>`__\nis somewhat related. And `this\n<http://stackoverflow.com/questions/11593270/coq-extract-witness-from-proposition>`__\none and `this\n<http://stackoverflow.com/questions/26493911/how-to-extract-z-from-subset-type-z-z-z-0>`__.\nAlso, `this\n<http://stackoverflow.com/questions/27079513/prove-equality-on-sigma-types>`__\nquestion on equality of sigma types can be of some interest too. I've\nadded these links because the automatic ones were not too close.\n|*)\n\n(*|\nAnswer\n******\n\nNon-dependent pairs vs. ``sig``\n===============================\n\n    The type is defined such that an element ``x`` of type ``A`` is of\n    type ``sig P`` if ``P x`` holds.\n\nThat is not entirely correct: we can't say ``x : sig A P``. An\ninhabitant ``e`` of type ``sig A P`` is essentially a *pair* of an\nelement ``x : A`` and a proof that ``P x`` holds (this is called a\n`dependent pair\n<https://en.wikipedia.org/wiki/Dependent_type#Dependent_pair_type>`__).\n``x`` and ``P x`` are \"wrapped\" together using the data constructor\n``exist``.\n\nTo see this let us first consider the non-dependent pair type\n``prod``, which is defined as follows:\n|*)\n\nPrint prod. (* .unfold .messages *)\n\n(*|\n``prod``'s inhabitants are pairs, like ``pair 1 true`` (or, using\nnotations, ``(1, true)``), where the *types* of both components are\n*independent* of each other.\n\nSince ``A -> B`` in Coq is just syntactic sugar for ``forall _ : A,\nB`` (defined `here\n<https://coq.inria.fr/library/Coq.Init.Logic.html>`__), the definition\nof ``prod`` can be desugared into\n|*)\n\nInductive prod (A B : Type) : Type :=  pair : forall _ : A, B -> prod A B.\n\n(*|\nThe above definition, perhaps, can help to see that elements of ``sig\nA P`` are (dependent) pairs.\n\nWhat we can derive from implementation and type of ``proj1_sig``\n================================================================\n\nFrom the implementation we can see that ``proj1_sig e`` unpacks the\npair and returns the *first* component, viz. ``x``, throwing away the\nproof of ``P x``.\n\nThe `Coq.Init.Specif\n<https://coq.inria.fr/library/Coq.Init.Specif.html>`__ module contains\nthe following comment:\n\n    ``(sig A P)``, or more suggestively ``{x:A | P x}``, denotes the\n    subset of elements of the type ``A`` which satisfy the predicate\n    ``P``.\n\nIf we look at the type of ``proj1_sig``\n|*)\n\nCheck proj1_sig. (* .unfold *)\n\n(*|\nwe will see that ``proj1_sig`` gives us a way of recovering an element\nof a superset ``A`` from its subset ``{x : A | P x}``.\n\nAnalogue between ``fst`` and ``proj1_sig``\n==========================================\n\nAlso, we can say that in some sense ``proj1_sig`` is analogous to the\n`fst <https://coq.inria.fr/library/Coq.Init.Datatypes.html#fst>`__\nfunction, which returns the first component of a pair:\n|*)\n\nCheck @fst. (* .unfold *)\n\n(*| There is a trivial property of ``fst``: |*)\n\nGoal forall A B (a : A) (b : B),\n    fst (a, b) = a.\nProof. reflexivity. Qed.\n\n(*| We can formulate a similar statement for ``proj1_sig``: |*)\n\nGoal forall A (P : A -> Prop) (x : A) (prf : P x),\n    proj1_sig (exist P x prf) = x.\nProof. reflexivity. Qed.\n\n(*|\n----\n\n**Q:** Okay, so suppose I have an element ``x`` of ``sig P``. Is\n``proj1_sig x`` just ``x``?\n\n**A:** No, it's not. ``x`` is a \"pair\". You probably meant something\nlike this ``proj1_sig (exist P x prf) = x``, which is an analogue of\n``fst (a, b) = a``.\n|*)\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/how-can-i-read-coqs-definition-of-proj1-sig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7059397586615869}}
{"text": "Add LoadPath \".\" as PDCoq.\nRequire Export quotient_proofs. \n(* OrderedTypeEx.*)\n\n(** %{\\em Regular expressions}% are defined by the following inductive type: *) \n\n(*Generalizable All Variables.*)\n\nInductive re : Type := \n| re0 : re\n| re1 : re\n| re_sy : Z -> re\n| re_union : re -> re -> re\n| re_conc : re -> re -> re\n| re_star : re -> re.\n\n(*Generate OrderedType re.*)\nHint Constructors re : lre.\nNotation \"0\"      := re0.\nNotation \"1\"      := re1.\nNotation \"\\! s\" := (re_sy s)(at level 10).\nNotation \"x + y\"  := (re_union x y)(at level 50,left associativity).\nNotation \"x · y\"  := (re_conc x y)(at level 58,left associativity).\nNotation \"x ⋆\"    := (re_star x)(at level 45).\n\n(* Length of regular expressions *)\n\nFixpoint len_re  (r:re) : nat :=\n  match r with\n    | 0 => (S O)\n    | 1 =>  (S O)\n    | \\!_ => (S O)\n    | x + y => S (len_re x + len_re y)\n    | x · y => S (len_re x + len_re y)\n    | x ⋆ => S (len_re x)\n  end.\n\n(** Symbol-length of regular expressions *)\nReserved Notation \"|< x >|\".\nFixpoint sylen  (r:re) : nat :=\n  match r with\n    | 0 => O\n    | 1 => O\n    | \\!_ => (S O)\n    | x + y => plus (sylen x) (sylen y)\n    | x · y => plus (sylen x) (sylen y)\n    | x ⋆ => (sylen x)\n  end.\nNotation \"|< x >|\" := (sylen x).\n\nFixpoint re2rel  (x:re) : language :=\n  match x with\n    | 0 => ∅\n    | 1 => {ε}\n    | \\!a => {{a}}\n    | X + Y => (re2rel X) ∪ (re2rel Y)\n    | X · Y => (re2rel X) • (re2rel Y)\n    | X ⋆ => (re2rel X) ∗\n  end.\n\nCoercion re2rel : re >-> language.\n  \nGlobal Instance re2rel_m : Proper(eq ==> leq) re2rel.\nProof.\n  repeat red.\n  split_eq;subst;\n  eauto with lgs.\nQed.\n\nTheorem re2rel_is_RL : forall r:re, rl r.\nProof.\n  induction r;simpl;intros;try constructor;try auto.\nQed.\n\n(** Word of the language of regular expressions is well formed  *)\nLemma re_wf : forall r:re, language_wf (r).\nProof.\n  induction r;simpl;auto with lgs.\nQed.\n\n(** Decidable syntactical equality of regular expressions is available\n     (through definitional equality of $\\Coq$), and they also form an\n     ordered set. The ordering of regular expressions is a\n     lexicografical one, and is defined in the following code block:\n     *)\n\nLemma re_sy_dec : forall r1 r2:re, {r1=r2}+{r1<>r2}.\nProof.\n  decide equality;auto with zarith.\n  apply Z_eq_dec.\nQed.\n  \n  (** Determining the empty word property for regular expressions is a syntactical version of the [cases_epsilon] function.*)\n\nReserved Notation \"ε( y )\" (at level 45,right associativity).\nFixpoint c_of_re  (r:re) : bool :=\n  match r with \n    | 0 => false\n    | 1 => true\n    | \\!_ => false\n    | _⋆ => true\n    | x + y => ε(x) || ε(y)\n    | x · y => ε(x) && ε(y)\n  end\n  where \"ε( y )\" := (c_of_re y).\n\nAdd Morphism c_of_re : c_of_re_m.\nProof.\n  repeat red;intros;subst;auto.\nQed.\n\n  (** We now determine the language of [c_of_re]. This means that, when [c_of_re] returns [true] then it must \n     represent $\\{\\epsilon\\}$. Otherwise, if [c_of_re] returns [false], then it should describe the language\n     $\\emptyset$. We define [lc_of_re] as such a function, and relate it to the [cases_epsilon] function to ensure\n     its correctness *)\n  \nDefinition lc_of_re  (r:re) := if ε(r) then {ε} else ∅.\nNotation \"ε'( x )\" := (lc_of_re x)(at level 45).\n  \n\nInstance lc_of_re_m : Proper(eq ==> leq) lc_of_re.\nProof.\n  unfold lc_of_re.\n  intro;intros.\n  subst.\n  destruct(ε(y));reflexivity.\nQed.\n  \n(** Production of the re. corresponding to the emptyness of the re. given\n     as argument *)\nDefinition c_c_of_re (r:re) := if ε(r) then 1 else 0.\nNotation \"ε''( x )\" := (c_c_of_re x)(at level 45).\n\nLemma c_of_c_c_true  : \n  forall r,\n    ε(r) = true -> ε''(r) = 1.\nProof.\n  intros r H;unfold c_c_of_re;rewrite H;auto.\nQed.\n\nLemma c_of_c_c_false : \n  forall r,\n    ε(r) = false -> ε''(r) = 0.\nProof.\n  intros r H;unfold c_c_of_re;rewrite H;auto.\nQed.\n\nLemma c_c_of_c_true : \n  forall r, \n    ε''(r) = 1 -> ε(r) = true.\nProof.\n  intros r H;unfold c_c_of_re in H;destruct(ε(r));congruence. \nQed.\n\nLemma c_c_of_c_false : \n  forall r, \n    ε''(r) = 0 -> ε(r) = false.\nProof.\n  intros r H;unfold c_c_of_re in H;destruct(ε(r));congruence. \nQed.\n\nHint Resolve \n  c_of_c_c_true \n  c_of_c_c_false\n  c_c_of_c_true\n  c_c_of_c_false : res.\n\n(** Decidability of emptyness testing for an re. *)\nLemma c_of_re_dec : \n  forall r, \n    {ε(r) = false}+{ε(r) = true}.\nProof.\n  intro r;destruct(ε(r));auto.\nQed.\n\n(** Nullability and epsilon membership *)\nLemma null_eps_in_l :\n  forall r:re,\n   ε(r) = true -> [] ∈ re2rel r.\nProof.\n  induction r;simpl;intros;try congruence;auto with lgs.\n  simpl_bool;destruct H as [H1|H2];[apply IHr1 in H1|apply IHr2 in H2];\n    solve_trivial_union.\n  simpl_bool;destruct H as [H1 H2];apply IHr1 in H1;apply IHr2 in H2.\n  rewrite app_nil_end;auto with lgs.\n  constructor 1 with (n:=0%nat);simpl;auto with lgs.\nQed.\n\nLemma eps_in_l_null :\n  forall r:re,\n   [] ∈ re2rel r -> ε(r) = true.\nProof.\n  induction r;simpl;intros;try congruence;try now(inv H);auto with lgs.\n  simpl_bool;invc H;eauto.\n  simpl_bool;inv H. \n  apply app_eq_nil in H0;destruct H0;subst;eauto.\nQed.\n\nLemma not_eps_not_in_l :\n  forall r:re,\n   ε(r) = false -> ~[] ∈ re2rel r.\nProof.\n  induction r;simpl;intros;try congruence;try (now(intro H1;inv H1));\n    auto with lgs.\n  simpl_bool;destruct H as [H1 H2];intro;apply IHr1 in H1;apply IHr2 in H2;\n    inv H.\n  simpl_bool;destruct H as [H1|H2];intro;[apply IHr1 in H1|apply IHr2 in H2];\n    inv H; apply app_eq_nil in H0;destruct H0;subst;eauto.\nQed.\n\nLemma neg_not_in_conc :\n  forall r1 r2:re,\n  ~ [] ∈ (r1 • r2) -> ~[] ∈ (re2rel r1) \\/ ~[] ∈ (re2rel r2).\nProof.\n  intros r1 r2 H;destruct(c_of_re_dec r1).\n  apply not_eps_not_in_l in e;auto.\n  right;intro;apply H;apply null_eps_in_l in e;\n    rewrite app_nil_end;auto with lgs.\nQed.\n\nLemma not_in_l_not_eps :\n  forall r:re,\n   ~[] ∈ re2rel r -> ε(r) = false.\nProof.\n  induction r;simpl;intros;try congruence;try (now(intro H1;inv H1));\n    auto with lgs.\n  assert([] ∈ {ε}) by auto with lgs;contradiction.\n  apply neg_not_nil_aux_1 in H;simpl_bool;destruct H;eauto. \n  simpl_bool;apply neg_not_in_conc in H;destruct H;eauto.\n  assert([] ∈ (r ∗)) by (constructor 1 with O;simpl;eauto with lgs);\n    contradiction.\nQed.\n\nHint Resolve\n  null_eps_in_l\n  eps_in_l_null\n  not_eps_not_in_l\n  neg_not_in_conc\n  not_in_l_not_eps : res lgs.\n\n", "meta": {"author": "dmrpereira", "repo": "PDCoq", "sha": "c0f6a96177538eae3e933f35265522a5f05582fa", "save_path": "github-repos/coq/dmrpereira-PDCoq", "path": "github-repos/coq/dmrpereira-PDCoq/PDCoq-c0f6a96177538eae3e933f35265522a5f05582fa/RegExprs/reg_expr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694177, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7059397452231343}}
{"text": "(** ** induction\n\ninduction term というのは数学的帰納法を適用する tactic です。\nterm は帰納的に定義された型である必要があります。\n\ninduction が構築する証明項をみるために、a + 0 = a を証明してみましょう。\n加算 (Nat.add) は第1引数で場合分けして計算を進めます。\nこの a + 0 というのは第1引数が変数なため、その場合分けを行えず、\n計算を進めることができません。\nそのため、これを証明するには帰納法が必要になります。\n\n*)\n\nGoal forall a, a + 0 = a.\nProof.\n  intros a.\n(**\nゴール: <<a + 0 = a>>\n*)\n  Show Proof.\n(**\n証明項: <<(fun a : nat => ?Goal)>>\n\ninduction の直前では、intros で構築した関数抽象の本体がゴールとなっています。\n*)\n  induction a.\n(**\nゴール1: <<0 + 0 = 0>>\nゴール2: <<S a + 0 = S a>>\n\ninduction の直後では、a が 0 の場合のゴールと、\na が 0 でない (つまり S a の場合の) ゴールのふたつのゴールが生成されています。\n*)\n    Show Proof.\n(**\n証明項:\n<<(fun a : nat =>\n nat_ind (fun a0 : nat => a0 + 0 = a0)\n   ?Goal\n   (fun (a0 : nat) (IHa : a0 + 0 = a0) => ?Goal0@{a:=a0})\n   a)>>\n\n証明項をみると、nat_ind という関数を呼び出しており、\n引数の中には ?Goal と ?Goal0@{n:=n0} があって、\nふたつのゴールがあることがわかります。\n\nnat_ind がどんな関数なのか About でみてみましょう。\n*)\n    About nat_ind.\n(**\n<<\nnat_ind :\nforall P : nat -> Prop,\n  P 0 ->\n  (forall n : nat, P n -> P (S n)) ->\n  forall n : nat,\n  P n\n>>\n\nDisplay notations を無効にして About しなおすと以下のようになります。\n\n<<\nnat_ind :\nforall (P : forall _ : nat, Prop)\n  (_ : P O)\n  (_ : forall (n : nat) (_ : P n), P (S n))\n  (n : nat),\n  P n\n>>\n\n- 第1引数 P として nat を受け取って命題を返す関数を受けとります。\n- 第2引数に P 0 の証明を受け取ります。\n- 第3引数に n と P n の証明を受け取って P (S n) の証明を返す関数を受けとります。\n- 第4引数に n を受けとります。\n- そして、P n の証明を返します。\n\n直感的には、nat_ind は、第2引数から始めて第3引数を n 回適用したものを返すと\n理解すればよさそうです。\n\n証明項で実引数は以下のようになっています。\n\n- 第1引数: (fun a0 : nat => a0 + 0 = a0)\n- 第2引数: ?Goal\n- 第3引数: (fun (a0 : nat) (IHa : a0 + 0 = a0) => ?Goal0@{a:=a0})\n- 第4引数: a\n\n返り値の型 P n は (fun a0 : nat => a0 + 0 = a0) a すなわち a + 0 = a であり、\ninduction を行う直前のゴールと一致しています。\n\nnat_ind の第2引数の型 P 0 は (fun a0 : nat => a0 + 0 = a0) 0 すなわち 0 + 0 = 0 であり、\ninduction を行った後の最初のゴールと一致しています。\n\n0 + 0 = 0 は計算すれば左右が同じになるので reflexivity で証明できます。\n*)\n    reflexivity.\n  Show Proof.\n(**\n<<\n(fun a : nat =>\n nat_ind (fun a0 : nat => a0 + 0 = a0) eq_refl\n   (fun (a0 : nat) (IHa : a0 + 0 = a0) => ?Goal@{a:=a0}) a)\n>>\n\n最初のゴールは reflexivity で生成された eq_refl が埋まったことがわかります。\n*)\n\n(**\n次に、ふたつめのゴールにとりかかることになります。\nここでは、以下の前提が表示されています。\n<<\na : nat\nIHa : a + 0 = a\n>>\nそして、<<S a + 0 = S a>> というゴールを証明しなければなりません。\n\nnat_ind の第3引数の型 forall n : nat, P n -> P (S n) を展開すると\nforall n : nat, n + 0 = n -> S n + 0 = S n となります。\n第3引数の実引数は (fun (a0 : nat) (IHa : a0 + 0 = a0) => ?Goal0@{a:=a0}) であり、\nすでに関数抽象が2段階生成されています。\n表示されている a と IHa という前提はこの a0 と IHa に対応しています。\nゴールに @{a:=a0} と付記されているのは、\n仮引数は a0 なのに前提は a という名前になっていることを示しているのでしょう。\n\nこれを証明するにはまず simpl としてゴール内で計算を進められるところを進めてしまいます。\n*)\n  simpl.\n  Show Proof.\n(**\nゴール: <<S (a + 0) = S a>>\n証明項:\n<<(fun a : nat =>\n nat_ind (fun a0 : nat => a0 + 0 = a0) eq_refl\n   (fun (a0 : nat) (IHa : a0 + 0 = a0) => ?Goal@{a:=a0}) a)>>\n\nsimpl では計算を進めるだけで、そういう計算でたどり着ける項は等しいと考えるので、\n証明項は変わりません。\n\nsimpl の結果、ゴール内に a + 0 という IHa で書き換えられる部分が出てきたので書き換えます。\n*)\n  rewrite IHa.\n  Show Proof.\n(**\nゴール: <<S a = S a>>\n証明項:\n<<(fun a : nat =>\n nat_ind (fun a0 : nat => a0 + 0 = a0) eq_refl\n   (fun (a0 : nat) (IHa : a0 + 0 = a0) =>\n    eq_ind_r (fun n : nat => S n = S a0) ?Goal@{a:=a0} IHa) a)>>\n\nrewrite により、eq_ind_r の呼び出しが生成され、ゴールは S a = S a に変化します。\nこのゴールは両辺が等しいので、reflexivity で証明できます。\n*)\n  reflexivity.\n  Show Proof.\n(**\n証明項:\n<<(fun a : nat =>\n nat_ind (fun a0 : nat => a0 + 0 = a0) eq_refl\n   (fun (a0 : nat) (IHa : a0 + 0 = a0) =>\n    eq_ind_r (fun n : nat => S n = S a0) eq_refl IHa) a)>>\n\nゴールに eq_refl が埋まって、ゴールがなくなったのでこれで証明は終了です。\n*)\nQed.\n\n(**\ninduction が nat_ind を呼び出す関数呼び出しを構築することがわかりました。\n\nそこで、induction ではなく、apply で同じ証明項を構築してみましょう。\n*)\n\nGoal forall a, a + 0 = a.\nProof.\n  intros a.\n(**\ninduction a とするかわりに、(nat_ind (fun a0 : nat => a0 + 0 = a0)) という\n関数の呼び出しを構築します。\n第1引数を指定しているのは、指定しない場合に Coq が推論する項はこれとは異なる項になってしまうからです。\n指定しない場合については後でみてみましょう。\n*)\n  apply (nat_ind (fun a0 : nat => a0 + 0 = a0)).\n  Show Proof.\n(**\nゴール1: <<0 + 0 = 0>>\nゴール2: <<forall n : nat, n + 0 = n -> S n + 0 = S n>>\n証明項: <<(fun a : nat => nat_ind (fun a0 : nat => a0 + 0 = a0) ?Goal ?Goal0 a)>>\n\n期待通り nat_ind の呼び出しが構築されています。\ninduction とは異なり、第3引数の関数抽象は構築されていませんが、\napply は関数呼び出しを構築するものですからしょうがないでしょう。\n\n最初のゴールは reflexivity で証明できます。\n*)\n    reflexivity.\n  Show Proof.\n(**\n証明項: <<(fun a : nat => nat_ind (fun a0 : nat => a0 + 0 = a0) eq_refl ?Goal a)>>\n\ninduction による証明項と同じ証明項を作るには、\nつぎのゴールに関数抽象を作る必要があります。\nこれは intros で可能ですが、ひとつ問題なのは前提にすでに a が存在するため、\nintro a がエラーになることです。\n*)\n  Fail intro a.\n(**\nそこで、まず前提の a を消去します。\nこれには clear を使います。\n*)\n  clear a.\n  Show Proof.\n(**\n証明項: <<(fun a : nat => nat_ind (fun a0 : nat => a0 + 0 = a0) eq_refl ?Goal a)>>\nclear が前提から消去するのは、束縛された変数を前提としてアクセスできなくするというだけで、\n証明項は変わりません。\n\nこれで前提が空になったので、intros a IHa として関数抽象を2段階構築します。\n*)\n  intros a IHa.\n  Show Proof.\n(**\n<<(fun a : nat =>\n nat_ind (fun a0 : nat => a0 + 0 = a0) (@eq_refl nat 0)\n   (fun (a0 : nat) (IHa : a0 + 0 = a0) => ?Goal@{a:=a0}) a)>>\nこれで、induction a 相当の証明項を構築できました。\nあとは前と同じように証明します。\n*)\n  simpl.\n  rewrite IHa.\n  reflexivity.\nQed.\n\n(**\napply nat_ind とだけ指定した場合にどうなるかみてみましょう。\n*)\n\nGoal forall a, a + 0 = a.\nProof.\n  intros a.\n  apply nat_ind.\n  Show Proof.\n(**\nゴール1: <<a + 0 = 0>>\nゴール2: <<forall n : nat, a + 0 = n -> a + 0 = S n>>\n証明項: <<(fun a : nat => nat_ind (@eq nat (a + 0)) ?Goal ?Goal0 a)>>\n\nゴール1をみるとこれはあからさまに証明できないので、なにか間違えたことがわかります。\n\n証明項をみると、第1引数P には (@eq nat (a + 0)) が渡されています。\neq の型をみてみましょう。\n*)\nAbout eq.\n(**\n<<\neq : forall A : Type, A -> A -> Prop\n>>\n\n最初の Type 型引数 A に nat が渡されており、つぎの A (つまり nat) 型引数に a + 0 が\n渡されています。\n最後の A (つまり nat) 型引数は渡されていないので、\n結局、(@eq nat (a + 0)) は nat を受け取って Prop を返す関数となります。\nこれは nat_ind の第1引数の型とあっていますが、期待した引数ではありません。\n\ninduction は induction a というように引数を指定するので、\nその引数を利用して期待した P を作ってくれるのでしょう。\n*)\nAbort.\n\n\n\n", "meta": {"author": "akr", "repo": "coq-curry-howard", "sha": "37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5", "save_path": "github-repos/coq/akr-coq-curry-howard", "path": "github-repos/coq/akr-coq-curry-howard/coq-curry-howard-37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5/theories/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7058869461570078}}
{"text": " \nSection PropositionalLogic.\n\nVariables A B C : Prop.\n\nDefinition anb1 :\n  A /\\ B -> A\n:=\n  fun '(conj a _) => a.\n\n\nDefinition impl_trans :\n  (A -> B) -> (B -> C) -> A -> C\n:=\n  fun ab => fun bc => fun a => bc (ab a).\n\n\nDefinition HilbertS :\n  (A -> B -> C) -> (A -> B) -> A -> C\n:=\n  fun abc => fun ab => fun a => abc a (ab a).\n\n\n(* ~ A = A -> False *)\n(* ~ ~ A = (A -> False) -> False *)\n(* ~ ~ ~ A = ((A -> False) -> False) -> False *)\nDefinition DNE_triple_neg :\n  ~ ~ ~ A -> ~ A\n:=\n  fun nnna => fun a => nnna (fun a2f => a2f a).\n\n\nDefinition or_comm :\n  A \\/ B -> B \\/ A\n:=\n  fun ab =>\n    match ab with \n    | or_introl l => or_intror l\n    | or_intror r => or_introl r\n    end.\n\nEnd PropositionalLogic.\n\n\n\nSection Quantifiers.\n\nDefinition forall_conj_to (A: Type) (P Q : A -> Prop) :\n  (forall x, P x /\\ Q x) -> (forall x, Q x /\\ P x)\n:=\n  fun x_pq => fun x => \n    match x_pq x with \n    | conj p q => conj q p\n    end.\n\nDefinition forall_disj_to (A: Type) (P Q : A -> Prop) :\n  (forall x, P x \\/ Q x) -> (forall x, Q x \\/ P x)\n:=\n  fun x_pq => fun x => \n    match x_pq x with \n    | or_introl p => or_intror p\n    | or_intror q => or_introl q\n    end.\n\n\nVariable T : Type.\nVariable A : Prop.\nVariable P Q : T -> Prop.\nDefinition forall_conj_comm :\n  (forall x, P x /\\ Q x) <-> (forall x, Q x /\\ P x)\n:= \n  conj (forall_conj_to T P Q) (forall_conj_to T Q P).\n  \n\nDefinition forall_disj_comm :\n  (forall x, P x \\/ Q x) <-> (forall x, Q x \\/ P x)\n:=\n  conj (forall_disj_to T P Q) (forall_disj_to T Q P).\n\n(* (ex_intro x px -> False) -> x -> P x -> False*)\nDefinition not_exists_forall_not :\n  ~(exists x, P x) -> forall x, ~P x\n:=\n  fun (x_px2F : (@ex T P) -> False) => fun (x : T) => fun (px : P x) => \n    x_px2F (@ex_intro T P x px).\n\n\nDefinition exists_forall_not_ :\n(exists x, A -> P x) -> (forall x, ~P x) -> ~A.\nProof. Admitted.\n\n(** Extra exercise (feel free to skip): the dual Frobenius rule *)\nDefinition LEM :=\n  forall P : Prop, P \\/ ~ P.\n\nDefinition Frobenius2 :=\n  forall (A : Type) (P : A -> Prop) (Q : Prop),\n    (forall x, Q \\/ P x) <-> (Q \\/ forall x, P x).\n\n\nDefinition lem_to_frob1  : \n  (forall {Q : Prop}, Q \\/ ~ Q) -> (forall (A : Type) (P : A -> Prop) (Q : Prop), (forall x, Q \\/ P x) -> (Q \\/ forall x, P x))\n:=\n  fun lem _ _ qt => fun x2QOrPx => \n    match lem qt with \n    | or_introl q => or_introl q\n    | or_intror notQ => or_intror (fun x => match x2QOrPx x with\n      | or_intror px => px\n      | or_introl q => match notQ q with end\n      end)\n    end.\n\nDefinition lem_to_frob2 : \n  (forall (Q : Prop), Q \\/ ~ Q) -> (forall (A : Type) (P : A -> Prop) (Q : Prop), (Q \\/ forall x, P x) -> (forall x, Q \\/ P x))\n:=\n  fun lem _ _ qt => fun qOrPx => \n    match lem qt with \n    | or_introl q => (fun x => or_introl q)\n    | or_intror notQ => \n      match qOrPx with\n      | or_introl q => match notQ q with end\n      | or_intror xPx => (fun x => or_intror (xPx x))\n      end\n    end.\n\nDefinition lem_to_frob : \n  (forall (Q : Prop), Q \\/ ~ Q) -> (forall (A : Type) (P : A -> Prop) (Q : Prop), (forall x, Q \\/ P x) <-> (Q \\/ forall x, P x))\n:=\n  fun lem a p q => conj (@lem_to_frob1 lem a p q) (@lem_to_frob2 lem a p q).\n\nDefinition lem_to_Frobenius2 : LEM -> Frobenius2\n:= lem_to_frob.\n\n\nInductive prop_holds (A : Prop) : Type :=\n  | a_holds : A -> prop_holds A.\n\n\n\nDefinition frob_to_lem :\n  (forall (A : Type) (P : A -> Prop) (Q : Prop), (forall x, Q \\/ P x) <-> (Q \\/ forall x, P x))\n  ->\n  (forall (Q : Prop), Q \\/ ~ Q)\n:=\n  fun frob (tQ : Prop) =>\n    match frob (prop_holds tQ) (fun _ => False) tQ with\n    | conj fw _ => \n      match fw (fun ph => match ph with a_holds _ q => or_introl q end) with\n      | or_introl q => or_introl q\n      | or_intror xPx => or_intror (fun Q => xPx (a_holds tQ Q))\n      end\n    end.\n\n\nDefinition lem_iff_Frobenius2 :\n  LEM <-> Frobenius2\n:= conj lem_to_frob frob_to_lem.\n\n\nEnd Quantifiers.\n\n\nVariable PP : Prop.\nVariable frob: Frobenius2.\nCheck frob PP (fun _ => False) PP.\n\n\n\n\n\n\n\n(* Section ExtensionalEqualityAndComposition. *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype.\n\nVariables A B C D : Type.\n\n(** Exercise 2a *)\n(** [\\o] is a notation for function composition in MathComp, prove that it's associative *)\n\nDefinition compA (f : A -> B) (g : B -> C) (h : C -> D) :\n  (h \\o g) \\o f = h \\o (g \\o f)\n:= \n  erefl.\n\n\n(** [=1] stands for extensional equality on unary functions,\n    i.e. [f =1 g] means [forall x, f x = g x].\n    This means it's an equivalence relation, i.e. it's reflexive, symmetric and transitive.\n    Let us prove a number of facts about [=1]. *)\n\n\nSearch \"=1\".\nPrint frefl.\nPrint erefl.\nPrint eq_trans.\n\nSearch Logic.eq_refl.\nPrint Logic.eq_refl.\n\n\n(*\n\n            Parameter             Index\n                |                   |\n  Inductive eq (A : Type) (x : A) : A -> Prop :=  \n    eq_refl : eq x x\n                 | |\n             param ind\n\n  match someEq in (_ = gx)\n                   |\n                impossible to match \n      parameter, but possible to match index\n\n  Index changable durint unification\n\n*)\n\n\n(** Exercise: Reflexivity *)\nDefinition eqext_refl :\n  forall (f : A -> B), f =1 f\n:= fun f => frefl f.\n\n(** Exercise: Symmetry *)\nDefinition eqext_sym :\n  forall (f g : A -> B), f =1 g -> g =1 f\n:= fun f g efg x => match (efg x) in (_ = gx) return (gx = f x) with\n                    | erefl => erefl\n                    end.\n\n\nDefinition eqext_trans :\n  forall (f g h : A -> B), f =1 g -> g =1 h -> f =1 h.\nProof. intros. intro x. rewrite (H x). apply (H0 x). Qed.\n\nPrint eqext_trans.\n\n(** Exercise: Transitivity *)\nDefinition eqext_trans2 :\n  forall (f g h : A -> B), f =1 g -> g =1 h -> f =1 h\n:= fun f g h efg egh x =>\n    (* Imagine that after PM all \"right = side\" replaced with \"left = side\" *)\n    (* after unification \"hx\" will be replaced with \"g x\" *)\n    match (egh x) in (_ = hx) return (f x = hx) with\n    | erefl => (efg x)\n    end.\n\n\nDefinition succ_inj (n m: nat) : n.+1 = m.+1 -> n = m :=\n                        (* sm - will be replaced with (S n) during unification *)\n                                              (* Also (S n).-1 willbe calculated *)\n  fun Sn_Sm => match Sn_Sm in (_ = sm) return (n = sm.-1) with\n               | erefl => erefl\n               end.\n\nDefinition or_introl_inj (A B: Prop) (p1 p2: A) :\n  or_introl p1 = or_introl p2 :> (A \\/ B) -> p1 = p2\n:=\n  fun eq =>\n    match eq \n      in (_ = oil2)\n      return (p1 = if oil2 is or_introl p2' then p2' else p2)\n    with\n    | erefl => erefl p1\n    end.\n\n\n\n(* return clause will be calculated twice. 1 - before PM, 2 - after PM *)\nDefinition discr_bool: false = true -> False \n:=\n  fun (eq: false = true) =>\n    match eq\n      in (_      = tr)\n      return   (if tr then False else True)   (* large elimination, not possible for Prop *)\n                (*  ^  tr will be true BEFORE pattern mach *)\n    with\n    | erefl => I (* after matching, return clause will be True*)\n    end.\n\nDefinition discr_bool_r: true = false -> False \n:=\n  fun (eq: true = false) =>\n    match eq\n      in (_      = tr)\n      return   (if tr then True else False)\n    with\n    | erefl => I\n    end.\n\nLocate \"<>\".\n\n\nFail Definition neq_sym A (x y: A) :\n  x <> y -> y <> x\n:=\n  fun (neq_xy: x <> y) (eq_yx: y = x) =>\n    match eq_yx \n      in (_ = a)\n      return False\n    with\n    | erefl => neq_xy _\n    end.\n\n\nDefinition unification_test: \n  (cons 1 (cons 2 (cons 3 nil))) = app (cons 1 (cons 2 nil)) (cons 3 nil)\n:= erefl.\n\nDefinition neq_sym A (x y: A) :\n  x <> y -> y <> x\n:=\n  fun (neq_xy: x <> y) (eq_yx: y = x) =>\n    (match eq_yx \n      in (_ = a)\n      return (a <> y -> False) (* before pattern match a := x, afler a := y *)\n    with\n    | erefl => fun (neq_xy': y <> y) => neq_xy' (erefl y) (* \"a\" become \"y = y\" after patterm matching *)\n    end) neq_xy.\n\n\nDefinition congr (A B: Type) (f: A -> B) x y: \n  x = y -> f x = f y\n:=\n  fun eq_xy =>\n    match eq_xy\n      in (_ = a)\n      return (f x = f a)\n    with\n    | erefl => erefl (f x)\n    end.\n\nDefinition addn0 : forall n, n + 0 = n\n:=\n  fix rec (n: nat) : n + 0 = n :=\n    match n as a return (a + 0 = a) with (* a  will be replaced with constructors  0 and (S n') *)\n    | 0 => erefl      (* 0 + 0 = 0 *)\n                 (* (S n') + 0 = S n' *) \n    | S n' => congr nat nat S (n' + 0) n' (rec n')\n    end.\n\n\nDefinition Pred (n: nat) : Type :=\n  if n is S n' then nat else unit.\n\nDefinition predn_dep (n: nat): Pred n :=\n  if n is S n' then n' else tt.\n\nCompute Pred 0.\nCompute predn_dep 0.\n\nCompute Pred 42.\nCompute predn_dep 42.\n\nDefinition pred (n: {x: nat | ~~ (x == 0)}) : nat :=\n  match n with \n  | exist x pneq0 => predn x\n  end.\n\nDefinition pred2 (n: {x: nat | x <> 0}) : nat :=\n  match n with \n  | exist x pneq0 => predn x\n  end.\n\n\nDefinition pred3 (n: {x: nat | x <> 0}) : nat :=\n  match n with \n  | exist x pneq0 =>(match x \n                      as a \n                      return ((a = 0 -> False) -> nat)\n                     with\n                     | 0    => fun contra => match (contra erefl) with end\n                     | S x' => fun _ => x'\n                     end) pneq0\n  end.\n\n\n(** Exercise: left congruence *)\nDefinition eq_compl :\n  forall (f g : A -> B) (h : B -> C),\n    f =1 g -> h \\o f =1 h \\o g\n:=\n\n(** Exercise: right congruence *)\nDefinition eq_compr :\n  forall (f g : B -> C) (h : A -> B),\n    f =1 g -> f \\o h =1 g \\o h\n:=\n\nEnd ExtensionalEqualityAndComposition.\n\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype.\n\n(* After importing `eqtype` you need to either use a qualified name for\n`eq_refl`: `Logic.eq_refl`, or use the `erefl` notation.\nThis is because `eqtype` reuses the `eq_refl` identifier for a\ndifferent lemma.\n *)\n\nDefinition iff_is_if_and_only_if :\n  forall a b : bool, (a ==> b) && (b ==> a) = (a == b)\n:=\n\nDefinition negbNE :\n  forall b : bool, ~~ ~~ b = true -> b = true\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/comp_sci_club-formal_verif_2021/Seminar2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7058869423104419}}
{"text": "(*\n@hatsugai さんの等式論理の証明チェッカ\nhttp://www.principia-m.com/ts/0072/index-jp.html\nを自分でもやりたくて、Coq/SSReflect で「==」を「=」にReflectすることまでは考えついた。\nでも、実際には、move=>とcaseで、trueとfalseの場合分けを尽すだけで解けてしまう。\n\n曰く、\nGoal forall p q, p && q == p == q == p || q.\nProof. move=> p q. by case p; case q. Qed.\n\nGoal forall p q r, p || (q == r) == p || q == p || r.\nProof. move=> p q r. by case p; case q; case r. Qed.\n\nProofとQedを含めても、5語でできる証明チェッカですね。\nここで、「==」はbool->bool->bool 、「=」はbool->bool->Propです。\n\nこれでは、おもしろくないので、caseを使わない証明を考えよう。\n*)\n\nRequire Import ssreflect ssrbool eqtype ssrnat.\nRequire Import seq ssrfun.\n\nSection Equational_logic.\n\n  Check eq_op.                              (* == *)\n  Check eqP.                                (* reflect (?2 = ?3) (?2 == ?3) *)\n  Check _ =P _.                             (* reflect (?2 = ?3) (?2 == ?3) *)\n  \n  Check eqb.                                (* bool -> bool -> bool *)\n\n(*\n  Lemma predU1P : reflect (p = q \\/ b) ((p == q) || b).\n  Lemma pred2P : reflect (p = q \\/ z = u) ((p == q) || (z == u)).\n*)\n\n  Theorem eq_refl : forall (p : bool), p == p.\n  Proof.\n    move=> p.\n      by apply/eqP.\n  Qed.\n\n  Lemma eq_assoc : forall p q r, \n                     (p == q == r) = (p == (q == r)).\n  Proof.\n    move=> p q r.\n      by case: p; case: q; case r.\n  Qed.\n  \n  Lemma eq_sym' : forall (p q : bool), (p == q) = (q == p).\n  Proof.\n    move=> p q.\n      by case p; case q.\n  Qed.\n\n  Theorem eq_sym : forall (p q : bool), p == q == q == p.\n  Proof.\n    move=> p q.\n    rewrite eq_assoc.\n    apply/eqP. apply eq_sym'.\n  Qed.\n  \n  Lemma ne_sym' : forall (p q : bool), (p != q) = (q != p).\n  Proof.\n    move=> p q.\n      by case p; case q.\n  Qed.\n\n  Theorem ne_sym : forall (p q : bool), (p != q) == (q != p).\n    move=> p q.\n    apply/eqP. apply ne_sym'.\n  Qed.\n    \n  Lemma eq_del_true' : forall (p : bool), (true == p) = p.\n  Proof.\n    done.\n  Qed.\n\n  Theorem eq_del_true : forall (p : bool), true == p == p.\n  Proof.\n    move=> p.\n    apply/eqP.\n    apply eq_del_true'.\n  Qed.\n(*\n    move=> p.\n    split.\n    (* -> *)\n    move=> H. case H.\n    done.\n    (* <- *)\n    move/eqP=> H.\n    bq rewrite -H.\n*)\n\n  Lemma eq_del_false' : forall (p : bool), false == p = ~~p.\n  Proof.\n    done.\n  Qed.\n\n  Theorem eq_del_false : forall (p : bool), false == p = ~~p.\n  Proof.\n    done.\n  Qed.\n  \n  Theorem eq_del_true'' : forall (p : bool), reflect p (true == p).\n  Proof.\n    move=> p. case: p.\n      by apply ReflectT.\n        by apply ReflectF.\n  Qed.\n\n  Lemma eq_neg' : forall (p q : bool), ~~(p == q) = (~~p == q).\n  Proof.\n    move=> p q.\n    by case p; case q.\n  Qed.\n  \n  Theorem eq_nag : forall (p q : bool), ~~(p == q) == ~~p == q.\n  Proof.\n    move=> p q.\n      by case p; case q.\n(*\n    rewrite eq_assoc.\n    apply/eqP.\n    apply eq_neg'.\n*)\n  Qed.\n  \n  Theorem eq_false : false == ~~true.\n  Proof.\n    done.\n  Qed.\n\n  Lemma eq_notp_q' : forall p q, (~~p == q) = (p == ~~q).\n  Proof.\n    move=> p q.\n    rewrite [_ == ~~_]eq_sym'.\n    rewrite -[~~_ == _]eq_neg'.\n    rewrite -[~~_ == _]eq_neg'.\n    rewrite -ne_sym'.\n    done.\n  Qed.\n\n  Theorem eq_notp_q : forall p q, ~~p == q == p == ~~q.\n  Proof.\n    move=> p q.\n      by case p; case q.\n(*\n    rewrite eq_assoc.\n    apply/eqP.\n    apply eq_notp_q'.\n*)\n  Qed.\n\n  Lemma eq_dbl_neg' : forall p, ~~ ~~p = p.\n  Proof.\n    move=> p.\n    case p; rewrite //.\n  Qed.\n\n  Theorem eq_dbl_neg : forall p, ~~ ~~p == p.\n  Proof.\n    move=> p.\n    by case p.\n(*\n    apply/eqP.\n    apply eq_dbl_neg'.\n*)\n  Qed.\n\n  Theorem eq_or : forall p q r, p || (q == r) == p || q == p || r.\n  Proof.\n    move=> p q r.\n    by case p; case q; case r.\n  Qed.\n\n  Theorem eq_imp : forall p q, p ==> q == p || q == q.\n  Proof.\n    move=> p q.\n      by case p; case q.\n  Qed.\n\n  Theorem eq_gold_law : forall p q, p && q == p == q == p || q.\n  Proof.\n    move=> p q.\n    by case p; case q.\n  Qed.\n\nEnd Equational_logic.\n\n\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/ssr/ssr_equational_logic_case.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064587, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7058869365627616}}
{"text": "Require Import Reals.\nLocal Open Scope R_scope.\nFrom ValidSDP Require Import validsdp.\n\nLet p (x0 x1 x2 : R) :=\n  (x0 - x1)^2 + (x1 - 1)^2 + (x0 - (x2)^2)^2 + (x2 - 1)^2.\n\nLet b1 (x0 x1 x2 : R) :=\n  (x0 + 10) * (10 - x0).\n\nLet b2 (x0 x1 x2 : R) :=\n  (x1 + 10) * (10 - x1).\n\nLet b3 (x0 x1 x2 : R) :=\n  (x2 + 10) * (10 - x2).\n\nLet lb := -1/10000.\n\nTheorem p_ge_lb (x0 x1 x2 : R) :\n  b1 x0 x1 x2 >= 0 ->\n  b2 x0 x1 x2 >= 0 ->\n  b3 x0 x1 x2 >= 0 ->\n  lb <= p x0 x1 x2.\nProof.\nunfold b1, b2, b3, p, lb.\nvalidsdp.\nQed.\n", "meta": {"author": "validsdp", "repo": "validsdp", "sha": "135dd32a2b1166f357df764b469ce14e24711536", "save_path": "github-repos/coq/validsdp-validsdp", "path": "github-repos/coq/validsdp-validsdp/validsdp-135dd32a2b1166f357df764b469ce14e24711536/benchs/global/schwefel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338046748209, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.7058807417864126}}
{"text": "Require Import Labels.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\n\n(** The two point finite lattice *)\nInductive Lab2 : Set :=\n  | L : Lab2\n  | H : Lab2.\n\nInstance JoinSemiLattice_Lab2 : JoinSemiLattice Lab2 :=\n{  bot := L\n;  join l1 l2 :=\n     match l1, l2 with\n       | H, _ => H\n       | _, H => H\n       | L, L => L\n     end\n; flows l1 l2 :=\n    match l1, l2 with\n      | L, _ => true\n      | _, H => true\n      | _, _ => false\n    end\n; meet l1 l2 :=\n    match l1, l2 with\n    | L, _ => L\n    | _, L => L\n    | H, H => H\n    end\n}.\nProof.\nauto.\nintros l; destruct l; auto.\nintros l1 l2 l3; destruct l1, l2, l3; auto.\nintros l1 l2; destruct l1, l2; auto.\nby [].\nby [].\nintros l1 l2; destruct l1, l2; auto.\nintros l1 l2; destruct l1, l2; auto.\nintros l1 l2 l; destruct l1, l2, l; auto.\nDefined.\n\nInstance Lattice_Lab2 : Lattice Lab2 := { top := H }.\nProof. intros l; destruct l; auto. Defined.\n\nInstance FiniteLattice_Lab2 : FiniteLattice Lab2 := { elems := [:: L;H] }.\nProof. by case. Defined.\n", "meta": {"author": "QuickChick", "repo": "IFC", "sha": "5af8d50df56e0b169cc47d1d1dbead199f7e08c2", "save_path": "github-repos/coq/QuickChick-IFC", "path": "github-repos/coq/QuickChick-IFC/IFC-5af8d50df56e0b169cc47d1d1dbead199f7e08c2/Lab2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7057846492807117}}
{"text": "Require Import GeoCoq.Axioms.parallel_postulates.\nRequire Import GeoCoq.Tarski_dev.Annexes.saccheri.\n\nSection rah_existential_saccheri.\n\nContext `{TnEQD:Tarski_neutral_dimensionless_with_decidable_point_equality}.\n\nLemma rah__existential_saccheri : postulate_of_right_saccheri_quadrilaterals -> postulate_of_existence_of_a_right_saccheri_quadrilateral.\nProof.\n  intro rah.\n  destruct ex_saccheri as [A [B [C [D HSac]]]].\n  exists A; exists B; exists C; exists D.\n  split.\n    assumption.\n    apply (rah A B C D HSac).\nQed.\n\nEnd rah_existential_saccheri.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Meta_theory/Parallel_postulates/rah_existential_saccheri.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7056284601817971}}
{"text": "Require Import Arith Lia Unicode.Utf8.\nRequire Import Coq.Classes.RelationClasses.\n\nLemma mod_unique_rev: ∀ (a b r : nat),\n  r < b → r = a mod b →\n  exists q, a = b * q + r.\nProof.\n  intros a b r Hq Hmod.\n  exists (a / b).\n  assert (a = b * (a / b) + (a mod b)) as Heq.\n  { apply Nat.div_mod; auto. lia. }\n  rewrite <- Hmod in Heq; auto.\nQed.\n\nLemma mod_div_sub : ∀ a b c, b < a → \n  c mod (2 * a) = a + b → Nat.divide a (c - b).\nProof.\n  intros a b y Hblta H.\n  symmetry in H.\n  apply mod_unique_rev with (a:=y) (b:=2 * a) (r:=a + b) in H.\n  destruct H.\n  rewrite H.\n  assert (2 * a * x + (a + b) - b = (2 * x + 1) * a) as h by lia. rewrite h; clear h.\n  apply Nat.divide_factor_r.\n  lia.\nQed.\n\nDefinition R (x y : nat) := 0 < x -> \n  (Nat.Odd x -> 0 < y -> y mod 6 = 4 -> \n   y = 3 * x + 1 <-> (y - 1) / 3 = x) /\\\n  (Nat.Even x -> x mod 2 = 0 ->\n   y = x / 2 <-> 2 * y = x).\n\nLemma R_Reflexive_f : Reflexive R.\nProof.\n  unfold Reflexive. intros x.\n  unfold R in *. split.\n  + intros Hodd Hygt0 Hmod. \n    split.\n    - intros.\n      apply Nat.mul_cancel_l with (p:=3) (n:=((x - 1) / 3)) (m:=x); auto.\n      rewrite <- Nat.divide_div_mul_exact; lia; auto.\n    - intros h.\n      apply Nat.mul_cancel_l with (p:=3) (n:=((x - 1) / 3)) (m:=x) in h; auto.\n      rewrite <- Nat.divide_div_mul_exact in h; auto.\n      rewrite Nat.mul_comm in h.\n      rewrite Nat.div_mul in h; lia; auto.\n      apply mod_div_sub; auto.\n  + intros Heven Hmod. split.\n    - intros Hx.\n      apply Nat.mul_cancel_l with (p:=2) (n:=x) (m:=x / 2) in Hx; auto.\n      rewrite <- Nat.div_exact with (a:=x) (b:=2) in Hmod;auto; rewrite <- Hmod in Hx; auto.\n    - intros Hx.\n      symmetry.\n      apply Nat.mul_cancel_l with (p:=2) (n:=(x / 2)) (m:=x); auto.\n      rewrite <- Nat.div_exact with (a:=x) (b:=2) in Hmod; auto; rewrite <- Hmod; auto.\nQed.\n\nLemma R_Transitive_f : Transitive R.\nProof.\n  unfold Transitive. intros x y z Rxy Ryz.\n  unfold R in *.\n  split.\n  + intros Hodd Hzgt0 Hmod.\n    split.\n    - intros h.\n      apply Nat.mul_cancel_l with (p:=3) (n:=((z - 1) / 3)) (m:=x); auto.\n      rewrite <- Nat.divide_div_mul_exact; auto.\n      rewrite Nat.mul_comm; auto.\n      rewrite Nat.div_mul; auto; lia.\n      apply mod_div_sub; auto.\n    - intros h.\n      apply Nat.mul_cancel_l with (p:=3) (n:=((z - 1) / 3)) (m:=x) in h; auto.\n      rewrite <- Nat.divide_div_mul_exact in h; auto.\n      rewrite Nat.mul_comm in h.\n      rewrite Nat.div_mul in h; lia; auto.\n      apply mod_div_sub; auto.\n  + intros Heven Hmod.\n    split.\n    - intros Hx.\n      apply Nat.mul_cancel_l with (p:=2) (n:=z) (m:=x / 2) in Hx; auto.\n      rewrite <- Nat.div_exact with (a:=x) (b:=2) in Hmod; auto. rewrite Hx; auto.\n    - intros Hx.\n      symmetry.\n      apply Nat.mul_cancel_l with (p:=2) (n:=(x / 2)) (m:=z); auto.\n      rewrite <- Nat.div_exact with (a:=x) (b:=2) in Hmod; auto; rewrite <- Hmod; auto.\n  Qed.\n", "meta": {"author": "kobayashigarden", "repo": "3xp1", "sha": "7cc5a84f39c3ee9b2936b11d330858de05acaf64", "save_path": "github-repos/coq/kobayashigarden-3xp1", "path": "github-repos/coq/kobayashigarden-3xp1/3xp1-7cc5a84f39c3ee9b2936b11d330858de05acaf64/R_Reflexive_Transitive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7056209979836824}}
{"text": "(** * Poly: 다형성과 고차원 함수 *)\n\n(* 마지막 알림: 연습문제들에 대한 해답을 공개적으로 접근 가능한 곳에\n   두지 마시오. 감사합니다!!  *)\n\n(* Coq에서 일부 귀찮은 경고들을 내지 않도록 하려면: *)\nSet Warnings \"-notation-overridden,-parsing\".\nRequire Export Lists.\n\n(*** 다형성 *)\n\n(** 이 장에서 함수형 프로그래밍의 기본 개념들을 계속 발전시킨다.\n    중요한 새로운 생각은 _다형성_ (함수가 다루는 데이터의 타입에 관해\n    함수를 추상화)과 _고차원 함수_ (함수를 데이터로 다루기)이다.\n    다형성부터 시작한다.  *)\n\n(* ================================================================= *)\n(** ** 다형 리스트 *)\n\n(** 지난 두 장에서 단지 숫자 리스트를 가지고 논의해왔었다. 흥미로운 프로그램이라면 분명히\n    다른 타입의 원소들로 구성된 리스트들을 다룰 있어야 한다. 문자열 리스트, 부울 리스트,\n    리스트의 리스트 등. 각 종류의 리스트에 대해 새로운 귀납적 데이터 타입을 _정의할 수도_\n    있다. 예를 들어... *)\n\nInductive boollist : Type :=\n  | bool_nil : boollist\n  | bool_cons : bool -> boollist -> boollist.\n\n(** ... 하지만 이렇게 매번 새로 정의하는 것은 금방 지루한 일이 될\n    것이다. 왜냐하면 각 데이터 타입에 대해 다른 생성자 이름들을\n    만들어야 하기 때문이기도 하고, 더 중요한 이유는 각 새로운 데이터\n    타입 정의 별로 리스트를 다루는 함수들 ([length], [rev], 등)을 모두\n    새로운 버전을 정의해야 하기 때문이다.  \n*)\n\n(** 이런 반복을 모두 피하기 위해 콕은 _다형성_ 귀납적 타입을 정의하는\n    방법을 지원한다.  예를 들어 _다형 리스트_ 데이터 타입은 다음과\n    같다.\n\n*)\n\nInductive list (X:Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\n(** 이 정의는 이전 장의 [natlist] 정의와 똑같다. 다만 [cons] 생성자의\n    [nat] 인자를 임의의 타입 [X]로 대체하고, [X]에 대한 바인딩을\n    헤더에 추가했으며, 생성자들 타입에 [natlist]를 [list X]로 바꾼\n    것이 다르다. ([nil]과 [cons] 생성자 이름들을 재사용할 수\n    있다. 왜냐하면 [natlist] 정의는 [Module] 정의 안에 있고 이 정의는\n    현재 범위 밖에 있기 때문이다.)\n\n    [list]의 실체는 무엇일까? 한 가지 좋은 설명은 [list]는 [Type]에서\n    [Inductive] 정의로 매핑하는 _함수_라고 생각하는 것이다. 또는 달리\n    설명하자면, [list]는 [Type]에서 [Type]으로 매핑하는 함수라고\n    얘기할 수 있다. 어떤 특정 타입 [X]에 대해 [list X] 타입은 타입\n    [X]의 원소들로 구성된 리스트들의 집합을 [Inductive](귀납적으로)\n    정의한다. *)\n\nCheck list.\n(* ===> list : Type -> Type *)\n\n(** [list] 정의의 인자 [X]는 생성자 [nil]과 [cons]의 인자가 된다. 즉,\n    [nil]과 [cons]는 다형성 생성자로, 이 생성자에 만들고자 하는\n    리스트의 타입을 인자로 제공해야 한다. 예를 들어, [nil nat]은 [nat]\n    타입의 빈 리스트이다.  *)\n\nCheck (nil nat).\n(* ===> nil nat : list nat *)\n\n(** 동일한 설명으로, [cons nat]은 [list nat] 타입의 리스트에 [nat]\n    타입의 원소를 포함시킨다. 여기 자연수 3만을 포함하는 리스트를\n    구성하는 예가 있다.  \n*)\n\nCheck (cons nat 3 (nil nat)).\n(* ===> cons nat 3 (nil nat) : list nat *)\n\n(** [nil]의 타입은 무엇이 될까? 그 정의로부터 [list X] 타입을 읽을 수\n    있지만, [list]의 인자인 [X]에 무엇이 바인딩되는지 모른다. [Type ->\n    list X]으로 [X]의 의미를 설명할 수 없다. [(X : Type) -> list X]로\n    조금 더 설명할 수 있다. 이러한 상황에 대한 콕의 표기법은 [forall X\n    : Type, list X]이다.  *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\n\n(** 비슷한 상황으로, [cons]의 타입은 그 정의로부터 [X -> list X ->\n    list X]로 읽을 수 있다. 하지만 콕의 표기법으로 [X]의 의미를\n    설명하자면 [forall X, X -> list X -> list X]이다.\n    *)\n\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** (표기법에 관한 풀이: .v 파일에서 \"forall\" 한정자를 문자로\n    작성한다. 이 파일로부터 생성한 HTML 파일에서 그리고 다양한\n    통합개발환경에서 .v 파일을 보여주는 방식에서 ( 표시 방식을 적절히\n    설정하면) [forall]은 흔히 알고 있는 수학의 \"뒤집어진 A\"로\n    표시한다. 하지만 몇 군데에서는 \"forall\"를 작성하는 것을 여전히\n    보게 될 것이다.  이것은 조판 방식의 스타일일 뿐 의미에서는 차이가\n    없다.) *)\n\n(** 리스트 생성자를 사용할 때마다 타입 인자를 지정하는 것은 어색한\n    부담으로 보일 수도 있지만 이 부담을 줄이는 방법을 곧 알게 될\n    것이다. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** (여기서 [nil]과 [cons]를 명시적으로 작성해왔는데 그 이유는 새로운\n    버전의 리스트에 대해 [ [] ]과 [::] 표기법을 아직 정의하지 않았기\n    때문이다. 곧 이 표기법을 정의할 것이다.) *)\n\n(** 이제 돌아가 이전에 작성한 모든 리스트 처리 함수들의 다형성\n    버전들을 만들 수 있다.  여기 [repeat]를 예로 보면: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** [nil]과 [cons]에서와 같이 [repeat]를 사용할 때도 우선 타입 인자에\n    이 함수를 적용하고 그런 다음 이 타입의 요소(와 숫자)에 적용한다:\n    *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\n(** [repeat]를 다른 종류의 리스트를 만들기 위해 사용하려면 간단히\n    적절한 타입 인자를 지정하기만 하면 된다. *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n\nModule MumbleGrumble.\n\n(** **** 연습문제: 별 두 개 (mumble_grumble)  *)\n(** 다음 두 개의 귀납적 정의 타입들을 고려하자.  *)\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\n(** 어떤 타입 [X]에 대해 [grumble X] 타입의 원소는 다음 중 어느 것인가?\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]\n(* 여기를 채우시오 *)\n*)\n(** [] *)\n\nEnd MumbleGrumble.\n\n(* ----------------------------------------------------------------- *)\n(** *** 타입 주석 추론 *)\n\n(** [repeat] 정의를 다시 작성해보자. 이번에는 어느 인자의 타입도\n    지정하지 않을 것이다.  콕 시스템은 여전히 이 정의를 받아들일까?\n    *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** 정말로 받아들인다. 콕은 [repeat']에 어떤 타입을 매겼을지 보자: *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** [repeat]와 정확히 동일한 타입이다. 콕은 _타입 유추_를 사용하여\n    [X]의 타입, [x]의 타입, [count]의 타입이 무엇이어야 하는지 추론할\n    수 있다. 예를 들어, [X]는 [cons]에 대한 인자로서 사용되기 때문에\n    [Type]이어야 한다. 왜냐하면 [cons]는 첫 번째 인자로 [Type]을\n    기대하기 때문이다. 그리고, [count]를 [0]과 [S]로 매칭 하므로 [nat]\n    타입이어야 한다, 등등.\n\n    이 강력한 방법으로 우리는 모든 곳에 타입 주석을 항상 명시적으로\n    작성할 필요는 없다.  물론 명시적으로 타입을 작성해놓으면 문서로써\n    그리고 제대로 작성되었는지 여부를 검사하는데도 여전히 매우\n    유용하다. 여러분의 코드에서 지나치게 많이 타입 주석을 달아놓거나\n    (혼란스럽고 산만할 수 있다) 너무 적게 작성하지 않도록 (여러분의\n    코드를 이해하기 위해 독자가 머리 속으로 타입 유추를 수행해야 한다)\n    적절한 균형을 찾도록 노력해야 한다.\n     *)\n\n(* ----------------------------------------------------------------- *)\n(** *** 타입 인자 합성 *)\n\n(** 다형 타입 함수를 사용하려면 다른 인자들과 함께 타입 인자들도\n    전달해야 한다. 예를 들어, 위의 [repeat] 함수의 몸체에서 재귀\n    호출은 타입 [X]를 함께 전달해야 한다. 그러나 [repeat]의 두 번째\n    인자는 [X] 타입의 원소이기 때문에 첫 번째 인자는 오직 [X]만\n    가능하다는 것은 온전히 명백하다. 따라서 왜 우리가 이 타입 인자\n    [X]를 명시적으로 작성해야 하는가?\n\n    다행히도 콕에서는 이런 종류의 중복을 피할 수 있다. 어떠한 타입\n    인자 대신 \"묵시적 인자\" [_]를 작성할 수 있는데, 이 것은 \"콕\n    시스템에서 스스로 이 자리에 나올 것을 파악하도록 해주세요\"라고\n    해석할 수 있다. 더 정확히 설명하자면, 콕 시스템에서 [_]를 만날 때\n    그 상황에서 사용 가능한 모든 정보를 _통합_할 것이다. 적용하려는\n    함수의 타입 다른 인자들의 타입들, 적용을 하는 문맥에서 기대하는\n    타입 등등. 그 결과로 [_]를 대체할 구체적인 타입을 결정한다.\n\n    이 타입 인자 합성은 타입 주석 유추와 비슷하게 들릴 수도\n    있다. 정말로 이 두 절차는 동일한 방법에 의존한다. 아래처럼 함수의\n    어떤 인자들의 타입들을 그냥 생략하는 대신\n\n      repeat' X x count : list X :=\n\n    이 타입들을 [_]로 대체할 수도 있다.\n   \n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    이 것은 콕 시스템으로 하여금 빠진 정보를 유추하도록 지시하는\n    것이다.\n\n    묵시적 인자들을 사용하면 이 [repeat] 함수를 다음과 같이 작성할 수\n    있다: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** 이 예에서, [X] 대신 [_]를 작성하기 때문에 그다지 많이 노력을\n    줄이지 않는다.  하지만 많은 경우에 키를 누르고 코드를 읽는 면에\n    있어서 사소하지 않은 차이를 보인다. 예를 들어 숫자들을 포함하는\n    리스트 [1], [2], [3]을 작성하기를 원한다고 가정하자. 이렇게\n    작성하는 대신에...  *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...인자 합성을 사용하여 다음과 같이 작성한다:  *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** 묵시적 인자 *)\n\n(** 한 단계 더 나아가 콕 시스템으로 하여금 주어진 함수의 타입 인자들을\n    _항상_ 유추하도록 설정하여 대부분의 경우 [_]를 작성하는 것도 피할\n    수도 있다.\n\n    다음의 [Arguments] 지시어를 사용하여 함수 이름을 지정하고 그\n    함수의 인자 이름들을 나열한다. 이때 중괄호로 묶인 인자들을 묵시적\n    인자로 다루도록 지시한다. (만일 정의의 어떤 인자들에 이름이 없다면\n    보통 생성자의 경우 그러한데, 와일드카드 패턴 [_]으로 표시할 수\n    있다.)  *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** 이제 타입 인자들을 전혀 작성할 필요가 없다:  *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** 또 다른 방법으로, 함수를 선언할 때 어떤 인자를 묵시적이라고 선언할\n    수 있다.  해당 인자를 괄호 대신 중괄호로 감싸면 된다. 예를 들어:\n    *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** ([repeat''']의 재귀 호출에 타입 인자를 제공할 필요 조차도 없었음을\n     보라.  타입 인자를 제공하면 무효가 될 것이다!)\n\n    앞으로 가능하면 이 스타일을 사용할 것이지만 [Inductive] 생성자들에\n    대해서는 명시적으로 [Argument] 선언하는 것을 계속 사용할 것이다.\n    그 이유는 귀납적 타입의 인자를 묵시적으로 선언하면 그 타입 자체가\n    묵시적이 되기 때문이다. 예를 들어 [list] 타입을 다음과 같이 선언해보자:\n    *)\n\nInductive list' {X:Type} : Type :=\n  | nil' : list'\n  | cons' : X -> list' -> list'.\n\n(** [X]를 [list'] 자체를 포함하는 귀납적 정의 _전체_에 대해 묵시적으로\n    선언하기 때문에 [list' nat]이나 [list' bool] 등으로 작성하지\n    못하고 단지 [list']로 이제 작성해야 한다. 이것은 의도하지 않게\n    지나치게 나아간 것이다.\n *)\n\n(** 이제 새로운 다형 리스트에 관한 두 세 가지 표준 리스트 함수들을\n    다시 구현함으로써 마무리짓자... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity.  Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** 명시적으로 타입 인자들을 작성하기 *)\n\n(** 때때로 콕 시스템은 타입 인자를 결정하기에 충분한 주변 정보를\n    가지고 있지 않은 경우에 [Implicit]로 인자들을 선언할 때 작은\n    문제가 발생할 수 있다. 그런 경우에 콕 시스템에 직접 그 인자를 이번\n    단 한 번만 지정하기를 원할 필요가 있다. 예를 들어 다음과 같이\n    작성하는 경우에: *)\n\nFail Definition mynil := nil.\n\n(** ([Definition] 앞의 [Fail] 속성은 _어떠한_ 명령어와 함께 사용할 수\n    있다.  그 의미는 이 명령어를 실행하면 정말로 실패한다는 것을\n    알리는데 사용한다.  만일 이 명령어가 실패하면 콕 시스템은 해당\n    에러 메시지를 출력하지만 그 다음을 계속해서 처리한다.)\n\n    여기에서 콕 시스템은 [nil]에 어떤 타입 인자를 제공해야 할지 몰라서\n    에러를 낸다. 명시적으로 타입을 선언하여 콕 시스템이 [nil]의\n    \"적용\"에 도달할 때 더 많은 정보를 갖도록 도와줄 수 있다:\n *)\n\nDefinition mynil : list nat := nil.\n\n(** 다른 방법으로는 함수 이름 앞에 [@]을 두어 묵시적 인자들을\n    명시적으로 작성하도록 강제할 수 있다. *)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** 인자 합성과 묵시적 인자를 사용하면 이전과 같이 리스트에 대한\n    편리한 표기법을 사용할 수 있다. 생성자 타입 인자들을 묵시적으로\n    만들었기 때문에 콕 시스템은 이 표기법을 사용할 때 마다 이 인자들을\n    자동으로 유추할 것이다. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** 이제 리스트를 우리가 바라던대로 그대로 작성할 수 있다: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** 연습문제 *)\n\n(** **** 연습문제: 별 두 개, 선택 사항 (poly_exercises)  *)\n(** 여기 두 세가지 간단한 연습문제가 있다. [Lists] 장에 있는\n    연습문제들과 유사한데, 다형성을 가지고 연습하도록 구성되어\n    있다. 아래에서 증명을 완성하시오. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 두 개, 선택 사항 (more_poly_exercises)  *)\n(** 다음은 조금 더 흥미로운 연습문제들이다... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** 다형성을 갖춘 쌍 *)\n\n(** 동일한 패턴을 따라 지난 장에서 정의했던 숫자 쌍의 타입 정의를 보통\n    _곱_이라고 부르는 _다형성을 갖춘 숫자 쌍_으로 일반화 시킬 수 있다: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\n(** 리스트에 대해 그랬던 것 처럼 타입 인자들을 묵시적으로 선언하고\n    익숙한 표기법을 정의한다. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** [Notation] 방법으로 곱 _타입_의 표준 표기법을 정의할 수도 있다: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** ([: type_scope] 주석은 콕 시스템에게 이 축약 표기는 타입을 파싱할\n    때 사용되기만 해야 한다고 알려준다. 이렇게 해야 곱셈 기호와 충돌을\n    피한다.) *)\n\n(** 처음에는 [(x,y)]와 [X*Y]를 혼동할 수 있다. [(x,y)]는 두 개의 다른 값들을 \n    조합해서 만든 _값_이고 [X*Y]는 두 개의 다른 타입들로 만든 _타입_이다. \n    만일 [x]가 [X] 타입이고 [y]가 [Y] 타입이면 [(x,y)]는 [X*Y] 타입이다. *)\n\n(** 첫 번째 원소와 두 번째 원소를 꺼내는 함수들은 이제 어떠한 함수형\n    프로그래밍 언어에서 있는 것과 상당히 비슷하게 보인다. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** 다음 함수는 두 개의 리스트들을을 받아 쌍들의 리스트로\n    조합한다. 다른 함수형 언어에서 종종 [zip]이라 부르는데, 우리는 콕\n    표준 라이브러리와의 일관성을 위해 [combine]이라 부른다. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** 연습문제: 별 한 개, 선택 사항 (combine_checks)  *)\n(** 다음 질문들에 대한 답을 종이 위에 작성해 답해보고 콕 시스템으로 그 답을\n    검사해보시오:\n    - [combine]의 타입은 무엇인가 (즉, [Check @combine]으로 \n      무엇을 출력하는가?)\n    - 아래 명령은 무엇을 출력하는가?\n\n        Compute (combine [1;2] [false;false;true;true]).\n *)\n\n(** [] *)\n\n(** **** 연습문제: 별 두 개, 추천 (split)  *)\n\n(** 함수 [split]은 [combine]의 오른쪽 역 함수이다. 쌍들의 리스트를\n    받아 리스트들의 쌍을 리턴한다. 많은 함수형 언어에서 [unzip]이라\n    부른다.\n\n    아래에서 [split]의 정의를 채우시오. 반드시 주어진 단위 테스트를\n    통과하도록 확인하시오. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y)\n  (* 이 줄을  \":= _당신의 정의_ .\"로 바꾸시오 *). Admitted.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n(* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** 다형성을 갖춘 선택 *)\n\n(** 일단 마지막 다형 타입: _다형성을 갖운 선택_,은 이전 장에서\n    [natoption]을 일반화한 것이다: *)\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\n(** [nth_error] 함수를 어떤 타입의 리스트에 대해서도 동작하도록 이제\n    다시 작성할 수 있다. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\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 [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** 연습문제: 별 한 개, 선택사항 (hd_error_poly)  *)\n(** 이전 장의 [hd_error] 함수의 다형성을 갖춘 버전을 완성하시오. 아래에\n    있는 단위 테스트들을 모두 통과하도록 확인하시오. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X\n  (* 이 줄을 \":= _당신의 정의_ .\"로 대체하시오. *). Admitted.\n\n(** 다시 한 번, 묵시적 인자들을 강제로 명시적으로 작성하게 만들려면 그\n    함수 이름 앞에 [@]을 사용할 수 있다. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\n (* 여기를 채우시오 *) Admitted.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\n (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * 데이터로서 함수 *)\n\n(** 모든 함수형 언어들 (ML, Haskell, Scheme, Scala, Clojure, 등)을\n    포함한 많은 다른 현대 프로그래밍 언어와 같이 콕 시스템은 함수들을\n    일등 시민으로 다룬다. 즉, 함수들을 다른 함수들의 인자로 전달하고\n    그 결과로 리턴하며 자료 구조에 저장하는 등등.  *)\n\n(* ================================================================= *)\n(** ** 고차원 함수 *)\n\n(** 다른 함수들을 다루는 함수들은 보통 _고차원_ 함수라 부른다. 여기\n    간단한 고차원 함수가 있다: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** 여기 인자 [f]는 그 자체로 함수 ([X]에서 [X]로\n    매핑하는)이다. [doit3times]의 몸체에서 [f]를 어떤 값 [n]에 세 번\n    적용한다.  *)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** 필터(Filter) *)\n\n(** 여기 더 유용한 고차원 함수가 있다. [X] 타입의 리스트와 [X]에 관한\n    _술어_([X]를 [bool]로 매핑하는 함수)를 받아 그 리스트를\n    \"필터링\"하고 이 술어가 [true]인 원소들만을 포함하는 새로운\n    리스트를 리턴한다. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** 예를 들어, [filter]를 술어 [evenb]와 숫자 리스트 [l]에 적용하면\n    [l]의 짝수들만을 포함하는 리스트를 리턴한다.  *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** [Lists] 장에서 정의한 [countoddmembers]을 [filter]를 사용하여\n    간단하게 정의할 수 있다. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** 이름이 없는 함수 *)\n\n(** 바로 위 예제에서 단지 [filter]의 인자로 전달하기 위해서 함수\n    [length_is_1]을 정의하고 이름을 붙여야 하는 것은 거의 틀림없이\n    약간 슬픈 일이다. 왜냐하면 이 함수는 결코 다시 사용하지 않을\n    것이기 때문이다. 더우기 이것은 단발성 예제가 아니다. 고차원\n    함수들을 사용할 때 다시 사용하지 않을 \"단발성\" 함수들을 인자들로\n    전달하기를 원할 것이다. 이런 함수들에 이름을 지어야 하는 것은 매우\n    번거로운 일이 될 것이다.\n\n    다행히도 더 나은 방법이 있다. 함수를 상위 레벨에서 선언하거나\n    이름을 붙이지 않고 \"즉석으로\" 함수를 만들 수 있다. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** 식 [(fun n => n * n)]은 \"주어진 숫자 [n]으로 부터 [n * n]을 내는\n    함수\"로 읽을 수 있다. *)\n\n(** 여기 [filter] 예제가 있다. 이름 없는 함수를 사용해서 다시\n    작성하였다. *)\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** 연습문제: 별 두 개 (filter_even_gt7)  *)\n(** ([Fixpoint] 대신) [filter]를 사용해서 콕 함수 [filter_even_gt7]을\n    작성하시오. 이 함수는 입력으로 자연수 리스트를 받아 짝수이면서\n    7보다 큰 숫자들만으로 이루어진 리스트를 리턴한다. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat\n  (* 이 줄을 \":= _당신의 정의_ .\"로 바꾸시오 *). Admitted.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n (* 여기를 채우시오 *) Admitted.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개 (partition)  *)\n(** [filter]를 사용하여 콕 함수 [partition]을 작성하시오:\n\n      partition : forall X : Type, (X -> bool) -> list X -> list X *\n                  list X\n\n   집합 [X], 타입 [X -> bool]의 테스트 함수와 [list X]가 주어지면\n   [partition]은 리스트들의 쌍을 리턴한다. 이 쌍의 첫 번째 원소는 원래\n   리스트의 서브 리스트로 그 테스트를 만족하는 원소들을 포함한다. 두\n   번째 원소는 이 테스트에 실패한 원소들을 포함하는 서브\n   리스트이다. 두 서브리스트들의 원소들의 순서는 원래 리스트에서\n   순서와 동일해야 한다. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X\n  (* 이 줄을 \":= _당신의 정의_ .\"로 대체하시오 *). Admitted.\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\n(* 여기를 채우시오 *) Admitted.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\n(* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** 맵(Map) *)\n\n(** 또 다른 편리한 고차원 함수 [map]이 있다. *)\n\nFixpoint map {X Y:Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** 함수 [f]와 리스트 [ l = [n1, n2, n3, ...] ]을 받아 리스트 [ [f n1,\n    f n2, f n3,...] ]을 리턴한다. 이 리스트는 [f]를 [l]의 각 원소에\n    차례로 적용한 결과이다. 예를 들어: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** 입출력 리스트의 원소 타입들은 동일할 필요가 없다. 그래서 [map]은\n    _두 개_의 타입 인자들 [X]와 [Y]를 받는다. 맵 함수는 숫자 리스트와\n    숫자를 부울 값으로 매핑하는 함수에 적용하면 부울 값 리스트를 낼 수\n    있다: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** 맵 함수는 숫자 리스트와 숫자를 _부울 리스트들_로 매핑하는 함수에\n    적용해서 부울 _리스트들의 리스트_를 낼 수 있다: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** 연습문제들 *)\n\n(** **** 연습문제: 별 세 개 (map_rev)  *)\n(** [map]과 [rev]의 교환 법칙을 보여준다. 보조 정리를 새로 정의할 필요가\n    있다. *)\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 두 개, 추천 (flat_map)  *)\n(** 함수 [map]은 [X -> Y] 타입의 함수를 사용하여 [list X]의 원소를\n    [list Y] 원소로 매핑한다. 이와 비슷한 함수 [flat_map]을 정의하여\n    [X -> list Y] 타입의 함수 [f]를 사용하여 [list X]의 원소를 [list\n    Y]의 원소로 매핑한다. 이 함수의 정의는 아래와 같이 [f]의 결과를\n    '펼치면서' 동작해야 한다:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10] = [1; 2; 3; 5; 6; 7;\n      10; 11; 12].  *)\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X)\n                   : (list Y)\n  (* 이 줄을  \":= _당신의 정의_ .\"로 대체하시오 *). Admitted.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\n (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** 리스트는 [map] 함수로 다룰 수 있는 유일한 귀납적 타입이 아니다.\n    [option] 타입에 대한 [map] 함수는 이렇게 정의할 수 있다: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** 연습문제: 별 두 개, 선택사항 (implicit_args)  *)\n(** [filter]와 [map]를 정의하고 사용할 때 많은 곳에서 묵시적 인자들을\n    사용한다.  묵시적 인자들 주위의 중괄호들을 괄호로 바꾸고 필요한\n    곳에 명시적으로 타입 인자들을 채운다. 콕 시스템을 사용하여 제대로\n    바꾸었음을 확인하시오. (이 연습문제의 답은 제출하지 않는다. 이\n    파일을 _복사_해서 연습문제를 풀고 나중에 버리는 것이 분명히 가장\n    쉬울 것이다.)  *)\n(** [] *)\n\n(* ================================================================= *)\n(** ** 접기(Fold) *)\n\n(** 훨씬 더 강력한 고차원 함수 [fold]가 있다. 이 함수는 구글의\n    맵/리듀스 분산 프로그래밍 프레임워크의 핵심에서 사용하는\n    \"[reduce]\" 연산을 위한 영감을 제공한다.  *)\n\nFixpoint fold {X Y:Type} (f: X->Y->Y) (l:list X) (b:Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** 직관적으로 [fold] 연산의 동작은 주어진 이진 연산 [f]를 주어진 리스트의 원소들의\n    각 쌍에 적용하는 것이다. 예를 들어 [ fold plus [1;2;3;4] ]는 직관적으로 \n    [1+2+3+4]가 된다. 자세히 설명하면, [f]에 대한 초기 두 번째 입력으로 사용할\n    \"시작 원소\"도 필요하다. 예를 들어,\n\n       fold plus [1;2;3;4] 0\n\n    는 아래 결과를 낸다:\n\n       1 + (2 + (3 + (4 + 0))).\n\n    몇 가지 추가 예제들: *)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** 연습문제: 별 한 개, 고급 (fold_types_different)  *)\n(** [fold]의 타입은 _두 개_의 타입 변수들 [X]와 [Y] 패러미터로\n    구성되어 있고, 인자 [f]는 [X]의 원소와 [Y]의 원소를 받아 [Y]의\n    원소를 리턴하는 이진 연산이다. [X]와 [Y]와 다르면 유용한 상황이\n    무엇일지 생각해보시오.  *)\n\n(* 여기를 채우시오 *)\n(** [] *)\n\n(* ================================================================= *)\n(** ** 함수를 만드는 함수 *)\n\n(** 지금까지 이야기한 대부분의 고차원 함수들은 함수들을 인자로 받는\n    것이었다. 다른 함수들의 결과로 함수들을 _리턴_하는 몇 가지 예제를\n    살펴보자. 우선 (어떤 타입 [X]의) 값 [x]를 받고 [nat]에서 [X]로\n    매핑하는 그래서 [x]를 내는 함수를 리턴하는 함수가 여기 있다.\n    [nat] 인자는 무시한다. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** 사실 이미 살펴본 다중 인자 함수들은 함수들을 데이터로 전달하는\n    예제이기도 하다.  그 이유를 살펴보기 위해 [plus] 타입을 다시\n    생각해본다. *)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** 이 식에서 각 [->]은 실제로 타입에 대한 _이진_ 연산이다. 이 것은\n    _우측으로 묶인_ 연산이다. 그래서 [plus]의 타입은 정말로 [nat ->\n    (nat -> nat)]을 짧게 줄인 것이다. 즉, \"[plus]는 단일 인자 함수로\n    [nat]의 값을 받고 또 다른 단일 인자 함수를 리턴한다. 이 함수는\n    [nat]의 값을 받아 [nat]의 값을 리턴한다\"이다.  위 예제에서 항상\n    [plus]를 한번에 두 개의 인자에 적용했지만 원한다면 단지 첫 번째\n    인자만 줄 수 있다. 이러한 함수 사용을 _부분 적용_이라 부른다. *)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * 추가 연습문제들 *)\n\nModule Exercises.\n\n(** **** 연습문제: 별 두 개 (fold_length)  *)\n(** 리스트에 대한 많은 공통 함수들은 [fold]를 이용해서 구현할 수 있다.\n    예를 들어, [length]를 이렇게 정의할 수도 있다: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** [fold_length]의 정확성을 증명하시오. *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\n(* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 세 개 (fold_map)  *)\n(** [fold]를 사용하여 [map]도 정의할 수 있다. 아래의 [fold_map]을\n    마무리 지으시오. *)\n\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y\n  (* 이 줄을 \":= _당신의 정의_ \"로 대체하시오. *). Admitted.\n\n(** [fold_map]의 정확성을 기술하는 [fold_map_correct] 정리를 콕으로\n    작성하고 증명하시오. *)\n\n(* 여기를 채우시오 *)\n(** [] *)\n\n(** **** 연습문제: 별 두 개, 고급 (currying)  *)\n(** 콕에서 함수 [f : A -> B -> C]는 실제로 [A -> (B -> C)]\n    타입이다. 즉, [f]에 [A] 타입의 값을 주면 함수 [f' B -> C]를 낼\n    것이다. [f']에 [B]를 주면 [C] 타입의 값을 리턴할 것이다. 이런\n    방식으로 [plus3]에서 처럼 부분 적용을 사용한다. 일련의 인자들을\n    함수를 리턴하는 함수로 처리하는 것을 _커링_이라 부른다. 논리학자\n    하스켈 커리(Haskell Curry)의 이름을 따서 붙인 것이다.\n\n    역으로 [A -> B -> C] 타입을 [(A * B) -> C]로 해석할 수 있다.  이\n    것을 _언커링_이라 부른다. 언커링 이진 함수에는 두 인자들을 쌍으로\n    한 번에 주어야 한다. 부분 적용을 허용하지 않는다. *)\n\n(** 다음과 같이 커링을 정의할 수 있다: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** 연습문제로 이 것의 역 [prod_uncurry]을 정의하시오. 그런 다음 이 두\n    가지가 서로 역이라는 것을 보이는 정리들을 아래에서 증명하시오. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z\n  (* 이 줄을 \":= _당신의 정의_ \"로 대체하시오. *). Admitted.\n\n(** 커링이 유용한 (사소한) 예로써 위에서 본 예제들 중 하나를 짧게 하기\n    위해 커링을 사용할 수 있다: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** 사고 단련: 다음 명령어들을 실행하기 전에 [prod_curry]와\n    [prod_uncurry]의 타입들을 계산해보자. *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  (* 여기를 채우시오 *) Admitted.\n(** [] *)\n\n(** **** 연습문제: 별 두 개, 고급 (nth_error_informal)  *)\n(** [nth_error] 함수의 정의를 생각해보자:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\n     end.\n\n   다음 정리를 비형싲거으로 증명해보시오:\n\n   forall X n l, length l = n -> @nth_error X l n = None\n\n(* 여기를 채우시오 *)\n*)\n(** [] *)\n\n(** **** 연습문제: 별 네 개, 고급 (church_numerals)  *)\n(** 이 연습문제는 수학자 알론조 처치 이름을 따서 _처치 숫자_라고\n    부르는 자연수를 정의하는 한 가지 방법을 탐구한다. 자연수 [n]을\n    함수 [f]를 인자로 받고 [f]를 [n]번 반복하는 함수로 표현할 수\n    있다. *)\n\nModule Church.\nDefinition nat := forall X : Type, (X -> X) -> X -> X.\n\n(** 이 표기법으로 몇 가지 숫자를 작성하는 법을 살펴보자. 함수를 한 번\n    반복하는 것은 적용하는 것과 동일해야 한다. 그래서: *)\n\nDefinition one : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** 비슷하게 [two]는 [f]를 그 인자에 두 번 적용해야 한다: *)\n\nDefinition two : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** 다소 교묘하게 [zero]를 정의한다. 어떻게 \"함수를 0번 적용\"할 수\n    있을까?  그 답은 실제로 간단하다. 그냥 인자를 건드리지 않고\n    반환하면 된다. *)\n\nDefinition zero : nat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** 더 일반적으로 숫자 [n]을 [fun X f x => f (f ... (f x) ...)]로\n    [f]가 [n]번 나타나도록 작성할 수 있다. 특히 이전에 정의했던\n    [doit3times] 함수가 실제로 [3]의 처치 표현임을 주목하라. *)\n\nDefinition three : nat := @doit3times.\n\n(** 다음 함수들의 정의를 완성하시오. 해당하는 단위 테스트들을\n    통과하는지 [reflexivity] 로 증명해서 확인하시오.  *)\n\n(** 다음 자연수: *)\n\nDefinition succ (n : nat) : nat\n  (* 이 줄을 \":= _당신의 정의_ \"로 대체하시오 *). Admitted.\n\nExample succ_1 : succ zero = one.\nProof. (* 여기를 채우시오 *) Admitted.\n\nExample succ_2 : succ one = two.\nProof. (* 여기를 채우시오 *) Admitted.\n\nExample succ_3 : succ two = three.\nProof. (* 여기를 채우시오 *) Admitted.\n\n(** 두 자연수에 대한 덧셈: *)\n\nDefinition plus (n m : nat) : nat\n  (* 이 줄을 \":= _당신의 정의_ \"로 대체하시오 *). Admitted.\n\nExample plus_1 : plus zero one = one.\nProof. (* 여기를 채우시오 *) Admitted.\n\nExample plus_2 : plus two three = plus three two.\nProof. (* 여기를 채우시오 *) Admitted.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. (* 여기를 채우시오 *) Admitted.\n\n(** 곱셈: *)\n\nDefinition mult (n m : nat) : nat\n  (* 이 줄을 \":= _당신의 정의_ \"로 대체하시오 *). Admitted.\n\nExample mult_1 : mult one one = one.\nProof. (* 여기를 채우시오 *) Admitted.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. (* 여기를 채우시오 *) Admitted.\n\nExample mult_3 : mult two three = plus three three.\nProof. (* 여기를 채우시오 *) Admitted.\n\n(** 누승: *)\n\n(** (_힌트_: 다형성은 여기서 중요한 역할을 담당한다. 그러나 반복할\n    적절한 타입을 선택하는 것이 까다롭다. 만일 \"Universe\n    inconsistency\" 에러를 만나면 다른 타입에 대해 반복할 것을\n    시도해보시오: [nat] 자체는 대체로 여러 문제가 있다.) *)\n\nDefinition exp (n m : nat) : nat\n  (* 이 줄을 \":= _당신의 정의_ \"로 대체하시오 *). Admitted.\n\nExample exp_1 : exp two two = plus two two.\nProof. (* 여기를 채우시오 *) Admitted.\n\nExample exp_2 : exp three two = plus (mult two (mult two two)) one.\nProof. (* 여기를 채우시오 *) Admitted.\n\nExample exp_3 : exp three zero = one.\nProof. (* 여기를 채우시오 *) Admitted.\n\nEnd Church.\n(** [] *)\n\nEnd Exercises.\n\n(** $Date: 2017-09-06 11:44:36 -0400 (Wed, 06 Sep 2017) $ *)\n\n", "meta": {"author": "kwanghoon", "repo": "sf", "sha": "6937265f0ba88524af8a5e0da1cb19d49c079875", "save_path": "github-repos/coq/kwanghoon-sf", "path": "github-repos/coq/kwanghoon-sf/sf-6937265f0ba88524af8a5e0da1cb19d49c079875/Poly_ko_utf8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7056166844646542}}
{"text": "(** * Perm: Basic Techniques for Comparisons and Permutations *)\n\n(** Consider these algorithms and data structures:\n    - sort a sequence of numbers\n    - finite maps from numbers to (arbitrary-type) data\n    - finite maps from any ordered type to (arbitrary-type) data\n    - priority queues: finding/deleting the highest number in a set\n\n    To prove the correctness of such programs, we need to reason about\n    comparisons, and about whether two collections have the same\n    contents.  In this chapter, we introduce some techniques for\n    reasoning about:\n\n    - less-than comparisons on natural numbers, and\n    - permutations (rearrangements of lists).\n\n    In later chapters, we'll apply these proof techniques to reasoning\n    about algorithms and data structures. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Strings.String.  (* for manual grading *)\nFrom Coq Require Export Bool.Bool.\nFrom Coq Require Export Arith.Arith.\nFrom Coq Require Export Arith.EqNat.\nFrom Coq Require Export Omega.\nFrom Coq Require Export Lists.List.\nExport ListNotations.\nFrom Coq Require Export Permutation.\n\n(* ################################################################# *)\n(** * The Less-Than Order on the Natural Numbers *)\n\n(** In our proofs about searching and sorting algorithms, we often\n    have to reason about the less-than order on natural numbers.\n    greater-than. Recall that the Coq standard library contains both\n    propositional and Boolean less-than operators on natural numbers.\n    We write [x < y] for the proposition that [x] is less than [y]: *)\n\nLocate \"_ < _\". (* \"x < y\" := lt x y *)\nCheck lt : nat -> nat -> Prop.\n\n(** And we write [x <? y] for the computation that returns [true] or\n    [false] depending on whether [x] is less than [y]: *)\n\nLocate \"_ <? _\". (* x <? y  := Nat.ltb x y *)\nCheck Nat.ltb : nat -> nat -> bool.\n\n(** The two operators are a reflection of one another, as discussed in\n    [Logic] and [IndProp]. The [Nat] module has a\n    theorem showing how they relate: *)\n\nCheck Nat.ltb_lt : forall n m : nat, (n <? m) = true <-> n < m.\n\n(** The [Nat] module contains a synonym for [lt]. *)\n\nPrint Nat.lt. (* Nat.lt = lt *)\n\n(** For unknown reasons, [Nat] does not define notations\n    for [>?] or [>=?].  So we define them here: *)\n\nNotation  \"a >=? b\" := (Nat.leb b a)\n                          (at level 70) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a)\n                         (at level 70) : nat_scope.\n\n(* ================================================================= *)\n(** ** The Omega Tactic *)\n\n(** Reasoning about inequalities by hand can be a little painful. Luckily, Coq\n    provides a tactic called [omega] that is quite helpful. *)\n\nTheorem omega_example1:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n\n(** The hard way to prove this is by hand. *)\n\n  (* try to remember the name of the lemma about negation and [<=] *)\n  Search (~ _ <= _ -> _).\n  apply not_le in H0.\n  (* try to remember the name of the transitivity lemma about [>] *)\n  Search (_ > _ -> _ > _ -> _ > _).\n  apply gt_trans with j.\n  apply gt_trans with (k-3).\n  (* Is [k] greater than [k-3]? On the integers, sure. But we're working\n     with natural numbers, which truncate subtraction at zero. *)\nAbort.\n\nTheorem truncated_subtraction: ~ (forall k:nat, k > k - 3).\nProof.\n  intros contra.\n  (* [specialize] applies a hypothesis to an argument *)\n  specialize (contra 0).\n  simpl in contra.\n  inversion contra.\nQed.\n\n(** Since subtraction is truncated, does [omega_example1] actually hold?\n    It does. Let's try again, the hard way, to find the proof. *)\n\nTheorem omega_example1:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof. (* try again! *)\n  intros.\n  apply not_le in H0.\n  unfold gt in H0.\n  unfold gt.\n  (* try to remember the name ... *)\n  Search (_ < _ -> _ <= _ -> _ < _).\n  apply lt_le_trans with j.\n  apply H.\n  apply le_trans with (k-3).\n  Search (_ < _ -> _ <= _).\n  apply lt_le_weak.\n  auto.\n  apply le_minus.\nQed.\n\n(** That was tedious.  Here's a much easier way: *)\n\nTheorem omega_example2:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n  omega.\nQed.\n\n(** Omega is a decision procedure invented in 1991 by William Pugh for\n    integer linear programming (ILP). The [omega] tactic was made\n    available by importing [Coq.omega.Omega], at the beginning of the\n    file.  It is an implementation of Pugh's algorithm.  The tactic\n    works with Coq types [Z] and [nat], and these operators: [<] [=] [>]\n    [<=] [>=] [+] [-] [~], as well as multiplication by small integer\n    literals (such as 0,1,2,3...), and some uses of [\\/] and [/\\].\n\n    Omega does not \"understand\" other operators.  It treats\n    expressions such as [a * b] and [f x y] as variables.  That is, it\n    can prove [f x y > a * b -> f x y + 3 >= a * b], in the same way it\n    would prove [u > v -> u + 3 >= v]. But it cannot reason about, e.g.,\n    multiplication. *)\n\nTheorem omega_example_3 : forall (f : nat -> nat -> nat) a b x y,\n    f x y > a * b -> f x y + 3 >= a * b.\nProof.\n  intros. omega.\nQed.\n\nTheorem omega_example_4 : forall a b,\n    a * b = b * a.\nProof.\n  intros. Fail omega.\nAbort.\n\n(** The Omega algorithm is NP-complete, so we might expect that\n    this tactic is exponential-time in the worst case.  Indeed,\n    if you have [N] equations, it could take [2^N] time.\n    But in the typical cases that result from reasoning about\n    programs, [omega] is much faster than that. *)\n\n(* ################################################################# *)\n(** * Swapping *)\n\n(** Consider trying to sort a list of natural numbers.  As a small piece of\n    a sorting algorithm, we might need to swap the first two elements of a list\n    if they are out of order. *)\n\nDefinition maybe_swap (al: list nat) : list nat :=\n  match al with\n  | a :: b :: ar => if a >? b then b :: a :: ar else a :: b :: ar\n  | _ => al\n  end.\n\nExample maybe_swap_123:\n  maybe_swap [1; 2; 3] = [1; 2; 3].\nProof. reflexivity. Qed.\n\nExample maybe_swap_321:\n  maybe_swap [3; 2; 1] = [2; 3; 1].\nProof. reflexivity. Qed.\n\n(** Applying [maybe_swap] twice should give the same result as applying it once.\n    That is, [maybe_swap] is _idempotent_. *)\n\nTheorem maybe_swap_idempotent: forall al,\n    maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros [ | a [ | b al]]; simpl; try reflexivity.\n  destruct (b <? a) eqn:Hb_lt_a; simpl.\n  - destruct (a <? b) eqn:Ha_lt_b; simpl.\n    + (** Now what?  We have a contradiction in the hypotheses: it\n          cannot hold that [a] is less than [b] and [b] is less than\n          [a].  Unfortunately, [omega] cannot immediately show that\n          for us, because it reasons about comparisons in [Prop] not\n          [bool]. *)\n      Fail omega.\nAbort.\n\n(** Of course we could finish the proof by reasoning directly about\n    inequalities in [bool].  But this situation is going to occur\n    repeatedly in our study of sorting. *)\n\n(** Let's set up some machinery to enable using [omega] on boolean\n    tests. *)\n\n(* ================================================================= *)\n(** ** Reflection *)\n\n(** The [reflect] type, defined in the standard library (and presented\n    in [IndProp]), relates a proposition to a Boolean. That is,\n    a value of type [reflect P b] contains a proof of [P] if [b] is\n    [true], or a proof of [~ P] if [b] is [false]. *)\n\nPrint reflect.\n(*\nInductive reflect (P : Prop) : bool -> Set :=\n  | ReflectT :   P -> reflect P true\n  | ReflectF : ~ P -> reflect P false\n *)\n\n(** The standard library proves a theorem that says if [P] is provable\n    whenever [b = true] is provable, then [P] and [b] are reflected. *)\n\nCheck iff_reflect : forall (P : Prop) (b : bool),\n    P <-> b = true -> reflect P b.\n\n(** Using that theorem, we can quickly prove that the (in)equality operators\n    are reflections. *)\n\nLemma eqb_reflect : forall x y, reflect (x = y) (x =? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.eqb_eq.\nQed.\n\nLemma ltb_reflect : forall x y, reflect (x < y) (x <? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.ltb_lt.\nQed.\n\nLemma leb_reflect : forall x y, reflect (x <= y) (x <=? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.leb_le.\nQed.\n\n(** Here's an example of how you could use these lemmas.  Suppose you\n    have this simple program, [(if a <? 5 then a else 2)], and you\n    want to prove that it evaluates to a number smaller than 6.  You\n    can use [ltb_reflect] \"by hand\": *)\n\nExample reflect_example1: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros a.\n  (* The next two lines aren't strictly necessary, but they\n     help make it clear what [destruct] does. *)\n  assert (R: reflect (a < 5) (a <? 5)) by apply ltb_reflect.\n  remember (a <? 5) as guard.\n  destruct R as [H|H] eqn:HR.\n  * (* ReflectT *) omega.\n  * (* ReflectF *) omega.\nQed.\n\n(** For the [ReflectT] constructor, the guard [a <? 5] must be equal\n    to [true]. The [if] expression in the goal has already been\n    simplified to take advantage of that fact. Also, for [ReflectT] to\n    have been used, there must be evidence [H] that [a < 5] holds.\n    From there, all that remains is to show [a < 5] entails [a < 6].\n    The [omega] tactic, which is capable of automatically proving some\n    theorems about inequalities, succeeds.\n\n    For the [ReflectF] constructor, the guard [a <? 5] must be equal\n    to [false]. So the [if] expression simplifies to [2 < 6], which is\n    immediately provable by [omega]. *)\n\n(** A less didactic version of the above proof wouldn't do the\n    [assert] and [remember]: we can directly skip to [destruct]. *)\n\nExample reflect_example1': forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros a. destruct (ltb_reflect a 5); omega.\nQed.\n\n(** But even that proof is a little unsatisfactory. The original expression,\n    [a <? 5], is not perfectly apparent from the expression [ltb_reflect a 5]\n    that we pass to [destruct]. *)\n\n(** It would be nice to be able to just say something like [destruct\n    (a <? 5)] and get the reflection \"for free.\"  That's what we'll\n    engineer, next. *)\n\n(* ================================================================= *)\n(** ** A Tactic for Boolean Destruction *)\n\n(** We're now going to build a tactic that you'll want to _use_, but\n    you won't need to understand the details of how to _build_ it\n    yourself.\n\n    Let's put several of these [reflect] lemmas into a Hint database.\n    We call it [bdestruct], because we'll use it in our\n    boolean-destruction tactic: *)\n\nHint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\n\n(** Here is the tactic, the body of which you do not need to\n    understand.  Invoking [bdestruct] on Boolean expression [b] does\n    the same kind of reasoning we did above: reflection and\n    destruction.  It also attempts to simplify negations involving\n    inequalities in hypotheses. *)\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n       [ | try first [apply not_lt in H | apply not_le in H]]].\n\n(** This tactic makes quick, easy-to-read work of our running example. *)\n\nExample reflect_example2: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros.\n  bdestruct (a <? 5);  (* instead of: [destruct (ltb_reflect a 5)]. *)\n  omega.\nQed.\n\n(* ================================================================= *)\n(** ** Finishing the [maybe_swap] Proof *)\n\n(** Now that we have [bdestruct], we can finish the proof of [maybe_swap]'s\n    idempotence. *)\n\nTheorem maybe_swap_idempotent: forall al,\n    maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros [ | a [ | b al]]; simpl; try reflexivity.\n  bdestruct (a >? b); simpl.\n  (** Note how [b < a] is a hypothesis, rather than [b <? a = true]. *)\n  - bdestruct (b >? a); simpl.\n    + (** [omega] can take care of the contradictory propositional inequalities. *)\n      omega.\n    + reflexivity.\n  - bdestruct (a >? b); simpl.\n    + omega.\n    + reflexivity.\nQed.\n\n(** When proving theorems about a program that uses Boolean\n    comparisons, use [bdestruct] followed by [omega], rather than\n    [destruct] followed by application of various theorems about\n    Boolean operators. *)\n\n(* ################################################################# *)\n(** * Permutations *)\n\n(** Another useful fact about [maybe_swap] is that it doesn't add or\n    remove elements from the list: it only reorders them.  That is,\n    the output list is a permutation of the input.  List [al] is a\n    _permutation_ of list [bl] if the elements of [al] can be\n    reordered to get the list [bl].  Note that reordering does not\n    permit adding or removing duplicate elements. *)\n\n(** Coq's [Permutation] library has an inductive definition of\n    permutations. *)\n\nPrint Permutation.\n\n(*\n Inductive Permutation {A : Type} : list A -> list A -> Prop :=\n    perm_nil : Permutation [] []\n  | perm_skip : forall (x : A) (l l' : list A),\n                Permutation l l' ->\n                Permutation (x :: l) (x :: l')\n  | perm_swap : forall (x y : A) (l : list A),\n                Permutation (y :: x :: l) (x :: y :: l)\n  | perm_trans : forall l l' l'' : list A,\n                 Permutation l l' ->\n                 Permutation l' l'' ->\n                 Permutation l l''.\n *)\n\n(** You might wonder, \"is that really the right definition?\"  And\n    indeed, it's important that we get a right definition, because\n    [Permutation] is going to be used in our specifications of\n    searching and sorting algorithms.  If we have the wrong\n    specification, then all our proofs of \"correctness\" will be\n    useless.\n\n    It's not obvious that this is indeed the right specification of\n    permutations. (It happens to be, but that's not obvious.) To gain\n    confidence that we have the right specification, let's use it\n    prove some properties that permutations ought to have. *)\n\n(** **** Exercise: 2 stars, standard (Permutation_properties) \n\n    Think of some desirable properties of the [Permutation] relation\n    and write them down informally in English, or a mix of Coq and\n    English.  Here are four to get you started:\n\n     - 1. If [Permutation al bl], then [length al = length bl].\n     - 2. If [Permutation al bl], then [Permutation bl al].\n     - 3. [[1;1]] is NOT a permutation of [[1;2]].\n     - 4. [[1;2;3;4]] IS a permutation of [[3;4;2;1]].\n\n   YOUR TASK: Add three more properties. Write them here: *)\n\n(** Now, let's examine all the theorems in the Coq library about\n    permutations: *)\n\nSearch Permutation.  (* Browse through the results of this query! *)\n\n(** Which of the properties that you wrote down above have already\n    been proved as theorems by the Coq library developers?  Answer\n    here:\n\n*)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_Permutation_properties : option (nat*string) := None.\n(** [] *)\n\n(** Let's use the permutation theorems in the library to prove the\n    following theorem. *)\n\nExample butterfly: forall b u t e r f l y : nat,\n  Permutation ([b;u;t;t;e;r]++[f;l;y]) ([f;l;u;t;t;e;r]++[b;y]).\nProof.\n  intros.\n  (** Let's group [[u;t;t;e;r]] together on both sides.  Tactic\n      [change t with u] replaces [t] with [u].  Terms [t] and [u] must\n      be _convertible_, here meaning that they evalute to the same\n      term. *)\n  change [b;u;t;t;e;r] with ([b]++[u;t;t;e;r]).\n  change [f;l;u;t;t;e;r] with ([f;l]++[u;t;t;e;r]).\n\n  (** We don't actually need to know the list elements in\n      [[u;t;t;e;r]].  Let's forget about them and just remember them\n      as a variable named [utter]. *)\n  remember [u;t;t;e;r] as utter. clear Hequtter.\n\n  (** Likewise, let's group [[f;l]] and remember it as a variable. *)\n  change [f;l;y] with ([f;l]++[y]).\n  remember [f;l] as fl. clear Heqfl.\n\n  (** Next, let's cancel [fl] from both sides.  In order to do that,\n      we need to bring it to the beginning of each list. For the right\n      list, that follows easily from the associativity of [++].  *)\n  replace ((fl ++ utter) ++ [b;y]) with (fl ++ utter ++ [b;y])\n    by apply app_assoc.\n\n  (** But for the left list, we can't just use associativity.\n      Instead, we need to reason about permutations and use some\n      library theorems. *)\n  apply perm_trans with (fl ++ [y] ++ ([b] ++ utter)).\n  - replace (fl ++ [y] ++ [b] ++ utter) with ((fl ++ [y]) ++ [b] ++ utter).\n    + apply Permutation_app_comm.\n    + rewrite <- app_assoc. reflexivity.\n\n  - (** A library theorem will now help us cancel [fl]. *)\n    apply Permutation_app_head.\n\n  (** Next let's cancel [utter]. *)\n    apply perm_trans with (utter ++ [y] ++ [b]).\n    + replace ([y] ++ [b] ++ utter) with (([y] ++ [b]) ++ utter).\n      * apply Permutation_app_comm.\n      * rewrite app_assoc. reflexivity.\n    + apply Permutation_app_head.\n\n      (** Finally we're left with just [y] and [b]. *)\n      apply perm_swap.\nQed.\n\n(** That example illustrates a general method for proving permutations\n    involving cons [::] and append [++]:\n\n    - Identify some portion appearing in both sides.\n    - Bring that portion to the front on each side using lemmas such\n      as [Permutation_app_comm] and [perm_swap], with generous use of\n      [perm_trans].\n    - Use [Permutation_app_head] to cancel an appended head.  You can\n      also use [perm_skip] to cancel a single element. *)\n\n(** **** Exercise: 3 stars, standard (permut_example) \n\n    Use the permutation rules in the library to prove the following\n    theorem.  The following [Check] commands are a hint about useful\n    lemmas.  You don't need all of them, and depending on your\n    approach you will find lemmas to be more useful than others. Use\n    [Search Permutation] to find others, if you like. *)\n\nCheck perm_skip.\nCheck perm_trans.\nCheck Permutation_refl.\nCheck Permutation_app_comm.\nCheck app_assoc.\nCheck app_nil_r.\nCheck app_comm_cons.\n\nExample permut_example: forall (a b: list nat),\n  Permutation (5 :: 6 :: a ++ b) ((5 :: b) ++ (6 :: a ++ [])).\nProof.\n(* SOLUTION: *)\n  intros. simpl. rewrite app_nil_r.\n  apply perm_skip. rewrite app_comm_cons.\n  apply Permutation_app_comm.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (not_a_permutation) \n\n    Prove that [[1;1]] is not a permutation of [[1;2]].\n    Hints are given as [Check] commands. *)\n\nCheck Permutation_cons_inv.\nCheck Permutation_length_1_inv.\n\nExample not_a_permutation:\n  ~ Permutation [1;1] [1;2].\nProof.\n(* SOLUTION: *)\nProof.\n  intros H.\n  apply Permutation_cons_inv in H.\n  apply Permutation_length_1_inv in H.\n  discriminate.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Correctness of [maybe_swap] *)\n\n(** Now we can prove that [maybe_swap] is a permutation: it reorders\n    elements but does not add or remove any. *)\n\nTheorem maybe_swap_perm: forall al,\n  Permutation al (maybe_swap al).\nProof.\n  (* WORKED IN CLASS *)\n  unfold maybe_swap.\n  destruct al as [ | a [ | b al]].\n  - simpl. apply perm_nil.\n  - apply Permutation_refl.\n  - bdestruct (b <? a).\n    + apply perm_swap.\n    + apply Permutation_refl.\nQed.\n\n(** And, we can prove that [maybe_swap] permutes elements such that\n    the first is less than or equal to the second. *)\n\nDefinition first_le_second (al: list nat) : Prop :=\n  match al with\n  | a :: b :: _ => a <= b\n  | _ => True\n  end.\n\nTheorem maybe_swap_correct: forall al,\n    Permutation al (maybe_swap al)\n    /\\ first_le_second (maybe_swap al).\nProof.\n  intros. split.\n  - apply maybe_swap_perm.\n  - (* WORKED IN CLASS *)\n    unfold maybe_swap.\n    destruct al as [ | a [ | b al]]; simpl; auto.\n    bdestruct (a >? b); simpl; omega.\nQed.\n\n(* ################################################################# *)\n(** * Summary: Comparisons and Permutations *)\n\n(** To prove correctness of algorithms for sorting and searching,\n    we'll reason about comparisons and permutations using the tools\n    developed in this chapter.  The [maybe_swap] program is a tiny\n    little example of a sorting program.  The proof style in\n    [maybe_swap_correct] will be applied (at a larger scale) in\n    the next few chapters. *)\n\n(** **** Exercise: 3 stars, standard (Forall_perm) \n\n    To close, we define a utility tactic and lemma.  First, the\n    tactic. *)\n\n(** Coq's [inversion H] tactic is so good at extracting\n    information from the hypothesis [H] that [H] sometimes becomes\n    completely redundant, and one might as well [clear] it from the\n    goal.  Then, since the [inversion] typically creates some equality\n    facts, why not then [subst] ?  Tactic [inv] does just that. *)\n\nLtac inv H := inversion H; clear H; subst.\n\n(** Second, the lemma.  You will find [inv] useful in proving it.\n\n    [Forall] is Coq library's version of the [All] proposition defined\n    in [Logic], but defined as an inductive proposition rather\n    than a fixpoint.  Prove this lemma by induction.  You will need to\n    decide what to induct on: [al], [bl], [Permutation al bl], and\n    [Forall f al] are possibilities. *)\n\nTheorem Forall_perm: forall {A} (f: A -> Prop) al bl,\n  Permutation al bl ->\n  Forall f al -> Forall f bl.\nProof.\n  (* SOLUTION: *)\n  intros A f al bl Hperm.\n  induction Hperm; simpl; intros; auto.\n  - inv H. constructor; auto.\n  - inv H. inv H3. constructor; auto.\nQed.\n(** [] *)\n\n\n(* Mon May 11 23:22:55 EDT 2020 *)\n", "meta": {"author": "maspin22", "repo": "CoqFormalVerification", "sha": "9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d", "save_path": "github-repos/coq/maspin22-CoqFormalVerification", "path": "github-repos/coq/maspin22-CoqFormalVerification/CoqFormalVerification-9734b70df7f8d4fee830ac6a82c2fa8a1c25bc3d/coq_4160/finalsrc/Perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.705616684000055}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Arith.EqNat.\nFrom Coq Require Import Init.Nat.\nFrom Coq Require Import omega.Omega.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\nFrom PLF Require Import Maps.\nFrom PLF Require Import Imp.\n\nInductive tm : Type :=\n  | C : nat -> tm (* Constant *)\n  | P : tm -> tm -> tm. (* Plus *)\n\nFixpoint evalF (t : tm) : nat :=\n  match t with\n  | C n => n\n  | P a1 a2 => evalF a1 + evalF a2\n  end.\n\nReserved Notation \" t '==>' n \" (at level 50, left associativity).\n\nInductive eval : tm -> nat -> Prop :=\n  | E_Const : forall n,\n      C n ==> n\n  | E_Plus : forall t1 t2 n1 n2,\n      t1 ==> n1 ->\n      t2 ==> n2 ->\n      P t1 t2 ==> (n1 + n2)\nwhere \" t '==>' n \" := (eval t n).\nModule SimpleArith1.\n  Reserved Notation \" t '-->' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_PlusConstConst : forall n1 n2,\n      P (C n1) (C n2) --> C (n1 + n2)\n  | ST_Plus1 : forall t1 t1' t2,\n      t1 --> t1' ->\n      P t1 t2 --> P t1' t2\n  | ST_Plus2 : forall n1 t2 t2',\n      t2 --> t2' ->\n      P (C n1) t2 --> P (C n1) t2'\nwhere \" t '-->' t' \" := (step t t').\n\nExample test_step_1 :\n      P\n        (P (C 0) (C 3))\n        (P (C 2) (C 4))\n      -->\n      P\n        (C (0 + 3))\n        (P (C 2) (C 4)).\nProof.\n  apply ST_Plus1. apply ST_PlusConstConst. Qed.\n\nExample test_step_2 :\n      P\n        (C 0)\n        (P\n          (C 2)\n          (P (C 0) (C 3)))\n      -->\n      P\n        (C 0)\n        (P\n          (C 2)\n          (C (0 + 3))).\nProof.\n  repeat apply ST_Plus2. apply ST_PlusConstConst. Qed.\n\nEnd SimpleArith1.\n\nDefinition relation (X : Type) := X -> X -> Prop.\n\nDefinition deterministic {X : Type} (R : relation X) :=\n  forall x y1 y2 : X, R x y1 -> R x y2 -> y1 = y2.\n\nModule SimpleArith2.\n  Import SimpleArith1.\n\nTheorem step_deterministic:\n  deterministic step.\nProof.\n  unfold deterministic.\n  intros x y1 y2 Hy1 Hy2.\n  generalize dependent y2.\n  induction Hy1; intros y2 Hy2.\n  - inversion Hy2; subst. reflexivity.\n    inversion H2; subst. inversion H2; subst.\n  - inversion Hy2; subst.\n    inversion Hy1. (* imposible case for different type of y1 and y2*)\n    rewrite (IHHy1 t1'0). reflexivity. assumption.\n    inversion Hy1. (* imposible *)\n  - inversion Hy2; subst.\n    inversion Hy1. (* imposible*)\n    inversion H2. (* imposible *)\n    rewrite (IHHy1 t2'0). reflexivity. assumption.\nQed.\n\nEnd SimpleArith2.\n\nLtac solve_by_inverts n :=\n  match goal with | H : ?T |- _ =>\n  match type of T with Prop =>\n    solve [\n      inversion H;\n      match n with S (S (?n')) => subst; solve_by_inverts (S n') end ]\n  end end.\n\nLtac solve_by_invert :=\n  solve_by_inverts 1.\n\nModule SimpleArith3.\nImport SimpleArith1.\nTheorem step_deterministic_alt: deterministic step.\nProof.\n  intros x y1 y2 Hy1 Hy2.\n  generalize dependent y2.\n  induction Hy1; intros y2 Hy2;\n    inversion Hy2; subst; try solve_by_invert.\n  - (* ST_PlusConstConst *) reflexivity.\n  - (* ST_Plus1 *)\n    apply IHHy1 in H2. rewrite H2. reflexivity.\n  - (* ST_Plus2 *)\n    apply IHHy1 in H2. rewrite H2. reflexivity.\nQed.\nEnd SimpleArith3.\n\nInductive value : tm -> Prop :=\n| v_const : forall n, value (C n).\n \nReserved Notation \" t '-->' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_PlusConstConst : forall n1 n2,\n          P (C n1) (C n2)\n      --> C (n1 + n2)\n  | ST_Plus1 : forall t1 t1' t2,\n        t1 --> t1' ->\n        P t1 t2 --> P t1' t2\n  | ST_Plus2 : forall v1 t2 t2',\n        value v1 -> (* <--- n.b. *)\n        t2 --> t2' ->\n        P v1 t2 --> P v1 t2'\nwhere \" t '-->' t' \" := (step t t').\n\nTheorem step_deterministic :\n  deterministic step.\nProof.\n  intros x y1 y2 Hy1 Hy2.\n  generalize dependent y2.\n  induction Hy1; intros y2 Hy2.\n  - inversion Hy2;subst. reflexivity.\n    inversion H2.\n    inversion H3.\n  - inversion Hy2; subst. inversion Hy1.\n    rewrite (IHHy1 t1'0). reflexivity. assumption.\n    inversion Hy1; subst. inversion H1. (* both has the form P t11 t12 and is a value (hence has the form C n). *)\n    inversion H1.\n    rewrite (IHHy1 t0). inversion H1.\n    inversion H1.\n  - inversion Hy2; subst. inversion Hy1; subst.\n    inversion H3; subst; inversion H.\n    rewrite (IHHy1 t2'0). reflexivity. assumption.\nQed.\n\nTheorem strong_progress : forall t,\n    value t \\/ (exists t', t --> t').\nProof.\n  induction t.\n  - left. apply v_const.\n  - right. destruct IHt1.\n    + destruct IHt2.\n      inversion H; subst. inversion H0; subst.\n      exists (C (n + n0)). apply ST_PlusConstConst.\n      destruct H0.\n      exists (P t1 x).\n      apply ST_Plus2. assumption. assumption.\n    + destruct H; destruct IHt2;\n        exists (P x t2); apply ST_Plus1; assumption.\nQed.\n\nDefinition normal_form {X : Type} (R : relation X) (t : X) : Prop :=\n  not (exists t', R t t').\n\nLemma value_is_nf : forall v,\n  value v -> normal_form step v.\nProof.\n  unfold normal_form. intros v H. inversion H.\n  intros contra. inversion contra. inversion H1.\nQed.\n\nLemma nf_is_value : forall t,\n  normal_form step t -> value t.\nProof. (* a corollary of strong_progress... *)\n  unfold normal_form. intros t H.\n  assert (G : value t \\/ exists t', t --> t').\n  { apply strong_progress. }\n  destruct G as [G | G].\n  - (* l *) apply G.\n  - (* r *) exfalso. apply H. assumption.\nQed.\n\nCorollary nf_same_as_value : forall t,\n  normal_form step t <-> value t.\nProof.\n  split. apply nf_is_value. apply value_is_nf.\nQed.\n\nModule Temp1.\nInductive value : tm -> Prop :=\n  | v_const : forall n, value (C n)\n  | v_funny : forall t1 n2,\n                value (P t1 (C n2)). (* <--- *)\nReserved Notation \" t '-->' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_PlusConstConst : forall n1 n2,\n      P (C n1) (C n2) --> C (n1 + n2)\n  | ST_Plus1 : forall t1 t1' t2,\n      t1 --> t1' ->\n      P t1 t2 --> P t1' t2\n  | ST_Plus2 : forall v1 t2 t2',\n      value v1 ->\n      t2 --> t2' ->\n      P v1 t2 --> P v1 t2'\n\nwhere \" t '-->' t' \" := (step t t').\n\nLemma value_not_same_as_normal_form :\n  exists v, value v /\\ not (normal_form step v).\nProof.\n  (* FILL IN HERE *) Admitted.\nEnd Temp1.\n\nModule Temp4.\n\nInductive tm : Type :=\n  | tru : tm\n  | fls : tm\n  | test : tm -> tm -> tm -> tm.\nInductive value : tm -> Prop :=\n  | v_tru : value tru\n  | v_fls : value fls.\nReserved Notation \" t '-->' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_IfTrue : forall t1 t2,\n      test tru t1 t2 --> t1\n  | ST_IfFalse : forall t1 t2,\n      test fls t1 t2 --> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 --> t1' ->\n      test t1 t2 t3 --> test t1' t2 t3\n\nwhere \" t '-->' t' \" := (step t t').\n\nDefinition bool_step_prop1 :=\n  fls --> fls.\n\nTheorem not_bool_step_prop1:\n  not bool_step_prop1.\nProof.\n  unfold bool_step_prop1.\n  intros contra. inversion contra. Qed.\n\nDefinition bool_step_prop2 :=\n     test\n       tru\n       (test tru tru tru)\n       (test fls fls fls)\n  -->\n  tru.\n\nTheorem not_bool_step_prop2:\n  not bool_step_prop2.\nProof.\n  intros contra. inversion contra.\nQed.\n\nDefinition bool_step_prop3 :=\n     test\n       (test tru tru tru)\n       (test tru tru tru)\n       fls\n   -->\n     test\n       tru\n       (test tru tru tru)\n       fls.\n\nTheorem true_bool_step_prop3 :\n  bool_step_prop3.\nProof.\n  unfold bool_step_prop3. constructor. constructor.\nQed.\n\nTheorem strong_progress : forall t,\n  value t \\/ (exists t', t --> t').\nProof.\n  induction t.\n  - left. apply v_tru.\n  - left. apply v_fls.\n  - right.\n    destruct IHt1. inversion H; subst.\n    exists t2. apply ST_IfTrue.\n    exists t3. apply ST_IfFalse.\n    destruct H.\n    exists (test x t2 t3). apply ST_If. assumption.\nQed.\n\nTheorem step_deterministic :\n  deterministic step.\nProof.\n  intros x y1 y2 Hy1 Hy2.\n  generalize dependent y2.\n  induction Hy1; intros y2 Hy2.\n  - inversion Hy2;subst. reflexivity.\n    inversion H3.\n  - inversion Hy2; subst. reflexivity.\n    inversion H3.\n  - inversion Hy2; subst.\n    inversion Hy1.\n    inversion Hy1.\n    rewrite (IHHy1 t1'0). reflexivity. assumption.\nQed.\n\nModule Temp5.\n\nReserved Notation \" t '-->' t' \" (at level 40).\nInductive step : tm -> tm -> Prop :=\n  | ST_IfTrue : forall t1 t2,\n      test tru t1 t2 --> t1\n  | ST_IfFalse : forall t1 t2,\n      test fls t1 t2 --> t2\n  | ST_If : forall t1 t1' t2 t3,\n      t1 --> t1' ->\n      test t1 t2 t3 --> test t1' t2 t3\n  | ST_Short : forall t1 t2 ,\n      test t1 t2 t2 --> t2\nwhere \" t '-->' t' \" := (step t t').\n\nDefinition bool_step_prop4 :=\n         test\n            (test tru tru tru)\n            fls\n            fls\n     -->\n     fls.\n\nExample bool_step_prop4_holds :\n  bool_step_prop4.\nProof.\n  unfold bool_step_prop4. apply ST_Short. Qed.\n\nEnd Temp5.\nEnd Temp4.\n\nInductive multi {X : Type} (R : relation X) : relation X :=\n  | multi_refl : forall (x : X), multi R x x\n  | multi_step : forall (x y z : X),\n                    R x y ->\n                    multi R y z ->\n                    multi R x z.\n\nNotation \" t '-->*' t' \" := (multi step t t') (at level 40).\n\nTheorem multi_R : forall (X : Type) (R : relation X) (x y : X),\n    R x y -> (multi R) x y.\nProof.\n  intros X R x y H.\n  apply multi_step with y. apply H. apply multi_refl.\nQed.\n\nTheorem multi_trans :\n  forall (X : Type) (R : relation X) (x y z : X),\n      multi R x y ->\n      multi R y z ->\n      multi R x z.\nProof.\n  intros X R x y z G H.\n  induction G.\n    - (* multi_refl *) assumption.\n    - (* multi_step *)\n      apply multi_step with y. assumption.\n      apply IHG. assumption.\nQed.\n\nLemma test_multistep_1:\n      P\n        (P (C 0) (C 3))\n        (P (C 2) (C 4))\n   -->*\n      C ((0 + 3) + (2 + 4)).\nProof.\n  apply multi_step with\n            (P (C (0 + 3))\n               (P (C 2) (C 4))).\n  { apply ST_Plus1. apply ST_PlusConstConst. }\n  apply multi_step with\n            (P (C (0 + 3))\n               (C (2 + 4))).\n  { apply ST_Plus2. apply v_const. apply ST_PlusConstConst. }\n  apply multi_R.\n  { apply ST_PlusConstConst. }\nQed.\n\nLemma test_multistep_1':\n      P\n        (P (C 0) (C 3))\n        (P (C 2) (C 4))\n  -->*\n      C ((0 + 3) + (2 + 4)).\nProof.\n  eapply multi_step. { apply ST_Plus1. apply ST_PlusConstConst. }\n  eapply multi_step. { apply ST_Plus2. apply v_const.\n                       apply ST_PlusConstConst. }\n  eapply multi_step. { apply ST_PlusConstConst. }\n  apply multi_refl.\nQed.\n\nLemma test_multistep_2:\n  C 3 -->* C 3.\nProof.\n  apply multi_refl. Qed.\n\nLemma test_multistep_3:\n      P (C 0) (C 3)\n   -->*\n      P (C 0) (C 3).\nProof.\n  apply multi_refl. Qed.\n\n\nLemma test_multistep_4:\n      P\n        (C 0)\n        (P\n          (C 2)\n          (P (C 0) (C 3)))\n  -->*\n      P\n        (C 0)\n        (C (2 + (0 + 3))).\nProof.\n  eapply multi_step. apply ST_Plus2. constructor.\n  apply ST_Plus2. constructor. constructor.\n  eapply multi_step. simpl.\n  apply ST_Plus2. constructor. constructor.\n  simpl.\n  apply multi_refl.\nQed.\n\nDefinition step_normal_form := normal_form step.\nDefinition normal_form_of (t t' : tm) :=\n  (t -->* t' /\\ step_normal_form t').\n\nTheorem normal_forms_unique:\n  deterministic normal_form_of.\nProof.\n  (* We recommend using this initial setup as-is! *)\n  unfold deterministic. unfold normal_form_of.\n  intros x y1 y2 P1 P2.\n  inversion P1 as [P11 P12]; clear P1.\n  inversion P2 as [P21 P22]; clear P2.\n  generalize dependent y2.\n  induction P11; intros.\n  destruct x.\n  inversion P21; subst. reflexivity.\n  inversion H; subst.\n  apply nf_is_value in P12. inversion P12.\n  apply IHP11.\n  assumption.\n  inversion P21; subst.\nAdmitted.\n\nDefinition normalizing {X : Type} (R : relation X) :=\n  forall t, exists t',\n      (multi R) t t' /\\ normal_form R t'.\n\nLemma multistep_congr_1 : forall t1 t1' t2,\n     t1 -->* t1' ->\n     P t1 t2 -->* P t1' t2.\nProof.\n  intros t1 t1' t2 H. induction H.\n  - (* multi_refl *) apply multi_refl.\n  - (* multi_step *) apply multi_step with (P y t2).\n    + apply ST_Plus1. apply H.\n    + apply IHmulti.\nQed.\n\nLemma multistep_congr_2 : forall t1 t2 t2',\n     value t1 ->\n     t2 -->* t2' ->\n     P t1 t2 -->* P t1 t2'.\nProof.\n  intros.\n  induction H0.\n  - apply multi_refl.\n  - apply multi_step with (P t1 y).\n    apply ST_Plus2. assumption.\n    assumption.\n    assumption.\nQed.\n\nTheorem step_normalizing :\n  normalizing step.\nProof.\n  unfold normalizing.\n  induction t.\n  - (* C *)\n    exists (C n).\n    split.\n    + (* l *) apply multi_refl.\n    + (* r *)\n      (* We can use rewrite with \"iff\" statements, not\n           just equalities: *)\n      rewrite nf_same_as_value. apply v_const.\n  - (* P *)\n    destruct IHt1 as [t1' [Hsteps1 Hnormal1]].\n    destruct IHt2 as [t2' [Hsteps2 Hnormal2]].\n    rewrite nf_same_as_value in Hnormal1.\n    rewrite nf_same_as_value in Hnormal2.\n    inversion Hnormal1 as [n1 H1].\n    inversion Hnormal2 as [n2 H2].\n    rewrite <- H1 in Hsteps1.\n    rewrite <- H2 in Hsteps2.\n    exists (C (n1 + n2)).\n    split.\n    + (* l *)\n      apply multi_trans with (P (C n1) t2).\n      * apply multistep_congr_1. apply Hsteps1.\n      * apply multi_trans with\n        (P (C n1) (C n2)).\n        { apply multistep_congr_2. apply v_const. apply Hsteps2. }\n        apply multi_R. { apply ST_PlusConstConst. }\n    + (* r *)\n      rewrite nf_same_as_value. apply v_const.\nQed.\n\nTheorem eval__multistep : forall t n,\n    t ==> n -> t -->* C n.\nProof.\n  intros.\n  induction H.\n  apply multi_refl.\n  apply multi_trans with (P (C n1) t2).\n  apply multistep_congr_1. assumption.\n  apply multi_trans with (P (C n1) (C n2)).\n  apply multistep_congr_2. apply v_const. assumption.\n  eapply multi_R. apply ST_PlusConstConst.\nQed.\n\nLemma step__eval : forall t t' n,\n     t --> t' ->\n     t' ==> n ->\n     t ==> n.\nProof.\n  intros t t' n Hs. generalize dependent n.\n  induction Hs; intros.\n  - inversion H; subst.\n    constructor. constructor.\n    constructor.\n  - inversion H; subst.\n    constructor. apply IHHs. assumption.\n    assumption.\n  - inversion H; subst.\n    inversion H0; subst.\n    constructor. assumption.\n    apply IHHs. assumption.\nQed.\n\nTheorem multistep__eval : forall t t',\n  normal_form_of t t' -> exists n, t' = C n /\\ t ==> n.\nProof.\n  intros.\n  destruct H.\n  induction H.\n  apply nf_is_value in H0.\n  inversion H0;subst. exists n.\n  split. reflexivity. constructor.\n  apply  IHmulti in H0.\n  destruct H0 as [n [Hz Hp]]. exists n.\n  inversion H; subst; split;\n    try reflexivity;\n    try eapply step__eval; eassumption; eassumption.\nQed.\n\n\n\n", "meta": {"author": "StarGazerM", "repo": "my-foolish-code", "sha": "2991997f9be4523bf190ef4143df8b0d89e528cf", "save_path": "github-repos/coq/StarGazerM-my-foolish-code", "path": "github-repos/coq/StarGazerM-my-foolish-code/my-foolish-code-2991997f9be4523bf190ef4143df8b0d89e528cf/plf/Smallstep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7056166829489999}}
{"text": "Require Export List. \nRequire Export ListSet. \nSet Implicit Arguments.\nUnset Strict Implicit. \n \n(*********************************************************************) \n(*                  Some List Functions                              *) \n(*********************************************************************) \n\nDefinition front (A : Set) (l : list A) : list A := rev (tail (rev l)). \n \nDefinition last (A : Set) (l : list A) := head (rev l). \n \nFixpoint take (A : Set) (n : nat) (l : list A) {struct l} : \n list A :=\n  match l with\n  | nil => nil (A:=A)\n  | a :: l' => match n with\n               | O => nil (A:=A)\n               | S m => a :: take m l'\n               end\n  end. \n\nFixpoint allunique (A : Set) (l : list A) {struct l} : Prop :=\n  match l with\n  | nil => True\n  | x :: l' => IF In x l' then False else allunique l'\n  end. \n \n(*********************************************************************) \n(*                  Some Functions for ListSet                       *) \n(*********************************************************************) \n \nDefinition IsEmpty (A : Set) (B : set A) := forall x : A, ~ set_In x B. \n \nDefinition Included (A : Set) (B C : set A) :=\n  forall x : A, set_In x B -> set_In x C. \n \nLemma AllWaysIncluded : forall (A : Set) (B : set A), Included B B. \nintros. \nunfold Included in |- *. \nauto. \n \nQed. \n \n(*********************************************************************) \n(*                  Some Results about ListSet                       *) \n(*********************************************************************) \nSection ListSetLemmas. \n \nVariable A : Set. \n \nHypothesis Aeq_dec : forall x y : A, {x = y} + {x <> y}. \n \nLemma Set_union1 :\n forall (B C : set A) (x : A),\n set_In x (set_union Aeq_dec B C) -> ~ set_In x B -> set_In x C. \nintros. \ncut (set_In x B \\/ set_In x C). \nintro H1; elim H1. \ntauto. \n \nauto. \n \neapply (set_union_elim (Aeq_dec:=Aeq_dec)); auto. \n \nQed. \n \nLemma Set_union2 :\n forall (B C : set A) (x : A),\n set_In x (set_union Aeq_dec B C) -> set_In x (set_union Aeq_dec C B). \nintros. \ncut (set_In x C \\/ set_In x B). \nintro; apply set_union_intro. \nauto. \n \ncut (set_In x B \\/ set_In x C). \ntauto. \n \neapply (set_union_elim (Aeq_dec:=Aeq_dec)). \nauto. \n \nQed. \n \n \nLemma Set_remove2 :\n forall (B : set A) (x y : A),\n set_In x (set_remove Aeq_dec y B) -> set_In x B. \nintro; intro; intro. \ninduction  B as [| a B HrecB]. \nauto. \n \nsimpl in |- *. \nelim (Aeq_dec y a). \nintros. \nright. \nauto. \n \nsimpl in |- *. \nintro. \nintro. \nelim H. \nintro. \nleft; auto. \n \nintro. \nright. \nauto. \nQed. \n \n \nLemma Set_add1 :\n forall (B : set A) (x y : A),\n set_In x (set_add Aeq_dec y B) -> x <> y -> set_In x B. \nintros. \ncut (x = y \\/ set_In x B). \nintro. \nelim H1. \nintro. \nabsurd (x = y). \nauto. \n \nauto. \n \nintro. \nauto. \n \neapply (set_add_elim (A:=A) (Aeq_dec:=Aeq_dec) (a:=x) (b:=y) (x:=B)). \nauto. \n \nQed. \n \n \nLemma Set_add2 :\n forall (B : set A) (x y : A),\n x <> y -> ~ set_In x B -> ~ set_In x (set_add Aeq_dec y B). \nintros. \nintro. \napply H0. \neapply (Set_add1 (B:=B) (x:=x) (y:=y)); auto. \n \nQed. \n \nEnd ListSetLemmas. \n \nHint Unfold IsEmpty Included. \nHint Resolve Set_remove2 Set_add1 AllWaysIncluded Set_union1 Set_union2\n  Set_add2. \n \n \n \nLemma Listeq_dec :\n forall A : Set,\n (forall a b : A, {a = b} + {a <> b}) ->\n forall x y : list A, {x = y} + {x <> y}. \nsimple induction x. \nsimple induction y. \nauto. \n \nintros. \nright. \nunfold not in |- *; intro D; discriminate D. \n \nintros. \ninduction  y as [| a0 y Hrecy]. \nright; unfold not in |- *; intro D; discriminate D. \n \nelim (H0 y). \nintro. \nrewrite a1. \nelim (H a a0). \nintro. \nrewrite a2. \nleft; auto. \n \nintro. \nright. \nunfold not in |- *. \nunfold not in b. \nintro; apply b. \ninjection H1. \nauto. \n \nunfold not in |- *; intro. \nright. \nintro; apply b. \ninjection H1. \nauto. \n \nQed. \n \nHint Resolve Listeq_dec. \n \n \nLemma Prodeq_dec :\n forall A B : Set,\n (forall x y : A, {x = y} + {x <> y}) ->\n (forall v w : B, {v = w} + {v <> w}) ->\n forall c d : A * B, {c = d} + {c <> d}. \nintros. \nelim c. \nelim d. \nintros. \nelim (H a a0); intro. \nrewrite a1. \nelim (H0 b b0); intro. \nrewrite a2. \nleft; auto. \n \nright. \nintro. \napply b1. \ninjection H1; auto. \n \nright; intro; apply b1. \ninjection H1; auto. \n \nQed. \n \nHint Resolve Prodeq_dec.", "meta": {"author": "coq-contribs", "repo": "fssec-model", "sha": "9c1148bf33f69f2e3ca4937e2243200a10c849c0", "save_path": "github-repos/coq/coq-contribs-fssec-model", "path": "github-repos/coq/coq-contribs-fssec-model/fssec-model-9c1148bf33f69f2e3ca4937e2243200a10c849c0/ListFunctions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7056166817633877}}
{"text": "\nRequire Import Arith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Init.Datatypes.\nSet Implicit Arguments .\n\n\n\nCheck 1::2::3::nil.\n\nEval compute in (1::2::3::nil) ++ (4::5::nil).\n\nEval compute in length (1::2::nil).\n\nEval compute in map (fun x => x + 1) (1::2::3::nil).\n\nEval compute in\nfold_right (fun x y => x + y) 0 (1::2::3::nil).\n\n\nDefinition ss :=\nfold_right (fun x y => x /\\ y) True (True::True::True::nil).\n\nEval compute in ss.\n\nCheck true.\nCheck andb.\nEval compute in\nfold_right (fun x y => (andb x y)) false (true::nil).\n\nSection nonemptylist.\n\nVariable X : Set.\n\nInductive nonemptylist : Set :=\n  | Single : X -> nonemptylist \n  | NewList : X -> nonemptylist -> nonemptylist.\n\n\nFixpoint app_nonempty (l1 l2 : nonemptylist) : nonemptylist := \n  match l1 with\n  | Single s  => NewList s l2\n  | NewList s rest => NewList s (app_nonempty rest l2)\n  end.\n\nEnd nonemptylist.\n\nSection Fold_Nonempty.\n  Variables A B : Set.\n  Variable f : B -> A -> A.\n  Variable a0 : A.\n\n  Fixpoint fold_nonempty (l:nonemptylist B) : A :=\n    match l with\n      | Single s => f s a0\n      | NewList s rest => f s (fold_nonempty rest)\n    end.\n\nEnd Fold_Nonempty.\n\nCheck andb.\nDefinition ne2 := Single 2.\n\nCheck Single 2.\n\nCheck app.\n\nSection MyPair.\n  Variable X : Set.\n  Variable Y : Set.\n\n  Record Twos : Set := \n  mkTwos \n  {\n    left    : X;\n    right   : Y\n  }.\nEnd MyPair.\n\nDefinition half := (mkTwos 2 5).\n\nEval compute in (left half).\nCheck half.\nCheck Twos.\n\nSection Process_Lists.\n\nVariable X : Set.\nVariable Y : Set.\nVariable Z : Set.\n\n\nFixpoint process_two_lists (l1 : nonemptylist X) (l2 : nonemptylist Y) :  nonemptylist (Twos X Y) := \n\nlet process_element_list := (fix process_element_list (e1 : X) (l2 : nonemptylist Y) :  nonemptylist (Twos X Y) :=\n  match l2 with\n    | Single s => Single (mkTwos e1 s)\n    | NewList s rest => app_nonempty (Single (mkTwos e1 s)) (process_element_list e1 rest) \n  end) in\n\n  match l1 with\n    | Single s => process_element_list s l2 \n    | NewList s rest => app_nonempty (process_element_list s l2) (process_two_lists rest l2) \n  end.\n\n\n  \n\nEnd Process_Lists.\n\nDefinition lst1 := process_two_lists (NewList 4 (NewList 8 (Single 8))) (NewList 3 (NewList 2 (Single 1))).\nEval compute in lst1.\n\n(*\nEval compute in\nfold_nonempty (fun x y => x + y) 0 lst1.\n*)\n\nDefinition lst2 := process_two_lists (NewList 91 (Single 92)) (NewList 3 (NewList 2 (Single 1))).\nEval compute in lst2.\n\n", "meta": {"author": "bsistany", "repo": "prins", "sha": "78336309f91a55a3eed1ee2447f9d15abd986654", "save_path": "github-repos/coq/bsistany-prins", "path": "github-repos/coq/bsistany-prins/prins-78336309f91a55a3eed1ee2447f9d15abd986654/FoldAndDoubleReversal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7056166751016144}}
{"text": "(* This file is an instantiation of RelationAlgebra's hrel but for\nsets as \"A -> Prop\" instead of \"A -> bool\". It is also possible to use\n\"A -> { P : Prop | P \\/ ~P }\" but we sometimes need the excluded\nmiddle if we want to be able to rewrite under negations, and also in\norder to prove that every relation is linearisable.\n\n(The same thing is/was in proprel_classic but with different names) *)\n\n(** * Propositions as a bounded distributive lattice *)\n\nFrom Coq Require Import Classical_Prop.\nFrom RelationAlgebra Require Import lattice kat.\nFrom RelationAlgebra Require Export prop.\n\n(** Lattice operations *)\n\nCanonical Structure Prop_lattice_ops: lattice.ops := {|\n  leq := impl;\n  weq := iff;\n  cup := or;\n  cap := and;\n  neg := not;\n  bot := False;\n  top := True\n|}.\n\nInstance Prop_lattice_laws: lattice.laws (BL+STR+CNV+DIV) Prop_lattice_ops.\nProof.\n  constructor; [ constructor | .. ].\n  all: repeat intros []; compute in *; try tauto.\n  pose proof classic. intro; tauto.\nQed.\n\n(** * rel: the main model of heterogeneous binary relations *)\n\nSet Printing Universes.\n\n(** We fix a type universe U and show that heterogeneous relations\nbetween types in this universe form a kleene algebra.  *)\n\nUniverse U.\nDefinition hrel (n m: Type@{U}) := n -> m -> Prop.\nDefinition relation A := hrel A A.\n\n(** * Relations as a (bounded, distributive) lattice *)\n\n(** lattice operations and laws are obtained for free, by two\n   successive pointwise liftings of the [Prop] lattice *)\n\nCanonical Structure hrel_lattice_ops n m :=\n  lattice.mk_ops (hrel n m) leq weq cup cap neg bot top.\n\n(* Having BL instead of BDL requires the excluded middle but allows\n   us to rewrite under negations *)\nGlobal Instance hrel_lattice_laws n m:\n  lattice.laws (BL+STR+CNV+DIV) (hrel_lattice_ops n m).\nProof.\n  constructor; try apply (pw_laws _).\n  all: firstorder.\nQed.\n\n(** * Relations as a residuated Kleene allegory *)\n\nSection RepOps.\n  Implicit Types n m p : Type@{U}.\n\n(** relational composition *)\nDefinition hrel_dot n m p (x: hrel n m) (y: hrel m p): hrel n p :=\n  fun i j => exists2 k, x i k & y k j.\n\n(** converse (or transpose) *)\nDefinition hrel_cnv n m (x: hrel n m): hrel m n :=\n  fun i j => x j i.\n\n(** left / right divisions *)\nDefinition hrel_ldv n m p (x: hrel n m) (y: hrel n p): hrel m p :=\n  fun i j => forall k, x k i -> y k j.\n\nDefinition hrel_rdv n m p (x: hrel m n) (y: hrel p n): hrel p m :=\n  fun j i => forall k, x i k -> y j k.\n\nSection i.\n  Variable n: Type@{U}.\n  Variable x: hrel n n.\n  (** finite iterations of a relation *)\n  Fixpoint iter u := match u with O => @eq _ | S u => hrel_dot _ _ _ x (iter u) end.\n  (** Kleene star (reflexive transitive closure) *)\n  Definition hrel_str: hrel n n := fun i j => exists u, iter u i j.\n  (** strict iteration (transitive closure) *)\n  Definition hrel_itr: hrel n n := hrel_dot n n n x hrel_str.\nEnd i.\n\nEnd RepOps.\n\n(** packing all operations into a monoid; note that the unit on [n] is\n   just the equality on [n], i.e., the identity relation on [n] *)\n\n(** We need to eta-expand @eq here. This generates the universe\nconstraint [U <= Coq.Init.Logic.8] (where the latter is the universe of\nthe type argument to [eq]). Without the eta-expansion, the definition\nwould yield the constraint [U = Coq.Init.Logig.8], which is too strong\nand leads to universe inconsistencies later on. *)\n\nCanonical Structure hrel_monoid_ops :=\n  monoid.mk_ops Type@{U} hrel_lattice_ops hrel_dot (fun n => @eq n)\n                hrel_itr hrel_str hrel_cnv hrel_ldv hrel_rdv.\n\n(** binary relations form a residuated Kleene allegory *)\nInstance hrel_monoid_laws: monoid.laws (BL+STR+CNV+DIV) hrel_monoid_ops.\nProof.\n  assert (dot_leq: forall n m p : Type@{U},\n   Proper (leq ==> leq ==> leq) (hrel_dot n m p)).\n   intros n m p x y H x' y' H' i k [j Hij Hjk]. exists j. apply H, Hij. apply H', Hjk.\n  constructor; (try now left); intros.\n   apply hrel_lattice_laws.\n   intros i j. firstorder.\n   intros i j. firstorder congruence.\n   intros i j. firstorder.\n   intros i j. reflexivity.\n   intros x y E i j. apply E.\n   intros i j E. exists O. exact E.\n   intros i k [j Hij [u Hjk]]. exists (S u). firstorder.\n   assert (E: forall i, (iter n x i: hrel n n) ⋅ z ≦ z).\n    induction i. simpl. firstorder now subst.\n    rewrite <-H0 at 2. transitivity (x⋅((iter n x i: hrel n n)⋅z)).\n     simpl. firstorder congruence. now apply dot_leq.\n    intros i j [? [? ?] ?]. eapply E. repeat eexists; eauto.\n   reflexivity.\n   intros i k [[j Hij Hjk] Hik]. exists j; trivial. split; firstorder.\n   split. intros E i j [k Hik Hkj]. apply E in Hkj. now apply Hkj.\n    intros E i j Hij k Hki. apply E. firstorder.\n   split. intros E i j [k Hik Hkj]. apply E in Hik. now apply Hik.\n    intros E i j Hij k Hki. apply E. firstorder.\nQed.\n\n\n(** * Relations as a Kleene algebra with Prop tests *)\n\nDefinition set : ob hrel_monoid_ops -> lattice.ops := fun Y => pw_ops Prop_lattice_ops Y.\n\n(** injection of Prop predicates into relations, as sub-identities *)\nDefinition hrel_inj n (x: set n): hrel n n := fun i j => i=j /\\ x i.\n\n(** packing relations and Prop sets as a Kleene algebra with tests *)\n\nCanonical Structure hrel_kat_ops :=\n  kat.mk_ops hrel_monoid_ops set hrel_inj.\n\n\nLemma iter_S {n} {x : hrel_kat_ops n n} {i} :\n  forall a c,\n    iter n x (S i) a c -> exists b, iter n x i a b /\\ x b c.\nProof.\n  induction i; intros a c it.\n  - exists a. compute. destruct it as [x0 H <-]; auto.\n  - destruct it as [d ad dc]. apply IHi in dc. firstorder.\nQed.\n\nConstraint U < pw.\nInstance hrel_set_kat_laws: kat.laws hrel_kat_ops.\nProof.\n  constructor.\n  - constructor.\n    1: now apply lower_laws.\n    all: try solve [compute; firstorder].\n    + intros n m x a b. split. intros [c <- H]; auto. intros H. exists a; firstorder; reflexivity.\n    + right. intros n m x a b. split. intros [c H <-]; auto. intros H. exists b; firstorder; reflexivity.\n    + intros _ n x a a_ <-. exists O. reflexivity.\n    + intros _ n x a c [b ab [i bc]]. exists (S i), b; auto.\n    + intros H n m x z e a c [b [i ab] bc]. revert a ab. induction i; intros a ab.\n      * rewrite ab; auto.\n      * apply e. destruct ab as [a' aa' a'b]. exists a'; eauto.\n    + intros _; right; right.\n      intros n m x z e a c [b ab [i bc]].\n      revert a b c ab bc. induction i; intros a b c ab bc.\n      * rewrite <-bc; auto.\n      * apply e. destruct (iter_S _ _ bc) as (b' & bb' & b'c). exists b'; eauto.\n  - intros A; constructor; try firstorder.\n    intros _ x a; split; compute; auto. pose proof classic. tauto.\n  - intros A. constructor; repeat intro; compute in *; discriminate || firstorder.\n  - intros A. constructor; repeat intro; compute in *; discriminate || firstorder.\n  - intros A x y a b; split.\n    + intros [<- ?]; exists a; firstorder.\n    + intros [c [<- ?] [<- ?]]. firstorder.\nQed.\n\n(*\n(** * Functional relations  *)\n\nDefinition drop_frel {A B: Set} (f: A -> B): hrel A B := fun x y => y = f x.\n\nLemma frel_comp {A B C: Set} (f: A -> B) (g: B -> C): drop_frel f ⋅ drop_frel g ≡ drop_frel (fun x => g (f x)).\nProof.\n  apply antisym. intros x z [y -> ->]. reflexivity.\n  simpl. intros x z ->. eexists; reflexivity.\nQed.\n\nInstance drop_frel_weq {A B}: Proper (pwr eq ==> weq) (@drop_frel A B).\nProof. unfold drop_frel; split; intros ->; simpl. apply H. apply eq_sym, H. Qed.\n*)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/lib/proprel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7056007218055479}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus (mult z y) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj285_coqofml_Kko27V.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7055672745872722}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************************)\n(* This contribution was updated for Coq V5.10 by the COQ workgroup.        *)\n(* January 1995                                                             *)\n(****************************************************************************)\n(*                                                                          *)\n(*      Coq V5.8                                                            *)\n(*                                                                          *)\n(*                                                                          *)\n(*      First-order Unification                                             *)\n(*                                                                          *)\n(*      Joseph Rouyer                                                       *)\n(*                                                                          *)\n(*      November 1992                                                       *)\n(*                                                                          *)\n(****************************************************************************)\n(*                         nat_term_eq_quasiterm.v                          *)\n(****************************************************************************)\n\nRequire Import Arith.\nRequire Import nat_complements.\n\n(*---------------------------------------------*)\n(*------------ Verifications on the terms:begin -------------*)\n(*---------------------------------------------*)\n\nSection nat_sequence.\n\nInductive list_nat : Set :=\n  | nil_nat : list_nat\n  | cons_nat : nat -> list_nat -> list_nat.\n\nFixpoint At_last (x : nat) (l : list_nat) {struct l} : list_nat :=\n  match l return list_nat with\n  | nil_nat =>\n      (* nil_nat *) cons_nat x nil_nat\n      (* cons_nat c ll *)\n  | cons_nat c ll => cons_nat c (At_last x ll)\n  end.\n\n\nFixpoint List_queue_nat (l : list_nat) : list_nat :=\n  match l return list_nat with\n  | nil_nat =>\n      (* nil_nat *) nil_nat\n      (* cons_nat c ll *)\n  | cons_nat c tail => At_last c (List_queue_nat tail)\n  end.\n\n\n\n\nFixpoint Constr_f (l : list_nat) : nat -> nat :=\n  fun n : nat =>\n  match l return nat with\n  | nil_nat =>\n      (* nil_nat *) 0\n  | cons_nat m tail =>\n      match n return nat with\n      | O =>\n          (* O *)  m\n          (* (S p) *)\n      | S p => Constr_f tail p\n      end\n  end.\n\n(***********************************************************************)\n(********************** Properties of  Constr_f ***************************)\n(***********************************************************************)\n\nInductive OK_Constr_f (f : list_nat -> nat -> nat) : Prop :=\n    OK_Constr_f_init :\n      (forall x : nat, 0 = f nil_nat x :>nat) ->\n      (forall (val : nat) (l : list_nat), val = f (cons_nat val l) 0 :>nat) ->\n      (forall (x val : nat) (l : list_nat),\n       f l x = f (cons_nat val l) (S x) :>nat) -> OK_Constr_f f.\n\nLemma Constr_f_OK : OK_Constr_f Constr_f.\napply OK_Constr_f_init; simpl in |- *; auto; simple induction x;\n simpl in |- *; auto.\nQed.\n\nInductive OK_At_last (f : nat -> list_nat -> list_nat) : Prop :=\n    OK_At_last_init :\n      (forall x : nat, cons_nat x nil_nat = f x nil_nat :>list_nat) ->\n      (forall x y : nat,\n       cons_nat y (cons_nat x nil_nat) = f x (f y nil_nat) :>list_nat) ->\n      OK_At_last f.\n\nLemma At_last_OK : OK_At_last At_last.\napply OK_At_last_init; simpl in |- *; auto.\nQed.\n\nInductive OK_List_queue_nat (f : list_nat -> list_nat) : Prop :=\n    OK_List_queue_nat_init :\n      nil_nat = f nil_nat :>list_nat ->\n      (forall (x : nat) (l : list_nat),\n       At_last x (f l) = f (cons_nat x l) :>list_nat) -> \n      OK_List_queue_nat f.\n\nLemma List_queue_nat_OK : OK_List_queue_nat List_queue_nat.\napply OK_List_queue_nat_init; simpl in |- *; auto.\nQed.\n\nEnd nat_sequence.\n\n(**********************************************************************)\n(******************* Specifications of terms ******************************)\n(**********************************************************************)\n\nSection terms.\n\nDefinition fun_ : Set := nat.\n\nDefinition var : Set := nat.\n\nLemma var_eq_decP : forall x x0 : var, x = x0 :>var \\/ x <> x0.\nintros; elim (nat_eq_decP x x0); auto.\nQed.\n\nLemma var_eq_decS : forall x x0 : var, {x = x0 :>var} + {x <> x0}.\nintros; elim (nat_eq_decS x x0); auto.\nQed.\n\nLemma fun_eq_decP : forall x x0 : fun_, x = x0 :>fun_ \\/ x <> x0.\nintros; elim (nat_eq_decP x x0); auto.\nQed.\n\nLemma fun_eq_decS : forall x x0 : fun_, {x = x0 :>fun_} + {x <> x0}.\nintros; elim (nat_eq_decS x x0); auto.\nQed.\n\n \nInductive quasiterm : Set :=\n  | V : var -> quasiterm (*variable quasiterm*)\n  | C : fun_ -> quasiterm (*constant quasiterm*)\n  | Root : fun_ -> quasiterm -> quasiterm (*rooting*)\n  | ConsArg : quasiterm -> quasiterm -> quasiterm.\n                                 (*building the pairs of quasiterms*)\n\n(**********************************************************************)\n(*********************** The arity function *****************************)\n(**********************************************************************)\n\nHypothesis list_arity : list_nat.\n\nDefinition arity : fun_ -> nat := Constr_f (List_queue_nat list_arity).\n\n(**********************************************************************)\n(********************** Length of a quasiterm ***************************)\n(**********************************************************************)\n\n\n\n\nFixpoint Length (t : quasiterm) : nat :=\n  match t return nat with\n  | V x => 1\n  | C f => 1\n  | Root f u => 1\n  | ConsArg t1 t2 =>\n      Length t1 + Length t2\n      (*(<nat>Match (Length t1) with (Length t2) [x:nat]S end)*)\n  end.\n\n\n(***********************************************************************)\n(********************** Predicate SIMPLE *******************************)\n(****** Simple term is constant term or variable term or rooted term. *******)\n(***********************************************************************)\n\nDefinition SIMPLE (t : quasiterm) : Prop :=\n  match t return Prop with\n  | V x => True\n  | C l => True\n  | Root l u => True\n  | ConsArg t1 t2 => False\n  end.\n\n(***********************************************************************)\n(***************** Predicates l_term and L_TERM : ***********************)\n(***********************************************************************)\n\nInductive l_term : quasiterm -> Prop :=\n  | l_term_initV : forall x : var, l_term (V x)\n  | l_term_initC : forall f : fun_, 0 = arity f :>nat -> l_term (C f)\n  | l_term_Root :\n      forall (f : fun_) (t : quasiterm),\n      l_term t -> arity f = Length t :>nat -> l_term (Root f t)\n  | l_term_ConsArg :\n      forall t1 t2 : quasiterm,\n      l_term t1 -> l_term t2 -> SIMPLE t1 -> l_term (ConsArg t1 t2).\n\nFixpoint L_TERM (t : quasiterm) : Prop :=\n  match t return Prop with\n  | V x => True\n  | C c => 0 = arity c\n  | Root l t => L_TERM t /\\ arity l = Length t\n  | ConsArg t1 t2 => SIMPLE t1 /\\ L_TERM t1 /\\ L_TERM t2\n  end.\n\n(***********************************************************************)\n(******************** L_TERM is equivalent to l_term : *******************)\n(***********************************************************************)\n\nLemma L_TERM_l_term : forall t : quasiterm, L_TERM t -> l_term t.\nintro; elim t; simpl in |- *; intros.\napply l_term_initV; auto.\napply l_term_initC; auto.\napply l_term_Root.\napply H; elim H0; auto.\nelim H0; auto.\napply l_term_ConsArg.\napply H; elim H1; intros H2 H3; elim H3; intros; auto.\napply H0; elim H1; intros H2 H3; elim H3; intros; auto.\nelim H1; auto.\nQed.\n\nLemma l_term_L_TERM : forall t : quasiterm, l_term t -> L_TERM t.\nintros; elim H; simpl in |- *; auto.\nQed.\n\n(***********************************************************************)\n(******************** Predicate term : ***********************************)\n(***********************************************************************)\n\nInductive term (t : quasiterm) : Prop :=\n    term_init : L_TERM t -> SIMPLE t -> term t.\n\n(***********************************************************************)\n(************ Decidability of L_TERM and decidability of term : ************)\n(***********************************************************************)\n\nLemma SIMPLE_decS : forall t : quasiterm, {SIMPLE t} + {~ SIMPLE t}.\nintros; elim t; simpl in |- *; auto.\nQed.\n\nLemma L_TERM_decS : forall t : quasiterm, {L_TERM t} + {~ L_TERM t}.\nsimple induction t; simpl in |- *; auto.\nintros f; elim (nat_eq_decS 0 (arity f)); intros; simpl in |- *; auto.\nintros f y h0; elim (nat_eq_decS (arity f) (Length y)); intros h.\nelim h; elim h0; intros; auto.\nright; tauto.\n\nright; tauto.\n\nintros y h y0 h0; elim h; intros.\nelim h0; intros.\nelim (SIMPLE_decS y); intros h1.\nauto.\nright; tauto.\nright; tauto.\nright; tauto.\nQed.\n\nLemma term_decS : forall t : quasiterm, {term t} + {~ term t}.\nintro; elim (L_TERM_decS t); intros h1; elim (SIMPLE_decS t); intros h2.\nleft; apply term_init; auto.\nright; unfold not in |- *; intros h3; elim h2; elim h3; intros; auto.\nright; unfold not in |- *; intros h3; elim h1; elim h3; intros; auto.\nright; unfold not in |- *; intros h3; elim h1; elim h3; intros; auto.\nQed.\n\n(***********************************************************************)\n(******************* Properties of  Length *******************************)\n(***********************************************************************)\n\nLemma Length_n_O : forall t : quasiterm, {x : nat | Length t = S x}.\nsimple induction t.\nexists 0; simpl in |- *; auto.\nexists 0; simpl in |- *; auto.\nexists 0; simpl in |- *; auto.\nintros qx Hqx qy Hqy.\nelim Hqy; elim Hqx; intros x Eqx y Eqy.\nexists (x + Length qy).\nsimpl in |- *.\nrewrite Eqx; auto.\nQed.\n \nLemma n_SO_Length_ConsArg :\n forall t t0 : quasiterm, 1 <> Length (ConsArg t t0).\nintros; elim (Length_n_O t); elim (Length_n_O t0); intros; simpl in |- *.\nreplace (Length t) with (S x0); replace (Length t0) with (S x).\nelim x0; simpl in |- *.\ndiscriminate.\nintros; discriminate.\nQed.\n\nLemma SIMPLE_SO : forall t : quasiterm, SIMPLE t -> 1 = Length t :>nat.\nsimple induction t; simpl in |- *; intros; auto.\nabsurd False; auto.\nQed.\n\nLemma Length_SO_term :\n forall t : quasiterm, L_TERM t -> 1 = Length t :>nat -> term t.\nsimple induction t; intros; apply term_init; simpl in |- *; auto.\napply (n_SO_Length_ConsArg q q0); auto.\nQed.\n\nLemma term_L_TERM_Length :\n forall t : quasiterm, term t -> L_TERM t /\\ 1 = Length t :>nat.\nsimple induction t.\nintros; simpl in |- *; auto.\nintros; simpl in |- *.\nsplit; auto.\nelim H; simpl in |- *; intros h; elim h; auto.\nsimpl in |- *; intros.\nsplit; auto.\nelim H0; simpl in |- *; intros h; elim h; intros; split; auto.\nsimpl in |- *; intros.\nsplit.\nelim H1; simpl in |- *; intros; auto.\nelim H1; simpl in |- *; intros.\nabsurd False; auto.\nQed.\n\nEnd terms.\n\nSection eq_quasiterm.\n\n(***********************************************************************)\n(************************ Structural predicates ***************************)\n(***********************************************************************)\n\nDefinition BC (t : quasiterm) : Prop :=\n  match t return Prop with\n  | V _ => False\n  | C _ => True\n  | Root _ _ => False\n  | ConsArg _ t2 => False\n  end.\n\nDefinition BV (t : quasiterm) : Prop :=\n  match t return Prop with\n  | V _ => True\n  | C _ => False\n  | Root _ _ => False\n  | ConsArg _ t2 => False\n  end.\n\nDefinition BRoot (t : quasiterm) : Prop :=\n  match t return Prop with\n  | V _ => False\n  | C _ => False\n  | Root _ _ => True\n  | ConsArg _ t2 => False\n  end.\n\nDefinition BConsArg (t : quasiterm) : Prop :=\n  match t return Prop with\n  | V _ => False\n  | C _ => False\n  | Root _ _ => False\n  | ConsArg _ t2 => True\n  end.\n\n(***********************************************************************)\n(********************** Destroyers (Destructors): *************************)\n(***********************************************************************)\nDefinition Destr1 (t : quasiterm) :=\n  match t return quasiterm with\n  | V x => V x\n  | C x => C x\n  | Root _ p => p\n  | ConsArg p _ => p\n  end.\n\nDefinition Destr2 (t : quasiterm) :=\n  match t return quasiterm with\n  | V x => V x\n  | C x => C x\n  | Root _ p => p\n  | ConsArg _ q => q\n  end.\n\nDefinition Destrvar (X : var) (t : quasiterm) :=\n  match t return var with\n  | V x => x\n  | C _ => X\n  | Root _ _ => X\n  | ConsArg _ _ => X\n  end.\n\n\nDefinition Destrfun (F : fun_) (t : quasiterm) :=\n  match t return fun_ with\n  | V _ => F\n  | C l => l\n  | Root l _ => l\n  | ConsArg p q => F\n  end.\n\n(**********************************************************************)\n(******************** Equal in the Set of quasiterms : *******************)\n(**********************************************************************)\n\nLemma proj_C : forall l1 l2 : fun_, C l1 = C l2 :>quasiterm -> l1 = l2 :>fun_.\nintros; replace l1 with (Destrfun l1 (C l1)); auto.\nreplace l2 with (Destrfun l1 (C l2)); auto.\nelim H; auto.\nQed.\n\nLemma proj_V : forall x1 x2 : var, V x1 = V x2 :>quasiterm -> x1 = x2 :>var.\nintros; replace x1 with (Destrvar x1 (V x1)); auto.\nreplace x2 with (Destrvar x1 (V x2)); auto.\nelim H; auto.\nQed.\n\nLemma proj_Root1 :\n forall (t1 t2 : quasiterm) (l1 l2 : fun_),\n Root l1 t1 = Root l2 t2 :>quasiterm -> l1 = l2 :>fun_.\nintros; replace l1 with (Destrfun l1 (Root l1 t1)); auto.\nreplace l2 with (Destrfun l1 (Root l2 t2)); auto.\nelim H; auto.\nQed.\n\nLemma proj_Root2 :\n forall (t1 t2 : quasiterm) (l1 l2 : fun_),\n Root l1 t1 = Root l2 t2 :>quasiterm -> t1 = t2 :>quasiterm.\nintros; replace t1 with (Destr1 (Root l1 t1)); auto.\nreplace t2 with (Destr2 (Root l2 t2)); auto.\nelim H; auto.\nQed.\n\nLemma proj_ConsArg1 :\n forall t1 t2 t3 t4 : quasiterm,\n ConsArg t1 t2 = ConsArg t3 t4 :>quasiterm -> t1 = t3 :>quasiterm.\nintros; replace t1 with (Destr1 (ConsArg t1 t2)); auto.\nreplace t3 with (Destr1 (ConsArg t3 t4)); auto.\nelim H; auto.\nQed.\n\nLemma proj_ConsArg2 :\n forall t1 t2 t3 t4 : quasiterm,\n ConsArg t1 t2 = ConsArg t3 t4 :>quasiterm -> t2 = t4 :>quasiterm.\nintros; replace t2 with (Destr2 (ConsArg t1 t2)); auto.\nreplace t4 with (Destr2 (ConsArg t3 t4)); auto.\nelim H; auto.\nQed.\n\n(**********************************************************************)\n(****************** Not equal in the Set of the quasiterms : **************)\n(**********************************************************************)\nLemma C_diff_C : forall l l0 : fun_, l <> l0 -> C l <> C l0 :>quasiterm.\nunfold not in |- *; intros; elim H; apply proj_C; auto.\nQed.\n\nLemma V_diff_V : forall x y : var, x <> y :>var -> V x <> V y :>quasiterm.\nunfold not in |- *; intros; elim H; apply proj_V; auto.\nQed.\n\nLemma ConsArg_diff_ConsArg :\n forall t t0 t1 t2 : quasiterm,\n t <> t1 :>quasiterm \\/ t0 <> t2 :>quasiterm ->\n ConsArg t t0 <> ConsArg t1 t2 :>quasiterm.\nunfold not in |- *; intros; elim H; intros; elim H1.\napply proj_ConsArg1 with t0 t2; auto.\napply proj_ConsArg2 with t t1; auto.\nQed.\n\nLemma Root_diff_Root :\n forall (l l0 : fun_) (t t0 : quasiterm),\n l <> l0 :>fun_ \\/ t <> t0 :>quasiterm -> Root l t <> Root l0 t0 :>quasiterm.\nunfold not in |- *; intros; elim H; intros; elim H1.\napply proj_Root1 with t t0; auto.\napply proj_Root2 with l l0; auto.\nQed.\n\n(**********************************************************************)\n(*********** Decidability of the equality in the Set of quasiterms : *********)\n(**********************************************************************)\nLemma quasiterm_eq_decS :\n forall t t0 : quasiterm, {t = t0 :>quasiterm} + {t <> t0 :>quasiterm}.\nsimple induction t.\nsimple induction t0.\n(*t=(V ...)*)\nintros; elim (var_eq_decS v v0); intros H.\nelim H; auto.\nright; apply V_diff_V; auto.\nintros; right; apply (Diff quasiterm BV); simpl in |- *; auto.\nintros; right; apply (Diff quasiterm BV); simpl in |- *; auto.\nintros; right; apply (Diff quasiterm BV); simpl in |- *; auto.\n(*t=(C ...)*)\nsimple induction t0.\nintros; right; apply (Diff quasiterm BC); simpl in |- *; auto.\nintros; elim (fun_eq_decS f f0); intros H.\nelim H; auto.\nright; apply C_diff_C; auto.\nintros; right; apply (Diff quasiterm BC); simpl in |- *; auto.\nintros; right; apply (Diff quasiterm BC); simpl in |- *; auto.\n(*t=(Root...)*)\nsimple induction t0.\nintros; right; apply (Diff quasiterm BRoot); simpl in |- *; auto.\nintros; right; apply (Diff quasiterm BRoot); simpl in |- *; auto.\nintros.\nelim (H q0); intros y.\nrewrite y; elim (fun_eq_decS f f0); intros y0.\nrewrite y0; auto.\nright; simplify_eq; auto.\nright; simplify_eq; auto.\nintros; right; simplify_eq.\n(*t=(ConsArg ...)*)\nsimple induction t0.\nintros; right; simplify_eq.\nintros; right; simplify_eq.\nintros; right; simplify_eq.\nintros y1 H1 y2 H2.\nelim (H y1); intros E1.\nelim (H0 y2); intros E2.\nrewrite E1; rewrite E2; auto.\nright; simplify_eq; tauto.\nright; simplify_eq; tauto.\nQed.\n\nLemma quasiterm_eq_decP :\n forall t t0 : quasiterm, t = t0 :>quasiterm \\/ t <> t0.\nintros; elim (quasiterm_eq_decS t t0); intros; auto.\nQed.\n\n(**********************************************************************)\n(********************* End of equality in quasiterm **********************)\n(**********************************************************************)\n\n\n(***********************************************************************)\n(************************* End eq_quasiterm. ***************************)\n(***********************************************************************)\nEnd eq_quasiterm.", "meta": {"author": "coq-contribs", "repo": "continuations", "sha": "52115376f182175321b0d9fac9ad7d61db51ddb0", "save_path": "github-repos/coq/coq-contribs-continuations", "path": "github-repos/coq/coq-contribs-continuations/continuations-52115376f182175321b0d9fac9ad7d61db51ddb0/FOUnify_cps/nat_term_eq_quasiterm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7055622019486154}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** Extraction of breadth-first numbering algorithm from Coq to Ocaml \n\n       see http://okasaki.blogspot.com/2008/07/breadth-first-numbering-algorithm-in.html\n       and https://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/jfp95queue.pdf\n       and https://www.cs.cmu.edu/~rwh/theses/okasaki.pdf\n       and https://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/icfp00bfn.pdf\n\n*)\n\nRequire Import List Arith Omega Wellfounded.\nRequire Import list_utils wf_utils bt bft fifo.\n\nSet Implicit Arguments.\n\nLocal Definition fifo_sum { X } { f : fifo (bt X) } (q : f) : nat := lsum (fifo_list q).\n\nSection bfn.\n\n  Variable (X : Type) (fX : fifo (bt X)) (fN : fifo (bt nat)).\n\n  (* the forest (list of bt nat) is a breadth first numbering from n if\n     its breadth first traversal yields [n;n+1;....;m[ for some m\n   *)\n\n  Definition is_bfn_from n l: Prop := is_seq_from n (bft_f l).\n\n  (* Breadth First Numbering: maps a forest X to a forest nat such that\n          1) the two forests are of the same shape\n          2) the result is a breadth first numbering from n \n     For this, the resulting forest is interpreted as a snoc list (in the spec., it is reversed as a list).\n   *)\n\n  Definition bfn_f_gen n (p : fX) : { q : fN | fifo_list p ~lt rev (fifo_list q) /\\ is_bfn_from n (rev (fifo_list q)) }.\n  Proof.\n    induction on n p as bfn_f_gen with measure (fifo_sum p).\n    refine (match fifo_void p as b return fifo_void p = b -> _ with\n      | true  => fun H1 => exist _ fifo_nil _\n      | false => fun H1 => _\n    end eq_refl).\n    { apply fifo_void_spec in H1.\n      rewrite H1, fifo_nil_spec; split; simpl; auto.\n      red; rewrite bft_f_fix_0; simpl; auto. }\n    assert (fifo_list p <> nil) as H2.\n    { red; intros H; apply fifo_void_spec in H; rewrite H in H1; discriminate. }\n    refine (match fifo_deq p H2 as k return fifo_deq p H2 = k -> _ with\n      | (leaf x ,p') => _\n      | (node a x b, p') => _\n    end eq_refl); intros H3.\n    + generalize (fifo_deq_spec _ p H2); rewrite H3; intros H4.\n      refine (let (q,Hq) := bfn_f_gen (S n) p' _ in exist _ (fifo_enq q (leaf n)) _).\n      { unfold fifo_sum; rewrite H4; simpl; omega. }\n      destruct Hq as (H5 & H6).\n      rewrite H4, fifo_enq_spec.\n      subst; split; auto.\n      rewrite rev_app_distr; simpl; auto.\n      rewrite rev_app_distr; simpl; red.\n      rewrite bft_f_fix_3; simpl; rewrite <- app_nil_end; auto.\n    + generalize (fifo_deq_spec _ p H2); rewrite H3; intros H4.\n      refine (let (q,Hq) := bfn_f_gen (S n) (fifo_enq (fifo_enq p' a) b) _ in _).\n      { unfold fifo_sum. \n        rewrite fifo_enq_spec, fifo_enq_spec, app_ass; simpl.\n        rewrite lsum_app, H4; simpl; omega. }\n      destruct Hq as (H5 & H6).\n      rewrite fifo_enq_spec, fifo_enq_spec, app_ass in H5; simpl in H5.\n      assert (2 <= length (fifo_list q)) as H7.\n      { apply Forall2_length in H5.\n        rewrite app_length, rev_length in H5.\n        simpl in H5; omega. }\n      assert (fifo_list q <> nil) as H8.\n      { revert H7; destruct (fifo_list q); simpl; try discriminate; intro; omega. } \n      generalize (fifo_deq_spec _ _ H8).\n      refine (match fifo_deq _ H8 with (u,q') => _ end); intros H9.\n      assert (fifo_list q' <> nil) as H10.\n      { revert H7; rewrite H9; destruct (fifo_list q'); simpl; try discriminate; intro; omega. }\n      generalize (fifo_deq_spec _ _ H10).\n      refine (match fifo_deq _ H10 with (v,q'') => _ end); intros H11.\n      exists (fifo_enq q'' (node v n u)).\n      rewrite H4, fifo_enq_spec, rev_app_distr; simpl.\n      rewrite H9, H11 in H5; simpl in H5; rewrite app_ass in H5; simpl in H5.\n      rewrite H9, H11 in H6; simpl in H6; rewrite app_ass in H6; simpl in H6.\n      unfold is_bfn_from in H6 |- *.\n      apply Forall2_2snoc_inv in H5.\n      destruct H5 as (G1 & G2 & H5).\n      rewrite bft_f_fix_3; simpl; split; auto.\n  Defined.\n\n  Section bfn.\n\n    Let bfn_full (t : bt X) : { t' | t ~t t' /\\ is_seq_from 0 (bft_std t') }.\n    Proof.\n      refine (match @bfn_f_gen 0 (fifo_enq fifo_nil t) with exist _ q Hq => _ end).\n      rewrite fifo_enq_spec, fifo_nil_spec in Hq; simpl in Hq.\n      destruct Hq as (H1 & H2).\n      assert (fifo_list q <> nil) as H3.\n      { apply Forall2_length in H1; rewrite rev_length in H1.\n        destruct (fifo_list q); discriminate. }\n      generalize (fifo_deq_spec _ _ H3).\n      refine (match fifo_deq _ H3 with (x,q') => _ end); intros H4.\n      exists x.\n      rewrite <- bft_std_eq_bft.\n      rewrite H4 in H1; simpl in H1.\n      apply Forall2_snoc_inv with (l := nil) in H1.\n      destruct H1 as (G1 & H1).\n      apply Forall2_nil_inv_right in H1.\n      apply f_equal with (f := @rev _) in H1.\n      rewrite rev_involutive in H1; simpl in H1.\n      rewrite H4, H1 in H2; simpl in H2.\n      auto.\n    Defined.\n\n    Definition bfn_gen t := proj1_sig (bfn_full t).\n\n    Fact bfn_gen_spec_1 t : t ~t bfn_gen t.\n    Proof. apply (proj2_sig (bfn_full t)). Qed.\n\n    Fact bfn_gen_spec_2 t : exists n, bft_std (bfn_gen t) = seq_an 0 n.\n    Proof. apply is_seq_from_spec, (proj2_sig (bfn_full t)). Qed.\n\n  End bfn.\n\nEnd bfn.\n\nRequire Import Extraction.\n\nDefinition bfn X := bfn_gen (fifo_two_lists (bt X)) (fifo_two_lists (bt nat)).\n\nExtraction Inline bfn_gen fifo_trivial.\nRecursive Extraction bfn.\n\nCheck bfn.\nCheck bfn_gen_spec_1.\nCheck bfn_gen_spec_2.\n             \n\n", "meta": {"author": "DmxLarchey", "repo": "Breadth-First-Numbering", "sha": "7f0fa3561968bef7f927d6bae4b1da6a67236762", "save_path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering", "path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering/Breadth-First-Numbering-7f0fa3561968bef7f927d6bae4b1da6a67236762/bfn_fifo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7055621777647959}}
{"text": "(* Exercise 19a *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* Doubly negated double negation *)\n\nTheorem exercise_019a : ~~(~~A -> A).\nProof.\ndis_e (A \\/ ~A) G H.\nLEM.\nneg_i (~~A -> A) first.\nhyp first.\nimp_i second.\nhyp G.\nneg_i (~~A -> A) first.\nhyp first.\nimp_i second.\nneg_e (~A).\nhyp second.\nhyp H.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak10/Taak10_prop019a.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.7054810518799542}}
{"text": "Require Import Coq.Relations.Relations.\nFrom Coq.Classes Require Import RelationClasses Morphisms.\nFrom algebra Require Import Semigroups Monoids Groups AbelianGroups.\n\nSection Rings.\nContext {Carrier: Type}.\nContext (equiv: relation Carrier).\nContext {equiv_equiv: Equivalence equiv}.\nContext (add: Carrier -> Carrier -> Carrier).\nContext {add_proper: Proper (equiv ==> equiv ==> equiv) add}.\nContext (zero: Carrier).\nContext (minus: Carrier -> Carrier).\nContext {minus_proper: Proper (equiv ==> equiv) minus}.\nContext (mul: Carrier -> Carrier -> Carrier).\nContext {mul_proper: Proper (equiv ==> equiv ==> equiv) mul}.\nContext (one: Carrier).\n\nInfix \"==\" := equiv (at level 60, no associativity).\nInfix \"<+>\" := add (at level 50, left associativity).\nInfix \"<*>\" := mul (at level 40, left associativity).\n\nClass Ring := {\n  ring_add_abelian :> AbelianGroup equiv add zero minus;\n  ring_mul_monoid :> Monoid equiv mul one;\n  ring_distrib_l:\n    forall (a b c: Carrier),\n      a <*> (b <+> c) == a <*> b <+> a <*> c;\n  ring_distrib_r:\n    forall (a b c: Carrier),\n      (b <+> c) <*> a == b <*> a <+> c <*> a;\n}.\n\nContext {ring: Ring}.\n\nTheorem ring_mul_0_l (a: Carrier):\n  zero <*> a == zero.\nProof.\n  apply (group_idemp_ident equiv add zero minus).\n  setoid_rewrite <- ring_distrib_r.\n  setoid_rewrite (monoid_ident_r equiv add zero).\n  reflexivity.\nQed.\n\nTheorem ring_mul_0_r (a: Carrier):\n  a <*> zero == zero.\nProof.\n  apply (group_idemp_ident equiv add zero minus).\n  setoid_rewrite <- ring_distrib_l.\n  setoid_rewrite (monoid_ident_r equiv add zero).\n  reflexivity.\nQed.\n\nTheorem ring_mul_minus_l (a b: Carrier):\n  (minus a) <*> b == minus (a <*> b).\nProof.\n  apply (group_inv_r_unique equiv add zero minus).\n  setoid_rewrite <- ring_distrib_r.\n  setoid_rewrite (group_inv_r equiv add zero minus).\n  apply ring_mul_0_l.\nQed.\n\nTheorem ring_mul_minus_r (a b: Carrier):\n  a <*> (minus b) == minus (a <*> b).\nProof.\n  apply (group_inv_r_unique equiv add zero minus).\n  setoid_rewrite <- ring_distrib_l.\n  setoid_rewrite (group_inv_r equiv add zero minus).\n  apply ring_mul_0_r.\nQed.\n\nTheorem ring_mul_minus_minus (a b: Carrier):\n  (minus a) <*> (minus b) == a <*> b.\nProof.\n  setoid_rewrite ring_mul_minus_l.\n  setoid_rewrite ring_mul_minus_r.\n  apply (group_inv_involute equiv add zero minus).\nQed.\n\nDefinition is_unit (u: Carrier) :=\n  exists (uInv: Carrier), u <*> uInv == one.\n\nTheorem ring_units_closed_mul (u0 u1: Carrier):\n  is_unit u0 ->\n  is_unit u1 ->\n  is_unit (u0 <*> u1).\nProof.\n  unfold is_unit.\n  intros [u0Inv Hu0] [u1Inv Hu1].\n  exists (u1Inv <*> u0Inv).\n  setoid_rewrite <- (semigroup_assoc equiv mul).\n  transitivity (u0 <*> (u1 <*> u1Inv) <*> u0Inv).\n  { apply (semigroup_op_r equiv mul).\n    apply (semigroup_assoc equiv mul). }\n  setoid_rewrite Hu1.\n  setoid_rewrite (monoid_ident_r equiv mul one).\n  assumption.\nQed.\n\nTheorem ring_nonunits_absorb_mul (r: Carrier):\n  ~ is_unit r ->\n  forall (s: Carrier), ~ is_unit (r <*> s).\nProof.\n  unfold is_unit.\n  intros Hnonunit s [rsInv Hcontra].\n  apply Hnonunit.\n  exists (s <*> rsInv).\n  setoid_rewrite <- (semigroup_assoc equiv mul).\n  apply Hcontra.\nQed.\nEnd Rings.\n", "meta": {"author": "ku-sldg", "repo": "algebra", "sha": "026fb7daeef2dcd88c7d6723929e90f261caf109", "save_path": "github-repos/coq/ku-sldg-algebra", "path": "github-repos/coq/ku-sldg-algebra/algebra-026fb7daeef2dcd88c7d6723929e90f261caf109/theories/Rings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7054793399449741}}
{"text": "Require Export euclidean__axioms.\nDefinition lemma__3__6a : forall A B C D, (euclidean__axioms.BetS A B C) -> ((euclidean__axioms.BetS A C D) -> (euclidean__axioms.BetS B C D)).\nProof.\nintro A.\nintro B.\nintro C.\nintro D.\nintro H.\nintro H0.\nassert (* Cut *) (euclidean__axioms.BetS C B A) as H1.\n- apply (@euclidean__axioms.axiom__betweennesssymmetry A B C H).\n- assert (* Cut *) (euclidean__axioms.BetS D C A) as H2.\n-- apply (@euclidean__axioms.axiom__betweennesssymmetry A C D H0).\n-- assert (* Cut *) (euclidean__axioms.BetS D C B) as H3.\n--- apply (@euclidean__axioms.axiom__innertransitivity D C B A H2 H1).\n--- assert (* Cut *) (euclidean__axioms.BetS B C D) as H4.\n---- apply (@euclidean__axioms.axiom__betweennesssymmetry D C B H3).\n---- exact H4.\nQed.\n", "meta": {"author": "Karnaj", "repo": "dktactgeo", "sha": "f98a62e5ffa2030dc89962e1349e0c273cc911b9", "save_path": "github-repos/coq/Karnaj-dktactgeo", "path": "github-repos/coq/Karnaj-dktactgeo/dktactgeo-f98a62e5ffa2030dc89962e1349e0c273cc911b9/lemma__3__6a.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.7053995026613756}}
{"text": "(* Exercise 82 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\n(* Destructive dilemma *)\n\nTheorem exercise_082 : (A -> B) /\\ (C -> D) -> (~B \\/ ~D) -> (~A \\/ ~C).\nProof.\nimp_i a1.\nimp_i a2.\ndis_e (~B \\/ ~D) a3 a3.\nhyp a2.\ndis_i1.\nneg_i B a4.\nhyp a3.\nimp_e A.\ncon_e1 (C -> D).\nhyp a1.\nhyp a4.\ndis_i2.\nneg_i (D) a4.\nhyp a3.\nimp_e C.\ncon_e2 (A -> B).\nhyp a1.\nhyp a4.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop082.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.7053889173754013}}
{"text": "Require Import Psatz ZArith Znumtheory Btauto.\nRequire Import QuantumLib.Prelim QuantumLib.VectorStates.\nRequire Import Examples.Utilities.\n\n(* ============================= *)\n(* =   Number theory results   = *)\n(* ============================= *)\n\nLocal Open Scope Z_scope.\nLocal Coercion Z.of_nat : nat >-> BinNums.Z.\nTactic Notation \"flia\" hyp_list(Hs) := clear - Hs; intros; nia.\n\n(*\n   exteuc a b = (n, m) :\n   a * n + b * m = gcd a b\n*)\nFixpoint exteuc (a b : nat) :=\n  match a with\n  | O => (0, 1)\n  | S a' => let (p, q) := exteuc (b mod (S a')) (S a') in\n           (q - (b / a) * p, p)\n  end.\n\nLocal Opaque Nat.modulo Nat.div Z.mul.\nLemma exteuc_correct :\n  forall (t a b : nat),\n    (a < t)%nat ->\n    let (n, m) := exteuc a b in\n    a * n + b * m = Nat.gcd a b.\nProof.\n  induction t; intros. lia.\n  bdestruct (a <? t)%nat. apply IHt. lia.\n  assert (a = t) by lia.\n  destruct a. simpl. lia.\n  simpl. rename a into a'. remember (S a') as a.\n  replace (Z.pos (Pos.of_succ_nat a')) with (Z.of_nat a) by lia.\n  assert (b mod a < a)%nat by (apply Nat.mod_upper_bound; lia).\n  assert (b mod a < t)%nat by lia.\n  specialize (IHt (b mod a)%nat a H3).\n  destruct (exteuc (b mod a) a) as (p, q) eqn:E.\n  rewrite mod_Zmod in IHt by lia. rewrite Zmod_eq_full in IHt by lia.\n  nia.\nQed.\nLocal Transparent Nat.modulo Nat.div Z.mul.\n\nLocal Close Scope Z_scope.\nLocal Open Scope nat_scope.\n\nLemma natmul1 :\n  forall a b,\n    b <> 1 ->\n    ~(a * b = 1).\nProof.\n  intros. intro. destruct a; destruct b; lia.\nQed.\n\nLemma mul_mod_1_gcd :\n  forall a b p,\n    a * b mod p = 1 ->\n    Nat.gcd a p = 1.\nProof.\n  intros. bdestruct (p =? 0). \n  subst. rewrite Nat.gcd_0_r. simpl in H. \n  try lia. (* versions < 8.14 *)\n  try (apply mult_is_one in H as [? ?]; assumption). (* version 8.14 *)\n  bdestruct (p =? 1). subst. easy.\n  bdestruct (Nat.gcd a p =? 1). easy.\n  destruct (Nat.gcd_divide a p). destruct H4, H3.\n  rewrite H3 in H. rewrite H4 in H at 2.\n  replace (x0 * Nat.gcd a p * b) with (Nat.gcd a p * (x0 * b)) in H by flia.\n  replace (x * Nat.gcd a p) with (Nat.gcd a p * x) in H by flia.\n  rewrite Nat.mul_mod_distr_l in H.\n  rewrite Nat.mul_comm in H. apply natmul1 in H; easy.\n  intro. subst. flia H4 H0.\n  intro. rewrite H5 in H4. flia H4 H0.\nQed.\n\nLemma Nsum_delete : forall n x f,\n  (x < n)%nat ->\n  (big_sum (update f x 0) n + f x = big_sum f n)%nat.\nProof.\n  induction n; intros. lia.\n  simpl. bdestruct (x =? n). subst. rewrite update_index_eq.\n  rewrite (big_sum_eq_bounded _ f). lia.\n  intros. rewrite update_index_neq. easy. lia.\n  assert (x < n)%nat by lia. apply IHn with (f := f) in H1. rewrite <- H1.\n  rewrite update_index_neq. lia. easy.\nQed.\n\n(* The main use of Nsum2d (and Nsum2dmask) is the \"Nsum2dmask_bijection\" lemma. *)\nFixpoint Nsum2d (n m : nat) (f : nat -> nat -> nat) :=\n  match n with\n  | O => O\n  | S n' => Nsum2d n' m f + big_sum (fun i => f n' i) m\n  end.\n\nLemma Nsum2d_eq :\n  forall n m f g,\n    (forall x y, x < n -> y < m -> f x y = g x y) ->\n    Nsum2d n m f = Nsum2d n m g.\nProof.\n  intros. induction n. easy.\n  simpl. rewrite (big_sum_eq_bounded _ (fun i : nat => g n i)).\n  rewrite IHn. lia.\n  intros. apply H; lia.\n  intros. apply H; lia.\nQed.\n\nLemma Nsum2d_allzero :\n  forall n m f,\n    (forall x y, x < n -> y < m -> f x y = 0) ->\n    Nsum2d n m f = 0.\nProof.\n  intros. induction n. easy.\n  simpl. rewrite IHn. rewrite (big_sum_eq_bounded _ (fun _ => 0)).\n  rewrite big_sum_0; auto.\n  intros. apply H; lia.\n  intros. apply H; lia.\nQed.\n\nLemma Nsum2d_scale :\n  forall n m f d,\n    Nsum2d n m (fun i j => d * f i j) = d * Nsum2d n m f.\nProof.\n  intros. induction n. simpl. flia.\n  simpl. rewrite IHn. \n  rewrite Nat.mul_add_distr_l.\n  rewrite Nsum_scale. \n  reflexivity.\nQed.\n\nLemma Nsum2d_eq_d2 :\n  forall n m f d,\n    (forall x, big_sum (fun i => f x i) m = d) ->\n    Nsum2d n m f = n * d.\nProof.\n  induction n; intros. easy.\n  simpl. rewrite IHn with (d := d). rewrite H. flia.\n  apply H.\nQed.\n\nLemma Nsum2d_le :\n  forall n m f g,\n    (forall x y, x < n -> y < m -> f x y <= g x y) ->\n    Nsum2d n m f <= Nsum2d n m g.\nProof.\n  intros. induction n. easy.\n  simpl.\n  assert (Nsum2d n m f <= Nsum2d n m g). {\n    apply IHn. intros. apply H; lia.\n  }\n  assert (big_sum (f n) m <= big_sum (g n) m). {\n    apply Nsum_le. intros. apply H; lia.\n  }\n  apply Nat.add_le_mono; assumption.\nQed.\n\nDefinition Nsum2d' n m (f : nat -> nat -> nat) := big_sum (fun i => big_sum (fun j => f i j) m) n.\n\nLemma Nsum2d'_Nsum2d :\n  forall n m f,\n    Nsum2d' n m f = Nsum2d n m f.\nProof.\n  intros. induction n; unfold Nsum2d' in *. easy.\n  simpl. rewrite IHn. easy.\nQed.\n\nLemma Nsum2d_swap_order :\n  forall n m f,\n    Nsum2d n m f = Nsum2d m n (fun i j => f j i).\nProof.\n  intros. do 2 rewrite <- Nsum2d'_Nsum2d.\n  induction n; unfold Nsum2d' in *. simpl. rewrite big_sum_0; easy.\n  simpl. rewrite IHn. symmetry. apply Nsum_add.\nQed.\n\nDefinition Nsum2dmask n m f (t : nat -> nat -> bool) := Nsum2d n m (fun i j => if t i j then f i j else 0).\n\nDefinition upd2d {A} f x y (a : A) := fun i j => if ((i =? x) && (j =? y)) then a else f i j.\n\nLemma upd2d_eq :\n  forall A x y f a,\n    @upd2d A f x y a x y = a.\nProof.\n  intros. unfold upd2d. do 2 rewrite Nat.eqb_refl. easy.\nQed.\n\nLemma upd2d_neq :\n  forall A x y f a i j,\n    i <> x \\/ j <> y ->\n    @upd2d A f x y a i j = f i j.\nProof.\n  intros. unfold upd2d.\n  destruct H. apply Nat.eqb_neq in H. rewrite H. easy.\n  apply Nat.eqb_neq in H. rewrite H, andb_false_r. easy.\nQed.\n\nLemma upd2d_update :\n  forall A x y f a, @upd2d A f x y a x = update (f x) y a.\nProof.\n  intros. unfold upd2d. rewrite Nat.eqb_refl. easy.\nQed.\n\nLemma Nsum2dmask_delete_d2 :\n  forall m n f t y,\n    y < m ->\n    Nsum2dmask (S n) m f (upd2d t n y false) + (if (t n y) then f n y else 0) = Nsum2dmask (S n) m f t.\nProof.\n  intros. unfold Nsum2dmask. simpl.\n  rewrite Nsum2d_eq with (g := (fun i j : nat => if t i j then f i j else 0)).\n  rewrite (big_sum_eq_bounded (fun i : nat => if upd2d t n y false n i then f n i else 0) (update (fun i : nat => if t n i then f n i else 0) y 0)).\n  rewrite plus_assoc_reverse. rewrite Nsum_delete. easy.\n  easy.\n  intros. bdestruct (y =? x). subst. rewrite upd2d_eq. rewrite update_index_eq. easy.\n  rewrite upd2d_neq by lia. rewrite update_index_neq by lia. easy.\n  intros. rewrite upd2d_neq by lia. easy.\nQed.\n\nLemma Nsum2dmask_delete :\n  forall n m f t x y,\n    x < n -> y < m ->\n    Nsum2dmask n m f (upd2d t x y false) + (if (t x y) then f x y else 0) = Nsum2dmask n m f t.\nProof.\n  induction n. easy.\n  intros. bdestruct (x =? n). subst. apply Nsum2dmask_delete_d2. easy.\n  assert (x < n) by lia.\n  unfold Nsum2dmask in *. simpl.\n  assert (forall a b c, a + b + c = (a + c) + b) by (intros; lia).\n  rewrite H3. rewrite IHn by easy. \n  rewrite (big_sum_eq_bounded _ (fun i : nat => if t n i then f n i else 0)); auto.\n  intros. rewrite upd2d_neq by lia. easy.\nQed.\n\nLemma Nsum2dmask_allfalse :\n  forall n m f t,\n    (forall x y, x < n -> y < m -> t x y = false) ->\n    Nsum2dmask n m f t = 0.\nProof.\n  intros. unfold Nsum2dmask. induction n. easy.\n  simpl. rewrite IHn. \n  rewrite (big_sum_eq_bounded _ (fun _ => 0)). \n  rewrite big_sum_constant. rewrite times_n_nat. easy.\n  intros. rewrite H. easy. lia. easy.\n  intros. apply H. lia. easy.\nQed.\n\nLemma pair_neq :\n  forall x y i j : nat, (x, y) <> (i, j) -> x <> i \\/ y <> j.\nProof.\n  intros. bdestruct (x =? i); bdestruct (y =? j); subst; try easy.\n  right. easy. left. easy. left. easy.\nQed.\n\nLemma Nsum2dmask_bijection :\n  forall n f p q g (t : nat -> nat -> bool) (map : nat -> nat * nat),\n    (forall x, x < n -> let (i, j) := map x in t i j = true) ->\n    (forall i j, i < p -> j < q -> t i j = true -> exists x, x < n /\\ map x = (i, j)) ->\n    (forall x, x < n -> let (i, j) := map x in i < p /\\ j < q) ->\n    (forall x, x < n -> let (i, j) := map x in f x = g i j) ->\n    (forall x y, x < n -> y < n -> x <> y -> map x <> map y) ->\n    big_sum f n = Nsum2dmask p q g t.\nProof.\n  induction n; intros.\n  - assert (forall x y, x < p -> y < q -> t x y = false). {\n      intros. specialize (H0 _ _ H4 H5).\n      destruct (t x y).\n      destruct H0. easy. destruct H0. lia. easy.\n    }\n    rewrite Nsum2dmask_allfalse by easy. easy.\n  - simpl. destruct (map n) as (i, j) eqn:E.\n    remember (upd2d t i j false) as u.\n    assert (t i j = true). {\n      specialize (H n). rewrite E in H. apply H. flia.\n    }\n    assert (i < p /\\ j < q). {\n      specialize (H1 n). rewrite E in H1. apply H1. flia.\n    }\n    assert (f n = g i j). {\n      specialize (H2 n). rewrite E in H2. apply H2. flia.\n    }\n    assert (forall x, x < n -> map n <> map x). {\n      intros. specialize (H3 n x). apply H3; flia H7.\n    }\n    rewrite (IHn f p q g u map). subst. symmetry. rewrite <- Nsum2dmask_delete with (x := i) (y := j).\n    rewrite H4, H6. easy. easy. easy.\n    + intros. specialize (H7 _ H8). destruct (map x) eqn:E'.\n      rewrite E in H7. apply pair_neq in H7. rewrite Hequ.\n      rewrite upd2d_neq by flia H7.\n      specialize (H x). rewrite E' in H. apply H. flia H8.\n    + intros.\n      assert (t i0 j0 = true). {\n        rewrite Hequ in H10. destruct (t i0 j0) eqn:Et. easy.\n        bdestruct (i =? i0).\n        - bdestruct (j =? j0). subst. rewrite upd2d_eq in H10. easy.\n          rewrite upd2d_neq in H10. rewrite H10 in Et. easy. right. flia H12.\n        - rewrite upd2d_neq in H10. rewrite H10 in Et. easy. left. flia H11.\n      }\n      apply H0 in H11. destruct H11 as [x [? ?]].\n      bdestruct (x =? n). subst. rewrite E in H12.\n      apply pair_equal_spec in H12. destruct H12.\n      subst. rewrite upd2d_eq in H10. easy.\n      exists x. split. flia H11 H13. easy. easy. easy.\n    + intros. apply H1. flia H8.\n    + intros. apply H2. flia H8.\n    + intros. apply H3. flia H8. flia H9. easy.\nQed.\n\nLemma Nsum2d_Nsum2dmask :\n  forall n m f t,\n    (forall x y, x < n -> y < m -> t x y = true) ->\n    Nsum2d n m f = Nsum2dmask n m f t.\nProof.\n  induction n; intros. easy.\n  unfold Nsum2dmask in *. simpl. rewrite IHn with (t := t).\n  symmetry. rewrite (big_sum_eq_bounded _ (fun i : nat => f n i)). easy.\n  intros. rewrite H by lia. easy.\n  intros. apply H; lia.\nQed.\n\nLemma Nsum_Nsum2d :\n  forall n f,\n    big_sum f n = Nsum2d 1 n (fun _ i => f i).\nProof.\n  intros. easy.\nQed.\n\nDefinition modinv (a N : nat) := let (n, m) := exteuc a N in Z.to_nat (n mod N)%Z.\n\nLemma modinv_correct :\n  forall a N,\n    0 < N ->\n    a * (modinv a N) mod N = (Nat.gcd a N) mod N.\nProof.\n  intros. unfold modinv. \n  assert (a < S a) by lia.\n  specialize (exteuc_correct (S a) a N H0) as G.\n  destruct (exteuc a N) as (n, m) eqn:E.\n  assert (((a * n + N * m) mod N)%Z = Nat.gcd a N mod N).\n  { rewrite G. rewrite mod_Zmod by lia. easy.\n  }\n  rewrite <- Zplus_mod_idemp_r in H1. replace (N * m)%Z with (m * N)%Z in H1 by lia.\n  rewrite Z_mod_mult in H1. rewrite Z.add_0_r in H1.\n  rewrite <- Zmult_mod_idemp_r in H1.\n  replace (n mod N)%Z with (Z.of_nat (Z.to_nat (n mod N)%Z)) in H1.\n  2:{ rewrite Z2Nat.id. easy.\n      assert (0 < N)%Z by lia.\n      specialize (Z.mod_pos_bound n N H2) as T.\n      lia.\n  }\n  rewrite <- Nat2Z.inj_mul in H1.\n  rewrite <- mod_Zmod in H1 by lia. \n  apply Nat2Z.inj_iff. easy.\nQed.\n\nLemma modinv_upper_bound :\n  forall a N,\n    0 < N ->\n    modinv a N < N.\nProof.\n  intros. unfold modinv. destruct (exteuc a N).\n  pattern N at 2. replace N with (Z.to_nat (Z.of_nat N)) by (rewrite Nat2Z.id; easy).\n  assert (0 <= z mod N < N)%Z by (apply Z_mod_lt; lia). \n  apply Z2Nat.inj_lt; lia.\nQed.\n\nLemma modinv_coprime' :\n  forall p q,\n    1 < p -> 0 < q ->\n    Nat.gcd p q = 1 ->\n    Nat.gcd (modinv q p) p = 1.\nProof.\n  intros.\n  assert ((q * modinv q p) mod p = 1). {\n    rewrite modinv_correct, Nat.gcd_comm, H1.\n    apply Nat.mod_small. easy. lia.\n  }\n  rewrite Nat.mul_comm in H2.\n  apply mul_mod_1_gcd with (b := q). easy.\nQed.\n\nLemma modinv_coprime :\n  forall p q,\n    1 < p ->\n    Nat.gcd p q = 1 ->\n    Nat.gcd (modinv q p) p = 1.\nProof.\n  intros.\n  bdestruct (0 <? q). apply modinv_coprime'; easy.\n  assert (q = 0) by lia. subst. rewrite Nat.gcd_0_r in H0. lia.\nQed.\n\nLemma Nsum_coprime_linear :\n  forall p (f : nat -> nat) a b,\n    a < p -> b < p -> 1 < p ->\n    Nat.gcd a p = 1 ->\n    big_sum (fun i => f ((i * a + b) mod p)%nat) p = big_sum f p.\nProof.\n  intros. rewrite Nsum_Nsum2d, Nsum2d_Nsum2dmask with (t := (fun _ _ => true)).\n  2: intros; easy.\n  symmetry. apply Nsum2dmask_bijection with (map := fun i => (0, ((i + (p - b)) * modinv a p) mod p)).\n  - intros. easy.\n  - intros. assert (i = 0) by flia H3. subst.\n    exists ((j * a + b) mod p).\n    split. apply Nat.mod_upper_bound. flia H.\n    rewrite pair_equal_spec. split. easy.\n    rewrite <- Nat.mul_mod_idemp_l by flia H.\n    rewrite Nat.add_mod_idemp_l by flia H.\n    replace (j * a + b + (p - b)) with (j * a + p) by flia H0.\n    rewrite <- Nat.add_mod_idemp_r by flia H.\n    rewrite Nat.mod_same by flia H. rewrite Nat.add_0_r.\n    rewrite Nat.mul_mod_idemp_l by flia H.\n    replace (j * a * modinv a p) with (j * (a * modinv a p)) by flia.\n    rewrite <- Nat.mul_mod_idemp_r by flia H.\n    rewrite modinv_correct by flia H. rewrite H2. rewrite Nat.mod_small with (a := 1) by flia H1.\n    rewrite Nat.mul_1_r.\n    apply Nat.mod_small. easy.\n  - intros. split. flia. apply Nat.mod_upper_bound. flia H.\n  - intros.\n    rewrite <- Nat.add_mod_idemp_l by flia H.\n    rewrite Nat.mul_mod_idemp_l by flia H.\n    replace ((x + (p - b)) * modinv a p * a) with ((x + (p - b)) * (a * modinv a p)) by flia.\n    rewrite <- Nat.mul_mod_idemp_r by flia H.\n    rewrite modinv_correct by flia H. rewrite H2. rewrite Nat.mod_small with (a := 1) by flia H1.\n    rewrite Nat.mul_1_r. rewrite Nat.add_mod_idemp_l by flia H.\n    replace (x + (p - b) + b) with (x + p) by flia H0.\n    rewrite <- Nat.add_mod_idemp_r by flia H.\n    rewrite Nat.mod_same by flia H. rewrite Nat.add_0_r.\n    rewrite Nat.mod_small; easy.\n  - intros. intro. apply pair_equal_spec in H6.\n    destruct H6.\n    assert (((x + (p - b)) * modinv a p * a + b) mod p = ((y + (p - b)) * modinv a p * a + b) mod p). {\n      rewrite <- Nat.add_mod_idemp_l, <- Nat.mul_mod_idemp_l by flia H.\n      rewrite H7.\n      rewrite Nat.mul_mod_idemp_l, Nat.add_mod_idemp_l by flia H.\n      easy.\n    }\n    replace ((x + (p - b)) * modinv a p * a) with ((x + (p - b)) * (a * modinv a p)) in H8 by flia.\n    replace ((y + (p - b)) * modinv a p * a) with ((y + (p - b)) * (a * modinv a p)) in H8 by flia.\n    rewrite <- Nat.add_mod_idemp_l, <- Nat.mul_mod_idemp_r, modinv_correct in H8 by flia H.\n    rewrite H2, Nat.mod_small with (a := 1), Nat.mul_1_r in H8 by flia H1.\n    rewrite Nat.add_mod_idemp_l in H8 by flia H.\n    replace (x + (p - b) + b) with (x + p) in H8 by flia H0.\n    rewrite <- Nat.add_mod_idemp_r, Nat.mod_same, Nat.add_0_r, Nat.mod_small in H8 by flia H H3.\n    symmetry in H8.\n    rewrite <- Nat.add_mod_idemp_l, <- Nat.mul_mod_idemp_r, modinv_correct in H8 by flia H.\n    rewrite H2, Nat.mod_small with (a := 1), Nat.mul_1_r in H8 by flia H1.\n    rewrite Nat.add_mod_idemp_l in H8 by flia H.\n    replace (y + (p - b) + b) with (y + p) in H8 by flia H0.\n    rewrite <- Nat.add_mod_idemp_r, Nat.mod_same, Nat.add_0_r, Nat.mod_small in H8 by flia H H4.\n    flia H5 H8.\nQed.\n\n\n\n\n(* ============================= *)\n(* =   Multiplicative Order    = *)\n(* ============================= *)\n\n\n\n(* r is the order of a modulo p *)\nDefinition Order (a r N : nat) :=\n  0 < r /\\\n  a^r mod N = 1 /\\\n  (forall r' : nat, (0 < r' /\\ a^r' mod N = 1) -> r' >= r).\n\nLemma pow_mod :\n  forall a b n : nat,\n    a^b mod n = (a mod n)^b mod n.\nProof.\n  intros. induction b. easy.\n  bdestruct (n =? 0). subst. easy.\n  simpl. rewrite Nat.mul_mod by easy. rewrite IHb. rewrite Nat.mul_mod_idemp_r by easy.\n  easy.\nQed.\n\nLemma Order_N_lb :\n  forall a r N, 0 < N ->\n    Order a r N ->\n    1 < N.\nProof.\n  intros a r N E H.\n  destruct (1 <? N)%nat eqn:S.\n  - apply Nat.ltb_lt in S; easy.\n  - apply Nat.ltb_ge in S. destruct H as [_ [? _]].\n    replace N with 1%nat in H by lia. simpl in H. discriminate H.\nQed.\n\nLemma Order_a_nonzero :\n  forall a r N, 0 < N ->\n    Order a r N ->\n    0 < a.\nProof.\n  intros a r n ? H. assert (HN := H). apply Order_N_lb in HN.\n  destruct (0 <? a)%nat eqn:E.\n  - apply Nat.ltb_lt in E; easy.\n  - apply Nat.ltb_ge in E. assert (a=0) by lia. destruct H as [? [? _]]. rewrite H1 in H2. rewrite Nat.pow_0_l in H2. rewrite Nat.mod_0_l in H2 by lia. lia. lia.\n  - assumption.\nQed.\n\nLemma Order_a_inv_ex :\n  forall a r N,\n    Order a r N ->\n    exists a_inv,\n      (a * a_inv) mod N = 1.\nProof.\n  intros. exists (a^(pred r))%nat. destruct H as [? [? _]].\n  assert (a * a ^ Init.Nat.pred r = a^1 * a^(Init.Nat.pred r))%nat. rewrite Nat.pow_1_r; easy. rewrite H1.\n  rewrite <- Nat.pow_add_r. rewrite Nat.succ_pred; lia.\nQed.\n\nLemma Order_rel_prime :\n  forall a r N, 0 < N ->\n    Order a r N ->\n    Nat.gcd a N = 1.\nProof.\n  intros. destruct (Order_a_inv_ex _ _ _ H0) as [ainv G].\n  specialize (Nat.gcd_divide a N) as [[a' Ha] [N' HN]].\n  remember (Nat.gcd a N) as g. bdestruct (g =? 1). easy.\n  rewrite Ha, HN in G. replace (a' * g * ainv) with (a' * ainv * g) in G by lia.\n  rewrite Nat.mul_mod_distr_r in G. specialize (natmul1 ((a' * ainv) mod N') g H1) as T. easy.\n  apply Order_N_lb in H0. lia. assumption.\n  apply Order_N_lb in H0. lia. assumption.\nQed.\n\nLemma Order_modinv_correct :\n  forall a r N, 0 < N ->\n    Order a r N ->\n    (a * (modinv a N)) mod N = 1.\nProof.\n  intros. specialize (Order_rel_prime _ _ _ H H0) as G.\n  apply Order_N_lb in H0.\n  rewrite modinv_correct by lia. rewrite G.\n  rewrite Nat.mod_small; easy.\n  assumption.\nQed.\n\nLemma inv_pow :\n  forall a r N a_inv x, 0 < N ->\n    Order a r N ->\n    (a * a_inv) mod N = 1 ->\n    (a^x * a_inv^x) mod N = 1.\nProof.\n  intros. assert (HN := H0). apply Order_N_lb in HN. induction x.\n  - simpl. apply Nat.mod_1_l. easy.\n  - simpl. rewrite Nat.mul_assoc. rewrite (Nat.mul_shuffle0 a (a^x)%nat a_inv).\n    rewrite mult_assoc_reverse with (n:=(a * a_inv)%nat). rewrite <- Nat.mul_mod_idemp_l with (a:=(a * a_inv)%nat); try lia. rewrite H1. rewrite Nat.mul_1_l. apply IHx.\n  - assumption.\nQed.\n\nLemma Pow_minus_aux :\n  forall a r N a_inv x d, 0 < N ->\n    Order a r N ->\n    (a * a_inv) mod N = 1 ->\n    a^d mod N = (a^(x + d) * a_inv^x) mod N.\nProof.\n  intros. replace (x + d)%nat with (d + x)%nat by lia. rewrite Nat.pow_add_r.\n  assert (HN := H0). apply Order_N_lb in HN.\n  rewrite <- Nat.mul_assoc. rewrite <- Nat.mul_mod_idemp_r; try lia. rewrite inv_pow with (r:=r); auto. rewrite Nat.mul_1_r. easy.\n  assumption.\nQed.\n\nLemma Pow_minus :\n  forall a r N a_inv x1 x2, 0 < N ->\n    Order a r N ->\n    x1 <= x2 ->\n    (a * a_inv) mod N = 1 ->\n    a^(x2-x1) mod N = (a^x2 * a_inv^x1) mod N.\nProof.\n  intros. rewrite Pow_minus_aux with (r:=r) (a:=a) (x:=x1) (a_inv:=a_inv); try easy. replace (x1 + (x2 - x1))%nat with (x2 - x1 + x1)%nat by lia. rewrite Nat.sub_add; easy.\nQed.\n\nLemma Pow_diff :\n  forall a r N x1 x2, 0 < N ->\n    Order a r N ->\n    0 <= x1 < r ->\n    0 <= x2 < r ->\n    x1 < x2 ->\n    a^x1 mod N <> a^x2 mod N.\nProof.\n  intros. intro.\n  assert (Ha_inv := H0). apply Order_a_inv_ex in Ha_inv. destruct Ha_inv as [a_inv Ha_inv].\n  assert (HN := H0). apply Order_N_lb in HN.\n  assert (a^(x2-x1) mod N = 1).\n  rewrite Pow_minus with (r:=r) (a_inv:=a_inv); try lia; try easy.\n  rewrite <- Nat.mul_mod_idemp_l; try lia.\n  rewrite <- H4. rewrite Nat.mul_mod_idemp_l; try lia.\n  rewrite <- Pow_minus with (r:=r); try lia; try easy.\n  rewrite Nat.sub_diag. simpl. apply Nat.mod_1_l; easy.\n  destruct H0 as [_ [_ Hminimal]].\n  specialize (Hminimal (x2 - x1)%nat) as Hcounter.\n  assert (0 < x2 - x1 /\\ a ^ (x2 - x1) mod N = 1)%nat by lia.\n  apply Hcounter in H0. lia.\n  assumption.\nQed.\n\nLemma Pow_diff_neq :\n  forall a r N x1 x2, 0 < N ->\n    Order a r N ->\n    0 <= x1 < r ->\n    0 <= x2 < r ->\n    x1 <> x2 ->\n    a^x1 mod N <> a^x2 mod N.\nProof.\n  intros. apply not_eq in H3. destruct H3.\n  - apply Pow_diff with (r:=r); easy.\n  - apply not_eq_sym. apply Pow_diff with (r:=r); easy.\nQed.\n\nLemma Pow_pos :\n  forall (a r N i : nat), 0 < N ->\n    Order a r N ->\n    a^i mod N > 0.\nProof.\n  intros. unfold gt. destruct (Nat.lt_ge_cases 0 (a ^ i mod N)). easy.\n  inversion H1.  exfalso. cut (a^r mod N = 0).\n  intros. destruct H0 as (Ha & Hb & Hc). lia.\n  assert (N <> 0).\n  { assert (1 < N). { apply (Order_N_lb a r _); easy. } lia. }\n  destruct (Nat.lt_ge_cases i r).\n  - assert (r = (i + (r - i))%nat) by lia.\n    rewrite H5. rewrite -> Nat.pow_add_r. rewrite Nat.mul_mod. rewrite H3. simpl.\n    apply Nat.mod_0_l.\n    easy. easy.\n  - assert (r = (i - (i - r))%nat) by lia.\n    rewrite H5. specialize (Order_a_inv_ex a r N H0) as e. destruct e.\n    rewrite (Pow_minus _ r _ x _ _); try easy; try lia.\n    rewrite Nat.mul_mod. rewrite H3. simpl.\n    apply Nat.mod_0_l. easy. easy.\nQed.\n\n(* from https://gist.github.com/jorpic/bf37de156f48ea438076 *)\nLemma nex_to_forall : forall k n x : nat, forall f,\n (~exists k, k < n /\\ f k = x) -> k < n -> f k <> x.\nProof.\n  intros k n x f H_nex H_P H_Q. \n  apply H_nex; exists k; auto.\nQed.\n\n(* from https://gist.github.com/jorpic/bf37de156f48ea438076 *)\nLemma exists_or_not :\n  forall n x : nat, forall f : nat -> nat,\n    (exists k, k < n /\\ f k = x) \\/ (~exists k, k < n /\\ f k = x).\nProof.\n  intros n x f.\n  induction n.\n  - right. intro H_ex.\n    destruct H_ex as [k [Hk Hf]]. easy.\n  - destruct IHn as [H_ex | H_nex].\n    + destruct H_ex as [k [H_kn H_fk]].\n      left; exists k; auto.\n    + destruct (eq_nat_dec (f n) x) as [H_fn_eqx | H_fn_neq_x].\n      * left; exists n; auto.\n      * right. intro H_nex'.\n        destruct H_nex' as [k [H_kn H_fk]].\n        apply H_fn_neq_x.\n        apply lt_n_Sm_le in H_kn.\n        apply le_lt_or_eq in H_kn.\n        destruct H_kn as [H_lt | H_eq]. \n        contradict H_fk.\n          apply (nex_to_forall k n x f H_nex H_lt).\n        rewrite <- H_eq; assumption.\nQed.\n\n(* from https://gist.github.com/jorpic/bf37de156f48ea438076 *)\nTheorem pigeonhole\n    :  forall n : nat, forall f : nat -> nat, (forall i, i <= n -> f i < n)\n    -> exists i j, i <= n /\\ j < i /\\ f i = f j.\nProof.\n  induction n.\n  - intros f Hf.\n    specialize (Hf 0 (le_refl 0)). easy.\n  - intros f Hf.\n    destruct (exists_or_not (n+1) (f (n+1)%nat) f) as [H_ex_k | H_nex_k].\n    + destruct H_ex_k as [k [Hk_le_Sn Hfk]].\n      exists (n+1)%nat, k.\n      split; [lia | split; [assumption | rewrite Hfk; reflexivity]].\n    + set (g := fun x => if eq_nat_dec (f x) n then f (n+1)%nat else f x).\n      assert (forall i : nat, i <= n -> g i < n).\n      { intros. unfold g.\n        destruct (eq_nat_dec (f i) n).\n        - apply nex_to_forall with (k := i) in H_nex_k. \n          + specialize (Hf (n+1)%nat); lia.\n          + lia.\n        - specialize (Hf i); lia.\n      }\n      destruct (IHn g H) as [x H0].\n      destruct H0 as [y [H1 [H2 H3]]].\n      exists x, y. split; [lia | split ; [assumption | idtac]].\n      (* lemma g x = g y -> f x = f y *)\n      unfold g in H3.\n      destruct eq_nat_dec in H3.\n      { destruct eq_nat_dec in H3.\n        - rewrite e; rewrite e0. reflexivity.\n        - contradict H3.\n          apply not_eq_sym.\n          apply nex_to_forall with (n := (n+1)%nat).\n          apply H_nex_k. lia.\n      }\n      { destruct eq_nat_dec in H3.\n        - contradict H3.\n          apply nex_to_forall with (n := (n+1)%nat).\n          apply H_nex_k. lia.\n        - assumption.\n      }\nQed.\n\nLemma Order_r_lt_N :\n  forall a r N, 0 < N ->\n    Order a r N ->\n    r < N.\nProof.\n  intros.\n  destruct (Nat.lt_ge_cases r N). easy.\n  remember (fun i => pred (a^i mod N))%nat as f.\n  cut (exists i j, i <= pred r /\\ j < i /\\ f i = f j).\n  - intros. destruct H2 as (i & j & H2 & H3 & H4).\n    cut (f i <> f j). easy.\n    rewrite Heqf.\n    assert (forall (a b : nat), a > 0 -> b > 0 -> a <> b -> pred a <> pred b).\n    { intros. lia. }\n    apply H5.\n    + apply (Pow_pos _ r _ _); easy.\n    + apply (Pow_pos _ r _ _); easy.\n    + assert (forall T (x y : T), x <> y -> y <> x) by auto.\n      apply H6. apply (Pow_diff _ r _ j i); try lia. easy.\n  - apply pigeonhole. intros. subst. \n    assert (forall (a b : nat), a > 0 -> b > 0 -> a < b -> pred a < pred b) by (intros; lia).\n    apply H3. apply (Pow_pos _ r _ _); easy. destruct H0. auto.\n    cut (a^i mod N < N). lia.\n    apply Nat.mod_upper_bound. \n    assert (1 < N). { apply (Order_N_lb a r _); easy. } lia.\nQed.\n", "meta": {"author": "inQWIRE", "repo": "SQIR", "sha": "7d2938bf63080e37d47059befa27a57f12cc099c", "save_path": "github-repos/coq/inQWIRE-SQIR", "path": "github-repos/coq/inQWIRE-SQIR/SQIR-7d2938bf63080e37d47059befa27a57f12cc099c/examples/shor/NumTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7053587873020313}}
{"text": "(**\nDFA (決定性有限オートマトン）を定義してみる。\n\n文献[1]：Tukuba Coq Users' Grup 「Coqによる定理証明」\n坂口さん著「反復定理で遊ぼう」\n\n実装にあたっては、\n文献[2]: https://www.ps.uni-saarland.de/~doczkal/regular/\nを参考にしているが、そのパッケージは使用しない。\n *)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import fintype finset div.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(**\n以下のDFA M = (Q, Σ, δ, q0, F) を考える（文献[1]のp.4 例1.9）。\n\nQ = {0, 1, 2, 3, 4, 5}    オートマトンの状態\nΣ = {0, 1}                受理するアルファベット\nδ(q, a) = (q + 2) mod 6 (a = 0)  状態遷移関数\nδ(q, a) = (q + 3) mod 6 (a = 1)\nq0 = 0                    初期状態\nF = {0}                   終了状態\n*)\n\nRecord dfa : Type :=\n  {\n    dfa_state :> finType;                          (* Q *)\n    dfa_char :> finType;                           (* Σ *)\n    dfa_s : dfa_state;                             (* q0 *)\n    dfa_fin : pred dfa_state;                      (* F *)\n    dfa_trans : dfa_state -> dfa_char -> dfa_state (* δ *)\n  }.\n\n(** オートマトンの状態 *)\nDefinition Q : predArgType := 'I_6.         (* {0, 1, 2, 3, 4, 5}  *)\n(** オートマトンの初期状態はq0 *)\nDefinition q0 : Q. Proof. have : 0 < 6 by []. apply Ordinal. Defined.\nCompute (nat_of_ord q0).                    (* 0 : nat *)\nDefinition q1 : Q. Proof. have : 1 < 6 by []. apply Ordinal. Defined.\nDefinition q2 : Q. Proof. have : 2 < 6 by []. apply Ordinal. Defined.\nDefinition q3 : Q. Proof. have : 3 < 6 by []. apply Ordinal. Defined.\nDefinition q4 : Q. Proof. have : 4 < 6 by []. apply Ordinal. Defined.\nDefinition q5 : Q. Proof. have : 5 < 6 by []. apply Ordinal. Defined.\n(** nat を Qに変換する。 *)\nLemma lt0_6 : 0 < 6. Proof. by []. Qed.\nDefinition qn (n : nat) : Q := Ordinal (@ltn_pmod n 6 lt0_6).\nCompute (nat_of_ord (qn 1)).                (* 1 : nat *)\n\n(** アルファベット  *)\nDefinition Sigma : predArgType := 'I_2.     (* {0, 1} *)\nDefinition a0 : Sigma. Proof. have : 0 < 2 by []. apply Ordinal. Defined.\nDefinition a1 : Sigma. Proof. have : 1 < 2 by []. apply Ordinal. Defined.\n(** nat を Sigmaに変換する。 *)\n(* Qのときと、少し違うことをしているが大差はない。 *)\nLemma lt2_pmod (n : nat) : n %% 2 < 2. Proof. by apply ltn_pmod. Qed.\nDefinition an (n : nat) : Sigma := Ordinal (lt2_pmod n).\nCompute (nat_of_ord (an 1)).                (* 1 : nat *)\n\n(** 状態遷移関数 *)\nDefinition delta (q : Q) (a : Sigma) :=\n  match (nat_of_ord a) with\n    | 0 => qn (nat_of_ord q).+2\n    | _ => qn (nat_of_ord q).+3\n  end.\n(* テスト  *)\nGoal delta q0 a0 == q2. Proof. by []. Qed.\nGoal delta q1 a0 == q3. Proof. by []. Qed.\nGoal delta q1 a0 == q3. Proof. by []. Qed.\n\n(** オートマトンの終了状態 *)\nDefinition Fin x := x \\in [:: q0].\nCompute Fin q0.                             (* true *)\nCompute Fin q1.                             (* false *)\n\n(** オートマトンの定義 *)\nDefinition mydfa := Build_dfa q0 Fin delta.\n(* テスト *)\nGoal q0 \\in @dfa_fin mydfa == true. Proof. by []. Qed.\nGoal @dfa_trans mydfa q0 a0 == q2. Proof. by []. Qed.\n\nSection DFA_Acceptance.\n  Variable A : dfa.\n  \n  Fixpoint dfa_accept (x : A) w : bool :=\n    if w is a :: w' then\n      dfa_accept (dfa_trans x a) w'\n    else\n      x \\in @dfa_fin A.\n  \n  Lemma dfa_accept_cons (x : A) a w :\n    dfa_accept x (a :: w) = dfa_accept (dfa_trans x a) w.\n  Proof.\n      by rewrite -simpl_predE /=.\n  Qed.\nEnd DFA_Acceptance.\n  \nArguments dfa_s [d].\nArguments dfa_trans [d] x a.\nArguments dfa_accept [A] x w.\nArguments dfa_accept_cons [A] x a w.\n\nGoal @dfa_accept mydfa dfa_s [::] == true.\nProof.\n  by [].\nQed.\n\nGoal @dfa_accept mydfa dfa_s [:: a0; a1; a0; a1; a0] == true.\nProof.\n  by [].\nQed.\n\n(**\n その他の 'I_6 についての補題\n*)\n\nDefinition p3 : 'I_5. Proof. have : 3 < 5 by []. apply Ordinal. Defined.\nCompute lift q3 p3.                         (* 'I_6 *)\nCompute nat_of_ord (lift q3 p3).            (* 5 : nat *)\n\nGoal #| 'I_6 | = 6.\nProof.\n  by apply card_ord.\nQed.\n\nGoal q0 \\in enum 'I_6.\nProof.\n  apply mem_enum.\nQed.\n\nGoal size (enum 'I_6) = 6.\nProof.\n  by apply size_enum_ord.\nQed.\n\nGoal index q0 (enum 'I_6) = q0.\nProof.\n  by apply index_enum_ord.\nQed.\n\nGoal [seq val i | i <- enum 'I_6] = [:: 0; 1; 2; 3; 4; 5].\nProof.\n  by rewrite val_enum_ord.\nQed.\n\nGoal ord_enum 6 =i enum 'I_6.\nProof.\n  move=> x.\n  apply/idP/idP => H.\n  - by apply mem_enum.\n  - by apply mem_ord_enum.\nQed.\n\nLemma eq_6_6 : 6 = 6. by []. Qed.\nCheck cast_ord eq_6_6 q0 : 'I_6.            (* 型を変える。 *)\nCheck lshift 0 q5 : 'I_6.                   (* 型を変える。 *)\n\nLemma le_6_8 : 6 <= 8. by []. Qed.\nCheck widen_ord le_6_8 q0 : 'I_8.           (* 型を変える。 *)\nCheck lshift 2 q5 : 'I_8.                   (* 型を変える。 *)\nCheck @lshift 6 2 q5 : 'I_8.                (* 型を変える。 *)\nCheck @rshift 2 6 q5 : 'I_8.                (* 型を変える。 *)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/regexp/ssr_simple_dfa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7053587777516346}}
{"text": "Require Import Undecidability.Shared.Libs.PSL.Base Lia.\nRequire Import Arith.\n(* Nats smaller than n *)\n\nFixpoint natsLess n : list nat :=\n  match n with\n    0 => []\n  | S n => n :: natsLess n\n  end.\n\nLemma natsLess_in_iff n m:\n  n el natsLess m <-> n < m.\nProof.\n  induction m in n|-*;cbn. lia.\n  split.\n  -intuition. destruct n; intuition lia. apply IHm in H0. lia.\n  -intros. decide (m=n). intuition lia. right. apply IHm. lia.\nQed.\n\n\nLemma natsLess_S n :\n  natsLess (S n) = map S (natsLess n)++[0].\nProof.\n  induction n;cbn in *;congruence.\nQed.\n\n\n(* Sum *)\n\nFixpoint sumn (A:list nat) :=\n  match A with\n    [] => 0\n  | a::A => a + sumn A\n  end.\n\nLemma sumn_app A B : sumn (A++B) = sumn A + sumn B.\nProof.\n  induction A;cbn;lia.\nQed.\n\nGlobal Hint Rewrite sumn_app : list. \n\nLemma length_concat X (A : list (list X)) :\n  length (concat A) = sumn (map (@length _) A).\nProof.\n  induction A;cbn. reflexivity. autorewrite with list in *. lia.\nQed.\n\nLemma sumn_rev A :\n  sumn A = sumn (rev A).\nProof.\n  enough (H:forall B, sumn A + sumn B = sumn (rev A++B)).\n  {specialize (H []). cbn in H. autorewrite with list in H. cbn in H. lia. }\n  induction A as [|a A];intros B. reflexivity.\n  cbn in *. specialize (IHA (a::B)). autorewrite with list in *. cbn in *. lia.\nQed.\n\nLemma sumn_map_natsLess f n :\n  sumn (map f (natsLess n)) = sumn (map (fun i => f (n - (1 + i))) (natsLess n)).\nProof.\n  rewrite sumn_rev. f_equal.\n  rewrite <- map_rev.\n  rewrite <- map_map with (g:=f) (f:= fun i => (n - (1+i))).\n  f_equal.\n  induction n;intros;autorewrite with list in *. reflexivity.\n  rewrite natsLess_S at 2. cbn. rewrite map_app. cbn.\n  rewrite map_map. cbn in IHn.\n  rewrite IHn. rewrite <- minus_n_O. reflexivity.\nQed.\n\n\nLemma sumn_map_add X f g (l:list X) :\n  sumn (map (fun x => f x + g x) l) = sumn (map f l) + sumn (map g l).\nProof.\n  induction l;cbn;nia.\nQed.\nLemma sumn_map_mult_c_r X f c (l:list X) :\n  sumn (map (fun x => f x *c) l) = sumn (map f l)*c.\nProof.\n  induction l;cbn;nia.\nQed.\nLemma sumn_map_c X c (l:list X) :\n  sumn (map (fun _ => c) l) = length l * c.\nProof.\n  induction l;cbn;nia.\nQed.\n\nLemma sumn_le_in n xs: n el xs -> n <= sumn xs.\nProof.\n  induction xs. easy. intros [ | ]. now cbn;nia.\n  cbn;etransitivity. apply IHxs. easy. nia.\nQed.\n\nLemma sumn_concat xs: sumn (concat xs) = sumn (map sumn xs).\nProof.\n  induction xs;cbn. easy. etransitivity. apply sumn_app. nia.\nQed.\n\n\nLemma sumn_repeat c n: sumn (repeat c n) = c * n.\nProof.\n  induction n;cbn. all:nia.\nQed.\n\nDefinition maxl := fold_right max 0.\nLemma maxl_leq n l: n el l -> n <= maxl l.\nProof.\n  induction l;cbn.\n  -easy.\n  -intros [->|]. all:apply Nat.max_case_strong;try intuition Lia.lia.\nQed.\n\nLemma maxl_leq_l c l :\n  (forall n, n el l -> n <= c) -> maxl l <= c.\nProof.\n  induction l;cbn. Lia.lia. \n  intros H. eapply Nat.max_lub_iff;split. all:eauto.  \nQed.\n\nLemma maxl_app l l': maxl (l++l') = max (maxl l) (maxl l').\nProof.\n  induction l;cbn;Lia.lia.\nQed.\n\nLemma maxl_rev l: maxl (rev l) = maxl l.\nProof.\n  unfold maxl. rewrite fold_left_rev_right. rewrite fold_symmetric. 2,3:now intros;Lia.lia.\n  induction l;cbn;try Lia.lia.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/L/Prelim/MoreList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7053587749184655}}
{"text": "Ltac forall_e H t := (generalize (H t); intro).\n\nRequire Import Setoid.\n\n\nSection Gaulois.\n  Variable personnage: Set.\n  Variables humain gaulois romain animal: personnage -> Prop.\n  Variables Idefix Panoramix: personnage.\n\n  Hypothesis Hngr: forall p:personnage, ~(gaulois p /\\ romain p).\n  Hypothesis Hpers: forall p:personnage, animal p \\/ gaulois p \\/ romain p.\n  Hypothesis Hhum: forall p:personnage, humain p <-> (gaulois p \\/ romain p).\n  Hypothesis Hnon_humain_animal:\n    forall p:personnage, ~(humain p /\\ animal p).\n\n  Hypothesis Hidef: animal Idefix.\n  Hypothesis Hpano: gaulois Panoramix.\n  Hypothesis Hrom: exists p:personnage, romain p.\n\n  Theorem Exemple: exists x:personnage, humain x /\\ ~gaulois x.\n  Proof.\n    destruct Hrom as [y Hy].\n    exists y.\n    split.\n    - rewrite Hhum.\n      right.\n      assumption.\n    - forall_e Hngr y.\n      intro Hgy.\n      apply H.\n      split.\n      + assumption.\n      + assumption.\n  Qed.\n\n(* Dans les 5 théorèmes ci-dessous, remplacez \"Admitted.\" par un \n   script de preuve complet, que vous terminerez par \"Qed.\"\n\n   Barème indicatif: pour chaque théorème, 3.5 points pour un\n   script qui prouve le théorème sans rien admetter; 0.5 point \n   supplémentaire si la preuve est structurée de manière à \n   permettre de la suivre sans interagir avec Coq (prendre exemple\n   sur la preuve précédente).\n\n   *)\n  \n  Theorem Exercice1: ~ gaulois Idefix.\n  Proof.\nintro.\nforall_e Hnon_humain_animal Idefix.\napply H0.\nsplit.\n- rewrite Hhum.\n  left;assumption.\n- assumption.\n  Qed.\n\n  Theorem Exercice2:\n    forall p:personnage, humain p -> ~romain p -> gaulois p.\n  Proof.\nintros.\nrewrite Hhum in H.\ndestruct H.\n- assumption.\n- exfalso.\n  apply H0 ; assumption.\n  Qed.\n\n  Theorem Exercice3:\n    exists p:personnage, humain p /\\ ~gaulois p.\n  Proof.\ndestruct Hrom.\nexists x.\nsplit.\n- rewrite Hhum.\n  right ; assumption.\n- intro.\n  forall_e Hngr x.\n  apply H1.\n  split.\n  * assumption.\n  * assumption.\n  Qed.\n\n  Theorem Exercice4:\n    forall p, ~animal p -> gaulois p \\/ romain p.\n  Proof.\nintros.\nforall_e Hpers p.\ndestruct H0.\n- exfalso.\n  apply H; assumption.\n- assumption.\n  Qed.\n\n  Theorem Exercice5: Idefix <> Panoramix.\n  Proof.\n    (* Indication: on peut utiliser n'importe quel théorème, \n       y compris un qui a été prouvé comme exercice *)\nintro.\nforall_e Hnon_humain_animal Idefix.\nrewrite H in Hidef.\napply H0.\nsplit.\n- rewrite H.\n  forall_e Hhum Panoramix.\n  apply H1 ; left; assumption.\n- rewrite H;assumption. \n  Qed.\n\nEnd Gaulois.", "meta": {"author": "Tpris", "repo": "Logique-et-preuve", "sha": "9aa09b9c7279201599b143918154f5a36aca83ee", "save_path": "github-repos/coq/Tpris-Logique-et-preuve", "path": "github-repos/coq/Tpris-Logique-et-preuve/Logique-et-preuve-9aa09b9c7279201599b143918154f5a36aca83ee/TP_Gaulois.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629214, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7053587745527709}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import Utf8.\nImport EqNotations.\nSet Implicit Arguments.\n\n(* useful stuff *)\n\nDefinition vmap A B n (f: A → B) (v: A^n): B^n := finfun (f \\o v).\n\n(* Language, Term, Formula *)\n\nStructure Language F R := {\n  function_arity: F → nat;\n  relation_arity: R → nat\n}.\n\nDefinition Function A n := A^n → A.\nDefinition Relation A n := A^n → Prop.\n\nInductive Term {F R} (V: eqType) (L: Language F R) :=\n  | variable: V → Term V L\n  | function_term: ∀ (f: F), (Term V L)^(function_arity L f) → Term V L.\n\nDefinition Term_induction F R (V: eqType) (L: Language F R) (P: Term V L -> Prop):\n  (∀ (s: V), P (variable V L s)) →\n  (∀ (f: F) (T: Term V L ^ function_arity L f), (forall (x: 'I_(function_arity L f)), P (T x)) → P (function_term f T)) →\n  ∀ T, P T.\nProof.\n  intros H H0. refine (fix IHt (t: Term V L) := match t with variable v => H v | function_term f T => _ end).\n  refine (H0 _ T _). intros. apply IHt.\nDefined.\n\nInductive Formula F R (V: eqType) (L: Language F R) :=\n  | equality: Term V L → Term V L → Formula V L\n  | atomic_formula: ∀ (r: R), (Term V L)^(relation_arity L r) → Formula V L\n  | negation: Formula V L → Formula V L\n  | disjunction: Formula V L → Formula V L → Formula V L\n  | conjunction: Formula V L → Formula V L → Formula V L\n  | existence_quantifier: V → Formula V L → Formula V L\n  | universal_quantifier: V → Formula V L → Formula V L.\n\nFixpoint term_has_variable F R (V: eqType) (L: Language F R) (i: V) (t: Term V L) {struct t}: bool :=\n  match t with\n  | variable x => (i == x)\n  | function_term f t' => has (eqb true) (codom (term_has_variable i \\o t'))\n  end.\n\nFixpoint formula_has_free_variable F R V (L: Language F R) (A: Formula V L) (i: V): Prop :=\n  match A with\n  | equality t1 t2 => term_has_variable i t1 ∨ term_has_variable i t2\n  | atomic_formula r v => has (term_has_variable i) (codom v)\n  | negation f => formula_has_free_variable f i\n  | disjunction f1 f2 => formula_has_free_variable f1 i ∨ formula_has_free_variable f2 i\n  | conjunction f1 f2 => formula_has_free_variable f1 i ∨ formula_has_free_variable f2 i\n  | existence_quantifier v f => v != i ∧ formula_has_free_variable f i\n  | universal_quantifier v f => v != i ∧ formula_has_free_variable f i\n  end.\n\nDefinition has_n_free_variables F R V (L: Language F R) (A: Formula V L) (n: nat) :=\n  ∃ (v: V ^ n), uniq (codom v) ∧ (∀ (x: V), formula_has_free_variable A x ↔ x \\in codom v).\n\nStructure Sentence F R V (L: Language F R) := {\n  sentenceFormula:> Formula V L;\n  sentenceProperty: ∀ i, ¬ formula_has_free_variable sentenceFormula i\n}.\n\n(* Structure, Interpretation *)\n\nStructure Structure {F R} (L: Language F R) := {\n  domain: Type;\n  function: ∀ (f: F), Function domain (function_arity L f);\n  relation: ∀ (r: R), Relation domain (relation_arity L r)\n}.\n\nFixpoint interpreted_term F R (V: eqType) (L: Language F R) (M: Structure L) (assignment: V → domain M) (T: Term V L): domain M :=\n  match T with\n  | variable x => assignment x\n  | function_term f v => function M f (finfun (interpreted_term M assignment \\o v))\n  end.\n\nFixpoint satisfies F R (V: eqType) (L: Language F R) (M: Structure L) (A: Formula V L) (assignment: V → domain M): Prop :=\n  match A with\n  | equality t1 t2 => interpreted_term M assignment t1 = interpreted_term M assignment t2\n  | atomic_formula r v => relation M r (vmap (interpreted_term M assignment) v)\n  | negation f => ¬ satisfies M f assignment\n  | disjunction f1 f2 => satisfies M f1 assignment ∨ satisfies M f2 assignment\n  | conjunction f1 f2 => satisfies M f1 assignment ∧ satisfies M f2 assignment\n  | existence_quantifier v f => ∃ i, satisfies M f (λ x, if v == x then i else assignment x)\n  | universal_quantifier v f => ∀ i, satisfies M f (λ x, if v == x then i else assignment x) \n  end.\n\nDefinition model_of_sentence F R V (L: Language F R) (M: Structure L) (A: Sentence V L) :=\n  ∀ a, satisfies M A a.\n\nDefinition model F R V (L: Language F R) (M: Structure L) (A: Sentence V L → Prop) :=\n  ∀ a, A a → model_of_sentence M a.\n\n(* Embedding, Isomorphism, Automorphism *)\n\nStructure Embedding Fm Rm Fn Rn (Lm: Language Fm Rm) (Ln: Language Fn Rn) (M: Structure Lm) (N: Structure Ln) := {\n  domain_map: domain M → domain N;\n  function_map: Fm → Fn;\n  relation_map: Rm → Rn;\n  domain_map_property: injective domain_map;\n  function_arity_preserved: ∀ f, function_arity Lm f = function_arity Ln (function_map f);\n  relation_arity_preserved: ∀ r, relation_arity Lm r = relation_arity Ln (relation_map r);\n  embedding_function_property: ∀ f v, domain_map (function M f v) =\n    function N (function_map f) (vmap domain_map (rew [λ W, (domain M ^ W)%type] (function_arity_preserved f) in v));\n  embedding_relation_property: ∀ r v, relation M r v ↔\n    relation N (relation_map r) (vmap domain_map (rew [λ W, (domain M ^ W)%type] (relation_arity_preserved r) in v));\n}.\n\nStructure Isomorphism Fm Rm Fn Rn (Lm: Language Fm Rm) (Ln: Language Fn Rn) (M: Structure Lm) (N: Structure Ln) := {\n  isomorphism_emb: Embedding M N;\n  isomorphism_emb_inv: Embedding N M;\n  isomorphism_property_1: ∀ x, domain_map isomorphism_emb (domain_map isomorphism_emb_inv x) = x;\n  isomorphism_property_2: ∀ x, domain_map isomorphism_emb_inv (domain_map isomorphism_emb x) = x\n}.\n\nDefinition Auomorphism F R (L: Language F R) (M: Structure L) := Isomorphism M M.\n\n(* Definable set *)\n\nDefinition replace_variables {V: eqType} M n (v: V ^ n) (m: M ^ n) (assignment: V → M): V → M.\nProof.\n  intro x. remember (x \\in codom v) as W. destruct W.\n  + refine (m _). exists (index x (codom v)). \n    assert (size (codom v) = n) by abstract(rewrite size_codom; simpl; apply card_ord).\n    assert (index x (codom v) < size (codom v)) by abstract(rewrite index_mem; auto).\n    abstract (rewrite H in H0; auto).\n  + exact (assignment x).\nDefined.\n\nDefinition definable F R (L: Language F R) (M: Structure L) n (X: domain M ^ n → Prop) :=\n  ∃ (V: eqType) (A: Formula V L), has_n_free_variables A n ∧\n     ∀ (a: V → domain M) (v: V ^ n), (∀ (m: domain M ^ n), X m ↔ satisfies M A (replace_variables v m a)).\n\n(* Theory, Entailment, Satisfiable, Deductively closed *)\n\nDefinition Theory F R V (L: Language F R) (C: Structure L → Prop): Sentence V L → Prop :=\n  λ (A: Sentence V L), ∀ (M: Structure L), C M → model_of_sentence M A.\n\nDefinition satisfiable_theory F R (L: Language F R) (C: Structure L → Prop) :=\n  ∃ V (M: Structure L), model M (Theory C) (V:=V).\n\nDefinition entailment F R V (L: Language F R) (S: Sentence V L → Prop) (A: Sentence V L) :=\n  ∀ (M: Structure L), model M S → model_of_sentence M A.\n\nDefinition deductively_closed F R V (L: Language F R) (S: Sentence V L → Prop) :=\n  ∀ (A: Sentence V L), entailment S A.\n\nDefinition deductive_closure F R V (L: Language F R) (S: Sentence V L → Prop): Sentence V L → Prop :=\n  λ (A: Sentence V L), entailment S A.\n\n(* Completeness *)\n\nTheorem negation_of_sentence_as_sentence F R V (L: Language F R) (A: Sentence V L): Sentence V L.\nProof.\n  refine (Build_Sentence (negation A) _). abstract (destruct A; simpl in *; auto).\nDefined.\n\nDefinition complete F R V (L: Language F R) (S: Sentence V L → Prop) :=\n  ∀ (A: Sentence V L), entailment S A ∨ entailment S (negation_of_sentence_as_sentence A).\n\n(* Elementary equivalence *)\n\nDefinition elementary_equivalence F R (L: Language F R) (M N: Structure L) :=\n  ∀ V (A: Sentence V L), model_of_sentence M A ↔ model_of_sentence N A.\n\n", "meta": {"author": "LessnessRandomness", "repo": "Model-theory-in-Coq", "sha": "851b4537e54990d0dc51a47ad45fd987c127d198", "save_path": "github-repos/coq/LessnessRandomness-Model-theory-in-Coq", "path": "github-repos/coq/LessnessRandomness-Model-theory-in-Coq/Model-theory-in-Coq-851b4537e54990d0dc51a47ad45fd987c127d198/mathcomp_version/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7052536609730882}}
{"text": "(* TLC in Coq\n *\n * Module: tlc.syntax.predicate\n * Purpose: Contains the syntax of predicates.\n *)\n\nRequire Import mathcomp.ssreflect.eqtype.\nRequire Import mathcomp.ssreflect.ssrbool.\nRequire Import mathcomp.ssreflect.ssreflect.\nRequire Import tlc.syntax.term.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Forms of logical predicates *)\nInductive predicate :=\n| PEqual (x1 x2 : term) (* x1 and x2 are equal *)\n| PLess (x1 x2 : term) (* x1 is less than x2 *)\n| PMember (y xs : term) (* y is a member of xs *)\n| PExtension (xs' xs : term). (* xs' is an extension of xs *)\n\n(* Equality *)\nSection eq.\n\n  (* Boolean equality *)\n  Definition predicate_eq p1 p2 :=\n    match p1, p2 with\n    | PEqual x1_1 x1_2, PEqual x2_1 x2_2 => (x1_1 == x2_1) && (x1_2 == x2_2)\n    | PLess x1_1 x1_2, PLess x2_1 x2_2 => (x1_1 == x2_1) && (x1_2 == x2_2)\n    | PMember y1 xs1, PMember y2 xs2 => (y1 == y2) && (xs1 == xs2)\n    | PExtension xs'1 xs1, PExtension xs'2 xs2 => (xs'1 == xs'2) && (xs1 == xs2)\n    | _, _ => false\n    end.\n\n  (* Boolean equality reflection *)\n  Lemma predicate_eqP : Equality.axiom predicate_eq.\n  Proof.\n    case=>\n      [x1_1 x1_2 | x1_1 x1_2 | y1 xs1 | xs'1 xs1]\n      [x2_1 x2_2 | x2_1 x2_2 | y2 xs2 | xs'2 xs2]\n      //=; try by constructor.\n    - have [<- | neqx] := x1_1 =P x2_1; last (by right; case); simpl.\n      have [<- | neqx] := x1_2 =P x2_2; last (by right; case); simpl.\n      by constructor.\n    - have [<- | neqx] := x1_1 =P x2_1; last (by right; case); simpl.\n      have [<- | neqx] := x1_2 =P x2_2; last (by right; case); simpl.\n      by constructor.\n    - have [<- | neqx] := y1 =P y2; last (by right; case); simpl.\n      have [<- | neqx] := xs1 =P xs2; last (by right; case); simpl.\n      by constructor.\n    - have [<- | neqx] := xs'1 =P xs'2; last (by right; case); simpl.\n      have [<- | neqx] := xs1 =P xs2; last (by right; case); simpl.\n      by constructor.\n  Qed.\n\n  (* EqType canonical structures *)\n  Definition predicate_eqMixin := EqMixin predicate_eqP.\n  Canonical predicate_eqType := EqType predicate predicate_eqMixin.\n\nEnd eq.\n", "meta": {"author": "jzgriffin", "repo": "tlc", "sha": "58919b43a5a1db887237dbeee812664147d657d4", "save_path": "github-repos/coq/jzgriffin-tlc", "path": "github-repos/coq/jzgriffin-tlc/tlc-58919b43a5a1db887237dbeee812664147d657d4/tlc/syntax/predicate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7052476098148589}}
{"text": "(** * Bijective functions *)\n\n(* Author: Maximilian Wuttke *)\n\n\nRequire Import Shared.Base.\n\n\nSection Bijection.\n  Variable X Y : Type.\n\n  (*\n   *      f\n   *   ------>\n   * X         Y\n   *   <------\n   *      g\n   *)\n\n  Definition left_inverse  (f : X -> Y) (g : Y -> X) := forall x : X, g (f x) = x.\n  Definition right_inverse (f : X -> Y) (g : Y -> X) := forall y : Y, f (g y) = y.\n  Definition inverse (f : X -> Y) (g : Y -> X) := left_inverse f g /\\ right_inverse f g.\n\n  Definition injective (f : X -> Y) :=\n    forall x y, f x = f y -> x = y.\n\n  Lemma left_inv_inj (f : X -> Y) (g : Y -> X) : left_inverse f g -> injective f.\n  Proof.\n    intros HInv. hnf in *. intros x1 x2 Heq.\n    enough (g (f x1) = g (f x2)) as L by now rewrite !HInv in L.\n    f_equal. assumption.\n  Qed.\n\n  Definition surjective (f : X -> Y) :=\n    forall y, exists x, f x = y.\n\n  Lemma right_inv_surjective f g :\n    right_inverse f g -> surjective f.\n  Proof. intros HInv. hnf. eauto. Qed.\n\n  Definition bijective (f : X -> Y) :=\n    injective f /\\ surjective f.\n  \n  Lemma inverse_bijective f g :\n    inverse f g -> bijective f.\n  Proof.\n    intros (HInv1&HInv2). hnf. split.\n    - eapply left_inv_inj; eauto.\n    - eapply right_inv_surjective; eauto.\n  Qed.\n\nEnd Bijection.\n", "meta": {"author": "uds-psl", "repo": "CoqTM", "sha": "f4d2aab2008e2158e2c7ca88ebb53b42808a0778", "save_path": "github-repos/coq/uds-psl-CoqTM", "path": "github-repos/coq/uds-psl-CoqTM/CoqTM-f4d2aab2008e2158e2c7ca88ebb53b42808a0778/external/base/Bijection.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7052471774900259}}
{"text": "Require Import Coq.NArith.NArith.\nRequire Import Coq.micromega.Lia.\n\nRequire Import Category.Lib.\nRequire Import Category.Lib.MapDecide.\nRequire Import Category.Theory.Category.\nRequire Import Category.Theory.Isomorphism.\nRequire Import Category.Theory.Functor.\n\nGeneralizable All Variables.\nSet Transparent Obligations.\n\n(* An arrows-only meta-category defines identity arrows as those which, when\n   composed to the left or right of another arrow, result in that same arrow.\n   This definition requires that all such composition be present. *)\n\nRecord Metacategory := {\n  arrow := N;\n  pairs : M.t arrow;\n\n  composite (f g h : arrow) := M.find (f, g) pairs = Some h;\n  defined (f g : arrow) := ∃ h, composite f g h;\n\n  composite_defined {f g h : arrow} (H : composite f g h) :\n    defined f g := (h; H);\n\n  (*a ∀ edges (X, Y) and (Y, Z), ∃ an edge (X, Z) which is equal to the\n     composition of those edges. *)\n  composite_correct {f g h fg gh : arrow} :\n    composite f g fg ->\n    composite g h gh → ∃ fgh, composite fg h fgh;\n\n  composition_law {f g h fg gh : arrow} :\n    composite f g fg ->\n    composite g h gh ->\n    ∀ fgh, composite fg h fgh ↔ composite f gh fgh;\n\n  is_identity (u : arrow) :=\n    (∀ f, defined f u → composite f u f) ∧\n    (∀ g, defined u g → composite u g g);\n\n  identity_law (x y f : arrow) : composite x y f ->\n    ∃ u u', is_identity u → is_identity u' ->\n      composite f u f ∧ composite u' f f\n}.\n\nSection Category.\n\nContext (M : Metacategory).\n\nRecord object := {\n  obj_arr : arrow M;\n  obj_def : composite M obj_arr obj_arr obj_arr;\n  obj_id  : is_identity M obj_arr\n}.\n\nRecord morphism (dom cod : object) := {\n  mor_arr : arrow M;\n  mor_dom : composite M mor_arr (obj_arr dom) mor_arr;\n  mor_cod : composite M (obj_arr cod) mor_arr mor_arr\n}.\n\nArguments mor_arr {_ _} _.\nArguments mor_dom {_ _} _.\nArguments mor_cod {_ _} _.\n\nDefinition identity (x : object) : morphism x x :=\n  {| mor_arr := obj_arr x\n   ; mor_dom := obj_def x\n   ; mor_cod := obj_def x |}.\n\nLemma composition_left {x y z : object}\n      {f : morphism y z} {g : morphism x y} {fg : arrow M} :\n  composite M (mor_arr f) (mor_arr g) fg ->\n  composite M (obj_arr z) (mor_arr f) (mor_arr f) ->\n  composite M (obj_arr z) fg fg.\nProof.\n  intros.\n  destruct z, obj_id0 as [c c0], f, g; simpl in *.\n  specialize (c0 _ (composite_defined M H0)); clear H0.\n  destruct (composite_correct M c0 H).\n  spose (fst (composition_law M c0 H _) e) as X.\n  unfold composite, arrow in *.\n  rewrite X, <- H, <- e; reflexivity.\nQed.\n\nLemma composition_right {x y z : object}\n      {f : morphism y z} {g : morphism x y} {fg : arrow M} :\n  composite M (mor_arr f) (mor_arr g) fg ->\n  composite M (mor_arr g) (obj_arr x) (mor_arr g) ->\n  composite M fg (obj_arr x) fg.\nProof.\n  intros.\n  destruct x, obj_id0 as [c c0], f, g; simpl in *.\n  specialize (c _ (composite_defined M H0)); clear H0.\n  destruct (composite_correct M H c).\n  spose (fst (composition_law M H c _) e) as X.\n  unfold composite, arrow in *.\n  rewrite e, <- H, <- X; reflexivity.\nQed.\n\nDefinition composition {x y z : object}\n           (f : morphism y z) (g : morphism x y) : morphism x z :=\n  let fg := composite_correct M (mor_dom f) (mor_cod g) in\n  {| mor_arr := `1 fg\n   ; mor_dom := composition_right (f:=f) (`2 fg) (mor_dom g)\n   ; mor_cod := composition_left  (g:=g) (`2 fg) (mor_cod f) |}.\n\n#[export] Program Instance morphism_preorder : PreOrder morphism := {\n  PreOrder_Reflexive  := identity;\n  PreOrder_Transitive := fun _ _ _ g f => composition f g\n}.\n\n#[export] Program Instance morphism_setoid (x y : object) :\n  Setoid (morphism x y) := {\n  equiv := fun f g => mor_arr f = mor_arr g\n}.\n\nLemma composition_respects {x y z : object} :\n  Proper (equiv ==> equiv ==> equiv) (@composition x y z).\nProof.\n  proper.\n  destruct x0, y0, x1, y1; simpl in *; subst.\n  repeat destruct (composite_correct _ _ _); simpl in *.\n  unfold composite, arrow in *.\n  rewrite e in e0.\n  inversion_clear e0.\n  reflexivity.\nQed.\n\nLemma composition_identity_left {x y : object} (f : morphism x y) :\n  composition (identity y) f ≈ f.\nProof.\n  destruct f; simpl.\n  destruct (composite_correct _ _ _); simpl in *.\n  unfold composite, arrow in *.\n  rewrite mor_cod0 in e.\n  inversion_clear e.\n  reflexivity.\nQed.\n\nLemma composition_identity_right {x y : object} (f : morphism x y) :\n  composition f (identity x) ≈ f.\nProof.\n  destruct f; simpl.\n  destruct (composite_correct _ _ _); simpl in *.\n  unfold composite, arrow in *.\n  rewrite mor_dom0 in e.\n  inversion_clear e.\n  reflexivity.\nQed.\n\nLemma composition_associative {x y z w : object}\n      (f : morphism z w) (g : morphism y z) (h : morphism x y) :\n  composition f (composition g h) ≈ composition (composition f g) h.\nProof.\n  destruct f, g, h; simpl.\n  repeat destruct (composite_correct _ _ _); simpl in *.\n  spose (fst (composition_law M e1 e x3) e2) as X1.\n  unfold composite, arrow in *.\n  rewrite e0 in X1.\n  inversion_clear X1.\n  reflexivity.\nQed.\n\n(* Every meta-category, defined wholly in terms of the axioms of category\n   theory, gives rise to a category interpreted in the context of set\n   theory. *)\n\nProgram Definition Category_from_Metacategory : Category := {|\n  obj     := object;\n  hom     := morphism;\n  homset  := fun _ _ => {| equiv := fun f g => mor_arr f = mor_arr g |};\n  id      := @identity;\n  compose := @composition;\n\n  compose_respects := @composition_respects;\n\n  id_left    := @composition_identity_left;\n  id_right   := @composition_identity_right;\n  comp_assoc := @composition_associative;\n  comp_assoc_sym := fun x y z w f g h =>\n    symmetry (@composition_associative x y z w f g h);\n|}.\n\nEnd Category.\n\nArguments mor_arr _ {_ _} _.\nArguments mor_dom _ {_ _} _.\nArguments mor_cod _ {_ _} _.\n\nImport FMapExt.\n\nLemma mapsto_inv : ∀ elt f g (fg : elt) x y z m,\n  M.MapsTo (f, g) fg (M.add (x, y) z m) ->\n    (x = f ∧ y = g ∧ z = fg) ∨ M.MapsTo (f, g) fg m.\nProof.\n  intros.\n  apply add_mapsto_iffT in H.\n  destruct H; simpl in *; intuition.\nDefined.\n\nLemma find_add_inv : ∀ f g (fg : N) x y z m,\n  M.find (f, g) (M.add (x, y) z m) = Some fg ->\n    (x = f ∧ y = g ∧ z = fg) ∨ M.find (f, g) m = Some fg.\nProof.\n  intros.\n  destruct (N.eq_dec x f).\n  - destruct (N.eq_dec y g).\n    + destruct (N.eq_dec z fg).\n      * subst; left; intuition.\n      * contradiction n.\n        rewrite F.add_eq_o in H.\n        ** inversion_clear H.\n           reflexivity.\n        ** simpl; intuition.\n    + rewrite F.add_neq_o in H; intuition.\n  - rewrite F.add_neq_o in H; intuition.\nDefined.\n\nLtac destruct_maps :=\n  repeat match goal with\n  | [ H : M.find (?X, ?Y) (M.empty _) = Some ?F |- _ ] =>\n    inversion H\n  | [ H : M.find (?X, ?Y) (M.add _ _ _) = Some ?F |- _ ] =>\n    apply find_add_inv in H;\n    (destruct H as [[? [? ?]]|]; [subst; try lia|])\n  | [ |- ∃ v, M.find _ _ = Some v ] =>\n    vm_compute; eexists; reflexivity\n\n  | [ H : M.find _ _ = Some _ |- _ ] =>\n    apply F.find_mapsto_iff in H\n  | [ |- M.find _ _ = Some _ ] =>\n    apply F.find_mapsto_iff\n  | [ |- ∃ v, M.find _ _ = Some v ] =>\n    apply find_mapsto_iff_ex\n\n  | [ H : M.MapsTo _ _ (M.empty _) |- _ ] =>\n    contradiction (proj1 (F.empty_mapsto_iff _ _) H)\n\n  | [ H : M.MapsTo (?X, ?Y) ?F (M.add _ _ _) |- _ ] =>\n    apply mapsto_inv in H; destruct H as [[? [? ?]]|]\n\n  | [ H : ?X = ?Y |- context[M.MapsTo (?Y, _)] ] =>\n    rewrite <- H; cbn\n  | [ H : ?X = ?Y |- context[M.MapsTo (_, ?Y)] ] =>\n    rewrite <- H; cbn\n  | [ H : ?X = ?Y |- context[M.MapsTo _ ?Y] ] =>\n    rewrite <- H; cbn\n\n  | [ |- ∃ _, M.MapsTo (?X, ?Y) _ _ ] =>\n    match goal with\n      [ |- context[M.add (X, Y) ?F _ ] ] =>\n      exists F\n    end\n  | [ |- M.MapsTo (?X, ?Y) ?F (M.add (?X, ?Y) ?F _) ] =>\n    simplify_maps\n  | [ |- M.MapsTo _ _ (M.add _ _ _) ] =>\n    simplify_maps; right; split; [idtac|]\n  end;\n  try congruence.\n\nLtac reflect_on_maps :=\n  simpl; intros;\n  match goal with\n  | [ |- ∃ _, M.find _ _ = _ ] => destruct_maps\n  | [ |- _ ↔ _ ] => split; intros; map_decide\n  | [ |- ∃ _ _, _ ] =>\n    destruct_maps;\n    eexists; eexists; split; intros; clear;\n    first [ instantiate (1 := 0%N); vm_compute; reflexivity\n          | instantiate (1 := 1%N); vm_compute; reflexivity\n          | instantiate (1 := 2%N); vm_compute; reflexivity\n          | instantiate (1 := 3%N); vm_compute; reflexivity\n          | instantiate (1 := 4%N); vm_compute; reflexivity\n          | instantiate (1 := 5%N); vm_compute; reflexivity\n          | instantiate (1 := 6%N); vm_compute; reflexivity\n          | instantiate (1 := 7%N); vm_compute; reflexivity\n          | instantiate (1 := 8%N); vm_compute; reflexivity\n          | instantiate (1 := 9%N); vm_compute; reflexivity ]\n  end.\n\n#[local] Open Scope N_scope.\n\nDefinition triangular_number (n : N) := (n * (n + 1)) / 2.\n\nDefinition composable_pairs_step (n : N) (z : M.t N) : M.t N :=\n  let next := triangular_number (N.pred n) in\n  let go i rest :=\n      let k j r :=\n          let mor := next + i in\n          let dom := triangular_number (j + i) + i in\n          let cod := mor + j in\n          M.add (cod, dom) mor r in\n      N.peano_rect _ rest k (n - i) in\n  N.peano_rect _ z go n.\n\nDefinition composable_pairs : N → M.t N :=\n  N.peano_rect _ (M.empty _) (λ n, composable_pairs_step (N.succ n)).\n\n(* The number of composable pairs, for objects N, is the tetrahedral_number *)\nDefinition tetrahedral_number (n : N) := (n * (n + 1) * (n + 2)) / 6.\n\n#[local] Obligation Tactic :=\n  simpl; intros; vm_compute triangular_number in *; reflect_on_maps.\n\nProgram Definition Zero  : Metacategory := {| pairs := composable_pairs 0 |}.\nProgram Definition One   : Metacategory := {| pairs := composable_pairs 1 |}.\nProgram Definition Two   : Metacategory := {| pairs := composable_pairs 2 |}.\nProgram Definition Three : Metacategory := {| pairs := composable_pairs 3 |}.\nProgram Definition Four  : Metacategory := {| pairs := composable_pairs 4 |}.\n\nLtac elimobj X :=\n  exfalso;\n  unfold composite in X; simpl in X;\n  clear -X;\n  vm_compute triangular_number in *;\n  destruct_maps; lia.\n\nLemma peano_rect' : ∀ P : N → Type, P 0%N → (∀ n : N, P (N.succ n)) → ∀ n : N, P n.\nProof.\n  intros.\n  induction n using N.peano_rect.\n  - apply X.\n  - apply X0.\nDefined.\n\nLtac reflect_on_pairs X Y F D C :=\n  repeat (\n    destruct X using peano_rect';\n    first\n      [ elimobj D | elimobj C\n      | repeat (\n          destruct Y using peano_rect';\n          first\n            [ elimobj D | elimobj C\n            | repeat (\n                destruct F using peano_rect';\n                first\n                  [ elimobj D | elimobj C\n                  | intuition idtac\n                  | reflect_on_pairs ]) ]) ]);\n  intuition.\n\nRequire Import Category.Instance.Two.\n\nMonomorphic Lemma object_Two_rect :\n  ∀ (P : object Two → Type),\n  (∀ x, obj_arr Two x = 0%N → P x) ->\n  (∀ x, obj_arr Two x = 2%N → P x) ->\n  ∀ (x : object Two), P x.\nProof.\n  intros; destruct x.\n  repeat (destruct obj_arr0 using peano_rect'; elimobj obj_def0 || auto).\nDefined.\n\nProgram Definition Two_2_object (x : object Two) : TwoObj.\nProof.\n  induction x using object_Two_rect.\n  - exact TwoX.\n  - exact TwoY.\nDefined.\n\nMonomorphic Lemma morphism_Two_rect :\n  ∀ {x y : object Two} (P : morphism Two x y → Type),\n  (∀ f, obj_arr Two x = 0%N → obj_arr Two y = 0%N → mor_arr Two f = 0%N → P f) ->\n  (∀ f, obj_arr Two x = 0%N → obj_arr Two y = 2%N → mor_arr Two f = 1%N → P f) ->\n  (∀ f, obj_arr Two x = 2%N → obj_arr Two y = 2%N → mor_arr Two f = 2%N → P f) ->\n  ∀ (f : morphism Two x y), P f.\nProof.\n  intros; destruct x, y, f.\n  reflect_on_pairs obj_arr0 obj_arr1 mor_arr0 mor_dom0 mor_cod0.\nDefined.\n\nProgram Definition Two_2_morphism (x y : object Two) (f : morphism Two x y) :\n  TwoHom (Two_2_object x) (Two_2_object y).\nProof.\n  induction f using morphism_Two_rect;\n  destruct x, y, f; simpl in *; subst; simpl.\n  - exact TwoIdX.\n  - exact TwoXY.\n  - exact TwoIdY.\nDefined.\n\n#[local] Obligation Tactic := intros.\n\nProgram Definition Two_to_Two : Category_from_Metacategory Two ⟶ _2 := {|\n  fobj := Two_2_object;\n  fmap := Two_2_morphism\n|}.\nNext Obligation.\n  proper.\n  destruct x0, y0; simpl in *; subst.\n  apply f_equal.\n  apply f_equal2;\n  apply Eqdep_dec.UIP_dec;\n  decide equality;\n  apply N.eq_dec.\nQed.\nNext Obligation.\n  simpl.\n  induction x using object_Two_rect;\n  destruct x;\n  simpl in H; subst;\n  vm_compute; reflexivity.\nQed.\nNext Obligation.\n  simpl in *.\n  induction f using morphism_Two_rect;\n  induction g using morphism_Two_rect;\n  repeat match goal with\n  | [ X : object _ |- _ ] => destruct X\n  | [ X : morphism _ _ _ |- _ ] => destruct X\n  | [ H : _ _ _ = _ |- _ ] => simpl in H\n  end; subst;\n  (exfalso; simpl in *; discriminate)\n    || (vm_compute; reflexivity).\nQed.\n\n#[local] Obligation Tactic :=\n  program_simpl;\n  try solve [ subst; unfold composite; simpl;\n              subst; vm_compute; reflexivity ].\n\nProgram Definition _2_Two_object (x : TwoObj) : object Two :=\n  match x with\n  | TwoX => {| obj_arr := 0%N; obj_def := _; obj_id  := _ |}\n  | TwoY => {| obj_arr := 2%N; obj_def := _; obj_id  := _ |}\n  end.\nNext Obligation.\n  unfold is_identity, defined, composite.\n  simpl; split; intros; destruct H; subst;\n  rewrite e; destruct_maps.\n  unfold triangular_number in e0.\n  rewrite N.div_same in e0; lia.\nDefined.\nNext Obligation.\n  unfold is_identity, defined, composite;\n  simpl; split; intros; destruct H; subst;\n  rewrite e; destruct_maps.\n  unfold triangular_number in e.\n  rewrite N.div_same in e; lia.\nDefined.\n\nProgram Definition _2_Two_morphism (x y : TwoObj) (f : TwoHom x y) :\n  morphism Two (_2_Two_object x) (_2_Two_object y) :=\n  match x as x' in TwoObj\n  return x = x' → morphism Two (_2_Two_object x) (_2_Two_object y) with\n  | TwoX => fun _ =>\n    match y as y' in TwoObj\n    return y = y' → morphism Two (_2_Two_object x) (_2_Two_object y) with\n    | TwoX => fun _ => {| mor_arr := 0%N; mor_dom := _; mor_cod := _ |}\n    | TwoY => fun _ => {| mor_arr := 1%N; mor_dom := _; mor_cod := _ |}\n    end eq_refl\n  | TwoY => fun _ =>\n    match y as y' in TwoObj\n    return y = y' → morphism Two (_2_Two_object x) (_2_Two_object y) with\n    | TwoY => fun _ => {| mor_arr := 2%N; mor_dom := _; mor_cod := _ |}\n    | TwoX => fun _ => !\n    end eq_refl\n  end eq_refl.\nNext Obligation. inversion f. Defined.\n\n#[local] Obligation Tactic := program_simpl.\n\nProgram Definition Two_from_Two : _2 ⟶ Category_from_Metacategory Two := {|\n  fobj := _2_Two_object;\n  fmap := _2_Two_morphism\n|}.\nNext Obligation. destruct x; reflexivity. Defined.\nNext Obligation.\n  destruct f; simpl;\n  destruct x; simpl;\n  spose (TwoHom_inv _ _ g) as H; subst;\n  contradiction || reflexivity.\nDefined.\n\nRequire Import Category.Instance.Cat.\n\n#[export]\nProgram Instance Two_iso_2 : Category_from_Metacategory Two ≅ _2 := {\n  to   := Two_to_Two;\n  from := Two_from_Two\n}.\nNext Obligation.\n  unshelve eexists; intros.\n  - induction x; reflexivity.\n  - induction f; reflexivity.\nQed.\nNext Obligation.\n  unshelve eexists; intros.\n  - induction x using object_Two_rect;\n    destruct x; simpl in H; subst.\n    + isomorphism; simpl.\n      * construct; [exact 0%N|..]; auto.\n      * construct; [exact 0%N|..]; auto.\n      * reflexivity.\n      * reflexivity.\n    + isomorphism; simpl.\n      * construct; [exact 2%N|..]; auto.\n      * construct; [exact 2%N|..]; auto.\n      * reflexivity.\n      * reflexivity.\n  - induction f using morphism_Two_rect;\n    destruct x, y, f;\n    simpl in H, H0, H1; subst;\n    vm_compute; reflexivity.\nQed.\n\n#[local] Obligation Tactic := simpl; intros.\n\nLemma composable_pairs_succ n :\n  composable_pairs (N.succ n)\n    = composable_pairs_step (N.succ n) (composable_pairs n).\nProof.\n  unfold composable_pairs.\n  rewrite N.peano_rect_succ; reflexivity.\nQed.\n\nLemma composable_pairs_step_disjoint n m :\n  P.Disjoint m (composable_pairs n) ->\n  P.Disjoint (composable_pairs_step (N.succ n) m) (composable_pairs n).\nProof.\n  intros.\n  generalize dependent m.\n  induction n using N.peano_rect; intros.\n  - apply P.Disjoint_alt; intros.\n    inversion H1.\n  - rewrite composable_pairs_succ in H.\nAbort.\n\nLemma composable_pairs_step_find n f g fg :\n  M.find (f, g) (composable_pairs_step (N.succ n) (composable_pairs n)) = Some fg\n    → M.find (f, g) (composable_pairs n) = Some fg ∨\n       M.find (f, g) (composable_pairs_step (N.succ n) (M.empty _)) = Some fg.\nProof.\n  generalize dependent fg.\n  generalize dependent g.\n  generalize dependent f.\n  induction n using N.peano_rect; intros.\n  - right; auto.\n  - rewrite composable_pairs_succ in *.\nAbort.\n\n(*\nProgram Definition from_composablePairs (n : N) : Metacategory := {|\n  pairs := composable_pairs n\n|}.\nNext Obligation.\n  generalize dependent gh.\n  generalize dependent fg.\n  generalize dependent h.\n  generalize dependent g.\n  generalize dependent f.\n  induction n using N.peano_rect; intros.\n    cbn in H; discriminate.\nNext Obligation.\n  generalize dependent gh.\n  generalize dependent fg.\n  generalize dependent h.\n  generalize dependent g.\n  generalize dependent f.\n  induction n; cbn; intros.\n    discriminate.\nNext Obligation.\n  generalize dependent f.\n  generalize dependent y.\n  generalize dependent x.\n  induction n; cbn; intros; eauto.\n*)\n", "meta": {"author": "jwiegley", "repo": "category-theory", "sha": "5376e32a4eeace4a84674820083bc2985a2a593f", "save_path": "github-repos/coq/jwiegley-category-theory", "path": "github-repos/coq/jwiegley-category-theory/category-theory-5376e32a4eeace4a84674820083bc2985a2a593f/Theory/Metacategory/ArrowsOnly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7052471741227283}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** * Object-level representation of Diophantine equations *)\n(** ** Diophantine logic *)\n\nRequire Import Arith Nat Omega.\nRequire Import gcd.\n\nSet Implicit Arguments.\n\nSection diophantine_expressions.\n\n  Inductive dio_op := do_add | do_mul.\n\n  Definition do_eval o :=\n    match o with\n      | do_add => plus\n      | do_mul => mult\n    end.\n\n  Inductive dio_expression : Set :=\n    | de_cst  : nat -> dio_expression\n    | de_var  : nat -> dio_expression\n    | de_comp : dio_op -> dio_expression -> dio_expression -> dio_expression.\n\n  Definition de_add := de_comp do_add.\n  Definition de_mul := de_comp do_mul.\n\n  Fixpoint de_size e :=\n    match e with\n      | de_cst n => 1\n      | de_var x => 1\n      | de_comp _ p q => 1 + de_size p + de_size q\n    end.\n\n  Fixpoint de_size_Z e :=\n    (match e with\n      | de_cst n => 1\n      | de_var x => 1\n      | de_comp _ p q => 1 + de_size_Z p + de_size_Z q\n    end)%Z.\n\n  Fact de_size_Z_spec e : de_size_Z e = Z.of_nat (de_size e).\n  Proof.\n    induction e as [ | | o f Hf g Hg ]; auto.\n    simpl de_size; unfold de_size_Z; fold de_size_Z.\n    rewrite Nat2Z.inj_succ, Nat2Z.inj_add; omega.\n  Qed.\n\n  Fixpoint de_eval ν e  :=\n    match e with\n      | de_cst n => n\n      | de_var x => ν x\n      | de_comp o p q => do_eval o (de_eval ν p) (de_eval ν q)\n    end.\n\n  Fact de_eval_ext e ν ω : (forall x, ν x = ω x) -> de_eval ν e = de_eval ω e.\n  Proof.\n    intros H; induction e as [ | | [] ]; simpl; auto.\n  Qed.\n\n  (* ρ σ ν *)\n\n  Fixpoint de_subst σ e :=\n    match e with\n      | de_cst n => de_cst n\n      | de_var x => σ x\n      | de_comp o p q => de_comp o (de_subst σ p) (de_subst σ q)\n    end.\n\n  Fact de_eval_subst σ ν e : de_eval ν (de_subst σ e) = de_eval (fun x => de_eval ν (σ x)) e.\n  Proof. induction e as [ | | [] ]; simpl; auto. Qed.\n\n  Fact de_subst_subst σ1 σ2 e : de_subst σ1 (de_subst σ2 e) = de_subst (fun x => de_subst σ1 (σ2 x)) e.\n  Proof. induction e as [ | | [] ]; simpl; f_equal; auto. Qed.\n\n  Definition de_ren ρ := de_subst (fun x => de_var (ρ x)).\n\n  Fact de_ren_size ρ e : de_size (de_ren ρ e) = de_size e.\n  Proof.\n    revert ρ; induction e as [ | | o e He f Hf ]; intros rho; auto.\n    unfold de_ren; simpl de_subst; unfold de_size; fold de_size. \n    f_equal; [ f_equal | ].\n    * apply He.\n    * apply Hf.\n  Qed.\n\n  Fact de_ren_size_Z ρ e : de_size_Z (de_ren ρ e) = de_size_Z e.\n  Proof. do 2 rewrite de_size_Z_spec; f_equal; apply de_ren_size. Qed.\n\n  Fact de_eval_ren ρ ν e : de_eval ν (de_ren ρ e)  = de_eval (fun x => ν (ρ x)) e.\n  Proof. apply de_eval_subst. Qed.\n\n  Definition de_lift := de_ren S.\n\n  Fact de_eval_lift ν e : de_eval ν (de_lift e) = de_eval (fun x => ν (S x)) e.\n  Proof. apply de_eval_ren. Qed.\n\nEnd diophantine_expressions.\n\nDefinition dio_expr t := { e | forall ν, de_eval ν e = t ν }.\n\nNotation 𝔻P := dio_expr.\n\nSection dio_expr.\n\n  (* How to analyse meta-level diophantine expressions *)\n\n  Implicit Types r t : (nat -> nat) -> nat.\n\n  Fact dio_expr_var i : 𝔻P (fun v => v i).\n  Proof. exists (de_var i); simpl; auto. Defined.\n\n  Fact dio_expr_cst c : 𝔻P (fun _ => c).\n  Proof. exists (de_cst c); simpl; auto. Defined.\n\n  Fact dio_expr_plus r t : 𝔻P r -> 𝔻P t -> 𝔻P (fun ν => r ν + t ν).\n  Proof. intros (e1 & H1) (e2 & H2); exists (de_add e1 e2); simpl; auto. Defined.\n  \n  Fact dio_expr_mult r t : 𝔻P r -> 𝔻P t -> 𝔻P (fun ν => r ν * t ν).\n  Proof. intros (e1 & H1) (e2 & H2); exists (de_mul e1 e2); simpl; auto. Defined.\n\n  Fact dio_expr_ren t ρ : 𝔻P t -> 𝔻P (fun ν => t (fun i => ν (ρ i))).\n  Proof. intros (e & He); exists (de_ren ρ e); intros; rewrite de_eval_ren, He; tauto. Defined.\n\n  Fact dio_expr_subst t σ : 𝔻P t -> 𝔻P (fun ν => t (fun i => de_eval ν (σ i))).\n  Proof. intros (e & He); exists (de_subst σ e); intros; rewrite de_eval_subst, He; tauto. Defined.\n\nEnd dio_expr.\n\nHint Resolve dio_expr_var dio_expr_cst dio_expr_plus dio_expr_mult dio_expr_ren.\n\nSection diophantine_logic.\n\n  (* De Bruin syntax for diophantine formulas of the form\n\n         A,B ::= e1 = e2 | A /\\ B | A \\/ B | ∃x.A\n\n   *)\n\n  Inductive dio_formula : Set :=\n    | df_atm  : dio_expression -> dio_expression -> dio_formula   (* a = b *)\n    | df_conj : dio_formula -> dio_formula -> dio_formula \n    | df_disj : dio_formula -> dio_formula -> dio_formula\n    | df_exst : dio_formula -> dio_formula.\n\n  Fixpoint df_size f :=\n    match f with\n      | df_atm a b  => 1 + de_size a + de_size b\n      | df_conj f g => 1 + df_size f + df_size g  \n      | df_disj f g => 1 + df_size f + df_size g  \n      | df_exst f   => 1 + df_size f\n    end.\n\n  Fixpoint df_size_Z f :=\n    (match f with\n      | df_atm a b  => 1 + de_size_Z a + de_size_Z b\n      | df_conj f g => 1 + df_size_Z f + df_size_Z g  \n      | df_disj f g => 1 + df_size_Z f + df_size_Z g  \n      | df_exst f   => 1 + df_size_Z f\n    end)%Z.\n\n  Fact df_size_Z_spec f : df_size_Z f = Z.of_nat (df_size f).\n  Proof.\n    induction f as [ a b | f Hf g Hg | f Hf g Hg | f Hf ]; simpl df_size;\n      rewrite Nat2Z.inj_succ; try rewrite Nat2Z.inj_add; unfold df_size_Z; fold df_size_Z; auto; try omega.\n    do 2 rewrite de_size_Z_spec; omega.\n  Qed.\n\n\n  (* dv_lift : lifting of a diophantive valuation *)\n\n  Definition dv_lift X ν (x : X) n :=\n     match n with \n       | 0   => x \n       | S n => ν n \n     end.\n\n  Fixpoint df_pred f ν :=\n    match f with\n      | df_atm a b  => de_eval ν a  = de_eval ν b\n      | df_conj f g => df_pred f ν /\\ df_pred g ν\n      | df_disj f g => df_pred f ν \\/ df_pred g ν\n      | df_exst f   => exists n, df_pred f (dv_lift ν n)\n    end.\n\n  Fact df_pred_atm a b ν : df_pred (df_atm a b) ν = (de_eval ν a = de_eval ν b).\n  Proof. auto. Qed.\n  \n  Fact df_pred_conj f g ν : df_pred (df_conj f g) ν = (df_pred f ν /\\ df_pred g ν).\n  Proof. auto. Qed.\n\n  Fact df_pred_disj f g ν : df_pred (df_disj f g) ν = (df_pred f ν \\/ df_pred g ν).\n  Proof. auto. Qed.\n\n  Fact df_pred_exst f ν : df_pred (df_exst f) ν = exists n, df_pred f (dv_lift ν n).\n  Proof. auto. Qed.\n\n  Fact df_pred_ext f ν ω : (forall x, ν x = ω x) -> df_pred f ν <-> df_pred f ω.\n  Proof.\n    revert ν ω; induction f as [ a b | f Hf g Hg | f Hf g Hg | f Hf ]; intros ν ω H; simpl.\n    + do 2 rewrite de_eval_ext with (1 := H); tauto.\n    + rewrite Hf, Hg; auto; tauto.\n    + rewrite Hf, Hg; auto; tauto.\n    + split; intros (n & Hn); exists n; revert Hn; apply Hf;\n        intros []; simpl; auto.\n  Qed.\n\n  (* Lifting of a diophantine expression renaming *)\n\n  Definition der_lift ρ x := match x with 0 => 0 | S x => S (ρ x) end.\n\n  Fixpoint df_ren ρ f :=\n    match f with\n      | df_atm a b  => let σ := fun x => de_var (ρ x) in df_atm (de_subst σ a) (de_subst σ b)\n      | df_conj f g => df_conj (df_ren ρ f) (df_ren ρ g)\n      | df_disj f g => df_disj (df_ren ρ f) (df_ren ρ g)\n      | df_exst f   => df_exst (df_ren (der_lift ρ) f)\n    end.\n\n  Fact df_ren_size ρ f : df_size (df_ren ρ f) = df_size f.\n  Proof.\n    revert ρ; induction f; intros; simpl; auto; do 2 f_equal; auto.\n    all: apply de_ren_size.\n  Qed.\n\n  Fact df_ren_size_Z ρ f : df_size_Z (df_ren ρ f) = df_size_Z f.\n  Proof.\n    do 2 rewrite df_size_Z_spec; f_equal; apply df_ren_size.\n  Qed.\n\n  Fact df_pred_ren f ν ρ : df_pred (df_ren ρ f) ν <-> df_pred f (fun x => ν (ρ x)).\n  Proof.\n    revert ν ρ; induction f as [ a b | f Hf g Hg | f Hf g Hg | f Hf ]; intros ν ρ; simpl.\n    + repeat rewrite de_eval_subst; simpl; tauto.\n    + rewrite Hf, Hg; tauto.\n    + rewrite Hf, Hg; tauto.\n    + split; intros (n & Hn); exists n; revert Hn; rewrite Hf;\n        apply df_pred_ext; intros []; simpl; auto.\n  Qed.\n\n  (* Lifting of a diophantine expression substitutions *)\n\n  Definition des_lift σ x := match x with 0 => de_var 0 | S x => de_ren S (σ x) end. \n     \n  Fixpoint df_subst σ f := \n    match f with\n      | df_atm a b  => df_atm (de_subst σ a) (de_subst σ b)\n      | df_conj f g => df_conj (df_subst σ f) (df_subst σ g)\n      | df_disj f g => df_disj (df_subst σ f) (df_subst σ g)\n      | df_exst f   => df_exst (df_subst (des_lift σ) f)\n    end.\n\n  Fact df_pred_subst f ν σ : df_pred (df_subst σ f) ν <-> df_pred f (fun x => de_eval ν (σ x)).\n  Proof.\n    revert ν σ; induction f as [ a b | f Hf g Hg | f Hf g Hg | f Hf ]; intros ν σ; simpl.\n    + repeat rewrite de_eval_subst; simpl; tauto.\n    + rewrite Hf, Hg; tauto.\n    + rewrite Hf, Hg; tauto.\n    + split; intros (n & Hn); exists n; revert Hn; rewrite Hf;\n        apply df_pred_ext; intros []; simpl; auto;\n        rewrite de_eval_ren; apply de_eval_ext; auto.\n  Qed.\n\n  Definition df_lift := df_ren S.\n\n  Fact df_pred_lift f ν : df_pred (df_lift f) ν <-> df_pred f (fun x => ν (S x)).\n  Proof. apply df_pred_ren. Qed. \n\nEnd diophantine_logic.\n\nSection examples.\n\n  Variable ν : nat -> nat.\n\n  Definition df_true := df_atm (de_cst 0) (de_cst 0).\n  Definition df_false := df_atm (de_cst 0) (de_cst 1).\n\n  Fact df_true_spec : df_pred df_true ν <-> True.\n  Proof. simpl; split; auto. Qed.\n\n  Fact df_false_spec : df_pred df_false ν <-> False.\n  Proof. simpl; split; try discriminate; tauto. Qed.\n\n  Notation \"'⟦' x '⟧'\" := (de_eval ν x).\n\n  Definition df_le x y := df_exst (df_atm (de_add (de_var 0) (de_lift x)) (de_lift y)).\n\n  Fact df_le_spec x y : df_pred (df_le x y) ν <-> ⟦x⟧ <= ⟦y⟧.\n  Proof.\n    simpl.\n    split.\n    + intros (n & Hn); revert Hn; do 2 rewrite de_eval_lift; simpl.\n      change (fun x => ν x) with ν; intros; omega.\n    + exists (de_eval ν y - de_eval ν x); simpl.\n      repeat rewrite de_eval_lift; simpl.\n      change (fun x => ν x) with ν; omega.\n  Qed.\n\n  Definition df_lt x y := df_exst (df_atm (de_add (de_cst 1) (de_add (de_var 0) (de_lift x))) (de_lift y)).\n\n  Fact df_lt_spec x y : df_pred (df_lt x y) ν <-> ⟦x⟧ < ⟦y⟧.\n  Proof.\n    simpl.\n    split.\n    + intros (? & Hn); revert Hn; simpl.\n      do 2 rewrite de_eval_lift; simpl.\n      change (fun x => ν x) with ν; intros; omega.\n    + exists (de_eval ν y - de_eval ν x - 1); simpl.\n      repeat rewrite de_eval_lift; simpl.\n      change (fun x => ν x) with ν; omega.\n  Qed.\n\n  Definition df_eq x y := df_atm x y.\n\n  Fact df_eq_spec x y : df_pred (df_eq x y) ν <-> ⟦x⟧ = ⟦y⟧.\n  Proof. simpl; tauto. Qed.\n\n  Definition df_neq x y := df_disj (df_lt x y) (df_lt y x).\n\n  Fact df_neq_spec x y : df_pred (df_neq x y) ν <-> ⟦x⟧ <> ⟦y⟧.\n  Proof.\n    unfold df_neq.\n    rewrite df_pred_disj, df_lt_spec, df_lt_spec.\n    omega.\n  Qed.\n\n  Definition df_div x y := df_exst (df_atm (de_lift y) (de_mul (de_var 0) (de_lift x))).\n\n  Fact df_div_spec x y : df_pred (df_div x y) ν <-> divides ⟦x⟧ ⟦y⟧.\n  Proof. \n    simpl; unfold divides.\n    split; intros (n & H); exists n; revert H; repeat rewrite de_eval_lift;\n      simpl; change (fun x => ν x) with ν; auto.\n  Qed.\n\nEnd examples.\n\nDefinition dio_rel R := { f | forall ν, df_pred f ν <-> R ν }.\nNotation 𝔻R := dio_rel.\n\nSection dio_rel.\n\n  (** How to analyse diophantine relations ... these are proved by\n      explicitely given the witness which we will avoid later on *)\n  \n  Implicit Types R S : (nat -> nat) -> Prop.\n\n  Fact dio_rel_True : 𝔻R (fun _ => True).\n  Proof.\n    exists df_true.\n    intros; rewrite df_true_spec; tauto.\n  Defined.\n\n  Fact dio_rel_False : 𝔻R (fun _ => False).\n  Proof.\n    exists df_false.\n    intros; rewrite df_false_spec; tauto.\n  Defined.\n\n  Fact dio_rel_eq r t : 𝔻P r -> 𝔻P t -> 𝔻R (fun ν => r ν = t ν).\n  Proof.\n    intros (e1 & H1) (e2 & H2); exists (df_atm e1 e2).\n    intros; rewrite df_pred_atm, H1, H2; tauto.\n  Defined.\n\n  Fact dio_rel_le r t : 𝔻P r -> 𝔻P t -> 𝔻R (fun ν => r ν <= t ν).\n  Proof. \n    intros (e1 & H1) (e2 & H2); exists (df_le e1 e2).\n    intro; rewrite df_le_spec, H1, H2; tauto.\n  Defined.\n\n  Fact dio_rel_lt r t : 𝔻P r -> 𝔻P t -> 𝔻R (fun ν => r ν < t ν).\n  Proof. \n    intros (e1 & H1) (e2 & H2); exists (df_lt e1 e2).\n    intro; rewrite df_lt_spec, H1, H2; tauto.\n  Defined.\n\n  Fact dio_rel_neq r t : 𝔻P r -> 𝔻P t -> 𝔻R (fun ν => r ν <> t ν).\n  Proof.\n    intros (e1 & H1) (e2 & H2); exists (df_neq e1 e2).\n    intros; rewrite df_neq_spec, H1, H2; tauto.\n  Defined.\n\n  Fact dio_rel_div r t : 𝔻P r -> 𝔻P t -> 𝔻R (fun ν => divides (r ν) (t ν)).\n  Proof.\n    intros (e1 & H1) (e2 & H2); exists (df_div e1 e2).\n    intros; rewrite df_div_spec, H1, H2; tauto.\n  Defined.\n\n  Fact dio_rel_conj R S : 𝔻R R -> 𝔻R S -> 𝔻R (fun ν => R ν /\\ S ν).\n  Proof.\n    intros (fR & H1) (fS & H2).\n    exists (df_conj fR fS); intros v.\n    rewrite df_pred_conj, H1, H2; tauto.\n  Defined.\n\n  Fact dio_rel_disj R S : 𝔻R R -> 𝔻R S -> 𝔻R (fun ν => R ν \\/ S ν).\n  Proof.\n    intros (fR & H1) (fS & H2).\n    exists (df_disj fR fS); intros v.\n    rewrite df_pred_disj, H1, H2; tauto.\n  Defined.\n\n  Fact dio_rel_exst (K : nat -> (nat -> nat) -> Prop) : \n                   𝔻R (fun v => K (v 0) (fun n => v (S n))) \n      -> 𝔻R (fun ν => exists x, K x ν).\n  Proof.\n    intros (f & Hf).\n    exists (df_exst f); intros v.\n    rewrite df_pred_exst.\n    split; intros (n & Hn); exists n; revert Hn; rewrite Hf; simpl; auto.\n  Defined.\n\n  Lemma dio_rel_equiv R S : (forall ν, S ν <-> R ν) -> 𝔻R R -> 𝔻R S.\n  Proof. \n    intros H (f & Hf); exists f; intro; rewrite Hf, H; tauto.\n  Defined.\n\n  Lemma dio_rel_ren R f : 𝔻R R -> 𝔻R (fun v => R (fun n => v (f n))).\n  Proof.\n    intros (r & HR).\n    exists (df_ren f r).\n    intros; rewrite df_pred_ren, HR; tauto.\n  Defined.\n\n  Lemma dio_rel_subst R f : 𝔻R R -> 𝔻R (fun v => R (fun n => de_eval v (f n))).\n  Proof.\n    intros (r & HR).\n    exists (df_subst f r).\n    intros; rewrite df_pred_subst, HR; tauto.\n  Defined.\n\nEnd dio_rel.\n\nHint Resolve dio_rel_True dio_rel_False dio_rel_eq dio_rel_neq \n             dio_rel_le dio_rel_lt dio_rel_div \n             dio_rel_conj \n             dio_rel_disj \n             dio_rel_exst.\n\nLtac dio_rel_auto := repeat ((apply dio_rel_exst || apply dio_rel_conj || apply dio_rel_disj || apply dio_rel_eq); auto).\n\nSection more_examples.\n\n  Fact ndivides_eq x y : ~ (divides x y) <-> x = 0 /\\ y <> 0 \\/ exists a b, y = a*x+b /\\ 0 < b < x.\n  Proof.\n    split.\n    + intros H.\n      destruct x as [ | x ].\n      * left; split; auto; contradict H; subst; apply divides_0.\n      * right; exists (div y (S x)), (rem y (S x)); split.\n        - apply div_rem_spec1.\n        - rewrite divides_rem_eq in H.\n          generalize (@div_rem_spec2 y (S x)); intros; omega.\n    + intros [ (H1 & H2) | (a & b & H1 & H2) ].\n      * subst; contradict H2; revert H2; apply divides_0_inv.\n      * rewrite divides_rem_eq.\n        rewrite (div_rem_spec1 y x) in H1.\n        apply div_rem_uniq in H1; try omega.\n        apply div_rem_spec2; omega.\n  Qed.\n  \n  Lemma dio_rel_ndivides x y : 𝔻P x -> 𝔻P y -> 𝔻R (fun ν => ~ divides (x ν) (y ν)).\n  Proof.\n    intros.\n    apply dio_rel_equiv with (1 := fun v => ndivides_eq (x v) (y v)).\n    dio_rel_auto.\n  Qed.\n\n  Hint Resolve dio_rel_ndivides.\n\n  Fact rem_equiv p x r : r = rem x p <-> (p = 0 /\\ x = r)\n                                      \\/ (p <> 0 /\\ r < p /\\ exists n, x = n*p + r).\n  Proof.\n    split.\n    + intro; subst.\n      destruct (eq_nat_dec p 0) as [ Hp | Hp ].\n      * left; split; auto; subst; rewrite rem_0; auto.\n      * right; split; auto; split.\n        - apply div_rem_spec2; auto.\n        - exists (div x p);apply div_rem_spec1.\n    + intros [ (H1 & H2) | (H1 & H2 & n & H3) ].\n      * subst; rewrite rem_0; auto.\n      * symmetry; apply rem_prop with n; auto.\n  Qed.\n \n  Lemma dio_rel_remainder p x r : 𝔻P p -> 𝔻P x -> 𝔻P r  \n                               -> 𝔻R (fun ν => r ν = rem (x ν) (p ν)).\n  Proof.\n    intros.\n    apply dio_rel_equiv with (1 := fun v => rem_equiv (p v) (x v) (r v)).\n    dio_rel_auto.\n  Defined.\n\n  (* Eval compute in proj1_sig (dio_rel_remainder (dio_expr_var 0) (dio_expr_var 1) (dio_expr_var 2)). *)\n\n  Hint Resolve dio_rel_remainder.\n\n  Fact congr_equiv x y p : rem x p = rem y p <-> (exists r, r = rem x p /\\ r = rem y p).\n  Proof.\n    split.\n    + intros H; exists (rem x p); auto.\n    + intros (? & ? & ?); subst; auto.\n  Qed.\n\n  Lemma dio_rel_congruence x y p : 𝔻P x -> 𝔻P y -> 𝔻P p  \n                                -> 𝔻R (fun ν => rem (x ν) (p ν) = rem (y ν) (p ν)).\n  Proof.\n    intros.\n    apply dio_rel_equiv with (1 := fun v => congr_equiv (x v) (y v) (p v)).\n    dio_rel_auto.\n  Defined.\n\n  Hint Resolve dio_rel_congruence.\n\n  Fact not_divides_eq p x : ~ divides p x <-> exists r, r = rem x p /\\ r <> 0.\n  Proof.\n    rewrite divides_rem_eq.\n    split.\n    + exists (rem x p); auto.\n    + intros (? & ? & ?); subst; auto.\n  Qed.\n\n  Lemma dio_rel_not_divides x p : 𝔻P x -> 𝔻P p -> 𝔻R (fun ν => ~ divides (x ν) (p ν)).\n  Proof.\n    intros.\n    apply dio_rel_equiv with (1 := fun v => not_divides_eq (x v) (p v)).\n    dio_rel_auto.\n  Defined.\n\nEnd more_examples.\n\nHint Resolve dio_rel_congruence dio_rel_not_divides.\n\n(* Even computation in Coq works well\n\nEval compute in proj1_sig (dio_rel_congruence (dio_expr_var 0) (dio_expr_var 1) (dio_expr_var 2)).\nEval compute in proj1_sig (dio_rel_not_divides (dio_expr_var 0) (dio_expr_var 1)).\n\n*)\n\nSection dio_rel_compose.\n\n  Variable (f : (nat -> nat) -> nat) (R : nat -> (nat -> nat) -> Prop).\n  Hypothesis (Hf : 𝔻R (fun ν => ν 0 = f (fun x => ν (S x)))) \n             (HR : 𝔻R (fun ν => R (ν 0) (fun x => ν (S x)))).\n\n  Lemma dio_rel_compose : 𝔻R (fun ν => R (f ν) ν).\n  Proof.\n    apply dio_rel_equiv with (R := fun v => exists y, y = f v /\\ R y v).\n    + intros v; split.\n      * exists (f v); auto.\n      * intros (? & -> & ?); auto.\n    + dio_rel_auto.\n  Defined.\n\nEnd dio_rel_compose.\n\nSection multiple_exists.\n\n  Fixpoint df_mexists n f :=\n    match n with \n      | 0   => f\n      | S n => df_mexists n (df_exst f)\n    end.\n\n  Fact df_mexists_size n f : df_size (df_mexists n f) = n + df_size f.\n  Proof. \n    revert f; induction n as [ | n IHn ]; intros f; auto; simpl df_mexists.\n    rewrite IHn; simpl; omega. \n  Qed.\n\n  Fact df_mexists_size_Z n f : df_size_Z (df_mexists n f) = (Z.of_nat n + df_size_Z f)%Z.\n  Proof.\n    rewrite df_size_Z_spec, df_mexists_size, Nat2Z.inj_add, df_size_Z_spec; omega. \n  Qed.\n\n  (* We only use it once so there is no need to automatize it *)\n\n  Lemma df_mexists_spec n f ν : \n           df_pred (df_mexists n f) ν \n       <-> exists π, df_pred f (fun i => if le_lt_dec n i then ν (i-n) else π i).\n  Proof.\n    revert f ν; induction n as [ | n IHn ]; intros f v.\n    + simpl; split; [ intros H; exists (fun _ => 0) | intros (_ & H) ]; revert H; \n        apply df_pred_ext; intros; f_equal; omega.\n    + simpl df_mexists; rewrite IHn; split; intros (pi & Hpi).\n      * revert Hpi; rewrite df_pred_exst.\n        intros (u & Hu).\n        exists (fun i => match i with 0 => u | S i => pi i end).\n        revert Hu; apply df_pred_ext.\n        intros [ | i ].\n        - replace (0-S n) with 0 by omega; simpl; auto.\n        - replace (S i - S n) with (i-n) by omega.\n          simpl dv_lift. \n          destruct (le_lt_dec (S n) (S i)); destruct (le_lt_dec n i); auto; omega.\n      * exists (fun i => pi (S i)).\n        rewrite df_pred_exst; exists (pi 0).\n        revert Hpi; apply df_pred_ext.\n        intros [ | i ].\n        - replace (0-S n) with 0 by omega; simpl; auto.\n        - replace (S i - S n) with (i-n) by omega.\n          simpl dv_lift. \n          destruct (le_lt_dec (S n) (S i)); destruct (le_lt_dec n i); auto; omega.\n  Qed.\n\nEnd multiple_exists.\n\n\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/H10/Dio/dio_logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.705247168701034}}
{"text": "Require Export TopologicalSpaces Neighborhoods OpenBases.\nFrom ZornsLemma Require Export IndexedFamilies EnsemblesSpec.\n\nRecord neighborhood_basis {X:TopologicalSpace}\n  (NB:Family X) (x:point_set X) : Prop := {\n  neighborhood_basis_elements: forall N:Ensemble X,\n    In NB N -> neighborhood N x;\n  neighborhood_basis_cond: forall N:Ensemble X,\n    neighborhood N x -> exists N':Ensemble X,\n    In NB N' /\\ Included N' N\n}.\n\nRecord open_neighborhood_basis {X:TopologicalSpace}\n  (NB:Family X) (x:point_set X) : Prop := {\n  open_neighborhood_basis_elements: forall U:Ensemble X,\n    In NB U -> open_neighborhood U x;\n  open_neighborhood_basis_cond: forall U:Ensemble X,\n    open_neighborhood U x -> exists V:Ensemble X,\n    In NB V /\\ Included V U\n}.\n\nLemma open_neighborhood_basis_is_neighborhood_basis:\n  forall {X:TopologicalSpace} (NB:Family X) (x:point_set X),\n  open_neighborhood_basis NB x -> neighborhood_basis NB x.\nProof.\nintros.\ndestruct H.\nconstructor; intros.\n- apply open_neighborhood_is_neighborhood.\n  auto.\n- destruct H as [U [? ?]].\n  destruct (open_neighborhood_basis_cond0 U H) as [V [? ?]].\n  exists V.\n  split; auto with sets.\nQed.\n\nLemma open_basis_to_open_neighborhood_basis:\n  forall {X:TopologicalSpace} (B:Family X) (x:point_set X),\n    open_basis B -> open_neighborhood_basis\n                    [ U:Ensemble X | In B U /\\ In U x ]\n                    x.\nProof.\nintros.\ndestruct H.\nconstructor;\n  intros.\n- now split;\n    destruct H as [[? ?]];\n    [ apply open_basis_elements | ].\n- destruct H.\n  destruct (open_basis_cover x U H H0).\n  destruct H1 as [? [? ?]].\n  exists x0.\n  now repeat split.\nQed.\n\nLemma open_neighborhood_bases_to_open_basis:\n  forall {X:TopologicalSpace} (NB : point_set X -> Family X),\n    (forall x:point_set X, open_neighborhood_basis (NB x) x) ->\n    open_basis (IndexedUnion NB).\nProof.\nintros.\nconstructor;\n  intros.\n- destruct H0.\n  destruct (H a).\n  now destruct (open_neighborhood_basis_elements0 x H0).\n- destruct (H x).\n  assert (open_neighborhood U x) by\n    now constructor.\n  destruct (open_neighborhood_basis_cond0 U H2) as [V [? ?]].\n  exists V.\n  repeat split; trivial.\n  + now exists x.\n  + now destruct (open_neighborhood_basis_elements0 V H3).\nQed.\n\nSection build_from_open_neighborhood_bases.\n\nVariable X:Type.\nVariable NB : X -> Family X.\n\nHypothesis neighborhood_basis_cond :\n  forall (U V:Ensemble X) (x:X), In (NB x) U -> In (NB x) V ->\n    exists W:Ensemble X, In (NB x) W /\\ Included W (Intersection U V).\nHypothesis neighborhood_basis_cond2 :\n  forall (U:Ensemble X) (x:X), In (NB x) U -> In U x.\nHypothesis neighborhood_basis_inhabited_cond :\n  forall x:X, Inhabited (NB x).\nHypothesis neighborhood_basis_system_cond :\n  forall (x y:X) (U:Ensemble X), In (NB x) U -> In U y ->\n  exists V:Ensemble X, In (NB y) V /\\ Included V U.\n\nDefinition Build_TopologicalSpace_from_open_neighborhood_bases :\n  TopologicalSpace.\nrefine (Build_TopologicalSpace_from_open_basis (IndexedUnion NB)\n  _ _);\n  red; intros.\n- destruct H as [y U'].\n  destruct H0 as [z V'].\n  destruct H1.\n  destruct (neighborhood_basis_system_cond y x U' H H1) as\n    [U'' [? ?]].\n  destruct (neighborhood_basis_system_cond z x V' H0 H2) as\n    [V'' [? ?]].\n  destruct (neighborhood_basis_cond U'' V'' x H3 H5) as\n    [W [? ?]].\n  exists W.\n  repeat split.\n  + now exists x.\n  + now apply neighborhood_basis_cond2.\n  + apply H4.\n    now destruct (H8 _ H9).\n  + apply H6.\n    now destruct (H8 _ H9).\n- destruct (neighborhood_basis_inhabited_cond x) as [U].\n  exists U.\n  split; auto.\n  now exists x.\nDefined.\n\nLemma Build_TopologicalSpace_from_open_neighborhood_bases_basis:\n  forall x:X,\n    open_neighborhood_basis (NB x) x\n      (X:=Build_TopologicalSpace_from_open_neighborhood_bases).\nProof.\nassert (open_basis (IndexedUnion NB)\n  (X:=Build_TopologicalSpace_from_open_neighborhood_bases))\n  by apply Build_TopologicalSpace_from_open_basis_basis.\ndestruct H.\nintros.\nconstructor;\n  intros.\n- constructor.\n  + apply open_basis_elements.\n    now exists x.\n  + now apply neighborhood_basis_cond2.\n- destruct H.\n  destruct (open_basis_cover x U H H0) as [V [? []]].\n  destruct H1 as [y V].\n  destruct (neighborhood_basis_system_cond y x V H1 H3) as [W []].\n  exists W.\n  auto with sets.\nQed.\n\nEnd build_from_open_neighborhood_bases.\n", "meta": {"author": "coq-community", "repo": "topology", "sha": "f784257d0b9c316601440e4f02256bd6068e4f94", "save_path": "github-repos/coq/coq-community-topology", "path": "github-repos/coq/coq-community-topology/topology-f784257d0b9c316601440e4f02256bd6068e4f94/theories/Topology/NeighborhoodBases.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7052152915011878}}
{"text": "Require Import CT.Category.\nRequire Import CT.Functor.\n\n(** * Faithful Functors\n\nA \"faithful\" functor is one that is injective on hom-sets. That is,\nA functor \\(F : C \\to D\\) is _faithful_ if \\(\\forall x, y \\in C\\), the function\n\\(F : C(x, y) \\to D(F(x), F(y))\\) is injective.\n\nSo we require a [Functor] and a proof that injectivity of hom-sets is satisfied.\n*)\nSection FaithfulFunctor.\n  Context {A B : Category}.\n  Variable (F : Functor A B).\n\n  (* Injectivity of [F_mor] *)\n  Definition FaithfulFunctor :=\n    forall {a b} (f : mor A a b) (g : mor A a b),\n      F_mor F f = F_mor F g -> f = g.\nEnd FaithfulFunctor.", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Instance/Functor/FaithfulFunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7052152812632149}}
{"text": "Require Import SAT.project_lib.\n\n(* Exercise 2.1 *)\nInductive form :=\n  | f_var : id -> form\n  | f_true : form\n  | f_false : form\n  | f_and : form -> form -> form\n  | f_or : form -> form -> form\n  | f_impl : form -> form -> form\n  | f_neg : form -> form.\n\n(* Custom Notation *)\nDeclare Custom Entry sat.\nNotation \"<{ e }>\" := e (e custom sat at level 99).\nNotation \"( x )\" := x (in custom sat, x at level 99).\nNotation \"x\" := x (in custom sat at level 0, x constr at level 0).\nNotation \"x -> y\" := (f_impl x y) (in custom sat at level 70, right associativity).\nNotation \"x /\\ y\" := (f_and x y) (in custom sat at level 40, left associativity).\nNotation \"x \\/ y\" := (f_or x y) (in custom sat at level 50, left associativity).\nNotation \"~ x\" := (f_neg x) (in custom sat at level 30).\nNotation \"'true'\"  := true (at level 1).\nNotation \"'true'\" := f_true (in custom sat at level 0).\nNotation \"'false'\"  := false (at level 1).\nNotation \"'false'\" := f_false (in custom sat at level 0).\nCoercion f_var : id >-> form.\n\nDefinition x : id := (Id 0).\nDefinition y : id := (Id 1).\nDefinition z : id := (Id 2).\nLocal Hint Unfold x : core.\nLocal Hint Unfold y : core.\nLocal Hint Unfold z : core.\n\n(* Exercise 2.2 *)\nDefinition twotwoone := <{(x \\/ ~y) /\\ (~x \\/ y)}>.\nDefinition twotwotwo := <{ ~y -> (x \\/ y) }> .\nDefinition twotwothree := <{ x /\\ ~x /\\ true }>.\n\nDefinition valuation := id -> bool .\nDefinition empty_valuation : valuation := fun x => false .\nDefinition override (V : valuation ) (x : id) (b : bool ) : valuation :=\n  fun y => if beq_id x y then b else V y.\n\n(* Exercise 2.3 *)\nFixpoint interp (V : valuation) (p : form ) : bool :=\n  match p with\n  | f_true => true\n  | f_false => false\n  | f_var x => V x\n  | <{ x /\\ y }> => (interp V x) && (interp V y)\n  | <{ x \\/ y }> => (interp V x) || (interp V y)\n  | <{ ~x }> => negb (interp V x)\n  | <{ x -> y }> => negb (interp V x) || (interp V y)\n  end.\n\nNotation \"'Ø'\" := empty_valuation.\nNotation \"m '|[' x '|->' v ']|'\" := (override m x v)  (at level 100, v at next level, right associativity).\n\n(* A test valuation, assigning  x = false, y = true, z = true using the custom notation*)\nDefinition testval := Ø|[x |-> false]||[y |-> true]||[z |-> true]|.\n\nExample interp_test1 : interp testval twotwoone = false. \nProof. reflexivity. Qed.\n\nExample interp_test2 : interp testval twotwotwo = true. \nProof. reflexivity. Qed.\n\nExample interp_test3 : interp testval twotwothree = false. \nProof. reflexivity. Qed.\n\n(* Satisfiability states that there exists some valuation, making the interpretation of the formular true *)\nDefinition satisfiable (p : form ) : Prop := exists V : valuation , interp V p = true.\n\n(* Exercise 2.4 *)\nLemma test1 : satisfiable twotwoone .\nProof. \n  unfold satisfiable, twotwoone. exists Ø. reflexivity.\nQed.\n\nLemma test2 : satisfiable twotwotwo .\nProof.\n  unfold satisfiable, twotwotwo. exists (Ø|[ x |-> true]|). reflexivity.\nQed.\n\n(* Helper function to add an element to a list, only if the element\n   is not already present within the list \n*)\nFixpoint set_add (x : id) (l : list id) :=\n  match l with\n  | nil => [x]\n  | a :: l' => if beq_id a x then l else a :: (set_add x l')\n  end.\n\n(* Computes the union of two lists as if they were sets, \n   i.e. disallowing duplicate entries\n*)\nFixpoint set_union (l1 l2 : list id) : list id :=\n  match l1 with\n  | nil => l2\n  | x :: l' => set_add x (set_union l' l2)\n  end.\n\n(* Computes the list of id's present in a given formular p *)\nFixpoint occuring_vars (p : form) : list id :=\n  match p with\n  | f_true => nil\n  | f_false => nil\n  | f_var x => [x]\n  | <{ x /\\ y }> => set_union (occuring_vars x) (occuring_vars y)\n  | <{ x \\/ y }> => set_union (occuring_vars x) (occuring_vars y)\n  | <{ ~x }> => (occuring_vars x)\n  | <{ x -> y }> => set_union (occuring_vars x) (occuring_vars y)\n  end.\n\nExample test_occuring_vars :occuring_vars twotwoone = [Id 1; Id 0]. \nProof. reflexivity. Qed.\n\n(* Computes a list of all possible valuations, given a list id possible id's *)\nFixpoint allValuations (l : list id) : list valuation :=\n  match l with\n  | nil => [empty_valuation]\n  | x :: l' => let lv := allValuations l' in (map (fun V => override V x false) lv) ++ (map (fun V => override V x true) lv) \n  end.\n\n(* Expecting length 4, since 2 variables both with mappings to true/false *)\nExample test_length_of_allValuations : length (allValuations (occuring_vars twotwoone)) = 4.\nProof. reflexivity. Qed.\n\nFixpoint find_valuation_helper (p : form) (l : list valuation) : option valuation :=\n  match l with\n  | nil => None\n  | v :: l' => if interp v p then Some v else find_valuation_helper p l'\n  end.\n\nDefinition find_valuation (p : form ) : option valuation :=\n  find_valuation_helper p (allValuations (occuring_vars p)).\n\nDefinition solver (p : form ) : bool :=\n  match find_valuation p with\n  | Some _ => true\n  | None => false\n  end.\n\n(* Exercse 2.6\n\n   Satisfiable is a definition, stating that there exists some valuation in which the formula is true.\n   It requires you to provide a witness, namely a valuation in which the formula's interpretation is true.\n\n   Solver is a function which returns true / false, depending on whether or not the formula is satisfiable,\n   enumerating all possible valuations to find one.\n*)\n\n(* Exercise 2.7 *)\n\nExample two7pos1 : solver twotwoone = true.\nProof. reflexivity. Qed.\n\nExample two7pos2 : solver twotwotwo = true.\nProof. reflexivity. Qed.\n\nExample two7neg1 : solver twotwothree = false.\nProof. reflexivity. Qed.\n\nExample two7neg2 : solver <{ (x \\/ y) /\\ (~x \\/ y) /\\ (x \\/ ~y) /\\ (~x \\/ ~y)  }> = false.\nProof. reflexivity. Qed.\n\nLemma solver_sound_helper : forall l p v, find_valuation_helper p l = Some v -> interp v p = true.\nProof. intros l. induction l; intros.\n  - easy.\n  - cbn in H. destruct (interp a p) eqn:E. inversion H. subst. auto. apply (IHl _ _ H).\nQed.\n\n(* Exercise 2.8\n   The proof that the solver is sound. Uses a helper function defined above to do so.\n*)\nLemma solver_sound : forall p, solver p = true -> satisfiable p.\nProof. intros. unfold satisfiable. unfold solver in H. destruct (find_valuation p) eqn:E; try easy. exists v.\n  unfold find_valuation in E. apply solver_sound_helper in E. auto.\nQed.\n\n(* Helper lemma stating that an equivalent valuation exists in the list of allValuations, \n   for all possible valuations over the id's in said valuation \n*)\nLemma val_in_allvals : forall l (v: valuation), exists v', In v' (allValuations l) /\\ forall x0, In x0 l ->  v x0 = v' x0.\nProof. induction l; intros.\n  - exists Ø. split. left. reflexivity. intros. inversion H.\n  - destruct (IHl v) as [v']. destruct H. destruct (v a) eqn:E1. \n    + exists (v'|[a |-> true]|). cbn. remember (fun V : valuation => V |[ a |-> true ]|) as f. assert (f v' = (v'|[a |-> true]|)) by (rewrite Heqf; reflexivity).\n       split.\n        * apply in_app_iff. right. rewrite <- H1. apply in_map. auto.\n        * intros. destruct H2.\n          -- subst. unfold override. rewrite <- beq_id_refl. apply E1.\n          -- apply H0 in H2. destruct (beq_id a x0) eqn:E; \n            unfold override; rewrite E.\n            ++ symmetry in E. apply beq_id_eq in E. subst. assumption.\n            ++ unfold override. apply H2.\n    + exists (v'|[a |-> false]|). cbn. remember (fun V : valuation => V |[ a |-> false ]|) as f. assert (f v' = (v'|[a |-> false]|)) by (rewrite Heqf; reflexivity).\n    split.\n      * apply in_app_iff. left. rewrite <- H1. apply in_map.  auto.\n      * intros. destruct H2.\n        -- subst. unfold override. rewrite <- beq_id_refl. apply E1.\n        -- apply H0 in H2. destruct (beq_id a x0) eqn:E; unfold override; rewrite E. \n          ++ symmetry in E. apply beq_id_eq in E. subst. assumption.\n          ++ apply H2.\nQed.\n\n(* Following couple of functions are helper functions for performing set operations on lists. *)\nLemma in_set_add: forall x l, In x (set_add x l).\nProof. intros. induction l. \n  - cbn. left. reflexivity.\n  - cbn. destruct (beq_id a x0) eqn:E.\n    + symmetry in E. apply beq_id_eq in E. subst. left. reflexivity.\n    + cbn. right. auto.\nQed.\n\nLemma in_set_add': forall x a l, In x l -> In x (set_add a l).\nProof. intros. induction l.\n      * inversion H.\n      * cbn. destruct (beq_id a0 a) eqn:E. auto. destruct H.\n        ++ subst. left. reflexivity.\n        ++ right. auto.\nQed.\n\nLemma in_set_union_l: forall x l1 l2, In x l1 -> In x (set_union l1 l2).\nProof. intros. induction l1.\n  - inversion H.\n  - destruct H.\n    + subst. cbn. apply in_set_add.\n    + cbn. apply in_set_add'. auto. \nQed.\n\nLemma in_set_union_r: forall x l1 l2, In x l2 -> In x (set_union l1 l2).\nProof. intros. induction l1.\n  - cbn. auto.\n  - cbn. apply in_set_add'. auto. \nQed.\n    \n(* If a formula is satisfiable then a valuation exists over the occuring vars which interpretation is true *)\nLemma satisfiable_helper : forall p, satisfiable p -> exists v, In v (allValuations (occuring_vars p)) /\\ interp v p = true.\nProof. intros. destruct H as [v]. destruct (val_in_allvals (occuring_vars p) v) as [v']. destruct H0. exists v'.\n  split.\n    - apply H0.\n    - clear H0. rewrite <- H. clear H. induction p; cbn;\n      try reflexivity; try (rewrite <- H1; auto; left; auto);\n      try (rewrite IHp1, IHp2; try reflexivity; intros; apply H1; cbn; [ apply in_set_union_r |  apply in_set_union_l]; auto);\n      (rewrite IHp; auto).\nQed.\n\nLemma solver_complete_help : forall l p v, interp v p = true -> In v l -> exists v', find_valuation_helper p l = Some v'.\nProof. induction l; intros.\n  - easy.\n  - destruct H0.\n    + subst. exists v. cbn. rewrite H. reflexivity.\n    + cbn. destruct (interp a p); eauto.\nQed.\n\n(* Exercise 2.9. Proof of completeness of the solver. *)\nLemma solver_complete : forall p, satisfiable p -> solver p = true.\nProof. \n  intros. unfold solver, find_valuation. apply satisfiable_helper in H. destruct H. destruct H.\n  pose proof (solver_complete_help (allValuations (occuring_vars p)) p x0 H0 H). \n  destruct H1. rewrite H1. reflexivity.\nQed. \n\n(* Transforms (p1 -> p2) into (~p1 \\/ p2) *)\nFixpoint negation_nf_1 p :=\n  match p with\n  | <{ p1 -> p2 }> => f_or (f_neg (negation_nf_1 p1)) (negation_nf_1 p2) \n  | <{ p1 /\\ p2 }> => f_and (negation_nf_1 p1) (negation_nf_1 p2) \n  | <{ p1 \\/ p2 }> => f_or (negation_nf_1 p1) (negation_nf_1 p2) \n  | <{ ~p1 }> => f_neg (negation_nf_1 p1)\n  | _ => p\n  end.\n\n(* De Morgan's Law, transforming ~(p1 \\/ p2) into (~p1) /\\ (~p2) and ~(p1 /\\ p2) into (~p1) \\/ (~p2)\n   Note. This is only called on negations, so whenever (p1 \\/ p2) is encountered, this is actually\n   ~(p1 \\/ p2). Therefore, if ~p1 is seen this actually means ~~p1 which is why p1 is returned (double neg elim).\n*)\nFixpoint de_morg p :=\n  match p with\n  | <{(p1 \\/ p2) }> => f_and (de_morg p1) (de_morg p2)  \n  | <{(p1 /\\ p2) }> => f_or (de_morg p1) (de_morg p2) \n  | f_neg p1 => p1\n  | _ => f_neg p\n  end.\n\n(* Applies De Morgan's Law + double negation elimination to a formula which is assumed to have no implications *)\nFixpoint negation_nf_2 p :=\n  match p with\n  | <{ ~p1 }> => de_morg (negation_nf_2 p1)\n  | <{ p1 /\\ p2 }> => f_and (negation_nf_2 p1) (negation_nf_2 p2) \n  | <{ p1 \\/ p2 }> => f_or (negation_nf_2 p1) (negation_nf_2 p2) \n  | _ => p\n  end.\n\n(* Converts an arbitrary formula into an equivalent one on NNF *)\nDefinition negation_nf p := \n  let p1 := negation_nf_1 p in\n  negation_nf_2 p1.\n\nFixpoint distr_left p q :=\n  match q with\n  | <{q1 /\\ q2 }> => f_and (distr_left p q1) (distr_left p q2)\n  | _ => <{p \\/ q}>\n  end.\n\nFixpoint distr_right q p :=\n  match q with\n  | <{q1 /\\ q2 }> => f_and (distr_right q1 p) (distr_right q2 p)\n  | _ => distr_left q p\n  end.\n\n(* Distributes Disjunctions from left and right *)\nDefinition distribute p := \n  match p with\n  | <{p \\/ q}> => distr_right p q\n  | _ => p\n  end.\n\n(* Assuming s is on negation normal form, turns it into cnf *)\nFixpoint cnf s :=\n  match s with\n  | <{ p /\\ q }> => f_and (cnf p) (cnf q)\n  | <{ p \\/ q}> => distribute (f_or (cnf p) (cnf q))\n  | _ => s\n  end.\n\n(* Converts a boolean formula to CNF *)\nDefinition cnf_conv p := \n  let p1 := negation_nf p in\n  cnf p1.\n\nFixpoint verify_cnf_aux s (seenor : bool) :=\n  match s with\n  | <{ p /\\ q }> => if seenor then false else (verify_cnf_aux p false) && (verify_cnf_aux q false)\n  | <{ p \\/ q }> => (verify_cnf_aux p true) && (verify_cnf_aux q true)\n  | f_false | f_true | f_var _ => true\n  | f_neg (f_var _) | f_neg (f_false) | f_neg (f_true)  => true\n  | _ => false\n  end.\n\n(* Verifies that a formula is on CNF - uses helper function to ensure no more conjunctions are seen after the first disjunction*)\nDefinition verify_cnf s := verify_cnf_aux s false.\n\nConjecture cnf_works : forall p, verify_cnf (cnf_conv p) = true.\n\n(* Check that the semantics of cnf_conv is preserved *)\nConjecture cnf_sat : forall p, solver p = solver (cnf_conv p).\n\nFrom QuickChick Require Import QuickChick.\n\n(* Derivies arbitrary for required parts, and executes QuickChick on the defined Conjectures. *)\nDerive Arbitrary for id.\nDerive Arbitrary for form.\nDerive Show for id.\nDerive Show for form.\n\n\nQuickChick cnf_works.\nQuickChick cnf_sat.", "meta": {"author": "Kasserne", "repo": "FSVproject", "sha": "326ec93628556919f021a2acd4d25d802c64b2e1", "save_path": "github-repos/coq/Kasserne-FSVproject", "path": "github-repos/coq/Kasserne-FSVproject/FSVproject-326ec93628556919f021a2acd4d25d802c64b2e1/SatSolver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733979704703, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7051531465666299}}
{"text": "(** * Verifying Programming Contest Problems *)\n\n(** ** Introduction *)\n\n(** \n    In programming contests, one of the most frustrating (and common!) verdicts to receive is Wrong Answer (WA).\n    One of the reasons behind this is that there are often many potential sources of WA that a programmer has to hunt down.\n    A WA could come from a typo in the implementation, or it could come from the use of a greedy observation which does not always hold, or many other reasons.\n\n    In this tutorial, I will try to give a brief overview of how you can _prove your programs correct_ by writing specifications and proofs in the Coq proof assistant.\n    Coq is based on a dependent type theory that allows you to define your programs and write proofs about them. \n    Writing proofs by hand can be quite laborious, so Coq also has an interactive proving system using _tactics_ that allows you to automate away tedious parts of proofs and also prove things in a much more natural way.\n    This very document is a (literate) Coq file, so you can download the source and follow along.\n    By the end of this tutorial, you should be able to compile this Coq file, extract it to Ocaml, and submit your solution to an online judge!\n*)\n\n(** *** Some Disclaimers *)\n\n(**    There are, of course, several caveats I should point out.\n    The first of which is that writing out a specification and proving an algorithm correct takes a significant amount of time, even for experienced users. \n    It would be utterly impractical for a contest setting, where \"proofs by AC\" are quite common.\n    My goal is to use contest problems as a vehicle to introduce formal verification in a small-scale, concrete way--although of course program verification is also used on much larger projects.\n\n    Secondly, we may be limited in the kinds of problems we can (easily) verify and write efficient solutions for.\n    For instance, many contest problems involve mutable arrays, while when using Coq, we tend to prefer lists and other functional data structures because they are easier to reason about.\n*)\n\n\n(** ** A Simple Example *)\n\n(** \n    For our example, we'll solve the Codeforces problem Red and Blue Beans:\n    #<a href=\"https://codeforces.com/contest/1519/problem/A\">https://codeforces.com/contest/1519/problem/A</a># \n    %\\url{https://codeforces.com/contest/1519/problem/A}%.\n\n    This is a pretty basic problem involving only basic arithmetic.\n    The answer is [YES] if and only if [b <= r * (d+1)] and [r <= b * (d+1)].\n\n    How can we prove this is the right condition? \n    Without loss of generality, we can assume that [r <= b]. \n    If we wanted to maximize the number of blue beans for a given number of red beans, we would create [r] packets, each with [1] red bean and [d+1] blue beans.\n    Therefore, if we have more than [r * (d+1)] blue beans, we cannot distribute all the beans; otherwise, we can.\n\n    Now, let's get to programming our solution!\n*)\n\n\nRequire Import Lia.\nRequire Import Bool.\nRequire Import List.\nRequire Import Arith.Arith.\nImport ListNotations.\nRequire Extraction.\n\nDefinition can_distribute (r b d : nat) : bool :=\n  (b <=? (r * (d + 1))) && (r <=? (b * (d + 1))).\n\n(** \n    That wasn't too bad!\n    If we were programming in another language like Java or C++, we would stop here and submit our solution.\n    However, even after passing hundreds of tests, we still can't be sure that is correct for all inputs. \n    The only way to be certain of a program's correctness is to prove it, like we did above.\n    But how do we know our _proof_ is correct? \n    People make mistakes in proofs all the time.\n    Luckily, Coq's type system is expressive enough to allow you to write propositions about your programs as types. \n    If we can find a term [t] that has type [T], we say that [T] is _inhabited_. Interpreting [T] as a proposition, we say that [t] is _evidence_ for [T] being true.  \n    This effectively means that we can use Coq's type-checker as a proof-checker!\n    This is known as the \n    #<a href=\"https://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence\">Curry-Howard correspondence</a>#.\n*)\n\n(**\n   Okay, here's a concrete example of writing a proposition and its proof in Coq.\n   When writing a specification for our original problem, we'll need to define a function [abs] that takes two natural numbers [a] and [b] and returns the absolute value [|a-b|].\n*)\n\nDefinition abs (a b : nat) := max (b-a) (a-b).\n\n(** \n    Note that since we are working with natural numbers, subtraction is capped at zero--so [3 - 5 = 0], for instance.\n\n    To show that [abs] is defined correctly, we can prove that it satisfies the properties want for all possible inputs.\n    For instance, we would expect that [abs a b] is the same as [abs b a].\n    We can write this proposition in Coq like so:\n*)\nTheorem abs_comm : forall (a b : nat), abs a b = abs b a.\n(** \n    We can read this like a sentence in first-order logic:\n    \"For all [a b], [abs a b] and [abs b a] are equal.\"\n    \n    By writing Proof., we enter into the interactive proving mode, where we can prove our goal by entering a series of tactics.\n*)\nProof.\n  (* This will make the most sense if you are following along in your own IDE! *)\n  (* First, we move [a] and [b] into our local context using the [intros] tactic. \n     This is like writing \"Let a and b be arbitrary natural numbers.\" in a written proof. *)\n  intros a b.\n  (* Next, we unfold the definition of [abs] using the [unfold] tactic. \n     Since [abs] is defined in terms of the [max] function, we can use properties about [max] to prove our goal. *)\n  unfold abs.\n  (* The theorem [Nat.max_comm] should be useful. We can check its type using the [Check] directive: *)\n  Check Nat.max_comm.\n  (* We can introduce a new hypothesis using [assert], prove it, and then use it to help prove our original goal. \n   This is like introducing a lemma in a written proof. *) \n  assert (H : max (b-a) (a-b) = max (a-b) (b-a)). \n  (* Our lemma follows directly from the [Nat.max_comm] theorem, so we can use the [apply] tactic: *)\n  { apply Nat.max_comm. }\n  (* The most important thing about equalities is that if [x = y], \n     then [x] and [y] are interchangeable in every context.\n     We can use the [rewrite] tactic to change [max (b-a) (a-b)] in our goal to [max (a-b) (b-a)].*)\n  rewrite H.\n  (* Now, both sides of the equality are exactly the same, so we can discharge the goal using [reflexivity].*)\n  reflexivity.\nQed.\n\n(** It's important to stress that tactics are only high-level directions that tell Coq how to create the proof. \n    The proof term itself is often much longer and harder to understand, and it is what is checked by the typechecker to verify that you have proven your theorem. You can view the proof [abs_comm] using the [Print] directive.\n*)\nPrint abs_comm.\n(* begin details : *)\n(**\n[[\nabs_comm = \nfun a b : nat =>\nlet H :\n  Init.Nat.max (b - a) (a - b) = Init.Nat.max (a - b) (b - a) :=\n  Nat.max_comm (b - a) (a - b) in\neq_ind_r (fun n : nat => n = Init.Nat.max (a - b) (b - a))\n  eq_refl H\n     : forall a b : nat, abs a b = abs b a\n]]\n*)\n\n(* end details *)\n\n\n(** \n    Let's prove one more property about [abs].\n    [abs a b] should be equal to the distance between [a] and [b], so if [a < b], then [a + abs a b = b], and if [b < a], then [b + abs a b = b].\n\n    To prove this, we can use the [lia] tactic, which is a decision procedure for linear integer arithmetic.\n    As our original problem involves a lot of arithmetic, [lia] will frequently come in handy.\n*)\n\nTheorem abs_correct : forall (a b : nat),\n    (a < b -> a + abs a b = b) /\\\n    (b < a -> b + abs a b = a).\nProof.\n  intros. \n  unfold abs.\n  lia.\nQed.\n\n\n(** ** Specification Using Lists \n*)\n\n(** Now let's return to our original problem. \n    We can write a proposition that defines whether there is a valid distribution of beans.\n    For any [r,b,d], there exists a _correct distribution_ of beans if and only if there exists a set of packets such that\n    - the sum of all the red beans is [r],\n    - the sum of all the blue beans is [b],\n    - each packet contains a positive number of red and blue beans,\n    - for each packet, the number of red and blue beans should not differ by more than [d].\n\n    The simplest way to represent a set of packets is a list.\n    We'll define a [packet] as a pair of natural numbers, and we'll define the function [packet_sum] which adds up the number of red and blue beans in a list of packets.\n*)\n\nModule ListSpec.\n\nDefinition packet : Set := nat * nat.\n\nFixpoint packet_sum (l : list packet) := match l with\n  | [] => (0,0)\n  | (r,b) :: rest => let (x,y) := packet_sum rest in (r+x,b+y)\n  end.\n\n(** Now we can define what a [correct_distribution] means as define above. Here, we use the existential quantifier [exists], meaning that to prove this proposition, we must supply a valid list that all the conditions. *)\n\nDefinition correct_distribution (r b d : nat) :=\n  exists l, packet_sum l = (r,b) /\\ Forall (fun '(x,y) => abs x y <= d /\\ x > 0 /\\ y > 0) l. \n\n\nExample ex1 : correct_distribution 1 1 0.\nProof.\n  exists [(1,1)].\n  split; unfold abs; auto.\n  repeat constructor; lia.\nQed.\n\nExample ex2 : correct_distribution 2 7 3.\nProof.\n  exists [(1,4);(1,3)].\n  split; unfold abs; auto.\n  repeat constructor; lia.\nQed.\n\n(** Finally, we can relate our algorithm [can_distribute] to our specification [correct_distribution]. \n    Our algorithm should return true if and only if [correct_distribution] is provable, meaning that there exists a list of packets that meets the conditions defined in [correct_distribution].\n*)\n\nDefinition algorithm_iff_correct_distribution := \n  forall r b d, \n    can_distribute r b d = true <-> correct_distribution r b d.\n\n\n(** If we can prove this theorem (meaning we can find a term which has this type), we know that our algorithm is correct.\n    Moreover, other people do not even need to read our proof to trust that our algorithm is correct.\n    They can simply read the specification and make sure the program typechecks.\n*)\n\n(** *** Some helpful lemmas\n*)\n\n(** A few lemmas about arithmetic that will come in handy. \n    We make heavy use of the [lia] to avoid having to deal with most of these proofs by hand, but for some cases (multiplication by non-constants), we need to help guide the solver: *)\n\nLemma d_leq_mult_d : forall d r, r > 0 -> d <= r * d.\nProof.\n  intros. \n  induction d; lia.\nQed.\n\nLemma d_bound : forall r b d x y,\n  r > 0 ->\n  b <= r + d ->\n  y <= x * (d+1) -> \n  b + y <= (r + x) * (d + 1).\nProof.\n  intros.\n  assert ((r+x)*(d+1) = x*(d+1) + r*(d+1)). { lia. } rewrite H2.\n  assert (r+d <= r*(d+1)); try lia. \n  pose proof (d_leq_mult_d d r). lia.\nQed.\n\n(** This lemma says that we can exchange the uses of [r] and [b], meaning that if we can distribute [r] red beans and [b] blue beans, we must also be able to distribute [b] red beans and [r] blue beans, and vice versa.\n    Although the proof is a bit complicated, the intuition is simple: we can flip the number of blue and red beans in each packet.\n*)\n\nLemma distribution_flip : forall r b d,\n  correct_distribution r b d <-> correct_distribution b r d.\nProof.\n  assert (H:forall r b d, correct_distribution r b d -> correct_distribution b r d). {\n  unfold correct_distribution.\n  intros r b d [l [H2 H3]].\n  generalize dependent r.\n  generalize dependent b.\n  induction l; intros.\n  + simpl in H2. inversion H2; subst. exists []; auto.\n  + destruct a as [r' b']. simpl in H2. \n    remember (packet_sum l) as X. destruct X as [x y]. \n    inversion H2; subst.\n    specialize IHl with y x.\n    destruct IHl; auto. inversion H3; auto.\n    destruct H.\n    exists ((b',r')::x0).\n    split. simpl. rewrite H. auto.\n    constructor; auto. inversion H3; subst. destruct H5 as [Ha [Hr Hb]]. split; auto; unfold abs in *; try lia.\n  }\n  split; apply H.\nQed.\n\n(** Here is the crucial lemma proving that our algorithm's conditions is sufficient. Note that we assume that [r <= b], like we did in the informal proof. \n *)\nLemma can_make_distr : forall r b d,\n    r <= b -> \n    b <= r * (d+1) ->\n    correct_distribution r b d.\nProof.\n  intros r b d r_leq_b H.\n  generalize dependent b.\n  induction r; intros.\n  - assert (b = 0). lia. subst. exists []. auto.\n  - remember (min (b - r) (d + 1)) as t.\n    specialize IHr with (b-t).\n    assert (Hr : r <= b - t). { lia. } apply IHr in Hr.\n    destruct Hr as [l [Hl1 Hl2]].\n    exists ((1,t) :: l); split. \n    + simpl. rewrite Hl1. \n      assert (Htb: t + (b - t) = b). { lia. } rewrite Htb. \n      reflexivity.\n    + constructor; try auto; split; try lia. unfold abs; lia. \n    + simpl in H. \n      pose proof (Nat.min_spec (b-r) (d+1)) as [[Hmin1 minEq] | [Hmin2 minEq]]; rewrite minEq in Heqt. \n      subst. assert (b - (b - r) = r). lia. rewrite H0. \n      rewrite plus_comm. rewrite <- mult_n_Sm. lia.\n\n      subst. lia.\nQed. \n\n(** Next, we'll prove that our algorithm's condition is necessary, meaning that if there is a list [l] that shows that [correct_distribution r b d] is true, then [b <= r * (d + 1)] and [r <= b * (d + 1)].\n\n    The proof proceeds by induction on the list [l].\n    \n*)\nTheorem algorithm_condition_necessary : forall r b d,\n  correct_distribution r b d -> can_distribute r b d = true.\nProof.\n  unfold correct_distribution, can_distribute.\n  intros.\n  destruct H as [l [H1 H2]].\n  unfold can_distribute.\n  rewrite andb_true_iff. repeat rewrite Nat.leb_le. \n  generalize dependent b.\n  generalize dependent r.\n  induction l; intros.\n  + simpl in H1. inversion H1; subst. lia.\n  + destruct a as [r' b']. simpl in H1. remember (packet_sum l) as X. destruct X as [x y]. inversion H1; subst; clear H1. \n    inversion H2; subst. apply IHl with x y in H3; auto. \n    unfold abs in H1.\n    split; apply d_bound; lia.\nQed.\n\n(** *** The proof of correctness!\n*)\nTheorem algorithm_correct : algorithm_iff_correct_distribution.\nProof.\n  unfold algorithm_iff_correct_distribution.\n  intros.\n  split; intros.\n  - unfold can_distribute in H.\n    rewrite andb_true_iff in H. repeat rewrite Nat.leb_le in H. destruct H as [H1 H2].\n    (* Case on whether r <= b or b <= r. *)\n    assert (r <= b \\/ b <= r) as [Hrb | Hbr]. lia.\n    + apply can_make_distr; auto.\n    + apply distribution_flip. apply can_make_distr; auto.\n\n  - apply algorithm_condition_necessary; auto. \nQed.\nEnd ListSpec.\n\n\n(** ** Specification Using Inductive Relations *)\n\n(** \n    We've done it! We have defined our specification using lists and proven that our algorithm always computes the correct answer according to our specification.\n    \n    Now that we know for certain that our program is correct, we can proceed to extracting the program into Ocaml.\n    Before we move on, however, I want to present another specification for this problem, this time defining [correct_distribution] as an inductive proposition.\n    \n    While it may be natural to interpret the specification using lists, it does make the definitions more complicated, which affects the length and readability of the proofs.\n    This alternate specification is equivalent (in fact, proving that these two specifications are equivalent is a good exercise), but it requires a lot less unfolding and destructing, which simplifies the proofs.\n\n*)\n\nModule InductiveSpec.\nInductive correct_distribution : nat -> nat -> nat -> Prop :=\n  | no_packets : forall d, \n      correct_distribution 0 0 d\n  | add_packet : forall r b r' b' d,\n      correct_distribution r b d ->\n      r' > 0 ->\n      b' > 0 ->\n      abs r' b' <= d ->\n      correct_distribution (r'+r) (b'+b) d.\nHint Constructors correct_distribution : core.\n\nDefinition algorithm_iff_correct_distribution := \n  forall r b d, \n    can_distribute r b d = true <-> correct_distribution r b d.\n\nLemma distribution_flip : forall r b d,\n  correct_distribution r b d <-> correct_distribution b r d.\nProof.\n  assert (H:forall r b d, correct_distribution r b d -> correct_distribution b r d). { \n  intros r b d H.\n  induction H.\n  - auto.\n  - constructor; auto. unfold abs in *. lia. }\n\n  split; apply H.\nQed.\n\nLemma can_make_distr : forall r b d,\n    r <= b -> \n    b <= r * (d+1) ->\n    correct_distribution r b d.\nProof.\n  intros r b d r_leq_b H.\n  generalize dependent b.\n  induction r; intros.\n  - assert (b = 0). lia. subst. auto.\n  - remember (min (b - r) (d + 1)) as t.\n    specialize IHr with (b-t).\n    assert (Hb: b = t+(b-t)). { lia. } rewrite Hb.\n    assert (Hr: S r = 1 + r). { lia. } rewrite Hr.\n    constructor; unfold abs; try apply IHr; try lia. \nQed.\n\nTheorem algorithm_correct : algorithm_iff_correct_distribution.\nProof.\n  unfold algorithm_iff_correct_distribution.\n  split; intros.\n  - unfold can_distribute in H.\n    rewrite andb_true_iff in H. repeat rewrite Nat.leb_le in H. destruct H as [H1 H2].\n    (* Case on whether r <= b or b <= r. *)\n    assert (r <= b \\/ b <= r) as [Hrb | Hbr]. lia.\n    + apply can_make_distr; auto. \n    + apply distribution_flip. apply can_make_distr; auto.\n  - unfold can_distribute.\n    rewrite andb_true_iff. repeat rewrite Nat.leb_le. \n    induction H.\n    + lia.\n    + split; apply ListSpec.d_bound; unfold abs in H2; try lia.\nQed.\n\nEnd InductiveSpec.\n\n\n\n(** ** Extraction *)\n(** \n    Now we can extract our verified algorithm to Ocaml.\n    We don't extract our proofs, since they not actually meant to be run.\n    So in this case, we only need to extract our function [can_distribute], which is quite simple.\n    We can try running the extraction command now:\n*)\nExtraction \"imp.ml\" can_distribute.\n(** \n    If you look in the file [imp.ml], you will see the following datatype definitions at the top:\n\n[[\ntype bool =\n  | True\n  | False\n]]\n\n[[\ntype nat =\n  | O\n  | S of nat\n]]\n\nWithout any directions on how to perform the extraction, Coq will redefine all the datatypes that are used, including booleans and nat.\nThis is a big problem for nat, since defining numbers Peano-style is quite inefficient--if you look how addition is defined, adding two numbers is actually linear in the size of the first number.\nWe can tell Coq to extract nat to [int] or [int64], but this can be quite dangerous. This is because theorems about nat may no longer hold. For instance, it is a theorem for nat that [x + y >= x], but this is not true for [int] or [int64], since there may be overflow cases.\n\nIn this case, since we know that the inputs are less than [10^9], we can determine that we will not run into overflow issues.\nSo, we can safely extract nat to [int64].\nSo, I chose\nIf you would like, you can also extract to an arbitrary precision integer type like [big_int].\n*)\n\nModule ExtractionDefs.\nModule ExtrNatToInt64.\nExtract Inductive nat => \"int64\"\n  [ \"Int64.zero\" \"(fun x -> Int64.succ x)\" ]\n  \"(fun zero succ n -> if Int64.compare n 0 = 0 then zero () else succ (Int64.pred n))\".\nExtract Constant plus => \"Int64.add\".\nExtract Constant mult => \"Int64.mul\".\nExtract Constant leb => \"(fun x y -> Int64.compare x y <= 0)\".\nEnd ExtrNatToInt64.\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\nEnd ExtractionDefs.\n\nExtraction \"imp.ml\" can_distribute.\n(** \n    And there we have it--a fully verified program that you can submit to Codeforces!\n    You can see #<a href=\"https://github.com/tmoux/verified-cp/blob/master/1519A/sol.ml\">here</a># for a version that includes the input/output plumbing.\n\n*)\n\n\n\n", "meta": {"author": "tmoux", "repo": "verified-cp", "sha": "beeac6acf403c69fc33cdf526917c4a619f179e1", "save_path": "github-repos/coq/tmoux-verified-cp", "path": "github-repos/coq/tmoux-verified-cp/verified-cp-beeac6acf403c69fc33cdf526917c4a619f179e1/tutorial/tut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7051299711078376}}
{"text": "(** Advanced recursive functions *)\n(** Recursion using Function *)\n\nRequire Import FunInd.\nRequire Import Coq.Lists.List.\nRequire Import Arith.\nRequire Import Recdef.\nRequire Import Program.\nLoad CpdtTactics.\n\n\n(* Using {struct n} \n   structural recursive function - \n   like Fixpoint \n*)\n\nFunction plus (m n : nat) {struct n} : nat :=\nmatch n with\n| 0 => m\n| S p => S (plus m p)\nend.\n\n(* Using {measure n} \n   non-structural recursive function \n*)\n\nFunction revapp (m n : list nat) {measure length n} :=\nmatch n with\n| nil => m\n| _   => cons (hd 0 n) (revapp m (tl n))\nend.\nintros. eauto.\nDefined.\n\n(** Equal equation to get rid of the decreasing lemma in subsequent proofs *)\nCheck revapp_equation.\n\nDefinition lengthOrder (x y:list nat) :=\n   length x < length y.\n\nHint Constructors Acc.\n\nTheorem lengthOrder_wf' : forall len,\n     forall ls, length ls <= len -> \n          Acc lengthOrder ls.\nProof. \nunfold lengthOrder; induction len; crush.\nQed.\n\nFunction revapp_ (m n : list nat) {wf lengthOrder n} :=\nmatch n with\n| nil => m\n| _   => cons (hd 0 n) (revapp_ m (tl n))\nend.\nintros. simpl. unfold lengthOrder. eauto.\nunfold well_founded. intro. \neapply lengthOrder_wf'. auto.\nDefined.\n\nCheck revapp_equation.\n\n(** Tactic functional induction (qualid term+) *)\n(* The tactic functional induction performs case analysis and induction\n   following the definition of a function. It makes use of a principle \n   generated by Function or Functional Scheme. \n*)\n\nFunctional Scheme revapp_ind := Induction for revapp Sort Prop.\n\nCheck revapp_ind.\n\n(** ?? func_ind only possible for simple(?) cases*)\n\n(** Simple example proof with functional induction*)\n\nFunctional Scheme minus_ind := Induction for minus Sort Prop.\n\nCheck minus_ind.\n\nLemma le_minus (n m:nat) : n - m <= n.\n(* 1 subgoal\n  \n  n, m : nat\n  ============================\n  n - m <= n\n*)\nfunctional induction (minus n m) using minus_ind; simpl; auto.\n\nQed.\n\n\n(** using program fixpoint - nested recursion is possible*)\n\nProgram Fixpoint revapp' (m n : list nat) {measure (length n)}  :=\n  match n with\n  | nil => m\n  | _   => cons (hd 0 n) (revapp' m (tl n))\n  end.\n\nObligations.\n\n\n\nPrint All.\n\n(** Diff between Program Fixpoint and Function *)\n(* As you already mentioned, Program Fixpoint allows the measure to look at more than one argument.\nFunction creates a foo_equation lemma that can be used to rewrite calls to foo with its RHS. Very useful to avoid problems like Coq simpl for Program Fixpoint.\nIn some (simple?) cases, Function can define a foo_ind lemma to perform induction along the structure of recursive calls of foo. Again, very useful to prove things about foo without effectively repeating the termination argument in the proof.\nProgram Fixpoint can be tricked into supporting nested recursion, see https://stackoverflow.com/a/46859452/946226. This is also why Program Fixpoint can define the Ackermann function when Function cannot.*)", "meta": {"author": "faribaK", "repo": "coqlearning", "sha": "bc4b4b4ec12220e84544eb557071d6f09e26ac79", "save_path": "github-repos/coq/faribaK-coqlearning", "path": "github-repos/coq/faribaK-coqlearning/coqlearning-bc4b4b4ec12220e84544eb557071d6f09e26ac79/recursion_variants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.705129966254473}}
{"text": "Require Import Omega.\nRequire Import Tactics.Tactics.\nFrom Equations Require Import Equations.\nImport Sigma_Notations.\n\nSet Implicit Arguments.\nOpen Scope equations_scope.\nNotation \"{< x >}\" := (sigmaI _ _ x).\n\nInductive Fin : nat -> Set :=\n| FZ : forall k, Fin (S k)\n| FS : forall k, Fin k -> Fin (S k).\n\nInductive Vect : nat -> Type -> Type :=\n| Nil : forall A, Vect 0 A\n| Cons : forall n A, A -> Vect n A -> Vect (S n) A.\nDerive Signature Subterm for Vect.\n\nArguments Nil {A}.\n\nSection Length.\n  Equations length {A} {n} (xs : Vect n A) : nat :=\n    length Nil := 0;\n    length (Cons x xs) := S (length xs).\n\n  Theorem lengthCorrect :\n    forall A n (xs : Vect n A), length xs = n.\n  Proof.\n    intros; funelim (length xs); auto.\n  Qed.\nEnd Length.\n\nEquations tail {A} {n} (xs : Vect (S n) A) : Vect n A :=\n  tail (Cons x xs) := xs.\n\nEquations head {A} {n} (xs : Vect (S n) A) : A :=\n  head (Cons x xs) := x.\n\nEquations last {A} {n} (xs : Vect (S n) A) : A :=\nlast xs by rec (signature_pack xs) Vect_subterm :=\n  last (Cons x Nil) := x;\n  last (Cons x ys) := last ys.\n\nEquations init {A} {n} (xs : Vect (S n) A) : Vect n A :=\ninit xs by rec (signature_pack xs) Vect_subterm :=\n  init (Cons x Nil) := Nil;\n  init (Cons x ys) := Cons x (init ys).\n\nEquations index {A} {n} (f : Fin n) (xs : Vect n A) : A :=\n  index FZ (Cons x xs) := x;\n  index (FS f) (Cons x xs) := index f xs.\n\nEquations insertAt {A} {n} (f : Fin (S n)) (y : A) (xs : Vect n A) : Vect (S n) A :=\n  insertAt FZ y xs := Cons y xs;\n  insertAt (FS f) y (Cons x xs) := Cons x (insertAt f y xs).\n\nEquations replaceAt {A} {n} (f : Fin n) (y : A) (xs : Vect n A) : Vect n A :=\n  replaceAt FZ y (Cons x xs) := Cons y xs;\n  replaceAt (FS f) y (Cons x xs) := Cons x (replaceAt f y xs).\n\nTheorem replaceIndex :\n  forall A n (y : A) (xs : Vect n A) (f : Fin n),\n    index f (replaceAt f y xs) = y.\nProof.\n  induction xs; intros.\n  - depelim f.\n  - depelim f; simp replaceAt index.\nQed.\n\nEquations take {A} n {m} (xs : Vect (n + m) A) : Vect n A :=\n  take 0 xs := Nil;\n  take (S n) (Cons x xs) := Cons x (take n xs).\n\nEquations drop {A} n {m} (xs : Vect (n + m) A) : Vect m A :=\n  drop 0 xs := xs;\n  drop (S n) (Cons x xs) := drop n xs.\n\nEquations takeWhile {A} {n} (p : A -> bool) (xs : Vect n A) :\n    &{ m : nat & Vect m A } :=\n  takeWhile p Nil := {< Nil >};\n  takeWhile p (Cons x xs) <= p x => {\n    takeWhile p (Cons x xs) true :=\n      let ys := takeWhile p xs in {< Cons x (ys.2) >};\n    takeWhile p (Cons x xs) false :=\n      {< Nil >}\n  }.\n\nEquations dropWhile {A} {n} (p : A -> bool) (xs : Vect n A) :\n    &{ m : nat & Vect m A } :=\n  dropWhile p Nil := {< Nil >};\n  dropWhile p (Cons x xs) <= p x => {\n    dropWhile p (Cons x xs) true := dropWhile p xs;\n    dropWhile p (Cons x xs) false := {< Cons x xs >}\n  }.\n\nEquations append {A} {n m} (xs : Vect n A) (ys : Vect m A) : Vect (n + m) A :=\n  append Nil ys := ys;\n  append (Cons x xs) ys := Cons x (append xs ys).\n\nEquations replicate {A} n (x : A) : Vect n A :=\n  replicate 0 x := Nil;\n  replicate (S n) x := Cons x (replicate n x).\n\nTheorem takeDropAppend :\n  forall A n m (xs : Vect (n + m) A),\n    append (take n xs) (drop n xs) = xs.\nProof.\n  induction n; intros.\n  - trivial.\n  - depelim xs; simp take drop append.\n    now rewrite IHn.\nQed.\n\nLemma Vectn :\n  forall A n m, Vect n A = Vect m A -> n = m.\nProof.\nAdmitted.\n\nLemma JMeqCons :\n  forall A n m (a : A) (b : Vect n A) (c : Vect m A),\n    b ~= c -> Cons a b ~= Cons a c.\nProof.\n  intros. depelim H.\n  apply Vectn in H; subst.\n  now rewrite H0.\nQed.\n\nTheorem takeDropWhileAppend :\n  forall A n (p : A -> bool) (xs : Vect n A),\n    append (takeWhile p xs).2 (dropWhile p xs).2 ~= xs.\nProof.\n  induction n; intros.\n  - depelim xs; intuition.\n  - funelim (takeWhile p xs); funelim (dropWhile p (Cons a v)); simpl in *.\n    + simp append.\n      specialize (IHn p v0).\n      remember (append (takeWhile p v0).2 (dropWhile p v0).2) as ys; clear Heqys.\n      now apply JMeqCons.\n    + rewrite Heq in Heq0; discriminate.\n    + rewrite Heq in Heq0; discriminate.\n    + simp append.\nQed.\n\nSection Reverse.\n  Equations Vect_plus_n_O_inject {A} {n} (xs : Vect n A) : Vect (n + 0) A :=\n    Vect_plus_n_O_inject xs := _.\n  Next Obligation.\n    rewrite <- plus_n_O; exact xs.\n  Defined.\n\n  Equations Vect_plus_S_inject {A} {n m} (xs : Vect (S n + m) A)\n      : Vect (n + S m) A :=\n    Vect_plus_S_inject xs := _.\n  Next Obligation.\n    assert (S n + m = n + S m). omega.\n    rewrite <- H; exact xs.\n  Defined.\n\n  Equations reverseHelper {A} {n} {m} (acc : Vect n A) (ys : Vect m A)\n      : Vect (n + m) A :=\n  reverseHelper acc ys by rec (signature_pack ys) Vect_subterm :=\n    reverseHelper acc Nil := Vect_plus_n_O_inject acc;\n    reverseHelper acc (Cons y ys) :=\n      Vect_plus_S_inject (reverseHelper (Cons y acc) ys).\n\n  Equations reverse {A} {n} (xs : Vect n A) : Vect n A :=\n    reverse xs := reverseHelper Nil xs.\n\n  Lemma reverseInvolutive :\n    forall A n (xs : Vect n A),\n      reverse (reverse xs) = xs.\n  Proof.\n    intros; simp reverse.\n  Admitted.\nEnd Reverse.", "meta": {"author": "foreverbell", "repo": "verified", "sha": "44bba8f17b8070de304e14bc6fe1580e6890cd43", "save_path": "github-repos/coq/foreverbell-verified", "path": "github-repos/coq/foreverbell-verified/verified-44bba8f17b8070de304e14bc6fe1580e6890cd43/vect-deptype/Vect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7050604739571408}}
{"text": "From Coq Require Import Arith Bool.\n\n(* At its core, Coq is a *typed* programing language *)\n(* There are a few (not many!) built-in types *)\n(*\n\n   On the online version, you can move your cursor up and down with\n   Alt+p and Alt+n respectively.\n\n   The result of the command should show up in the lower right hand\n   side of the screen.\n\n   Remember to leave it time to load up at the very beginning!\n\n *)\nCheck 3.\nCheck 3 + 4.\nCheck true.\nCheck (true && false).\n\n(* And so it can evaluate progr==ams *)\nEval compute in (3 + 4).\nEval compute in (true && false).\n\n(* Every top-level command starts with a capital letter and ends with a period. *)\n(* Grammar was very important to the original implementers... *)\n\n(* No side effects though, so no printing, scanning or reading from a file! *)\nFail Check print.\n\n(* Not to be confused with the *top level command* \"Print\", which asks\nthe Coq *system* to print a definition. *)\nPrint bool.\n\n(*\n\n  NB: Every piece of data in a program is *constant* and *immutable*\n  There are good reasons for this, which we will go into later.\n\n *)\n\n(* We can define types. This is a simple sum type *)\nInductive week_day :=\n| Monday : week_day\n| Tuesday : week_day\n| Wednesday : week_day\n| Thursday : week_day\n| Friday : week_day\n| Saturday : week_day\n| Sunday : week_day.\n\nCheck Thursday.\n\n(* And we can define functions *)\nDefinition add_one (x : nat) : nat := x + 1.\nDefinition return_monday (w : week_day) : week_day := Monday.\n\nCheck add_one.\nEval compute in (add_one 2).\n\nCheck return_monday.\n\n(* We can work by cases over sum types. *)\nDefinition is_monday (w : week_day) : bool :=\n  match w with\n  | Monday => true\n  | _ => false\n  end.\n\nCheck is_monday.\n\nEval compute in (is_monday Tuesday).\n\n(* There is a powerful search feature, which takes types and returns\n     potentially useful functions with similar types *)\n(* WARNING: this does not work on the online version! *)\n\nSearch (bool -> bool).\n\n\n(* We can define types which may be recursive, e.g. the type of lists *)\nInductive week_day_list :=\n| Nil : week_day_list\n| Cons : week_day -> week_day_list -> week_day_list.\n\nCheck (Cons Monday (Cons Tuesday Nil)).\nEval compute in (Cons Monday (Cons Tuesday Nil)).\n\n(* Ok, we have lisp-style lists. Can we define head? *)\nDefinition head (l : week_day_list) (default : week_day) : week_day :=\n  match l with\n  | Nil => default\n  | Cons w _ => w\n  end.\n(* We need a default value! A little unfortunate... but the price of being pure! *)\n\n(* How about tail? *)\nDefinition tail (l : week_day_list) : week_day_list := \n  match l with\n  | Nil => Nil\n  | Cons _ w => w\n  end.\n\nEval compute in (tail (Cons Monday (Cons Tuesday Nil))).\n\n(* List notation a la lisp is tedious. Thankfully, Coq's notation system is incredibly powerful! *)\n\nNotation \"[ ]\" := Nil.\n\nNotation \"[ w ]\" := (Cons w Nil).\n\nNotation \"[ w1 ; w2 ; .. ; wn ]\" := (Cons w1 (Cons w2 .. (Cons wn Nil) .. )).\n\nDefinition work_week := [Monday; Tuesday; Wednesday; Thursday; Friday].\n\nEval compute in work_week.\n\n(* All right, let's define some funner things. *)\n\nDefinition eq_wd (w1 : week_day) (w2 : week_day) : bool :=\n  match (w1, w2) with\n  | (Monday, Monday) => true\n  | (Tuesday, Tuesday) => true\n  | (Wednesday, Wednesday) => true\n  | (Thursday, Thursday) => true\n  | (Friday, Friday) => true\n  | (Saturday, Saturday) => true\n  | (Sunday, Sunday) => true\n  | _ => false\n  end.\n\n(* How about a length function? This requires a special syntax: *)\nFixpoint length (l : week_day_list) : nat :=\n  match l with\n  | [] => 0\n  | Cons w ws => (length ws) + 1\n  end.\n\nEval compute in (length work_week).\n\n(* Now let's define a membership function *)\nFixpoint is_a_member (w : week_day) (l : week_day_list) : bool :=\n  match l with\n  | [] => false\n  | Cons w' ws => eq_wd w w' || is_a_member w ws\n  end.\n\n(* Let's test it: *)\nEval compute in (is_a_member Monday work_week).\nEval compute in (is_a_member Sunday work_week).\n\n(* Ok, we're ready for some specifications! *)\n(* The simplest kind of specification is equality: *)\nCheck (Monday = Monday).\n\n(* The Prop type is the type of *specifications*. It is *not* bool! *)\nCheck (forall w, w = Monday).\nCheck (exists w, w = Monday).\n\n(* The basic propositional connectives: *)\n(* True. Always provable. *)\n(* False. Never provable. *)\n(* P\\/Q. Provable if one of P or Q (or both) is provable. *)\n(* P/\\Q. Provable if both P and Q are provable. *)\n(* P -> Q. Provable if, when *assuming* P is provable, then so is Q. *)\n(* ~P. Provable if P is *never* provable *)\n(* forall x : A, P x. Provable if for an *arbitrary* x (of type A), P x is provable. *)\n(* exists x : A, P x. Provable if there is some *specific* a such that P a is provable. *)\n(* a = b. Provable if, in fact, a is equal to b. Not to be confused\n   with \":=\" which is how we define functions and constants (and is\n   *not* a connective).  *)\n\n\n(* Obviously, we can state specifications about infinite types as well: *)\n\nCheck (forall l : week_day_list, l = [] \\/ exists w l', l = Cons w l').\n\n(* Some of these specifications are provable, some are not. *)\n\n(* We give some basic tools to prove some of these specs: *)\n\n\n\nLemma test1 : forall x y : week_day, x = y -> x = y.\nProof.\nAbort.\n\n\n(* ---------------------------------------------------------\n     There are some simple cheats on how to prove various kinds of specifications:\n     roughly, one can try certain tactics based on the *shape* of the goal and the\n     hypotheses. The breakdown is like this:\n\n     |               |   in goal   |   in hypotheses   |\n     |---------------+-------------+------------------ |\n     | A -> B        |  intros     |      apply        |\n     | A /\\ B        |  split      |     destruct      |\n     | A \\/ B        |  left/right |     destruct      |\n     | ~A            |  intro      |      apply        |\n     |  True         |  trivial    |       N/A         |\n     |  False        |    N/A      |   contradiction   |\n     | forall x, P x |  intros     |      apply        |\n     | exists x, P x |  exists t   |     destruct      |\n     | t = u         | reflexivity | rewrite/inversion |\n\n     but of course, these will not always suffice in all situations.\n *)\n\n\n(* Here's how one proves trivial equalities: *)\nLemma test2 : Monday = Monday.\nProof.\nAbort.\n\n(* It's nice to know that this doesn't always work: *)\nLemma test2_fail : Monday = Friday.\nProof.\n  Fail reflexivity.\nAbort.\n\n(* We can also perform computation steps in proofs, in order to\n     prove things about functions: *)\nLemma test3 : return_monday Friday = Monday.\nProof.\nAbort.\n\nLemma test3' : length work_week = 5.\nProof.\nAbort.\n\n(* But really we're interested in behavior over *all inputs*. *)\nLemma test4 : forall x : week_day, return_monday x = Monday.\nProof.\nAbort.\n\n(* How about this? Hint: use the [case some_variable] tactic *)\nLemma test5 : forall x : week_day, eq_wd x x = true.\nProof.\nAbort.\n\n(* Let's play with some logical connectives *)\nLemma test6 : forall x y z : week_day, x = y -> y = z -> x = y /\\ y = z.\nProof.\nAbort.\n\nLemma test7 : forall x y z : week_day, x = y -> x = y \\/ y = z.\nProof.\nAbort.\n\nLemma test8 : forall x y z : week_day, x = y /\\ y = z -> y = z.\nProof.\nAbort.\n\n(* This one is a little tougher! tactic order matters! *)\nLemma test9 : forall x y z : week_day, x = y \\/ x = z -> x = z \\/ x = y.\nProof.\nAbort.\n\n(* Proofs involving equalities *)\nLemma test10 : forall x y, x = Monday -> y = x -> y = Monday.\nProof.\nAbort.\n\nLemma test11 : Monday = Tuesday -> False.\nProof.\nAbort.\n\n(* All right we're ready for some serious stuff *) \nLemma first_real_lemma : forall x y, x = y -> eq_wd x y = true.\nProof.\nAbort.\n\n(* The other direction is harder! *)\nLemma second_real_lemma : forall x y, eq_wd x y = true -> x = y.\nProof.\nAbort.\n\n(* Now we have a program which we have proven correct! We can use this to prove some theorems! *)\nLemma test12 : Monday = Monday.\nProof.\nAbort.\n\n(* Let's show correctness of our membership function! But first we need to *specify* membership. *)\n(* To do this, we specify an *inductive predicate*, which describes all the ways an element can be in a list. *)\n(* We can again use the keyword inductive. *)\nInductive Mem : forall (w : week_day) (l : week_day_list), Prop :=\n| Mem_head : forall w l, Mem w (Cons w l)\n| Mem_tail : forall w w' l, Mem w l -> Mem w (Cons w' l).\n\n\n(* We can apply constructors of Mem like lemmas *)\nLemma test13 : Mem Monday [Tuesday; Monday; Thursday].\nProof.\nAbort.\n\n(* Here's some fun existential statements: *)\nLemma test14 : exists w, Mem w work_week.\nProof.\nAbort.\n\n(* This is harder! We'll be able to prove this easily once we have the\n     theorems.\n *)\nLemma test15 : exists w, ~ (Mem w work_week).\nProof.\nAbort.\n\n(* The theorems we want are these: *)\nTheorem is_a_member_correct : forall w l, is_a_member w l = true -> Mem w l.\nProof.\nAbort.\n\nTheorem is_a_member_complete : forall w l, Mem w l -> is_a_member w l = true.\nProof.\nAbort.\n\n(*\n\n  Finally, it's important to note that I purposefully hid a number of\n  powerful tactics from you, for pedagogical reasons. The easiest of\n  these is [auto], which tries to apply simple steps to finish a\n  goal. Exercise: how much easier are the lemmas to prove using\n  [auto]?\n\n*)\n\n(*\n\n  There is still a lot to learn! You can check out the resources on\n  https://coq.inria.fr/, most notably the tutorials on\n  https://coq.inria.fr/documentation.\n\n  You can try more online stuff on rhino-coq:\n  https://x80.org/rhino-coq/\n\n  I have a few things on my github:\n  https://github.com/codyroux?tab=repositories&q=&type=&language=coq\n\n  Or create an account on https://coq.zulipchat.com, and ask questions\n  there!\n\n  Go forth and prove!\n\n *)\n", "meta": {"author": "banrovegrie", "repo": "theorem-proving", "sha": "ca692d0f06db0bfd2721f1097c6110163f8023a8", "save_path": "github-repos/coq/banrovegrie-theorem-proving", "path": "github-repos/coq/banrovegrie-theorem-proving/theorem-proving-ca692d0f06db0bfd2721f1097c6110163f8023a8/coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7050604648730414}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Lists.\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** 在本章中，我们会继续发展函数式编程的基本概念，其中最关键的新概念就是 多态\n   （在所处理的数据类型上抽象出函数）和高阶函数（函数作为数据）。 *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** 在前几章中，我们只是使用了数的列表。很明显，有趣的程序还需要能够处理其它元素类型的列表，\n    如字符串列表、布尔值列表、 列表的列表等等。我们可以分别为它们定义新的归纳数据类型，例如...*)\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\n(** ...不过这样很快就会变得乏味。 部分原因在于我们必须为每种数据类型都定义不同的构造子， \n    然而主因还是我们必须为每种数据类型再重新定义一遍所有的列表处理函数 （如 length、rev 等）。*)\n\n(** 为避免这些重复，Coq 支持定义多态归纳类型。 例如，以下就是多态列表数据类型。 *)\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n(** 这和上一章中 [natlist] 的定义基本一样，只是将 [cons] 构造子的 [nat] 参数换成了任意的类型\n     [X]，定义的头部添加了 [X] 的绑定， 而构造子类型中的 [natlist] 则换成了 [list X]。（我们\n     可以重用构造子名 [nil] 和 [cons]，因为之前定义的 [natlist] 在当前作用之外的一个\n      [Module] 中。）\n\n      [list] 本身又是什么类型？一种不错的思路就是把 [list] 当做从 [Type] 类型到 [Inductive] \n      归纳定义的函数；或者换种思路，即 [list] 是个从 [Type] 类型到 [Type] 类型的函数。对于任何\n      特定的类型 [X]， 类型 [list X] 是一个 [Inductive] 归纳定义的，元素类型为 [X] 的列表的\n      集合。 *)\n\nCheck list.\n(* ===> list : Type -> Type *)\n\n(** The parameter [X] in the definition of [list] automatically\n    becomes a parameter to the constructors [nil] and [cons] -- that\n    is, [nil] and [cons] are now polymorphic constructors; when we use\n    them, we must now provide a first argument that is the type of the\n    list they are building. For example, [nil nat] constructs the\n    empty list of type [nat]. *)\n\nCheck (nil nat).\n(* ===> nil nat : list nat *)\n\n(** [cons nat] 与此类似，它将类型为 [nat] 的元素添加到类型为 [list nat] 的列表中。\n    以下示例构造了一个只包含自然数 3 的列表： *)\n\nCheck (cons nat 3 (nil nat)).\n(* ===> cons nat 3 (nil nat) : list nat *)\n\n(** [nil] 的类型可能是什么？我们可以从定义中看到 [list X] 的类型， 它忽略了 [list] 的\n    形参 [X] 的绑定。[Type → list X] 并没有解释 [X] 的含义，[(X : Type) → list X] 则\n    比较接近。Coq 对这种情况的记法为 [forall X : Type, list X]. *)\n\nCheck nil.\n(* ===> nil : forall X : Type, list X *)\n\n(** 类似地，定义中 [cons] 看起来像 [X → list X → list X] 然而以此约定来解释\n    [X] 的含义则是类型 [forall X, X → list X → list X]. *)\n\nCheck cons.\n(* ===> cons : forall X : Type, X -> list X -> list X *)\n\n(** （关于记法的附注：在 .v 文件中，量词 \"forall\" 会写成字母的形式， 而在生成的\n     HTML 和一些设置了显示控制的 IDE 中，[forall] 通常会渲染成一般的 \"∀\" 数学符号，\n     虽然你偶尔还是会看到英文拼写的 \"forall\"。这只是排版上的效果，它们的含义没有任何区别。）*)\n\n(** 如果在每次使用列表构造子时，都要为它提供类型参数，那样会很麻烦。 不过我们很快\n    就会看到如何省去这种麻烦。 *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat))).\n\n(** （这里显式地写出了 [nil] 和 [cons]，因为我们还没为新版本的列表定义 [[]] 和 [::] 记法。\n      我们待会儿再干。)\n      现在我们可以回过头来定义之前写下的列表处理函数的多态版本了。 例如 [repeat]： *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** 同 [nil] 与 [cons] 一样，我们可以通过将 [repeat] 应用到一个类型、\n    一个该类型的元素以及一个数字来使用它：*)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity.  Qed.\n\n(** 要用 [repeat] 构造其它种类的列表， 我们只需通过对应类型的参数将它实例化即可：*)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity.  Qed.\n\n\n(** **** Exercise: 2 stars, standard (mumble_grumble)  \n\n    Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\n\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?  (Add YES or NO to each line.)\n      - [d (b a 5)] \"NO\"\n      - [d mumble (b a 5)] \"YES\"\n      - [d bool (b a 5)] \"YES\"\n      - [e bool true] \"YES\"\n      - [e mumble (b c 0)] \"NO\"\n      - [e bool (b c 0)] \"NO\"\n      - [c] \"YES\" *)\n(* FILL IN HERE *)\nEval compute in d mumble (b a 5).\nEval compute in d bool (b a 5).\nEval compute in e bool true.\nEval compute in c.\nEnd MumbleGrumble.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_mumble_grumble : option (nat*string) := None.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** 我们再写一遍 [repeat] 的定义，不过这次不指定任何参数的类型。 Coq 还会接受它么？ *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** I当然会。我们来看看 Coq 赋予了 [repeat'] 什么类型： *)\n\nCheck repeat'.\n(* ===> forall X : Type, X -> nat -> list X *)\nCheck repeat.\n(* ===> forall X : Type, X -> nat -> list X *)\n\n(** 它与 [repeat] 的类型完全一致。Coq 可以使用类型推断 基于它们的使用方式来推出 [X]、[x] \n    和 [count] 一定是什么类型。例如， 由于 [X] 是作为 [cons] 的参数使用的，因此它必定是个\n    [Type] 类型， 因为 [cons] 期望一个 [Type] 作为其第一个参数，而用 [0] 和 [S] 来匹配\n     [count] 意味着它必须是个 [nat]，诸如此类。\n\n    这种强大的功能意味着我们不必总是在任何地方都显式地写出类型标注， 不过显式的类型标注对于\n    文档和完整性检查来说仍然非常有用， 因此我们仍会继续使用它。你应当在代码中把握好使用\n    类型标注的平衡点， 太多导致混乱并分散注意力，太少则会迫使读者为理解你的代码\n    而在大脑中进行类型推断。*)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** 要使用多态函数，我们需要为其参数再额外传入一个或更多类型。 例如，前面 [repeat]\n    函数体中的递归调用必须传递类型 [X]。不过由于 [repeat] 的第二个参数为 [X] 类型\n    的元素，第一个参数明显只能是 X， 既然如此，我们何必显式地写出它呢？\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write a \"hole\" [_], which can be\n    read as \"Please try to figure out for yourself what belongs here.\"\n    More precisely, when Coq encounters a [_], it will attempt to\n    _unify_ all locally available information -- the type of the\n    function being applied, the types of the other arguments, and the\n    type expected by the context in which the application appears --\n    to determine what concrete type should replace the [_].\n\n    这听起来很像类型标注推断。实际上，这两种个过程依赖于同样的底层机制。 \n    除了简单地忽略函数中某些参数的类型：\n\n      repeat' X x count : list X :=\n\n    我们还可以将类型换成 [_]：\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    以此来告诉 Coq 要尝试推断出缺少的信息。\n\n    Using holes, the [repeat] function can be written like this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** 在此例中，我们写出 [_] 并没有省略多少 [X]。然而在很多情况下，\n    这对减少击键次数和提高可读性还是很有效的。例如，假设我们要写下\n    一个包含数字 1、2 和 3 的列表，此时不必写成这样： *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use holes to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** 我们甚至可以通过告诉 Coq 总是推断给定函数的类型参数来避免 [_]。\n\n    [Arguments] 用于指令指定函数或构造子的名字并列出其参数名， 花括号中的\n    任何参数都会被视作隐式参数。（如果定义中的某个参数没有名字， 那么它可以\n    用通配模式 [_] 来标记。这种情况常见于构造子中。 *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** 现在我们再也不必提供类型参数了： *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** 此外，我们还可以在定义函数时声明隐式参数， 只是需要将它放在花括号内而非圆括号中。例如： *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (注意我们现在甚至不必在 [repeat'''] 的递归调用中提供类型参数了，\n    实际上提供了反而是无效的！)\n\n    我们会尽可能使用最后一种风格，不过还会继续在 Inductive 构造子中\n    使用显式的 Argument 声明。原因在于如果将归纳类型的形参标为隐式的话，\n    不仅构造子的类型会变成隐式的，类型本身也会变成隐式的。例如， 考虑\n    以下 list 类型的另一种定义：*)\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\n(** 由于 [X] 在包括 [list'] 本身的整个归纳定义中都是隐式声明的，\n    因此当我们讨论数值、布尔值或其它任何类型的列表时，都只能写 [list']，\n    而写不了 [list' nat]、[list' bool] 或其它的了，这样就跑得有点太远了。 *)\n\n(** 作为本节的收尾，我们为新的多态列表重新实现几个其它的标准列表函数... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity.  Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. simpl. reflexivity.  Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** 用 [Implicit] 将参数声明为隐式的会有个小问题：Coq 偶尔会没有足够的\n    局部信息来确定类型参数。此时，我们需要告诉 Coq 这次我们会显示地给出参数。\n    例如，假设我们写了如下定义：*)\n\nFail Definition mynil := nil.\n\n(** （[Definition] 前面的 [Fail] 限定符可用于 _任何_ 指令， 它的作用是确保该指令\n    在执行时确实会失败。如果该指令失败了，Coq 就会打印出相应的错误信息，不过之后会\n    继续处理文件中剩下的部分。）\n\n    在这里，Coq 给出了一条错误信息，因为它不知道应该为 [nil] 提供何种类型。 我们\n    可以为它提供个显式的类型声明来帮助它，这样 Coq 在\"应用\" [nil] 时就有更多可用的信息了：*)\n\nDefinition mynil : list nat := nil.\n\n(** 此外，我们还可以在函数名前加上前缀 [@] 来强制将隐式参数变成显式的：*)\n\nCheck @nil.\n\nDefinition mynil' := @nil nat.\n\n(** 使用参数推断和隐式参数，我们可以为列表定义和前面一样的简便记法。\n    由于我们让构造子的的类型参数变成了隐式的，因此 Coq 就知道在我们\n    使用该记法时自动推断它们了。\n *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** 现在列表就能写成我们希望的方式了： *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, optional (poly_exercises)  \n\n    Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros.\n  induction l as [| n l'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity. Qed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros.\n  induction l as [| n1 l1' IHl1'].\n  - reflexivity.\n  - simpl. rewrite -> IHl1'. reflexivity. Qed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros.\n  induction l1 as [| n2 l2' IHl2'].\n  - reflexivity.\n  - simpl. rewrite -> IHl2'. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (more_poly_exercises)  \n\n    Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros.\n  induction l1 as [| n l' IHl'].\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl'. rewrite -> app_assoc. reflexivity. Qed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros.\n  induction l as [| n l'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> rev_app_distr. rewrite -> IHl'. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** 按照相同的模式，我们在上一章中给出的数值序对的定义可被推广为_多态序对_（Polymorphic\n    Pairs），它通常叫做_积_（Products）：*)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y} _ _.\n\n(** 和列表一样，我们也可以将类型参数定义成隐式的， 并以此定义类似的具体记法：*)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** 我们也可以使用 [Notation] 来定义标准的_积类型_（Product Types）记法：*)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** （标注 [: type_scope] 会告诉 Coq 该缩写只能在解析类型时使用。\n    这避免了与乘法符号的冲突。)*)\n\n(** 一开始会很容易混淆 [(x,y)] 和 [X*Y]。不过要记住 [(x,y)] 是一个值，\n    它由两个其它的值构造得来；而 [X*Y] 是一个类型， 它由两个其它的类型\n    构造得来。如果 [x] 的类型为 [X] 而 [y] 的类型为 [Y]， 那么 [(x,y)]\n    的类型就是 [X*Y]。*)\n\n(** 第一元（first）和第二元（second）的射影函数（Projection Functions）\n    现在看起来和其它函数式编程语言中的很像了：*)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** 以下函数接受两个列表，并将它们结合成一个序对的列表。 在其它函数式语言中，\n    它通常被称作 [zip]。我们为了与 Coq 的标准库保持一致， 将它命名为 [combine]。*)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, standard, optional (combine_checks)  \n\n    Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print? \n\n    [] *)\nCheck @combine.\n(* forall X Y : Type, list X -> list Y -> list (X * Y) *)\nCompute (combine [1;2] [false;false;true;true]).\n(* [(1, false); (2, false)] *)\n(* forall X Y : Type, list X -> list Y -> list (X * Y) *)\n(** **** Exercise: 2 stars, standard, recommended (split)  \n\n    The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n  match l with\n    | [] => ([], [])\n    | (x, y)::l' => (x::(fst (split l')), y::(snd (split l')))\n end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** 现在介绍最后一种多态类型：多态候选（Polymorphic Options）, 它推广了上一章中的\n    [natoption]. (We put the definition inside a module because the \n    standard library already defines [option] and it's this one that\n    we want to use below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** 现在我们可以重写 [nth_error] 函数来让它适用于任何类型的列表了。*)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if n =? O then Some a else nth_error l' (pred n)\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 [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (hd_error_poly)  \n\n    Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n    | nil    => None\n    | h :: _ => Some h\nend.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** 和其它现代编程语言，包括所有函数式语言（ML、Haskell、 Scheme、Scala、Clojure 等）\n    一样，Coq 也将函数视作“一等公民（First-Class Citizens）”， 即允许将它们作为参数\n    传入其它函数、作为结果返回、以及存储在数据结构中等等。*)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** F用于操作其它函数的函数通常叫做_高阶函数_。以下是简单的示例：*)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** 这里的参数 [f] 本身也是个（从 [X] 到 [X] 的）函数， [doit3times] 的函数体\n    将 [f] 对某个值 [n] 应用三次。*)\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity.  Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** 下面是个更有用的高阶函数，它接受一个元素类型为 [X] 的列表和一个 [X] 的谓词\n   （即一个从 [X] 到 [bool] 的函数），然后\"过滤\"此列表并返回一个新列表， 其中\n   仅包含对该谓词返回 [true] 的元素。*)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** 例如，如果我们将 [filter] 应用到 predicate [evenb] 和\n    一个数值列表 [l] 上，那么它就会返回一个只包含 [l] 中偶数的列表。*)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity.  Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** 我们可以使用 [filter] 给出 [Lists] 章节中 [countoddmembers] 函数的简洁的版本。*)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'2:countoddmembers' [0;2;4] = 0.\nProof. reflexivity.  Qed.\nExample test_countoddmembers'3:countoddmembers' nil = 0.\nProof. reflexivity.  Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** 在上面这个例子中，我们不得不定义一个名为 [length_is_1] 的函数， 以便让它能够\n    作为参数传入到 [filter] 中，由于该函数可能再也用不到了， 这有点令人沮丧。\n    我们经常需要传入\"一次性\"的函数作为参数，之后不会再用， 而为每个函数取名是十分无聊的。\n    幸运的是，有一种更好的方法。我们可以按需随时构造函数而不必在顶层中声明它或给它取名 *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity.  Qed.\n\n(** 表达式 [(fun n => n * n)] 可读作\"一个给定 [n] 并返回 [n * n] 的函数。\" *)\n\n(** 以下为使用匿名函数重写的 [filter] 示例：*)\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity.  Qed.\n\n(** **** Exercise: 2 stars, standard (filter_even_gt7)\n\n    Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => (evenb n) && (leb 7 n)) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (partition)  \n\n    Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a test function of type [X -> bool] and a [list\n   X], [partition] should return a pair of lists.  The first member of\n   the pair is the sublist of the original list containing the\n   elements that satisfy the test, and the second is the sublist\n   containing those that fail the test.  The order of elements in the\n   two sublists should be the same as their order in the original\n   list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n  (filter test l, filter (fun n => negb (test n)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** 另一个方便的高阶函数叫做 [map]. *)\n\nFixpoint map {X Y: Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** 它接受一个函数 [f] 和一个列表 [l = [n1, n2, n3, ...]] 并返回列表\n    [[f n1, f n2, f n3,...]] ，其中 [f] 可分别应用于 [l] 中的每一个元素。例如： *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** 输入列表和输出列表的元素类型不必相同，因为 [map] 会接受_两个_类型参数 [X] 和 [Y]，\n    因此它可以应用到一个数值的列表和一个从数值到布尔值的函数， 并产生一个布尔值列表：*)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity.  Qed.\n\n(** 它甚至可以应用到一个数值的列表和一个从数值到布尔值列表的函数， \n    并产生一个布尔值的_列表的列表_： *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity.  Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars, standard (map_rev)  \n\n    Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nLemma app_map : forall (X Y : Type) (f : X -> Y) (l : list X) (x : X),\n  app (map f l) [f x] = map f (app l [x]).\nProof.\n  intros.\n  induction l.\n  - reflexivity.\n  - simpl. rewrite -> IHl. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [|x l'].\n  - (* l = nil *)\n    reflexivity.\n  - (* l = n :: l' *)\n    simpl. rewrite <- IHl'. simpl.\n    rewrite -> app_map. reflexivity.\nQed.\n\nLemma map_app : forall (X Y : Type) (f : X -> Y) (l1 l2 : list X),\n  map f (l1 ++ l2) = map f l1 ++ (map f l2).\nProof.\n  intros.\n  induction l1 as [| h1 t1 IH1].\n  - reflexivity.\n  - simpl. rewrite -> IH1. reflexivity.\nQed.\n\nTheorem map_rev' : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros.\n  induction l as [| h t IH].\n  - reflexivity.\n  - simpl. rewrite -> map_app.\n    simpl. rewrite -> IH.\n    reflexivity.\nQed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (flat_map)  \n\n    The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : (list Y) :=\n  match l with\n    | [] => []\n    | h :: t => (f h) ++ (flat_map f t)\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n(** [] *)\n\n(** Lists are not the only inductive type for which [map] makes sense.\n    Here is a [map] for the [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, standard, optional (implicit_args)  \n\n    The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n\n    [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** 一个更加强大的高阶函数叫做 [fold]。本函数启发自\"reduce\"归约操作，\n    它是 Google 的 map/reduce 分布式编程框架的核心。*)\n\nFixpoint fold {X Y: Type} (f: X->Y->Y) (l: list X) (b: Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** 直观上来说，[fold] 操作的行为就是将给定的二元操作符 [f] 插入到给定列表的每一对元素之间。\n    例如， [fold plus [1;2;3;4]] 直观上的意思是 [1+2+3+4]。为了让它更精确，我们还需要一个\n    \"起始元素\" 作为 f 初始的第二个输入。因此，例如\n\n       fold plus [1;2;3;4] 0\n\n    就会产生\n\n       1 + (2 + (3 + (4 + 0))).\n\n    更多例子: *)\n\nCheck (fold andb).\n(* ===> fold andb : list bool -> bool -> bool *)\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed. \n\n(** **** Exercise: 1 star, advanced (fold_types_different)  \n\n    Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n    \nDefinition flat_map' {X : Type} (l : list (list X)) : list X\n  := fold app l [].\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_types_different : option (nat*string) := None.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** 目前我们讨论过的大部分高阶函数都是接受函数作为参数的。 现在我们来看一些将函数\n    作为其它函数的_结果_返回的例子。 首先，下面是一个接受值 [x]（由某个类型 [X] 刻画）\n    并返回一个从 [nat] 到 [X] 的函数，当它被调用时总是产生 [x] 并忽略其 [nat] 参数。*)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** 实际上，我们已经见过的多参函数也是讲函数作为数据传入的例子。 \n    为了理解为什么，请回想 [plus] 的类型。*)\n\nCheck plus.\n(* ==> nat -> nat -> nat *)\n\n(** 该表达式中的每个 [->] 实际上都是一个类型上的二元操作符。 该操作符是_右结合_的，\n    因此 [plus] 的类型其实是 [nat -> (nat -> nat)] 的简写，即，它可以读作\n    \"[plus] 是一个单参数函数，它接受一个 [nat] 并返回另一个函数，该函数接受另一个\n    [nat] 并返回一个[nat]\"。 在上面的例子中，我们总是将 [plus]一次同时应用到两个参数上\n    不过如果我们喜欢，也可以一次只提供一个参数，这叫做_偏应用_（Partial Application）*)\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity.  Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity.  Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity.  Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars, standard (fold_length)  \n\n    Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length].  (Hint: It may help to\n    know that [reflexivity] simplifies expressions a bit more\n    aggressively than [simpl] does -- i.e., you may find yourself in a\n    situation where [simpl] does nothing but [reflexivity] solves the\n    goal.) *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros.\n  induction l as [| x l' IHl'].\n  - reflexivity.\n  - simpl. rewrite <- IHl'. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (fold_map)  \n\n    We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n  fold (fun x l => cons (f x) l) l [].\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it.  (Hint: again, remember that\n   [reflexivity] simplifies expressions a bit more aggressively than\n   [simpl].) *)\n\nTheorem fold_map_correct : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f l = fold_map f l.\nProof.\n  intros X Y f l.\n  induction l as [|x l'].\n  - reflexivity.\n  - simpl. rewrite -> IHl'. simpl. reflexivity. Qed.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying)  \n\n    In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p).\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity.  Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof. reflexivity. Qed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros.\n  unfold prod_uncurry. unfold prod_curry. destruct p. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal)  \n\n    Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X n l, length l = n -> @nth_error X l n = None\n*)\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** The following exercises explore an alternative way of defining\n    natural numbers, using the so-called _Church numerals_, named\n    after mathematician Alonzo Church.  We can represent a natural\n    number [n] as a function that takes a function [f] as a parameter\n    and returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : cnat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** **** Exercise: 1 star, advanced (church_succ)  *)\n\n(** Successor of a natural number: given a Church numeral [n],\n    the successor [succ n] is a function that iterates its\n    argument once more than [n]. *)\nDefinition succ (n : cnat) : cnat := fun (X : Type) (f : X -> X) (x : X) => f (n X f x).\n\nExample succ_1 : succ zero = one.\nProof. reflexivity. Qed.\n\nExample succ_2 : succ one = two.\nProof. reflexivity. Qed.\n\nExample succ_3 : succ two = three.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (church_plus)  *)\n\n(** Addition of two natural numbers: *)\nDefinition plus (n m : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => n X f (m X f x).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\n\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_mult)  *)\n\n(** Multiplication: *)\nDefinition mult (n m : cnat) : cnat  := fun (X : Type) (f : X -> X) => m X (n X f).\n\nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\n\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_exp)  *)\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type.  Iterating over [cnat] itself is usually problematic.) *)\n\nDefinition exp (n m : cnat) : cnat := fun (X : Type) => m (X -> X) (n X).\n\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\n\nExample exp_2 : exp three zero = one.\nProof. reflexivity. Qed.\n\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\n(** [] *)\n\nEnd Church.\n\nEnd Exercises.\n\n\n(* Wed Aug 28 14:52 EST 2019 *)\n", "meta": {"author": "klchai", "repo": "Coq", "sha": "9eff66584563a6dc2d320869af1e6b346278c7fc", "save_path": "github-repos/coq/klchai-Coq", "path": "github-repos/coq/klchai-Coq/Coq-9eff66584563a6dc2d320869af1e6b346278c7fc/Code/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.705060461946392}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLemma lshift_inj (m n : nat) : injective (@lshift m n).\nProof. by move=> x y /(f_equal val) /= /val_inj. Qed.\n\nLemma rshift_inj (m n : nat) : injective (@rshift m n).\nProof. by move=> x y /(f_equal val) /addnI /val_inj. Qed.\n\nLemma lshift_rshift_neq (m n : nat) i j : lshift m i != rshift n j.\nProof. by rewrite eqE /= neq_ltn ltn_addr. Qed.\n\nLemma rshift_lshift_neq (m n : nat) i j : rshift n j != lshift m i.\nProof. by rewrite eq_sym; exact: lshift_rshift_neq. Qed.\n\nLemma enum_rank_in_inj\n      (T : finType) (x0 y0 : T) A (Ax0 : x0 \\in A) (Ay0 : y0 \\in A) :\n  {in A &, forall x y, enum_rank_in Ax0 x = enum_rank_in Ay0 y -> x = y}.\nProof. by move=> x y xA yA /(congr1 enum_val); rewrite !enum_rankK_in. Qed.\n\nLemma all_allpairsP\n      (S : eqType) (T : S -> eqType) (R : Type)\n      (g : pred R) (f : forall i : S, T i -> R)\n      (s : seq S) (t : forall i : S, seq (T i)) :\n  reflect (forall (i : S) (j : T i), i \\in s -> j \\in t i -> g (f i j))\n          (all g [seq f i j | i <- s, j <- t i]).\nProof.\nelim: s => [|x s IHs]; first by constructor.\nrewrite /= all_cat all_map /preim.\napply/(iffP andP)=> [[/allP /= ? ? x' y x'_in_xs]|p_xs_t].\n  by move: x'_in_xs y; rewrite inE => /predU1P [-> //|? ?]; exact: IHs.\nsplit; first by apply/allP => ?; exact/p_xs_t/mem_head.\nby apply/IHs => x' y x'_in_s; apply: p_xs_t; rewrite inE x'_in_s orbT.\nQed.\n\nLemma all_pmap S T (p : pred T) (f : S -> option T) xs :\n  all p (pmap f xs) = all (fun i => oapp p true (f i)) xs.\nProof. by elim: xs => //= x xs <-; case: (f x). Qed.\n\nLemma all_filter S (p q : pred S) xs :\n  all p (filter q xs) = all (fun i => q i ==> p i) xs.\nProof. by elim: xs => //= x xs <-; case: (q x). Qed.\n\nLemma all_enum (T : finType) (P : pred T) : all P (enum T) = [forall i, P i].\nProof.\napply/allP/forallP => H x; move: (H x); rewrite mem_enum inE //; exact.\nQed.\n", "meta": {"author": "pi8027", "repo": "vass", "sha": "1ee42366a450d2743b52399a21ff80571b7bca94", "save_path": "github-repos/coq/pi8027-vass", "path": "github-repos/coq/pi8027-vass/vass-1ee42366a450d2743b52399a21ff80571b7bca94/utils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7050604497588951}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (y : natural) : natural := plus x (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_commut/goal33conj2910_coqofml_zSIxok.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7050325383480607}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** _Maps_ (or _dictionaries_) are ubiquitous data structures both\n    generally and in the theory of programming languages in\n    particular; we're going to need them in many places in the coming\n    chapters.  They also make a nice case study using ideas we've seen\n    in previous chapters, including building data structures out of\n    higher-order functions (from [Basics] and [Poly]) and the use of\n    reflection to streamline proofs (from [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which return an [option] to\n    indicate success or failure.  The latter is defined in terms of\n    the former, using [None] as the default element. *)\n\n(* ################################################################# *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we begin...\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (and, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Export Coq.Strings.String.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\n(** Documentation for the standard library can be found at\n    http://coq.inria.fr/library/.  \n\n    The [Search] command is a good way to look for theorems involving \n    objects of specific types.  Take a minute now to experiment with it. *)\n\n(* ################################################################# *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our \n    maps.  For this purpose, we will simply use plain [string]s. *)\n\n(** To compare strings, we define the function [beq_string], which \n    internally uses the function [string_dec] from Coq's string library. \n    We then establish its fundamental properties. *)\n\nDefinition beq_string x y :=\n  if string_dec x y then true else false.\n\n(** (The function [string_dec] comes from Coq's string library.\n    If you check the result type of [string_dec], you'll see that it\n    does not actually return a [bool], but rather a type that looks\n    like [{x = y} + {x <> y}], called a [sumbool], which can be\n    thought of as an \"evidence-carrying boolean.\"  Formally, an\n    element of [sumbool] is either a proof that two things are equal\n    or a proof that they are unequal, together with a tag indicating\n    which.  But for present purposes you can think of it as just a\n    fancy [bool].) *)\n\nTheorem beq_string_refl : forall s, true = beq_string s s.\nProof. intros s. unfold beq_string. destruct (string_dec s s) as [|Hs].\n  - reflexivity.\n  - destruct Hs. reflexivity.\nQed.\n\n(** The following useful property of [beq_string] follows from an \n    analogous lemma about strings: *)\n\nTheorem beq_string_true_iff : forall x y : string,\n  beq_string x y = true <-> x = y.\nProof.\n   intros x y.\n   unfold beq_string.\n   destruct (string_dec x y) as [|Hs].\n   - subst. split. reflexivity. reflexivity.\n   - split.\n     + intros contra. inversion contra.\n     + intros H. inversion H. subst. destruct Hs. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem beq_string_false_iff : forall x y : string,\n  beq_string x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_string_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This useful variant follows just by rewriting: *)\n\nTheorem false_beq_string : forall x y : string,\n   x <> y -> beq_string x y = false.\nProof.\n  intros x y. rewrite beq_string_false_iff.\n  intros H. apply H. Qed.\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about its behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the very same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps. *)\n\n(** We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A:Type) := string -> A.\n\n(** Intuitively, a total map over an element type [A] is just a\n    function that can be used to look up [string]s, yielding [A]s. *)\n\n(** The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any string. *)\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : string) (v : A) :=\n  fun x' => if beq_string x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming:\n    [t_update] takes a _function_ [m] and yields a new function \n    [fun x' => ...] that behaves like the desired map. *)\n\n(** For example, we can build a map taking [string]s to [bool]s, where\n    [\"foo\"] and [\"bar\"] are mapped to [true] and every other key is\n    mapped to [false], like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) \"foo\" true)\n           \"bar\" true.\n\n(** Next, let's introduce some new notations to facilitate working\n    with maps. *)\n\n(** First, we will use the following notation to create an empty total map \n    with a default value. *)\nNotation \"{ --> d }\" := (t_empty d) (at level 0).\n\n(** We then introduce a convenient notation for extending an existing\n    map with some bindings. *)\n\n(** (The definition of the notation is a bit ugly, but because the\n    notation mechanism of Coq is not very well suited for recursive\n    notations, it's the best we can do.) *)\n\nNotation \"m '&' { a --> x }\" := \n  (t_update m a x) (at level 20).\nNotation \"m '&' { a --> x ; b --> y }\" := \n  (t_update (m & { a --> x }) b y) (at level 20).\nNotation \"m '&' { a --> x ; b --> y ; c --> z }\" := \n  (t_update (m & { a --> x ; b --> y }) c z) (at level 20).\nNotation \"m '&' { a --> x ; b --> y ; c --> z ; d --> t }\" :=\n    (t_update (m & { a --> x ; b --> y ; c --> z }) d t) (at level 20).\nNotation \"m '&' { a --> x ; b --> y ; c --> z ; d --> t ; e --> u }\" :=\n    (t_update (m & { a --> x ; b --> y ; c --> z ; d --> t }) e u) (at level 20).\nNotation \"m '&' { a --> x ; b --> y ; c --> z ; d --> t ; e --> u ; f --> v }\" :=\n    (t_update (m & { a --> x ; b --> y ; c --> z ; d --> t ; e --> u }) f v) (at level 20).\n\n(** The [examplemap] above can now be defined as follows: *)\n\nDefinition examplemap' :=\n  { --> false } & { \"foo\" --> true ; \"bar\" --> true }.\n\n(** This completes the definition of total maps.  Note that we\n    don't need to define a [find] operation because it is just\n    function application! *)\n\nExample update_example1 : examplemap' \"baz\" = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap' \"foo\" = true.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap' \"quux\" = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap' \"bar\" = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental\n    facts about how they behave. *)\n\n(** Even if you don't work the following exercises, make sure\n    you thoroughly understand the statements of the lemmas! *)\n\n(** (Some of the proofs require the functional extensionality axiom,\n    which is discussed in the [Logic] chapter.) *)\n\n(** **** Exercise: 1 star, optional (t_apply_empty)  *)\n(** First, the empty map returns its default element for all keys: *)\n\nLemma t_apply_empty:  forall (A:Type) (x: string) (v: A), { --> v } x = v.\nProof.\n  intros. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_eq)  *)\n(** Next, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall A (m: total_map A) x v,\n  (m & {x --> v}) x = v.\nProof.\n  intros A m x v. unfold t_update. rewrite <- beq_string_refl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_neq)  *)\n(** On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (X:Type) v x1 x2\n                         (m : total_map X),\n  x1 <> x2 ->\n  (m & {x1 --> v}) x2 = m x2.\nProof.\n  intros X v x1 x2 m H0. unfold t_update. apply beq_string_false_iff in H0.\n  rewrite H0. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_shadow)  *)\n(** If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    m & {x --> v1 ; x --> v2} = m & {x --> v2}.\nProof.\n  intros A m v1 v2 x. unfold t_update. apply functional_extensionality.\n  intros x0. destruct (beq_string x x0) eqn : Hbeq.\n  - reflexivity.\n  - reflexivity. Qed.\n\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n    the reflection idioms introduced in chapter [IndProp].  We begin\n    by proving a fundamental _reflection lemma_ relating the equality\n    proposition on [id]s with the boolean function [beq_id]. *)\n\n(** **** Exercise: 2 stars, optional (beq_stringP)  *)\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma beq_stringP : forall x y, reflect (x = y) (beq_string x y).\nProof.\n  intros x y. destruct (beq_string x y) eqn : Hbeq.\n  - apply beq_string_true_iff in Hbeq. apply ReflectT. apply Hbeq.\n  - apply beq_string_false_iff in Hbeq. apply ReflectF. apply Hbeq. Qed.\n\n(** [] *)\n\n(** Now, given [string]s [x1] and [x2], we can use the [destruct (beq_stringP\n    x1 x2)] to simultaneously perform case analysis on the result of\n    [beq_string x1 x2] and generate hypotheses about the equality (in the\n    sense of [=]) of [x1] and [x2]. *)\n\n(** **** Exercise: 2 stars (t_update_same)  *)\n(** With the example in chapter [IndProp] as a template, use\n    [beq_stringP] to prove the following theorem, which states that if we\n    update a map to assign key [x] the same value as it already has in\n    [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall X x (m : total_map X),\n    m & { x --> m x } = m.\nProof.\n  intros X x m. unfold t_update. apply functional_extensionality.\n  intros x0. destruct (beq_string x x0) eqn : Hbeq.\n  - apply beq_string_true_iff in Hbeq. rewrite Hbeq. reflexivity.\n  - reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (t_update_permute)  *)\n(** Use [beq_stringP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n  m & { x2 --> v2 ; x1 --> v1 }\n  =  m & { x1 --> v1 ; x2 --> v2 }.\nProof.\n  intros X v1 v2 x1 x2 m H0. unfold t_update. apply functional_extensionality.\n  intros x. destruct (beq_string x1 x) eqn : Hbeq1.\n  - destruct (beq_string x2 x) eqn : Hbeq2.\n    + apply beq_string_true_iff in Hbeq1. apply beq_string_true_iff in Hbeq2.\n      rewrite <- Hbeq1 in Hbeq2. contradiction.\n    + reflexivity.\n  - reflexivity. Qed.\n\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A:Type} (m : partial_map A)\n           (x : string) (v : A) :=\n  m & { x --> (Some v) }.\n\n(** We introduce a similar notation for partial maps, using double\n    curly-brackets.  **)\n\nNotation \"m '&' {{ a --> x }}\" := \n  (update m a x) (at level 20).\nNotation \"m '&' {{ a --> x ; b --> y }}\" := \n  (update (m & {{ a --> x }}) b y) (at level 20).\nNotation \"m '&' {{ a --> x ; b --> y ; c --> z }}\" := \n  (update (m & {{ a --> x ; b --> y }}) c z) (at level 20).\nNotation \"m '&' {{ a --> x ; b --> y ; c --> z ; d --> t }}\" :=\n    (update (m & {{ a --> x ; b --> y ; c --> z }}) d t) (at level 20).\nNotation \"m '&' {{ a --> x ; b --> y ; c --> z ; d --> t ; e --> u }}\" :=\n    (update (m & {{ a --> x ; b --> y ; c --> z ; d --> t }}) e u) (at level 20).\nNotation \"m '&' {{ a --> x ; b --> y ; c --> z ; d --> t ; e --> u ; f --> v }}\" :=\n    (update (m & {{ a --> x ; b --> y ; c --> z ; d --> t ; e --> u }}) f v) (at level 20).\n\n(** We now straightforwardly lift all of the basic lemmas about total\n    maps to partial maps.  *)\n\nLemma apply_empty : forall (A: Type) (x: string),  @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall A (m: partial_map A) x v,\n    (m & {{ x --> v }}) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (X:Type) v x1 x2\n                       (m : partial_map X),\n  x2 <> x1 ->\n  (m & {{ x2 --> v }}) x1 = m x1.\nProof.\n  intros X v x1 x2 m H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall A (m: partial_map A) v1 v2 x,\n    m & {{ x --> v1 ; x --> v2 }} = m & {{x --> v2}}.\nProof.\n  intros A m v1 v2 x1. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall X v x (m : partial_map X),\n  m x = Some v ->\n  m & {{x --> v}} = m.\nProof.\n  intros X v x m H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (X:Type) v1 v2 x1 x2\n                           (m : partial_map X),\n  x2 <> x1 ->\n  m & {{x2 --> v2 ; x1 --> v1}}\n  = m & {{x1 --> v1 ; x2 --> v2}}.\nProof.\n  intros X v1 v2 x1 x2 m. unfold update.\n  apply t_update_permute.\nQed.\n\n\n", "meta": {"author": "tonyfloatersu", "repo": "SF-solution", "sha": "63d116cca62f4d8d4515b6ec7cffe8b88adf5a77", "save_path": "github-repos/coq/tonyfloatersu-SF-solution", "path": "github-repos/coq/tonyfloatersu-SF-solution/SF-solution-63d116cca62f4d8d4515b6ec7cffe8b88adf5a77/LogicFoundationSolution/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.8947894625955065, "lm_q1q2_score": 0.7050325311115405}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) : natural := plus lf1 lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj254_coqofml_ocwPHQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7050325295054904}}
{"text": "Require Import Algebra.Groups.Group.\nRequire Import Algebra.Groups.Subgroup.\nRequire Import WildCat.\n\n(** * Kernels of group homomorphisms *)\n\nLocal Open Scope mc_scope.\nLocal Open Scope mc_mult_scope.\n\nDefinition grp_kernel {A B : Group} (f : GroupHomomorphism A B) : NormalSubgroup A.\nProof.\n  snrapply Build_NormalSubgroup.\n  - srapply (Build_Subgroup' (fun x => f x = group_unit)).\n    1: apply grp_homo_unit.\n    intros x y p q; cbn in p, q; cbn.\n    refine (grp_homo_op _ _ _ @ ap011 _ p _ @ _).\n    1: apply grp_homo_inv.\n    rewrite q; apply right_inverse.\n  - intros x y; cbn.\n    rewrite 2 grp_homo_op.\n    rewrite 2 grp_homo_inv.\n    refine (_^-1 oE grp_moveL_M1).\n    refine (_ oE equiv_path_inverse _ _).\n    apply grp_moveR_1M.\n  Defined.\n\n(** ** Corecursion principle for group kernels *)\n\nProposition grp_kernel_corec {A B G : Group} {f : A $-> B} (g : G $-> A)\n            (h : f $o g == grp_homo_const) : G $-> grp_kernel f.\nProof.\n  snrapply Build_GroupHomomorphism.\n  - exact (fun x:G => (g x; h x)).\n  - intros x x'.\n    apply path_sigma_hprop; cbn.\n    apply grp_homo_op.\nDefined.\n\nTheorem equiv_grp_kernel_corec `{Funext} {A B G : Group} {f : A $-> B}\n  : (G $-> grp_kernel f) <~> (exists g : G $-> A, f $o g == grp_homo_const).\nProof.\n  srapply equiv_adjointify.\n  - intro k.\n    srefine (_ $o k; _).\n    1: apply subgroup_incl.\n    intro x; cbn.\n    exact (k x).2.\n  - intros [g p].\n    exact (grp_kernel_corec _ p).\n  - intros [g p].\n    apply path_sigma_hprop; unfold pr1.\n    apply equiv_path_grouphomomorphism; intro; reflexivity.\n  - intro k.\n    apply equiv_path_grouphomomorphism; intro x.\n    apply path_sigma_hprop; reflexivity.\nDefined.\n\n(** ** Characterisation of group embeddings *)\nProposition equiv_kernel_isembedding `{Univalence} {A B : Group} (f : A $-> B)\n  : (grp_kernel f = trivial_subgroup :> Subgroup A) <~> IsEmbedding f.\nProof.\n  refine (_ oE (equiv_path_subgroup' _ _)^-1%equiv).\n  apply equiv_iff_hprop_uncurried.\n  refine (iff_compose _ (isembedding_grouphomomorphism f)); split.\n  - intros E ? ?.\n    by apply E.\n  - intros e a; split.\n    + apply e.\n    + intro p.\n      exact (ap _ p @ grp_homo_unit f).\nDefined.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Algebra/Groups/Kernel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7050036811636886}}
{"text": "From Topology Require Export TopologicalSpaces WeakTopology FilterLimits Compactness.\nFrom Coq Require Import FunctionalExtensionality.\nFrom ZornsLemma Require Import DependentTypeChoice EnsembleProduct FiniteIntersections.\n\nSection product_topology.\n\nVariable A:Type.\nVariable X:forall a:A, TopologicalSpace.\n\nDefinition product_space_point_set : Type :=\n  forall a:A, X a.\nDefinition product_space_proj (a:A) :\n  product_space_point_set -> X a :=\n  fun (x:product_space_point_set) => x a.\n\nDefinition ProductTopology : TopologicalSpace :=\n  WeakTopology product_space_proj.\n\nLemma product_space_proj_continuous: forall a:A,\n  continuous (product_space_proj a) (X:=ProductTopology).\nProof.\napply weak_topology_makes_continuous_funcs.\nQed.\n\nLemma product_net_limit: forall (I:DirectedSet)\n  (x:Net I ProductTopology) (x0:ProductTopology),\n  inhabited (DS_set I) ->\n  (forall a:A, net_limit (fun i:DS_set I => x i a) (x0 a)) ->\n  net_limit x x0.\nProof.\nintros.\nnow apply net_limit_in_projections_impl_net_limit_in_weak_topology.\nQed.\n\nLemma product_filter_limit:\n  forall (F:Filter ProductTopology)\n    (x0:ProductTopology),\n  (forall a:A, filter_limit (filter_direct_image\n                     (product_space_proj a) F) (x0 a)) ->\n  filter_limit F x0.\nProof.\nintros.\nassert (subbasis\n  (weak_topology_subbasis product_space_proj)\n  (X:=ProductTopology)) by\n  apply Build_TopologicalSpace_from_subbasis_subbasis.\nred. intros.\nred. intros U ?.\ndestruct H1.\ndestruct H1 as [U' []].\ncut (In (filter_family F) U').\n- intro.\n  apply filter_upward_closed with U'; trivial.\n- destruct H1.\n  destruct (subbasis_cover _ _ H0 _ _ H3 H1) as\n    [B [? [V [? []]]]].\n  cut (In (filter_family F) (IndexedIntersection V)).\n  + intro.\n    eapply filter_upward_closed;\n      eassumption.\n  + apply filter_finite_indexed_intersection;\n      trivial.\n    intro b.\n    pose proof (H5 b).\n    inversion H8.\n    apply H.\n    constructor.\n    apply open_neighborhood_is_neighborhood.\n    constructor; trivial.\n    destruct H6.\n    pose proof (H6 b).\n    rewrite <- H9 in H11.\n    now destruct H11.\nQed.\n\nTheorem TychonoffProductTheorem:\n  (forall a:A, compact (X a)) -> compact ProductTopology.\nProof.\nintro.\napply ultrafilter_limit_impl_compact.\nintros.\ndestruct (choice_on_dependent_type (fun (a:A) (x:X a) =>\n  filter_limit (filter_direct_image (product_space_proj a) U) x))\n  as [choice_fun].\n- intro.\n  destruct (compact_impl_filter_cluster_point _ (H a)\n    (filter_direct_image (product_space_proj a) U)) as [xa].\n  exists xa.\n  apply ultrafilter_cluster_point_is_limit; trivial.\n  red. intros.\n  now destruct (H0 (inverse_image (product_space_proj a) S));\n    [left | right];\n    constructor;\n    [ | rewrite inverse_image_complement ].\n- exists choice_fun.\n  now apply product_filter_limit.\nQed.\n\nEnd product_topology.\n\nArguments ProductTopology {A}.\nArguments product_space_proj {A} {X}.\n\nLemma product_map_continuous: forall {A:Type}\n  (X:TopologicalSpace) (Y:A->TopologicalSpace)\n  (f:forall a:A, X -> Y a) (x:X),\n  (forall a:A, continuous_at (f a) x) ->\n  continuous_at (fun x:X => (fun a:A => f a x)) x\n    (Y:=ProductTopology Y).\nProof.\nintros.\napply func_preserving_net_limits_is_continuous.\nintros.\napply product_net_limit.\n- destruct (H0 Full_set) as [i].\n  + apply open_full.\n  + constructor.\n  + now exists.\n- intros.\n  now apply continuous_func_preserves_net_limits.\nQed.\n\nSection product_topology2.\n\n(* we provide a version of the product topology on [X] and [Y]\n   whose underlying set is [point_set X * point_set Y], for\n   more convenience as compared with the general definition *)\nVariable X Y:TopologicalSpace.\n\nInductive twoT := | twoT_1 | twoT_2.\nLet prod2_fun (i:twoT) := match i with\n  | twoT_1 => X | twoT_2 => Y end.\nLet prod2 := ProductTopology prod2_fun.\n\nLet prod2_conv1 (p:prod2) : X * Y :=\n  (p twoT_1, p twoT_2).\nLet prod2_conv2 (p : X * Y) : prod2 :=\n  let (x,y):=p in fun i:twoT => match i with\n    | twoT_1 => x | twoT_2 => y\n  end.\n\nLemma prod2_comp1: forall p:prod2,\n  prod2_conv2 (prod2_conv1 p) = p.\nProof.\nintros.\nextensionality i.\nnow destruct i.\nQed.\n\nLemma prod2_comp2: forall p:X * Y,\n  prod2_conv1 (prod2_conv2 p) = p.\nProof.\nnow intros [? ?].\nQed.\n\nLet prod2_proj := fun i:twoT =>\n  match i return (X * Y -> (prod2_fun i)) with\n  | twoT_1 => @fst X Y\n  | twoT_2 => @snd X Y\n  end.\n\nDefinition ProductTopology2 : TopologicalSpace :=\n  WeakTopology prod2_proj.\n\nLemma prod2_conv1_cont: continuous prod2_conv1 (Y:=ProductTopology2).\nProof.\napply pointwise_continuity.\nintros p.\napply func_preserving_net_limits_is_continuous.\nintros.\napply net_limit_in_projections_impl_net_limit_in_weak_topology.\n- destruct (H Full_set).\n  + apply open_full.\n  + constructor.\n  + exact (inhabits x0).\n- destruct a;\n    simpl.\n  + now apply net_limit_in_weak_topology_impl_net_limit_in_projections\n      with (a:=twoT_1) in H.\n  + now apply net_limit_in_weak_topology_impl_net_limit_in_projections\n      with (a:=twoT_2) in H.\nQed.\n\nLemma prod2_conv2_cont: continuous prod2_conv2 (X:=ProductTopology2).\nProof.\napply pointwise_continuity.\ndestruct x as [x y].\napply func_preserving_net_limits_is_continuous.\nintros.\napply net_limit_in_projections_impl_net_limit_in_weak_topology.\n- destruct (H Full_set).\n  + apply open_full.\n  + constructor.\n  + exact (inhabits x1).\n- destruct a.\n  + unfold product_space_proj.\n    simpl.\n    replace (fun i => prod2_conv2 (x0 i) twoT_1) with\n      (fun i => fst (x0 i)).\n    * now apply net_limit_in_weak_topology_impl_net_limit_in_projections\n        with (a:=twoT_1) in H.\n    * extensionality i.\n      now destruct (x0 i).\n  + unfold product_space_proj.\n    simpl.\n    replace (fun i:DS_set I => prod2_conv2 (x0 i) twoT_2) with\n      (fun i:DS_set I => snd (x0 i)).\n    * now apply net_limit_in_weak_topology_impl_net_limit_in_projections\n        with (a:=twoT_2) in H.\n    * extensionality i.\n      now destruct (x0 i).\nQed.\n\nLemma product2_fst_continuous:\n  continuous (@fst X Y)\n    (X:=ProductTopology2).\nProof.\nexact (weak_topology_makes_continuous_funcs\n  _ _ _ prod2_proj twoT_1).\nQed.\n\nLemma product2_snd_continuous:\n  continuous (@snd X Y)\n    (X:=ProductTopology2).\nProof.\nexact (weak_topology_makes_continuous_funcs\n  _ _ _ prod2_proj twoT_2).\nQed.\n\nLemma product2_map_continuous_at: forall (W:TopologicalSpace)\n  (f:W -> X) (g:W -> Y) (w:W),\n  continuous_at f w -> continuous_at g w ->\n  continuous_at (fun w:W => (f w, g w)) w (Y:=ProductTopology2).\nProof.\nintros.\nreplace (fun w:W => (f w, g w)) with\n  (fun w:W => prod2_conv1\n             (fun i:twoT =>\n                match i with\n                | twoT_1 => f w\n                | twoT_2 => g w end)).\n- apply (@continuous_composition_at W prod2 ProductTopology2\n    prod2_conv1\n    (fun w:W =>\n       fun i:twoT => match i with\n           | twoT_1 => f w | twoT_2 => g w end)).\n  + apply continuous_func_continuous_everywhere.\n    apply prod2_conv1_cont.\n  + apply product_map_continuous.\n    now destruct a.\n- now extensionality w0.\nQed.\n\nCorollary product2_map_continuous: forall (W:TopologicalSpace)\n  (f:W -> X) (g:W -> Y),\n  continuous f -> continuous g ->\n  continuous (fun w:W => (f w, g w))\n  (Y:=ProductTopology2).\nProof.\n  intros.\n  apply pointwise_continuity.\n  intros.\n  apply product2_map_continuous_at.\n  - apply continuous_func_continuous_everywhere.\n    assumption.\n  - apply continuous_func_continuous_everywhere.\n    assumption.\nQed.\n\nInductive ProductTopology2_basis :\n  Family ProductTopology2 :=\n| intro_product2_basis_elt:\n  forall (U:Ensemble X)\n         (V:Ensemble Y),\n  open U -> open V ->\n  In ProductTopology2_basis (EnsembleProduct U V).\n\nLemma ProductTopology2_basis_is_basis:\n  open_basis ProductTopology2_basis.\nProof.\nassert (open_basis (finite_intersections (weak_topology_subbasis prod2_proj))\n  (X:=ProductTopology2)) by apply\n  Build_TopologicalSpace_from_open_basis_basis.\napply eq_ind with (1:=H).\napply Extensionality_Ensembles; split; red; intros U ?.\n- induction H0.\n  + rewrite <- EnsembleProduct_Full.\n    constructor; apply open_full.\n  + destruct H0.\n    destruct a.\n    * simpl.\n      rewrite inverse_image_fst.\n      constructor; auto with topology.\n    * simpl.\n      rewrite inverse_image_snd.\n      constructor; auto with topology.\n  + destruct IHfinite_intersections as [U1 V1].\n    destruct IHfinite_intersections0 as [U2 V2].\n    rewrite EnsembleProduct_Intersection.\n    constructor; auto with topology.\n- destruct H0.\n  rewrite EnsembleProduct_proj.\n  constructor 3.\n  + constructor.\n    replace (@fst X Y) with (prod2_proj twoT_1); auto.\n    constructor. assumption.\n  + constructor.\n    replace (@snd X Y) with (prod2_proj twoT_2); auto.\n    constructor. assumption.\nQed.\n\nEnd product_topology2.\n\nSection two_arg_convenience_results.\n\nVariable X Y Z:TopologicalSpace.\nVariable f:X -> Y -> Z.\n\nDefinition continuous_2arg :=\n  continuous (fun p:X * Y =>\n                f (fst p) (snd p))\n  (X:=ProductTopology2 X Y).\nDefinition continuous_at_2arg (x:X) (y:Y) :=\n  continuous_at (fun p:X * Y =>\n                 f (fst p) (snd p))  (x, y)\n  (X:=ProductTopology2 X Y).\n\nLemma continuous_2arg_func_continuous_everywhere:\n  continuous_2arg -> forall (x:X) (y:Y),\n                       continuous_at_2arg x y.\nProof.\nintros.\nnow apply continuous_func_continuous_everywhere.\nQed.\n\nLemma pointwise_continuity_2arg:\n  (forall (x:X) (y:Y),\n   continuous_at_2arg x y) -> continuous_2arg.\nProof.\nintros.\napply pointwise_continuity.\nintros [? ?].\napply H.\nQed.\n\nEnd two_arg_convenience_results.\n\nArguments continuous_2arg {X} {Y} {Z}.\nArguments continuous_at_2arg {X} {Y} {Z}.\n\nLemma continuous_composition_at_2arg:\n  forall (W X Y Z:TopologicalSpace)\n    (f:X -> Y -> Z) (g:W -> X) (h:W -> Y)\n    (w:W),\n  continuous_at_2arg f (g w) (h w) ->\n  continuous_at g w -> continuous_at h w ->\n  continuous_at (fun w:W => f (g w) (h w)) w.\nProof.\nintros.\nred in H.\napply (continuous_composition_at\n  (fun p:ProductTopology2 X Y =>\n      f (fst p) (snd p))\n  (fun w:W => (g w, h w))); trivial.\nnow apply product2_map_continuous_at.\nQed.\n\nCorollary continuous_composition_2arg:\n  forall {U X Y Z : TopologicalSpace} (f : U -> X) (g : U -> Y) (h : X -> Y -> Z),\n    continuous f -> continuous g -> continuous_2arg h ->\n    continuous (fun p => h (f p) (g p)).\nProof.\n  intros.\n  apply pointwise_continuity.\n  intros.\n  apply continuous_composition_at_2arg.\n  - apply continuous_2arg_func_continuous_everywhere.\n    assumption.\n  - apply continuous_func_continuous_everywhere.\n    assumption.\n  - apply continuous_func_continuous_everywhere.\n    assumption.\nQed.\n\nLemma EnsembleProduct_open {X Y : TopologicalSpace} (U : Ensemble X) (V : Ensemble Y) :\nopen U -> open V -> @open (@ProductTopology2 X Y) (EnsembleProduct U V).\nProof.\nintros.\napply ProductTopology2_basis_is_basis.\nconstructor; assumption.\nQed.\n\nLemma Hausdorff_ProductTopology2 {X Y : TopologicalSpace} :\n  Hausdorff X -> Hausdorff Y ->\n  Hausdorff (ProductTopology2 X Y).\nProof.\n  intros HX HY [x0 y0] [x1 y1] Hxy.\n  specialize (HX x0 x1).\n  specialize (HY y0 y1).\n  (* Is there some \"symmetry\" that can be used, so the proof doesn't\n     contain redundant parts? *)\n  destruct (classic (x0 = x1)) as [|Hx].\n  { subst.\n    assert (y0 <> y1) as Hy by congruence.\n    clear Hxy.\n    specialize (HY Hy) as [U [V [HU [HV [HU0 [HV0 HUV]]]]]].\n    exists (EnsembleProduct Full_set U), (EnsembleProduct Full_set V).\n    repeat split; auto using EnsembleProduct_open, open_full.\n    simpl.\n    rewrite EnsembleProduct_Intersection.\n    rewrite Powerset_facts.Intersection_Full_set.\n    rewrite HUV.\n    apply EnsembleProduct_Empty_r.\n  }\n  clear Hxy.\n  specialize (HX Hx) as [U [V [HU [HV [HU0 [HV0 HUV]]]]]].\n  exists (EnsembleProduct U Full_set), (EnsembleProduct V Full_set).\n  repeat split; auto using EnsembleProduct_open, open_full.\n  simpl.\n  rewrite EnsembleProduct_Intersection.\n  rewrite Powerset_facts.Intersection_Full_set.\n  rewrite HUV.\n  apply EnsembleProduct_Empty_l.\nQed.\n", "meta": {"author": "coq-community", "repo": "topology", "sha": "f784257d0b9c316601440e4f02256bd6068e4f94", "save_path": "github-repos/coq/coq-community-topology", "path": "github-repos/coq/coq-community-topology/topology-f784257d0b9c316601440e4f02256bd6068e4f94/theories/Topology/ProductTopology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7050036697254614}}
{"text": "(*************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(*************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(*************************************************************)\n\nRequire Import List Arith Lia.\n\nFrom Undecidability.Shared.Libs.DLW\n  Require Import utils subcode sss.\n\nFrom Undecidability.MinskyMachines Require Export MM.\nFrom Undecidability.MinskyMachines.MMenv Require Import env. \n\nSet Implicit Arguments.\n\nSet Default Proof Using \"Type\".\n\n(* * Minsky Machines\n\n    A Minsky machine has n registers and there are just two instructions\n \n    1/ INC x   : increment register x by 1\n    2/ DEC x k : decrement register x by 1 if x > 0\n                 or jump to k if x = 0\n\n  *)\n\n(* Semantics for MM based on environments *)\n\nSection Minsky_Machine_env_based.\n\n  Variable (X : Set) (X_eq_dec : eqdec X).\n\n  Definition mm_state := (nat*env X nat)%type.\n\n  Local Notation \" e ⇢ x \" := (@get_env _ _ e x).\n  Local Notation \" e ⦃  x ⇠ v ⦄ \" := (@set_env _ _ X_eq_dec e x v).\n\n  (* Minsky machine small step semantics *)\n\n  Inductive mm_sss_env : mm_instr X -> mm_state -> mm_state -> Prop :=\n    | in_mm_sss_env_inc   : forall i x v,                   INC x  // (i,v) -1> (1+i,v⦃x⇠S(v⇢x)⦄)\n    | in_mm_sss_env_dec_0 : forall i x k v,   v⇢x = O   -> DEC x k // (i,v) -1> (k,v)\n    | in_mm_sss_env_dec_1 : forall i x k v u, v⇢x = S u -> DEC x k // (i,v) -1> (1+i,v⦃x⇠u⦄)\n  where \"i // s -1> t\" := (mm_sss_env i s t).\n\n  Fact mm_sss_env_fun i s t1 t2 : i // s -1> t1 -> i // s -1> t2 -> t1 = t2.\n  Proof.\n    intros []; subst.\n    inversion 1; subst; auto.\n    inversion 1; subst; auto.\n    rewrite H in H6; discriminate.\n    inversion 1; subst; auto.\n    rewrite H in H6; discriminate.\n    rewrite H in H6; inversion H6; subst; auto.\n  Qed.\n  \n  Fact mm_sss_env_total ii s : { t | ii // s -1> t }.\n  Proof.\n    destruct s as (i,v).\n    destruct ii as [ x | x j ]; [ | case_eq (v⇢x); [ | intros k ]; intros E ].\n    * exists (1+i,v⦃x⇠S(v⇢x)⦄); constructor.\n    * exists (j,v); constructor; auto.\n    * exists (1+i,v⦃x⇠k⦄); constructor; auto.\n  Qed.\n  \n  Fact mm_sss_env_INC_inv x i v j w : INC x // (i,v) -1> (j,w) -> j=1+i /\\ w = v⦃x⇠S(v⇢x)⦄.\n  Proof. inversion 1; subst; auto. Qed.\n  \n  Fact mm_sss_env_DEC0_inv x k i v j w : v⇢x = O -> DEC x k // (i,v) -1> (j,w) -> j = k /\\ w = v.\n  Proof. \n    intros H; inversion 1; subst; auto; rewrite H in H2; try discriminate.\n  Qed.\n  \n  Fact mm_sss_env_DEC1_inv x k u i v j w : v⇢x = S u -> DEC x k // (i,v) -1> (j,w) -> j=1+i /\\ w = v⦃x⇠u⦄.\n  Proof. \n    intros H; inversion 1; subst; auto; rewrite H in H2; try discriminate.\n    inversion H2; subst; auto.\n  Qed.\n\n  Notation \"P // s -[ k ]-> t\" := (sss_steps mm_sss_env P k s t).\n  Notation \"P // s -+> t\" := (sss_progress mm_sss_env P s t).\n  Notation \"P // s ->> t\" := (sss_compute mm_sss_env P s t).\n  \n  Fact mm_env_progress_INC P i x v st :\n         (i,INC x::nil) <sc P\n      -> P // (1+i,v⦃x⇠S(v⇢x)⦄) ->> st\n      -> P // (i,v) -+> st.\n  Proof.\n    intros H1 H2.\n    apply sss_progress_compute_trans with (2 := H2).\n    apply subcode_sss_progress with (1 := H1).\n    exists 1; split; auto; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; lia.\n    constructor; auto.\n  Qed.\n  \n  Corollary mm_env_compute_INC P i x v st : \n         (i,INC x::nil) <sc P \n      -> P // (1+i,v⦃x⇠S(v⇢x)⦄) ->> st \n      -> P // (i,v) ->> st.\n  Proof. intros; apply sss_progress_compute; eapply mm_env_progress_INC; eauto. Qed.\n  \n  Fact mm_env_progress_DEC_0 P i x k v st :\n         (i,DEC x k::nil) <sc P\n      -> v⇢x = O \n      -> P // (k,v) ->> st\n      -> P // (i,v) -+> st.\n  Proof.\n    intros H1 H2 H3.\n    apply sss_progress_compute_trans with (2 := H3).\n    apply subcode_sss_progress with (1 := H1).\n    exists 1; split; auto; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; lia.\n    constructor; auto.\n  Qed.\n  \n  Corollary mm_env_compute_DEC_0 P i x k v st : \n         (i,DEC x k::nil) <sc P \n      -> v⇢x = O \n      -> P // (k,v) ->> st \n      -> P // (i,v) ->> st.\n  Proof. intros; apply sss_progress_compute; eapply mm_env_progress_DEC_0; eauto. Qed.\n  \n  Fact mm_env_progress_DEC_S P i x k v u st :\n         (i,DEC x k::nil) <sc P\n      -> v⇢x = S u \n      -> P // (1+i,v⦃x⇠u⦄) ->> st\n      -> P // (i,v) -+> st.\n  Proof.\n    intros H1 H2 H3.\n    apply sss_progress_compute_trans with (2 := H3).\n    apply subcode_sss_progress with (1 := H1).\n    exists 1; split; auto; apply sss_steps_1.\n    apply in_sss_step with (l := nil).\n    simpl; lia.\n    constructor; auto.\n  Qed.\n  \n  Corollary mm_env_compute_DEC_S P i x k v u st : \n           (i,DEC x k::nil) <sc P \n        -> v⇢x = S u \n        -> P // (1+i,v⦃x⇠u⦄) ->> st \n        -> P // (i,v) ->> st.\n  Proof. intros; apply sss_progress_compute; eapply mm_env_progress_DEC_S; eauto. Qed.\n  \n  Fact mm_env_steps_INC_inv k P i x v st :\n         (i,INC x::nil) <sc P\n      -> k <> 0\n      -> P // (i,v) -[k]-> st\n      -> exists k', k' < k /\\ P // (1+i,v⦃x⇠S(v⇢x)⦄) -[k']-> st.\n  Proof.\n    intros H1 H2 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (? & ?) | (k' & st2 & ? & H4 & H5) ]; subst; auto.\n    destruct H2; auto.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    exists k'; split.\n    lia.\n    inversion H4; subst; auto.\n  Qed.\n  \n  Fact mm_env_steps_DEC_0_inv k P i x p v st :\n         (i,DEC x p::nil) <sc P\n      -> k <> 0\n      -> v⇢x = 0\n      -> P // (i,v) -[k]-> st\n      -> exists k', k' < k /\\ P // (p,v) -[k']-> st.\n  Proof.\n    intros H1 H2 H3 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (? & ?) | (k' & st2 & ? & H4 & H5) ]; subst; auto.\n    destruct H2; auto.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    exists k'; split.\n    lia.\n    inversion H4; subst; auto.\n    rewrite H3 in H9; discriminate.\n  Qed.\n  \n  Fact mm_env_steps_DEC_1_inv k P i x p v u st :\n         (i,DEC x p::nil) <sc P\n      -> k <> 0\n      -> v⇢x = S u\n      -> P // (i,v) -[k]-> st\n      -> exists k', k' < k /\\ P // (1+i,v⦃x⇠u⦄) -[k']-> st.\n  Proof.\n    intros H1 H2 H3 H4.\n    apply sss_steps_inv in H4.\n    destruct H4 as [ (? & ?) | (k' & st2 & ? & H4 & H5) ]; subst; auto.\n    destruct H2; auto.\n    apply sss_step_subcode_inv with (1 := H1) in H4.\n    exists k'; split.\n    lia.\n    inversion H4; subst; auto; rewrite H3 in H9.\n    discriminate.\n    inversion H9; subst; auto.\n  Qed.\n  \nEnd Minsky_Machine_env_based.\n\nLocal Notation \"P // s -[ k ]-> t\" := (sss_steps (@mm_sss_env _ _) P k s t).\nLocal Notation \"P // s -+> t\" := (sss_progress (@mm_sss_env _ _) P s t).\nLocal Notation \"P // s ->> t\" := (sss_compute (@mm_sss_env _ _) P s t).\n\nTactic Notation \"mm\" \"env\" \"INC\" \"with\" uconstr(a) := \n  match goal with\n    | |- _ // _ -+> _ => apply mm_env_progress_INC with (x := a)\n    | |- _ // _ ->> _ => apply mm_env_compute_INC with (x := a)\n  end; auto.\n\nTactic Notation \"mm\" \"env\" \"DEC\" \"zero\" \"with\" uconstr(a) uconstr(b) := \n  match goal with\n    | |- _ // _ -+> _ => apply mm_env_progress_DEC_0 with (x := a) (k := b)\n    | |- _ // _ ->> _ => apply mm_env_compute_DEC_0 with (x := a) (k := b)\n  end; auto.\n\nTactic Notation \"mm\" \"env\" \"DEC\" \"S\" \"with\" uconstr(a) uconstr(b) uconstr(c) := \n  match goal with\n    | |- _ // _ -+> _ => apply mm_env_progress_DEC_S with (x := a) (k := b) (u := c)\n    | |- _ // _ ->> _ => apply mm_env_compute_DEC_S with (x := a) (k := b) (u := c)\n  end; auto.\n\nTactic Notation \"mm\" \"env\" \"stop\" := exists 0; apply sss_steps_0; auto.\n\n(* The Halting problem for MM, for linear logic encoding, we restrict\n   to a very specific halting problem. Starting from (1,v), does the\n   MM halt at state (0,vec_zero) *)\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/MinskyMachines/MMenv/mme_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7050036675249043}}
{"text": "Require Import Undecidability.FOL.Syntax.Facts Undecidability.FOL.Syntax.Theories.\nRequire Export Undecidability.FOL.Semantics.Tarski.FragmentCore.\nFrom Undecidability Require Import Shared.ListAutomation.\nImport ListAutomationNotations.\nRequire Import Vector Lia.\n\n\nLocal Set Implicit Arguments.\nLocal Unset Strict Implicit.\n\nSet Default Proof Using \"Type\".\n\nLocal Notation vec := Vector.t.\n\n\n(* Tarski Semantics ***)\n\n\nSection Tarski.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  (* Semantic notions *)\n  \n  \n  Section Substs.\n    \n    Variable D : Type.\n    Variable I : interp D.\n        \n    Lemma eval_ext rho xi t :\n      (forall x, rho x = xi x) -> eval rho t = eval xi t.\n    Proof.\n      intros H. induction t; cbn.\n      - now apply H.\n      - f_equal. apply map_ext_in. now apply IH.\n    Qed.\n\n    Lemma eval_comp rho xi t :\n      eval rho (subst_term xi t) = eval (xi >> eval rho) t.\n    Proof.\n      induction t; cbn.\n      - reflexivity.\n      - f_equal. rewrite map_map. apply map_ext_in, IH.\n    Qed.\n\n    Lemma sat_ext {ff : falsity_flag} rho xi phi :\n      (forall x, rho x = xi x) -> rho ⊨ phi <-> xi ⊨ phi.\n    Proof.\n      induction phi  as [ | b P v | | ] in rho, xi |- *; cbn; intros H.\n      - reflexivity.\n      - erewrite map_ext; try reflexivity. intros t. now apply eval_ext.\n      - specialize (IHphi1 rho xi). specialize (IHphi2 rho xi). destruct b0; intuition.\n      - destruct q.\n        + split; intros H' d; eapply IHphi; try apply (H' d). 1,2: intros []; cbn; intuition.\n    Qed.\n\n    Lemma sat_ext' {ff : falsity_flag} rho xi phi :\n      (forall x, rho x = xi x) -> rho ⊨ phi -> xi ⊨ phi.\n    Proof.\n      intros Hext H. rewrite sat_ext. exact H.\n      intros x. now rewrite (Hext x).\n    Qed.\n\n    Lemma sat_comp {ff : falsity_flag} rho xi phi :\n      rho ⊨ (subst_form xi phi) <-> (xi >> eval rho) ⊨ phi.\n    Proof.\n      induction phi as [ | b P v | | ] in rho, xi |- *; cbn.\n      - reflexivity.\n      - erewrite map_map, map_ext; try reflexivity. intros t. apply eval_comp.\n      - specialize (IHphi1 rho xi). specialize (IHphi2 rho xi). destruct b0; intuition.\n      - destruct q.\n        + setoid_rewrite IHphi. split; intros H d; eapply sat_ext. 2, 4: apply (H d).\n          all: intros []; cbn; trivial; now setoid_rewrite eval_comp.\n    Qed.\n\n    Lemma sat_subst {ff : falsity_flag} rho sigma phi :\n      (forall x, eval rho (sigma x) = rho x) -> rho ⊨ phi <-> rho ⊨ (subst_form sigma phi).\n    Proof.\n      intros H. rewrite sat_comp. apply sat_ext. intros x. now rewrite <- H.\n    Qed.\n\n    Lemma sat_single {ff : falsity_flag} (rho : nat -> D) (Phi : form) (t : term) :\n      (eval rho t .: rho) ⊨ Phi <-> rho ⊨ subst_form (t..) Phi.\n    Proof.\n      rewrite sat_comp. apply sat_ext. now intros [].\n    Qed.\n\n    Lemma impl_sat {ff : falsity_flag} A rho phi :\n      sat rho (A ==> phi) <-> ((forall psi, psi el A -> sat rho psi) -> sat rho phi).\n    Proof.\n      induction A; cbn; firstorder congruence.\n    Qed.\n\n    Lemma impl_sat' {ff : falsity_flag} A rho phi :\n      sat rho (A ==> phi) -> ((forall psi, psi el A -> sat rho psi) -> sat rho phi).\n    Proof.\n      eapply impl_sat.\n    Qed.\n\n    Lemma bounded_eval_t n t sigma tau :\n      (forall k, n > k -> sigma k = tau k) -> bounded_t n t -> eval sigma t = eval tau t.\n    Proof.\n      intros H. induction 1; cbn; auto.\n      f_equal. now apply Vector.map_ext_in.\n    Qed.\n    \n    Lemma bound_ext {ff : falsity_flag} N phi rho sigma :\n      bounded N phi -> (forall n, n < N -> rho n = sigma n) -> (rho ⊨ phi <-> sigma ⊨ phi).\n    Proof.\n      induction 1 in sigma, rho |- *; cbn; intros HN; try tauto.\n      - enough (map (eval rho) v = map (eval sigma) v) as E. now setoid_rewrite E.\n        apply Vector.map_ext_in. intros t Ht.\n        eapply bounded_eval_t; try apply HN. now apply H.\n      - destruct binop; now rewrite (IHbounded1 rho sigma), (IHbounded2 rho sigma).\n      - destruct quantop.\n        + split; intros Hd d; eapply IHbounded.\n          all : try apply (Hd d); intros [] Hk; cbn; auto.\n          symmetry. all: apply HN; lia.\n    Qed. \n\n    Corollary sat_closed {ff : falsity_flag} rho sigma phi :\n      bounded 0 phi -> rho ⊨ phi <-> sigma ⊨ phi.\n    Proof.\n      intros H. eapply bound_ext. apply H. lia.\n    Qed.\n\n    Lemma bounded_S_forall {ff : falsity_flag} N phi :\n      bounded (S N) phi <-> bounded N (∀ phi).\n    Proof.\n      split; intros H.\n      - now constructor.\n      - inversion H. apply Eqdep_dec.inj_pair2_eq_dec in H4 as ->; trivial.\n        unfold Dec.dec. decide equality.\n    Qed.\n\n    Definition forall_times {ff : falsity_flag} n (phi : form) := iter (fun psi => ∀ psi) n phi.\n\n  End Substs.\n\nEnd Tarski.\n\n\n\n(* Trivial Model *)\n\nSection TM.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Instance TM : interp unit :=\n    {| i_func := fun _ _ => tt; i_atom := fun _ _ => True; |}.\n\n  Fact TM_sat (rho : nat -> unit) (phi : form falsity_off) :\n    rho ⊨ phi.\n  Proof.\n    revert rho. remember falsity_off as ff. induction phi; cbn; trivial.\n    - discriminate.\n    - destruct b0; auto.\n    - destruct q; firstorder.\n  Qed.\n\n  Fact TM_sat_decidable {ff} (rho : nat -> unit) (phi : form ff) :\n    rho ⊨ phi \\/ ~(rho ⊨ phi).\n  Proof.\n    revert rho. induction phi; cbn; intros rho; eauto.\n    - destruct b0. destruct (IHphi1 rho), (IHphi2 rho); tauto.\n    - destruct q. destruct (IHphi (tt .: rho)).\n      + left; now intros [].\n      + right; intros Hcc. apply H, Hcc.\n  Qed.\n\nEnd TM.\n\nSection FlagsTransport.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n  Context {ff1 : falsity_flag}.\n\n  Section Bottom.\n    Variable D : Type.\n    Variable I : interp D. \n    Context (default : @form _ _ _ ff1).\n\n    Lemma sat_to_falsity_compat {ff2} rho (phi : @form _ _ _ ff2) : \n      (sat rho default -> False)\n      -> sat rho phi <-> sat rho (phi[default /⊥]).\n    Proof.\n      induction phi as [|t1 t2|ff [] phi IHphi psi IHpsi|ff [] phi IHphi] in rho,default|-*; intros Hdefault; split.\n      - intros [].\n      - apply Hdefault.\n      - intros H; apply H.\n      - intros H; apply H.\n      - intros H H1. cbn in H. apply IHpsi. 1:easy. apply H. now eapply IHphi, H1.\n      - intros H H1. cbn in H. apply IHpsi with default. 1:easy. apply H. now apply IHphi.\n      - intros H d. apply IHphi. 2: apply H. intros Hd. apply Hdefault.\n        eapply sat_comp in Hd. eapply sat_ext in Hd. 1: apply Hd.\n        now intros [|x].\n      - intros H d. apply IHphi with (default [↑]). 2: apply H. intros Hd. apply Hdefault.\n        eapply sat_comp in Hd. eapply sat_ext in Hd. 1: apply Hd.\n        now intros [|x].\n    Qed.\n  End Bottom.\n  Section Atoms.\n\n    Context {Σ_preds2 : preds_signature}.\n    Context (s : forall (P : Σ_preds), Vector.t (@term Σ_funcs) (ar_preds P) -> (@form Σ_funcs Σ_preds2 _ _)).\n    Context (Hresp : atom_subst_respects s).\n\n    Definition rho_from_vec {A} n (v : Vector.t A n) d : env A := fun m => match Compare_dec.lt_dec m n with\n      left Hl => Vector.nth v (Fin.of_nat_lt Hl)\n    | right _ => d end.\n\n    Lemma rho_from_vec_map {A B} {n} (f : B -> A) (t : Vector.t B n) (d2 : A) (d:B):\n     f d = d2 ->\n     forall k, rho_from_vec (map f t) d2 k = f (rho_from_vec t d k).\n    Proof.\n      intros H k. unfold rho_from_vec. destruct (Compare_dec.lt_dec k n) as [Hl|Hr].\n      - erewrite nth_map. 2:reflexivity. easy.\n      - easy.\n    Qed.\n\n    Definition tabulate_vars n : Vector.t term n := Vectors.tabulate (fun p => $(proj1_sig (Fin.to_nat p))).\n\n    Lemma semantic_lifting_correct n t tt : \n      map (subst_term (rho_from_vec t tt)) (tabulate_vars n) = t.\n    Proof.\n      apply Vectors.eq_nth_iff'. intros i.\n      erewrite nth_map. 2:reflexivity.\n      unfold tabulate_vars. rewrite Vectors.nth_tabulate. cbn.\n      unfold rho_from_vec. destruct (Fin.to_nat i) as [k Hk] eqn:Heq. cbn.\n      destruct Compare_dec.lt_dec; try lia. f_equal.\n      erewrite Fin.of_nat_ext.\n      rewrite <- Fin.to_nat_of_nat in Heq.\n      apply Fin.to_nat_inj. rewrite <- Heq. easy.\n    Qed.\n\n    Section ConstructInterp.\n      Variable D : Type.\n      (* Crucially, we need an interpretation for the formulas s maps _to_ *)\n      Variable I : @interp Σ_funcs Σ_preds2 D. \n      Definition lift_s_semantically (d:D) (P : Σ_preds) (v : Vector.t D (ar_preds P)) : Prop\n        := sat (rho_from_vec v d) (s (tabulate_vars (ar_preds P))).\n\n      (* To construct an interpretation for the formulas we are mapping _from_ *)\n      Definition interp_s (d:D) : @interp Σ_funcs Σ_preds D := {|\n        i_func := @i_func _ _ D I;\n        i_atom := lift_s_semantically d\n      |}.\n\n      Lemma sat_atom_subst_compat rho phi n :\n        sat rho (phi [s/atom]) <-> @sat _ _ _ (interp_s (rho n)) _ rho phi.\n      Proof using Hresp.\n        unfold interp_s, lift_s_semantically. revert rho n.\n        induction phi as [|t1 t2|ff [] phi IHphi psi IHpsi|ff [] phi IHphi]; split.\n        - intros H; apply H.\n        - intros H; apply H.\n        - cbn; intros H.\n          eapply sat_ext with (((rho_from_vec t $n) >> eval rho)).\n          1: intros x; unfold funcomp. now apply rho_from_vec_map.\n          rewrite <- sat_comp. rewrite Hresp. now rewrite semantic_lifting_correct.\n        - cbn; intros H. \n          eapply (@sat_ext _ _ _ _ _ (((rho_from_vec t $n) >> eval rho))) in H.\n          2: intros x; unfold funcomp; symmetry; now apply rho_from_vec_map.\n          rewrite <- sat_comp in H. rewrite Hresp in H. now rewrite semantic_lifting_correct in H.\n        - cbn; intros H1 Hphi. apply IHpsi. 1:easy. apply H1. apply IHphi with n. 1:easy. apply Hphi.\n        - cbn; intros H1 Hphi. apply IHpsi with n. 1:easy. apply H1, IHphi. 1:easy. apply Hphi.\n        - cbn; intros H1 d. apply (IHphi s Hresp (d.:rho) (S n)). apply H1.\n        - cbn; intros H1 d. apply (IHphi s Hresp (d.:rho) (S n)). apply H1.\n      Qed.\n\n    End ConstructInterp.\n\n    Lemma valid_atom_subst_compat phi :\n      valid phi -> valid phi [s/atom].\n    Proof using Hresp.\n      intros H D I rho. unshelve apply <- sat_atom_subst_compat. 1:exact 0. apply H.\n    Qed.\n\n    Lemma satis_atom_subst_compat phi :\n      satis phi[s/atom] -> satis phi .\n    Proof using Hresp.\n      intros (D&I&rho&H). unshelve eapply sat_atom_subst_compat in H. 1:exact 0. do 3 eexists. apply H.\n    Qed.\n\n  End Atoms.\n\nEnd FlagsTransport.\n\nSection Bottom.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Variable D : Type.\n  Variable I : interp D.\n\n  Definition interp_bot (F_P : Prop) (i : @interp Σ_funcs Σ_preds D) : @interp Σ_funcs (@Σ_preds_bot Σ_preds) D := {|\n    i_func := @i_func _ _ D i;\n    i_atom := fun (P : (@preds (@Σ_preds_bot Σ_preds))) => match P with inl _ => fun v => F_P | inr P => fun v => @i_atom _ _ D i P v end\n  |}.\n\n  Definition sat_bot {ff : falsity_flag} (F_P : Prop) (rho : env D) (phi : form) : Prop \n    := @sat _ Σ_preds_bot D (interp_bot F_P I) falsity_off rho (falsity_to_pred phi).\n\n  Lemma sat_bot_False {ff:falsity_flag} rho phi : sat_bot False rho phi <-> sat rho phi.\n  Proof.\n    induction phi in rho|-*.\n    - easy.\n    - easy.\n    - destruct b0. unfold sat_bot, falsity_to_pred in *. cbn.\n      split; intros H H1 %IHphi1; apply IHphi2; apply H, H1.\n    - destruct q. unfold sat_bot, falsity_to_pred in *. cbn.\n      split; intros H d; apply IHphi, H.\n  Qed.\n\nEnd Bottom.\n\nArguments sat_bot {_} {_} {_} {_} {_} _ _ _.\n\nSection BottomDef.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Context {ff : falsity_flag}.\n\n  Definition exploding D (M : interp D) (F_P:Prop) := forall rho phi, sat_bot F_P rho (⊥ → phi).\n  Arguments exploding _ _ _ : clear implicits.\n  Definition valid_exploding_ctx A phi :=\n    forall D (M : interp D) F_P rho, exploding D M F_P -> (forall psi, psi el A -> sat_bot F_P rho psi) -> sat_bot F_P rho phi.\n\n  Definition valid_exploding_theory (T:theory) phi := \n    forall D (M : interp D) F_P rho, exploding D M F_P ->  (forall psi, T psi -> sat_bot F_P rho psi) -> sat_bot F_P rho phi.\n\n  Definition valid_exploding phi :=\n    forall D (M : interp D) F_P rho, exploding D M F_P -> sat_bot F_P rho phi.\n\n  Definition satis_exploding phi :=\n    exists D (M : interp D) F_P rho, exploding D M F_P /\\ sat_bot F_P rho phi.\n\nEnd BottomDef.\n\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/FOL/Semantics/Tarski/FragmentFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7050036611409534}}
{"text": "(* infotheo: information theory and error-correcting codes in Coq             *)\n(* Copyright (C) 2020 infotheo authors, license: LGPL-2.1-or-later            *)\nFrom mathcomp Require Import all_ssreflect ssralg fingroup finalg matrix.\nRequire Import Reals.\nFrom mathcomp Require Import Rstruct.\nRequire Import ssrR Reals_ext ssr_ext ssralg_ext logb ln_facts Rbigop num_occ.\nRequire Import fdist entropy types jtypes divergence conditional_divergence.\nRequire Import error_exponent channel_code channel success_decode_bound.\n\n(******************************************************************************)\n(*                 Channel coding theorem (converse part)                     *)\n(*                                                                            *)\n(* main theorem: channel_coding_converse                                      *)\n(*                                                                            *)\n(* For details, see Reynald Affeldt, Manabu Hagiwara, and Jonas Sénizergues.  *)\n(* Formalization of Shannon's theorems. Journal of Automated Reasoning,       *)\n(* 53(1):63--103, 2014                                                        *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope channel_code_scope.\nLocal Open Scope channel_scope.\nLocal Open Scope entropy_scope.\nLocal Open Scope tuple_ext_scope.\nLocal Open Scope reals_ext_scope.\nLocal Open Scope proba_scope.\nLocal Open Scope types_scope.\nLocal Open Scope divergence_scope.\nLocal Open Scope R_scope.\n\nSection channel_coding_converse_intermediate_lemma.\nVariables (A B : finType) (W : `Ch*(A, B)).\nVariable minRate : R.\nHypothesis HminRate : minRate > capacity W.\nHypothesis set_of_I_has_ubound :\n  classical_sets.has_ubound (fun y => exists P, `I(P, W) = y).\n\nLet Anot0 : (0 < #|A|)%nat. Proof. by case: W. Qed.\n\nLet Bnot0 : (0 < #|B|)%nat.\nProof. case/card_gt0P : Anot0 => a _; exact: (fdist_card_neq0 (W a)). Qed.\n\nLemma channel_coding_converse_gen : exists Delta, 0 < Delta /\\ forall n',\n  let n := n'.+1 in forall (M : finType) (c : code A B M n), (0 < #|M|)%nat ->\n    minRate <= CodeRate c ->\n      scha(W, c) <= n.+1%:R ^ (#|A| + #|A| * #|B|) * exp2 (- n%:R * Delta).\nProof.\nmove: error_exponent_bound => /(_ _ _ Bnot0 W _ HminRate set_of_I_has_ubound).\ncase => Delta [Delta_pos HDelta].\nexists Delta; split => // n' n M c Mnot0 H.\napply: (leR_trans (success_bound W Mnot0 c)).\nset Pmax := [arg max_(P > _) _]%O.\nset tc :=  _.-typed_code _.\nrewrite pow_add -mulRA.\napply leR_wpmul2l; first exact/pow_le/leR0n.\napply: (leR_trans (typed_success_bound W Mnot0 (Pmax.-typed_code c))).\napply leR_wpmul2l; first exact/pow_le/leR0n.\nset Vmax := [arg max_(V > _) _]%O.\nrewrite /success_factor_bound /exp_cdiv.\ncase : ifP => Hcase; last by rewrite mul0R.\nrewrite -ExpD.\napply Exp_le_increasing => //.\nrewrite -mulRDr 2!mulNR.\nrewrite leR_oppr oppRK; apply/leR_wpmul2l; first exact/leR0n.\nhave {}Hcase : Pmax |- Vmax << W.\n  move=> a Hp; apply/dominatesP => b /eqP Hw.\n  move/forallP : Hcase.\n  by move/(_ a)/implyP/(_ Hp)/forallP/(_ b)/implyP/(_ Hw)/eqP.\napply (leR_trans (HDelta Pmax Vmax Hcase)) => /=.\nexact/leR_add2l/Rle_max_compat_l/leR_add2r.\nQed.\n\nEnd channel_coding_converse_intermediate_lemma.\n\nSection channel_coding_converse.\nVariables (A B : finType) (W : `Ch*(A, B)).\nVariable minRate : R.\nHypothesis minRate_cap : minRate > capacity W.\nHypothesis set_of_I_has_ubound :\n  classical_sets.has_ubound (fun y => exists P, `I(P, W) = y).\n\nVariable epsilon : R. (* TODO: use posnum *)\nHypothesis eps_gt0 : 0 < epsilon.\n\nTheorem channel_coding_converse : exists n0,\n  forall n M (c : code A B M n),\n    (0 < #|M|)%nat -> n0 < n%:R -> minRate <= CodeRate c -> scha(W, c) < epsilon.\nProof.\ncase: (channel_coding_converse_gen minRate_cap set_of_I_has_ubound) => Delta [Delta_pos HDelta].\npose K := (#|A| + #|A| * #|B|)%nat.\npose n0 := 2 ^ K * K.+1`!%:R / ((Delta * ln 2) ^ K.+1) / epsilon.\nexists n0 => n M c HM n0_n HminRate.\nhave Rlt0n : 0 < n%:R.\n  apply: (ltR_trans _ n0_n).\n  rewrite /n0.\n  apply mulR_gt0; last exact/invR_gt0.\n  rewrite /Rdiv -mulRA.\n  apply mulR_gt0; first exact/expR_gt0/Rlt_0_2.\n  apply mulR_gt0;\n    [exact/ltR0n/fact_gt0 | exact/invR_gt0/expR_gt0/mulR_gt0].\ndestruct n as [|n'].\n  by apply ltRR in Rlt0n.\nset n := n'.+1.\napply: (@leR_ltR_trans (n.+1%:R ^ K * exp2 (- n%:R * Delta))).\n  exact: HDelta.\nmove: (n0_n) => /(@ltR_pmul2l (/ n%:R) _) => /(_ (invR_gt0 n%:R Rlt0n)).\nrewrite mulVR ?INR_eq0' //.\nmove/(@ltR_pmul2l epsilon) => /(_ eps_gt0); rewrite mulR1 => H1'.\napply: (leR_ltR_trans _ H1') => {H1'}.\nrewrite /n0 [in X in _ <= X]mulRC -2![in X in _ <= X]mulRA.\nrewrite mulVR ?mulR1 ?gtR_eqF //.\napply Rge_le; rewrite mulRC -2!mulRA; apply Rle_ge.\nset aux := _%:R * (_ * _).\nhave aux_gt0 : 0 < aux.\n  apply mulR_gt0; first exact/ltR0n/fact_gt0.\n  apply mulR_gt0; [exact/invR_gt0/expR_gt0/mulR_gt0 | exact/invR_gt0].\napply (@leR_trans ((n.+1%:R / n%:R) ^ K * aux)); last first.\n  apply leR_pmul => //.\n  - apply/expR_ge0/divR_ge0 => //; exact: leR0n.\n  - exact: ltRW.\n  - apply pow_incr; split.\n    + apply divR_ge0 => //; exact: leR0n.\n    + apply (@leR_pmul2r n%:R) => //.\n      rewrite -mulRA mulVR // ?mulR1 ?INR_eq0' ?gtn_eqF // (_ : 2 = 2%:R) //.\n      rewrite -natRM; apply/le_INR/leP; by rewrite -{1}(mul1n n) ltn_pmul2r.\n  - exact/leRR.\nrewrite expRM -mulRA; apply leR_pmul => //.\n- exact/expR_ge0/ltRW/ltR0n.\n- exact/leRR.\n- apply invR_le => //.\n  + apply mulR_gt0; last exact aux_gt0.\n    rewrite expRV ?INR_eq0' //; exact/invR_gt0/expR_gt0.\n  + rewrite -exp2_Ropp mulNR oppRK /exp2.\n    have nDeltaln2 : 0 <= n%:R * Delta * ln 2.\n      apply mulR_ge0; last exact/ltRW.\n      apply mulR_ge0; [exact/leR0n | exact/ltRW].\n    apply: (leR_trans _ (exp_lb (K.+1) nDeltaln2)) => {nDeltaln2}.\n    apply Req_le.\n    rewrite invRM; last 2 first.\n      exact/gtR_eqF/expR_gt0/invR_gt0.\n      exact/gtR_eqF.\n    rewrite -/(Rdiv _ _) divRM; last 2 first.\n      by rewrite INR_eq0' gtn_eqF // fact_gt0.\n      rewrite gtR_eqF //; apply/mulR_gt0; last exact/invR_gt0.\n      exact/invR_gt0/expR_gt0/mulR_gt0.\n    rewrite -mulRA mulRC invRM; last 2 first.\n    - by apply/eqP/invR_neq0/eqP; rewrite expR_eq0 mulR_neq0' ln2_neq0 andbT; exact/gtR_eqF.\n    - by apply/eqP/invR_neq0/eqP; by rewrite INR_eq0'.\n    - rewrite invRK; last first.\n        by rewrite expR_eq0 mulR_neq0' ln2_neq0 andbT; exact/gtR_eqF.\n      rewrite invRK; last by rewrite INR_eq0'.\n      rewrite (_ : / (/ n%:R) ^ K = n%:R ^ K); last first.\n        rewrite expRV ?INR_eq0' // invRK //; apply/expR_neq0; by rewrite INR_eq0'.\n      rewrite -mulRA {1}/Rdiv (mulRA n%:R) -expRS mulRA -expRM.\n      by rewrite -/(Rdiv _ _) mulRCA -mulRA (mulRC (ln 2)).\nQed.\n\nEnd channel_coding_converse.\n", "meta": {"author": "affeldt-aist", "repo": "infotheo", "sha": "5f9efb859dbadcbcae2330e2e21e76f9b632d879", "save_path": "github-repos/coq/affeldt-aist-infotheo", "path": "github-repos/coq/affeldt-aist-infotheo/infotheo-5f9efb859dbadcbcae2330e2e21e76f9b632d879/information_theory/channel_coding_converse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7049678290225951}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.ZUtil.Notations.\nRequire Import Crypto.Util.LetIn.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Definition pow2_mod n i := (n &' (Z.ones i)).\n\n  Definition zselect (cond zero_case nonzero_case : Z) :=\n    if cond =? 0 then zero_case else nonzero_case.\n\n  Definition add_modulo x y modulus :=\n    if (modulus <=? x + y) then (x + y) - modulus else (x + y).\n\n  (** Logical negation, modulo a number *)\n  Definition lnot_modulo (v : Z) (modulus : Z) : Z\n    := Z.lnot v mod modulus.\n\n  (** Boolean negation *)\n  Definition bneg (v : Z) : Z\n    := if dec (v = 0) then 1 else 0.\n\n  (* most significant bit *)\n  Definition cc_m s x := if dec (2 ^ (Z.log2 s) = s) then x >> (Z.log2 s - 1) else x / (s / 2).\n\n  (* least significant bit *)\n  Definition cc_l x := x mod 2.\n\n  (* two-register right shift *)\n  Definition rshi s hi lo n :=\n       let k := Z.log2 s in\n       if dec (2 ^ k = s)\n       then ((lo + (hi << k)) >> n) &' (Z.ones k)\n       else ((lo + hi * s) >> n) mod s.\n\n  (** left-shift that truncates *)\n  Definition truncating_shiftl bw x n := (x << n) mod (2^bw).\n\n  Definition get_carry (bitwidth : Z) (v : Z) : Z * Z\n    := (v mod 2^bitwidth, v / 2^bitwidth).\n  Definition add_with_carry (c : Z) (x y : Z) : Z\n    := c + x + y.\n  Definition add_with_get_carry (bitwidth : Z) (c : Z) (x y : Z) : Z * Z\n    := dlet v := add_with_carry c x y in get_carry bitwidth v.\n  Definition add_get_carry (bitwidth : Z) (x y : Z) : Z * Z\n    := add_with_get_carry bitwidth 0 x y.\n\n  Definition get_borrow (bitwidth : Z) (v : Z) : Z * Z\n    := let '(v, c) := get_carry bitwidth v in\n       (v, -c).\n  Definition sub_with_borrow (c : Z) (x y : Z) : Z\n    := add_with_carry (-c) x (-y).\n  Definition sub_with_get_borrow (bitwidth : Z) (c : Z) (x y : Z) : Z * Z\n    := dlet v := sub_with_borrow c x y in get_borrow bitwidth v.\n  Definition sub_get_borrow (bitwidth : Z) (x y : Z) : Z * Z\n    := sub_with_get_borrow bitwidth 0 x y.\n\n  (* splits at [bound], not [2^bitwidth]; wrapper to make add_getcarry\n  work if input is not known to be a power of 2 *)\n  Definition add_get_carry_full (bound : Z) (x y : Z) : Z * Z\n    := if 2 ^ (Z.log2 bound) =? bound\n       then add_get_carry (Z.log2 bound) x y\n       else ((x + y) mod bound, (x + y) / bound).\n  Definition add_with_get_carry_full (bound : Z) (c x y : Z) : Z * Z\n    := if 2 ^ (Z.log2 bound) =? bound\n       then add_with_get_carry (Z.log2 bound) c x y\n       else ((c + x + y) mod bound, (c + x + y) / bound).\n  Definition sub_get_borrow_full (bound : Z) (x y : Z) : Z * Z\n    := if 2 ^ (Z.log2 bound) =? bound\n       then sub_get_borrow (Z.log2 bound) x y\n       else ((x - y) mod bound, -((x - y) / bound)).\n  Definition sub_with_get_borrow_full (bound : Z) (c x y : Z) : Z * Z\n    := if 2 ^ (Z.log2 bound) =? bound\n       then sub_with_get_borrow (Z.log2 bound) c x y\n       else ((x - y - c) mod bound, -((x - y - c) / bound)).\n\n  Definition add_split (s x y : Z) : Z * Z\n    := dlet sum := Z.add x y in (sum mod s, sum / s).\n\n  Definition mul_split_at_bitwidth (bitwidth : Z) (x y : Z) : Z * Z\n    := dlet xy := x * y in\n       (if Z.geb bitwidth 0\n        then xy &' Z.ones bitwidth\n        else xy mod 2^bitwidth,\n        if Z.geb bitwidth 0\n        then xy >> bitwidth\n        else xy / 2^bitwidth).\n  Definition mul_split (s x y : Z) : Z * Z\n    := if s =? 2^Z.log2 s\n       then mul_split_at_bitwidth (Z.log2 s) x y\n       else ((x * y) mod s, (x * y) / s).\n\n  Definition mul_high (s x y : Z) : Z\n    := snd (mul_split s x y).\n\n  (** returns [1] iff [x < y] *)\n  Definition ltz (x y : Z) : Z\n    := if x <? y then 1 else 0.\n\n  Definition combine_at_bitwidth (bitwidth lo hi : Z) : Z\n    := lo + (hi << bitwidth).\n\n  (** if positive, round up to 2^k-1 (0b11111....); if negative, round down to -2^k (0b...111000000...) *)\n  Definition round_lor_land_bound (x : Z) : Z\n    := if (0 <=? x)%Z\n       then 2^(Z.log2_up (x+1))-1\n       else -2^(Z.log2_up (-x)).\n\n  Fixpoint log10_fuel (fuel : nat) (v : Z) :=\n    match fuel with\n    | O => 0\n    | S fuel\n      => if v >? 1\n         then 1 + log10_fuel fuel (v / 10)\n         else 0\n    end.\n  Definition log10 (v : Z) : Z := log10_fuel (Z.to_nat (Z.log2 v)) v.\n\n  (** Special identity function for constant-time cmov *)\n  Definition value_barrier (x : Z) := x.\n  \n  (* arithmetic right shift *)\n  Definition arithmetic_shiftr1 (m a : Z) :=\n    (a &' 2^(m - 1)) |' (a >> 1).\n\n  Definition sign_bit m a := a >> (m - 1).\n\n  Definition ones_from m k := (Z.ones k) << (m - k).\n  Definition ones_at m k := (Z.ones k) << m.\n\n  Definition sign_extend old_m new_m a :=\n    dlet q := Z.zselect (sign_bit old_m a) 0 (ones_at old_m (new_m - old_m)) in\n          q |' a.\n\n  Definition arithmetic_shiftr m a k :=\n    dlet q := Z.zselect (sign_bit m a) 0 (ones_from m k) in\n          q |' (a >> k).\n\n  (** Note that the following definition may be inconvenient to reason about,\n      and [(a + 2^(m-1)) mod 2^m - 2^(m-1)] may prove simpler to reason about arithmetically. \n      See also https://github.com/mit-plv/coqutil/blob/c8006ceca816076b117c31d7feaefb5bbb850754/src/coqutil/Word/Naive.v#L15\n      and https://github.com/mit-plv/coqutil/blob/c8006ceca816076b117c31d7feaefb5bbb850754/src/coqutil/Word/Properties.v#L190 *)\n\n  Definition twos_complement m a :=\n    (if ((a mod 2 ^ m) <? 2 ^ (m - 1)) then a mod 2 ^ m else a mod 2 ^ m - 2 ^ m).\n\n  (* Negation in twos complement *)\n  Definition twos_complement_opp m a :=\n    ((Z.lnot_modulo a (2 ^ m)) + 1) mod (2 ^ m).\n\n  (* Check if a number considered in twos complement of bitwidth m is negative *)\n  Definition twos_complement_neg m a := a >> (m - 1).\n\n  (* note the corner case condition: when f is exactly 2 to the mw-1'th power, then -f = f and\n   so checking that -f is negative does not work in that case.\n   This is not really an issue, since it just requires that our integers are small (which they are)\n   Long term, we would like to add comparison operators to the supported C language *)\n  Definition twos_complement_pos m a :=\n    dlet b := twos_complement_opp m a in sign_bit m b.\n\n  Definition twos_complement_mul ma mb a b :=\n    (sign_extend ma (ma + mb) a) * (sign_extend mb (ma + mb) b).\nEnd Z.\n", "meta": {"author": "dip-proto", "repo": "fiat-crypto", "sha": "fc3a9280c51f413943c167cc9292e953b8e42c02", "save_path": "github-repos/coq/dip-proto-fiat-crypto", "path": "github-repos/coq/dip-proto-fiat-crypto/fiat-crypto-fc3a9280c51f413943c167cc9292e953b8e42c02/src/Util/ZUtil/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7049678139768724}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat div seq.\nFrom mathcomp Require Import choice fintype finfun bigop prime binomial.\n\n(******************************************************************************)\n(*   The algebraic part of the Algebraic Hierarchy, as described in           *)\n(*          ``Packaging mathematical structures'', TPHOLs09, by               *)\n(*   Francois Garillot, Georges Gonthier, Assia Mahboubi, Laurence Rideau     *)\n(*                                                                            *)\n(* This file defines for each Structure (Zmodule, Ring, etc ...) its type,    *)\n(* its packers and its canonical properties :                                 *)\n(*                                                                            *)\n(*  * Zmodule (additive abelian groups):                                      *)\n(*              zmodType == interface type for Zmodule structure.             *)\n(* ZmodMixin addA addC add0x addNx == builds the mixin for a Zmodule from the *)\n(*                          algebraic properties of its operations.           *)\n(*          ZmodType V m == packs the mixin m to build a Zmodule of type      *)\n(*                          zmodType. The carrier type V must have a          *)\n(*                          choiceType canonical structure.                   *)\n(* [zmodType of V for S] == V-clone of the zmodType structure S: a copy of S  *)\n(*                          where the sort carrier has been replaced by V,    *)\n(*                          and which is therefore a zmodType structure on V. *)\n(*                          The sort carrier for S must be convertible to V.  *)\n(*       [zmodType of V] == clone of a canonical zmodType structure on V.     *)\n(*                          Similar to the above, except S is inferred, but   *)\n(*                          possibly with a syntactically different carrier.  *)\n(*                     0 == the zero (additive identity) of a Zmodule.        *)\n(*                 x + y == the sum of x and y (in a Zmodule).                *)\n(*                   - x == the opposite (additive inverse) of x.             *)\n(*                 x - y == the difference of x and y; this is only notation  *)\n(*                          for x + (- y).                                    *)\n(*                x *+ n == n times x, with n in nat (non-negative), i.e.,    *)\n(*                          x + (x + .. (x + x)..) (n terms); x *+ 1 is thus  *)\n(*                          convertible to x, and x *+ 2 to x + x.            *)\n(*                x *- n == notation for - (x *+ n), the opposite of x *+ n.  *)\n(*        \\sum_<range> e == iterated sum for a Zmodule (cf bigop.v).          *)\n(*                  e`_i == nth 0 e i, when e : seq M and M has a zmodType    *)\n(*                          structure.                                        *)\n(*             support f == 0.-support f, i.e., [pred x | f x != 0].          *)\n(*         oppr_closed S <-> collective predicate S is closed under opposite. *)\n(*         addr_closed S <-> collective predicate S is closed under finite    *)\n(*                           sums (0 and x + y in S, for x, y in S).          *)\n(*         zmod_closed S <-> collective predicate S is closed under zmodType  *)\n(*                          operations (0 and x - y in S, for x, y in S).     *)\n(*                          This property coerces to oppr_pred and addr_pred. *)\n(*         OpprPred oppS == packs oppS : oppr_closed S into an opprPred S     *)\n(*                          interface structure associating this property to  *)\n(*                          the canonical pred_key S, i.e. the k for which S  *)\n(*                          has a Canonical keyed_pred k structure (see file  *)\n(*                          ssrbool.v).                                       *)\n(*         AddrPred addS == packs addS : addr_closed S into an addrPred S     *)\n(*                          interface structure associating this property to  *)\n(*                          the canonical pred_key S (see above).             *)\n(*         ZmodPred oppS == packs oppS : oppr_closed S into an zmodPred S     *)\n(*                          interface structure associating the zmod_closed   *)\n(*                          property to the canonical pred_key S (see above), *)\n(*                          which must already be an addrPred.                *)\n(* [zmodMixin of M by <:] == zmodType mixin for a subType whose base type is  *)\n(*                          a zmodType and whose predicate's canonical        *)\n(*                          pred_key is a zmodPred.                           *)\n(* --> Coq can be made to behave as if all predicates had canonical zmodPred  *)\n(*     keys by executing Import DefaultKeying GRing.DefaultPred. The required *)\n(*     oppr_closed and addr_closed assumptions will be either abstracted,     *)\n(*     resolved or issued as separate proof obligations by the ssreflect      *)\n(*     plugin abstraction and Prop-irrelevance functions.                     *)\n(*  * Ring (non-commutative rings):                                           *)\n(*              ringType == interface type for a Ring structure.              *)\n(* RingMixin mulA mul1x mulx1 mulDx mulxD == builds the mixin for a Ring from *)\n(*                           the algebraic properties of its multiplicative   *)\n(*                           operators; the carrier type must have a zmodType *)\n(*                           structure.                                       *)\n(*           RingType R m == packs the ring mixin m into a ringType.          *)\n(*                    R^c == the converse Ring for R: R^c is convertible to R *)\n(*                           but when R has a canonical ringType structure    *)\n(*                           R^c has the converse one: if x y : R^c, then     *)\n(*                           x * y = (y : R) * (x : R).                       *)\n(*  [ringType of R for S] == R-clone of the ringType structure S.             *)\n(*        [ringType of R] == clone of a canonical ringType structure on R.    *)\n(*                      1 == the multiplicative identity element of a Ring.   *)\n(*                   n%:R == the ring image of an n in nat; this is just      *)\n(*                           notation for 1 *+ n, so 1%:R is convertible to 1 *)\n(*                           and 2%:R to 1 + 1.                               *)\n(*               <number> == <number>%:R with <number> a sequence of digits   *)\n(*                  x * y == the ring product of x and y.                     *)\n(*        \\prod_<range> e == iterated product for a ring (cf bigop.v).        *)\n(*                 x ^+ n == x to the nth power with n in nat (non-negative), *)\n(*                           i.e., x * (x * .. (x * x)..) (n factors); x ^+ 1 *)\n(*                           is thus convertible to x, and x ^+ 2 to x * x.   *)\n(*         GRing.sign R b := (-1) ^+ b in R : ringType, with b : bool.        *)\n(*                           This is a parsing-only helper notation, to be    *)\n(*                           used for defining more specific instances.       *)\n(*         GRing.comm x y <-> x and y commute, i.e., x * y = y * x.           *)\n(*           GRing.lreg x <-> x if left-regular, i.e., *%R x is injective.    *)\n(*           GRing.rreg x <-> x if right-regular, i.e., *%R x is injective.   *)\n(*               [char R] == the characteristic of R, defined as the set of   *)\n(*                           prime numbers p such that p%:R = 0 in R. The set *)\n(*                           [char R] has at most one element, and is         *)\n(*                           implemented as a pred_nat collective predicate   *)\n(*                           (see prime.v); thus the statement p \\in [char R] *)\n(*                           can be read as `R has characteristic p', while   *)\n(*                           [char R] =i pred0 means `R has characteristic 0' *)\n(*                           when R is a field.                               *)\n(*     Frobenius_aut chRp == the Frobenius automorphism mapping x in R to     *)\n(*                           x ^+ p, where chRp : p \\in [char R] is a proof   *)\n(*                           that R has (non-zero) characteristic p.          *)\n(*          mulr_closed S <-> collective predicate S is closed under finite   *)\n(*                           products (1 and x * y in S for x, y in S).       *)\n(*         smulr_closed S <-> collective predicate S is closed under products *)\n(*                           and opposite (-1 and x * y in S for x, y in S).  *)\n(*      semiring_closed S <-> collective predicate S is closed under semiring *)\n(*                           operations (0, 1, x + y and x * y in S).         *)\n(*       subring_closed S <-> collective predicate S is closed under ring     *)\n(*                           operations (1, x - y and x * y in S).            *)\n(*          MulrPred mulS == packs mulS : mulr_closed S into a mulrPred S,    *)\n(*        SmulrPred mulS     smulrPred S, semiringPred S, or subringPred S    *)\n(*     SemiringPred mulS     interface structure, corresponding to the above  *)\n(*      SubRingPred mulS     properties, respectively, provided S already has *)\n(*                           the supplementary zmodType closure properties.   *)\n(*                           The properties above coerce to subproperties so, *)\n(*                           e.g., ringS : subring_closed S can be used for   *)\n(*                           the proof obligations of all prerequisites.      *)\n(* [ringMixin of R by <:] == ringType mixin for a subType whose base type is  *)\n(*                           a ringType and whose predicate's canonical key   *)\n(*                           is a SubringPred.                                *)\n(*  --> As for zmodType predicates, Import DefaultKeying GRing.DefaultPred    *)\n(*      turns unresolved GRing.Pred unification constraints into proof        *)\n(*      obligations for basic closure assumptions.                            *)\n(*                                                                            *)\n(*  * ComRing (commutative Rings):                                            *)\n(*            comRingType == interface type for commutative ring structure.   *)\n(*     ComRingType R mulC == packs mulC into a comRingType; the carrier type  *)\n(*                           R must have a ringType canonical structure.      *)\n(* ComRingMixin mulA mulC mul1x mulDx == builds the mixin for a Ring (i.e., a *)\n(*                           *non commutative* ring), using the commutativity *)\n(*                           to reduce the number of proof obligations.       *)\n(* [comRingType of R for S] == R-clone of the comRingType structure S.        *)\n(*     [comRingType of R] == clone of a canonical comRingType structure on R. *)\n(* [comRingMixin of R by <:] == comutativity mixin axiom for R when it is a   *)\n(*                           subType of a commutative ring.                   *)\n(*                                                                            *)\n(*  * UnitRing (Rings whose units have computable inverses):                  *)\n(*           unitRingType == interface type for the UnitRing structure.       *)\n(* UnitRingMixin mulVr mulrV unitP inv0id == builds the mixin for a UnitRing  *)\n(*                           from the properties of the inverse operation and *)\n(*                           the boolean test for being a unit (invertible).  *)\n(*                           The inverse of a non-unit x is constrained to be *)\n(*                           x itself (property inv0id). The carrier type     *)\n(*                           must have a ringType canonical structure.        *)\n(*       UnitRingType R m == packs the unit ring mixin m into a unitRingType. *)\n(*                  WARNING: while it is possible to omit R for most of the   *)\n(*                           XxxType functions, R MUST be explicitly given    *)\n(*                           when UnitRingType is used with a mixin produced  *)\n(*                           by ComUnitRingMixin, in a Canonical definition,  *)\n(*                           otherwise the resulting structure will have the  *)\n(*                           WRONG sort key and will NOT BE USED during type  *)\n(*                           inference.                                       *)\n(* [unitRingType of R for S] == R-clone of the unitRingType structure S.      *)\n(*    [unitRingType of R] == clones a canonical unitRingType structure on R.  *)\n(*     x \\is a GRing.unit <=> x is a unit (i.e., has an inverse).             *)\n(*                   x^-1 == the ring inverse of x, if x is a unit, else x.   *)\n(*                  x / y == x divided by y (notation for x * y^-1).          *)\n(*                 x ^- n := notation for (x ^+ n)^-1, the inverse of x ^+ n. *)\n(*         invr_closed S <-> collective predicate S is closed under inverse.  *)\n(*         divr_closed S <-> collective predicate S is closed under division  *)\n(*                           (1 and x / y in S).                              *)\n(*        sdivr_closed S <-> collective predicate S is closed under division  *)\n(*                           and opposite (-1 and x / y in S, for x, y in S). *)\n(*      divring_closed S <-> collective predicate S is closed under unitRing  *)\n(*                           operations (1, x - y and x / y in S).            *)\n(*         DivrPred invS == packs invS : mulr_closed S into a divrPred S,     *)\n(*        SdivrPred invS    sdivrPred S or divringPred S interface structure, *)\n(*      DivringPred invS    corresponding to the above properties, resp.,     *)\n(*                          provided S already has the supplementary ringType *)\n(*                          closure properties. The properties above coerce   *)\n(*                          to subproperties, as explained above.             *)\n(* [unitRingMixin of R by <:] == unitRingType mixin for a subType whose base  *)\n(*                           type is a unitRingType and whose predicate's     *)\n(*                           canonical key is a divringPred and whose ring    *)\n(*                           structure is compatible with the base type's.    *)\n(*                                                                            *)\n(*  * ComUnitRing (commutative rings with computable inverses):               *)\n(*        comUnitRingType == interface type for ComUnitRing structure.        *)\n(* ComUnitRingMixin mulVr unitP inv0id == builds the mixin for a UnitRing (a  *)\n(*                           *non commutative* unit ring, using commutativity *)\n(*                           to simplify the proof obligations; the carrier   *)\n(*                           type must have a comRingType structure.          *)\n(*                           WARNING: ALWAYS give an explicit type argument   *)\n(*                           to UnitRingType along with a mixin produced by   *)\n(*                           ComUnitRingMixin (see above).                    *)\n(* [comUnitRingType of R] == a comUnitRingType structure for R created by     *)\n(*                           merging canonical comRingType and unitRingType   *)\n(*                           structures on R.                                 *)\n(*                                                                            *)\n(*  * IntegralDomain (integral, commutative, ring with partial inverses):     *)\n(*            idomainType == interface type for the IntegralDomain structure. *)\n(* IdomainType R mulf_eq0 == packs the integrality property into an           *)\n(*                           idomainType integral domain structure; R must    *)\n(*                           have a comUnitRingType canonical structure.      *)\n(* [idomainType of R for S] == R-clone of the idomainType structure S.        *)\n(*     [idomainType of R] == clone of a canonical idomainType structure on R. *)\n(* [idomainMixin of R by <:] == mixin axiom for a idomain subType.            *)\n(*                                                                            *)\n(*  * Field (commutative fields):                                             *)\n(*              fieldType == interface type for fields.                       *)\n(*  GRing.Field.mixin_of R == the field property: x != 0 -> x \\is a unit, for *)\n(*                           x : R; R must be or coerce to a unitRingType.    *)\n(*  GRing.Field.axiom inv == the field axiom: x != 0 -> inv x * x = 1 for all *)\n(*                           x. This is equivalent to the property above, but *)\n(*                           does not require a unitRingType as inv is an     *)\n(*                           explicit argument.                               *)\n(* FieldUnitMixin mulVf inv0 == a *non commutative unit ring* mixin, using an *)\n(*                           inverse function that satisfies the field axiom  *)\n(*                           and fixes 0 (arguments mulVf and inv0, resp.),   *)\n(*                           and x != 0 as the Ring.unit predicate. The       *)\n(*                           carrier type must be a canonical comRingType.    *)\n(*    FieldIdomainMixin m == an *idomain* mixin derived from a field mixin m. *)\n(* GRing.Field.IdomainType mulVf inv0 == an idomainType incorporating the two *)\n(*                           mixins above, where FieldIdomainMixin is applied *)\n(*                           to the trivial field mixin for FieldUnitMixin.   *)\n(*  FieldMixin mulVf inv0 == the (trivial) field mixin for Field.IdomainType. *)\n(*          FieldType R m == packs the field mixin M into a fieldType. The    *)\n(*                           carrier type R must be an idomainType.           *)\n(* --> Given proofs mulVf and inv0 as above, a non-Canonical instances        *)\n(* of fieldType can be created with FieldType _ (FieldMixin mulVf inv0).      *)\n(* For Canonical instances one should always specify the first (sort)         *)\n(* argument of FieldType and other instance constructors, as well as pose     *)\n(* Definitions for unit ring, field, and idomain mixins (in that order).      *)\n(* [fieldType of F for S] == F-clone of the fieldType structure S.            *)\n(*       [fieldType of F] == clone of a canonical fieldType structure on F.   *)\n(*   [fieldMixin of R by <:] == mixin axiom for a field subType.              *)\n(*                                                                            *)\n(*  * DecidableField (fields with a decidable first order theory):            *)\n(*           decFieldType == interface type for DecidableField structure.     *)\n(*     DecFieldMixin satP == builds the mixin for a DecidableField from the   *)\n(*                           correctness of its satisfiability predicate. The *)\n(*                           carrier type must have a unitRingType structure. *)\n(*       DecFieldType F m == packs the decidable field mixin m into a         *)\n(*                           decFieldType; the carrier type F must have a     *)\n(*                           fieldType structure.                             *)\n(* [decFieldType of F for S] == F-clone of the decFieldType structure S.      *)\n(*    [decFieldType of F] == clone of a canonical decFieldType structure on F *)\n(*           GRing.term R == the type of formal expressions in a unit ring R  *)\n(*                           with formal variables 'X_k, k : nat, and         *)\n(*                           manifest constants x%:T, x : R. The notation of  *)\n(*                           all the ring operations is redefined for terms,  *)\n(*                           in scope %T.                                     *)\n(*        GRing.formula R == the type of first order formulas over R; the %T  *)\n(*                           scope binds the logical connectives /\\, \\/, ~,   *)\n(*                           ==>, ==, and != to formulae; GRing.True/False    *)\n(*                           and GRing.Bool b denote constant formulae, and   *)\n(*                           quantifiers are written 'forall/'exists 'X_k, f. *)\n(*                             GRing.Unit x tests for ring units              *)\n(*                             GRing.If p_f t_f e_f emulates if-then-else     *)\n(*                             GRing.Pick p_f t_f e_f emulates fintype.pick   *)\n(*                             foldr GRing.Exists/Forall q_f xs can be used   *)\n(*                               to write iterated quantifiers.               *)\n(*         GRing.eval e t == the value of term t with valuation e : seq R     *)\n(*                           (e maps 'X_i to e`_i).                           *)\n(*  GRing.same_env e1 e2 <-> environments e1 and e2 are extensionally equal.  *)\n(*        GRing.qf_form f == f is quantifier-free.                            *)\n(*        GRing.holds e f == the intuitionistic CiC interpretation of the     *)\n(*                           formula f holds with valuation e.                *)\n(*      GRing.qf_eval e f == the value (in bool) of a quantifier-free f.      *)\n(*          GRing.sat e f == valuation e satisfies f (only in a decField).    *)\n(*          GRing.sol n f == a sequence e of size n such that e satisfies f,  *)\n(*                           if one exists, or [::] if there is no such e.    *)\n(* QEdecFieldMixin wfP okP == a decidable field Mixin built from a quantifier *)\n(*                           eliminator p and proofs wfP : GRing.wf_QE_proj p *)\n(*                           and okP : GRing.valid_QE_proj p that p returns   *)\n(*                           well-formed and valid formulae, i.e., p i (u, v) *)\n(*                           is a quantifier-free formula equivalent to       *)\n(*        'exists 'X_i, u1 == 0 /\\ ... /\\ u_m == 0 /\\ v1 != 0 ... /\\ v_n != 0 *)\n(*                                                                            *)\n(*  * ClosedField (algebraically closed fields):                              *)\n(*        closedFieldType == interface type for the ClosedField structure.    *)\n(*    ClosedFieldType F m == packs the closed field mixin m into a            *)\n(*                           closedFieldType. The carrier F must have a       *)\n(*                           decFieldType structure.                          *)\n(* [closedFieldType of F on S] == F-clone of a closedFieldType structure S.   *)\n(* [closedFieldType of F] == clone of a canonicalclosedFieldType structure    *)\n(*                           on F.                                            *)\n(*                                                                            *)\n(*  * Lmodule (module with left multiplication by external scalars).          *)\n(*             lmodType R == interface type for an Lmodule structure with     *)\n(*                           scalars of type R; R must have a ringType        *)\n(*                           structure.                                       *)\n(* LmodMixin scalA scal1v scalxD scalDv == builds an Lmodule mixin from the   *)\n(*                           algebraic properties of the scaling operation;   *)\n(*                           the module carrier type must have a zmodType     *)\n(*                           structure, and the scalar carrier must have a    *)\n(*                           ringType structure.                              *)\n(*         LmodType R V m == packs the mixin v to build an Lmodule of type    *)\n(*                           lmodType R. The carrier type V must have a       *)\n(*                           zmodType structure.                              *)\n(* [lmodType R of V for S] == V-clone of an lmodType R structure S.           *)\n(*      [lmodType R of V] == clone of a canonical lmodType R structure on V.  *)\n(*                 a *: v == v scaled by a, when v is in an Lmodule V and a   *)\n(*                           is in the scalar Ring of V.                      *)\n(*        scaler_closed S <-> collective predicate S is closed under scaling. *)\n(*        linear_closed S <-> collective predicate S is closed under linear   *)\n(*                           combinations (a *: u + v in S when u, v in S).   *)\n(*        submod_closed S <-> collective predicate S is closed under lmodType *)\n(*                           operations (0 and a *: u + v in S).              *)\n(*      SubmodPred scaleS == packs scaleS : scaler_closed S in a submodPred S *)\n(*                           interface structure corresponding to the above   *)\n(*                           property, provided S's key is a zmodPred;        *)\n(*                           submod_closed coerces to all the prerequisites.  *)\n(* [lmodMixin of V by <:] == mixin for a subType of an lmodType, whose        *)\n(*                           predicate's key is a submodPred.                 *)\n(*                                                                            *)\n(*  * Lalgebra (left algebra, ring with scaling that associates on the left): *)\n(*             lalgType R == interface type for Lalgebra structures with      *)\n(*                           scalars in R; R must have ringType structure.    *)\n(*    LalgType R V scalAl == packs scalAl : k (x y) = (k x) y into an         *)\n(*                           Lalgebra of type lalgType R. The carrier type V  *)\n(*                           must have both lmodType R and ringType canonical *)\n(*                           structures.                                      *)\n(*                    R^o == the regular algebra of R: R^o is convertible to  *)\n(*                           R, but when R has a ringType structure then R^o  *)\n(*                           extends it to an lalgType structure by letting R *)\n(*                           act on itself: if x : R and y : R^o then         *)\n(*                           x *: y = x * (y : R).                            *)\n(*                   k%:A == the image of the scalar k in an L-algebra; this  *)\n(*                           is simply notation for k *: 1.                   *)\n(* [lalgType R of V for S] == V-clone the lalgType R structure S.             *)\n(*      [lalgType R of V] == clone of a canonical lalgType R structure on V.  *)\n(*        subalg_closed S <-> collective predicate S is closed under lalgType *)\n(*                           operations (1, a *: u + v and u * v in S).       *)\n(*      SubalgPred scaleS == packs scaleS : scaler_closed S in a subalgPred S *)\n(*                           interface structure corresponding to the above   *)\n(*                           property, provided S's key is a subringPred;     *)\n(*                           subalg_closed coerces to all the prerequisites.  *)\n(* [lalgMixin of V by <:] == mixin axiom for a subType of an lalgType.        *)\n(*                                                                            *)\n(*  * Algebra (ring with scaling that associates both left and right):        *)\n(*              algType R == type for Algebra structure with scalars in R.    *)\n(*                           R should be a commutative ring.                  *)\n(*     AlgType R A scalAr == packs scalAr : k (x y) = x (k y) into an Algebra *)\n(*                           Structure of type algType R. The carrier type A  *)\n(*                           must have an lalgType R structure.               *)\n(*        CommAlgType R A == creates an Algebra structure for an A that has   *)\n(*                           both lalgType R and comRingType structures.      *)\n(* [algType R of V for S] == V-clone of an algType R structure on S.          *)\n(*       [algType R of V] == clone of a canonical algType R structure on V.   *)\n(*  [algMixin of V by <:] == mixin axiom for a subType of an algType.         *)\n(*                                                                            *)\n(*  * UnitAlgebra (algebra with computable inverses):                         *)\n(*          unitAlgType R == interface type for UnitAlgebra structure with    *)\n(*                           scalars in R; R should have a unitRingType       *)\n(*                           structure.                                       *)\n(*   [unitAlgType R of V] == a unitAlgType R structure for V created by       *)\n(*                           merging canonical algType and unitRingType on V. *)\n(*        divalg_closed S <-> collective predicate S is closed under all      *)\n(*                           unitAlgType operations (1, a *: u + v and u / v  *)\n(*                           are in S fo u, v in S).                          *)\n(*      DivalgPred scaleS == packs scaleS : scaler_closed S in a divalgPred S *)\n(*                           interface structure corresponding to the above   *)\n(*                           property, provided S's key is a divringPred;     *)\n(*                           divalg_closed coerces to all the prerequisites.  *)\n(*                                                                            *)\n(*  * ComAlgebra (commutative algebra):                                       *)\n(*           comAlgType R == interface type for ComAlgebra structure with     *)\n(*                           scalars in R; R should have a comRingType        *)\n(*                           structure.                                       *)\n(*    [comAlgType R of V] == a comAlgType R structure for V created by        *)\n(*                           merging canonical algType and comRingType on V.  *)\n(*                                                                            *)\n(*  * ComUnitAlgebra (commutative algebra with computable inverses):          *)\n(*       comUnitAlgType R == interface type for ComUnitAlgebra structure with *)\n(*                           scalars in R; R should have a comUnitRingType    *)\n(*                           structure.                                       *)\n(* [comUnitAlgType R of V] == a comUnitAlgType R structure for V created by   *)\n(*                           merging canonical comAlgType and                 *)\n(*                           unitRingType on V.                               *)\n(*                                                                            *)\n(*   In addition to this structure hierarchy, we also develop a separate,     *)\n(* parallel hierarchy for morphisms linking these structures:                 *)\n(*                                                                            *)\n(* * Additive (additive functions):                                           *)\n(*             additive f <-> f of type U -> V is additive, i.e., f maps the  *)\n(*                           Zmodule structure of U to that of V, 0 to 0,     *)\n(*                           - to - and + to + (equivalently, binary - to -). *)\n(*                        := {morph f : u v / u - v}.                         *)\n(*      {additive U -> V} == the interface type for a Structure (keyed on     *)\n(*                           a function f : U -> V) that encapsulates the     *)\n(*                           additive property; both U and V must have        *)\n(*                           zmodType canonical structures.                   *)\n(*         Additive add_f == packs add_f : additive f into an additive        *)\n(*                           function structure of type {additive U -> V}.    *)\n(*   [additive of f as g] == an f-clone of the additive structure on the      *)\n(*                           function g -- f and g must be convertible.       *)\n(*        [additive of f] == a clone of an existing additive structure on f.  *)\n(*                                                                            *)\n(* * RMorphism (ring morphisms):                                              *)\n(*       multiplicative f <-> f of type R -> S is multiplicative, i.e., f     *)\n(*                           maps 1 and * in R to 1 and * in S, respectively, *)\n(*                           R ans S must have canonical ringType structures. *)\n(*            rmorphism f <-> f is a ring morphism, i.e., f is both additive  *)\n(*                           and multiplicative.                              *)\n(*     {rmorphism R -> S} == the interface type for ring morphisms, i.e.,     *)\n(*                           a Structure that encapsulates the rmorphism      *)\n(*                           property for functions f : R -> S; both R and S  *)\n(*                           must have ringType structures.                   *)\n(*      RMorphism morph_f == packs morph_f : rmorphism f into a Ring morphism *)\n(*                           structure of type {rmorphism R -> S}.            *)\n(*     AddRMorphism mul_f == packs mul_f : multiplicative f into an rmorphism *)\n(*                           structure of type {rmorphism R -> S}; f must     *)\n(*                           already have an {additive R -> S} structure.     *)\n(*  [rmorphism of f as g] == an f-clone of the rmorphism structure of g.      *)\n(*       [rmorphism of f] == a clone of an existing additive structure on f.  *)\n(*  -> If R and S are UnitRings the f also maps units to units and inverses   *)\n(*     of units to inverses; if R is a field then f is a field isomorphism    *)\n(*     between R and its image.                                               *)\n(*  -> As rmorphism coerces to both additive and multiplicative, all          *)\n(*     structures for f can be built from a single proof of rmorphism f.      *)\n(*  -> Additive properties (raddf_suffix, see below) are duplicated and       *)\n(*     specialised for RMorphism (as rmorph_suffix). This allows more         *)\n(*     precise rewriting and cleaner chaining: although raddf lemmas will     *)\n(*     recognize RMorphism functions, the converse will not hold (we cannot   *)\n(*     add reverse inheritance rules because of incomplete backtracking in    *)\n(*     the Canonical Projection unification), so one would have to insert a   *)\n(*     /= every time one switched from additive to multiplicative rules.      *)\n(*  -> The property duplication also means that it is not strictly necessary  *)\n(*     to declare all Additive instances.                                     *)\n(*                                                                            *)\n(* * Linear (linear functions):                                               *)\n(*             scalable f <-> f of type U -> V is scalable, i.e., f morphs    *)\n(*                           scaling on U to scaling on V, a *: _ to a *: _.  *)\n(*                           U and V must both have lmodType R structures,    *)\n(*                           for the same ringType R.                         *)\n(*       scalable_for s f <-> f is scalable for scaling operator s, i.e.,     *)\n(*                           f morphs a *: _ to s a _; the range of f only    *)\n(*                           need to be a zmodType. The scaling operator s    *)\n(*                           should be one of *:%R (see scalable, above), *%R *)\n(*                           or a combination nu \\; *%R or nu \\; *:%R with    *)\n(*                           nu : {rmorphism _}; otherwise some of the theory *)\n(*                           (e.g., the linearZ rule) will not apply.         *)\n(*               linear f <-> f of type U -> V is linear, i.e., f morphs      *)\n(*                           linear combinations a *: u + v in U to similar   *)\n(*                           linear combinations in V; U and V must both have *)\n(*                           lmodType R structures, for the same ringType R.  *)\n(*                        := forall a, {morph f: u v / a *: u + v}.           *)\n(*               scalar f <-> f of type U -> R is a scalar function, i.e.,    *)\n(*                           f (a *: u + v) = a * f u + f v.                  *)\n(*         linear_for s f <-> f is linear for the scaling operator s, i.e.,   *)\n(*                           f (a *: u + v) = s a (f u) + f v. The range of f *)\n(*                           only needs to be a zmodType, but s MUST be of    *)\n(*                           the form described in in scalable_for paragraph  *)\n(*                           for this predicate to type check.                *)\n(*            lmorphism f <-> f is both additive and scalable. This is in     *)\n(*                           fact equivalent to linear f, although somewhat   *)\n(*                           less convenient to prove.                        *)\n(*     lmorphism_for s f <-> f is both additive and scalable for s.           *)\n(*        {linear U -> V} == the interface type for linear functions, i.e., a *)\n(*                           Structure that encapsulates the linear property  *)\n(*                           for functions f : U -> V; both U and V must have *)\n(*                           lmodType R structures, for the same R.           *)\n(*             {scalar U} == the interface type for scalar functions, of type *)\n(*                           U -> R where U has an lmodType R structure.      *)\n(*    {linear U -> V | s} == the interface type for functions linear for s.   *)\n(*           Linear lin_f == packs lin_f : lmorphism_for s f into a linear    *)\n(*                           function structure of type {linear U -> V | s}.  *)\n(*                           As linear_for s f coerces to lmorphism_for s f,  *)\n(*                           Linear can be used with lin_f : linear_for s f   *)\n(*                           (indeed, that is the recommended usage). Note    *)\n(*                           that as linear f, scalar f, {linear U -> V} and  *)\n(*                           {scalar U} are simply notation for corresponding *)\n(*                           generic \"_for\" forms, Linear can be used for any *)\n(*                           of these special cases, transparently.           *)\n(*       AddLinear scal_f == packs scal_f : scalable_for s f into a           *)\n(*                           {linear U -> V | s} structure; f must already    *)\n(*                           have an additive structure; as with Linear,      *)\n(*                           AddLinear can be used with lin_f : linear f, etc *)\n(*     [linear of f as g] == an f-clone of the linear structure of g.         *)\n(*          [linear of f] == a clone of an existing linear structure on f.    *)\n(*          (a *: u)%Rlin == transient forms that simplify to a *: u, a * u,  *)\n(*           (a * u)%Rlin    nu a *: u, and nu a * u, respectively, and are   *)\n(*       (a *:^nu u)%Rlin    created by rewriting with the linearZ lemma. The *)\n(*        (a *^nu u)%Rlin    forms allows the RHS of linearZ to be matched    *)\n(*                           reliably, using the GRing.Scale.law structure.   *)\n(* -> Similarly to Ring morphisms, additive properties are specialized for    *)\n(*    linear functions.                                                       *)\n(* -> Although {scalar U} is convertible to {linear U -> R^o}, it does not    *)\n(*    actually use R^o, so that rewriting preserves the canonical structure   *)\n(*    of the range of scalar functions.                                       *)\n(* -> The generic linearZ lemma uses a set of bespoke interface structures to *)\n(*    ensure that both left-to-right and right-to-left rewriting work even in *)\n(*    the presence of scaling functions that simplify non-trivially (e.g.,    *)\n(*    idfun \\; *%R). Because most of the canonical instances and projections  *)\n(*    are coercions the machinery will be mostly invisible (with only the     *)\n(*    {linear ...} structure and %Rlin notations showing), but users should   *)\n(*    beware that in (a *: f u)%Rlin, a actually occurs in the f u subterm.   *)\n(* -> The simpler linear_LR, or more specialized linearZZ and scalarZ rules   *)\n(*    should be used instead of linearZ if there are complexity issues, as    *)\n(*    well as for explicit forward and backward application, as the main      *)\n(*    parameter of linearZ is a proper sub-interface of {linear fUV | s}.     *)\n(*                                                                            *)\n(* * LRMorphism (linear ring morphisms, i.e., algebra morphisms):             *)\n(*           lrmorphism f <-> f of type A -> B is a linear Ring (Algebra)     *)\n(*                           morphism: f is both additive, multiplicative and *)\n(*                           scalable. A and B must both have lalgType R      *)\n(*                           canonical structures, for the same ringType R.   *)\n(*     lrmorphism_for s f <-> f a linear Ring morphism for the scaling        *)\n(*                           operator s: f is additive, multiplicative and    *)\n(*                           scalable for s. A must be an lalgType R, but B   *)\n(*                           only needs to have a ringType structure.         *)\n(*    {lrmorphism A -> B} == the interface type for linear morphisms, i.e., a *)\n(*                           Structure that encapsulates the lrmorphism       *)\n(*                           property for functions f : A -> B; both A and B  *)\n(*                           must have lalgType R structures, for the same R. *)\n(* {lrmorphism A -> B | s} == the interface type for morphisms linear for s.  *)\n(*   LRmorphism lrmorph_f == packs lrmorph_f : lrmorphism_for s f into a      *)\n(*                           linear morphism structure of type                *)\n(*                           {lrmorphism A -> B | s}. Like Linear, LRmorphism *)\n(*                           can be used transparently for lrmorphism f.      *)\n(*   AddLRmorphism scal_f == packs scal_f : scalable_for s f into a linear    *)\n(*                           morphism structure of type                       *)\n(*                           {lrmorphism A -> B | s}; f must already have an  *)\n(*                           {rmorphism A -> B} structure, and AddLRmorphism  *)\n(*                           can be applied to a linear_for s f, linear f,    *)\n(*                           scalar f, etc argument, like AddLinear.          *)\n(*      [lrmorphism of f] == creates an lrmorphism structure from existing    *)\n(*                           rmorphism and linear structures on f; this is    *)\n(*                           the preferred way of creating lrmorphism         *)\n(*                           structures.                                      *)\n(*  -> Linear and rmorphism properties do not need to be specialized for      *)\n(*     as we supply inheritance join instances in both directions.            *)\n(* Finally we supply some helper notation for morphisms:                      *)\n(*                    x^f == the image of x under some morphism. This         *)\n(*                           notation is only reserved (not defined) here;    *)\n(*                           it is bound locally in sections where some       *)\n(*                           morphism is used heavily (e.g., the container    *)\n(*                           morphism in the parametricity sections of poly   *)\n(*                           and matrix, or the Frobenius section here).      *)\n(*                     \\0 == the constant null function, which has a          *)\n(*                           canonical linear structure, and simplifies on    *)\n(*                           application (see ssrfun.v).                      *)\n(*                 f \\+ g == the additive composition of f and g, i.e., the   *)\n(*                           function x |-> f x + g x; f \\+ g is canonically  *)\n(*                           linear when f and g are, and simplifies on       *)\n(*                           application (see ssrfun.v).                      *)\n(*                 f \\- g == the function x |-> f x - g x, canonically        *)\n(*                           linear when f and g are, and simplifies on       *)\n(*                           application.                                     *)\n(*                   \\- g == the function x |-> - f x, canonically linear     *)\n(*                           when f is, and simplifies on application.        *)\n(*                k \\*: f == the function x |-> k *: f x, which is            *)\n(*                           canonically linear when f is and simplifies on   *)\n(*                           application (this is a shorter alternative to    *)\n(*                           *:%R k \\o f).                                    *)\n(*         GRing.in_alg A == the ring morphism that injects R into A, where A *)\n(*                           has an lalgType R structure; GRing.in_alg A k    *)\n(*                           simplifies to k%:A.                              *)\n(*                a \\*o f == the function x |-> a * f x, canonically linear   *)\n(*                           linear when f is and its codomain is an algType  *)\n(*                           and which simplifies on application.             *)\n(*                a \\o* f == the function x |-> f x * a, canonically linear   *)\n(*                           linear when f is and its codomain is an lalgType *)\n(*                           and which simplifies on application.             *)\n(*                 f \\* g == the function x |-> f x * g x; f \\* g simplifies  *)\n(*                           on application.                                  *)\n(* The Lemmas about these structures are contained in both the GRing module   *)\n(* and in the submodule GRing.Theory, which can be imported when unqualified  *)\n(* access to the theory is needed (GRing.Theory also allows the unqualified   *)\n(* use of additive, linear, Linear, etc). The main GRing module should NOT be *)\n(* imported.                                                                  *)\n(*   Notations are defined in scope ring_scope (delimiter %R), except term    *)\n(* and formula notations, which are in term_scope (delimiter %T).             *)\n(*   This library also extends the conventional suffixes described in library *)\n(* ssrbool.v with the following:                                              *)\n(*   0 -- ring 0, as in addr0 : x + 0 = x.                                    *)\n(*   1 -- ring 1, as in mulr1 : x * 1 = x.                                    *)\n(*   D -- ring addition, as in linearD : f (u + v) = f u + f v.               *)\n(*   B -- ring subtraction, as in opprB : - (x - y) = y - x.                  *)\n(*   M -- ring multiplication, as in invfM : (x * y)^-1 = x^-1 * y^-1.        *)\n(*  Mn -- ring by nat multiplication, as in raddfMn : f (x *+ n) = f x *+ n.  *)\n(*   N -- ring opposite, as in mulNr : (- x) * y = - (x * y).                 *)\n(*   V -- ring inverse, as in mulVr : x^-1 * x = 1.                           *)\n(*   X -- ring exponentiation, as in rmorphX : f (x ^+ n) = f x ^+ n.         *)\n(*   Z -- (left) module scaling, as in linearZ : f (a *: v)  = s *: f v.      *)\n(* The operator suffixes D, B, M and X are also used for the corresponding    *)\n(* operations on nat, as in natrX : (m ^ n)%:R = m%:R ^+ n. For the binary    *)\n(* power operator, a trailing \"n\" suffix is used to indicate the operator     *)\n(* suffix applies to the left-hand ring argument, as in                       *)\n(*   expr1n : 1 ^+ n = 1 vs. expr1 : x ^+ 1 = x.                              *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDeclare Scope ring_scope.\nDeclare Scope term_scope.\nDeclare Scope linear_ring_scope.\n\nReserved Notation \"+%R\" (at level 0).\nReserved Notation \"-%R\" (at level 0).\nReserved Notation \"*%R\" (at level 0, format \" *%R\").\nReserved Notation \"*:%R\" (at level 0, format \" *:%R\").\nReserved Notation \"n %:R\" (at level 2, left associativity, format \"n %:R\").\nReserved Notation \"k %:A\" (at level 2, left associativity, format \"k %:A\").\nReserved Notation \"[ 'char' F ]\" (at level 0, format \"[ 'char'  F ]\").\n\nReserved Notation \"x %:T\" (at level 2, left associativity, format \"x %:T\").\nReserved Notation \"''X_' i\" (at level 8, i at level 2, format \"''X_' i\").\n(* Patch for recurring Coq parser bug: Coq seg faults when a level 200 *)\n(* notation is used as a pattern.                                      *)\nReserved Notation \"''exists' ''X_' i , f\"\n  (at level 199, i at level 2, right associativity,\n   format \"'[hv' ''exists'  ''X_' i , '/ '  f ']'\").\nReserved Notation \"''forall' ''X_' i , f\"\n  (at level 199, i at level 2, right associativity,\n   format \"'[hv' ''forall'  ''X_' i , '/ '  f ']'\").\n\nReserved Notation \"x ^f\" (at level 2, left associativity, format \"x ^f\").\n\nReserved Notation \"\\0\" (at level 0).\nReserved Notation \"f \\+ g\" (at level 50, left associativity).\nReserved Notation \"f \\- g\" (at level 50, left associativity).\nReserved Notation \"\\- f\" (at level 35, f at level 35).\nReserved Notation \"a \\*o f\" (at level 40).\nReserved Notation \"a \\o* f\" (at level 40).\nReserved Notation \"a \\*: f\" (at level 40).\nReserved Notation \"f \\* g\" (at level 40, left associativity).\n\nDelimit Scope ring_scope with R.\nDelimit Scope term_scope with T.\nLocal Open Scope ring_scope.\n\nModule Import GRing.\n\nImport Monoid.Theory.\n\nModule Zmodule.\n\nRecord mixin_of (V : Type) : Type := Mixin {\n  zero : V;\n  opp : V -> V;\n  add : V -> V -> V;\n  _ : associative add;\n  _ : commutative add;\n  _ : left_id zero add;\n  _ : left_inverse zero opp add\n}.\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of T := Class { base : Choice.class_of T; mixin : mixin_of T }.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> Choice.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c.\n\nDefinition pack m :=\n  fun bT b & phant_id (Choice.class bT) b => Pack (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Choice.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nNotation zmodType := type.\nNotation ZmodType T m := (@pack T m _ _ id).\nNotation ZmodMixin := Mixin.\nNotation \"[ 'zmodType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'zmodType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'zmodType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'zmodType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Zmodule.\nImport Zmodule.Exports.\n\nDefinition zero V := Zmodule.zero (Zmodule.class V).\nDefinition opp V := Zmodule.opp (Zmodule.class V).\nDefinition add V := Zmodule.add (Zmodule.class V).\n\nLocal Notation \"0\" := (zero _) : ring_scope.\nLocal Notation \"-%R\" := (@opp _) : fun_scope.\nLocal Notation \"- x\" := (opp x) : ring_scope.\nLocal Notation \"+%R\" := (@add _) : fun_scope.\nLocal Notation \"x + y\" := (add x y) : ring_scope.\nLocal Notation \"x - y\" := (x + - y) : ring_scope.\n\nDefinition natmul V x n := nosimpl iterop _ n +%R x (zero V).\n\nLocal Notation \"x *+ n\" := (natmul x n) : ring_scope.\nLocal Notation \"x *- n\" := (- (x *+ n)) : ring_scope.\n\nLocal Notation \"\\sum_ ( i <- r | P ) F\" := (\\big[+%R/0]_(i <- r | P) F).\nLocal Notation \"\\sum_ ( m <= i < n ) F\" := (\\big[+%R/0]_(m <= i < n) F).\nLocal Notation \"\\sum_ ( i < n ) F\" := (\\big[+%R/0]_(i < n) F).\nLocal Notation \"\\sum_ ( i 'in' A ) F\" := (\\big[+%R/0]_(i in A) F).\n\nLocal Notation \"s `_ i\" := (nth 0 s i) : ring_scope.\n\nSection ZmoduleTheory.\n\nVariable V : zmodType.\nImplicit Types x y : V.\n\nLemma addrA : @associative V +%R. Proof. by case V => T [? []]. Qed.\nLemma addrC : @commutative V V +%R. Proof. by case V => T [? []]. Qed.\nLemma add0r : @left_id V V 0 +%R. Proof. by case V => T [? []]. Qed.\nLemma addNr : @left_inverse V V V 0 -%R +%R. Proof. by case V => T [? []]. Qed.\n\nLemma addr0 : @right_id V V 0 +%R.\nProof. by move=> x; rewrite addrC add0r. Qed.\nLemma addrN : @right_inverse V V V 0 -%R +%R.\nProof. by move=> x; rewrite addrC addNr. Qed.\nDefinition subrr := addrN.\n\nCanonical add_monoid := Monoid.Law addrA add0r addr0.\nCanonical add_comoid := Monoid.ComLaw addrC.\n\nLemma addrCA : @left_commutative V V +%R. Proof. exact: mulmCA. Qed.\nLemma addrAC : @right_commutative V V +%R. Proof. exact: mulmAC. Qed.\nLemma addrACA : @interchange V +%R +%R. Proof. exact: mulmACA. Qed.\n\nLemma addKr : @left_loop V V -%R +%R.\nProof. by move=> x y; rewrite addrA addNr add0r. Qed.\nLemma addNKr : @rev_left_loop V V -%R +%R.\nProof. by move=> x y; rewrite addrA addrN add0r. Qed.\nLemma addrK : @right_loop V V -%R +%R.\nProof. by move=> x y; rewrite -addrA addrN addr0. Qed.\nLemma addrNK : @rev_right_loop V V -%R +%R.\nProof. by move=> x y; rewrite -addrA addNr addr0. Qed.\nDefinition subrK := addrNK.\nLemma subKr x : involutive (fun y => x - y).\nProof. by move=> y; apply: (canLR (addrK _)); rewrite addrC subrK. Qed.\nLemma addrI : @right_injective V V V +%R.\nProof. by move=> x; apply: can_inj (addKr x). Qed.\nLemma addIr : @left_injective V V V +%R.\nProof. by move=> y; apply: can_inj (addrK y). Qed.\nLemma subrI : right_injective (fun x y => x - y).\nProof. by move=> x; apply: can_inj (subKr x). Qed.\nLemma subIr : left_injective (fun x y => x - y).\nProof. by move=> y; apply: addIr. Qed.\nLemma opprK : @involutive V -%R.\nProof. by move=> x; apply: (@subIr x); rewrite addNr addrN. Qed.\nLemma oppr_inj : @injective V V -%R.\nProof. exact: inv_inj opprK. Qed.\nLemma oppr0 : -0 = 0 :> V.\nProof. by rewrite -[-0]add0r subrr. Qed.\nLemma oppr_eq0 x : (- x == 0) = (x == 0).\nProof. by rewrite (inv_eq opprK) oppr0. Qed.\n\nLemma subr0 x : x - 0 = x. Proof. by rewrite oppr0 addr0. Qed.\nLemma sub0r x : 0 - x = - x. Proof. by rewrite add0r. Qed.\n\nLemma opprB x y : - (x - y) = y - x.\nProof. by apply: (canRL (addrK x)); rewrite addrC subKr. Qed.\n\nLemma opprD : {morph -%R: x y / x + y : V}.\nProof. by move=> x y; rewrite -[y in LHS]opprK opprB addrC. Qed.\n\nLemma addrKA z x y : (x + z) - (z + y) = x - y.\nProof. by rewrite opprD addrA addrK. Qed.\n\nLemma subrKA z x y : (x - z) + (z + y) = x + y.\nProof. by rewrite addrA addrNK. Qed.\n\nLemma addr0_eq x y : x + y = 0 -> - x = y.\nProof. by rewrite -[-x]addr0 => <-; rewrite addKr. Qed.\n\nLemma subr0_eq x y : x - y = 0 -> x = y. Proof. by move/addr0_eq/oppr_inj. Qed.\n\nLemma subr_eq x y z : (x - z == y) = (x == y + z).\nProof. exact: can2_eq (subrK z) (addrK z) x y. Qed.\n\nLemma subr_eq0 x y : (x - y == 0) = (x == y).\nProof. by rewrite subr_eq add0r. Qed.\n\nLemma addr_eq0 x y : (x + y == 0) = (x == - y).\nProof. by rewrite -[y in LHS]opprK subr_eq0. Qed.\n\nLemma eqr_opp x y : (- x == - y) = (x == y).\nProof. exact: can_eq opprK x y. Qed.\n\nLemma eqr_oppLR x y : (- x == y) = (x == - y).\nProof. exact: inv_eq opprK x y. Qed.\n\nLemma mulr0n x : x *+ 0 = 0. Proof. by []. Qed.\nLemma mulr1n x : x *+ 1 = x. Proof. by []. Qed.\nLemma mulr2n x : x *+ 2 = x + x. Proof. by []. Qed.\n\nLemma mulrS x n : x *+ n.+1 = x + x *+ n.\nProof. by case: n => //=; rewrite addr0. Qed.\n\nLemma mulrSr x n : x *+ n.+1 = x *+ n + x.\nProof. by rewrite addrC mulrS. Qed.\n\nLemma mulrb x (b : bool) : x *+ b = (if b then x else 0).\nProof. by case: b. Qed.\n\nLemma mul0rn n : 0 *+ n = 0 :> V.\nProof. by elim: n => // n IHn; rewrite mulrS add0r. Qed.\n\nLemma mulNrn x n : (- x) *+ n = x *- n.\nProof. by elim: n => [|n IHn]; rewrite ?oppr0 // !mulrS opprD IHn. Qed.\n\nLemma mulrnDl n : {morph (fun x => x *+ n) : x y / x + y}.\nProof.\nmove=> x y; elim: n => [|n IHn]; rewrite ?addr0 // !mulrS.\nby rewrite addrCA -!addrA -IHn -addrCA.\nQed.\n\nLemma mulrnDr x m n : x *+ (m + n) = x *+ m + x *+ n.\nProof.\nelim: m => [|m IHm]; first by rewrite add0r.\nby rewrite !mulrS IHm addrA.\nQed.\n\nLemma mulrnBl n : {morph (fun x => x *+ n) : x y / x - y}.\nProof.\nmove=> x y; elim: n => [|n IHn]; rewrite ?subr0 // !mulrS -!addrA; congr(_ + _).\nby rewrite addrC IHn -!addrA opprD [_ - y]addrC.\nQed.\n\nLemma mulrnBr x m n : n <= m -> x *+ (m - n) = x *+ m - x *+ n.\nProof.\nelim: m n => [|m IHm] [|n le_n_m]; rewrite ?subr0 // {}IHm //.\nby rewrite mulrSr mulrS opprD addrA addrK.\nQed.\n\nLemma mulrnA x m n : x *+ (m * n) = x *+ m *+ n.\nProof.\nby rewrite mulnC; elim: n => //= n IHn; rewrite mulrS mulrnDr IHn.\nQed.\n\nLemma mulrnAC x m n : x *+ m *+ n = x *+ n *+ m.\nProof. by rewrite -!mulrnA mulnC. Qed.\n\nLemma iter_addr n x y : iter n (+%R x) y = x *+ n + y.\nProof. by elim: n => [|n ih]; rewrite ?add0r //= ih mulrS addrA. Qed.\n\nLemma iter_addr_0 n x : iter n (+%R x) 0 = x *+ n.\nProof. by rewrite iter_addr addr0. Qed.\n\nLemma sumrN I r P (F : I -> V) :\n  (\\sum_(i <- r | P i) - F i = - (\\sum_(i <- r | P i) F i)).\nProof. by rewrite (big_morph _ opprD oppr0). Qed.\n\nLemma sumrB I r (P : pred I) (F1 F2 : I -> V) :\n  \\sum_(i <- r | P i) (F1 i - F2 i)\n     = \\sum_(i <- r | P i) F1 i - \\sum_(i <- r | P i) F2 i.\nProof. by rewrite -sumrN -big_split /=. Qed.\n\nLemma sumrMnl I r P (F : I -> V) n :\n  \\sum_(i <- r | P i) F i *+ n = (\\sum_(i <- r | P i) F i) *+ n.\nProof. by rewrite (big_morph _ (mulrnDl n) (mul0rn _)). Qed.\n\nLemma sumrMnr x I r P (F : I -> nat) :\n  \\sum_(i <- r | P i) x *+ F i = x *+ (\\sum_(i <- r | P i) F i).\nProof. by rewrite (big_morph _ (mulrnDr x) (erefl _)). Qed.\n\nLemma sumr_const (I : finType) (A : pred I) x : \\sum_(i in A) x = x *+ #|A|.\nProof. by rewrite big_const -iteropE. Qed.\n\nLemma sumr_const_nat m n x : \\sum_(n <= i < m) x = x *+ (m - n).\nProof. by rewrite big_const_nat iter_addr_0. Qed.\n\nLemma telescope_sumr n m (f : nat -> V) : n <= m ->\n  \\sum_(n <= k < m) (f k.+1 - f k) = f m - f n.\nProof.\nmove=> nm; rewrite (telescope_big (fun i j => f j - f i)).\n  by case: ltngtP nm => // ->; rewrite subrr.\nby move=> k /andP[nk km]/=; rewrite addrC subrKA.\nQed.\n\nLemma telescope_sumr_eq n m (f u : nat -> V) : n <= m ->\n    (forall k, (n <= k < m)%N -> u k = f k.+1 - f k) ->\n  \\sum_(n <= k < m) u k = f m - f n.\nProof.\nby move=> ? uE; under eq_big_nat do rewrite uE //=; exact: telescope_sumr.\nQed.\n\nSection ClosedPredicates.\n\nVariable S : {pred V}.\n\nDefinition addr_closed := 0 \\in S /\\ {in S &, forall u v, u + v \\in S}.\nDefinition oppr_closed := {in S, forall u, - u \\in S}.\nDefinition subr_2closed := {in S &, forall u v, u - v \\in S}.\nDefinition zmod_closed := 0 \\in S /\\ subr_2closed.\n\nLemma zmod_closedN : zmod_closed -> oppr_closed.\nProof. by case=> S0 SB y Sy; rewrite -sub0r !SB. Qed.\n\nLemma zmod_closedD : zmod_closed -> addr_closed.\nProof.\nby case=> S0 SB; split=> // y z Sy Sz; rewrite -[z]opprK -[- z]sub0r !SB.\nQed.\n\nEnd ClosedPredicates.\n\nEnd ZmoduleTheory.\n\nArguments addrI {V} y [x1 x2].\nArguments addIr {V} x [x1 x2].\nArguments opprK {V}.\nArguments oppr_inj {V} [x1 x2].\nArguments telescope_sumr_eq {V n m} f u.\n\nModule Ring.\n\nRecord mixin_of (R : zmodType) : Type := Mixin {\n  one : R;\n  mul : R -> R -> R;\n  _ : associative mul;\n  _ : left_id one mul;\n  _ : right_id one mul;\n  _ : left_distributive mul +%R;\n  _ : right_distributive mul +%R;\n  _ : one != 0\n}.\n\nDefinition EtaMixin R one mul mulA mul1x mulx1 mul_addl mul_addr nz1 :=\n  let _ := @Mixin R one mul mulA mul1x mulx1 mul_addl mul_addr nz1 in\n  @Mixin (Zmodule.Pack (Zmodule.class R)) _ _\n     mulA mul1x mulx1 mul_addl mul_addr nz1.\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of (R : Type) : Type := Class {\n  base : Zmodule.class_of R;\n  mixin : mixin_of (Zmodule.Pack base)\n}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> Zmodule.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c.\n\nDefinition pack b0 (m0 : mixin_of (@Zmodule.Pack T b0)) :=\n  fun bT b & phant_id (Zmodule.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Zmodule.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nNotation ringType := type.\nNotation RingType T m := (@pack T _ m _ _ id _ id).\nNotation RingMixin := Mixin.\nNotation \"[ 'ringType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'ringType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'ringType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'ringType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Ring.\nImport Ring.Exports.\n\nDefinition one (R : ringType) : R := Ring.one (Ring.class R).\nDefinition mul (R : ringType) : R -> R -> R := Ring.mul (Ring.class R).\nDefinition exp R x n := nosimpl iterop _ n (@mul R) x (one R).\nNotation sign R b := (exp (- one R) (nat_of_bool b)) (only parsing).\nDefinition comm R x y := @mul R x y = mul y x.\nDefinition lreg R x := injective (@mul R x).\nDefinition rreg R x := injective ((@mul R)^~ x).\n\nLocal Notation \"1\" := (one _) : ring_scope.\nLocal Notation \"- 1\" := (- (1)) : ring_scope.\nLocal Notation \"n %:R\" := (1 *+ n) : ring_scope.\nLocal Notation \"*%R\" := (@mul _) : fun_scope.\nLocal Notation \"x * y\" := (mul x y) : ring_scope.\nLocal Notation \"x ^+ n\" := (exp x n) : ring_scope.\n\nLocal Notation \"\\prod_ ( i <- r | P ) F\" := (\\big[*%R/1]_(i <- r | P) F).\nLocal Notation \"\\prod_ ( i | P ) F\" := (\\big[*%R/1]_(i | P) F).\nLocal Notation \"\\prod_ ( i 'in' A ) F\" := (\\big[*%R/1]_(i in A) F).\nLocal Notation \"\\prod_ ( m <= i < n ) F\" := (\\big[*%R/1%R]_(m <= i < n) F%R).\n\n(* The ``field'' characteristic; the definition, and many of the theorems,   *)\n(* has to apply to rings as well; indeed, we need the Frobenius automorphism *)\n(* results for a non commutative ring in the proof of Gorenstein 2.6.3.      *)\nDefinition char (R : Ring.type) of phant R : nat_pred :=\n  [pred p | prime p & p%:R == 0 :> R].\n\nLocal Notation \"[ 'char' R ]\" := (char (Phant R)) : ring_scope.\n\n(* Converse ring tag. *)\nDefinition converse R : Type := R.\nLocal Notation \"R ^c\" := (converse R) (at level 2, format \"R ^c\") : type_scope.\n\nSection RingTheory.\n\nVariable R : ringType.\nImplicit Types x y : R.\n\nLemma mulrA : @associative R *%R. Proof. by case R => T [? []]. Qed.\nLemma mul1r : @left_id R R 1 *%R. Proof. by case R => T [? []]. Qed.\nLemma mulr1 : @right_id R R 1 *%R. Proof. by case R => T [? []]. Qed.\nLemma mulrDl : @left_distributive R R *%R +%R.\nProof. by case R => T [? []]. Qed.\nLemma mulrDr : @right_distributive R R *%R +%R.\nProof. by case R => T [? []]. Qed.\nLemma oner_neq0 : 1 != 0 :> R. Proof. by case R => T [? []]. Qed.\nLemma oner_eq0 : (1 == 0 :> R) = false. Proof. exact: negbTE oner_neq0. Qed.\n\nLemma mul0r : @left_zero R R 0 *%R.\nProof.\nby move=> x; apply: (addIr (1 * x)); rewrite -mulrDl !add0r mul1r.\nQed.\nLemma mulr0 : @right_zero R R 0 *%R.\nProof.\nby move=> x; apply: (addIr (x * 1)); rewrite -mulrDr !add0r mulr1.\nQed.\nLemma mulrN x y : x * (- y) = - (x * y).\nProof. by apply: (addrI (x * y)); rewrite -mulrDr !subrr mulr0. Qed.\nLemma mulNr x y : (- x) * y = - (x * y).\nProof. by apply: (addrI (x * y)); rewrite -mulrDl !subrr mul0r. Qed.\nLemma mulrNN x y : (- x) * (- y) = x * y.\nProof. by rewrite mulrN mulNr opprK. Qed.\nLemma mulN1r x : -1 * x = - x.\nProof. by rewrite mulNr mul1r. Qed.\nLemma mulrN1 x : x * -1 = - x.\nProof. by rewrite mulrN mulr1. Qed.\n\nCanonical mul_monoid := Monoid.Law mulrA mul1r mulr1.\nCanonical muloid := Monoid.MulLaw mul0r mulr0.\nCanonical addoid := Monoid.AddLaw mulrDl mulrDr.\n\nLemma mulr_suml I r P (F : I -> R) x :\n  (\\sum_(i <- r | P i) F i) * x = \\sum_(i <- r | P i) F i * x.\nProof. exact: big_distrl. Qed.\n\nLemma mulr_sumr I r P (F : I -> R) x :\n  x * (\\sum_(i <- r | P i) F i) = \\sum_(i <- r | P i) x * F i.\nProof. exact: big_distrr. Qed.\n\nLemma mulrBl x y z : (y - z) * x = y * x - z * x.\nProof. by rewrite mulrDl mulNr. Qed.\n\nLemma mulrBr x y z : x * (y - z) = x * y - x * z.\nProof. by rewrite mulrDr mulrN. Qed.\n\nLemma mulrnAl x y n : (x *+ n) * y = (x * y) *+ n.\nProof. by elim: n => [|n IHn]; rewrite ?mul0r // !mulrS mulrDl IHn. Qed.\n\nLemma mulrnAr x y n : x * (y *+ n) = (x * y) *+ n.\nProof. by elim: n => [|n IHn]; rewrite ?mulr0 // !mulrS mulrDr IHn. Qed.\n\nLemma mulr_natl x n : n%:R * x = x *+ n.\nProof. by rewrite mulrnAl mul1r. Qed.\n\nLemma mulr_natr x n : x * n%:R = x *+ n.\nProof. by rewrite mulrnAr mulr1. Qed.\n\nLemma natrD m n : (m + n)%:R = m%:R + n%:R :> R.\nProof. exact: mulrnDr. Qed.\n\nLemma natr1 n : n%:R + 1 = n.+1%:R :> R. Proof. by rewrite mulrSr. Qed.\n\nLemma nat1r n : 1 + n%:R = n.+1%:R :> R. Proof. by rewrite mulrS. Qed.\n\nLemma natrB m n : n <= m -> (m - n)%:R = m%:R - n%:R :> R.\nProof. exact: mulrnBr. Qed.\n\nDefinition natr_sum := big_morph (natmul 1) natrD (mulr0n 1).\n\nLemma natrM m n : (m * n)%:R = m%:R * n%:R :> R.\nProof. by rewrite mulrnA -mulr_natr. Qed.\n\nLemma expr0 x : x ^+ 0 = 1. Proof. by []. Qed.\nLemma expr1 x : x ^+ 1 = x. Proof. by []. Qed.\nLemma expr2 x : x ^+ 2 = x * x. Proof. by []. Qed.\n\nLemma exprS x n : x ^+ n.+1 = x * x ^+ n.\nProof. by case: n => //; rewrite mulr1. Qed.\n\nLemma expr0n n : 0 ^+ n = (n == 0%N)%:R :> R.\nProof. by case: n => // n; rewrite exprS mul0r. Qed.\n\nLemma expr1n n : 1 ^+ n = 1 :> R.\nProof. by elim: n => // n IHn; rewrite exprS mul1r. Qed.\n\nLemma exprD x m n : x ^+ (m + n) = x ^+ m * x ^+ n.\nProof. by elim: m => [|m IHm]; rewrite ?mul1r // !exprS -mulrA -IHm. Qed.\n\nLemma exprSr x n : x ^+ n.+1 = x ^+ n * x.\nProof. by rewrite -addn1 exprD expr1. Qed.\n\nLemma expr_sum x (I : Type) (s : seq I) (P : pred I) F :\n  x ^+ (\\sum_(i <- s | P i) F i) = \\prod_(i <- s | P i) x ^+ F i :> R.\nProof. exact: (big_morph _ (exprD _)). Qed.\n\nLemma commr_sym x y : comm x y -> comm y x. Proof. by []. Qed.\nLemma commr_refl x : comm x x. Proof. by []. Qed.\n\nLemma commr0 x : comm x 0.\nProof. by rewrite /comm mulr0 mul0r. Qed.\n\nLemma commr1 x : comm x 1.\nProof. by rewrite /comm mulr1 mul1r. Qed.\n\nLemma commrN x y : comm x y -> comm x (- y).\nProof. by move=> com_xy; rewrite /comm mulrN com_xy mulNr. Qed.\n\nLemma commrN1 x : comm x (-1).\nProof. exact/commrN/commr1. Qed.\n\nLemma commrD x y z : comm x y -> comm x z -> comm x (y + z).\nProof. by rewrite /comm mulrDl mulrDr => -> ->. Qed.\n\nLemma commrB x y z : comm x y -> comm x z -> comm x (y - z).\nProof. by move=> com_xy com_xz; apply: commrD => //; apply: commrN. Qed.\n\nLemma commr_sum (I : Type) (s : seq I) (P : pred I) (F : I -> R) x :\n  (forall i, P i -> comm x (F i)) -> comm x (\\sum_(i <- s | P i) F i).\nProof.\nmove=> comm_x_F; rewrite /comm mulr_suml mulr_sumr.\nby apply: eq_bigr => i /comm_x_F.\nQed.\n\nLemma commrMn x y n : comm x y -> comm x (y *+ n).\nProof.\nrewrite /comm => com_xy.\nby elim: n => [|n IHn]; rewrite ?commr0 // mulrS commrD.\nQed.\n\nLemma commrM x y z : comm x y -> comm x z -> comm x (y * z).\nProof. by move=> com_xy; rewrite /comm mulrA com_xy -!mulrA => ->. Qed.\n\nLemma commr_prod (I : Type) (s : seq I) (P : pred I) (F : I -> R) x :\n  (forall i, P i -> comm x (F i)) -> comm x (\\prod_(i <- s | P i) F i).\nProof. exact: (big_ind _ (commr1 x) (@commrM x)). Qed.\n\nLemma commr_nat x n : comm x n%:R.\nProof. exact/commrMn/commr1. Qed.\n\nLemma commrX x y n : comm x y -> comm x (y ^+ n).\nProof.\nrewrite /comm => com_xy.\nby elim: n => [|n IHn]; rewrite ?commr1 // exprS commrM.\nQed.\n\nLemma exprMn_comm x y n : comm x y -> (x * y) ^+ n = x ^+ n * y ^+ n.\nProof.\nmove=> com_xy; elim: n => /= [|n IHn]; first by rewrite mulr1.\nby rewrite !exprS IHn !mulrA; congr (_ * _); rewrite -!mulrA -commrX.\nQed.\n\nLemma commr_sign x n : comm x ((-1) ^+ n).\nProof. exact: (commrX n (commrN1 x)). Qed.\n\nLemma exprMn_n x m n : (x *+ m) ^+ n = x ^+ n *+ (m ^ n) :> R.\nProof.\nelim: n => [|n IHn]; first by rewrite mulr1n.\nrewrite exprS IHn -mulr_natr -mulrA -commr_nat mulr_natr -mulrnA -expnSr.\nby rewrite -mulr_natr mulrA -exprS mulr_natr.\nQed.\n\nLemma exprM x m n : x ^+ (m * n) = x ^+ m ^+ n.\nProof.\nelim: m => [|m IHm]; first by rewrite expr1n.\nby rewrite mulSn exprD IHm exprS exprMn_comm //; apply: commrX.\nQed.\n\nLemma exprAC x m n : (x ^+ m) ^+ n = (x ^+ n) ^+ m.\nProof. by rewrite -!exprM mulnC. Qed.\n\nLemma expr_mod n x i : x ^+ n = 1 -> x ^+ (i %% n) = x ^+ i.\nProof.\nmove=> xn1; rewrite {2}(divn_eq i n) exprD mulnC exprM xn1.\nby rewrite expr1n mul1r.\nQed.\n\nLemma expr_dvd n x i : x ^+ n = 1 -> n %| i -> x ^+ i = 1.\nProof.\nby move=> xn1 dvd_n_i; rewrite -(expr_mod i xn1) (eqnP dvd_n_i).\nQed.\n\nLemma natrX n k : (n ^ k)%:R = n%:R ^+ k :> R.\nProof. by rewrite exprMn_n expr1n. Qed.\n\nLemma signr_odd n : (-1) ^+ (odd n) = (-1) ^+ n :> R.\nProof.\nelim: n => //= n IHn; rewrite exprS -{}IHn.\nby case/odd: n; rewrite !mulN1r ?opprK.\nQed.\n\nLemma signr_eq0 n : ((-1) ^+ n == 0 :> R) = false.\nProof. by rewrite -signr_odd; case: odd; rewrite ?oppr_eq0 oner_eq0. Qed.\n\nLemma mulr_sign (b : bool) x : (-1) ^+ b * x = (if b then - x else x).\nProof. by case: b; rewrite ?mulNr mul1r. Qed.\n\nLemma signr_addb b1 b2 : (-1) ^+ (b1 (+) b2) = (-1) ^+ b1 * (-1) ^+ b2 :> R.\nProof. by rewrite mulr_sign; case: b1 b2 => [] []; rewrite ?opprK. Qed.\n\nLemma signrE (b : bool) : (-1) ^+ b = 1 - b.*2%:R :> R.\nProof. by case: b; rewrite ?subr0 // opprD addNKr. Qed.\n\nLemma signrN b : (-1) ^+ (~~ b) = - (-1) ^+ b :> R.\nProof. by case: b; rewrite ?opprK. Qed.\n\nLemma mulr_signM (b1 b2 : bool) x1 x2 :\n  ((-1) ^+ b1 * x1) * ((-1) ^+ b2 * x2) = (-1) ^+ (b1 (+) b2) * (x1 * x2).\nProof.\nby rewrite signr_addb -!mulrA; congr (_ * _); rewrite !mulrA commr_sign.\nQed.\n\nLemma exprNn x n : (- x) ^+ n = (-1) ^+ n * x ^+ n :> R.\nProof. by rewrite -mulN1r exprMn_comm // /comm mulN1r mulrN mulr1. Qed.\n\nLemma sqrrN x : (- x) ^+ 2 = x ^+ 2.\nProof. exact: mulrNN. Qed.\n\nLemma sqrr_sign n : ((-1) ^+ n) ^+ 2 = 1 :> R.\nProof. by rewrite exprAC sqrrN !expr1n. Qed.\n\nLemma signrMK n : @involutive R ( *%R ((-1) ^+ n)).\nProof. by move=> x; rewrite mulrA -expr2 sqrr_sign mul1r. Qed.\n\nLemma lastr_eq0 (s : seq R) x : x != 0 -> (last x s == 0) = (last 1 s == 0).\nProof. by case: s => [|y s] /negPf // ->; rewrite oner_eq0. Qed.\n\nLemma mulrI_eq0 x y : lreg x -> (x * y == 0) = (y == 0).\nProof. by move=> reg_x; rewrite -{1}(mulr0 x) (inj_eq reg_x). Qed.\n\nLemma lreg_neq0 x : lreg x -> x != 0.\nProof. by move=> reg_x; rewrite -[x]mulr1 mulrI_eq0 ?oner_eq0. Qed.\n\nLemma mulrI0_lreg x : (forall y, x * y = 0 -> y = 0) -> lreg x.\nProof.\nmove=> reg_x y z eq_xy_xz; apply/eqP; rewrite -subr_eq0 [y - z]reg_x //.\nby rewrite mulrBr eq_xy_xz subrr.\nQed.\n\nLemma lregN x : lreg x -> lreg (- x).\nProof. by move=> reg_x y z; rewrite !mulNr => /oppr_inj/reg_x. Qed.\n\nLemma lreg1 : lreg (1 : R).\nProof. by move=> x y; rewrite !mul1r. Qed.\n\nLemma lregM x y : lreg x -> lreg y -> lreg (x * y).\nProof. by move=> reg_x reg_y z t; rewrite -!mulrA => /reg_x/reg_y. Qed.\n\nLemma lregMl (a b: R) : lreg (a * b) -> lreg b.\nProof. by move=> rab c c' eq_bc; apply/rab; rewrite -!mulrA eq_bc. Qed.\n\nLemma rregMr (a b: R) : rreg (a * b) -> rreg a.\nProof. by move=> rab c c' eq_ca; apply/rab; rewrite !mulrA eq_ca. Qed.\n\nLemma lregX x n : lreg x -> lreg (x ^+ n).\nProof.\nby move=> reg_x; elim: n => [|n]; [apply: lreg1 | rewrite exprS; apply: lregM].\nQed.\n\nLemma lreg_sign n : lreg ((-1) ^+ n : R). Proof. exact/lregX/lregN/lreg1. Qed.\n\nLemma iter_mulr n x y : iter n ( *%R x) y = x ^+ n * y.\nProof. by elim: n => [|n ih]; rewrite ?expr0 ?mul1r //= ih exprS -mulrA. Qed.\n\nLemma iter_mulr_1 n x : iter n ( *%R x) 1 = x ^+ n.\nProof. by rewrite iter_mulr mulr1. Qed.\n\nLemma prodr_const (I : finType) (A : pred I) x : \\prod_(i in A) x = x ^+ #|A|.\nProof. by rewrite big_const -iteropE. Qed.\n\nLemma prodr_const_nat n m x : \\prod_(n <= i < m) x = x ^+ (m - n).\nProof. by rewrite big_const_nat -iteropE. Qed.\n\nLemma prodrXr x I r P (F : I -> nat) :\n  \\prod_(i <- r | P i) x ^+ F i = x ^+ (\\sum_(i <- r | P i) F i).\nProof. by rewrite (big_morph _ (exprD _) (erefl _)). Qed.\n\nLemma prodrN (I : finType) (A : pred I) (F : I -> R) :\n  \\prod_(i in A) - F i = (- 1) ^+ #|A| * \\prod_(i in A) F i.\nProof.\nrewrite -sum1_card; elim/big_rec3: _ => [|i x n _ _ ->]; first by rewrite mulr1.\nby rewrite exprS !mulrA mulN1r !mulNr commrX //; apply: commrN1.\nQed.\n\nLemma prodrMn (I : Type) (s : seq I) (P : pred I) (F : I -> R) (g : I -> nat) : \n  \\prod_(i <- s | P i) (F i *+ g i) =\n  \\prod_(i <- s | P i) (F i) *+ \\prod_(i <- s | P i) g i.\nProof.\nby elim/big_rec3: _ => // i y1 y2 y3 _ ->; rewrite mulrnAr mulrnAl -mulrnA.\nQed.\n\nLemma prodrMn_const n (I : finType) (A : pred I) (F : I -> R) :\n  \\prod_(i in A) (F i *+ n) = \\prod_(i in A) F i *+ n ^ #|A|.\nProof. by rewrite prodrMn prod_nat_const. Qed.\n\nLemma natr_prod I r P (F : I -> nat) :\n  (\\prod_(i <- r | P i) F i)%:R = \\prod_(i <- r | P i) (F i)%:R :> R.\nProof. exact: (big_morph _ natrM). Qed.\n\nLemma exprDn_comm x y n (cxy : comm x y) :\n  (x + y) ^+ n = \\sum_(i < n.+1) (x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof.\nelim: n => [|n IHn]; rewrite big_ord_recl mulr1 ?big_ord0 ?addr0 //=.\nrewrite exprS {}IHn /= mulrDl !big_distrr /= big_ord_recl mulr1 subn0.\nrewrite !big_ord_recr /= !binn !subnn !mul1r !subn0 bin0 !exprS -addrA.\ncongr (_ + _); rewrite addrA -big_split /=; congr (_ + _).\napply: eq_bigr => i _; rewrite !mulrnAr !mulrA -exprS -subSn ?(valP i) //.\nby rewrite subSS (commrX _ (commr_sym cxy)) -mulrA -exprS -mulrnDr.\nQed.\n\nLemma exprBn_comm x y n (cxy : comm x y) :\n  (x - y) ^+ n =\n    \\sum_(i < n.+1) ((-1) ^+ i * x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof.\nrewrite exprDn_comm; last exact: commrN.\nby apply: eq_bigr => i _; congr (_ *+ _); rewrite -commr_sign -mulrA -exprNn.\nQed.\n\nLemma subrXX_comm x y n (cxy : comm x y) :\n  x ^+ n - y ^+ n = (x - y) * (\\sum_(i < n) x ^+ (n.-1 - i) * y ^+ i).\nProof.\ncase: n => [|n]; first by rewrite big_ord0 mulr0 subrr.\nrewrite mulrBl !big_distrr big_ord_recl big_ord_recr /= subnn mulr1 mul1r.\nrewrite subn0 -!exprS opprD -!addrA; congr (_ + _); rewrite addrA -sumrB.\nrewrite big1 ?add0r // => i _; rewrite !mulrA -exprS -subSn ?(valP i) //.\nby rewrite subSS (commrX _ (commr_sym cxy)) -mulrA -exprS subrr.\nQed.\n\nLemma exprD1n x n : (x + 1) ^+ n = \\sum_(i < n.+1) x ^+ i *+ 'C(n, i).\nProof.\nrewrite addrC (exprDn_comm n (commr_sym (commr1 x))).\nby apply: eq_bigr => i _; rewrite expr1n mul1r.\nQed.\n\nLemma subrX1 x n : x ^+ n - 1 = (x - 1) * (\\sum_(i < n) x ^+ i).\nProof.\nrewrite -!(opprB 1) mulNr -{1}(expr1n n).\nrewrite (subrXX_comm _ (commr_sym (commr1 x))); congr (- (_ * _)).\nby apply: eq_bigr => i _; rewrite expr1n mul1r.\nQed.\n\nLemma sqrrD1 x : (x + 1) ^+ 2 = x ^+ 2 + x *+ 2 + 1.\nProof.\nrewrite exprD1n !big_ord_recr big_ord0 /= add0r.\nby rewrite addrC addrA addrAC.\nQed.\n\nLemma sqrrB1 x : (x - 1) ^+ 2 = x ^+ 2 - x *+ 2 + 1.\nProof. by rewrite -sqrrN opprB addrC sqrrD1 sqrrN mulNrn. Qed.\n\nLemma subr_sqr_1 x : x ^+ 2 - 1 = (x - 1) * (x + 1).\nProof. by rewrite subrX1 !big_ord_recr big_ord0 /= addrAC add0r. Qed.\n\nDefinition Frobenius_aut p of p \\in [char R] := fun x => x ^+ p.\n\nSection FrobeniusAutomorphism.\n\nVariable p : nat.\nHypothesis charFp : p \\in [char R].\n\nLemma charf0 : p%:R = 0 :> R. Proof. by apply/eqP; case/andP: charFp. Qed.\nLemma charf_prime : prime p. Proof. by case/andP: charFp. Qed.\nHint Resolve charf_prime : core.\n\nLemma mulrn_char x : x *+ p = 0. Proof. by rewrite -mulr_natl charf0 mul0r. Qed.\n\nLemma natr_mod_char n : (n %% p)%:R = n%:R :> R.\nProof. by rewrite {2}(divn_eq n p) natrD mulrnA mulrn_char add0r. Qed.\n\nLemma dvdn_charf n : (p %| n)%N = (n%:R == 0 :> R).\nProof.\napply/idP/eqP=> [/dvdnP[n' ->]|n0]; first by rewrite natrM charf0 mulr0.\napply/idPn; rewrite -prime_coprime // => /eqnP pn1.\nhave [a _ /dvdnP[b]] := Bezoutl n (prime_gt0 charf_prime).\nmove/(congr1 (fun m => m%:R : R))/eqP.\nby rewrite natrD !natrM charf0 n0 !mulr0 pn1 addr0 oner_eq0.\nQed.\n\nLemma charf_eq : [char R] =i (p : nat_pred).\nProof.\nmove=> q; apply/andP/eqP=> [[q_pr q0] | ->]; last by rewrite charf0.\nby apply/eqP; rewrite eq_sym -dvdn_prime2 // dvdn_charf.\nQed.\n\nLemma bin_lt_charf_0 k : 0 < k < p -> 'C(p, k)%:R = 0 :> R.\nProof. by move=> lt0kp; apply/eqP; rewrite -dvdn_charf prime_dvd_bin. Qed.\n\nLocal Notation \"x ^f\" := (Frobenius_aut charFp x).\n\nLemma Frobenius_autE x : x^f = x ^+ p. Proof. by []. Qed.\nLocal Notation fE := Frobenius_autE.\n\nLemma Frobenius_aut0 : 0^f = 0.\nProof. by rewrite fE -(prednK (prime_gt0 charf_prime)) exprS mul0r. Qed.\n\nLemma Frobenius_aut1 : 1^f = 1.\nProof. by rewrite fE expr1n. Qed.\n\nLemma Frobenius_autD_comm x y (cxy : comm x y) : (x + y)^f = x^f + y^f.\nProof.\nhave defp := prednK (prime_gt0 charf_prime).\nrewrite !fE exprDn_comm // big_ord_recr subnn -defp big_ord_recl /= defp.\nrewrite subn0 mulr1 mul1r bin0 binn big1 ?addr0 // => i _.\nby rewrite -mulr_natl bin_lt_charf_0 ?mul0r //= -{2}defp ltnS (valP i).\nQed.\n\nLemma Frobenius_autMn x n : (x *+ n)^f = x^f *+ n.\nProof.\nelim: n => [|n IHn]; first exact: Frobenius_aut0.\nby rewrite !mulrS Frobenius_autD_comm ?IHn //; apply: commrMn.\nQed.\n\nLemma Frobenius_aut_nat n : (n%:R)^f = n%:R.\nProof. by rewrite Frobenius_autMn Frobenius_aut1. Qed.\n\nLemma Frobenius_autM_comm x y : comm x y -> (x * y)^f = x^f * y^f.\nProof. exact: exprMn_comm. Qed.\n\nLemma Frobenius_autX x n : (x ^+ n)^f = x^f ^+ n.\nProof. by rewrite !fE -!exprM mulnC. Qed.\n\nLemma Frobenius_autN x : (- x)^f = - x^f.\nProof.\napply/eqP; rewrite -subr_eq0 opprK addrC.\nby rewrite -(Frobenius_autD_comm (commrN _)) // subrr Frobenius_aut0.\nQed.\n\nLemma Frobenius_autB_comm x y : comm x y -> (x - y)^f = x^f - y^f.\nProof.\nby move/commrN/Frobenius_autD_comm->; rewrite Frobenius_autN.\nQed.\n\nEnd FrobeniusAutomorphism.\n\nLemma exprNn_char x n : [char R].-nat n -> (- x) ^+ n = - (x ^+ n).\nProof.\npose p := pdiv n; have [|n_gt1 charRn] := leqP n 1; first by case: (n) => [|[]].\nhave charRp: p \\in [char R] by rewrite (pnatPpi charRn) // pi_pdiv.\nhave /p_natP[e ->]: p.-nat n by rewrite -(eq_pnat _ (charf_eq charRp)).\nelim: e => // e IHe; rewrite expnSr !exprM {}IHe.\nby rewrite -Frobenius_autE Frobenius_autN.\nQed.\n\nSection Char2.\n\nHypothesis charR2 : 2 \\in [char R].\n\nLemma addrr_char2 x : x + x = 0. Proof. by rewrite -mulr2n mulrn_char. Qed.\n\nLemma oppr_char2 x : - x = x.\nProof. by apply/esym/eqP; rewrite -addr_eq0 addrr_char2. Qed.\n\nLemma subr_char2 x y : x - y = x + y. Proof. by rewrite oppr_char2. Qed.\n\nLemma addrK_char2 x : involutive (+%R^~ x).\nProof. by move=> y; rewrite /= -subr_char2 addrK. Qed.\n\nLemma addKr_char2 x : involutive (+%R x).\nProof. by move=> y; rewrite -{1}[x]oppr_char2 addKr. Qed.\n\nEnd Char2.\n\nCanonical converse_eqType := [eqType of R^c].\nCanonical converse_choiceType := [choiceType of R^c].\nCanonical converse_zmodType := [zmodType of R^c].\n\nDefinition converse_ringMixin :=\n  let mul' x y := y * x in\n  let mulrA' x y z := esym (mulrA z y x) in\n  let mulrDl' x y z := mulrDr z x y in\n  let mulrDr' x y z := mulrDl y z x in\n  @Ring.Mixin converse_zmodType\n    1 mul' mulrA' mulr1 mul1r mulrDl' mulrDr' oner_neq0.\nCanonical converse_ringType := RingType R^c converse_ringMixin.\n\nSection ClosedPredicates.\n\nVariable S : {pred R}.\n\nDefinition mulr_2closed := {in S &, forall u v, u * v \\in S}.\nDefinition mulr_closed := 1 \\in S /\\ mulr_2closed.\nDefinition smulr_closed := -1 \\in S /\\ mulr_2closed.\nDefinition semiring_closed := addr_closed S /\\ mulr_closed.\nDefinition subring_closed := [/\\ 1 \\in S, subr_2closed S & mulr_2closed].\n\nLemma smulr_closedM : smulr_closed -> mulr_closed.\nProof. by case=> SN1 SM; split=> //; rewrite -[1]mulr1 -mulrNN SM. Qed.\n\nLemma smulr_closedN : smulr_closed -> oppr_closed S.\nProof. by case=> SN1 SM x Sx; rewrite -mulN1r SM. Qed.\n\nLemma semiring_closedD : semiring_closed -> addr_closed S. Proof. by case. Qed.\n\nLemma semiring_closedM : semiring_closed -> mulr_closed. Proof. by case. Qed.\n\nLemma subring_closedB : subring_closed -> zmod_closed S.\nProof. by case=> S1 SB _; split; rewrite // -(subrr 1) SB. Qed.\n\nLemma subring_closedM : subring_closed -> smulr_closed.\nProof.\nby case=> S1 SB SM; split; rewrite ?(zmod_closedN (subring_closedB _)).\nQed.\n\nLemma subring_closed_semi : subring_closed -> semiring_closed.\nProof.\nby move=> ringS; split; [apply/zmod_closedD/subring_closedB | case: ringS].\nQed.\n \nEnd ClosedPredicates.\n\nEnd RingTheory.\n\nSection RightRegular.\n\nVariable R : ringType.\nImplicit Types x y : R.\nLet Rc := converse_ringType R.\n\nLemma mulIr_eq0 x y : rreg x -> (y * x == 0) = (y == 0).\nProof. exact: (@mulrI_eq0 Rc). Qed.\n\nLemma mulIr0_rreg x : (forall y, y * x = 0 -> y = 0) -> rreg x.\nProof. exact: (@mulrI0_lreg Rc). Qed.\n\nLemma rreg_neq0 x : rreg x -> x != 0.\nProof. exact: (@lreg_neq0 Rc). Qed.\n\nLemma rregN x : rreg x -> rreg (- x).\nProof. exact: (@lregN Rc). Qed.\n\nLemma rreg1 : rreg (1 : R).\nProof. exact: (@lreg1 Rc). Qed.\n\nLemma rregM x y : rreg x -> rreg y -> rreg (x * y).\nProof. by move=> reg_x reg_y; apply: (@lregM Rc). Qed.\n\nLemma revrX x n : (x : Rc) ^+ n = (x : R) ^+ n.\nProof. by elim: n => // n IHn; rewrite exprS exprSr IHn. Qed.\n\nLemma rregX x n : rreg x -> rreg (x ^+ n).\nProof. by move/(@lregX Rc x n); rewrite revrX. Qed.\n\nEnd RightRegular.\n\nModule Lmodule.\n\nStructure mixin_of (R : ringType) (V : zmodType) : Type := Mixin {\n  scale : R -> V -> V;\n  _ : forall a b v, scale a (scale b v) = scale (a * b) v;\n  _ : left_id 1 scale;\n  _ : right_distributive scale +%R;\n  _ : forall v, {morph scale^~ v: a b / a + b}\n}.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nSet Primitive Projections.\nRecord class_of V := Class {\n  base : Zmodule.class_of V;\n  mixin : mixin_of R (Zmodule.Pack base)\n}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> Zmodule.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\n\nDefinition pack b0 (m0 : mixin_of R (@Zmodule.Pack T b0)) :=\n  fun bT b & phant_id (Zmodule.class bT) b =>\n  fun    m & phant_id m0 m => Pack phR (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\n\nEnd ClassDef.\n\nModule Import Exports.\nCoercion base : class_of >-> Zmodule.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nNotation lmodType R := (type (Phant R)).\nNotation LmodType R T m := (@pack _ (Phant R) T _ m _ _ id _ id).\nNotation LmodMixin := Mixin.\nNotation \"[ 'lmodType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'lmodType'  R  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'lmodType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'lmodType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Lmodule.\nImport Lmodule.Exports.\n\nDefinition scale (R : ringType) (V : lmodType R) : R -> V -> V :=\n  Lmodule.scale (Lmodule.class V).\n\nLocal Notation \"*:%R\" := (@scale _ _) : fun_scope.\nLocal Notation \"a *: v\" := (scale a v) : ring_scope.\n\nSection LmoduleTheory.\n\nVariables (R : ringType) (V : lmodType R).\nImplicit Types (a b c : R) (u v : V).\n\nLocal Notation \"*:%R\" := (@scale R V) : fun_scope.\n\nLemma scalerA a b v : a *: (b *: v) = a * b *: v.\nProof. by case: V v => ? [] ? []. Qed.\n\nLemma scale1r : @left_id R V 1 *:%R.\nProof. by case: V => ? [] ? []. Qed.\n\nLemma scalerDr a : {morph *:%R a : u v / u + v}.\nProof. by case: V a => ? [] ? []. Qed.\n\nLemma scalerDl v : {morph *:%R^~ v : a b / a + b}.\nProof. by case: V v => ? [] ? []. Qed.\n\nLemma scale0r v : 0 *: v = 0.\nProof. by apply: (addIr (1 *: v)); rewrite -scalerDl !add0r. Qed.\n\nLemma scaler0 a : a *: 0 = 0 :> V.\nProof. by rewrite -{1}(scale0r 0) scalerA mulr0 scale0r. Qed.\n\nLemma scaleNr a v : - a *: v = - (a *: v).\nProof. by apply: (addIr (a *: v)); rewrite -scalerDl !addNr scale0r. Qed.\n\nLemma scaleN1r v : (- 1) *: v = - v.\nProof. by rewrite scaleNr scale1r. Qed.\n\nLemma scalerN a v : a *: (- v) = - (a *: v).\nProof. by apply: (addIr (a *: v)); rewrite -scalerDr !addNr scaler0. Qed.\n\nLemma scalerBl a b v : (a - b) *: v = a *: v - b *: v.\nProof. by rewrite scalerDl scaleNr. Qed.\n\nLemma scalerBr a u v : a *: (u - v) = a *: u - a *: v.\nProof. by rewrite scalerDr scalerN. Qed.\n\nLemma scaler_nat n v : n%:R *: v = v *+ n.\nProof.\nelim: n => /= [|n ]; first by rewrite scale0r.\nby rewrite !mulrS scalerDl ?scale1r => ->.\nQed.\n\nLemma scaler_sign (b : bool) v: (-1) ^+ b *: v = (if b then - v else v).\nProof. by case: b; rewrite ?scaleNr scale1r. Qed.\n\nLemma signrZK n : @involutive V ( *:%R ((-1) ^+ n)).\nProof. by move=> u; rewrite scalerA -expr2 sqrr_sign scale1r. Qed.\n\nLemma scalerMnl a v n : a *: v *+ n = (a *+ n) *: v.\nProof.\nelim: n => [|n IHn]; first by rewrite !mulr0n scale0r.\nby rewrite !mulrSr IHn scalerDl.\nQed.\n\nLemma scalerMnr a v n : a *: v *+ n = a *: (v *+ n).\nProof.\nelim: n => [|n IHn]; first by rewrite !mulr0n scaler0.\nby rewrite !mulrSr IHn scalerDr.\nQed.\n\nLemma scaler_suml v I r (P : pred I) F :\n  (\\sum_(i <- r | P i) F i) *: v = \\sum_(i <- r | P i) F i *: v.\nProof. exact: (big_morph _ (scalerDl v) (scale0r v)). Qed.\n\nLemma scaler_sumr a I r (P : pred I) (F : I -> V) :\n  a *: (\\sum_(i <- r | P i) F i) = \\sum_(i <- r | P i) a *: F i.\nProof. exact: big_endo (scalerDr a) (scaler0 a) I r P F. Qed.\n\nSection ClosedPredicates.\n\nVariable S : {pred V}.\n\nDefinition scaler_closed := forall a, {in S, forall v, a *: v \\in S}.\nDefinition linear_closed := forall a, {in S &, forall u v, a *: u + v \\in S}.\nDefinition submod_closed := 0 \\in S /\\ linear_closed.\n\nLemma linear_closedB : linear_closed -> subr_2closed S.\nProof. by move=> Slin u v Su Sv; rewrite addrC -scaleN1r Slin. Qed.\n\nLemma submod_closedB : submod_closed -> zmod_closed S.\nProof. by case=> S0 /linear_closedB. Qed.\n\nLemma submod_closedZ : submod_closed -> scaler_closed.\nProof. by case=> S0 Slin a v Sv; rewrite -[a *: v]addr0 Slin. Qed.\n\nEnd ClosedPredicates.\n\nEnd LmoduleTheory.\n\nModule Lalgebra.\n\nDefinition axiom (R : ringType) (V : lmodType R) (mul : V -> V -> V) :=\n  forall a u v, a *: mul u v = mul (a *: u) v.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nSet Primitive Projections.\nRecord class_of (T : Type) : Type := Class {\n  base : Ring.class_of T;\n  mixin : Lmodule.mixin_of R (Zmodule.Pack base);\n  ext : @axiom R (Lmodule.Pack _ (Lmodule.Class mixin)) (Ring.mul base)\n}.\nUnset Primitive Projections.\nDefinition base2 R m := Lmodule.Class (@mixin R m).\nLocal Coercion base : class_of >-> Ring.class_of.\nLocal Coercion base2 : class_of >-> Lmodule.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\n\nDefinition pack b0 mul0 (axT : @axiom R (@Lmodule.Pack R _ T b0) mul0) :=\n  fun bT b & phant_id (Ring.class bT) (b : Ring.class_of T) =>\n  fun mT m & phant_id (@Lmodule.class R phR mT) (@Lmodule.Class R T b m) =>\n  fun ax & phant_id axT ax =>\n  Pack (Phant R) (@Class T b m ax).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition lmodType := @Lmodule.Pack R phR cT class.\nDefinition lmod_ringType := @Lmodule.Pack R phR ringType class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Ring.class_of.\nCoercion base2 : class_of >-> Lmodule.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCanonical lmod_ringType.\nNotation lalgType R := (type (Phant R)).\nNotation LalgType R T a := (@pack _ (Phant R) T _ _ a _ _ id _ _ id _ id).\nNotation \"[ 'lalgType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'lalgType'  R  'of'  T  'for'  cT ]\")\n  : form_scope.\nNotation \"[ 'lalgType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'lalgType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Lalgebra.\nImport Lalgebra.Exports.\n\n(* Scalar injection (see the definition of in_alg A below). *)\nLocal Notation \"k %:A\" := (k *: 1) : ring_scope.\n\n(* Regular ring algebra tag. *)\nDefinition regular R : Type := R.\nLocal Notation \"R ^o\" := (regular R) (at level 2, format \"R ^o\") : type_scope.\n\nSection LalgebraTheory.\n\nVariables (R : ringType) (A : lalgType R).\nImplicit Types x y : A.\n\nLemma scalerAl k (x y : A) : k *: (x * y) = k *: x * y.\nProof. by case: A k x y => ? []. Qed.\n\nLemma mulr_algl a x : a%:A * x = a *: x.\nProof. by rewrite -scalerAl mul1r. Qed.\n\nCanonical regular_eqType := [eqType of R^o].\nCanonical regular_choiceType := [choiceType of R^o].\nCanonical regular_zmodType := [zmodType of R^o].\nCanonical regular_ringType := [ringType of R^o].\n\nDefinition regular_lmodMixin :=\n  let mkMixin := @Lmodule.Mixin R regular_zmodType (@mul R) in\n  mkMixin (@mulrA R) (@mul1r R) (@mulrDr R) (fun v a b => mulrDl a b v).\n\nCanonical regular_lmodType := LmodType R R^o regular_lmodMixin.\nCanonical regular_lalgType := LalgType R R^o (@mulrA regular_ringType).\n\nSection ClosedPredicates.\n\nVariable S : {pred A}.\n\nDefinition subalg_closed := [/\\ 1 \\in S, linear_closed S & mulr_2closed S].\n\nLemma subalg_closedZ : subalg_closed -> submod_closed S.\nProof. by case=> S1 Slin _; split; rewrite // -(subrr 1) linear_closedB. Qed.\n\nLemma subalg_closedBM : subalg_closed -> subring_closed S.\nProof. by case=> S1 Slin SM; split=> //; apply: linear_closedB. Qed.\n\nEnd ClosedPredicates.\n\nEnd LalgebraTheory.\n\n(* Morphism hierarchy. *)\n\nModule Additive.\n\nSection ClassDef.\n\nVariables U V : zmodType.\n\nDefinition axiom (f : U -> V) := {morph f : x y / x - y}.\n\nStructure map (phUV : phant (U -> V)) := Pack {apply; _ : axiom apply}.\nLocal Coercion apply : map >-> Funclass.\n\nVariables (phUV : phant (U -> V)) (f g : U -> V) (cF : map phUV).\nDefinition class := let: Pack _ c as cF' := cF return axiom cF' in c.\nDefinition clone fA of phant_id g (apply cF) & phant_id fA class :=\n  @Pack phUV f fA.\n\nEnd ClassDef.\n\nModule Exports.\nNotation additive f := (axiom f).\nCoercion apply : map >-> Funclass.\nNotation Additive fA := (Pack (Phant _) fA).\nNotation \"{ 'additive' fUV }\" := (map (Phant fUV))\n  (at level 0, format \"{ 'additive'  fUV }\") : type_scope.\nNotation \"[ 'additive' 'of' f 'as' g ]\" := (@clone _ _ _ f g _ _ idfun id)\n  (at level 0, format \"[ 'additive'  'of'  f  'as'  g ]\") : form_scope.\nNotation \"[ 'additive' 'of' f ]\" := (@clone _ _ _ f f _ _ id id)\n  (at level 0, format \"[ 'additive'  'of'  f ]\") : form_scope.\nEnd Exports.\n\nEnd Additive.\nInclude Additive.Exports. (* Allows GRing.additive to resolve conflicts. *)\n\n(* Lifted additive operations. *)\nSection LiftedZmod.\nVariables (U : Type) (V : zmodType).\nDefinition null_fun_head (phV : phant V) of U : V := let: Phant := phV in 0.\nDefinition add_fun (f g : U -> V) x := f x + g x.\nDefinition sub_fun (f g : U -> V) x := f x - g x.\nDefinition opp_fun (f : U -> V) x := - f x.\nEnd LiftedZmod.\n\n(* Lifted multiplication. *)\nSection LiftedRing.\nVariables (R : ringType) (T : Type).\nImplicit Type f : T -> R.\nDefinition mull_fun a f x := a * f x.\nDefinition mulr_fun a f x := f x * a.\nDefinition mul_fun f g x := f x * g x.\nEnd LiftedRing.\n\n(* Lifted linear operations. *)\nSection LiftedScale.\nVariables (R : ringType) (U : Type) (V : lmodType R) (A : lalgType R).\nDefinition scale_fun a (f : U -> V) x := a *: f x.\nDefinition in_alg_head (phA : phant A) k : A := let: Phant := phA in k%:A.\nEnd LiftedScale.\n\nNotation null_fun V := (null_fun_head (Phant V)) (only parsing).\n(* The real in_alg notation is declared after GRing.Theory so that at least *)\n(* in Coq 8.2 it gets precedence when GRing.Theory is not imported.         *)\nLocal Notation in_alg_loc A := (in_alg_head (Phant A)) (only parsing).\n\nLocal Notation \"\\0\" := (null_fun _) : ring_scope.\nLocal Notation \"f \\+ g\" := (add_fun f g) : ring_scope.\nLocal Notation \"f \\- g\" := (sub_fun f g) : ring_scope.\nLocal Notation \"\\- f\" := (opp_fun f) : ring_scope.\nLocal Notation \"a \\*: f\" := (scale_fun a f) : ring_scope.\nLocal Notation \"x \\*o f\" := (mull_fun x f) : ring_scope.\nLocal Notation \"x \\o* f\" := (mulr_fun x f) : ring_scope.\nLocal Notation \"f \\* g\" := (mul_fun f g) : ring_scope.\n\nArguments add_fun {_ _} f g _ /.\nArguments sub_fun {_ _} f g _ /.\nArguments opp_fun {_ _} f _ /.\nArguments mull_fun {_ _}  a f _ /.\nArguments mulr_fun {_ _} a f _ /.\nArguments scale_fun {_ _ _} a f _ /.\nArguments mul_fun {_ _} f g _ /.\n\nSection AdditiveTheory.\n\nSection Properties.\n\nVariables (U V : zmodType) (k : unit) (f : {additive U -> V}).\n\nLemma raddfB : {morph f : x y / x - y}. Proof. exact: Additive.class. Qed.\n\nLemma raddf0 : f 0 = 0.\nProof. by rewrite -[0]subr0 raddfB subrr. Qed.\n\nLemma raddf_eq0 x : injective f -> (f x == 0) = (x == 0).\nProof. by move=> /inj_eq <-; rewrite raddf0. Qed.\n\nLemma raddf_inj : (forall x, f x = 0 -> x = 0) -> injective f.\nProof. by move=> fI x y eqxy; apply/subr0_eq/fI; rewrite raddfB eqxy subrr. Qed.\n\nLemma raddfN : {morph f : x / - x}.\nProof. by move=> x /=; rewrite -sub0r raddfB raddf0 sub0r. Qed.\n\nLemma raddfD : {morph f : x y / x + y}.\nProof. by move=> x y; rewrite -[y]opprK raddfB -raddfN. Qed.\n\nLemma raddfMn n : {morph f : x / x *+ n}.\nProof. by elim: n => [|n IHn] x /=; rewrite ?raddf0 // !mulrS raddfD IHn. Qed.\n\nLemma raddfMNn n : {morph f : x / x *- n}.\nProof. by move=> x /=; rewrite raddfN raddfMn. Qed.\n\nLemma raddf_sum I r (P : pred I) E :\n  f (\\sum_(i <- r | P i) E i) = \\sum_(i <- r | P i) f (E i).\nProof. exact: (big_morph f raddfD raddf0). Qed.\n\nLemma can2_additive f' : cancel f f' -> cancel f' f -> additive f'.\nProof. by move=> fK f'K x y /=; apply: (canLR fK); rewrite raddfB !f'K. Qed.\n\nLemma bij_additive :\n  bijective f -> exists2 f' : {additive V -> U}, cancel f f' & cancel f' f.\nProof. by case=> f' fK f'K; exists (Additive (can2_additive fK f'K)). Qed.\n\nFact locked_is_additive : additive (locked_with k (f : U -> V)).\nProof. by case: k f => [] []. Qed.\nCanonical locked_additive := Additive locked_is_additive.\n\nEnd Properties.\n\nSection RingProperties.\n\nVariables (R S : ringType) (f : {additive R -> S}).\n\nLemma raddfMnat n x : f (n%:R * x) = n%:R * f x.\nProof. by rewrite !mulr_natl raddfMn. Qed.\n\nLemma raddfMsign n x : f ((-1) ^+ n * x) = (-1) ^+ n * f x.\nProof. by rewrite !(mulr_sign, =^~ signr_odd) (fun_if f) raddfN. Qed.\n\nVariables (U : lmodType R) (V : lmodType S) (h : {additive U -> V}).\n\nLemma raddfZnat n u : h (n%:R *: u) = n%:R *: h u.\nProof. by rewrite !scaler_nat raddfMn. Qed.\n\nLemma raddfZsign n u : h ((-1) ^+ n *: u) = (-1) ^+ n *: h u.\nProof. by rewrite !(scaler_sign, =^~ signr_odd) (fun_if h) raddfN. Qed.\n\nEnd RingProperties.\n\nSection AddFun.\n\nVariables (U V W : zmodType) (f g : {additive V -> W}) (h : {additive U -> V}).\n\nFact idfun_is_additive : additive (@idfun U).\nProof. by []. Qed.\nCanonical idfun_additive := Additive idfun_is_additive.\n\nFact comp_is_additive : additive (f \\o h).\nProof. by move=> x y /=; rewrite !raddfB. Qed.\nCanonical comp_additive := Additive comp_is_additive.\n\nFact opp_is_additive : additive (-%R : U -> U).\nProof. by move=> x y; rewrite /= opprD. Qed.\nCanonical opp_additive := Additive opp_is_additive.\n\nFact null_fun_is_additive : additive (\\0 : U -> V).\nProof. by move=> /=; rewrite subr0. Qed.\nCanonical null_fun_additive := Additive null_fun_is_additive.\n\nFact add_fun_is_additive : additive (f \\+ g).\nProof.\nby move=> x y /=; rewrite !raddfB addrCA -!addrA addrCA -opprD.\nQed.\nCanonical add_fun_additive := Additive add_fun_is_additive.\n\nFact sub_fun_is_additive : additive (f \\- g).\nProof.\nby move=> x y /=; rewrite !raddfB addrAC -!addrA -!opprD addrAC addrA.\nQed.\nCanonical sub_fun_additive := Additive sub_fun_is_additive.\n\nFact opp_fun_is_additive : additive (\\- g).\nProof. by move=> x y /=; rewrite !raddfB opprB addrC opprK. Qed.\nCanonical opp_fun_additive := Additive opp_fun_is_additive.\n\nEnd AddFun.\n\nSection MulFun.\n\nVariables (R : ringType) (U : zmodType).\nVariables (a : R) (f : {additive U -> R}).\n\nFact mull_fun_is_additive : additive (a \\*o f).\nProof. by move=> x y /=; rewrite raddfB mulrBr. Qed.\nCanonical mull_fun_additive := Additive mull_fun_is_additive.\n\nFact mulr_fun_is_additive : additive (a \\o* f).\nProof. by move=> x y /=; rewrite raddfB mulrBl. Qed.\nCanonical mulr_fun_additive := Additive mulr_fun_is_additive.\n\nEnd MulFun.\n\nSection ScaleFun.\n\nVariables (R : ringType) (U : zmodType) (V : lmodType R).\nVariables (a : R) (f : {additive U -> V}).\n\nCanonical scale_additive := Additive (@scalerBr R V a).\nCanonical scale_fun_additive := [additive of a \\*: f as f \\; *:%R a].\n\nEnd ScaleFun.\n\nEnd AdditiveTheory.\n\nModule RMorphism.\n\nSection ClassDef.\n\nVariables R S : ringType.\n\nDefinition mixin_of (f : R -> S) :=\n  {morph f : x y / x * y}%R * (f 1 = 1) : Prop.\n\nRecord class_of f : Prop := Class {base : additive f; mixin : mixin_of f}.\nLocal Coercion base : class_of >-> additive.\n\nStructure map (phRS : phant (R -> S)) := Pack {apply; _ : class_of apply}.\nLocal Coercion apply : map >-> Funclass.\nVariables (phRS : phant (R -> S)) (f g : R -> S) (cF : map phRS).\n\nDefinition class := let: Pack _ c as cF' := cF return class_of cF' in c.\n\nDefinition clone fM of phant_id g (apply cF) & phant_id fM class :=\n  @Pack phRS f fM.\n\nDefinition pack (fM : mixin_of f) :=\n  fun (bF : Additive.map phRS) fA & phant_id (Additive.class bF) fA =>\n  Pack phRS (Class fA fM).\n\nCanonical additive := Additive.Pack phRS class.\n\nEnd ClassDef.\n\nModule Exports.\nNotation multiplicative f := (mixin_of f).\nNotation rmorphism f := (class_of f).\nCoercion base : rmorphism >-> Additive.axiom.\nCoercion mixin : rmorphism >-> multiplicative.\nCoercion apply : map >-> Funclass.\nNotation RMorphism fM := (Pack (Phant _) fM).\nNotation AddRMorphism fM := (pack fM id).\nNotation \"{ 'rmorphism' fRS }\" := (map (Phant fRS))\n  (at level 0, format \"{ 'rmorphism'  fRS }\") : type_scope.\nNotation \"[ 'rmorphism' 'of' f 'as' g ]\" := (@clone _ _ _ f g _ _ idfun id)\n  (at level 0, format \"[ 'rmorphism'  'of'  f  'as'  g ]\") : form_scope.\nNotation \"[ 'rmorphism' 'of' f ]\" := (@clone _ _ _ f f _ _ id id)\n  (at level 0, format \"[ 'rmorphism'  'of'  f ]\") : form_scope.\nCoercion additive : map >-> Additive.map.\nCanonical additive.\nEnd Exports.\n\nEnd RMorphism.\nInclude RMorphism.Exports.\n\nSection RmorphismTheory.\n\nSection Properties.\n\nVariables (R S : ringType) (k : unit) (f : {rmorphism R -> S}).\n\nLemma rmorph0 : f 0 = 0. Proof. exact: raddf0. Qed.\nLemma rmorphN : {morph f : x / - x}. Proof. exact: raddfN. Qed.\nLemma rmorphD : {morph f : x y / x + y}. Proof. exact: raddfD. Qed.\nLemma rmorphB : {morph f: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma rmorphMn n : {morph f : x / x *+ n}. Proof. exact: raddfMn. Qed.\nLemma rmorphMNn n : {morph f : x / x *- n}. Proof. exact: raddfMNn. Qed.\nLemma rmorph_sum I r (P : pred I) E :\n  f (\\sum_(i <- r | P i) E i) = \\sum_(i <- r | P i) f (E i).\nProof. exact: raddf_sum. Qed.\nLemma rmorphMsign n : {morph f : x / (- 1) ^+ n * x}.\nProof. exact: raddfMsign. Qed.\n\nLemma rmorphismP : rmorphism f. Proof. exact: RMorphism.class. Qed.\nLemma rmorphismMP : multiplicative f. Proof. exact: rmorphismP. Qed.\nLemma rmorph1 : f 1 = 1. Proof. by case: rmorphismMP. Qed.\nLemma rmorphM : {morph f: x y  / x * y}. Proof. by case: rmorphismMP. Qed.\n\nLemma rmorph_prod I r (P : pred I) E :\n  f (\\prod_(i <- r | P i) E i) = \\prod_(i <- r | P i) f (E i).\nProof. exact: (big_morph f rmorphM rmorph1). Qed.\n\nLemma rmorphX n : {morph f: x / x ^+ n}.\nProof. by elim: n => [|n IHn] x; rewrite ?rmorph1 // !exprS rmorphM IHn. Qed.\n\nLemma rmorph_nat n : f n%:R = n%:R. Proof. by rewrite rmorphMn rmorph1. Qed.\nLemma rmorphN1 : f (- 1) = (- 1). Proof. by rewrite rmorphN rmorph1. Qed.\n\nLemma rmorph_sign n : f ((- 1) ^+ n) = (- 1) ^+ n.\nProof. by rewrite rmorphX rmorphN1. Qed.\n\nLemma rmorph_char p : p \\in [char R] -> p \\in [char S].\nProof. by rewrite !inE -rmorph_nat => /andP[-> /= /eqP->]; rewrite rmorph0. Qed.\n\nLemma rmorph_eq_nat x n : injective f -> (f x == n%:R) = (x == n%:R).\nProof. by move/inj_eq <-; rewrite rmorph_nat. Qed.\n\nLemma rmorph_eq1 x : injective f -> (f x == 1) = (x == 1).\nProof. exact: rmorph_eq_nat 1%N. Qed.\n\nLemma can2_rmorphism f' : cancel f f' -> cancel f' f -> rmorphism f'.\nProof.\nmove=> fK f'K; split; first exact: can2_additive fK f'K.\nby split=> [x y|]; apply: (canLR fK); rewrite /= (rmorphM, rmorph1) ?f'K.\nQed.\n\nLemma bij_rmorphism :\n  bijective f -> exists2 f' : {rmorphism S -> R}, cancel f f' & cancel f' f.\nProof. by case=> f' fK f'K; exists (RMorphism (can2_rmorphism fK f'K)). Qed.\n\nFact locked_is_multiplicative : multiplicative (locked_with k (f : R -> S)).\nProof. by case: k f => [] [? []]. Qed.\nCanonical locked_rmorphism := AddRMorphism locked_is_multiplicative.\n\nEnd Properties.\n\nSection Projections.\n\nVariables (R S T : ringType) (f : {rmorphism S -> T}) (g : {rmorphism R -> S}).\n\nFact idfun_is_multiplicative : multiplicative (@idfun R).\nProof. by []. Qed.\nCanonical idfun_rmorphism := AddRMorphism idfun_is_multiplicative.\n\nFact comp_is_multiplicative : multiplicative (f \\o g).\nProof. by split=> [x y|] /=; rewrite ?rmorph1 ?rmorphM. Qed.\nCanonical comp_rmorphism := AddRMorphism comp_is_multiplicative.\n\nEnd Projections.\n\nSection InAlgebra.\n\nVariables (R : ringType) (A : lalgType R).\n\nFact in_alg_is_rmorphism : rmorphism (in_alg_loc A).\nProof.\nsplit=> [x y|]; first exact: scalerBl.\nby split=> [x y|] /=; rewrite ?scale1r // -scalerAl mul1r scalerA.\nQed.\nCanonical in_alg_additive := Additive in_alg_is_rmorphism.\nCanonical in_alg_rmorphism := RMorphism in_alg_is_rmorphism.\n\nLemma in_algE a : in_alg_loc A a = a%:A. Proof. by []. Qed.\n\nEnd InAlgebra.\n\nEnd RmorphismTheory.\n\nModule Scale.\n\nSection ScaleLaw.\n\nStructure law (R : ringType) (V : zmodType) (s : R -> V -> V) := Law {\n  op : R -> V -> V;\n  _ : op = s;\n  _ : op (-1) =1 -%R;\n  _ : forall a, additive (op a)\n}.\n\nDefinition mul_law R := Law (erefl *%R) (@mulN1r R) (@mulrBr R).\nDefinition scale_law R U := Law (erefl *:%R) (@scaleN1r R U) (@scalerBr R U).\n\nVariables (R : ringType) (V : zmodType) (s : R -> V -> V) (s_law : law s).\nLocal Notation s_op := (op s_law).\n\nLemma opE : s_op = s. Proof. by case: s_law. Qed.\nLemma N1op : s_op (-1) =1 -%R. Proof. by case: s_law. Qed.\nFact opB a : additive (s_op a). Proof. by case: s_law. Qed.\nDefinition op_additive a := Additive (opB a).\n\nVariables (aR : ringType) (nu : {rmorphism aR -> R}).\nFact comp_opE : nu \\; s_op = nu \\; s. Proof. exact: congr1 opE. Qed.\nFact compN1op : (nu \\; s_op) (-1) =1 -%R.\nProof. by move=> v; rewrite /= rmorphN1 N1op. Qed.\nDefinition comp_law : law (nu \\; s) := Law comp_opE compN1op (fun a => opB _).\n\nEnd ScaleLaw.\n\nEnd Scale.\n\nModule Linear.\n\nSection ClassDef.\n\nVariables (R : ringType) (U : lmodType R) (V : zmodType) (s : R -> V -> V).\nImplicit Type phUV : phant (U -> V).\n\nLocal Coercion Scale.op : Scale.law >-> Funclass.\nDefinition axiom (f : U -> V) (s_law : Scale.law s) of s = s_law :=\n  forall a, {morph f : u v / a *: u + v >-> s a u + v}.\nDefinition mixin_of (f : U -> V) :=\n  forall a, {morph f : v / a *: v >-> s a v}.\n\nRecord class_of f : Prop := Class {base : additive f; mixin : mixin_of f}.\nLocal Coercion base : class_of >-> additive.\n\nLemma class_of_axiom f s_law Ds : @axiom f s_law Ds -> class_of f.\nProof.\nmove=> fL; have fB: additive f.\n  by move=> x y /=; rewrite -scaleN1r addrC fL Ds Scale.N1op addrC.\nby split=> // a v /=; rewrite -[a *: v](addrK v) fB fL addrK Ds.\nQed.\n\nStructure map (phUV : phant (U -> V)) := Pack {apply; _ : class_of apply}.\nLocal Coercion apply : map >-> Funclass.\n\nVariables (phUV : phant (U -> V)) (f g : U -> V) (cF : map phUV).\nDefinition class := let: Pack _ c as cF' := cF return class_of cF' in c.\nDefinition clone fL of phant_id g (apply cF) & phant_id fL class :=\n  @Pack phUV f fL.\n\nDefinition pack (fZ : mixin_of f) :=\n  fun (bF : Additive.map phUV) fA & phant_id (Additive.class bF) fA =>\n  Pack phUV (Class fA fZ).\n\nCanonical additive := Additive.Pack phUV class.\n\n(* Support for right-to-left rewriting with the generic linearZ rule. *)\nNotation mapUV := (map (Phant (U -> V))).\nDefinition map_class := mapUV.\nDefinition map_at (a : R) := mapUV.\nStructure map_for a s_a := MapFor {map_for_map : mapUV; _ : s a = s_a}.\nDefinition unify_map_at a (f : map_at a) := MapFor f (erefl (s a)).\nStructure wrapped := Wrap {unwrap : mapUV}.\nDefinition wrap (f : map_class) := Wrap f.\n\nEnd ClassDef.\n\nModule Exports.\nCanonical Scale.mul_law.\nCanonical Scale.scale_law.\nCanonical Scale.comp_law.\nCanonical Scale.op_additive.\nDelimit Scope linear_ring_scope with linR.\nNotation \"a *: u\" := (@Scale.op _ _ *:%R _ a u) : linear_ring_scope.\nNotation \"a * u\" := (@Scale.op _ _ *%R _ a u) : linear_ring_scope.\nNotation \"a *:^ nu u\" := (@Scale.op _ _ (nu \\; *:%R) _ a u)\n  (at level 40, nu at level 1, format \"a  *:^ nu  u\") : linear_ring_scope.\nNotation \"a *^ nu u\" := (@Scale.op _ _ (nu \\; *%R) _ a u)\n  (at level 40, nu at level 1, format \"a  *^ nu  u\") : linear_ring_scope.\nNotation scalable_for s f := (mixin_of s f).\nNotation scalable f := (scalable_for *:%R f).\nNotation linear_for s f := (axiom f (erefl s)).\nNotation linear f := (linear_for *:%R f).\nNotation scalar f := (linear_for *%R f).\nNotation lmorphism_for s f := (class_of s f).\nNotation lmorphism f := (lmorphism_for *:%R f).\nCoercion class_of_axiom : axiom >-> lmorphism_for.\nCoercion base : lmorphism_for >-> Additive.axiom.\nCoercion mixin : lmorphism_for >-> scalable.\nCoercion apply : map >-> Funclass.\nNotation Linear fL := (Pack (Phant _) fL).\nNotation AddLinear fZ := (pack fZ id).\nNotation \"{ 'linear' fUV | s }\" := (map s (Phant fUV))\n  (at level 0, format \"{ 'linear'  fUV  |  s }\") : type_scope.\nNotation \"{ 'linear' fUV }\" := {linear fUV | *:%R}\n  (at level 0, format \"{ 'linear'  fUV }\") : type_scope.\nNotation \"{ 'scalar' U }\" := {linear U -> _ | *%R}\n  (at level 0, format \"{ 'scalar'  U }\") : type_scope.\nNotation \"[ 'linear' 'of' f 'as' g ]\" := (@clone _ _ _ _ _ f g _ _ idfun id)\n  (at level 0, format \"[ 'linear'  'of'  f  'as'  g ]\") : form_scope.\nNotation \"[ 'linear' 'of' f ]\" := (@clone _ _ _ _ _ f f _ _ id id)\n  (at level 0, format \"[ 'linear'  'of'  f ]\") : form_scope.\nCoercion additive : map >-> Additive.map.\nCanonical additive.\n(* Support for right-to-left rewriting with the generic linearZ rule. *)\nCoercion map_for_map : map_for >-> map.\nCoercion unify_map_at : map_at >-> map_for.\nCanonical unify_map_at.\nCoercion unwrap : wrapped >-> map.\nCoercion wrap : map_class >-> wrapped.\nCanonical wrap.\nEnd Exports.\n\nEnd Linear.\nInclude Linear.Exports.\n\nSection LinearTheory.\n\nVariable R : ringType.\n\nSection GenericProperties.\n\nVariables (U : lmodType R) (V : zmodType) (s : R -> V -> V) (k : unit).\nVariable f : {linear U -> V | s}.\n\nLemma linear0 : f 0 = 0. Proof. exact: raddf0. Qed.\nLemma linearN : {morph f : x / - x}. Proof. exact: raddfN. Qed.\nLemma linearD : {morph f : x y / x + y}. Proof. exact: raddfD. Qed.\nLemma linearB : {morph f : x y / x - y}. Proof. exact: raddfB. Qed.\nLemma linearMn n : {morph f : x / x *+ n}. Proof. exact: raddfMn. Qed.\nLemma linearMNn n : {morph f : x / x *- n}. Proof. exact: raddfMNn. Qed.\nLemma linear_sum I r (P : pred I) E :\n  f (\\sum_(i <- r | P i) E i) = \\sum_(i <- r | P i) f (E i).\nProof. exact: raddf_sum. Qed.\n\nLemma linearZ_LR : scalable_for s f. Proof. by case: f => ? []. Qed.\nLemma linearP a : {morph f : u v / a *: u + v >-> s a u + v}.\nProof. by move=> u v /=; rewrite linearD linearZ_LR. Qed.\n\nFact locked_is_scalable : scalable_for s (locked_with k (f : U -> V)).\nProof. by case: k f => [] [? []]. Qed.\nCanonical locked_linear := AddLinear locked_is_scalable.\n\nEnd GenericProperties.\n\nSection BidirectionalLinearZ.\n\nVariables (U : lmodType R) (V : zmodType) (s : R -> V -> V).\n\n(*   The general form of the linearZ lemma uses some bespoke interfaces to   *)\n(* allow right-to-left rewriting when a composite scaling operation such as  *)\n(* conjC \\; *%R has been expanded, say in a^* * f u. This redex is matched   *)\n(* by using the Scale.law interface to recognize a \"head\" scaling operation  *)\n(* h (here *%R), stow away its \"scalar\" c, then reconcile h c and s a, once  *)\n(* s is known, that is, once the Linear.map structure for f has been found.  *)\n(* In general, s and a need not be equal to h and c; indeed they need not    *)\n(* have the same type! The unification is performed by the unify_map_at      *)\n(* default instance for the Linear.map_for U s a h_c sub-interface of        *)\n(* Linear.map; the h_c pattern uses the Scale.law structure to insure it is  *)\n(* inferred when rewriting right-to-left.                                    *)\n(*   The wrap on the rhs allows rewriting f (a *: b *: u) into a *: b *: f u *)\n(* with rewrite !linearZ /= instead of rewrite linearZ /= linearZ /=.        *)\n(* Without it, the first rewrite linearZ would produce                       *)\n(*    (a *: apply (map_for_map (@check_map_at .. a f)) (b *: u)%R)%Rlin      *)\n(* and matching the second rewrite LHS would bypass the unify_map_at default *)\n(* instance for b, reuse the one for a, and subsequently fail to match the   *)\n(* b *: u argument. The extra wrap / unwrap ensures that this can't happen.  *)\n(* In the RL direction, the wrap / unwrap will be inserted on the redex side *)\n(* as needed, without causing unnecessary delta-expansion: using an explicit *)\n(* identity function would have Coq normalize the redex to head normal, then *)\n(* reduce the identity to expose the map_for_map projection, and the         *)\n(* expanded Linear.map structure would then be exposed in the result.        *)\n(*   Most of this machinery will be invisible to a casual user, because all  *)\n(* the projections and default instances involved are declared as coercions. *)\n\nVariables (S : ringType) (h : S -> V -> V) (h_law : Scale.law h).\n\nLemma linearZ c a (h_c := Scale.op h_law c) (f : Linear.map_for U s a h_c) u :\n  f (a *: u) = h_c (Linear.wrap f u).\nProof. by rewrite linearZ_LR; case: f => f /= ->. Qed.\n\nEnd BidirectionalLinearZ.\n\nSection LmodProperties.\n\nVariables (U V : lmodType R) (f : {linear U -> V}).\n\nLemma linearZZ : scalable f. Proof. exact: linearZ_LR. Qed.\nLemma linearPZ : linear f. Proof. exact: linearP. Qed.\n\nLemma can2_linear f' : cancel f f' -> cancel f' f -> linear f'.\nProof. by move=> fK f'K a x y /=; apply: (canLR fK); rewrite linearP !f'K. Qed.\n\nLemma bij_linear :\n  bijective f -> exists2 f' : {linear V -> U}, cancel f f' & cancel f' f.\nProof. by case=> f' fK f'K; exists (Linear (can2_linear fK f'K)). Qed.\n\nEnd LmodProperties.\n\nSection ScalarProperties.\n\nVariable (U : lmodType R) (f : {scalar U}).\n\nLemma scalarZ : scalable_for *%R f. Proof. exact: linearZ_LR. Qed.\nLemma scalarP : scalar f. Proof. exact: linearP. Qed.\n\nEnd ScalarProperties.\n\nSection LinearLmod.\n\nVariables (W U : lmodType R) (V : zmodType) (s : R -> V -> V).\nVariables (f : {linear U -> V | s}) (h : {linear W -> U}).\n\nLemma idfun_is_scalable : scalable (@idfun U). Proof. by []. Qed.\nCanonical idfun_linear := AddLinear idfun_is_scalable.\n\nLemma opp_is_scalable : scalable (-%R : U -> U).\nProof. by move=> a v /=; rewrite scalerN. Qed.\nCanonical opp_linear := AddLinear opp_is_scalable.\n\nLemma comp_is_scalable : scalable_for s (f \\o h).\nProof. by move=> a v /=; rewrite !linearZ_LR. Qed.\nCanonical comp_linear := AddLinear comp_is_scalable.\n\nVariables (s_law : Scale.law s) (g : {linear U -> V | Scale.op s_law}).\nLet Ds : s =1 Scale.op s_law. Proof. by rewrite Scale.opE. Qed.\n\nLemma null_fun_is_scalable : scalable_for (Scale.op s_law) (\\0 : U -> V).\nProof. by move=> a v /=; rewrite raddf0. Qed.\nCanonical null_fun_linear := AddLinear null_fun_is_scalable.\n\nLemma add_fun_is_scalable : scalable_for s (f \\+ g).\nProof. by move=> a u; rewrite /= !linearZ_LR !Ds raddfD. Qed.\nCanonical add_fun_linear := AddLinear add_fun_is_scalable.\n\nLemma sub_fun_is_scalable : scalable_for s (f \\- g).\nProof. by move=> a u; rewrite /= !linearZ_LR !Ds raddfB. Qed.\nCanonical sub_fun_linear := AddLinear sub_fun_is_scalable.\n\nLemma opp_fun_is_scalable : scalable_for s (\\- g).\nProof. by move=> a u; rewrite /= linearZ_LR Ds raddfN. Qed.\nCanonical opp_fun_linear := AddLinear opp_fun_is_scalable.\n\nEnd LinearLmod.\n\nSection LinearLalg.\n\nVariables (A : lalgType R) (U : lmodType R).\n\nVariables (a : A) (f : {linear U -> A}).\n\nFact mulr_fun_is_scalable : scalable (a \\o* f).\nProof. by move=> k x /=; rewrite linearZ scalerAl. Qed.\nCanonical mulr_fun_linear := AddLinear mulr_fun_is_scalable.\n\nEnd LinearLalg.\n\nEnd LinearTheory.\n\nModule LRMorphism.\n\nSection ClassDef.\n\nVariables (R : ringType) (A : lalgType R) (B : ringType) (s : R -> B -> B).\n\nRecord class_of (f : A -> B) : Prop :=\n  Class {base : rmorphism f; mixin : scalable_for s f}.\nLocal Coercion base : class_of >-> rmorphism.\nDefinition base2 f (fLM : class_of f) := Linear.Class fLM (mixin fLM).\nLocal Coercion base2 : class_of >-> lmorphism.\n\nStructure map (phAB : phant (A -> B)) := Pack {apply; _ : class_of apply}.\nLocal Coercion apply : map >-> Funclass.\n\nVariables (phAB : phant (A -> B)) (f : A -> B) (cF : map phAB).\nDefinition class := let: Pack _ c as cF' := cF return class_of cF' in c.\n\nDefinition clone :=\n  fun (g : RMorphism.map phAB) fM & phant_id (RMorphism.class g) fM =>\n  fun (h : Linear.map s phAB) fZ &\n     phant_id (Linear.mixin (Linear.class h)) fZ =>\n  Pack phAB (@Class f fM fZ).\n\nDefinition pack (fZ : scalable_for s f) :=\n  fun (g : RMorphism.map phAB) fM & phant_id (RMorphism.class g) fM =>\n  Pack phAB (Class fM fZ).\n\nCanonical additive := Additive.Pack phAB class.\nCanonical rmorphism := RMorphism.Pack phAB class.\nCanonical linear := Linear.Pack phAB class.\nCanonical join_rmorphism := @RMorphism.Pack _ _ phAB linear class.\nCanonical join_linear := @Linear.Pack R A B s phAB rmorphism class.\n\nEnd ClassDef.\n\nModule Exports.\nNotation lrmorphism_for s f := (class_of s f).\nNotation lrmorphism f := (lrmorphism_for *:%R f).\nCoercion base : lrmorphism_for >-> RMorphism.class_of.\nCoercion base2 : lrmorphism_for >-> lmorphism_for.\nCoercion apply : map >-> Funclass.\nNotation LRMorphism f_lrM := (Pack (Phant _) (Class f_lrM f_lrM)).\nNotation AddLRMorphism fZ := (pack fZ id).\nNotation \"{ 'lrmorphism' fAB | s }\" := (map s (Phant fAB))\n  (at level 0, format \"{ 'lrmorphism'  fAB  |  s }\") : type_scope.\nNotation \"{ 'lrmorphism' fAB }\" := {lrmorphism fAB | *:%R}\n  (at level 0, format \"{ 'lrmorphism'  fAB }\") : type_scope.\nNotation \"[ 'lrmorphism' 'of' f ]\" := (@clone _ _ _ _ _ f _ _ id _ _ id)\n  (at level 0, format \"[ 'lrmorphism'  'of'  f ]\") : form_scope.\nCoercion additive : map >-> Additive.map.\nCanonical additive.\nCoercion rmorphism : map >-> RMorphism.map.\nCanonical rmorphism.\nCoercion linear : map >-> Linear.map.\nCanonical linear.\nCanonical join_rmorphism.\nCanonical join_linear.\nEnd Exports.\n\nEnd LRMorphism.\nInclude LRMorphism.Exports.\n\nSection LRMorphismTheory.\n\nVariables (R : ringType) (A B : lalgType R) (C : ringType) (s : R -> C -> C).\nVariables (k : unit) (f : {lrmorphism A -> B}) (g : {lrmorphism B -> C | s}).\n\nDefinition idfun_lrmorphism := [lrmorphism of @idfun A].\nDefinition comp_lrmorphism := [lrmorphism of g \\o f].\nDefinition locked_lrmorphism := [lrmorphism of locked_with k (f : A -> B)].\n\nLemma rmorph_alg a : f a%:A = a%:A.\nProof. by rewrite linearZ rmorph1. Qed.\n\nLemma lrmorphismP : lrmorphism f. Proof. exact: LRMorphism.class. Qed.\n\nLemma can2_lrmorphism f' : cancel f f' -> cancel f' f -> lrmorphism f'.\nProof.\nby move=> fK f'K; split; [apply: (can2_rmorphism fK) | apply: (can2_linear fK)].\nQed.\n\nLemma bij_lrmorphism :\n  bijective f -> exists2 f' : {lrmorphism B -> A}, cancel f f' & cancel f' f.\nProof.\nby case/bij_rmorphism=> f' fK f'K; exists (AddLRMorphism (can2_linear fK f'K)).\nQed.\n\nEnd LRMorphismTheory.\n\nModule ComRing.\n\nDefinition RingMixin R one mul mulA mulC mul1x mul_addl :=\n  let mulx1 := Monoid.mulC_id mulC mul1x in\n  let mul_addr := Monoid.mulC_dist mulC mul_addl in\n  @Ring.EtaMixin R one mul mulA mul1x mulx1 mul_addl mul_addr.\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of R :=\n  Class {base : Ring.class_of R; mixin : commutative (Ring.mul base)}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> Ring.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c.\n\nDefinition pack mul0 (m0 : @commutative T T mul0) :=\n  fun bT b & phant_id (Ring.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Ring.class_of.\nArguments mixin [R].\nCoercion mixin : class_of >-> commutative.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nNotation comRingType := type.\nNotation ComRingType T m := (@pack T _ m _ _ id _ id).\nNotation ComRingMixin := RingMixin.\nNotation \"[ 'comRingType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'comRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'comRingType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'comRingType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd ComRing.\nImport ComRing.Exports.\n\nSection ComRingTheory.\n\nVariable R : comRingType.\nImplicit Types x y : R.\n\nLemma mulrC : @commutative R R *%R. Proof. by case: R => T []. Qed.\nCanonical mul_comoid := Monoid.ComLaw mulrC.\nLemma mulrCA : @left_commutative R R *%R. Proof. exact: mulmCA. Qed.\nLemma mulrAC : @right_commutative R R *%R. Proof. exact: mulmAC. Qed.\nLemma mulrACA : @interchange R *%R *%R. Proof. exact: mulmACA. Qed.\n\nLemma exprMn n : {morph (fun x => x ^+ n) : x y / x * y}.\nProof. by move=> x y; exact/exprMn_comm/mulrC. Qed.\n\nLemma prodrXl n I r (P : pred I) (F : I -> R) :\n  \\prod_(i <- r | P i) F i ^+ n = (\\prod_(i <- r | P i) F i) ^+ n.\nProof. by rewrite (big_morph _ (exprMn n) (expr1n _ n)). Qed.\n\nLemma prodr_undup_exp_count (I : eqType) r (P : pred I) (F : I -> R) :\n  \\prod_(i <- undup r | P i) F i ^+ count_mem i r = \\prod_(i <- r | P i) F i.\nProof. exact: big_undup_iterop_count.  Qed.\n\nLemma exprDn x y n :\n  (x + y) ^+ n = \\sum_(i < n.+1) (x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof. by rewrite exprDn_comm //; apply: mulrC. Qed.\n\nLemma exprBn x y n :\n  (x - y) ^+ n =\n     \\sum_(i < n.+1) ((-1) ^+ i * x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof. by rewrite exprBn_comm //; apply: mulrC. Qed.\n\nLemma subrXX x y n :\n  x ^+ n - y ^+ n = (x - y) * (\\sum_(i < n) x ^+ (n.-1 - i) * y ^+ i).\nProof. by rewrite -subrXX_comm //; apply: mulrC. Qed.\n\nLemma sqrrD x y : (x + y) ^+ 2 = x ^+ 2 + x * y *+ 2 + y ^+ 2.\nProof. by rewrite exprDn !big_ord_recr big_ord0 /= add0r mulr1 mul1r. Qed.\n\nLemma sqrrB x y : (x - y) ^+ 2 = x ^+ 2 - x * y *+ 2 + y ^+ 2.\nProof. by rewrite sqrrD mulrN mulNrn sqrrN. Qed.\n\nLemma subr_sqr x y : x ^+ 2 - y ^+ 2 = (x - y) * (x + y).\nProof. by rewrite subrXX !big_ord_recr big_ord0 /= add0r mulr1 mul1r. Qed.\n\nLemma subr_sqrDB x y : (x + y) ^+ 2 - (x - y) ^+ 2 = x * y *+ 4.\nProof.\nrewrite sqrrD sqrrB -!(addrAC _ (y ^+ 2)) opprB.\nby rewrite addrC addrA subrK -mulrnDr.\nQed.\n\nSection FrobeniusAutomorphism.\n\nVariables (p : nat) (charRp : p \\in [char R]).\n\nLemma Frobenius_aut_is_rmorphism : rmorphism (Frobenius_aut charRp).\nProof.\nsplit=> [x y|]; first exact: Frobenius_autB_comm (mulrC _ _).\nsplit=> [x y|]; first exact: Frobenius_autM_comm (mulrC _ _).\nexact: Frobenius_aut1.\nQed.\n\nCanonical Frobenius_aut_additive := Additive Frobenius_aut_is_rmorphism.\nCanonical Frobenius_aut_rmorphism := RMorphism Frobenius_aut_is_rmorphism.\n\nEnd FrobeniusAutomorphism.\n\nLemma exprDn_char x y n : [char R].-nat n -> (x + y) ^+ n = x ^+ n + y ^+ n.\nProof.\npose p := pdiv n; have [|n_gt1 charRn] := leqP n 1; first by case: (n) => [|[]].\nhave charRp: p \\in [char R] by rewrite (pnatPpi charRn) ?pi_pdiv.\nhave{charRn} /p_natP[e ->]: p.-nat n by rewrite -(eq_pnat _ (charf_eq charRp)).\nby elim: e => // e IHe; rewrite !expnSr !exprM IHe -Frobenius_autE rmorphD.\nQed.\n\nLemma rmorph_comm (S : ringType) (f : {rmorphism R -> S}) x y : \n  comm (f x) (f y).\nProof. by red; rewrite -!rmorphM mulrC. Qed.\n\nSection ScaleLinear.\n\nVariables (U V : lmodType R) (b : R) (f : {linear U -> V}).\n\nLemma scale_is_scalable : scalable ( *:%R b : V -> V).\nProof. by move=> a v /=; rewrite !scalerA mulrC. Qed.\nCanonical scale_linear := AddLinear scale_is_scalable.\n\nLemma scale_fun_is_scalable : scalable (b \\*: f).\nProof. by move=> a v /=; rewrite !linearZ. Qed.\nCanonical scale_fun_linear := AddLinear scale_fun_is_scalable.\n\nEnd ScaleLinear.\n\nEnd ComRingTheory.\n\nModule Algebra.\n\nSection Mixin.\n\nVariables (R : ringType) (A : lalgType R).\n\nDefinition axiom := forall k (x y : A), k *: (x * y) = x * (k *: y).\n\nLemma comm_axiom : phant A -> commutative (@mul A) -> axiom.\nProof. by move=> _ commA k x y; rewrite commA scalerAl commA. Qed.\n\nEnd Mixin.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nSet Primitive Projections.\nRecord class_of (T : Type) : Type := Class {\n  base : Lalgebra.class_of R T;\n  mixin : axiom (Lalgebra.Pack _ base)\n}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> Lalgebra.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c.\n\nDefinition pack b0 (ax0 : @axiom R b0) :=\n  fun bT b & phant_id (@Lalgebra.class R phR bT) b =>\n  fun   ax & phant_id ax0 ax => Pack phR (@Class T b ax).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition lmodType := @Lmodule.Pack R phR cT class.\nDefinition lalgType := @Lalgebra.Pack R phR cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Lalgebra.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCoercion lalgType : type >-> Lalgebra.type.\nCanonical lalgType.\nNotation algType R := (type (Phant R)).\nNotation AlgType R A ax := (@pack _ (Phant R) A _ ax _ _ id _ id).\nNotation CommAlgType R A := (AlgType R A (comm_axiom (Phant A) (@mulrC _))).\nNotation \"[ 'algType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'algType'  R  'of'  T  'for'  cT ]\")\n  : form_scope.\nNotation \"[ 'algType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'algType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Algebra.\nImport Algebra.Exports.\n\nModule ComAlgebra.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nSet Primitive Projections.\nRecord class_of (T : Type) : Type := Class {\n  base : Algebra.class_of R T;\n  mixin : commutative (Ring.mul base)\n}.\nUnset Primitive Projections.\nDefinition base2 R m := ComRing.Class (@mixin R m).\nLocal Coercion base : class_of >-> Algebra.class_of.\nLocal Coercion base2 : class_of >-> ComRing.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\n\nDefinition pack :=\n  fun bT b & phant_id (@Algebra.class R phR bT) (b : Algebra.class_of R T) =>\n  fun mT m & phant_id (ComRing.mixin (ComRing.class mT)) m =>\n  Pack (Phant R) (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition comRingType := @ComRing.Pack cT class.\nDefinition lmodType := @Lmodule.Pack R phR cT class.\nDefinition lalgType := @Lalgebra.Pack R phR cT class.\nDefinition algType := @Algebra.Pack R phR cT class.\nDefinition lmod_comRingType := @Lmodule.Pack R phR comRingType class.\nDefinition lalg_comRingType := @Lalgebra.Pack R phR comRingType class.\nDefinition alg_comRingType := @Algebra.Pack R phR comRingType class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Algebra.class_of.\nCoercion base2 : class_of >-> ComRing.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCoercion lalgType : type >-> Lalgebra.type.\nCanonical lalgType.\nCoercion algType : type >-> Algebra.type.\nCanonical algType.\nCanonical lmod_comRingType.\nCanonical lalg_comRingType.\nCanonical alg_comRingType.\n\nNotation comAlgType R := (type (Phant R)).\nNotation \"[ 'comAlgType' R 'of' T ]\" := (@pack _ (Phant R) T _ _ id _ _ id)\n  (at level 0, format \"[ 'comAlgType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd ComAlgebra.\nImport ComAlgebra.Exports.\n\nSection AlgebraTheory.\n\nVariables (R : comRingType) (A : algType R).\nImplicit Types (k : R) (x y : A).\n\nLemma scalerAr k x y : k *: (x * y) = x * (k *: y).\nProof. by case: A k x y => T []. Qed.\n\nLemma scalerCA k x y : k *: x * y = x * (k *: y).\nProof. by rewrite -scalerAl scalerAr. Qed.\n\nLemma mulr_algr a x : x * a%:A = a *: x.\nProof. by rewrite -scalerAr mulr1. Qed.\n\nLemma comm_alg a x : comm a%:A x.\nProof. by rewrite /comm mulr_algr mulr_algl. Qed.\n\nLemma exprZn k x n : (k *: x) ^+ n = k ^+ n *: x ^+ n.\nProof.\nelim: n => [|n IHn]; first by rewrite !expr0 scale1r.\nby rewrite !exprS IHn -scalerA scalerAr scalerAl.\nQed.\n\nLemma scaler_prod I r (P : pred I) (F : I -> R) (G : I -> A) :\n  \\prod_(i <- r | P i) (F i *: G i) =\n    \\prod_(i <- r | P i) F i *: \\prod_(i <- r | P i) G i.\nProof.\nelim/big_rec3: _ => [|i x a _ _ ->]; first by rewrite scale1r.\nby rewrite -scalerAl -scalerAr scalerA.\nQed.\n\nLemma scaler_prodl (I : finType) (S : pred I) (F : I -> A) k :\n  \\prod_(i in S) (k *: F i)  = k ^+ #|S| *: \\prod_(i in S) F i.\nProof. by rewrite scaler_prod prodr_const. Qed.\n\nLemma scaler_prodr (I : finType) (S : pred I) (F : I -> R) x :\n  \\prod_(i in S) (F i *: x)  = \\prod_(i in S) F i *: x ^+ #|S|.\nProof. by rewrite scaler_prod prodr_const. Qed.\n\nCanonical regular_comRingType := [comRingType of R^o].\nCanonical regular_algType := CommAlgType R R^o.\nCanonical regular_comAlgType := [comAlgType R of R^o].\n\nVariables (U : lmodType R) (a : A) (f : {linear U -> A}).\n\nLemma mull_fun_is_scalable : scalable (a \\*o f).\nProof. by move=> k x /=; rewrite linearZ scalerAr. Qed.\nCanonical mull_fun_linear := AddLinear mull_fun_is_scalable.\n\nEnd AlgebraTheory.\n\nModule UnitRing.\n\nRecord mixin_of (R : ringType) : Type := Mixin {\n  unit : pred R;\n  inv : R -> R;\n  _ : {in unit, left_inverse 1 inv *%R};\n  _ : {in unit, right_inverse 1 inv *%R};\n  _ : forall x y, y * x = 1 /\\ x * y = 1 -> unit x;\n  _ : {in [predC unit], inv =1 id}\n}.\n\nDefinition EtaMixin R unit inv mulVr mulrV unitP inv_out :=\n  let _ := @Mixin R unit inv mulVr mulrV unitP inv_out in\n  @Mixin (Ring.Pack (Ring.class R)) unit inv mulVr mulrV unitP inv_out.\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of (R : Type) : Type := Class {\n  base : Ring.class_of R;\n  mixin : mixin_of (Ring.Pack base)\n}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> Ring.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c.\n\nDefinition pack b0 (m0 : mixin_of (@Ring.Pack T b0)) :=\n  fun bT b & phant_id (Ring.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Ring.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nNotation unitRingType := type.\nNotation UnitRingType T m := (@pack T _ m _ _ id _ id).\nNotation UnitRingMixin := EtaMixin.\nNotation \"[ 'unitRingType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'unitRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'unitRingType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'unitRingType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd UnitRing.\nImport UnitRing.Exports.\n\nDefinition unit {R : unitRingType} :=\n  [qualify a u : R | UnitRing.unit (UnitRing.class R) u].\nFact unit_key R : pred_key (@unit R). Proof. by []. Qed.\nCanonical unit_keyed R := KeyedQualifier (@unit_key R).\nDefinition inv {R : unitRingType} : R -> R := UnitRing.inv (UnitRing.class R).\n\nLocal Notation \"x ^-1\" := (inv x).\nLocal Notation \"x / y\" := (x * y^-1).\nLocal Notation \"x ^- n\" := ((x ^+ n)^-1).\n\nSection UnitRingTheory.\n\nVariable R : unitRingType.\nImplicit Types x y : R.\n\nLemma divrr : {in unit, right_inverse 1 (@inv R) *%R}.\nProof. by case: R => T [? []]. Qed.\nDefinition mulrV := divrr.\n\nLemma mulVr : {in unit, left_inverse 1 (@inv R) *%R}.\nProof. by case: R => T [? []]. Qed.\n\nLemma invr_out x : x \\isn't a unit -> x^-1 = x.\nProof. by case: R x => T [? []]. Qed.\n\nLemma unitrP x : reflect (exists y, y * x = 1 /\\ x * y = 1) (x \\is a unit).\nProof.\napply: (iffP idP) => [Ux | []]; last by case: R x => T [? []].\nby exists x^-1; rewrite divrr ?mulVr.\nQed.\n\nLemma mulKr : {in unit, left_loop (@inv R) *%R}.\nProof. by move=> x Ux y; rewrite mulrA mulVr ?mul1r. Qed.\n\nLemma mulVKr : {in unit, rev_left_loop (@inv R) *%R}.\nProof. by move=> x Ux y; rewrite mulrA mulrV ?mul1r. Qed.\n\nLemma mulrK : {in unit, right_loop (@inv R) *%R}.\nProof. by move=> x Ux y; rewrite -mulrA divrr ?mulr1. Qed.\n\nLemma mulrVK : {in unit, rev_right_loop (@inv R) *%R}.\nProof. by move=> x Ux y; rewrite -mulrA mulVr ?mulr1. Qed.\nDefinition divrK := mulrVK.\n\nLemma mulrI : {in @unit R, right_injective *%R}.\nProof. by move=> x Ux; apply: can_inj (mulKr Ux). Qed.\n\nLemma mulIr : {in @unit R, left_injective *%R}.\nProof. by move=> x Ux; apply: can_inj (mulrK Ux). Qed.\n\n(* Due to noncommutativity, fractions are inverted. *)\nLemma telescope_prodr n m (f : nat -> R) :\n    (forall k, n < k < m -> f k \\is a unit) -> n < m ->\n  \\prod_(n <= k < m) (f k / f k.+1) = f n / f m.\nProof.\nmove=> Uf ltnm; rewrite (telescope_big (fun i j => f i / f j)) ?ltnm//.\nby move=> k ltnkm /=; rewrite mulrA divrK// Uf.\nQed.\n\nLemma telescope_prodr_eq n m (f u : nat -> R) : n < m ->\n    (forall k, n < k < m -> f k \\is a unit) ->\n    (forall k, (n <= k < m)%N -> u k = f k / f k.+1) ->\n  \\prod_(n <= k < m) u k = f n / f m.\nProof.\nby move=> ? ? uE; under eq_big_nat do rewrite uE //=; exact: telescope_prodr.\nQed.\n\nLemma commrV x y : comm x y -> comm x y^-1.\nProof.\nhave [Uy cxy | /invr_out-> //] := boolP (y \\in unit).\nby apply: (canLR (mulrK Uy)); rewrite -mulrA cxy mulKr.\nQed.\n\nLemma unitrE x : (x \\is a unit) = (x / x == 1).\nProof.\napply/idP/eqP=> [Ux | xx1]; first exact: divrr.\nby apply/unitrP; exists x^-1; rewrite -commrV.\nQed.\n\nLemma invrK : involutive (@inv R).\nProof.\nmove=> x; case Ux: (x \\in unit); last by rewrite !invr_out ?Ux.\nrewrite -(mulrK Ux _^-1) -mulrA commrV ?mulKr //.\nby apply/unitrP; exists x; rewrite divrr ?mulVr.\nQed.\n\nLemma invr_inj : injective (@inv R).\nProof. exact: inv_inj invrK. Qed.\n\nLemma unitrV x : (x^-1 \\in unit) = (x \\in unit).\nProof. by rewrite !unitrE invrK commrV. Qed.\n\nLemma unitr1 : 1 \\in @unit R.\nProof. by apply/unitrP; exists 1; rewrite mulr1. Qed.\n\nLemma invr1 : 1^-1 = 1 :> R.\nProof. by rewrite -{2}(mulVr unitr1) mulr1. Qed.\n\nLemma div1r x : 1 / x = x^-1. Proof. by rewrite mul1r. Qed.\nLemma divr1 x : x / 1 = x. Proof. by rewrite invr1 mulr1. Qed.\n\nLemma natr_div m d :\n  d %| m -> d%:R \\is a @unit R -> (m %/ d)%:R = m%:R / d%:R :> R.\nProof.\nby rewrite dvdn_eq => /eqP def_m unit_d; rewrite -{2}def_m natrM mulrK.\nQed.\n\nLemma divrI : {in unit, right_injective (fun x y => x / y)}.\nProof. by move=> x /mulrI/inj_comp; apply; apply: invr_inj. Qed.\n\nLemma divIr : {in unit, left_injective (fun x y => x / y)}.\nProof. by move=> x; rewrite -unitrV => /mulIr. Qed.\n\nLemma unitr0 : (0 \\is a @unit R) = false.\nProof. by apply/unitrP=> [[x [_ /esym/eqP]]]; rewrite mul0r oner_eq0. Qed.\n\nLemma invr0 : 0^-1 = 0 :> R.\nProof. by rewrite invr_out ?unitr0. Qed.\n\nLemma unitrN1 : -1 \\is a @unit R.\nProof. by apply/unitrP; exists (-1); rewrite mulrNN mulr1. Qed.\n\nLemma invrN1 : (-1)^-1 = -1 :> R.\nProof. by rewrite -{2}(divrr unitrN1) mulN1r opprK. Qed.\n\nLemma invr_sign n : ((-1) ^- n) = (-1) ^+ n :> R.\nProof. by rewrite -signr_odd; case: (odd n); rewrite (invr1, invrN1). Qed.\n\nLemma unitrMl x y : y \\is a unit -> (x * y \\is a unit) = (x \\is a unit).\nProof.\nmove=> Uy; wlog Ux: x y Uy / x \\is a unit => [WHxy|].\n  by apply/idP/idP=> Ux; first rewrite -(mulrK Uy x); rewrite WHxy ?unitrV.\nrewrite Ux; apply/unitrP; exists (y^-1 * x^-1).\nby rewrite -!mulrA mulKr ?mulrA ?mulrK ?divrr ?mulVr.\nQed.\n\nLemma unitrMr x y : x \\is a unit -> (x * y \\is a unit) = (y \\is a unit).\nProof.\nmove=> Ux; apply/idP/idP=> [Uxy | Uy]; last by rewrite unitrMl.\nby rewrite -(mulKr Ux y) unitrMl ?unitrV.\nQed.\n\nLemma invrM : {in unit &, forall x y, (x * y)^-1 = y^-1 * x^-1}.\nProof.\nmove=> x y Ux Uy; have Uxy: (x * y \\in unit) by rewrite unitrMl.\nby apply: (mulrI Uxy); rewrite divrr ?mulrA ?mulrK ?divrr.\nQed.\n\nLemma unitrM_comm x y :\n  comm x y -> (x * y \\is a unit) = (x \\is a unit) && (y \\is a unit).\nProof.\nmove=> cxy; apply/idP/andP=> [Uxy | [Ux Uy]]; last by rewrite unitrMl.\nsuffices Ux: x \\in unit by rewrite unitrMr in Uxy.\napply/unitrP; case/unitrP: Uxy => z [zxy xyz]; exists (y * z).\nrewrite mulrA xyz -{1}[y]mul1r -{1}zxy cxy -!mulrA (mulrA x) (mulrA _ z) xyz.\nby rewrite mul1r -cxy.\nQed.\n\nLemma unitrX x n : x \\is a unit -> x ^+ n \\is a unit.\nProof.\nby move=> Ux; elim: n => [|n IHn]; rewrite ?unitr1 // exprS unitrMl.\nQed.\n\nLemma unitrX_pos x n : n > 0 -> (x ^+ n \\in unit) = (x \\in unit).\nProof.\ncase: n => // n _; rewrite exprS unitrM_comm; last exact: commrX.\nby case Ux: (x \\is a unit); rewrite // unitrX.\nQed.\n\nLemma exprVn x n : x^-1 ^+ n = x ^- n.\nProof.\nelim: n => [|n IHn]; first by rewrite !expr0 ?invr1.\ncase Ux: (x \\is a unit); first by rewrite exprSr exprS IHn -invrM // unitrX.\nby rewrite !invr_out ?unitrX_pos ?Ux.\nQed.\n\nLemma exprB m n x : n <= m -> x \\is a unit -> x ^+ (m - n) = x ^+ m / x ^+ n.\nProof. by move/subnK=> {2}<- Ux; rewrite exprD mulrK ?unitrX. Qed.\n\nLemma invr_neq0 x : x != 0 -> x^-1 != 0.\nProof.\nmove=> nx0; case Ux: (x \\is a unit); last by rewrite invr_out ?Ux.\nby apply/eqP=> x'0; rewrite -unitrV x'0 unitr0 in Ux.\nQed.\n\nLemma invr_eq0 x : (x^-1 == 0) = (x == 0).\nProof. by apply: negb_inj; apply/idP/idP; move/invr_neq0; rewrite ?invrK. Qed.\n\nLemma invr_eq1 x : (x^-1 == 1) = (x == 1).\nProof. by rewrite (inv_eq invrK) invr1. Qed.\n\nLemma rev_unitrP (x y : R^c) : y * x = 1 /\\ x * y = 1 -> x \\is a unit.\nProof. by case=> [yx1 xy1]; apply/unitrP; exists y. Qed.\n\nDefinition converse_unitRingMixin :=\n  @UnitRing.Mixin _ (unit : {pred R^c}) _ mulrV mulVr rev_unitrP invr_out.\nCanonical converse_unitRingType := UnitRingType R^c converse_unitRingMixin.\nCanonical regular_unitRingType := [unitRingType of R^o].\n\nSection ClosedPredicates.\n\nVariables S : {pred R}.\n\nDefinition invr_closed := {in S, forall x, x^-1 \\in S}.\nDefinition divr_2closed := {in S &, forall x y, x / y \\in S}.\nDefinition divr_closed := 1 \\in S /\\ divr_2closed.\nDefinition sdivr_closed := -1 \\in S /\\ divr_2closed.\nDefinition divring_closed := [/\\ 1 \\in S, subr_2closed S & divr_2closed].\n\nLemma divr_closedV : divr_closed -> invr_closed.\nProof. by case=> S1 Sdiv x Sx; rewrite -[x^-1]mul1r Sdiv. Qed.\n\nLemma divr_closedM : divr_closed -> mulr_closed S.\nProof.\nby case=> S1 Sdiv; split=> // x y Sx Sy; rewrite -[y]invrK -[y^-1]mul1r !Sdiv.\nQed.\n\nLemma sdivr_closed_div : sdivr_closed -> divr_closed.\nProof. by case=> SN1 Sdiv; split; rewrite // -(divrr unitrN1) Sdiv. Qed.\n\nLemma sdivr_closedM : sdivr_closed -> smulr_closed S.\nProof.\nby move=> Sdiv; have [_ SM] := divr_closedM (sdivr_closed_div Sdiv); case: Sdiv.\nQed.\n\nLemma divring_closedBM : divring_closed -> subring_closed S.\nProof. by case=> S1 SB Sdiv; split=> //; case: divr_closedM. Qed.\n\nLemma divring_closed_div : divring_closed -> sdivr_closed.\nProof.\ncase=> S1 SB Sdiv; split; rewrite ?zmod_closedN //.\nexact/subring_closedB/divring_closedBM.\nQed.\n\nEnd ClosedPredicates.\n\nEnd UnitRingTheory.\n\nArguments invrK {R}.\nArguments invr_inj {R} [x1 x2].\nArguments telescope_prodr_eq {R n m} f u.\n\nSection UnitRingMorphism.\n\nVariables (R S : unitRingType) (f : {rmorphism R -> S}).\n\nLemma rmorph_unit x : x \\in unit -> f x \\in unit.\nProof.\ncase/unitrP=> y [yx1 xy1]; apply/unitrP.\nby exists (f y); rewrite -!rmorphM // yx1 xy1 rmorph1.\nQed.\n\nLemma rmorphV : {in unit, {morph f: x / x^-1}}.\nProof.\nmove=> x Ux; rewrite /= -[(f x)^-1]mul1r.\nby apply: (canRL (mulrK (rmorph_unit Ux))); rewrite -rmorphM mulVr ?rmorph1.\nQed.\n\nLemma rmorph_div x y : y \\in unit -> f (x / y) = f x / f y.\nProof. by move=> Uy; rewrite rmorphM rmorphV. Qed.\n\nEnd UnitRingMorphism.\n\nModule ComUnitRing.\n\nSection Mixin.\n\nVariables (R : comRingType) (unit : pred R) (inv : R -> R).\nHypothesis mulVx : {in unit, left_inverse 1 inv *%R}.\nHypothesis unitPl : forall x y, y * x = 1 -> unit x.\n\nFact mulC_mulrV : {in unit, right_inverse 1 inv *%R}.\nProof. by move=> x Ux /=; rewrite mulrC mulVx. Qed.\n\nFact mulC_unitP x y : y * x = 1 /\\ x * y = 1 -> unit x.\nProof. by case=> yx _; apply: unitPl yx. Qed.\n\nDefinition Mixin := UnitRingMixin mulVx mulC_mulrV mulC_unitP.\n\nEnd Mixin.\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of (R : Type) : Type := Class {\n  base : ComRing.class_of R;\n  mixin : UnitRing.mixin_of (Ring.Pack base)\n}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> ComRing.class_of.\nDefinition base2 R m := UnitRing.Class (@mixin R m).\nLocal Coercion base2 : class_of >-> UnitRing.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\n\nDefinition pack :=\n  fun bT b & phant_id (ComRing.class bT) (b : ComRing.class_of T) =>\n  fun mT m & phant_id (UnitRing.class mT) (@UnitRing.Class T b m) =>\n  Pack (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition comRingType := @ComRing.Pack cT class.\nDefinition unitRingType := @UnitRing.Pack cT class.\nDefinition com_unitRingType := @UnitRing.Pack comRingType class.\n\nEnd ClassDef.\n\nModule Import Exports.\nCoercion base : class_of >-> ComRing.class_of.\nCoercion mixin : class_of >-> UnitRing.mixin_of.\nCoercion base2 : class_of >-> UnitRing.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCanonical com_unitRingType.\nNotation comUnitRingType := type.\nNotation ComUnitRingMixin := Mixin.\nNotation \"[ 'comUnitRingType' 'of' T ]\" := (@pack T _ _ id _ _ id)\n  (at level 0, format \"[ 'comUnitRingType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd ComUnitRing.\nImport ComUnitRing.Exports.\n\nModule UnitAlgebra.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nSet Primitive Projections.\nRecord class_of (T : Type) : Type := Class {\n  base : Algebra.class_of R T;\n  mixin : GRing.UnitRing.mixin_of (Ring.Pack base)\n}.\nUnset Primitive Projections.\nDefinition base2 R m := UnitRing.Class (@mixin R m).\nLocal Coercion base : class_of >-> Algebra.class_of.\nLocal Coercion base2 : class_of >-> UnitRing.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\n\nDefinition pack :=\n  fun bT b & phant_id (@Algebra.class R phR bT) (b : Algebra.class_of R T) =>\n  fun mT m & phant_id (UnitRing.mixin (UnitRing.class mT)) m =>\n  Pack (Phant R) (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition unitRingType := @UnitRing.Pack cT class.\nDefinition lmodType := @Lmodule.Pack R phR cT class.\nDefinition lalgType := @Lalgebra.Pack R phR cT class.\nDefinition algType := @Algebra.Pack R phR cT class.\nDefinition lmod_unitRingType := @Lmodule.Pack R phR unitRingType class.\nDefinition lalg_unitRingType := @Lalgebra.Pack R phR unitRingType class.\nDefinition alg_unitRingType := @Algebra.Pack R phR unitRingType class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Algebra.class_of.\nCoercion base2 : class_of >-> UnitRing.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCoercion lalgType : type >-> Lalgebra.type.\nCanonical lalgType.\nCoercion algType : type >-> Algebra.type.\nCanonical algType.\nCanonical lmod_unitRingType.\nCanonical lalg_unitRingType.\nCanonical alg_unitRingType.\nNotation unitAlgType R := (type (Phant R)).\nNotation \"[ 'unitAlgType' R 'of' T ]\" := (@pack _ (Phant R) T _ _ id _ _ id)\n  (at level 0, format \"[ 'unitAlgType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd UnitAlgebra.\nImport UnitAlgebra.Exports.\n\nModule ComUnitAlgebra.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nSet Primitive Projections.\nRecord class_of (T : Type) : Type := Class {\n  base : ComAlgebra.class_of R T;\n  mixin : GRing.UnitRing.mixin_of (ComRing.Pack base)\n}.\nUnset Primitive Projections.\nDefinition base2 R m := UnitAlgebra.Class (@mixin R m).\nDefinition base3 R m := ComUnitRing.Class (@mixin R m).\nLocal Coercion base : class_of >-> ComAlgebra.class_of.\nLocal Coercion base2 : class_of >-> UnitAlgebra.class_of.\nLocal Coercion base3 : class_of >-> ComUnitRing.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\n\nDefinition pack :=\n  fun bT b & phant_id (@ComAlgebra.class R phR bT) (b : ComAlgebra.class_of R T) =>\n  fun mT m & phant_id (UnitRing.mixin (UnitRing.class mT)) m =>\n  Pack (Phant R) (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition unitRingType := @UnitRing.Pack cT class.\nDefinition comRingType := @ComRing.Pack cT class.\nDefinition comUnitRingType := @ComUnitRing.Pack cT class.\nDefinition lmodType := @Lmodule.Pack R phR cT class.\nDefinition lalgType := @Lalgebra.Pack R phR cT class.\nDefinition algType := @Algebra.Pack R phR cT class.\nDefinition comAlgType := @ComAlgebra.Pack R phR cT class.\nDefinition unitAlgType := @UnitAlgebra.Pack R phR cT class.\nDefinition comalg_unitRingType := @ComAlgebra.Pack R phR unitRingType class.\nDefinition comalg_comUnitRingType :=\n  @ComAlgebra.Pack R phR comUnitRingType class.\nDefinition comalg_unitAlgType := @ComAlgebra.Pack R phR unitAlgType class.\nDefinition unitalg_comRingType := @UnitAlgebra.Pack R phR comRingType class.\nDefinition unitalg_comUnitRingType :=\n  @UnitAlgebra.Pack R phR comUnitRingType class.\nDefinition lmod_comUnitRingType := @Lmodule.Pack R phR comUnitRingType class.\nDefinition lalg_comUnitRingType := @Lalgebra.Pack R phR comUnitRingType class.\nDefinition alg_comUnitRingType := @Algebra.Pack R phR comUnitRingType class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> ComAlgebra.class_of.\nCoercion base2 : class_of >-> UnitAlgebra.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCoercion lalgType : type >-> Lalgebra.type.\nCanonical lalgType.\nCoercion algType : type >-> Algebra.type.\nCanonical algType.\nCoercion comAlgType : type >-> ComAlgebra.type.\nCanonical comAlgType.\nCoercion unitAlgType : type >-> UnitAlgebra.type.\nCanonical unitAlgType.\nCanonical comalg_unitRingType.\nCanonical comalg_comUnitRingType.\nCanonical comalg_unitAlgType.\nCanonical unitalg_comRingType.\nCanonical unitalg_comUnitRingType.\nCanonical lmod_comUnitRingType.\nCanonical lalg_comUnitRingType.\nCanonical alg_comUnitRingType.\n\nNotation comUnitAlgType R := (type (Phant R)).\nNotation \"[ 'comUnitAlgType' R 'of' T ]\" := (@pack _ (Phant R) T _ _ id _ _ id)\n  (at level 0, format \"[ 'comUnitAlgType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd ComUnitAlgebra.\nImport ComUnitAlgebra.Exports.\n\nSection ComUnitRingTheory.\n\nVariable R : comUnitRingType.\nImplicit Types x y : R.\n\nLemma unitrM x y : (x * y \\in unit) = (x \\in unit) && (y \\in unit).\nProof. exact/unitrM_comm/mulrC. Qed.\n\nLemma unitrPr x : reflect (exists y, x * y = 1) (x \\in unit).\nProof.\nby apply: (iffP (unitrP x)) => [[y []] | [y]]; exists y; rewrite // mulrC.\nQed.\n\nLemma mulr1_eq x y : x * y = 1 -> x^-1 = y.\nProof.\nby move=> xy_eq1; rewrite -[LHS]mulr1 -xy_eq1; apply/mulKr/unitrPr; exists y.\nQed.\n\nLemma divr1_eq x y : x / y = 1 -> x = y. Proof. by move/mulr1_eq/invr_inj. Qed.\n\nLemma divKr x : x \\is a unit -> {in unit, involutive (fun y => x / y)}.\nProof. by move=> Ux y Uy; rewrite /= invrM ?unitrV // invrK mulrC divrK. Qed.\n\nLemma expr_div_n x y n : (x / y) ^+ n = x ^+ n / y ^+ n.\nProof. by rewrite exprMn exprVn. Qed.\n\nCanonical regular_comUnitRingType := [comUnitRingType of R^o].\nCanonical regular_unitAlgType := [unitAlgType R of R^o].\nCanonical regular_comUnitAlgType := [comUnitAlgType R of R^o].\n\nEnd ComUnitRingTheory.\n\nSection UnitAlgebraTheory.\n\nVariable (R : comUnitRingType) (A : unitAlgType R).\nImplicit Types (k : R) (x y : A).\n\nLemma scaler_injl : {in unit, @right_injective R A A *:%R}.\nProof.\nmove=> k Uk x1 x2 Hx1x2.\nby rewrite -[x1]scale1r -(mulVr Uk) -scalerA Hx1x2 scalerA mulVr // scale1r.\nQed.\n\nLemma scaler_unit k x : k \\in unit -> (k *: x \\in unit) = (x \\in unit).\nProof.\nmove=> Uk; apply/idP/idP=> [Ukx | Ux]; apply/unitrP; last first.\n  exists (k^-1 *: x^-1).\n  by rewrite -!scalerAl -!scalerAr !scalerA !mulVr // !mulrV // scale1r.\nexists (k *: (k *: x)^-1); split.\n  apply: (mulrI Ukx).\n  by rewrite mulr1 mulrA -scalerAr mulrV // -scalerAl mul1r.\napply: (mulIr Ukx).\nby rewrite mul1r -mulrA -scalerAl mulVr // -scalerAr mulr1.\nQed.\n \nLemma invrZ k x : k \\in unit -> x \\in unit -> (k *: x)^-1 = k^-1 *: x^-1.\nProof.\nmove=> Uk Ux; have Ukx: (k *: x \\in unit) by rewrite scaler_unit.\napply: (mulIr Ukx).\nby rewrite mulVr // -scalerAl -scalerAr scalerA !mulVr // scale1r.\nQed.\n\nSection ClosedPredicates.\n\nVariables S : {pred A}.\n\nDefinition divalg_closed := [/\\ 1 \\in S, linear_closed S & divr_2closed S].\n\nLemma divalg_closedBdiv : divalg_closed -> divring_closed S.\nProof. by case=> S1 /linear_closedB. Qed.\n\nLemma divalg_closedZ : divalg_closed -> subalg_closed S.\nProof. by case=> S1 Slin Sdiv; split=> //; have [] := @divr_closedM A S. Qed.\n\nEnd ClosedPredicates.\n\nEnd UnitAlgebraTheory.\n\n(* Interface structures for algebraically closed predicates. *)\nModule Pred.\n\nStructure opp V S := Opp {opp_key : pred_key S; _ : @oppr_closed V S}.\nStructure add V S := Add {add_key : pred_key S; _ : @addr_closed V S}.\nStructure mul R S := Mul {mul_key : pred_key S; _ : @mulr_closed R S}.\nStructure zmod V S := Zmod {zmod_add : add S; _ : @oppr_closed V S}.\nStructure semiring R S := Semiring {semiring_add : add S; _ : @mulr_closed R S}.\nStructure smul R S := Smul {smul_opp : opp S; _ : @mulr_closed R S}.\nStructure div R S := Div {div_mul : mul S; _ : @invr_closed R S}.\nStructure submod R V S :=\n  Submod {submod_zmod : zmod S; _ : @scaler_closed R V S}.\nStructure subring R S := Subring {subring_zmod : zmod S; _ : @mulr_closed R S}.\nStructure sdiv R S := Sdiv {sdiv_smul : smul S; _ : @invr_closed R S}.\nStructure subalg (R : ringType) (A : lalgType R) S :=\n  Subalg {subalg_ring : subring S; _ : @scaler_closed R A S}.\nStructure divring R S :=\n  Divring {divring_ring : subring S; _ : @invr_closed R S}.\nStructure divalg (R : ringType) (A : unitAlgType R) S :=\n  Divalg {divalg_ring : divring S; _ : @scaler_closed R A S}.\n\nSection Subtyping.\n\nLtac done := case=> *; assumption.\nFact zmod_oppr R S : @zmod R S -> oppr_closed S. Proof. by []. Qed.\nFact semiring_mulr R S : @semiring R S -> mulr_closed S. Proof. by []. Qed.\nFact smul_mulr R S : @smul R S -> mulr_closed S. Proof. by []. Qed.\nFact submod_scaler R V S : @submod R V S -> scaler_closed S. Proof. by []. Qed.\nFact subring_mulr R S : @subring R S -> mulr_closed S. Proof. by []. Qed.\nFact sdiv_invr R S : @sdiv R S -> invr_closed S. Proof. by []. Qed.\nFact subalg_scaler R A S : @subalg R A S -> scaler_closed S. Proof. by []. Qed.\nFact divring_invr R S : @divring R S -> invr_closed S. Proof. by []. Qed.\nFact divalg_scaler R A S : @divalg R A S -> scaler_closed S. Proof. by []. Qed.\n\nDefinition zmod_opp R S (addS : @zmod R S) :=\n  Opp (add_key (zmod_add addS)) (zmod_oppr addS).\nDefinition semiring_mul R S (ringS : @semiring R S) :=\n  Mul (add_key (semiring_add ringS)) (semiring_mulr ringS).\nDefinition smul_mul R S (mulS : @smul R S) :=\n  Mul (opp_key (smul_opp mulS)) (smul_mulr mulS).\nDefinition subring_semi R S (ringS : @subring R S) :=\n  Semiring (zmod_add (subring_zmod ringS)) (subring_mulr ringS).\nDefinition subring_smul R S (ringS : @subring R S) :=\n  Smul (zmod_opp (subring_zmod ringS)) (subring_mulr ringS).\nDefinition sdiv_div R S (divS : @sdiv R S) :=\n  Div (smul_mul (sdiv_smul divS)) (sdiv_invr divS).\nDefinition subalg_submod R A S (algS : @subalg R A S) :=\n  Submod (subring_zmod (subalg_ring algS)) (subalg_scaler algS).\nDefinition divring_sdiv R S (ringS : @divring R S) :=\n  Sdiv (subring_smul (divring_ring ringS)) (divring_invr ringS).\nDefinition divalg_alg R A S (algS : @divalg R A S) :=\n  Subalg (divring_ring (divalg_ring algS)) (divalg_scaler algS).\n\nEnd Subtyping.\n\nSection Extensionality.\n(* This could be avoided by exploiting the Coq 8.4 eta-convertibility.        *)\n\nLemma opp_ext (U : zmodType) S k (kS : @keyed_pred U S k) :\n  oppr_closed kS -> oppr_closed S.\nProof. by move=> oppS x; rewrite -!(keyed_predE kS); apply: oppS. Qed.\n\nLemma add_ext (U : zmodType) S k (kS : @keyed_pred U S k) :\n  addr_closed kS -> addr_closed S.\nProof.\nby case=> S0 addS; split=> [|x y]; rewrite -!(keyed_predE kS) //; apply: addS.\nQed.\n\nLemma mul_ext (R : ringType) S k (kS : @keyed_pred R S k) :\n  mulr_closed kS -> mulr_closed S.\nProof.\nby case=> S1 mulS; split=> [|x y]; rewrite -!(keyed_predE kS) //; apply: mulS.\nQed.\n\nLemma scale_ext (R : ringType) (U : lmodType R) S k (kS : @keyed_pred U S k) :\n  scaler_closed kS -> scaler_closed S.\nProof. by move=> linS a x; rewrite -!(keyed_predE kS); apply: linS. Qed.\n\nLemma inv_ext (R : unitRingType) S k (kS : @keyed_pred R S k) :\n  invr_closed kS -> invr_closed S.\nProof. by move=> invS x; rewrite -!(keyed_predE kS); apply: invS. Qed.\n\nEnd Extensionality.\n\nModule Default.\nDefinition opp V S oppS := @Opp V S (DefaultPredKey S) oppS.\nDefinition add V S addS := @Add V S (DefaultPredKey S) addS.\nDefinition mul R S mulS := @Mul R S (DefaultPredKey S) mulS.\nDefinition zmod V S addS oppS := @Zmod V S (add addS) oppS.\nDefinition semiring R S addS mulS := @Semiring R S (add addS) mulS.\nDefinition smul R S oppS mulS := @Smul R S (opp oppS) mulS.\nDefinition div R S mulS invS := @Div R S (mul mulS) invS.\nDefinition submod R V S addS oppS linS := @Submod R V S (zmod addS oppS) linS.\nDefinition subring R S addS oppS mulS := @Subring R S (zmod addS oppS) mulS.\nDefinition sdiv R S oppS mulS invS := @Sdiv R S (smul oppS mulS) invS.\nDefinition subalg R A S addS oppS mulS linS :=\n  @Subalg R A S (subring addS oppS mulS) linS.\nDefinition divring R S addS oppS mulS invS :=\n  @Divring R S (subring addS oppS mulS) invS.\nDefinition divalg R A S addS oppS mulS invS linS :=\n  @Divalg R A S (divring addS oppS mulS invS) linS.\nEnd Default.\n\nModule Exports.\n\nNotation oppr_closed := oppr_closed.\nNotation addr_closed := addr_closed.\nNotation mulr_closed := mulr_closed.\nNotation zmod_closed := zmod_closed.\nNotation smulr_closed := smulr_closed.\nNotation invr_closed := invr_closed.\nNotation divr_closed := divr_closed.\nNotation scaler_closed := scaler_closed.\nNotation linear_closed := linear_closed.\nNotation submod_closed := submod_closed.\nNotation semiring_closed := semiring_closed.\nNotation subring_closed := subring_closed.\nNotation sdivr_closed := sdivr_closed.\nNotation subalg_closed := subalg_closed.\nNotation divring_closed := divring_closed.\nNotation divalg_closed := divalg_closed.\n \nCoercion zmod_closedD : zmod_closed >-> addr_closed.\nCoercion zmod_closedN : zmod_closed >-> oppr_closed.\nCoercion smulr_closedN : smulr_closed >-> oppr_closed.\nCoercion smulr_closedM : smulr_closed >-> mulr_closed.\nCoercion divr_closedV : divr_closed >-> invr_closed.\nCoercion divr_closedM : divr_closed >-> mulr_closed.\nCoercion submod_closedZ : submod_closed >-> scaler_closed.\nCoercion submod_closedB : submod_closed >-> zmod_closed.\nCoercion semiring_closedD : semiring_closed >-> addr_closed.\nCoercion semiring_closedM : semiring_closed >-> mulr_closed.\nCoercion subring_closedB : subring_closed >-> zmod_closed.\nCoercion subring_closedM : subring_closed >-> smulr_closed.\nCoercion subring_closed_semi : subring_closed >-> semiring_closed.\nCoercion sdivr_closedM : sdivr_closed >-> smulr_closed.\nCoercion sdivr_closed_div : sdivr_closed >-> divr_closed.\nCoercion subalg_closedZ : subalg_closed >-> submod_closed.\nCoercion subalg_closedBM : subalg_closed >-> subring_closed.\nCoercion divring_closedBM : divring_closed >-> subring_closed.\nCoercion divring_closed_div : divring_closed >-> sdivr_closed.\nCoercion divalg_closedZ : divalg_closed >-> subalg_closed.\nCoercion divalg_closedBdiv : divalg_closed >-> divring_closed.\n\nCoercion opp_key : opp >-> pred_key.\nCoercion add_key : add >-> pred_key.\nCoercion mul_key : mul >-> pred_key.\nCoercion zmod_opp : zmod >-> opp.\nCanonical zmod_opp.\nCoercion zmod_add : zmod >-> add.\nCoercion semiring_add : semiring >-> add.\nCoercion semiring_mul : semiring >-> mul.\nCanonical semiring_mul.\nCoercion smul_opp : smul >-> opp.\nCoercion smul_mul : smul >-> mul.\nCanonical smul_mul.\nCoercion div_mul : div >-> mul.\nCoercion submod_zmod : submod >-> zmod.\nCoercion subring_zmod : subring >-> zmod.\nCoercion subring_semi : subring >-> semiring.\nCanonical subring_semi.\nCoercion subring_smul : subring >-> smul.\nCanonical subring_smul.\nCoercion sdiv_smul : sdiv >-> smul.\nCoercion sdiv_div : sdiv >-> div.\nCanonical sdiv_div.\nCoercion subalg_submod : subalg >-> submod.\nCanonical subalg_submod.\nCoercion subalg_ring : subalg >-> subring.\nCoercion divring_ring : divring >-> subring.\nCoercion divring_sdiv : divring >-> sdiv.\nCanonical divring_sdiv.\nCoercion divalg_alg : divalg >-> subalg.\nCanonical divalg_alg.\nCoercion divalg_ring : divalg >-> divring.\n\nNotation opprPred := opp.\nNotation addrPred := add.\nNotation mulrPred := mul.\nNotation zmodPred := zmod.\nNotation semiringPred := semiring.\nNotation smulrPred := smul.\nNotation divrPred := div.\nNotation submodPred := submod.\nNotation subringPred := subring.\nNotation sdivrPred := sdiv.\nNotation subalgPred := subalg.\nNotation divringPred := divring.\nNotation divalgPred := divalg.\n\nDefinition OpprPred U S k kS NkS := Opp k (@opp_ext U S k kS NkS).\nDefinition AddrPred U S k kS DkS := Add k (@add_ext U S k kS DkS).\nDefinition MulrPred R S k kS MkS := Mul k (@mul_ext R S k kS MkS).\nDefinition ZmodPred U S k kS NkS := Zmod k (@opp_ext U S k kS NkS).\nDefinition SemiringPred R S k kS MkS := Semiring k (@mul_ext R S k kS MkS).\nDefinition SmulrPred R S k kS MkS := Smul k (@mul_ext R S k kS MkS).\nDefinition DivrPred R S k kS VkS := Div k (@inv_ext R S k kS VkS).\nDefinition SubmodPred R U S k kS ZkS := Submod k (@scale_ext R U S k kS ZkS).\nDefinition SubringPred R S k kS MkS := Subring k (@mul_ext R S k kS MkS).\nDefinition SdivrPred R S k kS VkS := Sdiv k (@inv_ext R S k kS VkS).\nDefinition SubalgPred (R : ringType) (A : lalgType R) S k kS ZkS :=\n  Subalg k (@scale_ext R A S k kS ZkS).\nDefinition DivringPred R S k kS VkS := Divring k (@inv_ext R S k kS VkS).\nDefinition DivalgPred (R : ringType) (A : unitAlgType R) S k kS ZkS :=\n  Divalg k (@scale_ext R A S k kS ZkS).\n\nEnd Exports.\n\nEnd Pred.\nImport Pred.Exports.\n\nModule DefaultPred.\n\nCanonical Pred.Default.opp.\nCanonical Pred.Default.add.\nCanonical Pred.Default.mul.\nCanonical Pred.Default.zmod.\nCanonical Pred.Default.semiring.\nCanonical Pred.Default.smul.\nCanonical Pred.Default.div.\nCanonical Pred.Default.submod.\nCanonical Pred.Default.subring.\nCanonical Pred.Default.sdiv.\nCanonical Pred.Default.subalg.\nCanonical Pred.Default.divring.\nCanonical Pred.Default.divalg.\n\nEnd DefaultPred.\n\nSection ZmodulePred.\n\nVariables (V : zmodType) (S : {pred V}).\n\nSection Add.\n\nVariables (addS : addrPred S) (kS : keyed_pred addS).\n\nLemma rpred0D : addr_closed kS.\nProof.\nby split=> [|x y]; rewrite !keyed_predE; case: addS => _ [_]//; apply.\nQed.\n\nLemma rpred0 : 0 \\in kS.\nProof. by case: rpred0D. Qed.\n\nLemma rpredD : {in kS &, forall u v, u + v \\in kS}.\nProof. by case: rpred0D. Qed.\n\nLemma rpred_sum I r (P : pred I) F :\n  (forall i, P i -> F i \\in kS) -> \\sum_(i <- r | P i) F i \\in kS.\nProof. by move=> IH; elim/big_ind: _; [apply: rpred0 | apply: rpredD |]. Qed.\n\nLemma rpredMn n : {in kS, forall u, u *+ n \\in kS}.\nProof. by move=> u Su; rewrite -(card_ord n) -sumr_const rpred_sum. Qed.\n\nEnd Add.\n\nSection Opp.\n\nVariables (oppS : opprPred S) (kS : keyed_pred oppS).\n\nLemma rpredNr : oppr_closed kS.\nProof. by move=> x; rewrite !keyed_predE; case: oppS => _; apply. Qed.\n\nLemma rpredN : {mono -%R: u / u \\in kS}.\nProof. by move=> u; apply/idP/idP=> /rpredNr; rewrite ?opprK; apply. Qed.\n\nEnd Opp.\n\nSection Sub.\n\nVariables (subS : zmodPred S) (kS : keyed_pred subS).\n\nLemma rpredB : {in kS &, forall u v, u - v \\in kS}.\nProof. by move=> u v Su Sv; rewrite /= rpredD ?rpredN. Qed.\n\nLemma rpredBC u v : u - v \\in kS = (v - u \\in kS).\nProof. by rewrite -rpredN opprB. Qed.\n\nLemma rpredMNn n : {in kS, forall u, u *- n \\in kS}.\nProof. by move=> u Su; rewrite /= rpredN rpredMn. Qed.\n\nLemma rpredDr x y : x \\in kS -> (y + x \\in kS) = (y \\in kS).\nProof.\nmove=> Sx; apply/idP/idP=> [Sxy | /rpredD-> //].\nby rewrite -(addrK x y) rpredB.\nQed.\n\nLemma rpredDl x y : x \\in kS -> (x + y \\in kS) = (y \\in kS).\nProof. by rewrite addrC; apply: rpredDr. Qed.\n\nLemma rpredBr x y : x \\in kS -> (y - x \\in kS) = (y \\in kS).\nProof. by rewrite -rpredN; apply: rpredDr. Qed.\n\nLemma rpredBl x y : x \\in kS -> (x - y \\in kS) = (y \\in kS).\nProof. by rewrite -(rpredN _ y); apply: rpredDl. Qed.\n\nEnd Sub.\n\nEnd ZmodulePred.\n\nSection RingPred.\n\nVariables (R : ringType) (S : {pred R}).\n\nLemma rpredMsign (oppS : opprPred S) (kS : keyed_pred oppS) n x :\n  ((-1) ^+ n * x \\in kS) = (x \\in kS).\nProof. by rewrite -signr_odd mulr_sign; case: ifP => // _; rewrite rpredN. Qed.\n\nSection Mul.\n\nVariables (mulS : mulrPred S) (kS : keyed_pred mulS).\n\nLemma rpred1M : mulr_closed kS.\nProof.\nby split=> [|x y]; rewrite !keyed_predE; case: mulS => _ [_] //; apply.\nQed.\n\nLemma rpred1 : 1 \\in kS.\nProof. by case: rpred1M. Qed.\n\nLemma rpredM : {in kS &, forall u v, u * v \\in kS}.\nProof. by case: rpred1M. Qed.\n\nLemma rpred_prod I r (P : pred I) F :\n  (forall i, P i -> F i \\in kS) -> \\prod_(i <- r | P i) F i \\in kS.\nProof. by move=> IH; elim/big_ind: _; [apply: rpred1 | apply: rpredM |]. Qed.\n\nLemma rpredX n : {in kS, forall u, u ^+ n \\in kS}.\nProof. by move=> u Su; rewrite -(card_ord n) -prodr_const rpred_prod. Qed.\n\nEnd Mul.\n\nLemma rpred_nat (rngS : semiringPred S) (kS : keyed_pred rngS) n : n%:R \\in kS.\nProof. by rewrite rpredMn ?rpred1. Qed.\n\nLemma rpredN1 (mulS : smulrPred S) (kS : keyed_pred mulS) : -1 \\in kS.\nProof. by rewrite rpredN rpred1. Qed.\n\nLemma rpred_sign (mulS : smulrPred S) (kS : keyed_pred mulS) n :\n  (-1) ^+ n \\in kS.\nProof. by rewrite rpredX ?rpredN1. Qed.\n\nEnd RingPred.\n\nSection LmodPred.\n\nVariables (R : ringType) (V : lmodType R) (S : {pred V}).\n\nLemma rpredZsign (oppS : opprPred S) (kS : keyed_pred oppS) n u :\n  ((-1) ^+ n *: u \\in kS) = (u \\in kS).\nProof. by rewrite -signr_odd scaler_sign fun_if if_arg rpredN if_same. Qed.\n\nLemma rpredZnat (addS : addrPred S) (kS : keyed_pred addS) n :\n  {in kS, forall u, n%:R *: u \\in kS}.\nProof. by move=> u Su; rewrite /= scaler_nat rpredMn. Qed.\n\nLemma rpredZ (linS : submodPred S) (kS : keyed_pred linS) : scaler_closed kS.\nProof. by move=> a u; rewrite !keyed_predE; case: {kS}linS => _; apply. Qed.\n\nEnd LmodPred.\n\nSection UnitRingPred.\n\nVariable R : unitRingType.\n\nSection Div.\n\nVariables (S : {pred R}) (divS : divrPred S) (kS : keyed_pred divS).\n\nLemma rpredVr x : x \\in kS -> x^-1 \\in kS.\nProof. by rewrite !keyed_predE; case: divS x. Qed.\n\nLemma rpredV x : (x^-1 \\in kS) = (x \\in kS).\nProof. by apply/idP/idP=> /rpredVr; rewrite ?invrK. Qed.\n\nLemma rpred_div : {in kS &, forall x y, x / y \\in kS}.\nProof. by move=> x y Sx Sy; rewrite /= rpredM ?rpredV. Qed.\n\nLemma rpredXN n : {in kS, forall x, x ^- n \\in kS}.\nProof. by move=> x Sx; rewrite /= rpredV rpredX. Qed.\n\nLemma rpredMl x y : x \\in kS -> x \\is a unit-> (x * y \\in kS) = (y \\in kS).\nProof.\nmove=> Sx Ux; apply/idP/idP=> [Sxy | /(rpredM Sx)-> //].\nby rewrite -(mulKr Ux y); rewrite rpredM ?rpredV.\nQed.\n\nLemma rpredMr x y : x \\in kS -> x \\is a unit -> (y * x \\in kS) = (y \\in kS).\nProof.\nmove=> Sx Ux; apply/idP/idP=> [Sxy | /rpredM-> //].\nby rewrite -(mulrK Ux y); rewrite rpred_div.\nQed.\n\nLemma rpred_divr x y : x \\in kS -> x \\is a unit -> (y / x \\in kS) = (y \\in kS).\nProof. by rewrite -rpredV -unitrV; apply: rpredMr. Qed.\n\nLemma rpred_divl x y : x \\in kS -> x \\is a unit -> (x / y \\in kS) = (y \\in kS).\nProof. by rewrite -(rpredV y); apply: rpredMl. Qed.\n\nEnd Div.\n\nFact unitr_sdivr_closed : @sdivr_closed R unit.\nProof. by split=> [|x y Ux Uy]; rewrite ?unitrN1 // unitrMl ?unitrV. Qed.\n\nCanonical unit_opprPred := OpprPred unitr_sdivr_closed.\nCanonical unit_mulrPred := MulrPred unitr_sdivr_closed.\nCanonical unit_divrPred := DivrPred unitr_sdivr_closed.\nCanonical unit_smulrPred := SmulrPred unitr_sdivr_closed.\nCanonical unit_sdivrPred := SdivrPred unitr_sdivr_closed.\n\nImplicit Type x : R.\n\nLemma unitrN x : (- x \\is a unit) = (x \\is a unit). Proof. exact: rpredN. Qed.\n\nLemma invrN x : (- x)^-1 = - x^-1.\nProof.\nhave [Ux | U'x] := boolP (x \\is a unit); last by rewrite !invr_out ?unitrN.\nby rewrite -mulN1r invrM ?unitrN1 // invrN1 mulrN1.\nQed.\n\nLemma divrNN x y : (- x) / (- y) = x / y.\nProof. by rewrite invrN mulrNN. Qed.\n\nLemma divrN x y : x / (- y) = - (x / y).\nProof. by rewrite invrN mulrN. Qed.\n\nLemma invr_signM n x : ((-1) ^+ n * x)^-1 = (-1) ^+ n * x^-1.\nProof. by rewrite -signr_odd !mulr_sign; case: ifP => // _; rewrite invrN. Qed.\n\nLemma divr_signM (b1 b2 : bool) x1 x2:\n  ((-1) ^+ b1 * x1) / ((-1) ^+ b2 * x2) = (-1) ^+ (b1 (+) b2) * (x1 / x2).\nProof. by rewrite invr_signM mulr_signM. Qed.\n\nEnd UnitRingPred.\n\n(* Reification of the theory of rings with units, in named style  *)\nSection TermDef.\n\nVariable R : Type.\n\nInductive term : Type :=\n| Var of nat\n| Const of R\n| NatConst of nat\n| Add of term & term\n| Opp of term\n| NatMul of term & nat\n| Mul of term & term\n| Inv of term\n| Exp of term & nat.\n\nInductive formula : Type :=\n| Bool of bool\n| Equal of term & term\n| Unit of term\n| And of formula & formula\n| Or of formula & formula\n| Implies of formula & formula\n| Not of formula\n| Exists of nat & formula\n| Forall of nat & formula.\n\nEnd TermDef.\n\nBind Scope term_scope with term.\nBind Scope term_scope with formula.\nArguments Add {R} t1%T t2%T.\nArguments Opp {R} t1%T.\nArguments NatMul {R} t1%T n%N.\nArguments Mul {R} t1%T t2%T.\nArguments Inv {R} t1%T.\nArguments Exp {R} t1%T n%N.\nArguments Equal {R} t1%T t2%T.\nArguments Unit {R} t1%T.\nArguments And {R} f1%T f2%T.\nArguments Or {R} f1%T f2%T.\nArguments Implies {R} f1%T f2%T.\nArguments Not {R} f1%T.\nArguments Exists {R} i%N f1%T.\nArguments Forall {R} i%N f1%T.\n\nArguments Bool {R} b.\nArguments Const {R} x.\n\nNotation True := (Bool true).\nNotation False := (Bool false).\n\nLocal Notation \"''X_' i\" := (Var _ i) : term_scope.\nLocal Notation \"n %:R\" := (NatConst _ n) : term_scope.\nLocal Notation \"x %:T\" := (Const x) : term_scope.\nLocal Notation \"0\" := 0%:R%T : term_scope.\nLocal Notation \"1\" := 1%:R%T : term_scope.\nLocal Infix \"+\" := Add : term_scope.\nLocal Notation \"- t\" := (Opp t) : term_scope.\nLocal Notation \"t - u\" := (Add t (- u)) : term_scope.\nLocal Infix \"*\" := Mul : term_scope.\nLocal Infix \"*+\" := NatMul : term_scope.\nLocal Notation \"t ^-1\" := (Inv t) : term_scope.\nLocal Notation \"t / u\" := (Mul t u^-1) : term_scope.\nLocal Infix \"^+\" := Exp : term_scope.\nLocal Infix \"==\" := Equal : term_scope.\nLocal Infix \"/\\\" := And : term_scope.\nLocal Infix \"\\/\" := Or : term_scope.\nLocal Infix \"==>\" := Implies : term_scope.\nLocal Notation \"~ f\" := (Not f) : term_scope.\nLocal Notation \"x != y\" := (Not (x == y)) : term_scope.\nLocal Notation \"''exists' ''X_' i , f\" := (Exists i f) : term_scope.\nLocal Notation \"''forall' ''X_' i , f\" := (Forall i f) : term_scope.\n\nSection Substitution.\n\nVariable R : Type.\n\nFixpoint tsubst (t : term R) (s : nat * term R) :=\n  match t with\n  | 'X_i => if i == s.1 then s.2 else t\n  | _%:T | _%:R => t\n  | t1 + t2 => tsubst t1 s + tsubst t2 s\n  | - t1 => - tsubst t1 s\n  | t1 *+ n => tsubst t1 s *+ n\n  | t1 * t2 => tsubst t1 s * tsubst t2 s\n  | t1^-1 => (tsubst t1 s)^-1\n  | t1 ^+ n => tsubst t1 s ^+ n\n  end%T.\n\nFixpoint fsubst (f : formula R) (s : nat * term R) :=\n  match f with\n  | Bool _ => f\n  | t1 == t2 => tsubst t1 s == tsubst t2 s\n  | Unit t1 => Unit (tsubst t1 s)\n  | f1 /\\ f2 => fsubst f1 s /\\ fsubst f2 s\n  | f1 \\/ f2 => fsubst f1 s \\/ fsubst f2 s\n  | f1 ==> f2 => fsubst f1 s ==> fsubst f2 s\n  | ~ f1 => ~ fsubst f1 s\n  | ('exists 'X_i, f1) => 'exists 'X_i, if i == s.1 then f1 else fsubst f1 s\n  | ('forall 'X_i, f1) => 'forall 'X_i, if i == s.1 then f1 else fsubst f1 s\n  end%T.\n\nEnd Substitution.\n\nSection EvalTerm.\n\nVariable R : unitRingType.\n\n(* Evaluation of a reified term into R a ring with units *)\nFixpoint eval (e : seq R) (t : term R) {struct t} : R :=\n  match t with\n  | ('X_i)%T => e`_i\n  | (x%:T)%T => x\n  | (n%:R)%T => n%:R\n  | (t1 + t2)%T => eval e t1 + eval e t2\n  | (- t1)%T => - eval e t1\n  | (t1 *+ n)%T => eval e t1 *+ n\n  | (t1 * t2)%T => eval e t1 * eval e t2\n  | t1^-1%T => (eval e t1)^-1\n  | (t1 ^+ n)%T => eval e t1 ^+ n\n  end.\n\nDefinition same_env (e e' : seq R) := nth 0 e =1 nth 0 e'.\n\nLemma eq_eval e e' t : same_env e e' -> eval e t = eval e' t.\nProof. by move=> eq_e; elim: t => //= t1 -> // t2 ->. Qed.\n\nLemma eval_tsubst e t s :\n  eval e (tsubst t s) = eval (set_nth 0 e s.1 (eval e s.2)) t.\nProof.\ncase: s => i u; elim: t => //=; do 2?[move=> ? -> //] => j.\nby rewrite nth_set_nth /=; case: (_ == _).\nQed.\n\n(* Evaluation of a reified formula *)\nFixpoint holds (e : seq R) (f : formula R) {struct f} : Prop :=\n  match f with\n  | Bool b => b\n  | (t1 == t2)%T => eval e t1 = eval e t2\n  | Unit t1 => eval e t1 \\in unit\n  | (f1 /\\ f2)%T => holds e f1 /\\ holds e f2\n  | (f1 \\/ f2)%T => holds e f1 \\/ holds e f2\n  | (f1 ==> f2)%T => holds e f1 -> holds e f2\n  | (~ f1)%T => ~ holds e f1\n  | ('exists 'X_i, f1)%T => exists x, holds (set_nth 0 e i x) f1\n  | ('forall 'X_i, f1)%T => forall x, holds (set_nth 0 e i x) f1\n  end.\n\nLemma same_env_sym e e' : same_env e e' -> same_env e' e.\nProof. exact: fsym. Qed.\n\n(* Extensionality of formula evaluation *)\nLemma eq_holds e e' f : same_env e e' -> holds e f -> holds e' f.\nProof.\npose sv := set_nth (0 : R).\nhave eq_i i v e1 e2: same_env e1 e2 -> same_env (sv e1 i v) (sv e2 i v).\n  by move=> eq_e j; rewrite !nth_set_nth /= eq_e.\nelim: f e e' => //=.\n- by move=> t1 t2 e e' eq_e; rewrite !(eq_eval _ eq_e).\n- by move=> t e e' eq_e; rewrite (eq_eval _ eq_e).\n- by move=> f1 IH1 f2 IH2 e e' eq_e; move/IH2: (eq_e); move/IH1: eq_e; tauto.\n- by move=> f1 IH1 f2 IH2 e e' eq_e; move/IH2: (eq_e); move/IH1: eq_e; tauto.\n- by move=> f1 IH1 f2 IH2 e e' eq_e f12; move/IH1: (same_env_sym eq_e); eauto.\n- by move=> f1 IH1 e e'; move/same_env_sym; move/IH1; tauto.\n- by move=> i f1 IH1 e e'; move/(eq_i i)=> eq_e [x f_ex]; exists x; eauto.\nby move=> i f1 IH1 e e'; move/(eq_i i); eauto.\nQed.\n\n(* Evaluation and substitution by a constant *)\nLemma holds_fsubst e f i v :\n  holds e (fsubst f (i, v%:T)%T) <-> holds (set_nth 0 e i v) f.\nProof.\nelim: f e => //=; do [\n  by move=> *; rewrite !eval_tsubst\n| move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto\n| move=> f IHf e; move: (IHf e); tauto\n| move=> j f IHf e].\n- case eq_ji: (j == i); first rewrite (eqP eq_ji).\n    by split=> [] [x f_x]; exists x; rewrite set_set_nth eqxx in f_x *.\n  split=> [] [x f_x]; exists x; move: f_x; rewrite set_set_nth eq_sym eq_ji;\n     have:= IHf (set_nth 0 e j x); tauto.\ncase eq_ji: (j == i); first rewrite (eqP eq_ji).\n  by split=> [] f_ x; move: (f_ x); rewrite set_set_nth eqxx.\nsplit=> [] f_ x; move: (IHf (set_nth 0 e j x)) (f_ x);\n  by rewrite set_set_nth eq_sym eq_ji; tauto.\nQed.\n\n(* Boolean test selecting terms in the language of rings *)\nFixpoint rterm (t : term R) :=\n  match t with\n  | _^-1 => false\n  | t1 + t2 | t1 * t2 => rterm t1 && rterm t2\n  | - t1 | t1 *+ _ | t1 ^+ _ => rterm t1\n  | _ => true\n  end%T.\n\n(* Boolean test selecting formulas in the theory of rings *)\nFixpoint rformula (f : formula R) :=\n  match f with\n  | Bool _ => true\n  | t1 == t2 => rterm t1 && rterm t2\n  | Unit t1 => false\n  | f1 /\\ f2 | f1 \\/ f2 | f1 ==> f2 => rformula f1 && rformula f2\n  | ~ f1 | ('exists 'X__, f1) | ('forall 'X__, f1) => rformula f1\n  end%T.\n\n(* Upper bound of the names used in a term *)\nFixpoint ub_var (t : term R) :=\n  match t with\n  | 'X_i => i.+1\n  | t1 + t2 | t1 * t2 => maxn (ub_var t1) (ub_var t2)\n  | - t1 | t1 *+ _ | t1 ^+ _ | t1^-1 => ub_var t1\n  | _ => 0%N\n  end%T.\n\n(* Replaces inverses in the term t by fresh variables, accumulating the *)\n(* substitution. *)\nFixpoint to_rterm (t : term R) (r : seq (term R)) (n : nat) {struct t} :=\n  match t with\n  | t1^-1 =>\n    let: (t1', r1) := to_rterm t1 r n in\n      ('X_(n + size r1), rcons r1 t1')\n  | t1 + t2 =>\n    let: (t1', r1) := to_rterm t1 r n in\n    let: (t2', r2) := to_rterm t2 r1 n in\n      (t1' + t2', r2)\n  | - t1 =>\n   let: (t1', r1) := to_rterm t1 r n in\n     (- t1', r1)\n  | t1 *+ m =>\n   let: (t1', r1) := to_rterm t1 r n in\n     (t1' *+ m, r1)\n  | t1 * t2 =>\n    let: (t1', r1) := to_rterm t1 r n in\n    let: (t2', r2) := to_rterm t2 r1 n in\n      (Mul t1' t2', r2)\n  | t1 ^+ m =>\n       let: (t1', r1) := to_rterm t1 r n in\n     (t1' ^+ m, r1)\n  | _ => (t, r)\n  end%T.\n\nLemma to_rterm_id t r n : rterm t -> to_rterm t r n = (t, r).\nProof.\nelim: t r n => //.\n- by move=> t1 IHt1 t2 IHt2 r n /= /andP[rt1 rt2]; rewrite {}IHt1 // IHt2.\n- by move=> t IHt r n /= rt; rewrite {}IHt.\n- by move=> t IHt r n m /= rt; rewrite {}IHt.\n- by move=> t1 IHt1 t2 IHt2 r n /= /andP[rt1 rt2]; rewrite {}IHt1 // IHt2.\n- by move=> t IHt r n m /= rt; rewrite {}IHt.\nQed.\n\n(* A ring formula stating that t1 is equal to 0 in the ring theory. *)\n(* Also applies to non commutative rings.                           *)\nDefinition eq0_rform t1 :=\n  let m := ub_var t1 in\n  let: (t1', r1) := to_rterm t1 [::] m in\n  let fix loop r i := match r with\n  | [::] => t1' == 0\n  | t :: r' =>\n    let f := 'X_i * t == 1 /\\ t * 'X_i == 1 in\n     'forall 'X_i, (f \\/ 'X_i == t /\\ ~ ('exists 'X_i,  f)) ==> loop r' i.+1\n  end%T\n  in loop r1 m.\n\n(* Transformation of a formula in the theory of rings with units into an *)\n(* equivalent formula in the sub-theory of rings.                        *)\nFixpoint to_rform f :=\n  match f with\n  | Bool b => f\n  | t1 == t2 => eq0_rform (t1 - t2)\n  | Unit t1 => eq0_rform (t1 * t1^-1 - 1)\n  | f1 /\\ f2 => to_rform f1 /\\ to_rform f2\n  | f1 \\/ f2 =>  to_rform f1 \\/ to_rform f2\n  | f1 ==> f2 => to_rform f1 ==> to_rform f2\n  | ~ f1 => ~ to_rform f1\n  | ('exists 'X_i, f1) => 'exists 'X_i, to_rform f1\n  | ('forall 'X_i, f1) => 'forall 'X_i, to_rform f1\n  end%T.\n\n(* The transformation gives a ring formula. *)\nLemma to_rform_rformula f : rformula (to_rform f).\nProof.\nsuffices eq0_ring t1: rformula (eq0_rform t1) by elim: f => //= => f1 ->.\nrewrite /eq0_rform; move: (ub_var t1) => m; set tr := _ m.\nsuffices: all rterm (tr.1 :: tr.2).\n  case: tr => {}t1 r /= /andP[t1_r].\n  by elim: r m => [|t r IHr] m; rewrite /= ?andbT // => /andP[->]; apply: IHr.\nhave: all rterm [::] by [].\nrewrite {}/tr; elim: t1 [::] => //=.\n- move=> t1 IHt1 t2 IHt2 r.\n  move/IHt1; case: to_rterm => {r IHt1}t1 r /= /andP[t1_r].\n  move/IHt2; case: to_rterm => {r IHt2}t2 r /= /andP[t2_r].\n  by rewrite t1_r t2_r.\n- by move=> t1 IHt1 r /IHt1; case: to_rterm.\n- by move=> t1 IHt1 n r /IHt1; case: to_rterm.\n- move=> t1 IHt1 t2 IHt2 r.\n  move/IHt1; case: to_rterm => {r IHt1}t1 r /= /andP[t1_r].\n  move/IHt2; case: to_rterm => {r IHt2}t2 r /= /andP[t2_r].\n  by rewrite t1_r t2_r.\n- move=> t1 IHt1 r.\n  by move/IHt1; case: to_rterm => {r IHt1}t1 r /=; rewrite all_rcons.\n- by move=> t1 IHt1 n r /IHt1; case: to_rterm.\nQed.\n\n(* Correctness of the transformation. *)\nLemma to_rformP e f : holds e (to_rform f) <-> holds e f.\nProof.\nsuffices{e f} equal0_equiv e t1 t2:\n  holds e (eq0_rform (t1 - t2)) <-> (eval e t1 == eval e t2).\n- elim: f e => /=; try tauto.\n  + move=> t1 t2 e.\n    by split; [move/equal0_equiv/eqP | move/eqP/equal0_equiv].\n  + by move=> t1 e; rewrite unitrE; apply: equal0_equiv.\n  + by move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + by move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + by move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + by move=> f1 IHf1 e; move: (IHf1 e); tauto.\n  + by move=> n f1 IHf1 e; split=> [] [x] /IHf1; exists x.\n  + by move=> n f1 IHf1 e; split=> Hx x; apply/IHf1.\nrewrite -(add0r (eval e t2)) -(can2_eq (subrK _) (addrK _)).\nrewrite -/(eval e (t1 - t2)); move: (t1 - t2)%T => {t1 t2} t.\nhave sub_var_tsubst s t0: s.1 >= ub_var t0 -> tsubst t0 s = t0.\n  elim: t0 {t} => //=.\n  - by move=> n; case: ltngtP.\n  - by move=> t1 IHt1 t2 IHt2; rewrite geq_max => /andP[/IHt1-> /IHt2->].\n  - by move=> t1 IHt1 /IHt1->.\n  - by move=> t1 IHt1 n /IHt1->.\n  - by move=> t1 IHt1 t2 IHt2; rewrite geq_max => /andP[/IHt1-> /IHt2->].\n  - by move=> t1 IHt1 /IHt1->.\n  - by move=> t1 IHt1 n /IHt1->.\npose fix rsub t' m r : term R :=\n  if r is u :: r' then tsubst (rsub t' m.+1 r') (m, u^-1)%T else t'.\npose fix ub_sub m r : Prop :=\n  if r is u :: r' then ub_var u <= m /\\ ub_sub m.+1 r' else true.\nsuffices{t} rsub_to_r t r0 m: m >= ub_var t -> ub_sub m r0 ->\n  let: (t', r) := to_rterm t r0 m in\n  [/\\ take (size r0) r = r0,\n      ub_var t' <= m + size r, ub_sub m r & rsub t' m r = t].\n- have:= rsub_to_r t [::] _ (leqnn _); rewrite /eq0_rform.\n  case: (to_rterm _ _ _) => [t1' r1] [//|_ _ ub_r1 def_t].\n  rewrite -{2}def_t {def_t}.\n  elim: r1 (ub_var t) e ub_r1 => [|u r1 IHr1] m e /= => [_|[ub_u ub_r1]].\n    by split=> /eqP.\n  rewrite eval_tsubst /=; set y := eval e u; split=> t_eq0.\n    apply/IHr1=> //; apply: t_eq0.\n    rewrite nth_set_nth /= eqxx -(eval_tsubst e u (m, Const _)).\n    rewrite sub_var_tsubst //= -/y.\n    case Uy: (y \\in unit); [left | right]; first by rewrite mulVr ?divrr.\n    split=> [|[z]]; first by rewrite invr_out ?Uy.\n    rewrite nth_set_nth /= eqxx.\n    rewrite -!(eval_tsubst _ _ (m, Const _)) !sub_var_tsubst // -/y => yz1.\n    by case/unitrP: Uy; exists z.\n  move=> x def_x; apply/IHr1=> //; suff ->: x = y^-1 by []; move: def_x.\n  rewrite nth_set_nth /= eqxx -(eval_tsubst e u (m, Const _)).\n  rewrite sub_var_tsubst //= -/y; case=> [[xy1 yx1] | [xy nUy]].\n    by rewrite -[y^-1]mul1r -[1]xy1 mulrK //; apply/unitrP; exists x.\n  rewrite invr_out //; apply/unitrP=> [[z yz1]]; case: nUy; exists z.\n  rewrite nth_set_nth /= eqxx -!(eval_tsubst _ _ (m, _%:T)%T).\n  by rewrite !sub_var_tsubst.\nhave rsub_id r t0 n: ub_var t0 <= n -> rsub t0 n r = t0.\n  by elim: r n => //= t1 r IHr n let0n; rewrite IHr ?sub_var_tsubst ?leqW.\nhave rsub_acc r s t1 m1:\n  ub_var t1 <= m1 + size r -> rsub t1 m1 (r ++ s) = rsub t1 m1 r.\n  elim: r t1 m1 => [|t1 r IHr] t2 m1 /=; first by rewrite addn0; apply: rsub_id.\n  by move=> letmr; rewrite IHr ?addSnnS.\nelim: t r0 m => /=; try do [\n  by move=> n r m hlt hub; rewrite take_size (ltn_addr _ hlt) rsub_id\n| by move=> n r m hlt hub; rewrite leq0n take_size rsub_id\n| move=> t1 IHt1 t2 IHt2 r m; rewrite geq_max; case/andP=> hub1 hub2 hmr;\n  case: to_rterm {hub1 hmr}(IHt1 r m hub1 hmr) => t1' r1;\n  case=> htake1 hub1' hsub1 <-;\n  case: to_rterm {IHt2 hub2 hsub1}(IHt2 r1 m hub2 hsub1) => t2' r2 /=;\n  rewrite geq_max; case=> htake2 -> hsub2 /= <-;\n  rewrite -{1 2}(cat_take_drop (size r1) r2) htake2; set r3 := drop _ _;\n  rewrite size_cat addnA (leq_trans _ (leq_addr _ _)) //;\n  split=> {hsub2}//;\n   first by [rewrite takel_cat // -htake1 size_take geq_min leqnn orbT];\n  rewrite -(rsub_acc r1 r3 t1') {hub1'}// -{htake1}htake2 {r3}cat_take_drop;\n  by elim: r2 m => //= u r2 IHr2 m; rewrite IHr2\n| do [ move=> t1 IHt1 r m; do 2!move=> /IHt1{}IHt1\n     | move=> t1 IHt1 n r m; do 2!move=> /IHt1{}IHt1];\n  case: to_rterm IHt1 => t1' r1 [-> -> hsub1 <-]; split=> {hsub1}//;\n  by elim: r1 m => //= u r1 IHr1 m; rewrite IHr1].\nmove=> t1 IH r m letm /IH {IH} /(_ letm) {letm}.\ncase: to_rterm => t1' r1 /= [def_r ub_t1' ub_r1 <-].\nrewrite size_rcons addnS leqnn -{1}cats1 takel_cat ?def_r; last first.\n  by rewrite -def_r size_take geq_min leqnn orbT.\nelim: r1 m ub_r1 ub_t1' {def_r} => /= [|u r1 IHr1] m => [_|[->]].\n  by rewrite addn0 eqxx.\nby rewrite -addSnnS => /IHr1 IH /IH[_ _ ub_r1 ->].\nQed.\n\n(* Boolean test selecting formulas which describe a constructible set, *)\n(* i.e. formulas without quantifiers.                                  *)\n\n(* The quantifier elimination check. *)\nFixpoint qf_form (f : formula R) :=\n  match f with\n  | Bool _ | _ == _ | Unit _ => true\n  | f1 /\\ f2 | f1 \\/ f2 | f1 ==> f2 => qf_form f1 && qf_form f2\n  | ~ f1 => qf_form f1\n  | _ => false\n  end%T.\n\n(* Boolean holds predicate for quantifier free formulas *)\nDefinition qf_eval e := fix loop (f : formula R) : bool :=\n  match f with\n  | Bool b => b\n  | t1 == t2 => (eval e t1 == eval e t2)%bool\n  | Unit t1 => eval e t1 \\in unit\n  | f1 /\\ f2 => loop f1 && loop f2\n  | f1 \\/ f2 => loop f1 || loop f2\n  | f1 ==> f2 => (loop f1 ==> loop f2)%bool\n  | ~ f1 => ~~ loop f1\n  |_ => false\n  end%T.\n\n(* qf_eval is equivalent to holds *)\nLemma qf_evalP e f : qf_form f -> reflect (holds e f) (qf_eval e f).\nProof.\nelim: f => //=; try by move=> *; apply: idP.\n- by move=> t1 t2 _; apply: eqP.\n- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1T]; last by right; case.\n  by case/IHf2; [left | right; case].\n- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1F]; first by do 2 left.\n  by case/IHf2; [left; right | right; case].\n- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1T]; last by left.\n  by case/IHf2; [left | right; move/(_ f1T)].\nby move=> f1 IHf1 /IHf1[]; [right | left].\nQed.\n\nImplicit Type bc : seq (term R) * seq (term R).\n\n(* Quantifier-free formula are normalized into DNF. A DNF is *)\n(* represented by the type seq (seq (term R) * seq (term R)), where we *)\n(* separate positive and negative literals *)\n\n(* DNF preserving conjunction *)\nDefinition and_dnf bcs1 bcs2 :=\n  \\big[cat/nil]_(bc1 <- bcs1)\n     map (fun bc2 => (bc1.1 ++ bc2.1, bc1.2 ++ bc2.2)) bcs2.\n\n(* Computes a DNF from a qf ring formula *)\nFixpoint qf_to_dnf (f : formula R) (neg : bool) {struct f} :=\n  match f with\n  | Bool b => if b (+) neg then [:: ([::], [::])] else [::]\n  | t1 == t2 => [:: if neg then ([::], [:: t1 - t2]) else ([:: t1 - t2], [::])]\n  | f1 /\\ f2 => (if neg then cat else and_dnf) [rec f1, neg] [rec f2, neg]\n  | f1 \\/ f2 => (if neg then and_dnf else cat) [rec f1, neg] [rec f2, neg]\n  | f1 ==> f2 => (if neg then and_dnf else cat) [rec f1, ~~ neg] [rec f2, neg]\n  | ~ f1 => [rec f1, ~~ neg]\n  | _ =>  if neg then [:: ([::], [::])] else [::]\n  end%T where \"[ 'rec' f , neg ]\" := (qf_to_dnf f neg).\n\n(* Conversely, transforms a DNF into a formula *)\nDefinition dnf_to_form :=\n  let pos_lit t := And (t == 0) in let neg_lit t := And (t != 0) in \n  let cls bc := Or (foldr pos_lit True bc.1 /\\ foldr neg_lit True bc.2) in\n  foldr cls False.\n\n(* Catenation of dnf is the Or of formulas *)\nLemma cat_dnfP e bcs1 bcs2 :\n  qf_eval e (dnf_to_form (bcs1 ++ bcs2))\n    = qf_eval e (dnf_to_form bcs1 \\/ dnf_to_form bcs2).\nProof.\nby elim: bcs1 => //= bc1 bcs1 IH1; rewrite -orbA; congr orb; rewrite IH1.\nQed.\n\n(* and_dnf is the And of formulas *)\nLemma and_dnfP e bcs1 bcs2 :\n  qf_eval e (dnf_to_form (and_dnf bcs1 bcs2))\n   = qf_eval e (dnf_to_form bcs1 /\\ dnf_to_form bcs2).\nProof.\nelim: bcs1 => [|bc1 bcs1 IH1] /=; first by rewrite /and_dnf big_nil.\nrewrite /and_dnf big_cons -/(and_dnf bcs1 bcs2) cat_dnfP  /=.\nrewrite {}IH1 /= andb_orl; congr orb.\nelim: bcs2 bc1 {bcs1} => [|bc2 bcs2 IH] bc1 /=; first by rewrite andbF.\nrewrite {}IH /= andb_orr; congr orb => {bcs2}.\nsuffices aux (l1 l2 : seq (term R)) g : let redg := foldr (And \\o g) True in\n  qf_eval e (redg (l1 ++ l2)) = qf_eval e (redg l1 /\\ redg l2)%T.\n+ by rewrite 2!aux /= 2!andbA -andbA -andbCA andbA andbCA andbA.\nby elim: l1 => [| t1 l1 IHl1] //=; rewrite -andbA IHl1.\nQed.\n\nLemma qf_to_dnfP e :\n  let qev f b := qf_eval e (dnf_to_form (qf_to_dnf f b)) in\n  forall f, qf_form f && rformula f -> qev f false = qf_eval e f.\nProof.\nmove=> qev; have qevT f: qev f true = ~~ qev f false.\n  rewrite {}/qev; elim: f => //=; do [by case | move=> f1 IH1 f2 IH2 | ].\n  - by move=> t1 t2; rewrite !andbT !orbF.\n  - by rewrite and_dnfP cat_dnfP negb_and -IH1 -IH2.\n  - by rewrite and_dnfP cat_dnfP negb_or -IH1 -IH2.\n  - by rewrite and_dnfP cat_dnfP /= negb_or IH1 -IH2 negbK.\n  by move=> t1 ->; rewrite negbK.\nrewrite /qev; elim=> //=; first by case.\n- by move=> t1 t2 _; rewrite subr_eq0 !andbT orbF.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite and_dnfP /= => /IH1-> /IH2->.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite cat_dnfP /= => /IH1-> => /IH2->.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite cat_dnfP /= [qf_eval _ _]qevT -implybE => /IH1 <- /IH2->.\nby move=> f1 IH1 /IH1 <-; rewrite -qevT.\nQed.\n\nLemma dnf_to_form_qf bcs : qf_form (dnf_to_form bcs).\nProof.\nby elim: bcs => //= [[clT clF] _ ->] /=; elim: clT => //=; elim: clF.\nQed.\n\nDefinition dnf_rterm cl := all rterm cl.1 && all rterm cl.2.\n\nLemma qf_to_dnf_rterm f b : rformula f -> all dnf_rterm (qf_to_dnf f b).\nProof.\nset ok := all dnf_rterm.\nhave cat_ok bcs1 bcs2: ok bcs1 -> ok bcs2 -> ok (bcs1 ++ bcs2).\n  by move=> ok1 ok2; rewrite [ok _]all_cat; apply/andP.\nhave and_ok bcs1 bcs2: ok bcs1 -> ok bcs2 -> ok (and_dnf bcs1 bcs2).\n  rewrite /and_dnf unlock; elim: bcs1 => //= cl1 bcs1 IH1; rewrite -andbA.\n  case/and3P=> ok11 ok12 ok1 ok2; rewrite cat_ok ?{}IH1 {bcs1 ok1}//.\n  elim: bcs2 ok2 => //= cl2 bcs2 IH2 /andP[ok2 /IH2->].\n  by rewrite /dnf_rterm !all_cat ok11 ok12 /= !andbT.\nelim: f b => //=; [ by do 2!case | | | | | by auto | | ];\n  try by repeat case/andP || intro; case: ifP; auto.\nby rewrite /dnf_rterm => ?? [] /= ->.\nQed.\n\nLemma dnf_to_rform bcs : rformula (dnf_to_form bcs) = all dnf_rterm bcs.\nProof.\nelim: bcs => //= [[cl1 cl2] bcs ->]; rewrite {2}/dnf_rterm /=; congr (_ && _).\nby congr andb; [elim: cl1 | elim: cl2] => //= t cl ->; rewrite andbT.\nQed.\n\nSection If.\n\nVariables (pred_f then_f else_f : formula R).\n\nDefinition If := (pred_f /\\ then_f \\/ ~ pred_f /\\ else_f)%T.\n\nLemma If_form_qf :\n  qf_form pred_f -> qf_form then_f -> qf_form else_f -> qf_form If.\nProof. by move=> /= -> -> ->. Qed.\n\nLemma If_form_rf :\n  rformula pred_f -> rformula then_f -> rformula else_f -> rformula If.\nProof. by move=> /= -> -> ->. Qed.\n\nLemma eval_If e :\n  let ev := qf_eval e in ev If = (if ev pred_f then ev then_f else ev else_f).\nProof. by rewrite /=; case: ifP => _; rewrite ?orbF. Qed.\n\nEnd If.\n\nSection Pick.\n\nVariables (I : finType) (pred_f then_f : I -> formula R) (else_f : formula R).\n\nDefinition Pick :=\n  \\big[Or/False]_(p : {ffun pred I})\n    ((\\big[And/True]_i (if p i then pred_f i else ~ pred_f i))\n    /\\ (if pick p is Some i then then_f i else else_f))%T.\n\nLemma Pick_form_qf :\n   (forall i, qf_form (pred_f i)) ->\n   (forall i, qf_form (then_f i)) ->\n    qf_form else_f ->\n  qf_form Pick.\nProof.\nmove=> qfp qft qfe; have mA := (big_morph qf_form) true andb.\nrewrite mA // big1 //= => p _.\nrewrite mA // big1 => [|i _]; first by case: pick.\nby rewrite fun_if if_same /= qfp.\nQed.\n\nLemma eval_Pick e (qev := qf_eval e) :\n  let P i := qev (pred_f i) in\n  qev Pick = (if pick P is Some i then qev (then_f i) else qev else_f).\nProof.\nmove=> P; rewrite ((big_morph qev) false orb) //= big_orE /=.\napply/existsP/idP=> [[p] | true_at_P].\n  rewrite ((big_morph qev) true andb) //= big_andE /=.\n  case/andP=> /forallP-eq_p_P.\n  rewrite (@eq_pick _ _ P) => [|i]; first by case: pick.\n  by move/(_ i): eq_p_P => /=; case: (p i) => //= /negPf.\nexists [ffun i => P i] => /=; apply/andP; split.\n  rewrite ((big_morph qev) true andb) //= big_andE /=.\n  by apply/forallP=> i; rewrite /= ffunE; case Pi: (P i) => //=; apply: negbT.\nrewrite (@eq_pick _ _ P) => [|i]; first by case: pick true_at_P.\nby rewrite ffunE.\nQed.\n\nEnd Pick.\n\nSection MultiQuant.\n\nVariable f : formula R.\nImplicit Types (I : seq nat) (e : seq R).\n\nLemma foldExistsP I e :\n  (exists2 e', {in [predC I], same_env e e'} & holds e' f)\n    <-> holds e (foldr Exists f I).\nProof.\nelim: I e => /= [|i I IHi] e.\n  by split=> [[e' eq_e] |]; [apply: eq_holds => i; rewrite eq_e | exists e].\nsplit=> [[e' eq_e f_e'] | [x]]; last set e_x := set_nth 0 e i x.\n  exists e'`_i; apply/IHi; exists e' => // j.\n  by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP => // ->.\ncase/IHi=> e' eq_e f_e'; exists e' => // j.\nby have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP.\nQed.\n\nLemma foldForallP I e :\n  (forall e', {in [predC I], same_env e e'} -> holds e' f)\n    <-> holds e (foldr Forall f I).\nProof.\nelim: I e => /= [|i I IHi] e.\n  by split=> [|f_e e' eq_e]; [apply | apply: eq_holds f_e => i; rewrite eq_e].\nsplit=> [f_e' x | f_e e' eq_e]; first set e_x := set_nth 0 e i x.\n  apply/IHi=> e' eq_e; apply: f_e' => j.\n  by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP.\nmove/IHi: (f_e e'`_i); apply=> j.\nby have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP => // ->.\nQed.\n\nEnd MultiQuant.\n\nEnd EvalTerm.\n\nPrenex Implicits dnf_rterm.\n\nModule IntegralDomain.\n\nDefinition axiom (R : ringType) :=\n  forall x y : R, x * y = 0 -> (x == 0) || (y == 0).\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of (R : Type) : Type :=\n  Class {base : ComUnitRing.class_of R; mixin : axiom (Ring.Pack base)}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> ComUnitRing.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c.\n\nDefinition pack b0 (m0 : axiom (@Ring.Pack T b0)) :=\n  fun bT b & phant_id (ComUnitRing.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition comRingType := @ComRing.Pack cT class.\nDefinition unitRingType := @UnitRing.Pack cT class.\nDefinition comUnitRingType := @ComUnitRing.Pack cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> ComUnitRing.class_of.\nArguments mixin [R] c [x y].\nCoercion mixin : class_of >-> axiom.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nNotation idomainType := type.\nNotation IdomainType T m := (@pack T _ m _ _ id _ id).\nNotation \"[ 'idomainType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'idomainType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'idomainType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'idomainType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd IntegralDomain.\nImport IntegralDomain.Exports.\n\nSection IntegralDomainTheory.\n\nVariable R : idomainType.\nImplicit Types x y : R.\n\nLemma mulf_eq0 x y : (x * y == 0) = (x == 0) || (y == 0).\nProof.\napply/eqP/idP; first by case: R x y => T [].\nby case/pred2P=> ->; rewrite (mulr0, mul0r).\nQed.\n\nLemma prodf_eq0 (I : finType) (P : pred I) (F : I -> R) :\n  reflect (exists2 i, P i & (F i == 0)) (\\prod_(i | P i) F i == 0).\nProof.\napply: (iffP idP) => [|[i Pi /eqP Fi0]]; last first.\n  by rewrite (bigD1 i) //= Fi0 mul0r.\nelim: (index_enum _) => [|i r IHr]; first by rewrite big_nil oner_eq0.\nrewrite big_cons /=; have [Pi | _] := ifP; last exact: IHr.\nby rewrite mulf_eq0; case/orP=> // Fi0; exists i.\nQed.\n\nLemma prodf_seq_eq0 I r (P : pred I) (F : I -> R) :\n  (\\prod_(i <- r | P i) F i == 0) = has (fun i => P i && (F i == 0)) r.\nProof. by rewrite (big_morph _ mulf_eq0 (oner_eq0 _)) big_has_cond. Qed.\n\nLemma mulf_neq0 x y : x != 0 -> y != 0 -> x * y != 0.\nProof. by move=> x0 y0; rewrite mulf_eq0; apply/norP. Qed.\n\nLemma prodf_neq0 (I : finType) (P : pred I) (F : I -> R) :\n  reflect (forall i, P i -> (F i != 0)) (\\prod_(i | P i) F i != 0).\nProof. by rewrite (sameP (prodf_eq0 _ _) exists_inP); apply: exists_inPn. Qed.\n\nLemma prodf_seq_neq0 I r (P : pred I) (F : I -> R) :\n  (\\prod_(i <- r | P i) F i != 0) = all (fun i => P i ==> (F i != 0)) r.\nProof.\nrewrite prodf_seq_eq0 -all_predC; apply: eq_all => i /=.\nby rewrite implybE negb_and.\nQed.\n\nLemma expf_eq0 x n : (x ^+ n == 0) = (n > 0) && (x == 0).\nProof.\nelim: n => [|n IHn]; first by rewrite oner_eq0.\nby rewrite exprS mulf_eq0 IHn andKb.\nQed.\n\nLemma sqrf_eq0 x : (x ^+ 2 == 0) = (x == 0). Proof. exact: expf_eq0. Qed.\n\nLemma expf_neq0 x m : x != 0 -> x ^+ m != 0.\nProof. by move=> x_nz; rewrite expf_eq0; apply/nandP; right. Qed.\n\nLemma natf_neq0 n : (n%:R != 0 :> R) = [char R]^'.-nat n.\nProof.\nhave [-> | /prod_prime_decomp->] := posnP n; first by rewrite eqxx.\nrewrite !big_seq; elim/big_rec: _ => [|[p e] s /=]; first by rewrite oner_eq0.\ncase/mem_prime_decomp=> p_pr _ _; rewrite pnatM pnatX eqn0Ngt orbC => <-.\nby rewrite natrM natrX mulf_eq0 expf_eq0 negb_or negb_and pnatE ?inE p_pr.\nQed.\n\nLemma natf0_char n : n > 0 -> n%:R == 0 :> R -> exists p, p \\in [char R].\nProof.\nmove=> n_gt0 nR_0; exists (pdiv n`_[char R]).\napply: pnatP (pdiv_dvd _); rewrite ?part_pnat // ?pdiv_prime //.\nby rewrite ltn_neqAle eq_sym partn_eq1 // -natf_neq0 nR_0 /=.\nQed.\n\nLemma charf'_nat n : [char R]^'.-nat n = (n%:R != 0 :> R).\nProof.\nhave [-> | n_gt0] := posnP n; first by rewrite eqxx.\napply/idP/idP => [|nz_n]; last first.\n  by apply/pnatP=> // p p_pr p_dvd_n; apply: contra nz_n => /dvdn_charf <-.\napply: contraL => n0; have [// | p charRp] := natf0_char _ n0.\nhave [p_pr _] := andP charRp; rewrite (eq_pnat _ (eq_negn (charf_eq charRp))).\nby rewrite p'natE // (dvdn_charf charRp) n0.\nQed.\n\nLemma charf0P : [char R] =i pred0 <-> (forall n, (n%:R == 0 :> R) = (n == 0)%N).\nProof.\nsplit=> charF0 n; last by rewrite !inE charF0 andbC; case: eqP => // ->.\nhave [-> | n_gt0] := posnP; first exact: eqxx.\nby apply/negP; case/natf0_char=> // p; rewrite charF0.\nQed.\n\nLemma eqf_sqr x y : (x ^+ 2 == y ^+ 2) = (x == y) || (x == - y).\nProof. by rewrite -subr_eq0 subr_sqr mulf_eq0 subr_eq0 addr_eq0. Qed.\n\nLemma mulfI x : x != 0 -> injective ( *%R x).\nProof.\nmove=> nz_x y z; apply: contra_eq => neq_yz.\nby rewrite -subr_eq0 -mulrBr mulf_neq0 ?subr_eq0.\nQed.\n\nLemma mulIf x : x != 0 -> injective ( *%R^~ x).\nProof. by move=> nz_x y z; rewrite -!(mulrC x); apply: mulfI. Qed.\n\nLemma divfI x : x != 0 -> injective (fun y => x / y).\nProof. by move/mulfI/inj_comp; apply; apply: invr_inj. Qed.\n\nLemma divIf y : y != 0 -> injective (fun x => x / y).\nProof. by rewrite -invr_eq0; apply: mulIf. Qed.\n\nLemma sqrf_eq1 x : (x ^+ 2 == 1) = (x == 1) || (x == -1).\nProof. by rewrite -subr_eq0 subr_sqr_1 mulf_eq0 subr_eq0 addr_eq0. Qed.\n\nLemma expfS_eq1 x n :\n  (x ^+ n.+1 == 1) = (x == 1) || (\\sum_(i < n.+1) x ^+ i == 0).\nProof. by rewrite -![_ == 1]subr_eq0 subrX1 mulf_eq0. Qed.\n\nLemma lregP x : reflect (lreg x) (x != 0).\nProof. by apply: (iffP idP) => [/mulfI | /lreg_neq0]. Qed.\n\nLemma rregP x : reflect (rreg x) (x != 0).\nProof. by apply: (iffP idP) => [/mulIf | /rreg_neq0]. Qed.\n\nCanonical regular_idomainType := [idomainType of R^o].\n\nEnd IntegralDomainTheory.\n\nArguments lregP {R x}.\nArguments rregP {R x}.\n\nModule Field.\n\nDefinition mixin_of (R : unitRingType) := forall x : R, x != 0 -> x \\in unit.\n\nLemma IdomainMixin R : mixin_of R -> IntegralDomain.axiom R.\nProof.\nmove=> m x y xy0; apply/norP=> [[]] /m Ux /m.\nby rewrite -(unitrMr _ Ux) xy0 unitr0.\nQed.\n\nSection Mixins.\n\nDefinition axiom (R : ringType) inv := forall x : R, x != 0 -> inv x * x = 1.\n\nVariables (R : comRingType) (inv : R -> R).\nHypotheses (mulVf : axiom inv) (inv0 : inv 0 = 0).\n\nFact intro_unit (x y : R) : y * x = 1 -> x != 0.\nProof.\nby move=> yx1; apply: contraNneq (oner_neq0 R) => x0; rewrite -yx1 x0 mulr0.\nQed.\n\nFact inv_out : {in predC (predC1 0), inv =1 id}.\nProof. by move=> x /negbNE/eqP->. Qed.\n\nDefinition UnitMixin := ComUnitRing.Mixin mulVf intro_unit inv_out.\n\nDefinition UnitRingType := [comUnitRingType of UnitRingType R UnitMixin].\n\nDefinition IdomainType :=\n  IdomainType UnitRingType (@IdomainMixin UnitRingType (fun => id)).\n\nLemma Mixin : mixin_of IdomainType. Proof. by []. Qed.\n\nEnd Mixins.\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of (F : Type) : Type := Class {\n  base : IntegralDomain.class_of F;\n  mixin : mixin_of (UnitRing.Pack base)\n}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> IntegralDomain.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c.\n\nDefinition pack b0 (m0 : mixin_of (@UnitRing.Pack T b0)) :=\n  fun bT b & phant_id (IntegralDomain.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition comRingType := @ComRing.Pack cT class.\nDefinition unitRingType := @UnitRing.Pack cT class.\nDefinition comUnitRingType := @ComUnitRing.Pack cT class.\nDefinition idomainType := @IntegralDomain.Pack cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> IntegralDomain.class_of.\nArguments mixin [F] c [x].\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nCoercion idomainType : type >-> IntegralDomain.type.\nCanonical idomainType.\nNotation fieldType := type.\nNotation FieldType T m := (@pack T _ m _ _ id _ id).\nArguments Mixin {R inv} mulVf inv0 [x] nz_x.\nNotation FieldUnitMixin := UnitMixin.\nNotation FieldIdomainMixin := IdomainMixin.\nNotation FieldMixin := Mixin.\nNotation \"[ 'fieldType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'fieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'fieldType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'fieldType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Field.\nImport Field.Exports.\n\nSection FieldTheory.\n\nVariable F : fieldType.\nImplicit Types x y : F.\n\nLemma fieldP : Field.mixin_of F. Proof. by case: F => T []. Qed.\n\nLemma unitfE x : (x \\in unit) = (x != 0).\nProof. by apply/idP/idP=> [/(memPn _)-> | /fieldP]; rewrite ?unitr0. Qed.\n\nLemma mulVf x : x != 0 -> x^-1 * x = 1.\nProof. by rewrite -unitfE; apply: mulVr. Qed.\nLemma divff x : x != 0 -> x / x = 1.\nProof. by rewrite -unitfE; apply: divrr. Qed.\nDefinition mulfV := divff.\nLemma mulKf x : x != 0 -> cancel ( *%R x) ( *%R x^-1).\nProof. by rewrite -unitfE; apply: mulKr. Qed.\nLemma mulVKf x : x != 0 -> cancel ( *%R x^-1) ( *%R x).\nProof. by rewrite -unitfE; apply: mulVKr. Qed.\nLemma mulfK x : x != 0 -> cancel ( *%R^~ x) ( *%R^~ x^-1).\nProof. by rewrite -unitfE; apply: mulrK. Qed.\nLemma mulfVK x : x != 0 -> cancel ( *%R^~ x^-1) ( *%R^~ x).\nProof. by rewrite -unitfE; apply: divrK. Qed.\nDefinition divfK := mulfVK.\n\nLemma invfM : {morph @inv F : x y / x * y}.\nProof.\nmove=> x y; have [->|nzx] := eqVneq x 0; first by rewrite !(mul0r, invr0).\nhave [->|nzy] := eqVneq y 0; first by rewrite !(mulr0, invr0).\nby rewrite mulrC invrM ?unitfE.\nQed.\n\nLemma invf_div x y : (x / y)^-1 = y / x.\nProof. by rewrite invfM invrK mulrC. Qed.\n\nLemma divKf x : x != 0 -> involutive (fun y => x / y).\nProof. by move=> nz_x y; rewrite invf_div mulrC divfK. Qed.\n\nLemma expfB_cond m n x : (x == 0) + n <= m -> x ^+ (m - n) = x ^+ m / x ^+ n.\nProof.\nmove/subnK=> <-; rewrite addnA addnK !exprD.\nhave [-> | nz_x] := eqVneq; first by rewrite !mulr0 !mul0r.\nby rewrite mulfK ?expf_neq0.\nQed.\n\nLemma expfB m n x : n < m -> x ^+ (m - n) = x ^+ m / x ^+ n.\nProof. by move=> lt_n_m; apply: expfB_cond; case: eqP => // _; apply: ltnW. Qed.\n\nLemma prodfV I r (P : pred I) (E : I -> F) :\n  \\prod_(i <- r | P i) (E i)^-1 = (\\prod_(i <- r | P i) E i)^-1.\nProof. by rewrite (big_morph _ invfM (invr1 F)). Qed.\n\nLemma prodf_div I r (P : pred I) (E D : I -> F) :\n  \\prod_(i <- r | P i) (E i / D i) =\n     \\prod_(i <- r | P i) E i / \\prod_(i <- r | P i) D i.\nProof. by rewrite big_split prodfV. Qed.\n\nLemma telescope_prodf n m (f : nat -> F) :\n    (forall k, n < k < m -> f k != 0) -> n < m ->\n  \\prod_(n <= k < m) (f k.+1 / f k) = f m / f n.\nProof.\nmove=> nz_f ltnm; apply: invr_inj; rewrite prodf_div !invf_div -prodf_div.\nby apply: telescope_prodr => // k /nz_f; rewrite unitfE.\nQed.\n\nLemma telescope_prodf_eq n m (f u : nat -> F) :\n    (forall k, n < k < m -> f k != 0) -> n < m ->\n    (forall k, n <= k < m -> u k = f k.+1 / f k) ->\n  \\prod_(n <= k < m) u k = f m / f n.\nProof.\nby move=> ? ? uE; under eq_big_nat do rewrite uE //=; exact: telescope_prodf.\nQed.\n\nLemma addf_div x1 y1 x2 y2 :\n  y1 != 0 -> y2 != 0 -> x1 / y1 + x2 / y2 = (x1 * y2 + x2 * y1) / (y1 * y2).\nProof. by move=> nzy1 nzy2; rewrite invfM mulrDl !mulrA mulrAC !mulfK. Qed.\n\nLemma mulf_div x1 y1 x2 y2 : (x1 / y1) * (x2 / y2) = (x1 * x2) / (y1 * y2).\nProof. by rewrite mulrACA -invfM. Qed.\n\nLemma eqr_div x y z t : y != 0 -> t != 0 -> (x / y == z / t) = (x * t == z * y).\nProof.\nmove=> yD0 tD0; rewrite -[x in RHS](divfK yD0) -[z in RHS](divfK tD0) mulrAC.\nby apply/eqP/eqP => [->|/(mulIf yD0)/(mulIf tD0)].\nQed.\n\nLemma eqr_sum_div I r P (f : I -> F) c a : c != 0 ->\n  \\big[+%R/0]_(x <- r | P x) (f x / c) == a\n  = (\\big[+%R/0]_(x <- r | P x) f x == a * c).\nProof.\nby move=> ?; rewrite -mulr_suml -(divr1 a) eqr_div ?oner_eq0// mulr1 divr1.\nQed.\n\nLemma char0_natf_div :\n  [char F] =i pred0 -> forall m d, d %| m -> (m %/ d)%:R = m%:R / d%:R :> F.\nProof.\nmove/charf0P=> char0F m [|d] d_dv_m; first by rewrite divn0 invr0 mulr0.\nby rewrite natr_div // unitfE char0F.\nQed.\n\nSection FieldMorphismInj.\n\nVariables (R : ringType) (f : {rmorphism F -> R}).\n\nLemma fmorph_eq0 x : (f x == 0) = (x == 0).\nProof.\nhave [-> | nz_x] := eqVneq x; first by rewrite rmorph0 eqxx.\napply/eqP; move/(congr1 ( *%R (f x^-1)))/eqP.\nby rewrite -rmorphM mulVf // mulr0 rmorph1 ?oner_eq0.\nQed.\n\nLemma fmorph_inj : injective f.\nProof. by apply/raddf_inj => x /eqP; rewrite fmorph_eq0 => /eqP. Qed.\n\nLemma fmorph_eq : {mono f : x y / x == y}.\nProof. exact: inj_eq fmorph_inj. Qed.\n\nLemma fmorph_eq1 x : (f x == 1) = (x == 1).\nProof. by rewrite -(inj_eq fmorph_inj) rmorph1. Qed.\n\nLemma fmorph_char : [char R] =i [char F].\nProof. by move=> p; rewrite !inE -fmorph_eq0 rmorph_nat. Qed.\n\nEnd FieldMorphismInj.\n\nSection FieldMorphismInv.\n\nVariables (R : unitRingType) (f : {rmorphism F -> R}).\n\nLemma fmorph_unit x : (f x \\in unit) = (x != 0).\nProof.\nhave [-> |] := eqVneq x; first by rewrite rmorph0 unitr0.\nby rewrite -unitfE; apply: rmorph_unit.\nQed.\n\nLemma fmorphV : {morph f: x / x^-1}.\nProof.\nmove=> x; have [-> | nz_x] := eqVneq x 0; first by rewrite !(invr0, rmorph0).\nby rewrite rmorphV ?unitfE.\nQed.\n\nLemma fmorph_div : {morph f : x y / x / y}.\nProof. by move=> x y; rewrite rmorphM fmorphV. Qed.\n\nEnd FieldMorphismInv.\n\nCanonical regular_fieldType := [fieldType of F^o].\n\nSection ModuleTheory.\n\nVariable V : lmodType F.\nImplicit Types (a : F) (v : V).\n\nLemma scalerK a : a != 0 -> cancel ( *:%R a : V -> V) ( *:%R a^-1).\nProof. by move=> nz_a v; rewrite scalerA mulVf // scale1r. Qed.\n\nLemma scalerKV a : a != 0 -> cancel ( *:%R a^-1 : V -> V) ( *:%R a).\nProof. by rewrite -invr_eq0 -{3}[a]invrK; apply: scalerK. Qed.\n\nLemma scalerI a : a != 0 -> injective ( *:%R a : V -> V).\nProof. by move=> nz_a; apply: can_inj (scalerK nz_a). Qed.\n\nLemma scaler_eq0 a v : (a *: v == 0) = (a == 0) || (v == 0).\nProof.\nhave [-> | nz_a] := eqVneq a; first by rewrite scale0r eqxx.\nby rewrite (can2_eq (scalerK nz_a) (scalerKV nz_a)) scaler0.\nQed.\n\nLemma rpredZeq S (modS : submodPred S) (kS : keyed_pred modS) a v :\n  (a *: v \\in kS) = (a == 0) || (v \\in kS).\nProof.\nhave [-> | nz_a] := eqVneq; first by rewrite scale0r rpred0.\nby apply/idP/idP; first rewrite -{2}(scalerK nz_a v); apply: rpredZ.\nQed.\n\nEnd ModuleTheory.\n\nLemma char_lalg (A : lalgType F) : [char A] =i [char F].\nProof. by move=> p; rewrite inE -scaler_nat scaler_eq0 oner_eq0 orbF. Qed.\n\nSection Predicates.\n\nContext (S : {pred F}) (divS : @divrPred F S) (kS : keyed_pred divS).\n\nLemma fpredMl x y : x \\in kS -> x != 0 -> (x * y \\in kS) = (y \\in kS).\nProof. by rewrite -!unitfE; apply: rpredMl. Qed.\n\nLemma fpredMr x y : x \\in kS -> x != 0 -> (y * x \\in kS) = (y \\in kS).\nProof. by rewrite -!unitfE; apply: rpredMr. Qed.\n\nLemma fpred_divl x y : x \\in kS -> x != 0 -> (x / y \\in kS) = (y \\in kS).\nProof. by rewrite -!unitfE; apply: rpred_divl. Qed.\n\nLemma fpred_divr x y : x \\in kS -> x != 0 -> (y / x \\in kS) = (y \\in kS).\nProof. by rewrite -!unitfE; apply: rpred_divr. Qed.\n\nEnd Predicates.\n\nEnd FieldTheory.\n\nArguments fmorph_inj {F R} f [x1 x2].\nArguments telescope_prodf_eq {F n m} f u.\n\nModule DecidableField.\n\nDefinition axiom (R : unitRingType) (s : seq R -> pred (formula R)) :=\n  forall e f, reflect (holds e f) (s e f).\n\nRecord mixin_of (R : unitRingType) : Type :=\n  Mixin { sat : seq R -> pred (formula R); satP : axiom sat}.\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of (F : Type) : Type :=\n  Class {base : Field.class_of F; mixin : mixin_of (UnitRing.Pack base)}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> Field.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c.\n\nDefinition pack b0 (m0 : mixin_of (@UnitRing.Pack T b0)) :=\n  fun bT b & phant_id (Field.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m).\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition comRingType := @ComRing.Pack cT class.\nDefinition unitRingType := @UnitRing.Pack cT class.\nDefinition comUnitRingType := @ComUnitRing.Pack cT class.\nDefinition idomainType := @IntegralDomain.Pack cT class.\nDefinition fieldType := @Field.Pack cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Field.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nCoercion idomainType : type >-> IntegralDomain.type.\nCanonical idomainType.\nCoercion fieldType : type >-> Field.type.\nCanonical fieldType.\nNotation decFieldType := type.\nNotation DecFieldType T m := (@pack T _ m _ _ id _ id).\nNotation DecFieldMixin := Mixin.\nNotation \"[ 'decFieldType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'decFieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'decFieldType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'decFieldType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd DecidableField.\nImport DecidableField.Exports.\n\nSection DecidableFieldTheory.\n\nVariable F : decFieldType.\n\nDefinition sat := DecidableField.sat (DecidableField.class F).\n\nLemma satP : DecidableField.axiom sat.\nProof. exact: DecidableField.satP. Qed.\n\nFact sol_subproof n f :\n  reflect (exists s, (size s == n) && sat s f)\n          (sat [::] (foldr Exists f (iota 0 n))).\nProof.\napply: (iffP (satP _ _)) => [|[s]]; last first.\n  case/andP=> /eqP sz_s /satP f_s; apply/foldExistsP.\n  exists s => // i; rewrite !inE mem_iota -leqNgt add0n => le_n_i.\n  by rewrite !nth_default ?sz_s.\ncase/foldExistsP=> e e0 f_e; set s := take n (set_nth 0 e n 0).\nhave sz_s: size s = n by rewrite size_take size_set_nth leq_max leqnn.\nexists s; rewrite sz_s eqxx; apply/satP; apply: eq_holds f_e => i.\ncase: (leqP n i) => [le_n_i | lt_i_n].\n  by rewrite -e0 ?nth_default ?sz_s // !inE mem_iota -leqNgt.\nby rewrite nth_take // nth_set_nth /= eq_sym eqn_leq leqNgt lt_i_n.\nQed.\n\nDefinition sol n f :=\n  if sol_subproof n f is ReflectT sP then xchoose sP else nseq n 0.\n\nLemma size_sol n f : size (sol n f) = n.\nProof.\nrewrite /sol; case: sol_subproof => [sP | _]; last exact: size_nseq.\nby case/andP: (xchooseP sP) => /eqP.\nQed.\n\nLemma solP n f : reflect (exists2 s, size s = n & holds s f) (sat (sol n f) f).\nProof.\nrewrite /sol; case: sol_subproof => [sP | sPn].\n  case/andP: (xchooseP sP) => _ ->; left.\n  by case: sP => s; case/andP; move/eqP=> <-; move/satP; exists s.\napply: (iffP (satP _ _)); first by exists (nseq n 0); rewrite ?size_nseq.\nby case=> s sz_s; move/satP=> f_s; case: sPn; exists s; rewrite sz_s eqxx.\nQed.\n\nLemma eq_sat f1 f2 :\n  (forall e, holds e f1 <-> holds e f2) -> sat^~ f1 =1 sat^~ f2.\nProof. by move=> eqf12 e; apply/satP/satP; case: (eqf12 e). Qed.\n\nLemma eq_sol f1 f2 :\n  (forall e, holds e f1 <-> holds e f2) -> sol^~ f1 =1 sol^~ f2.\nProof.\nrewrite /sol => /eq_sat eqf12 n.\ndo 2![case: sol_subproof] => //= [f1s f2s | ns1 [s f2s] | [s f1s] []].\n- by apply: eq_xchoose => s; rewrite eqf12.\n- by case: ns1; exists s; rewrite -eqf12.\nby exists s; rewrite eqf12.\nQed.\n\nEnd DecidableFieldTheory.\n\nArguments satP {F e f}.\nArguments solP {F n f}.\n\nSection QE_Mixin.\n\nVariable F : Field.type.\nImplicit Type f : formula F.\n\nVariable proj : nat -> seq (term F) * seq (term F) -> formula F.\n(* proj is the elimination of a single existential quantifier *)\n\n(* The elimination projector is well_formed. *)\nDefinition wf_QE_proj :=\n  forall i bc (bc_i := proj i bc),\n  dnf_rterm bc -> qf_form bc_i && rformula bc_i.\n\n(* The elimination projector is valid *)\nDefinition valid_QE_proj :=\n  forall i bc (ex_i_bc := ('exists 'X_i, dnf_to_form [:: bc])%T) e,\n  dnf_rterm bc -> reflect (holds e ex_i_bc) (qf_eval e (proj i bc)).\n\nHypotheses (wf_proj : wf_QE_proj) (ok_proj : valid_QE_proj).\n\nLet elim_aux f n := foldr Or False (map (proj n) (qf_to_dnf f false)).\n\nFixpoint quantifier_elim f :=\n  match f with\n  | f1 /\\ f2 => (quantifier_elim f1) /\\ (quantifier_elim f2)\n  | f1 \\/ f2 => (quantifier_elim f1) \\/ (quantifier_elim f2)\n  | f1 ==> f2 => (~ quantifier_elim f1) \\/ (quantifier_elim f2)\n  | ~ f => ~ quantifier_elim f\n  | ('exists 'X_n, f) => elim_aux (quantifier_elim f) n\n  | ('forall 'X_n, f) => ~ elim_aux (~ quantifier_elim f) n\n  | _ => f\n  end%T.\n\nLemma quantifier_elim_wf f :\n  let qf := quantifier_elim f in rformula f -> qf_form qf && rformula qf.\nProof.\nsuffices aux_wf f0 n : let qf := elim_aux f0 n in\n  rformula f0 -> qf_form qf && rformula qf.\n- by elim: f => //=; do ?[  move=> f1 IH1 f2 IH2;\n                     case/andP=> rf1 rf2;\n                     case/andP:(IH1 rf1)=> -> ->;\n                     case/andP:(IH2 rf2)=> -> -> //\n                  |  move=> n f1 IH rf1;\n                     case/andP: (IH rf1)=> qff rf;\n                     rewrite aux_wf ].\nrewrite /elim_aux => rf.\nsuffices or_wf fs : let ofs := foldr Or False fs in \n  all (@qf_form F) fs && all (@rformula F) fs -> qf_form ofs && rformula ofs.\n- apply: or_wf.\n  suffices map_proj_wf bcs: let mbcs := map (proj n) bcs in\n    all dnf_rterm bcs -> all (@qf_form _) mbcs && all (@rformula _) mbcs.\n    by apply/map_proj_wf/qf_to_dnf_rterm.\n  elim: bcs => [|bc bcs ihb] bcsr //= /andP[rbc rbcs].\n  by rewrite andbAC andbA wf_proj //= andbC ihb.\nelim: fs => //= g gs ihg; rewrite -andbA => /and4P[-> qgs -> rgs] /=.\nby apply: ihg; rewrite qgs rgs.\nQed.\n\nLemma quantifier_elim_rformP e f :\n  rformula f -> reflect (holds e f) (qf_eval e (quantifier_elim f)).\nProof.\npose rc e n f := exists x, qf_eval (set_nth 0 e n x) f.\nhave auxP f0 e0 n0: qf_form f0 && rformula f0 ->\n  reflect (rc e0 n0 f0) (qf_eval e0 (elim_aux f0 n0)).\n+ rewrite /elim_aux => cf; set bcs := qf_to_dnf f0 false.\n  apply: (@iffP (rc e0 n0 (dnf_to_form bcs))); last first.\n  - by case=> x; rewrite -qf_to_dnfP //; exists x.\n  - by case=> x; rewrite qf_to_dnfP //; exists x.\n  have: all dnf_rterm bcs by case/andP: cf => _; apply: qf_to_dnf_rterm.\n  elim: {f0 cf}bcs => [|bc bcs IHbcs] /=; first by right; case.\n  case/andP=> r_bc /IHbcs {IHbcs}bcsP.\n  have f_qf := dnf_to_form_qf [:: bc].\n  case: ok_proj => //= [ex_x|no_x].\n    left; case: ex_x => x /(qf_evalP _ f_qf); rewrite /= orbF => bc_x.\n    by exists x; rewrite /= bc_x.\n  apply: (iffP bcsP) => [[x bcs_x] | [x]] /=.\n    by exists x; rewrite /= bcs_x orbT.\n  case/orP => [bc_x|]; last by exists x.\n  by case: no_x; exists x; apply/(qf_evalP _ f_qf); rewrite /= bc_x.\nelim: f e => //.\n- by move=> b e _; apply: idP.\n- by move=> t1 t2 e _; apply: eqP.\n- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; last by right; case.\n  by case/IH2; [left | right; case].\n- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; first by do 2!left.\n  by case/IH2; [left; right | right; case].\n- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; last by left.\n  by case/IH2; [left | right; move/(_ f1e)].\n- by move=> f IHf e /= /IHf[]; [right | left].\n- move=> n f IHf e /= rf; have rqf := quantifier_elim_wf rf.\n  by apply: (iffP (auxP _ _ _ rqf)) => [] [x]; exists x; apply/IHf.\nmove=> n f IHf e /= rf; have rqf := quantifier_elim_wf rf.\ncase: auxP => // [f_x|no_x]; first by right=> no_x; case: f_x => x /IHf[].\nby left=> x; apply/IHf=> //; apply/idPn=> f_x; case: no_x; exists x.\nQed.\n\nDefinition proj_sat e f := qf_eval e (quantifier_elim (to_rform f)).\n\nLemma proj_satP : DecidableField.axiom proj_sat.\nProof.\nmove=> e f; have fP := quantifier_elim_rformP e (to_rform_rformula f).\nby apply: (iffP fP); move/to_rformP.\nQed.\n\nDefinition QEdecFieldMixin := DecidableField.Mixin proj_satP.\n\nEnd QE_Mixin.\n\nModule ClosedField.\n\n(* Axiom == all non-constant monic polynomials have a root *)\nDefinition axiom (R : ringType) :=\n  forall n (P : nat -> R), n > 0 ->\n   exists x : R, x ^+ n = \\sum_(i < n) P i * (x ^+ i).\n\nSection ClassDef.\n\nSet Primitive Projections.\nRecord class_of (F : Type) : Type :=\n  Class {base : DecidableField.class_of F; mixin : axiom (Ring.Pack base)}.\nUnset Primitive Projections.\nLocal Coercion base : class_of >-> DecidableField.class_of.\n\nStructure type := Pack {sort; _ : class_of sort}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c.\n\nDefinition pack b0 (m0 : axiom (@Ring.Pack T b0)) :=\n  fun bT b & phant_id (DecidableField.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m).\n\n(* There should eventually be a constructor from polynomial resolution *)\n(* that builds the DecidableField mixin using QE.                      *)\n\nDefinition eqType := @Equality.Pack cT class.\nDefinition choiceType := @Choice.Pack cT class.\nDefinition zmodType := @Zmodule.Pack cT class.\nDefinition ringType := @Ring.Pack cT class.\nDefinition comRingType := @ComRing.Pack cT class.\nDefinition unitRingType := @UnitRing.Pack cT class.\nDefinition comUnitRingType := @ComUnitRing.Pack cT class.\nDefinition idomainType := @IntegralDomain.Pack cT class.\nDefinition fieldType := @Field.Pack cT class.\nDefinition decFieldType := @DecidableField.Pack cT class.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> DecidableField.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nCoercion idomainType : type >-> IntegralDomain.type.\nCanonical idomainType.\nCoercion fieldType : type >-> Field.type.\nCanonical fieldType.\nCoercion decFieldType : type >-> DecidableField.type.\nCanonical decFieldType.\nNotation closedFieldType := type.\nNotation ClosedFieldType T m := (@pack T _ m _ _ id _ id).\nNotation \"[ 'closedFieldType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'closedFieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'closedFieldType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'closedFieldType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd ClosedField.\nImport ClosedField.Exports.\n\nSection ClosedFieldTheory.\n\nVariable F : closedFieldType.\n\nLemma solve_monicpoly : ClosedField.axiom F.\nProof. by case: F => ? []. Qed.\n\nLemma imaginary_exists : {i : F | i ^+ 2 = -1}.\nProof.\nhave /sig_eqW[i Di2] := @solve_monicpoly 2 (nth 0 [:: -1]) isT.\nby exists i; rewrite Di2 !big_ord_recl big_ord0 mul0r mulr1 !addr0.\nQed.\n\nEnd ClosedFieldTheory.\n\nModule SubType.\n\nSection Zmodule.\n\nVariables (V : zmodType) (S : {pred V}).\nVariables (subS : zmodPred S) (kS : keyed_pred subS).\nVariable U : subType [in kS].\n\nLet inU v Sv : U := Sub v Sv.\nLet zeroU := inU (rpred0 kS).\n\nLet oppU (u : U) := inU (rpredNr (valP u)).\nLet addU (u1 u2 : U) := inU (rpredD (valP u1) (valP u2)).\n\nFact addA : associative addU.\nProof. by move=> u1 u2 u3; apply: val_inj; rewrite !SubK addrA. Qed.\nFact addC : commutative addU.\nProof. by move=> u1 u2; apply: val_inj; rewrite !SubK addrC. Qed.\nFact add0 : left_id zeroU addU.\nProof. by move=> u; apply: val_inj; rewrite !SubK add0r. Qed.\nFact addN : left_inverse zeroU oppU addU.\nProof. by move=> u; apply: val_inj; rewrite !SubK addNr. Qed.\n\nDefinition zmodMixin of phant U := ZmodMixin addA addC add0 addN.\n\nEnd Zmodule.\n\nSection Ring.\n\nVariables (R : ringType) (S : {pred R}).\nVariables (ringS : subringPred S) (kS : keyed_pred ringS).\n\nDefinition cast_zmodType (V : zmodType) T (VeqT : V = T :> Type) :=\n  let cast mV := let: erefl in _ = T := VeqT return Zmodule.class_of T in mV in\n  Zmodule.Pack (cast (Zmodule.class V)).\n\nVariable (T : subType [in kS]) (V : zmodType) (VeqT: V = T :> Type).\n\nLet inT x Sx : T := Sub x Sx.\nLet oneT := inT (rpred1 kS).\nLet mulT (u1 u2 : T) := inT (rpredM (valP u1) (valP u2)).\nLet T' := cast_zmodType VeqT.\n\nHypothesis valM : {morph (val : T' -> R) : x y / x - y}.\n\nLet val0 : val (0 : T') = 0.\nProof. by rewrite -(subrr (0 : T')) valM subrr. Qed.\nLet valD : {morph (val : T' -> R): x y / x + y}.\nProof.\nby move=> u v; rewrite -{1}[v]opprK -[- v]sub0r !valM val0 sub0r opprK.\nQed.\n\nFact mulA : @associative T' mulT.\nProof. by move=> u1 u2 u3; apply: val_inj; rewrite !SubK mulrA. Qed.\nFact mul1l : left_id oneT mulT.\nProof. by move=> u; apply: val_inj; rewrite !SubK mul1r. Qed.\nFact mul1r : right_id oneT mulT.\nProof. by move=> u; apply: val_inj; rewrite !SubK mulr1. Qed.\nFact mulDl : @left_distributive T' T' mulT +%R.\nProof. by move=> u1 u2 u3; apply: val_inj; rewrite !(SubK, valD) mulrDl. Qed.\nFact mulDr : @right_distributive T' T' mulT +%R.\nProof. by move=> u1 u2 u3; apply: val_inj; rewrite !(SubK, valD) mulrDr. Qed.\nFact nz1 : oneT != 0 :> T'.\nProof.\nby apply: contraNneq (oner_neq0 R) => eq10; rewrite -val0 -eq10 SubK.\nQed.\n\nDefinition ringMixin := RingMixin mulA mul1l mul1r mulDl mulDr nz1.\n\nEnd Ring.\n\nSection Lmodule.\n\nVariables (R : ringType) (V : lmodType R) (S : {pred V}).\nVariables (linS : submodPred S) (kS : keyed_pred linS).\nVariables (W : subType [in kS]) (Z : zmodType) (ZeqW : Z = W :> Type).\n\nLet scaleW a (w : W) := (Sub _ : _ -> W) (rpredZ a (valP w)).\nLet W' := cast_zmodType ZeqW.\n\nHypothesis valD : {morph (val : W' -> V) : x y / x + y}.\n\nFact scaleA a b (w : W') : scaleW a (scaleW b w) = scaleW (a * b) w.\nProof. by apply: val_inj; rewrite !SubK scalerA. Qed.\nFact scale1 : left_id 1 scaleW.\nProof. by move=> w; apply: val_inj; rewrite !SubK scale1r. Qed.\nFact scaleDr : @right_distributive R W' scaleW +%R.\nProof. by move=> a w w2; apply: val_inj; rewrite !(SubK, valD) scalerDr. Qed.\nFact scaleDl w : {morph (scaleW^~ w : R -> W') : a b / a + b}.\nProof. by move=> a b; apply: val_inj; rewrite !(SubK, valD) scalerDl. Qed.\n\nDefinition lmodMixin := LmodMixin scaleA scale1 scaleDr scaleDl.\n\nEnd Lmodule.\n\nLemma lalgMixin (R : ringType) (A : lalgType R) (B : lmodType R) (f : B -> A) :\n     phant B -> injective f -> scalable f -> \n   forall mulB, {morph f : x y / mulB x y >-> x * y} -> Lalgebra.axiom mulB.\nProof.\nby move=> _ injf fZ mulB fM a x y; apply: injf; rewrite !(fZ, fM) scalerAl.\nQed.\n\nLemma comRingMixin (R : comRingType) (T : ringType) (f : T -> R) :\n  phant T -> injective f -> {morph f : x y / x * y} -> commutative (@mul T).\nProof. by move=> _ inj_f fM x y; apply: inj_f; rewrite !fM mulrC. Qed.\n\nLemma algMixin (R : comRingType) (A : algType R) (B : lalgType R) (f : B -> A) :\n    phant B -> injective f -> {morph f : x y / x * y} -> scalable f ->\n  @Algebra.axiom R B.\nProof.\nby move=> _ inj_f fM fZ a x y; apply: inj_f; rewrite !(fM, fZ) scalerAr.\nQed.\n\nSection UnitRing.\n\nDefinition cast_ringType (Q : ringType) T (QeqT : Q = T :> Type) :=\n  let cast rQ := let: erefl in _ = T := QeqT return Ring.class_of T in rQ in\n  Ring.Pack (cast (Ring.class Q)).\n\nVariables (R : unitRingType) (S : {pred R}).\nVariables (ringS : divringPred S) (kS : keyed_pred ringS).\n\nVariables (T : subType [in kS]) (Q : ringType) (QeqT : Q = T :> Type).\n\nLet inT x Sx : T := Sub x Sx.\nLet invT (u : T) := inT (rpredVr (valP u)).\nLet unitT := [qualify a u : T | val u \\is a unit].\nLet T' := cast_ringType QeqT.\n\nHypothesis val1 : val (1 : T') = 1.\nHypothesis valM : {morph (val : T' -> R) : x y / x * y}.\n\nFact mulVr :\n  {in (unitT : {pred T'}), left_inverse (1 : T') invT (@mul T')}.\nProof. by move=> u Uu; apply: val_inj; rewrite val1 valM SubK mulVr. Qed.\n\nFact mulrV : {in unitT, right_inverse (1 : T') invT (@mul T')}.\nProof. by move=> u Uu; apply: val_inj; rewrite val1 valM SubK mulrV. Qed.\n\nFact unitP (u v : T') : v * u = 1 /\\ u * v = 1 -> u \\in unitT.\nProof.\nby case=> vu1 uv1; apply/unitrP; exists (val v); rewrite -!valM vu1 uv1.\nQed.\n\nFact unit_id : {in [predC unitT], invT =1 id}.\nProof. by move=> u /invr_out def_u1; apply: val_inj; rewrite SubK. Qed.\n\nDefinition unitRingMixin := UnitRingMixin mulVr mulrV unitP unit_id.\n\nEnd UnitRing.\n\nLemma idomainMixin (R : idomainType) (T : ringType) (f : T -> R) :\n    phant T -> injective f -> f 0 = 0 -> {morph f : u v / u * v} ->\n  @IntegralDomain.axiom T.\nProof.\nmove=> _ injf f0 fM u v uv0.\nby rewrite -!(inj_eq injf) !f0 -mulf_eq0 -fM uv0 f0.\nQed.\n\nLemma fieldMixin (F : fieldType) (K : unitRingType) (f : K -> F) : \n    phant K -> injective f -> f 0 = 0 -> {mono f : u / u \\in unit} -> \n  @Field.mixin_of K.\nProof. by move=> _ injf f0 fU u; rewrite -fU unitfE -f0 inj_eq. Qed.\n\nModule Exports.\n\nNotation \"[ 'zmodMixin' 'of' U 'by' <: ]\" := (zmodMixin (Phant U))\n  (at level 0, format \"[ 'zmodMixin'  'of'  U  'by'  <: ]\") : form_scope.\nNotation \"[ 'ringMixin' 'of' R 'by' <: ]\" :=\n  (@ringMixin _ _ _ _ _ _ (@erefl Type R%type) (rrefl _))\n  (at level 0, format \"[ 'ringMixin'  'of'  R  'by'  <: ]\") : form_scope.\nNotation \"[ 'lmodMixin' 'of' U 'by' <: ]\" :=\n  (@lmodMixin _ _ _ _ _ _ _ (@erefl Type U%type) (rrefl _))\n  (at level 0, format \"[ 'lmodMixin'  'of'  U  'by'  <: ]\") : form_scope.\nNotation \"[ 'lalgMixin' 'of' A 'by' <: ]\" :=\n  ((lalgMixin (Phant A) val_inj (rrefl _)) *%R (rrefl _))\n  (at level 0, format \"[ 'lalgMixin'  'of'  A  'by'  <: ]\") : form_scope.\nNotation \"[ 'comRingMixin' 'of' R 'by' <: ]\" :=\n  (comRingMixin (Phant R) val_inj (rrefl _))\n  (at level 0, format \"[ 'comRingMixin'  'of'  R  'by'  <: ]\") : form_scope.\nNotation \"[ 'algMixin' 'of' A 'by' <: ]\" :=\n  (algMixin (Phant A) val_inj (rrefl _) (rrefl _))\n  (at level 0, format \"[ 'algMixin'  'of'  A  'by'  <: ]\") : form_scope.\nNotation \"[ 'unitRingMixin' 'of' R 'by' <: ]\" :=\n  (@unitRingMixin _ _ _ _ _ _ (@erefl Type R%type) (erefl _) (rrefl _))\n  (at level 0, format \"[ 'unitRingMixin'  'of'  R  'by'  <: ]\") : form_scope.\nNotation \"[ 'idomainMixin' 'of' R 'by' <: ]\" :=\n  (idomainMixin (Phant R) val_inj (erefl _) (rrefl _))\n  (at level 0, format \"[ 'idomainMixin'  'of'  R  'by'  <: ]\") : form_scope.\nNotation \"[ 'fieldMixin' 'of' F 'by' <: ]\" :=\n  (fieldMixin (Phant F) val_inj (erefl _) (frefl _))\n  (at level 0, format \"[ 'fieldMixin'  'of'  F  'by'  <: ]\") : form_scope.\n\nEnd Exports.\n\nEnd SubType.\n\nModule Theory.\n\nDefinition addrA := addrA.\nDefinition addrC := addrC.\nDefinition add0r := add0r.\nDefinition addNr := addNr.\nDefinition addr0 := addr0.\nDefinition addrN := addrN.\nDefinition subrr := subrr.\nDefinition addrCA := addrCA.\nDefinition addrAC := addrAC.\nDefinition addrACA := addrACA.\nDefinition addKr := addKr.\nDefinition addNKr := addNKr.\nDefinition addrK := addrK.\nDefinition addrNK := addrNK.\nDefinition subrK := subrK.\nDefinition subKr := subKr.\nDefinition addrI := @addrI.\nDefinition addIr := @addIr.\nDefinition subrI := @subrI.\nDefinition subIr := @subIr.\nArguments addrI {V} y [x1 x2].\nArguments addIr {V} x [x1 x2].\nArguments subrI {V} y [x1 x2].\nArguments subIr {V} x [x1 x2].\nDefinition opprK := @opprK.\nArguments opprK {V}.\nDefinition oppr_inj := @oppr_inj.\nArguments oppr_inj {V} [x1 x2].\nDefinition oppr0 := oppr0.\nDefinition oppr_eq0 := oppr_eq0.\nDefinition opprD := opprD.\nDefinition opprB := opprB.\nDefinition addrKA := addrKA.\nDefinition subrKA := subrKA.\nDefinition subr0 := subr0.\nDefinition sub0r := sub0r.\nDefinition subr_eq := subr_eq.\nDefinition addr0_eq := addr0_eq.\nDefinition subr0_eq := subr0_eq.\nDefinition subr_eq0 := subr_eq0.\nDefinition addr_eq0 := addr_eq0.\nDefinition eqr_opp := eqr_opp.\nDefinition eqr_oppLR := eqr_oppLR.\nDefinition sumrN := sumrN.\nDefinition sumrB := sumrB.\nDefinition sumrMnl := sumrMnl.\nDefinition sumrMnr := sumrMnr.\nDefinition sumr_const := sumr_const.\nDefinition sumr_const_nat := sumr_const_nat.\nDefinition telescope_sumr := telescope_sumr.\nDefinition telescope_sumr_eq := @telescope_sumr_eq.\nArguments telescope_sumr_eq {V n m} f u.\nDefinition mulr0n := mulr0n.\nDefinition mulr1n := mulr1n.\nDefinition mulr2n := mulr2n.\nDefinition mulrS := mulrS.\nDefinition mulrSr := mulrSr.\nDefinition mulrb := mulrb.\nDefinition mul0rn := mul0rn.\nDefinition mulNrn := mulNrn.\nDefinition mulrnDl := mulrnDl.\nDefinition mulrnDr := mulrnDr.\nDefinition mulrnBl := mulrnBl.\nDefinition mulrnBr := mulrnBr.\nDefinition mulrnA := mulrnA.\nDefinition mulrnAC := mulrnAC.\nDefinition iter_addr := iter_addr.\nDefinition iter_addr_0 := iter_addr_0.\nDefinition mulrA := mulrA.\nDefinition mul1r := mul1r.\nDefinition mulr1 := mulr1.\nDefinition mulrDl := mulrDl.\nDefinition mulrDr := mulrDr.\nDefinition oner_neq0 := oner_neq0.\nDefinition oner_eq0 := oner_eq0.\nDefinition mul0r := mul0r.\nDefinition mulr0 := mulr0.\nDefinition mulrN := mulrN.\nDefinition mulNr := mulNr.\nDefinition mulrNN := mulrNN.\nDefinition mulN1r := mulN1r.\nDefinition mulrN1 := mulrN1.\nDefinition mulr_suml := mulr_suml.\nDefinition mulr_sumr := mulr_sumr.\nDefinition mulrBl := mulrBl.\nDefinition mulrBr := mulrBr.\nDefinition mulrnAl := mulrnAl.\nDefinition mulrnAr := mulrnAr.\nDefinition mulr_natl := mulr_natl.\nDefinition mulr_natr := mulr_natr.\nDefinition natrD := natrD.\nDefinition nat1r := nat1r.\nDefinition natr1 := natr1.\nDefinition natrB := natrB.\nDefinition natr_sum := natr_sum.\nDefinition natrM := natrM.\nDefinition natrX := natrX.\nDefinition expr0 := expr0.\nDefinition exprS := exprS.\nDefinition expr1 := expr1.\nDefinition expr2 := expr2.\nDefinition expr0n := expr0n.\nDefinition expr1n := expr1n.\nDefinition exprD := exprD.\nDefinition exprSr := exprSr.\nDefinition expr_sum := expr_sum.\nDefinition commr_sym := commr_sym.\nDefinition commr_refl := commr_refl.\nDefinition commr0 := commr0.\nDefinition commr1 := commr1.\nDefinition commrN := commrN.\nDefinition commrN1 := commrN1.\nDefinition commrD := commrD.\nDefinition commrB := commrB.\nDefinition commr_sum := commr_sum.\nDefinition commr_prod := commr_prod.\nDefinition commrMn := commrMn.\nDefinition commrM := commrM.\nDefinition commr_nat := commr_nat.\nDefinition commrX := commrX.\nDefinition exprMn_comm := exprMn_comm.\nDefinition commr_sign := commr_sign.\nDefinition exprMn_n := exprMn_n.\nDefinition exprM := exprM.\nDefinition exprAC := exprAC.\nDefinition expr_mod := expr_mod.\nDefinition expr_dvd := expr_dvd.\nDefinition signr_odd := signr_odd.\nDefinition signr_eq0 := signr_eq0.\nDefinition mulr_sign := mulr_sign.\nDefinition signr_addb := signr_addb.\nDefinition signrN := signrN.\nDefinition signrE := signrE.\nDefinition mulr_signM := mulr_signM.\nDefinition exprNn := exprNn.\nDefinition sqrrN := sqrrN.\nDefinition sqrr_sign := sqrr_sign.\nDefinition signrMK := signrMK.\nDefinition mulrI_eq0 := mulrI_eq0.\nDefinition lreg_neq0 := lreg_neq0.\nDefinition mulrI0_lreg := mulrI0_lreg.\nDefinition lregN := lregN.\nDefinition lreg1 := lreg1.\nDefinition lregM := lregM.\nDefinition lregX := lregX.\nDefinition lreg_sign := lreg_sign.\nDefinition lregP {R x} := @lregP R x.\nDefinition mulIr_eq0 := mulIr_eq0.\nDefinition mulIr0_rreg := mulIr0_rreg.\nDefinition rreg_neq0 := rreg_neq0.\nDefinition rregN := rregN.\nDefinition rreg1 := rreg1.\nDefinition rregM := rregM.\nDefinition revrX := revrX.\nDefinition rregX := rregX.\nDefinition rregP {R x} := @rregP R x.\nDefinition exprDn_comm := exprDn_comm.\nDefinition exprBn_comm := exprBn_comm.\nDefinition subrXX_comm := subrXX_comm.\nDefinition exprD1n := exprD1n.\nDefinition subrX1 := subrX1.\nDefinition sqrrD1 := sqrrD1.\nDefinition sqrrB1 := sqrrB1.\nDefinition subr_sqr_1 := subr_sqr_1.\nDefinition charf0 := charf0.\nDefinition charf_prime := charf_prime.\nDefinition mulrn_char := mulrn_char.\nDefinition dvdn_charf := dvdn_charf.\nDefinition charf_eq := charf_eq.\nDefinition bin_lt_charf_0 := bin_lt_charf_0.\nDefinition Frobenius_autE := Frobenius_autE.\nDefinition Frobenius_aut0 := Frobenius_aut0.\nDefinition Frobenius_aut1 := Frobenius_aut1.\nDefinition Frobenius_autD_comm := Frobenius_autD_comm.\nDefinition Frobenius_autMn := Frobenius_autMn.\nDefinition Frobenius_aut_nat := Frobenius_aut_nat.\nDefinition Frobenius_autM_comm := Frobenius_autM_comm.\nDefinition Frobenius_autX := Frobenius_autX.\nDefinition Frobenius_autN := Frobenius_autN.\nDefinition Frobenius_autB_comm := Frobenius_autB_comm.\nDefinition exprNn_char := exprNn_char.\nDefinition addrr_char2 := addrr_char2.\nDefinition oppr_char2 := oppr_char2.\nDefinition addrK_char2 := addrK_char2.\nDefinition addKr_char2 := addKr_char2.\nDefinition iter_mulr := iter_mulr.\nDefinition iter_mulr_1 := iter_mulr_1.\nDefinition prodr_const := prodr_const.\nDefinition prodr_const_nat := prodr_const_nat.\nDefinition mulrC := mulrC.\nDefinition mulrCA := mulrCA.\nDefinition mulrAC := mulrAC.\nDefinition mulrACA := mulrACA.\nDefinition exprMn := exprMn.\nDefinition prodrXl := prodrXl.\nDefinition prodrXr := prodrXr.\nDefinition prodrN := prodrN.\nDefinition prodrMn_const := prodrMn_const.\nDefinition prodrMn := prodrMn.\nDefinition natr_prod := natr_prod.\nDefinition prodr_undup_exp_count := prodr_undup_exp_count.\nDefinition exprDn := exprDn.\nDefinition exprBn := exprBn.\nDefinition subrXX := subrXX.\nDefinition sqrrD := sqrrD.\nDefinition sqrrB := sqrrB.\nDefinition subr_sqr := subr_sqr.\nDefinition subr_sqrDB := subr_sqrDB.\nDefinition exprDn_char := exprDn_char.\nDefinition mulrV := mulrV.\nDefinition divrr := divrr.\nDefinition mulVr := mulVr.\nDefinition invr_out := invr_out.\nDefinition unitrP {R x} := @unitrP R x.\nDefinition mulKr := mulKr.\nDefinition mulVKr := mulVKr.\nDefinition mulrK := mulrK.\nDefinition mulrVK := mulrVK.\nDefinition divrK := divrK.\nDefinition mulrI := mulrI.\nDefinition mulIr := mulIr.\nDefinition divrI := divrI.\nDefinition divIr := divIr.\nDefinition telescope_prodr := telescope_prodr.\nDefinition telescope_prodr_eq := @telescope_prodr_eq.\nArguments telescope_prodr_eq {R n m} f u.\nDefinition commrV := commrV.\nDefinition unitrE := unitrE.\nDefinition invrK := @invrK.\nArguments invrK {R}.\nDefinition invr_inj := @invr_inj.\nArguments invr_inj {R} [x1 x2].\nDefinition unitrV := unitrV.\nDefinition unitr1 := unitr1.\nDefinition invr1 := invr1.\nDefinition divr1 := divr1.\nDefinition div1r := div1r.\nDefinition natr_div := natr_div.\nDefinition unitr0 := unitr0.\nDefinition invr0 := invr0.\nDefinition unitrN1 := unitrN1.\nDefinition unitrN := unitrN.\nDefinition invrN1 := invrN1.\nDefinition invrN := invrN.\nDefinition divrNN := divrNN.\nDefinition divrN := divrN.\nDefinition invr_sign := invr_sign.\nDefinition unitrMl := unitrMl.\nDefinition unitrMr := unitrMr.\nDefinition invrM := invrM.\nDefinition invr_eq0 := invr_eq0.\nDefinition invr_eq1 := invr_eq1.\nDefinition invr_neq0 := invr_neq0.\nDefinition unitrM_comm := unitrM_comm.\nDefinition unitrX := unitrX.\nDefinition unitrX_pos := unitrX_pos.\nDefinition exprVn := exprVn.\nDefinition exprB := exprB.\nDefinition invr_signM := invr_signM.\nDefinition divr_signM := divr_signM.\nDefinition rpred0D := rpred0D.\nDefinition rpred0 := rpred0.\nDefinition rpredD := rpredD.\nDefinition rpredNr := rpredNr.\nDefinition rpred_sum := rpred_sum.\nDefinition rpredMn := rpredMn.\nDefinition rpredN := rpredN.\nDefinition rpredB := rpredB.\nDefinition rpredBC := rpredBC.\nDefinition rpredMNn := rpredMNn.\nDefinition rpredDr := rpredDr.\nDefinition rpredDl := rpredDl.\nDefinition rpredBr := rpredBr.\nDefinition rpredBl := rpredBl.\nDefinition rpredMsign := rpredMsign.\nDefinition rpred1M := rpred1M.\nDefinition rpred1 := rpred1.\nDefinition rpredM := rpredM.\nDefinition rpred_prod := rpred_prod.\nDefinition rpredX := rpredX.\nDefinition rpred_nat := rpred_nat.\nDefinition rpredN1 := rpredN1.\nDefinition rpred_sign := rpred_sign.\nDefinition rpredZsign := rpredZsign.\nDefinition rpredZnat := rpredZnat.\nDefinition rpredZ := rpredZ.\nDefinition rpredVr := rpredVr.\nDefinition rpredV := rpredV.\nDefinition rpred_div := rpred_div.\nDefinition rpredXN := rpredXN.\nDefinition rpredZeq := rpredZeq.\nDefinition char_lalg := char_lalg.\nDefinition rpredMr := rpredMr.\nDefinition rpredMl := rpredMl.\nDefinition rpred_divr := rpred_divr.\nDefinition rpred_divl := rpred_divl.\nDefinition eq_eval := eq_eval.\nDefinition eval_tsubst := eval_tsubst.\nDefinition eq_holds := eq_holds.\nDefinition holds_fsubst := holds_fsubst.\nDefinition unitrM := unitrM.\nDefinition unitrPr {R x} := @unitrPr R x.\nDefinition expr_div_n := expr_div_n.\nDefinition mulr1_eq := mulr1_eq.\nDefinition divr1_eq := divr1_eq.\nDefinition divKr := divKr.\nDefinition mulf_eq0 := mulf_eq0.\nDefinition prodf_eq0 := prodf_eq0.\nDefinition prodf_seq_eq0 := prodf_seq_eq0.\nDefinition mulf_neq0 := mulf_neq0.\nDefinition prodf_neq0 := prodf_neq0.\nDefinition prodf_seq_neq0 := prodf_seq_neq0.\nDefinition expf_eq0 := expf_eq0.\nDefinition sqrf_eq0 := sqrf_eq0.\nDefinition expf_neq0 := expf_neq0.\nDefinition natf_neq0 := natf_neq0.\nDefinition natf0_char := natf0_char.\nDefinition charf'_nat := charf'_nat.\nDefinition charf0P := charf0P.\nDefinition eqf_sqr := eqf_sqr.\nDefinition mulfI := mulfI.\nDefinition mulIf := mulIf.\nDefinition divfI := divfI.\nDefinition divIf := divIf.\nDefinition sqrf_eq1 := sqrf_eq1.\nDefinition expfS_eq1 := expfS_eq1.\nDefinition fieldP := fieldP.\nDefinition unitfE := unitfE.\nDefinition mulVf := mulVf.\nDefinition mulfV := mulfV.\nDefinition divff := divff.\nDefinition mulKf := mulKf.\nDefinition mulVKf := mulVKf.\nDefinition mulfK := mulfK.\nDefinition mulfVK := mulfVK.\nDefinition divfK := divfK.\nDefinition divKf := divKf.\nDefinition invfM := invfM.\nDefinition invf_div := invf_div.\nDefinition expfB_cond := expfB_cond.\nDefinition expfB := expfB.\nDefinition prodfV := prodfV.\nDefinition prodf_div := prodf_div.\nDefinition telescope_prodf := telescope_prodf.\nDefinition telescope_prodf_eq := @telescope_prodf_eq.\nArguments telescope_prodf_eq {F n m} f u.\nDefinition addf_div := addf_div.\nDefinition mulf_div := mulf_div.\nDefinition eqr_div := eqr_div.\nDefinition eqr_sum_div := eqr_sum_div.\nDefinition char0_natf_div := char0_natf_div.\nDefinition fpredMr := fpredMr.\nDefinition fpredMl := fpredMl.\nDefinition fpred_divr := fpred_divr.\nDefinition fpred_divl := fpred_divl.\nDefinition satP {F e f} := @satP F e f.\nDefinition eq_sat := eq_sat.\nDefinition solP {F n f} := @solP F n f.\nDefinition eq_sol := eq_sol.\nDefinition size_sol := size_sol.\nDefinition solve_monicpoly := solve_monicpoly.\nDefinition raddf0 := raddf0.\nDefinition raddf_eq0 := raddf_eq0.\nDefinition raddf_inj := raddf_inj.\nDefinition raddfN := raddfN.\nDefinition raddfD := raddfD.\nDefinition raddfB := raddfB.\nDefinition raddf_sum := raddf_sum.\nDefinition raddfMn := raddfMn.\nDefinition raddfMNn := raddfMNn.\nDefinition raddfMnat := raddfMnat.\nDefinition raddfMsign := raddfMsign.\nDefinition can2_additive := can2_additive.\nDefinition bij_additive := bij_additive.\nDefinition rmorph0 := rmorph0.\nDefinition rmorphN := rmorphN.\nDefinition rmorphD := rmorphD.\nDefinition rmorphB := rmorphB.\nDefinition rmorph_sum := rmorph_sum.\nDefinition rmorphMn := rmorphMn.\nDefinition rmorphMNn := rmorphMNn.\nDefinition rmorphismP := rmorphismP.\nDefinition rmorphismMP := rmorphismMP.\nDefinition rmorph1 := rmorph1.\nDefinition rmorph_eq1 := rmorph_eq1.\nDefinition rmorphM := rmorphM.\nDefinition rmorphMsign := rmorphMsign.\nDefinition rmorph_nat := rmorph_nat.\nDefinition rmorph_eq_nat := rmorph_eq_nat.\nDefinition rmorph_prod := rmorph_prod.\nDefinition rmorphX := rmorphX.\nDefinition rmorphN1 := rmorphN1.\nDefinition rmorph_sign := rmorph_sign.\nDefinition rmorph_char := rmorph_char.\nDefinition can2_rmorphism := can2_rmorphism.\nDefinition bij_rmorphism := bij_rmorphism.\nDefinition rmorph_comm := rmorph_comm.\nDefinition rmorph_unit := rmorph_unit.\nDefinition rmorphV := rmorphV.\nDefinition rmorph_div := rmorph_div.\nDefinition fmorph_eq0 := fmorph_eq0.\nDefinition fmorph_inj := @fmorph_inj.\nArguments fmorph_inj {F R} f [x1 x2].\nDefinition fmorph_eq := fmorph_eq.\nDefinition fmorph_eq1 := fmorph_eq1.\nDefinition fmorph_char := fmorph_char.\nDefinition fmorph_unit := fmorph_unit.\nDefinition fmorphV := fmorphV.\nDefinition fmorph_div := fmorph_div.\nDefinition scalerA := scalerA.\nDefinition scale1r := scale1r.\nDefinition scalerDr := scalerDr.\nDefinition scalerDl := scalerDl.\nDefinition scaler0 := scaler0.\nDefinition scale0r := scale0r.\nDefinition scaleNr := scaleNr.\nDefinition scaleN1r := scaleN1r.\nDefinition scalerN := scalerN.\nDefinition scalerBl := scalerBl.\nDefinition scalerBr := scalerBr.\nDefinition scaler_nat := scaler_nat.\nDefinition scalerMnl := scalerMnl.\nDefinition scalerMnr := scalerMnr.\nDefinition scaler_suml := scaler_suml.\nDefinition scaler_sumr := scaler_sumr.\nDefinition scaler_eq0 := scaler_eq0.\nDefinition scalerK := scalerK.\nDefinition scalerKV := scalerKV.\nDefinition scalerI := scalerI.\nDefinition scalerAl := scalerAl.\nDefinition mulr_algl := mulr_algl.\nDefinition scaler_sign := scaler_sign.\nDefinition signrZK := signrZK.\nDefinition scalerCA := scalerCA.\nDefinition scalerAr := scalerAr.\nDefinition mulr_algr := mulr_algr.\nDefinition comm_alg := comm_alg.\nDefinition exprZn := exprZn.\nDefinition scaler_prodl := scaler_prodl.\nDefinition scaler_prodr := scaler_prodr.\nDefinition scaler_prod := scaler_prod.\nDefinition scaler_injl := scaler_injl.\nDefinition scaler_unit := scaler_unit.\nDefinition invrZ := invrZ.\nDefinition raddfZnat := raddfZnat.\nDefinition raddfZsign := raddfZsign.\nDefinition in_algE := in_algE.\nDefinition linear0 := linear0.\nDefinition linearN := linearN.\nDefinition linearD := linearD.\nDefinition linearB := linearB.\nDefinition linear_sum := linear_sum.\nDefinition linearMn := linearMn.\nDefinition linearMNn := linearMNn.\nDefinition linearP := linearP.\nDefinition linearZ_LR := linearZ_LR.\nDefinition linearZ := linearZ.\nDefinition linearPZ := linearPZ.\nDefinition linearZZ := linearZZ.\nDefinition scalarP := scalarP.\nDefinition scalarZ := scalarZ.\nDefinition can2_linear := can2_linear.\nDefinition bij_linear := bij_linear.\nDefinition rmorph_alg := rmorph_alg.\nDefinition lrmorphismP := lrmorphismP.\nDefinition can2_lrmorphism := can2_lrmorphism.\nDefinition bij_lrmorphism := bij_lrmorphism.\nDefinition imaginary_exists := imaginary_exists.\n\nDefinition raddf := (raddf0, raddfN, raddfD, raddfMn).\n\nDefinition rmorphE :=\n  (rmorphD, rmorph0, rmorphB, rmorphN, rmorphMNn, rmorphMn, rmorph1, rmorphX).\n\nDefinition linearE :=\n  (linearD, linear0, linearB, linearMNn, linearMn, linearZ).\n\nNotation null_fun V := (null_fun V) (only parsing).\nNotation in_alg A := (in_alg_loc A).\n\nEnd Theory.\n\nNotation in_alg A := (in_alg_loc A).\n\nEnd GRing.\n\nExport Zmodule.Exports Ring.Exports Lmodule.Exports Lalgebra.Exports.\nExport Additive.Exports RMorphism.Exports Linear.Exports LRMorphism.Exports.\nExport Algebra.Exports UnitRing.Exports UnitAlgebra.Exports.\nExport ComRing.Exports ComAlgebra.Exports ComUnitRing.Exports.\nExport ComUnitAlgebra.Exports IntegralDomain.Exports Field.Exports.\nExport DecidableField.Exports ClosedField.Exports.\nExport Pred.Exports SubType.Exports.\nNotation QEdecFieldMixin := QEdecFieldMixin.\n\nVariant Ione := IOne : Ione.\nVariant Inatmul := INatmul : Ione -> nat -> Inatmul.\nVariant Idummy_placeholder :=.\n\nDefinition parse (x : Number.uint) : Inatmul :=\n  INatmul IOne (Nat.of_num_uint x).\n\nDefinition print (x : Inatmul) : Number.uint :=\n  match x with\n  | INatmul IOne n => Number.UIntDecimal (Nat.to_uint n)\n  end.\n\nArguments GRing.one {R}.\nSet Warnings \"-via-type-remapping,-via-type-mismatch\".\nNumber Notation Idummy_placeholder parse print (via Inatmul\n  mapping [[GRing.natmul] => INatmul, [GRing.one] => IOne])\n  : ring_scope.\nSet Warnings \"via-type-remapping,via-type-mismatch\".\nArguments GRing.one : clear implicits.\n\nNotation \"0\" := (zero _) : ring_scope.\nNotation \"-%R\" := (@opp _) : fun_scope.\nNotation \"- x\" := (opp x) : ring_scope.\nNotation \"+%R\" := (@add _) : fun_scope.\nNotation \"x + y\" := (add x y) : ring_scope.\nNotation \"x - y\" := (add x (- y)) : ring_scope.\nNotation \"x *+ n\" := (natmul x n) : ring_scope.\nNotation \"x *- n\" := (opp (x *+ n)) : ring_scope.\nNotation \"s `_ i\" := (seq.nth 0%R s%R i) : ring_scope.\nNotation support := 0.-support.\n\nNotation \"1\" := (one _) : ring_scope.\nNotation \"- 1\" := (opp 1) : ring_scope.\n\nNotation \"n %:R\" := (natmul 1 n) : ring_scope.\nNotation \"[ 'char' R ]\" := (char (Phant R)) : ring_scope.\nNotation Frobenius_aut chRp := (Frobenius_aut chRp).\nNotation \"*%R\" := (@mul _) : fun_scope.\nNotation \"x * y\" := (mul x y) : ring_scope.\nNotation \"x ^+ n\" := (exp x n) : ring_scope.\nNotation \"x ^-1\" := (inv x) : ring_scope.\nNotation \"x ^- n\" := (inv (x ^+ n)) : ring_scope.\nNotation \"x / y\" := (mul x y^-1) : ring_scope.\n\nNotation \"*:%R\" := (@scale _ _) : fun_scope.\nNotation \"a *: m\" := (scale a m) : ring_scope.\nNotation \"k %:A\" := (scale k 1) : ring_scope.\nNotation \"\\0\" := (null_fun _) : ring_scope.\nNotation \"f \\+ g\" := (add_fun f g) : ring_scope.\nNotation \"f \\- g\" := (sub_fun f g) : ring_scope.\nNotation \"\\- f\" := (opp_fun f) : ring_scope.\nNotation \"a \\*: f\" := (scale_fun a f) : ring_scope.\nNotation \"x \\*o f\" := (mull_fun x f) : ring_scope.\nNotation \"x \\o* f\" := (mulr_fun x f) : ring_scope.\nNotation \"f \\* g\" := (mul_fun f g) : ring_scope.\n\nArguments add_fun {_ _} f g _ /.\nArguments sub_fun {_ _} f g _ /.\nArguments opp_fun {_ _} f _ /.\nArguments mull_fun {_ _}  a f _ /.\nArguments mulr_fun {_ _} a f _ /.\nArguments scale_fun {_ _ _} a f _ /.\nArguments mul_fun {_ _} f g _ /.\n\nNotation \"\\sum_ ( i <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r ) F\" :=\n  (\\big[+%R/0%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i | P ) F\" :=\n  (\\big[+%R/0%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\sum_ i F\" :=\n  (\\big[+%R/0%R]_i F%R) : ring_scope.\nNotation \"\\sum_ ( i : t | P ) F\" :=\n  (\\big[+%R/0%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i : t ) F\" :=\n  (\\big[+%R/0%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i < n ) F\" :=\n  (\\big[+%R/0%R]_(i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i 'in' A | P ) F\" :=\n  (\\big[+%R/0%R]_(i in A | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i 'in' A ) F\" :=\n  (\\big[+%R/0%R]_(i in A) F%R) : ring_scope.\n\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[*%R/1%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[*%R/1%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[*%R/1%R]_i F%R) : ring_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[*%R/1%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[*%R/1%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[*%R/1%R]_(i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i 'in' A | P ) F\" :=\n  (\\big[*%R/1%R]_(i in A | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i 'in' A ) F\" :=\n  (\\big[*%R/1%R]_(i in A) F%R) : ring_scope.\n\nCanonical add_monoid.\nCanonical add_comoid.\nCanonical mul_monoid.\nCanonical mul_comoid.\nCanonical muloid.\nCanonical addoid.\n\nCanonical locked_additive.\nCanonical locked_rmorphism.\nCanonical locked_linear.\nCanonical locked_lrmorphism.\nCanonical idfun_additive.\nCanonical idfun_rmorphism.\nCanonical idfun_linear.\nCanonical idfun_lrmorphism.\nCanonical comp_additive.\nCanonical comp_rmorphism.\nCanonical comp_linear.\nCanonical comp_lrmorphism.\nCanonical opp_additive.\nCanonical opp_linear.\nCanonical scale_additive.\nCanonical scale_linear.\nCanonical null_fun_additive.\nCanonical null_fun_linear.\nCanonical scale_fun_additive.\nCanonical scale_fun_linear.\nCanonical add_fun_additive.\nCanonical add_fun_linear.\nCanonical sub_fun_additive.\nCanonical sub_fun_linear.\nCanonical opp_fun_additive.\nCanonical opp_fun_linear.\nCanonical mull_fun_additive.\nCanonical mull_fun_linear.\nCanonical mulr_fun_additive.\nCanonical mulr_fun_linear.\nCanonical Frobenius_aut_additive.\nCanonical Frobenius_aut_rmorphism.\nCanonical in_alg_additive.\nCanonical in_alg_rmorphism.\n\nNotation \"R ^c\" := (converse R) (at level 2, format \"R ^c\") : type_scope.\nCanonical converse_eqType.\nCanonical converse_choiceType.\nCanonical converse_zmodType.\nCanonical converse_ringType.\nCanonical converse_unitRingType.\n\nNotation \"R ^o\" := (regular R) (at level 2, format \"R ^o\") : type_scope.\nCanonical regular_eqType.\nCanonical regular_choiceType.\nCanonical regular_zmodType.\nCanonical regular_ringType.\nCanonical regular_lmodType.\nCanonical regular_lalgType.\nCanonical regular_comRingType.\nCanonical regular_algType.\nCanonical regular_unitRingType.\nCanonical regular_comUnitRingType.\nCanonical regular_unitAlgType.\nCanonical regular_comAlgType.\nCanonical regular_comUnitAlgType.\nCanonical regular_idomainType.\nCanonical regular_fieldType.\n\nCanonical unit_keyed.\nCanonical unit_opprPred.\nCanonical unit_mulrPred.\nCanonical unit_smulrPred.\nCanonical unit_divrPred.\nCanonical unit_sdivrPred.\n\nBind Scope term_scope with term.\nBind Scope term_scope with formula.\n\nNotation \"''X_' i\" := (Var _ i) : term_scope.\nNotation \"n %:R\" := (NatConst _ n) : term_scope.\nNotation \"0\" := 0%:R%T : term_scope.\nNotation \"1\" := 1%:R%T : term_scope.\nNotation \"x %:T\" := (Const x) : term_scope.\nInfix \"+\" := Add : term_scope.\nNotation \"- t\" := (Opp t) : term_scope.\nNotation \"t - u\" := (Add t (- u)) : term_scope.\nInfix \"*\" := Mul : term_scope.\nInfix \"*+\" := NatMul : term_scope.\nNotation \"t ^-1\" := (Inv t) : term_scope.\nNotation \"t / u\" := (Mul t u^-1) : term_scope.\nInfix \"^+\" := Exp : term_scope.\nInfix \"==\" := Equal : term_scope.\nNotation \"x != y\" := (GRing.Not (x == y)) : term_scope.\nInfix \"/\\\" := And : term_scope.\nInfix \"\\/\" := Or : term_scope.\nInfix \"==>\" := Implies : term_scope.\nNotation \"~ f\" := (Not f) : term_scope.\nNotation \"''exists' ''X_' i , f\" := (Exists i f) : term_scope.\nNotation \"''forall' ''X_' i , f\" := (Forall i f) : term_scope.\n\n(* Lifting Structure from the codomain of finfuns. *)\nSection FinFunZmod.\n\nVariable (aT : finType) (rT : zmodType).\nImplicit Types f g : {ffun aT -> rT}.\n\nDefinition ffun_zero := [ffun a : aT => (0 : rT)].\nDefinition ffun_opp f := [ffun a => - f a].\nDefinition ffun_add f g := [ffun a => f a + g a].\n\nFact ffun_addA : associative ffun_add.\nProof. by move=> f1 f2 f3; apply/ffunP=> a; rewrite !ffunE addrA. Qed.\nFact ffun_addC : commutative ffun_add.\nProof. by move=> f1 f2; apply/ffunP=> a; rewrite !ffunE addrC. Qed.\nFact ffun_add0 : left_id ffun_zero ffun_add.\nProof. by move=> f; apply/ffunP=> a; rewrite !ffunE add0r. Qed.\nFact ffun_addN : left_inverse ffun_zero ffun_opp ffun_add.\nProof. by move=> f; apply/ffunP=> a; rewrite !ffunE addNr. Qed.\n\nDefinition ffun_zmodMixin :=\n  Zmodule.Mixin ffun_addA ffun_addC ffun_add0 ffun_addN.\nCanonical ffun_zmodType := Eval hnf in ZmodType _ ffun_zmodMixin.\n\nSection Sum.\n\nVariables (I : Type) (r : seq I) (P : pred I) (F : I -> {ffun aT -> rT}).\n\nLemma sum_ffunE x : (\\sum_(i <- r | P i) F i) x = \\sum_(i <- r | P i) F i x.\nProof. by elim/big_rec2: _ => // [|i _ y _ <-]; rewrite !ffunE. Qed.\n\nLemma sum_ffun :\n  \\sum_(i <- r | P i) F i = [ffun x => \\sum_(i <- r | P i) F i x].\nProof. by apply/ffunP=> i; rewrite sum_ffunE ffunE. Qed.\n\nEnd Sum.\n\nLemma ffunMnE f n x : (f *+ n) x = f x *+ n.\nProof. by rewrite -[n]card_ord -!sumr_const sum_ffunE. Qed.\n\nEnd FinFunZmod.\n\nSection FinFunRing.\n\n(* As rings require 1 != 0 in order to lift a ring structure over finfuns     *)\n(* we need evidence that the domain is non-empty.                             *)\n\nVariable (aT : finType) (R : ringType) (a : aT).\n\nDefinition ffun_one : {ffun aT -> R} := [ffun => 1].\nDefinition ffun_mul (f g : {ffun aT -> R}) := [ffun x => f x * g x].\n\nFact ffun_mulA : associative ffun_mul.\nProof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrA. Qed.\nFact ffun_mul_1l : left_id ffun_one ffun_mul.\nProof. by move=> f; apply/ffunP=> i; rewrite !ffunE mul1r. Qed.\nFact ffun_mul_1r : right_id ffun_one ffun_mul.\nProof. by move=> f; apply/ffunP=> i; rewrite !ffunE mulr1. Qed.\nFact ffun_mul_addl :  left_distributive ffun_mul (@ffun_add _ _).\nProof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrDl. Qed.\nFact ffun_mul_addr :  right_distributive ffun_mul (@ffun_add _ _).\nProof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrDr. Qed.\nFact ffun1_nonzero : ffun_one != 0.\nProof. by apply/eqP => /ffunP/(_ a)/eqP; rewrite !ffunE oner_eq0. Qed.\n\nDefinition ffun_ringMixin :=\n  RingMixin ffun_mulA ffun_mul_1l ffun_mul_1r ffun_mul_addl ffun_mul_addr\n            ffun1_nonzero.\nDefinition ffun_ringType :=\n  Eval hnf in RingType {ffun aT -> R} ffun_ringMixin.\n\nEnd FinFunRing.\n\nSection FinFunComRing.\n\nVariable (aT : finType) (R : comRingType) (a : aT).\n\nFact ffun_mulC : commutative (@ffun_mul aT R).\nProof. by move=> f1 f2; apply/ffunP=> i; rewrite !ffunE mulrC. Qed.\n\nDefinition ffun_comRingType :=\n  Eval hnf in ComRingType (ffun_ringType R a) ffun_mulC.\n\nEnd FinFunComRing.\n\nSection FinFunLmod.\n\nVariable (R : ringType) (aT : finType) (rT : lmodType R).\n\nImplicit Types f g : {ffun aT -> rT}.\n\nDefinition ffun_scale k f := [ffun a => k *: f a].\n\nFact ffun_scaleA k1 k2 f : \n  ffun_scale k1 (ffun_scale k2 f) = ffun_scale (k1 * k2) f.\nProof. by apply/ffunP=> a; rewrite !ffunE scalerA. Qed.\nFact ffun_scale1 : left_id 1 ffun_scale.\nProof. by move=> f; apply/ffunP=> a; rewrite !ffunE scale1r. Qed.\nFact ffun_scale_addr k : {morph (ffun_scale k) : x y / x + y}.\nProof. by move=> f g; apply/ffunP=> a; rewrite !ffunE scalerDr. Qed.\nFact ffun_scale_addl u : {morph (ffun_scale)^~ u : k1 k2 / k1 + k2}.\nProof. by move=> k1 k2; apply/ffunP=> a; rewrite !ffunE scalerDl. Qed.\n\nDefinition ffun_lmodMixin := \n  LmodMixin ffun_scaleA ffun_scale1 ffun_scale_addr ffun_scale_addl.\nCanonical ffun_lmodType :=\n  Eval hnf in LmodType R {ffun aT -> rT} ffun_lmodMixin.\n\nEnd FinFunLmod.\n\n(* External direct product. *)\nSection PairZmod.\n\nVariables M1 M2 : zmodType.\n\nDefinition opp_pair (x : M1 * M2) := (- x.1, - x.2).\nDefinition add_pair (x y : M1 * M2) := (x.1 + y.1, x.2 + y.2).\n\nFact pair_addA : associative add_pair.\nProof. by move=> x y z; congr (_, _); apply: addrA. Qed.\n\nFact pair_addC : commutative add_pair.\nProof. by move=> x y; congr (_, _); apply: addrC. Qed.\n\nFact pair_add0 : left_id (0, 0) add_pair.\nProof. by case=> x1 x2; congr (_, _); apply: add0r. Qed.\n\nFact pair_addN : left_inverse (0, 0) opp_pair add_pair.\nProof. by move=> x; congr (_, _); apply: addNr. Qed.\n\nDefinition pair_zmodMixin := ZmodMixin pair_addA pair_addC pair_add0 pair_addN.\nCanonical pair_zmodType := Eval hnf in ZmodType (M1 * M2) pair_zmodMixin.\n\nFact fst_is_additive : additive fst.\nProof. by []. Qed.\nCanonical fst_additive := Additive fst_is_additive.\nFact snd_is_additive : additive snd.\nProof. by []. Qed.\nCanonical snd_additive := Additive snd_is_additive.\n\nEnd PairZmod.\n\nSection PairRing.\n\nVariables R1 R2 : ringType.\n\nDefinition mul_pair (x y : R1 * R2) := (x.1 * y.1, x.2 * y.2).\n\nFact pair_mulA : associative mul_pair.\nProof. by move=> x y z; congr (_, _); apply: mulrA. Qed.\n\nFact pair_mul1l : left_id (1, 1) mul_pair.\nProof. by case=> x1 x2; congr (_, _); apply: mul1r. Qed.\n\nFact pair_mul1r : right_id (1, 1) mul_pair.\nProof. by case=> x1 x2; congr (_, _); apply: mulr1. Qed.\n\nFact pair_mulDl : left_distributive mul_pair +%R.\nProof. by move=> x y z; congr (_, _); apply: mulrDl. Qed.\n\nFact pair_mulDr : right_distributive mul_pair +%R.\nProof. by move=> x y z; congr (_, _); apply: mulrDr. Qed.\n\nFact pair_one_neq0 : (1, 1) != 0 :> R1 * R2.\nProof. by rewrite xpair_eqE oner_eq0. Qed.\n\nDefinition pair_ringMixin :=\n  RingMixin pair_mulA pair_mul1l pair_mul1r pair_mulDl pair_mulDr pair_one_neq0.\nCanonical pair_ringType := Eval hnf in RingType (R1 * R2) pair_ringMixin.\n\nFact fst_is_multiplicative : multiplicative fst.\nProof. by []. Qed.\nCanonical fst_rmorphism := AddRMorphism fst_is_multiplicative.\nFact snd_is_multiplicative : multiplicative snd.\nProof. by []. Qed.\nCanonical snd_rmorphism := AddRMorphism snd_is_multiplicative.\n\nEnd PairRing.\n\nSection PairComRing.\n\nVariables R1 R2 : comRingType.\n\nFact pair_mulC : commutative (@mul_pair R1 R2).\nProof. by move=> x y; congr (_, _); apply: mulrC. Qed.\n\nCanonical pair_comRingType := Eval hnf in ComRingType (R1 * R2) pair_mulC.\n\nEnd PairComRing.\n\nSection PairLmod.\n\nVariables (R : ringType) (V1 V2 : lmodType R).\n\nDefinition scale_pair a (v : V1 * V2) : V1 * V2 := (a *: v.1, a *: v.2).\n\nFact pair_scaleA a b u : scale_pair a (scale_pair b u) = scale_pair (a * b) u.\nProof. by congr (_, _); apply: scalerA. Qed.\n\nFact pair_scale1 u : scale_pair 1 u = u.\nProof. by case: u => u1 u2; congr (_, _); apply: scale1r. Qed.\n\nFact pair_scaleDr : right_distributive scale_pair +%R.\nProof. by move=> a u v; congr (_, _); apply: scalerDr. Qed.\n\nFact pair_scaleDl u : {morph scale_pair^~ u: a b / a + b}.\nProof. by move=> a b; congr (_, _); apply: scalerDl. Qed.\n\nDefinition pair_lmodMixin :=\n  LmodMixin pair_scaleA pair_scale1 pair_scaleDr pair_scaleDl.\nCanonical pair_lmodType := Eval hnf in LmodType R (V1 * V2) pair_lmodMixin.\n\nFact fst_is_scalable : scalable fst.\nProof. by []. Qed.\nCanonical fst_linear := AddLinear fst_is_scalable.\nFact snd_is_scalable : scalable snd.\nProof. by []. Qed.\nCanonical snd_linear := AddLinear snd_is_scalable.\n\nEnd PairLmod.\n\nSection PairLalg.\n\nVariables (R : ringType) (A1 A2 : lalgType R).\n\nFact pair_scaleAl a (u v : A1 * A2) : a *: (u * v) = (a *: u) * v.\nProof. by congr (_, _); apply: scalerAl. Qed.\nCanonical pair_lalgType :=  Eval hnf in LalgType R (A1 * A2) pair_scaleAl.\n\nDefinition fst_lrmorphism := [lrmorphism of fst].\nDefinition snd_lrmorphism := [lrmorphism of snd].\n\nEnd PairLalg.\n\nSection PairAlg.\n\nVariables (R : comRingType) (A1 A2 : algType R).\n\nFact pair_scaleAr a (u v : A1 * A2) : a *: (u * v) = u * (a *: v).\nProof. by congr (_, _); apply: scalerAr. Qed.\nCanonical pair_algType :=  Eval hnf in AlgType R (A1 * A2) pair_scaleAr.\n\nEnd PairAlg.\n\nSection PairUnitRing.\n\nVariables R1 R2 : unitRingType.\n\nDefinition pair_unitr :=\n  [qualify a x : R1 * R2 | (x.1 \\is a GRing.unit) && (x.2 \\is a GRing.unit)].\nDefinition pair_invr x :=\n  if x \\is a pair_unitr then (x.1^-1, x.2^-1) else x.\n\nLemma pair_mulVl : {in pair_unitr, left_inverse 1 pair_invr *%R}.\nProof.\nrewrite /pair_invr=> x; case: ifP => // /andP[Ux1 Ux2] _.\nby congr (_, _); apply: mulVr.\nQed.\n\nLemma pair_mulVr : {in pair_unitr, right_inverse 1 pair_invr *%R}.\nProof.\nrewrite /pair_invr=> x; case: ifP => // /andP[Ux1 Ux2] _.\nby congr (_, _); apply: mulrV.\nQed.\n\nLemma pair_unitP x y : y * x = 1 /\\ x * y = 1 -> x \\is a pair_unitr.\nProof.\ncase=> [[y1x y2x] [x1y x2y]]; apply/andP.\nby split; apply/unitrP; [exists y.1 | exists y.2].\nQed.\n\nLemma pair_invr_out : {in [predC pair_unitr], pair_invr =1 id}.\nProof. by rewrite /pair_invr => x /negPf/= ->. Qed.\n\nDefinition pair_unitRingMixin :=\n  UnitRingMixin pair_mulVl pair_mulVr pair_unitP pair_invr_out.\nCanonical pair_unitRingType :=\n  Eval hnf in UnitRingType (R1 * R2) pair_unitRingMixin.\n\nEnd PairUnitRing.\n\nCanonical pair_comUnitRingType (R1 R2 : comUnitRingType) :=\n  Eval hnf in [comUnitRingType of R1 * R2].\n\nCanonical pair_unitAlgType (R : comUnitRingType) (A1 A2 : unitAlgType R) :=\n  Eval hnf in [unitAlgType R of A1 * A2].\n\nLemma pairMnE (M1 M2 : zmodType) (x : M1 * M2) n :\n  x *+ n = (x.1 *+ n, x.2 *+ n).\nProof. by case: x => x y; elim: n => //= n; rewrite !mulrS => ->. Qed.\n\n(* begin hide *)\n\n(* Testing subtype hierarchy\nSection Test0.\n\nVariables (T : choiceType) (S : {pred T}).\n\nInductive B := mkB x & x \\in S.\nDefinition vB u := let: mkB x _ := u in x.\n\nCanonical B_subType := [subType for vB].\nDefinition B_eqMixin := [eqMixin of B by <:].\nCanonical B_eqType := EqType B B_eqMixin.\nDefinition B_choiceMixin := [choiceMixin of B by <:].\nCanonical B_choiceType := ChoiceType B B_choiceMixin.\n\nEnd Test0.\n\nSection Test1.\n\nVariables (R : unitRingType) (S : {pred R}).\nVariables (ringS : divringPred S) (kS : keyed_pred ringS).\n\nDefinition B_zmodMixin := [zmodMixin of B kS by <:].\nCanonical B_zmodType := ZmodType (B kS) B_zmodMixin.\nDefinition B_ringMixin := [ringMixin of B kS by <:].\nCanonical B_ringType := RingType (B kS) B_ringMixin.\nDefinition B_unitRingMixin := [unitRingMixin of B kS by <:].\nCanonical B_unitRingType := UnitRingType (B kS) B_unitRingMixin.\n\nEnd Test1.\n\nSection Test2.\n\nVariables (R : comUnitRingType) (A : unitAlgType R) (S : {pred A}).\nVariables (algS : divalgPred S) (kS : keyed_pred algS).\n\nDefinition B_lmodMixin := [lmodMixin of B kS by <:].\nCanonical B_lmodType := LmodType R (B kS) B_lmodMixin.\nDefinition B_lalgMixin := [lalgMixin of B kS by <:].\nCanonical B_lalgType := LalgType R (B kS) B_lalgMixin.\nDefinition B_algMixin := [algMixin of B kS by <:].\nCanonical B_algType := AlgType R (B kS) B_algMixin.\nCanonical B_unitAlgType := [unitAlgType R of B kS].\n\nEnd Test2.\n\nSection Test3.\n\nVariables (F : fieldType) (S : {pred F}).\nVariables (ringS : divringPred S) (kS : keyed_pred ringS).\n\nDefinition B_comRingMixin := [comRingMixin of B kS by <:].\nCanonical B_comRingType := ComRingType (B kS) B_comRingMixin.\nCanonical B_comUnitRingType := [comUnitRingType of B kS].\nDefinition B_idomainMixin := [idomainMixin of B kS by <:].\nCanonical B_idomainType := IdomainType (B kS) B_idomainMixin.\nDefinition B_fieldMixin := [fieldMixin of B kS by <:].\nCanonical B_fieldType := FieldType (B kS) B_fieldMixin.\n\nEnd Test3.\n\n*)\n\n(* end hide *)\n", "meta": {"author": "math-comp", "repo": "math-comp", "sha": "e39f9173b484f2e8e7f69f746a619dcc8f3abc1b", "save_path": "github-repos/coq/math-comp-math-comp", "path": "github-repos/coq/math-comp-math-comp/math-comp-e39f9173b484f2e8e7f69f746a619dcc8f3abc1b/mathcomp/algebra/ssralg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7049678118274832}}
{"text": "Require Import Morphisms.\nImport ProperNotations.\nRequire Import SetoidClass.\nRequire notation categories prods_pullbacks.\n\nModule Make(Import M: notation.T).\n Module Export functors_exp := categories.Make(M).\n\nClass Functor `(catC: Category) `(catD: Category) (F: obj catC -> obj catD)\n                (fmap: forall {a b: obj catC} (f: arrow catC b a), (arrow catD (F b) (F a))): Type :=\n  mk_Functor\n  {\n    preserve_id     : forall {a: obj catC}, fmap (@identity catC a) = (@identity catD (F a));\n    preserve_comp   : forall {a b c: obj catC} (f: arrow catC b a) (g : arrow catC c b), fmap (g o f) = (fmap g) o (fmap f)\n  }.\nCheck Functor.\n\nProgram Instance Opposite_Functor `(catC: Category) `(catD: Category) \n                            (F: obj catC -> obj catD)\n                            (fmapF: forall (a b: obj catC) (f: arrow catC b a), (arrow catD (F b) (F a)))\n                            `(FunctF: Functor catC catD F fmapF): \n                                `(Functor (Dual_Category catC) (Dual_Category catD) F (fun a b => fmapF b a)).\nObligation 1. specialize (@mk_Functor\n                (Dual_Category catC) \n                (Dual_Category catD)\n                F\n                (fun a b => fmapF b a)\n                (fun a => (@preserve_id catC catD F fmapF FunctF a)) \n                (fun a b c f g => (@preserve_comp catC catD F fmapF FunctF c b a g f))\n              ). intros. destruct H as [H1 H2]. apply H1. Qed.\nNext Obligation. specialize (@mk_Functor\n                (Dual_Category catC) \n                (Dual_Category catD)\n                F\n                (fun a b => fmapF b a)\n                (fun a => (@preserve_id catC catD F fmapF FunctF a)) \n                (fun a b c f g => (@preserve_comp catC catD F fmapF FunctF c b a g f))\n              ). intros. destruct H as [H1 H2]. apply H2. Qed.\nCheck Opposite_Functor.\n\n(* another way of showing the same instance above:\nDefinition Opposite_Functor_v2 `(catC: Category) `(catD: Category) \n                            (F: catC -> catD)\n                            (fmapF: forall (a b: catC) (f: arrow catC b a), (arrow catD (F b) (F a)))\n                            `(FunctF: Functor catC catD F fmapF): \n                                `(Functor (Dual_Category catC) (Dual_Category catD) F (fun a b => fmapF b a)).\nProof. refine (@mk_Functor\n                (Dual_Category catC) \n                (Dual_Category catD)\n                F\n                (fun a b => fmapF b a)\n                (fun a => (@preserve_id catC catD F fmapF FunctF a)) \n                (fun a b c f g => (@preserve_comp catC catD F fmapF FunctF c b a g f))\n              ).\nDefined.\n*)\n\nDefinition Opposite_Opposite_Functor `(catC: Category) `(catD: Category) \n                                     (F: obj (Dual_Category catC) -> obj (Dual_Category catD))\n                                     (fmapF: forall (a b: obj (Dual_Category catC)) (f: arrow (Dual_Category catC) b a), \n                                        (arrow (Dual_Category catD) (F b) (F a)))\n                                     `(FunctF: Functor (Dual_Category catC) (Dual_Category catD) F fmapF):\n                                        (Functor catC catD F (fun a b => fmapF b a)).\nProof. refine (@mk_Functor\n                catC \n                catD\n                F\n                (fun a b => fmapF b a)\n                (fun a => (@preserve_id (Dual_Category catC) (Dual_Category catD) F fmapF FunctF a)) \n                (fun a b c f g => (@preserve_comp (Dual_Category catC) (Dual_Category catD) F fmapF FunctF c b a g f))\n              ).\nDefined.\nCheck Opposite_Opposite_Functor.\n\n(** TODO:= prove the theorem here: oppositing is involutive **)\n\n(*define how the identity functor behaves on objects and morphisms*)\nDefinition id {catC: Category} (a: obj catC) := a.\nDefinition idf {catC: Category} {a b: obj catC} (f: arrow catC b a) := f.\n\n(** the identity functor **)\nProgram Instance IdentityFunctor (catC: Category): (@Functor catC catC id (fun a b f => (@idf catC a b f))).\nCheck IdentityFunctor.\n\n(*define how the functor composition behaves on objects and morphisms*)\nDefinition comp_obj_FG  {catC catD catE: Category} {F: obj catC -> obj catD} {G: obj catD -> obj catE} (a: obj catC) := G (F a).\nDefinition comp_morp_FG {catC catD catE: Category} {F: obj catC -> obj catD} {G: obj catD -> obj catE} \n                                {fmapF  : forall (a b: obj catC) (f: arrow catC b a), (arrow catD (F b) (F a))}\n                                {fmapG  : forall (a b: obj catD) (f: arrow catD b a), (arrow catE (G b) (G a))}\n                                (a b: obj catC) (f: (arrow catC b a)) := fmapG _ _ (fmapF _ _ f).\n\n(**functors compose**)\nProgram Instance Compose_Functors (catC catD catE: Category) (F: obj catC -> obj catD) (G: obj catD -> obj catE) \n                                  (fmapF  : forall (a b: obj catC) (f: arrow catC b a), (arrow catD (F b) (F a)))\n                                  (FunctF: @Functor catC catD F fmapF) \n                                  (fmapG  : forall (a b: obj catD) (f: arrow catD b a), (arrow catE (G b) (G a)))\n                                  (FunctG: @Functor catD catE G fmapG):\n                                  (@Functor catC catE (@comp_obj_FG catC catD catE F G) (@comp_morp_FG catC catD catE F G fmapF fmapG)).\nObligation 1. unfold comp_obj_FG, comp_morp_FG. remember (@preserve_id catC catD F fmapF FunctF a).\n  remember (@preserve_id catD catE G fmapG FunctG (F a)). rewrite <- e0. rewrite e. reflexivity. Qed.\nNext Obligation. unfold comp_obj_FG, comp_morp_FG. remember (@preserve_comp catC catD F fmapF FunctF a b c f g).\n  remember (@preserve_comp catD catE G fmapG FunctG (F a) (F b) (F c) (fmapF _ _ f) (fmapF _ _ g)).\n  rewrite <- e0. rewrite e. reflexivity. Qed.\nCheck Compose_Functors.\n\n(** constant functor **)\nDefinition Constant_Functor `(catC: Category) `(catD: Category) (const: obj catD): \n                                              `(Functor catC catD (fun _ => const) (fun _ _ _ => (@identity catD const))).\nProof. refine(@mk_Functor\n               catC\n               catD _ _ _ _\n             ).\n       intros. reflexivity.\n       intros. simpl. rewrite identity_f; reflexivity.\nDefined.\nCheck Constant_Functor.\n\n(* obligated fmap *)\n\nClass Functor2 `(catC: Category) `(catD: Category) (F: obj catC -> obj catD): Type :=\n  mk_Functor2\n  {\n    fmap2            : forall {a b: obj catC} (f: arrow catC b a), (arrow catD (F b) (F a));\n    preserve_id2     : forall {a: obj catC}, fmap2 (@identity catC a) = (@identity catD (F a));\n    preserve_comp2   : forall {a b c: obj catC} (f: arrow catC b a) (g : arrow catC c b), fmap2 (g o f) = (fmap2 g) o (fmap2 f)\n  }.\nCheck Functor2.\n\n(*\nProgram Instance IdentityFunctor2 (catC: Category): \n   (@Functor2 catC catC (fun a => id a)).\nCheck IdentityFunctor2.\n*)\n\nDefinition Opposite_Functor2 (catC: Category) `(catD: Category) \n                             (F: obj catC -> obj catD)\n                             (FunctF: Functor2 catC catD F ): (Functor2 (Dual_Category catC) (Dual_Category catD) F).\nProof. refine (@mk_Functor2\n                (Dual_Category catC)\n                (Dual_Category catD)\n                F\n                (fun a b => (@fmap2 catC catD F FunctF b a))\n                (fun a => (@preserve_id2 catC catD F FunctF a)) \n                (fun a b c f g => (@preserve_comp2 catC catD F FunctF c b a g f))).\nQed. \nCheck Opposite_Functor2.\n\nDefinition Opposite_Opposite_Functor2 (catC: Category) (catD: Category) \n                                     (F: obj (Dual_Category catC) -> obj (Dual_Category catD))\n                                     (FunctF: Functor2 (Dual_Category catC) (Dual_Category catD) F): (Functor2 catC catD F).\nProof. refine (@mk_Functor2\n                catC \n                catD\n                F\n                (fun a b => (@fmap2 (Dual_Category catC) (Dual_Category catD) F FunctF b a))\n                (fun a => (@preserve_id2 (Dual_Category catC) (Dual_Category catD) F FunctF a)) \n                (fun a b c f g => (@preserve_comp2 (Dual_Category catC) (Dual_Category catD) F FunctF c b a g f))\n              ).\nDefined.\nCheck Opposite_Opposite_Functor2.\n\n(**functors compose**)\nDefinition Compose_Functors2 (catC catD catE: Category) (F: obj catC -> obj catD) (G: obj catD -> obj catE) \n                             (FunctF : @Functor2 catC catD F) \n                             (FunctG : @Functor2 catD catE G): (@Functor2 catC catE (@comp_obj_FG catC catD catE F G)).\nProof. refine (@mk_Functor2\n                catC\n                catE\n                (fun a => G (F a))\n                (fun a b f => ((@fmap2 catD catE G FunctG _ _ (@fmap2 catC catD F FunctF a b f))))\n                _ _ ).\n      - intros. destruct catC, catD, catE, FunctF, FunctG. simpl in *.\n        specialize (preserve_id4 (F a)). rewrite <- preserve_id4. rewrite preserve_id3. reflexivity.\n      - intros. destruct catC, catD, catE, FunctF, FunctG. simpl in *.\n        rewrite <- preserve_comp4. rewrite preserve_comp3. reflexivity.\nDefined.\nCheck Compose_Functors2.\n\nDefinition IdentityFunctor2 (catC: Category): (@Functor2 catC catC id).\nProof. refine (@mk_Functor2\n                catC\n                catC\n                id\n                (fun a b f => (@idf catC a b f))\n                _ _ ).\n        - intros. unfold idf. simpl; reflexivity.\n        - intros. unfold idf; reflexivity.\nDefined.\nCheck IdentityFunctor2.\n\n(** constant functor **)\nDefinition Constant_Functor2 (catC: Category) (catD: Category) (const: obj catD): \n                            (Functor2 catC catD (fun _ => const)).\nProof. refine(@mk_Functor2\n               catC\n               catD\n               (fun _     => const)\n               (fun _ _ _ => (@identity catD const))\n               _ _\n             ).\n       - intros. reflexivity.\n       - intros. simpl. rewrite identity_f; reflexivity.\nDefined.\nCheck Constant_Functor2.\n\nEnd Make.\n", "meta": {"author": "ekiciburak", "repo": "monads", "sha": "6e4de9f06d52f05fd4172d41a6c2db6d9239223d", "save_path": "github-repos/coq/ekiciburak-monads", "path": "github-repos/coq/ekiciburak-monads/monads-6e4de9f06d52f05fd4172d41a6c2db6d9239223d/src/functors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7049678114038445}}
{"text": "Require Import Bool.\nRequire Import List.\nRequire Import Omega.\nRequire Import Classical.\n\nFrom mathcomp\nRequire Import ssreflect.\n\nRequire Import Utility.\nRequire Import Cell.\n\nImport ListNotations.\n\nSection Concentric.\n  Open Scope Z_scope.\n  Open Scope list_scope.\n\n  Inductive CellType: Set :=\n    | White\n    | Temp\n    | Safe.\n\n  Definition c_type (s: CellState): CellType :=\n    match s with\n    | W => White\n    | s true _ | si true _ _ => Temp\n    | S | s false _ | si false _ _ => Safe\n    end.\n\n  (***** Safety *****)\n  Definition init_safe (st : State) : Prop := st 0 0 = S.\n\n  Definition t_safe (st : State) : Prop :=\n    forall (x y : Z), c_type (st x y) = Temp ->\n    ((x > 0 /\\ c_type (st (x - 1) y) = Safe) \\/\n    (x < 0 /\\ c_type (st (x + 1) y) = Safe) \\/\n    (y > 0 /\\ c_type (st x (y - 1)) = Safe) \\/\n    (y < 0 /\\ c_type (st x (y + 1)) = Safe)\n    ).\n\n  Definition s_safe (st : State) : Prop :=\n    forall (x y : Z), c_type (st x y) = Safe ->\n    ((x > 0 -> c_type (st (x - 1) y) = Safe) /\\\n    (x < 0 -> c_type (st (x + 1) y) = Safe) /\\\n    (y > 0 -> c_type (st x (y - 1)) = Safe) /\\\n    (y < 0 -> c_type (st x (y + 1)) = Safe)).\n\n  Definition i_safe (st : State) : Prop :=\n    forall (x y i : Z) (tmp alt : bool),\n    (st x y = S -> x = 0 /\\ y = 0) /\\\n    (st x y = s tmp alt ->\n    (x = 1 /\\ y = 0) \\/ (x = -1 /\\ y = 0) \\/\n    (x = 0 /\\ y = 1) \\/ (x = 0 /\\ y = -1)) /\\\n    (st x y = si tmp alt i -> i = (Z.abs x + Z.abs y - 2) mod 5).\n\n  Definition safe (st : State) : Prop :=\n    init_safe st /\\ t_safe st /\\ s_safe st /\\ i_safe st.\n  (***** Safety *****)\n\n  (***** Reachability *****)\n  CoInductive Run : Type :=\n    | RCons : State -> Run -> Run.\n\n  Definition hd (r : Run) : State := let (a, b) := r in a.\n  Definition tl (r : Run) : Run := let (a, b) := r in b.\n\n  Definition Coord := prod Z Z.\n\n  Definition map_coord\n    (st : State) (cl : list Coord) : list CellState :=\n    map (fun c : Coord => st (fst c) (snd c)) cl.\n\n  CoInductive ValidRun : Run -> Prop :=\n    | VCons : forall (st : State) (r : Run),\n        ValidRun r -> trans st (hd r) -> ValidRun (RCons st r).\n\n  Inductive InRun (st : State) (r : Run) : Prop :=\n    | Here : st = hd r -> InRun st r\n    | Further : InRun st (tl r) -> InRun st r.\n\n  Definition trans_ss\n    (cl : list Coord)\n    (ul vl : list CellState)\n    (P : State -> Prop) (* e.g. safe *)\n    : Prop :=\n    forall (st : State),\n    P st /\\ ul = map_coord st cl ->\n    exists (st' : State),\n    vl = map_coord st' cl /\\ trans st st' /\\ P st' /\\\n    (forall (x y : Z), ~In (x, y) cl -> st x y = st' x y).\n\n  Inductive trans_subset\n    (cl : list Coord)\n    (ul vl : list CellState)\n    (P : State -> Prop) (* e.g. safe *)\n    : Prop :=\n    | I : ul = vl -> trans_subset cl ul vl P\n    | V : forall (wl : list CellState), \n        trans_ss cl ul wl P ->\n        trans_subset cl wl vl P ->\n        trans_subset cl ul vl P.\n\n  Definition fair\n    (r : Run)\n    (cl : list Coord) (* i.e. list (prod Z Z) *)\n    (P : State -> Prop) (* e.g. safe *)\n    (Q : list CellState -> Prop)\n    : Prop :=\n    ValidRun r ->\n    (forall (st : State), InRun st r /\\ P st ->\n    (exists (vl : list CellState),\n    trans_subset cl (map_coord st cl) vl P /\\ Q vl)) ->\n    (exists (st' : State), InRun st' r /\\ Q (map_coord st' cl)).\n\n  Definition side_coords (n y : Z) : list Coord :=\n    [ (n, y); (n + 1, y) ].\n\n  Definition axis_coords (n : Z) : list Coord :=\n    [ (n, 1); (n, 0); (n, -1) ].\n\n  (* P *)\n  Definition SideSSCnd (ul : list Coord) (st : State) : Prop :=\n    let l := map c_type (map_coord st ul) in\n    let a := nth 0 l White in\n    a = Safe.\n\n  Inductive subset_cnd (ul : list Coord) (st : State) : Prop :=\n    | I0 : ul = [] -> subset_cnd ul st\n    | I1 : forall (x y : Z) (res : list Coord),\n        ul = (x, y) :: res ->\n        c_type (st x y) = Safe \\/ c_type (st x y) = Temp ->\n        subset_cnd res st ->\n        subset_cnd ul st.\n\n  Definition pre_cnd (ul : list Coord) (st : State) : Prop :=\n    safe st /\\ subset_cnd ul st.\n\n  (* Q *)\n  Definition side_safe (vl : list CellState) : Prop :=\n    let l := map c_type vl in\n    let a := nth 1 l White in\n    a = Safe \\/ a = Temp.\n\n  Definition axis_safe (vl : list CellState) : Prop :=\n    let l := map c_type vl in\n    nth 1 l White = Safe.\n\n  Lemma temp_imply : forall (c : CellState),\n    c_type c = Temp -> exists (alt : bool) (i : Z),\n    c = s true alt \\/ c = si true alt i.\n  Proof.\n    move=> c s0.\n    destruct c.\n    -by [].\n    -by [].\n    -exists alt.\n      destruct tmp.\n      exists 0.\n      by left.\n      by discriminate.\n    -exists alt.\n      destruct tmp.\n      exists i.\n      by right.\n      by discriminate.\n  Qed.\n\n  Definition si_temp_st\n    (st : State) (tmp alt: bool) (n m i : Z) (x y : Z) : CellState :=\n    if ((x =? n) && (y =? m)) then si tmp alt i else st x y.\n\n  Definition s_temp_st\n    (st : State) (tmp alt: bool) (n m : Z) (x y : Z) : CellState :=\n    if ((x =? n) && (y =? m)) then s tmp alt else st x y.\n  (***** Reachability *****)\n\n  Close Scope list_scope.\n  Close Scope Z_scope.\n\nEnd Concentric.\n\n", "meta": {"author": "cathesis", "repo": "verification-ca", "sha": "ba4e7128591d98832caa34f0d6863d6fb77dc90e", "save_path": "github-repos/coq/cathesis-verification-ca", "path": "github-repos/coq/cathesis-verification-ca/verification-ca-ba4e7128591d98832caa34f0d6863d6fb77dc90e/Concentric.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7049678071050663}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** ** Elementary diophantine constraints *)\n\nRequire Import List Arith Nat Omega.\nRequire Import utils_list gcd prime dio_logic.\n\nSet Implicit Arguments.\n\nSection interval.\n\n  (** A small interval & valuation library *)\n\n  Definition interval := (nat * nat)%type. (* (a,b) <~~~> [a,b[ *)\n\n  Implicit Types (i j : interval).\n\n  Definition in_interval i x := let (a,b) := i in a <= x < b.\n  Definition out_interval i x := let (a,b) := i in x < a \\/ b <= x.\n  Definition interval_disjoint i j := forall x, in_interval i x -> in_interval j x -> False.\n\n  Definition interval_union (i j : interval) :=\n    match i, j with (a1,b1),(a2,b2) => (min a1 a2, max b1 b2) end.\n\n  Fact in_out_interval i x : in_interval i x -> out_interval i x -> False.\n  Proof. destruct i; simpl; omega. Qed.\n\n  Fact in_out_interval_dec i x : { in_interval i x } + { out_interval i x }.\n  Proof. \n    destruct i as (a,b); simpl.\n    destruct (le_lt_dec a x); destruct (le_lt_dec b x); try (left; omega);right; omega.\n  Qed. \n\n  Fact interval_union_left i j x : in_interval i x -> in_interval (interval_union i j) x.\n  Proof.\n    revert i j; intros (a,b) (u,v); simpl.\n    generalize (Nat.le_min_l a u) (Nat.le_max_l b v); omega.\n  Qed.\n\n  Fact interval_union_right i j x : in_interval j x -> in_interval (interval_union i j) x.\n  Proof.\n    revert i j; intros (a,b) (u,v); simpl.\n    generalize (Nat.le_min_r a u) (Nat.le_max_r b v); omega.\n  Qed.\n\n  Definition valuation_union i1 (g1 : nat -> nat) i2 g2 : \n               interval_disjoint i1 i2 \n            -> { g | (forall x, in_interval i1 x -> g x = g1 x)\n                  /\\ (forall x, in_interval i2 x -> g x = g2 x) }.\n  Proof.\n    intros H2.\n    exists (fun x => if in_out_interval_dec i1 x then g1 x else g2 x).\n    split; intros x Hx.\n    + destruct (in_out_interval_dec i1 x) as [ | H3 ]; auto.\n      exfalso; revert Hx H3; apply in_out_interval.\n    + destruct (in_out_interval_dec i1 x) as [ H3 | ]; auto.\n      exfalso; revert H3 Hx; apply H2.\n  Qed.\n\n  Definition valuation_one_union k v i1 (g1 : nat -> nat) i2 g2 : \n               ~ in_interval (interval_union i1 i2) k \n            -> interval_disjoint i1 i2 \n            -> { g | g k = v /\\ (forall x, in_interval i1 x -> g x = g1 x)\n                             /\\ (forall x, in_interval i2 x -> g x = g2 x) }.\n  Proof.\n    intros H1 H2.\n    exists (fun x => if eq_nat_dec x k then v \n                     else if in_out_interval_dec i1 x then g1 x \n                     else g2 x).\n    split; [ | split ].\n    + destruct (eq_nat_dec k k) as [ | [] ]; auto.\n    + intros x Hx.\n      destruct (eq_nat_dec x k) as [ | ].\n      * subst; destruct H1; apply interval_union_left; auto.\n      * destruct (in_out_interval_dec i1 x) as [ | H3 ]; auto.\n        exfalso; revert Hx H3; apply in_out_interval.\n    + intros x Hx.\n      destruct (eq_nat_dec x k) as [ | ].\n      * subst; destruct H1; apply interval_union_right; auto.\n      * destruct (in_out_interval_dec i1 x) as [ H3 | ]; auto.\n        exfalso; revert H3 Hx; apply H2.\n  Qed.\n\nEnd interval.\n\nSection diophantine_system.\n\n  (* v : cst = nat      constant (natural number)\n     p q : par = nat    parameter \n     x y z : var = nat  existentially quantified variable \n   \n     equations are of 4 types \n       1) x = v \n       2) x = p \n       3) x = y + z \n       4) x = y * z \n\n     We represent a relation between parameters R by a list of equations l and one\n     variable x : var such that\n       a) for any value f : nat -> nat of the params, l[f] has a solution\n       b) for any value f : nat -> nat of the params,\n\n                R f <-> ((x=0)::l)[f] has a solution\n\n     How do we simulate poly1 = poly2 linearly ?\n\n         poly1 = (eqn1,x) where x is output\n         poly2 = (eqn2,y) where y is output\n\n         example poly1 = p*(q+r)\n         gives eqn1:= (0=1*2, 1=p, 2=3+4, 3=q, 4=r) and x:=0\n\n         then we simulate poly1 = poly2 with\n \n               poly1 = poly2 <-> (eqn1 U eqn2 U { w=y+u, w=x+v, z=u+v }, z)\n\n         where u v z w are fresh\n\n     We implement conjunction (cap), disjunction (cup) and exists so that we get a linear encoding\n\n      cap) R by (lR,xR) and S by (lS,xS) \n           we assume (lR,xR) and (lS,xS) do not share existential variables\n           (always possible by renaming those of S)\n\n           R cap S = (lR U lS U { z = x+y },z) where z is fresh\n \n      cup) R cup S = (lR U lS U { z = x*y },z)\n\n      exists) ∃n.R f{p<-n} = (lR[p<-0], ...)\n\n   *)\n\n  Inductive dio_elem_expr : Set :=\n    | dee_nat  : nat -> dio_elem_expr   (* c : constant *)\n    | dee_var  : nat -> dio_elem_expr   (* v : existentially quant. var *)\n    | dee_par  : nat -> dio_elem_expr   (* p : parameter *)\n    | dee_comp : dio_op -> nat -> nat -> dio_elem_expr. (* v1 op v2 *)\n\n  Notation dee_add := (dee_comp do_add).\n  Notation dee_mul := (dee_comp do_mul).\n\n  (* ρ σ ν φ *)\n\n  Definition dee_eval φ ν e := \n    match e with\n      | dee_nat n => n\n      | dee_var v => φ v\n      | dee_par i => ν i\n      | dee_comp o v w => do_eval o (φ v) (φ w) \n    end.\n\n  Definition dee_vars e x  :=\n    match e with\n      | dee_nat _ => False\n      | dee_var v => x = v\n      | dee_par _ => False\n      | dee_comp _ v w => x = v \\/ x = w\n    end.\n\n  Fact dee_eval_ext e φ1 ν1 φ2 ν2  : \n        (forall x, dee_vars e x -> φ1 x = φ2 x) \n     -> (forall x, ν1 x = ν2 x)\n     -> dee_eval φ1 ν1 e = dee_eval φ2 ν2 e.\n  Proof. destruct e as [ | | | [] ]; simpl; auto. Qed.\n\n  (* ρ σ ν *)\n\n  Definition dee_move k p :=\n    match p with\n      | dee_nat n      => dee_nat n\n      | dee_var v      => dee_var (k+v)\n      | dee_par i      => dee_par i\n      | dee_comp o v w => dee_comp o (k+v) (k+w)\n    end.\n\n  Fact dee_eval_move k φ ν e : dee_eval φ ν (dee_move k e) = dee_eval (fun x => φ (k+x)) ν e.\n  Proof. destruct e as [ | | | [] ]; simpl; auto. Qed.\n\n  Fact dee_vars_move k e x : dee_vars (dee_move k e) x <-> exists y, dee_vars e y /\\ x = k+y.\n  Proof. destruct e as [ | | | [] ]; simpl; firstorder. Qed.\n\n  Definition dee_dec k e :=\n    match e with\n      | dee_nat n      => dee_nat n\n      | dee_var v      => dee_var v\n      | dee_par 0      => dee_var k \n      | dee_par (S i)  => dee_par i\n      | dee_comp o v w => dee_comp o v w\n    end.\n\n  Fact dee_eval_dec φ ν k e : dee_eval φ ν (dee_dec k e) = dee_eval φ (fun x => match x with 0 => φ k | S x => ν x end) e.\n  Proof. destruct e as [ | | [] | [] ]; simpl; auto. Qed.\n\n  Fact dee_vars_dec k e x : dee_vars (dee_dec k e) x -> x = k \\/ dee_vars e x.\n  Proof. destruct e as [ | | [] | [] ]; simpl; firstorder. Qed.\n\n  Definition dio_constraint := (nat * dio_elem_expr)%type.\n\n  Implicit Type (c : dio_constraint).\n\n  Definition dc_eval φ ν c := φ (fst c) = dee_eval φ ν (snd c).\n\n  Arguments dc_eval φ ν c /.\n  \n  Definition dc_vars c x := x = fst c \\/ dee_vars (snd c) x.\n\n  Arguments dc_vars c x /.\n\n  Fact dc_eval_ext c φ1 ν1 φ2 ν2  : \n        (forall x, dc_vars c x -> φ1 x = φ2 x) \n     -> (forall x, ν1 x = ν2 x)\n     -> dc_eval φ1 ν1 c <-> dc_eval φ2 ν2 c.\n  Proof.\n    intros H1 H2.\n    destruct c as (v,e); unfold dc_eval; simpl.\n    rewrite H1; simpl; auto.\n    rewrite dee_eval_ext with e φ1 ν1 φ2 ν2; try tauto.\n    intros; apply H1; simpl; auto.\n  Qed.\n\n  Definition dc_move k c := (k+fst c, dee_move k (snd c)).\n\n  Fact dc_eval_move k φ ν c : dc_eval φ ν (dc_move k c) <-> dc_eval (fun x => φ (k+x)) ν c.\n  Proof.\n    destruct c as (v,e); simpl.\n    rewrite dee_eval_move; tauto.\n  Qed.\n\n  Fact dc_vars_move k c x : dc_vars (dc_move k c) x <-> exists y, x = k + y /\\ dc_vars c y.\n  Proof.\n    destruct c as (v,e); simpl.\n    rewrite dee_vars_move.\n    split.\n    + intros [ ? | (y & Hy & ?) ]; subst x; firstorder; exists v; auto.\n    + intros (y & ? & [ | ]); subst; firstorder.\n  Qed.\n\n  Definition dc_dec k c := (fst c, dee_dec k (snd c)).\n\n  Fact dc_eval_dec φ ν k c : dc_eval φ ν (dc_dec k c) <-> dc_eval φ  (fun x => match x with 0 => φ k | S x => ν x end) c.\n  Proof. destruct c; simpl; rewrite dee_eval_dec; tauto. Qed.\n\n  Fact dc_vars_dec k c x : dc_vars (dc_dec k c) x -> x = k \\/ dc_vars c x.\n  Proof. destruct c; simpl; intros [ | H ]; auto; apply dee_vars_dec in H; tauto. Qed.\n\n  Implicit Type (R : (nat -> nat) -> Prop).\n\n  (* A diophantine system for R is an interval i, a list l of constraints, a reference variable x\n     such that\n       1) the variables in l U {x} and belong to i\n       2) for any valuation, the equations of l are satisfiable\n       3) for any valuation ν, R ν holds iff the equations of { x=0 } U l are satisfiable\n   *)\n\n  Record dio_repr_at R a n l := {\n    ds_eqns : list dio_constraint;\n    ds_ref  : nat;\n    ds_H0   : length ds_eqns = l;\n    ds_H1   : forall x c, In c ds_eqns -> dc_vars c x -> a <= x < a+n;\n    ds_H2   : a <= ds_ref < a+n;\n    ds_H3   : forall ν, exists φ, Forall (dc_eval φ ν) ds_eqns;\n    ds_H4   : forall ν, R ν <-> exists φ, Forall (dc_eval φ ν) ds_eqns /\\ φ ds_ref = 0;\n  }.\n\n  Section diophantine_sys_expr.\n\n    (* A compiler from expressions to lists of small expressions *)\n\n    Fixpoint de_eqns e x :=\n      match e with\n        | de_cst n      => (x,dee_nat n)::nil \n        | de_var p      => (x,dee_par p)::nil\n        | de_comp o p q => (x,dee_comp o (x+1) (x+1+de_size p)) :: de_eqns p (x+1) ++ de_eqns q (x+1+de_size p)\n      end.\n\n    Fact de_eqns_length e x : length (de_eqns e x) = de_size e.\n    Proof.\n      revert x; induction e as [ | | o p Hp q Hq ]; intros x; simpl; auto.\n      rewrite app_length, Hp, Hq; auto.\n    Qed.\n\n    Fact de_size_ge_1 e : 1 <= de_size e.\n    Proof. destruct e; simpl; omega. Qed.\n\n    Fact de_eqns_vars e x : forall c, In c (de_eqns e x) -> forall y, dc_vars c y -> x <= y < x+de_size e.\n    Proof.\n      revert x; induction e as [ | | o p Hp q Hq ]; intros x; simpl; auto.\n      + intros ? [ [] | [] ]; simpl; intros; omega.\n      + intros ? [ [] | [] ]; simpl; intros; omega.\n      + intros c [ Hc | Hc ]; [ | apply in_app_or in Hc; destruct Hc as [ Hc | Hc ] ]; subst; simpl.\n        * intros; generalize (de_size_ge_1 q); intros; omega.\n        * intros y Hy; apply Hp with (y := y) in Hc; simpl in *; auto; omega.\n        * intros y Hy; apply Hq with (y := y) in Hc; simpl in *; auto; omega.\n    Qed.\n\n    (* If equations in de_eqns e x are satisfied in φ, then φ x must be equal to de_eval ν e *)\n\n    Fact dc_Forall_eval φ ν e x : Forall (dc_eval φ ν) (de_eqns e x) -> de_eval ν e = φ x.\n    Proof.\n      rewrite Forall_forall.\n      revert x; induction e as [ | v| [] p Hp q Hq ]; simpl; intros x Hx; simpl; auto.\n      * specialize (Hx (x,dee_nat n)); simpl in Hx; rewrite Hx; auto.\n      * specialize (Hx (x,dee_par v)); simpl in Hx; rewrite Hx; auto.\n      * rewrite Hp with (x+1), Hq with (x+1+de_size p).\n        - symmetry; apply (Hx (_, dee_add _ _)); auto.\n        - intros; apply Hx; right; apply in_or_app; auto.\n        - intros; apply Hx; right; apply in_or_app; auto.\n      * rewrite Hp with (x+1), Hq with (x+1+de_size p).\n        - symmetry; apply (Hx (_, dee_mul _ _)); auto.\n        - intros; apply Hx; right; apply in_or_app; auto.\n        - intros; apply Hx; right; apply in_or_app; auto.\n    Qed.\n\n    (* Converselly, equations in de_eqns e x are satisfiable *)\n\n    Fact dc_eval_exists_Forall ν e x : { φ | Forall (dc_eval φ ν) (de_eqns e x) }. \n    Proof.\n      revert x; induction e as [ | v | o p Hp q Hq ]; simpl; intros x.\n      + exists (fun  _ => n); constructor; simpl; auto.\n      + exists (fun  _ => ν v); constructor; simpl; auto.\n      + destruct (Hp (x+1)) as (g1 & H2).\n        destruct (Hq (x+1+de_size p)) as (g2 & H4).\n        generalize (dc_Forall_eval _ _ H2) (dc_Forall_eval _ _ H4); intros H1 H3.\n        destruct (@valuation_one_union x (do_eval o (de_eval ν p) (de_eval ν q)) (x+1,x+1+de_size p) g1 (x+1+de_size p, x+1+de_size p+de_size q) g2)\n           as (g & H5 & H6 & H7).\n        * simpl; rewrite Min.min_l; omega.\n        * intros y; simpl; omega.\n        * exists g; constructor.\n          - red; unfold fst, snd; rewrite H5, H1, H3; simpl; f_equal; symmetry.\n            ++ apply H6; simpl; generalize (de_size_ge_1 p); intros; omega.\n            ++ apply H7; simpl; generalize (de_size_ge_1 q); intros; omega.\n          - apply Forall_app; split.\n            ++ revert H2; do 2 rewrite Forall_forall.\n               intros H c Hc.\n               generalize (H _ Hc); apply dc_eval_ext; auto.\n               intros y Hy; apply H6.\n               apply de_eqns_vars with (1 := Hc); auto.\n            ++ revert H4; do 2 rewrite Forall_forall.\n               intros H c Hc.\n               generalize (H _ Hc); apply dc_eval_ext; auto.\n               intros y Hy; apply H7.\n               apply de_eqns_vars with (1 := Hc); auto.\n    Qed.\n\n    Let compare_lemma x y : { u : nat & { v | u+x = v+y } }.\n    Proof.\n      destruct (le_lt_dec x y).\n      + exists (y-x), 0; omega.\n      + exists 0, (x-y); omega.\n    Qed.\n\n    (* poly1 = poly2 <-> (eqn1 U eqn2 U { w=x+u, w=y+v, z=u+v }, z) *)\n\n    Let g0 (n x0 x1 x2 x3 m : nat) := if le_lt_dec n m then \n                                match m - n with\n                                  | 0 => x0\n                                  | 1 => x1\n                                  | 2 => x2\n                                  | _ => x3\n                                end\n                              else x3.\n\n    Let g0_0 (n x0 x1 x2 x3 : nat) : g0 n x0 x1 x2 x3 n = x0.\n    Proof. \n      unfold g0; destruct (le_lt_dec n n); try omega.\n      replace (n-n) with 0 by omega; auto.\n    Qed.\n\n    Let g0_1 (n x0 x1 x2 x3 : nat) : g0 n x0 x1 x2 x3 (n+1) = x1.\n    Proof. \n      unfold g0; destruct (le_lt_dec n (n+1)); try omega.\n      replace (n+1-n) with 1 by omega; auto.\n    Qed.\n\n    Let g0_2 (n x0 x1 x2 x3 : nat) : g0 n x0 x1 x2 x3 (n+2) = x2.\n    Proof. \n      unfold g0; destruct (le_lt_dec n (n+2)); try omega.\n      replace (n+2-n) with 2 by omega; auto.\n    Qed.\n\n    Let g0_3 (n x0 x1 x2 x3 : nat) : g0 n x0 x1 x2 x3 (n+3) = x3.\n    Proof. \n      unfold g0; destruct (le_lt_dec n (n+3)); try omega.\n      replace (n+3-n) with 3 by omega; auto.\n    Qed.\n\n    (* x1+(x2*5) at 4 ~~> v4 = v5 + v6, v5 = x1, v6 = v7 * v8, v7 = x2, v8 = 5\n       x3 at 9        ~~> v9 = x3\n\n       x1+(x2*5) = x3 at 0\n                      ~~> v3 = v1 + v4, v3 = v2 + v9, v0 = v1 + v2\n    *)\n\n    Lemma dio_repr_at_eq n e1 e2 : dio_repr_at (fun ν => de_eval ν e1 = de_eval ν e2) n (4+de_size e1+de_size e2) (3+de_size e1+de_size e2).\n    Proof.\n      exists ((n+3, dee_add (n+1) (n+4)) ::\n              (n+3, dee_add (n+2) (n+4+de_size e1)) ::\n              (n,   dee_add (n+1) (n+2)) ::\n              (de_eqns e1 (n+4) ++ de_eqns e2 (n+4+de_size e1))) n.\n      + simpl; rewrite app_length; do 2 rewrite de_eqns_length; auto.\n      + intros x c [ Hc | [ Hc | [ Hc | Hc ] ] ].\n        * subst; simpl; generalize (de_size_ge_1 e2); omega.\n        * subst; simpl; generalize (de_size_ge_1 e2); omega.\n        * subst; simpl; generalize (de_size_ge_1 e2); omega.\n        * intros Hx; apply in_app_or in Hc.\n          destruct Hc as [ Hc | Hc ]; apply de_eqns_vars with (2 := Hx) in Hc;\n             simpl in *; omega.\n      + simpl; omega.\n      + intros f.\n        destruct (@dc_eval_exists_Forall f e1 (n+4)) as (g1 & H2).\n        destruct (@dc_eval_exists_Forall f e2 (n+4+de_size e1)) as (g2 & H4).\n        destruct (compare_lemma (g1 (n+4)) (g2 (n+4+de_size e1))) as (u & v & Huv).\n        set (g3 := g0 n (u+v) u v (u+g1 (n+4))).\n        destruct (@valuation_union (n+4, n+4+de_size e1) g1 (n+4+de_size e1, n+4+de_size e1+de_size e2) g2)\n           as (g4 & H5 & H6).\n        { intro; simpl; omega. }\n        destruct (@valuation_union (n,n+4) g3 (n+4,n+4+de_size e1+de_size e2) g4) \n           as (g & H7 & H8).\n        { intro; simpl; omega. }\n        generalize (de_size_ge_1 e1) (de_size_ge_1 e2); intros E1 E2.\n        exists g; repeat constructor; simpl.\n        * rewrite H7, H7; simpl; auto; try omega.\n          rewrite H8; simpl; try omega.\n          rewrite H5; simpl; try omega.\n          unfold g3; rewrite g0_1, g0_3; omega.\n        * rewrite H7, H7; simpl; auto; try omega.\n          rewrite H8; simpl; try omega.\n          rewrite H6; simpl; auto; try omega.\n          unfold g3; rewrite g0_2, g0_3; omega.\n        * rewrite H7, H7, H7; simpl; try omega.\n          unfold g3; rewrite g0_0, g0_1, g0_2; auto.\n        * apply Forall_app; split.\n          - revert H2; do 2 rewrite Forall_forall.\n            intros H c Hc; generalize (H _ Hc).\n            apply dc_eval_ext; auto.\n            intros x Hx; rewrite H8.\n            ++ apply H5, de_eqns_vars with (1 := Hc); auto.\n            ++ apply de_eqns_vars with (1 := Hc) in Hx.\n               simpl in *; omega.\n          - revert H4; do 2 rewrite Forall_forall.\n            intros H c Hc; generalize (H _ Hc).\n            apply dc_eval_ext; auto.\n            intros x Hx; rewrite H8.\n            ++ apply H6, de_eqns_vars with (1 := Hc); auto.\n            ++ apply de_eqns_vars with (1 := Hc) in Hx.\n               simpl in *; omega.\n      + intros f; split.\n        * intros Hf.\n          destruct (@dc_eval_exists_Forall f e1 (n+4)) as (g1 & H2).\n          destruct (@dc_eval_exists_Forall f e2 (n+4+de_size e1)) as (g2 & H4).\n          generalize (dc_Forall_eval _ _ H2) (dc_Forall_eval _ _ H4); intros H1 H3.\n          set (g3 := g0 n 0 0 0 (de_eval f e1)).\n          destruct (@valuation_union (n+4, n+4+de_size e1) g1 (n+4+de_size e1, n+4+de_size e1+de_size e2) g2)\n             as (g4 & H5 & H6).\n          { intro; simpl; omega. }\n          destruct (@valuation_union (n, n+4) g3 (n+4, n+4+de_size e1+de_size e2) g4) \n            as (g & H7 & H8).\n          { intro; simpl; omega. }\n          generalize (de_size_ge_1 e1) (de_size_ge_1 e2); intros E1 E2.\n          exists g; repeat constructor; simpl.\n          - rewrite H7, H7; simpl; auto; try omega.\n            rewrite H8; simpl; try omega.\n            rewrite H5; simpl; try omega.\n            unfold g3; rewrite g0_3, g0_1; omega.\n          - rewrite H7, H7; simpl; auto; try omega.\n            rewrite H8; simpl; try omega.\n            unfold g3; rewrite g0_3, g0_2.\n            rewrite Hf, H6; simpl; auto; omega.\n          - rewrite H7, H7, H7; simpl; try omega.\n            unfold g3; rewrite g0_0, g0_1, g0_2; auto.\n          - apply Forall_app; split.\n            ++ revert H2; do 2 rewrite Forall_forall.\n               intros H c Hc; generalize (H _ Hc).\n               apply dc_eval_ext; auto.\n               intros x Hx; rewrite H8.\n               ** apply H5, de_eqns_vars with (1 := Hc); auto.\n               ** apply de_eqns_vars with (1 := Hc) in Hx.\n                  simpl in *; omega.\n            ++ revert H4; do 2 rewrite Forall_forall.\n               intros H c Hc; generalize (H _ Hc).\n               apply dc_eval_ext; auto.\n               intros x Hx; rewrite H8.\n               ** apply H6, de_eqns_vars with (1 := Hc); auto.\n               ** apply de_eqns_vars with (1 := Hc) in Hx.\n                  simpl in *; omega.\n          - rewrite H7; simpl; try omega.\n            unfold g3; rewrite g0_0; auto.\n        * intros (g & H1 & H0).\n          do 3 rewrite Forall_cons_inv in H1.\n          rewrite Forall_app in H1.\n          destruct H1 as (H1 & H2 & H3 & H4 & H5).\n          simpl in *.\n          rewrite dc_Forall_eval with (1 := H4).\n          rewrite dc_Forall_eval with (1 := H5).\n          omega.\n    Defined.\n\n  End diophantine_sys_expr.\n\n  Let not_interval_union a1 n1 a2 n2 : \n           a1+n1 <= a2\n        -> ~ in_interval (interval_union (a1, a1 + n1) (a2, a2 + n2)) (a2 + n2).\n  Proof.\n    simpl; intros H1 (_ & H3).\n    rewrite Nat.max_r in H3; omega.\n  Qed.\n\n  Lemma dio_repr_at_conj R1 a1 n1 p1 R2 a2 n2 p2 n : \n          dio_repr_at R1 a1 n1 p1\n       -> dio_repr_at R2 a2 n2 p2\n       -> a1+n1 <= a2\n       -> n = 1+a2+n2-a1\n       -> dio_repr_at (fun ν => R1 ν /\\ R2 ν) a1 n (1+p1+p2).\n  Proof.\n    intros [ l1 r1 F0 F1 F2 F3 F4 ] [ l2 r2 G0 G1 G2 G3 G4 ] H12 ?; subst n.\n    exists ((a2+n2,dee_add r1 r2)::l1++l2) (a2+n2).\n    + simpl; rewrite app_length, F0, G0; omega.\n    + replace (a1+(1+a2+n2-a1)) with (1+a2+n2) by omega.\n      intros x c [ Hc | Hc ].\n      * subst; simpl; omega.\n      * intros H1; apply in_app_or in Hc; destruct Hc as [ Hc | Hc ].\n        - specialize (F1 _ _ Hc H1); omega.\n        - specialize (G1 _ _ Hc H1); omega.\n    + omega.\n    + intros f.\n      destruct (F3 f) as (g1 & H1).\n      destruct (G3 f) as (g2 & H2).\n      destruct (@valuation_one_union (a2+n2) (g1 r1+g2 r2) (a1,a1+n1) g1 (a2,a2+n2) g2) \n        as (g & Hg1 & Hg2 & Hg3); auto.\n      { red; simpl; intros; omega. }\n      exists g; constructor; [ | apply Forall_app; split ].\n      * simpl; rewrite (Hg2 r1), (Hg3 r2); auto.\n      * apply Forall_impl with (2 := H1).\n        intros c Hc; apply dc_eval_ext; auto.\n        intros x Hx; apply Hg2, F1 with c; auto.\n      * apply Forall_impl with (2 := H2).\n        intros c Hc; apply dc_eval_ext; auto.\n        intros x Hx; apply Hg3, G1 with c; auto.\n    + intros f; rewrite F4, G4; split.\n      * intros ((g1 & H1 & H2) & (g2 & H3 & H4)).\n        destruct (@valuation_one_union (a2+n2) 0 (a1,a1+n1) g1 (a2,a2+n2) g2) \n          as (g & Hg1 & Hg2 & Hg3); auto.\n        { red; simpl; intros; omega. }\n        exists g; split; auto; constructor; simpl.\n        ++ rewrite Hg1, Hg2, Hg3; auto; omega.\n        ++ apply Forall_app; split.\n           ** apply Forall_impl with (2 := H1).\n              intros c Hc; apply dc_eval_ext; auto.\n              intros x Hx; apply Hg2, F1 with c; auto.\n           ** apply Forall_impl with (2 := H3).\n              intros c Hc; apply dc_eval_ext; auto.\n              intros x Hx; apply Hg3, G1 with c; auto.\n      * intros (g & Hg1 & Hg2).\n        inversion Hg1 as [ | ? ? Hg3 Hg4 ].\n        apply Forall_app in Hg4; destruct Hg4 as (Hg4 & Hg5).\n        simpl in Hg3; split; exists g; split; auto; omega.\n  Defined.\n\n  Lemma dio_repr_at_disj R1 a1 n1 p1 R2 a2 n2 p2 n : \n          dio_repr_at R1 a1 n1 p1\n       -> dio_repr_at R2 a2 n2 p2\n       -> a1+n1 <= a2\n       -> n = 1+a2+n2-a1\n       -> dio_repr_at (fun ν => R1 ν \\/ R2 ν) a1 n (1+p1+p2). \n  Proof.\n    intros [ l1 r1 F0 F1 F2 F3 F4 ] [ l2 r2 G0 G1 G2 G3 G4 ] H12 ?; subst n.\n    exists ((a2+n2,dee_mul r1 r2)::l1++l2) (a2+n2).\n    + simpl; rewrite app_length, F0, G0; omega.\n    + replace (a1+(1+a2+n2-a1)) with (1+a2+n2) by omega.\n      intros x c [ Hc | Hc ].\n      * subst; simpl; omega.\n      * intros H1; apply in_app_or in Hc; destruct Hc as [ Hc | Hc ].\n        - specialize (F1 _ _ Hc H1); omega.\n        - specialize (G1 _ _ Hc H1); omega.\n    + omega.\n    + intros f.\n      destruct (F3 f) as (g1 & H1).\n      destruct (G3 f) as (g2 & H2).\n      destruct (@valuation_one_union (a2+n2) (g1 r1*g2 r2) (a1,a1+n1) g1 (a2,a2+n2) g2) \n        as (g & Hg1 & Hg2 & Hg3); auto.\n      { red; simpl; intros; omega. }\n      exists g; constructor; [ | apply Forall_app; split ].\n      * simpl; rewrite (Hg2 r1), (Hg3 r2); auto.\n      * apply Forall_impl with (2 := H1).\n        intros c Hc; apply dc_eval_ext; auto.\n        intros x Hx; apply Hg2, F1 with c; auto.\n      * apply Forall_impl with (2 := H2).\n        intros c Hc; apply dc_eval_ext; auto.\n        intros x Hx; apply Hg3, G1 with c; auto.\n    + intros f; rewrite F4, G4; split.\n      * intros [ (g1 & H1 & H2) | (g2 & H1 & H2) ].\n        - destruct (G3 f) as (g2 & H3).\n          destruct (@valuation_one_union (a2+n2) 0 (a1,a1+n1) g1 (a2,a2+n2) g2) \n            as (g & Hg1 & Hg2 & Hg3); auto.\n          { red; simpl; intros; omega. }\n          exists g; split; auto.\n          constructor; simpl; [ | apply Forall_app; split ].\n          ++ rewrite Hg1, Hg2, H2; auto.\n          ++ apply Forall_impl with (2 := H1).\n             intros c Hc; apply dc_eval_ext; auto.\n             intros x Hx; apply Hg2, F1 with c; auto.\n          ++ apply Forall_impl with (2 := H3).\n             intros c Hc; apply dc_eval_ext; auto.\n             intros x Hx; apply Hg3, G1 with c; auto.\n        - destruct (F3 f) as (g1 & H3).\n          destruct (@valuation_one_union (a2+n2) 0 (a1,a1+n1) g1 (a2,a2+n2) g2) \n            as (g & Hg1 & Hg2 & Hg3); auto.\n          { red; simpl; intros; omega. }\n          exists g; split; auto.\n          constructor; simpl; [ | apply Forall_app; split ].\n          ++ rewrite Hg1, (Hg3 r2), H2, mult_comm; auto.\n          ++ apply Forall_impl with (2 := H3).\n             intros c Hc; apply dc_eval_ext; auto.\n             intros x Hx; apply Hg2, F1 with c; auto.\n          ++ apply Forall_impl with (2 := H1).\n             intros c Hc; apply dc_eval_ext; auto.\n             intros x Hx; apply Hg3, G1 with c; auto.\n      * intros (g & Hg1 & Hg2).\n        inversion Hg1 as [ | ? ? Hg3 Hg4 ].\n        apply Forall_app in Hg4; destruct Hg4 as (Hg4 & Hg5).\n        simpl in Hg3; rewrite Hg2 in Hg3.\n        symmetry in Hg3; apply mult_is_O in Hg3.\n        destruct Hg3 as [ Hg3 | Hg3 ]; [ left | right ]; exists g; auto.\n  Defined.\n\n  Lemma dio_repr_at_exst R a n m p : \n          dio_repr_at R a n p\n       -> m = n+1\n       -> dio_repr_at (fun ν => exists n, R (dv_lift ν n)) a m p. \n  Proof.\n    intros [ l r F0 F1 F2 F3 F4 ] ?; subst m.\n    exists (map (dc_dec (a+n)) l) r.\n    + rewrite map_length; auto.\n    + intros x c'; rewrite in_map_iff.\n      intros (c & E & Hc) H; subst.\n      apply dc_vars_dec in H.\n      destruct H as [ | H ]; subst; simpl; try omega.\n      apply F1 in H; simpl in *; auto; omega.\n    + omega.\n    + intros f.\n      destruct (F3 (fun x => match x with 0 => 0 | S x => f x end)) as (g & Hg).\n      exists (fun x => if eq_nat_dec x (a+n) then 0 else g x).\n      rewrite Forall_map.\n      apply Forall_impl with (2 := Hg). \n      intros c Hc; rewrite dc_eval_dec; apply dc_eval_ext; auto.\n      * intros x Hx.\n        destruct (eq_nat_dec x (a+n)); subst; auto.\n        apply F1 in Hx; auto; omega.\n      * intros [ | x ]; auto.\n        destruct (eq_nat_dec (a+n) (a+n)); tauto.\n    + intros f; split.\n      * intros (u & Hu).\n        apply F4 in Hu.\n        destruct Hu as (g & H1 & H2).\n        exists (fun x => if eq_nat_dec x (a+n) then u else g x); simpl; split.\n        - rewrite Forall_map.\n          apply Forall_impl with (2 := H1).\n          intros c Hc; rewrite dc_eval_dec; apply dc_eval_ext; auto.\n          ++ intros x Hx.\n             destruct (eq_nat_dec x (a+n)); auto.\n             subst x; apply F1 in Hx; auto; omega.\n          ++ intros [ | x ]; auto.\n             destruct (eq_nat_dec (a+n) (a+n)); tauto.\n        - destruct (eq_nat_dec r (a+n)); auto.\n          subst; omega.\n      * intros (g & H1 & H2).\n        exists (g (a+n)); rewrite F4.\n        exists g; split; auto.\n        revert H1; do 2 rewrite Forall_forall.\n        intros H c Hc.\n        apply in_map with (f := dc_dec _), H in Hc.\n        revert Hc; rewrite dc_eval_dec; apply dc_eval_ext; auto.\n  Defined.\n\n  Fixpoint df_weight_1 f :=\n    match f with\n      | df_atm a b  => 4 + de_size a + de_size b\n      | df_conj f g => 1 + df_weight_1 f + df_weight_1 g  \n      | df_disj f g => 1 + df_weight_1 f + df_weight_1 g  \n      | df_exst f   => 1 + df_weight_1 f\n    end.\n\n  Fact df_weigth_1_size f : df_weight_1 f <= 4*df_size f.\n  Proof. induction f; simpl; omega. Qed.\n\n  Fixpoint df_weight_2 f :=\n    match f with\n      | df_atm a b  => 3 + de_size a + de_size b\n      | df_conj f g => 1 + df_weight_2 f + df_weight_2 g  \n      | df_disj f g => 1 + df_weight_2 f + df_weight_2 g  \n      | df_exst f   => df_weight_2 f\n    end.\n\n  Fact df_weigth_2_size f : df_weight_2 f <= 3*df_size f.\n  Proof. induction f; simpl in *; omega. Qed.\n\n  Lemma dio_repr_at_form n f : dio_repr_at (df_pred f) n (df_weight_1 f) (df_weight_2 f).\n  Proof.\n    revert n;\n    induction f as [ a b | f IHf g IHg | f IHf g IHg | f IHf ]; intros n; simpl df_pred; simpl df_weight_1; simpl df_weight_2.\n    + apply dio_repr_at_eq.\n    + apply dio_repr_at_conj with (n1 := df_weight_1 f) (a2 := n+df_weight_1 f) (n2 := df_weight_1 g); auto; omega.\n    + apply dio_repr_at_disj with (n1 := df_weight_1 f) (a2 := n+df_weight_1 f) (n2 := df_weight_1 g); auto; omega.\n    + apply dio_repr_at_exst with (n := df_weight_1 f); auto; omega.\n  Defined.\n\n  (** For any diophantine logic formula f of size s, one can compute a list l \n      of at most 1+3*s elementary diophantine constraints, containing at \n      most 4*s variables and such that df_pred f ν is equivalent to \n      the simultaneous satisfiability at ν of all the elementary constraints in l *)\n\n  Theorem dio_formula_elem f : { l | length l <= 1+3*df_size f\n                                 /\\ (forall c x, In c l -> dc_vars c x -> x < 4*df_size f)  \n                                 /\\  forall ν, df_pred f ν <-> exists φ, Forall (dc_eval φ ν) l }.\n  Proof.\n    destruct (dio_repr_at_form 0 f) as [l r H0 H1 H2 H3 H4].\n    exists ((r,dee_nat 0) :: l); split; [ | split ]; simpl length; try omega.\n    + rewrite H0; apply le_n_S, df_weigth_2_size.\n    + intros c x [ [] | H ].\n      * simpl dc_vars; intros [ | [] ]; subst.\n        generalize (df_weigth_1_size f); intros; omega.\n      * intros G; apply H1 in G; auto.\n        generalize (df_weigth_1_size f); intros; omega.\n    + intros ν; rewrite H4.\n      split; intros (φ & H); exists φ; revert H; rewrite Forall_cons_inv; simpl; tauto.\n  Defined.\n\n  Definition dio_fs f := proj1_sig (dio_formula_elem f).\n                 \nEnd diophantine_system.\n\n(* Check dio_formula_elem.\nPrint Assumptions dio_formula_elem. *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/coq-library-undecidability/H10/Dio/dio_elem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7049678049556772}}
{"text": "Require Import Lists.List.\nImport ListNotations.\n\n(** * Exercise 1: *)\n\nSection Ex1.\n\n(** Implement a datatype [Fml] of propositional formulas parameterized\nover [P : Type]. *)\n\nInductive Fml (P: Type): Type :=\n| Atom  : P -> Fml P\n| Neg   : Fml P -> Fml P\n| Or    : Fml P -> Fml P -> Fml P\n| And   : Fml P -> Fml P -> Fml P\n| Impl  : Fml P -> Fml P -> Fml P.\n\n\nEnd Ex1.\n\n(** * Exercise 2: recursion over lists *)\n\nSection Ex2.\n\nSection FoldList.\n\nVariable A X: Type.\n\n(** Define the signature functor [sigma_list] of lists as an inductive\ntype *)\n\nInductive sigma_list X :=\n| OpNil : sigma_list X\n| OpCons : A -> X -> sigma_list X.\n\nVariable alpha : sigma_list X -> X.\n\n(** Implement a function [fold_list : list A -> X] *)\n\nFixpoint fold_list (l: list A): X :=\n  match l with\n  | [] => alpha (OpNil _)\n  | a :: xs => alpha (OpCons _ a (fold_list xs))\n  end.\n\nEnd FoldList.\n\nCheck fold_right.\n\n(** Implement a function [length : list A -> nat] using [fold_list] *)\n\nDefinition length {A} :=\n  fold_list A nat (fun xs => match xs with\n                        | OpNil => 0\n                        | OpCons _ n => S n\n                        end).\n\nCompute (length (1 :: 2 :: 3 :: 4 :: [])).\n\nEnd Ex2.\n\n(** * Exercise 3: recursion over trees *)\n\nSection Ex3. \n\nInductive tree : Type := \n| Leaf : tree\n| Node : nat -> tree -> tree -> tree.\n\nInductive sigma_tree (X: Type): Type := \n| OpLeaf : sigma_tree X\n| OpNode : nat -> X -> X -> sigma_tree X.\n\nSection FoldTree.\n\nVariable X: Type.\nVariable alpha : sigma_tree X -> X.\n\n(** Implement a function [fold_tree : tree -> X] *)\n\nFixpoint fold_tree (t: tree): X := \n    match t with\n  | Leaf => alpha (OpLeaf _)\n  | Node n l r => alpha (OpNode _ n (fold_tree l) \n                                   (fold_tree r))\n  end.\n\nEnd FoldTree.\n\nCheck fold_tree.\n\n(** Implement a function [height : tree -> nat] that computes the\nmaximal height of a tree *)\n\nDefinition height :=\n  fold_tree nat\n            (fun xs => match xs with\n                    | OpLeaf => 0\n                    | OpNode _ lh rh => 1 + max lh rh\n                    end).\n\n\nCompute (height (Node 3 (Node 0 Leaf Leaf) (Node 1 (Node 2 Leaf Leaf) Leaf))).\n\nEnd Ex3.\n\n(** * Exercise 4: Initial algebra semantics *)\n\nSection Ex4.\n\n(** Implement [out_tree : tree -> sigma_tree tree] *)\n\nDefinition out_tree (t: tree): sigma_tree tree :=\n  match t with\n  | Leaf => OpLeaf _\n  | Node n l r => OpNode _ n l r\n  end.\n\n(** Implement the functorial map [sigma_tree_map : (X -> Y) ->\nsigma_tree X -> sigma_tree Y] *)\n\nDefinition sigma_tree_map {X Y} (f: X -> Y)\n           (xs: sigma_tree X): sigma_tree Y := \n  match xs with\n  | OpLeaf => OpLeaf _\n  | OpNode n l r => OpNode _ n (f l) (f r)\n  end.\n\nEnd Ex4.\n\n(** * Exercise 5: Uniform induction over natural numbers *)\n\nSection Ex5.\n\nHypothesis P: nat -> Type.\n\nInductive sigma_ind_nat: nat -> Type :=\n| OpIndZ : \n    sigma_ind_nat 0\n| OpIndS: forall n,\n    P n -> sigma_ind_nat (S n).\n\nFixpoint nat_rect' \n         (IH: forall n, sigma_ind_nat n -> P n)\n         (n: nat): P n :=\n  match n with\n  | 0 => IH 0 OpIndZ\n  | S n => IH (S n) (OpIndS n (nat_rect' IH n))\n  end.\n\nEnd Ex5.\n\n(** * Exercise 6: recursion from induction *)\n\nSection Ex6.\n\nSection FoldTree'.\n\nVariable X : Type.\nVariable alpha : sigma_tree X -> X.\n\n(** Implement [fold_tree' : tree -> X] from [tree_rect] *)\n\nDefinition fold_tree' : tree -> X\n  := @tree_rect (fun _ => X) \n                (alpha (OpLeaf _)) \n                (fun n l xl r xr => alpha (OpNode _ n xl xr)).\n\nEnd FoldTree'.\n\n(** Reimplement [height : tree -> nat] using this [fold_tree'] *)\n\nDefinition height' :=\n  fold_tree' nat \n            (fun xs => match xs with\n                    | OpLeaf => 0\n                    | OpNode _ lh rh => 1 + max lh rh\n                    end).\n\n\nCompute (height' (Node 3 (Node 0 Leaf Leaf) (Node 1 (Node 2 Leaf Leaf) Leaf))).\n\nEnd Ex6.\n\n(** * Exercise 7: induction over tree *)\n\nSection Ex7.\n\n(** Implement the uniform induction principle over trees *)\n\nSection TreeRect.\n\nHypothesis P: tree -> Type.\n\nInductive sigma_ind_tree: tree -> Type :=\n| OpIndLeaf : \n    sigma_ind_tree Leaf\n| OpIndNode : forall n l r,\n    P l -> P r -> sigma_ind_tree (Node n l r).\n\nFixpoint tree_rect'\n         (IH: forall t, sigma_ind_tree t -> P t)\n         (t : tree): P t := \n  match t with\n  | Leaf => IH Leaf OpIndLeaf\n  | Node n l r => IH (Node n l r)\n                    (OpIndNode n l r\n                               (tree_rect' IH l) \n                               (tree_rect' IH r))\n  end.\n\nEnd TreeRect.\n\nSection Ex7.\n\n(** * Exercise 8: induction over rose trees *)\n\nSection Ex8.\n\nInductive rosetree :=\n| rosenode : nat -> list rosetree -> rosetree.\n\n(** Implement induction over [rosetree] *)\n\nFixpoint rosetree_ind' \n         (P: rosetree -> Prop)\n         (Pl: list rosetree -> Prop)\n         (IH1: forall n ts, Pl ts -> P (rosenode n ts))\n         (IH2: Pl [])\n         (IH3: forall t ts, P t -> Pl ts -> Pl (t :: ts))\n         (t: rosetree): P t.\ndestruct t; apply IH1.\ninduction l.\n- apply IH2.\n- apply IH3.\n  + eapply rosetree_ind'; eauto.\n  + apply IHl.\nShow Proof.\nDefined.\n\n\nEnd Ex8.", "meta": {"author": "infou012", "repo": "Verification", "sha": "14ddcb52ab106d6b5b50c2b76b64f6908491dac3", "save_path": "github-repos/coq/infou012-Verification", "path": "github-repos/coq/infou012-Verification/Verification-14ddcb52ab106d6b5b50c2b76b64f6908491dac3/c1sol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.704944647849044}}
{"text": "Require Import Coq.Unicode.Utf8.\n\nRequire Export Induction.\nRequire Export Basics.\nModule NatList.\n\n  Inductive natprod : Type :=\n  | pair : nat → nat → natprod.\n\n  Check (pair 3 4).\n\n  Notation \"( x , y )\" := (pair x y).\n\n  Definition fst (p : natprod) : nat :=\n    match p with\n    | (x,_) => x\n    end.\n\n  Compute fst (3,4).\n\n  Definition snd (p : natprod) : nat :=\n    match p with\n    | (_,y) => y\n    end.\n\n  Definition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n  Compute snd (4,5).\n\nTheorem surjective_pairing_stuck : ∀ (p : natprod),\n  p = (fst p, snd p).\nProof.\n  destruct p.\n  reflexivity.\nQed.\n\nTheorem snd_fst_is_swap : ∀ (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\n  destruct p.\n  reflexivity.\nQed.\n\nTheorem fst_swap_is_snd : ∀ (p : natprod),\n  fst (swap_pair p) = snd p.\nProof.\n  destruct p.\n  reflexivity.\nQed.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat → natlist → natlist.\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\n\nNotation \"[ ]\" := nil.\n\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint repeat (n count : nat) : natlist :=\n  match count with\n  | O => nil\n  | S count' => n :: (repeat n count')\n  end.\n\nCompute (repeat 10 42).\n\nFixpoint length (l : natlist) : nat :=\n  match l with\n  | nil => 0\n  | (_ :: xs) => 1 + (length xs)\n  end.\n\nCompute length [1; 2; 3; 4].\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | (x :: xs) => x :: (app xs l2)\n  end.\n\nNotation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\nCompute [1; 2; 3] ++ [4; 5; 6].\n\nDefinition hd (default : nat) (l : natlist) : nat :=\n  match l with\n  | nil => default\n  | (x :: xs) => x\n  end.\n\nDefinition tl (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | (x :: xs) => xs\n  end.\n\nExample test_hd1: hd 0 [1;2;3] = 1.\nProof.\n  reflexivity.\nQed.\n\nExample test_hd2: hd 0 [] = 0.\nProof.\n  reflexivity.\nQed.\n\nExample test_tl: tl [1;2;3] = [2;3].\nProof.\n  reflexivity.\nQed.\n\nFixpoint filter (l : natlist) (p : nat → bool) : natlist :=\n  match l with\n  | nil => nil\n  | (x :: xs) =>\n    match p x with\n    | true => x :: (filter xs p)\n    | false => filter xs p\n    end\n  end.\n\nCheck beq_nat 0.\n                   \nDefinition nonzeros (l : natlist) : natlist :=\n  filter l (fun (x : nat) => negb (beq_nat x 0)).\n(* I should use composition, but I dont know how *)\n\nExample test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\nProof.\n  reflexivity.\nQed.\n\nDefinition oddmembers (l : natlist) : natlist := filter l oddb.\n\nExample test_oddmembers: oddmembers [0;1;0;2;3;0;0] = [1;3].\nProof.\n  reflexivity.\nQed.\n\nDefinition countoddmembers (l : natlist) : nat := length (oddmembers l).\n\nCompute oddmembers [1;0;3;1;4;5].\n\nExample test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\nProof.\n  reflexivity.\nQed.\n\nExample test_countoddmembers2: countoddmembers [0;2;4] = 0.\nProof.\n  reflexivity.\nQed.\n\nExample test_countoddmembers3: countoddmembers nil = 0.\nProof.\n  reflexivity.\nQed.\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | (x :: xs) =>\n    match l2 with\n    | nil => 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].\nProof.\n  reflexivity.\nQed.\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\nExample test_alternate4:\n  alternate [] [20;30] = [20;30].\nProof.\n  reflexivity.\nQed.\n\nDefinition bag := natlist.\n\nFixpoint count (v : nat) (s : bag) : nat :=\n  match s with\n  | nil => 0\n  | (x :: xs) =>\n    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.\n  reflexivity.\nQed.\n\nExample test_count2: count 6 [1;2;3;1;4;1] = 0.\nProof.\n  reflexivity.\nQed.\n\nDefinition sum : bag → bag → bag := app.\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 := cons v s.\n\nExample test_add1: count 1 (add 1 [1;4;1]) = 3.\nProof.\n  reflexivity.\nQed.\n\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 (length s) - (length (filter s (fun x => negb (beq_nat x v)))) with\n  | O => false\n  | n => 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(* Exercise: 3 stars, optional (bag_more_functions)\nMuh, boring *)\n\nTheorem tl_length_pred : ∀ l : natlist,\n    pred (length l) = length (tl l).\nProof.\n  destruct l.\n  - reflexivity.\n  - reflexivity.\nQed.\n\nTheorem app_assoc : ∀ l1 l2 l3 : natlist,\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  intros l1 l2 l3.\n  induction l1 as [| n l1' IHl1'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHl1'.\n    reflexivity.\nQed.\n\nFixpoint rev (l : natlist) : natlist :=\n  match l with\n  | nil => nil\n  | (x :: xs) => (rev xs) ++ [x]\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\nTheorem app_length : ∀ l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\n  induction l1 as [|n l' IHl'].\n  - reflexivity.\n  - intros l2.\n    simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.    \n\nTheorem rev_length_firsttry : ∀ l : natlist,\n  length (rev l) = length l.\nProof.\n  induction l as [|n l' IHl'].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHl'.\n    rewrite -> app_length.\n    rewrite -> plus_comm.\n    simpl.\n    reflexivity.\nQed.\n\nTheorem app_nil_r : ∀ l : natlist,\n  l ++ [] = l.\nProof.\n  induction l as [|n l' IHl'].\n  - reflexivity.\n  - simpl.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem rev_app_distr: ∀ l1 l2 : natlist,\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  induction l1 as [|n l1' IHl1'].\n  - intros l2.\n    simpl.\n    rewrite -> app_nil_r.\n    reflexivity.\n  - intros l2.\n    simpl.\n    rewrite -> IHl1'.\n    rewrite -> app_assoc.\n    reflexivity.\nQed.\n\nTheorem rev_involutive : ∀ l : natlist,\n  rev (rev l) = l.\nProof.\n  induction l as [|n l' IHl'].\n  - reflexivity.\n  - simpl.\n    rewrite -> rev_app_distr.\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nTheorem app_assoc4 : ∀ l1 l2 l3 l4 : natlist,\n  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\nProof.\n  induction l1 as [|n l1' IHl1'].\n  - simpl.\n    intros l2 l3 l4.\n    rewrite <- app_assoc.\n    reflexivity.\n  - intros l2 l3 l4.\n    simpl.\n    rewrite -> IHl1'.\n    reflexivity.\nQed.\n\n(* TODO *) (*\nLemma nonzeros_app : ∀ l1 l2 : natlist,\n  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\nProof. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool :=\n  match l1 with\n  | nil =>\n    match l2 with\n    | nil => true\n    | _ => false\n    end\n  | (x :: xs) =>\n    match l2 with\n    | nil => false\n    | (y :: ys) =>\n      match beq_nat x y with\n      | true => beq_natlist xs ys\n      | false => false\n      end\n    end\n  end.\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 : ∀ l : natlist,\n  true = beq_natlist l l.\nProof.\n  induction l as [|n l' IHl'].\n  - reflexivity.\n  - simpl.\n    rewrite <- IHl'.\n    assert (H: beq_nat n n = true). {\n      induction n as [|n' IHn'].\n      + reflexivity.\n      + simpl.\n        rewrite -> IHn'.\n        reflexivity.\n    }\n    rewrite -> H.\n    reflexivity.\nQed.\n\n(* Boring. *)\n\n(* Exercise: 4 stars, advanced (rev_injective) *)\nTheorem rev_inj : ∀ (l1 l2 : natlist), rev l1 = rev l2 → l1 = l2.\nProof.\n  intros l1 l2 Eq.\n  assert (H: rev (rev l1) = l1). {\n    rewrite -> rev_involutive.\n    reflexivity.\n  }\n  rewrite <- H.\n  rewrite -> Eq.\n  rewrite -> rev_involutive.\n  reflexivity.\nQed.  \n\nInductive natoption : Type :=\n  | Some : nat → natoption\n  | None : natoption.\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.\n  reflexivity.\nQed.\n\nExample test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.\nProof.\n  reflexivity.\nQed.\n\nExample test_nth_error3 : nth_error [4;5;6;7] 9 = None.\nProof.\n  reflexivity.\nQed.\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(* Exercise: 2 stars (hd_error) *)\n(* Boring *)\n\nInductive id : Type :=\n| Id : nat → id.\n\nDefinition beq_id (x1 x2 : id) :=\n  match x1, x2 with\n  | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : ∀ x, true = beq_id x x.\nProof.\n  destruct x.\n  induction n as [|n' IHn'].\n  - reflexivity.\n  - rewrite -> IHn'.\n    reflexivity.\nQed.\n\nEnd NatList.\n\nModule PartialMap.\n  \n  Export NatList.\n  \n  Inductive partial_map : Type :=\n  | empty : partial_map\n  | record : id → nat → partial_map → partial_map.\n\n  Definition update (d : partial_map) (x : id) (value : nat) : partial_map :=\n    record x value d.\n\n  Fixpoint 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  Compute find (Id 2) (record (Id 1) 42 (record (Id 2) 16 empty)).\n\nTheorem update_eq :\n  ∀ (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\nTheorem update_neq :\n  ∀ (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.\n  intros H.\n  simpl.\n  rewrite -> H.\n  reflexivity.\nQed.\n\nEnd PartialMap.\n", "meta": {"author": "Fwerskaje", "repo": "notes-on-functional-programming", "sha": "d45e66129625a0dd0e2c56bfc39bcfc4ff2fcd82", "save_path": "github-repos/coq/Fwerskaje-notes-on-functional-programming", "path": "github-repos/coq/Fwerskaje-notes-on-functional-programming/notes-on-functional-programming-d45e66129625a0dd0e2c56bfc39bcfc4ff2fcd82/coq/foundations/ex3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7049446392273846}}
{"text": "\nInductive I (A : Type) (x : A) : A -> Type :=\n  refl : I A x x.\n\nArguments refl {_} _.\n\nNotation \"x = y\" := (I _ x y): type_scope.\n\nDefinition subst (A:Type) (t:A) (P : forall y:A, t = y -> Type)\n           (u : A) (p : t = u) (v:P t (refl t)) : P u p :=\n  match p with\n  | refl _ => v (* : P t (refl t) *)\n  end.\n\n\nSection subst_computation. \n\n  Variable A : Type.\n  Variable t : A.\n  Variable P : forall y:A, t = y -> Type. \n  Variable v : P t (refl t).\n  \n  Eval cbn in\n      subst A t P t (refl t) v.  \n  \nEnd subst_computation. \n\n\n\n\n\n\n\n\n\n\nInductive nat : Set :=\n  O : nat\n| S : nat -> nat.\n\n\n\nFixpoint rec (P : nat -> Type) (P0 : P O) (PS: forall n : nat, P n -> P (S n)) (n : nat) : P n :=\n  match n with\n  | O => P0\n  | S n' => PS n' (rec P P0 PS n')\n  end. \n\nSection nat_computation. \n\n  Variable n : nat. \n  Variable P : nat -> Type. \n  Variable P0 : P O.\n  Variable PS : forall n : nat, P n -> P (S n).\n  \n  Eval cbn in\n      rec P P0 PS O.\n\n  Eval cbn in\n      rec P P0 PS (S n).\n  \n  Eval cbn in\n      rec P P0 PS (S (S (S O))).\n\n\nEnd nat_computation. \n\n\nFixpoint plus (n : nat) : nat -> nat :=\n  fun m =>\n    match n with\n    | O => m\n    | S n' => S (plus n' m)\n    end. \n\nCheck (fun m => refl m) : forall m:nat, plus O m = m.\n\nFail Check (fun n => refl n) : forall n:nat, plus n O = n.\n\nDefinition ap {A B:Type} (f:A -> B) {x y:A} (p:x = y) : f x = f y\n  := match p with refl _ => refl (f x) end.\n\n\n\nFixpoint plus_O_r (n : nat) : plus n O = n :=\n  match n with\n  | O => refl O (* : plus O O = O *)\n  | S n' => ap S (plus_O_r n') (* S (plus  n' 0) = S n' *)\n  end. \n\n\n(* Alternative definition of dependent pairs  *)\n\nInductive sigma (A: Type) (B: A -> Type) : Type :=\n  | exist : forall (a:A), B a -> sigma A B. \n", "meta": {"author": "tabareau", "repo": "lmfi_hott", "sha": "4c022427055be7450f7a71a91bf6d34a6bc793ab", "save_path": "github-repos/coq/tabareau-lmfi_hott", "path": "github-repos/coq/tabareau-lmfi_hott/lmfi_hott-4c022427055be7450f7a71a91bf6d34a6bc793ab/inductive_types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7049446372114555}}
{"text": "(** %\\chapter{Inductive Reasoning in SSReflect}% *)\n\nFrom mathcomp\nRequire Import ssreflect eqtype ssrnat ssrbool ssrfun seq.\nModule SsrStyle.\n\n(** \n\nIn the rest of this lecture we will be constantly relying on a series\nof standard SSReflect modules, such as [ssrbool], [ssrnat] and\n[eqtype], which we import right away.\n\n*)\n\n\n\n(**  * Structuring the proof scripts\n\nAn important part of the proof process is keeping to an established\nproof layout, which helps to maintain the proofs readable and restore\nthe intuition driving the prover's hand.  SSReflect offers a number of\nsyntactic primitives that help to maintain such a layout, and in this\nsection we give a short overview of them. As usual, the SSReflect\nreference manual provides an exhaustive formal definition of each\nprimitive's semantics, so we will just cover the base cases here,\nhoping that the subsequent proofs will provide more intuition on\ntypical usage scenarios.\n\n** Bullets and terminators\n\n*)\n\nLemma andb_true_elim b c: b && c -> c = true.\n\nProof.\ncase: c.\n\n(** \n[[\ntrue = true\n\nsubgoal 2 (ID 15) is:\n b && false -> false = true\n]]\n*)\n\n- by case: b.\n\n(** ** Using selectors and discharging subgoals\n\nLet us restart this proof and show an alternative way to structure the\nproof script, which should account for multiple cases.\n\n*)\n\nRestart.\n\ncase: c; first by [].\n\n(**\n[[\n  b : bool\n  ============================\n   b && false -> false = true\n]]\n*)\n\nRestart.\n\ncase:c; [by [] | by case: b].\n\n(** \n\nThe script above solves the first generated goal using [by []], and\nthen solves the second one via [by case: b].\n\n*)\n\n(** ** Iteration and alternatives *)\n\nRestart.\n\nby do ![done | apply: eqxx | case: b | case: c].\n\nQed.\n\n(** * Inductive predicates that should be functions *)\n\nInductive isZero (n: nat) : Prop := IsZero of n = 0.\n\n(**\n\nNaturally, such equality can be exploited to derived paradoxes, as the\nfollowing lemma shows:\n\n*)\n\nLemma isZero_paradox: isZero 1 -> False.\nProof. by case. Qed.\n\n\n(** \n\nHowever, the equality on natural numbers is, decidable, so the very\nsame definition can be rewritten as a function employing the boolean\nequality [(==)], which will make the proofs of paradoxes even shorter\nthan they already are:\n\n*)\n\nDefinition is_zero n : bool := n == 0.\n\nLemma is_zero_paradox: is_zero 1 -> False.\nProof. done. Qed.\n\n(** \n\nThat is, instead of the unavoidable case-analysis with the first\n[Prop]-based definition, the functional definition made Coq compute\nthe result for us, deriving the falsehood automatically.\n\nThe benefits of the computable definitions become even more obvious\nwhen considering the next example, the predicate defining whether a\nnatural number is even or odd. Again, we define two versions, the\ninductive predicate and a boolean function.\n\n*)\n\nInductive evenP n : Prop :=\n  Even0 of n = 0 | EvenSS m of n = m.+2 & evenP m.\n\nFixpoint evenb n := if n is n'.+2 then evenb n' else n == 0.\n\n(** \n\nLet us now prove a simple property: that fact that [(n + 1 + n)] is\neven leads to a paradox. We first prove it for the version defined in\n[Prop].\n\n*)\n\nLemma evenP_contra n : evenP (n + 1 + n) -> False.\nProof.\nelim: n=>//[| n Hn]; first by rewrite addn0 add0n; case=>//.\n\n(** \n[[\n  n : nat\n  Hn : evenP (n + 1 + n) -> False\n  ============================\n   evenP (n.+1 + 1 + n.+1) -> False\n]]\n*)\n\nrewrite addn1 addnS addnC !addnS. \nrewrite addnC addn1 addnS in Hn.\n\n(**\n[[\n  n : nat\n  Hn : evenP (n + n).+1 -> False\n  ============================\n   evenP (n + n).+3 -> False\n]] \n*)\n\ncase=>// m /eqP.\n\n(**\n\n[[\n  n : nat\n  Hn : evenP (n + n).+1 -> False\n  m : nat\n  ============================\n   (n + n).+3 = m.+2 -> evenP m -> False\n]]\n*)\n\nby rewrite !eqSS; move/eqP=><-.\nQed.\n\n(** \n\nNow, let us take a look at the proof of the same fact, but with the\ncomputable version of the predicate [evenb].\n\n*)\n\nLemma evenb_contra n: evenb (n + 1 + n) -> False.\nProof. \nelim: n=>[|n IH] //.\n\n(** \n[[\n  n : nat\n  IH : evenb (n + 1 + n) -> False\n  ============================\n   evenb (n.+1 + 1 + n.+1) -> False\n]]\n*)\n\nby rewrite addSn addnS. \nQed.\n\n(** \n\nSometimes, though, the value \"orbits\", which can be advantageous for\nthe proofs involving [bool]-returning predicates, might require a bit\ntrickier induction hypotheses than just the statement required to be\nproved. Let us compare the two proofs of the same fact, formulated\nwith [evenP] and [evennb].\n\n*)\n\nLemma evenP_plus n m : evenP n -> evenP m -> evenP (n + m).\nProof.\nelim=>//n'; first by move=>->; rewrite add0n.\n\n(** \n\n[[\n  n : nat\n  m : nat\n  n' : nat\n  ============================\n   forall m0 : nat,\n   n' = m0.+2 ->\n   evenP m0 -> (evenP m -> evenP (m0 + m)) -> evenP m -> evenP (n' + m)\n]]\n*)\n\nmove=> m'->{n'} H1 H2 H3; rewrite addnC !addnS addnC.\n\n(**\n\n[[\n  n : nat\n  m : nat\n  m' : nat\n  H1 : evenP m'\n  H2 : evenP m -> evenP (m' + m)\n  H3 : evenP m\n  ============================\n   evenP (m' + m).+2\n]]\n\n*)\n\nCheck EvenSS.\n\n(** \n[[\nEvenSS\n     : forall n m : nat, n = m.+2 -> evenP m -> evenP n\n]]\n*)\n\napply: (EvenSS _ (m' + m))=>//.\n\n(**\n\n[[\n  n : nat\n  m : nat\n  m' : nat\n  H1 : evenP m'\n  H2 : evenP m -> evenP (m' + m)\n  H3 : evenP m\n  ============================\n   evenP (m' + m)\n]] \n\n*)\n\nby apply: H2.\n\nQed.\n\n(** \n\nIn this particular case, the resulting proof was quite\nstraightforward, thanks to the explicit equality [n = m.+2] in the\ndefinition of the [EvenSS] constructor.\n\nIn the case of the boolean specification, though, the induction should\nbe done on the natural argument itself, which makes the first attempt\nof the proof to be not entirely trivial.\n\n*)\n\nLemma evenb_plus n m : evenb n -> evenb m -> evenb (n + m).\nProof.\nelim: n=>[|n Hn]; first by rewrite add0n.\n\n(** \n[[\n  m : nat\n  n : nat\n  Hn : evenb n -> evenb m -> evenb (n + m)\n  ============================\n   evenb n.+1 -> evenb m -> evenb (n.+1 + m)\n]]\n\nThe problem now is that, if we keep building the proof by induction on\n[n] or [m], the induction hypothesis and the goal will be always\n\"mismatched\" by one, which will prevent us finishing the proof using\nthe hypothesis. \n\nThere are multiple ways to escape this vicious circle, and one of them\nis to _generalize_ the induction hypothesis. To do so, let us restart\nthe proof.\n\n*)\n\nRestart.\n\nmove: (leqnn n).\n\n(**\n\n[[\n  n : nat\n  m : nat\n  ============================\n   n <= n -> evenb n -> evenb m -> evenb (n + m)\n]]\n\nNow, we are going to proceed with the proof by _selective_ induction\non [n], such that some of its occurrences in the goal will be a\nsubject of inductive reasoning (namely, the second one), and some\nothers will be left generalized (that is, bound by a forall-quantified\nvariable). We do so by using SSReflect's tactics [elim] with explicit\n_occurrence selectors_. \n\n*)\n\nelim: n {-2}n.\n\n(** \n\n[[\n  m : nat\n  ============================\n   forall n : nat, n <= 0 -> evenb n -> evenb m -> evenb (n + m)\n\nsubgoal 2 (ID 860) is:\n forall n : nat,\n (forall n0 : nat, n0 <= n -> evenb n0 -> evenb m -> evenb (n0 + m)) ->\n forall n0 : nat, n0 <= n.+1 -> evenb n0 -> evenb m -> evenb (n0 + m)\n]]\n\nThe same effect could be achieved by using [elim: n {1 3 4}n], that\nis, indicating which occurrences of [n] _should_ be generalized,\ninstead of specifying, which ones should not (as we did by means of\n[{-2}n]).\n\n*)\n\n- by case=>//.\n\n(** \n\nFor the second goal, we first move some of the assumptions to the context.\n\n*)\n\nmove=>n Hn. \n\n(** \n[[\n  m : nat\n  n : nat\n  Hn : forall n0 : nat, n0 <= n -> evenb n0 -> evenb m -> evenb (n0 + m)\n  ============================\n   forall n0 : nat, n0 <= n.+1 -> evenb n0 -> evenb m -> evenb (n0 + m)\n]]\n\nWe then perform the case-analysis on [n0] in the goal, which results\nin two goals, one of which is automatically discharged.\n\n*)\n\ncase=>//.\n\n(** \n\n[[\n  m : nat\n  n : nat\n  Hn : forall n0 : nat, n0 <= n -> evenb n0 -> evenb m -> evenb (n0 + m)\n  ============================\n   forall n0 : nat, n0 < n.+1 -> evenb n0.+1 -> evenb m -> evenb (n0.+1 + m)\n]]\n\nDoing _one more_ case analysis will adde one more [1] to the induction\nvariable [n0], which will bring us to the desired [(.+2)]-orbit.\n\n*)\n\ncase=>// n0.\n\n(**\n[[\n  m : nat\n  n : nat\n  Hn : forall n0 : nat, n0 <= n -> evenb n0 -> evenb m -> evenb (n0 + m)\n  n0 : nat\n  ============================\n   n0.+1 < n.+1 -> evenb n0.+2 -> evenb m -> evenb (n0.+2 + m)\n]]\n\nThe only thing left to do is to tweak the top assumption (by relaxing\nthe inequality via the [ltnW] lemma), so we could apply the induction\nhypothesis [Hn].\n\n*)\n\nby move/ltnW /Hn=>//.\nQed.\n\n(** ** Eliminating assumptions with a custom induction hypothesis\n\nThe functions like [evenb], with specific value orbits, are not\nparticularly uncommon, and it is useful to understand the key\ninduction principles to reason about them. In particular, the above\ndiscussed proof could have been much more straightforward if we first\nproved a different induction principle [nat2_ind] for natural numbers.\n\n*)\n\nLemma nat2_ind (P: nat -> Prop): \n  P 0 -> P 1 -> (forall n, P n -> P (n.+2)) -> forall n, P n.\nProof.\nmove=> H0 H1 H n. \n\n(** \n[[\n  P : nat -> Prop\n  H0 : P 0\n  H1 : P 1\n  H : forall n : nat, P n -> P n.+2\n  n : nat\n  ============================\n   P n\n]]\n\nUnsurprisingly, the proof of this induction principle follows the same\npattern as the proof of [evenb_plus]---generalizing the hypothesis. In\nthis particular case, we generalize it in the way that it would\nprovide an \"impedance matcher\" between the 1-step \"default\" induction\nprinciple on natural numbers and the 2-step induction in the\nhypothesis [H]. We show that for the proof it is sufficient to\nestablish [(P n /\\ P (n.+1))]:\n\n*)\n\nsuff: (P n /\\ P (n.+1)) by case.\n\n(** \n\nThe rest of the proof proceeds by the standard induction on [n].\n\n*)\n\nby elim: n=>//n; case=> H2 H3; split=>//; last by apply: H.\nQed.\n\n(** \n\nNow, since the new induction principle [nat2_ind] exactly matches the\n2-orbit, we can directly employ it for the proof of the previous result.\n\n*)\n\nLemma evenb_plus' n m : evenb n -> evenb m -> evenb (n + m).\nProof.\nby elim/nat2_ind : n.\nQed.\n\n(** \n\nNotice that we used the version of the [elim] tactics with specific\n_elimination view_ [nat2_ind], different from the default one, which\nis possible using the view tactical [/]. In this sense, the \"standard\ninduction\" [elim: n] would be equivalent to [elim/nat_ind: n].\n\n*)\n\n(** * Inductive predicates that are hard to avoid *)\n\nInductive beautiful (n: nat) : Prop :=\n| b_0 of n = 0\n| b_3 of n = 3\n| b_5 of n = 5\n| b_sum n' m' of beautiful n' & beautiful m' & n = n' + m'.\n\n(** \n\nThe number is beautiful if it's either [0], [3], [5] or a sum of two\nbeautiful numbers. Indeed, there are many ways to decompose some\nnumbers into the sum $3 * n + 5 * n$. Encoding a function,\nwhich checks whether a number is beautiful or not, although not\nimpossible, is not entirely trivial (and, in particular, it's not\ntrivial to prove the correctness of such function with respect to the\ndefinition above). Therefore, if one decides to stick with the\npredicate definition, some operations become tedious, as, even for\nconstants the property should be _inferred_ rather than proved:\n\n*)\n\nTheorem eight_is_beautiful: beautiful 8.\nProof.\napply: (b_sum _ 3 5)=>//; first by apply: b_3. \nby apply b_5.\nQed.\n\nTheorem b_times2 n: beautiful n ->  beautiful (2 * n).\nProof.\nby move=>H; apply: (b_sum _ n n)=>//; rewrite mul2n addnn.\nQed.\n\n(** \n\nIn particular, the negation proofs become much less straightforward\nthan one would expect:\n\n*)\n\nLemma one_not_beautiful n:  n = 1 -> ~ beautiful n.\nProof.\nmove=>E H. \n\n(** \n\n[[\n  n : nat\n  E : n = 1\n  H : beautiful n\n  ============================\n   False\n]]\n*)\n\nelim: H E=>n'; do?[by move=>->].\nmove=> n1 m' _ H2 _ H4 -> {n' n}.\n\n(** \n\nNotice how the assumptions [n'] and [n] are removed from the context\n(since we don't need them any more) by enumerating them using [{n' n}]\nnotation.\n\n*)\n\ncase: n1 H2=>// n'=> H3.\nby case: n' H3=>//; case.\nQed.\n\n(** * Working with SSReflect libraries\n\nWe conclude this chapter with a short overview of a subset of the\nstandard SSReflect programming and naming policies, which will,\nhopefully, simplify the use of the libraries in a standalone\ndevelopment.\n\n** Notation and standard operation properties\n\nSSReflect's module [ssrbool] introduces convenient notation for\npredicate connectives, such as [/\\] and [\\/]. In particular, multiple\nconjunctions and disjunctions are better to be written as [[ /\\ P1, P2\n& P3]] and [[ \\/ P1, P2 | P3]], respectively, opposed to [P1 /\\ P2 /\\\nP3] and [P1 \\/ P2 \\/ P3]. The specific notation makes it more\nconvenient to use such connectives in the proofs that proceed by case\nanalysis. Compare.\n\n*)\n\nLemma conj4 P1 P2 P3 P4 : P1 /\\ P2 /\\ P3 /\\ P4 -> P3.\nProof. by case=>p1 [p2][p3]. Qed.\n\nLemma conj4' P1 P2 P3 P4 : [ /\\ P1, P2, P3 & P4] -> P3.\nProof. by case. Qed.\n\n\nLocate \"_ ^~ _\".\n(** \n[[\n\"f ^~ y\" := fun x => f x y     : fun_scope\n]]\n\nFor instance, this is how one can now express the partially applied\nfunction, which applies its argument to the list [[:: 1; 2; 3]]:\n\n*)\n\nCheck map ^~ [:: 1; 2; 3].\n\n(**\n\n[[\nmap^~ [:: 1; 2; 3]\n     : (nat -> ?2919) -> seq ?2919\n]]\n\nFinally, [ssrfun] defines a number of standard operator properties,\nsuch as commutativity, distributivity etc in the form of the\ncorrespondingly defined predicates: [commutative], [right_inverse]\netc. For example, since we have now [ssrbool] and [ssrnat] imported,\nwe can search for left-distributive operations defined in those two\nmodules (such that they come with the proofs of the corresponding\npredicates):\n\n*)\n\nSearch _ (left_distributive _).\n\n(**\n\n[[\nandb_orl  left_distributive andb orb\norb_andl  left_distributive orb andb\nandb_addl  left_distributive andb addb\naddn_maxl  left_distributive addn maxn\naddn_minl  left_distributive addn minn\n...\n]]\n*)\n\n(** ** A library for lists\n\nFor instance, properties of some of the functions, such as _list\nreversal_ are simpler to prove not by the standard \"direct\" induction\non the list structure, but rather iterating the list from its last\nelement, for which the [seq] library provides the necessary definition\nand induction principle:\n\n[[\nFixpoint rcons s z := if s is x :: s' then x :: rcons s' z else [:: z].\n]]\n\n*)\n\nCheck last_ind.\n\n(**\n\n[[\nlast_ind\n     : forall (T : Type) (P : seq T -> Type),\n       P [::] ->\n       (forall (s : seq T) (x : T), P s -> P (rcons s x)) ->\n       forall s : seq T, P s\n]]\n\nTo demonstrate the power of the library for reasoning with lists, let\nus prove the following property, known as _Dirichlet's box principle_\n(sometimes also referred to as _pigeonhole principle_).\n\n*)\n\nVariable A : eqType.\n\nFixpoint has_repeats (xs : seq A) :=\n  if xs is x :: xs' then (x \\in xs') || has_repeats xs' else false.\n\n(** \n\nThe following lemma states that for two lists [xs1] and [xs2], is the\nsize [xs2] is strictly smaller than the size of [xs1], but\nnevertheless [xs1] as a set is a subset of [xs2] then there ought to\nbe repetitions in [xs1].\n\n*)\n\nTheorem dirichlet xs1 xs2 :\n        size xs2 < size xs1 -> {subset xs1 <= xs2} -> has_repeats xs1.\nProof.\n\n(** \n\nFirst, the proof scripts initiates the induction on the structure of\nthe first, \"longer\", list [xs1], simplifying and moving to the context\nsome hypotheses in the \"step\" case (as the [nil]-case is proved\nautomatically).\n\n*)\n\nelim: xs1 xs2=>[|x xs1 IH] xs2 //= H1 H2. \n\n(**\n[[\n  x : A\n  xs1 : seq A\n  IH : forall xs2 : seq A,\n       size xs2 < size xs1 -> {subset xs1 <= xs2} -> has_repeats xs1\n  xs2 : seq A\n  H1 : size xs2 < (size xs1).+1\n  H2 : {subset x :: xs1 <= xs2}\n  ============================\n   (x \\in xs1) || has_repeats xs1\n]]\n*)\n\ncase H3: (x \\in xs1) => //=.\n(**\n[[\n  ...\n  H3 : (x \\in xs1) = false\n  ============================\n   has_repeats xs1\n]]\n*)\n\npose xs2' := filter (predC (pred1 x)) xs2.\napply: (IH xs2'); last first.\n\n(**\n[[\n  ...\n  H2 : {subset x :: xs1 <= xs2}\n  H3 : (x \\in xs1) = false\n  xs2' := [seq x <- xs2 | (predC (pred1 x)) x0] : seq A\n  ============================\n   {subset xs1 <= xs2'}\n\nsubgoal 2 (ID 5716) is:\n size xs2' < size xs1\n]]\n*)\n\n- move=>y H4; move: (H2 y); rewrite inE H4 orbT mem_filter /=.\n  by move => -> //; case: eqP H3 H4 => // ->->. \n\n(** \n\nThe second goal requires to prove the inequality, which states that\nafter removal of [x] from [xs2], the length of the resulting list\n[xs2] is smaller than the length of [xs1]. \n\n*)\n\nrewrite ltnS in H1; apply: leq_trans H1. \nrewrite -(count_predC (pred1 x) xs2) -addn1 addnC. \nrewrite /xs2' size_filter leq_add2r -has_count.\n\n(**\n[[\n  ...\n  H2 : {subset x :: xs1 <= xs2}\n  H3 : (x \\in xs1) = false\n  xs2' := [seq x <- xs2 | (predC (pred1 x)) x0] : seq A\n  ============================\n   has (pred1 x) xs2\n]]\n*)\n\nby apply/hasP; exists x=>//=; apply: H2; rewrite inE eq_refl.\nQed.\n\n\n(*******************************************************************)\n(**                     * Exercices *                              *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [Integer binary division]\n---------------------------------------------------------------------\n\nLet us define the binary division function [div2] as follows.\n*)\n\nFixpoint div2 (n: nat) := if n is p.+2 then (div2 p).+1 else 0.\n\n(** \n\nProve the following lemma directly by induction on [n], _without_\nusing the [nat2_ind] induction principle. Then prove it using\n[nat2_ind].\n\n*)\n\nLemma div2_le n: div2 n <= n.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n---------------------------------------------------------------------\nExercise [Some facts about beautiful numbers]\n---------------------------------------------------------------------\n\nProof the following theorem about beautiful numbers.\n\nHint: Choose wisely, what to build the induction on.\n*)\n\nLemma b_timesm n m: beautiful n ->  beautiful (m * n).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\n(**\n---------------------------------------------------------------------\nExercise [Gorgeous numbers]\n---------------------------------------------------------------------\n\nTo practice with proofs by induction, let us consider yet another\ninductive predicate, defining which of natural numbers are _gorgeous_.\n\n*)\n\nInductive gorgeous (n: nat) : Prop :=\n| g_0 of n = 0\n| g_plus3 m of gorgeous m & n = m + 3\n| g_plus5 m of gorgeous m & n = m + 5.\n\n(** \nProve by induction the following statements about gorgeous numbers.\n\nHint: As usual, do not hesitate to use the [Search] utility for\nfinding the necessary rewriting lemmas from the [ssrnat] module.  \n*)\n\n\nLemma gorgeous_plus13 n: gorgeous n -> gorgeous (n + 13).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma beautiful_gorgeous (n: nat) : beautiful n -> gorgeous n.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma g_times2 (n: nat): gorgeous n -> gorgeous (n * 2).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma gorgeous_beautiful (n: nat) : gorgeous n -> beautiful n.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\n(** \n---------------------------------------------------------------------\nExercise [Gorgeous reflection]\n---------------------------------------------------------------------\n\nGorgeous and beautiful numbers, defining, in fact, exactly the same\nsubset of [nat] are a particular case of Frobenius coin problem, which\nasks for the largest integer amount of money, that cannot be obtained\nusing only coins of specified denominations.  In the case of\n[beautiful] and [gorgeous] numbers we have two denominations\navailable, namely 3 and 5. An explicit formula exists for the case\nof only two denominations n_1 and n_2, which allows one to compute\nthe Frobenius number as \n\ng(n_1, n_2) = n_1 * n_2 - n_1 - n_2. \n\nThat said, for the case n_1 = 3 and n_2 = 5 the Frobenius number is 7,\nwhich means that all numbers greater or equal than 8 are in fact\nbeautiful and gorgeous (since the two are equivalent, as was\nestablished by the previous exercise).\n\nIn this exercise, we suggest the reader to prove that the efficient\nprocedure of \"checking\" for gorgeousness is in fact correct. First,\nlet us defined the following candidate function.\n\n*)\n\nFixpoint gorgeous_b n : bool := match n with \n | 1 | 2 | 4 | 7 => false\n | _ => true\n end. \n\n(** \n\nThe ultimate goal of this exercise is to prove the proposition\n[reflect (gorgeous n) (gorgeous_b n)], which would mean that the two\nrepresentations are equivalent. Let us divide the proof into two\nstages:\n\n- The first stage is proving that all numbers greater or equal than\n  8 are gorgeous. To prove thism it might be useful to have the\n  following two facts established:\n\nHint: Use the tactic [constructor i] to prove a goal, which is an\nn-ary disjunction, which is satisfied if its i-th disjunct is true.\n\n*)\n\nLemma repr3 n : n >= 8 -> \n  exists k, [\\/ n = 3 * k + 8, n = 3 * k + 9 | n = 3 * k + 10].\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma gorg3 n : gorgeous (3 * n).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n\nNext, we can establish by induction the following criteria using the\nlemmas [repr3] and [gorg3] in the subgoals of the proof.\n\n*)\n\nLemma gorg_criteria n : n >= 8 -> gorgeous n.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n\nThis makes the proof of the following lemma trivial.\n\n*)\n\nLemma gorg_refl' n: n >= 8 -> reflect (gorgeous n) true.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\n(** \n\n- In the second stage of the proof of reflection, we will\n  need to prove four totally boring but unavoidable lemmas.\n\nHint: The rewriting lemmas [addnC] and [eqSS] from the [ssrnat]\nmodule might be particularly useful here.\n\n*)\n\nLemma not_g1: ~(gorgeous 1).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma not_g2: ~(gorgeous 2).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma not_g4: ~(gorgeous 4).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma not_g7: ~(gorgeous 7).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n\nWe can finally provide prove the ultimate reflection predicate,\nrelating [gorgeous] and [gorgeous_b].\n\n*)\nLemma gorg_refl n : reflect (gorgeous n) (gorgeous_b n).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n---------------------------------------------------------------------\nExercise [Boolean element inclusion predicate for lists]\n---------------------------------------------------------------------\n\nAssuming a type [X] with the boolean equality (i.e., elements of [X]\ncan be compared for being equal using the [==] operator returning\n[true] or [false]), define a recursive funciton [appears_in] on lists\nthat takes an element [a : X], a list [l : seq X] and returns a\nboolean value indicating whether [a] appears in [l] or not.\n\n*)\n\nSection Appears_bool.\nVariable X: eqType.\n\nFixpoint appears_in (a: X) (l: seq X) : bool := \n(* fill in your implemenation istead of the [false] stub *)\n  false.\n\n(** \n\nNext, prove the following lemma, relating [appears_in] and list\nconcatenation [++].\n\n*)\n\nLemma appears_in_app (xs ys : seq X) (x:X): \n     appears_in x (xs ++ ys) = appears_in x xs || appears_in x ys.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n\nLet us define the functions [disjoint] and [no_repeats] using\n[appears_in] as follows:\n\n*)\n\nFixpoint disjoint (l1 l2: seq X): bool := \n  if l1 is x::xs then ~~(appears_in x l2) && disjoint xs l2 else true.\n\nFixpoint no_repeats (ls : seq X) := \n  if ls is x :: xs then ~~ (appears_in x xs) && no_repeats xs else true.\n\n(** \n\nFinally, prove the following lemma, realting [no_repeats] and\n[disjoint].\n\n*)\n\nTheorem norep_disj_app l1 l2: \n  no_repeats l1 -> no_repeats l2 -> disjoint l1 l2 -> no_repeats (l1 ++ l2).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nEnd Appears_bool.\n\nEval compute in appears_in (EqType nat _) 1 [:: 1; 2; 3].\n(* true *)\n\nEval compute in appears_in (EqType nat _) 1 [:: 2; 4; 3].\n(* false *)\n\n\n(** \n---------------------------------------------------------------------\nExercise [Element inclusion predicate for lists in Prop]\n---------------------------------------------------------------------\n\nFor types [Y] with propositional equality, define the [appears_inP]\npredicate, which returns [Prop].\n\n*)\n\nSection Appears_Prop.\nVariable Y: Type.\n\nVariable appears_inP : forall (a: Y) (l: seq Y), Prop.\n(* Replace Variable by the actual implementation *)\n\n(**\nProve the lemma [appears_in_appP]:\n*)\n\nLemma appears_in_appP (xs ys : seq Y) (x:Y): \n     appears_inP x (xs ++ ys) <-> appears_inP x xs \\/ appears_inP x ys.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n\nFinally, define the [Prop]-versions of the [disjoint] and [no_repeat]\npredicates: [disjointP] and [no_repeatP] and prove the following lemma\nrelating them.\n\n*)\n\nVariable disjointP : forall (l1 l2: seq Y), Prop.\n(* Replace Variable by the actual implementation *)\n\nVariable no_repeatsP : forall (ls : seq Y), Prop. \n(* Replace Variable by the actual implementation *)\n\nTheorem norep_disj_appP l1 l2: \n  no_repeatsP l1 -> no_repeatsP l2 -> disjointP l1 l2 -> no_repeatsP (l1 ++ l2).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nEnd Appears_Prop.\n\n(** \n---------------------------------------------------------------------\nExercise [\"All\" predicate for lists]\n---------------------------------------------------------------------\n\nDefine two version of version of \"all-elements-satisfy\" predicate for\nlists. \n\n- The version [all] takes a type [X], a predicate [P : X -> Prop] and\n  a list [ls: seq X] and returns element of sort [Prop] which carries\n  a proof that all elements of ls satisfy [P].\n\n- The decidable version [allb] takes a type [X], a predicate [test : X\n  -> bool] and a list [ls: seq X], and returns a boolean result.\n\nProve the lemma [allP], stating that the two representations are\nequivalent whenever [P] and [test] are equivalent.\n\n*)\n\n\nVariable all : forall {X} (P : X -> Prop) (ls: seq X), Prop.\n(* Replace Variable by the actual implementation *)\n\nVariable allb : forall {X : Type} (test : X -> bool) (ls : seq X), bool.\n(* Replace Variable by the actual implementation *)\n\nLemma allP T P test: \n  (forall x: T, reflect (P x) (test x)) -> \n  forall ls, reflect (all P ls) (allb test ls).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nEnd SsrStyle.\n\n\n", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/lectures/SsrStyle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7049446341074064}}
{"text": "Require Import Ensembles.\nRequire Import Coq.Lists.List.\nRequire Import ListExt.\nRequire Import folProof.\nRequire Import folProp.\nRequire Vector.\nRequire Import Peano_dec.\nRequire Import misc.\nRequire Import Arith.\n\nSection Model_Theory.\n\nVariable L : Language.\n\nFixpoint naryFunc (A : Set) (n : nat) {struct n} : Set :=\n  match n with\n  | O => A\n  | S m => A -> naryFunc A m\n  end.\n\nFixpoint naryRel (A : Set) (n : nat) {struct n} : Type :=\n  match n with\n  | O => Prop\n  | S m => A -> naryRel A m\n  end.\n\nRecord Model : Type := model\n  {U : Set;\n   func : forall f : Functions L, naryFunc U (arity L (inr _ f));\n   rel : forall r : Relations L, naryRel U (arity L (inl _ r))}.\n\nVariable M : Model.\n\nFixpoint interpTerm (value : nat -> U M) (t : Term L) {struct t} : \n U M :=\n  match t with\n  | var v => value v\n  | apply f ts => interpTerms _ (func M f) value ts\n  end\n \n with interpTerms (m : nat) (f : naryFunc (U M) m) \n (value : nat -> U M) (ts : Terms L m) {struct ts} : \n U M :=\n  match ts in (Terms _ n) return (naryFunc (U M) n -> U M) with\n  | Tnil => fun f => f\n  | Tcons m t ts => fun f => interpTerms m (f (interpTerm value t)) value ts\n  end f.\n\nFixpoint interpRels (m : nat) (r : naryRel (U M) m) \n (value : nat -> U M) (ts : Terms L m) {struct ts} : Prop :=\n  match ts in (Terms _ n) return (naryRel (U M) n -> Prop) with\n  | Tnil => fun r => r\n  | Tcons m t ts => fun r => interpRels m (r (interpTerm value t)) value ts\n  end r.\n\nDefinition updateValue (value : nat -> U M) (n : nat) \n  (v : U M) (x : nat) : U M :=\n  match eq_nat_dec n x with\n  | left _ => v\n  | right _ => value x\n  end.\n\nFixpoint interpFormula (value : nat -> U M) (f : Formula L) {struct f} :\n Prop :=\n  match f with\n  | equal t s => interpTerm value t = interpTerm value s\n  | atomic r ts => interpRels _ (rel M r) value ts\n  | impH A B => interpFormula value A -> interpFormula value B\n  | notH A => interpFormula value A -> False\n  | forallH v A => forall x : U M, interpFormula (updateValue value v x) A\n  end.\n\nLemma freeVarInterpTerm :\n forall (v1 v2 : nat -> U M) (t : Term L),\n (forall x : nat, In x (freeVarTerm L t) -> v1 x = v2 x) ->\n interpTerm v1 t = interpTerm v2 t.\nProof.\nintros v1 v2 t.\nelim t using\n Term_Terms_ind\n  with\n    (P0 := fun (n : nat) (ts : Terms L n) =>\n           forall f : naryFunc (U M) n,\n           (forall x : nat, In x (freeVarTerms L n ts) -> v1 x = v2 x) ->\n           interpTerms n f v1 ts = interpTerms n f v2 ts); \n simpl in |- *; intros.\napply H.\nauto.\napply H.\nintros.\napply H0.\napply H1.\nauto.\nrewrite H.\napply H0.\nintros.\napply H1.\nunfold freeVarTerms in |- *.\napply in_or_app.\nright.\napply H2.\nintros.\napply H1.\nunfold freeVarTerms in |- *.\napply in_or_app.\nleft.\napply H2.\nQed.\n\nLemma freeVarInterpRel :\n forall (v1 v2 : nat -> U M) (n : nat) (ts : Terms L n) (r : naryRel (U M) n),\n (forall x : nat, In x (freeVarTerms L n ts) -> v1 x = v2 x) ->\n interpRels n r v1 ts -> interpRels n r v2 ts.\nProof.\nintros v1 v2 n ts r H.\ninduction ts as [| n t ts Hrects]; simpl in |- *.\nauto.\nrewrite (freeVarInterpTerm v1 v2).\napply Hrects.\nintros.\napply H.\nunfold freeVarTerms in |- *.\napply in_or_app.\nright.\napply H0.\nintros.\napply H.\nunfold freeVarTerms in |- *.\napply in_or_app.\nleft.\napply H0.\nQed.\n\nLemma freeVarInterpFormula :\n forall (v1 v2 : nat -> U M) (g : Formula L),\n (forall x : nat, In x (freeVarFormula L g) -> v1 x = v2 x) ->\n interpFormula v1 g -> interpFormula v2 g.\nProof.\nintros v1 v2 g.\ngeneralize v1 v2.\nclear v1 v2.\ninduction g as [t t0| r t| g1 Hrecg1 g0 Hrecg0| g Hrecg| n g Hrecg];\n simpl in |- *; intros v1 v2 H.\nrepeat rewrite (freeVarInterpTerm v1 v2).\nauto.\nintros.\napply H.\nsimpl in |- *.\nauto with datatypes.\nintros.\napply H.\nsimpl in |- *.\nauto with datatypes.\nintros.\napply (freeVarInterpRel v1 v2).\napply H.\napply H0.\nassert (interpFormula v2 g1 -> interpFormula v1 g1).\napply Hrecg1.\nintros.\nsymmetry  in |- *.\napply H.\nsimpl in |- *.\nauto with datatypes.\nassert (interpFormula v1 g0 -> interpFormula v2 g0).\napply Hrecg0.\nintros.\napply H.\nsimpl in |- *.\nauto with datatypes.\ntauto.\nintros.\napply H0.\napply Hrecg with v2.\nintros.\nsymmetry  in |- *.\nauto.\nassumption.\nintros.\napply Hrecg with (updateValue v1 n x).\nintros.\nunfold updateValue in |- *.\ninduction (eq_nat_dec n x0).\nreflexivity.\napply H.\napply In_list_remove3; auto.\nauto.\nQed.\n\nLemma subInterpTerm :\n forall (value : nat -> U M) (t : Term L) (v : nat) (s : Term L),\n interpTerm (updateValue value v (interpTerm value s)) t =\n interpTerm value (substituteTerm L t v s).\nProof.\nintros.\nelim t using\n Term_Terms_ind\n  with\n    (P0 := fun (n : nat) (ts : Terms L n) =>\n           forall f : naryFunc (U M) n,\n           interpTerms n f (updateValue value v (interpTerm value s)) ts =\n           interpTerms n f value (substituteTerms L n ts v s)); \n simpl in |- *; intros.\nunfold updateValue in |- *.\ninduction (eq_nat_dec v n); reflexivity.\nrewrite H.\nreflexivity.\nreflexivity.\nrewrite H.\napply H0.\nQed.\n\nLemma subInterpRel :\n forall (value : nat -> U M) (n : nat) (ts : Terms L n) \n   (v : nat) (s : Term L) (r : naryRel (U M) n),\n interpRels n r (updateValue value v (interpTerm value s)) ts <->\n interpRels n r value (substituteTerms L n ts v s).\nProof.\nintros.\ninduction ts as [| n t ts Hrects].\nsimpl in |- *.\ntauto.\nsimpl in |- *.\nrewrite <- subInterpTerm.\napply Hrects.\nQed.\n\nLemma subInterpFormula :\n forall (value : nat -> U M) (f : Formula L) (v : nat) (s : Term L),\n interpFormula (updateValue value v (interpTerm value s)) f <->\n interpFormula value (substituteFormula L f v s).\nProof.\nintros value f.\ngeneralize value.\nclear value.\nelim f using Formula_depth_ind2; simpl in |- *; intros.\nrepeat rewrite subInterpTerm.\ntauto.\napply subInterpRel.\nrewrite (subFormulaImp L).\nsimpl in |- *.\nassert\n (interpFormula (updateValue value v (interpTerm value s)) f1 <->\n  interpFormula value (substituteFormula L f1 v s)).\nauto.\nassert\n (interpFormula (updateValue value v (interpTerm value s)) f0 <->\n  interpFormula value (substituteFormula L f0 v s)).\nauto.\ntauto.\nrewrite (subFormulaNot L).\nsimpl in |- *.\nassert\n (interpFormula (updateValue value v (interpTerm value s)) f0 <->\n  interpFormula value (substituteFormula L f0 v s)).\nauto.\ntauto.\nrewrite (subFormulaForall L).\ninduction (eq_nat_dec v v0).\nrewrite a0.\nsimpl in |- *.\nunfold updateValue in |- *.\nsplit.\nintros.\napply\n freeVarInterpFormula\n  with\n    (fun x0 : nat =>\n     match eq_nat_dec v0 x0 with\n     | left _ => x\n     | right _ =>\n         match eq_nat_dec v0 x0 with\n         | left _ => interpTerm value s\n         | right _ => value x0\n         end\n     end).\nintros.\ninduction (eq_nat_dec v0 x0); reflexivity.\nauto.\nintros.\napply\n freeVarInterpFormula\n  with\n    (fun x0 : nat =>\n     match eq_nat_dec v0 x0 with\n     | left _ => x\n     | right _ => value x0\n     end).\nintros.\ninduction (eq_nat_dec v0 x0); reflexivity.\nauto.\ninduction (In_dec eq_nat_dec v (freeVarTerm L s)).\nsimpl in |- *.\nset (nv := newVar (v0 :: freeVarTerm L s ++ freeVarFormula L a)) in *.\nassert (~ In nv (v0 :: freeVarTerm L s ++ freeVarFormula L a)).\nunfold nv in |- *.\napply newVar1.\nassert\n (forall (x : U M) (x0 : nat),\n  In x0 (freeVarFormula L a) ->\n  updateValue (updateValue value v0 (interpTerm value s)) v x x0 =\n  updateValue\n    (updateValue (updateValue value nv x) v0\n       (interpTerm (updateValue value nv x) s)) v\n    (interpTerm\n       (updateValue (updateValue value nv x) v0\n          (interpTerm (updateValue value nv x) s)) \n       (var L nv)) x0).\nintros.\nunfold updateValue in |- *.\nsimpl in |- *.\ninduction (eq_nat_dec v x0).\ninduction (eq_nat_dec v0 nv).\nelim H0.\nrewrite a2.\nsimpl in |- *.\nauto.\ninduction (eq_nat_dec nv nv).\nreflexivity.\nelim b1.\nreflexivity.\ninduction (eq_nat_dec v0 x0).\napply freeVarInterpTerm.\nintros.\ninduction (eq_nat_dec nv x1).\nelim H0.\nrewrite a2.\nsimpl in |- *.\nauto with datatypes.\nreflexivity.\ninduction (eq_nat_dec nv x0).\nelim H0.\nrewrite a1.\nauto with datatypes.\nreflexivity.\nassert\n ((forall x : U M,\n   interpFormula\n     (updateValue\n        (updateValue (updateValue value nv x) v0\n           (interpTerm (updateValue value nv x) s)) v\n        (interpTerm\n           (updateValue (updateValue value nv x) v0\n              (interpTerm (updateValue value nv x) s)) \n           (var L nv))) a) <->\n  (forall x : U M,\n   interpFormula (updateValue value nv x)\n     (substituteFormula L (substituteFormula L a v (var L nv)) v0 s))).\nsplit.\nassert\n (forall b : Formula L,\n  lt_depth L b (forallH L v a) ->\n  forall (value : nat -> U M) (v : nat) (s : Term L),\n  interpFormula (updateValue value v (interpTerm value s)) b ->\n  interpFormula value (substituteFormula L b v s)).\nintros.\ninduction (H b0 H2 value0 v1 s0).\nauto.\nintros.\napply H2.\neapply eqDepth.\nsymmetry  in |- *.\napply subFormulaDepth.\napply depthForall.\napply H2.\napply depthForall.\napply H3.\nintros.\nassert\n (forall b : Formula L,\n  lt_depth L b (forallH L v a) ->\n  forall (value : nat -> U M) (v : nat) (s : Term L),\n  interpFormula value (substituteFormula L b v s) ->\n  interpFormula (updateValue value v (interpTerm value s)) b).\nintros.\ninduction (H b0 H3 value0 v1 s0).\nauto.\nclear H.\nintros.\napply H3.\napply depthForall.\napply H3.\neapply eqDepth.\nsymmetry  in |- *.\napply subFormulaDepth.\napply depthForall.\nauto.\nassert\n ((forall x : U M,\n   interpFormula\n     (updateValue (updateValue value v0 (interpTerm value s)) v x) a) <->\n  (forall x : U M,\n   interpFormula\n     (updateValue\n        (updateValue (updateValue value nv x) v0\n           (interpTerm (updateValue value nv x) s)) v\n        (interpTerm\n           (updateValue (updateValue value nv x) v0\n              (interpTerm (updateValue value nv x) s)) \n           (var L nv))) a)).\nsplit.\nintros.\napply\n freeVarInterpFormula\n  with (updateValue (updateValue value v0 (interpTerm value s)) v x).\nauto.\nauto.\nintros.\napply\n freeVarInterpFormula\n  with\n    (updateValue\n       (updateValue (updateValue value nv x) v0\n          (interpTerm (updateValue value nv x) s)) v\n       (interpTerm\n          (updateValue (updateValue value nv x) v0\n             (interpTerm (updateValue value nv x) s)) \n          (var L nv))).\nintros.\nsymmetry  in |- *.\nauto.\nauto.\ntauto.\nsimpl in |- *.\nassert\n (forall (x : U M) (x0 : nat),\n  In x0 (freeVarFormula L a) ->\n  updateValue (updateValue value v0 (interpTerm value s)) v x x0 =\n  updateValue (updateValue value v x) v0\n    (interpTerm (updateValue value v x) s) x0).\nintros.\nunfold updateValue in |- *.\ninduction (eq_nat_dec v x0).\ninduction (eq_nat_dec v0 x0).\nelim b.\ntransitivity x0; auto.\nreflexivity.\ninduction (eq_nat_dec v0 x0).\napply freeVarInterpTerm.\nintros.\ninduction (eq_nat_dec v x1).\nelim b0.\nrewrite a1.\nauto.\nreflexivity.\nreflexivity.\nsplit.\nintros.\nassert\n (forall b : Formula L,\n  lt_depth L b (forallH L v a) ->\n  forall (value : nat -> U M) (v : nat) (s : Term L),\n  interpFormula (updateValue value v (interpTerm value s)) b ->\n  interpFormula value (substituteFormula L b v s)).\nintros.\ninduction (H b1 H2 value0 v1 s0).\nauto.\napply H2.\napply depthForall.\napply\n freeVarInterpFormula\n  with (updateValue (updateValue value v0 (interpTerm value s)) v x).\napply (H0 x).\napply H1.\nassert\n (forall b : Formula L,\n  lt_depth L b (forallH L v a) ->\n  forall (value : nat -> U M) (v : nat) (s : Term L),\n  interpFormula value (substituteFormula L b v s) ->\n  interpFormula (updateValue value v (interpTerm value s)) b).\nintros.\ninduction (H b1 H1 value0 v1 s0).\nauto.\nintros.\napply\n freeVarInterpFormula\n  with\n    (updateValue (updateValue value v x) v0\n       (interpTerm (updateValue value v x) s)).\nintros.\nsymmetry  in |- *.\nauto.\napply H1.\napply depthForall.\nauto.\nQed.\n\nLemma subInterpFormula1 :\n forall (value : nat -> U M) (f : Formula L) (v : nat) (s : Term L),\n interpFormula (updateValue value v (interpTerm value s)) f ->\n interpFormula value (substituteFormula L f v s).\nProof.\nintros.\ninduction (subInterpFormula value f v s).\nauto.\nQed.\n\nLemma subInterpFormula2 :\n forall (value : nat -> U M) (f : Formula L) (v : nat) (s : Term L),\n interpFormula value (substituteFormula L f v s) ->\n interpFormula (updateValue value v (interpTerm value s)) f.\nProof.\nintros.\ninduction (subInterpFormula value f v s).\nauto.\nQed.\n\nFixpoint nnHelp (f : Formula L) : Formula L :=\n  match f with\n  | equal t s => equal L t s\n  | atomic r ts => atomic L r ts\n  | impH A B => impH L (nnHelp A) (nnHelp B)\n  | notH A => notH L (nnHelp A)\n  | forallH v A => forallH L v (notH L (notH L (nnHelp A)))\n  end.\n\nDefinition nnTranslate (f : Formula L) : Formula L :=\n  notH L (notH L (nnHelp f)).\n\nLemma freeVarNNHelp :\n forall f : Formula L, freeVarFormula L f = freeVarFormula L (nnHelp f).\nProof.\nintros.\ninduction f as [t t0| r t| f1 Hrecf1 f0 Hrecf0| f Hrecf| n f Hrecf];\n try reflexivity.\nsimpl in |- *.\nrewrite Hrecf1.\nrewrite Hrecf0.\nreflexivity.\nsimpl in |- *.\nassumption.\nsimpl in |- *.\nrewrite Hrecf.\nreflexivity.\nQed.\n\nLemma subNNHelp :\n forall (f : Formula L) (v : nat) (s : Term L),\n substituteFormula L (nnHelp f) v s = nnHelp (substituteFormula L f v s).\nProof.\nintro f.\nelim f using Formula_depth_ind2; intros; try reflexivity.\nsimpl in |- *.\nrewrite subFormulaImp.\nrewrite H.\nrewrite H0.\nrewrite subFormulaImp.\nreflexivity.\nsimpl in |- *.\nrewrite subFormulaNot.\nrewrite H.\nrewrite subFormulaNot.\nreflexivity.\nsimpl in |- *.\ndo 2 rewrite subFormulaForall.\nsimpl in |- *.\ninduction (eq_nat_dec v v0).\nsimpl in |- *.\nreflexivity.\ninduction (In_dec eq_nat_dec v (freeVarTerm L s)).\nsimpl in |- *.\nrepeat rewrite subFormulaNot.\nrepeat rewrite H.\nrewrite <- freeVarNNHelp.\nreflexivity.\neapply eqDepth.\nsymmetry  in |- *.\napply subFormulaDepth.\napply depthForall.\napply depthForall.\nrepeat rewrite subFormulaNot.\nrewrite H.\nsimpl in |- *.\nreflexivity.\napply depthForall.\nQed.\n\nSection Consistent_Theory.\n\nVariable T : System L.\n\nFixpoint interpTermsVector (value : nat -> U M) (n : nat) \n (ts : Terms L n) {struct ts} : Vector.t (U M) n :=\n  match ts in (Terms _ n) return (Vector.t (U M) n) with\n  | Tnil => Vector.nil (U M)\n  | Tcons m t ts =>\n      Vector.cons (U M) (interpTerm value t) m (interpTermsVector value m ts)\n  end.\n\nLemma preserveValue :\n forall value : nat -> U M,\n (forall f : Formula L,\n  mem _ T f -> interpFormula value (nnTranslate f)) ->\n forall g : Formula L, SysPrf L T g -> interpFormula value (nnTranslate g).\nProof.\nintros.\ninduction H0 as (x, H0).\ninduction H0 as (x0, H0).\ncut (forall g : Formula L, In g x -> interpFormula value (nnTranslate g)).\nclear H H0.\ngeneralize value.\nclear value.\ninduction x0\n as\n  [A|\n   Axm1 Axm2 A B x0_1 Hrecx0_1 x0_0 Hrecx0_0|\n   Axm A v n x0 Hrecx0|\n   A B|\n   A B C|\n   A B|\n   A v t|\n   A v n|\n   A B v|\n   |\n   |\n   |\n   R|\n   f]; intros; try (simpl in |- *; tauto).\napply H.\nauto with datatypes.\nassert (interpFormula value (nnTranslate A)).\nauto with datatypes.\nassert (interpFormula value (nnTranslate (impH L A B))).\nauto with datatypes.\nclear Hrecx0_1 Hrecx0_0.\nsimpl in H0.\nsimpl in H1.\nsimpl in |- *.\ntauto.\nsimpl in |- *.\nintros.\napply H0.\nclear H0.\nintros.\nsimpl in Hrecx0.\napply (Hrecx0 (updateValue value v x)).\nintros.\nsimpl in H.\neapply H.\napply H1.\nintros.\napply H2.\napply freeVarInterpFormula with value.\nintros.\nrewrite <- freeVarNNHelp in H4.\nunfold updateValue in |- *.\ninduction (eq_nat_dec v x1).\nelim n.\nrewrite a.\nclear n x0 Hrecx0 H.\ninduction Axm as [| a0 Axm HrecAxm].\napply H1.\nsimpl in |- *.\nsimpl in H1.\ninduction H1 as [H| H].\nrewrite H.\nauto with datatypes.\nauto with datatypes.\nreflexivity.\nassumption.\nassumption.\nsimpl in |- *.\nintros.\napply H0.\nintros.\nelim H1 with (interpTerm value t).\nintros.\napply H0.\nintros.\nrewrite <- subNNHelp.\napply subInterpFormula1.\nauto.\nsimpl in |- *.\nintros.\napply H0.\nintros.\napply H2.\napply freeVarInterpFormula with value.\nintros.\nunfold updateValue in |- *.\ninduction (eq_nat_dec v x0).\nelim n.\nrewrite a.\nrewrite freeVarNNHelp.\nassumption.\nreflexivity.\nassumption.\nsimpl in |- *.\nintros.\napply H0.\nclear H0.\nintros.\napply H0 with x.\nintros.\napply H1 with x.\nauto.\nsimpl in |- *.\nauto.\nsimpl in |- *.\nintros.\napply H0.\nintros.\ntransitivity (value 1); auto.\nsimpl in |- *.\nintros.\napply H0.\nclear H H0.\nunfold AxmEq4 in |- *.\ncut\n (forall a b : Terms L (arity L (inl (Functions L) R)),\n  interpTermsVector value _ a = interpTermsVector value _ b ->\n  interpFormula value (nnHelp (iffH L (atomic L R a) (atomic L R b)))).\nassert\n (forall A,\n  (forall a b : Terms L (arity L (inl (Functions L) R)),\n   interpTermsVector value (arity L (inl (Functions L) R)) a =\n   interpTermsVector value (arity L (inl (Functions L) R)) b ->\n   interpFormula value (nnHelp (A a b))) ->\n  interpFormula value\n    (nnHelp\n       (nat_rec (fun _ : nat => Formula L)\n          (prod_rec\n             (fun\n                _ : Terms L (arity L (inl (Functions L) R)) *\n                    Terms L (arity L (inl (Functions L) R)) => \n              Formula L)\n             (fun a b : Terms L (arity L (inl (Functions L) R)) => A a b)\n             (nVars L (arity L (inl (Functions L) R))))\n          (fun (n : nat) (Hrecn : Formula L) =>\n           impH L (equal L (var L (n + n)) (var L (S (n + n)))) Hrecn)\n          (arity L (inl (Functions L) R))))).\ngeneralize (arity L (inl (Functions L) R)).\nsimple induction n.\nsimpl in |- *.\nintros.\napply H.\nreflexivity.\nintros.\nsimpl in |- *.\ninduction (nVars L n0).\nsimpl in |- *.\nsimpl in H.\nintros.\napply\n (H\n    (fun x y : Terms L n0 =>\n     A (Tcons L n0 (var L (n0 + n0)) x) (Tcons L n0 (var L (S (n0 + n0))) y))).\nintros.\napply H0.\nsimpl in |- *.\nrewrite H1.\nrewrite H2.\nreflexivity.\napply (H (fun a b => iffH L (atomic L R a) (atomic L R b))).\nsimpl in |- *.\ngeneralize (rel M R).\ngeneralize (arity L (inl (Functions L) R)).\nintros.\ninduction a as [| n t a Hreca].\nassert (b = Tnil L).\nsymmetry  in |- *.\napply nilTerms.\nrewrite H1 in H0.\nauto.\ninduction (consTerms L n b).\ninduction x as (a0, b0).\nsimpl in p.\nrewrite <- p in H0.\nrewrite <- p in H.\nsimpl in H.\ninversion H.\nsimpl in H0.\nrewrite H2 in H0.\napply (Hreca (n0 (interpTerm value a0)) b0).\napply (inj_right_pair2 _ eq_nat_dec _ _ _ _ H3).\nauto.\nsimpl in |- *.\nintros.\napply H0.\nclear H H0.\nunfold AxmEq5 in |- *.\ncut\n (forall a b : Terms L (arity L (inr (Relations L) f)),\n  interpTermsVector value _ a = interpTermsVector value _ b ->\n  interpFormula value (nnHelp (equal L (apply L f a) (apply L f b)))).\nassert\n (forall A,\n  (forall a b : Terms L (arity L (inr (Relations L) f)),\n   interpTermsVector value (arity L (inr (Relations L) f)) a =\n   interpTermsVector value (arity L (inr (Relations L) f)) b ->\n   interpFormula value (nnHelp (A a b))) ->\n  interpFormula value\n    (nnHelp\n       (nat_rec (fun _ : nat => Formula L)\n          (prod_rec\n             (fun\n                _ : Terms L (arity L (inr (Relations L) f)) *\n                    Terms L (arity L (inr (Relations L) f)) => \n              Formula L)\n             (fun a b : Terms L (arity L (inr (Relations L) f)) => A a b)\n             (nVars L (arity L (inr (Relations L) f))))\n          (fun (n : nat) (Hrecn : Formula L) =>\n           impH L (equal L (var L (n + n)) (var L (S (n + n)))) Hrecn)\n          (arity L (inr (Relations L) f))))).\ngeneralize (arity L (inr (Relations L) f)).\nsimple induction n.\nsimpl in |- *.\nintros.\nauto.\nintros.\nsimpl in |- *.\ninduction (nVars L n0).\nsimpl in |- *.\nsimpl in H.\nintros.\napply\n (H\n    (fun x y : Terms L n0 =>\n     A (Tcons L n0 (var L (n0 + n0)) x) (Tcons L n0 (var L (S (n0 + n0))) y))).\nintros.\napply H0.\nsimpl in |- *.\nrewrite H1.\nrewrite H2.\nreflexivity.\napply (H (fun a b => equal L (apply L f a) (apply L f b))).\nsimpl in |- *.\ngeneralize (func M f).\ngeneralize (arity L (inr (Relations L) f)).\nintros.\ninduction a as [| n t a Hreca].\nassert (b = Tnil L).\nsymmetry  in |- *.\napply nilTerms.\nrewrite H0.\nreflexivity.\ninduction (consTerms L n b).\ninduction x as (a0, b0).\nsimpl in p.\nrewrite <- p.\nrewrite <- p in H.\nsimpl in H.\ninversion H.\nsimpl in |- *.\nrewrite H1.\napply Hreca.\napply (inj_right_pair2 _ eq_nat_dec _ _ _ _ H2).\nauto.\nQed.\n\nLemma ModelConsistent :\n forall value : nat -> U M,\n (forall f : Formula L,\n  mem _ T f -> interpFormula value (nnTranslate f)) ->\n Consistent L T.\nProof.\nintros.\nunfold Consistent in |- *.\nexists (notH L (equal L (var  L 0) (var L 0))).\nunfold not in |- *; intros.\nassert\n (interpFormula value\n    (nnTranslate (notH L (equal L (var L 0) (var L 0))))).\napply preserveValue.\nassumption.\nauto.\nsimpl in *.\nauto.\nQed.\n\nEnd Consistent_Theory.\n\nEnd Model_Theory.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/goedel/model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782094, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7049153183545075}}
{"text": "(*\n * Closed forms for the sum of the p-th power of the first n natural numbers.\n * TODO: Faulhaber’s formula\n *)\n\nFrom Coq Require Import\n  Arith\n  List\n  Lia.\nFrom FunProofs.Lib Require Import\n  Series\n  Util.\n\nImport NSum.\n\nSection TriangleSum.\n  Notation numer n := (n * (n + 1)) (only parsing).\n\n  Lemma tri_div_2 n : numer n mod 2 = 0.\n  Proof.\n    apply Nat.mod_divides, Nat.even_spec; try lia.\n    rewrite Nat.even_mul, Nat.add_1_r, Nat.even_succ.\n    apply Nat.orb_even_odd.\n  Qed.\n\n  Lemma triangle_sum n : sum (seq 1 n) = numer n / 2.\n  Proof.\n    induction n; auto.\n    cbn [seq]; rewrite <- seq_shift; cbn -[Nat.div Nat.mul]; normalize_sums.\n    rewrite sum_succ, sum_shift, IHn, seq_length.\n    apply Nat.div_unique_exact; [lia |].\n    unfold NSumOps.Tadd, NSumOps.T_of_nat, NSumOps.T0, id.\n    enough (numer n = 2 * (numer n / 2)) by lia.\n    apply Nat.div_exact; [lia | apply tri_div_2].\n  Qed.\nEnd TriangleSum.\n\nSection SumSquare.\n  Notation numer n := (n * (n + 1) * (2 * n + 1)) (only parsing).\n\n  Lemma square_succ n : Nat.square (S n) = Nat.square n + 2 * n + 1.\n  Proof. unfold Nat.square; lia. Qed.\n\n  Lemma sum_square_succ ns n :\n    sum' n (map (fun m => Nat.square (S m)) ns) =\n    sum' n (map Nat.square ns) + 2 * sum ns + length ns.\n  Proof.\n    erewrite map_ext by (apply square_succ).\n    rewrite !sum_add; fold (@const _ NSumOps.T 1).\n    rewrite sum_const, sum_mul_id; cbn.\n    unfold NSumOps.Tadd, NSumOps.T_of_nat, NSumOps.T, id in *; lia.\n  Qed.\n\n  Lemma square_div_6 n : numer n mod 6 = 0.\n  Proof.\n    induction n; auto.\n    apply Nat.mod_divides in IHn as (m & IHn); try lia.\n    match goal with |- ?x mod _ = _ => remember x as lhs end.\n    replace lhs with (6 * (m + n * n + 2 * n + 1)) by lia.\n    rewrite Nat.mul_comm; apply Nat.mod_mul; lia.\n  Qed.\n\n  Lemma sum_square n : sum (map Nat.square (seq 1 n)) = numer n / 6.\n  Proof.\n    induction n; auto.\n    cbn [seq]; rewrite <- seq_shift; cbn -[Nat.div Nat.mul]; normalize_sums.\n    change (Nat.square 1) with 1; rewrite sum_shift.\n    rewrite map_map, sum_square_succ, IHn, triangle_sum, seq_length.\n    apply Nat.div_unique_exact; [lia |].\n    pose proof (tri_div_2 n) as Htri; apply Nat.div_exact in Htri; try lia.\n    unfold NSumOps.Tadd, NSumOps.T_of_nat, NSumOps.T0, id.\n    enough (numer n = 6 * (numer n / 6)) by lia.\n    apply Nat.div_exact; [lia | apply square_div_6].\n  Qed.\nEnd SumSquare.\n\nSection SumCube.\n  Notation numer n := (n * n * (n + 1) * (n + 1)) (only parsing).\n\n  Definition cube n := n * n * n.\n\n  Lemma cube_succ n : cube (S n) = cube n + 3 * Nat.square n + 3 * n + 1.\n  Proof. unfold cube, Nat.square; lia. Qed.\n\n  Lemma sum_cube_succ ns n :\n    sum' n (map (fun m => cube (S m)) ns) =\n    sum' n (map cube ns) + 3 * sum (map (Nat.square) ns) + 3 * sum ns + length ns.\n  Proof.\n    erewrite map_ext by (apply cube_succ).\n    rewrite !sum_add; fold (@const _ NSumOps.T 1).\n    rewrite sum_const, sum_mul_id, sum_mul; cbn.\n    unfold NSumOps.Tadd, NSumOps.T_of_nat, NSumOps.T, id in *; lia.\n  Qed.\n\n  Lemma cube_div_4 n : numer n mod 4 = 0.\n  Proof.\n    replace (numer n) with ((n * (n + 1)) * (n * (n + 1))) by lia.\n    pose proof (tri_div_2 n) as Htri.\n    apply Nat.mod_divides in Htri as (m & ->); try lia.\n    replace (2 * m * (2 * m)) with (m * m * 4) by lia.\n    apply Nat.mod_mul; lia.\n  Qed.\n\n  Lemma cube_square n : sum (map cube (seq 1 n)) = numer n / 4.\n  Proof.\n    induction n; auto.\n    cbn [seq]; rewrite <- seq_shift; cbn -[Nat.div Nat.mul]; normalize_sums.\n    change (cube 1) with 1; rewrite sum_shift.\n    rewrite map_map, sum_cube_succ, IHn, sum_square, triangle_sum, seq_length.\n    apply Nat.div_unique_exact; [lia |].\n    pose proof (tri_div_2 n) as Htri; apply Nat.div_exact in Htri; try lia.\n    pose proof (square_div_6 n) as Hsq; apply Nat.div_exact in Hsq; try lia.\n    unfold NSumOps.Tadd, NSumOps.T_of_nat, NSumOps.T0, id.\n    enough (numer n = 4 * (numer n / 4)) by lia.\n    apply Nat.div_exact; [lia | apply cube_div_4].\n  Qed.\nEnd SumCube.\n", "meta": {"author": "whonore", "repo": "FunProofs", "sha": "f87c0d56670af0903f2a50a52c5f1056703f31cc", "save_path": "github-repos/coq/whonore-FunProofs", "path": "github-repos/coq/whonore-FunProofs/FunProofs-f87c0d56670af0903f2a50a52c5f1056703f31cc/TriSum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7048798929597795}}
{"text": "Require Export C11_Mediatrice.\n\nSection OPPOSED_ANGLE.\n\nLemma BetweenHalfLineBetween : forall A B C D : Point,\n\tBetween A B C ->\n\tHalfLine B C D ->\n\tBetween A B D.\nProof.\n\tintros.\n\tautoClockwise.\nQed.\n\nLemma CongruentOppParallelogramm : forall A B C D E : Point, \n\t\tBetween B A D -> \n\t\tBetween C A E ->\n\t\tDistance A B = Distance A C ->\n\t\tDistance A B = Distance A D ->\n\t\tDistance A B = Distance A E ->\n\t\t~Collinear A B C ->\n\t\tAngle B A C = Angle E A D.\nProof.\n\tintros.\n\tapply CongruentStrictTrianglesA; repeat split.\n\t trivial.\n\t apply (CongruentStrictTrianglesCA C D B D C E).\n\t   apply CongruentStrictTrianglesSASB.\n\t  autoDistance.\n\t  rewrite <- (Chasles D A B).\n\t   rewrite <- (Chasles C A E).\n\t    rewrite (DistSym D A); rewrite (DistSym C A).\n\t      rewrite <- H1; rewrite <- H2; autoDistance.\n\t    apply BetweenHalfLine; trivial.\n\t    apply BetweenSymHalfLine; trivial.\n\t   apply BetweenSymHalfLine; trivial.\n\t   apply BetweenHalfLine; trivial.\n\t  assert (H5 : C <> D).\n\t   intro; elim H4; subst.\n\t     apply CollinearBAC; apply BetweenCollinear; trivial.\n\t   rewrite (CongruentItself D C B C A).\n\t    rewrite (CongruentItself C D E D A).\n\t     apply CongruentStrictTrianglesB; repeat split.\n\t      autoDistance.\n\t      autoDistance.\n\t      rewrite (DistSym C A); rewrite <- H1; rewrite H2; autoDistance.\n\t      intro; elim H4; apply (CollinearTrans A D B C).\n\t       apply (BetweenDistinctBC _ _ _ H).\n\t       apply CollinearBCA; apply BetweenCollinear; trivial.\n\t       trivial.\n\t     trivial.\n\t     apply sym_not_eq; apply (BetweenDistinctCA _ _ _ H0).\n\t     canonize.\n\t     apply HalfLineSym.\n\t      apply (BetweenDistinctAB _ _ _ H0).\n\t      apply BetweenHalfLine; trivial.\n\t    auto.\n\t    apply (BetweenDistinctCA _ _ _ H).\n\t    canonize.\n\t    apply HalfLineSym.\n\t     apply sym_not_eq; apply (BetweenDistinctBC _ _ _ H).\n\t     apply BetweenHalfLine; apply BetweenSym; auto.\n\t  intro; elim H4; apply CollinearBAC; apply (CollinearTrans B D A C).\n\t   apply sym_not_eq; apply (BetweenDistinctCA _ _ _ H).\n\t   apply CollinearACB; apply BetweenCollinear; trivial.\n\t   autoCollinear.\n\t rewrite (DistSym C A); rewrite <- H1; rewrite H2; autoDistance.\n\t trivial.\n Qed.\n\nLemma CongruentOpp : forall A B C D E : Point, \n\t\tBetween B A D -> \n\t\tBetween C A E ->\n\t\t~Collinear A B C ->\n\t\tAngle B A C = Angle E A D.\nProof.\n\tintros.\n\tassert (A <> B).\n\t apply sym_not_eq; apply (BetweenDistinctAB _ _ _ H).\n\t assert (A <> C).\n\t  apply sym_not_eq; apply (BetweenDistinctAB _ _ _ H0).\n\t  assert (A <> D).\n\t   apply (BetweenDistinctBC _ _ _ H).\n\t   assert (A <> E).\n\t    apply (BetweenDistinctBC _ _ _ H0).\n\t    destruct (ExistsHalfLineEquidistant A B A C H2 H3) as (B', (H6, H7)).\n\t      destruct (ExistsHalfLineEquidistant A D A C H4 H3) as (D', (H8, H9)).\n\t      destruct (ExistsHalfLineEquidistant A E A C H5 H3) as (E', (H10, H11)).\n\t      rewrite (CongruentItself A B C B' C H2 H3 H6).\n\t     rewrite (CongruentItself A E D E' D' H5 H4 H10 H8).\n\t       apply (CongruentOppParallelogramm A C B' E' D').\n\t      autoClockwise.\n\t      apply (BetweenHalfLineBetween B' A D D').\n\t       apply BetweenSym; apply (BetweenHalfLineBetween D A B B').\n\t        apply BetweenSym; trivial.\n\t        trivial.\n\t       trivial.\n\t      auto.\n\t      auto.\n\t      auto.\n\t      intro; elim H1.\n\t        apply (CollinearTrans A B' B C).\n\t       apply (EquiDistantDistinct A C A B' H3); auto.\n\t       apply CollinearACB; apply HalfLineCollinear; trivial.\n\t       autoCollinear.\n\t     autoCollinear.\n Qed.\n\nLemma CongruentOpposedStrictTriangles : forall A B C D I : Point,\n\tBetween A I C ->\n\tBetween B I D ->\n\tDistance I A = Distance I C ->\n\tDistance I B = Distance I D ->\n\t~Collinear A I B ->\n\tCongruentStrictTriangles A I B C I D.\nProof.\n\tintros.\n\tapply CongruentStrictTrianglesSASB.\n\t trivial.\n\t trivial.\n\t rewrite (AngleSym I A B).\n\t  apply CongruentOpp.\n\t   trivial.\n\t   trivial.\n\t   intro; elim H3; autoCollinear.\n\t  apply sym_not_eq; apply (BetweenDistinctAB _ _ _ H).\n\t  apply sym_not_eq; apply (BetweenDistinctAB _ _ _ H0).\n\t trivial.\nQed.\n\nEnd OPPOSED_ANGLE.\n\n", "meta": {"author": "coq-contribs", "repo": "ruler-compass-geometry", "sha": "ee36f5cd523abaa2e0b676c4100c02ec496c0bfd", "save_path": "github-repos/coq/coq-contribs-ruler-compass-geometry", "path": "github-repos/coq/coq-contribs-ruler-compass-geometry/ruler-compass-geometry-ee36f5cd523abaa2e0b676c4100c02ec496c0bfd/C12_Angles_Opposes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7048798901317305}}
{"text": "(** %\\chapter{Equality and Rewriting Principles}% *)\n\nFrom mathcomp\nRequire Import ssreflect ssrfun eqtype ssrnat ssrbool.\n\nModule Rewriting.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** * Propositional equality in Coq *)\n\nLocate \"_ = _\".\n\n(**\n[[\n\"x = y\" := eq x y    : type_scope\n]]\n*)\n\nPrint eq.\n\n(**\n[[\nInductive eq (A : Type) (x : A) : A -> Prop :=  eq_refl : eq x x\n]]\n\nThe type of its only constructor [eq_refl] is a bit misleading, as it\nlooks like it is applied to two arguments: [x] and ... [x]. To\ndisambiguate it, we shall put some parentheses, so, it fact, it should\nread as\n\n[[\nInductive eq (A : Type) (x : A) : A -> Prop :=  eq_refl : (eq x) x\n]]\n\nThat is, the constructor [eq_refl] delivers an element of type [(eq\nx)], whose _parameter_ is some [x] (and [eq] is directly applied to\nit), and its _index_ (which comes second) is constrained to be [x] as\nwell. That is, case-analysing on an instance of [eq x y] in the\nprocess of the proof construction will inevitably lead the side\ncondition implying that [x] and [y] actually correspond to the _same\nobject_. Coq will take advantage of this fact immediately, by\nperforming the _unification_ and substituting all occurrences of [y]\nin the subsequent goal with [x].  Let us see how it works in practice.\n\n** Case analysis on an equality witness\n\nTo demonstrate the actual proofs on the case analysis by equality, we\nwill have to perform an awkward twist: define _our own_ equality\npredicate. \n\n*)\n\nSet Implicit Arguments.\nInductive my_eq (A : Type) (x : A) : A -> Prop :=  my_eq_refl : my_eq x x.\nNotation \"x === y\" := (my_eq x y) (at level 70).\n\n(** \n\nAs we can see, this definition literally repeats the Coq's standard\ndefinition of propositional equality. The reason for the code\nduplication is that SSReflect provides a specific treatment of Coq's\nstandard equality predicate, so the case-analysis on its instances is\ncompletely superseded by the powerful [rewrite] tactics, which we will\nsee in %Section~\\ref{sec:rewriting}% of this chapter. Alas, this\nspecial treatment also leads to a non-standard behaviour of\ncase-analysis on equality. This is why, for didactical purposes, we\nwill have to stick with or own home-brewed definition until the end of\nthis section.\n\n*)\n\nLemma my_eq_sym A (x y: A) : x === y -> y === x.\n\ncase.\n\n(** \n\n[[\n  A : Type\n  x : A\n  y : A\n  ============================\n   x === x\n]]\n*)\n\ndone.\nQed.\n\n(**\n\nOur next exercise will be to show that the predicate we have just\ndefined implies Leibniz equality. The proof is accomplished in one\nline by first moving the assumption [P x]\nto the top and then case-analysing on the equality, which leads to the\nautomatic replacements of [y] by [x].\n\n*)\n\nLemma my_eq_Leibniz A (x y: A) (P: A -> Prop) : x === y -> P x -> P y. \nProof. by case. Qed.\n\n(** ** Implementing discrimination\n\nAnother important application of the equality predicate family and\nsimilar ones are _proofs by discrimination_, in which the\ncontradiction is reached (i.e., the falsehood is derived) out of the\nfact that two clearly non-equal elements are assumed to be equal. The\nnext lemma demonstrates the essence of the proof by discrimination\nusing the [my_eq] predicate.\n\n*)\n\nLemma disaster : 2 === 1 -> False.\nProof.\nmove=> H.\n\n(**\n\n[[\n  H : 2 === 1\n  ============================\n   False\n]]\n\n*)\n\npose D x := if x is 2 then False else True.\n\n(**\n\n[[\n  H : 2 === 1\n  D := fun x : nat =>\n       match x with\n       | 0 => True\n       | 1 => True\n       | 2 => False\n       | S (S (S _)) => True\n       end : nat -> Prop\n  ============================\n   False\n]]\n*)\n\nhave D1: D 1. \nby [].\n\n(**\n\n[[\n  H : 2 === 1\n  D := ...\n  D1 : D 1\n  ============================\n   False\n]]\n*)\n\ncase: H D1. \n\n(**\n\n[[\n  D := ...\n  ============================\n   D 2 -> False\n]]\n*)\n\nmove=>/=.\n\n(**\n\nThe tactical [/=], coming after [=>] runs all possible simplifications\non the result obtained by the tactics, preceding [=>], finishing the\nproof.\n\n*)\n\ndone.\nQed.\n\n(** \n\n** Reasoning with Coq's standard equality\n\nNow we know what drives the reasoning by equality and discrimination,\nso let us forget about the home-brewed predicate [my_eq] and use the\nstandard equality instead. Happily, the discrimination pattern we used\nto implement \"by hand\" now is handled by Coq/SSReflect automatically,\nso the trivially false equalities deliver the proofs right away by\nsimply typing [done]. \n\n*)\n\nLemma disaster3: 2 = 1 -> False.\nProof. done. Qed.\n\n(** \n\n* Proofs by rewriting \n\nThe vast majority of the steps when constructing real-life proofs in\nCoq are _rewriting_ steps. The general flow of the interactive proof\nis typically targeted on formulating and proving small auxiliary\nhypotheses about equalities in the forward-style reasoning and then\nexploiting the derived equalities by means of rewriting in the goal\nand, occasionally, other assumptions in the context. All rewriting\nmachinery is handled by SSReflect's enhanced [rewrite]%\\ssrt{rewrite}%\ntactics, and in this section we focus on its particular uses.\n\n** Unfolding definitions and in-place rewritings\n\nOne of the common uses of the [rewrite] tactic is to fold/unfold\ntransparent definitions. In general, Coq is capable to perform the\nunfoldings itself, whenever it's required. Nevertheless, manual\nunfolding of a definition might help to understand the details of the\nimplementation, as demonstrated by the following example.\n\n*)\n\nDefinition double A (f: A -> A) (x: A) := f (f x).\n\nFixpoint nat_iter (n : nat) {A} (f : A -> A) (x : A) : A :=\n  if n is S n' then f (nat_iter n' f x) else x.\n\nLemma double2 A (x: A) f t: \n  t = double f x -> double f t = nat_iter 4 f x.\nProof.\n\nmove=>Et; rewrite Et.\n\n(**\n\n[[\n  A : Type\n  x : A\n  f : A -> A\n  t : A\n  Et : t = double f x\n  ============================\n   double f (double f x) = nat_iter 4 f x\n]]\n\nEven though the remaining goal is simple enough to be completed by\n[done], let us unfold both definition to make sure that the two terms\nare indeed equal structurally. Such unfoldings can be _chained_, just\nas any other rewritings.\n\n*)\n\nrewrite /double /nat_iter.\n\n(**\n[[\n  x : A\n  f : A -> A\n  ============================\n   f (f (f (f x))) = f (f (f (f x)))\n]]\n\nAn alternative way to prove the same statement would be to use the\n[->] tactical, which is usually combined with\n[move] or [case], but instead of moving the assumption to the top, it\nmakes sure that the assumption is an equality and rewrites by it.\n\n *)\n\nRestart.\nby move=>->.\nQed.\n\n(** \n\nNotice that the tactical has a companion one [<-], which performs the\nrewriting by an equality assumption from right to left, in contrast to\n[->], which rewrites left to right.\n\nThe reverse operation to folding is done by using [rewrite -/...]\ninstead of [rewrite /...].\n\n** Proofs by congruence and rewritings by lemmas\n\n*)\n\nDefinition f x y :=  x + y.\n\nGoal forall x y, x + y + (y + x) = f y x + f y x.\nProof. \nmove=> x y.\n\nrewrite /f.\n\n(**\n\n[[\n  x : nat\n  y : nat\n  ============================\n   x + y + (y + x) = y + x + (y + x)\n]]\n*)\n\ncongr (_ + _).\n\n(** \n\n[[\n  x : nat\n  y : nat\n  ============================\n   x + y = y + x\n]]\n*)\n\nCheck addnC.\n\n(**\n[[\naddnC\n     : commutative addn\n]]\n*)\n\nPrint ssrfun.commutative.\n\n(** \n[[\nssrfun.commutative = \n  fun (S T : Type) (op : S -> S -> T) => forall x y : S, op x y = op y x\n       : forall S T : Type, (S -> S -> T) -> Prop\n]]\n\nSo, after specializing the definition appropriately, the type of\n[addnC] should be read as:\n\n[[\naddnC\n     : forall n m: nat, n + m = m + n\n]]\n\nNow, we can take advantage of this equality and rewrite by it a part\nof the goal. Notice that Coq will figure out how the\nuniversally-quantified variables should be instantiated (i.e., with\n[y] and [x], respectively):\n\n*)\n\nby rewrite [y + _]addnC.\nQed.\n\nGoal forall x y z, (x + (y + z)) = (z + y + x).\nProof.\nby move=>x y z; rewrite [y + _]addnC; rewrite [z + _ + _]addnC.\nQed.\n\n(** ** Naming in subgoals and optional rewritings\n\nWhen working with multiple cases, it is possible to \"chain\" the\nexecution of several tactics. Then, in the case of a script [tac1;\ntac2], if the goal is replaced by several after applying [tac1], then\n[tac2] will be applied to _all_ subgoals, generated by [tac1]. For\nexample, let us consider a proof of the following lemma from the\nstandard [ssrnat] %\\ssrm{ssrnat}% module:\n\n*)\n\nLemma addnCA: forall m n p, m + (n + p) = n + (m + p).\nProof.\nmove=>m n. \n\n(** \n\n[[\n  m : nat\n  n : nat\n  ============================\n   forall p : nat, m + (n + p) = n + (m + p)\n]]\n\nThe proof will proceed by induction on [m]. We have already seen the\nuse of the [case] tactics, which just performs the case\nanalysis. Another SSReflect tactic [elim]  generalizes\n[case] by applying the default induction principle ([nat_ind] in this\ncase) with the respect to the remaining goal (that is, the predicate\n[[forall p : nat, m + (n + p) = n + (m + p)]]) is to be proven by\ninduction.  The following sequence of tactics proceeds by induction on\n[m] with the default induction principle. It also names some of the\ngenerated assumptions. \n\n*)\n\nelim: m=>[ | m Hm ] p. \n\n(**\n\nIn particular, the following steps are performed:\n\n- [m] is pushed as a top assumption of the goal;\n- [elim] is run, which leads to generation of the two goals;\n\n  - The first goal is of the shape\n[[\nforall p : nat, 0 + (n + p) = n + (0 + p)\n]]\n\n  - The second goal has the shape\n[[\nforall n0 : nat,\n (forall p : nat, n0 + (n + p) = n + (n0 + p)) ->\n forall p : nat, n0.+1 + (n + p) = n + (n0.+1 + p)\n]]\n\n- The subsequent structured naming [=> [ |m Hm ] p] names zero\n  assumptions in the first goal and the two top assumptions, [m] and\n  [Hm], in the second goal. It then next names the assumption [p] in\n  _both_ goals and moves it to the top.\n\nThe first goal can now be proved by multiple rewritings via the lemma\n[add0n], stating that [0] is the left unit with respect to the\naddition:\n\n*)\n\nby rewrite !add0n.\n\n(**\n\nThe second goal can be proved by a series of rewritings using the fact\nabout the [(_ + 1)] function:\n\n*)\n\n\nby rewrite !addSnnS -addnS.\n\n(**\n\nNotice that the conclusion of the [addnS] lemma is rewritten\nright-to-left.\n\nThe whole proof could be, however, accomplished in one line using the\n_optional_ rewritings. \n*)\n\nRestart.\n\nby move=>m n; elim: m=>[ | m Hm ] p; rewrite ?add0n ?addSnnS -?addnS.\nQed.\n\n(** \n\nNotice that the optional rewritings (e.g., [?addSnnS]) are\nperformed as many times as they can be.\n\n** Selective occurrence rewritings\n\nSometimes, instead of providing an r-pattern to specialize the\nrewriting, it is more convenient to specify, which particular\nsyntactic occurrences in the goal term should be rewritten. This is\ndemonstrated by the following alternative proof of commutativity of\naddition from the lemma [addnCA], which we have proved before:\n\n*)\n\nLemma addnC: forall m n, m + n = n + m.\nProof.\nmove=> m n. \nrewrite -{1}[n]addn0.\nby rewrite addnCA addn0. \nQed.\n\n(** \n\nThe first rewriting with [addn0] \"adds\" [0] to the first occurrence of\n[addn0], so the left-hand side of the equality becomes [m + (n +\n0)]. The next rewriting employs the lemma [addnCA], so we get [n + (m\n+ 0) = n + m] as the goal, and the last one \"removes\" zero, so the\nresult trivially follows.\n\n*)\n\n\n(** * Indexed datatype families as rewriting rules\n\nIn this chapter we have already seen how defining indexed datatype\nfamilies makes it possible for Coq to provide a convenient rewriting\nmachinery, which is implicitly invoked by case analysis on such\nfamilies' refined types, thanks to sophisticated Coq's unification\nprocedure.\n\nAlthough so far this approach has been demonstrated by only one\nindexed type family example---propositional equality, defined by means\nof the [eq] family, in this section, concluding the chapter, we will\nshow how to define other client-specific rewriting rules. Let us start\nfrom a motivating example in the form of an \"obvious\" lemma.\n\n*)\n\nLemma huh n m: (m <= n) /\\ (m > n) -> False.\n\n(**\n\nFrom now on, we will be consistently including yet another SSReflect\nmodules, [ssrbool] and [eqtype], %\\ssrm{ssrbool}\\ssrm{eqtype}% into\nour development. The need for them is due to the smooth combination of\nreasoning with [Prop]ositions and [bool]eans, which is a subject of\nthe next chapter. Even though in SSReflect's library, relations on\nnatural numbers, such as [<=] and [>], are defined as _boolean_\nfunctions, so far we recommend to the reader to think of them as of\npredicates defined in [Prop] and, therefore, valid arguments to the\n[/\\] connective.\n\nAlthough the statement is somewhat obvious, in the setting of Coq's\ninductive definition of natural numbers it should be no big surprise\nthat it is proved by induction. We present the proof here, leaving the\ndetails aside, so the reader could figure them out on his own, as a\nsimple exercise.%\\ssrt{elim}\\ssrt{suff:}\\ssrtl{//}%\n\n*)\n\nProof.\nsuff X: m <= n -> ~(m > n) by case=>/X. \nby elim: m n => [ | m IHm ] [ | n] //; exact: IHm n.\nQed.\n\nDefinition maxn m n := if m < n then n else m.\n\nLemma max_is_max m n: n <= maxn m n /\\ m <= maxn m n.\n\n(** \n\nThe stated lemma [max_is_max] can be, indeed, proved by induction on\n[m] and [n], which is a rather tedious exercise, so we will not be\nfollowing this path.\n*)\n\nAbort.\n\n(* ** Encoding custom rewriting rules *)\n\nInductive leq_xor_gtn m n : bool -> bool -> Set :=\n  | LeqNotGtn of m <= n : leq_xor_gtn m n true false\n  | GtnNotLeq of n < m  : leq_xor_gtn m n false true.\n\n\n(** \n\nHowever, this is not yet enough to enjoy the custom rewriting and case\nanalysis on these two variant. At this moment, the datatype family\n[leq_xor_gtn], whose constructors' indices encode a truth table's\n\"rows\", specifies two substitutions in the case when [m <= n] and [n <\nm], respectively and diagrammatically looks as follows:\n\n<<\n         |   C1  |   C2\n-------------------------\nm <= n   | true  | false\n-------------------------\nn < m    | false | true\n>>\n\nThe boolean values in the cells specify what the values of C1 and C2\nwill be substituted _with_ in each of the two cases. However, the\ntable does not capture, what to substitute them _for_.  Therefore, our\nnext task is to provide suitable variants for C1 and C2, so the table\nwould describe a real situation and capture exactly the \"case\nanalysis\" intuition. This values of the columns are captured by the\nfollowing lemma, which, informally speaking, states that the table\nwith this particular values of C1 and C2 \"makes sense\".\n*)\n\nLemma leqP m n : leq_xor_gtn m n (m <= n) (n < m).\nProof.\nrewrite ltnNge. \nby case X: (m <= n); constructor=>//; rewrite ltnNge X.\nQed.\n\n(*\nMoreover, the lemma [leqP], which we have just proved, delivers the\nnecessary instance of the \"truth\" table, which we can now case-analyse\nagainst.\n\n*)\n\n(** ** Using custom rewriting rules  *)\n\nLemma huh' n m: (m <= n) /\\ (m > n) -> False.\nProof.\n\nmove/andP.  \n\n(**\n\n[[\n  n : nat\n  m : nat\n  ============================\n   m <= n < m -> False\n]]\n\nThe top assumption [m <= n < m] of the goal is just a syntactic sugar\nfor [(m <= n) && (n < m)]. \n*)\n\ncase:leqP.\n\n(** \n\n[[\n  n : nat\n  m : nat\n  ============================\n   m <= n -> true && false -> False\n\nsubgoal 2 (ID 638) is:\n n < m -> false && true -> False\n]]\n\nNow, considering a boolean value [true && false] in a goal simply as a\nproposition [(true && false) = true], the proof is trivial by\nsimplification of the boolean conjunction.\n\n*)\n\ndone.\ndone.\nQed.\n\n(** \n\nThe proof of [huh'] is now indeed significantly shorter than the proof\nof its predecessor, [huh]. However, it might look like the definition\nof the rewriting rule [leq_xor_gtn] and its accompanying lemma [leqP]\nis quite narrowly-scoped, and it is not clear how useful it might be\nfor other proofs.\n*)\n\nLemma max_is_max m n: n <= maxn m n /\\ m <= maxn m n.\nProof.\n(** \n\nThe proof begins by unfolding the definition of [maxn].\n\n*)\nrewrite /maxn.\n\n(** \n[[\n  m : nat\n  n : nat\n  ============================\n   n <= (if m < n then n else m) /\\ m <= (if m < n then n else m)\n]]\n\nWe are now in the position to unleash our rewriting rule, which,\ntogether with simplifications by means of the [//] tactical\n%\\ssrtl{//}% does most of the job.\n\n*)\n\ncase: leqP=>//. \n\n(** \n\n[[\n  m : nat\n  n : nat\n  ============================\n   m < n -> n <= n /\\ m <= n\n]]\n\nThe res of the proof employs rewriting by some trivial lemmas from [ssrnat],\n%\\ssrm{ssrnat}% but conceptually is very easy.\n\n*)\n\nmove=>H; split.\n\nSearch _ (?X <= ?X).\n\nby apply: leqnn.\n\nSearch _ (?x < ?y) (?x <= ?y).\n\nby rewrite ltn_neqAle in H; case/andP: H.\nQed.\n\n(** \n\nThe key advantage we got out of using the custom rewriting rule,\ndefined as an indexed datatype family is lifting the need to prove _by\ninduction_ a statement, which one would intuitively prove by means of\n_case analysis_. In fact, all inductive reasoning was conveniently\n\"sealed\" by the proof of [leqP] and the lemmas it made use of, so just\nthe tailored \"truth table\"-like interface for case analysis was given\nto the client.\n*)\n\n\n(*******************************************************************)\n(**                     * Exercices *                              *)\n(*******************************************************************)\n\n(**\n---------------------------------------------------------------------\nExercise [Discriminating [===]]\n---------------------------------------------------------------------\nLet us change the statement of a lemma [disaster] for a little bit:\n*)\n\nLemma disaster2 : 1 === 2 -> False.\n\n(**\nNow, try to prove it using the same scheme. What goes wrong and how to\nfix it?\n*)\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(**\n---------------------------------------------------------------------\nExercise [Fun with rewritings]\n---------------------------------------------------------------------\nProve the following lemma by using the [rewrite] tactics.\n\n*)\n\nLemma rewrite_is_fun T (f : T -> T -> T) (a b c : T):\n  commutative f -> associative f ->\n  f (f b a) c = f a (f c b).     \nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\n(**\n---------------------------------------------------------------------\nExercise [Properties of maxn]\n---------------------------------------------------------------------\nProve the following lemmas about [maxn].\n*)\n\nLemma max_l m n: n <= m -> maxn m n = m.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma succ_max_distr_r n m : (maxn n m).+1 = maxn (n.+1) (m.+1).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nLemma plus_max_distr_l m n p: maxn (p + n) (p + m) = p + maxn n m.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n(** \n\nHint: it might be useful to employ the lemmas [ltnNge], [leqNgt],\n[ltnS] and similar to them from SSReflect's [ssrnat] module. Use the\n[Search] command to find propositions that might help you to deal with\nthe goal.\n\nHint: Forward-style reasoning via [suff] and [have] might be more\nintuitive.\n\nHint: A hypothesis of the shape [H: n < m] is a syntactic sugar for\n[H: n < m = true], since [n < m] in fact has type [bool], as will be\nexplained in the next lecture.\n\n*)\n\n(**\n---------------------------------------------------------------------\nExercise [More custom rewriting rules]\n---------------------------------------------------------------------\n\nLet us consider an instance of a more sophisticated custom rewriting\nrule, which now encodes a three-variant truth table for the ordering\nrelations on natural numbers.\n\n*)\n\nInductive nat_rels m n : bool -> bool -> bool -> Set :=\n  | CompareNatLt of m < n : nat_rels m n true false false\n  | CompareNatGt of m > n : nat_rels m n false true false\n  | CompareNatEq of m = n : nat_rels m n false false true.\n\n(** \n\nThe following rewriting lemma establishes a truth table for\n[nat_rels]. Step through the proofs (splitting the combined tactics\nwhenever it's necessary) to see what's going on.\n\n*)\n\nLemma natrelP m n : nat_rels m n (m < n) (n < m) (m == n).\nProof.\nrewrite ltn_neqAle eqn_leq; case: ltnP; first by constructor.\nby rewrite leq_eqVlt orbC; case: leqP; constructor; first exact/eqnP.\nQed.\n\n\n(** \nLet us define the minimum function [minn] on natural numbers as\nfollows:\n*)\n\nDefinition minn m n := if m < n then m else n.\n\n(**\nProve the following lemma about [minm] and [maxn]:\n*)\n\nLemma addn_min_max m n : minn m n + maxn m n = m + n.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\nEnd Rewriting.\n", "meta": {"author": "ilyasergey", "repo": "pnp", "sha": "dc32861434e072ed825ba1952cbb7acc4a3a4ce0", "save_path": "github-repos/coq/ilyasergey-pnp", "path": "github-repos/coq/ilyasergey-pnp/pnp-dc32861434e072ed825ba1952cbb7acc4a3a4ce0/lectures/Rewriting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7048325887922569}}
{"text": "(* determinant *)\n\nSet Nested Proofs Allowed.\nSet Implicit Arguments.\n\nRequire Import Utf8 Arith.\nImport List List.ListNotations.\nImport Init.Nat.\n\nRequire Import Misc RingLike IterAdd IterMul.\nRequire Import PermutationFun SortingFun SortRank.\nRequire Import MyVector Matrix PermutSeq Signature.\nRequire Import NatRingLike.\nImport matrix_Notations.\n\nDefinition set_minus {A} (eqb : A → _) E F :=\n  filter (λ e, negb (member eqb e F)) E.\n\nSection a.\n\nContext {T : Type}.\nContext (ro : ring_like_op T).\nContext (rp : ring_like_prop T).\n\n(*\n * three definitions of determinant\n *)\n\n(*\n   definition 1\n   det n M recursively computes determinant\n\n      0     n-1\n      |     |\n      v     v\n     ---------    ---------   ---------   ---------\n0    |x      |    | x     |   |  x    |   |   x   |\n     | ......| -  |. .....| + |.. ....| - |... ...| + etc.\n     | ......|    |. .....|   |.. ....|   |... ...|\nn-1  | ......|    |. .....|   |.. ....|   |... ...|\n     ---------    ---------   ---------   ---------\n\n   each term is the term \"x\" multiplied by det (n-1) of\n   the sub-matrix represented by the dots. The \"x\" goes through\n   the first row.\n*)\n\nFixpoint determinant_loop n (M : matrix T) :=\n  match n with\n  | 0 => 1%L\n  | S n' =>\n      ∑ (j = 1, n),\n      minus_one_pow (S j) * mat_el M 1 j *\n      determinant_loop n' (subm 1 j M)\n  end.\n\nDefinition det M := determinant_loop (mat_nrows M) M.\nArguments det M%M.\n\n(* definition 2\n   determinant by sum of products involving all permutations of columns,\n   aka \"Leibniz formula\";\n   sum of product of the factors a_{i,σ(i)} where σ goes through all\n   permutations of the naturals of the interval [0, n-1].\n   The permutations generated are in the same order as the\n   terms generated by the determinant defined by induction on\n   the size of the matrix.\n     The order happens to be the canonical (alphabetical) order.\n   Example for n=3\n     = [[0; 1; 2]; [0; 2; 1]; [1; 0; 2]; [1; 2; 0]; [2; 0; 1]; [2; 1; 0]]\n   Having the same terms order, the proof of equality of both definitions\n   of both determinants is easy.\n   This definitions holds n! terms.\n   See PermutSeq.v *)\n\nDefinition det' (M : matrix T) :=\n  let n := mat_nrows M in\n  ∑ (k = 0, fact n - 1),\n    ε (canon_sym_gr_list n k) *\n    ∏ (i = 1, n), mat_el M i ((canon_sym_gr_list n k).(i) + 1).\n\nArguments det' M%M.\n\n(* definition 3\n   determinant by sum of products like in definition 2, but running with all\n   combinations of columns, even with repetitions; the signatures ε of the\n   terms using twice the same column are 0 by definition of ε; the\n   remaining terms, whose ε is not 0, i.e. 1 or -1, are the ones when all\n   selected columns are different. It holds n^n terms *)\n\nDefinition cart_prod_rep_seq n := cart_prod (repeat (seq 1 n) n).\n\n(*\nCompute (cart_prod_rep_seq 3).\nCompute (cart_prod (repeat (seq 0 10) 2)).\n*)\n\nDefinition det'' (M : matrix T) :=\n  let n := mat_nrows M in\n  ∑ (l ∈ cart_prod_rep_seq n), ε l * ∏ (i = 1, n), mat_el M i l.(i).\n\n(* *)\n\nTheorem fold_det : ∀ M, determinant_loop (mat_nrows M) M = det M.\nProof. easy. Qed.\n\nTheorem determinant_zero : ∀ (M : matrix T),\n  determinant_loop 0 M = 1%L.\nProof. easy. Qed.\n\nTheorem determinant_succ : ∀ n (M : matrix T),\n  determinant_loop (S n) M =\n     ∑ (j = 1, S n),\n     minus_one_pow (S j) * mat_el M 1 j *\n     determinant_loop n (subm 1 j M).\nProof. easy. Qed.\n\n(*\nEnd a.\nCompute (length (cart_prod [[2;3];[5;7;2];[8;3];[7;2]])).\nCompute (length (cart_prod [[3;7;4;1];[0;6;2;7];[1;3;1;1];[18;3;2;1]])).\nCompute (length (cart_prod [[3;7;4;1];[0;6;2;7];[1;3;1;1];[18;3;1]])).\nCompute (length (cart_prod [[7;4;1];[0;6;2;7];[1;3;1;1];[18;3;1]])).\nCompute (length (cart_prod [[7;4;1];[2;7];[1;3;1;1];[18;3;1]])).\nArguments det {T ro} M%M.\nArguments det' {T ro} M%M.\nArguments det'' {T ro} M%M.\nRequire Import RnglAlg.Qrl.\nRequire Import RnglAlg.Rational.\nImport Q.Notations.\nOpen Scope Q_scope.\nCompute (let M := mk_mat [[3;7;4;1];[0;6;2;7];[1;3;1;1];[18;3;2;1]] in det M).\nCompute (let M := mk_mat [[3;7;4;1];[0;6;2;7];[1;3;1;1];[18;3;2;1]] in det' M).\nCompute (let M := mk_mat [[3;7;4;1];[0;6;2;7];[1;3;1;1];[18;3;2;1]] in det'' M).\nCompute (let M := mk_mat [] in det M).\nCompute (let M := mk_mat [] in det' M).\nCompute (let M := mk_mat [] in det'' M).\nCompute (let M := mk_mat [[3]] in det M).\nCompute (let M := mk_mat [[3]] in det' M).\nCompute (let M := mk_mat [[3]] in det'' M).\n*)\n\nTheorem rngl_summation_list_incl : ∀ A eqd la lb (f : A → T),\n  NoDup la\n  → NoDup lb\n  → la ⊂ lb\n  → ∑ (a ∈ la), f a =\n    ∑ (a ∈ lb), if ListDec.In_dec eqd a la then f a else 0.\nProof.\nintros * Hnda Hndb Hlab.\ninduction la as [| a]. {\n  cbn.\n  rewrite rngl_summation_list_empty; [ | easy ].\n  symmetry.\n  now apply all_0_rngl_summation_list_0.\n}\nrewrite rngl_summation_list_cons.\nspecialize (NoDup_remove [] la a Hnda) as H1.\ncbn in H1.\ndestruct H1 as (Hnd1, Hala).\nspecialize (IHla Hnd1).\nrewrite IHla; [ | now intros i Hi; apply Hlab; right ].\nassert (Ha : a ∈ lb) by now apply Hlab; left.\napply In_split in Ha.\ndestruct Ha as (lb1 & lb2 & Hlb); rewrite Hlb.\ndo 2 rewrite rngl_summation_list_app.\ndo 2 rewrite rngl_summation_list_cons.\ndestruct (ListDec.In_dec eqd a la) as [H| H]; [ easy | clear H ].\nrewrite rngl_add_0_l.\ndestruct (ListDec.In_dec eqd a (a :: la)) as [H| H]; [ clear H | ]. 2: {\n  now exfalso; apply H; left.\n}\nsymmetry; rewrite rngl_add_comm, rngl_add_assoc.\nrewrite rngl_add_add_swap.\nf_equal; [ f_equal | ]. {\n  apply rngl_summation_list_eq_compat.\n  intros i Hi.\n  destruct (ListDec.In_dec eqd i (a :: la)) as [H1| H1]. {\n    destruct (ListDec.In_dec eqd i la) as [H| H]; [ easy | ].\n    destruct H1 as [H1| H1]; [ clear H | easy ].\n    subst i.\n    rewrite Hlb in Hndb.\n    apply NoDup_remove_2 in Hndb.\n    exfalso; apply Hndb.\n    now apply in_or_app; left.\n  }\n  destruct (ListDec.In_dec eqd i la) as [H2| H2]; [ | easy ].\n  now exfalso; apply H1; right.\n} {\n  apply rngl_summation_list_eq_compat.\n  intros i Hi.\n  destruct (ListDec.In_dec eqd i (a :: la)) as [H1| H1]. {\n    destruct (ListDec.In_dec eqd i la) as [H| H]; [ easy | ].\n    destruct H1 as [H1| H1]; [ clear H | easy ].\n    subst i.\n    rewrite Hlb in Hndb.\n    apply NoDup_remove_2 in Hndb.\n    exfalso; apply Hndb.\n    now apply in_or_app; right.\n  }\n  destruct (ListDec.In_dec eqd i la) as [H2| H2]; [ | easy ].\n  now exfalso; apply H1; right.\n}\nQed.\n\nTheorem iter_list_mul_same_length : ∀ A (ll : list (list A)) n,\n  (∀ l, l ∈ ll → length l = n)\n  → iter_list ll (λ c l, c * length l) 1 = n ^ length ll.\nProof.\nintros * Hll.\ninduction ll as [| l]; [ now rewrite iter_list_empty | ].\nrewrite iter_list_cons; cbn; cycle 1.\n  apply Nat.add_0_r.\n  apply Nat.mul_1_r.\n  apply Nat.mul_assoc.\nrewrite Hll; [ f_equal | now left ].\napply IHll.\nintros l1 Hl1.\nnow apply Hll; right.\nQed.\n\nTheorem cart_prod_rep_seq_length : ∀ n, n ≠ 0 → length (cart_prod_rep_seq n) = n ^ n.\nProof.\nintros * Hnz.\nunfold cart_prod_rep_seq.\nrewrite cart_prod_length; [ | now destruct n ].\nrewrite iter_list_mul_same_length with (n := n). 2: {\n  intros l Hl.\n  apply repeat_spec in Hl; subst l.\n  apply seq_length.\n}\nf_equal; apply repeat_length.\nQed.\n\nFixpoint cart_prod_rep_seq_inv n l :=\n  match l with\n  | [] => 0\n  | a :: l' => pred a * n ^ length l' + cart_prod_rep_seq_inv n l'\n  end.\n\nFixpoint old_cart_prod_rep_seq_inv_loop n l :=\n  match l with\n  | [] => 0\n  | a :: l' => pred a + n * old_cart_prod_rep_seq_inv_loop n l'\n  end.\n\nDefinition old_cart_prod_rep_seq_inv n l := old_cart_prod_rep_seq_inv_loop n (rev l).\n\n(*\nCompute (\n  let n := 3 in\n  map (λ l, (cart_prod_rep_seq_inv n l, old_cart_prod_rep_seq_inv n l)) (cart_prod_rep_seq n)\n).\n*)\n\nTheorem in_cart_prod_repeat_iff : ∀ m n l,\n  n = 0 ∧ l = [] ∨\n  n ≠ 0 ∧ length l = n ∧ (∀ i : nat, i ∈ l → 1 ≤ i ≤ m)\n  ↔ l ∈ cart_prod (repeat (seq 1 m) n).\nProof.\nintros.\nsplit. {\n  intros [(Hnz, H1)| (Hnz & Hn & Hm)]; [ now subst n l; left | ].\n  apply (in_cart_prod_iff 0).\n  rewrite repeat_length.\n  split; [ easy | ].\n  intros i Hi.\n  rewrite List_nth_repeat.\n  rewrite Hn in Hi.\n  destruct (lt_dec i n) as [H| H]; [ clear H | easy ].\n  apply in_seq.\n  specialize (Hm (nth i l 0)) as H1.\n  assert (H : nth i l 0 ∈ l) by now apply nth_In; rewrite Hn.\n  specialize (H1 H); clear H.\n  split; [ easy | ].\n  now apply Nat.lt_succ_r.\n} {\n  intros Hl.\n  apply (in_cart_prod_iff 0) in Hl.\n  rewrite repeat_length in Hl.\n  destruct Hl as (Hln, Hl).\n  destruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n    left; subst n.\n    split; [ easy | now apply length_zero_iff_nil in Hnz ].\n  }\n  right.\n  split; [ easy | ].\n  split; [ easy | ].\n  intros i Hi.\n  apply (In_nth _ _ 0) in Hi.\n  destruct Hi as (j & Hjl & Hj); subst i.\n  specialize (Hl j Hjl) as H1.\n  rewrite List_nth_repeat in H1.\n  rewrite Hln in Hjl.\n  destruct (lt_dec j n) as [H| H]; [ clear H | easy ].\n  apply in_seq in H1.\n  split; [ easy | ].\n  now apply Nat.lt_succ_r.\n}\nQed.\n\nTheorem in_cart_prod_rep_seq_iff : ∀ n l,\n  n = 0 ∧ l = [] ∨\n  n ≠ 0 ∧ length l = n ∧ (∀ i, i ∈ l → 1 ≤ i ≤ n)\n  ↔ l ∈ cart_prod_rep_seq n.\nProof.\nintros.\nnow apply in_cart_prod_repeat_iff.\nQed.\n\nTheorem NoDup_cart_prod_repeat : ∀ m n,\n  NoDup (cart_prod (repeat (seq 1 m) n)).\nProof.\nintros.\nrevert m.\ninduction n; intros. {\n  constructor; [ easy | constructor ].\n}\ncbn.\nspecialize (IHn m) as H1.\nremember (cart_prod (repeat (seq 1 m) n)) as ll eqn:Hll.\nrewrite flat_map_concat_map.\napply NoDup_concat_if. {\n  intros l Hl.\n  apply in_map_iff in Hl.\n  destruct Hl as (i & Hl & Hi); subst l.\n  apply FinFun.Injective_map_NoDup; [ | easy ].\n  intros j k Hjk.\n  now injection Hjk.\n}\nintros i j Hij a Ha.\ndestruct (lt_dec i m) as [Him| Him]. 2: {\n  apply Nat.nlt_ge in Him.\n  rewrite nth_overflow in Ha; [ easy | now rewrite List_map_seq_length ].\n}\nrewrite (List_map_nth' 0) in Ha; [ | now rewrite seq_length ].\ndestruct (lt_dec j m) as [Hjm| Hjm]. 2: {\n  apply Nat.nlt_ge in Hjm.\n  rewrite nth_overflow; [ easy | now rewrite List_map_seq_length ].\n}\nrewrite (List_map_nth' 0); [ | now rewrite seq_length ].\nintros Hb.\napply in_map_iff in Ha.\napply in_map_iff in Hb.\ndestruct Ha as (u & H & Ha); subst a.\ndestruct Hb as (v & H & Hb).\ninjection H; clear H; intros H Hji; subst v.\nrewrite seq_nth in Hji; [ | easy ].\nrewrite seq_nth in Hji; [ | easy ].\nnow apply Nat.succ_inj in Hji; symmetry in Hji.\nQed.\n\nTheorem NoDup_cart_prod_rep_seq : ∀ n, NoDup (cart_prod_rep_seq n).\nProof.\nintros n.\nunfold cart_prod_rep_seq.\napply NoDup_cart_prod_repeat.\nQed.\n\nTheorem cart_prod_rep_seq_inj : ∀ n i j,\n  n ≠ 0\n  → i < n ^ n\n  → j < n ^ n\n  → nth i (cart_prod_rep_seq n) [] = nth j (cart_prod_rep_seq n) []\n  → i = j.\nProof.\nintros * Hnz Hi Hj Hij.\napply (NoDup_nth (cart_prod_rep_seq n) []); [ | | | easy ]. {\n  apply NoDup_cart_prod_rep_seq.\n} {\n  now rewrite cart_prod_rep_seq_length.\n} {\n  now rewrite cart_prod_rep_seq_length.\n}\nQed.\n\n(* det and det' are equal *)\n\nTheorem det_is_det' :\n  rngl_has_opp = true →\n  ∀ (M : matrix T),\n  is_square_matrix M = true\n  → det M = det' M.\nProof.\nintros Hop * Hm.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nunfold det'.\nremember (mat_nrows M) as n eqn:Hr; symmetry in Hr.\nunfold det.\nrewrite Hr.\nrevert M Hm Hr.\ninduction n; intros. {\n  cbn.\n  rewrite rngl_summation_only_one.\n  rewrite all_1_rngl_product_1; [ | intros * Hi; flia Hi ].\n  unfold ε, iter_seq, iter_list; unfold \"<?\"; cbn.\n  symmetry; apply rngl_mul_1_l.\n}\nrewrite determinant_succ.\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  subst n; cbn.\n  rewrite rngl_summation_only_one; cbn.\n  rewrite rngl_summation_only_one; cbn.\n  rewrite rngl_product_only_one; cbn.\n  now do 2 rewrite rngl_mul_1_r.\n}\nerewrite rngl_summation_eq_compat. 2: {\n  intros i Hi.\n  rewrite IHn; cycle 1. {\n    apply is_squ_mat_subm; [ rewrite Hr | rewrite Hr; flia Hi | easy ].\n    split; [ easy | now apply -> Nat.succ_le_mono ].\n  } {\n    rewrite mat_nrows_subm, Hr; cbn.\n    apply Nat.sub_0_r.\n  }\n  easy.\n}\ncbn - [ canon_sym_gr_list fact nth ].\nclear IHn.\nerewrite rngl_summation_eq_compat. 2: {\n  intros i Hi.\n  rewrite rngl_mul_summation_distr_l; [ | easy ].\n  easy.\n}\ncbn - [ canon_sym_gr_list fact nth ].\nrewrite (rngl_summation_shift 1); [ | flia ].\nrewrite Nat.sub_diag, Nat_sub_succ_1.\nrewrite rngl_summation_summation_distr.\nrewrite <- Nat.sub_succ_l; [ | apply Nat.neq_0_lt_0, fact_neq_0 ].\nrewrite Nat_sub_succ_1.\nrewrite <- Nat_fact_succ.\napply rngl_summation_eq_compat.\nintros k Hk.\n(* elimination of \"mat_el M 1 (1 + k / (n!)\" *)\nsymmetry.\nrewrite rngl_product_split_first; [ | flia ].\nrewrite Nat.sub_diag.\nrewrite Nat.add_1_r.\ncbn - [ canon_sym_gr_list nth ].\nremember (mat_el M 1 _) as x eqn:Hx.\nrewrite (ε_mul_comm Hop).\nsymmetry.\nrewrite <- rngl_mul_assoc.\nrewrite (minus_one_pow_mul_comm Hop).\ndo 3 rewrite <- rngl_mul_assoc.\nf_equal.\n(* elimination done *)\n(* separation factors \"∏\" and \"ε\" *)\nrewrite (ε_mul_comm Hop).\nrewrite <- rngl_mul_assoc.\nf_equal. {\n  (* equality of the two \"∏\" *)\n  rewrite (rngl_product_shift 1); [ | flia Hnz ].\n  rewrite Nat.sub_diag.\n  rewrite (rngl_product_shift 2 2); [ | flia Hnz ].\n  rewrite Nat.sub_diag.\n  rewrite Nat.sub_succ.\n  apply rngl_product_eq_compat.\n  intros i Hi.\n  rewrite Nat.add_comm, Nat.add_sub.\n  unfold mat_el.\n  do 3 rewrite Nat.add_sub.\n  replace (2 + i - 1) with (S i) by flia.\n  cbn - [ subm fact ].\n  rewrite (List_map_nth' 0). 2: {\n    rewrite canon_sym_gr_list_length; flia Hi Hnz.\n  }\n  cbn - [ butn ].\n  rewrite (List_map_nth' []). 2: {\n    apply is_scm_mat_iff in Hm.\n    destruct Hm as (Hcr & Hc).\n    rewrite butn_length, fold_mat_nrows, Hr.\n    unfold \"<?\"; cbn; flia Hi Hnz.\n  }\n  rewrite Nat.sub_0_r.\n  unfold succ_when_ge, Nat.b2n.\n  rewrite if_leb_le_dec.\n  destruct (le_dec (k / n!) _) as [H1| H1]. {\n    rewrite nth_butn_before; [ | easy ].\n    rewrite nth_butn_before; [ | easy ].\n    now rewrite (Nat.add_1_r i).\n  } {\n    apply Nat.nle_gt in H1.\n    rewrite Nat.add_0_r.\n    rewrite nth_butn_after; [ | easy ].\n    rewrite nth_butn_before; [ | easy ].\n    now rewrite Nat.add_1_r.\n  }\n  (* end proof equality of the two \"∏\" *)\n}\n(* equality of the two \"ε\" *)\nsymmetry.\nrewrite minus_one_pow_succ; [ | easy ].\nrewrite minus_one_pow_succ; [ | easy ].\nrewrite rngl_opp_involutive; [ | easy ].\napply ε_of_sym_gr_permut_succ; [ easy | ].\napply (le_lt_trans _ ((S n)! - 1)); [ easy | ].\napply Nat.sub_lt; [ | easy ].\napply Nat.le_succ_l, Nat.neq_0_lt_0, fact_neq_0.\nQed.\n\n(* det' and det'' are equal *)\n\nTheorem det'_is_det'' :\n  rngl_has_opp = true →\n  ∀ (M : matrix T), det' M = det'' M.\nProof.\nintros Hop *.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  unfold det', det''.\n  now rewrite Hrz.\n}\nunfold det''.\nremember (mat_nrows M) as n eqn:Hn.\nunfold det'.\nrewrite <- Hn.\nspecialize (fact_neq_0 n) as Hfnz.\nspecialize (Nat.pow_nonzero n n Hrz) as Hpnz.\nerewrite rngl_summation_change_var. 2: {\n  intros i Hi.\n  apply canon_sym_gr_list_inv_canon_sym_gr_list with (n := n).\n  flia Hi Hfnz.\n}\nrewrite Nat.sub_0_r.\nreplace (λ i, canon_sym_gr_list n i) with (canon_sym_gr_list n) by easy.\nrewrite <- Nat.sub_succ_l; [ | flia Hfnz ].\nrewrite Nat.sub_succ, Nat.sub_0_r.\nreplace (map _ _) with (canon_sym_gr_list_list n) by easy.\nerewrite rngl_summation_list_eq_compat. 2: {\n  intros i Hi.\n  rewrite canon_sym_gr_list_canon_sym_gr_list_inv. 2: {\n    apply in_map_iff in Hi.\n    destruct Hi as (j & Hji & Hj); subst i.\n    apply in_seq in Hj.\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  }\n  easy.\n}\ncbn.\nassert (Hincl : canon_sym_gr_list_list n ⊂ map (map pred) (cart_prod_rep_seq n)). {\n  intros l Hl.\n  apply in_map_iff in Hl.\n  apply in_map_iff.\n  destruct Hl as (i & Hil & Hi).\n  subst l.\n  apply in_seq in Hi; cbn in Hi; destruct Hi as (_, Hi).\n  exists (map S (canon_sym_gr_list n i)).\n  rewrite map_map.\n  erewrite map_ext_in. 2: {\n    intros j Hj.\n    now rewrite Nat.pred_succ.\n  }\n  rewrite map_id.\n  split; [ easy | ].\n  apply in_cart_prod_rep_seq_iff.\n  right.\n  split; [ easy | ].\n  split; [ now rewrite map_length, canon_sym_gr_list_length | ].\n  intros j Hj.\n  apply in_map_iff in Hj.\n  destruct Hj as (k & Hkj & Hk).\n  subst j.\n  split; [ flia | ].\n  apply Nat.le_succ_l.\n  apply (In_nth _ _ 0) in Hk.\n  destruct Hk as (j & Hj & Hjk).\n  rewrite canon_sym_gr_list_length in Hj; subst k.\n  now apply canon_sym_gr_list_ub.\n}\nsymmetry.\nreplace (cart_prod_rep_seq n) with (map (λ l, map S (map pred l)) (cart_prod_rep_seq n)). 2: {\n  erewrite map_ext_in. 2: {\n    intros l Hl.\n    rewrite map_map.\n    apply in_cart_prod_rep_seq_iff in Hl.\n    destruct Hl as [Hl| Hl]; [ now exfalso | ].\n    destruct Hl as (_ & _ & Hl).\n    erewrite map_ext_in. 2: {\n      intros i Hi.\n      specialize (Hl i Hi).\n      rewrite Nat.succ_pred_pos; [ | flia Hl ].\n      easy.\n    }\n    now rewrite map_id.\n  }\n  apply map_id.\n}\nrewrite <- map_map.\nrewrite rngl_summation_list_map.\nassert (H1 :\n  ∑ (l ∈ map (map pred) (cart_prod_rep_seq n)),\n  ε l * ∏ (j = 1, n), mat_el M j (l.(j) + 1) =\n  ∑ (l ∈ map (map pred) (cart_prod_rep_seq n)),\n  if ListDec.In_dec (list_eq_dec Nat.eq_dec) l (canon_sym_gr_list_list n) then\n    ε l * ∏ (j = 1, n), mat_el M j (l.(j) + 1)\n  else 0). {\n  apply rngl_summation_list_eq_compat.\n  intros l Hl.\n  destruct (ListDec.In_dec (list_eq_dec Nat.eq_dec)) as [H1| H1]; [ easy | ].\n  assert (H : ε l = 0%L). {\n    apply ε_when_dup; [ easy | ].\n    intros Hnd.\n    apply H1; clear H1.\n    apply in_map_iff.\n    apply in_map_iff in Hl.\n    destruct Hl as (l1 & H & Hl); subst l; rename l1 into l.\n    apply in_cart_prod_rep_seq_iff in Hl.\n    destruct Hl as [Hl| Hl]; [ easy | ].\n    destruct Hl as (_ & Hln & Hin).\n    exists (canon_sym_gr_list_inv n (map pred l)).\n    assert (Hp : permut_seq_with_len n (map pred l)). {\n      unfold permut_seq_with_len.\n      rewrite map_length.\n      split; [ | easy ].\n      apply permut_seq_iff.\n      split; [ | easy ].\n      intros j Hj.\n      rewrite map_length, Hln.\n      apply in_map_iff in Hj.\n      destruct Hj as (a & Hj & Ha); subst j.\n      specialize (Hin _ Ha).\n      flia Hin.\n    }\n    split; [ now apply canon_sym_gr_list_canon_sym_gr_list_inv | ].\n    apply in_seq.\n    split; [ easy | ].\n    rewrite Nat.add_0_l.\n    now apply canon_sym_gr_list_inv_ub.\n  }\n  rewrite H.\n  now apply rngl_mul_0_l.\n}\nerewrite rngl_summation_list_eq_compat. 2: {\n  intros l Hl.\n  rewrite ε_map_S.\n  erewrite rngl_product_eq_compat. 2: {\n    intros i Hi.\n    rewrite (List_map_nth' 0). 2: {\n      apply in_map_iff in Hl.\n      destruct Hl as (l1 & H & Hl); subst l.\n      rename l1 into l.\n      rewrite map_length.\n      apply in_cart_prod_rep_seq_iff in Hl.\n      destruct Hl as [Hl| Hl]; [ easy | ].\n      destruct Hl as (_ & Hln & Hin).\n      rewrite Hln; flia Hi.\n    }\n    rewrite <- Nat.add_1_r.\n    easy.\n  }\n  easy.\n}\ncbn.\nrewrite H1.\nsymmetry.\napply rngl_summation_list_incl; [ | | easy ]. {\n  unfold canon_sym_gr_list_list.\n  apply (NoDup_map_iff 0).\n  rewrite seq_length.\n  intros * Hi Hj Hij.\n  rewrite seq_nth in Hij; [ | easy ].\n  rewrite seq_nth in Hij; [ | easy ].\n  cbn in Hij.\n  now apply (canon_sym_gr_list_inj n).\n} {\n  apply NoDup_map_inv with (f := map S).\n  rewrite map_map.\n  erewrite map_ext_in. 2: {\n    intros l Hl.\n    rewrite map_map.\n    erewrite map_ext_in. 2: {\n      intros i Hi.\n      apply in_cart_prod_rep_seq_iff in Hl.\n      destruct Hl as [Hl| Hl]; [ now exfalso | ].\n      destruct Hl as (_ & _ & Hl).\n      specialize (Hl i Hi).\n      rewrite Nat.succ_pred_pos; [ | flia Hl ].\n      easy.\n    }\n    now rewrite map_id.\n  }\n  rewrite map_id.\n  apply NoDup_cart_prod_rep_seq.\n}\nQed.\n\n(* det and det'' are equal *)\n\nTheorem det_is_det'' :\n  rngl_has_opp = true →\n  ∀ (M : matrix T),\n  is_square_matrix M = true\n  → det M = det'' M.\nProof.\nintros Hop * Hm.\nrewrite (det_is_det' Hop); [ | easy ].\napply (det'_is_det'' Hop).\nQed.\n\n(* multilinearity *)\n\nTheorem determinant_multilinear :\n  rngl_mul_is_comm = true →\n  rngl_has_opp = true →\n  ∀ n (M : matrix T) i a b U V,\n  is_square_matrix M = true\n  → mat_nrows M = n\n  → vect_size U = n\n  → vect_size V = n\n  → 1 ≤ i ≤ n\n  → det (mat_repl_vect i M (a × U + b × V)%V) =\n       (a * det (mat_repl_vect i M U) +\n        b * det (mat_repl_vect i M V))%L.\nProof.\nintros Hic Hop * Hsm Hr Hu Hv Hi.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nspecialize (squ_mat_ncols _ Hsm) as Hcn.\n(* using the snd version of determinants: determinant' *)\nrewrite det_is_det'; try easy. 2: {\n  apply mat_repl_vect_is_square; [ congruence | cbn | easy ].\n  rewrite map2_length.\n  do 2 rewrite map_length, fold_vect_size.\n  rewrite Hu, Hv.\n  now rewrite Nat.min_id.\n}\nrewrite det_is_det'; try easy. 2: {\n  apply mat_repl_vect_is_square; [ congruence | congruence | easy ].\n}\nrewrite det_is_det'; try easy. 2: {\n  apply mat_repl_vect_is_square; [ congruence | congruence | easy ].\n}\nunfold det'.\n(* simplification of the lhs *)\nremember (a × U + b × V)%V as UV eqn:HUV.\nassert (Hvm : vect_size UV = mat_nrows M). {\n  rewrite Hr, HUV; cbn.\n  rewrite map2_length.\n  do 2 rewrite map_length.\n  do 2 rewrite fold_vect_size.\n  rewrite Hu, Hv.\n  apply Nat.min_id.\n}\nrewrite mat_repl_vect_nrows; [ | easy ].\nrewrite mat_repl_vect_nrows; [ | congruence ].\nrewrite mat_repl_vect_nrows; [ | congruence ].\nrewrite Hr.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  assert (Hkn : k < n!). {\n    eapply le_lt_trans; [ apply Hk | ].\n    apply Nat.sub_lt; [ | flia ].\n    apply Nat.neq_0_lt_0, fact_neq_0.\n  }\n  erewrite rngl_product_eq_compat. 2: {\n    intros j Hj.\n    rewrite mat_el_repl_vect; cycle 1. {\n      now apply squ_mat_is_corr.\n    } {\n      subst UV; cbn.\n      rewrite map2_length.\n      do 2 rewrite map_length.\n      do 2 rewrite fold_vect_size.\n      rewrite Hu, Hv, Nat.min_id.\n      flia Hj.\n    } {\n      rewrite Hr; flia Hj.\n    } {\n      rewrite Hcn, Hr.\n      rewrite Nat.add_1_r.\n      split; [ flia | ].\n      apply canon_sym_gr_list_ub; [ easy | flia Hj ].\n    } {\n      now rewrite Hcn, Hr.\n    }\n    unfold vect_el.\n    cbn - [ Nat.eq_dec ].\n    easy.\n  }\n  easy.\n}\ncbn - [ mat_el ].\n(* put a and b inside the sigma in the rhs *)\nrewrite rngl_mul_summation_distr_l; [ | easy ].\nrewrite rngl_mul_summation_distr_l; [ | easy ].\nsymmetry.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  assert (Hkn : k < fact n). {\n    specialize (fact_neq_0 n) as Hnz.\n    flia Hk Hnz.\n  }\n  rewrite rngl_mul_assoc.\n  rewrite <- (ε_mul_comm Hop).\n  erewrite rngl_product_eq_compat. 2: {\n    intros j Hj.\n    rewrite mat_el_repl_vect; cycle 1. {\n      now apply squ_mat_is_corr.\n    } {\n      rewrite Hu; flia Hj.\n    } {\n      rewrite Hr; flia Hj.\n    } {\n      cbn.\n      rewrite Hcn, Hr, Nat.add_1_r.\n      split; [ flia | ].\n      apply canon_sym_gr_list_ub; [ easy | flia Hj ].\n    } {\n      now rewrite Hcn, Hr.\n    }\n    now unfold vect_el; cbn.\n  }\n  easy.\n}\nrewrite rngl_add_comm.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  assert (Hkn : k < fact n). {\n    specialize (fact_neq_0 n) as Hnz.\n    flia Hk Hnz.\n  }\n  rewrite rngl_mul_assoc.\n  rewrite <- (ε_mul_comm Hop).\n  erewrite rngl_product_eq_compat. 2: {\n    intros j Hj.\n    rewrite mat_el_repl_vect; cycle 1. {\n      now apply squ_mat_is_corr.\n    } {\n      rewrite Hv; flia Hj.\n    } {\n      rewrite Hr; flia Hj.\n    } {\n      rewrite Hcn, Hr, Nat.add_1_r.\n      split; [ flia | ].\n      apply canon_sym_gr_list_ub; [ easy | flia Hj ].\n    } {\n      now rewrite Hcn, Hr.\n    }\n    now unfold vect_el; cbn.\n  }\n  easy.\n}\nrewrite rngl_add_comm.\n(* make one summation *)\nrewrite <- rngl_summation_add_distr.\napply rngl_summation_eq_compat.\nintros k Hk.\ndo 2 rewrite <- rngl_mul_assoc.\nrewrite <- rngl_mul_add_distr_l.\n(* elimination of the ε-s *)\nf_equal.\n(* *)\nassert (Hkn : k < fact n). {\n  specialize (fact_neq_0 n) as Hnz.\n  flia Hk Hnz.\n}\nassert (H : i - 1 < n) by flia Hi.\nspecialize (canon_sym_gr_surjective Hkn H) as Hp; clear H.\ndestruct Hp as (p & Hp & Hpp).\nrewrite (rngl_product_split (p + 1)); [ | flia Hp ].\nrewrite rngl_product_split_last; [ | flia ].\nerewrite rngl_product_eq_compat. 2: {\n  intros j Hj.\n  replace (j - 1 - 1) with (j - 2) by flia.\n  destruct (Nat.eq_dec (nth (j - 2) (canon_sym_gr_list n k) 0 + 1) i)\n    as [Hpj| Hpj]. {\n    exfalso.\n    rewrite <- Hpj in Hpp.\n    rewrite Nat.add_sub in Hpp.\n    symmetry in Hpp.\n    apply nth_canon_sym_gr_list_inj1 in Hpp; [ | easy | flia Hp Hj | easy ].\n    flia Hj Hpp.\n  }\n  easy.\n}\nrewrite rngl_add_comm.\nrewrite (rngl_product_split (p + 1)); [ | flia Hp ].\nrewrite rngl_product_split_last; [ | flia ].\nerewrite rngl_product_eq_compat. 2: {\n  intros j Hj.\n  replace (j - 1 - 1) with (j - 2) by flia.\n  destruct (Nat.eq_dec (nth (j - 2) (canon_sym_gr_list n k) 0 + 1) i)\n    as [Hpj| Hpj]. {\n    exfalso.\n    rewrite <- Hpj, Nat.add_sub in Hpp.\n    symmetry in Hpp.\n    apply nth_canon_sym_gr_list_inj1 in Hpp; [ | easy | flia Hp Hj | easy ].\n    flia Hj Hpp.\n  }\n  easy.\n}\nrewrite rngl_add_comm.\nsymmetry.\nrewrite (rngl_product_split (p + 1)); [ | flia Hp ].\nrewrite rngl_product_split_last; [ | flia ].\nerewrite rngl_product_eq_compat. 2: {\n  intros j Hj.\n  replace (j - 1 - 1) with (j - 2) by flia.\n  destruct (Nat.eq_dec (nth (j - 2) (canon_sym_gr_list n k) 0 + 1) i)\n    as [Hpj| Hpj]. {\n    exfalso.\n    rewrite <- Hpj, Nat.add_sub in Hpp.\n    symmetry in Hpp.\n    apply nth_canon_sym_gr_list_inj1 in Hpp; [ | easy | flia Hp Hj | easy ].\n    flia Hj Hpp.\n  }\n  easy.\n}\nrewrite Nat.add_sub.\nrewrite Hpp.\ndestruct (Nat.eq_dec i i) as [H| H]; [ clear H | easy ].\ndo 4 rewrite rngl_mul_assoc.\nsubst UV.\ncbn - [ mat_el ].\nrewrite map2_nth with (a := 0%L) (b := 0%L); cycle 1. {\n  now rewrite map_length, fold_vect_size, Hu.\n} {\n  now rewrite map_length, fold_vect_size, Hv.\n}\nrewrite (List_map_nth' 0%L); [ | now rewrite fold_vect_size, Hu ].\nrewrite (List_map_nth' 0%L); [ | now rewrite fold_vect_size, Hv ].\ndo 2 rewrite fold_vect_el.\nrewrite Nat.sub_add; [ | flia Hi ].\nrewrite <- if_eqb_eq_dec, Nat.eqb_refl.\nrewrite <- if_eqb_eq_dec, Nat.eqb_refl.\nrewrite <- if_eqb_eq_dec, Nat.eqb_refl.\n(* elimination of the following term (q) *)\nremember\n  (∏ (i0 = 2, p + 1),\n   mat_el M (i0 - 1) (nth (i0 - 2) (canon_sym_gr_list n k) O + 1))\n  as q eqn:Hq.\nsymmetry.\nrewrite (rngl_mul_comm Hic a).\nrewrite (rngl_mul_comm Hic b).\ndo 5 rewrite <- rngl_mul_assoc.\nrewrite <- rngl_mul_add_distr_l.\nf_equal.\nclear q Hq.\nerewrite rngl_product_eq_compat. 2: {\n  intros j Hj.\n  destruct (Nat.eq_dec (nth (j - 1) (canon_sym_gr_list n k) 0 + 1) i)\n    as [Hpj| Hpj]. {\n    rewrite <- Hpj, Nat.add_sub in Hpp.\n    symmetry in Hpp.\n    apply nth_canon_sym_gr_list_inj1 in Hpp; [ | easy | flia Hp Hj | easy ].\n    flia Hj Hpp.\n  }\n  easy.\n}\nsymmetry.\nerewrite rngl_product_eq_compat. 2: {\n  intros j Hj.\n  destruct (Nat.eq_dec (nth (j - 1) (canon_sym_gr_list n k) 0 + 1) i)\n    as [Hpj| Hpj]. {\n    rewrite <- Hpj, Nat.add_sub in Hpp.\n    symmetry in Hpp.\n    apply nth_canon_sym_gr_list_inj1 in Hpp; [ | easy | flia Hp Hj | easy ].\n    flia Hj Hpp.\n  }\n  easy.\n}\nsymmetry.\nrewrite rngl_add_comm.\nerewrite rngl_product_eq_compat. 2: {\n  intros j Hj.\n  destruct (Nat.eq_dec (nth (j - 1) (canon_sym_gr_list n k) 0 + 1) i)\n    as [Hpj| Hpj]. {\n    rewrite <- Hpj, Nat.add_sub in Hpp.\n    symmetry in Hpp.\n    apply nth_canon_sym_gr_list_inj1 in Hpp; [ | easy | flia Hp Hj | easy ].\n    flia Hj Hpp.\n  }\n  easy.\n}\ncbn.\nrewrite rngl_add_comm.\ndo 2 rewrite rngl_mul_assoc.\nnow rewrite <- rngl_mul_add_distr_r.\nQed.\n\nDefinition mat_swap_rows i1 i2 (M : matrix T) :=\n  mk_mat (list_swap_elem [] (mat_list_list M) (i1 - 1) (i2 - 1)).\n\nTheorem mat_swap_rows_is_square : ∀ (M : matrix T) p q,\n  1 ≤ p ≤ mat_nrows M\n  → 1 ≤ q ≤ mat_nrows M\n  → is_square_matrix M = true\n  → is_square_matrix (mat_swap_rows p q M) = true.\nProof.\nintros * Hp Hq Hsm.\nremember (mat_nrows M) as n eqn:Hr.\nsymmetry in Hr.\nspecialize (squ_mat_ncols _ Hsm) as Hcn.\nspecialize (squ_mat_is_corr M Hsm) as Hco.\napply is_scm_mat_iff in Hsm.\napply is_scm_mat_iff.\ndestruct Hsm as (Hcr & Hc).\ncbn; unfold list_swap_elem.\nrewrite List_map_seq_length.\nunfold mat_swap_rows, list_swap_elem; cbn.\nsplit. {\n  unfold mat_ncols; cbn.\n  rewrite fold_mat_nrows; rewrite Hr.\n  rewrite (List_map_hd 0); [ | rewrite seq_length; flia Hp ].\n  rewrite List_seq_hd; [ | flia Hp ].\n  rewrite Hc; [ now intros Hn; subst n | ].\n  apply nth_In; rewrite fold_mat_nrows; rewrite Hr.\n  unfold transposition.\n  do 2 rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec 0 (p - 1)); [ flia Hq | ].\n  destruct (Nat.eq_dec 0 (q - 1)); [ flia Hp | ].\n  flia Hp.\n} {\n  intros la Hla.\n  apply in_map_iff in Hla.\n  rewrite fold_mat_nrows, Hr in Hla.\n  destruct Hla as (a & Ha & Hla).\n  apply in_seq in Hla; subst la.\n  rewrite fold_corr_mat_ncols; [ easy | easy | rewrite Hr ].\n  unfold transposition.\n  do 2 rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec a (p - 1)); [ flia Hq | ].\n  destruct (Nat.eq_dec a (q - 1)); [ flia Hp | ].\n  easy.\n}\nQed.\n\nTheorem mat_swap_rows_nrows : ∀ (M : matrix T) p q,\n  mat_nrows (mat_swap_rows p q M) = mat_nrows M.\nProof.\nintros.\nunfold mat_swap_rows; cbn.\nunfold list_swap_elem.\nrewrite map_length.\nnow rewrite seq_length.\nQed.\n\nTheorem mat_swap_rows_ncols : ∀ (M : matrix T),\n  is_correct_matrix M = true\n  → ∀ p q, 1 ≤ p ≤ mat_nrows M → 1 ≤ q ≤ mat_nrows M →\n  mat_ncols (mat_swap_rows p q M) = mat_ncols M.\nProof.\nintros * Hcm * Hp Hq.\ngeneralize Hcm; intros H.\napply is_scm_mat_iff in H.\ndestruct H as (Hcr, Hc).\ndestruct (Nat.eq_dec (mat_nrows M) 0) as [Hrz| Hrz]. {\n  destruct M as (ll); cbn in Hrz.\n  now apply length_zero_iff_nil in Hrz; subst ll.\n}\napply Nat.neq_0_lt_0 in Hrz.\nunfold mat_swap_rows; cbn.\nunfold list_swap_elem.\nunfold mat_ncols; cbn.\ndo 2 rewrite List_hd_nth_0.\nrewrite fold_corr_mat_ncols; [ | easy | easy ].\ndestruct M as (ll); cbn.\ndestruct ll as [| la]; [ easy | cbn ].\nunfold transposition.\ndo 2 rewrite if_eqb_eq_dec.\ndestruct (Nat.eq_dec 0 (p - 1)) as [Hpz| Hpz]. {\n  destruct q; [ easy | ].\n  destruct q; [ easy | ].\n  rewrite Nat_sub_succ_1.\n  cbn - [ In ] in Hcr, Hc, Hq.\n  apply Hc; right.\n  apply nth_In; flia Hq.\n}\ndestruct (Nat.eq_dec 0 (q - 1)) as [Hqz| Hqz]. {\n  destruct p; [ easy | ].\n  destruct p; [ easy | ].\n  rewrite Nat_sub_succ_1.\n  cbn - [ In ] in Hcr, Hc, Hp.\n  apply Hc; right.\n  apply nth_In; flia Hp.\n}\neasy.\nQed.\n\nTheorem nth_transposition_canon_sym_gr_list_inj : ∀ n k p q i j,\n  k < n!\n  → p < n\n  → q < n\n  → i < n\n  → j < n\n  → nth (transposition p q i) (canon_sym_gr_list n k) 0 =\n    nth (transposition p q j) (canon_sym_gr_list n k) 0\n  → i = j.\nProof.\nintros * Hkn Hpn Hqn Hin Hjn Hij.\nunfold transposition in Hij.\ndo 4 rewrite if_eqb_eq_dec in Hij.\ndestruct (Nat.eq_dec i p) as [Hip| Hip]. {\n  destruct (Nat.eq_dec j p) as [Hjp| Hjp]; [ congruence | ].\n  destruct (Nat.eq_dec j q) as [Hjq| Hjq]. {\n    apply nth_canon_sym_gr_list_inj1 in Hij; [ | easy | easy | easy ].\n    congruence.\n  }\n  apply Nat.neq_sym in Hjq.\n  now apply nth_canon_sym_gr_list_inj1 in Hij.\n}\ndestruct (Nat.eq_dec i q) as [Hiq| Hiq]. {\n  destruct (Nat.eq_dec j p) as [Hjp| Hjp]. {\n    apply nth_canon_sym_gr_list_inj1 in Hij; [ | easy | easy | easy ].\n    congruence.\n  }\n  destruct (Nat.eq_dec j q) as [Hjq| Hjq]; [ congruence | ].\n  apply Nat.neq_sym in Hjp.\n  now apply nth_canon_sym_gr_list_inj1 in Hij.\n}\ndestruct (Nat.eq_dec j p) as [Hjp| Hjp]. {\n  now apply nth_canon_sym_gr_list_inj1 in Hij.\n}\ndestruct (Nat.eq_dec j q) as [Hjq| Hjq]. {\n  now apply nth_canon_sym_gr_list_inj1 in Hij.\n}\nnow apply nth_canon_sym_gr_list_inj1 in Hij.\nQed.\n\nTheorem determinant_alternating :\n  rngl_mul_is_comm = true →\n  rngl_has_opp = true →\n  ∀ (M : matrix T) p q,\n  p ≠ q\n  → 1 ≤ p ≤ mat_nrows M\n  → 1 ≤ q ≤ mat_nrows M\n  → is_square_matrix M = true\n  → det (mat_swap_rows p q M) = (- det M)%L.\nProof.\nintros Hic Hop * Hpq Hp Hq Hsm.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nremember (mat_nrows M) as n eqn:Hr; symmetry in Hr.\nrewrite (det_is_det' Hop). 2: {\n  rewrite <- Hr in Hp, Hq.\n  now apply mat_swap_rows_is_square.\n}\nunfold det'.\nrewrite mat_swap_rows_nrows.\nrewrite Hr.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  rewrite (rngl_product_shift 1); [ | flia Hp ].\n  rewrite Nat.sub_diag.\n  erewrite rngl_product_eq_compat. 2: {\n    intros i Hi.\n    now rewrite Nat.add_comm, Nat.add_sub.\n  }\n  easy.\n}\ncbn - [ mat_swap_rows ].\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  rewrite rngl_product_change_var with\n    (g := transposition (p - 1) (q - 1)) (h := transposition (p - 1) (q - 1)).\n  2: {\n    intros i Hi.\n    apply transposition_involutive.\n  }\n  rewrite Nat.sub_0_r.\n  rewrite <- Nat.sub_succ_l; [ | flia Hp ].\n  rewrite Nat_sub_succ_1.\n  easy.\n}\ncbn - [ mat_swap_rows ].\nassert (Hp' : p - 1 < n) by flia Hp.\nassert (Hq' : q - 1 < n) by flia Hq.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  rewrite (rngl_product_list_permut _ Nat.eqb_eq) with\n      (lb := seq 0 n); [ | easy | ]. 2: {\n    remember (map _ _) as la eqn:Hla.\n    replace n with (length la) by now rewrite Hla, List_map_seq_length.\n    subst la.\n    now apply transposition_permut_seq_with_len.\n  }\n  easy.\n}\ncbn - [ mat_swap_rows ].\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  assert (Hkn : k < n!). {\n    specialize (fact_neq_0 n) as Hn.\n    flia Hk Hn.\n  }\n  erewrite rngl_product_list_eq_compat. 2: {\n    intros i Hi.\n    replace (mat_el _ _ _) with\n      (mat_el M (i + 1)\n         (nth (transposition (p - 1) (q - 1) i) (canon_sym_gr_list n k) 0 + 1)).\n    2: {\n      cbn.\n      unfold mat_el; f_equal.\n      unfold list_swap_elem.\n      do 2 rewrite Nat.add_sub.\n      rewrite (List_map_nth' 0). 2: {\n        rewrite seq_length.\n        rewrite fold_mat_nrows, Hr.\n        apply in_seq in Hi.\n        now apply transposition_lt.\n      }\n      rewrite fold_mat_nrows, Hr.\n      unfold transposition.\n      do 2 rewrite if_eqb_eq_dec.\n      destruct (Nat.eq_dec i (p - 1)) as [Hip| Hip]. {\n        subst i.\n        rewrite seq_nth; [ | easy ].\n        rewrite Nat.add_0_l.\n        rewrite Nat.eqb_refl.\n        apply Nat.neq_sym in Hpq.\n        destruct (Nat.eq_dec (q - 1) (p - 1)) as [H| H]; [ | easy ].\n        now rewrite H.\n      }\n      rewrite if_eqb_eq_dec.\n      destruct (Nat.eq_dec i (q - 1)) as [Hiq| Hiq]. {\n        subst i.\n        rewrite seq_nth; [ | easy ].\n        rewrite Nat.add_0_l.\n        rewrite <- if_eqb_eq_dec.\n        now rewrite Nat.eqb_refl.\n      }\n      apply in_seq in Hi.\n      rewrite seq_nth; [ | easy ].\n      rewrite Nat.add_0_l.\n      rewrite if_eqb_eq_dec.\n      destruct (Nat.eq_dec i (p - 1)) as [H| H]; [ easy | clear H ].\n      now destruct (Nat.eq_dec i (q - 1)).\n    }\n    easy.\n  }\n  easy.\n}\ncbn.\nset (f := λ k, list_swap_elem 0 (canon_sym_gr_list n k) (p - 1) (q - 1)).\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  erewrite rngl_product_list_eq_compat. 2: {\n    intros i Hi.\n    apply in_seq in Hi.\n    replace (nth _ _ 0) with\n       (nth i (list_swap_elem 0 (canon_sym_gr_list n k) (p - 1) (q - 1)) 0).\n    2: {\n(* lemme à faire *)\n      unfold list_swap_elem.\n      rewrite (List_map_nth' 0). 2: {\n        now rewrite seq_length, canon_sym_gr_list_length.\n      }\n      rewrite seq_nth; [ easy | now rewrite canon_sym_gr_list_length ].\n    }\n    fold (f k).\n    easy.\n  }\n  easy.\n}\ncbn.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  assert (Hkn : k < n!). {\n    specialize (fact_neq_0 n) as Hn.\n    flia Hk Hn.\n  }\n  erewrite rngl_product_seq_product; [ | flia Hp ].\n  rewrite Nat.add_0_l.\n  replace (canon_sym_gr_list n k) with\n     (map (λ i, nth (transposition (p - 1) (q - 1) i) (f k) 0) (seq 0 n)).\n  2: {\n    rewrite List_map_nth_seq with (d := 0).\n    rewrite canon_sym_gr_list_length.\n    apply map_ext_in.\n    intros i Hi; cbn.\n    apply in_seq in Hi.\n    unfold f, list_swap_elem.\n    rewrite (List_map_nth' 0). 2: {\n      rewrite seq_length, canon_sym_gr_list_length.\n      now apply transposition_lt.\n    }\n    rewrite seq_nth. 2: {\n      rewrite canon_sym_gr_list_length.\n      now apply transposition_lt.\n    }\n    rewrite Nat.add_0_l.\n    now rewrite transposition_involutive.\n  }\n  replace (map (λ i, nth (transposition (p - 1) (q - 1) i) (f k) 0) (seq 0 n))\n  with (f k ° map (λ i, transposition (p - 1) (q - 1) i) (seq 0 n)). 2: {\n    unfold \"°\"; cbn.\n    now rewrite map_map.\n  }\n  rewrite sign_comp; [ | easy | ]. 2: {\n    split. 2: {\n      rewrite List_map_seq_length.\n      unfold f.\n      rewrite list_swap_elem_length.\n      symmetry.\n      apply canon_sym_gr_list_length.\n    }\n    apply permut_seq_iff.\n    split. {\n      intros i Hi.\n      rewrite List_map_seq_length.\n      apply In_nth with (d := 0) in Hi.\n      rewrite List_map_seq_length in Hi.\n      destruct Hi as (j & Hj & Hji).\n      rewrite (List_map_nth' 0) in Hji; [ | now rewrite seq_length ].\n      rewrite seq_nth in Hji; [ | easy ].\n      rewrite <- Hji.\n      now apply transposition_lt.\n    }\n    apply (NoDup_map_iff 0).\n    rewrite seq_length.\n    intros i j Hi Hj Hij.\n    rewrite seq_nth in Hij; [ | easy ].\n    rewrite seq_nth in Hij; [ | easy ].\n    cbn in Hij.\n    unfold transposition in Hij.\n    do 4 rewrite if_eqb_eq_dec in Hij.\n    destruct (Nat.eq_dec i (p - 1)) as [Hip| Hip]. {\n      subst i.\n      destruct (Nat.eq_dec j (p - 1)) as [Hjp| Hjp]; [ easy | ].\n      symmetry in Hij.\n      destruct (Nat.eq_dec j (q - 1)); [ | easy ].\n      congruence.\n    }\n    destruct (Nat.eq_dec i (q - 1)) as [Hiq| Hiq]. {\n      subst i.\n      symmetry in Hij.\n      destruct (Nat.eq_dec j (p - 1)) as [Hjp| Hjp]; [ easy | ].\n      now destruct (Nat.eq_dec j (q - 1)).\n    }\n    destruct (Nat.eq_dec j (p - 1)) as [Hjp| Hjp]; [ easy | ].\n    now destruct (Nat.eq_dec j (q - 1)).\n  }\n  easy.\n}\ncbn.\nerewrite rngl_summation_eq_compat. 2: {\n  intros k (_, Hk).\n  rewrite (rngl_mul_comm Hic (ε (f k))).\n  rewrite <- rngl_mul_assoc.\n  rewrite (transposition_signature Hop); [ easy | | easy | easy ].\n  flia Hp Hq Hpq.\n}\ncbn - [ f ].\nrewrite <- rngl_mul_summation_distr_l; [ | easy ].\nrewrite rngl_mul_opp_l; [ | easy ].\nf_equal.\nrewrite rngl_mul_1_l.\nsymmetry.\nset (g := λ k, canon_sym_gr_list_inv n (f k)).\nrewrite rngl_summation_change_var with (g := g) (h := g). 2: {\n  intros k (_, Hk).\n  assert (Hkn : k < n!). {\n    specialize (fact_neq_0 n) as Hn.\n    flia Hk Hn.\n  }\n  unfold g, f.\n  unfold list_swap_elem.\n  do 2 rewrite canon_sym_gr_list_length.\n  erewrite map_ext_in. 2: {\n    intros i Hi; apply in_seq in Hi.\n    rewrite canon_sym_gr_list_canon_sym_gr_list_inv. 2: {\n(* lemme à faire ? *)\n      split; [ | now rewrite map_length, seq_length ].\n      apply permut_seq_iff.\n      split. {\n        intros j Hj.\n        rewrite map_length, seq_length.\n        apply in_map_iff in Hj.\n        destruct Hj as (m & Hmj & Hm).\n        apply in_seq in Hm.\n        rewrite <- Hmj.\n        apply canon_sym_gr_list_ub; [ easy | ].\n        apply transposition_lt; [ flia Hp | flia Hq | easy ].\n      } {\n        apply (NoDup_map_iff 0).\n        rewrite seq_length.\n        intros u v Hu Hv Huv.\n        rewrite seq_nth in Huv; [ | easy ].\n        rewrite seq_nth in Huv; [ | easy ].\n        cbn in Huv.\n        now apply nth_transposition_canon_sym_gr_list_inj in Huv.\n      }\n    }\n    rewrite (List_map_nth' 0). 2: {\n      rewrite seq_length.\n      now apply transposition_lt.\n    }\n    rewrite seq_nth. 2: {\n      now apply transposition_lt.\n    }\n    rewrite Nat.add_0_l.\n    rewrite transposition_involutive.\n    easy.\n  }\n  rewrite <- List_map_nth_seq'; [ | now rewrite canon_sym_gr_list_length ].\n  now apply canon_sym_gr_list_inv_canon_sym_gr_list.\n}\nrewrite Nat.sub_0_r.\nrewrite <- Nat.sub_succ_l; [ | apply Nat.neq_0_lt_0, fact_neq_0 ].\nrewrite Nat_sub_succ_1.\nrewrite (rngl_summation_list_permut _ Nat.eqb_eq) with (lb := seq 0 n!);\n    cycle 1. {\n  remember (map _ _) as la eqn:Hla.\n  replace n! with (length la) by now rewrite Hla, List_map_seq_length.\n  subst la.\n(* lemma to do? *)\n  unfold g, f.\n  apply permut_seq_iff.\n  split. {\n    intros i Hi.\n    rewrite map_length, seq_length.\n    apply in_map_iff in Hi.\n    destruct Hi as (j & Hji & Hj).\n    apply in_seq in Hj.\n    rewrite <- Hji.\n    apply canon_sym_gr_list_inv_ub.\n    apply list_swap_elem_permut_seq_with_len; [ easy | easy | ].\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  } {\n    apply (NoDup_map_iff 0).\n    rewrite seq_length.\n    intros i j Hi Hj Hij.\n    rewrite seq_nth in Hij; [ | easy ].\n    rewrite seq_nth in Hij; [ | easy ].\n    do 2 rewrite Nat.add_0_l in Hij.\n    apply rank_of_permut_in_canon_gr_list_inj in Hij; cycle 1. {\n      apply list_swap_elem_permut_seq_with_len; [ easy | easy | ].\n      now apply canon_sym_gr_list_permut_seq_with_len.\n    } {\n      apply list_swap_elem_permut_seq_with_len; [ easy | easy | ].\n      now apply canon_sym_gr_list_permut_seq_with_len.\n    }\n(* lemme à faire ? *)\n    unfold list_swap_elem in Hij.\n    do 2 rewrite canon_sym_gr_list_length in Hij.\n    apply nth_canon_sym_gr_list_inj2 with (n := n); [ easy | easy | ].\n    intros k Hkn.\n    apply ext_in_map with (a := transposition (p - 1) (q - 1) k) in Hij. 2: {\n      apply in_seq.\n      split; [ flia | ].\n      now apply transposition_lt.\n    }\n    now rewrite transposition_involutive in Hij.\n  }\n}\nrewrite det_is_det'; [ | easy | easy ].\nunfold det'.\nrewrite rngl_summation_seq_summation; [ | apply fact_neq_0 ].\nrewrite Nat.add_0_l.\nrewrite Hr.\napply rngl_summation_eq_compat.\nintros k Hk.\nassert (Hkn : k < n!). {\n  specialize (fact_neq_0 n) as Hn.\n  flia Hk Hn.\n}\nassert (Hc : canon_sym_gr_list n k = f (g k)). {\n  unfold g, f.\n  rewrite canon_sym_gr_list_canon_sym_gr_list_inv. 2: {\n    apply list_swap_elem_permut_seq_with_len; [ easy | easy | ].\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  }\n  rewrite list_swap_elem_involutive; [ easy | | ]. {\n    now rewrite canon_sym_gr_list_length.\n  } {\n    now rewrite canon_sym_gr_list_length.\n  }\n}\nf_equal; [ now rewrite Hc | ].\nrewrite (rngl_product_shift 1); [ | flia Hp ].\napply rngl_product_eq_compat.\nintros i Hi.\nrewrite Nat.add_comm, Nat.add_sub.\nnow rewrite Hc.\nQed.\n\nTheorem determinant_same_rows :\n  rngl_mul_is_comm = true →\n  rngl_has_opp = true →\n  rngl_characteristic = 0 →\n  (rngl_is_integral || rngl_has_inv_or_quot)%bool = true →\n  ∀ (M : matrix T) p q,\n  is_square_matrix M = true\n  → p ≠ q\n  → 1 ≤ p ≤ mat_nrows M\n  → 1 ≤ q ≤ mat_nrows M\n  → (∀ j, 1 ≤ j → mat_el M p j = mat_el M q j)\n  → det M = 0%L.\nProof.\nintros Hic Hop Hch Hii * Hsm Hpq Hpn Hqn Hjpq.\nspecialize (proj2 rngl_has_opp_or_subt_iff) as Hos.\nspecialize (Hos (or_introl Hop)).\nmove Hos before Hop.\nremember (mat_nrows M) as n eqn:Hr; symmetry in Hr.\nspecialize (squ_mat_ncols M Hsm) as Hc.\nassert (HM : det M = (- det M)%L). {\n  rewrite <- Hr in Hpn, Hqn.\n  rewrite <- determinant_alternating with (p := p) (q := q); try easy.\n  f_equal.\n  destruct M as (ll); cbn in *.\n  unfold mat_swap_rows; cbn; f_equal.\n  rewrite (List_map_nth_seq ll) with (d := []) at 1.\n  apply map_ext_in.\n  intros i Hi; apply in_seq in Hi.\n  unfold transposition.\n  do 2 rewrite if_eqb_eq_dec.\n  destruct (Nat.eq_dec i (p - 1)) as [Hip| Hip]. {\n    subst i.\n    rewrite List_map_nth_seq with (d := 0%L); symmetry.\n    rewrite List_map_nth_seq with (d := 0%L); symmetry.\n    apply is_scm_mat_iff in Hsm.\n    cbn in Hsm.\n    destruct Hsm as (Hcz, Hsm).\n    rewrite Hsm; [ | now apply nth_In ].\n    rewrite Hsm; [ | apply nth_In; flia Hqn ].\n    apply map_ext_in.\n    intros j Hj.\n    specialize (Hjpq (S j)).\n    rewrite Nat_sub_succ_1 in Hjpq.\n    apply Hjpq; flia.\n  }\n  destruct (Nat.eq_dec i (q - 1)) as [Hiq| Hiq]. {\n    subst i.\n    rewrite List_map_nth_seq with (d := 0%L); symmetry.\n    rewrite List_map_nth_seq with (d := 0%L); symmetry.\n    apply is_scm_mat_iff in Hsm.\n    cbn in Hsm.\n    destruct Hsm as (Hcz, Hsm).\n    rewrite Hsm; [ | now apply nth_In ].\n    rewrite Hsm; [ | apply nth_In; flia Hpn ].\n    apply map_ext_in.\n    intros j Hj.\n    specialize (Hjpq (S j)).\n    rewrite Nat_sub_succ_1 in Hjpq.\n    symmetry; apply Hjpq; flia.\n  }\n  easy.\n}\napply rngl_add_move_0_r in HM; [ | easy ].\nnow apply (eq_rngl_add_same_0 Hos Hii Hch) in HM.\nQed.\n\n(* transpositions list of permutation *)\n\nFixpoint first_non_fixpoint it i σ :=\n  match it with\n  | 0 => None\n  | S it' => if i =? σ i then first_non_fixpoint it' (i + 1) σ else Some i\n  end.\n\nFixpoint tlopf_loop it n (σ : nat → nat) :=\n  match it with\n  | 0 => []\n  | S it' =>\n      match first_non_fixpoint n 0 σ with\n      | None => []\n      | Some i =>\n          let σ' := comp (transposition i (σ i)) σ in\n          (i, σ i) :: tlopf_loop it' n σ'\n      end\n  end.\n\n(* *)\n\nDefinition mat_mul_row_by_scal n k (M : matrix T) s :=\n  mk_mat\n    (map\n       (λ i,\n        map\n          (λ j, if Nat.eq_dec i k then (s * mat_el M i j)%L else mat_el M i j)\n          (seq 1 n))\n       (seq 1 n)).\n\n(* If we multiply a row (column) of A by a number, the determinant of\n   A will be multiplied by the same number. *)\n(* https://math.vanderbilt.edu/sapirmv/msapir/proofdet1.html\n   point 1 *)\n\n(* If the i-th row (column) in A is a sum of the i-th row (column) of\n   a matrix B and the i-th row (column) of a matrix C and all other\n   rows in B and C are equal to the corresponding rows in A (that is B\n   and C differ from A by one row only), then det(A)=det(B)+det(C). *)\n(* https://math.vanderbilt.edu/sapirmv/msapir/proofdet1.html\n   point 2 *)\n\n(* Well, since my definition of the discriminant only covers the\n   row 0, we can prove that only when i=0; this will able us to\n   prove the next theorem, swapping rows by going via row 0 *)\n\nTheorem det_add_row_row : ∀ n (A B C : matrix T),\n  n ≠ 0\n  → mat_nrows A = n\n  → mat_nrows B = n\n  → mat_nrows C = n\n  → is_square_matrix A = true\n  → is_square_matrix B = true\n  → is_square_matrix C = true\n  → (∀ j, mat_el A 1 j = (mat_el B 1 j + mat_el C 1 j)%L)\n  → (∀ i j, i ≠ 1 → mat_el B i j = mat_el A i j)\n  → (∀ i j, i ≠ 1 → mat_el C i j = mat_el A i j)\n  → det A = (det B + det C)%L.\nProof.\nintros * Hnz Hra Hrb Hrc Hsma Hsmb Hsmc Hbc Hb Hc.\nspecialize (squ_mat_ncols _ Hsma) as Hca.\nspecialize (squ_mat_ncols _ Hsmb) as Hcb.\nrewrite Hra in Hca.\nrewrite Hrb in Hcb.\ndestruct n; [ easy | clear Hnz; cbn ].\nassert (Hab : ∀ j, subm 1 j A = subm 1 j B). {\n  intros.\n  destruct A as (lla).\n  destruct B as (llb).\n  cbn in *.\n  unfold subm; f_equal.\n  cbn - [ butn ].\n  rewrite (List_map_nth_seq lla []).\n  rewrite (List_map_nth_seq llb []).\n  rewrite Hra, Hrb.\n  do 2 rewrite <- map_butn.\n  do 2 rewrite map_map.\n  apply map_ext_in.\n  intros u Hu.\n  destruct (Nat.eq_dec u 0) as [Huz| Huz]. {\n    subst u; cbn in Hu.\n    now apply in_seq in Hu.\n  }\n  rewrite (List_map_nth_seq (nth u lla []) 0%L).\n  rewrite (List_map_nth_seq (nth u llb []) 0%L).\n  apply is_scm_mat_iff in Hsma.\n  destruct Hsma as (_ & Hca').\n  apply in_butn, in_seq in Hu.\n  rewrite Hca'. 2: {\n    cbn; apply nth_In.\n    now rewrite Hra.\n  }\n  apply is_scm_mat_iff in Hsmb.\n  destruct Hsmb as (_ & Hcb').\n  rewrite Hcb'. 2: {\n    cbn; apply nth_In.\n    now rewrite Hrb.\n  }\n  f_equal; cbn; rewrite Hra, Hrb.\n  apply map_ext_in.\n  intros v Hv.\n  apply in_seq in Hv.\n  specialize (Hb (S u) (S v)).\n  do 2 rewrite Nat_sub_succ_1 in Hb.\n  symmetry; apply Hb; intros H; apply Huz.\n  now apply Nat.succ_inj in H.\n}\nassert (Hac : ∀ j, subm 1 j A = subm 1 j C). {\n  intros.\n  destruct A as (lla).\n  destruct C as (llc).\n  cbn in *.\n  unfold subm; f_equal.\n  cbn - [ butn ].\n  rewrite (List_map_nth_seq lla []).\n  rewrite (List_map_nth_seq llc []).\n  rewrite Hra, Hrc.\n  do 2 rewrite <- map_butn.\n  do 2 rewrite map_map.\n  apply map_ext_in.\n  intros u Hu.\n  destruct (Nat.eq_dec u 0) as [Huz| Huz]. {\n    subst u; cbn in Hu.\n    now apply in_seq in Hu.\n  }\n  rewrite (List_map_nth_seq (nth u lla []) 0%L).\n  rewrite (List_map_nth_seq (nth u llc []) 0%L).\n  apply is_scm_mat_iff in Hsma.\n  destruct Hsma as (_ & Hca').\n  apply in_butn, in_seq in Hu.\n  rewrite Hca'. 2: {\n    cbn; apply nth_In.\n    now rewrite Hra.\n  }\n  apply is_scm_mat_iff in Hsmc.\n  destruct Hsmc as (_ & Hcc').\n  rewrite Hcc'. 2: {\n    cbn; apply nth_In.\n    now rewrite Hrc.\n  }\n  f_equal; cbn; rewrite Hra, Hrc.\n  apply map_ext_in.\n  intros v Hv.\n  apply in_seq in Hv.\n  specialize (Hc (S u) (S v)).\n  do 2 rewrite Nat_sub_succ_1 in Hc.\n  symmetry; apply Hc; intros H; apply Huz.\n  now apply Nat.succ_inj in H.\n}\nunfold det; rewrite Hra, Hrb, Hrc.\ncbn.\nerewrite rngl_summation_eq_compat. 2: {\n  intros j Hj.\n  rewrite Hbc.\n  rewrite rngl_mul_add_distr_l.\n  rewrite rngl_mul_add_distr_r.\n  rewrite Hab at 1.\n  rewrite Hac at 1.\n  easy.\n}\ncbn.\nnow apply rngl_summation_add_distr.\nQed.\n\nTheorem rngl_product_map_permut :\n  rngl_mul_is_comm = true →\n   ∀ n f σ,\n  permut_seq_with_len n σ\n  → ∏ (i ∈ map (λ i, nth i σ 0) (seq 0 n)), f i = ∏ (i = 1, n), f (i - 1)%nat.\nProof.\nintros Hic * Hσ.\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]; [ now subst n | ].\nrewrite (rngl_product_list_permut _ Nat.eqb_eq) with\n    (lb := seq 0 n); [ | easy | ]. 2: {\n  destruct Hσ as (H1, H2).\n  rewrite <- H2 at 1.\n  now rewrite <- List_map_nth_seq, <- H2.\n}\nunfold iter_seq.\nrewrite Nat_sub_succ_1.\nrewrite <- seq_shift.\nreplace n with (S (n - 1) - 0) by flia Hnz.\nrewrite <- rngl_product_change_var; [ easy | ].\nintros i Hi.\nnow rewrite Nat.sub_succ, Nat.sub_0_r.\nQed.\n\nTheorem det_by_any_sym_gr :\n  rngl_has_opp = true →\n  rngl_characteristic ≠ 1 →\n  ∀ n (M : matrix T) (sg : list (list nat)),\n  n ≠ 0\n  → mat_nrows M = n\n  → is_square_matrix M = true\n  → is_sym_gr_list n sg\n  → det M =\n      ∑ (k = 0, n! - 1),\n        ε (nth k sg []) * ∏ (i = 1, n), mat_el M i ((nth k sg []).(i) + 1).\nProof.\nintros Hop H10 * Hnz Hr Hsm Hsg.\nrewrite (det_is_det' Hop); [ | easy ].\nunfold det'.\nrewrite Hr.\nset (g := λ i, canon_sym_gr_list_inv n (nth i sg [])).\nset (h := λ i, sym_gr_inv sg (canon_sym_gr_list n i)).\nrewrite rngl_summation_change_var with (g := g) (h := h). 2: {\n  intros i (_, Hi).\n  unfold g, h.\n  rewrite (nth_sym_gr_inv_sym_gr Hsg). 2: {\n    apply canon_sym_gr_list_permut_seq_with_len.\n    specialize (fact_neq_0 n) as H.\n    flia Hi H.\n  }\n  apply canon_sym_gr_list_inv_canon_sym_gr_list.\n  specialize (fact_neq_0 n) as H.\n  flia Hi H.\n}\nrewrite Nat.sub_0_r.\nrewrite <- Nat.sub_succ_l; [ | apply Nat.neq_0_lt_0, fact_neq_0 ].\nrewrite Nat_sub_succ_1.\nerewrite rngl_summation_list_eq_compat. 2: {\n  intros i Hi.\n  apply in_map_iff in Hi.\n  destruct Hi as (j & Hji & Hj).\n  apply in_seq in Hj.\n  unfold g.\n  rewrite canon_sym_gr_list_canon_sym_gr_list_inv. 2: {\n    split. {\n      apply Hsg; rewrite <- Hji.\n      now apply (sym_gr_inv_lt _ Hnz).\n    } {\n      destruct Hsg as (H1 & H2 & H3).\n      apply H1; rewrite <- Hji.\n      now apply (sym_gr_inv_lt _ Hnz).\n    }\n  }\n  easy.\n}\ncbn.\napply (rngl_summation_list_permut _ Nat.eqb_eq).\nrewrite Nat.sub_0_r.\nrewrite <- Nat.sub_succ_l; [ | apply Nat.neq_0_lt_0, fact_neq_0 ].\nrewrite Nat_sub_succ_1.\nremember (map _ _) as la eqn:Hla.\nreplace n! with (length la) by now rewrite Hla, List_map_seq_length.\nsubst la.\n(* lemma to do? *)\nunfold h.\napply permut_seq_iff.\nsplit. {\n  intros i Hi.\n  rewrite List_map_seq_length.\n  apply in_map_iff in Hi.\n  destruct Hi as (j & Hji & Hj).\n  apply in_seq in Hj.\n  rewrite <- Hji.\n  rewrite <- sym_gr_size with (sg := sg); [ | easy ].\n  now apply (sym_gr_inv_lt _ Hnz).\n} {\n  apply (NoDup_map_iff 0).\n  rewrite seq_length.\n  intros i j Hi Hj Hij.\n  rewrite seq_nth in Hij; [ | easy ].\n  rewrite seq_nth in Hij; [ | easy ].\n  do 2 rewrite Nat.add_0_l in Hij.\n  apply (@sym_gr_inv_inj n) in Hij; [ | easy | | ]; cycle 1. {\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  } {\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  }\n  now apply canon_sym_gr_list_inj in Hij.\n}\nQed.\n\nTheorem map_nth_permut_permut_permut_seq_with_len : ∀ n l1 l2,\n  permut_seq_with_len n l1\n  → permut_seq_with_len n l2\n  → permut_seq_with_len n (map (λ i, nth i l1 0) l2).\nProof.\nintros n l σ (Hl1, Hl2) (Hσ1, Hσ2).\nsplit; [ | now rewrite map_length ].\napply permut_seq_iff.\nsplit. {\n  intros i Hi; apply in_map_iff in Hi.\n  destruct Hi as (j & Hji & Hj).\n  rewrite map_length.\n  rewrite <- Hji.\n  rewrite Hσ2, <- Hl2.\n  apply permut_seq_ub; [ easy | ].\n  apply nth_In.\n  rewrite Hl2, <- Hσ2.\n  apply permut_seq_iff in Hσ1.\n  now apply Hσ1.\n} {\n  apply (NoDup_map_iff 0).\n  intros u v Hu Hv Huv.\n  apply permut_seq_iff in Hl1.\n  destruct Hl1 as (Ha1, Hn1).\n  apply (NoDup_nat _ Hn1) in Huv; cycle 1. {\n    rewrite Hl2, <- Hσ2.\n    apply permut_seq_iff in Hσ1.\n    now apply Hσ1, nth_In.\n  } {\n    rewrite Hl2, <- Hσ2.\n    apply permut_seq_iff in Hσ1.\n    now apply Hσ1, nth_In.\n  }\n  apply permut_seq_iff in Hσ1.\n  destruct Hσ1 as (Hσa1, Hσn1).\n  now apply (NoDup_nat _ Hσn1) in Huv.\n}\nQed.\n\nTheorem det_any_permut_l :\n  let ron := nat_ring_like_op in\n  rngl_mul_is_comm = true →\n  @rngl_has_opp T ro = true →\n  rngl_characteristic ≠ 1 →\n  ∀ n (M : matrix T) (σ : list nat),\n  n ≠ 0\n  → mat_nrows M = n\n  → is_square_matrix M = true\n  → permut_seq_with_len n σ\n  → det M =\n    (∑ (μ ∈ canon_sym_gr_list_list n), ε μ * ε σ *\n     ∏ (k = 0, n - 1), mat_el M (nth k σ 0 + 1) (nth k μ 0 + 1)).\nProof.\nintros ron Hic Hop H10 * Hnz Hr Hsm Hσ.\nsubst ron.\nerewrite rngl_summation_list_eq_compat. 2: {\n  intros μ Hμ.\n  assert (Hpμ : permut_seq_with_len n μ). {\n    apply in_map_iff in Hμ.\n    destruct Hμ as (i & Hiμ & Hi).\n    apply in_seq in Hi.\n    rewrite <- Hiμ.\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  }\n  remember (μ ° isort_rank Nat.leb σ) as ν eqn:Hν.\n  assert (Hσν : ν ° σ = μ). {\n    rewrite Hν.\n    assert (H : length (isort_rank Nat.leb σ) = n). {\n      rewrite isort_rank_length; apply Hσ.\n    }\n    destruct Hσ.\n    rewrite <- (permut_comp_assoc _ H); clear H; [ | easy | easy ].\n    rewrite permut_comp_isort_rank_l; [ | easy ].\n    apply comp_1_r.\n    destruct Hpμ; congruence.\n  }\n  subst ν.\n  rewrite <- Hσν at 1.\n  replace (ε ((μ ° isort_rank Nat.leb σ) ° σ)) with\n      (ε (μ ° isort_rank Nat.leb σ) * ε σ)%L. 2: {\n    destruct Hσ.\n    rewrite <- sign_comp; [ easy | easy | ].\n    now rewrite comp_length, isort_rank_length.\n  }\n  rewrite <- (rngl_mul_assoc _ (ε σ) (ε σ)).\n  rewrite NoDup_ε_square; [ | easy | ]. 2: {\n    destruct Hσ as (Hσ, _).\n    now apply permut_seq_iff in Hσ.\n  }\n  rewrite rngl_mul_1_r.\n  easy.\n}\ncbn.\nunfold canon_sym_gr_list_list.\nrewrite rngl_summation_list_map.\nrewrite rngl_summation_seq_summation; [ | apply fact_neq_0 ].\nrewrite Nat.add_0_l.\nerewrite rngl_summation_eq_compat. 2: {\n  intros i (_, Hi).\n  rewrite rngl_product_change_var with\n      (g := λ i, nth i (isort_rank Nat.leb σ) 0) (h := λ i, nth i σ 0). 2: {\n    intros j Hj.\n    apply permut_isort_permut; [ now destruct Hσ | ].\n    destruct Hσ as (Hσp, Hσl); rewrite Hσl.\n    flia Hj Hnz.\n  }\n  rewrite Nat.sub_0_r.\n  rewrite <- Nat.sub_succ_l; [ | flia Hnz ].\n  rewrite Nat_sub_succ_1.\n  erewrite rngl_product_list_eq_compat. 2: {\n    intros j Hj.\n    apply in_map_iff in Hj.\n    destruct Hj as (k & Hkj & Hk).\n    apply in_seq in Hk.\n    rewrite permut_permut_isort; [ | now destruct Hσ | ]. 2: {\n      rewrite <- Hkj.\n      destruct Hσ as (H1, H2).\n      rewrite <- H2 in Hk.\n      apply permut_seq_ub; [ easy | ].\n      now apply nth_In.\n    }\n    easy.\n  }\n  cbn.\n  rewrite rngl_product_map_permut; [ | easy | easy ].\n  easy.\n}\ncbn.\nset\n  (sg := map (λ k, canon_sym_gr_list n k ° isort_rank Nat.leb σ) (seq 0 n!)).\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  assert (Hkn : k < n!). {\n    specialize (fact_neq_0 n) as H.\n    flia Hk H.\n  }\n  replace (_ ° _) with (nth k sg []). 2: {\n    unfold sg.\n    rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n    now rewrite seq_nth.\n  }\n  erewrite rngl_product_eq_compat. 2: {\n    intros i Hi.\n    rewrite Nat.sub_add; [ | flia Hi ].\n    replace (nth _ _ 0) with (nth (i - 1) (nth k sg []) 0). 2: {\n      unfold sg.\n      rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n      rewrite seq_nth; [ | easy ].\n      rewrite Nat.add_0_l.\n      unfold \"°\".\n      rewrite (List_map_nth' 0). 2: {\n        rewrite isort_rank_length.\n        destruct Hσ as (H1, H2); rewrite H2.\n        flia Hi.\n      }\n      easy.\n    }\n    easy.\n  }\n  easy.\n}\ncbn.\napply (det_by_any_sym_gr Hop H10); [ easy | easy | easy | ].\nunfold sg.\nsplit. {\n  rewrite List_map_seq_length.\n  intros i Hi.\n  rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n  rewrite seq_nth; [ | easy ].\n  rewrite Nat.add_0_l.\n  split. {\n    unfold \"°\"; cbn.\n    rewrite map_length.\n    rewrite isort_rank_length.\n    now destruct Hσ.\n  } {\n    apply (comp_permut_seq n). {\n      now apply canon_sym_gr_list_permut_seq_with_len.\n    } {\n      now apply isort_rank_permut_seq_with_len; destruct Hσ.\n    }\n  }\n}\nsplit. {\n  rewrite List_map_seq_length.\n  intros i j Hi Hj Hij.\n  rewrite (List_map_nth' 0) in Hij; [ | now rewrite seq_length ].\n  rewrite (List_map_nth' 0) in Hij; [ | now rewrite seq_length ].\n  rewrite seq_nth in Hij; [ | easy ].\n  rewrite seq_nth in Hij; [ | easy ].\n  do 2 rewrite Nat.add_0_l in Hij.\n  unfold \"°\" in Hij.\n  specialize (ext_in_map Hij) as H1.\n  apply (nth_canon_sym_gr_list_inj2 n); [ easy | easy | ].\n  intros k Hk.\n  apply H1.\n  apply (permutation_in_iff Nat.eqb_eq) with (lb := seq 0 n). 2: {\n    clear - Hk.\n    induction n; intros; [ easy | ].\n    rewrite seq_S; cbn.\n    apply in_or_app.\n    destruct (Nat.eq_dec k n) as [Hkn| Hkn]. {\n      now subst k; right; left.\n    }\n    left; apply IHn; flia Hk Hkn.\n  }\n  replace n with (length (isort_rank Nat.leb σ)). 2: {\n    rewrite isort_rank_length.\n    now destruct Hσ.\n  }\n  apply isort_rank_permut_seq.\n} {\n  intros l Hl.\n  apply in_map_iff.\n  destruct Hl as (Hl1, Hl2).\n  destruct Hσ as (Hσ1, Hσ2).\n  exists (canon_sym_gr_list_inv n (l ° σ)).\n  rewrite canon_sym_gr_list_canon_sym_gr_list_inv. 2: {\n    now apply map_nth_permut_permut_permut_seq_with_len.\n  }\n  split. {\n    rewrite <- (permut_comp_assoc n); [ | easy | | ]; cycle 1. {\n      now rewrite isort_rank_length.\n    } {\n      apply isort_rank_permut_seq.\n    }\n    rewrite permut_comp_isort_rank_r; [ | easy ].\n    apply comp_1_r.\n    congruence.\n  }\n  apply in_seq.\n  split; [ easy | ].\n  rewrite Nat.add_0_l.\n  apply canon_sym_gr_list_inv_ub.\n  now apply map_nth_permut_permut_permut_seq_with_len.\n}\nQed.\n\nTheorem isort_rank_inj2 : ∀ l1 l2,\n  permut_seq l1\n  → permut_seq l2\n  → isort_rank Nat.leb l1 = isort_rank Nat.leb l2\n  → l1 = l2.\nProof.\nintros * Hpl1 Hpl2 Hill.\nassert (Hll : length l1 = length l2). {\n  apply List_eq_iff in Hill.\n  now do 2 rewrite isort_rank_length in Hill.\n}\napply (f_equal (comp_list l1)) in Hill.\nrewrite comp_isort_rank_r in Hill.\nrewrite permut_isort_leb in Hill; [ | easy ].\napply (f_equal (λ l, comp_list l l2)) in Hill.\nrewrite comp_1_l in Hill. 2: {\n  now rewrite Hll; apply permut_seq_iff in Hpl2.\n}\nrewrite <- (@permut_comp_assoc (length l2)) in Hill; [ | | easy | easy ]. 2: {\n  apply isort_rank_length.\n}\nrewrite permut_comp_isort_rank_l in Hill; [ | easy ].\nnow rewrite comp_1_r in Hill.\nQed.\n\nTheorem det_any_permut_r :\n  let ron := nat_ring_like_op in\n  rngl_mul_is_comm = true →\n  @rngl_has_opp T ro = true →\n  rngl_characteristic ≠ 1 →\n  ∀ n (M : matrix T) (σ : list nat),\n  n ≠ 0\n  → mat_nrows M = n\n  → is_square_matrix M = true\n  → permut_seq_with_len n σ\n  → det M =\n    (∑ (μ ∈ canon_sym_gr_list_list n), ε μ * ε σ *\n     ∏ (k = 0, n - 1), mat_el M (nth k μ 0 + 1) (nth k σ 0 + 1))%L.\nProof.\nintros ron Hic Hop H10 * Hnz Hr Hsm Hσ; subst ron.\nerewrite rngl_summation_list_eq_compat. 2: {\n  intros μ Hμ.\n  assert (Hpμ : permut_seq_with_len n μ). {\n    apply in_map_iff in Hμ.\n    destruct Hμ as (i & Hiμ & Hi).\n    apply in_seq in Hi.\n    rewrite <- Hiμ.\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  }\n  remember (σ ° isort_rank Nat.leb μ) as ν eqn:Hν.\n  assert (Hσν : ν ° μ = σ). {\n    rewrite Hν.\n    assert (H : length (isort_rank Nat.leb μ) = n). {\n      rewrite isort_rank_length.\n      apply Hpμ.\n    }\n    rewrite <- (permut_comp_assoc _ H); clear H; [ | apply Hpμ | ]. 2: {\n      now destruct Hpμ.\n    }\n    rewrite permut_comp_isort_rank_l; [ | now destruct Hpμ ].\n    apply comp_1_r.\n    destruct Hσ, Hpμ; congruence.\n  }\n  subst ν.\n  rewrite <- Hσν at 1.\n  replace (ε ((σ ° isort_rank Nat.leb μ) ° μ)) with\n      (ε (σ ° isort_rank Nat.leb μ) * ε μ)%L. 2: {\n    rewrite <- sign_comp; [ easy | easy | ].\n    rewrite comp_length, isort_rank_length.\n    now destruct Hpμ.\n  }\n  rewrite (rngl_mul_comm Hic _ (ε μ)).\n  rewrite rngl_mul_assoc.\n  rewrite NoDup_ε_square; [ | easy | ]. 2: {\n    apply permut_seq_NoDup.\n    now destruct Hpμ.\n  }\n  rewrite rngl_mul_1_l.\n  easy.\n}\ncbn.\nunfold canon_sym_gr_list_list.\nrewrite rngl_summation_list_map.\nrewrite rngl_summation_seq_summation; [ | apply fact_neq_0 ].\nrewrite Nat.add_0_l.\nerewrite rngl_summation_eq_compat. 2: {\n  intros i (_, Hi).\n  assert (Hc : permut_seq_with_len n (canon_sym_gr_list n i)). {\n    apply canon_sym_gr_list_permut_seq_with_len.\n    specialize (fact_neq_0 n) as H.\n    flia Hi H.\n  }\n  rewrite rngl_product_change_var with\n      (g := λ j, nth j (isort_rank Nat.leb (canon_sym_gr_list n i)) 0)\n      (h := λ j, nth j (canon_sym_gr_list n i) 0). 2: {\n    intros j (_, Hj).\n    apply permut_isort_permut. 2: {\n      rewrite canon_sym_gr_list_length; flia Hj Hnz.\n    }\n    apply canon_sym_gr_list_permut_seq_with_len.\n    specialize (fact_neq_0 n) as H.\n    flia Hi H.\n  }\n  rewrite Nat.sub_0_r.\n  rewrite <- Nat.sub_succ_l; [ | flia Hnz ].\n  rewrite Nat_sub_succ_1.\n  erewrite rngl_product_list_eq_compat. 2: {\n    intros j Hj.\n    apply in_map_iff in Hj.\n    destruct Hj as (k & Hkj & Hk).\n    apply in_seq in Hk.\n    rewrite permut_permut_isort; [ easy | | ]. {\n      apply canon_sym_gr_list_permut_seq.\n      specialize (fact_neq_0 n) as H.\n      flia Hi H.\n    }\n    rewrite <- Hkj.\n    apply permut_seq_ub; [ apply Hc | ].\n    apply nth_In.\n    now rewrite canon_sym_gr_list_length.\n  }\n  cbn.\n  rewrite rngl_product_map_permut; [ | easy | easy ].\n  easy.\n}\ncbn.\nset\n  (sg :=\n     map (λ k, σ ° isort_rank Nat.leb (canon_sym_gr_list n k)) (seq 0 n!)).\nerewrite rngl_summation_eq_compat. 2: {\n  intros k Hk.\n  assert (Hkn : k < n!). {\n    specialize (fact_neq_0 n) as H.\n    flia Hk H.\n  }\n  replace (_ ° _) with (nth k sg []). 2: {\n    unfold sg.\n    rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n    now rewrite seq_nth.\n  }\n  erewrite rngl_product_eq_compat. 2: {\n    intros i Hi.\n    rewrite Nat.sub_add; [ | flia Hi ].\n    replace (nth _ _ 0) with (nth (i - 1) (nth k sg []) 0). 2: {\n      unfold sg.\n      rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n      rewrite seq_nth; [ | easy ].\n      rewrite Nat.add_0_l.\n      unfold \"°\".\n      rewrite (List_map_nth' 0). 2: {\n        rewrite isort_rank_length.\n        rewrite canon_sym_gr_list_length.\n        flia Hi.\n      }\n      easy.\n    }\n    easy.\n  }\n  easy.\n}\ncbn.\napply (det_by_any_sym_gr Hop H10); [ easy | easy | easy | ].\nunfold sg.\nsplit. {\n  rewrite List_map_seq_length.\n  intros i Hi.\n  rewrite (List_map_nth' 0); [ | now rewrite seq_length ].\n  rewrite seq_nth; [ | easy ].\n  rewrite Nat.add_0_l.\n  split. {\n    unfold \"°\"; cbn.\n    rewrite map_length.\n    rewrite isort_rank_length.\n    apply canon_sym_gr_list_length.\n  } {\n    apply (comp_permut_seq n); [ easy | ].\n    apply isort_rank_permut_seq_with_len.\n    now apply canon_sym_gr_list_permut_seq_with_len.\n  }\n}\nsplit. {\n  rewrite List_map_seq_length.\n  intros i j Hi Hj Hij.\n  rewrite (List_map_nth' 0) in Hij; [ | now rewrite seq_length ].\n  rewrite (List_map_nth' 0) in Hij; [ | now rewrite seq_length ].\n  rewrite seq_nth in Hij; [ | easy ].\n  rewrite seq_nth in Hij; [ | easy ].\n  do 2 rewrite Nat.add_0_l in Hij.\n  unfold \"°\" in Hij.\n  apply (f_equal (map (λ i, nth i (isort_rank Nat.leb σ) 0))) in Hij.\n  do 2 rewrite map_map in Hij.\n  erewrite map_ext_in in Hij. 2: {\n    intros k Hk.\n    apply (In_nth _ _ 0) in Hk.\n    destruct Hk as (u & Hu1 & Hu2).\n    rewrite permut_isort_permut; [ | now destruct Hσ | ]. 2: {\n      rewrite <- Hu2.\n      eapply Nat.lt_le_trans. {\n        apply permut_seq_ub; [ | now apply nth_In ].\n        apply isort_rank_permut_seq.\n      }\n      rewrite isort_rank_length.\n      rewrite canon_sym_gr_list_length.\n      now destruct Hσ as (_, Hσl); rewrite Hσl.\n    }\n    easy.\n  }\n  symmetry in Hij.\n  erewrite map_ext_in in Hij. 2: {\n    intros k Hk.\n    apply (In_nth _ _ 0) in Hk.\n    destruct Hk as (u & Hu1 & Hu2).\n    rewrite permut_isort_permut; [ | now destruct Hσ | ]. 2: {\n      rewrite <- Hu2.\n      eapply Nat.lt_le_trans. {\n        apply permut_seq_ub; [ | now apply nth_In ].\n        apply isort_rank_permut_seq.\n      }\n      rewrite isort_rank_length.\n      rewrite canon_sym_gr_list_length.\n      now destruct Hσ as (_, Hσl); rewrite Hσl.\n    }\n    easy.\n  }\n  symmetry in Hij.\n  do 2 rewrite map_id in Hij.\n  apply isort_rank_inj2 in Hij; cycle 1. {\n    now apply canon_sym_gr_list_permut_seq.\n  } {\n    now apply canon_sym_gr_list_permut_seq.\n  }\n  now apply canon_sym_gr_list_inj in Hij.\n} {\n  intros l Hl.\n  apply in_map_iff.\n  exists (canon_sym_gr_list_inv n (isort_rank Nat.leb l ° σ)).\n  rewrite canon_sym_gr_list_canon_sym_gr_list_inv. 2: {\n   apply comp_permut_seq_with_len; [ | easy ].\n    apply isort_rank_permut_seq_with_len.\n    now destruct Hl.\n  }\n  rewrite (permut_isort_rank_comp n); [ | | | easy ]; cycle 1. {\n    apply NoDup_isort_rank.\n  } {\n    rewrite isort_rank_length.\n    now destruct Hl.\n  }\n  rewrite (permut_comp_assoc n); cycle 1. {\n    rewrite isort_rank_length.\n    now destruct Hσ.\n  } {\n    do 2 apply isort_rank_permut_seq_with_len.\n    now destruct Hl.\n  } {\n    apply isort_rank_permut_seq.\n  }\n  rewrite permut_comp_isort_rank_r; [ | now destruct Hσ ].\n  rewrite comp_1_l. 2: {\n    intros i Hi.\n    apply in_isort_rank in Hi.\n    rewrite isort_rank_length in Hi.\n    destruct Hσ, Hl; congruence.\n  }\n  rewrite permut_isort_rank_involutive; [ | now destruct Hl ].\n  split; [ easy | ].\n  apply in_seq.\n  split; [ easy | ].\n  apply canon_sym_gr_list_inv_ub.\n  apply comp_permut_seq_with_len; [ | easy ].\n  apply isort_rank_permut_seq_with_len.\n  now destruct Hl.\n}\nQed.\n\nTheorem determinant_transpose :\n  rngl_mul_is_comm = true →\n  rngl_has_opp = true →\n  rngl_characteristic ≠ 1 →\n  ∀ (M : matrix T),\n  is_square_matrix M = true\n  → det M⁺ = det M.\nProof.\nintros Hic Hop H10 * Hsm.\nremember (mat_nrows M) as n eqn:Hr; symmetry in Hr.\ndestruct (Nat.eq_dec n 0) as [Hnz| Hnz]. {\n  unfold det.\n  rewrite mat_transp_nrows, Hr.\n  rewrite squ_mat_ncols; [ | easy ].\n  now rewrite Hr, Hnz.\n}\nspecialize (mat_transp_is_square M Hsm) as Hts.\nassert (Hs : permut_seq_with_len n (seq 0 n)) by apply seq_permut_seq_with_len.\nassert (Hr' : mat_nrows M⁺ = n). {\n  now rewrite mat_transp_nrows, squ_mat_ncols.\n}\nrewrite (det_any_permut_l Hic Hop H10 M Hnz Hr Hsm Hs).\nrewrite (det_any_permut_r Hic Hop H10 (M⁺)%M Hnz Hr' Hts Hs).\napply rngl_summation_list_eq_compat.\nintros p Hp.\nf_equal.\napply rngl_product_eq_compat.\nintros k Hk.\nunfold mat_transp; cbn.\ndo 2 rewrite Nat.add_sub.\nrewrite seq_nth; [ | flia Hk Hnz ].\nassert (Hpr : nth k p 0 < mat_nrows M). {\n  apply in_map_iff in Hp.\n  destruct Hp as (i & Hi & His).\n  apply in_seq in His.\n  rewrite <- Hi.\n  rewrite Hr.\n  apply canon_sym_gr_list_ub; [ easy | ].\n  flia Hnz Hk.\n}\nrewrite (List_map_nth' 0). 2: {\n  now rewrite seq_length, squ_mat_ncols.\n}\nrewrite (List_map_nth' 0); [ | rewrite seq_length, Hr; flia Hk Hnz ].\nrewrite seq_nth; [ | rewrite Hr; flia Hk Hnz ].\nrewrite Nat.add_0_l.\nrewrite seq_nth; [ | now rewrite squ_mat_ncols ].\nnow do 2 rewrite Nat.add_1_r.\nQed.\n\nTheorem det_subm_transp :\n  rngl_mul_is_comm = true →\n  rngl_has_opp = true →\n  rngl_characteristic ≠ 1 →\n  ∀ i j (M : matrix T),\n  is_square_matrix M = true\n  → 1 ≤ i ≤ mat_ncols M\n  → 1 ≤ j ≤ mat_nrows M\n  → det (subm j i M) = det (subm i j M⁺).\nProof.\nintros Hic Hop H10 * Hsm Hi Hj.\nrewrite <- (determinant_transpose Hic Hop H10). 2: {\n  rewrite squ_mat_ncols in Hi; [ | easy ].\n  now apply is_squ_mat_subm.\n}\nnow rewrite mat_subm_transp.\nQed.\n\nTheorem det_mI :\n  rngl_has_opp_or_subt = true →\n  ∀ n, det (mI n) = 1%L.\nProof.\nintros Hop *; cbn.\nrewrite List_map_seq_length.\ninduction n; intros; [ easy | ].\nrewrite determinant_succ.\nrewrite rngl_summation_split_first; [ | flia ].\nreplace (minus_one_pow 2) with 1%L by easy.\nrewrite rngl_mul_1_l.\nrewrite mat_el_mI_diag; [ | flia ].\nrewrite rngl_mul_1_l.\nrewrite all_0_rngl_summation_0. 2: {\n  intros i Hi.\n  rewrite mat_el_mI_ndiag; [ | easy | flia Hi | flia Hi ].\n  rewrite rngl_mul_0_r; [ | easy ].\n  now apply rngl_mul_0_l.\n}\nrewrite rngl_add_0_r.\nunfold subm, mI; cbn.\nrewrite map_map; cbn.\nnow rewrite (mI_any_seq_start 1) in IHn.\nQed.\n\nEnd a.\n\nArguments det {T ro} M%M.\nArguments det' {T}%type {ro} M%M.\nArguments det'' {T}%type {ro} M%M.\nArguments determinant_alternating {T}%type {ro rp} Hic Hop M%M [p q]%nat.\nArguments determinant_loop {T}%type {ro} n%nat M%M.\nArguments determinant_same_rows {T ro rp} Hic Hop Hch Hit M [p q]%nat.\nArguments determinant_transpose {T ro rp} _ M%M.\nArguments det_is_det' {T ro rp} Hop M%M Hsm.\nArguments det'_is_det'' {T ro rp} Hop M%M.\nArguments det_is_det'' {T ro rp} Hop M%M Hsm.\nArguments det_mI {T ro rp} _ n%nat.\nArguments det_subm_transp {T ro rp} _ [i j]%nat.\n", "meta": {"author": "roglo", "repo": "coq_sensitivity", "sha": "398291aa86a447f0f35b4918043e94d9eb703c12", "save_path": "github-repos/coq/roglo-coq_sensitivity", "path": "github-repos/coq/roglo-coq_sensitivity/coq_sensitivity-398291aa86a447f0f35b4918043e94d9eb703c12/main/Determinant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.70483258712145}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** This file contains a library for encoding binary trees into\n    lists of Boolean values in {Zero,One} \n    \n    The proofs contain holes that have to be filled by students\n*)\n\nRequire Import List Arith Omega Wellfounded.\n\nSet Implicit Arguments.\n\n(** To reason or compute by induction on a measure *)\n\nTheorem measure_rect X (m : X -> nat) (P : X -> Type) :\n      (forall x, (forall y, m y < m x -> P y) -> P x) -> forall x, P x.\nProof. apply well_founded_induction_type, wf_inverse_image, lt_wf. Qed.\n\n(** To reason by induction on the length of lists *)\n\nDefinition list_length_rect X := measure_rect (@length X).\n\n(* And a friendly notation for this induction principle on lists *)\n\nTactic Notation \"induction\" \"on\" \"length\" \"of\" ident(x) \"as\" simple_intropattern(H) := \n  induction x as H using list_length_rect.\n  \n(* A small library with a tactic to rewrite length *)\n\nSection length.\n   \n  Variables (X : Type) (x : X) (l : list X).\n\n  Fact length_nil  : length (@nil X) = 0.             Proof. auto. Qed.\n  Fact length_cons : length (x::l)   = S (length l).  Proof. auto. Qed.\n\nEnd length.\n\nCreate HintDb length_db.\n\nTactic Notation \"rew\" \"length\" := autorewrite with length_db.\nTactic Notation \"rew\" \"length\" \"in\" hyp(H) := autorewrite with length_db in H.\nHint Rewrite length_nil length_cons app_length map_length : length_db.\n\n(** A small complement for the list library *)\n\n(* If a list is cut in half in two different way l1 ++ r1 = l2 ++ r2\n   and the cut is at the same place then l1 = l2 and r1 = r2 *)\n\nFact list_app_inj X (l1 l2 r1 r2 : list X) : length l1 = length l2 -> l1++r1 = l2++r2 -> l1 = l2 /\\ r1 = r2.\nProof.\n  revert l2; induction l1 as [ | x l1 IH ]; intros [ | y l2 ].\nAdmitted.\n\nSection flat_map.\n\n  Variable (X Y : Type) (f : X -> list Y).\n\n  Fact flat_map_app l1 l2 : flat_map f (l1++l2) = flat_map f l1 ++ flat_map f l2.\n  Proof. \n  Admitted.\n\n  Hypothesis Hf : forall x, f x <> nil.\n\n  Fact flat_map_nil l : nil = flat_map f l -> l = nil.\n  Proof.\n  Admitted.\n\nEnd flat_map.\n\n(** Definition of the notion of prefix \n    \n        l is a prefix of l++r \n        \n    which is denoted by l <p l++r\n    together with a small library\n*)\n\nDefinition prefix X (l ll : list X) := exists r, ll = l++r.\n  \nInfix \"<p\" := (@prefix _) (at level 70, no associativity).\n  \nSection prefix. (* as an inductive predicate *)\n   \n  Variable X : Type.\n  \n  Implicit Types (l ll : list X).\n  \n  Fact in_prefix_0 ll : nil <p ll.\n  Proof. exists ll; auto. Qed.\n  \n  Fact in_prefix_1 x l ll : l <p ll -> x::l <p x::ll.\n  Proof. intros (r & ?); subst; exists r; auto. Qed.\n\n  Fact prefix_right l r : l <p l ++ r.\n  Proof. exists r; auto. Qed.\n\n  Fact prefix_length l m : l <p m -> length l <= length m.\n  Proof. intros (? & ?); subst; rew length; omega. Qed.\n  \n  Fact prefix_app_lft l r1 r2 : r1 <p r2 -> l++r1 <p l++r2.\n  Proof.\n    intros (a & ?); subst.\n    exists a; rewrite app_ass; auto.\n  Qed.\n  \n  Fact prefix_inv x y l ll : x::l <p y::ll -> x = y /\\ l <p ll.\n  Proof.\n    intros (r & Hr).\n    inversion Hr; split; auto.\n    exists r; auto.\n  Qed.\n  \n  Fact prefix_list_inv l r rr : l++r <p l++rr -> r <p rr.\n  Proof.\n    induction l as [ | x l IHl ]; simpl; auto.\n    intros H; apply prefix_inv, proj2, IHl in H; auto.\n  Qed.\n\n  Fact prefix_refl l : l <p l.\n  Proof. exists nil; rewrite <- app_nil_end; auto. Qed.\n\n  Fact prefix_trans l1 l2 l3 : l1 <p l2 -> l2 <p l3 -> l1 <p l3.\n  Proof. intros (m1 & H1) (m2 & H2); subst; exists (m1++m2); rewrite app_ass; auto. Qed.\n\n  Section prefix_rect.\n\n    Variables (P : list X -> list X -> Type)\n              (HP0 : forall ll, P nil ll)\n              (HP1 : forall x l ll, l <p ll -> P l ll -> P (x::l) (x::ll)).\n              \n    Definition prefix_rect l ll : l <p ll -> P l ll.\n    Proof.\n      revert l; induction ll as [ | x ll IHll ]; intros l H.\n      \n      replace l with (nil : list X).\n      apply HP0.\n      destruct H as (r & Hr).\n      destruct l; auto; discriminate.\n      \n      destruct l as [ | y l ].\n      apply HP0.\n      apply prefix_inv in H.\n      destruct H as (? & E); subst y.\n      apply HP1; [ | apply IHll ]; trivial.\n    Qed.\n   \n  End prefix_rect.\n\n  Fact prefix_app_inv l1 l2 r1 r2 : l1++l2 <p r1++r2 -> { l1 <p r1 } + { r1 <p l1 }.\n  Proof.\n    revert l2 r1 r2; induction l1 as [ | x l1 IH ]; intros l2 r1 r2.\n    admit.\n    destruct r1 as [ | y r1 ].\n  Admitted.\n  \nEnd prefix.\n\nDefinition prefix_spec X (l ll : list X) : l <p ll -> { r | ll = l ++ r }.\nProof.\n  induction 1 as [ ll | x l ll _ (r & Hr) ] using prefix_rect.\nAdmitted.\n\nFact prefix_app_lft_inv X (l1 l2 m : list X) : l1++l2 <p m -> { m2 | m = l1++m2 /\\ l2 <p m2 }.\nProof.\nAdmitted.\n\n(** Binary trees *)\n\nInductive bt : Set := bt0 | bt1 : bt -> bt -> bt.\n\nDelimit Scope bt_scope with bt.\n\nNotation null := bt0.    (* typing that is easier *)\nNotation ø := bt0.       (* for a nicer display *)\n\nNotation \" '<<' x ',' y '>>' \" := (bt1 x y) (at level 0): bt_scope.\nNotation \" ⟨ x , y ⟩ \" := (bt1 x y) (at level 0): bt_scope.\n\nReserved Notation \"〈 t 〉\" (at level 0, no associativity).\nReserved Notation \" '[[' t ']]' \" (at level 0, no associativity).\n\nOpen Scope bt_scope.\n\n(* We can decide if two trees are equal or not *)\n\nDefinition bt_eq_dec (s t : bt) : { s = t } + { s <> t }.\nProof.\n  revert t; induction s as [ | a Ha b Hb ]; intros [ | c d ].\nAdmitted.\n\nFact bt_pair_neq a1 b1 a2 b2 : <<a1,a2>> <> <<b1,b2>> -> { a1 <> b1 } + { a2 <> b2 }.\nProof.\nAdmitted. \n\nInductive bt_mirror : bt -> bt -> Prop :=\n  | in_bt_mirror_0 : bt_mirror ø ø\n  | in_bt_mirror_1 : forall a b c d, bt_mirror a b \n                                  -> bt_mirror c d\n                                  -> bt_mirror <<a,c>> <<d,b>>.\n\nDefinition bt_compute_mirror s : { t | bt_mirror s t }.\nProof.\nAdmitted.\n\nFixpoint bt_size t :=\n  match t with \n    | ø         => 1\n    | <<t1,t2>> => 1 + 〈 t1 〉 + 〈 t2 〉\n  end\nwhere \"〈 t 〉\" := (bt_size t).\n\nFact bt_mirror_size s t : bt_mirror s t -> 〈 s 〉 = 〈 t 〉.\nProof.\nAdmitted.\n\n(* Encoding of binary trees as list of Zero and One *)\n\nNotation Zero := false.\nNotation One  := true.\n\nFixpoint bt_bin t : list bool :=\n  match t with\n    | ø       => Zero :: nil\n    | <<a,b>> => One :: [[a]] ++ [[b]]\n  end\nwhere \"[[ t ]]\" := (bt_bin t).\n\nEval compute in [[ <<ø,ø>> ]].\nEval compute in [[ <<ø,<<ø,ø>>>> ]].\n\nFact bt_bin_not_nil t : [[t]] <> nil.\nProof.\nAdmitted.\n\nHint Resolve bt_bin_not_nil.\n\n(* The length of the encoding is the size of the tree *)\n\nFact bt_bin_length t : length [[t]] = 〈 t 〉.\nProof.\nAdmitted.\n\nFact bt_bin_length_geq t : 1 <= length [[t]].\nProof.\nAdmitted.\n\n(** The essential lemma of non-ambiguity: \n       \n     if  [[s]] ++ l = [[t]] ++ m  then   s = t and l = m\n\n*) \n\nLemma bt_bin_eq s : forall t l m, [[s]] ++ l = [[t]] ++ m -> s = t /\\ l = m. \nProof.\n  induction s as [ | s1 IH1 s2 IH2 ]; intros [ | t1 t2 ].\nAdmitted.\n\nCorollary bt_bin_prefix_eq s t : [[s]] <p [[t]] -> s = t.\nProof.\n  intros (l & Hl).\n  rewrite (app_nil_end [[t]]) in Hl.\nAdmitted.\n\nCorollary bt_bin_inj s t : [[s]] = [[t]] -> s = t.\nProof.\nAdmitted.\n\nCorollary bt_bin_prefix_app_eq s t l m : [[s]]++l <p [[t]]++m -> s = t /\\ l <p m.\nProof.\nAdmitted.\n\nCorollary bt_bin_uniq ll t1 t2 : [[t1]] <p ll -> [[t2]] <p ll -> t1 = t2.\nProof.\nAdmitted.\n\nLemma flat_map_bt_bin_eq lt1 : forall lt2 l m, \n     flat_map bt_bin lt1 ++ l = flat_map bt_bin lt2 ++ m\n  -> { lt1 <p lt2 } + { lt2 <p lt1 }.\nProof. \n  induction lt1 as [ | t1 lt1 IH ]; intros lt2 l m E; \n    [ | destruct lt2 as [ | t2 lt2 ] ]; simpl in E.\nAdmitted.\n\n(* [[[t1;...;tn]]] = [[t1]]++...++[[tn]] *)\n\nNotation \" '[[[' l ']]]' \" := (flat_map bt_bin l) (at level 0, no associativity).\n\n(* The encoding of a list of trees is unambiguous \n\n     if [[s1]]++...++[[sk]] = [[t1]]++...++[[tp]] then [s1,...,sk] = [t1,...,tp] \n\n*)\n\nTheorem lbt_bin_inj lt1 lt2 : [[[lt1]]] = [[[lt2]]] -> lt1 = lt2.\nProof.\n  intros H; generalize H; intros H1.\n  rewrite (app_nil_end (_ _ lt2)), (app_nil_end (_ _ lt1)) in H.\n  apply flat_map_bt_bin_eq in H.\n  destruct H as [ (r & H) | (r & H) ]; subst; rewrite flat_map_app in H1.\nAdmitted.\n\n(** Now the decoders, beware that bt_bin is injective but not surjective !!\n    Indeed, no binary tree encodes into One :: nil for instance *)\n\n(* Given a sequence of boolean value lb, either \n\n     1/ computes a prefix of lb which encodes some binary tree t\n     2/ or show that no such tree exists.\n*)\n\n\nDefinition bin_bt_dec (lb : list bool) : { t : bt & { r | lb = [[t]] ++ r } } \n                                       + { forall t, ~ [[t]] <p lb }.\nProof.\n  induction on length of lb as [ [ | [] lb1 ] IH ].\n\n  (* lb = nil *)\n  \n  right; intros [] (r & Hr); discriminate.\n\n  (* lb = One :: lb1  >>>> call the induction hypothesis on lb1 (shorter than lb) *)\n\n  destruct (IH lb1) as [ (t1 & lb2 & H1) | C ]. \n  admit.\n  \n  (* lb1 = [[t1]] ++ lb2  >>>> call the induction hypothesis on lb2 (shorter than lb1, and thus of lb) *)\n  \n  destruct (IH lb2) as [ (t2 & lb' & H2) | C ].\n  admit.\n\n  (* lb2 = [[t2]] ++ lb' *)\n \n  admit.\n   \n  (* ~ [[t]] <p lb2 *)  \n  \n  admit.\n  \n  (* ~ [[t]] <p lb1,  *) \n  \n  admit. \n \n  (* lb = Zero :: lb1 *)\n  \n  left; exists ø, lb1; simpl; auto.\n\nAdmitted.\n\n(* Given a list of boolean values lb, computes a maximal list of trees [t1;...;tk]\n   such that lb = [[t1]]++...++[[tk]]++r where r is not prefixed by a bt *)\n\nDefinition bin_lbt_decode (lb : list bool) : \n        { lt : _ &  { r | lb = [[[lt]]] ++ r /\\ forall t, ~ [[t]] <p r } }.\nProof.\n  induction on length of lb as [ lb IH ].\n  destruct (bin_bt_dec lb) as [ (t & r & H) | H ].\nAdmitted.\n\n(* lb is not of the form [[t]]++... for any t *)\n\nDefinition not_prefixed lb := forall t, ~ [[t]] <p lb.\n\nFact not_prefixed_0 : not_prefixed nil.\nProof. intros [] []; discriminate. Qed.\n\nFact not_prefixed_1 lb : ~ not_prefixed (Zero::lb).\nProof.\n  intros H; apply (H ø); apply in_prefix_1, in_prefix_0.\nQed.\n\n(* If One::lb is not prefix by a tree then\n   either lb = [[t]]++r where r is not prefixed by a tree\n   or lb is not prefixed *)\n\nFact not_prefixed_2 lb : \n        not_prefixed (One::lb) \n     -> { t : _ & { r | lb = [[t]]++r /\\ not_prefixed r } } \n      + { not_prefixed lb }.\nProof.\n  intros H.\n  destruct (bin_bt_dec lb) as [ (t & r & H1) | H1 ].\nAdmitted.\n\n(** However, every list which is not prefixed by a tree can be extended into (the encoding of) a tree *)\n\nTheorem bin_bt_extend (lb : list bool) : (forall t, ~ [[t]] <p lb) -> { rb : _ & { t | lb ++ rb = [[t]] } }.\nProof.\n  fold (not_prefixed lb).\n  induction on length of lb as [ [ | [] lb ] IH ]; intros Hlb.\n  \n  admit.\n\n  destruct (not_prefixed_2 Hlb) as [ (t & r & H1 & H2) | H1 ].\n  admit.\n  admit.\n  \n  exfalso; revert Hlb; apply not_prefixed_1.\nAdmitted.\n\n(* Any sequence of 0s and 1s is the prefix of some encoded sequence of trees *)\n\nTheorem bin_lbt_complete lb : { lt | lb <p [[[lt]]] }.\nProof.\n  destruct (bin_lbt_decode lb) as (lt & r & H1 & H2).\n  destruct (bin_bt_extend H2) as (rb & t & H3).\n  exists (lt++t::nil), rb.\n  rewrite H1, flat_map_app, app_ass; simpl.\n  rewrite <- app_nil_end; f_equal; auto.\nQed.\n\n\n\n", "meta": {"author": "DmxLarchey", "repo": "Binary-trees-as-lists", "sha": "4e2f4de0c9c0e7a105493aa9aa3072341059ce86", "save_path": "github-repos/coq/DmxLarchey-Binary-trees-as-lists", "path": "github-repos/coq/DmxLarchey-Binary-trees-as-lists/Binary-trees-as-lists-4e2f4de0c9c0e7a105493aa9aa3072341059ce86/bt_exos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7048325858444031}}
{"text": "(* ** Addition for [positive] numbers *)\n\nFrom Undecidability.TM Require Import ProgrammingTools.\nFrom Undecidability Require Import BinNumbers.EncodeBinNumbers.\nFrom Undecidability Require Import BinNumbers.PosDefinitions.\nFrom Undecidability Require Import BinNumbers.PosPointers.\nFrom Undecidability Require Import BinNumbers.PosHelperMachines.\nFrom Undecidability Require Import BinNumbers.PosIncrementTM.\nFrom Undecidability Require Import BinNumbers.PosCompareTM.\n\nLocal Open Scope positive_scope.\n\n\n(* ** Tail-recursive versions of [Pos.add] and [Pos.add_carry] *)\n\n\nFixpoint addTR_rec (a : list bool) (x y : positive) : list bool :=\n  match x, y with\n  | p~1, q~1 => addTR_rec_carry (false :: a) p q\n  | p~1, q~0 => addTR_rec (true :: a) p q\n  | p~1, 1 => pos_to_bits (Pos.succ p) ++ false :: a\n  | p~0, q~1 => addTR_rec (true :: a) p q\n  | p~0, q~0 => addTR_rec (false :: a) p q\n  | p~0, 1 => pos_to_bits p ++ true :: a\n  | 1, q~1 => pos_to_bits (Pos.succ q) ++ false :: a\n  | 1, q~0 => pos_to_bits q ++ true :: a\n  | 1, 1 => false :: a\n  end\n\nwith addTR_rec_carry (a : list bool) (x y : positive) : list bool :=\n  match x, y with\n  | p~1, q~1 => addTR_rec_carry (true :: a) p q\n  | p~1, q~0 => addTR_rec_carry (false :: a) p q\n  | p~1, 1 => pos_to_bits (Pos.succ p) ++ true :: a\n  | p~0, q~1 => addTR_rec_carry (false :: a) p q\n  | p~0, q~0 => addTR_rec (true :: a) p q\n  | p~0, 1 => pos_to_bits (Pos.succ p) ++ false :: a\n  | 1, q~1 => pos_to_bits (Pos.succ q) ++ true :: a\n  | 1, q~0 => pos_to_bits (Pos.succ q) ++ false :: a\n  | 1, 1 => true :: a\n  end.\n\nDefinition addTR_rec' (carry : bool) (a : list bool) (x y : positive) : list bool := if carry then addTR_rec_carry a x y else addTR_rec a x y.\nDefinition addTR (x y : positive) := bits_to_pos (addTR_rec nil x y).\n\n(*\nCompute addTR 42 1. (* 43 *)\nCompute addTR 1 1. (* 2 *)\nCompute addTR 1 2. (* 3 *)\nCompute addTR 1 3. (* 4 *)\nCompute addTR 7 3. (* 10 *)\nCompute addTR 7 3. (* 10 *)\nCompute addTR 3 1. (* 4 *)\nCompute addTR 10 11. (* 21 *)\nCompute addTR 42 42. (* 84 *)\nCompute addTR 42 8. (* 50 *)\n*)\n\nLemma addTR_rec_correct (a : list bool) (x y : positive) :\n    addTR_rec a x y = pos_to_bits (Pos.add x y) ++ a /\\\n    addTR_rec_carry a x y = pos_to_bits (Pos.add_carry x y) ++ a.\nProof.\n  revert a y. induction x; intros; cbn in *.\n  - (* x = x ~ 1 *) destruct y as [ y' | y' | ] eqn:Ey; cbn; auto.\n    all: try rewrite !(proj2 (IHx (_ :: a) y')); try rewrite !(proj1 (IHx (_ :: a) y')); simpl_list; cbn; auto.\n  - (* x = x ~ 0 *) destruct y; cbn; auto.\n    all: try rewrite !(proj2 (IHx (_ :: a) y)); try rewrite !(proj1 (IHx (_ :: a) y)); simpl_list; cbn; auto.\n  - (* x = 1 *) destruct y; cbn; auto.\n    all: simpl_list; cbn; auto.\nQed.\n\nLemma addTR_correct (x y : positive) :\n  addTR x y = Pos.add x y.\nProof. unfold addTR. generalize (proj1 (addTR_rec_correct [] x y)). simpl_list. intros. rewrite H. now rewrite pos_to_bits_to_pos. Qed.\n\n\n(* Full adder (computes \"output bit\" and \"carry bit\") *)\nDefinition fullAdder (x y c : bool) : bool*bool := (xorb (xorb x y) c, (x && y) || (x && c) || (y && c)).\n\n(* Compute fullAdder false true true. *) (* (false, true) *)\n\n\n\n\n(* ** Addition Machine *)\n\n(* We maintain the invariant that tape 1 (the second tape) contains the smaller number. Otherwise, the base case woudn't work. *)\n(* In the final machine, [Add], the first step is to determine the maximum and copy it to the output tape. *)\n\n\n(* Some more lemmas that we need here *)\n\n(* More general than [pushHFS_append1] *)\nLemma pushHFS_append1' c bits :\n  pushHSB (append_bits (1~~c) bits) false = append_bits (2~~c) bits.\nProof.\n  apply Encode_positive_injective. cbn.\n  rewrite !encode_pushHSB, !encode_append_bits; cbn.\n  destruct c; cbn; auto.\nQed.\n\nLemma pushHFS_append2' c bits :\n  pushHSB (append_bits (2~~c) bits) false = append_bits (4~~c) bits.\nProof.\n  apply Encode_positive_injective. cbn.\n  rewrite !encode_pushHSB, !encode_append_bits; cbn.\n  destruct c; cbn; auto.\nQed.\n\n\n\n(* We use [StateWhile] to implement mutual recursion. The [bool] \"state\" corresponds to the carry. *)\n\n\n(* This function is used in the base case: t0 contains [xH] and t1 contains [p ++ b :: bits] and the pointer is on [b]. In some cases, we need to increment [p]. *)\nDefinition add_baseCase (b carry : bool) (p : positive) :=\n  if (b || carry) then (Pos.succ p) ~~ (negb (xorb b carry))\n  else p ~~ (negb (xorb b carry)).\n\n(* Compute add_baseCase true false 1. *)\n\n(* This base case is complex enough that I write an auxilliary machine for this *)\n\nDefinition Add_BaseCase_Rel (carry : bool) (b : bool) : pRel sigPos^+ unit 1 :=\n  fun tin '(_, tout) =>\n    forall (p : positive) (bits : list bool),\n      atBit tin[@Fin0] p b bits ->\n      atHSB tout[@Fin0] (append_bits (add_baseCase b carry p) bits).\n\nDefinition Add_BaseCase (carry : bool) (b : bool) : pTM sigPos^+ unit 1 :=\n  if (b || carry)\n  then SetBitAndMoveLeft (negb (xorb b carry));; Increment_Loop\n  else SetBitAndMoveLeft (negb (xorb b carry));; GoToHSB.\n\nLemma Add_BaseCase_Realise (carry : bool) (b : bool) : Add_BaseCase carry b ⊨ Add_BaseCase_Rel carry b.\nProof.\n  unfold Add_BaseCase. destruct (b||carry) eqn:Eb.\n  {\n    eapply Realise_monotone.\n    { TM_Correct.\n      - eapply RealiseIn_Realise. apply SetBitAndMoveLeft_Sem.\n      - apply Increment_Loop_Realise.\n    }\n    {\n      intros tin ([], tout) H. intros p bits Hp. TMSimp.\n      modpon H. destruct p; cbn in *.\n      - modpon H0. atBit_ext; cbn in *. destruct b, carry; cbn in *; auto.\n      - modpon H0. atBit_ext; cbn in *. destruct b, carry; cbn in *; auto.\n      - modpon H1. atBit_ext; cbn in *. rewrite pushHFS_append1'. destruct b, carry; cbn in *; auto.\n    }\n  }\n  {\n    eapply Realise_monotone.\n    { TM_Correct.\n      + eapply RealiseIn_Realise. apply SetBitAndMoveLeft_Sem.\n      + apply GoToHSB_Realise.\n    }\n    {\n      intros tin ([], tout) H. intros p bits Hp. TMSimp.\n      modpon H. destruct p; cbn in *.\n      - modpon H0. atBit_ext; cbn in *. destruct b, carry; cbn in *; auto.\n      - modpon H0. atBit_ext; cbn in *. destruct b, carry; cbn in *; auto.\n      - modpon H1. atBit_ext; cbn in *. destruct b, carry; cbn in *; auto.\n    }\n  }\nQed.\n\n\nDefinition Add_Step_Rel (carry : bool) : pRel sigPos^+ (bool+unit) 2 :=\n  fun tin '(yout, tout) =>\n    (forall (p0 : positive) (b0 : bool) (bits0 : list bool) (p1 : positive) (b1 : bool) (bits1 : list bool),\n        atBit tin[@Fin0] p0 b0 bits0 -> atBit tin[@Fin1] p1 b1 bits1 ->\n        (* Pos.le (p0 ~~ b0) (p1 ~~ b1) -> *)\n        movedToLeft tout[@Fin0] p0 b0 bits0 /\\\n        movedToLeft tout[@Fin1] p1 (fst (fullAdder b0 b1 carry)) bits1 /\\\n        yout = inl (snd (fullAdder b0 b1 carry))) /\\\n    (forall (p0 : positive) (p1 : positive) (b1 : bool) (bits1 : list bool),\n        atHSB tin[@Fin0] p0 ->\n        atBit tin[@Fin1] p1 b1 bits1 ->\n        atHSB tout[@Fin0] p0 /\\\n        atHSB tout[@Fin1] (append_bits (add_baseCase b1 carry p1) bits1) /\\\n        yout = inr tt) /\\\n    (forall (p0 : positive) (p1 : positive),\n        atHSB tin[@Fin0] p0 ->\n        atHSB tin[@Fin1] p1 ->\n        atHSB tout[@Fin0] p0 /\\\n        atHSB tout[@Fin1]  (pushHSB p1 carry) /\\\n        yout = inr tt).\n(* The case, [atBit t0 ... /\\ atHSB t1 ...] is not specified. *)\n\nDefinition Add_Step (carry : bool) : pTM sigPos^+ (bool+unit) 2 :=\n  Switch (ReadPosSym2)\n         (fun '(s0, s1) =>\n            match s0, s1 with\n            | Some b0, Some b1 => Return (SetBitAndMoveLeft b0 @ [|Fin0|];; SetBitAndMoveLeft (fst (fullAdder b0 b1 carry)) @ [|Fin1|]) (inl (snd (fullAdder b0 b1 carry)))\n            | None,    Some b1 => Return ((Add_BaseCase carry b1)@[|Fin1|]) (inr tt)\n            | None,    None    => Return (PushHSB carry @[|Fin1|]) (inr tt)\n            | Some b0, None    => Return Nop default (* not specified *)\n            end).\n\nLemma Add_Step_Realise (carry : bool) : Add_Step carry ⊨ Add_Step_Rel carry.\nProof.\n  eapply Realise_monotone.\n  { unfold Add_Step. cbn.\n    (* [TM_Correct] actually should do this automatically *)\n    eapply Switch_Realise with (R2 := fun '(s0, s1) => match s0, s1 with Some b0, Some b1 => _ | Some b0, None => _ | None, Some b1 => _ | None, None => _ end).\n    - eapply RealiseIn_Realise. apply ReadPosSym2_Sem.\n    - intros. destruct f as [s0 s1]. cbn. destruct s0 as [ b0 | ], s1 as [ b1 | ]; cbn; TM_Correct.\n      + eapply RealiseIn_Realise. apply SetBitAndMoveLeft_Sem.\n      + eapply RealiseIn_Realise. apply SetBitAndMoveLeft_Sem.\n      + apply Add_BaseCase_Realise.\n      + eapply RealiseIn_Realise. apply PushHSB_Sem. }\n  {\n    intros tin (yout, tout) H. TMSimp.\n    rename H into HReadSymA, H1 into HReadSymB, H2 into HReadSymC, H3 into HReadSymD. rename H0 into HSwich. rename o into s0, o0 into s1.\n    split; [ | split ]. (* Three obligations *)\n    - intros. modpon HReadSymA. clear HReadSymB HReadSymC HReadSymD.\n      destruct s0 as [ b0' | ], s1 as [ b1' | ]; cbn in *; auto.\n      + destruct b0' eqn:Eb0', b1' eqn:Eb1', b0, b1; TMSimp; eauto.\n      + destruct b0'; auto.\n    - intros. modpon HReadSymC. clear HReadSymA HReadSymB HReadSymD.\n      destruct s0 as [ b0' | ], s1 as [ b1' | ]; cbn in *; auto.\n      TMSimp. destruct b1' eqn:Eb0', b1; TMSimp; eauto.\n    - intros. modpon HReadSymD. clear HReadSymA HReadSymB HReadSymC. TMSimp. inv HReadSymD0. TMSimp. eauto.\n  }\nQed.\n\n\nDefinition Add_Loop_Rel (carry : bool) : pRel sigPos^+ unit 2 :=\n  fun tin '(_, tout) =>\n    (forall (p0 : positive) (b0 : bool) (bits0 : list bool) (p1 : positive) (b1 : bool) (bits1 : list bool),\n        atBit tin[@Fin0] p0 b0 bits0 -> atBit tin[@Fin1] p1 b1 bits1 ->\n        Pos.le (p0 ~~ b0) (p1 ~~ b1) ->\n        atHSB tout[@Fin0] (append_bits p0 (b0 :: bits0)) /\\\n        atHSB tout[@Fin1] (bits_to_pos (addTR_rec' carry bits1 (p0 ~~ b0) (p1 ~~ b1)))) /\\\n    (forall (p0 : positive) (p1 : positive) (b1 : bool) (bits1 : list bool),\n        atHSB tin[@Fin0] p0 ->\n        atBit tin[@Fin1] p1 b1 bits1 ->\n        atHSB tout[@Fin0] p0 /\\\n        atHSB tout[@Fin1] (append_bits (add_baseCase b1 carry p1) bits1)) /\\\n    (forall (p0 : positive) (p1 : positive),\n        atHSB tin[@Fin0] p0 ->\n        atHSB tin[@Fin1] p1 ->\n        atHSB tout[@Fin0] p0 /\\\n        atHSB tout[@Fin1] (pushHSB p1 carry)).\n\n\nDefinition Add_Loop : bool -> pTM sigPos^+ unit 2 := StateWhile Add_Step.\n\n\nLemma Add_Loop_Realise (carry : bool) : Add_Loop carry ⊨ Add_Loop_Rel carry.\nProof.\n  eapply Realise_monotone.\n  { unfold Add_Loop. TM_Correct. exact Add_Step_Realise. }\n  {\n    apply StateWhileInduction; intros.\n    {\n      destruct HLastStep as (HLastStepA&HLastStepB&HLastStepC). TMSimp. split; [ | split].\n      - intros. modpon HLastStepA. congruence.\n      - intros. modpon HLastStepB. repeat split; eauto.\n      - intros. modpon HLastStepC. repeat split; eauto.\n    }\n    {\n      destruct HStar as (HStarA&HStarB&HStarC). destruct HLastStep as (HLastStepA&HLastStepB&HLastStepC). TMSimp. split; [ | split].\n      - intros. modpon HStarA. clear HStarB HStarC. inv HStarA1.\n        destruct p0, p1; cbn in *.\n        { modpon HLastStepA; cbn in *.\n          { destruct b0, b1; cbn in *; auto; nia. }\n          repeat split; eauto. atBit_ext.\n          clear_all; destruct b0, b1, l; cbn; auto. }\n        { modpon HLastStepA. cbn in *.\n          { destruct b0, b1; cbn in *; auto; nia. }\n          cbn in *; repeat split; eauto. atBit_ext.\n          clear_all; destruct b0, b1, l; cbn; auto. }\n        { destruct b0, b1; cbn in *; nia. }\n        { modpon HLastStepA; cbn in *.\n          { destruct b0, b1; cbn in *; auto; nia. }\n          cbn in *; repeat split; eauto. atBit_ext.\n          clear_all; destruct b0, b1, l; cbn; auto. }\n        { modpon HLastStepA; cbn in *.\n          { destruct b0, b1; cbn in *; auto; nia. }\n          cbn in *; repeat split; eauto. atBit_ext.\n          clear_all; destruct b0, b1, l; cbn; auto. }\n        { destruct b0, b1; cbn in *; nia. }\n        { modpon HLastStepB. cbn in *; repeat split; eauto. atBit_ext.\n          clear_all; destruct b0, b1, l; cbn; auto.\n          all: apply pos_to_bits_inj; rewrite bits_to_pos_to_bits; rewrite pos_to_bits_append_bits; cbn; simpl_list; cbn; auto.\n        }\n        { modpon HLastStepB. cbn in *; repeat split; eauto. atBit_ext.\n          cbn in *. destruct b0, b1, l; cbn in *; auto; try nia.\n          all: apply pos_to_bits_inj; rewrite bits_to_pos_to_bits; rewrite pos_to_bits_append_bits; cbn; simpl_list; cbn; auto. }\n        { modpon HLastStepC. repeat split; eauto. atBit_ext.\n          clear_all; destruct b0, b1, l; cbn; auto.\n          all: apply pos_to_bits_inj; try rewrite pos_to_bits_pushHSB; try rewrite bits_to_pos_to_bits; try rewrite pos_to_bits_append_bits; cbn; auto.\n        }\n      - intros. modpon HStarB. congruence.\n      - intros. modpon HStarC. congruence.\n    }\n  }\nQed.\n\n\n(* We still assume that [p0<=p1] *)\nDefinition Add' : pTM sigPos^+ unit 2 :=\n  GoToLSB_start@[|Fin0|];; GoToLSB_start@[|Fin1|];;\n  (Add_Loop false)@[|Fin0; Fin1|];; (Move Lmove)@[|Fin0|];; (Move Lmove)@[|Fin1|].\n\n\nDefinition Add'_Rel : pRel sigPos^+ unit 2 :=\n  fun tin '(_, tout) =>\n    forall (p0 p1 : positive),\n      tin[@Fin0] ≃ p0 ->\n      tin[@Fin1] ≃ p1 ->\n      p0 <= p1 ->\n      tout[@Fin0] ≃ p0 /\\\n      tout[@Fin1] ≃ p0 + p1.\n\nLemma Add'_Realise : Add' ⊨ Add'_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold Add'. TM_Correct.\n    - apply GoToLSB_start_Realise.\n    - apply GoToLSB_start_Realise.\n    - apply Add_Loop_Realise. }\n  {\n    intros tin ([], tout) H. intros p0 p1 Hp0 Hp1 HRight. TMSimp.\n    rename H into HGoToHSB, H0 into HGoToHSB', H2 into HLoopA, H6 into HLoopB, H7 into HLoopC.\n    modpon HGoToHSB. modpon HGoToHSB'.\n    destruct p0; destruct p1; try nia.\n    - modpon HLoopA; cbn in *.\n      repeat split; eauto; apply atHSB_moveLeft_contains; eauto.\n      rewrite (proj2 (@addTR_rec_correct _ _ _)) in HLoopA0.\n      rewrite bits_to_pos_cons in HLoopA0.\n      now setoid_rewrite pos_to_bits_to_pos in HLoopA0.\n    - modpon HLoopA; cbn in *.\n      repeat split; eauto; apply atHSB_moveLeft_contains; eauto.\n      rewrite (proj1 (@addTR_rec_correct _ _ _)) in HLoopA0.\n      rewrite bits_to_pos_cons in HLoopA0.\n      now setoid_rewrite pos_to_bits_to_pos in HLoopA0.\n    - modpon HLoopA; cbn in *.\n      repeat split; eauto; apply atHSB_moveLeft_contains; eauto.\n      rewrite (proj1 (@addTR_rec_correct _ _ _)) in HLoopA0.\n      rewrite bits_to_pos_cons in HLoopA0.\n      now setoid_rewrite pos_to_bits_to_pos in HLoopA0.\n    - modpon HLoopA; cbn in *.\n      repeat split; eauto; apply atHSB_moveLeft_contains; eauto.\n      rewrite (proj1 (@addTR_rec_correct _ _ _)) in HLoopA0.\n      rewrite bits_to_pos_cons in HLoopA0.\n      now setoid_rewrite pos_to_bits_to_pos in HLoopA0.\n    - modpon HLoopB; cbn in *.\n      repeat split; eauto; apply atHSB_moveLeft_contains; eauto.\n    - modpon HLoopB; cbn in *.\n      repeat split; eauto; apply atHSB_moveLeft_contains; eauto.\n    - modpon HLoopC; cbn in *.\n      repeat split; eauto; apply atHSB_moveLeft_contains; eauto.\n  }\nQed.\n\n\n(* The final step: We find out which number is the maximum and copy the maximum to the output tape, before we start the actual computation *)\n\nDefinition Add : pTM sigPos^+ unit 3 :=\n  Switch Max\n         (fun (c : comparison) =>\n            match c with\n            | Gt => Add' @[|Fin1; Fin2|]\n            | _ =>  Add' @[|Fin0; Fin2|]\n            end).\n\nDefinition Add_Rel : pRel sigPos^+ unit 3 :=\n  fun tin '(_, tout) =>\n    forall (p0 p1 : positive),\n      tin[@Fin0] ≃ p0 ->\n      tin[@Fin1] ≃ p1 ->\n      isVoid tin[@Fin2] ->\n      tout[@Fin0] ≃ p0 /\\\n      tout[@Fin1] ≃ p1 /\\\n      tout[@Fin2] ≃ p0 + p1.\n\nLemma Add_Realise : Add ⊨ Add_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold Add. TM_Correct.\n    - apply Max_Realise.\n    - apply Add'_Realise.\n    - apply Add'_Realise.\n    - apply Add'_Realise. }\n  {\n    intros tin ([], tout) H. intros p0 p1 Hp0 Hp1 Hright. TMSimp.\n    rename H into HMax, H0 into HSwitch.\n    modpon HMax. destruct ymid; TMSimp.\n    - modpon H. nia. repeat split; auto. unfold Pos.max in H0. rewrite <- HMax2 in H0. auto.\n    - modpon H. nia. repeat split; auto. unfold Pos.max in H0. rewrite <- HMax2 in H0. auto.\n    - modpon H. nia. repeat split; auto. unfold Pos.max in H0. rewrite <- HMax2 in H0. auto.\n      now replace (p0 + p1) with (p1 + p0) by nia.\n  }\nQed.\n\n\n\n(* ** Add a number onto a register *)\n\n(* t1 <- t0 + t1; use t3 as internal register *)\nDefinition Add_onto : pTM sigPos^+ unit 3 := Add;; MoveValue _ @[|Fin2; Fin1|].\n\nDefinition Add_onto_Rel : pRel sigPos^+ unit 3 :=\n  fun tin '(_, tout) =>\n    forall (p0 p1 : positive),\n      tin[@Fin0] ≃ p0 ->\n      tin[@Fin1] ≃ p1 ->\n      isVoid tin[@Fin2] ->\n      tout[@Fin0] ≃ p0 /\\\n      tout[@Fin1] ≃ p0 + p1 /\\\n      isVoid tout[@Fin2].\n\nLemma Add_onto_Realise : Add_onto ⊨ Add_onto_Rel.\nProof.\n  eapply Realise_monotone.\n  { unfold Add_onto. TM_Correct.\n    - apply Add_Realise. }\n  {\n    intros tin ([], tout) H. intros p0 p1 Hp0 Hp1 Hright.\n    TMSimp. modpon H. modpon H0. auto.\n  }\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/TM/Code/BinNumbers/PosAddTM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.7048325784987105}}
{"text": "(* week-01_functional-programming-in-Coq.v *)\n(* YSC3236 2017-2018, Sem1 *)\n(* Olivier Danvy <danvy@yale-nus.edu.sg> *)\n(* Version of 27 Aug 2017 *)\n(* was: *)\n(* Version of 15 Aug 2017 *)\n\n(* ********** *)\n\n(* Your name and e-mail address: \nJeremy Yew\nJeremy.yew@u.yale-nus.edu.sg *)\n\n(* ********** *)\n\n(* ********** *)\n\nRequire Import Arith Bool.\n\nNotation \"A =n= B\" :=\n  (beq_nat A B) (at level 70, right associativity).\n\n(* ********** *)\n\nDefinition test_add (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 1)\n  &&\n  (candidate 1 0 =n= 1)\n  &&\n  (candidate 1 1 =n= 2)\n  &&\n  (candidate 1 2 =n= 3)\n  &&\n  (candidate 2 1 =n= 3)\n  &&\n  (candidate 2 2 =n= 4)\n  (* etc. *)\n  .\n\nFixpoint add_v1 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => S (add_v1 i' j)\n  end.\n\nCompute (test_add add_v1).\n\nFixpoint add_v2 (i j : nat) : nat :=\n  match i with\n    | O => j\n    | S i' => add_v2 i' (S j)\n  end.\n\nCompute (test_add add_v2).\n\nDefinition add_v3 (i j : nat) : nat :=\n  let fix visit n :=\n    match n with\n      | O => j\n      | S n' => S (visit n')\n    end\n  in visit i.\n\nCompute (test_add add_v3).\n\n\nDefinition test_mul (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 0)\n  &&\n  (candidate 0 1 =n= 0)\n  &&\n  (candidate 1 0 =n= 0)\n  &&\n  (candidate 1 1 =n= 1)\n  &&\n  (candidate 1 2 =n= 2)\n  &&\n  (candidate 2 1 =n= 2)\n  &&\n  (candidate 2 2 =n= 4)\n  &&\n  (candidate 2 3 =n= 6)\n(* etc. *)\n.\n\nFixpoint mul_v1 (i j : nat) : nat :=\n  match i with\n  | O =>\n    O\n  | S i' => \n    match j with\n    | O =>\n      O\n    | S j' =>\n      i + (mul_v1 i j')\n    end\n  end.\n\n  \nCompute (test_mul mul_v1).\n\n\nDefinition test_power (candidate: nat -> nat -> nat) : bool :=\n  (candidate 0 0 =n= 1)\n  &&\n  (candidate 1 0 =n= 1)\n  &&\n  (candidate 2 0 =n= 1)\n  &&\n  (candidate 0 1 =n= 0)\n  &&\n  (candidate 0 2 =n= 0)\n  &&\n  (candidate 0 10 =n= 0)\n  &&\n  (candidate 1 1 =n= 1)\n  &&\n  (candidate 1 2 =n= 1)\n  &&\n  (candidate 1 10 =n= 1)\n  &&\n  (candidate 2 1 =n= 2)\n  &&\n  (candidate 2 2 =n= 4)\n  &&\n  (candidate 2 10 =n= 1024)\n  (* etc. *)\n  .\n\n  Fixpoint power_v1 (x n : nat) : nat :=\n    match n with\n    | O =>\n      1\n    | S n' =>\n      match x with\n      | O =>\n        O \n      | S x' =>\n        mul_v1 x (power_v1 x n')\n      end\n    end.\n\nCompute (test_power power_v1).\n\n\nDefinition test_fac (candidate: nat -> nat) : bool :=\n  (candidate 0 =n= 1)\n  &&\n  (candidate 1 =n= 1)\n  &&\n  (candidate 2 =n= 2)\n  &&\n  (candidate 3 =n= 6)\n  &&\n  (candidate 4 =n= 24)\n  &&\n  (candidate 5 =n= 120)\n  &&\n  (candidate 6 =n= 720)\n  (* etc. *) .\n\nFixpoint fac_v1 (n : nat) : nat :=\n  match n with\n  | O =>\n    1\n  | S n'=>\n    n * (fac_v1 n')\n  end.\n\nCompute (test_fac fac_v1).\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  (* etc. *)\n.\n\nFixpoint fib_v1 (n : nat) : nat :=\n  match n with\n  | O =>\n    O\n  | S n' =>\n    match n' with\n    | O =>\n      1 \n    | S n'' =>\n      fib_v1 (n'') + fib_v1 (n')\n    end\n  end.\n\nCompute (test_fib fib_v1).\n\n\nFixpoint fibfib (n : nat) : (nat * nat) :=\n  match n with\n  | O =>\n   (O, S O)\n  | S n' =>\n    let (fib_n_minus_1, fib_n) := fibfib(n')\n    in (fib_n, fib_n_minus_1 + fib_n)\n  end.\n\nFixpoint fib_v2 (n : nat) : nat :=\n  let (fib_n, fib_n_plus_1) := fibfib n\n  in fib_n.\n\nCompute (test_fib fib_v2).\n\nDefinition test_even (candidate: nat -> bool) : bool :=\n  (eqb (candidate 0) true)&&\n  (eqb (candidate 1) false)&&\n  (eqb (candidate 2) true)&&\n  (eqb (candidate 3) false)&&\n  (eqb (candidate 4) true)&&\n  (eqb (candidate 5) false)&&\n  (eqb (candidate 1000) true)&&\n  (eqb (candidate 1001) false)\n  (* etc. *)\n  .\nFixpoint even_v1 (n : nat) : bool :=\n    match n with\n    | O =>\n      true\n    | S n' =>\n      negb (even_v1 n')\n    end.\n\n  Compute (test_even even_v1).\n  \nDefinition test_odd (candidate: nat -> bool) : bool :=\n  (eqb (candidate 0) false)&&\n  (eqb (candidate 1) true)&&\n  (eqb (candidate 2) false)&&\n  (eqb (candidate 3) true)&&\n  (eqb (candidate 4) false)&&\n  (eqb (candidate 5) true)&&\n  (eqb (candidate 1000) false)&&\n  (eqb (candidate 1001) true)\n  (* etc. *)\n  .\n\nFixpoint odd_v1 (n : nat) : bool :=\n  match n with\n    | O =>\n      false\n    | S n' =>\n      negb (odd_v1 n')\n    end.\n\nCompute (test_odd odd_v1).\n\n(* ***** *)\n\nInductive list_nat : Type :=\n  nil_nat : list_nat\n| cons_nat : nat -> list_nat -> list_nat.\n\nFixpoint beq_list_nat (xs ys : list_nat) : bool :=\n  match xs with\n    nil_nat =>\n    match ys with\n      nil_nat =>\n      true\n    | cons_nat y ys' =>\n      false\n    end\n  | cons_nat x xs' =>\n    match ys with\n      nil_nat =>\n      false\n    | cons_nat y ys' =>\n      (x =n= y) && beq_list_nat xs' ys'\n    end\n  end.\n\nNotation \"A =ns= B\" :=\n  (beq_list_nat A B) (at level 70, right associativity).\n\n(* ***** *)\n\nDefinition test_append (candidate: list_nat -> list_nat -> list_nat) : bool :=\n  (candidate nil_nat nil_nat =ns= nil_nat)\n  &&\n  (candidate nil_nat (cons_nat 10 nil_nat) =ns= (cons_nat 10 nil_nat))\n  &&\n  (candidate (cons_nat 1 nil_nat) (cons_nat 10 nil_nat) =ns= (cons_nat 1 (cons_nat 10 nil_nat)))\n  (* etc. *)\n  .\n\nFixpoint append_v0 (xs ys : list_nat) : list_nat :=\n  match xs with\n  | nil_nat =>\n    ys\n  | cons_nat x xs' =>\n    cons_nat x (append_v0 xs' ys)\n  end.\n\nCompute (test_append append_v0).\n\n(* ***** *)\n\nDefinition test_length (candidate: list_nat -> nat) : bool :=\n  (candidate nil_nat =n= 0)\n  &&\n  (candidate (cons_nat 1 nil_nat) =n= 1)\n  &&\n  (candidate (cons_nat 2 (cons_nat 1 nil_nat)) =n= 2)\n  (* etc. *)\n  .\n\nFixpoint length_v0 (xs : list_nat) : nat :=\n  match xs with\n  | nil_nat =>\n    0\n  | cons_nat x xs' =>\n    S (length_v0 xs')\n  end.\n\nCompute (test_length length_v0).\n\n(* ***** *)\n\n\nDefinition test_reverse (candidate : list_nat -> list_nat) : bool :=\n (candidate nil_nat =ns= nil_nat) &&\n  (candidate (cons_nat 0 nil_nat) =ns= (cons_nat 0 nil_nat)) &&\n  (candidate (cons_nat 0 (cons_nat 1 nil_nat)) =ns= (cons_nat 1 (cons_nat 0 nil_nat))) &&\n  (candidate (cons_nat 0 (cons_nat 1 (cons_nat 2 nil_nat))) =ns= (cons_nat 2 (cons_nat 1 (cons_nat 0 nil_nat))))\n  (* etc. *)\n.\n\nFixpoint reverse_v0 (xs : list_nat) : list_nat :=\n   match xs with\n  | nil_nat =>\n    nil_nat\n  | cons_nat x xs' =>\n    append_v0 (reverse_v0 xs') (cons_nat x nil_nat)\n  end. \n\nCompute (test_reverse reverse_v0).\n\n(* ***** *)\n\nInductive list_nat_nat : Type :=\n  nil_nat_nat : list_nat_nat\n| cons_nat_nat : nat -> nat -> list_nat_nat -> list_nat_nat.\n\nFixpoint beq_list_nat_nat (xs ys : list_nat_nat) : bool :=\n  match xs with\n  | nil_nat_nat =>\n    match ys with\n    | nil_nat_nat =>\n      true\n    | cons_nat_nat y1 y2 ys' =>\n      false\n     end \n  | cons_nat_nat x1 x2 xs' =>\n    match ys with\n    | nil_nat_nat =>\n      false\n    | cons_nat_nat y1 y2 ys' =>\n      (x1 =n= y1) && (x2 =n= y2) && beq_list_nat_nat xs' ys'\n    end\n  end. \n\nNotation \"A =nns= B\" :=\n  (beq_list_nat_nat A B) (at level 70, right associativity).\n\n(* ***** *)\n\nInductive option_list_nat_nat :=\n| None_list_nat_nat : option_list_nat_nat\n| Some_list_nat_nat : list_nat_nat -> option_list_nat_nat.\n\nDefinition beq_option_list_nat_nat (o1 o2 : option_list_nat_nat) : bool :=\n  match o1 with\n  | None_list_nat_nat =>\n    match o2 with\n    | None_list_nat_nat =>\n      true\n    | Some_list_nat_nat nn2s =>\n      false\n    end\n  | Some_list_nat_nat nn1s =>\n    match o2 with\n    | None_list_nat_nat =>\n      false\n    | Some_list_nat_nat nn2s =>\n      beq_list_nat_nat nn1s nn2s\n    end\n   end. \n      \nNotation \"A =onns= B\" :=\n  (beq_option_list_nat_nat A B) (at level 70, right associativity).\n\n\n\nDefinition test_append_nat_nat (candidate: list_nat_nat -> list_nat_nat -> list_nat_nat) : bool :=\n  (candidate nil_nat_nat nil_nat_nat =nns= nil_nat_nat)\n  &&\n  (candidate nil_nat_nat (cons_nat_nat 10 20 nil_nat_nat) =nns= (cons_nat_nat 10 20 nil_nat_nat))\n  &&\n  (candidate (cons_nat_nat 10 20 nil_nat_nat) (cons_nat_nat 30 40 nil_nat_nat) =nns= (cons_nat_nat 10 20 (cons_nat_nat 30 40 nil_nat_nat)))\n  (* etc. *)\n  .\n\nFixpoint append_nat_nat_v0 (xs ys : list_nat_nat) : list_nat_nat :=\n  match xs with\n  | nil_nat_nat =>\n    ys \n  | cons_nat_nat x1 x2 xs' =>\n    cons_nat_nat x1 x2 (append_nat_nat_v0 xs' ys)\n  end.\n\n  Compute (test_append_nat_nat append_nat_nat_v0).\n\n  \nDefinition test_scalar_product (candidate : list_nat -> list_nat -> option_list_nat_nat) : bool :=\n  ((candidate (cons_nat 1 nil_nat)\n              (cons_nat 10 (cons_nat 20 nil_nat)))\n   =onns=\n   None_list_nat_nat)\n  &&\n  ((candidate (cons_nat 1 (cons_nat 2 nil_nat))\n              (cons_nat 10 nil_nat))\n   =onns=\n   None_list_nat_nat)\n  &&\n  ((candidate (cons_nat 1 (cons_nat 2 nil_nat))\n              (cons_nat 10 (cons_nat 20 nil_nat)))\n   =onns=\n   (Some_list_nat_nat (cons_nat_nat 1 10 (cons_nat_nat 2 20 nil_nat_nat))))\n  (* etc. *)\n.\n\n(* This returns a reversed scalar product.*)\n(*\nFixpoint scalar_product_v0 (xs_init ys_init : list_nat) : option_list_nat_nat :=\n  let fix visit xs ys a:=\n      match xs with\n      | nil_nat =>\n        match ys with\n        | nil_nat =>\n          Some_list_nat_nat a\n        | cons_nat y ys' =>\n          None_list_nat_nat\n        end\n      | cons_nat x xs' =>\n        match ys with\n        | nil_nat =>\n          None_list_nat_nat \n        | cons_nat y ys' =>\n          visit  xs' ys' (cons_nat_nat x y a)\n        end\n      end \n  in visit xs_init ys_init nil_nat_nat.\n  \n\n  Compute (test_scalar_product scalar_product_v0).\n\n*)\n\nFixpoint scalar_product_v2 (xs_init ys_init: list_nat) : option_list_nat_nat :=\n  let fix visit xs ys a:=\n      match xs with\n      | nil_nat =>\n        match ys with\n        | nil_nat =>\n          Some_list_nat_nat a\n        | cons_nat y ys' =>\n          None_list_nat_nat\n        end\n      | cons_nat x xs' =>\n        match ys with\n        | nil_nat =>\n          None_list_nat_nat \n        | cons_nat y ys' =>\n        visit xs' ys' (append_nat_nat_v0 a (cons_nat_nat x y nil_nat_nat))\n        end\n      end \n  in visit xs_init ys_init nil_nat_nat.\n  \nCompute test_scalar_product scalar_product_v2.\n\n  \n(*Without accumulator: assumes xs ys are same length OR returns nil_nat when xs and ys are of different length, instead of option type*)\nFixpoint scalar_product_v1 (xs ys: list_nat) : list_nat_nat :=\n  match xs with\n  | nil_nat =>\n    nil_nat_nat\n  | cons_nat x xs' =>\n    match ys with\n    | nil_nat =>\n      nil_nat_nat\n    | cons_nat y ys' =>\n      cons_nat_nat x y (scalar_product_v1 xs' ys')\n    end\n  end. \n\nDefinition test_convolve (candidate : list_nat -> list_nat -> option_list_nat_nat) : bool :=\n  ((candidate (cons_nat 1 nil_nat)\n              (cons_nat 10 (cons_nat 20 nil_nat)))\n   =onns=\n   None_list_nat_nat)\n  &&\n  ((candidate (cons_nat 1 (cons_nat 2 nil_nat))\n              (cons_nat 10 nil_nat))\n   =onns=\n   None_list_nat_nat)\n  &&\n  ((candidate (cons_nat 1 (cons_nat 2 nil_nat))\n              (cons_nat 10 (cons_nat 20 nil_nat)))\n   =onns=\n   (Some_list_nat_nat (cons_nat_nat 1 20 (cons_nat_nat 2 10 nil_nat_nat))))\n  (* etc. *)\n  .\n\n  (*Attempted there-and-back-again. Didn't work.*)\n\n(*  \nFixpoint convolve_taba (xs ys : list_nat) : list_nat_nat :=\n  let fix walk xs k :=\n      match xs with\n      | nil_nat =>\n        k ys nil_nat_nat\n      | cons_nat x xs' =>\n        let back_again ys r:=\n        match ys with\n        | nil_nat =>\n          nil_nat\n        | cons_nat y ys' => \n          k ys' (cons_nat_nat x y r)\n        end\n        in walk xs' back_again\n      end\n  in walk xs (fun (n :list_nat) (m : list_nat_nat) => m). \n*)\n (* Compute (test_convolve convolve_taba).*)\n\nFixpoint convolve_v0 (xs ys : list_nat) : option_list_nat_nat :=\n    scalar_product_v2 xs (reverse_v0 ys).\n\n  Compute (test_convolve convolve_v0).\n\n\n(* ********** *)\n\nInductive binary_tree : Type :=\n  Leaf : nat -> binary_tree\n| Node : binary_tree -> binary_tree -> binary_tree.\n\nFixpoint beq_binary_tree (t1 t2 : binary_tree) : bool :=\n  match t1 with\n    Leaf n1 =>\n    match t2 with\n      Leaf n2 =>\n      n1 =n= n2\n    | Node t21 t22 =>\n      false\n    end\n  | Node t11 t12 =>\n    match t2 with\n      Leaf n2 =>\n      false\n    | Node t21 t22 =>\n      (beq_binary_tree t11 t21) && (beq_binary_tree t12 t22)\n    end\n  end.\n\nNotation \"A =bt= B\" :=\n  (beq_binary_tree A B) (at level 70, right associativity).\n\n(* ***** *)\n\nDefinition test_number_of_leaves (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 1) =n= 1)\n  &&\n  (candidate (Node (Leaf 1) (Leaf 2)) =n= 2)\n  (* etc. *)\n  .\n\nFixpoint number_of_leaves_v0 (t : binary_tree) : nat :=\n  match t with\n    Leaf n =>\n    1\n  | Node t1 t2 =>\n    (number_of_leaves_v0 t1) + (number_of_leaves_v0 t2)\n  end.\n\nCompute (test_number_of_leaves number_of_leaves_v0).\n\n(* ***** *)\n\n\nDefinition test_number_of_nodes (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 1) =n= 0)\n  &&\n  (candidate (Node (Leaf 1) (Leaf 2)) =n= 1)&&\n  (candidate (Node (Leaf 3) ((Node (Leaf 1) (Leaf 2)))) =n= 2)\n  (* etc. *)\n  .  \n\nFixpoint number_of_nodes_v0 (t : binary_tree) : nat :=\n  match t with\n    Leaf n =>\n    0\n  | Node t1 t2 =>\n    1 + (number_of_nodes_v0 t1) + (number_of_nodes_v0 t2)\n   end.\n  \n\nCompute (test_number_of_nodes number_of_nodes_v0).\n\n\n(* ***** *)\n\n\nDefinition test_smallest_leaf (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 0) =n= 0)&&\n  (candidate (Leaf 1) =n= 1)&&\n  (candidate (Node (Leaf 1) (Leaf 2)) =n= 1)&&\n  (candidate (Node (Leaf 3) ((Node (Leaf 1) (Leaf 2)))) =n= 1)&&\n  (candidate (Node (Node (Leaf 3) ((Node (Leaf 1) (Leaf 2)))) (Leaf 0)) =n= 0)                             \n  (* etc. *)\n  .\n  \nFixpoint smallest_leaf_v0 (t : binary_tree) : nat :=\n      match t with\n      | Leaf n => \n        n\n      | Node t1 t2 =>\n        min (smallest_leaf_v0 t1) (smallest_leaf_v0 t2)\n      end.\n\nCompute (test_smallest_leaf smallest_leaf_v0).\n\n\n(* ***** *)\n\nDefinition test_weight (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 0)\n   =n= 0)\n  &&\n  (candidate (Node (Leaf 1) (Leaf 10))\n   =n= 11)\n  &&\n  (candidate (Node (Leaf 1) (Node (Leaf 10) (Leaf 100)))\n   =n= 111)\n  &&\n  (candidate (Node (Node (Leaf 1) (Leaf 10)) (Leaf 100))\n   =n= 111)\n  &&\n  (candidate (Node (Node (Leaf 1) (Leaf 10)) (Node (Leaf 100) (Leaf 1000)))\n   =n= 1111)\n  (* etc. *)\n  .\n\nFixpoint weight_v0 (t : binary_tree) : nat :=\n  match t with\n  | Leaf n => \n    n\n  | Node t1 t2 =>\n    weight_v0 t1 + weight_v0 t2\n  end.\n\nCompute (test_weight weight_v0).\n\n(* ***** *)\n\n\nDefinition test_height (candidate: binary_tree -> nat) : bool :=\n  (candidate (Leaf 1)\n   =n= 0)\n  &&\n  (candidate (Node (Leaf 1) (Leaf 10))\n   =n= 1)\n  &&\n  (candidate (Node (Leaf 1) (Node (Leaf 10) (Leaf 100)))\n   =n= 2)\n  &&\n  (candidate (Node (Node (Leaf 1) (Leaf 10)) (Leaf 100))\n   =n= 2)\n  &&\n  (candidate (Node (Node (Leaf 1) (Leaf 10)) (Node (Leaf 100) (Leaf 1000)))\n   =n= 2)&&\n  (candidate (Node (Node (Node (Leaf 1) (Leaf 2)) (Leaf 10)) (Node (Leaf 100) (Leaf 1000)))\n   =n= 3)\n  (* etc. *)\n  .\n\nFixpoint height_v0 (t : binary_tree) : nat :=\n  match t with\n  | Leaf n => \n    0\n  | Node t1 t2 =>\n    S (max (height_v0 t1) (height_v0 t2))\n  end.\n\nCompute (test_height height_v0).\n\n(* ***** *)\nDefinition test_width (candidate: binary_tree -> nat) : bool :=\n   (candidate (Leaf 1)\n   =n= 1)\n  &&\n  (candidate (Node (Leaf 1) (Leaf 10))\n   =n= 2)\n  &&\n  (candidate (Node (Leaf 1) (Node (Leaf 10) (Leaf 100)))\n   =n= 2)\n  &&\n  (candidate (Node (Node (Leaf 1) (Leaf 10)) (Leaf 100))\n   =n= 2)\n  &&\n  (candidate (Node (Node (Leaf 1) (Leaf 10)) (Node (Leaf 100) (Leaf 1000)))\n   =n= 4)&&\n  (candidate (Node (Node (Node (Leaf 1) (Leaf 2)) (Leaf 10)) (Node (Leaf 100) (Leaf 1000)))\n   =n= 4)\n  (* etc. *)\n  .\nFixpoint get_width_v0 (t : binary_tree) (n : nat) : nat :=\n  match n with\n  | O => (*if n = 0*)\n    O\n  | S n' =>\n    match n' with\n    | O => (*if n = 1*)\n      match t with \n      | Leaf n =>\n        S O \n      | Node t1 t2 =>\n        S O\n      end  (*return 1 no matter what, since the width at level 1 is always 1*)\n    | S n'' => (*if n > 1*)\n      match t with\n      | Leaf n => (*no more trees to traverse, i.e. there are no trees that add to the width at level n*)\n        O\n      | Node t1 t2 =>\n        (get_width_v0 t1 n') + (get_width_v0 t2 n')\n      end\n    end\n  end.\n                                 \n \nFixpoint width_v0 (t : binary_tree) : nat :=\n  let l := S (height_v0 t) (*height + 1 = number of levels*)\n  in let fix visit l:=\n         match l with\n         | O =>\n           O\n         | S l' =>\n           match l' with\n           | O => (*if h = 1*)\n             S O (*then width = 1*)\n           | S l'' => (*if h > 1*)\n            max (get_width_v0 t l) (visit l')\n           end\n         end\n     in visit l. \n\n\nCompute (test_width width_v0).\n\n\n(* ***** *)\n\nDefinition test_flatten (candidate: binary_tree -> list_nat) : bool :=\n  (candidate (Leaf 1) =ns= (cons_nat 1 nil_nat))\n  &&\n  (candidate (Node (Leaf 1) (Leaf 2)) =ns= (cons_nat 1 (cons_nat 2 nil_nat)))\n  (* etc. *)\n  .\n\nFixpoint flatten_v0 (t : binary_tree) : list_nat :=\n  match t with\n  | Leaf n =>\n    cons_nat n nil_nat\n  | Node t1 t2 =>\n    append_v0 (flatten_v0 t1) (flatten_v0 t2)\n  end.\n\nCompute (test_flatten flatten_v0).\n\n(* ***** *)\n\nDefinition test_swap (candidate: binary_tree -> binary_tree) : bool :=\n  (candidate (Leaf 1) =bt= (Leaf 1))\n  &&\n  (candidate (Node (Leaf 1) (Leaf 2)) =bt= (Node (Leaf 2) (Leaf 1)))\n  (* etc. *)\n  .\n\nFixpoint swap_v0 (t : binary_tree) : binary_tree :=\n  match t with\n  | Leaf n =>\n    Leaf n\n  | Node t1 t2 =>\n    Node (swap_v0 t2) (swap_v0 t1)\n  end. \n\nCompute (test_swap swap_v0).\n\n(* ********** *)\n\n(* end of week-01_functional-programming-in-Coq.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-01_functional-programming-in-Coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7048325713259558}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_tactics.\nRequire Import ProofCheckingEuclid.lemma_equalitysymmetric.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral}.\n\nLemma lemma_collinear_ABC_BAC :\n\tforall A B C,\n\tCol A B C ->\n\tCol B A C.\nProof.\n\tintros A B C.\n\tintros Col_A_B_C.\n\n\tunfold Col.\n\n\tunfold Col in Col_A_B_C.\n\tdestruct Col_A_B_C as [eq_A_B | [eq_A_C | [eq_B_C | [BetS_B_A_C | [BetS_A_B_C | BetS_A_C_B]]]]].\n\t{\n\t\t(* case eq_A_B *)\n\t\tpose proof (lemma_equalitysymmetric _ _ eq_A_B) as eq_B_A.\n\t\tone_of_disjunct eq_B_A.\n\t}\n\t{\n\t\t(* case eq_A_C *)\n\t\tone_of_disjunct eq_A_C.\n\t}\n\t{\n\t\t(* case eq_B_C *)\n\t\tone_of_disjunct eq_B_C.\n\t}\n\t{\n\t\t(* case BetS_B_A_C *)\n\t\tone_of_disjunct BetS_B_A_C.\n\t}\n\t{\n\t\t(* case BetS_A_B_C *)\n\t\tone_of_disjunct BetS_A_B_C.\n\t}\n\t{\n\t\t(* case BetS_A_C_B *)\n\t\tpose proof (axiom_betweennesssymmetry _ _ _ BetS_A_C_B) as BetS_B_C_A.\n\t\tone_of_disjunct BetS_B_C_A.\n\t}\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_collinear_ABC_BAC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.704832569434327}}
{"text": "Require Export premises.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Ring.\nRequire Field.\n\nModule Type RealAxiomType.\n\nParameter ℝ : Set.\n\nDeclare Scope ℝ_scope.\nDelimit Scope ℝ_scope with ℝ.\nLocal Open Scope ℝ_scope.\n\nParameter R0 : ℝ.\nParameter R1 : ℝ.\n\n(** addition and multiplication *)\nParameter Rplus : ℝ -> ℝ -> ℝ.\nParameter Rmult : ℝ -> ℝ -> ℝ.\n\n(** the corresponding inverse elements *)\nParameter Ropp : ℝ -> ℝ.\nParameter Rinv : ℝ -> ℝ.\n\nInfix \"+\" := Rplus : ℝ_scope.\nInfix \"*\" := Rmult : ℝ_scope.\nNotation \"- x\" := (Ropp x) : ℝ_scope.\nNotation \"/ x\" := (Rinv x) : ℝ_scope.\n\n(** We'd like to be able to convert natural numbers to Rs, thereby allowing\n    ourselves to write numbers like 0, 1, 2, 3... *)\n\nFixpoint N2R (n : nat) : ℝ :=\n    match n with\n    | O    => R0\n    | 1    => R1            \n    | S n' => R1 + N2R n'\n    end.\nCoercion N2R : nat >-> ℝ.\n\n(* ################################################################# *)\n(** * The Field Equations *)\n\nAxiom R1_neq_R0 : (1:ℝ) <> (0:ℝ).\n\n(** Addition axioms *)\n\nAxiom Rplus_comm : forall r1 r2 : ℝ, r1 + r2 = r2 + r1.\n\nAxiom Rplus_assoc : forall r1 r2 r3 : ℝ, r1 + r2 + r3 = r1 + (r2 + r3).\n\nAxiom Rplus_opp_r : forall r : ℝ, r + - r = 0.\n\nAxiom Rplus_0_l : forall r : ℝ, 0 + r = r.\n\n(** Multiplicative axioms *)\n\nAxiom Rmult_comm : forall r1 r2:ℝ, r1 * r2 = r2 * r1.\n\nAxiom Rmult_assoc : forall r1 r2 r3:ℝ, r1 * r2 * r3 = r1 * (r2 * r3).\n\nAxiom Rinv_l : forall r:ℝ, r <> 0 -> / r * r = 1.\n\nAxiom Rmult_1_l : forall r:ℝ, 1 * r = r.\n\nAxiom Rmult_plus_distr_l : forall r1 r2 r3:ℝ, r1 * (r2 + r3) = r1 * r2 + r1 * r3.\n\n(* ################################################################# *)\n(** * Ordering *)\n\n(** We also impose the standard ordering on real numbers, again by\n    means of axioms *)\n\nParameter Rlt : ℝ -> ℝ -> Prop.\n\nInfix \"<\" := Rlt : ℝ_scope.\n\nDefinition Rgt (r1 r2:ℝ) : Prop := r2 < r1.\nDefinition Rle (r1 r2:ℝ) : Prop := r1 < r2 \\/ r1 = r2.\nDefinition Rge (r1 r2:ℝ) : Prop := Rgt r1 r2 \\/ r1 = r2.\n\nInfix \"<=\" := Rle : ℝ_scope.\nInfix \">=\" := Rge : ℝ_scope.\nInfix \">\" := Rgt : ℝ_scope.\n\nAxiom total_order_T : forall r1 r2 : ℝ, {r1 < r2} + {r1 = r2} + {r1 > r2}.\n    \nAxiom Rlt_asym : forall r1 r2 : ℝ, r1 < r2 -> ~ r2 < r1.\n\nAxiom Rlt_trans : forall r1 r2 r3 : ℝ, r1 < r2 -> r2 < r3 -> r1 < r3.\n\nAxiom Rplus_lt_compat_l : forall r r1 r2 : ℝ, r1 < r2 -> r + r1 < r + r2.\n\nAxiom Rmult_lt_compat_l : forall r r1 r2 : ℝ, 0 < r -> r1 < r2 -> r * r1 < r * r2.\n\n\n(* ################################################################# *)\n(** * Completeness *)\n\n(** Not every field corresponds to the real numbers:\n    Even the rational numbers (a strict subset of the reals) form a\n    field. The last thing we need to \"complete\" the real numbers is\n    the _completeness_ axiom. This states that every bounded set of\n    real numbers has a least upper bound, which itself is a real\n    number.\n\n    As usual, we will express sets as functions of type [R -> Prop],\n    indicating whether the given real number is a member of the\n    set. *)\n\nDefinition is_upper_bound (E:ℝ -> Prop) (m:ℝ) := forall x:ℝ, E x -> x <= m.\n\nDefinition bound (E:ℝ -> Prop) := exists m : ℝ, is_upper_bound E m.\n\nDefinition is_lub (E:ℝ -> Prop) (m:ℝ) :=\n    is_upper_bound E m /\\ (forall b:ℝ, is_upper_bound E b -> m <= b).\n\nAxiom\n    completeness :\n    forall E:ℝ -> Prop,\n        bound E -> (exists x : ℝ, E x) -> { m:ℝ | is_lub E m }.\n        \n(* ################################################################# *)\n(** * Computations *)\n\n(* ================================================================= *)\n(** ** The exp and log functions *)\nParameter RpowN : ℝ -> nat -> ℝ.\nInfix \"^\" := RpowN : ℝ_scope.\n\nParameter Rsqrt : ℝ -> ℝ.\nNotation \"√ x\" := (Rsqrt x) (at level 0) : ℝ_scope.\n\n\nEnd RealAxiomType.\n\n\nModule RealTheory (Export RealAxiom : RealAxiomType).\n\nOpen Scope ℝ_scope.\n\n(** Other basic operations are given in terms of our declared ones *)\n\nDefinition Rminus (r1 r2:ℝ) : ℝ := r1 + - r2.\nDefinition Rdiv (r1 r2:ℝ) : ℝ := r1 * / r2.\n\nInfix \"-\" := Rminus : ℝ_scope.\nInfix \"/\" := Rdiv : ℝ_scope.\n\n\nLemma Rplus_0_r : forall r : ℝ, r + 0 = r.\nProof.\n  (* WORKED IN CLASS *)\n  intros r.\n  rewrite Rplus_comm.\n  apply Rplus_0_l.\nQed.\n  \nLemma Rplus_opp_l : forall r, -r + r = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros r.\n  rewrite Rplus_comm.\n  apply Rplus_opp_r.\nQed.\n\nLemma Ropp_0 : -0 = 0.\nProof.\n  rewrite <- (Rplus_0_l (-0)).\n  rewrite Rplus_opp_r.\n  reflexivity.\nQed.\n\nLemma Rplus_cancel_l : forall r1 r2 r3, r1 + r2 = r1 + r3 -> r2 = r3.\nProof.\n  intros r1 r2 r3 H.\n  rewrite <- Rplus_0_l.\n  rewrite <- (Rplus_opp_l r1).\n  rewrite Rplus_assoc.\n  rewrite <- H.\n  rewrite <- Rplus_assoc.\n  rewrite Rplus_opp_l.\n  rewrite Rplus_0_l.\n  reflexivity.\nQed.\n    \nLemma R0_unique : forall r1 r2, r1 + r2 = r1 -> r2 = 0.\nProof.\n  intros r1 r2 H.\n  rewrite <- Rplus_0_r in H.\n  eapply Rplus_cancel_l.\n  apply H.\nQed.  \n\n\nLemma Rmult_0_r : forall r, r * 0 = 0.\nProof.\n  (* WORKED IN CLASS *)\n  intros r.\n  apply (@R0_unique (r * 0)).\n  rewrite <- Rmult_plus_distr_l.\n  rewrite Rplus_0_l.\n  reflexivity.\nQed.\n\nLemma Rmult_plus_distr_r : forall r1 r2 r3:ℝ, (r1 + r2) * r3 = r1 * r3 + r2 * r3.\nProof.\n  (* WORKED IN CLASS *)\n  intros r1 r2 r3.\n  rewrite Rmult_comm.\n  rewrite Rmult_plus_distr_l.\n  rewrite !(@Rmult_comm r3).\n  reflexivity.\nQed.\n\nLemma Rinv_r : forall r:ℝ, r <> 0 -> r * / r = 1.\nProof.\n  (* WORKED IN CLASS *)\n  intros. rewrite Rmult_comm.\n  apply Rinv_l.\n  assumption.\nQed.\n  \n(* ================================================================= *)\n(** ** The Ring and Field tactics *)\n\n(** We can tell Coq that R forms an algebraic _ring_ and _field_. *)\n\nExport Ring.\nExport Field.\n\nLemma R_Ring_Theory : ring_theory R0 R1 Rplus Rmult Rminus Ropp eq.\nProof.\n  constructor.\n  (* addition *)\n  (* left identity *) apply Rplus_0_l.\n  (* commutativity *) apply Rplus_comm.\n  (* associativity *) intros; rewrite Rplus_assoc; easy.\n  (* multiplication *)\n  (* left identity *) apply Rmult_1_l.\n  (* commutativity *) apply Rmult_comm.\n  (* associativity *) intros; rewrite Rmult_assoc; easy.\n  (* distributivity *) apply Rmult_plus_distr_r.\n  (* sub = opp *) reflexivity.\n  (* additive inverse *) apply Rplus_opp_r.\nDefined.\n\nAdd Ring RRing : R_Ring_Theory.  \n\nLemma R_Field_Theory : field_theory R0 R1 Rplus Rmult Rminus Ropp Rdiv Rinv eq.\nProof.\n  constructor.\n  (* ring axioms *) apply R_Ring_Theory.\n  (* 0 <> 1 *) apply R1_neq_R0.\n  (* div = inv *) reflexivity.\n  (* multiplicative inverse *) apply Rinv_l.\nDefined.\n\nAdd Field RField : R_Field_Theory.\n\nEnd RealTheory.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/history/RealTheories_Axiomatic copy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7048325675426985}}
{"text": "From mathcomp.ssreflect Require Import all_ssreflect.\n(*From mathcomp.ssreflect Require Import ssrnotation.*)\n(*From mathcomp Require Import all_ssreflect.*)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFixpoint has T (a : T -> bool) (s : seq T) : bool :=\n  if s is x :: s' then a x || has a s' else false.\n(*\nDefinition has_prop T (a : T -> bool) (x0 : T) (s : seq T)\n  :=\n    exists i, i < size s /\\ a (nth x0 s i)\n                           .*)\n\n\nDefinition is_true (b : bool) : Prop := b = true.\nCoercion is_true : bool >-> Sortclass.\n\nDefinition bool_Prop_equiv (P : Prop) (b : bool) := b = true <-> P.\n\nLemma test_bool_Prop_equiv b P : bool_Prop_equiv P b -> P \\/ ~P.\nProof.\n  case: b; case => hlr hrl.\n    by left; apply: hlr.\n      by right => hP; move: (hrl hP).\nQed.\n\nInductive reflect (P : Prop) (b : bool) : Prop :=\n| ReflectT (p : P) (e : b = true)\n| ReflectF (np : ~P) (e : b = false).\n\n                                    ", "meta": {"author": "ihasson", "repo": "coq", "sha": "0da545a4966f48b1874183812f61f54eac7b1976", "save_path": "github-repos/coq/ihasson-coq", "path": "github-repos/coq/ihasson-coq/coq-0da545a4966f48b1874183812f61f54eac7b1976/Cpdt/mcb_indspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7048108789527324}}
{"text": "(* -*- mode: coq; mode: visual-line -*- *)\nRequire Import Basics.\nRequire Import Types.\nRequire Import HSet.\nRequire Import HProp.\nRequire Import DProp.\nRequire Import Spaces.Nat.\nRequire Import Fibrations.\nRequire Import Factorization.\nRequire Import EquivalenceVarieties.\nRequire Import UnivalenceImpliesFunext.\nRequire Import Truncations.\nRequire Import Colimits.Quotient.\nImport TrM.\n\nLocal Open Scope path_scope.\nLocal Open Scope nat_scope.\n\n(** * Finite sets *)\n\n(** ** Canonical finite sets *)\n\n(** A *finite set* is a type that is merely equivalent to the canonical finite set determined by some natural number.  There are many equivalent ways to define the canonical finite sets, such as [{ k : nat & k < n}]; we instead choose a recursive one. *)\n\nFixpoint Fin (n : nat) : Type\n  := match n with\n       | 0 => Empty\n       | S n => Fin n + Unit\n     end.\n\nGlobal Instance decidable_fin (n : nat)\n: Decidable (Fin n).\nProof.\n  destruct n as [|n]; try exact _.\n  exact (inl (inr tt)).\nDefined.\n\nGlobal Instance decidablepaths_fin (n : nat)\n: DecidablePaths (Fin n).\nProof.\n  induction n as [|n IHn]; simpl; exact _.\nDefined.\n\nGlobal Instance contr_fin1 : Contr (Fin 1).\nProof.\n  refine (contr_equiv' Unit (sum_empty_l Unit)^-1).\nDefined.\n\nDefinition fin_empty (n : nat) (f : Fin n -> Empty) : n = 0.\nProof.\n  destruct n; [ reflexivity | ].\n  elim (f (inr tt)).\nDefined.\n\nFixpoint fin_max (n : nat) : Fin n.+1 :=\n  match n with\n  | O => inr tt\n  | S n' => inl (fin_max n')\n  end.\n\nFixpoint fin_finS_inject (n : nat) : Fin n -> Fin n.+1 :=\n  match n with\n  | O => Empty_rec\n  | S n' =>\n    fun i : Fin (S n') =>\n      match i with\n      | inl i' => inl (fin_finS_inject n' i')\n      | inr tt => inr tt\n      end\n  end.\n\nLemma isembedding_fin_finS_inject (n : nat) : IsEmbedding (fin_finS_inject n).\nProof.\n  apply isembedding_isinj_hset.\n  induction n.\n  - intro i. elim i.\n  - intros [] []; intro p.\n    + f_ap. apply IHn. eapply path_sum_inl. exact p.\n    + destruct u. elim (inl_ne_inr _ _ p).\n    + destruct u. elim (inr_ne_inl _ _ p).\n    + destruct u, u0; reflexivity.\nQed.\n\n(** ** Transposition equivalences *)\n\n(** To prove some basic facts about canonical finite sets, we need some standard automorphisms of them.  Here we define some transpositions and prove that they in fact do the desired things. *)\n\n(** *** Swap the last two elements. *)\n\nDefinition fin_transpose_last_two (n : nat)\n: Fin n.+2 <~> Fin n.+2\n  := ((equiv_sum_assoc _ _ _)^-1)\n       oE (1 +E (equiv_sum_symm _ _))\n       oE (equiv_sum_assoc _ _ _).\n\nArguments fin_transpose_last_two : simpl nomatch.\n\nDefinition fin_transpose_last_two_last (n : nat)\n: fin_transpose_last_two n (inr tt) = (inl (inr tt))\n  := 1.\n\nDefinition fin_transpose_last_two_nextlast (n : nat)\n: fin_transpose_last_two n (inl (inr tt)) = (inr tt)\n  := 1.\n\nDefinition fin_transpose_last_two_rest (n : nat) (k : Fin n)\n: fin_transpose_last_two n (inl (inl k)) = (inl (inl k))\n  := 1.\n\n(** *** Swap the last element with [k]. *)\n\nFixpoint fin_transpose_last_with (n : nat) (k : Fin n.+1)\n: Fin n.+1 <~> Fin n.+1.\nProof.\n  destruct k as [k|].\n  - destruct n as [|n].\n    + elim k.\n    + destruct k as [k|].\n      * refine ((fin_transpose_last_two n)\n                  oE _\n                  oE (fin_transpose_last_two n)).\n        refine ((fin_transpose_last_with n (inl k)) +E 1).\n      * apply fin_transpose_last_two.\n  - exact (equiv_idmap _).\nDefined.\n\nArguments fin_transpose_last_with : simpl nomatch.\n\nDefinition fin_transpose_last_with_last (n : nat) (k : Fin n.+1)\n: fin_transpose_last_with n k (inr tt) = k.\nProof.\n  destruct k as [k|].\n  - induction n as [|n IH]; simpl.\n    + elim k.\n    + destruct k as [k|].\n      * simpl. rewrite IH; reflexivity.\n      * simpl. apply ap, ap, path_contr.\n  - (** We have to destruct [n] since fixpoints don't reduce unless their argument is a constructor. *)\n    destruct n; simpl.\n    all:apply ap, path_contr.\nQed.\n\nDefinition fin_transpose_last_with_with (n : nat) (k : Fin n.+1)\n: fin_transpose_last_with n k k = inr tt.\nProof.\n  destruct k as [k|].\n  - induction n as [|n IH]; simpl.\n    + elim k.\n    + destruct k as [|k]; simpl.\n      * rewrite IH; reflexivity.\n      * apply ap, path_contr.\n  - destruct n; simpl.\n    all:apply ap, path_contr.\nQed.\n\nDefinition fin_transpose_last_with_rest (n : nat)\n           (k : Fin n.+1) (l : Fin n)\n           (notk : k <> inl l)\n: fin_transpose_last_with n k (inl l) = (inl l).\nProof.\n  destruct k as [k|].\n  - induction n as [|n IH]; simpl.\n    1:elim k.\n    destruct k as [k|]; simpl.\n    { destruct l as [l|]; simpl.\n      - rewrite IH.\n        + reflexivity.\n        + exact (fun p => notk (ap inl p)).\n      - reflexivity. }\n    { destruct l as [l|]; simpl.\n      - reflexivity.\n      - elim (notk (ap inl (ap inr (path_unit _ _)))). }\n  - destruct n; reflexivity.\nQed.\n\nDefinition fin_transpose_last_with_last_other (n : nat) (k : Fin n.+1)\n: fin_transpose_last_with n (inr tt) k = k.\nProof.\n  destruct n; reflexivity.\nQed.\n\nDefinition fin_transpose_last_with_invol (n : nat) (k : Fin n.+1)\n: fin_transpose_last_with n k o fin_transpose_last_with n k == idmap.\nProof.\n  intros l.\n  destruct l as [l|[]].\n  - destruct k as [k|[]].\n    { destruct (dec_paths k l) as [p|p].\n      - rewrite p.\n        rewrite fin_transpose_last_with_with.\n        apply fin_transpose_last_with_last.\n      - rewrite fin_transpose_last_with_rest;\n          try apply fin_transpose_last_with_rest;\n          exact (fun q => p (path_sum_inl _ q)). }\n    + rewrite fin_transpose_last_with_last_other.\n      apply fin_transpose_last_with_last_other.\n  - rewrite fin_transpose_last_with_last.\n    apply fin_transpose_last_with_with.\nQed.\n\n(** ** Equivalences between canonical finite sets *)\n\n(** To give an equivalence [Fin n.+1 <~> Fin m.+1] is equivalent to giving an element of [Fin m.+1] (the image of the last element) together with an equivalence [Fin n <~> Fin m].  More specifically, any such equivalence can be decomposed uniquely as a last-element transposition followed by an equivalence fixing the last element.  *)\n\n(** Here is the uncurried map that constructs an equivalence [Fin n.+1 <~> Fin m.+1]. *)\nDefinition fin_equiv (n m : nat)\n           (k : Fin m.+1) (e : Fin n <~> Fin m)\n: Fin n.+1 <~> Fin m.+1\n  := (fin_transpose_last_with m k)\n       oE (e +E 1).\n\n(** Here is the curried version that we will prove to be an equivalence. *)\nDefinition fin_equiv' (n m : nat)\n: ((Fin m.+1) * (Fin n <~> Fin m)) -> (Fin n.+1 <~> Fin m.+1)\n  := fun ke => fin_equiv n m (fst ke) (snd ke).\n\n(** We construct its inverse and the two homotopies first as versions using homotopies without funext (similar to [ExtendableAlong]), then apply funext at the end. *)\nDefinition fin_equiv_hfiber (n m : nat) (e : Fin n.+1 <~> Fin m.+1)\n: { kf : (Fin m.+1) * (Fin n <~> Fin m) & fin_equiv' n m kf == e }.\nProof.\n  simpl in e.\n  refine (equiv_sigma_prod _ _).\n  recall (e (inr tt)) as y eqn:p.\n  assert (p' := (moveL_equiv_V _ _ p)^).\n  exists y.\n  destruct y as [y|[]].\n  + simple refine (equiv_unfunctor_sum_l\n              (fin_transpose_last_with m (inl y) oE e)\n              _ _ ; _).\n    { intros a. ev_equiv.\n      assert (q : inl y <> e (inl a))\n        by exact (fun z => inl_ne_inr _ _ (equiv_inj e (z^ @ p^))).\n      set (z := e (inl a)) in *.\n      destruct z as [z|[]].\n      - rewrite fin_transpose_last_with_rest;\n        try exact tt; try assumption.\n      - rewrite fin_transpose_last_with_last; exact tt. }\n    { intros []. ev_equiv.\n      rewrite p.\n      rewrite fin_transpose_last_with_with; exact tt. }\n    intros x. unfold fst, snd; ev_equiv. simpl.\n    destruct x as [x|[]]; simpl.\n    * rewrite unfunctor_sum_l_beta.\n      apply fin_transpose_last_with_invol.\n    * refine (fin_transpose_last_with_last _ _ @ p^).\n  + simple refine (equiv_unfunctor_sum_l e _ _ ; _).\n    { intros a.\n      destruct (is_inl_or_is_inr (e (inl a))) as [l|r].\n      - exact l.\n      - assert (q := inr_un_inr (e (inl a)) r).\n        apply moveR_equiv_V in q.\n        assert (s := q^ @ ap (e^-1 o inr) (path_unit _ _) @ p').\n        elim (inl_ne_inr _ _ s). }\n    { intros []; exact (p^ # tt). }\n    intros x. unfold fst, snd; ev_equiv. simpl.\n    destruct x as [a|[]].\n    * rewrite fin_transpose_last_with_last_other.\n      apply unfunctor_sum_l_beta.\n    * simpl.\n      rewrite fin_transpose_last_with_last.\n      symmetry; apply p.\nQed.\n\nDefinition fin_equiv_inv (n m : nat) (e : Fin n.+1 <~> Fin m.+1)\n: (Fin m.+1) * (Fin n <~> Fin m)\n  := (fin_equiv_hfiber n m e).1.\n\nDefinition fin_equiv_issect (n m : nat) (e : Fin n.+1 <~> Fin m.+1)\n: fin_equiv' n m (fin_equiv_inv n m e) == e\n  := (fin_equiv_hfiber n m e).2.\n\nDefinition fin_equiv_inj_fst (n m : nat)\n           (k l : Fin m.+1) (e f : Fin n <~> Fin m)\n: (fin_equiv n m k e == fin_equiv n m l f) -> (k = l).\nProof.\n  intros p.\n  refine (_ @ p (inr tt) @ _); simpl;\n  rewrite fin_transpose_last_with_last; reflexivity.\nQed.\n\nDefinition fin_equiv_inj_snd (n m : nat)\n           (k l : Fin m.+1) (e f : Fin n <~> Fin m)\n: (fin_equiv n m k e == fin_equiv n m l f) -> (e == f).\nProof.\n  intros p.\n  intros x. assert (q := p (inr tt)); simpl in q.\n  rewrite !fin_transpose_last_with_last in q.\n  rewrite <- q in p; clear q l.\n  exact (path_sum_inl _\n           (equiv_inj (fin_transpose_last_with m k) (p (inl x)))).\nQed.\n\n(** Now it's time for funext. *)\nGlobal Instance isequiv_fin_equiv `{Funext} (n m : nat)\n: IsEquiv (fin_equiv' n m).\nProof.\n  refine (isequiv_pathsplit 0 _); split.\n  - intros e; exists (fin_equiv_inv n m e).\n    apply path_equiv, path_arrow, fin_equiv_issect.\n  - intros [k e] [l f]; simpl.\n    refine (_ , fun _ _ => tt).\n    intros p; refine (_ ; path_ishprop _ _).\n    apply (ap equiv_fun) in p.\n    apply ap10 in p.\n    apply path_prod'.\n    + refine (fin_equiv_inj_fst n m k l e f p).\n    + apply path_equiv, path_arrow.\n      refine (fin_equiv_inj_snd n m k l e f p).\nQed.\n\nDefinition equiv_fin_equiv `{Funext} (n m : nat)\n: ((Fin m.+1) * (Fin n <~> Fin m)) <~> (Fin n.+1 <~> Fin m.+1)\n  := Build_Equiv _ _ (fin_equiv' n m) _.\n\n(** In particular, this implies that if two canonical finite sets are equivalent, then their cardinalities are equal. *)\nDefinition nat_eq_fin_equiv (n m : nat)\n: (Fin n <~> Fin m) -> (n = m).\nProof.\n  revert m; induction n as [|n IHn]; induction m as [|m IHm]; intros e.\n  - exact idpath.\n  - elim (e^-1 (inr tt)).\n  - elim (e (inr tt)).\n  - refine (ap S (IHn m _)).\n    exact (snd (fin_equiv_inv n m e)).\nQed.\n\n(** ** Definition of general finite sets *)\n\nClass Finite (X : Type) :=\n  { fcard : nat ;\n    merely_equiv_fin : merely (X <~> Fin fcard) }.\n\nArguments fcard X {_}.\nArguments merely_equiv_fin X {_}.\n\nDefinition issig_finite X\n: { n : nat & merely (X <~> Fin n) } <~> Finite X.\nProof.\n  issig.\nDefined.\n\n(** Note that the sigma over cardinalities is not truncated.  Nevertheless, because canonical finite sets of different cardinalities are not isomorphic, being finite is still an hprop.  (Thus, we could have truncated the sigma and gotten an equivalent definition, but it would be less convenient to reason about.) *)\nGlobal Instance ishprop_finite X\n: IsHProp (Finite X).\nProof.\n  refine (trunc_equiv' _ (issig_finite X)).\n  apply ishprop_sigma_disjoint; intros n m Hn Hm.\n  strip_truncations.\n  refine (nat_eq_fin_equiv n m (Hm oE Hn^-1)).\nDefined.\n\n(** ** Preservation of finiteness by equivalences *)\n\nDefinition finite_equiv X {Y} (e : X -> Y) `{IsEquiv X Y e}\n: Finite X -> Finite Y.\nProof.\n  intros ?.\n  refine (Build_Finite Y (fcard X) _).\n  assert (f := merely_equiv_fin X); strip_truncations.\n  apply tr.\n  exact (equiv_compose f e^-1).\nDefined.\n\nDefinition finite_equiv' X {Y} (e : X <~> Y)\n: Finite X -> Finite Y\n  := finite_equiv X e.\n\nCorollary finite_equiv_equiv X Y\n: (X <~> Y) -> (Finite X <~> Finite Y).\nProof.\n  intros ?; apply equiv_iff_hprop; apply finite_equiv';\n    [ assumption | symmetry; assumption ].\nDefined.\n\nDefinition fcard_equiv {X Y} (e : X -> Y) `{IsEquiv X Y e}\n           `{Finite X} `{Finite Y}\n: fcard X = fcard Y.\nProof.\n  transitivity (@fcard Y (finite_equiv X e _)).\n  - reflexivity.\n  - exact (ap (@fcard Y) (path_ishprop _ _)).\nDefined.\n\nDefinition fcard_equiv' {X Y} (e : X <~> Y)\n           `{Finite X} `{Finite Y}\n: fcard X = fcard Y\n  := fcard_equiv e.\n\n(** ** Simple examples of finite sets *)\n\n(** Canonical finite sets are finite *)\nGlobal Instance finite_fin n : Finite (Fin n)\n  := Build_Finite _ n (tr (equiv_idmap _)).\n\n(** This includes the empty set. *)\nGlobal Instance finite_empty : Finite Empty\n  := finite_fin 0.\n\n(** The unit type is finite, since it's equivalent to [Fin 1]. *)\nGlobal Instance finite_unit : Finite Unit.\nProof.\n  refine (finite_equiv' (Fin 1) _ _); simpl.\n  apply sum_empty_l.\nDefined.\n\n(** Thus, any contractible type is finite. *)\nGlobal Instance finite_contr X `{Contr X} : Finite X\n  := finite_equiv Unit equiv_contr_unit^-1 _.\n\n(** Any decidable hprop is finite, since it must be equivalent to [Empty] or [Unit]. *)\nDefinition finite_decidable_hprop X `{IsHProp X} `{Decidable X}\n: Finite X.\nProof.\n  destruct (dec X) as [x|nx].\n  - assert (Contr X) by exact (contr_inhabited_hprop X x).\n    exact _.\n  - refine (finite_equiv Empty nx^-1 _).\nDefined.\n\nHint Immediate finite_decidable_hprop : typeclass_instances.\n\n(** It follows that the propositional truncation of any finite set is finite. *)\nGlobal Instance finite_merely X {fX : Finite X}\n: Finite (merely X).\nProof.\n  (** As in decidable_finite_hprop, we case on cardinality first to avoid needing funext. *)\n  destruct fX as [[|n] e]; refine (finite_decidable_hprop _).\n  - right.\n    intros x; strip_truncations; exact (e x).\n  - left.\n    strip_truncations; exact (tr (e^-1 (inr tt))).\nDefined.\n\n(** Finite sets are closed under path-spaces. *)\nGlobal Instance finite_paths {X} `{Finite X} (x y : X)\n: Finite (x = y).\nProof.\n  (** If we assume [Funext], then typeclass inference produces this automatically, since [X] has decidable equality and (hence) is a set, so [x=y] is a decidable hprop.  But we can also deduce it without funext, since [Finite] is an hprop even without funext. *)\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  refine (finite_equiv _ (ap e)^-1 _).\n  apply finite_decidable_hprop; exact _.\nDefined.\n\n(** Finite sets are also closed under successors. *)\n\nGlobal Instance finite_succ X `{Finite X} : Finite (X + Unit).\nProof.\n  refine (Build_Finite _ (fcard X).+1 _).\n  pose proof (merely_equiv_fin X).\n  strip_truncations; apply tr.\n  refine (_ +E 1); assumption.\nDefined.\n\nDefinition fcard_succ X `{Finite X}\n: fcard (X + Unit) = (fcard X).+1\n  := 1.\n\n(** ** Decidability *)\n\n(** Like canonical finite sets, finite sets have decidable equality. *)\nGlobal Instance decidablepaths_finite `{Funext} X `{Finite X}\n: DecidablePaths X.\nProof.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  refine (decidablepaths_equiv _ e^-1 _).\nDefined.\n\n(** However, contrary to what you might expect, we cannot assert that \"every finite set is decidable\"!  That would be claiming a *uniform* way to select an element from every nonempty finite set, which contradicts univalence. *)\n\n(** One thing we can prove is that any finite hprop is decidable. *)\nGlobal Instance decidable_finite_hprop X `{IsHProp X} {fX : Finite X}\n: Decidable X.\nProof.\n  (** To avoid having to use [Funext], we case on the cardinality of [X] before stripping the truncation from its equivalence to [Fin n]; if we did things in the other order then we'd have to know that [Decidable X] is an hprop, which requires funext. *)\n  destruct fX as [[|n] e].\n  - right; intros x.\n    strip_truncations; exact (e x).\n  - left.\n    strip_truncations; exact (e^-1 (inr tt)).\nDefined.\n\n(** It follows that if [X] is finite, then its propositional truncation is decidable. *)\nGlobal Instance decidable_merely_finite X {fX : Finite X}\n: Decidable (merely X).\nProof.\n  exact _.\nDefined.\n\n(** From this, it follows that any finite set is *merely* decidable. *)\nDefinition merely_decidable_finite X `{Finite X}\n: merely (Decidable X).\nProof.\n  apply O_decidable; exact _.\nDefined.\n\n(** ** Induction over finite sets *)\n\n(** Most concrete applications of this don't actually require univalence, but the general version does.  For this reason the general statement is less useful (and less used in the sequel) than it might be. *)\nDefinition finite_ind_hprop `{Univalence}\n           (P : forall X, Finite X -> Type)\n           `{forall X (fX:Finite X), IsHProp (P X _)}\n           (f0 : P Empty _)\n           (fs : forall X (fX:Finite X), P X _ -> P (X + Unit)%type _)\n           (X : Type) `{Finite X}\n: P X _.\nProof.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  assert (p := transportD Finite P (path_universe e^-1) _).\n  refine (transport (P X) (path_ishprop _ _) (p _)).\n  generalize (fcard X); intros n.\n  induction n as [|n IH].\n  - exact f0.\n  - refine (transport (P (Fin n.+1)) (path_ishprop _ _) (fs _ _ IH)).\nDefined.\n\n(** ** The finite axiom of choice *)\n\nDefinition finite_choice {X} `{Finite X} (P : X -> Type)\n: (forall x, merely (P x)) -> merely (forall x, P x).\nProof.\n  intros f.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  set (P' := P o e^-1).\n  assert (f' := (fun x => f (e^-1 x)) : forall x, merely (P' x)).\n  refine (Trunc_functor (X := forall x:Fin (fcard X), P' x) (-1) _ _).\n  - intros g x; exact (eissect e x # g (e x)).\n  - clearbody P'; clear f P e.\n    generalize dependent (fcard X); intros n P f.\n    induction n as [|n IH].\n    + exact (tr (Empty_ind P)).\n    + specialize (IH (P o inl) (f o inl)).\n      assert (e := f (inr tt)).\n      strip_truncations.\n      exact (tr (sum_ind P IH (Unit_ind e))).\nDefined.\n\n(** ** Constructions on finite sets *)\n\n(** Finite sets are closed under sums, products, function spaces, and equivalence spaces.  There are multiple choices we could make regarding how to prove these facts.  Since we know what the cardinalities ought to be in all cases (since we know how to add, multiply, exponentiate, and take factorials of natural numbers), we could specify those off the bat, and then reduce to the case of canonical finite sets.  However, it's more amusing to instead prove finiteness of these constructions by \"finite-set induction\", and then *deduce* that their cardinalities are given by the corresponding operations on natural numbers (because they satisfy the same recurrences). *)\n\n(** *** Binary sums *)\n\nGlobal Instance finite_sum X Y `{Finite X} `{Finite Y}\n: Finite (X + Y).\nProof.\n  assert (e := merely_equiv_fin Y).\n  strip_truncations.\n  refine (finite_equiv _ (functor_sum idmap e^-1) _).\n  generalize (fcard Y); intros n.\n  induction n as [|n IH].\n  - refine (finite_equiv _ (sum_empty_r X)^-1 _).\n  - refine (finite_equiv _ (equiv_sum_assoc X _ Unit) _).\nDefined.\n\n(** Note that the cardinality function [fcard] actually computes.  The same will be true of all the other proofs in this section, though we don't always verify it. *)\nGoal fcard (Fin 3 + Fin 4) = 7.\n  reflexivity.\nAbort.\n\nDefinition fcard_sum X Y `{Finite X} `{Finite Y}\n: fcard (X + Y) = (fcard X + fcard Y).\nProof.\n  refine (_ @ nat_plus_comm _ _).\n  assert (e := merely_equiv_fin Y).\n  strip_truncations.\n  refine (fcard_equiv' (1 +E e) @ _).\n  refine (_ @ ap (fun y => (y + fcard X)) (fcard_equiv e^-1)).\n  generalize (fcard Y); intros n.\n  induction n as [|n IH].\n  - refine (fcard_equiv (sum_empty_r X)^-1).\n  - refine (fcard_equiv (equiv_sum_assoc _ _ _)^-1 @ _).\n    exact (ap S IH).\nDefined.\n\n(** *** Binary products *)\n\nGlobal Instance finite_prod X Y `{Finite X} `{Finite Y}\n: Finite (X * Y).\nProof.\n  assert (e := merely_equiv_fin Y).\n  strip_truncations.\n  refine (finite_equiv _ (functor_prod idmap e^-1) _).\n  generalize (fcard Y); intros n.\n  induction n as [|n IH].\n  - refine (finite_equiv _ (prod_empty_r X)^-1 _).\n  - refine (finite_equiv _ (sum_distrib_l X _ Unit)^-1 (finite_sum _ _)).\n    refine (finite_equiv _ (prod_unit_r X)^-1 _).\nDefined.\n\nDefinition fcard_prod X Y `{Finite X} `{Finite Y}\n: fcard (X * Y) = fcard X * fcard Y.\nProof.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  refine (fcard_equiv' (e *E 1) @ _).\n  refine (_ @ ap (fun x => x * fcard Y) (fcard_equiv e^-1)).\n  generalize (fcard X); intros n.\n  induction n as [|n IH].\n  - refine (fcard_equiv (prod_empty_l Y)).\n  - refine (fcard_equiv (sum_distrib_r Y (Fin n) Unit) @ _).\n    refine (fcard_sum _ _ @ _).\n    simpl.\n    refine (_ @ nat_plus_comm _ _).\n    refine (ap011 plus _ _).\n    + apply IH.\n    + apply fcard_equiv', prod_unit_l.\n  Defined.\n\n(** *** Function types *)\n\n(** Finite sets are closed under function types, and even dependent function types. *)\n\nGlobal Instance finite_forall `{Funext} {X} (Y : X -> Type)\n       `{Finite X} `{forall x, Finite (Y x)}\n: Finite (forall x:X, Y x).\nProof.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  simple refine (finite_equiv' _\n            (equiv_functor_forall' (P := fun x => Y (e^-1 x)) e _) _); try exact _.\n  { intros x; refine (equiv_transport _ _ _ (eissect e x)). }\n  set (Y' := Y o e^-1); change (Finite (forall x, Y' x)).\n  assert (forall x, Finite (Y' x)) by exact _; clearbody Y'; clear e.\n  generalize dependent (fcard X); intros n Y' ?.\n  induction n as [|n IH].\n  - exact _.\n  - refine (finite_equiv _ (equiv_sum_ind Y') _).\n    apply finite_prod.\n    + apply IH; exact _.\n    + refine (finite_equiv _ (@Unit_ind (fun u => Y' (inr u))) _).\n      refine (isequiv_unit_ind (Y' o inr)).\nDefined.\n\nDefinition fcard_arrow `{Funext} X Y `{Finite X} `{Finite Y}\n: fcard (X -> Y) = nat_exp (fcard Y) (fcard X).\nProof.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  refine (fcard_equiv (functor_arrow e idmap)^-1 @ _).\n  refine (_ @ ap (fun x => nat_exp (fcard Y) x) (fcard_equiv e)).\n  generalize (fcard X); intros n.\n  induction n as [|n IH].\n  - reflexivity.\n  - refine (fcard_equiv (equiv_sum_ind (fun (_:Fin n.+1) => Y))^-1 @ _).\n    refine (fcard_prod _ _ @ _).\n    apply (ap011 mult).\n    + assumption.\n    + refine (fcard_equiv (@Unit_ind (fun (_:Unit) => Y))^-1).\nDefined.\n\n(** [fcard] still computes, despite the funext: *)\nGoal forall fs:Funext, fcard (Fin 3 -> Fin 4) = 64.\n  reflexivity.\nAbort.\n\n(** *** Automorphism types (i.e. symmetric groups) *)\n\nGlobal Instance finite_aut `{Funext} X `{Finite X}\n: Finite (X <~> X).\nProof.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  refine (finite_equiv _\n            (equiv_functor_equiv e^-1 e^-1) _).\n  generalize (fcard X); intros n.\n  induction n as [|n IH].\n  - exact _.\n  - refine (finite_equiv _ (equiv_fin_equiv n n) _).\nDefined.\n\nDefinition fcard_aut `{Funext} X `{Finite X}\n: fcard (X <~> X) = factorial (fcard X).\nProof.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  refine (fcard_equiv\n            (equiv_functor_equiv e^-1 e^-1)^-1 @ _).\n  generalize (fcard X); intros n.\n  induction n as [|n IH].\n  - reflexivity.\n  - refine (fcard_equiv (equiv_fin_equiv n n)^-1 @ _).\n    refine (fcard_prod _ _ @ _).\n    apply ap011.\n    + reflexivity.\n    + assumption.\nDefined.\n\n(** [fcard] still computes: *)\nGoal forall fs:Funext, fcard (Fin 4 <~> Fin 4) = 24.\n  reflexivity.\nAbort.\n\n(** ** Finite sums of natural numbers *)\n\n(** Perhaps slightly less obviously, finite sets are also closed under sigmas. *)\n\nGlobal Instance finite_sigma {X} (Y : X -> Type)\n       `{Finite X} `{forall x, Finite (Y x)}\n: Finite { x:X & Y x }.\nProof.\n  assert (e := merely_equiv_fin X).\n  strip_truncations.\n  refine (finite_equiv' _\n            (equiv_functor_sigma (equiv_inverse e)\n                                 (fun x (y:Y (e^-1 x)) => y)) _).\n  (** Unfortunately, because [compose] is currently beta-expanded, [set (Y' := Y o e^-1)] doesn't change the goal. *)\n  set (Y' := fun x => Y (e^-1 x)).\n  assert (forall x, Finite (Y' x)) by exact _; clearbody Y'; clear e.\n  generalize dependent (fcard X); intros n Y' ?.\n  induction n as [|n IH].\n  - refine (finite_equiv Empty pr1^-1 _).\n  - refine (finite_equiv _ (equiv_sigma_sum (Fin n) Unit Y')^-1 _).\n    apply finite_sum.\n    + apply IH; exact _.\n    + refine (finite_equiv _ (equiv_contr_sigma _)^-1 _).\nDefined.\n\n(** Amusingly, this automatically gives us a way to add up a family of natural numbers indexed by any finite set.  (We could of course also define such an operation directly, probably using [merely_ind_hset].) *)\n\nDefinition finplus {X} `{Finite X} (f : X -> nat) : nat\n  := fcard { x:X & Fin (f x) }.\n\nDefinition fcard_sigma {X} (Y : X -> Type)\n       `{Finite X} `{forall x, Finite (Y x)}\n: fcard { x:X & Y x } = finplus (fun x => fcard (Y x)).\nProof.\n  set (f := fun x => fcard (Y x)).\n  set (g := fun x => merely_equiv_fin (Y x) : merely (Y x <~> Fin (f x))).\n  apply finite_choice in g.\n  strip_truncations.\n  unfold finplus.\n  refine (fcard_equiv' (equiv_functor_sigma' (equiv_idmap X) g)).\nDefined.\n\n(** The sum of a finite constant family is the product by its cardinality. *)\nDefinition finplus_const X `{Finite X} n\n: finplus (fun x:X => n) = fcard X * n.\nProof.\n  transitivity (fcard (X * Fin n)).\n  - exact (fcard_equiv' (equiv_sigma_prod0 X (Fin n))).\n  - exact (fcard_prod X (Fin n)).\nDefined.\n\n(** Closure under sigmas and paths also implies closure under hfibers. *)\nDefinition finite_hfiber {X Y} (f : X -> Y) (y : Y)\n       `{Finite X} `{Finite Y}\n: Finite (hfiber f y).\nProof.\n  exact _.\nDefined.\n\n(** Therefore, the cardinality of the domain of a map between finite sets is the sum of the cardinalities of its hfibers. *)\nDefinition fcard_domain {X Y} (f : X -> Y) `{Finite X} `{Finite Y}\n: fcard X = finplus (fun y => fcard (hfiber f y)).\nProof.\n  refine (_ @ fcard_sigma (hfiber f)).\n  refine (fcard_equiv' (equiv_fibration_replacement f)).\nDefined.\n\n(** In particular, the image of a map between finite sets is finite. *)\nDefinition finite_image\n       {X Y} `{Finite X} `{Finite Y} (f : X -> Y)\n: Finite (himage f).\nProof.\n  exact _.\nDefined.\n\n(** ** Finite products of natural numbers *)\n\n(** Similarly, closure of finite sets under [forall] automatically gives us a way to multiply a family of natural numbers indexed by any finite set.  Of course, if we defined this explicitly, it wouldn't need funext. *)\n\nDefinition finmult `{Funext} {X} `{Finite X} (f : X -> nat) : nat\n  := fcard (forall x:X, Fin (f x)).\n\nDefinition fcard_forall `{Funext} {X} (Y : X -> Type)\n       `{Finite X} `{forall x, Finite (Y x)}\n: fcard (forall x:X, Y x) = finmult (fun x => fcard (Y x)).\nProof.\n  set (f := fun x => fcard (Y x)).\n  set (g := fun x => merely_equiv_fin (Y x) : merely (Y x <~> Fin (f x))).\n  apply finite_choice in g.\n  strip_truncations.\n  unfold finmult.\n  refine (fcard_equiv' (equiv_functor_forall' (equiv_idmap X) g)).\nDefined.\n\n(** The product of a finite constant family is the exponential by its cardinality. *)\nDefinition finmult_const `{Funext} X `{Finite X} n\n: finmult (fun x:X => n) = nat_exp n (fcard X).\nProof.\n  refine (fcard_arrow X (Fin n)).\nDefined.\n\n\n(** ** Finite subsets *)\n\n(** Closure under sigmas implies that a detachable subset of a finite set is finite. *)\nGlobal Instance finite_detachable_subset {X} `{Finite X} (P : X -> Type)\n       `{forall x, IsHProp (P x)} `{forall x, Decidable (P x)}\n: Finite { x:X & P x }.\nProof.\n  exact _.\nDefined.\n\n(** Conversely, if a subset of a finite set is finite, then it is detachable.  We show first that an embedding between finite subsets has detachable image. *)\nDefinition detachable_image_finite\n           {X Y} `{Finite X} `{Finite Y} (f : X -> Y) `{IsEmbedding f}\n: forall y, Decidable (hfiber f y).\nProof.\n  intros y.\n  assert (ff : Finite (hfiber f y)) by exact _.\n  destruct ff as [[|n] e].\n  - right; intros u; strip_truncations; exact (e u).\n  - left; strip_truncations; exact (e^-1 (inr tt)).\nDefined.\n\nDefinition detachable_finite_subset {X} `{Finite X}\n           (P : X -> Type) `{forall x, IsHProp (P x)}\n           {Pf : Finite ({ x:X & P x })}\n: forall x, Decidable (P x).\nProof.\n  intros x.\n  refine (decidable_equiv _ (hfiber_fibration x P)^-1 _).\n  refine (detachable_image_finite pr1 x).\n  - assumption.                 (** Why doesn't Coq find this? *)\n  - apply mapinO_pr1; exact _.  (** Why doesn't Coq find this? *)\nDefined.\n\n(** ** Quotients *)\n\n(** The quotient of a finite set by a detachable equivalence relation is finite. *)\n\nSection DecidableQuotients.\n  Context `{Univalence} {X} `{Finite X}\n          (R : Relation X) `{is_mere_relation X R}\n          `{Reflexive _ R} `{Transitive _ R} `{Symmetric _ R}\n          {Rd : forall x y, Decidable (R x y)}.\n\n  Global Instance finite_quotient : Finite (Quotient R).\n  Proof.\n    assert (e := merely_equiv_fin X).\n    strip_truncations.\n    pose (R' x y := R (e^-1 x) (e^-1 y)).\n    assert (is_mere_relation _ R') by exact _.\n    assert (Reflexive R') by (intros ?; unfold R'; apply reflexivity).\n    assert (Symmetric R') by (intros ? ?; unfold R'; apply symmetry).\n    assert (Transitive R') by (intros ? ? ?; unfold R'; apply transitivity).\n    assert (R'd : forall x y, Decidable (R' x y))\n      by (intros ? ?; unfold R'; apply Rd).\n    srefine (finite_equiv' _ (equiv_quotient_functor R' R e^-1 _) _).\n    1: by try (intros; split).\n    clearbody R'; clear e.\n    generalize dependent (fcard X);\n      intros n; induction n as [|n IH]; intros R' ? ? ? ? ?.\n    - refine (finite_equiv Empty _^-1 _).\n      refine (Quotient_rec R' _ Empty_rec (fun x _ _ => match x with end)).\n    - pose (R'' x y := R' (inl x) (inl y)).\n      assert (is_mere_relation _ R'') by exact _.\n      assert (Reflexive R'') by (intros ?; unfold R''; apply reflexivity).\n      assert (Symmetric R'') by (intros ? ?; unfold R''; apply symmetry).\n      assert (Transitive R'') by (intros ? ? ?; unfold R''; apply transitivity).\n      assert (forall x y, Decidable (R'' x y)) by (intros ? ?; unfold R''; apply R'd).\n      assert (inlresp := (fun x y => idmap)\n                         : forall x y, R'' x y -> R' (inl x) (inl y)).\n      destruct (dec (merely {x:Fin n & R' (inl x) (inr tt)})) as [p|np].\n      { strip_truncations.\n        destruct p as [x r].\n        refine (finite_equiv' (Quotient R'') _ _).\n        refine (Build_Equiv _ _ (Quotient_functor R'' R' inl inlresp) _).\n        apply isequiv_surj_emb.\n        - apply BuildIsSurjection.\n          refine (Quotient_ind_hprop R' _ _).\n          intros [y|[]]; apply tr.\n          + exists (class_of R'' y); reflexivity.\n          + exists (class_of R'' x); simpl.\n            apply qglue, r.\n        - apply isembedding_isinj_hset; intros u.\n          refine (Quotient_ind_hprop R'' _ _); intros v.\n          revert u; refine (Quotient_ind_hprop R'' _ _); intros u.\n          simpl; intros q.\n          apply qglue; unfold R''.\n          exact (related_quotient_paths R' (inl u) (inl v) q). }\n      { refine (finite_equiv' (Quotient R'' + Unit) _ _).\n        refine (Build_Equiv _ _ (sum_ind (fun _ => Quotient R')\n                                        (Quotient_functor R'' R' inl inlresp)\n                                        (fun _ => class_of R' (inr tt))) _).\n        apply isequiv_surj_emb.\n        - apply BuildIsSurjection.\n          refine (Quotient_ind_hprop R' _ _).\n          intros [y|[]]; apply tr.\n          + exists (inl (class_of R'' y)); reflexivity.\n          + exists (inr tt); reflexivity.\n        - apply isembedding_isinj_hset; intros u.\n          refine (sum_ind _ _ _).\n          + refine (Quotient_ind_hprop R'' _ _); intros v.\n            revert u; refine (sum_ind _ _ _).\n            * refine (Quotient_ind_hprop R'' _ _); intros u.\n              simpl; intros q.\n              apply ap, qglue; unfold R''.\n              exact (related_quotient_paths R' (inl u) (inl v) q).\n            * intros []; simpl.\n              intros q.\n              apply related_quotient_paths in q; try exact _.\n              apply symmetry in q.\n              elim (np (tr (v ; q))).\n          + intros []; simpl.\n            destruct u as [u|[]]; simpl.\n            * revert u; refine (Quotient_ind_hprop R'' _ _); intros u; simpl.\n              intros q.\n              apply related_quotient_paths in q; try exact _.\n              elim (np (tr (u;q))).\n            * intros; reflexivity. }\n  Defined.\n\n  (** Therefore, the cardinality of [X] is the sum of the cardinalities of its equivalence classes. *)\n  Definition fcard_quotient\n  : fcard X = finplus (fun z:Quotient R => fcard {x:X & in_class R z x}).\n  Proof.\n    refine (fcard_domain (class_of R) @ _).\n    apply ap, path_arrow; intros z; revert z.\n    refine (Quotient_ind_hprop _ _ _); intros x; simpl.\n    apply fcard_equiv'; unfold hfiber.\n    refine (equiv_functor_sigma' 1 _); intros y; simpl.\n    symmetry.\n    refine (path_quotient R y x oE _).\n    apply equiv_iff_hprop; apply symmetry.\n  Defined.\n\nEnd DecidableQuotients.\n\n(** ** Injections *)\n\n(** An injection between finite sets induces an inequality between their cardinalities. *)\nDefinition leq_inj_finite `{Funext} {X Y} {fX : Finite X} {fY : Finite Y}\n           (f : X -> Y) (i : IsEmbedding f)\n: fcard X <= fcard Y.\nProof.\n  assert (MapIn (-1)%trunc f) by exact _. clear i.\n  destruct fX as [n e]; simpl.\n  destruct fY as [m e']; simpl.\n  strip_truncations.\n  pose (g := e' o f o e^-1).\n  assert (MapIn (-1)%trunc g) by (unfold g; exact _).\n  clearbody g. clear e e'. generalize dependent m.\n  induction n as [|n IHn].\n  { intros; exact tt. }\n  intros m g ?.\n  assert (i : isinj g) by (apply isinj_embedding; exact _).\n  destruct m as [|m].\n  { elim (g (inr tt)). }\n  pose (h := (fin_transpose_last_with m (g (inr tt)))^-1 o g).\n  assert (MapIn (-1)%trunc h) by (unfold h; exact _).\n  assert (Ha : forall a:Fin n, is_inl (h (inl a))).\n  { intros a.\n    remember (g (inl a)) as b eqn:p.\n    destruct b as [b|[]].\n    - assert (q : g (inl a) <> (g (inr tt))).\n      { intros r. exact (inl_ne_inr _ _ (i _ _ r)). }\n      rewrite p in q; apply symmetric_neq in q.\n      assert (r : h (inl a) = inl b).\n      { unfold h; apply moveR_equiv_V; symmetry.\n        refine (fin_transpose_last_with_rest m (g (inr tt)) b q @ p^). }\n      rewrite r; exact tt.\n    - assert (q : h (inl a) = g (inr tt)).\n      { unfold h; apply moveR_equiv_V; symmetry.\n        refine (_ @ p^); apply fin_transpose_last_with_with. }\n      rewrite q.\n      destruct (is_inl_or_is_inr (g (inr tt))) as [l|r]; try assumption.\n      assert (s := inr_un_inr _ r).\n      revert s; generalize (un_inr (g (inr tt)) r); intros [] s.\n      elim (inl_ne_inr _ _ (i _ _ (p @ s))). }\n  assert (Hb : forall b:Unit, is_inr (h (inr b))).\n  { intros [].\n    assert (q : h (inr tt) = inr tt).\n    { unfold h; apply moveR_equiv_V; symmetry.\n      apply fin_transpose_last_with_last. }\n    rewrite q; exact tt. }\n  exact (IHn m (unfunctor_sum_l h Ha)\n             (mapinO_unfunctor_sum_l (-1)%trunc h Ha Hb)).\nQed.\n\n(** ** Initial segments of [nat] *)\n\nDefinition nat_fin (n : nat) (k : Fin n) : nat.\nProof.\n  induction n as [|n nf].\n  - contradiction.\n  - destruct k as [k|_].\n    + exact (nf k).\n    + exact n.\nDefined.\n\nDefinition nat_fin_inl (n : nat) (k : Fin n)\n: nat_fin n.+1 (inl k) = nat_fin n k\n  := 1.\n\nDefinition nat_fin_compl (n : nat) (k : Fin n) : nat.\nProof.\n  induction n as [|n nfc].\n  - contradiction.\n  - destruct k as [k|_].\n    + exact (nfc k).+1.\n    + exact 0.\nDefined.\n\nDefinition nat_fin_compl_compl n k\n: (nat_fin n k + nat_fin_compl n k).+1 = n.\nProof.\n  induction n as [|n IH].\n  - contradiction.\n  - destruct k as [k|?]; simpl.\n    + rewrite nat_plus_comm.\n      specialize (IH k).\n      rewrite nat_plus_comm in IH.\n      exact (ap S IH).\n    + rewrite nat_plus_comm; reflexivity.\nQed.\n\n(** ** Enumerations *)\n\n(** A function from [nat] to a finite set must repeat itself eventually. *)\nSection Enumeration.\n  Context `{Funext} {X} `{Finite X} (e : nat -> X).\n\n  Let er (n : nat) : Fin n -> X\n    := fun k => e (nat_fin n k).\n\n  Lemma finite_enumeration_stage (n : nat)\n  : IsEmbedding (er n)\n    + { n : nat & { k : nat & e n = e (n + k).+1 }}.\n  Proof.\n    induction n as [|n [IH|IH]].\n    - left. intros x.\n      apply hprop_inhabited_contr; intros [[] _].\n    - destruct (detachable_image_finite (er n) (er n.+1 (inr tt)))\n        as [[k p]|ne].\n      + right.\n        exists (nat_fin n k).\n        exists (nat_fin_compl n k).\n        rewrite nat_fin_compl_compl.\n        exact p.\n      + left. intros x.\n        apply hprop_allpath.\n        intros k l.\n        apply path_sigma_hprop.\n        destruct k as [[k|[]] p], l as [[l|[]] q]; simpl.\n        * apply isinj_embedding in IH.\n          apply ap.\n          apply IH.\n          unfold er in p, q. simpl in p, q.\n          exact (p @ q^).\n        * refine (Empty_rec (ne _)).\n          exists k.\n          exact (p @ q^).\n        * refine (Empty_rec (ne _)).\n          exists l.\n          exact (q @ p^).\n        * reflexivity.\n    - right; exact IH.\n  Defined.\n\n  Definition finite_enumeration_repeats\n  : { n : nat & { k : nat & e n = e (n + k).+1 }}.\n  Proof.\n    destruct (finite_enumeration_stage (fcard X).+1) as [p|?].\n    - assert (q := leq_inj_finite (er (fcard X).+1) p); simpl in q.\n      elim (not_nltn _ q).\n    - assumption.\n  Defined.\n\nEnd Enumeration.\n\nLtac FinIndOn X := repeat\n  match type of X with\n  | Fin 0 => destruct X\n  | Empty => destruct X\n  | Unit => destruct X\n  | Fin ?n => destruct X as [X|X]\n  | ?L + Unit => destruct X as [X|X]\n  end.\n\nLtac FinInd := let X := fresh \"X\" in intro X; FinIndOn X.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Spaces/Finite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7048108730710474}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.BinInt.\n\nRequire Import HJ.Vars.\nRequire Import HJ.Phasers.Lang.\nRequire Import HJ.Phasers.PhaseDiff.\n\nOpen Scope Z.\n\n(**\n\nThe wait-phase difference [z] is defined for a pair of tasks t1 t2 such\nthat there exists a phaser ph for which its wait phase difference is [z], [WP(ph,t1) - WP(ph,t2) = z].\n\nA well-formed phaser map respects a few properties:\n * for any task [t] registered in at least a phaser, we have that [t - t = 0]\n * for any two tasks [t1] and [t2], the wait-phase difference for any phaser is the same\n   (so the wait-phase difference is a function).\n\n*)\n\nSection DIFF_SUM.\n\nVariable A : Type.\nNotation edge := (A * A) % type.\nVariable diff: edge -> Z -> Prop.\nVariable get_diff: edge -> option Z.\nVariable get_diff_spec:\n  forall e z,\n  get_diff e = Some z <-> diff e z.\n\nLemma diff_fun:\n  forall e z z',\n  diff e z ->\n  diff e z' ->\n  z = z'.\nProof.\n  intros.\n  rewrite <- get_diff_spec in *.\n  rewrite H in H0.\n  inversion H0.\n  trivial.\nQed.\n\n(**\nWe say that the sequence of tasks [t1 t2 ... tn] has a sum of [s].\n\nsuch that there exists a wait phase difference between any task [t_i] and\ntask [t_{i + 1}], where [1 <= i <= n] and the sum of all wait-phase\ndifferences is [s].\n\n*)\nInductive DiffSum : list edge -> Z -> Prop :=\n  | diff_sum_nil:\n    DiffSum nil 0\n  | diff_sum_pair:\n    forall t1 t2 z,\n    diff (t1, t2) z ->\n    DiffSum ((t1, t2) :: nil) z\n  | diff_sum_cons:\n    forall t1 t2 t3 w z s,\n    DiffSum ((t2, t3) :: w) s ->\n    diff (t1, t2) z ->\n    DiffSum ((t1, t2) :: (t2, t3) :: w) (z + s).\n\nLemma diff_sum_nil_z:\n  forall z,\n  DiffSum nil z ->\n  z = 0.\nProof.\n  intros.\n  inversion H.\n  reflexivity.\nQed.\n\nDefinition as_z (o:option Z) :=\n  match o with\n  | Some z => z\n  | None => 0\n  end.\n\nDefinition diff_sum_accum (a:Z) (e:edge) : Z :=\n  (as_z (get_diff e)) + a.\n\nLemma diff_sum_accum_0:\n  forall e,\n  diff_sum_accum 0 e = as_z (get_diff e).\nProof.\n  intros.\n  unfold diff_sum_accum.\n  intuition.\nQed.\n\nDefinition diff_sum (l:list edge) : Z :=\n  fold_left diff_sum_accum l 0.\n\nLemma diff_sum_0: diff_sum nil = 0.\nProof.\n  unfold diff_sum.\n  auto.\nQed.\n\nLet fold_left_diff_sum_accum:\n  forall w z,\n  fold_left diff_sum_accum w z = z + fold_left diff_sum_accum w 0.\nProof.\n  intros w.\n  induction w.\n  - intros.\n    intuition.\n  - intros.\n    simpl.\n    remember (diff_sum_accum z a) as s.\n    rewrite diff_sum_accum_0 in *.\n    remember ((as_z (get_diff a))) as s'.\n    assert (Hx := IHw s).\n    assert (Hy := IHw s').\n    rewrite Hx.\n    rewrite Hy.\n    remember (fold_left diff_sum_accum w 0) as sum.\n    unfold diff_sum_accum in Heqs.\n    intuition.\nQed.\n\nLemma diff_sum_unfold:\n  forall e w,\n  diff_sum (e :: w) = (as_z (get_diff e)) + (diff_sum w).\nProof.\n  intros.\n  unfold diff_sum.\n  simpl.\n  remember (diff_sum_accum 0 e).\n  unfold diff_sum_accum in Heqz.\n  remember (get_diff e) as o.\n  assert (as_z o = z). {\n    intuition.\n  }\n  rewrite H in *.\n  auto.\nQed.\n\nTheorem diff_sum_spec:\n  forall l z,\n  DiffSum l z ->\n  z = diff_sum l.\nProof.\n  intros l.\n  induction l.\n  + intros; inversion H.\n    auto.\n  + intros.\n    inversion H.\n    - subst.\n      unfold diff_sum.\n      simpl.\n      rewrite <- get_diff_spec in H3.\n      remember (get_diff (t1, t2)).\n      destruct o.\n      * inversion H3; subst.\n        rewrite diff_sum_accum_0.\n        rewrite <- Heqo.\n        auto.\n      * inversion H3.\n    - subst.\n      simpl.\n      apply IHl in H2; clear IHl H.\n      rewrite <- get_diff_spec in H4.\n      rewrite diff_sum_unfold.\n      rewrite <- H2.\n      rewrite H4.\n      auto.\nQed.\n\nDefinition NegDiff (e:edge) := exists z, diff e z /\\ z <= 0.\n\nLemma diff_sum_le_0:\n  forall w z,\n  Forall NegDiff w ->\n  DiffSum w z ->\n  z <= 0.\nProof.\n  intros w.\n  induction w.\n  - intros.\n    apply diff_sum_nil_z in H0.\n    intuition.\n  - intros.\n    inversion H0.\n    + subst.\n      intuition.\n      assert (Hin : List.In (t1, t2) ((t1, t2) :: nil)). {\n        apply in_eq.\n      }\n      rewrite Forall_forall in H.\n      destruct (H _ Hin) as (z', (?, ?)).\n      assert (z' = z). { eauto using diff_fun. }\n      intuition.\n   + subst. clear H0.\n     assert (s <= 0). {\n       inversion H; subst.\n       auto using IHw.\n     }\n     assert (z0 <= 0). {\n       rewrite Forall_forall in H.\n       assert (Hin : List.In (t1, t2) ((t1, t2) :: (t2, t3) :: w0)). {\n         apply in_eq.\n       }\n       destruct (H _ Hin) as (z, (?,?)).\n       assert (z0 = z). { eauto using diff_fun. }\n       intuition.\n    }\n    intuition.\nQed.\n\nDefinition HasDiff e := exists z, diff e z.\n\nRequire Import Aniceto.Graphs.Graph.\n\nLemma has_diff_to_diff_sum:\n  forall w x y,\n  Walk2 HasDiff x y w ->\n  exists z : Z, DiffSum w z.\nProof.\n  intros w.\n  induction w.\n  - intros. apply walk2_nil_inv in H.\n    intuition.\n  - intros.\n    destruct w.\n    + apply walk2_inv_pair in H.\n      destruct H as (?, Hd).\n      subst.\n      unfold HasDiff in *.\n      destruct Hd as (z, Hd).\n      exists z.\n      apply diff_sum_pair.\n      auto.\n    + apply walk2_inv in H.\n      destruct H as (v1, (?, (?, ?))).\n      destruct p as (v1', v2).\n      assert (v1' = v1). {\n        apply walk2_inv_cons in H1.\n        destruct H1 as (?, (Heq, ?)).\n        inversion Heq.\n        reflexivity.\n      }\n      subst.\n      apply IHw in H1.\n      subst.\n      destruct H1 as (s, Hs).\n      unfold HasDiff in *.\n      destruct H0 as (z, Hd).\n      exists (z + s).\n      auto using diff_sum_cons.\nQed.\n\nLemma neg_diff_to_has_diff:\n  forall e,\n  NegDiff e ->\n  HasDiff e.\nProof.\n  intros.\n  unfold NegDiff in *.\n  unfold HasDiff in *.\n  destruct H as (z, (H,_)).\n  exists z; auto.\nQed.\n\nLemma walk2_neg_diff_to_has_diff:\n  forall t1 t2 w,\n  Walk2 NegDiff t1 t2 w ->\n  Walk2 HasDiff t1 t2 w.\nProof.\n  intros.\n  eauto using walk2_impl, neg_diff_to_has_diff.\nQed.\n\nInductive TransDiff: A -> A -> Z -> Prop :=\n  trans_diff_def:\n    forall t1 t2 w z,\n    DiffSum w z ->\n    Walk2 HasDiff t1 t2 w ->\n    TransDiff t1 t2 z.\n\nLemma diff_to_trans_diff:\n  forall t1 t2 z,\n  diff (t1, t2) z ->\n  TransDiff t1 t2 z.\nProof.\n  intros.\n  assert (Hw : Walk2 HasDiff t1 t2 ((t1,t2) :: nil)). {\n    apply walk2_nil; repeat auto.\n    unfold HasDiff; exists z; auto.\n  }\n  assert (Hd : DiffSum ((t1, t2)::nil) z). { auto using diff_sum_pair. }\n  eauto using trans_diff_def.\nQed.\n\nDefinition TransDiffFun :=\n  forall t1 t2 z z',\n  TransDiff t1 t2 z ->\n  TransDiff t1 t2 z' ->\n  z' = z.\n\nCorollary trans_diff_fun_1 (Hdet : TransDiffFun):\n  forall t1 t2 z z',\n  TransDiff t1 t2 z ->\n  diff (t1, t2) z' ->\n  z' = z.\nProof.\n  intros.\n  apply diff_to_trans_diff in H0.\n  eauto using Hdet.\nQed.\n\nCorollary trans_diff_fun_2 (Hdet : TransDiffFun):\n  forall t1 t2 z z',\n  diff (t1, t2) z ->\n  diff (t1, t2) z' ->\n  z' = z.\nProof.\n  intros.\n  apply diff_to_trans_diff in H.\n  eauto using trans_diff_fun_1.\nQed.\n\nEnd DIFF_SUM.\n(*\nArguments DiffSum.\nArguments HasDiff.\nArguments NegDiff.\n*)\nLemma diff_sum_impl_weak:\n  forall {A:Type} (D D': (A*A) -> Z -> Prop) ,\n  forall l,\n  (forall e z, List.In e l -> D e z -> D' e z) ->\n  forall z,\n  DiffSum D l z ->\n  DiffSum D' l z.\nProof.\n  induction l; intros.\n  - inversion H0.\n    apply diff_sum_nil.\n  - inversion H0.\n    + subst.\n      eauto using diff_sum_pair, in_eq.\n    + subst.\n      auto using diff_sum_cons, in_eq, in_cons.\nQed.\n\nLemma diff_sum_impl:\n  forall {A:Type} (D D': (A*A) -> Z -> Prop) ,\n  (forall e z, D e z -> D' e z) ->\n  forall l z,\n  DiffSum D l z ->\n  DiffSum D' l z.\nProof.\n  eauto using diff_sum_impl_weak.\nQed.\n", "meta": {"author": "cogumbreiro", "repo": "habanero-coq", "sha": "2e7b1be0e25e53b4c6aba20a45700d6c743d7ce2", "save_path": "github-repos/coq/cogumbreiro-habanero-coq", "path": "github-repos/coq/cogumbreiro-habanero-coq/habanero-coq-2e7b1be0e25e53b4c6aba20a45700d6c743d7ce2/src/Phasers/TransDiff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.7048108709816754}}
{"text": "Require Export Basic.\nRequire Export lemma.\n\n\n(* 函数f在闭区间[a,b]上一致连续 *)\nDefinition uniform_continuous f (a b:R) :=  \n  exists d, pos_inc d (0,b-a] /\\\n  bounded_rec_f d (0,b-a] /\\\n  (forall x h:R, x ∈ [a,b] /\\ (x+h) ∈ [a,b] /\\ h<>0 ->\n  (Rabs (f(x+h) - f(x))) <= d(Rabs h)).\n\n(* 函数f在闭区间[a,b]上一致可导 *)\nDefinition uniform_differentiable F (a b:R) := \n  exists d, pos_inc d (0,b-a] /\\\n  bounded_rec_f d (0,b-a] /\\\n  exists f M, 0<M /\\ forall x h:R, x ∈ [a,b] /\\ (x+h) ∈ [a,b] /\\ h<>0 ->\n  Rabs (F(x+h) - F(x) - f(x)*h) <= M*(Rabs h)*d(Rabs h).\n\n(* 函数f在闭区间[a,b]上强可导 *)\nDefinition str_differentiable F (a b:R) :=\n  exists f M, 0<M /\\ forall x h:R, x∈[a,b] /\\ (x+h)∈[a,b] ->\n  Rabs (F(x+h)-F(x)-f(x)*h) <= M*(h^2).\n\n(* 函数F在闭区间[a,b]上的导数为函数f *)\nDefinition derivative F f a b := \n  exists d, pos_inc d (0,b-a] /\\\n  bounded_rec_f d (0,b-a] /\\\n  exists M:R, 0<M /\\ forall x h:R, x ∈ [a,b] /\\ (x+h) ∈ [a,b] /\\ h<>0 ->\n  Rabs (F(x+h) - F(x) - f(x)*h) <= M*(Rabs h)*d(Rabs h).\n\n(* 函数F在闭区间[a,b]上的强可导导数为函数f *)\nDefinition str_derivative F f (a b:R) := \n  exists M:R, 0<M /\\ forall x h:R, x ∈ [a,b] /\\ (x+h) ∈ [a,b] ->\n  Rabs (F(x+h) - F(x) - f(x)*h) <= M*(h^2).\n\nTheorem strder_deduce_der : forall F f a b,\n  a<b -> str_derivative F f a b -> derivative F f a b.\nProof.\n  intros.\n  unfold str_derivative in H0.\n  unfold derivative.\n  exists (fun x => x).\n  split.\n  - unfold pos_inc.\n    split; intros.\n    unfold In in H1; unfold oc in H1; tauto.\n    apply Rlt_le; auto.\n  - split. \n    + unfold bounded_rec_f; intros.\n      assert(exists z : R, z ∈ (0, b - a] /\\ z < 1/M).\n       { assert(0<b-a).\n          { apply Rlt_Rminus; auto. }\n         generalize (total_order_T (1/M) (b-a)); intro.\n         destruct H3. destruct s.\n         - generalize(exist_Rgt_lt 0 (1/M)); intro.\n           destruct H3.\n           unfold Rdiv; rewrite Rmult_1_l; apply Rinv_0_lt_compat; auto.\n           exists x. unfold In; unfold oc.\n           destruct H3. repeat split; auto.\n           apply Rlt_le; apply Rlt_trans with (r2:=1/M); auto. \n         - apply Rinv_0_lt_compat in H1.\n           apply exist_Rgt_lt in H1. destruct H1, H1.\n           exists x. unfold In; unfold oc.\n           repeat split; auto. rewrite <- e; apply Rlt_le.\n           unfold Rdiv; rewrite Rmult_1_l; auto.\n           unfold Rdiv; rewrite Rmult_1_l; auto.\n         - generalize H2; auto.\n           apply exist_Rgt_lt in H2. destruct H2, H2.\n           exists x. unfold In; unfold oc.\n           repeat split; auto. apply Rlt_le; auto.\n           apply Rlt_trans with (r2:=b-a); auto. }\n        destruct H2, H2.\n        exists x. split; auto.\n        unfold In in H2; unfold oc in H2.\n        destruct H2, H4.\n        rewrite Rabs_right. unfold Rdiv; rewrite Rmult_1_l.\n        unfold Rdiv in H3; rewrite Rmult_1_l in H3.\n        apply Rinv_lt_contravar in H3.\n        rewrite Rinv_involutive in H3; auto.\n        apply Rgt_not_eq; auto.\n        apply Rmult_lt_0_compat; auto.\n        apply Rinv_0_lt_compat; auto.\n        unfold Rdiv; rewrite Rmult_1_l; apply Rgt_ge.\n        apply Rlt_gt; apply Rinv_0_lt_compat; auto.\n    + destruct H0, H0. exists x. split; auto.\n      intros.\n      rewrite Rmult_assoc; rewrite <- Rabs_mult.\n      rewrite (Rabs_pos_eq (h*h)).\n      simpl in H2.\n      rewrite <- (Rmult_1_r (h * h)); rewrite Rmult_assoc.\n      apply H1; tauto.\n      apply Rlt_le; apply Rsqr_pos_lt; tauto.\nQed.\n\n(* (*强可导唯一*)\n\nTheorem unique_dri : forall F f g a b,\n  str_derivative F f a b -> str_derivative F g a b ->\n  (forall x, x ∈ [a,b] -> f x = g x).\nProof.\n  unfold str_derivative. intros.\n  destruct H, H0. rename x0 into M. rename x1 into M1.\n  destruct H, H0.\n  generalize(classic (f x=g x)); intro.\n  destruct H4; auto.\n  SearchAbout(_<>_ -> _ _ <>_ _).\n  red. *)\n\n(* 设 F(x),G(x)一致(强)可导，并且导数分别是f(x),g(x) *)\n\n(* 对任意常数c，cF(x)一致(强)可导，且其导数分别是cf(x) *)\nTheorem Theorem2_1_1 : forall (a b c:R) F f,\n  derivative F f a b -> \n  derivative (mult_real_f c F) (mult_real_f c f) a b.\nProof.\n  intros a b c F f .\n  unfold derivative; intro.\n  destruct H, H, H0, H1, H1.\n  exists x; split; auto. split; auto.\n  generalize (total_eq_or_neq c 0); intro. destruct H3.\n  - exists x0. split; auto; intros.\n    apply H2 in H4. unfold mult_real_f; rewrite H3.\n    repeat rewrite Rmult_0_l. unfold Rminus; rewrite Ropp_0;\n    repeat rewrite Rplus_0_l; rewrite Rabs_R0.\n    apply Rle_trans with (r2:=Rabs(F(x1+h)-F x1-f x1*h)); auto. \n    apply Rabs_pos.\n  - exists (Rabs c * x0). split.\n    apply Rmult_lt_0_compat; auto.\n    apply Rabs_pos_lt; auto. intros. apply H2 in H4. \n    unfold mult_real_f. rewrite Rmult_assoc.\n    rewrite <- Rmult_minus_distr_1_3 with\n    (r:=c)(r1:=(F(x1+h)))(r2:=F x1)(r3:=f x1*h).\n    rewrite Rabs_mult; repeat rewrite Rmult_assoc; apply Rmult_le_compat_l.\n    apply Rabs_pos. repeat rewrite <- Rmult_assoc; apply H4. \nQed.\n\n(* 定义一个选择器，其性质为：\n      比较任意两个实数a，b的大小，如果a>b, if_a_gt_b a b 值为true\n      如果a<=b, if_a_gt_b a b值为false；且反向推也成立。该性质由公理comp_a_b_Pro定义 *)\n\nParameter if_a_gt_b : R -> R -> bool.\n\nAxiom comp_a_b_Pro : forall a b, (if_a_gt_b a b = true <-> a > b) /\\\n  (if_a_gt_b a b = false <-> a <= b).\n\n(* 定义一个函数，该函数在每一点的值，都为函数f1、f2在该点函数值中较大那一个 *)\nDefinition max_f1_f2 (f1 f2 : R -> R) := \n  fun x:R => if (if_a_gt_b (f1 x)(f2 x)) then (f1 x) else (f2 x).\n\n\nLemma existence_f : forall a b f1 f2, \n  pos_inc f1 (0,b-a] /\\\n  (forall r1:R, r1>0 -> exists z1:R, z1 ∈ (0,b-a] /\\ r1 < Rabs(1/(f1 z1))) /\\\n  pos_inc f2 (0,b-a] /\\\n  (forall r2:R, r2>0 -> exists z2:R, z2 ∈ (0,b-a] /\\ r2 < Rabs(1/(f2 z2))) ->\n  exists f3, (pos_inc f3 (0,b-a] /\\\n  (forall r3:R, r3>0 -> exists z3:R, z3 ∈ (0,b-a] /\\ r3 < Rabs(1/(f3 z3))) /\\\n  (forall a:R, f1 a <= f3 a /\\ f2 a <= f3 a)).\nProof.\n  intros.\n  exists (max_f1_f2 f1 f2).\n  destruct H, H0, H1. split.\n  - unfold pos_inc. unfold pos_inc in H, H1.\n    split; intros.\n    + destruct H, H1. generalize H3; intros. apply H in H3; apply H1 in H6.\n      unfold max_f1_f2; destruct if_a_gt_b; auto.\n    + destruct H, H1; generalize H5; intros.\n      apply H6 in H5; auto. apply H7 in H8; auto.\n      unfold max_f1_f2.\n      assert(if_a_gt_b(f1 z1)(f2 z1)=true \\/ if_a_gt_b(f1 z1)(f2 z1)=false).\n      { destruct if_a_gt_b; auto. }\n      destruct H9.\n      * rewrite H9; apply comp_a_b_Pro in H9.\n        assert(if_a_gt_b(f1 z2)(f2 z2)=true\\/if_a_gt_b(f1 z2)(f2 z2)=false).\n         { destruct if_a_gt_b; auto. }\n        destruct H10. rewrite H10; auto. rewrite H10; apply comp_a_b_Pro in H10.\n        eapply Rle_trans. apply H5. apply H10.\n      * rewrite H9; apply comp_a_b_Pro in H9.\n        assert(if_a_gt_b(f1 z2)(f2 z2)=true\\/if_a_gt_b(f1 z2)(f2 z2)=false).\n         { destruct if_a_gt_b; auto. }\n        destruct H10. rewrite H10; apply comp_a_b_Pro in H10.\n        eapply Rle_trans. apply H8. apply Rlt_le; auto.\n        rewrite H10; auto.\n  - split; intros.\n    generalize H3 as r; intro.\n    generalize H3 as H4; intro.\n    apply H0 in H3; apply H2 in H4. clear H0; clear H2.\n    unfold max_f1_f2.\n    destruct H3, H0. destruct H4, H3.\n    assert(if_a_gt_b(f1 x)(f2 x)=true\\/if_a_gt_b(f1 x)(f2 x)=false).\n      { destruct if_a_gt_b; auto. }\n    assert(if_a_gt_b(f1 x0)(f2 x0)=true\\/if_a_gt_b(f1 x0)(f2 x0)=false).\n      { destruct if_a_gt_b at 1 2; auto. }\n    generalize(classic (exists z3:R, z3 ∈ (0,b-a]/\\\n    r3 < Rabs (1/(if if_a_gt_b (f1 z3) (f2 z3) then f1 z3 else f2 z3)))); intro.\n    destruct H7; auto.\n    generalize H7; intro.\n    apply not_exist with(x:=x) in H7; auto. apply Rnot_lt_le in H7.\n    apply not_exist with(x:=x0) in H8; auto. apply Rnot_lt_le in H8.\n    destruct H5.\n    + rewrite H5 in H7; apply Rlt_not_le in H2; contradiction.\n    + rewrite H5 in H7.\n      destruct H6.\n      * rewrite H6 in H8.\n        unfold pos_inc in H, H1.\n        destruct H, H1.\n        generalize(H x H0); intro; apply Rinv_0_lt_compat in H11.\n        generalize(H x0 H3); intro; apply Rinv_0_lt_compat in H12.\n        generalize(H1 x H0); intro; apply Rinv_0_lt_compat in H13.\n        generalize(H1 x0 H3); intro; apply Rinv_0_lt_compat in H14.\n        unfold Rdiv in H2; rewrite Rmult_1_l in H2; rewrite Rabs_right in H2;\n        try apply Rgt_ge; try apply Rlt_inv in H2; auto.\n        unfold Rdiv in H4; rewrite Rmult_1_l in H4; rewrite Rabs_right in H4;\n        try apply Rgt_ge; try apply Rlt_inv in H4; auto.\n        unfold Rdiv in H7; rewrite Rmult_1_l in H7; rewrite Rabs_right in H7;\n        try apply Rgt_ge; try apply Rinv_le in H7; auto.\n        unfold Rdiv in H8; rewrite Rmult_1_l in H8; rewrite Rabs_right in H8;\n        try apply Rgt_ge; try apply Rinv_le in H8; auto.\n        clear H11 H12 H13 H14.\n        generalize (Rtotal_order x x0); intro.\n        destruct H11.\n        { generalize H11; intro.\n          apply H9 in H11; apply H10 in H12; auto.\n          apply Rge_le in H7.\n          generalize(Rlt_le_trans (f2 x0)(/r3)(f2 x) H4 H7); intro.\n          apply Rlt_not_le in H13; contradiction. }\n        destruct H11.\n        { rewrite H11 in H5; rewrite H5 in H6.\n          generalize Bool.diff_false_true; intro; contradiction. }\n        apply Rgt_lt in H11.\n        generalize H11; intro.\n        apply H9 in H11; apply H10 in H12; auto.\n        apply Rge_le in H8.\n        generalize(Rlt_le_trans (f1 x)(/r3)(f1 x0) H2 H8); intro.\n        apply Rlt_not_le in H13; contradiction.\n      * rewrite H6 in H8.\n        exists x0; split; auto. rewrite H6; auto.\n    + unfold max_f1_f2.\n      assert(if_a_gt_b(f1 a0)(f2 a0)=true\\/if_a_gt_b(f1 a0)(f2 a0)=false).\n      { destruct if_a_gt_b; auto. }\n      destruct H3.\n      * rewrite H3; apply comp_a_b_Pro in H3.\n        split.\n        apply Rge_refl.\n        apply Rlt_le; auto.\n      * rewrite H3; apply comp_a_b_Pro in H3.\n        split; auto.\n        apply Rge_refl.\nQed.\n\n(* F(x)+G(x)一致(强)可导,且其导数分别是f(x)和g(x) *)\nTheorem Theorem2_1_2 : forall F G f g (a b:R),\n  derivative F f a b -> derivative G g a b ->\n  derivative (plus_Fu F G) (plus_Fu f g) a b.\nProof.\n  intros F G f g a b.\n  unfold derivative; unfold bounded_rec_f; intros.\n  destruct H, H, H1, H2, H2. rename x into d1; rename x0 into M1.\n  destruct H0, H0, H4, H5, H5. rename x into d2; rename x0 into M2.\n  assert (exists d3, pos_inc d3 (0,b-a] /\\ (forall r3:R, r3>0 ->\n          exists z3:R, z3 ∈ (0,b-a] /\\ r3 < Rabs(1/(d3 z3))) /\\\n          forall a:R, d1 a <= d3 a /\\ d2 a <= d3 a).\n   { apply existence_f with (a:=a)(b:=b) (f1:=d1) (f2:=d2). \n     split; auto. }\n  destruct H7, H7, H8. rename x into d3.\n  exists d3; split; auto. split; auto.\n  exists (M1 + M2); intros.\n  split.\n  apply Rplus_lt_0_compat; auto. intros.\n    generalize H10; intro.\n    apply H3 in H10; apply H6 in H11.\n    unfold plus_Fu.\n    rewrite Rmult_plus_distr_r with (r1:=(f x))(r2:=(g x))(r3:=h).\n    rewrite plus_ab_minus_cd with (a:=F(x+h))(b:=G(x+h))(c:=F x)\n                                  (d:=G x)(e:=f x*h)(f:=g x*h).\n    assert (Rabs(F(x+h) - F x - f x*h)+Rabs(G(x+h) - G x - g x*h)\n            <= M1*(Rabs h)*d1(Rabs h) + M2*(Rabs h)*d2(Rabs h)).\n     { apply Rplus_le_compat; auto. }\n    apply Rle_abcd with (a:=Rabs(F(x+h)-F x-f x*h+(G(x+h)-G x-g x*h)))\n                        (b:=Rabs(F(x+h)-F x-f x*h)+Rabs(G(x+h)-G x-g x*h))\n                        (c:=M1*(Rabs h)*d1(Rabs h)+M2*(Rabs h)*d2(Rabs h))\n                        (d:=(M1+M2)*(Rabs h)*d3(Rabs h)).\n    + apply Rabs_triang.\n    + rewrite Rmult_plus_distr_r.\n      rewrite Rmult_plus_distr_r.\n      apply Rplus_le_compat; apply Rmult_le_compat_l.\n      apply Rmult_le_pos. apply Rlt_le; auto. apply Rabs_pos. apply H9.\n      apply Rmult_le_pos. apply Rlt_le; auto. apply Rabs_pos. apply H9.\n    + auto.\nQed.\n\nLemma th2' : forall (a b c:R) f, c > 0 -> pos_inc f (0, b-a] ->\n  pos_inc (Com_F_c f c) (0, (b/c-a/c)].\nProof.\n  intros a b c f C.\n  unfold pos_inc; unfold Com_F_c; intro.\n  assert ( forall z, z ∈ (0,(b / c - a / c)] ->(c * z) ∈ (0,b-a] ).\n   { unfold In; unfold oc; intros.\n     rewrite <- Rinv_minus_distr_r in H0.\n     unfold Rdiv in H0; destruct H0; split.\n     apply Rmult_0_lt_reg in H0; auto.\n     apply Rinv_0_lt_compat; auto.\n     apply Rlt_x_le with (r:=c); auto. rewrite Rmult_eq_r.\n     unfold Rdiv; tauto.\n     apply Rgt_not_eq; auto.\n     apply Rgt_not_eq; auto. }\n  destruct H; split; intros.\n  - apply H0 in H2; apply H in H2; auto.\n  - apply H0 in H2; apply H0 in H3; apply H1; auto.\n    apply Rmult_lt_compat_l; auto.\nQed.\n\n\n(*F(cx+d)一致（强）可导，且其导数为cf(cx+d)*)\nTheorem Theorem2_1_3 : forall F f (a b c d:R),\n  c > 0 -> derivative F f a b ->\n  derivative (Com_F F c d) (mult_real_f c (Com_F f c d))((a-d)/c)((b-d)/c).\nProof.\nintros F f a b c d C.\n  unfold derivative; intro.\n  destruct H, H, H0, H1, H1. rename x into p; rename x0 into M.\n  exists (Com_F_c p c); split.\n  apply th2'; auto.\n  rewrite Rminus_distr; rewrite R_distr; rewrite Rminus_plus_r; auto.\n  split.\n  unfold bounded_rec_f; unfold bounded_rec_f in H0; intros.\n  apply H0 in H3; destruct H3, H3, H3.\n  exists (x/c).\n  split.\n  - unfold In; unfold oc. split.\n    + rewrite <- Rdiv_minus_distr; rewrite Rminus_distr.\n      rewrite R_distr; rewrite Rminus_plus_r.\n      unfold Rdiv; apply Rmult_lt_0_compat; auto.\n      apply Rinv_0_lt_compat; auto.\n    + rewrite <- Rdiv_minus_distr; apply Rlt_x_le_reg; auto;\n      rewrite Rminus_distr.\n      rewrite R_distr; rewrite Rminus_plus_r; auto.\n  - unfold Com_F_c. rewrite Rmult_par_inv_eq. rewrite Rmult_eq_r; auto.\n    apply Rgt_not_eq; auto.  apply Rgt_not_eq; auto.\n  - unfold Com_F; unfold Com_F_c.\n    exists (c*M); intros.\n    split. apply Rmult_lt_0_compat; auto.\n    intros.\n    assert ((c*x+d) ∈ [a,b] /\\ ((c*x+d)+(c*h)) ∈ [a,b]).\n     { unfold In; unfold cc; unfold In in H3; unfold cc in H3.\n       destruct H3, H3, H4.\n       assert(a<b). \n       { unfold Rdiv in H3; \n         apply Rmult_lt_reg_r with (r:=/c) in H3; auto.\n         unfold Rminus in H3. eapply Rplus_lt_reg_r; apply H3.\n         apply Rinv_0_lt_compat; auto. }\n       split; split; auto.\n       - apply Rplus_le_3_r.\n         apply Rinv_le_r with(r:=c); auto.\n         rewrite Rmult_eq_r with (r:=c)(r1:=x); auto.\n         apply Rgt_not_eq; auto.\n       - rewrite Rplus_comm  with (r1:=c*x)(r2:=d).\n         rewrite Rplus_assoc; rewrite Rplus_comm. apply Rplus_le_3_r .\n         rewrite <- Rmult_plus_distr_l.\n         apply Rinv_le_r with (r:=c); auto.\n         rewrite Rmult_eq_r. tauto.\n         apply Rgt_not_eq; auto. }\n    assert((c*x+d) ∈ [a,b] /\\ (c*x+d+c*h) ∈ [a,b] /\\ c*h<>0).\n     { destruct H4. split; auto. split; auto. \n       apply Rmult_integral_contrapositive_currified.\n       apply Rgt_not_eq; auto. tauto. }\n    clear H4; apply H2 in H5.\n    unfold mult_real_f; unfold Com_F.\n    rewrite Rmult_plus_distr_l.\n    rewrite Rplus_assoc with(r1:=(c*x))(r2:=d)(r3:=(c*h)) in H5.\n    rewrite Rplus_comm  with (r1:=d)(r2:=c*h) in H5. \n    rewrite <- Rplus_assoc in H5.\n    rewrite <- Rmult_assoc with(r1:=(f(c*x+d)))(r2:=c)(r3:=h) in H5.\n    rewrite Rmult_comm with (r1:=c)(r2:=(f (c*x + d))).\n    rewrite Rmult_comm with (r1:=c)(r2:=M). \n    rewrite Rabs_mult in H5. rewrite Rabs_right with (r:=c)in H5.\n    rewrite Rmult_assoc with(r1:=M)(r2:=c)(r3:=Rabs h); auto.\n    unfold Rge; auto.\nQed.\n\n(*可加性*)\nDefinition additivity (S:R->R->R)(a b:R):=\n  forall(w1 w2 w3:R), w1 ∈ [a,b] /\\ w2 ∈ [a,b] /\\w3 ∈ [a,b] -> \n  S w1 w2 + S w2 w3 = S w1 w3. \n\n(*非负性*)\nDefinition nonnegativity (S:R->R->R)(f:R->R)(a b:R):=\n  forall(w1 w2:R), w1 ∈ [a,b] /\\ w2 ∈ [a,b] /\\ w2 - w1 > 0 ->\n  (forall m:R, (forall x:R, x ∈ [w1,w2] -> m <= f x) -> m*(w2-w1) <= S w1 w2) /\\\n  (forall M:R, (forall x:R, x ∈ [w1,w2] -> M >= f x) -> S w1 w2 <= M*(w2-w1)).\n\n(*积分系统*)\nDefinition integ_sys (S:R->R->R)(f:R->R)(a b:R) :=\n  additivity S a b /\\ nonnegativity S f a b.\n\n(*可积*)\nDefinition integrable (f:R->R)(a b:R) :=\n  exists S, integ_sys S f a b /\\\n  forall S':R->R->R, integ_sys S' f a b -> S = S'.\n\n\n(* 积分严格不等式 *)\nDefinition strict_inequal (S:R->R->R)(f:R->R)(a b:R) :=\n  integ_sys S f a b ->\n  forall w1 w2:R, w1 ∈ [a,b] /\\ w2 ∈ [a,b] /\\ w2 - w1 > 0 ->\n  (forall m:R, (forall x:R, x ∈ [w1,w2] -> m < f x) -> m*(w2 - w1) < S w1 w2) /\\\n  (forall M:R, (forall x:R, x ∈ [w1,w2] -> M > f x) -> S w1 w2 < M*(w2 - w1)).\n\n\nLemma equ_s : forall (S:R->R->R) (f G:R->R) (a b:R),\n  integ_sys S f a b ->\n  forall y, y ∈ [a,b] -> (forall x :R, x ∈ [a,b] -> G x = S y x) ->\n  forall u v:R, u ∈ [a,b] /\\ v ∈ [a,b] ->\n  S u v = S y v - S y u /\\ S y v - S y u  = G v - G u.\nProof.\n  intros.\n  unfold integ_sys in H; intros.\n  destruct H; unfold additivity in H; split.\n  - apply Rplus_eq_reg_r with (r:=(S y u)).\n    rewrite Rminus_plus_r with (r1:=(S y v)) (r:=(S y u)).\n    rewrite Rplus_comm; apply H.\n    split; auto.\n  - destruct H2; repeat rewrite H1; auto.\nQed.\n\n(* 估值定理 *)\nTheorem Valuation_Theorem : forall (S:R->R->R) (f G:R->R)(a b:R),\n  integ_sys S f a b ->\n  forall y, y ∈ [a,b] -> (forall x:R, x ∈ [a,b] -> G x = S y x) ->\n  strict_inequal S f a b ->\n  forall u v, u ∈ [a,b] /\\ v ∈ [a,b] /\\ v - u > 0 ->\n  exists x1 x2, x1 ∈ [u,v] /\\ x2 ∈ [u,v] /\\\n  (f x1)*(v-u) <= G(v) - G(u) <= (f x2)*(v-u).\nProof.\n  intros.\n  unfold strict_inequal in H2.\n  generalize H as l; intro.\n  apply H2 with (w1:=u)(w2:=v) in H; auto. clear H2.\n  destruct H, H3, H4.\n  assert (exists x1, x1 ∈ [u,v] /\\ (f x1)*(v-u) <= G(v) - G(u)).\n   { generalize (classic(exists x1, x1 ∈ [u,v] /\\ (f x1)*(v-u) <= G(v) - G(u))).\n     intros. destruct H6; auto.\n     assert (G v - G u < S u v). \n      { generalize (H ((G v - G u)/(v-u))); intros; clear H.\n        unfold Rdiv in H7.\n        rewrite Rinv_mult_rgt0 with (r1:=(G v - G u))(r:=(v - u))in H7; auto.\n        apply H7; intros.\n        apply not_exist with (x:=x) in H6. apply Rnot_le_gt in H6.\n        apply Rgt_mult in H6; auto. apply H. }\n     rewrite H1 in H7; auto. rewrite H1 in H7; auto.\n     assert ( S u v = S y v - S y u /\\ S y v - S y u = G v - G u).\n      { apply equ_s with (f:=f)(a:=a)(b:=b); auto. }\n     destruct H8.\n     rewrite H8 in H7; apply Rlt_irrefl in H7; contradiction. }\n  assert (exists x2, x2 ∈ [u,v] /\\ (f x2)*(v-u) >= G(v) - G(u)).\n   { generalize (classic(exists x2, x2 ∈ [u,v] /\\ (f x2)*(v-u) >= G(v) - G(u))).\n     intros. destruct H7; auto.\n     assert (G v - G u > S u v). \n      { generalize (H2 ((G v - G u)/(v-u))); intros; clear H2.\n        unfold Rdiv in H8.\n        rewrite Rinv_mult_rgt0 with (r1:=(G v - G u))(r:=(v - u))in H8; auto.\n        apply H8; intros.\n        apply not_exist with (x:=x) in H7. apply Rnot_ge_lt in H7.\n        apply Rlt_mult in H7; auto. apply H2. }\n     rewrite H1 in H8; auto. rewrite H1 in H8; auto.\n     assert ( S u v = S y v - S y u /\\ S y v - S y u = G v - G u).\n      { apply equ_s with (f:=f)(a:=a)(b:=b); auto. }\n     destruct H9.\n     rewrite H9 in H8; apply Rlt_irrefl in H8; contradiction. }\n  destruct H6, H6, H7, H7.\n  exists x, x0.\n  split; auto. split; auto. split; auto.\n  apply Rge_le; auto.\nQed.\n", "meta": {"author": "LittleGavin", "repo": "Calculus-without-limits", "sha": "8076e012d54882a6f0f499a9565703ffb130bb67", "save_path": "github-repos/coq/LittleGavin-Calculus-without-limits", "path": "github-repos/coq/LittleGavin-Calculus-without-limits/Calculus-without-limits-8076e012d54882a6f0f499a9565703ffb130bb67/chapter_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7048108709816753}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) : natural := mult lf1 lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj53_coqofml_kPjdHX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7048108664165007}}
{"text": "Coq < Section Socrates.\n\nCoq < Require Import Classical.\n\nCoq < Variables A B C : Prop.\nA is assumed\nB is assumed\nC is assumed\n\nCoq < Goal (A -> C) /\\ (B -> A) -> (B -> C).\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  C : Prop\n  ============================\n   (A -> C) /\\ (B -> A) -> B -> C\n\nUnnamed_thm < intros.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> C) /\\ (B -> A)\n  H0 : B\n  ============================\n   C\n\nUnnamed_thm < apply H.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> C) /\\ (B -> A)\n  H0 : B\n  ============================\n   A\n\nUnnamed_thm < elim H.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> C) /\\ (B -> A)\n  H0 : B\n  ============================\n   (A -> C) -> (B -> A) -> A\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> C) /\\ (B -> A)\n  H0 : B\n  H1 : A -> C\n  ============================\n   (B -> A) -> A\n\nUnnamed_thm < intro.\n1 subgoal\n  \n  A : Prop\n  B : Prop\n  C : Prop\n  H : (A -> C) /\\ (B -> A)\n  H0 : B\n  H1 : A -> C\n  H2 : B -> A\n  ============================\n   A\n\nUnnamed_thm < auto.\nNo more subgoals.\n\nUnnamed_thm < Qed.\nintros.\napply H.\nelim H.\nintro.\nintro.\nauto.\n\nUnnamed_thm is defined\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/logic/chapt01/practice09.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7047988555818089}}
{"text": "Require Import rt.util.tactics rt.util.induction.\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrnat seq fintype bigop.\n\nSection FixedPoint.\n  \n  Lemma iter_fix T (F : T -> T) x k n :\n    iter k F x = iter k.+1 F x ->\n    k <= n ->\n    iter n F x = iter n.+1 F x.\n  Proof.\n    move => e. elim: n. rewrite leqn0. by move/eqP<-.\n    move => n IH. rewrite leq_eqVlt; case/orP; first by move/eqP<-.\n    move/IH => /= IHe. by rewrite -!IHe.\n  Qed.\n\n  Lemma fun_mon_iter_mon :\n    forall (f: nat -> nat) x0 x1 x2,\n      x1 <= x2 ->\n      f x0 >= x0 ->\n      (forall x1 x2, x1 <= x2 -> f x1 <= f x2) ->\n      iter x1 f x0 <= iter x2 f x0.\n  Proof.\n    intros f x0 x1 x2 LE MIN MON.\n    revert LE; revert x2; rewrite leq_as_delta; intros delta.\n    induction x1; try rewrite add0n.\n    {\n      induction delta; first by apply leqnn.\n      apply leq_trans with (n := iter delta f x0); first by done.\n      clear IHdelta.\n      induction delta; first by done.\n      {\n        rewrite 2!iterS; apply MON.\n        apply IHdelta.\n      }\n    }\n    {\n      rewrite iterS -addn1 -addnA [1 + delta]addnC addnA addn1 iterS.\n      by apply MON, IHx1.\n    }\n  Qed.\n\n  Lemma fun_mon_iter_mon_helper :\n    forall T (f: T -> T) (le: rel T) x0 x1,\n      reflexive le ->\n      transitive le ->\n      (forall x2, le x0 (iter x2 f x0)) ->\n      (forall x1 x2, le x0 x1 -> le x1 x2 -> le (f x1) (f x2)) ->\n      le (iter x1 f x0) (iter x1.+1 f x0).\n  Proof.\n    intros T f le x0 x1 REFL TRANS MIN MON.\n    generalize dependent x0.\n    induction x1; first by ins; apply (MIN 1).\n    by ins; apply MON; [by apply MIN | by apply IHx1].\n  Qed.\n\n  Lemma fun_mon_iter_mon_generic :\n    forall T (f: T -> T) (le: rel T) x0 x1 x2,\n      reflexive le ->\n      transitive le ->\n      x1 <= x2 ->\n      (forall x1 x2, le x0 x1 -> le x1 x2 -> le (f x1) (f x2)) ->\n      (forall x2 : nat, le x0 (iter x2 f x0)) ->\n      le (iter x1 f x0) (iter x2 f x0).\n  Proof.\n    intros T f le x0 x1 x2 REFL TRANS LE MON MIN.\n    revert LE; revert x2; rewrite leq_as_delta; intros delta.\n    induction delta; first by rewrite addn0; apply REFL.\n    apply (TRANS) with (y := iter (x1 + delta) f x0);\n      first by apply IHdelta.\n    by rewrite addnS; apply fun_mon_iter_mon_helper.\n  Qed.\n\nEnd FixedPoint.\n\n(* In this section, we define some properties of relations\n   that are important for fixed-point iterations. *)\nSection Relations.\n\n  Context {T: Type}.\n  Variable R: rel T.\n  Variable f: T -> T.\n  \n  Definition monotone (R: rel T) :=\n    forall x y, R x y -> R (f x) (f y).\n\nEnd Relations.\n\n(* In this section we define a fixed-point iteration function\n   that stops as soon as it finds the solution. If no solution\n   is found, the function returns None. *)\nSection Iteration.\n\n  Context {T : eqType}.\n  Variable f: T -> T.\n\n  Fixpoint iter_fixpoint max_steps (x: T) :=\n    if max_steps is step.+1 then\n      let x' := f x in\n        if x == x' then\n          Some x\n        else iter_fixpoint step x'\n    else None.\n\n  Section BasicLemmas.\n\n    (* We prove that iter_fixpoint either returns either None\n       or Some y, where y is a fixed point. *)\n    Lemma iter_fixpoint_cases :\n      forall max_steps x0,\n        iter_fixpoint max_steps x0 = None \\/\n        exists y,\n          iter_fixpoint max_steps x0 = Some y /\\\n          y = f y. \n    Proof.\n      induction max_steps.\n      {\n        by ins; simpl; destruct (x0 == f x0); left. \n      }\n      {\n        intros x0; simpl.\n        destruct (x0 == f x0) eqn:EQ1;\n          first by right; exists x0; split; last by apply/eqP.\n        by destruct (IHmax_steps (f x0)) as [NONE | FOUND].\n      }\n    Qed. \n\n    (* We also show that any inductive property P is propagated\n       through the fixed-point iteration. *)\n    Lemma iter_fixpoint_ind:\n      forall max_steps x0 x,\n        iter_fixpoint max_steps x0 = Some x ->\n        forall P,\n          P x0 ->\n          (forall x, P x -> P (f x)) ->\n          P x.\n    Proof.\n      induction max_steps; first by done.\n      intros x0 x SOME P P0 ALL.\n      move: SOME; simpl.\n      case EQ: (_ == _).\n      {\n        move: EQ => /eqP EQ.\n        case => SAME; subst.\n        by rewrite EQ; apply ALL.\n      }\n      {\n        intros SOME; clear EQ.\n        apply (IHmax_steps (f x0) x SOME P); first by apply ALL.\n        by apply ALL.\n      }\n    Qed.\n      \n  End BasicLemmas.\n\n  Section RelationLemmas.\n\n    Variable R: rel T.\n    Hypothesis H_reflexive: reflexive R.\n    Hypothesis H_transitive: transitive R.\n    Hypothesis H_monotone: monotone f R.\n\n    Lemma iter_fixpoint_ge_min:\n      forall max_steps x0 x1 x,\n        iter_fixpoint max_steps x1 = Some x ->\n        R x0 x1 ->\n        R x1 (f x1) ->\n        R x0 x.\n    Proof.\n      induction max_steps; first by done.\n      {\n        intros x0 x1 x SOME MIN BOT; simpl in SOME.\n        destruct (x1 == f x1) eqn:EQ1;\n          first by inversion SOME; subst.\n        apply IHmax_steps with (x0 := x0) in SOME; first by done.\n        - by apply (@H_transitive x1).\n        - by apply H_monotone.\n      }\n    Qed.\n\n    Lemma iter_fixpoint_ge_bottom:\n      forall max_steps x0 x,\n        iter_fixpoint max_steps x0 = Some x ->\n        R x0 (f x0) ->\n        R x0 x.\n    Proof.\n      intros max_steps x0 x SOME BOT.\n      by apply iter_fixpoint_ge_min with (max_steps := max_steps) (x1 := x0). \n    Qed.\n    \n  End RelationLemmas.\n  \nEnd Iteration.", "meta": {"author": "cd-public", "repo": "rt-proofs", "sha": "ebef0b65460fe009c51f638fe2b459f16a6d1dd5", "save_path": "github-repos/coq/cd-public-rt-proofs", "path": "github-repos/coq/cd-public-rt-proofs/rt-proofs-ebef0b65460fe009c51f638fe2b459f16a6d1dd5/util/fixedpoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7047850420558541}}
{"text": "(** * Fibonacci \n  Copyright INRIA (2014) Marelle Team (Jose Grimm).\n*)\n\n(* $Id: fibm.v,v 1.3 2018/07/13 05:59:59 grimm Exp $ *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat.\nFrom mathcomp Require Import seq path fintype div bigop binomial.\nFrom mathcomp Require Import prime finset ssralg ssrnum ssrint.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(** ** Additional lemmas *)\n\n(* Comparison *) \nLemma ltn_paddl m n: 0 < m -> n < m + n.\nProof. by rewrite - (ltn_add2r n) add0n. Qed.\n\nLemma ltn_paddr m n: 0 < m -> n < n +m.\nProof. by move/(ltn_paddl n); rewrite addnC. Qed.\n\nLemma leq_BD n p : n - p <= n + p. \nProof. exact:(leq_trans (leq_subr p n) (leq_addr p n)). Qed.\n\nLemma leqn1 n: (n <=1) = (n==0) || (n ==1).\nProof. by rewrite leq_eqVlt orbC ltnS leqn0. Qed.\n\n(* Half *)\nLemma half_le1 m: m./2 <= m.\nProof. by rewrite -{2}(odd_double_half m) -addnn addnA leq_addl. Qed.\n\nLemma half_le2 m: (m.+1)./2 <= m.\nProof. by case: m => // m /=; rewrite ltnS half_le1. Qed.\n\nLemma half_le3 m: 1 < m ->  (m.+1)./2 < m.\nProof. by case: m => [|[|n _]] //;rewrite ltnS ltnS half_le2. Qed.\n\nLemma half_le3w m: 1 < m ->  m./2 < m.\nProof. move/half_le3 => h; exact: (leq_ltn_trans (half_leq (leqnSn m)) h). Qed.\n\nLemma half_le4 n: n <= n./2 -> n <= 1. \nProof. by apply: contraLR; rewrite -!ltnNge; apply: half_le3w. Qed.\n\nLemma double_half_le m : m./2.*2 <= m.\nProof. by rewrite -{2}(odd_double_half m) leq_addl. Qed.\n\n(* double *)\nLemma double_le1 n: n <= n.*2.\nProof. by rewrite -addnn leq_addl. Qed.\n\nLemma double_le2 n: n < n.*2.+1.\nProof. by rewrite ltnS double_le1. Qed.\n\nLemma double_le3 n: n.+1 < (n.+1).*2.\nProof. by rewrite doubleS !ltnS double_le1. Qed.\n\nLemma eqn_double m n: (m.*2 == n.*2) = (m == n).\nProof. by rewrite - !muln2 eqn_mul2r. Qed.\n\nLemma double_inj: injective (fun z  => z.*2).\nProof. apply:can_inj doubleK. Qed.\n\nLemma doubleS_inj: injective (fun z => z.*2.+1).\nProof. apply: inj_comp succn_inj  double_inj. Qed.\n\n\n(* Odd *)\n\nLemma odd_sqr n: odd (n^2) = odd n.\nProof. by rewrite oddX. Qed.\n\nLemma odd_dichot n: n = (n./2).*2.+1 \\/ n = (n./2).*2.\nProof. by rewrite -{1 3} (odd_double_half n);case: odd; [left | right]. Qed.\n\nLemma oddE n: odd n -> n = (n./2).*2.+1.\nProof. by rewrite -{2} (odd_double_half n) => ->. Qed.\n\nLemma evenE n: odd n = false -> n = (n./2).*2.\nProof. by rewrite -{2} (odd_double_half n) => ->. Qed.\n\nLemma cantor n : n < 2 ^n. \nProof. exact: (ltn_expl n (ltnSn 1)). Qed.\n\nLemma expn2S n: 2^n.+1 = (2^n).*2.\nProof. by rewrite expnS mul2n. Qed.\n\nLemma rem_two_prop1 m i: (m.*2) %% (2 ^(i.+1)) = (m %% 2^i).*2.\nProof.  \nrewrite {1}(divn_eq m (2^i)) doubleD doubleMr -expn2S modnMDl modn_small //. \nby rewrite expn2S ltn_double ltn_pmod // expn_gt0.\nQed.\n\nLemma rem_two_prop2 m i: (m.*2.+1) %% (2 ^(i.+1)) = (m %% 2^i).*2.+1.\nProof.  \nrewrite {1}(divn_eq m (2^i)) doubleD doubleMr -expn2S - addnS modnMDl.\nby rewrite modn_small // expn2S ltn_Sdouble ltn_pmod // expn_gt0.\nQed.\n\nLemma pow2_mod3 n: 2^n %% 3 = 1 + odd n.\nProof.\nby elim:n => // n Hr /=; rewrite expnS -modnMm Hr; case: odd.\nQed.\n\nLemma pow2_mod3' n:\n  2^n = if (odd n) then (3*(((2^n).-2) %/3)).+2 else (3*(((2^n).-1) %/3)).+1. \nProof.\nrewrite (divn_eq (2^n) 3) pow2_mod3 (mulnC _ 3).\nby case: odd; rewrite !addnS addn0 /= mulKn.\nQed.\n\nLemma sqrnD_sub' m n: n <= m -> (m + n) ^ 2 =  4 * (m * n) + (m - n) ^ 2.\nProof.\nmove => h; rewrite sqrnD sqrnB // -[4]/(2+2) mulnDl - [in RHS]addnA addnC.\nby rewrite subnKC // nat_Cauchy.\nQed.\n\n(* sums *)\n\n\nLemma split_sum_even_odd1 (F: nat -> nat) n:\n  \\sum_(i<n.*2) (F i) = \\sum_(i< n) (F i.*2) + \\sum_(i< n) (F i.*2.+1).\nProof.\nelim:n; first by rewrite !big_ord0.\nby move => k Hr; rewrite doubleS !big_ord_recr /= Hr addnACA addnA.\nQed.\n\nLemma split_sum_even_odd (F: nat -> nat) n:\n  \\sum_(i<n) (F i) = \\sum_(i< (n.+1)./2) (F i.*2) + \\sum_(i< n./2) (F i.*2.+1).\nProof.\nby  case:(odd_dichot n) => ->; rewrite (half_bit_double n./2 true) -? doubleS\n   doubleK ? big_ord_recr split_sum_even_odd1  // addnAC. \nQed.\n\nLemma sum_rcons a l (F: nat -> nat): \n  \\sum_(i <- rcons l a) F i = F a + \\sum_(i <- l) F i.\nProof.\nby elim: l a => [a | a l Ih b]; rewrite /= !big_cons ?big_nil // Ih addnCA.\nQed.\n\nLemma sum_rev l (F: nat -> nat):\n  \\sum_(i <- rev l) F i = \\sum_(i <- l) F i.\nProof. \nby elim: l => [|a l H]; rewrite ? big_nil // big_cons rev_cons sum_rcons H.\nQed.\n\nLemma big_nat_shift  a b c p F:\n  \\sum_(c + a <= i < c + b | p i)  F i = \n  \\sum_(a <= i < b | p (c + i)) F (c + i).\nProof.\nrewrite /index_iota subnDl unlock; elim: (b - a) {1 3} (a) => // i H d /=.\nby rewrite  -addnS H. \nQed.\n\nLemma big_nat_cond_eq  a b p p' F :\n  (forall i, a <= i < b ->  (p i = p' i)) -> \n  \\sum_(a <= i < b | p i) F i =  \\sum_(a <= i < b | p' i) F i.\nProof.\nrewrite big_nat_cond [in RHS] big_nat_cond => H; apply: eq_bigl => i.\nby apply: (andb_id2l (H i)).\nQed.\n\n(** A property of the totient function *)\n\nLemma coprime_if_bezout a b u v: u * a  = v * b + 1 -> coprime a b. \nProof.\nmove => H; apply/coprimeP. \n  by move: H; case:(posnP a) => // ->; rewrite muln0 addn1.\nby exists (u,v); rewrite /= H addKn.\nQed.\n\nLemma minimal_bezout a b: 0 < a -> 0 < b -> coprime a b ->\n  exists u v, [/\\ u * a  = v * b + 1,  v < a & u <= b].\nProof.\nmove => ap bp cab; move/(coprimeP b ap): cab => [p hp].\nhave : p.1 * a =  p.2 * b + 1.\n  by move: (ltnSn 0); rewrite -{2 3} hp subn_gt0 => /ltnW h; rewrite subnKC.\nrewrite (divn_eq p.2 a) mulnDl mulnAC -addnA => sa.\nhave la: p.2 %/ a * b  <= p.1 by rewrite -(leq_pmul2r ap) sa leq_addr.\nmove/eqP:sa; rewrite -{1} (subnKC la) mulnDl eqn_add2l => /eqP hc.\nhave va:= (ltn_pmod p.2 ap).\nmove: (va);rewrite -(ltn_pmul2r bp) -addn1- hc mulnC (leq_pmul2l ap) => hd.\nby exists  (p.1 - p.2 %/ a * b), (p.2 %% a).\nQed.\n\nLemma minimal_bezout_prop a b u v: u * a  = v * b + 1 -> v < a -> u <= b ->\n  (forall u' v', u' * a = v' * b +1 -> (u <= u') && (v <= v')).\nProof.\nmove => B ua vb u' v' B'.\nhave ap: 0 < a by move:ua; case:(a).\ncase (posnP b) => bp. \n  by move: vb B; rewrite bp leqn0 => /eqP ->; rewrite muln0.\ncase: (ltnP u' u) => cp; last first.\n  by rewrite -(leq_pmul2r bp) -(leq_add2r 1) -B' - B (leq_pmul2r ap) cp.\nhave cp2:=(ltnW cp).\nhave cp1: v' <= v.\n  by rewrite - (leq_pmul2r bp)-(leq_add2r 1) -B -B' (leq_pmul2r ap).\nmove /eqP: B; rewrite -(subnK cp1) -(subnK cp2) !mulnDl - addnA -B'.\nrewrite eqn_add2r; set x := (u - u'); set y := (v - v') => /eqP eq3.\nhave cap: coprime b a by rewrite coprime_sym; apply:(coprime_if_bezout B').\nhave eq4: x = (x %/ b) * b.\n  symmetry; apply /eqP; rewrite - (dvdn_eq b x).\n  by move:(Gauss_dvdr x cap); rewrite mulnC eq3 {1}/dvdn modnMl eqxx => <-.\ncase: (posnP u') =>uz; first by move/eqP: B'; rewrite uz addn1.\nhave: u < b + u' by  apply: (leq_ltn_trans vb); rewrite ltn_paddr.\nrewrite -(subnK cp2) -/x eq4 ltn_add2r -{3}(mul1n b) ltn_pmul2r // ltnS leqn0.\nby move => /eqP qp; move: (ltn_eqF cp); rewrite -(subnK cp2) -/x eq4 qp eqxx.\nQed.\n\nLemma totient_ltn n: 1 < n -> totient n < n.\nProof.\nmove => l1n; rewrite totient_count_coprime.\nrewrite -{1 3}(prednK (ltnW l1n)) big_nat_recl // /coprime gcdn0 (gtn_eqF l1n).\nmove:(sum_nat_const_nat 0 n.-1 1); rewrite subn0 muln1 => {2} <-.\nby rewrite ltnS; apply: leq_sum => // i _; case: eqP.\nQed.\n\nLemma totient_prime n: prime n = (0 < n) && (totient n == n.-1).\nProof.\ncase: (posnP n) => np /=; first by rewrite np.\ncase pn:(prime n); first by rewrite -{1}(expn1 n) totient_pfactor // muln1 eqxx.\ncase/primePn: (negbT pn).\n  by rewrite ltnS leqn1; case/orP => /eqP => h; move: np; rewrite h.\nmove => [d /andP[l1d ldn] /gcdn_idPr gnd].\nsymmetry; apply: ltn_eqF. \nhave ns:= prednK np; have dc:= (prednK(ltnW l1d)).\nhave df: d.-1 < n.-1 by rewrite -ltnS dc ns. \nrewrite totient_count_coprime -{1}ns big_nat_recl // {1} /coprime gcdn0.\nrewrite (gtn_eqF (ltn_trans l1d ldn)).\nrewrite  -{2} (card_ord n.-1) - sum1_card big_mkord.\nrewrite (bigD1 (Ordinal df)) // [X in _ < X] (bigD1 (Ordinal df)) //=.\nrewrite dc /coprime  gnd (gtn_eqF l1d) 2!add0n add1n ltnS. \nby rewrite leq_sum // => i _; case: eqP.\nQed.\n\nLemma totient_pfactor_alt p e: prime p -> 0 < e -> \n    totient (p ^ e) = p ^ e - p ^ e.-1.\nProof.\nmove => pp ep; rewrite totient_pfactor // -{2} (prednK ep) expnS.\nby rewrite - {3} (prednK (prime_gt0 pp)) mulSn addKn.\nQed.\n\nLemma totient_prime_alt n: 1 < n -> totient n = n.-1 -> prime n.\nProof.\nmove => n1; move:(ltnW n1) => n0.\nmove:(pdiv_prime n1); set u := (pdiv n) => pu.\nmove:(pfactor_coprime pu n0)(prime_gt1 pu) => [m pa pb] u1.\nhave lp: 0 <  logn u n by rewrite logn_gt0 mem_primes pu n0 pdiv_dvd.\nhave pc: coprime m (u ^ logn u n) by rewrite coprime_sym; apply:coprimeXl.\ncase m1: (m==1).\n  set y := u.-1 * u ^ (logn u n).-1.\n  have yp: 0 < y by rewrite muln_gt0 expn_gt0 -ltnS (ltnW u1) (ltn_predK u1) u1.\n  rewrite pb (eqP m1) mul1n totient_pfactor// -{2 3}(prednK lp) expnS.\n  rewrite - {4} (prednK (ltnW u1)) mulSn  -/y -(prednK yp) addnS /=.\n  by move/eqP; rewrite - add1n eqn_add2r=> /eqP  <-; rewrite muln1.\ncase: (posnP m)=> mz h; first by move: n0; rewrite pb mz ltnn.\nhave /totient_ltn ha: 1 <m by rewrite  ltn_neqAle eq_sym m1 mz. \nhave /totient_ltn hb: 1 < (u ^ logn u n). \n  by apply: (leq_trans u1); rewrite -{1} (expn1 u) leq_pexp2l // (ltnW u1). \nmove: (leq_mul ha hb); rewrite mulSn mulnS addnA -(totient_coprime pc) - pb.\nrewrite h addSn addSnnS (prednK n0) - {3} (add0n n) leq_add2r leqn0 addn_eq0.\nby move: mz; rewrite - totient_gt0 => /gtn_eqF ->; rewrite andbF.\nQed.\n\n(** **  Fermat of exponent two *)\n\nLemma gcd_aux x y (g := gcdn x y) (x' := x%/g) (y':= y%/ g):\n  0 < x ->  [/\\ x = x' * gcdn x y, y = y' * gcdn x y & coprime x' y'].\nProof.\nmove => xp.\ncase: (egcdnP y xp) => u v /= /eqP bz _.\nmove: (dvdn_gcdl x y)(dvdn_gcdr x y); rewrite !dvdn_eq => /eqP xv /eqP yv.\nsplit =>//.  \nmove: bz; rewrite -[gcdn x y]mul1n -{1} yv -{1} xv !mulnA -mulnDl addnC.\nby rewrite eqn_pmul2r ?gcdn_gt0 ?xp // addnC => /eqP /coprime_if_bezout.\nQed.\n\nLemma pythagore_aux a b c (d := (c %/ b)) :\n  0 < b -> a * b^2 = c^2 -> c = d * b /\\ a = d ^2.\nProof.\nmove => bp h; move: (esym (@dvdn_pexp2r b c 2 (ltnSn 1))).\nrewrite -h {2}/dvdn modnMl dvdn_eq eqxx => /eqP h1.\nby  move /eqP: h;  rewrite -{1 2} h1 expnMn eqn_pmul2r ? sqrn_gt0 // => /eqP.\nQed.\n\n\nLemma factor_square a b c (u:=a %/ gcdn a c) (v := c %/ gcdn a c):\n  0 < a -> coprime a b -> a * b = c ^2 -> [/\\ a = u ^2, b = v^2 & coprime u v].\nProof.\nmove => ap cab /eqP Eq.\nmove:(gcd_aux c ap); rewrite -/u -/v; move  => [av cv cuv].\nmove: cab; rewrite av coprimeMl => /andP [cub cgb].\nmove: Eq; rewrite {1}av {2} cv mulnAC expnMn - (mulnn (gcdn a c)) mulnA.\nrewrite eqn_pmul2r ?gcdn_gt0 ? ap // => /eqP Eq.\nmove:ap; rewrite {1}av muln_gt0  => /andP [up _].\nhave: (u %| v ^ 2 * gcdn a c) by rewrite -Eq /dvdn modnMr.\nhave: (gcdn a c %| b * u ) by rewrite mulnC Eq /dvdn mulnC modnMr.\nrewrite !Gauss_dvdr ? coprimeXr // => dvd1 dvd2.\nmove: (eqn_dvd (gcdn a c) u); rewrite dvd1 dvd2 /= => /eqP gv.\nby move /eqP:Eq; rewrite gv mulnn mulnC eqn_pmul2r // => /eqP ->.\nQed.\n\n\n(* not much simpler\nLemma double_square_square m n: (n ^2).*2 = m ^2 -> n = 0.\nProof.\nmove/eqP => h.\nelim: m {-2} m (leqnn m) n h.\n  move => m; rewrite leqn0 => /eqP -> n; rewrite double_eq0 expn_eq0 andbT.\n  by move/eqP.\nmove => k IH m; rewrite leq_eqVlt; case/orP=> [|Hm]; last first.\n  by apply: IH; rewrite -ltnS.\nmove => /eqP -> n; case: (odd_dichot k.+1) => od h.\n  by move:(f_equal odd (eqP h)); rewrite oddX od /= !odd_double. \nhave nk: n <= k. \n  rewrite - ltnS ltn_neqAle  - leq_sqr - (eqP h) double_le1 andbT. \n  apply /negP => eq1; move: h. \n  by rewrite - (addn0 (k.+1 ^ 2)) (eqP eq1) -addnn eqn_add2l expn_eq0 //.\nmove: h; rewrite od - (muln2 (k.+1)./2) expnMn -[2^2]/(2 * 2) mulnA muln2 muln2.\nrewrite eqn_double eq_sym => ea.\nby move: od; rewrite (IH n nk k.+1./2 ea). \nQed.\n\n*)\n\nLemma double_square n: n.*2 ^2 = (n ^2) .*2 .*2.\nProof. by  rewrite -muln2 expnMn -[2^2]/(2 * 2) mulnA 2!muln2.  Qed.\n\nLemma double_square_square m n: (n ^2).*2 = m ^2 -> n = 0.\nProof.\nmove/eqP.\nelim: n {-2} n (leqnn n) m; first by move => n; rewrite leqn0 => /eqP.\nmove => k IH n; rewrite leq_eqVlt; case/orP=> [/eqP -> m Hm |Hm]; last first.\n  by apply: IH; rewrite -ltnS. \nmove:(odd_double (k.+1 ^ 2)); rewrite (eqP Hm) odd_sqr => /evenE mv.\nmove: Hm; rewrite mv double_square eqn_double eq_sym => ea.\ncase: (ltnP k (m./2)).\n  by rewrite - leq_sqr - leq_double (eqP ea) leqNgt double_le3.\nby move => la; move: (ea); rewrite (IH  _ la _ ea) (eqn_sqr 0).\nQed.\n\nLemma gcd_n2 n: gcdn n 2 = if (odd n) then 1 else 2.\nProof.\nby rewrite -{1} (odd_double_half n) -muln2 addnC gcdnC gcdnMDl; case: odd.\nQed.\n\nLemma square_odd_mod4 n: odd n -> n^2 = 1 %[mod 4]. \nProof.\nrewrite -{2} (odd_double_half n) sqrnD => ->.\nby rewrite mul1n -mul2n mulnA expnMn -addnA -mulnDr addnC mulnC modnMDl.\nQed.\n\n\nLemma coprime_sqr m n: coprime (m ^2) (n ^ 2) = coprime m n.\nProof. rewrite coprime_pexpr // coprime_pexpl //. Qed.\n\nLemma coprimeDl m n: coprime m (m + n) = coprime m n.\nProof. by rewrite/coprime gcdnDl. Qed.\n\nLemma coprimeDr m n: coprime m (n + m) = coprime m n.\nProof. by rewrite/coprime gcdnDr. Qed.\n\nLemma pythagore_tripleA p q r \n  (x := r* (p^2 - q^2)) (y := r*(p*q).*2) (z:= r*(p^2 + q ^2)): \n  q <= p -> x^2 + y^2 = z ^2.\nProof.\nrewrite /x /y/z -leq_sqr /= !expnMn -mulnDr -mul2n !expnMn => h.\nrewrite -(sqrnD_sub h) subnK //; apply:nat_AGM2.\nQed.\n\nLemma pythagore_gcd p q:  q <= p -> coprime p q ->  odd p != odd q ->\n  coprime (p ^ 2 - q ^ 2) (p * q).*2.\nProof.\nmove => lqp; rewrite {2}/coprime.\nrewrite subn_sqr -{1 2 4 5} (subnK lqp); set r := p - q.\nrewrite /coprime_sym /coprime gcdnC gcdnDr -/(coprime _ _) => cqr.\nrewrite oddD negb_eqb - addbA addbb addbF => or.\nhave cpq: (coprime (r * (r + q + q)) q).\n  by rewrite coprime_sym /coprime Gauss_gcdr // !gcdnDr.\nhave cp2: coprime (r * (r + q + q)) 2.\n  by rewrite /coprime gcd_n2 oddM - addnA oddD or addnn odd_double.\nrewrite - mul2n Gauss_gcdr // Gauss_gcdl // gcdnC Gauss_gcdl.\n  by rewrite gcdnC -/(coprime _ _) coprimeDl coprime_sym.\nby rewrite coprimeDl coprime_sym  coprimeDr.\nQed.\n\nLemma pythagore_mod4 x y z: coprime x y -> x ^ 2 + y ^ 2 = z ^ 2 ->\n  odd x != odd y.\nProof.\nmove => cpa eq1.\ncase ox: (odd x); case oy: (odd y) => //.\n  move:(f_equal (fun z => z %% 4) eq1); rewrite -(modnDm) square_odd_mod4 //. \n  rewrite square_odd_mod4  // (@modn_small 1) // (@modn_small 2) //.\n  case oz: (odd z); first by rewrite square_odd_mod4.\n  by rewrite (evenE oz) -mul2n expnMn modnMr.\nmove: cpa; rewrite (evenE ox) (evenE oy) -!muln2 /coprime.\nby rewrite -muln_gcdl muln_eq1 andbF.\nQed.\n\nLemma pythagore_tripleB x y z (r := gcdn x y): x^2 + y ^2 = z^2 ->\n  [\\/ x=0 /\\ y = z, y = 0 /\\ x = z |\n  exists p q, [/\\ 0 < r, q < p, coprime p q, odd p != odd q &\n     [/\\ x = r* (p^2 - q^2), y = r*(p*q).*2 & z = r*(p^2 + q ^2) ] \\/\n     [/\\ y = r* (p^2 - q^2), x = r*(p*q).*2 & z = r*(p^2 + q ^2) ]]].\nProof. \ncase: (posnP x) => xp.\n  by move /eqP; rewrite xp add0n eqn_sqr => /eqP ->; constructor 1.\ncase: (posnP y) => yp.\n  by move /eqP; rewrite yp addn0 eqn_sqr => /eqP ->; constructor 2.\nmove => h;constructor 3.\ncase:(gcd_aux y xp); set a := _ %/ _; set b := _%/ _;  rewrite -/r => xv yv cp1.\nhave rp: 0 < r by rewrite gcdn_gt0 xp.\nmove: h xp yp; rewrite xv yv !expnMn - mulnDl {xv yv}.\nmove/(pythagore_aux rp); set c := z%/r; move => [-> h].\ncase az: (a==0); first by rewrite (eqP az) mul0n.\ncase bz: (b==0); first by rewrite (eqP bz) mul0n.\nmove => _ _; rewrite (mulnC a)  (mulnC b) (mulnC c).\nwlog: a b az bz h cp1 / odd a && ~~(odd b).\n  move => H; move: (pythagore_mod4 cp1 h).\n  case oa: (odd a); first by move =>  /= ob; apply: H => //; rewrite oa ob.\n  rewrite negb_eqb /= => /= ob; rewrite addnC in h; rewrite coprime_sym in cp1.\n  have oc:odd b && ~~ odd a by rewrite oa ob.\n  move:(H b a bz az h cp1 oc) =>[p [q [ha hb hc hd he]]];exists p,q.\n  by split =>//;case: he => hh;[right| left].\nmove => /andP[oa eb].\nhave lac: a < c by rewrite - ltn_sqr -h ltn_paddr // expn_gt0 lt0n bz.\nhave lac' := ltnW lac.\nmove: (f_equal odd h); rewrite oddD ! odd_sqr oa (negbTE eb) /= => oc.\nhave eq2:=(evenE (negbTE eb)).\nhave eq3: b^2 = (c-a)* (c+a) by rewrite - subn_sqr -h addKn.\nmove:(odd_double_half (c +a)); rewrite oddD oa - oc add0n => eq4.\nmove:(odd_double_half (c -a)); rewrite oddB // oa - oc add0n => eq5.\nhave eq6: (b./2) ^2 = (c - a)./2 * (c + a)./2.\n  apply/eqP; rewrite -(@eqn_pmul2l (2 * 2)) // mulnACA !mul2n eq4 eq5 - eq3.\n  by rewrite  -(expnMn 2 _ 2) mul2n - eq2.\nhave ap: 0 < a by rewrite lt0n az.\nhave cp:=(ltn_trans ap lac).\nhave cap: coprime c a.\n  by rewrite -coprime_sqr -h coprime_sym coprimeDl  coprime_sqr.\ncase: (posnP (c - a)./2) => lt1.\n  by move /eqP:eq6; rewrite lt1 expn_eq0 - double_eq0 -eq2 bz.\nhave av: ((c + a)./2 - (c - a)./2) == a.\n  by rewrite -eqn_double doubleB eq4 eq5 addnC -addnn -addnBA ?subKn// leq_subr.\nhave cv: ((c - a)./2 + (c + a)./2) == c.\n  by rewrite - eqn_double doubleD eq4 eq5 (addnC c) addnA (subnK lac') addnn.\nhave lt2:= (leq_ltn_trans (leq_subr a c) (ltn_paddr c ap)).\nhave cp2: (coprime (c - a)./2 (c + a)./2).\n  move: (esym oc); rewrite -coprimen2 => hw.\n  rewrite /coprime -gcdnDl (eqP cv) gcdnC -(Gauss_gcdr _ hw) mul2n eq5.\n  by rewrite gcdnC -{2}(subnK lac') gcdnDl gcdnC - gcdnDr subnK // gcdnC.\ncase: (factor_square lt1 cp2 (esym eq6)).\nset q := _ %/ _; set p := _ %/ _ => eq7 eq8 cpxy.\nhave H w: odd w = odd (w ^2) by rewrite oddM andbb.\nhave eq9: b = (p * q).*2.  \n  apply /eqP; rewrite -eqn_sqr - muln2 2!expnMn -eq8 -eq7 (mulnC (_ ./2)) -eq6.\n  by rewrite - expnMn muln2 -eq2.\nexists p, q; rewrite - eq9 coprime_sym; split => //.\n+ by rewrite - ltn_sqr -eq7 -eq8 - ltn_double eq4 eq5.\n+ by rewrite  (H p) (H q) negb_eqb -oddD -eq7 -eq8 addnC (eqP cv).\n+ by left; rewrite -eq7 - eq8 (eqP av) addnC  (eqP cv) eq9.\nQed.\n\nLemma Fermat4 x y z : x^2 + y^4 = z^4 -> (x == 0) || (y == 0).\nProof.\ncase: (posnP x) => xp //.\ncase: (posnP y) => yp //=.\ncase:(gcd_aux z yp); set a := _ %/ _; set b := _ %/ _; set r := gcdn y z. \nmove => sa sb cp eqa.\nmove: (subn_sqr (z^2) (y^2)); rewrite -!expnM - eqa addnK sa sb.\nrewrite !expnMn - mulnDl -mulnBl mulnACA mulnn => eqb.\nhave rp: 0 < r by rewrite gcdn_gt0  yp.\nhave: (r^2)^2 %| x ^2 by rewrite eqb /dvdn modnMl.\nrewrite dvdn_pexp2r // => /dvdnP [c xv].\nmove /eqP: eqb; rewrite xv expnMn eqn_pmul2r ?expn_gt0 ? rp// => eqc.\nhave ap: 0 < a by move: yp; rewrite sa muln_gt0 rp andbT.\nhave: a < b. \n  rewrite -ltn_sqr ltnNge /leq; apply/eqP => h. \n  by move: xp; rewrite -ltn_sqr xv expnMn (eqP eqc) h.\nmove: (leqnn b) cp eqc ap; clear; elim: b {-2} b a c.\n  by move => b a c; rewrite leqn0 => /eqP ->; rewrite ltn0.\nmove => K IH b a c ns cab eqa ap lab.\nhave ha: a ^ 2 <= b ^ 2 by rewrite leq_sqr (ltnW lab).\nhave eqd: c^2 + (a^2)^2 = (b^2)^2.\n   by rewrite (eqP eqa) - subn_sqr subnK // leq_sqr. \ncase: (posnP c) => cp; first by move/eqP:eqd;rewrite cp 2!eqn_sqr (ltn_eqF lab).\nmove: (cab). \nrewrite - 2!coprime_sqr -eqd addnC coprimeDl coprime_sym coprime_sqr => cac.\ncase oa: (odd a).\n  case: (pythagore_tripleB eqd).\n  + by case => /eqP; rewrite (gtn_eqF cp).\n  + by case => /eqP; rewrite expn_eq0 andbT (gtn_eqF ap).\n  + move => [p [q []]]; rewrite (eqP cac) ! mul1n => _ sb sc sd [][qa qb qc].\n      by move: (f_equal odd qb); rewrite odd_sqr odd_double oa.\n    case:(posnP q) => qp; first by move: cp; rewrite qb qp !muln0.\n    have lpk: p <= K.  \n       rewrite -ltnS; apply: leq_trans ns. \n       by rewrite -ltn_sqr qc ltn_paddr // expn_gt0 qp. \n    by apply: (IH p q (a*b)) => //; rewrite 1? coprime_sym // -qa -qc expnMn.\ncase ob: (odd b); last first.\n  move: cab;rewrite (evenE oa) (evenE ob) -!muln2. \n  by rewrite /coprime -muln_gcdl muln_eq1 andbF. \nhave cp2: coprime (b ^ 2 - a ^ 2)  (b ^ 2 + a ^ 2).\n  have cp1:coprime (b ^ 2 + a ^ 2) 2.\n    by rewrite coprimen2 oddD !odd_sqr oa addbF.\n  rewrite /coprime gcdnC -gcdnDl -addnA subnKC // addnn -muln2 Gauss_gcdl //.\n  by rewrite gcdnC gcdnDl gcdnC -/(coprime _ _) coprime_sqr. \nmove /eqP: (eqa); move/esym => eqa'.\ncase: (posnP (b ^ 2 - a ^ 2)) => dp.\n  by move: cp; rewrite -sqrn_gt0 - eqa' dp. \ncase: (factor_square dp cp2 eqa'); set t := _ %/ _; set s := _ %/ _.\nmove => t2 s2 cst.\nhave os: odd s by rewrite -odd_sqr -s2 oddD !odd_sqr oa ob.\nhave ot: odd t by rewrite -odd_sqr -t2 oddB // !odd_sqr oa ob.\nmove: (oddE os) (oddE ot) => sv1 tv1.\nset u := (s+t)./2; set v := (s-t)./2.\nhave cp0: t < s.\n  have qa: b ^ 2 - a ^ 2  <= b^2 by rewrite leq_subr.\n  have qb: b ^ 2  < b ^ 2 + a ^ 2 by apply: ltn_paddr; rewrite expn_gt0 ap.\n  by move: (leq_ltn_trans qa qb); rewrite t2 s2 ltn_sqr.\nhave cp1: t./2 <= s./2 by apply: half_leq; apply:ltnW.\nhave uE: u = s./2 + t./2 +1. \n  by rewrite /u {1} sv1 {1}tv1 addSnnS -doubleS -doubleD doubleK addn1 addnS.\nhave vE: v =  s./2 - t./2.\n  by rewrite /v {1} sv1 {1} tv1 subSS -doubleB doubleK.\nhave sE: s = u + v. \n  by rewrite uE vE addnAC -2!addnA (addnA t./2) subnKC //addnA addnn addn1. \nhave tE: t = u - v. \n  by rewrite uE vE (subnBA _ cp1) (addnAC s./2) -2!addnA addnn add1n -tv1 addKn.\nhave luv: v < u by rewrite uE addn1 ltnS vE leq_BD.\nhave cuv: coprime u v. \n  move: cst; rewrite sE tE /coprime gcdnC -gcdnDl -addnA (subnKC (ltnW luv)).\n  by rewrite addnn - muln2 Gauss_gcdl ? coprimen2 -?sE // sE gcdnC gcdnDl.\nhave suv: u^2 + v ^2 = b^2.\n  have h: (b^2).*2 = s^2 + t ^2 by rewrite -t2 -s2 -addnA (subnKC ha) addnn.\n  apply/eqP; rewrite - eqn_double h sE tE sqrnD (sqrnB (ltnW luv)) -addnA.\n  by rewrite subnKC ?addnn // nat_Cauchy.\nhave puv: v * (2 * u) = a ^2.\n  by move/eqP:(sqrnD u v);rewrite suv -sE -s2 eqn_add2l mulnA mulnC => /eqP ->.\ncase: (posnP v) => vz; first by move: ap; rewrite - sqrn_gt0 -puv vz.\ncase: (posnP u) => uz; first  by move: luv; rewrite uz ltn0.\ncase:(pythagore_tripleB suv).\n    by move => []; rewrite uE addn1.\n  by move => [vzz]; move: vz; rewrite vzz.\nmove => [p [q [gp lqp cpq opq]]]; rewrite (eqP cuv) ! mul1n.\nhave odf: odd (p ^ 2 - q ^ 2).\n  by rewrite oddB ?odd_sqr ?leq_sqr ?(ltnW lqp) //= - negb_eqb.\nhave pp: 0 < p by  move: lqp; case p. \nhave Hw w: 0 < w -> w <= w^2 by move => h; rewrite -{1}(expn1 w) leq_pexp2l.\ncase=> [] [up vp bp].\n  case: (posnP q) => qp; first by move: vz; rewrite vp qp !muln0.\n  have cp3: coprime u (2* v).\n     by rewrite /coprime Gauss_gcdl //  -/(coprime _ _) coprimen2 up. \n  have puv': u * (2 * v) = a ^ 2 by rewrite - puv mulnCA mulnA mulnC.\n  case:(factor_square uz cp3 puv'); set d := _ %/ _; set e := _ %/_.\n  move => us vs cp4.\n  move: (f_equal odd vs); rewrite odd_sqr mul2n odd_double => oe.\n  move /eqP: vs; rewrite  (evenE (esym oe)) - mul2n expnMn.\n  rewrite vp - mulnA !mul2n 2! eqn_double => pqs.\n  case: (factor_square pp cpq (eqP pqs)).\n  set aa := _ %/ _; set bb := _ %/ _ => [Ha Hb Hc].\n  have bbp: 0  < bb by rewrite -sqrn_gt0 -Hb.\n  have cba: bb < aa by rewrite -ltn_sqr -Ha -Hb.\n  case: (posnP aa) => aap; first by move: cba; rewrite aap;case: (aa).\n  have aaK: aa <= K. \n     move: (Hw aa aap); rewrite -Ha => hb; apply: (leq_trans hb).\n     rewrite -ltnS; apply: leq_trans ns. \n     by apply:(leq_ltn_trans (Hw p pp)); rewrite bp ltn_paddr // sqrn_gt0.\n  rewrite coprime_sym in Hc.\n  by apply: (IH aa bb d aaK Hc) => //; rewrite -Ha -Hb -us up -subn_sqr.\nhave cp3 : coprime v (2* u). \n  by rewrite /coprime Gauss_gcdl 1? coprime_sym // -/(coprime _ _) coprimen2 up.\ncase:(factor_square vz cp3 puv); set d:= _ %/ _; set e := _ %/ _  => us vs cp4.\nmove: (f_equal odd vs); rewrite odd_sqr mul2n odd_double => oe.\nmove /eqP: vs; rewrite (evenE (esym oe)) - mul2n expnMn -[2^2]/(2*2) - mulnA.\nrewrite vp !mul2n !eqn_double => pqs.\ncase: (posnP q) => qp; first by move: uz; rewrite vp qp !muln0.\ncase: (factor_square pp cpq (eqP pqs)).\nset aa := _ %/ _; set bb := _ %/ _ => [Ha Hb Hc].\nhave bbp: 0 < bb by rewrite -sqrn_gt0 -Hb.\nhave cba: bb < aa by rewrite -ltn_sqr -Ha -Hb.\ncase: (posnP aa) => aap; first by move: cba; rewrite aap;case: (aa).\nhave aaK: aa <= K. \n   move: (Hw aa aap); rewrite -Ha => hb; apply: (leq_trans hb).\n   rewrite -ltnS; apply: leq_trans ns. \n   by apply:(leq_ltn_trans (Hw p pp)); rewrite bp ltn_paddr // sqrn_gt0.\nrewrite coprime_sym in Hc.\nby apply: (IH aa bb d aaK Hc) => //; rewrite -Ha -Hb -us up -subn_sqr.\nQed.\n\nLemma Fermat4_alt x y z (pa:= fun x => exists y, x= y^2 \\/ x = (y^2).*2)\n  (pb := fun x y z => [\\/ pa x /\\ pa y, pa y /\\ pa z | pa z /\\ pa x]):\n  x^2 + y ^2 = z ^2 -> coprime x y -> pb x y z -> (x == 0) || (y == 0).\nProof.\nelim: z {-2} z (leqnn z) x y.\n   move => z; rewrite leqn0 => /eqP -> x y /eqP; rewrite addn_eq0 expn_eq0 //.\n   by rewrite andbT; move/andP => [->].\nmove => K Hrec z zB x y ha hb hc.\nwlog: x y ha hb hc /(odd y).\n  move => H; move:(pythagore_mod4 hb ha); case oy: (odd y).\n    by move => _; apply: H.\n  rewrite coprime_sym in hb; rewrite addnC in ha; rewrite negb_eqb addbF orbC. \n  apply: H => //; case: hc => [][qa qb]. \n  - by constructor 1.\n  - by constructor 3.\n  - by constructor 2.\nmove => oy; case: (pythagore_tripleB ha).\n    by move => [->].\n  by move => [->]; rewrite orbT.\nmove => [p [q []]]; rewrite (eqP  hb) !mul1n => _ lqp cp2 opq.\ncase => [][yv xv zv]; first by move: oy; rewrite xv odd_double.\nhave oz: odd z by rewrite -odd_sqr - ha oddD !odd_sqr oy xv odd_double.\nhave paw w:  pa w -> odd w ->exists y', w = y'^2.\n  move => [t]; case => ->; [ by exists t | by rewrite odd_double].\nhave lb: (q ^ 2) <= (p ^ 2)  by rewrite leq_sqr (ltnW lqp).\nhave la: (q ^ 2) ^ 2 <= (p ^ 2) ^ 2 by rewrite leq_sqr.\nhave zz: z = 0 -> (x == 0) || (y == 0).\n  by move => h; move /eqP:ha; rewrite h addn_eq0 !expn_eq0 !andbT => /andP[->].\ncase (posnP q) => qp; first by rewrite xv qp !muln0.\ncase (posnP p) => pp; first by rewrite xv pp. \nhave pax: pa x -> pa p /\\ pa q.\n  rewrite xv; move: opq cp2; rewrite negb_eqb; clear;wlog: p q /odd p.\n      move => H; case op: (odd p) => ww; first by apply:H => //; rewrite op.\n      rewrite coprime_sym mulnC=> sa sb.\n      simpl in ww; have opq: odd q (+) odd p by rewrite ww op.\n      by case: (H q p ww opq sa sb).\n   case: (posnP p) => pp; first by rewrite pp.\n   move => op; rewrite op /= => oq cpq [t]; case.\n     rewrite - muln2 -mulnA (mulnC q) => eqa.\n     have cp': coprime p (2 * q) by rewrite /coprime Gauss_gcdr // coprimen2.\n     case: (factor_square pp cp' eqa); set u:= _ %/ _; set v := _ %/ _.\n     move => -> hb hc.\n     move:(f_equal odd (esym hb)); rewrite odd_sqr mul2n odd_double => ov.\n     split; first by exists u; left.\n     move /eqP: hb; rewrite (evenE ov) - mul2n expnMn - (mulnA 2 2) !mul2n => h.\n     by exists (v./2); right; apply/eqP; rewrite -eqn_double h. \n  move/eqP; rewrite eqn_double => /eqP eqa.\n  case: (factor_square pp cpq eqa); set u := _ %/ _; set v := _ %/ _.\n  move => -> -> cp;split; [ by exists u; left | by exists v; left].\nhave lpk: p^2 <= K. \n  by rewrite -ltnS; apply: leq_trans zB; rewrite zv ltn_paddr // sqrn_gt0.\nhave lpk1: p <= K.\n  by apply: leq_trans lpk; rewrite -{1}(expn1 p) leq_pexp2l.\ncase: hc => [] [he hf].\n+ move: (paw _ hf oy) => [y' y'v].\n  move: (pax he)=> [sa sb].\n  have eq2: q ^ 2 + y' ^ 2 = p ^ 2 by rewrite -y'v yv subnKC.\n  have cp3: coprime q y'.\n    by rewrite -coprime_sqr -coprimeDl eq2 coprime_sqr coprime_sym.\n  have rc: pb q y' p by constructor 3.\n  move: (Hrec p lpk1 q y' eq2 cp3 rc); rewrite  (gtn_eqF qp) /= y'v => /eqP.\n  by move => ->; rewrite orbT.\n+ move: (paw _ he oy) => [y' ysv]; move: (paw _ hf oz) => [z' zsv].\n  have ra:(y' * z') ^ 2 + (q ^ 2) ^ 2 = (p ^ 2) ^ 2.\n    by rewrite expnMn - ysv - zsv yv zv - subn_sqr subnK.\n  have rb:coprime (y' * z') (q ^ 2). \n    by rewrite -coprime_sqr coprime_sym - coprimeDr ra !coprime_sqr coprime_sym.\n  have rc:pb (y' * z') (q ^ 2) (p ^ 2). \n    constructor 2; split; [ by exists q; left |  by exists p; left].\n  move: (Hrec (p^2) lpk (y'*z') (q^2) ra rb rc). \n  rewrite expn_eq0  (gtn_eqF qp) muln_eq0 orbF; case/orP => /eqP hw.\n    by rewrite ysv hw orbT.\n    by apply:zz; rewrite zsv hw.\n+ move: (paw _ he oz) => [z' z'v].\n  move: (pax hf)=> [sa sb].\n  have eq2: p ^ 2 + q ^ 2 = z' ^ 2 by rewrite - z'v zv.\n  have pbb: pb p q z' by constructor 1.\n  have lt1: z' <= K.\n    move: (qp)(pp); rewrite - sqrn_gt0 - (sqrn_gt0 p) => l1 l2.\n    move:(leq_add l2 l1) zB; rewrite - zv z'v; clear; case z' => //; case=> //.\n    move => n nb nc; rewrite - ltnS; apply: leq_trans nc.\n    by rewrite - mulnn; apply:ltn_Pmull.\n  by move: (Hrec z' lt1 p q eq2 cp2 pbb); rewrite (gtn_eqF qp) (gtn_eqF pp).\nQed.\n\nLemma Fermat4' x y z : x^2 + y^4 = z^4 -> (x == 0) || (y == 0).\nProof.\ncase: (posnP x) => xp //.\ncase: (posnP y) => yp //=.\ncase:(gcd_aux z yp); set a := _ %/ _; set b := _ %/ _; set r:= gcdn y z. \nmove => sa sb cp eqa.\nmove: (subn_sqr (z^2) (y^2)); rewrite - !expnM - eqa addnK sa sb.\nrewrite !expnMn - mulnDl -mulnBl mulnACA mulnn => eqb.\nhave rp: 0 < r by rewrite gcdn_gt0  yp.\nhave r4p:0 < r ^ (2 * 2) by rewrite  expn_gt0 rp.\nhave: (r^2)^2 %| x ^2 by rewrite eqb /dvdn modnMl.\nrewrite dvdn_pexp2r // => /dvdnP [c xv].\nmove /eqP: eqa; rewrite sa sb xv !expnMn mulnn - expnM -mulnDl eqn_pmul2r //.\nrewrite -[4]/(2*2) 2!expnM => /eqP eqc.\nhave cpp: coprime c (a^2).\n  by rewrite -coprime_sqr coprime_sym -coprimeDr eqc !coprime_sqr.\nmove: (Fermat4_alt eqc cpp); set W:= (or3 _ _ _) => H.\nhave wt: W by constructor 2; split; [ exists a| exists b]; left.\nmove: (H wt); case/orP => ea.\n  by move: xp; rewrite xv (eqP ea).\nby move: ea yp; rewrite expn_eq0 andbT sa => /eqP ->.\nQed.\n\n\nLemma Fermat2_bound a b c: a^2 + b^2 = c^2 -> b <= c ?= iff (a == 0).\nProof.\nmove => h. \nby rewrite - (mono_leqif leq_sqr) - h - {1} (add0n (b^2))\n             (mono_leqif (leq_add2r (b^2))) -[0]/(0^2) (mono_leqif leq_sqr). \nQed.\n\nLemma Fermat2_bound2 a b c: a^2 + b^2 = c^2 -> c <= (a+b) ?= iff (a*b == 0).\nProof.\nmove => h. \nrewrite - (mono_leqif leq_sqr) sqrnD - h - {1} (addn0 (a^2 + b^2)).\nby rewrite (mono_leqif (leq_add2l (a^2 + b^2))); split => //; case: (a*b).\nQed.\n\n\nLemma square_plus1_square m n: n ^2 + 1 = m ^2 -> n = 0.\nProof.\nrewrite -{2}[1]/(1^2) => h; apply/eqP.\ncase:(Fermat2_bound2 h);rewrite muln1 addn1 leq_eqVlt ltnS; case: eqP => //= _. \nby rewrite addnC in h; case:(Fermat2_bound h); rewrite  eqn_leq => -> /= ->.\nQed. \n\n\nLemma square_plus1_square_alt m n: n ^2 + 1 = m ^2 -> n = 0.\nProof.\nmove => h.\ncase: (ltnP n m); rewrite -leq_sqr -h addn1 ? ltnn//.\nrewrite - addn1 sqrnD addnAC addn1 ltnS  muln1 - {2} (addn0 (n^2)).\nby rewrite leq_add2l leqn0 muln_eq0 /= => /eqP.\nQed.\n\nLemma square_plus2_square m n: n ^2 + 2 = m ^2 -> False.\nProof.\nmove => eq1.\ncase: (ltnP n m);rewrite -leq_sqr -eq1; last by rewrite leqNgt ltn_paddr.\nrewrite -addn1 sqrnD -addnA leq_add2l muln1 mul2n add1n (ltn_double n 1).\nby move: eq1; case: n => //=; rewrite add0n; move/(@double_square_square m 1).\nQed.\n\n\nLemma square_plus3_square m n: n ^2 + 3 = m ^2 -> (n = 1 /\\ m = 2). \nProof.\nmove => eq1.  move:(subn_sqr m n); rewrite -eq1 addKn.\ncase: (ltnP m n); first by rewrite -ltn_sqr - (addn0 (n^2)) -eq1 ltn_add2l.\nmove => ha; rewrite -{2 3} (subnK ha)- addnA addnn => eqB.\nhave: (m-n) < 2 by rewrite - ltn_sqr ltnS eqB mulnDr mulnn leq_addr.\nmove: eqB;case: (m-n) => //; case => // /eqP.\nby rewrite mul1n -[3]/(1+1.*2) (eqn_add2l) eqn_double => /eqP <-.\nQed.\n\nLemma square_plus4_square m n: n ^2 + 4 = m ^2 -> n = 0.\nProof.\nmove => h; move:(subn_sqr m n); rewrite - h addKn.\ncase: (ltnP m n); first by rewrite -ltn_sqr - (addn0 (n^2)) -h ltn_add2l.\nmove => ha; rewrite -{2} (subnK ha)- addnA addnn.\nrewrite -(odd_double_half (m-n)); case: odd.\n  by move => eqA; move:(f_equal odd eqA); rewrite oddM !oddD !odd_double.\nmove/esym; move/eqP; rewrite -[4]/(1.*2.*2) add0n -doubleD -doubleMr.\nby rewrite -doubleMl 2!eqn_double muln_eq1 => /andP[/eqP -> /eqP]; case.\nQed.\n\n\n\nFact square_plus4_square_alt m n: n ^2 + 2^2 = m ^2 -> n = 0.\nProof.\nhave: prime 2 by []; move/primeP => [_ dvd2]. \ncase /pythagore_tripleB; [ by case => h | by case | ].\nmove => [p [q [ha hb hc hd]]]; case; case => ea eb ec.\n   move/eqP: eb;rewrite {2} ea -doubleMr (eqn_double 1) eq_sym !muln_eq1. \n   by move => /and3P [ /eqP -> /eqP ->  /eqP  -> ]. \nrewrite subn_sqr in ea.\nhave he: (p + q) %| 2 by rewrite ea mulnA /dvdn modnMl.\ncase/orP:  (dvd2 _ he) => /eqP.\n   move: eb; clear; case: q; first by rewrite !muln0. \n   move => q av /eqP; rewrite addnS eqSS addn_eq0 => /andP [ha hb].\n   by rewrite av (eqP ha) muln0.\nby move/(f_equal odd); rewrite oddD -negb_eqb hd.\nQed.\n\n\nLemma square_plus4_square_alt2 m n: n ^2 + 4 = m ^2 -> n = 0.\nProof.\nrewrite -[4]/(2^2) => h; apply/eqP.\ncase:(Fermat2_bound2 h). rewrite muln2 addn2 double_eq0 2!leq_eqVlt 2!ltnS.\nrewrite addnC in h; move/leqifP:(Fermat2_bound h) => /= lnm.\nrewrite leqNgt lnm /=; case/orP; first by move->.\nrewrite orbF eqSS => /eqP k; move:(congr1 odd h). \nby rewrite k oddD !odd_sqr/=; case: odd.\nQed.\n\nLemma square_plus9_square n m: n ^2 + 3^2 = m ^2 -> (n = 0 \\/ n = 4).\nProof.\ncase /pythagore_tripleB; [ by case => h _; left | by case | ].\nmove => [p [q[ha hb hc hd]]] [] [ea eb _].\n  by move: (f_equal odd eb); rewrite -doubleMr odd_double.\nrewrite subn_sqr in ea.\nhave /primeP [_ h]: prime 3 by [].\nhave da: (p + q) %| 3 by rewrite ea mulnA /dvdn modnMl.\ncase/orP:  (h _ da) => /eqP rv.\n   move: eb hb rv; clear; case: q; first by rewrite !muln0 => ->; left.\n   move => q _ np => /eqP; rewrite addnS eqSS addn_eq0 => /andP [ha hb].\n   by move: np; rewrite (eqP ha) (eqP hb).\nmove/eqP: ea; rewrite rv mulnA -{1}[3]/(1*3) eqn_pmul2r // eq_sym muln_eq1.\nmove /andP => [r1 pq].\nright; move /eqP: rv;rewrite eb (eqP r1) -(subnK (ltnW hb)) (eqP pq).\nby rewrite -addnA eqSS addnn (eqn_double q 1) => /eqP ->.\nQed.\n\nLemma square_plus16_square n m: \n  (n ^2 + 4^2 == m ^2) = (n==0) && (m==4)||(n==3)&&(m==5).\nProof.\napply/idP/orP; last by case => /andP [/eqP -> /eqP ->] //.\ncase:(ltnP n m); last first. \n  move => cap; have /gtn_eqF -> //: m^2 < n ^ 2 + 4^2.\n  by apply: (@leq_ltn_trans (n^2)); rewrite ? leq_sqr // -addSnnS leq_addr.\nmove => lnm /eqP h; move: lnm; rewrite leq_eqVlt; case/orP => lmn.\n  by move:(congr1 odd h); rewrite -(eqP lmn) oddD !odd_sqr /=; case: odd.\nmove:lmn; rewrite -(leq_sqr) - addn2 -h sqrnD - addnA leq_add2l.\nrewrite - [4 ^ 2]/( 2 ^ 2  + 4 * 3) leq_add2l (mulnC n) mulnA leq_pmul2l //.\nrewrite leq_eqVlt; case/orP => n3; [right | left].\n  by move/eqP: h; rewrite (eqP n3) (eqn_sqr 5) eq_sym.\ncase: (Fermat2_bound h); rewrite leq_eqVlt eq_sym -leq_sqr -h.\nby rewrite -[5^2]/(3^2+4^2) leq_add2r leq_sqr -ltnS ltnNge n3 orbF => -> <-. \nQed.\n\n\nFact square_plus16_square_alt n m: (n ^2 + 4^2 = m ^2) -> n = 0 \\/ n = 3.\nProof.\ncase /pythagore_tripleB; [ by case => h _; left | by case | ].\nhave H1 a b:  2 == a * b -> (a==1) || (a == 2).\n  by case: a => [|[|[| a]]] => //; rewrite mulnC;case: b.\nhave H a b:  odd b -> 2 == a * b -> (a == 2).\n  move => ob h; case/orP: (H1 _ _ h);last by move => ->. \n  by move => /eqP a1; move:(f_equal odd (eqP h)); rewrite a1 mul1n ob.\nmove => [p [q[ha hb hc hd]]]; case; case => ea eb ec.\n  move/eqP: eb; rewrite -{1}[4]/(2.*2) -doubleMr eqn_double => ed.\n  case opq: (odd (p * q)). \n     move: opq hd; rewrite oddM; case: odd; case: odd => //=.\n  move: ed; rewrite -{1} [2]/(1.*2) (evenE opq) -doubleMr eqn_double  eq_sym.\n  rewrite muln_eq1 -(eqn_double _./2) -(evenE opq) => /andP [g1 g2].\n  rewrite eq_sym in g2;case/orP: (H1 _ _ g2) => /eqP pv; rewrite pv in g2.\n    by rewrite mul1n in g2; move: hb; rewrite -(eqP g2) pv.\n  by right;move: g2; rewrite ea (eqP g1) mul1n pv mul2n eqn_double => /eqP <-.\nhave hb':= (ltnW hb).\nhave od: odd (p^2 - q^2).\n   by rewrite oddB ?leq_sqr // !odd_sqr  -negb_eqb.\nhave g4: gcdn n 4 = 4.\n  move: (f_equal odd ea); rewrite oddM od /= andbT => /esym neg.\n  move: ea;rewrite (evenE neg) -[4]/(2.*2) -doubleMl => /eqP.\n  by rewrite eqn_double => h; rewrite (eqP (H _ _ od h)).\nmove /eqP:ea; rewrite g4 -{1} (muln1 4) eqn_pmul2l // eb => /eqP h.\nhave: q^2  + 1 = p ^2 by rewrite {2} h subnKC // leq_sqr.\nby move/ square_plus1_square => ->; left; rewrite !muln0.\nQed.\n\nLemma square_plus_square_3square x y z: x^2 + y^2 = 3 * z ^2 -> z = 0.\nProof.\nwlog: x y/ y <= x.\n  by move => H; case/orP: (leq_total y x); [| rewrite addnC]; apply:H. \ncase: (posnP x) => xp. \n  rewrite xp leqn0 => /eqP -> /eqP; rewrite eq_sym muln_eq0 expn_eq0 /=.\n  by rewrite andbT => /eqP.\ncase (gcd_aux y xp); set a := _ %/ _; set b := _ %/ _.\nmove => {3} -> {3} ->.\nrewrite !expnMn -mulnDl => cp _ eqa. \ncase: (posnP z) => //; rewrite -sqrn_gt0 => zp.\nhave /(logn_Gauss ((gcdn x y) ^2)): coprime 3 (a ^ 2 + b ^ 2).\n  move: (dvdn_gcd 3 a b).\n  rewrite (eqP cp) /= /dvdn /coprime -gcdn_modr -modnDm - modnMm - (modnMm b).\n  move: (@ltn_pmod a 3 isT); move: (@ltn_pmod b 3 isT).\n  case:(a %% 3) => [|[|[]]];case:(b %% 3) => [|[|[]]] => //. \nrewrite eqa lognM // logn_prime // !lognX => H.\nby move: (f_equal odd H); rewrite !mul2n add1n /= !odd_double.\nQed.\n\n\n\n(* Functions on lists *) \nLemma seq2_ind (T1 T2 : Type) (P : seq T1 -> seq T2 -> Prop) :\n   P [::] [::] ->\n   (forall x1 x2 s1 s2, P s1 s2 -> P (x1 :: s1) (x2 :: s2)) ->\n   forall s1 s2, size s1 == size s2 -> P s1 s2.\nProof.\nmove=> Pnil Pcons; elim=> [|x1 l1 IH1]; case=> // x2 l2 /= H; auto.\nQed.\n\nLemma rev_inj  (T: Type) : injective (@rev T).\nProof. by apply: inv_inj; apply: revK. Qed.\n\nLemma all_rev (T: eqType) P (l: seq T) : all P (rev l) = all P l.\nProof. \nby apply /allP/allP => H x xi; apply:H; [rewrite mem_rev |rewrite - mem_rev].\nQed.\n\nLemma head_rev (T: Type) (a:T) l: head a (rev l) = last a l.\nProof.\nby elim: l a => // a l H b; rewrite rev_cons - cats1 /= -H;case: rev. \nQed.\n\nLemma split_rev (T: Type) (a:T) l: \n  rev (a :: l) = last a l :: behead (rev (a :: l)). \nProof. by rewrite rev_cons {1} headI head_rev. Qed.\n\nLemma rem_rcons1 a b l: a < b -> rem a (rcons l b) = rcons (rem a l) b.\nProof.\nmove => h; elim:l => /=; first by rewrite gtn_eqF.\nby move => x l H /=; case:(x==a) => //; rewrite H rcons_cons.\nQed.\n\nLemma rem_rcons2 (T:eqType) (a: T) l: a \\notin l -> rem a (rcons l a) = l.\nProof.\nelim: l => [| b l H]; rewrite /= ?eqxx //  inE /= eq_sym.\nby case: (b==a) => //=; move/H => ->.\nQed.\n\nLemma rem_rcons2_inv (T:eqType) (a: T) l (s := take (index a l) l):\n  rem a (rcons l a) = l -> a\\notin s /\\ l = s ++ nseq (size l - (index a l)) a.\nProof.\nrewrite /s{s} => h; split.\n  elim:l {h} => // b l Hr /=;case: ifP => //.\n  by rewrite eq_sym in_cons negb_or Hr => ->.\nelim:l h => // b l IHl /=; case: eqP.\n  move => ->; rewrite subn0 cat0s; clear IHl b; elim:l => // b l Hr /= [->].\n  by move/Hr ->.\nby move => nba [] /IHl; rewrite subSS cat_cons => <-.\nQed.  \n\nDefinition succ_seq l :=  [seq i.+1 | i <- l].\nDefinition pred_seq l :=  [seq i.-1 | i <- l].\n\nLemma seq_prednK l: all (leq 1) l ->  l = succ_seq (pred_seq l).\nProof. \nby elim:l => // a l H /= /andP [] /prednK -> /H <-.\nQed.\n\nLemma iota_S a n: iota a.+1 n = succ_seq (iota a n).\nProof. by elim: n a => // k H m /=; rewrite H. Qed. \n\nLemma iota_Sr i n: iota i n.+1 = rcons (iota i n)  (i+n).\nProof. by elim: n i => [i| n H i]; rewrite ? addn0 // /= - addSnnS - H. Qed.\n\nLemma last_iota a b c: last c (iota a b.+1) = a + b.\nProof. by rewrite iota_Sr last_rcons. Qed.\n\nLemma last_mkseq (T : Type) (f: nat -> T) a b c: \n  last c [seq f i | i <- iota a b.+1] = f (a + b).\nProof. by rewrite iota_Sr map_rcons last_rcons. Qed.\n\nLemma mkseq_succ (T: Type) (f: nat -> T) n: \n  mkseq f n.+1 = rcons (mkseq f n) (f n).\nProof.\nrewrite /mkseq - {3} (add0n n).\nby elim: n (0) => [n |n H m]; rewrite ? addn0 //= addnS - addSn - H.\nQed.\n\n\n(** *** Copy of the std lib   *)\nFixpoint fib_rec n :=\n  if n is n1.+1 then\n    if n1 is n2.+1 then fib_rec n1 + fib_rec n2\n    else 1\n  else 0.\n\nDefinition fib := nosimpl fib_rec.\n\nLemma fibE : fib = fib_rec.\nProof. by []. Qed.\n\nLemma fib0 : fib 0 = 0.\nProof. by []. Qed.\n\nLemma fib1 : fib 1 = 1.\nProof. by []. Qed.\n\nLemma fibSS n: fib n.+2 = fib n.+1 + fib n.\nProof. by []. Qed.\n\n\nLemma fib_gt0 m: 0 < m -> 0 < fib m.\nProof. by elim: m=> [|[|m] IH _] //; rewrite fibSS addn_gt0 IH. Qed.\n\nLemma fib_smonotone m n: 1 < m < n -> fib m < fib n.\nProof.\nelim: n=> [|[|n] IH]; first by rewrite andbF.\n  by case: (ltngtP 1 m).\nrewrite fibSS andbC; case/andP; rewrite leq_eqVlt; case/orP.\n  by rewrite eqSS; move/eqP=> -> H1m; rewrite -addn1 leq_add2l fib_gt0.\nby move=> H1m H2m; apply: ltn_addr; apply: IH; rewrite H2m.\nQed.\n\nLemma fib_monotone m n: m <= n -> fib m <= fib n.\nProof.\nelim: n=> [|[|n] IH]; first by case: m.\n  by case: m{IH}=> [|[]].\nrewrite fibSS leq_eqVlt; case/orP=>[|Hm]; first by move/eqP->.\napply: (leq_trans (IH Hm)); exact: leq_addr.\nQed.\n\nLemma fib_eq1 n: (fib n == 1) = ((n == 1) || (n == 2)).\nProof.\ncase:n => [|[|[|n]]] //;case: eqP => // Hm; have: 1 < 2 < n.+3 by [].\nby move/fib_smonotone; rewrite Hm.\nQed.\n\n\nLemma fib_eq m n:\n  (fib m == fib n) = [|| m == n, (m == 1) && (n == 2) | (m == 2) && (n == 1)].\nProof.\nwlog: m n/ m <= n=> [HH|].\n  case/orP: (leq_total m n)=> Hm; first by exact: HH.\n  by rewrite eq_sym HH // eq_sym ![(_ == 1) && _]andbC [(_ && _) || _] orbC.\nrewrite leq_eqVlt; case/orP; first by move/eqP->; rewrite !eqxx.\ncase: m=> [|[|m]] Hm. \n- by rewrite (ltn_eqF (fib_gt0 Hm)) (ltn_eqF Hm).\n- by rewrite eq_sym fib_eq1 orbF eq_sym. \nhave: 1 < m.+2 < n by [].\nmove/fib_smonotone =>/ltn_eqF ->.\nby case: n Hm=> [|[|n]] // /ltn_eqF -> //; rewrite andbF. \nQed.\n\nLemma fib_add m n:\n  m != 0 ->  fib (m + n) = fib m.-1 * fib n + fib m * fib n.+1.\nProof.\nelim: m {-2}m (leqnn m) n=> [[] // _ |m IH m1].\nrewrite leq_eqVlt; case/orP=> [|Hm]; last first.\n  by apply: IH; rewrite -ltnS.\nmove/eqP->; case: m IH=> [|[|m]] IH n _.\n- by rewrite mul1n.\n- by rewrite add2n fibSS addnC !mul1n.\n- rewrite 2!addSn fibSS -addSn !IH // addnA [fib _ * _ + _ + _]addnAC.\nby rewrite -addnA -!mulnDl -!fibSS.\nQed.\n\nLemma fib_sub m n: n <= m ->\n   fib (m - n) = if odd n then fib m.+1 * fib n - fib m * fib n.+1\n                 else fib m * fib n.+1 - fib m.+1 * fib n.\nProof.\nelim: m n => [|m IH]; first by case. \ncase=> [|n Hn]; first by rewrite muln0 muln1 !subn0.  \nby rewrite subSS IH //=;case:odd; rewrite !fibSS !mulnDr !mulnDl !subnDA !addKn.\nQed.\n\nLemma fib_doubleS n: fib (n.*2.+1) = fib n.+1 ^ 2 + fib n ^ 2.\nProof. by rewrite -addnn -addSn fib_add // addnC. Qed.\n\nTheorem dvdn_fib m n: m %| n -> fib m %| fib n.\nProof.\ncase/dvdnP=> n1 ->.\nelim: {n}n1 m=> [|m IH] // [|n]; first by rewrite muln0.\nby rewrite mulSn fib_add // dvdn_add //; [apply dvdn_mull | apply dvdn_mulr].\nQed.\n\n\nLemma fib_prime p: p != 4 -> prime (fib p) -> prime p.\nProof.\nmove=> Dp4 Pp.\napply/primeP; split; first by case: (p) Pp  => [|[]].\nmove=> d; case/dvdnP=> k Hp.\ncase/primeP: (Pp); rewrite Hp => _ Hf.\ncase/orP: (Hf _ (dvdn_fib (dvdn_mulr d (dvdnn k)))).\n  rewrite fib_eq1; case/orP; first by move/eqP->; rewrite mul1n eqxx orbT.\n  move/eqP=> Hk.\n  case/orP: (Hf _ (dvdn_fib (dvdn_mull k (dvdnn d)))).\n    rewrite fib_eq1; case/orP; first by move->.\n    by move/eqP=>Hd; case/negP: Dp4; rewrite Hp Hd Hk.\n  rewrite fib_eq; case/or3P; first by move/eqP<-; rewrite eqxx orbT.\n    by case/andP=>->.\n  by rewrite Hk; case: (d)=> [|[|[|]]].\nrewrite fib_eq; case/or3P; last by case/andP;move/eqP->; case: (d)=> [|[|]].\n  rewrite -{1}[k]muln1; rewrite eqn_mul2l; case/orP; move/eqP=> HH.\n    by move: Pp; rewrite Hp HH.\n  by rewrite -HH eqxx.\nby case/andP; move/eqP->; rewrite mul1n eqxx orbT.\nQed.\n\n\nLemma fib_sum n: \\sum_(i < n) fib i = (fib n.+1).-1.\nProof.\nelim:n => [|n IH]; first by rewrite big_ord0.\nby rewrite big_ord_recr /= IH fibSS; case: fib (fib_gt0 (ltn0Sn n)). \nQed.\n\nLemma fib_sum_even n: \\sum_(i < n) fib i.*2 = (fib n.*2.-1).-1.\nProof.\nelim:n => [|n IH]; first by rewrite big_ord0.\nrewrite big_ord_recr IH; case: (n)=> [|n1] //.\nrewrite (fibSS (n1.*2.+1)) addnC -[(n1.+1).*2.-1]/n1.*2.+1.\nby case: fib (fib_gt0 (ltn0Sn ((n1.*2)))).\nQed.\n\nLemma fib_sum_odd n: \\sum_(i < n) fib i.*2.+1 = fib n.*2.\nProof.\nelim:n=> [|n IH]; first by rewrite big_ord0.\nby rewrite big_ord_recr IH /= addnC -fibSS.\nQed.\n\nLemma fib_sum_square n: \\sum_(i < n) (fib i)^2 = fib n * fib n.-1.\nProof.\nelim:n=> [|n IH]; first by rewrite big_ord0.\nby rewrite big_ord_recr /= IH -mulnDr addnC mulnC; case: (n). \nQed.\n\nLemma bin_sum_diag n: \\sum_(i < n) 'C(n.-1-i,i) = fib n.\nProof.\nelim: n {-2}n (leqnn n)=> [[] // _ |n IH n1]; first by rewrite big_ord0.\nrewrite leq_eqVlt; case/orP=> [|Hn]; last by apply: IH; rewrite -ltnS.\nmove/eqP->; case: n IH=> [|[|n]] IH.\n- by rewrite big_ord_recr big_ord0.\n- by rewrite !big_ord_recr big_ord0.\nrewrite fibSS -!IH // big_ord_recl bin0 big_ord_recr /= subnn bin0n addn0.\nset ss := \\sum_(i < _) _.\nrewrite big_ord_recl bin0 -addnA -big_split; congr (_ + _).\nby apply eq_bigr=> i _ /=; rewrite -binS subSn //; case: i.\nQed.\n\n(** lucas *)\n\nFixpoint lucas_rec n :=\n  if n is n1.+1 then\n    if n1 is n2.+1 then lucas_rec n1 + lucas_rec n2\n    else 1\n  else 2. \n\nDefinition lucas := nosimpl lucas_rec.\n\nLemma lucasE : lucas = lucas_rec.\nProof. by []. Qed.\n\nLemma lucas0 : lucas 0 = 2.\nProof. by []. Qed.\n\nLemma lucas1 : lucas 1 = 1.\nProof. by []. Qed.\n\nLemma lucasSS n: lucas n.+2 = lucas n.+1 + lucas n.\nProof. by []. Qed.\n\n\nLemma lucas_fib n: n != 0 -> lucas n = fib n.+1 + fib n.-1.\nProof.\nelim: n {-2}n (leqnn n)=> [ [] // |n IH n1].\nrewrite leq_eqVlt; case/orP=> [|Hn1]; last  by apply: IH; rewrite -ltnS.\nmove/eqP->; case: n IH=> [|[|n] IH _] //.\nby rewrite lucasSS !IH // addnCA -addnA -fibSS addnC.\nQed.\n\nLemma lucas_gt0 m: 0 < lucas m.\nProof.\nby elim:m=> [|[|m] IH] //; rewrite lucasSS addn_gt0 IH.\nQed.\n\nLemma double_lucas n: 3 <= n -> (lucas n).*2 = fib (n.+3) + fib (n-3).\nProof.\ncase:n => [|[|[|n]]] // _ ; rewrite !subSS subn0.\nrewrite fibSS fibSS -addnA addnAC addnA addnn lucas_fib //= doubleD - addnA.\nby rewrite  (addnC (fib n)) (fibSS n.+1) - addnA -fibSS addnn.\nQed.\n\nLemma fib_double_lucas n: fib (n.*2) = fib n * lucas n.\nProof.\ncase:n=> [|n]; rewrite // -addnn fib_add // lucas_fib // mulnDr addnC /=.\nby rewrite (mulnC (fib n)(fib n.+1)).\nQed.\n\n(** Stuff not in the library *)\n\nDefinition like_fib F := (forall n, F n.+2 = F n.+1 + F n).\n\nLemma fib_like_fib: like_fib fib.\nProof. by move => n; rewrite fibSS. Qed.\n\nLemma lucas_like_fib: like_fib lucas.\nProof. by move => n; rewrite lucasSS. Qed. \n\nLemma like_fib_eq F F': \n  like_fib F -> like_fib F' -> F 0 = F' 0 -> F 1 = F' 1 -> F =1 F'.\nProof.\nmove => ha hb hc hd n.\nsuff:  F n = F' n /\\  F n.+1 = F' n.+1 by case.\nby elim:n => // n [he hf]; split => //; rewrite ha hb he hf.\nQed.\n\nLemma is_fib F: like_fib F -> F 0 = 0 -> F 1 = 1 -> F =1 fib.\nProof. by move => sa sb sc; apply:like_fib_eq. Qed.\n\nLemma like_fib_mul F c: like_fib F -> like_fib (fun n => c * F n).\nProof. by move => h n; rewrite -mulnDr h. Qed.\n\nLemma like_fib_add F F': like_fib F -> like_fib F' -> \n like_fib (fun n => F n + F' n).\nProof. by move => h1 h2 n; rewrite addnACA - h1 - h2. Qed.\n\nLemma like_fib_shift F m: like_fib F -> like_fib(fun n => F (n + m)).\nProof. by move => h n; rewrite !addSn h. Qed.\n\nLemma like_fib_succ F: like_fib F -> like_fib(fun n => F (n.+1)).\nProof. by move => h n. Qed.\n\n\nLemma like_fibE F: like_fib F -> \n   forall n, F n.+1 = (F 0) * (fib n) + (F 1) * (fib n.+1).\nProof.\nmove => H; apply:like_fib_eq => //=.\n- by apply: like_fib_add; apply: like_fib_mul.\n- by rewrite muln0 muln1.\n- by rewrite H !muln1 addnC.\nQed.\n\nLemma like_fib_shiftE F m n: like_fib F ->\n  F (n+m).+1 = F (n.+1)* fib m.+1 + F n * fib m.\nProof.\nmove => ha. \nby rewrite -addnS addnC (like_fibE(like_fib_shift n ha) m) add0n add1n addnC.\nQed.\n\n\nLemma lucasS n: lucas n.+1 = fib n.+1 + (fib n).*2.\nProof. by rewrite (like_fibE lucas_like_fib) addnC mul1n mul2n. Qed.\n\nLemma lucas_add m n: lucas (n+m).+1 = lucas (n.+1)* fib m.+1 + lucas n * fib m.\nProof. by rewrite (like_fib_shiftE _ _ lucas_like_fib). Qed.\n\nLemma like_fib_lucas F: like_fib F -> F 0 <= 2 * F 1 -> F 1 <=  3 * (F 0) ->\n   forall n, 5 * F n = \n     (3* (F 0) - F 1) * (lucas n) + (2* (F 1) - F 0)* (lucas n.+1).\nProof.\nhave Ha:= lucas_like_fib.\nmove => h la lb. \nmove: (subnK la) (subnK lb); set a := _ - _; set b := _ - _ => ea eb.\napply:like_fib_eq. \n+ exact: like_fib_mul.\n+ by apply: like_fib_add; apply: like_fib_mul.\n+ apply/eqP; rewrite lucas0 lucas1 muln1 -(eqn_add2l (2 * F 1)) (mulnC  b 2).\n  by rewrite addnA - mulnDr (addnC _ b) eb - ea - addnA addnC  -mulSn mulnA.\n+ apply/eqP;rewrite lucas1 muln1 -[lucas 2]/3  -(eqn_add2r (3 * F 0)).\n  by rewrite (mulnC a) - addnA - mulnDr ea mulnA (mulSn 5) addnA eb addnC.\nQed.\n\nLemma lucas_fib2 n: 5 * fib n.+2 = 3 * lucas n.+1 + lucas n.\nProof.\nby rewrite addnC (like_fib_lucas (F:= fun n => fib n.+2)) // mul1n.\nQed.\n\nLemma lucas_fib3 n: 5 * fib n.+1 = lucas n.+1 + (lucas n).*2.\nProof.\nby rewrite (like_fib_lucas (F:= fun n => fib n.+1)) // addnC mul1n mul2n.\nQed.\n\nLemma lucas5S n: lucas (n+5) = 5 * lucas n.+1 + 3 * lucas n.\nProof. by rewrite addnS lucas_add mulnC (mulnC (lucas n)). Qed.\n\nLemma fib3S n: fib n.+3 = (fib n.+1).*2 + (fib n).\nProof. by rewrite fibSS fibSS addnAC addnn. Qed.\n\nLemma lucas3S n: lucas n.+3 = (lucas n.+1).*2 + (lucas n).\nProof. by rewrite !lucasSS addnAC addnn. Qed.\n\nLemma fib4S n: fib n.+4 = 3*(fib n.+1) + (fib n).*2.\nProof. by rewrite fib3S fibSS doubleD addnAC - mul2n -mulSnr. Qed.\n\nLemma fib_square_succ n: (fib n.+2)^2 = (fib n.+1)^2 + (fib n)*(fib n.+3).\nProof.\nrewrite fibSS sqrnD mulnA mulnC -(mulnn (fib n)) -addnA -mulnDr.\nby rewrite fibSS fibSS addnAC addnn mul2n (addnC (fib n)).\nQed.\n\nLemma fib_double n: fib ((n.+1).*2) = (fib n.+1) *((fib n).*2 + fib (n.+1)).\nProof. by rewrite fib_double_lucas lucasS addnC. Qed.\n\n\nLemma fib_square_n3_n n: fib n.+3 ^ 2 + fib n ^ 2 = (fib (n.*2.+3)).*2.\nProof.\napply/eqP.\nrewrite -(eqn_add2l (fib (n.+1).*2.+1)) {1} fib_doubleS addnAC addnA.\nrewrite (addnC (fib n.+2 ^ 2)) -fib_doubleS -addnA (addnC (fib n ^2)). \nby rewrite - fib_doubleS !doubleS fib3S - addnA - fibSS addnC.\nQed.\n\nLemma lucas_square n:\n  (lucas n)^2 = (if (odd n) then subn else addn) (lucas (n.*2)) 2.\nProof.\ncase:n => // n.\nset b :=  fib n.+1 ^ 2.\nrewrite lucas_fib //= lucas_fib // !fib_doubleS - addnA sqrnD. \nrewrite (addnA b) addnn (addnC b.*2) addnA mul2n.\nset a := fib n.+2 * fib n;  set c := fib n.+2 ^ 2 + fib n ^ 2.\nmove:(fib_sub (leqnSn n)); rewrite mulnn (subSn (leqnn n)) subnn -/b -/a => h.\nhave: (if odd n then a > b else b > a).  \n  by case : odd h;  rewrite - subn_gt0 => <-.\nrewrite -[2]/((fib 1).*2) h; case: odd  => /= /ltnW/subnK {1} <-.\n  by rewrite - addnA - doubleD [in (_ + _).*2] addnC.\nby rewrite doubleD addnCA addKn.\nQed.\n\n  \nLemma like_fib_bis F: like_fib F -> F 0 <= 2 * F 1 -> \n   forall n, 2 * F n = (F 0) * (lucas n) + (2* (F 1) - F 0)* (fib n).\nProof.\nhave Ha:= lucas_like_fib.\nmove => h la. \napply:like_fib_eq.\n+ by apply: like_fib_mul.\n+ by apply: like_fib_add; apply: like_fib_mul.\n+ by rewrite mulnC muln0 addn0.\n+ by rewrite !muln1 subnKC.\nQed.\n\nLemma fib_pos n: fib (n.+1) = (fib (n.+1)).-1.+1.\nProof. by rewrite prednK // fib_gt0 //. Qed.\n\nLemma fib_eq0 n: (fib n == 0) = (n == 0). \nProof. by case: n => [|n]=> //=; rewrite eqn0Ngt fib_gt0. Qed.\n\nLemma fib_gen n: n <= fib n.+1.\nProof.\ncase:n => //; elim => // n IH.\nby move: (leq_add IH (fib_gt0 (isT:0<n.+1))); rewrite addn1.\nQed.\n\nLemma lucas_gen n: n <= lucas n.\nProof.\ncase:n => //; elim => // n IH.\nby move: (leq_add IH (lucas_gt0 n)); rewrite addn1 - lucasSS.\nQed.\n\n\nLemma fib_monotone_bis a b: fib a < fib b -> a < b.\nProof. by rewrite ltnNge; case: (ltnP a b) => // /fib_monotone ->. Qed.\n\nLemma fib_smonotone_bis a b: a < b -> fib a.+2 < fib b.+2.\nProof. by move => h; apply:fib_smonotone; rewrite !ltnS h. Qed.\n\nLemma fib_sum_bound a b n: a <=  fib n.+1 -> b <=  fib n ->\n   a + b = fib n.+2 -> (a = fib n.+1) /\\ (b = fib n).\nProof.\nmove => sa sb /esym /eqP; rewrite fibSS -(subnK sa) -(subnK sb) addnACA.\nby rewrite -{2}(add0n (a+b)) eqn_add2r addn_eq0 => /andP [] /eqP -> /eqP ->. \nQed.\n\nLemma fib_ge2_alt n: fib n.+3 = (fib n.+3).-2.+2.\nProof.\nby rewrite - (subnK(fib_gen (n.+2))) 2!addnS.\nQed.\n\nLemma fib_partition a b x:\n   fib a <= x < fib a.+1 -> fib b <= x < fib b.+1  -> a = b.\nProof.\nmove => /andP[ha hb] /andP[hc hd]; apply /eqP; rewrite eqn_leq.\nmove: (leq_ltn_trans ha hd) => /fib_monotone_bis; rewrite ltnS => ->.\nby move: (leq_ltn_trans hc hb) => /fib_monotone_bis; rewrite ltnS => ->.\nQed.\n\nLemma lucas_smonotone m n: 0 < m < n -> lucas m < lucas n.\nProof.\nelim: n=> [|[|n] IH]; first by rewrite andbF.\n  by rewrite ltnS ltnNge; case:leq.\nrewrite lucasSS andbC; case/andP; rewrite leq_eqVlt; case/orP.\n  by rewrite eqSS; move/eqP=> -> H1m; rewrite -addn1 leq_add // lucas_gt0.\nby move=> H1m H2m; apply: ltn_addr; apply: IH; rewrite // H2m.\nQed.\n\nLemma lucas_monotone m n: 0 < m <= n -> lucas m <= lucas n.\nProof.\nby rewrite (leq_eqVlt m); case: eqP =>[-> // | _  /lucas_smonotone /ltnW].  \nQed.\n\nLemma lucas_injective: injective lucas.\nProof.\nmove => m n; wlog: m n / m < n.\n   move => h;case: (ltngtP m n) => //; first by apply:h.\n   by move => ha hb; symmetry;apply: h.\nmove => lt1;case:(posnP m) => mp sv; last first.\n  by move/andP:(conj mp lt1) => /lucas_smonotone; rewrite sv ltnn.\nmove: lt1 sv; rewrite mp lucas0; case: n => [|[| n]] // _ ha.\nby move/lucas_monotone: (isT:0 < 2 <= n.+2); rewrite - ha.\nQed.\n\n\nLemma lucas_injective_bis a b: (lucas a == lucas b) = (a== b).\nProof. exact: (inj_eq lucas_injective). Qed.\n\nLemma lucas_smonotoneE m n: \n  lucas m < lucas n = [|| (0< m < n), (m==1) && (n== 0)| (m == 0) && (2<= n )].\nProof.\ncase nz: (n==0).\n   rewrite (eqP nz) /= leqn0; case: m => [|[|m]] //. \n   by rewrite ltnNge lucasSS (leq_add (lucas_gt0 m.+1) (lucas_gt0 m)).\ncase mz: (m==0).\n   rewrite (eqP mz) /= lucas0; move: nz; case: n => [|[| n]] // _.\n   by rewrite  -[3]/(lucas 2) lucas_monotone.\nrewrite andbF /= orbF; case: (ltnP m n) => h. \n  by rewrite lucas_smonotone ?h lt0n mz.\nby rewrite ltnNge lucas_monotone lt0n ?mz // nz h.\nQed.\n\nLemma lucas_monotoneE m n: \n  lucas m <= lucas n = \n    [|| m== n, 0< m < n, (m==1) && (n== 0)| (m == 0) && (2<= n )].\nProof. by rewrite leq_eqVlt lucas_injective_bis lucas_smonotoneE. Qed.\n\nLemma lucas_monotone2 n p: p <= n -> lucas (n - p) <= lucas (n + p).\nProof.\nmove/subnK => {2} <-; rewrite -addnA addnn lucas_monotoneE.\ncase pz:(p==0); first by rewrite (eqP pz) addn0 eqxx.\nhave p2: 2 <= p.*2 by rewrite (leq_double 1 p) lt0n pz.\nrewrite (ltn_paddr _ (ltnW p2)) (leq_trans p2 (leq_addl _ p.*2)) lt0n !andbT.\nby case np: (n-p==0); rewrite ? orbT.\nQed.\n\nLemma lucas_ge2 n: n !=1 -> lucas n = (lucas n).-2.+2.\nProof.\ncase:n => //; case => // n _.  \nby rewrite -(subnK (lucas_gen n.+2)) 2! addnS.\nQed.                        \n\nLemma lucas_ge2d n: 1 < lucas (n.*2).\nProof. by rewrite lucas_ge2 => //; case:n. Qed.\n\nLemma lucas_powge2 n: 1 < lucas (2 ^ n.+1) ^ 2.\nProof. by rewrite -{1}[1]/(1^2) ltn_sqr expn2S lucas_ge2d. Qed.\n\nLemma lucas_square' n: \n  lucas (n.*2) =  (if (odd n) then addn else subn) ( (lucas n)^2) 2.\nProof.\nby rewrite lucas_square; case: odd; rewrite ? addnK // subnK // lucas_ge2d.\nQed.\n\nLemma lucas_pow2_odd n: odd (lucas (2^n)).\nProof.\nelim: n => // n on; rewrite expn2S lucas_square'. case: n on=> // n.\nby rewrite {2} expn2S odd_double oddB ?lucas_powge2 // odd_sqr => ->.\nQed.\n\nLemma lucas_pow2_mod4 n: lucas (2^(n.+1)) = 3 %[mod 4].\nProof.\ncase: n => // n; rewrite expn2S lucas_square' {1} expn2S odd_double.\nhave aux:= (square_odd_mod4(lucas_pow2_odd n.+1)).\nby apply/eqP; rewrite -(eqn_modDr 2) subnK ?lucas_powge2 // aux.\nQed.\n\nLemma coprimeSn_fib n: coprime (fib n) (fib n.+1) .\nProof. by elim:n =>// h; rewrite /coprime fibSS  gcdnDl gcdnC. Qed.\n\nLemma gcd_fib n m: gcdn (fib n) (fib m) = fib (gcdn n m).\nProof.\nmove: (leq_maxl n m) (leq_maxr n m);move:(maxn _ _)=> k. \nelim: k n m; [ by case; [case  |] | move => max Hrec n m le1 le2 ].\nwlog lmn: n m le1 le2 / n < m.\n  move => H; case: (ltngtP n m) => aux; first by apply: H. \n    by rewrite gcdnC (gcdnC n); apply: H.\n  by rewrite aux !gcdnn.\ncase (posnP n); first by move => ->; rewrite!  gcd0n.\nmove:(subnK (ltnW lmn));set r := m - n => eq1 np.\nmove:(lmn); rewrite - subn_gt0 lt0n => rnz.\nmove:(ltn_sub2l (ltn_trans np lmn) np); rewrite subn0 => ha.\nrewrite -eq1 gcdnDr fib_add // gcdnMDl (Gauss_gcdl _ (coprimeSn_fib n)). \nby rewrite Hrec // - ltnS; apply: (leq_trans _ le2).\nQed.\n\nLemma mod3_small n: (n %% 3)  < 3.\nProof. by rewrite ltn_pmod. Qed.\n\nLemma fib_is_even_mod3 n: odd (fib n)  =  (n %%3 !=0). \nProof.\nmove: (gcd_fib n 3); rewrite - (gcdn_modl n) gcd_n2. \nmove:(mod3_small n);case:(n %% 3) => [|[|[| k]]] //= _; case: odd => //.\nQed.\n\nLemma lucas_is_even_mod3 n: odd (lucas n)  =  (n %%3 !=0). \nProof.\nrewrite - fib_is_even_mod3; case:n => // n.\nby rewrite lucasS oddD odd_double addbF.\nQed.\n\nLemma gcd_lucas_fib1 n: gcdn (lucas n.+1) (fib n.+1) = fib (gcdn n.+1 3).\nProof.\nhave h: coprime (fib n.+1) (fib n) by rewrite coprime_sym coprimeSn_fib.\nby rewrite gcdnC lucasS gcdnDl - muln2 Gauss_gcdr //(gcd_fib _ 3).\nQed.\n\nLemma gcd_lucas_fib2 n:  (n %%3 ==0) -> gcdn (lucas n) (fib n) = 2.\nProof.\nby case: n => // n H; rewrite gcd_lucas_fib1 - (gcdn_modl) (eqP H).\nQed.\n\nLemma gcd_lucas_fib3 n: (n %%3 !=0) -> coprime (lucas n) (fib n).\nProof.\ncase: n => // n H; rewrite /coprime gcd_lucas_fib1 - (gcdn_modl).\nby move: (mod3_small n.+1) H; case: (n.+1 %% 3) => [|[ | [| ]]].\nQed.\n\nLemma fib_mod3 n: 3 %| (fib n) =  (4 %| n).\nProof.\npose p n := (3 %| fib n) = (4 %| n).\nsuff: [/\\ p n, p n.+1, p n.+2 & p n.+3] by case.\nelim: n => // n [ha hb hc hd]; split => //.\nmove: ha;rewrite /p fib4S - (addn4 n) /dvdn  modnDr mulnC modnMDl.\nmove => <-; rewrite - addnn - modnDm.\nby move: (mod3_small (fib n)); case: (fib n %% 3) => [|[|[|]]].\nQed.\n\nLemma lucas_mod3 n: 3 %| (lucas n) = (n== 2 %[mod 4]).\nProof.\ncase:n => [| [| n ]] //.\nrewrite -{3} (add0n 2) - {2} (addn2 n) eqn_modDr - (add1n n) lucas_add /dvdn.\nrewrite mul1n mulnC modnMDl; exact:fib_mod3.\nQed.\n\nLemma sum_fib_pascal n:\n  \\sum_(i<n.+1) 'C(n,i)* fib i = fib(n.*2) /\\ \n  \\sum_(i<n.+1) 'C(n,i)* fib i.+1 = fib(n.*2.+1).\nProof.\nelim:n; first by rewrite !big_ord_recr  !big_ord0 /= //.\nmove =>n [He Ho]; split.\n  rewrite big_ord_recl muln0 add0n doubleS fibSS - Ho.\n  have ->: fib n.*2 = \\sum_(i < n.+1) 'C(n, i.+1) * fib i.+1.\n    by rewrite -He big_ord_recl big_ord_recr muln0 add0n bin_small //= addn0.\n  by rewrite addnC -big_split; apply:eq_bigr=> i _ /=; rewrite - mulnDl/= binS.\nrewrite doubleS fibSS fibSS -Ho - He big_ord_recl bin0 muln1 /=.\ntransitivity (\\sum_(i < n.+1) 'C(n, i) * fib (bump 0 i).+1 \n   + \\sum_(i < n.+2) 'C(n, i) * fib i.+1).\n  rewrite (big_ord_recl (n.+1)) bin0 muln1 [RHS] addnC - addnA; congr addn.\n  by rewrite -big_split; apply:eq_bigr=> i _ /=; rewrite - mulnDl/= binS.\nrewrite (big_ord_recr (n.+1)) bin_small //= addn0;congr addn.\nby rewrite -big_split; apply:eq_bigr=> i _ /=; rewrite - mulnDr/= fibSS.\nQed.\n\nLemma fib_lt_lucas n: n != 0 -> fib n <= lucas n ?= iff (n==1).\nProof.\nmove => h; rewrite (lucas_fib h); move: h; case:n => // n _.\nrewrite fibSS /= - addnA addnn eqSS; apply/leqifP.\nby case:(posnP n) => np; rewrite ? np // ltn_paddr // double_gt0 fib_gt0.\nQed.\n\nLemma lucas_ge_2fib n: 2 <= n -> (fib n).*2 <= lucas n.\nProof. \ncase:n => [|[| n]] //_; rewrite lucas_fib // -addnn (fibSS n.+1).\nrewrite {2} fibSS addnA leq_add2l fib_monotone //=.\nQed.\n\nLemma lucas_lt_fib n: n != 0 -> lucas n <= fib n.+2 ?= iff (n==2).\nProof.\nmove => h; rewrite (lucas_fib h) fibSS; apply/leqifP. \nmove:h; case:n =>[ | [| [| n]]] //= _ ;rewrite ltn_add2l fib_smonotone //=.\nQed.\n\nLemma fib_mon1 n: 2 <= n -> 3* fib n <= 2 * fib n.+1.\nProof.\ncase: n => [|[|n _]]//; rewrite (fibSS n.+1)mulnDr mulSnr leq_add2l.\nby rewrite fibSS mul2n - addnn leq_add2l fib_monotone.\nQed.\n\nLemma lucas_mon1 n: 3 <= n -> 3* lucas n <= 2 * lucas n.+1.\nProof.\ncase: n => [|[|n ]]//;rewrite (lucasSS n.+1) mulnDr mulSnr leq_add2l !ltnS => h.\nrewrite lucasSS mul2n - addnn leq_add2l lucas_monotone ?h //=.\nQed.\n\nLemma fib_square_bound n: 2 <= n -> fib n.*2 < (fib n.+1)^2 < fib n.*2.+1.\nProof.\nmove => ha;rewrite fib_doubleS -{2}(addn0 ((fib n.+1)^2)) ltn_add2l sqrn_gt0.\nrewrite (fib_gt0 (ltnW ha)) andbT.\nrewrite -(ltn_add2l (fib n.+1 * (fib n).*2)) -mulnn -mulnDr. \nrewrite -fib_double doubleS fibSS ltn_add2r fib_doubleS -muln2 mulnA mulnC.\nhave hb: fib n < fib n.+1 by rewrite fib_smonotone // ha leqnn.\nby move/leqifP:(nat_Cauchy (fib n.+1) (fib n)); rewrite (gtn_eqF hb).\nQed.\n\nLemma lucas_square_bound n: 3 <= n -> \n  fib n.*2.+1 < (lucas n)^2 < fib n.*2.+2.\nProof.\nrewrite lucas_square.\nhave ha k:  2 < fib k .+1.+4 by rewrite (fib_smonotone_bis (a:=1)) //.\ncase: (odd_dichot n) => -> /=; rewrite odd_double /=.\n  case: (n./2) => //k _; rewrite !doubleS lucas_fib //;have hb:= (ha k.*2.*2).\n  rewrite -(subnK (ltnW hb)) addnA addnK ltn_paddr ? subn_gt0 //.\n  rewrite (fibSS (k.*2).*2.+4.+2) ltn_add2l (fibSS  (k.*2).*2.+4). \n  by apply /(leq_ltn_trans (leq_subr 2 _)) /ltn_paddr /fib_gt0.\ncase:(n./2) => [// | [// | m _]].\nrewrite !doubleS lucas_fib //; set k :=  (m.*2).*2.+4.+2.\nby rewrite - addnA {1} addn2 ltn_paddr //= (fibSS k.+2) (fibSS k) !ltn_add2l ha.\nQed.\n\nLemma fib_lt_exp n: 2 <= n -> fib n.+2 < 2^n.\nProof.\nmove/ subnK => <-.\npose p k := fib (k + 2).+2 < 2 ^ (k + 2).\nsuff: p (n-2) /\\ p (n-2).+1 by case.\nelim: {n} (n -2) => // k [ha hb]; split => //.\nmove:(leq_add hb (ltnW ha));rewrite /p !addSn - fibSS => sa.\napply: (leq_trans sa). \nby rewrite (expnS _ _.+1) mul2n -addnn leq_add2l leq_exp2l.\nQed.\n\n\n\n(* -- *)\n\nLemma fib_lucas1 j k: j <= k ->\n  lucas j * fib k =\n    (if (odd j) then subn else addn) (fib (k + j)) (fib (k - j)).\nProof.\ncase:j; first by rewrite /= addn0 subn0 mul2n addnn.\nmove => j;rewrite leq_eqVlt; case/orP => ljk.\n  rewrite (eqP ljk) mulnC - fib_double_lucas addnn subnn fib0.\n  by case: odd => //; rewrite ?subn0 ?addn0.\nhave hb: 0 < fib (k - j.+1) by rewrite fib_gt0 //subn_gt0.\nhave ha:=(fib_sub (ltnW ljk)).\nrewrite mulnC lucas_fib // (addnC k) fib_add // mulnDr addnC.\nrewrite (mulnC _ (fib k))  (mulnC _ (fib k.+1)); move: ha; simpl.\ncase:odd => /= ha; rewrite ha.\n  by rewrite - addnA subnKC // ltnW // -subn_gt0 -ha.\nhave hc : fib k * fib j.+2 < fib k.+1 * fib j.+1 by rewrite - subn_gt0 -ha.\nby rewrite - {1} (subnKC (ltnW hc)) addnA addnK.\nQed.\n\nLemma fib_lucas2 j k: k <= j ->\n  lucas j * fib k =\n    (if (odd k) then addn else subn) (fib (k + j)) (fib (j - k)).\nProof.\ncase:j; first by rewrite leqn0 => /eqP ->.\nmove => j;rewrite  leq_eqVlt; case/orP => ljk.\n  rewrite (eqP ljk) mulnC - fib_double_lucas addnn subnn fib0.\n  by case: odd; rewrite ?subn0 ?addn0.\nhave hb: 0 < fib (j.+1 - k) by rewrite fib_gt0 //subn_gt0.\nrewrite addnC fib_add // lucas_fib // mulnDl // addnC.\nmove: (fib_sub (ltnW ljk))=> ha; rewrite ha /=;move: ha; case:odd => ha.\n  by rewrite -addnA subnKC // ltnW // -subn_gt0 -ha.\nhave: (fib j.+2 * fib k < fib j.+1 * fib k.+1) by rewrite - subn_gt0 -ha.\nby move => /ltnW/subnKC {1} <-; rewrite addnA addnK.\nQed.\n\nLemma lucas_lucas1 p n: p <= n ->\n  lucas n * lucas p =\n    (if (odd p) then subn else addn) (lucas (n + p)) (lucas (n - p)).\nProof.\ncase: n; first by rewrite leqn0 => /eqP -> //.\nmove => n; rewrite leq_eqVlt; case/orP; rewrite ?ltnS => ha.\n  by rewrite - (eqP ha) addnn subnn mulnn lucas_square.\nrewrite mulnC (@lucas_fib n.+1) //=  mulnDr subSn //.\nrewrite (fib_lucas1 (leqW (leqW ha))) (fib_lucas1 ha) lucas_fib //lucas_fib //.\nrewrite (subSn (leqW ha)) (subSn ha) addSn addSn /=. \ncase:odd; last by rewrite addnACA.\nhave hb:=leq_BD n p.  \nhave/subnK {2}<-: fib (n - p) <= fib (n + p) by apply: fib_monotone. \nhave: fib (n - p).+2 <= fib (n + p).+2 by  apply: fib_monotone; rewrite !ltnS.\nby move/subnK => {2} <-; rewrite addnACA addnK. \nQed.\n\nLemma lucas_lucas2 p n: p <= n ->\n  5 * fib n * fib p =\n    (if (odd p) then addn else subn) (lucas (n + p)) (lucas (n - p)).\nProof.\nelim: p {-2} p (leqnn p) => [p|p IHp p0].\n  by rewrite leqn0; move/eqP=>-> /=; rewrite /= addn0 subn0 subnn muln0.\nrewrite leq_eqVlt; case/orP=> [|Hn1]; last by apply: IHp; rewrite - ltnS.\nmove /eqP => -> lnp.\ncase wwa: (p == 0).\n   move: lnp; rewrite (eqP wwa)  => /subnK {1 2} <- /=.\n   by rewrite muln1 addn1 addn1 lucasSS - addnA addnn lucas_fib3.\ncase wwb: (p == 1).\n   move: lnp; rewrite (eqP wwb)  => /subnK {1 2} <- /=.\n   set x := lucas (n - 2).+1.\n   rewrite addn2 addn2 3!lucasSS muln1 lucas_fib2 (addnC x) - (addnA _ x x).\n   by rewrite addnn - addnACA -mul2n -(mulSnr 2 x) - addnA addKn addnC.\nhave Hg: (lucas (n - p.+1).+2).*2 = lucas (n - p.+1) + lucas (n - p.+1).+3. \n  by rewrite addnC [in RHS] lucasSS - addnA -lucasSS addnn.\ncase: (odd_dichot p) => pv; rewrite pv /= odd_double /=.\n  case (posnP p./2) => ww; first by move: wwb; rewrite pv ww. \n  move: (prednK ww) => eq1.\n  have Ha: (p./2.-1).*2 < p by rewrite {2} pv ltnS leq_double leq_pred.\n  have Hb: (p./2.-1).*2 < n by rewrite (ltn_trans  Ha lnp).\n  have Hc: (p./2).*2 <= p by apply: double_half_le.\n  have Hd:= (leq_trans Hc (ltnW lnp)).\n  have He: (p./2.-1).*2.+4 <= n by rewrite - doubleS eq1 - pv.\n  rewrite fibSS mulnDr -{1} eq1 doubleS fibSS - doubleS eq1.\n  rewrite mulnDr addnAC addnn IHp // IHp // /= !odd_double /=.\n  rewrite - {1 2 5 6} eq1 doubleS ! addnS 2! [in RHS] lucasSS  addnAC addnn.\n  rewrite - {2 4}(subnK He) -2!addSnnS addnK - addSnnS addnK -doubleS eq1 -pv.\n  set A := (lucas (n + (p./2.-1).*2).+2).*2.\n  have lt1: lucas (n - p.+1) + lucas (n - p.+1).+3 <= A.\n     rewrite - Hg /A leq_double; apply: lucas_monotone => /=.\n     by apply: (@leq_trans n.+2); rewrite !ltnS ? leq_subr // ?leq_addr.\n  move/ (leq_sub2r (lucas (n - p.+1))): (lt1); rewrite addKn => lt2.\n  rewrite doubleB Hg subnDA addnC - addnA subnKC // [in RHS] addnC - addnBA //. \n  apply: leq_trans lt1; apply leq_addr.\ncase (posnP p./2) => ww; first by move: wwa; rewrite pv ww. \nmove: (prednK ww) => eq1; rewrite - eq1 doubleS.\nhave Ha: (p./2.-1).*2 < p by rewrite {2} pv ltn_double eq1.\nhave Hc := leq_trans Ha (ltnW lnp).\nhave Hb:= ltnW Ha; have Hd:= ltnW Hc.\nhave Ht: (n - (p./2.-1).*2) = (n-p.+1).+3.\n  by rewrite -3! subSS - doubleS eq1 - pv -{1} (subnK lnp) - 3!addSn addnK.\nhave He: lucas (n - p.+1).+3 <= lucas (n + (p./2.-1).*2).\n  apply: lucas_monotone; rewrite /= - Ht; apply: leq_BD.\nhave Hf: (p./2.-1).*2.+3 <= n by rewrite -doubleS eq1 - pv.\nrewrite fibSS fibSS addnC addnA addnn mulnDr - doubleMr IHp // IHp //=.\nrewrite odd_double /= doubleD !addnS lucasSS lucasSS [ X in _ = X + _] addnAC. \nhave ->: (n - (p./2.-1).*2.+3) = n - p.+1 by  rewrite - doubleS eq1 - pv.\nhave ->: (n - (p./2.-1).*2.+1) = (n-p.+1).+2.\n  by rewrite -2! subSS - doubleS eq1 - pv -{1} (subnK lnp) - 2!addSn addnK.\nrewrite addnn -!addnA Ht (addnBA _ He) Hg; congr addn. \nby rewrite addnC addnA addnK.\nQed.\n\nLemma lucas_lucas3 n p:\n  (lucas (n + p)).*2 = lucas n * lucas p + 5 * fib n * fib p.\nProof.\nwlog cp: n p / p <= n.\n   move => H; case/orP: (leq_total p n); first by apply:H.\n   by move => ha; rewrite addnC mulnC mulnAC H.\nhave ha:= (lucas_monotone2 cp).\nrewrite (lucas_lucas2 cp) (lucas_lucas1 cp) - addnn.\nby case: odd; [rewrite addnCA subnK  | rewrite -addnA subnKC ].\nQed.\n\nLemma lucas_lucas4 n p:\n  (fib (n + p)).*2 = lucas n * fib p +  lucas p  * fib n.\nProof.\nwlog le1: n p / p <= n.\n   move => H; case/orP: (leq_total p n); first by apply:H.\n   by move => ha; rewrite addnC H // addnC. \nhave ha: fib (n - p) <= fib (n + p) by apply: fib_monotone; apply:leq_BD.\nrewrite (fib_lucas1 le1) (fib_lucas2 le1) -addnn (addnC p).\nby case: odd; [ rewrite - addnA subnKC | rewrite addnCA subnK].\nQed.\n\n\nLemma lucas_is_square n x: (lucas n) == x^2  = \n   ((n==1) &&(x==1 )) || (n==3) && (x==2).\nProof.\napply/idP/idP; last by case/orP => /andP[/eqP -> /eqP ->].\nhave Hb:[\\/ x ^2 == 0 %[mod 8], (x ^2 == 1 %[mod 8]) | x ^2 == 4 %[mod 8] ].\n  have H a b: (a.*2.*2 +b)^2 = b ^2 %[mod 8].\n    rewrite sqrnD addnAC -2!mul2n mulnA expnMn -[(2 * 2) ^ 2]/(8 * 2).\n    by rewrite 2! (mulnA 2) -[2*(2*2)]/8 - 2!mulnA - mulnDr mulnC modnMDl. \n  case:(odd_dichot x); case:(odd_dichot x./2)=> -> ->; set y := x./2./2.\n  - by constructor 2; rewrite doubleS - addn3 H.\n  - by constructor 2; rewrite - addn1 H.\n  - by constructor 3; rewrite doubleS - addn2 H.\n  - by constructor 1; rewrite - (addn0 (y.*2).*2) H.\nhave Ha a b: lucas (12 * a + b) = lucas b %[mod 8].\n  suff Hc c: lucas (12 + c) = lucas c %[mod 8].\n    by elim: a => // a hr; rewrite mulnS -addnA Hc hr.\n  case:c => // c. \n  rewrite addnS addnC lucas_add fibSS addnC mulnDr addnA -mulnDl.\n  rewrite -[fib 12]/(18 *8) mulnA modnMDl -[fib 11]/(11*8 +1).\n  by rewrite  mulnDr  mulnA modnMDl muln1.\nmove: (divn_eq n 12); set a := n %/ 12; set b := n %% 12 => nv.\nmove => eq1; case:(odd_dichot n) => eq2; last first.\n  move:(lucas_square n./2); rewrite - eq2 (eqP eq1);case: odd.\n    move => h; case:(ltnP (x^2) 2) => sa.\n      move: h; rewrite (eqP (ltnW sa)) => sb.\n      by move: (lucas_gt0 n./2); rewrite - ltn_sqr sb.\n    by move:(subnK sa); rewrite - h => /square_plus2_square.\n  by move/esym /square_plus2_square.\nmove: (f_equal odd nv);rewrite eq2 /= -[12]/(6.*2)oddD oddM !odd_double.\nrewrite andbF /= => ob.\n(*\nhave ob: odd b.\n  move: (f_equal odd nv);rewrite eq2 /= -[12]/(6.*2)oddD oddM !odd_double.\n  by rewrite andbF /=.\n*)\nhave Hc: ((b==1) || (b==3) || (b== 9)).\n  move: (Ha a b);  move: (ltn_pmod n (ltn0Sn 11)).\n  rewrite mulnC -nv (eqP eq1) -/b; move: ob Hb; clear.\n  case:b => [| [|[|[|[| [| [|[|[|[| [| [| ]]]]]]] ]]]]] // _ Hb _.\n  - by rewrite -[lucas 5]/(3 + 1 *8) addnC modnMDl => w; case Hb; rewrite w.\n  - by rewrite -[lucas 7]/(5 + 3 *8) addnC modnMDl => w; case Hb; rewrite w.\n  - by rewrite -[lucas 11]/(7 + 24 *8) addnC modnMDl => w; case Hb; rewrite w.\nset y := lucas (3*a + 4).\nhave: lucas (12 * a + 9) =  y * (y^2 +1).\n\nsimpl.\n\nAbort.\n\n\nLemma lucas_n_fib_mod5 n: n * lucas n == fib n %[mod 5].\nProof.\npose Y n := n * lucas n - fib n.\nhave Hx m: m != 0 -> fib m <= m * lucas m.\n  move => h; apply:(@leq_trans (lucas m)); first by apply:fib_lt_lucas.\n  by apply:leq_pmull; rewrite lt0n.\nhave Ha: forall n, n != 0  ->  n * lucas n = fib n + Y n.\n  move => m /Hx h; rewrite /Y subnKC //. \nhave Hb x y z:  x + z = y -> x = y - z by move => <-; rewrite  addnK.\nhave Hc a b: a = 0 %[mod 5] -> b = 0  %[mod 5]  -> a.*2+b = 0 %[mod 5]. \n  by move => sa sb; rewrite - modnDm - addnn - (modnDm a a 5) sa sb mod0n.\nhave Hd a b: a = 0 %[mod 5] -> b = 0  %[mod 5]  -> a-b = 0 %[mod 5]. \n  move => sa sb; case/orP:(leq_total a b); first by rewrite -subn_eq0 => /eqP->.\n  by move/subnKC=> sc; move: sa; rewrite -{1}sc -modnDm sb mod0n add0n modn_mod.\nsuff Hf : forall m, Y m.+4 = ((Y m.+3).*2 + Y m.+2) - ((Y m.+1).*2 + Y m).\n  case nz:(n== 0);  rewrite ? (eqP nz) // -(addn0 (fib n)) Ha ? nz // eqn_modDl.\n  suff: (forall k, k <= n.+3 -> Y k = 0 %[mod 5]).\n    by move => h; apply/eqP /h /ltnW /ltnW.\n  clear nz;elim: n; first by case => [|[|[|[| ]]]].\n  move => n Hrec k.\n  have ha: n < n.+3 by apply/ltnW/ltnW. \n  have hb := (ltnW ha).\n  rewrite (leq_eqVlt); case/orP; last by rewrite ltnS; apply: Hrec.\n  move => /eqP ->; rewrite Hf; apply: Hd; apply: Hc;apply: Hrec => //.\nhave He m: m!=0 -> (Y m.+1).*2 + Y m = (m.+1 * lucas m.+1).*2 + m * lucas m  -\n   ((fib m.+1).*2 + fib m).\n  move => h; apply: Hb. \n  rewrite addnACA -doubleD (addnC (Y m)) - Ha // (addnC (Y m.+1)) - Ha //.\nmove => m; case mz: (m==0); first by rewrite (eqP mz).\nhave mz' := (negbT mz).\nset x1 := (m.+1 * lucas m.+1).*2 + m * lucas m.\nset x2 := (fib m.+1).*2 + fib m.\nset x3  := (m.+3 * lucas m.+3).*2 + m.+2 * lucas m.+2.\nset x4 := (fib m.+3).*2 + fib m.+2.\nhave la: x2 <= x1 by rewrite /x1 /x2; apply: leq_add; rewrite ? leq_double Hx.\napply: (Hb); rewrite ! He //; apply: (Hb);rewrite addnAC (addnBA _ la). \nsymmetry;apply:(Hb);rewrite -/x3 -/x4 - addnA [RHS]addnC (addnBA _ (Hx _ _)) //.\napply:Hb;rewrite /x1 /x2 /x3 /x4; clear.\nrewrite (addnC _ ((fib m.+1).*2 + fib m)) addnAC - [in RHS] addnA; congr addn.\n  by rewrite -fib3S - fib3S addnC -fibSS.\nrewrite {1} [m.+3] (addnC 3 m) {1} [m.+4] (addnC 4 m) !mulnDl doubleD doubleMr.\nrewrite addnAC {2} [m.+2] (addnC 2 m) mulnDl addnA - mulnDr (mulSn m) addnA.\nrewrite - (addnA _.*2) - mulnDr doubleD (doubleMr m)  - (addnA _.*2) - mulnDr.\nrewrite (addnC (lucas m.+1).*2) -addnA - addnA; congr (m *_  + _).\n   by rewrite -lucas3S addnA - lucas3S addnC -lucasSS.\n(* alt proof:\n   have h := like_fib_lucas.\n   rewrite -2!mul2n mulnA - (addn4 m) -(addn3 m) -(addn2 m) - (addn1 m).\n   by move:m; apply: like_fib_eq => //;\n     apply: like_fib_add; apply:like_fib_mul;apply:like_fib_shift. *) \nrewrite -(mulnA 2 2) ! mul2n - !doubleD; congr double.\nrewrite (lucasSS m.+2) doubleD addnA addnAC mulSn mul2n addnA; congr addn.\nby rewrite addnC - lucasSS lucas3S addnC.\nQed.\n\n\nSection DiophanteEquation.\n\nDefinition DE_eq1 c d := c^2 = d^2 + c*d + 1.\nDefinition DE_eq2 c d := c^2 +1 = d^2 + c*d.\n\n\nLemma DE2_rec c d:  DE_eq2 c d <-> DE_eq2 (c.*2 +d) (c+d).\nProof.\nrewrite /DE_eq2 -{1}addnn -addnA (addnC c) sqrnD -addnA -addnA (addnC(_ * _) 1).\nrewrite (addnA (c^2))  mul2n doubleMr (addnC (_ + 1)) (mulnC _ c.*2) addnA.\nrewrite mulnDl (addnA ((c + d) ^ 2)) (addnC (d^2)) mulnC - mulnn -mulnDr.\nby split; [ move => -> | move/eqP; rewrite eqn_add2l => /eqP].\nQed.\n\nLemma DE2_lt0d c d: DE_eq2 c d -> 0 <d.\nProof.\nrewrite /DE_eq2 =>h;case:(posnP d) => dp //.\nby move /eqP: h; rewrite dp muln0 addn0 exp0n // addn_eq0 andbF.\nQed.\n\nLemma DE2_pos c d: 0 < c -> DE_eq2 c d -> d <= c < d.*2.\nProof.\nmove => ha hb.\nmove: (leq_mul ha (DE2_lt0d hb)); rewrite -(leq_add2l (d^2)) - hb. \nrewrite leq_add2r leq_exp2r // => -> /=.\ncase: (ltnP c d.*2) => // hc.\nhave ea: 4 * d^2 <= c^2 by rewrite -[4]/(2^2) -(expnMn 2) mul2n leq_exp2r.\nhave eb: 4 * (c * d) <= 2 * c^2. \n  by rewrite  -[4]/(2*2) mulnACA (mul2n d) -mulnn mulnA leq_mul2l hc orbT.\nmove: (leq_add ea eb); rewrite -mulnDr -hb mulnDr -mulSn mulSnr.\nby rewrite -[X in _ <= X](addn0) -addnA leq_add2l addnS ltn0.\nQed.\n\nLemma DE2_rec' c d: 0 < c -> DE_eq2 c d -> DE_eq2 (c-d) (d.*2-c).\nProof.\nmove => cp h.\nmove /andP:(DE2_pos cp h) => [ea eb];apply/DE2_rec.\nhave xv:=(subnK ea).\nmove/eqP: (subnK (ltnW eb)); rewrite -addnn - {2}xv addnA eqn_add2r  addnC. \nby rewrite -addnn -addnA;move/eqP ->; rewrite xv.\nQed.\n\nLemma DE2_solution c d: DE_eq2 c d <-> \n     (c=0 /\\ d = 1) \\/ exists n, c = fib n.*2.+2 /\\ d = fib n.*2.+1.\nProof.\nsplit; last first.\n  case; [ by move => [-> ->] | move => [n [-> ->]]].\n  by elim:n => // n /DE2_rec;  rewrite - fib3S - fibSS !doubleS. \nelim: c d {-2} c (leqnn c).\n  move => d c; rewrite leqn0 /DE_eq2 => /eqP ->.\n  rewrite {1} /expn /= addn0 add0n -{1} [1]/(1^2).\n  by move/eqP; rewrite eqn_sqr => /eqP ->; left.\nmove => n Hrec d c. \nrewrite leq_eqVlt ltnS; case /orP => [ha hb | le]; [right | by apply:Hrec ].\nhave cp: 0 < c by rewrite (eqP ha).\nmove /andP: (DE2_pos cp hb) => [la lb].\nhave hc:= (DE2_rec' cp hb).\nhave he: c - d <= n by rewrite (eqP ha) -(prednK (DE2_lt0d hb)) subSS leq_subr.\nmove: (subnK (ltnW lb)) (subnK la); set a := c -d; set b := d.*2 - c => xv yv.\nhave ra: d = a + b. \n  by apply/eqP; rewrite - (eqn_add2r d) addnn - xv addnAC yv addnC.\nhave rb: c = a.*2 + b by rewrite - yv ra addnA addnn.\ncase: (Hrec _ _ he hc).\n   by move => [sa sb]; exists 0; rewrite ra rb /a/b sa sb.\nmove => [m [sa sb]]; exists m.+1.\nby rewrite ra rb /a/b sa sb -fibSS -fib3S !doubleS.\nQed.\n\nLemma DE_equiv_12 c d: DE_eq1 c d <-> DE_eq2 (c+d) c.\nProof.\nrewrite /DE_eq2 sqrnD mulnDl mulnn (mulnC d) -addnA mul2n -addnn (addnAC _ _ 1).\nrewrite addnA -(addnA (c^2)) (addnA (d^2)) addnAC addnC.\nby split; [ move => -> | move/eqP; rewrite eqn_add2r => /eqP ].\nQed.\n\nLemma DE1_solution c d: DE_eq1 c d <-> \n   exists n, c = fib n.*2.+1 /\\ d = fib n.*2.\nProof.\nsplit; last first.\n   move => [n [-> ->]];apply /DE_equiv_12; rewrite - fibSS.\n   by apply/DE2_solution; right; exists n.\ncase/DE_equiv_12/DE2_solution => [[/eqP] | [n [sa sb]]].\n  by rewrite addn_eq0 => /andP[/eqP ->].\nby exists n; move/eqP: sa; rewrite fibSS - sb eqn_add2l => /eqP ->.\nQed.\n\nLemma DE1_sol n:\n   (fib n.*2.+1)^2 = (fib n.*2)^2 + (fib n.*2.+1)*(fib n.*2) + 1.\nProof. by apply/DE1_solution; exists n. Qed.\n\nLemma DE2_sol n:\n   (fib n.*2.+2)^2 + 1 = (fib n.*2.+1)^2 + (fib n.*2.+2)*(fib n.*2.+1).\nProof. by apply/DE2_solution; right; exists n. Qed.\n\n\nDefinition DE_eq3 y z := (z^2 == (y.+1)^2 + (y.*2)^2).\nDefinition DE_eq4 y z := (z^2 == (y.-1)^2 + (y.*2)^2).\n\nLemma DE_eq3_solution y z: DE_eq3 y z <-> \n   (exists n, y = fib n.*2 * fib n.*2.+1 /\\ z = fib (n.*2).*2.+1).\nProof.\nsplit; last first.\n  move => [n [-> ->]]; rewrite /DE_eq3 fib_doubleS.\n  set a := fib n.*2.+1; set b :=  fib n.*2.\n  have lea:  b^2 <= a ^2 by rewrite leq_sqr fib_monotone.\n  rewrite (sqrnD_sub' lea) -expnMn -[4]/(2^2) -expnMn mul2n mulnC addnC.\n  rewrite eqn_add2r eqn_sqr -(eqn_add2r (b^2)) subnK // addnC.\n  by rewrite -(addn1 (_ * _)) addnA mulnC - DE1_sol.\ncase: (posnP y) => lt1 h.\n  rewrite lt1; exists 0; split => //; rewrite fib1.\n  by move: h; rewrite /DE_eq3 lt1 addn0 eqn_sqr => /eqP.\nset r := gcdn y.+1 y.*2.\nhave: (y.+1)^2 + (y.*2)^2 = z^2 by rewrite (eqP h).\ncase/pythagore_tripleB.\n+ by move => []. \n+ by move => []; move: lt1;case:(y).\n+ move => [p [q [ha /ltnW hb hc hd]]]; case; case; rewrite -/r => e1 e2 e3.\n  move /eqP: e2; rewrite -doubleMr eqn_double => /eqP e2.\n  move: (dvdn_gcd r y y.+1); rewrite -{1} addn1 gcdnDl gcdn1 e1 e2.\n  rewrite {2 3} /dvdn !modnMr eqxx /= dvdn1 => /eqP r1.\n  move: e1 e2 e3; rewrite r1 !mul1n => e1 e2 e3.\n  have l1: q^2 <= p^2 by rewrite leq_exp2r ? hb.\n  move: (subnK l1); rewrite - e1 e2 addSn addnC - addn1; move/esym.\n  move/(DE1_solution p q) => [n [ra rb]]; exists n.\n  by rewrite e3 ra rb mulnC - fib_doubleS.\n+ have : ~~ odd y.+1 by rewrite e2 - doubleMr odd_double. \n  move => /= /negbNE oy.\n  have g2: r = 2.\n    rewrite /r -(odd_double_half y) oy add1n -doubleS -!muln2 - muln_gcdl.\n    by rewrite (muln2 y./2) -addnn -addSn gcdnDl (eqP (coprimeSn y./2)).\n  move: (pythagore_gcd hb hc hd).\n  set p1 := p + q; set q1 := p - q.\n  have pv: p.*2 = p1 + q1 by rewrite -addnn -{2} (subnKC hb) addnA.\n  have qv: q.*2 = p1 - q1 by rewrite subnBA// - addnA addKn addnn.\n  move/eqP: e1; rewrite g2 mul2n eqn_double subn_sqr => /eqP e1.\n  move: e2; rewrite g2 doubleMr qv mulnA mul2n pv mulnC -subn_sqr e1 => e2.\n  have: DE_eq1 p1 q1.\n    by rewrite /DE_eq1 -addnA addn1 mulnC e2 subnKC // leq_exp2r // leq_BD.\n  move/(DE1_solution) => [n [p1v p2v]].\n  have yv: y =  fib n.*2 * fib n.*2.+1 by rewrite e1 -/p1 -/q1 p1v p2v.\n  have : 2 * z = 2* fib (n.*2).*2.+1. \n   rewrite e3 g2 mulnA mulnDr -[2*2]/(2^2) -!expnMn !mul2n pv qv p1v p2v -fibSS.\n    by case:(n)=> // m; rewrite doubleS (fibSS m.*2.+1) addKn fib_square_n3_n.\n  move/eqP; rewrite !mul2n eqn_double => /eqP zv.\n  by exists n; rewrite - yv - e1.\nQed.\n\nLemma DE_eq4_solution y z: 0 < y -> \n  (DE_eq4 y z <-> \n   exists n, y = fib n.*2.+2 * fib n.*2.+1 /\\ z  = fib (n.*2).*2.+3).\nProof.\nmove => yp; split; last first.\n  move => [n [-> ->]]; rewrite /DE_eq4 - doubleS fib_doubleS.\n  set a := fib n.*2.+2 ; set b := fib n.*2.+1.\n  have lea:  b^2 <= a ^2 by rewrite leq_sqr fib_monotone.\n  have /prednK ww : 0 < a * b by rewrite muln_gt0 !fib_gt0.\n  rewrite (sqrnD_sub' lea) -expnMn -[4]/(2^2) -expnMn mul2n mulnC addnC.\n  rewrite eqn_add2r eqn_sqr -(eqn_add2r (b^2)) subnK // addnC mulnC.\n  by rewrite - eqSS - addnS ww - (DE2_sol n) addn1.\nhave yn := (prednK yp).\nmove => h.\nhave h': (y.-1)^2 + (y.*2)^2 = z^2 by rewrite (eqP h).\ncase:(pythagore_tripleB h'). \n+ by move  => [/eqP]; rewrite - eqSS yn =>/eqP -> <-; exists 0. \n+ by move => []; move: yp; case: (y) => //.\n+ move=> [p [q [ha /ltnW hb hc hd]]]. \n  case; case; set r := gcdn y.-1 y.*2 => e1 e2 e3.\n  move /eqP: e2; rewrite -doubleMr eqn_double => /eqP e2.\n  move: (dvdn_gcd r y y.-1); rewrite -{1} yn gcdnC -{1} addn1 gcdnDl. \n  rewrite gcdn1 e1 e2 {2 3} /dvdn !modnMr eqxx /= dvdn1 => /eqP r1.\n  move: e1 e2 e3; rewrite r1 !mul1n => e1 e2 e3.\n  have /DE2_solution: (DE_eq2 p q). \n    rewrite /DE_eq2 - e2 -yn e1 [in RHS] addnS.\n    by rewrite addn1 subnKC //  leq_exp2r ? hb.\n  case; first by move => [pz]; move: yp; rewrite e2 pz.\n  by move => [n [he hf]]; exists n; rewrite e3 he hf - fib_doubleS.\n+ have oy: odd y.-1 = false.  \n    by move: (f_equal odd e2); rewrite -doubleMr odd_double.\n  have g2: r = 2.\n    rewrite /r -{2} yn - (odd_double_half y.-1) oy add0n.\n    rewrite -!muln2 - muln_gcdl (muln2 y.-1./2) -addnn  - addSn.\n    by rewrite gcdnDr gcdnC (eqP (coprimeSn y.-1./2)).\n  set p1 := p + q; set q1 := p - q.\n  have pv: p.*2 = p1 + q1 by rewrite -addnn -{2} (subnKC hb) addnA.\n  have qv: q.*2 = p1 - q1 by rewrite subnBA// - addnA addKn addnn.\n  move/eqP: e1; rewrite g2 mul2n eqn_double subn_sqr => /eqP e1.\n  move/eqP: e2; rewrite - eqSS yn g2 doubleMr qv mulnA mul2n pv mulnC.\n  rewrite -subn_sqr e1 -/p1 -/q1 mulnC => /eqP e2.\n  have: DE_eq2 p1 q1.\n    by rewrite /DE_eq2 e2 -(addn1 (_ - _)) addnA subnKC // leq_exp2r // leq_BD.\n  case/(DE2_solution).\n     by move => [/eqP]; rewrite /p1 /q1 addn_eq0 => /andP[/eqP -> /eqP ->].\n  move=> [n [p1v p2v]]; exists n; rewrite p1v p2v; split => //.\n  apply/eqP; rewrite - eqn_double -!mul2n e3 g2 mulnA -[2 *2]/(2^2). \n  rewrite mulnDr -!expnMn ! mul2n pv qv p1v p2v - fibSS (fibSS n.*2) addKn.\n  by rewrite fib_square_n3_n.\nQed.\n\nEnd  DiophanteEquation.\n\n\n\nSection Diophantine2.\nImport GRing.Theory Num.Theory.\nLocal Open Scope ring_scope.\n\nDefinition DE_eq5 (x y:int):= (x^+2 + x*y + x - y^+2 == 0).\nDefinition DE_eq6 (x y:int):= (x^+2 - x*y - x - y^+2 == 0).\n\n\nLemma DE_eq6_sol n (x := fib n.*2.+1) (y := fib n.*2)(z := fib n.*2.+2):\n  [/\\  (x ^ 2)^2 = (x ^ 2)*(y * x) + (x ^ 2) + (y * x)^2,\n       (y ^ 2)^2 + (y ^ 2)*(y * x) + (y ^ 2) = (y * x)^2,\n       (x ^ 2)^2 + (x ^ 2)*(z * x) = (x ^ 2) + (z * x)^2 &\n       (z ^ 2)^2 + (z ^ 2) = (z ^ 2)*(z * x) +  (z * x)^2] %N.\nProof.\nsplit.\n+ rewrite (mulnC y) expnMn -mulnSr -mulnDr addnC - (addn1 (x* y)%N) addnA.\n  by rewrite -(DE1_sol n) mulnn.\n+ rewrite -addnA  -mulnSr -mulnn -mulnDr expnMn.\n  by rewrite (mulnC y) - (addn1 (x* y)%N) (DE1_sol n) addnA.\n+ by rewrite -mulnn -mulnDr - (DE2_sol n) mulnDr muln1 addnC mulnC expnMn.\n+ by rewrite -mulnn -mulnSr expnMn -mulnDr (addnC (z*x)%N) -DE2_sol addn1.\nQed.\n\nLemma DE_equiv_56 x y: (DE_eq5 x y) = (DE_eq6 (-x) y).\nProof. by rewrite /DE_eq5 /DE_eq6 sqrrN opprK mulNr opprK. Qed.\n\nLemma DE_eq6_alt x y: \n   (DE_eq6 x y) = ((x*+2 - (y+1))^+2 == (y+1)^+2 + (y*+2)^+2).\nProof.\nrewrite sqrrB mulrnAl - mulrnA !exprMn_n  addrC - subr_eq0 opprD addrACA subrr.\nrewrite add0r -mulNrn  -mulrnDl -mulNrn  -mulrnDl mulrn_eq0 /= mulrDr mulr1.\nby rewrite opprD !addrA.\nQed.\n\n\nLemma DE_eq6_pos x y: 0 <= y -> DE_eq6 x y -> \n  exists n, y = (fib n.*2 * fib n.*2.+1)%N /\\ \n     (x = (fib n.*2.+1 ^ 2)%N \\/ x = -((fib n.*2 ^ 2)%N:int)).\nProof.\nrewrite DE_eq6_alt => sa /eqP.\nset z := (x *+ 2 - (y + 1)) => sb.\nhave eq1: y = `|y|%N by move: sa; case y.\nhave eq2: z ^+2 =  ((`|z|)^2)%N.\n   by rewrite - abszX; move: (sqr_ge0 z); case: (z^+2).\nhave: DE_eq3 `|y| `|z|.\n  move: sb; rewrite eq2 eq1 /DE_eq3 - PoszD addnn mulnn mulnn addn1. \n  by case => <-. \nmove/DE_eq3_solution => [n [ha hb]]; exists n.\n  rewrite eq1 ha; split => //.\nhave eq3: z = `|z|%:Z \\/  z = - (`|z|%:Z) .\n  by case: (z) => a; [left |right ].\nhave: x *+ 2  = z + (y+1) by rewrite /z subrK.\nhave h u: (u.*2)%:Z = (u%:Z) *+ 2 by rewrite -muln2 PoszM - mulr_natr.\ncase: eq3 => ->; rewrite hb eq1 ha - PoszD fib_doubleS mulnC.\n  rewrite  - addnA (addnA (fib n.*2 ^ 2)%N) -(DE1_sol n).\n  by move/eqP;rewrite addnn h eqr_muln2r /= => /eqP; left.\nmove => hw; right; apply/eqP;move: (DE1_sol n) hw.\nrewrite -[X in _ *+2 = X] opprK opprD opprK - addnA addn1 => ->.\nby move/eqP; rewrite addnAC addnn PoszD addrK h -mulNrn eqr_muln2r.\nQed.\n\nLemma DE_eq6_neg x y: y <0 -> DE_eq6 x y -> \n  exists n, y = -((fib n.*2.+2 * fib n.*2.+1)%N:int) /\\ \n     (x = (fib n.*2.+1 ^ 2)%N \\/ x = -((fib n.*2.+2 ^ 2)%N:int)).\nProof.\nrewrite DE_eq6_alt => sa /eqP.\nset z := (x *+ 2 - (y + 1)) => eq0.\nhave eq2: z ^+2 =  ((`|z|)^2)%N.\n   by rewrite - abszX; move: (sqr_ge0 z); case: (z^+2).\nhave eq1: -y = `|y|%N by move: sa; case y.\nhave eq3 : (`|y|%:Z - 1) = (`|y|.-1)%N. \n  by move: sa;  clear;case: y => //; case.\nhave yp : 0 < `|y| by move: sa; case y.\nhave: DE_eq4 `|y| `|z|.\n  move: eq0; rewrite eq2 - sqrrN - (sqrrN (y *+ 2)) opprD -mulNrn.\n  by rewrite  eq1 eq3 - PoszD addnn mulnn mulnn; case => /eqP.\nmove/(DE_eq4_solution _ yp) => [n [ha hb]]; exists n; split.\n  by apply: oppr_inj; rewrite opprK eq1 ha.\nhave eq4: z = `|z|%:Z \\/  z = - (`|z|%:Z) by case: (z) => a; [left |right ].\nhave h u: (u.*2)%:Z = (u%:Z) *+ 2 by rewrite -muln2 PoszM - mulr_natr.\nhave: x *+ 2  = z +1 + (-(-y)) by rewrite opprK addrAC -addrA /z subrK.\ncase: eq4 => ->; rewrite hb -doubleS fib_doubleS eq1 ha.\n  rewrite - (PoszD _ 1%N) addnAC (DE2_sol n) addnAC PoszD addrK addnn.\n  by move/eqP; rewrite h eqr_muln2r /= => /eqP; left.\nmove => hw; right; apply/eqP; move /eqP: hw.\nrewrite addrAC -opprD - PoszD - addnA -(DE2_sol n) addnA addnn PoszD opprD.\nby rewrite addrK h -mulNrn eqr_muln2r.\nQed.\n\n\nLemma DE_eq6_solution (x y:int): (x^+2 - x*y - x - y^+2 == 0) <-> exists n,\n  [\\/ y = (fib n.*2 * fib n.*2.+1)%N /\\ x = (fib n.*2.+1 ^ 2)%N,\n      y = (fib n.*2 * fib n.*2.+1)%N /\\ x = -((fib n.*2 ^ 2)%N:int),\n    y = -((fib n.*2.+2 * fib n.*2.+1)%N:int) /\\ x = (fib n.*2.+1 ^ 2)%N |\n    y = -((fib n.*2.+2 * fib n.*2.+1)%N:int) /\\ x = -((fib n.*2.+2^2)%N:int)\n  ].\nProof.\nsplit.\n  move => h.\n  case: (lerP 0 y) => yp.\n    move: (DE_eq6_pos yp h) => [n [ha hb]]; exists n. \n    by case: hb; [ constructor 1 | constructor 2].\n  move: (DE_eq6_neg yp h) => [n [ha hb]]; exists n. \n  by case: hb; [ constructor 3 | constructor 4].\nhave hu (a:nat): (a%:Z)^+2 = (a^2)%:Z by [].\nrewrite /DE_eq6; move => [n]; move: (DE_eq6_sol n) => [ea eb ec ed].\ncase; move => [-> ->].\n+ rewrite addrAC - addrA addrAC addrA hu ea PoszD hu addrK PoszD addrK.\n  by rewrite PoszM subrr.  \n+ by rewrite - mulNr opprK sqrrN ! hu -PoszM -PoszD eb subrr.\n+ by rewrite sqrrN -mulrN opprK ! hu -PoszM -PoszD ec addnC PoszD addrK subrr.\n+ rewrite !sqrrN mulrN !opprK mulNr - addrA addrACA - opprD !hu.\n  by rewrite - PoszM -PoszD ed -PoszD subrr.\nQed.\n\nEnd Diophantine2.\n\nLemma fib_plus_fib a b c: b <= c -> \n  (fib a == fib b + fib c) =\n  [ || (b == 0) && (fib a == fib c), \n      [&& b ==c, (c==1) || (c== 2) & a==3],\n      [&& b ==1, c==3 & a==4] | \n      (c==b.+1) && (a==b.+2)].\nProof.\ncase:b. \n  move => _.\n  case wa: ((c == 1) && (a == 2)); first by move/andP:wa => [/eqP -> /eqP ->].\n  by case wb: (0==c); rewrite - ? (eqP wb) /= orbF. \nmove => b; rewrite/= !eqSS;case:b. \n  rewrite add1n - (addn1 (fib c)) (eq_sym 1 c) /=.\n  case: c => // c _; rewrite !eqSS.\n  case cz: (c==0); first by rewrite (eqP cz) (fib_eq a 3) /= !andbF !orbF.\n  case co: (c==1); first by rewrite (eqP co) (fib_eq a 3) /= !andbF !orbF.\n  case ct: (c==2); first by rewrite (eqP ct) (fib_eq a 4) /= ! andbF!orbF.\n  simpl; apply/negP => /eqP ha.\n  case: (ltnP c.+1 a) => lac; last first.\n    by move: (fib_monotone lac); rewrite ha addn1 ltnn.\n  have w: (3 <= c) by rewrite ltn_neqAle eq_sym ct ltn_neqAle eq_sym co lt0n cz.\n  move: (fib_monotone  lac); rewrite ha fibSS leq_add2l => la.\n  by move: (leq_trans (fib_monotone w) la).\nmove => b; rewrite leq_eqVlt; case/orP => ha.\n  have hh:=(ltn_eqF (ltnSn b)).\n  rewrite - (eqP ha) !eqSS eqxx hh /= orbF.\n  case bz: (b==0); first  by rewrite (eqP bz)  (fib_eq a 3) !andbF !orbF.\n  simpl; apply/negP => hb.\n  case: (ltngtP b.+3 a) => lac.\n  + move: (fib_monotone lac); rewrite (eqP hb) fibSS leq_add2r.\n    by apply/negP;rewrite -ltnNge fib_smonotone_bis.\n  + rewrite ltnS in lac; move: (fib_monotone lac).\n    by rewrite (eqP hb) leqNgt ltn_paddr // fib_gt0.\n  + by move: hb; rewrite - lac fibSS eqn_add2l fib_eq // !eqSS bz hh /= andbF.\nrewrite (ltn_eqF ha) /=; move: ha; rewrite leq_eqVlt; case/orP=> ha.\n  by rewrite - (eqP ha) addnC -fibSS eqxx fib_eq !eqSS !andbF!orbF.\nhave cp:=(ltn_predK ha).\nrewrite (gtn_eqF ha) /=; apply/negP => hb.\ncase: (ltngtP a c.+1) => lac.\n+ rewrite ltnS in lac; move: (fib_monotone lac). \n  by rewrite leqNgt (eqP hb) ltn_paddl // fib_gt0.\n+ move:(fib_monotone lac); rewrite (eqP hb) fibSS leq_add2r leqNgt.\n  by rewrite fib_smonotone //  !ltnS (ltnW(ltnW ha)) andbT.\n+ move: hb; rewrite lac -cp fibSS addnC eqn_add2r fib_eq !eqSS  andbF orbF. \n  rewrite -eqSS -(eqSS _ 1) !cp (gtn_eqF ha) /= => /andP [h1 h2].\n  by move: ha; rewrite (eqP h1) (eqP h2).\nQed.\n\nLemma lucas_plus_lucas a b c: b <= c -> \n  (lucas a == lucas b + lucas c) =\n     [ || [&& a==3, b==0 & c==0], [&& a==0, b==1 & c==1] |\n        (c==b.+1) && (a==b.+2)].\nProof.\nhave Ha i: i != 1 -> 2 <= lucas i.\n  by case: i => [| [| i _]]//; apply: ltnW; apply: (@lucas_monotone 2 i.+2).\nhave Hb i: 2 <=i -> 3 <= lucas i by apply:(lucas_monotone (m:=2)).\ncase az: (a== 0). \n  rewrite (eqP az) !andbF /= orbF => lbc; case: (ltngtP 1 b) => b1.\n  +  apply/negP => /eqP h.\n    by move: (Hb _ b1); rewrite -(ltn_add2r (lucas c)) - h.\n  + move: b1; rewrite ltnS leqn0 => /eqP ->.\n    by rewrite -{1} (addn0 (lucas 0)) eqn_add2l /= (ltn_eqF (lucas_gt0 c)).\n  + by rewrite - b1 /= -[lucas 0]/(1+(lucas 1))  eqn_add2l lucas_injective_bis.\ncase bz: (b == 0).\n  rewrite (eqP bz) /= => _.\n  case cz: (c== 0).\n     rewrite (eqP cz) /= andbT orbF; exact: (lucas_injective_bis a 3).\n  case co: (c== 1).\n     rewrite (eqP co) andbF /=; exact: (lucas_injective_bis a 2).\n  rewrite andbF /=; apply/negP => /eqP h.\n  case:(ltnP c a) => ha; last first.\n    have /lucas_monotone: 0 < a <=c by rewrite ha lt0n az.\n    by rewrite h ltnNge leqnSn.\n  have /lucas_monotone ww : 0 < c.+1 <= a by rewrite ha.\n  have /prednK cp : O < c by rewrite lt0n cz.\n  move: ww; rewrite  h -{1}cp lucasSS addnC cp leq_add2r  lucas_monotoneE.\n  rewrite !andbF /= -!(eqSS c.-1) cp co /= andbT orbF => c2.\n  move: h; rewrite (eqP c2); clear;case: a => [|[|[|[| a]]]] // ea.\n  have /lucas_monotone :0 < 4 <= a.+4 by []. \n  by rewrite ea.\nrewrite /= andbF /=.\nrewrite leq_eqVlt; case/orP => ebc.\n  rewrite - (eqP ebc) (ltn_eqF (ltnSn b)) /=; apply/negP => /eqP h.\n  case: (ltngtP b.+1 a) => lab.\n  + have /lucas_smonotone ha: 0 < b < b.+1 by rewrite ltnSn lt0n bz.\n    have /lucas_monotone: 0 < b.+2 <= a by rewrite lab. \n    by rewrite lucasSS h leq_add2r leqNgt ha.\n  + have /lucas_monotone: 0 < a <= b by rewrite lt0n - ltnS lab az.\n    by rewrite h  -{3} (add0n (lucas b)) leq_add2r leqNgt lucas_gt0.\n  + move /eqP:h; rewrite -lab.\n    move:bz; clear; case: b => // b _.\n    by rewrite lucasSS eqn_add2l lucas_injective_bis; apply/negP /eqP.\napply/eqP/andP; last by move => [/eqP -> /eqP ->]; rewrite lucasSS addnC.\nmove => h.\nhave c1:= (ltn_predK ebc).\nhave /lucas_monotone: 0 < b <= c.-1 by  rewrite lt0n bz - ltnS c1 ebc.\nrewrite - (leq_add2r (lucas c)) -h addnC - {1} c1 -lucasSS c1 => lb.\ncase: (ltngtP a c.+1) => la.\n+ have /lucas_monotone: 0 < a <= c by rewrite lt0n az -ltnS la.\n  by rewrite h -{2}(add0n (lucas c)) leq_add2r leqNgt lucas_gt0.\n+ have /lucas_smonotone: 0 < c.+1 < a by rewrite la.\n  by rewrite ltnNge lb.\n+ move /eqP: h; rewrite la - c1 lucasSS addnC eqn_add2r lucas_injective_bis.\n  by move/eqP ->. \nQed.\n\nLemma fib_eq_lucas m n: (fib m == lucas n) = \n  [|| (n==0) &&(m==3), (n==1) &&((m==1) || (m==2))  | (n==2)&&(m==4) ].\nProof.\ncase nz: (n==0).\n   by rewrite (eqP nz) lucas0 (fib_eq m 3) !andbF.\nhave ha:= (leq_ltn_trans (leq_pred n) (ltnSn n)).\nrewrite lucas_fib ? nz // addnC (fib_plus_fib _ (ltnW ha)) (ltn_eqF ha) !eqSS.\nhave hc:=(prednK (neq0_lt0n nz)).\ncase no: (n==1); first by rewrite (eqP no) /= fib_eq andbF !orbF andbT orbC.\ncase nt: (n==2); first by rewrite (eqP nt) /= orbF.\nby rewrite - eqSS hc no andbF /= - {1} hc  (gtn_eqF (ltnSn n.-1)).\nQed.\n\nLemma lucas_times_fib_is_fib m n k:\n   (fib n == lucas k * fib m) =\n   [|| [&& k==0, n==3 & (m==1) || (m==2) ],\n       (k==1) && [|| n == m, (n == 1) && (m == 2) | (n == 2) && (m == 1)] ,\n       ( ((m==0) && (n == 0))\n         || [&& ((m==1) || (m==2)), (k==2) &(n==4) ]) |\n       (k==m) && (n == m.*2)].\nProof.\ncase mz: (m==0). \n  by rewrite (eqP mz) muln0 fib_eq0; case nz:(n== 0); rewrite ?orbT //= !andbF.\ncase m12: ((m == 1) || (m == 2)).\n  have ->: fib m = 1 by case/orP:m12 => /eqP ->.\n  rewrite muln1 fib_eq_lucas andbT /=; case:((k == 0) && (n == 3)) => //=.\n  case n1: (n ==1). \n    rewrite (eqP n1) andbT andbF /= !orbF (eq_sym 1 m) m12 andbT.\n    by case:(orP m12) => /eqP ->; rewrite andbF orbF.\n  case n4: (n ==4). \n    rewrite /= (eqP n4) andbT !andbF /= orbF.\n    by case:(orP m12) => /eqP ->; rewrite !andbF ?orbF // andbT/= orbb.\n  rewrite andbF /= orbF;case:(orP m12)=> /eqP ->. \n    by rewrite n1 /= andbT orbb. \n  by rewrite n4 !andbF !orbF.\nhave [ha hb]: (m==1) = false /\\ (m==2) = false by move: m12; case: eqP.\nrewrite !andbF /=; case kz: (k==0). \n  rewrite (eqP kz) lucas0 mul2n -addnn fib_plus_fib //= (eq_sym 0 m).\n  by rewrite mz /= m12 /= andbF ha (ltn_eqF (ltnSn m)).\ncase k1: (k==1).\n  by rewrite (eqP k1) mul1n fib_eq (eq_sym 1) ha hb /= !andbF !orbF.\nhave mk5: (5 <= m + k).\n  have k2: 2 <= k by rewrite ltn_neqAle lt0n eq_sym k1 kz.\n  have m3: 3 <= m by rewrite ltn_neqAle ltn_neqAle lt0n eq_sym hb eq_sym mz ha.\n  exact: (leq_add m3 k2).\nmove: (gtn_eqF mk5)  (gtn_eqF (ltnW mk5)) (ltnW(ltnW mk5))=> mk4 mk3 mk5'.\nmove: (gtn_eqF mk5') (gtn_eqF (ltnW mk5')) => mk2 mk1.\nhave Hw p: p.*2 ==1 = false by case:p.\nhave LTD m' k': (k' == 0) = false -> m' - k' < m' + k'.\n  move => k'z; apply:(leq_ltn_trans (leq_subr k' m')). \n  by rewrite ltn_paddr // lt0n k'z.\ncase: (ltngtP m k) => hc; last first.\n+ rewrite hc mulnC - fib_double_lucas fib_eq -[2]/(1.*2) eqn_double k1.\n  by rewrite Hw  !andbF !orbF.\n+ rewrite (fib_lucas1 (ltnW hc)) /=; apply/negP => /eqP.\n  have hd:= (LTD m k kz). \n  case: odd; last first.\n    move/eqP;rewrite addnC (fib_plus_fib _ (ltnW hd)) subn_eq0  leqNgt mk3 mk2.\n    rewrite hc (ltn_eqF hd) /= - [in m +k](subnK (ltnW hc)) - addnA addnn.\n    by rewrite andbF /= - addn1 eqn_add2l Hw.\n  move: (subnK (ltnW hc)) => he ea.\n  move/eqP :(esym (subnK (fib_monotone (ltnW hd)))); rewrite - ea.\n  case /orP: (leq_total n (m - k)) => cnmk; [ | rewrite (addnC (fib n))  ];\n    rewrite (fib_plus_fib _ cnmk) mk4 mk3 !andbF /=.\n     case/orP; first by rewrite fib_eq (gtn_eqF hd) /= mk1 mk2 /= andbF.\n    rewrite - {2} he - addnA addnn => /andP[/eqP ->] /eqP  h.\n    by move:(f_equal odd h); rewrite oddD odd_double addbF /=;case:odd.\n  rewrite subn_eq0 leqNgt hc /= - {2} he => /andP[_].\n  by rewrite -addnA -addn2 eqn_add2l addnn (eqn_double _ 1) k1.\n+ rewrite (fib_lucas2 (ltnW hc)) ;  apply/negP => /eqP.\n  have he:= (subnKC (ltnW hc)).\n  move: (LTD k m mz); rewrite addnC => hd.\n  case: odd.\n    move/eqP; rewrite addnC (fib_plus_fib _ (ltnW hd)) subn_eq0 mk1 mk2 mk3.\n    by rewrite !andbF leqNgt hc //= -{1} he addnA addnn -add1n eqn_add2r Hw.\n  move => ea.\n  have: fib (m + k) == fib n + fib (k - m).\n    by rewrite ea; rewrite subnK // (fib_monotone (ltnW hd)).\n  case /orP: (leq_total n (k - m)) => cnmk;[ | rewrite (addnC (fib n))  ];\n     rewrite (fib_plus_fib _ cnmk) mk4 mk3 !andbF /=.\n     case/orP; first by  rewrite fib_eq (gtn_eqF hd) /= mk1 mk2 /= andbF.\n     rewrite - {2} he addnA addnn => /andP[/eqP ->] /eqP  h.\n     by move:(f_equal odd h); rewrite oddD odd_double /=;case:odd.\n   rewrite subn_eq0 leqNgt hc /= - {2} he => /andP[_].\n   by rewrite addnA -add2n eqn_add2r addnn (eqn_double _ 1) ha.\nQed.\n\n\nLemma lucas_times_lucas_is_fib m n k: k <= m ->\n   (fib n == (lucas m) * (lucas k)) =\n    [|| [&& k==0, m == 1 & n == 3], [&& k==0, m == 3 & n == 6],\n        (k==1) && \n         [|| (m == 1) && (n == 1), (m == 1) && (n == 2) | (m == 2) && (n == 4)]\n        | [&& k ==2, m==4 & n==8] ].\nProof.\nmove => h.\ncase kz: (k == 0). \n  by rewrite (eqP kz) -[lucas 0]/(fib 3) lucas_times_fib_is_fib !andbF !orbF.\ncase kn1: (k == 1). \n  move:h;rewrite (eqP kn1) muln1 fib_eq_lucas /= lt0n; case: eqP => // _ _.\n  by case m1: (m==1); rewrite orbF // (eqP m1) andFb !orbF.\nhave sk := (subnK h).\nsimpl;apply/eqP/idP; last by move/and3P => [/eqP -> /eqP -> /eqP ->].\nhave mkz: m + k != 0 by rewrite addn_eq0 kz andbF.\nhave la: 2 <= k by move: kz kn1; case:(k) => //; case.\nhave mk2:=(leq_add (leq_trans (ltnW la) h) (ltnW la)).\nmove:(subnK mk2); rewrite addn2 => hb.\nrewrite (lucas_lucas1 h); case ok: (odd k); last first. \n  rewrite (lucas_fib mkz) => ea.\n  have: fib (m + k).+1 < fib n.\n    by rewrite ea -addnA -[X in X < _] addn0 ltn_add2l addn_gt0 lucas_gt0 orbT.\n  move/fib_monotone_bis => /fib_monotone. \n  rewrite ea -addnA fibSS leq_add2l -hb fibSS leq_add2l.\n  move:h; rewrite leq_eqVlt; case/orP => hc.\n    move: ea;rewrite - (eqP hc) subnn lucas0 - ltnS -[3]/(fib 4) => fn h.\n    move: (fib_monotone_bis h) fn kz ok; case k => //; case => //; case => //.\n      rewrite -[RHS ]/9 => _ eb _ _; case: (ltngtP 7 n) => sa.\n      + by move:(@fib_smonotone 7 n); rewrite eb sa /=; apply.\n      + by rewrite ltnS in sa;move:(fib_monotone sa); rewrite eb.\n      + by move: eb; rewrite - sa.\n    by move => n1; rewrite !addnS !addSn /= subn2 !ltnS ltn0.\n  move: (hc); rewrite - subn_gt0 => /gtn_eqF /negbT/lucas_lt_fib /leqifP.\n  move:ea; rewrite - [in m+k] sk - !addnA addnn.\n  case ha: (m-k==2). \n    rewrite -[in m==4] sk (eqP ha) addKn.\n    move: kz ok; clear; case: k => [| [| [ | k ]]]//.\n      move => _ _; rewrite -[RHS]/(fib 8) => /eqP. \n      by rewrite fib_eq !andbF !orbF. \n    move => _ _ _ _ h.\n    have: 2 < (k.+2).*2 by rewrite !doubleS !ltnS.\n    by move /fib_smonotone_bis; rewrite ltnNge h.\n  move => ea lc lb; move:(leq_ltn_trans lb lc) => /fib_monotone_bis.\n  move: kz ok; clear; case: k => [| [| k]] // _ _.\n  by rewrite !doubleS -(addn2 k.*2.+2) addnA addnK - 2!addSnnS ltnNge leq_addr.\nmove:h;rewrite leq_eqVlt; case/orP => lkm.\n  rewrite - (eqP lkm) subnn lucas0; move: ok kn1; clear; case:k => //k.\n  rewrite addnS addSn addnn lucas_fib //=; case:k => // k ok _.\n  have e2: 2 < fib (k.+1).*2.+1.  \n     apply: (fib_monotone(m:=4)); rewrite doubleS !ltnS double_gt0.\n     by move:ok;case:(k).\n  rewrite  -(addnBA _ (ltnW e2)) => eq1.\n  have: fib (k.+1).*2.+3 < fib n.\n    by rewrite eq1 -[X in X < _] addn0 ltn_add2l subn_gt0.\n  move/fib_monotone_bis => /fib_monotone; rewrite fibSS eq1 leq_add2l fibSS.\n  by rewrite -{1} (subnK (ltnW e2)) -addnA leqNgt add2n addnS ltnS leq_addr.\nmove => ea.\nhave mkgt4:=(leq_add (leq_ltn_trans la lkm) la).\nhave eb: fib n + lucas (m - k) = lucas (m + k).\n  rewrite ea subnK // lucas_monotone // subn_gt0 lkm /=; apply: leq_BD.\nmove /leqifP: (lucas_lt_fib mkz).\nrewrite eq_sym (ltn_eqF (ltnW(ltnW mkgt4))) - eb => bnd1.\nmove:(leq_ltn_trans (leq_addr (lucas (m - k)) (fib n)) bnd1).\nmove => /fib_monotone_bis; rewrite ltnS => /fib_monotone.\nrewrite -(leq_add2r (lucas (m - k))) eb (lucas_fib mkz) leq_add2l => bnd2.\nmove:lkm; rewrite leq_eqVlt; case/orP => lkm1.\n   move: bnd2; rewrite - (eqP lkm1)  subSnn addSn addnn /=.\n   have: 1 < 3 < k.*2 by move: kz kn1; clear; case:k => [|[|]]//.\n   by move /fib_smonotone => hu hv; move:(leq_trans (ltnW hu) hv).\nmove:lkm1; rewrite leq_eqVlt; case/orP => lkm2.\n  move: bnd2; rewrite - (eqP lkm2) - (add2n k) addnK -addnA addnn add2n.\n  rewrite -[lucas 2]/(fib 4) leqNgt fib_smonotone //= ltnS (leq_double 2 k).\n  by move: kz kn1; clear; case:k => [|[|]]//.\nmove:(lkm2);rewrite - addn2 addSn -ltn_subRL => wa.\nmove/leqifP: (lucas_lt_fib (negbT (gtn_eqF (ltnW(ltnW wa))))).\nrewrite (gtn_eqF wa) => wb.\nmove:(fib_monotone_bis (leq_ltn_trans bnd2 wb)).\nrewrite ltnNge - {2} sk -addnA addnn - {3} (ltn_predK la) doubleS !addnS.\nrewrite !ltnS -{1} (addn0 (m-k)) ltn_add2l double_gt0.\nby move:kz kn1;clear; case: k => [| [| ]].\nQed. \n\nLemma fib_times_c_is_fib1 n k c: k !=1 -> k != 2 ->\n    fib n = c * (fib k) -> k %| n.\nProof.\nmove => k1 k2 h.\nmove:(gcd_fib n k); rewrite h gcdnC gcdnMl => /esym /eqP.\nby rewrite fib_eq (negbTE k1) (negbTE k2) !andbF !orbF => /eqP /gcdn_idPr.\nQed.\n\nLemma fib_times_c_is_fib2 n k c: 2 <= c -> 2 < k -> \n    fib n = c * (fib k) -> (lucas k) <= c.\nProof.\nmove => ha hb hc.\nhave fkz:(fib k == 0) = false.\n   by rewrite fib_eq0 eqn0Ngt (ltnW (ltnW hb)).\ncase k1:(k==1); first by  move:hb; rewrite (eqP k1).\ncase k2:(k==2); first by  move:hb; rewrite (eqP k2).\nmove:(fib_times_c_is_fib1 (negbT k1) (negbT k2) hc) => /dvdnP [a nv].\nmove: hc; rewrite nv => /eqP.\ncase: (ltngtP a 1).\n+ rewrite ltnS leqn0 => /eqP ->.\n  by rewrite  eq_sym muln_eq0 fkz eqn0Ngt (ltnW ha).\n+ move => sa sb.\n  have: 2 *k <= a * k by  rewrite leq_mul2r sa orbT.\n  move/fib_monotone; rewrite mul2n fib_double_lucas (eqP sb) mulnC.\n  by rewrite leq_mul2r fkz.\n+ by move ->; rewrite mul1n - {1}(mul1n (fib k)) eqn_mul2r fkz (ltn_eqF ha).\nQed.\n\nLemma fib_times_c_is_fib3 n k : \n  fib n == 2 * (fib k) = ((k==0) && (n==0)) || ((n==3) && ((k==1) || (k==2))).\nProof.\nrewrite (lucas_times_fib_is_fib k n 0) andbF !orbF /= (eq_sym 0 k).\nby case kz: (k==0); rewrite ? orbF // (eqP kz) !andbF orbb orbF.\nQed.\n\nLemma fib_times_c_is_fib4 n k : \n  fib n == 3 * (fib k) = ((k==0) && (n==0)) || (((k==1) || (k==2)) &&(n==4)).\nProof.\nrewrite (lucas_times_fib_is_fib k n 2) /= (eq_sym 2 k).\nby case kz: (k==2); rewrite ? orbF //= (eqP kz) orbb.\nQed.\n\nLemma fib_times_c_is_fib5 n k m: 2 < k -> 2 < m ->\n  fib n <> fib m * fib k.\nProof.\nwlog: k m / k <= m.\n  case /orP:(leq_total k m) => // ha hb. by apply: hb.\n  by move => hc h; rewrite mulnC; apply: hb.\nmove => sb sa _ h.\nhave m3 := (leq_trans sa sb).\nhave ms:= (ltn_predK  m3).\nhave ha: m.+1 != 0 by [].\nhave hb: m != 0 by rewrite -ms.\nhave hc: 0 < m.-1 by rewrite - ltnS ms (ltnW m3).\nhave fmp: (0 < fib m) by rewrite fib_gt0 // lt0n.\nhave lmn: m < n.\n  apply/fib_monotone_bis; rewrite h -{1} (muln1 (fib m)) ltn_mul2l.\n  rewrite fmp; apply:(fib_monotone sa). \nmove:(fib_add (n-m) hb); rewrite  (subnKC (ltnW lmn)) => eq1.\nhave : fib m * fib (n - m).+1 < fib n.\n  by rewrite eq1 ltn_paddl // muln_gt0 !fib_gt0 ?subn_gt0.\nrewrite h ltn_mul2l fmp /= => /fib_monotone_bis => la.\nhave: fib m.-1 * fib (n - m) <  fib m * fib (n - m).\n  by rewrite ltn_mul2r fib_gt0 ?subn_gt0 //= fib_smonotone // -ltnS ms m3 leqnn.\nrewrite -(leq_add2r (fib m * fib (n - m).+1)) addSn - eq1 -mulnDr addnC.\nrewrite - fibSS h ltn_mul2l fmp // => /fib_monotone_bis; rewrite ltnS.\nby rewrite leqNgt la.\nQed.\n\n\nLemma fib_times_lucas_is_lucas n k m: \n  lucas n == (fib m) * (lucas k) = \n  [ || ((m==1) || (m==2)) && (n == k),\n    ((k==1) &&\n    [|| (n==0) &&(m==3), (n==1) &&((m==1) || (m==2))  | (n==2)&&(m==4) ])\n  | [&& k ==0 , n == 3 & m ==3] ].\nProof.\nhave sc: (n == k) = false -> false = (k == 1) && (n == 1).\n  by case k1: (k==1) => //;rewrite (eqP k1). \ncase mz:(m==0).\n  by rewrite (eqP mz) mul0n (gtn_eqF (lucas_gt0 n)) !andbF /=.\ncase m1: (m==1). \n  rewrite (eqP m1) /= mul1n lucas_injective_bis; case nk: (n == k) => //.\n  by rewrite !andbF andbT /= !orbF; apply: sc.\ncase m2: (m==2).\n  rewrite (eqP m2) /= mul1n lucas_injective_bis; case nk: (n == k) => //.\n  by rewrite !andbF andbT /= !orbF; apply: sc.\ncase k1: (k==1). \n  by rewrite (eqP k1) muln1 eq_sym fib_eq_lucas m1 m2 !andbF /= orbF.\nhave lt1: 1 < m by move: mz m1; case m => [|[]].\nhave lt2: 2 < m by move: mz m1 m2; case m => [|[|[]]].\nhave ms1p:  0 < m.-1 by move: mz m1; case m => [|[]].\nhave ww := (ltn_predK lt1).\ncase kz: (k==0).\n  rewrite (eqP kz) lucas0 /=; case m3:(m==3).\n    by rewrite (eqP m3) -[fib 3 * 2]/ (lucas 3) lucas_injective_bis andbT.\n  rewrite andbF; apply /negbTE/eqP => eqa.\n  move:(lucas_ge_2fib lt1); rewrite - muln2 -eqa => eqb.\n  case: (ltnP m n) => lmn.\n    have /lucas_smonotone :0 < m < n by rewrite (ltnW lt1) lmn.\n    by rewrite ltnNge eqb.\n  case nz: (n==0).\n    move:(leq_mul2r 2 (fib 3) (fib m)); simpl; rewrite (fib_monotone lt2) - eqa.\n    by rewrite (eqP nz) lucas0. \n  case nt: (n==2).\n     move: eqa; rewrite (eqP nt) muln2 => h; move:(f_equal odd h).\n     by rewrite odd_double.\n  have: fib m.+1 <= lucas n.\n    by rewrite eqa muln2 -addnn -ww fibSS leq_add2l fib_monotone.\n  move/leqifP:(lucas_lt_fib (negbT nz)); rewrite nt => ha hb.\n  move:(leq_ltn_trans hb ha) => /fib_monotone_bis; rewrite !ltnS => hc.\n  move: (eqn_leq m n); rewrite lmn hc /= => /eqP emn.\n  move:eqa; rewrite - emn  muln2 -addnn (lucas_fib (negbT mz)) - {1}ww.\n  move/eqP; rewrite fibSS ww -addnA eqn_add2l eq_sym addnn - mul2n.\n  by rewrite fib_times_c_is_fib3 mz -3!(eqSS m.-1) ww m1 m2 m3.\nsimpl;  apply/negP => /eqP h.\nhave fp:= (fib_gt0 (ltnW lt1)).\nhave lk3: 3 <= lucas k. \n  by rewrite(lucas_monotoneE 2) /= orbF -leq_eqVlt ltn_neqAle eq_sym lt0n kz k1.\nhave  la: m < n.\n  have b1 := (leq_mul (fib_monotone lt2) lk3).\n  case nz: (n== 0); first by move: b1; rewrite - h (eqP nz).\n  case n2: (n== 2); first by move: b1; rewrite - h (eqP n2).\n  move/leqifP:(lucas_lt_fib (negbT nz)); rewrite n2 h.\n  move: (ltnW lk3); rewrite - (leq_pmul2r fp) mul2n mulnC => sa sb.\n  have lc : fib n.+2  <= (fib n.+1).*2. \n    by rewrite fibSS -addnn leq_add2l fib_monotone //.\n  move: (leq_trans (leq_ltn_trans sa sb) lc); rewrite ltn_double.\n  move/fib_monotone_bis; rewrite ltnS leq_eqVlt; case/orP => // emn.\n  move: lk3; rewrite - (leq_pmul2l fp) - h (eqP emn). \n  move: nz n2; clear; case: n => //n _; rewrite lucas_fib // fibSS.\n  rewrite mulnS -addnA leq_add2l /= muln2 addnn leq_double leqNgt.\n  case: n => //; case => //n; rewrite fib_smonotone // !ltnS leqnn //.\nmove: (lucas_add m.-1 (n-m)); rewrite -addnS ww (subnK (ltnW la)) => eq2.\nhave: lucas (n - m).+1  * fib m < lucas n.\n  rewrite eq2 ltn_paddr // muln_gt0 lucas_gt0 fib_gt0 //. \nrewrite h mulnC ltn_mul2l fp /= => lb.\ncase: (ltnP (n - m).+1 k) => lc; last first.\n   by move: lb; rewrite ltnNge lucas_monotone //lc lt0n kz.\nhave:lucas (n - m) * fib m.-1 < lucas (n - m) * fib m.\n  by rewrite ltn_mul2l lucas_gt0 /= fib_smonotone // - ltnS ww lt2 leqnn.\nrewrite -(ltn_add2l (lucas (n - m).+1 * fib m)) -eq2 h -mulnDl -lucasSS.\nby rewrite mulnC ltn_mul2r fp /= ltnNge lucas_monotone.\nQed.\n\n\nLemma lucas_times_lucas_is_lucas m n k: k <= m -> \n  lucas n == (lucas m) * (lucas k) = \n  [ || [&& k ==0, m == 0 & n == 3],\n       [&& k ==0, m == 1 & n == 0] |\n       [&& k ==1 & m == n] ].\nProof.\nmove => km.\ncase kz: (k==0).\n  rewrite mulnC (eqP kz) -[lucas 0]/(fib 3) fib_times_lucas_is_lucas.\n  by rewrite /= ! andbF !orbF eqxx !andbT orbC.\ncase k1: (k==1).\n  by rewrite mulnC (eqP k1) lucas1 mul1n /= lucas_injective_bis.\nsimpl;  apply/negP => /eqP; rewrite lucas_lucas1 //.\nhave ha: 1 < k by rewrite ltn_neqAle lt0n kz eq_sym k1.\nhave hb:=(leq_add (leq_trans  ha km) ha).\nhave x0:= (gtn_eqF(ltnW (ltnW(ltnW hb)))).\nhave x1 :=(gtn_eqF (ltnW(ltnW hb))).\ncase ok: (odd k); last first.\n  move/eqP; rewrite addnC lucas_plus_lucas ? leq_BD //  x0 x1 !andbF /=.\n  rewrite -{1} (subnKC km) addnAC addnn - add1n eqn_add2r.\n  by move/andP => [/eqP ea _]; move:(f_equal odd ea); rewrite odd_double.\ncase: (ltnP (lucas (m + k)) (lucas (m - k))) => hh.\n  by rewrite (eqP (ltnW hh))=> h; move: (lucas_gt0 n); rewrite h.\nmove => hc.\nhave: lucas (m + k) == lucas (m - k) + lucas n.\n by rewrite - {1} (subnK hh) - hc addnC.\ncase /orP: (leq_total (m - k) n) => la.\n  rewrite lucas_plus_lucas // (gtn_eqF  hb) x0 /= => /andP[_].\n  by rewrite - {1} (subnK km) -addnA -addn2 eqn_add2l addnn (eqn_double k 1) k1.\nrewrite (addnC (lucas _)) lucas_plus_lucas // (gtn_eqF  hb) x0 /= => /andP[].\nmove/eqP => <- /eqP ea; move:(f_equal odd ea).\nby rewrite -{1} (subnK km) -addnA addnn oddD /= odd_double addbF; case:odd.\nQed.\n\nLemma fib_times_fib_is_lucas m n k: k <= m -> \n  lucas n == (fib m) * (fib k) = \n  [|| (m==3) && [|| (k==1) && (n==0), (k==2) && (n==0) | (k==3) && (n==3)],\n    (k==1) && [|| (n==1)&&(m==1), (n==1) &&(m==2) | (n==2) && (m==4) ] |\n    (k==2) && [|| (n==1) &&(m==2) | (n==2) && (m==4) ] ].\nProof.\nset H := lucas_injective_bis.\ncase m3:(m==3).\n   rewrite (eqP m3) mulnC (fib_times_lucas_is_lucas n  0 k) /= !andbF !orbF.\n   by rewrite orbA - andb_orl (andbC (k == 3)).\ncase k1: (k == 1).\n  rewrite /= (eqP k1) muln1 eq_sym (fib_eq_lucas) /=.\n  case n0: (n==0); first by rewrite (eqP n0) /= m3.\n  by case n1: (n==1); rewrite orbF //  (eqP n1) /= !orbF.\ncase k2: (k == 2).\n  rewrite /= (eqP k2) muln1 eq_sym (fib_eq_lucas) m3 /= => /gtn_eqF ->.\n  by rewrite andbF.\nmove => le1 /=;apply/negP => h.\ncase:(ltnP k 4) => k4.\n  move: k4;rewrite leq_eqVlt eqSS; case /orP => k4.\n    move: le1 h; rewrite (eqP k4) (fib_times_lucas_is_lucas n  0 m) => m2.\n    by rewrite m3 (gtn_eqF m2) (gtn_eqF (ltnW m2)) /= andbF.\n  move: k4; rewrite !ltnS leq_eqVlt k2 ltnS leq_eqVlt k1 ltnS leqn0 /= =>/eqP.\n  by move => kz; move: (gtn_eqF (lucas_gt0 n)); rewrite (eqP h) kz muln0.\nmove: (f_equal (muln 5) (eqP h));rewrite mulnA lucas_lucas2 // => h1.\nhave la: m < m + k  by rewrite -{1} (addn0 m) ltn_add2l (ltnW (ltnW(ltnW k4))).\nhave bnd1:= (leq_add (leq_trans (ltnW k4) le1) k4).\nhave bnd2 :=(subnK (ltnW(ltnW bnd1))).\nset q := (m + k - 5) in bnd2.\nmove:(lucas5S q); rewrite bnd2 => ea.\nhave eb: lucas (m - k) <= lucas q. \n   case emk: (k==m). \n     rewrite -(eqP emk) subnn; apply: ltnW; apply:(@lucas_monotone 2).\n     by rewrite /= -(leq_add2r 5) bnd2 bnd1.\n  have mp:=(ltn_predK (leq_trans k4 le1)).\n  have mp1: m - k <= m.-1 by rewrite -(leq_add2r k) (subnK le1) -ltnS -addSn mp.\n  apply: lucas_monotone;rewrite subn_gt0 ltn_neqAle emk le1 (leq_trans mp1) //.\n  by rewrite  -(leq_add2r 5) bnd2 -addSnnS mp leq_add2l.\nhave: lucas (m - k) < 2 * lucas q. \n  by apply: (leq_ltn_trans eb); rewrite -[X in X< _] mul1n ltn_mul2r lucas_gt0.\nrewrite - (ltn_add2l (lucas (m + k))) => sa.\nhave sb: 5 * lucas n <= (lucas (m + k)) + (lucas (m - k)).\n  rewrite h1; case: odd => //; apply: leq_BD.\nmove: (leq_ltn_trans sb sa); rewrite ea - addnA -mulnDl - mulnDr - lucasSS.\nrewrite ltn_mul2l /= => e1.\ncase: (ltnP q.+1 n) => e3.\n   have: 0 < q.+2 <= n by [].\n   by move/lucas_monotone; rewrite leqNgt e1.\nhave ec:  (lucas (m + k)) - (lucas (m - k)) <=  5 * lucas n.\n  rewrite h1; case: odd => //; apply: leq_BD.\nhave: 0 < (2 * lucas q + (lucas q - lucas (m - k))).\n  move:(lucas_gt0 q); rewrite - double_gt0 - mul2n => pa.\n  apply: (leq_trans pa); apply: leq_addr.\nmove:(addnBA (5 * lucas q.+1 + 2 * lucas q)  eb).\nrewrite - 2!addnA -mulSnr - ea  -(ltn_add2l (5* lucas q.+1)) addn0.\nmove => -> ed; move: (leq_trans ed ec); rewrite ltn_mul2l /= ltnNge => /negP.\ncase; case: (posnP n) => np; last by apply: lucas_monotone; rewrite np e3.\nhave: 0 < 3 <= q.+1 by rewrite /= -ltnS ltnS ltnS -(leq_add2r 5) bnd2.\nby move/lucas_monotone; apply: leq_trans; rewrite np.\nQed.\n\n\nLemma fib_sum_square_is_fib_square m n k: \n   0 < m <= n -> (fib m)^2  + (fib n)^2 = (fib k)^2 -> False.\nProof.\nmove => /andP [la lb] hb.\ncase: (ltnP n k) => cp; last first.\n  move:(fib_monotone cp);  rewrite leqNgt => /negP; case.\n  by rewrite -ltn_sqr -(add0n (fib n ^ 2)) -hb ltn_add2r sqrn_gt0 fib_gt0.\nmove:(fib_monotone cp); rewrite -(leq_pmul2l (m:=2)) // => sa.\ncase: (ltngtP 1 n).\n+ move/fib_mon1 => sb;  move:(leq_trans sb sa); rewrite leqNgt => /negP.\n  case;rewrite -ltn_sqr !expnMn - hb -[3^2]/(5 + 2^2) mulnDr mulnDl ltn_add2r.\n  apply: (@leq_ltn_trans (4 * fib n ^ 2)).\n    by rewrite leq_pmul2l // leq_sqr fib_monotone.\n  by rewrite ltn_pmul2r // expn_gt0 fib_gt0 // (leq_trans la lb).\n+ by rewrite ltnNge (leq_trans la lb).\n+ move => n1; move: hb; rewrite -n1; move /square_plus1_square => fz.\n  by move: (fib_gt0 la); rewrite fz.\nQed.\n\nLemma lucas_sum_square_is_lucas_square m n k: \n   m <= n -> (lucas m)^2  + (lucas n)^2 = (lucas k)^2 -> False.\nProof.\nmove => la hb.\ncase kz: (k==0).\n   case n1: (n == 1). \n       by move:la hb; rewrite (eqP kz)(eqP n1); case:m => [|[|]].\n   have lb: 1 <= lucas m ^ 2  by rewrite (ltn_sqr 0) lucas_gt0.\n   have lc: 4 <= lucas n ^ 2.  \n      move:n1;rewrite (leq_sqr 2); case: (n) => [|[|u _]] //.\n      by apply: ltnW;apply: (@lucas_monotone 2).\n  by move: (leq_add lb lc); rewrite hb (eqP kz).\ncase: (ltnP n k) => cp; last first.\n  have: 0 < k <= n by rewrite lt0n kz cp.\n  move/lucas_monotone; rewrite leqNgt => /negP; case.\n  by rewrite -ltn_sqr -(add0n (lucas n ^ 2)) -hb ltn_add2r sqrn_gt0 lucas_gt0.\nhave HH x: 8<  x.+3 ^ 2 by rewrite (leq_sqr 3 x.+3) //.\nhave Ha x : x ^2 = 5 -> False.\n   by case: x => [|[|[|x h]]] //; move: (HH x); rewrite  h.\nhave Hb x : x ^2 = 8 -> False.\n   by case: x => [|[|[|x h]]] //; move: (HH x); rewrite  h.\ncase: (ltnP 2 n); last first.\n  rewrite leq_eqVlt ltnS  leq_eqVlt ltnS leqn0; case/or3P => n1.\n  + move: la hb; rewrite (eqP n1);rewrite leq_eqVlt ltnS  leq_eqVlt ltnS leqn0.\n    case/or3P => m1.\n    - by rewrite (eqP m1) addnn => /double_square_square.\n    - by rewrite (eqP m1) addnC => /square_plus1_square.\n    - rewrite (eqP m1) -[LHS]/13; case: (k) => [|[|[|x h]]] //.\n      suff // : 0 < 3<=x.+3 by  move/lucas_monotone; rewrite -leq_sqr -h. \n  +  move: hb; rewrite (eqP n1); move/square_plus1_square => lz.\n     by move:(lucas_gt0 m); rewrite lz.\n  +  by move: la hb; rewrite (eqP n1) leqn0 => /eqP -> /esym /Hb.\nmove /lucas_mon1 => sb.\nhave: 0 < n.+1 <= k by rewrite cp.\nmove/lucas_monotone; rewrite -(leq_pmul2l (m:=2)) // => sa.\nmove:(leq_trans sb sa); rewrite leqNgt => /negP; case.\nrewrite -ltn_sqr !expnMn - hb -[3^2]/(5 + 2^2) mulnDr mulnDl ltn_add2r.\ncase mz: (m==0).\n  move: hb; rewrite (eqP mz);  case:(n) =>[| [| n1]].\n  + by move/esym/Hb.\n  + by move/esym/Ha.\n  + move => _; apply: (@leq_trans 45) => //;rewrite (@leq_pmul2l 5 9) //.\n    by rewrite (leq_sqr 3); apply:(@lucas_monotone 2).\napply: (@leq_ltn_trans (4 * lucas n ^ 2)).\n  by rewrite leq_pmul2l // leq_sqr lucas_monotone // la lt0n mz.\nby rewrite ltn_pmul2r // expn_gt0 lucas_gt0.\nQed.\n\nLemma lucas_lucas_fib_square m n k: m <= n ->\n  ((lucas m)^2 + (lucas n^2) == (fib k)^2) = [&& m==2, n==3 & k==5].\nProof.\nhave H x: lucas x = 0 -> False.\n   by move/eqP;rewrite (gtn_eqF(lucas_gt0 x)).\nmove => lemn; apply/eqP/idP; last first.\n  by move =>/and3P [/eqP -> /eqP -> /eqP ->].\nmove:lemn;rewrite leq_eqVlt; case/orP => lmn.\n  by rewrite (eqP lmn) addnn => /double_square_square => /H.\ncase m0: (m==0).\n  by rewrite (eqP m0) addnC => /square_plus4_square /H.\ncase m1: (m==1).\n   by rewrite (eqP m1) addnC => /square_plus1_square /H.\nhave m2: 2 <= m by move: m0 m1; clear; case:m => [|[]].\nhave la: 3 <= lucas m by apply: (@lucas_monotone 2).\nhave lb: 4 <= lucas n. \n    by apply: (@lucas_monotone 3); rewrite /=(leq_ltn_trans m2 lmn).\nhave lc: 25 <= lucas m ^ 2 + lucas n ^ 2.\n  move: la; rewrite - leq_sqr => la.\n  move: lb; rewrite - leq_sqr => lb.\n  by rewrite (leq_add la lb).\nmove => h; have ld: 5 <= (fib k) by rewrite -leq_sqr - h.\nmove: h ld; case:k => [|[|[| [| [|]]]]] //; case.\n  case lm2: (m==2).\n    rewrite (eqP lm2) => /eqP.\n    rewrite -[fib 5 ^ 2]/(lucas 2 ^ 2 + lucas 3 ^ 2) eqn_add2l.\n    by rewrite eqn_sqr lucas_injective_bis => ->.\n  have m3: 0 < 3 <= m by rewrite /= ltn_neqAle eq_sym lm2 m2.\n  have: 0 < 4 <= n by rewrite /= (leq_trans  _ lmn).\n  move/lucas_monotone ; rewrite -leq_sqr => ha.\n  move:(lucas_monotone m3); rewrite -leq_sqr => hb h. \n  by move:(leq_add hb ha); rewrite h.\nhave Ha a b: a <= a - b + b.\n   case /orP: (leq_total a b) => lab; last  by rewrite subnK.\n    move:(lab); rewrite {1} /leq; move => /eqP ->//.\nmove => k.\nhave ->: k.+2.+4 = k+6 by rewrite !addnS addn0.\nhave l05: 0 < 5 by [].\nhave l5_12: 5 <= 12 by [].\nmove:(lucas5S (k.*2+7)); rewrite -(addnA _ 7 5) -[7 + 5]/12 => Lk h _.\nset x := 5*( (lucas m.*2 + lucas n.*2)).\nhave: (x <= lucas (k.*2+12) + 22) && (lucas (k.*2+12) <= x + 22).\n  move /eqP: h; rewrite -(eqn_pmul2l l05).\n  rewrite !lucas_square mulnA lucas_lucas2 ?leqnn // addnn subnn lucas0.\n  have ->: odd (k + 6) = ~~(odd k.+1) by rewrite oddD addbF/=; case: odd.\n  pose T b x := (if b then subn else addn) x 2.\n  have Ta: forall b x, x <= (T b x)  + 2. \n     by rewrite /T;move => b y; case b => //; rewrite -addnA leq_addr.\n  have Tb: forall b x, (T b x) <= x + 2. \n      rewrite /T;move => b y; case b => //; apply: leq_BD.\n  rewrite doubleD if_neg => /eqP ha; apply/andP; split.\n     move:(Tb (odd k.+1)  (lucas(k.*2 + 12))); rewrite -(leq_add2r 20) - addnA.\n     move: (leq_add (Ta (odd m)  (lucas m.*2)) (Ta (odd n)  (lucas n.*2))).\n     rewrite addnACA; rewrite - (leq_pmul2l l05) (mulnDr _ _ 4) ha -/x.\n     apply: leq_trans.\n   apply: (leq_trans(Ta (odd k.+1)  (lucas(k.*2 + 12)))).\n   rewrite (addnA _ 20 2) leq_add2r /T -ha /x - (mulnDr 5 _ 4) leq_pmul2l //.\n   rewrite -[4]/(2 +2) addnACA; apply: leq_add; apply: Tb.\nmove /andP => [ha hb].\nhave le: lucas (k.*2+12) +22 < 5* lucas (k.*2 +9).\n   rewrite Lk (addnS k.*2 8) (addnS k.*2 7).\n   rewrite lucasSS - addnA mulnDr ltn_add2l(mulnDl 3 2) ltn_add2l mul2n.\n   rewrite (ltn_double 11); apply: (@lucas_smonotone 5); rewrite l05 //=.\n   by rewrite -addSnnS -{1} (add0n 6) leq_add2r.\nhave hc: 5 * lucas n.*2 <= x by rewrite /x mulnDr leq_addl.\nmove: (leq_ltn_trans (leq_trans hc ha) le); rewrite ltn_pmul2l //.\ncase: (ltngtP (k.*2 +8)  n.*2 ) => hd.\n    by rewrite ltnNge; move/negP; case; apply: lucas_monotone;rewrite addnS hd. \n  have he: x + 22 <= 5 * (lucas n.*2.+1) + 22.\n    move: lmn; rewrite - ltn_double => sa.\n    have hx:= (ltn_predK sa). \n    rewrite leq_add2r /x (leq_pmul2l l05) -{2}hx lucasSS addnC hx leq_add2l. \n    by apply: lucas_monotone; rewrite (ltn_double 0) lt0n m0 - ltnS hx //.\n  have : 22 <3 * lucas (k.*2 +7). \n    apply: ltnW; rewrite (@leq_pmul2l 3 8) => //; apply: (@lucas_smonotone 4).\n    by rewrite /= (addnA _ 2 5) leq_addl.\n  rewrite - (ltn_add2l (5 * lucas n.*2.+1)) => hf.\n  move: (leq_ltn_trans (leq_trans hb he) hf).\n  rewrite Lk ltn_add2r (ltn_pmul2l l05) ltnNge => /negP; case.\n  by apply:lucas_monotone; rewrite - addnS hd.\nmove /eqP: hd; rewrite -(doubleD k 4) eqn_double eq_sym => /eqP hd _.\nmove:ha hb; rewrite /x Lk hd doubleD mulnDr addnC (addnS k.*2  7) - 2!addnA.\nrewrite !leq_add2l (addnS k.*2 6) (addnS k.*2 5) lucasSS (addnS k.*2 4) lucasSS.\nrewrite addnAC addnn -(mul2n (lucas _)) mulnDr mulnA => ec ed.\nset u := lucas (k.*2 + 4).+1 + 3 * lucas (k.*2 + 4).\nhave : 22 < u. \n   apply: (@leq_trans (lucas 5 + 3 * (lucas 4))) => //.\n   by apply: leq_add; rewrite ?(@leq_pmul2l 3)-? addnS  //;\n       apply: (lucas_monotone); rewrite /= leq_addl.\nrewrite -(ltn_add2l (5 * lucas m.*2)) => ef.\nmove:(leq_ltn_trans ed ef); rewrite (mulSnr 5) - addnA ltn_add2r ltn_pmul2l //.\nmove => ww. \ncase: (ltngtP (k.*2 + 4).+2 (m.*2)) => eg.\n+ have: 0 < (k.*2 + 4).+3 <= m.*2 by rewrite eg.\n  move/lucas_monotone; rewrite -(leq_pmul2l l05) => sa.\n  move:(leq_trans sa ec); rewrite lucasSS mulnDr (mulSnr 5) - 2!addnA. \n  rewrite addnC leq_add2l lucasSS mulnDr (addnC _ 22) (mulSn 4) - addnA.\n  rewrite leq_add2l (mulnDl 2 3) addnA leq_add2r.\n  have: 0 < 4 <= (k.*2 + 4).+1 by rewrite /= -addSn leq_addl.\n  move/lucas_monotone;rewrite -(@leq_pmul2l 4) // => sb sc. \n  have sd: 22 < 4* lucas 4 by [].\n  move: (leq_trans (leq_ltn_trans sc sd) sb).\n  rewrite ltnNge; move/negP; case; apply: leq_addr.\n+ move: ww; rewrite ltnNge => /negP; case; apply: lucas_monotone. \n  by rewrite - (ltnS m.*2)  eg double_gt0 lt0n m0.\n+ move:ec; rewrite - eg  lucasSS mulnDr (mulSnr 5) - 2!addnA leq_add2l.\n  rewrite (addnC _ 22) addnA (mulnDl 2 3) leq_add2r addnS lucasSS mul2n - addnn.\n  rewrite - addnA leq_add2l addnS lucasSS leq_add2l.\n  move: eg; rewrite -!addnS -(doubleD k 3) =>/eqP; rewrite eqn_double =>/eqP ha.\n  have L1: lucas 1 = 1 by rewrite lucas1.\n  have L2: lucas 2 = 3 by [].\n  have L3: lucas 3 = 4 by rewrite lucasSS.\n  have L4: lucas 4 = 7 by rewrite lucasSS L3 L2.\n  have L5: lucas 5 = 11 by rewrite lucasSS L4 L3.\n  have L6: lucas 6 = 18 by rewrite lucasSS L5 L4.\n  have L7: lucas 7 = 29 by rewrite lucasSS L6 L5.\n  have F5: fib 5 = 5 by [].\n  have F6: fib 6 = 8 by rewrite fibSS F5.\n  have F7: fib 7 = 13 by rewrite fibSS F6 F5.\n  have F8: fib 8 = 21 by rewrite fibSS F6 F7.\n  move: h; rewrite hd - ha; case k => [|[ | [| k']]];\n     rewrite ? L3 ? L4 ? L5 ? L6 ? F5 ? F6 ? F7 ? F8 //.\n  have: 0 < 8 <= ((k'.+3).*2 + 2) by rewrite /= addn2 !doubleS //.\n  move/lucas_monotone => sa _ sb.\n  by move: (leq_trans sa sb); rewrite lucasSS L7 L6.\nQed.\n\nLemma fib_sum_square_is_fib_square_bis m n k: \n  (fib m)^2  + (fib n)^2 == (fib k)^2 =\n    ((m==0) && (fib n== fib k)) || ((n == 0) && (fib m== fib k)).\nProof.\nwlog: m n / m <= n.\n   move => H; case/orP:(leq_total m n); first by apply: H.\n   by move => h; rewrite addnC orbC; apply: H.\nmove => mn; case: (posnP m) => mp.\n by  rewrite mp add0n eqn_sqr; case: (posnP n) => np; rewrite ?orbF//?np ?orbb.\nrewrite (gtn_eqF (leq_trans mp mn)) /=. \nby apply/eqP /fib_sum_square_is_fib_square; rewrite mn mp.\nQed.\n\n\nLemma lucas_fib_lucas_square m n k:\n  ((fib m)^2 + (lucas n^2) == (fib k)^2) =\n    ((m==0) && (fib k == lucas n)) || [&& k ==5, m==4 & n==3].\nProof.\ncase :(posnP m) => mz; first by rewrite mz eqn_sqr eq_sym /= !andbF orbF.\nhave fmp:=(fib_gt0 mz).\nhave fm: ~(fib m = 0) by move => h; move: fmp; rewrite h.\ncase:n => [|[|[| [|n]]]].\n+ by rewrite /= !andbF; apply/negP => /eqP /square_plus4_square.\n+ by rewrite /= !andbF; apply/negP => /eqP /square_plus1_square.\n+ rewrite -[lucas 2]/(fib 4).\n  by rewrite (fib_sum_square_is_fib_square_bis) (gtn_eqF mz) !andbF.\n  rewrite -[lucas 3 ^ 2]/(4 ^2) square_plus16_square (gtn_eqF fmp)  /=.\n+ by rewrite (fib_eq m 4) (fib_eq k 5) /= !andbF !orbF andbT andbC.\n+ rewrite !andbF /=; apply/negP => /eqP.\nhave ln :  ~(lucas n.+4 = 0) by move => h; move: (lucas_gt0 n.+4);rewrite h.\ncase: (ltngtP (fib m) (lucas n.+4)); last first.\n    by move => ->; rewrite addnn; move/double_square_square.\n  move => sa sb. \n  case: (ltnP m k) => ha.\n    move: (mz); rewrite leq_eqVlt; case/orP => m2.\n        by move: sb; rewrite addnC - (eqP m2); move /square_plus1_square.\n    move:(fib_mon1 m2); rewrite - leq_sqr !expnMn => h.\n    move: (fib_monotone ha); rewrite - leq_sqr => sc.\n    have: (lucas n.+4) ^2 < (fib m)^2 by rewrite ltn_sqr sa.\n    rewrite -(ltn_add2l (fib m ^ 2)) sb addnn - mul2n => sd.\n    move: (leq_ltn_trans sc sd); rewrite -(@ltn_pmul2l 4) // mulnA => hc.\n    by move:(leq_ltn_trans h hc); rewrite (ltn_pmul2r) // sqrn_gt0.\n  move: (fib_monotone ha); rewrite -leq_sqr - sb leqNgt => /negP; case.\n  by rewrite -{1} (addn0 (fib m ^ 2)) ltn_add2l sqrn_gt0 lucas_gt0.\nmove => sa sb; case: (ltngtP k (n.+4.+2))=> kn4. \n+ have hh: lucas n.+4 < fib k. \n    by rewrite  -ltn_sqr -(add0n  (lucas n.+4 ^ 2)) - sb ltn_add2r  sqrn_gt0.\n  rewrite ltnS in kn4; move: (leq_trans hh (fib_monotone kn4)).\n  by rewrite lucas_fib //= -{2} (addn0 (fib n.+4.+1)) ltn_add2l ltn0.\n+ move:(fib_monotone kn4); rewrite fib3S -leq_sqr.\n  move: sa; rewrite -ltn_sqr -(ltn_add2r (lucas n.+4 ^ 2)) sb addnn => sc sd.\n  move: (leq_ltn_trans sd sc); rewrite ltnNge => /negP; case.\n  rewrite sqrnD lucas_fib //= sqrnD 2!doubleD - 2!addnA -(muln2 (fib n.+4.+1)). \n  have: (fib n.+4.+1 ^ 2).*2 + (fib n.+3 ^ 2).*2  <= (fib n.+4.+1 * 2) ^ 2. \n    rewrite expnMn - doubleD  (mulnA _ 2 2) muln2 muln2 leq_double - addnn.\n    by rewrite leq_add2l leq_sqr fib_monotone // ltnS; apply: ltnW; apply: ltnW.\n  rewrite -(@leq_add2r (fib n.+4 ^ 2 + 2 * (fib n.+4.+1 * 2 * fib n.+4))) => ww.\n  apply:leq_trans ww; rewrite - addnA leq_add2l leq_add2l (mulnC _ 2) -mul2n. \n  apply: (@leq_trans (2 * (2 * (fib n.+4.+1 * fib n.+4)))).\n    by rewrite !leq_pmul2l //? fib_gt0 // fib_monotone.\n  by rewrite - mulnA leq_addl.\nmove /eqP: sb; rewrite kn4 lucas_fib //= fib3S (fib3S n.+3) addnAC - addnA.\nrewrite -fibSS - !mul2n 2!sqrnD  2!expnMn mulnAC addnA eqn_add2r addnA.\nrewrite (mulSnr 3) (mulSn 3) - (addnA (fib n.+4 ^ 2)) addnC  eqn_add2l.\nrewrite addnA eqn_add2r => sx.\nhave sc: 3 * (fib n.+3)^2 < 2 *(fib n.+4)^2.\n  have ww: 1 < n.+3 by [].   \n  move:(fib_mon1 ww); rewrite - (@leq_pmul2r (fib n.+3)) ? fib_gt0 // => h.\n  rewrite - mulnn - mulnn 2!mulnA; apply: (leq_ltn_trans h).\n  by rewrite (ltn_pmul2l) // ?fib_smonotone //= muln_gt0 fib_gt0.\nhave sb: 3 * fib n.+4 ^ 2 < (fib n.+4.+2)^2.\n  rewrite (fibSS (n.+4))  (fibSS (n.+3)) addnAC addnn sqrnD - addnA.\n  rewrite -mul2n expnMn (mulSnr 3) -addnA -[X in X < _] (addn0) ltn_add2l.\n  by rewrite addn_gt0 sqrn_gt0 fib_gt0.\ncase: (ltngtP m n.+4.+1).\n+ rewrite ltnS; move/fib_monotone; rewrite leqNgt - ltn_sqr.\n  by rewrite -(ltn_add2r (2 * fib n.+4 ^ 2)) - mulSn - (eqP sx) ltn_add2l sc.\n+ move/fib_monotone; rewrite -leq_sqr => sd.\n  by move:(leq_trans sb sd); rewrite - (eqP sx) ltnNge leq_addr.\n+ move => eq1.\n  move: sx; rewrite (fib_square_succ n.+2) addnC mulnDr eqn_add2l eq1.\n  rewrite -mulnn mulnA eqn_pmul2r ? fib_gt0 // fib4S - {2}(addn0 (3 *_)).\n  rewrite eqn_add2l double_eq0 fib_eq0 //.\nQed.\n\n\n(** Properties of ordered sequences *)\n\nDefinition ggen := [rel m n | m >= n.+2].\nDefinition llen := [rel n m | ggen m n]. \nDefinition even := [pred n | ~~ (odd n) ].\n\nLemma sorted_gtn l: uniq l -> sorted gtn (rev (sort leq l)).\nProof.\nrewrite rev_sorted ltn_sorted_uniq_leq sort_uniq (sort_sorted leq_total) => ->.\ndone.\nQed.\n\nLemma transitive_llen:  transitive llen.\nProof. by move => x y z /= sa /ltnW sb; exact: (ltn_trans sa sb). Qed.\n\nLemma irreflexive_llen: irreflexive llen.\nProof. by move => x /=;  rewrite ltnNge leqnSn. Qed.\n\nLemma sorted_ggenW s : sorted ggen s -> sorted gtn s.\nProof.\nby case: s => //= n s; elim: s n => //= m s IHs n /andP [/ltnW -> /IHs].\nQed.\n\nLemma sorted_ggenS s : all even s -> sorted gtn s -> sorted ggen s.\nProof.\ncase: s => // n s; elim: s n => //= m s Ihs n /andP [on ha] /andP [lnm hb].\nrewrite Ihs //; case/andP:ha => /negbTE => om _; move: lnm.\nby rewrite (evenE(negbTE on)) (evenE om) - doubleS leq_double ltn_double andbT.\nQed.\n\nLemma sorted_llen_uniq l: sorted llen l -> uniq l.\nProof.\napply: (sorted_uniq transitive_llen irreflexive_llen).\nQed.\n\nLemma sorted_ggen_uniq l : sorted ggen l -> uniq l.\nProof. \nby rewrite - {2} (revK l) - rev_sorted rev_uniq; apply: sorted_llen_uniq.\nQed.\n\nLemma uniq_llen a l: sorted llen (a :: l) -> uniq l.\nProof. by move/path_sorted => /sorted_llen_uniq. Qed.\n\n\nLemma path_all_llen a l: path llen a l -> all (llen a) l.\nProof. by apply: (order_path_min transitive_llen). Qed.\n\nLemma sorted_ggen_succ l: sorted ggen (succ_seq l) = sorted ggen l.\nProof.\nby case: l => //= a l; elim: l a => // a l H b /=; rewrite ltnS H.\nQed.\n\nLemma sorted_llen_succ l: sorted llen (succ_seq l) = sorted llen l.\nProof.\nby case: l => //= a l; elim: l a => // a l H b /=; rewrite ltnS H.\nQed.\n\nLemma mkseq_uniq (f: nat -> nat) a n: \n  injective f -> uniq [seq (f i) | i <- iota a n].\nProof. move => h; rewrite (map_inj_uniq h); exact: iota_uniq.  Qed.\n\nLemma sorted_llen_mkseq f a n: (forall u, llen (f u) (f u.+1)) ->\n  sorted llen [seq (f i) | i <- iota a n].\nProof.\nmove => h; case: n => // n /=; elim: n a => // n Hrec a /=. \nrewrite (Hrec a.+1) andbT; exact: (h a). \nQed.\n\nLemma sorted_llen_mkseq_e a n: sorted llen [seq i.*2 | i <- iota a n].\nProof. by apply:sorted_llen_mkseq => u /=; rewrite doubleS !ltnS. Qed.\n\nLemma sorted_ggen_sdouble n: sorted ggen (rev (mkseq double n)).\nProof. by rewrite rev_sorted; apply:sorted_llen_mkseq_e. Qed.\n\nLemma sorted_ge2_all_ps l: sorted ggen (rcons l 0) ->\n   all (leq 2) l /\\ all (leq 1) l.\nProof.\nrewrite - rev_sorted rev_rcons; move/path_all_llen; rewrite all_rev => h.\nby split; apply/allP => [x /(allP h) //= /ltnW].\nQed.\n\n(**  Definition of [Zeck_val ] etc *)\nDefinition Zeck_val l := \\sum_(i <-l) fib (i.+2).\nDefinition Zeck_valp l := \\sum_(i <-l) fib (i.+1).\nDefinition Zeck_valpp l := \\sum_(i <-l) fib i.\n\nLemma Zeckv_nil : Zeck_val nil = 0.\nProof. by rewrite /Zeck_val big_nil. Qed.\n\nLemma Zeckv_cons n l: Zeck_val (n ::l) = fib (n.+2) + Zeck_val l.\nProof. by rewrite /Zeck_val big_cons. Qed.\n\nLemma Zeckvp_cons n l: Zeck_valp (n ::l) = fib (n.+1) + Zeck_valp l.\nProof. by rewrite /Zeck_valp big_cons. Qed.\n\nLemma Zeckv_rev l: Zeck_val (rev l) = Zeck_val l.\nProof. by rewrite /Zeck_val sum_rev. Qed.\n\nLemma Zeckvp_rev l: Zeck_valp (rev l) = Zeck_valp l.\nProof. by rewrite /Zeck_valp sum_rev. Qed.\n\nLemma Zeck_valppE l: Zeck_val l = Zeck_valp l +  Zeck_valpp l. \nProof.\nrewrite /Zeck_val/Zeck_valp/Zeck_valpp. \nby elim:l => [| a l H]; rewrite ?big_nil // !big_cons addnACA fibSS H.\nQed.\n\nLemma Zeckv_pos n l: 0 < Zeck_val (n ::l).\nProof. by rewrite Zeckv_cons addn_gt0 fib_gt0. Qed.\n\nLemma Zeckv_bound0 n l : path gtn n l -> (Zeck_val (n::l)).+2 <= fib (n.+4).\nProof.\nelim: l n => [n _ | a l Hrec /= n/andP []].\n  rewrite Zeckv_cons Zeckv_nil - addnS - addnS (fibSS n.+2) addnC.\n  by rewrite leq_add2r (@fib_monotone 3).\nrewrite - 3!ltnS => /fib_monotone la /Hrec lb. \nby rewrite fibSS addnC Zeckv_cons -addnS ltn_add2l (leq_trans lb la).\nQed.\n\nLemma Zeckv_bound1 n l : path gtn n l -> Zeck_val (n::l) < fib (n.+4).\nProof. by move/Zeckv_bound0 => /ltnW. Qed.\n\nLemma Zeckv_bound2 n l : path ggen n l -> Zeck_val (n::l) < fib (n.+3).\nProof.\nelim: l n => [n _ |  a l Hrec /= n/andP []].\n  by rewrite Zeckv_cons Zeckv_nil addn0 fib_smonotone_bis.\nrewrite - ltnS  => /fib_monotone la /Hrec lb.\nby rewrite fibSS Zeckv_cons ltn_add2l (leq_trans lb la).\nQed.\n\nLemma Zeckv_bound3 l n: uniq l -> (all (leq^~ n) l) -> \n    (Zeck_val l).+2 <= fib n.+4.\nProof.\nmove /sorted_gtn;set l' := (rev (sort leq l))  => sa /allP sb.\nhave hc: perm_eq l l'.\n  rewrite /l' perm_sym; apply:(@perm_trans _  (sort leq l)).\n    by elim:(sort leq l)=> // a s h; rewrite rev_cons perm_rcons perm_cons.\n by apply/permPl; apply: perm_sort.\nhave ->: (Zeck_val l) = (Zeck_val l') by apply: perm_big.\nhave:(all (leq^~ n) l').\n  apply/allP => x; rewrite -(perm_mem hc x); apply: sb.\nmove: sa; case l'. \n  by move => _ _; rewrite Zeckv_nil  -[1]/(fib 2) //; apply:fib_smonotone_bis. \nmove => a s pa pb; apply: (leq_trans (Zeckv_bound0 pa)).\nby apply: fib_monotone; rewrite !ltnS; apply/(allP pb); rewrite inE eqxx.\nQed.\n\nLemma Zeck2_unique (s s': seq nat) : sorted ggen s -> sorted ggen s' -> \n   Zeck_val s = Zeck_val s' ->  s = s'.\nProof.\nhave A a l: Zeck_val [::] = Zeck_val (a :: l) -> False.\n  by rewrite Zeckv_nil => h; move: (Zeckv_pos a l); rewrite - h.\nelim: s' s; first by  case => // a l _ _; move/ esym /A.\nmove => a l Hrec; case; first by move => _ _ /A.\nmove => a' l'; rewrite !Zeckv_cons => pa pb ec.\nsuff aux:(a' == a).\n  move /eqP: ec; rewrite (eqP aux) eqn_add2l => /eqP h.\n  by rewrite (Hrec l'  (path_sorted pa) (path_sorted pb) h).\nmove:(Zeckv_bound2 pa); rewrite Zeckv_cons ec.\nmove/ (leq_ltn_trans (leq_addr (Zeck_val l) (fib a.+2))) => /fib_monotone_bis.\nmove:(Zeckv_bound2 pb); rewrite Zeckv_cons -ec.\nmove/ (leq_ltn_trans (leq_addr (Zeck_val l') (fib a'.+2))) => /fib_monotone_bis.\nby rewrite !ltnS eqn_leq => -> ->.\nQed.\n\nDefinition odd_last l := if l is a::b then odd(last a b)  else 2.\n\nLemma Zeck_valp_aux l: sorted gtn l ->\n  exists (l': seq nat), \n  [/\\ sorted ggen l', odd_last l = odd_last l',\n    Zeck_val l = Zeck_val l', Zeck_valp l = Zeck_valp l' &\n     size l' <= size l ?= iff (sorted ggen l)].\nProof.\nhave Hb a s: Zeck_valp (a::s) = fib (a.+1) + Zeck_valp s. \n  by rewrite /Zeck_valp big_cons.\npose z l := (Zeck_val l, Zeck_valp l, odd_last l).\nhave He a l1 : z [:: a.+1, a & l1] = z (a.+2 :: l1).\n  have od: odd (last a.+2 l1)= odd (last a l1) by case: l1 => //=;case: odd.\n  by rewrite /z !Zeckv_cons !Hb addnA addnA - !fibSS /= od.\nhave Hf a l1 l2: z l1 = z l2 -> z (a :: l1) = z (a::l2).\n  rewrite /z !Zeckv_cons !Hb; case => eq1 eq2 eq3; rewrite eq1 eq2 /=.\n  suff: odd (last a l1) = odd (last a l2) by move => ->.\n  move: eq1 eq3; clear; case: l1; case: l2 => //.\n  + by move => u v h;move:(Zeckv_pos u v); rewrite -h Zeckv_nil.\n  + by move => u v h;move:(Zeckv_pos u v); rewrite h Zeckv_nil.\n  + by move => u la v lb //= _; case:odd; case:odd.\nsuff H: forall (a:nat) l, sorted gtn (a :: l) ->\n  exists (b:nat) s, [/\\  sorted ggen (b::s), z(a::l) = z(b::s), b <= a.+1 &\n  size s <= size l ?= iff sorted ggen (a::l) ].\n  case: l => //; first by move => _; exists nil.\n  by move => a l /H [b [s [pa  [pb  pc pd _] pf]]]; exists (b::s).\nmove =>  {l} a l.\nmove: {2} ((size l).+1) (ltnSn (size l))=> n; elim: n a l; first by case.\nmove => n Hrec a [_ _ | b l ]; first by exists a, nil. \nrewrite /= ltnS => lt1 /andP [lt2 pa].\nmove: lt2; rewrite leq_eqVlt; case /orP => [/eqP <- | lt3].\n  move: l lt1 pa; case; first by exists (b.+2), nil; rewrite ltnn.\n  move => c l /= pa /andP [pb pc].\n  move: (Hrec c l (ltn_trans (ltnSn (size l)) pa) pc).\n  move => [u [v [/= qa qb qc qd]]]; exists (b.+2), (u::v). \n  rewrite He (Hf b.+2 _ _ qb) /= qa ! ltnS (leq_trans qc pb) ltnn.\n  by split => //; apply/leqifP; rewrite !ltnS /= qd.\ncase ww: (path ggen b l).\n  by exists a, (b::l);rewrite /= lt3 ww; split => //; apply /leqif_refl.\nmove: (Hrec b l lt1 pa) => [c [l' [r1 /(Hf a _ _ ) -> r4]] sc].\nmove:(leq_ltn_trans r4 lt3); rewrite leq_eqVlt; case /orP => lt4; last first.\n  by exists a, (c:: l'); rewrite /= lt4 lt3 /= -ww mono_leqif.\nexists (a.+1), l'; rewrite  - (eqP lt4) He andbF.\nmove: sc; rewrite /sorted ww => /leqifP => /ltnW ss.\nhave K:size l' <= (size l).+1 ?= iff false by apply /leqifP; rewrite ltnS.\nsplit => //; move: r1; case l' => // d l'' /= /andP[ w ->].\nby rewrite (ltn_trans w (ltn_trans (ltnSn c) (ltnSn c.+1))).\nQed.\n\nLemma Zeck_valp_same (l1 l2: seq nat): sorted gtn l1 -> sorted gtn l2 ->\n    Zeck_val l1 =  Zeck_val l2 ->  \n    Zeck_valp l1 =  Zeck_valp l2 /\\  odd_last l1 = odd_last l2. \nProof.\nmove /Zeck_valp_aux => [l3 [pa -> -> -> _]] /Zeck_valp_aux [l4 [pb -> -> -> _]].\nby move/(Zeck2_unique pa pb) ->.\nQed.\n\n(** Existence of a representation *)\n\n\nFact fib_cont_aux1 n: exists i, fib i.+2 <= n.+1.\nProof. by exists 0. Qed.\n\nFact fib_cont_aux2 n i: fib i.+2 <= n.+1 -> i <= n.\nProof. by move /(leq_trans (fib_gen i.+1)); rewrite ltnS.  Qed.\n\nDefinition fib_content n := ex_maxn (fib_cont_aux1 n) (@fib_cont_aux2 n).\n\nLemma fib_contentP n (r := fib_content n):  fib r.+2 <= n.+1 < fib r.+3.\nProof.\nrewrite /r /fib_content;case:ex_maxnP => i sa sb; rewrite sa  /=.\nby case: (ltnP (n.+1) (fib i.+3)) => // /sb; rewrite ltnn.\nQed.\n\nLemma fib_content_lt n (r := fib_content n): n.+1 - fib r.+2 < fib r.+1.\nProof.\nmove :(fib_contentP n) => /andP; rewrite -/r; move => [/subnK -{1} <- ].\nby rewrite (fibSS r.+1) addnC ltn_add2l.\nQed.\n\nLemma fib_content_large m: m.+1 - fib (fib_content m).+2 <= m.\nProof. by rewrite fib_pos subSS leq_subr. Qed.\n\nLemma fib_content_eq n: fib_content ((fib n.+2).-1) = n.\nProof.\nmove: (fib_contentP (fib n.+2).-1). \nrewrite /= - fib_pos  => /andP[sa /fib_monotone_bis].\nrewrite !ltnS leq_eqVlt; case/orP; first by move/eqP. \nby move => /fib_smonotone_bis; rewrite ltnNge sa.\nQed.\n\n(** The Zeckendorf function *)\n\nFixpoint Zeck_rec n k:=\n   if k is k'.+1 then\n     if n is n'.+1 then let r := fib_content n' in \n       r:: Zeck_rec (n - (fib (r.+2))) k'\n    else nil\n   else nil.\nDefinition Zeck n := Zeck_rec n n.\n\n\nLemma Zeck_0 : Zeck 0 = nil.\nProof. by []. Qed.\n\nLemma Zeck_S' n (r := fib_content n) : \n   Zeck n.+1 = r :: (Zeck (n.+1 - (fib (r.+2)))).\nProof.\nhave Ha := fib_content_large.\nsuff aux: forall m n k1 k2, m <= k1 -> m <= k2 ->  n <= m ->\n    Zeck_rec n k1 = Zeck_rec n k2.\n  by congr cons; apply: (aux (n.+1 - fib (fib_content n).+2)).\nclear n r. \nelim; first by move => n k1 k2 _ _;rewrite leqn0 => /eqP ->; case: k1; case: k2.\nmove => m Hrec n; case => // k1; case => // k2; rewrite (leq_eqVlt n) ! ltnS.\nmove => mk1 mk2 /orP [ /eqP ->| lenm]; first by congr cons; apply:Hrec.\nby apply:  Hrec => //; apply: ltnW; rewrite ltnS.\nQed.\n\nLemma Zeck_S k n: fib k.+2 <= n < fib k.+3 ->\n  Zeck n = k :: Zeck (n - fib k.+2).\nProof.\ncase: n => [|n bd]; first by rewrite leqn0 fib_eq0.\nmove /eqP: (fib_partition (fib_contentP n) bd); rewrite eqSS eqSS Zeck_S'.\nby move/eqP ->.\nQed.\n\nLemma Zeck_fib n: Zeck (fib n.+2) = [:: n].\nProof.\nhave eq1:= (fib_pos n.+1).\nby rewrite eq1 Zeck_S' fib_content_eq - eq1 subnn Zeck_0.\nQed.\n\nLemma Zeck_1 : Zeck 1 = [:: 0].  Proof. exact: (Zeck_fib 0). Qed.\nLemma Zeck_2 : Zeck 2 = [:: 1].  Proof. exact: (Zeck_fib 1). Qed.\n\nLemma Zeck_ggen n: sorted ggen (Zeck n).\nProof.\nelim: n {-2} n (leqnn n) => [ [] | n Hr k] //;rewrite leq_eqVlt ltnS.\ncase /orP => //; [move/eqP => -> | by apply: Hr].\nmove: (fib_content_lt n)(fib_content_large n); rewrite Zeck_S' /= => sa sb.\nmove:(Hr _ sb) sa; case: (_ - _) => // v; rewrite Zeck_S' /= => -> la.\nmove/andP: (fib_contentP v) => [lb _]; move: (leq_ltn_trans lb la).\nby move/fib_monotone_bis; rewrite ltnS andbT.\nQed.\n\nLemma Zeck_uniq n: uniq (Zeck n).\nProof. exact: (sorted_ggen_uniq (Zeck_ggen n)).  Qed.\n\nLemma Zeck_zeck_val n: Zeck_val (Zeck n) = n.\nProof.\nelim: n {-2} n (leqnn n).\n  by move => n; rewrite leqn0 => /eqP ->; rewrite Zeck_0 Zeckv_nil.\nmove=> n IH n1; rewrite leq_eqVlt; case/orP=> [/eqP ->|Hn]; last first.\n  by apply: IH; rewrite -ltnS.\nrewrite Zeck_S' Zeckv_cons; move:(fib_content_large n) => h.\nby rewrite (IH _ h); apply: subnKC; move/andP: (fib_contentP n) => [].\nQed.\n\nLemma ZeckP l: sorted ggen l -> Zeck (Zeck_val l) = l.\nProof.\nmove => h.\nby apply: (Zeck2_unique (Zeck_ggen (Zeck_val l)) h); rewrite Zeck_zeck_val.\nQed.\n\nLemma Zeck_prop1 n: n != 0 -> exists a l, \n  [/\\ sorted llen (a::l), Zeck n = rev (a::l) & n = Zeck_val (a::l) ].\nProof.\nmove:(Zeck_ggen n)(Zeck_zeck_val n); case: n => // n.\nrewrite Zeck_S' - (revK (_ :: _)) /= rev_sorted split_rev.\nset u := last _ _; set v := behead _ => ra rb _.\nby exists u, v; split => //; rewrite - rb Zeckv_rev.\nQed.  \n\nLemma Zeck_is_minimal l n (L := Zeck n): \n   sorted gtn l -> Zeck_val l = n -> size L <= size l ?= iff (l == L).\nProof.\nmove => ha hb; apply /leqifP.\nmove: (Zeck_valp_aux ha) => [ s [ /ZeckP pa _ pc _]].\nrewrite  -pa - pc hb -/L; move /leqifP.\ncase wx: (sorted ggen l); first by rewrite - (ZeckP wx) hb !eqxx.\nby case wy: (l == L) => //; rewrite (eqP wy).\nQed.\n\n\n(** Least element of the canonical representation *)\n\nDefinition Zeck_li n := last n (Zeck n).\n\nLemma Zeck_val_bounded n: all (fun i => fib i.+2 <= n) (Zeck n).\nProof.\nrewrite - {1} (Zeck_zeck_val n) /Zeck_val;  elim: (Zeck n) => // a l H.\nrewrite /= big_cons leq_addr /=;apply /allP => [x /(allP H) h].\nby apply: (leq_trans h); rewrite leq_addl.\nQed.\n\nLemma Zeck_val_bounded1 n: all (fun i => i < n) (Zeck n).\nProof.\napply/allP => x /(allP (Zeck_val_bounded n)) h.\nexact: (leq_trans (fib_gen x.+1) h).\nQed.\n\nLemma Zeck_li_pr n: n != 0 ->  Zeck_li n < n.\nProof.\nmove: (Zeck_val_bounded1 n); rewrite/Zeck_li;case: n => // n. \nby rewrite (Zeck_S' n) => sa sb; apply: (allP sa); simpl; apply:mem_last.\nQed.\n\nLemma Zeck_li_prop1 n : all (leq (Zeck_li n)) (Zeck n).\nProof.\nrewrite /Zeck_li; case: n => // n. \nmove: (Zeck_prop1 (n:=n.+1) isT) => [a [l [pa -> _]]].\nrewrite rev_cons last_rcons all_rcons (leqnn) /= all_rev.\nby apply /allP => [x  /(allP (path_all_llen pa)) /ltnW /ltnW /=].\nQed.\n\nLemma Zeck_li_prop2 n k: \n   k < (Zeck_li n) -> all [pred z | k < z] (Zeck n).\nProof.\nby move => h; apply/allP => [x /(allP (Zeck_li_prop1 n))]; apply: leq_trans.\nQed.\n\n(** The function e *)\n\nDefinition Zeckp n := Zeck_valp (Zeck n).\n\nLemma Zeckp_0: Zeckp 0 = 0.\nProof. by rewrite /Zeckp Zeck_0 /Zeck_valp big_nil. Qed.\n\nLemma Zeckp_1: Zeckp 1 = 1.\nProof. by rewrite /Zeckp Zeck_1 /Zeck_valp big_cons big_nil. Qed.\n\nLemma Zeckp_eq0 n: (Zeckp n == 0) = (n == 0).\nProof. \ncase:n; first by rewrite Zeckp_0.\nby move => n; rewrite /Zeckp Zeck_S' /Zeck_valp big_cons addn_eq0 fib_eq0 //. \nQed.\n\nLemma Zeckp_prop00 l: sorted gtn l -> \n  Zeckp (Zeck_val l) =  Zeck_valp l /\\  \n  odd_last(Zeck (Zeck_val l)) =  odd_last l. \nProof.\nmove => h;rewrite /Zeckp; apply: Zeck_valp_same => //. \n  apply: sorted_ggenW; apply:Zeck_ggen.\nexact:Zeck_zeck_val.\nQed.\n\nLemma Zeckp_prop0 l: sorted gtn l -> Zeckp (Zeck_val l) =  Zeck_valp l.\nProof. by move /Zeckp_prop00 => []. Qed.\n\nLemma Zeck_odd_last_prop l: sorted gtn l -> \n  odd_last(Zeck (Zeck_val l)) =  odd_last l. \nProof. by move /Zeckp_prop00 => []. Qed.\n\nLemma Zeckp_prop1 (l: seq nat): uniq l -> Zeckp (Zeck_val l) =  Zeck_valp l.\nProof.\nmove /sorted_gtn;set l' := (rev (sort leq l)).\nhave hb:perm_eq (sort leq l) l by apply/permPl; apply: perm_sort.\nhave ha: forall (l: seq nat), perm_eq (rev l) l.\n  by elim => // a s h; rewrite rev_cons perm_rcons perm_cons.\nhave hc: perm_eq l l' by rewrite perm_sym;apply: (perm_trans (ha _ ) hb).\nhave ->: (Zeck_val l) = (Zeck_val l') by apply: perm_big.\nhave ->: (Zeck_valp l) = (Zeck_valp l') by apply: perm_big.\napply: Zeckp_prop0.\nQed.\n\nLemma Zeckp_prop1_bis l:  all (leq 1) l -> uniq l ->\n  Zeckp (Zeck_valp l) =  Zeck_valpp l.\nProof.\nmove => sb; rewrite (seq_prednK sb) /Zeck_valp /Zeck_valpp /succ_seq.\nmove/ map_uniq; rewrite big_map big_map; apply:Zeckp_prop1.  \nQed.\n\nLemma Zeckp_prop2 n : n = Zeckp n + Zeck_valpp (Zeck n).\nProof. by rewrite - {1} (Zeck_zeck_val n) /Zeckp Zeck_valppE. Qed.\n\nLemma Zeckp_prop2_bis l (s := [seq i.+1 | i <- l]):\n  [/\\ Zeck_valp s = Zeck_val l,  Zeck_valpp s = Zeck_valp l &\n     Zeck_val l + Zeck_valp l = Zeck_val s].\nProof.\nby rewrite (Zeck_valppE s) /s /Zeck_valp /Zeck_val /Zeck_valpp !big_map.\nQed.\n\nLemma Zeckp_le n: Zeckp n <= n ?= iff (n <= 1).\nProof. \napply/leqifP; case:n => [ | [ | n]]; rewrite ? Zeckp_0 ? Zeckp_1 //=.\nrewrite {2} (Zeckp_prop2 n.+2); apply: ltn_paddr.\nrewrite Zeck_S' /Zeck_valpp big_cons; move: (fib_contentP n.+1) => /=.\ncase: (fib_content n.+1); [ rewrite !ltnS // | move => k _].\nby rewrite addn_gt0 fib_gt0.\nQed.\n\nLemma Zeck_split a l x: sorted llen (a :: l) -> x <= fib a.+2 ->\n    Zeckp (x + (Zeck_val l)) = Zeckp x + Zeckp (Zeck_val l).\nProof.\nmove => sr le1; move:(uniq_llen sr) (path_all_llen sr) => h sa.\nrewrite (Zeckp_prop1 h) {2}/Zeckp - {1}(Zeck_zeck_val x) /Zeck_val /Zeck_valp.\nrewrite - !big_cat /=; apply: Zeckp_prop1; rewrite cat_uniq h Zeck_uniq /=.\nrewrite andbT; apply/negP => /hasP [t /(allP sa)] => /= /ltnW sb tz.\nmove:(leq_trans (allP (Zeck_val_bounded x) _ tz) le1). \nby rewrite leqNgt (fib_smonotone_bis sb).\nQed.\n\nLemma fib_sum_alt n: Zeck_val (iota 0 n) = (fib (n.+3)).-2.\nProof.  \nrewrite - fib_sum /Zeck_val.  \nhave <-:(\\sum_(0 <= i0 < n.+2) fib i0) = (\\sum_(i0 < n.+2) fib i0).\n     by rewrite big_mkord. \nrewrite big_nat_recl // add0n  big_nat_recl // add1n /= big_mkord.\nelim: n; first by rewrite big_nil big_ord0.\nby move => k H; rewrite iota_Sr sum_rcons addnC H big_ord_recr. \nQed.\n\nLemma fib_sum_even_alt n: Zeck_valpp (mkseq double n) = (fib (n.*2.-1)).-1.\nProof. \nrewrite -fib_sum_even /Zeck_valpp; elim: n; first by rewrite big_nil big_ord0.\nby move => n H; rewrite /= mkseq_succ sum_rcons addnC H big_ord_recr.\nQed.\n\nLemma fib_sum_odd_alt n: Zeck_valp (mkseq double n) = fib (n.*2).\nProof. \nrewrite -fib_sum_odd /Zeck_valp; elim: n; first by rewrite big_nil big_ord0.\nby move => n H; rewrite /= mkseq_succ sum_rcons addnC H big_ord_recr.\nQed.\n\nLemma fib_sum_even_alt2 n: Zeck_val (mkseq double n) = (fib (n.*2.+1)).-1.\nProof.\nmove: (fib_sum_even_alt n.+1); rewrite doubleS succnK => <-.\nrewrite /Zeck_val /Zeck_valpp; elim:n; first by rewrite big_cons !big_nil. \nby move => n H; rewrite /= mkseq_succ  mkseq_succ !sum_rcons doubleS H. \nQed.\n\nLemma Zeckp_fib n: Zeckp (fib n.+2) = fib n.+1.\nProof. by rewrite /Zeckp Zeck_fib /Zeck_valp big_cons big_nil addn0. Qed.\n\nLemma Zeck_fib1 n: Zeck (fib n.*2.+1).-1 = rev (mkseq double n).\nProof.\nrewrite - fib_sum_even_alt2 - Zeckv_rev; apply: (ZeckP (sorted_ggen_sdouble n)).\nQed.\n\nLemma Zeck_fib2 n: Zeck (fib n.*2.+2).-1 = rev (succ_seq (mkseq double n)).\nProof.\nrewrite - doubleS -fib_sum_odd_alt /Zeck_valp /mkseq /= big_cons add1n succnK.\ntransitivity (Zeck (Zeck_val(rev (succ_seq [seq i.*2 | i <- iota 0 n])))).\n  by rewrite iota_S /Zeck_val /succ_seq sum_rev !big_map.\nby apply:ZeckP; rewrite rev_sorted sorted_llen_succ sorted_llen_mkseq_e.\nQed.\n\nLemma Zeckp_fiba n: Zeckp (fib (n.*2.+1)).-1 = fib n.*2.\nProof.\nrewrite -fib_sum_odd_alt -fib_sum_even_alt2.\napply:(Zeckp_prop1);apply: (mkseq_uniq _ _ double_inj).\nQed.\n\nLemma Zeckp_fibb n: Zeckp (fib n.*2.+1).-2 = (fib n.*2).-1.\nProof.\nrewrite -fib_sum_odd_alt - (fib_sum_even_alt2 n)  /Zeck_val /Zeck_valp /mkseq.\ncase: n; first by rewrite !big_nil Zeckp_0.\nmove => n; rewrite !map_cons !big_cons !add1n !succnK -/iota.\napply: Zeckp_prop1; apply: (mkseq_uniq _ _ double_inj). \nQed.\n\nLemma Zeckp_fibc n: Zeckp (fib n.*2).-1 = (fib n.*2.-1).-1.\nProof.\ncase: n => [| n];  rewrite ? Zeckp_0 // -fib_sum_odd_alt -fib_sum_even_alt2.\nset L := [seq z.*2.+1 | z <- iota 0 n].\nrewrite /Zeck_valp/mkseq map_cons -/iota iota_S big_cons add1n succnK !big_map.\ntransitivity (Zeckp (Zeck_val L)); first by rewrite /L /Zeck_val big_map.\ntransitivity (Zeck_valp L); last by rewrite /Zeck_val /Zeck_valp !big_map.\napply:Zeckp_prop1; apply: (mkseq_uniq _ _ doubleS_inj).\nQed.\n\nLemma Zeckp_fibd n: Zeckp ((fib n.*2).-2) = (fib n.*2.-1).-1.\nProof.\ncase: n => [| [|n]]; rewrite ?Zeckp_0 //.\nset L := [seq i.*2.+1 | i <- iota 1 n].\nrewrite - fib_sum_odd_alt - fib_sum_even_alt /mkseq /=/ Zeck_valp /Zeck_valpp. \nrewrite! big_cons add0n addnCA add2n !succnK iota_S - map_comp. \nrewrite (map_comp succn (fun i => i.*2.+1)) -/L  big_map big_map.\nhave sa: sorted llen (1 :: L). \n  rewrite - [(1::L) ] / [seq i.*2.+1 | i <- iota 0 n.+1].\n  by apply:sorted_llen_mkseq => u /=; rewrite doubleS !ltnS. \nby rewrite (Zeck_split sa) // Zeckp_1 (Zeckp_prop1 (uniq_llen sa)).\nQed.\n\nLemma Zeckp_prop3a n (e := Zeckp): e (n + e n) = n.\nProof.\nrewrite -{1 3}(Zeck_zeck_val n) /e {2}/Zeckp; move:(Zeckp_prop2_bis (Zeck n)).\nmove => [Ha Hb Hc]; rewrite Hc - Ha.\nby apply:Zeckp_prop1; rewrite (map_inj_uniq succn_inj) Zeck_uniq.\nQed.\n\nLemma Zeckp_prop3b n (e := Zeckp): Zeck_li n != 0 -> e (e n) = n - e n.\nProof.\nrewrite /e - lt0n => /Zeck_li_prop2 => h.\nrewrite {2} (Zeckp_prop2 n) addKn; apply:(Zeckp_prop1_bis h (Zeck_uniq n)).\nQed.\n\nLemma Zeckp_prop4a n (e := Zeckp): e (n + e n.-1) = n.\nProof.\nrewrite /e; case: n => [|n]; first by rewrite !Zeckp_0.\nmove: (Zeck_prop1 (n:=n.+1) isT) => [a [l [ss _ ->]]].\nhave fp: 0 < fib (a.+2) by rewrite fib_gt0.\nrewrite Zeckv_cons /Zeck_val; set q :=  \\sum_(j <- l) fib j.+2.\nrewrite -{2}(prednK fp) addSn succnK (Zeck_split ss (leq_pred (fib a.+2))).\nset E1 := (fib a.+2 + Zeckp (fib a.+2).-1); set E2 := q + Zeckp q.\nhave eq2: q = Zeckp E2 by rewrite (Zeckp_prop3a q).\nhave eq3: E1 = if (odd a) then fib a.+3 else (fib a.+3).-1.\n  rewrite /E1 -{1 2 4 5}(odd_double_half a); case: (odd a).\n    rewrite add1n -doubleS Zeckp_fiba  -fibSS //.\n  rewrite - doubleS Zeckp_fibc doubleS succnK.\n  by rewrite (fibSS (a./2).*2.+1) {2} (fib_pos (a./2).*2) addnS.\nhave eq4: fib a.+2 = Zeckp E1.\n  rewrite eq3; case h: (odd a); first by rewrite (oddE h) Zeckp_fib.\n  by rewrite (evenE h) - doubleS  Zeckp_fiba.\nmove:(Zeckp_prop2_bis l) => [ha hb]. \nhave <-: Zeckp q = Zeck_valp l by apply: Zeckp_prop1;apply: (uniq_llen ss).\nrewrite addnACA /E2 /q; move => ->; rewrite -/(Zeck_val l) - ha; symmetry.\nrewrite (Zeck_split  (a := a.+1)) => //.\n+ by rewrite - eq4 // Zeckp_prop1 // (map_inj_uniq succn_inj) (uniq_llen ss).\n+ by move: ss; rewrite - map_cons -sorted_llen_succ. \n+ by rewrite -/E1 eq3; case: (odd a) => //; apply: leq_pred.\nQed.\n\nLemma Zeckp_prop4b n (e := Zeckp): odd (Zeck_li n) ->\n   (e (e n).-1).+1 = n - e n.\nProof.\nhave ->: n - e n = Zeck_valpp (Zeck n) by rewrite {1} (Zeckp_prop2 n) addKn.\ncase: n => // n; move: (Zeck_prop1 (n:=n.+1) isT) => [a [l [ss ww ee]]].\nrewrite /e /Zeck_li {2} /Zeckp /Zeck_valp /Zeck_valpp ww rev_cons last_rcons.\nmove/oddE => ->; rewrite !sum_rcons ! sum_rev - doubleS.\nrewrite -fib_sum_odd_alt /Zeck_valp - big_cat /= big_cons add1n succnK.\nset u :=  ([seq i.*2 | i <- iota 1 a./2] ++ l).\nmove: (order_path_min transitive_llen ss) => sa.\nhave pb: all (leq 1) u. \n   rewrite all_cat; apply /andP; split. \n   + clear; by elim: (a./2) {2} (0) => // n H k /=.\n   + by apply/allP => [x /(allP sa)]; case x.\nhave pa: uniq u.  \n  rewrite cat_uniq;apply /and3P; split.\n  + by rewrite (map_inj_uniq double_inj) iota_uniq.\n  + apply/negP => /hasP [x /(allP sa) sb] /mapP [y].\n    rewrite mem_iota ltnS - (leq_double y) => /andP [_ sc] se.\n    rewrite se in sb;  move: (ltnW (leq_trans sb sc)).\n    by rewrite ltnNge double_half_le.\n  + apply: (uniq_llen ss).\nmove:(fib_sum_even_alt (a./2).+1). \nrewrite  (Zeckp_prop1_bis pb pa) /Zeck_valpp doubleS /mkseq /= big_cons add0n. \nby rewrite big_cat /= - addSn  => ->; rewrite fib_pos.\nQed.\n\n(** * Maximal  representation *)\n\nDefinition gespec := [rel i j | (i == j.+1) || (i== j.+2) ].\nDefinition lespec := [rel i j | gespec j i].\nDefinition spec_sorted (l: seq nat) :=\n    sorted gespec l && gespec (last 0 l).+1 0.\n\nLemma spec_sorted_nil: spec_sorted [::].\nProof. by []. Qed.\n\nLemma spec_sorted_rev l: \n  (spec_sorted (rev l)) = sorted lespec l && lespec 0 (head 0 l).+1.\nProof. by rewrite /spec_sorted rev_sorted - (head_rev 0 (rev l)) revK. Qed.\n \nLemma spec_sorted_rcons l i: \n  (spec_sorted (rcons l i)) = (sorted lespec (i:: rev l)) && (i <= 1).\nProof.\nby rewrite - {1} (revK ((rcons l i))) spec_sorted_rev rev_rcons /= !eqSS leqn1.\nQed.\n\nLemma spec_sorted_sorted l: spec_sorted l -> sorted gtn l.\nProof.\nmove /andP => [h _]; move:h.\ncase: l => //= n s; elim: s n => //= m s IHs n /andP [ h /IHs ->].\nrewrite andbT;case/orP: h => /eqP -> //.\nQed.\n\nLemma spec_sorted_rec a l: spec_sorted (a::l) = \n  (if l== nil then a <=1  else gespec a (head 0 l)) && spec_sorted l.\nProof.\ncase: l; first by rewrite -/(rcons nil a) spec_sorted_rcons andbT //.\nby move => b l; rewrite /spec_sorted /= andbA.\nQed.\n\nDefinition max_rep n l:= spec_sorted l && (Zeck_val l == n).\n\nLemma max_rep_fib1 n: max_rep (fib n.*2.+1).-1  (rev (mkseq double n)).\nProof.\nrewrite /max_rep - {2}(Zeck_fib1 n) Zeck_zeck_val eqxx andbT.\nrewrite spec_sorted_rev; case: n => //n /=; rewrite andbT.\nby elim: n (0) => // n H i /=; rewrite eqxx orbT H.\nQed.\n\nLemma max_rep_fib2 n: \n  max_rep (fib n.*2.+2).-1 (rev (succ_seq (mkseq double n))).\nProof.\nrewrite /max_rep - {2}(Zeck_fib2 n) Zeck_zeck_val eqxx andbT.\nrewrite spec_sorted_rev; case: n => //n /=; rewrite andbT.\nby elim: n (0) => // n H i /=; rewrite eqxx orbT H.\nQed.\n\nLemma max_rep_fib3 n: \n  max_rep (fib n.*2.+2) (rev (0::(succ_seq (mkseq double n)))).\nProof.\nrewrite /max_rep.\nmove:(max_rep_fib2 n) => /andP [sa sb].\nrewrite Zeckv_rev Zeckv_cons - Zeckv_rev (eqP sb) add1n - fib_pos eqxx.\nby move: sa; rewrite spec_sorted_rev spec_sorted_rev andbT //;case n. \nQed.\n\nLemma max_rep_fib4 n: \n  max_rep (fib n.*2.+3) (rev (1:: (map double (iota 1 n)))).\nProof.\nrewrite /max_rep.\nmove:(max_rep_fib1 n.+1) => /andP; rewrite /mkseq /=.\nset s := [seq i.*2 | i <- iota 1 n]; move => [sa /eqP].\nrewrite !Zeckv_rev !Zeckv_cons doubleS add1n add2n => ->.\nby move: sa; rewrite !spec_sorted_rev  /s- fib_pos eqxx /= !andbT; case n.\nQed.\n\n\nLemma fib_partial_sum k n (L := k:: mkseq (fun i => (k.+1+ i.*2)) n) :\n   \\sum_(i <- L) (fib i) = fib (k + n.*2) /\\ sorted gespec (rev L).\nProof.\nhave A i j:  j + (i.+1).*2 = j.+2 + i.*2.\n   by rewrite doubleS - add2n addnA - (addn2 j). \nrewrite /L big_cons; clear L;split.\n  elim:n k; first by move => k; rewrite /mkseq /= big_nil !addn0.\n  move => n H k; rewrite /mkseq /= iota_S big_cons addn0 addnA.\n  rewrite (addnC (fib k)) -fibSS A - H ! big_map.\n  by congr addn; apply: eq_bigr => i _; rewrite A.\nrewrite rev_sorted /=. \ncase: n => // n; elim: n k => [k| n H k]; first by rewrite /= addn0 eqxx.\nmove:(H k.+2) => /= /andP [_].\nrewrite A !addn0  !eqxx orbT /= (iota_S 1); congr (path _ k.+3).\nby rewrite - map_comp; apply/eq_in_map  => i _; rewrite /= A.\nQed.\n\nLemma fib_partial_sum' k n (L := k:: mkseq (fun i => (k.+1+ i.*2)) n) :\n  Zeck_val L = fib (k.+2 + n.*2) /\\ sorted gespec (rev L).\nProof.\nsplit; last by exact (proj2 (fib_partial_sum k n)).\nrewrite -(proj1 (fib_partial_sum k.+2 n)).\nrewrite /Zeck_val /L !big_cons ! big_map //.\nQed.\n\n \nLemma max_rep_prop1 (l: seq nat): sorted gtn l ->\n { l' | [/\\ spec_sorted l', Zeck_val l = Zeck_val l' &\n    size l <= size l' ?= iff (spec_sorted l)] }.\nProof.\nmove => h.\nsuff: {s: seq nat |\n  [/\\ spec_sorted s, Zeck_val l = Zeck_val s,\n    size l <= size s ?= iff (spec_sorted l) & head 0 s <= head 0 l] }.\n  move => [s [pa pb pc _ ]]; by exists s.\nelim: l h; first by move => _; exists [::]. \nmove => a l Hrec /= h; move: (Hrec (path_sorted h)).\nmove => [s [ha hb hc hd]].\ncase sa: (spec_sorted (a :: l)).\n  by exists (a::l); split => //; apply /leqifP.\ncase lz: (l== nil).\n  rewrite (eqP lz) Zeckv_cons Zeckv_nil.\n  move: sa; rewrite addn0 {1}/spec_sorted /= !eqSS - leqn1 => /negbT.\n  rewrite (eqP lz) - ltnNge => /subnK; rewrite subn2 addn2 /= =>av.\n  set u := ((a.-2)./2).\n  have ww: ((a.-2 == u.*2.+1) || (a.-2 == u.*2)).\n    by rewrite -(odd_double_half a.-2) /u;case: (odd _); rewrite eqxx // orbT.\n  case av2: (a.-2 == u.*2.+1).\n  + rewrite - av (eqP av2) - doubleS.\n    move: (max_rep_fib4 u.+1); set s1 := rev _; move=> /andP [he hf].\n    have hg: 1 <= size s1 ?= iff false by apply /leqifP; rewrite /s1 size_rev.\n    have hi: head 0 s1 <= (u.+1).*2.+1.\n      rewrite /s1 /= head_rev /= last_map; case u => // v.\n      rewrite last_iota add2n //.\n    by rewrite - (eqP hf); exists s1.\n  + move: ww; rewrite av2 /= => /eqP ww.\n    rewrite - av ww - doubleS.\n    move: (max_rep_fib3 u.+1); set s1 := rev _; move=> /andP [he hf].\n    have hg: 1 <= size s1 ?= iff false by apply /leqifP; rewrite /s1 size_rev.\n    have hi: head 0 s1 <= (u.+1).*2.\n      rewrite /s1 /= head_rev /= !last_map; case u => // v.\n      by rewrite last_iota add1n ltn_double.\n    by rewrite - (eqP hf); exists s1.\nset b := head 0 l.\nset c := head 0 s.\nhave pa: l = b:: behead l by move: lz; rewrite /b; case l.\nhave pb: s = c:: behead s by move:hc => []; rewrite pa /c; case s.\nrewrite -/c -/b in hd.\nhave lba: b < a by move: h; rewrite pa /= => /andP [].\ncase wa: (gespec a c).\n  have ra: spec_sorted (a :: s). \n      by move:ha wa; rewrite pb /spec_sorted /= ; move => /andP[ -> ->] ->.\n  have rb: ((a == b.+1) || (a == b.+2)).\n    rewrite (eqn_leq _ b.+1) (eqn_leq _ b.+2) lba.\n    by case/orP: wa => /eqP ->; rewrite! ltnS hd //= andbT (ltnNge c) orNb.\n  exists(a:: s); rewrite !Zeckv_cons hb /= leqnn; split => //.\n   move: hc; move: sa; rewrite /spec_sorted pa /= rb /= => ->.\n  by move /leqifP => H; apply/leqifP; rewrite ltnS.\nhave lac: c.+2 < a.\n  move: (leq_ltn_trans hd lba); rewrite leq_eqVlt; case /orP.\n    by rewrite eq_sym => h1; move: wa; rewrite /= h1.\n  rewrite leq_eqVlt; case /orP => //.\n  by rewrite eq_sym => h1; move: wa; rewrite /= h1 orbT.\nset n := (a -c.+1)./2; set k := a - n.*2.\nhave [kp1 /eqP kp2]: ((k == c.+1) ||(k == c.+2)) /\\ (k + n.*2 == a). \n  move: (subnK lac); set v := a -c.+3; rewrite - {1} add2n addnA addn2 => v1.\n  rewrite /k /n -v1 addnK -{1 3 5 8} (odd_double_half v.+2).\n  case: (odd _); first by rewrite add1n addSnnS addKn addnC !eqxx orbT.\n  by rewrite addKn addnC !eqxx.\ncase: (posnP n) => np.\n  move:kp1 lac; rewrite /k np subn0; case ww: (a==c.+2).   \n    by rewrite (eqP ww) ltnn.\n  by rewrite orbF => /eqP -> /ltnW; rewrite ltnn.\nmove: (fib_partial_sum' k n) => []; cbv zeta; set l1 := _ :: _.\nrewrite addSn addSn kp2 Zeckv_cons => <- => he.\nexists  (rev l1 ++ s).\nsplit => //.\n+ move: he ha; rewrite /l1; set l2 := mkseq _ _; move: (split_rev k l2) => eq1.\n  rewrite /spec_sorted {1 2} eq1 /= cat_path => -> /=.\n  rewrite last_cat rev_cons last_rcons pb /= => /andP[-> ->]. \n  set x := last _ _.\n  have: x = last k (rev (k :: l2)) by rewrite eq1 /x rev_cons. \n  by rewrite rev_cons last_rcons ! andbT => ->.\n+ by rewrite  hb /Zeck_val big_cat sum_rev.\n+ apply /leqifP; rewrite size_cat size_rev /l1/size_cat /= size_mkseq.\n  by rewrite -(prednK np) addSn addSn ltnS ltnS (leq_trans hc) // leq_addl.\n+ rewrite /l1 /= rev_cons cat_rcons -(prednK np)- (revK (k::s)) - rev_cat. \n  rewrite head_rev last_cat last_mkseq add0n - kp2 -{2} (prednK np) doubleS.\n  by rewrite addnS addnS addSn ltnS. \nQed.\n\n\nLemma max_rep_bound a l: spec_sorted (a::l) -> \n   (fib a.+3).-1 <= Zeck_val (a::l) < (fib a.+4).-1.\nProof.\nmove => h.\napply /andP; split; last first.\n  by rewrite -ltnS - fib_pos  (Zeckv_bound0 (spec_sorted_sorted h)).\nelim: l a h.\n  move => a; rewrite Zeckv_cons Zeckv_nil spec_sorted_rec /= andbT. \n  by case: a => //; case.\nmove => a l Hrec b.\nhave H:= (fib_pos b).\nrewrite spec_sorted_rec /= => /andP[ha /Hrec hb].\nrewrite Zeckv_cons fibSS H addnS /= leq_add2l (leq_trans _ hb) //.\nby case /orP: ha => /eqP <-; rewrite ? leqnn // fibSS {2} H addSn leq_addr.\nQed.\n\n\nLemma max_rep_unique (s s': seq nat) : spec_sorted s -> spec_sorted s' -> \n   Zeck_val s = Zeck_val s' ->  s = s'.\nProof.\nhave A a l: Zeck_val [::] = Zeck_val (a :: l) -> False.\n  by rewrite Zeckv_nil => h; move: (Zeckv_pos a l); rewrite - h.\nhave B a l: spec_sorted (a::l) ->   \n  (fib a.+3) <= (Zeck_val (a::l)).+1 < (fib a.+4).\n  by rewrite fib_pos(fib_pos a.+3) !ltnS => /max_rep_bound.\nelim: s' s; first by  case => // a l _ _; move/ esym /A.\nmove => a l Hrec  [_ _ /A //| a' l' sa sb sc].\nmove: (B _ _ sa); rewrite sc => sa'.\nmove /eqP: (fib_partition sa' (B _ _ sb)); rewrite !eqSS => /eqP aux.\nmove: sa sb sc; rewrite aux ! spec_sorted_rec => /andP[ _ hc] /andP[ _ hd].\nby move /eqP; rewrite !Zeckv_cons eqn_add2l => /eqP h; rewrite (Hrec l'). \nQed.\n\nDefinition ZeckM n := sval (max_rep_prop1  (sorted_ggenW (Zeck_ggen n))).\n\nLemma ZeckM_prop1 n: \n  [/\\ spec_sorted (ZeckM n), Zeck_val (Zeck n) = Zeck_val (ZeckM n)\n    & size (Zeck n) <= size (ZeckM n) ?= iff spec_sorted (Zeck n)].\nProof.\nexact :(svalP (max_rep_prop1  (sorted_ggenW (Zeck_ggen n)))).\nQed.\n\nLemma ZeckM_prop2 n: max_rep n (ZeckM n).\nProof. \nrewrite /max_rep;  move: (ZeckM_prop1 n) => [-> <- _]. \nby rewrite (Zeck_zeck_val n)  eqxx.\nQed.\n\nLemma ZeckM_prop3 n l: max_rep n l -> ZeckM n = l.\nProof.\nmove:(ZeckM_prop2 n) => /andP[ha /eqP hb] /andP[hc /eqP hd].\nby apply:max_rep_unique => //; rewrite hb.\nQed.\n\nLemma ZeckM_is_maximal n l: sorted gtn l -> Zeck_val l = n ->\n    size l <= size (ZeckM n) ?= iff (l == (ZeckM n)).\nProof.\nmove: (ZeckM_prop1 n) => [ha hb whc].\nrewrite  (Zeck_zeck_val n) in hb.\nmove => /max_rep_prop1 [s [hc hd  /leqifP M]] he.\ncase wx: (spec_sorted l).\n  by rewrite hb in he; rewrite (max_rep_unique wx ha he);  apply/leqif_refl.\napply/leqifP; move: M; rewrite he hb in hd;rewrite wx (max_rep_unique ha hc hd).\nby case H: (l==s) => //; rewrite (eqP H).\nQed.\n\nLemma ZeckM_prop4 n l: sorted gtn l -> Zeck_val l = n ->\n  (size (Zeck n) <= size l <= size (ZeckM n) /\\\n  (size (Zeck n) = size (ZeckM n) -> l = (Zeck n))).\nProof.\nmove => pa pb.\nmove: (ZeckM_is_maximal pa pb) => [pc pd].\nmove: (Zeck_is_minimal pa pb) => [pe pf].\nby rewrite pc pe; split => // h;apply /eqP; rewrite - pf eqn_leq pe h pc.\nQed.\n\nLemma unique_representation n:\n  (exists k, n = (fib k.+2).-1) <-> \n   (forall l l', sorted gtn l -> Zeck_val l = n ->\n     sorted gtn l' -> Zeck_val l' = n -> l = l').\nProof.\nsplit.   \n  move => [k nv].\n  have pa: Zeck n  = ZeckM n.\n   case: (odd_dichot k) => kv.\n     have ->: n = (fib((k./2.+1).*2.+1)).-1 by rewrite nv {1} kv /= doubleS.\n     by rewrite (ZeckM_prop3  (max_rep_fib1 (k./2.+1))) -(Zeck_fib1 (k./2.+1)).\n   by rewrite nv kv (ZeckM_prop3  (max_rep_fib2 k./2)) (Zeck_fib2 k./2).\n  have pb: (size (Zeck n) = size (ZeckM n)) by rewrite pa.\n  move => l l' la ea lb eb.\n  by rewrite (proj2 (ZeckM_prop4 la ea) pb) (proj2 (ZeckM_prop4 lb eb) pb).\nmove => H.\nmove: (ZeckM_prop2 n) => /andP [/spec_sorted_sorted  ha /eqP hb].\nmove: (sorted_ggenW (Zeck_ggen n)) => hc.\nmove: (Zeck_zeck_val n) => hd; rewrite - hd.\nmove: (ZeckM_prop1 n)=> []; rewrite (H _ _ ha hb hc hd) => [he _ _].\ncase: (posnP n) => np.\n    by exists 0; rewrite np  Zeckv_nil.\nrewrite lt0n in np;move: (Zeck_prop1 np) => [a [l [pa pb pc]]].\nsuff: a::l = (mkseq double (size l).+1) \n   \\/ a ::l =  (succ_seq (mkseq double (size l).+1)).\n  rewrite pb; case => ->.\n     by exists ((size l).*2.+1); rewrite -Zeck_fib1 Zeck_zeck_val.\n  by exists ((size l).*2.+2); rewrite -Zeck_fib2 Zeck_zeck_val.\nmove: he pa; rewrite pb spec_sorted_rev /= !eqSS.\nmove => /andP [pd pe] pf.\nsuff: a :: l = [seq i+a | i<- mkseq double (size l).+1].\n  move => ->; rewrite /mkseq /succ_seq -!map_comp /comp.\n  case: (orP pe) => av; rewrite (eqP av); [left | right].\n    by apply/eq_in_map => i _; rewrite addn0.\n  by simpl; congr cons; apply/eq_in_map => i _; rewrite addn1.\nmove: pd pf; clear; elim: l a => [a // | a l Hr b]. \nsimpl => /andP[ ha hb] /andP[hc hd].\ncase: (orP ha) => ha'; first by move: hc; rewrite (eqP ha') ltnn.\nrewrite Hr //= (eqP ha') (iota_S 1) /succ_seq -! map_comp /comp /=.\nby congr cons; congr cons; apply/eq_in_map => i _;rewrite !addnS ! addSn //.\nQed.\n\n\nLemma iota_lespec_sorted i n: sorted lespec (iota i n).\nProof. \nby elim: n i => //; case => // n H i /=; rewrite eqxx /=; apply: H.\nQed.\n\n\nLemma iota_rem_lespec_sorted i j n: sorted lespec (rem j (iota i n)).\nProof.\nelim: n i j; first by move => n k /=; case (n == k).\nmove => j H i k /=; case: (i==k); first by apply: iota_lespec_sorted.\nmove: (H i.+1 k);case j => // j1 /=; case:(i.+1 == k) => //;\n  case: j1 => // j2 /=;  rewrite eqxx // orbT //.\nQed.\n\nLemma iota_rem_spec_sorted j i: spec_sorted (rev (rem i (iota 0 j))).\nProof.\nrewrite spec_sorted_rev; apply/andP; split;last first.\n  case:j => // j /=;case ww: (0 == i) => //; case:j => //.\nby apply: iota_rem_lespec_sorted. \nQed.\n\n\nLemma iota_rem2_spec_sorted j i: \n  spec_sorted (rev (rem i.+2 (rem i (iota 0 j)))).\nProof.\nrewrite spec_sorted_rev; apply/andP; split;last first.\n  case:j => // j /=;case ww: (0 == i) => //; case:j => //.\nelim: j 0 i; first by move => n k /=; case (n == k).\nmove => j H i k /=; case: (i==k); first by apply:iota_rem_lespec_sorted.\nsimpl; case ww:(i == k.+2); first by apply:iota_rem_lespec_sorted.\nmove: (H i.+1 k); clear; case: j => // j /=.\ncase wwb: (i.+1 == k). \n  have wwc: k == k.+1 = false by apply/negP => /eqP; exact: n_Sn.\n  by case:j => // j /=; rewrite eqSS (eqP wwb) wwc /= (eqP wwb) eqxx orbT.\nrewrite /= eqSS; case wwc: (i == k.+1); last by rewrite /= eqxx.\nrewrite (eqP wwc);case: j => // j /=.\nby rewrite gtn_eqF /= ?eqxx ?orbT // ltnS - addn2 leq_addr.\nQed.\n\nLemma ZeckM_bound1 n (a := head 0 (ZeckM n)):\n  0 < n -> (fib a.+3).-1 <= n < (fib a.+4).-1.\nProof.\nrewrite /a; move/andP:(ZeckM_prop2 n) => [ h /eqP {1 3 4} <-]. \nby move: h;case: (ZeckM n) => [| b l / max_rep_bound //]; rewrite Zeckv_nil.\nQed.\n\nLemma ZeckM_bound2 n a: \n  (fib a.+3).-1 <= n < (fib a.+4).-1  -> a = head 0 (ZeckM n).\nProof.\ncase: (posnP n) => np; first by rewrite np fib_ge2_alt.\nrewrite -ltnS -(ltnS n.+1) -!fib_pos => la.\nmove:(ZeckM_bound1 np); rewrite -ltnS -(ltnS n.+1)  -!fib_pos => lb.\nby move /eqP:(fib_partition la lb); rewrite !eqSS => /eqP.\nQed.\n\nLemma ZeckM0: ZeckM 0 = [::].\nProof. by apply:ZeckM_prop3; rewrite /max_rep Zeckv_nil. Qed.\n\nLemma ZeckM1: ZeckM 1 = [:: 0].\nProof. by apply:ZeckM_prop3; rewrite /max_rep Zeckv_cons Zeckv_nil. Qed.\n\nLemma ZeckM2: ZeckM 2 = [:: 1].\nProof. by apply:ZeckM_prop3; rewrite /max_rep Zeckv_cons Zeckv_nil. Qed.\n\nLemma ZeckMgt2 n: 2 <n -> 2 <= size (ZeckM n).\nProof.\nmove/andP:(ZeckM_prop2 n)=> []; case: (ZeckM n).\n  by rewrite Zeckv_nil => _ /eqP <-.\nmove => a l; rewrite spec_sorted_rec /= ltnS; case:l => //=.\nby rewrite Zeckv_cons Zeckv_nil leqn1 => /andP []; case/orP=> /eqP -> _ /eqP <-.\nQed.\n\nLemma ZeckM_rec1 n a: (fib a.+3).-1 <= n < (fib a.+4).-1 ->\n  ZeckM (n + (fib a.+3)) = a.+1::ZeckM n.\nProof.\nmove /ZeckM_bound2 => sa.\nmove/andP: (ZeckM_prop2 n) => [ss /eqP nv].\napply:ZeckM_prop3; rewrite/max_rep Zeckv_cons nv addnC eqxx.\nby rewrite spec_sorted_rec ss sa; case:(ZeckM n) => // nb l /=; rewrite eqxx.\nQed.\n\nLemma ZeckM_rec2 n a: (fib a.+3).-1 <= n < (fib a.+4).-1 ->\n  ZeckM (n + (fib a.+4)) = a.+2::ZeckM n.\nProof.\ncase: (posnP n) => np; first by rewrite np fib_ge2_alt.\nmove/ZeckM_bound2 => sa.\nmove/andP: (ZeckM_prop2 n) => [ss /eqP nv].\napply:ZeckM_prop3; rewrite/max_rep Zeckv_cons nv addnC eqxx spec_sorted_rec.  \nmove: np; rewrite - {1}nv sa ss; case:(ZeckM n); first by rewrite Zeckv_nil.\nby move => // b l _ /=;rewrite eqxx orbT.\nQed.\n\nLemma ZeckM_fibm2 n:  ZeckM (fib (n.+3)).-2 = rev (iota 0 n).\nProof.\napply:ZeckM_prop3; apply/andP; split.\n   rewrite spec_sorted_rev; case: n => // n /=; rewrite andbT.\n   by elim:n (0) => // k H n /=; rewrite H eqxx.\nrewrite  /Zeck_val - fib_sum !big_ord_recl /=.\nelim:n => [|n Hr];first by rewrite big_nil big_ord0.\nby rewrite big_ord_recr - (eqP Hr) iota_Sr rev_rcons big_cons addnC.\nQed.\n\n\nLemma size_sorted a l:\n  sorted gtn (a::l) -> size l <= a ?= iff (l == rev (iota 0 a)).\nProof.\nelim: l a => [a _|b l Hrec a].\n  by apply /leqifP; case:a => // a; rewrite iota_Sr rev_rcons //.\nmove => /= /andP [lba /Hrec ha]. \n  split.  rewrite (leq_ltn_trans _ lba) //;apply: ha.\nmove: lba; case: a => // a. rewrite ltnS => lab.\nrewrite iota_Sr rev_rcons add0n eqseq_cons eqSS.\nhave sl: size l <= b by apply: ha.\nmove/leqifP: ha; move: lab; rewrite leq_eqVlt; case /orP => hx.\n  by rewrite -(eqP hx) eqxx; case: eqP => // _ /ltn_eqF ->.\nrewrite (ltn_eqF hx) /= => _; exact: (ltn_eqF (leq_ltn_trans sl hx)).\nQed.\n\n\nLemma ZeckM_bound3 n a:\n  (fib a.+3).-1 <= n < (fib a.+4).-1 ->\n  size (ZeckM n) <= a.+1 ?= iff (n== (fib (a.+4)).-2).\nProof.\nmove => h.\nmove:(ZeckM_bound2 h); move: (ZeckM_prop2 n) h => /andP[];case: (ZeckM n).\n   by rewrite Zeckv_nil => _ /eqP <-; rewrite fib_ge2_alt /=.\nmove => b l ss zv _ /= ->; apply/leqifP.\nmove:(ZeckM_prop2 (fib b.+4).-2) => /andP[wa /eqP zz].\ncase: eqP => nv.\n  have ea: Zeck_val (b :: l) = Zeck_val (ZeckM (fib b.+4).-2).\n    by rewrite zz -nv (eqP zv).\n  rewrite -/(size (b::l)) (max_rep_unique ss wa ea) ZeckM_fibm2. \n  by rewrite size_rev size_iota.\nmove /leqifP: (size_sorted (spec_sorted_sorted ss)); rewrite ltnS. \ncase: eqP => // lv; move: zv; rewrite lv  -rev_rcons -iota_Sr - ZeckM_fibm2 zz. \nby move => h;case: nv; rewrite (eqP h).\nQed.\n\n\nDefinition card_max_rep n m:=\n   \\sum_((fib n).-1 <= i < (fib n.+1).-1) (size (ZeckM i)== m).\n\nLemma  card_max_repE n m: \n  card_max_rep n m =\n    \\sum_((fib n).-1 <= i < (fib n.+1).-1 | (size (ZeckM i)== m)) 1.\nProof. by rewrite big_mkcond /= /card_max_rep; apply: eq_big. Qed.\n\nLemma card_max_rep0m m: card_max_rep 0 m = 0.\nProof. by rewrite/card_max_rep /= big_geq. Qed.\n\nLemma card_max_rep1m m: card_max_rep 1 m = 0.\nProof. by rewrite/card_max_rep /= big_geq. Qed.\n\nLemma card_max_rep2m m: card_max_rep 2 m = (m==0).\nProof. \nby rewrite/card_max_rep big_ltn // big_geq // fibE /= ZeckM0 addn0 eq_sym.\nQed.\n\nLemma card_max_rep41: card_max_rep 4 1 = 1.\nProof.\nby rewrite /card_max_rep big_ltn// big_ltn// big_geq//= ZeckM2 (ZeckM_fibm2 2).\nQed.\n\n\nLemma card_max_rep_smalln n m: n < m.+2 -> card_max_rep n m = 0.\nProof.\ncase:n => [|[| [|n]]]; rewrite ? card_max_rep0m ? card_max_rep1m // ! ltnS. \n  by move/gtn_eqF; rewrite  card_max_rep2m => ->.\nmove => lnm; rewrite card_max_repE big_hasC => //; apply /hasPn => x.\nrewrite mem_index_iota => ltn; apply/eqP => eq1.\nby move:(leq_ltn_trans (ZeckM_bound3 ltn) lnm); rewrite eq1 ltnn.\nQed.\n\nLemma card_max_repn0 n: card_max_rep n.+3 0 = 0.\nProof.\nrewrite card_max_repE big_hasC => //; apply /hasPn => i.\nrewrite mem_index_iota size_eq0 => fb; apply /eqP => ln.\nmove: (ZeckM_prop2 i); rewrite /max_rep ln Zeckv_nil => /andP[_ /eqP iz].\nby move: fb; rewrite - iz leqn0 (fib_ge2_alt).\nQed.\n\nLemma card_max_repn2n n: card_max_rep n.+2 n = 1.\nProof.\nmove: (fib_ge2_alt n); set p :=  (fib n.+3).-2 => pv.\nhave la: (fib n.+2).-1 <= p by rewrite - 2!ltnS -pv -fib_pos fib_smonotone_bis.\nhave lb: p <= (fib n.+3).-1 by rewrite pv /=.\nrewrite card_max_repE (big_cat_nat _ _ _ la lb) pv /= big_hasC.\n  by rewrite big_ltn_cond // /p ZeckM_fibm2 size_rev size_iota eqxx big_geq.\napply/hasPn => i; rewrite mem_index_iota /p.\ncase:(posnP n)=> [ | /prednK nv]; first by move ->; rewrite ltn0 andbF.\nrewrite ltn_neqAle (andbC  (i != _)) andbA -(ltnS i) -/p -[p.+1]/(p.+2.-1) -pv. \nrewrite -nv => /andP [] /ZeckM_bound3 /leqifP; rewrite nv; case:eqP => //.\nby move => _ /ltn_eqF ->.\nQed.\n\n\nLemma card_max_rep_rec n m: m.+2 <= n ->\n  card_max_rep n.+2 m.+1 = card_max_rep n.+1 m + card_max_rep n m.\nProof.\ncase: m.\n  case:n => [|[ | [| n _]]] //; rewrite !card_max_repn0.\n    by rewrite card_max_rep41 card_max_rep2m.   \n  rewrite card_max_repE big_hasC => //; apply /hasPn => i.\n  rewrite mem_index_iota => /andP [la _].\n  have l2n3: 2 < n.+3 by rewrite !ltnS.\n  move: (fib_smonotone_bis l2n3); rewrite (fib_pos n.+4) ltnS => lb.\n  by rewrite (gtn_eqF (ZeckMgt2 (leq_trans lb la))).\nmove => m lmn.\nset k :=  (fib n.+1) +  (fib n.+1).-1. \nhave kl1: (fib n.+2).-1 <= k.\n   by rewrite - ltnS /k -addnS -!fib_pos fibSS leq_add2l fib_monotone.\nhave kl2: k <= (fib n.+3).-1.\n  by rewrite - ltnS /k -addnS -!fib_pos fibSS leq_add2r fib_monotone.\nhave np:=(ltn_predK lmn).\nhave n3: n = (n-3).+3 by rewrite - addn3 subnK // (leq_trans _ lmn).\nrewrite addnC !card_max_repE (big_cat_nat _ _ _ kl1 kl2) /=; congr addn. \n   rewrite fibSS /k -[in fib n] np (fib_pos n.-1) addnS /= np big_nat_shift.\n   apply:big_nat_cond_eq => i eq1.\n   by rewrite n3 in eq1; move:(ZeckM_rec2 eq1); rewrite -n3 addnC => ->.\nrewrite fibSS /k (addnC (fib n.+2)) (fib_pos n.+1)  addnS /= big_nat_shift. \napply:big_nat_cond_eq => i eq1.\nby rewrite n3 in eq1; move:(ZeckM_rec1 eq1); rewrite -n3 addnC => ->.\nQed.\n\nLemma card_max_rep_val n m: m.+2 <= n -> card_max_rep n m = 'C(m,n- m.+2).\nProof.\nmove/subnK => {1} <-; set k := _ - _; move: k; elim: {n} m.\n  case; first by rewrite card_max_rep2m.\n  by move => k; rewrite bin0n /= addn2 card_max_repn0.\nmove => n Hr; case; first by rewrite card_max_repn2n bin0.\nmove => k; rewrite 2!addnS card_max_rep_rec ?ltn_paddl //. \nby rewrite addSnnS Hr - addSn Hr - binS.\nQed.\n\n\nDefinition card_min_rep n m:=\n   \\sum_((fib n) <= i < (fib n.+1)) (size (Zeck i)== m).\n\nLemma card_min_repE n m: \n  card_min_rep n m =\n    \\sum_((fib n) <= i < (fib n.+1)| (size (Zeck i)== m)) 1.\nProof. by rewrite big_mkcond /= /card_min_rep; apply: eq_big. Qed.\n\nLemma card_min_rep0m m: card_min_rep 0 m = (m==0).\nProof. by rewrite /card_min_rep big_nat1 Zeck_0 eq_sym. Qed.\n\nLemma card_min_rep1m m: card_min_rep 1 m = 0.\nProof. by rewrite /card_min_rep big_geq. Qed.\n\nLemma card_min_rep2m m: card_min_rep 2 m = (m==1).\nProof. by rewrite /card_min_rep big_nat1 Zeck_1 eq_sym. Qed.\n\nLemma card_min_repn0 n: card_min_rep n 0 = (n==0).\nProof.\ncase nz: (n==0); first by rewrite  (eqP nz) card_min_rep0m.\nrewrite card_min_repE big_hasC => //; apply /hasPn => i.\nrewrite mem_index_iota=> /andP[ha _]; rewrite size_eq0; move:(Zeck_zeck_val i).\nmove: ha; case:i; first by rewrite leqn0 fib_eq0 nz.\nby move=> i; case: (Zeck i.+1) => //; rewrite Zeckv_nil.\nQed. \n\nLemma card_min_repn1 n: card_min_rep n 1 = (2 <=n).\nProof.\ncase: n=> [|[|n]]; rewrite ? card_min_rep0m ?card_min_rep1m //=.\nrewrite card_min_repE big_ltn_cond ?fib_smonotone_bis // Zeck_fib /=.\nrewrite big_hasC => //; apply /hasPn => i.\nrewrite mem_index_iota=> /andP[ha hb]; move:(Zeck_zeck_val i).\ncase:(Zeck i) => // a [|b l //]; rewrite Zeckv_cons Zeckv_nil addn0 => h.\nmove:hb; rewrite - h => /fib_monotone_bis; rewrite ltnS => /fib_monotone.\nby rewrite h leqNgt ha.\nQed.\n\n\nLemma card_min_rep_rec n m:\n  card_min_rep n.+2 m.+1 = card_min_rep n.+1 m.+1 + card_min_rep n m.\nProof.\ncase: (posnP n) => np.\n  by rewrite np card_min_rep1m  card_min_rep0m card_min_rep2m eqSS.\nset k := fib n.+2 + fib n.\nhave kl1: (fib n.+2) <= k by rewrite leq_addr.\nhave kl2: k <= (fib n.+3) by rewrite  fibSS /k leq_add2l fib_monotone.\nrewrite {1} card_min_repE (big_cat_nat _ _ _ kl1 kl2) /=; congr addn. \n  rewrite /k {1} fibSS !(addnC _ (fib n)) big_nat_shift card_min_repE.\n  apply:big_nat_cond_eq => i eq1.\n  move/andP:(eq1) => [ha]; rewrite fibSS => hb.\n  have ww:(fib n + i - fib n.+2) = (i - fib n.+1).\n    by rewrite -{1} (subnKC ha) addnA (addnC (fib _)) - fibSS addKn.\n  have eq2: fib n.+2 <= fib n + i < fib n.+3. \n     rewrite !fibSS addnC leq_add2l -addnA ltn_add2l ha /=. \n     by apply: (leq_trans hb); rewrite  leq_add2l fib_monotone.\n  rewrite - (prednK np) in eq1.\n  by rewrite (Zeck_S eq1) (prednK np)  (Zeck_S eq2) ww.\nrewrite fibSS /k big_nat_shift card_min_repE.\napply:big_nat_cond_eq => i /andP [ha hb].\nhave eq2: fib n.+2 <= fib n.+2 + i < fib n.+3. \n  by rewrite leq_addr /= (fibSS n.+1) ltn_add2l. \nby rewrite (Zeck_S eq2) addKn /= eqSS.\nQed.\n\n\nLemma card_min_rep_small n m: 0 < n <= m -> card_min_rep n m = 0.\nProof.\ncase: n => [| [| n /= lnm]] //; first by rewrite card_min_rep1m.\nrewrite card_min_repE big_hasC => //; apply /hasPn => i.\nrewrite mem_index_iota => eqa.\nmove: (sorted_ggenW (Zeck_ggen i)); rewrite (Zeck_S eqa)  => /size_sorted /=.\nset s := size _ => ls.\nhave lsn: s.+2 <= n.+2 by rewrite !ltnS; apply:ls.\nby rewrite (ltn_eqF (leq_trans lsn lnm)).\nQed.\n\n\nLemma card_min_rep_val n m :  card_min_rep (n+m.+2) m.+1 = 'C(n,m). \nProof.\nelim:n m. \n  case; first by rewrite card_min_repn1.\n  by move => m; rewrite bin0n card_min_rep_rec  !card_min_rep_small /=.\nmove => n H; case; first by rewrite bin0; rewrite card_min_repn1 addn2 //.\nby move => m; rewrite 2!addnS  card_min_rep_rec addSnnS -addnS H H binS.\nQed.\n\nLemma card_min_rep_valbis n m: 0< m< n ->\n   card_min_rep n m = 'C(n-m-1,m.-1). \nProof.\nmove => /andP[sa sb]; rewrite -subnDA -{1}(subnK sb) addn1 -{2 3} (prednK sa). \nby rewrite card_min_rep_val.\nQed.\n\nSection DualUniqueRepresentation.\n\nParameter v: nat -> nat.\nDefinition Zval_v l:= \\sum_(i <- l) (v i).\nHypothesis v_exists:\n  forall n, exists2 l, spec_sorted l & Zval_v l = n.\nHypothesis v_unique:\n  forall l l', spec_sorted l ->  spec_sorted l' -> Zval_v l = Zval_v l' ->\n   l = l'.\n\n\n\nLemma DUR_injv: injective v.\nProof.\nmove => i j sv.\nset l:= iota 0 (i+j).+1.\nhave Ha: forall k, k\\in l ->  Zval_v l = Zval_v (k :: rem k l). \n  by move => k H;  apply: perm_big; apply:perm_to_rem.\nhave il: i \\in l by  rewrite mem_iota /= ltnS leq_addr.\nhave : Zval_v (i :: rem i l) = Zval_v (j :: rem j l).\n  by rewrite - Ha // -  Ha // mem_iota /= ltnS  leq_addl.\nmove/eqP; rewrite /Zval_v !big_cons sv eqn_add2l - sum_rev.\nrewrite - [ X in _ == X] sum_rev  => /eqP eq1.\nhave Hb:= (iota_rem_spec_sorted (i+j).+1).\nmove: (v_unique (Hb i) (Hb j) eq1) => /rev_inj eq2.\ncase ok:(i== j); first by rewrite (eqP ok).\nhave ul: uniq l by apply: iota_uniq.\nhave: i \\in rem j l by rewrite mem_rem_uniq // inE ok.\nby rewrite - eq2 mem_rem_uniq // inE // eqxx.\nQed.\n\n\nLemma DUR_positive i: 0 < v i.\nProof.\ncase: (posnP (v i)) => // h.\nhave ha j: spec_sorted (rev(iota 0 j)).\n  rewrite  spec_sorted_rev; apply/andP; split; last by case:j.\n  by elim: j 0 => // j H k /=; move:(H k.+1); case j => // m /=; rewrite eqxx.\nmove:(v_unique (ha i)(ha i.+1)).\nrewrite /Zval_v !sum_rev iota_Sr sum_rcons h add0n => H.\nhave: i \\in (iota 0 i) by  rewrite (rev_inj (H (erefl _))) mem_rcons inE eqxx.\nby rewrite mem_iota // ltnn andbF.\nQed.\n\n\nLemma DUR_exclusion1 i: v i + v i.+2 != v i.+1.\nProof.\ncase eqP => // eq1.\nset l := iota 0 i.\nset l1 := rev(rcons (rcons l i) i.+2).\nset l2 := rev (rcons l i.+1).\nhave ea:Zval_v l1 = Zval_v l2. \n  by rewrite /Zval_v /l1 /l2 !sum_rev !sum_rcons addnA (addnC _ (v i)) eq1.\nhave eb: l1 = rev (rem i.+1 (iota 0 i.+3)).\n  congr rev; rewrite iota_Sr iota_Sr add0n rem_rcons1 //.\n  by rewrite - iota_Sr rem_rcons2 // mem_iota ltnn andbF.\nhave ec: l2 = rev (rem i (iota 0 i.+2)).\n  congr rev; rewrite /l iota_Sr iota_Sr ! add0n; rewrite rem_rcons1 //.\n  by rewrite rem_rcons2 // mem_iota ltnn andbF. \nhave sa: spec_sorted l1 by rewrite eb; apply: iota_rem_spec_sorted.\nhave sb: spec_sorted l2 by rewrite ec; apply: iota_rem_spec_sorted.\nmove:(v_unique sa sb ea); rewrite eb ec => /rev_inj => ed.\nmove: (f_equal size ed); rewrite !size_rem ?size_iota ? mem_iota ?ltnS //=.\nby move/esym /n_Sn.\nQed.\n\nLemma DUR_exclusion2 i: v i + v i.+2 != v i.+1 + v i.+3.\nProof.\ncase eqP => // eq1.\nset l := iota 0 i.\nset l1 := rev(rcons (rcons l i) i.+2).\nset l2 := rev (rcons (rcons l i.+1) i.+3).\nhave ea:Zval_v l1 = Zval_v l2. \n  rewrite /Zval_v /l1 /l2 !sum_rev !sum_rcons !addnA (addnC _ (v i)) eq1.\n  by rewrite (addnC _ (v i.+1)).\nhave eb: l1 = rev (rem i.+1 (iota 0 i.+3)).\n  congr rev; rewrite iota_Sr iota_Sr add0n rem_rcons1 //.\n  by rewrite - iota_Sr rem_rcons2 // mem_iota ltnn andbF.\nhave ec: l2 = rev (rem i.+2 (rem i (iota 0 i.+4))).\n  have ha: i < i.+3 by  rewrite !ltnS; apply: (@leq_trans i.+1).\n  have hb: i \\notin iota 0 i by rewrite mem_iota ltnn andbF.\n  congr rev; rewrite ! iota_Sr !add0n rem_rcons1 // rem_rcons1 //.\n  rewrite rem_rcons1 // rem_rcons2 // rem_rcons1 //  rem_rcons2 //.\n  by rewrite mem_rcons inE mem_iota /= negb_or  gtn_eqF //= - leqNgt.\nhave sa: spec_sorted l1 by rewrite eb; apply: iota_rem_spec_sorted.\nhave sb: spec_sorted l2 by rewrite ec; apply: iota_rem2_spec_sorted. \nmove:(v_unique sa sb ea); rewrite eb ec => /rev_inj => ed.\nhave: i.+2 \\in rem i.+1 (iota 0 i.+3).\n  rewrite 2!iota_Sr !add0n rem_rcons1 // rem_rcons2 // ?mem_iota ?ltnn //.\n   by rewrite mem_rcons inE eqxx.\nrewrite ed mem_rem_uniq ?inE ?eqxx //; apply/ rem_uniq/iota_uniq.\nQed.\n\n\n\nLemma DUR_01 : v 0 = 1 /\\ v 1 = 2.\nProof.\nhave Ha a b l: spec_sorted [:: a, b & l] -> 2 < Zval_v (a::b::l).\n  move => /spec_sorted_sorted nab; rewrite /Zval_v !big_cons addnA. \n  apply:(@leq_trans ( v a + v b)); last by apply leq_addr.\n  move:(DUR_positive a) (DUR_positive b) => ha hb.\n  move: ha; rewrite leq_eqVlt => /orP; case => ha; last exact:(leq_add ha hb).\n  move: hb;rewrite leq_eqVlt => /orP; case=> hb;last by rewrite -(eqP ha) ltnS.\n  have eab: a = b by apply:DUR_injv; rewrite - (eqP ha) -(eqP hb).\n  by move/andP: nab=> []; rewrite eab /gtn /= ltnn.\nmove: (v_exists 2)  => [[| b l]]; first by rewrite /Zval_v big_nil //.\ncase:l; last by move => a l /Ha ha hb; move: ha; rewrite hb. \nrewrite spec_sorted_rec /Zval_v big_cons big_nil addn0/= => /andP [pa _] pb.\nmove: (v_exists 1)  => [[| a l]]; first by rewrite /Zval_v big_nil //.\ncase:l; last by move => c l /Ha ha hb; move: ha; rewrite hb. \nrewrite spec_sorted_rec /Zval_v big_cons big_nil addn0/= => /andP [pc _] pd.\nmove: pc; rewrite leqn1; case/orP => /eqP pc.\n  rewrite - pb - {1} pd; move: pa; rewrite leqn1; case/orP => /eqP pa.\n    have //: 1 = 2 by rewrite - pb - pd pa pc.\n  by rewrite pa pc.\nmove: pa; rewrite leqn1; case/orP => /eqP pa; last first.\n  have //: 1 = 2 by rewrite - pb - pd pa pc.\nmove: pb pd; rewrite pa pc => v0 v1; clear a b pa pc.\nhave Hb: forall i, 2 <= i -> 3 <= v i.\n  move => i i2;rewrite !ltn_neqAle; case: eqP.\n   by rewrite - v0; move/DUR_injv => h; move: (ltnW i2); rewrite h ltnn.\n  case: eqP; first by rewrite -v1;move/DUR_injv => h; move: i2; rewrite h ltnn.\n  by rewrite eq_sym (lt0n_neq0 (DUR_positive i)).\nhave Hc a b c l: spec_sorted [:: a, b,c & l] -> 6 <= Zval_v (a::b::c::l).\n  move => /spec_sorted_sorted nab; rewrite /Zval_v !big_cons !addnA. \n  apply:(@leq_trans (v a + v b + v c)); last by apply leq_addr.\n  move: nab => /= /andP [lta /andP [ltb _]].\n  move: (leq_ltn_trans (leq0n c) ltb); rewrite - ltnS => ltc. \n  move:(Hb _ (leq_trans ltc lta)) => ltd; case:(leqP b 1).\n    rewrite leqn1; case/orP => /eqP bv; move:ltb; rewrite bv //.\n    by rewrite ltnS leqn0 => /eqP ->; rewrite v0 v1 addn1 addn2 !ltnS.\n  move/Hb => lte; move:(leq_add ltd lte) => ltf;apply(leq_trans ltf).\n  by rewrite leq_addr.\nhave Hd: Zval_v [::] = 0 by rewrite / Zval_v big_nil.\nhave He a:spec_sorted [:: a] -> Zval_v [:: a] <= 2.\n   rewrite spec_sorted_rec /= /Zval_v big_cons big_nil addn0.\n   by rewrite leqn1; case/andP; case/orP => /eqP ->; rewrite ?v0 ?v1.\nmove: (v_exists 4) => [l].\n  case:l; [by rewrite Hd | move => a4]; case; last move => b4.\n    by move/He => h1 h2; move: h1; rewrite h2. \n  case; last by move => c4 l /Hc => h1 h2; move: h1; rewrite h2. \nmove: (v_exists 5) => [l].\n  case:l; [by rewrite Hd | move => a5]; case; last move => b5.\n    by move/He => h1 h2; move: h1; rewrite h2. \n  case; last by move => c4 l /Hc => h1 h2; move: h1; rewrite h2. \nrewrite !spec_sorted_rec /spec_sorted /= ! andbT.\nrewrite /Zval_v !big_cons !big_nil !addn0 => /andP [pa pb] pc /andP [pe pf] pg.\nmove:pb; rewrite leqn1;case/orP => /eqP eq1; move: pc; rewrite eq1; last first.\n  rewrite v1 addn1 => /eqP; rewrite eqSS => /eqP va5. \n  move: pf; rewrite leqn1;case/orP => /eqP eq2; move: pg; rewrite eq2.\n    rewrite v0; move => /eqP; rewrite addn2 eqSS eqSS - v0=> /eqP /DUR_injv.\n    by move => ba; move: pe;rewrite eq2 ba //.\n  rewrite v1 addn1 => /eqP; rewrite eqSS => /eqP va4; rewrite eq2 in pe.\n  rewrite eq1 in pa; case/orP: pa => /eqP ea;  case/orP: pe => /eqP eb.\n  + by move: va5 va4; rewrite ea eb => ->.\n  + by move:(DUR_exclusion1 1); rewrite v1 - eb va4 - {2} ea va5 //.\n  + by move:(DUR_exclusion2 0); rewrite - {1} ea - {1} eb v0 v1 va4 va5.\n  + by move: va5 va4; rewrite ea eb => ->.\nrewrite v0 addn2 => /eqP; rewrite !eqSS => /eqP va5.\nmove: pa va5; rewrite eq1; case /orP => /eqP ->;first by rewrite v1 //.\nmove => v2; clear a4 b4 a5 b5 pe pf pg eq1.\nhave Hf: v 3 != 4. \n  by apply/negP => /eqP v3; move:(DUR_exclusion2 0); rewrite v0 v1 v2 v3.\nhave Hg i: 3 <= i -> 4 <= v i.\n   move=> ha;rewrite !ltn_neqAle; case: eqP.\n     by rewrite - v2; move/DUR_injv => h; move: ha; rewrite h ltnn.\n  case: eqP; first by rewrite - v0; move/DUR_injv => h; move: ha; rewrite -h.\n  case: eqP; first by rewrite -v1;move/DUR_injv => h; move: ha; rewrite -h. \n  by rewrite eq_sym (lt0n_neq0 (DUR_positive i)).\nhave Hi a b c d l: spec_sorted [:: a, b, c, d & l] ->\n   10 <= Zval_v [:: a, b, c, d & l]. \n  move => H; move:(H).\n  move => /spec_sorted_sorted /= /andP [lta /andP [ltb /andP [ltc _]]].\n  have w: 3 <= d.+3 by [].\n  rewrite - 2!ltnS in ltc; rewrite - ltnS in ltb.\n  move: (leq_trans w (leq_trans (leq_trans ltc ltb) lta)) => /Hg la.\n  move: H; rewrite spec_sorted_rec => /= /andP [_ /Hc] lb.\n  rewrite /Zval_v (big_cons); exact:(leq_add la lb).\nmove:(v_exists 7) => [l]. \ncase:l; [by rewrite Hd | move => a7]; case.\n  by move/He => h1 h2; move: h1; rewrite h2. \nmove => b7; case; last first.  \n  have Hj i: 3 < i ->  v i + v 3 == 6  -> False.\n    move => ha hb. \n    by move: (leq_add (Hg _ (ltnW ha)) (Hg 3 (leqnn 3))); rewrite (eqP hb).\n  move => c7; case; last by move => a l /Hi => h1 h2; move: h1; rewrite h2.\n  rewrite !spec_sorted_rec /spec_sorted /= ! andbT.\n  rewrite /Zval_v !big_cons big_nil addn0 leqn1. \n  case/and3P; case/orP => /eqP ea; case/orP => /eqP eb; case/orP => /eqP ec;\n    rewrite ea eb ec ?v0 ?v1 ?v2 => /eqP.\n  + done.\n  + by rewrite -[7]/(3 + (3 +1)) (eqn_add2r) -{2} v2 => /eqP/DUR_injv.\n  + by rewrite -[7]/(2 + (3 +2)) (eqn_add2r) -{2} v0  => /eqP/DUR_injv.\n  + by rewrite addnA addn1 eqSS => /(Hj _ (leqnn 4)).\n  + by rewrite -[7]/(4 + (1 +2)) (eqn_add2r) => ha; move: Hf; rewrite ha.\n  + by rewrite -[7]/(3 + (3 +1)) (eqn_add2r)  -{2} v2 => /eqP/DUR_injv.\n  + by rewrite -[7]/(2 + (3 +2)) (eqn_add2r)  -{2} v0 => /eqP/DUR_injv.\n  + by rewrite addnA addn1 eqSS => /(Hj _ (ltnW (leqnn 5))).\nrewrite !spec_sorted_rec /spec_sorted /= ! andbT.\nrewrite /Zval_v !big_cons big_nil addn0 leqn1. \ncase/andP; case/orP => /eqP sa; case/orP => /eqP sb;\n    rewrite sa sb ? v0 ? v1 ? v2 // => /eqP; rewrite addn1 eqSS => /eqP v3.\nclear a7 b7 sa sb.\nmove:(v_exists 8) => [l]. \ncase:l; [by rewrite Hd | move => a8]; case.\n  by move/He => h1 h2; move: h1; rewrite h2. \nmove => b8; case.\n  rewrite !spec_sorted_rec /spec_sorted /= ! andbT.\n  rewrite /Zval_v !big_cons big_nil addn0 leqn1.\n  case/andP; case/orP => /eqP sa; case/orP => /eqP sb;\n    rewrite sa sb ? v0 ? v1 ? v2 // => /eqP; rewrite addn1 eqSS v3 //.\nmove => c8; case; last by move => a l /Hi => h1 h2; move: h1; rewrite h2.\nrewrite !spec_sorted_rec /spec_sorted /= ! andbT.\nrewrite /Zval_v !big_cons big_nil addn0 leqn1. \ncase/and3P; case/orP => /eqP ea; case/orP => /eqP eb; case/orP => /eqP ec;\n    rewrite ea eb ec ?v0 ?v1 ?v2 ?v3 => /eqP //.\n+ by rewrite -[8]/(1 + (6 +1)) (eqn_add2r) -{2} v1 => /eqP/DUR_injv.\n+ rewrite -[8]/(4 + (3 +1)) (eqn_add2r) => /eqP v4.\n  by move:(DUR_exclusion2 1); rewrite v1 v2 v3 v4.\n+ by rewrite -[8]/(3 + (3 +2)) (eqn_add2r) -{2} v2 => /eqP/DUR_injv.\n+ by rewrite -[8]/(1 + (6 +1)) (eqn_add2r) -{2} v1 => /eqP/DUR_injv.\nQed.\n\nLemma DUR_fib i : v i = fib i.+2.\nProof.\nmove:i.\nhave Ha l i a: i \\in a :: l -> path gtn a l -> i <= a.\n  rewrite inE; case/orP; first by move /eqP => ->.\n  elim:l i a => // a l H i b /= h /andP [ha hb]; move:h;  rewrite inE.\n  case/orP; [ by move/eqP ->; apply: ltnW |move => il;apply:H => //].\n  move: ha hb; case l => // a' l' /= ha /andP [hb ->]. \n  by rewrite (ltn_trans hb ha).\nhave Hb  k: (forall i, i < k.*2 -> v i = fib i.+2) ->\n   (v k.*2.+1 < fib k.*2.+1 \\/ \n      (v k.*2 = fib k.*2.+2 /\\ v k.*2.+1 < fib k.*2.+3)) -> False.\n  move => Hrec lta;case /andP: (max_rep_fib2 k.+1).\n  case/andP: (max_rep_fib2 k); set l' := rev _; set l := rev _.\n  move => _ /eqP zvl' ssl /eqP zvl.\n  have lt1:v k.*2.+1 < fib k.*2.+3.\n    case: lta; last by case. \n    move =>h;apply: (leq_trans h); by apply: fib_monotone;apply: ltnW => //.\n  have lv: l = k.*2.+1 :: l'.\n     rewrite /l /l' /mkseq iota_Sr /succ_seq - !map_comp /comp - !map_rev.\n     by rewrite rev_rcons.\n  set s :=  \\sum_(i <- l) v i; set s' := Zeck_val l.\n  have eqr: \\sum_(i <- l') v i = Zeck_val l'.\n    rewrite /Zeck_val /l' ! sum_rev /mkseq /succ_seq !big_map.\n    apply: eq_big_seq => i; rewrite mem_iota /= add0n => ik.\n    by apply: Hrec; rewrite ltn_Sdouble.\n  move: (ZeckM_prop2 s); set z := ZeckM s; move /andP => [ssz /eqP].\n  move: ssz; case:z. \n    rewrite Zeckv_nil /s lv big_cons => _ /eqP; rewrite eq_sym addn_eq0.\n    by move/andP => [/eqP h _]; move:(DUR_positive k.*2.+1); rewrite h.\n  move => hz tz ssz zv.\n  move:(max_rep_bound ssz); rewrite zv; move => /andP [le2 _ ].\n  have: s < s' by rewrite /s/s' lv Zeckv_cons big_cons eqr ltn_add2r. \n  move/(leq_ltn_trans le2); rewrite /s' zvl - ltnS - fib_pos // - fib_pos //.\n  move/fib_monotone_bis; rewrite doubleS !ltnS => hm.\n  suff Hz: forall i, i <= hz -> v i = fib i.+2.\n    have eq2: Zval_v (hz :: tz) = Zval_v l.\n      rewrite -[RHS] zv /Zeck_val /Zval_v;apply: eq_big_seq => i il.\n      exact (Hz _ (Ha _ _ _ il (spec_sorted_sorted ssz))).\n    move:(v_unique ssz ssl eq2);rewrite lv; case => eq3.\n    by move: hm; rewrite eq3 ltnn.\n  case: lta; last first.\n    move => [pa pb] i li; move: (leq_trans li hm); rewrite leq_eqVlt.\n    by case/orP; [ move/eqP => -> // | apply/ Hrec ].\n  move => la.\n  have: s < (fib k.*2.+3).-1. \n    rewrite /s lv big_cons eqr zvl' (fibSS k.*2.+1) {2} (fib_pos k.*2.+1). \n    by rewrite addSn addnC ltn_add2l.\n  move/(leq_ltn_trans le2); rewrite - ltnS - fib_pos //- fib_pos //.\n  move/fib_monotone_bis;rewrite  !ltnS => hm1 i ih; apply: Hrec.\n  apply: (leq_ltn_trans ih hm1). \nhave Hc k: (forall i, i < k.*2.+1 -> v i = fib i.+2) ->\n   (v k.*2.+2 < fib k.*2.+2 \\/ \n      (v k.*2.+1 = fib k.*2.+3 /\\ v k.*2.+2 < fib k.*2.+4)) -> False.\n  move => Hrec lta; case /andP: (max_rep_fib1 k.+2).\n  case /andP: (max_rep_fib1 k.+1); set l' := rev _; set l := rev _.\n  move => _ /eqP zl' ssl /eqP zvl.\n  have lv: l = k.+1.*2 :: l' by rewrite /l/l'/mkseq iota_Sr -!map_rev rev_rcons.\n  set s := \\sum_(i <- l) v i; set s' := Zeck_val l.\n  have lt1:v k.*2.+2 < fib k.*2.+4.\n    case: lta; last by case. \n    move =>h;apply: (leq_trans h); by apply: fib_monotone;apply: ltnW => //.\n   have eqr: \\sum_(i <- l') v i = Zeck_val l'.\n    rewrite /Zeck_val /l' ! sum_rev /mkseq /succ_seq !big_map.\n    apply: eq_big_seq => i; rewrite mem_iota /= add0n => ik.\n    by apply: Hrec; rewrite ltnS leq_double - ltnS.\n  move: (ZeckM_prop2 s); set z := ZeckM s; move /andP => [ssz /eqP].\n  move: ssz; case:z. \n    rewrite Zeckv_nil /s lv big_cons => _ /eqP; rewrite eq_sym addn_eq0.\n    by move/andP => [/eqP h _]; move:(DUR_positive (k.+1).*2); rewrite h.\n  move => hz tz ssz zv.\n  move:(max_rep_bound ssz); rewrite zv; move => /andP [le2 _ ].\n  have: s < s' by rewrite /s/s' lv Zeckv_cons big_cons eqr ltn_add2r.\n  move/(leq_ltn_trans le2); rewrite /s' zvl - ltnS - fib_pos // - fib_pos //.\n  move/fib_monotone_bis; rewrite doubleS 3!ltnS => hm.\n  suff Hz: forall i, i <= hz -> v i = fib i.+2.\n    have eq2: Zval_v (hz :: tz) = Zval_v l.\n      rewrite -[RHS] zv /Zeck_val /Zval_v;apply: eq_big_seq => i il.\n      exact (Hz _ (Ha _ _ _ il (spec_sorted_sorted ssz))).\n    move:(v_unique ssz ssl eq2);rewrite lv; case => eq3.\n    by move: hm; rewrite eq3 ltnn.\n  case: lta; last first.\n    move => [pa pb] i li; move: (leq_trans li hm); rewrite leq_eqVlt.\n    by case/orP; [ move/eqP => -> // | apply/ Hrec ].\n  move => la.\n  have: s < (fib k.*2.+4).-1. \n    rewrite /s lv big_cons eqr zl' (fibSS k.*2.+2) {2} (fib_pos k.*2.+2). \n    by rewrite addSn addnC ltn_add2l.\n  move/(leq_ltn_trans le2); rewrite - ltnS - fib_pos //- fib_pos //.\n  move/fib_monotone_bis;rewrite  !ltnS => hm1 i ih; apply: Hrec.\n  by rewrite ltnS (leq_trans ih hm1). \nhave Hj a l: spec_sorted l -> a \\in l -> exists w L,\n    spec_sorted (a :: L) /\\ l = w ++  (a :: L).\n  elim: l a => [ a // | b l H a ha]. \n  rewrite inE; case/orP; first by by move => /eqP ->; exists nil, l. \n  move: ha; rewrite spec_sorted_rec => /andP[_] ha hb; move:(H _ ha hb).\n  by move => [w [L [hc ->]]]; exists (b::w), L.\nmove => i. \nmove:DUR_01 =>[v0 v1].\nelim: i {-2} i (leqnn i); first by move => i; rewrite leqn0 => /eqP -> //.\nmove => n Hrec n1; rewrite leq_eqVlt; case/orP=> [|Hn]; last first.\n  by apply: Hrec; rewrite -ltnS.\nmove/eqP ->; clear n1.\ncase: (ltngtP (v n.+1)(fib n.+3)) => // lt1.\n  case: (odd_dichot n.+1); set k := (n.+1)./2 => nv.\n    move: nv => /eqP;rewrite eqSS => /eqP nv; case: (Hb k).\n      by rewrite - nv; move => i /ltnW /Hrec.\n    by right; rewrite - nv; split => //; apply: Hrec.\n  have nv2: n = (k.-1).*2.+1.\n     by move: nv; case:k => // k /= /eqP; rewrite doubleS eqSS => /eqP.\n  case: (Hc k.-1).\n    by move => i; rewrite -nv2 => /ltnW/Hrec.\n  by right; rewrite - nv2; split => //; apply: Hrec.\nmove: lt1;case: (ltngtP (fib n.+3) (v n.+1)) => // lt2 _.\nmove:(fib_sum_alt n.+1); rewrite - Zeckv_rev; set l := rev (iota 0 n.+1) => xm1.\nhave eq2: Zval_v l = Zeck_val l.\n  rewrite /Zeck_val /Zval_v; apply: eq_big_seq => i il; apply/ Hrec.\n  by move: il; rewrite /l mem_rev mem_iota /= ltnS.\nset x := (Zval_v l).+1; move: (v_exists x) => [L].\ncase:L =>[ |a L ss sv]; first by rewrite/Zval_v big_nil /x.\nhave Hi k: (fib k.+4).-2.+2 = fib k.+4.\n  have:  fib 3 < fib k.+4 by apply:fib_smonotone_bis.\n  by move/ltnW /subnK; rewrite subn2 addn2.\ncase: (leqP a n) => can.\n  have eq1: Zval_v (a :: L) = Zeck_val (a :: L).\n    rewrite /Zeck_val /Zval_v; apply: eq_big_seq => i il.\n    move:(leq_trans (Ha _ _ _ il (spec_sorted_sorted ss)) can); apply: Hrec.\n  move: (max_rep_bound ss); rewrite - eq1 sv /x eq2 xm1. \n  move /andP => [_]. rewrite - ltnS Hi - fib_pos => /fib_monotone_bis.\n  by rewrite !ltnS ltnNge can.\ncase nl: (n.+1 \\in (a::L)).\n  move:(Hj _ _ ss nl) => [w [l1 [sl1 l1v]]].\n  have eq3: \\sum_(j <- l1) v j = Zeck_val l1.\n    rewrite /Zeck_val; apply: eq_big_seq => i.\n    move: sl1; rewrite spec_sorted_rec; case/andP =>[].\n    case l1 => // b l2 /= pa pb pc; apply: Hrec.\n    apply: (leq_trans (Ha _ _ _  pc (spec_sorted_sorted pb))).\n    by move:pa; rewrite !eqSS; case/orP => /eqP ->.\n  have lta: Zeck_val (n.+1::l1) <= (fib n.+4).-2.\n    move: lt2; rewrite -(ltn_add2r ( Zeck_val l1));rewrite Zeckv_cons => h.\n    rewrite - ltnS;apply: (leq_trans h); rewrite -xm1 - eq2 -eq3 -/x -sv. \n    by rewrite /Zval_v l1v big_cat big_cons/=; apply: leq_addl.\n  move: (max_rep_bound sl1) => /andP [hh _].\n  by move: (leq_trans hh lta);rewrite - {1} Hi /= ltnn.\ncase nl2: (n.+2 \\in (a::L)); last first.\n   move:(negbT nl2); move/negP; case; move: ss can nl; clear.\n   elim: L a n.  \n     move => a n;rewrite spec_sorted_rec /= => /andP[la1 _] na.  \n     move:(leq_trans na la1); rewrite ltnS leqn0 => nz.\n     by move: la1 na; rewrite (eqP  nz) inE; case a => //; case.\n  move => a l Hrec b n; rewrite spec_sorted_rec /= => /andP[ha hb].\n  rewrite inE leq_eqVlt; case: (n.+1 == b) => //=;rewrite  leq_eqVlt !inE. \n  case: (n.+2 == b) => //=; move => nb; apply: Hrec => //.\n  by move: nb; case /orP: ha => /eqP -> // h; apply: ltnW.\nmove: (Hj _ _ ss nl2) => [w [l2 [sa sb]]].\nmove: nl; rewrite sb; rewrite mem_cat => /norP [_] nl.\nmove: sa sb nl; rewrite spec_sorted_rec; case: l2 => // b l2 /=.\nrewrite !inE !eqSS => /andP []; case/orP; first by move => -> //=;rewrite orbT.\nmove => /eqP <- => pa pb _.\nmove: (max_rep_bound pa) => /andP [lt1 _].\nhave pc: \\sum_(j <- (n :: l2)) v j = Zeck_val (n :: l2).\n  rewrite /Zeck_val; apply: eq_big_seq => i il; apply: Hrec.\n  exact: (Ha _ _ _  il (spec_sorted_sorted pa)).\nmove: sv; rewrite pb /Zval_v big_cat /= big_cons pc /x eq2 xm1 => sa.\nmove:(leq_addl (\\sum_(i <- w) v i) (v n.+2 + Zeck_val (n :: l2))).\nrewrite sa fibSS fib_pos addSn (fib_pos n.+1) addnS /= -addnS - fib_pos => lt3.\nmove: lt1; rewrite - (leq_add2r (fib n.+2)) => lt4.\nmove:(leq_trans lt3 lt4); rewrite addnC leq_add2l leq_eqVlt.\nhave W: forall k, k.+2 = k -> False by elim => // k H; case.\ncase: eqP; first by rewrite -(Hrec n (leqnn n)) => /DUR_injv // /W.\nmove => _ /= Hx.\ncase: (odd_dichot n.+2); set k := (n.+2)./2 => nv.\n  move: nv => /eqP;rewrite eqSS => /eqP nv; case: (Hb k); rewrite - nv //.\n  by left.\nmove: (Hc k.-1).\nhave  <-: n = (k.-1).*2.\n  by move: nv; case:k => // k /= /eqP; rewrite doubleS !eqSS => /eqP.\nby case => //; left.\nQed.\n\nEnd  DualUniqueRepresentation.\n\n\n(* -------------------------------------------------------- *)\n\n(** The cardinal of the stuff *)\n\n\n\nDefinition seto_to_seq B (l: {set 'I_B.+1}) := \n  [seq (nat_of_ord i) | i <- enum l].\n\n\nDefinition seq_to_seto B l := \n  [set i | i in [seq (inord i : 'I_B.+1) | i <- l]].\n\n\nLemma seto_to_seqK B (s: {set 'I_B.+1}) : seq_to_seto B (seto_to_seq s) = s.\nProof.\nrewrite /seq_to_seto/seto_to_seq - map_comp /comp.\napply/setP =>i; apply/imsetP/idP.\n  by move => [x /mapP [y ]]; rewrite mem_enum inord_val => ys -> ->. \nmove => h; rewrite - (inord_val i);exists (inord i) => //.\nby apply: map_f; rewrite mem_enum.\nQed.\n\n\nLemma seq_to_setoK B (l:  seq nat): \n  uniq l -> (all (fun z => z < B.+1) l) ->\n  perm_eq (seto_to_seq (seq_to_seto B l)) l.\nProof.\nmove => ul /allP bl.\nrewrite /seq_to_seto/seto_to_seq.\napply: uniq_perm => //.\n   rewrite map_inj_uniq; [ apply: enum_uniq | apply: ord_inj].\nmove => x;  apply/mapP/idP.\n  move=> [i]; rewrite mem_enum => /imsetP [j /mapP [k kl ->] ->] ->.\n  by rewrite inordK //; apply: bl.\nmove => xl; exists (inord x); last by rewrite inordK //; apply: bl.\nby rewrite mem_enum; apply /imsetP; exists (inord x) => //; apply: map_f.\nQed.\n\nLemma uniq_seto_to_seq B l: uniq (@seto_to_seq B l).\nProof. rewrite map_inj_uniq;[ exact: enum_uniq | exact:ord_inj]. Qed.\n\nLemma Zeckvp_bnd l i: i \\in l -> i <= Zeck_valp l.\nProof.\nelim: l i => // [a l Hrec i /=]; rewrite in_cons Zeckvp_cons; case/orP. \n   move /eqP => ->; case: a => // a.\n   apply: (leq_trans ((fib_gen a.+1))); apply: leq_addr.\nmove/Hrec/leq_trans => -> //; exact:leq_addl.\nQed.\n\nLemma Zeckv_bnd0 l i: i \\in l -> fib (i.+2) <= Zeck_val l.\nProof.\nelim: l i => // [a l Hrec i /=]; rewrite in_cons Zeckv_cons; case/orP. \n   move /eqP => ->; case: a => // a; apply: leq_addr.\nmove/Hrec/leq_trans => -> //; exact:leq_addl.\nQed.\n\nLemma Zeckv_bnd l i: i \\in l -> i <= Zeck_val l.\nProof. rewrite Zeck_valppE=> /Zeckvp_bnd/leq_trans -> //; exact: leq_addr. Qed.\n\nDefinition Zeck_sval B (t:{set 'I_B.+1}) := \\sum_(i in t) (fib i.+2).\nDefinition Zeck_svalp B (t:{set 'I_B.+1}) := \\sum_(i in t) (fib i.+1).\n\nLemma Zeck_val_cv0 B (t:{set 'I_B.+1}) (f:nat->nat):\n  \\sum_(i <- (seto_to_seq t)) f i =  \\sum_(i in t) f i.\nProof.\ntransitivity (\\sum_(i <- (enum t)) (f i)).\n  rewrite /seto_to_seq /Zeck_val;elim (enum t); first by rewrite ! big_nil. \n  by move => a l h; rewrite map_cons !big_cons h.\nby rewrite big_enum.\nQed.\n\nLemma Zeck_val_cv1 B (t:{set 'I_B.+1}) :\n  Zeck_val (seto_to_seq t) =  Zeck_sval t.\nProof. exact: Zeck_val_cv0. Qed.\n\nLemma Zeck_valp_cv1 B (t:{set 'I_B.+1}) :\n   Zeck_valp (seto_to_seq t) =  Zeck_svalp t.\nProof. exact: Zeck_val_cv0. Qed.\n\nLemma Zeck_val_cv2 l B (n := Zeck_val l): uniq l -> n <= B ->\n   n =  Zeck_sval (seq_to_seto B l).\nProof.\nmove => sa sb.\nsymmetry;rewrite - Zeck_val_cv1; apply: perm_big; apply:(seq_to_setoK sa).\napply /allP => i /Zeckv_bnd lin; rewrite ltnS; apply: (leq_trans lin sb).\nQed.\n\nLemma Zeck_valp_cv2 l B (n := Zeck_valp l): uniq l -> n <= B ->\n  n =  Zeck_svalp (seq_to_seto B l).\nProof.\nmove => sa sb.\nsymmetry;rewrite - Zeck_valp_cv1; apply: perm_big; apply:(seq_to_setoK sa).\napply /allP => i /Zeckvp_bnd lin; rewrite ltnS; apply: (leq_trans lin sb).\nQed.\n\n\nDefinition GRr B n := #|[set t:{set 'I_B.+1} | Zeck_sval t == n ]|.\nDefinition GAr B m n := #|[set t:{set 'I_B.+1} | \n   (Zeck_svalp t == m) && (Zeck_sval t == n) ]|.\n\nDefinition GR n := GRr n n.\nDefinition GA m n := GAr n m n.\n\nLemma GARr_aux n B \n  (g: ({set 'I_n.+1} ->  {set 'I_B.+1})\n     := (fun t => [set (inord (i:'I_n.+1)) | i in  t])):\n  n <= B -> \n  (injective g /\\ forall (t:{set 'I_n.+1}) (F: nat -> nat), \n     \\sum_(i in t) F i= \\sum_(i in (g t)) F i).\nProof.\nrewrite -ltnS => lenB.\nset f: ('I_n.+1 ->  'I_B.+1) := fun i => inord i.\npose Hw x := (inordK (leq_trans (ltn_ord x) lenB)).\nhave Ha: injective f.\n   move => i j; rewrite /f => sa.\n   move:(f_equal (@nat_of_ord B.+1) sa); rewrite (Hw i) (Hw j); apply:ord_inj.\nsplit.\n  rewrite /g => x y si; apply /setP => i; apply/idP/idP => ha.\n     have: (f i) \\in  [set f i | i in x] by apply/imsetP; exists i.\n     by rewrite si => /imsetP [t ty /Ha ->].\n  have: (f i) \\in  [set f i | i in y] by apply/imsetP; exists i.\n  by rewrite - si => /imsetP [t ty /Ha ->]. \nmove => t F.\nrewrite - (Zeck_val_cv0 t) - (Zeck_val_cv0 (g t)).\napply: perm_big; apply: uniq_perm.\n+ rewrite map_inj_uniq; [ apply: enum_uniq | apply: ord_inj].\n+ rewrite map_inj_uniq; [ apply: enum_uniq | apply: ord_inj].\n+ rewrite /seto_to_seq => i; rewrite /g;apply /mapP/idP.\n    move => [x]; rewrite mem_enum => xt ->. \n    by rewrite -(Hw x) map_f // mem_enum; apply /imsetP; exists x.\n  move/mapP => [j];rewrite mem_enum; move/imsetP => [k kt -> ->].\n  by apply/mapP; rewrite (Hw k) map_f // mem_enum.\nQed.\n\nLemma GRr_big0 A B n: n < fib A.+3 -> A <= B -> GRr A n = GRr B n.\nProof.\nrewrite /GRr => ns lenm.\nmove:(GARr_aux lenm); set g := (fun t:_ => _); move => [Hb Hx].\nmove:lenm; rewrite - ltnS => lenm.\npose Hw x := (inordK (leq_trans (ltn_ord x) lenm)).\nhave Hc: forall t, Zeck_sval t =  Zeck_sval (g t).\n  move => t; apply: (Hx t (fun z => (fib z.+2))).\nset pn := [pred t : {set 'I_A.+1} | Zeck_sval t == n].\nrewrite cardsE -(card_imset pn Hb).\napply: eq_card => e; rewrite inE; apply/imsetP/idP.\n  by move => [x]; rewrite  inE Hc => ww ->.\nset l :=(seq_to_seto A (seto_to_seq e)) => eq.\nsuff ww : e = g l by exists l => //; rewrite /pn inE Hc - ww.\nhave Hd: forall i, i \\in e -> i <= A.\n  move => i ie.\n  rewrite - 3!ltnS; apply:fib_monotone_bis; apply: leq_trans ns. \n   rewrite ltnS -(eqP eq) - Zeck_val_cv1.\n   by apply:Zeckv_bnd0; rewrite  /seto_to_seq map_f // mem_enum.\nrewrite /l /g /seq_to_seto/seto_to_seq - map_comp /comp.\napply/setP =>i; apply/idP/imsetP.\n  move => ie;  move:(inordK (Hd _ ie)) => sa.\n  rewrite - mem_enum in ie; exists (inord i); last by rewrite sa inord_val. \n  by apply /imsetP;  exists (inord i) => //;rewrite (map_f _ ie).\nmove => [j /imsetP [k /mapP [x]]];rewrite mem_enum => H.\nby move => -> -> -> /=; rewrite inordK ? inord_val // ltnS Hd.\nQed.\n\nLemma GAr_big0 A B m n:  ((m < fib A.+2) || (n < fib A.+3)) -> A <= B -> \n    GAr A m n = GAr B m n.\nProof.\nrewrite /GRr => ns lenm.\nmove:(GARr_aux lenm); set g := (fun t:_ => _); move => [Hb Hx].\nmove:lenm; rewrite - ltnS => lenm.\nhave HB0 l i: i \\in l -> fib (i.+1) <= Zeck_valp l.\n  elim: l i => // [a l Hrec i /=]; rewrite in_cons Zeckvp_cons; case/orP. \n     move /eqP => ->; case: a => // a; apply: leq_addr.\n  move/Hrec/leq_trans => -> //; exact:leq_addl.\npose Hw x := (inordK (leq_trans (ltn_ord x) lenm)).\nhave Hc1: forall t, Zeck_sval t =  Zeck_sval (g t).\n  move => t; apply: (Hx t (fun z => (fib z.+2))).\nhave Hc2: forall t, Zeck_svalp t =  Zeck_svalp (g t).\n  move => t; apply: (Hx t (fun z => (fib z.+1))). \nset pn := [pred t : {set 'I_A.+1} | Zeck_svalp t == m & Zeck_sval t == n].\nrewrite /GAr cardsE -(card_imset pn Hb).\napply: eq_card => e; rewrite inE; apply/imsetP/idP.\n  by move => [x]; rewrite  inE Hc1 Hc2 => ww ->.\nset l :=(seq_to_seto A (seto_to_seq e)) => eqa.\nmove: (eqa) => /andP[/eqP eqb /eqP eqc].\nsuff ww : e = g l by exists l => //; rewrite /pn inE Hc1 Hc2 - ww.\nhave Hd: forall i, i \\in e -> i <= A.\n  move => i ie.\n  have ie': (nat_of_ord i) \\in  (seto_to_seq e).\n    by rewrite  /seto_to_seq map_f // mem_enum. \n  move: (Zeckv_bnd0 ie')(HB0 _ _ ie').\n  rewrite Zeck_val_cv1  Zeck_valp_cv1 eqb eqc => la lb; case/orP: ns => lc.\n    by move: (leq_ltn_trans lb lc) => /fib_monotone_bis; rewrite !ltnS.\n  by move: (leq_ltn_trans la lc) => /fib_monotone_bis; rewrite !ltnS.\nrewrite /l /g /seq_to_seto/seto_to_seq - map_comp /comp.\napply/setP =>i; apply/idP/imsetP.\n  move => ie;  move:(inordK (Hd _ ie)) => sa.\n  rewrite - mem_enum in ie; exists (inord i); last by rewrite sa inord_val. \n  by apply /imsetP;  exists (inord i) => //;rewrite (map_f _ ie).\nmove => [j /imsetP [k /mapP [x]]];rewrite mem_enum => H.\nby move => -> -> -> /=; rewrite inordK ? inord_val // ltnS Hd.\nQed.\n\nLemma GRr_big B n: n <= B -> GRr B n = GR n.\nProof.\nrewrite /GR => lnb; symmetry; apply:GRr_big0 => //.\nby apply: leq_trans (fib_gen n.+2).\nQed.\n\n\nLemma GAr_big B m n: n <= B -> GAr B m n = GA m n.\nProof.\nrewrite /GA => lnb; symmetry; apply:GAr_big0 => //.\nby rewrite  (leq_ltn_trans  (leqnSn n)(fib_gen n.+2)) orbT.\nQed.\n \nLemma GAr_notz B m n: GAr B m n!= 0 -> m = Zeckp n.\nProof.\nrewrite /GAr cards_eq0 => /set0Pn [x ];rewrite inE => /andP [/eqP pa /eqP pb].\nmove:(Zeck_val_cv1 x) (Zeck_valp_cv1 x); rewrite - pa - pb  => <- <-.\nsymmetry; apply: Zeckp_prop1; apply:uniq_seto_to_seq.\nQed.\n\nLemma GARr_e B n: GAr B (Zeckp n) n = GRr B n.\nProof.\nrewrite /GAr/GRr; apply: eq_card => e; apply /idP/idP;rewrite !inE.\n  by move/andP => [].\nmove => /eqP <-; rewrite  eqxx andbT  - Zeck_val_cv1 - Zeck_valp_cv1. \napply/eqP; symmetry; apply: Zeckp_prop1;  apply:uniq_seto_to_seq.\nQed.\n\nLemma GAR_e n: GA (Zeckp n) n = GR n.\nProof. exact:GARr_e. Qed.\n\nLemma GRr_notz B n: fib B.+4 <= n.+1 -> GRr B n = 0.\nProof.\nsuff: GRr B n != 0 -> n.+2 <= fib B.+4.\n by move/contraR; rewrite -leqNgt => h h1; apply/eqP/h.\nrewrite cards_eq0 => /set0Pn [x ];rewrite inE => /eqP pa.\nrewrite -pa -(Zeck_val_cv1 x). apply: (Zeckv_bound3 (uniq_seto_to_seq x)).\nby apply/allP => i /mapP [j _ ->];case:j.\nQed.\n\nLemma GRr_b0 B:  GRr B 0 = 1.\nProof.\nrewrite /GRr; set E :=  [set t | _];set v := (@set0 ( (ordinal_finType B.+1))).\nsuff: [set v] = E by move => <-; rewrite cards1.\napply/ setP => x; rewrite !inE - Zeck_val_cv1; apply/eqP/eqP => h. \n  by rewrite h /seto_to_seq enum_set0 /= Zeckv_nil.\ncase ee: (x==v); [by apply/eqP |move:(negbT ee) ]. \nmove/set0Pn => [u]; rewrite - mem_enum - (mem_map (@ord_inj B.+1)). \nmove: h; rewrite -/(seto_to_seq _ ); case (seto_to_seq x) => // a l bad.\nby move: (Zeckv_pos a l); rewrite bad.\nQed.\n\nLemma GRr_b1 B:  GRr B 1 = 1.\nProof.\nrewrite /GRr; set E :=  [set t | _];set v := [set (@ord0 B) ].\nsuff: [set v] = E by move => <-; rewrite cards1.\napply/ setP => x; rewrite !inE - Zeck_val_cv1; apply/eqP/eqP => h. \n  by rewrite h /v /seto_to_seq enum_set1 /= Zeckv_cons Zeckv_nil.\nhave eqa: (seto_to_seq x)  = [::0].\n  move: h; case: (seto_to_seq x); first by rewrite Zeckv_nil.\n  move => a l; rewrite Zeckv_cons; case: a.\n    rewrite /fib/= addn0 - {2}(addn0 1) => /eqP; rewrite eqSS; case: l => //.\n    by move => b l /eqP h; move:(Zeckv_pos b l); rewrite h.\n  move => n. \n  move:(leq0n n); rewrite - ltnS => /fib_smonotone_bis => h1 h2.\n  by move: (leq_trans h1 (leq_addr (Zeck_val l) (fib n.+3))); rewrite h2.\nrewrite - (seto_to_seqK x) eqa /seq_to_seto /v /=.\nmove: (inord_val (@ord0 B)) => /= eqb.\napply/setP => i; rewrite inE eqb; apply/imsetP/eqP. \n  by move=> [y ]; rewrite inE => /eqP ea ->.\nby move => ->; exists ord0. \nQed.\n\nLemma GRr_0n n:  GRr 0 n = (n<=1).\nProof.\nmove: (@GRr_notz 0 n);rewrite !ltnS; case: n; first by rewrite GRr_b0.\nby case; [ by rewrite GRr_b1 | move => n]; rewrite !ltnS ltn0; apply.\nQed.\n\nLemma GRr_Sbn B n : \n  GRr B.+1 n =  GRr B n + (GRr B (n- fib(B.+3))) * (fib(B.+3) <= n).\nProof.\ncase: (ltnP n (fib B.+3)).\n  by rewrite muln0 addn0 => le1; rewrite - (GRr_big0 le1 (leqnSn B)).\nset b := (@ord_max B.+1).\nrewrite muln1 addnC /GRr => eq1. \nset E := [set t | Zeck_sval t == n].\nhave hb: forall (p: (pred {set 'I_B.+2})),\n #|[pred x | x \\in p & x \\in E]| =\n #|[set t | (p t) && (Zeck_sval t == n) ]|.\n  by move => p; rewrite cardsE;apply: eq_card => x; rewrite !inE.\nset p := [pred t:{set 'I_B.+2} | b \\in t].\nhave ha: #|[predI E & p]| = #|[pred x | (mem p) x &  (mem E) x]|. \n   by apply: eq_card => x; exact: andbC.\nmove:(GARr_aux (leqnSn B)); set g := (fun t: _ => _); move => [ig aux].\nhave ig2: forall (t : {set 'I_B.+1}), Zeck_sval t = Zeck_sval (g t).\n  move => t; rewrite/Zeck_sval; apply: (aux t (fun i => fib i.+2)).\nhave gpn: forall x, b \\notin (g x).\n  move => x;  apply/imsetP => [[w _ eq2]]; have hc:= (ltn_ord w).\n  move:(inordK (leq_trans hc (leqnSn B.+1))); rewrite - eq2.\n  by apply/eqP/negbT; apply:gtn_eqF. \nrewrite - (cardID p) ha hb hb; congr addn; symmetry;last first.\n  set pn := [pred t : {set 'I_B.+1} | Zeck_sval t == n].\n  rewrite cardsE -(card_imset pn ig).\n  apply: eq_card => e; rewrite inE; apply/imsetP/idP.\n    move => [x]; rewrite inE ig2 => ww ->;rewrite ww andbT; apply: gpn.\n  move/andP => [hc hd].\n  have Hd: forall i, i \\in e -> i <= B.\n    move => i ie; have:= (ltn_ord i); rewrite ltnS leq_eqVlt; case/orP => // eb.\n    have he: i = b by apply: ord_inj; rewrite (eqP eb) //.\n    by move: hc; rewrite /p he !inE - he ie.\n  set l :=(seq_to_seto B (seto_to_seq e)). \n  suff ww : e = g l by exists l => //; rewrite /pn inE ig2 - ww.\n  rewrite /l /g /seq_to_seto/seto_to_seq - map_comp /comp.\n  apply/setP =>i; apply/idP/imsetP.\n    move => ie;  move:(inordK (Hd _ ie)) => sa.\n    rewrite - mem_enum in ie; exists (inord i); last by rewrite sa inord_val. \n    by apply /imsetP;  exists (inord i) => //;rewrite (map_f _ ie).\n  move => [j /imsetP [k /mapP [x]]];rewrite mem_enum => H.\n  by move => -> -> -> /=; rewrite inordK ? inord_val // ltnS Hd.\nset pn := [pred t : {set 'I_B.+1} | Zeck_sval t == n- fib B.+3].\npose g1 t := b |: g t. \nhave hc: forall t, p (g1 t) by move => t; apply/setU11. \nhave ig1: injective g1.\n  move => t1 t2; rewrite /g1 => w; apply: ig.\n  by rewrite - (setU1K (gpn t1)) w (setU1K (gpn t2)).\nrewrite cardsE -(card_imset pn ig1).\nhave ig2': forall t, fib B.+3 + Zeck_sval t = Zeck_sval (g1 t).\n  by move => t; rewrite ig2 / Zeck_sval /g1 big_setU1.\napply: eq_card => e; rewrite inE; apply/imsetP/idP.\n    move => [x]; rewrite inE => /eqP sa sb.\n  by rewrite sb hc - (subnK eq1) - sa addnC ig2' eqxx.\nmove/andP => [hc1 hd2]. \nset e1 := e :\\ b.\nhave Hd: forall i, i \\in e1 -> i <= B.\n  move => i /setD1P[ib ie]. \n  have:= (ltn_ord i); rewrite ltnS leq_eqVlt; case/orP => // eb.\n  by case/negP:ib; apply/eqP /ord_inj; rewrite (eqP eb).\nset l :=(seq_to_seto B (seto_to_seq e1)). \nsuff ww : e = g1 l. \n  exists l => //; rewrite /pn inE.\n  by move: ww; rewrite - (eqP hd2) => ->; rewrite - ig2' addKn.\nrewrite /l /g1 /seq_to_seto/seto_to_seq - map_comp /comp.\nrewrite - {1} (setD1K hc1); congr setU. \napply/setP =>i; apply/idP/imsetP. \n  move => ie;  move:(inordK (Hd _ ie)) => sa.\n  rewrite - mem_enum in ie; exists (inord i); last by rewrite sa inord_val.\n  by apply /imsetP;  exists (inord i) => //;rewrite (map_f _ ie).\nmove => [j /imsetP [k /mapP [x]]];rewrite mem_enum => H.\nby move => -> -> -> /=; rewrite inordK ? inord_val // ltnS Hd.\nQed.\n\n\nLemma GAr_Sbn B m n: \n  GAr B.+1 m n =  GAr B m n + \n    (GAr B (m - fib (B.+2)) (n- fib(B.+3))) \n    * (fib(B.+3) <= n) * (fib(B.+2) <= m).\nProof.\nset b := (@ord_max B.+1). \ncase: (ltnP n (fib B.+3)).\n  rewrite muln0 addn0 => le1. \n  have ha: (m < fib B.+2) || (n < fib B.+3) by rewrite le1 orbT.\n  by rewrite -(GAr_big0 ha (leqnSn B)).\ncase: (ltnP m (fib B.+2)).\n  rewrite muln0 addn0 => le1 le2. \n  have ha: (m < fib B.+2) || (n < fib B.+3) by rewrite le1.\n  by rewrite -(GAr_big0 ha (leqnSn B)).\nrewrite !muln1 addnC /GAr => leqfm leqfn. \nset E := [set t | _].\nhave hb: forall (p: (pred {set 'I_B.+2})),\n #|[pred x | x \\in p & x \\in E]| =\n #|[set t | (p t) && ((Zeck_svalp t == m) && (Zeck_sval t == n)) ]|.\n  by move => p; rewrite cardsE;apply: eq_card => x; rewrite !inE.\nset p := [pred t:{set 'I_B.+2} | b \\in t].\nhave ha: #|[predI E & p]| = #|[pred x | (mem p) x &  (mem E) x]|. \n   by apply: eq_card => x; exact: andbC.\nmove:(GARr_aux (leqnSn B)); set g := (fun t: _ => _); move => [ig aux].\nhave ig2: forall (t : {set 'I_B.+1}), Zeck_sval t = Zeck_sval (g t).\n  move => t; rewrite/Zeck_sval; apply: (aux t (fun i => fib i.+2)).\nhave ig2': forall (t : {set 'I_B.+1}), Zeck_svalp t = Zeck_svalp (g t).\n  move => t; rewrite/Zeck_sval; apply: (aux t (fun i => fib i.+1)).\nhave gpn: forall x, b \\notin (g x).\n  move => x;  apply/imsetP => [[w _ eq2]]; have hc:= (ltn_ord w).\n  move:(inordK (leq_trans hc (leqnSn B.+1))); rewrite - eq2.\n  by apply/eqP/negbT; apply:gtn_eqF. \nrewrite - (cardID p) ha hb hb; congr addn; symmetry;last first.\n  set pn := [pred t : {set 'I_B.+1} |(Zeck_svalp t == m) && (Zeck_sval t == n)].\n  rewrite cardsE -(card_imset pn ig).\n  apply: eq_card => e; rewrite inE; apply/imsetP/idP.\n    move => [x]; rewrite inE ig2 ig2' => ww ->;rewrite ww andbT; apply: gpn.\n  move/andP => [hc hd].\n  have Hd: forall i, i \\in e -> i <= B.\n    move => i ie; have:= (ltn_ord i); rewrite ltnS leq_eqVlt; case/orP => // eb.\n    have he: i = b by apply: ord_inj; rewrite (eqP eb) //.\n    by move: hc; rewrite /p he !inE - he ie.\n  set l :=(seq_to_seto B (seto_to_seq e)). \n  suff ww : e = g l by exists l => //; rewrite /pn inE ig2 ig2' - ww.\n  rewrite /l /g /seq_to_seto/seto_to_seq - map_comp /comp.\n  apply/setP =>i; apply/idP/imsetP.\n    move => ie;  move:(inordK (Hd _ ie)) => sa.\n    rewrite - mem_enum in ie; exists (inord i); last by rewrite sa inord_val. \n    by apply /imsetP;  exists (inord i) => //;rewrite (map_f _ ie).\n  move => [j /imsetP [k /mapP [x]]];rewrite mem_enum => H.\n  by move => -> -> -> /=; rewrite inordK ? inord_val // ltnS Hd.\nset pn := [pred t : {set 'I_B.+1} | Zeck_svalp t == m - fib B.+2 & \n   Zeck_sval t == n- fib B.+3].\npose g1 t := b |: g t. \nhave hc: forall t, p (g1 t) by move => t; apply/setU11. \nhave ig1: injective g1.\n  move => t1 t2; rewrite /g1 => w; apply: ig.\n  by rewrite - (setU1K (gpn t1)) w (setU1K (gpn t2)).\nrewrite cardsE -(card_imset pn ig1).\nhave ig3: forall t, fib B.+3 + Zeck_sval t = Zeck_sval (g1 t).\n  by move => t; rewrite ig2 / Zeck_sval /g1 big_setU1.\nhave ig3': forall t, fib B.+2 + Zeck_svalp t = Zeck_svalp (g1 t).\n  by move => t; rewrite ig2' /Zeck_svalp /g1 big_setU1.\napply: eq_card => e; rewrite inE; apply/imsetP/idP.\n    move => [x]; rewrite inE; move => /andP[/eqP sa1 /eqP sa2] sb.\n  rewrite sb hc - (subnK leqfn)- (subnK leqfm) - sa1 - sa2 addnC ig3'.\n  by rewrite addnC ig3 !eqxx.\nmove/and3P => [hc1 /eqP hd2 /eqP hd2'].\nset e1 := e :\\ b.\nhave Hd: forall i, i \\in e1 -> i <= B.\n  move => i /setD1P[ib ie]. \n  have:= (ltn_ord i); rewrite ltnS leq_eqVlt; case/orP => // eb.\n  by case/negP:ib; apply/eqP /ord_inj; rewrite (eqP eb).\nset l :=(seq_to_seto B (seto_to_seq e1)). \nsuff ww : e = g1 l. \n  exists l => //; rewrite /pn inE.\n  by move: ww; rewrite -hd2 - hd2' => ->; rewrite -ig3 - ig3' !addKn !eqxx.\nrewrite /l /g1 /seq_to_seto/seto_to_seq - map_comp /comp.\nrewrite - {1} (setD1K hc1); congr setU. \napply/setP =>i; apply/idP/imsetP. \n  move => ie;  move:(inordK (Hd _ ie)) => sa.\n  rewrite - mem_enum in ie; exists (inord i); last by rewrite sa inord_val.\n  by apply /imsetP;  exists (inord i) => //;rewrite (map_f _ ie).\nmove => [j /imsetP [k /mapP [x]]];rewrite mem_enum => H.\nby move => -> -> -> /=; rewrite inordK ? inord_val // ltnS Hd.\nQed.\n\nLemma GR_example: GR 10 = 2.\nProof.\nhave Ha n: GRr 1 n = (n <= 3).\n  by rewrite GRr_Sbn !GRr_0n; case:n => [ | [| [ | [ | n]]]].\nhave ha: GRr 3 2 = 1 by rewrite -(@GRr_big0 1 3 2) // GRr_Sbn ! GRr_0n.\nrewrite /GR; rewrite -(@GRr_big0 4 10 10) // GRr_Sbn muln1 ha GRr_Sbn muln1.\nby rewrite (@GRr_notz 2 10) // GRr_Sbn ! Ha.\nQed.\n\nLemma FAx_00: GA 0 0 = 1.\nProof. by move:(GAR_e 0); rewrite Zeckp_0 /GR GRr_0n. Qed.\n\nLemma FAx_0S n: GA 0 n.+1 = 0.\nProof.\ncase w: (GAr n.+1 0 n.+1 == 0); first by rewrite /GA (eqP w).\nby move: (GAr_notz (negbT w)) => /esym/eqP;rewrite Zeckp_eq0.\nQed.\n\nLemma FAx_small m n: n < m -> GA m n = 0.\nProof.\nmove => h.\ncase w: (GAr n m n == 0); first by rewrite /GA (eqP w).\nmove: (GAr_notz (negbT w)) => ha.\nby move: h; rewrite (Zeckp_prop2 n) - ha ltnNge leq_addr.\nQed.\n\n(*\n\nLemma FA_0S n:  FA 0 n.+1 = 0.\nLemma FA_small m n: n < m -> FA m n = 0.\nLemma FA_gen m n: FA m.+1 (m.+1+n) = FA n m.+1 + FA n m.\n\n\n\n*)\n\n\n(** -----------  *)\n\n(* FA *)\n\nFixpoint FA_rec (m n k:nat) :=\n  if k is k'.+1 then\n    if (m==0) then (n==0): nat\n    else if n < m then 0  else FA_rec (n-m) m k' + FA_rec (n - m) (m-1) k'\n  else 0.\n\nDefinition FA m n := FA_rec m n (m+n).+1.\nDefinition FR n := FA (Zeckp n) n.\n\nLemma FA_00: FA 0 0 = 1.\nProof. by []. Qed.\n\nLemma FA_0S n:  FA 0 n.+1 = 0.\nProof.  by []. Qed.\n\nLemma FA_small m n: n < m -> FA m n = 0.\nProof. by rewrite /FA;case:m  => // m /= ->. Qed.\n\nLemma FA_gen m n: FA m.+1 (m.+1+n) = FA n m.+1 + FA n m.\nProof.\nsuff H: forall u v k1 k2, u + v < k1 -> u + v < k2 -> \n     FA_rec u v k1 = FA_rec u v k2.\n  have ha: n + m.+1 < m.+1 + (m.+1 + n). \n    by rewrite addnC ltn_add2l addSn ltnS leq_addl.\n  have hb: n + m.+1 < (n + m.+1).+1 by rewrite ltnSn.\n  have hc: n + m < m.+1 + (m.+1 + n).\n    by rewrite addSn ltnS addnA addnC leq_add2r leq_addr.\n  have hd: n + m < (n + m).+1 by apply: ltnSn.\n  rewrite /FA {1} /FA_rec addKn subn1 succnK ltnNge leq_addr.\n  by rewrite - (H  n m.+1  _ _ ha hb) - (H  n m  _ _ hc hd). \nmove => u v; move: {2 3 4} (u+v) (leqnn (u+v)) => k.\nclear m n; elim: k u v.\n  move => u v; rewrite leqn0 addn_eq0 => /andP [/eqP -> /eqP ->].\n  case => // k1; case => //. \nmove => n Hrec u v luv; case => // k1; case =>  // k2; rewrite !ltnS => la lb.\nmove: luv; case: u => // u; rewrite addSn ltnS /=.\ncase(ltnP v u.+1) => // luv l2.\nhave ha: v - u.+1 + u.+1 <= n by rewrite (subnK luv) (leq_trans _ l2)?leq_addl.\nhave hb: v - u.+1 + (u.+1 - 1) <= n. \n  by  apply: leq_trans ha;  rewrite leq_add2l leq_subr.\nby rewrite /= (Hrec _ _ ha k1 k2 la lb) (Hrec _ _ hb k1 k2).\nQed.\n\nLemma FA_mm m: FA m.+1 m.+1 = FA 0 m.\nProof. by move:(FA_gen m 0); rewrite addn0 FA_0S => ->. Qed.\n\nLemma FA_mm' m: FA m m = ((m <=1):nat).\nProof. by case: m => //m; rewrite FA_mm;case m. Qed.\n\nLemma FA_nz m n:  FA m n != 0 -> m = Zeckp n.\nProof.\nmove: (leq_maxl m n)  (leq_maxr m n); set s := (maxn m n).\nmove:s => s; elim: s m n.\n   by move => m n; rewrite !leqn0 => /eqP -> /eqP ->; rewrite Zeckp_0.\nmove => b Hr m n; case: (ltngtP m n); last first.\n+ move => -> _ _; rewrite FA_mm'; case n; first by rewrite Zeckp_0.\n  by move => k; rewrite ltnS leqn0; case: k => //; rewrite Zeckp_1.\n+ by move/FA_small => ->.\n+ move => lemn _; rewrite leq_eqVlt; case/orP=> [|]; last first.\n    by rewrite ltnS => nn; apply: (Hr _ _  (leq_trans (ltnW lemn) nn) nn).\n  move: lemn; case:m; first by move => _ /eqP ->; rewrite FA_0S.\n  move => m lmn /eqP nv.\n  have lta: m.+1 <= b by rewrite - ltnS -nv.\n  have ltc: (n - m.+1) <= b by rewrite -ltnS (subnSK (ltnW lmn)) -nv leq_subr.\n  rewrite - (subnKC (ltnW lmn)) FA_gen addn_eq0 negb_and => /orP; case.\n   by  move /(Hr _ _ ltc  lta) => ->; rewrite(Zeckp_prop3a m.+1).\n  by move /(Hr _ _ ltc  (ltnW lta)) => ->; rewrite (Zeckp_prop4a m.+1).\nQed.\n\nLemma FA_prop0 a b: Zeckp b = a.+1 -> FA a b = 0.\nProof.\nmove =>eq1; case eq2:(FA a b == 0); first by rewrite (eqP eq2).\nby move: (FA_nz (negbT eq2)); rewrite eq1 => /n_Sn.\nQed.\n\nLemma FA_prop0bis a b: (Zeckp b).+1 = a -> FA a b = 0.\nProof.\nmove => eq1; case eq2:(FA a b == 0); first by rewrite (eqP eq2).\nby move: (n_Sn (Zeckp b)); rewrite eq1 (FA_nz (negbT eq2)). \nQed.\n\nLemma FR_0: FR 0 = 1.\nProof. by rewrite /FR Zeckp_0 FA_00. Qed.\n\nLemma FR_1: FR 1 = 1.\nProof. by rewrite /FR Zeckp_1 FA_mm'. Qed.\n\nLemma FR_rec n (e := Zeckp n): n != 0 -> FR n = FA(n -e) e + FA (n-e) e.-1.\nProof.\nrewrite /FR/e -Zeckp_eq0 - lt0n => /prednK => eq.\nmove: (Zeckp_le n) => [/subnKC sa sb].\nby move: (FA_gen (Zeckp n).-1 (n - Zeckp n)); rewrite eq sa.\nQed.\n\nLemma Zeckp_prop5 n (e := Zeckp): Zeck_li n.+1 = 0 ->\n  (n == 0) || \n  [&& (Zeck_li n != 0), e (e n.+1) == (e (e n)).+1 & (e (n.+1) == (e n).+1)].\nProof.\nmove: (Zeck_prop1 (n:=n.+1) isT) => [a [l [pa]]]. \nmove: (path_all_llen pa) => ha.\nhave ha': all (leq 1) l by  apply/allP => [x /(allP ha)]; case x.\nrewrite /Zeck_li /e /Zeckp /Zeck_valp  rev_cons => pb; rewrite pb. \nrewrite last_rcons /Zeck_val => sa sb. \nmove: sa; rewrite sb !sum_rcons big_cons !add1n => /eqP. \nrewrite !eqSS => /eqP sa.\nhave sr: sorted ggen (rev l) by rewrite rev_sorted; exact (path_sorted pa).\nhave eq1 : Zeck n = rev l by rewrite sa -sum_rev; apply:ZeckP.\nrewrite {1} sa eq1 eqxx sum_rev.\ncase rvz: (l == nil); first by rewrite (eqP rvz) big_nil.\nhave ->: last n (rev l) != 0.\n  by move: ha rvz; case l => // b s; rewrite rev_cons last_rcons /=; case b.\nrewrite andbT /=;apply/orP; right.\nmove: (seq_prednK ha').\nset m := (\\sum_(i <- l) fib i.+1); set w :=  (pred_seq l) => hb.\nhave sa1: sorted ggen (rev w). \n  move: sr; rewrite hb !rev_sorted sorted_llen_succ //.  \nhave nv: m = Zeck_val (rev w) by rewrite /m /Zeck_val hb big_map sum_rev.\nhave ->: Zeck m = (rev w) by rewrite nv; apply:ZeckP.\nhave ->: m.+1 = Zeck_val (rcons (rev w) 0) by rewrite /Zeck_val sum_rcons nv.\nrewrite [X in X == _] (Zeckp_prop1) ? /Zeck_valp ? sum_rcons //.\nrewrite rcons_uniq (sorted_ggen_uniq sa1) andbT; apply/negP. \nrewrite mem_rev => /mapP [x /(allP ha)]; case x => // [] [] //.  \nQed.\n\nLemma FR_prop1 n: Zeck_li n.+1 = 0 -> FR n.+1 = FR (Zeckp n).\nProof.\ncase: n; first by rewrite Zeckp_0  FR_1 FR_0.\nmove => n; rewrite FR_rec // => /Zeckp_prop5 /= /and3P [ea /eqP ec /eqP eb].\nmove:(Zeckp_prop3b ea) => ed.\nby rewrite {1 3 4} eb subSS -(Zeckp_prop3b ea) -/(FR _) (FA_prop0 ec).\nQed.\n\nLemma FR_prop0 n: Zeck_li n != 0 ->\n  FR n = FR (Zeckp n) + FA (Zeckp (Zeckp n)) (Zeckp n).-1.\nProof.\ncase h: (n==0); first by rewrite  (eqP  h) /Zeck_li Zeck_0.\nby move =>h1;rewrite (FR_rec (negbT h)) -(Zeckp_prop3b h1).\nQed.\n\nLemma FR_positive n: 0 < FR n.\nProof.\nelim: n {-2} n (leqnn n). \n   by move => n; rewrite leqn0 => /eqP ->; rewrite FR_0.\nmove => n IH n1; rewrite leq_eqVlt; case/orP=> [|Hn]; last first.\n  by apply: IH; rewrite -ltnS.\nmove => /eqP => ->; case h:(Zeck_li n.+1 == 0).\n  by move: (Zeckp_le n) => [/ IH ha hb]; rewrite (FR_prop1 (eqP h)). \nmove:(FR_prop0 (negbT h)) IH; clear h; case: n; first by rewrite FR_1.\nmove => n -> h; move /leqifP: (Zeckp_le n.+2) => /=; rewrite ltnS => /h lt.\nby apply: (leq_trans lt); rewrite leq_addr.\nQed.\n\nLemma FR_prop3 n: odd (Zeck_li n) -> FR n = FR (Zeckp n).\nProof.\nmove => h.\nhave H1: Zeck_li n != 0. \n  by move: h; rewrite/ Zeck_li;case : (last n (Zeck n)).\nby rewrite (FR_prop0 H1) (Zeckp_prop3b H1) - (Zeckp_prop4b h) FA_prop0bis ?addn0.\nQed.\n\nLemma FR_prop4 m: llen 1 (Zeck_li m) ->FR (Zeckp m).+1 = FR (Zeckp (Zeckp m)).\nProof.\nmove => Hm;move: (Hm); rewrite /llen /ggen /= => /Zeck_li_prop2 Hm1.\nrewrite /= FR_prop1 //; move: Hm Hm1; rewrite /Zeck_li; case: m => // m.\nmove: (Zeck_prop1 (n:=m.+1) isT) => [a [l [pa -> ->]]].\nrewrite {1} rev_cons last_rcons => sc sd.\nhave: all (leq 1) (rev (a:: l)) by apply /allP; move => x /(allP sd)/ltnW/ltnW.\nmove /(seq_prednK); set s' := (pred_seq (rev (a :: l))) => sv'.\nhave sv:sorted ggen (rcons s' 0).\n  have aa: (rev (succ_seq (rcons s' 0))) = [:: 1, a & l].\n    by rewrite /succ_seq map_rcons -/(succ_seq s') - sv' - rev_cons revK.\n  by rewrite -sorted_ggen_succ - rev_sorted aa /=; apply/andP.\nhave eq: (Zeck_valp (a :: l)).+1 = Zeck_val (rcons s' 0).\n  by rewrite /Zeck_valp /Zeck_val sum_rcons - sum_rev sv' big_map.\nby rewrite (Zeckp_prop1 (sorted_llen_uniq pa)) eq (ZeckP sv) last_rcons.\nQed.\n\nLemma FR_fib1 k: FR (fib k.*2.+3) = FR (fib k.*2.+2).\nProof.\nby rewrite FR_prop3 /Zeck_li ?Zeck_fib ?Zeckp_fib //= odd_double. Qed.\n\nLemma FR_fib2 k: FR (fib k.*2.+1) = FR (fib k.*2).\nProof. by case k; [rewrite FR_1 FR_0 | apply: FR_fib1 ]. Qed.\n\nLemma FR_fib3 k: FR (fib k).-1 = 1.\nProof.\nhave h0:= FR_0; have h1:= FR_1.\nsuff H: forall k, FR (fib k.*2).-1 = 1 /\\ FR (fib k.*2.+1).-1 = 1.\n  move: (H k./2) => [sa sb]; rewrite - (odd_double_half k); case (odd k) => //.\nclear k; case => //;elim =>  // n []; set k := n.+1 => sa sb.\nset l := succ_seq  [seq i.*2 | i <- iota 0 k].\nhave eq1: [seq i.*2 | i <- iota 1 k] = [seq i.+1 |i <- l].\n  by rewrite /l iota_S - !map_comp /comp.\nhave ea: Zeck (Zeck_val l) = rev l.\n  rewrite -{1} (revK l) /Zeck_val sum_rev; apply: ZeckP.\n  by rewrite rev_sorted /l sorted_llen_succ sorted_llen_mkseq_e.\nhave eb : Zeck_val l = (fib (k.+1).*2).-1.\n  by rewrite - fib_sum_odd_alt  /Zeck_valp /mkseq map_cons big_cons eq1 big_map.\nhave res1:FR (Zeck_val l) = 1.\n  have ha:odd (Zeck_li (Zeck_val l)). \n    by rewrite /Zeck_li ea /l /succ_seq -map_comp /k /= rev_cons last_rcons.\n  by rewrite (FR_prop3 ha) eb Zeckp_fibc doubleS.\nsplit; first by rewrite - eb.\nset u:= [seq i.+2 | i <- l].\nhave ec: Zeck (Zeck_val u) = rev u.\n  rewrite -{1} (revK u) /Zeck_val sum_rev /u/l - map_comp /comp - map_rev.\n  apply: ZeckP. rewrite map_rev rev_sorted - map_comp  sorted_llen_mkseq //.\n  by move => x; rewrite doubleS /=.\nhave ed: llen 1 (Zeck_li (Zeck_val u)).\n   by rewrite /Zeck_li ec /u /l - !map_comp /comp /k /= rev_cons last_rcons.\nhave ee: Zeckp (Zeck_val u) = Zeck_val (rev ([seq i.+1 | i <- l])).\n  by rewrite /Zeckp ec /Zeck_valp /Zeck_val ! sum_rev /u ! big_map.\nrewrite - fib_sum_even_alt2 /mkseq map_cons eq1 /Zeck_val big_cons add1n. \nmove: (FR_prop4 ed); rewrite ee /Zeck_val sum_rev - res1 => ->; congr FR.     \nhave uu:uniq u.\n  rewrite /u /l - !map_comp /comp map_inj_uniq ?iota_uniq//.\n  by move => x y /= /eqP; rewrite !eqSS eqn_double => /eqP.\nhave au: all (leq 1) u by apply/allP => x /mapP [y yl ->].\nmove: (Zeckp_prop1_bis au uu).\nby rewrite /u /Zeck_val /Zeck_valp /Zeck_valpp !big_map.\nQed.\n\nDefinition Zeckpn k n:= iter k Zeckp n.\n\nLemma FR_split n (p := fib (Zeck_li n).+2) (m := n - p):\n  n != 0 -> n = p + m /\\  (m = 0 \\/  llen (Zeck_li n) (Zeck_li m)).\nProof.   \nrewrite /m/p; clear p m.\ncase:n => // n _; move: (Zeck_prop1 (n:=n.+1) isT) => [a [l [pa pb pc]]].\nrewrite /Zeck_li pb rev_cons last_rcons pc Zeckv_cons addKn; split => //.\nmove: pa;case l; first by left;rewrite Zeckv_nil. \nmove => u v /= /andP [sa sb]; right.\nby rewrite /Zeck_val - sum_rev ZeckP ? rev_sorted //= rev_cons last_rcons.\nQed.\n\n\nLemma Zeckp_prop6 n m q (s := pred_seq (Zeck m)):\n  n = m + fib q.+3 -> (m = 0 \\/  llen q.+1 (Zeck_li m)) ->\n  [/\\ Zeck (Zeckp n) = rcons (Zeck (Zeckp m)) q,\n     (q >0 -> Zeck (Zeckp (Zeckp n)) = rcons (Zeck (Zeckp (Zeckp m))) q.-1),\n     sorted llen (q :: rev s),  Zeckp m = Zeck_val (rev s) &\n    Zeckp n = fib q.+2 +  Zeckp m].\nProof.\nmove => sa sb; rewrite /s.\nmove:(Zeck_zeck_val m) (Zeck_ggen m) sb; rewrite /Zeck_li.\nset l := (Zeck m) => qa qb; case => qc.\n  rewrite /l sa qc /= !Zeckp_0 Zeck_0  !Zeckp_fib !Zeck_fib Zeckv_nil addn0.\n  by split => // /prednK {1} <-; rewrite Zeck_fib.\nhave lp0: 1 < last m l by apply: (leq_trans _ qc); rewrite !ltnS leq0n.\nmove:(Zeck_li_prop2 (ltnW lp0)) => lp1.\nhave qd: sorted llen (q.+1 :: rev l).\n   move: qb qc; rewrite - rev_sorted -/llen - qa - {2 3} (revK l).\n   by case: (rev l) => // u v; rewrite rev_cons last_rcons /= => -> ->.\nmove: (seq_prednK lp1); rewrite -/s => eq1.\nhave qg: sorted llen (q :: rev s).\n  by move:qd; rewrite /l eq1 -map_rev -map_cons -/(succ_seq _) sorted_llen_succ.\nhave qg':sorted ggen s by rewrite - rev_sorted; apply: (path_sorted qg).\nhave qe: m = Zeck_val (rev l) by rewrite - qa /Zeck_val sum_rev.\nhave qe': Zeck_valp s = Zeck_valp (rev s) by rewrite /Zeck_valp sum_rev.\nhave eq2: Zeckp m = Zeck_val (rev s).\n  rewrite qe /Zeck_val !sum_rev  (Zeckp_prop0 (sorted_ggenW qb)) /l eq1.\n  by rewrite /Zeck_valp big_map.\nmove: (Zeck_split qd (leqnn (fib q.+3))).\nrewrite - qe addnC - sa Zeckp_fib => eq3.\nrewrite - eq3 - eq2 qg.\nhave sv: Zeck (Zeckp m) = s by rewrite eq2 /Zeck_val -sum_rev ZeckP revK.\nhave eq4: Zeck (Zeckp n) = rcons s q.\n  move: qg; rewrite - rev_sorted rev_cons revK => /ZeckP <- //.\n  by rewrite eq3 /Zeck_val sum_rcons eq2 /Zeck_val sum_rev.\nrewrite {3 5} /Zeckp sv eq4 qe'; split => //.\nhave lp2: all [pred z | 0 < z] s.\n   apply /allP => [z /mapP [x /(allP (Zeck_li_prop2 lp0)) /=]].\n   by case x => // m';rewrite ltnS succnK => h ->.\nmove: (seq_prednK lp2); set s' := [seq i.-1 | i <- s] => sv' qp.\nmove: qg ; rewrite - {1 2} (prednK qp) => qg.\nhave qg'': sorted llen (q.-1 :: rev s').\n  move: qg; rewrite sv' - map_rev /llen /=.\n  by elim: (rev s') (q.-1) => // u v H b /= /andP[h /H ->];rewrite -ltnS h.\nhave qg''':sorted ggen s' by rewrite - rev_sorted; apply: (path_sorted qg'').\nrewrite/Zeck_valp sv' - map_rev big_map sum_rev  (ZeckP qg''') sum_rcons.\nby rewrite big_map - (sum_rcons q.-1) ZeckP // - rev_sorted rev_rcons.\nQed.\n\n\nLemma FR_prop5 n: ~~ odd (Zeck_li n) -> (Zeck_li n) != 0 ->\n  FR n =  FR (Zeckp n) + FR((Zeckp n).-1) /\\ FR (Zeckp n) = FR (Zeckpn 2 n).\nProof.\npose qk n := fib (Zeck_li n).+2;pose pk n := (n - qk n).\nmove => ha hb.\nhave nz: n != 0 by apply /negP => /eqP nz; move: hb; rewrite nz /Zeck_li Zeck_0.\nmove: (FR_split nz); set m := _ - _; set p := fib _; move => [pb pc].\nset k := (Zeck_li n)./2.-1.\nhave pq: (Zeck_li n) = (k.+1).*2.\n  move: hb; rewrite - (odd_double_half (Zeck_li n))(negbTE ha) add0n.\n  by rewrite double_eq0 -lt0n => /prednK => <-. \nmove: pb; rewrite addnC /p pq doubleS => pb; rewrite pq in pc.\nrewrite (FR_prop0 hb); case: pc => pc.\n  by rewrite pb pc add0n {3} /FR /= !Zeckp_fib FR_fib1 -! doubleS Zeckp_fiba. \nmove: (Zeckp_prop6 pb (or_intror (m = 0) pc)) => [qa _  qc qd qe].  \nsplit.\n  rewrite /FR;congr addn; congr FA.\n  have: 0 < fib k.*2.+3 by rewrite fib_gt0.\n  have qx := leqnn (fib (k.+1).*2.+1); have qy:= leq_pred (fib (k.+1).*2.+1).\n  move/prednK => xx; rewrite qe -{2} xx addSn succnK qd.\n  by rewrite (Zeck_split qc qx) (Zeck_split qc qy) Zeckp_fiba doubleS Zeckp_fib.\nby apply: FR_prop3; rewrite /Zeck_li qa last_rcons /= odd_double.\nQed.\n\nLemma FR_fib4 k: FR (fib k.*2) = k.-1.+1.\nProof.\nelim: k => [| k H]; first  by rewrite FR_0.\nhave h: Zeck_li (fib (k.+1).*2) = k.*2 by rewrite /Zeck_li doubleS Zeck_fib /=.\nhave ei: ~~ odd (Zeck_li (fib (k.+1).*2)) by rewrite h odd_double.\ncase kz: (k == 0); [by rewrite  (eqP kz) FR_1 | move: (negbT kz) => kp].\nhave mz: Zeck_li (fib (k.+1).*2) != 0 by rewrite h double_eq0 kp.\nrewrite (proj1 (FR_prop5 ei mz)) doubleS Zeckp_fib FR_fib2 H FR_fib3 addn1.\nby rewrite  /= prednK // lt0n.\nQed.\n\nTheorem FR_fib k: FR (fib k) = (k./2).-1.+1.\nProof.\nrewrite - {1} (odd_double_half k);case: (odd k).\n  by rewrite FR_fib2 FR_fib4.\nby rewrite FR_fib4.\nQed.\n\n\nLemma FR_prop6 k m: llen (k.+1).*2 (Zeck_li m) ->\n   FR (fib (k.+1).*2.+1 + Zeckp m).-1 = FR (Zeckpn (k.+1).*2 m).\nProof.\nrewrite (fib_pos) addSn succnK.\nelim: k m => [m mv | k Hrec m mv]; first by apply:(FR_prop4 (ltnW mv)).\nhave ->: (Zeckpn (k.+2).*2 m) = ((Zeckpn (k.+1).*2 (Zeckp (Zeckp m)))).\n  by elim k => // k1 /= ->.  \nset RHS :=  RHS.\nmove:(Zeckp_prop6 (erefl ( m + fib (k.+1).*2.+4)) (or_intror (m = 0) mv)).\nmove => [_ _ pc pd _].\nrewrite - fib_sum_even_alt2 /mkseq /= /Zeck_val big_cons addSn.\nset l := pred_seq (Zeck m) ++ rev ([seq i.*2 | i <- iota 1 k.+1]).\nset x := _ + _;  have {x} -> : x = Zeck_val l. \n   by rewrite /x/l pd /Zeck_val big_cat !sum_rev /= addnC.\nset lp := succ_seq l.\nhave ha: sorted ggen (rcons l 0).\n  have pa3 n a b: (last a [seq i.*2 | i <- iota b n.+1]) = (n + b).*2.\n    by elim: n a b => // n H a b;move: (H 0 b.+1); rewrite addnS addSn.\n  have pa2: sorted llen ((k.+1).*2 :: rev [seq i.-1 | i <- Zeck m]).\n    by move:pc; case: (rev _) => // a s /=/andP[/ltnW /= -> ->].\n  rewrite /l - rev_sorted rev_rcons rev_cat revK /= cat_path.\n  move:(sorted_llen_mkseq_e 1 k.+1) => /= ->.\n  by move: pa2;case k => // k'; rewrite pa3 addn2.\nhave hb: sorted ggen l. \n   move: ha;rewrite - rev_sorted  -(rev_sorted _ l)  rev_rcons /=. \n   by move /path_sorted.\nmove:(sorted_ge2_all_ps ha) => [hc hd].\nmove: (seq_prednK hd); set l' := (pred_seq l) => sv.\nhave hd' : all (leq 1) l'.\n  move: hc; rewrite /l' => h; apply/allP => [x /mapP [y /(allP h) u ->]].\n  by move: u; case y => //.\nmove: (seq_prednK hd'); set l'' := pred_seq l' => sv'.\nhave he: sorted ggen l' by rewrite - sorted_ggen_succ - sv.\nhave he': sorted ggen l'' by rewrite - sorted_ggen_succ - sv'.\nhave ea: Zeck_val l = Zeck_valp lp by rewrite  /Zeck_val /Zeck_valp big_map.\nhave eb: Zeck (Zeck_val lp) = lp by apply: ZeckP; rewrite sorted_ggen_succ.\nhave ec: Zeck (Zeck_val l) = l by apply: ZeckP.\nhave ed: Zeckp (Zeck_val lp) =  Zeck_val l by rewrite /Zeckp eb - ea.\nhave ee: Zeck (Zeck_val l') = l' by apply: ZeckP.\nhave ef: (Zeck_valp l) = Zeck_val l'. \n   by rewrite /Zeck_val /Zeck_valp sv big_map.\nhave eg: Zeck (Zeck_valp l) = l' by rewrite ef; apply:ZeckP.\nhave hf: llen 1 (Zeck_li (Zeck_val lp)).\n  rewrite /Zeck_li eb /lp /l /succ_seq map_cat map_rev - ! map_comp /=.\n  by rewrite last_cat rev_cons last_rcons. \nhave eh: Zeck_li (Zeck_valp l) = 1.  \n  rewrite /Zeck_li eg /l' /l /pred_seq map_cat map_rev - !map_comp /comp /=.\n  by rewrite last_cat ! rev_cons last_rcons.\nmove: pc pd; set s := rev (pred_seq (Zeck m)) => pc pd.\nhave us:= (uniq_llen pc).\nhave ei: Zeckp (Zeckp m) = Zeck_valp s by rewrite pd; apply: Zeckp_prop1. \nhave sb1: all (leq (k.+1).*2.+3) s.\n  move: pc; elim:(s) => // a L H /=/andP [h1 h2]; rewrite h1 /=; apply:H.\n  by move:h2; case:L => // a' L' /= /andP [/ltnW /(ltn_trans h1) -> ->].\nhave sb2: all (leq 1) s by apply/allP => [ x /(allP sb1)]; case:x.\nhave sb3: all (leq 2) s by apply/allP => [ x /(allP sb1)]; case:x => //; case.\nmove: (seq_prednK sb2); set s' :=  (pred_seq s) => s'v.\nhave ek: Zeck (Zeck_valp s) = rev s'.\n  rewrite /Zeck_valp s'v big_map - sum_rev; apply:ZeckP.\n  rewrite rev_sorted - sorted_llen_succ - s'v; exact:(path_sorted pc). \nhave ej: Zeckp (Zeckp (Zeckp m)) = Zeck_valpp s. \n    by rewrite ei Zeckp_prop1_bis.\nhave hi:llen (k.+1).*2 (Zeck_li (Zeckp (Zeckp m))).\n  move: mv sb1;rewrite /Zeck_li ei ek /s' /s -{1} (Zeck_zeck_val m).\n  case: (Zeck m); first  by rewrite /= Zeckv_nil //.\n  move => a l1 _; rewrite /pred_seq map_rev revK - map_comp /comp all_rev => w.\n  set y := last a.-2 [seq x.-2 | x <- l1];rewrite /= -/y.\n  have: y\\in [seq x.-2 | x <- a::l1] by rewrite /y map_cons; apply:mem_last.\n  move /mapP => [x /(map_f predn) /(allP w) xh ->]. \n  by move: xh; case x => //; case => //.\nhave aa:(Zeck_valp l') = Zeck_valpp l.\n   by rewrite /Zeck_valp /Zeck_valpp sv /succ_seq big_map.\nhave: odd (Zeck_li (Zeck_valp l)) by rewrite eh.\nrewrite - ed (FR_prop4 hf) ed /Zeckp ec; move /FR_prop3 => ->.\nrewrite /Zeckp eg aa /Zeck_valpp /l big_cat /= - sum_rev -/s addnC sum_rev.\nrewrite - map_cons -/(iota 1 k.+1) /RHS - (Hrec _ hi) ej; congr (FR (_ + _)). \nby rewrite -(fib_sum_even_alt k.+2) /Zeck_valpp /mkseq /= !big_cons /= add0n.\nQed.\n\nLemma FR_prop7 n (k :=Zeck_li n) (m := n -  fib (k.+2)) :\n  ~~(odd k) -> FR n = FR (Zeckpn k.+1 m) + (k./2) * FR (Zeckpn k m).\nProof.\nrewrite /m/k; clear.\ncase: n; first by rewrite /Zeck_li Zeck_0 /= sub0n Zeckp_0 addn0.\nmove => n sa.\nset q := (Zeck_li n.+1);move: (FR_split (n:=n.+1) isT) (erefl q). \nrewrite -/q {6} /q -(odd_double_half q) (negbTE sa) add0n. \nset k := (q./2); set m := _ - _; move => [->]; case.\n  have hu: forall k, Zeckpn k 0 = 0 by elim => // v /= ->; rewrite Zeckp_0.\n  by move => ->; rewrite !hu FR_0 doubleK addn0 - doubleS FR_fib4 muln1 //.\nmove => su.\nrewrite half_double; move: k m su; clear; elim.\n  move => m;rewrite /= add1n addn0 => hc mz.\n  set s := (succ_seq (Zeck m)); set n := Zeck_val s.\n  move: (Zeck_ggen m); rewrite -sorted_ggen_succ -/s => /ZeckP ha.\n  have ->: m = Zeckp n. \n    by rewrite /Zeckp ha - (Zeck_zeck_val m) /Zeck_valp /Zeck_val /s !big_map.\n  have hb: Zeck_li n = (Zeck_li m).+1. \n    move: hc;rewrite /Zeck_li ha /s - {1} (Zeck_zeck_val m).\n    by move: mz; case: (Zeck m) => [| u v]; rewrite ? Zeckv_nil //= last_map.\n  have /FR_prop4 //: llen 1 (Zeck_li n) by rewrite hb /= ltnS hc.\nmove => k Hrec m sa sb.\nset n := (fib (k.+1).*2.+2 + m). \nhave mz: Zeck m != nil. \n  apply /eqP => s. \n  by move: (Zeck_zeck_val m) sa; rewrite /Zeck_li s Zeckv_nil => <- //.\nhave e1: n = m + fib (k.+1).*2.+2 by rewrite addnC.\nhave qa: ~~ odd (Zeck_li n) by rewrite /n sb odd_double.\nhave qb: Zeck_li n != 0 by rewrite /n sb double_eq0.\nmove: (FR_prop5 qa qb) => [qc qd]; rewrite qd in qc.\nrewrite doubleS in e1.\nmove: (Zeckp_prop6 e1 (or_intror (m = 0) sa)) => [pa pb pc pd pe].\nrewrite qc pe (FR_prop6 sa); rewrite mulSnr addnA; congr addn.\nset s2:= [seq i.-2 | i <- Zeck m].\nset s1:= [seq i.-1 | i <- Zeck m]; rewrite -/s1 in pc pd.\nhave qh : (fib k.*2.+2 + Zeckpn 2 m) = Zeckpn 2 n.\n  have qh: fib (k.+1).*2.+1 <= fib k.*2.+3 by rewrite doubleS.\n  by rewrite /Zeckpn /= pe pd (Zeck_split  pc qh) doubleS Zeckp_fib.\nhave qf:Zeck_li (fib k.*2.+2 + Zeckpn 2 m) = k.*2.\n  by rewrite qh /= /Zeck_li pb // last_rcons.\nmove:(path_all_llen pc); rewrite all_rev => qe.\nhave qi: Zeck m = [seq i.+2 | i <- s2].\n  move: qe;rewrite /s1/s2; elim (Zeck m) => // a l H /= /andP [ h /H <-].\n  by move: h; case a => //; case.\nmove:(path_sorted pc); rewrite rev_sorted => /ZeckP. \nrewrite - Zeckv_rev  -pd => pf.\nhave pg: Zeckp (Zeckp m) = Zeck_val s2.\n  by rewrite {1} /Zeckp pf /Zeck_val /Zeck_valp /s1 qi !big_map. \nhave ph: Zeck (Zeckp (Zeckp m)) = s2.\n   rewrite pg; apply: ZeckP; rewrite -sorted_ggen_succ -sorted_ggen_succ.\n   rewrite /succ_seq - map_comp /comp - qi; apply: Zeck_ggen.\nhave qg: llen k.*2 (Zeck_li (Zeckpn 2 m)). \n  move: qe mz; rewrite /s1 /Zeck_li ph qi /pred_seq -map_comp /comp /=. \n  by case s2 => // a l h _ /=; move/(allP h) :(map_f succn (mem_last a l)). \nby rewrite -qh (Hrec _ qg qf)  /Zeckpn - ! iterD // !addn2 doubleS.\nQed.\n\n\nTheorem FR_prop8 n (k :=Zeck_li n) (m := n -  fib (k.+2)) :\n  FR n = FR (Zeckpn k.+1 m) + (k./2) * FR (Zeckpn k m).\nProof.\ncase ok: (odd k); last by rewrite (FR_prop7  (negbT ok)).\nmove: (prednK (odd_gt0 ok)) => eq1.\nhave opk: ~~(odd k.-1) by move: ok;rewrite - eq1.\ncase nz: (n ==0); first by  move: eq1; rewrite /k (eqP nz) /Zeck_li. \nmove: (Zeck_prop1 (negbT nz)) => [a [l [pa pb pc]]].\nhave eq2: a = k by rewrite /k /Zeck_li pb rev_cons last_rcons.\nrewrite eq2 in pa pb pc.\nhave eq3: m = Zeck_val l by  rewrite /m pc  Zeckv_cons addKn.\nhave: all (leq 1) l by apply/allP => [x /(allP (path_all_llen pa))]; case x.\nmove/seq_prednK; set s := pred_seq l => sv.\nhave pd:= (path_sorted pa).\nhave eq4: Zeck m = rev l.\n  by rewrite eq3 - Zeckv_rev; apply: ZeckP;  rewrite rev_sorted. \nhave pe: (Zeck_val l) = 0 \\/ llen k.-1.+1 (Zeck_li (Zeck_val l)).\n  move: ok pa;rewrite /Zeck_li - eq3 eq4 {1} eq3; case l => [_ _ | x y].\n     by left; rewrite Zeckv_nil.\n  by rewrite rev_cons last_rcons /=; case k => // k' _ /andP [ h];right.\nmove: (pc); rewrite Zeckv_cons addnC - eq1 => pc'. \nmove: (Zeckp_prop6 pc' pe); rewrite - eq3; move => [pf _ pg ph pi].\nhave eq5: (Zeck_li (fib k.-1.+2 + Zeckp m)) = k.-1. \n  by rewrite /Zeck_li -pi pf last_rcons.\nhave opk1: ~~odd (Zeck_li(fib k.-1.+2 + Zeckp m)) by rewrite eq5.\nrewrite (FR_prop3 ok) pi (FR_prop7 opk1) eq5 addKn.\nby rewrite /Zeckpn !iterSr  (evenE (negbTE opk)) doubleK /= uphalf_double.\nQed.\n\nLemma FR_unique n: FR n = 1 -> exists k, n = (fib k.+2).-1.\nProof.\nhave H k: FR k = 1 -> ((Zeck_li k)./2) = 0.\n  rewrite {1} FR_prop8.\n  case: (posnP (Zeck_li k)./2) => // ha.\n  set u := Zeckpn _ _; set v := Zeckpn _ _ => eq1.\n  have hb: 0 < (Zeck_li k)./2 * FR v by rewrite muln_gt0 ha (FR_positive v).\n    by move: (leq_add  (FR_positive u) hb); rewrite eq1.\nhave H0: exists k, 0 = (fib k.+2).-1 by exists 0.\nelim: n {-2} (n) (leqnn n); first by  move => n; rewrite leqn0 => /eqP ->.\nmove => b Hr n nb fz1.\ncase (posnP n); [by move => -> | move => np].\nhave H1: forall m, Zeckp m <= m.\n   move => m; rewrite /Zeckp -{2} (Zeck_zeck_val m) /Zeck_val /Zeck_valp.\n   elim: (Zeck m); first by rewrite !big_nil.\n   move => a l HH; rewrite !big_cons leq_add // ? fib_monotone //.\nhave H2: forall n m, Zeckpn n m <= m.\n  elim => // n1 HH m; exact (leq_trans (H1 (Zeckpn n1 m)) (HH  m)).\nhave n1b: n.-1 <= b by rewrite - ltnS (prednK np).\nmove: (H _ fz1) => fz2.\nmove: fz1; rewrite FR_prop8 fz2 addn0; set k := Zeck_li n.\nhave nnz: n != 0 by rewrite -lt0n.\nmove:(Zeck_prop1 nnz) => [a[l [pa pb pc]]].\nhave ak: a = k by rewrite /k /Zeck_li pb rev_cons last_rcons.\nhave: n - fib k.+2 = Zeck_val l by rewrite pc Zeckv_cons ak addKn.\nhave ul := (uniq_llen pa).\nhave lge2: all (leq a.+2) l by apply /allP => [x /(allP(path_all_llen pa))]. \nhave: all (leq 1) l by apply /allP => [x /(allP lge2) ]; case: x.\nmove/ (seq_prednK); set s := (pred_seq l) => sv.\nhave ss: sorted llen s by rewrite - sorted_llen_succ - sv (path_sorted pa).\nhave: (k == 0) || (k == 1) by move: fz2; rewrite -/k; case k => // [] [].\ncase /orP => /eqP kz; rewrite kz.\n  have aa: (Zeckpn 1 (n - fib 2)) <= b.\n    by apply:(leq_trans (H2 1 (n - fib 2))); rewrite subn1.\n  move => eqa  /(Hr _ aa) [u]; rewrite /Zeckpn /= eqa => eqb.\n  have: rev (Zeck (Zeckp (Zeck_val l))) = s.\n    rewrite -(revK s) (Zeckp_prop1 ul) sv /Zeck_valp big_map - sum_rev ZeckP //.\n    by rewrite rev_sorted. \n  rewrite eqb -(odd_double_half u); case: (odd u). \n    rewrite add1n - doubleS Zeck_fib1 revK => h.\n    have /(allP lge2) //: 1 \\in l by rewrite sv (mem_map succn_inj) - h. \n  rewrite  Zeck_fib2 revK => sv2; exists ((u./2)).*2.+1.\n  rewrite pc ak kz sv -sv2 /succ_seq -map_comp /comp -doubleS. \n  by rewrite -fib_sum_even_alt2  /mkseq /= iota_S - !map_comp.\nhave aa:  Zeckpn 2 (n - fib 3) <= b.\n  apply:(leq_trans (H2 2 (n - fib 3))); rewrite subn2.\n  exact(leq_trans (leq_pred n.-1) n1b).\nmove => eqa  /(Hr _ aa) [u]; rewrite /Zeckpn /= eqa => eqb.\nhave: all (leq 1) s. \n  by apply/allP => [x/mapP [y /(allP lge2) y2] ->];move: y2; case y => // [] [].\nmove/ (seq_prednK); set s' := pred_seq s => sv'.\nhave eq1 :=(Zeckp_prop1 (uniq_llen pa)).\nhave eq2: (Zeck (Zeckp (Zeck_val l))) = rev s.\n    rewrite eq1 sv /Zeck_valp big_map - sum_rev  ZeckP //.\n    by rewrite rev_sorted - sorted_llen_succ - sv (path_sorted pa).\nhave : rev (Zeck (Zeckp (Zeckp (Zeck_val l)))) = s'.\n  rewrite -(revK s') {1}/Zeckp eq2 sv' /Zeck_valp sum_rev big_map.\n  by rewrite - sum_rev ZeckP // rev_sorted - sorted_llen_succ - sv'.\nrewrite eqb -(odd_double_half u); case: (odd u).\n  rewrite add1n - doubleS Zeck_fib1 revK => sv2.\n  have: 2 \\in l by rewrite sv sv' /succ_seq -map_comp;apply/map_f; rewrite -sv2.\n  by move/(allP lge2); rewrite ak kz.\nrewrite  Zeck_fib2 revK => sv2; exists ((u./2).+1).*2.\nrewrite pc - doubleS -fib_sum_odd_alt sv sv' - sv2 ak kz.\nby rewrite /Zeck_val/Zeck_valp /mkseq/= !iota_S ! big_cons ! big_map succnK.\nQed.\n\nLemma Zeck_fib3 k:\n   Zeck (fib (k.+2).*2).-2 = rev(0 :: mkseq (fun i=> i.*2.+3) k).\nProof.\nset s := [seq i.*2.+3 | i <- iota 0 k].\nrewrite - (fib_sum_odd_alt)  /Zeck_valp /mkseq /= !big_cons /=.\ntransitivity (Zeck (Zeck_val(0:: s))).\n  by rewrite /s /Zeck_val iota_S iota_S !big_map // big_cons big_map.\nrewrite - Zeckv_rev; apply: ZeckP; rewrite rev_sorted /s/=; case k => // m.\nhave //:(sorted llen [seq i.*2.+3 | i <- iota 0 m.+1]). \nby apply:sorted_llen_mkseq => u /=; rewrite doubleS !ltnS.\nQed.\n\nLemma Zeck_fib4 k:\n   Zeck (fib k.*2.+3).-2 = rev (mkseq (fun i=> i.*2.+2) k).\nProof.\nset s := [seq i.*2.+2 | i <- iota 0 k].\nrewrite - doubleS-  (fib_sum_even_alt2 k.+1) /Zeck_val /mkseq /= big_cons /=.\nrewrite iota_S - map_comp /comp /= - /(Zeck_val _) - Zeckv_rev; apply: ZeckP.\nby rewrite rev_sorted; apply:sorted_llen_mkseq => u /=; rewrite !ltnS.\nQed.\n\n\nLemma FR_fib5 k: FR (fib k.*2.+4).-2 = FR(fib k.*2.+3).-2.\nProof.\nrewrite - !doubleS; move: (Zeck_fib3 k).\nset n := (fib (k.+2).*2).-2 => zn.\nset m := Zeck_val (mkseq (fun i : nat => i.*2.+3) k).\nhave eq2: n = m.+1 by rewrite - (Zeck_zeck_val n) zn Zeckv_rev Zeckv_cons.\nhave eq1: (Zeck_li m.+1 = 0) by rewrite /Zeck_li - eq2 zn rev_cons last_rcons.\nhave ul: uniq (mkseq (fun i => i.*2.+3) k).\n  by apply: mkseq_uniq => u v /eqP; rewrite !eqSS eqn_double => /eqP.\nrewrite eq2 (FR_prop1 eq1) /m (Zeckp_prop1 ul).\nrewrite - (Zeck_zeck_val ((fib (k.+1).*2.+1).-2)) (Zeck_fib4 k) Zeckv_rev.\nby rewrite /Zeck_val/Zeck_valp /mkseq !big_map.\nQed.\n\nLemma FR_fib6 k: FR (fib (k.+2).*2.+1).-2 = (FR (fib (k.+2).*2).-2).+1.\nProof.\nmove: (Zeck_fib4 k.+1); rewrite /mkseq /= iota_S - map_comp /comp.\nset s := [seq (x.+1).*2.+2 | x <- iota 0 k] => eq1.\nset m :=  Zeck_val s.\nrewrite FR_prop8; set n := (fib (k.+2).*2.+1).-2.\nrewrite /Zeck_li eq1 rev_cons last_rcons /= mul1n.\nhave ->: (n - fib 0.*2.+4) = m.\n  by rewrite - (Zeck_zeck_val n) /n eq1 Zeckv_rev Zeckv_cons addKn.\nset s1 := [seq (x.+1).*2.+1 | x <- iota 0 k].\nset s2 := [seq (x.+1).*2 | x <- iota 0 k].\nhave eq2 : s = [seq i.+1 | i <- s1] by rewrite /s /s1 - map_comp.\nhave eq3 : s1 = [seq i.+1 | i <- s2] by rewrite /s1 /s2 - map_comp.\nhave ha: sorted llen s2 by apply:sorted_llen_mkseq => u /=; rewrite !ltnS.\nhave hb: sorted llen s1 by rewrite eq3 sorted_llen_succ.\nhave hc: sorted llen s by rewrite eq2 sorted_llen_succ.\nhave eq4: Zeck m = rev s. \n   by rewrite /m - Zeckv_rev; apply: ZeckP; rewrite rev_sorted.\nhave eq5: Zeckp m = Zeck_val s1.\n  by rewrite /Zeckp eq4 /Zeck_val /Zeck_valp sum_rev eq2 big_map.\nhave eq6: Zeck (Zeckp m) = rev s1.\n  by rewrite eq5 - Zeckv_rev; apply: ZeckP; rewrite rev_sorted.\nhave eq7: Zeckp (Zeckp m) = Zeck_val s2.\n  by rewrite /Zeckp eq6 /Zeck_val /Zeck_valp sum_rev eq3 big_map.\nhave eq8: Zeck (Zeckp (Zeckp m)) = rev s2.\n  by rewrite eq7 - Zeckv_rev; apply: ZeckP; rewrite rev_sorted.\nhave eq9: (Zeck_valp (rev s2)) = (fib (k.+1).*2).-1.\n  rewrite  Zeckvp_rev - fib_sum_odd_alt /mkseq /= /s2 Zeckvp_cons /=.\n  rewrite iota_S - map_comp //.\nhave eq10 :(Zeck_val s2) = (fib k.*2.+3).-2.\n   by rewrite - Zeckv_rev - (Zeck_fib4 k) Zeck_zeck_val.\nby rewrite {1} /Zeckp eq8 eq7 eq9 FR_fib3 eq10 -FR_fib5.\nQed.\n\nTheorem FR_fib7 k:  FR (fib k.+3).-2 = (k.+2)./2.\nProof.\nhave H: forall u, FR (fib u.*2.+3).-2 = u.+1.\n  elim; first by rewrite FR_0.\n  by move => n Hr; rewrite - doubleS FR_fib6 // ! doubleS FR_fib5 Hr.\nrewrite -(odd_double_half k); case: (odd k).\n  by rewrite  FR_fib5 H /= uphalf_double.\nby rewrite H /= doubleK.\nQed.\n\nLemma FR_fib_sum1 i k: 2 <= k -> \n  FR(fib (i+ k.+2) + fib k) = (i.+3)./2 + (k./2).-1 * (i.+4)./2.\nProof.\nmove => kp.\nhave eq1: k = k.-2.+2 by move: kp; case:k => // [] [].\nset l := [:: k+i ; k.-2].\nhave sl: sorted ggen l by rewrite /= - eq1 leq_addr.\nmove: (ZeckP sl); rewrite {1}/l /Zeck_val !big_cons big_nil - eq1 addn0.\nrewrite (addnC k) - ! addnS;  set n:= (fib (i+ k.+2) + fib k) => eq2.\nrewrite FR_prop8 /Zeck_li eq2 /l /= - eq1 /n addnK.\nhave ->: (Zeckpn k.-2 (fib (i + k.+2))) = fib (i + 4).\n  rewrite {2} eq1 -!addSnnS addn0 addnC; elim: (k.-2) (i.+3) => // h H /= j.\n  by rewrite  addSnnS H Zeckp_fib.\nby rewrite addn4 Zeckp_fib !FR_fib {2} eq1.\nQed.\n\nLemma FR_fib_sum2 i j k : 2 <= k -> k.+2 <= j -> j.+2 <= i ->\n  FR(fib i + fib j + fib k) = (i-j+1)./2 + ((j-k-1)./2) * (i-j+2)./2\n    + (k./2.-1)*( (i-j+1)./2 + (j-k)./2 * (i-j+2)./2).\nProof.\nmove => ha hb hc.\nhave eq1: k = k.-2.+2 by move: ha; case k => // [] [].\nhave eq2: j = j.-2.+2 by move: hb; case j => // [] [].\nhave eq3: i = i.-2.+2 by move: hc; case i => // [] [].\nset l := [:: i.-2; j.-2 ; k.-2].\nhave sl: sorted ggen l.\n  rewrite /= - eq1 - eq2 - (ltnS j) - (ltnS j.+1) - eq3 hc.\n  by rewrite  - (ltnS k) - (ltnS k.+1) - eq2 hb.\nmove: (ZeckP sl); rewrite {1}/l /Zeck_val !big_cons big_nil -eq1 -eq2 -eq3. \nrewrite addn0 addnA; set n := (fib i + fib j + fib k) => eq4.\nhave eq5: (n - fib k) = fib i + fib j by rewrite /n addnK.\nrewrite FR_prop8 /Zeck_li eq4 /l /= - eq1 eq5 {5} eq1.\nrewrite -(subnK hc); set i1 := i - j.+2. \nrewrite -(subnK hb); set j1 := j - k.+2.\nrewrite - addSnnS  - addSnnS - addSnnS - addSnnS !addnK !addn1 addnA.\npose A n := (fib (i1.+2 + j1.+2 + n) + fib (j1.+2 + n)).\nhave Av m: A m = (fib (i1 + (j1.+2 + m).+2) + fib (j1.+2 + m)).\n  by rewrite /A - addnA addSnnS addSnnS.\nhave zl m:  Zeck_val [:: (i1.+2 + j1 + m);  (j1 + m) ] = A m.\n     by rewrite /Zeck_val  !big_cons big_nil addn0 /A !addnS ! addSn.\nhave zl' m:  Zeck_valp [:: (i1.+2 + j1 + m.+1);  (j1 + m.+1) ] = A m.\n     by rewrite /Zeck_valp  !big_cons big_nil addn0 /A !addnS ! addSn.\nhave aux: forall n, Zeckp (A n.+1) = A n.\n   move => m. rewrite - zl Zeckp_prop1 // /= mem_seq1 andbT -addnA.\n   by rewrite - {2} (add0n (j1 + m.+1)) eqn_add2r.\nhave aux2 a b: (Zeckpn a (A (a+b))) = A b.\n   by elim: a b => // a H b /=; rewrite addSnnS H aux.\nrewrite -/(A _) {2 5} eq1 - addn2 aux2 aux Av Av addn1 FR_fib_sum1 // !addn2. \nrewrite FR_fib_sum1 // subn1 //. \nQed.\n\nLemma FR_fib_sum3 i j : 4 <= j -> j.+2 <= i ->\n  FR(fib i + fib j + 1) = (i-j+1)./2 + (j-3)./2 * (i-j+2)./2.\nProof.\nby move => ha hb; rewrite (FR_fib_sum2 (leqnn 2) ha hb) mul0n addn0 - subnDA.\nQed.\n\nLemma FR_fib_sum4 i j : 5 <= j -> j.+2 <= i ->\n  FR(fib i + fib j + 2) = (i-j+1)./2 + (j-4)./2 * (i-j+2)./2.\nProof.\nmove => ha hb; have hc:=(subnK (ltn_trans (leqnn 4) ha)).\nby rewrite (FR_fib_sum2 (leqnSn 2) ha hb) mul0n -subnDA addn0.\nQed.\n\nLemma FR_fib_sum5 i: FR(fib (i + 4) + 1) = (i.+3)./2.\nProof. by rewrite (FR_fib_sum1 i (leqnn 2)) mul0n addn0. Qed.\n\nLemma FR_fib_sum6 i: FR(fib (i + 5) + 2) = (i.+3)./2.\nProof. by rewrite (FR_fib_sum1 i (leqnSn 2)) addn0. Qed.\n\nLemma FR_fib_sum7 i: FR(fib (i + 6) + 3) = (i.+3)./2 + (i.+4)./2.\nProof. by rewrite (FR_fib_sum1 i) //= mul1n. Qed.\n\nLemma FR_fib_sum8 i: FR(fib (i + 6) + 4) = (i.+3)./2.\nProof.\nhave ha : 5 <i +6 by apply (leq_trans (leqnn 6)); apply: leq_addl.\nmove: (FR_fib_sum3 (leqnn 4) ha); rewrite - addnA  => ->.\nby rewrite addn0 (addnA i 2 4) addnK addn2 addn1 /=.\nQed.\n\nLemma fib_times2 i: (fib i.+2) * 2 = fib i.+3 + fib i.\nProof.\nby rewrite  muln2 - addnn {1} fibSS addnAC (addnC (fib i.+1)) - fibSS.\nQed.\n\nLemma fib_times3 i: (fib i.+2) * 3 = fib i.+4 + fib i.\nProof.\nrewrite (fibSS i.+2) addnAC (fibSS i.+1). \nby rewrite addnC -addnA -fibSS addnn -muln2 -mulnS.\nQed.\n\nLemma fib_times4 i: (fib i.+2) * 4 = fib i.+4 + fib i.+2 + fib i.\nProof.\nrewrite (fibSS i.+2) - addnA - addnA (addnA (fib i.+2)) addnn.\nby rewrite (fibSS i.+1) addnACA - fibSS - muln2 - mulnS - mulnSr.\nQed.\n\nLemma FR_fib_sum9 i: FR ((fib i.+4) * 2) = ((i./2)*2).+2.\nProof. by rewrite fib_times2 (_: i.+1.+4 = 1 + i.+4) // FR_fib_sum1. Qed.\n\nLemma FR_fib_sum10 i: FR ((fib i.+4) * 3) = ((i./2)*3).+2.\nProof. by rewrite fib_times3 (_: i.+2.+4 = 2 + i.+4) // FR_fib_sum1. Qed.\n\nLemma FR_fib_sum11 i: FR ((fib i.+4) * 4) = ((i./2)*3).+1.\nProof.\nby rewrite fib_times4 (FR_fib_sum2) // - add2n - (add2n i.+2) !addnK.\nQed.\n\nLemma FR_lucas1 n: FR (lucas n.+3) = n./2.*2.+1.\nProof.\nhave h: 1 < n +2 by rewrite addn2 !ltnS.\nby move: (FR_fib_sum1 0 h); rewrite addn2 lucas_fib // muln2 //.  \nQed.\n\nLemma FR_lucas2 n: FR (lucas n.*2.+3) = n.*2.+1.\nProof. by rewrite FR_lucas1 doubleK. Qed.\n\nLemma FR_lucas3 n: FR (lucas n.*2.+4) = n.*2.+1.\nProof. by rewrite FR_lucas1 /= uphalf_double. Qed.\n\n\nLemma FR_lucas4 k j: j.*2.+2 <= k -> 1 <= j ->\n FR (lucas (j.*2) * (fib k)) = j.*2 + (j.*2.+1)*(k./2-j-1).\nProof.\nmove => h h1.\nrewrite (fib_lucas1 (ltnW(ltnW h))) odd_double.\nhave lt1: 1 < k - j.*2 by rewrite -(subnK h) -(add2n j.*2) addnA addnK addn2.\nhave lt2: j.*2 <= k by apply: leq_trans h; rewrite - addn2 leq_addr.\nhave eb: (j * 4).-2.+2 = j.*2.*2.\n    by rewrite - (prednK h1) mulSnr addn4 /= -addn4 -mulSnr -!muln2 -mulnA.\nhave ea:(k + j.*2) = (j*4).-2 + (k - j.*2).+2. \n  rewrite - addSnnS - addSnnS eb - (addnn j.*2) - addnA subnKC // addnC//.\nrewrite ea (FR_fib_sum1 _ lt1) eb /= doubleK uphalf_double mulnC. \nby rewrite -{2}(subnK lt2) halfD odd_double doubleK andbF add0n addnK subn1.\nQed.\n\n\n", "meta": {"author": "coq-community", "repo": "gaia", "sha": "fe0c2f359f28671bc5e47cb385e672c697d6e435", "save_path": "github-repos/coq/coq-community-gaia", "path": "github-repos/coq/coq-community-gaia/gaia-fe0c2f359f28671bc5e47cb385e672c697d6e435/theories/stern/fibm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7047850400905652}}
{"text": "\n\n\n(*-------------Description ------------------------------------------------------  \n\nThis file implements maps on lists. Here we define functions to calculate range \nof a function on list l. We also define one-one function predicate and its boolean\ncounterpart. \n\nFollowing are the notions defined in this file:\n\n s_map f l                  : range set of f on list l\n one_one_on l f             : f is one one on l\n one_one_onb l f            : boolean counterpart of (one_one_on l f)\n\nLemma one_one_onP (l:list A) (f: A->B)(Hl: NoDup l):\n    reflect (one_one_on l f)(one_one_onb l f).\n\nFurthermore, we have results relating the cardinality of domain and range \nfor various kinds of functions (many one/one one).\n\n---------------------------------------------------------------------------------*)\n\n\nRequire Export SetReflect.\nRequire Export OrdList.\nRequire Export OrdSet.\n\n\nSet Implicit Arguments.\n\nSection Set_maps.\n  Context { A B: ordType }.    \n\n  Lemma EM_A: forall x y: A, x=y \\/  x<>y.\n  Proof.  eauto.  Qed.\n  Lemma EM_B: forall x y:B, x=y \\/ x<>y.\n  Proof. eauto.  Qed.\n\n  \n  Fixpoint img (f:A->B) (l:list A): list B:= match l with\n                                        | nil => nil\n                                        | a1::l1 => add (f a1) (img f l1)\n                                              end.\n\n  Lemma IsOrd_img (f:A->B) (l:list A):  IsOrd (img f l).\n  Proof. { induction l. simpl. constructor. simpl. eauto. } Qed.\n  \n  Lemma NoDup_img (f:A->B) (l:list A):  NoDup (img f l).\n    Proof. cut (IsOrd (img f l)). eauto. apply IsOrd_img. Qed.\n  \n  Lemma img_intro1(f: A->B)(l: list A)(a:A)(y: B): In y (img f l)-> In y (img f (a::l)).\n    Proof. simpl. eapply set_add_intro1. Qed.\n  Lemma img_intro2 (f: A->B)(l: list A)(x:A): In x l -> In (f x) (img f l).\n  Proof.  { induction l. simpl.  tauto.\n          cut (x=a \\/ x <> a). \n          intro H;destruct H as [Hl | Hr].\n          { intro H. rewrite Hl. simpl. eapply set_add_intro2. auto. }\n          { intro H. cut (In x l). intro H1. eapply img_intro1;eauto.\n            eapply in_inv2;eauto.  } eauto. } Qed.\n\n  Lemma img_elim (f:A->B) (l: list A)(a0:A)(fa:B): In (fa) (img f (a0::l))->\n                                                    fa = f(a0) \\/ In fa (img f l).\n    Proof. simpl. eapply set_add_elim. Qed.\n\n  Lemma img_elim2 (f:A->B) (l: list A)(a0:A)(fa:B): In (fa) (img f (a0::l))->\n                                                   fa <> f(a0) -> In fa (img f l).\n  Proof. simpl. eapply set_add_elim2.  Qed.\n  \n  Lemma img_elim3 (f:A->B)(l:list A)(a:A): ~ In a l -> In (f a) (img f l) ->\n                                           (exists y, In y l /\\ f a = f y).\n  Proof. { intros H H1. induction l. inversion H1.\n         assert (H2: ~ In a l). intro H2; apply H. simpl;tauto. \n         cut ( f a = f a0 \\/ f a <> f a0 ). intro H3; destruct H3 as [H3a | H3b]. exists a0.\n         split; auto. assert (H4: In (f a) (img f l)). eapply img_elim2.\n         eapply H1. exact H3b. assert (H5: exists y : A, In y l /\\ f a = f y). eauto.\n         destruct H5 as [y0 H5]. exists y0. split;  simpl. tauto. tauto.\n         eapply EM_B. } Qed.\n  Lemma img_elim4 (f: A->B)(l: list A)(b:B): In b (img f l)-> (exists a, In a l /\\ b = f a).\n  Proof. { induction l.\n         { simpl. tauto. }\n         { intro H. apply img_elim in H as H1. destruct H1.\n           { exists a. split;auto. }\n           { apply IHl in H0 as H1.\n             destruct H1 as [a' H1]; destruct H1 as [H1 H2].\n             exists a'. split;auto. } } } Qed.\n        \n  Hint Resolve IsOrd_img NoDup_img : core.\n  Hint Resolve img_intro1 img_intro2 img_elim: core.\n  Hint Resolve img_elim2 img_elim3 img_elim4: core.\n  \n  Lemma funP (f: A->B)(x y: A): f x <> f y -> x <> y.\n  Proof. intros H H1. apply H;rewrite H1; auto. Qed.\n  \n  Definition one_one (f: A->B): Prop:= forall x y, x <> y -> f x <> f y.\n  \n  Lemma one_oneP1 (f:A->B): one_one f -> forall x y, f x = f y -> x =y.\n  Proof. { unfold one_one;intros H x y H1. elim (EM_A x y). tauto.\n           intro H2; absurd (f x = f y); auto. } Qed.\n  \n  Hint Immediate one_oneP1: core.\n  \n  Definition one_one_on (l: list A) (f: A-> B):Prop:= forall x y, In x l-> In y l ->  x<>y -> f x <> f y.\n  \n  Lemma one_one_on_elim (l:list A)(f: A-> B): one_one_on l f ->\n                                         (forall x y, In x l-> In y l-> f x = f y -> x = y). \n  Proof. { unfold one_one_on. intros H x y H1 H2. elim (EM_A x y). tauto.\n           intros H3 H4. absurd (f x = f y); auto. } Qed.\n  Lemma one_one_on_intro(l:list A)(f: A-> B): (forall x y, In x l-> In y l-> f x = f y -> x = y) ->\n                                         (one_one_on l f).\n  Proof. { intros H.  unfold one_one_on.\n         intros x y H1 H2 H3 H4. apply H3. auto. } Qed.  \n\n  Lemma one_one_on_nil (f:A->B): one_one_on nil f.\n  Proof. unfold one_one_on. intros x y H H0 H1 H2. inversion H. Qed.\n\n  Lemma one_one_on_intro1(l:list A) (f: A->B)(a:A):\n             (~ In (f a) (img f l)) -> (one_one_on l f) -> one_one_on (a::l) f.\n  Proof. { unfold one_one_on. intros H H1. \n         intros x y H2 H3. destruct H2; destruct H3.\n         rewrite <- H0; rewrite <- H2.  tauto.\n         rewrite <- H0. intros H3 H4. assert (H5: In (f a) (img f l)). rewrite H4.\n         apply img_intro2;auto. absurd (In (f a) (img f l)); assumption.\n         rewrite <- H2. intros H3 H4. absurd (In (f a) (img f l)). assumption.\n         rewrite <- H4. apply img_intro2;auto. apply H1; auto. } Qed.\n \n  Lemma one_one_on_elim1 (l:list A) (f: A->B)(a: A): one_one_on (a::l) f -> one_one_on l f.\n  Proof. { unfold one_one_on.  intro H. intros x y H1 H2. eapply H; auto. } Qed.\n  \n  Lemma one_one_on_elim2 (l:list A) (f: A->B)(a: A)(Hl: NoDup (a::l)):\n    one_one_on (a::l) f -> ~ In (f a)(img f l).\n  Proof. { unfold one_one_on.  intros H H1.\n         assert (H2: (exists y, In y l /\\ f a = f y)).\n         { eapply img_elim3. intro H2; inversion Hl;contradiction. auto. }\n         destruct H2 as [b H2]; destruct H2 as [H2 H3].\n         eapply H with (x:=a)(y:=b); auto. intro H4. rewrite <- H4 in H2.\n         inversion Hl;contradiction. } Qed.\n \n  \n  Hint Immediate one_one_on_nil one_one_on_elim one_one_on_elim1 one_one_on_elim2 : core.\n  Hint Immediate one_one_on_intro one_one_on_intro1: core.\n   \n\n  Fixpoint one_one_onb (l: list A) (f: A->B): bool:=\n    match l with\n    |nil => true\n    | a1::l1 => (negb ( memb (f a1) (img f l1))) && (one_one_onb l1 f)\n    end.\n\n\n   Lemma one_one_onP (l:list A) (f: A->B)(Hl: NoDup l):\n    reflect (one_one_on l f)(one_one_onb l f).\n  Proof. { apply reflect_intro. split.\n         { induction l.\n           { unfold one_one_onb. reflexivity. }\n           { intro H. simpl one_one_onb. apply /andP. split. cut (~ In (f a)(img f l)).\n             intro H1. assert (H2:  memb (f a) (img f l) = false ). apply /membP.\n             auto. rewrite H2. simpl. reflexivity. eapply one_one_on_elim2.\n             apply Hl. auto. apply IHl.\n             eauto. eauto. } }   \n         { induction l.\n           { auto.  }\n           { simpl. move /andP. intro H; destruct H as [H H1].\n             apply one_one_on_intro1.  \n             intro H2. unfold negb in H.\n             replace (memb (f a) (img f l)) with true in H. inversion H.\n             symmetry; apply /membP; eauto. apply IHl. eauto. apply H1. } }  } Qed.\n\n \n\n  (*--------- Some more properties of imgs-----------------------------------*)\n\n  Lemma one_one_img_elim (l: list A)(f: A->B)(x: A):\n    one_one f -> In (f x) (img f l) -> In x l.\n  Proof. { intros H H1. assert (H2: exists a, In a l /\\ f x = f a). auto.\n         destruct H2 as [a H2]. destruct H2 as [H2 H3].\n         cut (x = a). intros; subst x; auto. eauto. } Qed.\n  \n  Lemma img_subset (l s: list A)(f: A->B): l [<=] s -> (img f l) [<=] (img f s).\n  Proof. { intros H fx H1. assert (H2: exists x, In x l /\\ fx = f x). auto.\n         destruct H2 as [x H2]. destruct H2 as [H2 H3]. subst fx; auto. } Qed.\n\n  Lemma img_size_less (l: list A)(f: A->B): |img f l| <= |l|.\n  Proof.  { induction l.\n          { simpl;auto. }\n          { simpl. assert (H: (| add (f a) (img f l) |) <= S (| img f l |)).\n            auto. omega. } } Qed.\n          \n  Lemma img_size_same (l: list A)(f: A->B): NoDup l -> one_one_on l f-> |l|=| img f l|.\n  Proof.  { induction l.\n          { simpl. auto. }\n          { intros H H1.\n            assert (Hl: NoDup l). eauto.\n            assert (H1a: one_one_on l f). eauto.\n            assert (H2: (| l |) = (| img f l |)). auto.\n            simpl. assert (H3: ~ In (f a) (img f l)). auto.\n            rewrite H2; symmetry;auto. }  } Qed.\n  \n\n  Hint Resolve img_subset img_size_less img_size_same: core.\n\n  \n  Lemma img_strict_less (l: list A)(f: A->B):\n    NoDup l -> (|img f l| < |l|) -> ~ one_one_on l f.\n  Proof. intros H H1 H2. assert(H3: |l|=| img f l|). auto. omega. Qed. \n\n  Hint Immediate one_one_img_elim  img_strict_less : core.\n\n  \n  Lemma one_one_on_intro2 (l: list A)(f: A->B):\n    NoDup l -> (|img f l| = |l|)->  one_one_on l f.\n  Proof.  { induction l.\n          { simpl; auto. }\n          { intros H H0.\n            assert (Ha: NoDup l). eauto.\n            assert (Hb: ~ In a l ). auto.\n            assert (H1: |img f l| = |l|).\n            { match_up  (| img f l |)  (| l |).\n              { auto. }\n              { assert ((| img f (a :: l) |) <b (| a :: l |)).\n                { move /ltP in H1. apply /ltP. simpl.\n                  cut ((| add (f a) (img f l) |) <= S (|img f l|)). omega.\n                  auto. } by_conflict. }\n              { assert (H2: |img f l| <= |l|). auto.\n                move /lebP in H2. auto. } } \n            assert (H2: one_one_on l f). auto.\n            assert (H3: ~ In (f a) (img f l)).\n            { intro H3.\n              assert (H4: img f (a :: l) = (img f l)).\n              { simpl. eapply add_same. auto. auto. }\n              rewrite H4 in H0. rewrite H1 in H0. simpl in H0. omega. } auto. } } Qed.\n            \n\n  Lemma one_one_on_intro3 (l s: list A)(f: A-> B): s [<=] l -> one_one_on l f -> one_one_on s f.\n  Proof. intros H0 H1; unfold one_one_on; auto. Qed.\n\n  Hint Immediate one_one_on_intro2 one_one_on_intro3 : core.\n\n  (* ------------ set maps and set add interaction ------------------------ *)\n\n  Lemma img_add (a: A)(l: list A)(f: A-> B): img f (add a l) = add (f a) (img f l).\n  Proof. { apply set_equal;auto.\n         induction l.\n         { simpl. auto. }\n         {  simpl.\n           assert (H:  img f (add a l) = add (f a) (img f l)).\n           apply set_equal; auto.\n           destruct IHl as [IHl IHl1].  match_up a  a0.\n           { subst a. simpl. auto. }\n           { simpl. auto. }\n           { simpl. rewrite H. auto. } }  } Qed.\n            \n  Lemma img_same (l: list A) (f g: A->B): (forall x, In x l -> f x = g x)-> (img f l = img g l).\n  Proof. {  induction l.\n         { simpl; auto. }\n         { intro h1. simpl. replace (g a) with (f a). replace (img g l) with (img f l).\n           auto. apply IHl. intros x h2. apply h1; auto. apply h1; auto. } } Qed. \n  \n  Hint Resolve img_add img_same: core.\n\n  Lemma img_inter1 (l s: list A)(f: A-> B): img f (l [i] s) [<=] (img f l) [i] (img f s).\n  Proof. Admitted.\n  Lemma img_inter2 (l s: list A)(f: A-> B): one_one_on l f -> one_one_on s f->\n                                             img f (l [i] s) = (img f l) [i] (img f s).\n  Proof. Admitted.\n\n  Lemma img_union (l s: list A)(f: A-> B): img f (l [u] s) = (img f l) [u] (img f s).\n  Proof. Admitted.\n\n  Lemma img_diff (l s: list A)(f: A-> B): one_one_on l f -> one_one_on s f->\n                                           img f (l [\\] s) = (img f l) [\\] (img f s).\n  Proof. Admitted.\n  \n  Hint Resolve img_inter1 img_inter2 img_union img_diff: core.\n  \n    \nEnd Set_maps.\n\nHint Resolve IsOrd_img NoDup_img : core.\nHint Resolve img_intro1 img_intro2 img_elim: core.\nHint Resolve img_elim2 img_elim3 img_elim4 : core.\nHint Immediate one_oneP1: core.\nHint Immediate one_one_on_nil one_one_on_elim one_one_on_elim1 one_one_on_elim2 : core.\nHint Immediate one_one_on_intro one_one_on_intro1: core.\nHint Resolve one_one_onP: core.\n\nHint Resolve img_subset img_size_less img_size_same: core.\nHint Immediate one_one_img_elim img_strict_less : core.\n\nHint Immediate one_one_on_intro2 one_one_on_intro3 : core.\n\nHint Resolve img_add img_same: core.\n\nHint Resolve img_inter1 img_inter2 img_union img_diff: core.\n\n\nSection Map_composition.\n\n  Context {A B C: ordType}.\n\n \n\n  (*-------------------------  A  --f-->  B  --g-->  C    --------------------------------*)\n\n  Lemma range_of_range (l:list A)(f: A->B)(g: B->C):\n    img g (img f l) = img ( fun x => g (f x)) l.\n  Proof. { assert (H: Equal  (img g (img f l)) (img ( fun x => g (f x)) l) ).\n         { unfold Equal.\n           split.\n           { unfold Subset. intros c Hc.\n             assert (Hb: exists b, In b (img f l) /\\ c = g b). auto.\n             destruct Hb as [b Hb]. destruct Hb as [Hb Hb1].\n             assert (Ha: exists a, In a l /\\ b = f a). auto.\n             destruct Ha as [a Ha]. destruct Ha as [Ha Ha1].\n             rewrite Hb1. set (gf := (fun x : A => g (f x))).\n             rewrite Ha1. \n             assert (H: (g (f a)) = (gf a)). unfold gf. auto.\n             rewrite H. eapply img_intro2. auto. }\n           { unfold Subset. intros c Hc.\n             assert (Ha: exists a, In a l /\\ c = g (f a)). auto.\n             destruct Ha as [a Ha]. destruct Ha as [Ha1 Ha2].\n             subst c. auto. } }  auto. } Qed.\n\n  Hint Resolve range_of_range: core.\nEnd Map_composition.\n\nHint Resolve range_of_range: core.\n\n\nSection Maps_on_A.\n  Context {A: ordType}.\n\n    (*----------Identity map and its properties ---------------------------------*)\n\n  Definition id:= fun (x:A)=> x.\n\n  Lemma id_is_identity1 (l:list A) : l [=] img id l.\n  Proof.  { induction l.\n          { simpl. auto. }\n          { simpl.  split.\n           { intros x h. destruct h as [h | h].\n             subst a. unfold id. auto.\n             cut (In x (img id l)). auto.  apply IHl. auto. }\n           { unfold id. fold id. intros x h.\n             cut (x=a \\/ In x (img id l)).\n             intro h1. destruct h1 as [h1a | h1b].\n             subst x. all: auto. cut (In x l). auto. apply IHl. auto. } } }  Qed. \n  \n\n  Lemma id_is_identity (l:list A)(hl: IsOrd l): l = img id l.\n  Proof. { induction l.\n         { simpl. auto. }\n         { apply set_equal. auto. auto. \n           simpl. replace (img id l) with l.\n           split.\n           { intros x h. destruct h as [h | h].\n             subst a. unfold id. auto. unfold id. auto. }\n           { unfold id. intros x h. cut (x=a \\/ In x l).\n             intro h1. destruct h1 as [h1a | h1b].\n             subst x. all: auto. } eauto. } }  Qed.\n\n  Hint Immediate id_is_identity id_is_identity1: core.\n\n  End Maps_on_A.\n\n  Hint Immediate id_is_identity id_is_identity1: core.\n\n\n\n ", "meta": {"author": "Abhishek-TIFR", "repo": "List-Set", "sha": "f22e828ca348c8317a5235491e7e1dac848a691f", "save_path": "github-repos/coq/Abhishek-TIFR-List-Set", "path": "github-repos/coq/Abhishek-TIFR-List-Set/List-Set-f22e828ca348c8317a5235491e7e1dac848a691f/SetMaps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7047850249887408}}
{"text": "\nRequire Export Chap4.\n\n\nDefinition symmetric {X} (R : relation X) :=\n  forall x y, R x y -> R y x.\n\n\nTheorem asym_imp_alio :\n  forall {X} (R : relation X), asymmetrical R -> aliorelative R.\nProof.\n  unfold asymmetrical. unfold aliorelative.\n  intros. intro.\n  remember H0. clear Heqr.\n  generalize r.\n  apply H. assumption.\nQed.\n\n\n\n\n\nDefinition many_many {X} (R : relation X) : Prop := True. (* tautology *)\n\n(* page 47:\nOne-many relations may be defined as relations such that, if x has the\nrelation in question to y, there is no other term x' which also has the\nrelation to y.\n*)\nDefinition one_many {X} (R : relation X) : Prop :=\n  forall x y, R x y -> forall x', R x' y -> x = x'.\n\n(*\nOr, again, they may be defined as follows: Given two terms x and x',\nthe terms to which x has the given relation and those to which x' has\nit have no member in common.\n*)\nDefinition one_many' {X} (R : relation X) : Prop :=\n  forall x x' y, R x y /\\ R x' y -> x = x'.\n\n(* Or, again, they may be defined as relations such that the relative *)\n(*product of one of them and its converse implies identity, where the *)\n(*“relative product” of two relations R and S is that relation which *)\n(*holds between x and z when there is an intermediate term y, such *)\n(*that x has the relation R to y and y has the relation S to z. *)\n\nInductive relative_product\n          {X} (R: relation X) (S: relation X) : relation X :=\n  | rp0 : forall x y, forall z, R x y -> S y z -> relative_product R S x z.\n\nInductive converse {X} (R : relation X) : relation X :=\n  | cv0 : forall x y, R x y -> converse R y x.\nInductive id {X} : relation X :=\n  | id0 : forall x, id x x.\n\nDefinition one_many'' {X} (R : relation X) : Prop :=\n  forall x y, relative_product R (converse R) x y -> id x y.\n\n(* I'll try to prove the equivalence between these three definitions *)\n\nTheorem one_many_eqv1 :\n  forall {X} (R : relation X), one_many R -> one_many' R.\nProof.\n  unfold one_many. unfold one_many'.\n  intros. inversion H0.\n  apply H with y; assumption.\nQed.\n\nTheorem one_many_eqv2 :\n  forall {X} (R : relation X), one_many' R -> one_many R.\nProof.\n  unfold one_many. unfold one_many'.\n  intros.\n\n  apply H with y. split; assumption.\nQed.\n\nLemma id_eqv : forall {X} (x:X) (y:X), x = y <-> id x y.\nProof.\n  intros. split.\n  intro. rewrite H. apply id0.\n  intro. inversion H. reflexivity.\nQed.\n\n(* I asked a question about this on stackoverflow:\n   http://stackoverflow.com/q/25477855/1232832\n*)\n\nDefinition my_one_many'' {X} (R : relation X) :=\n  forall x y, R x y -> forall x', converse R y x' -> x = x'.\n\n\nLemma expand_one_many'' :\n  forall {X} (R : relation X),\n    one_many'' R <-> my_one_many'' R.\nProof.\n  intros. unfold one_many''. unfold my_one_many''. split.\n\n  intros.\n  assert (relative_product R (converse R) x x' -> id x x'). apply H.\n\n  apply id_eqv. apply H2.\n  apply rp0 with y. assumption. assumption.\n\n  intros.\n  inversion H0. subst.\n  apply id_eqv. apply H with y0.\n  assumption. assumption.\nQed.\n\n\nTheorem one_many_eqv3 :\n  forall {X} (R : relation X), one_many R -> my_one_many'' R.\nProof.\n  unfold my_one_many''. unfold one_many.\n  intros.\n  inversion H1. subst. clear H1.\n  apply H with y; assumption.\nQed.\n\n\nTheorem one_many_eqv4 :\n  forall {X} (R : relation X), my_one_many'' R -> one_many R.\nProof.\n  unfold one_many; unfold my_one_many''.\n  intros.\n  apply H with y. assumption.\n  apply cv0. assumption.\nQed.\n\nDefinition many_one {X} (R : relation X) : Prop :=\n  forall x y, R x y -> forall y', R x y' -> y = y'.\nDefinition one_one {X} (R : relation X) : Prop :=\n  many_one R /\\ one_many R.\n\n\nInductive domain {X} (R : relation X) : X -> Prop :=\n  | domain_intro : forall x y, R x y -> domain R x.\nInductive converse_domain {X} (R : relation X) : X -> Prop :=\n  | converse_domain_intro : forall x y, R x y -> converse_domain R y.\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/imp/Chap5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7047824979571926}}
{"text": "\nFrom mathcomp Require Export all_ssreflect.\nRequire Export Classical.\n\nNotation \"∅\" := set0.\nNotation \"x ∈ X\" := (x \\in X)(at level 50). \nNotation \"A ∩ B\" := (setI A B)(at level 40).\nNotation \"A ∪ B\" := (setU A B)(at level 40).\nNotation \"A ⊂ B\" := (A \\subset B)(at level 30).\nNotation \"A // B\" := (setD A B)(at level 40).\nNotation \"¬ A\" := (setC A)(at level 40).\nNotation \"pow[ A ]\" := (powerset A).\nNotation \"⊓ X\" := (\\bigcap_(x in X) x) (at level 30).\nNotation \"⊔ X\" := (\\bigcup_(x in X) x) (at level 30).\n\nLemma bigUP {T : finType} (x : T) (X : {set {set T}}) :\n    reflect (exists Y : {set T}, x ∈ Y /\\ Y ∈ X)(x ∈ ⊔ X).\nProof.\n    apply (iffP idP).\n    +   move /bigcupP => [i iX xi]; exists i => //.\n    +   move => [Y [xY YX]].\n        apply /bigcupP; exists Y => //.\nQed. \n\nLemma bigIP {T : finType} (x : T) (X : {set {set T}}) :\n    reflect (forall Y : {set T}, Y ∈ X -> x ∈ Y) (x ∈ ⊓ X).\nProof.\n    apply (iffP idP).\n    +   move /bigcapP => H Y YX; apply H => //.\n    +   move => H; apply /bigcapP => Y YX; apply H => //.\nQed.\n\n\n\n\nLemma extension {T : finType} (A B : {set T}) :\n    A ⊂ B -> B ⊂ A -> A = B.\nProof.\n    move => AB BA; apply /setP /subset_eqP /andP => //.    \nQed.\n\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "SetTheory", "sha": "2dba76ac2e4fb14380b5efc8c25001858ef6fb73", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-SetTheory", "path": "github-repos/coq/gaxiiiiiiiiiiii-SetTheory/SetTheory-2dba76ac2e4fb14380b5efc8c25001858ef6fb73/Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7047663667509216}}
{"text": "Require Export P04.\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 f x b.\n  rewrite -> x.\n  rewrite -> x.\n  destruct b.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\nQed.\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/01/P05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7047663605498115}}
{"text": "Require Export Bool.\nRequire Export ZArith.\n\nOpen Scope Z_scope.\n\nInductive Z_inf_branch_tree : Set :=\n  Z_inf_leaf : Z_inf_branch_tree\n| Z_inf_node : Z->(nat->Z_inf_branch_tree)->Z_inf_branch_tree.\n\nFixpoint any_true (n:nat)(f:nat->bool){struct n}:bool :=\n match n with\n   0%nat => f 0%nat\n | S p => orb (f (S p)) (any_true p f)\n end.\n\nFixpoint izero_present (n:nat)(t:Z_inf_branch_tree) {struct t} :bool :=\n match t with\n | Z_inf_leaf => false\n | Z_inf_node v f =>\n   match v with\n   |  0 => true\n   | _ => any_true n (fun p => izero_present n (f p))\n   end\n end.\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/ch6_inductive_data/SRC/izero_present.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7047254185401833}}
{"text": "Require Import Arith.\nRequire Import ZFnats ZFwf ZFwfr.\nRequire Export ZF.\n\n(** This file defines and develop the basic theory of ordinals in\n    intuitionistic set theory. We use directed plump ordinals.\n *)\n\n(** * Definition and elementary properties *)\n\n(** Directed set (finite union) *)\nDefinition isDir o := forall x y,\n  x < o -> y < o -> exists2 z, z < o & x ⊆ z /\\ y ⊆ z.\n\nGlobal Instance isDir_morph : Proper (eq_set==>iff) isDir.\ndo 2 red; intros; unfold isDir.\napply fa_morph; intros x0.\napply fa_morph; intros y0.\nrewrite H.\napply fa_morph; intros _.\napply fa_morph; intros _.\napply ex2_morph; red; intros; auto with *.\nrewrite H; reflexivity.\nQed.\n\n(** Directed plump ordinals.\n\n   Plumpness is the property that\n   forall ordinal x s.t. z ⊆ y ∈ x, we have z ∈ x\n\n   Since the plumpness property is not monotonic (if we have more\n   ordinals, the plumpness requirement becomes tighter), we could\n   not separate the directedness property from the plumpness one.\n\n   Even if plumpness is not monotonic, it can be defined by recursion\n   over the rank (since the rank of z is smaller than that of x). So\n   we go by first defining well-founded sets (cf ZFwf.v), then\n   well-founded, and finally define plumpness.\n *)\n\n(** Any property could replace directedness *)\nLocal Notation Q:=isDir.\nLocal Notation Qm:=isDir_morph.\n\n(** Not resorting to higher-order: *)\n\nSection FirstOrder.\n\n(** The set of plump ordinals included in ub, given [f] the sets of plump ordinals\n    of smaller rank. *)\nLet plump_set f ub :=\n   subset (power ub)\n    (fun x =>\n      isWf x /\\             \n      (forall y, y ∈ ub -> y ∈ x -> y ∈ f y) /\\\n      (forall z y, y ∈ ub -> z ∈ f y -> z ⊆ y -> y ∈ x -> z ∈ x) /\\\n      Q x).\n\nLet R x y := isWf x /\\ x ∈ y.\n\nLocal Instance Rmorph : Proper (eq_set==>eq_set==>iff) R.\nunfold R; do 3 red; intros.\nrewrite H,H0; reflexivity.\nQed.\n\nDefinition plumps := WFR R plump_set.\n\nLet plumps_m :\n  Proper ((eq_set ==> eq_set) ==> eq_set ==> eq_set) plump_set.\ndo 3 red; intros; unfold plump_set.\napply subset_morph.\n apply power_morph; trivial.\n\n red; intros.\n apply and_iff_morphism; auto with *.\n apply and_iff_morphism.\n  apply fa_morph; intros yy.\n  rewrite <- H0.\n  rewrite (H _ _ (reflexivity _)); reflexivity.\n\n  apply and_iff_morphism; auto with *.\n  apply fa_morph; intros zz.\n  apply fa_morph; intros yy.\n  rewrite H0; rewrite (H _ _ (reflexivity _)); reflexivity.\nQed.\n\nLet isWf_accR x : isWf x -> Acc R x.\nintros.\napply isWf_ind with (2:=H); intros.\nconstructor; destruct 1; auto.\nQed.\n\nLet plump_eqn ub x :\n  isWf ub ->\n  (x ∈ plumps ub <->\n   x ⊆ ub /\\\n   (forall y, y ∈ ub -> y ∈ x -> y ∈ plumps y) /\\\n   (forall z y, y ∈ ub -> z ∈ plumps y -> z ⊆ y -> y ∈ x -> z ∈ x) /\\\n   Q x).\nintro.\nrevert x; induction H using isWf_ind; intros.\nunfold plumps at 1; rewrite WFR_eqn; fold plumps; trivial with *.\n unfold plump_set; rewrite subset_ax.\n rewrite power_ax.\n apply and_iff_morphisml; auto with *.\n  intros _ xincla.\n  split; intros.\n   destruct H1 as (x',?,(?&?&?&?)).\n   split; [|split]; intros; try rewrite H1 in *; eauto.\n\n   exists x; auto with *.\n   split; auto.\n   apply isWf_incl with a; trivial.\n\n intros; apply subset_morph; auto with *.\n red; intros.\n apply and_iff_morphisml; auto with *.\n intros _ wfx1.\n assert (forall z, z ∈ x1 -> z ∈ x0 -> R z x0).\n  split; trivial.\n  apply isWf_inv with x1; trivial.\n apply and_iff_morphism.\n  apply fa_morph; intros y.\n  apply fa_morph; intros h0.\n  apply fa_morph; intros h1.\n  rewrite (H2 y y); auto with *.\n apply and_iff_morphism; auto with *.\n apply fa_morph; intros z.\n apply fa_morph; intros y.\n apply fa_morph; intros h.\n split; intros.\n  apply H5; trivial.\n  rewrite (H2 y y); auto with *.\n\n  apply H5; trivial.\n  rewrite <- (H2 y y); auto with *.\n\n apply isWf_accR; trivial.\nQed.\n\nInstance plumps_morph : morph1 plumps.\ndo 2 red; intros; unfold plumps.\napply WFR_morph; trivial.\napply Rmorph.\nQed.\n\nLemma plump_bound : forall ub1 ub2 x,\n isWf ub1 ->\n isWf ub2 ->\n x ⊆ ub2 ->\n x ∈ plumps ub1 -> x ∈ plumps ub2.\nintros.\nrewrite plump_eqn in H2|-*; trivial.\ndestruct H2 as (?,(?,(?,?))).\neauto 10.\nQed.\n\n(** The class of directed plump ordinals *)\nDefinition isOrd x := isWf x /\\ x ∈ plumps x.\n\nLemma isOrd_wf o : isOrd o -> isWf o.\ndestruct 1; trivial.\nQed.\nHint Resolve isOrd_wf.\n\nLemma isOrd_ext : forall x y, x == y -> isOrd x -> isOrd y.\ndestruct 2.\nunfold isOrd; rewrite H in H0,H1; auto.\nQed.\n\nGlobal Instance isOrd_morph : Proper (eq_set ==> iff) isOrd.\ndo 2 red; split; intros.\n apply isOrd_ext with x; trivial.\n\n symmetry in H.\n apply isOrd_ext with y; trivial.\nQed.\n\nLemma isOrd_inv : forall x y,\n  isOrd x -> y < x -> isOrd y.\nintros.\ndestruct H.\nsplit.\n apply isWf_inv with x; trivial.\n\n rewrite plump_eqn in H1; trivial.\n destruct H1 as (_,(?,_)); auto.\nQed.\n\nLemma isOrd_plump : forall z, isOrd z ->\n forall x y, isOrd x -> x ⊆ y -> y ∈ z -> x ∈ z.\ndestruct 1; intros.\nrewrite plump_eqn in H0; trivial.\ndestruct H0 as (_,(_,(?,_))).\napply H0 with y; auto with *.\ndestruct H1.\napply plump_bound with x; auto with *.\napply isWf_inv with z; trivial.\nQed.\n\nLemma isOrd_dir : forall z, isOrd z -> Q z.\ndestruct 1; intros.\nrewrite plump_eqn in H0; trivial.\ndestruct H0 as (_,(_,(_,?))); trivial.\nQed.\n\nLemma isOrd_intro : forall x,\n  (forall a b, isOrd a -> a ⊆ b -> b ∈ x -> a ∈ x) ->\n  Q x ->\n  (forall y, y ∈ x -> isOrd y) ->\n  isOrd x.\nintros.\nassert (wfx : isWf x).\n apply isWf_intro; intros; apply isOrd_wf; apply H1; trivial.\nsplit; trivial.\nrewrite plump_eqn; trivial.\nsplit; [|split;[|split]]; intros; auto with *.\n apply H1; trivial.\n\n apply H with y; trivial.\n assert (wfy : isWf y).\n  apply isWf_inv with x; trivial.\n assert (wfz : isWf z).\n  apply isWf_intro; intros; apply isWf_inv with y; auto.\n split; trivial.\n apply plump_bound with y; auto with *.\nQed.\n\nLemma isOrd_trans : forall x y z,\n  isOrd x -> z < y -> y < x -> z < x.\nunfold lt.\nintros.\nassert (isWf x) by auto.\nrevert H y z H0 H1.\ninduction H2 using isWf_ind; intros.\napply isOrd_plump with y; auto.\n apply isOrd_inv with y; trivial.\n apply isOrd_inv with a; trivial.\n\n red; intros.\n apply H with z; trivial.\n apply isOrd_inv with a; trivial.\nQed.\n\nLemma isOrd_ind : forall x (P:set->Prop),\n  (forall y, isOrd y ->\n   y ⊆ x ->\n   (forall z, z < y -> P z) -> P y) ->\n  isOrd x -> P x.\nintros.\nassert (isWf x).\n destruct H0; trivial.\ncut (forall x', x' == x -> P x'); auto with *.\nrevert H0 H .\ninduction H1 using isWf_ind; simpl; intros.\napply H2; intros; auto with *.\n rewrite H3; trivial.\n\n rewrite H3; reflexivity.\n\n rewrite H3 in H4; clear x' H3.\n apply H with z; auto with *.\n  apply isOrd_inv with a; trivial.\n\n  intros; apply H2; trivial.\n  red; intros; apply isOrd_trans with z; auto.\n  red; auto.\nQed.\nEnd FirstOrder.\n\n(** Alternative definition of ordinals, slightly shorter by using Coq's accessibility\n   predicate, and the plump property below by well-founded induction.\n *)\nModule HigherOrder.\n\nFixpoint plump ub (p:Acc in_set ub) x : Prop :=\n  (forall y (q: y ∈ ub), y ∈ x -> plump y (Acc_inv p _ q) y) /\\\n  (forall z y (q: y ∈ ub), plump y (Acc_inv p _ q) z ->\n   z ⊆ y -> y ∈ x -> z ∈ x) /\\\n  isDir x.\n\nLemma plump_morph : forall x x' p p' y y',\n  x == x' -> y == y' -> (plump x p y <-> plump x' p' y').\nintros x x' p; revert x'.\ninduction p using Acc_indd; simpl; intros.\ndestruct p'; simpl.\nsplit; destruct 1 as (?,(?,?)); (split; [|split]); intros.\n assert (q' := q).\n rewrite <- H0 in q'.\n rewrite <- H1 in H5.\n rewrite <- (H y0 q' _ _ y0 y0); auto with *.\n\n assert (q' := q).\n rewrite <- H0 in q'.\n rewrite <- H1 in H7|-*.\n rewrite <- (H y0 q' _ _ z z) in H5; eauto with *.\n\n red; intros.\n destruct H4 with x0 y0.\n  rewrite H1; trivial.\n  rewrite H1; trivial.\n  exists x1; trivial.\n  rewrite <- H1; trivial.\n\n assert (q' := q).\n rewrite H0 in q'.\n rewrite H1 in H5.\n rewrite (H _ _ y0 (a0 _ q') _ y0); auto with *.\n\n assert (q' := q).\n rewrite H0 in q'.\n rewrite H1 in H7|-*.\n rewrite (H _ _ y0 (a0 _ q') _ z) in H5; eauto with *.\n\n red; intros.\n destruct H4 with x0 y0.\n  rewrite <- H1; trivial.\n  rewrite <- H1; trivial.\n  exists x1; trivial.\n  rewrite H1; trivial.\nQed.\n\nLemma plump_bound : forall ub1 ub2 p1 p2 x,\n x ⊆ ub1 ->\n plump ub1 p1 x -> plump ub2 p2 x.\ndestruct p1; destruct p2; simpl; intros.\ndestruct H0 as (?,(?,?)).\nsplit; [|split]; intros; trivial.\n assert (y ∈ ub1).\n  apply H; trivial.\n rewrite (plump_morph _ y _ (a _ H4) _ y); auto with *.\n\n assert (y ∈ ub1).\n  apply H; trivial.\n rewrite (plump_morph _ y _ (a _ H6) _ z) in H3; auto with *.\n apply H1 with y H6; auto.\nQed.\n\nLemma plump_Acc : forall ub p x,\n  plump ub p x -> x ⊆ ub -> Acc in_set x.\ninduction p using Acc_indd; simpl; intros.\ndestruct H0.\nconstructor; intros.\napply H with y (H1 _ H3); auto with *.\nQed.\n\n\nDefinition isOrd x :=\n  { p:Acc in_set x | plump x p x }.\n\nLemma isOrd_ext : forall x y, x == y -> isOrd x -> isOrd y.\ndestruct 2.\ngeneralize x0; rewrite H; intro.\nexists H0.\nrewrite <- (plump_morph x y x0 H0 x y); trivial.\nQed.\n\nInstance isOrd_morph : Proper (eq_set ==> iff) isOrd.\ndo 2 red; split; intros.\n apply isOrd_ext with x; trivial.\n\n symmetry in H.\n apply isOrd_ext with y; trivial.\nQed.\n\nLemma isOrd_inv : forall x y,\n  isOrd x -> y < x -> isOrd y.\nintros.\ndestruct H.\nexists (Acc_inv x0 _ H0).\ndestruct x0; simpl in *.\ndestruct p; auto.\nQed.\n\n\nLemma isOrd_plump : forall z, isOrd z ->\n forall x y, isOrd x -> x ⊆ y -> y ∈ z -> x ∈ z.\ndestruct 1; intros.\nrevert p.\ndestruct x;simpl; intros.\ndestruct p as (_,(?,_)).\napply H2 with y H1; trivial.\ndestruct H.\napply plump_bound with (2:=p); reflexivity.\nQed.\n\nLemma isOrd_dir : forall z, isOrd z -> isDir z.\ndestruct 1; intros.\nrevert p.\ndestruct x;simpl; intros.\ndestruct p as (_,(_,?)); trivial.\nQed.\n\n\nLemma isOrd_intro : forall x,\n  (forall a b, isOrd a -> a ⊆ b -> b ∈ x -> a ∈ x) ->\n  isDir x ->\n  (forall y, y ∈ x -> isOrd y) ->\n  isOrd x.\nintros.\nexists (Acc_intro _ (fun y h => proj1_sig (H1 y h))); simpl.\nsplit; [|split]; intros; trivial.\n destruct (H1 y H2).\n rewrite <- (plump_morph y y x0 _ y y); auto with *.\n\n apply H with y; trivial.\n exists (plump_Acc _ _ _ H2 H3).\n apply plump_bound with (2:=H2); trivial.\nQed.\n\n\nLemma isOrd_trans : forall x y z,\n  isOrd x -> z < y -> y < x -> z < x.\nunfold lt.\ndestruct 1.\nrevert y z p.\ninduction x0 using Acc_indd; simpl; intros.\nassert (isOrd x).\n exists (Acc_intro _ a); simpl; trivial.\ndestruct p.\napply isOrd_plump with y; trivial.\n apply isOrd_inv with y; trivial.\n apply isOrd_inv with x; trivial.\n\n red; intros.\n apply H with H1 z; auto.\nQed.\n\nLemma isOrd_ind : forall x (P:set->Prop),\n  (forall y, isOrd y ->\n   y ⊆ x ->\n   (forall z, z < y -> P z) -> P y) ->\n  isOrd x -> P x.\nintros.\ndestruct H0.\ncut (forall x', x' == x -> P x'); auto with *.\nrevert p H .\ninduction x0 using Acc_indd; simpl; intros.\ndestruct p.\nassert (isOrd x).\n exists (Acc_intro _ a); simpl; split; trivial.\napply H0; intros; auto with *.\n rewrite H1; trivial.\n\n red; intros.\n rewrite <- H1; trivial.\n\nrewrite H1 in H5.\nclear x' H1.\napply H with (r:=H5); intros; auto with *.\napply H0; intros; auto.\nred; intros.\napply isOrd_trans with z; auto.\napply H6; trivial.\nQed.\nEnd HigherOrder.\n\n(** * Simple theory of ordinals *)\n\nLemma lt_antirefl : forall x, isOrd x -> ~ x < x.\ninduction 1 using isOrd_ind; intros.\nred; intros; apply H1 with y; trivial.\nQed.\n\nLemma isOrd_zero : isOrd zero.\napply isOrd_intro; intros.\n elim empty_ax with b; trivial.\n\n red; intros.\n elim empty_ax with x; trivial.\n\n elim empty_ax with y; trivial.\nQed.\n\n(** Successor *)\nDefinition osucc x := subset (power x) isOrd.\n\nInstance osucc_morph : morph1 osucc.\nunfold osucc; do 2 red; intros.\napply subset_morph.\n rewrite H; reflexivity.\n\n red; auto with *.\nQed.\n\nLemma lt_osucc : forall x, isOrd x -> x < osucc x.\nunfold osucc, lt; intros.\napply subset_intro; trivial.\napply power_intro; auto.\nQed.\n\nHint Resolve isOrd_zero lt_osucc.\n\nLemma olts_le : forall x y, x < osucc y -> x ⊆ y.\nred; intros.\napply subset_elim1 in H.\napply power_elim with (1:=H); trivial.\nQed.\n\nLemma ole_lts : forall x y, isOrd x -> x ⊆ y -> x < osucc y.\nintros.\napply subset_intro; trivial.\napply power_intro; trivial.\nQed.\n\nLemma oles_lt : forall x y,\n  isOrd x ->\n  osucc x ⊆ y ->\n  x < y.\nintros.\napply H0.\napply lt_osucc; trivial.\nQed.\n\nLemma le_lt_trans : forall x y z, isOrd z -> x < osucc y -> y < z -> x < z.\nintros.\napply isOrd_plump with y; trivial.\n apply subset_elim2 in H0; destruct H0.\n rewrite H0; trivial.\n\n apply olts_le; trivial.\nQed.\n\nLemma ord_lt_le : forall o o', isOrd o -> o' ∈ o -> o' ⊆ o.\nred; intros; apply isOrd_trans with o'; trivial.\nQed.\nHint Resolve ord_lt_le.\n\nLemma isOrd_succ : forall n, isOrd n -> isOrd (osucc n).\nunfold osucc.\nintros.\napply isOrd_intro; intros.\n apply subset_intro; trivial.\n apply subset_elim1 in H2.\n apply power_intro; intros.\n apply H1 in H3.\n apply power_elim with (1:=H2); trivial.\n\n red; intros.\n exists n.\n  apply subset_intro; trivial.\n  apply power_intro; auto.\n\n  split.\n   red; intros.\n   apply power_elim with x; trivial.\n   apply subset_elim1 in H0; trivial.\n\n   red; intros.\n   apply power_elim with y; trivial.\n   apply subset_elim1 in H1; trivial.\n\n apply subset_elim2 in H0.\n destruct H0.\n rewrite H0; trivial.\nQed.\nHint Resolve isOrd_succ.\n\nLemma lt_osucc_compat : forall n m, isOrd m -> n < m -> osucc n < osucc m.\nintros.\napply ole_lts; auto.\n apply isOrd_succ.\n apply isOrd_inv with m; trivial.\n\n red; intros.\n apply le_lt_trans with n; trivial.\nQed.\n\nLemma osucc_mono : forall n m, isOrd n -> isOrd m -> n ⊆ m -> osucc n ⊆ osucc m.\nred; intros.\napply ole_lts.\n apply isOrd_inv with (osucc n); auto.\n\n apply olts_le in H2.\n transitivity n; trivial.\nQed.\n\n  Lemma lt_osucc_inv : forall o o',\n    isOrd o ->\n    osucc o < osucc o' ->\n    o < o'.\nunfold osucc; intros.\nrewrite subset_ax in H0; destruct H0.\ndestruct H1.\nrewrite power_ax in H0.\napply H0.\napply subset_intro; trivial.\napply power_intro; auto.\nQed.\n\nLemma isOrd_eq : forall o, isOrd o -> o == sup o osucc.\nintros.\napply eq_intro; intros.\n rewrite sup_ax.\n 2:do 2 red; intros; apply osucc_morph; trivial.\n exists z; auto.\n apply lt_osucc.\n apply isOrd_inv with o; trivial.\n\n rewrite sup_ax in H0.\n 2:do 2 red; intros; apply osucc_morph; trivial.\n destruct H0.\n apply le_lt_trans with x; trivial.\nQed.\n\n(** Examples: ordinals of rank less than 2 *)\nModule Examples.\n\nDefinition ord_0 := empty.\nDefinition ord_1 := osucc ord_0.\nDefinition ord_2 := osucc ord_1.\n\n(** 1 = {0} *)\nLemma ord1 : forall x, x ∈ ord_1 <-> x == zero.\nintros.\nunfold ord_1, osucc.\nrewrite subset_ax.\nsplit; intros.\n destruct H.\n rewrite power_ax in H.\n apply empty_ext.\n red; intros.\n apply H in H1.\n apply empty_ax with (1:=H1).\n\n split.\n  apply power_intro; intros.\n  rewrite H in H0; trivial.\n\n  exists zero; auto.\nQed.\n\nDefinition ord_rk_1 P := subset ord_1 (fun _ => P).\n\nLemma rk1_order : forall P Q, ord_rk_1 P ⊆ ord_rk_1 Q <-> (P->Q).\nsplit; intros.\n assert (zero ∈ ord_rk_1 P).\n  apply subset_intro; trivial.\n  unfold ord_1; apply lt_osucc; auto.\n apply H in H1.\n apply subset_elim2 in H1.\n destruct H1; trivial.\n\n red; intros.\n apply subset_intro.\n  apply subset_elim1 in H0; trivial.\n\n  apply subset_elim2 in H0.\n  destruct H0; auto.\nQed.\n\nLemma isOrd_rk_1 : forall P, isOrd (ord_rk_1 P).\nintros.\napply isOrd_intro; intros.\n unfold ord_rk_1 in H1; rewrite subset_ax in H1; destruct H1.\n destruct H2.\n clear x H2.\n apply subset_intro; auto.\n apply isOrd_plump with b; auto.\n unfold ord_1; auto.\n\n red; intros.\n assert P.\n  apply subset_elim2 in H; destruct H; trivial.\n apply subset_elim1 in H.\n apply subset_elim1 in H0.\n apply ord1 in H.\n apply ord1 in H0.\n exists empty.\n  apply subset_intro; trivial.\n  apply ord1; reflexivity.\n\n  rewrite H; rewrite H0; split; reflexivity.\n\n apply subset_elim1 in H.\n apply isOrd_inv with (osucc zero); auto.\nQed.\n\nDefinition isOrd2 x := exists P:Prop, x == ord_rk_1 P.\n\n(** 2 = {o| 0<=o<=1 } is isomorphic to Prop *)\nLemma ord2 : forall x, x ∈ ord_2 <-> exists P, x == ord_rk_1 P.\nintros.\nunfold ord_2, osucc at 1.\nrewrite subset_ax.\nrewrite power_ax.\nsplit; intros.\n destruct H.\n destruct H0.\n rewrite <- H0 in H1; clear H0 x0.\n exists (zero ∈ x).\n apply subset_ext; intros; auto.\n  apply ord1 in H0.\n  rewrite H0; trivial.\n\n  exists x0; auto with *.\n  specialize H with (1:=H0).\n  apply ord1 in H.\n  rewrite H in H0; trivial.\n\n destruct H.\n split; intros.\n  rewrite H in H0; clear H x.\n  apply subset_elim1 with (1:=H0).\n\n  exists x; auto with *.\n  rewrite H.\n  apply isOrd_rk_1.\nQed.\n\n\nDefinition ord_rk_2 (P2:Prop->Prop) :=\n  subset ord_2 (fun x => exists2 P, x == ord_rk_1 P & P2 P).\n\nDefinition decr_2 (P2:Prop->Prop) :=\n   (forall P Q:Prop, (P -> Q) -> (P2 Q -> P2 P)) /\\\n   (forall P Q:Prop, P2 P -> P2 Q -> P2 (P\\/Q)).\n\nLemma isOrd_rk_2 : forall P2, decr_2 P2 -> isOrd (ord_rk_2 P2).\nintros.\napply isOrd_intro; intros.\n assert (a ∈ ord_2).\n  apply isOrd_plump with b; auto.\n  unfold ord_2, ord_1; auto.\n  apply subset_elim1 in H2; trivial.\n apply subset_intro; auto.\n rewrite ord2 in H3.\n destruct H3.\n exists x; trivial.\n unfold ord_rk_2 in H2; rewrite subset_ax in H2; destruct H2.\n destruct H4.\n destruct H5.\n apply (proj1 H x x1); trivial.\n rewrite H4 in H1; rewrite H5 in H1; rewrite H3 in H1.\n rewrite <- rk1_order; trivial.\n\n red; intros.\n  unfold ord_rk_2 in H0,H1.\n  rewrite subset_ax in H0; destruct H0.\n  destruct H2.\n  destruct H3 as (P,?,?).\n  rewrite <- H2 in H3; clear x0 H2.\n  rewrite subset_ax in H1; destruct H1.\n  destruct H2.\n  destruct H5 as (Q,?,?).\n  rewrite <- H2 in H5; clear x0 H2.\n  exists (ord_rk_1 (P\\/Q)).\n   apply subset_intro.\n    apply ord2.\n    exists (P\\/Q); auto with *.\n\n    exists (P\\/Q); auto with *.\n    apply (proj2 H); trivial.\n\n   split.\n    rewrite H3; apply rk1_order; auto.\n    rewrite H5; apply rk1_order; auto.\n\n apply subset_elim1 in H0.\n apply isOrd_inv with (osucc (osucc zero)); auto.\nQed.\n\n(** 3 is isomorphic to decreasing functions of type Prop->Prop\n    (and closed by union to ensure directedness) *)\nLemma ord3 : forall x,\n  x ∈ osucc ord_2 <-> exists2 P2, decr_2 P2 & x == ord_rk_2 P2.\nintros.\nunfold osucc.\nrewrite subset_ax.\nrewrite power_ax.\nsplit; intros.\n destruct H.\n destruct H0.\n rewrite <- H0 in H1; clear H0 x0.\n exists (fun P => ord_rk_1 P ∈ x).\n  split; intros.\n   apply isOrd_plump with (ord_rk_1 Q); trivial.\n    assert (ord_rk_1 P ∈ ord_2).\n     rewrite ord2.\n     exists P; auto with *.\n    apply isOrd_inv with ord_2; auto.\n    unfold ord_2, ord_1; auto.\n\n    rewrite rk1_order; trivial.\n\n   destruct (isOrd_dir _ H1 _ _ H0 H2).\n   destruct H4.\n   apply isOrd_plump with x0; trivial.\n    apply isOrd_rk_1.\n\n    assert (h := H _ H3).\n    apply ord2 in h.\n    destruct h as (R,h).\n    rewrite h in H4,H5|-*.\n    apply rk1_order; destruct 1.\n     apply (proj1 (rk1_order P R)); trivial.\n     apply (proj1 (rk1_order Q R)); trivial.\n\n  apply subset_ext; intros; auto.\n   apply ord2 in H0.\n   destruct H2.\n   rewrite H2; trivial.\n   exists x0; auto with *.\n   specialize H with (1:=H0).\n   apply ord2 in H.\n   destruct H.\n   exists x1; trivial.\n   rewrite H in H0; trivial.\n\n destruct H.\n split; intros.\n  rewrite H0 in H1; clear H0 x.\n  apply subset_elim1 with (1:=H1).\n\n  exists x; auto with *.\n  rewrite H0.\n  apply isOrd_rk_2; trivial.\nQed.\n\n\nEnd Examples.\n\n\n(** Increasing sequences *)\n\nDefinition increasing F :=\n  forall x y, isOrd x -> isOrd y -> y ⊆ x -> F y ⊆ F x.\n\nLemma increasing_is_ext : forall F,\n  increasing F ->\n  forall o, isOrd o ->\n  ext_fun o F.\nintros F Fincr o H.\nred; red; intros.\napply eq_intro.\n apply Fincr.\n  rewrite <- H1; eauto using isOrd_inv.\n  eauto using isOrd_inv.\n  rewrite H1; reflexivity.\n apply Fincr.\n  eauto using isOrd_inv.\n  rewrite <- H1; eauto using isOrd_inv.\n  rewrite H1; reflexivity.\nQed.\nHint Resolve increasing_is_ext.\n\nDefinition increasing_bounded o F :=\n  forall x x', x' < o -> x < x' -> F x ⊆ F x'.\n\n(** Successor ordinals *)\n\nDefinition succOrd o := exists2 o', isOrd o' & o == osucc o'.\n\n(** Limit ordinals *)\n\nDefinition limitOrd o := isOrd o /\\ (forall x, x < o -> lt (osucc x) o).\n\nLemma limit_is_ord : forall o, limitOrd o -> isOrd o.\ndestruct 1; trivial.\nQed.\nHint Resolve limit_is_ord.\n\nLemma limit_union : forall o, limitOrd o -> union o == o.\ndestruct 1.\napply eq_intro; intros.\n apply union_elim in H1; destruct H1.\n apply isOrd_trans with x; trivial.\n\n apply union_intro with (osucc z).\n  apply lt_osucc.\n  apply isOrd_inv with o; trivial.\n\n  apply H0; trivial.\nQed.\n\nLemma limit_union_intro : forall o, isOrd o -> union o == o -> limitOrd o.\nsplit; trivial.\nunfold lt; intros.\nassert (isOrd x).\n apply isOrd_inv with o; trivial.\nrewrite <- H0 in H1.\napply union_elim in H1; destruct H1.\napply isOrd_plump with x0; auto.\nred; intros.\napply le_lt_trans with x; trivial.\napply isOrd_inv with o; trivial.\nQed.\n\nLemma discr_lim_succ : forall o, limitOrd o -> succOrd o -> False.\ndestruct 1; destruct 1.\nassert (lt (osucc x) o).\n apply H0.\n rewrite H2; auto.\nrewrite <- H2 in H3.\nelim lt_antirefl with o; trivial.\nQed.\n\nLemma isOrd_inter2 : forall x y,\n  isOrd x -> isOrd y -> isOrd (x ∩ y).\nintros.\nrevert y H0; apply isOrd_ind with (2:=H); intros.\nclear x H H1; rename y into x; rename y0 into y.\napply isOrd_intro; intros.\n rewrite inter2_def in H4|-*; destruct H4; split.\n  apply isOrd_plump with b; trivial.\n  apply isOrd_plump with b; trivial.\n\n red; intros.\n rewrite inter2_def in H; destruct H.\n rewrite inter2_def in H1; destruct H1.\n destruct (isOrd_dir _ H0 _ _ H H1).\n destruct H7.\n destruct (isOrd_dir _ H3 _ _ H4 H5).\n destruct H10.\n exists (x1 ∩ x2).\n  rewrite inter2_def; split.\n   apply isOrd_plump with x1; trivial.\n    apply H2; trivial.\n    apply isOrd_inv with y; trivial.\n\n    apply inter2_incl1.\n\n   apply isOrd_plump with x2; trivial.\n    apply H2; trivial.\n    apply isOrd_inv with y; trivial.\n\n    apply inter2_incl2.\n\n  split; red; intros; rewrite inter2_def; split; auto.\n\n rewrite inter2_def in H; destruct H.\n apply isOrd_inv with x; trivial.\nQed.\n\nLemma inter2_succ : forall x y,\n  isOrd x -> isOrd y ->\n  osucc x ∩ osucc y == osucc (x ∩ y).\nintros.\napply eq_intro; intros.\n rewrite inter2_def in H1.\n destruct H1.\n apply ole_lts; eauto using isOrd_inv.\n apply olts_le in H1; apply olts_le in H2.\n red; intros; rewrite inter2_def; auto.\n\n assert (isOrd z).\n  apply isOrd_inv with (osucc (x ∩ y)); trivial.\n  apply isOrd_succ; apply isOrd_inter2; trivial.\n rewrite inter2_def; split.\n  apply ole_lts; eauto using isOrd_inv.\n  apply olts_le in H1.\n  transitivity (x ∩ y); trivial.\n  apply inter2_incl1.\n\n  apply ole_lts; eauto using isOrd_inv.\n  apply olts_le in H1.\n  transitivity (x ∩ y); trivial.\n  apply inter2_incl2.\nQed.\n\n(** * Transfinite recursion *)\n\n(*begin hide *)\nRequire Import ZFpairs ZFrelations.\nRequire Import ZFrepl.\n\nModule FirstOrderStyle.\n\nSection TransfiniteRecursion.\n\n  Variable F : (set -> set) -> set -> set.\n  Hypothesis Fm : Proper ((eq_set ==> eq_set) ==> eq_set ==> eq_set) F.\n\n  Variable ord : set.\n  Hypothesis Fmorph :\n    forall x f f', isOrd x -> x ⊆ ord -> eq_fun x f f' -> F f x == F f' x.\n\n\n  Definition isTR_rel P :=\n    forall o y,\n    couple o y ∈ P ->\n    exists2 f, (forall n, n ∈ o -> couple n (cc_app f n) ∈ P) &\n      y == F (cc_app f) o.\n\n  Lemma isTR_rel_fun P P' o y y':\n    isOrd o ->\n    o ⊆ ord ->\n    isTR_rel P ->\n    isTR_rel P' -> \n    couple o y ∈ P ->\n    couple o y' ∈ P' ->\n    y == y'.\nintros oo ole istr istr' inP inP'; revert y y' inP inP'; elim oo using isOrd_ind; intros.\ndestruct istr with (1:=inP) as (f,?,?).\ndestruct istr' with (1:=inP') as (f',?,?).\nrewrite H3; rewrite H5; apply Fmorph; auto.\n transitivity o; trivial.\n\n red; intros.\n rewrite <- H7; clear x' H7.\n apply H1 with x; auto.\nQed.\n\nInstance isTR_rel_morph : Proper (eq_set==>iff) isTR_rel.\ndo 2 red; intros.\napply fa_morph; intro o.\napply fa_morph; intro y'.\nrewrite H.\napply fa_morph; intros ?.\napply ex2_morph; red; intros; auto with *.\napply fa_morph; intros n.\nrewrite H; reflexivity.\nQed.\n\n  Definition TR_rel o y :=\n    exists2 P, isTR_rel P & couple o y ∈ P.\n\n  Instance TR_rel_morph : Proper (eq_set ==> eq_set ==> iff) TR_rel.\ndo 3 red; intros.\napply ex2_morph; red; intros; auto with *.\nrewrite H; rewrite H0; reflexivity.\nQed.\n\n  Lemma TR_rel_intro x f :\n    morph1 f ->\n    isOrd x ->\n    x ⊆ ord ->\n    (forall y, y ∈ x -> TR_rel y (f y)) ->\n    TR_rel x (F f x).\nintros fm xo xle Hsub.\nexists (singl (couple x (F f x)) ∪ replf x (fun y' => couple y' (f y'))).\n red; intros.\n rewrite union2_ax in H; destruct H.\n  apply singl_elim in H.\n  apply couple_injection in H; destruct H.\n  exists (cc_lam o f); intros.\n   rewrite H in H1|-*; clear o H.\n   apply union2_intro2.\n   rewrite replf_ax. 2:do 2 red; intros; apply couple_morph; auto.\n   exists n; auto with *.\n   rewrite cc_beta_eq; auto with *.\n\n   rewrite H; clear o H.\n   rewrite H0.\n   apply Fmorph; auto.\n   red; intros.\n   rewrite <- H1; clear x' H1.\n   rewrite cc_beta_eq; auto with *.\n\n  rewrite replf_ax in H. 2:do 2 red; intros; apply couple_morph; auto.\n  destruct H.\n  apply couple_injection in H0; destruct H0.\n  rewrite <- H0 in H,H1; clear x0 H0.\n  destruct Hsub with (1:=H) as (P,?,?).\n  assert (oo : isOrd o).\n   apply isOrd_inv with x; trivial.\n  assert (ole : o ⊆ ord).\n   red; intros; apply xle; apply isOrd_trans with o; trivial.\n  exists (cc_lam o f).\n   intros.\n   apply union2_intro2.\n   rewrite replf_ax. 2:do 2 red; intros; apply couple_morph; auto.\n   exists n; auto with *.\n    apply isOrd_trans with o; trivial.\n   rewrite cc_beta_eq; auto with *.\n\n   rewrite H1.\n   destruct H0 with (1:=H2) as (g,?,?).\n   rewrite H4.\n   apply Fmorph; auto.\n   red; intros.\n   rewrite <- H6; clear x' H6.\n   assert (x0o: isOrd x0).\n    apply isOrd_inv with o; trivial.\n   assert (x0le : x0 ⊆ ord).\n    red; intros; apply ole; apply isOrd_trans with x0; trivial.\n   rewrite cc_beta_eq; auto with *.\n   apply isTR_rel_fun with P P x0; auto.\n   destruct Hsub with x0 as (P',?,?).\n    apply isOrd_trans with o; trivial.\n   rewrite <- (isTR_rel_fun _ _ _ _ _) with (3:=H0) (4:=H6) (5:=H3 _ H5) (6:=H7); auto. (* ?*)\n\n apply union2_intro1.\n apply singl_intro.\nQed.\n\n  Lemma TR_rel_ex o :\n    isOrd o -> o ⊆ ord ->\n    uchoice_pred (TR_rel o).\nintros oo.\nelim oo using isOrd_ind; intros.\nsplit;[|split]; intros.\n rewrite <- H3; trivial.\n\n exists (F (fun y' => uchoice (TR_rel y')) y).\n assert (chm : morph1 (fun n => uchoice (TR_rel n))).\n  do 2 red; intros; apply uchoice_morph_raw.\n  red; intros.\n  apply TR_rel_morph; trivial.\n apply TR_rel_intro; intros; trivial.\n apply uchoice_def; apply H1; trivial.\n red; intros; apply H2; apply isOrd_trans with y0; trivial.\n\n destruct H3 as (P,?,?).\n destruct H4 as (P',?,?).\n apply isTR_rel_fun with P P' y; auto.\nQed.\n\n  Definition TR := uchoice (fun y => TR_rel ord y).\n\n  Lemma TR_eqn0 : forall o, isOrd o -> o ⊆ ord ->\n     uchoice (fun y => TR_rel o y) == F (fun o => uchoice (fun y => TR_rel o y)) o.\nintros.\nspecialize TR_rel_ex with (1:=H) (2:=H0); intro.\napply uchoice_def in H1.\ndestruct H1 as (P,?,?).\ndestruct H1 with (1:=H2) as (f,?,?).\nrewrite H4.\napply Fmorph; auto.\nred; intros.\nrewrite H6 in H5|-*; clear x H6.\napply uchoice_ext.\n apply TR_rel_ex.\n  apply isOrd_inv with o; trivial.\n\n  red; intros; apply H0; apply isOrd_trans with x'; trivial.\n\n exists P; auto.\nQed.\n\nEnd TransfiniteRecursion.\n\n  Global Instance TR_morph0 : forall F, morph1 (TR F).\ndo 2 red; intros.\nunfold TR.\napply uchoice_morph_raw.\nred; intros.\nassert (trm := TR_rel_morph).\nrewrite H; rewrite H0; reflexivity.\nQed.\n\n  Global Instance TR_morph :\n    Proper (((eq_set ==> eq_set) ==> eq_set ==> eq_set) ==> eq_set ==> eq_set) TR.\ndo 3 red; intros.\nunfold TR.\napply uchoice_morph_raw; red; intros.\nunfold TR_rel.\napply ex2_morph; red; intros.\n apply fa_morph; intros o.\n apply fa_morph; intros y'.\n apply fa_morph; intros _.\n apply ex2_morph; red; intros; auto with *.\n split; intros h; rewrite h;[|symmetry];\n   (apply H; [apply cc_app_morph|]; reflexivity).\n\n rewrite H0; rewrite H1; reflexivity.\nQed.\n\nEnd FirstOrderStyle.\n(*end hide *)\n\n(** Higher-order style: quantification over relations *)\n\nSection TransfiniteRecursion.\n\n  Variable F : (set -> set) -> set -> set.\n  Hypothesis Fm : Proper ((eq_set ==> eq_set) ==> eq_set ==> eq_set) F.\n\n  Let R o o' := o < o'.\n\n  Local Instance Rm : Proper (eq_set==>eq_set==>iff) R.\nunfold R; do 3 red; intros.\nrewrite H,H0; reflexivity.\nQed.\n\n  Definition TR := WFR R F.\n\nGlobal Instance TR_morph0 : morph1 TR.\nclear Fm; do 2 red; intros.\nunfold TR.\napply WFR_morph0; trivial.\nQed.\n\n  Lemma TR_eqn o :\n    isOrd o ->\n    (forall x f f', isOrd x -> x ⊆ o -> eq_fun x f f' -> F f x == F f' x) ->\n    TR o == F TR o.\nintros oo Fext.\nunfold TR.\napply WFR_eqn_gen; auto with *.\nelim oo using isOrd_ind; intros; constructor; intros; auto.\nQed. \n\n  Lemma TR_ind : forall o (P:set->set->Prop),\n    Proper (eq_set ==> eq_set ==> iff) P ->\n    isOrd o ->\n    (forall x f f', isOrd x -> x ⊆ o -> eq_fun x f f' -> F f x == F f' x) ->\n    (forall y, isOrd y -> y ⊆ o ->\n     (forall x, x < y -> P x (TR x)) ->\n     P y (F TR y)) ->\n    P o (TR o).\nintros o P Pm oo Fmorph.\nrevert Fmorph; induction oo using isOrd_ind; intros.\nrewrite TR_eqn; trivial.\napply H1; auto with *; intros.\napply H0; intros; trivial.\n  assert (x0 ⊆ y).\n   transitivity x; auto.\n auto.\napply H1; trivial.\ntransitivity x; auto.\nQed.\n\n  Lemma TR_typ : forall o X,\n    isOrd o ->\n    (forall x f f', isOrd x -> x ⊆ o -> eq_fun x f f' -> F f x == F f' x) ->\n    morph1 X ->\n    (forall y f, morph1 f -> isOrd y -> y ⊆ o ->\n     (forall z, z < y -> f z ∈ X z) -> F f y ∈ X y) ->\n    TR o ∈ X o.\nintros o X oo Fmorph Xm Hrec.\napply TR_ind with (o:=o); intros; trivial.\n do 3 red; intros.\n rewrite H; rewrite H0; reflexivity.\n\n apply Fmorph; trivial.\n\n apply Hrec; trivial; intros.\n apply TR_morph0.\nQed.\n\n  \nEnd TransfiniteRecursion.\n\n\nGlobal Instance TR_morph :\n    Proper (((eq_set ==> eq_set) ==> eq_set ==> eq_set) ==> eq_set ==> eq_set) TR.\ndo 3 red; intros.\napply WFR_morph; trivial.\n do 2 red; intros.\n rewrite H1, H2; reflexivity.\nQed.\n\n  Lemma TR_ext_ord F F' o o' :\n  (forall f f' oo,\n   morph1 f ->\n   morph1 f' ->\n   (forall z, z ∈ oo -> f z == f' z) ->\n   isOrd oo ->\n   oo ⊆ o ->\n   F f oo == F' f' oo) ->\n isOrd o ->\n o == o' ->\n TR F o == TR F' o'.\nintros.\napply WFR_ext; auto with *.\n do 2 red; intros.\n rewrite H2; reflexivity.\nintros.\nassert (isOrd y /\\ y ⊆ o).\n apply Kstar_rel with (3:=H5); auto with *.\n  do 2 red; intros.\n  rewrite H6; reflexivity.\n\n  destruct 2; split.\n   apply isOrd_inv with y0; trivial.\n   rewrite <- H8; auto.\nclear H5; destruct H6.\napply H; trivial.\nQed.\n\n(** Specialized version where the case of limit ordinals is union *)\nSection TransfiniteIteration.\n\n  Variable F : set -> set.\n  Hypothesis Fmorph : Proper (eq_set ==> eq_set) F.\n\nLet G f o := sup o (fun o' => F (f o')).\n\nLet Gm : Proper ((eq_set ==> eq_set) ==> eq_set ==> eq_set) G.\ndo 3 red; intros.\nunfold G.\napply sup_morph; trivial.\nred; intros.\napply Fmorph.\napply H; trivial.\nQed.\n\nLet Gmorph : forall o f f', eq_fun o f f' -> G f o == G f' o.\nunfold G; intros.\napply sup_morph; auto with *.\nred; auto.\nQed.\n\n  Definition TI := TR G.\n\n  Instance TI_morph : morph1 TI.\nunfold TI; do 2 red; intros.\napply TR_morph0; auto with *.\nQed.\n\n  Lemma TI_fun_ext : forall x, ext_fun x (fun y => F (TI y)).\ndo 2 red; intros.\napply Fmorph.\napply TI_morph; trivial.\nQed.\nHint Resolve TI_fun_ext.\n\n  Lemma TI_eq : forall o,\n    isOrd o ->\n    TI o == sup o (fun o' => F (TI o')).\nintros.\nunfold TI.\napply TR_eqn; auto.\nQed.\n\n  Lemma TI_intro : forall o o' x,\n    isOrd o ->\n    lt o' o ->\n    x ∈ F (TI o') ->\n    x ∈ TI o.\nintros.\nrewrite TI_eq; trivial.\nrewrite sup_ax; auto.\nexists o'; trivial.\nQed.\n\n  Lemma TI_elim : forall o x,\n    isOrd o ->\n    x ∈ TI o ->\n    exists2 o', o' < o & x ∈ F (TI o').\nintros.\nrewrite TI_eq in H0; trivial.\nrewrite sup_ax in H0; auto.\nQed.\n\n  Lemma TI_mono : increasing TI.\ndo 2 red; intros.\napply TI_elim in H2; intros; auto with *.\ndestruct H2.\napply TI_intro with x0; auto with *.\napply H1 in H2; trivial.\nQed.\n\n  Lemma TI_incl : forall o, isOrd o ->\n    forall o', o' < o ->\n    TI o' ⊆ TI o.\nintros.\napply TI_mono; trivial; auto.\napply isOrd_inv with o; trivial.\nQed.\n\n  Lemma TI_initial : TI zero == empty.\napply empty_ext; red; intros.\napply TI_elim in H.\n destruct H.\n elim empty_ax with (1:=H).\n\n apply isOrd_zero.\nQed.\n\n  Lemma TI_typ : forall n X,\n    (forall a, a ∈ X -> F a ∈ X) ->\n    isOrd n ->\n    (forall m G, isOrd m -> m ⊆ n ->\n     ext_fun m G ->\n     (forall x, x < m -> G x ∈ X) -> sup m G ∈ X) ->\n    TI n ∈ X.\ninduction 2 using isOrd_ind; intros.\nrewrite TI_eq; trivial.\napply H3 with (G:=fun o => F (TI o)); intros; auto with *.\napply H.\napply H2; trivial; intros.\napply H3; auto.\nred; intros.\napply H6 in H9.\napply isOrd_trans with x; trivial.\nQed.\n\nEnd TransfiniteIteration.\nHint Resolve TI_fun_ext.\n\nGlobal Instance TI_morph_gen :\n  Proper ((eq_set==>eq_set)==>eq_set==>eq_set) TI.\ndo 3 red; intros.\nunfold TI.\napply TR_morph; trivial.\ndo 2 red; intros.\napply sup_morph; trivial.\nred; intros.\napply H; apply H1; trivial.\nQed.\n\n(** * Supremum of directed ordinals *)\n\n(** ** Binary supremum *)\n\nSection BinarySup.\n\n  Definition isCouple c := c == couple (fst c) (snd c).\n  Global Instance isCouple_morph : Proper (eq_set==>iff) isCouple.\ndo 2 red; intros; unfold isCouple.\nrewrite H; reflexivity.\nQed.\n  Lemma isCouple_couple a b : isCouple (couple a b).\nred.\nrewrite fst_def, snd_def; reflexivity.\nQed.\nHint Resolve isCouple_couple.\n  \n  Let R xy xy' := isCouple xy /\\ fst xy < fst xy'.\n  Let Rm : Proper (eq_set==>eq_set==>iff) R.\nunfold R; do 3 red; intros.\nrewrite H,H0; reflexivity.\nQed.\n\n  Let F f xy :=\n    let x := fst xy in\n    let y := snd xy in\n    x ∪ y ∪ sup x (fun x' => replf y (fun y' => f (couple x' y'))).\n  Let Fm : Proper ((eq_set==>eq_set)==>eq_set==>eq_set) F.       \nunfold F; do 3 red; intros.\napply union2_morph.\n rewrite H0; reflexivity.\napply sup_morph;[rewrite H0;reflexivity|].\nred; intros.\napply replf_morph;[rewrite H0;reflexivity|].\nred; intros.\napply H; rewrite H2,H4; reflexivity.\nQed.\n\n  Definition osup2 x y := WFR R F (couple x y).\n\nInfix \"⊔\" := osup2 (at level 50). (* input method: \\sqcup *)\n(* ⋓ = \\Cup would be nicer, but poor html rendering... *)\n\nInstance osup2_morph : morph2 osup2.\nunfold osup2; do 3 red; intros.\nrewrite H,H0; reflexivity.\nQed.\n\n  Lemma osup2_def : forall x y, isOrd x ->\n    x ⊔ y == x ∪ y ∪ sup x (fun x' => replf y (fun y' => x' ⊔ y')).\nintros.\nunfold osup2 at 1.\nrewrite WFR_eqn; auto.\n unfold F.\n apply union2_morph.\n  rewrite fst_def,snd_def; reflexivity.\n apply sup_morph.\n  apply fst_def.\n red; intros.\n apply replf_morph.\n  apply snd_def.\n red; intros.\n apply osup2_morph; trivial.\n\n intros.\n apply union2_morph; auto with *.\n apply sup_morph; auto with *.\n red; intros.\n apply replf_morph; auto with *.\n red; intros.\n apply H1.\n  red.\n  rewrite fst_def; auto.\n\n  rewrite H3,H5; reflexivity.\n\n revert y; elim H using isOrd_ind; intros.\n constructor; destruct 1.\n rewrite fst_def in H4.\n eapply wf_morph with  (3:=Rm)(4:=H3) ; auto with *.\nQed.\n\nLemma osup2_ax : forall x y z,\n  isOrd x ->\n  (z ∈ x ⊔ y <->\n   z ∈ x \\/ z ∈ y \\/\n   exists2 x', x' ∈ x & exists2 y', y' ∈ y & z == x' ⊔ y').\nintros x y z wfx.\nrewrite osup2_def; trivial.\nsplit; intros.\n apply union2_elim in H; destruct H.\n  apply union2_elim in H; destruct H; auto.\n\n  rewrite sup_ax in H.\n   destruct H.\n   rewrite replf_ax in H0.\n    destruct H0; eauto.\n\n    red; red; intros.\n    apply osup2_morph; auto with *.\n\n   red; red; intros.\n   apply replf_morph; auto with *.\n   red; intros.\n   apply osup2_morph; trivial.\n\n destruct H as [?|[?|?]].\n  apply union2_intro1; apply union2_intro1; trivial.\n\n  apply union2_intro1; apply union2_intro2; trivial.\n\n  apply union2_intro2.\n  destruct H.\n  destruct H0.\n  rewrite sup_ax.\n   exists x0; trivial.\n   rewrite replf_ax.\n    exists x1; trivial.\n\n    red; red; intros.\n    apply osup2_morph; auto with *.\n\n   red; red; intros.\n   apply replf_morph; auto with *.\n   red; intros.\n   apply osup2_morph; trivial.\nQed.\n\nLemma osup2_incl1 : forall x y, isOrd x -> x ⊆ x ⊔ y.\nred; intros.\nrewrite osup2_ax; auto.\nQed.\n\nLemma osup2_incl2 : forall x y, isOrd x -> y ⊆ x ⊔ y.\nred; intros.\nrewrite osup2_ax; auto.\nQed.\n\nLemma osup2_mono x x' y y' :\n  isOrd x' ->\n  isOrd x ->\n  x ⊆ x' -> y ⊆ y' ->\n  x ⊔ y ⊆ x' ⊔ y'.\nred; intros.\nrewrite osup2_ax in H3|-*; trivial.\ndestruct H3 as [?|[?|(a,?,(b,?,?))]]; auto.\nright; right.\nexists a; auto.\nexists b; auto with *.\nQed.\n\nLemma isDir_osup2 : forall x y, isOrd x -> isDir x -> isDir y -> isDir (x ⊔ y).\nred; unfold lt; intros x y wfx H H0; intros.\nassert (wfi := isOrd_inv).\nrewrite osup2_ax in H1,H2; trivial.\ndestruct H1 as [?|[?|(x1,?,(x2,?,?))]];\n  destruct H2 as [?|[?|(y1,?,(y2,?,?))]].\n (* case 1. *)\n destruct (H x0 y0); trivial.\n exists x1; trivial.\n apply osup2_incl1; trivial.\n (* case 2. *)\n exists (x0 ⊔ y0).\n  rewrite osup2_ax; trivial; right; right; eauto with *.\n\n  split.\n   apply osup2_incl1; eauto.\n   apply osup2_incl2; eauto.\n (* case 3. *)\n destruct (H x0 y1); trivial.\n destruct H6.\n exists (x1 ⊔ y2).\n  rewrite osup2_ax; trivial; right; right; eauto with *.\n\n  split.\n   transitivity x1; trivial.\n   apply osup2_incl1; eauto.\n\n   rewrite H4; apply osup2_mono; eauto with *.\n (* case 4. *)\n exists (y0 ⊔ x0).\n  rewrite osup2_ax; trivial; right; right; eauto with *.\n\n  split.\n   apply osup2_incl2; eauto.\n   apply osup2_incl1; eauto.\n (* case 5. *)\n destruct (H0 x0 y0); trivial.\n exists x1; trivial.\n apply osup2_incl2; trivial.\n (* case 6. *)\n destruct (H0 x0 y2); trivial.\n destruct H6.\n exists (y1 ⊔ x1).\n  rewrite osup2_ax; trivial; right; right; eauto with *.\n\n  split.\n   transitivity x1; trivial.\n   apply osup2_incl2; eauto.\n\n   rewrite H4; apply osup2_mono; eauto with *.\n (* case 7. *)\n destruct (H x1 y0); trivial.\n destruct H6.\n exists (x3 ⊔ x2).\n  rewrite osup2_ax; trivial; right; right; eauto with *.\n\n  split.\n   rewrite H4; apply osup2_mono; eauto with *.\n\n   transitivity x3; trivial; apply osup2_incl1; eauto.\n (* case 8. *)\n destruct (H0 x2 y0); trivial.\n destruct H6.\n exists (x1 ⊔ x3).\n  rewrite osup2_ax; trivial; right; right; eauto with *.\n\n  split.\n   rewrite H4; apply osup2_mono; eauto with *.\n\n   transitivity x3; trivial; apply osup2_incl2; eauto.\n (* case 9. *)\n destruct (H x1 y1); trivial.\n destruct H8.\n destruct (H0 x2 y2); trivial.\n destruct H11.\n exists (x3 ⊔ x4).\n  rewrite osup2_ax; trivial; right; right; eauto with *.\n\n  split.\n   rewrite H4; apply osup2_mono; eauto with *.\n\n   rewrite H6; apply osup2_mono; eauto with *.\nQed.\n\nLemma osup2_proof : forall x, isOrd x -> forall y, isOrd y ->\n  isOrd (x ⊔ y) /\\\n  (forall z, isOrd z -> z ∩ (x ⊔ y) == z ∩ x ⊔ z ∩ y).\ninduction 1 using isOrd_ind.\nclear H0 x; rename y into x; rename H1 into Hrecx.\nintros y yo.\nrename H into xo.\nsplit.\n (* isOrd *)\n apply isOrd_intro; intros.\n  (* plump *)\n  rewrite osup2_ax in H1|-*; auto.\n  destruct H1 as [?|[?|(x',?,(y',?,?))]].\n   left; apply isOrd_plump with b; trivial.\n\n   right; left; apply isOrd_plump with b; trivial.\n\n   right; right.\n   exists (a ∩ x').\n    apply isOrd_plump with x'; trivial.\n     apply isOrd_inter2; eauto using isOrd_inv.\n     apply inter2_incl2.\n\n    exists (a ∩ y').\n     apply isOrd_plump with y'; trivial.\n      apply isOrd_inter2; eauto using isOrd_inv.\n      apply inter2_incl2.\n\n     destruct Hrecx with x' y' as (_,?); eauto using isOrd_inv.\n     rewrite <- H4; trivial.\n     apply eq_intro; intros.\n      rewrite inter2_def; split; trivial.\n      rewrite <- H3; auto.\n\n      apply inter2_def in H5; destruct H5; trivial.\n\n  (* dir *)\n  apply isDir_osup2; auto.\n\n  apply isOrd_dir; trivial.\n   apply isOrd_dir; trivial.\n\n  (* trans *)\n  apply osup2_ax in H; auto.\n  destruct H as [?|[?|(x',?,(y',?,?))]]; eauto using isOrd_inv.\n  rewrite H1; apply Hrecx; eauto using isOrd_inv.\n\n (* inter distrib *)\n intros.\n assert (wfizx : isOrd (z ∩ x)).\n  apply isOrd_inter2; auto.\n assert (wfizy : isOrd (z ∩ y)).\n  apply isOrd_inter2; auto.\n assert (Hrec: forall x' y' z, x' ∈ x -> y' ∈ y -> isOrd z ->\n                 z ∩ (x' ⊔ y') == z ∩ x' ⊔ z ∩ y').\n  intros; apply Hrecx; eauto using isOrd_inv.\n apply eq_intro; intros.\n  rewrite inter2_def in H0; trivial; destruct H0.\n  rewrite osup2_ax in H1; auto.\n  destruct H1 as [?|[?|(x',?,(y',?,?))]].\n   apply osup2_incl1; trivial.\n   rewrite inter2_def; auto.\n\n   apply osup2_incl2; trivial.\n   rewrite inter2_def; auto.\n\n   rewrite osup2_ax; trivial; right; right.\n   exists (z0 ∩ x').\n    rewrite inter2_def; split.\n     apply isOrd_plump with z0; auto.\n      apply isOrd_inter2; eauto using isOrd_inv.\n      apply inter2_incl1.\n     apply isOrd_plump with x'; auto.\n      apply isOrd_inter2; eauto using isOrd_inv.\n      apply inter2_incl2.\n   exists (z0 ∩ y').\n    rewrite inter2_def; split.\n     apply isOrd_plump with z0; auto.\n      apply isOrd_inter2; eauto using isOrd_inv.\n      apply inter2_incl1.\n     apply isOrd_plump with y'; auto.\n      apply isOrd_inter2; eauto using isOrd_inv.\n      apply inter2_incl2.\n   rewrite <- Hrec; eauto using isOrd_inv.\n   rewrite incl_inter2; auto with *. \n   rewrite H3; reflexivity.\n\n  rewrite osup2_ax in H0; trivial.\n  destruct H0 as [?|[?|(x',?,(y',?,?))]].\n   rewrite inter2_def in H0; destruct H0; rewrite inter2_def; split; trivial.\n   apply osup2_incl1; auto.\n\n   rewrite inter2_def in H0; destruct H0; rewrite inter2_def; split; trivial.\n   apply osup2_incl2; auto.\n\n   rewrite inter2_def in H0; destruct H0.\n   rewrite inter2_def in H1; destruct H1.\n   rewrite H2; clear z0 H2.\n   destruct (isOrd_dir _ H x' y'); trivial.\n   destruct H5.\n   rewrite inter2_def; split.\n    apply isOrd_plump with x0; trivial.\n     apply Hrecx; eauto using isOrd_inv.\n     rewrite <- (incl_inter2 _ _) with (1:=H5). (*!*)\n     rewrite <- (incl_inter2 _ _) with (1:=H6). (*!*)\n     rewrite (inter2_comm x' x0); rewrite (inter2_comm y' x0).\n     rewrite <- Hrec; eauto using isOrd_inv.\n     apply inter2_incl1.\n\n    rewrite (osup2_ax x y); auto; right; right; eauto with *.\nQed.\n\nLemma isOrd_osup2 : forall x y,\n  isOrd x ->\n  isOrd y ->\n  isOrd (x ⊔ y).\nintros.\napply osup2_proof; trivial.\nQed.\n\nLemma osup2_lub : forall x y z,\n  isOrd x -> isOrd y -> isOrd z ->\n  x ⊆ z -> y ⊆ z -> x ⊔ y ⊆ z.\nintros.\nrewrite <- (incl_inter2 _ _) with (1:=H2). (*!*)\nrewrite <- (incl_inter2 _ _) with (1:=H3). (*!*)\nrewrite (inter2_comm x z); rewrite (inter2_comm y z).\ndestruct osup2_proof with (1:=H)(2:=H0) as (_,dint); rewrite <- dint; trivial.\napply inter2_incl1.\nQed.\n\nLemma osup2_refl x : isOrd x -> x ⊔ x == x.\nintros.\napply eq_intro; intros.\n revert H0; apply osup2_lub; auto with *.\n\n apply osup2_incl1; auto.\nQed.\n\nLemma osup2_lt x y z : isOrd z -> x ∈ z -> y ∈ z -> x ⊔ y ∈ z.\nintros.\ndestruct (isOrd_dir _ H x y); trivial.\ndestruct H3.\napply isOrd_plump with x0; trivial.\n apply isOrd_osup2; eauto using isOrd_inv.\n\n apply osup2_lub; eauto using isOrd_inv.\nQed.\n\nLemma isDir_succ : forall o,\n  isOrd o -> isDir (osucc o).\nred; intros.\nassert (xo : isWf x) by (apply isOrd_inv with (osucc o); auto).\nexists (x ⊔ y).\n apply osup2_lt; auto.\n\n split.\n  apply osup2_incl1; eauto using isOrd_inv.\n  apply osup2_incl2; eauto using isOrd_inv.\nQed.\n\n\nLemma osup2_sym : forall x y, isOrd x -> isOrd y -> x ⊔ y == y ⊔ x.\nintros x y wfx wfy.\nrevert y wfy ; apply isOrd_ind with (2:=wfx); intros.\napply eq_intro; intros.\n rewrite osup2_ax in H2|-*; trivial.\n destruct H2 as [?|[?|(x',?,(y',?,?))]];[right;left|left|right;right]; trivial.\n exists y'; trivial.\n exists x'; trivial.\n rewrite H4; apply H1; eauto using isOrd_inv.\n\n rewrite osup2_ax in H2|-*; trivial.\n destruct H2 as [?|[?|(x',?,(y',?,?))]];[right;left|left|right;right]; trivial.\n exists y'; trivial.\n exists x'; trivial.\n rewrite H4; symmetry; apply H1; eauto using isOrd_inv.\nQed.\n\nLemma osup2_assoc : forall x y z, isOrd x -> isOrd y -> isOrd z ->\n  x ⊔ (y ⊔ z) == x ⊔ y ⊔ z.\nintros x y z wfx; revert y z; apply isOrd_ind with (2:=wfx); intros.\napply eq_intro; intros.\n rewrite osup2_ax in H4|-*; auto.\n 2:apply isOrd_osup2; trivial.\n rewrite osup2_ax; auto.\n destruct H4 as [?|[?|(x',?,(w',?,?))]]; auto.\n  rewrite osup2_ax in H4; auto.\n  destruct H4 as [?|[?|(y',?,(z',?,?))]]; auto.\n  right; right.\n  exists y';[|exists z']; trivial.\n  apply osup2_incl2; auto.\n\n  rewrite osup2_ax in H5; auto.\n  destruct H5 as [?|[?|(y'',?,(z',?,?))]]; auto.\n   left; right; right; exists x'; [trivial|exists w';trivial].\n\n   right; right; exists x'; [|exists w';trivial].\n   apply osup2_incl1; auto.\n\n   right; right; exists (x' ⊔ y'');[|exists z']; trivial.\n    rewrite osup2_ax; [right; right; exists x'; [trivial|exists y'']; auto with *|auto].\n\n    rewrite <- H1; eauto using isOrd_inv.\n    rewrite <- H8; trivial.\n\n rewrite osup2_ax in H4|-*; auto.\n 2:apply isOrd_osup2; trivial.\n rewrite osup2_ax; auto.\n destruct H4 as [?|[?|(w',?,(z',?,?))]]; auto.\n  rewrite osup2_ax in H4; auto.\n  destruct H4 as [?|[?|(y',?,(z',?,?))]]; auto.\n  right; right.\n  exists y';[|exists z']; trivial.\n  apply osup2_incl1; auto.\n\n  rewrite osup2_ax in H4; auto.\n  destruct H4 as [?|[?|(x',?,(y',?,?))]]; auto.\n   right; right; exists w'; [trivial|exists z';trivial].\n   apply osup2_incl2; auto.\n\n   right; left; right; right; exists w'; [trivial|exists z';trivial].\n\n   right; right; exists x';[|exists (y' ⊔ z')]; trivial.\n    rewrite osup2_ax; [right; right; exists y'; [trivial|exists z']; auto with *|auto].\n\n    rewrite H1; eauto using isOrd_inv.\n    rewrite <- H8; trivial.\nQed.\n\nEnd BinarySup.\nInfix \"⊔\" := osup2 (at level 50). (* input method: \\sqcup *)\n\n(** ** Indexed supremum of monotonic family *)\n\nSection OrdinalUpperBound.\n\n  Variable I : set.\n  Variable f : set -> set.\n  Hypothesis f_ext : ext_fun I f.\n  Hypothesis f_ord : forall x, x ∈ I -> isOrd (f x).\n\n  Lemma isOrd_supf_intro : forall n, n ∈ I -> f n ⊆ sup I f.\nred; intros.\nrewrite sup_ax; trivial.\nexists n; trivial.\nQed.\n\n  Lemma isOrd_supf_elim : forall x, x < sup I f -> exists2 n, n ∈ I & x < f n.\nintros.\nrewrite sup_ax in H; trivial.\nQed.\n\n  (* Directed union: *)\n  Hypothesis supf_dir : forall x y, x ∈ I -> y ∈ I ->\n    exists2 z, z ∈ I & f x ⊆ f z /\\ f y ⊆ f z.\n\n  Lemma isDir_ord_sup : isDir (sup I f).\nred; intros.\nrewrite sup_ax in H; trivial; destruct H.\nrewrite sup_ax in H0; trivial; destruct H0.\nassert (xo : isOrd x).\n apply isOrd_inv with (f x0); auto.\ndestruct supf_dir with x0 x1; trivial.\ndestruct H4.\nexists (x ⊔ y).\n rewrite sup_ax; trivial.\n exists x2; trivial.\n apply osup2_lt; auto.\n\n split.\n  apply osup2_incl1; trivial.\n  apply osup2_incl2; trivial.\nQed.\n\n  Lemma isOrd_supf : isOrd (sup I f).\napply isOrd_intro; intros.\n elim isOrd_supf_elim with (1:=H1); intros.\n apply isOrd_supf_intro with x; trivial.\n apply isOrd_plump with b; auto.\n\n apply isDir_ord_sup.\n\n elim isOrd_supf_elim with (1:=H); intros.\n apply isOrd_inv with (f x); auto.\nQed.\n\nEnd OrdinalUpperBound.\n\n\n(********************************************************************)\n\nRequire Import ZFrepl.\n\nSection LimOrd.\n\n  Variable f : nat -> set.\n  Variable ford : forall n, isOrd (f n).\n  Variable fmono : forall m n, (m <= n)%nat -> f m ⊆ f n.\n\n  Let F x := uchoice (fun y => exists2 n, x == nat2set n & f n == y).\n\n  Let Fm : morph1 F.\ndo 2 red; intros.\napply uchoice_morph_raw.\nred; intros.\napply ex2_morph.\n red; intros.\n rewrite H; reflexivity.\n\n red; intros.\n rewrite H0; reflexivity.\nQed.\n\n  Let Fch : forall x, x ∈ N ->\n    uchoice_pred (fun y => exists2 n, x == nat2set n & f n == y).\nintros.\nsplit;[|split]; intros.\n revert H1; apply ex2_morph; red; intros; auto with *.\n rewrite H0; reflexivity.\n\n elim H using N_ind; intros.\n  revert H2; apply ex_morph.\n  red; intros.\n  apply ex2_morph; red; intros; auto with *.\n  rewrite H1; reflexivity.\n\n  exists (f 0); exists 0; simpl; auto with *.\n\n  destruct H1 as (y,(m,?,?)).\n  exists (f (S m)); exists (S m); simpl; auto with *.\n  apply succ_morph; trivial.\n\n destruct H0; destruct H1.\n rewrite <- H2; rewrite <- H3; rewrite H0 in H1; apply nat2set_inj in H1.\n rewrite H1; reflexivity.\nQed.\n\n  Definition ord_sup := sup N F.\n\n  Lemma isOrd_sup_intro : forall n, f n ⊆ ord_sup.\nunfold ord_sup.\nred; intros.\nrewrite sup_ax; trivial.\n2:do 2 red; intros; apply Fm; trivial.\nexists (nat2set n).\n apply nat2set_typ.\n\n destruct (uchoice_def _ (Fch _ (nat2set_typ n))).\n unfold F; rewrite <- H1.\n apply nat2set_inj in H0; rewrite <- H0; trivial.\nQed.\n\n  Lemma isOrd_sup_elim : forall x, x < ord_sup -> exists n, x < f n.\nunfold ord_sup; intros.\nrewrite sup_ax in H.\n2:do 2 red; intros; apply Fm; trivial.\ndestruct H.\ndestruct (uchoice_def _ (Fch _ H)).\nexists x1; rewrite H2; trivial.\nQed.\n\n  Lemma isOrd_sup : isOrd ord_sup.\napply isOrd_intro; intros.\n elim isOrd_sup_elim with (1:=H1); intros.\n apply isOrd_sup_intro with x.\n apply isOrd_plump with b; auto.\n\n red; intros.\n apply isOrd_sup_elim in H; destruct H.\n apply isOrd_sup_elim in H0; destruct H0.\n assert (xo : isOrd x).\n  apply isOrd_inv with (f x0); trivial.\n exists (x ⊔ y).\n  destruct (isOrd_dir _ (ford (x0+x1)) x y).\n   apply (fmono x0); auto with arith.\n   apply (fmono x1); auto with *.\n\n   destruct H2.\n   apply (isOrd_sup_intro (x0+x1)).\n   apply isOrd_plump with x2; auto.\n    apply isOrd_osup2; eauto using isOrd_inv.\n\n    apply osup2_lub; eauto using isOrd_inv.\n\n  split.\n   apply osup2_incl1; trivial.\n   apply osup2_incl2; trivial.\n\n elim isOrd_sup_elim with (1:=H); intros.\n apply isOrd_inv with (f x); trivial.\nQed.\n\n\n  Lemma ord_sup_typ X :\n    (forall n, f n ∈ X) ->\n    (forall g, morph1 g -> (forall n, n ∈ N -> g n ∈ X) -> sup N g ∈ X) ->\n    ord_sup ∈ X.\nunfold ord_sup.\nintros.\napply H0; trivial; intros.\ndestruct (uchoice_def _ (Fch _ H1)).\nunfold F; rewrite <- H3; trivial.\nQed.\n\nEnd LimOrd.\n\nLemma isOrd_union : forall x,\n  (forall y, y ∈ x -> isOrd y) ->\n  (forall a a', a ∈ x -> a' ∈ x -> exists2 b, b ∈ x & a ⊆ b /\\ a' ⊆ b) ->\n isOrd (union x).\nintros.\nrewrite union_is_sup.\napply isOrd_supf; auto.\ndo 2 red; trivial.\nQed.\n\nLemma isOrd_inter : forall x,\n  (forall y, y ∈ x -> isOrd y) -> isOrd (inter x).\nintros.\napply isOrd_intro; intros.\n apply inter_intro; trivial.\n  intros.\n  apply isOrd_plump with b; auto.\n  apply inter_elim with (1:=H2); trivial.\n\n  destruct inter_non_empty with (1:=H2); eauto.\n\n red; intros.\n destruct inter_non_empty with (1:=H0) as (w,?,?).\n assert (x0o : isOrd x0).\n  apply isOrd_inv with w; auto.\n exists (x0 ⊔ y).\n  apply inter_intro; intros; eauto.\n  apply osup2_lt; auto.\n   apply inter_elim with (1:=H0); trivial.\n   apply inter_elim with (1:=H1); trivial.\n\n  split.\n   apply osup2_incl1; trivial.\n   apply osup2_incl2; trivial.\n\n destruct inter_non_empty with (1:=H0).\n eauto using isOrd_inv.\nQed.\n\nFixpoint nat2ordset n :=\n  match n with\n  | 0 => zero\n  | S k => osucc (nat2ordset k)\n  end.\n\nLemma nat2ordset_typ : forall n, isOrd (nat2ordset n).\ninduction n; simpl; intros.\n apply isOrd_zero.\n apply isOrd_succ; trivial.\nQed.\nHint Resolve nat2ordset_typ.\n\n(** Ordinal omega *)\n\nDefinition omega := ord_sup nat2ordset.\n\nLemma isOrd_omega : isOrd omega.\napply isOrd_sup; trivial.\ninduction 1; intros; auto with *.\nsimpl.\ntransitivity (nat2ordset m0); trivial.\nred; intros.\napply isOrd_trans with (2:=H0); auto.\nQed.\nHint Resolve isOrd_omega.\n\nLemma zero_omega : lt zero omega.\napply isOrd_sup_intro with 1; simpl.\napply lt_osucc; trivial.\nQed.\nHint Resolve zero_omega.\n\nLemma osucc_omega : forall n, lt n omega -> lt (osucc n) omega.\nintros.\napply isOrd_sup_elim in H; destruct H.\napply isOrd_sup_intro with (S x); simpl.\napply lt_osucc_compat; auto.\nQed.\nHint Resolve osucc_omega.\n\nLemma omega_limit_ord : limitOrd omega.\nsplit; auto.\nQed.\nHint Resolve omega_limit_ord.\n\n(* f^w(o) *)\nDefinition iter_w (f:set->set) o :=\n  ord_sup(nat_rect(fun _=>set) o (fun _ => f)).\n\nLemma isOrd_iter_w : forall f o,\n  o ⊆ f o ->\n  (forall x y, isOrd x -> isOrd y -> x ⊆ y -> f x ⊆ f y) ->\n  (forall x, isOrd x -> isOrd (f x)) ->\n  isOrd o ->\n  isOrd (iter_w f o).\nintros.\nunfold iter_w.\napply isOrd_sup.\n induction n; simpl; intros; auto.\n\n induction m; simpl; intros.\n  revert o H H2; elim n; simpl; intros; auto with *.\n  transitivity (f o); trivial.\n  apply H0; auto.\n  elim n0; simpl; auto.\n\n  destruct n; simpl.\n   inversion H3.\n  apply H0; auto with arith.\n   elim m; simpl; auto.\n   elim n; simpl; auto.\nQed.\n\nDefinition plus_w := iter_w osucc.\n\n(** ** Indexed supremum of arbitrary family *)\n\nSection DirOrdinalSup.\n\n  Variable I : set.\n  Variable f : set -> set.\n  Hypothesis f_ext : ext_fun I f.\n  Hypothesis f_ord : forall x, x ∈ I -> isOrd (f x).\n\n  (** Taking the supremum pairwise *)\n  Definition osupf X := sup X (fun x => replf X (fun y => x ⊔ y)).\n  Definition osupfn n := nat_rect (fun _ => set) (sup I f) (fun _ => osupf) n.\n  (** Iterating ω times, we get a fixpoint *)\n  Definition osup := ord_sup osupfn.\n\n  Lemma osupf_def X z : z ∈ osupf X <-> exists2 x, x ∈ X & exists2 y, y ∈ X & z == x ⊔ y.\nunfold osupf; rewrite sup_ax.\n apply ex2_morph.\n  red; reflexivity.\n\n  red; intros.\n  rewrite replf_ax.\n   reflexivity.\n\n   do 2 red; intros; apply osup2_morph; auto with *.\n\n do 2 red; intros; apply replf_morph; auto with *.\n red; intros; apply osup2_morph; trivial.\nQed.\n\n  Lemma osupf_mono X Y :\n    X ⊆ Y ->\n    osupf X ⊆ osupf Y.\nred; intros.\nrewrite osupf_def in H0|-*.\ndestruct H0 as (x,?,(y,?,?)); exists x; auto.\nexists y; auto.\nQed.\n\n  Lemma osupfn_mono m n : (m <= n)%nat -> osupfn m ⊆ osupfn n.\nrevert n; induction m; simpl; intros.\n clear H; induction n; simpl; auto with *.\n apply osupf_mono in IHn.\n red; intros; apply IHn.\n rewrite osupf_def.\n exists z; trivial.\n exists z; trivial.\n symmetry; apply osup2_refl.\n rewrite sup_ax in H; trivial.\n destruct H.\n apply isOrd_inv with (f x); auto.\n\n destruct n; simpl.\n  inversion H.\n apply osupf_mono; apply IHm; auto with arith.\nQed.\n\n  Lemma osup_intro : forall x, x ∈ I -> f x ⊆ osup.\nred; intros.\nunfold osup.\napply isOrd_sup_intro with (n:=0); simpl.\nrewrite sup_ax; eauto.\nQed.\n\n  Lemma isOrd_osupfn : forall n x, x ∈ osupfn n -> isOrd x.\ninduction n; simpl; intros.\n rewrite sup_ax in H; trivial.\n destruct H; eauto using isOrd_inv.\n\n rewrite osupf_def in H.\n destruct H as (y,?,(y',?,?)).\n rewrite H1; apply isOrd_osup2; eauto using isOrd_inv.\nQed.\n\n  Lemma isOrd_osup : isOrd osup.\nunfold osup.\napply isOrd_intro; intros.\n apply isOrd_sup_elim in H1.\n destruct H1 as (n,?).\n apply isOrd_sup_intro with n.\n revert a b H H0 H1.\n induction n; simpl; intros.\n  rewrite sup_ax in H1|-*; trivial.\n  destruct H1.\n  exists x; trivial.\n  apply isOrd_plump with b; auto.\n\n  rewrite osupf_def in H1|-*.\n  destruct H1 as (x,?,(y,?,?)).\n  assert (xo : isOrd x).\n   apply isOrd_osupfn in H1; trivial.\n  assert (yo : isOrd y).\n   apply isOrd_osupfn in H2; trivial.\n  exists (a ∩ x).\n   apply IHn with x; trivial.\n    apply isOrd_inter2; trivial.\n\n    apply inter2_incl2.\n\n  exists (a ∩ y).\n   apply IHn with y; trivial.\n    apply isOrd_inter2; trivial.\n\n    apply inter2_incl2.\n\n   destruct osup2_proof with x y as (_,?); trivial.\n   rewrite <- H4; trivial.\n   apply eq_intro; intros.\n    rewrite inter2_def; split; trivial.\n    rewrite <- H3; auto.\n\n    rewrite inter2_def in H5; destruct H5; trivial.\n\n red; intros.\n apply isOrd_sup_elim in H; destruct H as (n,?).\n apply isOrd_sup_elim in H0; destruct H0 as (m,?).\n assert (xo : isOrd x).\n  apply isOrd_osupfn in H; trivial.\n assert (yo : isOrd y).\n   apply isOrd_osupfn in H0; trivial.\n exists (x ⊔ y).\n  apply isOrd_sup_intro with (S(n+m)); simpl.\n  rewrite osupf_def; exists x.\n   revert H; apply osupfn_mono; auto with arith.\n  exists y; auto with *.\n   revert H0; apply osupfn_mono; auto with arith.\n\n  split.\n   apply osup2_incl1; apply xo.\n   apply osup2_incl2; apply xo.\n\n apply isOrd_sup_elim in H; destruct H as (n,?).\n apply isOrd_osupfn in H; trivial.\nQed.\n\n  Lemma osup_lub z :\n    isOrd z ->\n    (forall x, x ∈ I -> f x ⊆ z) ->\n    osup ⊆ z.\nred; intros.\napply isOrd_sup_elim in H1; destruct H1 as (n,?).\nrevert z0 H1; induction n; simpl; intros.\n rewrite sup_ax in H1; trivial.\n destruct H1.\n revert H2; apply H0; trivial.\n\n rewrite osupf_def in H1; destruct H1 as (x,?,(y,?,?)).\n rewrite H3; apply osup2_lt; auto.\nQed.\n\n  Lemma osup_univ U :\n    (forall X F, ext_fun X F -> X ∈ U -> (forall x, x ∈ X -> F x ∈ U) -> \n     sup X F ∈ U) ->\n    (forall X x y, X ∈ U -> isOrd x -> x ∈ X -> y ∈ X -> singl (x ⊔ y) ∈ U) ->\n    N ∈ U ->\n    I ∈ U ->\n    (forall x, x ∈ I -> f x ∈ U) ->\n    osup ∈ U.\nintros.\nunfold osup.\napply ord_sup_typ; intros.\n induction n; simpl; intros; auto.\n unfold osupf.\n apply H; intros; trivial.\n  do 2 red; intros; apply replf_morph; auto with *.\n  red; intros; apply osup2_morph; auto.\n\n  intros.\n  rewrite replf_is_sup.\n  2:do 2 red; intros; apply osup2_morph; auto with *.\n  apply H; eauto.\n   do 2 red; intros; apply singl_morph; apply osup2_morph; auto with *.\n\n   intros.\n   apply H0 with (1:=IHn); trivial.\n   apply isOrd_osupfn in H4; auto.\n apply H; trivial.\n do 2 red; intros; apply H4; trivial.\nQed.\n\nEnd DirOrdinalSup.\n\nLemma isOrd_eq_osup : forall o, isOrd o -> o == osup o osucc.\nintros.\napply incl_eq.\n red; intros.\n apply osup_intro with (x:=z); trivial.\n  do 2 red; intros; apply osucc_morph; trivial.\n\n  apply lt_osucc; eauto using isOrd_inv.\n\n apply osup_lub; trivial.\n  do 2 red; intros; apply osucc_morph; trivial.\n\n  red; intros.\n  apply le_lt_trans with x; trivial.\nQed.\n\n  Lemma osup_morph : forall x x' f f',\n    x == x' -> eq_fun x f f' -> osup x f == osup x' f'.\nunfold osup, ord_sup; intros.\napply sup_morph; auto with *.\nred; intros.\napply uchoice_morph_raw.\nred; intros.\napply ex2_morph; red; intros.\n rewrite H2; reflexivity.\n\n assert (osupfn x f a == osupfn x' f' a).\n  induction a; simpl; intros.\n   apply sup_morph; auto.\n\n   apply incl_eq; apply osupf_mono; rewrite IHa; reflexivity.\n rewrite H4; rewrite H3; reflexivity.\nQed.\n\n(** * Projection toward ordinals *)\n\nDefinition toOrd (x : set) :=\n  osup (subset x isOrd) osucc.\n\nInstance toOrd_morph : morph1 toOrd.\ndo 2 red; intros.\nunfold toOrd.\napply osup_morph.\n apply subset_morph; auto with *.\n\n red; intros; rewrite H1; reflexivity.\nQed.\n\nLemma toOrd_isOrd : forall x, isOrd (toOrd x).\nintros.\nunfold toOrd.\napply isOrd_osup; intros.\n red; red; intros.\n rewrite H0; reflexivity.\n\n apply isOrd_succ.\n destruct subset_elim2 with (1:=H).\n rewrite H0; trivial.\nQed.\n\nLemma toOrd_ord : forall o, isOrd o -> toOrd o == o.\nintros.\nunfold toOrd.\napply incl_eq.\n apply osup_lub; trivial.\n  do 2 red; intros; apply osucc_morph; trivial.\n\n  intros.\n  red; intros.\n  assert (isOrd x).\n   apply subset_elim2 in H0; destruct H0.\n   rewrite H0; trivial.\n  apply subset_elim1 in H0.\n  apply isOrd_plump with x; eauto using isOrd_inv.\n  apply olts_le in H1; trivial.\n\n red; intros.\n assert (z ∈ osucc z).\n  apply lt_osucc.\n  apply isOrd_inv with o; trivial.\n revert H1; apply osup_intro.\n  do 2 red; intros; apply osucc_morph; auto.\n\n  apply subset_intro; trivial.\n  apply isOrd_inv with o; trivial.\nQed.\n", "meta": {"author": "barras", "repo": "cic-model", "sha": "dcc38f3104048aa50d230f819085131b16702d3d", "save_path": "github-repos/coq/barras-cic-model", "path": "github-repos/coq/barras-cic-model/cic-model-dcc38f3104048aa50d230f819085131b16702d3d/ZFord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.7047254101033853}}
{"text": "C02W82DBHV2R:~ i847419$ coqtop\nWelcome to Coq 8.8.0 (April 2018)\n\nCoq < Require Import Classical.\n\nCoq < Theorem exp020 : (forall P Q : Prop, ((P -> Q) -> (~~P -> Q))).\n1 subgoal\n  \n  ============================\n  forall P Q : Prop, (P -> Q) -> ~ ~ P -> Q\n\nexp020 < intros.\n1 subgoal\n  \n  P, Q : Prop\n  H : P -> Q\n  H0 : ~ ~ P\n  ============================\n  Q\n\nexp020 < tauto.\nNo more subgoals.\n\nexp020 < Qed.\nexp020 is defined\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/logic/misc/020.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642528975397, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7047162287736852}}
{"text": "(* Software Foundations *)\n(* Exercice 1 star, dictionary_invariant1 *)\n\nModule Dictionary.\nInductive natoption: Type :=\n|Some: nat -> natoption\n|None: natoption.\n\nInductive dictionary: Type :=\n|empty: dictionary\n|record: nat -> nat -> dictionary -> dictionary.\n\nDefinition insert(k v: nat)(d: dictionary): dictionary :=\n  (record k v d).\n\n\nFixpoint find(key: nat)(d: dictionary): natoption :=\nmatch d with\n|empty         => None\n|record k v d' => if (Nat.eqb key k) then Some v else find key d'\nend.\n\nLemma nat_eq_self: forall n: nat, Nat.eqb n n = true.\nProof.\n    intros. induction n as [|n'].\n    reflexivity.\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem dictionary_invariant1: forall (d: dictionary)(k v: nat),\n  find k (insert k v d) = Some v.\nProof.\n    intros. induction d as [|k' v' d'].\n    simpl. rewrite nat_eq_self. reflexivity.\n    simpl. rewrite nat_eq_self. reflexivity.\nQed.\n\nEnd Dictionary.\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter5_Library_List/dictionary_invariant1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7047162253983209}}
{"text": "(* fibonacci_numbers.v *)\n(* dIFP 2014-2015, Q1 *)\n(* Teacher: Olivier Danvy <danvy@cs.au.dk> *)\n\n(* Student name: ... *)\n(* Student number: ... *)\n\n(* ********** *)\n\n(* The goal of this project is to study\n   the Fibonacci function and\n   properties of Fibonacci numbers. *)\n\n(* ********** *)\n\nRequire Import Arith.\nRequire Import unfold_tactic.\n\nLemma unfold_plus_bc :\n  forall j : nat,\n    plus 0 j = j.\nProof.\n  unfold_tactic plus.\nQed.\n\nLemma unfold_plus_ic :\n  forall i' j : nat,\n    plus (S i') j = S (plus i' j).\nProof.\n  unfold_tactic plus.\nQed.\n\nProposition plus_1_S :\n  forall n : nat,\n    S n = plus 1 n.\nProof.\n  intro n.\n  induction n as [ | n' IHn'].\n    rewrite -> (plus_0_r 1).\n    reflexivity.\n    \n    rewrite -> (unfold_plus_ic).\n    rewrite -> (plus_0_l (S n')).\n    reflexivity.\nQed.\n\n\n\nLemma nat_ind2 :\n  forall P : nat -> Prop,\n    P 0 ->\n    P 1 ->\n    (forall i : nat,\n      P i -> P (S i) -> P (S (S i))) ->\n    forall n : nat,\n      P n.\nProof.\n  intros P H_P0 H_P1 H_PSS n.\n  assert(consecutive :\n           forall x : nat,\n             P x /\\ P (S x)).\n    intro x.\n    induction x as [ | x' [IHx' IHSx']].\n      split.\n        exact H_P0.\n      exact H_P1.\n\n      split.\n        exact IHSx'.\n      exact (H_PSS x' IHx' IHSx').\n\n      destruct (consecutive n) as [ly _].\n\n      exact ly.\nQed.\n\n\n\nDefinition square (x : nat) : nat :=\n  x * x.\n\n(* ********** *)\n\n(* You are given the two following specifications\n   of the Fibonacci function:\n*)\n\nDefinition specification_of_fibonacci (fib : nat -> nat) :=\n  fib 0 = 0\n  /\\\n  fib 1 = 1\n  /\\\n  forall n'' : nat,\n    fib (S (S n'')) = fib (S n'') + fib n''.\n\nDefinition specification_of_fibonacci_alt (fib : nat -> nat) :=\n  fib 0 = 0\n  /\\\n  fib 1 = 1\n  /\\\n  fib 2 = 1\n  /\\\n  forall p q : nat,\n    fib (S (p + q)) =\n    fib (S p) * fib (S q) + fib p * fib q.\n\n(* Prove that each of these specifications\n   specifies a unique function.   \n*)\n\nLemma specification_of_fibonacci_is_unique :\n  forall (f g : nat -> nat),\n    specification_of_fibonacci f ->\n    specification_of_fibonacci g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_fibonacci.\n  intros [f0 [f1 fn]] [g0 [g1 gn]].\n  intro n.\n  \n  induction n as [ | | n' IHn' IHSn'] using nat_ind2.\n\n  rewrite -> f0.\n  rewrite -> g0.\n  reflexivity.\n\n  rewrite -> f1.\n  rewrite -> g1.\n  reflexivity.\n\n  rewrite -> fn.\n  rewrite -> gn.\n  rewrite -> IHn'.\n  rewrite -> IHSn'.\n  reflexivity.\nQed.\n\nLemma specification_of_fibonacci_alt_is_unique :\n  forall (f g : nat -> nat),\n    specification_of_fibonacci_alt f ->\n    specification_of_fibonacci_alt g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_fibonacci_alt.\n  intros [f0 [f1 [f2 fn]]] [g0 [g1 [g2 gn]]].\n  intro n.\n  \n  induction n as [ | | n' IHn' IHSn'] using nat_ind2.\n\n  rewrite -> f0.\n  rewrite -> g0.\n  reflexivity.\n\n  rewrite -> f1.\n  rewrite -> g1.\n  reflexivity.\n\n  rewrite -> (plus_1_S).\n  rewrite <- (plus_n_Sm).\n  rewrite -> fn.\n  rewrite -> gn.\n  rewrite -> IHn'.\n  rewrite -> IHSn'.\n  rewrite -> f2.\n  rewrite -> f1.\n  rewrite -> g2.\n  rewrite -> g1.\n  reflexivity.\nQed.\n\n\n\n(* If we removed the clause \"fib 2 = 1\" in\n   specification_of_fibonacci_alt,\n   would the specification still specify a unique function?\n*)\n\nDefinition specification_of_fibonacci_alt_alt (fib : nat -> nat) :=\n  fib 0 = 0\n  /\\\n  fib 1 = 1\n  /\\\n  forall p q : nat,\n    fib (S (p + q)) =\n    fib (S p) * fib (S q) + fib p * fib q.\n\n\nLemma specification_of_fibonacci_alt_alt_is_unique :\n  forall (f g : nat -> nat),\n    specification_of_fibonacci_alt_alt f ->\n    specification_of_fibonacci_alt_alt g ->\n    forall n : nat,\n      f n = g n.\nProof.\n  intros f g.\n  unfold specification_of_fibonacci_alt_alt.\n  intros [f0 [f1 fn]] [g0 [g1 gn]].\n  intro n.\n  \n  induction n as [ | | n' IHn' IHSn'] using nat_ind2.\n\n  rewrite -> f0.\n  rewrite -> g0.\n  reflexivity.\n\n  rewrite -> f1.\n  rewrite -> g1.\n  reflexivity.\n\n  rewrite <- (plus_0_r (S n')).\n  rewrite -> fn.\n  rewrite -> gn.\n\n  Abort.\n(* Hvordan skriver vi det i bevis at det ikke findes? *)\n\n\n\n(*\n   Show that these specifications are equivalent,\n   i.e., prove the following proposition:\n*)\n\nProposition equivalence_of_the_specifications_of_fibonacci:\n  forall fib: nat -> nat,\n    specification_of_fibonacci fib\n    <->\n    specification_of_fibonacci_alt fib.\n\n(* Suppose that you have only proved\n   that one of the two specifications is unique.\n   Deduce that the other specification is also unique (i.e.,\n   do not prove it from scratch: prove that it is a consequence\n   of the uniqueness of the first specification).\n*)\n\n(* ********** *)\n\n(* Given either of the specifications\n   of the Fibonacci function above,\n   prove the following propositions:\n*)\n\nProposition about_fibonacci_numbers_whose_index_is_even :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      fib (2 * (S n)) + square (fib n) =\n      square (fib (S (S n))).\nProof.\n  intro fib.\n  unfold specification_of_fibonacci.\n  intros [f0 [f1 fn]].\n  intro n.\n  \n  induction n as [ | | n' IHn' IHSn'] using nat_ind2.\n  rewrite -> (mult_1_r).\n  rewrite -> f0.\n  rewrite -> fn.\n  rewrite -> f0.\n  rewrite ->2 (plus_0_r).\n  unfold square.\n  rewrite -> f1.\n  rewrite -> (mult_1_r).\n  reflexivity.\n\n  rewrite -> f1.\n  rewrite -> (fn 1).\n  rewrite -> (mult_succ_r 2).\n  rewrite -> (mult_1_r).\n  rewrite -> (plus_1_S 1) at 2.\n  rewrite -> (plus_assoc 2 1 1).\n  rewrite <- (plus_n_Sm 2 0).\n  rewrite -> (plus_0_r).\n  rewrite <- (plus_n_Sm 3 0).\n  rewrite -> (plus_0_r).\n  rewrite -> (fn 2).\n  rewrite -> (fn 1).\n  rewrite -> f1.\n  rewrite  -> (fn 0).\n  rewrite -> f1.\n  rewrite -> f0.\nAbort.\n\nProposition d_Occagne_s_identity :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      fib (2 * (S n)) = fib (S n) * (fib (S (S n)) + fib n).\nProof.\n  intro fib.\n  unfold specification_of_fibonacci.\n  intros [f0 [f1 fn]].\n  intro n.\n  \n  induction n as [ | | n' IHn' IHSn'] using nat_ind2.\n  rewrite -> (mult_1_r).\n  rewrite -> f1.\n  rewrite -> f0.\n  rewrite -> (plus_0_r).\n  rewrite -> (mult_1_l).\n  reflexivity.\n\n  \n\n\n\nAbort.\n\nProposition Cassini_s_identity_for_even_numbers :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      square (fib (S (2 * n))) =\n      S ((fib (2 * (S n))) * (fib (2 * n))).\nProof.\nAbort.\n\nProposition Cassini_s_identity_for_odd_numbers :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      S (square (fib (2 * (S n)))) =\n      (fib (S (2 * (S n)))) * (fib (S (2 * n))).\nProof.\nAbort.\n\n(* ********** *)\n\n(* Here is the sum function from Week 37: *)\n\nFixpoint sum_ds (f : nat -> nat) (n : nat) : nat :=\n  match n with\n  | 0 => f 0\n  | S n' => sum_ds f n' + f n\n  end.\n\nDefinition sum  (f : nat -> nat) (n : nat) : nat :=\n  sum_ds f n.\n\n(* ********** *)\n\n(* Given either of the specifications\n   of the Fibonacci function above,\n   prove the following propositions:\n*)\n\nProposition sum_of_the_first_fibonacci_numbers :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      S (sum fib n) = fib (S (S n)).\nProof.\nAbort.\n\nProposition sum_of_the_first_fibonacci_numbers_whose_index_is_even :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      S (sum (fun i => fib (2 * i)) n) = fib (S (2 * n)).\nProof.\nAbort.\n\nProposition sum_of_the_first_fibonacci_numbers_whose_index_is_odd :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      sum (fun i => fib (S (2 * i))) n = fib (2 * (S n)).\nProof.\nAbort.\n\nProposition sum_of_the_squares_of_the_first_fibonacci_numbers :\n  forall fib : nat -> nat,\n    specification_of_fibonacci fib ->\n    forall n : nat,\n      sum (fun i => square (fib i)) n = fib n * fib (S n).\nProof.\nAbort.\n\n(* ********** *)\n\n(* end of fibonacci_numbers.v *)\n", "meta": {"author": "madsravn", "repo": "dcoq", "sha": "e6e840c60d97fc12f3ad08caa81765c21785af06", "save_path": "github-repos/coq/madsravn-dcoq", "path": "github-repos/coq/madsravn-dcoq/dcoq-e6e840c60d97fc12f3ad08caa81765c21785af06/difp/term-projects/fibonacci_numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7046598555581549}}
{"text": "(* Copyright (C) 2005-2008 Sebastien Briais *)\n(* http://lamp.epfl.ch/~sbriais/ *)\n\n(* This library is free software; you can redistribute it and/or modify *)\n(* it under the terms of the GNU Lesser General Public License as *)\n(* published by the Free Software Foundation; either version 2.1 of the *)\n(* License, or (at your option) any later version. *)\n\n(* This library is distributed in the hope that it will be useful, but *)\n(* WITHOUT ANY WARRANTY; without even the implied warranty of *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU *)\n(* Lesser General Public License for more details. *)\n\n(* You should have received a copy of the GNU Lesser General Public *)\n(* License along with this library; if not, write to the Free Software *)\n(* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA *)\n\n(** First, we show the following theorem: *)\n(** if p is a prime number and gcd(p,k)=1 then sqrt(p*k) is not rational *)\n\n(** Then, we strengthen the result to the n-th root of p^r*k *)\n(** where 0 < r < n obtaining the theorem: *)\n(**  if p is a prime number, gcd(p,k)=1 and 0 < r < n then the n-th root of p^r*k is not rational *)\n\nRequire Import missing.\nRequire Import division.\nRequire Import gcd.\nRequire Import primes.\nRequire Import power.\n\nUnset Standard Proposition Elimination Names.\n\n(** now, we show the result claimed in the header *)\nLemma sqrt_prime_irrat_aux : forall (p k a b:nat),(is_prime p)->(rel_prime p k)->(rel_prime a b)->(p*k*(square b) <> (square a)).\n  intros.\n  intro.\n  assert (divides a p).\n  apply prime_square;trivial.\n  exists (k*(square b)).\n  rewrite <- H2;ring.\n  elim H3;intro n_a;intro.\n  rewrite H4 in H2;rewrite square_mult_lemma in H2;unfold square in H2.\n  assert (k*(b*b)=p*(n_a*n_a)).\n  apply mult_lemma6 with p.\n  intro H5;rewrite H5 in H;apply not_prime_zero;trivial.\n  rewrite mult_assoc;rewrite H2;ring.\n  assert (divides b p).\n  apply prime_square;trivial;unfold square.\n  apply gauss with k.\n  apply rel_prime_sym;trivial.\n  exists (n_a*n_a);trivial.\n  assert (p=1).\n  unfold rel_prime in H1.\n  elim H1;intros.\n  apply divides_antisym;try (apply one_min_div).\n  apply H8;red;tauto.\n  elim H;tauto.\nQed.\n\n(** Theorem: if p is prime, p and k are relatively prime, then sqrt(p*k) is not rationnal *)\nTheorem sqrt_prime_irrat : forall (p k a b:nat),(is_prime p)->(rel_prime p k)->(b<>O)->(p*k*(square b) <> (square a)).\n  intros.\n  generalize (gcd_is_gcd a b);intro.\n  generalize (quo_is_quo a (gcd a b) (gcd_div_l (gcd a b) a b H2));intro.\n  generalize (quo_is_quo b (gcd a b) (gcd_div_r (gcd a b) a b H2));intro.\n  intro.\n  rewrite H3 in H5.\n  replace (square b) with (square (gcd a b * quo b (gcd a b) (gcd_div_r (gcd a b) a b H2))) in H5;auto.\n  rewrite square_mult_lemma in H5;rewrite square_mult_lemma in H5.\n  assert (p*k*(square (quo b (gcd a b) (gcd_div_r (gcd a b) a b H2)))=(square (quo a (gcd a b) (gcd_div_l (gcd a b) a b H2)))).\n  apply mult_lemma6 with (square (gcd a b)).\n  unfold square.\n  generalize (gcd_non_zero (gcd a b) a b H1 H2);intro.\n  intro;apply H6.\n  case (mult_lemma2 (gcd a b) (gcd a b) H7);trivial.\n  rewrite <- H5;ring.\n  apply (sqrt_prime_irrat_aux p k (quo a (gcd a b) (gcd_div_l (gcd a b) a b H2)) (quo b (gcd a b) (gcd_div_r (gcd a b) a b H2)));auto.\n  apply gcd_rel_prime;apply (gcd_non_zero (gcd a b) a b);trivial.\nQed.\n\n(** if p is prime then sqrt(p) is not rationnal *)\nFact sqrt_prime : forall (p:nat),(is_prime p)->forall (a b:nat),(b<>O)->(p*(square b)<>(square a)).\n  intros.\n  replace p with (p*1);try (auto with arith).\n  apply sqrt_prime_irrat;trivial;apply rel_prime_1.\nQed.\n\n(** We now deduce from this theorem that sqrt(2) is not rationnal *)\n(** here is it! *)\nFact sqrt_2_irrat : forall (p q:nat),(q<>O)->(2*(square q)<>(square p)).\n  intros.\n  apply sqrt_prime;trivial.\n  apply is_prime_2.\nQed.\n\n(** generalisation *)\nLemma nth_root_irrat_aux : forall (p k a b n r:nat),(is_prime p)->(rel_prime p k)->(0<r)->(r<n)->(rel_prime a b)->((power p r)*k*(power b n) <> (power a n)).\n  intros.\n  intro.\n  assert (divides a p).\n  apply prime_power with n;trivial.\n  generalize (power_divides_lemma1 r p H1);intro.\n  elim H5;intro q;intros.\n  rewrite H6 in H4.\n  rewrite <- H4;exists (q*k*(power b n));ring.\n  assert (divides b p).\n  elim H5;intro q;intros.\n  rewrite H6 in H4.\n  rewrite power_mult_lemma1 in H4.\n  assert ((power p n)=(power p (r+(n-r)))).\n  rewrite <- le_plus_minus;try (auto with arith).\n  rewrite H7 in H4;rewrite power_plus_lemma1 in H4.\n  assert ((power p r)<>O).\n  intro.\n  apply not_prime_zero.\n  assert (p=O).\n  apply power_zero with r;trivial.\n  rewrite H9 in H;trivial.\n  rewrite <- mult_assoc in H4;rewrite <- mult_assoc in H4;generalize (mult_lemma6 (k*(power b n)) ((power p (n-r))*(power q n)) (power p r) H8 H4);intro.\n  assert (divides (power p (n-r)) p).\n  apply power_divides_lemma1;apply minus_lt_lemma1;trivial.\n  apply prime_power with n;trivial.\n  apply gauss with k;try (apply rel_prime_sym;trivial).\n  rewrite H9;apply divides_mult;trivial.\n  elim H3;intros.\n  elim H;intros.\n  apply H9;apply divides_antisym;try (apply one_min_div).\n  apply H8;red;tauto.\nQed.\n\n(** generalization of the theorem: if p is a prime number, 0 < r < n and gcd(p,k)=1 then the n-th root of p^r*k is not rationnal! *)\nTheorem nth_root_irrat : forall (p k a b n r:nat),(is_prime p)->(rel_prime p k)->(0<r)->(r<n)->(b<>0)->((power p r)*k*(power b n) <> (power a n)).\n  intros.\n  intro.\n  generalize (gcd_is_gcd a b);intro.\n  generalize (quo_is_quo a (gcd a b) (gcd_div_l (gcd a b) a b H5));intro.\n  generalize (quo_is_quo b (gcd a b) (gcd_div_r (gcd a b) a b H5));intro.\n  assert ((power a n)=(power (gcd a b * quo a (gcd a b) (gcd_div_l (gcd a b) a b H5)) n));try (rewrite <- H6;trivial).\n  assert ((power b n)=(power (gcd a b * quo b (gcd a b) (gcd_div_r (gcd a b) a b H5)) n));try (rewrite <- H7;trivial).\n  rewrite power_mult_lemma1 in H8;rewrite H8 in H4.\n  rewrite power_mult_lemma1 in H9;rewrite H9 in H4.\n  rewrite mult_lemma7 in H4.\n  assert ((power (gcd a b) n)<>O).\n  intro.\n  generalize (power_zero n (gcd a b) H10);intro.\n  apply (gcd_non_zero (gcd a b) a b);trivial.\n  generalize (mult_lemma6 (power p r * k * power (quo b (gcd a b) (gcd_div_r (gcd a b) a b H5)) n) (power (quo a (gcd a b) (gcd_div_l (gcd a b) a b H5)) n) (power (gcd a b) n) H10 H4).\n  fold ((power p r * k * power (quo b (gcd a b) (gcd_div_r (gcd a b) a b H5)) n)<>(power (quo a (gcd a b) (gcd_div_l (gcd a b) a b H5)) n)).\n  apply nth_root_irrat_aux;trivial.\n  apply gcd_rel_prime;apply (gcd_non_zero (gcd a b) a b);trivial.\nQed.\n\n(** Generalization of the previous theorem *)\nTheorem nth_root_irrational : forall (p k a b n q r:nat),(is_prime p)->(rel_prime p k)->(0<r)->(r<n)->(b<>0)->((power p (q*n+r))*k*(power b n) <> (power a n)).\n  intros.\n  intro.\n  rewrite power_plus_lemma1 in H4.\n  assert (divides a (power p q)).\n  apply prime_power_qn with n;try (auto with arith);try omega.\n  exists ((power p r)*k*(power b n)).\n  rewrite <- H4;ring.\n  assert (0<n);try omega.\n  elim H5;intro a';intro.\n  rewrite H7 in H4.\n  rewrite power_mult_lemma1 in H4;rewrite power_power_lemma1 in H4.\n  assert ((power p (q*n))<>0).\n  intro;apply not_prime_zero;generalize (power_zero (q*n) p H8);intro;rewrite H9 in H;trivial.\n  rewrite <- (mult_assoc (power p (q*n))) in H4;rewrite <- (mult_assoc (power p (q*n))) in H4.\n  generalize (mult_lemma6 (power p r*k*power b n) (power a' n) (power p (q*n)) H8 H4).\n  fold (power p r * k * power b n <> power a' n).\n  apply nth_root_irrat;trivial.\nQed.\n\n(** let x and n be two numbers such that n > 0, then either the n-th root of x is a natural number of it is not rationnal *)\nTheorem nth_root : forall (x n:nat),(n>0)->{y:nat | x=(power y n)}+{forall (a b:nat),(b<>0)->x*(power b n)<>(power a n)}.\n  intros.\n  case (is_power_m_dec x n H);intro;try tauto.\n  elim s;intro p;intro.\n  elim p0;intro q;intro.\n  elim p1;intro r;intro.\n  elim p2;intro k;intro.\n  right;intros.\n  assert (x=(power p (q*n+r))*k);try tauto.\n  rewrite H1;apply nth_root_irrational;tauto.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "fundamental-arithmetics", "sha": "8976d4ba6a5c53b7eb25d08921e592d200189431", "save_path": "github-repos/coq/coq-contribs-fundamental-arithmetics", "path": "github-repos/coq/coq-contribs-fundamental-arithmetics/fundamental-arithmetics-8976d4ba6a5c53b7eb25d08921e592d200189431/nthroot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7046598550458442}}
{"text": "Require Import Problem PeanoNat List Omega Permutation.\nImport ListNotations.\n\nFixpoint sorted (xs : list nat) :=\n  match xs with\n  | nil => True\n  | x :: ys =>\n    match ys with\n    | nil => True\n    | y :: zs => x <= y /\\ sorted ys\n    end\n  end.\n\nDefinition all (P : nat -> Prop) (xs : list nat) := fold_right and True (map P xs).\nDefinition upper_bound (n : nat) := all (fun x => x <= n).\nDefinition lower_bound (n : nat) := all (fun x => n <= x).\n\nLemma len_0_nil (xs : list nat) : length xs <= 0 -> xs = nil.\nProof.\n  intros; apply length_zero_iff_nil; omega.\nQed.\n\nLemma perm_dig : forall x xs ys, Permutation (A:=nat) (x :: xs) ys -> exists zs ws, ys = zs ++ x :: ws.\nProof.\n  intros.\n  assert (In x ys) by (refine (Permutation_in _ H _); simpl; auto); clear H.\n  induction ys; [inversion H0|].\n  simpl in H0.\n  destruct H0; [subst a; exists nil; exists ys; auto|].\n  apply IHys in H; clear IHys.\n  destruct H; destruct H.\n  exists (a :: x0); exists x1.\n  subst ys.\n  auto.\nQed.\n\nLemma perm_all : forall P xs, all P xs -> forall ys, Permutation xs ys -> all P ys.\nProof.\n  induction xs; intros.\n  - apply Permutation_nil in H0.\n    subst ys; simpl; auto.\n  - unfold all in H; simpl in H; fold (all P xs) in H.\n    destruct H.\n    specialize (IHxs H1); clear H1.\n    destruct (perm_dig a xs ys H0); destruct H1.\n    subst ys.\n    specialize (Permutation_middle x x0 a); intro.\n    apply Permutation_sym in H1.\n    apply (Permutation_trans H0) in H1; clear H0.\n    apply Permutation_cons_inv in H1.\n    apply IHxs in H1; clear IHxs.\n    induction x; [simpl in H1; split; auto|].\n    destruct H1.\n    split; [|apply IHx]; auto.\nQed.\n\nLemma perm_upper : forall n xs, upper_bound n xs -> forall ys, Permutation xs ys -> upper_bound n ys.\nProof.\n  intro; apply (perm_all _).\nQed.\n\nLemma perm_lower : forall n xs, lower_bound n xs -> forall ys, Permutation xs ys -> lower_bound n ys.\nProof.\n  intro; apply (perm_all _).\nQed.\n\nLemma sorted_tail : forall x xs, sorted (x :: xs) -> sorted xs.\nProof.\n  destruct xs; [auto|].\n  intro H; destruct H.\n  auto.\nQed.\n\nLemma sorted_app : forall xs n ys, upper_bound n xs -> lower_bound n ys ->\n                                   sorted xs -> sorted ys -> sorted (xs ++ [n] ++ ys).\nProof.\n  intros.\n  induction xs; simpl.\n  - destruct ys; [auto|].\n    destruct H0; split; auto.\n  - destruct H.\n    destruct xs.\n    * simpl.\n      clear H3 H1; simpl in IHxs; specialize (IHxs I I).\n      split; auto.\n    * simpl; simpl in IHxs; simpl in H1.\n      destruct H1.\n      split; [auto|].\n      fold (all (fun x : nat => x <= n) (n0 :: xs)) in H3.\n      fold (upper_bound n (n0 :: xs)) in H3.\n      apply IHxs; auto.\nQed.\n\nLemma filter_short (k : nat) (xs : list nat)\n  : length xs <= k -> forall P, length (filter P xs) <= k.\nProof.\n  intros.\n  refine (Nat.le_trans _ _ _ _ H); clear k H.\n  induction xs; simpl; [auto|].\n  destruct (P a); simpl; omega.\nQed.\n\nLemma filter_split (P Q : nat -> bool) : (forall x, P x = negb (Q x)) -> forall xs, Permutation xs (filter P xs ++ filter Q xs).\nProof.\n  intros.\n  induction xs; simpl; [constructor|].\n  rewrite H.\n  destruct (Q a); simpl; [|apply perm_skip; auto].\n  apply (perm_skip a) in IHxs.\n  refine (Permutation_trans IHxs _).\n  apply Permutation_middle.\nQed.\n\nDefinition lt_n (n : nat) := fun x => x <? n.\nDefinition ge_n (n : nat) := fun x => n <=? x.\nDefinition le_n (n : nat) := fun x => x <=? n.\nDefinition gt_n (n : nat) := fun x => n <? x.\n\nLemma boundary : forall n xs, upper_bound n (filter (lt_n n) xs) /\\\n                              upper_bound n (filter (le_n n) xs) /\\\n                              lower_bound n (filter (gt_n n) xs) /\\\n                              lower_bound n (filter (ge_n n) xs).\nProof.\n  unfold upper_bound; unfold lower_bound; unfold all.\n  unfold lt_n; unfold le_n; unfold gt_n; unfold ge_n.\n  induction xs; simpl; [auto|].\n  destruct IHxs; destruct H0; destruct H1.\n  assert (C: a = n \\/ a > n \\/ a < n) by omega.\n  destruct C; [subst|destruct H3;repeat rewrite Nat.ltb_antisym]; simpl.\n  rewrite Nat.ltb_irrefl; rewrite Nat.leb_refl; simpl.\n  repeat split; auto.\n  all: repeat rewrite (proj2 (Nat.leb_gt _ _) H3).\n  all: repeat rewrite (proj2 (Nat.leb_le _ _) (Nat.lt_le_incl _ _ H3)).\n  all: simpl; repeat split; auto; omega.\nQed.\n\nLemma sort_mid : forall x ys z ws, sorted (x :: ys ++ z :: ws) -> x <= z.\nProof.\n  induction ys; intros; destruct H; [auto|].\n  destruct ys; [destruct H0; omega|].\n  refine (IHys _ ws _); clear IHys.\n  destruct H0.\n  split; [omega|auto].\nQed.\n\nLemma qs1_inj : forall xs ys, quicksort1 xs ys -> quicksort1 xs ys \\/ quicksort2 xs ys.\nProof.\n  auto.\nQed.\n\nLemma qs2_inj : forall xs ys, quicksort2 xs ys -> quicksort1 xs ys \\/ quicksort2 xs ys.\nProof.\n  auto.\nQed.\n\nLemma qs1_split : forall n xs, Permutation xs (filter (lt_n n) xs ++ filter (ge_n n) xs).\nProof.\n  intros.\n  apply filter_split.\n  apply Nat.ltb_antisym.\nQed.\n\nLemma qs2_split : forall n xs, Permutation xs (filter (le_n n) xs ++ filter (gt_n n) xs).\nProof.\n  intros.\n  apply filter_split.\n  apply Nat.leb_antisym.\nQed.\n\nLemma qs_perm : forall xs ys, quicksort1 xs ys \\/ quicksort2 xs ys -> Permutation xs ys.\nProof.\n  intro; remember (length xs) as k.\n  assert (length xs <= k) by omega; clear Heqk.\n  revert xs H.\n  induction k; intros.\n  - apply len_0_nil in H; subst xs.\n    destruct H0; inversion_clear H; auto.\n  - destruct xs; [destruct H0; inversion_clear H0; auto|].\n    simpl in H; assert (length xs <= k) by omega; clear H.\n    destruct H0; inversion_clear H.\n    all: refine (Permutation_trans _ (Permutation_middle _ _ _)).\n    all: apply perm_skip.\n    1: refine (Permutation_trans (qs1_split n xs) _).\n    2: refine (Permutation_trans (qs2_split n xs) _).\n    all: refine (Permutation_app _ _).\n    all: apply IHk; [apply filter_short|]; auto.\nQed.\n\nLemma qs1_perm : forall xs ys, quicksort1 xs ys -> Permutation xs ys.\nProof.\n  intros; apply qs_perm; auto.\nQed.\n\nLemma qs2_perm : forall xs ys, quicksort2 xs ys -> Permutation xs ys.\nProof.\n  intros; apply qs_perm; auto.\nQed.\n\nLemma qs_sorted : forall xs ys, quicksort1 xs ys \\/ quicksort2 xs ys -> sorted ys.\nProof.\n  intro.\n  remember (length xs) as k.\n  assert (length xs <= k) by omega; clear Heqk.\n  revert xs H.\n  induction k; intros.\n  - apply len_0_nil in H; subst xs.\n    destruct H0; inversion_clear H; simpl; auto.\n  - destruct xs; [destruct H0; inversion_clear H0; simpl; auto|].\n    simpl in H; assert (length xs <= k) by omega; clear H.\n    destruct H0; inversion_clear H; apply sorted_app.\n    all: try clear l H0; try clear r H2.\n    all: try rename l into zs; try rename H0 into H.\n    all: try rename r into zs; try rename H2 into H.\n    1,2: apply qs1_perm in H.\n    5,6: apply qs2_perm in H.\n    1,5: apply (perm_upper n) in H; [auto|].\n    3,6: apply (perm_lower n) in H; [auto|].\n    1-4: apply boundary.\n    all: try apply qs1_inj in H; try apply qs2_inj in H.\n    all: apply IHk in H; [auto|].\n    all: apply filter_short; auto.\nQed.\n\nLemma low_head : forall x xs, sorted (x :: xs) -> lower_bound x (x :: xs).\nProof.\n  unfold lower_bound; unfold all.\n  induction xs; simpl; [auto|].\n  intro H; destruct H.\n  split; [auto|split;[auto|]].\n  apply IHxs; clear IHxs.\n  destruct xs; simpl; [auto|].\n  split; [omega|destruct H0; auto].\nQed.\n\nLemma sort_uniq : forall xs ys, Permutation xs ys -> sorted xs -> sorted ys -> xs = ys.\nProof.\n  induction xs; simpl; intros; [apply Permutation_nil in H; auto|].\n  destruct (perm_dig a _ _ H); destruct H2.\n  subst ys.\n  destruct x.\n  - simpl in H; apply Permutation_cons_inv in H.\n    apply sorted_tail in H0.\n    apply sorted_tail in H1.\n    simpl; f_equal.\n    apply IHxs; auto.\n  - assert (a <= n).\n    * specialize (low_head _ _ H0); intro.\n      destruct (perm_lower _ _ H2 _ H); auto.\n    * rewrite <- app_comm_cons in H1.\n      assert (n <= a) by (apply sort_mid in H1; auto).\n      assert (n = a) by omega; clear H2 H3.\n      subst n; simpl; f_equal.\n      apply sorted_tail in H0.\n      apply sorted_tail in H1.\n      simpl in H; apply Permutation_cons_inv in H.\n      apply IHxs; auto.\nQed.\n\nTheorem solution : task.\nProof.\n  unfold task.\n  intros.\n  apply sort_uniq.\n  - apply qs1_perm in H.\n    apply qs2_perm in H0.\n    apply Permutation_sym in H.\n    apply (Permutation_trans H H0).\n  - apply (qs_sorted x); auto.\n  - apply (qs_sorted x); auto.\nQed.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/008/Solution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.704659851523028}}
{"text": "Require Import Setoid.\n\nInductive mynat := z : mynat | s : mynat -> mynat.\n\nParameter E : mynat -> mynat -> Prop.\nAxiom E_equiv : equiv mynat E.\n\nAdd Relation mynat E\n reflexivity proved by (proj1 E_equiv)\n symmetry proved by (proj2 (proj2 E_equiv))\n transitivity proved by (proj1 (proj2 E_equiv))\nas E_rel.\n\nNotation \"x == y\" := (E x y) (at level 70).\n\nGoal z == s z -> s z == z. intros H. setoid_rewrite H at 2. reflexivity. Qed.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/test-suite/bugs/closed/shouldsucceed/1696.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152282, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.7046381121020927}}
{"text": "(** * MoreInd: More on Induction *)\n\nRequire Export \"ProofObjects\".\n\n(* ##################################################### *)\n(** * Induction Principles *)\n\n(** This is a good point to pause and take a deeper look at induction\n    principles. \n\n    Every time we declare a new [Inductive] datatype, Coq\n    automatically generates and proves an _induction principle_ \n    for this type.\n\n    The induction principle for a type [t] is called [t_ind].  Here is\n    the one for natural numbers: *)\n\nCheck nat_ind.\n(*  ===> nat_ind : \n           forall P : nat -> Prop,\n              P 0  ->\n              (forall n : nat, P n -> P (S n))  ->\n              forall n : nat, P n  *)\n\n(** *** *)\n(** The [induction] tactic is a straightforward wrapper that, at\n    its core, simply performs [apply t_ind].  To see this more\n    clearly, let's experiment a little with using [apply nat_ind]\n    directly, instead of the [induction] tactic, to carry out some\n    proofs.  Here, for example, is an alternate proof of a theorem\n    that we saw in the [Basics] chapter. *)\n\nTheorem mult_0_r' : forall n:nat, \n  n * 0 = 0.\nProof.\n  apply nat_ind. \n  Case \"O\". reflexivity.\n  Case \"S\". simpl. intros n IHn. rewrite -> IHn. \n    reflexivity.  Qed.\n\n\n(** This proof is basically the same as the earlier one, but a\n    few minor differences are worth noting.  First, in the induction\n    step of the proof (the [\"S\"] case), we have to do a little\n    bookkeeping manually (the [intros]) that [induction] does\n    automatically.\n\n    Second, we do not introduce [n] into the context before applying\n    [nat_ind] -- the conclusion of [nat_ind] is a quantified formula,\n    and [apply] needs this conclusion to exactly match the shape of\n    the goal state, including the quantifier.  The [induction] tactic\n    works either with a variable in the context or a quantified\n    variable in the goal.\n\n    Third, the [apply] tactic automatically chooses variable names for\n    us (in the second subgoal, here), whereas [induction] lets us\n    specify (with the [as...]  clause) what names should be used.  The\n    automatic choice is actually a little unfortunate, since it\n    re-uses the name [n] for a variable that is different from the [n]\n    in the original theorem.  This is why the [Case] annotation is\n    just [S] -- if we tried to write it out in the more explicit form\n    that we've been using for most proofs, we'd have to write [n = S\n    n], which doesn't make a lot of sense!  All of these conveniences\n    make [induction] nicer to use in practice than applying induction\n    principles like [nat_ind] directly.  But it is important to\n    realize that, modulo this little bit of bookkeeping, applying\n    [nat_ind] is what we are really doing. *)\n\n(** **** Exercise: 2 stars, optional (plus_one_r') *)\n(** Complete this proof as we did [mult_0_r'] above, without using\n    the [induction] tactic. *)\n\nTheorem plus_one_r' : forall n:nat, \n  n + 1 = S n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Coq generates induction principles for every datatype defined with\n    [Inductive], including those that aren't recursive. (Although \n    we don't need induction to prove properties of non-recursive \n    datatypes, the idea of an induction principle still makes sense\n    for them: it gives a way to prove that a property holds for all\n    values of the type.)\n    \n    These generated principles follow a similar pattern. If we define a\n    type [t] with constructors [c1] ... [cn], Coq generates a theorem\n    with this shape:\n    t_ind :\n       forall P : t -> Prop,\n            ... case for c1 ... ->\n            ... case for c2 ... ->\n            ...                \n            ... case for cn ... ->\n            forall n : t, P n\n    The specific shape of each case depends on the arguments to the\n    corresponding constructor.  Before trying to write down a general\n    rule, let's look at some more examples. First, an example where\n    the constructors take no arguments: *)\n\nInductive yesno : Type :=\n  | yes : yesno\n  | no : yesno.\n\nCheck yesno_ind. \n(* ===> yesno_ind : forall P : yesno -> Prop, \n                      P yes  ->\n                      P no  ->\n                      forall y : yesno, P y *)\n\n(** **** Exercise: 1 star, optional (rgb) *)\n(** Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive rgb : Type :=\n  | red : rgb\n  | green : rgb\n  | blue : rgb.\nCheck rgb_ind.\n(** [] *)\n\n(** Here's another example, this time with one of the constructors\n    taking some arguments. *)\n\nInductive natlist : Type :=\n  | nnil : natlist\n  | ncons : nat -> natlist -> natlist.\n\nCheck natlist_ind.\n(* ===> (modulo a little variable renaming for clarity)\n   natlist_ind :\n      forall P : natlist -> Prop,\n         P nnil  ->\n         (forall (n : nat) (l : natlist), P l -> P (ncons n l)) ->\n         forall n : natlist, P n *)\n\n(** **** Exercise: 1 star, optional (natlist1) *)\n(** Suppose we had written the above definition a little\n   differently: *)\n\nInductive natlist1 : Type :=\n  | nnil1 : natlist1\n  | nsnoc1 : natlist1 -> nat -> natlist1.\n\n(** Now what will the induction principle look like? *)\n(** [] *)\n\n(** From these examples, we can extract this general rule:\n\n    - The type declaration gives several constructors; each\n      corresponds to one clause of the induction principle.\n    - Each constructor [c] takes argument types [a1]...[an].\n    - Each [ai] can be either [t] (the datatype we are defining) or\n      some other type [s].\n    - The corresponding case of the induction principle\n      says (in English):\n        - \"for all values [x1]...[xn] of types [a1]...[an], if [P]\n           holds for each of the inductive arguments (each [xi] of\n           type [t]), then [P] holds for [c x1 ... xn]\". \n\n*)\n\n\n\n(** **** Exercise: 1 star, optional (byntree_ind) *)\n(** Write out the induction principle that Coq will generate for the\n    following datatype.  Write down your answer on paper or type it\n    into a comment, and then compare it with what Coq prints. *)\n\nInductive byntree : Type :=\n | bempty : byntree  \n | bleaf  : yesno -> byntree\n | nbranch : yesno -> byntree -> byntree -> byntree.\n(** [] *)\n\n\n(** **** Exercise: 1 star, optional (ex_set) *)\n(** Here is an induction principle for an inductively defined\n    set.\n      ExSet_ind :\n         forall P : ExSet -> Prop,\n             (forall b : bool, P (con1 b)) ->\n             (forall (n : nat) (e : ExSet), P e -> P (con2 n e)) ->\n             forall e : ExSet, P e\n    Give an [Inductive] definition of [ExSet]: *)\n\nInductive ExSet : Type :=\n  (* FILL IN HERE *)\n.\n(** [] *)\n\n(** What about polymorphic datatypes?\n\n    The inductive definition of polymorphic lists\n      Inductive list (X:Type) : Type :=\n        | nil : list X\n        | cons : X -> list X -> list X.\n    is very similar to that of [natlist].  The main difference is\n    that, here, the whole definition is _parameterized_ on a set [X]:\n    that is, we are defining a _family_ of inductive types [list X],\n    one for each [X].  (Note that, wherever [list] appears in the body\n    of the declaration, it is always applied to the parameter [X].)\n    The induction principle is likewise parameterized on [X]:\n     list_ind :\n       forall (X : Type) (P : list X -> Prop),\n          P [] ->\n          (forall (x : X) (l : list X), P l -> P (x :: l)) ->\n          forall l : list X, P l\n   Note the wording here (and, accordingly, the form of [list_ind]):\n   The _whole_ induction principle is parameterized on [X].  That is,\n   [list_ind] can be thought of as a polymorphic function that, when\n   applied to a type [X], gives us back an induction principle\n   specialized to the type [list X]. *)\n\n(** **** Exercise: 1 star, optional (tree) *)\n(** Write out the induction principle that Coq will generate for\n   the following datatype.  Compare your answer with what Coq\n   prints. *)\n\nInductive tree (X:Type) : Type :=\n  | leaf : X -> tree X\n  | node : tree X -> tree X -> tree X.\nCheck tree_ind.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (mytype) *)\n(** Find an inductive definition that gives rise to the\n    following induction principle:\n      mytype_ind :\n        forall (X : Type) (P : mytype X -> Prop),\n            (forall x : X, P (constr1 X x)) ->\n            (forall n : nat, P (constr2 X n)) ->\n            (forall m : mytype X, P m -> \n               forall n : nat, P (constr3 X m n)) ->\n            forall m : mytype X, P m                   \n*) \n(** [] *)\n\n(** **** Exercise: 1 star, optional (foo) *)\n(** Find an inductive definition that gives rise to the\n    following induction principle:\n      foo_ind :\n        forall (X Y : Type) (P : foo X Y -> Prop),\n             (forall x : X, P (bar X Y x)) ->\n             (forall y : Y, P (baz X Y y)) ->\n             (forall f1 : nat -> foo X Y,\n               (forall n : nat, P (f1 n)) -> P (quux X Y f1)) ->\n             forall f2 : foo X Y, P f2       \n*) \n(** [] *)\n\n(** **** Exercise: 1 star, optional (foo') *)\n(** Consider the following inductive definition: *)\n\nInductive foo' (X:Type) : Type :=\n  | C1 : list X -> foo' X -> foo' X\n  | C2 : foo' X.\n\n(** What induction principle will Coq generate for [foo']?  Fill\n   in the blanks, then check your answer with Coq.)\n     foo'_ind :\n        forall (X : Type) (P : foo' X -> Prop),\n              (forall (l : list X) (f : foo' X),\n                    _______________________ -> \n                    _______________________   ) ->\n             ___________________________________________ ->\n             forall f : foo' X, ________________________\n*)\n\n(** [] *)\n\n(* ##################################################### *)\n(** ** Induction Hypotheses *)\n\n(** Where does the phrase \"induction hypothesis\" fit into this story?\n\n    The induction principle for numbers\n       forall P : nat -> Prop,\n            P 0  ->\n            (forall n : nat, P n -> P (S n))  ->\n            forall n : nat, P n\n   is a generic statement that holds for all propositions\n   [P] (strictly speaking, for all families of propositions [P]\n   indexed by a number [n]).  Each time we use this principle, we\n   are choosing [P] to be a particular expression of type\n   [nat->Prop].\n\n   We can make the proof more explicit by giving this expression a\n   name.  For example, instead of stating the theorem [mult_0_r] as\n   \"[forall n, n * 0 = 0],\" we can write it as \"[forall n, P_m0r\n   n]\", where [P_m0r] is defined as... *)\n\nDefinition P_m0r (n:nat) : Prop := \n  n * 0 = 0.\n\n(** ... or equivalently... *)\n\nDefinition P_m0r' : nat->Prop := \n  fun n => n * 0 = 0.\n\n(** Now when we do the proof it is easier to see where [P_m0r]\n    appears. *)\n\nTheorem mult_0_r'' : forall n:nat, \n  P_m0r n.\nProof.\n  apply nat_ind.\n  Case \"n = O\". reflexivity.\n  Case \"n = S n'\". \n    (* Note the proof state at this point! *)\n    intros n IHn. \n    unfold P_m0r in IHn. unfold P_m0r. simpl. apply IHn. Qed.\n\n(** This extra naming step isn't something that we'll do in\n    normal proofs, but it is useful to do it explicitly for an example\n    or two, because it allows us to see exactly what the induction\n    hypothesis is.  If we prove [forall n, P_m0r n] by induction on\n    [n] (using either [induction] or [apply nat_ind]), we see that the\n    first subgoal requires us to prove [P_m0r 0] (\"[P] holds for\n    zero\"), while the second subgoal requires us to prove [forall n',\n    P_m0r n' -> P_m0r n' (S n')] (that is \"[P] holds of [S n'] if it\n    holds of [n']\" or, more elegantly, \"[P] is preserved by [S]\").\n    The _induction hypothesis_ is the premise of this latter\n    implication -- the assumption that [P] holds of [n'], which we are\n    allowed to use in proving that [P] holds for [S n']. *)\n\n(* ##################################################### *)\n(** ** More on the [induction] Tactic *)\n\n(** The [induction] tactic actually does even more low-level\n    bookkeeping for us than we discussed above.\n\n    Recall the informal statement of the induction principle for\n    natural numbers:\n      - If [P n] is some proposition involving a natural number n, and\n        we want to show that P holds for _all_ numbers n, we can\n        reason like this:\n          - show that [P O] holds\n          - show that, if [P n'] holds, then so does [P (S n')]\n          - conclude that [P n] holds for all n.\n    So, when we begin a proof with [intros n] and then [induction n],\n    we are first telling Coq to consider a _particular_ [n] (by\n    introducing it into the context) and then telling it to prove\n    something about _all_ numbers (by using induction).\n\n    What Coq actually does in this situation, internally, is to\n    \"re-generalize\" the variable we perform induction on.  For\n    example, in our original proof that [plus] is associative...\n*)\n\nTheorem plus_assoc' : forall n m p : nat, \n  n + (m + p) = (n + m) + p.   \nProof.\n  (* ...we first introduce all 3 variables into the context,\n     which amounts to saying \"Consider an arbitrary [n], [m], and\n     [p]...\" *)\n  intros n m p. \n  (* ...We now use the [induction] tactic to prove [P n] (that\n     is, [n + (m + p) = (n + m) + p]) for _all_ [n],\n     and hence also for the particular [n] that is in the context\n     at the moment. *)\n  induction n as [| n'].\n  Case \"n = O\". reflexivity.\n  Case \"n = S n'\". \n    (* In the second subgoal generated by [induction] -- the\n       \"inductive step\" -- we must prove that [P n'] implies \n       [P (S n')] for all [n'].  The [induction] tactic \n       automatically introduces [n'] and [P n'] into the context\n       for us, leaving just [P (S n')] as the goal. *)\n    simpl. rewrite -> IHn'. reflexivity.  Qed.\n\n\n(** It also works to apply [induction] to a variable that is\n   quantified in the goal. *)\n\nTheorem plus_comm' : forall n m : nat, \n  n + m = m + n.\nProof.\n  induction n as [| n']. \n  Case \"n = O\". intros m. rewrite -> plus_0_r. reflexivity.\n  Case \"n = S n'\". intros m. simpl. rewrite -> IHn'. \n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** Note that [induction n] leaves [m] still bound in the goal --\n    i.e., what we are proving inductively is a statement beginning\n    with [forall m].\n\n    If we do [induction] on a variable that is quantified in the goal\n    _after_ some other quantifiers, the [induction] tactic will\n    automatically introduce the variables bound by these quantifiers\n    into the context. *)\n\nTheorem plus_comm'' : forall n m : nat, \n  n + m = m + n.\nProof.\n  (* Let's do induction on [m] this time, instead of [n]... *)\n  induction m as [| m']. \n  Case \"m = O\". simpl. rewrite -> plus_0_r. reflexivity.\n  Case \"m = S m'\". simpl. rewrite <- IHm'.\n    rewrite <- plus_n_Sm. reflexivity.  Qed.\n\n(** **** Exercise: 1 star, optional (plus_explicit_prop) *)\n(** Rewrite both [plus_assoc'] and [plus_comm'] and their proofs in\n    the same style as [mult_0_r''] above -- that is, for each theorem,\n    give an explicit [Definition] of the proposition being proved by\n    induction, and state the theorem and proof in terms of this\n    defined proposition.  *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** ** Generalizing Inductions. *)\n\n(** One potentially confusing feature of the [induction] tactic is\nthat it happily lets you try to set up an induction over a term\nthat isn't sufficiently general.  The net effect of this will be \nto lose information (much as [destruct] can do), and leave\nyou unable to complete the proof. Here's an example: *)\n\nLemma one_not_beautiful_FAILED: ~ beautiful 1. \nProof.\n  intro H.\n  (* Just doing an [inversion] on [H] won't get us very far in the [b_sum]\n    case. (Try it!). So we'll need induction. A naive first attempt: *)\n  induction H. \n  (* But now, although we get four cases, as we would expect from\n     the definition of [beautiful], we lose all information about [H] ! *) \nAbort.\n\n(** The problem is that [induction] over a Prop only works properly over \n   completely general instances of the Prop, i.e. one in which all\n   the arguments are free (unconstrained) variables. \n   In this respect it behaves more\n   like [destruct] than like [inversion]. \n\n   When you're tempted to do use [induction] like this, it is generally\n   an indication that you need to be proving something more general.\n   But in some cases, it suffices to pull out any concrete arguments\n   into separate equations, like this: *)\n\nLemma one_not_beautiful: forall n, n = 1 -> ~ beautiful n. \nProof.\n intros n E H.\n  induction H  as [| | | p q Hp IHp Hq IHq]. \n    Case \"b_0\".\n      inversion E.\n    Case \"b_3\". \n      inversion E. \n    Case \"b_5\". \n      inversion E. \n    Case \"b_sum\". \n      (* the rest is a tedious case analysis *)\n      destruct p as [|p'].\n      SCase \"p = 0\".\n        destruct q as [|q'].\n        SSCase \"q = 0\". \n          inversion E.\n        SSCase \"q = S q'\".\n          apply IHq. apply E. \n      SCase \"p = S p'\". \n        destruct q as [|q'].\n        SSCase \"q = 0\". \n          apply IHp.  rewrite plus_0_r in E. apply E. \n        SSCase \"q = S q'\".\n          simpl in E. inversion E.  destruct p'.  inversion H0.  inversion H0. \nQed.\n\n(** There's a handy [remember] tactic that can generate the second\nproof state out of the original one. *)\n\nLemma one_not_beautiful': ~ beautiful 1. \nProof.\n  intros H.  \n  remember 1 as n eqn:E. \n  (* now carry on as above *)\n  induction H.   \nAdmitted.\n\n\n(* ####################################################### *)\n(** * Informal Proofs (Advanced) *)\n\n(** Q: What is the relation between a formal proof of a proposition\n       [P] and an informal proof of the same proposition [P]?\n\n    A: The latter should _teach_ the reader how to produce the\n       former.\n\n    Q: How much detail is needed??\n\n    Unfortunately, There is no single right answer; rather, there is a\n    range of choices.\n\n    At one end of the spectrum, we can essentially give the reader the\n    whole formal proof (i.e., the informal proof amounts to just\n    transcribing the formal one into words).  This gives the reader\n    the _ability_ to reproduce the formal one for themselves, but it\n    doesn't _teach_ them anything.\n\n   At the other end of the spectrum, we can say \"The theorem is true\n   and you can figure out why for yourself if you think about it hard\n   enough.\"  This is also not a good teaching strategy, because\n   usually writing the proof requires some deep insights into the\n   thing we're proving, and most readers will give up before they\n   rediscover all the same insights as we did.\n\n   In the middle is the golden mean -- a proof that includes all of\n   the essential insights (saving the reader the hard part of work\n   that we went through to find the proof in the first place) and\n   clear high-level suggestions for the more routine parts to save the\n   reader from spending too much time reconstructing these\n   parts (e.g., what the IH says and what must be shown in each case\n   of an inductive proof), but not so much detail that the main ideas\n   are obscured.\n\n   Another key point: if we're comparing a formal proof of a\n   proposition [P] and an informal proof of [P], the proposition [P]\n   doesn't change.  That is, formal and informal proofs are _talking\n   about the same world_ and they _must play by the same rules_. *)\n(** ** Informal Proofs by Induction *)\n\n(** Since we've spent much of this chapter looking \"under the hood\" at\n    formal proofs by induction, now is a good moment to talk a little\n    about _informal_ proofs by induction.\n\n    In the real world of mathematical communication, written proofs\n    range from extremely longwinded and pedantic to extremely brief\n    and telegraphic.  The ideal is somewhere in between, of course,\n    but while you are getting used to the style it is better to start\n    out at the pedantic end.  Also, during the learning phase, it is\n    probably helpful to have a clear standard to compare against.\n    With this in mind, we offer two templates below -- one for proofs\n    by induction over _data_ (i.e., where the thing we're doing\n    induction on lives in [Type]) and one for proofs by induction over\n    _evidence_ (i.e., where the inductively defined thing lives in\n    [Prop]).  In the rest of this course, please follow one of the two\n    for _all_ of your inductive proofs. *)\n\n(** *** Induction Over an Inductively Defined Set *)\n \n(** _Template_: \n\n       - _Theorem_: <Universally quantified proposition of the form\n         \"For all [n:S], [P(n)],\" where [S] is some inductively defined\n         set.>\n\n         _Proof_: By induction on [n].\n\n           <one case for each constructor [c] of [S]...>\n\n           - Suppose [n = c a1 ... ak], where <...and here we state\n             the IH for each of the [a]'s that has type [S], if any>.\n             We must show <...and here we restate [P(c a1 ... ak)]>.\n\n             <go on and prove [P(n)] to finish the case...>\n\n           - <other cases similarly...>                        []\n \n    _Example_:\n \n      - _Theorem_: For all sets [X], lists [l : list X], and numbers\n        [n], if [length l = n] then [index (S n) l = None].\n\n        _Proof_: By induction on [l].\n\n        - Suppose [l = []].  We must show, for all numbers [n],\n          that, if length [[] = n], then [index (S n) [] =\n          None].\n\n          This follows immediately from the definition of index.\n\n        - Suppose [l = x :: l'] for some [x] and [l'], where\n          [length l' = n'] implies [index (S n') l' = None], for\n          any number [n'].  We must show, for all [n], that, if\n          [length (x::l') = n] then [index (S n) (x::l') =\n          None].\n\n          Let [n] be a number with [length l = n].  Since\n            length l = length (x::l') = S (length l'),\n          it suffices to show that \n            index (S (length l')) l' = None.\n]]  \n          But this follows directly from the induction hypothesis,\n          picking [n'] to be length [l'].  [] *)\n \n(** *** Induction Over an Inductively Defined Proposition *)\n\n(** Since inductively defined proof objects are often called\n    \"derivation trees,\" this form of proof is also known as _induction\n    on derivations_. \n\n    _Template_:\n \n       - _Theorem_: <Proposition of the form \"[Q -> P],\" where [Q] is\n         some inductively defined proposition (more generally,\n         \"For all [x] [y] [z], [Q x y z -> P x y z]\")>\n\n         _Proof_: By induction on a derivation of [Q].  <Or, more\n         generally, \"Suppose we are given [x], [y], and [z].  We\n         show that [Q x y z] implies [P x y z], by induction on a\n         derivation of [Q x y z]\"...>\n\n           <one case for each constructor [c] of [Q]...>\n\n           - Suppose the final rule used to show [Q] is [c].  Then\n             <...and here we state the types of all of the [a]'s\n             together with any equalities that follow from the\n             definition of the constructor and the IH for each of\n             the [a]'s that has type [Q], if there are any>.  We must\n             show <...and here we restate [P]>.\n\n             <go on and prove [P] to finish the case...>\n\n           - <other cases similarly...>                        []\n\n    _Example_\n \n       - _Theorem_: The [<=] relation is transitive -- i.e., for all\n         numbers [n], [m], and [o], if [n <= m] and [m <= o], then\n         [n <= o].\n\n         _Proof_: By induction on a derivation of [m <= o].\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_n]. Then [m = o] and we must show that [n <= m],\n             which is immediate by hypothesis.\n\n           - Suppose the final rule used to show [m <= o] is\n             [le_S].  Then [o = S o'] for some [o'] with [m <= o'].\n             We must show that [n <= S o'].\n             By induction hypothesis, [n <= o'].\n\n             But then, by [le_S], [n <= S o'].  [] *)\n\n\n\n(* ##################################################### *)\n(** * Optional Material *)\n\n(** The remainder of this chapter offers some additional details on\n    how induction works in Coq, the process of building proof\n    trees, and the \"trusted computing base\" that underlies\n    Coq proofs.  It can safely be skimmed on a first reading.  (We\n    recommend skimming rather than skipping over it outright: it\n    answers some questions that occur to many Coq users at some point,\n    so it is useful to have a rough idea of what's here.) *)\n\n\n(* ##################################################### *)\n(** ** Induction Principles in [Prop] *)\n\n\n(** Earlier, we looked in detail at the induction principles that Coq\n    generates for inductively defined _sets_.  The induction\n    principles for inductively defined _propositions_ like [gorgeous]\n    are a tiny bit more complicated.  As with all induction\n    principles, we want to use the induction principle on [gorgeous]\n    to prove things by inductively considering the possible shapes\n    that something in [gorgeous] can have -- either it is evidence\n    that [0] is gorgeous, or it is evidence that, for some [n], [3+n]\n    is gorgeous, or it is evidence that, for some [n], [5+n] is\n    gorgeous and it includes evidence that [n] itself is.  Intuitively\n    speaking, however, what we want to prove are not statements about\n    _evidence_ but statements about _numbers_.  So we want an\n    induction principle that lets us prove properties of numbers by\n    induction on evidence.\n\n    For example, from what we've said so far, you might expect the\n    inductive definition of [gorgeous]...\n    Inductive gorgeous : nat -> Prop :=\n         g_0 : gorgeous 0\n       | g_plus3 : forall n, gorgeous n -> gorgeous (3+m)\n       | g_plus5 : forall n, gorgeous n -> gorgeous (5+m).\n    ...to give rise to an induction principle that looks like this...\n    gorgeous_ind_max :\n       forall P : (forall n : nat, gorgeous n -> Prop),\n            P O g_0 ->\n            (forall (m : nat) (e : gorgeous m), \n               P m e -> P (3+m) (g_plus3 m e) ->\n            (forall (m : nat) (e : gorgeous m), \n               P m e -> P (5+m) (g_plus5 m e) ->\n            forall (n : nat) (e : gorgeous n), P n e\n    ... because:\n\n     - Since [gorgeous] is indexed by a number [n] (every [gorgeous]\n       object [e] is a piece of evidence that some particular number\n       [n] is gorgeous), the proposition [P] is parameterized by both\n       [n] and [e] -- that is, the induction principle can be used to\n       prove assertions involving both a gorgeous number and the\n       evidence that it is gorgeous.\n\n     - Since there are three ways of giving evidence of gorgeousness\n       ([gorgeous] has three constructors), applying the induction\n       principle generates three subgoals:\n\n         - We must prove that [P] holds for [O] and [b_0].\n\n         - We must prove that, whenever [n] is a gorgeous\n           number and [e] is an evidence of its gorgeousness,\n           if [P] holds of [n] and [e],\n           then it also holds of [3+m] and [g_plus3 n e].\n\n         - We must prove that, whenever [n] is a gorgeous\n           number and [e] is an evidence of its gorgeousness,\n           if [P] holds of [n] and [e],\n           then it also holds of [5+m] and [g_plus5 n e].\n\n     - If these subgoals can be proved, then the induction principle\n       tells us that [P] is true for _all_ gorgeous numbers [n] and\n       evidence [e] of their gorgeousness.\n\n    But this is a little more flexibility than we actually need or\n    want: it is giving us a way to prove logical assertions where the\n    assertion involves properties of some piece of _evidence_ of\n    gorgeousness, while all we really care about is proving\n    properties of _numbers_ that are gorgeous -- we are interested in\n    assertions about numbers, not about evidence.  It would therefore\n    be more convenient to have an induction principle for proving\n    propositions [P] that are parameterized just by [n] and whose\n    conclusion establishes [P] for all gorgeous numbers [n]:\n       forall P : nat -> Prop,\n          ... ->\n             forall n : nat, gorgeous n -> P n\n    For this reason, Coq actually generates the following simplified\n    induction principle for [gorgeous]: *)\n\n\n\nCheck gorgeous_ind.\n(* ===>  gorgeous_ind\n     : forall P : nat -> Prop,\n       P 0 ->\n       (forall n : nat, gorgeous n -> P n -> P (3 + n)) ->\n       (forall n : nat, gorgeous n -> P n -> P (5 + n)) ->\n       forall n : nat, gorgeous n -> P n *)\n\n(** In particular, Coq has dropped the evidence term [e] as a\n    parameter of the the proposition [P], and consequently has\n    rewritten the assumption [forall (n : nat) (e: gorgeous n), ...]\n    to be [forall (n : nat), gorgeous n -> ...]; i.e., we no longer\n    require explicit evidence of the provability of [gorgeous n]. *)\n\n(** In English, [gorgeous_ind] says:\n\n    - Suppose, [P] is a property of natural numbers (that is, [P n] is\n      a [Prop] for every [n]).  To show that [P n] holds whenever [n]\n      is gorgeous, it suffices to show:\n  \n      - [P] holds for [0],\n  \n      - for any [n], if [n] is gorgeous and [P] holds for\n        [n], then [P] holds for [3+n],\n\n      - for any [n], if [n] is gorgeous and [P] holds for\n        [n], then [P] holds for [5+n]. *)\n\n(** As expected, we can apply [gorgeous_ind] directly instead of using [induction]. *)\n\nTheorem gorgeous__beautiful' : forall n, gorgeous n -> beautiful n.\nProof.\n   intros.\n   apply gorgeous_ind.\n   Case \"g_0\".\n       apply b_0.\n   Case \"g_plus3\".\n       intros.\n       apply b_sum. apply b_3.\n       apply H1.\n   Case \"g_plus5\".\n       intros.\n       apply b_sum. apply b_5.\n       apply H1.\n   apply H.\nQed.\n\n\n\n(** The precise form of an Inductive definition can affect the\n    induction principle Coq generates.\n\nFor example, in [Logic], we have defined [<=] as: *)\n\n(* Inductive 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\n(** This definition can be streamlined a little by observing that the \n    left-hand argument [n] is the same everywhere in the definition, \n    so we can actually make it a \"general parameter\" to the whole \n    definition, rather than an argument to each constructor. *)\n\nInductive le (n:nat) : nat -> Prop :=\n  | le_n : le n n\n  | le_S : forall m, (le n m) -> (le n (S m)).\n\nNotation \"m <= n\" := (le m n).\n\n(** The second one is better, even though it looks less symmetric.\n    Why?  Because it gives us a simpler induction principle. *)\n\nCheck le_ind.\n(* ===>  forall (n : nat) (P : nat -> Prop),\n           P n ->\n           (forall m : nat, n <= m -> P m -> P (S m)) ->\n           forall n0 : nat, n <= n0 -> P n0 *)\n\n(** By contrast, the induction principle that Coq calculates for the\n    first definition has a lot of extra quantifiers, which makes it\n    messier to work with when proving things by induction.  Here is\n    the induction principle for the first [le]: *)\n\n(* le_ind : \n     forall P : nat -> nat -> Prop,\n     (forall n : nat, P n n) ->\n     (forall n m : nat, le n m -> P n m -> P n (S m)) ->\n     forall n n0 : nat, le n n0 -> P n n0 *)\n\n\n(* ##################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 2 stars, optional (foo_ind_principle) *)\n(** Suppose we make the following inductive definition:\n   Inductive foo (X : Set) (Y : Set) : Set :=\n     | foo1 : X -> foo X Y\n     | foo2 : Y -> foo X Y\n     | foo3 : foo X Y -> foo X Y.\n   Fill in the blanks to complete the induction principle that will be\n   generated by Coq. \n   foo_ind\n        : forall (X Y : Set) (P : foo X Y -> Prop),   \n          (forall x : X, __________________________________) ->\n          (forall y : Y, __________________________________) ->\n          (________________________________________________) ->\n           ________________________________________________\n\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (bar_ind_principle) *)\n(** Consider the following induction principle:\n   bar_ind\n        : forall P : bar -> Prop,\n          (forall n : nat, P (bar1 n)) ->\n          (forall b : bar, P b -> P (bar2 b)) ->\n          (forall (b : bool) (b0 : bar), P b0 -> P (bar3 b b0)) ->\n          forall b : bar, P b\n   Write out the corresponding inductive set definition.\n   Inductive bar : Set :=\n     | bar1 : ________________________________________\n     | bar2 : ________________________________________\n     | bar3 : ________________________________________.\n\n*)\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (no_longer_than_ind) *)\n(** Given the following inductively defined proposition:\n  Inductive no_longer_than (X : Set) : (list X) -> nat -> Prop :=\n    | nlt_nil  : forall n, no_longer_than X [] n\n    | nlt_cons : forall x l n, no_longer_than X l n -> \n                               no_longer_than X (x::l) (S n)\n    | nlt_succ : forall l n, no_longer_than X l n -> \n                             no_longer_than X l (S n).\n  write the induction principle generated by Coq.\n  no_longer_than_ind\n       : forall (X : Set) (P : list X -> nat -> Prop),\n         (forall n : nat, ____________________) ->\n         (forall (x : X) (l : list X) (n : nat),\n          no_longer_than X l n -> ____________________ -> \n                                  _____________________________ ->\n         (forall (l : list X) (n : nat),\n          no_longer_than X l n -> ____________________ -> \n                                  _____________________________ ->\n         forall (l : list X) (n : nat), no_longer_than X l n -> \n           ____________________\n\n*)\n(** [] *)\n\n\n(* ##################################################### *)\n(** ** Induction Principles for other Logical Propositions *)\n\n(** Similarly, in [Logic] we have defined [eq] as: *)\n\n(* Inductive eq (X:Type) : X -> X -> Prop :=\n       refl_equal : forall x, eq X x x. *)\n\n(** In the Coq standard library, the definition of equality is \n    slightly different: *)\n\nInductive eq' (X:Type) (x:X) : X -> Prop :=\n    refl_equal' : eq' X x x.\n\n(** The advantage of this definition is that the induction\n    principle that Coq derives for it is precisely the familiar\n    principle of _Leibniz equality_: what we mean when we say \"[x] and\n    [y] are equal\" is that every property on [P] that is true of [x]\n    is also true of [y].  *)\n\nCheck eq'_ind.\n(* ===> \n     forall (X : Type) (x : X) (P : X -> Prop),\n       P x -> forall y : X, x =' y -> P y \n\n   ===>  (i.e., after a little reorganization)\n     forall (X : Type) (x : X) forall y : X, \n       x =' y -> \n       forall P : X -> Prop, P x -> P y *)\n\n\n\n(** The induction principles for conjunction and disjunction are a\n    good illustration of Coq's way of generating simplified induction\n    principles for [Inductive]ly defined propositions, which we\n    discussed above.  You try first: *)\n\n(** **** Exercise: 1 star, optional (and_ind_principle) *)\n(** See if you can predict the induction principle for conjunction. *)\n\n(* Check and_ind. *)\n(** [] *)\n\n(** **** Exercise: 1 star, optional (or_ind_principle) *)\n(** See if you can predict the induction principle for disjunction. *)\n\n(* Check or_ind. *)\n(** [] *)\n\nCheck and_ind.\n\n(** From the inductive definition of the proposition [and P Q]\n     Inductive and (P Q : Prop) : Prop :=\n       conj : P -> Q -> (and P Q).\n    we might expect Coq to generate this induction principle\n     and_ind_max :\n       forall (P Q : Prop) (P0 : P /\\ Q -> Prop),\n            (forall (a : P) (b : Q), P0 (conj P Q a b)) ->\n            forall a : P /\\ Q, P0 a\n    but actually it generates this simpler and more useful one:\n     and_ind :\n       forall P Q P0 : Prop,\n            (P -> Q -> P0) ->\n            P /\\ Q -> P0\n    In the same way, when given the inductive definition of [or P Q]\n     Inductive or (P Q : Prop) : Prop :=\n       | or_introl : P -> or P Q\n       | or_intror : Q -> or P Q.\n    instead of the \"maximal induction principle\"\n     or_ind_max :\n       forall (P Q : Prop) (P0 : P \\/ Q -> Prop),\n            (forall a : P, P0 (or_introl P Q a)) ->\n            (forall b : Q, P0 (or_intror P Q b)) ->\n            forall o : P \\/ Q, P0 o\n    what Coq actually generates is this:\n     or_ind :\n       forall P Q P0 : Prop,\n            (P -> P0) ->\n            (Q -> P0) ->\n            P \\/ Q -> P0\n]] \n*)\n\n(** **** Exercise: 1 star, optional (False_ind_principle) *)\n(** Can you predict the induction principle for falsehood? *)\n\n(* Check False_ind. *)\n(** [] *)\n\n(** Here's the induction principle that Coq generates for existentials: *)\n\nCheck ex_ind.\n(* ===>  forall (X:Type) (P: X->Prop) (Q: Prop),\n         (forall witness:X, P witness -> Q) -> \n          ex X P -> \n           Q *)\n\n(** This induction principle can be understood as follows: If we have\n         a function [f] that can construct evidence for [Q] given _any_\n        witness of type [X] together with evidence that this witness has\n        property [P], then from a proof of [ex X P] we can extract the\n        witness and evidence that must have been supplied to the\n        constructor, give these to [f], and thus obtain a proof of [Q]. *)\n\n\n\n(* ######################################################### *)\n(** ** Explicit Proof Objects for Induction *)\n\n\n(** Although tactic-based proofs are normally much easier to\n    work with, the ability to write a proof term directly is sometimes\n    very handy, particularly when we want Coq to do something slightly\n    non-standard.  *)\n    \n(** Recall the induction principle on naturals that Coq generates for\n    us automatically from the Inductive declation for [nat]. *)\n\nCheck nat_ind.\n(* ===> \n   nat_ind : forall P : nat -> Prop,\n      P 0 -> \n      (forall n : nat, P n -> P (S n)) -> \n      forall n : nat, P n  *)\n\n(** There's nothing magic about this induction lemma: it's just\n   another Coq lemma that requires a proof.  Coq generates the proof\n   automatically too...  *)\n\nPrint nat_ind.\nPrint nat_rect.\n(* ===> (after some manual inlining and tidying)\n   nat_ind =\n    fun (P : nat -> Prop) \n        (f : P 0) \n        (f0 : forall n : nat, P n -> P (S n)) =>\n          fix F (n : nat) : P n :=\n             match n with\n            | 0 => f\n            | S n0 => f0 n0 (F n0)\n            end.\n*)\n\n(** We can read this as follows: \n     Suppose we have evidence [f] that [P] holds on 0,  and \n     evidence [f0] that [forall n:nat, P n -> P (S n)].  \n     Then we can prove that [P] holds of an arbitrary nat [n] via \n     a recursive function [F] (here defined using the expression \n     form [Fix] rather than by a top-level [Fixpoint] \n     declaration).  [F] pattern matches on [n]: \n      - If it finds 0, [F] uses [f] to show that [P n] holds.\n      - If it finds [S n0], [F] applies itself recursively on [n0] \n         to obtain evidence that [P n0] holds; then it applies [f0] \n         on that evidence to show that [P (S n)] holds. \n    [F] is just an ordinary recursive function that happens to \n    operate on evidence in [Prop] rather than on terms in [Set].\n \n*)\n\n \n(**  We can adapt this approach to proving [nat_ind] to help prove\n    _non-standard_ induction principles too.  Recall our desire to\n    prove that\n\n    [forall n : nat, even n -> ev n].\n \n    Attempts to do this by standard induction on [n] fail, because the\n    induction principle only lets us proceed when we can prove that\n    [even n -> even (S n)] -- which is of course never provable.  What\n    we did in [Logic] was a bit of a hack:\n \n    [Theorem even__ev : forall n : nat,\n     (even n -> ev n) /\\ (even (S n) -> ev (S n))].\n \n    We can make a much better proof by defining and proving a\n    non-standard induction principle that goes \"by twos\":\n \n *)\n \n Definition nat_ind2 : \n    forall (P : nat -> Prop), \n    P 0 -> \n    P 1 -> \n    (forall n : nat, P n -> P (S(S n))) -> \n    forall n : nat , P n :=\n       fun P => fun P0 => fun P1 => fun PSS => \n          fix f (n:nat) := match n with \n                             0 => P0 \n                           | 1 => P1 \n                           | S (S n') => PSS n' (f n') \n                          end.\n \n (** Once you get the hang of it, it is entirely straightforward to\n     give an explicit proof term for induction principles like this.\n     Proving this as a lemma using tactics is much less intuitive (try\n     it!).\n\n     The [induction ... using] tactic variant gives a convenient way to\n     specify a non-standard induction principle like this. *)\n \nLemma even__ev' : forall n, even n -> ev n.\nProof. \n intros.  \n induction n as [ | |n'] using nat_ind2. \n  Case \"even 0\". \n    apply ev_0.  \n  Case \"even 1\". \n    inversion H.\n  Case \"even (S(S n'))\". \n    apply ev_SS. \n    apply IHn'.  unfold even.  unfold even in H.  simpl in H. apply H. \nQed. \n\n(* ######################################################### *)\n(** ** The Coq Trusted Computing Base *)\n\n(** One issue that arises with any automated proof assistant is \"why\n    trust it?\": what if there is a bug in the implementation that\n    renders all its reasoning suspect?\n\n    While it is impossible to allay such concerns completely, the fact\n    that Coq is based on the Curry-Howard correspondence gives it a\n    strong foundation. Because propositions are just types and proofs\n    are just terms, checking that an alleged proof of a proposition is\n    valid just amounts to _type-checking_ the term.  Type checkers are\n    relatively small and straightforward programs, so the \"trusted\n    computing base\" for Coq -- the part of the code that we have to\n    believe is operating correctly -- is small too.\n\n    What must a typechecker do?  Its primary job is to make sure that\n    in each function application the expected and actual argument\n    types match, that the arms of a [match] expression are constructor\n    patterns belonging to the inductive type being matched over and\n    all arms of the [match] return the same type, and so on.\n\n    There are a few additional wrinkles:\n\n    - Since Coq types can themselves be expressions, the checker must\n      normalize these (by using the computation rules) before\n      comparing them.\n\n    - The checker must make sure that [match] expressions are\n      _exhaustive_.  That is, there must be an arm for every possible\n      constructor.  To see why, consider the following alleged proof\n      object:\n      Definition or_bogus : forall P Q, P \\/ Q -> P :=\n        fun (P Q : Prop) (A : P \\/ Q) =>\n           match A with\n           | or_introl H => H\n           end. \n      All the types here match correctly, but the [match] only\n      considers one of the possible constructors for [or].  Coq's\n      exhaustiveness check will reject this definition.\n\n    - The checker must make sure that each [fix] expression\n      terminates.  It does this using a syntactic check to make sure\n      that each recursive call is on a subexpression of the original\n      argument.  To see why this is essential, consider this alleged\n      proof:\n          Definition nat_false : forall (n:nat), False :=\n             fix f (n:nat) : False := f n. \n      Again, this is perfectly well-typed, but (fortunately) Coq will\n      reject it. *)\n\n(** Note that the soundness of Coq depends only on the correctness of\n    this typechecking engine, not on the tactic machinery.  If there\n    is a bug in a tactic implementation (and this certainly does\n    happen!), that tactic might construct an invalid proof term.  But\n    when you type [Qed], Coq checks the term for validity from\n    scratch.  Only lemmas whose proofs pass the type-checker can be\n    used in further proof developments.  *)\n\n(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)\n\n\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/MoreInd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928951399099, "lm_q2_score": 0.9032942099580604, "lm_q1q2_score": 0.7045630659883052}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat.\n\nSet Implicit Arguments.\n\nModule MyNamespace.\n\n(** Euclidean division: returns quotient and reminder  *)\n\n(** Type constructors, Product type *)\n\nSection ProductType.\n\nInductive prod (A B : Type) : Type :=\n  | pair of A & B.\n\nAbout pair.\n\n(** Explicit binding of type constructor's parameters for\n    data constructors\n  *)\nCheck pair 42 true : prod nat bool.\n\n(** Implicit arguments;\n    local deactivation of implicit arguments (@)\n *)\n\nFail Check pair nat bool 42 true : prod nat bool.  (* inconvenient *)\nCheck @pair nat bool 42 true.\n\n\n\n\n(** Notations for better UX *)\n\nNotation \"A * B\" := (prod A B) (at level 40, left associativity) : type_scope.\n\n\n\n(** Notation scopes *)\n\nFail Check nat * bool.\n\nCheck (nat * nat)%type.\n\nCheck (nat * bool) : Type.\n\nOpen Scope type_scope.\nCheck (nat * nat).\nClose Scope type_scope.\nFail Check (nat * nat).\n\n(** Left / right associativity *)\nCheck ((nat * bool) * nat)%type.\n\nCheck (nat * (bool * nat))%type.\n\n(** Weak notation *)\nNotation \"( p ; q )\" := (pair p q).\n\n(** Triples, quadruples, ... ? *)\n\n(** Recursive notations *)\n\nNotation \"( p , q , .. , r )\" := (pair .. (pair p q) .. r)\n                                   : core_scope.\n\nCheck (1, false) : nat * bool.\n\nUnset Printing Notations.\nCheck (1, false) : nat * bool.\nSet Printing Notations.\n\nDefinition fst {A B : Type} : A * B -> A :=\n  (* fun p => match p with | pair a b => a end. *)\n  (* fun p => let (a, b) := p in a. *)\n  fun '(a, _) => a. \n\nNotation \"p .1\" := (fst p).\n\nDefinition snd {A B : Type} : A * B -> B :=\n  fun '(a, b) => b.\n\nNotation \"p .2\" := (snd p).\n\nDefinition swap {A B : Type} : A * B -> B * A :=\n  fun '(a,b) => (b,a).\n\nEnd ProductType.\n\n(**\n      A /\\ B -> B /\\ A\n *)\n\nCheck fst.\nCheck snd.\nCheck @pair _ _.\n\n\nSection Intuitionistic_Propositional_Logic.\n\n(** Implication *)\n\nDefinition A_implies_A (A : Prop) :\n  A -> A\n:=\n  fun proof_A : A => proof_A.\n\nDefinition A_implies_B_implies_A (A B : Prop) :\n  A -> B -> A\n:=\n  fun proof_A => fun proof_B => proof_A.\n(* const *)\n\n\n(** Conjunction *)\n\nInductive and (A B : Prop) : Prop :=\n  | conj of A & B.\n\nNotation \"A /\\ B\" := (and A B) : type_scope.\n\nDefinition andC (A B : Prop) :\n  A /\\ B -> B /\\ A\n:=\n  fun '(conj proof_A proof_B) => conj proof_B proof_A.\n\nDefinition andA (A B C : Prop) :\n  (A /\\ B) /\\ C -> A /\\ (B /\\ C)\n:=\n  fun '(conj (conj a b) c) => conj a (conj b c).\n\n\n(** Biimplication, a.k.a. if and only if *)\n\nDefinition iff (A B : Prop) : Prop :=\n  (A -> B) /\\ (B -> A).\n\nNotation \"A <-> B\" := (iff A B) : type_scope.\n\nDefinition andA_iff (A B C : Prop) :\n  (A /\\ B) /\\ C <-> A /\\ (B /\\ C)\n:=\n  conj\n    (fun '(conj (conj a b) c) => conj a (conj b c))\n    (fun '(conj a (conj b c)) => (conj (conj a b) c)).\n\n\n(** Disjunction *)\n\nInductive or (A B : Prop) : Prop :=\n| or_introl of A\n| or_intror of B.\n\nArguments or_introl [A B] a, [A] B a.\nArguments or_intror [A B] b, A [B] b.\n\nNotation \"A \\/ B\" := (or A B) : type_scope.\n\nDefinition or1 (A B : Prop) : A -> A \\/ B\n  :=\nfun proofA => or_introl proofA.\n\nDefinition orC A B :\n  A \\/ B -> B \\/ A\n:=\n  fun a_or_b =>\n    match a_or_b with\n    | or_introl proofA => or_intror proofA\n    | or_intror proofB => or_introl proofB\n    end.\n\nDefinition or_and_distr A B C :\n  (A \\/ B) /\\ C -> (A /\\ C) \\/ (B /\\ C)\n:=\n  fun '(conj a_or_b c) =>\n    match a_or_b with\n    | or_introl a => or_introl (conj a c)\n    | or_intror b => or_intror (conj b c)\n    end.\n\nInductive False : Prop := .\n\nInductive True : Prop :=\n  | I.\n\nDefinition t : True\n  :=\nI.\n\nDefinition t_and_t : True /\\ True\n  :=\nconj I I.\n\nDefinition not (A : Prop) :=\n  A -> False.\n\nNotation \"~ A\" := (not A) : type_scope.\n\nDefinition A_implies_not_not_A (A : Prop) :\n   A -> ~ ~ A\n(* A -> (A -> False) -> False *)\n:=\n  fun a => fun not_a => not_a a.\n\n(* Double negation elimination is\n   not provable in Intuitionistic Logic *)\nFail Definition DNE (A : Prop) :\n   ~ ~ A -> A\n:=\n  fun nna => __.  (* can't call [nna] *)\n\n(* Since the Law of Excluded Middle\n   is equivalent to DNE it's not provable\n   either\n *)\nFail Definition LEM (A : Prop) :\n   A \\/ ~A\n:=\n  (* or_intror (fun a => ???). *)\n  __. (* or_introl / or_intror ? *)\n\nEnd Intuitionistic_Propositional_Logic.\n\n\nSection Propositional_Equality.\n\nInductive eq (A : Type)\n             (a : A) : A -> Prop :=\n| eq_refl : eq a a.\nCheck eq_ind.\n\nAbout eq.\nCheck eq_refl 1 : eq 1 1.\nFail Check eq_refl 1 : eq 1 21.\n\nCheck @eq_refl nat 2 : @eq nat 2 2.\nFail Check eq_refl 1 : @eq nat 1 2.\nFail Check eq_refl 2 : @eq nat 1 2.\n\nNotation \"a = b\" := (eq a b) : type_scope.\n\n\nDefinition eq_reflexive A (x : A) :\n  x = x\n:=\n  eq_refl x.\n\n(* dependent pattern matching *)\nDefinition eq_sym A (x y : A) :\n  x = y -> y = x\n:=\n  fun proof_x_eq_y =>\n    match proof_x_eq_y with\n    | eq_refl => eq_refl x\n    end.\n\nDefinition eq_foo (x y z : nat) :\n  x + y = y + z -> (x + y) + z = (y + z) + z\n:=\n  fun prf_eq =>\n    match prf_eq with\n    | eq_refl => eq_refl ((x + y) + z)\n    end.\n\nDefinition eq_trans A (x y z : A) :\n  x = y -> (y = z -> x = z)\n:=\n  fun x_eq_y : x = y =>\n    match x_eq_y with\n    | eq_refl => id\n    end.\n\nEnd Propositional_Equality.\n\nEnd MyNamespace.\n\n\n(** The SSReflect proof language *)\n\nLemma A_implies_A (A : Prop) :\n  A -> A.\nProof. (* <-- optional *)\nShow Proof.\nmove => a.   (* tactical *)\nShow Proof.\n(* move: a. exact. *)\nexact: a.\nShow Proof.\n(* by []. *)\nQed.\n\nLemma or_and_distr A B C :\n  (A \\/ B) /\\ C -> A /\\ C \\/ B /\\ C.\nProof.\ncase.\ncase.\n- move=> a. move=> c. left. split.\n  - exact: a.\n  by apply: c.\nmove=> b c. right. by split.\nQed.\n\nAbout or_and_distr.\n\n\n(* a terser version *)\nLemma or_and_distr' A B C :\n  (A \\/ B) /\\ C -> A /\\ C \\/ B /\\ C.\nProof.\nby move=> [[a | b] c]; [left | right].\nQed.\n\n(* An example taken from\n\"An Ssreflect Tutorial\" by G.Gonthier, R.S. Le(2009)\n *)\nSection HilbertSaxiom.\n\nVariables A B C : Prop.\n\nLemma HilbertS :\n  (A -> B -> C) -> (A -> B) -> A -> C.\nProof.\nmove=> hAiBiC hAiB hA.\nmove: hAiBiC.\napply.\n- by [].\nby apply: hAiB.\nQed.\n\nEnd HilbertSaxiom.\n\nSection Rewrite.\n\nVariable A : Type.\nImplicit Types x y z : A.\n\nLemma eq_reflexive x :\n  x = x.\nProof. by []. Qed.\n\n\nLemma eq_sym x y :\n  x = y -> y = x.\nProof.\nmove=> x_eq_y. rewrite -x_eq_y. by [].\nShow Proof.\nQed.\nEval compute in eq_sym.\n\nLemma eq_sym_shorter x y :\n  x = y -> y = x.\nProof.\nby move=> ->.\nQed.\n\nLemma eq_trans x y z :\n  x = y -> y = z -> x = z.\nProof.\nmove=> ->->.\napply: eq_reflexive.\nQed.\n", "meta": {"author": "anton-trunov", "repo": "coq-lecture-notes", "sha": "e012addae82da6d8d03f6e789e43f35140dcdfea", "save_path": "github-repos/coq/anton-trunov-coq-lecture-notes", "path": "github-repos/coq/anton-trunov-coq-lecture-notes/coq-lecture-notes-e012addae82da6d8d03f6e789e43f35140dcdfea/code/lecture02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7043716600079681}}
{"text": "Require Import FOL Deduction Tarski DecidabilityFacts Synthetic NumberTheory.\nRequire Import List Lia.\nImport Vector.VectorNotations.\n\nRequire Import Equations.Equations Equations.Prop.DepElim.\n\n\n(* For Definitions, my reference was the treatment of Peter Smith in \"Introduction to Gödel's Theorems\"\n (page 37) *)\n\nExisting Instance falsity_on.\n\n(** * Peano Arithmetic *)\n\n(** Non-logical symbols used in the language of PA *)\n\nInductive PA_funcs : Type :=\n  Zero : PA_funcs\n| Succ : PA_funcs\n| Plus : PA_funcs\n| Mult : PA_funcs.\n\nDefinition PA_funcs_ar (f : PA_funcs ) :=\nmatch f with\n | Zero => 0\n | Succ => 1\n | Plus => 2\n | Mult => 2\n end.\n\nInductive PA_preds : Type := .\n\nDefinition PA_preds_ar (P : PA_preds) :=\nmatch P with\n | _ => 0\nend.\n\n\nInstance PA_funcs_signature : funcs_signature :=\n{| syms := PA_funcs ; ar_syms := PA_funcs_ar |}.\n\nInstance PA_preds_signature : preds_signature :=\n{| preds := PA_preds ; ar_preds := PA_preds_ar |}.\n\n\nArguments Vector.cons {_} _ {_} _, _ _ _ _.\n\n\n\nDeclare Scope PA_Notation.\nOpen Scope PA_Notation.\n\nNotation \"'zero'\" := (func Zero ([])) (at level 1) : PA_Notation.\nNotation \"'σ' x\" := (func Succ ([x])) (at level 37) : PA_Notation.\nNotation \"x '⊕' y\" := (func Plus ([x ; y]) ) (at level 39) : PA_Notation.\nNotation \"x '⊗' y\" := (func Mult ([x ; y]) ) (at level 38) : PA_Notation.\nNotation \"x '==' y\" := (eq x y) (at level 40) : PA_Notation.\n(* Definition syntac_less (x y : term) := (∃ y[↑] == σ (x[↑] ⊕ $0)) : PA_Notation. *)\nDefinition sless x y := (∃ y`[↑] == σ (x`[↑] ⊕ $0)). \nNotation \"x '⧀' y\" := (sless x y)  (at level 40) : PA_Notation.\n\n\nFact unfold_sless x y :\n  sless x y = ∃ y`[↑] == σ (x`[↑] ⊕ $0).\nProof.\nreflexivity.\nQed.\n\nFact sless_subst x y s :\n  (sless x y)[s] = sless (x`[s]) (y`[s]).\nProof.\ncbn. now rewrite !up_term.\nQed.\n\n\n(* Defines numerals i.e. a corresponding term for every natural number *)\nFixpoint num n :=  \n  match n with\n    O => zero\n  | S x => σ (num x)\n  end.\n\n\n\n\n\n\nDefinition forall_times n (phi : form) := iter (fun psi => ∀ psi) n phi.\n\n(** ** PA Axioms *)\n\n(** Basic Axioms *)\n\nDefinition ax_zero_succ := ∀  (zero == σ var 0 --> ⊥).\nDefinition ax_succ_inj :=  ∀∀ (σ $1 == σ $0 --> $1 == $0).\nDefinition ax_add_zero :=  ∀  (zero ⊕ $0 == $0).\nDefinition ax_add_rec :=   ∀∀ ((σ $0) ⊕ $1 == σ ($0 ⊕ $1)).\nDefinition ax_mult_zero := ∀  (zero ⊗ $0 == zero).\nDefinition ax_mult_rec :=  ∀∀ (σ $1 ⊗ $0 == $0 ⊕ $1 ⊗ $0).\n\n(** Induction Scheme *)\n\nDefinition ax_induction (phi : form) :=\n  phi[zero..] --> (∀ phi --> phi[σ $0 .: S >> var]) --> ∀ phi.\n\nDefinition ax_zero_or_succ := ∀ $0 == zero ∨ ∃ $1 == σ $0.\n\n\n\n(** Equality Axioms *)\n\nDefinition ax_refl :=  ∀   $0 == $0.\nDefinition ax_sym :=   ∀∀  $1 == $0 --> $0 == $1.\nDefinition ax_trans := ∀∀∀ $2 == $1 --> $1 == $0 --> $2 == $0.\n\nDefinition ax_succ_congr := ∀∀ $0 == $1 --> σ $0 == σ $1.\nDefinition ax_add_congr := ∀∀∀∀ $0 == $1 --> $2 == $3 --> $0 ⊕ $2 == $1 ⊕ $3.\nDefinition ax_mult_congr := ∀∀∀∀ $0 == $1 --> $2 == $3 --> $0 ⊗ $2 == $1 ⊗ $3.\n\n\nDefinition EQ :=\n  (ax_refl :: ax_sym :: ax_trans :: ax_succ_congr :: ax_add_congr :: ax_mult_congr :: nil)%list.\n\n\n(** ** Robinson Arithmetic *)\nDefinition Q := (EQ ++ ax_zero_succ :: ax_succ_inj :: ax_add_zero :: ax_add_rec :: ax_mult_zero :: ax_mult_rec :: ax_zero_or_succ :: nil)%list.\n\nFact unfold_Q :\n  Q = (EQ ++ ax_zero_succ :: ax_succ_inj :: ax_add_zero :: ax_add_rec :: ax_mult_zero :: ax_mult_rec :: ax_zero_or_succ :: nil)%list.\nProof. reflexivity. Qed.\n\nGlobal Opaque Q.\n\n\n\n(** The Theory PA *)\nInductive PA : form -> Prop :=\n| PA_Q : forall ax, List.In ax Q -> PA ax\n| PA_induction : forall phi, bounded 1 phi -> PA (ax_induction phi).\n\n\nNotation \"x 'i=' y\" := (i_P (Σ_funcs:=PA_preds_signature) (P:=Eq) [x ; y]) (at level 30) : PA_Notation.\nNotation \"'i0'\" := (i_f (Σ_funcs:=PA_funcs_signature) (f:=Zero) []) (at level 2) : PA_Notation.\nNotation \"'iσ' d\" := (i_f (Σ_funcs:=PA_funcs_signature) (f:=Succ) [d]) (at level 37) : PA_Notation.\nNotation \"x 'i⊕' y\" := (i_f (Σ_funcs:=PA_funcs_signature) (f:=Plus) [x ; y]) (at level 39) : PA_Notation.\nNotation \"x 'i⊗' y\" := (i_f (Σ_funcs:=PA_funcs_signature) (f:=Mult) [x ; y]) (at level 38) : PA_Notation.\n\n\n(** ** PA Models *)\n\nSection Models.\n\n\n  Variable D : Type.\n  Variable I : interp D.\n\n  Notation \"x 'i⧀' y\" := (exists d : D, y = iσ (x i⊕ d) ) (at level 40).\n\n\n\n  Definition theory := form -> Prop.\n  Definition in_theory (T : theory) phi := T phi.\n\n  Notation \"phi ∈ T\" := (in_theory T phi) (at level 70).\n  Notation \"A ⊏ T\" := (forall phi, In phi A -> phi ∈ T) (at level 70).\n  Definition PAsat phi := exists A, A ⊏ PA /\\ forall rho, (forall α, In α A -> rho ⊨ α) -> rho ⊨ phi.\n\n  Fixpoint inu n := \n    match n with\n    | 0 => i0\n    | S x => iσ (inu x)\n    end.\n  \n  Fact eval_num sigma n : \n    eval sigma (num n) = inu n.\n  Proof.\n    induction n.\n    - reflexivity.\n    - cbn. now rewrite IHn.\n  Qed.\n\n\n  Lemma num_subst : \n    forall n rho, (num n)`[rho] = num n.\n  Proof.\n    induction n.\n    - reflexivity.\n    - intros rho. cbn. now rewrite IHn.\n  Qed.\n\n\n  Lemma switch_num alpha rho n : \n    rho ⊨ alpha[(num n)..] <-> ((inu n).:rho) ⊨ alpha.\n  Proof.    \n    split; intros H.\n    - erewrite <-eval_num. apply sat_single, H.\n    - apply sat_single. now rewrite eval_num.\n  Qed.\n\n  \n  Lemma switch_up_num α rho x d : \n    (d.:rho) ⊨ (α [up (num x)..]) <-> (d.:((inu x).:rho)) ⊨ α.\n  Proof.\n    rewrite sat_comp. apply sat_ext.\n    intros [|[]]; try reflexivity.\n    cbn. now rewrite num_subst, eval_num.\n  Qed.\n\n\n\n  Lemma eq_sym : forall rho a b, rho ⊨ (a == b) -> rho ⊨ (b == a).\n  Proof.\n    intros. now cbn in *.\n  Qed.\n  \n  Lemma eq_trans : forall rho a b c, rho ⊨ (a == b) /\\ rho ⊨ (b == c) -> rho ⊨ (a == c).\n  Proof.\n    intros ????. cbn in *. intros []. congruence.\n  Qed.\n\n  Notation \"⊨ phi\" := (forall rho, rho ⊨ phi) (at level 21).\n\n\n\n\n  Section PA_Model.\n\n    Context {axioms : forall ax, PA ax -> ⊨ ax}. \n\n\n    (* provide all axioms in a more useful form *)\n\n    Lemma zero_succ x : i0 = iσ x -> False.\n    Proof.\n      assert (⊨ ax_zero_succ) as H.\n      apply axioms; constructor.\n      firstorder.\n      specialize (H (fun _ => i0) x).\n      apply H.\n    Qed.\n\n    Lemma succ_inj x y : iσ y = iσ x -> y = x.\n    Proof.\n      assert (⊨ ax_succ_inj ) as H.\n      apply axioms; constructor.\n      firstorder.\n      specialize (H (fun _ => i0) y x).\n      apply H.\n    Qed.\n\n    Lemma succ_inj' x y : iσ y = iσ x <-> y = x.\n    Proof.\n      split.\n      apply succ_inj. now intros ->.\n    Qed.\n\n\n    Lemma add_zero d : i0 i⊕ d = d.\n    Proof.\n      assert (⊨ ax_add_zero) as H.\n      apply axioms; constructor.\n      firstorder.\n      specialize (H (fun _ => i0) d).\n      apply H.\n    Qed.\n\n    Lemma add_rec n d : (iσ n) i⊕ d = iσ (n i⊕ d). \n    Proof.\n      assert (⊨ ax_add_rec) as H.\n      apply axioms; constructor.\n      firstorder.\n      specialize (H (fun _ => i0) d n).\n      apply H.\n    Qed.\n\n    Lemma mult_zero d : i0 i⊗ d = i0.\n    Proof.\n      assert (⊨ ax_mult_zero) as H.\n      apply axioms; constructor.\n      firstorder.\n      specialize (H (fun _ => i0) d).\n      apply H.\n    Qed.\n\n    Lemma mult_rec n d : (iσ d) i⊗ n = n i⊕ (d i⊗ n).\n    Proof.\n      assert (⊨ ax_mult_rec) as H.\n      apply axioms; constructor.\n      firstorder.\n      specialize (H (fun _ => i0) d n).\n      apply H.\n    Qed.\n\n\n\n    Section Induction.\n      \n      Notation \"phi [[ d ]] \" := (forall rho, (d.:rho) ⊨ phi) (at level 19).\n\n      Variable phi : form.\n      Variable pred : bounded 1 phi.\n      \n      Lemma induction1 : phi[[i0]] -> ⊨ phi[zero..].\n      Proof.\n        intros H0 rho.\n        apply sat_single. apply H0.\n      Qed.\n\n      Lemma induction2 :\n        (forall n, phi[[n]] -> phi[[iσ n]]) -> ⊨ (∀ phi --> phi[σ $ 0 .: S >> var]).\n      Proof.\n        intros IH rho d Hd.\n        eapply sat_comp, sat_ext.\n        instantiate (1 := ((iσ d).:rho)).\n        intros []; now cbn.\n        apply IH. intros ?.\n        eapply bound_ext. apply pred. 2 : apply Hd.\n        intros []; intros.\n        reflexivity. lia.\n      Qed.\n\n\n      Theorem induction : phi[[i0]] -> (forall n, phi[[n]] -> phi[[iσ n]] ) -> forall n, phi[[n]].\n      Proof.\n        assert (⊨ ax_induction phi) as H.\n        apply axioms. apply PA_induction; trivial.\n        intros ??? rho.\n        specialize (H rho). \n        apply H.\n        now apply induction1.\n        now apply induction2.\n      Qed.  \n\n    End Induction.\n\n\n\n    Lemma inu_inj x y : inu x = inu y <-> x = y.\n    Proof.\n      split.\n      induction x in y |-*; destruct y; auto; cbn.\n      - now intros ?%zero_succ.\n      - intros H. symmetry in H. now apply zero_succ in H.\n      - now intros <-%succ_inj%IHx.\n      - congruence.\n    Qed.\n\n\n    Lemma inu_add_hom x y : inu (x + y) = inu x i⊕ inu y.\n    Proof.\n      induction x; cbn.\n      - now rewrite add_zero.\n      - now rewrite add_rec, IHx.\n    Qed.\n\n\n    Lemma inu_mult_hom x y : inu (x * y) = inu x i⊗ inu y.\n    Proof.\n      induction x; cbn.\n      - now rewrite mult_zero.\n      - now rewrite inu_add_hom, IHx, mult_rec.\n    Qed.\n\n\n\n    Lemma add_zero_r n : n i⊕ i0 = n.\n    Proof.\n      pose (phi := $0 ⊕ zero == $0). \n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds. \n      - intros ?. cbn. now rewrite add_zero.\n      - intros x IH rho. \n        specialize (IH (fun _ => i0)); cbn in *.\n        now rewrite add_rec, IH. \n      - now specialize (H n (fun _ => i0)). \n    Qed. \n\n\n    Lemma mult_zero_r n : n i⊗ i0 = i0.\n    Proof.\n      pose (phi := $0 ⊗ zero == zero). \n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds. \n      - intros ?. cbn. now rewrite mult_zero.\n      - intros x IH rho. \n        specialize (IH (fun _ => i0)); cbn in *.\n        now rewrite mult_rec, IH, add_zero. \n      - now specialize (H n (fun _ => i0)).\n    Qed. \n\n\n    Lemma add_rec_r n d : n i⊕ (iσ d) = iσ (n i⊕ d). \n    Proof.\n      pose (phi := ∀ $1 ⊕ (σ $0) == σ ($1 ⊕ $0) ).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros ??. cbn. now rewrite !add_zero.\n      - intros x IH rho y. cbn.\n        specialize (IH (fun _ => i0) y); cbn in *.\n        now rewrite !add_rec, IH.\n      - now specialize (H n (fun _ => i0) d); cbn in *.\n    Qed.\n\n\n    Lemma add_comm n d : n i⊕ d = d i⊕ n.\n    Proof.\n      pose (phi := ∀ $0 ⊕ $1 == $1 ⊕ $0).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros ??; cbn. now rewrite add_zero, add_zero_r.\n      - intros x IH rho.\n        specialize (IH (fun _ => i0)); cbn in *.\n        intros y. now rewrite add_rec, add_rec_r, IH.\n      - now specialize (H n (fun _ => i0) d); cbn in *.\n    Qed.\n\n\n    Lemma add_asso x y z : (x i⊕ y) i⊕ z = x i⊕ (y i⊕ z).\n    Proof.\n      pose (phi := ∀∀ ($2 ⊕ $1) ⊕ $0 == $2 ⊕ ($1 ⊕ $0) ).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros ???. cbn. now rewrite !add_zero.\n      - intros X IH rho Y Z. cbn.\n        specialize (IH (fun _ => i0) Y); cbn in *.\n        now rewrite !add_rec, IH.\n      - now specialize (H x (fun _ => i0) y z); cbn in *.\n    Qed.\n\n\n    Lemma mult_rec_r n d : n i⊗ (iσ d) = n i⊕ (n i⊗ d) . \n    Proof.\n      pose (phi := ∀ $1 ⊗ (σ $0) == $1 ⊕ ($1 ⊗ $0) ).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros ??. cbn. now rewrite !mult_zero, add_zero.\n      - intros x IH rho y. cbn.\n        specialize (IH (fun _ => i0) y); cbn in *.\n        rewrite !mult_rec, IH, <- !add_asso.\n        rewrite add_rec, <- add_rec_r. now rewrite (add_comm y).\n      - now specialize (H n (fun _ => i0) d); cbn in *.\n    Qed.\n\n\n    Lemma mult_comm n d : n i⊗ d = d i⊗ n.\n    Proof.\n      pose (phi := ∀ $0 ⊗ $1 == $1 ⊗ $0).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros ??; cbn. now rewrite mult_zero, mult_zero_r.\n      - intros x IH rho.\n        specialize (IH (fun _ => i0)); cbn in *.\n        intros y. now rewrite mult_rec, mult_rec_r, IH.\n      - now specialize (H n (fun _ => i0) d); cbn in *.\n    Qed.\n\n\n    Lemma distributive x y z : (x i⊕ y) i⊗ z = (x i⊗ z) i⊕ (y i⊗ z).\n    Proof.\n      pose (phi := ∀∀ ($1 ⊕ $0) ⊗ $2 == ($1 ⊗ $2) ⊕ ($0 ⊗ $2) ).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros ???. cbn. now rewrite !mult_zero_r, add_zero.\n      - intros X IH rho Y Z. cbn.\n        specialize (IH (fun _ => i0) Y); cbn in *.\n        rewrite mult_rec_r, IH.\n        rewrite <- add_asso, (add_comm Y Z), (add_asso Z Y).\n        rewrite <- mult_rec_r.\n        rewrite add_comm, <-add_asso, (add_comm _ Z).\n        rewrite <- mult_rec_r.\n        now rewrite add_comm.\n      - now specialize (H z (fun _ => i0) x y); cbn in *.\n    Qed.\n\n\n    Lemma mult_asso x y z : (x i⊗ y) i⊗ z = x i⊗ (y i⊗ z).\n    Proof.\n      pose (phi := ∀∀ ($2 ⊗ $1) ⊗ $0 == $2 ⊗ ($1 ⊗ $0) ).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros ???. cbn. now rewrite !mult_zero.\n      - intros X IH rho Y Z. cbn.\n        specialize (IH (fun _ => i0) Y); cbn in *.\n        now rewrite !mult_rec, <-IH, distributive.\n      - now specialize (H x (fun _ => i0) y z); cbn in *.\n    Qed.\n\n\n    Lemma nolessthen_zero d : ~ d i⧀ i0.\n    Proof. now intros [? []%zero_succ]. Qed.\n\n\n    Lemma zero_or_succ : forall d, d = i0 \\/ exists x, d = iσ x.\n    Proof.\n      pose (phi := $0 == zero ∨ ∃ $1 == σ $0).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros rho. cbn. now left.\n      - intros n IH rho. cbn. right. exists n. reflexivity.\n      - intros d. now specialize (H d (fun _ => i0)); cbn in *.\n    Qed.\n\n    Lemma eq_dec : forall x y : D, x = y \\/ x <> y.\n    Proof.\n      pose (phi := ∀ $1 == $0 ∨ ($1 == $0 --> ⊥)).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros rho d. cbn.\n        destruct (zero_or_succ d) as [|[x ->]].\n        + now left.\n        + right. apply zero_succ.\n      - intros n IH rho. cbn.\n        intros d. destruct (zero_or_succ d) as [-> | [x ->]].\n        + right. intros ?. eapply zero_succ. eauto.\n        + destruct (IH (fun _ => i0) x); cbn in H.\n          left. now rewrite H.\n          right. intros ?%succ_inj. auto.\n      - intros x y. \n        now specialize (H x (fun _ => i0) y); cbn in *.\n    Qed.\n\n    Lemma sum_is_zero x y : x i⊕ y = i0 -> x = i0 /\\ y = i0.\n    Proof.\n      intros H.\n      destruct (zero_or_succ x) as [-> |[? ->]], (zero_or_succ y) as [-> |[? ->]]; auto.\n      - repeat split. now rewrite add_zero in H.\n      - repeat split. rewrite add_rec in H. symmetry in H.\n        now apply zero_succ in H.\n      - split; rewrite add_rec in H; symmetry in H; now apply zero_succ in H.\n    Qed.\n\n    \n    Lemma lt_SS x y : (iσ x) i⧀ (iσ y) <-> x i⧀ y.\n    Proof.\n      split; intros [k Hk]; exists k.\n      - apply succ_inj in Hk. now rewrite <-add_rec.\n      - now rewrite Hk, add_rec. \n    Qed.\n\n    Lemma trichotomy x y : x i⧀ y \\/ x = y \\/ y i⧀ x.\n    Proof.\n      pose (phi := ∀ ($1 ⧀ $0) ∨ ($1 == $0 ∨ $0 ⧀ $1)).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros rho d; cbn. destruct (zero_or_succ d) as [-> | [k ->] ].\n        + now right; left.\n        + left. exists k. now rewrite add_zero.\n      - intros n IH rho d. cbn. destruct (zero_or_succ d) as [-> | [k ->] ].\n        + right; right. exists n. now rewrite add_zero.\n        + specialize (IH (fun _ => i0) k); cbn in IH.\n          rewrite !lt_SS. intuition congruence. \n      - now specialize (H x (fun _ => i0) y); cbn in H.\n    Qed.\n\n\n\n    Lemma add_eq x y t : x i⊕ t = y i⊕ t -> x = y.\n    Proof.\n      pose (phi := ∀∀ $0 ⊕ $2 == $1 ⊕ $2 --> $0 == $1  ).\n      assert (forall n rho, (n.:rho) ⊨ phi).\n      apply induction. repeat solve_bounds.\n      - intros ???. cbn. now rewrite !add_zero_r.\n      - intros T IH rho Y X; cbn in *.\n        rewrite !add_rec_r, <-!add_rec.\n        now intros ?%IH%succ_inj.\n      - now specialize (H t (fun _ => i0) y x); cbn in *.\n    Qed.\n\n\n    Lemma lt_neq x y : x i⧀ y -> x = y -> False.\n    Proof.\n      intros [k Hk] ->. revert Hk.\n      rewrite <-add_rec_r, <-(add_zero_r y) at 1.\n      rewrite !(add_comm y).\n      intros H%add_eq. revert H.\n      apply zero_succ.\n    Qed.\n\n\n    Notation \"x 'i≤' y\" := (exists d : D, y = x i⊕ d)  (at level 40).\n\n    Lemma lt_le_equiv1 x y : x i⧀ iσ y <-> x i≤ y.\n    Proof.\n      split; intros [k Hk].\n      - exists k. now apply succ_inj in Hk.\n      - exists k. congruence.\n    Qed.\n\n\n\n    Lemma lt_S d e : d i⧀ (iσ e) <-> d i⧀ e \\/ d = e.\n    Proof.\n      pose (Φ := ∀ $0 ⧀ σ $1 <--> $0 ⧀ $1 ∨ $0 == $1).\n      assert (H: forall d rho, (d .: rho)⊨ Φ).\n      apply induction.\n      repeat solve_bounds; cbn in H.\n      1,2 : apply vec_cons_inv in H; destruct H as [-> |]; solve_bounds.\n      - intros rho x. cbn; destruct (zero_or_succ x) as [-> | [x' ->]]; cbn; split.\n        + intros _. now right.\n        + intros _. exists i0. now rewrite add_zero.\n        + rewrite lt_SS. now intros ?%nolessthen_zero.\n        + intros [?%nolessthen_zero | E]. tauto.\n          symmetry in E. now apply zero_succ in E.\n      - intros y IH rho x; cbn; destruct (zero_or_succ x) as [-> | [x' ->]].\n        + split.\n        ++ intros _. left. exists y. now rewrite add_zero.\n        ++ intros _. exists (iσ y). now rewrite add_zero.\n        + rewrite !lt_SS, !succ_inj'.\n          specialize (IH rho x'). apply IH.\n      - specialize (H e (fun _ => d) d). apply H.\n    Qed.\n\n    Lemma lt_le_trans {x z} y : x i⧀ y -> y i≤ z -> x i⧀ z.\n    Proof.\n      intros [k1 H1] [k2 H2]. exists (k1 i⊕ k2). rewrite H2, H1.\n      now rewrite add_rec, add_asso.\n    Qed.\n\n    Lemma le_le_trans {x z} y : x i≤ y -> y i≤ z -> x i≤ z.\n    Proof.\n      intros [k1 H1] [k2 H2]. exists (k1 i⊕ k2). rewrite H2, H1.\n      now rewrite add_asso.\n    Qed.\n\n    Lemma add_lt_mono x y t : x i⧀ y -> x i⊕ t i⧀ y i⊕ t.\n    Proof.\n      intros [k Hk]. exists k. rewrite Hk.\n      now rewrite add_rec, !add_asso, (add_comm k t).\n    Qed.\n\n    Lemma add_le_mono x y t : x i≤ y -> x i⊕ t i≤ y i⊕ t.\n    Proof.\n      intros [k Hk]. exists k. rewrite Hk.\n      now rewrite !add_asso, (add_comm k t).\n    Qed.\n\n    Lemma mult_le_mono x y t : x i≤ y -> x i⊗ t i≤ y i⊗ t.\n    Proof.\n      intros [k Hk]. exists (k i⊗ t). rewrite Hk.\n      now rewrite distributive. \n    Qed.\n\n\n\n    Section Euclid.\n\n      (** *** Euclidean Lemma *)\n\n      Lemma iEuclid : \n        forall x q, exists d r, x = d i⊗ q i⊕ r /\\ (i0 i⧀ q -> r i⧀ q).\n      Proof.\n        intros x q.\n        destruct (zero_or_succ q) as [-> | [q_ ->]].\n        - exists i0, x. split.\n          + rewrite mult_zero, add_zero. reflexivity.\n          + now intros ?%nolessthen_zero.\n        - pose (phi := ∀∃∃ $3 == $1 ⊗ (σ $2) ⊕ $0 ∧ (zero ⧀ (σ $2) --> $0 ⧀ (σ $2) ) ).\n          assert (forall n rho, (n.:rho) ⊨ phi).\n          apply induction. unfold sless in *. cbn. cbn in *. repeat solve_bounds.\n          + intros rho d. cbn. exists i0, i0. fold i0. split.\n            * now rewrite mult_zero, add_zero.\n            * tauto.\n          + intros x' IH rho q'. cbn.\n            destruct (IH rho q') as [d' [r' [H ]]]. cbn in *.\n            destruct (eq_dec r' q') as [<- | F].\n            * exists (iσ d'), i0. split.\n              rewrite add_zero_r, H.\n              now rewrite <-add_rec_r, mult_rec, add_comm.\n              tauto.\n            * exists d', (iσ r'). split.\n              now rewrite H, <-add_rec_r.\n              intros _. rewrite lt_SS.\n              assert (r' i≤ q') as G.\n              { rewrite <-lt_le_equiv1.\n                apply H0. exists q'. now rewrite add_zero. }\n              destruct (trichotomy r' q') as [h |[h|h] ]; intuition.\n              exfalso. specialize (lt_le_trans _ h G).\n              intros. now apply (lt_neq q' q').\n          + destruct (H x (fun _ => i0) q_) as [d [r [H1 H2]]]. cbn in H1, H2.\n            exists d, r. split; auto.\n      Qed.\n\n      Lemma iFac_unique1 d q1 r1 q2 r2 : r1 i⧀ d ->\n            r1 i⊕ q1 i⊗ d = r2 i⊕ q2 i⊗ d -> q1 i⧀ q2 -> False.\n      Proof.\n        intros H1 E H. revert E. apply lt_neq.\n        apply lt_le_trans with (d i⊕ q1 i⊗ d).\n        - now apply add_lt_mono.\n        - rewrite <- !mult_rec.\n          apply le_le_trans with (q2 i⊗ d).\n          + apply mult_le_mono.\n            destruct H as [k ->].\n            exists k. now rewrite add_rec.\n          + pattern (q2 i⊗ d) at 2.\n            rewrite <-(add_zero (q2 i⊗ d)).\n            apply add_le_mono.\n            exists r2. now rewrite add_zero.\n      Qed.\n\n\n      (** Uniqueness for the Euclidean Lemma *)\n      \n      Lemma iFac_unique q d1 r1 d2 r2 : r1 i⧀ q -> r2 i⧀ q ->\n            r1 i⊕ d1 i⊗ q = r2 i⊕ d2 i⊗ q -> d1 = d2 /\\ r1 = r2.\n      Proof.\n        intros H1 H2 E.\n        assert (d1 = d2) as ->.\n        - destruct (trichotomy d1 d2) as [ H | [ | H ]]; auto.\n          + exfalso. eapply iFac_unique1. 2: apply E. all: tauto.\n          + exfalso. eapply iFac_unique1. symmetry in E.\n            3: apply H. apply H2. eauto.\n        - repeat split. now apply add_eq in E.\n      Qed.\n\n\n    End Euclid. \n\n\n\n    Lemma lessthen_num : forall n d, d i⧀ inu n -> exists k, k < n /\\ d = inu k.\n    Proof.\n      induction n ; intros d H.\n      - now apply nolessthen_zero in H.\n      - destruct (zero_or_succ d) as [-> | [e ->]].\n        exists 0; split; auto; lia.\n        cbn in H; apply ->lt_SS in H.\n        apply IHn in H.\n        destruct H as [k []].\n        exists (S k); split. lia. cbn; congruence.\n    Qed.\n\n\n    Lemma iEuclid' : forall x y, 0 < y -> exists a b, b < y /\\ x = a i⊗ inu y i⊕ inu b.\n      Proof.\n        intros x y.\n        destruct y as [|y]. lia.\n        destruct (iEuclid x (inu (S y))) as (a & b & H).\n        intros Hy.\n        enough (Hlt : forall x y, x < y -> inu x i⧀ inu y).\n        apply Hlt, H, lessthen_num in Hy.\n        destruct Hy as [r [Hr ->]].\n        exists a, r. split.\n        apply Hr. apply H.\n        intros n m [k <-]%lt_nat_equiv.\n        exists (inu k); cbn. now rewrite inu_add_hom.\n      Qed.\n\n  End PA_Model.\n\n\nEnd Models.\n\n\n\nArguments PAsat {_ _} _.\nNotation \"'PA⊨' phi\" := (forall D (I : interp D) rho, (forall psi : form, PA psi -> rho ⊨ psi) -> rho ⊨ phi) (at level 30).\n\n(** *** Standard Model of PA *)\n\nSection StandartModel.\n\n  Definition interp_nat : interp nat.\n  Proof.\n    split.\n    - destruct f; intros v.\n      + exact 0.\n      + exact (S (Vector.hd v) ).\n      + exact (Vector.hd v + Vector.hd (Vector.tl v) ).\n      + exact (Vector.hd v * Vector.hd (Vector.tl v) ).\n    - destruct P.\n  Defined.\n\n\n  (* We now show that there is a model in which all of PA's axioms hold. *)\n  Lemma PA_std_axioms :\n    forall rho ax, PA ax -> @sat _ _ nat interp_nat _ rho ax. \n  Proof.\n    intros rho ax [a H | H].\n    repeat (destruct H as [<-| H]); cbn ; try congruence.\n    intros []. auto. \n    - right. exists n; auto. \n    - destruct H.\n    - intros H1 IH. intros d. induction d.\n      + apply sat_single in H1. apply H1.\n      + apply IH in IHd. \n        eapply sat_comp, sat_ext in IHd.\n        apply IHd. intros []; now cbn.\n  Qed.\n\n  Lemma Q_std_axioms :\n    forall rho ax, In ax Q -> @sat _ _ nat interp_nat _ rho ax. \n  Proof.\n    intros rho ax H.\n    repeat (destruct H as [<-| H]); cbn ; try congruence.\n    - intros []; auto. right. exists n; auto. \n    - destruct H.\n  Qed.\n\n\n\n  Fact inu_nat_id : forall n, @inu nat interp_nat n = n.\n  Proof.\n    induction n; cbn; congruence.\n  Qed.\n\n\nEnd StandartModel.\n\n\n\nArguments inu {_ _} _.\n\n\n\nSection ND.\n\n  Variable p : peirce.\n\n  Fixpoint iter {X: Type} f n (x : X) :=\n    match n with\n      0 => x\n    | S m => f (iter f m x)\n    end.\n\n  Fact iter_switch {X} f n x : f (@iter X f n x) = iter f n (f x).\n  Proof. induction n; cbn; now try rewrite IHn. Qed.\n\n\n  Lemma subst_up_var k x sigma :\n    x < k -> (var x)`[iter up k sigma] = var x.\n  Proof.\n    induction k in x, sigma |-*.\n    - now intros ?%PeanoNat.Nat.nlt_0_r.\n    - intros H.\n      destruct (Compare_dec.lt_eq_lt_dec x k) as [[| <-]|].\n      + cbn [iter]. rewrite iter_switch. now apply IHk.\n      + destruct x. reflexivity.\n        change (iter _ _ _) with (up (iter up (S x) sigma)).\n        change (var (S x)) with ((var x)`[↑]).\n        rewrite up_term, IHk. reflexivity. constructor.\n      + lia.\n  Qed.\n\n\n  Lemma subst_bounded_term t sigma k : \n    bounded_t k t -> t`[iter up k sigma] = t.\n  Proof.\n    induction 1.\n    - now apply subst_up_var.\n    - cbn. f_equal.\n      rewrite <-(Vector.map_id _ _ v) at 2.\n      apply Vector.map_ext_in. auto.\n  Qed.\n\n\n  Lemma subst_closed_term t sigma :\n    bounded_t 0 t -> t`[sigma] = t.\n  Proof.\n    intros H0.\n    refine (_ (subst_bounded_term t sigma 0 H0)).\n    now cbn.\n  Qed.\n\n\n  Lemma subst_bounded k phi sigma : \n    bounded k phi -> phi[iter up k sigma] = phi.\n  Proof.\n    induction 1 in sigma |-*; cbn.\n    - f_equal.\n      rewrite <-(Vector.map_id _ _ v) at 2.\n      apply Vector.map_ext_in.\n      intros t Ht. apply subst_bounded_term. auto.\n    - now rewrite IHbounded1, IHbounded2.\n    - f_equal; now apply subst_bounded_term.\n    - f_equal.\n      change (up _) with (iter up (S n) sigma).\n      apply IHbounded.\n    - reflexivity.\n  Qed.\n\n\n  Definition exist_times n (phi : form) := iter (fun psi => ∃ psi) n phi.\n\n\n  Lemma up_decompose sigma phi : \n    phi[up (S >> sigma)][(sigma 0)..] = phi[sigma].\n  Proof.\n    rewrite subst_comp. apply subst_ext.\n    intros [].\n    - reflexivity.\n    - apply subst_term_shift.\n  Qed.\n\n\n  Lemma subst_exist_prv {sigma N Gamma} phi :\n    Gamma ⊢ phi[sigma] -> bounded N phi -> Gamma ⊢ exist_times N phi. \n  Proof.\n    induction N in phi, sigma |-*; intros; cbn.\n    - erewrite <-(subst_bounded 0); eassumption.\n    - rewrite iter_switch. eapply (IHN (S >> sigma)).\n      cbn. eapply (ExI (sigma 0)).\n      now rewrite up_decompose.\n      now apply bounded_S_exists.\n  Qed.\n\n\n  Lemma subst_forall_prv phi {N Gamma} :\n    Gamma ⊢ (forall_times N phi) -> bounded N phi -> forall sigma, Gamma ⊢ phi[sigma].\n  Proof.\n    induction N in phi |-*; intros ?? sigma; cbn in *.\n    - change sigma with (iter up 0 sigma).\n      now rewrite (subst_bounded 0).\n    - specialize (IHN (∀ phi) ).\n      rewrite <-up_decompose.\n      apply AllE. apply IHN.\n      unfold forall_times. now rewrite <-iter_switch.\n      now apply bounded_S_forall.\n  Qed.\n\nEnd ND.\n\n\n\nFixpoint join {X n} (v : Vector.t X n) (rho : nat -> X) :=\n    match v with\n    | Vector.nil _ => rho\n    | Vector.cons _ x n w  => join w (x.:rho)\n    end.\n\nNotation \"v '∗' rho\" := (join v rho) (at level 20).\n\n \nSection Q_prv.\n\n  Variable p : peirce.\n\n  Variable Gamma : list form.\n  Variable G : incl Q Gamma.\n\n  Arguments Weak {_ _ _ _}, _.\n\n\n  Lemma reflexivity t : Gamma ⊢ (t == t).\n  Proof.\n    apply (Weak Q).\n    pose (sigma := [t] ∗ var ).\n    change (Q ⊢ _) with (Q ⊢ ($0 == $0)[sigma]).\n    eapply (@subst_forall_prv _ _ 1).\n    apply Ctx. \n    - now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n\n  Lemma symmetry x y : Gamma ⊢ (x == y) -> Gamma ⊢ (y == x).\n  Proof.\n    apply IE. apply (Weak Q).\n    pose (sigma := [x ; y] ∗ var ).\n    change (Q ⊢ _) with (Q ⊢ ($1 == $0 --> $0 == $1)[sigma]).\n    apply (@subst_forall_prv _ _ 2).\n    apply Ctx.\n    - do 1 right; now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n\n  Lemma transitivity x y z :\n    Gamma ⊢ (x == y) -> Gamma ⊢ (y == z) -> Gamma ⊢ (x == z).\n  Proof.\n    intros H. apply IE. revert H; apply IE.\n    apply Weak with Q.\n    pose (sigma := [x ; y ; z] ∗ var).\n    change (Q ⊢ _) with (Q ⊢ ($2 == $1 --> $1 == $0 --> $2 == $0)[sigma]).\n    apply (@subst_forall_prv _ _ 3).\n    apply Ctx.\n    - do 2 right; now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n\n  Lemma eq_succ x y : Gamma ⊢ (x == y) -> Gamma ⊢ (σ x == σ y).\n  Proof.\n    apply IE. apply Weak with Q.\n    pose (sigma := [y ; x] ∗ var ).\n    change (Q ⊢ _) with (Q ⊢ ($0 == $1 --> σ $0 == σ $1)[sigma]).\n    apply (@subst_forall_prv _ _ 2).\n    apply Ctx.\n    - do 3 right; now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n\n  Lemma eq_add {x1 y1 x2 y2} :\n    Gamma ⊢ (x1 == x2) -> Gamma ⊢ (y1 == y2) -> Gamma ⊢ (x1 ⊕ y1 == x2 ⊕ y2).\n  Proof.\n    intros H; apply IE. revert H; apply IE.\n    apply Weak with Q.\n    pose (sigma := [y2 ; y1 ; x2 ; x1] ∗ var).\n    change (Q ⊢ _) with (Q ⊢ ($0 == $1 --> $2 == $3 --> $0 ⊕ $2 == $1 ⊕ $3)[sigma]).\n    apply (@subst_forall_prv _ _ 4).\n    apply Ctx.\n    - do 4 right; now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n\n  Lemma eq_mult {x1 y1 x2 y2} :\n    Gamma ⊢ (x1 == x2) -> Gamma ⊢ (y1 == y2) -> Gamma ⊢ (x1 ⊗ y1 == x2 ⊗ y2).\n  Proof.\n    intros H; apply IE. revert H; apply IE.\n    apply Weak with Q.\n    pose (sigma := [y2 ; y1 ; x2 ; x1] ∗ var).\n    change (Q ⊢ _) with (Q ⊢ ($0 == $1 --> $2 == $3 --> $0 ⊗ $2 == $1 ⊗ $3)[sigma]).\n    apply (@subst_forall_prv _ _ 4).\n    apply Ctx.\n    - do 5 right; now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n\n  Lemma Zero_succ x : \n    Gamma ⊢ ¬ zero == σ x.\n  Proof.\n    apply Weak with Q.\n    pose (sigma := [x] ∗ var).\n    change (Q ⊢ _) with (Q ⊢ (¬ zero == σ $0)[sigma]).\n    apply (@subst_forall_prv _ _ 1).\n    apply Ctx.\n    - do 6 right; now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n\n  Lemma Succ_inj x y : \n    Gamma ⊢ σ x == σ y -> Gamma ⊢ x == y.\n  Proof.\n    intros H; eapply IE. 2: apply H.\n    apply Weak with Q.\n    pose (sigma := [x ; y] ∗ var).\n    change (Q ⊢ _) with (Q ⊢ (σ $1 == σ $0 --> $1 == $0)[sigma]).\n    apply (@subst_forall_prv _ _ 2).\n    apply Ctx.\n    - do 7 right; now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n\n\n  Lemma Add_rec x y : \n    Gamma ⊢ ( (σ x) ⊕ y == σ (x ⊕ y) ).\n  Proof.\n    apply Weak with Q.\n    pose (sigma := [y ; x] ∗ var).\n    change (Q ⊢ _) with (Q ⊢ (σ $0 ⊕ $1 == σ ($0 ⊕ $1))[sigma]).\n    apply (@subst_forall_prv _ _ 2).\n    apply Ctx. \n    - do 9 right; now left.\n    - repeat solve_bounds.\n    - assumption.\n  Qed.\n\n  (** Homomorphism Properties of Numerals *)\n\n  Lemma num_add_homomorphism  x y : \n    Gamma ⊢ ( num x ⊕ num y == num (x + y) ).\n  Proof.\n    induction x; cbn.\n    - pose (phi := zero ⊕ $0 == $0).\n      apply (@AllE _ _ _ _ _ _ phi ).\n      apply Weak with Q.\n      apply Ctx. do 8 right; now left.\n      assumption.\n    - eapply transitivity.\n      apply Add_rec.\n      now apply eq_succ.\n  Qed.\n\n\n  Lemma Mult_rec x y : \n    Gamma ⊢ ( (σ x) ⊗ y == y ⊕ (x ⊗ y) ).\n  Proof.\n    apply Weak with Q.\n    pose (sigma := [x ; y] ∗ var).\n    change (Q ⊢ _) with (Q ⊢ ((σ $1) ⊗ $0 == $0 ⊕ ($1 ⊗ $0))[sigma]).\n    eapply (@subst_forall_prv _ _ 2).\n    apply Ctx. \n    - do 11 right; now left.\n    - repeat solve_bounds.\n    - assumption. \n  Qed.\n\n\n  Lemma num_mult_homomorphism (x y : nat) : \n    Gamma ⊢ ( num x ⊗ num y == num (x * y) ).\n  Proof.\n    induction x; cbn.\n    - pose (phi := zero ⊗ $0 == zero).\n      apply (@AllE _ _ _ _ _ _ phi).\n      apply Weak with Q. apply Ctx; do 10 right; now left.\n      assumption.\n    - eapply transitivity.\n      apply Mult_rec.\n      eapply transitivity.\n      2: apply num_add_homomorphism.\n      apply eq_add. apply reflexivity. apply IHx.\n  Qed.\n\nEnd Q_prv.\n\n\nSection Q_prv.\n\n  Variable p : peirce.\n\n  Variable Gamma : list form.\n  Variable G : incl Q Gamma.\n\n  Derive Signature for Vector.t.\n  \n  Lemma vec_nil_eq X (v : vec X 0) :\n    v = Vector.nil X.\n  Proof.\n    depelim v. reflexivity.\n  Qed.\n\n  Lemma vec_inv1 X (v : vec X 1) :\n    v = [ Vector.hd v ].\n  Proof.\n    repeat depelim v. cbn. reflexivity.\n  Qed.\n\n  Lemma vec_inv2 X (v : vec X 2) :\n    v = [ Vector.hd v ; Vector.hd (Vector.tl v) ].\n  Proof.\n    repeat depelim v. cbn. reflexivity.\n  Qed.\n\n  Lemma map_hd X Y n (f : X -> Y) (v : vec X (S n)) :\n    Vector.hd (Vector.map f v) = f (Vector.hd v).\n  Proof.\n    depelim v. reflexivity.\n  Qed.\n\n  Lemma map_tl X Y n (f : X -> Y) (v : vec X (S n)) :\n    Vector.tl (Vector.map f v) = Vector.map f (Vector.tl v).\n  Proof.\n    depelim v. reflexivity.\n  Qed.\n\n  Lemma vec_in_hd X n (v : vec X (S n)) :\n    vec_in (Vector.hd v) v.\n  Proof.\n    depelim v. constructor.\n  Qed.\n\n  Lemma vec_in_hd_tl X n (v : vec X (S (S n))) :\n    vec_in (Vector.hd (Vector.tl v)) v.\n  Proof.\n    depelim v. constructor. depelim v. constructor.\n  Qed.\n\n  Lemma in_hd X n (v : vec X (S n)) :\n    Vector.In (Vector.hd v) v.\n  Proof.\n    depelim v. constructor.\n  Qed.\n\n  Lemma in_hd_tl X n (v : vec X (S (S n))) :\n    Vector.In (Vector.hd (Vector.tl v)) v.\n  Proof.\n    depelim v. constructor. depelim v. constructor.\n  Qed.\n\n\n  (** Closed terms are numerals. *)\n\n  Lemma closed_term_is_num s : \n    bounded_t 0 s -> { n & Gamma ⊢ s == num n }.\n  Proof.\n    pattern s; revert s. apply term_rect.\n    - intros ? H. exists 0. inversion H; lia.\n    - intros [] v N H; cbn in v.\n      + exists 0. rewrite (vec_nil_eq _ v).\n        now apply reflexivity.\n      + rewrite (vec_inv1 _ v).\n        destruct (N (Vector.hd v)) as [n Hn].\n        apply vec_in_hd.\n        inversion H. subst.\n        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.\n        apply H1. apply in_hd. decide equality.\n        exists (S n); cbn. now apply eq_succ.\n      + rewrite (vec_inv2 _ v).\n        remember (Vector.hd v) as x eqn:Hx.\n        remember (Vector.hd (Vector.tl v)) as y eqn:Hy.\n        destruct (N x) as [n Hn].\n        rewrite Hx. apply vec_in_hd.\n        inversion H. subst.\n        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.\n        apply H1. apply in_hd. decide equality.\n        destruct (N y) as [m Hm].\n        rewrite Hy. apply vec_in_hd_tl.\n        inversion H. subst.\n        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.\n        apply H1. apply in_hd_tl. decide equality.\n        exists (n + m).\n        eapply transitivity.\n        3 : apply num_add_homomorphism.\n        all: try assumption.\n        now apply eq_add.\n      + rewrite (vec_inv2 _ v).\n        remember (Vector.hd v) as x eqn:Hx.\n        remember (Vector.hd (Vector.tl v)) as y eqn:Hy.\n        destruct (N x) as [n Hn].\n        rewrite Hx. apply vec_in_hd.\n        inversion H. subst.\n        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.\n        apply H1. apply in_hd. decide equality.\n        destruct (N y) as [m Hm].\n        rewrite Hy. apply vec_in_hd_tl.\n        inversion H. subst.\n        apply Eqdep_dec.inj_pair2_eq_dec in H2 as ->.\n        apply H1. apply in_hd_tl. decide equality.\n        exists (n * m).\n        eapply transitivity.\n        3 : apply num_mult_homomorphism.\n        all: try assumption.\n        now apply eq_mult.\n  Qed.\n\n\n  Fact num_eq x y : \n    x = y -> Gamma ⊢ num x == num y.\n  Proof.\n    intros ->. now apply reflexivity.\n  Qed.\n\n  Lemma num_neq x : \n    forall y, x <> y -> Gamma ⊢ ¬ num x == num y.\n  Proof.\n    induction x as [| x IHx].\n    - intros [] neq.\n      + congruence.\n      + now apply Zero_succ.\n    - intros [|y] neq.\n      + apply II. eapply IE with (phi := num 0 == num (S x)).\n        eapply Weak with Gamma. now apply Zero_succ.\n        firstorder.\n        apply symmetry; [now right; apply G|].\n        apply Ctx. now left.\n      + apply II. eapply IE with (phi := num x == num y).\n        { eapply Weak with Gamma. apply IHx. \n          - lia. \n          - now right. }\n        apply Succ_inj. \n        ++ now right; apply G.\n        ++ apply Ctx. now left.\n  Qed. \n\n\n  Lemma num_eq_dec x y : \n    { Gamma ⊢ num x == num y } + { Gamma ⊢ ¬ num x == num y }.\n  Proof.\n    destruct (dec_eq_nat x y); [left|right].\n    - now apply num_eq.\n    - now apply num_neq.\n  Qed.  \n\n\n  (** Provability of equality for closed terms is decidable. *)\n  \n  Lemma term_eq_dec s t : \n    bounded_t 0 s -> bounded_t 0 t -> { Gamma ⊢ s == t } + { Gamma ⊢ ¬ s == t }.\n  Proof.\n    intros Hs Ht.\n    destruct (closed_term_is_num s Hs) as [n Hn], (closed_term_is_num t Ht) as [m Hm].\n    destruct (num_eq_dec n m) as [H|H].\n    - left. eapply transitivity; eauto 1.\n      eapply transitivity; eauto 1.\n      apply symmetry; assumption.\n    - right.\n      apply II. eapply IE.\n      apply Weak with Gamma; try apply H; firstorder.\n      eapply transitivity. shelve.\n      2 : eapply Weak with Gamma; try apply Hm.\n      eapply transitivity. shelve.\n      eapply Weak with Gamma. apply symmetry in Hn. apply Hn.\n      assumption. shelve.\n      apply Ctx. Unshelve.\n      + now left.\n      + now right.\n      + right. now apply G.\n      + right. now apply G.\n      + now right.\n  Qed.\n\n\n  Lemma num_lt x y :\n    x < y -> Gamma ⊢ num x ⧀ num y.\n  Proof.\n    intros [k Hk]%lt_nat_equiv.\n    apply ExI with (t := num k). cbn.\n    rewrite !num_subst, <-Hk. cbn.\n    apply eq_succ. easy.\n    apply symmetry, num_add_homomorphism; easy.\n  Qed.\n\n  Lemma not_lt_zero_prv' :\n  Q ⊢ ∀ ¬ $0 ⧀ num 0.\n  Proof.\n    apply AllI, II. eapply ExE.\n    - apply Ctx. now left.\n    - cbn. eapply IE.\n      + pose (s := $1 ⊕ $0).\n        apply Zero_succ with (x := s).\n        right; now right.\n      + apply Ctx. now left.\n  Qed.\n\n  Lemma not_lt_zero_prv t :\n    Q ⊢ ¬ t ⧀ num 0.\n  Proof.\n    change (Q ⊢ (¬ $0 ⧀ num 0)[t..]).\n    apply AllE, not_lt_zero_prv'.\n  Qed.\n\n  Lemma Faster3 :\n    forall A, Q <<= A ++ map (subst_form ↑) Q.\n  Proof.\n    intros A; induction A; cbn.\n    - firstorder.\n    - right. now apply IHA.\n  Qed.\n\n  Lemma num_nlt x :\n    forall y, ~ (x < y) -> Q ⊢ ¬ num x ⧀ num y.\n  Proof.\n    induction x as [| x IHx].\n    - intros [] ineq.\n      + apply not_lt_zero_prv.\n      + lia.\n    - intros [|y] ineq.\n      + apply not_lt_zero_prv.\n      + assert (~ x < y) as H % IHx by lia.\n        apply II. eapply IE.\n        { eapply Weak; [apply H | now right]. }\n        eapply ExE.\n        * apply Ctx. now left.\n        * apply ExI with (t := $0).\n          cbn. rewrite !num_subst.\n          eapply transitivity. right; now right.\n          2 : {apply Add_rec. right; now right. }\n          apply Succ_inj. right; now right.\n          apply Ctx. now left.\n  Qed. \n  \n  \n  Lemma num_lt_dec x y :\n    { Gamma ⊢ num x ⧀ num y } + { Gamma ⊢ ¬ num x ⧀ num y }.\n  Proof.\n    destruct (lt_dec x y); [left|right].\n    - now apply num_lt.\n    - apply Weak with Q; [now apply num_nlt | assumption].\n  Qed.\n\n\n  Lemma term_lt_dec s t :\n    map (subst_form ↑) Gamma = Gamma -> bounded_t 0 s -> bounded_t 0 t -> { Gamma ⊢ s ⧀ t } + { Gamma ⊢ ¬ s ⧀ t }.\n  Proof.\n    intros HG Hs Ht.\n    destruct (closed_term_is_num s Hs) as [n Hn], (closed_term_is_num t Ht) as [m Hm].\n    destruct (num_lt_dec n m) as [H|H].\n    - left. eapply ExE. apply H.\n      apply ExI with (t0:=$0).\n      rewrite !num_subst, HG. cbn.\n      repeat rewrite (subst_closed_term t), (subst_closed_term s); auto. \n      eapply transitivity.\n      2 : { eapply Weak. apply Hm. now right. }\n      now right; apply G.\n      apply symmetry. now right; apply G.\n      pose (j := σ (num n ⊕ $0)).\n      eapply transitivity with (y:= j); unfold j. now right; apply G.\n      apply eq_succ. now right; apply G.\n      apply eq_add. now right; apply G.\n      eapply Weak. apply Hn. now right.\n      apply reflexivity. now right; apply G.\n      apply symmetry. now right; apply G.\n      apply Ctx; now left.\n    - right. apply II. eapply IE.\n      eapply Weak. apply H. now right.\n      eapply ExE. apply Ctx; now left.\n      apply ExI with (t0:=$0).\n      cbn. rewrite !num_subst.\n      repeat rewrite (subst_closed_term t), (subst_closed_term s), HG; auto.\n      apply symmetry in Hm; auto.\n      apply symmetry in Hn; auto.\n      eapply transitivity.\n      2 : { eapply Weak. apply Hm. right; now right. }\n      now right; right; apply G.\n      apply symmetry. now right; right; apply G.\n      pose (j := σ (s ⊕ $0)).\n      eapply transitivity with (y:= j); unfold j. \n      now right; right; apply G.\n      apply eq_succ. now right; right; apply G.\n      apply eq_add. now right; right; apply G.\n      eapply Weak. apply Hn. now right; right.\n      apply reflexivity. now right; right; apply G.\n      apply symmetry. now right; right; apply G.\n      apply Ctx; now left.\n  Qed.\n\n\nEnd Q_prv.\n\n\nDefinition std {D I} d := exists n, @inu D I n = d.\nDefinition stdModel D {I} := forall d, exists n, (@inu D I) n = d.\nDefinition nonStd D {I} := exists e, ~ @std D I e.\nDefinition notStd D {I} := ~ @stdModel D I.\n\nFact nonStd_notStd {D I} :\n  @nonStd D I -> ~ stdModel D.\nProof.\n  intros [e He] H; apply He, H.\nQed.\n\nNotation \"⊨ phi\" := (forall rho, rho ⊨ phi) (at level 21).\n\nSection stdModel.\n\n  Variable D : Type.\n  Variable I : interp D.\n  Variable axioms : forall ax, PA ax -> ⊨ ax.\n\n  Definition nat_hom (f : nat -> D) := \n    f 0 = @inu D I 0\n    /\\ forall n, f (S n) = iσ (f n).\n  Definition stdModel' := exists f, nat_hom f /\\ bij f.\n\n  Lemma hom_agree_inu f :\n    nat_hom f -> forall x, f x = inu x.\n  Proof.\n    intros [H0 H] x. induction x as [| x IH].\n    - assumption.\n    - cbn. now rewrite H, IH.\n  Qed.\n\n  Lemma stdModel_eqiv :\n    stdModel' <-> @stdModel D I.\n  Proof.\n    split.\n    - intros (f & Hf & [inj surj]) e.\n      destruct (surj e) as [n <-].\n      exists n. now rewrite (hom_agree_inu _ Hf).\n    - intros H. exists inu. repeat split.\n      + intros ???. now eapply inu_inj.\n      + apply H.\n  Qed.\n\nEnd stdModel.\n", "meta": {"author": "HermesMarc", "repo": "Tennenbaum-CTT", "sha": "6e5b15df59f35cad91a0c6de679a31374a160cf0", "save_path": "github-repos/coq/HermesMarc-Tennenbaum-CTT", "path": "github-repos/coq/HermesMarc-Tennenbaum-CTT/Tennenbaum-CTT-6e5b15df59f35cad91a0c6de679a31374a160cf0/Peano.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7043716512192713}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Graphs                                                                  *\n**************************************************************************)\n\n(* under construction *)\n\nSet Implicit Arguments.\nRequire Import LibCore LibSet.\n\n(*-----------------------------------------------------------*)\n\nDefinition value_nonneg A (f:A->int) (P:A->Prop) :=\n  forall x, P x -> f x >= 0.\n\n(*-----------------------------------------------------------*)\n\nParameter graph : Type -> Type.\nParameter nodes : forall A, graph A -> set int.\nParameter edges : forall A, graph A -> set (int*int*A).\n\nDefinition has_edge A (g:graph A) x y w :=\n  (x,y,w) \\in edges g.\n\nParameter has_edge_nodes : forall A (g : graph A) x y w,\n  has_edge g x y w -> x \\in nodes g /\\ y \\in nodes g.\n\nLemma has_edge_in_nodes_l : forall A (g : graph A) x y w,\n  has_edge g x y w -> x \\in nodes g.\nProof using. intros. forwards*: has_edge_nodes. Qed.\n\nLemma has_edge_in_nodes_r : forall A (g : graph A) x y w,\n  has_edge g x y w -> y \\in nodes g.\nProof using. intros. forwards*: has_edge_nodes. Qed.\n\nDefinition nonneg_edges (g:graph int) :=\n  forall x y w, has_edge g x y w -> w >= 0.\n  (* forall x y, value_nonneg id (has_edge g x y) *)\n\n(*-----------------------------------------------------------*)\n\nDefinition path A := list (int*int*A).\n\nInductive is_path A (g:graph A) : int -> int -> path A -> Prop :=\n  | is_path_nil : forall x,\n      x \\in nodes g ->\n      is_path g x x nil\n  | is_path_cons : forall x y z w p,\n      is_path g x y p ->\n      has_edge g y z w ->\n      is_path g x z ((y,z,w)::p).\n\nLemma is_path_in_nodes_l : forall A (g:graph A) x y p,\n  is_path g x y p -> x \\in nodes g.\nProof using. introv H. induction~ H. Qed.\n\nLemma is_path_in_nodes_r : forall A (g:graph A) x y p,\n  is_path g x y p -> y \\in nodes g.\nProof using. introv H. inverts~ H. apply* has_edge_in_nodes_r. Qed.\n\nLemma is_path_cons_has_edge : forall A (g:graph A) x y z w p,\n  is_path g x z ((y,z,w)::p) -> has_edge g y z w.\nProof using. introv H. inverts~ H. Qed.\n\n(*-----------------------------------------------------------*)\n\nDefinition weight (p:path int) :=\n  nosimpl (fold_right (fun e acc => let '(_,_,w) := e in w+acc) 0 p).\n\nLemma weight_nil :\n  weight (nil : path int) = 0.\nProof using. auto. Qed.\n\nLemma weight_cons : forall (p:path int) x y w,\n  weight ((x,y,w)::p) = w + weight p.\nProof using. intros. unfold weight. rew_list~. Qed.\n\n(** A graph with nonnegative edges has only paths\n    of nonnegative weight *)\n\nLemma nonneg_edges_to_path : forall g,\n  nonneg_edges g -> forall x y,\n  value_nonneg weight (is_path g x y).\nProof using.\n  introv NG H. induction H.\n  rewrite weight_nil. math.\n  rewrite weight_cons. forwards: NG H0. math.\nQed.\n\n", "meta": {"author": "zhiyuanshi", "repo": "intersection", "sha": "825f69cf7f70db7d0b829875f590fa38468bfad1", "save_path": "github-repos/coq/zhiyuanshi-intersection", "path": "github-repos/coq/zhiyuanshi-intersection/intersection-825f69cf7f70db7d0b829875f590fa38468bfad1/workinprogress/semantics/tlc/src/LibGraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7043716387390427}}
{"text": "Require Export Unicode.Utf8_core.\nRequire Import Bool List Le String Showable HoTT.\n\nSet Implicit Arguments.\nSet Universe Polymorphism.\n\n(** * The Decidable Class *)\n\n(** This code is mostly imported from\n[https://github.com/HoTT/HoTT]. We are defining it here to be\nindependent of the Coq/HoTT library.\n\nWe can not use the Decidable class of Coq because its definition is in\n[Prop] (using [\\/]) instead of [Type] (using [+]). All the predicates\ndefined in this file are proof-relevant.\n*)\n\n(** ** Decidability *)\n\n(* =Decidable= *)\nClass Decidable (A: HProp) := dec: A + (not A).\n(* =end= *)\n\nArguments dec A {_}.\n\n\n(**\n\nA [DecidableProp] [A] is, essentially, isomorphic to [Bool]: it is\neither [true] or [false].\n\n *)\n\n(* Class DecidableProp (A : Type) := { *)\n(*     dec_p :> Decidable A; *)\n(*     is_hprop_p :> IsHProp A }. *)\n\n(* Instance DecidableProp_Decidable_HProp (A : Type) {Hdec: Decidable A} *)\n(*          {Hprop:IsHProp A} : DecidableProp A := *)\n(*   {|dec_p := Hdec ; is_hprop_p := Hprop |}. *)\n\n\n(** \n\nThe canonical example of a [DecidableProp] is the decidable equality\nfor a type [A], as per Hedberg theorem. We package it in a dedicated\nclass.\n\n*)\n\nClass DecidablePaths (A : HSet) := { \n  dec_paths : forall a b : A, Decidable (hprop (a = b))\n}.\n\n(**\n\nHedberg theorem is a standard theorem of HoTT: it states that if a\ntype [A] has decidable equality, then it is a hSet, i.e. its equality\nis proof-irrelevant. See the proof at [https://github.com/HoTT] in\n[HoTT/theories/Basics/Decidable.v] *)\n\nInstance Hedberg A (dec_paths_ : forall a b : A, ((a = b) + (not (a = b)))%type)\n  : IsHSet A.\nProof. \nintros a b.\nassert (lemma: forall p: a = b,  \n    match dec_paths_ a a, dec_paths_ a b with\n    | inl r, inl s => p = r^ @ s\n    | _, _ => False\n    end).\n{\n  destruct p.\n  destruct (dec_paths_ a a) as [pr | f].\n  apply inverse_left_inverse.\n  specialize (f eq_refl).\n  inversion f.\n}\n\nintros p q.\nassert (p_given_by_dec := lemma p).\nassert (q_given_by_dec := lemma q).\ndestruct (dec_paths_ a a); try contradiction.\ndestruct (dec_paths_ a b); try contradiction.\napply (p_given_by_dec @ q_given_by_dec ^).\nDefined.\n\nInstance DecidablePaths_DecidableProp A\n   (DecidablePaths_A : DecidablePaths A)\n  : forall (a b : A), Decidable (hprop (a = b)).\nintros. exact (@dec_paths _ DecidablePaths_A _ _). \nDefined.\n\n(** ** Checkability *)\n\n(**\n\n  A [Checkable] type is a type that contains a decidable subset\n  [checkP]. Moreover, it is [CheckableProp] if its elements are\n  proof-irrelevant.\n\n *)\n\n(* =Checkable= *)\nClass Checkable (A: HProp) := {\n    check: HProp;\n    check_dec: Decidable check ;\n    convert: check -> A\n}.\n(* =end= *)\n\nArguments check _ {_}.\n\n\n(** A decidable type is checkable (over all its elements). *)\n\nInstance decidable_is_checkable A {H:Decidable A} : Checkable A\n  := {| check := A ; check_dec := H ; convert := id |}.\n\n(** We can project the [Decidable] property out of [Checkable]: *)\n\nInstance checkable_decidable A {H:Checkable A} : Decidable (@check _ H)\n  := check_dec.\n\n\n(** ** A few instances *)\n\n\n(** ***  Reflecting a boolean as a decidable property *)\n\nInstance Decidable_bool (t : bool) : Decidable (hprop (Is_true t)) :=\n  match t with\n    | true => inl tt\n    | false => inr id\n  end.\n\n(* Connexion to a boolean version of decidable as in \n   native-coq/theories/Classes/DecidableClass.v \n*)\n\n(*\nClass Decidable_relate (P : Type) := {\n  Decidable_witness : bool;\n  Decidable_spec : Decidable_witness = true <-> P\n}.\n\n(* Decidable_relate and Decidable are equivalent *)\n\nInstance Dec_relate_Decidable P (HP: Decidable_relate P) : \n  Decidable P.\ndestruct HP as [witness spec]. destruct witness.\n- left. exact (proj1 spec eq_refl).\n- right. intro p. pose (proj2 spec p). inversion e.\nDefined.\n\nDefinition Decidable_Dec_relate P (HP: Decidable P) :\n  Decidable_relate P.\ncase HP; intro p.\n- refine {| Decidable_witness := true |}.  split; auto.\n- refine {| Decidable_witness := false |}. split; auto.\n  intro e; inversion e.\nDefined.\n*)\n\n(** ***  Instances for bool *)\n\nDefinition absurd_eq_bool : not (true = false).\nProof.\n  inversion 1.\nDefined. \n\n(* =Decidable_eq_bool= *)\nDefinition Decidable_eq_bool (x y : bool) : (x = y) + not (x = y) :=\n  match x,y with\n    true, true   => inl eq_refl\n  | false, false => inl eq_refl\n  | true, false  => inr absurd_eq_bool\n  | false, true  => inr (absurd_eq_bool ° inverse)\n  end.\n(* =end= *)\n\nInstance IsHSet_bool : IsHSet bool := Hedberg Decidable_eq_bool.\n\nInstance DecidablePaths_bool : DecidablePaths (hset bool) := \n  { dec_paths := Decidable_eq_bool }.\n\n(** ***  Instances for nat *)\n\nDefinition Decidable_eq_nat : forall (x y : nat),  (x = y) + not (x = y).\ninduction x.\n- destruct y.\n + left ;reflexivity.\n + right; intro H; inversion H.\n- induction y.\n  + right; intro H; inversion H.\n  + case (IHx y). intro H. left. exact (f_equal S H).\n    intro H; right. intro e. inversion e. apply (H H1).\nDefined.\n\nInstance IsHSet_nat : IsHSet nat := Hedberg Decidable_eq_nat.\n\nInstance DecidablePaths_nat : DecidablePaths (hset nat) := \n  { dec_paths := Decidable_eq_nat }.\n\nDefinition Hnat : HSet := hset nat.\n\n(** *** Instances for list *)\n\nDefinition Decidable_eq_list : forall (A:HSet) (HA: DecidablePaths A) \n  (x y: list A),  (x = y) + not (x = y).\nintros A HA. induction x.\n- destruct y.\n  + left; reflexivity.\n  + right; intro H; inversion H.\n- induction y.\n  + right; intro H; inversion H.\n  + case (dec_paths a a0); intro H. \n    * case (IHx y); intro Hl.\n      left. rewrite H. rewrite Hl. reflexivity.\n      right. rewrite H. unfold not in *. \n      intro Hc. inversion Hc. exact (Hl H1).\n    * right. unfold not in *. \n      intro Hc. inversion Hc. exact (H H1).\nDefined.\n\n(** *** Instance for decidable equality on list *)\n\nInstance IsHSet_list (A:HSet) HA : IsHSet (list A) := Hedberg (@Decidable_eq_list A HA).\n\nInstance DecidablePaths_list : \n  forall A (HA: DecidablePaths A), DecidablePaths (hset (list A)) := \n    { dec_paths := Decidable_eq_list HA }.\n\n(** *** Instance for less than *)\n\nDefinition Decidable_le_nat : forall (x y : nat), (x <= y) + not (x <= y).\ninduction x.\n- destruct y.\n + left; reflexivity.\n + left. apply le_S, le_0_n. \n- induction y.\n  + right. intro e. destruct (le_Sn_0 _ e).\n  + case (IHx y). intro H. left. exact (le_n_S _ _ H).\n    intro H; right. intro. apply H. exact (le_S_n _ _ H0). \nDefined.\n\n(** *** Instances for option *)\n\nDefinition Decidable_eq_option : forall A (HA: DecidablePaths A) \n  (x y: option A), (x = y) + not (x = y).\nintros. destruct x as [a|]; destruct y as [a0 |].\n- case (dec_paths a a0); intro H.\n  + left. rewrite H. reflexivity.\n  + right. unfold not in *. intro Hc. inversion Hc. \n    exact (H H1).\n- right. unfold not. intro Hc. inversion Hc.\n- right. unfold not. intro Hc. inversion Hc.\n- left. reflexivity.\nDefined.\n\nInstance IsHSet_option (A:HSet) HA : IsHSet (option A) := Hedberg (@Decidable_eq_option A HA).\n\nInstance DecidablePaths_option :\n  forall A (HA: DecidablePaths A), DecidablePaths (hset (option A)) := \n    { dec_paths := Decidable_eq_option HA }.\n\n(** *** Instances for logical connectives *)\n\nInstance Decidable_and P Q (HP : Decidable P) \n (HQ : Decidable Q) : Decidable (hprop (P * Q)).\ndestruct HP as [p | n].\n- destruct HQ as [q| n]. \n  + exact (inl (p, q)).\n  + apply inr. intro H. exact (n (snd H)).\n- apply inr. intro H. exact (n (fst H)).\nDefined.\n\n(* Instance Decidable_or P Q (HP : Decidable P) *)\n(*         (HQ : Decidable Q) : Decidable (hprop (P + Q) _). *)\n(* destruct HP. *)\n(* - exact (inl (inl p)). *)\n(* - destruct HQ.  *)\n(*   + exact (inl (inr q)). *)\n(*   + apply inr. intro H. case H; auto. *)\n(* Defined. *)\n\n\nInstance Decidable_not P (HP : Decidable P): \n  Decidable (hprop (not P)).\ncase HP; intro H.\n- exact (inr (fun X => X H)).\n- exact (inl H).\nDefined.\n\nInstance Decidable_implies P Q (HP : Decidable P) \n  (HQ : Decidable Q) : Decidable (hprop (P -> Q)).\ndestruct HQ as [q | n].\n- exact (inl (fun _ => q)).\n- destruct HP as [p | n0]. \n  + apply inr. intro H. exact (n (H p)).\n  + apply inl. intro p. destruct (n0 p).\nDefined.\n\n\nInstance Decidable_True : Decidable (hprop True) := inl I.\n\nInstance Decidable_False : Decidable (hprop False).\nright. destruct 1.\nDefined. \n\nInstance Hprop_unit : IsHProp unit.\nProof.\n  intros x y. destruct x, y; reflexivity.\nDefined. \n\nInstance DecidablePaths_unit : DecidablePaths (hset unit).\neconstructor. intros x y. destruct x, y. exact (inl eq_refl).\nDefined.\n\n(** *** Decidability of proven properties *)\n\nInstance Decidable_proven (P : HProp) (ev :  P):  Decidable P :=\n  inl ev.\n\n(*\nInstance DecidablePaths_prod A B `{DecidablePaths A} `{DecidablePaths B}:\n  DecidablePaths (hset (A*B) _).\neconstructor. intros (a,b) (a',b').\ndestruct (dec (a = a')), (dec (b=b'));\n  try solve [apply inr; intro H'; inversion H'; auto].\napply inl. subst. reflexivity. \nDefined.\n\nInstance DecidablePaths_fun A B A'\n         (H : forall a, DecidablePaths (B a)) (f : A' -> A)\n  a' : DecidablePaths (B (f a')) .\nProof.\n  auto with typeclass_instances.\nDefined.\n\n\n*)", "meta": {"author": "CoqHott", "repo": "DICoq", "sha": "6abf83fbf3a78f45885760afa700c26a804f7ccc", "save_path": "github-repos/coq/CoqHott-DICoq", "path": "github-repos/coq/CoqHott-DICoq/DICoq-6abf83fbf3a78f45885760afa700c26a804f7ccc/Decidable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7043422641353223}}
{"text": "(** * BasicTactics: Additional Basic Coq Tactics *)\n\nRequire Export Poly.\n\n(** This chapter introduces several more proof strategies and\n    tactics that, together, allow us to prove theorems about the\n    functional programs we have been writing. In particular, we'll\n    reason about functions that work with natural numbers and\n    lists. We will see:\n\n    - how to use auxiliary lemmas, in both forwards and backwards reasoning;\n    - how to reason about data constructors, which are injective and disjoint;\n    - how to create a strong induction hypothesis (and when\n      strengthening is required); and\n    - how to reason by case analysis.\n *)\n\n(* ###################################################### *)\n(** * The [apply] Tactic *)\n\n(** We often encounter situations where the goal to be proved is\n    exactly the same as some hypothesis in the context or some\n    previously proved lemma. *)\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m  ->\n     [n;o] = [n;p] ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  (* At this point, we could finish with \n     \"[rewrite -> eq2. reflexivity.]\" as we have \n     done several times above. But we can achieve the\n     same effect in a single step by using the \n     [apply] tactic instead: *)\n  apply eq2.  Qed.\n\n(** The [apply] tactic also works with _conditional_ hypotheses\n    and lemmas: if the statement being applied is an implication, then\n    the premises of this implication will be added to the list of\n    subgoals needing to be proved. *)\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m  ->\n     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->\n     [n;o] = [m;p].\nProof.\n  intros n m o p eq1 eq2. \n  apply eq2. apply eq1.  Qed.\n\n(** You may find it instructive to experiment with this proof\n    and see if there is a way to complete it using just [rewrite]\n    instead of [apply]. *)\n\n(** Typically, when we use [apply H], the statement [H] will\n    begin with a [forall] binding some _universal variables_.  When\n    Coq matches the current goal against the conclusion of [H], it\n    will try to find appropriate values for these variables.  For\n    example, when we do [apply eq2] in the following proof, the\n    universal variable [q] in [eq2] gets instantiated with [n] and [r]\n    gets instantiated with [m]. *)\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m)  ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1.  Qed.\n\n(** **** Exercise: 2 stars, optional (silly_ex)  *)\n(** Complete the following proof without using [simpl]. *)\n\nTheorem silly_ex : \n     (forall n, evenb n = true -> oddb (S n) = true) ->\n     evenb 3 = true ->\n     oddb 4 = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** To use the [apply] tactic, the (conclusion of the) fact\n    being applied must match the goal _exactly_ -- for example, [apply]\n    will not work if the left and right sides of the equality are\n    swapped. *)\n\nTheorem silly3_firsttry : forall (n : nat),\n     true = beq_nat n 5  ->\n     beq_nat (S (S n)) 7 = true.\nProof.\n  intros n H.\n  simpl.\n  (* Here we cannot use [apply] directly *)\nAbort.\n\n(** In this case we can use the [symmetry] tactic, which switches the\n    left and right sides of an equality in the goal. *)\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  symmetry.\n  simpl. (* Actually, this [simpl] is unnecessary, since \n            [apply] will perform simplification first. *)\n  apply H.  Qed.         \n\n(** **** Exercise: 3 stars (apply_exercise1)  *)\n(** Hint: you can use [apply] with previously defined lemmas, not\n    just hypotheses in the context.  Remember that [SearchAbout] is\n    your friend. *)\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n     l = rev l' ->\n     l' = rev l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 1 star, optional (apply_rewrite)  *)\n(** Briefly explain the difference between the tactics [apply] and\n    [rewrite].  Are there situations where both can usefully be\n    applied?\n  (* FILL IN HERE *)\n*)\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [apply ... with ...] Tactic *)\n\n(** The following silly example uses two rewrites in a row to\n    get from [[a,b]] to [[e,f]]. *)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.\n\n(** Since this is a common pattern, we might\n    abstract it out as a lemma recording once and for all\n    the fact that equality is transitive. *)\n\nTheorem trans_eq : forall (X:Type) (n m o : X),\n  n = m -> m = o -> n = o.\nProof.\n  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. \n  reflexivity.  Qed.\n\n(** Now, we should be able to use [trans_eq] to\n    prove the above example.  However, to do this we need\n    a slight refinement of the [apply] tactic. *)\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n     [a;b] = [c;d] ->\n     [c;d] = [e;f] ->\n     [a;b] = [e;f].\nProof.\n  intros a b c d e f eq1 eq2. \n  (* If we simply tell Coq [apply trans_eq] at this point,\n     it can tell (by matching the goal against the\n     conclusion of the lemma) that it should instantiate [X]\n     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].\n     However, the matching process doesn't determine an\n     instantiation for [m]: we have to supply one explicitly\n     by adding [with (m:=[c,d])] to the invocation of\n     [apply]. *)\n  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.\n\n(**  Actually, we usually don't have to include the name [m]\n    in the [with] clause; Coq is often smart enough to\n    figure out which instantiation we're giving. We could\n    instead write: [apply trans_eq with [c,d]]. *)\n\n(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)\nExample trans_eq_exercise : forall (n m o p : nat),\n     m = (minustwo o) ->\n     (n + p) = m ->\n     (n + p) = (minustwo o). \nProof.\n  intros. rewrite H0. apply H.\nQed.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * The [inversion] tactic *)\n\n(** Recall the definition of natural numbers:\n     Inductive nat : Type :=\n       | O : nat\n       | S : nat -> nat.\n    It is clear from this definition that every number has one of two\n    forms: either it is the constructor [O] or it is built by applying\n    the constructor [S] to another number.  But there is more here than\n    meets the eye: implicit in the definition (and in our informal\n    understanding of how datatype declarations work in other\n    programming languages) are two other facts:\n\n    - The constructor [S] is _injective_.  That is, the only way we can\n      have [S n = S m] is if [n = m].\n\n    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not\n      equal to [S n] for any [n]. *)\n\n(** Similar principles apply to all inductively defined types: all\n    constructors are injective, and the values built from distinct\n    constructors are never equal.  For lists, the [cons] constructor is\n    injective and [nil] is different from every non-empty list.  For\n    booleans, [true] and [false] are unequal.  (Since neither [true]\n    nor [false] take any arguments, their injectivity is not an issue.) *)\n\n(** Coq provides a tactic called [inversion] that allows us to exploit\n    these principles in proofs.\n \n    The [inversion] tactic is used like this.  Suppose [H] is a\n    hypothesis in the context (or a previously proven lemma) of the\n    form\n      c a1 a2 ... an = d b1 b2 ... bm\n    for some constructors [c] and [d] and arguments [a1 ... an] and\n    [b1 ... bm].  Then [inversion H] instructs Coq to \"invert\" this\n    equality to extract the information it contains about these terms:\n\n    - If [c] and [d] are the same constructor, then we know, by the\n      injectivity of this constructor, that [a1 = b1], [a2 = b2],\n      etc.; [inversion H] adds these facts to the context, and tries\n      to use them to rewrite the goal.\n\n    - If [c] and [d] are different constructors, then the hypothesis\n      [H] is contradictory.  That is, a false assumption has crept\n      into the context, and this means that any goal whatsoever is\n      provable!  In this case, [inversion H] marks the current goal as\n      completed and pops it off the goal stack. *)\n\n(** The [inversion] tactic is probably easier to understand by\n    seeing it in action than from general descriptions like the above.\n    Below you will find example theorems that demonstrate the use of\n    [inversion] and exercises to test your understanding. *)\n\nTheorem eq_add_S : forall (n m : nat),\n     S n = S m ->\n     n = m.\nProof.\n  intros n m eq. inversion eq. reflexivity.  Qed.\n\nTheorem silly4 : forall (n m : nat),\n     [n] = [m] ->\n     n = m.\nProof.\n  intros n o eq. inversion eq. reflexivity.  Qed.\n\n(** As a convenience, the [inversion] tactic can also\n    destruct equalities between complex values, binding\n    multiple variables as it goes. *)\n\nTheorem silly5 : forall (n m o : nat),\n     [n;m] = [o;o] ->\n     [n] = [m].\nProof.\n  intros n m o eq. inversion eq. reflexivity. Qed.\n\n(** **** Exercise: 1 star (sillyex1)  *) \nExample sillyex1 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = z :: j ->\n     y :: l = x :: j ->\n     x = y.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\nTheorem silly6 : forall (n : nat),\n     S n = O ->\n     2 + 2 = 5.\nProof.\n  intros n contra. inversion contra. Qed.\n\nTheorem silly7 : forall (n m : nat),\n     false = true ->\n     [n] = [m].\nProof.\n  intros n m contra. inversion contra.  Qed.\n\n(** **** Exercise: 1 star (sillyex2)  *)\nExample sillyex2 : forall (X : Type) (x y z : X) (l j : list X),\n     x :: y :: l = [] ->\n     y :: l = z :: j ->\n     x = z.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** While the injectivity of constructors allows us to reason\n    [forall (n m : nat), S n = S m -> n = m], the reverse direction of\n    the implication is an instance of a more general fact about\n    constructors and functions, which we will often find useful: *)\n\nTheorem f_equal : forall (A B : Type) (f: A -> B) (x y: A), \n    x = y -> f x = f y. \nProof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed. \n\n\n\n\n(** **** Exercise: 2 stars, optional (practice)  *)\n(** A couple more nontrivial but not-too-complicated proofs to work\n    together in class, or for you to work as exercises. *)\n \n\nTheorem beq_nat_0_l : forall n,\n   beq_nat 0 n = true -> n = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n\nTheorem beq_nat_0_r : forall n,\n   beq_nat n 0 = true -> n = 0.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Using Tactics on Hypotheses *)\n\n(** By default, most tactics work on the goal formula and leave\n    the context unchanged.  However, most tactics also have a variant\n    that performs a similar operation on a statement in the context.\n\n    For example, the tactic [simpl in H] performs simplification in\n    the hypothesis named [H] in the context. *)\n\nTheorem S_inj : forall (n m : nat) (b : bool),\n     beq_nat (S n) (S m) = b  ->\n     beq_nat n m = b. \nProof.\n  intros n m b H. simpl in H. apply H.  Qed.\n\n(** Similarly, the tactic [apply L in H] matches some\n    conditional statement [L] (of the form [L1 -> L2], say) against a\n    hypothesis [H] in the context.  However, unlike ordinary\n    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),\n    [apply L in H] matches [H] against [L1] and, if successful,\n    replaces it with [L2].\n \n    In other words, [apply L in H] gives us a form of \"forward\n    reasoning\" -- from [L1 -> L2] and a hypothesis matching [L1], it\n    gives us a hypothesis matching [L2].  By contrast, [apply L] is\n    \"backward reasoning\" -- it says that if we know [L1->L2] and we\n    are trying to prove [L2], it suffices to prove [L1].  \n\n    Here is a variant of a proof from above, using forward reasoning\n    throughout instead of backward reasoning. *)\n\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  symmetry in H. apply eq in H. symmetry in H. \n  apply H.  Qed.\n\n(** Forward reasoning starts from what is _given_ (premises,\n    previously proven theorems) and iteratively draws conclusions from\n    them until the goal is reached.  Backward reasoning starts from\n    the _goal_, and iteratively reasons about what would imply the\n    goal, until premises or previously proven theorems are reached.\n    If you've seen informal proofs before (for example, in a math or\n    computer science class), they probably used forward reasoning.  In\n    general, Coq tends to favor backward reasoning, but in some\n    situations the forward style can be easier to use or to think\n    about.  *)\n\n(** **** Exercise: 3 stars (plus_n_n_injective)  *)\n(** Practice using \"in\" variants in this exercise. *)\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    (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ###################################################### *)\n(** * Varying the Induction Hypothesis *)\n\n(** Sometimes it is important to control the exact form of the\n    induction hypothesis when carrying out inductive proofs in Coq.\n    In particular, we need to be careful about which of the\n    assumptions we move (using [intros]) from the goal to the context\n    before invoking the [induction] tactic.  For example, suppose \n    we want to show that the [double] function is injective -- i.e., \n    that it always maps different arguments to different results:  \n    Theorem double_injective: forall n m, double n = double m -> n = m. \n    The way we _start_ this proof is a little bit delicate: if we \n    begin it with\n      intros n. induction n.\n]] \n    all is well.  But if we begin it with\n      intros n m. induction n.\n    we get stuck in the middle of the inductive case... *)\n\nTheorem double_injective_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction n as [| n'].\n  - (* n = O *) simpl. intros eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq. \n  - (* n = S n' *) intros eq. destruct m as [| m'].\n    + (* m = O *) inversion eq.\n    + (* m = S m' *)  apply f_equal. \n      (* Here we are stuck.  The induction hypothesis, [IHn'], does\n         not give us [n' = m'] -- there is an extra [S] in the\n         way -- so the goal is not provable. *)\n      Abort.\n\n(** What went wrong? *)\n\n(** The problem is that, at the point we invoke the induction\n    hypothesis, we have already introduced [m] into the context -- \n    intuitively, we have told Coq, \"Let's consider some particular\n    [n] and [m]...\" and we now have to prove that, if [double n =\n    double m] for _these particular_ [n] and [m], then [n = m].\n\n    The next tactic, [induction n] says to Coq: We are going to show\n    the goal by induction on [n].  That is, we are going to prove that\n    the proposition\n\n      - [P n]  =  \"if [double n = double m], then [n = m]\"\n\n    holds for all [n] by showing\n\n      - [P O]              \n\n         (i.e., \"if [double O = double m] then [O = m]\")\n\n      - [P n -> P (S n)]  \n\n        (i.e., \"if [double n = double m] then [n = m]\" implies \"if\n        [double (S n) = double m] then [S n = m]\").\n\n    If we look closely at the second statement, it is saying something\n    rather strange: it says that, for a _particular_ [m], if we know\n\n      - \"if [double n = double m] then [n = m]\"\n\n    then we can prove\n\n       - \"if [double (S n) = double m] then [S n = m]\".\n\n    To see why this is strange, let's think of a particular [m] --\n    say, [5].  The statement is then saying that, if we know\n\n      - [Q] = \"if [double n = 10] then [n = 5]\"\n\n    then we can prove\n\n      - [R] = \"if [double (S n) = 10] then [S n = 5]\".\n\n    But knowing [Q] doesn't give us any help with proving [R]!  (If we\n    tried to prove [R] from [Q], we would say something like \"Suppose\n    [double (S n) = 10]...\" but then we'd be stuck: knowing that\n    [double (S n)] is [10] tells us nothing about whether [double n]\n    is [10], so [Q] is useless at this point.) *)\n\n(** To summarize: Trying to carry out this proof by induction on [n]\n    when [m] is already in the context doesn't work because we are\n    trying to prove a relation involving _every_ [n] but just a\n    _single_ [m]. *)\n\n(** The good proof of [double_injective] leaves [m] in the goal\n    statement at the point where the [induction] tactic is invoked on\n    [n]: *)\n\nTheorem double_injective : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n. induction n as [| n'].\n  - (* n = O *) simpl. intros m eq. destruct m as [| m'].\n    + (* m = O *) reflexivity.\n    + (* m = S m' *) inversion eq. \n  - (* n = S n' *) \n    (* Notice that both the goal and the induction\n       hypothesis have changed: the goal asks us to prove\n       something more general (i.e., to prove the\n       statement for _every_ [m]), but the IH is\n       correspondingly more flexible, allowing us to\n       choose any [m] we like when we apply the IH.  *)\n    intros m eq.\n    (* Now we choose a particular [m] and introduce the\n       assumption that [double n = double m].  Since we\n       are doing a case analysis on [n], we need a case\n       analysis on [m] to keep the two \"in sync.\" *)\n    destruct m as [| m'].\n    + (* m = O *) \n      (* The 0 case is trivial *)\n      inversion eq.  \n    + (* m = S m' *)  \n      apply f_equal. \n      (* At this point, since we are in the second\n         branch of the [destruct m], the [m'] mentioned\n         in the context at this point is actually the\n         predecessor of the one we started out talking\n         about.  Since we are also in the [S] branch of\n         the induction, this is perfect: if we\n         instantiate the generic [m] in the IH with the\n         [m'] that we are talking about right now (this\n         instantiation is performed automatically by\n         [apply]), then [IHn'] gives us exactly what we\n         need to finish the proof. *)\n      apply IHn'. inversion eq. reflexivity. Qed.\n\n(** What this teaches us is that we need to be careful about using\n    induction to try to prove something too specific: If we're proving\n    a property of [n] and [m] by induction on [n], we may need to\n    leave [m] generic. *)\n\n(** The proof of this theorem (left as an exercise) has to be treated similarly: *)\n\n(** **** Exercise: 2 stars (beq_nat_true)  *)\nTheorem beq_nat_true : forall n m,\n    beq_nat n m = true -> n = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)\n(** Give a careful informal proof of [beq_nat_true], being as explicit\n    as possible about quantifiers. *)\n\n(* FILL IN HERE *)\n(** [] *)\n\n\n(** The strategy of doing fewer [intros] before an [induction] doesn't\n    always work directly; sometimes a little _rearrangement_ of\n    quantified variables is needed.  Suppose, for example, that we\n    wanted to prove [double_injective] by induction on [m] instead of\n    [n]. *)\n\nTheorem double_injective_take2_FAILED : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. induction m as [| m'].\n  - (* m = O *) simpl. intros eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq. \n  - (* m = S m' *) intros eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *)  apply f_equal.\n        (* Stuck again here, just like before. *)\nAbort.\n\n(** The problem is that, to do induction on [m], we must first\n    introduce [n].  (If we simply say [induction m] without\n    introducing anything first, Coq will automatically introduce\n    [n] for us!)   *)\n\n(** What can we do about this?  One possibility is to rewrite the\n    statement of the lemma so that [m] is quantified before [n].  This\n    will work, but it's not nice: We don't want to have to mangle the\n    statements of lemmas to fit the needs of a particular strategy for\n    proving them -- we want to state them in the most clear and\n    natural way. *)\n\n(**  What we can do instead is to first introduce all the\n    quantified variables and then _re-generalize_ one or more of\n    them, taking them out of the context and putting them back at\n    the beginning of the goal.  The [generalize dependent] tactic\n    does this. *)\n\nTheorem double_injective_take2 : forall n m,\n     double n = double m ->\n     n = m.\nProof.\n  intros n m. \n  (* [n] and [m] are both in the context *)\n  generalize dependent n.\n  (* Now [n] is back in the goal and we can do induction on\n     [m] and get a sufficiently general IH. *)\n  induction m as [| m'].\n  - (* m = O *) simpl. intros n eq. destruct n as [| n'].\n    + (* n = O *) reflexivity.\n    + (* n = S n' *) inversion eq.\n  - (* m = S m' *) intros n eq. destruct n as [| n'].\n    + (* n = O *) inversion eq.\n    + (* n = S n' *) apply f_equal.\n      apply IHm'. inversion eq. reflexivity. Qed.\n\n(** Let's look at an informal proof of this theorem.  Note that\n    the proposition we prove by induction leaves [n] quantified,\n    corresponding to the use of generalize dependent in our formal\n    proof.\n\n_Theorem_: For any nats [n] and [m], if [double n = double m], then\n  [n = m].\n\n_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for\n  any [n], if [double n = double m] then [n = m].\n\n  - First, suppose [m = 0], and suppose [n] is a number such\n    that [double n = double m].  We must show that [n = 0].\n\n    Since [m = 0], by the definition of [double] we have [double n =\n    0].  There are two cases to consider for [n].  If [n = 0] we are\n    done, since this is what we wanted to show.  Otherwise, if [n = S\n    n'] for some [n'], we derive a contradiction: by the definition of\n    [double] we would have [double n = S (S (double n'))], but this\n    contradicts the assumption that [double n = 0].\n\n  - Otherwise, suppose [m = S m'] and that [n] is again a number such\n    that [double n = double m].  We must show that [n = S m'], with\n    the induction hypothesis that for every number [s], if [double s =\n    double m'] then [s = m'].\n \n    By the fact that [m = S m'] and the definition of [double], we\n    have [double n = S (S (double m'))].  There are two cases to\n    consider for [n].\n\n    If [n = 0], then by definition [double n = 0], a contradiction.\n    Thus, we may assume that [n = S n'] for some [n'], and again by\n    the definition of [double] we have [S (S (double n')) = S (S\n    (double m'))], which implies by inversion that [double n' = double\n    m'].\n\n    Instantiating the induction hypothesis with [n'] thus allows us to\n    conclude that [n' = m'], and it follows immediately that [S n' = S\n    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted\n    to show. [] *)\n\n\n\n(** Here's another illustration of [inversion] and using an\n    appropriately general induction hypothesis.  This is a slightly\n    roundabout way of stating a fact that we have already proved\n    above.  The extra equalities force us to do a little more\n    equational reasoning and exercise some of the tactics we've seen\n    recently. *)\n\nTheorem length_snoc' : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l. induction l as [| v' l'].\n\n  - (* l = [] *) \n    intros n eq. rewrite <- eq. reflexivity.\n\n  - (* l = v' :: l' *) \n    intros n eq. simpl. destruct n as [| n'].\n    + (* n = 0 *) inversion eq.\n    + (* n = S n' *)\n      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.\n\n(** It might be tempting to start proving the above theorem\n    by introducing [n] and [eq] at the outset.  However, this leads\n    to an induction hypothesis that is not strong enough.  Compare\n    the above to the following (aborted) attempt: *)\n\nTheorem length_snoc_bad : forall (X : Type) (v : X)\n                              (l : list X) (n : nat),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  intros X v l n eq. induction l as [| v' l'].\n\n  - (* l = [] *) \n    rewrite <- eq. reflexivity.\n\n  - (* l = v' :: l' *) \n    simpl. destruct n as [| n'].\n    + (* n = 0 *) inversion eq.\n    + (* n = S n' *)\n      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)\n\n\n(** As in the double examples, the problem is that by\n    introducing [n] before doing induction on [l], the induction\n    hypothesis is specialized to one particular natural number, namely\n    [n].  In the induction case, however, we need to be able to use\n    the induction hypothesis on some other natural number [n'].\n    Retaining the more general form of the induction hypothesis thus\n    gives us more flexibility.\n\n    In general, a good rule of thumb is to make the induction hypothesis\n    as general as possible. *)\n\n(** **** Exercise: 3 stars (gen_dep_practice)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem index_after_last: forall (n : nat) (X : Type) (l : list X),\n     length l = n ->\n     index n l = None.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal)  *)\n(** Write an informal proof corresponding to your Coq proof\n    of [index_after_last]:\n \n     _Theorem_: For all sets [X], lists [l : list X], and numbers\n      [n], if [length l = n] then [index n l = None].\n \n     _Proof_:\n     (* FILL IN HERE *)\n[]\n*)\n\n(** **** Exercise: 3 stars, optional (gen_dep_practice_more)  *)\n(** Prove this by induction on [l]. *)\n\nTheorem length_snoc''' : forall (n : nat) (X : Type) \n                              (v : X) (l : list X),\n     length l = n ->\n     length (snoc l v) = S n. \nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, optional (app_length_cons)  *)\n(** Prove this by induction on [l1], without using [app_length]\n    from [Lists]. *)\n\nTheorem app_length_cons : forall (X : Type) (l1 l2 : list X) \n                                  (x : X) (n : nat),\n     length (l1 ++ (x :: l2)) = n ->\n     S (length (l1 ++ l2)) = n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 4 stars, optional (app_length_twice)  *)\n(** Prove this by induction on [l], without using [app_length] from [Lists]. *)\n\nTheorem app_length_twice : forall (X:Type) (n:nat) (l:list X),\n     length l = n ->\n     length (l ++ l) = n + n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(** **** Exercise: 3 stars, optional (double_induction)  *)\n(** Prove the following principle of induction over two naturals. *)\n\nTheorem double_induction: forall (P : nat -> nat -> Prop), \n  P 0 0 ->\n  (forall m, P m 0 -> P (S m) 0) ->\n  (forall n, P 0 n -> P 0 (S n)) ->\n  (forall m n, P m n -> P (S m) (S n)) ->\n  forall m n, P m n.\nProof.\n  intros P POO PmO POn Pmn m n.\n  induction m.\n  - induction n.\n    +  apply POO.\n    + apply POn. apply IHn.\n  - induction n.\n    +  apply PmO. apply IHm. \n    + apply Pmn. admit.\n(** [] *)\n\n\n(* ###################################################### *)\n(** * Using [destruct] on Compound Expressions *)\n\n(** We have seen many examples where the [destruct] tactic is\n    used to perform case analysis of the value of some variable.  But\n    sometimes we need to reason by cases on the result of some\n    _expression_.  We can also do this with [destruct].\n\n    Here are some examples: *)\n\nDefinition sillyfun (n : nat) : bool :=\n  if beq_nat n 3 then false\n  else if beq_nat n 5 then false\n  else false.\n\nTheorem sillyfun_false : forall (n : nat),\n  sillyfun n = false.\nProof.\n  intros n. unfold sillyfun. \n  destruct (beq_nat n 3).\n    - (* beq_nat n 3 = true *) reflexivity.\n    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).\n      + (* beq_nat n 5 = true *) reflexivity.\n      + (* beq_nat n 5 = false *) reflexivity.  Qed.\n\n(** After unfolding [sillyfun] in the above proof, we find that\n    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,\n    either [n] is equal to [3] or it isn't, so we use [destruct\n    (beq_nat n 3)] to let us reason about the two cases. \n\n    In general, the [destruct] tactic can be used to perform case\n    analysis of the results of arbitrary computations.  If [e] is an\n    expression whose type is some inductively defined type [T], then,\n    for each constructor [c] of [T], [destruct e] generates a subgoal\n    in which all occurrences of [e] (in the goal and in the context)\n    are replaced by [c].\n\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(** **** Exercise: 3 stars, optional (combine_split)  *)\n(** Complete the proof below *)\n\nTheorem combine_split : forall X Y (l : list (X * Y)) l1 l2,\n  split l = (l1, l2) ->\n  combine l1 l2 = l.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Sometimes, doing a [destruct] on a compound expression (a\n    non-variable) will erase information we need to complete a proof. *)\n(** For example, suppose\n    we define a function [sillyfun1] like this: *)\n\nDefinition sillyfun1 (n : nat) : bool :=\n  if beq_nat n 3 then true\n  else if beq_nat n 5 then true\n  else false.\n\n(** And suppose that we want to convince Coq of the rather\n    obvious observation that [sillyfun1 n] yields [true] only when [n]\n    is odd.  By analogy with the proofs we did with [sillyfun] above,\n    it is natural to start the proof like this: *)\n\nTheorem sillyfun1_odd_FAILED : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3).\n  (* stuck... *)\nAbort.\n\n(** We get stuck at this point because the context does not\n    contain enough information to prove the goal!  The problem is that\n    the substitution peformed by [destruct] is too brutal -- it threw\n    away every occurrence of [beq_nat n 3], but we need to keep some\n    memory of this expression and how it was destructed, because we\n    need to be able to reason that since, in this branch of the case\n    analysis, [beq_nat n 3 = true], it must be that [n = 3], from\n    which it follows that [n] is odd.\n\n    What we would really like is to substitute away all existing\n    occurences of [beq_nat n 3], but at the same time add an equation\n    to the context that records which case we are in.  The [eqn:]\n    qualifier allows us to introduce such an equation (with whatever\n    name we choose). *)\n\nTheorem sillyfun1_odd : forall (n : nat),\n     sillyfun1 n = true ->\n     oddb n = true.\nProof.\n  intros n eq. unfold sillyfun1 in eq.\n  destruct (beq_nat n 3) eqn:Heqe3.\n  (* Now we have the same state as at the point where we got stuck\n    above, except that the context contains an extra equality\n    assumption, which is exactly what we need to make progress. *)\n    - (* e3 = true *) apply beq_nat_true in Heqe3.\n      rewrite -> Heqe3. reflexivity.\n    - (* e3 = false *)\n     (* When we come to the second equality test in the body of the\n       function we are reasoning about, we can use [eqn:] again in the\n       same way, allow us to finish the proof. *)\n      destruct (beq_nat n 5) eqn:Heqe5. \n        + (* e5 = true *)\n          apply beq_nat_true in Heqe5.\n          rewrite -> Heqe5. reflexivity.\n        + (* e5 = false *) inversion eq.  Qed.\n\n\n(** **** Exercise: 2 stars (destruct_eqn_practice)  *)\nTheorem bool_fn_applied_thrice : \n  forall (f : bool -> bool) (b : bool), \n  f (f (f b)) = f b.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars (override_same)  *)\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  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################## *)\n(** * Review *)\n\n(** We've now seen a bunch of Coq's fundamental tactics.  We'll\n    introduce a few more as we go along through the coming lectures,\n    and later in the course we'll introduce some more powerful\n    _automation_ tactics that make Coq do more of the low-level work\n    in many cases.  But basically we've got what we need to get work\n    done.\n\n    Here are the ones we've seen:\n\n      - [intros]: \n        move hypotheses/variables from goal to context \n\n      - [reflexivity]:\n        finish the proof (when the goal looks like [e = e])\n\n      - [apply]:\n        prove goal using a hypothesis, lemma, or constructor\n\n      - [apply... in H]: \n        apply a hypothesis, lemma, or constructor to a hypothesis in\n        the context (forward reasoning)\n\n      - [apply... with...]:\n        explicitly specify values for variables that cannot be\n        determined by pattern matching\n\n      - [simpl]:\n        simplify computations in the goal \n\n      - [simpl in H]:\n        ... or a hypothesis \n\n      - [rewrite]:\n        use an equality hypothesis (or lemma) to rewrite the goal \n\n      - [rewrite ... in H]:\n        ... or a hypothesis \n\n      - [symmetry]:\n        changes a goal of the form [t=u] into [u=t]\n\n      - [symmetry in H]:\n        changes a hypothesis of the form [t=u] into [u=t]\n\n      - [unfold]:\n        replace a defined constant by its right-hand side in the goal \n\n      - [unfold... in H]:\n        ... or a hypothesis  \n\n      - [destruct... as...]:\n        case analysis on values of inductively defined types \n\n      - [destruct... eqn:...]:\n        specify the name of an equation to be added to the context,\n        recording the result of the case analysis\n\n      - [induction... as...]:\n        induction on values of inductively defined types \n\n      - [inversion]:\n        reason by injectivity and distinctness of constructors\n\n      - [assert (e) as H]:\n        introduce a \"local lemma\" [e] and call it [H] \n\n      - [generalize dependent x]:\n        move the variable [x] (and anything else that depends on it)\n        from the context back to an explicit hypothesis in the goal\n        formula \n*)\n\n(* ###################################################### *)\n(** * Additional Exercises *)\n\n(** **** Exercise: 3 stars (beq_nat_sym)  *)\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)\n(** Give an informal proof of this lemma that corresponds to your\n    formal proof above:\n\n   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].\n\n   Proof:\n   (* FILL IN HERE *)\n[]\n *)\n\n(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)\nTheorem beq_nat_trans : forall n m p,\n  beq_nat n m = true ->\n  beq_nat m p = true ->\n  beq_nat n p = true.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (split_combine)  *)\n(** We have just proven that for all lists of pairs, [combine] is the\n    inverse of [split].  How would you formalize the statement that\n    [split] is the inverse of [combine]? When is this property true?\n\n    Complete the definition of [split_combine_statement] below with a\n    property that states that [split] is the inverse of\n    [combine]. Then, prove that the property holds. (Be sure to leave\n    your induction hypothesis general by not doing [intros] on more\n    things than necessary.  Hint: what property do you need of [l1]\n    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)\n\nDefinition split_combine_statement : Prop :=\n(* FILL IN HERE *) admit.\n\nTheorem split_combine : split_combine_statement.\nProof.\n(* FILL IN HERE *) Admitted.\n\n\n\n(** [] *)\n\n(** **** Exercise: 3 stars (override_permute)  *)\nTheorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),\n  beq_nat k2 k1 = false ->\n  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, advanced (filter_exercise)  *)\n(** This one is a bit challenging.  Pay attention to the form of your IH. *)\n\nTheorem filter_exercise : forall (X : Type) (test : X -> bool)\n                             (x : X) (l lf : list X),\n     filter test l = x :: lf ->\n     test x = true.\nProof.\n  intros X test x l lf.\n  induction l.\n  + intros. unfold filter in H. inversion H.\n  + intros.\n    destruct (test x0) eqn: testH.\n    - unfold filter in H. rewrite testH in H. fold (filter test) in H. inversion H. rewrite <- H1. apply testH.\n    - unfold filter in H. rewrite testH in H. fold (filter test) in H. apply IHl. apply H.\nQed. \n(** [] *)\n\n(** **** Exercise: 4 stars, advanced (forall_exists_challenge)  *)\n(** Define two recursive [Fixpoints], [forallb] and [existsb].  The\n    first checks whether every element in a list satisfies a given\n    predicate:\n      forallb oddb [1;3;5;7;9] = true\n\n      forallb negb [false;false] = true\n  \n      forallb evenb [0;2;4;5] = false\n  \n      forallb (beq_nat 5) [] = true\n    The second checks whether there exists an element in the list that\n    satisfies a given predicate:\n      existsb (beq_nat 5) [0;2;3;6] = false\n \n      existsb (andb true) [true;true;false] = true\n \n      existsb oddb [1;0;0;0;0;3] = true\n \n      existsb evenb [] = false\n    Next, define a _nonrecursive_ version of [existsb] -- call it\n    [existsb'] -- using [forallb] and [negb].\n \n    Prove theorem [existsb_existsb'] that [existsb'] and [existsb] have\n    the same behavior.\n*)\n\nFixpoint forallb {X : Type} (p : X -> bool) (l : list X) := \n  match l with \n  | []       => true\n  | x :: l'  => if p x then forallb p l' else false\nend.\n\nFixpoint existsb {X : Type} (p : X -> bool) (l : list X) := \n  match l with \n  | []       => false\n  | x :: l'  => if p x then true else existsb p l'\nend.\n\nDefinition existsb' {X : Type} (p : X -> bool) (l : list X) := \n  negb (forallb (fun x => negb (p x)) l).\n\nTheorem existsb_existsb': forall (X : Type) (p : X -> bool)\n                             (l : list X),\n     existsb p l = existsb' p l.\nProof.\n  intros. \n  induction l.\n  - simpl. unfold existsb'. unfold forallb. simpl. reflexivity.\n  - destruct (p x) eqn: Hpx.\n    + simpl. \n      unfold existsb'. unfold forallb.  \n      rewrite Hpx. simpl. reflexivity.\n    + simpl. unfold existsb'. unfold forallb. rewrite Hpx.\n      simpl. fold (forallb (fun x0 : X => negb (p x0))).\n      unfold existsb' in IHl. rewrite IHl. reflexivity.\nQed.\n\n(* FILL IN HERE *)\n(** [] *)\n\n(** $Date: 2015-08-11 03:46:09 +0200 (Tue, 11 Aug 2015) $ *)\n\n\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/BasicTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867729389246, "lm_q2_score": 0.882427872638409, "lm_q1q2_score": 0.704342256012612}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nRequire Export Field.\nRequire Export QArith_base.\nRequire Import NArithRing.\n\n(** * field and ring tactics for rational numbers *)\n\nDefinition Qsrt : ring_theory 0 1 Qplus Qmult Qminus Qopp Qeq.\nProof.\n  constructor.\n  exact Qplus_0_l.\n  exact Qplus_comm.\n  exact Qplus_assoc.\n  exact Qmult_1_l.\n  exact Qmult_comm.\n  exact Qmult_assoc.\n  exact Qmult_plus_distr_l.\n  reflexivity.\n  exact Qplus_opp_r.\nQed.\n\nDefinition Qsft : field_theory 0 1 Qplus Qmult Qminus Qopp Qdiv Qinv Qeq.\nProof.\n  constructor.\n  exact Qsrt.\n  discriminate.\n  reflexivity.\n  intros p Hp.\n  rewrite Qmult_comm.\n  apply Qmult_inv_r.\n  exact Hp.\nQed.\n\nLemma Qpower_theory : power_theory 1 Qmult Qeq Z.of_N Qpower.\nProof.\nconstructor.\nintros r [|n];\nreflexivity.\nQed.\n\nLtac isQcst t :=\n  match t with\n  | inject_Z ?z => isZcst z\n  | Qmake ?n ?d =>\n    match isZcst n with\n      true => isPcst d\n    | _ => false\n    end\n  | _ => false\n  end.\n\nLtac Qcst t :=\n  match isQcst t with\n    true => t\n    | _ => NotConstant\n  end.\n\nLtac Qpow_tac t :=\n  match t with\n  | Z0 => N0\n  | Zpos ?n => Ncst (Npos n)\n  | Z.of_N ?n => Ncst n\n  | NtoZ ?n => Ncst n\n  | _ => NotConstant\n  end.\n\nAdd Field Qfield : Qsft\n (decidable Qeq_bool_eq,\n  completeness Qeq_eq_bool,\n  constants [Qcst],\n  power_tac Qpower_theory [Qpow_tac]).\n\n(** Exemple of use: *)\n\nSection Examples.\n\nLet ex1 : forall x y z : Q, (x+y)*z ==  (x*z)+(y*z).\n  intros.\n  ring.\nQed.\n\nLet ex2 : forall x y : Q, x+y == y+x.\n  intros.\n  ring.\nQed.\n\nLet ex3 : forall x y z : Q, (x+y)+z == x+(y+z).\n  intros.\n  ring.\nQed.\n\nLet ex4 : (inject_Z 1)+(inject_Z 1)==(inject_Z 2).\n  ring.\nQed.\n\nLet ex5 : 1+1 == 2#1.\n  ring.\nQed.\n\nLet ex6 : (1#1)+(1#1) == 2#1.\n  ring.\nQed.\n\nLet ex7 : forall x : Q, x-x== 0.\n  intro.\n  ring.\nQed.\n\nLet ex8 : forall x : Q, x^1 == x.\n  intro.\n  ring.\nQed.\n\nLet ex9 : forall x : Q, x^0 == 1.\n  intro.\n  ring.\nQed.\n\nLet ex10 : forall x y : Q, ~(y==0) -> (x/y)*y == x.\nintros.\nfield.\nauto.\nQed.\n\nEnd Examples.\n\nLemma Qopp_plus : forall a b,  -(a+b) == -a + -b.\nProof.\n  intros; ring.\nQed.\n\nLemma Qopp_opp : forall q, - -q==q.\nProof.\n  intros; ring.\nQed.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/QArith/Qfield.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7043422517763434}}
{"text": "(* Exercise 19 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_019 : (exists x : D, P x \\/ Q x) -> (exists x : D, P x) \\/ (exists x : D, Q x).\nProof.\nimp_i a1.\nexi_e (exists x:D, P x \\/ Q x) a a2.\nhyp a1.\ndis_e (P a \\/ Q a) a3 a3.\nhyp a2.\ndis_i1.\nexi_i a.\nhyp a3.\ndis_i2.\nexi_i a.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred019.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7043247064444983}}
{"text": "(* Exercise 73 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_073 : (exists x : D, exists y : D, R x y) -> (exists x : D, x=x).\nProof.\nimp_i a1.\nexi_e (exists x:D, exists y:D, R x y) a a2.\nhyp a1.\nexi_e (exists y:D, R a y) b a3.\nhyp a2.\nexi_i a.\nlin_solve.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred073.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404077216356, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7043247043226422}}
{"text": "Require Import ZArith.\nRequire Import Coq.Logic.Decidable.\n\nDefinition divides a b := exists k, b = k * a.\nDefinition prime p := 2 <= p /\\ forall k, divides k p -> (k = 1 \\/ k = p).\n\nLemma divides_comm : forall a b, divides a b <-> exists k, b = a * k.\n  intros; cbv [divides]; firstorder; exists x; rewrite Nat.mul_comm; assumption.\nQed.\n\nDefinition divides' a b := Nat.modulo b a = 0.\n\nLemma divides_eq : forall a b, b <> 0 -> divides' b a <-> divides b a.\n  cbv [divides']; intros; split; rewrite divides_comm; apply Nat.mod_divides; assumption.\nQed.\n\nInfix \"==n\" := eq_nat_dec (no associativity, at level 50).\n\nTheorem divides_dec : forall n m : nat, {divides n m} + {~divides n m}.\n  destruct n.\n  { destruct m; cbv [divides].\n    { left; exists 0; omega. }\n    { right; intro H; destruct H; omega. }\n  }\n  { intro; destruct (m mod (S n) ==n 0).\n    { left; apply divides_eq; auto. }\n    { right; rewrite <- divides_eq; auto. }\n  }\nQed.\n\nFixpoint prime_decider' (n m : nat) : bool :=\n  match m with\n    | 0 => true\n    | S m => prime_decider' n m &&\n            if divides_dec (S m) n then\n              if (S m ==n 1) then true else\n                if (S m ==n n) then true else false\n            else true\n  end.\n\nDefinition prime_decider (n : nat) : bool := if (le_dec 2 n) then prime_decider' n n else false.\n\nLtac simpl_prime_decider :=\n  match goal with\n  | [ H : prime_decider' _ _ = _ |- _ ] =>\n    unfold prime_decider' in H; fold prime_decider' in H;\n    rewrite Bool.andb_true_iff in H; firstorder\n  | [ |- prime_decider' _ _ = _ ] =>\n    unfold prime_decider'; fold prime_decider';\n    rewrite Bool.andb_true_iff; firstorder\n  end.\n\nLemma prime_decider_eq_prime' : forall (n m : nat), 2 <= n -> (prime_decider' n m = true) <-> (forall k : nat, k <= m -> divides k n -> k = 1 \\/ k = n).\n  induction m; firstorder.\n  { destruct (le_lt_eq_dec k 0); [assumption | omega | subst; omega]. }\n  { destruct (le_lt_eq_dec k (S m)).\n    { assumption. }\n    { apply H3.\n      { simpl_prime_decider. }\n      { apply (lt_n_Sm_le k m l). }\n      { cbv [divides]; exists x; assumption. }\n    }\n    { simpl_prime_decider; rewrite e in H2; destruct (divides_dec (S m) n).\n      { destruct (S m ==n 1).\n        { firstorder. }\n        { destruct (S m ==n n); firstorder; discriminate. }\n      }\n      { destruct n0; cbv [divides]; exists x; assumption. }\n    }\n  }\n  { simpl_prime_decider; destruct (divides_dec (S m) n).\n    { destruct (S m ==n 1).\n      { trivial. }\n      { destruct (S m ==n n).\n        { trivial. }\n        { specialize (H0 (S m) (le_n (S m))); firstorder; trivial. }\n      }\n    }\n    { trivial. }\n  }\nQed.\n\nLemma le_sufficient : forall (n : nat), 2 <= n -> (forall k : nat, k <= n -> divides k n -> k = 1 \\/ k = n) <-> prime n.\n  intros; cbv [prime]; split.\n  { intros; split.\n    { assumption. }\n    { intro; destruct (le_gt_dec k n).\n      { specialize (H0 k l); assumption. }\n      { intros; rewrite <- divides_eq in H1.\n        { cbv [divides'] in H1; pose proof (Nat.mod_small n k); omega. }\n        { intro; subst; omega. }\n      }\n    }\n  }\n  { firstorder. }\nQed.\n\nLemma prime_decider_eq_prime : forall n, (prime_decider n = true) <-> prime n.\n  intros; cbv [prime_decider]; destruct (le_dec 2 n).\n  { pose proof (prime_decider_eq_prime' n n l); rewrite H; apply le_sufficient; assumption. }\n  { firstorder; discriminate. }\nQed.\n\nTheorem prime_dec : forall n : nat, {prime n} + {~ prime n}.\n  intros; destruct (Bool.bool_dec (prime_decider n) true) as [dec | dec];\n            rewrite prime_decider_eq_prime in dec; firstorder.\nQed.\n\nFixpoint mult_primes_up_to' (n prod : nat) :=\n  match n with\n  | 0 => prod\n  | S n => if prime_dec n then mult_primes_up_to' n prod * (S n) else mult_primes_up_to' n prod\n  end.\n\nDefinition mult_primes_up_to (n : nat) := mult_primes_up_to' n 1.\n\nLemma not_prime_impl_prime_factor : forall (n : nat), 2 <= n -> ~ prime n -> exists x, divides x n /\\ prime x.\nAdmitted.\n\nLemma checking_primes_sufficient : forall (n : nat), 2 <= n -> (forall k : nat, prime k -> divides k n -> k = 1 \\/ k = n) <-> prime n.\n  intros; split.\n  { intros; split.\n    { assumption. }\n    { cut (forall k : nat, divides k n -> ~ ~(k = 1 \\/ k = n)).\n      { intros; specialize (H1 k H2); apply not_not.\n        { apply dec_or; apply dec_eq_nat; assumption. }\n        { assumption. }\n      }\n      { cut (~ exists k, divides k n /\\ ~(k = 1 \\/ k = n)).\n        { firstorder. }\n        { intro.\n          destruct H1.\n          destruct (prime_dec x).\n          specialize (H0 x); firstorder.\n          pose proof (not_prime_impl_prime_factor x).\n          Admitted.\n\nLemma succ_doesnt_divide : forall (n : nat), 2 <= n -> (forall k : nat, 2 <= k -> divides k n -> ~ divides k (S n)).\n  intros; intro. rewrite <- divides_eq in H1.\n  { rewrite <- divides_eq in H2.\n    { cbv [divides'] in H1; cbv [divides'] in H2; rewrite <- Nat.add_1_r in H2; rewrite Nat.add_mod in H2.\n      { rewrite H1 in H2; simpl in H2; rewrite Nat.mod_mod in H2.\n        { pose proof (Nat.mod_small 1 k); omega. }\n        { omega. }\n      }\n      { omega. }\n    }\n    { omega. }\n  }\n  { omega. }\nQed.\n\nLemma succ_mult_primes_up_to_prime : forall n, prime (S (mult_primes_up_to n)).\nAdmitted.\n\nLemma succ_mult_primes_up_to_gt : forall n, S (mult_primes_up_to n) > n.\n  intros; destruct (le_gt_dec (S (mult_primes_up_to n)) n).\n  { pose proof (succ_mult_primes_up_to_prime n); exfalso; admit. }\n  { assumption. }\nAdmitted.\n\nTheorem primes_infinite : forall n, exists p, p > n /\\ prime p.\n  intros; exists (S (mult_primes_up_to n)); split.\n  { apply succ_mult_primes_up_to_gt. }\n  { apply succ_mult_primes_up_to_prime. }\nQed.", "meta": {"author": "asya-bergal", "repo": "coq-examples", "sha": "70c3abe7afa47533133a62efd1bfc143d06b4e06", "save_path": "github-repos/coq/asya-bergal-coq-examples", "path": "github-repos/coq/asya-bergal-coq-examples/coq-examples-70c3abe7afa47533133a62efd1bfc143d06b4e06/infinite_primes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582426, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.7043246947953757}}
{"text": "Set Implicit Arguments.\n\n\nCoInductive LList (A:Type) : Type :=\n  | LNil : LList A\n  | LCons : A -> LList A -> LList A.\n\nImplicit Arguments LNil [A].\n\nCoInductive Infinite {A:Type} : LList A -> Prop :=\n    Infinite_LCons :\n      forall (a:A) (l:LList A), Infinite l -> Infinite (LCons a l).\n\nHint Constructors Infinite: llists.\n\n  \n\nDefinition Infinite_ok {A: Type} (X:LList A -> Prop) : Prop :=\n  forall l:LList A,\n    X l ->  exists a : A, exists l' : LList A, l = LCons a l' /\\ X l'.\n \nDefinition Infinite1 {A: Type} (l:LList A) :=\n   exists X : LList A -> Prop, Infinite_ok X /\\ X l.\n\n\nLemma ok_LNil {A: Type}:\n forall X:LList A -> Prop, Infinite_ok X -> ~ X LNil.\nProof.\n unfold Infinite_ok.\n intros X H H0;  case (H LNil).  \n - assumption. \n - intros x H1; case H1; intros x0 H2; case H2; discriminate 1.\nQed.\n\nLemma ok_LCons {A: Type} :\n  forall  (X:LList A -> Prop) (a:A) (l:LList A),\n   Infinite_ok X -> X (LCons a l) -> X l.\nProof.\n intros  X a l H H0; case (H (LCons a l)).\n -  assumption.\n -  simple destruct 1; intros x0 H2; case H2; injection 1.\n    simple destruct 1; auto.\nQed.\n\n\n\nLemma Infinite1_LNil {A: Type} :  ~ Infinite1 (LNil (A:=A)).\nProof.\n intros  H; destruct H as [X [H1 H2]].\n now apply (ok_LNil H1).\nQed.\n\n\nLemma Infinite1_LCons  {A: Type} :\n forall  (a:A) (l:LList A), Infinite1 (LCons a l) -> Infinite1 l.\nProof.\n intros  a l H.\n case H; intros X HX; case HX; intros H1 H2; clear HX.\n  exists (fun u:LList A =>  exists b : A, X (LCons b u)); split.\n -  unfold Infinite_ok in |- *.\n    intros l0 [b Hb]. \n    assert (H4 : X l0) by apply (ok_LCons _ _  H1 Hb);eauto.  \n    case (H1 l0 H4);  intros x [l' [el' Hl']].\n    exists x, l'; split; try assumption.\n    exists x; rewrite <- el'; auto.\n-  exists a; auto.\nQed.\n\n\n(* equivalence between both definitions of infinity *)\n\n\nLemma Inf_Inf1 {A : Type} : forall l:LList A, Infinite l -> Infinite1 l.\nProof.\n intros l ;  exists (Infinite (A:=A)).\n split; try assumption.\n unfold Infinite_ok in |- *.\n simple destruct l0.\n -  inversion 1.\n - inversion_clear 1.\n   exists a; exists l1; auto.\nQed.\n\nLemma Inf1_Inf {A : Type}: forall l:LList A, Infinite1 l -> Infinite l.\nProof.\n cofix.\n simple destruct l.\n - intro H;  case (Infinite1_LNil H).\n -  intros a l0 H0;  generalize (Infinite1_LCons H0); constructor.\n    now apply Inf1_Inf. \nQed.\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/ch13_co_inductive_types/SRC/infinite_impred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7043194392312663}}
{"text": "Require Export Induction.\n\nModule NatList.\n\n  Inductive natprod : Type :=\n    pair : nat -> nat -> natprod.\n\n  Definition fst (p:natprod) : nat :=\n    match p with\n      | pair x _ => x\n    end.\n\n  Definition snd (p:natprod) : nat :=\n    match p with\n      | pair _ y => y\n    end.\n\n  Notation \"( x , y )\" := (pair x y).\n\n  Definition swap_pair (p:natprod) : natprod :=\n    match p with\n      | (x,y) => (y,x)\n    end.\n\n  Theorem surjective_pairing' : forall (n m : nat),\n                                  (n, m) = (fst (n, m), snd (n, m)).\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem surjective_pairing : forall (p : natprod),\n                                 p = (fst p, snd p).\n  Proof.\n    intros p. destruct p as [n m]. reflexivity.\n  Qed.\n\n  Theorem snd_fst_is_swap : forall (p : natprod),\n                              (snd p, fst p) = swap_pair p.\n  Proof.\n    intros p. destruct p as [n m]. reflexivity.\n  Qed.\n\n  Theorem fst_swap_is_snd : forall (p : natprod),\n                              fst (swap_pair p) = snd p.\n  Proof.\n    intros p. destruct p as [n m]. reflexivity.\n  Qed.\n\n  Inductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\n  Notation \"x :: l\" := (cons x l) (at level 60, right associativity).\n  Notation \"[ ]\" := nil.\n  Notation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\n  Fixpoint repeat (n count : nat) : natlist :=\n    match count with\n      | 0 => nil\n      | S count' => n :: (repeat n count')\n    end.\n\n  Fixpoint length (l:natlist) : nat :=\n    match l with\n      | nil => 0\n      | h :: t => S (length t)\n    end.\n\n  Fixpoint app (l1 l2 : natlist) : natlist :=\n    match l1 with\n      | nil => l2\n      | h :: t => h :: (app t l2)\n    end.\n\n  Notation \"x ++ y\" := (app x y) (right associativity, at level 60).\n\n  Definition hd (default:nat) (l:natlist) : nat :=\n    match l with\n      | nil => default\n      | h :: t => h\n    end.\n\n  Definition tl (l:natlist) : natlist :=\n    match l with\n      | nil => nil\n      | h :: t => t\n    end.\n\n  Fixpoint 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\n  Example test_nonzeros: nonzeros [0;1;0;2;3;0;0] = [1;2;3].\n  Proof. reflexivity. Qed.\n\n  Fixpoint 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\n  Example test_oddmembers : oddmembers [0;1;0;2;3;0;0] = [1;3].\n  Proof. reflexivity. Qed.\n\n  Fixpoint 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\n  Example test_countoddmembers1: countoddmembers [1;0;3;1;4;5] = 4.\n  Proof. reflexivity. Qed.\n  Example test_countoddmembers2: countoddmembers [0;2;4] = 0.\n  Proof. reflexivity. Qed.\n\n  Fixpoint alternate (l1 l2 : natlist) : natlist :=\n    match l1, l2 with\n      | nil, _ => l2\n      | _, nil => l1\n      | h :: t, h' :: t' => h :: h' :: (alternate t t')\n    end.\n\n  Example test_alternate1: alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].\n  Proof. reflexivity. Qed.\n  Example test_alternate2: alternate [1] [4;5;6] = [1;4;5;6].\n  Proof. reflexivity. Qed.\n  Example test_alternate3: alternate [1;2;3] [4] = [1;4;2;3].\n  Proof. reflexivity. Qed.\n  Example test_alternate4: alternate [] [20;30] = [20;30].\n  Proof. reflexivity. Qed.\n\n  Definition bag := natlist.\n\n  Fixpoint count (v:nat) (s:bag) : nat :=\n    match s with\n      | nil => 0\n      | h :: t => if beq_nat h v then 1 + (count v t) else count v t\n    end.\n\n  Example test_count1: count 1 [1;2;3;1;4;1] = 3.\n  Proof. reflexivity. Qed.\n  Example test_count2: count 6 [1;2;3;1;4;1] = 0.\n  Proof. reflexivity. Qed.\n\n  Definition sum : bag -> bag -> bag :=\n    app.\n\n  Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.\n  Proof. reflexivity. Qed.\n\n  Definition add (v:nat) (s:bag) : bag :=\n    v :: s.\n\n  Example test_add1: count 1 (add 1 [1;4;1]) = 3.\n  Proof. reflexivity. Qed.\n  Example test_add2: count 5 (add 1 [1;4;1]) = 0.\n  Proof. reflexivity. Qed.\n\n  Definition member (v:nat) (s:bag) : bool :=\n    negb (beq_nat (count v s) 0).\n\n  Example test_member1: member 1 [1;4;1] = true.\n  Proof. reflexivity. Qed.\n  Example test_member2: member 2 [1;4;1] = false.\n  Proof. reflexivity. Qed.\n\n  Fixpoint remove_one (v:nat) (s:bag) : bag :=\n    match s with\n      | nil => nil\n      | h :: t => if beq_nat h v then t else h :: remove_one v t\n    end.\n\n  Example test_remove_one1: count 5 (remove_one 5 [2;1;5;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_one2: count 5 (remove_one 5 [2;1;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_one3: count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.\n  Proof. reflexivity. Qed.\n  Example test_remove_one4: count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.\n  Proof. reflexivity. Qed.\n\n  Fixpoint 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\n  Example test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.\n  Proof. reflexivity. Qed.\n  Example test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.\n  Proof. reflexivity. Qed.\n  Example test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.\n  Proof. reflexivity. Qed.\n\n  Fixpoint 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\n  Example test_subset1: subset [1;2] [2;1;4;1] = true.\n  Proof. reflexivity. Qed.\n  Example test_subset2: subset [1;2;2] [2;1;4;1] = false.\n  Proof. reflexivity. Qed.\n\n  Theorem bag_theorem :\n    forall (b : bag) (n : nat),\n      count n (add n b) = (count n b) + 1.\n  Proof.\n    intros b n.\n    simpl.\n    rewrite <- beq_nat_refl. rewrite <- plus_1_l. rewrite -> plus_comm.\n    reflexivity.\n  Qed.\n\n  Theorem nil_app : forall l : natlist,\n                      [] ++ l = l.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Theorem tl_length_pred : forall l : natlist,\n                             pred (length l) = length (tl l).\n  Proof.\n    intros l. destruct l; reflexivity.\n  Qed.\n\n  Theorem app_assoc : forall l1 l2 l3 : natlist,\n                        (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\n  Proof.\n    intros l1 l2 l3. induction l1 as [| n l1'].\n    Case \"l1 = nil\". reflexivity.\n    Case \"l1 = cons n l1'\".\n      simpl. rewrite -> IHl1'. reflexivity.\n  Qed.\n\n  Theorem app_length : forall l1 l2 : natlist,\n                         length (l1 ++ l2) = (length l1) + (length l2).\n  Proof.\n    intros l1 l2. induction l1 as [| n l1'].\n    Case \"l1 = nil\". reflexivity.\n    Case \"l1 = cons\".\n      simpl. rewrite -> IHl1'. reflexivity.\n  Qed.\n\n  Fixpoint snoc (l:natlist) (v:nat) : natlist :=\n    match l with\n      | nil => [v]\n      | h :: t => h :: (snoc t v)\n    end.\n\n  Fixpoint rev (l:natlist) : natlist :=\n    match l with\n        | nil => nil\n        | h :: t => snoc (rev t) h\n    end.\n\n  Example test_rev1: rev [1;2;3] = [3;2;1].\n  Proof. reflexivity. Qed.\n  Example test_rev2: rev nil = nil.\n  Proof. reflexivity. Qed.\n\n  Theorem length_snoc : forall n : nat, forall l : natlist,\n                          length (snoc l n) = S (length l).\n  Proof.\n    intros n l. induction l as [| n' l'].\n    Case \"l = nil\". reflexivity.\n    Case \"l = cons n' l'\".\n      simpl. rewrite -> IHl'. reflexivity.\n  Qed.\n\n  Theorem rev_length : forall l : natlist,\n                         length (rev l) = length l.\n  Proof.\n    intros l. induction l as [| n l'].\n    Case \"l = nil\". reflexivity.\n    Case \"l = cons\".\n      simpl.\n      rewrite -> length_snoc. rewrite -> IHl'.\n      reflexivity.\n  Qed.\n\n  Theorem app_nil_end : forall l : natlist,\n                          l ++ [] = l.\n  Proof.\n    intros l. induction l as [| n l'].\n    Case \"l = nil\". reflexivity.\n    Case \"l = cons n l''\".\n      simpl.\n      rewrite -> IHl'.\n      reflexivity.\n  Qed.\n\n  Lemma snoc_cons_rev : forall n : nat, forall l : natlist,\n                          rev (snoc l n) = n :: rev l.\n  Proof.\n    intros n l. induction l as [| n' l'].\n    Case \"l = nil\". reflexivity.\n    Case \"l = n' :: l'\".\n      simpl.\n      rewrite -> IHl'.\n      reflexivity.\n  Qed.\n\n  Theorem rev_involutive : forall l : natlist,\n                             rev (rev l) = l.\n  Proof.\n    intros l. induction l as [| n l'].\n    Case \"l = nil\". reflexivity.\n    Case \"l = cons n l''\".\n      simpl.\n      rewrite -> snoc_cons_rev. rewrite -> IHl'.\n      reflexivity.\n  Qed.\n\n  Theorem app_assoc4:\n    forall l1 l2 l3 l4 : natlist,\n      l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.\n  Proof.\n    intros l1 l2 l3 l4. induction l1 as [| n l1'].\n    Case \"l1 = nil\".\n      simpl.\n      rewrite -> app_assoc.\n      reflexivity.\n    Case \"l1 = n :: l1'\".\n      simpl.\n      rewrite -> IHl1'.\n      reflexivity.\n  Qed.\n\n  Theorem snoc_append : forall (l:natlist) (n:nat),\n                          snoc l n = l ++ [n].\n  Proof.\n    intros l n. induction l as [| n' l'].\n    Case \"l = nil\". reflexivity.\n    Case \"l = n' :: l'\".\n      simpl.\n      rewrite -> IHl'.\n      reflexivity.\n  Qed.\n\n  Theorem distr_rev : forall l1 l2 : natlist,\n                        rev (l1 ++ l2) = (rev l2) ++ (rev l1).\n  Proof.\n    intros l1 l2. induction l1 as [| n l1'].\n    Case \"l1 = nil\".\n      simpl.\n      rewrite -> app_nil_end.\n      reflexivity.\n    Case \"l1 = n :: l1'\".\n      simpl.\n      rewrite -> IHl1'.\n      assert (H: snoc (rev l1') n = (rev l1') ++ [n]).\n      SCase \"Assertion\".\n        rewrite -> snoc_append.\n        reflexivity.\n      rewrite -> H.\n      rewrite -> snoc_append. rewrite -> app_assoc.\n      reflexivity.\n  Qed.\n\n  Lemma nonzeros_app : forall l1 l2 : natlist,\n                         nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).\n  Proof.\n    intros l1 l2. induction l1 as [|n l1'].\n    Case \"l1 = nil\". reflexivity.\n    Case \"l1 = n :: l1'\".\n      destruct n as [|n']; simpl; rewrite -> IHl1'; reflexivity.\n  Qed.\n\n  Fixpoint beq_natlist (l1 l2 : natlist) : bool :=\n    match l1, l2 with\n      | nil, nil => true\n      | nil, _ => false\n      | _, nil => false\n      | h :: t, h' :: t' => if beq_nat h h'\n                            then beq_natlist t t'\n                            else false\n    end.\n\n  Example test_beq_natlist1 : beq_natlist nil nil = true.\n  Proof. reflexivity. Qed.\n  Example test_beq_natlist2 : beq_natlist [1;2;3] [1;2;3] = true.\n  Proof. reflexivity. Qed.\n  Example test_beq_natlist3 : beq_natlist [1;2;3] [1;2;4] = false.\n  Proof. reflexivity. Qed.\n\n  Theorem bew_natlist_refl : forall l : natlist,\n                               true = beq_natlist l l.\n  Proof.\n    intros l. induction l as [|n l'].\n    Case \"l = nil\". reflexivity.\n    Case \"l = n :: l'\".\n      simpl.\n      rewrite <- beq_nat_refl.\n      rewrite -> IHl'.\n      reflexivity.\n  Qed.\n\n  Theorem count_member_nonzero : forall (s:bag),\n                                   ble_nat 1 (count 1 (1 :: s)) = true.\n  Proof.\n    intros s. reflexivity.\n  Qed.\n\n  Theorem ble_n_Sn : forall n,\n                       ble_nat n (S n) = true.\n  Proof.\n    intros n. induction n as [|n'].\n    Case \"0\". reflexivity.\n    Case \"S n'\".\n      simpl.\n      rewrite -> IHn'.\n      reflexivity.\n  Qed.\n\n  Theorem bag_count_sum: forall (s1 s2:bag) (n:nat),\n                           count n (sum s1 s2) = count n s1 + count n s2.\n  Proof.\n    intros s1 s2 n. induction s1 as [|n' s1'].\n    Case \"s1 = nil\". reflexivity.\n    Case \"s1 = n' :: s1'\".\n      simpl.\n      rewrite -> IHs1'.\n      destruct (beq_nat n' n); reflexivity.\n  Qed.\n\n  Theorem rev_injective : forall (l1 l2 : natlist),\n                            rev l1 = rev l2 -> l1 = l2.\n  Proof.\n    intros l1 l2 H.\n    rewrite <- rev_involutive.\n    rewrite <- H.\n    rewrite -> rev_involutive.\n    reflexivity.\n  Qed.\n\n  Inductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\n  Fixpoint index (n:nat) (l:natlist) : natoption :=\n    match l with\n      | nil => None\n      | a :: l' => match beq_nat n 0 with\n                     | true => Some a\n                     | false => index (pred n) l'\n                   end\n    end.\n\n  Example test_index1 : index 0 [4;5;6;7] = Some 4.\n  Proof. reflexivity. Qed.\n  Example test_index2 : index 3 [4;5;6;7] = Some 7.\n  Proof. reflexivity. Qed.\n  Example test_index3 : index 10 [4;5;6;7] = None.\n  Proof. reflexivity. Qed.\n\n  Definition option_elim (d:nat) (o:natoption) : nat :=\n    match o with\n      | Some n' => n'\n      | None => d\n    end.\n\n  Definition hd_opt (l:natlist) : natoption :=\n    match l with\n      | nil => None\n      | h :: t => Some h\n    end.\n\n  Example test_hd_opt1 : hd_opt [] = None.\n  Proof. reflexivity. Qed.\n  Example test_hd_opt2 : hd_opt [1] = Some 1.\n  Proof. reflexivity. Qed.\n  Example test_hd_opt3 : hd_opt [5;6] = Some 5.\n  Proof. reflexivity. Qed.\n\n  Theorem option_elim_hd : forall (l:natlist) (default:nat),\n                             hd default l = option_elim default (hd_opt l).\n  Proof.\n    intros l default. destruct l; reflexivity.\n  Qed.\n\n  Module Dictionary.\n\n    Inductive dictionary : Type :=\n    | empty : dictionary\n    | record : nat -> nat -> dictionary -> dictionary.\n\n    Definition insert (key value : nat) (d:dictionary) :\n      dictionary := (record key value d).\n\n    Fixpoint 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    Theorem dictionary_invariant1' : forall (d:dictionary) (k v : nat),\n                                       (find k (insert k v d)) = Some v.\n    Proof.\n      intros d k v.\n      simpl. rewrite <- beq_nat_refl. reflexivity.\n    Qed.\n\n    Theorem dictioniary_invariant2' :\n      forall (d:dictionary) (m n o : nat),\n        beq_nat m n = false -> find m d = find m (insert n o d).\n    Proof.\n      intros d m n o H.\n      simpl. rewrite -> H. reflexivity.\n    Qed.\n\n  End Dictionary.\nEnd NatList.\n", "meta": {"author": "micxjo", "repo": "sf", "sha": "a3a841e52ba88baddedea691259086520d0b85bd", "save_path": "github-repos/coq/micxjo-sf", "path": "github-repos/coq/micxjo-sf/sf-a3a841e52ba88baddedea691259086520d0b85bd/src/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706735, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7043194278249776}}
{"text": "Require Import List. Import ListNotations.\nRequire Import Recdef.\nRequire Import Lia.\n\nInductive tree : Type :=\n| Node : nat -> list tree -> tree.\n\nFunction binary_tree start n { wf lt n } :=\n  match n with\n  | 0 => Node start []\n  | S n =>\n    let p := Nat.div2 n in\n    match n - p with\n    | 0 => Node start []\n    | _ =>\n      let l := binary_tree start (n-p) in\n      match p with\n      | 0 => Node start [l]\n      | _ =>\n        let r := binary_tree start p in\n        Node start [l;r]\n      end\n    end\n  end.\nProof.\n  - intros; subst.\n    destruct n0; [discriminate|].\n    rewrite PeanoNat.Nat.sub_0_r in teq0.\n    inversion teq0; subst.\n    apply le_n.\n  - intros; subst.\n    destruct n0; [discriminate|].\n    destruct n0; [discriminate|].\n    inversion teq1; subst.\n    destruct n0.\n    + simpl. apply le_n_S, le_n_S, le_0_n.\n    + apply le_n_S, le_S, le_S. apply PeanoNat.Nat.lt_div2. apply le_n_S, le_0_n.\n  - intros; subst. lia.\n  - Search well_founded lt. apply Wf_nat.lt_wf.\nDefined.\n\nDefinition t_1024 := Eval compute in binary_tree 0 1024.\nDefinition t_1025 := Eval compute in binary_tree 1 1024.\n\nFrom elpi.apps Require Import feqb.\n\nfeqb nat.\nfeqb list.\nfeqb tree.\n\nScheme Boolean Equality for tree.\n\nEval compute in tree_beq t_1024 t_1025.\nEval compute in tree_eqb t_1024 t_1025.\n", "meta": {"author": "eponier", "repo": "compare-eq", "sha": "cc2da184e747d0ad6ada8597e1ebf03377e413e2", "save_path": "github-repos/coq/eponier-compare-eq", "path": "github-repos/coq/eponier-compare-eq/compare-eq-cc2da184e747d0ad6ada8597e1ebf03377e413e2/perfs/equality_test/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7043194239226876}}
{"text": "Require Import PolTac.\n\nTheorem pols_test1: forall x y, x < y ->  (x + x < y + x).\nintros.\npols.\nauto.\nQed.\n\nTheorem pols_test2: forall x y, y < 0 ->  (x + y < x).\nintros.\npols.\nauto.\nQed.\n \nTheorem pols_test4:\n forall x y,\n x * x  < y * y ->  ((x + y) * (x + y) < 2 * (x * y + y * y)).\nintros.\npols.\nauto.\nQed.\n \nTheorem pols_test5:\n forall x y z, x + y * (y + z) = 2 * z ->  2 * x + y * (y + z) = (x + z) + z.\nintros.\npols.\nauto.\nQed.\n\n\nTheorem polf_test1: forall x y, (1 <= y -> x  <= x  * y).\nintros.\npolf.\nQed.\n\nTheorem polf_test2: forall x y, 0 < x -> x  <= x  * y -> 1 <= y.\nintros.\nhyp_polf H0.\nauto.\nQed.\n\n\n\nTheorem polr_test1: forall x y z, (x + z) < y -> x + y + z < 2*y.\nintros x y z H.\npolr H.\npols.\nauto.\npols.\nauto.\nQed.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/PolTac/Natex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7042579194952132}}
{"text": "Require Export P04.\n\n\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 Hall Hexist.\n  destruct Hexist as [x HPnot].\n  unfold not in HPnot. apply HPnot. apply Hall.\nQed.\n\n", "meta": {"author": "tinkerrobot", "repo": "Software_Foundations_Solutions2", "sha": "c88b2445a3c06bba27fb97f939a8070b0d2713e6", "save_path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2", "path": "github-repos/coq/tinkerrobot-Software_Foundations_Solutions2/Software_Foundations_Solutions2-c88b2445a3c06bba27fb97f939a8070b0d2713e6/assignments/05/P05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7042579176573778}}
{"text": "\nRequire Import HoTT.Classes.interfaces.abstract_algebra\n               HoTT.Classes.interfaces.orders\n               HoTT.HSet HoTT.Basics.Trunc HProp HSet\n               Types.Universe UnivalenceImpliesFunext\n               TruncType UnivalenceAxiom Types.Sigma\n               FunextVarieties. \n\nRequire Import HoTTClasses.partiality\n               sierpinsky\n               dedekind. \n\n(** * Definition of wCpo on A:hSet *)\n\n\nSection Mono.\n\nContext {A : hSet}.\nContext {LA : Le A}.\nContext {B : hSet}.\nContext {LB : Le B}.\n\nDefinition monotonic  {OA : PartialOrder LA}\n                     {OB : PartialOrder LB}\n                     (f : A -> B) := forall (x y:A), \n                                 LA x y -> LB (f x) (f y).\n\n\nRecord fmono {OA : PartialOrder  LA}\n             {OB : PartialOrder  LB} : Type :=\n              mk_fmono{ fmonot :> A -> B;\n                        fmonotonic: monotonic fmonot}.\n\nDefinition fmon {OA : PartialOrder LA}\n                {OB : PartialOrder LB} : Le fmono.\nProof.\nrefine (fun f g:fmono => BuildhProp (forall x, LB (fmonot f x) (fmonot g x))).\nDefined.\n\nEnd Mono.\n\nSection Cpo.\n\nContext {A : hSet}.\nContext {LA : Le A}.\nContext {B : hSet}.\nContext {LB : Le B}.\n                                   \nClass cpo C {LC : Le C} := mkcpo{\n     cpobot : C;\n     lub : forall (f : IncreasingSequence C), C; \n     le_lub : forall (f : IncreasingSequence C) n, \n                                      LC (f n) (lub f); \n     lub_le : forall (f : IncreasingSequence C) x, \n               (forall n, LC (f n) x) -> LC (lub f) x ;\n     cpobot_bot : forall x, LC cpobot x    \n}.\n\nEnd Cpo.\n   \n", "meta": {"author": "FFaissole", "repo": "Valuations", "sha": "d06d2c8c9cce3ddf6137ca3440ab02031912d292", "save_path": "github-repos/coq/FFaissole-Valuations", "path": "github-repos/coq/FFaissole-Valuations/Valuations-d06d2c8c9cce3ddf6137ca3440ab02031912d292/Cpo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7042257601540329}}
{"text": "\n(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Sebastien Hinderer, 2004-04-20\n- Frederic Blanqui, 2005-02-24\n\npolynomials with multiple variables and integer coefficients\n\n- Kim Quyen Ly, 2013-08-23\n\nPolynomials with multiple variables and rational coefficients.\n\n*)\n\nSet Implicit Arguments.\n\nRequire Import VecUtil LogicUtil List ZArith Arith RingType2 QArith.\n\n(***********************************************************************)\n(** monomials with n variables *)\n\nNotation monom := (vector nat).\n\nLemma monom_eq_dec : forall n (m1 m2 : monom n), {m1 = m2} + {~m1 = m2}.\n  \nProof.\n  intros. eapply eq_vec_dec. apply eq_nat_dec.\nQed.\n\n(***********************************************************************)\n(** polynomials on a ring *)\n\nNotation A := Q.\nNotation \"0\" := QA0.\nNotation \"1\" := QA1.\n\nNotation \"x + y\" := (QAadd x y).\nNotation \"x * y\" := (QAmul x y).\nNotation \"- x\" := (QAopp x).\n\nDefinition Qpoly n := list (A * monom n).\n\nDelimit Scope Qpoly_scope with Qpoly.\n\nBind Scope Qpoly_scope with Qpoly.\n\n(***********************************************************************)\n(** coefficient of monomial m in polynomial p *)\n\nOpen Local Scope Q_scope.\n\nFixpoint Qcoef n (m : monom n) (p : Qpoly n) {struct p} : A :=\n  match p with\n    | nil => 0\n    | cons (c,m') p' =>\n      match monom_eq_dec m m' with\n\t| left _ => c + Qcoef m p'\n\t| right _ => Qcoef m p'\n      end\n  end.\n\n(***********************************************************************)\n(** simple polynomials *)\n\n(* monomial 1 *)\n\nOpen Local Scope nat_scope.\n\nNotation mone := (Vconst O).\n\n(* monomial x_i^1 *)\n\nFixpoint Qmxi n : forall i, lt i n -> monom n :=\n  match n as n return forall i, lt i n -> monom n with\n    | O => fun i h => False_rec (monom O) (lt_n_O h)\n    | S n' => fun i =>\n      match i as i return lt i (S n') -> monom (S n') with\n        | O => fun _ => Vcons (S O) (mone n')\n\t| S _ => fun h => Vcons O (Qmxi (lt_S_n h))\n      end\n  end.\n\nClose Scope nat_scope.\n\n(* polynomial x_i for i<n *)\n\n(* REMARK: mxi in the improving has kmax in the NewPolynom.v *)\n\nDefinition Qpxi n i (h : lt i n) : list (A * monom n) := (1, Qmxi h) :: nil.\n\n(* null polynomial *)\n\nDefinition Qpzero n : Qpoly n := nil.\n\n(* constant polynomial *)\n\nDefinition Qpconst n (c : A) : Qpoly n := (c, mone n) :: nil.\n\n(***********************************************************************)\n(** multiplication by a constant *)\n\nDefinition cpmult c n (p : Qpoly n) := map (fun cm => (c * fst cm, snd cm)) p.\n\n(***********************************************************************)\n(** opposite *)\n\nDefinition popp n (p : Qpoly n) := map (fun cm => (- fst cm, snd cm)) p.\n\nNotation \"'-' p\" := (popp p) (at level 35, right associativity) : Qpoly_scope.\n\n(***********************************************************************)\n(** addition *)\n\nFixpoint mpadd n (c : A) (m : monom n) (p : Qpoly n) {struct p} : Qpoly n :=\n  match p with\n    | nil => (c,m) :: nil\n    | cons (c',m') p' =>\n      match monom_eq_dec m m' with\n\t| left _ => (c+c',m) :: p'\n\t| right _ => (c',m') :: mpadd c m p'\n      end\n  end.\n\nFixpoint padd n (p1 p2 : Qpoly n) {struct p1} : Qpoly n :=\n  match p1 with\n    | nil => p2\n    | cons (c,m) p' => mpadd c m (padd p' p2)\n  end.\n\nInfix \"+\" := padd : Qpoly_scope.\n\n(***********************************************************************)\n(** substraction *)\n\nOpen Local Scope Qpoly_scope.\n\nDefinition pminus n (p1 p2 : Qpoly n) := p1 + (- p2).\n\nInfix \"-\" := pminus : Qpoly_scope.\n\n(***********************************************************************)\n(** multiplication *)\n\n(* monomial multiplication *)\n\nDefinition mmult n (m1 m2 : monom n) := Vmap2 plus m1 m2.\n\nDefinition mpmult n c (m : monom n) (p : Qpoly n) :=\n  map (fun cm => (c * fst cm, mmult m (snd cm))) p.\n\nFixpoint pmult n (p1 p2 : Qpoly n) {struct p1} : Qpoly n :=\n  match p1 with\n    | nil => nil\n    | cons (c,m) p' => mpmult c m p2 + pmult p' p2\n  end.\n\nInfix \"*\" := pmult : Qpoly_scope.\n\n(***********************************************************************)\n(** power *)\n\nFixpoint ppower n (p : Qpoly n) (k : nat) {struct k} : Qpoly n :=\n  match k with\n    | O => Qpconst n 1\n    | S k' => p * ppower p k'\n  end.\n\nInfix \"^\" := ppower : Qpoly_scope.\n\n(***********************************************************************)\n(** composition *)\n\nFixpoint mcomp n : monom n -> forall k, vector (Qpoly k) n -> Qpoly k :=\n  match n as n return monom n -> forall k, vector (Qpoly k) n -> Qpoly k with\n    | O => fun _ k _ => Qpconst k 1\n    | S _ => fun m _ ps => Vhead ps ^ Vhead m * mcomp (Vtail m) (Vtail ps)\n  end.\n\nFixpoint pcomp n (p : Qpoly n) k (ps : vector (Qpoly k) n) {struct p} : Qpoly k :=\n  match p with\n    | nil => nil\n    | cons (c,m) p' => cpmult c (mcomp m ps) + pcomp p' ps\n  end.\n\nClose Local Scope Qpoly_scope.\n\n(***********************************************************************)\n(** evaluation *)\n\nNotation vec := (vector A).\n\nNotation \"x * y\" := (QAmul x y).\nNotation \"x + y\" := (QAadd x y).\n\n(* Using Qpower Because power has type A and not define in Q. *)\n\nFixpoint meval n : monom n -> vec n -> A :=\n  match n as n return monom n -> vec n -> A with\n    | O => fun _ _ => 1\n    | S _ => fun m v => Qpower (Vhead v) (Z.of_nat (Vhead m)) * meval (Vtail m) (Vtail v)\n  end.\n\nFixpoint peval n (p : Qpoly n) (v : vec n) {struct p} : A :=\n  match p with\n    | nil => 0\n    | cons (c,m) p' => c * meval m v + peval p' v\n  end.\n\nRequire Import BoolUtil RelExtras2.\n\nNotation \"x =A= y\" := (QeqA x y) (at level 70).\n\nLemma meval_eqA : forall n (m : monom n) (v1 v2 : vec n),\n  beq_vec QbeqA v1 v2 = true -> meval m v1 =A= meval m v2.\n\nProof.\n  induction n; simpl; intros. refl. gen H. VSntac v1. VSntac v2. simpl.\n  rewrite andb_eq. rewrite QbeqA_ok. intuition.\n  rewrite H3. rewrite (IHn _ _ _ H4). refl.\nQed.\n\nImplicit Arguments meval_eqA [n m v1 v2].\n\nLemma peval_eqA : forall n (p : Qpoly n) (v1 v2 : vec n),\n  beq_vec QbeqA v1 v2 = true -> peval p v1 =A= peval p v2.\n\nProof.\n  induction p; simpl; intros. refl. destruct a. rewrite (IHp _ _ H).\n  rewrite (meval_eqA H). refl.\nQed.\n\nLemma meval_app : forall n1 (m1 : monom n1) (v1 : vec n1)\n  n2 (m2 : monom n2) (v2 : vec n2),\n  meval (Vapp m1 m2) (Vapp v1 v2) =A= meval m1 v1 * meval m2 v2.\n  \nProof. \n  induction m1. intros. VOtac. simpl in *. unfold QeqA. ring.\n  intros. VSntac v1. simpl. rewrite IHm1. unfold QeqA. ring. \nQed.\n\nLemma meval_one : forall n (v : vec n), meval (mone n) v =A= 1.\n  \nProof. \n  intros n v. induction v; simpl. refl. rewrite IHv. unfold QeqA.\n  ring.\nQed.\n\nLemma meval_xi : forall (n i: nat) (H: lt i n) (v: vec n),\n  meval (Qmxi H) v =A= Vnth v H.\n  \nProof.\n  induction n. intros. absurd(lt i 0). omega. hyp.\n  intro. destruct i; intros; VSntac v. simpl.\n  rewrite meval_one. unfold QeqA. ring. simpl. rewrite IHn. \n  unfold QeqA. ring.\nQed.\n\nLemma peval_const : forall n c (v : vec n), peval (Qpconst n c) v =A= c.\n  \nProof. \n  intros. simpl. rewrite meval_one. unfold QeqA. ring.\nQed.\n\nLemma peval_app : forall n (p1 p2 : Qpoly n) (v : vec n),\n  peval (p1 ++ p2) v =A= peval p1 v + peval p2 v.\n  \nProof.\n  intros. elim p1. simpl. auto. unfold QeqA. ring. \n  intros (c, m). intros. simpl. rewrite H. unfold QeqA. ring.  \nQed.\n\nLemma peval_opp : forall n (p : Qpoly n) (v : vec n),\n  peval (- p) v =A= - peval p v.\n  \nProof. \n  intros. elim p. simpl. unfold QeqA. ring.\n  intros (c, m). intros. simpl. rewrite H. unfold QeqA. ring.\nQed.\n\nLemma peval_mpadd : forall n c (m : monom n) (p : Qpoly n) (v : vec n),\n  peval (mpadd c m p) v =A= c * meval m v + peval p v.\n  \nProof. \n  intros. elim p. simpl in *. unfold QeqA. ring. \n  intros (c', m'). intros. simpl.\n  case (monom_eq_dec m m'); simpl; intro. subst m'. unfold QeqA. ring.\n  rewrite H. unfold QeqA. ring.\nQed.\n\nLemma peval_add : forall n (p1 p2 : Qpoly n) (v : vec n),\n  peval (p1 + p2) v =A= peval p1 v + peval p2 v.\n  \nProof. intros. elim p1. simpl. unfold QeqA. ring. auto.\n  intros (c, m). intros. simpl. rewrite peval_mpadd. rewrite H.\n  unfold QeqA. ring.\nQed.\n\nLemma peval_minus : forall n (p1 p2 : Qpoly n) (v : vec n),\n  peval (p1 - p2) v =A= peval p1 v - peval p2 v.\n  \nProof.\n  intros. unfold pminus. rewrite peval_add. rewrite peval_opp.\n  unfold QeqA. ring.\nQed.\n\nLemma Qpower_add : forall x n1 n2, Qpower x (n1 + n2) =A= Qpower x n1 * Qpower x n2.\nProof.\nAdmitted.\n\nLemma meval_mult : forall n (m1 m2 : monom n) (v : vec n),\n  meval (mmult m1 m2) v =A= meval m1 v * meval m2 v.\n  \nProof.\n  induction n; intros. VOtac. refl.\n  VSntac m1. VSntac m2. simpl. unfold mmult in IHn.\n  rewrite IHn. \n  (* TODO: new lemma for power_add in Q. *)\n  (*rewrite Qpower_add. ring.\n     Qed.*)\nAdmitted.\n\nLemma peval_mpmult : forall n c (m : monom n) (p : Qpoly n) (v : vec n),\n  peval (mpmult c m p) v =A= c * meval m v * peval p v.\n  \nProof.\n  induction p; intros; simpl. unfold QeqA. ring.\n  destruct a. simpl. rewrite IHp.\n  rewrite meval_mult. unfold QeqA. ring.\nQed.\n\nLemma peval_mult : forall n (p1 p2 : Qpoly n) (v : vec n),\n  peval (p1 * p2) v =A= peval p1 v * peval p2 v.\n  \nProof.\n  induction p1; intros; simpl. unfold QeqA. ring.\n  destruct a. simpl. rewrite peval_add.\n  rewrite peval_mpmult. rewrite IHp1. unfold QeqA. ring.\nQed.\n\nLemma peval_power : forall n (p : Qpoly n) (k : nat) (v : vec n),\n  peval (ppower p k) v =A= Qpower (peval p v) (Z.of_nat k).\n  \nProof.\n  induction k; intros; simpl. rewrite meval_one. unfold QeqA. ring.\n  rewrite peval_mult. rewrite IHk. \n  (* TODO *)\n  (*ring.\n     Qed.*)\nAdmitted.\n\nLemma peval_mcomp : forall n k (m: monom n) (ps: vector (Qpoly k) n)\n  (v: vec k), peval (mcomp m ps) v =A= meval m (Vmap (fun p => peval p v) ps).\n  \nProof.\n  induction n; intros. VOtac. simpl. rewrite meval_one.\n  unfold QeqA. ring.\n  VSntac m. VSntac ps. simpl. rewrite peval_mult. rewrite peval_power.\n  rewrite IHn. refl.\nQed.\n\nLemma peval_cpmult : forall n c (p : Qpoly n) (v : vec n),\n  peval (cpmult c p) v =A= c * peval p v.\n  \nProof.\n  induction p; intros; simpl. unfold QeqA. ring.\n  destruct a. simpl. rewrite IHp.\n  unfold QeqA. ring.\nQed.\n\nLemma peval_comp : forall n k (p: Qpoly n) (ps: vector (Qpoly k) n) (v: vec k),\n  peval (pcomp p ps) v =A= peval p (Vmap (fun p => peval p v) ps).\n  \nProof.\n  induction p; intros; simpl.\n  unfold QeqA. ring. destruct a. rewrite peval_add.\n  rewrite peval_cpmult. rewrite IHp. rewrite peval_mcomp.\n  unfold QeqA. ring. \nQed.", "meta": {"author": "fblanqui", "repo": "rainbow", "sha": "3c437c0d40f01038b1d82f2a9a8085e366de3f15", "save_path": "github-repos/coq/fblanqui-rainbow", "path": "github-repos/coq/fblanqui-rainbow/rainbow-3c437c0d40f01038b1d82f2a9a8085e366de3f15/devel/gwen/coq_old/NewPolynom2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7042257510166545}}
{"text": "\nRequire Import Omega.\n\nRequire Import bigstep.\nRequire Import coinduction.\nRequire Import datatypes.\nRequire Import Ndiv2oo.\nRequire Import streams_vs_lists.\n\n(* Function div2(n) = n/2       if n is even\n                      undefined otherwise\n\n   Example machine:\n      1 1 -> 1 B\n      1 B -> 2 R\n      2 1 -> 3 R\n      3 B -> 3 R\n      3 1 -> 4 B\n      4 B -> 2 R\n\nDefinition div2: Spec := (1, one, W B, 1) ::\n                         (1, B  ,   R, 2) ::\n                         (2, one,   R, 3) ::\n                         (3, B  ,   R, 3) ::\n                         (3, one, W B, 4) ::\n                         (4, B  ,   R, 2) :: nil.\n*)\n\n(************************ Convergence proof ************************)\n\nFixpoint repeat (n:nat): list Sym :=\n         match n with\n         | 0 => nil\n         | (S m) => (cons B (cons one (repeat m)))\n         end.\n\nLemma repeat_comm: forall n l,\n      (Cons B (Cons one (app_ls (repeat n) l))) =\n      (app_ls (repeat n) (Cons B (Cons one l))).\ninduction n.\nsimpl. reflexivity.\nsimpl. intro. rewrite <- IHn. reflexivity.\nQed.\n\n(*\ncycle from the state 2, if an even number of ones\n*)\n\nLemma div2_stops_2even: forall n l,\n      bf div2 (pair l\n                    (app_ls (ones (2*n)) Bs)) 2\n              (pair (app_ls (repeat n) l)\n                    Bs)                       2.\ninduction n.\n\nsimpl. intro. apply bfH.\nunfold is_value. auto.\n\nsimpl. intro. apply bfR with 3.\nauto.\nsimpl. replace (n + S (n + 0)) with (S (2*n)).\nsimpl. apply bfW with 4 B.\nauto.\nsimpl. apply bfR with 2.\nauto.\nsimpl. replace (n + (n + 0)) with (2*n).\nrewrite repeat_comm. apply IHn.\nomega. omega.\nQed.\n\n(*\nstop from the starting state 1\n*)\n\nLemma div2_stops: forall n,\n      bf div2 (pair Bs\n                    (Cons one (app_ls (ones (2*n)) Bs))) 1\n              (pair (app_ls (repeat n) (Cons B Bs))\n                    Bs)                                  2.\nintros. apply bfW with 1 B.\nauto.\nsimpl. apply bfR with 2.\nauto.\nsimpl. replace (n + (n + 0)) with (2*n). apply div2_stops_2even.\nomega.\nQed.\n", "meta": {"author": "asr", "repo": "tm-coinduction", "sha": "599083b74ffdf0c1032c5c2495fef9bf23a4058c", "save_path": "github-repos/coq/asr-tm-coinduction", "path": "github-repos/coq/asr-tm-coinduction/tm-coinduction-599083b74ffdf0c1032c5c2495fef9bf23a4058c/animation/examples/Ndiv2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7041847644626941}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nInductive binop  : Set := Plus | Times.\nInductive exp : Set :=\n| Const : nat -> exp\n| Binop : binop -> exp -> exp -> exp.\n\nDefinition binopDenote (b : binop) : nat -> nat -> nat :=\n  match b with\n  | Plus => plus\n  | Times => mult\n  end.               \n\nFixpoint expDenote (e : exp) : nat :=\n  match e with\n  | Const n => n\n  | Binop b e1 e2 => (binopDenote b) (expDenote e1) (expDenote e2)\n  end.\n\nEval simpl in expDenote (Const 42).\n\nEval simpl in expDenote (Binop Plus (Const 2) (Const 2)).\n\nEval simpl in expDenote (Binop Times (Binop Plus (Const 2) (Const 2)) (Const 7)).\n\nInductive instr : Set :=\n  | iConst : nat -> instr\n  | iBinop : binop -> instr.\n\nDefinition prog := list instr.\nDefinition stack := list nat.\n\nDefinition instrDenote (i : instr) (s : stack) : option stack :=\n  match i with\n  | iConst n => Some (n :: s)\n  | iBinop b =>\n    match s with\n    | arg1 :: arg2 :: s' => Some ((binopDenote b) arg1 arg2 :: s')\n    | _ => None\n    end\n  end.\n\nFixpoint progDenote (p : prog) (s : stack) : option stack :=\n  match p with\n  | nil => Some s\n  | i :: p' =>\n    match instrDenote i s with\n    | None => None\n    | Some s' => progDenote p' s'\n    end\n  end.\n\nFixpoint compile (e : exp) : prog :=\n  match e with\n  | Const n =>  iConst n :: nil\n  | Binop b e1 e2 => compile e2 ++ compile e1 ++ iBinop b :: nil\n  end.\n\nEval simpl in compile (Const 42).\n\n(* Eliding other eval examples... *)\n\nTheorem compile_correct : forall e, progDenote (compile e) nil\n                                    = Some (expDenote e :: nil).\nAbort.\n\nLemma compile_correct' : forall e p s,\n    progDenote (compile e ++ p) s = progDenote p (expDenote e :: s).\n  induction e. intros.\n  unfold compile. unfold expDenote.\n  unfold progDenote at 1. simpl.\n  fold progDenote. reflexivity.\n\n  intros. unfold compile. fold compile.\n  unfold expDenote. fold expDenote.\n  rewrite app_assoc_reverse.\n  rewrite IHe2.\n  rewrite app_assoc_reverse.\n  rewrite IHe1.\n  unfold progDenote at 1. simpl.\n  fold progDenote. reflexivity.\nAbort.\n\nLemma compile_correct' : forall e s p, progDenote (compile e ++ p) s =\n                                       progDenote p (expDenote e :: s).\n  induction e; crush.\nQed.\n\nTheorem compile_correct : forall e, progDenote (compile e) nil\n                                    = Some (expDenote e :: nil).\n  intros.\n  rewrite (app_nil_end (compile e)).\n  rewrite compile_correct'.\n  reflexivity.\nQed.\n\nInductive type : Set := Nat | Bool.\n\nInductive tbinop : type -> type -> type -> Set :=\n| TPlus : tbinop Nat Nat Nat\n| TTimes : tbinop Nat Nat Nat\n| TEq : forall t, tbinop t t Bool\n| TLt : tbinop Nat Nat Bool.\n\nInductive texp : type -> Set :=\n| TNConst : nat -> texp Nat\n| TBConst : bool -> texp Bool\n| TBinop : forall t1 t2 t, tbinop t1 t2 t -> texp t1 -> texp t2 -> texp t.\n\nDefinition typeDenote (t : type) : Set :=\n  match t with\n  | Nat => nat\n  | Bool => bool\n  end.\n\nDefinition tbinopDenote arg1 arg2 res (b : tbinop arg1 arg2 res)\n  : typeDenote arg1 -> typeDenote arg2 -> typeDenote res :=\n  match b with\n  | TPlus => plus\n  | TTimes => mult\n  | TEq Nat => beq_nat\n  | TEq Bool => eqb\n  | TLt => leb\n  end.\n\nFixpoint texpDenote t (e : texp t) : typeDenote t :=\n  match e with\n  | TNConst n => n\n  | TBConst b => b\n  | TBinop _ _ _ b e1 e2 => (tbinopDenote b) (texpDenote e1) (texpDenote e2)\n  end.\n\n(* Eliding example translations... *)\n\nDefinition tstack := list type.\n\nInductive tinstr : tstack -> tstack -> Set :=\n| TiNConst : forall s, nat -> tinstr s (Nat :: s)\n| TiBConst : forall s, bool -> tinstr s (Bool :: s)\n| TiBinop : forall arg1 arg2 res s,\n    tbinop arg1 arg2 res -> tinstr (arg1 :: arg2 :: s) (res :: s).\n\nInductive tprog : tstack -> tstack -> Set :=\n| TNil : forall s, tprog s s\n| TCons : forall s1 s2 s3,\n    tinstr s1 s2\n    -> tprog s2 s3\n    -> tprog s1 s3.\n\nFixpoint vstack (ts : tstack) : Set :=\n  match ts with\n  | nil => unit\n  | t :: ts' => typeDenote t * vstack ts'\n  end%type.\n\nDefinition tinstrDenote ts ts' (i : tinstr ts ts') : vstack ts -> vstack ts' :=\n  match i with\n  | TiNConst _ n => fun s => (n, s)\n  | TiBConst _ b => fun s => (b, s)\n  | TiBinop _ _ _ _ b => fun s =>\n                           let '(arg1, (arg2, s')) := s in\n                           ((tbinopDenote b) arg1 arg2, s')\n  end.\n\nFixpoint tprogDenote ts ts' (p : tprog ts ts') : vstack ts -> vstack ts' :=\n  match p with\n  | TNil _ => fun s => s\n  | TCons _ _ _ i p' => fun s => tprogDenote p' (tinstrDenote i s)\n  end.\n\nFixpoint tconcat ts ts' ts'' (p : tprog ts ts') : tprog ts' ts'' -> tprog ts ts'' :=\n  match p with\n  | TNil _ => fun p' => p'\n  | TCons _ _ _ i p1 => fun p' => TCons i (tconcat p1 p')\n  end.\n\nFixpoint tcompile t (e : texp t) (ts : tstack) : tprog ts (t :: ts) :=\n  match e with\n  | TNConst n => TCons (TiNConst _ n) (TNil _)\n  | TBConst b => TCons (TiBConst _ b) (TNil _)\n  | TBinop _ _ _ b e1 e2 => tconcat (tcompile e2 _)\n                                    (tconcat (tcompile e1 _) (TCons (TiBinop _ b) (TNil _)))\n  end.\n\nPrint tcompile.\n\nEval simpl in tprogDenote (tcompile (TNConst 42) nil) tt.\n\n(* Eliding other examples... *)\n\nTheorem tcompile_correct : forall t (e : texp t),\n    tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\nAbort.\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n    tprogDenote (tcompile e ts) s = (texpDenote e, s).\n  induction e; crush.\nAbort.\n\nLemma tconcat_correct : forall ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'')\n                               (s : vstack ts),\n    tprogDenote (tconcat p p') s = tprogDenote p' (tprogDenote p s).\n  induction p; crush.\nQed.\n\nHint Rewrite tconcat_correct.\n\nLemma tcompile_correct' : forall t (e : texp t) ts (s : vstack ts),\n    tprogDenote (tcompile e ts) s = (texpDenote e, s).\n  induction e; crush.\nQed.\n\nHint Rewrite tcompile_correct'.\n\nTheorem tcompile_correct : forall t (e : texp t),\n    tprogDenote (tcompile e nil) tt = (texpDenote e, tt).\n  crush.\nQed.\n\nRequire Extraction.\nExtraction tcompile.\n", "meta": {"author": "mattjquinn", "repo": "distsyscoq", "sha": "815906ff12881c26010dd8312a3bcb94fc45fe9a", "save_path": "github-repos/coq/mattjquinn-distsyscoq", "path": "github-repos/coq/mattjquinn-distsyscoq/distsyscoq-815906ff12881c26010dd8312a3bcb94fc45fe9a/cpdt/src/MQuinnStackMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7041847624231595}}
{"text": "(* BEGIN FIX *)\nRequire Import Coq.Strings.String.\n\nInductive aexp : Type :=\n  | ANum (n : nat)\n  | AVar (x : string)\n  | APlus (a a' : aexp)\n  | AMult (a a' : aexp).\n\nDefinition state : Type := string -> nat.\n\nFixpoint aeval (e : aexp)(s : state) : nat := match e with\n  | ANum n => n\n  | AVar x => s x\n  | APlus a a' => aeval a s + aeval a' s\n  | AMult a a' => aeval a s * aeval a' s\n  end.\n\nInductive zart : aexp -> Prop :=\n  | szam (n : nat) : zart (ANum n)\n  | osszeg (a a' : aexp)(az : zart a)\n           (a'z : zart a') : zart (APlus a a')\n  | szorzat (a a' : aexp)(az : zart a)\n            (a'z : zart a') : zart (AMult a a').\n\n\nExample pl1 : zart (APlus (ANum 3) (ANum 4)).\n(* END FIX *)\napply osszeg; apply szam. Qed.\n\n(* BEGIN FIX *)\nExample pl3 : zart (APlus (ANum 3) \n                          (AMult (ANum 1) (ANum 2))).\n(* END FIX *)\napply osszeg. apply szam. apply szorzat; apply szam. Qed.\n\n(* BEGIN FIX *)\nTheorem zartEval (e : aexp)(s s' : state)(p : zart e) :\n  aeval e s = aeval e s'.\n(* p-n vegezz indukciot! *)\n(* END FIX *)\ninduction p. simpl. reflexivity. simpl. rewrite -> IHp1. rewrite -> IHp2. reflexivity.\nsimpl. rewrite -> IHp1. rewrite -> IHp2. reflexivity. Qed.\n\n(* BEGIN FIX *)\n(* ez a fuggveny az osszes valtozot 0-ra csereli *)\nFixpoint lezar (e : aexp) : aexp :=\n(* END FIX *)\n  match e with\n  | ANum n => ANum n\n  | AVar x => ANum 0\n  | APlus a a' => APlus (lezar a) (lezar a')\n  | AMult a a' => AMult(lezar a) (lezar a')\nend.\n\n(* BEGIN FIX *)\nLemma lezarZart (e : aexp) : zart (lezar e).\n(* END FIX *)\ninduction e; simpl. apply szam. apply szam. apply osszeg. apply IHe1. apply IHe2. apply szorzat.\napply IHe1. apply IHe2. Qed.\n\n(* BEGIN FIX *)\nLemma ugyanaz (e : aexp)(p : zart e) : lezar e = e.\n(* END FIX *)\ninduction p. simpl. reflexivity. simpl. rewrite -> IHp1. rewrite -> IHp2. reflexivity.\nsimpl. rewrite -> IHp1. rewrite -> IHp2. reflexivity. Qed.\n\n(* BEGIN FIX *)\nLemma szemantikaUgyanaz (e : aexp)(s : state) :\n  aeval (lezar e) s = aeval e (fun _ => 0).\n(* END FIX *)\ninduction e; simpl; try (reflexivity); rewrite -> IHe1; rewrite IHe2; reflexivity. Qed.\n", "meta": {"author": "marko1777", "repo": "FormSzem", "sha": "7162911df76ca0fad2fb1b535affba2b2ed19cd7", "save_path": "github-repos/coq/marko1777-FormSzem", "path": "github-repos/coq/marko1777-FormSzem/FormSzem-7162911df76ca0fad2fb1b535affba2b2ed19cd7/06/hf06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7041847563045558}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom stdpp Require Import prelude.\nFrom VLSM.Lib Require Import Preamble.\n\n(** * Finite set utility definitions and lemmas *)\n\nSection sec_fin_set.\n\nContext\n  `{FinSet A C}.\n\nSection sec_general.\n\nLemma elements_subseteq (X Y : C) :\n  X ⊆ Y -> elements X ⊆ elements Y.\nProof. by set_solver. Qed.\n\nLemma union_size_ge_size1\n  (X Y : C) :\n  size (X ∪ Y) >= size X.\nProof.\n  apply subseteq_size.\n  apply subseteq_union.\n  by set_solver.\nQed.\n\nLemma union_size_ge_size2\n  (X Y : C) :\n  size (X ∪ Y) >= size Y.\nProof.\n  apply subseteq_size.\n  apply subseteq_union.\n  by set_solver.\nQed.\n\nLemma union_size_ge_average\n  (X Y : C) :\n  2 * size (X ∪ Y) >= size X + size Y.\nProof.\n  specialize (union_size_ge_size1 X Y) as Hx.\n  specialize (union_size_ge_size2 X Y) as Hy.\n  by lia.\nQed.\n\nLemma difference_size_le_self\n  (X Y : C) :\n  size (X ∖  Y) <= size X.\nProof.\n  apply subseteq_size.\n  apply elem_of_subseteq.\n  intros x Hx.\n  apply elem_of_difference in Hx.\n  by itauto.\nQed.\n\nLemma union_size_le_sum\n  (X Y : C) :\n  size (X ∪ Y) <= size X + size Y.\nProof.\n  specialize (size_union_alt X Y) as Halt.\n  rewrite Halt.\n  specialize (difference_size_le_self Y X).\n  by lia.\nQed.\n\nLemma intersection_size1\n  (X Y : C) :\n  size (X ∩ Y) <= size X.\nProof.\n  apply (subseteq_size (X ∩ Y) X).\n  by set_solver.\nQed.\n\nLemma intersection_size2\n  (X Y : C) :\n  size (X ∩ Y) <= size Y.\nProof.\n  apply (subseteq_size (X ∩ Y) Y).\n  by set_solver.\nQed.\n\nLemma difference_size_subset\n  (X Y : C)\n  (Hsub : Y ⊆ X) :\n  (Z.of_nat (size (X ∖ Y)) = Z.of_nat (size X) - Z.of_nat (size Y))%Z.\nProof.\n  assert (Htemp : Y ∪ (X ∖ Y) ≡ X).\n  {\n    apply set_equiv_equivalence.\n    intros a.\n    split; intros Ha.\n    - by set_solver.\n    - destruct (@decide (a ∈ Y)).\n      apply elem_of_dec_slow.\n      + by apply elem_of_union; left; itauto.\n      + by apply elem_of_union; right; set_solver.\n  }\n  assert (Htemp2 : size Y + size (X ∖ Y) = size X).\n  {\n    specialize (size_union Y (X ∖ Y)) as Hun.\n    spec Hun.\n    {\n      apply elem_of_disjoint.\n      intros a Ha Ha2.\n      apply elem_of_difference in Ha2.\n      by itauto.\n    }\n    rewrite Htemp in Hun.\n    by itauto.\n  }\n  by lia.\nQed.\n\nLemma difference_with_intersection\n  (X Y : C) :\n  X ∖ Y ≡ X ∖ (X ∩ Y).\nProof.\n  by set_solver.\nQed.\n\nLemma difference_size\n  (X Y : C) :\n  (Z.of_nat (size (X ∖ Y)) = Z.of_nat (size X) - Z.of_nat (size (X ∩ Y)))%Z.\nProof.\n  rewrite difference_with_intersection.\n  specialize (difference_size_subset X (X ∩ Y)) as Hdif.\n  by set_solver.\nQed.\n\nLemma difference_size_ge_disjoint_case\n  (X Y : C) :\n  size (X ∖ Y) >= size X - size Y.\nProof.\n  specialize (difference_size X Y).\n  specialize (intersection_size2 X Y).\n  by lia.\nQed.\n\nLemma list_to_set_size\n  (l : list A) :\n  size (list_to_set l (C := C)) <= length l.\nProof.\n  induction l; cbn.\n  - by rewrite size_empty; lia.\n  - specialize (union_size_le_sum ({[ a ]}) (list_to_set l)) as Hun_size.\n    by rewrite size_singleton in Hun_size; lia.\nQed.\n\nEnd sec_general.\n\nSection sec_filter.\n\nContext\n  (P P2 : A -> Prop)\n  `{!forall x, Decision (P x)}\n  `{!forall x, Decision (P2 x)}\n  (X Y : C).\n\nLemma filter_subset\n  (Hsub : X ⊆ Y) :\n  filter P X ⊆ filter P Y.\nProof.\n  intros a HaX.\n  apply elem_of_filter in HaX.\n  apply elem_of_filter.\n  by set_solver.\nQed.\n\nLemma filter_subprop\n  (Hsub : forall a, (P a -> P2 a)) :\n  filter P X ⊆ filter P2 X.\nProof.\n  intros a HaP.\n  apply elem_of_filter in HaP.\n  apply elem_of_filter.\n  by itauto.\nQed.\n\nEnd sec_filter.\n\nEnd sec_fin_set.\n\nSection sec_map.\n\nContext\n  `{FinSet A C}\n  `{FinSet B D}.\n\nLemma set_map_subset\n  (f : A -> B)\n  (X Y : C)\n  (Hsub : X ⊆ Y) :\n  set_map (D := D) f X ⊆ set_map (D := D) f Y.\nProof.\n  intros a Ha.\n  apply elem_of_map in Ha.\n  apply elem_of_map.\n  by firstorder.\nQed.\n\nLemma set_map_size_upper_bound\n  (f : A -> B)\n  (X : C) :\n  size (set_map (D := D) f X) <= size X.\nProof.\n  unfold set_map.\n  remember (f <$> elements X) as fX.\n  set (x := size (list_to_set _)).\n  cut (x <= length fX); [| by apply list_to_set_size].\n  enough (length fX = size X) by lia.\n  unfold size, set_size.\n  simpl; subst fX.\n  by apply fmap_length.\nQed.\n\nLemma elem_of_set_map_inj (f : A -> B) `{!Inj (=) (=) f} (a : A) (X : C) :\n  f a ∈@{D} fin_sets.set_map f X <-> a ∈ X.\nProof.\n  intros; rewrite elem_of_map.\n  split; [| by eexists].\n  intros (_v & HeqAv & H_v).\n  eapply inj in HeqAv; [| done].\n  by subst.\nQed.\n\nLemma set_map_id (X : C) : X ≡ set_map id X.\nProof. by set_solver. Qed.\n\nEnd sec_map.\n", "meta": {"author": "runtimeverification", "repo": "vlsm", "sha": "9115beb539257427467872ce65a224a0268cdae7", "save_path": "github-repos/coq/runtimeverification-vlsm", "path": "github-repos/coq/runtimeverification-vlsm/vlsm-9115beb539257427467872ce65a224a0268cdae7/theories/VLSM/Lib/FinSetExtras.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8056321819811829, "lm_q1q2_score": 0.704184750185952}}
{"text": "(***\n * Oqarina\n * Copyright 2021 Carnegie Mellon University.\n *\n * NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING\n * INSTITUTE MATERIAL IS FURNISHED ON AN \"AS-IS\" BASIS. CARNEGIE MELLON\n * UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR\n * IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF\n * FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS\n * OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT\n * MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT,\n * TRADEMARK, OR COPYRIGHT INFRINGEMENT.\n *\n * Released under a BSD (SEI)-style license, please see license.txt or\n * contact permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public\n * release and unlimited distribution.  Please see Copyright notice for\n * non-US Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party\n * Software subject to its own license:\n *\n * 1. Coq theorem prover (https://github.com/coq/coq/blob/master/LICENSE)\n * Copyright 2021 INRIA.\n *\n * 2. Coq JSON (https://github.com/liyishuai/coq-json/blob/comrade/LICENSE)\n * Copyright 2021 Yishuai Li.\n *\n * DM21-0762\n***)\n\n(*| .. coq:: none |*)\nRequire Import PeanoNat.\nRequire Import Lia.\n(*| .. coq:: |*)\n\n(*|\nStrong Induction Principle\n==========================\n\nCoq generates general induction principles. In some cases, we need a strong induction princple that is introduced in this section.\n\n|*)\n\n(*| .. coq:: none |*)\nSection StrongInduction.\n(*| .. coq:: |*)\n\n(*|\n.. index:: strong induction, CoqExt; strong induction (tactic)\n\nLet's assume we have a proposition indexed by a natural number and the stronger inductive hypothesis :coq:`IH`. |*)\n\nVariable P : nat -> Prop.\nHypothesis IH : forall m, (forall n, n < m -> P n) -> P m.\n\n(*| A direct result is that :coq:`P (0)` always holds. |*)\n\nLemma P0 : P 0.\nProof.\n    apply IH; intros.\n    inversion H.\nQed.\n\n(*| We prove a strong hypothesis first, then the final result. |*)\n\nLemma strong_induction_leq : forall n,\n    (forall m, m <= n -> P m).\nProof.\n    induction n ; intros.\n    - inversion H. apply P0.\n    - inversion H.\n        + apply IH. intros. apply le_S_n in H1. apply IHn. apply H1.\n        + apply IHn. apply H1.\nQed.\n\nTheorem strong_induction : forall n, P n.\nProof.\n    intros.\n    induction n.\n    - apply P0.\n    - apply IH. intros.\n      apply le_S_n in H.\n      eapply strong_induction_leq.\n      apply H.\n  Qed.\n\n(*| .. coq:: none |*)\nEnd StrongInduction.\n(*| .. coq:: |*)\n\n(*| Here is the new strong induction principle we obtain: |*)\n\nCheck strong_induction.\n(* strong_induction\n\t : forall P : nat -> Prop,\n       (forall m : nat, (forall n : nat, n < m -> P n) -> P m) ->\n       forall n : nat, P n *)\n\n(*| We provide the tactic :coq:`strong induction` to use this new principle in our proofs. |*)\n\nTactic Notation \"strong\" \"induction\" ident(n) :=\n    induction n using strong_induction.\n", "meta": {"author": "Oqarina", "repo": "oqarina", "sha": "5a5ea65688188e462b20d30ee4e5eba08285f629", "save_path": "github-repos/coq/Oqarina-oqarina", "path": "github-repos/coq/Oqarina-oqarina/oqarina-5a5ea65688188e462b20d30ee4e5eba08285f629/src/CoqExt/strong_ind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321843145405, "lm_q2_score": 0.8740772318846387, "lm_q1q2_score": 0.7041847495828286}}
{"text": "Require Import String.\nRequire Import DProp.Tactics.\nRequire Import List.\nImport List.ListNotations.\n\n(** * Syntax *)\nInductive sentence : Set :=\n| p_top : sentence\n| p_var : nat -> sentence\n| p_conj : sentence -> sentence -> sentence\n| p_neg : sentence -> sentence.\n\n(** We ask Coq to infer that equality of sentences is decidable *)\nScheme Equality for sentence.\nCheck sentence_eq_dec. (* : : forall x y : sentence, {x = y} + {x <> y} *)\n\n(** We'll give names to a few of the variables for convenience... *)\n(* Notation \"[ n ]\" := (p_var n). *)\nNotation \"'P'\" := (p_var 0).\nNotation \"'Q'\" := (p_var 1).\nNotation \"'R'\" := (p_var 2).\n\n(** ... and set up some pleasant notations. Notice some of these\n    notations define new connectives, like disjunction, in terms of\n    simpler ones.\n\n    These notations use Unicode. Proof General and CoqIDE both support\n    quick Unicode entry by typing TeX-like strings, see\n\n\n   - #<a href=\"https://coq.github.io/doc/master/refman/practical-tools/coqide.html\">Coqide information</a> (See \"Using Unicode symbols\")# *)\n(**\n   - #<a href=\"https://github.com/cpitclaudel/company-coq\">Company Coq</a>#\n\n*)\nNotation \"⊤\" := (p_top). (* \\top *)\nNotation \"x ∧ y\" := (p_conj x y) (at level 50). (* \\land or \\wedge *)\nNotation \"¬ x\" := (p_neg x) (at level 10). (* \\neg *)\nNotation \"⊥\" := (¬ ⊤). (* \\bot *)\nNotation \"x ∨ y\" := (¬ (¬ x ∧ ¬ y)) (at level 50). (* \\lor or \\vee *)\nNotation \"x ⇒ y\" := (¬ x ∨ y) (at level 70). (* \\Rightarrow *)\n\n\n(** Next we define the semantics of our language. We want to translate\n    sentences into Coq-level propositions, i.e. elements of type\n    [Prop]. You might expect to use [bool] here instead. Both choices\n    \"work,\" but using [Prop] is more general and more natural for the\n    metatheory we build here today, and ultimately it better captures\n    the idea that a semantics maps object-level propositions into\n    host-level propositions. Further information about this topic is\n    provided below.  *)\n\n(** A valuation might also be called an _interpretation_ or a _model_,\n    especially in the context of higher-order logics.\n\n    Notice that we require a valuation to come with a proof that the\n    propositional symbols of our language are mapped to propositions\n    for which the excluded middle is provable (or taken as an\n    axiom). This is necessary for our logic to be sound, which is\n    discussed in the section on proof theory.\n\n*)\nClass valuation : Type :=\n  { val : nat -> Prop\n  ; excluded_middle : forall n, val n \\/ ~ (val n)\n  }.\n\n(** This coercion tells Coq that we can use a [valuation] as a\n    function [nat -> Prop] by using its [val] field, for convenience. *)\nCoercion val : valuation >-> Funclass.\n\n(** * Model theory *)\n\n(** We define a recursive function, [denotation], which translates\n    sentences to \"actual\" propositions, meaning types whose sort is [Prop].\n\n    Another good name for this function could be \"is_true\" or \"translation.\"\n    Notice that any valuation [v] defines a subset [denotation v] of sentences,\n    namely the \"true\" ones.\n*)\nFixpoint denotation (v : valuation) (s : sentence) : Prop :=\n  match s with\n  | p_top => True\n  | p_var x => val x\n  | p_conj s1 s2 => denotation v s1 /\\ denotation v s2\n  | p_neg s1 => not (denotation v s1)\n  end.\n\n(** Hereafter we let [denotation] take the valuation as an implicit\n    argument. This follows common mathematical practice in which one\n    generally assumes some valuation is clear from the context.\n*)\nArguments denotation {v} s.\n\nNotation \"⟦ ϕ ⟧\" := (denotation ϕ). (* \\llbracket and \\rrbracket *)\n\n(** The law of excluded middle extends to the entire language straightforwardly. *)\nLemma full_lem : forall {v : valuation}, forall ϕ, ⟦ ϕ ⟧ \\/ ⟦ ¬ ϕ ⟧.\nProof.\n  intros v ϕ. induction ϕ.\n  - simpl. intuition.\n  - exact (excluded_middle n).\n  - simpl. intuition.\n  - simpl. intuition.\nQed.\n\n(** This tactic splits a (Coq-level) proof into two cases: one in\n    which ϕ is true and one in which it is false. *)\nLtac lem ϕ := destruct (full_lem ϕ).\n\n(** Sample usage of the [lem] tactic. *)\nGoal forall ϕ, forall v : valuation, ⟦ ϕ ⟧ \\/ ⟦ ¬ ϕ ⟧.\nProof.\n  intros.\n  lem ϕ.\n  - left. auto.\n  - right. auto.\nQed.\n\n(** In this file, we're not very interested in individual valuations. Instead,\n    we would like to define a notion of \"truth\" which abstracts over the valuation,\n    capturing the idea that a sentence is true under every possible interpretation.\n*)\nDefinition tautology (ϕ : sentence) := forall v : valuation, ⟦ ϕ ⟧.\n\n(** The universal quantifier---the dependent product---can be thought\n    of as a kind of infinite conjunction asserting the truth of ϕ\n    under _every_ interpretation. *)\n\n(** But we aren't just interested in tautologies. Often we want to\n    restrict our attention to only those valuations which make certain\n    pre-chosen sentences true. We develop this idea now.  *)\n\n(** A set of sentences is _satisfied_ or _modeled_ by a valuation if\n    all of its elements are true under that valuation. Elements of [Γ]\n    may also be called \"axioms.\" *)\nDefinition models (v : valuation) (Γ : list sentence) : Prop :=\n  forall ϕ, List.In ϕ Γ -> ⟦ ϕ ⟧.\n\n(** A valuation that models Γ is called a model, unsurprisingly. *)\nDefinition model Γ := { v : valuation | models v Γ }.\n\n(** A set of axioms _entails_ a sentence when that sentence is true\n    under all valuations that also satisfy the axioms, i.e. all\n    models. This relation also known as _semantic consequence_ or\n    _logical consequence_.\n\n    We might also read this definition as a restricted variant of\n    [tautology] that intersects only over that subset of valuations\n    which satisfy Γ. This property is sometimes known as being /valid/\n    for Γ (but this word is sometimes used differently). When we\n    formalize our proof system, the most ideal outcome is that the\n    provable formulas are precisely the valid ones. *)\nDefinition entails (Γ : list sentence) (ϕ : sentence) :=\n  forall v, models v Γ -> ⟦ ϕ ⟧.\n\nNotation \"Γ ⊧ ϕ\" := (entails Γ ϕ) (at level 70).\n\nHint Unfold tautology : dp.\nHint Unfold models : dp.\nHint Unfold entails : dp.\n\n(** Use the following tactic to quickly get rid unfold many definitions. *)\nTactic Notation \"unf\" := (repeat autounfold with dp in *).\n\n\n(** Exercise 1 (easy): Prove that a sentence is a tautology if and\n    only if it is entailed by the empty set of axioms.\n\n    Note: This is almost true by definition, but formalizing logics in\n   Coq often means proving such \"obvious\" facts. *)\nTheorem exercise1 : forall ϕ, tautology ϕ <-> nil ⊧ ϕ.\nProof.\nAdmitted.\n\n(** Exercise 2 (easy): Prove the following tautology.\n\n *)\nTheorem exercise2 : forall ϕ : sentence, tautology (ϕ ∨ ¬ ϕ).\nProof.\nAdmitted.\n\n(** Exercise 3 (medium): Have we formalized implication correctly?\n    Check our work by proving if [x ⇒ y] is true and [x] is true, then\n    [y] is true.\n\n    Hint: Use the [lem] tactic to do case analysis on [Q]. You may\n    want to [Unset Printing Notations]. *)\nTheorem exercise3 : forall (v : valuation), ⟦ P ⇒ Q ⟧ /\\ ⟦ P ⟧ -> ⟦ Q ⟧.\nProof.\nAdmitted.\n\n(** Logically equivalent formulas are those which have the same\n    denotation under every interpretation. Since we are interpreting\n    into [Prop], rather than [bool], we define this notion using\n    biconditionality (at the Coq level) rather than equality of\n    boolean values, but the idea is the same. *)\nDefinition equivalent ϕ ψ := forall (v : valuation), ⟦ ϕ ⟧ <-> ⟦ ψ ⟧.\n\n  (** Exercise 4 (easy): Prove that [P] and [P ∧ ⊤] are semantically\n  equivalent.  *)\nTheorem exercise4 : equivalent P (P ∧ ⊤).\nProof.\nAdmitted.\n\n (** Exercise [5] (medium): Prove that [P] and [P ∨ ¬ ⊤] are\n     semantically equivalent.  Use [lem P]. *)\nTheorem exercise5 : equivalent P (P ∨ ¬ ⊤).\nProof.\nAdmitted.\n\n (** Exercise 6 (hard): Why did the last exercise require law of\n     excluded middle, when Coq trivially proves the following\n     intuitionistic tautology? Can you prove (with pen and paper, not\n     in Coq) that the last exercise cannot be completed without LEM?\n     *)\nGoal forall p : Prop, p <-> (p \\/ ~ True).\n  tauto.\nQed.\n\n(** * Proof theory\n\n    This section explores basic proof theory. The goal is to define a\n    particular syntactical notion called \"proof,\" where each proof is\n    associated with a formula called its \"conclusion.\" Formulas with\n    proofs are \"theorems.\" Later, our primary goal will be to show\n    that a formula ϕ is entailed by Γ precisely if there is a proof\n    with conclusion ϕ using only axioms from Γ, i.e. the theorems are\n    exactly the valid statements. (Many logics do not have this strong\n    property, but propositional logic does.)  *)\n\n(** The following proof system is a natural deduction, which is\n    essentially the type system of the simply typed lambda\n    calculus. However, we are not formalizing lambda terms here, only\n    the type inhabitation property itself. To be precise, you might\n    call this a version of natural deduction with localized\n    hypotheses, but without proof objects.\n\n    The distinguishing feature of natural deduction is that each\n    logical connective is defined by introduction and elimination\n    rules. Another common system is a \"sequent calculus,\" which looks\n    visually similar but is subtly different. A sequent calculus would\n    better highlight the symmetries of logic and lend itself better to\n    automated proof search and inversion lemmas (discussed briefly in\n    the section on incompleteness). *)\n\nReserved Notation \"Γ ⊢ ϕ\" (at level 90).\nInductive provable (Γ : list sentence) : sentence -> Prop :=\n| j_var : forall ϕ, List.In ϕ Γ -> Γ ⊢ ϕ\n| j_conj_intro : forall ϕ ψ, Γ ⊢ ϕ -> Γ ⊢ ψ -> Γ ⊢ ϕ ∧ ψ\n| j_conj_elim1 : forall ϕ ψ, Γ ⊢ ϕ ∧ ψ -> Γ ⊢ ϕ\n| j_conj_elim2 : forall ϕ ψ, Γ ⊢ ϕ ∧ ψ -> Γ ⊢ ψ\n| j_neg_intro : forall ϕ, ϕ :: Γ ⊢ ⊥ -> Γ ⊢ ¬ ϕ\n| j_neg_elim : forall ϕ ψ, Γ ⊢ ϕ -> Γ ⊢ ¬ ϕ -> Γ ⊢ ψ\n| j_raa: forall ϕ, (¬ ϕ :: Γ ⊢ ¬ ⊤) -> Γ ⊢ ϕ\n| j_top_intro : Γ ⊢ ⊤\nwhere \"Γ ⊢ ϕ\" := (provable Γ ϕ).\n\n(** The next two lemmas are fundamental properties of most logics.\n    Substitution shows that provable hypotheses are\n    redundant. Weakening says unused hypotheses are okay and plays an\n    important role in proving substitution. *)\nLemma weakening : forall Γ1 Γ2 Γ3 ϕ,\n    Γ1 ++ Γ2 ⊢ ϕ ->\n    Γ1 ++ Γ3 ++ Γ2 ⊢ ϕ.\nProof.\n  intros ? ? ? ? Hϕ.\n  remember (Γ1 ++ Γ2) as Γ.\n  generalize dependent Γ1.\n  induction Hϕ; intros; subst.\n  - apply j_var.\n    rewrite ?List.in_app_iff in *.\n    intuition.\n  - apply j_conj_intro; auto.\n  - eapply j_conj_elim1. eauto.\n  - eapply j_conj_elim2. eauto.\n  - eapply j_neg_intro.\n    specialize (IHHϕ (ϕ :: Γ1)). simpl in *. auto.\n  - eapply j_neg_elim. eapply IHHϕ1; reflexivity. auto.\n  - eapply j_raa. specialize (IHHϕ (¬ ϕ :: Γ1)).\n    simpl in *. eauto.\n  - apply j_top_intro.\nQed.\n\n(** To picture substitution, imagine a natural deduction derivation D\n    that uses of ψ using hypotheses from Γ1, Γ2, and ϕ. Given a\n    natural deduction derivation E of ϕ, picture \"moving up\" the tree\n    of D and finding all leaves that introduce the axiom ϕ, and\n    replace them with E. Through Curry-Howard, this is essentially\n    function evaluation. *)\nLemma substitution : forall Γ1 ϕ Γ2 ψ,\n    Γ1 ++ (ϕ :: Γ2) ⊢ ψ ->\n    Γ2 ⊢ ϕ ->\n    Γ1 ++ Γ2 ⊢ ψ.\nProof.\n  intros ? ? ? ? J1 J2.\n  remember (List.app Γ1 (ϕ :: Γ2)).\n  generalize dependent Γ1.\n  induction J1; intros Γ1 Eq; subst.\n  - destruct (sentence_eq_dec ϕ ϕ0).\n    { (* Equal *)\n      subst.\n      replace (Γ1 ++ Γ2) with (nil ++ Γ1 ++ Γ2) by (rewrite app_nil_l; auto).\n      apply weakening. rewrite app_nil_l. auto. }\n    { (* Unequal *)\n      apply j_var.\n      rewrite ?List.in_app_iff in *.\n      destruct H; try tauto.\n      inversion H; subst. contradiction. tauto. }\n  - apply j_conj_intro; auto.\n  - eapply j_conj_elim1; auto.\n  - eapply j_conj_elim2; auto.\n  - apply j_neg_intro. specialize (IHJ1 (ϕ0 :: Γ1)). simpl in *. eauto.\n  - apply j_neg_elim with (ϕ := ϕ0); auto.\n  - apply j_raa.\n    specialize (IHJ1 (¬ ϕ0 :: Γ1)). simpl in *. eauto.\n  - apply j_top_intro.\nQed.\n\n(** * Relating proofs to truths*)\n\n(** The following exercise is mostly straightforward but\n    requires a good grasp on the definitions in play. By unfolding the\n    definitions, we see that soundness is a computation with two inputs:\n    - a \"proofs\" of a \"proposition\"\n    - a model of the axioms Γ\n    and the output is exactly a (Coq-level) proof of the (Coq-level) proposition\n    which interprets the \"proposition\" in that model!\n *)\n\n(** Exercise 7 (medium/hard): Prove that all sentences provable from Γ\n    are logically entailed by Γ.\n\n    The negation introduction and reductio ad absurdum cases may\n    require some pen-and-paper thinking. You will certainly need to\n    use the [lem] tactic at some point. *)\nTheorem soundness : forall Γ ϕ, (Γ ⊢ ϕ) -> Γ ⊧ ϕ.\nProof.\nAdmitted.\n\n\n(** Our next theorem is the converse of soundness, known as semantic\n    completeness. It states that logically valid sentences have\n    proofs. There is another notion of completeness (\"syntactical\n    (in)completeness\") discussed later. It is sometimes clear from\n    context which notion of completeness one has in mind, since\n    well-known logics have equally well-known completeness properties,\n    but this can also be a source of confusion to newcomers. The\n    reader is advised to be very careful when reading discussions of\n    this topic on the internet, which are frequently confusing and\n    often simply incorrect.\n\n    Many logics do not have semantic completeness. Fortunately,\n    propositional logic is one of the logics with this\n    property. Unfortunately, proving this is difficult, even for such\n    a simple system. In fact, that we won't even try to prove it in\n    Coq. You are encouraged to attempt it to find where the difficulty\n    lies.\n\n    Why should this be hard to prove? Consider the premise: In all\n    valuations satisfying every sentence of Γ, ϕ is true. This quite\n    abstract condition is a statement about truth tables. If we read\n    the statement of completeness as the type of a constructive proof\n    in Coq, we find a challenging problem: \"Given the fact that all\n    rows of a truth table that happen to satisfy each formula in Γ\n    also satisfy ϕ, find a natural deduction derivation of ϕ.\"\n\n    Notice the premise gives us almost no information about ϕ, not\n    even its basic structure. The sentences of Γ may also be very\n    complex, perhaps more complex than ϕ, so they don't necessary tell\n    us anything about ϕ's subformulas. In fact, while ϕ may be true\n    under every Γ-satisfying valuation, each Γ-satisfying row of the\n    truth table might make ϕ true \"for different reasons,\" so to speak\n    (try some examples). Where do we get started?\n\n    Nonetheless, this theorem is true, and can even be proved\n    constructively. For now, we admit it without proof.  *)\nTheorem completeness :  forall Γ ϕ, Γ ⊧ ϕ -> Γ ⊢ ϕ.\nProof.\n  intros Γ ϕ.\n  intros mod.\n  unf.\n  (* ????????????????????????????? *)\nAdmitted.\n\n  (** Exercise 8 (easy? hard?): Attempt to prove the following: \"There\n  is a sentence of propositional logic that is neither provable nor\n  disprovable from the empty set of axioms.\"\n\n  Use the formula [P] (a simple propositional variable) as ϕ.  Attempt\n  to prove this by induction on the derivation of P. A template has been provided.\n  What happens?\n *)\nTheorem syntactical_incompleteness : exists ϕ, not (nil ⊢ ϕ) /\\ not (nil ⊢ ¬ ϕ).\nProof.\n  exists P.\n  split; intro J.\n  - Case \"P is not provable\".\n  (** We want to scrutinize the supposed derivation of [P].\n      If we just do [induction J], Coq will automatically generalize over the context and conclusion P,\n      as if were trying to show there are no proofs of anything. To avoid this silly behavior,\n      we tell Coq to remember both the conclusion P and the emptiness of the context.\n      We also discharge trivial cases instantly. *)\n    Ltac cleanup := repeat match goal with | H : _ |- _ => specialize (H eq_refl) end.\n    remember nil as empty; remember P as conc;\n      induction J; subst; cleanup.\n    + SCase \"j_var\".\n      (* for you to finish *)\n      admit.\n    + SCase \"j_conj_intro\".\n      (* contradiction, the conclusions don't match *)\n      inversion Heqconc.\n    + SCase \"j_conj_elim1\".\n      (* Why doesn't the induction hypothesis apply?\n         What happens if you try [inversion] on the [J]? Why?\n       *)\n      admit.\n    + SCase \"j_conj_elim2\".\n      (* Same story as above. *)\n      admit.\n    + SCase \"j_neg_intro\".\n      (* contradiction, the conclusions don't match *)\n      inversion Heqconc.\n    + SCase \"j_neg_elim\".\n      (* Why doesn't the induction hypothesis apply?\n         What happens if you try [inversion] on the [J]? Why?\n       *)\n      admit.\n    + SCase \"j_raa\".\n      (* Why doesn't the induction hypothesis apply?\n         What happens if you try [inversion] on the [J]? Why?\n       *)\n      admit.\n    + SCase \"j_top_intro\".\n      (* contradiction, the conclusions don't match *)\n      inversion Heqconc.\n  - Case \"~ P is not provable\".\n    remember nil as empty; remember (¬ P) as conc;\n    induction J; subst; cleanup.\n    + SCase \"j_var\".\n      (* for you to finish *)\n      admit.\n    + SCase \"j_conj_intro\".\n      (* contradiction, the conclusions don't match *)\n      inversion Heqconc.\n    + SCase \"j_conj_elim1\".\n      (* What happens if you try [inversion] on the [J]? Why?\n       *)\n      admit.\n    + SCase \"j_conj_elim2\".\n      (* Same story as above. *)\n      admit.\n    + SCase \"j_neg_intro\".\n      inversion Heqconc. subst; clear Heqconc.\n      (* What happens if you try [inversion] on the [J]? Why? *)\n      admit.\n    + SCase \"j_neg_elim\".\n      (* What happens if you try [inversion] on the [J]? Why?\n       *)\n      admit.\n    + SCase \"j_raa\".\n      (* What happens if you try [inversion] on the [J]? Why?\n       *)\n      admit.\n    + SCase \"j_top_intro\".\n      (* contradiction, the conclusions don't match *)\n      inversion Heqconc.\nAbort.\n\n(** Exercise 9 (easy):\n    What do the hard cases above have in common? (Hint: Look at the\n    names of the rules that caused us difficulty.).\n*)\n\n(** The theorem above seems obvious, but it is hard to show by\n    examining proof trees. The trouble is that in each elimination\n    rule, we cannot be confident that the rule used to prove the\n    hypothesis is a corresponding introduction rule. Indeed, it might not\n    be: Perhaps we prove [P] by proving [P /\\ Q], and perhaps to prove\n    /that/ we use reductio ad absurdum (for example). Can you\n    rule this out?\n\n    Although implication is not defined primitively, it is an\n    illustrative example: Perhaps we prove [P] by showing [Q ⇒ P] and\n    [Q]. How can we rule this out? Fundamentally we need a\n    _cut-elimination_ theorem, specifically the corollary of a\n    canonical form lemma (or inversion lemma). This would justify a\n    more controlled case analysis by showing, without loss of\n    generality, that we may assume proofs are of a particularly simple\n    form.\n\n    We won't prove this hard theorem here. Instead, we can show the\n    above theorem by using soundness: We cannot prove [P] because it\n    is not true in all models!  *)\n\nDefinition vtrue : valuation :=\n  {| val := fun n => True ; excluded_middle := ltac:(intuition) |}.\n\nDefinition vfalse : valuation :=\n  {| val := fun n => False ; excluded_middle := ltac:(intuition) |}.\n\n(** Exercise 10 (medium): Prove the following statement using\n    the two constant valuations defined above. *)\nTheorem syntactical_incompleteness : exists ϕ, not (nil ⊢ ϕ) /\\ not (nil ⊢ ¬ ϕ).\nProof.\nAdmitted.\n\n\n(** * Commentary *)\n\n(** ** Understanding Incompleteness\n\n    So how can we understand Gödel's incompleteness theorem?\n\n    Let's imagine starting over at the beginning. Suppose instead of\n    formalizing propositional logic, we allowed propositions to vary\n    over tuples of /terms/, as well as introducing quantifiers. This\n    would be first-order logic (FOL).\n\n    Formalizing the syntax is not particularly hard (albeit\n    tedious). The semantics are also straightforward: The valuation\n    primarily consists of a type [D] called the /domain/, with\n    constants mapped to terms of [D], and functions denoting Coq-level\n    functions over D. Finally, relations will denote subsets of D\n    (e.g., binary relations are of type [D -> D -> Prop].\n\n    The proof rules are also not too complicated: To prove a\n    universally quantified sentence, give a natural deduction proof of\n    the body after substitution by a fresh variable known as a\n    /parameter/. Existentials are proved by proving the body for an\n    arbitrary closed term.\n\n    It turns out, this logic is also complete: if ϕ is true in all\n    models satisfying Γ, there is a natural deduction proof of ϕ using\n    the set Γ as axioms. This is Gödel's completeness theorem. First\n    order logic is essentially the strongest logic that can have this\n    property, as provability (as a semi-decidable property) is too\n    weak to properly capture the semantics of higher logics.\n\n    Finally, instead of considering an arbitrary Γ, consider a\n    particular set of sentences called the /Peano axioms/. (This set\n    is actually infinite due to the induction schema, so we would need\n    to tweak our definitions to handle this.) This combination of\n    first-order logic with a fixed set Γ of Peano axioms is\n    first-order Peano arithmetic. Coq's natural numbers type [nat] is a\n    model of this theory, but one can show there are other models.  *)\n    (** Gödel proved the following fact (actually, Gödel's theorem is\n    significantly more general. But the following is a corollary.):\n    There is a sentence ϕ of the language which is: *)\n(**\n    - True, in the sense that it is true when interpreted into the model given by\n      [nat].\n    - Unprovable: There is no natural deduction derivation of\n      this sentence.\n\n    Since Gödel also proved first-order logic is complete, as an\n    instant corollary we see ϕ is:\n    - invalid: There are models in Coq of first-order Peano\n      arithmetic in which the sentence is not true.\n    *)\n(** This last fact is somewhat of a coincidence. Gödel's\n    incompleteness theorem applies equally to say, second-order\n    arithmetic. That theory also has a (different!) sentence which is\n    true when interpreted into Coq's [nat] type, but unprovable in this\n    theory. However, this sentence is valid because second order\n    arithmetic has only one model, [nat], in which the sentence is true.\n    *)\n\n(** ** Why is incompleteness important? Or is it?\n\n    Clearly, syntactical incompleteness is not generally\n    surprising. For instance\n\n     - Coq is incomplete because it neither\n       proves nor disproves LEM\n     - Group theory is incomplete because it\n       neither proves nor disproves the commutativity property\n     - Propositional logic is incomplete because it neither proves nor\n       disproves any atomic propositional symbol P *)\n\n(** It is somewhat surprising that Peano arithmetic is incomplete,\n       because it is not at all obvious which properties of [nat] are\n       being left out. What else can we add? But it's still not\n       terribly hard to understand, either.  *)\n\n(** But Gödel's theorem says a lot more than this, because the real\n    theorem proves that **any** theory of natural numbers is\n    incomplete, provided: *)\n(**\n   - we can recognize valid proofs when we see them\n   - the theory can prove basic facts (things which can be proved without\n     even using induction) *)\n(** Surely it is reasonable to say Gödel's theorem proves the\n    incompleteness of any reasonable number theory. It is the\n    _fundamental inability to ever form a complete number theory_\n    which is so surprising.\n\n    Furthermore, some additional logic from Gödel proves that such a theory\n    cannot prove its own consistency. But why do we care? After all,\n    if we don't trust a logic, then we would never trust such a proof\n    of consistency in the first place. The answer is simple: Because\n    if arithmetic can't prove the consistency of itself, obviously it\n    could never prove the consistency of all of mathematics! This\n    effectively invalidates Hilbert's program to \"finitize\" mathematics. *)\n\n(** ** Does this mean natural numbers can't be defined?\n\n    Not in any mathematical sense. Coq can prove the uniqueness of [nat]\n    with some ease. ZFC (set theory) can also prove that there is a\n    set, omega, with the properties of natural numbers which is unique\n    up to ordinal isomorphism. If we upgrade first-order Peano\n    arithmetic to its second-order version, both Coq and ZFC (etc.)\n    prove that there is exactly one type/set that can model this\n    theory, so the valid first-order statements of second-order Peano\n    arithmeitic are precisely the \"true\" facts about natural numbers\n    (that are definable in first-order logic). Unfortunately, this\n    instantly proves second-order logic lacks the completeness\n    property of first-order logic, since the provable sentences of\n    second-order P.A. must be a strict subset of the true ones.\n\n    And so provided you are willing to work within a powerful theory\n    like Coq, there is absolutely a unique \"thing\" called the natural\n    numbers. It just happens that there will be some sentence of our\n    logic that we cannot prove, even though it is true if you\n    interpret your metalogic as a formal theory (inside some other\n    theory).  *)\n\n(** ** Interpreting into Prop and bool\n\n    You might expect that we would translate propositional logic into\n    [bool] instead. This would work for most purposes, and might better\n    align with your normal intuition for propositional logic, but\n    there are several reasons to prefer translation into [Prop] over [bool]:\n *)\n(**\n    1.) Due to Coq's constructive nature, we can only write functions\n    of type [sentence -> bool] that we can compute. This means we can only\n    describe computable models in Coq, which rules out much of\n    mathematics if you extend this to higher-order logics. In the best\n    case scenario, this is just an artificial limitation on which\n    individual models we can define in Coq. In some scenarios, it\n    might limit what we can prove about the metatheory, since we can't\n    describe uncomputable counterexamples, for example.\n *)\n(**\n    2.) Ultimately a semantics **must** map object-level propositions\n    into meta-level propositions, since [ X ⊧ ϕ ] is a proposition in\n    the host logic--that's the whole point. If we used a boolean\n    valued semantics in Coq, the notion [X ⊧ ϕ] must be understood as\n    the Coq-level proposition [⟦ ϕ ⟧ = 1] (for valuations satisfying\n    [X]), which means our boolean-semantics must be composed with the\n    function [fun b : bool => b = true : bool -> Prop]. Again, this \"works,\" but it\n    is somewhat awkward for some purposes in Coq.\n\n    A [bool]-valued semantics might be preferred if we want to compute\n    with propositional logic (such as to model circuits), but our\n    perspective is that [Prop]-valued interpretations are the more\n    general approach, and more illuminating when understanding the\n    relationship between the host and guest logics. This approach is\n    called algebraic semantics, and with propositional logic it means\n    our valuatons can be any Boolean-algebra homomorphism. Using [bool]\n    is then a kind of degenerate case.\n\n    How is our approach more general? Consider that ⟦ p → p ⟧ is a\n    propositional tautology, and accordingly [⟦ p ⟧ → ⟦ p ⟧] is\n    provable in Coq no matter what [ Prop ] we assign to [p], even if\n    that proposition is not itself provable in Coq. This illustrates\n    that the soundness of propositional logic does not depend on the\n    fact that we often study computable models of this logic.\n\n    However, there are some caveats to the algebraic approach in Coq:\n\n    1. We must assume LEM, or at least assume (or prove) this property\n    for every valuation we consider in order to have soundness. This\n    is a result of interpreting propositional logic into a\n    constructive logic.\n\n    2. If we want to \"count\" valuations (common when thinking about\n    circuits), the right notion of equivalence between two valuations\n    is that two interpretations yield equi-provable sentences in\n    Coq. Different valuations are rarely literally equal.\n\n*)\n", "meta": {"author": "dunnl", "repo": "dprop", "sha": "3cfac766ebe72ac3829fb6cfad83cffbb9e76727", "save_path": "github-repos/coq/dunnl-dprop", "path": "github-repos/coq/dunnl-dprop/dprop-3cfac766ebe72ac3829fb6cfad83cffbb9e76727/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276107, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7041657916532638}}
{"text": " (* We define what a ring ideal is, show that they yield congruences,\n define what a kernel is, and show that kernels are ideal. *)\nRequire Import\n  Coq.setoid_ring.Ring MathClasses.interfaces.abstract_algebra MathClasses.theory.rings.\nRequire Export\n   MathClasses.theory.ring_congruence.\n\n(* Require ua_congruence varieties.rings. *)\n\nClass RingIdeal A (P : A → Prop) `{Ring A} : Prop :=\n  { ideal_proper :> Proper ((=) ==> iff) P\n  ; ideal_NonEmpty :> NonEmpty (sig P)\n  ; ideal_closed_plus_negate : ∀ x y, P x → P y → P (x - y)\n  ; ideal_closed_mult_r : ∀ x y, P x → P (x * y)\n  ; ideal_closed_mult_l: ∀ x y, P y → P (x * y) }.\n\nNotation Factor A P := (Quotient A (λ x y, P (x - y))).\n\nSection ideal_congruence.\n  Context `{ideal : RingIdeal A P}.\n  Add Ring A2 : (rings.stdlib_ring_theory A).\n\n  (* If P is an ideal, we can easily derive some further closedness properties: *)\n  Hint Resolve (ideal_closed_plus_negate) (ideal_closed_mult_l) (ideal_closed_mult_r).\n\n  Lemma ideal_closed_0 : P 0.\n  Proof. destruct ideal_NonEmpty as [[x Px]]. rewrite <-(plus_negate_r x). intuition. Qed.\n  Hint Resolve ideal_closed_0.\n\n  Lemma ideal_closed_negate x : P x → P (-x).\n  Proof. intros. rewrite <- rings.plus_0_l. intuition. Qed.\n  Hint Resolve ideal_closed_negate.\n\n  Lemma ideal_closed_plus x y : P x → P y → P (x + y).\n  Proof. intros. assert (x + y = -(-x + -y)) as E by ring. rewrite E. intuition. Qed.\n  Hint Resolve ideal_closed_plus.\n\n  Global Instance: RingCongruence A (λ x y, P (x - y)).\n  Proof.\n    split.\n        constructor.\n          intros x. now rewrite plus_negate_r.\n         intros x y E. rewrite negate_swap_r. intuition.\n        intros x y z E1 E2. mc_setoid_replace (x - z) with ((x - y) + (y - z)) by ring. intuition.\n       intros ?? E. now rewrite E, plus_negate_r.\n      intros x1 x2 E1 y1 y2 E2.\n      mc_setoid_replace (x1 + y1 - (x2 + y2)) with ((x1 - x2) + (y1 - y2)) by ring. intuition.\n     intros x1 x2 E1 y1 y2 E2.\n     mc_setoid_replace (x1 * y1 - (x2 * y2)) with ((x1 - x2) * y1 + x2 * (y1 - y2)) by ring. intuition.\n    intros x1 x2 E.\n    mc_setoid_replace (-x1 - - x2) with (-(x1 - x2)) by ring. intuition.\n  Qed.\n\n  Lemma factor_ring_eq (x y : Factor A P) : x = y ↔ P ('x - 'y).\n  Proof. intuition. Qed.\n\n  Lemma factor_ring_eq_0 (x y : Factor A P) : x = 0 ↔ P ('x).\n  Proof.\n    transitivity (P ('x - cast (Factor A P) A 0)).\n     intuition.\n    apply ideal_proper. unfold cast. simpl. ring.\n  Qed.\n\n(*\n  Let hint := rings.encode_operations R.\n\n  Instance: Congruence rings.sig (λ _, congr_equiv).\n  Proof. constructor; intros; apply _. Qed.\n*)\nEnd ideal_congruence.\n\nSection kernel_is_ideal.\n  Context `{Ring A} `{Ring B} `{f : A → B} `{!SemiRing_Morphism f}.\n\n  Add Ring A3 : (rings.stdlib_ring_theory A).\n  Add Ring B3 : (rings.stdlib_ring_theory B).\n\n  Definition kernel : A → Prop := (= 0) ∘ f.\n\n  Global Instance: RingIdeal A kernel.\n  Proof with ring.\n   unfold kernel, compose, flip.\n   split.\n       intros ? ? E. now rewrite E.\n      split. exists (0:A). apply preserves_0.\n     intros ?? E E'. rewrite preserves_plus, preserves_negate, E, E'...\n    intros ?? E. rewrite preserves_mult, E...\n   intros ?? E. rewrite preserves_mult, E...\n  Qed.\nEnd kernel_is_ideal.\n", "meta": {"author": "coq-community", "repo": "math-classes", "sha": "c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc", "save_path": "github-repos/coq/coq-community-math-classes", "path": "github-repos/coq/coq-community-math-classes/math-classes-c11eb05a1e58a7293ef9a9a046ca02a9fd5b44bc/theory/ring_ideals.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7041657833949486}}
{"text": "(* The following lemma from Div2 is useful:\n   ind_0_1_SS : forall P : nat -> Prop,\n      P 0 -> P 1 ->\n        (forall n : nat, P n -> P (S (S n))) ->\n          forall n : nat, P n *)\n\nFrom Coq Require Import Arith Div2 Lia PeanoNat.\n\nFixpoint div_mod2 (n : nat) : (nat * bool) :=\n  match n with\n  | 0 => (0, false)\n  | 1 => (0, true)\n  | S (S n) => let (a, b) := div_mod2 n in (S a, b)\n  end.\n\nLemma dd n: exists m,  n = 2 * m \\/ n = 1 + 2 * m.\nProof.\n  intros.\n  induction n.\n  exists 0.\n  lia.\n  destruct IHn.\n  destruct H.\n  exists x.\n  lia.\n  exists (S x).\n  lia.\nQed.\n\nLemma div_spec1 n: div_mod2(2 * n) = (n, false).\nProof.\n  induction n.\n  easy.\n  simpl.\n  replace (n + S (n + 0)) with (S (2 * n)) by lia.\n  rewrite IHn.\n  easy.\nQed.\n\nLemma div_spec2 n: div_mod2(1 + 2 * n) = (n, true).\nProof.\n  induction n.\n  easy.\n  simpl.\n  replace (n + S (n + 0)) with (1 + 2 * n) by lia.\n  rewrite IHn.\n  easy.\nQed.\n\nLemma dind: forall (P : nat -> Prop),\n    P 0 ->\n    (forall n, P n ->  P (2 * n)) ->\n    (forall n, P n -> P (1 + 2 * n))\n    -> forall n, P n.\nProof.\n  intros P P0 P2 PS2 n.\n  induction n using lt_wf_ind.\n  destruct (dd n) as [m [Hd | Hd]]; subst.\n  destruct m.\n  simpl.\n  exact P0.\n  apply P2.\n  apply H.\n  lia.\n  apply PS2.\n  apply H.\n  lia.\nQed.\n\nFixpoint pow_sqr_aux (k b e : nat) : nat :=\n  match k, e with\n  | 0, _ => 1\n  | _, 0 => 1\n  | S k, _ => match div_mod2 e with\n              | (e', false) => pow_sqr_aux k (b * b) e'\n              | (e', true) => b * pow_sqr_aux k (b * b) e'\n              end\n  end.\n\nDefinition pow_sqr (b e : nat) : nat := pow_sqr_aux e b e.\n\nTheorem pow_eq (b e : nat) : pow_sqr b e = b ^ e.\nProof.\n  revert b.\n  induction e using dind; intros.\n  reflexivity.\n  unfold pow_sqr, pow_sqr_aux.\n  destruct e.\n  simpl.\n  reflexivity.\n  replace (2 * S e) with (S (S (2 * e))) by lia.\n  replace (S (S (2 * e))) with (2 * S e) by lia.\n  rewrite div_spec1.\n  destruct (div_mod2 (S e)).\n  destruct b0.\n  replace (e + S (e + 0)) with (1 + 2 * e) by lia.\n", "meta": {"author": "HaroldVemeno", "repo": "coq-stuff", "sha": "c233fca4c766781bb1f90d3356708f0519310fb5", "save_path": "github-repos/coq/HaroldVemeno-coq-stuff", "path": "github-repos/coq/HaroldVemeno-coq-stuff/coq-stuff-c233fca4c766781bb1f90d3356708f0519310fb5/pow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7041657821704734}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** * Finite sets library *)\n\n(** This module proves many properties of finite sets that\n    are consequences of the axiomatization in [FsetInterface]\n    Contrary to the functor in [FsetProperties] it uses\n    sets operations instead of predicates over sets, i.e.\n    [mem x s=true] instead of [In x s],\n    [equal s s'=true] instead of [Equal s s'], etc. *)\n\nRequire Import MSetProperties Zerob Sumbool Omega DecidableTypeEx.\n\nModule WEqPropertiesOn (Import E:DecidableType)(M:WSetsOn E).\nModule Import MP := WPropertiesOn E M.\nImport FM Dec.F.\nImport M.\n\nDefinition Add := MP.Add.\n\nSection BasicProperties.\n\n(** Some old specifications written with boolean equalities. *)\n\nVariable s s' s'': t.\nVariable x y z : elt.\n\nLemma mem_eq:\n  E.eq x y -> mem x s=mem y s.\nProof.\nintro H; rewrite H; auto.\nQed.\n\nLemma equal_mem_1:\n  (forall a, mem a s=mem a s') -> equal s s'=true.\nProof.\nintros; apply equal_1; unfold Equal; intros.\ndo 2 rewrite mem_iff; rewrite H; tauto.\nQed.\n\nLemma equal_mem_2:\n  equal s s'=true -> forall a, mem a s=mem a s'.\nProof.\nintros; rewrite (equal_2 H); auto.\nQed.\n\nLemma subset_mem_1:\n  (forall a, mem a s=true->mem a s'=true) -> subset s s'=true.\nProof.\nintros; apply subset_1; unfold Subset; intros a.\ndo 2 rewrite mem_iff; auto.\nQed.\n\nLemma subset_mem_2:\n  subset s s'=true -> forall a, mem a s=true -> mem a s'=true.\nProof.\nintros H a; do 2 rewrite <- mem_iff; apply subset_2; auto.\nQed.\n\nLemma empty_mem: mem x empty=false.\nProof.\nrewrite <- not_mem_iff; auto with set.\nQed.\n\nLemma is_empty_equal_empty: is_empty s = equal s empty.\nProof.\napply bool_1; split; intros.\nauto with set.\nrewrite <- is_empty_iff; auto with set.\nQed.\n\nLemma choose_mem_1: choose s=Some x -> mem x s=true.\nProof.\nauto with set.\nQed.\n\nLemma choose_mem_2: choose s=None -> is_empty s=true.\nProof.\nauto with set.\nQed.\n\nLemma add_mem_1: mem x (add x s)=true.\nProof.\nauto with set relations.\nQed.\n\nLemma add_mem_2: ~E.eq x y -> mem y (add x s)=mem y s.\nProof.\napply add_neq_b.\nQed.\n\nLemma remove_mem_1: mem x (remove x s)=false.\nProof.\nrewrite <- not_mem_iff; auto with set relations.\nQed.\n\nLemma remove_mem_2: ~E.eq x y -> mem y (remove x s)=mem y s.\nProof.\napply remove_neq_b.\nQed.\n\nLemma singleton_equal_add:\n  equal (singleton x) (add x empty)=true.\nProof.\nrewrite (singleton_equal_add x); auto with set.\nQed.\n\nLemma union_mem:\n  mem x (union s s')=mem x s || mem x s'.\nProof.\napply union_b.\nQed.\n\nLemma inter_mem:\n  mem x (inter s s')=mem x s && mem x s'.\nProof.\napply inter_b.\nQed.\n\nLemma diff_mem:\n  mem x (diff s s')=mem x s && negb (mem x s').\nProof.\napply diff_b.\nQed.\n\n(** properties of [mem] *)\n\nLemma mem_3 : ~In x s -> mem x s=false.\nProof.\nintros; rewrite <- not_mem_iff; auto.\nQed.\n\nLemma mem_4 : mem x s=false -> ~In x s.\nProof.\nintros; rewrite not_mem_iff; auto.\nQed.\n\n(** Properties of [equal] *)\n\nLemma equal_refl: equal s s=true.\nProof.\nauto with set.\nQed.\n\nLemma equal_sym: equal s s'=equal s' s.\nProof.\nintros; apply bool_1; do 2 rewrite <- equal_iff; intuition.\nQed.\n\nLemma equal_trans:\n equal s s'=true -> equal s' s''=true -> equal s s''=true.\nProof.\nintros; rewrite (equal_2 H); auto.\nQed.\n\nLemma equal_equal:\n equal s s'=true -> equal s s''=equal s' s''.\nProof.\nintros; rewrite (equal_2 H); auto.\nQed.\n\nLemma equal_cardinal:\n equal s s'=true -> cardinal s=cardinal s'.\nProof.\nauto with set.\nQed.\n\n(* Properties of [subset] *)\n\nLemma subset_refl: subset s s=true.\nProof.\nauto with set.\nQed.\n\nLemma subset_antisym:\n subset s s'=true -> subset s' s=true -> equal s s'=true.\nProof.\nauto with set.\nQed.\n\nLemma subset_trans:\n subset s s'=true -> subset s' s''=true -> subset s s''=true.\nProof.\ndo 3 rewrite <- subset_iff; intros.\napply subset_trans with s'; auto.\nQed.\n\nLemma subset_equal:\n equal s s'=true -> subset s s'=true.\nProof.\nauto with set.\nQed.\n\n(** Properties of [choose] *)\n\nLemma choose_mem_3:\n is_empty s=false -> {x:elt|choose s=Some x /\\ mem x s=true}.\nProof.\nintros.\ngeneralize (@choose_1 s) (@choose_2 s).\ndestruct (choose s);intros.\nexists e;auto with set.\ngeneralize (H1 (eq_refl None)); clear H1.\nintros; rewrite (is_empty_1 H1) in H; discriminate.\nQed.\n\nLemma choose_mem_4: choose empty=None.\nProof.\ngeneralize (@choose_1 empty).\ncase (@choose empty);intros;auto.\nelim (@empty_1 e); auto.\nQed.\n\n(** Properties of [add] *)\n\nLemma add_mem_3:\n mem y s=true -> mem y (add x s)=true.\nProof.\nauto with set.\nQed.\n\nLemma add_equal:\n mem x s=true -> equal (add x s) s=true.\nProof.\nauto with set.\nQed.\n\n(** Properties of [remove] *)\n\nLemma remove_mem_3:\n mem y (remove x s)=true -> mem y s=true.\nProof.\nrewrite remove_b; intros H;destruct (andb_prop _ _ H); auto.\nQed.\n\nLemma remove_equal:\n mem x s=false -> equal (remove x s) s=true.\nProof.\nintros; apply equal_1; apply remove_equal.\nrewrite not_mem_iff; auto.\nQed.\n\nLemma add_remove:\n mem x s=true -> equal (add x (remove x s)) s=true.\nProof.\nintros; apply equal_1; apply add_remove; auto with set.\nQed.\n\nLemma remove_add:\n mem x s=false -> equal (remove x (add x s)) s=true.\nProof.\nintros; apply equal_1; apply remove_add; auto.\nrewrite not_mem_iff; auto.\nQed.\n\n(** Properties of [is_empty] *)\n\nLemma is_empty_cardinal: is_empty s = zerob (cardinal s).\nProof.\nintros; apply bool_1; split; intros.\nrewrite MP.cardinal_1; simpl; auto with set.\nassert (cardinal s = 0) by (apply zerob_true_elim; auto).\nauto with set.\nQed.\n\n(** Properties of [singleton] *)\n\nLemma singleton_mem_1: mem x (singleton x)=true.\nProof.\nauto with set relations.\nQed.\n\nLemma singleton_mem_2: ~E.eq x y -> mem y (singleton x)=false.\nProof.\nintros; rewrite singleton_b.\nunfold eqb; destruct (E.eq_dec x y); intuition.\nQed.\n\nLemma singleton_mem_3: mem y (singleton x)=true -> E.eq x y.\nProof.\nintros; apply singleton_1; auto with set.\nQed.\n\n(** Properties of [union] *)\n\nLemma union_sym:\n equal (union s s') (union s' s)=true.\nProof.\nauto with set.\nQed.\n\nLemma union_subset_equal:\n subset s s'=true -> equal (union s s') s'=true.\nProof.\nauto with set.\nQed.\n\nLemma union_equal_1:\n equal s s'=true-> equal (union s s'') (union s' s'')=true.\nProof.\nauto with set.\nQed.\n\nLemma union_equal_2:\n equal s' s''=true-> equal (union s s') (union s s'')=true.\nProof.\nauto with set.\nQed.\n\nLemma union_assoc:\n equal (union (union s s') s'') (union s (union s' s''))=true.\nProof.\nauto with set.\nQed.\n\nLemma add_union_singleton:\n equal (add x s) (union (singleton x) s)=true.\nProof.\nauto with set.\nQed.\n\nLemma union_add:\n equal (union (add x s) s') (add x (union s s'))=true.\nProof.\nauto with set.\nQed.\n\n(* caracterisation of [union] via [subset] *)\n\nLemma union_subset_1: subset s (union s s')=true.\nProof.\nauto with set.\nQed.\n\nLemma union_subset_2: subset s' (union s s')=true.\nProof.\nauto with set.\nQed.\n\nLemma union_subset_3:\n subset s s''=true -> subset s' s''=true ->\n  subset (union s s') s''=true.\nProof.\nintros; apply subset_1; apply union_subset_3; auto with set.\nQed.\n\n(** Properties of [inter] *)\n\nLemma inter_sym: equal (inter s s') (inter s' s)=true.\nProof.\nauto with set.\nQed.\n\nLemma inter_subset_equal:\n subset s s'=true -> equal (inter s s') s=true.\nProof.\nauto with set.\nQed.\n\nLemma inter_equal_1:\n equal s s'=true -> equal (inter s s'') (inter s' s'')=true.\nProof.\nauto with set.\nQed.\n\nLemma inter_equal_2:\n equal s' s''=true -> equal (inter s s') (inter s s'')=true.\nProof.\nauto with set.\nQed.\n\nLemma inter_assoc:\n equal (inter (inter s s') s'') (inter s (inter s' s''))=true.\nProof.\nauto with set.\nQed.\n\nLemma union_inter_1:\n equal (inter (union s s') s'') (union (inter s s'') (inter s' s''))=true.\nProof.\nauto with set.\nQed.\n\nLemma union_inter_2:\n equal (union (inter s s') s'') (inter (union s s'') (union s' s''))=true.\nProof.\nauto with set.\nQed.\n\nLemma inter_add_1: mem x s'=true ->\n equal (inter (add x s) s') (add x (inter s s'))=true.\nProof.\nauto with set.\nQed.\n\nLemma inter_add_2: mem x s'=false ->\n equal (inter (add x s) s') (inter s s')=true.\nProof.\nintros; apply equal_1; apply inter_add_2.\nrewrite not_mem_iff; auto.\nQed.\n\n(* caracterisation of [union] via [subset] *)\n\nLemma inter_subset_1: subset (inter s s') s=true.\nProof.\nauto with set.\nQed.\n\nLemma inter_subset_2: subset (inter s s') s'=true.\nProof.\nauto with set.\nQed.\n\nLemma inter_subset_3:\n subset s'' s=true -> subset s'' s'=true ->\n  subset s'' (inter s s')=true.\nProof.\nintros; apply subset_1; apply inter_subset_3; auto with set.\nQed.\n\n(** Properties of [diff] *)\n\nLemma diff_subset: subset (diff s s') s=true.\nProof.\nauto with set.\nQed.\n\nLemma diff_subset_equal:\n subset s s'=true -> equal (diff s s') empty=true.\nProof.\nauto with set.\nQed.\n\nLemma remove_inter_singleton:\n equal (remove x s) (diff s (singleton x))=true.\nProof.\nauto with set.\nQed.\n\nLemma diff_inter_empty:\n equal (inter (diff s s') (inter s s')) empty=true.\nProof.\nauto with set.\nQed.\n\nLemma diff_inter_all:\n equal (union (diff s s') (inter s s')) s=true.\nProof.\nauto with set.\nQed.\n\nEnd BasicProperties.\n\nHint Immediate empty_mem is_empty_equal_empty add_mem_1\n   remove_mem_1 singleton_equal_add union_mem inter_mem\n   diff_mem equal_sym add_remove remove_add : set.\nHint Resolve equal_mem_1 subset_mem_1 choose_mem_1\n   choose_mem_2 add_mem_2 remove_mem_2 equal_refl equal_equal\n   subset_refl subset_equal subset_antisym\n   add_mem_3 add_equal remove_mem_3 remove_equal : set.\n\n\n(** General recursion principle *)\n\nLemma set_rec:  forall (P:t->Type),\n (forall s s', equal s s'=true -> P s -> P s') ->\n (forall s x, mem x s=false -> P s -> P (add x s)) ->\n P empty -> forall s, P s.\nProof.\nintros.\napply set_induction; auto; intros.\napply X with empty; auto with set.\napply X with (add x s0); auto with set.\napply equal_1; intro a; rewrite add_iff; rewrite (H0 a); tauto.\napply X0; auto with set; apply mem_3; auto.\nQed.\n\n(** Properties of [fold] *)\n\nLemma exclusive_set : forall s s' x,\n ~(In x s/\\In x s') <-> mem x s && mem x s'=false.\nProof.\nintros; do 2 rewrite mem_iff.\ndestruct (mem x s); destruct (mem x s'); intuition.\nQed.\n\nSection Fold.\nVariables (A:Type)(eqA:A->A->Prop)(st:Equivalence eqA).\nVariables (f:elt->A->A)(Comp:Proper (E.eq==>eqA==>eqA) f)(Ass:transpose eqA f).\nVariables (i:A).\nVariables (s s':t)(x:elt).\n\nLemma fold_empty: (fold f empty i) = i.\nProof.\napply fold_empty; auto.\nQed.\n\nLemma fold_equal:\n equal s s'=true -> eqA (fold f s i) (fold f s' i).\nProof.\nintros; apply fold_equal with (eqA:=eqA); auto with set.\nQed.\n\nLemma fold_add:\n mem x s=false -> eqA (fold f (add x s) i) (f x (fold f s i)).\nProof.\nintros; apply fold_add with (eqA:=eqA); auto.\nrewrite not_mem_iff; auto.\nQed.\n\nLemma add_fold:\n  mem x s=true -> eqA (fold f (add x s) i) (fold f s i).\nProof.\nintros; apply add_fold with (eqA:=eqA); auto with set.\nQed.\n\nLemma remove_fold_1:\n mem x s=true -> eqA (f x (fold f (remove x s) i)) (fold f s i).\nProof.\nintros; apply remove_fold_1 with (eqA:=eqA); auto with set.\nQed.\n\nLemma remove_fold_2:\n mem x s=false -> eqA (fold f (remove x s) i) (fold f s i).\nProof.\nintros; apply remove_fold_2 with (eqA:=eqA); auto.\nrewrite not_mem_iff; auto.\nQed.\n\nLemma fold_union:\n (forall x, mem x s && mem x s'=false) ->\n eqA (fold f (union s s') i) (fold f s (fold f s' i)).\nProof.\nintros; apply fold_union with (eqA:=eqA); auto.\nintros; rewrite exclusive_set; auto.\nQed.\n\nEnd Fold.\n\n(** Properties of [cardinal] *)\n\nLemma add_cardinal_1:\n forall s x, mem x s=true -> cardinal (add x s)=cardinal s.\nProof.\nauto with set.\nQed.\n\nLemma add_cardinal_2:\n forall s x, mem x s=false -> cardinal (add x s)=S (cardinal s).\nProof.\nintros; apply add_cardinal_2; auto.\nrewrite not_mem_iff; auto.\nQed.\n\nLemma remove_cardinal_1:\n forall s x, mem x s=true -> S (cardinal (remove x s))=cardinal s.\nProof.\nintros; apply remove_cardinal_1; auto with set.\nQed.\n\nLemma remove_cardinal_2:\n forall s x, mem x s=false -> cardinal (remove x s)=cardinal s.\nProof.\nintros; apply Equal_cardinal; apply equal_2; auto with set.\nQed.\n\nLemma union_cardinal:\n forall s s', (forall x, mem x s && mem x s'=false) ->\n cardinal (union s s')=cardinal s+cardinal s'.\nProof.\nintros; apply union_cardinal; auto; intros.\nrewrite exclusive_set; auto.\nQed.\n\nLemma subset_cardinal:\n forall s s', subset s s'=true -> cardinal s<=cardinal s'.\nProof.\nintros; apply subset_cardinal; auto with set.\nQed.\n\nSection Bool.\n\n(** Properties of [filter] *)\n\nVariable f:elt->bool.\nVariable Comp: Proper (E.eq==>Logic.eq) f.\n\nLet Comp' : Proper (E.eq==>Logic.eq) (fun x =>negb (f x)).\nProof.\nrepeat red; intros; f_equal; auto.\nQed.\n\nLemma filter_mem: forall s x, mem x (filter f s)=mem x s && f x.\nProof.\nintros; apply filter_b; auto.\nQed.\n\nLemma for_all_filter:\n forall s, for_all f s=is_empty (filter (fun x => negb (f x)) s).\nProof.\nintros; apply bool_1; split; intros.\napply is_empty_1.\nunfold Empty; intros.\nrewrite filter_iff; auto.\nred; destruct 1.\nrewrite <- (@for_all_iff s f) in H; auto.\nrewrite (H a H0) in H1; discriminate.\napply for_all_1; auto; red; intros.\nrevert H; rewrite <- is_empty_iff.\nunfold Empty; intro H; generalize (H x); clear H.\nrewrite filter_iff; auto.\ndestruct (f x); auto.\nQed.\n\nLemma exists_filter :\n forall s, exists_ f s=negb (is_empty (filter f s)).\nProof.\nintros; apply bool_1; split; intros.\ndestruct (exists_2 Comp H) as (a,(Ha1,Ha2)).\napply bool_6.\nred; intros; apply (@is_empty_2 _ H0 a); auto with set.\ngeneralize (@choose_1 (filter f s)) (@choose_2 (filter f s)).\ndestruct (choose (filter f s)).\nintros H0 _; apply exists_1; auto.\nexists e; generalize (H0 e); rewrite filter_iff; auto.\nintros _ H0.\nrewrite (is_empty_1 (H0 (eq_refl None))) in H; auto; discriminate.\nQed.\n\nLemma partition_filter_1:\n forall s, equal (fst (partition f s)) (filter f s)=true.\nProof.\nauto with set.\nQed.\n\nLemma partition_filter_2:\n forall s, equal (snd (partition f s)) (filter (fun x => negb (f x)) s)=true.\nProof.\nauto with set.\nQed.\n\nLemma filter_add_1 : forall s x, f x = true ->\n filter f (add x s) [=] add x (filter f s).\nProof.\nred; intros; set_iff; do 2 (rewrite filter_iff; auto); set_iff.\nintuition.\nrewrite <- H; apply Comp; auto with relations.\nQed.\n\nLemma filter_add_2 : forall s x, f x = false ->\n filter f (add x s) [=] filter f s.\nProof.\nred; intros; do 2 (rewrite filter_iff; auto); set_iff.\nintuition.\nassert (f x = f a) by (apply Comp; auto).\nrewrite H in H1; rewrite H2 in H1; discriminate.\nQed.\n\nLemma add_filter_1 : forall s s' x,\n f x=true -> (Add x s s') -> (Add x (filter f s) (filter f s')).\nProof.\nunfold Add, MP.Add; intros.\nrepeat rewrite filter_iff; auto.\nrewrite H0; clear H0.\nintuition.\nsetoid_replace y with x; auto with relations.\nQed.\n\nLemma add_filter_2 : forall s s' x,\n f x=false -> (Add x s s') -> filter f s [=] filter f s'.\nProof.\nunfold Add, MP.Add, Equal; intros.\nrepeat rewrite filter_iff; auto.\nrewrite H0; clear H0.\nintuition.\nsetoid_replace x with a in H; auto. congruence.\nQed.\n\nLemma union_filter: forall f g,\n  Proper (E.eq==>Logic.eq) f -> Proper (E.eq==>Logic.eq) g ->\n  forall s, union (filter f s) (filter g s) [=] filter (fun x=>orb (f x) (g x)) s.\nProof.\nclear Comp' Comp f.\nintros.\nassert (Proper (E.eq==>Logic.eq) (fun x => orb (f x) (g x))).\n  repeat red; intros.\n  rewrite (H x y H1);  rewrite (H0 x y H1); auto.\nunfold Equal; intros; set_iff; repeat rewrite filter_iff; auto.\nassert (f a || g a = true <-> f a = true \\/ g a = true).\n  split; auto with bool.\n  intro H3; destruct (orb_prop _ _ H3); auto.\ntauto.\nQed.\n\nLemma filter_union: forall s s', filter f (union s s') [=] union (filter f s) (filter f s').\nProof.\nunfold Equal; intros; set_iff; repeat rewrite filter_iff; auto; set_iff; tauto.\nQed.\n\n(** Properties of [for_all] *)\n\nLemma for_all_mem_1: forall s,\n (forall x, (mem x s)=true->(f x)=true) -> (for_all f s)=true.\nProof.\nintros.\nrewrite for_all_filter; auto.\nrewrite is_empty_equal_empty.\napply equal_mem_1;intros.\nrewrite filter_b; auto.\nrewrite empty_mem.\ngeneralize (H a); case (mem a s);intros;auto.\nrewrite H0;auto.\nQed.\n\nLemma for_all_mem_2: forall s,\n (for_all f s)=true -> forall x,(mem x s)=true -> (f x)=true.\nProof.\nintros.\nrewrite for_all_filter in H; auto.\nrewrite is_empty_equal_empty in H.\ngeneralize (equal_mem_2 _ _ H x).\nrewrite filter_b; auto.\nrewrite empty_mem.\nrewrite H0; simpl;intros.\nrewrite <- negb_false_iff; auto.\nQed.\n\nLemma for_all_mem_3:\n forall s x,(mem x s)=true -> (f x)=false -> (for_all f s)=false.\nProof.\nintros.\napply (bool_eq_ind (for_all f s));intros;auto.\nrewrite for_all_filter in H1; auto.\nrewrite is_empty_equal_empty in H1.\ngeneralize (equal_mem_2 _ _ H1 x).\nrewrite filter_b; auto.\nrewrite empty_mem.\nrewrite H.\nrewrite H0.\nsimpl;auto.\nQed.\n\nLemma for_all_mem_4:\n forall s, for_all f s=false -> {x:elt | mem x s=true /\\ f x=false}.\nProof.\nintros.\nrewrite for_all_filter in H; auto.\ndestruct (choose_mem_3 _ H) as (x,(H0,H1));intros.\nexists x.\nrewrite filter_b in H1; auto.\nelim (andb_prop _ _ H1).\nsplit;auto.\nrewrite <- negb_true_iff; auto.\nQed.\n\n(** Properties of [exists] *)\n\nLemma for_all_exists:\n forall s, exists_ f s = negb (for_all (fun x =>negb (f x)) s).\nProof.\nintros.\nrewrite for_all_b; auto.\nrewrite exists_b; auto.\ninduction (elements s); simpl; auto.\ndestruct (f a); simpl; auto.\nQed.\n\nEnd Bool.\nSection Bool'.\n\nVariable f:elt->bool.\nVariable Comp: Proper (E.eq==>Logic.eq) f.\n\nLet Comp' : Proper (E.eq==>Logic.eq) (fun x => negb (f x)).\nProof.\nrepeat red; intros; f_equal; auto.\nQed.\n\nLemma exists_mem_1:\n forall s, (forall x, mem x s=true->f x=false) -> exists_ f s=false.\nProof.\nintros.\nrewrite for_all_exists; auto.\nrewrite for_all_mem_1;auto with bool.\nintros;generalize (H x H0);intros.\nrewrite negb_true_iff; auto.\nQed.\n\nLemma exists_mem_2:\n forall s, exists_ f s=false -> forall x, mem x s=true -> f x=false.\nProof.\nintros.\nrewrite for_all_exists in H; auto.\nrewrite negb_false_iff in H.\nrewrite <- negb_true_iff.\napply for_all_mem_2 with (2:=H); auto.\nQed.\n\nLemma exists_mem_3:\n forall s x, mem x s=true -> f x=true -> exists_ f s=true.\nProof.\nintros.\nrewrite for_all_exists; auto.\nrewrite negb_true_iff.\napply for_all_mem_3 with x;auto.\nrewrite negb_false_iff; auto.\nQed.\n\nLemma exists_mem_4:\n forall s, exists_ f s=true -> {x:elt | (mem x s)=true /\\ (f x)=true}.\nProof.\nintros.\nrewrite for_all_exists in H; auto.\nrewrite negb_true_iff in H.\ndestruct (@for_all_mem_4 (fun x =>negb (f x)) Comp' s) as (x,[]); auto.\nexists x;split;auto.\nrewrite <-negb_false_iff; auto.\nQed.\n\nEnd Bool'.\n\nSection Sum.\n\n(** Adding a valuation function on all elements of a set. *)\n\nDefinition sum (f:elt -> nat)(s:t) := fold (fun x => plus (f x)) s 0.\nNotation compat_opL := (Proper (E.eq==>Logic.eq==>Logic.eq)).\nNotation transposeL := (transpose Logic.eq).\n\nLemma sum_plus :\n  forall f g,\n  Proper (E.eq==>Logic.eq) f -> Proper (E.eq==>Logic.eq) g ->\n    forall s, sum (fun x =>f x+g x) s = sum f s + sum g s.\nProof.\nunfold sum.\nintros f g Hf Hg.\nassert (fc : compat_opL (fun x:elt =>plus (f x))) by\n (repeat red; intros; rewrite Hf; auto).\nassert (ft : transposeL (fun x:elt =>plus (f x))) by (red; intros; omega).\nassert (gc : compat_opL (fun x:elt => plus (g x))) by\n (repeat red; intros; rewrite Hg; auto).\nassert (gt : transposeL (fun x:elt =>plus (g x))) by (red; intros; omega).\nassert (fgc : compat_opL (fun x:elt =>plus ((f x)+(g x)))) by\n  (repeat red; intros; rewrite Hf,Hg; auto).\nassert (fgt : transposeL (fun x:elt=>plus ((f x)+(g x)))) by (red; intros; omega).\nintros s;pattern s; apply set_rec.\nintros.\nrewrite <- (fold_equal _ _ _ _ fc ft 0 _ _ H).\nrewrite <- (fold_equal _ _ _ _ gc gt 0 _ _ H).\nrewrite <- (fold_equal _ _ _ _ fgc fgt 0 _ _ H); auto.\nintros. do 3 (rewrite fold_add; auto with *).\ndo 3 rewrite fold_empty;auto.\nQed.\n\nLemma sum_filter : forall f : elt -> bool, Proper (E.eq==>Logic.eq) f ->\n  forall s, (sum (fun x => if f x then 1 else 0) s) = (cardinal (filter f s)).\nProof.\nunfold sum; intros f Hf.\nassert (st : Equivalence (@Logic.eq nat)) by (split; congruence).\nassert (cc : compat_opL (fun x => plus (if f x then 1 else 0))) by\n (repeat red; intros; rewrite Hf; auto).\nassert (ct : transposeL (fun x => plus (if f x then 1 else 0))) by\n (red; intros; omega).\nintros s;pattern s; apply set_rec.\nintros.\nchange elt with E.t.\nrewrite <- (fold_equal _ _ st _ cc ct 0 _ _ H).\napply equal_2 in H; rewrite <- H, <-H0; auto.\nintros; rewrite (fold_add _ _ st _ cc ct); auto.\ngeneralize (@add_filter_1 f Hf s0 (add x s0) x) (@add_filter_2 f Hf s0 (add x s0) x) .\nassert (~ In x (filter f s0)).\n intro H1; rewrite (mem_1 (filter_1 Hf H1)) in H; discriminate H.\ncase (f x); simpl; intros.\nrewrite (MP.cardinal_2 H1 (H2 (eq_refl true) (MP.Add_add s0 x))); auto.\nrewrite <- (MP.Equal_cardinal (H3 (eq_refl false) (MP.Add_add s0 x))); auto.\nintros; rewrite fold_empty;auto.\nrewrite MP.cardinal_1; auto.\nunfold Empty; intros.\nrewrite filter_iff; auto; set_iff; tauto.\nQed.\n\nLemma fold_compat :\n  forall (A:Type)(eqA:A->A->Prop)(st:Equivalence eqA)\n  (f g:elt->A->A),\n  Proper (E.eq==>eqA==>eqA) f -> transpose eqA f ->\n  Proper (E.eq==>eqA==>eqA) g -> transpose eqA g ->\n  forall (i:A)(s:t),(forall x:elt, (In x s) -> forall y, (eqA (f x y) (g x y))) ->\n  (eqA (fold f s i) (fold g s i)).\nProof.\nintros A eqA st f g fc ft gc gt i.\nintro s; pattern s; apply set_rec; intros.\ntransitivity (fold f s0 i).\napply fold_equal with (eqA:=eqA); auto.\nrewrite equal_sym; auto.\ntransitivity (fold g s0 i).\napply H0; intros; apply H1; auto with set.\nelim  (equal_2 H x); auto with set; intros.\napply fold_equal with (eqA:=eqA); auto with set.\ntransitivity (f x (fold f s0 i)).\napply fold_add with (eqA:=eqA); auto with set.\ntransitivity (g x (fold f s0 i)); auto with set relations.\ntransitivity (g x (fold g s0 i)); auto with set relations.\napply gc; auto with set relations.\nsymmetry; apply fold_add with (eqA:=eqA); auto.\ndo 2 rewrite fold_empty; reflexivity.\nQed.\n\nLemma sum_compat :\n  forall f g, Proper (E.eq==>Logic.eq) f -> Proper (E.eq==>Logic.eq) g ->\n  forall s, (forall x, In x s -> f x=g x) -> sum f s=sum g s.\nintros.\nunfold sum; apply (@fold_compat _ (@Logic.eq nat));\n repeat red; auto with *.\nQed.\n\nEnd Sum.\n\nEnd WEqPropertiesOn.\n\n(** Now comes variants for self-contained weak sets and for full sets.\n    For these variants, only one argument is necessary. Thanks to\n    the subtyping [WS<=S], the [EqProperties] functor which is meant to be\n    used on modules [(M:S)] can simply be an alias of [WEqProperties]. *)\n\nModule WEqProperties (M:WSets) := WEqPropertiesOn M.E M.\nModule EqProperties := WEqProperties.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/MSets/MSetEqProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7041657797215225}}
{"text": "Require Import Unicode.Utf8. \n\nOpen Scope type_scope. \nDefinition relation (X : Type) (Y : Type) := X → Y → Type.\n\nDefinition transition (X : Type) := X → X → Type.\n\nDefinition strong_bisim (A B : Type) (fa : transition A) (fb : transition B) (R : relation A B) :\n  Type := ∀ a b, R a b → \n         (∀ a', fa a a' → {b' : B & fb b b' * R a' b'})\n       * (∀ b', fb b b' → {a' : A & fa a a' * R a' b'}). \n\nInductive refl_trans_clos {X} (f : transition X) : transition X := \n  | t_refl (x : X) : refl_trans_clos f x x\n  | t_step (x y z : X) : f x y → refl_trans_clos f y z → refl_trans_clos f x z.\n\nLemma t_step2 {X} : ∀ (f : transition X) (x y z : X), f y z → refl_trans_clos f x y →\n  refl_trans_clos f x z. \nintros f x y z H H0. induction H0. apply t_step with (y:=z). assumption. apply t_refl. apply\nIHrefl_trans_clos in H. apply (t_step f x y z); assumption. Qed. \n\nLemma refl_trans_clos_app {X} : ∀ (f : transition X) (x y z : X), \n  refl_trans_clos f x y → refl_trans_clos f y z → refl_trans_clos f x z. \nintros f x y z H H0. induction H. auto. apply IHrefl_trans_clos in H0. rename y into Y. apply\nt_step with (y:=Y); auto. Qed. \n\n(* p and q are bisimilar *)\n(*Notation \"p '~' q\" := (∃ fp fq R, strong_bisim p q fp fq R) (at level 30). *)\n\nDefinition partial_function {X Y: Type} (R: relation X Y) :=\n  ∀ (x : X) (y1 y2 : Y), R x y1 → R x y2 → y1 = y2. \n\nDefinition total_function {X Y: Type} (R: relation X Y) :=\n  (∀ x:X, {y:Y & R x y}) * partial_function R. \n\nDefinition surjective {X Y: Type} (f : X → Y) : Type :=\n  ∀ y:Y, ∃ x:X, f x = y.\n\nDefinition injective {X Y : Type} (f : X → Y) : Type :=\n  ∀ a b: X, f a = f b → a = b.\n\nDefinition bijective {X Y : Type} (f : X → Y) : Type :=\n  injective f * surjective f.\n\nDefinition reflexive {X : Type} (R: relation X X) :=\n  ∀ a : X, R a a.\n\nDefinition symmetric {X : Type} (R: relation X X) :=\n  ∀ a b : X, (R a b) → (R b a).\n\nDefinition antisymmetric {X: Type} (R: relation X X) :=\n  ∀ a b : X, (R a b) → (R b a) → a = b.\n\nDefinition transitive {X: Type} (R: relation X X) :=\n  ∀ a b c : X, (R a b) → (R b c) → (R a c).\n\nDefinition equivalence {X:Type} (R: relation X X) :=\n  reflexive R * symmetric R * transitive R.\n\nDefinition partial_order {X:Type} (R: relation X X) :=\n  reflexive R * antisymmetric R * transitive R.\n\n(* Examples *)\n\nInductive next_nat (n : nat) : nat → Prop := \n    | succ : next_nat n (S n).\n\n(*\nLemma next_nat_le : ∀ m n, refl_trans_clos next_nat m n ↔ le m n.\nintros. split. intros. induction H. auto. inversion H. subst. apply le_S in\nIHrefl_trans_clos. apply le_S_n. assumption. intros. induction H. apply t_refl.\napply t_step2 with (y:=m0). apply succ. auto. Qed. \n\n(* simple bisimulation *)\nTheorem bisim_next_nat_eq : strong_bisim nat nat next_nat next_nat eq. \nProof. unfold strong_bisim. intros. subst. split. intros. apply ex_intro with a'.\nsplit; auto. intros. apply ex_intro with b'. split; auto. Qed. \n\n*)\n", "meta": {"author": "stelleg", "repo": "cem_coq", "sha": "3487124d10e2bd4bb9328e4cb5e26d4e96f62387", "save_path": "github-repos/coq/stelleg-cem_coq", "path": "github-repos/coq/stelleg-cem_coq/cem_coq-3487124d10e2bd4bb9328e4cb5e26d4e96f62387/relations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7041657691707623}}
{"text": "Inductive na: Type :=\n  |O\n  |S (n:na).\n\nFixpoint plus (n m:na):na :=\n  match n with\n  |O => m\n  |S n' => S (plus n' m)\nend.\n\nFixpoint square (n:na):na :=\n  match n with\n  |O => O\n  |S n' => plus (square n') (plus n' n)\nend.\n\nCompute square(S(S(O))).", "meta": {"author": "pikapikapikaori", "repo": "Coq", "sha": "d2af0d21f12b45ee70c3298882b219a133ba9425", "save_path": "github-repos/coq/pikapikapikaori-Coq", "path": "github-repos/coq/pikapikapikaori-Coq/Coq-d2af0d21f12b45ee70c3298882b219a133ba9425/Quiz/quiz1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.7040980969452861}}
{"text": "(* ea *)\n\nInductive Boole : Set :=\n  | igaz : Boole\n  | hamis : Boole.\n\nPrint Boole_ind.\n\nDefinition Boole_Or (b1:Boole) (b2:Boole) : Boole :=\n  match b1 with \n    | igaz => match b2 with \n                | igaz => igaz\n                | hamis => igaz \n              end \n    | hamis => match b2 with \n                | igaz => igaz\n                | hamis => hamis\n              end\n  end.\n\nNotation \"x 'vagy' y\" := (Boole_Or x y) (at level 20) : type_scope.\n\nCheck igaz vagy hamis.\n\nEval compute in (igaz vagy hamis).\n\nDefinition Boole_And (b1 : Boole) (b2: Boole) : Boole := \n  match b1 with \n    | igaz => match b2 with | igaz => igaz | hamis => hamis end\n    | hamis => match b2 with | igaz => hamis | hamis => hamis end end.\n\nNotation \"x 'es' y\" := (Boole_And x y) (at level 20) : type_scope.\n\nDefinition Boole_Not (b : Boole) : Boole := \n  match b with \n    | igaz => hamis \n    | hamis => igaz\n  end.\n\nNotation \"'nem' x\" := (Boole_Not x) (at level 20) : type_scope.\n\nDefinition Boole_Imp (x : Boole) (y: Boole) : Boole := \n  match x with \n    | igaz => match y with\n                | igaz => igaz\n                | hamis => hamis\n              end\n    | hamis => match y with\n                | igaz => igaz\n                | hamis => igaz\n              end\n  end.\n\nNotation \"x 'imp' y\" := (Boole_Imp x y) (at level 20) : type_scope.\n\nDefinition Boole_Iff (x : Boole) (y: Boole) : Boole := \n  match x with \n    | igaz => match y with\n                | igaz => igaz\n                | hamis => hamis\n              end\n    | hamis => match y with\n                | igaz => hamis\n                | hamis => igaz\n              end\n  end.\n\nNotation \"x 'acsa' y\" := (Boole_Iff x y) (at level 20) : type_scope.\n\n\n(* hf 1 *)\n\nTheorem hf_1a : (forall x y : Boole, (x imp y) = ((nem x) vagy y)).\nProof. \n  intros.\n  apply Boole_ind with (P:=fun x => (x imp y) = ((nem x) vagy y)).\n  unfold Boole_Imp.\n  unfold Boole_Not.\n  unfold Boole_Or.\n  reflexivity.\n  unfold Boole_Imp.\n  unfold Boole_Not.\n  unfold Boole_Or.\n  reflexivity.\n  Show Proof.\nQed.\n\nTheorem hf_1b : (forall x y : Boole, (x imp y) acsa ((nem x) vagy y) = igaz).\nProof. \n  intros.\n  apply Boole_ind with (P:=fun x => (x imp y) acsa ((nem x) vagy y) = igaz).\n  apply Boole_ind with (P:=fun y => (igaz imp y) acsa ((nem igaz) vagy y) = igaz).\n  unfold Boole_Iff.\n  unfold Boole_Not.\n  unfold Boole_Imp.\n  unfold Boole_Or.\n  reflexivity.\n  unfold Boole_Iff.\n  unfold Boole_Not.\n  unfold Boole_Imp.\n  unfold Boole_Or.\n  reflexivity.\n  apply Boole_ind with (P:=fun y => (hamis imp y) acsa ((nem hamis) vagy y) = igaz).\n  unfold Boole_Iff.\n  unfold Boole_Not.\n  unfold Boole_Imp.\n  unfold Boole_Or.\n  reflexivity.\n  unfold Boole_Iff.\n  unfold Boole_Not.\n  unfold Boole_Imp.\n  unfold Boole_Or.\n  reflexivity.\n  Show Proof.\nQed.\n\n\n(* hf 2 *)\n\nTheorem hf_2 : (forall x y : Boole, ((nem x) es (nem y)) = nem (x vagy y)).\nProof. \n  intros.\n  apply Boole_ind with (P:=fun x => ((nem x) es (nem y)) = nem (x vagy y)).\n  apply Boole_ind with (P:=fun y => (nem igaz) es (nem y) = nem (igaz vagy y)).\n  unfold Boole_Not.\n  unfold Boole_And.\n  unfold Boole_Or.\n  reflexivity.\n  unfold Boole_Not.\n  unfold Boole_And.\n  unfold Boole_Or.\n  reflexivity.\n  apply Boole_ind with (P:=fun y => (nem hamis) es (nem y) = nem (hamis vagy y)).\n  unfold Boole_Not.\n  unfold Boole_And.\n  unfold Boole_Or.\n  reflexivity.\n  unfold Boole_Not.\n  unfold Boole_And.\n  unfold Boole_Or.\n  reflexivity.\n  Show Proof.\nQed. \n", "meta": {"author": "mozow01", "repo": "bizcoq2021", "sha": "f98f22ba3ce80899bc88605ce3193d8972102c92", "save_path": "github-repos/coq/mozow01-bizcoq2021", "path": "github-repos/coq/mozow01-bizcoq2021/bizcoq2021-f98f22ba3ce80899bc88605ce3193d8972102c92/hallgatoi/gabormarton/bizcoq_1_hf_1-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7040185557155181}}
{"text": "Set Implicit Arguments.\n\n\nCoInductive LList (A:Type) : Type :=\n  | LNil : LList A\n  | LCons : A -> LList A -> LList A.\n\nArguments LNil {A}.\n\nCoInductive Infinite {A:Type} : LList A -> Prop :=\n    Infinite_LCons :\n      forall (a:A) (l:LList A), Infinite l -> Infinite (LCons a l).\n\n#[export] Hint Constructors Infinite: llists.\n\n  \n\nDefinition Infinite_ok {A: Type} (X:LList A -> Prop) : Prop :=\n  forall l:LList A,\n    X l ->  exists a : A, exists l' : LList A, l = LCons a l' /\\ X l'.\n \nDefinition Infinite1 {A: Type} (l:LList A) :=\n   exists X : LList A -> Prop, Infinite_ok X /\\ X l.\n\n\nLemma ok_LNil {A: Type}:\n forall X:LList A -> Prop, Infinite_ok X -> ~ X LNil.\nProof.\n unfold Infinite_ok.\n intros X H H0;  case (H LNil).  \n - assumption. \n - intros x H1; case H1; intros x0 H2; case H2; discriminate 1.\nQed.\n\nLemma ok_LCons {A: Type} :\n  forall  (X:LList A -> Prop) (a:A) (l:LList A),\n   Infinite_ok X -> X (LCons a l) -> X l.\nProof.\n intros  X a l H H0; case (H (LCons a l)).\n -  assumption.\n -  simple destruct 1; intros x0 H2; case H2; injection 1.\n    simple destruct 1; auto.\nQed.\n\n\n\nLemma Infinite1_LNil {A: Type} :  ~ Infinite1 (LNil (A:=A)).\nProof.\n intros  H; destruct H as [X [H1 H2]].\n now apply (ok_LNil H1).\nQed.\n\n\nLemma Infinite1_LCons  {A: Type} :\n forall  (a:A) (l:LList A), Infinite1 (LCons a l) -> Infinite1 l.\nProof.\n intros  a l H.\n case H; intros X HX; case HX; intros H1 H2; clear HX.\n  exists (fun u:LList A =>  exists b : A, X (LCons b u)); split.\n -  unfold Infinite_ok in |- *.\n    intros l0 [b Hb]. \n    assert (H4 : X l0) by apply (ok_LCons _ _  H1 Hb);eauto.  \n    case (H1 l0 H4);  intros x [l' [el' Hl']].\n    exists x, l'; split; try assumption.\n    exists x; rewrite <- el'; auto.\n-  exists a; auto.\nQed.\n\n\n(* equivalence between both definitions of infinity *)\n\n\nLemma Inf_Inf1 {A : Type} : forall l:LList A, Infinite l -> Infinite1 l.\nProof.\n intros l ;  exists (Infinite (A:=A)).\n split; try assumption.\n unfold Infinite_ok in |- *.\n simple destruct l0.\n -  inversion 1.\n - inversion_clear 1.\n   exists a; exists l1; auto.\nQed.\n\nLemma Inf1_Inf {A : Type}: forall l:LList A, Infinite1 l -> Infinite l.\nProof.\n cofix Inf1_Inf.\n simple destruct l.\n - intro H;  case (Infinite1_LNil H).\n -  intros a l0 H0;  generalize (Infinite1_LCons H0); constructor.\n    now apply Inf1_Inf. \nQed.\n\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch13_co_inductive_types/SRC/infinite_impred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7040185538617603}}
{"text": "Require Import ZArith Znumtheory.\nOpen Scope Z.\n\nDefinition Square (n : Z) := Z.sqrt n * Z.sqrt n = n.\n\nDefinition task := forall n m, 1 <= n -> 1 <= m -> rel_prime n m -> Square (n * m) -> Square n.", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/036/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9511422199928904, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.7040110749887218}}
{"text": "(** Calculation of the simple arithmetic language. *)\n\nRequire Import Tactics.\nRequire Export Memory.\nModule Arith (mem : Memory).\nImport mem.\n\n(** * Syntax *)\n\nInductive Expr : Set := \n| Val : nat -> Expr \n| Add : Expr -> Expr -> Expr.\n\n(** * Semantics *)\n\nFixpoint eval (x: Expr) : nat :=\n  match x with\n    | Val n => n\n    | Add x1 x2 => eval x1 + eval x2\n  end.\n\n(** * Compiler *)\n\nInductive Code : Set :=\n| LOAD : nat -> Code -> Code\n| ADD : adr -> Code -> Code\n| STORE : adr -> Code -> Code\n| HALT : Code.\n\nFixpoint comp' (x : Expr) (r : adr) (c : Code) : Code :=\n  match x with\n  | Val n => LOAD n c\n  | Add x1 x2 => comp' x1 r (STORE r (comp' x2 (next r) (ADD r c)))\n  end.\n\nDefinition comp (x : Expr) : Code := comp' x first HALT.\n\n(** * Virtual Machine *)\n\nDefinition Memory : Type := Mem.\nDefinition Acc : Type := nat.\n\nDefinition State : Type := (Code * Memory * Acc)%type.\n\nReserved Notation \"x ==> y\" (at level 80, no associativity).\nInductive VM : State -> State -> Prop :=\n| vm_load n c m a : (LOAD n c , m, a) ==> (c , m, n)\n| vm_add c r m a : (ADD r c, m, a) ==> (c, free r m, get r m + a)\n| vm_store c r m a : (STORE r c, m, a) ==> (c, set r a m, a)\nwhere \"x ==> y\" := (VM x y).\n\n(** * Calculation *)\n\n(** Boilerplate to import calculation tactics *)\n\nModule VM <: Preorder.\nDefinition State := State.\nDefinition VM := VM.\nEnd VM.\nModule VMCalc := Calculation VM.\nImport VMCalc.\n\n(** Specification of the compiler *)\n\nTheorem spec x r c a m :\n  isFreeFrom r m ->\n  (comp' x r c, m, a) =>> (c , m, eval x).\n\n(** Setup the induction proof *)\n\nProof.\n  intros.\n  generalize dependent c.\n  generalize dependent m.\n  generalize dependent r.\n  generalize dependent a.\n  induction x;intros.\n\n(** Calculation of the compiler *)\n\n(** - [x = Val n]: *)\n\n  begin\n  (c, m, n).\n  <== { apply vm_load }\n  (LOAD n c, m, a).\n  [].\n\n(** - [x = Add x1 x2]: *)\n\n  begin\n    (c, m, eval x1 + eval x2).\n  = {rewrite isFreeFrom_free, get_set}\n    (c, free r (set r (eval x1) m), get r (set r (eval x1) m)  + eval x2).\n  <== {apply vm_add}\n    (ADD r c, set r (eval x1) m, eval x2).\n  <<= {apply IHx2; auto using isFreeFrom_set}\n    (comp' x2 (next r) (ADD r c), set r (eval x1) m, eval x1).\n  <== {apply vm_store}\n    (STORE r (comp' x2 (next r) (ADD r c)), m, eval x1).\n  <<= { apply IHx1}\n    (comp' x1 r (STORE r (comp' x2 (next r) (ADD r c))), m, a).\n  [].\nQed.\n\n\n(** * Soundness *)\n  \n(** Since the VM is defined as a small step operational semantics, we\nhave to prove that the VM is deterministic and does not get stuck in\norder to derive soundness from the above theorem. *)\n\n\nLemma determ_vm : determ VM.\n  intros C C1 C2 V. induction V; intro V'; inversion V'; subst; reflexivity.\nQed.\n\n\nTheorem sound x a C : (comp x, empty, a) =>>! C -> C = (HALT , empty, eval x).\nProof.\n  intros.\n  pose (spec x first HALT) as H'. unfold comp in *. pose (determ_trc determ_vm) as D.\n  unfold determ in D. eapply D. apply H. split. apply H'. apply isFreeFrom_first. intro Contra. destruct Contra.\n  inversion H0.\nQed.\n\nEnd Arith.", "meta": {"author": "pa-ba", "repo": "McCarthy-Painter", "sha": "0ec03dd95afe5c50657a0107ed247ea2374d182c", "save_path": "github-repos/coq/pa-ba-McCarthy-Painter", "path": "github-repos/coq/pa-ba-McCarthy-Painter/McCarthy-Painter-0ec03dd95afe5c50657a0107ed247ea2374d182c/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7039257967558714}}
{"text": "Require Export D.\n\n\n(** **** Problem #3 : 2 stars (boolean functions) *)\n(** Use the tactics you have learned so far to prove the following \n    theorem about boolean functions. *)\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\tintros. rewrite -> H. rewrite -> H. destruct b. reflexivity. reflexivity.\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/01/P06.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7039257740709114}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) (lf2 : natural)\n  : natural := plus (Succ Zero) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj187_coqofml_7rysDD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7038723554537079}}
{"text": "(* Exercise 49 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_049 : (A -> (B -> ~A)) -> ~A \\/ ~B.\nProof.\nimp_i a1.\ndis_e (A \\/ ~A) a2 a2.\nLEM.\ndis_e (B \\/ ~B) a3 a3.\nLEM.\ndis_i1.\nimp_e B.\nimp_e A.\nhyp a1.\nhyp a2.\nhyp a3.\ndis_i2.\nhyp a3.\ndis_i1.\nhyp a2.\nQed.\n", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop049.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7038723538637238}}
{"text": "(* ArithCompl.v *)\n\n(**********************************)\n(* Some complements of arithmetic *)\n(**********************************)\n\nRequire Export Wf_nat.\nRequire Export ZArith.\nRequire Export Znumtheory.\nRequire Export Reals.\nOpen Scope Z_scope.\n\nUnset Standard Proposition Elimination Names.\n\n(***************)\n(* Regarding Z *)\n(***************)\n\nDefinition is_sqr (n : Z) : Prop :=\n  0 <= n /\\ exists i : Z, i * i = n /\\ 0 <= i.\n\nLemma is_sqr_sqr : forall n: Z, is_sqr (n * n).\nProof.\n  intro; unfold is_sqr; split; try (apply Zge_le; apply sqr_pos);\n    elim (Z_le_dec 0 n); intro;\n      [ exists n; auto | exists (- n); intuition; ring ].\nQed.\n\nLemma is_sqr_mult : forall p q : Z, is_sqr p -> is_sqr q -> is_sqr (p * q).\nProof.\n  unfold is_sqr; intros; elim H; clear H; intros; elim H0; clear H0; intros;\n    elim H1; clear H1; intros; elim H1; clear H1; intros; elim H2; clear H2;\n    intros; elim H2; clear H2; intros.\n  split;\n    [ auto with zarith\n    | exists (x * x0); rewrite <- H1; rewrite <- H2; intuition; ring ].\nQed.\n\nLemma sqr_0 : forall z : Z, z * z = 0 -> z = 0.\nProof.\n  intros; elim (Zmult_integral _ _ H); auto.\nQed.\n\nLemma sqr_compat : forall a b : Z, a * a = b * b -> a = b \\/ a = -b.\nProof.\n  intros; cut (a * a - b * b = 0); auto with zarith; clear H; intro;\n    replace (a * a - b * b) with ((a + b) * (a - b)) in H; try ring;\n    elim (Zmult_integral _ _ H); auto with zarith.\nQed.\n\nLemma sqr_le : forall a : Z, a <= a * a.\nProof.\n  intro; elim (Z_le_dec 0 a); intro;\n    [ elim (Z_eq_dec a 0); intro; try (rewrite a1; auto with zarith);\n      pattern a at 1; replace a with (a * 1); try ring;\n      apply (Zmult_le_compat a 1 a a)\n    | generalize (sqr_pos a) ]; auto with zarith.\nQed.\n\nLemma sqr_spos : forall z : Z, z <> 0 -> z * z > 0.\nProof.\n  intros; elim (not_Zeq _ _ H); clear H; intro.\n  unfold Zlt in H; rewrite Zcompare_opp in H; fold (- (0) < - z) in H;\n    simpl in H; cut (z * z = - z * - z);\n      [ intro; rewrite H0; apply Zmult_gt_0_compat; auto with zarith\n      | ring ].\n  apply Zmult_gt_0_compat; auto with zarith.\nQed.\n\nLemma sqr_poss : forall z : Z, 0 < z * z -> z <> 0.\nProof.\nintros;intro;rewrite H0 in H;auto with zarith.\nQed.\n\nLemma sqr_lt : forall a : Z, a <> 0 -> a <> 1 -> a < a * a.\nProof.\n  intros; case (Z_le_dec 0 a); intro;\n    [ pattern a at 1; rewrite <- Zmult_1_r; apply Zmult_lt_compat_l;\n      auto with zarith\n    | generalize (sqr_spos _ H); intro; auto with zarith ].\nQed.\n\nLemma sqr_sum : forall a b : Z, b <> 0 -> a * a + b * b <> 0.\nProof.\n  intros; elim (Z_eq_dec a 0).\n  intro; rewrite a0; simpl; generalize (sqr_spos b H); intro; auto with zarith.\n  intro; generalize (sqr_spos a b0); intro; generalize (sqr_spos b H); intro;\n    auto with zarith.\nQed.\n\nLemma sqr_sum2 : forall a b : Z, 0 <= a * a + b * b.\nProof.\n  intros; generalize (Zplus_le_compat 0 (a * a) 0 (b * b)); simpl; intro;\n    apply H; apply Zge_le; apply sqr_pos.\nQed.\n\nLemma sqr_sum3 : forall a b : Z, b > 0 -> a * a + b * b > 0.\nProof.\n  intros; apply Zlt_gt; fold (0 + 0); apply Zplus_le_lt_compat;\n    [ apply Zge_le; apply sqr_pos | apply Zgt_lt; auto with zarith ].\nQed.\n\nLemma sqr_sum4: forall a b : Z, a * a + b * b = 0 -> a = 0 /\\ b = 0.\nProof.\n  intros; elim (Z_eq_dec a 0); intro;\n    [ elim (Z_eq_dec b 0); intro;\n      [ auto | generalize (sqr_sum a _ b0); tauto ]\n    | generalize (sqr_sum b _ b0); rewrite Zplus_comm in H; tauto].\nQed.\n\nLemma sqr_sub1 : forall a b : Z, 0 <= b -> b <= a -> 0 <= a * a - b * b.\nProof.\n  intros; replace (a * a - b * b) with ((a + b) * (a - b)); try ring;\n    apply Zmult_le_0_compat; auto with zarith.\nQed.\n\nLemma sqr_sub2 : forall a b : Z, 0 <= b -> b < a -> 0 < a * a - b * b.\nProof.\n  intros; replace (a * a - b * b) with ((a + b) * (a - b)); try ring;\n    apply Zmult_lt_0_compat; auto with zarith.\nQed.\n\nLemma sqr_sub3 : forall a b : Z, 0 < a -> 0 < b -> 0 < a * a - b * b -> b < a.\nProof.\n  intros; replace (a * a - b * b) with ((a + b) * (a - b)) in H1; try ring;\n    cut (0 < a + b); auto with zarith; intro; rewrite Zmult_comm in H1;\n    generalize (Zmult_lt_0_reg_r _ _ H2 H1); clear H1 H2; intro;\n    auto with zarith.\nQed.\n\nLemma sqr_2 : forall a : Z, 0 <= 2 * (a * a).\nProof.\n  intro; generalize (sqr_pos a); auto with zarith.\nQed.\n\nLemma sqr_gt : forall a b : Z, a >= 0 -> a < b -> a * a < b * b.\nProof.\n  intros; generalize (Zge_le _ _ H); clear H; intro;\n    elim (Zle_lt_or_eq _ _ H); clear H; intro.\n  generalize (Zmult_lt_compat_l _ _ _ H H0); intro; assert (0 < b);\n    auto with zarith; generalize (Zmult_lt_compat_r _ _ _ H2 H0);\n    auto with zarith.\n  rewrite <- H; rewrite <- H in H0; apply Zgt_lt; auto with zarith.\nQed.\n\nLemma sqr_ge : forall a b : Z, a >= 0 -> a <= b -> a * a <= b * b.\nProof.\n  intros; apply Zmult_le_compat; auto with zarith.\nQed.\n\nLemma Zle_square_simpl : forall n m:Z,\n  0 <= n -> 0 <= m -> m * m <= n * n -> m <= n.\nProof.\n  intros; elim (Zle_lt_or_eq _ _ H1); intro;\n    [ generalize (Zlt_square_simpl _ m H H2)\n    | generalize (Zeq_minus _ _ H2); clear H2; intro;\n      replace (m * m - n * n) with ((m + n) * (m - n)) in H2; try ring;\n      elim (Zmult_integral _ _ H2); clear H2; intro ]; auto with zarith.\nQed.\n\nLemma neq_1 : forall u v m n : Z,\n  m <> 0 -> n <> 0 -> u * u = m * m + n * n -> v * v = n * n - m * m ->\n  u <> 1 /\\ v <> 1.\nProof.\n  intros; case (Z_eq_dec u 1); intro; case (Z_eq_dec v 1); intro; try tauto;\n    elimtype False;\n      [ rewrite e in H1; simpl in H1; rewrite e0 in H2; simpl in H2;\n        rewrite H2 in H1; cut (2 * (m * m) = 0); auto with zarith; intro;\n        elim (Zmult_integral _ _ H3); auto with zarith; intro;\n        generalize (sqr_0 _ H4); auto\n      | rewrite e in H1; simpl in H1; generalize (sqr_pos m); intro;\n        generalize (sqr_pos n); intro; cut (m * m = 0 \\/ n * n = 0);\n        try omega; intro; elim H5; clear H5; intros; generalize (sqr_0 _ H5);\n        auto\n      | rewrite e in H2; simpl in H2; replace (n * n - m * m) with\n        ((n + m) * (n - m)) in H2; try ring; symmetry in H2;\n        elim (Zmult_1_inversion_l _ _ H2); intro;\n        rewrite Zmult_comm in H2; elim (Zmult_1_inversion_l _ _ H2);\n        auto with zarith ].\nQed.\n\nLemma Zmult_eq_reg_l : forall z z1 z2, z * z1 = z * z2 -> z <> 0 -> z1 = z2.\nProof.\n  intros; apply eq_IZR; generalize (IZR_eq _ _ H); intro;\n    repeat rewrite mult_IZR in H1; generalize (not_O_IZR _ H0); intro;\n    apply (Rmult_eq_reg_l (IZR z)); assumption.\nQed.\n\nLemma Zmult_neq_0 : forall a b : Z, a * b <> 0 -> a <> 0 /\\ b <> 0.\nProof.\n  intros; elim (Z_eq_dec a 0); intro;\n    [ rewrite a0 in H; simpl in H; auto\n    | elim (Z_eq_dec b 0); intro; try (rewrite a0 in H;\n      rewrite Zmult_comm in H; simpl in H); auto ].\nQed.\n\nDefinition both_odd (x y : Z) := Zodd x /\\ Zodd y.\n\nDefinition distinct_parity (a b : Z) :=\n   (Zeven a) /\\ (Zodd b) \\/ (Zodd a) /\\ (Zeven b).\n\nLemma ndistp_eq : forall a : Z, ~ distinct_parity a a.\nProof.\n  red; intros; do 2 (elim H; clear H; intros);\n    match goal with\n    | id : Zeven _ |- _ => generalize (Zeven_not_Zodd _ id)\n    end; auto.\nQed.\n\nLemma sqr_sum5 : forall a b: Z,\n  a <> 0 -> b <> 0 -> distinct_parity a b -> a + b < a * a + b * b.\nProof.\n  intros; case (Z_eq_dec a 1); intro;\n    [ rewrite e; replace (1 * 1 + b * b) with (1+b*b);[idtac|ring];\n      apply Zplus_lt_compat_l;\n      case (Z_eq_dec b 1); intro;\n      [ elimtype False; rewrite e in H1; rewrite e0 in H1;\n        generalize (ndistp_eq 1); auto\n      | apply sqr_lt; assumption ]\n    | case (Z_eq_dec b 1); intro;\n      [ rewrite e; replace (a * a + 1 * 1) with (a * a + 1); try ring;\n        apply Zplus_lt_compat_r; apply sqr_lt; assumption\n      | apply Zplus_lt_compat; apply sqr_lt; assumption ] ].\nQed.\n\nLemma Zeven_def1 : forall z : Z, (Zeven z) -> exists k : Z, z = 2 * k.\nProof.\n  intros; generalize (Zeven_div2 _ H); intro; exists (Zdiv2 z); assumption.\nQed.\n\nLemma Zeven_def2 : forall z : Z, (exists k : Z, z = 2 * k) -> (Zeven z).\nProof.\n  intros; elim H; intros; rewrite H0; elim x; intros; simpl; auto.\nQed.\n\nLemma Zodd_def1 : forall z : Z, (Zodd z) -> exists k : Z, z = 2 * k + 1.\nProof.\n apply Zodd_ex.\nQed.\n\nLemma Zodd_def2 : forall z : Z, (exists k : Z, z = 2 * k + 1) -> (Zodd z).\nProof.\n  intros; elim H; intros; rewrite H0; elim x; intros; simpl; auto.\n  elim p; simpl; auto.\nQed.\n\nLemma Zodd_0: forall n : Z, Zodd n -> n <> 0.\nProof.\n  intros; intro; rewrite H0 in H; auto.\nQed.\n\nLemma Zodd_opp1 : forall a : Z, Zodd (-a) -> Zodd a.\nProof.\n  intros; elim (Zodd_def1 _ H); clear H; intros; apply Zodd_def2;\n    exists (-x - 1); rewrite <- (Zopp_involutive a); rewrite H; ring.\nQed.\n\nLemma Zodd_opp2 : forall a : Z, Zodd a -> Zodd (-a).\nProof.\n  intros; elim (Zodd_def1 _ H); clear H; intros; apply Zodd_def2; rewrite H;\n    exists (-x - 1); ring.\nQed.\n\nLemma Zodd_sum1 : forall a b : Z, Zodd a -> Zodd b -> Zeven (a + b).\nProof.\n  intros; elim (Zodd_def1 _ H); clear H; intros; elim (Zodd_def1 _ H0);\n    clear H0; intros; apply Zeven_def2; rewrite H; rewrite H0;\n    exists (x + x0 + 1); ring.\nQed.\n\nLemma Zodd_sum2 : forall a b : Z, Zodd a -> Zodd b -> Zeven (a - b).\nProof.\n  intros; generalize (Zodd_opp2 _ H0); clear H0; intro; unfold Zminus;\n    apply Zodd_sum1; assumption.\nQed.\n\nLemma Zodd_sum3 : forall a b : Z, Zodd (a + 2 * b) -> Zodd a.\nProof.\n  intros; elim (Zodd_def1 _ H); clear H; intros; cut (a = 2 * x + 1 - 2 * b);\n    auto with zarith; clear H; intro; rewrite H; apply Zodd_def2;\n    exists (x - b); ring.\nQed.\n\nLemma Zodd_mult : forall u v : Z,\n  Zodd u -> Zodd v -> \n  (exists s : Z, \n    (exists w : Z, (u - v = 4 * s /\\ u + v = 2 * w) \\/\n                   (u - v = 2 * w /\\ u + v = 4 * s))).\nProof.\n  intros; elim (Zodd_def1 u H); elim (Zodd_def1 v H0); intros k Hk k' Hk';\n    elim (Zeven_odd_dec k); elim (Zeven_odd_dec k'); intros.\n  elim (Zeven_def1 k a0); elim (Zeven_def1 k' a); intros t Ht t' Ht';\n    split with (t - t'); split with (2 * t + 2 * t' + 1); left;\n    auto with zarith.\n  elim (Zeven_def1 k a); elim (Zodd_def1 k' b); intros t Ht t' Ht';\n    split with (t + t' + 1); split with (2 * t - 2 * t' + 1); right;\n    auto with zarith.\n  elim (Zeven_def1 k' a); elim (Zodd_def1 k b); intros t Ht t' Ht';\n    split with (t + t' +1); split with (2 * t' - 2 * t - 1); right;\n    auto with zarith.\n  elim (Zodd_def1 k b0); elim (Zodd_def1 k' b); intros t Ht t' Ht';\n    split with (t - t'); split with (k' + k + 1); left; auto with zarith.\nQed.\n\nLemma Zeven_sqr1 : forall z : Z, Zeven z -> Zeven (z * z).\nProof.\n  intros; generalize (Zeven_def1 _ H); clear H; intro; elim H; clear H; intros;\n    rewrite H; apply Zeven_def2; exists (2 * x * x); ring.\nQed.\n\nLemma Zeven_sqr2 : forall n, Zeven (n * n) -> Zeven n.\nProof.\n  induction n; auto; induction p; auto.\nQed.\n\nLemma Zodd_sqr1 : forall z : Z, Zodd z -> Zodd (z * z).\nProof.\n  intros; generalize (Zodd_def1 _ H); clear H; intro; elim H; clear H; intros;\n    rewrite H; apply Zodd_def2; exists (2 * x * x + 2 * x); ring.\nQed.\n\nLemma Zodd_sqr2 : forall n, Zodd (n * n) -> Zodd n.\nProof.\n  induction n; auto; induction p; auto.\nQed.\n\nLemma distp_neq : forall p q : Z, distinct_parity p q -> p <> q.\nProof.\n  intros; elim H; clear H; intro; elim H; clear H; intros;\n    [ elim (Zeven_def1 _ H); clear H; intros; elim (Zodd_def1 _ H0); clear H0;\n      intros; rewrite H; rewrite H0\n    | elim (Zodd_def1 _ H); clear H; intros; elim (Zeven_def1 _ H0); clear H0;\n      intros; rewrite H; rewrite H0 ]; auto with zarith.\nQed.\n\nLemma distp_sqr1 : forall p q : Z,\n  (distinct_parity p q) -> (distinct_parity (p * p) (q * q)).\nProof.\n  intros; unfold distinct_parity; do 2 (elim H; clear H; intros);\n    [ generalize (Zeven_sqr1 _ H); clear H; intro; generalize (Zodd_sqr1 _ H0)\n    | generalize (Zodd_sqr1 _ H); clear H; intro;\n      generalize (Zeven_sqr1 _ H0) ]; tauto.\nQed.\n\nLemma distp_sqr2 : forall p q : Z,\n  (distinct_parity (p * p) (q * q)) -> (distinct_parity p q).\nProof.\n  intros; unfold distinct_parity; elim H; clear H; intros; elim H; clear H;\n    intros; [ left | right ];\n    repeat (match goal with\n            | id : Zeven _ |- _ => generalize (Zeven_sqr2 _ id); clear id\n            | id : Zodd _ |- _ => generalize (Zodd_sqr2 _ id); clear id\n            end); tauto.\nQed.\n\nLemma distp_odd : forall p q : Z,\n  (distinct_parity p q) -> both_odd (p + q) (q - p).\nProof.\n  unfold distinct_parity, both_odd; intros; elim H; clear H; intro; elim H;\n    clear H; intros;\n      [ elim (Zeven_def1 _ H); clear H; intros; elim (Zodd_def1 _ H0);\n        clear H0; intros\n      | elim (Zodd_def1 _ H); clear H; intros; elim (Zeven_def1 _ H0);\n        clear H0; intros ]; split; apply Zodd_def2; (exists (x + x0);\n        rewrite H; rewrite H0; solve [ ring ]) || (exists (x0 - x); rewrite H;\n        rewrite H0; solve [ ring ] ) || (exists (x0 - x - 1); rewrite H;\n        rewrite H0; ring).\nQed.\n\nLemma not_divide1 : forall a b : Z,\n  a <> 1 -> a <> -1 -> b <> 0 -> ~(a * b | b).\nProof.\n  intros; red; intro; elim H2; clear H2; intros; rewrite Zmult_assoc in H2;\n    pattern b at 1 in H2; rewrite -> (Zred_factor0 b) in H2;\n    rewrite (Zmult_comm b 1) in H2; generalize (Zmult_reg_r _ _ _ H1 H2);\n    clear H2; intro; generalize (sym_eq H2); clear H2; intro;\n    rewrite Zmult_comm in H2; generalize (Zmult_1_inversion_l _ _ H2); tauto.\nQed.\n\nLemma not_divide2 : forall a b : Z, 0 < a -> 0 < b -> b < a -> ~(a | b).\nProof.\n  intros; red; intro; elim H2; clear H2; intros; replace a with (1 * a) in H1;\n    try ring; replace 0 with (0 * a) in H0; try ring; rewrite H2 in H1;\n    rewrite H2 in H0; generalize (Zmult_lt_reg_r _ _ _ H H1); clear H1; intro;\n    generalize (Zmult_lt_reg_r _ _ _ H H0); auto with zarith.\nQed.\n\nLemma rel_prime_1: forall a : Z, rel_prime 1 a.\nProof.\n  intro; unfold rel_prime; apply Zis_gcd_intro; auto with zarith.\nQed.\n\nLemma prime_2 : prime 2.\nProof.\n  apply prime_intro; auto with zarith; intros; case (Z_eq_dec n 1); intro;\n    try (elimtype False; progress auto with zarith); rewrite e;\n    apply rel_prime_1.\nQed.\n\nLemma rel_prime_sym : forall x y : Z, rel_prime x y -> rel_prime y x.\nProof.\n  unfold rel_prime; intros; apply Zis_gcd_sym; assumption.\nQed.\n\nLemma rel_prime_dec : forall x y : Z, {rel_prime x y} + {~ rel_prime x y}.\nProof.\n  intros; unfold rel_prime; elim (Zgcd_spec x y); intros; elim p; clear p;\n    intros; elim (Z_eq_dec x0 1); intro;\n      [ rewrite a in H; left; assumption\n      | right; red; intro; elim H; clear H; intros; elim H1; clear H1; intros;\n        generalize (H5 _ H H2); clear H H2 H3 H1 H4 H5; intro;\n        elim (Zdivide_1  _ H); clear H; intro; auto with zarith ].\nQed.\n\nLemma not_rel_prime1 : forall x y : Z,\n  ~ rel_prime x y -> exists d : Z, Zis_gcd x y d /\\ d <> 1 /\\ d <> -1.\nProof.\n  unfold rel_prime; intros; elim (Zgcd_spec x y); intros; elim p; clear p;\n    intros; exists x0; split;\n      [ assumption\n      | split;\n        [ elim (Z_eq_dec x0 1); intro; [ rewrite a in H0; auto | assumption ]\n        | elim (Z_eq_dec x0 (-1)); intro;\n          [ rewrite a in H0; generalize (Zis_gcd_opp _ _ _ H0); simpl;\n            clear H0; intro; generalize (Zis_gcd_sym _ _ _ H0); auto\n          | assumption ] ] ].\nQed.\n\nLemma not_rel_prime2 : forall x y d : Z,\n  (d | x) -> (d | y) -> d <> 1 -> d <> -1 -> ~ rel_prime x y.\nProof.\n  intros; elim (rel_prime_dec x y); auto; unfold rel_prime; intro;\n    elimtype False; elim a; clear a; intros; generalize (H5 _ H H0);\n    clear H H0 H3 H4 H5; intro; elim (Zdivide_1 _ H); auto.\nQed.\n\nLemma gcd_rel_prime : forall x y d : Z,\n  Zis_gcd x y d -> exists a : Z, exists b : Z,\n    x = d * a /\\ y = d * b /\\ rel_prime a b.\nProof.\n  intros; elim (Z_eq_dec d 0); intro;\n    [ rewrite a in H; elim H; clear H; intros;\n      destruct H as (q,H), H0 as (q0,H0); revert H H0;\n      ring_simplify (q * 0); ring_simplify (q0 * 0); intros;\n      exists 1; exists 1; rewrite a; intuition; apply rel_prime_1\n    | elim H; clear H; intros; destruct H as (q,H), H0 as (q0,H0);\n      exists q; exists q0; rewrite (Zmult_comm d q);\n      rewrite (Zmult_comm d q0); intuition; elim (rel_prime_dec q q0); intro;\n        [ auto\n        | elimtype False; elim (not_rel_prime1 _ _ b0); clear b0; intros;\n          elim H2; clear H2; intros; elim H2; clear H2; intros;\n          generalize (Zdivide_mult_l _ _ d H2); intro; \n          generalize (Zdivide_mult_l _ _ d H4); intro; rewrite <- H in H6;\n          rewrite <- H0 in H7; generalize (H1 _ H6 H7); clear H5 H6 H7; intro;\n          elim H2; clear H2; intros; elim H4; clear H4; intros;\n          rewrite H2 in H; clear H2; rewrite H4 in H0; clear H4;\n          rewrite <- Zmult_assoc in H; rewrite <- Zmult_assoc in H0;\n          generalize (Zdivide_intro (x0 * d) x _ H); clear H; intro;\n          generalize (Zdivide_intro (x0 * d) y _ H0); clear H0; intro;\n          generalize (H1 _ H H0); elim H3; clear H H0 H3; do 2 intro;\n          apply not_divide1; auto ] ].\nQed.\n\nLemma relp_mult2 : forall a b : Z, rel_prime (a * b) a -> a = 1 \\/ a = -1.\nProof.\n  intros; elim (Z_eq_dec a 1); intro; try tauto; elim (Z_eq_dec a (-1)); intro;\n    try tauto; elimtype False; generalize (Zdivide_refl a); intro;\n    generalize (Zdivide_factor_r a b); intro;\n    generalize (not_rel_prime2 _ _ _ H1 H0 b0 b1); auto.\nQed.\n\nLemma relp_mult3 : forall a b c : Z, rel_prime (a * b) c -> rel_prime a c.\nProof.\n  intros; elim (rel_prime_dec a c); intro; try assumption; elimtype False;\n    elim (not_rel_prime1 _ _ b0); clear b0; intros; do 2 (elim H0; clear H0;\n    intros); elim H1; clear H1; intros; generalize (Zdivide_mult_l _ _ b H0);\n    clear H0; intro; generalize (not_rel_prime2 _ _ _ H0 H2 H1 H4); auto.\nQed.\n\nLemma gcd2_rel_prime : forall a b s w : Z,\n  (Zis_gcd a b 2) -> a = 4 * s -> b = 2 * w -> rel_prime s w.\nProof.\n  intros; elim (gcd_rel_prime _ _ _ H); clear H; intros; rewrite H0 in H;\n    rewrite H1 in H; do 2 (elim H; clear H; intros); elim H2; clear H2; intros;\n    replace (4 * s) with (2 * (2 * s)) in H; try ring; cut (2 <> 0);\n    auto with zarith; intro; generalize (Zmult_eq_reg_l _ _ _ H H4); intro;\n    generalize (Zmult_eq_reg_l _ _ _ H2 H4); intro; rewrite <- H5 in H3;\n    rewrite <- H6 in H3; rewrite Zmult_comm in H3;\n    apply relp_mult3 with (b := 2); assumption.\nQed.\n\nLemma relp_neq : forall m n : Z, m <> 1 -> m <> -1 -> rel_prime m n -> m <> n.\nProof.\n  intros; case (Z_eq_dec m n); auto; intro; elimtype False;\n    generalize (Zdivide_refl m); intro; generalize (Zdivide_refl n);\n    pattern n at 1; rewrite <- e; intro;\n    generalize (not_rel_prime2 _ _ _ H2 H3 H H0); auto.\nQed.\n\nLemma prop2 : forall m n : Z, rel_prime m n -> rel_prime (m * m) (n * n).\nProof.\n  intros; apply rel_prime_mult; apply rel_prime_sym; apply rel_prime_mult;\n    apply rel_prime_sym; assumption.\nQed.\n\nLemma is_sqr_compat : forall k a : Z,\n  k <> 0 -> is_sqr ((k * k) * a) -> is_sqr a.\nProof.\n  intros; elim H0; clear H0; intros; do 2 (elim H1; clear H1; intros);\n    elim (rel_prime_dec x k); intro;\n      [ generalize (prop2 _ _ a0); clear a0; intro; rewrite H1 in H3;\n        elim (relp_mult2 _ _ H3); intro;\n          [ rewrite H4 in H1; rewrite Zmult_1_l in H1; rewrite <- H1;\n            unfold is_sqr; intuition; exists x; intuition\n          | elimtype False; generalize (sqr_pos k); intro; rewrite H4 in H5;\n            auto with zarith ]\n      | elim (not_rel_prime1 _ _ b); clear b; intros; elim H3; clear H3;\n        intros; elim H4; clear H4; intros; elim (gcd_rel_prime _ _ _ H3);\n        clear H3; intros; do 2 (elim H3; clear H3; intros); elim H6; clear H6;\n        intros; rewrite H3 in H1; rewrite H6 in H1; elim (Z_eq_dec x0 0);\n        intro; try (elimtype False; rewrite a0 in H6; simpl in H6; auto);\n        replace (x0 * x1 * (x0 * x1)) with (x0 * x0 * (x1 * x1)) in H1;\n        try ring; replace (x0 * x2 * (x0 * x2) * a) with\n        (x0 * x0 * (x2 * x2 * a)) in H1; try ring; generalize (sqr_spos _ b);\n        clear b; intro; cut ((x1 * x1) = x2 * x2 * a);\n        try (apply Zcompare_Eq_eq;\n        rewrite (Zmult_compare_compat_l (x1 * x1) (x2 * x2 * a) (x0 * x0) H8);\n        elim (Zcompare_Eq_iff_eq (x0 * x0 * (x1 * x1))\n        (x0 * x0 * (x2 * x2 * a))); auto); clear H1; intro;\n        generalize (prop2 _ _ H7); clear H7; intro; rewrite H1 in H7;\n        elim (relp_mult2 _ _ H7); intro;\n          [ rewrite H9 in H1; rewrite Zmult_1_l in H1; rewrite <- H1;\n            elim (Z_le_dec 0 x1); intro;\n              [ unfold is_sqr; intuition; exists x1; intuition\n              | split; [ apply Zge_le; apply sqr_pos | exists (-x1);\n                intuition; ring ] ]\n          | elimtype False; generalize (sqr_pos x2); intro; rewrite H9 in H10;\n            auto with zarith ] ].\nQed.\n\nLemma divide_trans : forall a b c : Z, (a | b) -> (b | c) -> (a | c).\nProof.\n  intros a b c (q,H) (q0,H0);\n    rewrite H in H0; clear H; rewrite Zmult_assoc in H0;\n    apply (Zdivide_intro a c (q0 * q)); assumption.\nQed.\n\nLemma divide_sum : forall a b c : Z, (a | b) -> (a | b + c) -> (a | c).\nProof.\n  intros a b c (q,H) (q0,H0);\n    cut (c = q0 * a - b); auto with zarith; clear H0; intro; rewrite H in H0;\n    exists (q0 - q); rewrite H0; ring.\nQed.\n\nLemma divide_mult_l : forall a b c : Z, c <> 0 -> (c * a | c * b) -> (a | b).\nProof.\n  intros a b c H (q,H0); replace (q * (c * a)) with (c * (q * a))\n    in H0; try ring; generalize (Zmult_eq_reg_l _ _ _ H0 H); clear H0; intro;\n    apply Zdivide_intro with (q := q); assumption.\nQed.\n\nLemma divide_0 : forall z : Z, (0 | z) -> z = 0.\nProof.\n  intros; elim H; clear H; intros; auto with zarith.\nQed.\n\nLemma divide_2 : forall z : Z, 0 <= z -> z <> 0 -> z <> 1 -> (z | 2) -> z = 2.\nProof.\n  intros; cut (2 <> 0); auto with zarith; intro;\n    generalize (Zdivide_bounds _ _ H2 H3); clear H2; simpl; generalize H;\n      generalize H0; generalize H1; elim z; simpl; intros;\n      progress (auto with zarith) || (elimtype False; auto with zarith).\nQed.\n\nLemma divide_2b : forall z : Z,\n  z <> 1 -> z <> -1 -> (z | 2) -> z = 2 \\/ z = -2.\nProof.\n  intros; elim (Z_eq_dec z 0); intro;\n    [ elim H1; clear H1; intros; rewrite a in H1; auto with zarith\n    | cut (2 <> 0); auto with zarith; intro;\n      generalize (Zdivide_bounds _ _ H1 H2); clear H1; simpl; generalize H;\n      generalize H0; generalize b; elim z; simpl; intros;\n      progress (auto with zarith) || (generalize (Zle_0_pos p); intro;\n      progress (auto with zarith)) || (rewrite <- Zopp_neg in H4;\n      generalize (Zlt_neg_0 p); auto with zarith) ].\nQed.\n\nLemma divide_4 : forall a b : Z, (a * a * a * a | b * b * b * b) -> (a | b).\nProof.\n  intros a b (q,H); cut (is_sqr ((a * a * (a * a)) * q));\n    [ intro; elim (Z_eq_dec a 0); intro; try (rewrite a0 in H;\n      rewrite (Zmult_comm q) in H; simpl in H; rewrite <- Zmult_assoc in H;\n      do 2 (generalize (sqr_0 _ H); clear H; intro); rewrite H;\n      apply Zdivide_0); cut (a * a <> 0); try (generalize (sqr_spos _ b0);\n      solve [ auto with zarith ]); intro; generalize (is_sqr_compat _ _ H1 H0);\n      clear H0; intro; elim H0; clear H0; intros; do 2 (elim H2; clear H2;\n      intros); rewrite <- H2 in H; replace (x * x * (a * a * a * a)) with\n      (a * a * x * (a * a * x)) in H; try ring; cut (0 <= a * a * x);\n      try (apply Zmult_le_0_compat; try assumption; apply Zge_le;\n      apply sqr_pos); intro; rewrite <- Zmult_assoc in H;\n      elim (sqr_compat _ _ H); intro; try (elim (Z_eq_dec b 0); intro;\n        [ rewrite a0; exists 0\n        | elimtype False; generalize (sqr_spos _ b1); intro ];\n      solve [ auto with zarith ]); cut (is_sqr (a * a * x));\n      try (unfold is_sqr; intuition; elim (Z_le_dec b 0); intro;\n      [ exists (-b) | exists b ]; intuition; rewrite <- H5; ring); intro;\n      generalize (is_sqr_compat _ _ b0 H6); clear H6; intro; elim H6; clear H6;\n      intros; do 2 (elim H7; clear H7; intros); rewrite <- H7 in H5;\n      replace (a * a * (x0 * x0)) with (a * x0 * (a * x0)) in H5; try ring;\n      elim (sqr_compat _ _ H5); intro; [ exists x0 | exists (-x0) ];\n      rewrite H9; ring\n    | split;\n      [ replace (a * a * (a * a) * q) with (q * (a * a * a * a)); try ring;\n        rewrite <- H; rewrite <- (Zmult_assoc (b * b)); apply Zge_le;\n        apply sqr_pos\n      | exists (b * b); split;\n        [ rewrite Zmult_assoc; rewrite H; ring\n        | apply Zge_le; apply sqr_pos ] ] ].\nQed.\n\nLemma divide_sqr : forall a b : Z, (a | b) -> (a * a | b * b).\nProof.\n  intros a b (q,H); rewrite H; replace (q * a * (q * a)) with\n    ((q * q) * (a * a)); try ring; apply Zdivide_factor_l.\nQed.\n\nLemma gcd2_relp_odd : forall u v : Z,\n  Zodd u -> Zodd v -> rel_prime u v -> (Zis_gcd (u - v) (u + v) 2).\nProof.\n  intros; elim (Zgcd_spec (u - v) (u + v)); intros; elim p; clear p; intros;\n    elim H2; intros; generalize (Zdivide_plus_r _ _ _ H4 H5);\n    ring_simplify (u - v + (u + v)); intro;\n    generalize (Zdivide_opp_r _ _ H4); intro;\n    generalize (Zdivide_plus_r _ _ _ H5 H8);\n    ring_simplify (u + v + - (u - v));\n    clear H8; intro; generalize (Zodd_sum2 _ _ H H0); intro;\n    elim (Zeven_def1 _ H9); clear H9; intros; rewrite Zmult_comm in H9;\n    generalize (Zdivide_intro _ _ _ H9); clear x0 H9; intro;\n    generalize (Zodd_sum1 _ _ H H0); intro; elim (Zeven_def1 _ H10); clear H10;\n    intros; rewrite Zmult_comm in H10; generalize (Zdivide_intro _ _ _ H10);\n    clear x0 H10; intro; generalize (H6 _ H9 H10); clear H9 H10; intro;\n    elim H9; clear H9; intros; rewrite Zmult_comm in H9; rewrite H9 in H7;\n    rewrite H9 in H8; cut (2 <> 0); auto with zarith; intro;\n    generalize (divide_mult_l _ _ _ H10 H7); clear H7; intro;\n    generalize (divide_mult_l _ _ _ H10 H8); clear H8 H10; intro; elim H1;\n    intros; generalize (H12 _ H7 H8); intro; elim (Zdivide_1 _ H13); intro;\n    try (elimtype False; rewrite H14 in H9; progress auto with zarith);\n    rewrite H14 in H9; simpl in H9; rewrite H9 in H2; assumption.\nQed.\n\nLemma rel_prime_opp : forall x y : Z, rel_prime x y -> rel_prime (-x) (-y).\nProof.\n  unfold rel_prime; intros; do 2 (apply Zis_gcd_minus;\n    rewrite Zopp_involutive); assumption.\nQed.\n\nLemma rel_prime_oppr : forall x y : Z, rel_prime x y -> rel_prime x (-y).\nProof.\n  intros; unfold rel_prime; apply Zis_gcd_minus; apply Zis_gcd_sym;\n    apply rel_prime_opp; assumption.\nQed.\n\nLemma rel_prime_2 : forall z : Z, Zodd z -> rel_prime 2 z.\nProof.\n  intros; elim (rel_prime_dec 2 z); auto; intro; elimtype False;\n    elim (Zodd_def1 _ H); clear H; intros; elim (not_rel_prime1 _ _ b);\n    clear b; intros; do 2 (elim H0; clear H0; intros); elim H1; clear H1;\n    intros; elim (divide_2b _ H1 H4 H0); clear H0 H3 H1 H4; intro;\n    rewrite H0 in H2; clear H0; elim H2; clear H2; intros; rewrite H0 in H;\n    clear H0; auto with zarith.\nQed.\n\nLemma relp_mult1 : forall a b c d k: Z, 0 <= a -> 0 <= b -> 0 < c -> 0 <= d ->\n  a = k * c -> b = k * d -> rel_prime a b -> k = 1.\nProof.\n  intros; rewrite H3 in H5; rewrite H4 in H5; rewrite H3 in H; clear H3 H4;\n    elim H5; clear H5; intros; elim (Zdivide_1 k); auto with zarith; intro;\n    rewrite H6 in H; clear H6; auto with zarith.\nQed.\n\nLemma relp_parity :\n  forall x y : Z, (rel_prime x y) -> (distinct_parity x y) \\/ (both_odd x y).\nProof.\n  intros; unfold distinct_parity, both_odd; elim (Zeven_odd_dec x); intro;\n    elim (Zeven_odd_dec y); intro; intuition.\n  elimtype False; unfold rel_prime in H; elim (Zeven_def1 _ a); clear a;\n    intros; elim (Zeven_def1 _ a0); clear a0; intros;\n    rewrite Zmult_comm in H1; rewrite Zmult_comm in H0;\n    generalize (Zdivide_intro _ _ x0 H0); clear H0; intro;\n    generalize (Zdivide_intro _ _ x1 H1); clear H1; intro;\n    elim H; clear H; intros; generalize (H3 _  H0 H1); clear H3; intro;\n    elim H3; clear H3; intros; auto with zarith.\nQed.\n\nLemma relp_sum :\n  forall m n : Z, (rel_prime (m + n) (m - n)) -> (rel_prime m n).\nProof.\n  intros; elim (rel_prime_dec m n); intro; try assumption.\n  elimtype False; elim (not_rel_prime1 _ _ b); clear b; intros; elim H0;\n    clear H0; intros; elim H1; clear H1; intros; elim H0; clear H0; intros;\n    elim H; clear H; intros; generalize (Zdivide_plus_r _ _ _ H0 H3); intro;\n    generalize (Zdivide_minus_l _ _ _ H0 H3); clear H H0 H3 H4 H5; intro;\n    generalize (H6 _ H7 H); clear H H6 H7; intro; elim (Zdivide_1 _ H);\n    auto.\nQed.\n\nLemma prop1 : forall m n : Z,\n  rel_prime m n -> distinct_parity m n -> rel_prime (m + n) (n - m).\nProof.\n  unfold rel_prime; intros; elim (distp_odd _ _ H0); clear H0; intros;\n    elim (Zgcd_spec (m + n) (n - m)); intros; elim p; clear p; intros;\n    elim (Z_eq_dec x 1); intro;\n      [ rewrite a in H2; assumption\n      | elimtype False; elim H2; clear H2; intros;\n        generalize (Zdivide_plus_r _ _ _ H2 H4);\n        ring_simplify (m + n + (n - m)); intro;\n        generalize (Zdivide_minus_l _ _ _ H2 H4);\n        ring_simplify (m + n - (n - m));\n        intro; elim (Zdivide_dec x 2); intro;\n          [ elim (Z_eq_dec x 0); intro;\n            [ rewrite a0 in a; clear a0; elim a; clear a; intros;\n              auto with zarith\n            | generalize (divide_2 _ H3 b0 b a); clear a; intro;\n              rewrite H8 in H2; rewrite H8 in H4; clear x H3 b H5 H6 H7 b0 H8;\n              destruct H2 as (q,H2), H4 as (q0,H3);\n              rewrite Zmult_comm in H2; rewrite Zmult_comm in H3;\n              generalize (Zeven_def2 _ (ex_intro (fun x => m + n = 2 * x)\n              q H2)); clear q H2; intro; generalize (Zeven_not_Zodd _ H2);\n              auto ]\n          | elim (Zdivide_dec 2 x); intro;\n            [ generalize (divide_trans _ _ _ a H2);\n              clear H H1 x H3 b H2 H4 H5 H6 H7 b0 a; intro; destruct H as (q,H);\n              rewrite Zmult_comm in H; generalize (Zeven_def2 _\n              (ex_intro (fun x => m + n = 2 * x) q H)); clear H; intro;\n              generalize (Zeven_not_Zodd _ H); auto\n            | generalize (prime_rel_prime _ prime_2 _ b1); intro;\n              generalize (rel_prime_sym _ _ H8); clear H8; intro;\n              generalize (Gauss _ _ _ H6 H8); clear H6; intro;\n              generalize (Gauss _ _ _ H7 H8); clear H7; intro;\n              cut (x <> -1); auto with zarith; intro;\n              generalize (not_rel_prime2 _ _ _ H7 H6 b H9); auto ] ] ].\nQed.\n\nLemma prop2b : forall m n : Z, rel_prime m n -> rel_prime m (m * m + n * n).\nProof.\n  intros; elim (rel_prime_dec m (m * m + n * n)); intros; auto;\n    elimtype False; elim (not_rel_prime1 _ _ b); clear b; intros;\n    do 2 (elim H0; clear H0; intros); elim H1; clear H1; intros;\n    generalize (Zdivide_mult_l _ _ m H0); intro;\n    generalize (divide_sum _ _ (n * n) H5 H2); intro;\n    generalize (prop2 _ _ H); clear H; intro;\n    apply (not_rel_prime2 _ _ _ H5 H6 H1 H4); assumption.\nQed.\n\nLemma prop2c : forall m n : Z, rel_prime m n -> rel_prime m (m * m - n * n).\nProof.\n  intros; elim (rel_prime_dec m (m * m - n * n)); intros; auto;\n    elimtype False; elim (not_rel_prime1 _ _ b); clear b; intros;\n    do 2 (elim H0; clear H0; intros); elim H1; clear H1; intros;\n    generalize (Zdivide_mult_l _ _ m H0); intro;\n    generalize (divide_sum _ _ (- (n * n)) H5 H2); intro;\n    generalize (Zdivide_opp_r_rev _ _ H6); clear H6; intro;\n    generalize (prop2 _ _ H); clear H; intro;\n    apply (not_rel_prime2 _ _ _ H5 H6 H1 H4); assumption.\nQed.\n\nLemma prop3 : forall m n : Z, rel_prime (m * m) (n * n) -> rel_prime m n.\nProof.\n  intros; elim H; intros; unfold rel_prime; apply Zis_gcd_intro;\n    auto with zarith.\nQed.\n\nDefinition R_prime (x y : Z) := 1 < x /\\ 1 < y /\\ x < y.\n\nDefinition f_Z (x : Z) := Zabs_nat x.\n\nLemma R_prime_wf : well_founded R_prime.\nProof.\n  apply (well_founded_lt_compat _ f_Z R_prime); unfold R_prime, f_Z; intros;\n    apply Zabs_nat_lt; intuition.\nQed.\n\nLemma ind_prime : forall P : Z -> Prop,\n  (forall x : Z, (forall y : Z, (R_prime y x -> P y)) -> P x) ->\n  forall x : Z, P x.\nProof.\n  intros; generalize (well_founded_ind R_prime_wf P); auto.\nQed.\n\nLemma prime_dec_gen : forall a b : Z, 1 < b -> b < a ->\n  (forall c : Z, b < c < a -> rel_prime c a) -> prime a \\/ ~ prime a.\nProof.\n  intros a b; pattern b;\n    match goal with\n    | |- (?p _) =>\n      simpl; case (Z_lt_dec 1 a); intro; try (right; red; intro; elim H2;\n      clear H2; intros; progress auto); apply (ind_prime p); intros;\n      case (rel_prime_dec x a); intro;\n        [ case (Z_eq_dec x 2); intro;\n          [ left; rewrite e in H2; rewrite e in r; generalize (rel_prime_1 a);\n            intro; apply prime_intro; try assumption; intros;\n            case (Z_eq_dec n 1); intro; try (rewrite e0; assumption);\n            case (Z_eq_dec n 2); intro; try (rewrite e0; assumption); apply H2;\n            auto with zarith\n          | apply (H (x - 1)); try unfold R_prime; auto with zarith; intros;\n            case (Z_eq_dec c x); intro; try (rewrite e; assumption); apply H2;\n            auto with zarith ]\n        | right; red; intro; elim H3; clear H3; intros; cut (1 <= x < a);\n          auto with zarith; intro; generalize (H4 _ H5); auto ]\n    end.\nQed.\n\nLemma prime_dec : forall a : Z, prime a \\/ ~ prime a.\nProof.\n  intros; case (Z_eq_dec a 2); intro;\n    [ left; rewrite e; apply prime_2\n    | case (Z_lt_dec 1 a); intro; try (right; red; intro; elim H; clear H;\n      intros; progress auto); apply (prime_dec_gen a (a - 1));\n      auto with zarith; intros; elimtype False; auto with zarith ].\nQed.\n\nLemma not_prime_gen : forall a b : Z, 1 < a -> 1 < b -> b < a -> ~ prime a ->\n  (forall c : Z, b < c < a -> rel_prime c a) ->\n  exists q : Z, exists b : Z, a = q * b /\\ 1 < q /\\ 1 < b.\nProof.\n  induction b using ind_prime; intros.\n  destruct (Zdivide_dec b a) as [(q,H5)|n].\n  - exists q; exists b; intuition;\n    apply (Zmult_gt_0_lt_reg_r 1 q b); auto with zarith.\n  - case (rel_prime_dec b a); intro.\n    * case (Z_eq_dec b 2); intro.\n      + absurd (prime a); try assumption.\n        apply prime_intro; auto; rewrite e in H4; rewrite e in r;\n        generalize (rel_prime_1 a); intros; case (Z_eq_dec n0 1); intro;\n        try (rewrite e0; assumption); case (Z_eq_dec n0 2); intro;\n        try (rewrite e0; assumption); apply H4; auto with zarith.\n      + assert (R_prime (b - 1) b) by (unfold R_prime; intuition).\n        assert (1 < b - 1) by auto with zarith.\n        assert (b - 1 < a) by auto with zarith.\n        assert (forall c : Z, (b - 1) < c < a -> rel_prime c a)\n        by (intros; case (Z_eq_dec c b); intro;\n            try (rewrite e; assumption);\n            apply H4; auto with zarith).\n        elim (H _ H5 H0 H6 H7 H3 H8); intros; elim H9; clear H9; intros;\n        exists x; exists x0; intuition.\n    * elim (not_rel_prime1 _ _ n0); clear n0; intros;\n      do 2 (elim H5; clear H5; intros); elim H6; clear H6; intros;\n      destruct H7 as (q,H7).\n      assert (x <> 0)\n      by (assert (a <> 0) by auto with zarith; rewrite H7 in H10;\n          elim (Zmult_neq_0 _ _ H10); auto).\n      case (Z_le_dec 0 x); intro.\n      + exists q; exists x; intuition; rewrite H7 in H0.\n        assert (0 < q * x) by auto with zarith.\n        assert (0 < x) by auto with zarith.\n        generalize (Zmult_lt_0_reg_r _ _ H12 H11); intro;\n        case (Z_eq_dec q 1); auto with zarith; intro; elimtype False;\n        rewrite e in H7; rewrite Zmult_1_l in H7; destruct H5 as (q0,H5);\n        rewrite H5 in H1; cut (0 < q0 * x); auto with zarith;\n        intro; generalize (Zmult_lt_0_reg_r _ _ H12 H14); intro;\n        rewrite H7 in H2; rewrite <- (Zmult_1_l x) in H2;\n        rewrite H5 in H2; generalize (Zmult_lt_reg_r _ _ _ H12 H2);\n        auto with zarith.\n      + exists (-q); exists (-x); intuition; try (rewrite H7; ring);\n        rewrite H7 in H0; replace (q * x) with (-q * -x) in H0 by ring.\n        assert (0 < -q * -x) by auto with zarith.\n        assert (0 < -x) by auto with zarith.\n        generalize (Zmult_lt_0_reg_r _ _ H12 H11);\n        intro; case (Z_eq_dec q (-1)); auto with zarith; intro;\n        elimtype False; rewrite e in H7; rewrite Zmult_comm in H7;\n        rewrite <- Zopp_eq_mult_neg_1 in H7; destruct H5 as (q0,H5);\n        replace (q0 * x) with (-q0 * -x) in H5 by ring;\n        rewrite H5 in H1;\n        assert (0 < -q0 * -x) by auto with zarith;\n        generalize (Zmult_lt_0_reg_r _ _ H12 H14); intro;\n        rewrite <- (Zmult_1_l a) in H2; rewrite H7 in H2; rewrite H5 in H2;\n        generalize (Zmult_lt_reg_r _ _ _ H12 H2); auto with zarith.\nQed.\n\nLemma not_prime : forall a : Z, 1 < a -> ~ prime a ->\n  exists q : Z, exists b : Z, a = q * b /\\ 1 < q /\\ 1 < b.\nProof.\n  intros; case (Z_eq_dec a 2); intro;\n    [ elimtype False; rewrite e in H0; generalize (prime_2); auto\n    | apply (not_prime_gen a (a - 1)); auto with zarith; intros;\n      elimtype False; auto with zarith ].\nQed.\n\nDefinition R_fact (x y : Z) :=\n  1 < x /\\ 1 < y /\\ exists q : Z, y = q * x /\\ 1 < q.\n\nLemma R_fact_wf : well_founded R_fact.\nProof.\n  apply (well_founded_lt_compat _ f_Z R_fact); unfold R_fact, f_Z; intros;\n    apply Zabs_nat_lt; intuition; elim H2; clear H2; intros; elim H1; clear H1;\n    intros; replace x with (1 * x); try ring; rewrite H1;\n    apply Zmult_lt_compat_r; auto with zarith.\nQed.\n\nLemma ind_fact : forall P : Z -> Prop,\n  (forall x : Z, (forall y : Z, (R_fact y x -> P y)) -> P x) ->\n  forall x : Z, P x.\nProof.\n  intros; generalize (well_founded_ind R_fact_wf P); auto.\nQed.\n\nLemma Zfact : forall a : Z, 1 < a -> exists b : Z, (b | a) /\\ prime b.\nProof.\n  intro a; pattern a;\n    match goal with\n    | |- (?p _) =>\n      simpl; apply (ind_fact p); intros; case (prime_dec x); intro;\n        [ exists x; intuition\n        | elim (not_prime _ H0 H1); intros; do 2 (elim H2; clear H2; intros);\n          elim H3; clear H3; intros; cut (exists b : Z, (b | x1) /\\ prime b);\n          try (apply H; try assumption; unfold R_fact; intuition; exists x0;\n          intuition); intro; do 2 (elim H5; clear H5; intros); exists x2;\n          intuition; elim H5; clear H5; intros; rewrite H5 in H2;\n          rewrite Zmult_assoc in H2; apply (Zdivide_intro _ _ _ H2) ]\n    end.\nQed.\n\nDefinition R_p4 (x y : Z) :=\n  0 <= x /\\ 1 < y /\\ exists d : Z, y = d * d * x /\\ 1 < d.\n\nLemma R_p4_wf : well_founded R_p4.\nProof.\n  apply (well_founded_lt_compat _ f_Z R_p4); unfold R_p4, f_Z; intros;\n    apply Zabs_nat_lt; intuition; elim H2; clear H2; intros; elim H1; clear H1;\n    intros; cut (1 < x0 * x0); try (cut (1 >= 0); auto with zarith; intro;\n    generalize (sqr_gt _ _ H3 H2); simpl; progress auto); intro; \n    cut (y <> 0); auto with zarith; intro; rewrite H1 in H4;\n    elim (Zmult_neq_0 _ _ H4); intros; rewrite H1; pattern x at 1;\n    replace x with (1 * x); try ring; apply Zmult_lt_compat_r;\n    auto with zarith.\nQed.\n\nLemma ind_p4 : forall P : Z -> Prop,\n  (forall x : Z, (forall y : Z, (R_p4 y x -> P y)) -> P x) ->\n  forall x : Z, P x.\nProof.\n  intros; generalize (well_founded_ind R_p4_wf P); auto.\nQed.\n\nLemma sqr_prime1 :\n  forall a : Z, is_sqr a -> forall b : Z, (b | a) -> prime b -> (b * b | a).\nProof.\n  intros; elim H; clear H; intros; elim H2; clear H2; intros; elim H2;\n    clear H2; intros; rewrite <- H2 in H0; elim (prime_mult _ H1 _ _ H0);\n    intro; generalize (divide_sqr _ _ H4); clear H4; intro; rewrite H2 in H4;\n    assumption.\nQed.\n\nLemma sqr_prime2 : forall a b c : Z,\n  (a | b) -> (a * a | b * c) -> prime a -> (a * a | b) \\/ (a | c).\nProof.\n  intros; elim H; intros q H2; elim H0; intros q0 H3;\n  rewrite H2 in H3; elim H1; intros;\n    replace (q * a * c) with (a * (q * c)) in H3; try ring;\n    replace (q0 * (a * a)) with (a * (q0 * a)) in H3; try ring;\n    cut (a <> 0); auto with zarith; intro;\n    generalize (Zmult_eq_reg_l _ _ _ H3 H6); clear H3; intro;\n    generalize (Zdivide_intro _ _ _ H3); clear H3; intro;\n    elim (prime_mult _ H1 _ _ H3); try tauto; intro; elim H7; intros;\n    rewrite H8 in H2; rewrite <- Zmult_assoc in H2;\n    generalize (Zdivide_intro _ _ _ H2); tauto.\nQed.\n\nLemma prop4 : forall p q : Z,\n  0 <= p -> 0 <= q -> rel_prime p q -> is_sqr (p * q) -> is_sqr p /\\ is_sqr q.\nProof.\n  split; generalize H2; generalize H1; generalize H0; generalize H;\n    [ pattern p\n    | pattern q ];\n    match goal with\n    | |- (?p _) =>\n      simpl; apply (ind_p4 p); intros\n    end;\n    match goal with\n    | |- is_sqr ?x => elim (Z_lt_dec 1 x); intro;\n      [ idtac\n      | elim (Z_eq_dec x 0); intro;\n        [ rewrite a; unfold is_sqr; intuition; exists 0; intuition\n        | elim (Z_eq_dec x 1); intro;\n          [ rewrite a; unfold is_sqr; intuition; exists 1; intuition\n          | elimtype False; auto with zarith ] ] ]\n    end; generalize (sqr_prime1 _ H7); intro; elim (Zfact _ a); intros; \n    elim H9; clear H9; intros; (generalize (Zdivide_mult_l _ _ q H9); intro;\n    generalize (H8 _ H11 H10)) || (generalize (Zdivide_mult_r _ p _ H9); intro;\n    generalize (H8 _ H11 H10)); intro; elim (sqr_prime2 _ _ _ H9 H12 H10) ||\n    (rewrite (Zmult_comm p) in H12; elim (sqr_prime2 _ _ _ H9 H12 H10));\n    intros; try (elimtype False; elim H10; intros; cut (x0 <> 1);\n    auto with zarith; intro; cut (x0 <> -1); auto with zarith; intro;\n    generalize (not_rel_prime2 _ _ _ H9 H13 H16 H17); progress auto ||\n    (generalize (rel_prime_sym _ _ H6); auto)); elim H13;\n    intros q0 ?; cut (is_sqr q0); try (intro; elim H15; clear H15; intros;\n    do 2 (elim H16; clear H16; intros); rewrite <- H16 in H14; unfold is_sqr;\n    intuition; rewrite H14; exists (x0 * x1); split; try ring; elim H10;\n    intros; apply Zmult_le_0_compat; auto with zarith); elim H10; intros;\n    cut (0 <= q0); try (cut (x0 <> 0); auto with zarith; intro;\n    generalize (sqr_spos _ H17); clear H17; intro; cut (0 < x);\n    auto with zarith; intro; rewrite H14 in H18;\n    generalize (Zmult_gt_0_lt_0_reg_r _ _ H17 H18); progress auto with zarith);\n    intro; (apply H3; try assumption; [ unfold R_p4; intuition; exists x0;\n    intuition; rewrite H14; ring | rewrite H14 in H6;\n    (apply (relp_mult3 q0 (x0 * x0)) || (apply rel_prime_sym;\n    apply (relp_mult3 q0 (x0 * x0)); apply rel_prime_sym)); assumption\n    | rewrite H14 in H7; (replace (q0 * (x0 * x0) * q) with\n    (x0 * x0 * (q0 * q)) in H7; try ring; apply (is_sqr_compat x0);\n    progress auto with zarith) || (replace (p * (q0 * (x0 * x0))) with\n    (x0 * x0 * (p * q0)) in H7; try ring; apply (is_sqr_compat x0);\n    auto with zarith) ]).\nQed.\n\nLemma prop4b : forall p q : Z, 0 <= p -> 0 <= q -> p <= q -> rel_prime p q ->\n  is_sqr (p * (q * (q * q - p * p))) ->\n  is_sqr p /\\ is_sqr q /\\ is_sqr (q * q - p * p).\nProof.\n  intros; generalize (prop2c _ _ H2); intro;\n    generalize (rel_prime_oppr _ _ H4); clear H4; intro;\n    replace (- (p * p - q * q)) with (q * q - p * p) in H4; try ring;\n    generalize (rel_prime_sym _ _ H2); intro; generalize (prop2c _ _ H5);\n    clear H5; intro; generalize (rel_prime_sym _ _ H4); clear H4; intro;\n    generalize (rel_prime_sym _ _ H5); clear H5; intro;\n    generalize (rel_prime_mult _ _ _ H4 H5); clear H4 H5; intro;\n    generalize (rel_prime_sym _ _ H4); clear H4; intro;\n    rewrite Zmult_assoc in H3; cut (0 <= p * q); auto with zarith; intro;\n    cut (0 <= q * q - p * p); try (apply sqr_sub1; assumption); intro;\n    generalize (prop4 _ _ H5 H6 H4 H3); clear H3 H4 H5 H6; intro; elim H3;\n    clear H3; intros; generalize (prop4 _ _ H H0 H2 H3); tauto.\nQed.\n\nLemma relp_pq1 : forall p q : Z, p >= 0 -> p <= q -> (rel_prime p q) ->\n  (distinct_parity p q) -> (rel_prime (q * q - p * p) (p * p + q * q)).\nProof.\n  intros; cut (rel_prime (p * p) (q * q));\n    [ clear H1; intro; cut (distinct_parity (p * p) (q * q));\n      [ clear H2; intro; apply rel_prime_sym; apply prop1; try apply sqr_ge;\n        assumption\n      | apply (distp_sqr1 _ _ H2) ]\n    | generalize (rel_prime_mult _ _ _ H1 H1); clear H1; intro;\n      generalize (rel_prime_sym _ _ H1); clear H1; intro;\n      generalize (rel_prime_mult _ _ _ H1 H1); clear H1; intro;\n      apply rel_prime_sym; assumption ].\nQed.\n\nLemma relp_pq2 : forall p q : Z, (rel_prime p q) -> (distinct_parity p q) ->\n  (rel_prime (2 * p * q) (p * p + q * q)).\nProof.\n  intros; generalize (prop2b _ _ H); intro; generalize (rel_prime_sym _ _ H);\n    intro; generalize (prop2b _ _ H2); clear H2; intro;\n    rewrite Zplus_comm in H2; generalize (rel_prime_sym _ _ H1); clear H1;\n    intro; generalize (rel_prime_sym _ _ H2); clear H2; intro;\n    generalize (rel_prime_mult _ _ _ H1 H2); clear H1 H2; intro;\n    cut (Zodd (p * p + q * q));\n      [ intro; generalize (rel_prime_2 _ H2); clear H2; intro;\n        generalize (rel_prime_sym _ _ H2); clear H2; intro;\n        generalize (rel_prime_mult _ _ _ H2 H1); clear H1 H2; intro;\n        apply rel_prime_sym; rewrite <- Zmult_assoc; assumption\n      | generalize (distp_sqr1 _ _ H0); clear H0; intro;\n        elim (distp_odd _ _ H0); auto ].\nQed.\n\n(***************)\n(* Regarding R *)\n(***************)\n\nLemma not_IZR_0 : forall a : Z, (IZR a <> 0)%R -> a <> 0.\nProof.\n  intros; red; intro; rewrite H0 in H; simpl in H; auto.\nQed.\n\nLemma sqr_inv : forall a b : Z, b <> 0 ->\n  (1 + IZR a * / IZR b * (IZR a * / IZR b) <> 0)%R.\nProof.\n  intros; cut (1 + IZR a * / IZR b * (IZR a * / IZR b) =\n              ((IZR a * IZR a + IZR b * IZR b) / (IZR b * IZR b)))%R.\n  intro; rewrite H0; unfold Rdiv; split_Rmult;\n    [ discrR; apply sqr_sum; assumption\n    | apply Rinv_neq_0_compat; split_Rmult; discrR; assumption ].\n  field; discrR; assumption.\nQed.\n\nLemma Rdiv_ge_0 : forall a b : R, (a >= 0 -> b > 0 -> a / b >= 0)%R.\nProof.\n  intros; unfold Rge; elim H; clear H; intro;\n    [ left; unfold Rdiv, Rgt; unfold Rgt in H0; unfold Rgt in H;\n      generalize (Rinv_0_lt_compat _ H0); clear H0; intro; \n      replace 0%R with (0 * / b)%R; [ apply Rmult_lt_compat_r; auto | ring ]\n    | right; rewrite H; field; auto with real ].\nQed.\n\nLemma Rcross_prod : forall a b c d : R,\n  (b <> 0 -> d <> 0 -> a / b = c / d -> a * d = b * c)%R.\nProof.\n  intros; generalize (Rmult_eq_compat_l (b * d) _ _ H1); clear H1; intro;\n    replace (b * d * (a / b))%R with (a * d)%R in H1;\n      [ replace (b * d * (c / d))%R with (b * c)%R in H1;\n        [ assumption | field; assumption ]\n      | field; assumption ].\nQed.\n\n(***********************)\n(* Regarding rationals *)\n(***********************)\n\nDefinition frac (a b : Z) := ((IZR a) / (IZR b))%R.\nDefinition is_rat (r : R) :=\n  exists pq : Z * Z, let (p,q) := pq in ~(q = 0) /\\ r = (frac p q).\nDefinition is_ratp (c : R * R) := let (x,y) := c in (is_rat x) /\\ (is_rat y).\n\nLemma frac_eq : forall a b c d : Z,\n  b <> 0 -> c <> 0 -> (frac a (b * c)) = (frac d c) -> a = b * d.\nProof.\n  unfold frac; intros; cut (IZR (b * c) <> 0%R);\n    [ intro; cut (IZR c <> 0%R);\n      [ intro; generalize (Rcross_prod _ _ _ _ H2 H3 H1); clear H1; intro;\n        rewrite mult_IZR in H1;\n        cut (IZR c * IZR a = IZR c * (IZR b * IZR d))%R;\n          [ clear H1; intro; generalize (Rmult_eq_reg_l _ _ _ H1 H3); clear H1;\n            intro; rewrite <- mult_IZR in H1; apply eq_IZR; assumption\n          | rewrite (Rmult_comm (IZR c) (IZR a)); rewrite H1; ring ]\n      | apply not_O_IZR; assumption ]\n    | rewrite mult_IZR; split_Rmult; apply not_O_IZR; assumption ].\nQed.\n\nLemma frac_rat : forall a b : Z,\n  b <> 0 -> (frac a b >= 0)%R -> (frac a b <= 1)%R ->\n    a >= 0 /\\ b > 0 /\\ a <= b \\/ a <= 0 /\\ b < 0 /\\ b <= a.\nProof.\n  unfold frac, Rdiv; intros; generalize (Rge_le _ _ H0); clear H0; intro; \n    elim (Z_dec b 0); intros; try (elim a0; clear a0; intros);\n    [ right; cut (0 < -b); auto with zarith; intro;\n      generalize (IZR_lt _ _ H2); clear H2; intro; simpl in H2;\n      replace 0%R with (/ IZR (- b) * 0)%R in H0; try ring;\n      rewrite (Rmult_comm (IZR a)) in H0;\n      cut (/ IZR b * IZR a = / IZR (- b) * IZR (- a))%R;\n      try (repeat rewrite Ropp_Ropp_IZR; field; \n      try rewrite <- Ropp_Ropp_IZR; apply not_O_IZR; auto with zarith);\n      intro; rewrite H3 in H0; generalize (Rinv_0_lt_compat _ H2); clear H2;\n      intro; generalize (Rmult_le_reg_l _ _ _ H2 H0); intro;\n      generalize (le_O_IZR _ H4); clear H4; intro; rewrite Rmult_comm in H1;\n      rewrite H3 in H1; replace 1%R with (/ IZR (- b) * IZR (- b))%R in H1;\n      try (field; apply not_O_IZR; auto with zarith);\n      generalize (Rmult_le_reg_l _ _ _ H2 H1); intro;\n      generalize (le_IZR _ _ H5); clear H5; intro; intuition\n    | left; generalize (Zgt_lt _ _ b0); intro; generalize (IZR_lt _ _ H2);\n      clear H2; intro; simpl in H2; replace 0%R with (/ IZR b * 0)%R in H0;\n      try ring; rewrite (Rmult_comm (IZR a)) in H0;\n      generalize (Rinv_0_lt_compat _ H2); clear H2; intro;\n      generalize (Rmult_le_reg_l _ _ _ H2 H0); intro;\n      generalize (le_O_IZR _ H3); clear H3; intro; rewrite Rmult_comm in H1;\n      replace 1%R with (/ IZR b * IZR b)%R in H1; try (field; apply not_O_IZR;\n      auto with zarith); generalize (Rmult_le_reg_l _ _ _ H2 H1); intro;\n      generalize (le_IZR _ _ H4); clear H4; intro; intuition\n    | contradiction ].\nQed.\n\nLemma frac_simp : forall a b c : Z,\n  b <> 0 -> c <> 0 -> frac (c * a) (c * b) = frac a b.\nProof.\n  intros; unfold frac; repeat rewrite mult_IZR; field; split;\n    apply not_O_IZR; assumption.\nQed.\n\nLemma frac_opp : forall a b : Z, b <> 0 -> frac (-a) (-b) = frac a b.\nProof.\n  intros; replace (-a) with (-1 * a); try replace (-b) with (-1 * b);\n    try rewrite frac_simp; auto with zarith.\nQed.\n\nLemma relp_rat : forall r : R, (is_rat r) -> (r >= 0)%R -> (r <= 1)%R ->\n  exists pq : Z * Z,\n  let (p,q) := pq in\n  (p >= 0) /\\ (q > 0) /\\ (p <= q) /\\ (rel_prime p q) /\\ r = (frac p q).\nProof.\n  intros; elim H; clear H; induction x; intro; elim H; clear H; intros;\n    elim (rel_prime_dec a b); intro;\n      [ rewrite H2 in H0; rewrite H2 in H1; elim (frac_rat _ _ H H0 H1); intro;\n        [ exists (a, b); tauto\n        | exists (-a, -b); intuition; \n          [ apply rel_prime_opp | rewrite (frac_opp a b H) ]; assumption ]\n      | elim (not_rel_prime1 _ _ b0); clear b0; intros; elim H3; clear H3;\n        intros; elim (gcd_rel_prime _ _ _ H3); clear H3; intros; elim H3;\n        clear H3; intros; elim H3; clear H3; intros; elim H5; clear H5; intros;\n        rewrite H5 in H; elim (Zmult_neq_0 _ _ H); clear H;\n        intros; rewrite H3 in H2; rewrite H5 in H2;\n        rewrite (frac_simp x0 _ _ H7 H) in H2; rewrite H2 in H0;\n        rewrite H2 in H1; elim (frac_rat _ _ H7 H0 H1); intro;\n        [ exists (x0, x1); intuition\n        | exists (-x0, -x1); intuition;\n          [ apply rel_prime_opp\n          | rewrite (frac_opp x0 x1 H7) ]; assumption ] ].\nQed.\n\n(***************************************)\n(* Adding lemmas in the auto databases *)\n(***************************************)\n\nHint Resolve rel_prime_sym : zarith.\n\nHint Immediate sqr_0 sqr_pos sqr_spos sqr_sum sqr_sum2 sqr_sum3 sqr_sum4\n  sqr_sum5 sqr_sub1 sqr_sub2 sqr_sub3 sqr_ge : zarith.\n\nHint Immediate sqr_inv Rdiv_ge_0 : reals.\n", "meta": {"author": "coq-contribs", "repo": "fermat4", "sha": "9c7417c11f0c2468fe068d56e450a6b05ecd363a", "save_path": "github-repos/coq/coq-contribs-fermat4", "path": "github-repos/coq/coq-contribs-fermat4/fermat4-9c7417c11f0c2468fe068d56e450a6b05ecd363a/ArithCompl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7038648934224726}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Type.Exp.Base.\nRequire Export Iron.Language.SystemF2Effect.Type.Relation.KindTs.\nRequire Export Iron.Language.SystemF2Effect.Type.Relation.EquivTs.\n\n\n(********************************************************************)\nFixpoint flattenT (tt : ty) : list ty\n := match tt with\n    | TSum t1 t2    => flattenT t1 ++ flattenT t2\n    | TBot    _     => nil\n    | _             => tt :: nil\n    end.\n\n\n(********************************************************************)\nLemma flattenT_kindTs\n :  forall ke sp t1 k\n ,  KindT  ke sp t1 k\n -> KindTs ke sp (flattenT t1) k.\nProof.\n intros. gen ke sp.\n induction t1; intros; simpl; eauto.\n\n Case \"TSum\". \n  inverts H.\n  unfold KindTs in *.\n   eapply Forall_app; eauto.\nQed.\nHint Resolve flattenT_kindTs.\n\n\nLemma equivT_equivTs \n :  forall  ke sp t1 t2 k\n ,  SumKind k\n -> EquivT  ke sp t1 t2 k\n -> EquivTs ke sp (flattenT t1) (flattenT t2) k.\nProof.\n intros ke sp t1 t2 k HK HE.\n induction HE; intros.\n  eapply equivTs_refl;  auto.\n  eapply equivTs_sym;   auto.\n  eapply equivTs_trans; auto.\n\n - Case \"EqSumCong\".\n   simpl.\n   spec IHHE1 HK.\n   spec IHHE2 HK.\n   eauto.\n\n - Case \"EqSumBot\".\n   simpl. norm. \n   apply equivTs_refl; auto.\n   \n - Case \"EqSumIdemp\".\n   simpl.\n   eapply EqsSum; norm; auto.\n   + eapply in_app_split in H1.\n     inverts H1; auto.\n\n - Case \"EqSumComm\".\n   simpl.\n   eapply EqsSum; snorm.\n\n - Case \"EqSumAssoc\".\n   simpl.\n   eapply EqsSum; auto.\n   + norm. \n     eapply in_app_split in H3. inverts H3.\n     eapply in_app_split in H4. inverts H4.\n     auto. auto. auto.\n   + norm.\n     eapply in_app_split in H3. inverts H3. auto.\n     eapply in_app_split in H4. inverts H4. \n     auto. auto.\nQed.\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/SystemF2Effect/Type/Operator/FlattenT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.703833907313391}}
{"text": "Require Import Undecidability.FOL.Syntax.Facts Undecidability.FOL.Syntax.Theories.\nRequire Export Undecidability.FOL.Semantics.Tarski.FragmentCore.\nFrom Undecidability Require Import Shared.ListAutomation.\nImport ListAutomationNotations.\nRequire Import Vector Lia.\n\n\nLocal Set Implicit Arguments.\nLocal Unset Strict Implicit.\n\n\nLocal Notation vec := Vector.t.\n\n\n(* Tarski Semantics ***)\n\n\nSection Tarski.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  (* Semantic notions *)\n  \n  \n  Section Substs.\n    \n    Variable D : Type.\n    Variable I : interp D.\n        \n    Lemma eval_ext rho xi t :\n      (forall x, rho x = xi x) -> eval rho t = eval xi t.\n    Proof.\n      intros H. induction t; cbn.\n      - now apply H.\n      - f_equal. apply map_ext_in. now apply IH.\n    Qed.\n\n    Lemma eval_comp rho xi t :\n      eval rho (subst_term xi t) = eval (xi >> eval rho) t.\n    Proof.\n      induction t; cbn.\n      - reflexivity.\n      - f_equal. rewrite map_map. apply map_ext_in, IH.\n    Qed.\n\n    Lemma sat_ext {ff : falsity_flag} rho xi phi :\n      (forall x, rho x = xi x) -> rho ⊨ phi <-> xi ⊨ phi.\n    Proof.\n      induction phi  as [ | b P v | | ] in rho, xi |- *; cbn; intros H.\n      - reflexivity.\n      - erewrite map_ext; try reflexivity. intros t. now apply eval_ext.\n      - specialize (IHphi1 rho xi). specialize (IHphi2 rho xi). destruct b0; intuition.\n      - destruct q.\n        + split; intros H' d; eapply IHphi; try apply (H' d). 1,2: intros []; cbn; intuition.\n    Qed.\n\n    Lemma sat_ext' {ff : falsity_flag} rho xi phi :\n      (forall x, rho x = xi x) -> rho ⊨ phi -> xi ⊨ phi.\n    Proof.\n      intros Hext H. rewrite sat_ext. exact H.\n      intros x. now rewrite (Hext x).\n    Qed.\n\n    Lemma sat_comp {ff : falsity_flag} rho xi phi :\n      rho ⊨ (subst_form xi phi) <-> (xi >> eval rho) ⊨ phi.\n    Proof.\n      induction phi as [ | b P v | | ] in rho, xi |- *; cbn.\n      - reflexivity.\n      - erewrite map_map, map_ext; try reflexivity. intros t. apply eval_comp.\n      - specialize (IHphi1 rho xi). specialize (IHphi2 rho xi). destruct b0; intuition.\n      - destruct q.\n        + setoid_rewrite IHphi. split; intros H d; eapply sat_ext. 2, 4: apply (H d).\n          all: intros []; cbn; trivial; now setoid_rewrite eval_comp.\n    Qed.\n\n    Lemma sat_subst {ff : falsity_flag} rho sigma phi :\n      (forall x, eval rho (sigma x) = rho x) -> rho ⊨ phi <-> rho ⊨ (subst_form sigma phi).\n    Proof.\n      intros H. rewrite sat_comp. apply sat_ext. intros x. now rewrite <- H.\n    Qed.\n\n    Lemma sat_single {ff : falsity_flag} (rho : nat -> D) (Phi : form) (t : term) :\n      (eval rho t .: rho) ⊨ Phi <-> rho ⊨ subst_form (t..) Phi.\n    Proof.\n      rewrite sat_comp. apply sat_ext. now intros [].\n    Qed.\n\n    Lemma impl_sat {ff : falsity_flag} A rho phi :\n      sat rho (A ==> phi) <-> ((forall psi, psi el A -> sat rho psi) -> sat rho phi).\n    Proof.\n      induction A; cbn; firstorder congruence.\n    Qed.\n\n    Lemma impl_sat' {ff : falsity_flag} A rho phi :\n      sat rho (A ==> phi) -> ((forall psi, psi el A -> sat rho psi) -> sat rho phi).\n    Proof.\n      eapply impl_sat.\n    Qed.\n\n    Lemma bounded_eval_t n t sigma tau :\n      (forall k, n > k -> sigma k = tau k) -> bounded_t n t -> eval sigma t = eval tau t.\n    Proof.\n      intros H. induction 1; cbn; auto.\n      f_equal. now apply Vector.map_ext_in.\n    Qed.\n    \n    Lemma bound_ext {ff : falsity_flag} N phi rho sigma :\n      bounded N phi -> (forall n, n < N -> rho n = sigma n) -> (rho ⊨ phi <-> sigma ⊨ phi).\n    Proof.\n      induction 1 in sigma, rho |- *; cbn; intros HN; try tauto.\n      - enough (map (eval rho) v = map (eval sigma) v) as E. now setoid_rewrite E.\n        apply Vector.map_ext_in. intros t Ht.\n        eapply bounded_eval_t; try apply HN. now apply H.\n      - destruct binop; now rewrite (IHbounded1 rho sigma), (IHbounded2 rho sigma).\n      - destruct quantop.\n        + split; intros Hd d; eapply IHbounded.\n          all : try apply (Hd d); intros [] Hk; cbn; auto.\n          symmetry. all: apply HN; lia.\n    Qed. \n\n    Corollary sat_closed {ff : falsity_flag} rho sigma phi :\n      bounded 0 phi -> rho ⊨ phi <-> sigma ⊨ phi.\n    Proof.\n      intros H. eapply bound_ext. apply H. lia.\n    Qed.\n\n    Lemma bounded_S_forall {ff : falsity_flag} N phi :\n      bounded (S N) phi <-> bounded N (∀ phi).\n    Proof.\n      split; intros H.\n      - now constructor.\n      - inversion H. apply Eqdep_dec.inj_pair2_eq_dec in H4 as ->; trivial.\n        unfold Dec.dec. decide equality.\n    Qed.\n\n    Definition forall_times {ff : falsity_flag} n (phi : form) := iter (fun psi => ∀ psi) n phi.\n\n  End Substs.\n\nEnd Tarski.\n\n\n\n(* Trivial Model *)\n\nSection TM.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Instance TM : interp unit :=\n    {| i_func := fun _ _ => tt; i_atom := fun _ _ => True; |}.\n\n  Fact TM_sat (rho : nat -> unit) (phi : form falsity_off) :\n    rho ⊨ phi.\n  Proof.\n    revert rho. remember falsity_off as ff. induction phi; cbn; trivial.\n    - discriminate.\n    - destruct b0; auto.\n    - destruct q; firstorder.\n  Qed.\n\n  Fact TM_sat_decidable {ff} (rho : nat -> unit) (phi : form ff) :\n    rho ⊨ phi \\/ ~(rho ⊨ phi).\n  Proof.\n    revert rho. induction phi; cbn; intros rho; eauto.\n    - destruct b0. destruct (IHphi1 rho), (IHphi2 rho); tauto.\n    - destruct q. destruct (IHphi (tt .: rho)).\n      + left; now intros [].\n      + right; intros Hcc. apply H, Hcc.\n  Qed.\n\nEnd TM.\n\nSection FlagsTransport.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n  Context {ff1 : falsity_flag}.\n\n  Section Bottom.\n    Variable D : Type.\n    Variable I : interp D. \n    Context (default : @form _ _ _ ff1).\n\n    Lemma sat_to_falsity_compat {ff2} rho (phi : @form _ _ _ ff2) : \n      (sat rho default -> False)\n      -> sat rho phi <-> sat rho (phi[default /⊥]).\n    Proof.\n      induction phi as [|t1 t2|ff [] phi IHphi psi IHpsi|ff [] phi IHphi] in rho,default|-*; intros Hdefault; split.\n      - intros [].\n      - apply Hdefault.\n      - intros H; apply H.\n      - intros H; apply H.\n      - intros H H1. cbn in H. apply IHpsi. 1:easy. apply H. now eapply IHphi, H1.\n      - intros H H1. cbn in H. apply IHpsi with default. 1:easy. apply H. now apply IHphi.\n      - intros H d. apply IHphi. 2: apply H. intros Hd. apply Hdefault.\n        eapply sat_comp in Hd. eapply sat_ext in Hd. 1: apply Hd.\n        now intros [|x].\n      - intros H d. apply IHphi with (default [↑]). 2: apply H. intros Hd. apply Hdefault.\n        eapply sat_comp in Hd. eapply sat_ext in Hd. 1: apply Hd.\n        now intros [|x].\n    Qed.\n  End Bottom.\n  Section Atoms.\n\n    Context {Σ_preds2 : preds_signature}.\n    Context (s : forall (P : Σ_preds), Vector.t (@term Σ_funcs) (ar_preds P) -> (@form Σ_funcs Σ_preds2 _ _)).\n    Context (Hresp : atom_subst_respects s).\n\n    Definition rho_from_vec {A} n (v : Vector.t A n) d : env A := fun m => match Compare_dec.lt_dec m n with\n      left Hl => Vector.nth v (Fin.of_nat_lt Hl)\n    | right _ => d end.\n\n    Lemma rho_from_vec_map {A B} {n} (f : B -> A) (t : Vector.t B n) (d2 : A) (d:B):\n     f d = d2 ->\n     forall k, rho_from_vec (map f t) d2 k = f (rho_from_vec t d k).\n    Proof.\n      intros H k. unfold rho_from_vec. destruct (Compare_dec.lt_dec k n) as [Hl|Hr].\n      - erewrite nth_map. 2:reflexivity. easy.\n      - easy.\n    Qed.\n\n    Fixpoint tabulate_vars n : Vector.t term n := match n with\n        0 => Vector.nil _\n    | S n => Vector.cons _ ($0) _ (map (subst_term (S >> var)) (tabulate_vars n)) end.\n\n    Lemma tabulate_vars_nth n (x : Fin.t n) : Vector.nth (tabulate_vars n) x = $(proj1_sig (Fin.to_nat x)).\n    Proof.\n      induction n in x|-*. 1: exfalso; revert x; apply Fin.case0.\n      induction x. try easy.\n      cbn. destruct (Fin.to_nat x) as [i P]. cbn in *. erewrite nth_map. 2:easy.\n      rewrite IHx. easy.\n    Qed.\n\n    Lemma semantic_lifting_correct n t tt : \n      map (subst_term (rho_from_vec t tt)) (tabulate_vars n) = t.\n    Proof.\n      apply eq_nth_iff. intros i ? <-.\n      erewrite nth_map. 2:reflexivity.\n      rewrite tabulate_vars_nth. cbn.\n      unfold rho_from_vec. destruct (Fin.to_nat i) as [i2 P2] eqn:Heq; cbn. \n      destruct Compare_dec.lt_dec; try lia.\n      f_equal. erewrite <- Fin.of_nat_to_nat_inv. rewrite Heq. cbn. apply Fin.of_nat_ext.\n    Qed.\n\n    Section ConstructInterp.\n      Variable D : Type.\n      (* Crucially, we need an interpretation for the formulas s maps _to_ *)\n      Variable I : @interp Σ_funcs Σ_preds2 D. \n      Definition lift_s_semantically (d:D) (P : Σ_preds) (v : Vector.t D (ar_preds P)) : Prop\n        := sat (rho_from_vec v d) (s (tabulate_vars (ar_preds P))).\n\n      (* To construct an interpretation for the formulas we are mapping _from_ *)\n      Definition interp_s (d:D) : @interp Σ_funcs Σ_preds D := {|\n        i_func := @i_func _ _ D I;\n        i_atom := lift_s_semantically d\n      |}.\n\n      Lemma sat_atom_subst_compat rho phi n :\n        sat rho (phi [s/atom]) <-> @sat _ _ _ (interp_s (rho n)) _ rho phi.\n      Proof using Hresp.\n        unfold interp_s, lift_s_semantically. revert rho n.\n        induction phi as [|t1 t2|ff [] phi IHphi psi IHpsi|ff [] phi IHphi]; split.\n        - intros H; apply H.\n        - intros H; apply H.\n        - cbn; intros H.\n          eapply sat_ext with (((rho_from_vec t $n) >> eval rho)).\n          1: intros x; unfold funcomp. now apply rho_from_vec_map.\n          rewrite <- sat_comp. rewrite Hresp. now rewrite semantic_lifting_correct.\n        - cbn; intros H. \n          eapply (@sat_ext _ _ _ _ _ (((rho_from_vec t $n) >> eval rho))) in H.\n          2: intros x; unfold funcomp; symmetry; now apply rho_from_vec_map.\n          rewrite <- sat_comp in H. rewrite Hresp in H. now rewrite semantic_lifting_correct in H.\n        - cbn; intros H1 Hphi. apply IHpsi. 1:easy. apply H1. apply IHphi with n. 1:easy. apply Hphi.\n        - cbn; intros H1 Hphi. apply IHpsi with n. 1:easy. apply H1, IHphi. 1:easy. apply Hphi.\n        - cbn; intros H1 d. apply (IHphi s Hresp (d.:rho) (S n)). apply H1.\n        - cbn; intros H1 d. apply (IHphi s Hresp (d.:rho) (S n)). apply H1.\n      Qed.\n\n    End ConstructInterp.\n\n    Lemma valid_atom_subst_compat phi :\n      valid phi -> valid phi [s/atom].\n    Proof using Hresp.\n      intros H D I rho. unshelve apply <- sat_atom_subst_compat. 1:exact 0. apply H.\n    Qed.\n\n    Lemma satis_atom_subst_compat phi :\n      satis phi[s/atom] -> satis phi .\n    Proof using Hresp.\n      intros (D&I&rho&H). unshelve eapply sat_atom_subst_compat in H. 1:exact 0. do 3 eexists. apply H.\n    Qed.\n\n  End Atoms.\n\nEnd FlagsTransport.\n\nSection Bottom.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Variable D : Type.\n  Variable I : interp D.\n\n  Definition interp_bot (F_P : Prop) (i : @interp Σ_funcs Σ_preds D) : @interp Σ_funcs (@Σ_preds_bot Σ_preds) D := {|\n    i_func := @i_func _ _ D i;\n    i_atom := fun (P : (@preds (@Σ_preds_bot Σ_preds))) => match P with inl _ => fun v => F_P | inr P => fun v => @i_atom _ _ D i P v end\n  |}.\n\n  Definition sat_bot {ff : falsity_flag} (F_P : Prop) (rho : env D) (phi : form) : Prop \n    := @sat _ Σ_preds_bot D (interp_bot F_P I) falsity_off rho (falsity_to_pred phi).\n\n  Lemma sat_bot_False {ff:falsity_flag} rho phi : sat_bot False rho phi <-> sat rho phi.\n  Proof.\n    induction phi in rho|-*.\n    - easy.\n    - easy.\n    - destruct b0. unfold sat_bot, falsity_to_pred in *. cbn.\n      split; intros H H1 %IHphi1; apply IHphi2; apply H, H1.\n    - destruct q. unfold sat_bot, falsity_to_pred in *. cbn.\n      split; intros H d; apply IHphi, H.\n  Qed.\n\nEnd Bottom.\n\nArguments sat_bot {_} {_} {_} {_} {_} _ _ _.\n\nSection BottomDef.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Context {ff : falsity_flag}.\n\n  Definition exploding D (M : interp D) (F_P:Prop) := forall rho phi, sat_bot F_P rho (⊥ → phi).\n  Arguments exploding _ _ _ : clear implicits.\n  Definition valid_exploding_ctx A phi :=\n    forall D (M : interp D) F_P rho, exploding D M F_P -> (forall psi, psi el A -> sat_bot F_P rho psi) -> sat_bot F_P rho phi.\n\n  Definition valid_exploding_theory (T:theory) phi := \n    forall D (M : interp D) F_P rho, exploding D M F_P ->  (forall psi, T psi -> sat_bot F_P rho psi) -> sat_bot F_P rho phi.\n\n  Definition valid_exploding phi :=\n    forall D (M : interp D) F_P rho, exploding D M F_P -> sat_bot F_P rho phi.\n\n  Definition satis_exploding phi :=\n    exists D (M : interp D) F_P rho, exploding D M F_P /\\ sat_bot F_P rho phi.\n\nEnd BottomDef.\n\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FOL/Semantics/Tarski/FragmentFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7038338941051716}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (x : natural) (lf2 : natural) (y : natural) (lf1 : natural)\n  : natural := plus y (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj206_coqofml_xFmGJ3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.7038255757164714}}
{"text": "Require Import FV.ZFLib.\nRequire Export FV.Tutorial.\n\n(** Your tasks **)\n\n(** Your target is to prove mathematical induction. Please write your own\n    proof. **)\n\nLemma Nat_inductive_base_step:\n  [[ ZF;;\n    is_natural_number N;;\n    ∅ ∈ X;;\n    ∀ n, n ∈ N -> n ∈ X -> n ∪ {n} ∈ X\n  |--\n    ∅ ∈ X ∩ N ]].\nProof.\n  pose proof Intersection_iff.\n  universal instantiation H X N empty_set.\n  The conclusion is already proved.\nQed.\n\nLemma Nat_inductive_inductive_step_X:\n [[ ZF;;\n    is_natural_number N;;\n    ∅ ∈ X;;\n    ∀ n, n ∈ N -> n ∈ X ->n ∪ {n} ∈ X;;\n    y  ∈  X ∩ N \n  |--\n    y ∪ {y} ∈ X]].\nProof.\n  pose proof Intersection_iff.\n  universal instantiation H X N y.\n  assert [[ ZF;; ∀ n, n ∈ N -> n∈X -> n ∪ {n} ∈ X\n    |-- ∀ n, n ∈ N -> n ∈ X ->  n ∪ {n} ∈ X]] by Tauto.\n  universal instantiation H1 y.\n  The conclusion is already proved.\nQed.\n\nLemma Nat_inductive_inductive_step_N:\n  [[ZF;;\n    is_natural_number N;;\n    ∅ ∈ X;;\n    ∀ n, n ∈ N -> n∈ X -> n ∪ {n}∈ X;;\n    y  ∈ X ∩ N \n  |--\n    y ∪ {y} ∈ N]].\nProof.\n  pose proof Intersection_iff.\n  universal instantiation H X N y.\n  assert [[ZF;; is_natural_number N |-- ∀ y, y ∈ N -> y ∪ {y} ∈ N]] by Tauto.\n  universal instantiation H1 y.\n  The conclusion is already proved.\nQed.\n\nLemma Nat_inductive_inductive_step:\n  [[ZF;;\n    is_natural_number N;;\n    ∅ ∈ X;;\n    ∀ n, n ∈ N -> n ∈ X ->n ∪ {n} ∈ X\n     |-- y ∈ X ∩ N ->\n   y ∪ {y}∈ X ∩ N]].\nProof.\n  pose proof Intersection_iff.\n  universal instantiation H X N [[y ∪ {y}]].\n  pose proof Nat_inductive_inductive_step_X.\n  pose proof Nat_inductive_inductive_step_N.\n  The conclusion is already proved.\nQed.\n\nLemma Nat_intersection_inductive:\n    [[ZF;;\n    is_natural_number N;;\n    ∅ ∈ X;;\n    ∀ n, n ∈ N -> n ∈ X -> n ∪ {n}∈ X\n  |-- is_inductive (X ∩ N)]].     \nProof.\n  pose proof Nat_inductive_base_step.\n  pose proof Nat_inductive_inductive_step.\n  universal generalization H0 y.\n  The conclusion is already proved.\nQed.\n\nTheorem mathematical_induction:\n  [[ZF;;\n    is_natural_number N;;\n    ∅ ∈ X;;\n    ∀ n, n ∈ N -> n ∈ X -> n ∪ {n}∈ X\n  |-- ∀ n, n ∈ N -> n ∈ X]].\nProof.\n  pose proof Nat_intersection_inductive.\n  \n  assert ([[ZF;; is_natural_number N \n     |-- ∀ w, is_inductive w -> N ⊆ w]]) by Tauto.\n     \n  universal instantiation H0 [[X∩N]].\n  \n  assert ([[ZF;; is_natural_number N;; is_inductive X ∩ N \n    |-- N ⊆ X ∩ N]]) by Tauto.\n    \n  universal instantiation H2 n.\n  \n  pose proof Intersection_iff.\n  \n  universal instantiation H4 X N n.\n  \n  assert ([[ZF;; is_natural_number N;; ∅ ∈ X;; \n        ∀ n, n ∈ N -> n ∈ X -> n ∪ {n} ∈ X \n        |-- n ∈ N -> n ∈ X ]]) by Tauto.\n  \n  universal generalization H6 n.\n  \n  The conclusion is already proved.\nQed.\n\nLemma induction_intersect:\n  [[ ZF |-- ∀ x, ∀ y, is_inductive(x) -> is_inductive(y) -> is_inductive(x ∩ y)]].\nProof.\n  assert [[ ZF;; is_inductive(x) |-- ∅ ∈ x ]] by Tauto.\n  assert [[ ZF;; is_inductive(y) |-- ∅ ∈ y ]] by Tauto.\n  pose proof Intersection_iff.\n  universal instantiation H1 x y [[∅]].\n  assert [[ ZF;; is_inductive(x);; is_inductive(y) |-- ∅ ∈ x ∩ y ]] by Tauto.\n  assert [[ ZF;; is_inductive(x) |-- ∀ n, n ∈ x -> n ∪ {n} ∈ x ]] by Tauto.\n  assert [[ ZF;; is_inductive(y) |-- ∀ n, n ∈ y -> n ∪ {n} ∈ y ]] by Tauto.\n  universal instantiation H4 n.\n  universal instantiation H5 n.\n  universal instantiation H1 x y n.\n  universal instantiation H1 x y [[ n ∪ {n} ]].\n  assert [[ ZF;; is_inductive(x);; is_inductive(y) |-- n ∈ x ∩ y -> n ∪ {n} ∈ x ∩ y ]] by Tauto.\n  universal generalization H10 n.\n  assert [[ ZF |-- is_inductive(x) -> is_inductive(y) -> is_inductive (x ∩ y) ]] by Tauto.\n  universal generalization H12 x y.\n  The conclusion is already proved.\nQed.", "meta": {"author": "rikosellic", "repo": "ZFC-prover-in-Coq", "sha": "49938756877ad26bcaf73a04592e6f2b0f126b8d", "save_path": "github-repos/coq/rikosellic-ZFC-prover-in-Coq", "path": "github-repos/coq/rikosellic-ZFC-prover-in-Coq/ZFC-prover-in-Coq-49938756877ad26bcaf73a04592e6f2b0f126b8d/MathematicalInduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7038255624923345}}
{"text": "Require Export List.\n \nInductive ltree (A : Set) : Set :=\n  lnode: A -> list (ltree A) ->  ltree A .\n \nSection correct_ltree_ind.\nVariables (A : Set) (P : ltree A ->  Prop) (Q : list (ltree A) ->  Prop).\nHypotheses\n   (H : forall (a : A) (l : list (ltree A)), Q l ->  P (lnode A a l))\n   (H0 : Q nil)\n   (H1 : forall (t : ltree A),\n         P t -> forall (l : list (ltree A)), Q l ->  Q (cons t l)).\n \nFixpoint ltree_ind2 (t : ltree A) : P t :=\n match t as x return P x with\n    lnode a l =>\n      H a l ((fix l_ind (l' : list (ltree A)) : Q l' :=\n                     match l' as x return Q x with\n                        nil => H0\n                       | cons t1 tl => H1 t1 (ltree_ind2 t1) tl (l_ind tl)\n                     end) l)\n end.\n \nEnd correct_ltree_ind.\n \nSection correct_list_ltree_ind.\nVariables (A : Set) (P : ltree A ->  Prop) (Q : list (ltree A) ->  Prop).\nHypotheses\n   (H : forall (a : A) (l : list (ltree A)), Q l ->  P (lnode A a l))\n   (H0 : Q nil)\n   (H1 : forall (t : ltree A),\n         P t -> forall (l : list (ltree A)), Q l ->  Q (cons t l)).\n \nFixpoint list_ltree_ind2 (l : list (ltree A)) : Q l :=\n match l as x return Q x with\n    nil => H0\n   | t :: tl => H1 t (ltree_ind2 A P Q H H0 H1 t) tl (list_ltree_ind2 tl)\n end.\n \nEnd correct_list_ltree_ind.\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/induc-fond/SRC/list_ltree_ind2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7038045850849932}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (z : natural) (x : natural) (lf1 : natural)\n  : natural := mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj75_coqofml_4CojkD.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7037767707386386}}
{"text": "(* Chapter 2 Induction *)\n\n\n\nRequire Export basics.\n\n\n\n(* Naming Cases *)\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 andb_true_elim1 : forall b c : bool,\n                            andb b c = true -> b = true.\nProof.\n  intros b c H.\n  destruct b.\n  Case \"b = true\".\n    reflexivity.\n  Case \"b = false\".\n    rewrite <- H. reflexivity.\nQed.\n\n\n(* Exercise: ** andb_true_elim2 *)\nTheorem andb_true_elim2 : forall b c : bool,\n                            andb b c = true -> c = true.\nProof.\n  intros b c H.\n  destruct c.\n  Case \"c = true\".\n    reflexivity.\n  Case \"c = false\".\n    destruct b.\n    SCase \"b = true\".\n      rewrite <- H. reflexivity.\n    SCase \"b = false\".\n      rewrite <- H. reflexivity.\nQed.\n\n\n\n(* Proof by Induction *)\n\nTheorem plus_0_r_firsttry : forall n : nat,\n                              n + 0 = n.\nProof.\n  intros n.\n  simpl.\nAbort.\n\nTheorem plus_0_r_secondtry : forall n : nat,\n                               n + 0 = n.\nProof.\n  intros n. destruct n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl.\nAbort.\n\n\nTheorem plus_0_r : forall n : nat, n + 0 = n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem minus_diag : forall n, minus n n = 0.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\n\n(* Exercise: ** basic induction *)\n\nTheorem mult_0_r : forall n : nat, n * 0 = 0.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_n_Sm : forall n m : nat, S (n + m) = n + S m.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S n'\".\n    simpl. rewrite IHn'. reflexivity.\nQed.\n\nTheorem plus_comm : forall n m : nat, n + m = m + n.\nProof.\n  intros n m. induction n as [| n'].\n  Case \"n = 0\".\n    rewrite plus_0_r. reflexivity.\n  Case \"n = S n'\".\n    rewrite <- plus_n_Sm. rewrite <- IHn'. reflexivity.\nQed.\n\nTheorem plus_assoc : forall n m p : nat, n + (m + p) = (n + m) + p.\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'. reflexivity.\nQed.\n\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\nTheorem double_plus : forall n, double n = n + n.\nProof.\n  intros n. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S\".\n    simpl. rewrite IHn'. rewrite plus_n_Sm. reflexivity.\nQed.\n\n\n(* Exercise: * destruct induction\n   [destruct] and [induction] both split a value into its separate constructors.\n   Creating subgoals for each constructor.\n   They differ in that [induction] adds an induction hypothesis to the context\n   [destruct] does not add an induction hypothesis.\n *)\n\n\n\n(* Proofs within Proofs *)\n\nTheorem mult_0_plus' : forall n m : nat, (0 + n) * m = n * m.\nProof.\n  intros n m.\n  assert (H: 0 + n = n).\n    Case \"Proof of assertion\". reflexivity.\n  rewrite H. 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  (* need to swap (n + m) with (m + n) *)\n  rewrite plus_comm.\n  (* swapped the *outer* plus: (p+q) + (n+m)... *)\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  Case \"Proof of assertion\".\n    rewrite plus_comm. reflexivity.\n  rewrite H. reflexivity.\nQed.\n\n\n\n(* Exercise: **** mult comm *)\nTheorem plus_swap : forall n m p : nat, n + (m + p) = m + (n + p).\nProof.\n  intros n m p.\n  assert (H: n + m = m + n).\n  Case \"Proof of assertion\".\n    rewrite plus_comm. reflexivity.\n  rewrite plus_assoc. rewrite H. rewrite plus_assoc. reflexivity.\nQed.\n\n\nTheorem mult_plus : forall n m : nat, n * S m = n + (n * m).\nProof.\n  intros n m.\n  induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S\".\n    simpl. rewrite IHn'. rewrite plus_swap. reflexivity.\nQed.\n\nTheorem mult_comm : forall m n : nat, m * n = n * m.\nProof.\n  intros m n. induction m as [| m'].\n  Case \"m = 0\".\n    rewrite mult_0_r. reflexivity.\n  Case \"m = S\".\n    simpl. rewrite mult_plus. rewrite IHm'. reflexivity.\nQed.\n\n\n\n(* More Exercises *)\n\n(* Exercise: *** optional more exercises *)\n\n(* Guess: simplification *)\nTheorem ble_nat_refl : forall n : nat,\n  true = ble_nat n n.\nProof.\n  intros. induction n as [| n'].\n  Case \"n = 0\".\n    reflexivity.\n  Case \"n = S\".\n    rewrite IHn'. reflexivity.\nQed.\n(* Guessed wrong. [ble_nat] is defined as recursive... use induction on that? *)\n\n(* Guess: Even though recursively defined, I'll guess destruct is required *)\nTheorem zero_nbeq_S : forall n : nat,\n  beq_nat 0 (S n) = false.\nProof.\n  reflexivity.\nQed.\n(* Guessed wrong. only needed simpl/reflexivity... *)\n\n(* Guess: simpl/reflexivity *)\nTheorem andb_false_r : forall b : bool,\n  andb b false = false.\nProof.\n  destruct b. reflexivity. reflexivity.\nQed.\n(* Guessed wrong: needed destruct *)\n\n(* Guess: induction required *)\nTheorem plus_ble_compat_l : forall n m p : nat,\n  ble_nat n m = true -> ble_nat (p + n) (p + m) = true.\nProof.\n  intros. induction p as [| n'].\n  Case \"p = 0\".\n    simpl. rewrite H. reflexivity.\n  Case \"P = S\".\n    simpl. rewrite IHn'. reflexivity.\nQed.\n(* Guessed correctly *)\n\n\n(* Guess: simpl/reflexivity. Same as other beq_nat proof. *)\nTheorem S_nbeq_0 : forall n : nat,\n  beq_nat (S n) 0 = false.\nProof.\n  reflexivity.\nQed.\n(* Guessed correct *)\n\n\n(* Guess: induction required *)\nTheorem mult_1_l : forall n : nat, 1 * n = n.\nProof.\n  intros. destruct n. reflexivity.\n  simpl. rewrite plus_0_r. reflexivity.\nQed.\n(* Guessed wrong... dammit *)\n\n(* Guess: destruct required. Bools aren't inductively defined *)\nTheorem all3_spec : forall b c : bool,\n  orb (andb b c)\n      (orb (negb b)\n           (negb c)) = true.\nProof.\n  intros. destruct b.\n  Case \"b = true\".\n    destruct c. reflexivity. reflexivity.\n  Case \"b = false\".\n    reflexivity.\nQed.\n(* Guessed correctly *)\n\n(* Guess: induction required *)\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  Case \"n=0\".\n    reflexivity.\n  Case \"n=S\".\n    simpl. rewrite IHn. rewrite plus_assoc. reflexivity.\nQed.\n(* could this be done without induction? *)\n\n(* Guess: induction *)\nTheorem mult_assoc : forall n m p : nat,\n  n * (m * p) = (n * m) * p.\nProof.\n  intros n m p. induction n.\n  Case \"n=0\".\n    reflexivity.\n  Case \"n=S\".\n    simpl. rewrite IHn. rewrite mult_plus_distr_r. reflexivity.\nQed.\n(* induction it seems *)\n\n\n\n(* Exercise: ** optional beq_nat_refl *)\nTheorem beq_nat_refl : forall n : nat,\n  true = beq_nat n n.\nProof.\n  intros. induction n.\n  Case \"n=0\".\n    reflexivity.\n  Case \"n=S\".\n    simpl. rewrite IHn. reflexivity.\nQed.\n\n\n(* Exercise: ** optional plus_swap' *)\nTheorem plus_swap' : forall n m p : nat,\n  n + (m + p) = m + (n + p).\nProof.\n  intros.\n  rewrite plus_assoc. rewrite plus_assoc.\n  replace (n+m) with (m+n). reflexivity.\n    Case \"Proof of replace\". rewrite plus_comm. reflexivity.\nQed.\n\n\n(* Exerice: *** binary_commute *)\nTheorem bin_unary_comm : forall n : bin,\n  bin_to_nat (increment n) = plus 1 (bin_to_nat n).\nProof.\n  intros. induction n.\n  Case \"n=zero\".\n    reflexivity.\n  Case \"n=Twice\".\n    reflexivity.\n    Case \"n=twicePlus1\".\n    simpl. rewrite IHn. simpl. rewrite <- plus_n_Sm. reflexivity.\nQed.", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.8991213759183765, "lm_q1q2_score": 0.7037085740719223}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) : natural := plus (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj91_coqofml_5pybZB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.70370856178239}}
{"text": "Section Minimal_Logic.\nVariables A B C : Prop.\n\nLemma or_commutative : A \\/ B -> B \\/ A.\n\ntauto.\n\nQed.\n\nPrint or_commutative.\n\nLemma distr_and : A -> B /\\ C -> (A -> B) /\\ (A -> C).\n\ntauto.\n\nQed.\n\n(*Lemma Peirce : ((A -> B) -> A) -> A.\n\ntry tauto.*)\n\n(*tauto.*)\n\n\nLemma NNPeirce : ~ ~ (((A -> B) -> A) -> A).\n\ntauto.\n\nQed.\n\nRequire Import Classical.\n\nCheck NNPP.\n\nLemma Peirce : ((A -> B) -> A) -> A.\n\napply NNPP.\n\ntauto.\n\nQed.\n\nSection club.\n\nVariables Scottish RedSocks WearKilt Married GoOutSunday : Prop.\n\nHypothesis rule1 : ~ Scottish -> RedSocks.\nHypothesis rule2 : WearKilt \\/ ~ RedSocks.\nHypothesis rule3 : Married -> ~ GoOutSunday.\nHypothesis rule4 : GoOutSunday <-> Scottish.\nHypothesis rule5 : WearKilt -> Scottish /\\ Married.\nHypothesis rule6 : Scottish -> WearKilt.\n\nLemma NoMember : False.\n\ntauto.\n\nQed.\n\nEnd club.\n\nCheck NoMember.", "meta": {"author": "kawaharasouta", "repo": "coq_exp", "sha": "aad20566e02cf61344a58d32060c1fcc2370ee4c", "save_path": "github-repos/coq/kawaharasouta-coq_exp", "path": "github-repos/coq/kawaharasouta-coq_exp/coq_exp-aad20566e02cf61344a58d32060c1fcc2370ee4c/coqt1-4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7037085529930718}}
{"text": "From Complexity.NP.SAT Require Export SAT.\nFrom Undecidability.L.Datatypes Require Import LProd LTerm LNat Lists LOptions.\nFrom Undecidability.L.Functions Require Import EqBool.\n\n(** * k-SAT  *)\n(** A CNF is a k-CNF if each of its clauses has exactly k literals. k-SAT is SAT restricted to k-CNFs. *)\n\nInductive kCNF (k : nat) : cnf -> Prop :=\n| kCNFB : kCNF k []\n| kCNFS (N : cnf) (C : clause) : (|C|) = k -> kCNF k N -> kCNF k (C ::  N).               \n\n#[export]\nHint Constructors kCNF : core.\n\nLemma kCNF_clause_length (k : nat) (N : cnf) : kCNF k N <-> forall C, C el N -> |C| =k.\nProof.\n  split. \n  - induction 1. \n    + intros C [].\n    + intros C' [-> | Hel]; [assumption | now apply IHkCNF]. \n  - intros H. induction N; [eauto | ].\n    constructor; [now apply H | apply IHN; eauto].\nQed. \n\nLemma kCNF_app (k : nat) (N1 N2 : cnf) : kCNF k (N1 ++ N2) <-> kCNF k N1 /\\ kCNF k N2. \nProof. \n  induction N1; cbn; split. \n  - eauto.\n  - tauto.\n  - intros H. inv H. apply IHN1 in H3 as (H3 & H4). split; eauto.\n  - intros [H1 H2]. inv H1. constructor; [easy | ]. now apply IHN1. \nQed. \n\nDefinition kSAT (k : nat) (N : cnf) : Prop := k > 0 /\\ kCNF k N /\\ SAT N. \n\n(** boolean decider for kCNF *)\nDefinition clause_length_decb (k : nat) := (fun (C : clause) => Nat.eqb k (|C|)).\nDefinition kCNF_decb (k : nat) (N : cnf) := forallb (clause_length_decb k) N. \n\nLemma kCNF_decb_iff (k : nat) (N : cnf) : kCNF_decb k N = true <-> kCNF k N. \nProof.\n  rewrite kCNF_clause_length. unfold kCNF_decb, clause_length_decb. \n  rewrite forallb_forall. setoid_rewrite Nat.eqb_eq. firstorder.\nQed. \n\n(** extraction of decider *)\nFrom Undecidability.L.Tactics Require Import LTactics GenEncode.\nFrom Complexity.Libs.CookPrelim Require Import PolyBounds. \n\nDefinition c__clauseLengthDecb :=  c__length + 5 + 1.\nDefinition clause_length_decb_time (k : nat) (C : clause) := c__length * (|C|) + eqbTime (X := nat) (size (enc k)) (size (enc (|C|))) + c__clauseLengthDecb.\n#[export]\nInstance term_clause_length_decb : computableTime' clause_length_decb (fun k _ => (1, fun C _ => (clause_length_decb_time k C, tt))). \nProof. \n  extract. solverec. unfold clause_length_decb_time, c__clauseLengthDecb. solverec. \nQed.\n\nDefinition c__kCNFDecb := 3. \nDefinition kCNF_decb_time (k : nat) (N : cnf) := forallb_time (fun C => clause_length_decb_time k C) N + c__kCNFDecb.\n#[export]\nInstance term_kCNF_decb : computableTime' kCNF_decb (fun k _ => (1, fun N _ => (kCNF_decb_time k N, tt))). \nProof. \n  extract. solverec. unfold kCNF_decb_time, c__kCNFDecb. solverec. \nQed.\n\nDefinition c__kCNFDecbBound1 := c__length + c__eqbComp nat.\nDefinition c__kCNFDecbBound2 := c__clauseLengthDecb + c__forallb + c__kCNFDecb.\nDefinition poly__kCNFDecb n := (n + 1) * (c__kCNFDecbBound1 * (n + 1)  + c__kCNFDecbBound2). \nLemma kCNF_decb_time_bound k N : kCNF_decb_time k N <= poly__kCNFDecb (size (enc N) + size (enc k)). \nProof. \n  unfold kCNF_decb_time. rewrite forallb_time_bound_env.\n  2: { \n    split. \n    - intros C n. unfold clause_length_decb_time. \n      rewrite eqbTime_le_r. rewrite list_size_length at 1. rewrite list_size_enc_length. \n      instantiate (1 := encodable_nat_enc).\n      instantiate (1 := fun n => (c__length + c__eqbComp nat) * (n + 1) + c__clauseLengthDecb). \n      cbn -[Nat.add Nat.mul]. solverec. \n    - smpl_inO. \n  } \n  rewrite list_size_length. \n  unfold poly__kCNFDecb, c__kCNFDecbBound1, c__kCNFDecbBound2. lia.\nQed. \nLemma kCNF_decb_poly : monotonic poly__kCNFDecb /\\ inOPoly poly__kCNFDecb. \nProof. \n  unfold poly__kCNFDecb. split; smpl_inO. \nQed. \n", "meta": {"author": "uds-psl", "repo": "coq-library-complexity", "sha": "5a996877f16fd6fe16dc5f0c3b933486957869df", "save_path": "github-repos/coq/uds-psl-coq-library-complexity", "path": "github-repos/coq/uds-psl-coq-library-complexity/coq-library-complexity-5a996877f16fd6fe16dc5f0c3b933486957869df/theories/NP/SAT/kSAT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7036715164271291}}
{"text": "\n\n\n\n(*-------------- Description -----------------------------------------------------\n\n \n Lemma insert_nodup (a:A)(l: list A): NoDup l -> NoDup (insert a l).\n\n\n Lemma list_del_IsOrd (a:A)(l: list A): IsOrd l -> IsOrd (del_all a l).\n Lemma list_del_nodup (a:A)(l: list A): NoDup l -> NoDup (del_all a l).   *)\n\n\nRequire Export Lists.List.\nRequire Export GenReflect SetSpecs DecType.\nRequire Export SetReflect.\n\nSet Implicit Arguments.\n\nSection DecLists.\n\n  Context { A: eqType }.\n\n  Definition empty: list A:= nil.\n  \n  Lemma empty_equal_nil (l: list A): l [=] empty -> l = empty.\n  Proof. { case l.  auto. intros s l0. unfold \"[=]\". intro H. \n           destruct H as [H1 H2]. absurd (In s empty). all: eauto. } Qed.\n\n\n (* -------------- list_insert operation and its properties---------------------------  *)\n  Fixpoint insert (a:A)(l: list A): list A :=\n    match l with\n    |nil => a::nil\n    |a1::l1 => match a == a1 with\n              |true => a1::l1\n              |false => a1:: (insert a l1)\n              end\n    end.\n  (* this function adds an element correctly even in an unsorted list *)\n  Lemma insert_intro1 (a b: A)(l: list A): In a l -> In a ( insert b l).\n  Proof. { intro H. induction l.  inversion H.\n         destruct H.\n         { subst a0. simpl; destruct (b == a); eauto. }\n         { simpl; destruct (b == a0); eauto. } } Qed.\n  \n  Lemma insert_intro2 (a b: A)(l: list A): a=b -> In a (insert b l).\n  Proof. { intro. subst a. induction l.\n         simpl. left;auto. simpl. destruct (b == a) eqn:H. move /eqP in H.\n         subst b; auto. all: auto. } Qed.\n  Lemma insert_intro (a b: A)(l: list A): (a=b \\/ In a l) -> In a (insert b l).\n  Proof. intro H. destruct H.  eapply insert_intro2;auto.  eapply insert_intro1;auto. Qed.\n  Lemma insert_intro3 (a:A)(l: list A): In a (insert a l).\n  Proof. { eapply insert_intro2. auto.  } Qed.\n  Hint Resolve insert_intro insert_intro1 insert_intro2 insert_intro3: core.\n  \n  Lemma insert_not_empty (a: A)(l:list A): insert a l <> (empty).\n  Proof. intro H. absurd (In a empty). simpl; auto. rewrite <- H.\n         eauto.  Qed. \n    \n  Lemma insert_elim (a b: A)(l: list A): In a (insert b l)-> ( a=b \\/ In a l).\n  Proof. { induction l.\n         simpl. left. symmetry. tauto. intro H.\n         simpl in H. destruct (b == a0) eqn: eqH.  \n         right;auto. destruct H. right;subst a0;auto.\n         cut (a=b \\/ In a l). intro H1;destruct H1. left;auto. right; eauto.\n         auto.  } Qed. \n  \n  Lemma insert_elim1 (a b: A)(l: list A): In a (insert b l)-> ~ In a l -> a=b.\n  Proof. { intros H H0.\n         assert (H1: a=b \\/ In a l). eapply insert_elim;eauto.\n         destruct H1. auto. absurd (In a l);auto. } Qed.\n  Lemma  insert_elim2 (a b: A)(l: list A): In a (insert b l)-> a<>b-> In a l.\n  Proof. { intros H H0.\n         assert (H1: a=b \\/ In a l). eapply insert_elim;eauto.\n         destruct H1. absurd (a=b); auto. auto. } Qed.\n  \n  Hint Resolve insert_elim insert_elim1 insert_elim2: core.\n  Lemma insert_iff (a b:A)(l:list A): In a (insert b l) <-> (a=b \\/ In a l).\n  Proof. split; auto. Qed.\n\n  \n  Lemma insert_nodup (a:A)(l: list A): NoDup l -> NoDup (insert a l).\n  Proof. { induction l. simpl. constructor;auto.\n         { intro H. simpl. destruct (a == a0) eqn: eqH.\n           { auto. }\n           { constructor. intro H1.\n           assert (H2: a0 =a \\/ In a0 l); eauto.\n           destruct H2. subst a0. switch_in eqH. apply eqH. eauto. \n           absurd (In a0 l); auto. eauto. } } } Qed.\n  \n  Hint Resolve insert_nodup : core.\n\n    \n  (*------------ list remove operation on ordered list ----------------------------------- *)\n   Fixpoint delete (a:A)(l: list A): list A:=\n    match l with\n    |nil => nil\n    | a1::l1 => match a == a1 with\n               |true => l1\n               |false => a1:: delete a l1\n               end\n    end.\n   (* This function deletes only the first occurence of 'a' from the list l *)\n  \n  Lemma delete_elim1 (a b:A)(l: list A): In a (delete b l)-> In a l.\n  Proof. { induction l. simpl. auto.\n         { simpl. destruct (b == a0) eqn: eqH.\n           { right;auto. }\n           { intro H1. destruct H1. left;auto. right;auto. } } } Qed.\n  \n  Lemma delete_elim2 (a b:A)(l: list A): NoDup l -> In a (delete b l)-> (a<>b).\n  Proof. { induction l. simpl. auto.\n         { simpl. destruct  (b == a0) eqn: eqH.\n           { intros H1 H2. move /eqP in eqH. subst b. intro H3. subst a.\n             absurd (In a0 l); eauto. }\n           { intros H1 H2. destruct H2. intro. subst a0; subst a.\n             switch_in eqH. apply eqH. eauto. eauto. } } } Qed.\n  \n  Lemma delete_intro (a b: A)(l:list A): In a l -> a<>b -> In a (delete b l).\n  Proof. { induction l. simpl.  auto.\n         { simpl. destruct (b == a0) eqn: eqH.\n           { intros H1 H2. destruct H1. move /eqP in eqH. subst a; subst b.\n             absurd (a0=a0); auto. auto. }\n           { intros H1 H2. simpl. destruct H1. left;auto. right;auto. } } } Qed.\n            \n  Hint Resolve delete_elim1 delete_elim2 delete_intro: core.\n  Lemma delete_iff (a b:A)(l: list A): NoDup l -> (In a (delete b l) <-> (In a l /\\ a<>b)).\n  Proof. intro H. split. eauto.\n         intro H0. destruct H0 as [H0 H1]. eauto.  Qed. \n  \n\n   Lemma delete_nodup (a:A)(l: list A): NoDup l -> NoDup (delete a l).\n  Proof.  { induction l. simpl. constructor.\n          { intro H. simpl. destruct (a == a0) eqn: eqH. \n            { eauto. }\n            {  switch_in eqH. constructor. intro H1. absurd (In a0 l). all: eauto. } } } Qed.\n              \n  Hint Resolve delete_nodup: core.\n  \n  \n\n(*--- Index (idx x l) function to locate the first position of the element x in list l ----- *)\nFixpoint idx (x:A)(l: list A):= match l with\n                                |nil => 0\n                                |a::l' => match (x==a) with\n                                        | true => 1\n                                        |false => match (memb x l') with\n                                                 |true => S (idx x l')\n                                                 |false => 0\n                                                 end\n                                         end\n                                end.\nLemma absnt_idx_zero (x:A)(l:list A): ~ In x l -> (idx x l)=0.\nProof. { induction l.\n       { simpl. auto. }\n       { intro H. simpl.\n         replace (x ==a ) with false. replace (memb x l) with false. auto.\n         symmetry;switch; auto.\n         symmetry;switch;move /eqP. intro H1. subst x. auto. } } Qed.\n\nLemma idx_zero_absnt (x:A)(l:list A): (idx x l)=0 -> ~ In x l.\nProof. { induction l.\n         { simpl. auto. }\n         { intros H1 H2. inversion H1.\n           destruct (x==a) eqn:Hxa. inversion H0.\n           destruct (memb x l) eqn: Hxl. move /membP in Hxl.\n           inversion H0. assert (H3: x=a \\/ In x l). auto.\n           destruct H3. subst x. conflict_eq. switch_in Hxl. apply Hxl.\n           apply /membP. auto. } } Qed.\n\nLemma idx_gt_zero (x:A)(l: list A): In x l -> (idx x l) > 0.\nProof. { intro H. assert (H1: idx x l = 0 \\/ ~ idx x l =0). eauto.\n       destruct H1.\n       { absurd (In x l). apply idx_zero_absnt. auto. auto. }\n       { omega. } } Qed.\n\nLemma idx_is_one (a:A)(l: list A): idx a (a::l) = 1.\nProof. simpl. replace (a==a) with true; auto. Qed.\n\nHint Immediate absnt_idx_zero idx_zero_absnt idx_gt_zero idx_is_one: core.\n\nLemma idx_successor (x a:A)(l: list A): In x (a::l)-> x<>a -> idx x (a::l) = S (idx x l).\nProof. { intros H H1. destruct H.\n         { subst a. conflict_eq. }\n         { simpl. replace (x==a) with false. replace (memb x l) with true. all: auto. } } Qed.\n\nLemma nodup_idx_successor(x a: A)(l: list A):In x (a::l)-> NoDup(a::l)-> idx x (a::l)= S(idx x l).\nProof. { intros H H1. destruct H.\n         { subst x. simpl. replace (a==a) with true. replace (idx a l) with 0.\n           auto. symmetry. apply absnt_idx_zero; auto. auto. }\n         { apply idx_successor. auto. intro H2. subst x. absurd (In a l);auto. } } Qed. \n\nLemma diff_index (x y:A)(l: list A): In x l -> In y l -> x<>y -> (idx x l <> idx y l).\nProof. { induction l.\n       { simpl;auto. }\n       { intros Hx Hy Hxy.\n         assert (Hxa: x=a \\/ x<>a); eauto.\n         assert (Hya: y=a \\/ y <> a); eauto.\n         destruct Hxa;destruct Hya.\n         {(* case x=a y=a *)\n           subst x. subst y. contradiction. }\n         { (* case x=a y<> a *) \n           subst x. replace (idx a (a::l)) with 1.\n           destruct Hy. contradiction.\n           assert (H1: idx y l > 0). auto.\n           simpl. replace (y==a) with false. replace (memb y l) with true.\n           intro H2. inversion H2. rewrite <- H4 in H1. inversion H1.\n           auto. symmetry. switch. move /eqP. auto. symmetry;auto. }\n         { (* case x<> a y = a *)\n           subst y. replace (idx a (a::l)) with 1.\n           destruct Hx. subst x. contradiction.\n           assert (H1: idx x l > 0). auto.\n           simpl. replace (x==a) with false. replace (memb x l) with true.\n           intro H2. inversion H2. rewrite H4 in H1. inversion H1.\n           auto. symmetry. switch. move /eqP. auto. symmetry;auto. }\n         { (* case x<>a y <> a *)\n           destruct Hx. symmetry in H1; contradiction.\n           destruct Hy. symmetry in H2;contradiction.\n           replace (idx x (a::l)) with (S (idx x l)).\n           replace (idx y (a::l)) with (S (idx y l)).\n           cut (idx x l <> idx y l). auto.\n           apply IHl;auto. all: symmetry; apply idx_successor;auto. } } } Qed.\n\nLemma same_index (x y:A)(l: list A): In x l -> In y l -> (idx x l = idx y l) -> x=y.\nProof. { intros H H1 H2.\n       assert (H3: x=y \\/ x<>y). eapply reflect_EM;auto.\n       destruct H3. auto.\n       absurd(idx x l = idx y l); auto using diff_index. } Qed.\n\nHint Resolve idx_successor diff_index same_index: core.\n\n\n\n(*----------------- Properties of list cardinality ------------------------------------*)\n\n Lemma delete_size1 (a:A)(l: list A): In a l -> |delete a l| = (|l| - 1).\n   Proof. { induction l.\n          { simpl; auto. }\n          { intro H. simpl.\n            destruct (a==a0) eqn: H1. omega.\n            assert (H2: a<>a0). switch_in H1. auto.\n            assert (H3: In a l). eauto.\n            simpl. replace (|delete a l|) with (|l| - 1).\n            cut (|l| > 0). omega. eauto.  symmetry;auto. } } Qed.\n   \n  Lemma delete_size2 (a:A)(l: list A): ~ In a l -> |delete a l| = |l|.\n  Proof. { induction l.\n         { simpl; auto. }\n         { intros H.\n           assert (H1: a<> a0).\n           { intro H1; subst a. absurd (In a0 (a0::l)); auto. }\n           assert (H2: ~ In a l). auto.\n           simpl. replace (a==a0) with false.\n           simpl. auto. auto. } } Qed.\n  \n  Lemma delete_size (a:A) (l:list A): |delete a l| <=|l|.\n  Proof. { assert (H: In a l \\/ ~ In a l). eauto.\n         destruct H. replace (|delete a l|) with (|l| - 1). omega.\n         symmetry;auto using delete_size1.\n         replace (|delete a l|) with (|l|). auto.\n         symmetry; auto using delete_size2. } Qed.\n\n  Hint Immediate delete_size delete_size1 delete_size2: core.\n\n   \n  Lemma subset_cardinal_le (l s: list A): NoDup l -> l [<=] s -> |l| <= |s|.\n  Proof. { revert s. induction l.\n         { simpl. intros. omega. }\n         { intros s H H1. assert (H2: NoDup l). eauto.\n           assert (H3: ~ In a l). eauto. assert (Has: In a s). auto.\n           assert (H4: l [<=] (delete a s)).\n           { intros x H4. apply delete_intro.\n             auto. intro H5. subst x. contradiction. }\n           simpl. assert (H5: |l| <= | delete a s|).\n           { apply IHl;auto. }\n           replace (|delete a s|) with (|s| -1) in H5. revert H5.\n           cut(|s| > 0). intros. omega. eauto.\n           symmetry. auto using delete_size1. } } Qed.\n           \n  Lemma subset_cardinal_lt (l s: list A)(a: A):\n    NoDup l -> l [<=] s->  In a s -> ~ In a l -> |l| < |s|.\n  Proof. { intros H H1 H2 H3.\n         assert (H4: l [<=] (delete a s)).\n         { intros x H4. apply delete_intro. auto.\n           intro H5. subst x. contradiction. }\n         assert (H5: |l| <= | delete a s|).\n         { auto using subset_cardinal_le. }\n         replace (|delete a s|) with (|s| -1) in H5. revert H5.\n         cut(|s| > 0). intros. omega. eauto.\n         symmetry. auto using delete_size1. } Qed.\n\n  Hint Resolve subset_cardinal_le subset_cardinal_lt: core.\n\nEnd DecLists.\n\n\n\n Hint Resolve insert_intro insert_intro1 insert_intro2 insert_intro3: core.\n Hint Resolve insert_elim insert_elim1 insert_elim2: core.\n Hint Resolve insert_nodup :core.\n\n Hint Resolve delete_elim1 delete_elim2 delete_intro delete_size: core.\n Hint Resolve delete_nodup: core.\n \nHint Immediate absnt_idx_zero idx_zero_absnt idx_gt_zero idx_is_one: core.\nHint Resolve idx_successor diff_index same_index: core.\n\n\n Hint Resolve subset_cardinal_le subset_cardinal_lt: core.\n  ", "meta": {"author": "Abhishek-TIFR", "repo": "List-Set", "sha": "f22e828ca348c8317a5235491e7e1dac848a691f", "save_path": "github-repos/coq/Abhishek-TIFR-List-Set", "path": "github-repos/coq/Abhishek-TIFR-List-Set/List-Set-f22e828ca348c8317a5235491e7e1dac848a691f/DecList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7036715159745446}}
{"text": "(* (c) Copyright Christian Doczkal, Saarland University                   *)\n(* Distributed under the terms of the CeCILL-B license                    *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import all_ssreflect.\nFrom CompDecModal.libs\n Require Import edone bcase fset base modular_hilbert sltype.\nFrom CompDecModal.CTL\n Require Import CTL_def.\n\nSet Default Proof Using \"Type\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** * Hilbert System for CTL *)\n\nModule IC.\nSection Hilbert.\n  Local Notation \"s ---> t\" := (fImp s t).\n\n  Inductive prv : form -> Prop :=\n  | rMP s t : prv (s ---> t) -> prv s -> prv t\n  | axK s t : prv (s ---> t ---> s)\n  | axS s t u : prv ((u ---> s ---> t) ---> (u ---> s) ---> u ---> t)\n  | axDN s : prv (((s ---> fF) ---> fF)  ---> s)\n  | rNec s : prv s -> prv (fAX s)\n  | axN s t : prv (fAX (s ---> t) ---> fAX s ---> fAX t)\n\n  | AU_ind s t u : prv (t ---> u) -> prv (s ---> fAX u ---> u) -> prv ((fAU s t) ---> u)\n  | axAUI s t     : prv (t ---> fAU s t)\n  | axAUf s t     : prv (s ---> fAX (fAU s t) ---> fAU s t)\n\n  | rAR_ind s t u :\n      prv (u ---> t) -> prv (u ---> (s ---> fF) ---> fAX u) -> prv (u ---> fAR s t)\n  | axARE s t    : prv (fAR s t ---> t)\n  | axARu s t    : prv (fAR s t ---> (s ---> fF) ---> fAX (fAR s t))\n\n  | ax_serial : prv (fAX fF ---> fF).\n\n  (** The hilbert system for CTL can be seen as the composition of\n  Hilbert systems for minimal logic (M), classical propositional logic\n  (P), basic modal logic (K) and the rules and axioms specific to CTL *)\n\n  Canonical Structure prv_mSystem := MSystem rMP axK axS.\n  Canonical Structure prv_pSystem := PSystem axDN.\n  Canonical Structure prv_kSystem := KSystem rNec axN.\n  Canonical Structure prv_ctlSystem := CTLSystem AU_ind axAUI axAUf rAR_ind axARE axARu.\n\n  Canonical Structure form_slpType := @SLPType prv_pSystem form_slClass.\n\n  (** ** Soundness *)\n\n  Lemma soundness s : prv s -> forall (M:cmodel) (w:M), eval s w.\n  Proof.\n    elim => {s}; try by [move => /= *; firstorder].\n    - move => /= s M w H. by case: (modelP s w); firstorder.\n    - move => s t u _ /= IH1 _ IH2 M w. elim => {w} - w; first exact: IH1.\n      move => ws H1 H2. exact: IH2.\n    - move => s t M w /=. exact: AU0.\n    - move => s t M w /=. exact: AUs.\n    - move => s t u _ IH1 _ IH2.\n      cofix soundness => /= M w H. case (modelP s w) => Hs.\n      - apply: AR0 Hs _. exact: IH1 H.\n      - apply: ARs. exact: IH1 H. move => v wv. apply: soundness.\n        exact: IH2 wv.\n    - move => s t M w /=. by case.\n    - move => s t M w /=. by case.\n    - move => M w /=. case: (serial w) => v wv. by move/(_ _ wv).\n  Qed.\n\n  Lemma box_request (C : clause) : prv ([af C] ---> AX [af R C]).\n  Proof.\n    rewrite <- bigABBA. apply: bigAI. case => [s [|]]; last by rewrite (negbTE (Rpos _ _)).\n    rewrite RE. exact: bigAE.\n  Qed.\n\nEnd Hilbert.\nEnd IC.\n\n", "meta": {"author": "coq-community", "repo": "comp-dec-modal", "sha": "1113d6c4adb71842e00c9dd83c33bc58d997b7d2", "save_path": "github-repos/coq/coq-community-comp-dec-modal", "path": "github-repos/coq/coq-community-comp-dec-modal/comp-dec-modal-1113d6c4adb71842e00c9dd83c33bc58d997b7d2/theories/CTL/hilbert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7036472544335836}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf1 : natural) (lf2 : natural)\n  : natural := plus z (plus Zero lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj125_coqofml_eR5N2d.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7036322397932037}}
{"text": "Load LFindLoad.\nFrom lfind Require Import LFind.\nUnset Printing Notations.\nSet Printing Implicit.\n\nRequire Import Arith. \nFrom QuickChick Require Import QuickChick.\nInductive natural : Type := Succ : natural -> natural |  Zero : natural.\nDerive Show for natural. Derive Arbitrary for natural.  Instance Dec_Eq_natural : Dec_Eq natural. Proof. dec_eq. Qed.\nInductive lst : Type :=   Nil : lst | Cons : natural -> lst -> lst .\n\nInductive tree : Type := Node : natural -> tree -> tree -> tree |  Leaf : tree.\n\nInductive Pair : Type := mkpair : natural -> natural -> Pair\nwith Zlst : Type := zcons : Pair -> Zlst -> Zlst |  znil : Zlst.\n\nFixpoint append (append_arg0 : lst) (append_arg1 : lst) : lst\n           := match append_arg0, append_arg1 with\n              | Nil, x => x\n              | Cons x y, z => Cons x (append y z)\n              end.\n\nFixpoint rev (rev_arg0 : lst) : lst\n           := match rev_arg0 with\n              | Nil => Nil\n              | Cons x y => append (rev y) (Cons x Nil)\n              end.\n\nFixpoint qreva (qreva_arg0 : lst) (qreva_arg1 : lst) : lst\n           := match qreva_arg0, qreva_arg1 with\n              | Nil, x => x\n              | Cons z x, y => qreva x (Cons z y)\n              end.\n\nLemma append_nil : forall (x : lst), append x Nil = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma append_assoc : forall (x y z : lst), append (append x y) z = append x (append y z).\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. rewrite IHx. reflexivity.\nQed.\n\nLemma rev_append : forall (x y : lst), rev (append x y) = append (rev y) (rev x).\nProof.\n   intros.\n   induction x.\n   - simpl. rewrite append_nil. reflexivity.\n   - simpl. rewrite IHx. rewrite append_assoc. reflexivity.\nQed.\n\nLemma rev_rev : forall (x : lst), rev (rev x) = x.\nProof.\n   intros.\n   induction x.\n   - reflexivity.\n   - simpl. lfind.  simpl.  rewrite IHx.  reflexivity. \nAdmitted.\n\nLemma qreva_rev : forall (x y : lst), qreva x y = append (rev x) y.\nProof.\n   induction x.\n   - reflexivity.\n   - intros. simpl. rewrite IHx. rewrite append_assoc. simpl. reflexivity.\nQed.\n\nTheorem theorem0 : forall (x : lst) (y : lst), eq (qreva (qreva x (rev y)) Nil) (append y x).\nProof.\n   induction x.\n   - intros. simpl. rewrite qreva_rev. rewrite rev_rev. reflexivity.\n   - intros. simpl. \n   rewrite (eq_refl : Cons n (rev y) = append (rev (Cons n Nil)) (rev y)). \n   rewrite <- rev_append. \n   rewrite IHx. \n   rewrite append_assoc. \n   simpl. reflexivity.\nQed.\n              \n\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/clam_lf_goal82_rev_rev_58_rev_append/goal82.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7035011114313972}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(** \n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** The Coq proof assistant and the Mathematical Components library\n\nObjective: learn the Coq system in the MC library\n\n*** Roadmap\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/lesson1.html\">lesson 1</a>#: Functions and computations\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise1.html\">exercise</a> <!-- and <a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise1-solution.html\">solution</a>-->#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/lesson2.html\">lesson 2</a>#: First steps in formal proofs\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise2.html\">exercise</a> <!-- and <a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise2-solution.html\">solution</a>-->#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/lesson3.html\">lesson 3</a>#: A few more steps in formal proofs\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise3.html\">exercise</a> <!-- and <a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise3-solution.html\">solution</a>-->#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/lesson4.html\">lesson 4</a>#: Type theory\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise4.html\">exercise</a> <!-- and <a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise4-solution.html\">solution</a>-->#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/lesson5.html\">lesson 5</a>#: Boolean reflection\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise5.html\">exercise</a> <!-- and <a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise5-solution.html\">solution</a>-->#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/lesson6.html\">lesson 6</a>#: Real proofs, finally!\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise6.html\">exercise</a> <!-- and <a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise6-solution.html\">solution</a>-->#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/lesson7.html\">lesson 7</a>#: Generic theories\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise7.html\">exercise</a> <!-- and <a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise7-solution.html\">solution</a>-->#\n\n- #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/lesson8.html\">lesson 8</a>#: Subtypes\n  - #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise8.html\">exercise</a> <!-- and <a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/exercise8-solution.html\">solution</a>-->#\n\n*** Teaching material\n\n- Slides and exercises\n  #<a href=\"https://www-sop.inria.fr/teams/marelle/coq-18/\">https://www-sop.inria.fr/teams/marelle/coq-18/</a>#\n- Coq (#<a href=\"https://coq.inria.fr/download\">software</a>#\n  and #<a href=\"https://coq.inria.fr/distrib/current/refman/\">user manual</a>#, in particular the chapter about #<a href=\"https://coq.inria.fr/distrib/current/refman/proof-engine/ssreflect-proof-language.html\">SSReflect</a>#)\n- Mathematical Components\n  (#<a href=\"http://math-comp.github.io/math-comp/\">software</a># and\n  #<a href=\"https://math-comp.github.io/mcb/\">book</a>#)\n\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\nYou don't need to install Coq in order to follow this\nclass, you just need a recent browser thanks to\n#<a href=\"https://github.com/ejgallego/jscoq\">jsCoq</a>#.\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 1: summary\n\n- functions\n- simple data\n- containers\n- symbolic computations\n- higher order functions and mathematical notations\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Functions\n\nFunctions are built using the [fun .. => ..] syntax.\nThe command [Check] verifies that a term is well typed.\n\n#<div>#\n*)\nCheck (fun n => 1 + n + 1).\n(**\n#</div>#\n\nNotice that the type of [n] was inferred and that\nthe whole term has type [nat -> nat], where [->]\nis the function space.\n\nFunction application is written by writing the function\non the left of the argument (eg, not as in the mathematical\npractice).\n\n#<div>#\n*)\nCheck 2.\nCheck (fun n => 1 + n + 1) 2.\n(**\n#</div>#\n\nNotice how [2] has a type that fits, and hence\nthe type of the function applied to [2] is [nat].\n\nTerms (hence functions) can be given a name using\nthe [Definition] command. The command offers some\nsyntactic sugar for binding the function arguments.\n\n#<div>#\n*)\nDefinition f := (fun n => 1 + n + 1).\n(* Definition f n := 1 + n + 1. *)\n(* Definition f (n : nat) := 1 + n + 1. *)\n(**\n#</div>#\n\nNamed terms can be printed.\n\n#<div>#\n*)\nPrint f.\n(**\n#</div>#\n\nCoq is able to compute with terms, in particular\none can obtain the normal form via the [Eval lazy in]\ncommand.\n\n#<div>#\n*)\nEval lazy in f 2.\n(**\n#</div>#\n\nNotice that \"computation\" is made of many steps.\nIn particular [f] has to be unfolded (delta step)\nand then the variable substituted for the argument\n(beta).\n\n#<div>#\n*)\nEval lazy delta [f] in f 2.\nEval lazy delta [f] beta in f 2.\n(**\n#</div>#\n\nNothing but functions (and their types) are built-in in Coq.\nAll the rest is defined, even [1], [2] and [+] are not primitive.\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 1.1 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Data types\n\nData types can be declared using the [Inductive] command.\n\nMany of them are already available in the Coq library called\n[Prelude] that is automatically loaded. We hence just print\nthem.\n\n[Inductive bool := true | false.]\n\n#<div>#\n*)\nPrint bool.\n(**\n#</div>#\n\nThis command declares a new type [bool] and declares\nhow the terms (in normal form) of this type are built.\nOnly [true] and [false] are canonical inhabitants of\n[bool].\n\nTo use a boolean value Coq provides the [if..then..else..]\nsyntax.\n\n#<div>#\n*)\nDefinition twoVtree (b : bool) := if b then 2 else 3.\nEval lazy in twoVtree true.\nEval lazy delta in twoVtree true.\nEval lazy delta beta in twoVtree true.\nEval lazy delta beta iota in twoVtree true.\n(**\n#</div>#\n\nWe define a few boolean operators that will come in handy\nlater on.\n\n#<div>#\n*)\nDefinition andb (b1 b2 : bool) := if b1 then b2 else false.\nDefinition orb (b1 b2 : bool) := if b1 then true else b2.\n\nInfix \"&&\" := andb.\nInfix \"||\" := orb.\n\nCheck true && false || false.\n(**\n#</div>#\n\nThe [Infix] command lets one declare infix notations.\nPrecedence and associativity is already declared in the\nprelude of Coq, here we just associate the constants\n[andb] and [orb] to these notataions.\n\nNatural numbers are defined similarly to booleans:\n\n[Inductive nat := O | S (n : nat).]\n\n#<div>#\n*)\nPrint nat.\n(**\n#</div>#\n\nCoq provides a special notation for literals, eg [3],\nthat is just sugar for [S (S (S O))].\n\nThe Mathematical Components library adds on top of that\nthe postfix [.+1], [.+2], .. for iterated applications\nof [S] to terms other than [O].\n\n#<div>#\n*)\nCheck 3.\nCheck (fun x => (x + x).+2).\nEval lazy in (fun x => (x + x).+2) 1.\n(**\n#</div>#\n\nIn order to use natural numbers Coq provides two\ntools. An extended [if..then..else..] syntax to\nextract the argument of [S] and the [Fixpoint]\ncommand to define recusrsive functions.\n\n#<div>#\n*)\nDefinition pred (n : nat) :=\n  if n is p.+1 then p else 0.\n\nEval lazy in pred 7.\n(**\n#</div>#\n\nNotice that [p] is a binder. When the [if..then..else..]\nis evaluated, and [n] put in normal form, then if it\nis [S t] the variable [p] takes [t] and the then-branch\nis taken.\n\nNow lets define addition using recursion\n\n#<div>#\n*)\nFixpoint addn n m :=\n  if n is p.+1 then (addn p m).+1 else m.\nInfix \"+\" := addn.\nEval lazy in 3 + 2.\n(**\n#</div>#\n\nThe [if..then..else..] syntax is just sugar for\n[match..with..end].\n\n#<div>#\n*)\nPrint addn.\n(**\n#</div>#\n\nLet's now write the equality test for natural numbers\n\n#<div>#\n*)\nFixpoint eqn n m :=\n  match n, m with\n  | 0, 0 => true\n  | p.+1, q.+1 => eqn p q\n  | _, _ => false\n  end.\nInfix \"==\" := eqn.\nEval lazy in 3 == 4.\n(**\n#</div>#\n\nOther examples are subtraction and order\n\n#<div>#\n*)\nFixpoint subn m n : nat :=\n  match m, n with\n  | p.+1, q.+1 => subn p q\n  | _ , _ => m\n  end.\n\nInfix \"-\" := subn.\n\nEval lazy in 3 - 2.\nEval lazy in 2 - 3. (* truncated *)\n\nDefinition leq m n := m - n == 0.\n\nInfix \"<=\" := leq.\n\nEval lazy in 4 <= 5.\n(**\n#</div>#\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nAll the constants defined in this slide are already\ndefined in Coq's prelude or in Mathematical Components.\nThe main difference is that [==] is not specific to\n[nat] but overloaded (it works for most data types).\nThis topic is to be developed in lesson 4.\n\nThis slide corresponds to\nsection 1.2 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Containers\n\nContainers let one aggregate data, for example to form a\npair or a list.  The interesting characteristic of containers\nis that they are polymorphic: the same container can be used\nto hold terms of many types.\n\n[Inductive seq (A : Type) := nil | cons (hd : A) (tl : seq A).]\n\n#<div>#\n*)\nCheck nil.\nCheck cons 3 [::].\n(**\n#</div>#\n\nWe learn that [[::]] is a notation for the empty sequence\nand that the type parameter [?A] is implicit.\n\n#<div>#\n*)\nCheck 1 :: nil.\nCheck [:: 3; 4; 5 ].\n(**\n#</div>#\n\nThe infix [::] notation stands for [cons]. This one is mostly\nused to pattern match a sequence.\n\nThe notation [[:: .. ; .. ]] can be used to form sequences\nby separating the elements with [;]. When there are no elements\nwhat is left is [[::]] that is the empty seqeunce.\n\nAnd of course we can use sequences with other data types\n\n#<div>#\n*)\nCheck [:: 3; 4; 5 ].\nCheck [:: true; false; true ].\n(**\n#</div>#\n\nLet's now define the [size] function.\n\n#<div>#\n*)\nFixpoint size A (s : seq A) :=\n  if s is _ :: tl then (size tl).+1 else 0.\n\nEval lazy in size [:: 1; 8; 34].\n(**\n#</div>#\n\nGiven that the contents of containers are of an\narbitrary type many common operations are parametrized\nby functions that are specific to the type of the\ncontents.\n\n[[\nFixpoint map A B (f : A -> B) s :=\nif s is e :: tl then f e :: map f tl else nil.\n]]\n\n#<div>#\n*)\nDefinition l := [:: 1; 2; 3].\nEval lazy in [seq x.+1 | x <- l].\n(**\n#</div>#\n\nThe #<a href=\"http://math-comp.github.io/math-comp/htmldoc/mathcomp.ssreflect.seq.html\">seq</a>#\nlibrary of Mathematical Components contains many combinators. Their syntax\nis documented in the header of the file.\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 1.3 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Symbols\n\nThe section mecanism is used to describe a context under\nwhich definitions are made. Coq lets us not only define\nterms, but also compute with them in that context.\n\nWe use this mecanism to talk about symbolic computation.\n\n#<div>#\n*)\nSection symbols.\nVariables v : nat.\n\nEval lazy in pred v.+1 .\nEval lazy in pred v .\n(**\n#</div>#\n\nComputation can take place in presence of variables\nas long as constructors can be consumed. When no\nmore constructors are available computation is\nstuck.\n\nLet's not look at a very common higher order\nfunction.\n\n#<div>#\n*)\n\nFixpoint foldr A T f (a : A) (s : seq T) :=\n  if s is x :: xs then f x (foldr f a xs) else a.\n(**\n#</div>#\n\nThe best way to understand what [foldr] does \nis to postulate a variable [f] and compute. \n\n#<div>#\n*)\n\nVariable f : nat -> nat -> nat.\n\nEval lazy in foldr f    3 [:: 1; 2 ].\n\n(**\n#</div>#\n\nIf we plug [addn] in place of [f] we\nobtain a term that evaluates to a number.\n\n#<div>#\n*)\n\nEval lazy in foldr addn 3 [:: 1; 2 ].\n\nEnd symbols.\n\n(**\n#</div>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsections 1.4 and 1.5 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Higher order functions and mathematical notations\n\nLet's try to write this formula in Coq\n\n#$$ \\sum_{i=1}^n (i * 2 - 1) = n ^ 2 $$#\n\nWe need a bit of infrastruture\n\n#<div>#\n*)\nFixpoint iota m n := if n is u.+1 then m :: iota m.+1 u else [::].\n\nEval lazy in iota 0 5.\n\n(**\n#</div>#\n\nCombining [iota] and [foldr] we can get pretty\nclose to the LaTeX source for the formula above.\n\n#<div>#\n*)\n\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (foldr (fun i a => F + a) 0 (iota m (n-m))).\n\nCheck \\sum_(1 <= x < 5) (x * 2 - 1).\nEval lazy in \\sum_(1 <= x < 5) (x * 2 - 1).\n(**\n#</div>#\n\n#<p><br/><p>#\n\n#<div class=\"note\">(notes)<div class=\"note-text\">#\n\nThis slide corresponds to\nsection 1.6 of\n#<a href=\"https://math-comp.github.io/mcb/\">the Mathematical Components book</a>#\n#</div></div>#\n\n#</div>#\n\n----------------------------------------------------------\n#<div class=\"slide\">#\n** Lesson 1: sum up\n\n- [fun .. => ..]\n- [Check]\n- [Definition]\n- [Print]\n- [Eval lazy]\n- [Inductive] declarations [bool], [nat], [seq].\n- [match .. with .. end] and [if .. is .. then .. else ..]\n- [Fixpoint]\n- [andb] [orb] [eqn] [leq] [addn] [subn] [size] [foldr]\n\n#</div>#\n\n\n*)\n", "meta": {"author": "gares", "repo": "COQWS18", "sha": "2d438b94357d4be0baf47808db111214f08db467", "save_path": "github-repos/coq/gares-COQWS18", "path": "github-repos/coq/gares-COQWS18/COQWS18-2d438b94357d4be0baf47808db111214f08db467/lesson1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7035011102114415}}
{"text": "From mathcomp Require Import all_ssreflect ssralg matrix ssrnum vector reals normedtype order boolp classical_sets.\nRequire Import counterclockwise.\n\n(******************************************************************************)\n(*       a <| t |> b := t *: a + (1 - t) *: b where a,b : lmodType R          *)\n(*                      for instance, a <| 0 |> b = b, etc.                   *)\n(*     between x y z := x \\in [y,z]                                           *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing Num.Theory Order.POrderTheory Order.TotalTheory.\n\nLocal Open Scope order_scope.\nLocal Open Scope ring_scope.\n\nSection In01.\nVariable R : realType.\n\nDefinition in01 (t : R) := 0 <= t <= 1.\n\nLemma in010 : in01 0.\nProof. by rewrite/in01 lexx ler01. Qed.\n\nLemma in011 : in01 1.\nProof. by rewrite/in01 lexx ler01. Qed.\n\nLemma in01_ge0 t : in01 t -> 0 <= t.\nProof. by move=>/andP[]. Qed.\n\nLemma in01M_ge0 (t : R) : in01 t = (0 <= t * (1-t)).\nProof.\napply/idP/idP.\n   by move=>/andP[t0 t1]; apply mulr_ge0=>//; rewrite subr_ge0.\nmove=>ge0; apply/andP; split; rewrite leNgt; apply/negP=>ti; move:ge0.\n   by rewrite nmulr_rge0// subr_le0=>t1; move:(lt_trans ltr01 (le_lt_trans t1 ti)); rewrite ltxx.\nby move:(ti); rewrite -subr_lt0=>t1'; rewrite nmulr_lge0// =>t0; move:(lt_trans (le_lt_trans t0 ltr01) ti); rewrite ltxx.\nQed.\n\nLemma in01_onem t : in01 t = in01 (1 - t).\nProof. by rewrite 2!in01M_ge0 opprB addrCA subrr addr0 mulrC. Qed.\n\nLemma in01M t u : in01 t -> in01 u -> in01 (t * u).\nProof.\nmove=>/andP[t0 t1]/andP[u0 u1]; apply/andP; split; first by apply mulr_ge0.\nby apply mulr_ile1.\nQed.\n\nLemma in01M1 t u : in01 t -> in01 u -> (t * u == 1) = (t == 1) && (u == 1).\nProof.\nmove=>/andP[t0 t1]/andP[u0 u1].\napply/idP/idP; last by move=>/andP[/eqP-> /eqP->]; rewrite mulr1.\ncase tn1: (t == 1); first by move:tn1=>/eqP->; rewrite mul1r.\ncase un1: (u == 1); first by move:un1=>/eqP->; rewrite mulr1 tn1.\nmove=>/eqP tu1/=.\nsuff: t * u < 1 by rewrite tu1 ltxx.\nby apply mulr_ilt1=>//; rewrite -subr_gt0 lt0r subr_eq0 subr_ge0 eq_sym ?t1 ?u1 ?tn1 ?un1.\nQed.\n\nLemma in01_convA t u : in01 t -> in01 u -> in01 (t / (1-(1-t)*(1-u))).\nProof.\nmove=> t01 u01.\nhave c0 : 0 <= 1 - (1 - t) * (1 - u).\n  by move:t01 u01; rewrite in01_onem=>t01; rewrite in01_onem=>/(in01M t01); rewrite in01_onem=>/andP[].\napply/andP; split.\n   by apply divr_ge0=>//; move:t01=>/andP[].\nhave [->|e0] := eqVneq (1 - (1 - t) * (1 - u)) 0; first by rewrite invr0 mulr0; exact ler01.\nrewrite -{4}(divff e0).\nrewrite ler_wpmul2r ?invr_ge0//.\nrewrite mulrBr mulr1 mulrBl -addrA opprD addrA subrr add0r opprB opprK -mulrBl -subr_ge0 -addrA subrr addr0; apply mulr_ge0; last by move:u01=>/andP[].\nby move:t01; rewrite in01_onem=>/andP[].\nQed.\n\nEnd In01.\n\nSection Conv.\nVariable R : realType.\nVariable E : lmodType R.\n\nDefinition conv (t : R) (a b : E) := t *: a + (1 - t) *: b.\n\nEnd Conv.\n\n(* NB(rei): same notation as infotheo *)\nReserved Notation \"x <| p |> y\" (format \"x  <| p |>  y\", at level 49).\nNotation \"a <| p |> b\" := (conv p a b). (* TODO(rei): needs scope *)\n\nSection Conv.\nVariable R : realType.\nVariable E : lmodType R.\nImplicit Types (t u v : R) (a b c d : E).\n\nLemma conv0 a b : a <| 0 |> b = b.\nProof. by rewrite/conv scale0r add0r subr0 scale1r. Qed.\n\nLemma conv1 a b : a <| 1 |> b = a.\nProof. by rewrite/conv scale1r subrr scale0r addr0. Qed.\n\nLemma convmm t a : a <| t |> a = a.\nProof. by rewrite/conv -scalerDl addrCA subrr addr0 scale1r. Qed.\n\nLemma convC t a b : a <| t |> b = b <| 1 - t |> a.\nProof. by rewrite/conv opprB addrCA subrr addr0 addrC. Qed.\n\nLemma convlr t a b : a <| t |> b = a + (1 - t) *: (b-a).\nProof. by rewrite scalerDr scalerN addrCA -{2}[a]scale1r -scalerBl opprB addrCA subrr addr0 addrC. Qed.\n\nLemma convrl t a b : a <| t |> b = b + t *: (a - b).\nProof. by rewrite convC convlr opprB addrCA subrr addr0. Qed.\n\nEnd Conv.\n\nSection Conv.\nVariable R : realType.\nVariable E : lmodType R.\nImplicit Types (t u v : R) (a b c d : E).\n\nLemma convA t u a b c : in01 t -> in01 u ->\n  a <| t |> (b <| u |> c) =\n  (a <| t / ((1 : R^o) <| t |> u) |> b) <| (1 : R^o) <| t |> u |> c.\nProof.\nmove=> t01 u01.\nhave -> : (1 : R^o) <| t |> u = 1 - (1 - t) * (1 - u).\n  by rewrite (convlr _ (1 : R^o)) -[u-1]opprB scalerN.\nrewrite/conv scalerDr addrA 2!scalerA opprB addrCA subrr addr0; congr add.\nhave [/eqP|tu1] := eqVneq (1 - (1 - t) * (1 - u)) 0.\n  rewrite {1}subr_eq0 eq_sym in01M1 -?in01_onem// -2![_-_ == 1]subr_eq0.\n  rewrite 2![1-_-1]addrAC subrr 2!add0r 2!oppr_eq0=>/andP[/eqP-> /eqP->].\n  by rewrite mulr0 subr0 mulr1 subrr 3!scale0r addr0.\nrewrite scalerDr 2!scalerA [(1-_*_)*(1-_)]mulrBr mulrCA divff// 2!mulr1 mulrBr.\nby rewrite mulr1 addrAC opprB addrCA subrr addr0.\nQed.\n\nLemma convA' t u a b c : in01 t -> in01 u ->\n  (a <| u |> b) <| t |> c =\n  a <| t * u |> (b <| t * (1 - u) / ((1 - u : R^o) <| t |> 1) |> c).\nProof.\nmove=>t01 u01.\nrewrite convC (convC u) convA.\n   2, 3: by rewrite -in01_onem.\nrewrite -convC convC (convC _ c).\nhave -> : (1 - u : R^o) <| t |> 1 = 1 - t * u.\n  by rewrite (convrl _ _ 1) addrAC subrr add0r scalerN.\nrewrite opprB addrCA subrr addr0.\nhave [/eqP|tu1] := eqVneq (1 - t * u) 0.\n    by rewrite subr_eq0 eq_sym in01M1// =>/andP[/eqP-> /eqP->]; rewrite 2!mul1r 2!conv1.\ncongr (_ <| _ |> (_ <| _ |> _)).\nby apply (mulfI tu1); rewrite mulrBr mulr1 2![(1-t*u)*(_/_)]mulrCA divff// 2!mulr1 opprB addrCA addrAC subrr add0r mulrBr mulr1.\nQed.\n\nLemma in01_conv (t u v : R) : in01 t -> in01 u -> in01 v ->\n  in01 ((u : R^o) <| t |> v).\nProof.\nmove=>/andP[t0 t1] /andP[u0 u1] /andP[v0 v1]; apply/andP; split.\n   apply addr_ge0; apply mulr_ge0=>//.\n   by rewrite subr_ge0.\nhave<-: t + (1-t) = 1 by rewrite addrCA subrr addr0.\napply ler_add; rewrite -subr_ge0.\n   rewrite -{1}[t]mulr1 -mulrBr; apply mulr_ge0=>//.\n   by rewrite subr_ge0.\nby rewrite -{1}[1-t]mulr1 -mulrBr; apply mulr_ge0; rewrite subr_ge0.\nQed.\n\nLemma in01_convl (t u : R) : 0 <= t*u -> in01 (t / (t+u)).\nProof.\nhave H: forall a b : R, 0 <= a*b -> 0 <= a/(a+b) by move=>a b ab0; rewrite -sgr_ge0 sgrM sgrV -sgrM sgr_ge0 mulrDr -expr2; apply addr_ge0=>//; apply sqr_ge0.\nmove=>tu0.\nhave [->|tun0] := eqVneq (t + u) 0.\n   by rewrite invr0 mulr0; apply in010.\napply/andP; split; first by apply H.\nrewrite -{1}[t](addr0) -(subrr u) addrA mulrBl divff// -subr_ge0 opprB addrCA subrr addr0 addrC; apply H.\nby rewrite mulrC.\nQed.\n\nLemma conv_onem (t u v : R) :\n  (1-u : R^o) <| t |> (1-v) =\n  1 - (u : R^o) <| t |> v.\nProof.\nrewrite/conv 2!scalerBr addrACA opprD; congr add.\nhave sm: forall u, u *: (1 : R^o) = u*1 by [].\nby rewrite 2!sm 2!mulr1 addrCA subrr addr0.\nQed.\n\nLemma convACA (t u v : R) (a b c d : E) : in01 t -> in01 u -> in01 v ->\n  (a <| u |> b) <| t |> (c <| v |> d) =\n  (a <| t * u / ((u : R^o) <| t |> v) |> c)\n    <| (u : R^o) <| t |> v |>\n  (b <| t * (1 - u) / ((1 - u : R^o) <| t |> (1 - v)) |> d).\nProof.\nmove=>/andP[t0 t1]/andP[u0 u1]/andP[v0 v1].\nmove:t0; rewrite le0r => /orP[|].\n   by move=>/eqP->; rewrite !mul0r !conv0.\nmove=>t0; move:t1; rewrite -subr_ge0 le0r => /orP[|].\n   rewrite subr_eq0=>/eqP<-; rewrite !mul1r !conv1.\n   move:u0; rewrite le0r => /orP[|].\n      by move=>/eqP->; rewrite subr0 !conv0 divff ?oner_neq0// conv1.\n   rewrite lt0r=>/andP[u0 _]; rewrite divff// conv1.\n   move:u1; rewrite -subr_ge0 le0r => /orP[|].\n      by rewrite subr_eq0=>/eqP<-; rewrite 2!conv1.\n   by rewrite lt0r=>/andP[t1 _]; rewrite divff// conv1.\nmove=>t1.\nhave c0: forall x y : R, 0 <= x -> 0 <= y -> (x : R^o) <| t |> y = 0 -> x = 0 /\\ y = 0.\n   move=>x y; rewrite le0r => /orP[|].\n      move=>/eqP-> _ /eqP.\n      rewrite/conv scaler0 add0r mulf_eq0 => /orP[|].\n         by move=>t1'; move:t1; rewrite lt0r=>/andP[/negPf]; rewrite t1'.\n      by move=>/eqP->.\n   move=>x0 y0 c0.\n   suff: 0 < (x : R^o) <| t |> y by rewrite c0 ltxx.\n   rewrite /conv -(addr0 0) ; apply ltr_le_add.\n      by apply mulr_gt0.\n   by apply mulr_ge0=>//; apply ltW.\nhave [|uv0] := eqVneq ((u : R^o) <| t |> v) 0.\n   by move=>/(c0 _ _ u0 v0) [-> ->]; rewrite convmm !conv0 subr0 convmm -mulrA divff ?oner_neq0// mulr1.\nmove:u1 v1; rewrite -2![_ <= 1]subr_ge0=>u1 v1.\nhave [|uv0'] := eqVneq ((1 - u : R^o) <| t |> (1 -v)) 0.\n    by move=> /(c0 _ _ u1 v1)[/eqP]; rewrite subr_eq0=>/eqP<- /eqP; rewrite subr_eq0=>/eqP<-; rewrite convmm !conv1 -mulrA divff ?oner_neq0// mulr1.\nrewrite{1 2 3 4 6 8}/conv 4!scalerDr 2!addrA !scalerA -conv_onem.\nrewrite 2![((_ : R^o) <| _ |> _) * (1 - _)]mulrBr 2![_ * (_ * _ / _)]mulrC -!mulrA 2![_^-1 * _]mulrC divff// divff// !mulr1 /conv [t *: _ + _ + _]addrAC subrr add0r [t *: _ + _ + _]addrAC subrr add0r; congr add.\nby rewrite -2!addrA; congr add; rewrite addrC.\nQed.\nEnd Conv.\n\nSection between.\nVariable R : realType.\nLet Plane := pair_vectType (regular_vectType R) (regular_vectType R).\n\nLemma det_conv (p p' q r : Plane) (t : R) :\n  det (p <| t |> p') q r = (det p q r : R^o) <| t |> det p' q r.\nProof.\nhave sm t' u : t' *: (u : R^o) = t' * u by [].\nrewrite/conv !sm -det_cyclique -[det p q r]det_cyclique -[det p' q r]det_cyclique 3!det_scalar_productE -2!scalar_productZL -scalar_productDl; congr scalar_product.\nrewrite 2!scalerBr -!addrA; congr GRing.add.\nrewrite !addrA [-_ + _]addrC -addrA; congr GRing.add.\nby rewrite -[-(t*:r)]scaleNr -scalerBl -opprB opprK -addrA [-t+t]addrC subrr addr0 scaleN1r.\nQed.\n\nLemma det0_aligned (p q r: Plane) : det p q r = 0%R <->\n  (p = q \\/ exists t, p <| t |> q = r).\nProof.\nrewrite det_scalar_productE.\nsymmetry; split.\n   case.\n      by move=>->; rewrite subrr -(scaler0 _ 0) scalar_productZL mul0r.\n      by move=> [t <-]; rewrite convlr addrAC subrr add0r rotateZ scalar_productZR scalar_product_rotatexx mulr0.\nwlog: p q r / p == 0%R.\n   move=> h; rewrite -[q-p]subr0 -[r-p]subr0.\n   move=>/(h 0%R (q-p) (r-p) (eqxx 0%R)); case=>[ /eqP | [t] ].\n      by rewrite eq_sym subr_eq0 eq_sym=>/eqP=>pq; left.\n    by rewrite{1}/conv scaler0 add0r=>/(f_equal (fun x=> p+x)); rewrite [r-p]addrC addrA subrr add0r=><-; right; exists t=>//; apply convlr.\nmove=>/eqP p0; subst p; rewrite !subr0/scalar_product/= mulrN=>/eqP; rewrite subr_eq0=>/eqP e.\nhave [q0|q0] := eqVneq q 0%R; first by left.\nright.\nmove:q0; rewrite -pair_eqE /= negb_and => /orP[|] q0.\n   exists (1 - xcoord r / xcoord q)=>//.\n   rewrite -convC convrl add0r subr0; apply /eqP; rewrite -pair_eqE; apply /andP; split=>/=; have ->: forall (a: R) (b: (regular_vectType (Real.ringType R))), a *: b = a*b by lazy.\n   - by rewrite -mulrA [_^-1*_]mulrC divff // mulr1.\n   - by rewrite mulrC mulrA -e mulrC mulrA [_^-1*_]mulrC divff // mul1r.\nexists (1 - ycoord r / ycoord q)=>//.\n   rewrite -convC convrl add0r subr0; apply /eqP; rewrite -pair_eqE; apply /andP; split=>/=; have ->: forall (a: R) (b: regular_vectType (Real.ringType R)), a *: b = a*b by lazy.\n- by rewrite mulrC mulrA e mulrC mulrA [_^-1*_]mulrC divff // mul1r.\n- by rewrite -mulrA [_^-1*_]mulrC divff // mulr1.\nQed.\n\nDefinition between (x y z : Plane) := [&& (det x y z == 0)%R,\n  (0%R <= scalar_product (x - y) (z - y)) ,\n  (0%R <= scalar_product (x - z) (y - z)) &\n  ((y == z) ==> (x == z))].\n\nLemma between_conv x y z : between x y z <->\n  exists t, in01 t && (x == y <| t |> z).\nProof.\ncase yz: (y == z).\n   rewrite/between yz; move:yz=>/eqP yz; rewrite yz subrr -(scale0r 0) scalar_productZR mul0r det_cyclique det_alternate eqxx lexx/=.\n   split; first by move=>/eqP->; exists 0; rewrite in010 convmm/=.\n   by move=>[t /andP[_]]; rewrite convmm.\nrewrite /between yz/= andbT.\nmove:yz=>/negbT yz.\nhave zye: forall t (y z: Plane), t *: y + (1-t) *: z - y = (1-t) *: (z-y).\n   by move=>t y' z'; rewrite {1}[_*:_+_]addrC -addrA scalerBr; congr +%R; rewrite -scaleNr opprB scalerBl scale1r.\nhave yze: forall t (y z: Plane), t *: y + (1-t) *: z - z = t *: (y-z).\n   by move=>t y' z'; rewrite -addrA scalerBr; congr +%R; rewrite scalerBl scale1r [_-_*:_]addrC -addrA subrr addr0.\nsplit.\n   rewrite det_cyclique =>/and3P[/eqP/det0_aligned]; case; first by move=> yz'; move:yz' yz=>->; rewrite eqxx.\n   move=>[t <-].\n   rewrite yze zye 2!scalar_productZL=> yp zp; exists t; apply/andP; split=>//.\n   apply/andP; split.\n      by move:zp; rewrite pmulr_lge0//; apply scalar_productrr_gt0; rewrite subr_eq0.\n    by move:yp; rewrite pmulr_lge0 ?subr_ge0//; apply scalar_productrr_gt0; rewrite subr_eq0 eq_sym.\nmove=>[t] /andP [/andP [t0 t1]] /eqP->.\nrewrite yze zye 2!scalar_productZL; apply/and3P; split.\n- by rewrite det_cyclique; apply/eqP; apply det0_aligned; right; exists t.\n- by rewrite mulr_ge0// ?subr_ge0// scalar_productrr_ge0.\n- by rewrite mulr_ge0// scalar_productrr_ge0.\nQed.\n\nLemma betweenC (a b c : Plane) : between a b c = between a c b.\nProof.\nrewrite /between det_inverse -det_cyclique oppr_eq0; congr andb; rewrite !andbA; congr andb.\n   by apply andbC.\nby rewrite eq_sym; apply implyb_id2l=>/eqP->.\nQed.\n\nLemma betweenl (a b : Plane) : between a a b.\nProof. rewrite/between det_alternate eqxx/= subrr -(scale0r 0) scalar_productZL mul0r lexx/= Bool.implb_same andbT; apply scalar_productrr_ge0. Qed.\n\nLemma betweenr (a b : Plane) : between a b a.\nProof. rewrite betweenC; apply betweenl. Qed.\n\nLemma between_depl (a b c : Plane) : between a b c <->\n  exists (d : Plane) (t u : R),\n    (t*u <= 0) && (b == a + t *: d) && (c == a + u *: d).\nProof.\nsplit.\n   move=>/between_conv[t] /andP[t01].\n   have aconv: a = t *: a + (1-t) *: a by rewrite -scalerDl addrCA subrr addr0 scale1r.\n   rewrite {1}aconv -subr_eq0 opprD addrACA -2!scalerBr.\n   case t1: (t == 1).\n      move:t1=>/eqP->; rewrite subrr scale1r scale0r addr0 subr_eq0=>/eqP->.\n      exists (c-b), 0, 1.\n      by rewrite mul0r lexx scale0r addr0 eqxx scale1r addrCA subrr addr0 eqxx.\n   rewrite addr_eq0 -scalerN opprB=>/eqP e.\n   exists (b-a), 1, (-t / (1-t)).\n   move:t1=>/negbT; rewrite eq_sym -subr_eq0=>tn1.\n   move:t01=>/andP[t0 t1]; rewrite mul1r mulNr oppr_le0 scale1r addrCA subrr addr0 eqxx mulrC scaleNr -scalerN opprB -scalerA e scalerA [_*(1-t)]mulrC divff// scale1r addrCA subrr addr0 eqxx 2!andbT; apply mulr_ge0=>//.\n      by rewrite invr_ge0 subr_ge0.\nmove=>[d][t][u]/andP[/andP[tu0]].\nwlog: d t u tu0 / 0 < t.\n   move=>h.\n   have [t0|t0] := ltP 0 t; first by apply h.\n   move:t0; rewrite le_eqVlt => /orP[|].\n      by move=>/eqP->; rewrite scale0r addr0=>/eqP-> _; apply betweenl.\n   by rewrite -oppr_gt0 -(opprK d) 2![_ *: - - _]scalerN -2!scaleNr; apply h=>//; rewrite mulrN -mulNr opprK.\nmove=>t0 /eqP be /eqP ce.\nmove:tu0; rewrite pmulr_rle0// =>u0.\nhave tugt0: 0 < t-u by rewrite subr_gt0; exact (le_lt_trans u0 t0).\nhave tun0: t-u != 0 by apply/negP=>/eqP tu0; move:tugt0; rewrite tu0 ltxx.\napply/between_conv; exists (-u/(t-u)); apply/andP; split.\n   apply/andP; split.\n      by rewrite mulr_ge0 ?oppr_ge0// invr_ge0 ltW.\n   by rewrite -subr_ge0 -(pmulr_rge0 _ tugt0) mulrBr mulrCA divff// 2!mulr1 -addrA subrr addr0; apply ltW.\nby rewrite/conv be ce 2!scalerDr addrACA -scalerDl [_ + (1-_)]addrCA subrr addr0 scale1r -subr_eq0 opprD addrA subrr add0r oppr_eq0 2!scalerA -scalerDl mulrBl mul1r addrCA -mulrBr mulrAC -mulrA divff// mulr1 subrr scale0r.\nQed.\n\nLemma between_trans (a b c d e : Plane) :\n  between c a b -> between d a b -> between e c d -> between e a b.\nProof.\nmove=>/between_conv[t]/andP[t01 /eqP->] /between_conv[u]/andP[u01 /eqP->] /between_conv[v]/andP[v01 /eqP->].\nrewrite convACA// 2!convmm.\napply between_conv; exists ((t : R^o) <| v |> u); apply/andP; split=>//.\nby apply in01_conv.\nQed.\n\nEnd between.\n", "meta": {"author": "math-comp", "repo": "trajectories", "sha": "cc6e1298208a93592230f5b4ee3228a024aa03e7", "save_path": "github-repos/coq/math-comp-trajectories", "path": "github-repos/coq/math-comp-trajectories/trajectories-cc6e1298208a93592230f5b4ee3228a024aa03e7/theories/conv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.703501109419369}}
{"text": "Require Export Bvector ZArith Zdigits.\nRequire Import Program.Equality Znumtheory.\nRequire Export BDef.\nRequire Import Program.\nRequire Import Coq.micromega.Lia.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(* useful for b2z lemmas in Zbits *)\nLemma bit_value_b2z :\n  forall b, bit_value b = Z.b2z b.\nProof.\n  destruct b; auto.\nQed.\n\nLemma bit_value_eq :\n  forall b1 b2, bit_value b1 = bit_value b2 -> b1 = b2.\nProof.\n  intros.\n  apply Z.b2z_inj.\n  generalize (bit_value_b2z b1) (bit_value_b2z b2).\n  tauto.\nQed.\n\nLemma binary_value_eq :\n  forall n (v1 v2 : Bvector n), binary_value v1 = binary_value v2 -> v1 = v2.\nProof.\n  refine (@Vector.rect2 _ _ _ _ _); auto.\n  intros ? ? ? H b1 b2 IH.\n  repeat rewrite binary_value_Sn in *.\n  assert (v1 = v2).\n  destruct b1, b2; unfold bit_value in *; firstorder.\n  subst v2.\n  rewrite Z.add_cancel_r in *.\n  f_equal.\n  now apply bit_value_eq.\nQed.\n\nLemma binary_value_bound :\n  forall n (v : Bvector n), binary_value v < two_power_nat n.\nProof.\n  induction v as [| b n v' IHv].\n  - firstorder.\n  - rewrite two_power_nat_S.\n    rewrite binary_value_Sn.\n    destruct b; unfold bit_value; lia.\nQed.\n\nLemma binary_value_pos_bound :\n  forall n (v : Bvector n), 0 <= binary_value v < two_power_nat n.\nProof.\n  split.\n  generalize (binary_value_pos n v); firstorder.\n  apply binary_value_bound.\nQed.\n\nLemma two_power_nat_le_mono : forall (a b : nat),\n  (a <= b)%nat -> two_power_nat a <= two_power_nat b.\nProof.\n  intros.\n  repeat rewrite two_power_nat_equiv.\n  apply Z.pow_le_mono_r; lia.\nQed.\n\nLemma binary_value_mod_lt : forall m n (v : Bvector n),\n  (n <= m)% nat ->\n  binary_value v = (binary_value v) mod (two_power_nat m).\nProof.\n  intros.\n  apply eq_sym.\n  apply Zmod_small.\n  pose proof (binary_value_pos_bound v).\n  firstorder.\n  apply Z.lt_le_trans with (m:=two_power_nat n); auto.\n  apply two_power_nat_le_mono.\n  lia.\nQed.\n\nLemma binary_value_mod : forall n (v : Bvector n),\n  binary_value v = (binary_value v) mod (two_power_nat n).\nProof.\n  intros.\n  now apply binary_value_mod_lt.\nQed.\n\n(* signed representation *)\n\nLemma msb_Sn : forall n (v : Bvector (S n)) h,\n  msb (h :: v) = msb v.\nProof.\n  intros.\n  unfold msb, testbit.\n  rewrite binary_value_Sn.\n  rewrite <- (Z.testbit_succ_r (binary_value v) h _); try lia.\n  rewrite bit_value_b2z.\n  f_equal; zify; lia.\nQed.\n\nLemma binary_value_range_msb_0 : forall n (v : Bvector (S n)),\n  msb v = false -> binary_value v < two_power_nat n.\nProof.\n  dependent destruction v.\n  revert h.\n  induction v as [| a n v' IHv]; intros.\n  destruct h; firstorder; inversion H.\n  rewrite msb_Sn, binary_value_Sn, two_power_nat_S in *.\n  generalize (IHv h).\n  destruct h; unfold bit_value; firstorder.\nQed.\n\nLemma binary_value_range_msb_1 : forall n (v : Bvector (S n)),\n  msb v = true -> two_power_nat n <= binary_value v.\nProof.\n  dependent destruction v.\n  revert h.\n  induction v as [| a n v' IHv]; intros.\n  destruct h; firstorder.\n  rewrite msb_Sn, binary_value_Sn, two_power_nat_S in *.\n  destruct h; unfold bit_value; firstorder.\nQed.\n\nLemma two_compl_value_binary_value_msb_0 : forall n (v : Bvector (S n)),\n  msb v = false -> two_compl_value v = binary_value v.\nProof.\n  dependent destruction v.\n  revert h.\n  induction v as [| a n v' IHv]; intros.\n  destruct h; firstorder; inversion H.\n  repeat rewrite two_compl_value_Sn, binary_value_Sn.\n  rewrite msb_Sn in *.\n  generalize (IHv a).\n  destruct h; unfold bit_value; firstorder.\nQed.\n\nLemma two_compl_value_binary_value_msb_1 : forall n (v : Bvector (S n)),\n  msb v = true -> two_compl_value v = binary_value v - two_power_nat (S n).\nProof.\n  dependent destruction v.\n  revert h.\n  induction v as [| a n v' IHv]; intros.\n  destruct h; firstorder; inversion H.\n  rewrite msb_Sn in *.\n  generalize (IHv a).\n  repeat rewrite binary_value_Sn.\n  repeat rewrite two_power_nat_S.\n  rewrite two_compl_value_Sn.\n  destruct h; unfold bit_value; firstorder.\nQed.\n\nLemma two_compl_value_range_msb_0 : forall n (v : Bvector (S n)),\n  msb v = false -> 0 <= two_compl_value v < two_power_nat n.\nProof.\n  intros.\n  generalize (two_compl_value_binary_value_msb_0 v).\n  generalize (binary_value_range_msb_0 v).\n  generalize (binary_value_pos_bound v).\n  rewrite two_power_nat_S.\n  firstorder.\nQed.\n\nLemma two_compl_value_range_msb_1 : forall n (v : Bvector (S n)),\n  msb v = true -> - (two_power_nat n) <= two_compl_value v < 0.\nProof.\n  intros.\n  generalize (two_compl_value_binary_value_msb_1 v).\n  generalize (binary_value_range_msb_1 v).\n  generalize (binary_value_pos_bound v).\n  rewrite two_power_nat_S.\n  firstorder.\nQed.\n\nLemma two_compl_value_range : forall n (v : Bvector (S n)),\n  - (two_power_nat n) <= two_compl_value v < two_power_nat n.\nProof.\n  intros.\n  destruct (sumbool_of_bool (msb v));\n  generalize (two_compl_value_range_msb_0 v);\n  generalize (two_compl_value_range_msb_1 v);\n  firstorder.\nQed.\n\nLemma Zmod_add :\n  forall a b c : Z, (a + b * c) mod c = a mod c.\nProof.\n  intros.\n  destruct (Z.eq_dec c 0).\n  - f_equal.\n    subst.\n    lia.\n  - now apply Z.mod_add.\nQed.\n\nLemma two_compl_value_mod : forall n (v : Bvector (S n)),\n  binary_value v = (two_compl_value v) mod (two_power_nat (S n)).\nProof.\n  intros.\n  destruct (sumbool_of_bool (msb v)).\n  - rewrite two_compl_value_binary_value_msb_1; auto.\n    rewrite <- Z.add_opp_r.\n    rewrite (Zmod_add _ (-1) _).\n    apply binary_value_mod.\n  - rewrite two_compl_value_binary_value_msb_0; auto.\n    apply binary_value_mod.\nQed.\n\nLemma two_compl_value_binary_value_eqm : forall n (v : Bvector (S n)),\n  eqm (two_power_nat (S n)) (two_compl_value v) (binary_value v).\nProof.\n  intros.\n  unfold eqm.\n  rewrite <- two_compl_value_mod.\n  apply binary_value_mod.\nQed.\n\nLemma Z_to_binary_mod :\n  forall (n:nat) (z:Z),\n  Z_to_binary n z = Z_to_binary n (z mod two_power_nat n).\nProof.\n  induction n as [| n IHn]; simpl; auto.\n  intros.\n  (* normalize *)\n  rewrite two_power_nat_equiv in *.\n  repeat rewrite Z.div2_div.\n  f_equal.\n  - repeat rewrite <- Z.bit0_odd.\n    rewrite Z.mod_pow2_bits_low; firstorder.\n  - rewrite IHn.\n    f_equal.\n    apply Z.bits_inj'.\n    unfold Z.eqf; intros i Hi.\n    rewrite Z.div2_bits; auto.\n    (* high bits are all 0s *)\n    destruct (Z.lt_ge_cases i (Z.of_nat n)).\n    + repeat rewrite Z.mod_pow2_bits_low; zify; firstorder.\n      apply Z.div2_bits; auto.\n    + repeat rewrite Z.mod_pow2_bits_high; zify; firstorder.\nQed.\n\nLemma Z_to_binary_to_Z_mod :\n  forall n z, binary_value (Z_to_binary n z) = z mod two_power_nat n.\nProof.\n  intros.\n  rewrite Z_to_binary_mod.\n  apply Z_to_binary_to_Z; generalize (Z_mod_lt z (two_power_nat n)); firstorder.\nQed.\n\nLemma Z_to_binary_eqm :\n  forall n x y, eqm (two_power_nat n) x y <-> Z_to_binary n x =  Z_to_binary n y.\nProof.\n  split; intros H.\n  - rewrite Z_to_binary_mod.\n    rewrite H.\n    rewrite <- Z_to_binary_mod.\n    trivial.\n  - assert (binary_value (Z_to_binary n x) = binary_value (Z_to_binary n y)).\n    congruence.\n    now repeat rewrite Z_to_binary_to_Z_mod in *.\nQed.\n\n(* another redundant function *)\nLemma Zmod2_div2 : forall z,\n  Zmod2 z = Z.div2 z.\nProof.\n  intros.\n  destruct z; try (destruct p); auto.\n  destruct p; auto.\nQed.\n\n(* the two Z->Bvector conversions are equivalent *)\nLemma Z_to_two_compl_Z_to_binary : forall n z,\n  Z_to_two_compl n z = Z_to_binary (S n) z.\nProof.\n  induction n; intros.\n  destruct z; auto.\n  rewrite Z_to_two_compl_Sn_z.\n  rewrite Z_to_binary_Sn_z.\n  rewrite Zmod2_div2.\n  rewrite IHn.\n  auto.\nQed.\n\n(* easier to use than two_compl_to_Z_to_two_compl *)\nLemma two_compl_to_Z_to_binary : forall n (v : Bvector (S n)),\n  Z_to_binary (S n) (two_compl_value v) = v.\nProof.\n  dependent destruction v.\n  rewrite <- Z_to_two_compl_Z_to_binary.\n  apply two_compl_to_Z_to_two_compl.\nQed.\n\n(* Lemma two_compl_to_Z_to_binary_gt : forall m n (v : Bvector (S n)), *)\n(*   (n <= m)%nat ->  *)\n(*   Z_to_binary (S m) (two_compl_value v) = zero_cast (S m) v. *)\n(* Proof. *)\n(*   intros. *)\n(*   dependent destruction v. *)\n(*   rewrite <- Z_to_two_compl_Z_to_binary. *)\n(*   pose proof two_compl_to_Z_to_two_compl. *)\n(*   unfold zero_cast. *)\n(*   rewrite binary_to_Z_to_binary. *)\n\nLemma bv_distr_sub:\n  forall {n : nat} (i1 i2: Bvector n),\n    binary_value i1 >= binary_value i2 ->\n    binary_value (sub i1 i2) =\n    binary_value i1 - binary_value i2.\nProof.\n  unfold sub; intros.\n  pose proof (binary_value_pos_bound i1).\n  pose proof (binary_value_pos_bound i2).\n  rewrite Z_to_binary_to_Z; lia.\nQed.\n\nLemma bv_distr_add:\n  forall {n : nat} (i1 i2: Bvector n),\n    binary_value i1 + binary_value i2 < two_power_nat n ->\n    binary_value (add i1 i2) = binary_value i1 + binary_value i2.\nProof.\n  unfold add; intros.\n  pose proof (binary_value_pos_bound i1).\n  pose proof (binary_value_pos_bound i2).\n  rewrite Z_to_binary_to_Z; lia.\nQed.\n\nLemma bv_distr_mul :\n  forall {n : nat} (i1 i2 : Bvector n),\n    0 <= binary_value i1 * binary_value i2 < two_power_nat n ->\n    binary_value (mul i1 i2) = binary_value i1 * binary_value i2.\nProof.\n  unfold mul; intros.\n  pose proof (binary_value_pos_bound i1).\n  pose proof (binary_value_pos_bound i2).\n  rewrite Z_to_binary_to_Z; auto.\n  lia.\n  lia.\nQed.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-aggregation", "sha": "c81681555d63d4a3db225119600833868caf4607", "save_path": "github-repos/coq/DistributedComponents-verdi-aggregation", "path": "github-repos/coq/DistributedComponents-verdi-aggregation/verdi-aggregation-c81681555d63d4a3db225119600833868caf4607/lib/BBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359806, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7035011067063155}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Program.Basics.\n\n(**************)\n(* Categories *)\n(**************)\n\nModule Type Category.\n  Parameter object : Set.\n  Parameter morphism : object -> object -> Set.\n\n  (**\n   * Composition takes two morphisms f : b -> c and g : a -> b. It\n   * returns a morphism from a -> c.\n   * f o g can also be thought of as f after g, following the g morphism\n   * and then the f morphism.\n   *)\n  Parameter compose :\n    forall { a b c },\n    morphism b c ->\n    morphism a b ->\n    morphism a c.\n\n  (**\n   * Composition must be associative.\n   *)\n  Axiom assoc :\n    forall a b c d\n    (f : morphism c d)\n    (g : morphism b c)\n    (h : morphism a b),\n    compose f (compose g h) =\n    compose (compose f g) h.\n\n  (**\n   * Every object must have an identity morphism.\n   *)\n  Axiom ident :\n    forall a,\n    exists (f : morphism a a),\n    forall b (g : morphism a b) (h : morphism b a),\n    compose g f = g /\\\n    compose f h = h.\nEnd Category.\n\n(************)\n(* Functors *)\n(************)\n\nModule Type Functor (C D : Category).\n  Parameter obj : C.object -> D.object.\n  Parameter morph :\n    forall { a b },\n    C.morphism a b -> D.morphism (obj a) (obj b).\n\n  (**\n   * Functors preserve identity morphisms.\n   *)\n  Axiom ident :\n    forall a,\n    exists (f : (C.morphism a a)) (g : D.morphism (obj a) (obj a)),\n    morph f = g.\n\n  (**\n   * Functors preserve composition.\n   *)\n  Axiom composition :\n    forall a b c\n      (f : C.morphism b a)\n      (g : C.morphism c b),\n    morph (C.compose f g) = D.compose (morph f) (morph g).\nEnd Functor.\n\n(* The identity functor is a functor. *)\nModule IdentityFunctor (C : Category) : Functor C C.\n  Definition obj (a : C.object) := a.\n  Definition morph { a b } (f : C.morphism a b) := f.\n\n  Lemma ident :\n    forall a,\n    exists (f : (C.morphism a a)) (g : C.morphism (obj a) (obj a)),\n    morph f = g.\n  Proof.\n    intros.\n    set (H := C.ident a).\n    elim H. intros.\n    exists x.\n    eauto.\n  Qed.\n\n  Lemma composition :\n    forall a b c\n      (f : C.morphism b a)\n      (g : C.morphism c b),\n    morph (C.compose f g) = C.compose (morph f) (morph g).\n  Proof.\n    auto.\n  Qed.\nEnd IdentityFunctor.\n\n(* The composition of two functors is a functor. *)\nModule ComposedFunctors\n  (B C D : Category)\n  (F : Functor C D)\n  (G : Functor B C) : Functor B D.\n  Definition obj := compose F.obj G.obj.\n  Definition morph {a : B.object} {b : B.object}\n    := compose F.morph (@G.morph a b).\n\n  Lemma ident :\n    forall a,\n    exists (f : (B.morphism a a)) (g : D.morphism (obj a) (obj a)),\n    morph f = g.\n  Proof.\n    intros.\n    set (H := G.ident a).\n    elim H. intros.\n    exists x.\n    eauto.\n  Qed.\n\n  Lemma composition :\n    forall a b c\n      (f : B.morphism b a)\n      (g : B.morphism c b),\n    morph (B.compose f g) = D.compose (morph f) (morph g).\n  Proof.\n    intros.\n    unfold morph, compose.\n    replace (G.morph (B.compose f g)) with\n      (C.compose (G.morph f) (G.morph g)).\n    - refine (F.composition _ _ _ _ _).\n    - symmetry.\n      refine (G.composition _ _ _ _ _).\n  Qed.\nEnd ComposedFunctors.\n\n(***************************)\n(* Natural Transformations *)\n(***************************)\n\nModule Type NaturalTransformation (C D : Category) (F G : Functor C D).\n  Parameter fn : forall { a b }, C.object -> D.morphism a b.\n\n  Axiom commute :\n    forall a b (f : C.morphism a b),\n    D.compose (fn b) (F.morph f) =\n    D.compose (G.morph f) (fn a).\nEnd NaturalTransformation.\n\n(*********)\n(* Monad *)\n(*********)\n\nModule Type MonadWrapper (C : Category) (F : Functor C C).\n  (* This structure is necessary because a module cannot be applied to *)\n  (* another module application. *)\n  Module IdFunctor := IdentityFunctor C.\n  Module FSquared := ComposedFunctors C C C F F.\n  Module Type Monad\n    (Eta : NaturalTransformation C C IdFunctor F)\n    (Mu : NaturalTransformation C C FSquared F).\n    Axiom associative :\n      forall x : C.object,\n      @C.compose\n        (F.obj (F.obj (F.obj x)))\n        (F.obj (F.obj x))\n        (F.obj x)\n        (Mu.fn x)\n        (F.morph (Mu.fn x)) =\n      @C.compose\n        (F.obj (F.obj (F.obj x)))\n        (F.obj (F.obj x))\n        (F.obj x)\n        (Mu.fn x)\n        (Mu.fn (F.obj x)).\n\n    Axiom identity :\n      forall (x : C.object),\n      @C.compose\n        (F.obj x)\n        (F.obj (F.obj x))\n        (F.obj x)\n        (Mu.fn x)\n        (Eta.fn (F.obj x)) =\n      @C.compose\n        (F.obj x)\n        (F.obj (F.obj x))\n        (F.obj x)\n        (Mu.fn x)\n        (F.morph (Eta.fn x)).\n  End Monad.\nEnd MonadWrapper.\n", "meta": {"author": "etawang", "repo": "coq-practice", "sha": "89af7aec8422f200d868f14ee4d60de3030d4bbc", "save_path": "github-repos/coq/etawang-coq-practice", "path": "github-repos/coq/etawang-coq-practice/coq-practice-89af7aec8422f200d868f14ee4d60de3030d4bbc/category-theory/definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7034917350669231}}
{"text": "From Coq Require Import ZArith Reals Psatz.\nFrom Flocq Require Import Binary Bits Core.\nFrom compcert.lib Require Import IEEE754_extra\n (* Coqlib Floats Zbits Integers*).\n\nRequire Import vcfloat.FPCore vcfloat.Reify vcfloat.Float_notations.\nSet Bullet Behavior \"Strict Subproofs\". \n\nLocal Open Scope float32_scope.\n\nSection WITHNANS.\nContext {NANS: Nans}.\n\n(** A single step of integration can modeled as either \n(1) a transition matrix update to the vector (p,q) of momentum \"p\" and position \"q\", as\n  given in \"leapfrog_stepF\"\n-or-\n(2) the \"typical\" velocity verlet scheme, as given in \"leapfrog_stepF_ver\" **)\n\n\n(** Compute one time-step: given \"ic\" which is a pair of momentum \"q\" and position \"p\" ,\n  calculate the new position and mometum after time \"h\" has elapsed. **)\n\nDefinition h : ftype Tsingle := 1 / 32.   (* Time-step: 1/32 of a second *)\nDefinition ω : ftype Tsingle := 1.\n\n(* Linear force function *)\nDefinition F_alt (x : ftype Tsingle) : ftype Tsingle := -((ω*ω)*x).\nDefinition F (x : ftype Tsingle) : ftype Tsingle := -x.\n(* We will use F rather than F_alt in the floating-point functional model,\n  because the C program omits the multiplication by 1.0*1.0.  \n  You might think that (1.0*1.0)*x is the same as x, but we do\n  not wish to use the identity (1.0*x=x)  _in the floats_;  we want\n  to match exactly the computation that the C program does. *)\n\nDefinition state : Type := ftype Tsingle * ftype Tsingle.  (* momenum,position*)\n\n(* Single step of Verlet integration *)\nDefinition leapfrog_stepF (h: ftype Tsingle) (ic : state) : state :=\n  let p  := fst ic in let q := snd ic in \n  let q' := (q + h * p) + (0.5 * (h * h)) * F q in\n  let p' :=  p +  (0.5 * h) * (F q + F q') in \n  (p', q').\n\n\n(** Iterations **)\n\n(* Main *)\nFixpoint iternF (h: ftype Tsingle) (ic: state) (n : nat): state:=\n  match n with\n  | 0%nat => ic\n  | S n' => iternF  h (leapfrog_stepF h ic) n'\nend.\n\n\n(** Lemmas **)\n\n\nLemma lfstep_lfn:\n  forall n ic ,\n  leapfrog_stepF h (iternF h ic n) = iternF h (leapfrog_stepF h ic) n.\nProof.\ninduction n. \n- auto.\n- simpl. auto. \nQed.\n\n\nLemma step_iternF:\n  forall n ic ,\n  iternF h ic (S n) = leapfrog_stepF h (iternF h ic n).\nProof.\ninduction n.\n- auto.\n- intros. rewrite -> IHn. simpl. \nreplace (leapfrog_stepF h (iternF _ _ _ )) with (iternF h (leapfrog_stepF h ic) n). \n  destruct (leapfrog_stepF h ic). \nall: symmetry; apply lfstep_lfn. \nQed.\n\n(* The initial conditions of the momentum \"p\" and position \"q\" specified for the integration scheme*)\nDefinition p_init: ftype Tsingle :=  0%F32.\nDefinition q_init: ftype Tsingle :=  1%F32.\nDefinition pq_init := (p_init, q_init).\nDefinition N : nat := 1000.\n\nEnd WITHNANS.\n\n\n", "meta": {"author": "VeriNum", "repo": "VerifiedLeapfrog", "sha": "c8d07f86747bd9e44f4cb02f19a691cc895c1279", "save_path": "github-repos/coq/VeriNum-VerifiedLeapfrog", "path": "github-repos/coq/VeriNum-VerifiedLeapfrog/VerifiedLeapfrog-c8d07f86747bd9e44f4cb02f19a691cc895c1279/leapfrog_project/float_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.703491729398021}}
{"text": "Theorem iff_trans : forall P Q R : Prop,\n  (P <-> Q) -> (Q <-> R) -> (P <-> R).\nProof.\n  intros.\n  destruct H as [Hpq Hqp].\n  destruct H0 as [Hqr Hrq].\n  split.\n  - intros.\n    apply Hqr.\n    apply Hpq.\n    apply H.\n  - intros.\n    apply Hqp.\n    apply Hrq.\n    apply H.\nQed.", "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/Chapter6/iff_trans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.703491724785421}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\n\n(* power set *)\nDefinition Pow T := T -> Prop.\n\n\nDefinition Subset {T} (s1 s2: Pow T) : Prop := forall t, s1 t -> s2 t.\nNotation \"s1 <: s2\" := (Subset s1 s2)\n                         (at level 30, no associativity).\n\nHint Unfold Subset.\n\nTheorem subset_refl : forall T (s: Pow T), s <: s.\nProof.\n  intros. unfold Subset. auto.\nQed.\n\nHint Resolve subset_refl.\n\nTheorem subset_trans : forall T (a b c: Pow T), a <: b -> b <: c -> a <: c.\nProof.\n  eauto.\nQed.\n\nHint Resolve subset_trans.\n\nDefinition Gen T := Pow T -> Pow T.\nHint Unfold Gen.\n\nDefinition monotone {T} (f: Gen T) : Prop := forall t1 t2, t1 <: t2 -> f t1 <: f t2.\nHint Unfold monotone.\n\nDefinition f_closed {T} (f: Gen T) (x: Pow T) := f x <: x.\nDefinition f_consistent {T} (f: Gen T) (x: Pow T) := x <: f x.\n(* or [forall t, x t = f x t] because of prop_ext axiom. *)\nDefinition f_fixpoint {T} (f: Gen T) (x: Pow T) := forall t, x t <-> f x t.\nDefinition f_fixpoint' {T} (f: Gen T) (x: Pow T) := x = f x.\n\nHint Unfold f_closed.\nHint Unfold f_consistent.\nHint Unfold f_fixpoint.\n\nLemma fixpoint_ext : forall T (f: Gen T) x, f_fixpoint' f x  <-> f_fixpoint f x.\nProof.\n  unfold f_fixpoint, f_fixpoint'.\n  intros. split.\n  - intros. split; intro. rewrite <- H. auto. rewrite H. auto.\n  - intros.\n    apply functional_extensionality. intro t.\n    apply propositional_extensionality. specialize H with t. destruct H.\n    split; intro; auto.\nQed.\n\n(* let's give it a try *)\nTheorem closed_consistent_implies_fixpoint : forall T (f: Gen T) (x: Pow T),\n    f_closed f x /\\ f_consistent f x -> f_fixpoint f x.\nProof.\n  intros.\n  destruct H. unfold f_closed in *. unfold f_consistent in *. unfold f_fixpoint.\n  unfold Subset in *.\n  intros.\n  pose proof H t.\n  pose proof H0 t.\n  split; auto.\nQed.\n\nHint Resolve closed_consistent_implies_fixpoint.\n\nTheorem fixpoint_implies_closed_consistent : forall T (f: Gen T) (x: Pow T),\n    f_fixpoint f x -> f_closed f x /\\ f_consistent f x.\nProof.\n  intros.\n  unfold f_closed in *. unfold f_consistent in *. unfold f_fixpoint in *.\n  split; unfold Subset.\n  - intros. apply H. auto.\n  - intros. apply H. auto.\nQed.\n\nHint Resolve fixpoint_implies_closed_consistent.\n\nLemma f_consistent_recursive : forall T (f: Gen T) (x: Pow T),\n    monotone f -> f_consistent f x -> f_consistent f (f x).\nProof.\n  unfold f_consistent.\n  intros.\n  intro.\n  intro.\n  eapply H with x.\n  apply H0. apply H1.\nQed.\n\nDefinition Intersect {T} (p: Pow T -> Prop) : Pow T :=\n  (fun t => forall x, p x -> x t).\n\nDefinition Union {T} (p: Pow T -> Prop) : Pow T :=\n  (fun t => exists x, p x /\\ x t).\n\nHint Unfold Intersect. Hint Unfold Union.\n\nLemma Intersect_Subset : forall T {p: Pow T -> Prop} x, p x -> Intersect p <: x.\nProof.\n  intros.\n  unfold Intersect, Subset.\n  intros.\n  apply H0.\n  apply H.\nQed.\n\nLemma Union_Subset : forall T {p: Pow T -> Prop} x, p x -> x <: Union p.\nProof. eauto. Qed.\n\nLemma Intersect_f_closed : forall T (f: Gen T),\n    monotone f -> f_closed f (Intersect (f_closed f)).\nProof.\n  intros.\n  repeat intro.\n  apply H1. eapply H.\n  apply Intersect_Subset.\n  apply H1. apply H0. Qed.\n\nLemma Union_f_consistent : forall T (f: Gen T),\n    monotone f -> f_consistent f (Union (f_consistent f)).\nProof.\n  intros.\n  intro. intro.\n  unfold Union in *. destruct H0. destruct H0.\n  apply H with x. apply Union_Subset.\n  apply H0. unfold f_consistent in H0. unfold Subset in H0.\n  auto.\nQed.\n\nLemma knaster_tarski_1_fixpoint : forall T (f: Gen T),\n    monotone f -> f_consistent f (Intersect (f_closed f)).\nProof.\n  intros T f Hmono.\n  unfold f_consistent.\n  repeat intro.\n  apply H.\n  apply Hmono.\n  clear H.\n  repeat intro.\n  apply H0.\n  eapply Hmono.\n  apply Intersect_Subset.\n  apply H0. apply H.\nQed.\n\nLemma knaster_tarski_2_fixpoint : forall T (f: Gen T),\n    monotone f -> f_closed f (Union (f_consistent f)).\nProof.\n  intros T f Hmono.\n  unfold f_closed.\n  repeat intro.\n  exists (f (Union (f_consistent f))).\n  split.\n  - repeat intro.\n    apply f_consistent_recursive; auto.\n    apply Union_f_consistent. auto.\n  - apply H.\nQed.\n\nDefinition IsMin {T} (p: Pow T -> Prop) (x: Pow T) : Prop :=\n  p x /\\ forall x', p x' -> x <: x'.\nDefinition IsMax {T} (p: Pow T -> Prop) (x: Pow T) : Prop :=\n  p x /\\ forall x', p x' -> x' <: x.\n\n\nLemma knaster_tarski_1 : forall T (f: Gen T),\n    monotone f -> IsMin (f_fixpoint f) (Intersect (f_closed f)).\nProof.\n  intros.\n  unfold IsMin.\n  split.\n  - apply closed_consistent_implies_fixpoint. split.\n    + apply Intersect_f_closed; easy.\n    + apply knaster_tarski_1_fixpoint; easy.\n  - intros.\n    apply Intersect_Subset.\n    apply fixpoint_implies_closed_consistent in H0. easy.\nQed.\n\nLemma knaster_tarski_2 : forall T (f: Gen T),\n    monotone f -> IsMax (f_fixpoint f) (Union (f_consistent f)).\nProof.\n  intros.\n  unfold IsMax.\n  split.\n  - apply closed_consistent_implies_fixpoint. split.\n    + apply knaster_tarski_2_fixpoint; easy.\n    + apply Union_f_consistent; easy.\n  - intros.\n    apply Union_Subset.\n    apply fixpoint_implies_closed_consistent in H0. easy.\nQed.\n\nTheorem knaster_tarski: forall T (f: Gen T),\n    monotone f ->\n    IsMin (f_fixpoint f) (Intersect (f_closed f)) /\\\n    IsMax (f_fixpoint f) (Union (f_consistent f)).\nProof.\n  auto using knaster_tarski_1, knaster_tarski_2.\nQed.\n\nLemma min_unique : forall T (p: Pow T -> Prop) (x1 x2: Pow T),\n    IsMin p x1 -> IsMin p x2 -> forall t, x1 t <-> x2 t.\nProof.\n  unfold IsMin.\n  unfold Subset.\n  intros. destruct H; destruct H0.\n  split; intro.\n  - apply H1; eauto.\n  - apply H2; eauto.\nQed.\n\nLemma max_unique : forall T (p: Pow T -> Prop) (x1 x2: Pow T),\n    IsMax p x1 -> IsMax p x2 -> forall t, x1 t <-> x2 t.\nProof.\n  unfold IsMax.\n  unfold Subset.\n  intros. destruct H; destruct H0.\n  split; intro.\n  - apply H2 with x1; eauto.\n  - apply H1 with x2; eauto.\nQed.\n\nDefinition MinFix {T} (f: Gen T) : Pow T := Intersect (f_closed f).\nDefinition MaxFix {T} (f: Gen T) : Pow T := Union (f_consistent f).\n\nCorollary principle_of_induction : forall T (f: Gen T) (x : Pow T),\n    monotone f -> f_closed f x -> MinFix f <: x.\nProof.\n  intros.\n  apply Intersect_Subset.\n  auto.\nQed.\n\nCorollary principle_of_coinduction : forall T (f: Gen T) (x : Pow T),\n    monotone f -> f_consistent f x -> x <: MaxFix f.\nProof.\n  intros.\n  apply Union_Subset.\n  auto.\nQed.\n\n\nInductive TypeTreeNode := TNTop | TNArrow | TNPair.\n\n(* a tree is a partial function from a list of branches to a node\n   branch mapping: false => left, true => right\n *)\nDefinition Tree : Type := list bool -> option TypeTreeNode.\n\nDefinition is_some {T} (v: option T) : Prop := match v with\n                                            | Some _ => True\n                                            | _ => False\n                                            end.\n\nImport ListNotations.\n\n(* Assert whether or not t is defined for input pi *)\nInductive tree_defined : Tree -> list bool -> Prop :=\n| TD_nil : forall t, tree_defined t nil\n(* i simplified the rule from the book to an equivalent form *)\n| TD_split : forall t p1 s, tree_defined t (p1 ++ [s]) -> tree_defined t p1\n| TD_arrow : forall t p1 s, t p1 = Some(TNArrow) -> tree_defined t (p1 ++ cons s nil)\n| TD_pair  : forall t p1 s, t p1 = Some(TNPair) -> tree_defined t (p1 ++ cons s nil)\n.\n\nDefinition tree_valid (t: Tree) : Prop :=\n  forall path, tree_defined t path <-> is_some (t path).\n\n(* I used an alternative definition for a tree to be finite:\n\n  if a tree is undefined after a given path length, then this tree is finite.\n *)\nDefinition tree_finite (t: Tree): Prop :=\n  exists n, forall p, n <= length p -> t p = None.\n\nDefinition tree_infinite (t: Tree): Prop := ~(tree_finite t).\n\n(* The tree: (Top -> Top, Top) *)\nExample tree1 : Tree :=\n  fun p => match p with\n        | [] => Some TNPair\n        | [false] => Some TNArrow\n        | [false; _] => Some TNTop\n        | [true] => Some TNTop\n        | _ => None\n        end.\n\nInductive TypeTree : Type :=\n| TTop : TypeTree\n| TArrow (l r: TypeTree) : TypeTree\n| TPair (l r: TypeTree) : TypeTree.\n\nFixpoint depth(t: TypeTree) : nat :=\n  match t with\n  | TTop => 1\n  | TArrow a b => max (depth a) (depth b)\n  | TPair a b => max (depth a) (depth b)\n  end.\n\nDefinition FiniteTree (t: TypeTree) : Prop := exists d, depth t <= d.\nDefinition InfiniteTree (t: TypeTree) : Prop := ~(FiniteTree t).\n\nDefinition relation (T: Type) := Pow (T * T).\n\nDefinition TR {U} (R: relation U) : relation U :=\n  fun pair => match pair with\n           | (x, y) => exists z, R (x, z) /\\ R (z, y)\n           end.\n\nDefinition Transitive {U} (R: relation U) := TR R <: R.\n\n\nLemma fixpoint_transitive :\n  forall U (F : relation U -> relation U),\n    monotone F ->\n    (forall R, TR(F(R)) <: F(TR(R))) ->\n    Transitive (MaxFix F).\nProof.\n  intros.\n  intro. intro.\n  assert (f_fixpoint' F (MaxFix F)).\n  { apply fixpoint_ext.\n    apply knaster_tarski_2.\n    apply H.\n  }\n  assert (f_consistent F (TR (MaxFix F))).\n  { intro. intro.\n    apply H0.\n    rewrite <- H2. apply H3.\n  }\n  apply principle_of_coinduction in H3; auto.\nQed.\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/tpl/recursive_type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7034091742788504}}
{"text": "(* Least-significant bit encoding and decoding of numbers. *)\n\nRequire Import Bool BinNat BinPos Nnat.\nFrom larith Require Import A_setup B1_utils.\n\nOpen Scope N.\n\nFixpoint pbits (p : positive) : list bool :=\n  match p with\n  | xI q => true :: pbits q\n  | xO q => false :: pbits q\n  | xH   => [true]\n  end.\n\nDefinition bits (n : N) :=\n  match n with\n  | 0%N     => []\n  | N.pos p => pbits p\n  end. \n\nFixpoint bnum (bits : list bool) : N :=\n  match bits with\n  | []      => 0\n  | b :: bs =>\n    match (bnum bs) with\n    | 0       => if b then 1 else 0\n    | N.pos p => N.pos (if b then p~1 else p~0)\n    end\n  end.\n\nTheorem bnum_bits_id n :\n  bnum (bits n) = n.\nProof.\ndestruct n; simpl. easy.\ninduction p; simpl.\n1,2: rewrite IHp. all: easy.\nQed.\n\nTheorem bnum_padding b :\n  bnum (b ++ [false]) = bnum b.\nProof.\ninduction b; simpl.\neasy. now rewrite IHb.\nQed.\n\nTheorem bnum_cons x xs :\n  bnum (x :: xs) = bnum [x] + 2 * (bnum xs).\nProof.\nsimpl; now destruct x, (bnum xs).\nQed.\n\nCorollary bnum_cons_eq_one xs :\n  bnum (true :: xs) = 1 <-> bnum xs = 0.\nProof.\nrewrite bnum_cons; simpl bnum.\ndestruct (bnum xs); easy.\nQed.\n\nTheorem bnum_cons_compare x xs y ys :\n  bnum (x :: xs) ?= bnum (y :: ys) =\n  Pos.switch_Eq (Bool.compare x y) (bnum xs ?= bnum ys).\nProof.\nsimpl; destruct x, y, (bnum xs), (bnum ys); simpl; try easy.\n1: rewrite Pos.compare_xI_xI. 4: rewrite Pos.compare_xO_xO.\n3: apply Pos.compare_xO_xI. 2: apply Pos.compare_xI_xO.\nall: now destruct (p ?= p0)%positive.\nQed.\n\nCorollary bnum_cons_eq x xs y ys :\n  bnum (x :: xs) = bnum (y :: ys) <-> x = y /\\ bnum xs = bnum ys.\nProof.\nrewrite <-?N.compare_eq_iff, bnum_cons_compare.\nnow destruct x, y, (bnum xs ?= bnum ys).\nQed.\n\nCorollary bnum_cons_le x xs y ys :\n  bnum (x :: xs) <= bnum (y :: ys) <->\n  bnum xs < bnum ys \\/ (bnum xs = bnum ys /\\ Bool.le x y).\nProof.\nrewrite <-?N.compare_le_iff, <-N.compare_lt_iff;\nrewrite <-N.compare_eq_iff, bnum_cons_compare.\ndestruct x, y, (bnum xs ?= bnum ys) eqn:H; simpl.\nall: try (rewrite and_remove_r; [|easy]).\nall: try (rewrite or_remove_r; [|easy]).\nall: try (rewrite or_comm, or_remove_r; [|easy]).\nall: try easy.\nQed.\n\nCorollary bnum_cons_lt x xs y ys :\n  bnum (x :: xs) < bnum (y :: ys) <->\n  bnum xs < bnum ys \\/ (bnum xs = bnum ys /\\ Bool.lt x y).\nProof.\nrewrite <-?N.compare_lt_iff, <-N.compare_eq_iff, bnum_cons_compare.\ndestruct x, y, (bnum xs ?= bnum ys) eqn:H; simpl.\nall: try (rewrite and_remove_r; [|easy]).\nall: try (rewrite or_remove_r; [|easy]).\nall: try (rewrite or_comm, or_remove_r; [|easy]).\nall: try easy.\nQed.\n\nClose Scope N.\n", "meta": {"author": "bergwerf", "repo": "linear_integer_arithmetic", "sha": "123b0b02accfbbc3407033b43d74fac5288bf073", "save_path": "github-repos/coq/bergwerf-linear_integer_arithmetic", "path": "github-repos/coq/bergwerf-linear_integer_arithmetic/linear_integer_arithmetic-123b0b02accfbbc3407033b43d74fac5288bf073/B3_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7034091722157942}}
{"text": "Require Import Essentials.Notations.\nRequire Import Essentials.Types.\nRequire Import Essentials.Facts_Tactics.\nRequire Import Category.Main.\nRequire Import Functor.Functor.\nRequire Import Functor.Functor_Ops.\n\nLocal Open Scope functor_scope.\n\nSection Functor_Properties.\n  Context {C C' : Category} (F : C –≻ C').\n\n  Local Open Scope object_scope.\n  Local Open Scope isomorphism_scope.\n  Local Open Scope morphism_scope.\n    \n  (** A functor is said to be injective if its object map is. *)\n  Definition Injective_Func := ∀ (c c' : Obj), F _o c = F _o c' → c = c'.\n\n  (** A functor is said to be essentially injective if its object map maps\nequal objects to isomorphic objects in the codomain category. *)\n  Definition Essentially_Injective_Func := ∀ (c c' : Obj), F _o c = F _o c' → c ≃ c'.\n  \n  (** A functor is said to be surjective if its object map is. *)\n  Definition Surjective_Func := ∀ (c : Obj), {c' : Obj | F _o c' = c}.\n\n  (** A functor is said to be essentially surjective if for each object in the\ncodomain category there is an aobject in the domain category that is mapped\nto an aobject isomorphic to it. *)\n  Definition Essentially_Surjective_Func := ∀ (c : Obj), {c' : Obj & F _o c' ≃ c}.\n\n  (** A functor is said to be faithful if its arrow map is injective. *)\n  Definition Faithful_Func := ∀ (c c' : Obj) (h h' : (c –≻ c')%morphism),\n      F _a h = F _a h' → h = h'.\n\n  (** A functor is said to be full if its arrow map is surjective. *)\n  Definition Full_Func := ∀ (c1 c2 : Obj) (h' : ((F _o c1) –≻ (F _o c2))%morphism),\n      {h : (c1 –≻ c2)%morphism | F _a h = h'}\n  .\n\n  Local Ltac Inv_FTH :=\n    match goal with\n      [fl : Full_Func |- _] =>\n      progress (\n          repeat\n            match goal with\n              [|- context [(F _a (proj1_sig (fl _ _ ?x)))]] =>\n              rewrite (proj2_sig (fl _ _ x))\n            end\n        )\n    end\n  .\n\n  Local Hint Extern 1 => Inv_FTH.\n\n  Local Hint Extern 1 => rewrite F_compose.\n\n  Local Hint Extern 1 =>\n  match goal with\n    [fth : Faithful_Func |- _ = _ ] => apply fth\n  end\n  .\n\n  Local Obligation Tactic := basic_simpl; auto 6.\n  \n  (** Any fully-faithful functor is essentially surjective. *)\n  Program Definition Fully_Faithful_Essentially_Injective (fth : Faithful_Func) (fl : Full_Func)\n    : Essentially_Injective_Func\n    :=\n      fun c c' eq =>\n        {|\n          iso_morphism :=\n            proj1_sig (\n                fl\n                  _\n                  _\n                  match eq in _ = y return\n                        (_ –≻ y)%morphism\n                  with\n                    idpath => id (F _o c)\n                  end\n              );\n          inverse_morphism :=\n            proj1_sig (\n                fl\n                  _\n                  _\n                  match eq in _ = y return\n                        (y –≻ _)%morphism\n                  with\n                    idpath => id (F _o c)\n                  end\n              )\n        |}\n  .\n    \n  (** Any fully-faithful functor is conservative.\n\nA conservative functor is one for which we have to objects of the domain category are isomorphic if their images are ismorphic. *)\n  Program Definition Fully_Faithful_Conservative (fth : Faithful_Func) (fl : Full_Func)\n    : ∀ (c c' : Obj), F _o c ≃ F _o c' → c ≃ c' :=\n    fun c c' I =>\n      {|\n        iso_morphism := proj1_sig (fl _ _ I);\n        inverse_morphism := proj1_sig (fl _ _ (I⁻¹))\n      |}\n  .\n\nEnd Functor_Properties.\n\n(** Functors Preserve Isomorphisms. *)\nSection Functors_Preserve_Isos.\n  Context {C C' : Category} (F : C –≻ C') {a b : C} (I : (a ≃≃ b ::> C)%isomorphism).\n\n  Program Definition Functors_Preserve_Isos : (F _o a ≃ F _o b)%isomorphism :=\n    {|\n      iso_morphism := (F _a I)%morphism;\n      inverse_morphism := (F _a (I⁻¹))%morphism\n    |}.\n\nEnd Functors_Preserve_Isos.\n  \nSection Embedding.\n  Context (C C' : Category).\n\n  (**\n    An embedding is a functor that is faully-faithful. Such a functor is necessarily essentially injective and conservative, i.e., if F _O c ≃ F _O c' then c ≃ c'.\n   *)\n\n  Record Embedding : Type :=\n    {\n      Emb_Func : C –≻ C';\n\n      Emb_Faithful : Faithful_Func Emb_Func;\n      \n      Emb_Full : Full_Func Emb_Func\n    }.\n\n  Coercion Emb_Func : Embedding >-> Functor.\n\n  Definition Emb_Essent_Inj (E : Embedding) := Fully_Faithful_Essentially_Injective (Emb_Func E) (Emb_Faithful E) (Emb_Full E).\n  \n  Definition Emb_Conservative (E : Embedding) := Fully_Faithful_Conservative (Emb_Func E) (Emb_Faithful E) (Emb_Full E).\n\nEnd Embedding.\n\nArguments Emb_Func {_ _} _.\nArguments Emb_Faithful {_ _} _ {_ _} _ _ _.\nArguments Emb_Full {_ _} _ {_ _} _.", "meta": {"author": "amintimany", "repo": "Categories-HoTT", "sha": "fd6018c7abd496b44fd31b1119f6b31795c251d8", "save_path": "github-repos/coq/amintimany-Categories-HoTT", "path": "github-repos/coq/amintimany-Categories-HoTT/Categories-HoTT-fd6018c7abd496b44fd31b1119f6b31795c251d8/Functor/Functor_Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639067, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7034091618001727}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\nRequire Export Setoid Morphisms.\nRequire Export Coq.Program.Basics.\nFrom Undecidability.FOL Require Import FullSyntax.\nFrom Equations Require Import Equations.\nFrom Coq Require Import Arith Lia List Program.Equality.\n\nClass HeytingAlgebra : Type :=\n  {\n    H : Type ;\n    \n    R : H -> H -> Prop ;\n    Rref : Reflexive R ;\n    Rtra : Transitive R ;\n    \n    Bot : H ;\n    Meet : H -> H -> H ;\n    Join : H -> H -> H ;\n    Impl : H -> H -> H ;\n    \n    Bot1 : forall u, R Bot u ;\n    (*Bot2 : ~ R (Imp Bot Bot) Bot ;*)\n    Meet1 : forall u v w, R w u /\\ R w v <-> R w (Meet u v) ;\n    Join1 : forall u v w, R u w /\\ R v w <-> R (Join u v) w ;\n    Impl1 : forall u v w, R (Meet w u) v <-> R w (Impl u v) ;\n  }.\n\nCoercion H : HeytingAlgebra >-> Sortclass.\nNotation \"s '<=' t\" := (R s t) (at level 70).\n\n\n\n(* Registering the relation R of Heyting algebras as preorder for rewriting *)\n#[global]\nInstance preorder_HA (HA : HeytingAlgebra) :\n  PreOrder (@R HA).\nProof.\n  split. apply Rref. apply Rtra.\nQed.\n\n\n\n(* Simple properties of Heyting algebras *)\n\nSection HAProperty.\n\n  Context { HA : HeytingAlgebra }.\n  Implicit Type u v w : HA.\n\n  Definition eqH u v := u <= v /\\ v <= u.\n\n  Lemma Meet2 u v :\n    Meet u v <= u.\n  Proof.\n    now apply (Meet1 u v).\n  Qed.\n\n  Lemma Meet3 u v :\n    Meet u v <= v.\n  Proof.\n    now apply (Meet1 u v).\n  Qed.\n\n  Lemma Meet_com u v :\n    Meet u v <= Meet v u.\n  Proof.\n    apply Meet1; split; auto using Meet2, Meet3.\n  Qed.\n\n  Lemma Meet_left x y z :\n    x <= y -> Meet z x <= Meet z y.\n  Proof.\n    intros H. apply Meet1. split.\n    - apply Meet2.\n    - rewrite <- H. apply Meet3.\n  Qed.\n\n  Definition Top := Impl Bot Bot.\n\n  Lemma Top1 u :\n    u <= Top.\n  Proof.\n    apply Impl1, Meet3.\n  Qed.\n\n  Lemma Join2 u v :\n    u <= Join u v.\n  Proof.\n    now apply (Join1 u v).\n  Qed.\n\n  Lemma Join3 u v :\n    v <= Join u v.\n  Proof.\n    now apply (Join1 u v).\n  Qed.\n\n  Lemma Join_com u v :\n    eqH (Join u v) (Join v u).\n  Proof.\n    split; apply Join1; split; auto using Join2, Join3.\n  Qed.\n\n  Lemma Imp2 u v :\n    Meet (Impl u v) u <= v.\n  Proof. \n    apply Impl1, Rref.\n  Qed.\n\n  Lemma Meet_assoc u v w :\n    Meet u (Meet v w) <= Meet (Meet u v) w.\n  Proof.\n    simpl. apply Meet1. split.\n    - apply Meet1. split.\n      + apply Meet2.\n      + now rewrite Meet3, Meet2.\n    - now rewrite Meet3, Meet3.\n  Qed.\n\n  Lemma Meet_extend x y :\n    x <= y -> x <= Meet x y.\n  Proof.\n    intros H. apply Meet1. now split.\n  Qed.\n\n  Lemma Imp_bot x y :\n    y <= Impl Bot x.\n  Proof.\n    apply Impl1. rewrite Meet3. apply Bot1.\n  Qed.\n\n  Lemma meet_join_distr x y z :\n    Meet x (Join y z) <= Join (Meet x y) (Meet x z).\n  Proof.\n    rewrite Meet_com, Impl1, <- Join1. split.\n    - rewrite <- Impl1, Meet_com. apply Join2.\n    - rewrite <- Impl1, Meet_com. apply Join3.\n  Qed.\n\n  Lemma meet_join_expansion x y z :\n    x <= Join y z -> x <= Join (Meet x y) (Meet x z).\n  Proof.\n    intros H. rewrite <- meet_join_distr.\n    apply Meet1. split; trivial. reflexivity.\n  Qed.\n  \n  Definition equiv_HA x y := x <= y /\\ y <= x.\n  Notation \"x ≡ y\" := (equiv_HA x y) (at level 40).\n\n  Global Instance subrelation_HA : subrelation equiv_HA R.\n  Proof.\n    firstorder.\n  Qed.\n\n  \n  Global Instance subrelation_HA_flip : subrelation equiv_HA (flip R).\n  Proof.\n    firstorder.\n  Qed.\n  \n  Global Instance equiv_HA_refl : Equivalence equiv_HA.\n  Proof.\n    split.\n    - split; reflexivity.\n    - split; eapply H0.\n    - split. now rewrite H0, H1. now rewrite <- H1, <- H0.\n  Qed.\n\n  Hint Resolve Meet2 Meet3 Join2 Join3 Impl1 Imp2 : core.\n      \n  Global Instance proper_HA_Meet : Proper (equiv_HA ==> equiv_HA ==> equiv_HA) Meet.\n  Proof.\n    intros ? ? ? ? ? ?.\n    split.\n    - rewrite <- Meet1, <- H0, <- H1; eauto.\n    - rewrite <- Meet1, H0, H1; eauto.\n  Qed.\n  \n  Global Instance proper_HA_Join : Proper (equiv_HA ==> equiv_HA ==> equiv_HA) Join.\n  Proof.\n    intros ? ? ? ? ? ?.\n    split.\n    - rewrite <- Join1, H0, H1; eauto.\n    - rewrite <- Join1, <- H0, <- H1; eauto.\n  Qed.\n\n  Global Instance proper_HA_Impl : Proper (equiv_HA ==> equiv_HA ==> equiv_HA) Impl.\n  Proof.\n    intros ? ? ? ? ? ?.\n    split.\n    - rewrite <- Impl1. rewrite <- H1, <- H0. eauto.\n    - rewrite <- Impl1. rewrite H1, H0. eauto.\n  Qed.\n  \nEnd HAProperty.\n\nNotation is_inf P inf :=\n  (forall u, (forall v, P v -> u <= v) <-> u <= inf).\n\nNotation is_sup P sup :=\n  (forall u, (forall v, P v -> v <= u) <-> sup <= u).\n#[global]\nHint Resolve Meet2 Meet3 : core.\n\n(* ** Complete Heyting Algebras *)\n\nClass CompleteHeytingAlgebra : Type :=\n  {\n    HA : HeytingAlgebra ;\n    Inf : (HA -> Prop) -> HA ;\n    Inf1 : forall (P : HA -> Prop), is_inf P (Inf P) ;\n  }.\n\nCoercion HA : CompleteHeytingAlgebra >-> HeytingAlgebra.\n\nSection CHAProperty.\n\n  Context { HA : CompleteHeytingAlgebra }.\n  Implicit Type u v w : HA.\n  Implicit Type P : HA -> Prop.\n\n  Lemma Inf2 P u :\n    P u -> Inf P <= u.\n  Proof.\n    now apply Inf1.\n  Qed.\n\n  Definition Inf_indexed I (F : I -> HA) :=\n    Inf (fun u => exists i, equiv_HA u (F i)).\n\n  Lemma Inf_indexed1 I (F : I -> HA) u :\n    (forall i, u <= F i) <-> u <= Inf_indexed F.\n  Proof.\n    unfold Inf_indexed. rewrite <- Inf1. split; intros H.\n    - intros v [i ->]. now apply H.\n    - intros i. apply H. now exists i.\n  Qed.\n\n  Definition Sup P :=\n    Inf (fun u => forall v, P v -> v <= u).\n\n  Lemma Sup2 P u :\n    P u -> u <= Sup P.\n  Proof.\n    intros H. apply Inf1. firstorder.\n  Qed.\n\n  Lemma Sup1 P :\n    is_sup P (Sup P).\n  Proof.\n    split; intros H.\n    - now apply Inf2.\n    - intros v H' % Sup2. now rewrite H'.\n  Qed.\n\n  Definition Sup_indexed I (F : I -> HA) :=\n    Sup (fun u => exists i, equiv_HA u (F i)).\n\n  Lemma Sup_indexed1 I (F : I -> HA) u :\n    (forall i, F i <= u) <-> Sup_indexed F <= u.\n  Proof.\n    unfold Sup_indexed. rewrite <- (Sup1 _ u). split; intros H.\n    - intros v [i ->]. now apply H.\n    - intros i. apply H. now exists i.\n  Qed.\n\n  Lemma meet_sup_distr x I (F : I -> HA) :\n    Meet x (Sup_indexed F) <= Sup_indexed (fun i => Meet x (F i)).\n  Proof.\n    rewrite Meet_com, Impl1, <- Sup_indexed1.\n    intros i. rewrite <- Impl1, Meet_com.\n    apply Sup2. now exists i.\n  Qed.\n\n  Lemma meet_sup_expansion x I (F : I -> HA) :\n    x <= Sup_indexed F -> x <= Sup_indexed (fun i => Meet x (F i)).\n  Proof.\n    intros H. rewrite <- meet_sup_distr.\n    apply Meet1. split; trivial. reflexivity.\n  Qed.\n\n  Instance proper_HA_Inf : Proper (pointwise_relation _ iff ==> equiv_HA) Inf.\n  Proof.\n    intros ? ? ?.\n    split.\n    - rewrite <- Inf1. intros. eapply H0 in H1.\n      now eapply Inf2.\n    - rewrite <- Inf1. intros. eapply H0 in H1.\n      now eapply Inf2.\n  Qed.      \n\n  Instance proper_HA_Sup : Proper (pointwise_relation _ iff ==> equiv_HA) Sup.\n  Proof.\n    intros ? ? ?. unfold Sup. eapply proper_HA_Inf.\n    intros ?.\n    split; firstorder.\n  Qed.      \n\n  Instance proper_HA_Sup_indexed I : Proper (pointwise_relation _ equiv_HA ==> equiv_HA) (@Sup_indexed I).\n  Proof.\n    intros ? ? ?. unfold Sup_indexed. eapply proper_HA_Sup.\n    split.\n    - firstorder subst. exists x0. split. rewrite H1. eapply H0. rewrite <- H2. eapply H0.\n    - firstorder subst. exists x0. split. rewrite H1. eapply H0. rewrite <- H2. eapply H0.\n  Qed.      \n  \n  Instance proper_HA_Inf_indexed I : Proper (pointwise_relation _ equiv_HA ==> equiv_HA) (@Inf_indexed I).\n  Proof.\n    intros ? ? ?. unfold Inf_indexed. eapply proper_HA_Inf.\n    split.\n    - firstorder subst. exists x0. split. rewrite H1. eapply H0. rewrite <- H2. eapply H0.\n    - firstorder subst. exists x0. split. rewrite H1. eapply H0. rewrite <- H2. eapply H0.\n  Qed.      \n\n  Notation \"A <~> B\" := ((A -> B) * (B -> A))%type (at level 85) : type_scope.      \n  \nEnd CHAProperty.\n\n\n\nSection CHAEval.\n\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Context { HA : CompleteHeytingAlgebra }.\n\n  Variable hinter_Pr : forall (P : Σ_preds), Vector.t term (ar_preds P) -> HA.\n\n  Obligation Tactic := intros; subst; cbn; try lia.\n\n  Derive NoConfusion for falsity_flag.\n\n  Equations hsat (phi : form) : HA by wf (size phi) lt :=\n    hsat (atom P v) := hinter_Pr v ;\n    hsat ⊥ := Bot ;\n    hsat (phi → psi) := Impl (hsat phi) (hsat psi) ;\n    hsat (phi ∧ psi) := Meet (hsat phi) (hsat psi) ;\n    hsat (phi ∨ psi) := Join (hsat phi) (hsat psi) ;\n    hsat (∀ phi) := Inf_indexed (fun t => hsat (phi [t..])) ;\n    hsat (∃ phi) := Sup_indexed (fun t => hsat (phi [t..])).\n  Next Obligation.\n    rewrite subst_size. econstructor.\n  Qed.\n  Next Obligation.\n    rewrite subst_size. econstructor.\n  Qed.\n\n  Definition hsat_L A : HA :=\n    Inf (fun x => exists phi, In phi A /\\ x = hsat phi).\n\n  Lemma top_hsat_L :\n    Top <= hsat_L nil.\n  Proof.\n    apply Inf1. intros v [phi [[] _]].\n  Qed.\n\nEnd CHAEval.\n\n(* ** Boolean Semantics *)\n\nDefinition boolean (HA : HeytingAlgebra) :=\n  forall x y : HA, Impl (Impl x y) x <= x.\n\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/FOL/Semantics/Heyting/Heyting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7034091488809863}}
{"text": "\n(* ================================================================== *)\n(* ==================== Programming and proving ===================== *)\n(* ================================================================== *)\n\nRequire Import ZArith.\n\nRequire Import List.\n\nRequire Import Lia.\n\n\nSet Implicit Arguments.\n\nFixpoint elem (a:Z) (l:list Z) {struct l} : bool :=   (* !!!!!!!!!!! *)\n    match l with\n      | nil => false\n      | cons x xs => if Z.eq_dec x a then true else (elem a xs)\n    end.\n\n\nProposition elem_corr : forall (a:Z) (l1 l2:list Z),\n                  elem a (app l1 l2) = orb (elem a l1) (elem a l2).\nProof.\n  induction l1.\n  - intros. simpl. reflexivity.\n  - intros. simpl.\n    elim (Z.eq_dec a0 a).     \n    + intros. simpl.  reflexivity.\n    + auto.\nQed.\n\n\n(* Exercise: *)\n(* Sugestion: use de previous proposition *)\nLemma ex : forall (a:Z) (l1 l2:list Z), elem a (app l1 (cons a l2)) = true.\nProof.\n  intros. (*Este resultado encaixa na prop elem_corr*)\n  rewrite(elem_corr a l1 (a::l2)).\n  simpl. elim(Z.eq_dec).\n  - Search \"||\". intros. apply Bool.orb_true_r.\n  - intros. contradiction.\nQed.\n(* ================================================================== *)\n(* ======================== Partiality ============================== *)\n\n(* defining the function head *)\n\nDefinition head (A:Type) (l:list A) : l<>nil -> A.\n(* \"refine term\" tactic applies to any goal. It behaves like exact with\na big difference: the user can leave some holes (denoted by _ or (_:type)) \nin the term. \nrefine will generate as many subgoals as there are holes in the term. *) \n  refine (\n  match l as l' return l'<>nil -> A with\n  | nil => fun H => _\n  | cons x xs => fun H => x\n  end ).  \n  contradiction.\nDefined.\n\nPrint head. Print False_rect.\nPrint Implicit head.\n\n\n(* head precondition *)\nDefinition headPre (A:Type) (l:list A) : Prop := l<>nil.\n\n(* the specification of head *) \nInductive headRel (A:Type) (x:A) : list A -> Prop :=\n  headIntro : forall l, headRel x (cons x l).\n\nPrint Implicit headRel.\n\n\n(* we can prove the correctness of head w.r.t. its specification *)\n(* note that (head p) is the same as (@head A l p) since A and l are implicit arguments *)\nLemma head_correct : forall (A:Type) (l:list A) (p:headPre l), headRel (head  p) l.\nProof.\n  destruct l.\n  - intro H. elim H. reflexivity.\n  - intros.  destruct l.\n    + simpl. apply headIntro.\n    + simpl. constructor. (*apply headIntro tb pode ser usado*)\n    (* change de proof script so that you can see effect each tactic *)\nQed.\n\n\n\n(* ================================================================== *)\n(* ==================== Program Extraction ========================== *)\n\nRequire Extraction.  (* the extraction framework must be loaded explicitly *)\n\n\n(* we can convert to Haskell the function head defined *)\nExtraction Language Haskell.\n\nExtraction head.\n\nExtraction False_rect.\nExtraction Inline False_rect.  (* will make the code more readable *)\nExtraction head.\n\nRecursive Extraction head.\nExtraction \"exemplo1\" head.\n\nExtract Inductive list => \"[]\" [ \"[]\" \"(:)\" ].\n\nRecursive Extraction head.\nExtraction \"exemplo2\" head.\n\n(* We have just followed the \"weak specification\" approach: \n   we defined the function and add, as a companion lemma, that the function \n   satisfies its specification. \n*)\n\n\n(* ================================================================== *)\n\n(* Instead of this approach, we can give a \"strong specification\" of a\n   function  (using specification types), and extract the function from \n   its proof (the prove that the specification is inhabited).\n*)\n\n(* An inductive relation \"x is the last element of list l\" *)\nInductive Last (A:Type) (x:A) : list A -> Prop :=\n| last_base : Last x (cons x nil)\n| last_step : forall l y, Last x l -> Last x (cons y l).\n\n \nTheorem last_correct : forall (A:Type) (l:list A), l<>nil -> { x:A | Last x l }.\nProof.\n  induction l.\n  - intro H. elim H. reflexivity.\n  - intros. destruct l.\n    + exists a. constructor.\n    + elim IHl.\n      * intros. exists x. constructor. assumption.\n      * discriminate.\nQed.\n\n\n\nRecursive Extraction last_correct.\n\n\nExtraction Inline False_rect sig_rect list_rect.\n\nRecursive Extraction last_correct.\n\n\n\n(* ================================================================== *)\n\n(* Following this alternative approach we can give a \"strong specification\" of \n   function head (using specification types), and extract the function from \n   its proof (the prove that the specification is inhabited).\n*)\n\n(* Exercise: built an alternative definition of function head called “head corr” \n   based on the strong specification mechanism *)\n\n\n\n\n(* ================================================================== *)\n(* ======================= Sorting a list =========================== *)\n\nOpen Scope Z_scope. \n\nInductive Sorted : list Z -> Prop := \n  | sorted0 : Sorted nil \n  | sorted1 : forall z:Z, Sorted (z :: nil) \n  | sorted2 : forall (z1 z2:Z) (l:list Z), \n        z1 <= z2 -> Sorted (z2 :: l) -> Sorted (z1 :: z2 :: l). \n\n\nFixpoint count (z:Z) (l:list Z) {struct l} : nat :=\n  match l with\n  | nil => 0%nat     (* %nat to force the interpretation in nat, since have we open Z_scope *)\n  | (z' :: l') => if Z.eq_dec z z' \n                  then S (count z l')\n                  else count z l'\n  end.\n\n\nDefinition Perm (l1 l2:list Z) : Prop :=\n                                 forall z, count z l1 = count z l2.\n\n\n(* Perm is an equivalence relation (i.e. is reflexive, symmetric and transitive) *)\n\nLemma Perm_reflex : forall l:list Z, Perm l l.\nProof.\n  intros. red. reflexivity.\nQed.\n\nLemma Perm_sym : forall l1 l2, Perm l1 l2 -> Perm l2 l1.\nProof. \n  unfold Perm.\n  intros l1 l2 H z.\n  symmetry.\n  (* apply H. *)\n  generalize z. \n  assumption.\nQed.\n\n\nLemma Perm_trans : forall l1 l2 l3, Perm l1 l2 -> Perm l2 l3 -> Perm l1 l3.\nProof.\n  unfold Perm.\n  intros.\n  transitivity (count z l2); [ apply H | apply H0 ].  \nQed.\n\n\n\n(*  Exercise: prove the following lemmas: *)\n\n\nLemma Perm_cons : forall a l1 l2, Perm l1 l2 -> Perm (a::l1) (a::l2).\nProof.\n  intros.\n  unfold Perm in *. simpl.\n  intro.\n  elim (Z.eq_dec). auto. auto.\nQed.\n\n\n\nLemma Perm_cons_cons : forall x y l, Perm (x::y::l) (y::x::l).\nProof.\n  unfold Perm.\n  intros.\n  simpl. elim(Z.eq_dec z x).\n  - elim (Z.eq_dec z y); auto. (*auto auto*)\n  - reflexivity.\nQed.\n\nFixpoint insert (x:Z) (l:list Z) {struct l} : list Z :=\n  match l with\n    nil => cons x (@nil Z)\n  | cons h t => if Z_lt_ge_dec x h\n                then cons x (cons h t)\n                else cons h (insert x t)\n  end.\n\n\nFixpoint isort (l:list Z) : list Z :=\n  match l with\n    nil => nil\n  | cons h t => insert h (isort t)\n  end.\n\nPrint isort.\n\n\n(* some  usefull lemmas about count *)\n\nLemma count_insert_eq : forall x l,\n                       count x (insert x l) = S (count x l).\nProof.\n  induction l.\n  - simpl. destruct (Z.eq_dec x x).\n    + reflexivity.\n    + destruct n. reflexivity.\n  - simpl insert. destruct (Z_lt_ge_dec x a).\n    + simpl. destruct (Z.eq_dec x x).\n      * reflexivity.\n      * easy.\n    + simpl. destruct (Z.eq_dec x a).\n      * rewrite IHl. reflexivity.\n      * assumption.\nQed.\n\nLemma count_cons_diff : forall z x l, z <> x -> count z l = count z  (x :: l).\nProof.\n  intros. induction l.\n  - simpl. destruct (Z.eq_dec z x); easy.\n  - simpl. destruct (Z.eq_dec z a).\n    + destruct (Z.eq_dec z x); easy.\n    + destruct (Z.eq_dec z x); easy.\nQed.\n\n \nLemma count_insert_diff : forall z x l, z <> x -> count z l = count z (insert x l).\nProof.\n  intros. induction l.\n  - simpl. destruct (Z.eq_dec z x); easy.\n  - simpl insert. destruct (Z_lt_ge_dec x a).\n    + simpl. destruct (Z.eq_dec z x); try easy. (*O try aplica tecnicas automaticas mas se nao resolver nao avança na prova*)\n    + simpl. destruct (Z.eq_dec z a); try easy.\n      apply f_equal. apply IHl.\nQed.    \n\n\n(* the two auxiliary lemmas *)\n\nLemma insert_Perm : forall x l, Perm (x::l) (insert x l).\nProof.\n  unfold Perm; induction l.\n - simpl. reflexivity.\n - simpl insert. destruct (Z_lt_ge_dec x a).\n   + reflexivity.\n   + intros. \n     destruct (Z.eq_dec z a).\n     * simpl. destruct (Z.eq_dec z a).\n       -- destruct (Z.eq_dec z x). \n          ++ apply f_equal. rewrite e1. rewrite count_insert_eq. reflexivity.\n          ++ apply f_equal. apply count_insert_diff. assumption.\n       -- destruct (Z.eq_dec z x).\n          ++ destruct n. assumption.\n          ++ destruct n. assumption.\n     * simpl. destruct (Z.eq_dec z a).\n       -- destruct (Z.eq_dec z x); easy.\n       -- destruct (Z.eq_dec z x). \n          ++ rewrite e. rewrite count_insert_eq. reflexivity.\n          ++ rewrite <- count_insert_diff; [reflexivity|assumption].\nQed.\n\n\n\nLemma insert_Sorted : forall x l, Sorted l -> Sorted (insert x l).\nProof.\n  - intros x l H; elim H; simpl. \n    + constructor.\n    + intro z; elim (Z_lt_ge_dec x z); intros.\n      * constructor.\n        auto with zarith. constructor.\n      * constructor.\n        -- auto with zarith.\n        -- constructor.\n    + intros z1 z2 l0 H0 H1.\n      elim (Z_lt_ge_dec x z2); elim (Z_lt_ge_dec x z1).\n      * intros. constructor.\n        -- lia. (* auto with zarith.*)\n        -- constructor.\n           ++ lia. \n           ++ assumption.  \n      * intros. constructor.\n        -- lia.\n        -- assumption.\n      * intros. constructor.\n        -- lia.\n        -- constructor; [lia|assumption].\n      * intros. constructor; [lia|assumption].\nQed.\n\n\n(* the proof that isort is correct *)\nTheorem isort_correct : forall (l l':list Z), l'=isort l -> Perm l l' /\\ Sorted l'.\nProof.\n  induction l; intros.\n  - unfold Perm; rewrite H; split; auto. simpl. constructor.\n  - simpl in H.\n    rewrite H. (* ??????????? *) \n    elim (IHl (isort l)); intros; split.\n    + apply Perm_trans with (a::isort l).\n      * unfold Perm. intro z. simpl. elim (Z.eq_dec z a).\n        -- intros. elim H0; reflexivity.   (* auto with zarith. *)\n        -- auto with zarith.   (* intros. elim H0. reflexivity. *)\n      * apply insert_Perm.\n    + apply insert_Sorted. assumption.\nQed.\n\n\n(* EXTRACTION *) \n(* using specification types *)\nDefinition inssort : forall (l:list Z), { l' | Perm l l' & Sorted l' }.\nProof.\n  induction l.\n  - exists nil. constructor. constructor.\n  - elim IHl. intros l1 H H1. exists (insert a l1).\n    + apply Perm_trans with (a::l1).\n      * apply Perm_cons. assumption.\n      * apply insert_Perm.\n    + apply insert_Sorted. assumption.\nDefined.\n\nExtraction Language Haskell.\nRecursive Extraction inssort.\n\nExtraction Inline list_rec list_rect sig2_rec sig2_rect.\n\nExtraction inssort.\nRecursive Extraction inssort.\n\n\n(* ================================================================== *)\n(* =================== Non-structural recursion ===================== *)\n\nClose Scope Z_scope.\n\nRequire Import Recdef. (* because of Function *)\n\n\nFunction div (p:nat*nat) {measure fst} : nat*nat :=\n  match p with\n  | (_,0) => (0,0)\n  | (a,b) => if le_lt_dec b a\n             then let (x,y):=div (a-b,b) in (1+x,y)\n             else (0,a)\n  end.\nProof.\n intros. simpl. lia.\nQed.\n\n\n\n(* Exercise: *)\nFunction merge (p:list Z*list Z)\n{measure (fun p=>(length (fst p))+(length (snd p)))} : list Z :=\n  match p with\n  | (nil,l) => l\n  | (l,nil) => l\n  | (x::xs,y::ys) => if Z_lt_ge_dec x y\n                     then x::(merge (xs,y::ys))\n                     else y::(merge (x::xs,ys))\n  end.\nAdmitted.\n(* FILL IN HERE *)\n\n\n\n\n(* ========== Introducing a new induction principle =========== *)\n\n\n\nFixpoint split (A:Type) (l:list A) : (list A * list A) :=\n  match l with\n  | [] => ([],[])     (* Import ListNotations. *)\n  | [x] => ([x],[])\n  | x1::x2::l' => let (l1,l2) := split l' in (x1::l1,x2::l2) \n  end.\n\n\n\n(*\n    While this function is straightforward to define, it can be a bit challenging\n    to work with.  Let's try to prove the following lemma, which is obviously true:\n*)\n\nLemma split_len_first_try: forall (A:Type) (l:list A) (l1 l2: list A),\n             split l = (l1,l2) ->  length l1 <= length l /\\ length l2 <= length l.\nProof.\n  induction l; intros. \n  - inversion H. simpl. lia. \n  - destruct l as [| x l'].\n    + inversion_clear H. split; simpl; auto.\n    + inversion H. destruct (split l') as [l1' l2']. inversion H1. \n      (* We're stuck! The IH talks about split (x::l') but we\n         only know aobut split (a::x::l'). *)\nAbort.\n\n(*  The problem here is that the standard induction principle for lists\n    requires us to show that the property being proved follows for      \n    any non-empty list if it holds for the tail of that list.\n    What we want here is a \"two-step\" induction principle, that instead requires\n    us to show that the property being proved follows for a list of\n    length at least two, if it holds for the tail of the tail of that list.\n    Formally: \n*)\n\nDefinition list_ind2_principle:=\n    forall (A : Type) (P : list A -> Prop),\n      P nil ->\n      (forall (a:A), P (a::nil)) ->\n      (forall (a b : A) (l : list A), P l -> P (a :: b :: l)) ->\n      forall l : list A, P l.\n\n(* If we assume the correctness of this \"non-standard\" induction principle, \n    our split_len proof is easy, using a form of the induction tactic \n    that lets us specify the induction principle to use: \n *)\n\n\n\nLemma split_len': list_ind2_principle -> \n    forall (A:Type) (l:list A) (l1 l2: list A),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n  unfold list_ind2_principle; intro IP.\n  induction l using IP; intros.\n  - inversion H. lia.\n  - inversion H. simpl; lia.\n  - inversion H. destruct (split l) as [l1' l2']. inversion H1. \n    simpl. \n    destruct (IHl l1' l2') as [P1 P2]; auto; lia.\nQed.\n\n(*  We still need to prove list_ind2_principle.  There are several\n    ways to do this, but one direct way is to write an explicit proof\n    term, thus: *)\n\nDefinition list_ind2 :\n  forall (A : Type) (P : list A -> Prop),\n      P nil ->\n      (forall (a:A), P (a::nil)) ->\n      (forall (a b : A) (l : list A), P l -> P (a :: b :: l)) ->\n      forall l : list A, P l :=\n  fun (A : Type)\n      (P : list A -> Prop)\n      (H : P nil)\n      (H0 : forall a : A, P (a::nil))\n      (H1 : forall (a b : A) (l : list A), P l -> P (a :: b :: l))  => \n    fix IH (l : list A) :  P l :=\n    match l with\n    | nil => H\n    | (x::nil) => H0 x\n    | x::y::l' => H1 x y l' (IH l')\n    end.\n\n\n\n    \n(*  Here, the fix keyword defines a local recursive function IH\n    of type forall l:list A, P l, which is returned as the overall value of\n    list_ind2. As usual, this function must be obviously terminating \n    to Coq (which it is because the recursive call is on a sublist l' \n    of the original argument l) and the match must be exhaustive over\n    all possible lists (which it evidently is). \n*)\n\n(*  With our induction principle in hand, we can finally prove \n    split_len free and clear: \n*)\n\nLemma split_len: forall (A:Type) (l:list A) (l1 l2: list A),\n    split l = (l1,l2) ->\n    length l1 <= length l /\\\n    length l2 <= length l.\nProof.\n apply (split_len' list_ind2).\nQed.\n\n\n\n\n\n\n\n\n(* ========== Euclidean division correction =========== *)\n\nDefinition divRel (args:nat*nat) (res:nat*nat) : Prop := \n          let (n,d):=args in let (q,r):=res in q*d+r=n /\\ r<d. \n\nDefinition divPre (args:nat*nat) : Prop := (snd args)<>0.\n\n\nTheorem div_correct : forall (p:nat*nat),  divPre p -> divRel p (div p). \nProof. \n  unfold divPre, divRel. \n  intro p. \n  (* we make use of the specialised induction principle to conduct the proof... *) \n  functional induction (div p); simpl. \n  - intro H; elim H; reflexivity. \n  - (* a first trick: we expand (div (a-b,b)) in order to get rid of the let (q,r)=... *) \n    replace (div (a-b,b)) with (fst (div (a-b,b)),snd (div (a-b,b))) in IHp0. \n    + simpl in *. intro H; elim (IHp0 H); intros. split. \n      * (* again a similar trick: we expand \"x\" and \"y0\" in order to use an hypothesis *) \n        change (b + (fst (x,y0)) * b + (snd (x,y0)) = a). \n        rewrite <- e1. lia. \n      * (* and again... *) \n        change (snd (x,y0)<b); rewrite <- e1; assumption. \n    + symmetry.  apply surjective_pairing. \n  - auto. \nQed. \n\n\n", "meta": {"author": "jotorres526", "repo": "VF2022", "sha": "52376d15e905753f1c4f3aa6be86946c544895ec", "save_path": "github-repos/coq/jotorres526-VF2022", "path": "github-repos/coq/jotorres526-VF2022/VF2022-52376d15e905753f1c4f3aa6be86946c544895ec/Aula03/lesson3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7033930134425319}}
{"text": "\n\nFixpoint plus (n m : nat) : nat :=\n\tmatch n with\n\t\t| O => m\n\t\t| S n' => S (plus n' m)\n\tend.\n\nFixpoint mul (n m : nat) : nat :=\n\tmatch n with\n\t\t| O => O\n\t\t| S O => m\n\t\t| S n' => (plus m (mul n' m))\n\tend.\n\n\n\nFixpoint factoria (n : nat) : nat :=\n\tmatch n with\n\t\t| O => (S O)\n\t\t| S n' => (mul n (factoria n'))\n\tend.\n\n(*Notation \"x + y\" := (plus x y) : nat_scope.*)\n\n\nEval compute in (mul 3 8).\nEval compute in (factoria 3).\nEval compute in (22 + 11).\nEval compute in (eq 22 22).\n", "meta": {"author": "middlefeng", "repo": "SoftwareFoundationsExercise", "sha": "a4033ac6eb2936117ddd1a7ecde6012261bd3ab6", "save_path": "github-repos/coq/middlefeng-SoftwareFoundationsExercise", "path": "github-repos/coq/middlefeng-SoftwareFoundationsExercise/SoftwareFoundationsExercise-a4033ac6eb2936117ddd1a7ecde6012261bd3ab6/Ch1_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465134460244, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.7033923337353053}}
{"text": "Require Import XRbase.\nRequire Import XR_Ifp.\nLocal Open Scope XR_scope.\n\nImplicit Type r : R.\n\nDefinition Rmin (x y:R) : R :=\n  match Rle_dec x y with\n    | left _ => x\n    | right _ => y\n  end.\n\nLemma Rmin_case : forall r1 r2 (P:R -> Type), P r1 -> P r2 -> P (Rmin r1 r2).\nProof.\n  intros x y p px py.\n  unfold Rmin.\n  destruct (Rle_dec x y) as [ le | nle ].\n  exact px.\n  exact py.\nQed.\n\nLemma Rmin_case_strong : forall r1 r2 (P:R -> Type), \n  (r1 <= r2 -> P r1) -> (r2 <= r1 -> P r2) -> P (Rmin r1 r2).\nProof.\n  intros x y p hxy hyx.\n  unfold Rmin.\n  destruct (Rle_dec x y) as [ le | nle ].\n  apply hxy. exact le.\n  apply hyx.\n  left.\n  apply Rnot_le_lt.\n  exact nle.\nQed.\n\nLemma Rmin_Rgt_l : forall r1 r2 r, r < Rmin r1 r2 -> r < r1 /\\ r < r2.\nProof.\n  intros x y z h.\n  unfold Rmin in h.\n  destruct (Rle_dec x y).\n  {\n    split.\n    { exact h. }\n    { destruct r as [ lt | eq ].\n      { apply Rlt_trans with x. exact h. exact lt. }\n      { subst x. exact h. }\n    }\n  }\n  { apply Rnot_le_lt in n. split.\n    { apply Rlt_trans with y. exact h. exact n. }\n    { exact h. }\n  }\nQed.\n\nLemma Rmin_Rgt_r : forall r1 r2 r, r < r1 /\\ r < r2 -> r < Rmin r1 r2.\nProof.\n  intros x y z [hx hy].\n  unfold Rmin.\n  destruct (Rle_dec x y) as [ h | h ].\n  exact hx. exact hy.\nQed.\n\nLemma Rmin_Rgt : forall r1 r2 r, r < Rmin r1 r2 <-> r < r1 /\\ r < r2.\nProof.\n  intros x y z.\n  split.\n  { intro h. apply Rmin_Rgt_l. exact h. }\n  { intro h. apply Rmin_Rgt_r. exact h. }\nQed.\n\nLemma Rmin_l : forall x y:R, Rmin x y <= x.\nProof.\n  intros x y.\n  unfold Rmin.\n  destruct (Rle_dec x y) as [ h | h ].\n  right. reflexivity.\n  left. apply Rnot_le_lt. exact h.\nQed.\n\nLemma Rmin_r : forall x y:R, Rmin x y <= y.\nProof.\n  intros x y.\n  unfold Rmin.\n  destruct (Rle_dec x y).\n  exact r.\n  right. reflexivity.\nQed.\n\nLemma Rmin_left : forall x y, x <= y -> Rmin x y = x.\nProof.\n  intros x y h.\n  apply Rmin_case_strong.\n  intro same. reflexivity.\n  intro converse.\n  apply Rle_antisym. exact converse. exact h.\nQed.\n\nLemma Rmin_right : forall x y, y <= x -> Rmin x y = y.\nProof.\n  intros x y h.\n  unfold Rmin.\n  destruct (Rle_dec x y).\n  apply Rle_antisym. exact r. exact h.\n  reflexivity.\nQed.\n\nLemma Rle_min_compat_r : forall x y z, x <= y -> Rmin x z <= Rmin y z.\nProof.\n  intros x y z h.\n  apply Rmin_case_strong.\n  intro hxz. apply Rmin_case_strong.\n  intro hyz. exact h.\n  intro hzy. exact hxz.\n  intro hzx. apply Rmin_case_strong.\n  intro hyz. apply Rle_trans with x. exact hzx. exact h.\n  intro hzy. right. reflexivity.\nQed.\n\nLemma Rle_min_compat_l : forall x y z, x <= y -> Rmin z x <= Rmin z y.\nProof.\n  intros x y z hxy.\n  apply Rmin_case_strong.\n  {\n    intro hzx. apply Rmin_case_strong.\n    {\n      intro hzy. right. reflexivity.\n    }\n    {\n      intro hyz. apply Rle_trans with x. exact hzx. exact hxy.\n    }\n  }\n  {\n    intro hxz. apply Rmin_case_strong.\n    {\n      intro hzy. exact hxz.\n    }\n    {\n      intro hyz. exact hxy.\n    }\n  }\nQed.\n\nLemma Rmin_comm : forall x y:R, Rmin x y = Rmin y x.\nProof.\n  intros x y.\n  apply Rmin_case_strong.\n  {\n    intro hxy. apply Rmin_case_strong.\n    {\n      intro hyx. apply Rle_antisym. exact hxy. exact hyx.\n    }\n    {\n      intro hxy'. reflexivity.\n    }\n  }\n  {\n    intro hyx. apply Rmin_case_strong.\n    {\n      intro hyx'. reflexivity.\n    }\n    {\n      intro hxy. apply Rle_antisym. exact hyx. exact hxy.\n    }\n  }\nQed.\n\nLemma Rmin_stable_in_posreal : forall x y:posreal, R0 < Rmin x y.\nProof.\n  intros x y.\n  apply Rmin_case.\n  apply cond_pos.\n  apply cond_pos.\nQed.\n\nLemma Rmin_pos : forall x y:R, R0 < x -> R0 < y -> R0 < Rmin x y.\nProof.\n  intros x y hx hy.\n  apply Rmin_case.\n  exact hx.\n  exact hy.\nQed.\n\nLemma Rmin_glb : forall x y z:R, z <= x -> z <= y -> z <= Rmin x y.\nProof.\n  intros x y z hzx hzy.\n  apply Rmin_case.\n  exact hzx.\n  exact hzy.\nQed.\n\nLemma Rmin_glb_lt : forall x y z:R, z < x -> z < y -> z < Rmin x y.\nProof.\n  intros x y z hzx hzy.\n  apply Rmin_case.\n  exact hzx. exact hzy.\nQed.\n\nDefinition Rmax (x y:R) : R :=\n  match Rle_dec x y with\n    | left _ => y\n    | right _ => x\n  end.\n\nLemma Rmax_case : forall r1 r2 (P:R -> Type), P r1 -> P r2 -> P (Rmax r1 r2).\nProof.\n  intros x y p px py.\n  unfold Rmax. destruct (Rle_dec x y) as [ h | h ].\n  exact py. exact px.\nQed.\n\nLemma Rmax_case_strong : forall r1 r2 (P:R -> Type),\n  (r2 <= r1 -> P r1) -> (r1 <= r2 -> P r2) -> P (Rmax r1 r2).\nProof.\n  intros x y p px py.\n  unfold Rmax. destruct (Rle_dec x y) as [ h | h ].\n  apply py. exact h.\n  apply px.\n  apply Rlt_le. apply Rnot_le_lt. exact h.\nQed.\n\nLemma Rmax_Rle : forall r1 r2 r, r <= Rmax r1 r2 <-> r <= r1 \\/ r <= r2.\nProof.\n  intros x y z.\n  split.\n  {\n    intro h. unfold Rmax in h. destruct (Rle_dec x y) as [ h' | h' ].\n    right. exact h.\n    left. exact h.\n  }\n  {\n    intros [ hzx | hzy ].\n    apply Rmax_case_strong.\n    {\n      intro hyx. exact hzx.\n    }\n    {\n      intro hxy. apply Rle_trans with x. exact hzx. exact hxy.\n    }\n    apply Rmax_case_strong.\n    { intro yx. apply Rle_trans with y. exact hzy. exact yx. }\n    { intro hxy. exact hzy. }\n  }\nQed.\n\nLemma Rmax_comm : forall x y:R, Rmax x y = Rmax y x.\nProof.\n  intros x y.\n  apply Rmax_case_strong;apply Rmax_case_strong;intros.\n  apply Rle_antisym;assumption.\n  reflexivity.\n  reflexivity.\n  apply Rle_antisym;assumption.\nQed.\n\nNotation RmaxSym := Rmax_comm (only parsing).\n\nLemma Rmax_l : forall x y:R, x <= Rmax x y.\nProof.\n  intros x y.\n  apply Rmax_case_strong.\n  intro. right. reflexivity.\n  intro;assumption.\nQed.\n\nLemma Rmax_r : forall x y:R, y <= Rmax x y.\nProof.\n  intros x y.\n  apply Rmax_case_strong.\n  intro;assumption.\n  intro. right. reflexivity.\nQed.\n\nNotation RmaxLess1 := Rmax_l (only parsing).\nNotation RmaxLess2 := Rmax_r (only parsing).\n\nLemma Rmax_left : forall x y, y <= x -> Rmax x y = x.\nProof.\n  intros x y h.\n  apply Rmax_case_strong.\n  intro;reflexivity.\n  intro h'. apply Rle_antisym;assumption.\nQed.\n\nLemma Rmax_right : forall x y, x <= y -> Rmax x y = y.\nProof.\n  intros x y h.\n  apply Rmax_case_strong.\n  intro h'. apply Rle_antisym;assumption.\n  reflexivity.\nQed.\n\nLemma Rle_max_compat_r : forall x y z, x <= y -> Rmax x z <= Rmax y z.\nProof.\n  intros x y z hxy.\n  apply Rmax_case_strong;apply Rmax_case_strong.\n  intros hzy hzx. exact hxy.\n  intros hyz hzx. apply Rle_trans with y;assumption.\n  intros hzy hxz. exact hzy.\n  intros hyz hxz. right. reflexivity.\nQed.\n\nLemma Rle_max_compat_l : forall x y z, x <= y -> Rmax z x <= Rmax z y.\nProof.\n  intros x y z hxy.\n  apply Rmax_case_strong;apply Rmax_case_strong.\n  intros;right;reflexivity.\n  intros;assumption.\n  intros hyz hzx. apply Rle_trans with y;assumption.\n  intros;assumption.\nQed.\n\nLemma RmaxRmult :\n  forall (p q:R) r, R0 <= r -> Rmax (r * p) (r * q) = r * Rmax p q.\nProof.\n  intros x y z h.\n  apply Rmax_case_strong;apply Rmax_case_strong.\n  { intros;reflexivity. }\n  {\n    intros hxy hyx.\n    apply Rle_antisym.\n    apply Rmult_le_compat_l.\n    exact h. exact hxy. exact hyx.\n  }\n  {\n    intros hyx hxy.\n    apply Rle_antisym.\n    apply Rmult_le_compat_l.\n    exact h. exact hyx. exact hxy.\n  }\n  { intros;reflexivity. }\nQed.\n\n\nLemma Rmax_stable_in_negreal : forall x y:negreal, Rmax x y < R0.\nProof.\n  intros x y.\n  apply Rmax_case.\n  apply cond_neg.\n  apply cond_neg.\nQed.\n\nLemma Rmax_lub : forall x y z:R, x <= z -> y <= z -> Rmax x y <= z.\nProof.\n  intros x y z hxz hyz.\n  apply Rmax_case;assumption.\nQed.\n\nLemma Rmax_lub_lt : forall x y z:R, x < z -> y < z -> Rmax x y < z.\nProof.\n  intros x y z hxz hyz.\n  apply Rmax_case;assumption.\nQed.\n\nLemma Rmax_Rlt : forall x y z, \n  Rmax x y < z <-> x < z /\\ y < z.\nProof.\n  intros x y z.\n  apply Rmax_case_strong.\n  {\n    intro hyx. split.\n    {\n      intro hxz. split.\n      { exact hxz. }\n      {\n        destruct hyx as [ hyx | hyx ].\n        apply Rlt_trans with x;assumption.\n        subst y. exact hxz.\n      }\n    }\n    {\n      intros [ hxz hyz ].\n      exact hxz.\n    }\n  }\n  {\n    intro hxy.\n    split.    \n    {\n      intro hyz. split.\n      {\n        destruct hxy as [ hlt | heq ].\n        apply Rlt_trans with y;assumption.\n        subst y. assumption.\n      }\n      { assumption. }\n    }\n    { intros [ hxz hyz ] ; assumption. }\n  }\nQed.\n\nLemma Rmax_neg : forall x y:R, x < R0 -> y < R0 -> Rmax x y < R0.\nProof.\n  intros x y hx hy.\n  apply Rmax_case;assumption.\nQed.\n\nLemma Rcase_abs : forall r, {r < R0} + {R0 <= r}.\nProof.\n  intro x.\n  destruct (total_order_T x R0) as [ [ hlt | heq ] | hgt ].\n  left. assumption.\n  subst x. right. right. reflexivity.\n  right;left;assumption.\nQed.\n\nDefinition Rabs r : R :=\n  match Rcase_abs r with\n    | left _ => - r\n    | right _ => r\n  end.\n\nLemma Rabs_R0 : Rabs R0 = R0.\nProof.\n  unfold Rabs.\n  destruct (Rcase_abs R0).\n  rewrite Ropp_0. reflexivity.\n  reflexivity.\nQed.\n\nLemma Rabs_R1 : Rabs R1 = R1.\nProof.\n  unfold Rabs.\n  destruct (Rcase_abs R1).\n  exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with R1. apply Rlt_0_1. assumption.\n  reflexivity.\nQed.\n\nLemma Rabs_no_R0 : forall r, r <> R0 -> Rabs r <> R0.\nProof.\n  intros x h eq.\n  apply h.\n  unfold Rabs in eq.\n  destruct (Rcase_abs x).\n  apply Rplus_eq_reg_l with (-x).\n  rewrite Rplus_opp_l.\n  rewrite eq.\n  rewrite Rplus_0_l.\n  reflexivity.\n  exact eq.\nQed.\n\nLemma Rabs_left : forall r, r < R0 -> Rabs r = - r.\nProof.\n  intros x h.\n  unfold Rabs. destruct (Rcase_abs x).\n  reflexivity.\n  destruct r.\n  exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x;assumption.\n  subst x. rewrite Ropp_0. reflexivity.\nQed.\n\nLemma Rabs_right : forall r, R0 <= r -> Rabs r = r.\nProof.\n  intros x h.\n  destruct h as [ h | h ].\n  unfold Rabs. destruct (Rcase_abs x).\n  exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x;assumption.\n  reflexivity.\n  subst x.\n  exact Rabs_R0.\nQed.\n\nLemma Rabs_left1 : forall a:R, a <= R0 -> Rabs a = - a.\nProof.\n  intros x h.\n  destruct h as [ lt | eq ].\n  {\n    unfold Rabs. destruct (Rcase_abs x).\n    reflexivity.\n    destruct r as [ lt' | eq' ].\n    exfalso. apply Rlt_irrefl with x. apply Rlt_trans with R0;assumption.\n    subst x. rewrite Ropp_0. reflexivity.\n  }\n  subst x. rewrite Ropp_0. exact Rabs_R0.\nQed.\n\nLemma Rabs_pos : forall x:R, R0 <= Rabs x.\nProof.\n  intros x.\n  unfold Rabs. destruct (Rcase_abs x).\n  left. apply Rplus_lt_reg_l with x. rewrite Rplus_0_r.\n  rewrite Rplus_opp_r. exact r.\n  exact r.\nQed.\n\nLemma Rle_abs : forall x:R, x <= Rabs x.\nProof.\n  intros x.\n  unfold Rabs. destruct (Rcase_abs x).\n  left. apply Rlt_trans with R0. exact r.\n  apply Rplus_lt_reg_l with x. rewrite Rplus_0_r. rewrite Rplus_opp_r.\n  exact r.\n  right. reflexivity.\nQed.\n\nDefinition RRle_abs := Rle_abs.\n\nLemma Rabs_le : forall a b, -b <= a <= b -> Rabs a <= b.\nProof.\n  intros x y [ hyx hxy ].\n  unfold Rabs. destruct (Rcase_abs x).\n  apply Rplus_le_reg_r with x.\n  rewrite Rplus_opp_l.\n  apply Rplus_le_reg_l with (-y).\n  rewrite <- Rplus_assoc.\n  rewrite Rplus_opp_l.\n  rewrite Rplus_0_l.\n  rewrite Rplus_0_r.\n  exact hyx.\n  exact hxy.\nQed.\n\nLemma Rabs_pos_eq : forall x:R, R0 <= x -> Rabs x = x.\nProof.\n  intros x h.\n  destruct h as [ lt | eq ].\n  unfold Rabs. destruct (Rcase_abs x).\n  exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x;assumption.\n  reflexivity.\n  subst x. exact Rabs_R0.\nQed.\n\nLemma Rabs_Rabsolu : forall x:R, Rabs (Rabs x) = Rabs x.\nProof.\n  intro x.\n  unfold Rabs.\n  destruct (Rcase_abs x).\n  destruct (Rcase_abs (-x)).\n  exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x.\n  apply Rplus_lt_reg_l with (-x). rewrite Rplus_opp_l.\n  rewrite Rplus_0_r. exact r0. exact r.\n  reflexivity.\n  destruct (Rcase_abs x).\n  destruct r.\n  exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x;assumption.\n  subst x. rewrite Ropp_0. reflexivity.\n  reflexivity.\nQed.\n\nLemma Rabs_pos_lt : forall x:R, x <> R0 -> R0 < Rabs x.\nProof.\n  intros x h.\n  unfold Rabs. destruct (Rcase_abs x).\n  apply Rplus_lt_reg_l with x.\n  rewrite Rplus_0_r.\n  rewrite Rplus_opp_r.\n  exact r.\n  destruct r.\n  exact H.\n  subst x. exfalso.\n  apply h. reflexivity.\nQed.\n\nLemma Rabs_minus_sym : forall x y:R, Rabs (x - y) = Rabs (y - x).\nProof.\n  intros x y.\n  unfold Rabs.\n  destruct (Rcase_abs (x-y));destruct (Rcase_abs (y-x));\n  unfold Rminus;\n  repeat (rewrite Ropp_plus_distr);\n  repeat (rewrite Ropp_involutive).\n  {\n    exfalso.\n    unfold Rminus in r, r0.\n    apply (Rplus_lt_compat_r y) in r.\n    rewrite Rplus_assoc in r.\n    rewrite Rplus_opp_l in r.\n    rewrite Rplus_0_r in r.\n    rewrite Rplus_0_l in r.\n    apply (Rplus_lt_compat_r x) in r0.\n    rewrite Rplus_assoc in r0.\n    rewrite Rplus_opp_l in r0.\n    rewrite Rplus_0_l in r0.\n    rewrite Rplus_0_r in r0.\n    apply Rlt_irrefl with x.\n    apply Rlt_trans with y;assumption.\n  }\n  {\n    rewrite (Rplus_comm _ y).\n    reflexivity.\n  }\n  {\n    rewrite Rplus_comm.\n    reflexivity.\n  }\n  {\n    destruct r.\n    {\n      destruct r0.\n      {\n        exfalso.\n        unfold Rminus in H.\n        unfold Rminus in H0.\n        apply (Rplus_lt_compat_r y) in H.\n        apply (Rplus_lt_compat_r x) in H0.\n        repeat (rewrite Rplus_assoc in H, H0).\n        rewrite Rplus_opp_l in H, H0.\n        rewrite Rplus_0_l in H, H0.\n        rewrite Rplus_0_r in H, H0.\n        apply Rlt_irrefl with x.\n        apply Rlt_trans with y;assumption.\n    }\n    unfold Rminus in *.\n    apply (Rplus_eq_compat_r x) in H0.\n    rewrite Rplus_assoc in H0.\n    rewrite Rplus_opp_l in H0.\n    rewrite Rplus_0_l in H0.\n    rewrite Rplus_0_r in H0.\n    subst y.\n    rewrite Rplus_comm. reflexivity.\n  }\n  apply (Rplus_eq_compat_r y) in H.\n  unfold Rminus in H.\n  rewrite Rplus_assoc in H.\n  rewrite Rplus_opp_l in H.\n  rewrite Rplus_0_r in H.\n  rewrite Rplus_0_l in H.\n  subst y.\n  reflexivity.\n  }\nQed.\n\nLemma Rabs_mult : forall x y:R, Rabs (x * y) = Rabs x * Rabs y.\nProof.\n  intros x y.\n  unfold Rabs.\n  destruct (Rcase_abs x);\n  destruct (Rcase_abs y);\n  destruct (Rcase_abs (x*y)).\n  {\n    exfalso.\n    apply Rlt_irrefl with (x*y).\n    apply Rlt_trans with R0.\n    assumption.\n    rewrite <- Ropp_involutive with (x*y).\n    rewrite Ropp_mult_distr_l.\n    rewrite Ropp_mult_distr_r.\n    apply Rmult_lt_0_compat.\n    apply Rplus_lt_reg_l with x.\n    rewrite Rplus_0_r.\n    rewrite Rplus_opp_r.\n    assumption.\n    apply Rplus_lt_reg_l with y.\n    rewrite Rplus_opp_r.\n    rewrite Rplus_0_r.\n    assumption.\n  }\n  {\n    rewrite <- Ropp_mult_distr_l.\n    rewrite <- Ropp_mult_distr_r.\n    rewrite Ropp_involutive.\n    reflexivity.\n  }\n  {\n    rewrite Ropp_mult_distr_l.\n    reflexivity.\n  }\n  {\n    destruct r1.\n    destruct r0.\n    exfalso.\n    apply Rlt_irrefl with (x*y).\n    apply Rlt_trans with R0.\n    apply Rplus_lt_reg_l with (- (x*y)).\n    rewrite Rplus_opp_l.\n    rewrite Rplus_0_r.\n    rewrite Ropp_mult_distr_l.\n    apply Rmult_lt_0_compat.\n    apply Rplus_lt_reg_l with x.\n    rewrite Rplus_0_r.\n    rewrite Rplus_opp_r.\n    assumption.\n    assumption.\n    assumption.\n    subst y. do 2 rewrite Rmult_0_r. reflexivity.\n    rewrite <- H. rewrite <- Ropp_mult_distr_l.\n    rewrite <- H. rewrite Ropp_0. reflexivity.\n  }\n  {\n    rewrite Ropp_mult_distr_r.\n    reflexivity.\n  }\n  {\n    destruct r1.\n    destruct r.\n    exfalso. apply Rlt_irrefl with (x*y).\n    apply Rlt_trans with R0.\n    apply Rplus_lt_reg_l with (- (x*y)).\n    rewrite Rplus_opp_l.\n    rewrite Rplus_0_r.\n    rewrite Ropp_mult_distr_r.\n    apply Rmult_lt_0_compat.\n    assumption.\n    apply Rplus_lt_reg_l with y.\n    rewrite Rplus_0_r.\n    rewrite Rplus_opp_r.\n    assumption.\n    assumption.\n    subst x. do 2 rewrite Rmult_0_l. reflexivity.\n    rewrite <- H. rewrite <- Ropp_mult_distr_r.\n    rewrite <- H. rewrite Ropp_0. reflexivity.\n  }\n  {\n    destruct r. destruct r0.\n    exfalso. apply Rlt_irrefl with (x*y).\n    apply Rlt_trans with R0.\n    assumption.\n    apply Rmult_lt_0_compat.\n    assumption.\n    assumption.\n    subst y. rewrite Rmult_0_r. rewrite Ropp_0. reflexivity.\n    subst x. rewrite Rmult_0_l. rewrite Ropp_0. reflexivity.\n  }\n  { reflexivity. }\nQed.\n\nLemma Rabs_Rinv : forall r, r <> R0 -> Rabs (/ r) = / Rabs r.\nProof.\n  intros x h.\n  unfold Rabs.\n  destruct (Rcase_abs x);destruct (Rcase_abs (/ x)).\n  {\n    rewrite Ropp_inv_permute.\n    reflexivity.\n    assumption.\n  }\n  {\n    destruct r0.\n    exfalso.\n    apply Rinv_lt_0_compat in r.\n    apply Rlt_irrefl with R0.\n    apply Rlt_trans with (/ x);assumption.\n    rewrite <- H.\n    rewrite <- Ropp_inv_permute.\n    rewrite <- H.\n    rewrite Ropp_0. reflexivity. assumption.\n  }\n  {\n    destruct r.\n    exfalso.\n    apply Rlt_irrefl with R0.\n    apply Rlt_trans with x.\n    assumption.\n    apply Rinv_lt_0_compat in r0.\n    rewrite Rinv_involutive in r0.\n    assumption. assumption.\n    subst x. exfalso. apply h. reflexivity.\n  }\n  {\n    reflexivity.\n  }\nQed.\n\nLemma Rabs_Ropp : forall x:R, Rabs (- x) = Rabs x.\nProof.\n  intro x.\n  unfold Rabs.\n  destruct (Rcase_abs (-x));\n  destruct (Rcase_abs x).\n  {\n    exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x.\n    apply Rplus_lt_reg_l with (-x).\n    rewrite Rplus_0_r. rewrite Rplus_opp_l. assumption.\n    assumption.\n  }\n  {\n    rewrite Ropp_involutive.\n    reflexivity.\n  }\n  {\n    reflexivity.\n  }\n  {\n    destruct r.\n    destruct r0.\n    exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x.\n    assumption.\n    apply Rplus_lt_reg_l with (-x). rewrite Rplus_0_r.\n    rewrite Rplus_opp_l. assumption.\n    subst x. rewrite Ropp_0. reflexivity.\n    rewrite <- H. rewrite <- Ropp_involutive with x. rewrite <- H.\n    rewrite Ropp_0. reflexivity.\n  }\nQed.\n\nLemma Rabs_triang : forall a b:R, Rabs (a + b) <= Rabs a + Rabs b.\nProof.\n  intros x y.\n  unfold Rabs.\n  destruct (Rcase_abs x);\n  destruct (Rcase_abs y);\n  destruct (Rcase_abs (x+y)).\n  {\n    rewrite Ropp_plus_distr. right. reflexivity.\n  }\n  {\n    destruct r1.\n    exfalso.\n    apply Rlt_irrefl with R0.\n    apply Rlt_trans with (x+y).\n    assumption.\n    rewrite <- Rplus_0_l with R0.\n    apply Rplus_lt_compat. assumption. assumption.\n    rewrite <- H. rewrite <- Ropp_plus_distr. rewrite <- H.\n    rewrite Ropp_0. right. reflexivity.\n  }\n  {\n    rewrite Ropp_plus_distr.\n    apply Rplus_le_compat_l.\n    apply Rplus_le_reg_r with y.\n    rewrite Rplus_opp_l.\n    apply Rle_trans with y.\n    assumption.\n    pattern y at 1;rewrite <- Rplus_0_l with y.\n    apply Rplus_le_compat_r. assumption.\n  }\n  {\n    apply Rplus_le_compat_r.\n    left.\n    apply Rlt_trans with R0. assumption.\n    apply Rplus_lt_reg_l with x. rewrite Rplus_opp_r. rewrite Rplus_0_r.\n    assumption.\n  }\n  {\n    rewrite Ropp_plus_distr.\n    apply Rplus_le_compat_r.\n    apply Rle_trans with R0.\n    apply Rplus_le_reg_l with x.\n    rewrite Rplus_opp_r.\n    rewrite Rplus_0_r.\n    assumption.\n    assumption.\n  }\n  {\n    apply Rplus_le_compat_l.\n    apply Rle_trans with R0.\n    left. assumption.\n    left. apply Rplus_lt_reg_r with y.\n    rewrite Rplus_0_l. rewrite Rplus_opp_l. assumption.\n  }\n  {\n    rewrite Ropp_plus_distr.\n    apply Rplus_le_compat.\n    apply Rle_trans with R0.\n    apply Rplus_le_reg_l with x.\n    rewrite Rplus_opp_r.\n    rewrite Rplus_0_r.\n    assumption.\n    assumption.\n    apply Rle_trans with R0.\n    apply Rplus_le_reg_l with y.\n    rewrite Rplus_0_r.\n    rewrite Rplus_opp_r.\n    assumption.\n    assumption.\n  }\n  {\n    right. reflexivity.\n  }\nQed.\n\nLemma Rabs_triang_inv : forall a b:R, Rabs a - Rabs b <= Rabs (a - b).\nProof.\n  intros a b.\n  unfold Rabs.\n  destruct (Rcase_abs a);\n  destruct (Rcase_abs b);\n  destruct (Rcase_abs (a-b));\n  unfold Rminus in *;\n  try(rewrite Ropp_plus_distr in *);\n  try(rewrite Ropp_involutive in *).\n  {\n    right. reflexivity.\n  }\n  {\n    destruct r1.\n    left. apply Rlt_trans with R0.\n    apply Rplus_lt_reg_l with a.\n    rewrite <- Rplus_assoc.\n    rewrite Rplus_opp_r.\n    rewrite Rplus_0_r.\n    rewrite Rplus_0_l.\n    apply Rplus_lt_reg_r with (-b).\n    rewrite Rplus_opp_r. assumption. assumption.\n    rewrite <- H. right.\n    apply Rplus_eq_reg_l with a.\n    apply Rplus_eq_reg_r with (-b).\n    repeat (rewrite Rplus_assoc).\n    rewrite Rplus_opp_r.\n    repeat (rewrite <- Rplus_assoc).\n    rewrite Rplus_opp_r.\n    rewrite Rplus_0_r.\n    rewrite Rplus_0_r.\n    rewrite <- H. reflexivity.\n  }\n  {\n    apply Rplus_le_compat_l.\n    apply Rle_trans with R0.\n    apply Rplus_le_reg_r with b.\n    rewrite Rplus_opp_l. rewrite Rplus_0_l. assumption. assumption.\n  }\n  {\n    apply Rplus_le_compat_r.\n    destruct r0.\n    destruct r1.\n    exfalso.\n    apply (Rplus_lt_compat_r b) in H0.\n    rewrite Rplus_0_l in H0.\n    rewrite Rplus_assoc in H0.\n    rewrite Rplus_opp_l in H0.\n    rewrite Rplus_0_r in H0.\n    apply Rlt_irrefl with R0.\n    apply Rlt_trans with b.\n    assumption. apply Rlt_trans with a.\n    assumption. assumption.\n    apply (Rplus_eq_compat_r b) in H0.\n    rewrite Rplus_assoc in H0.\n    rewrite Rplus_opp_l in H0.\n    rewrite Rplus_0_r in H0.\n    rewrite Rplus_0_l in H0.\n    subst b.\n    exfalso. apply Rlt_irrefl with R0.\n    apply Rlt_trans with a; assumption.\n    subst b.\n    rewrite Ropp_0 in r1.\n    rewrite Rplus_0_r in r1.\n    destruct r1.\n    exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with a;assumption.\n    subst a. exfalso. apply Rlt_irrefl with R0;assumption.\n  }\n  {\n    apply Rplus_le_compat_r.\n    apply (Rplus_lt_compat_r b) in r1.\n    rewrite Rplus_assoc in r1.\n    rewrite Rplus_opp_l in r1.\n    rewrite Rplus_0_r in r1.\n    rewrite Rplus_0_l in r1.\n    destruct r.\n    exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with a. assumption.\n    apply Rlt_trans with b. assumption. assumption.\n    subst a. exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with b;assumption.\n  }\n  {\n    apply Rplus_le_compat_l.\n    left. apply Rlt_trans with R0. assumption.\n    apply Rplus_lt_reg_l with b. rewrite Rplus_0_r.\n    rewrite Rplus_opp_r. assumption.\n  }\n  {\n    destruct r.\n    destruct r0.\n    apply (Rplus_lt_compat_r b) in r1.\n    rewrite Rplus_assoc in r1.\n    rewrite Rplus_opp_l in r1.\n    rewrite Rplus_0_r in r1.\n    rewrite Rplus_0_l in r1.\n    left.\n    apply Rplus_lt_reg_l with a.\n    repeat (rewrite <- Rplus_assoc).\n    rewrite Rplus_opp_r. rewrite Rplus_0_l.\n    apply Rplus_lt_reg_r with b.\n    repeat (rewrite Rplus_assoc).\n    rewrite Rplus_opp_l. rewrite Rplus_0_r.\n    apply Rplus_lt_compat. assumption. assumption.\n    subst b. rewrite Ropp_0 in *. rewrite Rplus_0_r in *.\n    exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with a;assumption.\n    subst a. rewrite Ropp_0 in *. rewrite Rplus_0_l in *.\n    rewrite Rplus_0_l. left.\n    apply Rlt_trans with R0. assumption.\n    apply Rplus_lt_reg_l with (-b). rewrite Rplus_0_r.\n    rewrite Rplus_opp_l. assumption.\n  }\n  { right. reflexivity. }\nQed.\n\nLemma Rabs_case : forall x:R, Rabs x = x /\\ R0 <= x \\/ Rabs x = -x /\\ x < R0.\n  intro x.\n  unfold Rabs. destruct (Rcase_abs x).\n  right. split. reflexivity. assumption.\n  left. split. reflexivity. assumption.\nQed.\n\nLemma Rabs_triang_inv2 : forall a b:R, Rabs (Rabs a - Rabs b) <= Rabs (a - b).\nProof.\n  intros x y.\n  unfold Rminus.\n  destruct (Rabs_case x) as [ [ eqx hx ] | [ eqx hx ] ];\n  destruct (Rabs_case y) as [ [ eqy hy ] | [ eqy hy ] ].\n  {\n    rewrite eqx. rewrite eqy.\n    right. reflexivity.\n  }\n  {\n    rewrite eqx. rewrite eqy.\n    rewrite Ropp_involutive.\n    destruct (Rabs_case (x+y)) as [ [ eqxy hxy ] | [ eqxy hxy ] ];\n    destruct (Rabs_case (x+-y)) as [ [ eqxym hxym ] | [ eqxym hxym ] ].\n    {\n      rewrite eqxy. rewrite eqxym.\n      apply Rplus_le_compat_l.\n      left. apply Rlt_trans with R0. assumption.\n      rewrite <- Ropp_0.\n      apply Ropp_lt_contravar.\n      assumption.\n    }\n    {\n      rewrite eqxy;rewrite eqxym.\n      rewrite Ropp_plus_distr. rewrite Ropp_involutive.\n      apply Rplus_le_compat_r.\n      clear eqx eqy eqxy eqxym.\n      destruct hx as [ lt | eq ].\n      exfalso. apply Rlt_irrefl with R0. apply Rlt_trans with x.\n      assumption. apply Rlt_trans with y.\n      apply Rplus_lt_reg_r with (-y).\n      rewrite Rplus_opp_r. assumption.\n      assumption.\n      subst x. right. rewrite Ropp_0. reflexivity.\n    }\n    {\n      rewrite eqxy;rewrite eqxym.\n      rewrite Ropp_plus_distr.\n      apply Rplus_le_compat_r.\n      apply Rle_trans with R0.\n      rewrite <- Ropp_0.\n      apply Ropp_le_contravar.\n      assumption. assumption.\n    }\n    {\n      rewrite eqxy;rewrite eqxym.\n      rewrite Ropp_plus_distr.\n      rewrite Ropp_plus_distr.\n      rewrite Ropp_involutive.\n      apply Rplus_le_compat_l.\n      clear eqx eqy eqxy eqxym.\n      destruct hx as [ hx | hx ].\n      exfalso. apply Rlt_irrefl with R0.\n      apply Rlt_trans with x. assumption.\n      apply Rlt_trans with y.\n      apply Rplus_lt_reg_r with (-y).\n      rewrite Rplus_opp_r.\n      assumption.\n      assumption.\n      subst x. rewrite Rplus_0_l in *.\n      exfalso. apply Rlt_irrefl with y. apply Rlt_trans with R0.\n      assumption.\n      apply Ropp_lt_cancel.\n      rewrite Ropp_0. assumption.\n    }\n  }\n  {\n    destruct hy as [ hy | hy ].\n    {\n      rewrite eqx;rewrite eqy.\n      rewrite <- Ropp_plus_distr.\n      rewrite Rabs_Ropp.\n      destruct (Rabs_case (x+y)) as [ [ eqxy hxy ] | [ eqxy hxy ] ];\n      destruct (Rabs_case (x+-y)) as [ [ eqxym hxym ] | [ eqxym hxym ] ].\n      {\n        rewrite eqxy. rewrite eqxym.\n        apply Rplus_le_compat_l.\n        clear eqx eqy eqxy eqxym.\n        destruct hxym.\n        {\n          exfalso.\n          apply Rlt_irrefl with R0.\n          apply Rlt_trans with y.\n          assumption.\n          apply Rlt_trans with x.\n          apply Rplus_lt_reg_r with (-y).\n          rewrite Rplus_opp_r. assumption.\n          assumption.\n        }\n        {\n          apply (Rplus_eq_compat_r y) in H.\n          rewrite Rplus_assoc in H.\n          rewrite Rplus_opp_l in H.\n          rewrite Rplus_0_l in H.\n          rewrite Rplus_0_r in H.\n          subst y. exfalso. apply Rlt_irrefl with R0.\n          apply Rlt_trans with x;assumption.\n        }\n      }\n      {\n        rewrite eqxy;rewrite eqxym.\n        rewrite Ropp_plus_distr. rewrite Ropp_involutive.\n        apply Rplus_le_compat_r.\n        left. apply Rlt_trans with R0.\n        assumption. rewrite <- Ropp_0.\n        apply Ropp_lt_contravar. assumption.\n      }\n      {\n        rewrite eqxy;rewrite eqxym.\n        rewrite Ropp_plus_distr.\n        apply Rplus_le_compat_r.\n        destruct hxym.\n        exfalso. apply Rlt_irrefl with R0.\n        apply Rlt_trans with y.\n        assumption.\n        apply Rlt_trans with x.\n        apply Rplus_lt_reg_r with (-y).\n        rewrite Rplus_opp_r. assumption.\n        assumption.\n        apply (Rplus_eq_compat_r y) in H.\n        rewrite Rplus_assoc in H.\n        rewrite Rplus_opp_l in H.\n        rewrite Rplus_0_r in H.\n        rewrite Rplus_0_l in H.\n        subst x. exfalso. apply Rlt_irrefl with R0.\n        apply Rlt_trans with y.\n        assumption.\n        apply Rlt_trans with (y+y).\n        apply Rplus_lt_reg_l with (-y).\n        rewrite <- Rplus_assoc.\n        rewrite Rplus_opp_l.\n        rewrite Rplus_0_l. assumption. assumption.\n      }\n      {\n        rewrite eqxy;rewrite eqxym.\n        rewrite Ropp_plus_distr.\n        rewrite Ropp_plus_distr.\n        rewrite Ropp_involutive.\n        apply Rplus_le_compat_l.\n        left. apply Rlt_trans with R0.\n        rewrite <- Ropp_0. apply Ropp_lt_contravar. assumption.\n        assumption.\n      }\n    }\n    {\n      subst y.\n      rewrite eqx. rewrite eqy.\n      rewrite Ropp_0.\n      rewrite Rplus_0_r.\n      rewrite Rplus_0_r.\n      rewrite Rabs_Ropp.\n      right. reflexivity.\n    }\n  }\n  {\n    rewrite eqx. rewrite eqy.\n    rewrite <- Ropp_plus_distr.\n    rewrite Rabs_Ropp.\n    right. reflexivity.\n  }\nQed.\n\nLemma Rabs_def1 : forall x a:R, x < a -> - a < x -> Rabs x < a.\nProof.\n  intros x a hu hl.\n  unfold Rabs. destruct (Rcase_abs x).\n  apply Ropp_lt_cancel. rewrite Ropp_involutive. assumption.\n  assumption.\nQed.\n\nLemma Rabs_def2 : forall x a:R, Rabs x < a -> x < a /\\ - a < x.\nProof.\n  intros x a.\n  split.\n  unfold Rabs in H. destruct (Rcase_abs x).\n  apply Rlt_trans with R0. assumption.\n  apply Rlt_trans with (-x).\n  apply Ropp_lt_cancel. rewrite Ropp_involutive. rewrite Ropp_0.\n  assumption. assumption.\n  assumption.\n  unfold Rabs in H. destruct (Rcase_abs x).\n  apply Ropp_lt_cancel. rewrite Ropp_involutive. assumption.\n  destruct r.\n  apply Rlt_trans with R0.\n  apply Ropp_lt_cancel. rewrite Ropp_involutive. rewrite Ropp_0.\n  apply Rlt_trans with x. assumption. assumption. assumption.\n  subst x. apply Ropp_lt_cancel. rewrite Ropp_involutive. rewrite Ropp_0.\n  assumption.\nQed.\n\nLemma RmaxAbs :\n  forall (p q:R) r, p <= q -> q <= r -> Rabs q <= Rmax (Rabs p) (Rabs r).\nProof.\n  intros x y z.\n  intros hxy hyz.\n  unfold Rabs, Rmax.\n  destruct (Rcase_abs y) as [ hy | hy ];\n  destruct (Rcase_abs x) as [ hx | hx ];\n  destruct (Rcase_abs z) as [ hz | hz ].\n  {\n    destruct (Rle_dec (-x) (-z)) as [ hxz | hxz ].\n    {\n      apply Ropp_le_cancel in hxz.\n      assert (eq:z=x).\n      {\n        apply Rle_antisym.\n        { assumption. }\n        { apply Rle_trans with y;assumption. }\n      }\n      subst z.\n      assert (eq:x=y).\n      {\n        apply Rle_antisym;assumption.\n      }\n      subst y.\n      right. reflexivity.\n    }\n    {\n      apply Rnot_le_lt in hxz.\n      apply Ropp_le_contravar.\n      assumption.\n    }\n  }\n  {\n    destruct (Rle_dec (-x) z) as [ hxz | hxz ].\n    {\n      apply Rle_trans with (-x).\n      { apply Ropp_le_contravar. assumption. }\n      { assumption. }\n    }\n    {\n      apply Rnot_le_lt in hxz.\n      apply Ropp_le_contravar.\n      assumption.\n    }\n  }\n  {\n    destruct (Rle_dec x (-z)) as [ hxz | hxz ].\n    {\n      apply Ropp_le_contravar.\n      apply Rle_trans with x.\n      2:assumption.\n      apply Rle_trans with (-x).\n      { apply Ropp_le_cancel. rewrite Ropp_involutive. assumption. }\n      {\n        apply Rle_trans with R0.\n        2:assumption.\n        rewrite <- Ropp_0.\n        apply Ropp_le_contravar.\n        assumption.\n      }\n    }\n    {\n      apply Rnot_le_lt in hxz.\n      exfalso.\n      apply Rlt_irrefl with R0.\n      apply Rlt_trans with z.\n      2:exact hz. clear hz.\n      apply Rlt_trans with (-x).\n      2:{\n        apply Ropp_lt_cancel.\n        rewrite Ropp_involutive.\n        exact hxz.\n      }\n      clear hxz.\n      apply Ropp_lt_cancel.\n      rewrite Ropp_involutive.\n      rewrite Ropp_0.\n      apply Rle_lt_trans with y.\n      { exact hxy. }\n      { exact hy. }\n    }\n  }\n  {\n    exfalso.\n    apply Rlt_irrefl with x.\n    apply Rle_lt_trans with y.\n    exact hxy.\n    clear hxy.\n    apply Rlt_le_trans with R0.\n    exact hy.\n    exact hx.\n  }\n  {\n    destruct (Rle_dec (-x) (-z)) as [ hxz | hxz ].\n    {\n      apply Ropp_le_cancel in hxz.\n      assert (eq : z = x).\n      {\n        apply Rle_antisym;try assumption.\n        apply Rle_trans with y;assumption.\n      }\n      subst z.\n      assert (eq : x = y).\n      { apply Rle_antisym; assumption. }\n      subst y.\n      exfalso.\n      apply Rlt_irrefl with R0.\n      apply Rle_lt_trans with x;assumption.\n    }\n    {\n      apply Rnot_le_lt in hxz.\n      apply Ropp_lt_cancel in hxz.\n      clear hxy.\n      clear hx.\n      clear hxz.\n      exfalso.\n      apply Rlt_irrefl with R0.\n      apply Rle_lt_trans with z;try assumption.\n      apply Rle_trans with y;assumption.\n    }\n  }\n  {\n    destruct (Rle_dec (-x) z) as [ hxz | hxz ].\n    { assumption. }\n    {\n      apply Rnot_le_lt in hxz.\n      apply Rle_trans with z.\n      exact hyz.\n      clear hyz.\n      left. exact hxz.\n    }\n  }\n  {\n    exfalso.\n    apply Rlt_irrefl with R0.\n    apply Rle_lt_trans with z.\n    2:exact hz.\n    clear hz.\n    apply Rle_trans with y; assumption.\n  }\n  {\n    destruct (Rle_dec x z) as [ hxz | hxz ].\n    { assumption. }\n    {\n      apply Rnot_le_lt in hxz.\n      exfalso.\n      apply Rlt_irrefl with z.\n      apply Rlt_le_trans with x; try assumption.\n      apply Rle_trans with y;assumption.\n    }\n  }\nQed.\n\nLemma abs_IZR : forall z, IZR (Z.abs z) = Rabs (IZR z).\nProof.\n  intro z.\n  unfold Rabs.\n  destruct (Rcase_abs (IZR z)) as [ h | h ].\n  {\n    unfold Z.abs.\n    destruct z.\n    { change (IZR 0) with R0. rewrite Ropp_0. reflexivity. }\n    {\n      exfalso.\n      apply Rlt_irrefl with R0.\n      apply Rlt_trans with (IZR (Z.pos p)).\n      {\n        change R0 with (IZR 0).\n        apply IZR_lt.\n        apply Pos2Z.pos_is_pos.\n      }\n      { assumption. }\n    }\n    {\n      rewrite <- opp_IZR.\n      rewrite Pos2Z.opp_neg.\n      reflexivity.\n    }\n  }\n  {\n    unfold Z.abs.\n    destruct z.\n    { reflexivity. }\n    { reflexivity. }\n    {\n      exfalso.\n      apply Rlt_irrefl with R0.\n      apply Rle_lt_trans with (IZR (Z.neg p)).\n      { assumption. }\n      {\n        change R0 with (IZR 0).\n        apply IZR_lt.\n        apply Pos2Z.neg_is_neg.\n      }\n    }\n  }\nQed.\n\nLemma Rabs_Zabs : forall z:Z, Rabs (IZR z) = IZR (Z.abs z).\nProof.\n  intro z.\n  symmetry.\n  apply abs_IZR.\nQed.\n\nLemma Ropp_Rmax : forall x y, - Rmax x y = Rmin (-x) (-y).\nProof.\n  intros x y.\n  unfold Rmax, Rmin.\n  destruct (Rle_dec x y) as [ hxy | hxy ];\n  destruct (Rle_dec (-x) (-y)) as [ hxy' | hxy' ].\n  {\n    apply Rle_antisym.\n    apply Ropp_le_contravar. assumption.\n    assumption.\n  }\n  { reflexivity. }\n  { reflexivity. }\n  {\n    apply Rnot_le_lt in hxy.\n    apply Rnot_le_lt in hxy'.\n    apply Rle_antisym.\n    left. apply Ropp_lt_contravar. assumption.\n    left. assumption.\n  }\nQed.\n\nLemma Ropp_Rmin : forall x y, - Rmin x y = Rmax (-x) (-y).\nProof.\nintros x y.\nunfold Rmax.\nunfold Rmin.\ndestruct (Rle_dec x y) as [ hmin | hmin ];\ndestruct (Rle_dec (-x) (-y)) as [ hmax | hmax ].\n{\n  apply Rle_antisym.\n  assumption.\n  apply Ropp_le_contravar.\n  assumption.\n}\n{ reflexivity. }\n{ reflexivity. }\n{\n  apply Rnot_le_lt in hmin.\n  apply Rnot_le_lt in hmax.\n  apply Rle_antisym.\n  left. assumption.\n  left. apply Ropp_lt_contravar. assumption.\n}\nQed.\n\nLemma Rmax_assoc : forall x y z, Rmax x (Rmax y z) = Rmax (Rmax x y) z.\nProof.\nintros x y z.\nunfold Rmax.\ndestruct (Rle_dec y z) as [ hyz | hyz ] eqn:eqyz.\n{\n  destruct (Rle_dec x y) as [ hxy | hxy ] eqn:eqxy.\n  {\n    destruct (Rle_dec x z) as [ hxz | hxz ] eqn:eqxz.\n    {\n      rewrite eqyz. reflexivity.\n    }\n    {\n      rewrite eqyz. apply Rle_antisym.\n      apply Rle_trans with y;assumption.\n      clear eqxz.\n      apply Rnot_le_lt in hxz.\n      left. assumption.\n    }\n  }\n  {\n    destruct (Rle_dec x z) as [ hxz | hxz ] eqn:eqxz.\n    { reflexivity. }\n    { reflexivity. }\n  }\n}\n{\n  destruct (Rle_dec x y) as [ hxy | hxy ] eqn:eqxy.\n  {\n    rewrite eqyz. reflexivity.\n  }\n  {\n    destruct (Rle_dec x z) as [ hxz | hxz ] eqn:eqxz.\n    {\n      apply Rle_antisym.\n      assumption.\n      left.\n      clear eqyz. apply Rnot_le_lt in hyz.\n      clear eqxy. apply Rnot_le_lt in hxy.\n      apply Rlt_trans with y;assumption.\n    }\n    { reflexivity. }\n  }\n}\nQed.\n\nLemma Rminmax : forall a b, Rmin a b <= Rmax a b.\nProof.\n  intros x y.\n  unfold Rmin, Rmax.\n  destruct (Rle_dec x y) as [ hxy | hxy ].\n  { assumption. }\n  {\n    apply Rnot_le_lt in hxy.\n    left. assumption.\n  }\nQed.\n\nLemma Rmin_assoc : forall x y z, Rmin x (Rmin y z) =\n  Rmin (Rmin x y) z.\nProof.\nintros x y z.\nunfold Rmin.\ndestruct (Rle_dec y z) as [ hyz | hyz ] eqn:eqyz.\n{\n  destruct (Rle_dec x y) as [ hxy | hxy ] eqn:eqxy.\n  {\n    destruct (Rle_dec x z) as [ hxz | hxz ] eqn:eqxz.\n    { reflexivity. }\n    {\n      apply Rle_antisym.\n      apply Rle_trans with y;assumption.\n      clear eqxz; apply Rnot_le_lt in hxz.\n      left.\n      assumption.\n    }\n  }\n  { rewrite eqyz. reflexivity. }\n}\n{\n  destruct (Rle_dec x y) as [ hxy | hxy ] eqn:eqxy.\n  {\n    destruct (Rle_dec x z) as [ hxz | hxz ] eqn:eqxz.\n    { reflexivity. }\n    { reflexivity. }\n  }\n  {\n    destruct (Rle_dec x z) as [ hxz | hxz ] eqn:eqxz.\n    {\n      rewrite eqyz.\n      apply Rle_antisym.\n      assumption.\n      left.\n      clear eqxy. apply Rnot_le_lt in hxy.\n      clear eqyz. apply Rnot_le_lt in hyz.\n      apply Rlt_trans with y;assumption.\n    }\n    { rewrite eqyz. reflexivity. }\n  }\n}\nQed.\n(*\ncompleteness\n     : forall E : R -> Prop, bound E -> (exists x : R, E x) -> {m : R | is_lub E m}\n*)\n\nDefinition tada x s := s * s <= x.\n\nDefinition tada' x s := s * s = x \\/ s * s = R0.\n\nLemma Rsqr_le_1 : forall x, R0 < x -> x <= R1 -> x * x <= x.\nProof.\n  intros x hl hr .\n  destruct hr as [ hr | hr ].\n  {\n    left.\n    pattern x at 3;rewrite <- Rmult_1_r.\n    apply Rmult_lt_compat_l.\n    exact hl.\n    exact hr.\n  }\n  {\n    subst x.\n    rewrite Rmult_1_l.\n    right.\n    reflexivity.\n  }\nQed.\n\nLemma Rsqr_le_0 : forall x, Rsqr x <= R0 -> x = R0.\nProof.\n  intros x h.\n  destruct h as [ h | h ].\n  {\n    exfalso.\n    apply Rlt_irrefl with R0.\n    apply Rle_lt_trans with (Rsqr x).\n    { apply Rle_0_sqr. }\n    { exact h. }\n  }\n  {\n    unfold Rsqr in h.\n    apply Rmult_integral in h.\n    destruct h as [ h | h ].\n    { exact h. }\n    { exact h. }\n  }\nQed.\n\nLemma tada_bound : forall x, R0 <= x -> bound (tada x).\nProof.\n  intros x hx.\n  unfold bound.\n  unfold is_upper_bound.\n  unfold tada.\n  destruct hx as [ hx | hx ].\n  {\n    destruct (Rtotal_order x R1) as [ ho | [ ho | ho ] ].\n    {\n      exists R1.\n      intros y hy.\n      destruct (Rtotal_order y R0) as [ hoy | [ hoy | hoy ] ].\n      {\n        destruct (Rtotal_order y (-R1)) as [ hoy' | [ hoy' | hoy' ] ].\n        {\n          apply Rle_trans with (-R1).\n          left. exact hoy'.\n          apply Rle_trans with R0.\n          rewrite <- Ropp_0. apply Ropp_le_contravar. left. exact Rlt_0_1.\n          left. exact Rlt_0_1.\n        }\n        {\n          subst y.\n          apply Rle_trans with R0.\n          { rewrite <- Ropp_0. apply Ropp_le_contravar. left. exact Rlt_0_1. }\n          { left. exact Rlt_0_1. }\n        }\n        {\n          apply Rle_trans with R0.\n          left. exact hoy.\n          left. exact Rlt_0_1.\n        }\n      }\n      {\n        subst y.\n        left.\n        exact Rlt_0_1.\n      }\n      {\n        destruct (Rtotal_order y R1) as [ hoy' | [ hoy' | hoy' ] ].\n        {\n          left.\n          exact hoy'.\n        }\n        {\n          subst y.\n          right.\n          reflexivity.\n        }\n        {\n          exfalso.\n          eapply Rlt_irrefl.\n          eapply Rlt_le_trans.\n          { exact hoy'. }\n          {\n            eapply Rle_trans.\n            2:{\n              left.\n              exact ho.\n            }\n            {\n              clear ho.\n              apply Rmult_le_reg_r with y.\n              { exact hoy. }\n              {\n                eapply Rle_trans.\n                { exact hy. }\n                {\n                  pattern x at 1;rewrite <- Rmult_1_r.\n                  apply Rmult_le_compat_l.\n                  { left. exact hx. }\n                  { left. exact hoy'. }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n    {\n      subst x.\n      exists R1.\n      intros y hy.\n      destruct (Rtotal_order y R0) as [ hoy | [ hoy | hoy ] ].\n      {\n        apply Rle_trans with R0.\n        left. exact hoy.\n        left. exact Rlt_0_1.\n      }\n      {\n        subst y.\n        left.\n        exact Rlt_0_1.\n      }\n      {\n        destruct (Rtotal_order y R1) as [ hoy' | [ hoy' | hoy' ] ].\n        { left. exact hoy'. }\n        { subst y. right. reflexivity. }\n        {\n          exfalso.\n          eapply Rlt_irrefl.\n          eapply Rle_lt_trans.\n          { apply hy. }\n          {\n            pattern R1;rewrite <- Rmult_1_r.\n            apply Rmult_gt_0_lt_compat.\n            { exact Rlt_0_1. }\n            { exact hoy. }\n            { exact hoy'. }\n            { exact hoy'. }\n          }\n        }\n      }\n    }\n    {\n      exists x.\n      intros y hy.\n      destruct (Rtotal_order y R0) as [ hoy | [ hoy | hoy ] ].\n      {\n        left.\n        apply Rlt_trans with R0.\n        exact hoy.\n        exact hx.\n      }\n      {\n        subst y.\n        left.\n        exact hx.\n      }\n      {\n        destruct (Rtotal_order y R1) as [ hoy' | [ hoy' | hoy' ] ].\n        {\n          left.\n          apply Rlt_trans with R1.\n          exact hoy'.\n          exact ho.\n        }\n        {\n          subst y .\n          left.\n          exact ho.\n        }\n        {\n          apply Rmult_le_reg_r with y.\n          exact hoy.\n          apply Rle_trans with x.\n          exact hy.\n          pattern x at 1;rewrite <- Rmult_1_r.\n          apply Rmult_le_compat_l.\n          left. exact hx.\n          left. exact hoy'.\n        }\n      }\n    }\n  }\n  {\n    subst x.\n    exists R0.\n    intros x hx.\n    apply Rsqr_le_0 in hx.\n    right.\n    exact hx.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/Reals/XRbasic_fun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867851, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7033779402949687}}
{"text": "From Coq Require Export Setoid.\nSet Implicit Arguments.\n\n(** * Preliminaries *)\n(** ** Definition of iterator [comp]\n   [comp f u n x] is defined as $(f~(u~(n-1)).. (f (u~ 0)~x))$ *)\n\nFixpoint comp (A:Type) (f : A -> A -> A) (x : A) (u : nat -> A) (n:nat) {struct n}: A := \n   match n with O => x| (S p) => f (u p) (comp f x u p) end.\n      \nLemma comp0 : forall (A:Type) (f : A -> A -> A) (x : A) (u : nat -> A), comp f x u 0 = x.\ntrivial.\nQed.\n\nLemma compS : forall (A:Type) (f : A -> A -> A) (x : A) (u : nat -> A) (n:nat),\n              comp f x u (S n) = f (u n) (comp f x u n).\ntrivial.\nQed.\n\n(** ** Reducing if constructs *)\n\nLemma if_then : forall (P:Prop) (b:{P}+{ ~P})(A:Type)(p q:A), P -> (if b then p else q) =p.\ndestruct b; simpl; intuition.\nQed.\n\nLemma if_else : forall (P:Prop) (b:{P}+{ ~P})(A:Type)(p q:A), ~P -> (if b then p else q) =q.\ndestruct b; simpl; intuition.\nQed.\n\n(** ** Classical reasoning *)\n\nDefinition class (A:Prop) := ~ ~A -> A.\n\nLemma class_neg : forall A:Prop, class ( ~ A).\nunfold class; intuition.\nQed.\n\nLemma class_false : class False.\nunfold class; intuition.\nQed.\nHint Resolve class_neg class_false: core.\n\nDefinition orc (A B:Prop) := forall C:Prop, class C -> (A ->C) -> (B->C) -> C.\n\nLemma orc_left : forall A B:Prop, A -> orc A B.\nred;intuition.\nQed.\n\nLemma orc_right : forall A B:Prop, B -> orc A B.\nred;intuition.\nQed.\n\nHint Resolve orc_left orc_right: core.\n\nLemma class_orc : forall A B, class (orc A B).\nrepeat red; intros.\napply H0; red; intro.\napply H; red; intro. \napply H3; apply H4; auto.\nQed.\n\nArguments class_orc : clear implicits.\n\nLemma orc_intro : forall A B, ( ~A -> ~B -> False) -> orc A B.\nintros; apply class_orc; red; intros.\napply H; red; auto.\nQed.\n\nLemma class_and : forall A B, class A -> class B -> class (A /\\ B).\nunfold class; intuition.\nQed.\n\nLemma excluded_middle : forall A, orc A ( ~A).\nred; intros.\napply H; red; intro.\nintuition.\nQed.\n\nDefinition exc (A :Type)(P:A->Prop) := \n   forall C:Prop, class C -> (forall x:A, P x ->C) -> C.\n\nLemma exc_intro : forall (A :Type)(P:A->Prop) (x:A), P x -> exc P.\nred;firstorder.\nQed.\n\nLemma class_exc : forall (A :Type)(P:A->Prop), class (exc P).\nrepeat red; intros.\napply H0; clear H0; red; intro.\napply H; clear H; red; intro H2. \napply H2; intros; auto.\napply H0; apply (H1 x); auto.\nQed.\n\nLemma exc_intro_class : forall (A:Type) (P:A->Prop), ((forall x, ~P x) -> False) -> exc P.\nintros; apply class_exc; red; intros.\napply H; red; intros; auto.\napply H0; apply exc_intro with (x:=x);auto.\nQed.\n\nLemma not_and_elim_left : forall A B, ~ (A /\\ B) -> A -> ~B.\nintuition.\nQed.\n\nLemma not_and_elim_right : forall A B, ~ (A /\\ B) -> B -> ~A.\nintuition.\nQed.\n\nHint Resolve class_orc class_and class_exc excluded_middle: core.\n\nLemma class_double_neg : forall P Q: Prop, class Q -> (P -> Q) -> ~~P -> Q.\nintros.\napply (excluded_middle (A:=P)); auto.\nQed.\n\n(** ** Extensional equality *)\n\nDefinition feq A B (f g : A -> B) := forall x, f x = g x.\n\nLemma feq_refl : forall A B (f:A->B), feq f f.\nred; trivial.\nQed.\n\nLemma feq_sym : forall A B (f g : A -> B), feq f g -> feq g f.\nunfold feq; auto.\nQed.\n\nLemma feq_trans : forall A B (f g h: A -> B), feq f g -> feq g h -> feq f h.\nunfold feq; intros.\ntransitivity (g x); auto.\nQed.\n\nHint Resolve feq_refl: core.\nHint Immediate feq_sym: core.\nHint Unfold feq: core.\n\nAdd Parametric Relation (A B : Type) : (A -> B) (feq (A:=A) (B:=B)) \n  reflexivity proved by (feq_refl (A:=A) (B:=B))\n  symmetry proved by (feq_sym (A:=A) (B:=B))\n  transitivity proved by (feq_trans (A:=A) (B:=B))\nas feq_rel.\n\n\n\n", "meta": {"author": "coq-community", "repo": "alea", "sha": "0cd68687229aaa26623c7092d4b40e9a812f17bc", "save_path": "github-repos/coq/coq-community-alea", "path": "github-repos/coq/coq-community-alea/alea-0cd68687229aaa26623c7092d4b40e9a812f17bc/Misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7033779335980378}}
{"text": "(** ** intro\n\nこの forall (P : Prop), P -> P という命題を、今度は\nintro と exact を使って証明してみましょう。\n*)\n\nGoal forall (P : Prop), P -> P.\nProof.\n(**\n1 subgoal\n______________________________________(1/1)\nforall P : Prop, P -> P\n*)\n  Show Proof.\n(**\n<<\n?Goal\n>>\nここでは証明を始めたばかりなので、Goal に与えた\nforall P : Prop, P -> P という命題そのものを証明せよ、と Coq から要求されています。\nそこで Show Proof とすると ?Goal と表示されます。\nつまり、証明項はまったく構築されておらず、\nforall P : Prop, P -> P という型の\n値をどうにか作ってここに埋めていかなければならないというわけです。\n*)\n  intro P.\n(**\n<<\n1 subgoal\nP : Prop\n______________________________________(1/1)\nP -> P\n>>\n*)\n  Show Proof.\n(**\n<<\n(fun P : Prop => ?Goal)\n>>\nintro P により、証明すべき命題 forall P : Prop, P -> P の左側の\nforall P : Prop という部分が前提に移動して前提に P : Prop が入り、\n証明すべき命題は P -> P に変化します。\nここで Show Proof とすると、(fun P : Prop => ?Goal) と表示されます。\nつまり、intro P は証明項を Prop型の値Pを受け取る関数抽象として構築せよ、\nという指示です。\n関数抽象の本体はまだ不明なので ?Goal となっていますが、\nこの部分の型は (forall P : Prop, P -> P から左側の forall P : Prop を取り除いた型である)\nP -> P です。\nそのため、P -> P という型である ?Goal の部分をこれから構築しなければならない、\nという状態であることがわかります。\n\nなお、この段階で Display notations を無効にすると、証明すべき命題は\nP -> P から、forall _ : P, P に変化します。\nこれにより、P -> P というのは forall _ : P, P の省略形であることがわかります。\n\n前提に P が入ったのでここからは P を自由に使えますが、このことを\n証明項の構造から説明すると、?Goal の部分の外側で P が束縛されているため、\n?Goal の中では P を参照できる、という意味になります。\n*)\n  intro H.\n(**\n<<\n1 subgoal\nP : Prop\nH : P\n______________________________________(1/1)\nP\n>>\n*)\n  Show Proof.\n(**\n<<\n(fun (P : Prop) (H : P) => ?Goal)\n>>\nintro H により、証明すべき命題 P -> P の左側の P -> が消えて\n前提に H : P に移動し、証明すべき命題は P に変化します。\n\nShow Proof とすると、(fun (P : Prop) (H : P) => ?Goal) と表示されます。\nつまり、?Goal を（また）関数抽象として構築せよ、という指示を行ったので、\n証明項は関数抽象が2段ネストしたものとして (fun (P : Prop) (H : P) => ?Goal) という形に\nなり、関数抽象の本体の P という型である ?Goal の部分をこれから構築しなければならない、\nという状態であることが分かります。\n\nDisplay notations が無効にするとわかるように、\nこれは証明すべき命題 forall _ : P, P の左側の\nforall _ : P が前提に移動した、というわけで、\n最初の intro P が forall P : Prop を前提に移動したのと\n同様なことをしていることがわかるでしょう。\nただし、forall P : Prop では、Prop 型の値に P という名前がついていましたが、\n今回の forall _ : P では、P 型の値に名前がついておらず、_ になっています。\nどちらにしても、intro で指定した名前が関数抽象で導入される変数の名前として使われます。\n\n前提に H が入ったのでここからは H を自由に使えますが、このことを\n証明項の構造から説明すると、?Goal の部分の外側で H が束縛されているため、\n?Goal の中では H を参照できる、という意味になります。\n*)\n  exact H.\n(**\n<<\nNo more subgoals.\n>>\n*)\n  Show Proof.\n(**\n<<\n(fun (P : Prop) (H : P) => H)\n>>\nP という型の値としては H が存在する（参照できる）ので、\nそれを証明項として与えれば証明は終わりです。\nexact H により H を証明項として直接与えると No more subgoals. と表示されて\n証明が終ったことがわかります。\nここで Show Proof とすると、(fun (P : Prop) (H : P) => H) と表示され、\n上で ?Goal だったところに H が埋められていることが分かります。\n証明項に不明な部分はもうないので、やることはもうありません。\nQed で証明を終りましょう。\n*)\nQed.\n", "meta": {"author": "akr", "repo": "coq-curry-howard", "sha": "37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5", "save_path": "github-repos/coq/akr-coq-curry-howard", "path": "github-repos/coq/akr-coq-curry-howard/coq-curry-howard-37a7f3afc07bb17e49ec915be1a1a2ddb67a5ee5/theories/intro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7033779284922504}}
{"text": "Require Import Frap.\n\n\n(** * Finite sets as inductive predicates *)\n\nInductive my_favorite_numbers : nat -> Prop :=\n| ILike17 : my_favorite_numbers 17\n| ILike23 : my_favorite_numbers 23\n| ILike42 : my_favorite_numbers 42.\n\nCheck my_favorite_numbers_ind.\n\nTheorem favorites_below_50 : forall n, my_favorite_numbers n -> n < 50.\nProof.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(** * Transitive closure of relations *)\n\nInductive tc {A} (R : A -> A -> Prop) : A -> A -> Prop :=\n| TcBase : forall x y, R x y -> tc R x y\n| TcTrans : forall x y z, tc R x y -> tc R y z -> tc R x z.\n\n(** ** Less-than reimagined *)\n\nDefinition oneApart (n m : nat) : Prop :=\n  n + 1 = m.\n\nDefinition lt' : nat -> nat -> Prop := tc oneApart.\n\nTheorem lt'_lt : forall n m, lt' n m -> n < m.\nProof.\nAdmitted.\n\nTheorem lt_lt' : forall n m, n < m -> lt' n m.\nProof.\nAdmitted.\n\n(** ** Transitive closure is idempotent. *)\n\nTheorem tc_tc2 : forall A (R : A -> A -> Prop) x y, tc R x y -> tc (tc R) x y.\nProof.\nAdmitted.\n\nTheorem tc2_tc : forall A (R : A -> A -> Prop) x y, tc (tc R) x y -> tc R x y.\nProof.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(** * Permutation *)\n\n(* Lifted from the Coq standard library: *)\nInductive Permutation {A} : list A -> list A -> Prop :=\n| perm_nil :\n    Permutation [] []\n| perm_skip : forall x l l',\n    Permutation l l' -> Permutation (x::l) (x::l')\n| perm_swap : forall x y l,\n    Permutation (y::x::l) (x::y::l)\n| perm_trans : forall l l' l'',\n    Permutation l l' -> Permutation l' l'' -> Permutation l l''.\n\nTheorem Permutation_rev : forall A (ls : list A),\n    Permutation ls (rev ls).\nProof.\nAdmitted.\n\nTheorem Permutation_length : forall A (ls1 ls2 : list A),\n    Permutation ls1 ls2 -> length ls1 = length ls2.\nProof.\nAdmitted.\n\nTheorem Permutation_app : forall A (ls1 ls1' ls2 ls2' : list A),\n    Permutation ls1 ls1'\n    -> Permutation ls2 ls2'\n    -> Permutation (ls1 ++ ls2) (ls1' ++ ls2').\nProof.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(** * Simple propositional logic *)\n\nInductive prop :=\n| Truth\n| Falsehood\n| And (p1 p2 : prop)\n| Or (p1 p2 : prop).\n\nInductive valid : prop -> Prop :=\n| ValidTruth :\n    valid Truth\n| ValidAnd : forall p1 p2,\n    valid p1\n    -> valid p2\n    -> valid (And p1 p2)\n| ValidOr1 : forall p1 p2,\n    valid p1\n    -> valid (Or p1 p2)\n| ValidOr2 : forall p1 p2,\n    valid p2\n    -> valid (Or p1 p2).\n\nFixpoint interp (p : prop) : Prop :=\n  match p with\n  | Truth => True\n  | Falsehood => False\n  | And p1 p2 => interp p1 /\\ interp p2\n  | Or p1 p2 => interp p1 \\/ interp p2\n  end.\n\nTheorem interp_valid : forall p, interp p -> valid p.\nProof.\nAdmitted.\n\nTheorem valid_interp : forall p, valid p -> interp p.\nProof.\nAdmitted.\n\nFixpoint commuter (p : prop) : prop :=\n  match p with\n  | Truth => Truth\n  | Falsehood => Falsehood\n  | And p1 p2 => And (commuter p2) (commuter p1)\n  | Or p1 p2 => Or (commuter p2) (commuter p1)\n  end.\n\nTheorem valid_commuter_fwd : forall p, valid p -> valid (commuter p).\nProof.\nAdmitted.\n\nTheorem valid_commuter_bwd : forall p, valid (commuter p) -> valid p.\nProof.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(* Proofs for an extension I hope we'll get to:\n\nFixpoint interp (vars : var -> Prop) (p : prop) : Prop :=\n  match p with\n  | Truth => True\n  | Falsehood => False\n  | Var x => vars x\n  | And p1 p2 => interp vars p1 /\\ interp vars p2\n  | Or p1 p2 => interp vars p1 \\/ interp vars p2\n  | Imply p1 p2 => interp vars p1 -> interp vars p2\n  end.\n\nTheorem valid_interp : forall vars hyps p,\n    valid hyps p\n    -> (forall h, hyps h -> interp vars h)\n    -> interp vars p.\nProof.\n  induct 1; simplify.\n\n  apply H0.\n  assumption.\n\n  propositional.\n\n  propositional.\n\n  propositional.\n\n  propositional.\n\n  propositional.\n\n  propositional.\n\n  propositional.\n\n  propositional.\n  apply IHvalid2.\n  propositional.\n  equality.\n  apply H2.\n  assumption.\n  apply IHvalid3.\n  propositional.\n  equality.\n  apply H2.\n  assumption.\n\n  apply IHvalid.\n  propositional.\n  equality.\n  apply H0.\n  assumption.\n\n  propositional.\n\n  excluded_middle (interp vars p); propositional.\n  (* Note that use of excluded middle is a bit controversial in Coq,\n   * and we'll generally be trying to avoid it,\n   * but it helps enough with this example that we don't sweat the details. *)\nQed.\n\nLemma valid_weaken : forall hyps1 p,\n    valid hyps1 p\n    -> forall hyps2 : prop -> Prop,\n      (forall h, hyps1 h -> hyps2 h)\n      -> valid hyps2 p.\nProof.\n  induct 1; simplify.\n\n  apply ValidHyp.\n  apply H0.\n  assumption.\n\n  apply ValidTruthIntro.\n\n  apply ValidFalsehoodElim.\n  apply IHvalid.\n  assumption.\n\n  apply ValidAndIntro.\n  apply IHvalid1.\n  assumption.\n  apply IHvalid2.\n  assumption.\n\n  apply ValidAndElim1 with p2.\n  apply IHvalid.\n  assumption.\n\n  apply ValidAndElim2 with p1.\n  apply IHvalid.\n  assumption.\n\n  apply ValidOrIntro1.\n  apply IHvalid.\n  assumption.\n\n  apply ValidOrIntro2.\n  apply IHvalid.\n  assumption.\n\n  apply ValidOrElim with p1 p2.\n  apply IHvalid1.\n  assumption.\n  apply IHvalid2.\n  first_order.\n  apply IHvalid3.\n  first_order.\n\n  apply ValidImplyIntro.\n  apply IHvalid.\n  propositional.\n  right.\n  apply H0.\n  assumption.\n\n  apply ValidImplyElim with p1.\n  apply IHvalid1.\n  assumption.\n  apply IHvalid2.\n  assumption.\n\n  apply ValidExcludedMiddle.\nQed.\n\nLemma valid_cut : forall hyps1 p p',\n    valid hyps1 p\n    -> forall hyps2, valid hyps2 p'\n                     -> (forall h, hyps1 h -> hyps2 h \\/ h = p')\n                     -> valid hyps2 p.\nProof.\n  induct 1; simplify.\n\n  apply H1 in H.\n  propositional.\n  apply ValidHyp.\n  assumption.\n  equality.\n\n  apply ValidTruthIntro.\n\n  apply ValidFalsehoodElim.\n  apply IHvalid; assumption.\n\n  apply ValidAndIntro.\n  apply IHvalid1; assumption.\n  apply IHvalid2; assumption.\n\n  apply ValidAndElim1 with p2.\n  apply IHvalid; assumption.\n\n  apply ValidAndElim2 with p1.\n  apply IHvalid; assumption.\n\n  apply ValidOrIntro1.\n  apply IHvalid; assumption.\n\n  apply ValidOrIntro2.\n  apply IHvalid; assumption.\n\n  apply ValidOrElim with p1 p2.\n  apply IHvalid1; assumption.\n  apply IHvalid2.\n  apply valid_weaken with hyps2.\n  assumption.\n  propositional.\n  first_order.\n  apply IHvalid3.\n  apply valid_weaken with hyps2.\n  assumption.\n  propositional.\n  first_order.\n\n  apply ValidImplyIntro.\n  apply IHvalid.\n  apply valid_weaken with hyps2.\n  assumption.\n  propositional.\n  first_order.\n\n  apply ValidImplyElim with p1.\n  apply IHvalid1; assumption.\n  apply IHvalid2; assumption.\n\n  apply ValidExcludedMiddle.\nQed.\n\nFixpoint varsOf (p : prop) : list var :=\n  match p with\n  | Truth\n  | Falsehood => []\n  | Var x => [x]\n  | And p1 p2\n  | Or p1 p2\n  | Imply p1 p2 => varsOf p1 ++ varsOf p2\n  end.\n\nLemma interp_valid'' : forall p hyps,\n    (forall x, In x (varsOf p) -> hyps (Var x) \\/ hyps (Not (Var x)))\n    -> (forall x, hyps (Var x) -> ~hyps (Not (Var x)))\n    -> IFF interp (fun x => hyps (Var x)) p\n       then valid hyps p\n       else valid hyps (Not p).\nProof.\n  induct p; unfold IF_then_else; simplify.\n\n  left; propositional.\n  apply ValidTruthIntro.\n\n  right; propositional.\n  apply ValidImplyIntro.\n  apply ValidHyp.\n  propositional.\n\n  specialize (H x); propositional.\n  left; propositional.\n  apply ValidHyp.\n  assumption.\n  right; first_order.\n  apply ValidHyp.\n  assumption.\n\n  excluded_middle (interp (fun x => hyps (Var x)) p1).\n  excluded_middle (interp (fun x => hyps (Var x)) p2).\n  left; propositional.\n  apply ValidAndIntro.\n  assert (IFF interp (fun x : var => hyps (Var x)) p1 then valid hyps p1 else valid hyps (Not p1)).\n  apply IHp1; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H3; propositional.\n  assert (IFF interp (fun x : var => hyps (Var x)) p2 then valid hyps p2 else valid hyps (Not p2)).\n  apply IHp2; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H3; propositional.\n  right; propositional.\n  assert (IFF interp (fun x : var => hyps (Var x)) p2 then valid hyps p2 else valid hyps (Not p2)).\n  apply IHp2; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H3; propositional.\n  apply ValidImplyIntro.\n  apply ValidImplyElim with p2.\n  apply valid_weaken with hyps.\n  assumption.\n  propositional.\n  apply ValidAndElim2 with p1.\n  apply ValidHyp.\n  propositional.\n  right; propositional.\n  assert (IFF interp (fun x : var => hyps (Var x)) p1 then valid hyps p1 else valid hyps (Not p1)).\n  apply IHp1; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H2; propositional.\n  apply ValidImplyIntro.\n  apply ValidImplyElim with p1.\n  apply valid_weaken with hyps.\n  assumption.\n  propositional.\n  apply ValidAndElim1 with p2.\n  apply ValidHyp.\n  propositional.\n\n  excluded_middle (interp (fun x => hyps (Var x)) p1).\n  left; propositional.\n  apply ValidOrIntro1.\n  assert (IFF interp (fun x : var => hyps (Var x)) p1 then valid hyps p1 else valid hyps (Not p1)).\n  apply IHp1; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H2; propositional.\n  excluded_middle (interp (fun x => hyps (Var x)) p2).\n  left; propositional.\n  apply ValidOrIntro2.\n  assert (IFF interp (fun x : var => hyps (Var x)) p2 then valid hyps p2 else valid hyps (Not p2)).\n  apply IHp2; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H3; propositional.\n  right; propositional.\n  apply ValidImplyIntro.\n  apply ValidOrElim with p1 p2.\n  apply ValidHyp.\n  propositional.\n  assert (IFF interp (fun x : var => hyps (Var x)) p1 then valid hyps p1 else valid hyps (Not p1)).\n  apply IHp1; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H3; propositional.\n  apply ValidImplyElim with p1.\n  apply valid_weaken with hyps.\n  assumption.\n  propositional.\n  apply ValidHyp.\n  propositional.\n  assert (IFF interp (fun x : var => hyps (Var x)) p2 then valid hyps p2 else valid hyps (Not p2)).\n  apply IHp2; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H3; propositional.\n  apply ValidImplyElim with p2.\n  apply valid_weaken with hyps.\n  assumption.\n  propositional.\n  apply ValidHyp.\n  propositional.\n\n  excluded_middle (interp (fun x => hyps (Var x)) p1).\n  excluded_middle (interp (fun x => hyps (Var x)) p2).\n  left; propositional.\n  apply ValidImplyIntro.\n  assert (IFF interp (fun x : var => hyps (Var x)) p2 then valid hyps p2 else valid hyps (Not p2)).\n  apply IHp2; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H3; propositional.\n  apply valid_weaken with hyps.\n  assumption.\n  propositional.\n  right; propositional.\n  apply ValidImplyIntro.\n  assert (IFF interp (fun x : var => hyps (Var x)) p1 then valid hyps p1 else valid hyps (Not p1)).\n  apply IHp1; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H3; propositional.\n  assert (IFF interp (fun x : var => hyps (Var x)) p2 then valid hyps p2 else valid hyps (Not p2)).\n  apply IHp2; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H4; propositional.\n  apply ValidImplyElim with p2.\n  apply valid_weaken with hyps.\n  assumption.\n  propositional.\n  apply ValidImplyElim with p1.\n  apply ValidHyp.\n  propositional.\n  apply valid_weaken with hyps.\n  assumption.\n  propositional.\n  left; propositional.\n  apply ValidImplyIntro.\n  assert (IFF interp (fun x : var => hyps (Var x)) p1 then valid hyps p1 else valid hyps (Not p1)).\n  apply IHp1; propositional.\n  apply H.\n  apply in_or_app; propositional.\n  unfold IF_then_else in H2; propositional.\n  apply ValidFalsehoodElim.\n  apply ValidImplyElim with p1.\n  apply valid_weaken with hyps.\n  assumption.\n  propositional.\n  apply ValidHyp.\n  propositional.\nQed.\n\nLemma interp_valid' : forall p leftToDo alreadySplit,\n    (forall x, In x (varsOf p) -> In x (alreadySplit ++ leftToDo))\n    -> forall hyps, (forall x, In x alreadySplit -> hyps (Var x) \\/ hyps (Not (Var x)))\n    -> (forall x, hyps (Var x) \\/ hyps (Not (Var x)) -> In x alreadySplit)\n    -> (forall x, hyps (Var x) -> ~hyps (Not (Var x)))\n    -> (forall vars : var -> Prop,\n           (forall x, hyps (Var x) -> vars x)\n           -> (forall x, hyps (Not (Var x)) -> ~vars x)\n           -> interp vars p)\n    -> valid hyps p.\nProof.\n  induct leftToDo; simplify.\n\n  rewrite app_nil_r in H.\n  assert (IFF interp (fun x : var => hyps (Var x)) p then valid hyps p else valid hyps (Not p)).\n  apply interp_valid''; first_order.\n  unfold IF_then_else in H4; propositional.\n  exfalso.\n  apply H4.\n  apply H3.\n  propositional.\n  first_order.\n\n  excluded_middle (In a alreadySplit).\n\n  apply IHleftToDo with alreadySplit; simplify.\n  apply H in H5.\n  apply in_app_or in H5.\n  simplify.\n  apply in_or_app.\n  propositional; subst.\n  propositional.\n  first_order.\n  first_order.\n  first_order.\n  first_order.\n\n  apply ValidOrElim with (Var a) (Not (Var a)).\n  apply ValidExcludedMiddle.\n\n  apply IHleftToDo with (alreadySplit ++ [a]); simplify.\n  apply H in H5.\n  apply in_app_or in H5.\n  simplify.\n  apply in_or_app.\n  propositional; subst.\n  left; apply in_or_app; propositional.\n  left; apply in_or_app; simplify; propositional.\n  apply in_app_or in H5.\n  simplify.\n  propositional; subst.\n  apply H0 in H6.\n  propositional.\n  propositional.\n  propositional.\n  invert H5.\n  apply in_or_app.\n  simplify.\n  propositional.\n  apply in_or_app.\n  simplify.\n  first_order.\n  invert H5.\n  apply in_or_app.\n  simplify.\n  first_order.\n  propositional.\n  invert H5.\n  invert H7.\n  first_order.\n  invert H5.\n  first_order.\n  apply H3.\n  first_order.\n  first_order.\n\n  apply IHleftToDo with (alreadySplit ++ [a]); simplify.\n  apply H in H5.\n  apply in_app_or in H5.\n  simplify.\n  apply in_or_app.\n  propositional; subst.\n  left; apply in_or_app; propositional.\n  left; apply in_or_app; simplify; propositional.\n  apply in_app_or in H5.\n  simplify.\n  propositional; subst.\n  apply H0 in H6.\n  propositional.\n  propositional.\n  propositional.\n  invert H5.\n  apply in_or_app.\n  simplify.\n  first_order.\n  invert H5.\n  apply in_or_app.\n  simplify.\n  propositional.\n  apply in_or_app.\n  simplify.\n  first_order.\n  propositional.\n  invert H7.\n  invert H7.\n  invert H5.\n  first_order.\n  first_order.\n  apply H3.\n  first_order.\n  first_order.\nQed.\n\nTheorem interp_valid : forall p,\n    (forall vars, interp vars p)\n    -> valid (fun _ => False) p.\nProof.\n  simplify.\n  apply interp_valid' with (varsOf p) []; simplify; first_order.\nQed.\n*)\n", "meta": {"author": "achlipala", "repo": "frap", "sha": "ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb", "save_path": "github-repos/coq/achlipala-frap", "path": "github-repos/coq/achlipala-frap/frap-ac0a15e9f23bb9bfbff7c376a5597b0850b3d4bb/RuleInduction_template.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7033314725726723}}
{"text": "Require Import Bool Setoid ZArith.\nRequire Export List.\nRequire Omega.\n\n(*********************************firstn/skipn*********************************)\n\nLemma firstn_nil : forall {A : Type} (n : nat), firstn n (@nil A) = @nil A.\nProof.\n  intros ? []; reflexivity.\nQed.\n\nLemma skipn_nil : forall {A : Type} (n : nat), skipn n (@nil A) = @nil A.\nProof.\n  intros ? []; reflexivity.\nQed.\n\nNotation length_firstn := firstn_length.\n\nLemma length_skipn : forall {A : Type} (n : nat) (l : list A),\n  length (skipn n l) = length l - n.\nProof.\n  intros ? n; induction n as [| n' IHn']; intro l.\n  - apply minus_n_O.\n  - destruct l.\n    + reflexivity.\n    + apply IHn'.\nQed.\n\nLemma skipn_whole : forall {A : Type} (n : nat) (l : list A),\n  n >= length l -> skipn n l = nil.\nProof.\n  intros ? n l ?.\n  assert (length (skipn n l) = 0). {\n    rewrite length_skipn.\n    omega.\n  }\n  destruct (skipn n l).\n  - reflexivity.\n  - discriminate.\nQed.\n\nLemma firstn_whole : forall {A : Type} (n : nat) (l : list A),\n  n >= length l -> firstn n l = l.\nProof.\n  intros ? n l ?.\n  rewrite <- (firstn_skipn n l) at 2.\n  rewrite skipn_whole; try assumption.\n  apply app_nil_end.\nQed.\n\nLemma firstn_firstn : forall {A : Type} (n m : nat) (l : list A),\n  firstn n (firstn m l) = firstn (min n m) l.\nProof.\n  intros ? n m l; destruct (le_ge_dec n m).\n  - rewrite min_l; try assumption.\n    generalize dependent m; generalize dependent n;\n    induction l as [| h t IHt]; intros n m ?.\n    + rewrite (firstn_nil m). reflexivity.\n    + destruct n.\n      * reflexivity.\n      *{destruct m.\n        - omega.\n        - simpl. f_equal.\n          apply IHt. omega.\n      }\n  - rewrite min_r; try assumption.\n    apply firstn_whole.\n    rewrite length_firstn.\n    apply (le_trans _ m).\n    + apply NPeano.Nat.le_min_l.\n    + assumption.\nQed.\n\n(******************************************************************************)\n\n(**********************************list bool***********************************)\n\nDelimit Scope word_scope with word.\n\nLocal Open Scope word_scope.\n\nNotation \"l ~ b\" := (b :: l)\n (at level 7, left associativity, format \"l '~' b\") : word_scope.\nNotation \"l ~ 0\" := (false :: l)\n (at level 7, left associativity, format \"l '~' '0'\") : word_scope.\nNotation \"l ~ 1\" := (true :: l)\n (at level 7, left associativity, format \"l '~' '1'\") : word_scope.\n\nNotation \"w1 # w2\" := (w2 ++ w1)\n (at level 60, right associativity) : word_scope.\n\nFixpoint list_bool_to_N (l : list bool) : N :=\n  match l with\n  | nil => N0\n  | t~0 => N.double (list_bool_to_N t)\n  | t~1 => N.succ_double (list_bool_to_N t)\n  end.\n\nFixpoint list_bool_of_N (len : nat) (n : N) : list bool :=\n  match len with\n  | 0 => nil\n  | S len' => match n with\n              | N0 => (list_bool_of_N len' N0)~0\n              | Npos xH => (list_bool_of_N len' N0)~1\n              | Npos (xO p) => (list_bool_of_N len' (Npos p))~0\n              | Npos (xI p) => (list_bool_of_N len' (Npos p))~1\n              end\n  end.\n\nNotation falsen := (fun n : nat => nat_iter n (cons false) nil).\nNotation truen := (fun n : nat => nat_iter n (cons true) nil).\n\nFixpoint blist {A B C : Type} (f : A -> B -> C) (l1 : list A) (l2 : list B) :=\n  match l1, l2 with\n  | nil, _ => nil\n  | _, nil => nil\n  | h1 :: t1, h2 :: t2 => f h1 h2 :: blist f t1 t2\n  end.\n\nLemma length_of_N : forall (len : nat) (n : N),\n  length (list_bool_of_N len n) = len.\nProof.\n  intro len; induction len; intro n.\n  - reflexivity.\n  - destruct n as [| []]; simpl; f_equal; trivial.\nQed.\n\nLemma length_iter_cons : forall {A : Type} (n : nat) (h : A) (t : list A),\n  length (nat_iter n (cons h) t) = n + length t.\nProof.\n  intros ? n ? ?; induction n.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma iter_cons_split : forall {A : Type} (n m : nat) (h : A),\n  nat_iter (n + m) (cons h) nil = nat_iter n (cons h) nil ++\n                                  nat_iter m (cons h) nil.\nProof.\n  intros ? n ? ?; induction n.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma firstn_iter_cons : forall {A : Type} (n m : nat) (h : A),\n  firstn n (nat_iter m (cons h) nil) = nat_iter (min n m) (cons h) nil.\nProof.\n  intros ? n m ?.\n  generalize dependent m;\n  induction n; intro m.\n  - reflexivity.\n  - destruct m.\n    + reflexivity.\n    + simpl. f_equal. trivial.\nQed.\n\nLemma length_blist :\n  forall {A B C : Type} (f : A -> B -> C) (l1 : list A) (l2 : list B),\n  length (blist f l1 l2) = min (length l1) (length l2).\nProof.\n  intros ? ? ? ? l1; induction l1; intro l2.\n  - reflexivity.\n  - destruct l2.\n    + reflexivity.\n    + simpl. f_equal. trivial.\nQed.\n\nLemma blist_firstn :\n  forall {A B C : Type} (f : A -> B -> C) (l1 : list A) (l2 : list B) n m,\n  blist f (firstn n l1) (firstn m l2) = firstn (min n m) (blist f l1 l2).\nProof.\n  intros ? ? ? ? l1 l2 n.\n  generalize dependent l2; generalize dependent l1;\n  induction n; intros l1 l2 m.\n  - reflexivity.\n  - destruct l1, l2, m; try reflexivity.\n    simpl. f_equal. trivial.\nQed.\n\nLemma blist_app :\n  forall {A B C : Type} (f : A -> B -> C) (l1 l1' : list A) (l2 l2' : list B),\n  length l1 = length l2 ->\n  blist f (l1 ++ l1') (l2 ++ l2') = (blist f l1 l2) ++ (blist f l1' l2').\nProof.\n  intros ? ? ? ? l1 ? l2 ?.\n  generalize dependent l2;\n  induction l1; intros l2 ?.\n  - destruct l2; reflexivity || discriminate.\n  - destruct l2.\n    + discriminate.\n    + simpl. f_equal. auto.\nQed.\n\nLemma blist_andb_falsen_l : forall (n : nat) (l : list bool),\n  blist andb (falsen n) l = falsen (min n (length l)).\nProof.\n  intro n; induction n; intro l.\n  - reflexivity.\n  - destruct l.\n    + reflexivity.\n    + simpl. f_equal. trivial.\nQed.\n\nLemma blist_andb_falsen_r : forall (l : list bool) (n : nat),\n  blist andb l (falsen n) = falsen (min (length l) n).\nProof.\n  intro l; induction l; intro n.\n  - reflexivity.\n  - destruct n.\n    + reflexivity.\n    + simpl. f_equal.\n      * apply andb_false_r.\n      * trivial.\nQed.\n\n(******************************************************************************)\n\n(*************************************word*************************************)\n\nDefinition word (n : nat) : Set := {l : list bool | length l = n}.\n\nDefinition weq {n m : nat} (w1 : word n) (w2 : word m) : Prop :=\n  match w1, w2 with exist l1 _, exist l2 _ => l1 = l2 end.\nInfix \"==\" := weq (at level 80, no associativity) : word_scope.\n\nLemma weq_refl : forall {n : nat} (w : word n), w == w.\nProof.\n  intros ? w; destruct w.\n  reflexivity.\nQed.\n\nLemma weq_sym : forall {n m : nat} (w1 : word n) (w2 : word m),\n  w1 == w2 -> w2 == w1.\nProof.\n  intros ? ? w1 w2; destruct w1, w2.\n  apply eq_sym.\nQed.\n\nLemma weq_trans :\n  forall {n m l : nat} (w1 : word n) (w2 : word m) (w3 : word l),\n  w1 == w2 -> w2 == w3 -> w1 == w3.\nProof.\n  intros ? ? ? w1 w2 w3; destruct w1, w2, w3.\n  apply eq_trans.\nQed.\n\nAdd Parametric Relation (n : nat) : (word n) weq\n  reflexivity proved by weq_refl\n  symmetry proved by weq_sym\n  transitivity proved by weq_trans as weq_rel.\n\nDefinition wto_N {n : nat} (w : word n) : N :=\n  let (l, _) := w in list_bool_to_N l.\n\nDefinition wof_N (len : nat) (n : N) : word len.\n  refine (exist _ (list_bool_of_N len n) _).\n  apply length_of_N.\nDefined.\n\nLemma wto_N_id : forall {n : nat} (w : word n), wof_N n (wto_N w) == w.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l as [| h t IHt].\n  - reflexivity.\n  - destruct h; simpl; destruct (list_bool_to_N t); simpl; congruence.\nQed.\n\nLemma wof_N_mod : forall (len : nat) (n : N),\n  wto_N (wof_N len n) = (n mod (Npos (shift_nat len xH)))%N.\nProof.\n  intro len; simpl; induction len as [| len' IHlen']; intro n.\n  - symmetry; apply N.mod_1_r.\n  - destruct n as [| []]; simpl; rewrite IHlen'; simpl.\n    + symmetry; apply N.mod_0_l. discriminate.\n    + rewrite <- (N.mod_small (N.succ_double _) (Npos (shift_nat (S len') 1))).\n      Focus 2.\n        change (Npos (shift_nat (S len') 1))\n        with (N.double (Npos (shift_nat len' 1))).\n        apply N.succ_double_lt. apply N.mod_lt. discriminate.\n      rewrite N.succ_double_spec.\n      rewrite <- N.mul_mod_distr_l; try discriminate.\n      rewrite N.add_mod_idemp_l; try discriminate.\n      reflexivity.\n    + rewrite N.double_spec.\n      rewrite <- N.mul_mod_distr_l; try discriminate.\n      reflexivity.\n    + symmetry; apply N.mod_1_l. reflexivity.\nQed.\n\nLemma wof_N_weq : forall {len : nat} (n : N) (w : word len),\n  (n mod (Npos (shift_nat len xH)))%N = wto_N w -> wof_N len n == w.\nProof.\n  assert (H0 : forall n1 n2 : N, N.succ_double n1 <> N.double n2)\n  by (intros [] []; discriminate).\n  intros ? n w; destruct w as [l Hl]; subst; simpl.\n  generalize dependent n;\n  induction l as [| h t IHt]; intros n H.\n  - reflexivity.\n  - destruct n as [| [p | p |]].\n    + rewrite N.mod_0_l in H; try discriminate.\n      destruct h; simpl in *.\n      * destruct (list_bool_to_N t); discriminate.\n      * f_equal. apply IHt. rewrite N.mod_0_l; try discriminate.\n        destruct (list_bool_to_N t); reflexivity || discriminate.\n    + replace (_ mod _)%N\n      with (N.succ_double (Npos p mod Npos (shift_nat (length t) 1))) in H.\n      Focus 2.\n        rewrite <- (N.mod_small (N.succ_double _)\n                                (N.pos (shift_nat (S (length t)) 1))). Focus 2.\n          change (N.pos (shift_nat (S (length t)) 1))\n          with (N.double (N.pos (shift_nat (length t) 1))).\n          apply N.succ_double_lt. apply N.mod_lt. discriminate.\n        rewrite N.succ_double_spec.\n        rewrite <- N.mul_mod_distr_l; try discriminate.\n        apply N.add_mod_idemp_l. discriminate.\n      destruct h; simpl in *.\n      * f_equal. apply IHt. apply N.succ_double_inj. assumption.\n      * elim (H0 _ _ H).\n    + replace (_ mod _)%N\n      with (N.double (Npos p mod Npos (shift_nat (length t) 1))) in H.\n      Focus 2.\n        rewrite N.double_spec. rewrite <- N.mul_mod_distr_l; try discriminate.\n        reflexivity.\n      destruct h; simpl in *.\n      * elim (H0 _ _ (eq_sym H)).\n      * f_equal. apply IHt. apply N.double_inj. assumption.\n    + rewrite N.mod_1_l in H; try reflexivity.\n      destruct h; simpl in *.\n      * f_equal. apply IHt. rewrite N.mod_0_l; try discriminate.\n        destruct (list_bool_to_N t); reflexivity || discriminate.\n      * destruct (list_bool_to_N t); discriminate.\nQed.\n\nLemma weq_iff_Neq : forall {n : nat} (w1 w2 : word n),\n  w1 == w2 <-> wto_N w1 = wto_N w2.\nProof.\n  intros ? w1 w2; split; intro H.\n  - destruct w1, w2; simpl in *; subst. reflexivity.\n  - rewrite <- (wto_N_id w1). rewrite H. apply wto_N_id.\nQed.\n\nDefinition wfalse (n : nat) : word n.\n  refine (exist _ (falsen n) _).\n  rewrite length_iter_cons.\n  apply plus_0_r.\nDefined.\n\nLemma wto_N_wfalse : forall n : nat, wto_N (wfalse n) = N0.\nProof.\n  intro n; simpl; induction n as [| n' IHn'].\n  - reflexivity.\n  - simpl. rewrite IHn'. reflexivity.\nQed.\n\nLemma wof_N_0 : forall n : nat, wof_N n 0 == wfalse n.\nProof.\n  intro n; induction n.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nDefinition wtrue (n : nat) : word n.\n  refine (exist _ (truen n) _).\n  rewrite length_iter_cons.\n  apply plus_0_r.\nDefined.\n\nDefinition wnot {n : nat} (w : word n) : word n.\n  refine (let (l, _) := w in exist _ (map negb l) _).\n  rewrite map_length.\n  assumption.\nDefined.\nNotation \"~ w\" := (wnot w) (at level 75, right associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wnot n) with\n  signature weq ==> weq as wnot_mor.\nProof.\n  intros w w'; destruct w, w'; simpl; intro.\n  subst. reflexivity.\nQed.\n\nDefinition wor {n : nat} (w1 w2 : word n) : word n.\n  refine (match w1, w2 with\n            exist l1 H1, exist l2 H2 => exist _ (blist orb l1 l2) _\n          end).\n  rewrite length_blist.\n  rewrite H1. rewrite H2.\n  apply NPeano.Nat.min_id.\nDefined.\nInfix \"|\" := wor (at level 77, left associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wor n) with\n  signature weq ==> weq ==> weq as wor_mor.\nProof.\n  intros w1 w1' ? w2 w2' ?; destruct w1, w1', w2, w2'; simpl in *.\n  subst. reflexivity.\nQed.\n\nDefinition wand {n : nat} (w1 w2 : word n) : word n.\n  refine (match w1, w2 with\n            exist l1 H1, exist l2 H2 => exist _ (blist andb l1 l2) _\n          end).\n  rewrite length_blist.\n  rewrite H1. rewrite H2.\n  apply NPeano.Nat.min_id.\nDefined.\nInfix \"&\" := wand (at level 76, left associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wand n) with\n  signature weq ==> weq ==> weq as wand_mor.\nProof.\n  intros w1 w1' ? w2 w2' ?; destruct w1, w1', w2, w2'; simpl in *.\n  subst. reflexivity.\nQed.\n\nDefinition wshl {n : nat} (w1 w2 : word n) : word n.\n  refine (let (l1, _) := w1 in\n            exist _ (firstn n (l1 # falsen (N.to_nat (wto_N w2)))) _).\n  rewrite length_firstn. rewrite app_length. rewrite length_iter_cons.\n  apply min_l. omega.\nDefined.\nInfix \"<<\" := wshl (at level 65, left associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wshl n) with\n  signature weq ==> weq ==> weq as wshl_mor.\nProof.\n  intros w1 w1' ? w2 w2' ?; destruct w1, w1', w2, w2'; simpl in *.\n  subst. reflexivity.\nQed.\n\nDefinition wshr {n : nat} (w1 w2 : word n) : word n.\n  refine (let (l1, _) := w1 in\n            exist _ (skipn (N.to_nat (wto_N w2))\n                           (falsen (N.to_nat (wto_N w2)) # l1)) _).\n  rewrite length_skipn. rewrite app_length. rewrite length_iter_cons.\n  simpl; omega.\nDefined.\nInfix \">>\" := wshr (at level 65, left associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wshr n) with\n  signature weq ==> weq ==> weq as wshr_mor.\nProof.\n  intros w1 w1' ? w2 w2' ?; destruct w1, w1', w2, w2'; simpl in *.\n  subst. reflexivity.\nQed.\n\nDefinition wsar {n : nat} (w1 w2 : word n) : word n.\n  refine (let (l1, _) := w1 in\n            exist _ (skipn (N.to_nat (wto_N w2))\n                           ((nat_iter (N.to_nat (wto_N w2))\n                                      (cons (last l1 false)) nil)\n                           # l1)) _).\n  rewrite length_skipn. rewrite app_length. rewrite length_iter_cons.\n  simpl; omega.\nDefined.\nInfix \">->\" := wsar (at level 65, left associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wsar n) with\n  signature weq ==> weq ==> weq as wsar_mor.\nProof.\n  intros w1 w1' ? w2 w2' ?; destruct w1, w1', w2, w2'; simpl in *.\n  subst. reflexivity.\nQed.\n\nDefinition wopp {n : nat} (w : word n) : word n :=\n  wof_N n (N.succ (wto_N (~w))).\nNotation \"- w\" := (wopp w) (at level 35, right associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wopp n) with\n  signature weq ==> weq as wopp_mor.\nProof.\n  intros w w'; destruct w, w'; simpl; intro.\n  subst. reflexivity.\nQed.\n\nDefinition wadd {n : nat} (w1 w2 : word n) : word n :=\n  wof_N n (wto_N w1 + wto_N w2).\nInfix \"+\" := wadd (at level 50, left associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wadd n) with\n  signature weq ==> weq ==> weq as wadd_mor.\nProof.\n  intros w1 w1' ? w2 w2' ?; destruct w1, w1', w2, w2'; simpl in *.\n  subst. reflexivity.\nQed.\n\nDefinition wsub {n : nat} (w1 w2 : word n) : word n := w1 + (- w2).\nInfix \"-\" := wsub (at level 50, left associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wsub n) with\n  signature weq ==> weq ==> weq as wsub_mor.\nProof.\n  unfold wsub. intros w1 w1' H1 w2 w2' H2.\n  rewrite H1. rewrite H2. reflexivity.\nQed.\n\nDefinition wmul {n : nat} (w1 w2 : word n) : word n :=\n  wof_N n (wto_N w1 * wto_N w2).\nInfix \"*\" := wmul (at level 40, left associativity) : word_scope.\n\nAdd Parametric Morphism (n : nat) : (@wmul n) with\n  signature weq ==> weq ==> weq as wmul_mor.\nProof.\n  intros w1 w1' ? w2 w2' ?; destruct w1, w1', w2, w2'; simpl in *.\n  subst. reflexivity.\nQed.\n\n(******************************************************************************)\n\n(***********************************boolean************************************)\n\nLemma wand_assoc : forall {n : nat} (w1 w2 w3 : word n),\n  w1 & (w2 & w3) == w1 & w2 & w3.\nProof.\n  intros ? w1 w2 w3;\n  destruct w1 as [l1 Hl1], w2 as [l2 Hl2], w3 as [l3 Hl3]; simpl.\n  clear; generalize dependent l3; generalize dependent l2;\n  induction l1; intros l2 l3.\n  - reflexivity.\n  - destruct l2, l3; try reflexivity; simpl. f_equal.\n    + apply andb_assoc.\n    + trivial.\nQed.\n\nLemma wand_comm : forall {n : nat} (w1 w2 : word n),\n  w1 & w2 == w2 & w1.\nProof.\n  intros ? w1 w2; destruct w1 as [l1 Hl1], w2 as [l2 Hl2]; simpl.\n  clear; generalize dependent l2;\n  induction l1; intro l2; destruct l2; try reflexivity.\n  simpl. f_equal.\n  - apply andb_comm.\n  - trivial.\nQed.\n\nLemma wand_wnot_r : forall {n : nat} (w : word n), w & ~w == wfalse n.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal.\n    + apply andb_negb_r.\n    + assumption.\nQed.\n\nLemma weq_iff : forall {n : nat} (w1 w2 : word n),\n  w1 == w2 <-> w1 & ~w2 == wfalse n /\\ w2 & ~w1 == wfalse n.\nProof.\n  intros ? w1 w2; split.\n  - intro H. rewrite <- H.\n    refine ((fun p => conj p p) _).\n    clear; destruct w1 as [l1 Hl1]; subst; simpl; induction l1.\n    + reflexivity.\n    + simpl. f_equal.\n      * apply andb_negb_r.\n      * assumption.\n  - destruct w1 as [l1 Hl1], w2 as [l2 Hl2]; subst; simpl.\n    generalize dependent l2;\n    induction l1 as [| h1 t1 IHt1]; intros l2 H [H1 H2].\n    + destruct l2.\n      * reflexivity.\n      * discriminate.\n    + destruct l2 as [| h2 t2].\n      * discriminate.\n      * destruct h1, h2; try discriminate; f_equal;\n        inversion H; inversion H1; inversion H2; auto.\nQed.\n\nLemma wnot_involutive : forall {n : nat} (w : word n), ~~w == w.\nProof.\n  intros ? w; destruct w as [l Hl]; simpl; clear; induction l.\n  - reflexivity.\n  - simpl. f_equal.\n    + apply negb_involutive.\n    + assumption.\nQed.\n\nLemma wnot_wor : forall {n : nat} (w1 w2 : word n), ~(w1 | w2) == ~w1 & ~w2.\nProof.\n  intros ? w1 w2; destruct w1 as [l1 Hl1], w2 as [l2 Hl2]; simpl.\n  clear; generalize dependent l2;\n  induction l1; intro l2.\n  - reflexivity.\n  - destruct l2.\n    + reflexivity.\n    + simpl. f_equal.\n      * apply negb_orb.\n      * trivial.\nQed.\n\nLemma wnot_wand : forall {n : nat} (w1 w2 : word n), ~(w1 & w2) == ~w1 | ~w2.\nProof.\n  intros ? w1 w2; destruct w1 as [l1 Hl1], w2 as [l2 Hl2]; simpl.\n  clear; generalize dependent l2;\n  induction l1; intro l2.\n  - reflexivity.\n  - destruct l2.\n    + reflexivity.\n    + simpl. f_equal.\n      * apply negb_andb.\n      * trivial.\nQed.\n\nLemma wand_wor_distrib_l : forall {n : nat} (w1 w2 w3 : word n),\n  (w1 | w2) & w3 == w1 & w3 | w2 & w3.\nProof.\n  intros ? w1 w2 w3;\n  destruct w1 as [l1 Hl1], w2 as [l2 Hl2], w3 as [l3 Hl3]; simpl.\n  clear; generalize dependent l3; generalize dependent l2;\n  induction l1; intros l2 l3.\n  - reflexivity.\n  - destruct l2, l3; try reflexivity.\n    simpl. f_equal.\n    + apply andb_orb_distrib_l.\n    + trivial.\nQed.\n\nLemma wand_wor_distrib_r : forall {n : nat} (w1 w2 w3 : word n),\n  w1 & (w2 | w3) == w1 & w2 | w1 & w3.\nProof.\n  intros ? w1 w2 w3;\n  destruct w1 as [l1 Hl1], w2 as [l2 Hl2], w3 as [l3 Hl3]; simpl.\n  clear; generalize dependent l3; generalize dependent l2;\n  induction l1; intros l2 l3.\n  - reflexivity.\n  - destruct l2, l3; try reflexivity.\n    simpl. f_equal.\n    + apply andb_orb_distrib_r.\n    + trivial.\nQed.\n\nLemma wnot_wfalse : forall n : nat, ~wfalse n == wtrue n.\nProof.\n  intro n; induction n.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma wnot_wtrue : forall n : nat, ~wtrue n == wfalse n.\nProof.\n  intro n; induction n.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma wand_wfalse_l : forall {n : nat} (w : word n), wfalse n & w == wfalse n.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma wand_wfalse_r : forall {n : nat} (w : word n), w & wfalse n == wfalse n.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal.\n    + apply andb_false_r.\n    + assumption.\nQed.\n\nLemma wand_wtrue_l : forall {n : nat} (w : word n), wtrue n & w == w.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma wand_wtrue_r : forall {n : nat} (w : word n), w & wtrue n == w.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal.\n    + apply andb_true_r.\n    + assumption.\nQed.\n\nLemma wor_wtrue_l : forall {n : nat} (w : word n), wtrue n | w == wtrue n.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma wor_wtrue_r : forall {n : nat} (w : word n), w | wtrue n == wtrue n.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal.\n    + apply orb_true_r.\n    + assumption.\nQed.\n\nLemma wor_wfalse_l : forall {n : nat} (w : word n), wfalse n | w == w.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal. assumption.\nQed.\n\nLemma wor_wfalse_r : forall {n : nat} (w : word n), w | wfalse n == w.\nProof.\n  intros ? w; destruct w as [l Hl]; subst; simpl; induction l.\n  - reflexivity.\n  - simpl. f_equal.\n    + apply orb_false_r.\n    + assumption.\nQed.\n\nLemma wor_wfalse_intro : forall {n : nat} (w1 w2 : word n),\n  w1 == wfalse n -> w2 == wfalse n -> w1 | w2 == wfalse n.\nProof.\n  intros ? ? ? H1 H2. rewrite H1. rewrite H2. apply wor_wfalse_l.\nQed.\n\nLemma wand_wfalse_intro1 : forall {n : nat} (w1 w2 : word n),\n  w1 == wfalse n -> w1 & w2 == wfalse n.\nProof.\n  intros ? ? ? H. rewrite H. apply wand_wfalse_l.\nQed.\n\nLtac wand_weqf :=\n  lazymatch goal with\n    |- context [wnot _] => repeat rewrite wand_assoc;\n        lazymatch goal with\n        | |- ?E & ~?W == _ =>\n              lazymatch E with\n              | W => apply wand_wnot_r\n              | ?E' & W => rewrite <- (wand_assoc E' W (~W));\n                           rewrite (wand_wnot_r W);\n                           apply wand_wfalse_r\n              | context [W & _] =>\n                  lazymatch E with\n                    ?E1 & ?E2 => rewrite (wand_comm E1 E2); wand_weqf\n                  end\n              | context [_ & W] =>\n                  lazymatch E with\n                    ?E1 & ?E2 => rewrite (wand_comm E1 E2); wand_weqf\n                  end\n              | _ => apply wand_wfalse_intro1; wand_weqf\n              end\n        | |- ?E & ?W == _ => rewrite (wand_comm E W); wand_weqf\n        end\n  end.\n\nLtac weq_bool :=\n  intros; apply weq_iff;\n  repeat (rewrite wnot_involutive || rewrite wnot_wor || rewrite wnot_wand);\n  repeat (rewrite wand_wor_distrib_l || rewrite wand_wor_distrib_r);\n  try rewrite wnot_wfalse; try rewrite wnot_wtrue;\n  repeat (rewrite wand_wfalse_l || rewrite wand_wfalse_r);\n  repeat (rewrite wand_wtrue_l || rewrite wand_wtrue_r);\n  repeat (rewrite wor_wtrue_l || rewrite wor_wtrue_r);\n  repeat (rewrite wor_wfalse_l || rewrite wor_wfalse_r);\n  split; repeat apply wor_wfalse_intro; try reflexivity; try wand_weqf.\n\n(******************************************************************************)\n\n(************************************shift*************************************)\n\nLemma wand_1_wshl : forall {n : nat} (w1 w2 : word n),\n  ~ (w1 == w2) -> ((wof_N n 1) << w1) & ((wof_N n 1) << w2) == wfalse n.\nProof.\n  intros ? w1 w2 H. rewrite weq_iff_Neq in H.\n  rewrite <- Nnat.N2Nat.inj_iff in H.\n  destruct n as [| n'].\n  - reflexivity.\n  - change (blist andb\n      (firstn (S n') (((list_bool_of_N n' 0) # nil~1) #\n                      nat_iter (N.to_nat (wto_N w1)) (cons false) nil))\n      (firstn (S n') (((list_bool_of_N n' 0) # nil~1) #\n                      nat_iter (N.to_nat (wto_N w2)) (cons false) nil)) =\n      nat_iter (S n') (cons false) nil).\n    rewrite blist_firstn. rewrite NPeano.Nat.min_id. rewrite wof_N_0.\n    apply not_eq in H; destruct H.\n    + rewrite (app_assoc (nat_iter (N.to_nat (wto_N w1)) (cons false) nil)).\n      replace (N.to_nat (wto_N w2))\n      with (S (N.to_nat (wto_N w1)) +\n            (N.to_nat (wto_N w2) - S (N.to_nat (wto_N w1))))%nat by omega.\n      rewrite iter_cons_split.\n      rewrite <- (app_assoc (nat_iter (S (N.to_nat (wto_N w1)))\n                                      (cons false) nil)).\n      rewrite blist_app. Focus 2.\n        rewrite app_length. repeat rewrite length_iter_cons. simpl; omega.\n      rewrite blist_andb_falsen_l. rewrite blist_andb_falsen_r.\n      rewrite <- iter_cons_split. rewrite firstn_iter_cons. f_equal.\n      apply min_l. repeat rewrite app_length. repeat rewrite length_iter_cons.\n      repeat rewrite min_l; simpl; omega.\n    + rewrite (app_assoc (nat_iter (N.to_nat (wto_N w2)) (cons false) nil)).\n      replace (N.to_nat (wto_N w1))\n      with (S (N.to_nat (wto_N w2)) +\n            (N.to_nat (wto_N w1) - S (N.to_nat (wto_N w2))))%nat by omega.\n      rewrite iter_cons_split.\n      rewrite <- (app_assoc (nat_iter (S (N.to_nat (wto_N w2)))\n                                      (cons false) nil)).\n      rewrite blist_app. Focus 2.\n        rewrite app_length. repeat rewrite length_iter_cons. simpl; omega.\n      rewrite blist_andb_falsen_l. rewrite blist_andb_falsen_r.\n      rewrite <- iter_cons_split. rewrite firstn_iter_cons. f_equal.\n      apply min_l. repeat rewrite app_length. repeat rewrite length_iter_cons.\n      repeat rewrite min_r; simpl; omega.\nQed.\n\nLtac wand_1_wshl_weqf w1 w2 :=\n  lazymatch goal with\n    |- context [(wof_N _ 1) << w2] => repeat rewrite wand_assoc;\n        lazymatch goal with\n        | |- ?E & ((wof_N _ 1) << w2) == _ =>\n              lazymatch E with\n              | (wof_N _ 1) << w1 => apply wand_1_wshl\n              | ?E' & ((wof_N _ 1) << w1) => rewrite <- (wand_assoc E' _ _);\n                                             rewrite (wand_1_wshl w1 w2);\n                                             try apply wand_wfalse_r\n              | context [((wof_N _ 1) << w1) & _] =>\n                  lazymatch E with\n                    ?E1 & ?E2 => rewrite (wand_comm E1 E2);\n                                 wand_1_wshl_weqf w1 w2\n                  end\n              | context [_ & ((wof_N _ 1) << w1)] =>\n                  lazymatch E with\n                    ?E1 & ?E2 => rewrite (wand_comm E1 E2);\n                                 wand_1_wshl_weqf w1 w2\n                  end\n              end\n        | |- ?E & ?W == _ => rewrite (wand_comm E W); wand_1_wshl_weqf w1 w2\n        end\n  end.\n\n(******************************************************************************)\n\n(*************************************ring*************************************)\n\nLemma wadd_0_l : forall {n : nat} (w : word n), wfalse n + w == w.\nProof.\n  unfold wadd. intros. rewrite wto_N_wfalse. apply wto_N_id.\nQed.\n\nLemma wadd_sym : forall {n : nat} (w1 w2 : word n), w1 + w2 == w2 + w1.\nProof.\n  unfold wadd. intros. rewrite N.add_comm. reflexivity.\nQed.\n\nLemma wadd_assoc : forall {n : nat} (w1 w2 w3 : word n),\n  w1 + (w2 + w3) == w1 + w2 + w3.\nProof.\n  unfold wadd. intros. apply wof_N_weq. repeat rewrite wof_N_mod.\n  rewrite N.add_mod_idemp_l; try discriminate.\n  rewrite N.add_mod_idemp_r; try discriminate.\n  rewrite N.add_assoc. reflexivity.\nQed.\n\nLemma wmul_1_l : forall {n : nat} (w : word n), (wof_N n 1) * w == w.\nProof.\n  unfold wmul. intros n w. rewrite wof_N_mod.\n  destruct n as [| n'].\n  - destruct w as [l Hl]. destruct l; reflexivity || discriminate.\n  - rewrite N.mod_1_l; try reflexivity. rewrite N.mul_1_l. apply wto_N_id.\nQed.\n\nLemma wmul_sym : forall {n : nat} (w1 w2 : word n), w1 * w2 == w2 * w1.\nProof.\n  unfold wmul. intros. rewrite N.mul_comm. reflexivity.\nQed.\n\nLemma wmul_assoc : forall {n : nat} (w1 w2 w3 : word n),\n  w1 * (w2 * w3) == w1 * w2 * w3.\nProof.\n  unfold wmul. intros. apply wof_N_weq. repeat rewrite wof_N_mod.\n  rewrite N.mul_mod_idemp_l; try discriminate.\n  rewrite N.mul_mod_idemp_r; try discriminate.\n  rewrite N.mul_assoc. reflexivity.\nQed.\n\nLemma wdistr_l : forall {n : nat} (w1 w2 w3 : word n),\n  (w1 + w2) * w3 == w1 * w3 + w2 * w3.\nProof.\n  unfold wadd, wmul. intros. apply wof_N_weq. repeat rewrite wof_N_mod.\n  rewrite N.mul_mod_idemp_l; try discriminate.\n  rewrite <- N.add_mod; try discriminate.\n  rewrite N.mul_add_distr_r. reflexivity.\nQed.\n\nLemma wsub_def : forall {n : nat} (w1 w2 : word n), w1 - w2 == w1 + (- w2).\nProof.\n  reflexivity.\nQed.\n\nLemma wopp_def : forall {n : nat} (w : word n), w + (- w) == wfalse n.\nProof.\n  unfold wopp, wadd. intros ? w. rewrite wof_N_mod. apply wof_N_weq.\n  rewrite wto_N_wfalse. rewrite N.add_mod_idemp_r; try discriminate.\n  replace (wto_N w + N.succ (wto_N (~ w)))%N with (N.pos (shift_nat n 1)).\n  - apply N.mod_same. discriminate.\n  - destruct w as [l Hl]; subst; simpl; induction l as [| h t IHt].\n    + reflexivity.\n    + destruct h; simpl.\n      * rewrite N.succ_double_spec. rewrite <- N.add_assoc.\n        rewrite <- N.add_1_l. rewrite (N.add_assoc 1).\n        change (1 + 1)%N with (2 * 1)%N. repeat rewrite <- N.mul_add_distr_l.\n        rewrite N.add_1_l. rewrite <- IHt. reflexivity.\n      * rewrite N.succ_double_spec. rewrite <- N.add_1_r.\n        rewrite <- (N.add_assoc _ 1). change (1 + 1)%N with (2 * 1)%N.\n        rewrite N.double_spec. repeat rewrite <- N.mul_add_distr_l.\n        rewrite N.add_1_r. rewrite <- IHt. reflexivity.\nQed.\n\nModule Type Word.\n  Parameter n : nat.\nEnd Word.\n\nModule RingWord (Import W : Word).\nAdd Ring word_ring : (mk_rt (wfalse n) _ _ _ _ _ _\n  wadd_0_l wadd_sym wadd_assoc\n  wmul_1_l wmul_sym wmul_assoc\n  wdistr_l wsub_def wopp_def).\nEnd RingWord.\n\n(******************************************************************************)\n", "meta": {"author": "guoly15", "repo": "hello-word", "sha": "1ec0fc9e7e3f3ecbfa0b3394973c17102298b82d", "save_path": "github-repos/coq/guoly15-hello-word", "path": "github-repos/coq/guoly15-hello-word/hello-word-1ec0fc9e7e3f3ecbfa0b3394973c17102298b82d/Word.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7033314724397357}}
{"text": "\nRequire Import List Omega.\n\nRequire Import bigstep.\nRequire Import coinduction.\nRequire Import datatypes.\nRequire Import streams_vs_lists.\n\n(* Function div2(n) = n/2       if n is even\n                      undefined otherwise\n\n   Example machine:\n      1 1 -> 1 B\n      1 B -> 2 R\n      2 1 -> 3 R\n      3 B -> 3 R\n      3 1 -> 4 B\n      4 B -> 2 R\n*)\n\nDefinition div2: Spec := (1, one, 1, W B) ::\n                         (1, B  , 2,   R) ::\n                         (2, one, 3,   R) ::\n                         (3, B  , 3,   R) ::\n                         (3, one, 4, W B) ::\n                         (4, B  , 2,   R) :: nil.\n\n(************************ Divergence proof ************************)\n\nFixpoint ones (n:nat) {struct n}: list Sym :=\n         match n with\n         | 0 => nil\n         | (S m) => (cons one (ones m))\n         end.\n\n(*\nloop from state 3, if Bs on the right\n*)\n\nLemma div2_loops_3B: forall l,\n      bi div2 (pair l Bs) 3.\ncofix co_hp.\nintro. apply biR with 3.\nauto.\nsimpl. apply co_hp.\nQed.\n\n(*\nloop from state 2, if an odd number of \"1\"\n*)\n\nLemma div2_loops_2odd: forall n l,\n      bi div2 (pair l (app_ls (ones (2*n + 1)) Bs)) 2.\ninduction n; intro.\n\nsimpl. apply biR with 3.\nauto.\nsimpl. apply div2_loops_3B.\n\nreplace (2*S n + 1) with (S (S (2*n + 1))).\nsimpl. apply biR with 3.\nauto.\nsimpl. apply biW with 4 B.\nauto.\nsimpl. apply biR with 2.\nauto.\nsimpl. replace (n + (n + 0) + 1) with (2*n + 1). apply IHn.\nomega. omega.\nQed.\n\n(*\nloop from the initial state 1\n*)\n\nLemma div2_loops: forall n,\n      bi div2 (pair Bs (Cons one (app_ls (ones (2*n + 1)) Bs))) 1.\nintros. apply biW with 1 B.\nauto.\nsimpl. apply biR with 2.\nauto.\nsimpl. replace (n + (n + 0) + 1) with (2*n + 1). apply div2_loops_2odd.\nomega.\nQed.\n", "meta": {"author": "asr", "repo": "tm-coinduction", "sha": "599083b74ffdf0c1032c5c2495fef9bf23a4058c", "save_path": "github-repos/coq/asr-tm-coinduction", "path": "github-repos/coq/asr-tm-coinduction/tm-coinduction-599083b74ffdf0c1032c5c2495fef9bf23a4058c/animation/examples/Ndiv2oo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8128673223709252, "lm_q1q2_score": 0.7033123832552414}}
{"text": "Require Import Ensembles.\nRequire Import Coq.Lists.List.\nRequire Import ListExt.\n\nRequire Import folProp.\nRequire Import folProof.\nRequire Export folLogic.\nRequire Import subProp.\nRequire Import folReplace.\nRequire Import Arith.\n\nSection More_Logic_Rules.\n\nVariable L : Language.\nLet Formula := Formula L.\nLet Formulas := Formulas L.\nLet System := System L.\nLet Term := Term L.\nLet Terms := Terms L.\nLet Prf := Prf L.\nLet SysPrf := SysPrf L.\n\nLemma rebindForall (T : System) (a b : nat) (f : Formula):\n  ~ In b (freeVarFormula L (forallH a f)) ->\n  SysPrf T (iffH (forallH a f) \n              (forallH b (substituteFormula L f a (var b)))).\nProof.\n  intros H; eapply (sysExtend L) with (Empty_set Formula).\n  - intros x H0; destruct H0.\n  - apply (iffI L).\n    + apply (impI L), (forallI L).\n      intros [x [H0 H1]].\n      destruct H1 as [x H1| x H1]; [ induction H1 | induction H1 ].\n      * auto.\n      * apply forallE; apply Axm; right; constructor.\n    + apply (impI L), (forallI L).\n      intros [x [H0 H1]] ; destruct H1 as [x H1| x H1]; \n        [induction H1 | induction H1].\n     * assert (H1: In a (freeVarFormula L (substituteFormula L f a (var b))))\n       by (eapply in_remove; apply H0).\n       induction (freeVarSubFormula3 _ _ _ _ _ H1).\n       elim (in_remove_neq _ _ _ _ _ H2).\n       -- auto.\n       -- elim (in_remove_neq _ _ _ _ _ H0).\n          destruct H2 as [H2| H2].\n          auto.\n          elim H2.\n     * set (A1 := forallH b (substituteFormula L f a (var b))) in *.\n       rewrite <- (subFormulaId L f a).\n       apply (impE L) with\n         (substituteFormula L (substituteFormula L f a (var b)) b \n            (var a)).\n       -- apply (iffE1 L).\n          apply (subFormulaTrans L); apply H.\n       -- apply forallE, Axm; right; constructor.\nQed.\n\nLemma rebindExist (T : System) (a b : nat) (f : Formula):\n  ~ In b (freeVarFormula L (existH a f)) ->\n  SysPrf T (iffH (existH a f) (existH b (substituteFormula L f a (var b)))).\nProof.\n  intro H; unfold existH.  \n  apply (reduceNot L); eapply (iffTrans L).\n  - apply (rebindForall T a b (notH f)), H. \n  - rewrite (subFormulaNot L); apply (iffRefl L).\nQed.\n\nLemma subSubTerm (t : Term) (v1 v2 : nat) (s1 s2 : Term):\n  v1 <> v2 ->\n  ~ In v1 (freeVarTerm L s2) ->\n  substituteTerm L (substituteTerm L t v1 s1) v2 s2 =\n    substituteTerm L \n      (substituteTerm L t v2 s2) v1 (substituteTerm L s1 v2 s2).\nProof.\n  intros H H0. \n  elim t using Term_Terms_ind with\n    (P0 := fun (n : nat) (ts : fol.Terms L n) =>\n             substituteTerms L n (substituteTerms L n ts v1 s1) v2 s2 =\n               substituteTerms L n (substituteTerms L n ts v2 s2) v1\n                 (substituteTerm L s1 v2 s2)); simpl in |- *.\n  - intros n. \n    destruct (eq_nat_dec v1 n)  as [ e | n0].\n    + destruct (eq_nat_dec v2 n)  as [e0 | n0].\n      * elim H; transitivity n; auto.\n      * simpl in |- *; destruct (eq_nat_dec v1 n)as [e0 | n1].\n        -- reflexivity.\n        -- elim n1;auto.\n    + simpl in |- *; destruct (eq_nat_dec v2 n) as [e | n1].\n      * rewrite subTermNil; easy. \n      * simpl in |- *; destruct (eq_nat_dec v1 n) as [e | ].\n        --  elim n0; auto.\n        -- reflexivity.\n  - intros f t0 H1;  rewrite H1; reflexivity.\n  - reflexivity.\n  - intros  n t0 H1 t1 H2; rewrite H1, H2; easy. \nQed.\n\nLemma subSubTerms (n : nat) (ts : Terms n) (v1 v2 : nat) (s1 s2 : Term):\n  v1 <> v2 ->\n  ~ In v1 (freeVarTerm L s2) ->\n  substituteTerms L n (substituteTerms L n ts v1 s1) v2 s2 =\n    substituteTerms L n (substituteTerms L n ts v2 s2) v1\n      (substituteTerm L s1 v2 s2).\nProof.\n  intros H H0; induction ts as [| n t ts Hrects].\n  - reflexivity.\n  - simpl in |- *; rewrite Hrects, subSubTerm.\n    + reflexivity.\n    + assumption. \n    + assumption.\nQed.\n\nLemma subSubFormula (f : Formula) (v1 v2 : nat) (s1 s2 : Term):\n v1 <> v2 ->\n ~ In v1 (freeVarTerm L s2) ->\n forall T : System,\n SysPrf T\n   (iffH (substituteFormula L (substituteFormula L f v1 s1) v2 s2)\n      (substituteFormula L (substituteFormula L f v2 s2) v1\n         (substituteTerm L s1 v2 s2))).\nProof.\n  intros H H0 T; apply (sysExtend L) with (Empty_set Formula).\n  - intros x H1; destruct H1.\n  - elim f using Formula_depth_ind2; intros.\n    + repeat rewrite (subFormulaEqual L).\n      rewrite subSubTerm; auto.\n      rewrite (subSubTerm t0); auto.\n      apply (iffRefl L).\n    + repeat rewrite (subFormulaRelation L).\n      rewrite subSubTerms; auto.\n      apply (iffRefl L).\n    + repeat rewrite (subFormulaImp L).\n      apply (reduceImp L); auto.\n    + repeat rewrite (subFormulaNot L).\n      apply (reduceNot L); auto.\n    + set (v' :=\n             newVar\n               (v1\n                  :: v2\n                  :: freeVarFormula L (forallH v a) ++\n                  freeVarTerm L s1 ++ freeVarTerm L s2)) in *.\n      assert (H2: v' <> v1).\n      { intro H2;\n        elim\n          (newVar1\n             (v1\n                :: v2\n                :: freeVarFormula L (forallH v a) ++\n                freeVarTerm L s1 ++ freeVarTerm L s2)).\n        fold v' ; simpl; auto.\n      } \n      assert (H3: v' <> v2).\n      { intro H3; \n        elim\n          (newVar1\n             (v1\n                :: v2\n                :: freeVarFormula L (forallH v a) ++\n                freeVarTerm L s1 ++ freeVarTerm L s2)).\n        fold v'; simpl; auto.\n      } \n      assert (H4: ~ In v' (freeVarFormula L (forallH v a))).\n      { intro H4; \n        elim\n          (newVar1\n             (v1\n                :: v2\n                :: freeVarFormula L (forallH v a) ++\n                freeVarTerm L s1 ++ freeVarTerm L s2)).\n        fold v' ;simpl; auto with datatypes.\n      } \n      assert (H5: ~ In v' (freeVarTerm L s1)).\n      { intro H5; \n        elim\n          (newVar1\n             (v1\n                :: v2\n                :: freeVarFormula L (forallH v a) ++\n                freeVarTerm L s1 ++ freeVarTerm L s2)).\n        fold v' ;  simpl; repeat right; auto with datatypes.\n      } \n      assert (H6: ~ In v' (freeVarTerm L s2)).\n      { intro H6; \n          elim\n            (newVar1\n               (v1\n                  :: v2\n                  :: freeVarFormula L (forallH v a) ++\n                  freeVarTerm L s1 ++ freeVarTerm L s2)).\n       fold v' ; simpl;  repeat right; auto with datatypes.\n     }\n     apply impE with\n       (iffH\n          (substituteFormula L\n             (substituteFormula L\n                (forallH v' (substituteFormula L a v (var v'))) v1 s1) v2\n             s2)\n          (substituteFormula L\n             (substituteFormula L\n                (forallH v' (substituteFormula L a v (var v'))) v2 s2) v1\n             (substituteTerm L s1 v2 s2))).\n     apply (iffE2 L).\n      * assert\n          (H7: folProof.SysPrf L (Empty_set Formula)\n                 (iffH (forallH v a)\n                    (forallH v' (substituteFormula L a v (var v')))))\n          by (apply rebindForall; auto).\n       repeat first\n       [ apply (reduceIff L)\n       | apply (reduceSub L)\n       | apply (notInFreeVarSys L) ]; auto.\n       * assert (H7: \n                  forall (f : Formula) (x v : nat) (s : Term),\n                    x <> v ->\n                    ~ In x (freeVarTerm L s) ->\n                    substituteFormula L (forallH x f) v s =\n                      forallH x (substituteFormula L f v s)). \n         { intros f0 x v0 s H7; rewrite (subFormulaForall L).\n           destruct (eq_nat_dec x v0) as [e | n0].\n           - elim H7; auto.\n           - destruct (In_dec eq_nat_dec x (freeVarTerm L s)) as [i | n1]. \n         + intro H8; elim H8; auto.\n         + reflexivity.\n     }\n     repeat rewrite H7; try easy. \n     --  apply (reduceForall L).\n         apply (notInFreeVarSys L).\n         apply H1.\n         apply eqDepth with a.\n         symmetry  in |- *.\n         apply subFormulaDepth.\n         apply depthForall.\n     --  intro H8; induction (freeVarSubTerm3 _ _ _ _ _ H8).\n         elim H5; eapply in_remove.\n         apply H9.\n         now apply H6. \nQed.\n\nEnd More_Logic_Rules.\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/Ackermann/folLogic2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7033123823914743}}
{"text": "(** * Perm: Basic Techniques for Comparisons and Permutations *)\n\n(** Consider these algorithms and data structures:\n    - sort a sequence of numbers\n    - finite maps from numbers to (arbitrary-type) data\n    - finite maps from any ordered type to (arbitrary-type) data\n    - priority queues: finding/deleting the highest number in a set\n\n    To prove the correctness of such programs, we need to reason about\n    comparisons, and about whether two collections have the same\n    contents.  In this chapter, we introduce some techniques for\n    reasoning about:\n\n    - less-than comparisons on natural numbers, and\n    - permutations (rearrangements of lists).\n\n    In later chapters, we'll apply these proof techniques to reasoning\n    about algorithms and data structures. *)\n\nSet Warnings \"-notation-overridden,-parsing\".\nFrom Coq Require Import Strings.String.  (* for manual grading *)\nFrom Coq Require Export Bool.Bool.\nFrom Coq Require Export Arith.Arith.\nFrom Coq Require Export Arith.EqNat.\nFrom Coq Require Export Omega.\nFrom Coq Require Export Lists.List.\nExport ListNotations.\nFrom Coq Require Export Permutation.\n\n(* ################################################################# *)\n(** * The Less-Than Order on the Natural Numbers *)\n\n(** In our proofs about searching and sorting algorithms, we often\n    have to reason about the less-than order on natural numbers.\n    greater-than. Recall that the Coq standard library contains both\n    propositional and Boolean less-than operators on natural numbers.\n    We write [x < y] for the proposition that [x] is less than [y]: *)\n\nLocate \"_ < _\". (* \"x < y\" := lt x y *)\nCheck lt : nat -> nat -> Prop.\n\n(** And we write [x <? y] for the computation that returns [true] or\n    [false] depending on whether [x] is less than [y]: *)\n\nLocate \"_ <? _\". (* x <? y  := Nat.ltb x y *)\nCheck Nat.ltb : nat -> nat -> bool.\n\n(** Operation [<] is a reflection of [<?], as discussed in\n    [Logic] and [IndProp]. The [Nat] module has a\n    theorem showing how they relate: *)\n\nCheck Nat.ltb_lt : forall n m : nat, (n <? m) = true <-> n < m.\n\n(** The [Nat] module contains a synonym for [lt]. *)\n\nPrint Nat.lt. (* Nat.lt = lt *)\n\n(** For unknown reasons, [Nat] does not define notations\n    for [>?] or [>=?].  So we define them here: *)\n\nNotation  \"a >=? b\" := (Nat.leb b a)\n                          (at level 70) : nat_scope.\nNotation  \"a >? b\"  := (Nat.ltb b a)\n                         (at level 70) : nat_scope.\n\n(* ================================================================= *)\n(** ** The Omega Tactic *)\n\n(** Reasoning about inequalities by hand can be a little painful. Luckily, Coq\n    provides a tactic called [omega] that is quite helpful. *)\n\nTheorem omega_example1:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n\n(** The hard way to prove this is by hand. *)\n\n  (* try to remember the name of the lemma about negation and [<=] *)\n  Search (~ _ <= _ -> _).\n  apply not_le in H0.\n  (* try to remember the name of the transitivity lemma about [>] *)\n  Search (_ > _ -> _ > _ -> _ > _).\n  apply gt_trans with j.\n  apply gt_trans with (k-3).\n  (* Is [k] greater than [k-3]? On the integers, sure. But we're working\n     with natural numbers, which truncate subtraction at zero. *)\nAbort.\n\nTheorem truncated_subtraction: ~ (forall k:nat, k > k - 3).\nProof.\n  intros contra.\n  (* [specialize] applies a hypothesis to an argument *)\n  specialize (contra 0).\n  simpl in contra.\n  inversion contra.\nQed.\n\n(** Since subtraction is truncated, does [omega_example1] actually hold?\n    It does. Let's try again, the hard way, to find the proof. *)\n\nTheorem omega_example1:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof. (* try again! *)\n  intros.\n  apply not_le in H0.\n  unfold gt in H0.\n  unfold gt.\n  (* try to remember the name ... *)\n  Search (_ < _ -> _ <= _ -> _ < _).\n  apply lt_le_trans with j.\n  apply H.\n  apply le_trans with (k-3).\n  Search (_ < _ -> _ <= _).\n  apply lt_le_weak.\n  auto.\n  apply le_minus.\nQed.\n\n(** That was tedious.  Here's a much easier way: *)\n\nTheorem omega_example2:\n forall i j k,\n    i < j ->\n    ~ (k - 3 <= j) ->\n   k > i.\nProof.\n  intros.\n  omega.\nQed.\n\n(** Omega is a decision procedure invented in 1991 by William Pugh for\n    integer linear programming (ILP). The [omega] tactic was made\n    available by importing [Coq.omega.Omega], at the beginning of the\n    file.  It is an implementation of Pugh's algorithm.  The tactic\n    works with Coq types [Z] and [nat], and these operators: [<] [=] [>]\n    [<=] [>=] [+] [-] [~], as well as multiplication by small integer\n    literals (such as 0,1,2,3...), and some uses of [\\/] and [/\\].\n\n    Omega does not \"understand\" other operators.  It treats\n    expressions such as [a * b] and [f x y] as variables.  That is, it\n    can prove [f x y > a * b -> f x y + 3 >= a * b], in the same way it\n    would prove [u > v -> u + 3 >= v]. But it cannot reason about, e.g.,\n    multiplication. *)\n\nTheorem omega_example_3 : forall (f : nat -> nat -> nat) a b x y,\n    f x y > a * b -> f x y + 3 >= a * b.\nProof.\n  intros. omega.\nQed.\n\nTheorem omega_example_4 : forall a b,\n    a * b = b * a.\nProof.\n  intros. Fail omega.\nAbort.\n\n(** The Omega algorithm is NP-complete, so we might expect that\n    this tactic is exponential-time in the worst case.  Indeed,\n    if you have [N] equations, it could take [2^N] time.\n    But in the typical cases that result from reasoning about\n    programs, [omega] is much faster than that. *)\n\n(* ################################################################# *)\n(** * Swapping *)\n\n(** Consider trying to sort a list of natural numbers.  As a small piece of\n    a sorting algorithm, we might need to swap the first two elements of a list\n    if they are out of order. *)\n\nDefinition maybe_swap (al: list nat) : list nat :=\n  match al with\n  | a :: b :: ar => if a >? b then b :: a :: ar else a :: b :: ar\n  | _ => al\n  end.\n\nExample maybe_swap_123:\n  maybe_swap [1; 2; 3] = [1; 2; 3].\nProof. reflexivity. Qed.\n\nExample maybe_swap_321:\n  maybe_swap [3; 2; 1] = [2; 3; 1].\nProof. reflexivity. Qed.\n\n(** Applying [maybe_swap] twice should give the same result as applying it once.\n    That is, [maybe_swap] is _idempotent_. *)\n\nTheorem maybe_swap_idempotent: forall al,\n    maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros [ | a [ | b al]]; simpl; try reflexivity.\n  destruct (b <? a) eqn:Hb_lt_a; simpl.\n  - destruct (a <? b) eqn:Ha_lt_b; simpl.\n    + (** Now what?  We have a contradiction in the hypotheses: it\n          cannot hold that [a] is less than [b] and [b] is less than\n          [a].  Unfortunately, [omega] cannot immediately show that\n          for us, because it reasons about comparisons in [Prop] not\n          [bool]. *)\n      Fail omega.\nAbort.\n\n(** Of course we could finish the proof by reasoning directly about\n    inequalities in [bool].  But this situation is going to occur\n    repeatedly in our study of sorting. *)\n\n(** Let's set up some machinery to enable using [omega] on boolean\n    tests. *)\n\n(* ================================================================= *)\n(** ** Reflection *)\n\n(** The [reflect] type, defined in the standard library (and presented\n    in [IndProp]), relates a proposition to a Boolean. That is,\n    a value of type [reflect P b] contains a proof of [P] if [b] is\n    [true], or a proof of [~ P] if [b] is [false]. *)\n\nPrint reflect.\n(*\nInductive reflect (P : Prop) : bool -> Set :=\n  | ReflectT :   P -> reflect P true\n  | ReflectF : ~ P -> reflect P false\n *)\n\n(** The standard library proves a theorem that says if [P] is provable\n    whenever [b = true] is provable, then [P] reflects [b]. *)\n\nCheck iff_reflect : forall (P : Prop) (b : bool),\n    P <-> b = true -> reflect P b.\n\n(** Using that theorem, we can quickly prove that the propositional\n    (in)equality operators are reflections of the Boolean\n    operators. *)\n\nLemma eqb_reflect : forall x y, reflect (x = y) (x =? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.eqb_eq.\nQed.\n\nLemma ltb_reflect : forall x y, reflect (x < y) (x <? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.ltb_lt.\nQed.\n\nLemma leb_reflect : forall x y, reflect (x <= y) (x <=? y).\nProof.\n  intros x y. apply iff_reflect. symmetry.\n  apply Nat.leb_le.\nQed.\n\n(** Here's an example of how you could use these lemmas.  Suppose you\n    have this simple program, [(if a <? 5 then a else 2)], and you\n    want to prove that it evaluates to a number smaller than 6.  You\n    can use [ltb_reflect] \"by hand\": *)\n\nExample reflect_example1: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros a.\n  (* The next two lines aren't strictly necessary, but they\n     help make it clear what [destruct] does. *)\n  assert (R: reflect (a < 5) (a <? 5)) by apply ltb_reflect.\n  remember (a <? 5) as guard.\n  destruct R as [H|H] eqn:HR.\n  * (* ReflectT *) omega.\n  * (* ReflectF *) omega.\nQed.\n\n(** For the [ReflectT] constructor, the guard [a <? 5] must be equal\n    to [true]. The [if] expression in the goal has already been\n    simplified to take advantage of that fact. Also, for [ReflectT] to\n    have been used, there must be evidence [H] that [a < 5] holds.\n    From there, all that remains is to show [a < 5] entails [a < 6].\n    The [omega] tactic, which is capable of automatically proving some\n    theorems about inequalities, succeeds.\n\n    For the [ReflectF] constructor, the guard [a <? 5] must be equal\n    to [false]. So the [if] expression simplifies to [2 < 6], which is\n    immediately provable by [omega]. *)\n\n(** A less didactic version of the above proof wouldn't do the\n    [assert] and [remember]: we can directly skip to [destruct]. *)\n\nExample reflect_example1': forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros a. destruct (ltb_reflect a 5); omega.\nQed.\n\n(** But even that proof is a little unsatisfactory. The original expression,\n    [a <? 5], is not perfectly apparent from the expression [ltb_reflect a 5]\n    that we pass to [destruct]. *)\n\n(** It would be nice to be able to just say something like [destruct\n    (a <? 5)] and get the reflection \"for free.\"  That's what we'll\n    engineer, next. *)\n\n(* ================================================================= *)\n(** ** A Tactic for Boolean Destruction *)\n\n(** We're now going to build a tactic that you'll want to _use_, but\n    you won't need to understand the details of how to _build_ it\n    yourself.\n\n    Let's put several of these [reflect] lemmas into a Hint database.\n    We call it [bdestruct], because we'll use it in our\n    boolean-destruction tactic: *)\n\nHint Resolve ltb_reflect leb_reflect eqb_reflect : bdestruct.\n\n(** Here is the tactic, the body of which you do not need to\n    understand.  Invoking [bdestruct] on Boolean expression [b] does\n    the same kind of reasoning we did above: reflection and\n    destruction.  It also attempts to simplify negations involving\n    inequalities in hypotheses. *)\n\nLtac bdestruct X :=\n  let H := fresh in let e := fresh \"e\" in\n   evar (e: Prop);\n   assert (H: reflect e X); subst e;\n    [eauto with bdestruct\n    | destruct H as [H|H];\n       [ | try first [apply not_lt in H | apply not_le in H]]].\n\n(** This tactic makes quick, easy-to-read work of our running example. *)\n\nExample reflect_example2: forall a,\n    (if a <? 5 then a else 2) < 6.\nProof.\n  intros.\n  bdestruct (a <? 5);  (* instead of: [destruct (ltb_reflect a 5)]. *)\n  omega.\nQed.\n\n(* ================================================================= *)\n(** ** Finishing the [maybe_swap] Proof *)\n\n(** Now that we have [bdestruct], we can finish the proof of [maybe_swap]'s\n    idempotence. *)\n\nTheorem maybe_swap_idempotent: forall al,\n    maybe_swap (maybe_swap al) = maybe_swap al.\nProof.\n  intros [ | a [ | b al]]; simpl; try reflexivity.\n  bdestruct (a >? b); simpl.\n  (** Note how [b < a] is a hypothesis, rather than [b <? a = true]. *)\n  - bdestruct (b >? a); simpl.\n    + (** [omega] can take care of the contradictory propositional inequalities. *)\n      omega.\n    + reflexivity.\n  - bdestruct (a >? b); simpl.\n    + omega.\n    + reflexivity.\nQed.\n\n(** When proving theorems about a program that uses Boolean\n    comparisons, use [bdestruct] followed by [omega], rather than\n    [destruct] followed by application of various theorems about\n    Boolean operators. *)\n\n(* ################################################################# *)\n(** * Permutations *)\n\n(** Another useful fact about [maybe_swap] is that it doesn't add or\n    remove elements from the list: it only reorders them.  That is,\n    the output list is a permutation of the input.  List [al] is a\n    _permutation_ of list [bl] if the elements of [al] can be\n    reordered to get the list [bl].  Note that reordering does not\n    permit adding or removing duplicate elements. *)\n\n(** Coq's [Permutation] library has an inductive definition of\n    permutations. *)\n\nPrint Permutation.\n\n(*\n Inductive Permutation {A : Type} : list A -> list A -> Prop :=\n    perm_nil : Permutation [] []\n  | perm_skip : forall (x : A) (l l' : list A),\n                Permutation l l' ->\n                Permutation (x :: l) (x :: l')\n  | perm_swap : forall (x y : A) (l : list A),\n                Permutation (y :: x :: l) (x :: y :: l)\n  | perm_trans : forall l l' l'' : list A,\n                 Permutation l l' ->\n                 Permutation l' l'' ->\n                 Permutation l l''.\n *)\n\n(** You might wonder, \"is that really the right definition?\"  And\n    indeed, it's important that we get a right definition, because\n    [Permutation] is going to be used in our specifications of\n    searching and sorting algorithms.  If we have the wrong\n    specification, then all our proofs of \"correctness\" will be\n    useless.\n\n    It's not obvious that this is indeed the right specification of\n    permutations. (It happens to be, but that's not obvious.) To gain\n    confidence that we have the right specification, let's use it\n    prove some properties that permutations ought to have. *)\n\n(** **** Exercise: 2 stars, standard (Permutation_properties) \n\n    Think of some desirable properties of the [Permutation] relation\n    and write them down informally in English, or a mix of Coq and\n    English.  Here are four to get you started:\n\n     - 1. If [Permutation al bl], then [length al = length bl].\n     - 2. If [Permutation al bl], then [Permutation bl al].\n     - 3. [[1;1]] is NOT a permutation of [[1;2]].\n     - 4. [[1;2;3;4]] IS a permutation of [[3;4;2;1]].\n\n   YOUR TASK: Add three more properties. Write them here: *)\n\n(** Now, let's examine all the theorems in the Coq library about\n    permutations: *)\n\nSearch Permutation.  (* Browse through the results of this query! *)\n\n(** Which of the properties that you wrote down above have already\n    been proved as theorems by the Coq library developers?  Answer\n    here:\n\n*)\n(* Do not modify the following line: *)\nDefinition manual_grade_for_Permutation_properties : option (nat*string) := None.\n(** [] *)\n\n(** Let's use the permutation theorems in the library to prove the\n    following theorem. *)\n\nExample butterfly: forall b u t e r f l y : nat,\n  Permutation ([b;u;t;t;e;r]++[f;l;y]) ([f;l;u;t;t;e;r]++[b;y]).\nProof.\n  intros.\n  (** Let's group [[u;t;t;e;r]] together on both sides.  Tactic\n      [change t with u] replaces [t] with [u].  Terms [t] and [u] must\n      be _convertible_, here meaning that they evalute to the same\n      term. *)\n  change [b;u;t;t;e;r] with ([b]++[u;t;t;e;r]).\n  change [f;l;u;t;t;e;r] with ([f;l]++[u;t;t;e;r]).\n\n  (** We don't actually need to know the list elements in\n      [[u;t;t;e;r]].  Let's forget about them and just remember them\n      as a variable named [utter]. *)\n  remember [u;t;t;e;r] as utter. clear Hequtter.\n\n  (** Likewise, let's group [[f;l]] and remember it as a variable. *)\n  change [f;l;y] with ([f;l]++[y]).\n  remember [f;l] as fl. clear Heqfl.\n\n  (** Next, let's cancel [fl] from both sides.  In order to do that,\n      we need to bring it to the beginning of each list. For the right\n      list, that follows easily from the associativity of [++].  *)\n  replace ((fl ++ utter) ++ [b;y]) with (fl ++ utter ++ [b;y])\n    by apply app_assoc.\n\n  (** But for the left list, we can't just use associativity.\n      Instead, we need to reason about permutations and use some\n      library theorems. *)\n  apply perm_trans with (fl ++ [y] ++ ([b] ++ utter)).\n  - replace (fl ++ [y] ++ [b] ++ utter) with ((fl ++ [y]) ++ [b] ++ utter).\n    + apply Permutation_app_comm.\n    + rewrite <- app_assoc. reflexivity.\n\n  - (** A library theorem will now help us cancel [fl]. *)\n    apply Permutation_app_head.\n\n  (** Next let's cancel [utter]. *)\n    apply perm_trans with (utter ++ [y] ++ [b]).\n    + replace ([y] ++ [b] ++ utter) with (([y] ++ [b]) ++ utter).\n      * apply Permutation_app_comm.\n      * rewrite app_assoc. reflexivity.\n    + apply Permutation_app_head.\n\n      (** Finally we're left with just [y] and [b]. *)\n      apply perm_swap.\nQed.\n\n(** That example illustrates a general method for proving permutations\n    involving cons [::] and append [++]:\n\n    - Identify some portion appearing in both sides.\n    - Bring that portion to the front on each side using lemmas such\n      as [Permutation_app_comm] and [perm_swap], with generous use of\n      [perm_trans].\n    - Use [Permutation_app_head] to cancel an appended head.  You can\n      also use [perm_skip] to cancel a single element. *)\n\n(** **** Exercise: 3 stars, standard (permut_example) \n\n    Use the permutation rules in the library to prove the following\n    theorem.  The following [Check] commands are a hint about useful\n    lemmas.  You don't need all of them, and depending on your\n    approach you will find lemmas to be more useful than others. Use\n    [Search Permutation] to find others, if you like. *)\n\nCheck perm_skip.\nCheck perm_trans.\nCheck Permutation_refl.\nCheck Permutation_app_comm.\nCheck app_assoc.\nCheck app_nil_r.\nCheck app_comm_cons.\n\nExample permut_example: forall (a b: list nat),\n  Permutation (5 :: 6 :: a ++ b) ((5 :: b) ++ (6 :: a ++ [])).\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard (not_a_permutation) \n\n    Prove that [[1;1]] is not a permutation of [[1;2]].\n    Hints are given as [Check] commands. *)\n\nCheck Permutation_cons_inv.\nCheck Permutation_length_1_inv.\n\nExample not_a_permutation:\n  ~ Permutation [1;1] [1;2].\nProof.\n(* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Correctness of [maybe_swap] *)\n\n(** Now we can prove that [maybe_swap] is a permutation: it reorders\n    elements but does not add or remove any. *)\n\nTheorem maybe_swap_perm: forall al,\n  Permutation al (maybe_swap al).\nProof.\n  (* WORKED IN CLASS *)\n  unfold maybe_swap.\n  destruct al as [ | a [ | b al]].\n  - simpl. apply perm_nil.\n  - apply Permutation_refl.\n  - bdestruct (b <? a).\n    + apply perm_swap.\n    + apply Permutation_refl.\nQed.\n\n(** And, we can prove that [maybe_swap] permutes elements such that\n    the first is less than or equal to the second. *)\n\nDefinition first_le_second (al: list nat) : Prop :=\n  match al with\n  | a :: b :: _ => a <= b\n  | _ => True\n  end.\n\nTheorem maybe_swap_correct: forall al,\n    Permutation al (maybe_swap al)\n    /\\ first_le_second (maybe_swap al).\nProof.\n  intros. split.\n  - apply maybe_swap_perm.\n  - (* WORKED IN CLASS *)\n    unfold maybe_swap.\n    destruct al as [ | a [ | b al]]; simpl; auto.\n    bdestruct (a >? b); simpl; omega.\nQed.\n\n(* ################################################################# *)\n(** * Summary: Comparisons and Permutations *)\n\n(** To prove correctness of algorithms for sorting and searching,\n    we'll reason about comparisons and permutations using the tools\n    developed in this chapter.  The [maybe_swap] program is a tiny\n    little example of a sorting program.  The proof style in\n    [maybe_swap_correct] will be applied (at a larger scale) in\n    the next few chapters. *)\n\n(** **** Exercise: 3 stars, standard (Forall_perm) \n\n    To close, we define a utility tactic and lemma.  First, the\n    tactic. *)\n\n(** Coq's [inversion H] tactic is so good at extracting\n    information from the hypothesis [H] that [H] sometimes becomes\n    completely redundant, and one might as well [clear] it from the\n    goal.  Then, since the [inversion] typically creates some equality\n    facts, why not then [subst] ?  Tactic [inv] does just that. *)\n\nLtac inv H := inversion H; clear H; subst.\n\n(** Second, the lemma.  You will find [inv] useful in proving it.\n\n    [Forall] is Coq library's version of the [All] proposition defined\n    in [Logic], but defined as an inductive proposition rather\n    than a fixpoint.  Prove this lemma by induction.  You will need to\n    decide what to induct on: [al], [bl], [Permutation al bl], and\n    [Forall f al] are possibilities. *)\n\nTheorem Forall_perm: forall {A} (f: A -> Prop) al bl,\n  Permutation al bl ->\n  Forall f al -> Forall f bl.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n\n(* 2020-08-07 17:08 *)\n", "meta": {"author": "Kraks", "repo": "playground", "sha": "677da3823615d4e241f7d1de05ee9b79ddabb118", "save_path": "github-repos/coq/Kraks-playground", "path": "github-repos/coq/Kraks-playground/playground-677da3823615d4e241f7d1de05ee9b79ddabb118/coq/vfa/Perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.865224073888819, "lm_q1q2_score": 0.7033123801152326}}
{"text": "Require Import list.\nRequire Import fmap.\n\nFixpoint In (a:Type) (x:a) (l:list a) : Prop :=\n    match l with\n    | []        => False\n    | y :: xs   => y = x \\/ In a x xs\n    end.\n\nArguments In {a} _ _.\n\n\n\nLemma In_map : forall (a b:Type) (f:a -> b) (l:list a) (x:a),\n    In x l -> In (f x) (map f l).\nProof.\n    intros a b f l x. induction l as [|y ys H].\n    - intros H. inversion H.\n    - simpl. intros [H'|H'].\n        + left. rewrite H'. reflexivity.\n        + right. apply H. apply H'.\nQed.\n\nLemma In_map_iff : forall (a b:Type) (f:a -> b) (l:list a) (y:b),\n    In y (map f l) <-> exists x, f x = y /\\ In x l.\nProof.\n    intros a b f l y. split.\n    - induction l as [|x xs H].\n        + intros H. inversion H.\n        + simpl. intros [H'|H'].\n            { exists x. split. \n                { exact H'. }\n                { left. reflexivity. }}\n            { apply H in H'. destruct H' as [x' H']. destruct H' as [H1 H2].  \n                exists x'. split.\n                    { exact H1. }\n                    { right. exact H2. }}\n    - intros [x [H1 H2]]. rewrite <- H1. apply In_map. exact H2.\nQed.\n\n\nLemma In_app_iff : forall (a:Type) (l k:list a) (x:a),\n    In x (l ++ k) <-> In x l \\/ In x k.\nProof.\n    intros a l k x. split.\n    - induction l as [|y xs H].\n        + simpl. intros H. right. exact H.\n        + simpl. intros [H'|H'].\n            { left. left. exact H'. }\n            { apply H in H'. destruct H' as [H1|H2].\n                { left. right. exact H1. }\n                { right. exact H2. }}\n    - induction l as [|y xs H]. \n        + intros [H'|H'].\n            { inversion H'. }\n            { exact H'. }\n        + simpl. intros [[H'|H']|H'].\n            { left. exact H'. }\n            { right. apply H. left. exact H'. }\n            { right. apply H. right. exact H'. }\nQed.\n\n\nFixpoint All (a:Type) (P:a -> Prop) (l:list a) : Prop :=\n    match l with\n    | []        => True\n    | x :: xs   => P x /\\ All a P xs\n    end.\n\nArguments All {a} _ _.\n\nLemma All_In : forall (a:Type) (P:a -> Prop) (l:list a),\n    (forall x, In x l -> P x) <-> All P l.\nProof.\n    intros a P l. split.\n    - induction l as [|x xs H].\n        + intros. reflexivity.\n        + simpl. intros H'. split.\n            { apply H'. left. reflexivity. }\n            { apply H. intros x' H0. apply H'. right. exact H0. }\n    - induction l as [|x xs H].\n        + intros H x H'. inversion H'.\n        + simpl. intros [H1 H2] x'[H'|H'].\n            { rewrite <- H'. exact H1. }\n            { apply H. exact H2. exact H'. }\nQed.\n\nLemma In_split : forall (a:Type)(x:a)(l:list a), \n    In x l -> exists k m, l = k ++ x :: m.\nProof.\n    intros a x l. induction l as [|y xs IH].\n    - intros H. inversion H.\n    - intros [H|H].\n        + exists [], xs. simpl. rewrite H. reflexivity.\n        + apply IH in H. clear IH. destruct H as [k [m H]].\n            exists (y :: k), m. rewrite H. rewrite app_cons. reflexivity.\nQed.\n\n\nLemma In_Decidable : forall (a:Type), (forall (x y:a), (x = y) \\/ (x <> y)) -> \n    forall (x:a) (l:list a), In x l \\/ ~In x l.\nProof.\n    intros a EqDec x l. induction l as [|y xs [IH|IH]]. \n    - right. intros H. inversion H.\n    - left. right. exact IH.\n    - destruct (EqDec x y) as [E|E].\n        + left. left. rewrite E. reflexivity.\n        + right. intros [H|H].\n            { apply E. rewrite H. reflexivity. }\n            { apply IH. exact H. }\nQed.\n\n\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/sf/In.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7033123697606124}}
{"text": "(* Software Foundations *)\n(* Exercice 3 stars, alternate *)\n\nInductive natlist: Type:=\n|nil: natlist\n|cons: nat -> natlist -> natlist.\n\nNotation \"[]\" := nil.\nNotation \" x :: l\" := (cons x l).\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nFixpoint alternate (l1 l2 : natlist) : natlist :=\nmatch l1, l2 with\n|nil , _ => l2\n|_ , nil => l1\n|cons h1 t1, cons 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. reflexivity. Qed.\n\nExample test_alternate2 : alternate [1] [4;5;6] = [1;4;5;6]. \nProof. reflexivity. Qed.\n\nExample test_alternate3 : alternate [1;2;3] [4] = [1;4;2;3]. \nProof. reflexivity. Qed.\n\nExample test_alternate4 : alternate [] [20;30] = [20;30]. \nProof. reflexivity. Qed.\n\n", "meta": {"author": "chekkal", "repo": "software-foundations", "sha": "c63ba8ee5ca1d5b6889f74559f7716ffab2141b2", "save_path": "github-repos/coq/chekkal-software-foundations", "path": "github-repos/coq/chekkal-software-foundations/software-foundations-c63ba8ee5ca1d5b6889f74559f7716ffab2141b2/chapter5_Library_List/alternate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.7033123601883482}}
{"text": "\n(** Exercise: 2 points (plus_assoc) *)\nTheorem plus_assoc : forall m n p : nat,\n    m + (n + p) = (m + n) + p.\nProof.\n  induction m; intros; simpl; eauto.\nQed.\n\nModule Number.\n  (** Exercise: 1 point (plus_n_O) *)\n  Theorem plus_n_O : forall n : nat,\n      n = n + 0.\n  Proof.\n    induction n; eauto.\n  Qed.\n\nEnd Number.\n\n(** Bonus question: 5 bonus points (plus_very_hard) *)\nTheorem plus_very_hard : 0 + 0 = 0.\nProof.\n  reflexivity.\nQed.\n\n(** We define a double function. *)\nFixpoint double (n:nat) :=\n  match n with\n  | O => O\n  | S n' => S (S (double n'))\n  end.\n\n(** Also the even predicate. *)\nInductive ev : nat -> Prop :=\n| ev_0 : ev 0\n| ev_SS : forall n : nat, ev n -> ev (S (S n)).\n\nLemma plus_n_Sm : forall n m : nat,\n  S (n + m) = n + (S m).\nProof.\n  induction n; simpl; eauto.\nQed.\n\n(** Exercise: 3 points (plus_plus_double) *)\nTheorem plus_plus_double : forall n : nat,\n    n + n = double n.\nProof.\n  induction n; simpl; eauto.\n  rewrite <- IHn.\n  rewrite <- plus_n_Sm.\n  reflexivity.\nQed.\n\n(** Exercise: 3 points (double_ev) *)\nTheorem double_ev : forall n : nat,\n    ev (double n).\nProof.\n  induction n; eauto using ev.\nQed.\n\n(** Exercise: 1 points (test_plus) *)\nExample test_plus1 : plus 1 1 = 2.\nProof.\n  reflexivity. Qed.\n\nExample test_plus2 : plus 1 2 = 3.\nProof.\n  reflexivity. Qed.\n\nExample test_plus3 : plus 1 3 = 4.\nProof.\n  reflexivity. Qed.\n\n\n(** Exercise: 1 points (test_double) *)\nExample test_double1 : double 1 = 2.\nProof.\n  reflexivity. Qed.\n\nExample test_double2 : double 2 = 4.\nProof.\n  reflexivity. Qed.\n\nExample test_double3 : double 3 = 6.\nProof.\n  reflexivity. Qed.\n\n(* Exercise: 2 point (leb) *)\nFixpoint leb (n m : nat) : bool :=\n  match n, m with\n  | 0, _ => true\n  | S n', 0 => false\n  | S n', S m' => leb n' m'\n  end.\n\n(* Exercise: 2 point (leb_refl) *)\nTheorem leb_refl : forall n, leb n n = true.\nProof.\n  induction n; eauto.\nQed.\n\n(* Exercise: 3 point (leb_succ) *)\n(* State and prove that [n] is smaller than or equal to [S n]. *)\nTheorem leb_succ :\n  forall n, true = leb n (S n).\nProof.\n  induction n; eauto.\nQed.\n\nLemma leb_trans : forall m n p,\n    leb m n = true -> leb n p = true -> leb m p = true.\nProof.\n  induction m; intros.\n  - eauto.\n  - destruct n, p; eauto; easy.\nQed.\n\n(* Exercise: 3 point (leb_double) *)\n(* State and prove that [n] is smaller than or equal to [double n]. *)\nTheorem leb_double :\n  forall n, leb n (double n) = true.\nProof.\n  induction n.\n  simpl. reflexivity.\n  simpl.\n  eapply leb_trans.\n  eauto.\n  symmetry.\n  apply leb_succ.\nQed.\n\n(* Exercise: 10 point (plus_1) *)\nTheorem plus_1 : forall n, plus n 1 = S n.\nProof.\n  induction n; simpl; eauto.\nQed.\n", "meta": {"author": "ccyip", "repo": "CS565Grader", "sha": "6e3c9497d99f416097b6ed521f0558ae631cefc9", "save_path": "github-repos/coq/ccyip-CS565Grader", "path": "github-repos/coq/ccyip-CS565Grader/CS565Grader-6e3c9497d99f416097b6ed521f0558ae631cefc9/example/for_grader/input/hw/00000-135266 - Smart Ass - Nov 23, 2020 1226 PM/hw.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7032881430408704}}
{"text": "(* (c) Copyright 2006-2016 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp\nRequire Import ssrfun ssrbool eqtype ssrnat seq div.\nFrom mathcomp\nRequire Import fintype bigop finset prime fingroup ssralg finalg countalg.\n\n(******************************************************************************)\n(*  Definition of the additive group and ring Zp, represented as 'I_p         *)\n(******************************************************************************)\n(* Definitions:                                                               *)\n(* From fintype.v:                                                            *)\n(*     'I_p == the subtype of integers less than p, taken here as the type of *)\n(*             the integers mod p.                                            *)\n(* This file:                                                                 *)\n(*     inZp == the natural projection from nat into the integers mod p,       *)\n(*             represented as 'I_p. Here p is implicit, but MUST be of the    *)\n(*             form n.+1.                                                     *)\n(* The operations:                                                            *)\n(*      Zp0 == the identity element for addition                              *)\n(*      Zp1 == the identity element for multiplication, and a generator of    *)\n(*             additive group                                                 *)\n(*   Zp_opp == inverse function for addition                                  *)\n(*   Zp_add == addition                                                       *)\n(*   Zp_mul == multiplication                                                 *)\n(*   Zp_inv == inverse function for multiplication                            *)\n(* Note that while 'I_n.+1 has canonical finZmodType and finGroupType         *)\n(* structures, only 'I_n.+2 has a canonical ring structure (it has, in fact,  *)\n(* a canonical finComUnitRing structure), and hence an associated             *)\n(* multiplicative unit finGroupType. To mitigate the issues caused by the     *)\n(* trivial \"ring\" (which is, indeed is NOT a ring in the ssralg/finalg        *)\n(* formalization), we define additional notation:                             *)\n(*       'Z_p == the type of integers mod (max p 2); this is always a proper  *)\n(*               ring, by constructions. Note that 'Z_p is provably equal to  *)\n(*               'I_p if p > 1, and convertible to 'I_p if p is of the form   *)\n(*               n.+2.                                                        *)\n(*       Zp p == the subgroup of integers mod (max p 1) in 'Z_p; this is thus *)\n(*               is thus all of 'Z_p if p > 1, and else the trivial group.    *)\n(* units_Zp p == the group of all units of 'Z_p -- i.e., the group of         *)\n(*               (multiplicative) automorphisms of Zp p.                      *)\n(* We show that Zp and units_Zp are abelian, and compute their orders.        *)\n(* We use a similar technique to represent the prime fields:                  *)\n(*        'F_p == the finite field of integers mod the first prime divisor of *)\n(*                maxn p 2. This is provably equal to 'Z_p and 'I_p if p is   *)\n(*                provably prime, and indeed convertible to the above if p is *)\n(*                a concrete prime such as 2, 5 or 23.                        *)\n(* Note finally that due to the canonical structures it is possible to use    *)\n(* 0%R instead of Zp0, and 1%R instead of Zp1 (for the latter, p must be of   *)\n(* the form n.+2, and 1%R : nat will simplify to 1%N).                        *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope ring_scope.\n\nSection ZpDef.\n\n(***********************************************************************)\n(*                                                                     *)\n(*  Mod p arithmetic on the finite set {0, 1, 2, ..., p - 1}           *)\n(*                                                                     *)\n(***********************************************************************)\n\nVariable p' : nat.\nLocal Notation p := p'.+1.\n\nImplicit Types x y z : 'I_p.\n\n(* Standard injection; val (inZp i) = i %% p *)\nDefinition inZp i := Ordinal (ltn_pmod i (ltn0Sn p')).\nLemma modZp x : x %% p = x.\nProof. by rewrite modn_small ?ltn_ord. Qed.\nLemma valZpK x : inZp x = x.\nProof. by apply: val_inj; rewrite /= modZp. Qed.\n\n(* Operations *)\nDefinition Zp0 : 'I_p := ord0.\nDefinition Zp1 := inZp 1.\nDefinition Zp_opp x := inZp (p - x).\nDefinition Zp_add x y := inZp (x + y).\nDefinition Zp_mul x y := inZp (x * y).\nDefinition Zp_inv x := if coprime p x then inZp (egcdn x p).1 else x.\n\n(* Additive group structure. *)\n\nLemma Zp_add0z : left_id Zp0 Zp_add.\nProof. exact: valZpK. Qed.\n\nLemma Zp_addNz : left_inverse Zp0 Zp_opp Zp_add.\nProof.\nby move=> x; apply: val_inj; rewrite /= modnDml subnK ?modnn // ltnW.\nQed.\n\nLemma Zp_addA : associative Zp_add.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modnDml modnDmr addnA.\nQed.\n\nLemma Zp_addC : commutative Zp_add.\nProof. by move=> x y; apply: val_inj; rewrite /= addnC. Qed.\n\nDefinition Zp_zmodMixin := ZmodMixin Zp_addA Zp_addC Zp_add0z Zp_addNz.\nCanonical Zp_zmodType := Eval hnf in ZmodType 'I_p Zp_zmodMixin.\nCanonical Zp_finZmodType := Eval hnf in [finZmodType of 'I_p].\nCanonical Zp_baseFinGroupType := Eval hnf in [baseFinGroupType of 'I_p for +%R].\nCanonical Zp_finGroupType := Eval hnf in [finGroupType of 'I_p for +%R].\n\n(* Ring operations *)\n\nLemma Zp_mul1z : left_id Zp1 Zp_mul.\nProof. by move=> x; apply: val_inj; rewrite /= modnMml mul1n modZp. Qed.\n\nLemma Zp_mulC : commutative Zp_mul.\nProof. by move=> x y; apply: val_inj; rewrite /= mulnC. Qed.\n\nLemma Zp_mulz1 : right_id Zp1 Zp_mul.\nProof. by move=> x; rewrite Zp_mulC Zp_mul1z. Qed.\n\nLemma Zp_mulA : associative Zp_mul.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modnMml modnMmr mulnA.\nQed.\n\nLemma Zp_mul_addr : right_distributive Zp_mul Zp_add.\nProof.\nby move=> x y z; apply: val_inj; rewrite /= modnMmr modnDm mulnDr.\nQed.\n\nLemma Zp_mul_addl : left_distributive Zp_mul Zp_add.\nProof. by move=> x y z; rewrite -!(Zp_mulC z) Zp_mul_addr. Qed.\n\nLemma Zp_mulVz x : coprime p x -> Zp_mul (Zp_inv x) x = Zp1.\nProof.\nmove=> co_p_x; apply: val_inj; rewrite /Zp_inv co_p_x /= modnMml.\nby rewrite -(chinese_modl co_p_x 1 0) /chinese addn0 mul1n mulnC.\nQed.\n\nLemma Zp_mulzV x : coprime p x -> Zp_mul x (Zp_inv x) = Zp1.\nProof. by move=> Ux; rewrite /= Zp_mulC Zp_mulVz. Qed.\n\nLemma Zp_intro_unit x y : Zp_mul y x = Zp1 -> coprime p x.\nProof.\ncase=> yx1; have:= coprimen1 p.\nby rewrite -coprime_modr -yx1 coprime_modr coprime_mulr; case/andP.\nQed.\n\nLemma Zp_inv_out x : ~~ coprime p x -> Zp_inv x = x.\nProof. by rewrite /Zp_inv => /negPf->. Qed.\n\nLemma Zp_mulrn x n : x *+ n = inZp (x * n).\nProof.\napply: val_inj => /=; elim: n => [|n IHn]; first by rewrite muln0 modn_small.\nby rewrite !GRing.mulrS /= IHn modnDmr mulnS.\nQed.\n\nImport GroupScope.\n\nLemma Zp_mulgC : @commutative 'I_p _ mulg.\nProof. exact: Zp_addC. Qed.\n\nLemma Zp_abelian : abelian [set: 'I_p].\nProof. exact: FinRing.zmod_abelian. Qed.\n\nLemma Zp_expg x n : x ^+ n = inZp (x * n).\nProof. exact: Zp_mulrn. Qed.\n\nLemma Zp1_expgz x : Zp1 ^+ x = x.\nProof. by rewrite Zp_expg; apply: Zp_mul1z. Qed.\n\nLemma Zp_cycle : setT = <[Zp1]>.\nProof. by apply/setP=> x; rewrite -[x]Zp1_expgz inE groupX ?mem_gen ?set11. Qed.\n\nLemma order_Zp1 : #[Zp1] = p.\nProof. by rewrite orderE -Zp_cycle cardsT card_ord. Qed.\n\nEnd ZpDef.\n\nArguments Zp0 {p'}.\nArguments Zp1 {p'}.\nArguments inZp {p'} i.\nArguments valZpK {p'} x.\n\nLemma ord1 : all_equal_to (0 : 'I_1).\nProof. by case=> [[] // ?]; apply: val_inj. Qed.\n\nLemma lshift0 m n : lshift m (0 : 'I_n.+1) = (0 : 'I_(n + m).+1).\nProof. exact: val_inj. Qed.\n\nLemma rshift1 n : @rshift 1 n =1 lift (0 : 'I_n.+1).\nProof. by move=> i; apply: val_inj. Qed.\n\nLemma split1 n i :\n  split (i : 'I_(1 + n)) = oapp (@inr _ _) (inl _ 0) (unlift 0 i).\nProof.\ncase: unliftP => [i'|] -> /=.\n  by rewrite -rshift1 (unsplitK (inr _ _)).\nby rewrite -(lshift0 n 0) (unsplitK (inl _ _)).\nQed.\n\nLemma big_ord1 R idx (op : @Monoid.law R idx) F :\n  \\big[op/idx]_(i < 1) F i = F 0.\nProof. by rewrite big_ord_recl big_ord0 Monoid.mulm1. Qed.\n\nLemma big_ord1_cond R idx (op : @Monoid.law R idx) P F :\n  \\big[op/idx]_(i < 1 | P i) F i = if P 0 then F 0 else idx.\nProof. by rewrite big_mkcond big_ord1. Qed.\n\nSection ZpRing.\n\nVariable p' : nat.\nLocal Notation p := p'.+2.\n\nLemma Zp_nontrivial : Zp1 != 0 :> 'I_p. Proof. by []. Qed.\n\nDefinition Zp_ringMixin :=\n  ComRingMixin (@Zp_mulA _) (@Zp_mulC _) (@Zp_mul1z _) (@Zp_mul_addl _)\n               Zp_nontrivial.\nCanonical Zp_ringType := Eval hnf in RingType 'I_p Zp_ringMixin.\nCanonical Zp_finRingType := Eval hnf in [finRingType of 'I_p].\nCanonical Zp_comRingType := Eval hnf in ComRingType 'I_p (@Zp_mulC _).\nCanonical Zp_finComRingType := Eval hnf in [finComRingType of 'I_p].\n\nDefinition Zp_unitRingMixin :=\n  ComUnitRingMixin (@Zp_mulVz _) (@Zp_intro_unit _) (@Zp_inv_out _).\nCanonical Zp_unitRingType := Eval hnf in UnitRingType 'I_p Zp_unitRingMixin.\nCanonical Zp_finUnitRingType := Eval hnf in [finUnitRingType of 'I_p].\nCanonical Zp_comUnitRingType := Eval hnf in [comUnitRingType of 'I_p].\nCanonical Zp_finComUnitRingType := Eval hnf in [finComUnitRingType of 'I_p].\n\nLemma Zp_nat n : n%:R = inZp n :> 'I_p.\nProof. by apply: val_inj; rewrite [n%:R]Zp_mulrn /= modnMml mul1n. Qed.\n\nLemma natr_Zp (x : 'I_p) : x%:R = x.\nProof. by rewrite Zp_nat valZpK. Qed.\n\nLemma natr_negZp (x : 'I_p) : (- x)%:R = - x.\nProof. by apply: val_inj; rewrite /= Zp_nat /= modn_mod. Qed.\n\nImport GroupScope.\n\nLemma unit_Zp_mulgC : @commutative {unit 'I_p} _ mulg.\nProof. by move=> u v; apply: val_inj; rewrite /= GRing.mulrC. Qed.\n\nLemma unit_Zp_expg (u : {unit 'I_p}) n :\n  val (u ^+ n) = inZp (val u ^ n) :> 'I_p.\nProof.\napply: val_inj => /=; elim: n => [|n IHn] //.\nby rewrite expgS /= IHn expnS modnMmr.\nQed.\n\nEnd ZpRing.\n\nDefinition Zp_trunc p := p.-2.\n\nNotation \"''Z_' p\" := 'I_(Zp_trunc p).+2\n  (at level 8, p at level 2, format \"''Z_' p\") : type_scope.\nNotation \"''F_' p\" := 'Z_(pdiv p)\n  (at level 8, p at level 2, format \"''F_' p\") : type_scope.\n\nArguments natr_Zp {p'} x.\n\nSection Groups.\n\nVariable p : nat.\n\nDefinition Zp := if p > 1 then [set: 'Z_p] else 1%g.\nDefinition units_Zp := [set: {unit 'Z_p}].\n\nLemma Zp_cast : p > 1 -> (Zp_trunc p).+2 = p.\nProof. by case: p => [|[]]. Qed.\n\nLemma val_Zp_nat (p_gt1 : p > 1) n : (n%:R : 'Z_p) = (n %% p)%N :> nat.\nProof. by rewrite Zp_nat /= Zp_cast. Qed.\n\nLemma Zp_nat_mod (p_gt1 : p > 1)m : (m %% p)%:R = m%:R :> 'Z_p.\nProof. by apply: ord_inj; rewrite !val_Zp_nat // modn_mod. Qed.\n\nLemma char_Zp : p > 1 -> p%:R = 0 :> 'Z_p.\nProof. by move=> p_gt1; rewrite -Zp_nat_mod ?modnn. Qed.\n\nLemma unitZpE x : p > 1 -> ((x%:R : 'Z_p) \\is a GRing.unit) = coprime p x.\nProof.\nby move=> p_gt1; rewrite qualifE /= val_Zp_nat ?Zp_cast ?coprime_modr.\nQed.\n\nLemma Zp_group_set : group_set Zp.\nProof. by rewrite /Zp; case: (p > 1); apply: groupP. Qed.\nCanonical Zp_group := Group Zp_group_set.\n\nLemma card_Zp : p > 0 -> #|Zp| = p.\nProof.\nrewrite /Zp; case: p => [|[|p']] //= _; first by rewrite cards1.\nby rewrite cardsT card_ord.\nQed.\n\nLemma mem_Zp x : p > 1 -> x \\in Zp. Proof. by rewrite /Zp => ->. Qed.\n\nCanonical units_Zp_group := [group of units_Zp].\n\nLemma card_units_Zp : p > 0 -> #|units_Zp| = totient p.\nProof.\nmove=> p_gt0; transitivity (totient p.-2.+2); last by case: p p_gt0 => [|[|p']].\nrewrite cardsT card_sub -sum1_card big_mkcond /=.\nby rewrite totient_count_coprime big_mkord.\nQed.\n\nLemma units_Zp_abelian : abelian units_Zp.\nProof. by apply/centsP=> u _ v _; apply: unit_Zp_mulgC. Qed.\n\nEnd Groups.\n\n(* Field structure for primes. *)\n\nSection PrimeField.\n\nOpen Scope ring_scope.\n\nVariable p : nat.\n\nSection F_prime.\n\nHypothesis p_pr : prime p.\n\nLemma Fp_Zcast : (Zp_trunc (pdiv p)).+2 = (Zp_trunc p).+2.\nProof. by rewrite /pdiv primes_prime. Qed.\n\nLemma Fp_cast : (Zp_trunc (pdiv p)).+2 = p.\nProof. by rewrite Fp_Zcast ?Zp_cast ?prime_gt1. Qed.\n\nLemma card_Fp : #|'F_p| = p.\nProof. by rewrite card_ord Fp_cast. Qed.\n\nLemma val_Fp_nat n : (n%:R : 'F_p) = (n %% p)%N :> nat.\nProof. by rewrite Zp_nat /= Fp_cast. Qed.\n\nLemma Fp_nat_mod m : (m %% p)%:R = m%:R :> 'F_p.\nProof. by apply: ord_inj; rewrite !val_Fp_nat // modn_mod. Qed.\n\nLemma char_Fp : p \\in [char 'F_p].\nProof. by rewrite !inE -Fp_nat_mod p_pr ?modnn. Qed.\n\nLemma char_Fp_0 : p%:R = 0 :> 'F_p.\nProof. exact: GRing.charf0 char_Fp. Qed.\n\nLemma unitFpE x : ((x%:R : 'F_p) \\is a GRing.unit) = coprime p x.\nProof. by rewrite pdiv_id // unitZpE // prime_gt1. Qed.\n\nEnd F_prime.\n\nLemma Fp_fieldMixin : GRing.Field.mixin_of [the unitRingType of 'F_p].\nProof.\nmove=> x nzx; rewrite qualifE /= prime_coprime ?gtnNdvd ?lt0n //.\ncase: (ltnP 1 p) => [lt1p | ]; last by case: p => [|[|p']].\nby rewrite Zp_cast ?prime_gt1 ?pdiv_prime.\nQed.\n\nDefinition Fp_idomainMixin := FieldIdomainMixin Fp_fieldMixin.\n\nCanonical Fp_idomainType := Eval hnf in IdomainType 'F_p  Fp_idomainMixin.\nCanonical Fp_finIdomainType := Eval hnf in [finIdomainType of 'F_p].\nCanonical Fp_fieldType := Eval hnf in FieldType 'F_p Fp_fieldMixin.\nCanonical Fp_finFieldType := Eval hnf in [finFieldType of 'F_p].\nCanonical Fp_decFieldType :=\n  Eval hnf in [decFieldType of 'F_p for Fp_finFieldType].\n\nEnd PrimeField.\n\nCanonical Zp_countZmodType m := [countZmodType of 'I_m.+1].\nCanonical Zp_countRingType m := [countRingType of 'I_m.+2].\nCanonical Zp_countComRingType m := [countComRingType of 'I_m.+2].\nCanonical Zp_countUnitRingType m := [countUnitRingType of 'I_m.+2].\nCanonical Zp_countComUnitRingType m := [countComUnitRingType of 'I_m.+2].\nCanonical Fp_countIdomainType p := [countIdomainType of 'F_p].\nCanonical Fp_countFieldType p := [countFieldType of 'F_p].\nCanonical Fp_countDecFieldType p := [countDecFieldType of 'F_p].\n", "meta": {"author": "palmskog", "repo": "mathcomp-experiment", "sha": "67a6e83c025784b1e6f646a30dde38e0f33060eb", "save_path": "github-repos/coq/palmskog-mathcomp-experiment", "path": "github-repos/coq/palmskog-mathcomp-experiment/mathcomp-experiment-67a6e83c025784b1e6f646a30dde38e0f33060eb/algebra/zmodp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.7032881156631728}}
{"text": "Require Export NatList.\n\nCheck (pair 3 4).\n\nInductive list (X: Type) : Type :=\n  | nil : list X\n  | cons : X -> list X -> list X.\n\nCheck nil.\nCheck nil nat.\n\nCheck cons.\n\nCheck cons nat.\nCheck cons nat 3.\nCheck cons nat 3 (nil nat).\n\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\nModule MumbleGrumble.\n\n\nInductive mumble : Type :=\n  | a : mumble\n  | b : mumble -> nat -> mumble\n  | c : mumble.\n\nInductive grumble (X:Type) : Type :=\n  | d : mumble -> grumble X\n  | e : X -> grumble X.\n\nCheck d.\nCheck d nat.\nCheck e.\nCheck e nat.\n\n(* d (b a 5 ) is invalid *) \n\nCheck d nat (b a 5).\n\nCheck d mumble (b a 5).\n\nCheck d bool (b a 5).\n\nCheck e bool true.\n\nCheck e mumble (b c 0).\n\n(* Check e bool (b c 0). is not valid *)\n\nEnd MumbleGrumble.\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\nFixpoint app {X : Type} (l1 l2 : list X) : (list X) :=\n  match l1 with\n  | nil => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nFail Definition mynil := nil.\n\nDefinition mynil : list nat := nil.\n\nCheck nil.\n\nCheck @nil.\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n\nDefinition list123''' := [1; 2; 3].\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X l.\n  induction l as [| n l'].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl'. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros A l m n.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl. reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1.\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHl1. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1.\n  - simpl. rewrite -> app_nil_r. reflexivity.\n  - simpl. rewrite -> IHl1. rewrite -> app_assoc.\n    reflexivity.\nQed.\n\nTheorem rev_involutive_helper : forall X : Type, forall l : list X, forall x: X,\n      rev (l ++ [x]) = [x] ++ rev l.\nProof.\n  intros X l x.\n  induction l.\n  - simpl. reflexivity.\n  - simpl.\n    rewrite -> IHl.\n    rewrite <- app_assoc at 1.\n    simpl. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros X l.\n  induction l.\n  - simpl. reflexivity.\n  - simpl. \n    rewrite -> rev_involutive_helper.\n    rewrite -> IHl at 1.\n    simpl.\n    reflexivity.\nQed.\n\nInductive prod (X Y : Type) : Type :=\n| pair : X -> Y -> prod X Y.\n\nArguments pair {X} {Y} _ _.\n\nNotation \"( x , y )\" := (pair x y).\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\nCheck @combine.\n\nCompute (combine [1;2] [false;false;true;true]).\n\nFixpoint split {A B} (l : list (A * B)) : list A * list B :=\n  match l with\n    [] => ([], [])\n  | (x, y) :: xs => let (xs2, ys2) := split xs in (x::xs2, y::ys2)\n  end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n  simpl.\n  reflexivity.\nQed.\n\nInductive option (X:Type) : Type :=\n  | Some : X -> option X\n  | None : option X.\n\nArguments Some {X} _.\nArguments None {X}.\n\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if beq_nat n O then Some a else nth_error l' (pred n)\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 [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\nDefinition doit3times {X:Type} (f:X -> X) (n:X) : X :=\n  f (f (f n)).\n\nCheck @doit3times.\n(* ===> doit3times : forall X : Type, (X -> X) -> X -> X *)\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | [] => []\n  | h :: t => if test h then h :: (filter test t)\n                        else filter test t\n  end.\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  beq_nat (length l) 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1: countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2: countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3: countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\nExample test_filter2':\n    filter (fun l => beq_nat (length l) 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nCheck filter.\n\nFixpoint is_even (n : nat) : bool :=\n  match n with\n  | O => true\n  | S O => false\n  | (S (S n')) => is_even n'\n  end.\n\nCheck ble_nat.\nPrint ble_nat.\nLocate ble_nat.\nCheck and.\nLocate and.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => andb (is_even n) (ble_nat 8 n)) l.\n\nEval compute in filter_even_gt7 [1;2;6;9;10;3;12;8].\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. \n  simpl.\n  reflexivity.\nQed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. reflexivity. Qed.\n\nDefinition partition {X : Type} (test : X -> bool) (l : list X) : list X * list X :=\n  (filter (fun n => test n) l, filter (fun n => negb (test n)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\nFixpoint map {X Y:Type} (f:X -> Y) (l:list X) : (list Y) :=\n  match l with\n  | [] => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed.\n\nLemma map_helper : forall (X Y : Type) (f : X -> Y) (a b : list X),\n    map f (a ++ b) = map f a ++ map f b.\nProof.\n  intros X Y f a b.\n  induction a as [|].\n  - simpl. reflexivity.\n  - simpl. rewrite -> IHa. reflexivity.\nQed.\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [| n l' IHl].\n  - simpl. reflexivity.\n  - simpl. \n    rewrite -> map_helper with (a := rev l') (b := [n]) at 1.\n    rewrite -> IHl at 1.\n    simpl.\n    reflexivity.\nQed.\n\nFixpoint flat_map {X Y:Type} (f:X -> list Y) (l:list X) : (list Y) :=\n  match l with\n    | [] => []\n    | (x :: xs) => f x ++ flat_map f xs\n  end.\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. reflexivity. Qed.\n\nFixpoint fold {X Y:Type} (f: X -> Y -> Y) (l:list X) (b:Y) : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\nCheck (fold andb).\n\nEval compute in (fold andb [true; true; false] true).\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\nDefinition constfun {X: Type} (x: X) : nat -> X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\nDefinition plus3 := plus 3.\nCheck plus3.\n\nExample test_plus3 : plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' : doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' : doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\nModule Exercises.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [| n l' IHl'].\n  - simpl.\n    unfold fold_length.\n    simpl.\n    reflexivity.\n  - simpl.\n    unfold fold_length.\n    simpl.\n    fold (fold_length l').\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\n    \nCheck fold.\n\nDefinition fold_map {X Y:Type} (f : X -> Y) (l : list X) : list Y :=\n  fold (fun y ys => f y :: ys) l [].\n\nTheorem fold_map_correct: forall X Y (l : list X) (f : X -> Y),\n    map f l = fold_map f l.\nProof.\n  intros X Y l f.\n  induction l as [|n l' IHl'].\n  - simpl. \n    unfold fold_map.\n    simpl.\n    reflexivity.\n  - simpl.\n    unfold fold_map.\n    simpl.\n    fold (fold_map f l').\n    rewrite -> IHl'.\n    reflexivity.\nQed.\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n\nDefinition prod_uncurry {X Y Z : Type} \n  (f : X -> Y -> Z) (p : X * Y) : Z := f (fst p) (snd p).\n\nExample test_map2: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(* prod_curry : forall X Y Z :Type, (f : X * Y -> Z) -> (x : X) (y : Y) : Z *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z f x y.\n  unfold prod_uncurry.\n  unfold prod_curry.\n  simpl.\n  reflexivity.\nQed.\n\nLemma fst_snd : forall (X Y : Type) (a : X) (b : Y),\n    (fst (a,b), snd (a,b)) = (a,b).\nProof.\n  intros X Y a b.\n  simpl.\n  reflexivity.\nQed.  \n\nLemma fst_snd_p : forall (X Y : Type) (p : X * Y),\n    (fst p, snd p) = p.\nProof.\n  intros X Y p.\n  destruct p.\n  - simpl. reflexivity. Qed.\n\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  unfold prod_curry.\n  unfold prod_uncurry.\n  rewrite -> fst_snd_p.\n  reflexivity.\nQed.\n\nTheorem nth_theorem : forall X n l, \n  length l = n -> @nth_error X l n = None.\nProof.\n  intros X n l.\n  intros H.\n  induction n as [|].\nAbort.\n\nEnd Exercises.\n", "meta": {"author": "psibi", "repo": "sf", "sha": "36d1f95b4d4ed894ecc2c55c81095c822f3e9c69", "save_path": "github-repos/coq/psibi-sf", "path": "github-repos/coq/psibi-sf/sf-36d1f95b4d4ed894ecc2c55c81095c822f3e9c69/chapter4-poly/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7032783515500259}}
{"text": "Require Import Logic.Rel.R.\nRequire Import Logic.Rel.Id.\nRequire Import Logic.Rel.Include.\nRequire Import Logic.Rel.Function.\nRequire Import Logic.Rel.Converse.\nRequire Import Logic.Rel.Composition.\n\nLemma shunting_rule_left : \n    forall (a b c:Type) (r:R a b) (f:R b c) (s:R a c), Function f -> \n        f ; r <= s <-> r <= conv f ; s.\nProof.\n    intros a b c r f s [H1 H2]. split; intros H3.\n    - apply incl_trans with ((conv f; f) ; r).\n        + remember ((conv f; f) ; r) as e eqn:E. rewrite <- (id_left _ _ r). \n          rewrite E. clear e E. apply incl_comp_compat_l. assumption.\n        + rewrite comp_assoc. apply incl_comp_compat_r. assumption.\n    - apply incl_trans with ((f ; conv f) ; s).\n        + rewrite comp_assoc. apply incl_comp_compat_r. assumption.\n        + remember ((f ; conv f) ; s) as e eqn:E. rewrite <- (id_left _ _ s).\n          rewrite E. clear e E. apply incl_comp_compat_l. assumption.\nQed.\n\nLemma shunting_rule_right :\n    forall (a b c:Type) (f:R b a) (r:R b c) (s:R a c), Function f ->\n        r ; conv f <= s <-> r <= s ; f.\nProof.\n    intros a b c f r s [H1 H2]. split; intros H3.\n    - apply incl_trans with (r; (conv f; f)).\n        + remember (r ; (conv f; f)) as e eqn:E. rewrite <- (id_right _ _ r).\n          rewrite E. clear e E. apply incl_comp_compat_r. assumption.\n        + rewrite <- comp_assoc. apply incl_comp_compat_l. assumption.\n    - apply incl_trans with (s; (f ; conv f)).\n        + rewrite <- comp_assoc. apply incl_comp_compat_l. assumption.\n        + remember (s ; (f ; conv f)) as e eqn:E. rewrite <- (id_right _ _ s).\n          rewrite E. clear e E. apply incl_comp_compat_r. assumption.\nQed.\n\nLemma shunting_rev_left : forall (b c:Type) (f:R b c),\n    (forall (a:Type) (r:R a b) (s:R a c), f ; r <= s <-> r <= conv f ; s) -> \n    Function f.\nProof.\n    intros b c f H1. split.\n    - apply (H1 _ (conv f) id). rewrite id_right. apply incl_refl.\n    - apply (H1 _ id f). rewrite id_right. apply incl_refl.\nQed.\n\nLemma shunting_rev_right : forall (a b:Type) (f:R b a),\n    (forall (c:Type) (r:R b c) (s:R a c), r ; conv f <= s <-> r <= s ; f) -> \n    Function f.\nProof.\n    intros a b f H1. split.\n   - apply (H1 _ f id). rewrite id_left. apply incl_refl. \n   - apply (H1 _ id (conv f)). rewrite id_left. apply incl_refl.\nQed.\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/Logic/Rel/Shunting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7032783478722278}}
{"text": "(* 問1 *)\nTheorem ex1 : forall x, x = 1 -> x + 1 = 2.\nProof.\n  intros x H.\n  rewrite H.\n  reflexivity.\nQed.\n\n\n(* 問2 *)\n(* 1.9 *)\nInductive list (A : Set) : Set :=\n  | Nil  : list A\n  | Cons : A -> list A -> list A.\n\n(* 1.10 *)\nImplicit Arguments Nil  [A].\nImplicit Arguments Cons [A].\n\n(* 1.11 *)\nInfix \"::\" := Cons (at level 60, right associativity).\n\n(* 1.12 *)\nFixpoint length {A : Set} (xs : list A) :=\n  match xs with\n    | Nil      => 0\n    | x :: xs' => 1 + length xs'\n  end.\n\n(* 1.13 *)\nFixpoint app {A : Set} (xs ys : list A) :=\n  match xs with\n    | Nil      => ys\n    | x :: xs' => x :: app xs' ys\n  end.\n\n(* 1.14 *)\nInfix \"++\" := app (at level 60, right associativity).\n\nFixpoint map_succ (xs : list nat) : list nat :=\n  match xs with\n    | Nil      => Nil\n    | x :: xs' => (x + 1) :: map_succ xs'\n  end.\n\n(* 問3 *)\nTheorem map_succ_length : forall (xs : list nat),\n                            length (map_succ xs) = length xs.\nProof.\n  intros xs.\n  induction xs.\n\n  reflexivity.\n\n  simpl.\n  rewrite IHxs.\n  reflexivity.\nQed.\n\n(* おまけ *)\n(* map_succ して map_pred で戻る *)\n\nFixpoint map_pred (xs : list nat) : list nat :=\n  match xs with\n    | Nil      => Nil\n    | x :: xs' => (x - 1) :: map_pred xs'\n  end.\n\nRequire Import Arith.\n\nTheorem map_succ_pred : forall (xs : list nat),\n                          map_pred (map_succ xs) = xs.\nProof.\n  intros xs.\n  induction xs.\n\n  simpl.\n  reflexivity.\n\n  unfold map_succ.\n  unfold map_pred.\n  rewrite plus_comm.\n  rewrite minus_plus.\n  fold map_pred.\n  fold map_succ.\n  rewrite IHxs.\n  reflexivity.\nQed.\n", "meta": {"author": "khibino", "repo": "coq-TopSE-201203", "sha": "557e473e23bc709297f4b1d2183f3bdef759fda0", "save_path": "github-repos/coq/khibino-coq-TopSE-201203", "path": "github-repos/coq/khibino-coq-TopSE-201203/coq-TopSE-201203-557e473e23bc709297f4b1d2183f3bdef759fda0/Report.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7032385563836715}}
{"text": "Require Import TestCommon.\nRequire Import Equations.\n\n(*\n\nThis file implements a list type with type-level-encoded length, called Vector.\n\nWe introduce two phantom types: Zero : * and Succ : * -> *, to encode natural numbers on typelevel.\n\nIt has the following constructors:\ndata Vector A N\n  empty : () -> Vector a Zero\n  cons : (a * Vector a n) -> Vector a (Succ n)\n\nor in dotty:\ntrait Zero\ntrait Succ[N]\n\nenum Vector[A,N] {\n  case Empty[A](unused: Unit) extends Vector[A, Zero]\n  case Cons[A, N](data: (A, Vector[A, N])) extends Vector[A, Succ[N]]\n}\n\nThen we wrap the constructors as functions (just as an exercise):\n  empty': forall a, Vector a Zero\n  cons' : forall a n, a -> Vector a n -> Vector a (Succ n)\nor in dotty:\n  def empty[A]: Vector[A, Zero]\n  def cons[A,N](head: A)(tail: Vector[A, N]): Vector[A, Succ[N]]\n\nwe can create a vector containing two units:\n  uvec = (cons () (cons () empty)) // I skip the type args here, they are elaborated in the proof\n  uvec : Vector Unit (Succ (Succ Zero))\n\nwe can create a map function that guarantees that it preserves length:\n  map : forall a b n, (a -> b) -> Vector a n -> Vector b n\n\nthen we implement the 'safe' head function that works only on non-empty vectors:\n  head : forall a n, Vector a (Succ n) -> a\n  def head[A,N](v: Vector[A, Succ[N]]): A\nthis will be an occassion to show how we handle contradictory branches:\n- we may use the contradictory type equalities to prove that unit: A for every a and just return it\n\nanother showcase of GADT abilities will be a typesafe zip function that only allows to zip vectors of equal length\n  zip : forall a b n, Vector a n -> Vector b n -> Vector (a * b) n\n  def zip[A,B,N](va: Vector[A,N])(vb: Vector[B,N]): Vector[(A,B), N]\n\n  append (nat - plus)\n*)\n\n(* type level natural numbers *)\nAxiom Zero : var.\nAxiom Succ : var.\nAxiom Vector : var.\n\nOpen Scope L2GMu.\nAxiom all_distinct :\n  (Zero <> Succ) /\\ (Succ <> Vector) /\\ (Zero <> Vector).\n\n(* De Bruijn indices for arguments are in 'reverse' order, that is the last arg on the list is treated as 'closest' and referred to as ##0 *)\nDefinition VectorDef := (* Vector a len *)\n  enum 2 {{\n         (* empty : forall a, () -> Vector a Zero *)\n         mkGADTconstructor 1 typ_unit [##0; γ() Zero]* |\n         (* cons : forall a n, (a * Vector a n) -> Vector a (Succ n) *)\n         mkGADTconstructor 2 (##1 ** γ(##1, ##0) Vector) [##1; γ(##0) Succ]*\n         }}\n.\n\nDefinition sigma :=\n  empty\n    (* Zero and Succ are phantom types, but we add them constructors as at least one constructor is required for consistency *)\n  & Zero ~ enum 0 {{\n           mkGADTconstructor 0 typ_unit []*\n         }}\n  & Succ ~ enum 1 {{\n           mkGADTconstructor 1 typ_unit [##0]*\n         }}\n  & Vector ~ VectorDef.\n\nLemma oksigma : okGadt sigma.\nProof.\n  unfold sigma.\n  unfold VectorDef.\n  lets [? [? ?]]: all_distinct.\n  lets: is_var_defined_split.\n  econstructor; autotyper1;\n    try congruence;\n    try econstructor; autotyper1;\n      destruct_const_len_list;\n      autotyper1;\n      repeat rewrite union_empty_r; auto.\nQed.\n\nDefinition Nil := (Vector, 0).\nDefinition Cons := (Vector, 1).\n\nDefinition nil A := new Nil [| A |] (trm_unit).\nDefinition cons A N h t := new Cons [|A, N|]  (trm_tuple h t).\n\nLemma nil_type : {sigma, emptyΔ, empty} ⊢(Treg) (Λ => nil (##0)) ∈ typ_all (γ(##0, γ() Zero) Vector).\nProof.\n  cbv.\n  lets: oksigma.\n  autotyper1.\nQed.\n\nLtac distinct22 :=\n  lazymatch goal with\n  | |- ?a <> ?b =>\n    match goal with\n    | H: a \\in ?S -> False |- _ =>\n      intro; apply H; subst; apply in_singleton_self\n    | H: b \\in ?S -> False |- _ =>\n      intro; apply H; subst; apply in_singleton_self\n    end\n  end.\n\nLtac free_abs :=\n  unshelve econstructor; cbv; try (let v := gather_vars in exact v).\n\nLemma notin_eqv : forall A (x : A) L,\n    (x \\in L -> False) <-> x \\notin L.\nProof.\n  introv.\n  intuition.\nQed.\n\nLemma cons_type :\n  {sigma, emptyΔ, empty} ⊢(Treg)\n                         (Λ => Λ =>\n                          (λ ##1 => λ γ(##1, ##0) Vector =>\n                           cons (##1) (##0) (#1) (#0)\n                         ))\n                         ∈\n                         ∀ ∀ (##1 ==> (γ(##1, ##0) Vector) ==> (γ(##1, γ(##0) Succ) Vector)).\nProof.\n  cbv.\n  lets: oksigma.\n  autotyper1.\nQed.\n\nDefinition GZ := γ() Zero.\nDefinition GS (T : typ) := γ(T) Succ.\n\nDefinition uvec2 := cons typ_unit (GS GZ) trm_unit (cons typ_unit GZ trm_unit (nil typ_unit)).\n\nDefinition two := GS (GS GZ).\nLemma uvec2_type : {sigma, emptyΔ, empty} ⊢(Treg) uvec2 ∈ γ(typ_unit, two) Vector.\nProof.\n  cbv.\n  lets: oksigma.\n  lets [? [? ?]]: all_distinct.\n  autotyper1.\nQed.\n\n(*\nhead : ∀a. ∀n. ((a, (n) Succ) Vector) -> a\nhead = Λa. Λn. λv: ((a, (n) Succ) Vector).\n        case v of {\n          Nil[a2](unused) => <>\n        | Cons[a2, n2](da) => fst(da)\n        }\nThe term below has been generated from the pseudocode above using the converter tool.\n*)\nDefinition head_trm :=\n  trm_tabs (trm_tabs (trm_abs (typ_gadt [##1; typ_gadt [##0]* Succ]* Vector) (trm_matchgadt (#0) Vector [clause 2 (trm_fst (#0)); clause 1 (trm_unit)]*)))\n.\nDefinition head_typ :=\n  ∀ ∀ (γ(##1, γ(##0) Succ) Vector ==> ##1).\n\nLemma head_types : {sigma, emptyΔ, empty} ⊢(Treg) head_trm ∈ head_typ.\nProof.\ncbv.\nlets: oksigma.\n  lets [? [? ?]]: all_distinct.\nautotyper4;\n  try solve[\n    cbn in *;\n    destruct_const_len_list;\n    cbn; autotyper4\n  ].\n  - forwards*: H6 v. cbn in *.\n    eapply typing_eq.\n    + autotyper4.\n    + unfold entails_semantic.\n      intros O OM.\n      exfalso.\n      repeat (\n        match goal with\n        | H: subst_matches_typctx ?A ?B ?C |- _ =>\n          inversions H\n        end\n      ).\n      repeat (\n        match goal with\n        | H: wft ?A ?B ?C |- _ =>\n          clear H\n        end\n      ).\n      cbn in *.\n      congruence.\n    + autotyper4.\n  - forwards*: H6 v.\n    forwards*: H6 v0.\n    cbn in *.\n    eapply typing_eq.\n    + autotyper4.\n    + apply teq_symmetry.\n      apply teq_axiom; listin.\n    + autotyper4.\n  Unshelve.\n  fs. fs. fs.\nQed.\n\n(*\nzip : ∀a. ∀b. ∀n. ((a,n) Vector -> (b,n) Vector -> (a * b,n) Vector\nzip = fix $self: (∀a. ∀b. ∀n. ((a,n) Vector -> (b,n) Vector -> (a * b,n) Vector)).\n        Λa. Λb. Λn. λva: ((a,n) Vector). λvb: ((b,n) Vector). case va of {\n            Nil[a2](unused) => Nil[a * b](<>)\n          | Cons[a2, n2](da) =>\n            case vb of {\n              Nil[b2](unused) => <>\n            | Cons[b2, n3](db) =>\n                let h = <fst(da), fst(db)> in\n                  let t = (((($self[a])[b])[n2]) (snd(da))) (snd(db)) in\n                    Cons[(a*b),n2](<h, t>)\n                  end\n                end\n            }\n          }\nThe term below has been generated from the pseudocode above using the converter tool.\n*)\nDefinition zip_trm :=\n  trm_fix (typ_all (typ_all (typ_all ((typ_gadt [##2; ##0]* Vector) ==> ((typ_gadt [##1; ##0]* Vector) ==> (typ_gadt [(##2) ** (##1); ##0]* Vector)))))) (trm_tabs (trm_tabs (trm_tabs (trm_abs (typ_gadt [##2; ##0]* Vector) (trm_abs (typ_gadt [##1; ##0]* Vector) (trm_matchgadt (#1) Vector [clause 2 (trm_matchgadt (#1) Vector [clause 2 (trm_let (trm_tuple (trm_fst (#1)) (trm_fst (#0))) (trm_let (trm_app (trm_app (trm_tapp (trm_tapp (trm_tapp (#5) (##6)) (##5)) (##2)) (trm_snd (#2))) (trm_snd (#1))) (trm_constructor [(##6) ** (##5); ##2]* (Vector, 1) (trm_tuple (#1) (#0))))); clause 1 (trm_unit)]*); clause 1 (trm_constructor [(##3) ** (##2)]* (Vector, 0) (trm_unit))]*))))))\n.\n\nDefinition zip_typ :=\n  ∀ ∀ ∀ (γ(##2, ##0) Vector ==> γ(##1, ##0) Vector ==> γ(##2 ** ##1, ##0) Vector).\n\nLemma zip_types : {sigma, emptyΔ, empty} ⊢(Treg) zip_trm ∈ zip_typ.\nProof.\ncbv.\nlets: oksigma.\n  lets [? [? ?]]: all_distinct.\nautotyper4;\n  try solve[\n    cbn in *;\n    destruct_const_len_list;\n    cbn; autotyper4\n  ].\n  - forwards*: H6 v.\n    eapply typing_eq with (γ( x1 ** x2, (γ() Zero)) Vector) _;\n      try solve[autotyper4].\n      apply eq_typ_gadt.\n      apply F2_iff_In_zip.\n      split~.\n      intros.\n      repeat ininv2.\n      + apply teq_symmetry.\n        apply teq_axiom. listin.\n      + apply teq_reflexivity.\n  - forwards*: H6 v.\n    forwards*: H6 v0.\n    cbn in *.\n    apply Tgen_from_any with Treg.\n    autotyper4.\n    + cbn in *.\n      forwards*: H12 v1.\n      eapply typing_eq.\n      * autotyper4.\n      * unfold entails_semantic.\n        intros O OM.\n        exfalso.\n        repeat (\n          match goal with\n          | H: subst_matches_typctx ?A ?B ?C |- _ =>\n            inversions H\n          end\n        ).\n        repeat (\n          match goal with\n          | H: wft ?A ?B ?C |- _ =>\n            clear H\n          end\n        ).\n        match goal with\n        | H1: subst_tt' (typ_fvar x3) ?S1 = subst_tt' ?A ?S2,\n          H2: subst_tt' (typ_fvar x3) ?S3 = subst_tt' ?B ?S4 |- _ =>\n          assert (subst_tt' (typ_fvar x3) S1 = subst_tt' (typ_fvar x3) S3)\n        end.\n        -- cbn.\n           fold (subst_tt v T0 x3).\n           repeat f_equal.\n           assert (x3 <> v1) by (apply neq_from_notin; notin_solve).\n           case_if*.\n        -- match goal with\n          | H1: subst_tt' (typ_fvar x3) ?S1 = subst_tt' ?A ?S2,\n            H2: subst_tt' (typ_fvar x3) ?S3 = subst_tt' ?B ?S4,\n            H3: subst_tt' (typ_fvar x3) ?S5 = subst_tt' ?C ?S6 |- _ =>\n            assert (HEQ: subst_tt' A S1 = subst_tt' B S3) by congruence\n          end.\n          cbn in HEQ.\n          congruence.\n      * autotyper4.\n    + eapply typing_eq.\n      * forwards*: H12 v1.\n        forwards*: H12 v2.\n        cbn in *.\n        match goal with\n        | |- {?E, ?D, ?G} ⊢( ?TT) ?t ∈ ?T =>\n          assert (okt E D G) by autotyper4\n        end.\n        econstructor.\n        -- econstructor.\n           ++ econstructor. econstructor.\n              ** solve_bind.\n              ** auto.\n           ++ econstructor. econstructor.\n              ** solve_bind.\n              ** auto.\n        -- let FR := gather_vars in\n            introv xFr;\n            instantiate (1:=FR) in xFr.\n           match goal with\n           | |- {?E, ?D, ?G} ⊢( ?TT) ?t ∈ ?T =>\n             assert (okt E D G)\n           end.\n           1: {\n             autotyper4.\n           }\n           econstructor.\n           ++ econstructor.\n              2: {\n                econstructor.\n                2: {\n                  econstructor.\n                  - econstructor.\n                    + econstructor.\n                      * econstructor; solve_bind; auto.\n                      * autotyper4.\n                      * cbn. auto.\n                    + autotyper4.\n                    + cbn. auto.\n                  - autotyper4.\n                  - cbn. auto.\n                }\n\n                match goal with\n                | |- context[x ~l (?A ** ?B)] =>\n                  apply typing_eq with B Treg\n                end.\n                - econstructor.\n                  econstructor; solve_bind; auto.\n                - apply eq_typ_gadt.\n                  apply F2_iff_In_zip.\n                  split~.\n                  intros.\n                  repeat ininv2.\n                  * apply teq_reflexivity.\n                  * apply teq_symmetry.\n                    apply teq_axiom. listin.\n                - autotyper4.\n              }\n\n              match goal with\n              | |- context[x6 ~l (?A ** ?B)] =>\n                apply typing_eq with B Treg\n              end.\n              ** econstructor.\n                 econstructor; solve_bind; auto.\n              ** apply eq_typ_gadt.\n                 apply F2_iff_In_zip.\n                 split~.\n                 intros.\n                 repeat ininv2.\n                 --- forwards* HI: inversion_eq_typ_gadt [typ_fvar v1]* [typ_fvar v]*.\n                     2: {\n                      rewrite F2_iff_In_zip in HI.\n                      destruct HI as [? HI].\n                      lets* HI2: HI v1 v.\n                      apply HI2.\n                      cbn; auto.\n                     }\n                     apply teq_transitivity with (typ_fvar x3).\n                     +++ apply teq_symmetry.\n                         apply teq_axiom; listin.\n                     +++ apply teq_axiom; listin.\n                 --- apply teq_symmetry. apply teq_axiom. listin.\n              ** autotyper4.\n            ++ cbn.\n               let FR := gather_vars in\n                 introv xFr2;instantiate (1:=FR) in xFr2.\n               match goal with\n               | |- {?E, ?D, ?G} ⊢( ?TT) ?t ∈ ?T =>\n                 assert (okt E D G) by autotyper4\n               end.\n               econstructor.\n               2: {\n                 solve_bind.\n               }\n               2: {\n                 cbn. auto.\n               }\n               2: {\n                 cbn. auto.\n               }\n               2: {\n                 cbn. auto.\n               }\n               1: {\n                 eapply typing_eq.\n                 - econstructor.\n                   + econstructor; solve_bind; auto.\n                   + econstructor; solve_bind; auto.\n                 - apply eq_typ_tuple.\n                   + apply eq_typ_tuple;\n                      apply teq_symmetry;\n                      apply teq_axiom; listin.\n                   + apply teq_reflexivity.\n                 - autotyper4.\n               }\n               2: {\n                 cbn.\n                 auto.\n               }\n               autotyper4.\n      * apply eq_typ_gadt.\n        apply F2_iff_In_zip.\n        split~.\n        intros.\n        repeat ininv2.\n        -- apply teq_symmetry.\n           apply teq_axiom; listin.\n        -- apply teq_reflexivity.\n      * autotyper4.\nUnshelve.\nfs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs.\nfs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs. fs.\nQed.\n\n(*\n  map : forall a b n, (a -> b) -> Vector a n -> Vector b n\n *)\nDefinition map :=\n  fixs ∀ ∀ ∀ ((##2 ==> ##1) ==> γ(##2, ##0) Vector ==> γ(##1, ##0) Vector) =>\n  Λ (* a *) => Λ (* b *) => Λ (* n *) =>\n  λ (* f *) (##2 ==> ##1) =>\n  λ (* v *) γ(##2, ##0) Vector =>\n  case #0 as Vector of {\n                      (* a' *) 1 => new Nil [| ##2 |] ( <.> ) |\n                      (* a', n'; elem *) 2 => new Cons [| ##3, ##0 |] (\n                                      trm_tuple\n                                        (#2 <| fst(#0))\n                                        (#3 <|| ##4 <|| ##3 <|| ##0 <| #2 <| snd(#0))\n                                    )\n                    }.\n\n\nLemma map_types : {sigma, emptyΔ, empty} ⊢(Treg) map ∈ ∀ ∀ ∀ ((##2 ==> ##1) ==> γ(##2, ##0) Vector ==> γ(##1, ##0) Vector).\nProof.\n  cbv.\n  lets: oksigma.\n  lets [? [? ?]]: all_distinct.\n  autotyper3;\n    rename x0 into map;\n    rename x4 into f;\n    rename x1 into A;\n    rename x2 into B;\n    rename x3 into N;\n    rename x5 into vec.\n  - rename v into C.\n    forwards~ : H6 C.\n    eapply typing_eq with (T1:=γ(typ_fvar B, γ() Zero) Vector).\n    + autotyper4.\n    + apply eq_typ_gadt.\n      apply F2_iff_In_zip.\n      split~.\n      intros.\n      repeat ininv2.\n      * apply teq_symmetry.\n        apply teq_axiom. listin.\n      * apply teq_reflexivity.\n    + autotyper4.\n  - rename v0 into A'.\n    rename v into N'.\n    forwards~ : H6 A'.\n    forwards~ : H6 N'.\n    apply typing_eq with (γ(typ_fvar B, γ(typ_fvar N') Succ) Vector) Treg.\n    + eapply typing_cons; autotyper0.\n      * eapply typing_tuple; autotyper0.\n        -- econstructor.\n           ++ instantiate (1:=A).\n              apply typing_eq with A' Treg.\n              ** autotyper4.\n              ** apply teq_symmetry. apply teq_axiom. listin.\n              ** autotyper4.\n           ++ autotyper4.\n        -- econstructor; autotyper0.\n           instantiate (1:= γ(typ_fvar A, typ_fvar N') Vector).\n           ++ apply typing_eq with (γ(typ_fvar A', typ_fvar N') Vector) Treg.\n              ** autotyper4.\n              ** apply eq_typ_gadt.\n                 apply F2_iff_In_zip.\n                 split~.\n                 intros.\n                 repeat ininv2.\n                 --- apply teq_reflexivity.\n                 --- apply teq_symmetry.\n                     apply teq_axiom. listin.\n              ** autotyper4.\n           ++ autotyper4.\n      * autotyper4.\n    + apply eq_typ_gadt.\n      apply F2_iff_In_zip.\n      split~.\n      intros.\n      repeat ininv2.\n      * apply teq_symmetry.\n        apply teq_axiom. listin.\n      * apply teq_reflexivity.\n    + autotyper4.\n      Unshelve.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\n      fs.\nQed.\n", "meta": {"author": "radeusgd", "repo": "GADT-thesis", "sha": "18be642b1f9ef145c9fbc02f55eefb51d4bc1fdf", "save_path": "github-repos/coq/radeusgd-GADT-thesis", "path": "github-repos/coq/radeusgd-GADT-thesis/GADT-thesis-18be642b1f9ef145c9fbc02f55eefb51d4bc1fdf/lambda2Gmu/TestVector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8438950947024555, "lm_q1q2_score": 0.7032385452651386}}
{"text": "(** * Lists: Working with Structured Data *)\n\nFrom QuickChick Require Import QuickChick.\nImport QcDefaultNotation. Open Scope qc_scope.\nImport GenLow GenHigh.\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\nRequire Import List ZArith.\nImport ListNotations.\n(* \nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import seq ssreflect ssrbool ssrnat eqtype.\n*)\n\nRequire Export Induction.\nModule NatList.\n\nInductive natprod : Type :=\n| pair : nat -> nat -> natprod.\nDerive Arbitrary for natprod.\nDerive Show for natprod.\nInstance natprod_eq (x y : natprod) : Dec (x = y).\nconstructor. unfold ssrbool.decidable. repeat (decide equality). Defined.\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\nNotation \"( x , y )\" := (pair x y).\n\nDefinition swap_pair (p : natprod) : natprod :=\n  match p with\n  | (x,y) => (y,x)\n  end.\n\n(* BCP: boring! *)\nDefinition equal_pair (p : natprod) (q : natprod) : bool :=\n  match p,q with\n  | (p1,p2),(q1,q2) => andb (p1 =? q1) (p2 =? q2)\n  end.\n\nDefinition surjective_pairing (p : natprod) :=\n  equal_pair p (fst p, snd p).\n(*! QuickCheck surjective_pairing. *)\n\nInductive natlist : Type :=\n  | nil  : natlist\n  | cons : nat -> natlist -> natlist.\nDerive Arbitrary for natlist.\nDerive Show for natlist.\nInstance natlist_eq (x y : natlist) : Dec (x = y).\nconstructor. unfold ssrbool.decidable. repeat (decide equality). Defined.\n\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\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 length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil    => l2\n  | h :: t => h :: (app t l2)\n  end.\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\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\nDefinition test_hd1 := hd 0 [1;2;3] =? 1.\n(*! QuickChick test_hd1. *)\n\nFixpoint equal_list l1 l2 :=\n  match l1,l2 with\n  | [],[] => true\n  | h1::t1,h2::t2 => andb (h1=?h2) (equal_list t1 t2)\n  | _,_ => false\n  end.\n\nDefinition test_tl := equal_list (tl [1;2;3]) [2;3].\n(*! QuickChick test_tl. *)\n\nFixpoint alternate (l1 l2 : natlist) : natlist\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *) := [].\n\nDefinition bag := natlist.\n\nDefinition nil_app := fun l:natlist =>\n  equal_list ([] ++ l) l.\n(* QuickChick nil_app. *)\n\nDefinition tl_length_pred := fun l:natlist =>\n  pred (length l) =? length (tl l).\n\n(* Ugh -- temporary hack *)\nDefinition tl_length_prop := \n  forAllShrink arbitrary shrink tl_length_pred.\n(*! QuickChick tl_length_prop. *)\n\nDefinition app_assoc := fun l1 l2 l3 : natlist =>\n  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nInstance app_assoc_dec (l1 l2 l3 : natlist) : Dec (app_assoc l1 l2 l3).\nunfold app_assoc. apply natlist_eq. Defined.\n\n(* BCP: What do I need to write here?\nQuickChick app_assoc.\n*)\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil    => nil\n  | h :: t => rev t ++ [h]\n  end.\n\nDefinition rev_length := fun l : natlist =>\n  length (rev l) =? length l.\n(*! QuickChick rev_length. *)\n\nFixpoint beq_natlist (l1 l2 : natlist) : bool\n  (* REPLACE THIS LINE WITH \":= _your_definition_ .\" *) := false.\n\n(* BCP: Use this elsewhere *)\nDefinition beq_natlist_refl := fun l:natlist =>\n  Bool.eqb true (beq_natlist l l).\nQuickChick (expectFailure beq_natlist).\n\n(* BCP: I wonder how best to do this...? *)\nDefinition rev_injective := fun (l1 l2 : natlist) =>\n  (equal_list (rev l1) (rev l2)) ==> equal_list l1 l2.\n(* BCP: Probably needs some mutations to be interesting... *)\n(*! QuickChick beq_natlist. *)\n\n(* Let's try with the dependent stuff... *)\nInductive eq_list : natlist -> natlist -> Prop :=\n  | eq_nil : eq_list [] []\n  | eq_cons : forall h l1 l2, eq_list l1 l2 -> eq_list (h::l1) (h::l2).\n\nInductive snoc_of : natlist -> nat -> natlist -> Prop :=\n  | snoc_of_nil : forall x, snoc_of [] x [x]\n  | snoc_of_cons : forall x h t t',\n      snoc_of t x t' -> snoc_of (h::t) x (h::t').\n\nDerive ArbitrarySizedSuchThat for (fun h  => snoc_of t h t').\nDerive ArbitrarySizedSuchThat for (fun t' => snoc_of t h t').\n\nInductive reverse_of : natlist -> natlist -> Prop :=\n  | reverse_of_nil : reverse_of [] []\n  | reverse_of_cons : forall h t t' t'',\n      reverse_of t t' ->\n      snoc_of t' h t'' ->\n      reverse_of (h::t) t''.\n\nDerive ArbitrarySizedSuchThat for (fun l => reverse_of l l').\nDerive ArbitrarySizedSuchThat for (fun l => reverse_of l' l).\n\nInductive equal_reverses : (natlist * natlist)%type -> Prop :=\n  | eqrev : forall l1 l2 l,\n      reverse_of l1 l -> reverse_of l2 l ->\n      equal_reverses (Coq.Init.Datatypes.pair l1 l2).\n\nDerive ArbitrarySizedSuchThat for (fun l1l2 => equal_reverses l1l2). \n\n(* Need to actual write decidability if we want to use it \nInstance equal_reverses_dec l1l2 : Dec (equal_reverses l1l2).\nProof. \n  constructor; unfold ssrbool.decidable. \n  destruct l1l2 as [l1 l2].\n  (* ... *)\nAdmitted.\n*)\n\nDefinition rev_injective_checker : Checker :=\n  forAll (genST (fun l1l2 => equal_reverses l1l2))\n         (fun l1l2 => match l1l2 with \n                        | Some (Coq.Init.Datatypes.pair l1 l2) => ((l1 = l2)?)\n                        | None => true\n                      end).\n\nQuickChick rev_injective_checker.\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\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\nDerive Arbitrary for natoption.\nDerive Show for natoption.\nInstance natoption_eq (x y : natoption) : Dec (x = y).\nconstructor. unfold ssrbool.decidable. repeat (decide equality). Defined.\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\n(* BCP: Fix *)\nDefinition test_nth_error1 :=\n  (nth_error [4;5;6;7] 0) = (Some 4)?.\n(*! QuickChick test_nth_error1. *)\n\nEnd NatList.\n\nInductive id : Type :=\n  | Id : nat -> id.\nDerive Arbitrary for id.\nDerive Show for id.\nInstance id_eq (x y : id) : Dec (x = y).\nconstructor. unfold ssrbool.decidable. repeat (decide equality). Defined.\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(* BCP: Extraction inside modules is broken! *)\n(*\nModule PartialMap.\n*)\nExport NatList.\n  \nInductive partial_map : Type :=\n  | empty  : partial_map\n  | record : id -> nat -> partial_map -> partial_map.\nDerive Arbitrary for partial_map.\nDerive Show for partial_map.\nInstance partial_map_eq (x y : partial_map) : Dec (x = y).\nconstructor. unfold ssrbool.decidable. repeat (decide equality). Defined.\n\nDefinition update (d : partial_map)\n                  (x : id) (value : nat)\n                  : partial_map :=\n  record x value d.\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\nDefinition update_eq :=\n  fun (d : partial_map) (x : id) (v: nat) =>\n    (find x (update d x v) = Some v)?.\n(*! QuickChick update_eq. *)\n\n", "meta": {"author": "QuickChick", "repo": "QuickChick", "sha": "ca56cc21ecc76bc0e1443e917ce26c010980ae2f", "save_path": "github-repos/coq/QuickChick-QuickChick", "path": "github-repos/coq/QuickChick-QuickChick/QuickChick-ca56cc21ecc76bc0e1443e917ce26c010980ae2f/sf-experiment/Lists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7030991868006595}}
{"text": "(**\nThis file is part of the Coq.Interval library for proving bounds of\nreal-valued expressions in Coq: http://coq-interval.gforge.inria.fr/\n\nCopyright (C) 2007-2016, Inria\n\nThis library is governed by the CeCILL-C license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the library under the terms of the CeCILL-C\nlicense as circulated by CEA, CNRS and Inria at the following URL:\nhttp://www.cecill.info/\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided\nonly with a limited warranty and the library's author, the holder of\nthe economic rights, and the successive licensors have only limited\nliability. See the COPYING file for more details.\n*)\n\nFrom Coq Require Import Reals Psatz.\nFrom Flocq Require Export Raux.\n\nLtac evar_last :=\n  match goal with\n  | |- ?f ?x =>\n    let tx := type of x in\n    let tx := eval simpl in tx in\n    let tmp := fresh \"tmp\" in\n    evar (tmp : tx) ;\n    refine (@eq_ind tx tmp f _ x _) ;\n    unfold tmp ; clear tmp\n  end.\n\nLemma Rmult_le_compat_neg_r :\n  forall r r1 r2 : R,\n  (r <= 0)%R -> (r1 <= r2)%R -> (r2 * r <= r1 * r)%R.\nProof.\nintros.\nrewrite (Rmult_comm r2).\nrewrite (Rmult_comm r1).\napply Rmult_le_compat_neg_l.\nexact H.\nexact H0.\nQed.\n\nLemma Rsqr_plus1_pos x : (0 < 1 + Rsqr x)%R.\nProof. now apply (Rplus_lt_le_0_compat _ _ Rlt_0_1 (Rle_0_sqr x)). Qed.\n\nLemma Rsqr_plus1_neq0 x : (1 + Rsqr x <> 0)%R.\nProof. now apply Rgt_not_eq; apply Rlt_gt; apply Rsqr_plus1_pos. Qed.\n\nLemma Rmin_Rle :\n  forall r1 r2 r,\n  (Rmin r1 r2 <= r)%R <-> (r1 <= r)%R \\/ (r2 <= r)%R.\nProof.\nintros.\nunfold Rmin.\nsplit.\ncase (Rle_dec r1 r2) ; intros.\nleft. exact H.\nright. exact H.\nintros [H|H] ; case (Rle_dec r1 r2) ; intros H0.\nexact H.\napply Rle_trans with (2 := H).\napply Rlt_le.\napply Rnot_le_lt with (1 := H0).\napply Rle_trans with r2 ; assumption.\nexact H.\nQed.\n\nLemma Rle_Rinv_pos :\n  forall x y : R,\n  (0 < x)%R -> (x <= y)%R -> (/y <= /x)%R.\nProof.\nintros.\napply Rle_Rinv.\nexact H.\napply Rlt_le_trans with x ; assumption.\nexact H0.\nQed.\n\nLemma Rle_Rinv_neg :\n  forall x y : R,\n  (y < 0)%R -> (x <= y)%R -> (/y <= /x)%R.\nProof.\nintros.\napply Ropp_le_cancel.\nrepeat rewrite Ropp_inv_permute.\napply Rle_Rinv.\nauto with real.\napply Rlt_le_trans with (Ropp y).\nauto with real.\nauto with real.\nauto with real.\napply Rlt_dichotomy_converse.\nleft. exact H.\napply Rlt_dichotomy_converse.\nleft.\napply Rle_lt_trans with y ; assumption.\nQed.\n\nLemma Rmult_le_pos_pos :\n  forall x y : R,\n  (0 <= x)%R -> (0 <= y)%R -> (0 <= x * y)%R.\nProof.\nexact Rmult_le_pos.\nQed.\n\nLemma Rmult_le_pos_neg :\n  forall x y : R,\n  (0 <= x)%R -> (y <= 0)%R -> (x * y <= 0)%R.\nProof.\nintros.\nrewrite <- (Rmult_0_r x).\napply Rmult_le_compat_l ; assumption.\nQed.\n\nLemma Rmult_le_neg_pos :\n  forall x y : R,\n  (x <= 0)%R -> (0 <= y)%R -> (x * y <= 0)%R.\nProof.\nintros.\nrewrite <- (Rmult_0_l y).\napply Rmult_le_compat_r ; assumption.\nQed.\n\nLemma Rmult_le_neg_neg :\n  forall x y : R,\n  (x <= 0)%R -> (y <= 0)%R -> (0 <= x * y)%R.\nProof.\nintros.\nrewrite <- (Rmult_0_r x).\napply Rmult_le_compat_neg_l ; assumption.\nQed.\n\nLemma Rabs_def1_le :\n  forall x a,\n  (x <= a)%R -> (-a <= x)%R ->\n  (Rabs x <= a)%R.\nProof.\nintros.\ncase (Rcase_abs x) ; intros.\nrewrite (Rabs_left _ r).\nrewrite <- (Ropp_involutive a).\napply Ropp_le_contravar.\nexact H0.\nrewrite (Rabs_right _ r).\nexact H.\nQed.\n\nLemma Rabs_def2_le :\n  forall x a,\n  (Rabs x <= a)%R ->\n  (-a <= x <= a)%R.\nProof.\nintros x a H.\nassert (0 <= a)%R.\napply Rle_trans with (2 := H).\napply Rabs_pos.\ngeneralize H. clear H.\nunfold Rabs.\ncase (Rcase_abs x) ; split.\nrewrite <- (Ropp_involutive x).\napply Ropp_le_contravar.\nexact H.\napply Rlt_le.\napply Rlt_le_trans with (1 := r).\nexact H0.\ngeneralize (Rge_le _ _ r).\nclear r.\nintro.\napply Rle_trans with (2 := H1).\nrewrite <- Ropp_0.\napply Ropp_le_contravar.\nexact H0.\nexact H.\nQed.\n\nTheorem derivable_pt_lim_eq :\n  forall f g,\n (forall x, f x = g x) ->\n  forall x l,\n  derivable_pt_lim f x l -> derivable_pt_lim g x l.\nProof.\nintros f g H x l.\nunfold derivable_pt_lim.\nintros.\ndestruct (H0 _ H1) as (delta, H2).\nexists delta.\nintros.\ndo 2 rewrite <- H.\napply H2 ; assumption.\nQed.\n\nDefinition locally_true x (P : R -> Prop) :=\n  exists delta, (0 < delta)%R /\\\n  forall h, (Rabs h < delta)%R -> P (x + h)%R.\n\nTheorem derivable_pt_lim_eq_locally :\n  forall f g x l,\n  locally_true x (fun v => f v = g v) ->\n  derivable_pt_lim f x l -> derivable_pt_lim g x l.\nProof.\nintros f g x l (delta1, (Hd, Heq)) Hf eps Heps.\ndestruct (Hf eps Heps) as (delta2, H0).\nclear Hf.\nassert (0 < Rmin delta1 delta2)%R.\napply Rmin_pos.\nexact Hd.\nexact (cond_pos delta2).\nexists (mkposreal (Rmin delta1 delta2) H).\nintros.\nrewrite <- Heq.\npattern x at 2 ; rewrite <- Rplus_0_r.\nrewrite <- Heq.\nrewrite Rplus_0_r.\napply H0.\nexact H1.\napply Rlt_le_trans with (1 := H2).\nsimpl.\napply Rmin_r.\nrewrite Rabs_R0.\nexact Hd.\napply Rlt_le_trans with (1 := H2).\nsimpl.\napply Rmin_l.\nQed.\n\nTheorem locally_true_and :\n  forall P Q x,\n  locally_true x P ->\n  locally_true x Q ->\n  locally_true x (fun x => P x /\\ Q x).\nProof.\nintros P Q x HP HQ.\ndestruct HP as (e1, (He1, H3)).\ndestruct HQ as (e2, (He2, H4)).\nexists (Rmin e1 e2).\nsplit.\napply Rmin_pos ; assumption.\nintros.\nsplit.\napply H3.\napply Rlt_le_trans with (1 := H).\napply Rmin_l.\napply H4.\napply Rlt_le_trans with (1 := H).\napply Rmin_r.\nQed.\n\nTheorem locally_true_imp :\n  forall P Q : R -> Prop,\n (forall x, P x -> Q x) ->\n  forall x,\n  locally_true x P ->\n  locally_true x Q.\nProof.\nintros P Q H x (d, (Hd, H0)).\nexists d.\nsplit.\nexact Hd.\nintros.\napply H.\napply H0.\nexact H1.\nQed.\n\nTheorem continuity_pt_lt :\n  forall f x y,\n  (f x < y)%R ->\n  continuity_pt f x ->\n  locally_true x (fun u => (f u < y)%R).\nProof.\nintros.\nassert (0 < y - f x)%R.\napply Rplus_lt_reg_l with (f x).\nrewrite Rplus_0_r.\nreplace (f x + (y - f x))%R with y. 2: ring.\nexact H.\ndestruct (H0 _ H1) as (delta, (Hdelta, H2)).\nclear H0.\nexists delta.\nsplit.\nexact Hdelta.\nintros.\ncase (Req_dec h 0) ; intro H3.\nrewrite H3.\nrewrite Rplus_0_r.\nexact H.\ngeneralize (H2 (x + h)%R). clear H2.\nunfold R_met, R_dist, D_x, no_cond.\nsimpl.\nintro.\napply Rplus_lt_reg_r with (- f x)%R.\napply Rle_lt_trans with (1 := RRle_abs (f (x + h) - f x)%R).\napply H2.\nassert (x + h - x = h)%R. ring.\nsplit.\nsplit.\nexact I.\nintro H5.\nelim H3.\nrewrite <- H4.\nrewrite <- H5.\nexact (Rplus_opp_r _).\nrewrite H4.\nexact H0.\nQed.\n\nTheorem continuity_pt_gt :\n  forall f x y,\n  (y < f x)%R ->\n  continuity_pt f x ->\n  locally_true x (fun u => (y < f u)%R).\nProof.\nintros.\ngeneralize (Ropp_lt_contravar _ _ H).\nclear H. intro H.\ngeneralize (continuity_pt_opp _ _ H0).\nclear H0. intro H0.\ndestruct (continuity_pt_lt (opp_fct f) _ _ H H0) as (delta, (Hdelta, H1)).\nexists delta.\nsplit.\nexact Hdelta.\nintros.\napply Ropp_lt_cancel.\nexact (H1 _ H2).\nQed.\n\nTheorem continuity_pt_ne :\n  forall f x y,\n  f x <> y ->\n  continuity_pt f x ->\n  locally_true x (fun u => f u <> y).\nProof.\nintros.\ndestruct (Rdichotomy _ _ H) as [H1|H1].\ndestruct (continuity_pt_lt _ _ _ H1 H0) as (delta, (Hdelta, H2)).\nexists delta.\nsplit.\nexact Hdelta.\nintros.\napply Rlt_not_eq.\nexact (H2 _ H3).\ndestruct (continuity_pt_gt _ _ _ H1 H0) as (delta, (Hdelta, H2)).\nexists delta.\nsplit.\nexact Hdelta.\nintros.\napply Rgt_not_eq.\nexact (H2 _ H3).\nQed.\n\nTheorem derivable_pt_lim_tan :\n  forall x,\n  (cos x <> 0)%R ->\n  derivable_pt_lim tan x (1 + Rsqr (tan x))%R.\nProof.\nintros x Hx.\nchange (derivable_pt_lim (sin/cos) x (1 + Rsqr (tan x))%R).\nreplace (1 + Rsqr (tan x))%R with ((cos x * cos x - (-sin x) * sin x) / Rsqr (cos x))%R.\napply derivable_pt_lim_div.\napply derivable_pt_lim_sin.\napply derivable_pt_lim_cos.\nexact Hx.\nunfold Rsqr, tan.\nfield.\nexact Hx.\nQed.\n\nDefinition connected (P : R -> Prop) :=\n  forall x y, P x -> P y ->\n  forall z, (x <= z <= y)%R -> P z.\n\nLemma connected_and :\n  forall d1 d2, connected d1 -> connected d2 -> connected (fun t => d1 t /\\ d2 t).\nProof.\nintros d1 d2 H1 H2 u v [D1u D2u] [D1v D2v] t Ht.\nsplit.\nnow apply H1 with (3 := Ht).\nnow apply H2 with (3 := Ht).\nQed.\n\nLemma connected_ge :\n  forall x, connected (Rle x).\nProof.\nintros x u v Hu _ t [Ht _].\nexact (Rle_trans _ _ _ Hu Ht).\nQed.\n\nLemma connected_le :\n  forall x, connected (fun t => Rle t x).\nProof.\nintros x u v _ Hv t [_ Ht].\nexact (Rle_trans _ _ _ Ht Hv).\nQed.\n\nTheorem derivable_pos_imp_increasing :\n  forall f f' dom,\n  connected dom ->\n (forall x, dom x -> derivable_pt_lim f x (f' x) /\\ (0 <= f' x)%R) ->\n  forall u v, dom u -> dom v -> (u <= v)%R -> (f u <= f v)%R.\nProof.\nintros f f' dom Hdom Hd u v Hu Hv [Huv|Huv].\nassert (forall w, (u <= w <= v)%R -> derivable_pt_lim f w (f' w)).\nintros w Hw.\nrefine (proj1 (Hd _ _)).\nexact (Hdom _ _ Hu Hv _ Hw).\ndestruct (MVT_cor2 _ _ _ _ Huv H) as (w, (Hw1, Hw2)).\nreplace (f v) with (f u + (f v - f u))%R by ring.\nrewrite Hw1.\npattern (f u) at 1 ; rewrite <- Rplus_0_r.\napply Rplus_le_compat_l.\napply Rmult_le_pos.\nrefine (proj2 (Hd _ _)).\nrefine (Hdom _ _ Hu Hv _ _).\nexact (conj (Rlt_le _ _ (proj1 Hw2)) (Rlt_le _ _ (proj2 Hw2))).\nrewrite <- (Rplus_opp_r u).\nunfold Rminus.\napply Rplus_le_compat_r.\nexact (Rlt_le _ _ Huv).\nrewrite Huv.\napply Rle_refl.\nQed.\n\nTheorem derivable_neg_imp_decreasing :\n  forall f f' dom,\n  connected dom ->\n (forall x, dom x -> derivable_pt_lim f x (f' x) /\\ (f' x <= 0)%R) ->\n  forall u v, dom u -> dom v -> (u <= v)%R -> (f v <= f u)%R.\nProof.\nintros f f' dom Hdom Hd u v Hu Hv Huv.\napply Ropp_le_cancel.\nrefine (derivable_pos_imp_increasing (opp_fct f) (opp_fct f') _ Hdom _ _ _ Hu Hv Huv).\nintros.\ndestruct (Hd x H) as (H1, H2).\nsplit.\napply derivable_pt_lim_opp with (1 := H1).\nrewrite <- Ropp_0.\napply Ropp_le_contravar with (1 := H2).\nQed.\n\nLemma even_or_odd :\n  forall n : nat, exists k, n = 2 * k \\/ n = S (2 * k).\nProof.\ninduction n.\nexists 0.\nnow left.\ndestruct IHn as [k [Hk|Hk]].\nexists k.\nright.\nnow apply f_equal.\nexists (S k).\nleft.\nlia.\nQed.\n\nLemma alternated_series_ineq' :\n  forall u l,\n  Un_decreasing u ->\n  Un_cv u 0 ->\n  Un_cv (fun n => sum_f_R0 (tg_alt u) n) l ->\n  forall n,\n  (0 <= (-1)^(S n) * (l - sum_f_R0 (tg_alt u) n) <= u (S n))%R.\nProof.\nintros u l Du Cu Cl n.\ndestruct (even_or_odd n) as [p [Hp|Hp]].\n- destruct (alternated_series_ineq u l p Du Cu Cl) as [H1 H2].\n  rewrite Hp, pow_1_odd.\n  split.\n  + lra.\n  + apply Rplus_le_reg_r with (- sum_f_R0 (tg_alt u) (2 * p))%R.\n    ring_simplify.\n    replace (- sum_f_R0 (tg_alt u) (2 * p) + u (S (2 * p)))%R\n      with (- (sum_f_R0 (tg_alt u) (2 * p) + (-1) * u (S (2 * p))))%R by ring.\n    rewrite <- (pow_1_odd p).\n    now apply Ropp_le_contravar.\n- assert (H0: S (S (2 * p)) = 2 * (p + 1)) by ring.\n  rewrite Hp.\n  rewrite H0 at 1 2.\n  rewrite pow_1_even, Rmult_1_l.\n  split.\n  + apply Rle_0_minus.\n    now apply alternated_series_ineq.\n  + apply Rplus_le_reg_l with (sum_f_R0 (tg_alt u) (S (2 * p))).\n    ring_simplify.\n    rewrite <- (Rmult_1_l (u (S (S (2 * p))))).\n    rewrite <- (pow_1_even (p + 1)).\n    rewrite <- H0.\n    destruct (alternated_series_ineq u l (p + 1) Du Cu Cl) as [_ H1].\n    now rewrite <- H0 in H1.\nQed.\n\nLemma Un_decreasing_exp :\n  forall x : R,\n  (0 <= x <= 1)%R ->\n  Un_decreasing (fun n => / INR (fact n) * x ^ n)%R.\nProof.\nintros x Hx n.\nchange (fact (S n)) with (S n * fact n).\nrewrite mult_INR.\nrewrite Rinv_mult_distr.\nsimpl pow.\nrewrite <- (Rmult_1_r (/ _ * _ ^ n)).\nreplace (/ INR (S n) * / INR (fact n) * (x * x ^ n))%R\n  with (/ INR (fact n) * x ^ n * (/ INR (S n) * x))%R by ring.\napply Rmult_le_compat_l.\napply Rmult_le_pos.\napply Rlt_le.\napply Rinv_0_lt_compat.\napply (lt_INR 0).\napply lt_O_fact.\nnow apply pow_le.\nrewrite <- (Rmult_1_r 1).\napply Rmult_le_compat.\napply Rlt_le.\napply Rinv_0_lt_compat.\napply (lt_INR 0).\napply lt_O_Sn.\napply Hx.\nrewrite <- Rinv_1.\napply Rle_Rinv_pos.\napply Rlt_0_1.\napply (le_INR 1).\napply le_n_S, le_0_n.\napply Hx.\nnow apply not_0_INR.\napply INR_fact_neq_0.\nQed.\n\nLemma Un_decreasing_cos :\n  forall x : R,\n  (Rabs x <= 1)%R ->\n  Un_decreasing (fun n => / INR (fact (2 * n)) * x ^ (2 * n))%R.\nProof.\nintros x Hx n.\nreplace (2 * S n) with (2 + 2 * n) by ring.\nrewrite pow_add.\nrewrite <- Rmult_assoc.\napply Rmult_le_compat_r.\nrewrite pow_sqr.\napply pow_le.\napply Rle_0_sqr.\nchange (fact (2 + 2 * n)) with ((2 + 2 * n) * ((1 + 2 * n) * fact (2 * n))).\nrewrite  mult_assoc, mult_comm.\nrewrite mult_INR.\nrewrite <- (Rmult_1_r (/ INR (fact _))).\nrewrite Rinv_mult_distr.\nrewrite Rmult_assoc.\napply Rmult_le_compat_l.\napply Rlt_le.\napply Rinv_0_lt_compat.\napply (lt_INR 0).\napply lt_O_fact.\nrewrite <- (Rmult_1_r 1).\napply Rmult_le_compat.\napply Rlt_le.\napply Rinv_0_lt_compat.\napply (lt_INR 0).\napply lt_O_Sn.\nunfold pow.\nrewrite Rmult_1_r.\napply Rle_0_sqr.\nrewrite <- Rinv_1.\napply Rle_Rinv_pos.\napply Rlt_0_1.\napply (le_INR 1).\napply le_n_S, le_0_n.\nreplace 1%R with (1 * (1 * 1))%R by ring.\napply pow_maj_Rabs with (1 := Hx).\napply INR_fact_neq_0.\nnow apply not_0_INR.\nQed.\n\nLemma Un_cv_subseq :\n  forall (u : nat -> R) (f : nat -> nat) (l : R),\n  (forall n, f n < f (S n)) ->\n  Un_cv u l -> Un_cv (fun n => u (f n)) l.\nProof.\nintros u f l Hf Cu eps He.\ndestruct (Cu eps He) as [N HN].\nexists N.\nintros n Hn.\napply HN.\napply le_trans with (1 := Hn).\nclear -Hf.\ninduction n.\napply le_0_n.\nspecialize (Hf n).\nlia.\nQed.\n\nDefinition sinc (x : R) := proj1_sig (exist_sin (Rsqr x)).\n\nLemma sin_sinc :\n  forall x,\n  sin x = (x * sinc x)%R.\nProof.\nintros x.\nunfold sin, sinc.\nnow case exist_sin.\nQed.\n\nLemma sinc_0 :\n  sinc 0 = 1%R.\nProof.\nunfold sinc.\ncase exist_sin.\nsimpl.\nunfold sin_in.\nintros y Hy.\napply uniqueness_sum with (1 := Hy).\nintros eps He.\nexists 1.\nintros n Hn.\nrewrite (tech2 _ 0) by easy.\nsimpl sum_f_R0 at 1.\nrewrite sum_eq_R0.\nunfold R_dist, sin_n.\nsimpl.\nreplace (1 / 1 * 1 + 0 - 1)%R with 0%R by field.\nnow rewrite Rabs_R0.\nclear.\nintros m _.\nrewrite Rsqr_0, pow_i.\napply Rmult_0_r.\napply lt_0_Sn.\nQed.\n\nLemma Un_decreasing_sinc :\n  forall x : R,\n  (Rabs x <= 1)%R ->\n  Un_decreasing (fun n : nat => (/ INR (fact (2 * n + 1)) * x ^ (2 * n)))%R.\nProof.\nintros x Hx n.\nreplace (2 * S n) with (2 + 2 * n) by ring.\nrewrite pow_add.\nrewrite <- Rmult_assoc.\napply Rmult_le_compat_r.\nrewrite pow_sqr.\napply pow_le.\napply Rle_0_sqr.\nchange (fact (2 + 2 * n + 1)) with ((2 + 2 * n + 1) * ((1 + 2 * n + 1) * fact (2 * n + 1))).\nrewrite mult_assoc, mult_comm.\nrewrite mult_INR.\nrewrite <- (Rmult_1_r (/ INR (fact _))).\nrewrite Rinv_mult_distr.\nrewrite Rmult_assoc.\napply Rmult_le_compat_l.\napply Rlt_le.\napply Rinv_0_lt_compat.\napply (lt_INR 0).\napply lt_O_fact.\nrewrite <- (Rmult_1_r 1).\napply Rmult_le_compat.\napply Rlt_le.\napply Rinv_0_lt_compat.\napply (lt_INR 0).\napply lt_O_Sn.\nunfold pow.\nrewrite Rmult_1_r.\napply Rle_0_sqr.\nrewrite <- Rinv_1.\napply Rle_Rinv_pos.\napply Rlt_0_1.\napply (le_INR 1).\napply le_n_S, le_0_n.\nrewrite <- (pow1 2).\napply pow_maj_Rabs with (1 := Hx).\napply INR_fact_neq_0.\nnow apply not_0_INR.\nQed.\n\nLemma atan_plus_PI4 :\n  forall x, (-1 < x)%R ->\n  (atan ((x - 1) / (x + 1)) + PI / 4)%R = atan x.\nProof.\nintros x Hx.\nassert (H1: ((x - 1) / (x + 1) < 1)%R).\n  apply Rmult_lt_reg_r with (x + 1)%R.\n  lra.\n  unfold Rdiv.\n  rewrite Rmult_1_l, Rmult_assoc, Rinv_l, Rmult_1_r.\n  lra.\n  apply Rgt_not_eq.\n  lra.\nassert (H2: (- PI / 2 < atan ((x - 1) / (x + 1)) + PI / 4 < PI / 2)%R).\n  split.\n  rewrite <- (Rplus_0_r (- PI / 2)).\n  apply Rplus_lt_compat.\n  apply atan_bound.\n  apply PI4_RGT_0.\n  apply Rplus_lt_reg_r with (-(PI / 4))%R.\n  rewrite Rplus_assoc, Rplus_opp_r, Rplus_0_r.\n  replace (PI/2 + - (PI/4))%R with (PI/4)%R by field.\n  rewrite <- atan_1.\n  now apply atan_increasing.\napply tan_is_inj.\nexact H2.\napply atan_bound.\nrewrite atan_right_inv.\nrewrite tan_plus.\nrewrite atan_right_inv.\nrewrite tan_PI4.\nfield.\nsplit.\napply Rgt_not_eq.\nlra.\napply Rgt_not_eq.\nring_simplify.\napply Rlt_0_2.\napply Rgt_not_eq, cos_gt_0.\nunfold Rdiv.\nrewrite <- Ropp_mult_distr_l_reverse.\napply atan_bound.\napply atan_bound.\nrewrite cos_PI4.\napply Rgt_not_eq.\nunfold Rdiv.\nrewrite Rmult_1_l.\napply Rinv_0_lt_compat.\napply sqrt_lt_R0.\napply Rlt_0_2.\napply Rgt_not_eq, cos_gt_0.\nunfold Rdiv.\nnow rewrite <- Ropp_mult_distr_l_reverse.\napply H2.\nrewrite tan_PI4, Rmult_1_r.\nrewrite atan_right_inv.\napply Rgt_not_eq.\nnow apply Rgt_minus.\nQed.\n\nLemma atan_inv :\n  forall x, (0 < x)%R ->\n  atan (/ x) = (PI / 2 - atan x)%R.\nProof.\nintros x Hx.\napply tan_is_inj.\napply atan_bound.\nsplit.\napply Rlt_trans with R0.\nunfold Rdiv.\nrewrite Ropp_mult_distr_l_reverse.\napply Ropp_lt_gt_0_contravar.\napply PI2_RGT_0.\napply Rgt_minus.\napply atan_bound.\napply Rplus_lt_reg_r with (atan x - PI / 2)%R.\nring_simplify.\nrewrite <- atan_0.\nnow apply atan_increasing.\nrewrite atan_right_inv.\nunfold tan.\nrewrite sin_shift.\nrewrite cos_shift.\nrewrite <- Rinv_Rdiv.\napply f_equal, sym_eq, atan_right_inv.\napply Rgt_not_eq, sin_gt_0.\nrewrite <- atan_0.\nnow apply atan_increasing.\napply Rlt_trans with (2 := PI2_Rlt_PI).\napply atan_bound.\napply Rgt_not_eq, cos_gt_0.\nunfold Rdiv.\nrewrite <- Ropp_mult_distr_l_reverse.\napply atan_bound.\napply atan_bound.\nQed.\n\nLemma Un_decreasing_atanc :\n  forall x : R,\n  (Rabs x <= 1)%R ->\n  Un_decreasing (fun n : nat => (/ INR (2 * n + 1) * x ^ (2 * n)))%R.\nProof.\nintros x Hx n.\nreplace (2 * S n) with (2 + 2 * n) by ring.\nrewrite pow_add.\nrewrite <- Rmult_assoc.\napply Rmult_le_compat_r.\nrewrite pow_sqr.\napply pow_le.\napply Rle_0_sqr.\nrewrite <- (Rmult_1_r (/ INR (2 * n + 1))).\napply Rmult_le_compat.\napply Rlt_le.\napply Rinv_0_lt_compat.\napply (lt_INR 0).\napply lt_O_Sn.\nunfold pow.\nrewrite Rmult_1_r.\napply Rle_0_sqr.\napply Rlt_le.\napply Rinv_lt.\napply (lt_INR 0).\nrewrite plus_comm.\napply lt_O_Sn.\napply lt_INR.\nrewrite <- plus_assoc.\napply (plus_lt_compat_r 0).\napply lt_O_Sn.\nrewrite <- (pow1 2).\napply pow_maj_Rabs with (1 := Hx).\nQed.\n\nLemma Un_cv_atanc :\n  forall x : R,\n  (Rabs x <= 1)%R ->\n  Un_cv (fun n : nat => (/ INR (2 * n + 1) * x ^ (2 * n)))%R 0.\nProof.\nintros x Hx eps Heps.\nunfold R_dist.\ndestruct (archimed_cor1 eps Heps) as [N [HN1 HN2]].\nexists N.\nintros n Hn.\nassert (H: (0 < / INR (2 * n + 1))%R).\n  apply Rinv_0_lt_compat.\n  apply (lt_INR 0).\n  rewrite plus_comm.\n  apply lt_O_Sn.\nrewrite Rminus_0_r, Rabs_pos_eq.\napply Rle_lt_trans with (/ INR (2 * n + 1) * 1)%R.\napply Rmult_le_compat_l.\nnow apply Rlt_le.\nrewrite <- (pow1 (2 * n)).\napply pow_maj_Rabs with (1 := Hx).\nrewrite Rmult_1_r.\napply Rlt_trans with (2 := HN1).\napply Rinv_lt.\nnow apply (lt_INR 0).\napply lt_INR.\napply le_lt_trans with (1 := Hn).\nclear ; omega.\napply Rmult_le_pos.\nnow apply Rlt_le.\nrewrite pow_Rsqr.\napply pow_le.\napply Rle_0_sqr.\nQed.\n\nLemma atanc_exists :\n  forall x,\n  (Rabs x <= 1)%R ->\n  { l : R | Un_cv (sum_f_R0 (tg_alt (fun n => / INR (2 * n + 1) * x ^ (2 * n))%R)) l }.\nProof.\nintros x Hx.\napply alternated_series.\nnow apply Un_decreasing_atanc.\nnow apply Un_cv_atanc.\nQed.\n\nDefinition atanc x :=\n  match Ratan.in_int x with\n  | left H => proj1_sig (atanc_exists x (Rabs_le _ _ H))\n  | right _ => (atan x / x)%R\n  end.\n\nLemma atanc_opp :\n  forall x,\n  atanc (- x) = atanc x.\nProof.\nintros x.\nunfold atanc.\ndestruct (Ratan.in_int x) as [Hx|Hx] ;\n  case Ratan.in_int ; intros Hx'.\ndo 2 case atanc_exists ; simpl projT1.\nintros l1 C1 l2 C2.\napply UL_sequence with (1 := C2).\napply Un_cv_ext with (2 := C1).\nintros N.\napply sum_eq.\nintros n _.\nunfold tg_alt.\nreplace (-x)%R with ((-1) * x)%R by ring.\nnow rewrite Rpow_mult_distr, pow_1_even, Rmult_1_l.\nelim Hx'.\nsplit.\nnow apply Ropp_le_contravar.\nrewrite <- (Ropp_involutive 1).\nnow apply Ropp_le_contravar.\nelim Hx.\nsplit.\nrewrite <- (Ropp_involutive x).\nnow apply Ropp_le_contravar.\nnow apply Ropp_le_cancel.\nrewrite atan_opp.\nfield.\ncontradict Hx.\nrewrite Hx.\nsplit.\nrewrite <- Ropp_0.\napply Ropp_le_contravar.\napply Rle_0_1.\napply Rle_0_1.\nQed.\n\nLemma atan_atanc :\n  forall x,\n  atan x = (x * atanc x)%R.\nProof.\nassert (H1: forall x, (0 < x < 1 -> atan x = x * atanc x)%R).\n  intros x Hx.\n  rewrite atan_eq_ps_atan with (1 := Hx).\n  unfold ps_atan, atanc.\n  case Ratan.in_int ; intros H.\n  destruct ps_atan_exists_1 as [l1 C1].\n  destruct atanc_exists as [l2 C2].\n  simpl.\n  clear H.\n  apply UL_sequence with (1 := C1).\n  apply Un_cv_ext with (fun N => x * sum_f_R0 (tg_alt (fun n => (/ INR (2 * n + 1) * x ^ (2 * n)))) N)%R.\n  intros N.\n  rewrite scal_sum.\n  apply sum_eq.\n  intros n Hn.\n  unfold tg_alt, Ratan_seq.\n  rewrite pow_add.\n  unfold Rdiv.\n  ring.\n  apply CV_mult with (2 := C2).\n  intros eps Heps.\n  exists 0.\n  intros n _.\n  now rewrite R_dist_eq.\n  elim H.\n  split.\n  apply Rle_trans with 0%R.\n  rewrite <- Ropp_0.\n  apply Ropp_le_contravar.\n  apply Rle_0_1.\n  now apply Rlt_le.\n  now apply Rlt_le.\nassert (H2: atan 1 = Rmult 1 (atanc 1)).\n  rewrite Rmult_1_l.\n  rewrite atan_1.\n  rewrite <- Alt_PI_eq.\n  unfold Alt_PI.\n  destruct exist_PI as [pi C1].\n  replace (4 * pi / 4)%R with pi by field.\n  unfold atanc.\n  case Ratan.in_int ; intros H'.\n  destruct atanc_exists as [l C2].\n  simpl.\n  apply UL_sequence with (1 := C1).\n  apply Un_cv_ext with (2 := C2).\n  intros N.\n  apply sum_eq.\n  intros n _.\n  unfold tg_alt, PI_tg.\n  now rewrite pow1, Rmult_1_r.\n  elim H'.\n  split.\n  apply Rle_trans with (2 := Rle_0_1).\n  rewrite <- Ropp_0.\n  apply Ropp_le_contravar.\n  apply Rle_0_1.\n  apply Rle_refl.\nassert (H3: forall x, (0 < x -> atan x = x * atanc x)%R).\n  intros x Hx.\n  destruct (Req_dec x 1) as [J1|J1].\n  now rewrite J1.\n  generalize (H1 x).\n  unfold atanc.\n  case Ratan.in_int ; intros H.\n  destruct (proj2 H) as [J2|J2].\n  case atanc_exists ; simpl ; intros l _.\n  intros K.\n  apply K.\n  now split.\n  now elim J1.\n  intros _.\n  field.\n  now apply Rgt_not_eq.\nintros x.\ndestruct (total_order_T 0 x) as [[J|J]|J].\nnow apply H3.\nrewrite <- J.\nnow rewrite atan_0, Rmult_0_l.\nrewrite <- (Ropp_involutive x).\nrewrite atan_opp, atanc_opp.\nrewrite H3.\napply sym_eq, Ropp_mult_distr_l_reverse.\nrewrite <- Ropp_0.\nnow apply Ropp_lt_contravar.\nQed.\n\nLemma Un_decreasing_ln1pc :\n  forall x : R,\n  (0 <= x <= 1)%R ->\n  Un_decreasing (fun n : nat => (/ INR (n + 1) * x ^ n))%R.\nProof.\nintros x Hx n.\nchange (S n) with (1 + n) at 2.\nrewrite pow_add.\nsimpl (pow x 1).\nrewrite Rmult_1_r, <- Rmult_assoc.\napply Rmult_le_compat_r.\nnow apply pow_le.\nrewrite <- (Rmult_1_r (/ INR (n + 1))).\napply Rmult_le_compat ; try easy.\napply Rlt_le.\napply Rinv_0_lt_compat.\napply (lt_INR 0).\napply lt_O_Sn.\napply Rlt_le.\napply Rinv_lt.\napply (lt_INR 0).\nrewrite plus_comm.\napply lt_O_Sn.\napply lt_INR.\napply lt_n_Sn.\nQed.\n\nLemma Un_cv_ln1pc :\n  forall x : R,\n  (Rabs x <= 1)%R ->\n  Un_cv (fun n : nat => (/ INR (n + 1) * x ^ n))%R 0.\nProof.\nintros x Hx eps Heps.\nunfold R_dist.\ndestruct (archimed_cor1 eps Heps) as [N [HN1 HN2]].\nexists N.\nintros n Hn.\nassert (H: (0 < / INR (n + 1))%R).\n  apply Rinv_0_lt_compat.\n  apply (lt_INR 0).\n  rewrite plus_comm.\n  apply lt_O_Sn.\nrewrite Rminus_0_r.\nrewrite Rabs_mult, Rabs_pos_eq.\napply Rle_lt_trans with (/ INR (n + 1) * 1)%R.\napply Rmult_le_compat_l.\nnow apply Rlt_le.\nrewrite <- (pow1 n).\nrewrite <- RPow_abs.\napply pow_maj_Rabs.\nnow rewrite Rabs_Rabsolu.\nrewrite Rmult_1_r.\napply Rlt_trans with (2 := HN1).\napply Rinv_lt.\nnow apply (lt_INR 0).\napply lt_INR.\napply le_lt_trans with (1 := Hn).\nrewrite plus_comm.\napply lt_n_Sn.\nnow apply Rlt_le.\nQed.\n\nLemma ln1pc_exists :\n  forall x,\n  (0 <= x < 1)%R ->\n  { l : R | Un_cv (sum_f_R0 (tg_alt (fun n => / INR (n + 1) * x ^ n)%R)) l }.\nProof.\nintros x Hx.\napply alternated_series.\napply Un_decreasing_ln1pc.\napply (conj (proj1 Hx)).\nnow apply Rlt_le.\napply Un_cv_ln1pc.\nrewrite Rabs_pos_eq by easy.\nnow apply Rlt_le.\nQed.\n\nLemma ln1pc_in_int :\n  forall x,\n  { (0 <= x < 1)%R } + { ~(0 <= x < 1)%R }.\nProof.\nintros x.\ndestruct (Rle_dec 0 x) as [H1|H1].\ndestruct (Rlt_dec x 1) as [H2|H2].\nleft.\nnow split.\nright.\nnow contradict H2.\nright.\nnow contradict H1.\nQed.\n\nDefinition ln1pc x :=\n  match ln1pc_in_int x with\n  | left H => proj1_sig (ln1pc_exists x H)\n  | right _ => (ln (1 + x) / x)%R\n  end.\n\nRequire Import Coquelicot.Coquelicot.\n\nLemma ln1p_ln1pc :\n  forall x,\n  ln (1 + x) = (x * ln1pc x)%R.\nProof.\nintros x.\nunfold ln1pc.\ndestruct ln1pc_in_int as [Hx|Hx].\n2: field ; contradict Hx ; rewrite Hx ; split ;\n  [ apply Rle_refl | apply Rlt_0_1 ].\ndestruct ln1pc_exists as [y Hy].\nsimpl.\nreplace y with (PSeries (fun n => (-1)^n / INR (n + 1)) x).\nrewrite <- PSeries_incr_1.\nreplace (ln (1 + x)) with (RInt (fun t => / (1 + t)) 0 x).\nrewrite <- (PSeries_ext (PS_Int (fun n => (-1)^n))).\nassert (Hc: Rbar_lt (Rabs x) (CV_radius (fun n : nat => (-1) ^ n))).\n  rewrite (CV_radius_finite_DAlembert _ 1).\n  now rewrite Rinv_1, Rabs_pos_eq.\n  intros n.\n  apply pow_nonzero.\n  now apply IZR_neq.\n  exact Rlt_0_1.\n  apply is_lim_seq_ext with (fun _ => 1%R).\n    intros n.\n    change ((-1)^(S n) / (-1)^n)%R with (-(1) * (-1)^n */ (-1)^n)%R.\n    rewrite Rmult_assoc, Rinv_r, Rmult_1_r, Rabs_Ropp.\n    apply eq_sym, Rabs_R1.\n    apply pow_nonzero.\n    now apply IZR_neq.\n  apply is_lim_seq_const.\nrewrite <- RInt_PSeries with (1 := Hc).\napply RInt_ext.\nintros t.\nrewrite Rmin_left, Rmax_right by easy.\nintros Ht.\nrewrite <- (Ropp_involutive t) at 1.\nunfold PSeries.\nrewrite <- (Series_ext (fun k => (-t)^k)).\napply eq_sym, Series_geom.\nrewrite Rabs_Ropp, Rabs_pos_eq.\nnow apply Rlt_trans with x.\nnow apply Rlt_le.\nintros n.\nreplace (-t)%R with (-1 * t)%R by ring.\napply Rpow_mult_distr.\nintros [|n].\neasy.\nunfold PS_incr_1.\nnow rewrite Plus.plus_comm.\napply is_RInt_unique.\nassert (H: forall t, -1 < t -> is_derive (fun t : R => ln (1 + t)) t (/ (1 + t))).\n  intros t Ht.\n  auto_derive.\n  rewrite <- (Rplus_opp_r 1).\n  now apply Rplus_lt_compat_l.\n  apply Rmult_1_l.\napply (is_RInt_ext (Derive (fun t => ln (1 + t)))).\n  intros t.\n  rewrite Rmin_left by easy.\n  intros [Ht _].\n  apply is_derive_unique.\n  apply H.\n  apply Rlt_trans with (2 := Ht).\n  now apply IZR_lt.\nreplace (ln (1 + x)) with (ln (1 + x) - ln (1 + 0))%R.\napply (is_RInt_derive (fun t => ln (1 + t))).\n  intros t.\n  rewrite Rmin_left by easy.\n  intros [Ht _].\n  apply Derive_correct.\n  eexists.\n  apply H.\n  apply Rlt_le_trans with (2 := Ht).\n  now apply IZR_lt.\nintros t.\nrewrite Rmin_left by easy.\nintros [Ht _].\napply continuous_ext_loc with (fun t : R => /(1 + t)).\napply locally_interval with (-1)%R p_infty.\napply Rlt_le_trans with (2 := Ht).\nnow apply IZR_lt.\neasy.\nclear t Ht.\nintros t Ht _.\napply sym_eq, is_derive_unique.\nnow apply H.\napply continuous_comp.\napply (continuous_plus (fun t : R => 1)).\napply filterlim_const.\napply filterlim_id.\napply (filterlim_Rbar_inv (1 + t)).\napply Rbar_finite_neq.\napply Rgt_not_eq.\nrewrite <- (Rplus_0_l 0).\napply Rplus_lt_le_compat with (1 := Rlt_0_1) (2 := Ht).\nrewrite Rplus_0_r, ln_1.\napply Rminus_0_r.\napply is_pseries_unique.\napply is_lim_seq_Reals.\napply Un_cv_ext with (2 := Hy).\nintros n.\nrewrite <- sum_n_Reals.\napply sum_n_ext.\nintros m.\nrewrite pow_n_pow.\nunfold tg_alt.\nrewrite <- Rmult_assoc.\napply Rmult_comm.\nQed.\n\n(** Define a shorter name *)\nNotation Rmult_neq0 := Rmult_integral_contrapositive_currified.\n\nLemma Rdiv_eq_reg a b c d :\n  (a * d = b * c -> b <> 0%R -> d <> 0%R -> a / b = c / d)%R.\nProof.\nintros Heq Hb Hd.\napply (Rmult_eq_reg_r (b * d)).\nfield_simplify; trivial.\ntry now rewrite Heq.\nnow apply Rmult_neq0.\nQed.\n\nLemma Rlt_neq_sym (x y : R) :\n  (x < y -> y <> x)%R.\nProof. now intros Hxy Keq; rewrite Keq in Hxy; apply (Rlt_irrefl _ Hxy). Qed.\n\nLemma Rdiv_pos_compat (x y : R) :\n  (0 <= x -> 0 < y -> 0 <= x / y)%R.\nProof.\nintros Hx Hy.\nunfold Rdiv; rewrite <- (@Rmult_0_l (/ y)).\napply Rmult_le_compat_r; trivial.\nnow left; apply Rinv_0_lt_compat.\nQed.\n\nLemma Rdiv_pos_compat_rev (x y : R) :\n  (0 <= x / y -> 0 < y -> 0 <= x)%R.\nProof.\nintros Hx Hy.\nunfold Rdiv; rewrite <-(@Rmult_0_l y), <-(@Rmult_1_r x).\nrewrite <-(Rinv_r y); [|now apply Rlt_neq_sym].\nrewrite (Rmult_comm y), <-Rmult_assoc.\nnow apply Rmult_le_compat_r; trivial; left.\nQed.\n\nLemma Rdiv_neg_compat (x y : R) :\n  (x <= 0 -> 0 < y -> x / y <= 0)%R.\nProof.\nintros Hx Hy.\nunfold Rdiv; rewrite <-(@Rmult_0_l (/ y)).\napply Rmult_le_compat_r; trivial.\nnow left; apply Rinv_0_lt_compat.\nQed.\n\nLemma Rdiv_neg_compat_rev (x y : R) :\n  (x / y <= 0 -> 0 < y -> x <= 0)%R.\nProof.\nintros Hx Hy.\nrewrite <-(@Rmult_0_l y), <-(@Rmult_1_r x).\nrewrite <-(Rinv_r y); [|now apply Rlt_neq_sym].\nrewrite (Rmult_comm y), <-Rmult_assoc.\napply Rmult_le_compat_r; trivial.\nnow left.\nQed.\n\n(** The following definition can be used by doing [rewrite !Rsimpl] *)\nDefinition Rsimpl :=\n  (Rplus_0_l, Rplus_0_r, Rmult_1_l, Rmult_1_r, Rmult_0_l, Rmult_0_r, Rdiv_1).\n\nSection Integral.\n\nVariables (f : R -> R) (ra rb : R).\nHypothesis Hab : ra < rb.\nHypothesis Hint : ex_RInt f ra rb.\n\nLemma RInt_le_r (u : R) :\n (forall x : R, ra <= x <= rb -> f x <= u) -> RInt f ra rb / (rb - ra) <= u.\nProof.\nintros Hf.\napply Rle_div_l.\nnow apply Rgt_minus.\nrewrite Rmult_comm, <- (RInt_const (V := R_CompleteNormedModule)).\napply RInt_le with (2 := Hint).\nnow apply Rlt_le.\napply ex_RInt_const.\nintros x [Hx1 Hx2].\napply Hf.\nsplit; now apply Rlt_le.\nQed.\n\nLemma RInt_le_l (l : R) :\n  (forall x : R, ra <= x <= rb -> l <= f x) -> l <= RInt f ra rb / (rb - ra).\nProof.\nintros Hf.\napply Rle_div_r.\nnow apply Rgt_minus.\nrewrite Rmult_comm, <- (RInt_const (V := R_CompleteNormedModule)).\napply RInt_le with (3 := Hint).\nnow apply Rlt_le.\napply ex_RInt_const.\nintros x [Hx1 Hx2].\napply Hf.\nsplit; now apply Rlt_le.\nQed.\n\nEnd Integral.\n\n", "meta": {"author": "MSoegtropIMC", "repo": "interval", "sha": "2d7d7fe5d7e150372008924487186215774ba535", "save_path": "github-repos/coq/MSoegtropIMC-interval", "path": "github-repos/coq/MSoegtropIMC-interval/interval-2d7d7fe5d7e150372008924487186215774ba535/src/Missing/Stdlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409024, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7030991791955185}}
{"text": "Require Import Utf8.\n\n(*\n   Documentations: \n       * #<a href=\"https://coq.inria.fr/distrib/current/refman/Reference-Manual018.html\">CoqIDE</a>#\n       * #<a href=\"http://lim.univ-reunion.fr/staff/fred/Enseignement/IntroCoq/Exos-Coq/Petit-guide-de-survie-en-Coq.html\">Petit guide de survie en Coq</a>#\n       * #<a href=\"http://www.inf.ed.ac.uk/teaching/courses/tspl/cheatsheet.pdf\">Cheat sheet</a>#\n       * #<a href=\"https://www.lri.fr/~paulin/MathInfo2/coq-survey.pdf\">Coq Survey</a> (Guide coq de Christine Paulin-Mohring)</a>#\n\n   Charger le fichier #<a href=\"LIFLC-TP3.v\">LIFLC-TP3.v</a>#, qui est\n   à compléter dans ce TP, dans CoqIDE.\n\n *)\n\n\n(* Quelques erreurs de raisonnement fréquentes\n    \n   On peut montrer que ces raisonnements sont faux en Coq.\n *)\n\n(* ex falso sequitur quodlibet *)\nLemma ex_falso : forall P, False -> P.\nProof.\nAdmitted.\n\n(* erreur très fréquente *)\nDefinition dyslexic_imp := ∀ P Q:Prop, (P → Q) → (Q → P).\n(* Pour cette preuve il faut appliquer une hypothèse contenant des\n   quantificateurs forall. Si H est le nom de l'hypothèse, \n\n   apply (H toto) \n\n   permet d'appliquer H en remplaçant la variable quantifiée par toto.\n   Si plusieurs variables sont quantifiées, on peut écrire \n\n   apply (H toto titi)\n*)\nGoal dyslexic_imp -> False.\nProof.\nAdmitted.\n\n(* erreur très fréquente, bis *)\nDefinition dyslexic_contrap := ∀ P Q:Prop, (P → Q) → (~P → ~Q).\nGoal dyslexic_contrap -> False.\nProof.\nAdmitted.\n\n(*\n   Quelques équivalences remarquables en logique du premier ordre\n *)\n\n(* on ouvre une section pour alléger les assertions *)\nSection Basic_FOL.\n\nVariable U : Type.                  (*le type du domaine *)\nVariable P Q : U -> Prop.           (*des prédicats unaires *)\nVariable R S : U -> U -> Prop.      (*des prédicats binaires, ie des relations *)\n\n\nLemma neg_exists_equiv_forall_neg : (~ ∃ x , P x ) <-> ∀ x , ~ P x .\nProof.\nAdmitted.\n\n\nLemma exists_is_or : (∃ x , P x ∨ Q x) <-> (∃ x,  P x) ∨ (∃ x, Q x).\nProof.\nAdmitted.\n\nLemma forall_is_and : (∀ x , P x /\\ Q x) <-> (∀ x,  P x) /\\ (∀ x, Q x).\nProof.\nAdmitted.\n\n\n\nLemma forall_implies_neg_exists_neg  : (∀ x, P x)→ ~(∃ y, ~ P y).\nProof.\nAdmitted.\n\n\n\nGoal (∃ x, (∀ F:U → Prop, F x)) → 2 = 3.\nProof.\nAdmitted.\n\n\n\nGoal (∀ x y, (P(x) ∧ (P(y) -> Q(x)))) -> ∀x, Q(x).\nProof.\nAdmitted.\n\n(* si qq'un est aimé de tous, alors tout le monde aime qq'un *)\nGoal (∃ y, ∀ x, R x y) -> (∀ x, ∃ y, R x y).\nProof.\nAdmitted.\n\n\nGoal (∃ y, ∀ x, R x y) -> (∃ x, R x x).\nProof.\nAdmitted.\n\nEnd Basic_FOL.\n\n\nSection Ensembles.\n(* On va maintenant prouver quelques propriétés des ensembles dont les\n   élements sont d'un certain type U.\n *)\nVariable U : Type.\n  \n(* Un ensemble E peut être représenté par un prédicat unaire qui est\n   vrai lorsque son argument est un élément de E. On utilise cela pour\n   cela Prop (le type des proposition de Coq). Les ensembles sont donc\n   vus comme de type U -> Prop. Une manière de le comprendre est voir\n   un ensemble comme une fonction qui prend un élement et donne une\n   formule qui sera vraie si cet élement est dans l'ensemble. *)\nDefinition Ensemble := U -> Prop.\n\n(* On peut alors redéfinir l'appartenance (In) de x à E comme le fait\n   que le prédicat qui représente E est vrai.  *)\nDefinition In (A:Ensemble) (x:U) : Prop := A x.\nNotation \"x ∈ E\" := (In E x)  (at level 45, right associativity).\n\n(* Les définitions suivantes se construisent naturellement à partir de\n   celle de appartient (In). *)\nDefinition Included (A B:Ensemble) : Prop := forall x, x ∈ A -> x ∈ B.\nNotation \"A ⊆ B\" := (Included A B)  (at level 70, right associativity).\n\nDefinition Cup (A B:Ensemble) : U -> Prop := fun x => x ∈ A \\/ x ∈ B.\nNotation \"A ∪ B\" := (Cup A B)  (at level 70, right associativity).\n\nDefinition Cap (A B:Ensemble) : U -> Prop := fun x => x ∈ A /\\ x ∈ B.\nNotation \"A ∩ B\" := (Cap A B)  (at level 70, right associativity).\n\nDefinition Empty : U -> Prop := fun x => False .\nNotation \"∅\" := (Empty).\n\nDefinition Setminus (B C:Ensemble) : Ensemble := fun x:U => x ∈ B /\\ ~ x ∈ C.\nNotation \"A \\ B\" := (Setminus A B)  (at level 80, right associativity).\n\n(* Cet axiome permet de déduire une égalité à partir de la double\n   inclusion. *)\nAxiom Extensionality_Ensembles : forall A B:Ensemble,  (A ⊆ B /\\ B ⊆ A) -> A = B.\n\nVariable A B C: Ensemble.\n\n(* Exemple pour comprendre comment utiliser les définitons ci-dessus *)\n(* Réflexivité de ⊆ *)\nGoal A ⊆ A.\nProof.\n  unfold Included.\n  intros x.\n  auto.\nQed.\n\n(* Transitivité de ⊆.\n\n   Remarque: Avec la réflexivité et l'axiome Extensionality_Ensembles,\n   on a que ⊆ est un ensemble.\n\n *)\nGoal A ⊆ B -> B ⊆ C  -> A ⊆ C.\nProof.\nAdmitted.\n\nGoal ∅ ⊆ A.\nProof.\nAdmitted.\n\nGoal A ⊆ B <-> (A ∩ B) = A.\nProof.\nAdmitted.\n\n(* exo de td lif LF *)\nGoal  (A \\ (B ∪ C)) = ((A \\ B) ∩ (A \\ C)).\nProof.\nAdmitted.\n\n\nGoal A ⊆ B -> (A \\ B) = ∅.\n(* la réciproque est DIFFICILE *)\nProof.\nAdmitted.\n \nEnd Ensembles.\n", "meta": {"author": "badbayard", "repo": "code_coq_logique_classique", "sha": "5e995971a26af2c502a5c04aefe9ba775580f3e5", "save_path": "github-repos/coq/badbayard-code_coq_logique_classique", "path": "github-repos/coq/badbayard-code_coq_logique_classique/code_coq_logique_classique-5e995971a26af2c502a5c04aefe9ba775580f3e5/LIFLC-TP3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7030991721190654}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) (y : natural) (lf2 : natural)\n  : natural := Succ (plus Zero y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_commut/goal33conj187_coqofml_rXZUSr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7030079738060515}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Sgn.\nRequire Import Crypto.Util.ZUtil.Modulo.\nRequire Import Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma quot_div_full a b : Z.quot a b = Z.sgn a * Z.sgn b * (Z.abs a / Z.abs b).\n  Proof.\n    destruct (Z_zerop b); [ subst | apply Z.quot_div; assumption ].\n    destruct a; simpl; reflexivity.\n  Qed.\n\n  Local Arguments Z.mul !_ !_.\n\n  Lemma quot_sgn_nonneg a b : 0 <= Z.sgn (Z.quot a b) * Z.sgn a * Z.sgn b.\n  Proof.\n    rewrite quot_div_full, !Z.sgn_mul, !Z.sgn_sgn.\n    set (d := Z.abs a / Z.abs b).\n    destruct a, b; simpl; try (subst d; simpl; lia);\n      try rewrite (Z.mul_opp_l 1);\n      do 2 try rewrite (Z.mul_opp_r _ 1);\n      rewrite ?Z.mul_1_l, ?Z.mul_1_r, ?Z.opp_involutive;\n      apply Z.div_abs_sgn_nonneg.\n  Qed.\n\n  Lemma quot_nonneg_same_sgn a b : Z.sgn a = Z.sgn b -> 0 <= Z.quot a b.\n  Proof.\n    intro H.\n    generalize (quot_sgn_nonneg a b); rewrite H.\n    rewrite <- Z.mul_assoc, <- Z.sgn_mul.\n    destruct (Z_zerop b); [ subst; destruct a; unfold Z.quot; simpl in *; congruence | ].\n    rewrite (Z.sgn_pos (_ * _)) by nia.\n    intro; apply Z.sgn_nonneg; lia.\n  Qed.\n\n  Lemma mul_quot_eq_full a m : m <> 0 -> m * (Z.quot a m) = a - a mod (Z.abs m * Z.sgn a).\n  Proof.\n    intro Hm.\n    assert (0 <> m * m) by (intro; apply Hm; nia).\n    assert (0 < m * m) by nia.\n    assert (0 <> Z.abs m) by (destruct m; simpl in *; try congruence).\n    rewrite quot_div_full.\n    rewrite <- (Z.abs_sgn m) at 1.\n    transitivity ((Z.sgn m * Z.sgn m) * Z.sgn a * (Z.abs m * (Z.abs a / Z.abs m))); [ nia | ].\n    rewrite <- Z.sgn_mul, Z.sgn_pos, Z.mul_1_l, Z.mul_div_eq_full by lia.\n    rewrite Z.mul_sub_distr_l.\n    rewrite Z.mul_comm, Z.abs_sgn.\n    destruct a; simpl Z.sgn; simpl Z.abs; autorewrite with zsimplify_const; [ reflexivity | reflexivity | ].\n    repeat match goal with |- context[-1 * ?x] => replace (-1 * x) with (-x) by lia end.\n    repeat match goal with |- context[?x * -1] => replace (x * -1) with (-x) by lia end.\n    rewrite <- Zmod_opp_opp; simpl Z.opp.\n    reflexivity.\n  Qed.\n\n  Lemma quot_sub_sgn a : Z.quot (a - Z.sgn a) a = 0.\n  Proof.\n    rewrite quot_div_full.\n    destruct (Z_zerop a); subst; [ lia | ].\n    rewrite Z.div_small; lia.\n  Qed.\n\n  Lemma quot_small_abs a b : 0 <= Z.abs a < Z.abs b -> Z.quot a b = 0.\n  Proof.\n    intros; rewrite Z.quot_small_iff by lia; lia.\n  Qed.\n\n  Lemma quot_add_sub_sgn_small a b : b <> 0 -> Z.sgn a = Z.sgn b -> Z.quot (a + b - Z.sgn b) b = Z.quot (a - Z.sgn b) b + 1.\n  Proof.\n    destruct (Z_zerop a), (Z_zerop b), (Z_lt_le_dec a 0), (Z_lt_le_dec b 0), (Z_lt_le_dec 1 (Z.abs a));\n      subst;\n      try lia;\n      rewrite !Z.quot_div_full;\n      try rewrite (Z.sgn_neg a) by lia;\n      try rewrite (Z.sgn_neg b) by lia;\n      repeat first [ reflexivity\n                   | rewrite Z.sgn_neg by lia\n                   | rewrite Z.sgn_pos by lia\n                   | rewrite Z.abs_eq by lia\n                   | rewrite Z.abs_neq by lia\n                   | rewrite !Z.mul_opp_l\n                   | rewrite Z.abs_opp in *\n                   | rewrite Z.abs_eq in * by lia\n                   | match goal with\n                     | [ |- context[-1 * ?x] ]\n                       => replace (-1 * x) with (-x) by lia\n                     | [ |- context[?x * -1] ]\n                       => replace (x * -1) with (-x) by lia\n                     | [ |- context[-?x - ?y] ]\n                       => replace (-x - y) with (-(x + y)) by lia\n                     | [ |- context[-?x + - ?y] ]\n                       => replace (-x + - y) with (-(x + y)) by lia\n                     | [ |- context[(?a + ?b + ?c) / ?b] ]\n                       => replace (a + b + c) with (((a + c) + b * 1)) by lia; rewrite Z.div_add' by lia\n                     | [ |- context[(?a + ?b - ?c) / ?b] ]\n                       => replace (a + b - c) with (((a - c) + b * 1)) by lia; rewrite Z.div_add' by lia\n                     end\n                   | progress intros\n                   | progress Z.replace_all_neg_with_pos\n                   | progress autorewrite with zsimplify ].\n  Qed.\nEnd Z.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ZUtil/Quot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.703007968850736}}
{"text": "Require Export Grothendieck.ToCat CategoryOfSections.\nRequire Import Common.\n\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\nSet Universe Polymorphism.\n\nLocal Open Scope functor_scope.\n\nSection dependent_product.\n  Context `{Funext}.\n  Variable C : PreCategory.\n  Variable P : PreCategory -> Type.\n  Context `{forall C, IsHProp (P C)}.\n  Context `{HF : forall C D, P C -> P D -> IsHSet (Functor C D)}.\n\n  Local Notation Cat := (SubPreCat P).\n\n  Variable F : Functor C Cat.\n\n  (** Quoting http://mathoverflow.net/questions/137689/explicit-description-of-the-oplax-limit-of-a-functor-to-cat:\n\n      The oplax limit is the category of sections for the functor from\n      the Grothendieck construction to the base category.\n\n      The strong limit is the category of cartesian sections\n      (every arrow in the base category gets mapped to a cartesian\n      one).\n\n      Notice how this goes along very well with the interpretation as\n      dependent product and as $∀$: The set theoretic product is just\n      the set of sections into the disjoint union.\n\n      Given a strong functor [F : X → Cat] we denote the Grothendieck\n      construction by [Gr F].\n\n      There is a canonical functor [π : Gr F → X]. Sections of this\n      functor are functors [s : X → Gr F] such that [s ∘ π = id]. *)\n\n  Definition DependentProduct : PreCategory\n    := CategoryOfSections (GrothendieckCatFunctorOfFunctor F).\nEnd dependent_product.\n\nNotation Pi := DependentProduct.\n", "meta": {"author": "CategoricalData", "repo": "HoTT-categories", "sha": "31230d90405631c07d58c9e6ac74fe329237de69", "save_path": "github-repos/coq/CategoricalData-HoTT-categories", "path": "github-repos/coq/CategoricalData-HoTT-categories/HoTT-categories-31230d90405631c07d58c9e6ac74fe329237de69/theories/Categories/DependentProduct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.7029490817116023}}
{"text": "Require Export euclidean__axioms.\nRequire Export euclidean__defs.\nRequire Export lemma__congruencesymmetric.\nRequire Export lemma__lessthancongruence.\nRequire Export logic.\nDefinition proposition__03 : forall A B C D E F, (euclidean__defs.Lt C D A B) -> ((euclidean__axioms.Cong E F A B) -> (exists X, (euclidean__axioms.BetS E X F) /\\ (euclidean__axioms.Cong E X C D))).\nProof.\nintro A.\nintro B.\nintro C.\nintro D.\nintro E.\nintro F.\nintro H.\nintro H0.\nassert (* Cut *) (euclidean__axioms.Cong A B E F) as H1.\n- apply (@lemma__congruencesymmetric.lemma__congruencesymmetric A E F B H0).\n- assert (* Cut *) (euclidean__defs.Lt C D E F) as H2.\n-- apply (@lemma__lessthancongruence.lemma__lessthancongruence C D A B E F H H1).\n-- assert (exists G, (euclidean__axioms.BetS E G F) /\\ (euclidean__axioms.Cong E G C D)) as H3 by exact H2.\ndestruct H3 as [G H4].\ndestruct H4 as [H5 H6].\nexact H2.\nQed.\n", "meta": {"author": "Karnaj", "repo": "dktactgeo", "sha": "f98a62e5ffa2030dc89962e1349e0c273cc911b9", "save_path": "github-repos/coq/Karnaj-dktactgeo", "path": "github-repos/coq/Karnaj-dktactgeo/dktactgeo-f98a62e5ffa2030dc89962e1349e0c273cc911b9/proposition__03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7029232069194521}}
{"text": "Require Import Omega.\n\nInductive added: nat -> nat -> nat -> Prop :=\n  | add_z: added 0 0 0\n  | add_l: forall m n r, added m n r -> added (S m) n (S r)\n  | add_r: forall m n r, added m n r -> added m (S n) (S r).\n\nHint Constructors added.\n\nLemma added_plus:\n  forall m n r, added m n r -> m + n = r.\nProof.\n\nQed.\n\nLemma plus_added:\n  forall m n r, m + n = r -> added m n r.\nProof.\n\nQed.\n", "meta": {"author": "mbrcknl", "repo": "coq-fight-2017", "sha": "7f5ec82d47b79769d3b92ae7f0d8cb8e45891aba", "save_path": "github-repos/coq/mbrcknl-coq-fight-2017", "path": "github-repos/coq/mbrcknl-coq-fight-2017/coq-fight-2017-7f5ec82d47b79769d3b92ae7f0d8cb8e45891aba/added.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7029231916291652}}
{"text": "\nAxiom A1: forall p q : Prop, p->(q->p).\nAxiom A2: forall p q r: Prop, p -> (q->r)->(p->q)->(p->r).\nAxiom A3: forall p q: Prop, (~p->~q)->(q->p).\n\nRequire Import Coq.Logic.Classical_Prop.\n\nLemma HS1 : forall p q r : Prop, (q -> r) -> ((p -> q) -> (p -> r)).\nProof.\nintros P Q R QimplicaR PimplicaQ HP. Show Proof.\napply QimplicaR, PimplicaQ, HP. Show Proof.\n(*Since PimplicaQ : P->Q  and HP : P, then PimplicaQ HP:Q\nand since QimplicaR : Q->R and (PimplicaQ HP): Q, then\nQimplicaR (PimplicaQ HP): R\n*)\nQed.\n\nLemma HS2 : forall p q r : Prop, (p -> q) -> ((q -> r) -> (p -> r)).\nProof.\nintros P Q R PimplicaQ QimplicaR HP. Show Proof.\napply QimplicaR, PimplicaQ, HP. Show Proof.\nQed.\n\nLemma DN1 : forall p : Prop, ~~p -> p.\nProof.\nintros P HDNP.\ndestruct (classic P) as [HP | HNP].\nexact HP.\ntauto.\n\nQed.\n\nLemma DN2 : forall q : Prop, q -> ~~q.\nProof.\nintros Q HDNQ.\ntauto. Show Proof.\nQed.\n\nLemma I8 : forall p q : Prop, (p -> q) -> (~q -> ~p).\nProof. \nintros P Q PimplicaQ HNQ.\napply A3 with (q:=~Q).\n- tauto.\n- exact HNQ.\nShow Proof.\nQed.\n\nLemma CEFMT : forall p r : Prop, r -> (p -> r).\nProof.\n(*A1=p->(q->p)\nR -> (P -> R)\nQ := P*\n*) \nintros P R HR HP.\napply A1 with (q := P).\napply HR. apply HP. Show Proof.\n(*\nA1 R P HR HP\nA1 R P = R ->(P->R)\nA1 R P HR  (P->R)\n*)\nQed.\n\nLemma counterexamplemodustollens : forall p q r : Prop, ~(p -> r) -> ~(r).\nProof.\nintros P Q R NPimplicaR.\ntauto.\nQed.\n \nTheorem counterexamplea: forall p q r:Prop, ~(~(p -> q) -> ~(r)) -> ~ (~(p -> q) -> (~(p -> q) ->\t~(p -> r))).\nProof.\nintros P Q R NNPimplicaQimplicaNR. Show Proof.\ntauto.\nQed.\n\nLemma I1 : forall p q : Prop, p -> ((p -> q) -> q).\nProof.\nintros P Q HP PimplicaQ.\napply PimplicaQ ,HP.\n(*apply H0,H. Show Proof.\napply H0.\nexact H.*)\nQed.\n\nLemma I4 : forall p q r : Prop, (p -> (q -> r)) -> (q -> (p -> r)).\nProof. \nintros P Q R PimplicaQimplicaR HQ HP.\napply PimplicaQimplicaR in HP  as HR.\n- exact HR.\n- exact HQ. Show Proof.\nQed.\n\nLemma I5 : forall p q r : Prop, (p -> q) -> ((q -> r) -> (p -> r)).\nProof.\nintros P Q R PimplicaQ QimplicaR HP.\napply QimplicaR, PimplicaQ, HP. Show Proof.\nQed.\n\nLemma I6: forall p q : Prop, (~p -> q) -> (~q -> p).\nProof.\nintros P Q NPimplicaQ.\ntauto.\nQed.\n\nLemma I7 : forall p : Prop, (~p -> p) -> p.\nProof.\nintros P NPimplicaP.\ntauto.\nQed.\n", "meta": {"author": "JoanDaniel18", "repo": "Proofs-in-Coq-with-and-without-axiom-applications", "sha": "dfabad10b1cdc657daeea26776421f65c77cb694", "save_path": "github-repos/coq/JoanDaniel18-Proofs-in-Coq-with-and-without-axiom-applications", "path": "github-repos/coq/JoanDaniel18-Proofs-in-Coq-with-and-without-axiom-applications/Proofs-in-Coq-with-and-without-axiom-applications-dfabad10b1cdc657daeea26776421f65c77cb694/practice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7029231884657162}}
{"text": "Section simple_proofs.\n Variables P Q R S : Prop.\n\n Lemma id_P : P -> P.\n Proof.\n  intro; assumption.\n Qed. \n \n\n Lemma id_PP : (P -> P) -> P -> P.\n Proof.\n  intro; assumption.\n Qed. \n \n Lemma imp_trans : (P -> Q) -> (Q -> R) -> P -> R.\n Proof.\n  intros H H0 p.\n  apply H0; apply H; assumption.\n Qed.\n\n Lemma imp_perm : (P -> Q -> R) -> Q -> P -> R.\n Proof.\n  intros H q p; apply H; assumption.\n Qed.\n\n Lemma ignore_Q : (P -> R) -> P -> Q -> R.\n Proof.\n  intros H p q; apply H; assumption.\n Qed.\n\n Lemma delta_imp : (P -> P -> Q) -> P -> Q.\n Proof.\n  intros H p; apply H; assumption.\n Qed.\n\n Lemma delta_impR : (P -> Q) -> P -> P -> Q.\n Proof.\n  intros H p p'; apply H; assumption.\n Qed.\n\n Lemma diamond : (P -> Q) -> (P -> R) -> (Q -> R -> S) -> P -> S.\n Proof.\n  intros H H0 H1 p.\n  apply H1; [ apply H | apply H0 ]; assumption.\n Qed.\n\n Lemma weak_peirce : ((((P -> Q) -> P) -> P) -> Q) -> Q.\n Proof.\n  intro H; apply H.\n  intro H0; apply H0.\n  intro p; apply H; intro; assumption.\n Qed.\nEnd simple_proofs.\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/propproof/SRC/simple_proofs2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7029231850009052}}
{"text": "(**\nリストのリフレクション補題\n======\n2019/07/25\n\nこの文書のソースコードは以下にあります。\n\n\nhttps://github.com/suharahiromichi/coq/blob/master/pearl/ssr_list_1.v\n\n *)\n\n(**\n# 説明\n\nMathComp の seq は、seq.v の中で、\n\n``Notation seq := list``\n\n\nという具合に、list のNotation (構文糖）として定義されていて、\nStandard Coq の list と同じものであることが判ります。\n\n（注記）\n\n括弧による表記については、``[::]`` など、MathCompのNotationで上書きされるので、\nかなり変わったものになりますが、支障にはなりません。\nここでは、型としてはseqを、括弧の表記はMathCompの表記を使いますが、\nデータ型として「リスト」と呼ぶことにします。\n\n（注記終わり）\n\nMathComp の中から、Standard Coq で定義されたリストの命題を使用することができます。\n当然、おなじ意味（同値）な命題もあります。\n\n実際には、Standard Coqでは Prop型の命題（述語）として、\nMathCompではbool型を返す関数として定義されているわけですが、\nそれらの間で同値性を示すリフレクション補題を証明することで、\n相互の変換ができ（リフレクションですね）、証明が捗ることがあるかもしれません。\n*)\n\n(**\n# コード例 その1\n*)\n\nRequire Import List.\nFrom mathcomp Require Import all_ssreflect.\n\nSection List_1_1.\n\n(**\n最初の例は、Standard Coq の Lists/List.v で定義されている Forall と Exists です。\n述語Pが、リストの要素のすべてで成り立つ、あるいは、ある要素で成り立つ、\nことを示す命題です。（∀と∃の意味の、forallとexists とは別な意味です。）\n *)\n\n  Check Forall : forall A : Type, (A -> Prop) -> seq A -> Prop.\n  Check Exists : forall A : Type, (A -> Prop) -> seq A -> Prop.\n\n(**\nこれらに対して、MathComp では、\nssreflect/seq.v で all と has という関数が定義されています。\n\n@は、implicitな引数を表示するために使っています。\nこの場合、型Tの指定は、引数として省略できます。\n*)\n\n  Check @all : forall A : Type, (A -> bool) -> seq A -> bool.\n  Check @has : forall A : Type, (A -> bool) -> seq A -> bool.  \n\n(**\nここでは、型しか示しませんが、実際の定義はそれぞれのソースコードを参照してください。\n\nStandard Coq の Forall と Exists は、\n(A->Prop)型の述語と、A型のリストをとり、全体としてProp型を返します。\n\nMathcop の allと has は、(A->bool)型の関数と、A型のリストをとり、\n全体としてbool型を返します。\n*)\n\n(**\nForall と all の間のリフレクション補題を次に示します。\n*)\n  Lemma ForallP {A : Type} (P : A -> Prop) (p : A -> bool) :\n    (forall (a : A), reflect (P a) (p a)) ->\n    forall (s : seq A), reflect (Forall P s) (all p s).\n  Proof.\n    move=> H s.\n    apply/(iffP idP).\n    - elim: s => [Hp | a s IHs /= /andP].\n      + by apply: Forall_nil.\n      + case.\n        move/H => Hpa Hps.\n        apply: Forall_cons.\n        * done.\n        * by apply: IHs.\n    - elim: s => /= [| a s IHs].\n      + done.\n      + move=> HP.\n        apply/andP.\n        inversion HP; subst.\n        split.\n        * by apply/H.\n        * by apply IHs.\n  Qed.\n\n(**\n``reflect (Forall P s) (all p s)``\nが、Forall と all が同値であることを示す\nリフレクション補題で、これだけで同値であることを示します。\n\nしかし、(A->Prop)型の述語P と、(A->bool)型の関数p とがリフレクション関係である\nことを条件としなければなりません。なので、前提に\n``reflect (P a) (p a)``\nが必要となります。\n\nリフレクション補題をしめす reflect の定義は、\nssreflect/ssrbool.v にある定義か、\n文献 [1.] を参照してください。\n*)\n  \n(**\nExists についても同様です。\n*)\n  Lemma ExistsP {A : Type} (P : A -> Prop) (p : A -> bool) :\n    (forall (a : A), reflect (P a) (p a)) ->\n    forall (s : seq A), reflect (Exists P s) (has p s).\n  Proof.\n    move=> H s.\n    apply/(iffP idP).\n    - elim: s => [Hp | a s IHs /= /orP].\n      + done.\n      + case=> [Hpa | Hpa].\n        * apply: Exists_cons_hd.\n            by apply/H.\n        * apply: Exists_cons_tl.\n            by apply: IHs.\n    - elim: s => /= [| a s IHs] HP.\n      + by inversion HP.\n      + apply/orP.\n        inversion HP; subst.\n        * left.\n            by apply/H.\n        * right.\n            by apply: IHs.\n  Qed.\n\nEnd List_1_1.\n\n(**\n# 実行例 その1\n\n最初に、ここで証明したリフレクション補題を使う例です。\n*)\n\nGoal Forall (fun n => n == 1) [:: 1; 1; 1; 1].\nProof.\n  apply/ForallP.\n(**\n``apply/ForallP`` がゴールに対してリフレクション補題を使うことを示します。\n詳細は、文献 [2.] の 3.7節を参照してください。\n\nすると、ForallP の前提部分の証明を求められます。\n``a == 1`` と同値な命題は ``a = 1`` ですから、補題 eqP\n*)\n\nCheck eqP : reflect (_ = _) (_ == _).\n\n(**\nを使って証明することができます。\n*)\n  - move=> a.\n      by apply: eqP.\n\n(**\n残った\n\n``all (fun a => (a == 1) == true) [:: 1; 1; 1; 1]``\n\n\nについては、「計算」で真偽を決定することができるので、\ndone で証明を終了することができます。\n*)\n  - done.\nQed.\n    \n(**\nリフレクション補題を使わない場合は、\nForall のコンストラクタである、Forall_cons と Forall_nil を適用して\nゴールの要素を個々に証明することになります。\n*)\n\nCheck Forall_cons :\n  forall A  (P : A -> Prop) x l, P x -> Forall P l -> Forall P (x :: l).\nCheck Forall_nil :\n  forall A  (P : A -> Prop), Forall P [::].\n\nGoal Forall (fun n => n == 1) [:: 1; 1; 1; 1].\nProof.\n  apply: Forall_cons.\n  - done.\n  - apply: Forall_cons.\n    + done.\n    + apply: Forall_cons.\n      * done.\n      * apply: Forall_cons.\n        ** done.\n        ** apply: Forall_nil.\nQed.\n\n(**\nタクティカルの利用して、短く書くことは可能ですが、\n本質的な操作は変わらないことに注意してください。\n*)\n\nGoal Forall (fun n => n == 1) [:: 1; 1; 1; 1].\nProof.\n  do ! apply: Forall_cons => //=.\nQed.\n\n(**\n# コード例 その2\n*)\n\nSection List_1_2.\n\n(**\n次の例は、指定の値と同じ値がリストの中に存在することを示す In です。\nStarndard Coq の場合は、値とリストをとる述語 In、\nMathComp の場合は、\\in という中置記法の演算子を使います。\n*)  \n\n  Lemma In_inb {A : eqType} (x : A) (s : seq A) : In x s <-> x \\in s.\n  Proof.\n    elim: s.\n    - done.\n    - move=> a s IHs.\n      split=> /=; rewrite inE.\n      + case=> H.\n        * by apply/orP/or_introl/eqP.\n        * by apply/orP/or_intror/IHs.\n      + move/orP; case.\n        * move/eqP => ->.\n            by left.\n        * move=> H.\n          move/IHs in H.\n            by right.\n  Qed.\n  \n  Lemma InP {A : eqType} (x : A) (s : seq A) : reflect (In x s) (x \\in s).\n  Proof.\n    apply: (iffP idP) => H.\n    - by apply/In_inb.\n    - by apply/In_inb.\n  Qed.\n\nEnd List_1_2.\n\n(**\n# 実行例 その2\n*)\n\nGoal In 3 [:: 1; 2; 3; 4].\nProof.\n  apply/InP.\n(**\nここで証明したリフレクション補題 InP を使うと、\nGoal として: ``3 \\in [:: 1; 2; 3; 4]`` が得られます。\nこれについても、「計算」で真偽を決定することができるので、\ndone で終了します。\n*)\n  \n  done.\nQed.\n\n(**\n# 参考文献\n\n[1.] リフレクションのしくみをつくる\n\nhttps://qiita.com/suharahiromichi/items/9cd109386278b4a22a63\n\n\n[2.] 萩原学 アフェルト・レナルド 「Coq/SSReflect/MathCompによる定理証明」 森北出版\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/pearl/ssr_list_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473628, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7029133914854239}}
{"text": "(** Some examples with streams **)\n\n(* Potentially infinite streams *)\nCoInductive pstream A : Type :=\n| pNil : pstream A\n| pCons : A -> pstream A -> pstream A.\n\nArguments pNil {A}.\nArguments pCons {A} _ _.\n\n(* From the \"lecture\", but with pnil case also *)\nCoInductive pstream_eq {A} : pstream A -> pstream A -> Prop :=\n| Pstream_eq_pnil :\n    pstream_eq pNil pNil\n| Pstream_eq_pcons : forall h t1 t2,\n    pstream_eq t1 t2 -> pstream_eq (pCons h t1) (pCons h t2).\n\n(* Implement the standard map function for potentially infinite streams *)\nCoFixpoint pmap {A B} (f : A -> B) (s : pstream A) : pstream B. Admitted.\n\nCoFixpoint pzeroes : pstream nat := pCons 0 pzeroes.\nCoFixpoint pones : pstream nat := pCons 1 pones.\nDefinition pones' := pmap S pzeroes.\n\n(* Reusing the name from CPDT, maybe unfold, destruct or something else would be a better name\n   (as mentioned during the \"lecture\") *)\nDefinition pfrob {A} (s : pstream A) : pstream A :=\n  match s with\n  | pNil => pNil\n  | pCons h t => pCons h t\n  end.\n\nTheorem pfrob_eq : forall {A} (s : pstream A), s = pfrob s.\nProof. destruct s; reflexivity. Qed.\n\n(* Warm up: Same as from the \"lecture\", but here with potentially infinite stream instead *)\nTheorem ones_eq : pstream_eq pones pones'.\nAdmitted.\n\n(* Some problems stolen from http://www.labri.fr/perso/casteran/RecTutorial.pdf,\n   section \"7.2 About injection, discriminate, and inversion\".\n   Illustrates that these things work for co-inductive reasoning also.\n   Warning: Note that the proofs are given in the PDF... *)\nTheorem pNil_not_pCons : forall {A} (a : A) (s : pstream A),\n    pNil <> pCons a s.\nAdmitted.\n\nInductive Finite {A} : pstream A -> Prop :=\n| pNil_fin : Finite pNil\n| pCons_fin : forall a s, Finite s -> Finite (pCons a s).\n\n(* Provide a definition analogous to Finite *)\nCoInductive Infinite {A} : pstream A -> Prop :=.\n\nTheorem pNil_not_Infinite : forall {A:Type}, ~ Infinite (pNil : pstream A).\nAdmitted.\n\nTheorem Finite_not_Infinite : forall {A} (s : pstream A), Finite s -> ~Infinite s.\nAdmitted.\n\nTheorem Not_Finite_Infinite : forall {A} (s : pstream A), ~Finite s -> Infinite s.\nAdmitted.\n\n(* And now we will need similar definitions for (always infinite) streams... *)\nCoInductive stream A : Type :=\n| Cons : A -> stream A -> stream A.\nArguments Cons {A} _ _.\nInfix \"::\" := Cons.\n\nCoInductive stream_eq {A} : stream A -> stream A -> Prop :=\n| Stream_eq : forall h t1 t2,\n    stream_eq t1 t2 -> stream_eq (h::t1) (h::t2).\n\n(* Some standard functions on streams also *)\nDefinition head {A} (s : stream A) : A :=\n  match s with\n  | h::t => h\n  end.\n\nDefinition tail {A} (s : stream A) : stream A :=\n  match s with\n  | h::t => t\n  end.\n\n(* repeatedly apply a function [n] times *)\nFixpoint iterate {A} (n : nat) (f : A -> A) (a : A) : A :=\n  match n with\n  | O => a\n  | S n' => f (iterate n' f a)\n  end.\n\nDefinition tail_n {A} (n : nat) (s : stream A) : stream A := iterate n tail s.\n\nDefinition head_n {A} (n : nat) (s : stream A) : A := head (tail_n n s).\n\n(* For example, this holds *)\nTheorem tail_n_plus_m :\n  forall {A} (n m : nat) (s : stream A), tail_n n (tail_n m s) = tail_n (n + m) s.\nAdmitted.\n\n(* Some more examples of inductive and co-inductive definitions,\n   from the standard library *)\nInductive Exists {A} (s : stream A) (P : stream A -> Prop) : Prop :=\n| Here : P s -> Exists s P\n| Further : Exists (tail s) P -> Exists s P.\n\n(* Provide a definition analogous to Exists *)\nCoInductive ForAll {A} (s : stream A) (P : stream A -> Prop) : Prop :=.\n\n(* A simple thm *)\nTheorem ForAll_tail : forall {A} n (P : stream A -> Prop) (s : stream A),\n  ForAll s P -> ForAll (tail_n n s) P.\nAdmitted.\n\n(* But, of course, the analogous thm for Exists does not hold.\n   I only found ugly/long proofs for this... *)\nTheorem Exists_tail : ~(forall {A} n (P : stream A -> Prop) (s : stream A),\n                       Exists s P -> Exists (tail_n n s) P).\nAdmitted.\n\n(* Let's prove things about this class of streams %[%#[#an element repeated indefinitely#]#%]% instead of general thms *)\nCoFixpoint repeat n : stream nat := n::(repeat n).\n\nTheorem tail_n_zeroes : forall n, stream_eq (tail (repeat n)) (repeat n).\nAdmitted.\n\nTheorem iterate_n_tail_repeat : forall n m, stream_eq (tail_n n (repeat m))\n                                                      (repeat m).\nAdmitted.\n\n(* Mutual recursion, nothing exciting *)\nCoFixpoint flip1 : stream nat := 1::flip0\nwith       flip0 := 0::flip1.\n\nTheorem tail_flip1_flip0_eq : stream_eq (tail flip1) flip0.\nAdmitted.\n\n(** Infinite trees **)\n\n(* T(h)ree exercises stolen from https://www.eecs.northwestern.edu/~robby/courses/395-495-2013-fall/HW6.v: *)\n\n(* Define the coinductive types representing the following infinite data structures: *)\n\n(* 1. Infinite binary trees *)\n\n(* 2. Infinitely branching infinite trees (i.e. infinitely wide and infinitely deep) *)\n\n(* 3. Finitely and infinitely branching infinite trees (i.e. finitely or infinitely wide and infinitely deep) *)\n\n(** Back to streams again: Bisimilarity **)\nDefinition Bisimulation {A} (R : stream A -> stream A -> Prop) :=\n    (forall s1 s2, R s1 s2 -> head s1 = head s2) /\\\n    (forall s1 s2, R s1 s2 -> R (tail s1) (tail s2)).\n\nTheorem stream_eq_bisim : forall {A}, @Bisimulation A stream_eq /\\ forall (R : stream A -> stream A -> Prop),\n    Bisimulation R ->\n    forall s1 s2, R s1 s2 -> stream_eq s1 s2.\nProof.\n  (* Same proof as in the \"lecture\" *)\n  split.\n  split; destruct 1; trivial.\n  intros R [H_head H_tail]. cofix. destruct s1, s2. intros.\n  generalize (H_head _ _ H). intros. simpl in H0. rewrite H0. constructor.\n  apply stream_eq_bisim.\n  apply (H_tail _ _ H). Qed.\n\n(* Same as above, but use stream_eq_bisim here *)\nTheorem tail_flip1_flip0_eq' : stream_eq (tail flip1) flip0.\nAdmitted.\n\n(* I suggest using stream_eq_bisim again *)\nTheorem heads_iff_eq : forall {A} (s1 s2 : stream A),\n    (forall (n : nat), head_n n s1 = head_n n s2) <-> stream_eq s1 s2.\nAdmitted.\n\n(** Optional: Do the co-inductive big-step operational semantics for an imperative language optimization example from 5.3 in CPDT in SF-style instead of CPDT-style. **)\n\n(** Even more exercise in case you're interested: In the coinduction chapter in Coq'Art there are some exercises. Consider especially 13.9 and 13.10, for some non-stream examples. **)\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/4/ex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7029133908874831}}
{"text": "Check (3,4=1):nat*Prop.\nCheck (fun x:nat => x=3).\n\nCheck (forall x:nat, x<3 \\/ (exists y:nat, x = y + 3)).\n\nCheck (let f := fun x:nat => (x*3,x) in f).\n\nLocate \"_ <= _\".\n\nCheck and.\n\nCheck and True False.\n\nLocate \"\\/\".\n\nCompute let f := fun x:nat => (x*x,x) in f 30.\n\nCompute fun x:nat => (x*x).\n\nDefinition example1 := fun x:nat => x*x.\nCheck example1.\nCompute example1 3.\n\nPrint example1.\n\nRequire Import Bool.\n\nCompute if true then 2 else 5.\n\nSearchPattern bool.\n\nRequire Import Arith.\n\nDefinition is_zero (n:nat) := \n match n with \n  0 => true\n| S p => false\nend.\n\nCompute is_zero 0.\n\nPrint pred.\n\nCompute pred 12.\n\nDefinition get_pred(n:nat) :=\n match n with \n  0 => n\n| S u => u\n end.\n\nCompute get_pred 12.\n\nDefinition get_succ(n:nat) :=\n match n with\n  0 => S n\n| S u => S (S u)\n end.\n\nCompute get_succ 0.\n\n\n\n\n\n\n\n\n\n(*do this question at the end of 2.5 section\nCheck let f := fun a::b::nil => (a+b+c+d+e+f) in f. \n  *)\n", "meta": {"author": "shauray8", "repo": "coq-theorems", "sha": "f82c2ff299dd111cae5edc59991f4f3a5c646b84", "save_path": "github-repos/coq/shauray8-coq-theorems", "path": "github-repos/coq/shauray8-coq-theorems/coq-theorems-f82c2ff299dd111cae5edc59991f4f3a5c646b84/learn_coq/learn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7029133884998974}}
{"text": "(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Binary relations                                                        *\n**************************************************************************)\n\nSet Implicit Arguments.\nFrom TLC Require Import LibTactics LibLogic LibBool LibLogic LibProd LibSum.\nFrom TLC Require Export LibOperation.\n\n\n(* ********************************************************************** *)\n(** * Type of binary relations *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Type of endorelation, i.e. homogeneous binary relations *)\n\n(* --TODO: what would be a better name for [binary]? *)\n\nDefinition binary (A : Type) := A -> A -> Prop.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inhabited *)\n\n#[global]\nInstance Inhab_binary : forall A, Inhab (binary A).\nProof using. intros. apply (Inhab_of_val (fun _ _ => True)). Qed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Extensionality *)\n\nLemma binary_ext : forall A (R1 R2:binary A),\n  (forall x y, R1 x y <-> R2 x y) ->\n  R1 = R2.\nProof using. extens*. Qed.\n\n#[global]\nInstance Extensionality_binary : forall A,\n  Extensionality (binary A).\nProof using. intros. apply (Extensionality_make (@binary_ext A)). Defined.\n\n\n(* ********************************************************************** *)\n(** * Properties of relations *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexivity *)\n\nDefinition refl A (R:binary A) :=\n  forall x, R x x.\n\nSection Refl.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma refl_inv : forall x y R,\n  refl R ->\n  x = y ->\n  R x y.\nProof using. intros_all. subst~. Qed.\n\nEnd Refl.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Irreflexivity *)\n\nDefinition irrefl A (R:binary A) :=\n  forall x, ~ (R x x).\n\nSection Irrefl.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma irrefl_inv : forall x R,\n  irrefl R ->\n  R x x ->\n  False.\nProof using. introv H P. apply* H. Qed.\n\nLemma irrefl_eq_forall_neq : forall R,\n  irrefl R = (forall x y, R x y -> x <> y).\nProof using.\n  unfold irrefl. extens. iff M.\n  { introv H E. subst*. }\n  { autos*. }\nQed.\n\nLemma irrefl_inv_neq : forall x y R,\n  irrefl R ->\n  R x y ->\n  x <> y.\nProof using. introv H M. rewrite* irrefl_eq_forall_neq in H. Qed.\n\nEnd Irrefl.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Symmetry *)\n\nDefinition sym A (R:binary A) :=\n  forall x y, R x y -> R y x.\n\nSection Sym.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma sym_inv : forall x y R,\n  sym R ->\n  R x y ->\n  R y x.\nProof using. introv Sy R1. apply* Sy. Qed.\n\nLemma sym_inv_eq : forall x y R,\n  sym R ->\n  R x y = R y x.\nProof using. unfold sym. extens*. Qed.\n\nLemma sym_eq_forall_eq : forall R,\n  sym R = (forall x y, R x y = R y x).\nProof using.\n  unfold sym. extens. iff M.\n  { extens*. }\n  { intros. rewrite* M. }\nQed.\n\nEnd Sym.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Asymmetry *)\n\nDefinition asym A (R:binary A) :=\n  forall x y, R x y -> ~ R y x.\n\nSection Asym.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma asym_eq_forall_false : forall R,\n  asym R = (forall x y, R x y -> R y x -> False).\nProof using. unfold asym. extens*. Qed.\n\nLemma asym_inv : forall x y R,\n  asym R ->\n  R x y ->\n  R y x ->\n  False.\nProof using. introv H M1 M2. apply* H. Qed.\n\nEnd Asym.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Antisymmetry *)\n\nDefinition antisym A (R:binary A) :=\n  forall x y, R x y -> R y x -> x = y.\n\nSection Antisym.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma antisym_eq_forall_eq : forall R,\n  antisym R = (forall x y, R x y -> R y x -> x = y).\nProof using. unfold antisym. extens*. Qed.\n\nLemma antisym_inv : forall x y R,\n  antisym R ->\n  R x y ->\n  R y x ->\n  x <> y ->\n  False.\nProof using. intros_all*. Qed.\n\nEnd Antisym.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Antisymmetry with respect to an equivalence relation *)\n\nDefinition antisym_wrt A (E:binary A) R :=\n  forall x y, R x y -> R y x -> E x y.\n\n(* --LATER: lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Transitivity *)\n\nDefinition trans A (R:binary A) :=\n  forall y x z, R x y -> R y z -> R x z.\n\nSection Trans.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma trans_eq_forall_impl : forall R,\n  trans R = (forall y x z, R x y -> R y z -> R x z).\nProof using. unfold trans. extens*. Qed.\n\nLemma trans_inv : forall y x z R,\n  trans R ->\n  R x y ->\n  R y z ->\n  R x z.\nProof using. introv Tr R1 R2. apply* Tr. Qed.\n\nLemma trans_inv_swap : forall y x z R,\n  trans R ->\n  R y z ->\n  R x y ->\n  R x z.\nProof using. introv Tr R1 R2. apply* Tr. Qed.\n\n(** [trans] + [sym] *)\n\nDefinition trans_sym_ll := trans_inv.\n\nLemma trans_sym_lr : forall y x z R,\n  trans R ->\n  sym R ->\n  R x y ->\n  R z y ->\n  R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_rr : forall y x z R,\n  trans R ->\n  sym R ->\n  R y x ->\n  R z y ->\n  R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nLemma trans_sym_rl : forall y x z R,\n  trans R ->\n  sym R ->\n  R y x ->\n  R y z ->\n  R x z.\nProof using. introv Tr Sy R1 R2. apply* Tr. Qed.\n\nEnd Trans.\n\nArguments trans_inv [A] y [x] [z] [R].\nArguments trans_inv_swap [A] y [x] [z] [R].\nArguments trans_sym_rr [A] y [x] [z] [R].\nArguments trans_sym_lr [A] y [x] [z] [R].\nArguments trans_sym_rl [A] y [x] [z] [R].\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Equivalence relation *)\n\nRecord equiv A (R:binary A) :=\n { equiv_refl : refl R;\n   equiv_sym : sym R;\n   equiv_trans : trans R }.\n\nSection Equiv.\nVariables (A : Type).\nImplicit Types R : binary A.\n\n(* --LATER: lemmas *)\n\nEnd Equiv.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion *)\n\n(* --LATER: see also typeclass [incl] *)\n\nDefinition rel_incl A B (R1 R2:A->B->Prop) :=\n  forall x y, R1 x y -> R2 x y.\n\nSection Incl.\nVariables (A B : Type).\nImplicit Types R : A->B->Prop.\n\nLemma rel_incl_eq_forall_impl : forall R1 R2,\n  rel_incl R1 R2 = (forall x y, R1 x y -> R2 x y).\nProof using. auto. Qed.\n\nLemma refl_rel_incl :\n  refl (@rel_incl A B).\n  (* forall (R:A->B->Prop), rel_incl R R *)\nProof using. unfolds refl, rel_incl. autos*. Qed.\n\nLemma refl_rel_incl' : forall R,\n  rel_incl R R.\nProof using. intros. applys refl_rel_incl. Qed.\n\nHint Resolve refl_rel_incl refl_rel_incl'.\n\nLemma antisym_rel_incl :\n  antisym (@rel_incl A B).\n  (* forall R1 R2, rel_incl R1 R2 -> rel_incl R2 R1 -> R1 = R2. *)\nProof using. unfolds rel_incl. extens*. Qed.\n  (* See also extensionality_pred_2 from LibEqual *)\n\nLemma trans_rel_incl :\n  trans (@rel_incl A B).\nProof using. unfold trans, rel_incl. autos*. Qed.\n  (* forall R1 R2 R3, rel_incl R1 R2 -> rel_incl R2 R3 ->  rel_incl R1 R3. *)\n\nEnd Incl.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Totality *)\n\nDefinition total A (R:binary A) :=\n  forall x y, R x y \\/ R y x.\n\nSection Total.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma total_eq_forall_or : forall R,\n  total R = (forall x y, R x y \\/ R y x).\nProof using. auto. Qed.\n\nLemma total_inv : forall x y R,\n  total R ->\n  R x y \\/ R y x.\nProof using. introv H. apply* H. Qed.\n\nLemma total_inv_not_l : forall x y R,\n  total R ->\n  ~ R x y ->\n  R y x.\nProof using. introv H N. destruct* (H x y). Qed.\n\nLemma total_inv_not_r : forall x y R,\n  total R ->\n  ~ R y x ->\n  R x y.\nProof using. introv H N. destruct* (H x y). Qed.\n\nEnd Total.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Trichotomy *)\n\nInductive trichotomy A (R:binary A) : binary A :=\n  | trichotomy_left : forall x y,\n      R x y ->\n      x <> y ->\n      ~ R y x ->\n      trichotomy R x y\n  | trichotomy_eq : forall x,\n      ~ R x x ->\n      trichotomy R x x\n  | trichotomy_right : forall x y,\n      ~ R x y ->\n      x <> y ->\n      R y x ->\n      trichotomy R x y.\n\nDefinition trichotomous A (R:binary A) :=\n  forall x y, trichotomy R x y.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Definedness *)\n\nDefinition defined A B (R:A->B->Prop) :=\n  forall x, exists y, R x y.\n\nSection Defined.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma total_eq_forall_exists : forall R,\n  defined R = (forall x, exists y, R x y).\nProof using. auto. Qed.\n\nLemma defined_inv : forall x R,\n  defined R ->\n  exists y, R x y.\nProof using. introv H. apply* H. Qed.\n\nLemma defined_inv_not : forall x R,\n  defined R ->\n  (forall y, ~ R x y) ->\n  False.\nProof using. introv H N. forwards* (?&?): H. Qed.\n\nEnd Defined.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Functionality *)\n\nDefinition functional A B (R:A->B->Prop) :=\n  forall x y z, R x y -> R x z -> y = z.\n\nSection Functional.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma functional_eq_forall_eq : forall R,\n  functional R = (forall x y z, R x y -> R x z -> y = z).\nProof using. auto. Qed.\n\nLemma functional_inv : forall x z y R,\n  functional R ->\n  R x y ->\n  R x z ->\n  y = z.\nProof using. introv H N1 N2. apply* H. Qed.\n\nEnd Functional.\n\n(* --TODO: define a tactic \"functional_exploit R\" that looks for two distinct\n   assumptions in the goal of the form [R ?x ?y] and produces [functional R]\n   as subgoal, and provides the equality [?y1 = ?y2]. *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Criteria for equality *)\n\nSection Equality.\nVariables (A : Type).\nImplicit Types R : binary A.\n\n(** If [R1] is defined, [R2] is functional, and [R1] is a subset of [R2],\n    then [R1] equals [R2]. In that case, [R1] and [R2] represent the graph\n    of a total function. *)\n\nLemma eq_of_incl_defined_functional : forall R1 R2,\n  rel_incl R1 R2 ->\n  defined R1 ->\n  functional R2 ->\n  R1 = R2.\nProof using.\n  introv Hincl Hdef Hfun. extens. intros x y. iff M.\n  { eauto. }\n  { forwards (w'&M1): Hdef x.\n    forwards M2: Hincl M1.\n    forwards: Hfun M M2. subst*. }\nQed.\n\nEnd Equality.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of the equality relation *)\n\n(** These results are not in [LibEqual] because the definitions from\n    [LibRelation] are not yet available from that file. *)\n\nSection Eq.\nVariables (A : Type).\n\nLemma refl_eq :\n  refl (@eq A).\nProof using. intros_all; subst~. Qed.\n\nLemma sym_eq :\n  sym (@eq A).\nProof using. intros_all; subst~. Qed.\n\nLemma trans_eq :\n  trans (@eq A).\nProof using. intros_all; subst~. Qed.\n\nLemma equiv_eq :\n  equiv (@eq A).\nProof using. intros. constructor; intros_all; subst~. Qed.\n\nEnd Eq.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of the equality relation *)\n\n(** These results are not in [LibLogic] because the definitions from\n    [LibRelation] are not yet available from that file.\n    See also [LibOrder] for a package of these properties. *)\n\nSection Pred_incl.\nVariables (A : Type).\n\nLemma refl_pred_incl :\n  refl (@pred_incl A).\nProof using. unfold refl, pred_incl. autos*. Qed.\n\nLemma antisym_pred_incl :\n  antisym (@pred_incl A).\nProof using. unfold antisym, pred_incl. extens*. Qed.\n\nLemma trans_pred_incl :\n  trans (@pred_incl A).\nProof using. unfold trans, pred_incl. autos*. Qed.\n\nEnd Pred_incl.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Properties of the equivalence relation *)\n\n(** These results are not in [LibLogic] because the definitions from\n    [LibRelation] are not yet available from that file.\n    See also [LibOrder] for a package of these properties. *)\n\nSection Iff.\n\nLemma refl_iff :\n  refl iff.\nProof using. unfold refl, iff. autos*. Qed.\n\nLemma antisym_iff :\n  antisym iff.\nProof using. unfold antisym, iff. extens*. Qed.\n\nLemma trans_iff :\n  trans iff.\nProof using. unfold trans, iff. autos*. Qed.\n\nEnd Iff.\n\n\n(* ********************************************************************** *)\n(** * Basic constructions *)\n\n(** LATER: plan to use typeclasses from LibContainer:\n    - empty\n    - single\n    - in\n    - binds\n    - union\n    - inter\n    - incl\n    - disjoint\n    - restrict\n    - remove\n    - dom\n    - img\n*)\n\n(* ---------------------------------------------------------------------- *)\n(** ** The empty relation *)\n\n(* --LATER: see also typeclass [empty] *)\n\nDefinition empty A : binary A :=\n  fun x y => False.\n\nSection Empty.\nVariables (A : Type).\nImplicit Types x y : A.\n\nLemma empty_eq : forall x y,\n  empty x y = False.\nProof using. auto. Qed.\n\nLemma empty_inv : forall x y,\n  empty x y ->\n  False.\nProof using. auto. Qed.\n\nLemma functional_empty :\n  functional (@empty A).\nProof using. unfolds* empty, functional. Qed.\n\nEnd Empty.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Union of two relations  *)\n\n(* --LATER: see also typeclass [union] *)\n\nDefinition union A (R1 R2:binary A) : binary A :=\n  fun x y => R1 x y \\/ R2 x y.\n\nSection Union.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma union_l : forall R1 R2 x y,\n  R1 x y ->\n  union R1 R2 x y.\nProof using. unfold union. eauto. Qed.\n\nLemma union_r : forall R1 R2 x y,\n  R2 x y ->\n  union R1 R2 x y.\nProof using. unfold union. eauto. Qed.\n\nLemma rel_incl_union_l : forall R1 R2,\n  rel_incl R1 (union R1 R2).\nProof using. unfold rel_incl, union. eauto. Qed.\n\nLemma rel_incl_union_r : forall R1 R2,\n  rel_incl R2 (union R1 R2).\nProof using. unfold rel_incl, union. eauto. Qed.\n\nLemma refl_union_l : forall R1 R2,\n  refl R1 ->\n  refl (union R1 R2).\nProof using. unfold refl, union. eauto. Qed.\n\nLemma refl_union_r : forall R1 R2,\n  refl R2 ->\n  refl (union R1 R2).\nProof using. unfold refl, union. eauto. Qed.\n\nLemma comm_union :\n  comm (@union A).\n  (* forall R1 R2, union R1 R2 = union R2 R1. *)\nProof using. unfold union. extens*. Qed.\n\nLemma comm_union_args : forall R1 R2 x y,\n  union R2 R1 x y ->\n  union R1 R2 x y.\nProof using. intros. rewrite~ comm_union. Qed.\n\n(** Union is functional provided disjoint domains *)\nLemma functional_union : forall R1 R2,\n  functional R1 ->\n  functional R2 ->\n  (forall x y z, R1 x y -> R2 x z -> False) ->\n  functional (union R1 R2).\nProof using.\n  intros. unfold union. intros x y z Hxy Hxz.\n  destruct Hxy; destruct Hxz; auto_false*.\nQed.\n\n(* --TODO: generic definition of covariant? *)\nLemma covariant_union : forall R1 R2 S1 S2,\n  rel_incl R1 S1 ->\n  rel_incl R2 S2 ->\n  rel_incl (union R1 R2) (union S1 S2).\nProof using. unfold rel_incl, union. autos*. Qed.\n\nEnd Union.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Intersection of two relations  *)\n\n(* --LATER: see also typeclass [inter] *)\n\nDefinition inter A (R1 R2:binary A) : binary A :=\n  fun x y => R1 x y /\\ R2 x y.\n\n(* --LATER: add lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Complement of a relation *)\n\nDefinition compl A (R:binary A) : binary A :=\n  fun x y => ~ R y x.\n\n(* --LATER: add lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inverse of a relation *)\n\nDefinition inverse A (R:binary A) : binary A :=\n  fun x y => R y x.\n\nSection Inverse.\nVariables (A : Type).\nImplicit Types R : binary A.\n\nLemma inverse_eq_fun : forall R,\n  inverse R = (fun x y => R y x).\nProof using. auto. Qed.\n\nLemma inverse_eq : forall R x y,\n  inverse R x y = R y x.\nProof using. auto. Qed.\n\nLemma injective_inverse :\n  injective (@inverse A).\nProof using.\n  intros R1 R2 E. extens. intros x y.\n  unfolds inverse. rewrite* (fun_eq_2 y x E).\nQed.\n\nLemma inverse_sym : forall R,\n  sym R ->\n  inverse R = R.\nProof using. intros. unfold inverse. extens*. Qed.\n\nLemma inverse_inverse : forall R,\n  inverse (inverse R) = R.\nProof using. extens*. Qed.\n\nLemma inverse_eq_l : forall R2 R1,\n  R1 = inverse R2 ->\n  inverse R1 = R2.\nProof using. intros. apply injective_inverse. rewrite~ inverse_inverse. Qed.\n\nLemma inverse_eq_r : forall R2 R1,\n  inverse R1 = R2 ->\n  R1 = inverse R2.\nProof using. intros. apply injective_inverse. rewrite~ inverse_inverse. Qed.\n\nLemma refl_inverse : forall R,\n  refl R ->\n  refl (inverse R).\nProof using. intros_all. unfolds inverse. auto. Qed.\n\nLemma trans_inverse : forall R,\n  trans R ->\n  trans (inverse R).\nProof using. intros_all. unfolds inverse. eauto. Qed.\n\nLemma antisym_inverse : forall R,\n  antisym R ->\n  antisym (inverse R).\nProof using. intros_all. unfolds inverse. auto. Qed.\n\nLemma antisym_wrt_inverse : forall E R,\n  antisym_wrt E R ->\n  antisym_wrt E (inverse R).\nProof using. intros_all. unfolds inverse. auto. Qed.\n\nLemma asym_inverse : forall R,\n  asym R ->\n  asym (inverse R).\nProof using. intros_all. unfolds inverse. apply* H. Qed.\n\nLemma total_inverse : forall R,\n  total R ->\n  total (inverse R).\nProof using. intros_all. unfolds inverse. auto. Qed.\n\nLemma trichotomous_inverse : forall R,\n  trichotomous R ->\n  trichotomous (inverse R).\nProof using.\n  introv H. intros x y. destruct (H x y).\n  apply~ trichotomy_right.\n  apply~ trichotomy_eq.\n  apply~ trichotomy_left.\nQed.\n\n(* TODO rename to equiv_inverse *)\nLemma inverse_equiv : forall A (E:binary A),\n  equiv E ->\n  equiv (inverse E).\nProof using.\n  introv Equi. unfold inverse. constructor; intros_all;\n    dintuition eauto.\nQed.\n\nLemma inverse_union : forall R1 R2,\n  inverse (union R1 R2) = union (inverse R1) (inverse R2).\nProof using.\n  unfold inverse, union. constructor; intros_all;\n    dintuition eauto.\nQed.\n\n\nEnd Inverse.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** [preimage] *)\n\n(** Preimage, a.k.a. inverse image *)\n\nDefinition rel_preimage (A B:Type) (R:binary B) (f:A->B) : binary A :=\n  fun x y => R (f x) (f y).\n\n(* --TODO: lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** [rel_seq] *)\n\n(** Composition of two relations, usually written [R1; R2]. *)\n\nDefinition rel_seq (A B C:Type) (R1:A->B->Prop) (R2:B->C->Prop) : A->C->Prop :=\n  fun x z => exists y, R1 x y /\\ R2 y z.\n\n(** A relation [R] is functional if and only if [inverse R] composed\n    with [R] is a subset of the diagonal relation [eq]. *)\n\nLemma functional_eq_seq_inverse_incl_eq : forall A (R:binary A),\n  functional R = rel_incl (rel_seq (inverse R) R) eq.\nProof using.\n  unfold functional, rel_incl, rel_seq, inverse. extens. iff M; jauto.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Turning a function into a relation. *)\n\nDefinition rel_fun A B (f:A->B) :=\n  fun x y => (y = f x).\n\nSection Rel_fun.\nVariables (A : Type).\nImplicit Types R : binary A.\n\n(* --LATER: properties of [rel_fun] *)\n\nEnd Rel_fun.\n\n\n\n(* ********************************************************************** *)\n(** * Products *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Pointwise product *)\n\nDefinition prod2 (A1 A2:Type)\n  (R1:binary A1) (R2:binary A2)\n   : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => match p1,p2 with (x1,x2),(y1,y2) =>\n    R1 x1 y1 /\\ R2 x2 y2 end.\n\nDefinition prod3 (A1 A2 A3:Type)\n  (R1:binary A1) (R2:binary A2) (R3:binary A3)\n   : binary (A1*A2*A3) :=\n  prod2 (prod2 R1 R2) R3.\n\nDefinition prod4 (A1 A2 A3 A4:Type)\n  (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4)\n   : binary (A1*A2*A3*A4) :=\n  prod2 (prod3 R1 R2 R3) R4.\n\n(** Tactics *)\n\nTactic Notation \"unfold_prod\" :=\n  unfold prod4, prod3, prod2.\nTactic Notation \"unfolds_prod\" :=\n  unfold prod4, prod3, prod2 in *.\n\n(** Equivalence *)\n\nLemma prod2_equiv : forall A1 A2 (E1:binary A1) (E2:binary A2),\n  equiv E1 ->\n  equiv E2 ->\n  equiv (prod2 E1 E2).\nProof using.\n  introv [R1 S1 T1] [R2 S2 T2]. constructor.\n  { intros [x1 x2]. simple*. }\n  { intros [x1 x2] [y1 y2]. simple*. }\n  { intros [x1 x2] [y1 y2] [z1 z2]. simple*. }\nQed.\n\n(* --LATER: other lemmas *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Lexicographical product *)\n\nDefinition lexico2 {A1 A2} (R1:binary A1) (R2:binary A2)\n   : binary (A1*A2) :=\n  fun p1 p2 : A1*A2 => let (x1,x2) := p1 in let (y1,y2) := p2 in\n  (R1 x1 y1) \\/ (x1 = y1) /\\ (R2 x2 y2).\n\nDefinition lexico3 {A1 A2 A3}\n   (R1:binary A1) (R2:binary A2) (R3:binary A3) : binary (A1*A2*A3) :=\n  lexico2 (lexico2 R1 R2) R3.\n\nDefinition lexico4 {A1 A2 A3 A4}\n   (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4)\n   : binary (A1*A2*A3*A4) :=\n  lexico2 (lexico3 R1 R2 R3) R4.\n\n(** Tactics *)\n\nTactic Notation \"unfold_lexico\" :=\n  unfold lexico4, lexico3, lexico2.\nTactic Notation \"unfolds_lexico\" :=\n  unfold lexico4, lexico3, lexico2 in *.\n\n(** Elimination *)\n\nSection Lexico.\nVariables (A1 A2 A3 A4:Type).\nVariables (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4).\n\nLemma lexico2_1 : forall x1 x2 y1 y2,\n  R1 x1 y1 ->\n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof using. intros. left~. Qed.\n\nLemma lexico2_2 : forall x1 x2 y1 y2,\n  x1 = y1 ->\n  R2 x2 y2 ->\n  lexico2 R1 R2 (x1,x2) (y1,y2).\nProof using. intros. right~. Qed.\n\nLemma lexico3_1 : forall x1 x2 x3 y1 y2 y3,\n  R1 x1 y1 ->\n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intros. left. left~. Qed.\n\nLemma lexico3_2 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 ->\n  R2 x2 y2 ->\n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intro. left. right~. Qed.\n\nLemma lexico3_3 : forall x1 x2 x3 y1 y2 y3,\n  x1 = y1 ->\n  x2 = y2 ->\n  R3 x3 y3 ->\n  lexico3 R1 R2 R3 (x1,x2,x3) (y1,y2,y3).\nProof using. intros. right~. Qed.\n\nLemma lexico4_1 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  R1 x1 y1 ->\n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. left. left~. Qed.\n\nLemma lexico4_2 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 ->\n  R2 x2 y2 ->\n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. left. right~. Qed.\n\nLemma lexico4_3 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 ->\n  x2 = y2 ->\n  R3 x3 y3 ->\n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. left. right~. Qed.\n\nLemma lexico4_4 : forall x1 x2 x3 x4 y1 y2 y3 y4,\n  x1 = y1 ->\n  x2 = y2 ->\n  x3 = y3 ->\n  R4 x4 y4 ->\n  lexico4 R1 R2 R3 R4 (x1,x2,x3,x4) (y1,y2,y3,y4).\nProof using. intros. right~. Qed.\n\nEnd Lexico.\n\n(** Transitivity *)\n\nLemma trans_lexico2 : forall A1 A2\n   (R1:binary A1) (R2:binary A2),\n  trans R1 ->\n  trans R2 ->\n  trans (lexico2 R1 R2).\nProof using.\n  introv Tr1 Tr2. intros [x1 x2] [y1 y2] [z1 z2] Rxy Ryz.\n  simpls. destruct Rxy as [L1|[Eq1 L1]];\n   destruct Ryz as [M2|[Eq2 M2]]; subst*.\nQed.\n\nLemma trans_lexico3 : forall A1 A2 A3\n   (R1:binary A1) (R2:binary A2) (R3:binary A3),\n  trans R1 ->\n  trans R2 ->\n  trans R3 ->\n  trans (lexico3 R1 R2 R3).\nProof using.\n  introv Tr1 Tr2 Tr3. applys~ trans_lexico2. applys~ trans_lexico2.\nQed.\n\nLemma trans_lexico4 : forall A1 A2 A3 A4\n   (R1:binary A1) (R2:binary A2) (R3:binary A3) (R4:binary A4),\n  trans R1 ->\n  trans R2 ->\n  trans R3 ->\n  trans R4 ->\n  trans (lexico4 R1 R2 R3 R4).\nProof using.\n  introv Tr1 Tr2 Tr3. applys~ trans_lexico3. applys~ trans_lexico2.\nQed.\n\n(** Inclusion *)\n\nLemma rel_incl_lexico2 : forall A1 A2\n   (R1 R1':binary A1) (R2 R2':binary A2),\n  rel_incl R1 R1' ->\n  rel_incl R2 R2' ->\n  rel_incl (lexico2 R1 R2) (lexico2 R1' R2').\nProof using.\n  introv I1 I2. intros [x1 x2] [y1 y2] [H1|[H1 H2]].\n  { left~. } { subst. right~. }\nQed.\n\n(* --LATER: other lemmas *)\n\n\n\n(* ********************************************************************** *)\n(** * Closures *)\n\n(* --LATER: more lemmas about union and inter *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexive closure  *)\n\nInductive rclosure A (R:binary A) : binary A :=\n  | rclosure_once : forall x y,\n      R x y ->\n      rclosure R x y\n  | rclosure_refl : forall x,\n      rclosure R x x.\n\nSection Rclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rclosure.\n\n(** Equivalent definition *)\n\nLemma rclosure_eq_fun : forall R,\n  rclosure R = (fun x y => R x y \\/ x = y).\nProof using. extens. iff M; destruct M; subst*. Qed.\n\nLemma rclosure_eq : forall R x y,\n  rclosure R x y = (R x y \\/ x = y).\nProof using. extens. iff M; destruct M; subst*. Qed.\n\nLemma rclosure_inv : forall R x y,\n  rclosure R x y ->\n  R x y \\/ x = y.\nProof using. introv M; rewrite* rclosure_eq in M. Qed.\n\n(** Properties *)\n\nLemma refl_rclosure : forall R,\n  refl (rclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_rclosure : forall R,\n  sym R ->\n  sym (rclosure R).\nProof using. unfolds sym. introv M N. destruct* N. Qed.\n\nLemma antisym_rclosure : forall R,\n  antisym R ->\n  antisym (rclosure R).\nProof using.\n  unfolds antisym. introv M N1 N2.\n  destruct N1; destruct N2; subst*.\nQed.\n\nLemma antisym_wrt_rclosure : forall E R,\n  antisym_wrt E R ->\n  antisym_wrt (rclosure E) (rclosure R).\nProof using.\n  unfolds antisym_wrt. introv M N1 N2.\n  destruct N1; destruct N2; subst*.\nQed.\n\nLemma trans_rclosure : forall R,\n  trans R ->\n  trans (rclosure R).\nProof using.\n  unfolds trans. introv H M1 M2.\n  destruct M1; destruct M2; subst*.\nQed.\n\nLemma total_rclosure : forall R,\n  total R ->\n  total (rclosure R).\nProof using.\n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma rclosure_eq_of_refl : forall R,\n  refl R ->\n  rclosure R = R.\nProof using.\n  unfolds refl. introv H. extens. iff M.\n  { destruct M; subst*. } { auto. }\nQed.\n\nLemma rclosure_inverse_eq : forall R,\n  rclosure (inverse R) = inverse (rclosure R).\nProof using. unfold inverse. extens. iff M; destruct* M. Qed.\n\n(** Constructors *)\n\n(** -- TODO: rename to\n   rclosure_of_rclosure_step\n   rclosure_of_step_rclosure\n   trans_inv_rclosure_step\n   trans_inv_step_rclosure *)\n\nLemma rclosure_trans_l : forall y x z R,\n  trans R ->\n  rclosure R x y ->\n  R y z ->\n  rclosure R x z.\nProof using. introv T M N. rewrite rclosure_eq in *. destruct M; subst*. Qed.\n\nLemma rclosure_trans_r : forall y x z R,\n  trans R ->\n  R x y ->\n  rclosure R y z ->\n  rclosure R x z.\nProof using. introv T M N. rewrite rclosure_eq in *. destruct N; subst*. Qed.\n\nLemma trans_rclosure_l : forall y x z R,\n  trans R ->\n  rclosure R x y ->\n  R y z ->\n  R x z.\nProof using. introv T M H. rewrite rclosure_eq in *. destruct M; subst*. Qed.\n\nLemma trans_rclosure_r : forall y x z R,\n  trans R ->\n  R x y ->\n  rclosure R y z ->\n  R x z.\nProof using. introv T M N. rewrite rclosure_eq in *. destruct N; subst*. Qed.\n\n(** Negation *)\n\nLemma not_rclosure_inv : forall R x y,\n  ~ rclosure R x y ->\n  ~ R x y /\\ x <> y.\nProof using. introv M. rewrite* rclosure_eq in M. Qed.\n\nLemma not_rclosure_inv_rel : forall R x y,\n  ~ rclosure R x y ->\n  ~ R x y.\nProof using. introv M. rewrite* rclosure_eq in M. Qed.\n\nLemma not_rclosure_inv_neq : forall R x y,\n  ~ rclosure R x y ->\n  x <> y.\nProof using. introv M. rewrite* rclosure_eq in M. Qed.\n\n(** Inclusions *)\n\nLemma rel_incl_rclosure : forall R,\n  rel_incl R (rclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma rclosure_of_rel : forall R x y,\n  R x y ->\n  rclosure R x y.\nProof using. intros. applys* rel_incl_rclosure. Qed.\n\nLemma covariant_rclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (rclosure R1) (rclosure R2).\nProof using. introv H M. destruct* M. Qed.\n\nLemma rel_incl_rclosure_rclosure : forall R1 R2,\n  rel_incl R1 (rclosure R2) ->\n  rel_incl (rclosure R1) (rclosure R2).\nProof using. introv H M. destruct* M. Qed.\n\nEnd Rclosure.\n\n#[global]\nHint Constructors rclosure : rclosure.\n(* --LATER: here and later, add more hints *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Symmetric closure  *)\n\nInductive sclosure A (R:binary A) : binary A :=\n  | sclosure_once : forall x y,\n      R x y ->\n      sclosure R x y\n  | sclosure_sym : forall x y,\n      sclosure R y x ->\n      sclosure R x y.\n\nSection Sclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors sclosure.\n\n(** Equivalent definition *)\n\nLemma sclosure_eq : forall R x y,\n  sclosure R x y = (R x y \\/ R y x).\nProof using.\n  extens. iff M.\n  { induction* M. }\n  { destruct M; subst*. }\nQed.\n\nLemma sclosure_inv : forall R x y,\n  sclosure R x y ->\n  R x y \\/ R y x.\nProof using. introv M; rewrite* sclosure_eq in M. Qed.\n\n(** Properties *)\n\nLemma refl_sclosure : forall R,\n  refl R ->\n  refl (sclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_sclosure : forall R,\n  sym (sclosure R).\nProof using. unfolds sym. introv N. destruct* N. Qed.\n\nLemma total_sclosure : forall R,\n  total R ->\n  total (sclosure R).\nProof using.\n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma sclosure_eq_of_sym : forall R,\n  sym R ->\n  sclosure R = R.\nProof using.\n  unfolds sym. introv H. extens. intros. rewrite sclosure_eq.\n  iff M. { destruct M; subst*. } { auto. }\nQed.\n\nLemma sclosure_inverse_eq : forall R,\n  sclosure (inverse R) = sclosure R.\nProof using.\n  unfolds inverse. extens. intros. do 2 rewrite sclosure_eq. autos*.\nQed.\n\n(** Negation *)\n\nLemma not_sclosure_inv : forall R x y,\n  ~ sclosure R x y ->\n  ~ R x y /\\ ~ R y x.\nProof using. introv M. rewrite* sclosure_eq in M. Qed.\n\nLemma not_sclosure_inv_l : forall R x y,\n  ~ sclosure R x y ->\n  R x y ->\n  False.\nProof using. introv M. rewrite* sclosure_eq in M. Qed.\n\nLemma not_sclosure_inv_r : forall R x y,\n  ~ sclosure R x y ->\n  R y x ->\n  False.\nProof using. introv M. rewrite* sclosure_eq in M. Qed.\n\n(** Inclusions *)\n\nLemma rel_incl_sclosure : forall R,\n  rel_incl R (sclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma rel_incl_inverse_sclosure : forall R,\n  rel_incl (inverse R) (sclosure R).\nProof using. unfolds* rel_incl, inverse. Qed.\n\nLemma covariant_sclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (sclosure R1) (sclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_sclosure_sclosure : forall R1 R2,\n  rel_incl R1 (sclosure R2) ->\n  rel_incl (sclosure R1) (sclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nEnd Sclosure.\n\n#[global]\nHint Constructors sclosure : sclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexive-symmetric closure  *)\n\nInductive rsclosure A (R:binary A) : binary A :=\n  | rsclosure_once : forall x y,\n      R x y ->\n      rsclosure R x y\n  | rsclosure_refl : forall x,\n      rsclosure R x x\n  | rsclosure_sym : forall x y,\n      rsclosure R x y ->\n      rsclosure R y x.\n\nSection Rsclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rsclosure.\n\n(** Equivalent definition *)\n\nLemma rsclosure_eq : forall R x y,\n  rsclosure R x y = (R x y \\/ R y x \\/ x = y).\nProof using.\n  extens. iff M.\n  { induction* M. }\n  { destruct M as [M|[M|M]]; subst*. }\nQed.\n\nLemma rsclosure_inv : forall R x y,\n  rsclosure R x y ->\n  R x y \\/ R y x \\/ x = y.\nProof using. introv M; rewrite* rsclosure_eq in M. Qed.\n\n(** Properties *)\n\nLemma refl_rsclosure : forall R,\n  refl (rsclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_rsclosure : forall R,\n  sym (rsclosure R).\nProof using. unfolds sym. introv N. destruct* N. Qed.\n\nLemma total_rsclosure : forall R,\n  total R ->\n  total (rsclosure R).\nProof using.\n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma rsclosure_inverse_eq : forall R,\n  rsclosure (inverse R) = rsclosure R.\nProof using.\n  unfold inverse. extens. intros. do 2 rewrite rsclosure_eq. autos*.\nQed.\n\n(** Negation *)\n\nLemma not_rsclosure_inv : forall R x y,\n  ~ rsclosure R x y ->\n  ~ R x y /\\ ~ R y x /\\ ~ x = y.\nProof using. introv M. rewrite* rsclosure_eq in M. Qed.\n\nLemma not_rsclosure_inv_l : forall R x y,\n  ~ rsclosure R x y ->\n  R x y ->\n  False.\nProof using. introv M. rewrite* rsclosure_eq in M. Qed.\n\nLemma not_rsclosure_inv_r : forall R x y,\n  ~ rsclosure R x y ->\n  R y x ->\n  False.\nProof using. introv M. rewrite* rsclosure_eq in M. Qed.\n\nLemma not_rsclosure_inv_neq : forall R x y,\n  ~ rsclosure R x y ->\n  x <> y.\nProof using. introv M. rewrite* rsclosure_eq in M. Qed.\n\n(** Inclusions *)\n\nLemma rel_incl_rsclosure : forall R,\n  rel_incl R (rsclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma rel_incl_inverse_rsclosure : forall R,\n  rel_incl (inverse R) (rsclosure R).\nProof using. unfolds* rel_incl, inverse. Qed.\n\nLemma covariant_rsclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (rsclosure R1) (rsclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_rsclosure_rsclosure : forall R1 R2,\n  rel_incl R1 (rsclosure R2) ->\n  rel_incl (rsclosure R1) (rsclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nEnd Rsclosure.\n\n#[global]\nHint Constructors rsclosure : rsclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Transitive closure ( R+ ), defined as [R \\o R*] *)\n\nInductive tclosure A (R:binary A) : binary A :=\n  | tclosure_once : forall x y,\n      R x y ->\n      tclosure R x y\n  | tclosure_trans : forall y x z,\n      tclosure R x y ->\n      tclosure R y z ->\n      tclosure R x z.\n\nSection Tclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors tclosure.\n\n(** Properties *)\n\nLemma refl_tclosure : forall R,\n  refl R ->\n  refl (tclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_tclosure : forall R,\n  sym R ->\n  sym (tclosure R).\nProof using. unfolds sym. introv H N. induction* N. Qed.\n\nLemma trans_tclosure : forall R,\n  trans (tclosure R).\nProof using. unfolds* trans. Qed.\n\nLemma total_tclosure : forall R,\n  total R ->\n  total (tclosure R).\nProof using.\n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma tclosure_eq_of_trans : forall R,\n  trans R ->\n  tclosure R = R.\nProof using.\n  unfolds trans. introv H. extens. iff M.\n  { induction M; subst*. }\n  { auto. }\nQed.\n\nLemma tclosure_inverse_eq : forall R,\n  tclosure (inverse R) = inverse (tclosure R).\nProof using.\n  unfolds inverse. extens. intros x y. iff M; induction* M.\nQed.\n\n(** Constructors *)\n\nLemma tclosure_l : forall R y x z,\n  R x y ->\n  tclosure R y z ->\n  tclosure R x z.\nProof using. autos*. Qed.\n\nLemma tclosure_r : forall R y x z,\n  tclosure R x y ->\n  R y z ->\n  tclosure R x z.\nProof using. autos*. Qed.\n\n(** Inclusions *)\n\nLemma rel_incl_tclosure : forall R,\n  rel_incl R (tclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma covariant_tclosure : forall A (R1 R2 : binary A),\n  rel_incl R1 R2 ->\n  rel_incl (tclosure R1) (tclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_tclosure_tclosure : forall R1 R2,\n  rel_incl R1 (tclosure R2) ->\n  rel_incl (tclosure R1) (tclosure R2).\nProof using. introv H M. induction* M. Qed.\n\n(** Induction principle with steps at head or tail *)\n\nSection Ind.\n\nInductive tclosure'l A (R:binary A) : binary A :=\n  | tclosure'l_once : forall x y,\n      R x y ->\n      tclosure'l R x y\n  | tclosure'l_step : forall y x z,\n      R x y ->\n      tclosure'l R y z ->\n      tclosure'l R x z.\n\nLemma trans_tclosure'l : forall R,\n  trans (tclosure'l R).\nProof using.\n  Hint Constructors tclosure'l.\n  intros R y x z M1. gen z. induction M1; introv M2; autos*.\nQed.\n\nLemma tclosure_eq_tclosure'l : forall R,\n  tclosure R = tclosure'l R.\n  (* --LATER: tclosure'l = tclosure. *)\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. applys* trans_tclosure'l y. }\n  { induction* M. }\nQed.\n\nLemma tclosure_ind_l : forall R (P : A -> A -> Prop),\n  (forall x y, R x y -> P x y) ->\n  (forall y x z, R x y -> tclosure R y z -> P y z -> P x z) ->\n  (forall x y, tclosure R x y -> P x y).\nProof using.\n  introv H1 H2 M. rewrite tclosure_eq_tclosure'l in *. induction* M.\nQed.\n\nInductive tclosure'r A (R:binary A) : binary A :=\n  | tclosure'r_once : forall x y,\n      R x y ->\n      tclosure'r R x y\n  | tclosure'r_step : forall y x z,\n      tclosure'r R x y ->\n      R y z ->\n      tclosure'r R x z.\n\nLemma trans_tclosure'r : forall R,\n  trans (tclosure'r R).\nProof using.\n  Hint Constructors tclosure'r.\n  intros R y x z M1 M2. gen x. induction M2; introv M1; autos*.\nQed.\n\nLemma tclosure_eq_tclosure'r : forall R,\n  tclosure R = tclosure'r R.\n  (* --LATER: tclosure'l = tclosure. *)\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. applys* trans_tclosure'r y. }\n  { induction* M. }\nQed.\n\nLemma tclosure_ind_r : forall R (P : A -> A -> Prop),\n  (forall x y, R x y -> P x y) ->\n  (forall y x z, tclosure R x y -> P x y -> R y z -> P x z) ->\n  (forall x y, tclosure R x y -> P x y).\nProof using.\n  introv H1 H2 M. rewrite tclosure_eq_tclosure'r in *. induction* M.\nQed.\n\n(* --LATER: can these induction principles be proved directly? *)\n\nEnd Ind.\n\n(** Inversion principle with steps at head or tail *)\n\nLemma tclosure_inv_l : forall R x z,\n  tclosure R x z ->\n  (R x z) \\/ (exists y, R x y /\\ tclosure R y z).\nProof using. intros R. applys* tclosure_ind_l. Qed.\n\nLemma tclosure_inv_r : forall R x z,\n  tclosure R x z ->\n  (R x z) \\/ (exists y, tclosure R x y /\\ R y z).\nProof using. intros R. applys* tclosure_ind_r. Qed.\n\nEnd Tclosure.\n\n#[global]\nHint Resolve tclosure_once tclosure_l tclosure_r\n  : rtclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexive-transitive closure ( R* ) *)\n\nInductive rtclosure A (R:binary A) : binary A :=\n  | rtclosure_once : forall x y,\n      R x y ->\n      rtclosure R x y\n  | rtclosure_refl : forall x,\n      rtclosure R x x\n  | rtclosure_trans : forall y x z,\n      rtclosure R x y ->\n      rtclosure R y z ->\n      rtclosure R x z.\n\nSection Rtclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rtclosure.\n\n(** Properties *)\n\nLemma refl_rtclosure : forall R,\n  refl (rtclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_rtclosure : forall R,\n  sym R ->\n  sym (rtclosure R).\nProof using. unfolds sym. introv M N. induction* N. Qed.\n\nLemma trans_rtclosure : forall R,\n  trans (rtclosure R).\nProof using. unfolds* trans. Qed.\n\nLemma total_rtclosure : forall R,\n  total R ->\n  total (rtclosure R).\nProof using.\n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma tclosure_eq_of_refl_trans : forall R,\n  refl R ->\n  trans R ->\n  rtclosure R = R.\nProof using.\n  unfolds refl, trans. introv H1 H2. extens. iff M.\n  { induction M; subst*. }\n  { autos*. }\nQed.\n\nLemma rtclosure_inverse_eq : forall R,\n  rtclosure (inverse R) = inverse (rtclosure R).\nProof using. unfold inverse. extens. iff M; induction* M. Qed.\n\n(** Constructors *)\n\nLemma rtclosure_l : forall R y x z,\n  R x y ->\n  rtclosure R y z ->\n  rtclosure R x z.\nProof using. autos*. Qed.\n\nLemma rtclosure_r : forall R y x z,\n  rtclosure R x y ->\n  R y z ->\n  rtclosure R x z.\nProof using. autos*. Qed.\n\n(* Same as above, reformulated to make [eauto] faster *)\nLemma rtclosure_r' : forall R y x z,\n  R y z ->\n  rtclosure R x y ->\n  rtclosure R x z.\nProof using. autos*. Qed.\n\n(** Inclusion *)\n\nLemma rel_incl_rtclosure : forall R,\n  rel_incl R (rtclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma covariant_rtclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (rtclosure R1) (rtclosure R2).\nProof using. unfolds rel_incl. introv H M. induction* M. Qed.\n\n(* --TODO: find better name for this one and similar *)\nLemma rel_incl_rtclosure_rtclosure : forall R1 R2,\n  rel_incl R1 (rtclosure R2) ->\n  rel_incl (rtclosure R1) (rtclosure R2).\nProof using. unfolds rel_incl. introv H M. induction* M. Qed.\n\nLemma rel_incl_union_rtclosure : forall R1 R2,\n  rel_incl (union (rtclosure R1) (rtclosure R2))\n           (rtclosure (union R1 R2)).\nProof using.\n  hint rel_incl_union_l, rel_incl_union_r. introv [M|M].\n  { applys* covariant_rtclosure R1. }\n  { applys* covariant_rtclosure R2. }\nQed.\n\n(** Negation *)\n\nLemma not_rtclosure_inv_neq : forall R x y,\n  ~ rtclosure R x y ->\n  x <> y.\nProof using. introv M E. subst. induction* M. Qed.\n\n(** Induction principle with steps at head or tail *)\n\nSection Ind.\n\nInductive rtclosure'l A (R:binary A) : binary A :=\n  | rtclosure'l_refl : forall x,\n      rtclosure'l R x x\n  | rtclosure'l_step : forall y x z,\n      R x y ->\n      rtclosure'l R y z ->\n      rtclosure'l R x z.\n\nLemma trans_rtclosure'l : forall R,\n  trans (rtclosure'l R).\nProof using.\n  Hint Constructors rtclosure'l.\n  intros R y x z M1. gen z. induction M1; introv M2; autos*.\nQed.\n\nLemma rtclosure_eq_rtclosure'l : forall R,\n  rtclosure R = rtclosure'l R.\n  (* --LATER: tclosure'l = tclosure. *)\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. applys* trans_rtclosure'l y. }\n  { induction* M. }\nQed.\n\nLemma rtclosure_ind_l : forall R (P : A -> A -> Prop),\n  (forall x, P x x) ->\n  (forall y x z, R x y -> rtclosure R y z -> P y z -> P x z) ->\n  (forall x y, rtclosure R x y -> P x y).\nProof using.\n  introv H1 H2 M. rewrite rtclosure_eq_rtclosure'l in *. induction* M.\nQed.\n\nInductive rtclosure'r A (R:binary A) : binary A :=\n  | rtclosure'r_refl : forall x,\n      rtclosure'r R x x\n  | rtclosure'r_step : forall y x z,\n      rtclosure'r R x y ->\n      R y z ->\n      rtclosure'r R x z.\n\nLemma trans_rtclosure'r : forall R,\n  trans (rtclosure'r R).\nProof using.\n  Hint Constructors rtclosure'r.\n  intros R y x z M1 M2. gen x. induction M2; introv M1; autos*.\nQed.\n\nLemma rtclosure_eq_rtclosure'r : forall R,\n  rtclosure R = rtclosure'r R.\n  (* --LATER: tclosure'l = tclosure. *)\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. applys* trans_rtclosure'r y. }\n  { induction* M. }\nQed.\n\nLemma rtclosure_ind_r : forall R (P : A -> A -> Prop),\n  (forall x, P x x) ->\n  (forall y x z, rtclosure R x y -> P x y -> R y z -> P x z) ->\n  (forall x y, rtclosure R x y -> P x y).\nProof using.\n  introv H1 H2 M. rewrite rtclosure_eq_rtclosure'r in *. induction* M.\nQed.\n\nEnd Ind.\n\n(** Inversion principle with steps at head or tail *)\n\nLemma rtclosure_inv_l : forall R x z,\n  rtclosure R x z ->\n  (x = z) \\/ (exists y, R x y /\\ rtclosure R y z).\nProof using. intros R. applys* rtclosure_ind_l. Qed.\n\nLemma rtclosure_inv_r : forall R x z,\n  rtclosure R x z ->\n  (x = z) \\/ (exists y, rtclosure R x y /\\ R y z).\nProof using. intros R. applys* rtclosure_ind_r. Qed.\n\nEnd Rtclosure.\n\n#[global]\nHint Resolve rtclosure_refl rtclosure_once\n  rtclosure_l rtclosure_r' : rtclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Symmetric-transitive closure *)\n\nInductive stclosure A (R:binary A) : binary A :=\n  | stclosure_once : forall x y,\n      R x y ->\n      stclosure R x y\n  | stclosure_sym : forall x y,\n      stclosure R x y ->\n      stclosure R y x\n  | stclosure_trans : forall y x z,\n      stclosure R x y ->\n      stclosure R y z ->\n      stclosure R x z.\n\nSection Stclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors stclosure.\n\n(** Properties *)\n\nLemma refl_stclosure : forall R,\n  refl R ->\n  refl (stclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_stclosure : forall R,\n  sym (stclosure R).\nProof using. unfolds sym. introv N. induction* N. Qed.\n\nLemma trans_stclosure : forall R,\n  trans (stclosure R).\nProof using. unfolds* trans. Qed.\n\nLemma total_stclosure : forall R,\n  total R ->\n  total (stclosure R).\nProof using.\n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma stclosure_eq_of_sym_trans : forall R,\n  sym R ->\n  trans R ->\n  stclosure R = R.\nProof using.\n  unfolds sym, trans. introv H1 H2. extens. iff M.\n  { induction M; subst*. }\n  { autos*. }\nQed.\n\nLemma stclosure_inverse_eq : forall R,\n  stclosure (inverse R) = inverse (stclosure R).\nProof using.\n  unfolds inverse. extens. intros x y. iff M; induction* M.\nQed.\n\n(** Constructors *)\n\nLemma stclosure_l : forall R y x z,\n  R x y ->\n  stclosure R y z ->\n  stclosure R x z.\nProof using. autos*. Qed.\n\nLemma stclosure_r : forall R y x z,\n  stclosure R x y ->\n  R y z ->\n  stclosure R x z.\nProof using. autos*. Qed.\n\n(** Inclusion *)\n\nLemma rel_incl_stclosure : forall R,\n  rel_incl R (stclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma covariant_stclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (stclosure R1) (stclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_stclosure_stclosure : forall R1 R2,\n  rel_incl R1 (stclosure R2) ->\n  rel_incl (stclosure R1) (stclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nEnd Stclosure.\n\n#[global]\nHint Constructors stclosure : stclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Reflexive-symmetric-transitive closure *)\n\nInductive rstclosure A (R:binary A) : binary A :=\n  | rstclosure_once : forall x y,\n      R x y ->\n      rstclosure R x y\n  | rstclosure_refl : forall x,\n      rstclosure R x x\n  | rstclosure_sym : forall x y,\n      rstclosure R x y ->\n      rstclosure R y x\n  | rstclosure_trans : forall y x z,\n      rstclosure R x y ->\n      rstclosure R y z ->\n      rstclosure R x z.\n\nSection Rstclosure.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rstclosure.\n\n(** Properties *)\n\nLemma refl_rstclosure : forall R,\n  refl (rstclosure R).\nProof using. unfolds* refl. Qed.\n\nLemma sym_rstclosure : forall R,\n  sym (rstclosure R).\nProof using. unfolds* sym. Qed.\n\nLemma trans_rstclosure : forall R,\n  trans (rstclosure R).\nProof using. unfolds* trans. Qed.\n\nLemma total_rstclosure : forall R,\n  total R ->\n  total (rstclosure R).\nProof using.\n  unfolds total. introv H. intros x y. destruct* (H x y).\nQed.\n\nLemma rstclosure_eq_of_refl_sym_trans : forall R,\n  refl R ->\n  sym R ->\n  trans R ->\n  rstclosure R = R.\nProof using.\n  unfolds refl, sym, trans. introv H. extens. iff M.\n  { induction M; subst*. }\n  { auto. }\nQed.\n\nLemma rstclosure_inverse_eq : forall R,\n  rstclosure (inverse R) = rstclosure R.\nProof using.\n  unfolds inverse. extens. intros x y. iff M; induction* M.\nQed.\n\n(** Constructors *)\n\nLemma rstclosure_l : forall R y x z,\n  R x y ->\n  rstclosure R y z ->\n  rstclosure R x z.\nProof using. autos*. Qed.\n\nLemma rstclosure_r : forall R y x z,\n  rstclosure R x y ->\n  R y z ->\n  rstclosure R x z.\nProof using. autos*. Qed.\n\n(** Inclusion *)\n\nLemma rel_incl_rstclosure : forall R,\n  rel_incl R (rstclosure R).\nProof using. unfolds* rel_incl. Qed.\n\nLemma rel_incl_inverse_rstclosure : forall R,\n  rel_incl (inverse R) (rstclosure R).\nProof using. unfolds* rel_incl, inverse. Qed.\n\nLemma covariant_rstclosure : forall R1 R2,\n  rel_incl R1 R2 ->\n  rel_incl (rstclosure R1) (rstclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_rstclosure_rstclosure : forall R1 R2,\n  rel_incl R1 (rstclosure R2) ->\n  rel_incl (rstclosure R1) (rstclosure R2).\nProof using. introv H M. induction* M. Qed.\n\nLemma rel_incl_union_rstclosure : forall R1 R2,\n  rel_incl (union (rstclosure R1) (rstclosure R2))\n           (rstclosure (union R1 R2)).\nProof using.\n  hint rel_incl_union_l, rel_incl_union_r. introv [M|M].\n  { applys* covariant_rstclosure R1. }\n  { applys* covariant_rstclosure R2. }\nQed.\n\nEnd Rstclosure.\n\n#[global]\nHint Constructors rstclosure : rstclosure.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Relationship between closures *)\n\nSection ClosuresRel.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rtclosure rsclosure stclosure rstclosure.\n\n(** [rclosure] to [rtclosure] *)\n\nLemma rtclosure_of_rclosure : forall R x y,\n  rclosure R x y ->\n  rtclosure R x y.\nProof using. intros. destruct* H. Qed.\n\nLemma rel_incl_rclosure_rtclosure : forall R,\n  rel_incl (rclosure R) (rtclosure R).\nProof using. intros. applys* rtclosure_of_rclosure. Qed.\n\n(** [tclosure] to [rtclosure] *)\n\nLemma rtclosure_of_tclosure : forall R x y,\n  tclosure R x y ->\n  rtclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_tclosure_rtclosure : forall R,\n  rel_incl (tclosure R) (rtclosure R).\nProof using. intros. applys* rtclosure_of_tclosure. Qed.\n\n(** [rclosure] to [rsclosure] *)\n\nLemma rsclosure_of_rclosure : forall R x y,\n  rclosure R x y ->\n  rsclosure R x y.\nProof using. intros. destruct* H. Qed.\n\nLemma rel_incl_rclosure_rsclosure : forall R,\n  rel_incl (rclosure R) (rsclosure R).\nProof using. intros. applys* rsclosure_of_rclosure. Qed.\n\n(** [sclosure] to [rsclosure] *)\n\nLemma rsclosure_of_sclosure : forall R x y,\n  sclosure R x y ->\n  rsclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_sclosure_rsclosure : forall R,\n  rel_incl (sclosure R) (rsclosure R).\nProof using. intros. applys* rsclosure_of_sclosure. Qed.\n\n(** [sclosure] to [stclosure] *)\n\nLemma stclosure_of_sclosure : forall R x y,\n  sclosure R x y ->\n  stclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_slosure_rsclosure : forall R,\n  rel_incl (sclosure R) (stclosure R).\nProof using. intros. applys* stclosure_of_sclosure. Qed.\n\n(** [tclosure] to [stclosure] *)\n\nLemma stclosure_of_tclosure : forall R x y,\n  tclosure R x y ->\n  stclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_tclosure_stclosure : forall R,\n  rel_incl (tclosure R) (stclosure R).\nProof using. intros. applys* stclosure_of_tclosure. Qed.\n\n(** [rclosure] to [rstclosure] *)\n\nLemma rstclosure_of_rclosure : forall R x y,\n  rclosure R x y ->\n  rstclosure R x y.\nProof using. intros. destruct* H. Qed.\n\nLemma rel_incl_rclosure_rstclosure : forall R,\n  rel_incl (rclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_rclosure. Qed.\n\n(** [sclosure] to [rstclosure] *)\n\nLemma rstclosure_of_sclosure : forall R x y,\n  sclosure R x y ->\n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_sclosure_rstclosure : forall R,\n  rel_incl (sclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_sclosure. Qed.\n\n(** [tclosure] to [tstclosure] *)\n\nLemma rstclosure_of_tclosure : forall R x y,\n  tclosure R x y ->\n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_tclosure_rstclosure : forall R,\n  rel_incl (tclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_tclosure. Qed.\n\n(** [rsclosure] to [rstclosure] *)\n\nLemma rstclosure_of_rsclosure : forall R x y,\n  rsclosure R x y ->\n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_rsclosure_rstclosure : forall R,\n  rel_incl (rsclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_rsclosure. Qed.\n\n(** [rtclosure] to [rstclosure] *)\n\nLemma rstclosure_of_rtclosure : forall R x y,\n  rtclosure R x y ->\n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_rtclosure_rstclosure : forall R,\n  rel_incl (rtclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_rtclosure. Qed.\n\n(** [stclosure] to [rstclosure] *)\n\nLemma rstclosure_of_stclosure : forall R x y,\n  stclosure R x y ->\n  rstclosure R x y.\nProof using. intros. induction* H. Qed.\n\nLemma rel_incl_stclosure_rstclosure : forall R,\n  rel_incl (stclosure R) (rstclosure R).\nProof using. intros. applys* rstclosure_of_stclosure. Qed.\n\nEnd ClosuresRel.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Iterated closures *)\n\nSection IterClosures.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rclosure sclosure tclosure\n  rtclosure rsclosure stclosure rstclosure.\nHint Resolve sym_tclosure sym_sclosure sym_rclosure\n  sym_rtclosure sym_rsclosure sym_rtclosure sym_rstclosure.\n\nLemma rclosure_sclosure_eq_rsclosure : forall R,\n  rclosure (sclosure R) = rsclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { destruct* M. { applys* rsclosure_of_sclosure. } }\n  { induction* M. { applys* sym_inv. } }\nQed.\n\nLemma sclosure_rclosure_eq_rsclosure : forall R,\n  sclosure (rclosure R) = rsclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rsclosure_of_rclosure. } }\n  { induction* M. }\nQed.\n\nLemma rclosure_tclosure_eq_rtclosure : forall R,\n  rclosure (tclosure R) = rtclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rtclosure_of_tclosure. } }\n  { induction* M. { destruct IHM1; destruct IHM2; autos*. } }\nQed.\n\nLemma tclosure_rclosure_eq_rtclosure : forall R,\n  tclosure (rclosure R) = rtclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rtclosure_of_rclosure. } }\n  { induction* M. }\nQed.\n\nLemma tclosure_sclosure_eq_stclosure : forall R,\n  tclosure (sclosure R) = stclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* stclosure_of_sclosure. } }\n  { induction* M. { applys* sym_inv. } }\nQed.\n\nLemma rclosure_stclosure_eq_rstclosure : forall R,\n  rclosure (stclosure R) = rstclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rstclosure_of_stclosure. } }\n  { induction* M.\n    { destruct IHM; autos*. }\n    { destruct IHM1; destruct IHM2; autos*. } }\nQed.\n\nLemma stclosure_rclosure_eq_rstclosure : forall R,\n  stclosure (rclosure R) = rstclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rstclosure_of_rclosure. } }\n  { induction* M. }\nQed.\n\nLemma rtclosure_sclosure_eq_rstclosure : forall R,\n  rtclosure (sclosure R) = rstclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rstclosure_of_sclosure. } }\n  { induction* M. { applys* sym_inv. } }\nQed.\n\nLemma tclosure_rsclosure_eq_rstclosure : forall R,\n  tclosure (rsclosure R) = rstclosure R.\nProof using.\n  extens. intros x y. iff M.\n  { induction* M. { applys* rstclosure_of_rsclosure. } }\n  { induction* M. { applys* sym_inv. } }\nQed.\n\nEnd IterClosures.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Other lemmas -- TODO *)\n\nSection EquivClosures.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors rclosure sclosure tclosure rsclosure stclosure.\n\nLemma rsclosure_eq_union_rclosure_sclosure : forall R,\n  rsclosure R = union (rclosure R) (sclosure R).\nProof using.\n  extens. intros x y. unfold union. iff M.\n  { induction* M. destruct* IHM as [H|H]. destruct* H. }\n  { destruct* M as [H|H]. destruct* H. applys* rsclosure_of_sclosure. }\nQed.\n\nLemma rtclosure_eq_union_rclosure_tclosure : forall R,\n  rtclosure R = union (rclosure R) (tclosure R).\nProof using.\n  extens. intros x y. unfold union. iff M.\n  { induction* M. destruct IHM1 as [H1|H1]; destruct IHM2 as [H2|H2].\n     { destruct H1; destruct* H2. }\n     { destruct* H1. }\n     { destruct* H2. }\n     { autos*. } }\n  { destruct* M.\n    { applys* rtclosure_of_rclosure. }\n    { applys* rtclosure_of_tclosure. } }\nQed.\n\nLemma rtclosure_inv_rclosure_or_tclosure : forall R x y,\n  rtclosure R x y ->\n  x = y \\/ tclosure R x y.\nProof using.\n  introv M. rewrite rtclosure_eq_union_rclosure_tclosure in M.\n  destruct M as [M|M]. { destruct* M. } { auto. }\nQed.\n\nLemma stclosure_eq_rstclosure_of_refl : forall R,\n  refl R ->\n  stclosure R = rstclosure R.\nProof using.\n  introv H. extens. intros x y. iff M.\n  { applys* rstclosure_of_stclosure. }\n  { induction* M. }\nQed.\n\n(* --LATER: many lemmas like the above? *)\n\n(* --TODO: rename this lemma *)\nLemma rel_incl_tclosure_stclosure_l : forall R1 R2,\n  rel_incl R1 (stclosure R2) ->\n  rel_incl (tclosure R1) (stclosure R2).\nProof using. introv H M. induction* M. Qed.\n\n(* --LATER: many lemmas like the above? *)\n\nEnd EquivClosures.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Mixed transitivity between closures *)\n\nSection MixedClosures.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Constructors tclosure.\n\nLemma tclosure_of_rtclosure_l : forall R x y z,\n  rtclosure R x y ->\n  R y z ->\n  tclosure R x z.\nProof using.\n  introv H M. destruct (rtclosure_inv_rclosure_or_tclosure H).\n  { subst*. }\n  { applys* tclosure_r. }\nQed.\n\nLemma tclosure_of_rtclosure_r : forall R x y z,\n  R x y ->\n  rtclosure R y z ->\n  tclosure R x z.\nProof using.\n  introv M H. destruct (rtclosure_inv_rclosure_or_tclosure H).\n  { subst*. }\n  { applys* tclosure_l. }\nQed.\n\nLemma tclosure_of_rtclosure_tclosure : forall R y x z,\n  rtclosure R x y ->\n  tclosure R y z ->\n  tclosure R x z.\nProof using.\n  introv H M. destruct (rtclosure_inv_rclosure_or_tclosure H); subst*.\nQed.\n\nLemma tclosure_of_tclosure_rtclosure : forall R y x z,\n  tclosure R x y ->\n  rtclosure R y z ->\n  tclosure R x z.\nProof using.\n  introv M H. destruct (rtclosure_inv_rclosure_or_tclosure H); subst*.\nQed.\n\nEnd MixedClosures.\n\n(* --LATER: similar lemmas relating [rstclosure] and [stclosure] *)\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Irreflexive restriction of a relation *)\n\nDefinition strict A (R:binary A) : binary A :=\n  fun x y => R x y /\\ x <> y.\n\nSection Strict.\nVariables (A : Type).\nImplicit Types R : binary A.\nHint Unfold strict.\n\nLemma strict_eq_fun : forall R,\n  strict R = (fun x y => R x y /\\ x <> y).\nProof using. auto. Qed.\n\nLemma strict_eq : forall R x y,\n  strict R x y = (R x y /\\ x <> y).\nProof using. auto. Qed.\n\nLemma inverse_strict : forall R,\n  inverse (strict R) = strict (inverse R).\nProof using. intros. unfold inverse, strict. extens*. Qed.\n\nLemma trans_strict_l : forall y x z R,\n  trans R ->\n  strict R x y ->\n  R y z ->\n  R x z.\nProof using. introv T (E&H) H'; subst*. Qed.\n\nLemma trans_strict_r : forall y x z R,\n  trans R ->\n  R x y ->\n  strict R y z ->\n  R x z.\nProof using. introv T H (E&H'); subst*. Qed.\n\nLemma irrefl_strict : forall R,\n  irrefl (strict R).\nProof using. unfold strict, irrefl. intros. rew_logic*. Qed.\n\nLemma antisym_strict : forall R,\n  antisym R ->\n  antisym (strict R).\nProof using. unfolds* antisym, strict. Qed.\n\nLemma trans_strict : forall R,\n  trans R ->\n  antisym R ->\n  trans (strict R).\nProof using.\n  introv T S. unfold strict. introv [H1 H2] [H3 H4]. split.\n  { apply* T. }\n  { intros K. subst. apply H2. apply~ S. }\nQed.\n\nLemma strict_rclosure : forall R,\n  irrefl R ->\n  strict (rclosure R) = R.\nProof using.\n  unfold strict. extens. intros x y. iff (K1&K2) K.\n  { destruct* K1. }\n  { split. { left*. } { apply* irrefl_inv_neq. } }\nQed.\n\nLemma rclosure_strict : forall R,\n  refl R ->\n  rclosure (strict R) = R.\nProof using.\n  Hint Constructors rclosure.\n  unfold strict. extens. intros x y. iff K.\n  { destruct K; subst*. }\n  { tests: (x = y); subst*. }\nQed.\n\nEnd Strict.\n\n\n(* ********************************************************************** *)\n(** Function to relation *)\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion of a function in a relation *)\n\n(** [fun_in_rel f R] asserts that input-output pairs of [f] are\n    included in the relation [R]. *)\n\nDefinition fun_in_rel A B (f:A->B) (R:A->B->Prop) :=\n  forall x, R x (f x).\n\nSection Fun_in_rel.\nVariables (A B : Type).\nImplicit Type f : A->B.\nImplicit Type R : A->B->Prop.\n\nLemma defined_of_fun_in_rel : forall f R,\n  fun_in_rel f R ->\n  defined R.\nProof using. unfolds* fun_in_rel, defined. Qed.\n\n(** The relation built from a function [f] is included in a relation\n    [R] iff the function [f] is included in [R] *)\n\nLemma rel_incl_rel_fun_eq_fun_in_rel : forall f R,\n  rel_incl (rel_fun f) R = fun_in_rel f R.\nProof using.\n  extens. unfold rel_fun, fun_in_rel. iff H; intros x; specializes H x.\n  { applys* H. }\n  { intros y Hy. subst~. }\nQed.\n\nEnd Fun_in_rel.\n\n\n(* ---------------------------------------------------------------------- *)\n(** ** Inclusion of a relation in a function *)\n\n(** [rel_in_fun R f] asserts that input-output pairs of [R]\n    are input-output for [f]. *)\n\nDefinition rel_in_fun A B (R:A->B->Prop) (f:A->B) :=\n  forall x y, R x y -> f x = y.\n\nSection Rel_in_fun.\nVariables (A B : Type).\nImplicit Type f : A->B.\nImplicit Type R : A->B->Prop.\n\nLemma functional_of_rel_in_fun : forall R f,\n  rel_in_fun R f ->\n  functional R.\nProof using.\n  unfold rel_in_fun, functional. introv M N1 N2.\n  lets: M N1. lets: M N2. congruence.\nQed.\n\n(* If the relation [R] is functional and if [f] is included in [R],\n   then [R] is included in [f], i.e., they coincide. *)\n\nLemma rel_in_fun_of_fun_in_rel_functional : forall f R,\n  fun_in_rel f R ->\n  functional R ->\n  rel_in_fun R f.\nProof using.\n  introv h1 h2. intros a b H. forwards M: h1 a. forwards*: h2 H M.\nQed.\n\nEnd Rel_in_fun.\n\n", "meta": {"author": "charguer", "repo": "tlc", "sha": "590c8c8d80442376b8ac19198b7ed446cebc6934", "save_path": "github-repos/coq/charguer-tlc", "path": "github-repos/coq/charguer-tlc/tlc-590c8c8d80442376b8ac19198b7ed446cebc6934/src/LibRelation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7029133845178035}}
{"text": "Require Export Basics_J.\n\nModule NatList.\n\nInductive natlist : Type :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nInductive natprod : Type :=\n  pair : nat -> nat -> natprod.\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\nNotation \"( x , y )\" := (pair x y).\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\nTheorem surjective_pairing' : forall (n m : nat),\n  (n,m) = (fst (n,m), snd (n,m)).\nProof.\n  reflexivity. Qed.\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\nTheorem snd_fst_is_swap : forall (p : natprod),\n  (snd p, fst p) = swap_pair p.\nProof.\nAdmitted.\n\n(* Inductive natlist : Type := *)\n(*   | nil : natlist *)\n(*   | cons : nat -> natlist -> natlist. *)\n\nDefinition l_123 := cons 1 (cons 2 (cons 3 nil)).\n\nNotation \"x :: l\" := (cons x l) (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\nNotation \"x + y\" := (plus x y)\n                    (at level 50, left associativity). \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 length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\n\nFixpoint app (l1 l2 : natlist) : natlist :=\n  match l1 with\n  | nil => l2\n  | h :: t => h :: (app t l2)\n  end.\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\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\nDefinition bag := natlist.\n\nTheorem nil_app : forall l:natlist,\n  [] ++ l = l.\nProof.\n   reflexivity. Qed.\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\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\nTheorem app_length : forall l1 l2 : natlist,\n  length (l1 ++ l2) = (length l1) + (length l2).\nProof.\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\nFixpoint snoc (l:natlist) (v:nat) : natlist :=\n  match l with\n  | nil => [v]\n  | h :: t => h :: (snoc t v)\n  end.\n\nFixpoint rev (l:natlist) : natlist :=\n  match l with\n  | nil => nil\n  | h :: t => snoc (rev t) h\n  end.\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\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\nInductive natoption : Type :=\n  | Some : nat -> natoption\n  | None : natoption.\n\nFixpoint index_bad (n:nat) (l:natlist) : nat :=\n  match l with\n  | nil => 42 \n  | a :: l' => match beq_nat n O with\n               | true => a\n               | false => index_bad (pred n) l'\n               end\n  end.\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\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\nDefinition option_elim (o : natoption) (d : nat) : nat :=\n  match o with\n  | Some n' => n'\n  | None => d\n  end.\n\nTheorem silly1 : forall (n m o p : nat),\n     n = m ->\n     [n,o] = [n,p] ->\n     [n,o] = [m,p].\nProof.\n  intros n m o p eq1 eq2.\n  rewrite <- eq1.\n  apply eq2. Qed.\n\nTheorem silly2 : forall (n m o p : nat),\n     n = m ->\n     (forall (q r : nat), q = r -> [q,o] = [r,p]) ->\n     [n,o] = [m,p].\nProof.\n  intros n m o p eq1 eq2.\n  apply eq2. apply eq1. Qed.\n\nTheorem silly2a : forall (n m : nat),\n     (n,n) = (m,m) ->\n     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->\n     [n] = [m].\nProof.\n  intros n m eq1 eq2.\n  apply eq2. apply eq1. Qed.\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. apply H0. Qed.\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  symmetry.\n  simpl.   apply H. Qed.\n\nTheorem beq_nat_sym : forall (n m : nat),\n  beq_nat n m = beq_nat m n.\nProof.\n  intros n. induction n as [| n'].\nAdmitted.\n(* Theorem rev_exercise1 : forall (l l' : natlist), *)\n(*      l = rev l' -> *)\n(*      l' = rev l. *)\n(* Proof. *)\n(* Admitted. *)\nEnd NatList.\n\nModule Dictionary.\n\nInductive dictionary : Type :=\n  | empty : dictionary\n  | record : nat -> nat -> dictionary -> dictionary.\n\nDefinition insert (key value : nat) (d : dictionary) : dictionary :=\n  (record key value d).\n\nFixpoint find (key : nat) (d : dictionary) : option nat :=\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\nEnd Dictionary.\n\nDefinition beq_nat_sym := NatList.beq_nat_sym.\n", "meta": {"author": "denjiry", "repo": "pgeneral", "sha": "190a607a5071af6d41d1abe2af85b86dc085b9ea", "save_path": "github-repos/coq/denjiry-pgeneral", "path": "github-repos/coq/denjiry-pgeneral/pgeneral-190a607a5071af6d41d1abe2af85b86dc085b9ea/Lists_J.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7029133757605368}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.ListSet.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Aniceto.List.\nSection LISTS.\n\nVariable A:Type.\nVariable eq_dec : forall (v1 v2:A), {v1 = v2} + {v1 <> v2}.\n\nFixpoint as_set (l:list A) :=\n  match l with\n    | cons x l' =>\n      if set_mem eq_dec x l'\n      then as_set l'\n      else x :: (as_set l')\n    | nil => nil\n  end.\n\nDefinition set_length (l:list A) := length (as_set l).\n\nLemma as_set_simpl:\n  forall a l,\n  In a l ->\n  as_set (a :: l) = as_set l.\nProof.\n  intros.\n  simpl.\n  remember (set_mem eq_dec a l) as x.\n  destruct x.\n  trivial.\n  symmetry in Heqx.\n  apply set_mem_correct2 with (Aeq_dec := eq_dec) in H.\n  rewrite H in Heqx.\n  inversion Heqx.\nQed.\n\nLemma as_set_in1:\n  forall a l,\n  In a l ->\n  In a (as_set l).\nProof.\n  intros.\n  induction l.\n  - inversion H.\n  - simpl.\n    remember (set_mem eq_dec a0 l) as x.\n    destruct x.\n    symmetry in Heqx.\n    apply set_mem_correct1 in Heqx.\n    inversion H.\n    subst.\n    apply IHl. assumption.\n    apply IHl. assumption.\n    symmetry in Heqx.\n    simpl.\n    inversion H.\n    subst.\n    intuition.\n    right.\n    apply IHl.\n    assumption.\nQed.\n\nLemma as_set_in2:\n  forall a l,\n  In a (as_set l) ->\n  In a l.\nProof.\n  intros.\n  induction l.\n  inversion H.\n  simpl in *.\n  remember (set_mem eq_dec a0 l) as x. symmetry in Heqx.\n  destruct x.\n  - right. apply IHl.\n    assumption.\n  - inversion H.\n    intuition.\n    right. apply IHl.\n    assumption.\nQed.\n\nLemma as_set_def1:\n  forall l,\n  incl l (as_set l).\nProof.\n  intros.\n  unfold incl.\n  intros.\n  apply as_set_in1.\n  assumption.\nQed.\n\nLemma as_set_def2:\n  forall l,\n  incl (as_set l) l.\nProof.\n  intros.\n  unfold incl. intros.\n  apply as_set_in2.\n  assumption.\nQed.\n\nLemma as_set_no_dup:\n  forall l,\n  NoDup (as_set l).\nProof.\n  intros.\n  induction l.\n  - apply NoDup_nil.\n  - simpl.\n    remember (set_mem eq_dec a l) as x. symmetry in Heqx.\n    destruct x.\n    + assumption.\n    + assert (a_nin_l: ~ In a l).\n      intuition.\n      apply set_mem_correct2 with (Aeq_dec := eq_dec) in H.\n      rewrite H in *.\n      inversion Heqx.\n      apply NoDup_cons.\n      intuition.\n      apply as_set_in2 in H.\n      apply a_nin_l.\n      assumption.\n      assumption.\nQed.\n\nLemma as_set_no_dup_simpl:\n  forall l,\n  NoDup l ->\n  as_set l = l.\nProof.\n  intros.\n  induction l.\n  - auto.\n  - simpl.\n    inversion H; subst.\n    remember (set_mem eq_dec a l).\n    destruct b.\n    + symmetry in Heqb.\n      apply (set_mem_complete2 eq_dec)  in H2.\n      rewrite H2 in Heqb.\n      inversion Heqb.\n    + apply IHl in H3.\n      rewrite H3.\n      auto.\nQed.\n\n\n(***************************************) \n\nDefinition set_eq (l1:list A) (l2:list A) := (forall x, In x l1 <-> In x l2).\n\nLemma set_eq_nil:\n  set_eq nil nil.\nProof.\n  unfold set_eq.\n  split; auto.\nQed.\n\nLemma set_eq_spec:\n  forall l1 l2,\n  set_eq l1 l2 ->\n  (forall x, In x l1 <-> In x l2).\nProof.\n  unfold set_eq.\n  auto.\nQed.\n\n\n  Lemma set_eq_refl:\n    forall (l:list A),\n    set_eq l l.\n  Proof.\n    intros.\n    unfold set_eq.\n    intros.\n    tauto.\n  Qed.\n\n  Lemma set_eq_symm:\n    forall (l1 l2:list A),\n    set_eq l1 l2 ->\n    set_eq l2 l1.\n  Proof.\n    unfold set_eq; intuition; apply H in H0; eauto.\n  Qed.\n\n  Lemma set_eq_def:\n    forall (l1 l2:list A),\n    incl l1 l2 ->\n    incl l2 l1 ->\n    set_eq l1 l2.\n  Proof.\n    unfold incl, set_eq.\n    split; intros; eauto.\n  Qed.\n\n  Lemma set_eq_to_incl:\n    forall (l1 l2:list A),\n    set_eq l1 l2 ->\n    incl l1 l2.\n  Proof.\n    unfold set_eq, incl.\n    intros.\n    apply H in H0.\n    assumption.\n  Qed.\n\n  Lemma set_eq_to_incl_alt:\n    forall (l1 l2:list A),\n    set_eq l1 l2 ->\n    incl l2 l1.\n  Proof.\n    unfold set_eq, incl.\n    intros.\n    apply H in H0.\n    assumption.\n  Qed.\n\nTheorem exists_no_dup:\n  forall l, exists l', set_eq l l' /\\ NoDup l'.\nProof.\n  intros.\n  exists (as_set l).\n  split.\n  - unfold set_eq.\n    intuition.\n    apply as_set_def1; assumption.\n    apply as_set_def2; assumption.\n  - apply as_set_no_dup.\nQed.\n\nLemma set_eq_perm:\n  forall l1 l2,\n  NoDup l1 ->\n  NoDup l2 ->\n  set_eq l1 l2 ->\n  length l1 = length l2.\nProof.\n  intros.\n  unfold set_eq in H1.\n  assert (p: Permutation l1 l2).\n  apply NoDup_Permutation; repeat auto.\n  apply Permutation_length ; repeat auto.\nQed.\n\nLemma set_length_le:\n  forall l1 l2,\n  incl l1 l2 ->\n  set_length l1 <= set_length l2. \nProof.\n  intros.\n  assert (NoDup (as_set l1)) by apply as_set_no_dup.\n  assert (NoDup (as_set l2)) by apply as_set_no_dup.\n  unfold set_length.\n  remember (as_set l1) as l1'.\n  remember (as_set l2) as l2'.\n  apply no_dup_length_le; auto.\n  assert (incl (as_set l1) l1) by apply as_set_def2.\n  assert (incl l2 (as_set l2)) by apply as_set_def1.\n  subst.\n  eauto using incl_tran.\nQed.\n\nLemma set_length_succ:\n  forall a l,\n  ~ In a l ->\n  set_length (a :: l) = S (set_length l).\nProof.\n  intros.\n  unfold set_length.\n  simpl.\n  remember (set_mem eq_dec a l).\n  destruct b.\n  - symmetry in Heqb.\n    apply set_mem_correct1 in Heqb.\n    contradiction Heqb.\n  - auto.\nQed.\n\nLet minus_lt_compat:\n  forall n m : nat,\n  (S m) <= n ->\n  n - (S m) < n - m.\nProof.\n  induction n, m; eauto using Le.le_S_n; intuition.\nQed.\n\nLemma set_length_minus:\n  forall a l1 l2,\n  ~ In a l1 ->\n  incl (a :: l1) l2 ->\n  set_length l2 - set_length (a :: l1) <\n  set_length l2 - set_length l1.\nProof.\n  intros.\n  apply set_length_le in H0.\n  rewrite set_length_succ in *; repeat auto.\nQed.\n\nEnd LISTS.\n", "meta": {"author": "cogumbreiro", "repo": "aniceto-coq", "sha": "a719321532dd55643f14ec99215891641ee912ec", "save_path": "github-repos/coq/cogumbreiro-aniceto-coq", "path": "github-repos/coq/cogumbreiro-aniceto-coq/aniceto-coq-a719321532dd55643f14ec99215891641ee912ec/src/ListSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7029133735701767}}
{"text": "Require Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Strings.String.\n\nRequire Import Hapsl.Ascii.Equality.\nRequire Import Hapsl.String.Equality.\nRequire Import Hapsl.String.Transform.\n\nImport AsciiEqualityNotations.\nImport StringEqualityNotations.\n\n(* Returns true if a string is a palindrome, otherwise returns false. *)\nDefinition palindrome (s : string) : bool :=\n  s ==_s (string_reverse s).\n\n(* Prove that palindrome behaves correctly. *)\nTheorem palindrome_correct : forall (s : string),\n  s = string_reverse s -> Is_true (palindrome s).\nProof.\n  intros.\n  unfold palindrome.\n  rewrite <- H.\n  rewrite -> beq_string_reflexive.\n  reflexivity.\nQed.\n\n(* The recursive portion of the efficient palindrome function. *)\nFixpoint palindrome_efficient_recursive (s : string) (x y : nat) : bool :=\n  if Nat.leb y x then\n    true (* This is included only for efficiency. *)\n  else\n    match y with\n      | S y' => (get x s) ?==_a (get y' s)\n        && (palindrome_efficient_recursive s (x + 1) y')\n      | O => true\n    end.\n\n(* A more efficient implementation of the palindrome function. *)\nDefinition palindrome_efficient (s : string) : bool :=\n  palindrome_efficient_recursive s 0 (length s).\n", "meta": {"author": "sr-lab", "repo": "verified-pam-cracklib", "sha": "f2fe95c54c1085a9577490f06a22e797c3697375", "save_path": "github-repos/coq/sr-lab-verified-pam-cracklib", "path": "github-repos/coq/sr-lab-verified-pam-cracklib/verified-pam-cracklib-f2fe95c54c1085a9577490f06a22e797c3697375/src/String/Palindrome.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7028391405258083}}
{"text": "Require Import BinNat BinNatDef BinPos BinPosDef.\nInclude BinNatDef.N.\n\nLocal Open Scope positive_scope.\n\nCoercion bool_to_Prop (b : bool) : Prop := b = true.\n\nCoercion pos_to_N (p : positive) : N := pos p.\n\nDefinition finset := N.\nNotation \"∅\" := N0.\n\nFixpoint pos_cardinality (p : positive) : nat :=\n  match p with\n  | 1 => 1\n  | p~0 => pos_cardinality p\n  | p~1 => S (pos_cardinality p)\n  end.\n\nDefinition cardinality (s : finset) : nat :=\n  match s with\n  | ∅ => 0\n  | pos p => pos_cardinality p\n  end.\nNotation \"# s\" := (cardinality s) (at level 50).\n\nDefinition union : finset -> finset -> finset := lor.\nInfix \"∪\" := union (left associativity, at level 61).\n\nDefinition intersection : finset -> finset -> finset := land.\nInfix \"∩\" := intersection (left associativity, at level 61).\n\nDefinition diff : finset -> finset -> finset := ldiff.\nInfix \"\\\" := diff (left associativity, at level 62).\n\nDefinition mem : nat -> finset -> bool := fun n s => testbit_nat s n.\nInfix \"∈\" := mem (at level 60).\n\nFixpoint pos_incl (p1 p2 : positive) : bool :=\n  match (p1, p2) with\n  | (1, 1) => true\n  | (_, 1) => false\n  | (1, p~0) => false\n  | (1, p~1) => true\n  | (p1~0, p2~0) => pos_incl p1 p2\n  | (p1~0, p2~1) => pos_incl p1 p2\n  | (p1~1, p2~0) => false\n  | (p1~1, p2~1) => pos_incl p1 p2\n  end.\n\nFixpoint incl (s1 s2 : finset) : bool :=\n  match (s1, s2) with\n  | (∅, _) => true\n  | (_, ∅) => false\n  | (pos p1, pos p2) => pos_incl p1 p2\n  end.\nInfix \"⊆\" := incl (at level 70).\n\nFixpoint pos_singleton_of (n : nat) : positive :=\n  match n with\n  | O => 1\n  | S n => (pos_singleton_of n)~0\n  end.\n\nFixpoint singleton_of (n : nat) : finset := pos (pos_singleton_of n).\nNotation \"{{ n }}\" := (singleton_of n).\n\nLemma emp_minimum : forall s, ∅ ⊆ s. Proof. reflexivity. Qed.\n\nLemma emp_min : forall s, s ⊆ ∅ -> ∅ = s.\nProof.\n  destruct s; auto. destruct p; intros cont; inversion cont.\nQed.\n\nLemma zero_incl : forall p, 1 ⊆ p~1.\nProof. reflexivity. Qed.\n\nLemma zero_not_incl : forall p, 1 ⊆ p~0 = false.\nProof. reflexivity. Qed.\n\nLemma pos_incl_reflexive: forall p, pos_incl p p.\nProof. induction p; try (apply IHp). reflexivity. Qed.\n\n\nLemma incl_reflexive : forall s1, s1 ⊆ s1.\nProof.\n  destruct s1; try reflexivity.\n  induction p; try reflexivity; apply IHp.\nQed.\n\nLemma incl_transitive : forall s1 s2 s3, s1 ⊆ s2 -> s2 ⊆ s3 -> s1 ⊆ s3.\nProof.\n  destruct s1; destruct s2; destruct s3; try reflexivity;\n    intros H1 H2; try (apply H1); try (apply H2).\n    - apply emp_min in H1. rewrite <- H1. reflexivity.\n    - generalize dependent p0. generalize dependent p1.\n      induction p; destruct p0; destruct p1; intros H1 H2;\n        inversion H1; inversion H2; try reflexivity; simpl in *;\n        apply (IHp p1 p0); try (apply H1); try (apply H2).\nQed.\n\n\nLemma choice : forall s, (Nat.leb 1 (# s)) <-> exists n, n ∈ s.\nProof.\n  destruct s.\n    - split; simpl; intros H; inversion H; inversion H0.\n    - induction p; split; intros H;\n      try reflexivity;\n      try (exists 0%nat; reflexivity).\n      + apply IHp in H. destruct H as [n H].\n        exists (S n). apply H.\n      + apply IHp. destruct H as [n H].\n        exists (Nat.pred n). destruct n.\n        * inversion H.\n        * apply H.\nQed.\n\nLemma pos_card_min : forall p, Nat.leb 1 (pos_cardinality p).\nProof. induction p; try reflexivity. apply IHp. Qed.\n\nDefinition pos_choice : forall p, exists n, n ∈ (pos p) :=\n  fun p => proj1 (choice (pos p)) (pos_card_min p).\n\n\nLemma extensionality : forall s1 s2, s1 ⊆ s2 -> s2 ⊆ s1 -> s1 = s2.\nProof.\n  destruct s1; destruct s2;\n    try reflexivity.\n    - intros T F. inversion F.\n    - intros F T. inversion F.\n    - generalize dependent p0.\n      induction p; induction p0; simpl;\n        intros sI Is; try (inversion Is);\n        try (apply IHp in sI);\n        try (inversion sI); try (reflexivity);\n        apply Is.\nQed.\n\nLemma extensionality_iff : forall s1 s2, (s1 ⊆ s2 /\\ s2 ⊆ s1) <-> s1 = s2.\nProof.\n  split.\n    - intros [sI Is]. apply extensionality. apply sI. apply Is.\n    - intros E. rewrite E. split; apply incl_reflexive.\nQed.\n\nLemma mem_incl : forall s1 s2, s1 ⊆ s2 <-> forall n, n ∈ s1 -> n ∈ s2.\nProof.\n  split.\n    - intros H n Hn. destruct s1.\n      + inversion Hn.\n      + destruct s2.\n        * inversion H.\n        * generalize dependent p.\n          generalize dependent n.\n          induction p0; destruct n; destruct p;\n            try reflexivity;\n            intros H; intros Hn;\n            inversion H;\n            inversion Hn;\n            try (apply (IHp0 n p H Hn)).\n    - destruct s1; destruct s2; try reflexivity.\n      + intros H.\n        destruct (pos_choice p) as [n nIp].\n        apply H in nIp. inversion nIp.\n      + generalize dependent p0.\n        induction p; destruct p0;\n          try reflexivity;\n          try (intros H; apply IHp; destruct n; try (apply (H 1%nat)); try (apply (H (S (S n)))));\n          intros H;\n          try (destruct (pos_choice p) as [n nIp]; apply (H (S n)) in nIp; inversion nIp).\n        * assert (cont : 0%nat ∈ p~1). { reflexivity. }\n          apply H in cont. inversion cont.\n        * assert (cont : 0%nat ∈ 1). { reflexivity. }\n          apply H in cont. inversion cont.\nQed.\n\nLemma mem_pos_singleton1 : forall n, n ∈ pos_singleton_of n.\nProof. induction n. reflexivity. simpl. apply IHn. Qed.\n\nLemma mem_singleton1 : forall n, n ∈ {{n}}.\nProof. destruct n. reflexivity. simpl. apply mem_pos_singleton1. Qed.\n\nLemma mem_pos_singleton2 : forall n m, m ∈ pos_singleton_of n -> n = m.\nProof. induction n; destruct m; auto; intros H; inversion H. Qed.\n\nLemma mem_singleton2 : forall n m, m ∈ {{n}} -> n = m.\nProof.\n  destruct n; destruct m; intros H; inversion H; auto.\n  simpl in H. apply eq_S. apply (mem_pos_singleton2 _ _ H).\nQed.\n\nLemma singleton_mem_incl : forall n s, n ∈ s -> {{n}} ⊆ s.\nProof. intros. apply mem_incl. intros. destruct (mem_singleton2 _ _ H0). apply H. Qed.\n\nLemma double_nonempty : forall p, double (pos p) <> ∅.\nProof. intros p cont. inversion cont. Qed.\n\n\nLemma double_empty : forall s, double s = ∅ -> s = ∅.\nProof.\n  destruct s; auto.\n    intros con; inversion con.\nQed.\n\nLemma empty_double : forall s, s = ∅ -> double s = ∅.\nProof. intros s H. rewrite H. reflexivity. Qed.\n\nLemma succ_double_nonempty : forall s, BinPos.Pos.Nsucc_double s <> ∅.\nProof. destruct s; intros cont; inversion cont. Qed.\n\nLemma double_incl : forall s1 s2, s1 ⊆ s2 -> double s1 ⊆ double s2.\nProof. destruct s1; destruct s2; auto. Qed.\n\nLemma succ_double_incl : forall s1 s2, s1 ⊆ s2 ->\n  BinPos.Pos.Nsucc_double s1 ⊆ BinPos.Pos.Nsucc_double s2.\nProof. destruct s1; destruct s2; auto. Qed.\n\nLemma double_succ_double_incl : forall s1 s2,\n  s1 ⊆ s2 -> double s1 ⊆ BinPos.Pos.Nsucc_double s2.\nProof. destruct s1; destruct s2; auto. Qed.\n\nLemma pos_incl0 : forall p1 p2 : positive, p1 ⊆ p2 -> p1~0 ⊆ p2~0.\nProof. destruct p1; destruct p2; auto. Qed.\n\nLemma pos_incl1 : forall p1 p2 : positive, p1 ⊆ p2 -> p1~0 ⊆ p2~1.\nProof. destruct p1; destruct p2; auto. Qed.\n\nLemma pos_incl3 : forall p1 p2 : positive, p1 ⊆ p2 -> p1~1 ⊆ p2~1.\nProof. destruct p1; destruct p2; auto. Qed.\n\nLemma double_0 : forall s, 0%nat ∈ double s = false.\nProof. destruct s; auto. Qed.\n\nLemma succ_double_0 : forall s, 0%nat ∈ BinPos.Pos.Nsucc_double s.\nProof. destruct s; reflexivity. Qed.\n\nLemma double_n : forall s n, n ∈ s -> S n ∈ double s.\nProof. destruct s; auto. Qed.\n\nLemma succ_double_n : forall s n, n ∈ s -> S n ∈ BinPos.Pos.Nsucc_double s.\nProof. destruct s; auto. Qed.\n\nLemma double_Sn : forall s n, S n ∈ double s -> n ∈ s.\nProof. destruct s; auto. Qed.\n\nLemma succ_double_Sn : forall s n, S n ∈ BinPos.Pos.Nsucc_double s -> n ∈ s.\nProof. destruct s; auto. Qed.\n\nLemma union_idl : forall s, ∅ ∪ s = s. Proof. auto. Qed.\n\nLemma union_idr : forall s, s ∪ ∅ = s. Proof. destruct s; auto. Qed.\n\nLemma intersection_empl : forall s, ∅ ∩ s = ∅. Proof. auto. Qed.\n\nLemma intersection_empr : forall s, s ∩ ∅ = ∅. Proof. destruct s; auto. Qed.\n\nHint Resolve union_idl union_idr incl_reflexive pos_incl_reflexive.\n\nLemma union_lub1 : forall s1 s2, s1 ⊆ s1 ∪ s2.\nProof.\n  destruct s1; destruct s2; auto.\n    - rewrite union_idl. reflexivity.\n    - generalize dependent p0.\n      induction p; destruct p0; try reflexivity; simpl; auto;\n        try (apply IHp).\nQed.\n\nLemma union_lub2 : forall s1 s2 s3, s1 ⊆ s3 -> s2 ⊆ s3 -> s1 ∪ s2 ⊆ s3.\nProof.\n  destruct s1; destruct s2; destruct s3; auto.\n  generalize dependent p0. generalize dependent p1.\n  induction p; destruct p0; destruct p1; simpl; auto;\n    try (apply IHp).\nQed.\n\nDefinition union_absorb : forall s1 s2, s1 ⊆ s2 -> s2 ∪ s1 = s2 :=\n  fun s1 s2 (s1I2: s1 ⊆ s2) =>\n    extensionality _ _\n    (union_lub2 _ _ _ (incl_reflexive _) s1I2)\n      (union_lub1 _ _).\n\nHint Resolve intersection_empl intersection_empr emp_minimum.\n\nLemma intersection_glb1 : forall s1 s2, s1 ∩ s2 ⊆ s2.\nProof.\n  destruct s1; destruct s2; auto.\n  generalize dependent p0.\n  induction p; destruct p0; auto;\n    try reflexivity; simpl in *;\n    destruct (BinPos.Pos.land p p0) eqn:H; try reflexivity;\n    pose proof (IHp p0) as H'; rewrite H in H'; apply H'.\nQed.\n\nLemma intersection_glb2 : forall s1 s2 s3, s1 ⊆ s2 -> s1 ⊆ s3 -> s1 ⊆ s2 ∩ s3.\nProof.\n  destruct s1; destruct s2; destruct s3; auto.\n  generalize dependent p0. generalize dependent p1.\n  induction p; destruct p0; destruct p1; auto; simpl in *;\n      destruct (BinPos.Pos.land p0 p1) eqn:H;\n      try reflexivity;\n      try (pose proof (IHp p1 p0) as H'; rewrite H in H'; simpl; apply H');\n      intros H1 H2; inversion H1; inversion H2.\nQed.\n\nDefinition intersection_absorb : forall s1 s2, s1 ⊆ s2 -> s2 ∩ s1 = s1 :=\n  fun s1 s2 (s1I2: s1 ⊆ s2) =>\n    extensionality _ _\n    (intersection_glb1 _ _)\n    (intersection_glb2 _ _ _ s1I2 (incl_reflexive _)).\n\nDefinition incl_union : forall s1 s2, s2 ⊆ s1 -> s1 ∪ s2 = s1 :=\n  fun s1 s2 s2Is1 =>\n    extensionality (s1 ∪ s2) s1\n      (union_lub2 s1 s2 s1 (incl_reflexive s1) s2Is1) (union_lub1 s1 s2).\n\nDefinition intersection_incl : forall s1 s2, s2 ⊆ s1 -> s1 ∩ s2 = s2 :=\n  fun s1 s2 s2Is1 =>\n    extensionality (s1 ∩ s2) s2\n      (intersection_glb1 s1 s2) (intersection_glb2 s2 s1 s2 s2Is1 (incl_reflexive s2)).\n\n\nDefinition zero_intersection p : p~1 ∩ 1 = 1 :=\n  intersection_incl _ _ (zero_incl _).\n\nLemma union_comm : forall s1 s2, s1 ∪ s2 = s2 ∪ s1.\nProof.\n  intros s1 s2. apply extensionality;\n        destruct s1; destruct s2; auto;\n        generalize dependent p0;\n        induction p; destruct p0; auto;\n        try (apply IHp).\nQed.\n\nHint Resolve double_incl succ_double_incl.\n\nLemma intersection_comm : forall s1 s2, s1 ∩ s2 = s2 ∩ s1.\nProof.\n  intros s1 s2. apply extensionality;\n        destruct s1; destruct s2; auto;\n        generalize dependent p0;\n        induction p; destruct p0; try reflexivity;\n        try (apply succ_double_incl; apply IHp);\n        apply double_incl; apply IHp.\nQed.\n\nLemma intersection_incl_union : forall s1 s2, s1 ∩ s2 ⊆ s1 ∪ s2.\nProof.\n  intros. rewrite union_comm.\n  apply (incl_transitive _ s2 _).\n  apply intersection_glb1. apply union_lub1.\nQed.\n\nLemma union_assoc : forall s1 s2 s3, s1 ∪ (s2 ∪ s3) = (s1 ∪ s2) ∪ s3.\nProof.\n  destruct s1; destruct s2; destruct s3; auto.\n  apply extensionality;\n    generalize dependent p0; generalize dependent p1;\n    induction p; destruct p0; destruct p1; auto;\n    simpl; try (apply IHp); auto.\nQed.\n\nHint Resolve zero_intersection.\n\n\nLemma intersection_assoc : forall s1 s2 s3, s1 ∩ (s2 ∩ s3) = (s1 ∩ s2) ∩ s3.\nProof.\n  destruct s1; destruct s2; destruct s3; auto.\n  apply extensionality.\n    - generalize dependent p0. generalize dependent p1.\n      induction p; destruct p0; destruct p1; auto; simpl in *;\n        try (\n          destruct (BinPos.Pos.land p0 p1) eqn:H0;\n          auto\n        );\n        try (\n          destruct (BinPos.Pos.land p p0) eqn:H1;\n          auto\n        );\n        try reflexivity; simpl;\n        try (\n          pose proof (IHp p1 p0) as H'; rewrite H0 in H';\n          rewrite H1 in H'; rewrite intersection_empl in H';\n          apply emp_min in H'; rewrite <- H'; reflexivity\n        );\n        try (\n          pose proof (IHp p1 p0) as H'; rewrite H0 in H';\n          rewrite H1 in H'; simpl in H'; apply (double_incl _ _ H')\n        ).\n        + destruct (BinPos.Pos.land p2 p1) eqn: H'; reflexivity.\n        + pose proof (IHp p1 p0) as H'. rewrite H0 in H'.\n          rewrite H1 in H'. simpl in H'. apply (succ_double_incl _ _ H').\n    - generalize dependent p0. generalize dependent p1.\n      induction p; destruct p0; destruct p1; auto; simpl;\n          try (\n            destruct (BinPos.Pos.land p p0) eqn:H1; try reflexivity; simpl; \n            destruct (BinPos.Pos.land p0 p1) eqn:H1'; try reflexivity;\n            pose proof (IHp p1 p0) as H; simpl in H; rewrite H1 in H; rewrite H1' in H;\n            simpl in H;\n            try (assert (Z: 0%N = BinPos.Pos.Ndouble 0%N); try reflexivity; rewrite Z);\n            apply double_incl; apply H\n          ).\n        + destruct (BinPos.Pos.land p p0) eqn:H1;\n            destruct (BinPos.Pos.land p0 p1) eqn:H1'; simpl; try reflexivity.\n            * destruct (BinPos.Pos.land p p2) eqn:H1''; try reflexivity.\n            * destruct (BinPos.Pos.land p2 p1) eqn:H2. reflexivity.\n              (* assert (con: (BinPos.Pos.land (pos (BinPos.Pos.land p p0)) p1) = 0%N). *)\n              simpl in IHp. pose proof (IHp p1 p0) as H. rewrite H1' in H.\n              rewrite H1 in H. simpl in H. apply emp_min in H. rewrite H2 in H.\n              inversion H.\n            * simpl in IHp. pose proof (IHp p1 p0) as H.\n              rewrite H1 in H. rewrite H1' in H. simpl in H.\n              apply succ_double_incl. apply H.\n        + destruct (BinPos.Pos.land p0 p1) eqn:H1; simpl; try reflexivity.\nQed.\n\nLemma incl_union_inv : forall s1 s2 s3, s1 ⊆ s2 -> s1 ∪ s3 ⊆ s2 ∪ s3.\nProof.\n  intros s1 s2 s3 s1I2. apply union_lub2.\n    - apply (incl_transitive _ s2).\n      + apply s1I2.\n      + apply union_lub1.\n    - rewrite union_comm. apply union_lub1.\nQed.\n\nLemma incl_intersection_inv : forall s1 s2 s3, s1 ⊆ s2 -> s3 ∩ s1 ⊆ s3 ∩ s2.\nProof.\n  intros s1 s2 s3 s1I2. apply intersection_glb2.\n    - rewrite intersection_comm. apply intersection_glb1.\n    - apply (incl_transitive _ s1).\n      + apply intersection_glb1.\n      + apply s1I2.\nQed.\n\nDefinition mem_union : forall n s1 s2, n ∈ s1 -> n ∈ (s1 ∪ s2) :=\n  fun n s1 s2 (nIs1 : n ∈ s1) =>\n    proj1 (mem_incl _ _) (union_lub1 _ _) _ nIs1.\n\nLemma unioun_mem : forall n s1 s2, n ∈ (s1 ∪ s2) -> n ∈ s1 \\/ n ∈ s2.\nProof.\n  destruct s1; destruct s2; auto.\n  generalize dependent p0. generalize dependent n.\n  induction p; destruct p0; destruct n; auto; simpl;\n    pose proof (IHp n p0) as H; simpl in H; apply H.\nQed.\n\nLemma mem_intersection : forall n s1 s2, n ∈ s1 /\\ n ∈ s2 -> n ∈ (s1 ∩ s2).\nProof.\n  intros n s1 s2 [nIs1 nIs2].\n  destruct s1; destruct s2; auto.\n  generalize dependent p0. generalize dependent n.\n  induction p; destruct p0; destruct n; auto; simpl;\n    intros nIs2; inversion nIs1; inversion nIs2;\n    try (\n      pose proof (IHp n H0 p0 H1) as H; simpl in H;\n      destruct (BinPos.Pos.land p p0);\n      inversion H;\n      simpl; apply H\n    ).\n    destruct (BinPos.Pos.land p p0); try reflexivity.\nQed.\n\nDefinition intersection_mem : forall n s1 s2, n ∈ (s1 ∩ s2) -> n ∈ s2 :=\n  fun n s1 s2 (nIi : n ∈ (s1 ∩ s2)) =>\n    proj1 (mem_incl _ _) (intersection_glb1 _ _) _ nIi.\n\nLemma pos_card_nonzero : forall p, pos_cardinality p <> 0%nat.\nProof.\n  induction p; simpl.\n    - intros cont. inversion cont.\n    - exact IHp.\n    - intros cont. inversion cont.\nQed.\n\nLemma empty_card : # ∅ = 0%nat. Proof. reflexivity. Qed.\n\nLemma card_empty : forall s, # s = 0%nat -> s = ∅.\nProof.\n  destruct s.\n    - reflexivity.\n    - destruct p; simpl;\n        intros cont;\n        try (apply pos_card_nonzero in cont);\n        inversion cont.\nQed.\n\nLemma singleton_nonemp : forall n, {{n}} <> ∅.\nProof. induction n; intros H; inversion H. Qed.\n\nLemma singleton_card : forall n, #{{ n }} = 1%nat.\nProof.\n  induction n.\n    - reflexivity.\n    - destruct n.\n      + reflexivity.\n      + simpl in *. apply IHn.\nQed.\n\nLemma card_incl : forall s1 s2, s1 ⊆ s2 -> Nat.leb (# s1) (# s2).\nProof.\n\n  destruct s1; destruct s2; auto.\n    - intros con. inversion con.\n    - generalize dependent p0.\n      induction p; destruct p0; auto; intros H; inversion H;\n        pose proof (IHp p0) as H'; simpl in H';\n        try (apply (proj2 (Arith.PeanoNat.Nat.leb_le _ _) (le_S _ _ (proj1 (Arith.PeanoNat.Nat.leb_le _ _) (H' H)))));\n        apply H'; apply H.\nQed.\n\nDefinition card_union_leb_intersection :\n  forall s1 s2, Nat.leb (# (s1 ∩ s2)) (# (s1 ∪ s2)) :=\n    fun s1 s2 => card_incl _ _ (intersection_incl_union _ _).\n\n\nLemma card_land_plus : forall p1 p2,\n  Nat.leb (# (BinPos.Pos.land p1 p2)) (pos_cardinality p1 + pos_cardinality p2).\nProof.\n  intros. apply PeanoNat.Nat.leb_le. apply Plus.le_plus_trans. apply PeanoNat.Nat.leb_le.\n  assert (A: pos_cardinality p1 = # (pos p1)). { reflexivity. }\n  rewrite A.\n  apply card_incl.\n  assert (B: BinPos.Pos.land p1 p2 = p1 ∩ p2). { reflexivity. }\n  rewrite B.\n  rewrite intersection_comm.\n  apply intersection_glb1.\nQed.\n\nHint Resolve PeanoNat.Nat.sub_0_r.\n\nLemma card_union : forall s1 s2,\n  # (s1 ∪ s2) = ((# s1) + (# s2) - # (s1 ∩ s2))%nat.\nProof.\n  destruct s1; destruct s2; auto.\n    - simpl. rewrite PeanoNat.Nat.add_0_r. auto.\n    - generalize dependent p0.\n      induction p; destruct p0; auto; simpl;\n        try (\n          destruct (BinPos.Pos.lor p p0) eqn:H1;\n          destruct (BinPos.Pos.land p p0) eqn:H2; simpl;\n          pose proof (IHp p0) as H; simpl in H;\n          rewrite H1 in H; rewrite H2 in H; simpl in H;\n          try (\n            destruct (pos_cardinality p2) eqn:H';\n            try (rewrite H' in H); simpl in H\n          );\n          try (\n            pose proof (card_land_plus p p0) as less;\n            rewrite H2 in less; simpl in less;\n            rewrite H;\n            try (\n              rewrite <- plus_n_Sm;\n              rewrite (PeanoNat.Nat.sub_succ_l _ _ (proj1 (PeanoNat.Nat.leb_le _ _) less))\n            );\n            try (\n              rewrite H' in less;\n              rewrite PeanoNat.Nat.sub_succ_r;\n              rewrite (PeanoNat.Nat.succ_pred _\n                        (PeanoNat.Nat.sub_gt _ _\n                          (proj1 (PeanoNat.Nat.le_succ_l _ _) (\n                            proj1 (PeanoNat.Nat.leb_le _ _) less\n                          ))\n                        )\n              )\n            );\n            try reflexivity\n          );\n          try (rewrite <- PeanoNat.Nat.add_succ_comm; simpl);\n          try (rewrite PeanoNat.Nat.sub_0_r in H; rewrite H; reflexivity);\n          try reflexivity\n        );\n        try (rewrite PeanoNat.Nat.sub_0_r);\n        try (rewrite PeanoNat.Nat.add_1_r); try reflexivity.\n  \n      destruct (pos_cardinality p1) eqn:Hh; auto.\n      rewrite PeanoNat.Nat.sub_succ_r.\n      rewrite PeanoNat.Nat.sub_succ_r in H.\n      assert (what: (0 < (pos_cardinality p + pos_cardinality p0 - n))%nat). {\n        unfold lt. rewrite H. apply PeanoNat.Nat.le_pred_l.\n      }\n      apply (PeanoNat.Nat.succ_pred_pos _ what).\nQed.\n\nLemma diff_emp_id : forall s, s \\ ∅ = s.\nProof. destruct s; reflexivity. Qed.\n \nLemma diff_le : forall s1 s2, s1 \\ s2 ⊆ s1.\nProof.\n  destruct s1; destruct s2;\n    try reflexivity.\n      - rewrite diff_emp_id. apply incl_reflexive.\n      - generalize dependent p0.\n        induction p; destruct p0;\n        try reflexivity; simpl in *;\n        try (apply pos_incl_reflexive);\n        try (pose proof (IHp p0) as IHp0;\n          destruct (BinPos.Pos.ldiff p p0); try reflexivity; try (apply IHp0)).\nQed.\n\nHint Resolve diff_emp_id diff_le.\n\nLemma diff_incl : forall s1 s2, s1 \\ s2 ⊆ s1.\nProof. destruct s1; destruct s2; auto. Qed.\n\nHint Resolve diff_incl.\nHint Resolve double_0 succ_double_0 double_n succ_double_n double_Sn succ_double_Sn.\n\nLemma mem_diff : forall n s1 s2, n ∈ s1 /\\ (n ∈ s2 = false) <-> n ∈ (s1 \\ s2).\nProof.\n  destruct s1; destruct s2; split; simpl; auto;\n    try (\n      intros [H1 H2]; inversion H1; inversion H2;\n      try (apply H1)\n    );\n    try (intros H; inversion H).\n    - clear H1 H3.\n      generalize dependent p0. generalize dependent n.\n      induction p; destruct p0; destruct n; simpl; auto;\n        intros H; inversion H.\n      inversion H0.\n    - clear H1. generalize dependent p0. generalize dependent n.\n      induction p; destruct p0; destruct n; simpl; auto;\n        intros H; try (rewrite double_0 in H); inversion H.\n      split; auto.\nQed.\n\nLemma diff_cut : forall s1 s2, s2 ∩ (s1 \\ s2) = ∅.\nProof.\n  intros. apply extensionality.\n    - apply mem_incl. intros n H.\n      pose proof (intersection_mem _ _ _ H) as nId.\n      rewrite intersection_comm in H.\n      pose proof (intersection_mem _ _ _ H) as nI2.\n      apply mem_diff in nId as [_ nNI2].\n      rewrite nNI2 in nI2. inversion nI2.\n    - apply emp_minimum.\nQed.\n\nLemma incl_diff_inv1 : forall s1 s2 s3, s1 ⊆ s2 -> s1 \\ s3 ⊆ s2 \\ s3.\nProof.\n  destruct s1; destruct s2; destruct s3; auto.\n    - intros con. inversion con.\n    - generalize dependent p0. generalize dependent p1.\n      induction p; destruct p0; destruct p1; auto; try reflexivity;\n        try (intros H; inversion H);\n        try (apply double_incl);\n        try (apply succ_double_incl);\n        try (apply double_succ_double_incl);\n        try (apply (IHp p1 p0 H)).\n      + simpl. destruct (BinPos.Pos.ldiff p0 p1) eqn:H'; reflexivity.\nQed.\n\nLemma incl_diff_inv2 : forall s1 s2 s3, s1 ⊆ s2 -> s3 \\ s2 ⊆ s3 \\ s1.\nProof.\n  destruct s1; destruct s2; destruct s3; auto.\n    - intros con. inversion con.\n    - generalize dependent p0. generalize dependent p1.\n      induction p; destruct p0; destruct p1;\n        try (intros H; inversion H);\n        try (apply double_incl);\n        try (apply succ_double_incl);\n        try (apply double_succ_double_incl);\n        try (apply (IHp p1 p0 H));\n        auto.\n      + simpl. destruct (BinPos.Pos.ldiff p1 p0) eqn:H'.\n        * reflexivity.\n        * simpl. pose proof (diff_le p1 p0) as H1. simpl in H1.\n          rewrite H' in H1. apply H1.\nQed.\n\n\nHint Resolve intersection_glb1 intersection_glb2.\n\nLemma diff_intersection : forall s1 s2, s1 \\ s2 = s1 \\ s1 ∩ s2.\nProof.\n  destruct s1; destruct s2; auto.\n  apply extensionality.\n    - apply (incl_diff_inv2 (p ∩ p0) p0 p (intersection_glb1 p p0)).\n    - generalize dependent p0. induction p; destruct p0; auto; simpl;\n        destruct (BinPos.Pos.land p p0) eqn:H1; simpl;\n        destruct (BinPos.Pos.ldiff p p0) eqn:H2; simpl; try reflexivity;\n        try (destruct (BinPos.Pos.ldiff p p1) eqn:H3; simpl; try reflexivity); \n        try (\n          try (apply emp_min; symmetry; apply double_empty);\n          pose proof (IHp p0) as H; simpl in H;\n          rewrite H1 in H; rewrite H2 in H;\n          try (rewrite H3 in H);\n          try (apply emp_min in H; rewrite <- H; reflexivity);\n          apply H\n        ).\nQed.\n\nLemma diff_emp_incl : forall s1 s2, s1 \\ s2 = ∅ <-> s1 ⊆ s2.\nProof.\n  destruct s1; destruct s2; split; try reflexivity;\n    try (generalize dependent p0); induction p;\n      try (intros H; rewrite diff_emp_id in H; rewrite H; reflexivity);\n      try (intros H; apply emp_min in H; rewrite <- H; reflexivity);\n      destruct p0;\n        try reflexivity;\n        try (intros H; inversion H; simpl in *; rewrite H; reflexivity);\n        intros H;\n        try (apply double_empty in H; apply IHp; apply H);\n        try (apply double_empty; apply IHp in H; apply H);\n        try (apply empty_double; apply IHp; apply H).\n  simpl in *. apply succ_double_nonempty in H. inversion H.\nQed.\n\nLemma diff_semi_comm : forall s1 s2 s3, s1 \\ s2 \\ s3 = s1 \\ s3 \\ s2.\nProof.\n  destruct s1; destruct s2; destruct s3; auto.\n  apply extensionality;\n  generalize dependent p0; generalize dependent p1;\n  induction p; destruct p0; destruct p1; auto; simpl;\n    try (destruct (BinPos.Pos.ldiff p p0) eqn:H1);\n    try (destruct (BinPos.Pos.ldiff p p1) eqn:H2; auto);\n    try (\n      pose proof (IHp p1 p0) as H; simpl in H;\n      rewrite H1 in H; rewrite H2 in H;\n      simpl in H; simpl;\n      try (destruct (BinPos.Pos.ldiff p2 p1); auto);\n      apply H\n    ); try reflexivity; simpl;\n    destruct (BinPos.Pos.ldiff p2 p0) eqn:H3; simpl;\n    try (\n      pose proof (IHp p1 p0) as H; simpl in H;\n      rewrite H1 in H; rewrite H2 in H; simpl in H; apply emp_min in H;\n      rewrite H3 in H; inversion H\n    );\n    reflexivity.\nQed.\n\nHint Resolve mem_intersection mem_diff diff_cut.\n\nLemma diff_relcompl1 : forall s1 s2, (s1 ∩ s2) ∩ (s1 \\ s2) = ∅.\nProof.\n  intros. apply extensionality.\n    - apply (incl_transitive _ (s2 ∩ (s1 \\ s2)) _).\n        + rewrite intersection_comm.\n          rewrite (intersection_comm s1 s2).\n          rewrite intersection_assoc.\n          rewrite (intersection_comm _ s2).\n          rewrite intersection_comm.\n          apply intersection_glb1.\n        + rewrite diff_cut. apply incl_reflexive.\n    - apply emp_minimum.\nQed.\n\nLemma diff_relcompl2 : forall s1 s2, (s1 ∩ s2) ∪ (s1 \\ s2) = s1.\nProof.\n  intros. apply extensionality.\n    - pose proof (intersection_glb1 s2 s1) as iI1.\n      rewrite intersection_comm in iI1.\n      pose proof (diff_incl s1 s2) as dI1.\n      apply (union_lub2 _ _ _ iI1 dI1).\n    - apply mem_incl. intros n nI1.\n      destruct (n ∈ s2) eqn:nI2.\n        + apply mem_union. apply mem_intersection. split.\n          * apply nI1.\n          * apply nI2.\n        + rewrite union_comm. apply mem_union. apply mem_diff. split.\n          * apply nI1.\n          * apply nI2.\nQed.\n\nLemma card_cut : forall s1 s2, # s1 = ((# (s1 ∩ s2)) + (# (s1 \\ s2)))%nat.\nProof.\n  intros. rewrite <- (diff_relcompl2 s1 s2) at 1.\n  rewrite <- PeanoNat.Nat.sub_0_r.\n  rewrite <- empty_card.\n  rewrite <- (diff_relcompl1 s1 s2).\n  apply card_union.\nQed.\n\nLemma card_incl_diff : forall s1 s2, s2 ⊆ s1 -> # s1 = (# s2 + # (s1 \\ s2))%nat.\nProof.\n  intros s1 s2 s1I2. rewrite <- (intersection_absorb _ _ s1I2) at 1.\n  apply card_cut.\nQed.\n\nLemma card_single_diff : forall s n, n ∈ s -> # s = S (# (s \\ {{n}})).\nProof.\n  intros s n nIs. pose proof (card_incl_diff s {{n}}) as H.\n  rewrite singleton_card in H. simpl in H. apply H.\n  apply (singleton_mem_incl _ _ nIs).\nQed.\n\n(*        \nCheck 1~0~1~0~1.\nCompute (∅ ⊆ ∅).\nCompute (∅ ⊆ 1).\nCompute (1 ⊆ 1).\nCompute (1 ⊆ 1~1).\nCompute (1 ⊆ 1~0).\nCompute (1~1~0 ⊆ 1~0).\nCompute (1~0~1~1~0~1 ⊆ 1~1~0~1~0~1~0~1~1~0~1).\nCompute (1~0~1~1~0~1 ⊆ 1~1~0~1~0~1~0~1~1~0~0).\nCompute (1~0~1~1~1~1 ⊆ 1~1~0~1~0~1~0~1~1~0~1).\nCompute (1~1~0~1~0~1~0~1~1~0~1 ⊆ 1~0~1~1~0~1).\n\n\n\nCompute (cardinality 1~0~1~0~1).\n\n\nCompute (1 ∈ 1~0~1~0~1). (* false *)\n\nCompute (1 ∈ (1~0 ∪ 1~0~1~0~1)). (* true *)\n\n\nCompute (0 ∈ 1~0~1~0~0). (* false *)\n\nCompute (0 ∈ (1 ∪ 1~0~1~0~0)). (* true *)\n\n\nCompute (0 ∈ ∅). (* false *)\n\nCompute (0 ∈ (1 ∪ ∅)). (* true *)\n\nCompute (0 ∈ 1). (* true *)\n*)", "meta": {"author": "TypicalMath", "repo": "subst-interpol", "sha": "ebb2d8b8c0061719a5c82dbb5b40b9825cf08f81", "save_path": "github-repos/coq/TypicalMath-subst-interpol", "path": "github-repos/coq/TypicalMath-subst-interpol/subst-interpol-ebb2d8b8c0061719a5c82dbb5b40b9825cf08f81/Finset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7028391356757274}}
{"text": "Theorem frobenius (A : Set) (p : A -> Prop) (q : Prop):\n  (exists x : A, q /\\ p x) <-> (q /\\ exists x : A, p x).\nProof.\n  split.\n  intros [y [H1 H2]].\n  split.\n  assumption.\n  exists y.\n  assumption.\n  intros [H1 [y H2]].\n  exists y.\n  split.\n  assumption.\n  assumption.\nQed.\n\nParameter A B C : Set.\n\n(* f : A -> B -> C *)\nDefinition curry (f : A * B -> C) := fun a => fun b => f (a, b).\nDefinition uncurry (g : A -> B -> C) := fun p => g (fst p) (snd p).\n\nTheorem prf0 : forall f a b, uncurry (curry f) (a, b)= f (a, b).\nProof.\n  intros.\n  unfold curry, uncurry.\n  simpl.\n  reflexivity.\nQed.\n\nTheorem prf1 : forall g a b, curry (uncurry g) a b = g a b.\nProof.\n  intros.\n  unfold curry, uncurry.\n  simpl.\n  auto.\nQed.\n\n", "meta": {"author": "jxwr", "repo": "coq-exercise", "sha": "7c915a628cbc1efa2e342651cfb218d65e82da1f", "save_path": "github-repos/coq/jxwr-coq-exercise", "path": "github-repos/coq/jxwr-coq-exercise/coq-exercise-7c915a628cbc1efa2e342651cfb218d65e82da1f/coq-ex0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7028391347941155}}
{"text": "(*|\n##################################\nTransitivity of subsequence in Coq\n##################################\n\n:Link: https://stackoverflow.com/q/69797654\n|*)\n\n(*|\nQuestion\n********\n\nI have been working my way through logical foundations and have gotten\nvery stuck on the transitivity of subsequences exercise.\n\nExercise: 2 stars, advanced (subsequence)\n=========================================\n\nA list is a *subsequence* of another list if all of the elements in\nthe first list occur in the same order in the second list, possibly\nwith some extra elements in between. For example,\n\n(Optional, harder) Prove ``subseq_trans`` that subsequence is\ntransitive -- that is, if ``l1`` is a subsequence of ``l2`` and ``l2``\nis a subsequence of ``l3``, then ``l1`` is a subsequence of ``l3``.\nHint: choose your induction carefully!\n\n.. coq:: none\n|*)\n\nRequire Import List.\nImport ListNotations.\n\n(*||*)\n\nInductive subseq : list nat -> list nat -> Prop :=\n| sseq_e (l2 : list nat) : subseq [] l2\n| sseq_m (l1 l2 : list nat) (n : nat) (H: subseq l1 l2) : subseq (n::l1) (n::l2)\n| sseq_nm (l1 l2 : list nat) (n : nat) (H: subseq l1 l2) : subseq l1 (n::l2).\n\nTheorem subseq_trans : forall l1 l2 l3 : list nat,\n    subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3 H H0. induction H.\n  - apply sseq_e.\n  - induction l3.\n    + inversion H0.\n    + inversion H0.\n      * apply sseq_m.\nAbort. (* .none *)\n\n(*|\nI am having trouble getting the right induction hypothesis after\nhaving tried a couple of different approaches. I have tried a number\nof approaches and end up with a situation where, in my assumptions, I\nhave something like ``subseq l2 (x::l3)`` but then I need to prove\n``subseq l2 l3`` which seems like a dead end. Any pointers in the\nright direction would be much appreciated.\n|*)\n\n(*|\nAnswer\n******\n\nThat experience suggests generalizing the induction hypothesis over\n``l3``.\n|*)\n\nTheorem subseq_trans : forall l1 l2 l3 : list nat,\n    subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.\nProof.\n  intros l1 l2 l3 H. generalize dependent l3. induction H; intros l3 H0.\n  - apply sseq_e.\n  - induction l3.\n    + inversion H0.\n    + inversion H0.\n      * specialize (IHsubseq l3 H2). apply (sseq_m l1 l3 a IHsubseq).\n      * specialize (IHl3 H3). apply (sseq_nm (n :: l1) l3 a IHl3).\n  - induction l3.\n    + inversion H0.\n    + inversion H0.\n      * specialize (IHsubseq l3 H2). apply (sseq_nm l1 l3 a IHsubseq).\n      * specialize (IHl3 H3). apply (sseq_nm l1 l3 a IHl3).\nQed.\n", "meta": {"author": "vonavi", "repo": "coq-examples", "sha": "5e76634f5a069db118df57cb869235a9e0b5c30a", "save_path": "github-repos/coq/vonavi-coq-examples", "path": "github-repos/coq/vonavi-coq-examples/coq-examples-5e76634f5a069db118df57cb869235a9e0b5c30a/examples/transitivity-of-subsequence-in-coq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.7027911331560498}}
{"text": "Require Import String.\nRequire Import Ascii.\n\nDefinition L (s : ascii) : Prop := True.\n\nInductive L1 : string -> Prop :=\n| epsilon1 : L1 \"\"\n| cons1 : forall x y, L x -> L1 y -> L1 (String x y).\n\nInductive L2 : string -> Prop :=\n| epsilon2 : L2 \"\"\n| L_e_L2 : forall x, L x -> L2 (String x EmptyString)\n| cons2 : forall x y, L2 x -> L2 y -> L2 (x ++ y).\n\nTheorem eq_L1_L2 : forall s, L1 s -> L2 s.\nProof.\ninduction s. \nconstructor.\nintro.\ninversion H.\napply L_e_L2 in H2.\napply IHs in H3.\nassert ((append (String a EmptyString) s) = (String a s)).\nreflexivity.\nrewrite <- H4.\nconstructor.\nexact H2.\nexact H3.\nQed.\n", "meta": {"author": "jaeem006", "repo": "Semantica", "sha": "fdfdf544dd2d30b2f03a82849d78879762d48811", "save_path": "github-repos/coq/jaeem006-Semantica", "path": "github-repos/coq/jaeem006-Semantica/Semantica-fdfdf544dd2d30b2f03a82849d78879762d48811/repo_seman4_javier_enriquez (1).v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7027911290850534}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra all_fingroup.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** -------------------------------------------- *)\n\n(** #<div class='slide'># \n\n** Lesson 2 MathCompWS ITP'2016 \n#</div># *)\n\n\n(** #<div class='slide'># \n** Big operators\n\n   - a library to manipulate cumulative operators\n   - an encapsulation of the fold function\n*)\n\nSection F.\n\n(*\nFixpoint foldr f z s := if s is x :: s' then f x (foldr f z s') else z.\n*)\n\nDefinition f x := x.*2.\nDefinition g x y := x + y.\nDefinition r := [::1; 2; 3].\nLemma bfold : foldr (g \\o f) 0 r = 12.\nProof.\nrewrite /=.\nrewrite /f.\nrewrite /g.\nby [].\nQed.\n\nEnd F.\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n\n   ** Notation\n\n   - the basic \\big notation\n   - operations on elements of a list\n   - special notations for usual case (\\sum, \\prod, \\bigcap ..) \n*)\n\nLemma bfoldl : \\big[addn/0]_(i <- [::1; 2; 3]) i.*2 = 12.\nProof.\nset bigop := BigOp.bigop.\nrewrite /bigop.\nrewrite big_cons.\nrewrite big_cons.\nrewrite big_cons.\nrewrite big_nil.\nby [].\nQed.\n\nLemma bfoldlm : \\big[muln/1]_(i <- [::1; 2; 3]) i.*2 = 48.\nProof.\nset bigop := BigOp.bigop.\nrewrite /bigop.\nrewrite big_cons.\nrewrite big_cons.\nrewrite big_cons.\nrewrite big_nil.\nby [].\nQed.\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n   ** Range \n   - different ranges are provided\n*)\n\nLemma bfoldl1 : \\sum_(1 <= i < 4) i.*2 = 12.\nProof.\nset bigop := BigOp.bigop.\nrewrite /bigop.\nhave bl := big_ltn.\nhave be := big_geq.\nrewrite bl.\n  rewrite bl.\n    rewrite bl.\n      rewrite be.\n        by [].\n      by [].\n    by [].\n  by [].\nby [].\nQed.\n\nLemma bfoldl2 : \\sum_(i < 4) i.*2 = 12.\nProof.\nset bigop := BigOp.bigop.\nPrint ordinal.\nrewrite /bigop.\nrewrite big_ord_recl.\nCheck lift.\nPrint bump.\nrewrite /=.\nrewrite big_ord_recl.\nrewrite /=.\nrewrite big_ord_recl.\nrewrite big_ord_recl.\nrewrite big_ord0.\nby [].\nQed.\nQed.\n\nLemma bfoldl3 : \\sum_(i : 'I_4) i.*2 = 12.\nProof.\nexact: bfoldl2.\nQed.\n\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n   ** Filtering \n   - selecting some elements of the range \n*)\n\nLemma bfoldl4 : \\sum_(i <- [::1; 2; 3; 4; 5; 6] | ~~ odd i) i = 12.\nProof.\nset bigop := BigOp.bigop.\nrewrite /bigop.\nhave bp0 := big_pred0.\nhave bC := big_hasC.\nhave bmc := big_mkcond.\npose x :=  \\sum_(i < 8 | ~~ odd i) i.\npose y :=  \\sum_(0 <= i < 8 | ~~ odd i) i.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_cons.\nrewrite /=.\nrewrite big_nil.\nby [].\nQed.\n\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n   ** Switching range\n   - changing representation (big_nth, big_mkord).\n*)\n\nLemma bswitch :  \n  \\sum_(i <- [::1; 2; 3]) i.*2 = \\sum_(i < 3) (nth 0 [::1; 2; 3] i).*2.\nProof.\nhave bn := big_nth.\nrewrite (big_nth 0).\nrewrite /=.\nhave bm := big_mkord.\nrewrite big_mkord.\nby [].\nQed.\n\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n   ** Few examples from the library\n*)\n\n(** \n   - prime.v\n*)\n\nCheck divn_count_dvd.\nCheck logn_count_dvd.\nCheck dvdn_sum.\nCheck totient_count_coprime.\nCheck totientE.\n\n\n(**- poly.v\n*)\n\nCheck horner_sum.\nCheck nderiv_taylor.\n\n(**\n\n   - matrix.v\n*)\n\nCheck expand_cofactor.\nCheck expand_det_row.\n\n(** \n   - vector.v\n*)\n\nCheck sumv_sup.\nCheck freeP.\n\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n  ** Big operators and equality\n  - replacing function and/or predicate \n *)\n\nLemma beql : \n  \\sum_(i < 4 | odd i || ~~ odd i) i.*2 =  \\sum_(i < 4) i.*2.\nProof.\nhave ebl := eq_bigl.\napply: eq_bigl  => /=.\nmove=> n.\nby case: odd.\nQed.\n\nLemma beqr : \n  \\sum_(i < 4) i.*2 = \\sum_(i < 4) (i + i).\nProof.\nhave ebr := eq_bigr.\napply: eq_bigr.\nrewrite /=.\nmove=> n _.\nrewrite addnn.\nby [].\nQed.\n\nLemma beq : \n  \\sum_(i < 4 | odd i || ~~ odd i) i.*2 = \\sum_(i < 4) (i + i).\nProof.\nhave eb := eq_big.\napply: eq_big => [n|i Hi]; first by case: odd.\nby rewrite addnn.\nQed.\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n  ** Monoid structure\n  - regrouping thanks to associativity\n *)\n\nLemma bmon1 : \\sum_(i <- [::1; 2; 3]) i.*2 = 12.\nProof.\nhave bc := big_cat.\nrewrite -[[::1; 2; 3]]/([::1] ++ [::2; 3]).\nrewrite big_cat.\nrewrite /=.\nrewrite !big_cons !big_nil.\nby [].\nQed.\n\nLemma bmon2 : \\sum_(1 <= i < 4) i.*2 = 12.\nProof.\nhave bcn := big_cat_nat.\nrewrite (big_cat_nat _ _ _ (isT : 1 <= 2)).\n  rewrite /=.\n  rewrite big_ltn //=.\n  rewrite big_geq //.\n  by rewrite 2?big_ltn //= big_geq.\nby [].\nQed.\n\nLemma bmon3 : \\sum_(i < 4) i.*2 = 12.\nProof.\nhave borl := big_ord_recl.\nhave borr := big_ord_recr.\nrewrite big_ord_recr.\nrewrite /=.\nrewrite !big_ord_recr //=.\nrewrite big_ord0.\nby [].\nQed.\n\nLemma bmon4 : \\sum_(i < 8 | ~~ odd i) i = 12.\nProof.\nhave H := big_mkcond.\nrewrite big_mkcond.\nrewrite /=.\nrewrite !big_ord_recr /=.\nrewrite big_ord0.\nby [].\nQed.\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n  ** Abelian Monoid structure\n  - dispatching thanks to communitativity\n *)\n\n\nLemma bab : \\sum_(i < 4) i.*2 = 12.\nProof.\nhave bd1 := bigD1.\npose x := Ordinal (isT : 2 < 4).\nrewrite (bigD1 x).\n  rewrite /=.\n  rewrite big_mkcond /=.\n  rewrite !big_ord_recr /= big_ord0.\n  by [].\nby [].\nQed.\n\nLemma bab1 : \\sum_(i < 4) (i + i.*2) = 18.\nProof.\nhave H := big_split.\nrewrite big_split /=.\nrewrite !big_ord_recr ?big_ord0 /=.\nby [].\nQed.\n\nLemma bab2 :\n  \\sum_(i < 3) \\sum_(j < 4) (i + j) = \\sum_(i < 4) \\sum_(j < 3) (i + j).\nProof.\nhave H := exchange_big.\nhave H1 := reindex_inj.\nrewrite exchange_big.\nrewrite /=.\napply: eq_bigr.\nmove=> i _.\napply: eq_bigr.\nmove=>   j _.\nby rewrite addnC.\nQed.\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n  ** Distributivity\n  - exchanging sum and product \n *)\n\nLemma bab3 : \\sum_(i < 4) (2 * i) = 2 * \\sum_(i < 4) i.\nProof.\nhave H := big_distrr.\nby rewrite big_distrr.\nQed.\n\nLemma bab4 : \n  (\\prod_(i < 3) \\sum_(j < 4) (i ^ j)) = \n  \\sum_(f : {ffun 'I_3 -> 'I_4}) \\prod_(i < 3) (i ^ (f i)).\nProof.\nhave bdb := big_distr_big.\nhave bdbd := big_distr_big_dep.\nrewrite  (big_distr_big ord0).\nrewrite /=.\napply: eq_bigl.\nmove=> f.\nrewrite /=.\napply/forallP.\nrewrite /=.\nby [].\nQed.\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n  ** Property, Relation and Morphism\n   - higher-order properties \n *)\n\nLemma bap n : ~~ odd (\\sum_(i < n) i.*2). \nProof.\nhave bi := big_ind.\nhave bi2 := big_ind2.\nhave bm := big_morph.\nelim/big_ind: _.\n- by [].\n- move=> x y.\n  rewrite odd_add.\n  case: odd.\n     by [].\n  by [].\nrewrite /=.\nmove=> i _.\nby rewrite odd_double.\nQed.\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n     ** Leibniz Triangle\n   *)\n\nDefinition leibnizn m n := m.+1 *  'C(m, n).\n\nNotation \"''L' ( n , m )\" := (leibnizn n m)\n  (at level 8, format \"''L' ( n ,  m )\") : nat_scope.\n\nLemma leibn0 n : 'L(n, 0) = n.+1.\nProof. by rewrite /leibnizn bin0 muln1. Qed.\n\nLemma leibnn n : 'L(n, n) = n.+1.\nProof. by rewrite /leibnizn binn muln1. Qed.\n\nLemma leibn_small m n : m < n -> 'L(m, n) = 0.\nProof. by move=> Hmn; rewrite /leibnizn bin_small ?muln0. Qed.\n\nLemma leibn_sub m n :  n <= m -> 'L(m, m - n) = 'L(m, n).\nProof. by move=> Lnm; rewrite /leibnizn bin_sub. Qed.\n \nLemma leibn_gt0 m n : n <= m -> 0 < 'L(m, n).\nProof. by move=> Lnm; rewrite /leibnizn muln_gt0 bin_gt0. Qed.\n\nLemma bin_up m n : m.+1 * 'C(m, n) = (m.+1 - n) * 'C(m.+1, n).\nProof.\nelim: m n => [|m IHm] [|n] //.\ncase: (leqP m.+1 n)=> [H|H].\n  by apply/eqP; rewrite bin_small // muln0 eq_sym muln_eq0 subn_eq0 ltnS H.\nrewrite subSS mulSn {2}binS mulnDr !IHm addnA subSS -mulSn -subSn //.\nby rewrite -mulnDr -binS.\nQed.\n\nLemma leibn_up m n : m.+2 * 'L(m, n) = (m.+1 - n) * 'L(m.+1, n).\nProof. by rewrite /leibnizn bin_up mulnCA. Qed.\n\nLemma bin_right m n : n.+1 * 'C(m.+1, n.+1) = (m.+1 - n) * 'C(m.+1, n).\nProof.\nelim: m n => [|m IHm] [|n] //; first by rewrite bin0 bin1 muln1 mul1n.\nrewrite [in RHS]binS subSS mulnDr -IHm -mulnDl -mul_Sm_binm.\ncase: (leqP n m.+1)=> [H|H]; first by rewrite addnS subnK.\nby rewrite bin_small ?muln0 // ltnW.\nQed.\n\nLemma leibn_right m n : n.+1 * 'L(m.+1, n.+1) = (m.+1 - n) * 'L(m.+1, n).\nProof. by rewrite /leibnizn mulnCA bin_right mulnCA. Qed.\n\nLemma leibnS m n : \n  'L(m.+1, n.+1) * 'L(m.+1, n) = 'L(m, n) * ('L(m.+1, n.+1) + 'L(m.+1, n)).\nProof.\ncase: (leqP n m.+1) => H; last first.\n  by rewrite leibn_small 1?ltnW // leibn_small.\napply/eqP.\nhave /eqn_pmul2l<- : m.+2 * n.+1 > 0 by [].\napply/eqP.\nrewrite -[_.+2 * _ * _]mulnA [n.+1 * _]mulnA.\nrewrite [in RHS]mulnCA -[_.+2 * _ * _ in RHS]mulnA.\nrewrite mulnDr leibn_right.\nrewrite mulnDr [m.+2 * (_.+1 * _) in RHS] mulnCA.\nrewrite -{1}leibn_up [in RHS]mulnC mulnDl.\nrewrite -mulnA ['L(_,_) * _]mulnC 2!mulnA.\nrewrite -mulnDl; congr (_ * _).\nrewrite [X in _ = X + _]mulnA [X in _ = _ + X]mulnA.\nrewrite -mulnDl; congr (_ * _).\nby rewrite [_ * _.+2 in RHS]mulnC -mulnDr addnS subnK.\nQed.\n\nLemma lcmn_swap a b c :\n    a * c = b * (a + c) -> lcmn b c = lcmn a c.\nProof.\ncase: a => [|a].\n  by move/eqP; rewrite add0n eq_sym muln_eq0=> /orP[] /eqP->; rewrite !(lcm0n,lcmn0). \ncase: b => [|b].\n  by move/eqP; rewrite muln_eq0=> /orP[] /eqP->; rewrite !(lcm0n,lcmn0).\ncase: c => [|c H].\n  by move/eqP; rewrite addn0 eq_sym muln0 muln_eq0=> /orP[] /eqP->; \n     rewrite !(lcm0n,lcmn0).\napply/eqP.\nhave /eqn_pmul2r<- : a.+1 * gcdn b.+1 c.+1 > 0 by rewrite muln_gt0 gcdn_gt0.\n  rewrite {2}muln_gcdr H [b.+1 * _]mulnC mulnDl gcdnDl.\n  by rewrite mulnCA muln_lcm_gcd -muln_gcdl !mulnA muln_lcm_gcd [X in _ == X]mulnAC.\nQed.\n\nLemma leibn_lcm_swap m n :\n   lcmn 'L(m.+1, n) 'L(m, n) = lcmn 'L(m.+1, n) 'L(m.+1, n.+1).\nProof.\nrewrite ![lcmn 'L(m.+1, n) _]lcmnC.\nby apply/lcmn_swap/leibnS.\nQed.\n\n(** #</div># *)\n\n(** -------------------------------------------- *)\n\n(**  #<div class='slide'>#  \n    ** Lcm bigop\n   *)\n\n\nNotation \"\\lcm_ ( i < n ) F\" :=\n (\\big[lcmn/1%N]_(i < n ) F%N) \n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\lcm_ ( i  <  n  ) '/  '  F ']'\") : nat_scope.\n\nCanonical Structure lcmn_moid : Monoid.law 1 :=\n  Monoid.Law lcmnA lcm1n lcmn1.\nCanonical lcmn_comoid := Monoid.ComLaw lcmnC.\n\nLemma leib_line n i k : lcmn 'L(n.+1, i) (\\lcm_(j < k) 'L(n, i + j)) = \n                   \\lcm_(j < k.+1) 'L(n.+1, i + j).\nProof.\nelim: k i => [i|k1 IH i].\n  by rewrite big_ord_recr !big_ord0 /= lcmn1 lcm1n addn0.\nrewrite big_ord_recl /= addn0.\nrewrite lcmnA leibn_lcm_swap.\nrewrite (eq_bigr (fun j : 'I_k1 => 'L(n, i.+1 + j))).\nrewrite -lcmnA.\nrewrite IH.\nrewrite [RHS]big_ord_recl.\nrewrite addn0; congr (lcmn _ _).\nby apply: eq_bigr => j _; rewrite addnS.\nmove=> j _.\nby rewrite addnS.\nQed.\n\nLemma leib_corner n : \\lcm_(i < n.+1) 'L(i, 0) = \\lcm_(i < n.+1) 'L(n, i).\nProof.\nelim: n => [|n IH]; first by rewrite !big_ord_recr !big_ord0 /=.\nrewrite big_ord_recr /= IH lcmnC.\nrewrite (eq_bigr (fun i : 'I_n.+1 => 'L(n, 0 + i))) //.\nby rewrite leib_line.\nQed.\n\nLemma main_result n : 2^n.-1 <= \\lcm_(i < n) i.+1.\nProof.\ncase: n => [|n /=]; first by rewrite big_ord0.\nhave <-: \\lcm_(i < n.+1) 'L(i, 0) = \\lcm_(i < n.+1) i.+1.\n  by apply: eq_bigr => i _; rewrite leibn0.\nrewrite leib_corner.\nhave -> : forall j,  \\lcm_(i < j.+1) 'L(n, i) = n.+1 *  \\lcm_(i < j.+1) 'C(n, i).\n  elim=> [|j IH]; first by rewrite !big_ord_recr !big_ord0 /= !lcm1n.\n  by rewrite big_ord_recr [in RHS]big_ord_recr /= IH muln_lcmr.\nrewrite (expnDn 1 1) /=  (eq_bigr (fun i : 'I_n.+1 => 'C(n, i))) => \n       [|i _]; last by rewrite !exp1n !muln1.\nhave <- : forall n m,  \\sum_(i < n) m = n * m.\n  by move=> m1 n1; rewrite sum_nat_const card_ord.\napply: leq_sum => i _.\napply: dvdn_leq; last by rewrite (bigD1 i) //= dvdn_lcml.\napply big_ind => // [x y Hx Hy|x H]; first by rewrite lcmn_gt0 Hx.\nby rewrite bin_gt0 -ltnS.\nQed.\n\n(** #</div># *)\n\n(**\n#\n<script>\nalignWithTop = true;\ncurrent = 0;\nslides = [];\nfunction select_current() {\n  for (var i = 0; i < slides.length; i++) {\n    var s = document.getElementById('slideno' + i);\n    if (i == current) {\n      s.setAttribute('class','slideno selected');\n    } else {\n      s.setAttribute('class','slideno');\n    }\n  }\t\n}\nfunction init_slides() {\n  var toolbar = document.getElementById('panel-wrapper');\n  if (toolbar) {\n  var tools = document.createElement(\"div\");\n  var tprev = document.createElement(\"div\");\n  var tnext = document.createElement(\"div\");\n  tools.setAttribute('id','tools');\n  tprev.setAttribute('id','prev');\n  tprev.setAttribute('onclick','prev_slide();');\n  tnext.setAttribute('id','next');\n  tnext.setAttribute('onclick','next_slide();');\n  toolbar.appendChild(tools);\n  tools.appendChild(tprev);\n  tools.appendChild(tnext);\n  \n  slides = document.getElementsByClassName('slide');\n  for (var i = 0; i < slides.length; i++) {\n    var s = document.createElement(\"div\");\n    s.setAttribute('id','slideno' + i);\n    s.setAttribute('class','slideno');\n    s.setAttribute('onclick','goto_slide('+ i +');');\n    s.innerHTML = i;\n    tools.appendChild(s);\n  }\n  select_current();\n  } else {\n  //retry later\n  setTimeout(init_slides,100);\t  \n  }\n}\nfunction on_screen(rect) {\n  return (\n    rect.top >= 0 &&\n    rect.top <= (window.innerHeight || document.documentElement.clientHeight)\n  );\n}\nfunction update_scrolled(){\n  for (var i = 0; i < slides.length; i++) {\n    var rect = slides[i].getBoundingClientRect();\n      if (on_screen(rect)) {\n        current = i;\n        select_current();\t\n    }\n  }\n}\nfunction goto_slide(n) {\n  current = n;\n  var element = slides[current];\n  console.log(element);\n  element.scrollIntoView(alignWithTop);\n  select_current();\n}\nfunction next_slide() {\n  current++;\n  if (current >= slides.length) { current = slides.length - 1; }\n  var element = slides[current];\n  console.log(element);\n  element.scrollIntoView(alignWithTop);\n  select_current();\n}\nfunction prev_slide() {\n  current--;\n  if (current < 0) { current = 0; }\n  var element = slides[current];\n  element.scrollIntoView(alignWithTop);\n  select_current();\n}\nwindow.onload = init_slides;\nwindow.onscroll = update_scrolled;\n</script>\n# *)", "meta": {"author": "gares", "repo": "MathCompWS", "sha": "f06e05bea3694857ce22fc9671efd3971b195d4c", "save_path": "github-repos/coq/gares-MathCompWS", "path": "github-repos/coq/gares-MathCompWS/MathCompWS-f06e05bea3694857ce22fc9671efd3971b195d4c/lesson2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7027911283258781}}
{"text": "(* Exercise 102 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n(* Inverse Double Contrapositive *)\n\nTheorem exercise_102 : (~~A -> ~~B) -> (A -> B).\nProof.\nimp_i a1.\nimp_i a2.\nneg_e' (~B) a3.\nimp_e (~~A).\nhyp a1.\nneg_i A a4.\nhyp a4.\nhyp a2.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop102.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7027889834022859}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := plus x y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj275_coqofml_GcR5Ck.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7027889795196427}}
{"text": "Require Import StateMachines.Preliminaries.\nRequire Import StateMachines.Concepts.\nImport ListNotations.\n\nSection MachineTheory.\nVariable m : Machine.\n\n(* Rest law *)\nDefinition act0 (f : state m → list (input m) → state m)\n:= ∀ s : state m, f s [] = s.\n(* Single impact law *)\nDefinition act1 (f : state m → list (input m) → state m)\n:= ∀ (s : state m) (i : input m), f s [i] = pass m s i.\n(* Cumulative law *)\nDefinition actC (f : state m → list (input m) → state m)\n:= ∀ (s : state m) (u' u'' : list (input m)),\n     f s (u' ++ u'') = f (f s u') u''.\n\nLemma run0 : act0 (run m).\nProof. unfold act0. trivial. Qed.\n\nLemma run1 : act1 (run m).\nProof. unfold act1. trivial. Qed.\n\nLemma runC : actC (run m).\nProof.\n  unfold actC. intros. revert s.\n  induction u' as [| i v IHu']; intro; simpl.\n  - reflexivity.\n  - exact (IHu' (pass m s i)).\nQed.\n\nSection UniquenessTheorem.\nVariable run' : state m → list (input m) → state m. \nHypotheses (H0 : act0 run')\n           (H1 : act1 run')\n           (HC : actC run').\n\nTheorem run_uniqueness : ∀ (s : state m) (u : list (input m)),\n  run' s u = run m s u.\nProof.\n  intros. revert s.\n  induction u as [| i u' IHu]; intro; simpl.\n  - apply H0.\n  - assert (H : [i] ++ u' = i :: u'). { trivial. }\n    rewrite <- H. rewrite (HC s [i] u').\n    rewrite <- (H1 s). apply IHu.\nQed.\nEnd UniquenessTheorem.\nEnd MachineTheory.\n", "meta": {"author": "gzholtkevych", "repo": "state-machines", "sha": "15fdb6deafb960c878a2accefd3d2d1e47e30d87", "save_path": "github-repos/coq/gzholtkevych-state-machines", "path": "github-repos/coq/gzholtkevych-state-machines/state-machines-15fdb6deafb960c878a2accefd3d2d1e47e30d87/MachineTheory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7027889764756488}}
{"text": "(* Exercise 35 *) \n\nRequire Import BenB.\n\nVariable D : Set.\nVariables P Q S T : D -> Prop.\nVariable R : D -> D -> Prop.\n\nTheorem exercise_035 : (forall y, Q y -> ~ exists x, P x) /\\ (forall x, P x) -> (forall y, ~ Q y).\nProof.\nimp_i a1.\nall_i a.\nneg_i (exists x:D, P x) a2.\nimp_e (Q a).\nall_e (forall y:D, Q y -> ~(exists x:D, P x)) a.\ncon_e1 (forall x:D, P x).\nhyp a1.\nhyp a2.\nexi_i a.\nall_e (forall x:D, P x) a.\ncon_e2 (forall y:D, Q y -> ~(exists x:D, P x)).\nhyp a1.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_pred035.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7027506840465073}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(* Zadanie 83. *)\n\nModule Tree83.\n\nInductive Tree a :=\n  | L : a -> Tree a\n  | B : Tree a -> Tree a -> Tree a\n.\n\nClass Functor (F: Type -> Type) := {\n  fmap : forall {A B}, (A -> B) -> (F A -> F B);\n  fmap_pres_comp : forall (A B C: Type) (f: A->B) (g: B->C),\n    fmap (compose g f) = compose (fmap g) (fmap f);\n  fmap_pres_id : forall A, fmap (@id A) = @id (F A);\n}.\n\nDefinition Natural F G {FunF : Functor F} {FunG : Functor G} := forall A, F A -> G A.\n\nInstance Functor_tree : Functor Tree := {\n  fmap := fix rec A X f t :=\n    match t with\n    | L _ a => L X (f a)\n    | B _ l r => B X (rec A X f l) (rec A X f r)\n    end\n}.\nProof.\n  - intros.\n    extensionality l.\n    induction l.\n    + trivial.\n    + simpl.\n      rewrite IHl1.\n      rewrite IHl2.\n      trivial.\n  - intros.\n    extensionality l.\n    induction l.\n    + trivial.\n    + simpl.\n      rewrite IHl1.\n      rewrite IHl2.\n      trivial.\nDefined.\n\nClass Applicative (F: Type -> Type) := {\n  applicative_functor: Functor F;\n  pure : forall {A}, A -> F A;\n  ap : forall {A B}, F (A -> B) -> F A -> F B;\n  pure_id : forall A (v: F A), \n    ap (pure (@id A)) v = v;\n  pure_compose : forall A B C \n    (u:F (B->C)) (v: F (A->B)) (w: F A),\n    ap (ap (ap (pure compose) u) v) w = ap u (ap v w);\n  pure_homo : forall A B (f:A->B) (x:A),\n    ap (pure f) (pure x) = pure (f x);\n  pure_int : forall A B (u : F (A->B)) (y: A),  \n    ap u (pure y) = ap (pure (fun x => x y)) u;\n}.\n\nFixpoint ap_tree {A X} (ff: Tree (A->X)) (fa: Tree A) :=\n  match ff with\n  | L _ f => fmap f fa\n  | B _ l r => B X (ap_tree l fa) (ap_tree r fa)\n  end.\n\nInstance Applicative_Tree : Applicative Tree := {\n  applicative_functor := Functor_tree;\n  pure := L;\n  ap := @ap_tree;\n}.\nProof.\n  - intros.\n    induction v.\n    + trivial.\n    + unfold ap_tree.\n      rewrite fmap_pres_id. \n      unfold id. \n      trivial.\n  - intros A B C u v w.\n    induction u; induction v; induction w.\n    + trivial.\n    + simpl in *.\n      rewrite IHw1.\n      rewrite IHw2.\n      trivial.\n    + simpl in *.\n      rewrite IHv1.\n      rewrite IHv2.\n      trivial.\n    + simpl in *.\n      rewrite IHv1.\n      rewrite IHv2.\n      trivial.\n    + simpl in *.\n      rewrite IHu1.\n      rewrite IHu2.\n      trivial.\n    + simpl in *.\n      rewrite IHu1.\n      rewrite IHu2.\n      trivial.\n    + simpl in *.\n      rewrite IHu1.\n      rewrite IHu2.\n      trivial.\n    + simpl in *.\n      rewrite IHu1.\n      rewrite IHu2.\n      trivial.\n  - intros.\n    simpl in *.\n    trivial.\n  - intros.\n    induction u.\n    + trivial.\n    + simpl in *.\n      rewrite IHu1.\n      rewrite IHu2.\n      trivial.\nDefined.\n\nClass Monad (F: Type -> Type) := {\n  monad_applicative : Applicative F;\n  ret : forall {A}, A -> F A;\n  bind : forall {A X}, F A -> (A -> F X) -> F X;\n  monad_left_id : forall A X (a: A) (f: A -> F X),\n    bind (ret a) f = f a;\n  monad_right_id : forall A (m: F A), bind m ret = m;\n  monad_assoc : forall A X Y (m : F A) (f: A -> F X) (g: X -> F Y),\n    bind (bind m f) g = bind m (fun x => bind (f x) g);\n}.\n\nFixpoint Tree_bind {A X} (fa: Tree A) (f: A -> Tree X) : Tree X :=\n  match fa with\n  | L _ a => f a\n  | B _ l r => B X (Tree_bind l f) (Tree_bind r f)\n  end.\n\nInstance Monad_Tree : Monad Tree := {\n  monad_applicative := Applicative_Tree;\n  ret := L;\n  bind := @Tree_bind;\n}.\nProof.\n  - trivial.\n  - intros.\n    induction m.\n    + trivial.\n    + simpl in *.\n      rewrite IHm1.\n      rewrite IHm2.\n      trivial.\n  - intros.\n    induction m.\n    + trivial.\n    + simpl in *.\n      rewrite IHm1.\n      rewrite IHm2.\n      trivial.\nDefined.\n\nClass MonadJoin (F: Type -> Type) := {\n  monadjoin_applicative : Applicative F;\n  monadjoin_functor : Functor F := applicative_functor;\n  eta : forall {A}, A -> F A;\n  mu : forall {A}, F (F A) -> F A;\n  monadjoin_left_id : forall A (fa: F A), mu (eta fa) = fa;\n  monadjoin_right_id : forall A (fa: F A), \n    mu (fmap eta fa) = fa;\n  monadjoin_assoc : forall A (ma : F (F (F A))),\n    mu (mu ma) = mu (fmap mu ma);\n}.\n\nFixpoint Tree_mu {A} (ma: Tree (Tree A)) : Tree A := \n  match ma with\n  | L _ t => t\n  | B _ l r => B A (Tree_mu l) (Tree_mu r)\n  end.\n\nInstance MonadJoin_Tree : MonadJoin Tree := {\n  eta := L;\n  mu := @Tree_mu;\n}.\nProof.\n  - trivial.\n  - intros.\n    induction fa.\n    + trivial.\n    + simpl in *.\n      rewrite IHfa1.\n      rewrite IHfa2.\n      trivial.\n  - intros.\n    induction ma.\n    + trivial.\n    + simpl in *.\n      rewrite IHma1.\n      rewrite IHma2.\n      trivial.\nDefined.", "meta": {"author": "KatJon", "repo": "CoqProofs", "sha": "d01345015b6e6d137f7b4f2163ae418bc828c86a", "save_path": "github-repos/coq/KatJon-CoqProofs", "path": "github-repos/coq/KatJon-CoqProofs/CoqProofs-d01345015b6e6d137f7b4f2163ae418bc828c86a/Tree83.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7027141947824441}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nSet Implicit Arguments.\n\nModule Chapter2.\n\n  (* Большинство из этого я уже знаю,\n     поэтому буду много пропускать. *)\n\n  Lemma muln_eq0 m n :\n    (m * n == 0) = (m == 0) || (n == 0).\n  Proof.\n    (* Читается как: [m] может быть или [0] или\n       некоторым выражением [m.+1] (для нового [m])*)\n    case: m=> [|m].\n    by [].\n    (* По умолчанию successor case становится 2-ой подцелью\n       (согласно порядку, в котором определены конструкторы\n       соответствующего индуктивного типа). Мы можем это изменить\n       при помощи [; last first] \"суффикса\" *)\n    case: n=> [|k]; last first.\n    - by [].\n    by rewrite muln0.\n  Abort.\n\n  Lemma seq_eq_ext (s1 s2 : seq nat) :\n    size s1 = size s2 ->\n    (forall i : nat, nth 0 s1 i = nth 0 s2 i) ->\n    s1 = s2.\n  Proof.\n  Admitted.\n\n  Lemma size_map (T1 T2 : Type) :\n    forall (f : T1 -> T2) (s : seq T1),\n      size (map f s) = size s.\n\n    (* [forall (f : T1 -> T2) (s : seq T1)]\n       is a syntactic sugar for\n       [forall f : T1 - T2, forall s : seq T1] *)\n  Admitted.\n\n  (* Квантификаторы так же могут быть\n     использованы в теле определений *)\n  Definition commutative (S T : Type) (op : S -> S -> T) :=\n    forall x y, op x y = op y x.\n\n  (* Такие определения позволяют более лаконично\n     записывать вещи вроде *)\n  Lemma addnC : commutative addn. Admitted.\n\n  Check (3 = 3).\n  Check (commutative addn).\n\n  Lemma leqnn n : n <= n. Proof. Admitted.\n\n  Lemma example1 a b : a + b <= a + b.\n  Proof. apply: leqnn. Qed.\n\n  (* The comparison performed by the\n     [apply] tactic is up to computation *)\n  (* Т.е. перед тем, как применить тактику [apply] с указанной леммой,\n     будут выполнены возможные символические вычисления *)\n  Lemma example2 a b : a.+1 + b <= (a + b).+1.\n  Proof. apply: leqnn. Qed.\n\n  (* Чтобы упростить доказательства, мы можем усилить терминатор [by],\n     включив в него некоторые дополнительные леммы.\n     Для этого используется команда [Hint Resolve]: *)\n  Hint Resolve leqnn. (* Это нужно писать рядом с доказанной леммой *)\n\n  (* Теперь предыдущую лемму можно доказать тривиально *)\n  Lemma example3 a b : a + b <= a + b.\n  Proof. by []. Qed.\n\n  Lemma contra' (c b : bool) : (c -> b) -> ~~ b -> ~~ c.\n  Proof.\n    (* rewrite /negb. *)\n    case: b.\n    - by [].\n    case: c.\n    - by [].\n    by [].\n  Qed.\n\n  Lemma negbNE' b : ~~ ~~ b -> b.\n  Proof.\n    rewrite /negb.\n    case: b.\n    - by [].\n    by [].\n  Qed.\n\n  Locate \"%|\".\n  About dvdn.\n  (* Definition dvdn d m := m %% d == 0. *)\n\n  Lemma prime_example1 m p :\n    (* - [p] простое\n       - [p] делит [m! + 1] без остатка *)\n    prime p -> p %| m`! + 1 -> m < p.\n  Proof.\n    move=> H_prime_p.\n    (* Преoбразуем в обратное утверждение *)\n    (* contraLR : forall c b : bool,\n       (~~ c -> ~~ b) -> b -> c *)\n    apply: contraLR.\n\n    (* leqNgt : forall m n : nat,\n       (m <= n) = ~~ (n < m) *)\n    rewrite -leqNgt=> leq_p_m.\n    (* dvdn_addr : forall m d n : nat,\n       d %| m -> (d %| m + n) = (d %| n) *)\n\n    (* Можно переписывать и \"условные равенства\".\n       При попытке это сделать нам придётся доказать предпосылку\n       (создастся\\добавится соответствующая подцель). *)\n    rewrite dvdn_addr.\n\n    (* gtnNdvd n d : 0 < n -> n < d -> (d %| n) = false *)\n    rewrite gtnNdvd=> // //.\n    (* Сразу убрали 2 тривиально-доказуемых неравенства при помощи [// //]. *)\n    - apply: prime_gt1. (* prime_gt1 p : prime p -> 1 < p *)\n      exact: H_prime_p.\n   (* dvdn_fact m n : 0 < m <= n -> m %| n`! *)\n   apply: dvdn_fact.\n   (* Имеем [0 < p <= m], что есть сокращённая запись для\n      [(0 < p) && (p <= m)] *)\n   (* Воспользуемся [prime_gt0 p : prime p -> 0 < p].\n      Нужно это читать как [prime p -> 0 < p = true] *)\n   (* Тут происходит по сути тоже самое, что и в примере выше, где\n      мы переписывали с [dvdn_addr] -- Coq заменит [0 < p] на [true] и\n      попросит нас доказать препосылку [prime p] *)\n   rewrite prime_gt0.\n   - exact: leq_p_m.\n   - exact: H_prime_p.\n  Qed.\n\nEnd Chapter2.\n", "meta": {"author": "vyorkin", "repo": "math-comp-notes", "sha": "897b39bb515231ace5b729c21d8ac1cc67fdc62d", "save_path": "github-repos/coq/vyorkin-math-comp-notes", "path": "github-repos/coq/vyorkin-math-comp-notes/math-comp-notes-897b39bb515231ace5b729c21d8ac1cc67fdc62d/Chapter2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7027141904290346}}
{"text": "\nSection ExtensionalEqualityAndComposition.\n\nVariables A B C D : Type.\n\n(** Exercise 2a *)\n(** [\\o] is a notation for function composition in MathComp, prove that it's associative *)\n\nDefinition compA (f : A -> B) (g : B -> C) (h : C -> D) :\n  (h \\o g) \\o f = h \\o (g \\o f)\n:=\n\n\n(** [=1] stands for extensional equality on unary functions,\n    i.e. [f =1 g] means [forall x, f x = g x].\n    This means it's an equivalence relation, i.e. it's reflexive, symmetric and transitive.\n    Let us prove a number of facts about [=1]. *)\n\n\n(** Exercise: Reflexivity *)\nDefinition eqext_refl :\n  forall (f : A -> B), f =1 f\n:=\n\n(** Exercise: Symmetry *)\nDefinition eqext_sym :\n  forall (f g : A -> B), f =1 g -> g =1 f\n:=\n\n(** Exercise: Transitivity *)\nDefinition eqext_trans :\n  forall (f g h : A -> B), f =1 g -> g =1 h -> f =1 h\n:=\n\n(** Exercise: left congruence *)\nDefinition eq_compl :\n  forall (f g : A -> B) (h : B -> C),\n    f =1 g -> h \\o f =1 h \\o g\n:=\n\n(** Exercise: right congruence *)\nDefinition eq_compr :\n  forall (f g : B -> C) (h : A -> B),\n    f =1 g -> f \\o h =1 g \\o h\n:=\n\nEnd ExtensionalEqualityAndComposition.\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/comp_sci_club-formal_verif_2021/Seminar2-2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.7026858369604507}}
{"text": "(** * Maps: Total and Partial Maps *)\n\n(** Maps (or dictionaries) are ubiquitous data structures, both in\n    software construction generally and in the theory of programming\n    languages in particular; we're going to need them in many places\n    in the coming chapters.  They also make a nice case study using\n    ideas we've seen in previous chapters, including building data\n    structures out of higher-order functions (from [Basics] and\n    [Poly]) and the use of reflection to streamline proofs (from\n    [IndProp]).\n\n    We'll define two flavors of maps: _total_ maps, which include a\n    \"default\" element to be returned when a key being looked up\n    doesn't exist, and _partial_ maps, which return an [option] to\n    indicate success or failure.  The latter is defined in terms of\n    the former, using [None] as the default element. *)\n\n(* ################################################################# *)\n(** * The Coq Standard Library *)\n\n(** One small digression before we start.\n\n    Unlike the chapters we have seen so far, this one does not\n    [Require Import] the chapter before it (and, transitively, all the\n    earlier chapters).  Instead, in this chapter and from now, on\n    we're going to import the definitions and theorems we need\n    directly from Coq's standard library stuff.  You should not notice\n    much difference, though, because we've been careful to name our\n    own definitions and theorems the same as their counterparts in the\n    standard library, wherever they overlap. *)\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(** Documentation for the standard library can be found at\n    http://coq.inria.fr/library/.  \n\n    The [SearchAbout] command is a good way to look for theorems \n    involving objects of specific types. *)\n\n(* ################################################################# *)\n(** * Identifiers *)\n\n(** First, we need a type for the keys that we use to index into our\n    maps.  For this purpose, we again use the type [id] from the\n    [Lists] chapter.  To make this chapter self contained, we repeat\n    its definition here, together with the equality comparison\n    function for [id]s and its fundamental property. *)\n\nInductive id : Type :=\n  | Id : nat -> id.\n\nDefinition beq_id id1 id2 :=\n  match id1,id2 with\n    | Id n1, Id n2 => beq_nat n1 n2\n  end.\n\nTheorem beq_id_refl : forall id, true = beq_id id id.\nProof.\n  intros [n]. simpl. rewrite <- beq_nat_refl.\n  reflexivity. Qed.\n\n(** The following useful property of [beq_id] follows from an\n    analogous lemma about numbers: *)\n\nTheorem beq_id_true_iff : forall id1 id2 : id,\n  beq_id id1 id2 = true <-> id1 = id2.\nProof.\n   intros [n1] [n2].\n   unfold beq_id.\n   rewrite beq_nat_true_iff.\n   split.\n   - (* -> *) intros H. rewrite H. reflexivity.\n   - (* <- *) intros H. inversion H. reflexivity.\nQed.\n\n(** Similarly: *)\n\nTheorem beq_id_false_iff : forall x y : id,\n  beq_id x y = false\n  <-> x <> y.\nProof.\n  intros x y. rewrite <- beq_id_true_iff.\n  rewrite not_true_iff_false. reflexivity. Qed.\n\n(** This useful variant follows just by rewriting: *)\n\nTheorem false_beq_id : forall x y : id,\n   x <> y\n   -> beq_id x y = false.\nProof.\n  intros x y. rewrite beq_id_false_iff.\n  intros H. apply H. Qed.\n\n(* ################################################################# *)\n(** * Total Maps *)\n\n(** Our main job in this chapter will be to build a definition of\n    partial maps that is similar in behavior to the one we saw in the\n    [Lists] chapter, plus accompanying lemmas about their behavior.\n\n    This time around, though, we're going to use _functions_, rather\n    than lists of key-value pairs, to build maps.  The advantage of\n    this representation is that it offers a more _extensional_ view of\n    maps, where two maps that respond to queries in the same way will\n    be represented as literally the same thing (the same function),\n    rather than just \"equivalent\" data structures.  This, in turn,\n    simplifies proofs that use maps.\n\n    We build partial maps in two steps.  First, we define a type of\n    _total maps_ that return a default value when we look up a key\n    that is not present in the map. *)\n\nDefinition total_map (A:Type) := id -> A.\n\n(** Intuitively, a total map over an element type [A] _is_ just a\n    function that can be used to look up [id]s, yielding [A]s.\n\n    The function [t_empty] yields an empty total map, given a default\n    element; this map always returns the default element when applied\n    to any id. *)\n\nDefinition t_empty {A:Type} (v : A) : total_map A :=\n  (fun _ => v).\n\n(** More interesting is the [update] function, which (as before) takes\n    a map [m], a key [x], and a value [v] and returns a new map that\n    takes [x] to [v] and takes every other key to whatever [m] does. *)\n\nDefinition t_update {A:Type} (m : total_map A)\n                    (x : id) (v : A) :=\n  fun x' => if beq_id x x' then v else m x'.\n\n(** This definition is a nice example of higher-order programming.\n    The [t_update] function takes a _function_ [m] and yields a new\n    function [fun x' => ...] that behaves like the desired map.\n\n    For example, we can build a map taking [id]s to [bool]s, where [Id\n    3] is mapped to [true] and every other key is mapped to [false],\n    like this: *)\n\nDefinition examplemap :=\n  t_update (t_update (t_empty false) (Id 1) false)\n           (Id 3) true.\n\n(** This completes the definition of total maps.  Note that we don't\n    need to define a [find] operation because it is just function\n    application! *)\n\nExample update_example1 : examplemap (Id 0) = false.\nProof. reflexivity. Qed.\n\nExample update_example2 : examplemap (Id 1) = false.\nProof. reflexivity. Qed.\n\nExample update_example3 : examplemap (Id 2) = false.\nProof. reflexivity. Qed.\n\nExample update_example4 : examplemap (Id 3) = true.\nProof. reflexivity. Qed.\n\n(** To use maps in later chapters, we'll need several fundamental\n    facts about how they behave.  Even if you don't work the following\n    exercises, make sure you thoroughly understand the statements of\n    the lemmas!  (Some of the proofs require the functional\n    extensionality axiom, which is discussed in the [Logic]\n    chapter and included in the Coq standard library.) *)\n\n(** **** Exercise: 1 star, optional (t_apply_empty)  *)\n(** First, the empty map returns its default element for all keys: *)\nLemma t_apply_empty:  forall A x v, @t_empty A v x = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_eq)  *)\n(** Next, if we update a map [m] at a key [x] with a new value [v]\n    and then look up [x] in the map resulting from the [update], we\n    get back [v]: *)\n\nLemma t_update_eq : forall A (m: total_map A) x v,\n  (t_update m x v) x = v.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_neq)  *)\n(** On the other hand, if we update a map [m] at a key [x1] and then\n    look up a _different_ key [x2] in the resulting map, we get the\n    same result that [m] would have given: *)\n\nTheorem t_update_neq : forall (X:Type) v x1 x2\n                         (m : total_map X),\n  x1 <> x2 ->\n  (t_update m x1 v) x2 = m x2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 2 stars, optional (t_update_shadow)  *)\n(** If we update a map [m] at a key [x] with a value [v1] and then\n    update again with the same key [x] and another value [v2], the\n    resulting map behaves the same (gives the same result when applied\n    to any key) as the simpler map obtained by performing just\n    the second [update] on [m]: *)\n\nLemma t_update_shadow : forall A (m: total_map A) v1 v2 x,\n    t_update (t_update m x v1) x v2\n  = t_update m x v2.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** For the final two lemmas about total maps, it's convenient to use\n    the reflection idioms introduced in chapter [IndProp].  We begin\n    by proving a fundamental _reflection lemma_ relating the equality\n    proposition on [id]s with the boolean function [beq_id]. *)\n\n(** **** Exercise: 2 stars (beq_idP)  *)\n(** Use the proof of [beq_natP] in chapter [IndProp] as a template to\n    prove the following: *)\n\nLemma beq_idP : forall x y, reflect (x = y) (beq_id x y).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** Now, given [id]s [x1] and [x2], we can use the [destruct (beq_idP\n    x1 x2)] to simultaneously perform case analysis on the result of\n    [beq_id x1 x2] and generate hypotheses about the equality (in the\n    sense of [=]) of [x1] and [x2]. *)\n\n(** **** Exercise: 2 stars (t_update_same)  *)\n(** Using the example in chapter [IndProp] as a template, use\n    [beq_idP] to prove the following theorem, which states that if we\n    update a map to assign key [x] the same value as it already has in\n    [m], then the result is equal to [m]: *)\n\nTheorem t_update_same : forall X x (m : total_map X),\n  t_update m x (m x) = m.\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(** **** Exercise: 3 stars, recommended (t_update_permute)  *)\n(** Use [beq_idP] to prove one final property of the [update]\n    function: If we update a map [m] at two distinct keys, it doesn't\n    matter in which order we do the updates. *)\n\nTheorem t_update_permute : forall (X:Type) v1 v2 x1 x2\n                             (m : total_map X),\n  x2 <> x1 ->\n    (t_update (t_update m x2 v2) x1 v1)\n  = (t_update (t_update m x1 v1) x2 v2).\nProof.\n  (* FILL IN HERE *) Admitted.\n(** [] *)\n\n(* ################################################################# *)\n(** * Partial maps *)\n\n(** Finally, we define _partial maps_ on top of total maps.  A partial\n    map with elements of type [A] is simply a total map with elements\n    of type [option A] and default element [None]. *)\n\nDefinition partial_map (A:Type) := total_map (option A).\n\nDefinition empty {A:Type} : partial_map A :=\n  t_empty None.\n\nDefinition update {A:Type} (m : partial_map A)\n                  (x : id) (v : A) :=\n  t_update m x (Some v).\n\n(** We can now lift all of the basic lemmas about total maps to\n    partial maps.  *)\n\nLemma apply_empty : forall A x, @empty A x = None.\nProof.\n  intros. unfold empty. rewrite t_apply_empty.\n  reflexivity.\nQed.\n\nLemma update_eq : forall A (m: partial_map A) x v,\n  (update m x v) x = Some v.\nProof.\n  intros. unfold update. rewrite t_update_eq.\n  reflexivity.\nQed.\n\nTheorem update_neq : forall (X:Type) v x1 x2\n                       (m : partial_map X),\n  x2 <> x1 ->\n  (update m x2 v) x1 = m x1.\nProof.\n  intros X v x1 x2 m H.\n  unfold update. rewrite t_update_neq. reflexivity.\n  apply H. Qed.\n\nLemma update_shadow : forall A (m: partial_map A) v1 v2 x,\n  update (update m x v1) x v2 = update m x v2.\nProof.\n  intros A m v1 v2 x1. unfold update. rewrite t_update_shadow.\n  reflexivity.\nQed.\n\nTheorem update_same : forall X v x (m : partial_map X),\n  m x = Some v ->\n  update m x v = m.\nProof.\n  intros X v x m H. unfold update. rewrite <- H.\n  apply t_update_same.\nQed.\n\nTheorem update_permute : forall (X:Type) v1 v2 x1 x2\n                                (m : partial_map X),\n  x2 <> x1 ->\n    (update (update m x2 v2) x1 v1)\n  = (update (update m x1 v1) x2 v2).\nProof.\n  intros X v1 v2 x1 x2 m. unfold update.\n  apply t_update_permute.\nQed.\n\n(** $Date: 2015-12-11 17:17:29 -0500 (Fri, 11 Dec 2015) $ *)\n\n", "meta": {"author": "coqoon", "repo": "Software-Foundations", "sha": "a327b63aa8ff8543ae2cedee7a5960da05bbfaa7", "save_path": "github-repos/coq/coqoon-Software-Foundations", "path": "github-repos/coq/coqoon-Software-Foundations/Software-Foundations-a327b63aa8ff8543ae2cedee7a5960da05bbfaa7/Software Foundations/src/SF/Maps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.8947894639983208, "lm_q1q2_score": 0.7026858351738451}}
{"text": "(****************************************************************************\n                                                                             \n          IEEE754  :  FPred                                                     \n                                                                             \n          Laurent Thery                                                      \n                                                                             \n  ******************************************************************************)\nRequire Export FSucc.\nSection pred.\nVariable b : Fbound.\nVariable radix : Z.\nVariable precision : nat.\n \nLet FtoRradix := FtoR radix.\nLocal Coercion FtoRradix : float >-> R.\n\nHypothesis radixMoreThanOne : (1 < radix)%Z.\nHypothesis precisionNotZero : precision <> 0.\nHypothesis pGivesBound : Zpos (vNum b) = Zpower_nat radix precision.\n \nDefinition FPred (x : float) :=\n  match Z_eq_bool (Fnum x) (- pPred (vNum b)) with\n  | true => Float (- nNormMin radix precision) (Zsucc (Fexp x))\n  | false =>\n      match Z_eq_bool (Fnum x) (nNormMin radix precision) with\n      | true =>\n          match Z_eq_bool (Fexp x) (- dExp b) with\n          | true => Float (Zpred (Fnum x)) (Fexp x)\n          | false => Float (pPred (vNum b)) (Zpred (Fexp x))\n          end\n      | false => Float (Zpred (Fnum x)) (Fexp x)\n      end\n  end.\n \nTheorem FPredSimpl1 :\n forall x : float,\n Fnum x = (- pPred (vNum b))%Z ->\n FPred x = Float (- nNormMin radix precision) (Zsucc (Fexp x)).\nintros x H'; unfold FPred in |- *.\ngeneralize (Z_eq_bool_correct (Fnum x) (- pPred (vNum b)));\n case (Z_eq_bool (Fnum x) (- pPred (vNum b))); auto.\nintros H'0; Contradict H'0; auto.\nQed.\n \nTheorem FPredSimpl2 :\n forall x : float,\n Fnum x = nNormMin radix precision ->\n Fexp x <> (- dExp b)%Z -> FPred x = Float (pPred (vNum b)) (Zpred (Fexp x)).\nintros x H' H'0; unfold FPred in |- *.\ngeneralize (Z_eq_bool_correct (Fnum x) (- pPred (vNum b)));\n case (Z_eq_bool (Fnum x) (- pPred (vNum b))); auto.\nintros H'1; absurd (0%nat < Fnum x)%Z; auto with zarith arith.\napply Zle_not_lt; rewrite H'1; replace (Z_of_nat 0) with (- (0))%Z;\n [ apply Zle_Zopp | simpl in |- *; auto ].\nunfold pPred in |- *; apply Zle_Zpred; red in |- *; simpl in |- *; auto.\nrewrite H'.\napply nNormPos; auto with zarith.\nintros H'1;\n generalize (Z_eq_bool_correct (Fnum x) (nNormMin radix precision));\n case (Z_eq_bool (Fnum x) (nNormMin radix precision)).\nintros H'2; generalize (Z_eq_bool_correct (Fexp x) (- dExp b));\n case (Z_eq_bool (Fexp x) (- dExp b)); auto.\nintros H'3; Contradict H'0; auto.\nintros H'2; Contradict H'2; auto.\nQed.\n \nTheorem FPredSimpl3 :\n FPred (Float (nNormMin radix precision) (- dExp b)) =\n Float (Zpred (nNormMin radix precision)) (- dExp b).\nunfold FPred in |- *; simpl in |- *.\ngeneralize (Z_eq_bool_correct (nNormMin radix precision) (- pPred (vNum b)));\n case (Z_eq_bool (nNormMin radix precision) (- pPred (vNum b))); \n auto.\nintros H'0; absurd (0 < pPred (vNum b))%Z; auto with zarith arith.\nrewrite <- (Zopp_involutive (pPred (vNum b))); rewrite <- H'0.\napply Zle_not_lt; replace 0%Z with (- (0))%Z;\n [ apply Zle_Zopp | simpl in |- *; auto ].\napply Zlt_le_weak; apply nNormPos; auto with float zarith.\nunfold pPred in |- *; apply Zlt_succ_pred; simpl in |- *;\n auto with float zarith.\nsimpl in |- *; apply vNumbMoreThanOne with (3 := pGivesBound); auto.\nintros H';\n generalize\n  (Z_eq_bool_correct (nNormMin radix precision) (nNormMin radix precision));\n case (Z_eq_bool (nNormMin radix precision) (nNormMin radix precision)).\nintros H'0; generalize (Z_eq_bool_correct (- dExp b) (- dExp b));\n case (Z_eq_bool (- dExp b) (- dExp b)); auto.\nintros H'1; Contradict H'1; auto.\nintros H'1; Contradict H'1; auto.\nQed.\n \nTheorem FPredSimpl4 :\n forall x : float,\n Fnum x <> (- pPred (vNum b))%Z ->\n Fnum x <> nNormMin radix precision ->\n FPred x = Float (Zpred (Fnum x)) (Fexp x).\nintros x H' H'0; unfold FPred in |- *.\ngeneralize (Z_eq_bool_correct (Fnum x) (- pPred (vNum b)));\n case (Z_eq_bool (Fnum x) (- pPred (vNum b))); auto.\nintros H'1; Contradict H'; auto.\nintros H'1;\n generalize (Z_eq_bool_correct (Fnum x) (nNormMin radix precision));\n case (Z_eq_bool (Fnum x) (nNormMin radix precision)); \n auto.\nintros H'2; Contradict H'0; auto.\nQed.\n \nTheorem FPredFopFSucc :\n forall x : float, FPred x = Fopp (FSucc b radix precision (Fopp x)).\nintros x.\ngeneralize (Z_eq_bool_correct (Fnum x) (- pPred (vNum b)));\n case (Z_eq_bool (Fnum x) (- pPred (vNum b))); intros H'1.\nrewrite FPredSimpl1; auto; rewrite FSuccSimpl1; auto.\nunfold Fopp in |- *; simpl in |- *; rewrite H'1; auto with zarith.\ngeneralize (Z_eq_bool_correct (Fnum x) (nNormMin radix precision));\n case (Z_eq_bool (Fnum x) (nNormMin radix precision)); \n intros H'2.\ngeneralize (Z_eq_bool_correct (Fexp x) (- dExp b));\n case (Z_eq_bool (Fexp x) (- dExp b)); intros H'3.\nreplace x with (Float (Fnum x) (Fexp x)).\nrewrite H'2; rewrite H'3; rewrite FPredSimpl3; unfold Fopp in |- *;\n simpl in |- *; rewrite FSuccSimpl3; simpl in |- *; \n auto.\nrewrite <- Zopp_Zpred_Zs; rewrite Zopp_involutive; auto.\ncase x; simpl in |- *; auto.\nrewrite FPredSimpl2; auto; rewrite FSuccSimpl2; unfold Fopp in |- *;\n simpl in |- *; try rewrite Zopp_involutive; \n auto.\nrewrite H'2; auto.\nrewrite FPredSimpl4; auto; rewrite FSuccSimpl4; auto.\nunfold Fopp in |- *; simpl in |- *; rewrite <- Zopp_Zpred_Zs;\n rewrite Zopp_involutive; auto.\nunfold Fopp in |- *; simpl in |- *; Contradict H'1; rewrite <- H'1;\n rewrite Zopp_involutive; auto.\nunfold Fopp in |- *; simpl in |- *; Contradict H'2; auto with zarith.\nQed.\n \nTheorem FPredDiff1 :\n forall x : float,\n Fnum x <> nNormMin radix precision ->\n Fminus radix x (FPred x) = Float 1%nat (Fexp x) :>R.\nintros x H'; rewrite (FPredFopFSucc x).\npattern x at 1 in |- *; rewrite <- (Fopp_Fopp x).\nrewrite <- Fopp_Fminus_dist.\nrewrite Fopp_Fminus.\nunfold FtoRradix in |- *; rewrite FSuccDiff1; auto.\nreplace (Fnum (Fopp x)) with (- Fnum x)%Z.\nContradict H'; rewrite <- (Zopp_involutive (Fnum x)); rewrite H';\n auto with zarith.\ncase x; simpl in |- *; auto.\nQed.\n \nTheorem FPredDiff2 :\n forall x : float,\n Fnum x = nNormMin radix precision ->\n Fexp x = (- dExp b)%Z -> Fminus radix x (FPred x) = Float 1%nat (Fexp x) :>R.\nintros x H' H'0; rewrite (FPredFopFSucc x).\npattern x at 1 in |- *; rewrite <- (Fopp_Fopp x).\nrewrite <- Fopp_Fminus_dist.\nrewrite Fopp_Fminus.\nunfold FtoRradix in |- *; rewrite FSuccDiff2; auto.\nrewrite <- H'; case x; auto.\nQed.\n \nTheorem FPredDiff3 :\n forall x : float,\n Fnum x = nNormMin radix precision ->\n Fexp x <> (- dExp b)%Z ->\n Fminus radix x (FPred x) = Float 1%nat (Zpred (Fexp x)) :>R.\nintros x H' H'0; rewrite (FPredFopFSucc x).\npattern x at 1 in |- *; rewrite <- (Fopp_Fopp x).\nrewrite <- Fopp_Fminus_dist.\nrewrite Fopp_Fminus.\nunfold FtoRradix in |- *; rewrite FSuccDiff3; auto.\nrewrite <- H'; case x; auto.\nQed.\n \nTheorem FBoundedPred : forall f : float, Fbounded b f -> Fbounded b (FPred f).\nintros f H'; rewrite (FPredFopFSucc f); auto with float.\nQed.\n \nTheorem FPredCanonic :\n forall a : float, Fcanonic radix b a -> Fcanonic radix b (FPred a).\nintros a H'.\nrewrite FPredFopFSucc; auto with float.\nQed.\n \nTheorem FPredLt : forall a : float, (FPred a < a)%R.\nintros a; rewrite FPredFopFSucc.\npattern a at 2 in |- *; rewrite <- (Fopp_Fopp a).\nunfold FtoRradix in |- *; repeat rewrite Fopp_correct.\napply Ropp_lt_contravar.\nrewrite <- Fopp_correct; auto with float.\nQed.\n \nTheorem R0RltRlePred : forall x : float, (0 < x)%R -> (0 <= FPred x)%R.\nintros x H'; rewrite FPredFopFSucc.\nunfold FtoRradix in |- *; repeat rewrite Fopp_correct.\nreplace 0%R with (-0)%R; auto with real.\napply Ropp_le_contravar.\napply R0RltRleSucc; auto.\nunfold FtoRradix in |- *; repeat rewrite Fopp_correct.\nreplace 0%R with (-0)%R; auto with real.\nQed.\n \nTheorem FPredProp :\n forall x y : float,\n Fcanonic radix b x -> Fcanonic radix b y -> (x < y)%R -> (x <= FPred y)%R.\nintros x y H' H'0 H'1; rewrite FPredFopFSucc.\nrewrite <- (Fopp_Fopp x).\nunfold FtoRradix in |- *; rewrite Fopp_correct with (x := Fopp x).\nrewrite Fopp_correct with (x := FSucc b radix precision (Fopp y));\n auto with float real.\napply Ropp_le_contravar.\napply FSuccProp; auto with float.\nrepeat rewrite Fopp_correct; auto with real.\nQed.\n \nTheorem FPredZleEq :\n forall p q : float,\n (FPred p < q)%R -> (q <= p)%R -> (Fexp p <= Fexp q)%Z -> p = q :>R.\nintros p q H' H'0 H'1.\nrewrite <- (Ropp_involutive p); rewrite <- (Ropp_involutive q);\n apply Ropp_eq_compat.\nunfold FtoRradix in |- *; repeat rewrite <- Fopp_correct.\napply FSuccZleEq with (b := b) (precision := precision); auto.\nrepeat rewrite Fopp_correct; auto with real.\napply Ropp_lt_cancel.\nrepeat rewrite <- Fopp_correct; rewrite <- FPredFopFSucc; rewrite Fopp_Fopp;\n auto.\nQed.\n \nDefinition FNPred (x : float) := FPred (Fnormalize radix b precision x).\n \nTheorem FNPredFopFNSucc :\n forall x : float, FNPred x = Fopp (FNSucc b radix precision (Fopp x)).\nintros x; unfold FNPred, FNSucc in |- *; auto.\nrewrite Fnormalize_Fopp; auto.\napply FPredFopFSucc; auto.\nQed.\n \nTheorem FNPredCanonic :\n forall a : float, Fbounded b a -> Fcanonic radix b (FNPred a).\nintros a H'; unfold FNPred in |- *.\napply FPredCanonic; auto with float.\nQed.\n \nTheorem FNPredLt : forall a : float, (FNPred a < a)%R.\nintros a; unfold FNPred in |- *.\nunfold FtoRradix in |- *;\n rewrite <- (FnormalizeCorrect _ radixMoreThanOne b precision a).\napply FPredLt; auto.\nQed.\n \nTheorem FNPredProp :\n forall x y : float,\n Fbounded b x -> Fbounded b y -> (x < y)%R -> (x <= FNPred y)%R.\nintros x y H' H'0 H'1; unfold FNPred in |- *.\nreplace (FtoRradix x) with (FtoRradix (Fnormalize radix b precision x)).\napply FPredProp; auto with float.\nunfold FtoRradix in |- *; repeat rewrite FnormalizeCorrect; auto.\nunfold FtoRradix in |- *; repeat rewrite FnormalizeCorrect; auto.\nQed.\n \nTheorem FPredSuc :\n forall x : float,\n Fcanonic radix b x -> FPred (FSucc b radix precision x) = x.\nintros x H; unfold FPred, FSucc in |- *.\ncut (Fbounded b x); [ intros Fb0 | apply FcanonicBound with (1 := H) ].\ngeneralize (Z_eq_bool_correct (Fnum x) (pPred (vNum b)));\n case (Z_eq_bool (Fnum x) (pPred (vNum b))); simpl in |- *.\ngeneralize (Z_eq_bool_correct (nNormMin radix precision) (- pPred (vNum b)));\n case (Z_eq_bool (nNormMin radix precision) (- pPred (vNum b)));\n simpl in |- *.\nintros H'; Contradict H'; apply sym_not_equal; apply Zlt_not_eq; auto.\napply Zlt_le_trans with (- 0%nat)%Z.\napply Zlt_Zopp; unfold pPred in |- *; apply Zlt_succ_pred; simpl in |- *;\n apply vNumbMoreThanOne with (3 := pGivesBound); auto.\nsimpl in |- *; apply Zlt_le_weak; apply nNormPos; auto.\ngeneralize\n (Z_eq_bool_correct (nNormMin radix precision) (nNormMin radix precision));\n case (Z_eq_bool (nNormMin radix precision) (nNormMin radix precision));\n simpl in |- *.\ngeneralize (Z_eq_bool_correct (Zsucc (Fexp x)) (- dExp b));\n case (Z_eq_bool (Zsucc (Fexp x)) (- dExp b)); simpl in |- *.\nintros H' H'0 H'1 H'2; absurd (- dExp b <= Fexp x)%Z; auto with float.\nrewrite <- H'; auto with float zarith.\nreplace (Zpred (Zsucc (Fexp x))) with (Fexp x);\n [ idtac | unfold Zsucc, Zpred in |- *; ring ]; auto.\nintros H' H'0 H'1 H'2; rewrite <- H'2; auto.\napply floatEq; auto.\nintros H'; case H'; auto.\ngeneralize (Z_eq_bool_correct (Fnum x) (- nNormMin radix precision));\n case (Z_eq_bool (Fnum x) (- nNormMin radix precision)); \n simpl in |- *.\ngeneralize (Z_eq_bool_correct (Fexp x) (- dExp b));\n case (Z_eq_bool (Fexp x) (- dExp b)); simpl in |- *.\ngeneralize (Z_eq_bool_correct (Zsucc (Fnum x)) (- pPred (vNum b)));\n case (Z_eq_bool (Zsucc (Fnum x)) (- pPred (vNum b))); \n simpl in |- *.\nintros H0 H1 H2; absurd (Zsucc (Fnum x) <= Fnum x)%Z; auto with zarith.\nrewrite H0; rewrite H2; (apply Zle_Zopp; auto with float arith).\nunfold pPred in |- *; apply Zle_Zpred; apply ZltNormMinVnum; auto with zarith.\ngeneralize (Z_eq_bool_correct (Zsucc (Fnum x)) (nNormMin radix precision));\n case (Z_eq_bool (Zsucc (Fnum x)) (nNormMin radix precision)); \n simpl in |- *.\nintros H' H'0 H'1 H'2; Contradict H'2.\nrewrite <- H'; auto with zarith.\nreplace (Zpred (Zsucc (Fnum x))) with (Fnum x);\n [ idtac | unfold Zsucc, Zpred in |- *; ring ]; auto.\nintros H' H'0 H'1 H'2 H'3; apply floatEq; auto.\ngeneralize (Z_eq_bool_correct (- pPred (vNum b)) (- pPred (vNum b)));\n case (Z_eq_bool (- pPred (vNum b)) (- pPred (vNum b))); \n auto.\nintros H' H'0 H'1 H'2; rewrite <- H'1.\nreplace (Zsucc (Zpred (Fexp x))) with (Fexp x);\n [ idtac | unfold Zsucc, Zpred in |- *; ring ]; auto.\napply floatEq; auto.\nintros H'; case H'; auto.\ngeneralize (Z_eq_bool_correct (Zsucc (Fnum x)) (- pPred (vNum b)));\n case (Z_eq_bool (Zsucc (Fnum x)) (- pPred (vNum b))); \n simpl in |- *.\nintros H'; absurd (- pPred (vNum b) <= Fnum x)%Z; auto with float.\nrewrite <- H'; auto with zarith.\napply Zle_Zabs_inv1; auto with float.\nunfold pPred in |- *; apply Zle_Zpred; auto with float.\ngeneralize (Z_eq_bool_correct (Zsucc (Fnum x)) (nNormMin radix precision));\n case (Z_eq_bool (Zsucc (Fnum x)) (nNormMin radix precision)); \n simpl in |- *.\ngeneralize (Z_eq_bool_correct (Fexp x) (- dExp b));\n case (Z_eq_bool (Fexp x) (- dExp b)); simpl in |- *.\nintros H' H'0 H'1 H'2 H'3.\nreplace (Zpred (Zsucc (Fnum x))) with (Fnum x);\n [ idtac | unfold Zsucc, Zpred in |- *; ring ]; auto.\napply floatEq; auto.\nintros H' H'0 H'1 H'2 H'3; case H.\nintros H'4; absurd (nNormMin radix precision <= Zabs (Fnum x))%Z.\nreplace (Fnum x) with (Zpred (Zsucc (Fnum x)));\n [ idtac | unfold Zsucc, Zpred in |- *; ring ]; auto.\nrewrite H'0.\napply Zlt_not_le; rewrite Zabs_eq; auto with zarith.\napply Zle_Zpred; apply nNormPos; auto with float zarith.\napply pNormal_absolu_min with (b := b); auto.\nintros H'4; Contradict H'; apply FsubnormalFexp with (1 := H'4).\nintros H' H'0 H'1 H'2; apply floatEq; simpl in |- *; auto.\nunfold Zpred, Zsucc in |- *; ring.\nQed.\n \nTheorem FSucPred :\n forall x : float,\n Fcanonic radix b x -> FSucc b radix precision (FPred x) = x.\nintros x H; unfold FPred, FSucc in |- *.\ncut (Fbounded b x); [ intros Fb0 | apply FcanonicBound with (1 := H) ].\ngeneralize (Z_eq_bool_correct (Fnum x) (- pPred (vNum b)));\n case (Z_eq_bool (Fnum x) (- pPred (vNum b))); simpl in |- *.\ngeneralize (Z_eq_bool_correct (- nNormMin radix precision) (pPred (vNum b)));\n case (Z_eq_bool (- nNormMin radix precision) (pPred (vNum b)));\n simpl in |- *.\nintros H'; Contradict H'; apply Zlt_not_eq; auto.\nrewrite <- (Zopp_involutive (pPred (vNum b))); apply Zlt_Zopp.\napply Zlt_le_trans with (- 0%nat)%Z.\napply Zlt_Zopp; unfold pPred in |- *; apply Zlt_succ_pred; simpl in |- *.\napply (vNumbMoreThanOne radix) with (precision := precision); auto.\nsimpl in |- *; apply Zlt_le_weak; apply nNormPos; auto with zarith arith.\ngeneralize\n (Z_eq_bool_correct (- nNormMin radix precision) (- nNormMin radix precision));\n case (Z_eq_bool (- nNormMin radix precision) (- nNormMin radix precision));\n simpl in |- *.\ngeneralize (Z_eq_bool_correct (Zsucc (Fexp x)) (- dExp b));\n case (Z_eq_bool (Zsucc (Fexp x)) (- dExp b)); simpl in |- *.\nintros H' H'0 H'1 H'2; absurd (- dExp b <= Fexp x)%Z; auto with float.\nrewrite <- H'; auto with zarith.\nintros H' H'0 H'1 H'2; rewrite <- H'2; apply floatEq; simpl in |- *; auto;\n unfold Zsucc, Zpred in |- *; ring.\nintros H'; case H'; auto.\ngeneralize (Z_eq_bool_correct (Fnum x) (nNormMin radix precision));\n case (Z_eq_bool (Fnum x) (nNormMin radix precision)); \n simpl in |- *.\ngeneralize (Z_eq_bool_correct (Fexp x) (- dExp b));\n case (Z_eq_bool (Fexp x) (- dExp b)); simpl in |- *.\ngeneralize (Z_eq_bool_correct (Zpred (Fnum x)) (pPred (vNum b)));\n case (Z_eq_bool (Zpred (Fnum x)) (pPred (vNum b))); \n simpl in |- *.\nintros H' H'0 H'1 H'2; absurd (nNormMin radix precision <= pPred (vNum b))%Z;\n auto with float.\nrewrite <- H'; rewrite H'1; auto with zarith.\nrewrite <- H'1; auto with float.\napply Zle_Zabs_inv2; auto with float zarith.\nunfold pPred in |- *; apply Zle_Zpred; auto with float.\ngeneralize (Z_eq_bool_correct (Zpred (Fnum x)) (- nNormMin radix precision));\n case (Z_eq_bool (Zpred (Fnum x)) (- nNormMin radix precision));\n simpl in |- *.\nintros H' H'0 H'1 H'2 H'3;\n absurd (Zpred (nNormMin radix precision) = (- nNormMin radix precision)%Z);\n auto with zarith.\nintros H' H'0 H'1 H'2 H'3; apply floatEq; simpl in |- *; auto;\n unfold Zpred, Zsucc in |- *; ring.\ngeneralize (Z_eq_bool_correct (pPred (vNum b)) (pPred (vNum b)));\n case (Z_eq_bool (pPred (vNum b)) (pPred (vNum b))); \n auto.\nintros H' H'0 H'1 H'2; rewrite <- H'1; apply floatEq; simpl in |- *; auto;\n unfold Zpred, Zsucc in |- *; ring.\nintros H'; case H'; auto.\ngeneralize (Z_eq_bool_correct (Zpred (Fnum x)) (pPred (vNum b)));\n case (Z_eq_bool (Zpred (Fnum x)) (pPred (vNum b))); \n simpl in |- *.\nintros H'; absurd (Fnum x <= pPred (vNum b))%Z; auto with float.\nrewrite <- H'.\napply Zlt_not_le; apply Zlt_pred; auto.\napply Zle_Zabs_inv2; unfold pPred in |- *; apply Zle_Zpred; auto with float.\ngeneralize (Z_eq_bool_correct (Zpred (Fnum x)) (- nNormMin radix precision));\n case (Z_eq_bool (Zpred (Fnum x)) (- nNormMin radix precision));\n simpl in |- *.\ngeneralize (Z_eq_bool_correct (Fexp x) (- dExp b));\n case (Z_eq_bool (Fexp x) (- dExp b)); simpl in |- *.\nintros H' H'0 H'1 H'2 H'3; apply floatEq; simpl in |- *; auto;\n unfold Zsucc, Zpred in |- *; ring.\nintros H' H'0 H'1 H'2 H'3; case H; intros C0.\nabsurd (nNormMin radix precision <= Zabs (Fnum x))%Z; auto with float.\nreplace (Fnum x) with (Zsucc (Zpred (Fnum x)));\n [ idtac | unfold Zsucc, Zpred in |- *; ring ].\nrewrite H'0.\nrewrite <- Zopp_Zpred_Zs; rewrite Zabs_Zopp.\nrewrite Zabs_eq; auto with zarith.\napply Zle_Zpred; simpl in |- *; apply nNormPos; auto with float zarith.\napply pNormal_absolu_min with (b := b); auto.\nContradict H'; apply FsubnormalFexp with (1 := C0).\nintros H' H'0 H'1 H'2; apply floatEq; simpl in |- *; auto.\nunfold Zpred, Zsucc in |- *; ring.\nQed.\n \nTheorem FNPredSuc :\n forall x : float,\n Fbounded b x -> FNPred (FNSucc b radix precision x) = x :>R.\nintros x H'; unfold FNPred in |- *; rewrite FcanonicFnormalizeEq; auto.\nunfold FNSucc in |- *; rewrite FPredSuc; auto.\nunfold FtoRradix in |- *; apply FnormalizeCorrect; auto.\napply FnormalizeCanonic; auto.\napply FNSuccCanonic; auto.\nQed.\n \nTheorem FNPredSucEq :\n forall x : float,\n Fcanonic radix b x -> FNPred (FNSucc b radix precision x) = x.\nintros x H'.\napply FcanonicUnique with (precision := precision) (5 := H'); auto.\napply FNPredCanonic; auto with float.\napply FcanonicBound with (radix := radix); auto.\napply FNSuccCanonic; auto.\napply FcanonicBound with (radix := radix); auto.\napply FNPredSuc; auto.\napply FcanonicBound with (radix := radix); auto.\nQed.\n \nTheorem FNSucPred :\n forall x : float,\n Fbounded b x -> FNSucc b radix precision (FNPred x) = x :>R.\nintros x H'; unfold FNSucc in |- *; rewrite FcanonicFnormalizeEq; auto.\nunfold FNPred in |- *; rewrite FSucPred; auto.\nunfold FtoRradix in |- *; apply FnormalizeCorrect; auto.\napply FnormalizeCanonic; auto.\napply FNPredCanonic; auto.\nQed.\n \nTheorem FNSucPredEq :\n forall x : float,\n Fcanonic radix b x -> FNSucc b radix precision (FNPred x) = x.\nintros x H'.\napply FcanonicUnique with (5 := H') (precision := precision); auto.\napply FNSuccCanonic; auto.\napply FcanonicBound with (radix := radix); auto.\napply FNPredCanonic; auto.\napply FcanonicBound with (radix := radix); auto.\napply FNSucPred; auto.\napply FcanonicBound with (radix := radix); auto.\nQed.\n\n\nEnd pred.\nHint Resolve FBoundedPred FPredCanonic FPredLt R0RltRleSucc FPredProp\n  FNPredCanonic FNPredLt FNPredProp: float.", "meta": {"author": "coq-contribs", "repo": "float", "sha": "b3bfbd67f7be553f169a5b257a848ea13654bbb3", "save_path": "github-repos/coq/coq-contribs-float", "path": "github-repos/coq/coq-contribs-float/float-b3bfbd67f7be553f169a5b257a848ea13654bbb3/FPred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7026857454948648}}
{"text": "(* -------------------------------------------------------------------- *)\nFrom mathcomp Require Import ssreflect ssrnat ssrbool eqtype div ssrint.\nFrom mathcomp Require Import ssrnum fintype ssralg ssrfun.\nFrom mathcomp Require Import choice seq bigop matrix intdiv.\n\nRequire Import ec.\n\nImport GRing.Theory.\n\nOpen Local Scope ring_scope.\n\nSection Multiexponentiation.\n\nFixpoint nat_to_bin_aux (n a : nat) : seq bool :=\n  match a with\n    |0 => [::]\n    |a.+1 => \n      match n with \n        |0 => [::]\n        |_.+1 => (odd n) :: (nat_to_bin_aux n./2 a)\n      end   \n  end.\n\nDefinition nat_to_bin (n : nat) := nat_to_bin_aux n n.\n\n(*lsb ... msb*)\n\nLemma nat_to_bin0 : nat_to_bin 0 = [::].\nProof. by []. Qed.\n\nLemma nat_to_bin1 : nat_to_bin 1 = [:: true].\nProof. by []. Qed.\n\nLemma nat_to_bin_eq_nil n : (nat_to_bin n == [::]) = (n == 0%N).\nProof.\napply/eqP/eqP => h.\n+ by case: n h.\n+ by rewrite h.\nQed.\n\nLemma nat_to_bin_simpl n a :\nnat_to_bin_aux n.+1 a.+1 = (odd n.+1) :: (nat_to_bin_aux (n.+1)./2 a).\nProof. by []. Qed.\n\nLemma general_ind :\nforall (P : nat -> Prop),\n(forall n, (forall p : nat , (p < n)%N -> P p) -> P n) ->\nforall n, P n.\nProof.\n    move=> P ind n; move: {-2}n (leqnn n); elim: n => [|n IHn] p.\n      by rewrite leqn0=> /eqP->; apply: ind.\n    move=> lt_p_Sn; apply: ind=> k lt_k_p; apply: IHn.\n    by rewrite -ltnS; rewrite (leq_trans lt_k_p).\n  Qed.\n\nLemma nat_to_bin_aux_G (n m : nat) :\n(n <= m)%N -> nat_to_bin_aux n m = nat_to_bin_aux n n. \nProof.\nelim/general_ind : n m.\ncase.\n* by move=> IH m nGETm /= ;  case : m nGETm.\n* move => n IH m nLTm ; case : m nLTm IH.\n + by rewrite ltn0.\n + move=> m nLTm IH; rewrite !nat_to_bin_simpl.\n* have h1 : nat_to_bin_aux (n.+1)./2 m = nat_to_bin_aux (n.+1)./2 (n.+1)./2.\n  apply: IH.\n+ rewrite -divn2 ; apply: ltn_Pdiv => //.\n+ case : m nLTm.\n  * rewrite ltnS leqn0; move/eqP => nEQ0; by rewrite nEQ0 /=.\n  * move=> m; rewrite ltnS; move=> nLTm; rewrite -divn2.\n    have hn : (n.+1 %/ 2 <= n)%N.\n    rewrite -ltnS;  by apply: ltn_Pdiv.\n    apply: (leq_trans hn nLTm).\n* have h2 : nat_to_bin_aux (n.+1)./2 n = nat_to_bin_aux (n.+1)./2 (n.+1)./2.\n  apply: IH.\n+ rewrite -divn2; apply: ltn_Pdiv => //.\n+ rewrite -ltnS -divn2; apply: ltn_Pdiv => //.\nby rewrite h1 h2.\nQed.\n\nLemma nat_to_bin_S :\nforall (x : bool) (m : nat), m != 0%N ->\nnat_to_bin (x + 2 * m)%N = x :: (nat_to_bin m).\nProof.\nmove=> x m mN0.\ncase : x.\n* rewrite addnC addn1 /nat_to_bin /=.\n  rewrite {2}mul2n uphalf_double -dvdn2 dvdn_mulr; last by rewrite dvdnn.\n  have h : nat_to_bin_aux m (2 * m) = nat_to_bin_aux m m. \n  + apply: nat_to_bin_aux_G; by apply: leq_pmull.\n  by rewrite h.\n* rewrite add0n /nat_to_bin /=.\n  have h : exists n, m = n.+1.\n  + move: mN0; case:m => // x hx; exists x => //.\n  move:h => [x mSx]; rewrite mSx.\n  have h : (2 * x.+1)%N = ((2 * x).+1).+1.\n  + by rewrite -[x.+1]addn1 mulnDr muln1 mul2n addn2.\n  rewrite h nat_to_bin_simpl.\n  have hodd : (odd (2 * x).+2) = false.\n  + apply: negbTE; rewrite -h -dvdn2 dvdn_mulr // dvdnn.\n  rewrite hodd -h -divn2 mulKn //.\n  have H : nat_to_bin_aux x.+1 (2 * x).+1 = nat_to_bin_aux x.+1 x.+1. \n  + apply: nat_to_bin_aux_G; rewrite ltnS; by apply: leq_pmull.\n  by rewrite H.\nQed.\n\nFixpoint bin_to_nat (l : seq bool) : nat :=\n  match l with \n    |[::] => 0%N\n    |x :: xs => (x + 2 * (bin_to_nat xs))%N \n  end.\n\nDefinition epurate (b : bool):=\n  match b with\n    |true => [:: true]\n    |false => [::]\n  end.\n\nFixpoint norm_bin1 (u : seq bool) :=\n  match u with\n    |[::] => [::]\n    |x :: xs =>\n      let v := norm_bin1 xs in \n        match v with \n          |[::] => epurate x\n          |y :: ys => x :: v\n        end\n  end.\n\nFixpoint norm_bin_rev (v : seq bool) : seq bool :=\n  match v with \n    |[::] => [::]\n    |x :: xs => \n      if (x == true) then v\n        else norm_bin_rev xs\n  end.\n\n(* norm_bin2 was an alternative but not used *)\nDefinition norm_bin2 (u : seq bool) :=\n  rev (norm_bin_rev (rev u)).\n\nLemma norm_bin2_true : norm_bin2 [:: true] = [:: true].\nProof. by []. Qed.\n\nLemma norm_bin2_false : norm_bin2 [:: false] = [::].\nProof. by []. Qed.\n\nLemma norm_bin2_nil : norm_bin2 [::] = [::].\nProof. by []. Qed.\n\nLemma norm_bin1_true : norm_bin1 [:: true] = [:: true].\nProof. by []. Qed.\n\nLemma norm_bin1_false : norm_bin1 [:: false] = [::].\nProof. by []. Qed.\n\n\nLemma norm_bin1_nil : norm_bin1 [::] = [::].\nProof. by []. Qed.\n\n\nLemma rev_last :\nforall (x b : bool) (xs : seq bool), last b (rev (x::xs)) = x.\nProof.\nmove=> x b xs.\nby rewrite rev_cons last_rcons.\nQed.\n\nLemma correct_norm_bin (u : seq bool) :\nbin_to_nat u == bin_to_nat (norm_bin1 u).\nProof.\nelim: u => //=.\nmove=> x xs.\ncase h : (norm_bin1 xs)=> [//= | y ys].\n* move/eqP => h0.\nrewrite h0 muln0 addn0.\nrewrite /epurate.\ncase: x => //=.\n* move/eqP=> IH.\nby rewrite IH.\nQed.\n\nLemma cancelB u : \nnat_to_bin (bin_to_nat u) = norm_bin1 u.\nProof.\nelim: u.\n* by rewrite /=.\n* move=> x xs IH; rewrite /=.\ncase Hbtn: (bin_to_nat xs).\n+ rewrite muln0 addn0; move: IH.\nrewrite Hbtn nat_to_bin0 => <-.\nby case: x.\n+ rewrite nat_to_bin_S // -Hbtn IH.\ncase thenilcase : (norm_bin1 xs) => [|y ys //].\nhave absurd : bin_to_nat xs = 0%N.\n* move: (correct_norm_bin xs).\n  rewrite thenilcase //=.\n  move/eqP => -> //.\nmove: Hbtn. \nby rewrite absurd.\nQed.\n\nLemma bin_to_nat_nil : bin_to_nat [::] = 0%N.\nProof. by []. Qed.\n\nLemma bin_to_nat_true : bin_to_nat [:: true] = 1%N.\nProof. by []. Qed.\n\nLemma bin_to_nat_false u : norm_bin1 u = [::] -> bin_to_nat u = 0%N.\nProof. \nmove/eqP: (correct_norm_bin u)=> -> -> //. Qed.\n\nLemma bin_to_nat_cons x xs : bin_to_nat (x :: xs) = (x + 2 * bin_to_nat xs)%N.\nProof. by []. Qed.\n\nLemma uphalf_len m : (uphalf m <= m)%N.\nProof.\nelim:m => //.\nmove=> n IH.\nhave uphalfS : (uphalf (n.+1) <= (uphalf n) + 1)%N.\n* by rewrite /= uphalf_half -addnA addn1 ltn_addl.\nrewrite -(leq_add2r 1 (uphalf n) n) in IH. \nrewrite -{2}[n.+1]addn1.\napply: (leq_trans uphalfS IH).\nQed.\n\nLemma uphalf_S m : (~~ odd m + 2 * (odd m + m./2))%N = m.+1.\nProof.\nmove: (odd_double_half m)=> Hm.\nrewrite -[m.+1]addn1 -{4}Hm.\ncase HHm : (odd m) => /=; rewrite !add0n.\nby rewrite mulnDr muln1 [(1 + (m./2).*2)%N]addnC -[((m./2).*2 + 1 + 1)%N]addnA addn1 addnC mul2n.\nby rewrite mul2n addnC.\nQed.\n\nLemma cancelN n : \nbin_to_nat (nat_to_bin n) = n.\nProof. \nelim/general_ind : n => n IH.\ncase Hn : n => [// | m].\nhave h : nat_to_bin (uphalf m) = nat_to_bin_aux (uphalf m) m. \n* rewrite /nat_to_bin; symmetry.\n  apply : nat_to_bin_aux_G.\n  by rewrite uphalf_len.\n* rewrite /= -h IH.\n+ by rewrite uphalf_half uphalf_S.\n+ have mltn : (m < n)%N. by rewrite Hn ltnSn.\n  by apply: (leq_ltn_trans (uphalf_len m) mltn).\nQed.\n \nDefinition block (u : seq bool) (w i : nat) :=\n mkseq (fun k => nth false u (w*i + k)) w.\n\n(*first block is the zero-block*)\n(* when i > (size u)%/w then block = [::false; .. ; false] *)\n(* block [::] w i = [::false; .. ;false] *)\n\nDefinition n_blocks (u : seq bool) (w : nat) :=\nif size u is 0%N then 0%N\nelse (((size u).-1) %/ w).+1.\n\nLemma size_block u w i: \nsize (block u w i) = w.\nProof.\nby rewrite size_mkseq.\nQed.\n\nLemma block_size0 u i w: w = 0%N -> block u w i = [::]. \nProof. by move => ->. Qed.\n\nLemma n_blocks_nil w : n_blocks [::] w = 0%N.\nProof. by []. Qed.\n\nLemma n_blocks_size0 u : u != [::] -> n_blocks u 0%N = 1%N.\nProof. by case : u. Qed.\n\nLemma n_blocks_cons x xs w : n_blocks (x :: xs) w != 0%N.\nProof. by []. Qed.\n\nLemma n_blocks0_eq_nil u w : (n_blocks u w == 0%N) = (u == [::]).   \nProof.\napply/eqP/eqP => h.\n+ by case : u h.\n+ by rewrite h n_blocks_nil.\nQed.\n\nVariable G : zmodType.\n\nDefinition expG w (u : seq bool) (P : G) :=\n    let d := (n_blocks u w) in\n    foldl\n      (fun R i =>\n        let R := R *+ (2^w) in\n          R + (P *+ (bin_to_nat (block u w i))))\n      0 (rev (iota 0 d)).\n\nLemma expG_nil w P : expG w [::] P = 0.\nProof. by []. Qed.\n\nLemma size_normalized_lt_seq b:\n(size (norm_bin1 b) <= size b)%N.\nProof.\nelim:b => [//= | x xs IH].\nrewrite /=; case H : (norm_bin1 xs) => [|y ys].\n+ by case: x => /=.\n+ rewrite {1}/size // -/size.\nhave hsize : size (norm_bin1 xs) = (size ys).+1.\n* by rewrite H.\nby rewrite -hsize ltnS.\nQed.\n\nLemma size_seq_lt_block b (w : nat):\n  w != 0%N -> ((size b) <= w * (n_blocks b w))%N.\nProof.\nmove=> wNz.\nelim:b => [//| x xs IH].\nrewrite /n_blocks //=  mulnC; apply: ltn_ceil.\nby rewrite lt0n.\nQed.\n\nLemma nat2bin_size_block b (w : nat):\n  w != 0%N -> (size (norm_bin1 b) <= w * (n_blocks b w))%N.\nProof. \nmove=> wNz.\nmove: (size_seq_lt_block b w wNz) => ineq.\napply: (leq_trans (size_normalized_lt_seq b) ineq).\nQed.\n\nLemma norm_bin1_cons_true xs : \n norm_bin1 (true :: xs) = true :: (norm_bin1 xs).\nProof.\ncase H : (norm_bin1 xs) => [|y ys] ; by rewrite /= H.\nQed.\n\nLemma norm_bin1_cons_false1 xs : \nnorm_bin1 xs != nil -> norm_bin1 (false :: xs) = false :: (norm_bin1 xs).\nProof.\ncase H : (norm_bin1 xs) => [|y ys] ; by rewrite /= H.\nQed.\n\nLemma norm_bin1_cons_false2 xs : \nnorm_bin1 xs = nil -> norm_bin1 (false :: xs) = (norm_bin1 xs).\nProof.\nmove=> Hnil.\nby rewrite /= Hnil.\nQed.\n\nLemma half_leqn n : ((n./2) <= n)%N.\nProof. by rewrite -divn2 leq_div. Qed.\n\nLemma halfS_ltSn n : (((n.+1)./2) < n.+1)%N.\nProof. \nrewrite -divn2.\nby apply: ltn_Pdiv.\nQed.\n\nLemma nat2bin_normalized n:\n  norm_bin1 (nat_to_bin n) = nat_to_bin n.\nProof. \nelim/general_ind : n => n IH.\nrewrite /nat_to_bin; case Hn : n => [//|m].\nrewrite nat_to_bin_simpl; case H : (odd m.+1).\n+ rewrite norm_bin1_cons_true !nat_to_bin_aux_G; last by rewrite -ltnS halfS_ltSn.\n  rewrite !IH //; by rewrite Hn halfS_ltSn. \n+ rewrite !nat_to_bin_aux_G; last by rewrite -ltnS halfS_ltSn.\n  have h : nat_to_bin (m.+1)./2 = nat_to_bin_aux (m.+1)./2 (m.+1)./2. by [].\n  rewrite -h; set s := nat_to_bin _ ; rewrite /=.\n  have notodd : ((m.+1)./2 > 0)%N.\n  * move/negbT : H; rewrite -dvdn2 -divn2; move=> H; by rewrite ltn_divRL.\n  case H1 : (norm_bin1 s)=> [|x xs //].\n  * move: H1; rewrite /s; move/bin_to_nat_false; rewrite cancelN.\n    move: notodd; rewrite lt0n; move=> h1 h2. \n    move: h1; by rewrite h2.\n  * by rewrite -H1 /s IH ; last by rewrite Hn halfS_ltSn.\nQed.\n\nLemma bin_to_nat_MSB0:\n  forall b n, bin_to_nat (b ++ nseq n false) = bin_to_nat b. \nProof. \nmove=> b n.\nelim: b=> //=.\n+ elim: n => //=.\n  move=> n IH; by rewrite IH.\n+ move=> x xs IH; by rewrite IH.\nQed.\n\nLemma bin_to_nat_singl b : bin_to_nat [:: b] = b%N.\nProof.\ncase : b.\nby rewrite bin_to_nat_true.\nby apply: bin_to_nat_false.\nQed.\n\nLemma bin_to_nat_last x xs : \nbin_to_nat (rcons xs x) = \n((bin_to_nat xs) + bin_to_nat [:: x] * 2 ^ (size xs))%N.\nProof.\nelim: xs=> [ /= |y ys IH].\n+ by rewrite !muln0 !addn0 add0n expn0 muln1.\n+ rewrite /= muln0 addn0 IH bin_to_nat_singl.\n  rewrite expnS mulnA [(x * 2)%N]mulnC mulnDr.\n  by rewrite addnA mulnA.\nQed.\n\nLemma take_drop_lemma l k : \nbin_to_nat l = (bin_to_nat (take k l) + bin_to_nat (drop k l) * 2 ^ k)%N.\nProof.\ncase H : (l == [::]).\n* rewrite (eqP H) //=.\n* elim : k => [| n IH].\n  + by rewrite take0 drop0 expn0 muln1.\n  + move/negbT :H.\n    rewrite -[l!= [::]]Bool.andb_true_r.\n    move/predD1P; case => lNnil _.\n    case Hsize: (size l < n.+1)%N; last first.\n    * have Hn: (n < size l)%N. \n    by rewrite ltnNge (negbT Hsize).\n    rewrite (@take_nth _ false _ _) // bin_to_nat_last size_takel; last first.\n    + by rewrite leq_eqVlt Hn orbT.\n    + rewrite expnS mulnA -addnA -mulnDl [(_ * 2)%N]mulnC.\n    rewrite bin_to_nat_singl -bin_to_nat_cons -drop_nth //.\n    * rewrite take_oversize.\n    rewrite drop_oversize.\n    rewrite bin_to_nat_nil mul0n addn0 //.\n    by apply: ltnW.\n    by apply: ltnW.\nQed.\n\nLemma block_false bs w i k:\nblock (bs ++ nseq k false) w i = block bs w i. \nProof.\nrewrite /block /=.\nhave funeq : (fun k0 : nat => nth false (bs ++ nseq k false) (w * i + k0)) =1\n(fun k0 : nat => nth false bs (w * i + k0)).\n+ move=> n /=.\n  rewrite nth_cat.\n  case H : (w * i + n < size bs)%N => //.\n  rewrite nth_nseq //=.\n  case: (w * i + n - size bs < k)%N ; symmetry; apply: nth_default; by rewrite leqNgt H.\nmove: (eq_mkseq funeq)=> H.\nby rewrite (H w).\nQed.\n\nLemma take_block us w i : \nw != 0%N -> \n(w * i.+1 <= size us)%N ->\n(block us w i) = take w (drop (w * i) us).\nProof.\nmove=> wNz ineq.\napply: (@eq_from_nth _ false _ _).\nrewrite size_block size_take size_drop.\n+ have H : (w <= size us  - w * i)%N.\n    rewrite -(leq_add2r (w * i) _ _) subnK.\n    by rewrite addnC -{2}[w]muln1 -mulnDr addn1.\n    have h : (w * i <= w * i.+1)%N.\n    by rewrite leq_pmul2l ?leqnSn // ?lt0n.\n    by apply: leq_trans h ineq.\n  move: H; rewrite leq_eqVlt.\n  move/orP; case=> H.\n  by rewrite -(eqP H) //= ltnn.\n  by rewrite H.\n+ rewrite size_block; move=> k Hsize.\n  by rewrite nth_take // nth_drop /block nth_mkseq.\nQed.\n\n(* missing property for drop *)\nLemma drop_add k m (us: seq bool) :\n  drop (k + m) us = drop k (drop m us).\nProof.\nelim: us m => [|x us ih] // [|m].\nby rewrite addn0 drop0. by rewrite addnS /= ih.\nQed.\n\nLemma lemma us w i : \n  w != 0%N -> \n  (w * i.+1 <= size us)%N ->\n  (bin_to_nat (drop (w * i.+1) us) * 2 ^ w  +  bin_to_nat (block us w i))%N  =  \n  bin_to_nat (drop (w * i) us).\nProof.\nmove=> wNz ineq.\nrewrite take_block //.\nhave dropw : drop (w * i.+1) us = drop w (drop (w * i) us). \nby rewrite -addn1 mulnDr muln1 addnC drop_add.\nrewrite dropw.\nrewrite addnC.\nby rewrite -take_drop_lemma.\nQed.\n\n\n(* Fancy proof :) *)\nLemma expG_correct : forall (P : G) (n w : nat),\n  w != 0%N -> expG w (nat_to_bin n) P = P *+ n.\nProof.\n  move=> x n w nz_w; rewrite /expG foldl_rev.\n  set d := (n_blocks _ _).\n  set f := (fun _ _ => _).\n  rewrite -[n]cancelN -(bin_to_nat_MSB0 _ (w * d - size (nat_to_bin n))).\n  set u := (nseq _ _).\n  have ->: nat_to_bin n ++ u = drop (w * (d - d)) (nat_to_bin n ++ u).\n    by rewrite subnn muln0 drop0.\n  move: (erefl (0 + d)%N).\n  rewrite {1}add0n => /esym.\n  move: 0%N => i; move: {1 3 5}d => j.\n  elim : j i => [|j IH] i //=.  \n   move=> _;  rewrite subn0 drop_oversize //.\n   rewrite -nat2bin_normalized.\n   rewrite size_cat size_nseq.\n   rewrite nat2bin_normalized addnC subnK ?leqnn //.\n   + rewrite /d -{1}nat2bin_normalized; by apply: nat2bin_size_block.\n  move=> H; rewrite IH /f; last by rewrite addSnnS.\n  rewrite -mulrnA -mulrnDr; congr (_ *+ _).\n  rewrite -H -{1}addSnnS -!addnBA // !subnn !addn0.\n  set us := nat_to_bin n ++ u.\n  have Hblock : block (nat_to_bin n) w i = block us w i.\n  by rewrite /us /u block_false.\n  rewrite Hblock.\n  apply: lemma => //.\n  have size_us : size us = (w * d)%N.\n  rewrite /us size_cat /u size_nseq subnKC //.\n  by rewrite /d -{1}nat2bin_normalized nat2bin_size_block.\n  rewrite size_us leq_pmul2l ?lt0n.\n  by rewrite -H -{1}[i]addn0 ltn_add2l.\n  done.\nQed.\n\n\n(******************************************)\n(*          MULTIEXPONENTIATION !!!       *)\n(******************************************)\n\nDefinition algoG (w : nat) (u v : seq bool) (P Q : G) :=\nlet d := maxn (n_blocks u w) (n_blocks v w) in \nfoldl \n( fun (R : G) (i : nat) => \n let R0 := R *+ 2 ^ w in \n   R0 + (P *+ bin_to_nat (block u w i)) + (Q *+ bin_to_nat (block v w i)))  0\n(rev (iota 0 d)).\n\nLemma algo_nil2 w P Q : algoG w [::] [::] P Q = 0.\nProof. by []. Qed.\n\nLemma algo_correct :\n  forall (P Q : G) (n m w : nat), \n    w != 0%N -> \n    algoG w (nat_to_bin n) (nat_to_bin m) P Q = P *+ n + Q *+ m.\nProof.\n  move=> P Q n m w nz_w; rewrite /algoG foldl_rev.\n  set d := maxn  _ _.\n  set f := (fun _ _ => _).\n  rewrite -[n]cancelN -(bin_to_nat_MSB0 _ (w * d - size (nat_to_bin n))).\n  set u := (nseq _ _).\n  rewrite -[m]cancelN -(bin_to_nat_MSB0 (nat_to_bin m) (w * d - size (nat_to_bin m))).\n  set v := (nseq _ _).\n  have Hn: nat_to_bin n ++ u = drop (w * (d - d)) (nat_to_bin n ++ u).\n    by rewrite subnn muln0 drop0.\n  have Hm: nat_to_bin m ++ v = drop (w * (d - d)) (nat_to_bin m ++ v).\n    by rewrite subnn muln0 drop0.\n  rewrite Hn Hm; clear Hn Hm.\n  move: (erefl (0 + d)%N).\n  rewrite {1}add0n => /esym.\n  move: 0%N => i; move: {1 3 5 7}d => j.\n  elim : j i => [|j IH] i //=.  \n   move=> _;  rewrite subn0 !drop_oversize //.\n   by rewrite bin_to_nat_nil !mulr0n addr0.\n   + rewrite size_cat size_nseq subnKC.\n   by rewrite leqnn.\n   move: (size_seq_lt_block (nat_to_bin m) w nz_w)=> H1.\n   move: (leq_maxr (n_blocks (nat_to_bin n) w) (n_blocks (nat_to_bin m) w)).\n   rewrite -/d -(@leq_pmul2l w (n_blocks (nat_to_bin m) w) d) ?lt0n //.\n   move=> H2; by rewrite (leq_trans H1 H2).\n   + rewrite size_cat size_nseq subnKC.\n   by rewrite leqnn.\n   move: (size_seq_lt_block (nat_to_bin n) w nz_w)=> H1.\n   move: (leq_maxl (n_blocks (nat_to_bin n) w) (n_blocks (nat_to_bin m) w)).\n   rewrite -/d -(@leq_pmul2l w (n_blocks (nat_to_bin n) w) d) ?lt0n //.\n   move=> H2; by rewrite (leq_trans H1 H2).\n move=> H; rewrite IH /f; last by rewrite addSnnS.\n set us := nat_to_bin n ++ u.\n set vs := nat_to_bin m ++ v.\n rewrite mulrnDl -!mulrnA [(P *+ _) + _]addrC.\n set q1 := (bin_to_nat (drop (w * (d - j)) vs) * 2 ^ w)%N.\n set q2 := bin_to_nat (block (nat_to_bin m) w i)%N.\n set p1 := (bin_to_nat (drop (w * (d - j)) us) * 2 ^ w)%N.\n set p2 :=  bin_to_nat (block (nat_to_bin n) w i)%N.\n rewrite -[Q *+ q1 + P *+ p1 + P *+ p2]addrA.\n rewrite -mulrnDr addrC addrA -mulrnDr addrC.\n have Hp : (p1 + p2 = bin_to_nat (drop (w * (d - j.+1)) us))%N.\n * rewrite /p1 /p2.\n have Hblock : block (nat_to_bin n) w i = block us w i.\n by rewrite /us /u block_false.\n rewrite Hblock.\n rewrite -H -{1}addSnnS -!addnBA // !subnn !addn0.\n apply: lemma=> //.\n + rewrite /us size_cat /u size_nseq subnKC -H.\n  rewrite leq_pmul2l ?lt0n //.\n  move: (ltn_add2l i 0 j.+1);  by rewrite addn0.\n + rewrite H.\n  move: (size_seq_lt_block (nat_to_bin n) w nz_w)=> H1.\n  move: (leq_maxl (n_blocks (nat_to_bin n) w) (n_blocks (nat_to_bin m) w)).\n  rewrite -/d -(@leq_pmul2l w (n_blocks (nat_to_bin n) w) d) ?lt0n //.\n  move=> H2; by rewrite (leq_trans H1 H2).\n have Hq : (q1 + q2 = bin_to_nat (drop (w * (d - j.+1)) vs))%N.\n * rewrite /q1 /q2.\n have Hblock : block (nat_to_bin m) w i = block vs w i.\n by rewrite /us /u block_false.\n rewrite Hblock.\n rewrite -H -{1}addSnnS -!addnBA // !subnn !addn0.\n apply: lemma=> //.\n + rewrite /us size_cat /u size_nseq subnKC -H.\n  rewrite leq_pmul2l ?lt0n //.\n  move: (ltn_add2l i 0 j.+1);  by rewrite addn0.\n + rewrite H.\n  move: (size_seq_lt_block (nat_to_bin m) w nz_w)=> H1.\n  move: (leq_maxr (n_blocks (nat_to_bin n) w) (n_blocks (nat_to_bin m) w)).\n  rewrite -/d -(@leq_pmul2l w (n_blocks (nat_to_bin m) w) d) ?lt0n //.\n  move=> H2.\n  by rewrite (leq_trans H1 H2).\nrewrite [(q2 + q1)%N]addnC.\nby rewrite Hp Hq.\nQed.\n\nLemma algo_nilf w m P Q : w != 0%N -> algoG w [::] (nat_to_bin m) P Q = Q *+ m.\nProof. \n  move=> wNz.\n  rewrite -nat_to_bin0 algo_correct //.\n  by rewrite mulr0n add0r.\nQed.\n\nLemma algo_nils w n P Q : w != 0%N -> algoG w (nat_to_bin n) [::] P Q = P *+ n.\nProof. \n  move=> wNz.\n  rewrite -nat_to_bin0 algo_correct //.\n  by rewrite mulr0n addr0.\nQed.\n\nEnd Multiexponentiation.\n\n\nSection Decomposition.\n\n(****************************************)\n(*        short vectors                 *)\n(****************************************)\n(*  The Algorithm :                     *)          \n(*                                      *)                   \n(* Let E ec over Fq                     *) \n(* Let P <- E(Fq) of prime order n      *) \n(* Let h endomorphism over Fq and       *)\n(* Let l : nat, st h(P) = [l]*P         *)\n(*                                      *)\n(* Input : n, l, k                      *)\n(* Output k1 and k2 st k = k1 + k2 * l [mod n]       *)\n(*                                                   *)\n(*   Methodology                                     *)\n(* Following the GLV-paper we can divide the problem *)\n(*   into the two following subproblems:             *)\n(* (1) finding two short linearly ind vectors v1 = (x1, y1), v2 = (x2, y2) st  *)\n(* f (v1) = f (v2) = 0 i.e.                                                    *) \n(* (x1 + lamda * y1) mod n = (x2 + lamda * y2) mod n  = 0                      *)\n(* (2) find vector v in the lattice L(v1, v2) close to (k, 0)                  *)\n(* Then we take (k1 , k2) = (k, 0) - v                                         *)\n(*******************************************************************************)\n\nDefinition P (a b : nat) (r : nat) (x y : int) :=\n  r%:Z = x * a%:Z + y * b%:Z.\n\n Fixpoint eea_rec (r' : nat) (u' v' : int) (acc : seq (nat * int * int)) n :=\n  match n with\n  | 0    => None\n  | n.+1 =>\n    if   r' == 0%N\n    then Some acc\n    else\n      let: (r, u, v) := head (0%N, 0, 0) acc in\n        let (q, m) := (r %/ r', r %% r') in\n          eea_rec m (u - q%:Z * u') (v - q%:Z * v') ((r', u', v') :: acc) n\n  end.\n\nDefinition eea (a b : nat) : seq (nat * int * int) :=\n  if   a == 0%N\n  then [:: (b, 0, 1)]\n  else odflt [::] (eea_rec b 0 1 [:: (a, 1, 0)] (maxn a b).+1).\n\n(***************************)\n\nLemma relation_eea_rec a b: \n  forall r' u' v' (acc : (seq (nat * int * int))) n,\n    (P a b) r' u' v' ->\n    (forall r x y, (r, x, y) \\in acc -> (P a b) r x y )-> \n    acc != [::] -> \n    (forall r u v, (r, u, v) \\in odflt [::] (eea_rec r' u' v' acc n) -> \n      (P a b) r u v).\nProof.\n  move=> r' u' v' acc n.\n  elim : n acc r' u' v' => [//|n IH acc r' u' v']. \n  case Hr' : r' IH => [//=|m]  IH P1 inacc acc_Nnil r u v /=.\n  set R := head _ _ .\n  have : R = head (0%N, 0, 0) acc. done. \n  move: R => [[r1 u1] v1] HR H.\n  apply : (IH  ((m.+1, u', v') :: acc) (r1 %% m.+1) (u1 - (r1 %/ m.+1)%:Z * u') (v1 - (r1 %/ m.+1)%:Z * v')); \n    rewrite //=; last first.\n  + move => r0 x y; rewrite in_cons; case/orP.\n  by move/eqP=>  [-> -> ->].\n  by apply: inacc.\n  + have HP : P a b r1 u1 v1.\n  apply: inacc; by rewrite HR -nth0 mem_nth // lt0n size_eq0.\n  move: HP; rewrite /P => HP; rewrite -Hr'.\n  set k := _ %% _; set q := _ %/ _.\n  rewrite !mulrBl addrAC addrA -HP -!mulrA -addrA -!mulNr -(mulrDr (- q%:Z) (v' * b) (u' * a)).\n  rewrite -Hr' /P in P1. \n  rewrite [_ * _ + _ * _]addrC -P1 /k /q {2}(divn_eq r1 r') mulNr.\n  symmetry; apply/eqP; by rewrite subr_eq addrC.\nQed.\n\n\nLemma relation_eea a b :\n  forall v,  \n    let: (r, x, y) := v in\n      (r, x, y) \\in (eea a b) -> (P a b) r x y.\nProof.\n  move=> [[r x] y]; rewrite /eea /P.\n  case Ha : (a == 0%N).\n  + by rewrite mem_seq1 => /eqP [-> -> ->]; rewrite mul0r mul1r add0r.\n  + set d := (maxn _ _).+1 ; set acc := [:: _]; move=> H.\n  apply: (relation_eea_rec a b b 0 1 acc d).\n  * by rewrite /P mul0r add0r mul1r.\n  * move=> r1 x1 y1; rewrite /acc /P.  \n  by rewrite mem_seq1 => /eqP [-> -> ->]; rewrite mul0r mul1r addr0.\n  * by rewrite /acc.\n  done.\nQed.\n\n\nLemma eea_mod a b :\n  forall v,  \n    let: (r, x, y) := v in\n      (r, x, y) \\in (eea a b) -> r%:Z - y * b%:Z = x * a%:Z.  \nProof.\n  move=> [[r x] y] H.\n  move: (relation_eea a b (r, x, y) H).\n  rewrite /P; move/eqP; rewrite -subr_eq; move/eqP => //.\nQed.\n\n\nLemma in_acc_in_eea r u v (acc : seq ( nat * int * int)) \nn (x : nat * int * int) :\n(r <= n)%N -> \nx \\in acc -> x \\in odflt [::] (eea_rec r u v acc n.+1). \nProof.\nelim : n acc r u v x.\n+ move=> acc r u v x; rewrite leqn0.\nmove/eqP => -> //.\n+ move=> n IH acc r u v x rleqSn xin.\ncase Head : (head (0%N, 0%:Z, 0%:Z) acc) => [[r1 u1] v1]. \nset q := r1 %/ r; set m := r1 %% r.\nhave H1 : r == 0%N -> odflt [::] (eea_rec r u v acc n.+2) = acc.\n* move/eqP => -> //.\nhave H2 : r != 0%N -> eea_rec r u v acc n.+2 = \neea_rec m (u1 - q%:Z * u) (v1 - q%:Z * v) ((r, u, v) :: acc) n.+1.\n* move=> rnz; by rewrite //= Head (negbTE rnz) /m.\ncase Hr : (r == 0%N); first by rewrite (H1 Hr).\nrewrite (H2 (negbT Hr)); apply: IH.\nrewrite /m; move: rleqSn.\nrewrite leq_eqVlt; move/orP; case => H.\n* by rewrite (eqP H) -ltnS ltn_mod.\n* have : (r1 %% r < r)%N. \nby rewrite ltn_mod lt0n (negbT Hr).\nmove=> lt2; rewrite -ltnS.\nby rewrite (ltn_trans lt2 H).\n* rewrite in_cons; apply/orP; by right.\nQed.\n\nLemma size_cons : forall (T : Type) (x : T) (xs : seq T), \nsize (x :: xs) = (size xs).+1.  \nProof. by rewrite {1}/size. Qed.\n\nLemma eea_size_nz a b :\na != 0%N -> b != 0%N -> (size (eea a b) > 1)%N.\nProof.\nmove=> a_nz b_nz.\nhave a_in : (a, 1, 0) \\in (eea a b).\n+ rewrite /eea (negbTE a_nz). \n  apply: in_acc_in_eea; by rewrite ?inE ?eqxx ?leq_maxr.\nhave b_in : (b, 0, 1) \\in (eea a b).\n  rewrite /eea (negbTE a_nz) /= (negbTE b_nz).\n  case Hmaxn : (maxn _ _)=> [|n].  \n+ move: Hmaxn; rewrite /maxn; case ineq : (a < b)%N => H.\n  by move: b_nz; rewrite H.\n  by move: a_nz; rewrite H.\n+ apply: in_acc_in_eea.\n* rewrite -ltnS -Hmaxn; move: (leq_maxr a b)=> H2.\n  have H1: (a %% b < b)%N by rewrite ltn_mod lt0n.\n  move: H2; rewrite leq_eqVlt; move/orP; case.\n  + move/eqP=> H2; rewrite -H2 ltn_mod lt0n //.\n  + by apply: ltn_trans.\n* rewrite inE; apply/orP; left; done.\ncase: (eea a b) a_in b_in => [//|x xs].\nrewrite in_cons; move/orP; case=> A.\n+ rewrite in_cons; move/orP; case=> B.\n  move/eqP:A => A; move:B; rewrite -A. \n  by rewrite !xpair_eqE //= oner_eq0 Bool.andb_false_r. \n  rewrite size_cons; case: xs B => [//| y ys B].\n  by rewrite size_cons.\n+ rewrite in_cons; move/orP; case=> B.\n  move/eqP:B => B; rewrite size_cons.\n  case: xs A => [//| y ys A]; by rewrite size_cons.\n  rewrite size_cons; case: xs A B => [//| y ys A].\n  by rewrite size_cons.\nQed.\n\n\nDefinition filter_sqrr (n : nat) (rs : seq (nat * int * int)) :=\n[seq t <- rs | let: (r, x, y) := t in (n <= r ^2)%N].\n\n\nDefinition eea_sqrr (n l : nat) :=\nfilter_sqrr n (eea n l).\n\n\nLemma head_in n l :  head (0%N, 0%:Z, 0%:Z) (eea_sqrr n l) \\in eea n l. \nProof.\nrewrite /eea_sqrr; set s := eea _ _.\nhave Hs : forall x, x \\in (filter_sqrr n s) -> x \\in s.\n+ move=> x; rewrite /filter_sqrr mem_filter.\nmove/andP; case=> _ -> //.\n+ apply: Hs; rewrite -nth0; apply: mem_nth.\nrewrite lt0n size_eq0 /filter_sqrr /s -has_filter //=.\napply/hasP => //=; case Hn : n => [|k].\n+ rewrite /eea //=; exists (l, 0, 1); rewrite ?inE ?eqxx ?leq0n //.\n+ rewrite /eea.\nhave Hk : (k.+1 == 0%N) = false by [].\nrewrite Hk; clear Hk; exists (k.+1, 1, 0).\napply: in_acc_in_eea; rewrite ?leq_maxr ?inE //.\nclear Hn; case:k => [//|k].\nrewrite -mulnn -{1}[k.+1]mul1n.\nby apply: ltn_mul.\nQed.\n\n\n\nLemma eea_size_gt0 a b :\n(size (eea a b) > 0)%N.\nProof.\nrewrite lt0n size_eq0.\ncase H: (eea a b)=> [|//].\nmove: (head_in a b); by rewrite H.\nQed.\n\n\n(* as it is in the math proof but for our case is just the index of the head *)\n(* not used in the proof *)\nDefinition maxrseq (n l : nat) :=\n\\max_(i <- (eea_sqrr n l)) (index i (eea n l)). \n\nDefinition index_hd (n l : nat) :=\nindex (head (0%N, 0, 0) (eea_sqrr n l)) (eea n l).\n\n(* before\nDefinition base (n l : nat) :=\nif (l %| n) then ((l, -1),(n, 0)) else\nlet m := index_hd n l in \nlet: (r1, x1, y1) := nth (0%N, 0, 0) (eea n l) m.-1 in \nlet: (r0, x0, y0) := nth (0%N, 0, 0) (eea n l) m in \nlet: (r2, x2, y2) := nth (0%N, 0, 0) (eea n l) m.-2 in \nif (r0%:Z ^+ 2 + y0 ^+ 2 <= r2%:Z ^+ 2 + y2 ^+ 2) then ((r1, -y1),(r0, -y0))\nelse ((r1, -y1),(r2, -y2)).\n(*  what is going on with the first if branch :                    *)\n(*  if l %| n then size (eea n l) == 2                             *)\n(*  in that case we have m = index_hd n l = 0 or 1                 *)\n(*  and then m-1 or m-2 = -1 in theory                             *)\n(*  but by definition in nat, 0.-1 = 0                             *)\n(*  i.e. if m == 0 => m.-1 == 0 => m.-2 == 0  case 5 5             *)\n(*  in practice we never enter the if branch because n is prime    *)\n(*  (page 4 of the GLV article :) Let E be an ec defined over Fq   *)\n(*   and P <- E(Fq) be a point of prime order n                    *)\n\n(*  in the case that l %| n we definitely have a problem but it will never happen  *)\n(*  if l does not divide n then size (eea n l) >= 3                                *)\n(*  but in that case we may have problems too                                      *)\n(*  because nothing stops m from being 1 or 0 ,                                    *) \n(*  (case 9 8,  m = 1) (case 9 87, m = 0)                                          *)\n(*  m == 0 -> take (triplet_0, triplet_1) what else can I do ?                     *)\n(*  m == 1 -> take (triplet_0, triplet_1) this is normal enough                    *)\n*)\n\nDefinition base (n l : nat) :=\nlet m := index_hd n l in \nif (m <= 1)%N then \nlet: (r0, x0, y0) := nth (0%N, 0, 0) (eea n l) 0%N in \nlet: (r1, x1, y1) := nth (0%N, 0, 0) (eea n l) 1%N in \n((r0, -y0),(r1, -y1))\nelse \nlet: (r1, x1, y1) := nth (0%N, 0, 0) (eea n l) m.-1 in \nlet: (r0, x0, y0) := nth (0%N, 0, 0) (eea n l) m in \nlet: (r2, x2, y2) := nth (0%N, 0, 0) (eea n l) m.-2 in \nif (r0%:Z ^+ 2 + y0 ^+ 2 <= r2%:Z ^+ 2 + y2 ^+ 2) then ((r1, -y1),(r0, -y0))\nelse ((r1, -y1),(r2, -y2)).\n\n\n(****************************************************)\n(* n != 0 ok because n = order of the point & n prime *)\n(* l != 0 ok because l from the endomorphism of the curve *)\n(* to clean *)\nLemma base_modn_snd n l :\nn != 0%N -> l != 0%N ->\nlet (u,v) := base n l in \n((v.1)%:Z + v.2 * l = 0 %[mod n])%Z.\nProof.\nmove=> n_nz l_nz.\ncase Hbase : (base n l)=> [u v]. \napply /eqP.\nrewrite eqz_mod_dvd subr0.\nset m := index_hd n l. \ncase Hm : (m <= 1)%N.\n+ move : (Hbase); rewrite /base Hm.\ncase Hnth0 : (nth (0%N, 0, 0) (eea n l) 0) => [[r0 x0] y0]. \ncase Hnth1 : (nth (0%N, 0, 0) (eea n l) 1) => [[r1 x1] y1]. \nmove/eqP; rewrite xpair_eqE; move/andP; case => Hu Hv.\nrewrite (surjective_pairing u) in Hu; rewrite (surjective_pairing v) in Hv.\nmove : Hv; rewrite xpair_eqE; case/andP; rewrite eq_sym; move/eqP=> -> //.\nrewrite eq_sym; move/eqP=> -> //.\napply/dvdzP.\nexists x1.\nrewrite mulNr.\napply: (eea_mod n l (r1, x1, y1)).\nrewrite -Hnth1; apply: mem_nth.\napply: eea_size_nz => //.\n\n(* seconde case *)\nmove : (Hbase); rewrite /base Hm.\ncase Hnth : (nth (0%N, 0, 0) (eea n l) m.-1) => [[rm xm] ym].\ncase Hnth0 : (nth (0%N, 0, 0) (eea n l) m) => [[rm0 xm0] ym0]. \ncase Hnth2 : (nth (0%N, 0, 0) (eea n l) m.-2) => [[rm2 xm2] ym2]. \ncase H : (rm0%:Z ^+ 2 + ym0 ^+ 2 <= rm2%:Z ^+ 2 + ym2 ^+ 2).\n\n(*one*)\nmove/eqP; rewrite xpair_eqE; move/andP; case.\nmove=> _; rewrite eq_sym; move/eqP=> //.\nrewrite (surjective_pairing v).\nmove/eqP; rewrite xpair_eqE; move/andP; case => H1 H2.\nrewrite (eqP H1) (eqP H2) //=.\napply/dvdzP.\nexists xm0.\nrewrite mulNr.\napply : (eea_mod n l (rm0, xm0, ym0)).\nrewrite -Hnth0.\napply: mem_nth.\nrewrite /m /index_hd.\nby rewrite index_mem head_in.\n\n(* two *)\nmove/eqP; rewrite xpair_eqE; move/andP; case.\nmove=> _; rewrite eq_sym; move/eqP=> //.\nrewrite (surjective_pairing v).\nmove/eqP; rewrite xpair_eqE; move/andP; case => H1 H2.\nrewrite (eqP H1) (eqP H2) //=.\napply/dvdzP.\nexists xm2.\nrewrite mulNr.\napply : (eea_mod n l (rm2, xm2, ym2)).\nrewrite -Hnth2.\napply: mem_nth.\n\nhave Hinter: (m < size (eea n l))%N.\nby rewrite /m /index_hd index_mem head_in.\n\nhave Hfst : (m.-2 < m)%N.\nmove: (leq_trans (leq_pred m.-1) (leq_pred m)).\nrewrite leq_eqVlt.\nmove/orP; case=> //.\nmove/eqP => H0.\n\ncase h : m=> [|x].\nby move: Hm; rewrite h.\nrewrite //=.\ncase X : x=> [//|y //].\napply: (ltn_trans Hfst Hinter).\nQed.\n\nLemma base_modn_fst n l :\nlet (u,v) := base n l in \n((u.1)%:Z + u.2 * l = 0 %[mod n])%Z.\nProof.\ncase Hbase : (base n l)=> [u v]. \napply /eqP.\nrewrite eqz_mod_dvd subr0.\nset m := index_hd n l. \ncase Hm : (m <= 1)%N. \n+ move : (Hbase); rewrite /base Hm.\ncase Hnth0 : (nth (0%N, 0, 0) (eea n l) 0) => [[r0 x0] y0]. \ncase Hnth1 : (nth (0%N, 0, 0) (eea n l) 1) => [[r1 x1] y1]. \nmove/eqP; rewrite xpair_eqE; move/andP; case => Hu Hv.\nrewrite (surjective_pairing u) in Hu; rewrite (surjective_pairing v) in Hv.\nmove : Hu; rewrite xpair_eqE; case/andP; rewrite eq_sym; move/eqP=> -> //.\nrewrite eq_sym; move/eqP=> -> //.\napply/dvdzP.\nexists x0.\nrewrite mulNr.\napply: (eea_mod n l (r0, x0, y0)).\nrewrite -Hnth0; apply: mem_nth.\nby rewrite eea_size_gt0.\n\nmove : (Hbase); rewrite /base Hm.\ncase Hnth : (nth (0%N, 0, 0) (eea n l) m.-1) => [[rm xm] ym].\ncase Hnth0 : (nth (0%N, 0, 0) (eea n l) m) => [[rm0 xm0] ym0]. \ncase Hnth2 : (nth (0%N, 0, 0) (eea n l) m.-2) => [[rm2 xm2] ym2]. \n\nmove=> Hu.\n\nhave U : u = (rm, -ym).\ncase H : (rm0%:Z ^+ 2 + ym0 ^+ 2 <= rm2%:Z ^+ 2 + ym2 ^+ 2).\n+ move/eqP: Hu; rewrite H //.\nrewrite xpair_eqE; move/andP; case.\nrewrite eq_sym. move/eqP=> U _; by rewrite U.\n+ move/eqP: Hu; rewrite H //.\nrewrite xpair_eqE; move/andP; case.\nrewrite eq_sym. move/eqP=> U _; by rewrite U.\nmove:U; rewrite (surjective_pairing u).\nmove/eqP; rewrite xpair_eqE; move/andP; case => H1 H2.\nrewrite (eqP H1) (eqP H2) //=.\napply/dvdzP.\nexists xm.\nrewrite mulNr.\napply: (eea_mod n l (rm, xm, ym)).\nrewrite -Hnth; apply: mem_nth.\n\nhave ineq : (m < size (eea n l))%N.\nby rewrite /m /index_hd index_mem head_in. \napply: leq_ltn_trans (leq_pred m) ineq.\nQed.\n\n\n(*approximation of n/m (in Q) by an integer*)\nDefinition approx (n m : nat) := \nlet r := n %% m in \nlet q := n %/ m in\nif (2*r <= m)%N then q else q.+1. \n\nDefinition approxZ (n m : int) :=\n((sgz n) * (sgz m)) * (approx (absz n) (absz m))%:Z.\n\n\n(*using base*) \nDefinition cramer_coefs n l k :=\nlet (u, v) := base n l in \nlet D := u.1%:Z * v.2 - u.2 * v.1%:Z in\n(approxZ (k * v.2) D, approxZ (- k * u.2) D).\n\n\nDefinition decomp (n l k : nat) : int * int :=\nlet (a, b) := cramer_coefs n l k in \nlet (u, v) := base n l in \nlet k1 := k%:Z - (a * u.1%:Z + b * v.1%:Z) in \nlet k2 := - (a * u.2 + b * v.2) in \n(k1, k2).\n\n\nLemma correct_decomp n l k :\nlet (k1, k2) := decomp n l k in\nn != 0%N -> l != 0%N -> \n(k = (k1 + k2 * l) %[mod n])%Z.\nProof.\ncase Hdecomp : (decomp n l k)=> [k1 k2]. \nmove=> nNz lNz.\nmove: Hdecomp; rewrite /decomp.\ncase Hcramer : (cramer_coefs n l k)=> [a b]. \ncase Hbase : (base n l)=> [u v]. \nmove/eqP; rewrite xpair_eqE; move/andP; case => H1 H2.\nmove: H1; rewrite eq_sym; move/eqP => -> //.\nmove: H2; rewrite eq_sym; move/eqP => -> //.\nrewrite mulNr mulrDl; apply/eqP.\nrewrite eqz_mod_dvd.\nrewrite opprB addrA opprB addrA addrC. \nrewrite addrA addrA [_ + k%:Z]addrC.\nhave Hk : k%:Z - k%:Z = 0.\nby apply/eqP; rewrite subr_eq0.\nrewrite Hk; clear Hk.\nrewrite add0r -addrA [b * v.2 * l + _]addrC.\nrewrite -addrA -[b * v.2 * l]mulrA -mulrDr.\nrewrite addrA  -[a * u.2 * l]mulrA  -mulrDr.\nrewrite [_ + u.1%:Z]addrC. \nmove : (base_modn_fst n l); rewrite Hbase. \nmove/eqP; rewrite eqz_mod_dvd subr0; move=> Hu.\nmove : (base_modn_snd n l nNz lNz); rewrite Hbase.\nmove/eqP; rewrite eqz_mod_dvd subr0; move=> Hv.\napply/ dvdzP.\nmove/dvdzP :Hu=> [x Hu].\nmove/dvdzP :Hv=> [y Hv].\nrewrite Hu Hv.\nexists (a * x + b * y).\nby rewrite mulrDl !mulrA.\nQed.\n\nEnd Decomposition.\n", "meta": {"author": "strub", "repo": "glv", "sha": "1dec9027e731cd1a23d09c17da19d04e5dd70e63", "save_path": "github-repos/coq/strub-glv", "path": "github-repos/coq/strub-glv/glv-1dec9027e731cd1a23d09c17da19d04e5dd70e63/src/multiexponentiation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7026811910670265}}
{"text": "Require Import QArith.\nRequire Import ZNatPairs.\nRequire Import Zsqrt.\n\n(** \n    encode(k1, k2) = (k1 + k2) * (k1 + k2 + 1) / 2 + k2  \n**)\n\n\nDefinition encode (k : (Z * Z)) : Q :=\nQmake \n  (((fst k) + (snd k)) * ((fst k) + (snd k) + 1) + 2 * (snd k))\n    2.\n\n(** \n    decode(z):\n        w = (sqrt(8z + 1) - 1) / 2\n        t = (w^2 + w) / 2\n        y = z - t\n        x = w - y\n        return <x, y>\n\n    x = w - (z - t)\n    y = z - t\n**)\n\nDefinition to_pos (z:Z) : positive :=\n  match z with\n    | Zpos p => p\n    | _ => 1%positive\n  end.\n\nDefinition Zsqrt_plain_pos (p : positive) : positive :=\nto_pos (Zsqrt_plain (Zpos p)).\n\nDefinition W (z : Q) : Q :=\n let x := (Zsqrt_plain (8 * (Qnum z) + (Zpos (Qden z)))) in\n let y := (Zsqrt_plain_pos (Qden z)) in\n Qmake (x - (Zpos y)) (2 * y).\n\nDefinition T (w : Q) : Q :=\n  let a := (Qnum w) in\n  let b := (Qden w) in\nQmake (a*a + a* (Zpos b)) (2 * b * b).\n\nDefinition ZofQ (x : Q) : option Z :=\n  let (q,r) := Zdiv_eucl (Qnum x) (Zpos (Qden x)) in\n  match r with\n  | Z0 => Some q\n  | Zpos r' => None\n  | Zneg r' => None\n  end.\n\n\nDefinition option_bind {A B:Type} (f : A -> option B) (o : option A) :=\nmatch o with\n| Some a => f a\n| None => None\nend.\n\nDefinition mdecode (z : Q) : option (Z * Z) :=\noption_bind (fun lhs =>\n option_bind (fun rhs => Some (lhs, rhs))\n (ZofQ (z - (T (W z)))))\n (ZofQ ((W z) - (z - T (W z)))).\n\nTheorem mdecode_some :\n forall z,\n  { zz | mdecode z = Some zz }.\nProof.\n  intros.  \nAdmitted.\n\nDefinition decode z :=\nmatch mdecode_some z with\n| exist zz _ => zz\nend.\n\nTheorem decode_encode : forall x y ,\n    decode (encode (x, y)) = (x, y).\nProof.\n intros x y.\n unfold decode.\n remember (encode (x, y)) as exy.\n destruct (mdecode_some exy) as [[ax ay] P].\n\nAdmitted.\n\nTheorem encode_decode : forall z ,\n    encode (decode z) = z.\nProof.\nAdmitted.", "meta": {"author": "dennacerise", "repo": "cantor-pairing-function", "sha": "5a131623168f64308de32ed88416cde3d840c29a", "save_path": "github-repos/coq/dennacerise-cantor-pairing-function", "path": "github-repos/coq/dennacerise-cantor-pairing-function/cantor-pairing-function-5a131623168f64308de32ed88416cde3d840c29a/impls_with_Q.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.702604890363161}}
{"text": "Require Import Nat Arith.\n\nInductive INT : Type := succ : INT -> INT |  zero : INT.\n\nFixpoint add (add_arg0 : INT) (add_arg1 : INT) : INT\n           := match add_arg0, add_arg1 with\n              | n, zero => n\n              | n, succ m => succ (add n m)\n              | add x y, z => add x (add y z)\n              | x, y => add y x\n              end.\n\nFixpoint mult (mult_arg0 : INT) (mult_arg1 : INT) : INT\n           := match mult_arg0, mult_arg1 with\n              | n, zero => zero\n              | n, succ m => add n (mult n m)\n              | zero, n => mult n zero\n              end.\n\nTheorem theorem0 : forall (n : INT) (m : INT), eq (mult n m) (mult m n).\nProof.\nAdmitted.\n\n", "meta": {"author": "ana-brendel", "repo": "coq-benchmarks", "sha": "78b9ca2993b0fb579d814ed17e63c6859e79681c", "save_path": "github-repos/coq/ana-brendel-coq-benchmarks", "path": "github-repos/coq/ana-brendel-coq-benchmarks/coq-benchmarks-78b9ca2993b0fb579d814ed17e63c6859e79681c/testing_results_initial/old_script_testing/NoLfindCall/lia/mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.7026048809535577}}
{"text": "(* Exercise 53 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_053 : ((A -> B) -> B) -> ~A -> B.\nProof.\nimp_i a1.\nimp_i a2.\nimp_e (A -> B).\nhyp a1.\nimp_i a3.\nneg_e (A).\nhyp a2.\nhyp a3.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak13/Taak13_prop053.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541561135442, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.7026048785101205}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (lf1 : natural) : natural :=\n  plus lf1 Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj43_coqofml_g4vme3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7025924290915572}}
{"text": "Require Import List.\nRequire Import Bool.\nRequire Import ZArith.\nRequire Import pomozne.\nRequire Import Recdef.\n\nFixpoint ostanek (l : list Z) : list Z :=\n  match l with\n    | nil => nil\n    | a :: l' => if (a =? najmanjsi a l')%Z then l' else a :: (ostanek l')\n  end.\n\nEval compute in (ostanek (4 :: 2 :: 6 :: 3 :: 1 :: 10 :: nil)%Z).\n\nLemma dolzina_nic (l : list Z) :\n  length l <= 0 -> l = nil.\nProof.\n  intro.\n  induction l; auto.\n  simpl in H.\n  omega.\nQed.\n\nLemma najmanjsi_spust (x y : Z) (l : list Z) :\n  x = najmanjsi x (y :: l) -> x = najmanjsi x l.\nProof.\n  intro.\n  assert (x <= y)%Z as G.\n  rewrite H.\n  apply najmanjsi_tail.\n  firstorder.\n  unfold najmanjsi in H.\n  apply Zle_is_le_bool in G.\n  now rewrite G in H.\nQed.\n\nLemma najmanjsi_dod (x y : Z) (l : list Z) :\n  y = najmanjsi y l -> (y < x)%Z -> y = najmanjsi y (x :: l).\nProof.\n  intros H G.\n  simpl.\n  apply Z.lt_le_incl in G.\n  apply Zle_is_le_bool in G.\n  now rewrite G.\nQed.\n\nLemma se_manjsi (x y : Z) (l : list Z) :\n  x = (najmanjsi x l) -> (y < x)%Z -> y = (najmanjsi y l).\nProof.\n  intros H G.\n  induction l; auto.\n  assert (x <= a)%Z as F.\n  rewrite H.\n  apply najmanjsi_tail.\n  firstorder.\n  apply najmanjsi_spust in H.\n  apply IHl in H.\n  apply najmanjsi_dod.\n  assumption.\n  firstorder.\nQed. \n\nLemma dolzina_ostanka (x : Z) (l : list Z) :\n  length (ostanek (x :: l) )= length  l.\nProof. \n  induction l.\n  - simpl.\n    now rewrite Z.eqb_refl.\n  - simpl.\n    simpl in IHl.\n    case_eq (Z.leb x a);\n    case_eq (Z.eqb a (najmanjsi a l));\n    case_eq (Z.eqb x (najmanjsi x l));\n    intros H G F; auto.\n    + rewrite H in IHl.\n      simpl.\n      simpl in IHl.\n      now rewrite IHl.\n    + apply Z.eqb_eq in G.\n      rewrite G in F.\n      apply Z.leb_gt in F.\n      apply Z.lt_neq in F.\n      apply Z.neq_sym in F.\n      apply Z.eqb_neq in F.\n      now rewrite F.\n    + apply Z.eqb_eq in G.\n      rewrite <- G.\n      apply Z.leb_gt in F.\n      apply Z.lt_neq in F.\n      apply Z.neq_sym in F.\n      apply Z.eqb_neq in F.\n      now rewrite F.\n    + apply Z.eqb_eq in H.\n      apply Z.eqb_neq in G.\n      apply Z.leb_gt in F.\n      assert (a = najmanjsi a l) as E.\n      apply (se_manjsi x a);assumption.\n      firstorder.\n    + rewrite H in IHl.\n      simpl in IHl.\n      apply Z.leb_gt in F.\n      assert (najmanjsi a l < x)%Z as E.\n      apply (trans (najmanjsi a l) a x).\n      apply najmanjsi_head.\n      assumption.\n      apply Z.lt_neq in E.\n      apply Z.neq_sym in E.\n      apply Z.eqb_neq in E.\n      rewrite E.\n      simpl.\n      now apply eq_S.   \nQed.\n\nFunction bsort (l : list Z) {measure length l} :=\n  match l with\n    |nil => nil\n    | x :: l' => (najmanjsi x l') :: (bsort (ostanek (x :: l')))\n  end.\nProof.\n  intros l x l' H.\n  rewrite (dolzina_ostanka x l').\n  firstorder.\nDefined.\n\nLemma ostanek_pod (x : Z) (l : list Z) :\n  In x (ostanek l) -> In x l.\nProof.\n  intro.\n  induction l.\n  - simpl in H.\n    contradiction.\n  - simpl in H.\n    case_eq (a =? najmanjsi a l)%Z; intro G.\n    + rewrite G in H.\n      simpl.\n      now right.\n    + rewrite G in H.\n      simpl in H.\n      destruct H.\n      * firstorder.\n      * apply IHl in H.\n        firstorder.\nQed.\n\nLemma urejen_najmanjsi (x : Z) (l : list Z) :\n  urejen l -> (forall y, In y l -> (x <= y)%Z) -> urejen (x :: l).\nProof.\n  intros H G.\n  destruct l.\n  now simpl.\n  simpl.\n  split.\n  - apply G.\n    firstorder.\n  - destruct l; auto.\nQed.\n\nLemma ohranjanje_el (n : nat) (x : Z) (l : list Z) :\n  length l <= n -> In x (bsort l) -> In x l.\nProof.\n  generalize l.\n  induction n; intros l' H G.\n  - destruct l'.\n    + now simpl in G.\n    + simpl in H.\n      omega.\n  - apply le_lt_or_eq in H.\n    destruct H.\n    + apply IHn.\n      now apply lt_n_Sm_le in H.\n      assumption.\n    + destruct l'.\n      simpl in H.\n      omega.\n      rewrite bsort_equation in G.\n      apply in_inv in G.\n      destruct G as [F|F].\n      * rewrite <- F.\n        apply najmanjsi_In.\n      * apply IHn in F.\n        now apply ostanek_pod.\n        rewrite dolzina_ostanka.\n        simpl in H.\n        omega.\nQed.         \n\nLemma bsort_ureja_n (n : nat) (l : list Z) :\n  (length l <= n)%nat -> urejen (bsort l).\nProof.\n  generalize l.\n  induction n; intros l' H.\n  - destruct l'.\n    + now simpl.\n    + simpl in H.\n      assert (S (length l') > 0) as G.\n      apply gt_Sn_O.\n      apply le_not_gt in H.\n      contradiction.\n  - apply le_lt_or_eq in H.\n    destruct H.\n    + apply lt_n_Sm_le in H.\n      apply IHn in H.\n      assumption.\n    + destruct l'.\n      * now simpl.\n      * simpl in H.\n        apply eq_add_S in H.\n        rewrite bsort_equation.\n        assert (length (ostanek (z :: l')) = n) as G.\n        now rewrite dolzina_ostanka.\n        apply urejen_najmanjsi.\n        apply IHn.\n        omega.\n        intros y F.\n        apply (ohranjanje_el n) in F.\n        simpl in F.\n        { case_eq (z =? najmanjsi z l')%Z; intro D.\n        - rewrite D in F. \n          now apply najmanjsi_tail.\n        - rewrite D in F.\n          simpl in F.\n          destruct F.\n          + rewrite H0.\n            apply najmanjsi_head.\n          + apply ostanek_pod in H0.\n            now apply najmanjsi_tail.\n        }\n        omega.\nQed.\n\nTheorem bsort_ureja : forall l : list Z, urejen (bsort l).\nProof.\n  intro.\n  apply (bsort_ureja_n (length l)).\n  omega.\nQed.\n\nLemma pojavi_notIn (x : Z) (l : list Z) : \n  ~In x l -> pojavi x l = pojavi x (ostanek l).\nProof.\n  intro.\n  induction l; auto.\n  simpl in H.\n  apply Decidable.not_or in H.\n  destruct H as [H G].\n  apply IHl in G.\n  simpl.\n  apply Z.neq_sym in H.\n  apply Z.eqb_neq in H.\n  rewrite H.\n  case_eq (Z.eqb a (najmanjsi a l)); intro F; auto.\n  simpl.\n  now rewrite H.\nQed.\n\nLemma najmanjsi_ostanek (x : Z) (l : list Z) :\n  (x = najmanjsi x l)%Z -> In x l -> S (pojavi x (ostanek l)) = pojavi x l.\nProof.\n  intros H G.\n  induction l.\n  now simpl in G.\n  case_eq (Z.eqb a (najmanjsi a l)); intro F.\n  + simpl.\n    rewrite F.\n    simpl in G.\n    destruct G as [E|E].\n    * rewrite E.\n      now rewrite Z.eqb_refl.\n    * apply Z.eqb_eq in F.\n      assert ((a <= x)%Z /\\ (x <= a)%Z) as D.\n      split.\n      rewrite F.\n      now apply najmanjsi_tail.\n      rewrite H.\n      apply najmanjsi_tail.\n      firstorder.\n      assert (x = a) as C.\n      omega.\n      apply Z.eqb_eq in C.\n      now rewrite C.\n  + simpl.\n    rewrite F.\n    case_eq (Z.eqb x a); intro E.\n    * apply Z.eqb_neq in F.\n      apply Z.eqb_eq in E.\n      rewrite E in H.\n      simpl in H.\n      rewrite Z.leb_refl in H.\n      firstorder.\n    * simpl.\n      rewrite E.\n      {destruct G as [D|D].\n      - apply Z.eqb_neq in E.\n        firstorder.\n      - apply IHl.\n        apply Z.eqb_eq.\n        case_eq (Z.leb x a); intro C.\n        + simpl in H.\n          rewrite C in H.\n          now apply Z.eqb_eq.\n        + apply Z.leb_gt in C.\n          assert (x <= a)%Z as B.\n          rewrite H.\n          apply najmanjsi_tail.\n          firstorder.\n          firstorder.\n        + assumption. }\nQed.\n\nLemma nenajmanjsi_ostanek (x : Z) (l : list Z) :\n  (x <> najmanjsi x l)%Z -> pojavi x (ostanek l) = pojavi x l.\nProof.\n  intro.\n  induction l; auto.\n  simpl.\n  case_eq (Z.eqb a (najmanjsi a l)); case_eq (Z.eqb x a); intros F E.\n  + apply Z.eqb_eq in F.\n    rewrite F in H.\n    apply Z.eqb_eq in E.\n    simpl in H.\n    rewrite Z.leb_refl in H.\n    firstorder.\n  + reflexivity.\n  + simpl.\n    rewrite F.\n    apply eq_S.\n    apply IHl.\n    apply Z.eqb_eq in F.\n    apply Z.eqb_neq in E.\n    now rewrite F.\n  + simpl.\n    rewrite F.\n    apply IHl.\n    apply Z.eqb_neq.\n    simpl in H.\n    case_eq (Z.leb x a); intro G.\n    rewrite G in H.\n    now apply Z.eqb_neq.\n    rewrite G in H.\n    case_eq (Z.eqb x (najmanjsi x l)); intro D; auto.\n    apply Z.eqb_eq in D.\n    apply Z.eqb_neq in F.\n    apply Z.eqb_neq in E.\n    apply Z.leb_gt in G.\n    assert (a = najmanjsi a l \\/ In (najmanjsi a l) l) as C.\n    apply najmanjsi_inv.\n    destruct C as [C|C];firstorder.\n    apply (najmanjsi_tail x (najmanjsi a l) l) in C.\n    rewrite <- D in C.\n    assert (x <= a)%Z as B.\n    transitivity (najmanjsi a l);auto.\n    apply najmanjsi_head.\n    omega.\nQed.\n\nLemma pomo_In (x : Z) (l : list Z) :\n  In x l -> length l > 0.\nProof.\n  intro.\n  destruct l.\n  now simpl in H.\n  simpl.\n  omega.\nQed.\n\nLemma pomo_ostanek (x : Z) (l : list Z) :\n  length l > 0 -> length (x :: ostanek l) = length l.\nProof.\n  generalize x.\n  induction l.\n  intros.\n  now simpl in H.\n  intros.\n  simpl.\n  case_eq (Z.eqb a (najmanjsi a l)).\n   + now intro.\n   + intro.\n     apply Z.eqb_neq in H0.\n     assert (a = najmanjsi a l \\/ In (najmanjsi a l) l). apply najmanjsi_inv.\n     destruct H1 as [F | F].\n      - contradiction.\n      - assert (length l > 0).\n         * now apply pomo_In in F.\n         * apply eq_S.\n           now apply (IHl a) in H1.\nQed.\n\nLemma pojavi_bsort_n (x : Z) (n : nat) (l : list Z) :\n  length l <= n -> pojavi x l = pojavi x (bsort l).\nProof.\n  generalize x l.\n  induction n; intros y l' H.\n  - apply dolzina_nic in H.\n    now rewrite H.\n  - apply le_lt_or_eq in H.\n    destruct H as [H|H].\n    + apply lt_n_Sm_le in H.\n      now apply (IHn y l') in H.\n    + destruct l';auto.\n      simpl in H.\n      apply eq_add_S in H.\n      rewrite bsort_equation.\n      simpl.\n      case_eq (Z.eqb y z);\n      case_eq (Z.eqb z (najmanjsi z l'));\n      case_eq (Z.eqb y (najmanjsi z l'));\n      intros G F E.\n      * apply eq_S.\n        apply (IHn y l').\n        omega.\n      * apply Z.eqb_eq in E.\n        apply Z.eqb_eq in F.\n        apply Z.eqb_neq in G.\n        rewrite E in G.\n        firstorder.\n      * apply Z.eqb_eq in E.\n        apply Z.eqb_neq in F.\n        apply Z.eqb_eq in G.\n        rewrite E in G.\n        firstorder.\n      * apply Z.eqb_eq in E.\n        rewrite E.\n        assert (pojavi z (z :: ostanek l') = S(pojavi z l')) as D.\n        simpl.\n        rewrite Z.eqb_refl.\n        apply eq_S.\n        apply (nenajmanjsi_ostanek ).\n        now apply Z.eqb_neq in F.\n        rewrite  <- D.\n        apply IHn.\n        simpl.\n        destruct l'.\n        simpl in F.\n        apply Z.eqb_neq in F.\n        omega.\n        rewrite dolzina_ostanka.\n        simpl in H.\n        omega.\n      * apply Z.eqb_eq in G; apply Z.eqb_eq in F; apply Z.eqb_neq in E.\n        firstorder.\n      * apply IHn.\n        omega.\n      * {\n        assert (S (pojavi y (z :: ostanek l')) = pojavi y l') as D.\n        simpl.\n        rewrite E.\n        apply najmanjsi_ostanek.\n         - apply Z.eqb_eq in G.\n           apply Z.eqb_neq in F.\n           now apply najmanjsi_manjsi in G.\n         - apply Z.eqb_eq in G.\n           apply Z.eqb_neq in E.\n           now apply (najmanjsi_neq y z l') in E.\n         - simpl in D.\n           rewrite E in D.\n           apply Z.eqb_eq in G.\n           assert (y = najmanjsi z l') as GG. assumption.\n           apply najmanjsi_inv1 in G.\n           destruct G as [G|G].\n           apply Z.eqb_neq in E; contradiction.\n           assert (y = najmanjsi z l') as GGG. assumption.\n           apply najmanjsi_manjsi in GG.\n           rewrite <- D.\n           apply eq_S.\n           assert (length (z :: ostanek (l')) <= n).\n            + rewrite <- (pomo_ostanek z l') in H.\n              firstorder.\n              now apply pomo_In in G.\n            + apply (IHn y) in H0.\n              rewrite <- H0.\n              simpl.\n              now rewrite E.\n        }\n      * {\n        assert (pojavi y (z :: ostanek l') = pojavi y l') as D.\n        - simpl.\n          rewrite E.\n          apply Z.eqb_neq in G; apply Z.eqb_neq in F; apply Z.eqb_neq in E.\n          case_eq (Z.eqb y (najmanjsi y l'));intro C.\n          + apply Z.eqb_eq in C.\n            assert (~ In y l') as B.\n            apply (nenajmanjse_fore y z l'); assumption.\n            rewrite <- pojavi_notIn; auto.           \n          + apply Z.eqb_neq in C.\n            now apply nenajmanjsi_ostanek.\n        - rewrite <- D.\n          apply IHn.\n          simpl.\n          destruct l'.\n          simpl in F.\n          apply Z.eqb_neq in F.\n          omega.\n          rewrite dolzina_ostanka.\n          simpl in H.\n          omega.\n        }\nQed.\n\nTheorem bsort_permutira : forall l : list Z, permutiran l (bsort l).\nProof.\n  intro l.\n  unfold permutiran.\n  intro x.\n  now apply (pojavi_bsort_n x (length l) l).\nQed.", "meta": {"author": "TStepi", "repo": "coq-sort", "sha": "df80cac8633b3bb5c6636637db97be89fc6f9527", "save_path": "github-repos/coq/TStepi-coq-sort", "path": "github-repos/coq/TStepi-coq-sort/coq-sort-df80cac8633b3bb5c6636637db97be89fc6f9527/bsort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7025907811484062}}
{"text": "Set Implicit Arguments.\nRequire Import Omega.\nRequire Import Coq.Numbers.Natural.Peano.NPeano. (* [mod] *)\nRequire Import Coq.Arith.Wf_nat.                 (* [lt_wf] *)\nRequire Import Coq.Wellfounded.Inclusion.        (* [wf_incl] *)\nRequire Import Coq.Wellfounded.Inverse_Image.    (* [wf_inverse_image] *)\nRequire Import Coq.Arith.Peano_dec.              (* [eq_nat_dec] *)\nRequire Import Loop.\n\n(* This file contains a few demos of the use of [Loop]. *)\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Use OCaml integers at extraction time. *)\n\nRequire Import ExtrOcamlNatInt.\nExtract Inlined Constant modulo => \"(mod)\".\nExtract Inlined Constant plus => \"(+)\".\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Demo 1. Euclid's GCD algorithm. *)\n\n(* The body of Euclid's loop. *)\n\nDefinition gcd_body (ab : nat * nat) :=\n  let (a, b) := ab in\n  if eq_nat_dec b 0 then\n    MsgFinished a\n  else\n    MsgContinue (b, a mod b).\n\n(* The algorithm terminates because [b], the second component of the\n   state, decreases at every iteration. *)\n\nDefinition gcd_evolution (s' s : nat * nat) :=\n  snd s' < snd s.\n\nLemma gcd_wf:\n  well_founded gcd_evolution.\nProof.\n  unfold gcd_evolution. eapply wf_inverse_image. eapply lt_wf.\nQed.\n\nLemma gcd_body_evolution:\n  forall s s',\n  gcd_body s = MsgContinue s' ->\n  gcd_evolution s' s.\nProof.\n  unfold gcd_body. intros [ a b ] [ a' b' ].\n  destruct (eq_nat_dec b 0).\n  { congruence. }\n  { intros h. injection h. clear h. intros. subst. unfold gcd_evolution.\n    eauto using Nat.mod_upper_bound. }\nQed.\n\n(* Thus, we are allowed to construct the loop. *)\n\nDefinition gcd : nat * nat -> nat :=\n  loop gcd_body\n    gcd_wf gcd_body_evolution.\n\n(* This code has the desired property. *)\n\nLemma gcd_eq:\n  forall a b,\n  gcd (a, b) =\n    if eq_nat_dec b 0 then\n      a\n    else\n      gcd (b, a mod b).\nProof.\n  intros. unfold gcd, gcd_body. rewrite loop_eq.\n  (* The match/match optimisation must be justified by a case analysis. *)\n  destruct (eq_nat_dec b 0); eauto.\nQed.\n\n(* The code can be extracted as follows. Inlining [loop] and [gcd_body]\n   triggers a match/match optimisation in Coq's extraction engine, and allows\n   us to obtain the clean code that we would have written by hand in OCaml.\n   Although this code apparently constructs a pair at every iteration, a\n   recent OCaml compiler is able to produce machine code that keeps the\n   parameters [a] and [b] in two registers. *)\n\nExtraction Inline gcd_body.\n\nExtraction gcd.\n(* This should yield the following OCaml code:\n\nlet rec gcd = function\n| (a, b) -> if (=) b 0 then a else let s' = (b, ((mod) a b)) in gcd s'\n\nso we have, in OCaml:\n\n# gcd (25, 185);;\n- : int = 5\n# gcd (42, 735);;\n- : int = 21\n# gcd (8, 13);;\n- : int = 1\n\n*)\n\n(* ---------------------------------------------------------------------------- *)\n\n(* Demo 2. Counting up to 100, two by two, accumulating a list of indices.\n   This is a loop whose termination argument relies on an invariant, namely\n   the property of being even and less than (or equal to) 100. *)\n\nRequire Import List.\n\n(* The type of the current state. *)\n\nNotation state := (nat * list nat)%type.\n\n(* The loop body. *)\n\nDefinition MAX := 100.\nDefinition TWO := 2.\n\nDefinition count_body (s : state) :=\n  let (n, ns) := s in\n  if eq_nat_dec n MAX then\n    MsgFinished ns\n  else\n    MsgContinue (n + TWO, n :: ns).\n\n(* The evolution relation. *)\n\nDefinition count_evolution (s' s : state) :=\n  let (n , _) := s  in\n  let (n', _) := s' in\n  n' = n + 2.\n\n(* The invariant. *)\n\nDefinition count_invariant (s : state) :=\n  let (n , _) := s in\n  n = 2 * (n/2) /\\ n <= MAX.\n\n(* A technical arithmetic lemma. *)\n\nLemma plus2_div2:\n  forall n,\n  (n + 2) / 2 = n/2 + 1.\nProof.\nAdmitted.\n\n(* We must prove the following facts. *)\n\nLemma wf_count_evolution:\n  well_founded (fun s' s =>\n    count_evolution s' s /\\ count_invariant s /\\ count_invariant s'\n  ).\nProof.\n  eapply wf_incl; [ |\n    eapply wf_inverse_image\n      with (f := fun s : state => let (n, _) := s in 50 - n/2);\n    eapply lt_wf\n  ].\n  unfold count_evolution, count_invariant. intros [ n' _ ] [ n _ ] ?.\n  repeat match goal with h: _ /\\ _ |- _ => destruct h end.\n  generalize (plus2_div2 n); intro.\n  unfold MAX in *. omega.\nQed.\n\nLemma count_body_evolution:\n  forall s s', count_invariant s -> count_body s = MsgContinue s' -> count_evolution s' s.\nProof.\n  unfold count_body, count_evolution, count_invariant.\n  intros [ n ? ] [ n' ? ] [ ? ? ].\n  destruct (eq_nat_dec n MAX); [ congruence | ].\n  intro h. injection h. clear h. intro h.\n  unfold TWO in *. omega.\nQed.\n\n(* We isolate the following auxiliary lemma because it is used in the\n   statement of [count_eq_simplified] below. *)\n\nLemma count_invariant_preserved_aux:\n  forall n ns, count_invariant (n, ns) -> n <> MAX -> count_invariant (n + 2, n :: ns).\nProof.\n  unfold count_invariant. intros ? ? [ ? ? ] ?.\n  split.\n  { generalize (plus2_div2 n); intro. omega. }\n  { unfold MAX in *. omega. }\nQed.\n\nLemma count_invariant_preserved:\n  forall s,\n  count_invariant s ->\n  forall s',\n  count_body s = MsgContinue s' ->\n  count_invariant s'.\nProof.\n  unfold count_body, count_evolution. intros [ n ns ]. intros.\n  destruct (eq_nat_dec n MAX); [ congruence | msg_injection ].\n  eauto using count_invariant_preserved_aux.\n  (* We use [Defined] as opposed to [Qed] because we need to unfold\n     this definition in the proof of [count_eq_simplified]. *)\nDefined.\n\n(* Thus, we are allowed to construct the loop. *)\n\nDefinition count :=\n  loop_with_invariant count_body\n    wf_count_evolution count_body_evolution count_invariant_preserved.\n\n(* This code has the desired property. *)\n\nLemma count_eq:\n  forall s,\n  forall hs : count_invariant s,\n  count (exist _ s hs) =\n    match count_body s as m return (count_body s = m -> list nat) with\n    | MsgContinue s' => fun eq =>\n        count (exist _ s' (count_invariant_preserved _ hs eq))\n    | MsgFinished t  => fun _  =>\n        t\n    end eq_refl.\nProof.\n  intros. unfold count. rewrite loop_eq_with_invariant. fold count. reflexivity.\nQed.\n\n(* By inlining [count_body] in the statement of [count_eq] and\n   exchanging the two [match] constructs, we obtain the following\n   somewhat simplified statement of the fixed point equation. *)\n\nLemma count_eq_simplified:\n  forall n ns,\n  forall hs : count_invariant (n, ns),\n  count (exist _ (n, ns) hs) =\n    match eq_nat_dec n MAX with\n    | right hneq =>\n        count (exist _ (n + 2, n :: ns) (count_invariant_preserved_aux hs hneq))\n    | left  heq  =>\n        ns\n    end.\nProof.\n  intros. rewrite count_eq. unfold count_body.\n  (* It is definitely not nice to have to rely on a transparent proof!\n     So far, I haven't found a better way. Suggestions are welcome! *)\n  unfold count_invariant_preserved.\n  generalize (count_invariant_preserved_aux hs). intro cxhs.\n  destruct (eq_nat_dec n MAX).\n  { reflexivity. }\n  { reflexivity. }\nQed.\n\n(* Extraction. *)\n\n(* Unfortunately, there seems to be no generic way of translating\n   integer constants to integer constants during extraction. *)\nExtract Inlined Constant MAX => \"100\".\nExtract Inlined Constant TWO => \"2\".\n\nExtraction Inline count_body.\n\nExtraction count.\n(* This should yield the following OCaml code:\n\nlet rec count = function\n| (n, ns) ->\n  if (=) n 100 then ns else let s' = (((+) n 2), (n :: ns)) in count s'\n\nso we have, in OCaml:\n\n# count (90, []);;\n- : int list = [98; 96; 94; 92; 90]\n\n*)\n\n(* As an example of reasoning a posteriori with an extra invariant,\n   we prove that if the loop starts at [MIN], then every element in\n   the final list is greater than or equal to [MIN]. (We could also\n   prove that all of them are even and less than [MAX].) *)\n\nDefinition goal MIN (ms : list nat) :=\n  forall m, In m ms -> MIN <= m.\n\nDefinition extra_invariant MIN (s : state) :=\n  let (n, ns) := s in\n  MIN <= n /\\ goal MIN ns.\n\nLemma above_min:\n  forall MIN,\n  forall s,\n  proj1_sig s = (MIN, nil) ->\n  goal MIN (count s).\nProof.\n  intros ? ? heq. unfold count.\n  eapply loop_with_invariant_invariant_alt with (X := extra_invariant MIN);\n    unfold count_invariant, extra_invariant, count_body.\n  (* The extra invariant is preserved. *)\n  { intros [ n ns ] [ n' ns' ] [ ? ? ] [ ? ? ] ?.\n    destruct (eq_nat_dec n MAX); [ congruence | msg_injection ].\n    intros. subst n' ns'.\n    split.\n    { omega. }\n    { unfold goal in *. simpl. intros ? [ | ].\n      intros. subst n. assumption.\n      eauto. }\n  }\n  (* The extra invariant implies the goal. *)\n  { intros [ n ns ] ns' [ ? ? ] [ ? ? ] ?.\n    destruct (eq_nat_dec n MAX); [ msg_injection | congruence ].\n    assumption. }\n  (* The extra invariant holds initially. *)\n  { destruct s as [ [ n ns ] hs ]. simpl in *.\n    injection heq. clear heq. intros. subst.\n    split.\n      { eauto. }\n      { unfold goal. simpl. tauto. }\n  }\nQed.\n\n", "meta": {"author": "fpottier", "repo": "loop", "sha": "8cd74ba718e2cb761572a33f01e343f7b0563b73", "save_path": "github-repos/coq/fpottier-loop", "path": "github-repos/coq/fpottier-loop/loop-8cd74ba718e2cb761572a33f01e343f7b0563b73/LoopDemo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7025907631954932}}
{"text": "(* -------------------------------------------------------------------- *)\nRequire Import Arith List.\nFrom Autosubst Require Import Autosubst.\n(* These are already required by Autosubst. However, having them\n   available is useful to prove equality lemmas about the translation\n  to Coq formulas. *)\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(* -------------------------------------------------------------------- *)\nInductive expr : Type :=\n| Var (_ : var)\n| Zero\n| Succ (_ : expr)\n| Plus (_ : expr) (_ : expr)\n| Mult (_ : expr) (_ : expr).\n\nInductive formula : Type :=\n| Bottom\n(* Autosubst complains if this line is not present.\n   See https://github.com/uds-psl/autosubst/issues/4 *)\n| DummyVar (_ : var)\n| Implies (_ : formula) (_ : formula)\n| And (_ : formula) (_ : formula)\n| Or (_ : formula) (_ : formula)\n| Eq (_ : expr) (_ : expr)\n| Forall (_ : {bind expr in formula})\n| Exists (_ : {bind expr in formula}).\n\n\nInfix \"@+\" := Plus (at level 50, left associativity).\nInfix \"@*\" := Mult (at level 40, left associativity).\nNotation \"x @-> y\" := (Implies x y) (at level 99, right associativity, y at level 200).\nInfix \"@/\\\" := And (at level 80, right associativity).\nInfix \"@\\/\" := Or (at level 85, right associativity).\nInfix \"@=\" := Eq (at level 70).\nNotation Not := (fun P => P @-> Bottom).\nNotation \"@~ x\" := (Not x) (at level 75, right associativity).\n\n(* -------------------------------------------------------------------- *)\n(* Magic commands to bind Autosubst to our formulas and expressions. *)\nInstance Ids_expr : Ids expr. derive. Defined.\nInstance Rename_expr : Rename expr. derive. Defined.\nInstance Subst_expr : Subst expr. derive. Defined.\nInstance SubstLemmas_expr : SubstLemmas expr. derive. Qed.\nInstance HSubst_formula : HSubst expr formula. derive. Defined.\nInstance Ids_formula : Ids formula. derive. Defined.\nInstance Rename_formula : Rename formula. derive. Defined.\nInstance Subst_formula : Subst formula. derive. Defined.\nInstance HSubstLemmas_formula : HSubstLemmas expr formula. derive. Qed.\nInstance SubstHSubstComp_expr_formula : SubstHSubstComp expr formula. derive. Qed.\nInstance SubstLemmas_formula : SubstLemmas formula. derive. Qed.\n\n(* -------------------------------------------------------------------- *)\n(* Some useful lemmas that seem to be missing from Autosubst. *)\nLemma subst_cons :\n  forall A Gamma sigma, (A :: Gamma)..|[sigma] = A.|[sigma] :: Gamma..|[sigma].\nProof.\n  auto.\nQed.\n\nLemma subst_app :\n  forall Gamma Delta sigma, (Gamma ++ Delta)..|[sigma] = Gamma..|[sigma] ++ Delta..|[sigma].\nProof.\n  intros Gamma Delta sigma; induction Gamma.\n  - simpl; auto.\n  - simpl. f_equal. auto.\nQed.\n\n(* -------------------------------------------------------------------- *)\n(* Definition of the rules of natural deduction, given a way to know\n   whether a formula is an axiom. Note that this is a Type, in order to\n   allow computation on proofs. *)\nDefinition env := list formula.\nInductive nd (ax : formula -> Type) : env -> formula -> Type :=\n| Nd_axiom : forall A Gamma, ax A -> nd ax Gamma A\n| Nd_assume : forall A Gamma, nd ax (A :: Gamma) A\n| Nd_weak : forall A B Gamma, nd ax Gamma A -> nd ax (B :: Gamma) A\n| Nd_impI : forall A B Gamma, nd ax (A :: Gamma) B -> nd ax Gamma (Implies A B)\n| Nd_impE : forall A B Gamma, nd ax Gamma (Implies A B) -> nd ax Gamma A -> nd ax Gamma B\n| Nd_andI : forall A B Gamma, nd ax Gamma A -> nd ax Gamma B -> nd ax Gamma (And A B)\n| Nd_andEL : forall A B Gamma, nd ax Gamma (And A B) -> nd ax Gamma A\n| Nd_andER : forall A B Gamma, nd ax Gamma (And A B) -> nd ax Gamma B\n| Nd_orIL : forall A B Gamma, nd ax Gamma A -> nd ax Gamma (Or A B)\n| Nd_orIR : forall A B Gamma, nd ax Gamma B -> nd ax Gamma (Or A B)\n| Nd_orE : forall A B C Gamma, nd ax Gamma (Or A B) -> nd ax (A :: Gamma) C -> nd ax (B :: Gamma) C -> nd ax Gamma C\n| Nd_botE : forall A Gamma, nd ax Gamma Bottom -> nd ax Gamma A\n| Nd_forallI : forall A Gamma, nd ax Gamma..|[ren (+1)] A -> nd ax Gamma (Forall A)\n| Nd_forallE : forall A Gamma t, nd ax Gamma (Forall A) -> nd ax Gamma A.|[t/]\n| Nd_existI : forall A Gamma t, nd ax Gamma A.|[t/] -> nd ax Gamma (Exists A)\n| Nd_existE : forall A B Gamma, nd ax Gamma (Exists A) -> nd ax (A :: Gamma..|[ren (+1)]) B.|[ren (+1)] -> nd ax Gamma B\n| Nd_eq_refl : forall Gamma t, nd ax Gamma (t @= t)\n| Nd_eq_elim : forall Gamma A t1 t2, nd ax Gamma (t1 @= t2) -> nd ax Gamma A.|[t1/] -> nd ax Gamma A.|[t2/].\n\n(* -------------------------------------------------------------------- *)\n(* Some useful tactics to reason about natural deduction. *)\n\n(* Clear the [n] first hypotheses of the sequent. *)\nLtac nd_clear n :=\n  match n with\n  | 0 => idtac\n  | S ?n => apply Nd_weak; nd_clear n\n  end.\n\n(* Try to prove the sequent by applying any assumption. *)\nLtac nd_assumption_rec :=\n  solve [apply Nd_assume | apply Nd_weak; nd_assumption_rec].\nTactic Notation \"nd_assumption\" := nd_assumption_rec.\n\n(* Try to prove the sequent by applying the [n]th,\n   0-indexed, assumption. *)\nTactic Notation \"nd_assumption\" constr(n) := nd_clear n; apply Nd_assume.\n\n(* -------------------------------------------------------------------- *)\n(* Definition of the axioms of Heyting and Peano arithmetic. *)\n\nInductive PeanoAxioms : formula -> Type :=\n| Peano_0_ne_Sn : PeanoAxioms (Forall (@~ (Succ (Var 0) @= Zero)))\n| Peano_ne_0_Sn : PeanoAxioms (Forall (Exists ((@~ (Var 1 @= Zero)) @-> (Succ (Var 0) @= Var 1))))\n| Peano_S_inj : PeanoAxioms (Forall (Forall ((Succ (Var 1) @= Succ (Var 0)) @-> (Var 1 @= Var 0))))\n| Peano_plus_0 : PeanoAxioms (Forall (Zero @+ Var 0 @= Var 0))\n| Peano_plus_S : PeanoAxioms (Forall (Forall (Succ (Var 1) @+ Var 0 @= Succ (Var 1 @+ Var 0))))\n| Peano_mult_0 : PeanoAxioms (Forall (Zero @* Var 0 @= Zero))\n| Peano_mult_S : PeanoAxioms (Forall (Forall (Succ (Var 1) @* Var 0 @= Var 1 @* Var 0 @+ Var 0)))\n| Peano_rec : forall P, PeanoAxioms (P.|[Zero/] @-> ((Forall (Implies P P.|[Succ (Var 0) .: ren (+1)])) @-> (Forall P))).\n\nInductive ClassicalPeano : formula -> Type :=\n| PeanoAxiom : forall A, PeanoAxioms A -> ClassicalPeano A\n| DoubleNegation : forall A, ClassicalPeano (@~ @~ A @-> A).\n\nNotation Heyting := (nd PeanoAxioms).\nNotation Peano := (nd ClassicalPeano).\n\n(* -------------------------------------------------------------------- *)\n(* Definition of the translation of formulas into Coq [Type]s. This\n   allows to prove the theorems in a constructive setting. *)\n\nFixpoint tr_expr sigma e :=\n  match e with\n  | Var n => sigma n\n  | Zero => 0\n  | Succ e => S (tr_expr sigma e)\n  | e1 @+ e2 => (tr_expr sigma e1) + (tr_expr sigma e2)\n  | e1 @* e2 => (tr_expr sigma e1) * (tr_expr sigma e2)\n  end.\n\nFixpoint tr_formula sigma A : Type :=\n  match A with\n  | Bottom => False\n  | DummyVar _ => True\n  | A @-> B => (tr_formula sigma A) -> (tr_formula sigma B)\n  | A @/\\ B => (tr_formula sigma A) * (tr_formula sigma B)\n  | A @\\/ B => (tr_formula sigma A) + (tr_formula sigma B)\n  | e1 @= e2 => (tr_expr sigma e1) = (tr_expr sigma e2)\n  | Forall A => forall x, tr_formula (x .: sigma) A\n  | Exists A => {x : nat & tr_formula (x .: sigma) A}\n  end.\n\nDefinition tr_env sigma Gamma := fold_right prod True (map (tr_formula sigma) Gamma).\nHint Unfold tr_env.\n\nLemma tr_env_cons : forall sigma A Gamma,\n    tr_env sigma (A :: Gamma) = (tr_formula sigma A * tr_env sigma Gamma)%type.\nProof.\n  intros; unfold tr_env; auto.\nQed.\n\nLemma tr_expr_subst : forall e sigma xi,\n    tr_expr xi e.[sigma] = tr_expr (fun x => tr_expr xi (sigma x)) e.\nProof.\n  intros e; induction e; intros; simpl; auto.\nQed.\n\nLemma tr_expr_extensionality : forall e sigma1 sigma2,\n    (forall x, sigma1 x = sigma2 x) -> tr_expr sigma1 e = tr_expr sigma2 e.\nProof.\n  intros e; induction e; intros; simpl; auto.\nQed.\n\n(* Helpful tactic to prove equality of sigT types. *)\nLtac sigT_extensionality x :=\n  f_equal; [intros H1 H2; rewrite H2; reflexivity | extensionality x].\n\nLemma tr_formula_extensionality : forall A sigma1 sigma2,\n    (forall x, sigma1 x = sigma2 x) -> tr_formula sigma1 A = tr_formula sigma2 A.\nProof.\n  intros A; induction A; intros; simpl; try auto.\n  - rewrite (IHA1 sigma1 sigma2 H); rewrite (IHA2 sigma1 sigma2 H); auto.\n  - rewrite (IHA1 sigma1 sigma2 H); rewrite (IHA2 sigma1 sigma2 H); auto.\n  - rewrite (IHA1 sigma1 sigma2 H); rewrite (IHA2 sigma1 sigma2 H); auto.\n  - repeat (rewrite (tr_expr_extensionality _ sigma1 sigma2); auto).\n  - extensionality x. apply IHA. intros [|n]; autosubst.\n  - sigT_extensionality x. apply IHA. intros [|n]; autosubst.\nQed.\n\nLemma tr_env_extensionality : forall Gamma sigma1 sigma2,\n    (forall x, sigma1 x = sigma2 x) -> tr_env sigma1 Gamma = tr_env sigma2 Gamma.\nProof.\n  intros Gamma; induction Gamma.\n  - intros; simpl; auto.\n  - intros; do 2 (rewrite tr_env_cons); simpl.\n    erewrite tr_formula_extensionality; auto.\n    f_equal. apply IHGamma; auto.\nQed.\n\nLemma tr_formula_subst : forall A sigma xi,\n    tr_formula xi A.|[sigma] = tr_formula (fun x => tr_expr xi (sigma x)) A.\nProof.\n  intros A; induction A; intros; simpl; auto.\n  - rewrite IHA1; rewrite IHA2; auto.\n  - rewrite IHA1; rewrite IHA2; auto.\n  - rewrite IHA1; rewrite IHA2; auto.\n  - do 2 (rewrite tr_expr_subst); auto.\n  - extensionality x. rewrite IHA. apply tr_formula_extensionality.\n    intros [|n]; simpl; asimpl; auto.\n    rewrite tr_expr_subst. apply tr_expr_extensionality. intros; simpl; auto.\n  - sigT_extensionality x. rewrite IHA. apply tr_formula_extensionality.\n    intros [|n]; simpl; asimpl; auto.\n    rewrite tr_expr_subst. apply tr_expr_extensionality. intros; simpl; auto.\nQed.\n\nLemma tr_formula_subst1 : forall A sigma e,\n    tr_formula sigma A.|[e/] = tr_formula ((tr_expr sigma e) .: sigma) A.\nProof.\n  intros A sigma e; rewrite tr_formula_subst; apply tr_formula_extensionality.\n  intros [|n]; simpl; auto.\nQed.\n\nLemma tr_env_subst : forall Gamma sigma xi,\n    tr_env xi Gamma..|[sigma] = tr_env (fun x => tr_expr xi (sigma x)) Gamma.\nProof.\n  intros Gamma; induction Gamma.\n  - intros; unfold tr_env; simpl; auto.\n  - intros sigma xi; unfold tr_env; simpl; asimpl.\n    rewrite tr_formula_subst. f_equal.\n    unfold tr_env in IHGamma. rewrite <- IHGamma. auto.\nQed.\n\n(* A formula that can be proved in Heyting arithmetic can also be\n   proved in Coq *)\nTheorem reflect : forall Gamma A, Heyting Gamma A -> forall sigma, tr_env sigma Gamma -> tr_formula sigma A.\nProof.\n  intros Gamma A dn; elim dn.\n  - intros A0 Gamma0 H sigma Henv.\n    destruct H; simpl; try (intros; auto; congruence).\n    + intros [|n].\n      * exists 0; intros; exfalso; auto.\n      * exists n; auto.\n    + intros; apply plus_comm.\n    + intros H0 HI x; induction x as [|x IHx]; simpl in *.\n      * rewrite tr_formula_subst1 in H0. auto.\n      * specialize (HI x IHx). rewrite tr_formula_subst in HI.\n        erewrite tr_formula_extensionality; [apply HI|].\n        intros [|n]; simpl; auto.\n  - simpl. intros A0 Gamma0 sigma [H1 H2]; auto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 sigma [H3 H4]. auto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 sigma H3 H4.\n    apply H2. unfold tr_env; simpl. auto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 H3 H4 sigma H5.\n    apply H2; auto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 H3 H4 sigma H5. auto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 sigma H3. apply H2; auto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 sigma H3. apply H2; auto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 sigma H3. auto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 sigma H3. auto.\n  - simpl. intros A0 B0 C0 Gamma0 H1 H2 H3 H4 H5 H6 sigma H7.\n    destruct (H2 sigma H7); [apply H4 | apply H6]; unfold tr_env; simpl; auto.\n  - simpl. intros A0 Gamma0 H1 H2 sigma H3. exfalso; eapply H2; eauto.\n  - simpl. intros A0 Gamma0 H1 H2 sigma H3 x. apply H2.\n    rewrite tr_env_subst.\n    erewrite tr_env_extensionality; eauto.\n  - simpl. intros A0 Gamma0 t H1 H2 sigma H3.\n    rewrite tr_formula_subst1. apply H2; auto.\n  - simpl. intros A0 Gamma0 t H1 H2 sigma H3.\n    specialize (H2 sigma H3). rewrite tr_formula_subst1 in H2.\n    eauto.\n  - simpl. intros A0 B0 Gamma0 H1 H2 H3 H4 sigma H5.\n    destruct (H2 sigma H5) as [x H6].\n    specialize (H4 (x .: sigma)). rewrite tr_env_cons in H4.\n    rewrite tr_formula_subst in H4.\n    apply H4. rewrite tr_env_subst; auto.\n  - simpl. intros Gamma0 t sigma H. reflexivity.\n  - simpl. intros Gamma0 A0 t1 t2 H1 H2 H3 H4 sigma H5.\n    specialize (H2 sigma H5).\n    specialize (H4 sigma H5).\n    rewrite tr_formula_subst1 in *. congruence.\nDefined.\n\n(* As a trivial corollary, Heyting arithmetic is consistent. *)\nCorollary Heyting_consistent : Heyting nil Bottom -> False.\nProof.\n  intros H. apply reflect with (sigma := fun _ => 0) in H; auto.\n  unfold tr_env; simpl; auto.\nDefined.\n\n(* -------------------------------------------------------------------- *)\n(* Definition of the combined double-negation and Friedman translation\n   of Peano arithmetic to Friedman arithmetic. *)\nDefinition dnegA A B := (B @-> A) @-> A.\n\nFixpoint friedman A B :=\n  match B with\n  | Bottom | DummyVar _ | _ @= _ => B @\\/ A\n  | B @/\\ C => (dnegA A (friedman A B)) @/\\ (dnegA A (friedman A C))\n  | B @\\/ C => (dnegA A (friedman A B)) @\\/ (dnegA A (friedman A C))\n  | B @-> C => (dnegA A (friedman A B)) @-> (dnegA A (friedman A C))\n  | Forall B => (Forall (dnegA A.|[ren (+1)] (friedman (A.|[ren (+1)]) B)))\n  | Exists B => (dnegA A (Exists (friedman (A.|[ren (+1)]) B)))\n  end.\n\nLemma nd_cut : forall ax Gamma A B, nd ax Gamma A -> nd ax (A :: Gamma) B -> nd ax Gamma B.\nProof.\n  intros ax Gamma A B H0 H1.\n  apply Nd_impE with (A := A).\n  - apply Nd_impI; auto.\n  - auto.\nDefined.\n\nLemma nd_weak_r : forall ax Gamma A, nd ax Gamma A -> forall Delta Pi B, Gamma = Delta ++ Pi -> nd ax (Delta ++ (B :: Pi)) A.\nProof.\n  intros ax Gamma A dn; elim dn.\n  - intros; apply Nd_axiom; auto.\n  - intros A0 Gamma0 [|A1 Delta] Pi B H.\n    + simpl in *. apply Nd_weak. rewrite <- H. apply Nd_assume.\n    + simpl in *. replace A1 with A0 by congruence. apply Nd_assume.\n  - intros A0 B Gamma0 H1 H2 [|B1 Delta] Pi B0 H3.\n    + simpl in *. rewrite <- H3. apply Nd_weak. apply Nd_weak. auto.\n    + simpl in *. apply Nd_weak. apply H2. congruence.\n  - intros A0 B Gamma0 H1 H2 Delta Pi B0 H3. apply Nd_impI.\n    apply H2 with (Delta := A0 :: Delta). simpl; congruence.\n  - intros A0 B Gamma0 H1 H2 H3 H4 Delta Pi B0 H5. apply Nd_impE with (A := A0).\n    + apply H2; auto.\n    + apply H4; auto.\n  - intros A0 B Gamma0 H1 H2 H3 H4 Delta Pi B0 H5. apply Nd_andI.\n    + apply H2; auto.\n    + apply H4; auto.\n  - intros A0 B Gamma0 H1 H2 Delta Pi B0 H3. eapply Nd_andEL. apply H2; auto.\n  - intros A0 B Gamma0 H1 H2 Delta Pi B0 H3. eapply Nd_andER. apply H2; auto.\n  - intros A0 B Gamma0 H1 H2 Delta Pi B0 H3. eapply Nd_orIL. apply H2; auto.\n  - intros A0 B Gamma0 H1 H2 Delta Pi B0 H3. eapply Nd_orIR. apply H2; auto.\n  - intros A0 B0 C Gamma0 H1 H2 H3 H4 H5 H6 Delta Pi B1 H7. eapply Nd_orE.\n    + apply H2; auto.\n    + apply H4 with (Delta := A0 :: Delta). simpl; congruence.\n    + apply H6 with (Delta := B0 :: Delta). simpl; congruence.\n  - intros A0 Gamma0 H1 H2 Delta Pi B H3. apply Nd_botE. auto.\n  - intros A0 Gamma0 H1 H2 Delta Pi B H3. apply Nd_forallI.\n    rewrite H3 in *. rewrite subst_app in *. rewrite subst_cons.\n    apply H2; auto.\n  - intros A0 Gamma0 t H1 H2 Delta Pi B H3. apply Nd_forallE. apply H2; auto.\n  - intros A0 Gamma0 t H1 H2 Delta Pi B H3. apply Nd_existI with (t := t).\n    apply H2; auto.\n  - intros A0 B Gamma0 H1 H2 H3 H4 Delta Pi B0 H5. eapply Nd_existE.\n    + apply H2; auto.\n    + rewrite H5 in *. rewrite subst_app in *. rewrite subst_cons.\n      apply H4 with (Delta0 := (A0 :: Delta..|[ren (+1)])); auto.\n  - intros Gamma0 t Delta Pi B H. apply Nd_eq_refl.\n  - intros Gamma0 A0 t1 t2 H1 H2 H3 H4 Delta Pi B H5.\n    eapply Nd_eq_elim; [apply H2 | apply H4]; auto.\nDefined.\n\nLemma nd_weak : forall ax Gamma Delta A B, nd ax (Gamma ++ Delta) A -> nd ax (Gamma ++ (B :: Delta)) A.\nProof.\n  intros ax Gamma Delta A B H.\n  apply nd_weak_r with (Gamma := Gamma ++ Delta) (Delta := Gamma) (Pi := Delta); auto.\nDefined.\n\n(* Helpful tactics to handle natural deduction sequents. *)\n\nLtac nd_weak n :=\n  match n with\n  | 0 => apply Nd_weak\n  | 1 => apply (nd_weak _ (_ :: nil)); simpl\n  | 2 => apply (nd_weak _ (_ :: _ :: nil)); simpl\n  | 3 => apply (nd_weak _ (_ :: _ :: _ :: nil)); simpl\n  | 4 => apply (nd_weak _ (_ :: _ :: _ :: _ :: nil)); simpl\n  | 5 => apply (nd_weak _ (_ :: _ :: _ :: _ :: _ :: nil)); simpl\n  | 6 => apply (nd_weak _ (_ :: _ :: _ :: _ :: _ :: _ :: nil)); simpl\n  end.\n\nLtac nd_apply n :=\n  eapply Nd_impE; [nd_assumption n|].\n\nLtac nd_intro := apply Nd_impI.\n\nLtac nd_destruct_or n :=\n  eapply Nd_orE; [nd_assumption n|nd_weak (S n)|nd_weak (S n)].\nLtac nd_left := apply Nd_orIL.\nLtac nd_right := apply Nd_orIR.\n\nLtac nd_assert H :=\n  apply Nd_impE with (A := H); [nd_intro|].\n\nLtac nd_destruct_and n :=\n  eapply Nd_impE;\n  [\n    nd_intro; eapply Nd_impE;\n    [nd_intro; nd_weak (S (S n))\n    |eapply Nd_andEL; nd_assumption (S n)\n    ]\n   |eapply Nd_andER; nd_assumption n\n  ].\nLtac nd_split := apply Nd_andI.\n\nLtac nd_exfalso := apply Nd_botE.\n\nLtac nd_unapply n := eapply Nd_impE; [|nd_assumption n].\nLtac nd_revert n := nd_unapply n; nd_weak n.\n\n(* Some lemmas concerning double-negation translation *)\n\nLemma double_neg_simpl :\n  forall ax Gamma A B, nd ax Gamma A -> nd ax Gamma (dnegA B A).\nProof.\n  intros ax Gamma A B H.\n  nd_intro. nd_apply 0. nd_weak 0; auto.\nDefined.\n\nLemma double_neg_imp :\n  forall ax Gamma A B C, nd ax (B :: Gamma) C -> nd ax (dnegA A B :: Gamma) (dnegA A C).\nProof.\n  intros ax Gamma A B C H.\n  nd_intro. nd_apply 1. nd_intro. nd_apply 1.\n  nd_weak 1; nd_weak 1; auto.\nDefined.\n\nLemma or_imp :\n  forall Gamma A B C, Heyting (B :: Gamma) C -> Heyting ((A @\\/ B) :: Gamma) (A @\\/ C).\nProof.\n  intros Gamma A B C H.\n  nd_destruct_or 0.\n  - nd_left; nd_assumption.\n  - nd_right; auto.\nDefined.\n\nLemma or_double_neg :\n  forall ax Gamma A B, nd ax Gamma (A @\\/ B) -> nd ax Gamma (dnegA A B).\nProof.\n  intros ax Gamma A B H.\n  nd_intro.\n  eapply Nd_orE; [nd_weak 0; eauto| |].\n  - nd_assumption.\n  - nd_apply 1; nd_assumption.\nDefined.\n\nLemma double_neg_or :\n  forall ax Gamma A B, nd ax Gamma (dnegA A B) -> nd ax Gamma (dnegA A (B @\\/ A)).\nProof.\n  intros ax Gamma A B H.\n  nd_intro. eapply Nd_impE; [nd_weak 0; apply H|].\n  nd_intro. nd_apply 1. nd_left; nd_assumption.\nDefined.\n\nLemma or_double_neg_rev :\n  forall ax Gamma A B, nd ax Gamma (B @\\/ A) -> nd ax Gamma (dnegA A B).\nProof.\n  intros ax Gamma A B H.\n  nd_intro.\n  eapply Nd_orE; [nd_weak 0; eauto| |].\n  - nd_apply 1; nd_assumption.\n  - nd_assumption.\nDefined.\n\nLemma double_neg_4 : forall ax Gamma A B, nd ax Gamma (dnegA B (dnegA B A)) -> nd ax Gamma (dnegA B A).\nProof.\n  intros ax Gamma A B H.\n  nd_intro.\n  eapply Nd_impE; [nd_weak 0; eauto|].\n  nd_intro; nd_apply 0; nd_assumption.\nDefined.\n\nLemma double_neg_weak :\n  forall ax Gamma A B C, nd ax (B :: Gamma) (dnegA A C) -> nd ax (dnegA A B :: Gamma) (dnegA A C).\nProof.\n  intros ax Gamma A B C H.\n  apply double_neg_4. apply double_neg_imp; auto.\nDefined.\n\nLemma double_neg_weakH :\n  forall ax Gamma A B C, nd ax (B :: Gamma) (dnegA A C) -> nd ax Gamma (dnegA A B) -> nd ax Gamma (dnegA A C).\nProof.\n  intros ax Gamma A B C H1 H2.\n  eapply Nd_impE; [|apply H2].\n  nd_intro; apply double_neg_weak; auto.\nDefined.\n\n(* Compatibility between Friedman translation and substitution *)\n\nLemma friedman_subst :\n  forall B A sigma, (friedman A B).|[sigma] = friedman A.|[sigma] B.|[sigma].\nProof.\n  intros B. induction B; intros; simpl; auto.\n  - rewrite IHB1; rewrite IHB2; auto.\n  - rewrite IHB1; rewrite IHB2; auto.\n  - rewrite IHB1; rewrite IHB2; auto.\n  - rewrite IHB. asimpl. auto.\n  - rewrite IHB. asimpl. auto.\nDefined.\n\nLemma friedman_subst_map :\n  forall Gamma A sigma, (map (friedman A) Gamma)..|[sigma] = map (friedman A.|[sigma]) Gamma..|[sigma].\nProof.\n  intros. induction Gamma.\n  - simpl; auto.\n  - rewrite subst_cons. unfold map in *. rewrite subst_cons.\n    rewrite IHGamma. rewrite friedman_subst. auto.\nDefined.\n\nLemma double_neg_bottom :\n  forall Gamma A, Heyting Gamma (dnegA A (Bottom @\\/ A)) -> Heyting Gamma A.\nProof.\n  intros Gamma A H.\n  eapply Nd_impE; [apply H|].\n  nd_intro. nd_destruct_or 0.\n  - nd_exfalso; nd_assumption.\n  - nd_assumption.\nDefined.\n\nFixpoint QF P : Type :=\n  match P with\n  | Bottom | _ @= _ => True\n  | (A @-> B) | A @\\/ B | A @/\\ B => QF A * QF B\n  | Forall _ | Exists _ | DummyVar _ => False\n  end.\n\nDefinition equiv (A B : Type) : Type := (A -> B) * (B -> A).\n\nLemma equiv_refl :\n  forall A, equiv A A.\nProof.\n  split; auto.\nDefined.\n\nLemma nd_eq_sym : forall ax Gamma t1 t2, nd ax Gamma (t1 @= t2) -> nd ax Gamma (t2 @= t1).\nProof.\n  intros ax Gamma t1 t2 H.\n  apply Nd_eq_elim with (A := Var 0 @= t1.[ren (+1)]) in H; asimpl in *; auto.\n  apply Nd_eq_refl.\nDefined.\n\n(* Instantiations of Peano axioms *)\n\nLemma Peano_0_ne_Sn_i : forall Gamma t,\n    Heyting Gamma (@~ (Succ t @= Zero)).\nProof.\n  intros Gamma t.\n  evar (Delta : env).\n  set (H := Nd_axiom PeanoAxioms _ ?Delta Peano_0_ne_Sn).\n  apply Nd_forallE with (t := t) in H.\n  asimpl in H.\n  apply H.\nDefined.\n\nLemma Peano_ne_0_Sn_i : forall Gamma t,\n    Heyting Gamma (Exists ((@~ (t.[ren (+1)] @= Zero)) @-> (Succ (Var 0) @= t.[ren (+1)]))).\nProof.\n  intros Gamma t.\n  evar (Delta : env).\n  set (H := Nd_axiom PeanoAxioms _ ?Delta Peano_ne_0_Sn).\n  apply Nd_forallE with (t := t) in H.\n  asimpl in H. apply H.\nDefined.\n\nLemma Peano_S_inj_i : forall Gamma t1 t2,\n    Heyting ((Succ t1 @= Succ t2) :: Gamma) (t1 @= t2).\nProof.\n  intros Gamma t1 t2.\n  evar (Delta : env).\n  set (H := Nd_axiom PeanoAxioms _ ?Delta Peano_S_inj).\n  apply Nd_forallE with (t := t1) in H.\n  apply Nd_forallE with (t := t2) in H.\n  asimpl in H.\n  eapply Nd_impE; [apply H|apply Nd_assume].\nDefined.\n\nLemma Peano_plus_0_i : forall Gamma t,\n    Heyting Gamma ((Zero @+ t) @= t).\nProof.\n  intros Gamma t.\n  evar (Delta : env).\n  set (H := Nd_axiom PeanoAxioms _ ?Delta Peano_plus_0).\n  apply Nd_forallE with (t := t) in H.\n  asimpl in H.\n  apply H.\nDefined.\n\nLemma Peano_plus_S_i : forall Gamma t1 t2,\n    Heyting Gamma ((Succ t1 @+ t2) @= Succ (t1 @+ t2)).\nProof.\n  intros Gamma t1 t2.\n  evar (Delta : env).\n  set (H := Nd_axiom PeanoAxioms _ ?Delta Peano_plus_S).\n  apply Nd_forallE with (t := t1) in H.\n  apply Nd_forallE with (t := t2) in H.\n  asimpl in H.\n  apply H.\nDefined.\n\nLemma Peano_mult_0_i : forall Gamma t,\n    Heyting Gamma ((Zero @* t) @= Zero).\nProof.\n  intros Gamma t.\n  evar (Delta : env).\n  set (H := Nd_axiom PeanoAxioms _ ?Delta Peano_mult_0).\n  apply Nd_forallE with (t := t) in H.\n  asimpl in H.\n  apply H.\nDefined.\n\nLemma Peano_mult_S_i : forall Gamma t1 t2,\n    Heyting Gamma ((Succ t1 @* t2) @= t1 @* t2 @+ t2).\nProof.\n  intros Gamma t1 t2.\n  evar (Delta : env).\n  set (H := Nd_axiom PeanoAxioms _ ?Delta Peano_mult_S).\n  apply Nd_forallE with (t := t1) in H.\n  apply Nd_forallE with (t := t2) in H.\n  asimpl in H.\n  apply H.\nDefined.\n\nLtac HA_rec :=\n  eapply Nd_impE; [\n    eapply Nd_impE; [\n      apply Nd_axiom; apply Peano_rec\n     |asimpl]\n   |asimpl; apply Nd_forallI; asimpl; nd_intro].\n\n(* Equality is decidable in Heyting arithmetic *)\n\nLemma eq_decidable_forall : forall Gamma,\n    Heyting Gamma (Forall (Forall ((Var 1 @= Var 0) @\\/ @~ (Var 1 @= Var 0)))).\nProof.\n  intros Gamma.\n  HA_rec.\n  - HA_rec.\n    + nd_left; apply Nd_eq_refl.\n    + nd_weak 0; nd_right.\n      nd_intro.\n      eapply Nd_impE; [|apply nd_eq_sym; nd_assumption].\n      apply Peano_0_ne_Sn_i.\n  - HA_rec.\n    + nd_right.\n      apply Peano_0_ne_Sn_i.\n    + nd_weak 0.\n      eapply Nd_impE; [|apply Nd_forallE with (t := Var 0); apply Nd_assume].\n      asimpl. nd_intro.\n      nd_destruct_or 0.\n      * nd_left.\n        evar (Delta : env).\n        set (H := (Nd_eq_elim PeanoAxioms ?Delta (Succ (Var 2) @= Succ (Var 0)) (Var 1) (Var 0))).\n        asimpl in H. apply H; [nd_assumption|apply Nd_eq_refl].\n      * nd_right; nd_intro; nd_apply 1.\n        apply Peano_S_inj_i.\nDefined.\n\nLemma eq_decidable : forall Gamma e1 e2,\n    Heyting Gamma ((e1 @= e2) @\\/ @~ (e1 @= e2)).\nProof.\n  intros Gamma e1 e2.\n  set (H := eq_decidable_forall Gamma).\n  apply Nd_forallE with (t := e1) in H.\n  apply Nd_forallE with (t := e2) in H.\n  asimpl in H; auto.\nDefined.\n\n(* Quantifier-free formulas are decidable *)\n\nLemma qf_decidable : forall Gamma A, QF A -> Heyting Gamma (A @\\/ (@~ A)).\nProof.\n  intros Gamma A. induction A; intros H; simpl in H; try (exfalso; assumption).\n  - nd_right; nd_intro; nd_assumption.\n  - destruct H as [H1 H2].\n    eapply Nd_orE; [apply IHA2; auto| |].\n    + apply Nd_orIL; nd_intro; nd_assumption.\n    + eapply Nd_orE; [nd_weak 0; apply IHA1; auto| |].\n      * nd_right; nd_intro.\n        nd_apply 2. nd_apply 0. nd_assumption.\n      * nd_left; nd_intro; nd_exfalso.\n        nd_apply 1; nd_assumption.\n  - destruct H as [H1 H2].\n    eapply Nd_orE; [apply IHA1; auto| |].\n    + eapply Nd_orE; [nd_weak 0; apply IHA2; auto| |].\n      * nd_left; nd_split; nd_assumption.\n      * nd_right; nd_intro.\n        nd_destruct_and 0; nd_apply 2; nd_assumption.\n    + nd_right; nd_intro.\n      nd_apply 1; nd_destruct_and 0; nd_assumption.\n  - destruct H as [H1 H2].\n    eapply Nd_orE; [apply IHA1; auto| |].\n    + nd_left; nd_left; nd_assumption.\n    + eapply Nd_orE; [apply Nd_weak; apply IHA2; auto| |].\n      * nd_left; nd_right; nd_assumption.\n      * nd_right; nd_intro; nd_destruct_or 0; [nd_apply 2 | nd_apply 1]; nd_assumption.\n  - apply eq_decidable.\nDefined.\n\n(* The Friedman translation of a formula that can be proved in Peano arithmetic\n   can be proved in Heyting arithmetic *)\n\nLemma friedman_Peano_Heyting :\n  forall Gamma A, Peano Gamma A -> forall P, Heyting (map (friedman P) Gamma) (dnegA P (friedman P A)).\nProof.\n  intros Gamma A dn; elim dn; clear Gamma A dn.\n  - intros A Gamma H P. destruct H as [A HA | A].\n    (* Axioms *)\n    + apply double_neg_simpl.\n      destruct HA; simpl.\n      * apply Nd_forallI. apply double_neg_simpl.\n        nd_intro; apply double_neg_imp.\n        nd_destruct_or 0; [|nd_right; nd_assumption].\n        nd_left; nd_revert 0.\n        apply Peano_0_ne_Sn_i.\n      * apply Nd_forallI. apply double_neg_simpl; apply double_neg_simpl.\n        eapply Nd_impE; [|apply Nd_forallE with (t := Var 0); apply Nd_axiom; apply Peano_ne_0_Sn].\n        asimpl. nd_intro.\n        eapply Nd_existE; [nd_assumption|].\n        rewrite subst_cons; nd_weak 1. asimpl.\n        apply Nd_existI with (t := Var 0). asimpl.\n        nd_intro. apply double_neg_weak. apply double_neg_or.\n        apply Nd_impE with (A := dnegA P.|[ren (+2)] (Var 1 @= Zero @-> Bottom)).\n        -- nd_intro. apply double_neg_imp. nd_apply 2. nd_assumption.\n        -- nd_weak 1. nd_intro. eapply Nd_impE; [nd_apply 1|].\n           ++ nd_weak 1. nd_intro.\n              eapply Nd_impE; [|apply eq_decidable].\n              nd_intro; nd_destruct_or 0.\n              ** nd_apply 1; nd_left; nd_assumption.\n              ** nd_apply 2; nd_assumption.\n           ++ nd_intro. nd_destruct_or 0; [nd_exfalso|]; nd_assumption.\n      * apply Nd_forallI. apply double_neg_simpl.\n        apply Nd_forallI. apply double_neg_simpl.\n        nd_intro. apply double_neg_imp.\n        nd_destruct_or 0; [|nd_right; nd_assumption].\n        nd_left. apply Peano_S_inj_i.\n      * apply Nd_forallI. apply double_neg_simpl.\n        nd_left. apply Peano_plus_0_i.\n      * apply Nd_forallI. apply double_neg_simpl.\n        apply Nd_forallI. apply double_neg_simpl.\n        nd_left. apply Peano_plus_S_i.\n      * apply Nd_forallI. apply double_neg_simpl.\n        nd_left. apply Peano_mult_0_i.\n      * apply Nd_forallI. apply double_neg_simpl.\n        apply Nd_forallI. apply double_neg_simpl.\n        nd_left. apply Peano_mult_S_i.\n      * eapply Nd_impE; [|apply Nd_axiom; apply Peano_rec with\n          (P := dnegA P.|[ren (+1)] (friedman P.|[ren (+1)] P0))].\n        nd_intro. nd_intro. apply double_neg_simpl.\n        nd_intro. apply double_neg_imp.\n        eapply Nd_impE; [nd_apply 2|]; asimpl.\n        -- rewrite friedman_subst. asimpl. nd_assumption.\n        -- nd_weak 1. nd_weak 1. apply Nd_forallI.\n           eapply Nd_impE; [|apply Nd_forallE with (t := Var 0); nd_assumption].\n           rewrite subst_cons. nd_weak 0. asimpl.\n           nd_intro. nd_intro. rewrite friedman_subst.\n           eapply Nd_impE; [|nd_assumption 1]; nd_intro.\n           apply double_neg_weak.\n           asimpl. nd_apply 0. nd_assumption.\n    + simpl. remember (friedman P A) as C.\n      apply double_neg_simpl.\n      nd_intro. apply double_neg_weak.\n      nd_intro. apply double_neg_bottom.\n      nd_apply 1. apply double_neg_simpl.\n      nd_intro. apply double_neg_weak.\n      nd_intro; nd_apply 2; nd_assumption.\n  - intros A Gamma P; simpl; apply double_neg_simpl; nd_assumption.\n  - intros A B Gamma H1 H2 P; simpl; nd_weak 0; apply H2.\n  - intros A B Gamma H1 H2 P; simpl in *; apply double_neg_simpl.\n    nd_intro. apply double_neg_weak; auto.\n  - intros A B Gamma H1 H2 H3 H4 P. simpl in *.\n    nd_intro. eapply Nd_impE; [nd_weak 0; apply H2|].\n    nd_intro. nd_revert 1. nd_apply 0. nd_weak 0; apply H4.\n  - intros A B Gamma H1 H2 H3 H4 P. simpl in *.\n    apply double_neg_simpl. nd_split; auto.\n  - intros A B Gamma H1 H2 P. simpl in *.\n    eapply double_neg_weakH; [|apply H2].\n    nd_destruct_and 0; nd_assumption.\n  - intros A B Gamma H1 H2 P. simpl in *.\n    eapply double_neg_weakH; [|apply H2].\n    nd_destruct_and 0; nd_assumption.\n  - intros A B Gamma H1 H2 P. simpl in *.\n    apply double_neg_simpl; nd_left; auto.\n  - intros A B Gamma H1 H2 P. simpl in *.\n    apply double_neg_simpl; nd_right; auto.\n  - intros A B C Gamma H1 H2 H3 H4 H5 H6 P. simpl in *.\n    eapply double_neg_weakH; [|apply H2].\n    nd_destruct_or 0; apply double_neg_weak; [apply H4 | apply H6].\n  - intros A Gamma H1 H2 P; simpl in *.\n    nd_intro. nd_weak 0.\n    eapply Nd_impE; [apply H2|].\n    nd_intro. nd_destruct_or 0; [nd_exfalso|]; nd_assumption.\n  - intros A Gamma H1 H2 P; simpl in *.\n    apply double_neg_simpl.\n    specialize (H2 P.|[ren (+1)]).\n    apply Nd_forallI. rewrite friedman_subst_map. auto.\n  - intros A Gamma t H1 H2 P; simpl in *.\n    specialize (H2 P).\n    eapply double_neg_weakH; [|apply H2].\n    replace (dnegA P (friedman P A.|[t/]))\n      with (dnegA P.|[ren (+1)] (friedman P.|[ren (+1)] A)).|[t/]\n      by (asimpl; rewrite friedman_subst; autosubst).\n    apply Nd_forallE; nd_assumption.\n  - intros A Gamma t H1 H2 P; simpl in *.\n    apply double_neg_simpl.\n    specialize (H2 P).\n    nd_intro. eapply Nd_impE; [nd_weak 0; apply H2|].\n    nd_intro. nd_apply 1.\n    eapply Nd_existI. asimpl; rewrite friedman_subst; asimpl; nd_assumption.\n  - intros A B Gamma H1 H2 H3 H4 P; simpl in *.\n    specialize (H4 P.|[ren (+1)]); specialize (H2 P).\n    apply double_neg_4 in H2.\n    eapply double_neg_weakH; [|apply H2].\n    eapply Nd_existE; [nd_assumption|].\n    rewrite subst_cons.\n    nd_weak 1.\n    rewrite friedman_subst_map; simpl. rewrite friedman_subst. auto.\n  - intros Gamma t P; simpl in *.\n    apply double_neg_simpl. nd_left. apply Nd_eq_refl.\n  - intros Gamma A t1 t2 H1 H2 H3 H4 P.\n    nd_assert (dnegA P ((t1 @= t2) @\\/ P)); [|apply H2].\n    apply double_neg_weak. nd_destruct_or 0.\n    + replace (dnegA P (friedman P A.|[t2/]))\n        with (dnegA P.|[ren (+1)] (friedman P.|[ren (+1)] A)).|[t2/]\n        by (asimpl; rewrite friedman_subst; autosubst).\n      eapply Nd_eq_elim; [nd_assumption|].\n      asimpl; rewrite friedman_subst; asimpl. nd_weak 0; apply H4.\n    + nd_intro; nd_assumption.\nDefined.\n\n(* For a quantifier-free formula, friedman A P and P \\/ A are equivalent\n   in Heyting arithmetic *)\n\nLemma friedman_or_equiv :\n  forall P Gamma A, QF P -> (Heyting Gamma ((friedman A P) @-> (P @\\/ A)) *\n                 Heyting Gamma ((P @\\/ A) @-> (friedman A P))).\nProof.\n  intros P. induction P.\n  - intros Gamma A H. simpl in *.\n    split; nd_intro; nd_assumption.\n  - intros Gamma A H. simpl in *.\n    split; nd_intro; nd_assumption.\n  - intros Gamma A [HQF1 HQF2]. simpl in *.\n    split.\n    + nd_intro.\n      eapply Nd_impE; [|apply (qf_decidable _ P1 HQF1)]; nd_intro.\n      nd_destruct_or 0.\n      * eapply Nd_impE; [|apply (qf_decidable _ P2 HQF2)]; nd_intro.\n        nd_destruct_or 0.\n        -- nd_left; nd_intro; nd_assumption.\n        -- nd_right.\n           apply Nd_impE with (A := friedman A P2 @-> A).\n           ++ nd_apply 2. apply double_neg_simpl.\n              eapply Nd_impE; [apply IHP1; auto|].\n              nd_left. nd_assumption.\n           ++ nd_intro.\n              eapply Nd_orE; [|nd_exfalso; nd_apply 2; nd_assumption|nd_assumption].\n              nd_revert 0; apply IHP2; auto.\n      * nd_left; nd_intro; nd_exfalso.\n        nd_apply 1; nd_assumption.\n    + nd_intro; nd_intro; nd_intro.\n      nd_destruct_or 2; [|nd_assumption].\n      nd_assert (P1 @-> A).\n      * nd_apply 3. nd_intro.\n        eapply Nd_orE; [eapply Nd_impE; [apply IHP1; auto|nd_assumption]| |nd_assumption].\n        nd_apply 2; nd_assumption.\n      * nd_intro. nd_apply 2.\n        eapply Nd_impE; [apply IHP2; auto|].\n        nd_left; nd_apply 1; nd_assumption.\n  - intros Gamma A [HQF1 HQF2]. simpl in *.\n    split.\n    + nd_intro.\n      eapply Nd_impE; [|apply (qf_decidable _ P1 HQF1)]; nd_intro.\n      nd_destruct_or 0.\n      * eapply Nd_impE; [|apply (qf_decidable _ P2 HQF2)]; nd_intro.\n        nd_destruct_or 0.\n        -- nd_left. nd_split; nd_assumption.\n        -- nd_right. nd_destruct_and 2.\n           nd_apply 1; nd_intro.\n           nd_assert (P2 @\\/ A); [|nd_revert 0; apply IHP2; auto].\n           nd_destruct_or 0; [nd_exfalso; nd_apply 4|]; nd_assumption.\n      * nd_right. nd_destruct_and 1.\n        nd_apply 0; nd_intro.\n        nd_assert (P1 @\\/ A); [|nd_revert 0; apply IHP1; auto].\n        nd_destruct_or 0; [nd_exfalso; nd_apply 4|]; nd_assumption.\n    + nd_intro.\n      nd_destruct_or 0.\n      * nd_destruct_and 0. nd_split; apply double_neg_simpl.\n        -- eapply Nd_impE; [apply IHP1; auto|]. nd_left; nd_assumption.\n        -- eapply Nd_impE; [apply IHP2; auto|]. nd_left; nd_assumption.\n      * nd_split; nd_intro; nd_assumption.\n  - intros Gamma A [HQF1 HQF2]. simpl in *.\n    split.\n    + nd_intro.\n      eapply Nd_impE; [|apply (qf_decidable _ P1 HQF1)]; nd_intro.\n      nd_destruct_or 0.\n      * nd_left; nd_left; nd_assumption.\n      * eapply Nd_impE; [|apply (qf_decidable _ P2 HQF2)]; nd_intro.\n        nd_destruct_or 0.\n        -- nd_left; nd_right; nd_assumption.\n        -- nd_right. nd_destruct_or 2; nd_apply 0; nd_intro.\n           ++ nd_assert (P1 @\\/ A); [|nd_revert 0; apply IHP1; auto].\n              nd_destruct_or 0; [nd_exfalso; nd_apply 4|]; nd_assumption.\n           ++ nd_assert (P2 @\\/ A); [|nd_revert 0; apply IHP2; auto].\n              nd_destruct_or 0; [nd_exfalso; nd_apply 3|]; nd_assumption.\n    + nd_intro. nd_destruct_or 0.\n      * nd_destruct_or 0; [nd_left | nd_right]; apply double_neg_simpl.\n        -- eapply Nd_impE; [apply IHP1; auto|]. nd_left; nd_assumption.\n        -- eapply Nd_impE; [apply IHP2; auto|]. nd_left; nd_assumption.\n      * nd_left; nd_intro; nd_assumption.\n  - intros Gamma A H. simpl in *.\n    split; nd_intro; nd_assumption.\n  - intros; simpl in *; exfalso; auto.\n  - intros; simpl in *; exfalso; auto.\nDefined.\n\nLemma friedman_or_equiv_l :\n  forall P Gamma A, QF P -> Heyting Gamma ((friedman A P) @-> (P @\\/ A)).\nProof.\n  intros. apply friedman_or_equiv; auto.\nDefined.\n\nLemma friedman_or_equiv_r :\n  forall P Gamma A, QF P -> Heyting Gamma ((P @\\/ A) @-> (friedman A P)).\nProof.\n  intros. apply friedman_or_equiv; auto.\nDefined.\n\n\nLemma tr_friedman_equiv :\n  forall P A sigma, QF P ->\n    equiv (tr_formula sigma (friedman A P)) (tr_formula sigma (P @\\/ A)).\nProof.\n  intros P A sigma H.\n  destruct (friedman_or_equiv P nil A) as [E1 E2]; auto.\n  split.\n  - apply reflect with (sigma := sigma) in E1; simpl in *; auto.\n    unfold tr_env; simpl; auto.\n  - apply reflect with (sigma := sigma) in E2; simpl in *; auto.\n    unfold tr_env; simpl; auto.\nDefined.\n\n(* Definition of Sigma_0 and Pi_0 formulas *)\n\nInductive Sigma_0 : nat -> formula -> Type :=\n| QF_Sigma : forall n A, QF A -> Sigma_0 n A\n| Exists_Sigma : forall n A, Sigma_0 (S n) A -> Sigma_0 (S n) (Exists A)\n| Pi_Sigma : forall n A, Pi_0 n A -> Sigma_0 (S n) A\n\nwith Pi_0 : nat -> formula -> Type :=\n| QF_Pi : forall n A, QF A -> Pi_0 n A\n| Sigma_Pi : forall n A, Sigma_0 n A -> Pi_0 (S n) A\n| Forall_Pi : forall n A, Pi_0 (S n) A -> Pi_0 (S n) (Forall A).\n\nFixpoint leading_exists A :=\n  match A with\n  | Exists A => S (leading_exists A)\n  | _ => 0\n  end.\n\nFixpoint after_exists A :=\n  match A with\n  | Exists A => after_exists A\n  | _ => A\n  end.\n\nFixpoint add_n_exists n A :=\n  match n with\n  | 0 => A\n  | S n => Exists (add_n_exists n A)\n  end.\n\nTheorem add_n_exists_inverse :\n  forall A, add_n_exists (leading_exists A) (after_exists A) = A.\nProof.\n  intros A. induction A; simpl; congruence.\nDefined.\n\nLemma double_neg_exists :\n  forall Gamma P A, Heyting (A :: Gamma..|[ren (+1)]) P.|[ren (+1)] -> Heyting ((dnegA P (Exists A)) :: Gamma) P.\nProof.\n  intros Gamma P A H.\n  nd_apply 0. nd_intro. eapply Nd_existE; [nd_assumption|].\n  rewrite subst_cons; rewrite subst_cons. nd_weak 1; nd_weak 1. apply H.\nDefined.\n\nLemma exists_imply :\n  forall n Gamma A, Heyting Gamma (A @-> (add_n_exists n A).|[ren (+n)]).\nProof.\n  intros n. induction n as [|n IHn].\n  - intros Gamma A. asimpl. nd_intro; nd_assumption.\n  - intros Gamma A. simpl; nd_intro.\n    apply Nd_existI with (t := Var n). asimpl.\n    nd_revert 0. apply IHn.\nDefined.\n\nLemma friedman_n_exists :\n  forall n Gamma P A, Heyting ((friedman P.|[ren (+n)] A) :: Gamma..|[ren (+n)]) P.|[ren (+n)] -> Heyting (friedman P (add_n_exists n A) :: Gamma) P.\nProof.\n  intros n. induction n as [|n IHn].\n  - intros Gamma P A H. asimpl in *. apply H.\n  - intros Gamma P A H. asimpl in *.\n    apply double_neg_exists. apply IHn. asimpl. apply H.\nDefined.\n\nLemma n_exists_friedman_imply :\n  forall n Gamma A, QF A -> Heyting Gamma (dnegA (add_n_exists n A) (friedman (add_n_exists n A) (add_n_exists n A))) -> Heyting Gamma (add_n_exists n A).\nProof.\n  intros n Gamma A H1 H2.\n  eapply Nd_impE; [apply H2|].\n  nd_intro. apply friedman_n_exists.\n  eapply Nd_impE; [|apply friedman_or_equiv_l; apply H1].\n  nd_intro. eapply Nd_impE; [|nd_apply 0; nd_assumption].\n  nd_intro. nd_destruct_or 0; [|nd_assumption].\n  nd_revert 0; nd_clear 2. apply exists_imply.\nDefined.\n\nLemma after_exists_QF :\n  forall A, QF A -> QF (after_exists A).\nProof.\n  intros A H; destruct A; simpl in *; auto.\n  exfalso; auto.\nDefined.\n\nLemma Sigma_0_1_after_exists_QF :\n  forall A, Sigma_0 1 A -> QF (after_exists A).\nProof.\n  intros A H. remember 1 as n. induction H.\n  - apply after_exists_QF; auto.\n  - simpl; auto.\n  - injection Heqn; intro; subst. inversion p. apply after_exists_QF; auto.\nDefined.\n\nLemma Sigma_0_1_equiv :\n  forall Gamma A, Sigma_0 1 A -> Heyting Gamma (dnegA A (friedman A A)) -> Heyting Gamma A.\nProof.\n  intros Gamma A H1 H2.\n  rewrite <- add_n_exists_inverse.\n  apply n_exists_friedman_imply.\n  - apply Sigma_0_1_after_exists_QF; auto.\n  - rewrite add_n_exists_inverse; apply H2.\nDefined.\n\n(* Peano arithmetic is Sigma_0^1 conservative over Heyting arithmetic *)\n\nLemma Peano_Sigma_0_1_conservative :\n  forall A, Sigma_0 1 A -> Peano nil A -> Heyting nil A.\nProof.\n  intros A H1 H2.\n  apply Sigma_0_1_equiv; auto.\n  apply friedman_Peano_Heyting with (Gamma := nil); auto.\nDefined.\n\nFixpoint leading_foralls A :=\n  match A with\n  | Forall A => S (leading_foralls A)\n  | _ => 0\n  end.\n\nFixpoint after_foralls A :=\n  match A with\n  | Forall A => after_foralls A\n  | _ => A\n  end.\n\nFixpoint add_n_foralls n A :=\n  match n with\n  | 0 => A\n  | S n => Forall (add_n_foralls n A)\n  end.\n\nTheorem add_n_foralls_inverse :\n  forall A, add_n_foralls (leading_foralls A) (after_foralls A) = A.\nProof.\n  intros A. induction A; simpl; congruence.\nDefined.\n\nLemma after_foralls_QF :\n  forall A, QF A -> QF (after_foralls A).\nProof.\n  intros A H; destruct A; simpl in *; auto.\n  exfalso; auto.\nDefined.\n\nLemma Sigma_0_n_Pi_0_n_after_foralls :\n  forall n A, (Pi_0 n A -> Pi_0 n (after_foralls A)) * (Sigma_0 n A -> Sigma_0 n (after_foralls A)).\nProof.\n  intros n. induction n as [|n IHn].\n  - intros A. split; intros H; inversion H; constructor; apply after_foralls_QF; auto.\n  - intros A. remember (S n) as m. split.\n    + intros H. induction H.\n      * apply QF_Pi; apply after_foralls_QF; auto.\n      * injection Heqm; intros; subst. apply Sigma_Pi; apply IHn; auto.\n      * simpl; auto.\n    + intros H. induction H.\n      * apply QF_Sigma; apply after_foralls_QF; auto.\n      * simpl; apply Exists_Sigma; auto.\n      * injection Heqm; intros; subst. apply Pi_Sigma; apply IHn; auto.\nDefined.\n\nLemma Pi_0_Sn_after_foralls_Sigma_0_n :\n  forall n A, Pi_0 (S n) A -> Sigma_0 n (after_foralls A).\nProof.\n  intros n A H. remember (S n) as m. induction H.\n  - apply QF_Sigma; apply after_foralls_QF; auto.\n  - apply Sigma_0_n_Pi_0_n_after_foralls; congruence.\n  - simpl; auto.\nDefined.\n\nLemma add_foralls :\n  forall ax n A Gamma, nd ax Gamma..|[ren (+n)] A -> nd ax Gamma (add_n_foralls n A).\nProof.\n  intros ax n. induction n as [|n IHn].\n  - intros. simpl. asimpl in *. auto.\n  - intros A Gamma H. simpl in *. apply Nd_forallI. apply IHn.\n    asimpl; auto.\nDefined.\n\nLemma fold_env :\n  forall ax Gamma A, nd ax Gamma A -> nd ax nil (fold_left (fun B C => C @-> B) Gamma A).\nProof.\n  intros ax Gamma. induction Gamma as [|B Gamma IH].\n  - simpl. auto.\n  - intros A H. simpl. apply IH.\n    nd_intro; auto.\nDefined.\n\nLemma unfold_env :\n  forall ax Gamma A, nd ax nil (fold_left (fun B C => C @-> B) Gamma A) -> nd ax Gamma A.\nProof.\n  intros ax Gamma. induction Gamma as [|B Gamma IH].\n  - simpl. auto.\n  - intros A H. simpl. nd_revert 0. apply IH. simpl in H. auto.\nDefined.\n\nDefinition closed_formula A := forall sigma, A.|[sigma] = A.\n\nLemma add_n_foralls_r :\n  forall A n, add_n_foralls n (Forall A) = add_n_foralls (S n) A.\nProof.\n  intros A n; induction n; simpl in *; congruence.\nDefined.\n\nLemma add_n_foralls_closed :\n  forall n A, closed_formula A -> closed_formula (add_n_foralls n A).\nProof.\n  intros n. induction n as [|n IHn].\n  - intros A H; simpl in *; auto.\n  - intros A H sigma. simpl in *.\n    rewrite IHn; auto.\nDefined.\n\nLemma add_n_foralls_compose :\n  forall n m A, add_n_foralls n (add_n_foralls m A) = add_n_foralls (n + m) A.\nProof.\n  intros n m A. induction n; simpl in *; congruence.\nDefined.\n\nLemma add_more_foralls_closed :\n  forall n m A, m >= n -> closed_formula (add_n_foralls n A) -> closed_formula (add_n_foralls m A).\nProof.\n  intros n m A H1 H2.\n  replace m with ((m - n) + n) by (auto using Nat.sub_add).\n  rewrite <- add_n_foralls_compose. apply add_n_foralls_closed; auto.\nDefined.\n\nLemma iterate_sum :\n  forall (X : Type) (f : X -> X) x n1 n2, iterate f n1 (iterate f n2 x) = iterate f (n1 + n2) x.\nProof.\n  intros; induction n1 as [|n1 IH].\n  - asimpl; auto.\n  - simpl. unfold iterate in *. congruence.\nDefined.\nHint Rewrite iterate_sum : autosubst.\n\nLemma upn_max :\n  forall (P1 P2 : ((var -> expr) -> Prop)),\n    {n | forall sigma, P1 (upn n sigma)} -> {n | forall sigma, P2 (upn n sigma)} ->\n           {n | forall sigma, P1 (upn n sigma) /\\ P2 (upn n sigma)}.\nProof.\n  intros P1 P2 [n1 H1] [n2 H2].\n  set (m := max n1 n2). exists m. intros sigma. asimpl.\n  specialize (H1 (upn (m - n1) sigma)). specialize (H2 (upn (m - n2) sigma)).\n  asimpl in *.\n  rewrite Nat.add_comm in H1; rewrite Nat.sub_add in H1 by apply Nat.le_max_l.\n  rewrite Nat.add_comm in H2; rewrite Nat.sub_add in H2 by apply Nat.le_max_r.\n  auto.\nDefined.\n\nLemma upn_succ :\n  forall n sigma, upn (S n) sigma n = Var n.\nProof.\n  intros n. induction n as [|n IH].\n  - intros sigma. asimpl. auto.\n  - intros sigma. asimpl. rewrite IH. auto.\nDefined.\nHint Rewrite upn_succ : autosubst.\n\nLemma can_close_expr :\n  forall (t : expr), {n | forall sigma, t.[upn n sigma] = t}.\nProof.\n  intros t. induction t.\n  - exists (S v). intros sigma. asimpl. rewrite upn_succ; auto.\n  - exists 0. intros sigma. simpl. auto.\n  - destruct IHt as [n H]. exists n. intros sigma. specialize (H sigma). simpl. congruence.\n  - destruct (upn_max (fun sigma => t1.[sigma] = t1) (fun sigma => t2.[sigma] = t2) IHt1 IHt2)\n      as [m H].\n    exists m. intros sigma. specialize (H sigma). asimpl. destruct H; f_equal; auto.\n  - destruct (upn_max (fun sigma => t1.[sigma] = t1) (fun sigma => t2.[sigma] = t2) IHt1 IHt2)\n      as [m H].\n    exists m. intros sigma. specialize (H sigma). asimpl. destruct H; f_equal; auto.\nDefined.\n\n(* Every formula can be closed *)\n\nLemma can_close_formula :\n  forall A, {n | forall sigma, A.|[upn n sigma] = A}.\nProof.\n  intros A. induction A; try (exists 0; intro sigma; simpl in *; autosubst).\n  - destruct (upn_max (fun sigma => A1.|[sigma] = A1) (fun sigma => A2.|[sigma] = A2) IHA1 IHA2)\n      as [m H].\n    exists m. asimpl. intros sigma; specialize (H sigma). destruct H.\n    f_equal; auto.\n  - destruct (upn_max (fun sigma => A1.|[sigma] = A1) (fun sigma => A2.|[sigma] = A2) IHA1 IHA2)\n      as [m H].\n    exists m. asimpl. intros sigma; specialize (H sigma). destruct H.\n    f_equal; auto.\n  - destruct (upn_max (fun sigma => A1.|[sigma] = A1) (fun sigma => A2.|[sigma] = A2) IHA1 IHA2)\n      as [m H].\n    exists m. asimpl. intros sigma; specialize (H sigma). destruct H.\n    f_equal; auto.\n  - asimpl.\n    destruct (upn_max (fun sigma => e.[sigma] = e) (fun sigma => e0.[sigma] = e0) (can_close_expr e) (can_close_expr e0))\n      as [m H].\n    exists m. intros sigma; specialize (H sigma). destruct H.\n    f_equal; auto.\n  - destruct IHA as [n IHA].\n    exists n. intros sigma. asimpl. specialize (IHA (up sigma)).\n    asimpl in *. congruence.\n  - destruct IHA as [n IHA].\n    exists n. intros sigma. asimpl. specialize (IHA (up sigma)).\n    asimpl in *. congruence.\nDefined.\n\nLemma n_foralls_closed :\n  forall n A, (forall sigma, A.|[upn n sigma] = A) -> closed_formula (add_n_foralls n A).\nProof.\n  intros n. induction n as [|n IHn].\n  - intros. simpl. auto.\n  - intros. rewrite <- add_n_foralls_r.\n    apply IHn. intros sigma. asimpl. rewrite H; auto.\nDefined.\n\nLemma elim_foralls_closed :\n  forall ax n A, closed_formula (add_n_foralls n A) -> nd ax nil (add_n_foralls n A) -> forall sigma, nd ax nil A.|[sigma].\nProof.\n  intros ax n. induction n as [|n IHn].\n  - intros A H1 H2 sigma. simpl in *. rewrite H1. auto.\n  - intros A H1 H2 sigma. simpl in *.\n    replace A.|[sigma] with A.|[Var 0 .: ((ren (+1)) >> sigma >> ren (+1))].|[sigma 0/] by autosubst.\n    apply Nd_forallE.\n    replace (Forall A.|[Var 0 .: ren (+1) >> sigma >> ren (+1)])\n      with (Forall A).|[ren (+1) >> sigma] by autosubst.\n    apply IHn; rewrite add_n_foralls_r; auto.\nDefined.\n\nLemma fold_env_subst :\n  forall Gamma A sigma,\n    (fold_left (fun B C : formula => C @-> B) Gamma A).|[sigma] =\n    fold_left (fun B C : formula => C @-> B) Gamma..|[sigma] A.|[sigma].\nProof.\n  intros Gamma. induction Gamma as [|B Gamma IH].\n  - intros. simpl. auto.\n  - intros. rewrite subst_cons. simpl. rewrite IH. auto.\nDefined.\n\nLemma prove_subst :\n  forall ax Gamma A sigma, nd ax Gamma A -> nd ax Gamma..|[sigma] A.|[sigma].\nProof.\n  intros ax Gamma A sigma H.\n  apply unfold_env.\n  replace (fold_left (fun B C : formula => C @-> B) Gamma..|[sigma] A.|[sigma])\n    with (fold_left (fun B C : formula => C @-> B) Gamma A).|[sigma] by apply fold_env_subst.\n  set (B := fold_left (fun B C : formula => C @-> B) Gamma A).\n  destruct (can_close_formula B) as [n H1].\n  eapply elim_foralls_closed.\n  - apply n_foralls_closed. apply H1.\n  - apply add_foralls. simpl. apply fold_env; auto.\nDefined.\n\n(*\n\n(* Another way to prove the above lemma -- simpler, but requires to prove the\n   compatibility with substitution of all axioms. *)\n\nLemma prove_subst2 :\n  forall ax Gamma A, nd ax Gamma A -> forall sigma, nd ax Gamma..|[sigma] A.|[sigma].\nProof.\n  intros ax Gamma A H.\n  induction H; intros sigma; simpl; asimpl in *; try (constructor; auto; fail).\n  - admit.\n  - apply Nd_weak. specialize (IHnd sigma). auto.\n  - specialize (IHnd sigma). apply Nd_impI. auto.\n  - specialize (IHnd1 sigma); specialize (IHnd2 sigma). eapply Nd_impE; simpl; eauto.\n  - specialize (IHnd sigma); eapply Nd_andEL; eauto.\n  - specialize (IHnd sigma); eapply Nd_andER; eauto.\n  - specialize (IHnd1 sigma); specialize (IHnd2 sigma); specialize (IHnd3 sigma); eapply Nd_orE; eauto.\n  - eapply Nd_forallI. asimpl in *. specialize (IHnd (up sigma)).\n    asimpl in *. auto.\n  - replace A.|[t.[sigma] .: sigma] with A.|[up sigma].|[t.[sigma]/] by autosubst.\n    apply Nd_forallE. auto.\n  - eapply Nd_existI. asimpl. specialize (IHnd sigma). asimpl in *. eauto.\n  - eapply Nd_existE. apply IHnd1. specialize (IHnd2 (up sigma)). asimpl in *. auto.\n  - specialize (IHnd2 sigma). specialize (IHnd1 sigma).\n    replace A.|[t2.[sigma] .: sigma] with A.|[up sigma].|[t2.[sigma]/] by autosubst.\n    eapply Nd_eq_elim. apply IHnd1. asimpl in *. auto.\n\n *)\n\nLemma elim_foralls :\n  forall ax n Gamma A, nd ax Gamma (add_n_foralls n A) -> forall sigma, nd ax Gamma..|[ren (+n) >> sigma] A.|[sigma].\nProof.\n  intros ax n. induction n as [|n IHn].\n  - intros Gamma A H sigma. simpl in *. asimpl. apply prove_subst. auto.\n  - intros Gamma A H sigma. rewrite <- add_n_foralls_r in H.\n    specialize (IHn Gamma (Forall A) H (ren (+1) >> sigma)).\n    apply Nd_forallE with (t := sigma 0) in IHn.\n    asimpl in *. auto.\nDefined.\n\n(* Peano arithmetic is Pi_0^2 conservative over Heyting arithmetic *)\n\nLemma Peano_Pi_0_2_conservative :\n  forall A, Pi_0 2 A -> Peano nil A -> Heyting nil A.\nProof.\n  intros A H1 H2.\n  rewrite <- add_n_foralls_inverse in H2.\n  apply elim_foralls with (sigma := ids) in H2. asimpl in H2.\n  apply Peano_Sigma_0_1_conservative in H2; [|apply Pi_0_Sn_after_foralls_Sigma_0_n; auto].\n  rewrite <- add_n_foralls_inverse.\n  apply add_foralls. asimpl. auto.\nDefined.\n", "meta": {"author": "Ekdohibs", "repo": "foundations-of-proof-systems-project", "sha": "9d9a03345c04d1be4252dfa87a8f3da18c3ce013", "save_path": "github-repos/coq/Ekdohibs-foundations-of-proof-systems-project", "path": "github-repos/coq/Ekdohibs-foundations-of-proof-systems-project/foundations-of-proof-systems-project-9d9a03345c04d1be4252dfa87a8f3da18c3ce013/arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7025886504136797}}
{"text": "(*\n  Copyright 2022 ZhengPu Shi\n  This file is part of CoqMatrix. It is distributed under the MIT\n  \"expat license\". You should have recieved a LICENSE file with it.\n\n  purpose   : Matrix implemented with Function (Safe version) (Fixed Shape)\n  author    : ZhengPu Shi\n  date      : 2021.12\n  \n  remark    :\n  1. This is safe version of NatFun, which corrected the shape problem\n\n  2. About determinant and inversion matrix:\n  (1). There are three methods to compute the determinant,\n     ref: https://zhuanlan.zhihu.com/p/435900775\n     a. expand by row or column, then compute it with the algebraic remainder (代数\n        余子式) 。Each expansion corresponds to a drop of one order.\n        Note: expanding by rows/columns is a special case of Laplace's expansion \n        theorem.\n     b. using primitive transformations (初等变换).\n     c. with the help of inverse ordinal (逆序数) and permutation, i.e., by the \n        definition.\n  (2). Test the performance of inversion algorithm here which is an OCaml program \n     extracted from Coq.\n\n     Test result:\n          n=8, 1.1s;  n=9, 12s;  n=10, 120s\n\n     Main issue:\n     a. observed that, the CPU usage is too high, but memory usage is low.\n     b. maybe caused by the index of nat type, and I think that int type should \n        better. So, maybe we need to write an implementation in OCaml directly.\n     c. another reason is that the recursion of det function is too much.\n\n     So, we should write several version in OCaml, to check which one resulting the \n     bad performane.\n     a. version1, still use NatFun, but with index of int type.\n     b. version2, use array\n     c. version3, use matrix (bigarray)\n\n     New test result:\n     a. version1,\n        n=8, 0.25s;  n=9, 2.4s;  n=10, 32s\n        I think it is still slow, maybe causing by functional style\n     b. version2,\n        n=8, 1s;  n=9,7s; n=10, not tested yet\n        This version is slower than original one, although we have used\n        array structure, why? maybe too much foo loop? I'm not sure.\n *)\n\n\nRequire Export MatrixTheory.\nRequire Sequence SafeNatFun.Matrix.\nRequire PermutationExt.\n\n\n(* ######################################################################### *)\n(** * Basic matrix theory implemented with SafeNatFun *)\n\nModule BasicMatrixTheorySF (E : ElementType) <: BasicMatrixTheory E.\n\n  (** Basic library *)\n  Export BasicConfig TupleExt SetoidListListExt HierarchySetoid.\n\n  Export Sequence SafeNatFun.Matrix.\n  \n  (* ==================================== *)\n  (** ** Matrix element type *)\n  Export E.\n\n  Global Infix \"==\" := Aeq : A_scope.\n  Global Infix \"==\" := (eqlistA (eqlistA Aeq)) : dlist_scope.\n\n  Open Scope nat_scope.\n  Open Scope A_scope.\n  Open Scope mat_scope.\n\n  (* ==================================== *)\n  (** ** Matrix type and basic operations *)\n  \n  (** We define a _matrix_ as record which contains only one field has type of \n      nat -> nat -> A.\n      Meanwhile, thare are two parameters respresenting rows and columns of \n      the matrix as parts of type of mat. *)\n  Definition mat (r c : nat) := @mat A r c.\n\n  (** Square matrix *)\n  Definition smat (n : nat) := mat n n.\n\n  (* (** matrix equality *) *)\n  Definition meq {r c : nat} (m1 m2 : mat r c) : Prop := @meq A Aeq r c m1 m2.\n  Global Infix \"==\" := meq : mat_scope.\n\n  Lemma meq_equiv : forall {r c}, Equivalence (meq (r:=r) (c:=c)).\n  Proof. \n    intros. apply meq_equiv.\n  Qed.\n\n  Global Existing Instance meq_equiv.\n\n  (** Get n-th element of a matrix *)  \n  Definition mnth {r c} (m : mat r c) (ri ci : nat) := mnth (A0:=A0) m ri ci.\n  Global Notation \"m ! r ! c\" := (mnth m r c) : mat_scope.\n\n  (** meq and mnth should satisfy this constraint *)\n  Lemma meq_iff_mnth : forall {r c : nat} (m1 m2 : mat r c),\n      m1 == m2 <-> (forall ri ci, ri < r -> ci < c -> (m1 ! ri ! ci == m2 ! ri ! ci)%A).\n  Proof.\n    intros. apply meq_iff_mnth.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** Convert between list list and matrix *)\n\n  (** *** list list to mat *)\n  \n  Definition l2m {r c} (dl : list (list A)) : mat r c := @l2m A A0 r c dl.\n\n  (** l2m is a proper morphism *)\n  Lemma l2m_aeq_mor : forall r c, Proper (eqlistA (eqlistA Aeq) ==> meq) (@l2m r c).\n  Proof.\n  Admitted.\n\n  Global Existing Instance l2m_aeq_mor.\n  \n  Lemma l2m_inj : forall {r c} (d1 d2 : list (list A)),\n      length d1 = r -> width d1 c -> \n      length d2 = r -> width d2 c -> \n      ~(d1 == d2)%dlist -> ~(@l2m r c d1 == l2m d2).\n  Proof.\n    intros. apply l2m_inj; auto.\n  Qed.\n  \n  Lemma l2m_surj : forall {r c} (m : mat r c), \n      (exists d, l2m d == m).\n  Proof.\n    intros. apply l2m_surj.\n  Qed.\n\n  \n  (** *** mat to list list *)\n  Definition m2l {r c} (m : mat r c) : list (list A) := @m2l A r c m.\n\n  (** m2l is a proper morphism *)\n  Lemma m2l_aeq_mor : forall r c, Proper (meq ==> eqlistA (eqlistA Aeq)) (@m2l r c).\n  Proof.\n  Admitted.\n\n  Global Existing Instance m2l_aeq_mor.\n\n  Lemma m2l_length : forall {r c} (m : mat r c), length (m2l m) = r.\n  Proof.\n    intros. apply m2l_length.\n  Qed.\n\n  Global Hint Resolve m2l_length : mat.\n  \n  Lemma m2l_width : forall {r c} (m : mat r c), width (m2l m) c.\n  Proof.\n    intros. apply m2l_width.\n  Qed.\n\n  Global Hint Resolve m2l_width : mat.\n  \n  Lemma m2l_l2m_id : forall {r c} (dl : list (list A)) (H1 : length dl = r)\n                            (H2 : width dl c), (@m2l r c (l2m dl) == dl)%dlist.\n  Proof.\n    intros. apply m2l_l2m_id; auto.\n  Qed.\n  \n  Lemma l2m_m2l_id : forall {r c} (m : mat r c), l2m (m2l m) == m. \n  Proof.\n    intros. apply l2m_m2l_id; auto.\n  Qed.\n  \n  Lemma m2l_inj : forall {r c} (m1 m2 : mat r c),\n      ~(m1 == m2) -> ~(m2l m1 == m2l m2)%dlist.\n  Proof.\n    intros. apply (m2l_inj (A0:=A0)). easy.\n  Qed.\n  \n  Lemma m2l_surj : forall {r c} (d : list (list A)), \n      length d = r -> width d c -> \n      (exists m, @m2l r c m == d)%dlist.\n  Proof.\n    intros. apply (m2l_surj (A0:=A0)); auto.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** Specific matrix *)\n\n  Definition mk_mat_1_1 (a00 : A) : mat 1 1 := mk_mat_1_1 (A0:=A0) a00.\n\n  Definition mk_mat_3_1 (a00 a10 a20 : A) : mat 3 1 := mk_mat_3_1 (A0:=A0) a00 a10 a20.\n\n  Definition mk_mat_4_1 (a00 a10 a20 a30 : A) : mat 4 1 :=\n    mk_mat_4_1 (A0:=A0) a00 a10 a20 a30.\n\n  Definition mk_mat_2_2 (a00 a01 a10 a11 : A) : mat 2 2\n    := mk_mat_2_2 (A0:=A0) a00 a01 a10 a11.\n  \n  Definition mk_mat_3_3 (a00 a01 a02 a10 a11 a12 a20 a21 a22 : A) : mat 3 3 \n    := mk_mat_3_3 (A0:=A0) a00 a01 a02 a10 a11 a12 a20 a21 a22.\n\n  Definition mk_mat_4_4 (a00 a01 a02 a03 a10 a11 a12 a13\n                           a20 a21 a22 a23 a30 a31 a32 a33 : A) : mat 4 4 \n    := mk_mat_4_4 (A0:=A0) a00 a01 a02 a03 a10 a11 a12 a13\n         a20 a21 a22 a23 a30 a31 a32 a33.\n\n  (* ==================================== *)\n  (** ** Convert between tuples and matrix *)\n  \n  (** tuple_3x3 -> mat_3x3 *)\n  Definition t2m_3x3 (t : @T_3x3 A) : mat 3 3 := t2m_3x3 (A0:=A0) t.\n  \n  (** mat_3x3 -> tuple_3x3 *)\n  Definition m2t_3x3 (m : mat 3 3) : @T_3x3 A := m2t_3x3 m.\n  \n  (** m[0,0] : mat_1x1 -> A *)\n  Definition scalar_of_mat (m : mat 1 1) := m ! 0 ! 0.\n\n  (* ==================================== *)\n  (** ** Matrix transposition *)\n  \n  Definition mtrans {r c} (m : mat r c): mat c r :=\n    @mtrans A r c m.\n  \n  Global Notation \"m \\T\" := (mtrans m) : mat_scope.\n  \n  Lemma mtrans_trans : forall {r c} (m : mat r c), mtrans (mtrans m) == m.\n  Proof.\n    intros. apply mtrans_trans.\n  Qed.\n  \n  (* ==================================== *)\n  (** ** Mapping of matrix *)\n\n  (** Mapping of a matrix *)\n  Definition mmap {r c} (f : A -> A) (m : mat r c) : mat r c := @mmap A r c f m.\n  \n  Definition mmap2 {r c} (f: A -> A -> A) (m1 m2: mat r c) : mat r c :=\n    @mmap2 A r c f m1 m2.\n  \n  Lemma mmap2_comm : forall {r c} (f : A -> A -> A)\n                            (f_comm : forall a b : A, (f a b == f b a)%A)\n                            (m1 m2 : mat r c), \n      mmap2 f m1 m2 == mmap2 f m2 m1.\n  Proof.\n    (* lma. (* this tactic is enough too. *) *)\n    intros. apply mmap2_comm. auto.\n  Qed.\n  \n  Lemma mmap2_assoc : forall {r c} (f : A -> A -> A)\n                             (f_assoc : forall a b c, (f (f a b) c == f a (f b c))%A)\n                             (m1 m2 m3 : mat r c), \n      mmap2 f (mmap2 f m1 m2) m3 == mmap2 f m1 (mmap2 f m2 m3).\n  Proof.\n    intros. apply mmap2_assoc. auto.\n  Qed.\n\n  (** Auto unfold these definitions *)\n  Global Hint Unfold meq mmap mmap2 : mat.\n\n  (** linear matrix arithmetic tactic for equation: split goal to every element *)\n  Global Ltac lma :=\n    autounfold with mat;\n    Matrix.lma.\n\nEnd BasicMatrixTheorySF.\n\n\n(* ######################################################################### *)\n(** * Decidable matrix theory implemented with SafeNatFun *)\n\nModule DecidableMatrixTheorySF (E : DecidableElementType) <: DecidableMatrixTheory E.\n\n  (* Export E. *)\n  Include BasicMatrixTheorySF E.\n\n  (** linear matrix arithmetic tactic for equation: split goal to every element *)\n\n  (** meq is decidable *)\n  Lemma meq_dec : forall {r c}, Decidable (meq (r:=r)(c:=c)).\n  Proof.\n    intros. apply @meq_dec. apply Dec_Aeq.\n  Qed.\n\nEnd DecidableMatrixTheorySF.\n\n\n(* ######################################################################### *)\n(** * Ring matrix theory implemented with SafeNatFun *)\n\nModule RingMatrixTheorySF (E : RingElementType) <: RingMatrixTheory E.\n\n  (* Export E. *)\n  Include BasicMatrixTheorySF E.\n\n  Add Ring ring_thy_inst : Ring_thy.\n\n  (** Zero matrix *)\n  Definition mat0 r c : mat r c := @mat0 A A0 r c.\n\n  (** Unit matrix *)\n  Definition mat1 n : mat n n := @mat1 A A0 A1 n.\n\n  (** *** Addition of matrix *)\n\n  Definition madd {r c} (m1 m2 : mat r c) : mat r c := madd (Aadd:=Aadd) m1 m2.\n  Infix \"+\" := madd : mat_scope.\n  \n  (** m1 + m2 = m2 + m1 *)\n  Lemma madd_comm : forall {r c} (m1 m2 : mat r c), m1 + m2 == m2 + m1.\n  Proof.\n    intros. apply madd_comm.\n  Qed.\n  \n  (** (m1 + m2) + m3 = m1 + (m2 + m3) *)\n  Lemma madd_assoc : forall {r c} (m1 m2 m3 : mat r c), (m1 + m2) + m3 == m1 + (m2 + m3).\n  Proof.\n    intros. apply madd_assoc.\n  Qed.\n  \n  (** 0 + m = m *)\n  Lemma madd_0_l : forall {r c} (m : mat r c), (mat0 r c) + m == m.\n  Proof.\n    intros. apply madd_0_l.\n  Qed.\n  \n  (** m + 0 = m *)\n  Lemma madd_0_r : forall {r c} (m : mat r c), m + (mat0 r c) == m.\n  Proof.\n    intros. apply madd_0_r.\n  Qed.\n  \n\n  (** *** Opposite of matrix *)\n  \n  Definition mopp {r c} (m : mat r c) : mat r c := @mopp A Aopp r c m.\n  Global Notation \"- m\" := (mopp m) : mat_scope.\n\n  (** - - m = m *)\n  Lemma mopp_opp : forall {r c} (m : mat r c), - - m == m.\n  Proof.\n    intros. apply mopp_opp.\n  Qed.\n\n  (** m + (-m) = 0 *)\n  Lemma madd_opp : forall {r c} (m : mat r c), m + (-m) == mat0 r c.\n  Proof.\n    intros. apply madd_opp.\n  Qed.\n  \n  \n  (** *** Subtraction of matrix *)\n\n  Definition msub {r c} (m1 m2 : mat r c) : mat r c := @msub A Aadd Aopp r c m1 m2.\n  Infix \"-\" := msub : mat_scope.\n\n  (** m1 - m2 = - (m2 - m1) *)\n  Lemma msub_comm : forall {r c} (m1 m2 : mat r c), m1 - m2 == - (m2 - m1).\n  Proof.\n    intros. apply msub_comm.\n  Qed.\n  (** (m1 - m2) - m3 = m1 - (m2 + m3) *)\n  Lemma msub_assoc : forall {r c} (m1 m2 m3 : mat r c), (m1 - m2) - m3 == m1 - (m2 + m3).\n  Proof.\n    intros. apply msub_assoc.\n  Qed.\n\n  (** 0 - m = - m *)\n  Lemma msub_0_l : forall {r c} (m : mat r c), (mat0 r c) - m == - m.\n  Proof.\n    intros. apply msub_0_l.\n  Qed.\n  \n  (** m - 0 = m *)\n  Lemma msub_0_r : forall {r c} (m : mat r c), m - (mat0 r c) == m.\n  Proof.\n    intros. apply msub_0_r.\n  Qed.\n  \n  (** m - m = 0 *)\n  Lemma msub_self : forall {r c} (m : mat r c), m - m == (mat0 r c).\n  Proof.\n    intros. apply msub_self.\n  Qed.\n\n  \n  (** *** Scalar multiplication of matrix *)\n  \n  (** Left scalar multiplication of matrix *)\n  Definition mcmul {r c} (a : A) (m : mat r c) : mat r c :=\n    @mcmul A Amul r c a m.\n  Notation \"a c* m\" := (mcmul a m) : mat_scope.\n\n  (** Right scalar multiplication of matrix *)\n  Definition mmulc {r c} (m : mat r c) (a : A) : mat r c :=\n    @mmulc A Amul r c m a.\n  Notation \"m *c a\" := (mmulc m a) : mat_scope.\n  \n  (** m *c a = a c* m *)\n  Lemma mmulc_eq_mcmul : forall {r c} (a : A) (m : mat r c), m *c a == a c* m.\n  Proof.\n    intros. apply mmulc_eq_mcmul.\n  Qed.\n  \n  (** a * (b * m) = (a * b) * m *)\n  Lemma mcmul_assoc : forall {r c} (a b : A) (m : mat r c), a c* (b c* m) == (a * b)%A c* m.\n  Proof.\n    intros. apply mcmul_assoc.\n  Qed.\n  \n  (** a * (b * m) = b * (a * m) *)\n  Lemma mcmul_perm : forall {r c} (a b : A) (m : mat r c), a c* (b c* m) == b c* (a c* m).\n  Proof.\n    intros. apply mcmul_perm.\n  Qed.\n  \n  (** a * (m1 + m2) = (a * m1) + (a * m2) *)\n  Lemma mcmul_add_distr_l : forall {r c} (a : A) (m1 m2 : mat r c),\n      a c* (m1 + m2) == (a c* m1) + (a c* m2).\n  Proof.\n    intros. apply mcmul_add_distr_l.\n  Qed.\n  \n  (** (a + b) * m = (a * m) + (b * m) *)\n  Lemma mcmul_add_distr_r : forall {r c} (a b : A) (m : mat r c),\n      (a + b)%A c* m == (a c* m) + (b c* m).\n  Proof.\n    intros. apply mcmul_add_distr_r.\n  Qed.\n  \n  (** 0 * m = 0 *)\n  Lemma mcmul_0_l : forall {r c} (m : mat r c), A0 c* m == mat0 r c.\n  Proof.\n    intros. apply mcmul_0_l.\n  Qed.\n  \n  (** 1 * m = m *)\n  Lemma mcmul_1_l : forall {r c} (m : mat r c), A1 c* m == m.\n  Proof.\n    intros. apply mcmul_1_l.\n  Qed.\n\n\n  (** *** Multiplication of matrix *)\n  \n  Definition mmul {r c s} (m1 : mat r c) (m2 : mat c s) : mat r s :=\n    @mmul A Aadd A0 Amul r c s m1 m2.\n\n  Global Infix \"*\" := mmul : mat_scope.\n  \n  (** m1 * (m2 + m3) = (m1 * m2) + (m1 * m3) *)\n  Lemma mmul_add_distr_l : forall {r c s} (m1 : mat r c) (m2 m3 : mat c s),\n      m1 * (@madd c s m2 m3) == @madd r s (m1 * m2) (m1 * m3).\n  Proof.\n    intros. apply mmul_add_distr_l.\n  Qed.\n  \n  (** (m1 + m2) * m3 = (m1 * m3) + (m2 * m3) *)\n  Lemma mmul_add_distr_r : forall {r c s} (m1 m2 : mat r c) (m3 : mat c s),\n      (@madd r c m1 m2) * m3 == @madd r s (m1 * m3) (m2 * m3).\n  Proof.\n    intros. apply mmul_add_distr_r.\n  Qed.\n  \n  (** (m1 * m2) * m3 = m1 * (m2 * m3) *)\n  Lemma mmul_assoc : forall {r c s t} (m1 : mat r c) (m2 : mat c s) (m3 : mat s t),\n      (m1 * m2) * m3 == m1 * (m2 * m3).\n  Proof.\n    intros. apply mmul_assoc.\n  Qed.\n  \n  (** mat0 * m = mat0 *)\n  Lemma mmul_0_l : forall {r c s} (m : mat c s), (mat0 r c) * m == mat0 r s.\n  Proof.\n    intros. apply mmul_0_l.\n  Qed.\n  \n  (** m * mat0 = mat0 *)\n  Lemma mmul_0_r : forall {r c s} (m : mat r c), m * (mat0 c s) == mat0 r s.\n  Proof.\n    intros. apply mmul_0_r.\n  Qed.\n  \n  (** mat1 * m = m *)\n  Lemma mmul_1_l : forall {r c} (m : mat r c), (mat1 r) * m == m.\n  Proof.\n    intros. apply mmul_1_l.\n  Qed.\n  \n  (** m * mat1 = m *)\n  Lemma mmul_1_r : forall {r c} (m : mat r c), m * (mat1 c) == m.\n  Proof.\n    intros. apply mmul_1_r.\n  Qed.\n\n  (** a c* (m1 * m2) = (a c* m1) * m2. *)\n  Lemma mcmul_mul_assoc : forall {r c s} (a : A) (m1 : mat r c) (m2 : mat c s), \n      a c* (m1 * m2) == (a c* m1) * m2.\n  Proof.\n    intros. apply mcmul_mul_assoc.\n  Qed.\n  \n  (** m1 * (a c* m2) = a c* (m1 * m2). *)\n  Lemma mcmul_mul_perm : forall {r c s} (a : A) (m1 : mat r c) (m2 : mat c s), \n      a c* (m1 * m2) == m1 * (a c* m2).\n  Proof.\n    intros. apply mcmul_mul_perm.\n  Qed.\n\n  \n  (** Auto unfold these definitions *)\n  Global Hint Unfold madd mopp msub mcmul mmul : mat.\n\n  (** ** Extended matrix theory *)\n\n  (** Trace of a square matrix *)\n  Definition trace {n : nat} (m : smat n) :=\n    seqsum (A0:=A0) (Aadd:=Aadd) (fun i => m!i!i) n.\n  \n  (** Determinant of 3x3 matrix *)\n  Definition det3 (m : mat 3 3) : A :=\n    (let '((a11,a12,a13),(a21,a22,a23),(a31,a32,a33)) := m2t_3x3 m in\n     let b1 := (a11 * a22 * a33) in\n     let b2 := (a12 * a23 * a31) in\n     let b3 := (a13 * a21 * a32) in\n     let c1 := (a11 * a23 * a32) in\n     let c2 := (a12 * a21 * a33) in\n     let c3 := (a13 * a22 * a31) in\n     let b := (b1 + b2 + b3) in\n     let c := (c1 + c2 + c3) in\n     (b - c))%A.\n\nEnd RingMatrixTheorySF.\n\n\n(* ######################################################################### *)\n(** * Decidable Field matrix theory implemented with SafeNatFun *)\n\nModule DecidableFieldMatrixTheorySF (E : DecidableFieldElementType)\n<: DecidableFieldMatrixTheory E.\n\n  (* Export E. *)\n  Include RingMatrixTheorySF E.\n\n  Add Field field_inst : make_field_theory.\n\n  Import PermutationExt.\n\n  (** meq is decidable *)\n  Lemma meq_dec : forall (r c : nat), Decidable (meq (r:=r) (c:=c)).\n  Proof.\n    intros. apply meq_dec.\n  Qed.\n  \n  (** ** matrix theory *)\n\n  (** *** matrix inversion *)\n  Section Inversion.\n\n    (** Determinant of a square matrix.  *)\n    Definition det {n} (m : smat n) : A := @det A Aadd A0 Aopp Amul A1 n m.\n\n    (** Determinant of a matrix of 1D *)\n    Definition det_1_1 (m : smat 1) := @det_1_1 A m.\n\n    (** Determinant of a matrix of 2D *)\n    Definition det_2_2 (m : smat 2) := @det_2_2 A Aadd Aopp Amul m.\n\n    (** Determinant of a matrix of dimension-3 *)\n    Definition det_3_3 (m : smat 3) := @det_3_3 A Aadd Aopp Amul m.\n    \n    (** Cramer rule, which can slving the equation with form of M*x=b.\n      Note, the result is valid only when D is not zero *)\n    Definition cramerRule {n} (M : smat n) (b : mat n 1) : mat n 1 :=\n      @cramerRule A Aadd A0 Aopp Amul A1 Ainv n M b.\n    \n    (** Inverse matrix of a matrix *)\n    Definition minv {n} (m : smat n) := @minv A Aadd A0 Aopp Amul A1 Ainv n m.\n    \n    (** Simplified formula of inverse matrix of 1D *)\n    Definition inv_1_1 (m : smat 1) : smat 1 := @inv_1_1 A A0 Amul A1 Ainv m.\n\n    (** Simplified formula of inverse matrix of 2D *)\n    Definition inv_2_2 (m : smat 2) : smat 2 := @inv_2_2 A Aadd A0 Aopp Amul Ainv m.\n\n    (** Simplified formula of inverse matrix of 2D *)\n    Definition inv_3_3 (m : smat 3) : smat 3 := @inv_3_3 A Aadd A0 Aopp Amul Ainv m.\n\n  End Inversion.\n  \nEnd DecidableFieldMatrixTheorySF.\n\n\n(** Test *)\nModule Test.\n  Module Export MatrixQ := DecidableFieldMatrixTheorySF DecidableFieldElementTypeQ.\n  Open Scope Q.\n  Open Scope mat_scope.\n\n  Example m3 := mk_mat_3_3 1 2 3 4 5 6 7 8 9.\n  (* Compute m2l (m3 + m3). *)\n  (* Compute m2l (m3 * m3). *)\n\n  (** inverse matrix with concrete number *)\n  (* Compute m2l (minv m3). *)\n  Example m4 := mk_mat_3_3 1 2 3 4 5 7 6 8 9.\n  (* Compute m2l (minv m4). *)\n  (* Compute (m2l (m4 * (minv m4))). *)\n\n  Module Export MatrixR := DecidableFieldMatrixTheorySF DecidableFieldElementTypeR.\n  Open Scope R.\n  Open Scope mat_scope.\n\n  Variable a b c d : R.\n  \n  (** inverse matrix with symbol *)\n\n  (** direct result has many redundant items *)\n  (* Eval cbv in m2l (minv (mk_mat_2_2 a b c d)). *)\n\n  (** simplified result is better *)\n  (* Eval cbv in m2l (inv_2_2 (mk_mat_2_2 a b c d)). *)\n\nEnd Test.\n", "meta": {"author": "zhengpushi", "repo": "CoqMatrix", "sha": "28fa5f96e38a07659cfd373e09b0e75c24c22bfd", "save_path": "github-repos/coq/zhengpushi-CoqMatrix", "path": "github-repos/coq/zhengpushi-CoqMatrix/CoqMatrix-28fa5f96e38a07659cfd373e09b0e75c24c22bfd/CoqMatrix/SafeNatFun/MatrixTheorySF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7024068396393058}}
{"text": "(*\n(C) Copyright 2010, COQTAIL team\n\nProject Info: http://sourceforge.net/projects/coqtail/\n\nThis library is free software; you can redistribute it and/or modify it\nunder the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 2.1 of the License, or\n(at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,\nUSA.\n*)\n\nRequire Import Arith.\nRequire Export Nk_ind.\nRequire Export Ndiv.\nOpen Scope nat_scope.\n\n(** * Definition of a finite sum on [nat] with an index starting from 0 *)\n\nFixpoint Nfinite_sum_0_n (n : nat) (f : nat -> nat) {struct n} : nat :=\nmatch n with\n| 0 => f 0\n| S n' => (f n) + Nfinite_sum_0_n n' f\nend.\n\n(** * Properties of finite sum *)\n\n(** Compatibility with sum *)\nLemma Nfinite_sum_plus_compat : forall n f g,\n  Nfinite_sum_0_n n f + Nfinite_sum_0_n n g = Nfinite_sum_0_n n (fun k => f k + g k).\nProof.\ninduction n.\ncompute. reflexivity.\nintros.\nunfold Nfinite_sum_0_n. fold Nfinite_sum_0_n.\nrewrite plus_assoc_reverse.\nrewrite plus_assoc_reverse.\nassert (g (S n) + Nfinite_sum_0_n n g = Nfinite_sum_0_n n g + g (S n)).\nauto with arith.\nrewrite H.\nclear H.\nassert (Nfinite_sum_0_n n f + (Nfinite_sum_0_n n g + g (S n)) =\n  Nfinite_sum_0_n n f + Nfinite_sum_0_n n g + g (S n)).\nauto with arith.\nrewrite H.\nclear H.\nrewrite IHn.\nauto with arith.\nQed.\n\n(** Distributivity of multiplication *)\nLemma Nfinite_sum_mult_distrib : forall a n f, \n  a * Nfinite_sum_0_n n f = Nfinite_sum_0_n n (fun k => a * f k).\nProof.\ninduction n.\ncompute. reflexivity.\nintros.\nunfold Nfinite_sum_0_n. fold Nfinite_sum_0_n.\nrewrite <- IHn.\nring.\nQed.\n\n(** Compatibility with equality (limited equality) *)\nLemma Nfinite_sum_subtle_eq_compat :\n  forall n f g, (forall k, k <= n -> f k = g k) -> Nfinite_sum_0_n n f = Nfinite_sum_0_n n g.\nProof.\ninduction n.\ncompute. intros.\napply H. trivial.\nintros.\nunfold Nfinite_sum_0_n. fold Nfinite_sum_0_n.\nrewrite (IHn f g).\nrewrite (H (S n)).\nreflexivity.\ntrivial.\nintros.\napply H.\nauto with arith.\nQed.\n\n(** compatibility with equality (unlimited equality) *)\nLemma Nfinite_sum_eq_compat : forall n f g, \n  (forall k, f k = g k) -> Nfinite_sum_0_n n f = Nfinite_sum_0_n n g.\nProof.\nintros.\napply Nfinite_sum_subtle_eq_compat.\nintros.\napply H.\nQed.\n\n(** One term, lower splitting of finite sum *)\nLemma Nfinite_sum_split_lower : forall n f,\n  Nfinite_sum_0_n (S n) f = f 0 + Nfinite_sum_0_n n (fun k => f (S k)).\nProof.\ninduction n.\ncompute. auto with arith.\nintros.\nunfold Nfinite_sum_0_n. fold Nfinite_sum_0_n.\nunfold Nfinite_sum_0_n in IHn. fold Nfinite_sum_0_n in IHn.\nrewrite IHn.\nrewrite plus_assoc.\nrewrite plus_assoc.\nauto with arith.\nQed.\n\n(** One term, upper splitting of finite sum *)\nLemma Nfinite_sum_split_upper : forall n f,\n  Nfinite_sum_0_n (S n) f = Nfinite_sum_0_n n f + f (S n).\nProof.\nintros.\nunfold Nfinite_sum_0_n. fold Nfinite_sum_0_n.\nauto with arith.\nQed.\n\n(** General splitting of finite sum *)\nLemma Nfinite_sum_split : forall n p q f, \n  p + q = n -> Nfinite_sum_0_n (S n) f = Nfinite_sum_0_n p f + Nfinite_sum_0_n q (fun k => f (kth_S p k)).\nProof.\ninduction n.\ninduction p.\nintros.\nsimpl in H.\nrewrite H.\nunfold Nfinite_sum_0_n.\nunfold kth_S.\nauto with arith.\n\nintros.\ndiscriminate H.\n\ndestruct p.\nintros.\nsimpl in H.\nrewrite H. clear H.\nassert (Nfinite_sum_0_n 0 f=f 0).\ncompute. reflexivity.\nrewrite H. clear H.\nrewrite Nfinite_sum_split_lower.\nunfold kth_S.\nreflexivity.\nintros.\nassert (p+q=n).\nauto with arith.\nclear H.\nassert (Nfinite_sum_0_n (S (S n)) f=f(S(S n))+Nfinite_sum_0_n (S n) f).\nrewrite plus_comm.\napply Nfinite_sum_split_upper.\nrewrite H. clear H.\nrewrite (IHn p q).\nrewrite Nfinite_sum_split_upper.\nassert (f (S p) + Nfinite_sum_0_n q (fun k : nat => f (kth_S (S p) k))\n  = Nfinite_sum_0_n (S q) (fun k=>f(kth_S p k))).\nrewrite Nfinite_sum_split_lower.\nrewrite kth_S_special.\nunfold kth_S. fold kth_S.\nassert (forall k:nat, kth_S p (S k)=S(kth_S p k)).\nintro.\nrewrite kth_S_sym.\nunfold kth_S. fold kth_S.\nrewrite kth_S_sym.\nreflexivity.\nassert (Nfinite_sum_0_n q (fun k : nat => f (S (kth_S p k)))=\n  Nfinite_sum_0_n q (fun k : nat => f (kth_S p (S k)))).\napply Nfinite_sum_eq_compat.\nintro.\nrewrite (H k).\nreflexivity.\nrewrite H1.\nreflexivity.\nassert (Nfinite_sum_0_n p f + f (S p) +\n  Nfinite_sum_0_n q (fun k : nat => f (kth_S (S p) k))\n  =\n  Nfinite_sum_0_n p f + (f (S p) +\n  Nfinite_sum_0_n q (fun k : nat => f (kth_S (S p) k)))).\nauto with arith.\nrewrite H1. clear H1.\nrewrite H. clear H.\nassert (f (S (S n)) +\n  (Nfinite_sum_0_n p f + Nfinite_sum_0_n q (fun k : nat => f (kth_S p k)))\n  =\n  Nfinite_sum_0_n p f + (Nfinite_sum_0_n q (fun k : nat => f (kth_S p k))+f (S (S n)))).\nrewrite plus_comm.\nauto with arith.\nrewrite H. clear H.\nassert (Nfinite_sum_0_n (S q) (fun k : nat => f (kth_S p k)) =\n  Nfinite_sum_0_n q (fun k : nat => f (kth_S p k)) + f (S (S n))).\nrewrite Nfinite_sum_split_upper.\nassert (kth_S p (S q)=S(S n)).\nrewrite kth_S_sym.\nunfold kth_S. fold kth_S.\nrewrite kth_S_sym.\nrewrite kth_S_plus.\nassert (q+p+1=(p+q)+1).\nauto with arith.\nrewrite H. rewrite H0. clear H.\nrewrite plus_1_r.\nreflexivity.\nrewrite <- H.\nreflexivity.\nrewrite H.\nauto with arith.\nexact H0.\nQed.\n\n(** Compatibility with division *)\nLemma Nfinite_sum_div_compat : forall n f p,\n  (forall k, k <= n -> (p | f k)) -> (p | Nfinite_sum_0_n n f).\nProof.\ninduction n.\nintros.\nsimpl. apply H. auto.\nintros.\nrewrite Nfinite_sum_split_upper.\napply Ndiv_plus_compat.\napply IHn.\nintros.\napply H. auto with arith.\napply H.\nauto.\nQed.\n", "meta": {"author": "coqtail", "repo": "coqtail", "sha": "96799cc6901b9cdb1c5f47add0f9cd6584fdd389", "save_path": "github-repos/coq/coqtail-coqtail", "path": "github-repos/coq/coqtail-coqtail/coqtail-96799cc6901b9cdb1c5f47add0f9cd6584fdd389/rls/rls1/Arith/Nfinite_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619393159451, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7024026562173405}}
{"text": "\nRequire Arith.\n\n(*\nInductive le (n : nat) : nat -> Prop :=\n | le_n : n <= n \n | le_S : forall m : nat, n <= m -> n <= S m\n*)\n\n\nFixpoint leb (n m : nat) : bool :=\n  match n with\n    | 0 => true\n    | S n' => match m with\n                | 0 => false\n                | S m' => leb n' m'\n              end\n  end.\n\nEval compute in (leb 5 2).\nEval compute in (leb 50 2).\nEval compute in (leb 52 52).\nEval compute in (leb 100 424).\n\n(*\nLemma le_0_any : forall m, 0 <= m.\nProof.\n  induction m.\n  constructor. (*  apply le_n. *)\n  constructor.\n  trivial.\nDefined.\n*)\n\nFixpoint le_0_any (m:nat) : 0 <= m :=\n  match m return 0 <= m with\n    | 0 => le_n 0\n    | S m' => le_S _ _ (le_0_any m')\n  end.\n\n\nDefinition le_n_S      : forall n m : nat, n <= m -> S n <= S m :=\nfun (n m : nat) (H : n <= m) =>\nle_ind n (fun m0 : nat => S n <= S m0) (le_n (S n))\n  (fun (m0 : nat) (_ : n <= m0) (IHle : S n <= S m0) =>\n   le_S (S n) (S m0) IHle) m H\n.\n\n\nLemma leb_le : forall n m, leb n m = true -> n <= m.\nProof.\n  induction n; try rename n into n'.\n  intros m H.\n  apply le_0_any.\n\n  simpl.\n  intros m.\n  case m; clear m.\n  intros Habs.\n  discriminate.\n  intros m'.\n  intros H.\n  generalize (IHn _ H); intros H1.\n  apply le_n_S.\n  trivial.\nDefined.\n\nEval compute in (leb_le 4 9 (refl_equal _)).\n\n\nLemma le_leb : forall n m, n <= m -> leb n m = true.\nProof.\n  induction n.\n  intros m H.\n  simpl.\n  trivial.\n  intros m.\n  intros H.\n  generalize (IHn _ H); intros H1.\n  simpl.\n  case m.\n  intros Habs.\n\nQed.\n\n(*\n; A nat is\n;  - 0  or\n;  - S n\n\n; le : nat nat -> boolean\n(define (le n m)\n  (cond [(n = 0) ...]\n        [(n = S n')   .. (le n' ..)... ]))\n\n..)\n\n\n*)\n\n", "meta": {"author": "nadeemabdulhamid", "repo": "make-change", "sha": "2b8667e4a0db00b6988f249c29bb4452ea254f3a", "save_path": "github-repos/coq/nadeemabdulhamid-make-change", "path": "github-repos/coq/nadeemabdulhamid-make-change/make-change-2b8667e4a0db00b6988f249c29bb4452ea254f3a/coq/ltplay.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7024026551772656}}
{"text": "From Coq Require Import Lia.\nFrom Coq Require Import List.\nFrom Coq Require Import Logic.Eqdep_dec.\nFrom Coq Require Import ZArith.\n\nClass IsMonoid (M : Type) (op : M -> M -> M) (e : M) : Prop :=\n  { munit_left  : forall m, (op e m) = m;\n    munit_right : forall m, (op m e) = m;\n    massoc      : forall m1 m2 m3, op m1 (op m2 m3) = op (op m1 m2) m3\n  }.\n\n#[refine]\nInstance nat_sum_monoid : IsMonoid nat (fun x y => x + y) 0 :=\n  {| munit_left  := _;\n     munit_right := _;\n     massoc      := _\n  |}.\nall: lia.\nQed.\n\n#[refine]\nInstance nat_mul_monoid : IsMonoid nat (fun x y => x * y) 1 :=\n  {| munit_left  := _;\n     munit_right := _;\n     massoc      := _\n  |}.\nall: lia.\nQed.\n\nOpen Scope Z.\n\n#[refine]\nInstance Z_sum_monoid : IsMonoid Z (fun x y => x + y) 0 :=\n  {| munit_left  := _;\n     munit_right := _;\n     massoc      := _\n  |}.\nall: lia.\nQed.\n\nClose Scope Z.\n\nClass Dec (A : Type) : Prop :=\n  { dec : forall x y : A, x = y \\/ x <> y }.\n\n#[refine]\nInstance Z_dec : Dec Z := { dec := _ }.\nrepeat decide equality. Qed.\n\n#[refine]\nInstance from_dec {A : Type} (d : forall x y : A, {x = y} + {x <> y}) : Dec A :=\n  { dec := _ }.\nintros x y; specialize (d x y) as []; [left | right]; assumption. Qed.\n\nInstance bool_dec : Dec bool := from_dec Bool.bool_dec.\nInstance nat_dec  : Dec nat := from_dec Nat.eq_dec.\n\n#[refine]\nInstance list_dec {A : Type} `{Dec A} : Dec (list A) :=\n  { dec := _ }.\ndecide equality; apply dec. Qed.\n\n#[refine]\nInstance Tuple_dec {A B : Type} `{Dec A} `{Dec B} : Dec (A * B) :=\n  { dec := _ }.\ndecide equality; apply dec. Qed.\n\nClass SigEq {A : Type} (P : A -> Prop) : Prop :=\n  { subset_eq : forall x y : sig P, proj1_sig x = proj1_sig y -> x = y }.\n\n#[refine]\nInstance SigEq_dec {A B : Type} `{Dec B} {f g : A -> B} : SigEq (fun x => f x = g x) :=\n  { subset_eq := _ }.\nintros [x px] [y py]; simpl; intros; subst; f_equal; apply (eq_proofs_unicity dec).\nQed.\n\n#[refine]\nInstance sig_dec {A : Type} {P : A -> Prop} `{Dec A} `{SigEq A P} : Dec (sig P) :=\n  { dec := _ }.\nintros [x px] [y py];\n  specialize (dec x y) as [];\n  subst.\n* left; apply subset_eq; simpl; reflexivity.\n* right; unfold not; inversion 1; auto.\nQed.\n\n(** A result that helps in dealing with situations where heterogeneous equality\n    might seem needed. Instead of assuming [JMeq_eq] we can prove that, after a\n    function application, elements of equal \"dependent subset types\" are equal *)\nLemma heterog_subset_eq_f {D X Y : Type} {P : D -> X -> Prop}:\n    forall (sigeq : forall (d : D), SigEq (P d))\n      (f : forall {d : D}, sig (P d) -> Y)\n      (d1 d2 : D)\n      (x1 : sig (P d1))\n      (x2 : sig (P d2)),\n    d1 = d2 -> proj1_sig x1 = proj1_sig x2 -> f x1 = f x2.\nProof.\n  intros pi * H1 H2; subst; apply subset_eq in H2; subst; reflexivity.\nQed.\n", "meta": {"author": "annenkov", "repo": "futhark-extract", "sha": "a637d37382e602a707db398a30168664c0a73c42", "save_path": "github-repos/coq/annenkov-futhark-extract", "path": "github-repos/coq/annenkov-futhark-extract/futhark-extract-a637d37382e602a707db398a30168664c0a73c42/theories/FutharkUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.70240264450726}}
{"text": "Require Export DFA.\n\nSection Normalization.\n\nContext {State Symbol : Type}.\nHypothesis State_eq_dec : forall (x1 x2:State), { x1 = x2 } + { x1 <> x2 }.\nHypothesis Symbol_eq_dec : forall (x1 x2:Symbol), { x1 = x2 } + { x1 <> x2 }.\nDefinition NFA := @NFA State Symbol.\n\nDefinition Det_state := ListSet State.\n\nLemma Det_state_eq_dec : forall (x1 x2:Det_state), { x1 = x2 } + { x1 <> x2 }.\nProof.\n  apply list_eq_dec, State_eq_dec.\nQed.\n\n(* Normalize the set states of a NFA *)\nFixpoint normalize_nfa (g cp:@NFA.NFA Det_state Symbol) :=\n  let normalize_state := fun q => get_set State State_eq_dec q (states cp) in\n\n  match g with\n  | state q::g => state (normalize_state q)::normalize_nfa g cp\n  | start q::g => start (normalize_state q)::normalize_nfa g cp\n  | accept q::g => accept (normalize_state q)::normalize_nfa g cp\n  | transition q1 a q2::g => transition (normalize_state q1) a (normalize_state q2)::normalize_nfa g cp\n  | x::g => x::normalize_nfa g cp\n  | nil => nil\n  end.\n\n(* The resulting states *)\nLemma normalize_states g cp q :\n  In q (states (normalize_nfa g cp)) ->\n  exists q', q = get_set State State_eq_dec q' (states cp) /\\\n  In q' (states g).\nProof.\n  intro H.\n  induction g as [|c g IH].\n  contradiction.\n  assert (forall A (x:A) l, x::l = [x] ++ l).\n  simpl; intuition.\n  simpl in H; destruct c.\n  2: intuition.\n  - rewrite H0 in H; apply in_states_app in H.\n    destruct H.\n    2: apply IH in H; destruct H as [q' H]; exists q'; split; try right; intuition.\n    destruct H.\n    2: contradiction.\n    symmetry in H; exists q0; split; try left; intuition.\n  (* same code from above: *)\n  - rewrite H0 in H; apply in_states_app in H.\n    destruct H.\n    2: apply IH in H; destruct H as [q' H]; exists q'; split; try right; intuition.\n    destruct H.\n    2: contradiction.\n    symmetry in H; exists q0; split; try left; intuition.\n  (* same code from above: *)\n  - rewrite H0 in H; apply in_states_app in H.\n    destruct H.\n    2: apply IH in H; destruct H as [q' H]; exists q'; split; try right; intuition.\n    destruct H.\n    2: contradiction.\n    symmetry in H; exists q0; split; try left; intuition.\n  - rewrite H0 in H; apply in_states_app in H.\n    destruct H.\n    2: apply IH in H; destruct H as [q' H]; exists q'; split; try right; intuition.\n    destruct H.\n    symmetry in H; exists q1; split; try left; intuition.\n    destruct H.\n    2: contradiction.\n    symmetry in H; exists q2; split; try (right; left); intuition.\nQed.\n\n(* The resulting start state *)\nLemma normalize_start_states_singleton g cp Q :\n  let normalize_state := fun q => get_set State State_eq_dec q (states cp) in\n  \n  start_states g = [Q] -> start_states (normalize_nfa g cp) = [normalize_state Q].\nProof.\n  intros f H.\n  assert (start_states (normalize_nfa g cp) = map f (start_states g)).\n  2: rewrite H in H0; intuition.\n  clear H.\n  induction g as [|c g IH].\n  intuition.\n  destruct c.\n  1,2,4,5: intuition.\n  simpl; rewrite IH; intuition.\nQed.\n\n(* The resulting accept states *)\nLemma normalize_accept_states g cp q :\n  In q (accept_states (normalize_nfa g cp)) ->\n  exists q', q = get_set State State_eq_dec q' (states cp) /\\\n  In q' (accept_states g).\nProof.\n  intro H.\n  induction g as [|c g IH].\n  contradiction.\n  simpl in H; destruct c.\n  1-3,5: intuition.\n  assert (forall A (x:A) l, x::l = [x] ++ l).\n  simpl; intuition.\n  rewrite H0 in H.\n  apply in_accept_states_app in H.\n  destruct H.\n  2: apply IH in H; destruct H as [q' H]; exists q'; split; try right; intuition.\n  destruct H.\n  2: contradiction.\n  exists q0; split.\n  symmetry; intuition.\n  left; intuition.\nQed.\n\n(* The resulting transitions *)\nLemma normalize_states_transitions1 g cp q1 a q2 :\n  In (transition q1 a q2) (normalize_nfa g cp) ->\n  exists q1' q2', equiv_sets State q1 q1' /\\ equiv_sets State q2 q2' /\\\n  In (transition q1' a q2') g /\\ q1 = get_set State State_eq_dec q1' (states cp) /\\\n  q2 = get_set State State_eq_dec q2' (states cp).\nProof.\n  intro H.\n  induction g as [|c g IH].\n  contradiction.\n  simpl in H; destruct c.\n  1-4: simpl in H; destruct H; try discriminate; apply IH in H;\n  destruct H as [q1' [q2' [H0 [H1 [H2 [H3 H4]]]]]];\n  exists q1', q2'; repeat split; try right; intuition; try apply H0; try apply H1.\n  destruct H.\n  2: apply IH in H; destruct H as [q1' [q2' [H0 [H1 [H2 [H3 H4]]]]]];\n  exists q1', q2'; repeat split; try right; intuition; try apply H0; try apply H1.\n  injection H; intros; subst; exists q0, q3; split.\n  2: split.\n  3: split.\n  3,4: intuition.\n  remember (get_set State State_eq_dec q0 (states cp)) eqn:H0.\n  2: remember (get_set State State_eq_dec q3 (states cp)) eqn:H0.\n  1,2: symmetry in H0; apply get_set_equiv in H0; apply equiv_sets_comm;\n  intuition.\nQed.\n\nLemma normalize_states_transitions2 g cp q1 a q2 :\n  let normalize_state := fun q => get_set State State_eq_dec q (states cp) in\n\n  In (transition q1 a q2) g ->\n  In (transition (normalize_state q1) a (normalize_state q2)) (normalize_nfa g cp).\nProof.\n  intros f H.\n  induction g as [|c g IH].\n  contradiction.\n  simpl in H; destruct c.\n  1-4: destruct H; try discriminate; right; intuition.\n  destruct H.\n  injection H; intros; subst; left; intuition.\n  right; intuition.\nQed.\n\n\nLemma normalize_equiv_set_states g cp q1 q2 :\n  (subset (ListSet State) (states g) (states cp)) ->\n  In q1 (states (normalize_nfa g cp)) ->\n  In q2 (states (normalize_nfa g cp)) ->\n  equiv_sets State q1 q2 -> q1 = q2.\nProof.\n  intros H H0 H1 H2.\n  apply normalize_states in H0, H1.\n  destruct H0 as [q1' [H0 H3]]; destruct H1 as [q2' [H1 H4]].\n  apply H in H3, H4; clear H.\n  remember (states cp) as s eqn:H5.\n  assert (q1 = get_set State State_eq_dec q1' s).\n  rewrite H5; intuition.\n  clear H0.\n  assert (q2 = get_set State State_eq_dec q2' s).\n  rewrite H5; intuition.\n  clear H1 H5 cp.\n  induction s as [|q s IH].\n  contradiction.\n  destruct H3, H4; subst.\n  intuition.\n  1,2: apply get_equiv_sets; intuition.\n  simpl; simpl in H2, IH.\n  destruct (equiv_sets_dec State State_eq_dec q q1') as [H4|H4];\n  destruct (equiv_sets_dec State State_eq_dec q q2') as [H5|H5].\n  1,4: intuition.\n  - remember (get_set State State_eq_dec q2' s) as q' eqn:H6; symmetry in H6; apply get_set_equiv in H6.\n    assert (False).\n    2: intuition.\n    apply H5.\n    apply equiv_sets_trans with q'.\n    2: apply equiv_sets_comm.\n    1,2: intuition.\n  - remember (get_set State State_eq_dec q1' s) as q' eqn:H6; symmetry in H6; apply get_set_equiv in H6.\n    assert (False).\n    2: intuition.\n    apply H4.\n    apply equiv_sets_trans with q'.\n    1,2: apply equiv_sets_comm; intuition.\nQed.\n\nEnd Normalization.", "meta": {"author": "fil1pe", "repo": "brzozowski-algorithm", "sha": "66bdff98c14c203d9f88cb6fe2b5c81612a81439", "save_path": "github-repos/coq/fil1pe-brzozowski-algorithm", "path": "github-repos/coq/fil1pe-brzozowski-algorithm/brzozowski-algorithm-66bdff98c14c203d9f88cb6fe2b5c81612a81439/Normalization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.702399593920767}}
{"text": "From Coq Require Lia.\nFrom Coq Require Import Relations Wellfounded.\nSet Implicit Arguments.\n\nSection star.\nUnset Implicit Arguments.\nVariable A:Type.\nVariable R : A -> A -> Prop.\nInductive star (x:A) : A -> Prop := \n| star_refl : star x x\n| star_step : forall y, star x y -> forall z, R y z -> star x z\n.\n\n\nLemma star_trans: forall x y z, star x y -> star y z -> star x z.\nProof. \nintros x y z H H1;revert x H; \ninduction H1.\n\ntauto.\nintros.\neconstructor 2 with y0;auto.\nQed.\n\nLemma star_R : forall x y, R x y -> star x y.\nProof.\nintros x y H;constructor 2 with x;[constructor|assumption].\nQed.\n\nLemma star_ind2 : forall  x (P:A -> Prop),\n  (P x) -> \n  (forall y, P y -> forall z, R y z -> P z) ->\n  forall a, star x a -> P a.\nProof.\n  intros x P H H0 a H1.\n  induction H1.\n  exact H.\n  apply H0 with (y:=y);assumption.\nQed.\n\nEnd star.\n\nLtac prove_star := \n  match goal with \n    | |- star _ _ ?t ?t => exact rt_refl\n    | H:star _ _ ?t' ?t |- star _ _ ?t' ?t =>  assumption\n    | H:star _ _ ?t'' ?t |- star _ _ ?t' ?t =>  \n      (apply star_trans with t'';[prove_star|exact H]) || \n        (clear H;prove_star)\n    | H:star _ _ ?t' ?t'' |- star _ _ ?t' ?t =>  \n      (apply star_trans with t'';[exact H|prove_star]) || \n        (clear H;prove_star)\n    | H:?R ?t' ?t |- star _ _ ?t' ?t =>  apply star_R;exact H\n    | H:?R ?t'' ?t |- star _ _ ?t' ?t =>  \n      (apply star_trans with t'';[prove_star|apply star_R;exact H]) || \n        (clear H;prove_star)\n    | H:?R ?t' ?t'' |- star _ _ ?t' ?t =>  \n      (apply star_trans with t'';[apply star_R;exact H|prove_star]) || \n        (clear H;prove_star)\n    | _ => solve [eauto]\n  end.\n\n\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Coccinelle/basis/terminaison.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7931059462938814, "lm_q1q2_score": 0.7023995905043108}}
{"text": "Require Export Coq.Unicode.Utf8.\nRequire Import Coq.micromega.Lia.\n\nLemma S_le {n m} : S n ≤ m → exists m', m = S m' ∧ n ≤ m'.\nProof.\n  intros le; destruct m; [exfalso|exists m]; lia.\nQed.\n\nLemma lt_inv_plus {n m} : n < m → exists r, m = n + S r.\nProof.\n  induction 1.\n  - exists 0; lia.\n  - destruct IHle as [r ?]; subst.\n    exists (S r); lia.\nQed.\n\nLemma le_inv_plus {n m} : n ≤ m → exists r, m = n + r.\nProof.\n  induction 1.\n  - exists 0; lia.\n  - destruct IHle as [r ?]; subst.\n    exists (S r); lia.\nQed.\n\n", "meta": {"author": "dominiquedevriese", "repo": "fixismu-coq", "sha": "8a98893e9ab1277bf5d6980446c2ec71a805c283", "save_path": "github-repos/coq/dominiquedevriese-fixismu-coq", "path": "github-repos/coq/dominiquedevriese-fixismu-coq/fixismu-coq-8a98893e9ab1277bf5d6980446c2ec71a805c283/Common/Common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.7023995854875048}}
{"text": "From Coq Require Import Bool.Bool.\nFrom Coq Require Import Init.Nat.\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Arith.EqNat. Import Nat.\nFrom Coq Require Import Lia.\nFrom Coq Require Import Lists.List. Import ListNotations.\nFrom Coq Require Import Strings.String.\nFrom LF Require Export Maps.\n\nModule AExp.\n  (* Abstract syntax *)\n  Inductive aexp : Type :=\n  | ANum (n : nat)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp).\n\n  (* Bool expression *)\n  Inductive bexp : Type :=\n  | BTrue\n  | BFalse\n  | BEq (a1 a2 : aexp)\n  | BNEq (a1 a2 : aexp)\n  | BLe (a1 a2 : aexp)\n  | BGt (a1 a2 : aexp)\n  | BNot (b : bexp)\n  | BOr (b1 b2 : bexp)\n  | BAnd (b1 b2 : bexp).\n\n  Fixpoint aeval (a : aexp) : nat :=\n    match a with\n    | ANum n => n\n    | APlus a1 a2 => (aeval a1) + (aeval a2)\n    | AMinus a1 a2 => (aeval a1) - (aeval a2)\n    | AMult a1 a2 => (aeval a1) * (aeval a2)\n    end.\n\n  Example test_aeval :\n    aeval (APlus (ANum 2) (ANum 2)) = 4.\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Fixpoint beval (b : bexp) : bool :=\n    match b with\n    | BTrue => true\n    | BFalse => false\n    | BEq a1 a2 => (aeval a1) =? (aeval a2)\n    | BNEq a1 a2 => negb ((aeval a1) =? (aeval a2))\n    | BLe a1 a2 => (aeval a1) <=? (aeval a2)\n    | BGt a1 a2 => negb ((aeval a1) <=? (aeval a2))\n    | BNot b => negb (beval b)\n    | BAnd b1 b2 => andb (beval b1) (beval b1)\n    | BOr b1 b2 => orb (beval b1) (beval b1)\n    end.\n\n  Fixpoint optimize_0plus (a : aexp) : aexp :=\n    match a with\n    | ANum n => ANum n\n    | APlus (ANum 0) a2 => optimize_0plus a2\n    (* | APlus a1 (ANum 0) => optimize_0plus a1 *)\n    | APlus a1 a2 => APlus (optimize_0plus a1) (optimize_0plus a2)\n    | AMinus a1 a2 => AMinus (optimize_0plus a1) (optimize_0plus a2)\n    | AMult a1 a2 => AMult (optimize_0plus a1) (optimize_0plus a2)\n    end.\n\n  Example test_optimize_0plus :\n    optimize_0plus (APlus (ANum 2)\n                      (APlus (ANum 0)\n                        (APlus (ANum 0) (ANum 1))))\n    = APlus (ANum 2) (ANum 1).\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Theorem optimize_0plus_sound:\n    forall a : aexp, aeval (optimize_0plus a) = aeval a.\n  Proof.\n    intros a.\n    induction a.\n    - simpl.\n      reflexivity.\n    - destruct a1 eqn: E1.\n      + destruct n eqn: En.\n        * simpl.\n          rewrite IHa2.\n          reflexivity.\n        * simpl.\n          rewrite IHa2.\n          reflexivity.\n      + simpl.\n        simpl in IHa1.\n        rewrite IHa1.\n        rewrite IHa2.\n        reflexivity.\n      + simpl. \n        rewrite IHa2.\n        simpl in IHa1.\n        rewrite IHa1.\n        reflexivity.\n      + simpl.\n        rewrite IHa2.\n        simpl in IHa1.\n        rewrite IHa1.\n        reflexivity.\n    - simpl.\n      rewrite IHa1.\n      rewrite IHa2.\n      reflexivity.\n    - simpl.\n      rewrite IHa1.\n      rewrite IHa2.\n      reflexivity.\nQed.\n\n\nTheorem silly1 :\n  forall ae, aeval ae = aeval ae.\nProof.\n  try reflexivity.\nQed.\n\n\nTheorem silly2 :\n  forall (P : Prop), P -> P.\nProof.\n  intros P H.\n  try reflexivity.\n  apply H.\nQed.\n\nLemma foo : forall n, 0 <=? n = true.\nProof.\n  intros.\n  destruct n.\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nQed.\n\nLemma foo' : forall n, 0 <=? n = true.\nProof.\n  intros.\n  destruct n;\n  simpl;\n  reflexivity.\nQed.\n\nTheorem optimize_0plus_sound': forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros a.\n  induction a;\n  try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).\n  - reflexivity.\n  - destruct a1 eqn: Ea1;\n    try (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).\n    + destruct n eqn : En;\n      simpl; rewrite IHa2; reflexivity.\nQed.\n\nTheorem optimize_0plus_sound'': forall a,\n  aeval (optimize_0plus a) = aeval a.\nProof.\n  intros a.\n  induction a;\n  try (simpl; rewrite IHa1; rewrite IHa2; reflexivity).\n  try reflexivity.\n  - destruct a1;\n    try (simpl; simpl in IHa1; rewrite IHa1; rewrite IHa2; reflexivity).\n    + destruct n;\n      try (simpl; rewrite IHa2; reflexivity).\nQed.\n\n\nTheorem In10 : In 10 [1;2;3;4;5;6;7;8;9;10].\nProof.\n  repeat (try (left; reflexivity); right).\nQed.\n\n\nTheorem In10' : In 10 [1;2;3;4;5;6;7;8;9;10].\nProof.\n  (* left. *)\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  right.\n  left.\n  reflexivity.\nQed.\n\n\nTheorem In10'' : In 10 [1;2;3;4;5;6;7;8;9;10].\nProof.\n  repeat simpl.\n  repeat (left; reflexivity).\n  repeat (right; try (left; reflexivity)).\nQed.\n\n\nTheorem repeat_loop : forall (m n : nat),\n  m + n = n + m.\nProof.\n  intros m n.\n  (* repeat rewrite Nat.add_comm. *)\n  repeat (rewrite Nat.add_comm; reflexivity).\nQed.\n\n\nFixpoint optimize_0plus_b (b : bexp) : bexp :=\n  match b with\n  | BTrue => BTrue\n  | BFalse => BFalse\n  | BEq a1 a2 => BEq (optimize_0plus a1) (optimize_0plus a2)\n  | BNEq a1 a2 => BNEq (optimize_0plus a1) (optimize_0plus a2)\n  | BLe a1 a2 => BLe (optimize_0plus a1) (optimize_0plus a2)\n  | BGt a1 a2 => BGt (optimize_0plus a1) (optimize_0plus a2)\n  | BNot b => BNot (optimize_0plus_b b)\n  | BOr b1 b2 => BOr (optimize_0plus_b b1) (optimize_0plus_b b2)\n  | BAnd b1 b2 => BAnd (optimize_0plus_b b1) (optimize_0plus_b b2)\n  end.\n\nTheorem optimize_0plus_b_sound : forall b,\n  beval (optimize_0plus_b b) = beval b.\n  Proof.\n    intros b.\n    induction b;\n    simpl;\n    repeat reflexivity;\n    repeat (rewrite optimize_0plus_sound;\n            rewrite optimize_0plus_sound; reflexivity);\n    repeat (rewrite IHb; reflexivity);\n    repeat (rewrite IHb1; reflexivity).\nQed.\n\n\n(** TODO\n  Design exercise: The optimization implemented by our optimize_0plus\n  function is only one of many possible optimizations on arithmetic\n  and boolean expressions. Write a more sophisticated optimizer and\n  prove it correct. (You will probably find it easiest to start small\n  -- add just a single, simple optimization and its correctness proof\n  -- and build up incrementally to something more interesting.)\n*)\n\n\nLtac invert H := inversion H; subst; clear H.\n\n\nLemma invert_example1:\n  forall {a b c: nat}, [a ;b] = [a;c] -> b = c.\nProof.\n  intros.\n  invert H.\n  reflexivity.\nQed.\n\nLemma invert_example1':\n  forall {a b c: nat}, [a ;b] = [a;c] -> b = c.\nProof.\n  intros.\n  inversion H. subst. clear H.\n  reflexivity.\nQed.\n\nExample silly_presburger_example :\n  forall m n o p : nat, m + n <= n + O /\\ O + 3 = p + 3 -> m <= p.\nProof.\n  intros.\n  lia.\nQed.\n\n\n\nExample add_comm__lia : forall m n,\n    m + n = n + m.\nProof.\n  intros.\n  lia.\nQed.\n\nExample add_assoc__lia : forall m n p,\n    m + (n + p) = m + n + p.\nProof.\n  intros.\n  lia.\nQed.\n\n\nModule aevalR_first_try.\n\n  Inductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum (n : nat) : aevalR (ANum n) n\n  | E_APlus (e1 e2 : aexp) (n1 n2 : nat) :\n    aevalR e1 n1 -> aevalR e2 n2 -> aevalR (APlus e1 e2) (n1 + n2)\n  | E_AMinus (e1 e2 : aexp) (n1 n2 : nat) :\n    aevalR e1 n1 -> aevalR e2 n2 -> aevalR (AMinus e1 e2) (n1 - n2)\n  | E_AMult (e1 e2 : aexp) (n1 n2 : nat) :\n    aevalR e1 n1 -> aevalR e2 n2 -> aevalR (AMult e1 e2) (n1 * n2).\n\n  Module HypothesisNames.\n    Inductive aevalR : aexp -> nat -> Prop :=\n    | E_ANum (n : nat) : aevalR (ANum n) n\n    | E_APlus (e1 e2 : aexp) (n1 n2 : nat)\n      (H1 : aevalR e1 n1) (H2 : aevalR e2 n2) :\n      aevalR (APlus e1 e2) (n1 + n2)\n    | E_AMinus (e1 e2 : aexp) (n1 n2 : nat)\n      (H1 : aevalR e1 n1) (H2 : aevalR e2 n2) :\n      aevalR (AMinus e1 e2) (n1 - n2)\n    | E_AMult (e1 e2 : aexp) (n1 n2 : nat)\n      (H1 : aevalR e1 n1) (H2 : aevalR e2 n2) :\n      aevalR (AMult e1 e2) (n1 * n2).\n  End HypothesisNames.\n  \n  Notation \"e '==>' n\" :=\n    (aevalR e n)\n    (at level 90, left associativity)\n    : type_scope.\n\nEnd aevalR_first_try.\n\n\nReserved Notation \"e '==>' n\"\n  (at level 90, left associativity).\n\nInductive aevalR : aexp -> nat -> Prop :=\n  | E_ANum (n : nat) : (ANum n) ==> n\n  | E_APlus (e1 e2 : aexp) (n1 n2 : nat) :\n    (e1 ==> n1) -> (e2 ==> n2) ->\n    (APlus e1 e2) ==> (n1 + n2)\n  | E_AMinus (e1 e2 : aexp) (n1 n2 : nat) :\n    (e1 ==> n1) -> (e2 ==> n2) ->\n    (AMinus e1 e2) ==> (n1 - n2)\n  | E_AMult (e1 e2 : aexp) (n1 n2 : nat) :\n    (e1 ==> n1) -> (e2 ==> n2) ->\n    (AMult e1 e2) ==> (n1 * n2)\n  where \"e '==>' n\" := (aevalR e n) : type_scope.\n\n\n  Theorem aeval_iff_aevalR :\n    forall a n, (a ==> n) <-> aeval a = n.\n  Proof.\n    intros a n.\n    split.\n    - intros H.\n      induction H; simpl;\n      (try rewrite IHaevalR1; try rewrite IHaevalR2; reflexivity).\n    - intros H.\n      generalize dependent n.\n      induction a; simpl; intros; subst.\n      + apply E_ANum.\n      + apply E_APlus.\n        apply IHa1. reflexivity.\n        apply IHa2. reflexivity.\n      + apply E_AMinus.\n        apply IHa1. reflexivity.\n        apply IHa2. reflexivity.\n      + apply E_AMult.\n        apply IHa1. reflexivity.\n        apply IHa2. reflexivity.\n  Qed.\n  \n  Theorem aeval_iff_aevalR' :\n    forall a n, (a ==> n) <-> aeval a = n.\n  Proof.\n    split.\n    - intros H.\n      induction H; subst; reflexivity.\n    - generalize dependent n.\n      induction a; simpl; intros; subst; constructor;\n      try apply IHa1; try apply IHa2; reflexivity.\n  Qed.\n\n  Reserved Notation \"e '==>b' b\" (at level 90, left associativity).\n\n  Inductive bevalR : bexp -> bool -> Prop :=\n    | E_BTrue : BTrue ==>b true\n    | E_BFalse : BFalse ==>b false \n    | E_BEq (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) ->\n      BEq a1 a2 ==>b (n1 =? n2)\n    | E_BNeq (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) ->\n      BNEq a1 a2 ==>b negb (n1 =? n2)\n    | E_BLe (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) ->\n      BLe a1 a2 ==>b (n1 <=? n2)\n    | E_BGt (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) ->\n      BGt a1 a2 ==>b negb (n1 <=? n2)\n    | E_BNot (e : bexp) (b : bool) :\n      (e ==>b b) ->\n      BNot e ==>b negb b\n    | E_BAnd (e1 e2 : bexp) (b1 b2 : bool) :\n      (e1 ==>b b1) -> (e2 ==>b b2) ->\n      BAnd e1 e2 ==>b andb b1 b2\n    | E_BOr (e1 e2 : bexp) (b1 b2 : bool) :\n      (e1 ==>b b1) -> (e2 ==>b b2) ->\n      BOr e1 e2 ==>b orb b1 b2\n    where \"e '==>b' b\" := (bevalR e b) : type_scope.\n\n  Lemma beval_iff_bevalR :\n    forall b bv, b ==>b bv <-> beval b = bv.\n  Proof.\n  Admitted.\n\nEnd AExp.\n\n\nModule aevalR_division.\n  Inductive aexp : Type :=\n  | ANum (n : nat)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp)\n  | ADiv (a1 a2 : aexp).\n\n  Reserved Notation \"e '==>' n\"\n    (at level 90, left associativity).\n  \n    Inductive aevalR : aexp -> nat -> Prop :=\n    | E_ANum (n : nat) :\n      (ANum n) ==> n\n    | E_APlus (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) ->\n      (APlus a1 a2) ==> (n1 + n2)\n    | E_AMinus (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) ->\n      (AMinus a1 a2) ==> (n1 - n2)\n    | E_AMult (a1 a2 : aexp) (n1 n2 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) ->\n      (AMult a1 a2) ==> (n1 * n2)\n    | E_ADiv (a1 a2 : aexp) (n1 n2 n3 : nat) :\n      (a1 ==> n1) -> (a2 ==> n2) -> (n2 > 0) ->\n      (mult n2 n3 = n1) ->\n      (ADiv a1 a2) ==> n3\n    where \"e '==>' n\" := (aevalR e n) : type_scope.\nEnd aevalR_division.\n\n\nModule aevalR_extended.\n  Reserved Notation \"e '==>' n\" (at level 90, left associativity).\n\n  Inductive aexp : Type :=\n  | AAny\n  | ANum (n : nat)\n  | APlus (a1 a2 : aexp)\n  | AMinus (a1 a2 : aexp)\n  | AMult (a1 a2 : aexp).\n\n  Inductive aevalR : aexp -> nat -> Prop :=\n  | E_AAny (n : nat) :\n    AAny ==> n\n  | E_ANum (n : nat) :\n    (ANum n) ==> n\n  | E_APlus (a1 a2 : aexp) (n1 n2 : nat) :\n    (a1 ==> n1) -> (a2 ==> n2) -> \n    (APlus a1 a2) ==> (n1 + n2)\n  | E_AMinus (a1 a2 : aexp) (n1 n2 : nat) :\n    (a1 ==> n1) -> (a2 ==> n2) ->\n    (AMinus a1 a2) ==> (n1 - n2)\n  | E_AMult (a1 a2 : aexp) (n1 n2 : nat) :\n    (a1 ==> n1) -> (a2 ==> n2) ->\n    (AMult a1 a2) ==> (n2 * n2)\n  where \"e '==>' n\" := (aevalR e n) : type_scope.\n\n\nEnd aevalR_extended.\n\nDefinition state := total_map nat.\n\n\nInductive aexp : Type :=\n| ANum (n : nat)\n| AId (x : string)\n| APlus (a1 a2 : aexp)\n| AMinus (a1 a2 : aexp)\n| AMult (a1 a2 : aexp).\n\n\nDefinition W : string := \"W\".\nDefinition X : string := \"X\".\nDefinition Y : string := \"Y\".\nDefinition Z : string := \"Z\".\n\n\nInductive bexp : Type :=\n| BTrue\n| BFalse\n| BEq (a1 a2 : aexp)\n| BNEq (a1 a2 : aexp)\n| BLe (a1 a2 : aexp)\n| BGt (a1 a2 : aexp)\n| BNot (b : bexp)\n| BOr (b1 b2 : bexp)\n| BAnd (b1 b2 : bexp).\n\n\nCoercion AId : string >-> aexp.\nCoercion ANum : nat >-> aexp.\n\nDeclare Custom Entry com.\nDeclare Scope com_scope.\n\n\nNotation \"<{ e }>\" :=\n  (e)\n  (at level 0, e custom com at level 99)\n  : com_scope.\nNotation \"( x )\" :=\n  (x)\n  (in custom com, x at level 99)\n  : com_scope.\nNotation \"x\" :=\n  (x)\n  (in custom com at level 0, x constr at level 0)\n  : com_scope.\nNotation \"f x .. y\" :=\n  (.. (f x) .. y)\n  (in custom com at level 0, only parsing,\n   f constr at level 0, x constr at level 9,\n   y constr at level 9)\n  : com_scope.\nNotation \"x + y\" :=\n  (APlus x y)\n  (in custom com at level 50, left associativity).\nNotation \"x - y\" :=\n  (AMinus x y)\n  (in custom com at level 50, left associativity).\nNotation \"x * y\" :=\n  (AMult x y)\n  (in custom com at level 40, left associativity).\nNotation \"'true'\" :=\n  (true)\n  (at level 1).\nNotation \"'false'\" :=\n  (false)\n  (at level 1).\nNotation \"'true'\" :=\n  (BTrue)\n  (in custom com at level 1).\nNotation \"'false'\" :=\n  (BFalse)\n  (in custom com at level 1).\nNotation \"x <= y\" :=\n  (BLe x y)\n  (in custom com at level 70, no associativity).\nNotation \"x > y\" :=\n  (BGt x y)\n  (in custom com at level 70, no associativity).\nNotation \"x = y\" :=\n  (BEq x y)\n  (in custom com at level 70, no associativity).\nNotation \"x <> y\" :=\n  (BNEq x y)\n  (in custom com at level 70, no associativity).\nNotation \"x '&&' y\" :=\n  (BAnd x y)\n  (in custom com at level 80, left associativity).\nNotation \"x '||' y\" :=\n  (BOr x y)\n  (in custom com at level 80, left associativity).\nNotation \"'~' y\" :=\n  (BNot y)\n  (in custom com at level 75, right associativity).\n\nOpen Scope com_scope.\n\n\nDefinition example_aexp : aexp := <{ 3 + (X * 2) }>.\nDefinition example_bexp : bexp := <{ true && ~(X <= 4)}>.\n\nFixpoint aeval (st : state) (a : aexp) : nat :=\n  match a with\n  | ANum n => n\n  | AId x => st x\n  | <{a1 + a2}> => (aeval st a1) + (aeval st a2)\n  | <{a1 - a2}> => (aeval st a1) - (aeval st a2)\n  | <{a1 * a2}> => (aeval st a1) * (aeval st a2)\n  end.\n\n\nFixpoint beval (st : state) (b : bexp) : bool :=\n  match b with\n  | BTrue => true\n  | BFalse => false\n  | <{ a1 = a2}> => (aeval st a1) =? (aeval st a2)\n  | <{ a1 <> a2}> => negb ((aeval st a1) =? (aeval st a2))\n  | <{ a1 <= a2}> => (aeval st a1) <=? (aeval st a2)\n  | <{ a1 > a2}> => negb ((aeval st a1) <=? (aeval st a2))\n  | <{ ~b }> => negb (beval st b)\n  | <{b1 && b2}> => andb (beval st b1) (beval st b2)\n  | <{b1 || b2}> => orb (beval st b1) (beval st b2)\n  end.\n\n\nDefinition empty_st := (_ !-> 0).\n\n\nNotation \"x '!->' v\" := (x !-> v; empty_st) (at level 100).\n\n\nExample aexp1 :\n  aeval (X !-> 5) <{3 + (X * 2)}> = 13.\nProof.\n  reflexivity.\nQed.\n\n\nExample aexp2 :\n    aeval (X !-> 5 ; Y !-> 4) <{ Z + (X * Y) }>\n  = 20.\nProof.\n  reflexivity.\nQed.\n\n\nExample bexp1 :\n    beval (X !-> 5) <{ true && ~(X <= 4) }>\n  = true.\nProof.\n  reflexivity.\nQed.\n\n\nInductive com : Type :=\n| CSkip\n| CAsgn (x : string) (a : aexp)\n| CSeq (c1 c2 : com)\n| CIf (b : bexp) (c1 c2 : com)\n| CWhile (b : bexp) (c : com).\n\n\nNotation \"'skip'\" :=\n  (CSkip)\n  (in custom com at level 0)\n  : com_scope.\nNotation \"x ':=' y\" :=\n  (CAsgn x y)\n  (in custom com at level 0, x constr at level 0,\n   y at level 85, no associativity)\n  : com_scope.\nNotation \"x ';' y\" :=\n  (CSeq x y)\n  (in custom com at level 90, right associativity)\n  : com_scope.\nNotation \"'if' x 'then' y 'else' z 'end'\" :=\n  (CIf x y z)\n  (in custom com at level 89, x at level 99,\n   y at level 99, z at level 99)\n  : com_scope.\nNotation \"'while' x 'do' y 'end'\" :=\n  (CWhile x y)\n  (in custom com at level 89, x at level 99, y at level 99)\n  : com_scope.\n\n\nDefinition fact_in_coq : com :=\n  <{\n    Z := X;\n    Y := 1;\n    while Z <> 0 do\n      Y := Y * Z;\n      Z := Z - 1\n    end\n  }>.\n\n\nPrint fact_in_coq.\n\n\nUnset Printing Notations.\nPrint fact_in_coq.\nSet Printing Notations.\n\n\nPrint example_bexp.\nSet Printing Coercions.\nPrint example_bexp.\nPrint fact_in_coq.\nUnset Printing Coercions.\n\n\nLocate aexp.\nLocate \"&&\".\nLocate \"||\".\nLocate \";\".\nLocate \"while\".\n\n\nDefinition plus2 : com :=\n  <{ X := X + 2 }>.\n\nDefinition XtimesYinZ : com :=\n  <{ Z := X * Y }>.\n\nDefinition substract_slowly_body : com :=\n  <{\n    Z := Z - 1;\n    X := X -1\n  }>.\n\n\nDefinition substract_slowly : com :=\n  <{\n    while X <> 0 do\n      substract_slowly_body\n    end\n  }>.\n\n\nDefinition substract_3_from_5_slowly : com :=\n  <{\n    X := 3;\n    Z := 5;\n    substract_slowly\n  }>.\n\n\nDefinition loop : com :=\n  <{\n    while true do\n      skip\n    end\n  }>.\n\n\nFixpoint ceval_fun_not_while (st : state) (c : com) : state :=\n  match c with\n  | <{ skip }>\n    => st\n  | <{ x := a }>\n    => (x !-> (aeval st a); st)\n  | <{ c1 ; c2 }>\n    => let st' := ceval_fun_not_while st c1 in\n       ceval_fun_not_while st' c2\n  | <{ if b then c1 else c2 end }>\n    => if (beval st b) then ceval_fun_not_while st c1\n       else ceval_fun_not_while st c2\n  | <{ while b do c end }>\n    => st (* TODO *)\n  end.\n\n\nReserved Notation \"st '=[' c ']=>' st'\"\n  (at level 40, c custom com at level 99,\n   st constr, st' constr at next level).\n\nInductive ceval : com -> state -> state -> Prop :=\n  | E_Skip : forall st, st =[ skip ]=> st\n  | E_Asgn : forall st a n x,\n             aeval st a = n ->\n             st =[ x := a ]=> (x !-> n; st)\n  | E_Seq : forall st st' st'' c1 c2,\n             st =[ c1 ]=> st' ->\n             st' =[ c2 ]=> st'' ->\n             st =[c1 ; c2]=> st''\n  | E_IfTrue : forall st st' b c1 c2,\n             beval st b = true ->\n             st =[ c1 ]=> st' ->\n             st =[if b then c1 else c2 end]=> st'\n  | E_IfFalse : forall st st' b c1 c2,\n             beval st b = false ->\n             st =[ c2 ]=> st' ->\n             st =[if b then c1 else c2 end]=> st'\n  | E_WhileFalse : forall st b c,\n             beval st b = false ->\n             st =[while b do c end]=> st\n  | E_WhileTrue : forall st st' st'' b c,\n             beval st b = true ->\n             st =[ c ]=> st' ->\n             st' =[while b do c end]=> st'' ->\n             st =[while b do c end]=> st''\n  where \"st '=[' c ']=>' st'\" := (ceval c st st').\n\n\nExample ceval_example1 :\n  empty_st =[\n    X := 2;\n    if (X <= 1) then Y := 3\n    else Z := 4\n    end\n  ]=> (Z !-> 4; X !-> 2).\nProof.\n  apply E_Seq with (X !-> 2). (* The intermidiate state *)\n  - apply E_Asgn.\n    reflexivity.\n  - apply E_IfFalse.\n    reflexivity.\n    apply E_Asgn.\n    reflexivity.\nQed.\n\n\n\nExample ceval_example2:\n  empty_st =[\n    X := 0;\n    Y := 1;\n    Z := 2\n  ]=> (Z !-> 2 ; Y !-> 1 ; X !-> 0).\nProof.\n  apply E_Seq with (X !-> 0).\n  - apply E_Asgn.\n    reflexivity.\n  - apply E_Seq with (Y !-> 1; X !-> 0).\n    + apply E_Asgn.\n      reflexivity.\n    + apply E_Asgn.\n      reflexivity.\nQed.\n\n\nSet Printing Implicit.\nCheck @ceval_example2.\n\n\nDefinition pup_to_n : com :=\n  <{\n    Y := 0;\n    while X <> 0 do\n      Y := Y + X;\n      X := X - 1\n    end\n  }>.\n\n\nTheorem pup_to_2_ceval :\n  (X !-> 2) =[\n    pup_to_n\n  ]=> (X !-> 0 ; Y !-> 3 ; X !-> 1 ; Y !-> 2 ; Y !-> 0 ; X !-> 2).\nProof.\n  unfold pup_to_n.\n  apply E_Seq with (Y !-> 0 ; X !-> 2).\n  - apply E_Asgn.\n    reflexivity.\n  - apply E_WhileTrue with (X !-> 1 ;Y !-> 2; Y !-> 0; X !-> 2).\n    + reflexivity.\n    + apply E_Seq with (Y !-> 2; Y !-> 0; X !-> 2).\n      * apply E_Asgn.\n        reflexivity.\n      * apply E_Asgn.\n        reflexivity.\n    + apply E_WhileTrue with (X !-> 0 ;Y !-> 3 ;X !-> 1 ;Y !-> 2; Y !-> 0; X !-> 2).\n      * reflexivity.\n      * apply E_Seq with (Y !-> 3 ;X !-> 1 ;Y !-> 2; Y !-> 0; X !-> 2).\n        ** apply E_Asgn.\n           reflexivity.\n        ** apply E_Asgn.\n           reflexivity.\n      * apply E_WhileFalse.\n        reflexivity.\nQed.\n\n\nTheorem ceval_deterministic: forall c st st1 st2,\n     st =[ c ]=> st1 ->\n     st =[ c ]=> st2 ->\n     st1 = st2.\nProof.\n  intros c st st1 st2 E1 E2.\n  generalize dependent st2.\n  induction E1; intros st2 E2; inversion E2; subst.\n  - reflexivity.\n  - reflexivity.\n  - rewrite (IHE1_1 st'0 H1) in *.\n    apply IHE1_2.\n    assumption.\n  - apply IHE1.\n    assumption.\n  - apply IHE1.\n    rewrite H in H5.\n    discriminate.\n  - apply IHE1.\n    rewrite H in H5.\n    discriminate.\n  - apply IHE1.\n    apply H6.\n  - reflexivity.\n  - rewrite H in H2.\n    discriminate.\n  - rewrite H in H4.\n    discriminate.\n  - rewrite (IHE1_1 st'0 H3) in *.\n    apply IHE1_2.\n    assumption.\nQed.\n\n\nTheorem plus2_spec : forall st n st',\n  st X = n ->\n  st =[ plus2 ]=> st' ->\n  st' X = n + 2.\nProof.\n  intros.\n  inversion H0.\n  subst.\n  simpl.\n  apply t_update_eq.\nQed.\n\n\nModule StackMachine.\n  Inductive sinstr : Type :=\n  | SPush (n : nat)\n  | SLoad (x : string)\n  | SPlus\n  | SMinus\n  | SMult.\n\n\n  Fixpoint s_execute (st : state) (stack : list nat) (prog : list sinstr)\n          : list nat :=\n  match prog with\n  | [] => stack\n  | (SPush n) :: prog' => s_execute st (n :: stack) prog'\n  | (SLoad x) :: prog' => s_execute st ((st x) :: stack) prog'\n  | SPlus :: prog' => \n    let stack'' := match stack with\n    | [] => []\n    | [a] => [a]\n    | a :: b :: stack' => (a + b) :: stack'\n    end in\n    s_execute st stack'' prog'\n  | SMinus :: prog' =>\n    let stack'' := match stack with\n    | [] => []\n    | [a] => [a]\n    | a :: b :: stack' => (b - a) :: stack'\n    end in\n    s_execute st stack'' prog'\n  | SMult :: prog' => \n    let stack'' := match stack with\n    | [] => []\n    | [a] => [a]\n    | a :: b :: stack' => (a * b) :: stack'\n    end in\n    s_execute st stack'' prog'\n  end.\n\n\n  Check s_execute.\n\n\n  Example s_execute1 :\n    s_execute empty_st []\n    [SPush 5; SPush 3; SPush 1; SMinus]\n    = [2; 5].\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\n\n  Example s_execute2 :\n    s_execute (X !-> 3) [3;4]\n    [SPush 4; SLoad X; SMult; SPlus]\n    = [15; 4].\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Fixpoint s_compile (e : aexp) : list sinstr :=\n    match e with\n    | ANum n => [SPush n]\n    | AId x => [SLoad x]\n    | <{ a1 + a2}> =>\n      (s_compile a1) ++ (s_compile a2) ++ [SPlus]\n    | <{ a1 - a2 }> =>\n      (s_compile a1) ++ (s_compile a2) ++ [SMinus]\n    | <{ a1 * a2 }> =>\n      (s_compile a1) ++ (s_compile a2) ++ [SMult]\n    end.\n\n  Example s_compile1 :\n    s_compile <{ X - (2 * Y) }>\n    = [SLoad X; SPush 2; SLoad Y; SMult; SMinus].\n  Proof.\n    simpl.\n    reflexivity.\n  Qed.\n\n  Lemma s_compile_correct_aux : forall st e stack,\n    s_execute st stack (s_compile e) = aeval st e :: stack.\n  Proof.\n    intros st e.\n    induction e.\n    - simpl.\n      reflexivity.\n    - simpl.\n      reflexivity.\n    - intros stack.\n      simpl.\n  Admitted.\n\n\n  Theorem s_compile_correct : forall (st : state) (e : aexp),\n    s_execute st [] (s_compile e) = [ aeval st e ].\n  Proof.\n  Admitted.\n\nEnd StackMachine.\n\n\nModule BreakImp.\n\n  Inductive com : Type :=\n  | CSKip\n  | CBreak\n  | CAsgn (x : string) (a : aexp)\n  | CSeq (c1 c2 : com)\n  | CIf (b : bexp) (c1 c2 : com)\n  | CWhile (b : bexp) (c : com).\n\n  Notation \"'break'\" :=\n    (CBreak)\n    (in custom com at level 0)\n    : com_scope.\n  Notation \"'skip'\" :=\n    (CSkip)\n    (in custom com at level 0)\n    : com_scope.\n  Notation \"x ':=' y\" :=\n    (CAsgn x y)\n    (in custom com at level 0, x constr at level 0,\n     y at level 85, no associativity)\n    : com_scope.\n  Notation \"x ; y\" :=\n    (CSeq x y)\n    (in custom com at level 90, right associativity)\n    : com_scope.\n  Notation \"'if' x 'then' y 'else' z 'end'\" :=\n    (CIf x y z)\n    (in custom com at level 89, x at level 99,\n     y at level 99, z at level 99)\n    : com_scope.\n  Notation \"'while' x 'do' y 'end'\" :=\n    (CWhile x y)\n    (in custom com at level 89,\n     x at level 99, y at level 99)\n    : com_scope.\n  \n  Inductive result : Type :=\n  | SContinue\n  | SBreak.\n  \n  Reserved Notation \"st '=[' c ']=>' st' '/' s\"\n    (at level 40, c custom com at level 99,\n     st' constr at next level).\n  \n  Inductive ceval : com -> state -> result -> state -> Prop :=\n    | E_Skip : forall st,\n      st =[ CSKip ]=> st / SContinue\n    where \"st '=[' c ']=>' st' '/' s\" := (ceval c st s st').\n  \n  \n\nEnd BreakImp.\n\n", "meta": {"author": "tor4z", "repo": "SoftwareFoundations", "sha": "ad0d3d65d0deb4c0f1ea76b54cfb5ce2d8fcdef6", "save_path": "github-repos/coq/tor4z-SoftwareFoundations", "path": "github-repos/coq/tor4z-SoftwareFoundations/SoftwareFoundations-ad0d3d65d0deb4c0f1ea76b54cfb5ce2d8fcdef6/lf/Imp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7023539488103435}}
{"text": "From mathcomp Require Import all_ssreflect.\nRequire Import ssromega.\nRequire Import Recdef.                      (* Function *)\nRequire Import Wf_nat.                      (* wf *)\nRequire Import Program.Wf.                  (* Program wf *)\n(* Import Program とすると、リストなど余計なものがついてくるので、Wfだけにする。 *)\n\nRequire Import Extraction.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n(* Set Print All. *)\n\n(**\n# 連分数 Continued fraction\n\n有限単純連分数 または 有限正則連分数 (finite regular continued fraction)\nこれは、分子が全て 1 の連分数で、有限回で表現できるもの。有理数を表す。\n\nまた、ここでは、正数のみ考えるが、1以上であってもよい。\n *)\nSection CF.\n\n(**\n## （正の）有理数と有限正則連分数 の相互変換\n\n-（正の）有理数は、自然数のpairで表現する。既約である必要はない。\n- 有限正則連分数は、自然数のリストで表現する。\n*)\n\n(**\n### 正則連分数から有理数\n\n得られた有理数は、結果として既約になる。ただし証明が必要。\n*)  \n  Fixpoint cf2f (sa : seq nat)  : (nat * nat) :=\n    match sa with\n    | a :: sa' =>\n      (a * (cf2f sa').1 + (cf2f sa').2, (cf2f sa').1)\n    (* let (p1, p2) := cf2f sa' in (a * p1 + p2, p1) *)\n    | [::] => (1, 0)\n    end.\n\n  Compute cf2f [:: 3; 3; 1; 2].             (* (36, 11) *)\n  Compute cf2f [:: 0; 1; 1; 1; 1; 1; 1].\n  Compute cf2f [:: 1; 2; 2; 2; 2; 2; 2].  \n  \n(**\n### 有理数から正則連分数\n*)\n  Program Fixpoint f2cf'p (n d : nat) {wf lt d} : (seq nat) := (* notu *)\n    match d with\n    | 0 => [::]\n    | _ => (n %/ d) :: f2cf'p d (n %% d)\n    end.\n  Obligation 1.\n  Proof.\n    apply/ltP/ltn_pmod.\n    move/Lt.neq_0_lt in H.\n    apply/ltP/H.\n  Qed.\n  Compute f2cf'p 36 11.                     (* [:: 3; 3; 1; 2] *)\n  \n  Function f2cf' (n d : nat) {wf lt d} : (seq nat) :=\n    match d with\n    | 0 => [::]\n    | _ => (n %/ d) :: f2cf' d (n %% d)\n    end.\n  Proof.\n    - move=> n d d0 _.\n      apply/ltP.\n        by rewrite ltn_mod.\n    - by apply: lt_wf.\n  Defined.                                (* Defined が必要である。 *)\n(**\n- Coq は停止性が判定できないので、Function コマンドを使う。\n第2引数（分母側）が、割り算の余りを求めることによって小さくなることを示す。\n\n- Function コマンドにより、カスタムインダクションが可能になる\n(functional inducntion タクティクが使えるようになる）。\n\n- Function コマンドにより、不動点を示す等式 f2cf'_equation が定義される。\n *)\n  \n  Definition f2cf (p : (nat * nat)) : (seq nat) := f2cf' p.1 p.2.\n  Compute f2cf (36, 11).                    (* = [:: 3; 3; 1; 2] *)\n  \n  Compute cf2f (f2cf (36, 11)).             (* (36, 11) *)\n  Compute cf2f (f2cf (72, 22)).             (* (36, 11) *)\n  \n\n(**\n## 有理数→正則連分数→有理数 の変換\n*)\n  Goal forall p, cf2f (f2cf p) = p.\n  Proof.\n    case=> n d.\n    functional induction (f2cf' n d).\n    - rewrite /=.\n      (* (1, 0) = (n, 0) .... p は既約になるので。 *)\n      admit.\n    - case: d y IHl => [H IHl | d H IHl].\n      + done.\n      + admit.\n(**\n  IHl : cf2f (f2cf (d.+1, n %% d.+1)) = (d.+1, n %% d.+1)\n  ============================\n  cf2f (f2cf (n, d.+1)) = (n, d.+1)\n *)\n  Admitted.                                 (* OK *)\n\n(**\n## 正則連分数→有理数→正則連分数 の変換\n\ncf2f (f2cf p) = p は証明できない（pが約分される）ので、\nf2cf (cf2f s) = s を証明する。\n*)  \n  Lemma f2cfE (n d : nat) : d != 0 -> f2cf' n d = (n %/ d) :: f2cf' d (n %% d).\n  Proof.\n    case: d => //= n' Hd.\n      by apply: f2cf'_equation.\n  Qed.\n  \n  Lemma div_d__n n d r : 0 < d -> r < d -> (n * d + r) %/ d = n.\n  Proof.\n    move=> Hd Hrd.\n    rewrite divnMDl; last done.\n    rewrite divn_small; last done.\n      by rewrite addn0.\n  Qed.\n  \n  Lemma mod_d__r n d r : r < d -> (n * d + r) %% d = r.\n  Proof.\n    move=> Hrd.\n    Check modnMDl.                     (* (p * d + m) %% d = m %% d *)\n    rewrite modnMDl.\n    rewrite modn_small; last done.\n    done.\n  Qed.\n  \n  Goal forall s, f2cf (cf2f s) = s.\n  Proof.\n    elim => // n s IHs /=.\n    rewrite /f2cf /=.\n    - rewrite f2cfE /=.\n      + rewrite div_d__n.\n        * rewrite mod_d__r.\n          -- rewrite /f2cf in IHs.\n               by rewrite IHs.\n          -- admit.                      (* (cf2f s).2 < (cf2f s).1 *)\n        * admit.                         (* 0 < (cf2f s).1 *)\n        * admit.                         (* (cf2f s).2 < (cf2f s).1 *)\n    - admit.                             (* (cf2f s).1 != 0 *)  \n  Admitted.\n  \nEnd CF.\n\n(**\n# continuant polynomial\n\n文献[1] では Gauss が定義してものとして、H(・) と表記されている。\nリストの前に追加する。consによる定義。\n\n文献[2] では、Eulerが研究したものとして、 K(・) と表記されている。\nリストの後に追加する。rconsによる定義。\n *)\nSection CP.\n\n(**\n## Gauss の H関数\n\n### Gauss の H関数の定義\n\n```\nH() = 1\nH(x_1) = x_1\nH(x_1 ... x_n) = x_1 * K(x_2 ... x_n) + K(x_3 ... x_n)\n```\n*)\n  Program Fixpoint GaussHp (s : seq nat) {measure (size s)} : nat := (* notu *)\n    match s with\n    | [::] => 1\n    | [:: n] => n\n    | n0 :: n1 :: s' => n0 * GaussHp (n1 :: s') + GaussHp s'\n    end.\n  Obligation 2.\n  Proof.\n    apply/ltP => //=.\n  Qed.\n\n  Function GaussH (s : seq nat) {measure size s} : nat :=\n    match s with\n    | [::] => 1\n    | [:: n] => n\n    | n0 :: n1 :: s' => n0 * GaussH (n1 :: s') + GaussH s'\n    end.\n  Proof.\n    - move=> s n0 l n1 s' H1 H2.\n      apply/ltP => /=.\n        by ssromega.\n    - move=> s n0 l n1 s' H1 H2.\n      apply/ltP => /=.\n        by ssromega.\n  Defined.\n  \n  Compute GaussH [:: 3; 3; 1; 2].           (* 36 *)\n  Compute GaussH [:: 3; 1; 2].              (* 11 *)\n  Compute cf2f [:: 3; 3; 1; 2].             (* (36, 11) *)\n  \n(**\n### 連分数とcontinuant\n\n有限正則連分数 s が、有理数 ``n / d`` を示すとする。\n\n- H(s)は、有理数の分子 n である。\n- H(behead s)は、有理数の分母 d である。\n\n```n / d = H(x1 x2 x3 ... ) / H(x2 x3 ...) = [x1; x2, x3 ...]```\nのように表される（文献 [3]）。\n*)\n  Lemma cf2fE n0 n1 s :\n    (cf2f [:: n0, n1 & s]).1 = n0 * (cf2f (n1 :: s)).1 + (cf2f s).1.\n  Proof. done. Qed.\n  \n  Lemma num_GaussH s : (cf2f s).1 = GaussH s.\n  Proof.\n    functional induction (GaussH s) => //.\n    - by rewrite /cf2f muln1 addn0.\n    - rewrite -IHn -IHn0.\n      rewrite -cf2fE.\n      done.\n  Qed.\n  \n  Lemma den_GaussH n s : (cf2f (n :: s)).2 = GaussH s.\n  Proof.\n    functional induction (GaussH s) => //.\n    - by rewrite /cf2f muln1 addn0.\n    - rewrite -IHn0 -IHn1.\n      rewrite -cf2fE.\n      done.\n  Qed.\n  \n(**\n### continuant の性質\n*)\n\n  Compute GaussH [:: 1;2;3;4;5].                       (* 225 *)\n  Compute GaussH [:: 5;4;3;2;1].                       (* 225 *)\n  Compute 5 * GaussH [:: 1;2;3;4] + GaussH [:: 1;2;3]. (* 225 *)\n\n  Compute (GaussH [:: 1;2;3] * GaussH [:: 4;5]) + (GaussH [:: 1;2] * GaussH [:: 5]).\n  (* 225 *)\n\n  Lemma GaussH1 : GaussH [::] = 1.\n  Proof. done. Qed.\n\n  Lemma GaussHn n : GaussH [:: n] = n.\n  Proof. done. Qed.\n  \n  Lemma GaussHE (n0 n1 : nat) (s : seq nat) :\n    GaussH (n0 :: n1 :: s) = n0 * GaussH (n1 :: s) + GaussH s.\n  Proof.\n    by rewrite GaussH_equation.\n  Qed.\n  \n  Lemma GaussHEr (n0 n1 : nat) (s : seq nat) :\n    GaussH (rcons (rcons s n1) n0) = n0 * GaussH (rcons s n1) + GaussH s.\n  Proof.\n    functional induction (GaussH s).\n    - rewrite GaussHE /GaussH /=.\n      by rewrite mulnC.\n    - rewrite GaussHE /GaussH /=.\n    (* n * (n1 * n0 + 1) + n0 = n0 * (n * n1 + 1) + n *)\n      rewrite !mulnDr !mulnA !muln1.\n      rewrite ?addnA addnAC.                (* n を最後に。 *)\n      rewrite ?mulnA mulnAC.                (* n1 を最後に。 *)\n      rewrite -?mulnA mulnCA.               (* n0 を最初に。 *)\n      done.\n    - rewrite /=.\n      rewrite GaussHE IHn0 /=.\n      rewrite GaussHE IHn /=.\n      rewrite !mulnDr.\n      rewrite ?addnA.\n      rewrite [n2 * (n0 * GaussH (n3 :: rcons s' n1))]mulnCA.\n        by ssromega.\n  Qed.\n  \n  Lemma GaussH__GaussH_rev s : GaussH s = GaussH (rev s).\n  Proof.\n    functional induction (GaussH s) => //.\n    rewrite !rev_cons.\n    rewrite GaussHEr.\n    rewrite -rev_cons.\n    rewrite IHn IHn0.\n    done.\n  Qed.\n\n(**\n## Euler の K関数\n\n### Euler の K関数の定義\n\n```\nK() = 1\nK(x_1) = x_1\nK(x_1 ... x_n) = K(x_1 ... x_n-1) * x_n + K(x_1 ... x_n-2)\n```\n*)\n\n(*\n  Fixpoint tail (s : seq nat) : nat :=\n    match s with\n    | [::] => 0\n    | [:: a] => a\n    | a :: s => tail s\n    end.\n  \n  Fixpoint body (s : seq nat) : seq nat :=\n    match s with\n    | [::] => [::]\n    | [:: a] => [::]\n    | a :: s => a :: body s\n    end.\n *)\n  Definition tail (s : seq nat) : nat := head 0 (rev s).\n  Compute tail [:: 1; 2; 3].                (* 3 *)\n\n  Definition body (s : seq nat) : seq nat := rev (drop 1 (rev s)).\n  Compute body [:: 1; 2; 3].                (* [:: 1; 2] *)\n  \n  Lemma tail_rcons s n : tail (rcons s n) = n.\n  Proof.\n      by rewrite /tail rev_rcons.\n  Qed.\n  \n  Lemma body_rcons s n : body (rcons s n) = s.\n  Proof.\n      by rewrite /body rev_rcons /= drop0 revK.\n  Qed.\n  \n  Lemma size_body_1 s : 1 <= size s -> size (body s) < size s.\n  Proof.\n    case/lastP : s => // s n Hs.\n    rewrite body_rcons size_rcons.\n    done.\n  Qed.\n  \n  Lemma size_body_21 s : 2 <= size s -> size (body (body s)) < size (body s).\n  Proof.\n    case/lastP : s => // s n Hs.\n    rewrite body_rcons.\n    apply: size_body_1.\n    rewrite size_rcons in Hs.\n      by ssromega.\n  Qed.\n  \n  Lemma size_body_2 s : 2 <= size s -> size (body (body s)) < size s.\n  Proof.\n    move=> Hs.\n    Check @ltn_trans (size (body s)) (size (body (body s))) (size s).\n    apply: (@ltn_trans (size (body s)) (size (body (body s))) (size s)).\n    - by apply: (@size_body_21 s).\n    - apply: size_body_1.\n        by ssromega.\n  Qed.\n  \n  Lemma tail_rev n s : tail (rev (n :: s)) = n.\n  Proof.\n    rewrite rev_cons.\n      by rewrite tail_rcons.\n  Qed.\n  \n  Lemma body_rev n s : body (rev (n :: s)) = rev s.\n  Proof.\n    rewrite rev_cons.\n      by rewrite body_rcons.\n  Qed.\n  \n  Function EulerK (s : seq nat) {measure size s} : nat :=\n    match s with\n    | [::] => 1\n    | [:: n] => n\n    | _ => tail s * EulerK (body s) + EulerK (body (body s))\n    end.\n  - move=> s n s' n' s'' H1 H2.\n    apply/ltP.\n    Check @size_body_2 [:: n, n' & s''].\n    apply: (@size_body_2 [:: n, n' & s'']).\n    done.\n  - move=> s n s' n' s'' H1 H2.\n    apply/ltP.\n    Check @size_body_1 [:: n, n' & s''].\n    apply: (@size_body_1 [:: n, n' & s'']).\n    done.\n  Defined.\n  \n  Compute EulerK  [:: 3; 3; 1; 2].          (* 36 *)\n  Compute EulerK  [:: 3; 1; 2].             (* 11 *)\n\n(**\n### EulerK と GaussH が同じ\n*)  \n  Lemma EulerKE s :\n    2 <= size s ->\n    EulerK s = tail s * EulerK (body s) + EulerK (body (body s)).\n  Proof.\n    case: s => //= n0 s.\n    case: s.\n    + done.\n    + move=> n1 s Hs.\n        by rewrite EulerK_equation.\n  Qed.\n  \n  Lemma EulerK_rev__GaussH s : EulerK (rev s) = GaussH s.\n  Proof.\n    functional induction (GaussH s) => [//= | //= |].\n    rewrite EulerKE.\n    - rewrite tail_rev 2!body_rev.\n      rewrite IHn -IHn0.\n      done.\n    - rewrite size_rev.\n      done.\n  Qed.\n  \n  Lemma EulerK_GaussH s : EulerK s = GaussH s.\n  Proof.\n    rewrite -(revK s).\n    rewrite EulerK_rev__GaussH GaussH__GaussH_rev.\n    rewrite revK.\n    done.\n  Qed.\n  \n(**\n# 連分数とフィボナッチ数（と黄金数）\n\n```n/d = (a2 / a1) = 3/2 = H(1, 1, 1) / H(1, 1) = [1; 1, 1] = (fib 4 / fib 3)```\n\n``(a_n / a_n-1) = [1をn個] = H(1をn個)/H(1をn-1個) = (fib n+1 / fib n)```\n\n文献[4]。このことから、1をn個の連分数は、``fib n.+1`` に等しい。\n\n- H(1; 1; 1) = fib 4\n- H(nseq n 1) = fib n.+1\n*)\n  Compute GaussH [::].                      (*      1 = fib 1 *)\n  Compute GaussH [:: 1].                    (* a0 = 1 = fib 2 *)\n  Compute GaussH [:: 1; 1].                 (* a1 = 2 = fib 3 *)\n  Compute GaussH [:: 1; 1; 1].              (* a2 = 3 = fib 4 *)\n  Compute GaussH (nseq 3 1).\n\n  Function fib (n : nat) : nat :=\n    match n with\n    | 0 => 0\n    | 1 => 1\n    | (m.+1 as pn).+1 => fib m + fib pn (* fib n.-2 + fib n.-1 *)\n    end.\n  \n  Lemma fibE n : fib n.+2 = fib n + fib n.+1.\n  Proof. done. Qed.\n  \n  Lemma GaussH_fib n : GaussH (nseq n 1) = fib n.+1.\n  Proof.\n    functional induction (fib n) => [//= | //= |].\n    rewrite fibE -IHn0 -IHn1.\n    rewrite [nseq _.+2 1]/=.\n    rewrite GaussHE mul1n.\n    rewrite [nseq _.+1 1]/=.\n      by rewrite addnC.\n  Qed.\n  \n(**\n（参考）フィボナッチ数列の隣接2項の商は、黄金数φに収束する。  \n*)\n\nEnd CP.\n\n(**\n# 文献\n\n[1] 有澤健治、平方根の連分数とペル方程式, 第1章\nhttps://leo.aichi-u.ac.jp/~keisoken/research/books/book51/book51.pdf\n\n\n[2] Ronald L. Graham, Donald E. Knuth, Oren Patashnik, Concrete Mathematics,\n6.7 CONTINUANTS\n\n\n[3] Wikipedia, Continuant (mathematics), \nhttps://en.wikipedia.org/wiki/Continuant_(mathematics)\nProperties 「Ratios of continuants represent (convergents to) \ncontinued fractions as follows:」\n\n[4] Wikipedia, 連分数\nhttps://ja.wikipedia.org/wiki/連分数\n連分数の性質「なお数列an が全て 1 の場合、数列pn, qn はともにフィボナッチ数列 \n(F0 = 0, F1 = 1) である」\n *)\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/math/ssr_cont_fract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7023539381818327}}
{"text": "(* See github.com/andrejbaur for more details on getting started. *)\n\nDefinition P (A : Type) := A -> Prop.\n\nNotation \"{ x : A | P }\" := (fun x : A => P).\n\nDefinition singleton {A : Type} (x : A) := {y:A | x = y}.\n\nDefinition subset {A : Type} (u v : P A) :=\n  forall x : A, u x -> v x.\n\nNotation \"u <= v\" := (subset u v).\n\nDefinition disjoint {A : Type} (u v : P A) :=\n  forall x, ~(u x /\\ v x).\n\nNotation \"'all' x : U , P\" := (forall x, U x -> P) (at level 20, x at level 99).\n\nNotation \"'some' x : U , P\" := (exists x, U x /\\ P) (at level 20, x at level 99).\n\nDefinition union {A : Type} (S : P (P A)) :=\n  {x : A | some U : S, U x }.\n\nDefinition inter {A : Type} (u v : P A) :=\n  {x : A | u x /\\ v x}.\n\nNotation \"u * v\" := (inter u v).\n\nDefinition empty {A : Type} := { x : A | False}.\nDefinition full {A : Type} := { x : A | True}.\n\nStructure topology (A : Type) :=\n  {\n    open :> P A -> Prop ;\n    empty_open : open empty ;\n    full_open : open full;\n    inter_open : all u : open, all v :open, open (u * v);\n    union_open : forall S, S<= open -> open (union S)\n  }.\n\nDefinition discrete (A : Type) : topology A.\nProof.\n  exists full ; firstorder.\nDefined.\n\nDefinition T1 {A : Type} (T : topology A) :=\n  forall x y : A,\n    x <> y ->\n    some u : T, (u x /\\ ~(u y)).\n\nDefinition hausdorff {A : Type} (T : topology A) :=\n  forall x y : A,\n    x <> y ->\n    some u : T, some v : T,\n  (u x /\\ v y /\\ disjoint u v).\n\nLemma discrete_hausdorff {A : Type} : hausdorff (discrete A).\nProof.\n  intros x y N.\n  exists { z : A | x = z}; split ; [exact I | idtac].\n  exists { z : A | y = z}; split ; [exact I | idtac].\n  repeat split ; auto.\n  intros z [? ?].\n  absurd (x = y); auto.\n  transitivity z ; auto.\nQed.\n\nLemma hausdorff_is_T1 {A : Type} (T : topology A):\n  hausdorff T -> T1 T.\nProof.\n  intros H x y N.\n  destruct (H x y N) as [u [? [v [? [? [? G]]]]]].\n  exists u ; repeat split ; auto.\n  intro.\n  absurd (u y /\\ v y); auto.\nQed.\n\nDefinition indiscrete (A : Type) : topology A.\nProof.\n  exists { u : P A | forall x : A, u x -> (forall y : A, u y) }; firstorder.\nDefined.\n\nLemma indiscrete_least (A : Type) (T : topology A) :\n  (forall (X : Type) (s t : P X), s <= t -> t <= s -> s = t) ->\n  indiscrete A <= T.\nProof.\n  intros ext u H.\n  assert (G : (u = union { v : P A | T v /\\ some x : v, u x })).\n  - apply ext.\n    + intros x ?. exists full; firstorder using full_open.\n    + intros x [v [[? [y [? ?]]] ?]] ; now apply (H y).\n  - rewrite G ; apply union_open ; firstorder.\nQed.\n\nDefinition particular {A : Type} (x : A) : topology A.\nProof.\n  exists { u : P A | (exists y, u y) -> u x } ; firstorder.\nQed.\n\n(* the topology generated by a family B of subsets that are \n   closed under finite intersections. *)\nDefinition base {A : Type} (B : P (P A)) :\n  B full -> (all u : B, all v : B, B (u * v)) -> topology A.\nProof.\n  intros H G.\n  exists { u : P A | forall x, u x <-> some v : B, (v x /\\ v <= u) }.\n  - firstorder.\n  - firstorder.\n  - intros u Hu v Hv x.\n    split.\n    + intros [Gu Gv].\n      destruct (proj1 (Hu x) Gu) as [u' [? [? ?]]].\n      destruct (proj1 (Hv x) Gv) as [v' [? [? ?]]].\n      exists (u' * v') ; firstorder.\n    + intros [w [? [? ?]]].\n      split ; now apply H2.\n  - intros S K x.\n    split.\n    + intros [u [H1 H2]].\n      destruct (K u H1 x) as [L1 _].\n      destruct (L1 H2) as [v ?].\n      exists v; firstorder.\n    + firstorder.\nDefined.\n\nRequire Import List.\n\n(* The intersection of a finite list of subsets. *)\nDefinition inters {A : Type} (us : list (P A)) : P A :=\n  {x : A | Forall (fun u => u x) us }.\n\n(* The closure of a family of sets by finite intersections. *)\nDefinition inter_close {A : Type} (S : P (P A)) :=\n  { v : P A | some us : Forall S, (forall x, v x <-> inters us x) }.\n\nLemma Forall_app {A : Type} (l1 l2 : list A) (P : A -> Prop):\n  Forall P l1 -> Forall P l2 -> Forall P (l1 ++ l2).\nProof.\n  induction l1 ; simpl ; auto.\n  intro H.\n  inversion H; auto.\nQed.\n\nLemma Forall_app1 {A : Type} (l1 l2 : list A) (P : A -> Prop) :\n  Forall P (l1 ++ l2) -> Forall P l1.\nProof.\n  induction l1; simpl ; auto.\n  intro H.\n  inversion H; auto.\nQed.\n\nLemma Forall_app2 {A : Type} (l1 l2 : list A) (P : A -> Prop):\n  Forall P (l1 ++ l2) -> Forall P l2.\nProof.\n  induction l1; simpl ; auto.\n  intros H.\n  inversion H; auto.\nQed.\n\n(* The topology generated by a subbase S. *)\nDefinition subbase {A : Type} (S : P (P A)) : topology A.\nProof.\n  apply (base (inter_close S)).\n  - exists nil ; firstorder using Forall_nil.\n  - intros u [us [Hu Gu]] v [vs [Hv Gv]].\n    exists (us ++ vs).\n    split ; [ (now apply Forall_app) | idtac ].\n    split.\n    + intros [? ?].\n      apply Forall_app ; firstorder.\n    + intro K; split.\n      * apply Gu.\n        apply (Forall_app1 _ _ _ K).\n      * apply Gv.\n        apply (Forall_app2 _ _ _ K).\nDefined.\n\nLemma subbase_open {A : Type} (S : P (P A)) (u : P A) :\n  S u -> (subbase S) u.\nProof.\n  intros H x.\n  split.\n  - intro G.\n    exists u ; split ; [ idtac | firstorder ].\n    exists (u :: nil).\n    split ; [now constructor | idtac].\n    intro y; split.\n    + intro ; now constructor.\n    + intro K.\n      inversion K; auto.\n  - firstorder.\nQed.\n\nDefinition cofinite (A: Type) : topology A :=\n  subbase { u : P A | exists x, forall y, (u y <-> y <> x) }.\n\nLemma cofinite_T1 (A : Type) : T1 (cofinite A).\nProof.\n  intros x y N.\n  exists {z : A | z<>y}.\n  split ; auto.\n  apply subbase_open.\n  exists y; firstorder.\nQed.\n\n", "meta": {"author": "ihasson", "repo": "coq", "sha": "0da545a4966f48b1874183812f61f54eac7b1976", "save_path": "github-repos/coq/ihasson-coq", "path": "github-repos/coq/ihasson-coq/coq-0da545a4966f48b1874183812f61f54eac7b1976/topology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7023539372173373}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (lf3 : natural) (lf2 : natural) : natural :=\n  plus (plus z lf3) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_99_plus_assoc/goal33conj162_coqofml_SCk1ol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7023058137913962}}
{"text": "Require Import Init Nat.\n\nModule sets.\n Fixpoint ninl (n : nat) (a : list nat) : bool :=\n  match a with\n  | nil => true\n  | cons x a' =>\n   match eqb n x with\n   | false => ninl n a'\n   | true => false\n   end\n  end\n .\n\n Fixpoint uniques (a : list nat) : bool :=\n  match a with\n  | nil => true\n  | cons x a' =>\n   match ninl x a' with\n   | false => false\n   | true => uniques a'\n   end\n  end\n .\n\n Definition set := { x : list nat | eq_true (uniques x) }.\n\n Definition add_uniques (n : nat) (s : list nat) (p : eq_true (uniques s)) (q : eq_true (ninl n s))\n     : eq_true (uniques (cons n s)).\n Proof.\n  unfold uniques.\n  fold (uniques s).\n  destruct (ninl n s).\n  -\n   apply p.\n  -\n   apply q.\n Defined.\n\n Definition if_eq_true {r : Type} (b : bool) (t : eq_true b -> r) (f : r) : r.\n Proof.\n  destruct b.\n  -\n   apply t.\n   apply is_eq_true.\n  -\n   apply f.\n Defined.\n\n Definition add (n : nat) (s : set) : set :=\n  match s with\n  | exist _ s' p =>\n   if_eq_true (ninl n s')\n    (fun q => exist _ (cons n s') (add_uniques n s' p q))\n    (exist _ s' p)\n  end\n .\nEnd sets.\n\nExtraction Language Haskell.\n\nExtraction sets.\n", "meta": {"author": "Hexirp", "repo": "coq-gist", "sha": "ee215045eaf99febb40fca953c3d1ba75a4d1d36", "save_path": "github-repos/coq/Hexirp-coq-gist", "path": "github-repos/coq/Hexirp-coq-gist/coq-gist-ee215045eaf99febb40fca953c3d1ba75a4d1d36/set.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7023058053670489}}
{"text": "Require Export MetricSpaces.\nRequire Import Psatz.\nFrom Coq Require Import ProofIrrelevance.\n\nSection Completeness.\n\nVariable X:Type.\nVariable d:X->X->R.\nHypothesis d_metric: metric d.\n\nDefinition cauchy (x:nat->X) : Prop :=\n  forall eps:R, eps > 0 -> exists N:nat, forall m n:nat,\n    (m >= N)%nat -> (n >= N)%nat -> d (x m) (x n) < eps.\n\nLemma convergent_sequence_is_cauchy:\n  forall (x:Net nat_DS (MetricTopology d d_metric))\n    (x0:point_set (MetricTopology d d_metric)),\n  net_limit x x0 -> cauchy x.\nProof.\nintros.\ndestruct (MetricTopology_metrized X d d_metric x0).\nred; intros.\ndestruct (H (open_ball d x0 (eps/2))) as [N].\n- Opaque In. apply open_neighborhood_basis_elements. Transparent In.\n  constructor.\n  lra.\n- constructor.\n  rewrite metric_zero; trivial.\n  lra.\n- simpl in N.\n  exists N.\n  intros.\n  destruct (H1 m H2).\n  destruct (H1 n H3).\n  apply Rle_lt_trans with (d x0 (x m) + d x0 (x n)).\n  + rewrite (metric_sym _ _ d_metric x0 (x m)); trivial.\n    now apply triangle_inequality.\n  + lra.\nQed.\n\nLemma cauchy_sequence_with_cluster_point_converges:\n  forall (x:Net nat_DS (MetricTopology d d_metric))\n    (x0:point_set (MetricTopology d d_metric)),\n  cauchy x -> net_cluster_point x x0 -> net_limit x x0.\nProof.\nintros.\napply metric_space_net_limit with d.\n- apply MetricTopology_metrized.\n- intros.\n  red; intros.\n  destruct (H (eps/2)) as [N].\n  + lra.\n  + pose (U := open_ball d x0 (eps/2)).\n    assert (open_neighborhood U x0 (X:=MetricTopology d d_metric)).\n  { apply MetricTopology_metrized.\n    constructor.\n    lra. }\n    destruct H3.\n    destruct (H0 U H3 H4 N) as [m [? []]].\n    simpl in H5.\n    exists N; intros n ?.\n    simpl in H7.\n    apply Rle_lt_trans with (d x0 (x m) + d (x m) (x n)).\n    * now apply triangle_inequality.\n    * cut (d (x m) (x n) < eps/2).\n      ** lra.\n      ** now apply H2.\nQed.\n\nDefinition complete : Prop :=\n  forall x:nat->X, cauchy x ->\n    exists x0:X, net_limit x x0 (I:=nat_DS)\n      (X:=MetricTopology d d_metric).\n\nEnd Completeness.\n\nArguments cauchy {X}.\nArguments complete {X}.\n\nSection closed_subset_of_complete.\n\nVariable X:Type.\nVariable d:X->X->R.\nHypothesis d_metric:metric d.\nVariable F:Ensemble X.\n\nLet FT := { x:X | In F x }.\nLet d_restriction := fun x y:FT => d (proj1_sig x) (proj1_sig y).\n\nLemma d_restriction_metric: metric d_restriction.\nProof.\nconstructor; intros; try destruct x; try destruct y; try destruct z;\n  try apply subset_eq_compat; apply d_metric; trivial.\nQed.\n\nLemma closed_subset_of_complete_is_complete:\n  complete d d_metric ->\n  closed F (X:=MetricTopology d d_metric) ->\n  complete d_restriction d_restriction_metric.\nProof.\nintros.\nred; intros.\npose (y := fun n:nat => proj1_sig (x n)).\ndestruct (H y) as [y0].\n- red; intros.\n  destruct (H1 eps H2) as [N].\n  now exists N.\n- intros.\n  assert (In F y0).\n{ rewrite <- (closure_fixes_closed _ H0); trivial.\n  apply @net_limit_in_closure with (I:=nat_DS) (x:=y); trivial.\n  red; intros.\n  exists i; split.\n  - apply le_refl.\n  - unfold y.\n    destruct (x i); trivial. }\n  exists (exist _ y0 H3).\n  apply metric_space_net_limit with d_restriction.\n  + apply MetricTopology_metrized.\n  + intros.\n    unfold d_restriction; simpl.\n    apply metric_space_net_limit_converse with\n      (MetricTopology d d_metric); trivial.\n    apply MetricTopology_metrized.\nQed.\n\nLemma complete_subset_is_closed:\n  complete d_restriction d_restriction_metric ->\n  closed F (X:=MetricTopology d d_metric).\nProof.\nintros.\ncut (Included (closure F (X:=MetricTopology d d_metric)) F).\n- intros.\n  assert (closure F (X:=MetricTopology d d_metric) = F).\n{ apply Extensionality_Ensembles.\n  split; trivial; apply closure_inflationary. }\n  rewrite <- H1; apply closure_closed.\n- red; intros.\n  assert (exists y:Net nat_DS (MetricTopology d d_metric),\n    (forall n:nat, In F (y n)) /\\ net_limit y x).\n{ apply first_countable_sequence_closure; trivial.\n  apply metrizable_impl_first_countable.\n  exists d; trivial; apply MetricTopology_metrized. }\n  destruct H1 as [y []].\n  pose (y' := ((fun n:nat => exist _ (y n) (H1 n)) :\n               Net nat_DS (MetricTopology d_restriction d_restriction_metric))).\n  assert (cauchy d y).\n{ apply convergent_sequence_is_cauchy with d_metric x; trivial. }\n  assert (cauchy d_restriction y').\n{ red; intros.\n  destruct (H3 eps H4) as [N].\n  exists N; intros.\n  unfold d_restriction; unfold y'; simpl.\n  now apply H5. }\n  destruct (H _ H4) as [[x0]].\n  cut (net_limit y x0 (I:=nat_DS) (X:=MetricTopology d d_metric)).\n  + intros.\n    assert (x = x0).\n  { assert (uniqueness (net_limit y (I:=nat_DS)\n                            (X:=MetricTopology d d_metric))).\n  { apply Hausdorff_impl_net_limit_unique.\n    apply T3_sep_impl_Hausdorff.\n    apply normal_sep_impl_T3_sep.\n    apply metrizable_impl_normal_sep.\n    exists d; trivial.\n    apply MetricTopology_metrized. }\n    now apply H7. }\n    now rewrite H7.\n  + apply metric_space_net_limit with d.\n    * apply MetricTopology_metrized.\n    * exact (metric_space_net_limit_converse\n        (MetricTopology d_restriction d_restriction_metric)\n        d_restriction (MetricTopology_metrized _ d_restriction\n                             d_restriction_metric)\n        nat_DS y' (exist _ x0 i) H5).\nQed.\n\nEnd closed_subset_of_complete.\n", "meta": {"author": "coq-community", "repo": "topology", "sha": "f784257d0b9c316601440e4f02256bd6068e4f94", "save_path": "github-repos/coq/coq-community-topology", "path": "github-repos/coq/coq-community-topology/topology-f784257d0b9c316601440e4f02256bd6068e4f94/theories/Topology/Completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.7023058052446475}}
{"text": "Require Import mathcomp.ssreflect.all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Bullet Behavior \"Strict Subproofs\".\n\nInductive Fibonacci : nat -> nat -> Prop :=\n  | Fib1 : Fibonacci 1 1\n  | Fib2 : Fibonacci 1 2\n  | FibPlus : forall val_1 val_2 seq, Fibonacci val_1 seq -> Fibonacci val_2 (seq + 1) -> Fibonacci (val_1 + val_2) (seq + 2).\nHint Constructors Fibonacci.\n\nDefinition f3 : Fibonacci 2 3 := FibPlus Fib1 Fib2.\n\nDefinition f4 : Fibonacci 3 4.\n  exact (FibPlus Fib2 f3).\nQed.\n\nPrint f4.\n\nDefinition f6 : Fibonacci 8 6.\n  cut (Fibonacci 5 5).\n  move=> f5.\n  exact (FibPlus f4 f5).\n  exact (FibPlus f3 f4).\nQed.\n\nPrint f6.\n\nLemma weird :\n  Fibonacci 7 18 ->\n  Fibonacci 8 19 ->\n  Fibonacci 15 20.\n  intros.\n  exact (FibPlus H H0).\nQed.\n\n\nRequire Import Coq.Arith.Even.\n\nPrint even.\n\nDefinition even0: even 0 := even_O.\nDefinition odd1 : odd 1 := odd_S 0 even0.\nDefinition odd3: odd 3 := odd_S 2 (even_S 1 odd1).\n(* https://coq.inria.fr/library/Coq.Arith.Even.html *)\n(* https://math-comp.github.io/htmldoc/mathcomp.ssreflect.ssrnat.html *)\n\nLemma even_repeat_3 :\n  forall n0 n1 seq,\n    Fibonacci n0 seq ->\n    Fibonacci n1 (seq + 1) ->\n    even n0 ->\n    odd n1 ->\n    (exists n3,\n     Fibonacci n3 (seq + 3) /\\ even n3).\n  move=> n0 n1 seq fib0 fib1 even0 odd1.\n  have fib2: Fibonacci (n0 + n1) (seq + 2).\n  (exact (FibPlus fib0 fib1)).\n  have plus1 : 2 = (1 + 1). eauto.\n  rewrite plus1 in fib2.\n  rewrite addnA in fib2.\n  exists (n1 + (n0 + n1)).\n  split.\n  - have->: (3) = (1 + 2). eauto.\n    rewrite [(seq + (1 + 2))] addnA.\n    exact: (FibPlus fib1 fib2).\n  - have odd2: odd (n0 + n1). by apply odd_plus_r.\n    by apply odd_even_plus.\nQed.\n\nPrint even_repeat_3.\n", "meta": {"author": "dmelcer9", "repo": "coq-lunch-learn", "sha": "760c7a511cd8dcb4188970fc681e3f19f8f2c7c1", "save_path": "github-repos/coq/dmelcer9-coq-lunch-learn", "path": "github-repos/coq/dmelcer9-coq-lunch-learn/coq-lunch-learn-760c7a511cd8dcb4188970fc681e3f19f8f2c7c1/fibonacci.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7023058034813713}}
{"text": "Fixpoint product_of_range from count :=\n  match count with\n  | O => 1\n  | S count' => (S from) * product_of_range (S from) count'\n  end.\n\nDefinition task :=\n  forall from count, exists k,\n      product_of_range from count = k * product_of_range O count.\n", "meta": {"author": "tzik", "repo": "top-prover", "sha": "3f92af1e76e437bee6b49152f11a6dfb3b730a61", "save_path": "github-repos/coq/tzik-top-prover", "path": "github-repos/coq/tzik-top-prover/top-prover-3f92af1e76e437bee6b49152f11a6dfb3b730a61/tasks/007/Problem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7023057995876157}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) (y : natural) (x : natural)\n  : natural := plus Zero (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj237_coqofml_ZVI1pR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849807, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7021321508218398}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq div fintype tuple.\nRequire Import finfun bigop fingroup perm ssralg zmodp matrix mxalgebra.\nRequire Import poly polydiv.\n\n(******************************************************************************)\n(*   This file provides basic support for formal computation with matrices,   *)\n(* mainly results combining matrices and univariate polynomials, such as the  *)\n(* Cayley-Hamilton theorem; it also contains an extension of the first order  *)\n(* representation of algebra introduced in ssralg (GRing.term/formula).       *)\n(*      rVpoly v == the little-endian decoding of the row vector v as a       *)\n(*                  polynomial p = \\sum_i (v 0 i)%:P * 'X^i.                  *)\n(*     poly_rV p == the partial inverse to rVpoly, for polynomials of degree  *)\n(*                  less than d to 'rV_d (d is inferred from the context).    *)\n(* Sylvester_mx p q == the Sylvester matrix of p and q.                       *)\n(* resultant p q == the resultant of p and q, i.e., \\det (Sylvester_mx p q).  *)\n(*   horner_mx A == the morphism from {poly R} to 'M_n (n of the form n'.+1)  *)\n(*                  mapping a (scalar) polynomial p to the value of its       *)\n(*                  scalar matrix interpretation at A (this is an instance of *)\n(*                  the generic horner_morph construct defined in poly).      *)\n(* powers_mx A d == the d x (n ^ 2) matrix whose rows are the mxvec encodings *)\n(*                  of the first d powers of A (n of the form n'.+1). Thus,   *)\n(*                  vec_mx (v *m powers_mx A d) = horner_mx A (rVpoly v).     *)\n(*   char_poly A == the characteristic polynomial of A.                       *)\n(* char_poly_mx A == a matrix whose detereminant is char_poly A.              *)\n(*   mxminpoly A == the minimal polynomial of A, i.e., the smallest monic     *)\n(*                  polynomial that annihilates A (A must be nontrivial).     *)\n(* degree_mxminpoly A == the (positive) degree of mxminpoly A.                *)\n(* mx_inv_horner A == the inverse of horner_mx A for polynomials of degree    *)\n(*                  smaller than degree_mxminpoly A.                          *)\n(*  integralOver RtoK u <-> u is in the integral closure of the image of R    *)\n(*                  under RtoK : R -> K, i.e. u is a root of the image of a   *)\n(*                  monic polynomial in R.                                    *)\n(*  algebraicOver FtoE u <-> u : E is algebraic over E; it is a root of the   *)\n(*                  image of a nonzero polynomial under FtoE; as F must be a  *)\n(*                  fieldType, this is equivalent to integralOver FtoE u.     *)\n(*  integralRange RtoK <-> the integral closure of the image of R contains    *)\n(*                  all of K (:= forall u, integralOver RtoK u).              *)\n(* This toolkit for building formal matrix expressions is packaged in the     *)\n(* MatrixFormula submodule, and comprises the following:                      *)\n(*     eval_mx e == GRing.eval lifted to matrices (:= map_mx (GRing.eval e)). *)\n(*     mx_term A == GRing.Const lifted to matrices.                           *)\n(* mulmx_term A B == the formal product of two matrices of terms.             *)\n(* mxrank_form m A == a GRing.formula asserting that the interpretation of    *)\n(*                  the term matrix A has rank m.                             *)\n(* submx_form A B == a GRing.formula asserting that the row space of the      *)\n(*                  interpretation of the term matrix A is included in the    *)\n(*                  row space of the interpretation of B.                     *)\n(*   seq_of_rV v == the seq corresponding to a row vector.                    *)\n(*     row_env e == the flattening of a tensored environment e : seq 'rV_d.   *)\n(* row_var F d k == the term vector of width d such that for e : seq 'rV[F]_d *)\n(*                  we have eval e 'X_k = eval_mx (row_env e) (row_var d k).  *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GRing.Theory.\nImport Monoid.Theory.\n\nOpen Local Scope ring_scope.\n\nImport Pdiv.Idomain.\n(* Row vector <-> bounded degree polynomial bijection *)\nSection RowPoly.\n\nVariables (R : ringType) (d : nat).\nImplicit Types u v : 'rV[R]_d.\nImplicit Types p q : {poly R}.\n\nDefinition rVpoly v := \\poly_(k < d) (if insub k is Some i then v 0 i else 0).\nDefinition poly_rV p := \\row_(i < d) p`_i.\n\nLemma coef_rVpoly v k : (rVpoly v)`_k = if insub k is Some i then v 0 i else 0.\nProof. by rewrite coef_poly; case: insubP => [i ->|]; rewrite ?if_same. Qed.\n\nLemma coef_rVpoly_ord v (i : 'I_d) : (rVpoly v)`_i = v 0 i.\nProof. by rewrite coef_rVpoly valK. Qed.\n\nLemma rVpoly_delta i : rVpoly (delta_mx 0 i) = 'X^i.\nProof.\napply/polyP=> j; rewrite coef_rVpoly coefXn.\ncase: insubP => [k _ <- | j_ge_d]; first by rewrite mxE.\nby case: eqP j_ge_d => // ->; rewrite ltn_ord.\nQed.\n\nLemma rVpolyK : cancel rVpoly poly_rV.\nProof. by move=> u; apply/rowP=> i; rewrite mxE coef_rVpoly_ord. Qed.\n\nLemma poly_rV_K p : size p <= d -> rVpoly (poly_rV p) = p.\nProof.\nmove=> le_p_d; apply/polyP=> k; rewrite coef_rVpoly.\ncase: insubP => [i _ <- | ]; first by rewrite mxE.\nby rewrite -ltnNge => le_d_l; rewrite nth_default ?(leq_trans le_p_d).\nQed.\n\nLemma poly_rV_is_linear : linear poly_rV.\nProof. by move=> a p q; apply/rowP=> i; rewrite !mxE coefD coefZ. Qed.\nCanonical poly_rV_additive := Additive poly_rV_is_linear.\nCanonical poly_rV_linear := Linear poly_rV_is_linear.\n\nLemma rVpoly_is_linear : linear rVpoly.\nProof.\nmove=> a u v; apply/polyP=> k; rewrite coefD coefZ !coef_rVpoly.\nby case: insubP => [i _ _ | _]; rewrite ?mxE // mulr0 addr0.\nQed.\nCanonical rVpoly_additive := Additive rVpoly_is_linear.\nCanonical rVpoly_linear := Linear rVpoly_is_linear.\n\nEnd RowPoly.\n\nImplicit Arguments poly_rV [R d].\nPrenex Implicits rVpoly poly_rV.\n\nSection Resultant.\n\nVariables (R : ringType) (p q : {poly R}).\n\nLet dS := ((size q).-1 + (size p).-1)%N.\nLocal Notation band r := (lin1_mx (poly_rV \\o r \\o* rVpoly)).\n\nDefinition Sylvester_mx : 'M[R]_dS := col_mx (band p) (band q).\n\nLemma Sylvester_mxE (i j : 'I_dS) :\n  let S_ r k := r`_(j - k) *+ (k <= j) in\n  Sylvester_mx i j = match split i with inl k => S_ p k | inr k => S_ q k end.\nProof.\nmove=> S_; rewrite mxE; case: {i}(split i) => i; rewrite !mxE /=;\n  by rewrite rVpoly_delta coefXnM ltnNge if_neg -mulrb.\nQed.\n\nDefinition resultant := \\det Sylvester_mx.\n\nEnd Resultant.\n\nLemma resultant_in_ideal (R : comRingType) (p q : {poly R}) :\n    size p > 1 -> size q > 1 ->\n  {uv : {poly R} * {poly R} | size uv.1 < size q /\\ size uv.2 < size p\n  & (resultant p q)%:P = uv.1 * p + uv.2 * q}.\nProof.\nmove=> p_nc q_nc; pose dp := (size p).-1; pose dq := (size q).-1.\npose S := Sylvester_mx p q; pose dS := (dq + dp)%N.\nhave dS_gt0: dS > 0 by rewrite /dS /dq -(subnKC q_nc).\npose j0 := Ordinal dS_gt0. \npose Ss0 := col_mx (p *: \\col_(i < dq) 'X^i) (q *: \\col_(i < dp) 'X^i).\npose Ss := \\matrix_(i, j) (if j == j0 then Ss0 i 0 else (S i j)%:P).\npose u ds s := \\sum_(i < ds) cofactor Ss (s i) j0 * 'X^i.\nexists (u _ (lshift dp), u _ ((rshift dq) _)).\n  suffices sz_u ds s: ds > 1 -> size (u ds.-1 s) < ds by rewrite !sz_u.\n  move/ltn_predK=> {2}<-; apply: leq_trans (size_sum _ _ _) _.\n  apply/bigmax_leqP=> i _.\n  have ->: cofactor Ss (s i) j0 = (cofactor S (s i) j0)%:P.\n    rewrite rmorphM rmorph_sign -det_map_mx; congr (_ * \\det _).\n    by apply/matrixP=> i' j'; rewrite !mxE.\n  apply: leq_trans (size_mul_leq _ _) (leq_trans _ (valP i)).\n  by rewrite size_polyC size_polyXn addnS /= -add1n leq_add2r leq_b1.\ntransitivity (\\det Ss); last first.\n  rewrite (expand_det_col Ss j0) big_split_ord !big_distrl /=.\n  by congr (_ + _); apply: eq_bigr => i _;\n    rewrite mxE eqxx (col_mxEu, col_mxEd) !mxE mulrC mulrA mulrAC.\npose S_ j1 := map_mx polyC (\\matrix_(i, j) S i (if j == j0 then j1 else j)).\npose Ss0_ i dj := \\poly_(j < dj) S i (insubd j0 j).\npose Ss_ dj := \\matrix_(i, j) (if j == j0 then Ss0_ i dj else (S i j)%:P).\nhave{Ss u} ->: Ss = Ss_ dS.\n  apply/matrixP=> i j; rewrite mxE [in X in _ = X]mxE; case: (j == j0) => {j}//.\n  apply/polyP=> k; rewrite coef_poly Sylvester_mxE mxE.\n  have [k_ge_dS | k_lt_dS] := leqP dS k.\n    case: (split i) => {i}i; rewrite !mxE coefMXn;\n    case: ifP => // /negbT; rewrite -ltnNge ltnS => hi.\n      apply: (leq_sizeP _ _ (leqnn (size p))); rewrite -(ltn_predK p_nc).\n      by rewrite ltn_subRL (leq_trans _ k_ge_dS) // ltn_add2r.\n    - apply: (leq_sizeP _ _ (leqnn (size q))); rewrite -(ltn_predK q_nc).\n      by rewrite ltn_subRL (leq_trans _ k_ge_dS) // addnC ltn_add2l.\n  by rewrite insubdK //; case: (split i) => {i}i;\n     rewrite !mxE coefMXn; case: leqP.\nelim: {-2}dS (leqnn dS) (dS_gt0) => // dj IHj dj_lt_dS _.\npose j1 := Ordinal dj_lt_dS; pose rj0T (A : 'M[{poly R}]_dS) := row j0 A^T.\nhave: rj0T (Ss_ dj.+1) = 'X^dj *: rj0T (S_ j1) + 1 *: rj0T (Ss_ dj).\n\n  apply/rowP=> i; apply/polyP=> k; rewrite scale1r !(Sylvester_mxE, mxE) eqxx.\n\n  rewrite coefD coefXnM coefC !coef_poly ltnS subn_eq0 ltn_neqAle andbC.\n  case: (leqP k dj) => [k_le_dj | k_gt_dj] /=; last by rewrite addr0.\n  rewrite Sylvester_mxE insubdK; last exact: leq_ltn_trans (dj_lt_dS).\n  by case: eqP => [-> | _]; rewrite (addr0, add0r).\nrewrite -det_tr => /determinant_multilinear->;\n  try by apply/matrixP=> i j; rewrite !mxE eq_sym (negPf (neq_lift _ _)).\nhave [dj0 | dj_gt0] := posnP dj; rewrite ?dj0 !mul1r.\n  rewrite !det_tr det_map_mx addrC (expand_det_col _ j0) big1 => [|i _].\n    rewrite add0r; congr (\\det _)%:P.\n    apply/matrixP=> i j; rewrite [in X in _ = X]mxE; case: eqP => // ->.\n    by congr (S i _); apply: val_inj.\n  by rewrite mxE /= [Ss0_ _ _]poly_def big_ord0 mul0r.\nhave /determinant_alternate->: j1 != j0 by rewrite -val_eqE -lt0n.\n  by rewrite mulr0 add0r det_tr IHj // ltnW.\nby move=> i; rewrite !mxE if_same.\nQed.\n\nLemma resultant_eq0 (R : idomainType) (p q : {poly R}) :\n  (resultant p q == 0) = (size (gcdp p q) > 1).\nProof.\nhave dvdpp := dvdpp; set r := gcdp p q.\npose dp := (size p).-1; pose dq := (size q).-1.\nhave /andP[r_p r_q]: (r %| p) && (r %| q) by rewrite -dvdp_gcd.\napply/det0P/idP=> [[uv nz_uv] | r_nonC].\n  have [p0 _ | p_nz] := eqVneq p 0.\n    have: dq + dp > 0.\n      rewrite lt0n; apply: contraNneq nz_uv => dqp0.\n      by rewrite dqp0 in uv *; rewrite [uv]thinmx0.\n    by rewrite /dp /dq /r p0 size_poly0 addn0 gcd0p -subn1 subn_gt0.\n  do [rewrite -[uv]hsubmxK -{1}row_mx0 mul_row_col !mul_rV_lin1 /=] in nz_uv *.\n  set u := rVpoly _; set v := rVpoly _; pose m := gcdp (v * p) (v * q).\n  have lt_vp: size v < size p by rewrite (polySpred p_nz) ltnS size_poly.\n  move/(congr1 rVpoly); rewrite linearD linear0 /=; move/(canRL (addKr _)).\n  rewrite !poly_rV_K ?(leq_trans (size_mul_leq _ _)) // => [vq_up||]; first 1 last.\n  - by rewrite -subn1 leq_subLR addnCA leq_add ?leqSpred ?size_poly.\n  - by rewrite -subn1 leq_subLR addnC addnA leq_add ?leqSpred ?size_poly.\n  have nz_v: v != 0.\n    apply: contraNneq nz_uv => v0; apply/eqP.\n    congr row_mx; apply: (can_inj (@rVpolyK _ _)); rewrite linear0 // -/u.\n    move/eqP: vq_up; apply: contraTeq => nz_u.\n    by rewrite v0 mul0r addr0 eq_sym oppr_eq0 mulf_neq0.\n  have r_nz: r != 0 := dvdpN0 r_p p_nz.\n  have /dvdpP [[c w] /= nz_c wv]: v %| m by rewrite dvdp_gcd !dvdp_mulr.\n  have m_wd d: m %| v * d -> w %| d.\n    case/dvdpP=> [[k f]] /= nz_k; move/(congr1 ( *:%R c)).\n    rewrite mulrC scalerA scalerAl scalerAr wv mulrA.\n    move/(mulIf nz_v)=> def_fw; apply/dvdpP.\n    by exists (c * k, f); rewrite //= mulf_neq0.\n  have w_r: w %| r by rewrite dvdp_gcd !m_wd ?dvdp_gcdl ?dvdp_gcdr.\n  have w_nz: w != 0 := dvdpN0 w_r r_nz.\n  have p_m: p %| m by rewrite dvdp_gcd vq_up addr0 -mulNr !dvdp_mull.\n  rewrite (leq_trans _ (dvdp_leq r_nz w_r)) // -(ltn_add2l (size v)).\n  rewrite addnC -ltn_subRL subn1 -size_mul // mulrC -wv size_scale //.\n  rewrite (leq_trans lt_vp) // dvdp_leq // -size_poly_eq0.\n  by rewrite -(size_scale _ nz_c) size_poly_eq0 wv mulf_neq0.\nhave [[c p'] /= nz_c p'r] := dvdpP _ _ r_p.\nhave [[k q'] /= nz_k q'r] := dvdpP _ _ r_q.\nhave def_r := subnKC r_nonC; have r_nz: r != 0 by rewrite -size_poly_eq0 -def_r.\nhave le_p'_dp: size p' <= dp.\n  have [-> | nz_p'] := eqVneq p' 0; first by rewrite size_poly0.\n  by rewrite /dp -(size_scale p nz_c) p'r size_mul // addnC -def_r leq_addl.\nhave le_q'_dq: size q' <= dq.\n  have [-> | nz_q'] := eqVneq q' 0; first by rewrite size_poly0.\n  by rewrite /dq -(size_scale q nz_k) q'r size_mul // addnC -def_r leq_addl.\nexists (row_mx (- c *: poly_rV q') (k *: poly_rV p')).\n  apply: contraNneq r_nz; rewrite -row_mx0; case/eq_row_mx=> q0 p0.\n  have{p0} p0: p = 0.\n    apply/eqP; rewrite -size_poly_eq0 -(size_scale p nz_c) p'r.\n    rewrite -(size_scale _ nz_k) scalerAl -(poly_rV_K le_p'_dp) -linearZ p0.\n    by rewrite linear0 mul0r size_poly0.\n  rewrite /r p0 gcd0p -size_poly_eq0 -(size_scale q nz_k) q'r.\n  rewrite -(size_scale _ nz_c) scalerAl -(poly_rV_K le_q'_dq) -linearZ.\n  by rewrite -[c]opprK scaleNr q0 !linear0 mul0r size_poly0.\nrewrite mul_row_col scaleNr mulNmx !mul_rV_lin1 /= !linearZ /= !poly_rV_K //.\nby rewrite !scalerCA p'r q'r mulrCA addNr.\nQed.\n\nSection HornerMx.\n\nVariables (R : comRingType) (n' : nat).\nLocal Notation n := n'.+1.\nVariable A : 'M[R]_n.\nImplicit Types p q : {poly R}.\n\nDefinition horner_mx := horner_morph (fun a => scalar_mx_comm a A).\nCanonical horner_mx_additive := [additive of horner_mx].\nCanonical horner_mx_rmorphism := [rmorphism of horner_mx].\n\nLemma horner_mx_C a : horner_mx a%:P = a%:M.\nProof. exact: horner_morphC. Qed.\n\nLemma horner_mx_X : horner_mx 'X = A. Proof. exact: horner_morphX. Qed.\n\nLemma horner_mxZ : scalable horner_mx.\nProof.\nmove=> a p /=; rewrite -mul_polyC rmorphM /=.\nby rewrite horner_mx_C [_ * _]mul_scalar_mx.\nQed.\n\nCanonical horner_mx_linear := AddLinear horner_mxZ.\nCanonical horner_mx_lrmorphism := [lrmorphism of horner_mx].\n\nDefinition powers_mx d := \\matrix_(i < d) mxvec (A ^+ i).\n\nLemma horner_rVpoly m (u : 'rV_m) :\n  horner_mx (rVpoly u) = vec_mx (u *m powers_mx m).\nProof.\nrewrite mulmx_sum_row linear_sum [rVpoly u]poly_def rmorph_sum.\napply: eq_bigr => i _.\nby rewrite valK !linearZ rmorphX /= horner_mx_X rowK /= mxvecK.\nQed.\n\nEnd HornerMx.\n\nSection CharPoly.\n\nVariables (R : ringType) (n : nat) (A : 'M[R]_n).\nImplicit Types p q : {poly R}.\n\nDefinition char_poly_mx := 'X%:M - map_mx (@polyC R) A.\nDefinition char_poly := \\det char_poly_mx.\n\nLet diagA := [seq A i i | i : 'I_n].\nLet size_diagA : size diagA = n.\nProof. by rewrite size_image card_ord. Qed.\n\nLet split_diagA :\n  exists2 q, \\prod_(x <- diagA) ('X - x%:P) + q = char_poly & size q <= n.-1.\nProof.\nrewrite [char_poly](bigD1 1%g) //=; set q := \\sum_(s | _) _; exists q.\n  congr (_ + _); rewrite odd_perm1 mul1r big_map enumT; apply: eq_bigr => i _.\n  by rewrite !mxE perm1 eqxx.\napply: leq_trans {q}(size_sum _ _ _) _; apply/bigmax_leqP=> s nt_s.\nhave{nt_s} [i nfix_i]: exists i, s i != i.\n  apply/existsP; rewrite -negb_forall; apply: contra nt_s => s_1.\n  by apply/eqP; apply/permP=> i; apply/eqP; rewrite perm1 (forallP s_1).\napply: leq_trans (_ : #|[pred j | s j == j]|.+1 <= n.-1).\n  rewrite -sum1_card (@big_mkcond nat) /= size_Msign.\n  apply: (big_ind2 (fun p m => size p <= m.+1)) => [| p mp q mq IHp IHq | j _].\n  - by rewrite size_poly1.\n  - apply: leq_trans (size_mul_leq _ _) _.\n    by rewrite -subn1 -addnS leq_subLR addnA leq_add.\n  rewrite !mxE eq_sym !inE; case: (s j == j); first by rewrite polyseqXsubC. \n  by rewrite sub0r size_opp size_polyC leq_b1.\nrewrite -{8}[n]card_ord -(cardC (pred2 (s i) i)) card2 nfix_i !ltnS.\napply: subset_leq_card; apply/subsetP=> j; move/(_ =P j)=> fix_j.\nrewrite !inE -{1}fix_j (inj_eq (@perm_inj _ s)) orbb.\nby apply: contraNneq nfix_i => <-; rewrite fix_j.\nQed.   \n\nLemma size_char_poly : size char_poly = n.+1.\nProof.\nhave [q <- lt_q_n] := split_diagA; have le_q_n := leq_trans lt_q_n (leq_pred n).\nby rewrite size_addl size_prod_XsubC size_diagA.\nQed.\n\nLemma char_poly_monic : char_poly \\is monic.\nProof.\nrewrite monicE -(monicP (monic_prod_XsubC diagA xpredT id)).\nrewrite !lead_coefE size_char_poly.\nhave [q <- lt_q_n] := split_diagA; have le_q_n := leq_trans lt_q_n (leq_pred n).\nby rewrite size_prod_XsubC size_diagA coefD (nth_default 0 le_q_n) addr0.\nQed.\n\nLemma char_poly_trace : n > 0 -> char_poly`_n.-1 = - \\tr A.\nProof.\nmove=> n_gt0; have [q <- lt_q_n] := split_diagA; set p := \\prod_(x <- _) _.\nrewrite coefD {q lt_q_n}(nth_default 0 lt_q_n) addr0.\nhave{n_gt0} ->: p`_n.-1 = ('X * p)`_n by rewrite coefXM eqn0Ngt n_gt0.\nhave ->: \\tr A = \\sum_(x <- diagA) x by rewrite big_map enumT.\nrewrite -size_diagA {}/p; elim: diagA => [|x d IHd].\n  by rewrite !big_nil mulr1 coefX oppr0.\nrewrite !big_cons coefXM mulrBl coefB IHd opprD addrC; congr (- _ + _).\nrewrite mul_polyC coefZ [size _]/= -(size_prod_XsubC _ id) -lead_coefE. \nby rewrite (monicP _) ?monic_prod_XsubC ?mulr1.\nQed.\n\nLemma char_poly_det : char_poly`_0 = (- 1) ^+ n * \\det A.\nProof.\nrewrite big_distrr coef_sum [0%N]lock /=; apply: eq_bigr => s _.\nrewrite -{1}rmorphN -rmorphX mul_polyC coefZ /=.\nrewrite mulrA -exprD addnC exprD -mulrA -lock; congr (_ * _).\ntransitivity (\\prod_(i < n) - A i (s i)); last by rewrite prodrN card_ord.\nelim: (index_enum _) => [|i e IHe]; rewrite !(big_nil, big_cons) ?coef1 //.\nby rewrite coefM big_ord1 IHe !mxE coefB coefC coefMn coefX mul0rn sub0r.\nQed.\n\nEnd CharPoly.\n\nLemma mx_poly_ring_isom (R : ringType) n' (n := n'.+1) :\n  exists phi : {rmorphism 'M[{poly R}]_n -> {poly 'M[R]_n}},\n  [/\\ bijective phi,\n      forall p, phi p%:M = map_poly scalar_mx p,\n      forall A, phi (map_mx polyC A) = A%:P\n    & forall A i j k, (phi A)`_k i j = (A i j)`_k].\nProof.\nset M_RX := 'M[{poly R}]_n; set MR_X := ({poly 'M[R]_n}).\npose Msize (A : M_RX) := \\max_i \\max_j size (A i j).\npose phi (A : M_RX) := \\poly_(k < Msize A) \\matrix_(i, j) (A i j)`_k.\nhave coef_phi A i j k: (phi A)`_k i j = (A i j)`_k.\n  rewrite coef_poly; case: (ltnP k _) => le_m_k; rewrite mxE // nth_default //.\n  apply: leq_trans (leq_trans (leq_bigmax i) le_m_k); exact: (leq_bigmax j).\nhave phi_is_rmorphism : rmorphism phi.\n  do 2?[split=> [A B|]]; apply/polyP=> k; apply/matrixP=> i j; last 1 first.\n  - rewrite coef_phi mxE coefMn !coefC.\n    by case: (k == _); rewrite ?mxE ?mul0rn.\n  - by rewrite !(coef_phi, mxE, coefD, coefN).\n  rewrite !coef_phi !mxE !coefM summxE coef_sum.\n  pose F k1 k2 := (A i k1)`_k2 * (B k1 j)`_(k - k2).\n  transitivity (\\sum_k1 \\sum_(k2 < k.+1) F k1 k2); rewrite {}/F.\n    by apply: eq_bigr=> k1 _; rewrite coefM.\n  rewrite exchange_big /=; apply: eq_bigr => k2 _.\n  by rewrite mxE; apply: eq_bigr => k1 _; rewrite !coef_phi.\nhave bij_phi: bijective phi.\n  exists (fun P : MR_X => \\matrix_(i, j) \\poly_(k < size P) P`_k i j) => [A|P].\n    apply/matrixP=> i j; rewrite mxE; apply/polyP=> k.\n    rewrite coef_poly -coef_phi.\n    by case: leqP => // P_le_k; rewrite nth_default ?mxE.\n  apply/polyP=> k; apply/matrixP=> i j; rewrite coef_phi mxE coef_poly.\n  by case: leqP => // P_le_k; rewrite nth_default ?mxE.\nexists (RMorphism phi_is_rmorphism).\nsplit=> // [p | A]; apply/polyP=> k; apply/matrixP=> i j.\n  by rewrite coef_phi coef_map !mxE coefMn.\nby rewrite coef_phi !mxE !coefC; case k; last rewrite /= mxE.\nQed.\n\nTheorem Cayley_Hamilton (R : comRingType) n' (A : 'M[R]_n'.+1) :\n  horner_mx A (char_poly A) = 0.\nProof.\nhave [phi [_ phiZ phiC _]] := mx_poly_ring_isom R n'.\napply/rootP/factor_theorem; rewrite -phiZ -mul_adj_mx rmorphM.\nby move: (phi _) => q; exists q; rewrite rmorphB phiC phiZ map_polyX.\nQed.\n\nLemma eigenvalue_root_char (F : fieldType) n (A : 'M[F]_n) a :\n  eigenvalue A a = root (char_poly A) a.\nProof.\ntransitivity (\\det (a%:M - A) == 0).\n  apply/eigenvalueP/det0P=> [[v Av_av v_nz] | [v v_nz Av_av]]; exists v => //.\n    by rewrite mulmxBr Av_av mul_mx_scalar subrr.\n  by apply/eqP; rewrite -mul_mx_scalar eq_sym -subr_eq0 -mulmxBr Av_av.\ncongr (_ == 0); rewrite horner_sum; apply: eq_bigr => s _.\nrewrite hornerM horner_exp !hornerE; congr (_ * _).\nrewrite (big_morph _ (fun p q => hornerM p q a) (hornerC 1 a)).\nby apply: eq_bigr => i _; rewrite !mxE !(hornerE, hornerMn).\nQed.\n\nSection MinPoly.\n\nVariables (F : fieldType) (n' : nat).\nLocal Notation n := n'.+1.\nVariable A : 'M[F]_n.\nImplicit Types p q : {poly F}.\n\nFact degree_mxminpoly_proof : exists d, \\rank (powers_mx A d.+1) <= d.\nProof. by exists (n ^ 2)%N; rewrite rank_leq_col. Qed.\nDefinition degree_mxminpoly := ex_minn degree_mxminpoly_proof.\nLocal Notation d := degree_mxminpoly.\nLocal Notation Ad := (powers_mx A d).\n\nLemma mxminpoly_nonconstant : d > 0.\nProof.\nrewrite /d; case: ex_minnP; case=> //; rewrite leqn0 mxrank_eq0; move/eqP.\nmove/row_matrixP; move/(_ 0); move/eqP; rewrite rowK row0 mxvec_eq0.\nby rewrite -mxrank_eq0 mxrank1.\nQed.\n\nLemma minpoly_mx1 : (1%:M \\in Ad)%MS.\nProof.\nby apply: (eq_row_sub (Ordinal mxminpoly_nonconstant)); rewrite rowK.\nQed.\n\nLemma minpoly_mx_free : row_free Ad.\nProof.\nhave:= mxminpoly_nonconstant; rewrite /d; case: ex_minnP; case=> // d' _.\nmove/(_ d'); move/implyP; rewrite ltnn implybF -ltnS ltn_neqAle.\nby rewrite rank_leq_row andbT negbK.\nQed.\n\nLemma horner_mx_mem p : (horner_mx A p \\in Ad)%MS.\nProof.\nelim/poly_ind: p => [|p a IHp]; first by rewrite rmorph0 // linear0 sub0mx.\nrewrite rmorphD rmorphM /= horner_mx_C horner_mx_X.\nrewrite addrC -scalemx1 linearP /= -(mul_vec_lin (mulmxr_linear _ A)).\ncase/submxP: IHp => u ->{p}.\nhave: (powers_mx A (1 + d) <= Ad)%MS.\n  rewrite -(geq_leqif (mxrank_leqif_sup _)).\n    by rewrite (eqnP minpoly_mx_free) /d; case: ex_minnP.\n  rewrite addnC; apply/row_subP=> i.\n  by apply: eq_row_sub (lshift 1 i) _; rewrite !rowK.\napply: submx_trans; rewrite addmx_sub ?scalemx_sub //.\n  by apply: (eq_row_sub 0); rewrite rowK.\nrewrite -mulmxA mulmx_sub {u}//; apply/row_subP=> i.\nrewrite row_mul rowK mul_vec_lin /= mulmxE -exprSr.\nby apply: (eq_row_sub (rshift 1 i)); rewrite rowK.\nQed.\n\nDefinition mx_inv_horner B := rVpoly (mxvec B *m pinvmx Ad).\n\nLemma mx_inv_horner0 :  mx_inv_horner 0 = 0.\nProof. by rewrite /mx_inv_horner !(linear0, mul0mx). Qed.\n\nLemma mx_inv_hornerK B : (B \\in Ad)%MS -> horner_mx A (mx_inv_horner B) = B.\nProof. by move=> sBAd; rewrite horner_rVpoly mulmxKpV ?mxvecK. Qed.\n\nLemma minpoly_mxM B C : (B \\in Ad -> C \\in Ad -> B * C \\in Ad)%MS.\nProof.\nmove=> AdB AdC; rewrite -(mx_inv_hornerK AdB) -(mx_inv_hornerK AdC).\nby rewrite -rmorphM ?horner_mx_mem.\nQed.\n\nLemma minpoly_mx_ring : mxring Ad.\nProof.\napply/andP; split; first by apply/mulsmx_subP; exact: minpoly_mxM.\napply/mxring_idP; exists 1%:M; split=> *; rewrite ?mulmx1 ?mul1mx //.\n  by rewrite -mxrank_eq0 mxrank1.\nexact: minpoly_mx1.\nQed.\n\nDefinition mxminpoly := 'X^d - mx_inv_horner (A ^+ d).\nLocal Notation p_A := mxminpoly.\n\nLemma size_mxminpoly : size p_A = d.+1.\nProof. by rewrite size_addl ?size_polyXn // size_opp ltnS size_poly. Qed.\n\nLemma mxminpoly_monic : p_A \\is monic.\nProof.\nrewrite monicE /lead_coef size_mxminpoly coefB coefXn eqxx /=.\nby rewrite nth_default ?size_poly // subr0.\nQed.\n\nLemma size_mod_mxminpoly p : size (p %% p_A) <= d.\nProof.\nby rewrite -ltnS -size_mxminpoly ltn_modp // -size_poly_eq0 size_mxminpoly.\nQed.\n\nLemma mx_root_minpoly : horner_mx A p_A = 0.\nProof.\nrewrite rmorphB -{3}(horner_mx_X A) -rmorphX /=.\nby rewrite mx_inv_hornerK ?subrr ?horner_mx_mem.\nQed.\n\nLemma horner_rVpolyK (u : 'rV_d) :\n  mx_inv_horner (horner_mx A (rVpoly u)) = rVpoly u.\nProof.\ncongr rVpoly; rewrite horner_rVpoly vec_mxK.\nby apply: (row_free_inj minpoly_mx_free); rewrite mulmxKpV ?submxMl.\nQed.\n\nLemma horner_mxK p : mx_inv_horner (horner_mx A p) = p %% p_A.\nProof.\nrewrite {1}(Pdiv.IdomainMonic.divp_eq mxminpoly_monic p) rmorphD rmorphM /=.\nrewrite mx_root_minpoly mulr0 add0r.\nby rewrite -(poly_rV_K (size_mod_mxminpoly _)) horner_rVpolyK.\nQed.\n\nLemma mxminpoly_min p : horner_mx A p = 0 -> p_A %| p.\nProof. by move=> pA0; rewrite /dvdp -horner_mxK pA0 mx_inv_horner0. Qed.\n\nLemma horner_rVpoly_inj : @injective 'M_n 'rV_d (horner_mx A \\o rVpoly).\nProof.\napply: can_inj (poly_rV \\o mx_inv_horner) _ => u.\nby rewrite /= horner_rVpolyK rVpolyK.\nQed.\n\nLemma mxminpoly_linear_is_scalar : (d <= 1) = is_scalar_mx A.\nProof.\nhave scalP := has_non_scalar_mxP minpoly_mx1.\nrewrite leqNgt -(eqnP minpoly_mx_free); apply/scalP/idP=> [|[[B]]].\n  case scalA: (is_scalar_mx A); [by right | left].\n  by exists A; rewrite ?scalA // -{1}(horner_mx_X A) horner_mx_mem.\nmove/mx_inv_hornerK=> <- nsB; case/is_scalar_mxP=> a defA; case/negP: nsB.\nmove: {B}(_ B); apply: poly_ind => [|p c].\n  by rewrite rmorph0 ?mx0_is_scalar.\nrewrite rmorphD ?rmorphM /= horner_mx_X defA; case/is_scalar_mxP=> b ->.\nby rewrite -rmorphM horner_mx_C -rmorphD /= scalar_mx_is_scalar.\nQed.\n\nLemma mxminpoly_dvd_char : p_A %| char_poly A.\nProof. by apply: mxminpoly_min; exact: Cayley_Hamilton. Qed.\n\nLemma eigenvalue_root_min a : eigenvalue A a = root p_A a.\nProof.\napply/idP/idP=> Aa; last first.\n  rewrite eigenvalue_root_char !root_factor_theorem in Aa *.\n  exact: dvdp_trans Aa mxminpoly_dvd_char.\nhave{Aa} [v Av_av v_nz] := eigenvalueP Aa.\napply: contraR v_nz => pa_nz; rewrite -{pa_nz}(eqmx_eq0 (eqmx_scale _ pa_nz)).\napply/eqP; rewrite -(mulmx0 _ v) -mx_root_minpoly.\nelim/poly_ind: p_A => [|p c IHp].\n  by rewrite rmorph0 horner0 scale0r mulmx0.\nrewrite !hornerE rmorphD rmorphM /= horner_mx_X horner_mx_C scalerDl.\nby rewrite -scalerA mulmxDr mul_mx_scalar mulmxA -IHp -scalemxAl Av_av.\nQed.\n\nEnd MinPoly.\n\n(* Parametricity. *)\nSection MapRingMatrix.\n\nVariables (aR rR : ringType) (f : {rmorphism aR -> rR}).\nLocal Notation \"A ^f\" := (map_mx (GRing.RMorphism.apply f) A) : ring_scope.\nLocal Notation fp := (map_poly (GRing.RMorphism.apply f)).\nVariables (d n : nat) (A : 'M[aR]_n).\n\nLemma map_rVpoly (u : 'rV_d) : fp (rVpoly u) = rVpoly u^f.\nProof.\napply/polyP=> k; rewrite coef_map !coef_rVpoly.\nby case: (insub k) => [i|]; rewrite  /=  ?rmorph0 // mxE.\nQed.\n\nLemma map_poly_rV p : (poly_rV p)^f = poly_rV (fp p) :> 'rV_d.\nProof. by apply/rowP=> j; rewrite !mxE coef_map. Qed.\n\nLemma map_char_poly_mx : map_mx fp (char_poly_mx A) = char_poly_mx A^f.\nProof.\nrewrite raddfB /= map_scalar_mx /= map_polyX; congr (_ - _).\nby apply/matrixP=> i j; rewrite !mxE map_polyC.\nQed.\n\nLemma map_char_poly : fp (char_poly A) = char_poly A^f.\nProof. by rewrite -det_map_mx map_char_poly_mx. Qed.\n\nEnd MapRingMatrix.\n\nSection MapResultant.\n\nLemma map_resultant (aR rR : ringType) (f : {rmorphism {poly aR} -> rR}) p q :\n    f (lead_coef p) != 0 -> f (lead_coef q) != 0 ->\n  f (resultant p q)= resultant (map_poly f p) (map_poly f q).\nProof.\nmove=> nz_fp nz_fq; rewrite /resultant /Sylvester_mx !size_map_poly_id0 //.\nrewrite -det_map_mx /= map_col_mx; congr (\\det (col_mx _ _));\n  by apply: map_lin1_mx => v; rewrite map_poly_rV rmorphM /= map_rVpoly.\nQed.\n\nEnd MapResultant.\n\nSection MapComRing.\n\nVariables (aR rR : comRingType) (f : {rmorphism aR -> rR}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\nLocal Notation fp := (map_poly f).\nVariables (n' : nat) (A : 'M[aR]_n'.+1).\n\nLemma map_powers_mx e : (powers_mx A e)^f = powers_mx A^f e.\nProof. by apply/row_matrixP=> i; rewrite -map_row !rowK map_mxvec rmorphX. Qed.\n\nLemma map_horner_mx p : (horner_mx A p)^f = horner_mx A^f (fp p).\nProof.\nrewrite -[p](poly_rV_K (leqnn _)) map_rVpoly.\nby rewrite !horner_rVpoly map_vec_mx map_mxM map_powers_mx.\nQed.\n\nEnd MapComRing.\n\nSection MapField.\n\nVariables (aF rF : fieldType) (f : {rmorphism aF -> rF}).\nLocal Notation \"A ^f\" := (map_mx f A) : ring_scope.\nLocal Notation fp := (map_poly f).\nVariables (n' : nat) (A : 'M[aF]_n'.+1).\n\nLemma degree_mxminpoly_map : degree_mxminpoly A^f = degree_mxminpoly A.\nProof. by apply: eq_ex_minn => e; rewrite -map_powers_mx mxrank_map. Qed.\n\nLemma mxminpoly_map : mxminpoly A^f = fp (mxminpoly A).\nProof.\nrewrite rmorphB; congr (_ - _).\n  by rewrite /= map_polyXn degree_mxminpoly_map.\nrewrite degree_mxminpoly_map -rmorphX /=.\napply/polyP=> i; rewrite coef_map //= !coef_rVpoly degree_mxminpoly_map.\ncase/insub: i => [i|]; last by rewrite rmorph0.\nby rewrite -map_powers_mx -map_pinvmx // -map_mxvec -map_mxM // mxE.\nQed.\n\nLemma map_mx_inv_horner u : fp (mx_inv_horner A u) = mx_inv_horner A^f u^f.\nProof.\nrewrite map_rVpoly map_mxM map_mxvec map_pinvmx map_powers_mx.\nby rewrite /mx_inv_horner degree_mxminpoly_map.\nQed.\n\nEnd MapField.\n\nSection IntegralOverRing.\n\nDefinition integralOver (R K : ringType) (RtoK : R -> K) (z : K) :=\n  exists2 p, p \\is monic & root (map_poly RtoK p) z.\n\nDefinition integralRange R K RtoK := forall z, @integralOver R K RtoK z.\n\nVariables (B R K : ringType) (BtoR : B -> R) (RtoK : {rmorphism R -> K}).\n\nLemma integral_rmorph x :\n  integralOver BtoR x -> integralOver (RtoK \\o BtoR) (RtoK x).\nProof. by case=> p; exists p; rewrite // map_poly_comp rmorph_root. Qed.\n\nLemma integral_id x : integralOver RtoK (RtoK x).\nProof. by exists ('X - x%:P); rewrite ?monicXsubC ?rmorph_root ?root_XsubC. Qed.\n\nLemma integral_nat n : integralOver RtoK n%:R.\nProof. by rewrite -(rmorph_nat RtoK); apply: integral_id. Qed.\n\nLemma integral0 : integralOver RtoK 0. Proof. exact: (integral_nat 0). Qed.\n\nLemma integral1 : integralOver RtoK 1. Proof. exact: (integral_nat 1). Qed.\n\nLemma integral_poly (p : {poly K}) :\n  (forall i, integralOver RtoK p`_i) <-> {in p : seq K, integralRange RtoK}.\nProof.\nsplit=> intRp => [_ /(nthP 0)[i _ <-] // | i]; rewrite -[p]coefK coef_poly.\nby case: ifP => [ltip | _]; [apply/intRp/mem_nth | apply: integral0].\nQed.\n\nEnd IntegralOverRing.\n\nSection IntegralOverComRing.\n\nVariables (R K : comRingType) (RtoK : {rmorphism R -> K}).\n\nLemma integral_horner_root w (p q : {poly K}) :\n    p \\is monic -> root p w ->\n    {in p : seq K, integralRange RtoK} -> {in q : seq K, integralRange RtoK} ->\n  integralOver RtoK q.[w].\nProof.\nmove=> mon_p pw0 intRp intRq.\npose memR y := exists x, y = RtoK x.\nhave memRid x: memR (RtoK x) by exists x.\nhave memR_nat n: memR n%:R by rewrite -(rmorph_nat RtoK).\nhave [memR0 memR1]: memR 0 * memR 1 := (memR_nat 0%N, memR_nat 1%N).\nhave memRN1: memR (- 1) by exists (- 1); rewrite rmorphN1.\npose rVin (E : K -> Prop) n (a : 'rV[K]_n) := forall i, E (a 0 i).\npose pXin (E : K -> Prop) (r : {poly K}) := forall i, E r`_i.\npose memM E n (X : 'rV_n) y := exists a, rVin E n a /\\ y = (a *m X^T) 0 0.\npose finM E S := exists n, exists X, forall y, memM E n X y <-> S y.\nhave tensorM E n1 n2 X Y: finM E (memM (memM E n2 Y) n1 X).\n  exists (n1 * n2)%N, (mxvec (X^T *m Y)) => y.\n  split=> [[a [Ea Dy]] | [a1 [/fin_all_exists[a /all_and2[Ea Da1]] ->]]].\n    exists (Y *m (vec_mx a)^T); split=> [i|].\n      exists (row i (vec_mx a)); split=> [j|]; first by rewrite !mxE; apply: Ea.\n      by rewrite -row_mul -{1}[Y]trmxK -trmx_mul !mxE.\n    by rewrite -[Y]trmxK -!trmx_mul mulmxA -mxvec_dotmul trmx_mul trmxK vec_mxK.\n  exists (mxvec (\\matrix_i a i)); split.\n    by case/mxvec_indexP=> i j; rewrite mxvecE mxE; apply: Ea.\n  rewrite -[mxvec _]trmxK -trmx_mul mxvec_dotmul -mulmxA trmx_mul !mxE.\n  apply: eq_bigr => i _; rewrite Da1 !mxE; congr (_ * _).\n  by apply: eq_bigr => j _; rewrite !mxE.\nsuffices [m [X [[u [_ Du]] idealM]]]: exists m,\n  exists X, let M := memM memR m X in M 1 /\\ forall y, M y -> M (q.[w] * y).\n- do [set M := memM _ m X; move: q.[w] => z] in idealM *.\n  have MX i: M (X 0 i).\n    by exists (delta_mx 0 i); split=> [j|]; rewrite -?rowE !mxE.\n  have /fin_all_exists[a /all_and2[Fa Da1]] i := idealM _ (MX i).\n  have /fin_all_exists[r Dr] i := fin_all_exists (Fa i).\n  pose A := \\matrix_(i, j) r j i; pose B := z%:M - map_mx RtoK A.\n  have XB0: X *m B = 0.\n    apply/eqP; rewrite mulmxBr mul_mx_scalar subr_eq0; apply/eqP/rowP=> i.\n    by rewrite !mxE Da1 mxE; apply: eq_bigr=> j _; rewrite !mxE mulrC Dr.\n  exists (char_poly A); first exact: char_poly_monic.\n  have: (\\det B *: (u *m X^T)) 0 0 == 0.\n    rewrite scalemxAr -linearZ -mul_mx_scalar -mul_mx_adj mulmxA XB0 /=.\n    by rewrite mul0mx trmx0 mulmx0 mxE.\n  rewrite mxE -Du mulr1 rootE -horner_evalE -!det_map_mx; congr (\\det _ == 0).\n  rewrite !raddfB /= !map_scalar_mx /= map_polyX horner_evalE hornerX.\n  by apply/matrixP=> i j; rewrite !mxE map_polyC /horner_eval hornerC.\npose gen1 x E y := exists2 r, pXin E r & y = r.[x]; pose gen := foldr gen1 memR.\nhave gen1S (E : K -> Prop) x y: E 0 -> E y -> gen1 x E y.\n  by exists y%:P => [i|]; rewrite ?hornerC ?coefC //; case: ifP.\nhave genR S y: memR y -> gen S y.\n  by elim: S => //= x S IH in y * => /IH; apply: gen1S; apply: IH.\nhave gen0 := genR _ 0 memR0; have gen_1 := genR _ 1 memR1.\nhave{gen1S} genS S y: y \\in S -> gen S y.\n  elim: S => //= x S IH /predU1P[-> | /IH//]; last exact: gen1S.\n  by exists 'X => [i|]; rewrite ?hornerX // coefX; apply: genR.\npose propD (R : K -> Prop) := forall x y, R x -> R y -> R (x + y).\nhave memRD: propD memR.\n  by move=> _ _ [a ->] [b ->]; exists (a + b); rewrite rmorphD.\nhave genD S: propD (gen S).\n  elim: S => //= x S IH _ _ [r1 Sr1 ->] [r2 Sr2 ->]; rewrite -hornerD.\n  by exists (r1 + r2) => // i; rewrite coefD; apply: IH.\nhave gen_sum S := big_ind _ (gen0 S) (genD S).\npose propM (R : K -> Prop) := forall x y, R x -> R y -> R (x * y).\nhave memRM: propM memR.\n  by move=> _ _ [a ->] [b ->]; exists (a * b); rewrite rmorphM.\nhave genM S: propM (gen S).\n  elim: S => //= x S IH _ _ [r1 Sr1 ->] [r2 Sr2 ->]; rewrite -hornerM.\n  by exists (r1 * r2) => // i; rewrite coefM; apply: gen_sum => j _; apply: IH.\nhave gen_horner S r y: pXin (gen S) r -> gen S y -> gen S r.[y].\n  move=> Sq Sy; rewrite horner_coef; apply: gen_sum => [[i _] /= _].\n  by elim: {2}i => [|n IHn]; rewrite ?mulr1 // exprSr mulrA; apply: genM.\npose S := w :: q ++ p; suffices [m [X defX]]: finM memR (gen S).\n  exists m, X => M; split=> [|y /defX Xy]; first exact/defX.\n  apply/defX/genM => //; apply: gen_horner => // [i|]; last exact/genS/mem_head.\n  rewrite -[q]coefK coef_poly; case: ifP => // lt_i_q.\n  by apply: genS; rewrite inE mem_cat mem_nth ?orbT.\npose intR R y := exists r, [/\\ r \\is monic, root r y & pXin R r].\npose fix genI s := if s is y :: s1 then intR (gen s1) y /\\ genI s1 else True.\nhave{mon_p pw0 intRp intRq}: genI S.\n  split; set S1 := _ ++ _; first exists p.\n    split=> // i; rewrite -[p]coefK coef_poly; case: ifP => // lt_i_p.\n    by apply: genS; rewrite mem_cat orbC mem_nth.\n  have: all (mem S1) S1 by exact/allP.\n  elim: {-1}S1 => //= y S2 IH /andP[S1y S12]; split; last exact: IH.\n  have{q S S1 IH S1y S12 intRp intRq} [q mon_q qx0]: integralOver RtoK y.\n    by move: S1y; rewrite mem_cat => /orP[]; [apply: intRq | apply: intRp].\n  exists (map_poly RtoK q); split=> // [|i]; first exact: monic_map.\n  by rewrite coef_map /=; apply: genR.\nelim: {w p q}S => /= [_|x S IH [[p [mon_p px0 Sp]] /IH{IH}[m2 [X2 defS]]]].\n  exists 1%N, 1 => y; split=> [[a [Fa ->]] | Fy].\n    by rewrite tr_scalar_mx mulmx1; apply: Fa.\n  by exists y%:M; split=> [i|]; rewrite 1?ord1 ?tr_scalar_mx ?mulmx1 mxE.\npose m1 := (size p).-1; pose X1 := \\row_(i < m1) x ^+ i.\nhave [m [X defM]] := tensorM memR m1 m2 X1 X2; set M := memM _ _ _ in defM.\nexists m, X => y; rewrite -/M; split=> [/defM[a [M2a]] | [q Sq]] -> {y}.\n  exists (rVpoly a) => [i|].\n    by rewrite coef_rVpoly; case/insub: i => // i; apply/defS/M2a.\n  rewrite mxE (horner_coef_wide _ (size_poly _ _)) -/(rVpoly a).\n  by apply: eq_bigr => i _; rewrite coef_rVpoly_ord !mxE.\nhave M_0: M 0 by exists 0; split=> [i|]; rewrite ?mul0mx mxE.\nhave M_D: propD M.\n  move=> _ _ [a [Fa ->]] [b [Fb ->]]; exists (a + b).\n  by rewrite mulmxDl !mxE; split=> // i; rewrite mxE; apply: memRD.\nhave{M_0 M_D} Msum := big_ind _ M_0 M_D.\nrewrite horner_coef; apply: (Msum) => i _; case: i q`_i {Sq}(Sq i) => /=.\nelim: {q}(size q) => // n IHn i i_le_n y Sy.\nhave [i_lt_m1 | m1_le_i] := ltnP i m1.\n  apply/defM; exists (y *: delta_mx 0 (Ordinal i_lt_m1)); split=> [j|].\n    by apply/defS; rewrite !mxE /= mulr_natr; case: eqP.\n  by rewrite -scalemxAl -rowE !mxE.\nrewrite -(subnK m1_le_i) exprD -[x ^+ m1]subr0 -(rootP px0) horner_coef.\nrewrite polySpred ?monic_neq0 // -/m1 big_ord_recr /= -lead_coefE.\nrewrite opprD addrC (monicP mon_p) mul1r subrK !mulrN -mulNr !mulr_sumr.\napply: Msum => j _; rewrite mulrA mulrACA -exprD; apply: IHn.\n  by rewrite -addnS addnC addnBA // leq_subLR leq_add.\nby rewrite -mulN1r; do 2!apply: (genM) => //; apply: genR. \nQed.\n\nLemma integral_root_monic u p :\n    p \\is monic -> root p u -> {in p : seq K, integralRange RtoK} -> \n  integralOver RtoK u.\nProof.\nmove=> mon_p pu0 intRp; rewrite -[u]hornerX.\napply: integral_horner_root mon_p pu0 intRp _.\nby apply/integral_poly => i; rewrite coefX; apply: integral_nat.\nQed.\n\nHint Resolve (integral0 RtoK) (integral1 RtoK) (@monicXsubC K).\n\nLet XsubC0 (u : K) : root ('X - u%:P) u. Proof. by rewrite root_XsubC. Qed.\nLet intR_XsubC u :\n  integralOver RtoK (- u) -> {in 'X - u%:P : seq K, integralRange RtoK}.\nProof. by move=> intRu v; rewrite polyseqXsubC !inE => /pred2P[]->. Qed.\n\nLemma integral_opp u : integralOver RtoK u -> integralOver RtoK (- u).\nProof. by rewrite -{1}[u]opprK => /intR_XsubC/integral_root_monic; apply. Qed.\n\nLemma integral_horner (p : {poly K}) u :\n    {in p : seq K, integralRange RtoK} -> integralOver RtoK u -> \n  integralOver RtoK p.[u].\nProof. by move=> ? /integral_opp/intR_XsubC/integral_horner_root; apply. Qed.\n\nLemma integral_sub u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u - v).\nProof.\nmove=> intRu /integral_opp/intR_XsubC/integral_horner/(_ intRu).\nby rewrite !hornerE.\nQed.\n\nLemma integral_add u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u + v).\nProof. by rewrite -{2}[v]opprK => intRu /integral_opp; apply: integral_sub. Qed.\n\nLemma integral_mul u v :\n  integralOver RtoK u -> integralOver RtoK v -> integralOver RtoK (u * v).\nProof.\nrewrite -{2}[v]hornerX -hornerZ => intRu; apply: integral_horner.\nby apply/integral_poly=> i; rewrite coefZ coefX mulr_natr mulrb; case: ifP.\nQed.\n\nEnd IntegralOverComRing.\n\nSection IntegralOverField.\n\nVariables (F E : fieldType) (FtoE : {rmorphism F -> E}).\n\nDefinition algebraicOver (fFtoE : F -> E) u :=\n  exists2 p, p != 0 & root (map_poly fFtoE p) u.\n\nNotation mk_mon p := ((lead_coef p)^-1 *: p).\n\nLemma integral_algebraic u : algebraicOver FtoE u <-> integralOver FtoE u.\nProof.\nsplit=> [] [p p_nz pu0]; last by exists p; rewrite ?monic_neq0.\nexists (mk_mon p); first by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0.\nby rewrite linearZ rootE hornerZ (rootP pu0) mulr0.\nQed.\n\nLemma integral_inv u : integralOver FtoE u -> integralOver FtoE u^-1.\nProof.\nhave [-> | /expf_neq0 nz_u_n] := eqVneq u 0; first by rewrite invr0.\ncase/integral_algebraic=> p nz_p pu0; apply/integral_algebraic.\nexists (Poly (rev p)).\n  apply/eqP=> /polyP/(_ 0%N); rewrite coef_Poly coef0 nth_rev ?size_poly_gt0 //.\n  by apply/eqP; rewrite subn1 lead_coef_eq0.\napply/eqP/(mulfI (nz_u_n (size p).-1)); rewrite mulr0 -(rootP pu0).\nrewrite (@horner_coef_wide _ (size p)); last first.\n  by rewrite size_map_poly -(size_rev p) size_Poly.\nrewrite horner_coef mulr_sumr size_map_poly.\nrewrite [rhs in _ = rhs](reindex_inj rev_ord_inj) /=.\napply: eq_bigr => i _; rewrite !coef_map coef_Poly nth_rev // mulrCA.\nby congr (_ * _); rewrite -{1}(subnKC (valP i)) addSn addnC exprD exprVn ?mulfK.\nQed.\n\nLemma integral_div u v :\n  integralOver FtoE u -> integralOver FtoE v -> integralOver FtoE (u / v).\nProof. by move=> algFu /integral_inv; apply: integral_mul. Qed.\n\nLemma integral_root p u :\n    p != 0 -> root p u -> {in p : seq E, integralRange FtoE} ->\n  integralOver FtoE u.\nProof.\nmove=> nz_p pu0 algFp.\nhave mon_p1: mk_mon p \\is monic.\n  by rewrite monicE lead_coefZ mulVf ?lead_coef_eq0.\nhave p1u0: root (mk_mon p) u by rewrite rootE hornerZ (rootP pu0) mulr0.\napply: integral_root_monic mon_p1 p1u0 _ => _ /(nthP 0)[i ltip <-].\nrewrite coefZ mulrC; rewrite size_scale ?invr_eq0 ?lead_coef_eq0 // in ltip.\nby apply: integral_div; apply/algFp/mem_nth; rewrite -?polySpred.\nQed.\n\nEnd IntegralOverField.\n\n(* Lifting term, formula, envs and eval to matrices. Wlog, and for the sake  *)\n(* of simplicity, we only lift (tensor) envs to row vectors; we can always   *)\n(* use mxvec/vec_mx to store and retrieve matrices.                          *)\n(* We don't provide definitions for addition, substraction, scaling, etc,    *)\n(* because they have simple matrix expressions.                              *)\nModule MatrixFormula.\n\nSection MatrixFormula.\n\nVariable F : fieldType.\n\nLocal Notation False := GRing.False.\nLocal Notation True := GRing.True.\nLocal Notation And := GRing.And (only parsing).\nLocal Notation Add := GRing.Add (only parsing).\nLocal Notation Bool b := (GRing.Bool b%bool).\nLocal Notation term := (GRing.term F).\nLocal Notation form := (GRing.formula F).\nLocal Notation eval := GRing.eval.\nLocal Notation holds := GRing.holds.\nLocal Notation qf_form := GRing.qf_form.\nLocal Notation qf_eval := GRing.qf_eval.\n\nDefinition eval_mx (e : seq F) := map_mx (eval e).\n\nDefinition mx_term := map_mx (@GRing.Const F).\n\nLemma eval_mx_term e m n (A : 'M_(m, n)) : eval_mx e (mx_term A) = A.\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nDefinition mulmx_term m n p (A : 'M[term]_(m, n)) (B : 'M_(n, p)) :=\n  \\matrix_(i, k) (\\big[Add/0]_j (A i j * B j k))%T.\n\nLemma eval_mulmx e m n p (A : 'M[term]_(m, n)) (B : 'M_(n, p)) :\n  eval_mx e (mulmx_term A B) = eval_mx e A *m eval_mx e B.\nProof.\napply/matrixP=> i k; rewrite !mxE /= ((big_morph (eval e)) 0 +%R) //=.\nby apply: eq_bigr => j _; rewrite /= !mxE.\nQed.\n\nLocal Notation morphAnd f := ((big_morph f) true andb).\n\nLet Schur m n (A : 'M[term]_(1 + m, 1 + n)) (a := A 0 0) :=\n  \\matrix_(i, j) (drsubmx A i j - a^-1 * dlsubmx A i 0%R * ursubmx A 0%R j)%T.\n\nFixpoint mxrank_form (r m n : nat) : 'M_(m, n) -> form :=\n  match m, n return 'M_(m, n) -> form with\n  | m'.+1, n'.+1 => fun A : 'M_(1 + m', 1 + n') =>\n    let nzA k := A k.1 k.2 != 0 in\n    let xSchur k := Schur (xrow k.1 0%R (xcol k.2 0%R A)) in\n    let recf k := Bool (r > 0) /\\ mxrank_form r.-1 (xSchur k) in\n    GRing.Pick nzA recf (Bool (r == 0%N))\n  | _, _ => fun _ => Bool (r == 0%N)\n  end%T.\n\nLemma mxrank_form_qf r m n (A : 'M_(m, n)) : qf_form (mxrank_form r A).\nProof.\nby elim: m r n A => [|m IHm] r [|n] A //=; rewrite GRing.Pick_form_qf /=.\nQed.\n\nLemma eval_mxrank e r m n (A : 'M_(m, n)) :\n  qf_eval e (mxrank_form r A) = (\\rank (eval_mx e A) == r).\nProof.\nelim: m r n A => [|m IHm] r [|n] A /=; try by case r.\nrewrite GRing.eval_Pick /mxrank unlock /=; set pf := fun _ => _.\nrewrite -(@eq_pick _ pf) => [|k]; rewrite {}/pf ?mxE // eq_sym.\ncase: pick => [[i j]|] //=; set B := _ - _; have:= mxrankE B.\ncase: (Gaussian_elimination B) r => [[_ _] _] [|r] //= <-; rewrite {}IHm eqSS.\nby congr (\\rank _ == r); apply/matrixP=> k l; rewrite !(mxE, big_ord1) !tpermR.\nQed.\n\nLemma eval_vec_mx e m n (u : 'rV_(m * n)) :\n  eval_mx e (vec_mx u) = vec_mx (eval_mx e u).\nProof. by apply/matrixP=> i j; rewrite !mxE. Qed.\n\nLemma eval_mxvec e m n (A : 'M_(m, n)) :\n  eval_mx e (mxvec A) = mxvec (eval_mx e A).\nProof. by rewrite -{2}[A]mxvecK eval_vec_mx vec_mxK. Qed.\n\nSection Subsetmx.\n\nVariables (m1 m2 n : nat) (A : 'M[term]_(m1, n)) (B : 'M[term]_(m2, n)).\n\nDefinition submx_form :=\n  \\big[And/True]_(r < n.+1) (mxrank_form r (col_mx A B) ==> mxrank_form r B)%T.\n\nLemma eval_col_mx e :\n  eval_mx e (col_mx A B) = col_mx (eval_mx e A) (eval_mx e B).\nProof. by apply/matrixP=> i j; do 2![rewrite !mxE //; case: split => ?]. Qed.\n\nLemma submx_form_qf : qf_form submx_form.\nProof.\nby rewrite (morphAnd (@qf_form _)) ?big1 //= => r _; rewrite !mxrank_form_qf.\nQed.\n\nLemma eval_submx e : qf_eval e submx_form = (eval_mx e A <= eval_mx e B)%MS.\nProof.\nrewrite (morphAnd (qf_eval e)) //= big_andE /=.\napply/forallP/idP=> /= [|sAB d]; last first.\n  rewrite !eval_mxrank eval_col_mx -addsmxE; apply/implyP=> /eqP <-.\n  by rewrite mxrank_leqif_sup ?addsmxSr // addsmx_sub sAB /=.\nmove/(_ (inord (\\rank (eval_mx e (col_mx A B))))).\nrewrite inordK ?ltnS ?rank_leq_col // !eval_mxrank eqxx /= eval_col_mx.\nby rewrite -addsmxE mxrank_leqif_sup ?addsmxSr // addsmx_sub; case/andP.\nQed.\n\nEnd Subsetmx.\n\nSection Env.\n\nVariable d : nat.\n\nDefinition seq_of_rV (v : 'rV_d) : seq F := fgraph [ffun i => v 0 i].\n\nLemma size_seq_of_rV v : size (seq_of_rV v) = d.\nProof. by rewrite tuple.size_tuple card_ord. Qed.\n\nLemma nth_seq_of_rV x0 v (i : 'I_d) : nth x0 (seq_of_rV v) i = v 0 i.\nProof. by rewrite nth_fgraph_ord ffunE. Qed.\n\nDefinition row_var k : 'rV[term]_d := \\row_i ('X_(k * d + i))%T.\n\nDefinition row_env (e : seq 'rV_d) := flatten (map seq_of_rV e).\n\nLemma nth_row_env e k (i : 'I_d) : (row_env e)`_(k * d + i) = e`_k 0 i.\nProof.\nelim: e k => [|v e IHe] k; first by rewrite !nth_nil mxE.\nrewrite /row_env /= nth_cat size_seq_of_rV.\ncase: k => [|k]; first by rewrite (valP i) nth_seq_of_rV.\nby rewrite mulSn -addnA -if_neg -leqNgt leq_addr addKn IHe.\nQed.\n\nLemma eval_row_var e k : eval_mx (row_env e) (row_var k) = e`_k :> 'rV_d.\nProof. by apply/rowP=> i; rewrite !mxE /= nth_row_env. Qed.\n\nDefinition Exists_row_form k (f : form) :=\n  foldr GRing.Exists f (codom (fun i : 'I_d => k * d + i)%N).\n\nLemma Exists_rowP e k f :\n  d > 0 ->\n   ((exists v : 'rV[F]_d, holds (row_env (set_nth 0 e k v)) f)\n      <-> holds (row_env e) (Exists_row_form k f)).\nProof.\nmove=> d_gt0; pose i_ j := Ordinal (ltn_pmod j d_gt0).\nhave d_eq j: (j = j %/ d * d + i_ j)%N := divn_eq j d.\nsplit=> [[v f_v] | ]; last case/GRing.foldExistsP=> e' ee' f_e'.\n  apply/GRing.foldExistsP; exists (row_env (set_nth 0 e k v)) => {f f_v}// j.\n  rewrite [j]d_eq !nth_row_env nth_set_nth /=; case: eqP => // ->.\n  by case/imageP; exists (i_ j).\nexists (\\row_i e'`_(k * d + i)); apply: eq_holds f_e' => j /=.\nmove/(_ j): ee'; rewrite [j]d_eq !nth_row_env nth_set_nth /=.\ncase: eqP => [-> | ne_j_k -> //]; first by rewrite mxE.\napply/mapP=> [[r lt_r_d]]; rewrite -d_eq => def_j; case: ne_j_k.\nby rewrite def_j divnMDl // divn_small ?addn0.\nQed.\n\nEnd Env.\n\nEnd MatrixFormula.\n\nEnd MatrixFormula.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect1.4_v8.3/theories/mxpoly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7021321508218397}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import Bool.\n\nLemma n1 : forall x : nat, 1 + x = S x.\nProof.\ntrivial. Qed.\n\nDefinition n2 : forall x y : nat, S x + y = S(x + y).\nProof.\nAdmitted. \n(* Use Admitted so that we can work on more difficult asserts\nbefore. We can search in built theorems that prove\nthe \"trivialities\".*)\n\n\n\nRequire Import List.\nRequire Import Arith.\nRequire Import Bool.\n\nFrom Coq Require Import ssreflect ssrfun ssrbool.\nFrom mathcomp Require Import eqtype ssrnat div prime. \n\nNotation \"x | y\" := (y mod x = 0)\n(at level 50, left associativity).\n\nLemma one_div_all_nat : forall n : nat, 1 | n.\nProof.\nintro. simpl. reflexivity. Qed.\n\nLemma k_div_k_times_n : forall (k n : nat), (k > 0) -> (k | n*k).\nProof.\nintros.\ninduction k as [|k']. \n  trivial.\nAdmitted.\n\n(* A nice proof of the infinitude of primes, by Georges Gonthier *)\nLemma infinite_prime_above m : {p | m < p & prime p}.\nProof. \n\nhave /pdivP[p pr_p p_dv_m1]: 1 < m`! + 1\n  by rewrite addn1 ltnS fact_gt0.\n\nexists p => //; rewrite ltnNge; apply: contraL p_dv_m1 => p_le_m.\n\nby rewrite dvdn_addr ?dvdn_fact ?prime_gt0 // gtnNdvd ?prime_gt1.\nQed.\n\n\n\n\n \n\n ", "meta": {"author": "Caue-Aramaki", "repo": "random_pushes_caue_aramaki", "sha": "da1274778c7106d6e3cb46e21f0b0f7bb0eef624", "save_path": "github-repos/coq/Caue-Aramaki-random_pushes_caue_aramaki", "path": "github-repos/coq/Caue-Aramaki-random_pushes_caue_aramaki/random_pushes_caue_aramaki-da1274778c7106d6e3cb46e21f0b0f7bb0eef624/coq codes/test3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7021321473635137}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (y : natural) (x : natural) (lf2 : natural)\n  : natural := mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj164_coqofml_iN9SId.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7021321440958654}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (x : natural) (y : natural) (lf2 : natural)\n  : natural := plus Zero (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_commut/goal33conj187_coqofml_8uRaj4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7021321374652297}}
{"text": "(*  AGCT in Coq *)\n \nRequire Import List.\n \nInductive dna : Type :=\n  | A : dna\n  | G : dna\n  | C : dna\n  | T : dna.\n \nNotation \"[ ]\" := nil.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n \nFixpoint selection_aux(n:nat)(xs:list (list dna)):list (list dna) :=\nmatch n with\n| O => xs\n| S n' => let ys := selection_aux n' xs in\n  fold_left \n    (fun stat x => stat ++ (map (fun s => x :: s) ys)) \n    [A, G, C, T]    \n    []\nend.\nDefinition selection(n:nat) := selection_aux n [[]].\n \nDefinition beq_dna (a b : dna) : bool :=\n  match a, b with\n  | A, A => true\n  | G, G => true\n  | C, C => true\n  | T, T => true\n  | _, _ => false\n  end.\n \nFixpoint match_left (xs ys : list dna) : bool :=\n  match xs, ys with\n  | [], _ => true\n  | x :: xs', [] => false\n  | x :: xs', y :: ys' =>\n      if beq_dna x y then match_left xs' ys'\n               else false\n  end.\n \nFixpoint contains_dna (xs ys : list dna) : bool :=\n  match ys with\n  | [] => false\n  | y :: ys' =>\n      if match_left xs ys then true\n                       else contains_dna xs ys'\n  end.\n \nEval compute in filter (fun x => contains_dna [A, A, G] x) (selection 4).\n(*\n     = [[A, A, A, G], [A, A, G, A], [A, A, G, G], [A, A, G, C], [A, A, G, T],\n       [G, A, A, G], [C, A, A, G], [T, A, A, G]]\n     : list (list dna)\n*)", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/totorial20120216/acgt_sample1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7021304701780146}}
{"text": "(***************************************************************************)\n(*   This is part of FA_Landau, it is distributed under the terms of the   *)\n(*             GNU Lesser General Public License version 3                 *)\n(*                (see file LICENSE for more details)                      *)\n(*                                                                         *)\n(*           Copyright 2020-2022: Yaoshun Fu and Wensheng Yu.              *)\n(***************************************************************************)\n\nRequire Export Nats.\n\nInductive Compose {U V W} (f :Relation U V) (g :Relation V W) x y :Prop :=\n  | Com_intro: ∀ z, f x z -> g z y -> Compose f g x y.\n\nCorollary comp : \n  ∀ {U V W A B C} {f :Relation U V} {g :Relation V W},\n  Surjection A B f -> Surjection B C g -> Surjection A C (Compose f g).\nProof.\n  intros; red; repeat split; intros; try red; intros.\n  - destruct H1, H2.\n    assert (z0 = z1). { eapply H; eauto. }\n    subst z0; eapply H0; eauto.\n  - apply H in H1; destruct H1; pose proof H1.\n    apply H in H2; apply H0 in H2; destruct H2.\n    exists x1; econstructor; eauto.\n  - apply H0 in H1; destruct H0 as [_ [_ [_ [H0 _]]]], H1.\n    pose proof H1; apply H0 in H1.\n    apply H in H1; destruct H1. exists x0; econstructor; eauto.\n  - destruct H1; eapply H; eauto.\n  - destruct H1; eapply H0; eauto.\nQed.\n\nDefinition Fin_En x := /{ z | z < x /}.\nDefinition fin {U} (A :Ensemble U) := (∃ x f, Surjection (Fin_En x) A f).\n\nInductive RelE {U} (A :Ensemble U)(x :Nat) y :=\n  | RelE_intro : y ∈ A -> RelE A x y.\n\nCorollary Fin_Empty : ∀ {U} (A :Ensemble U), ~ No_Empty A -> fin A.\nProof.\n  intros; exists 1,(RelE A); red; repeat split;\n  try red; intros; try (destruct H0; elim H; red; eauto).\n  - N1F H0.\n  - destruct H; red; eauto.\nQed.\n\nInductive RelUn {U} p q (f g :Relation Nat U) x r :Prop :=\n  | RelUn_intro : x < p -> f x r -> RelUn p q f g x r\n  | RelUn_intro' : ∀ H :p ≦ x, x ≦ (p + q)\n    -> g (((x + 1) - p) (Theorem26' H)) r -> RelUn p q f g x r.\n\nCorollary Fin_Union : ∀ {U} {A B :Ensemble U}, \n  fin A -> fin B -> fin (A ∪ B).\nProof.\n  intros; destruct H as [x [f1 H]], H0 as [y [f2 H0]].\n  set (f3 := RelUn x y f1 f2); red. exists (((x + y) - 1) N1P), f3.\n  red; repeat split; try red; intros.\n  - destruct H1, H2; [|LEGN H2 H1|LEGN H1 H2|].\n    * apply H with x0; auto.\n    * rewrite (proof_irr H2 H1) in H6; eapply H0; eauto.\n  - destruct H as [_ [H _]],  H0 as [_ [H0 _]], H1; red in H, H0.\n    destruct (classic (x ≦ x0)) as  [H2 | H2].\n    * apply Theorem26' in H2.\n      destruct H0 with (Minus_N (x0 + 1) x H2); try constructor.\n      + apply Theorem19_1 with (z:=1) in H1; Simpl_Nin H1.\n        apply Theorem20_1 with (z:=x); Simpl_N.\n        rewrite Theorem6; auto.\n      + apply Theorem19_1 with (z:=1) in H1; Simpl_Nin H1.\n        pose proof H2. apply Theorem26 in H4.\n        rewrite (proof_irr H2 (Theorem26' H4)) in H3.\n        exists x1; constructor 2 with H4; auto.\n        left; eapply Theorem15; eauto. apply Nlt_S_.\n    * apply property_not in H2; destruct H2.\n      destruct (Theorem10 x x0) as [H4 | [H4 | H4]]; try tauto.\n      destruct H with x0; try constructor; auto.\n      exists x1; constructor; auto; red; auto.\n  - destruct H1, H1, H as [_ [_ [H]]], H0 as [_ [_ [H0]]], H2, H3.\n    * destruct H with y0; auto. exists x0; constructor; auto.\n      apply H2 in H6; destruct H6; auto.\n    * destruct H0 with y0; auto; destruct (H3 _ _ H6).\n      assert (x ≦ ((Minus_N (x0 + x) 1 N1P))).\n      { destruct x0.\n        - right; apply Theorem20_2 with (z:=1); Simpl_N.\n        - left; apply Theorem20_1 with (z:=1); Simpl_N.\n          rewrite Theorem6; exists x0; Simpl_N. }\n      exists ((Minus_N (x0 + x) 1 N1P)). econstructor 2 with H8.\n      + left; apply Theorem20_1 with (z:=1); Simpl_N.\n        apply Theorem19_1 with (z:=x) in H7.\n        eapply Theorem15; eauto. rewrite Theorem6. apply Nlt_S_.\n      + assert (x0 = \n          (Minus_N (Minus_N (x0 + x) 1 N1P + 1) x (Theorem26' H8))).\n        { apply Theorem20_2 with (z:=x); Simpl_N. }\n        { rewrite <- H9; auto. }\n  - destruct H1; auto.\n    * exists (Minus_N ((Minus_N x x0 H1) + y) 1 N1P).\n      apply Theorem20_2 with (z:=1).\n      rewrite Theorem5; Simpl_N.\n      rewrite <- Theorem5,(Theorem6 x0 (Minus_N x x0 H1));Simpl_N.\n    * destruct H0 as [_ [_ [_ [H0 _]]]]. apply H0 in H3. \n      destruct H3. apply Theorem19_1 with (z:=x) in H3.\n      Simpl_Nin H3. rewrite <- NPl_1, Theorem6 in H3.\n      exists (Minus_N (x + y) (x0 + 1) H3).\n      apply Theorem20_2 with (z:=(x0 + 1)).\n      rewrite Theorem5; Simpl_N.\n      rewrite <- NPlS_, Theorem6; f_equal; Simpl_N.\n  - destruct H1.\n    * apply H in H2; auto. * apply H0 in H3; auto.\nQed.\n\nInductive RelAB {U V} A B v (f :Relation U V) x y :Prop :=\n  | Como1_intro : x ∈ A -> f x y -> RelAB A B v f x y\n  | Como1_intro' : ~ x ∈ A -> x ∈ B -> y = v -> RelAB A B v f x y.\n\nCorollary Fin_EleUnion :  ∀ {U B}, fin B -> \n  (∀ b :Ensemble U, b ∈ B -> fin b) -> fin (∪ B).\nProof.\n  intros; destruct H as [x [f H]].\n  generalize dependent B; generalize dependent f;\n  generalize dependent x; induction x; intros.\n  - apply Fin_Empty; intro; destruct H1, H1, H1, H1.\n    apply H in H1; destruct H1, H as [_ [_ [_ [H _]]]].\n    apply H in H1; destruct H1. N1F H1.\n  - rename H0 into H1; rename H into H0; rename IHx into H.\n    destruct H0, H2, H3, H4; red in H0, H2, H3.\n    destruct H2 with x as [b H6]. constructor; apply Nlt_S_.\n    assert (∪ B = (∪ /{ z | z ∈ B /\\ z <> b/}) ∪ b).\n    { apply ens_ext; red; split; intros; destruct H7; constructor.\n      - destruct H7, H7, (classic (x0 ∈ b)); auto.\n        left; constructor. exists x1; split; auto.\n        constructor; split; auto. intro; subst b; auto.\n      - destruct H7; eauto. destruct H7, H7, H7, H7, H7; eauto. }\n    rewrite H7; apply Fin_Union.\n    + set (B':= /{ z | z ∈ B /\\ z <> b /}).\n      set (A:=/{ z | ∃ b', (b' ∈ B') /\\ (f z b') /}).\n      assert ((~ ∃ c, c ∈ B /\\ c <> b) -> fin (EleUnion B')) as G.\n      { intros. apply Fin_Empty; intro.\n        destruct H9, H9, H9, H9, H9, H9. apply H8; eauto. }\n      destruct (classic (∃ c, c ∈ B /\\ c <> b)) as [H8 | H8];auto.\n      destruct H8, H8. apply H with (RelAB A (Fin_En x) x0 f).\n      red; repeat split; try red; intros. \n      { destruct H10, H11; try tauto.\n        - eapply H0; eauto. - subst y z; auto. }\n      { destruct (classic (x1 ∈ A)).\n        - destruct H10, H2 with x1.\n          + constructor; eapply Theorem15; eauto. apply Nlt_S_.\n          + exists x2; constructor; auto.\n        - exists x0; constructor 2; eauto. }\n      { destruct H10, H10, H3 with y; auto. \n        exists x1; constructor; auto.\n        constructor; exists y; split; auto. constructor; auto. }\n      { destruct H10.\n        - destruct H10, H10, H10, H10, H10.\n          eapply H0 in H12; eauto; subst x2.\n          pose proof H11; apply H4 in H11; destruct H11.\n          apply Theorem26 in H11. destruct H11; auto.\n          subst x1. elim H13; eapply H0; eauto.\n        - destruct H11; auto. }\n      { destruct H10;[eapply H5; eauto|subst y; auto]. }\n      { subst y; destruct H10.\n        - destruct H10,H10,H10,H10,H10. apply H13; eapply H0;eauto.\n        - subst x0; auto. }\n      { intros; destruct H10, H10; auto. }\n  + apply H5 in H6; auto.\nQed.\n\nCorollary Fin_Included : ∀ {U} (A B :Ensemble U), \n  A ⊂ B -> fin B -> fin A.\nProof.\n  intros; red. pose proof (Fin_Empty A) as G.\n  destruct (classic (No_Empty A)) as [H1 | H1]; try tauto.\n  destruct H0 as [N [f H0]], H1 as [u H1].\n  set (A1:=/{ z | ∃ b', (b' ∈ A) /\\ (f z b') /}).\n  assert (A1 ⊂ (Fin_En N)).\n  { red; intros; destruct H2, H2, H2. eapply H0; eauto. }\n  exists N, (RelAB A1 (Fin_En N) u f). red; repeat split; try red; intros.\n  - destruct H3, H4; try tauto;[eapply H0; eauto|subst y z; auto].\n  - destruct (classic (x ∈ A1)).\n    * apply H0 in H3. destruct H3 as [y H3]. exists y; constructor; auto.\n    * exists u; constructor 2; eauto.\n  - pose proof H3. apply H, H0 in H3. destruct H3.\n    exists x. constructor; auto. constructor. exists y; auto.\n  - destruct H3; [|destruct H4; auto]. destruct H0 as [_ [_ [_ [H0 _]]]].\n    apply H0 in H4. destruct H4; auto.\n  - destruct H3; [|subst u; auto]. destruct H3, H3, H3.\n    assert (x0 = y); try eapply H0; eauto. subst y; auto.\nQed.\n", "meta": {"author": "coderfys", "repo": "Analysis", "sha": "1610987e019c90a08db4b788564fb0c2c91eebed", "save_path": "github-repos/coq/coderfys-Analysis", "path": "github-repos/coq/coderfys-Analysis/Analysis-1610987e019c90a08db4b788564fb0c2c91eebed/extension/finite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7021304661308543}}
{"text": "Require Import List reduction basic ZArith.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nInductive Stack_Action (alphabet : Type) : Type :=\n  eps_action : Stack_Action alphabet\n| push_action : alphabet -> Stack_Action alphabet\n| pop_action : alphabet -> Stack_Action alphabet.\n\nInductive Allow_SAs (A : Type) : list (Stack_Action A) -> Prop :=\n| allow_empty : Allow_SAs []\n| allow_eps : forall κ, Allow_SAs κ -> Allow_SAs (κ ++ [eps_action _])\n| allow_push : forall κ γ, Allow_SAs κ -> Allow_SAs (κ ++ [push_action γ])\n| allow_pop : forall κ γ, Allow_SAs (κ++[push_action γ]) -> Allow_SAs (κ++[push_action γ; pop_action γ]).\n\nDefinition Allow_SA (A : Type) : list (Stack_Action A) -> (Stack_Action A) -> Prop :=\n  fun κ a => Allow_SAs (κ ++ [a]).\nDefinition kont_to_actions {A} (κ : list A) : list (Stack_Action A) := map (@push_action _) (rev κ).\n\nInductive Balanced_action_red (A : Type) : list (Stack_Action A) -> list (Stack_Action A) -> Prop :=\n  balance_eps : forall las ras,\n                  Balanced_action_red (las ++ (eps_action A :: ras)) (las ++ ras)\n| balance_cancel : forall las ras γ,\n                      Balanced_action_red (las ++ [push_action γ; pop_action γ] ++ ras)\n                                          (las ++ ras).\nInductive Actions_form_kont (A : Type) : list (Stack_Action A) -> list A -> Prop :=\n  mt_kont : Actions_form_kont [] []\n| push_kont : forall actions γ κ, Actions_form_kont actions κ ->\n                                  Actions_form_kont (actions ++ [push_action γ]) (γ :: κ).\n\nDefinition Balanced_actions (A : Type) := direct_clos_refl_trans (@Balanced_action_red A).\nDefinition Balance_to_kont_P (A : Type) (actions : list (Stack_Action A)) (κ : list A) :=\n  fun actions' => Balanced_actions actions actions' /\\ Actions_form_kont actions' κ.\n\nDefinition Balance_to_kont (A : Type) (actions : list (Stack_Action A)) (κ : list A) : Prop :=\n  ex (Balance_to_kont_P actions κ).\n\n(* one pass of cancellation *)\nFixpoint remove_cancel {A} (eq_dec : dec_type A) (l : list (Stack_Action A)) :=\n  match l with\n      nil => nil\n    | eps_action::l' => (eps_action _)::l'\n    | push_action γ::l' => match l' with\n                             | pop_action γ'::l'' =>\n                               if (eq_dec γ γ') then\n                                 (remove_cancel eq_dec l'')\n                               else \n                                 push_action γ :: pop_action γ' :: (remove_cancel eq_dec l'')\n                             | _ => push_action γ :: (remove_cancel eq_dec l')\n                           end\n    | pop_action γ::l' => pop_action γ :: (remove_cancel eq_dec l')\n  end.\nFunctional Scheme remove_cancel_ind := Induction for remove_cancel Sort Prop.\n\nFixpoint remove_cancel_n {A} (eq_dec : dec_type A) (n : nat)  (acc : list (Stack_Action A)) :=\n  match n with\n      0 => acc\n    | S n' => remove_cancel_n eq_dec n' (remove_cancel eq_dec acc)\n  end.\n\nLemma balance_actions_at_end : forall A (actions actions' : list (Stack_Action A)),\n                                   Balanced_actions actions actions' ->\n                                   forall actions'',\n                                   Balanced_actions (actions ++ actions'') (actions' ++ actions'').\nProof.\n  intros ? ? ? H; induction H as [|? ? ? ? ? Hred];intro actions''.\n  constructor.\n  inversion Hred;\n  subst;\n  eapply (drt_append (IHdirect_clos_refl_trans actions''));\n  eapply drt_step; auto;\n  do 2 rewrite <- app_assoc.\n  eapply balance_eps.\n  eapply balance_cancel.\nQed.\n\nLemma balance_actions_at_front : forall A (actions actions' : list (Stack_Action A)),\n                                   Balanced_actions actions actions' ->\n                                   forall actions'',\n                                   Balanced_actions (actions'' ++ actions) (actions'' ++ actions').\nProof.\n  intros ? ? ? H; induction H as [|? ? ? ? ? Hred];intro actions''.\n  constructor.\n  inversion Hred;\n  subst;\n  eapply (drt_append (IHdirect_clos_refl_trans actions''));\n  eapply drt_step; auto;\n  do 2 rewrite app_assoc.\n  eapply balance_eps.\n  eapply balance_cancel.\nQed.\n\nTheorem remove_eps_balances : forall A (l : list (Stack_Action A)), Balanced_actions l (remove_eps l).\nProof.\n  induction l;[constructor|simpl; destruct a as [|γ|γ]].\n  eapply (drt_append _ IHl). (* grab _ at end *)\n  eapply (balance_actions_at_front IHl [push_action γ]).\n  eapply (balance_actions_at_front IHl [pop_action γ]).\nGrab Existential Variables.\neapply drt_step; [apply drt_refl|apply (balance_eps [] l)].\nQed.\n\nTheorem remove_cancel_balances : forall A (eq_dec : dec_type A) (l : list (Stack_Action A)),\n                                   Balanced_actions l (remove_cancel eq_dec l).\nProof.\n  intros ? ? l; apply remove_cancel_ind; intros; subst;\n  try solve [constructor\n            |simpl; apply drt_refl \n            |apply (balance_actions_at_front (drt_refl _ l') [eps_action _])\n            |apply (balance_actions_at_front H [push_action γ])\n            |apply (balance_actions_at_front H [pop_action γ])\n            |apply (balance_actions_at_front H [push_action γ; pop_action γ'])].\n  intros; subst; eapply (drt_append _ H).\n  Grab Existential Variables.\n  eapply drt_step; [apply drt_refl|apply (balance_cancel [] l'')].\nQed.\n\nLemma balance_length : forall A (l l' : list (Stack_Action A)),\n                         l <> l' -> Balanced_action_red l l' -> length l' < length l.\nProof.\n  intros ? ? ? Hneq H; hnf in H; inversion H; subst; do 2 rewrite app_length; simpl; omega.\nQed.\n\nLemma remove_cancel_le : forall A (eq_dec : dec_type A) (l : list (Stack_Action A)),\n                           length (remove_cancel eq_dec l) <= length l.\nProof.\n  intros ? ? l; apply remove_cancel_ind; intros; subst; try solve [auto | unfold length in *; omega].\nQed.  \n\nLemma remove_cancel_same_length_eq : forall A (eq_dec : dec_type A) (l : list (Stack_Action A)),\n                                       length (remove_cancel eq_dec l) = length l ->\n                                       remove_cancel eq_dec l = l.\nProof.\n  intros ? ? l; apply remove_cancel_ind; intros; subst; auto.\n  f_equal; apply H; auto.\n  pose (contr := remove_cancel_le eq_dec l'');\n  unfold length in *; elimtype False; omega.\n  do 2 f_equal; apply H; simpl in H0; omega.\n  f_equal; apply H; auto.\nQed. \n\nLemma idempotent_remains : forall A (eq_dec : dec_type A) l, remove_cancel eq_dec l = l ->\n                                                             forall n, remove_cancel_n eq_dec n l = l.\nProof.\n  induction n; [|simpl; rewrite H,IHn];reflexivity.\nQed.\n\nTheorem remove_cancel_n_idempotency : forall A (eq_dec : dec_type A) n' n l,\n                                        length l <= n -> n <= n' ->\n                                        remove_cancel_n eq_dec n l = remove_cancel_n eq_dec n' l.\nProof.\n  induction n'.\n  intros.\n  inversion H0; subst; reflexivity.\n  intros n l Hle HSnle.\n  simpl.\n  rewrite NPeano.Nat.le_lteq in HSnle.\n  inversion HSnle as [Hnlt|Hneq]; [|subst; reflexivity].\n  destruct n.\n  cut (l = []); [clear IHn' HSnle Hnlt;\n                  intros; subst; simpl; induction n'; simpl; [reflexivity|auto]\n                |destruct l; [auto|elimtype False; simpl in Hle; omega]].\n  rewrite NPeano.Nat.le_lteq in Hle.\n  inversion Hle as [lenlt|crap].\n  simpl; apply IHn'; [cut (length (remove_cancel eq_dec l) <= length l); [omega|apply remove_cancel_le]\n                     |omega].\n  cut (length (remove_cancel eq_dec l) <= S n).\n  intro crap'; rewrite NPeano.Nat.le_lteq in crap'.\n  inversion crap' as [less|idemp];\n    [simpl; apply IHn'; omega\n    |].\n  rewrite <- crap in idemp.\n  apply remove_cancel_same_length_eq in idemp.\n  simpl. rewrite idemp; rewrite idempotent_remains; [rewrite idempotent_remains; [reflexivity|] |]; auto.\n  pose (remove_cancel_le eq_dec l); omega.\nQed.\n\nLemma remove_eps_idemponent : forall A (l : list (Stack_Action A)), remove_eps (remove_eps l) = remove_eps l.\nProof.\n  induction l; [reflexivity|simpl; destruct a; simpl; [|f_equal|f_equal]; rewrite IHl; try reflexivity].\nQed.\n\nConjecture confluent_eps : forall A (l l' : list (Stack_Action A)),\n                          (remove_eps l) = (remove_eps l') ->\n                          length l' <= length l ->\n                          Balanced_actions l l'.\n\nLtac list_unit :=\n  match goal with [H : ?l ++ ?r = [?x] |- _] => apply app_eq_unit in H; inversion_clear H as [[? ?]|[? ?]]; subst end.\n\nConjecture balance_remove_stuck : forall A (actions' actions : list (Stack_Action A)) γ,\n                                    Balanced_actions (actions ++ [push_action γ]) (actions' ++ [push_action γ]) ->\n                                    Balanced_actions actions actions'.\n  \nLemma kont_to_actions_balanced : forall A (κ : list A), Balance_to_kont (kont_to_actions κ) κ.\nProof.\n  induction κ as [|γ κ IH].\n  exists []; repeat constructor.\n  unfold kont_to_actions; rewrite map_rev; simpl.\n  destruct IH as [actions [H0 H1]].\n  exists (actions ++ [push_action γ]); split.\n  eapply balance_actions_at_end; rewrite <- map_rev; auto.\n  constructor; auto.\nQed.\n\nSection ExtraListFacts.\nDefinition res A l := (fun l' : list A => {last : A & l = l' ++ [last]}).\nDefinition all_but_last {A} (lstart : list A) (nnilstart : lstart <> nil) : sigT (res lstart).\nrefine ((fix abl l (nnil : l <> nil) : sigT (res l) :=\n          (match l as l_ return (l = l_ -> _) with\n              nil => fun H : l = nil => match (nnil H) with end\n            | a::l' => fun H : l = a::l' =>\n                         (match l' as l'_ return (l' = l'_ -> sigT (res l)) with\n                              nil => fun H' : l' = nil =>\n                                       existT (res l) [] \n                                              (existT (fun lst : A => l = [] ++ [lst]) \n                                                      a\n                                                      _ (* goal 1 *))\n                            | a'::l'' => fun H' : l' = a'::l'' =>\n                                           match (abl l' _ (* goal 2 *)) with\n                                               | existT abll (existT last prf) =>\n                                                 existT (res l)\n                                                        (a::abll)\n                                                        _ (* goal 3 *)\n                                                        (*(existT (fun lst : A => l = l' ++ [lst]) last _)*)\n                                           end\n                          end (eq_refl l'))\n          end (eq_refl l))) lstart nnilstart).\nrewrite H' in H; assumption.\nintro bad; rewrite bad in H'; discriminate.\nexists last; rewrite H; simpl; f_equal; assumption.\nDefined. \n\nLemma nonempty_right_app_last' : forall A (r l res : list A) (last : A)\n                                 (H : r <> nil)\n                                 (Heq : l ++ r = res ++ [last])\n                                 abl sub\n                                 (ablH : (all_but_last H) = existT _ abl sub)\n                                 last' Heq'\n                                 (subeq : sub = existT _ last' Heq'),\n                                   l ++ abl = res /\\ last = last' /\\ r = abl ++ [last].\nProof.\n  induction r; intros.\n  destruct abl; discriminate.\n  subst.\n  destruct r as [|a' r'].\n  destruct (all_but_last H). \n  cut (abl = []);\n    [intro; subst; simpl in Heq'; injects Heq';\n     apply app_inj_tail in Heq; autorewrite with list; intuition (simpl; subst; auto)\n    |destruct abl; [reflexivity\n                   |simpl in Heq'; injects Heq'; destruct abl; discriminate]].\n  specialize (IHr (l ++ [a]) res0 last).\n  cut (a' :: r' <> []); [intro use|discriminate].\n  rewrite app_assoc_reverse in IHr;\n  case_eq (all_but_last use); intros lx Pr use';\n  case_eq Pr; intros xa appeq use''; specialize (IHr use Heq _ _ use' _ _ use'').\n  destruct IHr as [IHleq [IHlasteq IHableq]].\n  subst.\n  destruct (all_but_last H); injects ablH.\n  destruct (exists_last use) as [l_ [a_ arlast]].\n  rewrite arlast in *.\n  apply app_inj_tail in IHableq.\n  destruct IHableq as [leq_ aeq_]; subst.\n\n  cut (abl = a :: lx /\\ xa = last');\n    [intros [Habl xalst]; subst abl; rewrite app_assoc_reverse; auto\n    |clear ablH H0;\n      rewrite appeq in Heq';\n      cut ((a :: lx) ++ [xa] = abl ++ [last']);\n      [intro Hinj; apply app_inj_tail in Hinj; destruct Hinj; auto\n      |simpl; auto]].\nQed.\n\nLemma nonempty_right_app_last : forall A (r l res : list A) (last : A),\n                                  r <> nil ->\n                                  l ++ r = res ++ [last] ->\n                                  exists r', r = r' ++ [last].\nProof.\n  intros.\n  case_eq (all_but_last H); intros x rr H1.\n  case_eq rr; intros ? ? H2.\n  pose (@nonempty_right_app_last' _ r l res0 last H H0 _ _ H1 _ _ H2).\n  exists x; intuition.\nQed.\nEnd ExtraListFacts.\n\nLemma push_end_remains : forall A actions actions' (γ : A),\n                           Balanced_actions (actions ++ [push_action γ]) actions' ->\n                           exists actions'', actions' = actions'' ++ [push_action γ].\nProof.\n  intros ? ? ? ? H; unfold Balanced_actions in H; rewrite drt_family_iff_index in H; induction H as [|foo bar baz IH].\n  exists actions; auto.\n  rewrite <- drt_family_iff_index in baz.\n  destruct IH as [actions'' Heq].\n  subst.\n  inversion H; subst.\n  - revert actions'' baz H H1.\n  induction las;\n  intros actions'' bar H H1.\n  destruct actions'' as [|act actions''']; simpl in H1; \n    [discriminate|exists actions'''; injects H1; auto].\n  cut (eps_action _:: ras <> []);[|intro bad; discriminate].\n  intro Hne; destruct (@nonempty_right_app_last _ (eps_action _ :: ras) (a :: las) actions'' (push_action γ) Hne H1) as [r' Hr'];\n  destruct r' as [|ra r''];[discriminate|];\n  exists ((a :: las) ++ r'');\n  simpl in Hr'; injects Hr'; auto; simpl; rewrite app_assoc; auto.\n  - revert actions'' baz H H1.\n  induction las;\n  intros actions'' bar H H1.\n  destruct actions'' as [|act actions''']; simpl in H1; \n    [discriminate|destruct actions''' as [|act' actions''''];\n                   [discriminate\n                   |exists actions''''; simpl in H1; injects H1; auto]].  \n  cut (push_action γ0 :: pop_action γ0 :: ras <> []);[|intro bad; discriminate].\n  intro Hne; destruct (@nonempty_right_app_last _ (push_action γ0 :: pop_action γ0 :: ras) (a :: las) actions'' (push_action γ) Hne H1) as [r' Hr'];\n  destruct r' as [|ra r''];[discriminate|destruct r'' as [|ra' r'''];[discriminate|]];\n  exists ((a :: las) ++ r''');\n  simpl in Hr'; injects Hr'.\nsimpl; f_equal. rewrite app_assoc; reflexivity.\nQed.\n\nHint Resolve kont_to_actions_balanced.\n", "meta": {"author": "deeglaze", "repo": "concrete-summaries", "sha": "2be8622f2c79734f6c0060013b56807ab83992fe", "save_path": "github-repos/coq/deeglaze-concrete-summaries", "path": "github-repos/coq/deeglaze-concrete-summaries/concrete-summaries-2be8622f2c79734f6c0060013b56807ab83992fe/balance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7021304634944077}}
{"text": "Require Import PeanoNat.\n\nLemma leq_and_not: forall x y, x <= S y -> x = S y \\/ x <= y.\nProof.\n  intro x.\n  case x.\n  + right.\n    exact (le_0_n _).\n  + intros n y H.\n    case (le_S_n _ _ H).\n    - left.\n      reflexivity.\n    - right.\n      apply le_n_S.\n      assumption.\nQed.\n\nLemma leq_and_not': forall x y, x <= S y -> x <> S y -> x <= y.\nProof.\n  intros x y H.\n  case (leq_and_not _ _ H).\n  - contradiction.\n  - intros.\n    assumption.\nQed.\n\nLemma leq_and_not'': forall x y, x <= y -> x <> y -> x <= pred y.\nProof.\n  intro x.\n  induction y.\n  - intros H H0.\n    pose (p := proj1 (Nat.le_0_r x) H).\n    contradiction.\n  - apply leq_and_not'.\nQed.\n\nLemma le_sub: forall n x y, n + x <= y -> n <= y - x.\nProof.\n  intros n x y H.\n  assert (x <= y) as H0.\n  - pose (p := Nat.add_le_mono 0 n x x (le_0_n _) (le_n _)).\n    Nat.order.\n  - assert (y = y - x + x) as H1.\n    + symmetry.\n      exact (Nat.sub_add x y H0).\n    + rewrite H1 in H.\n      rewrite (Nat.add_comm n x) in H.\n      rewrite (Nat.add_comm (y - x) x) in H.\n      exact (proj2 (Nat.add_le_mono_l n (y-x) x) H).\nQed.\n\nLemma le_sub_ident: forall n x y, n + x <= y -> y = y - x + x.\nProof.\n  intros n x y H.\n  assert (x <= y) as H0.\n  - pose (p := Nat.add_le_mono 0 n x x (le_0_n _) (le_n _)).\n    Nat.order.\n  - symmetry.\n    exact (Nat.sub_add x y H0).\nQed.\n", "meta": {"author": "rootmos", "repo": "coq-hack", "sha": "957da2727d3d269c0c12fe9294cba33b437da738", "save_path": "github-repos/coq/rootmos-coq-hack", "path": "github-repos/coq/rootmos-coq-hack/coq-hack-957da2727d3d269c0c12fe9294cba33b437da738/src/CMP/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7021304521507737}}
{"text": "\n\n(** In this file, we define more advanced linear algebra concepts such as bases, linear independence, etc... *)\n\n\nRequire Import Psatz.  \nRequire Import Reals.\n  \nRequire Export Matrix.\n\n\n(************************************)\n(** * some preliminary defs and lemmas *)\n(************************************)\n\nLocal Open Scope nat_scope.\n\n\nDefinition e_i {n : nat} (i : nat) : Vector n :=\n  fun x y => (if (x =? i) && (x <? n) && (y =? 0) then C1 else C0). \n\n(* using previous def's, takes matrix and increases its rank by 1 (assuming c <> 0) *)\nDefinition pad1 {n m : nat} (A : Matrix n m) (c : C) : Matrix (S n) (S m) :=\n  col_wedge (row_wedge A Zero 0) (c .* e_i 0) 0.\n\nLemma WF_pad1 : forall {n m : nat} (A : Matrix n m) (c : C),\n  WF_Matrix A <-> WF_Matrix (pad1 A c).\nProof. unfold WF_Matrix, pad1. split.\n       - intros. \n         unfold col_wedge, row_wedge, e_i, scale.\n         bdestruct (y <? 0); bdestruct (y =? 0); try lia. \n         destruct H0; try lia. \n         bdestruct (x =? 0); bdestruct (x <? n); try lia; try easy.\n         lca.  \n         destruct y; try lia. \n         rewrite Sn_minus_1. \n         bdestruct (x <? 0); bdestruct (x =? 0); try lia; try easy. \n         destruct x; try lia. \n         rewrite Sn_minus_1.\n         apply H; lia. \n       - intros. \n         unfold col_wedge, row_wedge, e_i in H.\n         rewrite <- (H (S x) (S y)); try lia. \n         bdestruct (S y <? 0); bdestruct (S y =? 0); try lia. \n         bdestruct (S x =? 0); bdestruct (S x <? 0); try lia; try easy.\n         do 2 rewrite Sn_minus_1; easy.\nQed.\n\nLemma WF_e_i : forall {n : nat} (i : nat),\n  WF_Matrix (@e_i n i).\nProof. unfold WF_Matrix, e_i.\n       intros; destruct H as [H | H].\n       bdestruct (x =? i); bdestruct (x <? n); bdestruct (y =? 0); try lia; easy.\n       bdestruct (x =? i); bdestruct (x <? n); bdestruct (y =? 0); try lia; easy.\nQed.\n\n#[export] Hint Resolve WF_e_i WF_pad1 : wf_db.\n\nLemma I_is_eis : forall {n} (i : nat),\n  get_vec i (I n) = e_i i. \nProof. intros. unfold get_vec, e_i.\n       prep_matrix_equality. \n       bdestruct (x =? i).\n       - bdestruct (y =? 0).\n         rewrite H. unfold I. simpl. \n         assert (H1 : (i =? i) && (i <? n) = (i <? n) && true).\n         { bdestruct (i =? i). apply andb_comm. easy. }\n         rewrite H1. reflexivity.\n         simpl; rewrite andb_false_r; reflexivity.\n       - simpl. destruct (y =? 0). unfold I.\n         bdestruct (x =? i). easy.\n         reflexivity. reflexivity.\nQed. \n\nLemma reduce_mul_0 : forall {n} (A : Square (S n)) (v : Vector (S n)),\n  get_vec 0 A = @e_i (S n) 0 -> (reduce A 0 0) × (reduce_row v 0) = reduce_row (A × v) 0.\nProof. intros. \n       prep_matrix_equality. \n       unfold Mmult, reduce, reduce_row. \n       bdestruct (x <? 0); try lia.  \n       rewrite <- big_sum_extend_l.\n       assert (H' : A (1 + x) 0 = C0).\n       { rewrite <- get_vec_conv.  \n         rewrite H. unfold e_i. \n         bdestruct (1 + x =? 0); try lia. \n         easy. }\n       rewrite H'. \n       rewrite Cmult_0_l. \n       rewrite Cplus_0_l.\n       apply big_sum_eq_bounded. \n       intros. bdestruct (x0 <? 0); try lia; try easy.\nQed.\n\nLemma reduce_mul_n : forall {n} (A : Square (S n)) (v : Vector (S n)),\n  get_vec n A = @e_i (S n) n -> (reduce A n n) × (reduce_row v n) = reduce_row (A × v) n.\nProof. intros. \n       prep_matrix_equality. \n       unfold Mmult, reduce, reduce_row.\n       assert (H' : S n - 1 = n). { lia. }\n       bdestruct (x <? n).  \n       - rewrite <- big_sum_extend_r.\n         assert (H'' : A x n = C0).\n         { rewrite <- get_vec_conv.  \n           rewrite H. unfold e_i. \n           bdestruct (x =? n); try lia. \n           easy. }\n         rewrite H''. rewrite Cmult_0_l. \n         rewrite Cplus_0_r.\n         apply big_sum_eq_bounded. \n         intros. bdestruct (x0 <? n); try lia; try easy.\n       - rewrite <- big_sum_extend_r.\n         assert (H'' : A (1 + x) n = C0).\n         { rewrite <- get_vec_conv.  \n           rewrite H. unfold e_i. \n           bdestruct (1 + x =? n); try lia. \n           easy. }\n         rewrite H''. rewrite Cmult_0_l. \n         rewrite Cplus_0_r.\n         apply big_sum_eq_bounded. \n         intros.\n         bdestruct (x0 <? n); try lia; try easy.\nQed.\n \n\n(* More general case: \nLemma reduce_mul : forall {n} (A : Square (S n)) (v : Vector (S n)) (x : nat),\n  get_vec x A = @e_i (S n) x -> (reduce A x x) × (reduce_row v x) = reduce_row (A × v) x.\nProof. *)\n\n\n(* similar lemma for append *) \nLemma append_mul : forall {n m} (A : Matrix n m) (v : Vector n) (a : Vector m),\n  (col_append A v) × (row_append a (@Zero 1 1)) = A × a.\nProof. intros. \n       prep_matrix_equality. \n       unfold Mmult.\n       simpl. \n       assert (H' : (col_append A v x m * row_append a Zero m y = C0)%C). \n       { unfold col_append, row_append.\n         bdestruct (m =? m); try lia; lca. }\n       rewrite H'. \n       rewrite Cplus_0_r. \n       apply big_sum_eq_bounded. \n       intros. \n       unfold col_append, row_append. \n       bdestruct (x0 =? m); try lia; try easy.\nQed.\n\nLemma matrix_by_basis : forall {n m} (T : Matrix n m) (i : nat),\n  i < m -> get_vec i T = T × e_i i.\nProof. intros. unfold get_vec, e_i, Mmult.\n       prep_matrix_equality.\n       bdestruct (y =? 0). \n       - rewrite (big_sum_unique (T x i) _ m); try easy.\n         exists i. split.\n         apply H. split.\n         bdestruct (i =? i); bdestruct (i <? m); try lia; lca. \n         intros.\n         bdestruct (x' =? i); try lia; lca. \n       - rewrite big_sum_0; try reflexivity.\n         intros. rewrite andb_false_r. \n         rewrite Cmult_0_r. reflexivity.\nQed.    \n\n\nLemma pad1_conv : forall {n m : nat} (A : Matrix n m) (c : C) (i j : nat),\n  (pad1 A c) (S i) (S j) = A i j.\nProof. intros.\n       unfold pad1, col_wedge, row_wedge, e_i.\n       bdestruct (S j <? 0); bdestruct (S j =? 0); try lia.\n       bdestruct (S i <? 0); bdestruct (S i =? 0); try lia.\n       do 2 rewrite Sn_minus_1.\n       easy.\nQed.\n\nLemma pad1_mult : forall {n m o : nat} (A : Matrix n m) (B : Matrix m o) (c1 c2 : C),\n  pad1 (A × B) (c1 * c2)%C = (pad1 A c1) × (pad1 B c2).\nProof. intros. \n       prep_matrix_equality. \n       unfold Mmult. \n       destruct x. \n       - unfold pad1, col_wedge, row_wedge, e_i, scale.\n         bdestruct_all. \n         rewrite <- big_sum_extend_l; simpl. \n         rewrite <- (Cplus_0_r (c1 * c2 * C1)).\n         apply Cplus_simplify; try lca. \n         rewrite big_sum_0_bounded; try easy.\n         intros; lca. \n         rewrite big_sum_0_bounded; try easy.\n         simpl; intros. \n         bdestruct_all; lca. \n       - destruct y.\n         unfold pad1, col_wedge, row_wedge, e_i, scale. \n         simpl. \n         rewrite big_sum_0_bounded; try lca.   \n         bdestruct_all; lca. \n         intros. bdestruct_all; lca. \n         rewrite pad1_conv.\n         rewrite <- big_sum_extend_l.\n         rewrite <- (Cplus_0_l (big_sum _ _)). \n         apply Cplus_simplify.\n         unfold pad1, col_wedge, row_wedge, e_i, scale. \n         bdestruct_all; lca. \n         apply big_sum_eq_bounded; intros. \n         do 2 rewrite pad1_conv; easy.\nQed.\n\nLemma pad1_row_wedge_mult : forall {n m : nat} (A : Matrix n m) (v : Vector m) (c : C),\n  pad1 A c × row_wedge v Zero 0 = row_wedge (A × v) Zero 0.\nProof. intros. \n       prep_matrix_equality.\n       destruct x.\n       - unfold pad1, Mmult, col_wedge, row_wedge, scale, e_i.\n         bdestruct_all;\n         rewrite big_sum_0_bounded; try lca; intros;\n         bdestruct_all; lca. \n       - destruct y;\n         unfold pad1, Mmult, col_wedge, row_wedge, scale, e_i;\n         bdestruct_all;\n         rewrite <- big_sum_extend_l, <- Cplus_0_l;\n         apply Cplus_simplify; try lca;\n         apply big_sum_eq_bounded; intros;  \n         bdestruct_all; do 2 rewrite Sn_minus_1; easy. \nQed.\n\nLemma pad1_I : forall (n : nat), pad1 (I n) C1 = I (S n).\nProof. intros. \n       unfold pad1, I, col_wedge, row_wedge, e_i, scale.\n       prep_matrix_equality. \n       bdestruct (y <? 0); bdestruct (y =? 0); bdestruct (x <? 0); bdestruct (x <? S n);\n         bdestruct (x =? 0); bdestruct (x =? y); bdestruct (x - 1 =? y - 1); \n         bdestruct (x - 1 <? n); try lia; try lca.\nQed.\n\n(* ∃ weakens this lemma, but makes future proofs less messy *)\nLemma pad1ed_matrix : forall {n m : nat} (A : Matrix (S n) (S m)) (c : C),\n  (forall (i j : nat), (i = 0 \\/ j = 0) /\\ i <> j -> A i j = C0) -> A 0 0 = c ->\n  exists a, pad1 a c = A.\nProof. intros.\n       exists (reduce_col (reduce_row A 0) 0).\n       unfold pad1, reduce_row, reduce_col, col_wedge, row_wedge, e_i, scale.\n       prep_matrix_equality. \n       bdestruct (y <? 0); bdestruct (y =? 0); bdestruct (x <? 0); bdestruct (x =? 0);\n         try lia. \n       rewrite H4, H2, H0. lca. \n       rewrite H; try lia.\n       destruct x; try lia. lca. \n       rewrite H; try lia; easy. \n       destruct x; destruct y; try lia. \n       do 2 rewrite Sn_minus_1 in *.\n       bdestruct (x <? 0); bdestruct (y <? 0); try lia. \n       easy.\nQed.\n\nLemma reduce_pad1 : forall {n : nat} (A : Square n) (c : C),\n  A = reduce (pad1 A c) 0 0.\nProof. intros. \n       prep_matrix_equality.\n       unfold reduce, pad1, col_wedge, row_wedge, e_i. \n       bdestruct_all.\n       destruct x; destruct y; easy.  \nQed.\n\n\nLemma pad1_col_swap : forall {n m : nat} (A : Matrix n m) (x y : nat) (c : C),\n  (pad1 (col_swap A x y) c) = col_swap (pad1 A c) (S x) (S y).\nProof. intros. \n       unfold pad1, col_wedge, row_wedge, col_swap, e_i, scale. \n       prep_matrix_equality.\n       bdestruct_all; try easy. \n       all : rewrite Sn_minus_1; easy.\nQed.\n\nLemma pad1_col_scale : forall {n m : nat} (A : Matrix n m) (x : nat) (c1 c2 : C),\n  (pad1 (col_scale A x c1) c2) = col_scale (pad1 A c2) (S x) c1.\nProof. intros. \n       unfold pad1, col_wedge, row_wedge, col_scale, e_i, scale. \n       prep_matrix_equality.\n       bdestruct_all; try easy. \n       lca. \nQed.\n\nLemma pad1_col_add : forall {n m : nat} (A : Matrix n m) (x y : nat) (c1 c2 : C),\n  (pad1 (col_add A x y c1) c2) = col_add (pad1 A c2) (S x) (S y) c1.\nProof. intros. \n       unfold pad1, col_wedge, row_wedge, col_add, e_i, scale. \n       prep_matrix_equality.\n       bdestruct_all; try easy. \n       all : rewrite Sn_minus_1; try easy.\n       lca. \nQed.\n\n(***************************************************************************)\n(** * Defining properties which are invarient under column operations, etc... *)\n(***************************************************************************)\n\nInductive invr_col_swap : (forall n m : nat, Matrix n m -> Prop) -> Prop :=\n| invr_swap : forall (P : (forall n m : nat, Matrix n m -> Prop)), \n    (forall (n m x y : nat) (T : Matrix n m), x < m -> y < m -> P n m T -> P n m (col_swap T x y)) \n    -> invr_col_swap P.\n\nInductive invr_col_scale : (forall n m : nat, Matrix n m -> Prop) -> Prop :=\n| invr_scale : forall (P : (forall n m : nat, Matrix n m -> Prop)), \n    (forall (n m x : nat) (T : Matrix n m) (c : C), c <> C0 -> P n m T -> P n m (col_scale T x c)) \n    -> invr_col_scale P.\n\nInductive invr_col_add : (forall n m : nat, Matrix n m -> Prop) -> Prop :=\n| invr_add : forall (P : (forall n m : nat, Matrix n m -> Prop)), \n    (forall (n m x y : nat) (T : Matrix n m) (c : C), \n        x <> y -> x < m -> y < m -> P n m T -> P n m (col_add T x y c)) \n    -> invr_col_add P.\n\nInductive invr_col_add_many : (forall n m : nat, Matrix n m -> Prop) -> Prop :=\n| invr_add_many : forall (P : (forall n m : nat, Matrix n m -> Prop)), \n    (forall (n m col : nat) (T : Matrix n m) (as' : Vector m), \n        col < m -> as' col 0 = C0 -> P n m T -> P n m (col_add_many col as' T)) \n    -> invr_col_add_many P.\n\nInductive invr_col_add_each : (forall n m : nat, Matrix n m -> Prop) -> Prop :=\n| invr_add_each : forall (P : (forall n m : nat, Matrix n m -> Prop)), \n    (forall (n m col : nat) (T : Matrix n m) (as' : Matrix 1 m), \n        col < m -> WF_Matrix as' -> P n m T -> P n m (col_add_each col (make_col_zero col as') T)) \n    -> invr_col_add_each P.\n\nInductive invr_pad1 : (forall n m : nat, Matrix n m -> Prop) -> Prop :=\n| invr_p : forall (P : (forall n m : nat, Matrix n m -> Prop)), \n    (forall (n m : nat) (T : Matrix n m) (c : C), c <> C0 -> P (S n) (S m) (pad1 T c) -> P n m T) \n    -> invr_pad1 P.\n\nInductive prop_zero_true : (forall n m : nat, Matrix n m -> Prop) -> Prop :=\n| PZT : forall (P : (forall n m : nat, Matrix n m -> Prop)), \n  (forall (n m : nat) (T : Matrix n m), (exists i, i < m /\\ get_vec i T = Zero) -> P n m T) ->\n  prop_zero_true P.\n\nInductive prop_zero_false : (forall n m : nat, Matrix n m -> Prop) -> Prop :=\n| PZF : forall (P : (forall n m : nat, Matrix n m -> Prop)), \n  (forall (n m : nat) (T : Matrix n m), (exists i, i < m /\\ get_vec i T = Zero) -> ~ (P n m T)) ->\n  prop_zero_false P.\n\n(* Ltac to help apply these properties of (Mat -> Prop)s *)\nLtac apply_mat_prop tac := \n  let H := fresh \"H\" in \n  assert (H := tac); inversion H; subst; try apply H. \n\nLemma mat_prop_col_add_many_some : forall (e n m col : nat) (P : forall n m : nat, Matrix n m -> Prop)\n                                     (T : Matrix n m) (as' : Vector m),\n  (skip_count col e) < m -> col < m -> \n  (forall i : nat, (skip_count col e) < i -> as' i 0 = C0) -> as' col 0 = C0 ->\n  invr_col_add P ->\n  P n m T -> P n m (col_add_many col as' T).\nProof. induction e as [| e].\n       - intros. \n         inversion H3; subst. \n         rewrite (col_add_many_col_add _ (skip_count col 0)); \n           try lia; try easy.  \n         apply H5; try lia.\n         apply skip_count_not_skip.\n         assert (H' : (col_add_many col (make_row_zero (skip_count col 0) as') T) = T).\n         { prep_matrix_equality. \n           unfold col_add_many, make_row_zero, skip_count, gen_new_vec, scale in *. \n           bdestruct (y =? col); try lia; try easy.\n           rewrite <- Cplus_0_l.\n           rewrite Cplus_comm.\n           apply Cplus_simplify; try easy.\n           rewrite Msum_Csum.\n           apply (@big_sum_0_bounded C C_is_monoid); intros. \n           destruct col; simpl in *. \n           bdestruct (x0 =? 1); try lca. \n           destruct x0; try rewrite H2; try rewrite H1; try lca; try lia. \n           destruct x0; try lca; rewrite H1; try lca; lia. }\n         rewrite H'; easy.\n         apply skip_count_not_skip.\n       - intros. \n         inversion H3; subst. \n         rewrite (col_add_many_col_add _ (skip_count col (S e))); \n           try lia; try easy.\n         apply H5; try lia.\n         apply skip_count_not_skip.\n         apply IHe; try lia; try easy; auto with wf_db. \n         assert (H' : e < S e). lia. \n         apply (skip_count_mono col) in H'.\n         lia. \n         intros. \n         unfold skip_count, make_row_zero in *. \n         bdestruct (e <? col); bdestruct (S e <? col); try lia.\n         bdestruct (i =? S e); try easy; try apply H1; try lia. \n         bdestruct (i =? S e); bdestruct (i =? S (S e)); try lia; try easy. \n         bdestruct (S e =? col); try lia. rewrite H9, H11. apply H2.\n         apply H1; lia. \n         bdestruct (i =? S e); bdestruct (i =? S (S e)); try lia; try easy. \n         apply H1; lia. \n         unfold make_row_zero, skip_count.\n         bdestruct (S e <? col); try lia; bdestruct (col =? S e); bdestruct (col =? S (S e)); \n           try lia; try easy.\n         apply skip_count_not_skip.\nQed.\n\n\nLemma invr_col_add_col_add_many : forall (P : forall n m : nat, Matrix n m -> Prop),\n  invr_col_add P -> invr_col_add_many P.\nProof. intros. \n       inversion H; subst. \n       apply invr_add_many; intros. \n       destruct m; try lia. \n       destruct m.\n       - assert (H' : as' == Zero).\n         { unfold mat_equiv; intros. \n           destruct col; destruct i; destruct j; try lia. \n           easy. }\n         rewrite <- col_add_many_0; easy. \n       - rewrite (col_add_many_mat_equiv _ _ _ (make_WF as'));\n           try apply mat_equiv_make_WF.\n         bdestruct (col =? S m).\n         + apply (mat_prop_col_add_many_some m); try lia; try easy.\n           unfold skip_count. bdestruct (m <? col); lia. \n           intros. \n           unfold skip_count in H5; rewrite H4 in H5. \n           bdestruct (m <? S m); try lia. \n           unfold make_WF. \n           bdestruct (i <? S (S m)); bdestruct (0 <? 1); try lia; try easy.\n           bdestruct (i =? S m); try lia. \n           rewrite H9, <- H4; easy.\n           unfold make_WF. \n           bdestruct_all; auto. \n         + apply (mat_prop_col_add_many_some m); try lia; try easy.\n           unfold skip_count.\n           bdestruct (m <? col); try lia. \n           intros. unfold make_WF.\n           unfold skip_count in H5.\n           bdestruct (m <? col); try lia. \n           bdestruct (i <? S (S m)); try lia; try easy.\n           unfold make_WF. \n           bdestruct_all; auto. \nQed.\n\nLemma mat_prop_col_add_each_some : forall (e n m col : nat) (P : forall n m : nat, Matrix n m -> Prop)\n                                     (as' : Matrix 1 m) (T : Matrix n m),\n  WF_Matrix as' -> (skip_count col e) < m -> col < m -> \n  (forall i : nat, (skip_count col e) < i -> as' 0 i = C0) -> as' 0 col = C0 ->\n  invr_col_add P -> \n  P n m T -> P n m (col_add_each col as' T).\nProof. induction e as [| e].\n       - intros.\n         inversion H4; subst.\n         rewrite (col_add_each_col_add _ (skip_count col 0)); try lia. \n         apply H6; try lia.\n         assert (H' := skip_count_not_skip col 0). auto.\n         assert (H' : (make_col_zero (skip_count col 0) as') = Zero).\n         { apply mat_equiv_eq; auto with wf_db.\n           unfold mat_equiv; intros. \n           unfold make_col_zero, skip_count in *.\n           destruct i; try lia. \n           destruct col; simpl in *. \n           all : destruct j; try easy; simpl. \n           destruct j; try easy; simpl.  \n           all : apply H2; lia. }\n         rewrite H'. \n         rewrite <- col_add_each_0; easy. \n         apply skip_count_not_skip.\n         intros x. destruct x; try easy.\n         apply H; lia.\n       - intros.  \n         inversion H4; subst.\n         rewrite (col_add_each_col_add _ (skip_count col (S e))); try lia. \n         apply H6; try lia.\n         assert (H' := skip_count_not_skip col (S e)). auto.\n         apply IHe; try lia; try easy; auto with wf_db. \n         assert (H' : e < S e). lia. \n         apply (skip_count_mono col) in H'.\n         lia. \n         intros. \n         unfold skip_count, make_col_zero in *. \n         bdestruct (e <? col); bdestruct (S e <? col); try lia.\n         bdestruct (i =? S e); try easy; try apply H2; try lia. \n         bdestruct (i =? S e); bdestruct (i =? S (S e)); try lia; try easy. \n         bdestruct (S e =? col); try lia. rewrite H10, H12. apply H3.\n         apply H2; lia. \n         bdestruct (i =? S e); bdestruct (i =? S (S e)); try lia; try easy. \n         apply H2; lia. \n         unfold make_col_zero, skip_count.\n         bdestruct (S e <? col); try lia; bdestruct (col =? S e); bdestruct (col =? S (S e)); \n           try lia; try easy.\n         assert (H' := skip_count_not_skip col (S e)). auto.\n         intros. destruct x; try easy.\n         apply H; lia.\nQed.\n              \nLemma invr_col_add_col_add_each : forall (P : forall n m : nat, Matrix n m -> Prop),\n  invr_col_add P -> invr_col_add_each P.\nProof. intros.  \n       inversion H; subst. \n       apply invr_add_each; intros. \n       destruct m; try lia. \n       destruct m.\n       - assert (H' : make_col_zero col as' = Zero).\n         { apply mat_equiv_eq; auto with wf_db.\n           unfold mat_equiv; intros. \n           destruct col; destruct i; destruct j; try lia. \n           unfold make_col_zero. \n           easy. }\n         rewrite H'. \n         rewrite <- col_add_each_0; easy. \n       - bdestruct (col =? S m).\n         + apply (mat_prop_col_add_each_some m); try lia; try easy; auto with wf_db.\n           unfold skip_count. bdestruct (m <? col); lia. \n           intros. \n           unfold make_col_zero. \n           bdestruct (i =? col); try lia; try easy.\n           rewrite H4 in H5; unfold skip_count in H5.\n           bdestruct (m <? S m); try lia. \n           rewrite H2; try lia; easy.\n           unfold make_col_zero. \n           bdestruct (col =? col); try lia; easy.\n         + apply (mat_prop_col_add_each_some m); try lia; try easy; auto with wf_db.\n           unfold skip_count.\n           bdestruct (m <? col); try lia. \n           intros. unfold make_col_zero. \n           bdestruct (i =? col); try lia; try easy.\n           unfold skip_count in H5.\n           bdestruct (m <? col); try lia. \n           apply H2; lia. \n           unfold make_col_zero. \n           bdestruct (col =? col); try lia; easy.\nQed.\n\nLemma mat_prop_col_swap_conv : forall {n m} (P : forall n m : nat, Matrix n m -> Prop) (T : Matrix n m) (x y : nat),\n  invr_col_swap P -> \n  x < m -> y < m -> \n  P n m (col_swap T x y) -> P n m T.\nProof. intros. \n       inversion H; subst.\n       rewrite (col_swap_inv T x y).\n       apply H3; easy.\nQed.\n\nLemma mat_prop_col_scale_conv : forall {n m} (P : forall n m : nat, Matrix n m -> Prop) \n                                  (T : Matrix n m) (x : nat) (c : C),\n  invr_col_scale P ->\n  c <> C0 ->\n  P n m (col_scale T x c) -> P n m T.\nProof. intros. \n       inversion H; subst.\n       rewrite (col_scale_inv T x c); try easy.\n       apply H2; try apply nonzero_div_nonzero; easy.\nQed.\n\nLemma mat_prop_col_add_conv : forall {n m} (P : forall n m : nat, Matrix n m -> Prop)  \n                                (T : Matrix n m) (x y : nat) (c : C),\n  invr_col_add P ->\n  x <> y -> x < m -> y < m -> \n  P n m (col_add T x y c) -> P n m T.\nProof. intros. \n       inversion H; subst.\n       rewrite (col_add_inv T x y c); try easy. \n       apply H4; try easy. \nQed.\n\nLemma mat_prop_col_add_many_conv : forall {n m} (P : forall n m : nat, Matrix n m -> Prop) \n                                     (T : Matrix n m) (col : nat) (as' : Vector m),\n  invr_col_add P ->\n  col < m -> as' col 0 = C0 -> \n  P n m (col_add_many col as' T) -> P n m T.\nProof. intros. \n       apply invr_col_add_col_add_many in H.\n       inversion H; subst. \n       rewrite (col_add_many_inv T col as'); try easy.\n       apply H3; try easy. \n       unfold scale; rewrite H1.\n       lca. \nQed.\n\nLemma mat_prop_col_add_each_conv : forall {n m} (P : forall n m : nat, Matrix n m -> Prop) \n                                     (T : Matrix n m) (col : nat) (as' : Matrix 1 m),\n  invr_col_add P ->\n  col < m -> WF_Matrix as' -> \n  P n m (col_add_each col (make_col_zero col as') T) -> P n m T.\nProof. intros. \n       apply invr_col_add_col_add_each in H.\n       inversion H; subst. \n       rewrite (col_add_each_inv col as'); try easy.\n       apply H3; try easy.\n       auto with wf_db.\nQed.\n\n(***********************************************************)\n(** * Defining and proving lemmas relating to the determinant *)\n(***********************************************************)\n\n\nFixpoint parity (n : nat) : C := \n  match n with \n  | 0 => C1 \n  | S 0 => -C1\n  | S (S n) => parity n\n  end. \n\n\nLemma parity_S : forall (n : nat),\n  (parity (S n) = -C1 * parity n)%C. \nProof. intros.\n       induction n as [| n']; try lca.\n       rewrite IHn'.\n       simpl. lca. \nQed.\n\n\nFixpoint Determinant (n : nat) (A : Square n) : C :=\n  match n with \n  | 0 => C1\n  | S 0 => A 0 0\n  | S n' => (big_sum (fun i => (parity i) * (A i 0) * (Determinant n' (reduce A i 0)))%C n)\n  end.\n\nArguments Determinant {n}.\n\nLemma Det_simplify : forall {n} (A : Square (S (S n))),\n  Determinant A =  \n  (big_sum (fun i => (parity i) * (A i 0) * (Determinant (reduce A i 0)))%C (S (S n))).\nProof. intros. easy. Qed.\n\n\nLemma Det_simplify_fun : forall {n} (A : Square (S (S (S n)))),\n  (fun i : nat => parity i * A i 0 * Determinant (reduce A i 0))%C =\n  (fun i : nat => (big_sum (fun j => \n           (parity i) * (A i 0) * (parity j) * ((reduce A i 0) j 0) * \n           (Determinant (reduce (reduce A i 0) j 0)))%C (S (S n))))%C.\nProof. intros. \n       apply functional_extensionality; intros. \n       rewrite Det_simplify. \n       rewrite (@big_sum_mult_l C _ _ _ C_is_ring). \n       apply big_sum_eq_bounded; intros. \n       lca. \nQed.\n\n\nLemma reduce_I : forall (n : nat), reduce (I (S n)) 0 0 = I n.\nProof. intros.\n       apply mat_equiv_eq.\n       apply WF_reduce; try lia; auto with wf_db.\n       apply WF_I.\n       unfold mat_equiv; intros.\n       unfold reduce, I.\n       bdestruct (i <? 0); bdestruct (j <? 0); try lia. \n       easy. \nQed.       \n\nLemma Det_I : forall (n : nat), Determinant (I n) = C1.\nProof. intros.\n       induction n as [| n'].\n       - easy.\n       - simpl. destruct n'; try easy.\n         rewrite <- big_sum_extend_l.\n         rewrite <- Cplus_0_r.\n         rewrite <- Cplus_assoc.\n         apply Cplus_simplify.\n         rewrite reduce_I, IHn'.\n         lca.\n         rewrite (@big_sum_extend_r C C_is_monoid).\n         apply (@big_sum_0_bounded C C_is_monoid); intros.\n         replace (I (S (S n')) (S x) 0) with C0 by easy.\n         lca. \nQed.\n\nLemma Det_make_WF : forall (n : nat) (A : Square n),\n  Determinant A = Determinant (make_WF A).\nProof. induction n as [| n'].  \n       - easy. \n       - intros. \n         destruct n'; try easy. \n         do 2 rewrite Det_simplify. \n         apply big_sum_eq_bounded; intros. \n         assert (H' : (reduce (make_WF A) x 0) = make_WF (reduce A x 0)).\n         { prep_matrix_equality.\n           unfold reduce, make_WF.\n           bdestruct_all; try easy. }\n         rewrite H', IHn'.\n         unfold make_WF. \n         bdestruct_all; easy. \nQed.\n\nLemma Det_Mmult_make_WF_l : forall (n : nat) (A B : Square n),\n  Determinant (A × B) = Determinant (make_WF A × B).\nProof. intros. \n       rewrite Det_make_WF, (Det_make_WF _ (make_WF A × B)).\n       do 2 rewrite <- Mmult_make_WF.\n       rewrite <- (eq_make_WF (make_WF A)); auto with wf_db.\nQed.\n\nLemma Det_Mmult_make_WF_r : forall (n : nat) (A B : Square n),\n  Determinant (A × B) = Determinant (A × (make_WF B)).\nProof. intros. \n       rewrite Det_make_WF, (Det_make_WF _ (A × make_WF B)).\n       do 2 rewrite <- Mmult_make_WF.\n       rewrite <- (eq_make_WF (make_WF B)); auto with wf_db.\nQed.\n\nLemma Det_Mmult_make_WF : forall (n : nat) (A B : Square n),\n  Determinant (A × B) = Determinant ((make_WF A) × (make_WF B)).\nProof. intros. \n       rewrite <- Det_Mmult_make_WF_r, <- Det_Mmult_make_WF_l; easy. \nQed.\n\n\nDefinition M22 : Square 2 :=\n  fun x y => \n  match (x, y) with\n  | (0, 0) => 1%R\n  | (0, 1) => 2%R\n  | (1, 0) => 4%R\n  | (1, 1) => 5%R\n  | _ => C0\n  end.\n\n\nLemma Det_M22 : (Determinant M22) = (Copp (3%R,0%R))%C.\nProof. lca. Qed.\n\n\n\n(** Now, we show the effects of the column operations on determinant *)\n\nLemma Determinant_scale : forall {n} (A : Square n) (c : C) (col : nat),\n  col < n -> Determinant (col_scale A col c) = (c * Determinant A)%C.\nProof. induction n.\n       + intros. easy.\n       + intros. simpl.  \n         destruct n. \n         - simpl. unfold col_scale. \n           bdestruct (0 =? col); try lia; easy.\n         - rewrite Cmult_plus_distr_l.\n           apply Cplus_simplify.\n           * rewrite (@big_sum_mult_l C _ _ _ C_is_ring).\n             apply big_sum_eq_bounded.\n             intros. \n             destruct col. \n             rewrite col_scale_reduce_same; try lia. \n             unfold col_scale. bdestruct (0 =? 0); try lia. \n             lca. \n             rewrite col_scale_reduce_before; try lia.\n             rewrite Sn_minus_1.\n             rewrite IHn; try lia. \n             unfold col_scale. \n             bdestruct (0 =? S col); try lia; lca.\n           * destruct col. \n             rewrite col_scale_reduce_same; try lia. \n             unfold col_scale. bdestruct (0 =? 0); try lia. \n             lca. \n             rewrite col_scale_reduce_before; try lia.\n             rewrite Sn_minus_1.\n             rewrite IHn; try lia. \n             unfold col_scale. \n             bdestruct (0 =? S col); try lia; lca. \nQed.\n\n\n(* some helper lemmas, since showing the effect of col_swap is a bit tricky *)\nLemma Det_diff_1 : forall {n} (A : Square (S (S (S n)))),\n  Determinant (col_swap A 0 1) = \n  big_sum (fun i => (big_sum (fun j => ((A i 1) * (A (skip_count i j) 0) * (parity i) * (parity j) * \n                             Determinant (reduce (reduce A i 0) j 0))%C)  \n                             (S (S n)))) (S (S (S n))).\nProof. intros. \n       rewrite Det_simplify.\n       rewrite Det_simplify_fun.\n       apply big_sum_eq_bounded; intros. \n       apply big_sum_eq_bounded; intros. \n       replace (col_swap A 0 1 x 0) with (A x 1) by easy. \n       assert (H' : @reduce (S (S n)) (col_swap A 0 1) x 0 x0 0 = A (skip_count x x0) 0).\n       { unfold reduce, col_swap, skip_count. \n         simpl. bdestruct (x0 <? x); try easy. } \n       rewrite H'.    \n       apply Cmult_simplify; try easy. \n       lca. \nQed.\n\nLemma Det_diff_2 : forall {n} (A : Square (S (S (S n)))),\n  Determinant A = \n  big_sum (fun i => (big_sum (fun j => ((A i 0) * (A (skip_count i j) 1) * (parity i) * (parity j) * \n                             Determinant (reduce (reduce A i 0) j 0))%C)  \n                             (S (S n)))) (S (S (S n))).\nProof. intros. \n       rewrite Det_simplify.\n       rewrite Det_simplify_fun.\n       apply big_sum_eq_bounded; intros. \n       apply big_sum_eq_bounded; intros. \n       apply Cmult_simplify; try easy. \n       assert (H' : @reduce (S (S n)) A x 0 x0 0 = A (skip_count x x0) 1).\n       { unfold reduce, col_swap, skip_count. \n         simpl. bdestruct (x0 <? x); try easy. } \n       rewrite H'. \n       lca. \nQed.\n  \n(* if we show that swapping 0th col and 1st col, we can generalize using some cleverness *)\nLemma Determinant_swap_01 : forall {n} (A : Square n),\n  1 < n -> Determinant (col_swap A 0 1) = (-C1 * (Determinant A))%C.\nProof. intros.\n       destruct n; try lia.\n       destruct n; try lia. \n       destruct n.\n       - simpl. unfold col_swap, reduce. lca. \n       - rewrite Det_diff_1, Det_diff_2.\n         apply big_sum_rearrange; intros.\n         + unfold skip_count. \n           bdestruct (x <? (S y)); bdestruct (y <? x); try lia.\n           rewrite Cmult_assoc.\n           apply Cmult_simplify.\n           rewrite parity_S.\n           lca. \n           rewrite reduce_reduce_0; easy.\n         + unfold skip_count. \n           bdestruct (x <? y); bdestruct (y <? (S x)); try lia.\n           rewrite Cmult_assoc.\n           apply Cmult_simplify.\n           rewrite parity_S.\n           lca. \n           rewrite <- reduce_reduce_0; easy.\nQed.\n\n(* swapping adjacent columns *)\nLemma Determinant_swap_adj : forall {n} (A : Square n) (i : nat),\n  S i < n -> Determinant (col_swap A i (S i)) = (-C1 * (Determinant A))%C.\nProof. induction n as [| n'].\n       - easy.\n       - intros. \n         destruct i. \n         + apply Determinant_swap_01; easy.\n         + simpl. destruct n'; try lia.\n           do 2 rewrite (@big_sum_extend_r C C_is_monoid).\n           rewrite (@big_sum_mult_l C _ _ _ C_is_ring).\n           apply big_sum_eq_bounded; intros. \n           rewrite col_swap_reduce_before; try lia. \n           rewrite IHn'; try lia. \n           replace (col_swap A (S i) (S (S i)) x 0) with (A x 0) by easy.\n           lca. \nQed.\n\n(* swapping columns i and i + (S k), use previous lemma to induct *)\nLemma Determinant_swap_ik : forall {n} (k i : nat) (A : Square n),\n  i + (S k) < n -> Determinant (col_swap A i (i + (S k))) = (-C1 * (Determinant A))%C.\nProof. induction k as [| k'].\n       - intros. \n         replace (i + 1) with (S i) by lia. \n         rewrite Determinant_swap_adj; try lia; lca. \n       - intros. \n         rewrite (col_swap_three A i (i + (S k')) (i + (S (S k')))); try lia. \n         rewrite IHk'; try lia. \n         replace (i + (S (S k'))) with (S (i + (S k'))) by lia. \n         rewrite Determinant_swap_adj; try lia.\n         rewrite IHk'; try lia. \n         lca. \nQed.\n\n(* finally, we can prove Determinant_swap *)\nLemma Determinant_swap : forall {n} (A : Square n) (i j : nat),\n  i < n -> j < n -> i <> j ->\n  Determinant (col_swap A i j) = (-C1 * (Determinant A))%C.\nProof. intros. \n       bdestruct (i <? j); bdestruct (j <? i); try lia. \n       - replace j with (i + (S (j - i - 1))) by lia. \n         rewrite Determinant_swap_ik; try lia; easy.\n       - replace i with (j + (S (i - j - 1))) by lia. \n         rewrite col_swap_diff_order. \n         rewrite Determinant_swap_ik; try lia; easy.\nQed.\n\nLemma col_0_Det_0 : forall {n} (A : Square n),\n  (exists i, i < n /\\ get_vec i A = Zero) -> Determinant A = C0.\nProof. intros n A [i [H H0]].\n       destruct n; try easy.\n       destruct n.\n       destruct i; try lia. \n       replace C0 with (@Zero 1 1 0 0) by easy.\n       rewrite <- H0. easy. \n       destruct i.\n       - rewrite Det_simplify.\n         apply (@big_sum_0_bounded C C_is_monoid); intros. \n         replace (A x 0) with (@Zero (S (S n)) 1 x 0) by (rewrite <- H0; easy). \n         unfold Zero; lca.\n       - rewrite (col_swap_inv _ 0 (S i)).\n         rewrite Determinant_swap; try lia.\n         rewrite Det_simplify.\n         rewrite (@big_sum_mult_l C _ _ _ C_is_ring).\n         apply (@big_sum_0_bounded C C_is_monoid); intros. \n         replace (col_swap A 0 (S i) x 0) with \n                 (@Zero (S (S n)) 1 x 0) by (rewrite <- H0; easy). \n         unfold Zero; lca.\nQed.\n\nLemma col_same_Det_0 : forall {n} (A : Square n) (i j : nat),\n  i < n -> j < n -> i <> j -> \n  get_vec i A = get_vec j A ->\n  Determinant A = C0.\nProof. intros. \n       apply eq_neg_implies_0.\n       rewrite <- (Determinant_swap _ i j); try easy.\n       rewrite (det_by_get_vec (col_swap A i j) A); try easy; intros. \n       prep_matrix_equality. \n       destruct y; try easy.\n       bdestruct (i0 =? i); bdestruct (i0 =? j); try lia.\n       - rewrite H3, <- col_swap_get_vec, H2; easy.\n       - rewrite H4, col_swap_diff_order, <- col_swap_get_vec, H2; easy.\n       - unfold col_swap, get_vec. simpl. \n         bdestruct (i0 =? i); bdestruct (i0 =? j); try lia; easy.\nQed.\n\nLemma col_scale_same_Det_0 : forall {n} (A : Square n) (i j : nat) (c : C),\n  i < n -> j < n -> i <> j -> \n  get_vec i A = c .* (get_vec j A) ->\n  Determinant A = C0.\nProof. intros. \n       destruct (Ceq_dec c C0).\n       - apply col_0_Det_0.\n         exists i.\n         split; try easy.\n         rewrite H2, e.\n         apply Mscale_0_l.\n       - rewrite (col_scale_inv A j c); try easy.\n         rewrite Determinant_scale; try easy.\n         assert (H3 : Determinant (col_scale A j c) = C0).\n         { apply (col_same_Det_0 _ i j); try easy.\n           prep_matrix_equality.\n           unfold get_vec, col_scale. \n           bdestruct (y =? 0); try easy.\n           bdestruct (i =? j); bdestruct (j =? j); try lia. \n           rewrite <- get_vec_conv.\n           rewrite H2.\n           unfold scale.\n           rewrite get_vec_conv. \n           easy. }\n         rewrite H3.\n         lca. \nQed.\n\n(* use this to show det_col_add_0i *)\nLemma Det_col_add_comm : forall {n} (T : Matrix (S n) n) (v1 v2 : Vector (S n)),\n  (Determinant (col_wedge T v1 0) + Determinant (col_wedge T v2 0) = \n   Determinant (col_wedge T (v1 .+ v2) 0))%C.\nProof. intros. \n       destruct n; try easy.\n       do 3 rewrite Det_simplify.\n       rewrite <- (@big_sum_plus C _ _ C_is_comm_group).\n       apply big_sum_eq_bounded; intros. \n       repeat rewrite reduce_is_redcol_redrow.\n       repeat rewrite col_wedge_reduce_col_same.\n       unfold col_wedge, Mplus.\n       bdestruct (0 <? 0); bdestruct (0 =? 0); try lia. \n       lca. \nQed.\n\n(* like before, we prove a specific case in order to prove the general case *)\nLemma Determinant_col_add0i : forall {n} (A : Square n) (i : nat) (c : C),\n  i < n -> i <> 0 -> Determinant (col_add A 0 i c) = Determinant A.     \nProof. intros. \n       destruct n; try easy.\n       rewrite col_add_split.\n       assert (H' := (@Det_col_add_comm n (reduce_col A 0) (get_vec 0 A) (c .* get_vec i A))).\n       rewrite <- H'.\n       rewrite <- Cplus_0_r.\n       apply Cplus_simplify. \n       assert (H1 : col_wedge (reduce_col A 0) (get_vec 0 A) 0 = A).\n       { prep_matrix_equality.\n         unfold col_wedge, reduce_col, get_vec. \n         destruct y; try easy; simpl.  \n         replace (y - 0) with y by lia; easy. }\n       rewrite H1; easy.\n       apply (col_scale_same_Det_0 _ 0 i c); try lia.\n       prep_matrix_equality. \n       unfold get_vec, col_wedge, reduce_col, scale; simpl. \n       bdestruct (y =? 0); bdestruct (i =? 0); try lca; try lia.\n       replace (S (i - 1)) with i by lia. \n       easy. \nQed.\n\nLemma Determinant_col_add : forall {n} (A : Square n) (i j : nat) (c : C),\n  i < n -> j < n -> i <> j -> Determinant (col_add A i j c) = Determinant A.     \nProof. intros. \n       destruct j.\n       - rewrite <- col_swap_col_add_0.\n         rewrite Determinant_swap. \n         rewrite Determinant_col_add0i.\n         rewrite Determinant_swap. \n         lca. \n         all : easy. \n       - destruct i. \n         rewrite Determinant_col_add0i; try easy.\n         rewrite <- col_swap_col_add_Si.\n         rewrite Determinant_swap. \n         rewrite Determinant_col_add0i.\n         rewrite Determinant_swap. \n         lca. \n         all : try easy; try lia. \nQed.\n\n\n(** * We can now define some invariants for Determinant *)\nDefinition det_neq_0 {n m : nat} (A : Matrix n m) : Prop :=\n  n = m /\\ @Determinant n A <> C0.\n\nDefinition det_eq_c (c : C) {n m : nat} (A : Matrix n m) : Prop :=\n  n = m /\\ @Determinant n A = c.\n\n\nLemma det_neq_0_swap_invr : invr_col_swap (@det_neq_0).\nProof. apply invr_swap; intros.  \n       destruct H1; subst. \n       split; auto.\n       bdestruct (x =? y); subst. \n       - rewrite col_swap_same.\n         easy. \n       - rewrite Determinant_swap; auto.         \n         unfold not; intros.\n         apply H2.\n         rewrite <- (Cmult_1_l _).\n         replace C1 with ((-C1) * (-C1))%C by lca. \n         rewrite <- Cmult_assoc, H3. \n         lca. \nQed.\n\nLemma det_neq_0_scale_invr : invr_col_scale (@det_neq_0).\nProof. apply invr_scale; intros.  \n       destruct H0; subst. \n       split; auto.\n       bdestruct (x <? m).\n       - rewrite Determinant_scale; auto. \n         apply Cmult_neq_0; easy. \n       - rewrite Det_make_WF in *. \n         assert (H' : (make_WF T) = (make_WF (col_scale T x c))).\n         { apply mat_equiv_eq; auto with wf_db.\n           unfold mat_equiv, make_WF, col_scale; intros. \n           bdestruct_all; easy. }\n         rewrite <- H'; easy. \nQed.\n\nLemma det_neq_0_add_invr : invr_col_add (@det_neq_0).\nProof. apply invr_add; intros.  \n       destruct H2; subst. \n       split; auto. \n       rewrite Determinant_col_add; easy.\nQed.\n\n\nLemma det_neq_0_pad1_invr : invr_pad1 (@det_neq_0).  \nProof. apply invr_p; intros. \n       destruct H0; apply eq_add_S in H0; subst. \n       split; auto. \n       destruct m. \n       - apply C1_neq_C0. \n       - unfold not; intros; apply H1.\n         rewrite Det_simplify. \n         apply (@big_sum_0_bounded C C_is_monoid); intros. \n         destruct x. \n         + rewrite <- reduce_pad1, H0; lca. \n         + unfold pad1, col_wedge, row_wedge, e_i, scale.\n           bdestruct_all; simpl. \n           lca. \nQed.\n\nLemma det_neq_0_pzf : prop_zero_false (@det_neq_0).  \nProof. apply PZF; intros.\n       unfold not; intros. \n       destruct H0; subst. \n       apply (col_0_Det_0 T) in H.\n       easy. \nQed.\n\nLemma det_0_swap_invr : invr_col_swap (@det_eq_c C0).\nProof. apply invr_swap; intros.  \n       unfold det_eq_c in *; destruct H1; subst. \n       split; auto.\n       bdestruct (x =? y); subst. \n       - rewrite col_swap_same.\n         easy. \n       - rewrite Determinant_swap; auto. \n         rewrite H2; lca. \nQed.\n\nLemma det_0_scale_invr : invr_col_scale (@det_eq_c C0).\nProof. apply invr_scale; intros. \n       unfold det_eq_c in *; destruct H0; subst. \n       split; auto.\n       bdestruct (x <? m).\n       - rewrite Determinant_scale; auto. \n         rewrite H1; lca. \n       - rewrite Det_make_WF in *. \n         assert (H' : (make_WF T) = (make_WF (col_scale T x c))).\n         { apply mat_equiv_eq; auto with wf_db.\n           unfold mat_equiv, make_WF, col_scale; intros. \n           bdestruct_all; easy. }\n         rewrite <- H'; easy. \nQed.\n\nLemma det_c_add_invr : forall (c : C), invr_col_add (@det_eq_c c).\nProof. intros. \n       apply invr_add; intros.  \n       unfold det_eq_c in *; destruct H2; subst. \n       split; auto. \n       apply Determinant_col_add; easy.\nQed.\n\nLemma det_0_pad1_invr : invr_pad1 (@det_eq_c C0).\nProof. apply invr_p; intros. \n       destruct H0; apply eq_add_S in H0; subst. \n       split; auto. \n       destruct m. \n       - simpl in H1.         \n         unfold pad1, col_wedge, row_wedge, e_i, scale in H1; \n         simpl in H1. \n         rewrite Cmult_1_r in H1. \n         easy.\n       - rewrite Det_simplify in H1. \n         assert (H' : (c * Determinant (reduce (pad1 T c) 0 0) = C0)%C).\n         { rewrite <- H1, (big_sum_unique (c * Determinant (reduce (pad1 T c) 0 0))%C).  \n           easy. \n           exists 0. split; try lia. \n           split. simpl parity. \n           apply Cmult_simplify; try easy.  \n           unfold pad1, col_wedge, row_wedge, e_i, scale. \n           bdestruct_all; lca. \n           intros. \n           unfold pad1, col_wedge, row_wedge, e_i, scale. \n           bdestruct_all; lca. }\n         rewrite <- reduce_pad1 in H'.\n         destruct (Ceq_dec (Determinant T) C0); try easy. \n         apply (Cmult_neq_0 c _) in n; easy. \nQed.\n\n#[export] Hint Resolve det_neq_0_swap_invr det_neq_0_scale_invr det_neq_0_add_invr det_neq_0_pad1_invr : invr_db.\n#[export] Hint Resolve det_neq_0_pzf det_0_swap_invr det_0_scale_invr det_c_add_invr det_0_pad1_invr : invr_db.\n\n\nLemma Determinant_col_add_many : forall (n col : nat) (A : Square n) (as' : Vector n),\n  col < n -> as' col 0 = C0 -> \n  Determinant A = Determinant (col_add_many col as' A).\nProof. intros.\n       assert (H' := det_c_add_invr (Determinant A)).\n       apply invr_col_add_col_add_many in H'. \n       inversion H'; subst. \n       apply (H1 n n col A as') in H; try easy.\n       unfold det_eq_c in *.\n       destruct H; easy. \nQed.\n\n\nLemma Determinant_col_add_each : forall (n col : nat) (as' : Matrix 1 n) \n                                          (A : Square n),\n  col < n -> WF_Matrix as' -> as' 0 col = C0 ->\n  Determinant A = Determinant (col_add_each col as' A).\nProof. intros. \n       assert (H' := det_c_add_invr (Determinant A)).\n       apply invr_col_add_col_add_each in H'. \n       inversion H'; subst. \n       apply (H2 n n col A as') in H; try easy.\n       unfold det_eq_c in *.\n       destruct H; rewrite <- H3.\n       assert (H4 : (make_col_zero col as') = as').\n       { apply mat_equiv_eq; auto with wf_db.\n         unfold mat_equiv; intros. \n         unfold make_col_zero.\n         destruct i; try lia.\n         bdestruct_all; subst; easy. }\n       rewrite H4; easy.\nQed.\n\n\n(***********************************************************)\n(** * Defining linear independence, and proving lemmas etc... *)\n(***********************************************************)\n\n\nDefinition linearly_independent {n m} (T : Matrix n m) : Prop :=\n  forall (a : Vector m), WF_Matrix a -> @Mmult n m 1 T a = Zero -> a = Zero.\n\nDefinition linearly_dependent {n m} (T : Matrix n m) : Prop :=\n  exists (a : Vector m), WF_Matrix a /\\ a <> Zero /\\ @Mmult n m 1 T a = Zero.\n\nLemma lindep_implies_not_linindep : forall {n m} (T : Matrix n m),\n  linearly_dependent T -> ~ (linearly_independent T).\nProof. unfold not, linearly_dependent, linearly_independent in *.\n       intros. \n       destruct H as [a [H1 [H2 H3]]].\n       apply H0 in H1; easy.\nQed.\n\nLemma not_lindep_implies_linindep : forall {n m} (T : Matrix n m),\n  not (linearly_dependent T) -> linearly_independent T.\nProof. unfold not, linearly_dependent, linearly_independent in *.\n       intros. \n       destruct (vec_equiv_dec a Zero). \n       - apply mat_equiv_eq; auto with wf_db.\n       - assert (H2 : (exists a : Vector m, WF_Matrix a /\\ a <> Zero /\\ T × a = Zero)).\n         { exists a.\n           split; auto. \n           split; try easy.  \n           unfold not; intros. \n           apply n0.\n           rewrite H2.\n           easy. }\n         apply H in H2.\n         easy.\nQed.\n\nLemma lin_indep_vec : forall {n} (v : Vector n), \n  WF_Matrix v -> v <> Zero -> linearly_independent v.\nProof. intros. \n       unfold linearly_independent.\n       intros. \n       assert (H' : v × a = (a 0 0) .* v).\n       { apply mat_equiv_eq; auto with wf_db.\n         unfold Mmult, scale, mat_equiv. \n         intros. simpl. \n         destruct j; try lia; lca. }\n       assert (H1' := H).\n       apply nonzero_vec_nonzero_elem in H1'; try easy.\n       destruct H1' as [x H1'].\n       destruct (Ceq_dec (a 0 0) C0).\n       + prep_matrix_equality. \n         destruct x0. destruct y.\n         rewrite e; easy.\n         all : apply H1; lia.\n       + assert (H'' : ((a 0 0) .* v) x 0 = C0).\n         { rewrite <- H'. rewrite H2; easy. }\n         unfold scale in H''. \n         assert (H3 : (a 0 0 * v x 0)%C <> C0).\n         { apply Cmult_neq_0; easy. }\n         easy. \nQed.\n\nLemma invertible_l_implies_linind : forall {n} (A B : Square n),\n  A × B = I n -> linearly_independent B.\nProof. intros.\n       unfold linearly_independent. intros.\n       rewrite <- (Mmult_1_l _ _ a); try easy.\n       rewrite <- H.\n       rewrite Mmult_assoc, H1.\n       rewrite Mmult_0_r.\n       reflexivity.\nQed.\n\nLemma lin_indep_col_reduce_n : forall {n m} (A : Matrix n (S m)),\n  linearly_independent A -> linearly_independent (reduce_col A m).\nProof. intros. \n       unfold linearly_independent in *. \n       intros. \n       assert (H' : row_append a Zero = Zero).\n       { apply H.\n         apply WF_row_append; try easy.\n         prep_matrix_equality. \n         unfold Mmult, row_append, Zero.  \n         rewrite <- big_sum_extend_r. \n         bdestruct (m =? m); try lia. \n         autorewrite with C_db.\n         assert (H' : (reduce_col A m × a) x y = C0).\n         { rewrite H1; easy. }\n         rewrite <- H'. \n         unfold Mmult. \n         apply big_sum_eq_bounded. \n         intros.\n         unfold reduce_col.\n         bdestruct (x0 =? m); bdestruct (x0 <? m); try lia. \n         reflexivity. } \n       prep_matrix_equality. \n       assert (H'' : row_append a Zero x y = C0). { rewrite H'. easy. }\n       unfold Zero; simpl. rewrite <- H''. \n       unfold row_append.\n       bdestruct (x =? m); try easy.\n       unfold WF_Matrix in H0. \n       unfold Zero; simpl. \n       apply H0. lia. \nQed.\n\n(* more general than lin_indep_col_reduce_n *)\nLemma lin_indep_smash : forall {n m2 m1} (A1 : Matrix n m1) (A2 : Matrix n m2),\n  linearly_independent (smash A1 A2) -> linearly_independent A1. \nProof. induction m2 as [| m2'].\n       - intros.  \n         unfold linearly_independent in *. \n         intros. assert (H' : m1 + 0 = m1). lia. \n         rewrite H' in *.\n         apply H; try easy.\n         rewrite <- H1.\n         unfold smash, Mmult. \n         prep_matrix_equality. \n         apply big_sum_eq_bounded.\n         intros. \n         bdestruct (x0 <? m1); try lia; easy.\n       - intros.  \n         assert (H1 := @lin_indep_col_reduce_n n (m1 + m2') (smash A1 A2)). \n         rewrite <- plus_n_Sm in H.\n         apply H1 in H.\n         rewrite smash_reduce in H.\n         apply (IHm2' m1 A1 (reduce_col A2 m2')).\n         easy.\nQed.\n\nLemma lin_dep_mult_r : forall {n m o} (A : Matrix n m) (B : Matrix m o),\n  linearly_dependent B -> linearly_dependent (A × B).\nProof. intros. \n       unfold linearly_dependent in *.\n       destruct H as [a [H [H0 H1]]].\n       exists a. \n       repeat split; auto.  \n       rewrite Mmult_assoc, H1, Mmult_0_r; easy. \nQed.      \n\nLemma lin_dep_col_append_n : forall {n m} (A : Matrix n m) (v : Vector n),\n  linearly_dependent A -> linearly_dependent (col_append A v).\nProof. intros. \n       unfold linearly_dependent in *. \n       destruct H as [a [H [H1 H2]]].\n       exists (row_append a (@Zero 1 1)). \n       split; auto with wf_db. \n       split. unfold not; intros; apply H1.\n       prep_matrix_equality. \n       assert (H' : row_append a Zero x y = C0). \n       { rewrite H0. easy. }\n       unfold row_append in H'.\n       bdestruct (x =? m). \n       rewrite H; try easy; lia. \n       rewrite H'; easy.\n       rewrite append_mul.\n       easy.\nQed.\n\n\n(* proving invr properties for linearly_independent *)\nLemma lin_indep_swap_invr : invr_col_swap (@linearly_independent). \nProof. apply invr_swap; intros. \n       unfold linearly_independent in *.\n       intros. \n       rewrite (row_swap_inv a x y) in H3.\n       rewrite <- (swap_preserves_mul T (row_swap a x y) x y) in H3; try easy.\n       apply H1 in H3.\n       rewrite (row_swap_inv a x y).\n       rewrite H3.\n       prep_matrix_equality.\n       unfold row_swap.\n       bdestruct (x0 =? x); bdestruct (x0 =? y); easy.\n       apply WF_row_swap; easy.\nQed.\n\nLemma lin_indep_scale_invr : invr_col_scale (@linearly_independent). \nProof. apply invr_scale; intros. \n       unfold linearly_independent in *.\n       intros. \n       rewrite <- scale_preserves_mul in H2.\n       apply H0 in H2.\n       rewrite (row_scale_inv _ x c); try easy.\n       rewrite H2.\n       prep_matrix_equality. \n       unfold row_scale.\n       bdestruct (x0 =? x);\n       lca. \n       apply WF_row_scale; easy.\nQed.\n\nLemma lin_indep_add_invr : invr_col_add (@linearly_independent). \nProof. apply invr_add; intros. \n       unfold linearly_independent in *.\n       intros.  \n       rewrite <- add_preserves_mul in H4; try easy.\n       apply H2 in H4.\n       rewrite (row_add_inv a y x c); try lia.\n       rewrite H4.\n       prep_matrix_equality. \n       unfold row_add.\n       bdestruct (x0 =? y);\n       lca. \n       apply WF_row_add; easy.\nQed.\n\nLemma lin_indep_pad1_invr : invr_pad1 (@linearly_independent).  \nProof. apply invr_p; intros. \n       unfold linearly_independent in *.\n       intros. \n       assert (H3 : @Mmult (S n) (S m) 1 (pad1 T c) (row_wedge a Zero 0) = Zero).\n       { prep_matrix_equality. \n         destruct x. unfold Mmult. \n         unfold Zero. apply (@big_sum_0_bounded C C_is_monoid). \n         intros.\n         unfold pad1, row_wedge, col_wedge, e_i, scale.\n         bdestruct (x <? 0); bdestruct (x =? 0); try lia. lca. \n         lca.\n         assert (p : @Zero (S n) 1 (S x) y = C0).\n         easy.\n         assert (H2' : (T × a) x y = C0). \n         rewrite H2; easy.\n         rewrite p. \n         rewrite <- H2'.\n         unfold Mmult. rewrite <- big_sum_extend_l.  \n         rewrite <- Cplus_0_l.\n         apply Cplus_simplify.\n         unfold pad1, row_wedge, col_wedge, e_i.\n         bdestruct (x <? 0); bdestruct (x =? 0); try lia. \n         rewrite H4; simpl. lca. \n         rewrite Sn_minus_1. lca. \n         apply big_sum_eq_bounded; intros. \n         rewrite pad1_conv.\n         unfold row_wedge.\n         rewrite Sn_minus_1. \n         easy. }\n       apply H0 in H3.\n       prep_matrix_equality. \n       assert (H4 : row_wedge a Zero 0 (S x) y = C0).\n       rewrite H3; easy.\n       unfold Zero. rewrite <- H4.\n       unfold row_wedge. \n       rewrite Sn_minus_1.\n       easy.\n       apply WF_row_wedge; try lia; easy.\nQed.   \n\nLemma lin_indep_pzf : prop_zero_false (@linearly_independent).\nProof. apply PZF; intros. \n       unfold not; intros. \n       unfold linearly_independent in *.  \n       destruct H as [i [H H1]].\n       assert (H2 : T × @e_i m i = Zero).\n       { prep_matrix_equality.\n         unfold Mmult, Zero, e_i; simpl.  \n         apply (@big_sum_0_bounded C C_is_monoid); intros. \n         bdestruct_all; try lca; \n         rewrite <- get_vec_conv; subst.\n         rewrite H1; lca. }\n       apply H0 in H2; auto with wf_db.\n       assert (H3 : @e_i m i i 0 = C0).\n       rewrite H2; easy.\n       unfold e_i in H3.\n       apply C1_neq_C0.\n       rewrite <- H3.\n       bdestruct_all; easy.\nQed.\n\nLemma lin_dep_swap_invr : invr_col_swap (@linearly_dependent).\nProof. apply invr_swap; intros. \n       unfold linearly_dependent in *.\n       destruct H1 as [a [H1 [H2 H3]]].\n       rewrite (row_swap_inv a x y) in H3.\n       rewrite (col_swap_inv T x y) in H3.\n       rewrite <- (swap_preserves_mul _ (row_swap a x y) x y) in H3; try easy.\n       exists (row_swap a x y).\n       split; auto with wf_db.\n       split; try easy; unfold not in *.\n       intros; apply H2.\n       rewrite (row_swap_inv a x y).\n       rewrite H4.\n       prep_matrix_equality. \n       unfold Zero, row_swap. \n       bdestruct (x0 =? x); bdestruct (x0 =? y); easy. \nQed.\n \nLemma lin_dep_scale_invr : invr_col_scale (@linearly_dependent).\nProof. intros. \n       apply invr_scale; intros. \n       unfold linearly_dependent in *.\n          destruct H0 as [a [H1 [H2 H3]]].\n          exists (row_scale a x (/ c)).\n          split; auto with wf_db.\n          split. unfold not; intros.\n          apply H2.\n          rewrite (row_scale_inv _ x (/ c)); try easy.\n          rewrite H0. \n          prep_matrix_equality. \n          unfold row_scale, Zero. \n          bdestruct (x0 =? x); try lia; lca. \n          apply nonzero_div_nonzero; easy.\n          rewrite scale_preserves_mul. \n          rewrite <- (col_scale_inv T x c); easy.       \nQed.\n\nLemma lin_dep_add_invr : invr_col_add (@linearly_dependent).\nProof. intros.\n       apply invr_add; intros. \n       unfold linearly_dependent in *.\n       destruct H2 as [a [H2 [H3 H4]]].\n       exists (row_add a y x (- c)).\n       split; auto with wf_db.\n       split. unfold not; intros; apply H3.\n       rewrite (row_add_inv a y x (- c)); try lia.\n       rewrite H5.\n       unfold row_add, Zero.\n       prep_matrix_equality.\n       bdestruct (x0 =? y); lca. \n       rewrite add_preserves_mul; try easy.\n       rewrite <- (col_add_inv T x y c); try lia; easy.\nQed.\n\nLemma lin_dep_pzt : prop_zero_true (@linearly_dependent).\nProof. apply PZT; intros. \n       unfold linearly_dependent in *; intros. \n       destruct H as [i [H0 H1]].\n       exists (@e_i m i).\n       split; auto with wf_db. \n       split. \n       unfold not; intros. \n       assert (H' : (@e_i m i) i 0 = C0).\n       { rewrite H; easy. }\n       unfold e_i in H'; simpl in H'.\n       bdestruct (i =? i); bdestruct (i <? m); try lia. \n       simpl in H'.\n       apply C1_neq_C0.\n       easy.\n       rewrite <- matrix_by_basis; easy.\nQed.\n\n#[export] Hint Resolve lin_indep_swap_invr lin_indep_scale_invr lin_indep_add_invr lin_indep_pad1_invr : invr_db.\n#[export] Hint Resolve lin_indep_pzf lin_dep_swap_invr lin_dep_scale_invr lin_dep_add_invr lin_dep_pzt : invr_db.\n\n\n(** we begin to prove that if n < m, then any Matrix n m is linearly_dependent. This is quite useful, as we get a vector that can be used to cancel a column *)\n\nLemma lin_dep_gen_elem : forall {m n} (T : Matrix n (S m)),\n  WF_Matrix T -> linearly_dependent T -> \n  (exists i, i < (S m) /\\ \n             (exists v : Vector m, WF_Matrix v /\\ \n                 @Mmult n m 1 (reduce_col T i) v = (-C1) .* (get_vec i T))). \nProof. intros. \n       unfold linearly_dependent in H.\n       destruct H0 as [a [H1 [H2 H3]]].\n       assert (H4 := H1).\n       apply nonzero_vec_nonzero_elem in H4; try easy.\n       destruct H4 as [x H4].\n       exists x.\n       bdestruct (x <? S m).\n       - split; try easy.\n         exists ( (/ (a x 0)) .* (reduce_row a x)).\n         split; auto with wf_db. \n         apply mat_equiv_eq; auto with wf_db.\n         rewrite Mscale_mult_dist_r.  \n         unfold mat_equiv; intros. \n         unfold Mmult, scale.\n         assert (H' : (big_sum (fun y : nat => reduce_col T x i y * reduce_row a x y j) m +\n                       (a x 0) * get_vec x T i j = @Zero n 1 i j)%C).\n         { rewrite <- H3. unfold Mmult.\n           assert (H'' : m = x + (m - x)). lia. \n           rewrite H''. \n           rewrite big_sum_sum.\n           rewrite <- H''. \n           assert (H2' : S m = x + S (m - x)). lia. \n           rewrite H2'. \n           rewrite big_sum_sum.\n           rewrite <- big_sum_extend_l.\n           rewrite <- Cplus_assoc.\n           apply Cplus_simplify. \n           apply big_sum_eq_bounded.\n           intros. unfold reduce_col, reduce_row. \n           bdestruct (x0 <? x); try lia; easy.\n           rewrite Cplus_comm.\n           apply Cplus_simplify. \n           unfold get_vec.\n           bdestruct (j =? 0); try lia. \n           assert (p0 : x + 0 = x). lia. \n           rewrite p0, H7; lca.\n           apply big_sum_eq_bounded.\n           intros. \n           unfold reduce_col, reduce_row.\n           bdestruct (x + x0 <? x); try lia.\n           assert (p1 : (1 + (x + x0)) = (x + S x0)). lia. \n           rewrite p1. easy. }\n         assert (H1' : (big_sum (fun y : nat => reduce_col T x i y * reduce_row a x y j) m +\n                       (a x 0) * get_vec x T i j + (a x 0) * (- (get_vec x T i j)) = \n                       (- (a x 0)) * get_vec x T i j)%C).\n         { rewrite H'. lca. }\n         rewrite <- Cplus_assoc in H1'.\n         rewrite <- Cmult_plus_distr_l in H1'.\n         rewrite Cplus_opp_r in H1'.\n         rewrite Cmult_0_r, Cplus_0_r in H1'.\n         rewrite H1'. \n         rewrite Cmult_assoc. \n         rewrite <- Copp_mult_distr_r.\n         rewrite Cinv_l; easy. \n       - assert (H' : a x 0 = C0).\n         apply H1; try lia.\n         easy. \nQed.\n\n\nLemma gt_dim_lindep_ind_step1 : forall {n m} (T : Matrix (S n) (S m)) (col : nat),\n  WF_Matrix T -> col <= m -> get_vec col T = @e_i (S n) 0 -> \n  linearly_dependent (reduce_row (reduce_col T col) 0) -> linearly_dependent T.\nProof. intros.  \n       apply (mat_prop_col_add_each_conv _ _ col (-C1 .* (get_row 0 T))); \n         auto with wf_db; try lia.\n       apply lin_dep_add_invr.\n       unfold linearly_dependent in *.\n       destruct H2 as [a [H3 [H4 H5]]]. \n       repeat rewrite Sn_minus_1 in *.\n       exists (row_wedge a (@Zero 1 1) col).\n       split; auto with wf_db.\n       split. \n       + unfold not in *. \n         intros. apply H4. \n         prep_matrix_equality.\n         bdestruct (x <? col).\n         assert (H' : (row_wedge a Zero col) x y = C0 ).\n         { rewrite H2. easy. }\n         unfold row_wedge in *. \n         bdestruct (x <? col); try lia. easy. \n         assert (H' : (row_wedge a Zero col) (S x) y = C0 ).\n         { rewrite H2. easy. }\n         unfold row_wedge in *.\n         bdestruct (S x <? col); bdestruct (S x =? col); try lia. \n         rewrite Sn_minus_1 in *; easy. \n       + repeat rewrite Sn_minus_1 in *.\n         apply mat_equiv_eq; auto with wf_db.\n         apply WF_mult; auto with wf_db.\n         unfold mat_equiv; intros. \n         assert (H' : (get_vec col T) i 0 = @e_i (S n) 0 i 0).\n         { rewrite H1. easy. }  \n         unfold col_add_each, make_col_zero, get_row, Mmult, Mplus, get_vec, \n         scale, row_append, row_wedge.\n         destruct i.  \n         * unfold get_vec, e_i in H'; simpl in H'. \n           rewrite H'. unfold Zero. \n           apply (@big_sum_0_bounded C C_is_monoid). \n           intros; simpl.  \n           bdestruct (x =? col); bdestruct (x <? col); try lia; lca. \n         * unfold get_vec, e_i in H'; simpl in H'. \n           assert (H0' : (reduce_row (reduce_col T col) 0 × a) i j = @Zero (S n) 1 (S i) j).\n           repeat rewrite Sn_minus_1 in *; rewrite H5. easy.\n           rewrite <- H0'.\n           unfold Mmult, reduce_row, reduce_col.\n           repeat rewrite Sn_minus_1 in *.\n           assert (p : S m = col + (S m - col)). lia.\n           rewrite p, big_sum_sum.\n           assert (p1 : S m - col = S (m - col)). lia. \n           rewrite p1, <- big_sum_extend_l. \n           simpl. bdestruct (col + 0 =? col); bdestruct (col + 0 <? col); try lia. \n           assert (p2 : m = col + (m - col)). lia.\n           rewrite p2, big_sum_sum, <- p2.\n           apply Cplus_simplify.\n           apply big_sum_eq_bounded; intros. \n           bdestruct (x <? col); bdestruct (x =? col); try lia.\n           rewrite H'. lca. \n           rewrite <- Cplus_0_l.\n           apply Cplus_simplify; try lca.\n           apply big_sum_eq_bounded; intros.\n           bdestruct (col + S x <? col); bdestruct (col + S x =? col); \n             bdestruct (col + x <? col); try lia. \n           assert (p4 : col + S x - 1 = col + x). lia. \n           assert (p5 : S (col + x) = col + S x). lia.  \n           rewrite H', p4, p5. lca. \nQed.             \n             \n\nLemma gt_dim_lindep_ind_step2 : forall {n m} (T : Matrix (S n) (S m)) \n                                       (v : Vector (S m)) (col : nat),\n  WF_Matrix T -> col < S m -> v col 0 = C0 ->\n  reduce_col (reduce_row T 0) col × (reduce_row v col) = \n                     - C1 .* get_vec col (reduce_row T 0) -> \n  linearly_dependent (reduce_row (reduce_col T col) 0) -> linearly_dependent T.\nProof. intros. \n       assert (H' := @col_add_many_cancel n m (reduce_row T 0) v col).\n       assert (H0' : forall i : nat, @col_add_many n (S m) col v  (reduce_row T 0) i col = C0).\n       { apply H'; try easy. }\n       apply (mat_prop_col_add_many_conv _ _ col v); try easy.\n       apply lin_dep_add_invr.\n       destruct (Ceq_dec ((col_add_many col v T) 0 col) C0).\n       - apply_mat_prop (@lin_dep_pzt). \n         apply H5; exists col. \n         split; auto. \n         prep_matrix_equality. unfold get_vec.\n         destruct y; try easy; simpl. \n         destruct x; try easy. unfold Zero.\n         rewrite <- (H0' x).\n         unfold col_add_many, reduce_row. \n         bdestruct (col =? col); bdestruct (x <? 0); try lia. \n         apply Cplus_simplify. \n         easy. unfold gen_new_vec.\n         do 2 rewrite Msum_Csum.\n         apply big_sum_eq_bounded; intros. \n         unfold scale, get_vec; lca.  \n       - apply (mat_prop_col_scale_conv _ _ col (/ (col_add_many col v T 0 col))); \n           try apply nonzero_div_nonzero; try easy.\n         apply lin_dep_scale_invr.\n         apply (gt_dim_lindep_ind_step1 _ col); try lia; auto with wf_db.\n         apply mat_equiv_eq; auto with wf_db.\n         unfold mat_equiv; intros. \n         unfold get_vec, e_i.\n         bdestruct (j =? 0); bdestruct (i =? 0); bdestruct (i <? S n); \n           try lia; simpl. \n         + unfold col_scale. bdestruct (col =? col); try lia. \n           rewrite H7. rewrite Cinv_l; easy.\n         + unfold col_scale. bdestruct (col =? col); try lia. \n           destruct i; try easy.\n           assert (r : col_add_many col v T (S i) col = \n                       col_add_many col v (reduce_row T 0) i col).\n           { unfold reduce_row, col_add_many, gen_new_vec, get_vec, scale.\n             bdestruct (col =? col); bdestruct (i <? 0); try lia. \n             apply Cplus_simplify; try easy.\n             do 2 rewrite Msum_Csum. \n             apply big_sum_eq_bounded; intros. \n             bdestruct (i <? 0); try lia; easy. }\n           rewrite r.  \n           rewrite (H0' i); lca. \n         + rewrite col_scale_reduce_col_same; try easy.\n           rewrite col_add_many_reduce_col_same. \n           easy.\nQed.\n\nLemma gt_dim_lindep : forall {m n} (T : Matrix n m),\n  n < m -> WF_Matrix T -> linearly_dependent T.\nProof. induction m as [| m'].\n       - intros; lia. \n       - intros. \n         destruct n as [| n'].\n         + exists (e_i 0).\n           split. apply WF_e_i.\n           split. unfold not; intros. \n           assert (H' : (@e_i (S m') 0) 0 0 = C0).\n           { rewrite H1; easy. }\n           unfold e_i in H'; simpl in H'.\n           apply C1_neq_C0; easy.\n           assert (H' : T = Zero). \n           { prep_matrix_equality. \n             rewrite H0; try easy; try lia. }\n           rewrite H'. apply Mmult_0_l.\n         + bdestruct (n' <? m'); try lia. \n           assert (H' : linearly_dependent (reduce_row T 0)).\n           { rewrite (reduce_append_split (reduce_row T 0)).\n             assert (H'' := @lin_dep_col_append_n n' m' \n                                (reduce_col (reduce_row T 0) m') (get_vec m' (reduce_row T 0))).\n             apply H''.\n             apply IHm'; try easy; auto with wf_db.\n             apply WF_reduce_col. lia. \n             all : apply WF_reduce_row; try lia; easy. }\n           apply lin_dep_gen_elem in H'; auto with wf_db.\n           destruct H' as [i [H2 H3]].\n           destruct H3 as [v [H3 H4]]. \n           * apply (gt_dim_lindep_ind_step2 _ (row_wedge v (@Zero 1 1) i) i); try easy.\n             unfold row_wedge.\n             bdestruct (i <? i); bdestruct (i =? i); try lia; easy.\n             rewrite row_wedge_reduce_row_same; easy.\n             apply (IHm' n' (reduce_row (reduce_col T i) 0)); try lia. \n             apply WF_reduce_row; try apply WF_reduce_col; try lia; easy. \n           * apply WF_reduce_row; try lia; easy.\nQed.\n\n(*****************************************************************************************)\n(** * defining a new type of matrix which we will show is the lin_indep/invertible matrices *)\n(*****************************************************************************************)\n\nInductive op_to_I {n : nat} : Square n -> Prop :=\n| otI_I: op_to_I (I n)\n| otI_swap : forall (A : Square n) (x y : nat), x < n -> y < n -> \n                                         op_to_I A -> op_to_I (col_swap A x y)\n| otI_scale : forall (A : Square n) (x : nat) (c : C), x < n -> c <> C0 -> \n                                         op_to_I A -> op_to_I (col_scale A x c)\n| otI_add : forall (A : Square n) (x y : nat) (c : C), x < n -> y < n -> x <> y -> \n                                         op_to_I A -> op_to_I (col_add A x y c).\n\n\nLemma op_to_I_WF : forall {n} (A : Square n),\n  op_to_I A -> WF_Matrix A.\nProof. intros.  \n       apply op_to_I_ind; auto with wf_db.\nQed.\n\n#[export] Hint Resolve op_to_I_WF : wf_db.\n\n\n(* this is useful since we can easily show that every op_to_I matrix has this prop *)\nDefinition otI_multiplicative {n} (A : Square n) : Prop := \n  forall (B : Square n), (op_to_I B -> op_to_I (B × A)).\n\nLemma otI_implies_otI_multiplicative : forall {n} (A : Square n),\n  op_to_I A -> otI_multiplicative A. \nProof. intros.   \n       apply op_to_I_ind; auto. \n       - unfold otI_multiplicative; intros.\n         rewrite Mmult_1_r; auto with wf_db.\n       - unfold otI_multiplicative; intros. \n         rewrite col_swap_mult_r; auto with wf_db.\n         rewrite <- Mmult_assoc. \n         rewrite <- col_swap_mult_r; auto with wf_db.\n         apply otI_swap; auto with wf_db.\n       - unfold otI_multiplicative; intros. \n         rewrite col_scale_mult_r; auto with wf_db.\n         rewrite <- Mmult_assoc. \n         rewrite <- col_scale_mult_r; auto with wf_db.\n         apply otI_scale; auto with wf_db.\n       - unfold otI_multiplicative; intros. \n         rewrite col_add_mult_r; auto with wf_db.\n         rewrite <- Mmult_assoc. \n         rewrite <- col_add_mult_r; auto with wf_db.\n         apply otI_add; auto with wf_db.\nQed.\n\n(* it follows that the op_to_I matrices are multiplicative *)\nLemma otI_Mmult : forall {n} (A B : Square n),\n  op_to_I A -> op_to_I B ->\n  op_to_I (A × B).\nProof. intros. \n       apply otI_implies_otI_multiplicative in H0.\n       unfold otI_multiplicative in H0.\n       apply H0; easy. \nQed.\n\n(* using a similar technique, will show that op_to_I is preserved by pad1 *) \nDefinition otI_pad1ed {n} (A : Square n) : Prop := \n  forall (c :  C), (c <> C0 -> op_to_I (pad1 A c)).\n\nLemma otI_implies_otI_pad1ed : forall {n} (A : Square n),\n  op_to_I A -> otI_pad1ed A.\nProof. intros. \n       apply op_to_I_ind; auto. \n       - unfold otI_pad1ed; intros. \n         assert (H' : (pad1 (I n) c) = col_scale (I (S n)) 0 c).\n         { apply mat_equiv_eq; auto with wf_db.\n           apply WF_pad1; apply WF_I.\n           unfold mat_equiv; intros. \n           unfold pad1, col_scale, col_wedge, row_wedge, e_i, scale, I.\n           bdestruct_all; easy. }\n         rewrite H'.\n         apply otI_scale; auto; try lia. \n         apply otI_I.\n       - intros. \n         unfold otI_pad1ed in *; intros. \n         rewrite pad1_col_swap. \n         apply otI_swap; try lia. \n         apply H3; easy. \n       - intros. \n         unfold otI_pad1ed in *; intros. \n         rewrite pad1_col_scale. \n         apply otI_scale; try lia; try easy. \n         apply H3; easy. \n       - intros. \n         unfold otI_pad1ed in *; intros. \n         rewrite pad1_col_add. \n         apply otI_add; try lia; try easy. \n         apply H4; easy. \nQed.\n\nLemma otI_pad1 : forall {n} (A : Square n) (c : C),\n  c <> C0 -> op_to_I A -> \n  op_to_I (pad1 A c).\nProof. intros. \n       apply otI_implies_otI_pad1ed in H0.\n       unfold otI_pad1ed in H0.\n       apply H0; easy. \nQed.\n\nLemma otI_lin_indep : forall {n} (A : Square n),\n  op_to_I A -> linearly_independent A.\nProof. intros. \n       apply op_to_I_ind; auto. \n       - unfold linearly_independent; intros. \n         rewrite Mmult_1_l in H1; auto with wf_db.\n       - intros. \n         apply_mat_prop lin_indep_swap_invr.\n         apply H5; auto. \n       - intros. \n         apply_mat_prop lin_indep_scale_invr.\n         apply H5; auto. \n       - intros. \n         apply_mat_prop lin_indep_add_invr.\n         apply H6; auto. \nQed.\n\n\n(* need alternate def to deal with broader n <> m case *)\nDefinition op_to_I' {n m : nat} (A : Matrix n m) :=\n  n = m /\\ @op_to_I n A.\n\nLemma otI_equiv_otI' : forall {n} (A : Square n),\n  op_to_I' A <-> op_to_I A.\nProof. intros. split. \n       - intros. \n         destruct H; easy. \n       - intros. \n         split; easy. \nQed.\n\nLemma otI'_add_invr : invr_col_add (@op_to_I').\nProof. apply invr_add; intros. \n       destruct H2; split; try easy; subst. \n       apply otI_add; easy. \nQed.\n\nLemma otI_col_add_many : forall (n col : nat) (A : Square n) (as' : Vector n),\n  col < n -> as' col 0 = C0 -> \n  op_to_I A -> op_to_I (col_add_many col as' A).\nProof. intros. \n       assert (H' := otI'_add_invr).\n       apply invr_col_add_col_add_many in H'. \n       inversion H'; subst. \n       apply (H2 n n col A as') in H; try easy. \n       destruct H; easy. \nQed.\n\nLemma otI_col_add_each : forall (n col : nat) (A : Square n) (as' : Matrix 1 n),\n  col < n -> WF_Matrix as' -> as' 0 col = C0 ->  \n  op_to_I A -> op_to_I (col_add_each col as' A).\nProof. intros. \n       assert (H' := otI'_add_invr).\n       apply invr_col_add_col_add_each in H'. \n       inversion H'; subst. \n       apply (H3 n n col A as') in H; try easy. \n       assert (H4 : (make_col_zero col as') = as').\n       { apply mat_equiv_eq; auto with wf_db.\n         unfold mat_equiv; intros. \n         unfold make_col_zero.\n         destruct i; try lia.\n         bdestruct_all; subst; easy. }\n       rewrite H4 in *.\n       destruct H; easy. \nQed.\n\n\n(**********************************************)\n(** *  Now we prove more properties of invariants *) \n(**********************************************)\n\n         \n(** a case for when we consider (Mat -> Prop)s that are the same as lin_indep, invertible, \n   etc... these props will satisfy 'prop_zero_false P' *)\nLemma mpr_step1_pzf_P : forall {n} (A : Square (S n)) (P : forall m o, Matrix m o -> Prop),\n  invr_col_add P -> invr_col_scale P -> \n  prop_zero_false P -> \n  WF_Matrix A -> P (S n) (S n) A ->\n  (exists B : Square (S n), op_to_I B /\\ P (S n) (S n) (A × B) /\\\n                       (exists i, i < (S n) /\\ get_vec i (A × B) = e_i 0)).\nProof. intros.  \n       assert (H4 : WF_Matrix (reduce_row A 0)).\n       { apply WF_reduce_row; try lia; easy. } \n       assert (H5 : linearly_dependent (reduce_row A 0)).\n       { apply gt_dim_lindep; try lia. \n         apply H4. }\n       apply lin_dep_gen_elem in H4; try easy. \n       destruct H4 as [i [H6 H4]]. \n       destruct H4 as [v [H4 H7]].\n       apply invr_col_add_col_add_many in H.\n       inversion H; subst.\n       assert (H9 : P (S n) (S n) (col_add_many i (row_wedge v Zero i) A)).\n       apply H8; auto. \n       unfold row_wedge; bdestruct_all; easy.\n       destruct (Ceq_dec ((col_add_many i (row_wedge v Zero i) A) 0 i) C0).\n       - assert (H10 : forall i0 : nat, \n                   col_add_many i (row_wedge v Zero i) (reduce_row A 0) i0 i = C0).\n         apply (col_add_many_cancel (reduce_row A 0) (row_wedge v Zero i) i); try easy.\n         unfold row_wedge. \n         bdestruct (i <? i); bdestruct (i =? i); try lia; easy. \n         rewrite row_wedge_reduce_row_same. \n         easy. \n         assert (H11: get_vec i (col_add_many i (row_wedge v Zero i) A) = Zero).\n         { apply mat_equiv_eq; auto with wf_db.\n           unfold mat_equiv; intros. \n           destruct j; try lia.\n           unfold get_vec; simpl. \n           destruct i0.\n           rewrite e; easy.\n           rewrite col_add_many_reduce_row in H10.\n           replace ((@Zero (S n) 1 (S i0) 0)) with C0 by easy.  \n           rewrite <- (H10 i0).\n           unfold reduce_row.\n           bdestruct (i0 <? 0); try lia. \n           easy. }\n         inversion H1; subst.\n         assert (H13 : ~ P (S n) (S n) (col_add_many i (row_wedge v Zero i) A)).\n         { apply H12.\n           exists i; split; auto. }\n         easy.\n       - inversion H0; subst. \n         assert (n0' := n0).\n         apply nonzero_div_nonzero in n0.\n         apply (H10 _ _ i (col_add_many i (row_wedge v Zero i) A)\n                 (/ col_add_many i (row_wedge v Zero i) A 0 i)) in n0.\n         assert (H11 : forall i0 : nat, \n                   col_add_many i (row_wedge v Zero i) (reduce_row A 0) i0 i = C0).\n         apply (col_add_many_cancel (reduce_row A 0) (row_wedge v Zero i) i); try easy.\n         unfold row_wedge.  \n         bdestruct (i <? i); bdestruct (i =? i); try lia; easy. \n         rewrite row_wedge_reduce_row_same. \n         easy. \n         rewrite col_add_many_reduce_row in H11.                \n         exists ((row_add_each i (row_wedge v Zero i) (I (S n))) × \n                  (row_scale (I (S n)) i \n                  (/ (col_add_many i (row_wedge v Zero i) A 0 i)))).\n         split. \n         apply otI_Mmult.\n         rewrite row_each_col_many_invr_I; auto with wf_db.\n         apply otI_col_add_many; auto with wf_db. \n         all : try (unfold row_wedge; bdestruct_all; easy).\n         apply otI_I.\n         apply WF_row_wedge; auto with wf_db; try lia.\n         rewrite <- col_row_scale_invr_I.\n         apply otI_scale; auto with wf_db.\n         apply nonzero_div_nonzero; auto. \n         apply otI_I.\n         rewrite <- Mmult_assoc.\n         rewrite <- col_add_many_mult_r; try easy.\n         rewrite <- col_scale_mult_r; try easy.\n         split; try easy.\n         exists i. split; try easy.\n         apply mat_equiv_eq; auto with wf_db.\n         unfold mat_equiv; intros. \n         destruct j; try lia. \n         unfold get_vec, col_scale.\n         bdestruct (i =? i); simpl; try lia.  \n         destruct i0.\n         rewrite Cinv_l; try easy.\n         assert (H15 : col_add_many i (row_wedge v Zero i) A (S i0) i = C0).\n         rewrite <- (H11 i0).\n         unfold reduce_row.\n         bdestruct (i0 <? 0); try lia; easy.\n         rewrite H15. lca. \n         apply WF_col_add_many; auto with wf_db.\n         apply WF_row_wedge; auto with wf_db; lia.\n         unfold row_wedge.\n         bdestruct (i <? i); bdestruct (i =? i); try lia; easy. \nQed.   \n\n(** a different case for when we consider (Mat -> Prop)s that are \n   the same as lin_dep, not_invertible, etc... *)\nLemma mrp_step1_pzt_P0 : forall {n} (A : Square (S n)) (P P0: forall m o, Matrix m o -> Prop),\n  invr_col_add P -> invr_col_scale P -> \n  invr_col_add P0 -> prop_zero_true P0 -> \n  WF_Matrix A -> P (S n) (S n) A ->\n  (exists B : Square (S n), op_to_I B /\\ P (S n) (S n) (A × B) /\\\n                       (exists i, i < (S n) /\\ get_vec i (A × B) = e_i 0)) \\/ P0 (S n) (S n) A.\nProof. intros. \n       assert (H5 : WF_Matrix (reduce_row A 0)).\n       { apply WF_reduce_row; try lia; easy. }\n       assert (H6 : linearly_dependent (reduce_row A 0)).\n       { apply gt_dim_lindep; try lia. \n         apply H5. }\n       apply lin_dep_gen_elem in H5; try easy. \n       destruct H5 as [i [H7 H5]]. \n       destruct H5 as [v [H5 H8]].\n       apply invr_col_add_col_add_many in H.\n       inversion H; subst.\n       assert (H10 : P (S n) (S n) (col_add_many i (row_wedge v Zero i) A)).\n       apply H9; auto. \n       unfold row_wedge; bdestruct_all; easy.\n       destruct (Ceq_dec ((col_add_many i (row_wedge v Zero i) A) 0 i) C0).\n       - right. \n         assert (H11 : forall i0 : nat, \n                   col_add_many i (row_wedge v Zero i) (reduce_row A 0) i0 i = C0).\n         apply (col_add_many_cancel (reduce_row A 0) (row_wedge v Zero i) i); try easy.\n         unfold row_wedge. \n         bdestruct (i <? i); bdestruct (i =? i); try lia; easy. \n         rewrite row_wedge_reduce_row_same. \n         easy. \n         assert (H12: get_vec i (col_add_many i (row_wedge v Zero i) A) = Zero).\n         { apply mat_equiv_eq; auto with wf_db.\n           unfold mat_equiv; intros. \n           destruct j; try lia.\n           unfold get_vec; simpl. \n           destruct i0.\n           rewrite e; easy.\n           rewrite col_add_many_reduce_row in H11.\n           replace ((@Zero (S n) 1 (S i0) 0)) with C0 by easy.  \n           rewrite <- (H11 i0).\n           unfold reduce_row.\n           bdestruct (i0 <? 0); try lia. \n           easy. }\n         inversion H2; subst. \n         apply (mat_prop_col_add_many_conv _ _ i (row_wedge v Zero i)); auto. \n         unfold row_wedge; bdestruct_all; easy.\n         apply H13.\n         exists i. split; auto. \n       - inversion H0; subst. \n         assert (n0' := n0).\n         left. \n         apply nonzero_div_nonzero in n0.\n         apply (H11 _ _ i (col_add_many i (row_wedge v Zero i) A)\n                 (/ col_add_many i (row_wedge v Zero i) A 0 i)) in n0.\n         assert (H12 : forall i0 : nat, \n                   col_add_many i (row_wedge v Zero i) (reduce_row A 0) i0 i = C0).\n         apply (col_add_many_cancel (reduce_row A 0) (row_wedge v Zero i) i); try easy.\n         unfold row_wedge.  \n         bdestruct (i <? i); bdestruct (i =? i); try lia; easy. \n         rewrite row_wedge_reduce_row_same. \n         easy. \n         rewrite col_add_many_reduce_row in H12.                \n         exists ((row_add_each i (row_wedge v Zero i) (I (S n))) × \n                  (row_scale (I (S n)) i \n                  (/ (col_add_many i (row_wedge v Zero i) A 0 i)))).\n         split. \n         apply otI_Mmult.\n         rewrite row_each_col_many_invr_I; auto with wf_db.\n         apply otI_col_add_many; auto with wf_db. \n         all : try (unfold row_wedge; bdestruct_all; easy).\n         apply otI_I.\n         apply WF_row_wedge; auto with wf_db; try lia.\n         rewrite <- col_row_scale_invr_I.\n         apply otI_scale; auto with wf_db.\n         apply nonzero_div_nonzero; auto. \n         apply otI_I.\n         rewrite <- Mmult_assoc.\n         rewrite <- col_add_many_mult_r; try easy.\n         rewrite <- col_scale_mult_r; try easy.\n         split; try easy.\n         exists i. split; try easy.\n         apply mat_equiv_eq; auto with wf_db.\n         unfold mat_equiv; intros. \n         destruct j; try lia. \n         unfold get_vec, col_scale.\n         bdestruct (i =? i); simpl; try lia.  \n         destruct i0.\n         rewrite Cinv_l; try easy.\n         assert (H16 : col_add_many i (row_wedge v Zero i) A (S i0) i = C0).\n         rewrite <- (H12 i0).\n         unfold reduce_row.\n         bdestruct (i0 <? 0); try lia; easy.\n         rewrite H16. lca. \n         apply WF_col_add_many; auto with wf_db.\n         apply WF_row_wedge; auto with wf_db; lia.\n         unfold row_wedge.\n         bdestruct (i <? i); bdestruct (i =? i); try lia; easy. \nQed.   \n\n(** in both cases, we can use mrp_step2 when we get that (exists i, ... ) *) \nLemma mpr_step2 : forall {n} (A : Square (S n)) (P : forall m o, Matrix m o -> Prop), \n  invr_col_add P -> invr_col_swap P -> \n  WF_Matrix A -> P (S n) (S n) A ->  \n  (exists i, i < (S n) /\\ get_vec i A = e_i 0) ->\n  (exists B : Square (S n), op_to_I B /\\ P (S n) (S n) (A × B) /\\\n                            (exists a : Square n, pad1 a C1 = (A × B))).\nProof. intros.\n       destruct H3 as [i [H3 H4]].\n       inversion H0; subst.\n       apply (H5 _ _ 0 i A) in H2; try lia; try easy.\n       apply invr_col_add_col_add_each in H.\n       inversion H; subst.\n       assert (H3' : 0 < S n). lia.\n       apply (H6 _ _ 0 (col_swap A 0 i) (-C1 .* (get_row 0 (col_swap A 0 i)))) in H3'; try lia.\n       exists ((row_swap (I (S n)) 0 i) × (row_add_many 0 \n                                (make_col_zero 0 (-C1 .* (get_row 0 (col_swap A 0 i)))) \n                                (I (S n)))).\n       split. \n       apply otI_Mmult.\n       rewrite <- col_row_swap_invr_I; try lia. \n       apply otI_swap; try lia; apply otI_I.\n       rewrite row_many_col_each_invr_I; try lia; auto.\n       apply otI_col_add_each; try lia; auto with  wf_db.\n       all : try (apply WF_make_col_zero; apply WF_scale; \n         apply WF_get_row; apply WF_col_swap; try lia; auto).  \n       apply otI_I.\n       rewrite <- Mmult_assoc. \n       rewrite <- col_swap_mult_r; try lia; try easy.\n       rewrite <- col_add_each_mult_r; try lia; try easy.\n       split; try easy.\n       apply pad1ed_matrix; intros. \n       4 : apply WF_make_col_zero.\n       all : try (apply WF_scale; apply WF_get_row).  \n       all : try (apply WF_col_swap; try lia; easy).\n       destruct H7 as [H7 H8].\n       destruct H7. \n       + unfold col_add_each, make_col_zero, get_row, col_swap, \n         Mplus, Mmult, get_vec, scale.\n         rewrite H7 in *.\n         bdestruct (j =? 0); try lia. \n         assert (H' : (get_vec i A) 0 0 = C1).\n         { rewrite H4. easy. }\n         simpl. bdestruct (j =? i); try lia. \n         all : unfold get_vec in H'; simpl in H'.\n         all : rewrite H'; lca. \n       + unfold col_add_each, make_col_zero, get_row, col_swap, \n         Mplus, Mmult, get_vec, scale.\n         rewrite H7 in *; simpl. \n         destruct i0; try lia.\n         assert (H' : (get_vec i A) (S i0) 0 = C0).\n         { rewrite H4. easy. }\n         unfold get_vec in H'; simpl in H'. \n         rewrite H'; lca. \n       + unfold col_add_each, make_col_zero, get_row, col_swap, \n         Mplus, Mmult, get_vec, scale; simpl.\n         assert (H' : (get_vec i A) 0 0 = C1).\n         { rewrite H4. easy. }\n         unfold get_vec in H'; simpl in H'.\n         rewrite H'; lca.\n       + easy. \nQed.    \n\n\n(** these two lemmas allow us to reduce our study of Square (S n) to Square n, allowing \n   us to induct on n. Then, 'invr_pad1 P' allows us to jump from the n case to (S n) *) \nLemma mat_prop_reduce_pzf_P : forall {n} (A : Square (S n)) (P : forall m o, Matrix m o -> Prop), \n  invr_col_swap P -> invr_col_scale P -> \n  invr_col_add P -> prop_zero_false P ->   \n  invr_pad1 P -> \n  WF_Matrix A -> P (S n) (S n) A -> \n  (exists B : Square (S n), op_to_I B /\\ P (S n) (S n) (A × B) /\\\n                            (exists a : Square n, pad1 a C1 = (A × B))). \nProof. intros. \n       apply (mpr_step1_pzf_P A P) in H5; auto.  \n       destruct H5 as [B [H5 [H6 [i [H7 H8]]]]].\n         apply (mpr_step2 (A × B) P) in H1; auto with wf_db.  \n         destruct H1 as [B0 [H10 [H11 H12]]].\n         exists (B × B0); split.  \n         apply otI_Mmult; auto. \n         split; rewrite <- Mmult_assoc; easy.  \n         exists i. split; easy. \nQed.\n\nLemma mat_prop_reduce_pzt_P0 : forall {n} (A : Square (S n)) (P P0 : forall m o, Matrix m o -> Prop), \n  invr_col_swap P -> invr_col_scale P -> \n  invr_col_add P -> \n  invr_pad1 P -> \n  invr_col_add P0 -> prop_zero_true P0 -> \n  WF_Matrix A -> P (S n) (S n) A -> \n  (exists B : Square (S n), op_to_I B /\\ P (S n) (S n) (A × B) /\\\n                            (exists a : Square n, pad1 a C1 = (A × B))) \\/ P0 (S n) (S n) A.\nProof. intros. \n       apply (mrp_step1_pzt_P0 A P P0) in H6; auto. \n       destruct H6.\n       - left. \n         destruct H6 as [B [H6 [H7 [i [H8 H9]]]]].\n         apply (mpr_step2 (A × B) P) in H1; auto with wf_db.  \n         destruct H1 as [B0 [H10 [H11 H12]]].\n         exists (B × B0); split.  \n         apply otI_Mmult; auto. \n         split; rewrite <- Mmult_assoc; easy.  \n         exists i. split; easy. \n       - right; easy. \nQed.\n\n\n(** now, we prove some theorems with these powerful lemmas *)\nTheorem invr_P_implies_invertible_r : forall {n} (A : Square n) (P : forall m o, Matrix m o -> Prop), \n  invr_col_swap P -> invr_col_scale P -> \n  invr_col_add P -> prop_zero_false P ->   \n  invr_pad1 P -> \n  WF_Matrix A -> P n n A -> \n  (exists B, op_to_I B /\\ A × B = I n).\nProof. induction n as [| n'].\n       - intros.  \n         exists (I 0). split.\n         apply otI_I.\n         assert (H' : I 0 = Zero). \n         prep_matrix_equality. \n         unfold I; bdestruct_all; easy. \n         rewrite H', Mmult_0_r.\n         apply mat_equiv_eq; auto with wf_db. \n         unfold mat_equiv. lia.  \n       - intros. \n         apply mat_prop_reduce_pzf_P in H5; auto. \n         destruct H5 as [B [H5 [H6 [a H7]]]].\n         rewrite <- H7 in H6.\n         inversion H3; subst. \n         apply H8 in H6. \n         apply IHn' in H6; auto.\n         destruct H6 as [B0 [H9 H10]].\n         exists (B × (pad1 B0 C1)). \n         split. \n         apply otI_Mmult; auto. \n         apply otI_pad1; auto. \n         all : try apply C1_neq_C0.  \n         rewrite <- Mmult_assoc, <- H7.          \n         rewrite <- pad1_mult, H10, Cmult_1_l, pad1_I; easy.\n         apply (WF_pad1 a C1). \n         rewrite H7; auto with wf_db. \nQed.\n\n\nCorollary lin_ind_implies_invertible_r : forall {n} (A : Square n),\n  WF_Matrix A ->\n  linearly_independent A -> \n  (exists B, op_to_I B /\\ A × B = I n).\nProof. intros. \n       apply (invr_P_implies_invertible_r _ (@linearly_independent));\n         auto with invr_db.\nQed.\n\n\n(*******************************)\n(** * Inverses of square matrices *)\n(*******************************) \n\nDefinition Minv {n : nat} (A B : Square n) : Prop := A × B = I n /\\ B × A = I n.\n\n\nDefinition invertible {n : nat} (A : Square n) : Prop :=\n  exists B, Minv A B.\n\n\nLemma Minv_unique : forall (n : nat) (A B C : Square n), \n                      WF_Matrix A -> WF_Matrix B -> WF_Matrix C ->\n                      Minv A B -> Minv A C -> B = C.\nProof.\n  intros n A B C WFA WFB WFC [HAB HBA] [HAC HCA].\n  replace B with (B × I n) by (apply Mmult_1_r; assumption).\n  rewrite <- HAC.  \n  replace C with (I n × C) at 2 by (apply Mmult_1_l; assumption).\n  rewrite <- HBA.  \n  rewrite Mmult_assoc.\n  reflexivity.\nQed.\n\nLemma Minv_symm : forall (n : nat) (A B : Square n), Minv A B -> Minv B A.\nProof. unfold Minv; intuition. Qed.\n\n(* The left inverse of a square matrix is also its right inverse *)\nLemma Minv_flip : forall (n : nat) (A B : Square n), \n  WF_Matrix A -> WF_Matrix B ->  \n  A × B = I n -> B × A = I n.\nProof. intros.   \n       assert (H3 := H1).\n       apply invertible_l_implies_linind in H1.\n       apply lin_ind_implies_invertible_r in H1; try easy.\n       destruct H1 as [A' [H2 H4]].\n       assert (H' : (A × B) × A' = A').\n       { rewrite H3. apply Mmult_1_l; auto with wf_db. }\n       rewrite Mmult_assoc in H'.\n       rewrite H4 in H'.\n       rewrite Mmult_1_r in H'; try easy.\n       rewrite H'; easy.\nQed.\n\nLemma Minv_left : forall (n : nat) (A B : Square n), \n    WF_Matrix A -> WF_Matrix B -> \n    A × B = I n -> Minv A B.\nProof.\n  intros n A B H H0 H1. \n  unfold Minv. split; trivial.\n  apply Minv_flip; \n  assumption.\nQed.\n\nLemma Minv_right : forall (n : nat) (A B : Square n), \n    WF_Matrix A -> WF_Matrix B -> \n    B × A = I n -> Minv A B.\nProof.\n  intros n A B H H0. \n  unfold Minv. split; trivial.\n  apply Minv_flip;\n  assumption.\nQed.\n\n\nCorollary lin_indep_invertible : forall (n : nat) (A : Square n),\n  WF_Matrix A -> (linearly_independent A <-> invertible A).\nProof. intros; split.\n       - intros. \n         assert (H1 := H).\n         apply lin_ind_implies_invertible_r in H; try easy.\n         destruct H as [B [H H2]].\n         unfold invertible.\n         exists B. unfold Minv.\n         split; try easy.\n         apply Minv_flip in H2; auto with wf_db. \n       - intros. \n         destruct H0 as [B [H1 H2]].\n         apply invertible_l_implies_linind in H2.\n         easy.\nQed.\n\nLemma Minv_otI_l : forall (n : nat) (A B : Square n),\n  WF_Matrix A -> WF_Matrix B -> \n  Minv A B ->\n  op_to_I A.\nProof. intros.           \n       assert (H2 := lin_indep_invertible).\n       assert (H3 : invertible B).\n       { exists A. apply Minv_symm; easy. }\n       apply H2 in H3; auto. \n       apply lin_ind_implies_invertible_r in H3; auto. \n       destruct H3 as [B' [H3 H4]].\n       apply Minv_left in H4; auto with wf_db.\n       apply Minv_symm in H1.\n       apply (Minv_unique _ B A B') in H4; auto with wf_db; subst.\n       easy. \nQed.\n\n\n(*********************************************)\n(** * We finish proving lemmas about invarients *)\n(*********************************************)\n\n(** Finally, we show that if all 6 nice properties are true about two (Mat -> Prop)s, then\n   they are equivalent on well formed matrices *)\nTheorem invr_P_equiv_otI : forall {n} (A : Square n) (P : forall m o, Matrix m o -> Prop), \n  invr_col_swap P -> invr_col_scale P -> \n  invr_col_add P -> prop_zero_false P ->   \n  invr_pad1 P -> P n n (I n) -> \n  WF_Matrix A -> \n  (P n n A <-> op_to_I A).  \nProof. intros. split. \n       - intros. \n         apply invr_P_implies_invertible_r in H6; auto. \n         destruct H6 as [B [H6 H7]]. \n         apply (Minv_otI_l _ A B); auto with wf_db.\n         apply Minv_left; auto with wf_db.\n       - intros. \n         apply op_to_I_ind; auto; intros.  \n         + inversion H; subst. \n           apply H11; easy. \n         + inversion H0; subst. \n           apply H11; easy. \n         + inversion H1; subst. \n           apply H12; easy.\nQed.\n\n(** slightly weaker version, if 4 nice properties are true, then op_to_I -> P *)\nTheorem invr_P_implies_otI_weak : forall {n} (A : Square n) (P : forall m o, Matrix m o -> Prop), \n  invr_col_swap P -> invr_col_scale P -> \n  invr_col_add P -> \n  P n n (I n) -> \n  (op_to_I A -> P n n A).  \nProof. intros. \n       apply op_to_I_ind; auto; intros.  \n       + inversion H; subst. \n         apply H8; easy. \n       + inversion H0; subst. \n         apply H8; easy. \n       + inversion H1; subst. \n         apply H9; easy.\nQed.\n\nCorollary lin_indep_det_neq_0 : forall {n} (A : Square n),\n  WF_Matrix A -> (linearly_independent A <-> det_neq_0 A).\nProof. intros. split.  \n       - intros. \n         apply invr_P_equiv_otI in H0; auto with invr_db.      \n         apply invr_P_equiv_otI; auto with invr_db.\n         split; auto. \n         rewrite Det_I; apply C1_neq_C0.\n         unfold linearly_independent; intros. \n         rewrite Mmult_1_l in H3; auto. \n       - intros. \n         apply invr_P_equiv_otI in H0; auto with invr_db.    \n         apply invr_P_equiv_otI; auto with invr_db.\n         unfold linearly_independent; intros. \n         rewrite Mmult_1_l in H2; auto. \n         split; auto. \n         rewrite Det_I; apply C1_neq_C0.\nQed.\n\nCorollary lin_dep_det_eq_0 : forall {n} (A : Square n), \n  WF_Matrix A -> (linearly_dependent A <-> det_eq_c C0 A).\nProof. induction n as [| n'].\n       - intros. split; intros.\n         destruct H0 as [v [H0 [H1 H2]]]. \n         assert (H' : v = Zero).\n         { apply mat_equiv_eq; auto with wf_db. \n           unfold mat_equiv; easy. }\n         easy.          \n         destruct H0.\n         unfold Determinant in H1.\n         assert (H2 := C1_neq_C0).\n         easy.\n       - intros.\n         split; intros.  \n         + split; try easy. \n           apply lindep_implies_not_linindep in H0.\n           assert (H' : ~  (det_neq_0 A)).\n           unfold not; intros; apply H0.\n           apply lin_indep_det_neq_0; auto. \n           unfold not in H'. \n           destruct (Ceq_dec (Determinant A) C0); try easy. \n           assert (H'' : False). apply H'.\n           split; easy. \n           easy. \n         + apply (mat_prop_reduce_pzt_P0 _ _ (@linearly_dependent)) in H0; \n             auto with invr_db.\n           destruct H0; try easy. \n           destruct H0 as [B [H0 [H1 [a H2]]]]. \n           assert (H' : linearly_dependent a).\n           { apply IHn'. \n             apply <- (@WF_pad1 n' n' a C1). \n             rewrite H2; auto with wf_db. \n             apply_mat_prop det_0_pad1_invr.           \n             apply (H4 n' n' a C1).\n             apply C1_neq_C0.\n             rewrite H2; easy. }\n           unfold linearly_dependent in *.\n           destruct H' as [v [H3 [H4 H5]]].\n           exists (B × (row_wedge v Zero 0)); split.\n           apply WF_mult; auto with wf_db.\n           apply WF_row_wedge; try lia; auto with wf_db. split.  \n           unfold not; intros; apply H4.\n           assert (H7 := H0); apply otI_lin_indep in H7.\n           apply lin_indep_invertible in H7; auto with wf_db.\n           destruct H7 as [B0 H7].\n           assert (H8 : B0 × (B × row_wedge v Zero 0) = Zero). { rewrite H6, Mmult_0_r; easy. } \n           destruct H7. \n           rewrite <- Mmult_assoc, H9, Mmult_1_l in H8. \n           prep_matrix_equality. \n           assert (H' : row_wedge v Zero 0 (S x) y = C0). { rewrite H8; easy. }\n           unfold Zero; rewrite <- H'.\n           unfold row_wedge; bdestruct_all.  \n           rewrite Sn_minus_1; easy. \n           apply WF_row_wedge; try lia;  auto with wf_db.\n           rewrite <- Mmult_assoc, <- H2.\n           rewrite pad1_row_wedge_mult, H5.\n           prep_matrix_equality.\n           unfold row_wedge. \n           bdestruct_all; easy. \nQed.\n\n\nCorollary lin_dep_indep_dec : forall {n} (A : Square n),\n  WF_Matrix A -> { linearly_independent A } + { linearly_dependent A }. \nProof. intros. \n       destruct (Ceq_dec (Determinant A) C0).\n       - right. \n         apply lin_dep_det_eq_0; auto. \n         split; easy. \n       - left. \n         apply lin_indep_det_neq_0; auto.\n         split; easy. \nQed.\n\n(*************************************************************************************)\n(** * we define another set of invariants to help show that Det A × Det B = Det (A × B) *)\n(*************************************************************************************)\n\nDefinition Det_mult_comm_l (n m : nat) (A : Matrix n m) :=\n  n = m /\\ (forall (B : Square n), (Determinant B) * (@Determinant n A) = (@Determinant n (B × A)))%C.\n\n\nLemma Dmc_I : forall {n}, Det_mult_comm_l n n (I n).\nProof. intros. \n       unfold Det_mult_comm_l; split; auto.\n       intros. \n       rewrite Det_I, Det_make_WF, (Det_make_WF _ (B × I n)).\n       rewrite <- Mmult_make_WF.\n       rewrite <- (eq_make_WF (I n)); auto with wf_db.\n       rewrite Mmult_1_r; auto with wf_db.\n       lca. \nQed.\n\nLemma Dmc_make_WF : forall {n} (A : Square n),\n  Det_mult_comm_l n n (make_WF A) <-> Det_mult_comm_l n n A.\nProof. intros; split; intros. \n       - destruct H; subst. \n         split; auto; intros. \n         rewrite (Det_make_WF _ A), H0.\n         rewrite <- Det_Mmult_make_WF_r; easy. \n       - destruct H; subst. \n         split; auto; intros. \n         rewrite <- Det_make_WF.\n         rewrite <- Det_Mmult_make_WF_r; easy. \nQed.\n\nLemma Dmc_Mmult : forall {n} (A B : Square n),\n  Det_mult_comm_l n n A -> Det_mult_comm_l n n B -> \n  Det_mult_comm_l n n (A × B).\nProof. intros. \n       destruct H; destruct H0; subst. \n       split; auto. \n       intros. \n       rewrite <- H2, Cmult_assoc, H1, H2, Mmult_assoc; easy.\nQed.\n\nLemma Dmc_swap_I : forall (n x y : nat),\n  x < n -> y < n -> \n  Det_mult_comm_l n n (row_swap (I n) x y).\nProof. intros.  \n       bdestruct (x =? y); subst. \n       - rewrite row_swap_same. \n         apply Dmc_I.\n       - split; auto; intros. \n         rewrite Det_Mmult_make_WF_l. \n         rewrite <- col_swap_mult_r; auto with wf_db.\n         rewrite <- col_row_swap_invr_I; auto.\n         rewrite Determinant_swap, Det_I, Determinant_swap; auto.\n         rewrite Det_make_WF; lca. \nQed.\n\nLemma Dmc_scale_I : forall (n x : nat) (c : C),\n  Det_mult_comm_l n n (row_scale (I n) x c).\nProof. intros.  \n       split; auto; intros. \n       rewrite Det_Mmult_make_WF_l. \n       rewrite <- col_scale_mult_r; auto with wf_db.\n       rewrite <- col_row_scale_invr_I; auto.\n       bdestruct (x <? n).\n       - rewrite Determinant_scale, Det_I, Determinant_scale; auto.\n         rewrite Det_make_WF; lca. \n       - assert (H' : (col_scale (I n) x c) = I n).\n         { apply mat_equiv_eq; auto with wf_db.\n           unfold mat_equiv, col_scale, I; intros. \n           bdestruct_all; easy. }\n         assert (H'' : (col_scale (make_WF B) x c) = make_WF B).\n         { apply mat_equiv_eq; auto with wf_db.\n           unfold mat_equiv, col_scale, I; intros. \n           bdestruct_all; easy. }\n         rewrite H', H''.\n         rewrite Det_make_WF, Det_I; lca. \nQed. \n\nLemma Dmc_add_I : forall (n x y : nat) (c : C),\n  x <> y -> x < n -> y < n -> Det_mult_comm_l n n (row_add (I n) x y c).\nProof. intros.  \n       split; auto; intros. \n       rewrite Det_Mmult_make_WF_l. \n       rewrite <- col_add_mult_r; auto with wf_db.\n       rewrite <- col_row_add_invr_I; auto.\n       rewrite Determinant_col_add, Det_I, Determinant_col_add; auto.\n       rewrite Det_make_WF; lca. \nQed.\n\n(* proving Dmc invariants *)\nLemma Dmc_swap_invr : invr_col_swap (Det_mult_comm_l).\nProof. apply invr_swap; intros.   \n       bdestruct (x =? y); subst.\n       - rewrite col_swap_same; easy.\n       - bdestruct (n =? m); subst; try (destruct H1; easy).\n         apply Dmc_make_WF.       \n         rewrite <- col_swap_make_WF; auto.\n         rewrite col_swap_mult_r; auto with wf_db. \n         apply Dmc_Mmult.\n         apply Dmc_make_WF; easy.\n         apply Dmc_swap_I; auto. \nQed.\n\nLemma Dmc_scale_invr : invr_col_scale (Det_mult_comm_l).\nProof. apply invr_scale; intros.   \n       bdestruct (n =? m); subst; try (destruct H0; easy).\n       apply Dmc_make_WF.       \n       rewrite <- col_scale_make_WF; auto.\n       rewrite col_scale_mult_r; auto with wf_db. \n       apply Dmc_Mmult.\n       apply Dmc_make_WF; easy.\n       apply Dmc_scale_I; auto. \nQed.\n\nLemma Dmc_add_invr : invr_col_add (Det_mult_comm_l).\nProof. apply invr_add; intros.   \n       bdestruct (n =? m); subst; try (destruct H2; easy).\n       apply Dmc_make_WF.       \n       rewrite <- col_add_make_WF; auto.\n       rewrite col_add_mult_r; auto with wf_db. \n       apply Dmc_Mmult.\n       apply Dmc_make_WF; easy.\n       apply Dmc_add_I; auto. \nQed.\n\nLocal Close Scope nat_scope.\n\nLemma otI_Dmc : forall {n} (A : Square n),\n  op_to_I A -> Det_mult_comm_l n n A.\nProof. intros n A. \n       apply invr_P_implies_otI_weak.\n       apply_mat_prop Dmc_swap_invr.\n       apply_mat_prop Dmc_scale_invr.\n       apply_mat_prop Dmc_add_invr.\n       apply Dmc_I. \nQed. \n\nLemma Determinant_multiplicative_WF : forall {n} (A B : Square n), \n  WF_Matrix A -> WF_Matrix B -> \n  (Determinant A) * (Determinant B) = Determinant (A × B).\nProof. intros. \n       destruct (lin_dep_indep_dec B); auto. \n       - apply invr_P_equiv_otI in l; auto with invr_db. \n         apply otI_Dmc in l; destruct l. \n         apply H2. \n         unfold linearly_independent; intros. \n         rewrite <- H3, Mmult_1_l; easy. \n       - assert (H' : linearly_dependent (A × B)).\n         { apply lin_dep_mult_r; easy. }\n         apply lin_dep_det_eq_0 in l; \n         apply lin_dep_det_eq_0 in H'; auto with wf_db. \n         destruct l; destruct H'. \n         rewrite H2, H4; lca. \nQed.\n\nTheorem Determinant_multiplicative : forall {n} (A B : Square n), \n  (Determinant A) * (Determinant B) = Determinant (A × B).\nProof. intros. \n       rewrite Det_make_WF, (Det_make_WF _ B), Determinant_multiplicative_WF;\n         auto with wf_db. \n       rewrite <- Det_Mmult_make_WF_l, <- Det_Mmult_make_WF_r; easy. \nQed.\n\n", "meta": {"author": "inQWIRE", "repo": "QuantumLib", "sha": "d97ea40581961d7b53291a4a3dc7885fe7428060", "save_path": "github-repos/coq/inQWIRE-QuantumLib", "path": "github-repos/coq/inQWIRE-QuantumLib/QuantumLib-d97ea40581961d7b53291a4a3dc7885fe7428060/VecSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7021108955979078}}
{"text": "Require Import XR_Rmax.\nRequire Import XR_Rle_dec.\nRequire Import XR_Rnot_le_lt.\n\nLocal Open Scope R_scope.\n\nLemma Rmax_r : forall x y:R, y <= Rmax x y.\nProof.\n  intros x y.\n  unfold Rmax.\n  destruct (Rle_dec x y) as [ hl | hr ].\n  {\n    right.\n    reflexivity.\n  }\n  {\n    left.\n    apply Rnot_le_lt.\n    exact hr.\n  }\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rmax_r.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7021108916444111}}
{"text": "Require Import List.\n(* Funktionen die aus der List Bibliothek importiert und hier verwendet werden sind\n - rev, app und concat. *)\n\n(* Beispiel fuer ein Eingabealphabet: Inductive Sigma := h : Sigma | a : Sigma | l : Sigma | o : Sigma.*)\n\n(** Die Ursprungsidee war auf Listen zu arbeiten. Da die Verfahren aus der Vorlesung\n moeglichst eins zu eins abgebildet werden sollen, ist es notwendig einen induktiven Typen\n [Word] zu definieren, der, anders als bei Listen, die Zeichen am Ende der Zeichenkette anfuegt.\n Da sowohl Listen als auch Woerter fuer die Darstellung benoetigt werden, muessen die Typen\n ineinander ueberfuehrbar sein. *)\n\n(** Definition von Woertern: *)\nInductive Word {A : Type} : Type:=\n  | eps   : @Word A\n  | snoc : @Word A -> A -> @Word A.\n\n(** Anpassung der Notation der Woerter zur Verbesserung der Lesbarkeit. *)\n\nNotation \"[ ]\" := eps.\nNotation \"[ x ; .. ; y ]\" := (snoc ( .. (snoc eps x) .. ) y).\n\n(** Grundoperationen auf dem Typ [Word]: *)\n\n(** Einheit der [Word]-Monade. *)\n\nDefinition unit_w {A : Type} (a : A) : @Word A := snoc eps a.\n\n(** Berechnung der Wortlaenge. *)\n\nFixpoint word_length {A : Type} (w : @Word A) : nat :=\n  match w with\n    | eps          => 0\n    | snoc w' x => S (word_length w')\n  end.\n\n(** Verknuepfung zweier Woerter. *)\n\nFixpoint concat_word {A : Type} (w1 w2 : @Word A) : @Word A :=\n  match w2 with\n    | eps         => w1\n    | snoc w x => snoc (concat_word w1 w) x\n  end.\n\n(** Ein Wort umdrehen. *)\n\nFixpoint word_reverse {A : Type} (w : @Word A) : @Word A  :=\n  match w with\n    | eps           => eps\n    | snoc w' x  => concat_word (snoc eps x) (word_reverse w')\n  end.\n\n(** Map-Funktion auf Woertern ([Word] ist ein Funktor). *)\n\nFixpoint map_word {A B : Type} (f : A -> B) (w : @Word A) : @Word B :=\n  match w with\n    | eps          => eps\n    | snoc w' x => snoc (map_word f w') (f x)\n  end.\n\n(** Die Map-Funktion ist laengenerhaltend. *)\n\nLemma map_length_w {A B : Type} : forall (f : A -> B) (w : @Word A),\n      word_length (map_word f w) = word_length w.\nProof.\n  intros f w.\n  induction w as [ | w' IHw].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw.\n    reflexivity.\nDefined.\n\n(** Definition von Listen: *)\n\n(** In der Standardbibliothek befinden sich bereits Listenoperationen wie [concat] und [rev],\n die analog zu [concat_word] und [word_reverse] arbeiten. Zusaetzlich werden noch weitere\n Eigenschaften benoetigt, die nachfolgend gezeigt werden. *)\n\n(** Eigenschaften von [concat] und [rev] ueber Listen: *)\n\n(** Die leere Liste [nil] ist rechtsneutral bzgl. der Konkatenation. (Per Definition ist [nil] auch\nlinksneutral.) *)\n\nLemma concat_nil {A : Type} (ls : list A) : (ls ++ nil) = ls.\nProof.\n  induction ls.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHls.\n    reflexivity.\nDefined.\n\n(** Die Konkatenation von Listen ist assoziativ.*)\n\nLemma concat_associative {A : Type} (l1 l2 l3 : list A) :\n     (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).\nProof.\n  induction l1.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl1.\n    reflexivity.\nDefined.\n\n(** Das Umdrehen von Listen ist ein Antihomomorphismus bzgl. der Konkatenation. *)\n\nLemma rev_concat {A : Type} (l1 l2 : list A) :\n      rev (l1 ++ l2) = (rev l2) ++ (rev l1).\nProof.\n  induction l1.\n  - assert (rev nil = @nil A).\n    + simpl.\n       reflexivity.\n    + rewrite H.\n       pose (concat_nil (rev l2)).\n       rewrite e.\n       simpl.\n       reflexivity.\n  - simpl.\n    rewrite IHl1.\n    apply concat_associative.\nDefined.\n\n(** Das Umdrehen von Listen ist selbstinvers.*)\n\nLemma rev_involutiv {A : Type} (ls : list A) : rev (rev ls) = ls.\nProof.\n  induction ls.\n  - simpl.\n    reflexivity.\n  - simpl.\n    pose (rev_concat (rev ls) (a :: nil)).\n    rewrite e.\n    rewrite IHls.\n    simpl.\n    reflexivity.\nDefined.\n\n(** Analog zum Typen [list] werden diese Eigenschaften ebenfalls fuer die Operationen auf [Word]\n bewiesen.*)\n\n(** Eigenschaften von [concat_word] und [word_reverse].*)\n\n(** Das leere Wort [eps] ist linksneutral bzgl. der Konkatenation. (Per Definition ist [eps] auch\nrechtsneutral.)*)\n\nLemma concat_word_eps {A : Type} (w : @Word A) : concat_word eps w = w.\nProof.\n  induction w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw.\n    reflexivity.\nDefined.\n\nLemma commute_snoc_concat_w {A} (w w': @Word A) (a : A) :\n      concat_word (snoc w a) w' =\n      concat_word w (concat_word (snoc eps a) w').\nProof.\n  destruct w.\n  - rewrite concat_word_eps.\n    reflexivity.\n  - induction w'.\n    + simpl.\n       reflexivity.\n    + simpl.\n       rewrite IHw'.\n       reflexivity. \nDefined.\n\n(** Die Konkatenation von Woertern ist assoziativ.*)\n\nLemma concat_word_associative {A : Type} (w1 w2 w3 : @Word A) :\n      concat_word (concat_word w1 w2) w3 =\n      concat_word w1 (concat_word w2 w3).\nProof.\n  induction w3.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw3.\n    reflexivity.\nDefined.\n\n(** Das Umdrehen von Woertern ist ein Antihomomorphismus bzgl. der Konkatenation. *)\n\nLemma word_reverse_concat_word {A : Type} (w1 w2 : @Word A) :\n      word_reverse (concat_word w1 w2) =\n      concat_word (word_reverse w2) (word_reverse w1).\nProof.\n  induction w2.\n  - assert (word_reverse eps = @eps A).\n    + simpl.\n       reflexivity.\n    + rewrite H.\n       simpl.\n       pose (concat_word_eps (word_reverse w1)) as con_nil.\n       rewrite con_nil.\n       reflexivity.\n  - simpl.\n    rewrite IHw2.\n    apply eq_sym.\n    apply concat_word_associative.\nDefined.\n\nLemma word_reverse_snoc {A : Type} (w : @Word A) (a : A) :\n      word_reverse (snoc w a) = concat_word [a] (word_reverse w).\nProof.\n  simpl.\n  reflexivity.\nDefined.\n\n(** Das Umdrehen von Woertern ist selbstinvers.*)\n\nLemma word_reverse_involutiv {A : Type} (w : @Word A) :\n      word_reverse (word_reverse w) = w.\nProof.\n  induction w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    pose (word_reverse_concat_word (snoc eps a) (word_reverse w)).\n    rewrite e.\n    rewrite IHw.\n    simpl.\n    reflexivity.\nDefined.\n\n(** [word_reverse] ist injektiv.*)\n\nLemma word_reverse_injective {A : Type} (w1 w2 : @Word A) :\n      word_reverse w1 = word_reverse w2 -> w1 = w2.\nProof.\n  intro revEq.\n  apply (f_equal word_reverse) in revEq.\n  rewrite <- (word_reverse_involutiv w1).\n  rewrite <- (word_reverse_involutiv w2).\n  exact revEq.\nDefined.\n\n(** Somit ist [Word] als Monoid mit [concat_word] als assoziative Konkatenation\n und [eps] als neutrales Element definiert. Bei [list] erhalten wir die gleichen Eigenschaften\n durch [concat] als assoziative Konkatenation und [nil] als neutrales Element bzgl. der\n Konkatenation.\n\n Diese Eigenschaften von Listen und Woertern ermoeglichen weitere Schlussfolgerungen\n bzgl. der Ueberfuehrung von Listen in Woertern und anders herum. *)\n\n(** Eine Liste in ein Wort umwandeln:*)\n\n(** Ein Problem das sich hierbei ergibt, ist dass die Typen von Listen und Woertern auf unterschiedlich\n arbeitenden Konstruktoren aufbauen. Die Liste wird von hinten nach vorn aufgebaut, indem das\n naechste Zeichen vorn angehaengt wird und der Aufbau eines Wortes ist entgegengesetzt. Wenn\n die Umwandlung von einer Liste in ein Wort eins zu eins implementiert wird, entsteht die Funktion, die in\n [list_to_word_simple] beschrieben ist.*)\n\nFixpoint list_to_word_simple {A : Type} (l : list A) : @Word A :=\n  match l with\n    | nil           => eps\n    | cons x l'  => snoc (list_to_word_simple l') x\n  end.\n\n(** Das Ergebnis ist jedoch ein Wort in umgedrehter Reihenfolge. Hierbei handelt \nes sich um einen Antihomomorphismus: Das neutrale Element wird erhalten, das Bild einer Konkatenation\nist die umgekehrte Konkatenation der Bilder der Einzellisten.*)\n\nLemma list_to_word_simple_antihom {A: Type} (l1 l2 : list A) :\n      list_to_word_simple (l1 ++ l2) =\n      concat_word (list_to_word_simple l2) (list_to_word_simple l1).\nProof.\n  induction l1.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl1.\n    reflexivity.\nDefined.\n\n(** Um eine Liste mit Hilfe von [list_to_word_simple] in ein Wort unter Beachtung der Reihenfolge umzuwandeln,\n koennen zwei verschiedene Ansaetze verwendet werden. Die Liste wird zuerst in ein Wort umgewandelt\nund anschliessend wird die Reihenfolge mit [word_reverse] geaendert oder die Liste wird zuerst mit [rev]\numgedreht und anschliessend in ein Wort umgewandelt. Da jeweils zwei Antihomomorphismen hintereinander\nausgefuehrt werden, sind beide entstehenden Funktionen Homomorphismen bzgl. der Konkatenationen.*)\n\nDefinition list_to_word' {A : Type} (l : list A) : @Word A :=\n           word_reverse (list_to_word_simple l).\n\nDefinition list_to_word'' {A : Type} (l : list A) : @Word A :=\n           list_to_word_simple (rev l).\n\n(**  [list_to_word'] und [list_to_word''] basieren auf Funktionen, die durch Pattern Matching definiert sind.\nDurch Auffaltung der Definitionen koennen auch [list_to_word'] und [list_to_word''] ueber Pattern Matching\ndefiniert werden. Es stellt sich heraus, dass in beiden Faellen dieselbe Funktion [list_to_word] entsteht.\nDie Gleichheiten werden in [list_to_word_Lemma] und [list_to_word_Lemma'] gezeigt.*)\n\nFixpoint list_to_word {A : Type} (l : list A) : @Word A :=\n  match l with\n    | nil           => eps\n    | cons x l'  => concat_word (snoc eps x) (list_to_word l')\n  end.\n\n(** [list_to_word_single] auf einelementigen Listen.*)\n\nLemma list_to_word_single {A : Type} (a : A) :\n      list_to_word (cons a nil) = snoc eps a.\nProof.\n  simpl.\n  reflexivity.\nDefined.\n\n(** [list_to_word] ist ein Homomorphismus bzgl. Konkatenationen.*)\n\nLemma list_to_word_hom {A : Type} (l1 l2 : list A) :\n      list_to_word (l1 ++ l2) =\n      concat_word (list_to_word l1) (list_to_word l2).\nProof.\n  induction l1.\n  - simpl.\n    rewrite (concat_word_eps (list_to_word l2)).\n    reflexivity.\n  - simpl.\n    rewrite IHl1.\n    apply eq_sym.\n    apply concat_word_associative.\nDefined.\n\n(** [list_to_word], [list_to_word'] und [list_to_word''] beschreiben dieselbe Funktion.*)\n\nLemma list_to_word_Lemma {A : Type} (l : list A) :\n      list_to_word l = list_to_word' l.\nProof.\n  unfold list_to_word'.\n  induction l.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl.\n    reflexivity.\nDefined.\n\nLemma list_to_word_Lemma' {A : Type} (l : list A) :\n      list_to_word l = list_to_word'' l.\nProof.\n  unfold list_to_word''.\n  induction l.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite list_to_word_simple_antihom.\n    rewrite IHl.\n    reflexivity.\nDefined.\n\nLemma list_to_word'_Lemma {A : Type} (l : list A) :\n      list_to_word' l = list_to_word'' l.\nProof.\n  rewrite <- list_to_word_Lemma.\n  rewrite <- list_to_word_Lemma'.\n  reflexivity.\nDefined.\n\n(** Ein Wort in eine Liste umwandeln: *)\n\n(** Wie auch schon bei der Umwandlung von einer Liste in ein Wort, besteht auch hier das\n Problem mit der Reihenfolge aufgrund der Konstruktoren. Die eins zu eins Implementierung\n der Umwandlung liefert die Funktion [word_to_list_simple].*)\n\nFixpoint word_to_list_simple {A : Type} (w : @Word A) : list A :=\n  match w with\n    | eps           => nil\n    | snoc w' x  => cons x (word_to_list_simple w')\n  end.\n\n(** [word_to_list_simple] ist ein Antihomomorphismus bzgl. der Konkatenation. *)\n\nLemma word_to_list_simple_antihom {A: Type} (w1 w2 : @Word A) :\n      word_to_list_simple (concat_word w1 w2) =\n     (word_to_list_simple w2) ++ (word_to_list_simple w1).\nProof.\n  induction w2.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw2.\n    reflexivity.\nDefined.\n\n(** Wie schon bei [list_to_word] kann bei [word_to_list] die Reihenfolge durch das Umdrehen der Liste nach der\n Umwandlung mit [rev] oder das vorherige Umdrehen gewaehrleistet werden. Dies wird durch die Funktionen\n [word_to_list'] und [word_to_list''] dargestellt.*)\n\nDefinition word_to_list' {A : Type} (w : @Word A) : list A :=\n           rev (word_to_list_simple w).\n\nDefinition word_to_list'' {A : Type} (w : @Word A) : list A :=\n           word_to_list_simple (word_reverse w).\n\n(** Es entsteht durch Auffaltung beider Definitionen dieselbe Funktion [word_to_list],\n siehe [list_to_word].*)\n\nFixpoint word_to_list {A: Type} (w : @Word A) : list A :=\n  match w with\n    | eps           => nil\n    | snoc w' x  => app (word_to_list w') (cons x nil)\n  end.\n\n(** Die Abarbeitung eines Zeichens von [word_to_list].*)\n\nLemma word_to_list_single {A : Type} (a : A) :\n      word_to_list (snoc eps a) = cons a nil.\nProof.\n  simpl.\n  reflexivity.\nDefined.\n\n(** [word_to_list] ist ein Homomorphismus bzgl. der Konkatenation. *)\n\nLemma word_to_list_hom {A : Type} (w1 w2 : @Word A) :\n      word_to_list (concat_word w1 w2) = \n      word_to_list w1 ++ word_to_list w2.\nProof.\n  induction w2.\n  - simpl.\n    rewrite (concat_nil (word_to_list w1)).\n    reflexivity.\n  - simpl.\n    rewrite IHw2.\n    apply concat_associative.\nDefined.\n\n(** [word_to_list], [word_to_list'] und [word_to_list''] beschreiben dieselbe Funktion.*)\n\nLemma word_to_list_Lemma {A : Type} (w : @Word A) :\n      word_to_list w = word_to_list' w.\nProof.\n  unfold word_to_list'.\n  induction w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw.\n    reflexivity.\nDefined.\n\nLemma word_to_list_Lemma' {A : Type} (w : @Word A) :\n      word_to_list w = word_to_list'' w.\nProof.\n  unfold word_to_list''.\n  induction w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite word_to_list_simple_antihom.\n    rewrite IHw.\n    reflexivity.\nDefined.\n\nLemma word_to_list'_Lemma {A : Type} (w : @Word A) :\n      word_to_list' w = word_to_list'' w.\nProof.\n  rewrite <- word_to_list_Lemma.\n  rewrite <- word_to_list_Lemma'.\n  reflexivity.\nDefined.\n\n(** [list_to_word_simple] und [word_to_list_simple] sind zueinander inverse Isomorphismen.*)\n\nLemma list_word_list_simple {A : Type} (l : list A) :\n      word_to_list_simple (list_to_word_simple l) = l.\nProof.\n  induction l.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHl.\n    reflexivity.\nQed.\n\nLemma word_list_word_simple {A : Type} (w : @Word A) :\n      list_to_word_simple (word_to_list_simple w) = w.\nProof.\n  induction w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw.\n    reflexivity.\nQed.\n\n(** [list_to_word] und [word_to_list] sind zueinander inverse Isomorphismen.*)\n\nLemma list_word_list {A : Type} (l : list A) :\n      word_to_list (list_to_word l) = l.\nProof.\n  rewrite list_to_word_Lemma.\n  rewrite word_to_list_Lemma'.\n  unfold list_to_word'.\n  unfold word_to_list''.\n  rewrite word_reverse_involutiv.\n  apply list_word_list_simple.\nDefined.\n\nLemma word_list_word {A : Type} (w : @Word A) :\n      list_to_word (word_to_list w) = w.\nProof.\n  rewrite list_to_word_Lemma.\n  rewrite word_to_list_Lemma'.\n  unfold list_to_word'.\n  unfold word_to_list''.\n  rewrite word_list_word_simple.\n  apply word_reverse_involutiv.\nDefined.\n\n(** Weitere Lemmata zu Word-List und List-Word-Umwandlungen. *)\n\nLemma lw_pres_eq {A} (l : list A) : forall (w : @Word A),\n      l = word_to_list w -> list_to_word l = w.\nProof.\n  intros w eq.\n  rewrite <- word_list_word.\n  rewrite eq.\n  reflexivity.\nDefined.\n\n(** [word_to_list] ist laengenerhaltend. *)\n\nLemma wl_pres_length {A : Type} (w : @Word A) :\n      length (word_to_list w) = word_length w.\nProof.\n  induction w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite app_length.\n    simpl.\n    rewrite <- plus_n_Sm.\n    rewrite <- plus_n_O.\n    rewrite IHw.\n    reflexivity.\nDefined.\n\nLemma lw_concat {A} (l1 l2: list A) (a : A):\n     {w1 : @Word A & {w2 : @Word A &\n      concat_word (list_to_word l1) (list_to_word (a :: l2)) =\n      concat_word (snoc w1 a) w2 } }.\nProof.\n  exists (list_to_word l1).\n  exists (list_to_word l2).\n  simpl.\n  rewrite <- commute_snoc_concat_w.\n  reflexivity.\nDefined.\n\n(* --------------------------------------------------------------------------*)\n\n(** Inits und Tails: *)\n\n(* --------------------------------------------------------------------------*)\n\n(** Typsynonym fuer @Word (@Word X) und @Word (@Word (@Word X)). *)\n\nDefinition Word2 {X : Type} := (@Word (@Word X)).\nDefinition Word3 {X : Type} := (@Word (@Word (@Word X))).\n\n(* unbenutzt, aber ok als Standard ? *)\n\nFixpoint tails_w {X : Type} (w : @Word X) : Word2 :=\n  match w with\n    | eps          => snoc eps eps\n    | snoc xs x => snoc (map_word (fun w => snoc w x) (tails_w xs)) eps\n  end.\n\n(** Verschiedene inits-Varianten: *)\n\nFixpoint inits_l {X : Type} (l : list X) : list (list X) :=\n  match l with\n    | nil       => nil :: nil\n    | x :: xs => nil :: map (cons x) (inits_l xs)\n  end.\n\n(* Die fuer das Pumping_Lemma_Word benutzte Variante *)\n\nFixpoint inits_w {X : Type} (w : @Word X) : Word2 :=\n  match w with\n    | eps          => snoc eps eps\n    | snoc w' x => snoc (inits_w w') w\n end.\n\nDefinition inits_w'{X : Type} (w : @Word X) : @Word (@Word X) :=\n           list_to_word (map (list_to_word) (inits_l (word_to_list w))).\n\nFixpoint inits_w''{X : Type} (w : @Word X) : Word2 :=\n  match w with\n    | eps          => snoc eps eps\n    | snoc w' x =>\n        concat_word (snoc eps eps) \n                    (map_word (fun w'' => concat_word w'' (snoc eps x))\n                              (inits_w w'))\n  end.\n\nDefinition inits_list_w {X : Type} (w : @Word X) : list (@Word X) :=\n           map (list_to_word) (inits_l (word_to_list w)).\n\nFixpoint removelast_w {A} (w : @Word A) :=\n  match w with\n    |eps          => eps\n    |snoc w' _ => w'\n  end.\n\n(* --------------------------------------------------------------------------*)\n\n(** Lemmata zu inits, concat und map: *)\n\n(* --------------------------------------------------------------------------*)\n\nLemma inits_len_l : forall X : Type, forall l : list X,\n      length (inits_l l) = S (length l).\nProof.\n  induction l as [ | x l' IHl].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite map_length.\n    rewrite IHl.\n    reflexivity.\nDefined.\n\nLemma inits_len_w : forall X : Type, forall w : @Word X,\n      word_length (inits_w w) = S (word_length w).\nProof.\n  intros X w.\n  induction w as [ | w' IHw x].\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw.\n    reflexivity.\nDefined.\n\nLemma commute_inits_concat_w {A} (w w': @Word A) :\n      inits_w (concat_word w w') =\n      concat_word (removelast_w (inits_w w))\n     (map_word (concat_word w) (inits_w w')).\nProof.\n  induction w'.\n  - simpl.\n    induction w.\n    + simpl.\n       reflexivity.\n    + simpl (inits_w (snoc w a)).\n       simpl (removelast_w (snoc (inits_w w) (snoc w a))).\n       reflexivity.\n  - simpl.\n    rewrite IHw'.\n    reflexivity.\nDefined.\n\nLemma commute_concat_map_w {A B} (w w': @Word A) (f : A -> B) :\n      map_word f (concat_word w w') =\n      concat_word (map_word f w) (map_word f w').\nProof.\n  induction w'.\n  - simpl.\n    reflexivity.\n  - simpl.\n    rewrite IHw'.\n    reflexivity.\nDefined.\n\nLemma commute_removelast_map_w {A B} (w : @Word A) (f : A -> B) :\n      map_word f (removelast_w w) = removelast_w (map_word f w).\nProof.\n  induction w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nDefined.\n\nLemma inits_last_w {A : Type} (w : @Word A) :\n      inits_w w = snoc (removelast_w (inits_w w)) w.\nProof.\n  destruct w.\n  - simpl.\n    reflexivity.\n  - simpl.\n    reflexivity.\nDefined.\n\nLemma app_length_w {A : Type} : forall (w w' : @Word A),\n      word_length (concat_word w w') = word_length w + word_length w'.\nProof.\n  intros w w'.\n  induction w'.\n  - simpl.\n    rewrite <- plus_n_O.\n   reflexivity.\n  - simpl.\n    rewrite <- plus_n_Sm.\n    rewrite IHw'.\n    reflexivity.\nDefined.\n\nLemma absurd_eps_eq_concat_snoc {A : Type} (w w' : @Word A) (a : A) :\n      eps = concat_word (snoc w a) w' -> False.\nProof.\n  intro eps_eq_waw'.\n  destruct w'.\n  - simpl in eps_eq_waw'.\n    inversion eps_eq_waw'.\n  - simpl in eps_eq_waw'.\n    inversion eps_eq_waw'.\nDefined.\n\nLemma ex_snoc_map {A B : Type} (w : @Word A) (v : @Word B) (b : B) (f : A -> B) :\n      map_word f w = snoc v b ->\n     {w' : @Word A & { a : A &\n     ((w = snoc w' a) * (map_word f w' = v) * (b = f a))%type } }.\nProof.\n  destruct w as [| w' a'].\n  - intro eq.\n    simpl in eq.\n    inversion eq.\n  - intro eq.\n    exists w'.\n    exists a'.\n    simpl in eq.\n    inversion eq.\n    repeat split; reflexivity.\nDefined.", "meta": {"author": "margrit", "repo": "Code", "sha": "b3e89580b33732c23cdf4df8171d6c76ce9186e7", "save_path": "github-repos/coq/margrit-Code", "path": "github-repos/coq/margrit-Code/Code-b3e89580b33732c23cdf4df8171d6c76ce9186e7/Code/Word_Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7020777820307497}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2018 - Pset 6 *)\n\nRequire Import Frap.\n\n(* Authors: \n * Ben Sherman (sherman@csail.mit.edu),\n * Joonwon Choi (joonwonc@csail.mit.edu), \n * Adam Chlipala (adamc@csail.mit.edu)\n *)\n\n(* In this problem set, we will work with the following simple imperative language with\n * a nondeterministic choice operator. Your task is to define both big-step as well as\n * a particular kind of small-step operational semantics for this language\n * (one that is in fact deterministic), and to prove a theorem connecting the two:\n * if the small-step semantics aborts, then the big-step semantics may abort.\n *\n * This is the first problem set so far in this class that is truly open-ended.\n * We want to give you the flexibility to define the operational semantics as\n * you wish, and if you'd like you may even differ from the template shown here\n * if you find it more convenient.\n * Additionally, this is the first problem set where it is *NOT* sufficient to\n * just get the file compiling without any use of [admit] or [Admitted].\n * This will not necessarily guarantee that you have given reasonable semantics\n * for the programming language, and accordingly, will not necessarily\n * guarantee that you will earn full credit. For instance, if you define\n * your small-step semantics as the empty relation (which is incorrect), \n * the theorem you must prove to connect your big-step and small-step \n * semantics will be trivial.\n *)\n\n(** * Syntax *)\n\n(* Basic arithmetic expressions, as we've seen several times in class. *)\nInductive arith : Set :=\n| Const : nat -> arith\n| Var : var -> arith\n| Plus : arith -> arith -> arith\n| Eq : arith -> arith -> arith\n(* should return 1 if the two expressions are equal, and 0 otherwise. *)\n| Lt : arith -> arith -> arith\n(* should return 1 if the two expressions are equal, and 0 otherwise. *)\n.\n\n(* The simple imperative language with a [Choose] syntax for \n * nondeterminism. The intended meaning of the program \n * [Choose c c'] is that either [c] should run or [c'] should run.\n *)\nInductive cmd :=\n| Assign : var -> arith -> cmd\n| Skip : cmd\n| Seq : cmd -> cmd -> cmd\n| Choose : cmd -> cmd -> cmd (* Here's the main novelty: nondeterministic choice *)\n| If : arith -> cmd (* then *) -> cmd (* else *) -> cmd\n| While : arith -> cmd -> cmd\n| Abort : cmd (* This command should immediately terminate the program *)\n.\n\n\n(** Notations *)\n\nDelimit Scope cmd_scope with cmd.\n\nCoercion Const : nat >-> arith.\nCoercion Var : var >-> arith.\nInfix \"+\" := Plus : arith_scope.\nInfix \"==\" := Eq (at level 75) : arith_scope.\nInfix \"<\" := Lt : arith_scope.\nDelimit Scope arith_scope with arith.\nNotation \"x <- e\" := (Assign x e%arith) (at level 75) : cmd_scope.\nInfix \"<|>\" := Choose (at level 78) : cmd_scope.\nInfix \";;\" := Seq (at level 80) : cmd_scope.\n\nNotation \"'if_' c 'then' t 'else' f\" := (If c%arith t f) (at level 75) : cmd_scope.\nNotation \"'while' c 'do' p\" := (While c%arith p) (at level 75) : cmd_scope.\n\n\n(** * Examples *)\n\n(* All nondeterministic realizations of [test_prog1] terminate\n * (either normally or by aborting). [test_prog1 5] may abort,\n * but [test_prog1 6] always terminates normally.\n *)\nDefinition test_prog1 (k : nat) : cmd := (\n  \"target\" <- 8 ;;\n  (\"x\" <- 3 <|> \"x\" <- 4) ;;\n  (\"y\" <- 1 <|> \"y\" <- k) ;;\n  if_ \"x\" + \"y\" == \"target\"\n     then Abort\n     else Skip\n  )%cmd.\n\n(* No matter the value of [num_iters], [test_prog2 num_iters]\n * always may potentially fail to terminate, and always\n * may potentially abort.\n *)\nDefinition test_prog2 (num_iters : nat) : cmd := (\n   \"acc\" <- 0 ;;\n   \"n\" <- 0;;\n   while (\"n\" < 1) do (\n     (Skip <|> \"n\" <- 1) ;;\n     \"acc\" <- \"acc\" + 1\n   ) ;;\n   if_ \"acc\" == S num_iters\n     then Abort\n     else Skip\n  )%cmd.\n\n\n(* We've seen the expression language in class a few times,\n * so here we'll just give you the interpreter for that\n * expression language.\n *)\nDefinition valuation := fmap var nat.\n\nFixpoint interp (e : arith) (v : valuation) : nat :=\n  match e with\n  | Const n => n\n  | Var x =>\n    match v $? x with\n    | None => 0\n    | Some n => n\n    end\n  | Plus e1 e2 => interp e1 v + interp e2 v\n  | Eq e1 e2 => if interp e1 v ==n interp e2 v then 1 else 0\n  | Lt e1 e2 => if lt_dec (interp e1 v) (interp e2 v) then 1 else 0\n  end.\n\n(** ** Part 1: Big-step operational semantics *)\n\n(* You should define some result type (say, [result]) for values that commands\n   in the language run to, and define a big-step operational semantics\n   [eval : valuation -> cmd -> result -> Prop]\n   that says when a program *may* run to some result in *some* nondeterministic\n   realization of the program. Then you should also define a predicate\n   [big_aborted : result -> Prop]\n   that describes which results indicate that the program aborted.\n\n * Looking at the examples, we should have\n   [exists res, eval $0 (test_prog1 5) res /\\ big_aborted res]\n   but\n   [forall res, eval $0 (test_prog1 6) res -> big_aborted res -> False] \n * . You are not required to prove these facts, but it could be a good\n     sanity check!\n *)\n\nDefinition result : Type.\nAdmitted.\n\nDefinition eval : valuation -> cmd -> result -> Prop.\nAdmitted.\n\nDefinition big_aborted : result -> Prop.\nAdmitted.\n\n(* As an optional sanity check, you may attempt to\n * prove that your big-step semantics behaves appropriately\n * for an example program:\n \nExample test_prog1_reachable :\n  exists res, eval $0 (test_prog1 5) res /\\ big_aborted res.\nProof.\nAdmitted.\n\nExample test_prog1_unreachable :\n  forall res, eval $0 (test_prog1 6) res -> big_aborted res -> False.\nProof.\nAdmitted.\n*)\n\n\n  (** ** Part 2: Small-step deterministic operational semantics *)\n\n(* Next, you should define a small-step operational semantics for this\n   language that in some sense tries to run *all* possible nondeterministic\n   realizations and aborts if any possible realization aborts.\n   Define a type [state] that represents the underlying state that the\n   small-step semantics should take steps on, and then define a small-step\n   semantics\n   [step : state -> state -> Prop]\n   .\n\n   Here's the twist: we ask that you define an operational semantics that \n   is *deterministic*, in the sense of the following formal statement:\n   [forall s1 s2 s2', step s1 s2 -> step s1 s2' -> s2 = s2'].\n\n   The operational model that we have in mind in this: when we encounter\n   a nondeterministic choice, we execute the left branch. If the left\n   branch terminates without aborting, we backtrack and try the\n   other nondeterministic choice.\n\n   Note that if any possible realization does not terminate,\n   we allow the deterministic small-step semantics to diverge as well.\n   (It is actually possible to define a semantics that always \"finds\" aborts,\n   even if some branches of nondeterminism diverge!  However, the proof of that\n   variant would likely be significantly more complicated, and we haven't tried\n   it ourselves.)\n\n   Define a function\n   [init : valuation -> cmd -> state]\n   that builds starting states for the small-step semantics,\n   a predicate\n   [small_aborted : state -> Prop]\n   that describes which states are considered aborted, and\n   a predicate\n   [small_terminated : state -> Prop]\n   that describes states that have run to completion without any\n   nondeterministic branch aborting.\n\n * Looking at the examples, we should have\n   [exists st, step^* (init $0 (test_prog1 5)) st /\\ small_aborted st]\n   but\n   [forall st, step^* (init $0 (test_prog1 6)) st -> small_aborted st -> False]\n   . You are not required to prove these facts, but it could be\n   a good sanity check!\n *)\n\nDefinition state : Type.\nAdmitted.\n\nDefinition step : state -> state -> Prop.\nAdmitted.\n\nDefinition init : valuation -> cmd -> state.\nAdmitted.\n\nDefinition small_aborted : state -> Prop.\nAdmitted.\n\nDefinition small_terminated : state -> Prop.\nAdmitted.\n\n\n(* As an optional sanity check, you may attempt to\n * prove that your small-step semantics behaves appropriately\n * for an example program:\n\nExample test_prog1_reachable_small :\n  exists st, step^* (init $0 (test_prog1 5)) st /\\ small_aborted st.\nProof.\nAdmitted.\n\nExample test_prog1_unreachable_small :\n  forall st, step^* (init $0 (test_prog1 6)) st -> small_aborted st -> False.\nProof.\nAdmitted.\n*)\n\n(** ** Part 3: Connection between big- and small-step semantics *)\n\n(* Prove the following theorem demonstrating the connection between the big-step\n * and small-step semantics:\n *\n * If the small-step semantics aborts, then the big-step semantics may\n * potentially abort.\n *)\n\nTheorem small_abort_big_may_abort : forall v c s,\n         step^* (init v c) s\n      -> small_aborted s\n      -> exists res, eval v c res /\\ big_aborted res.\nProof.\nAdmitted.\n\n\n\n(* As an additional challenge, you  you may want to prove the following\n * theorem. Note that this is *NOT* required for this assignment and\n * will not affect your grade.\n *\n * If the small-step semantics terminates without aborting, then the\n * big-step semantics may *not* abort.\n\nTheorem small_terminates_big_may_not_abort :\n       forall v c s,\n         step^* (init v c) s\n      -> small_terminated s\n      -> forall res, \n             eval v c res \n          -> big_aborted res\n          -> False.\nProof.\nAdmitted.\n*)\n", "meta": {"author": "mit-frap", "repo": "spring18", "sha": "f0f8b35613938e61e2c46f1c70f2fc6a9e04659f", "save_path": "github-repos/coq/mit-frap-spring18", "path": "github-repos/coq/mit-frap-spring18/spring18-f0f8b35613938e61e2c46f1c70f2fc6a9e04659f/pset6/Pset6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7020704409032095}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import List Arith Omega Wellfounded Permutation.\nRequire Import list_utils wf_utils bt zip sorted increase bft.\n\nSet Implicit Arguments.\n\nSection bt_branches.\n\n  Variable X : Type.\n\n  Implicit Types (l : list bool) (ll: list(list bool)) (t : bt X).\n\n  (* Depth first traversal, VERY standard algo *)\n\n  Fixpoint dft_std t : list X :=\n    match t with \n      | leaf x => x::nil\n      | node u x v => x::dft_std u++dft_std v\n    end.\n\n  Fact dft_std_length t : length (dft_std t) = m_bt t.\n  Proof. induction t; simpl; repeat rewrite app_length; omega. Qed.\n\n  (* The tree branches by Depth First Traversal *)\n\n  Fixpoint dft_br t : list (list bool) :=\n    nil::match t with \n           | leaf _     => nil\n           | node u _ v => map (cons false) (dft_br u) ++ map (cons true) (dft_br v)\n         end.\n\n  (* dft_br corresponds to dft_std *)\n\n  Theorem dft_br_std t : Forall2 (bt_path_node t) (dft_br t) (dft_std t).\n  Proof.\n    induction t as [ | ? Hu ? ? Hv ]; simpl; repeat constructor.\n    apply Forall2_app; apply Forall2_map_left; [ revert Hu | revert Hv ];\n      apply Forall2_mono; constructor; auto.\n  Qed.\n\n  (* number of branches equals size of tree *)\n\n  Fact dft_br_length t : length (dft_br t) = m_bt t.\n  Proof. rewrite (Forall2_length (dft_br_std t)), dft_std_length; trivial. Qed.\n\n  (* dft_br lists the branches of t *)\n\n  Fact dft_br_spec l t : In l (dft_br t) <-> btb t l.\n  Proof.\n    split.\n    + intros Hl; rewrite btb_spec.\n      destruct Forall2_In_inv_left with (1 := dft_br_std t) (2 := Hl) as (x & ? & ?).\n      exists x; auto.\n    + induction 1 as [ [] | | ]; simpl; auto; right; apply in_or_app;\n        [ left | right ]; apply in_map; auto.\n   Qed.\n\n  Corollary dft_br_spec_1 t : Forall (btb t) (dft_br t).\n  Proof. rewrite Forall_forall; intro; apply dft_br_spec. Qed.\n\n  (* the branches of t in dft_br t are sorted according to lb_lex *)\n\n  Fact dft_br_sorted t : sorted lb_lex (dft_br t).\n  Proof.\n    induction t; simpl.\n    + do 2 constructor.\n    + constructor.\n      * apply Forall_app; rewrite Forall_forall; intro; \n          rewrite in_map_iff; intros (? & ? & ?); subst; constructor.\n      * apply sorted_app.\n        - intros ? ?; do 2 rewrite in_map_iff.\n          intros (? & ? & ?) (? & ? & ?); subst; constructor.\n        - apply sorted_map; auto; constructor; auto.\n        - apply sorted_map; auto; constructor; auto.\n  Qed.\n\n  (* Now niveaux and then Breadth first traversal *)\n\n  Fixpoint niveaux_br (t : bt X) : list (list (list bool)) :=\n    match t with \n      | leaf _     => (nil::nil) :: nil\n      | node a _ b => (nil::nil) :: zip (@app _) (map (map (cons false)) (niveaux_br a))\n                                                 (map (map (cons true))  (niveaux_br b))\n    end.\n\n  Lemma niveaux_br_niveaux t : Forall2 (Forall2 (bt_path_node t)) (niveaux_br t) (niveaux t).\n  Proof.\n    induction t as [ | ? Hu ? ? Hv ]; simpl; repeat constructor.\n    apply Forall2_zip_app; apply Forall2_map_left;\n      [ revert Hu | revert Hv ]; apply Forall2_mono;\n      intros ? ? G; apply Forall2_map_left; revert G;\n      apply Forall2_mono; constructor; auto.\n  Qed.\n\n  Lemma niveaux_br_spec_0 l t : btb t l -> In l (concat (niveaux_br t)).\n  Proof.\n    induction 1 as [ t | | ].\n    + apply in_concat_iff; exists (nil::nil); destruct t; simpl; auto.\n    + simpl; right; apply In_concat_zip_app_left; rewrite <- map_concat; apply in_map; assumption.\n    + simpl; right; apply In_concat_zip_app_right; rewrite <- map_concat; apply in_map; assumption.\n  Qed. \n\n  Corollary niveaux_br_spec_1 t : forall l ll, In l ll -> In ll (niveaux_br t) -> btb t l.\n  Proof.\n    intros l ll H1 H2.\n    destruct Forall2_In_inv_left with (1 := niveaux_br_niveaux t) (2 := H2) as (? & ? & H3).\n    destruct Forall2_In_inv_left with (1 := H3) (2 := H1) as (? & ? & ?).\n    apply btb_spec; firstorder.\n  Qed.\n  \n  Fact niveaux_br_increase t : increase (fun n ll => Forall (fun l => length l = n) ll) 0 (niveaux_br t).\n  Proof.\n    induction t as [ | u Hu x v Hv ]; simpl.\n    + do 2 constructor; auto.\n    + constructor.\n      * constructor; auto.\n      * apply zip_increase.\n        1: intros; apply Forall_app; auto.\n        1,2 : apply map_increase; try assumption; \n            intros ? ? G; apply Forall_map; simpl;\n            revert G; apply Forall_impl; intros; omega.\n  Qed.\n\n  Fact niveaux_br_sorted t : Forall (sorted lb_lex) (niveaux_br t).\n  Proof.\n    induction t as [ x | u Hu x v Hv ]; simpl.\n    + repeat constructor.\n    + constructor.\n      * repeat constructor.\n      * apply zip_monotone.\n        - apply Forall_map; revert Hu; apply Forall_impl.\n          intros; apply sorted_map; auto.\n          intros; constructor; auto.\n        - apply Forall_map; revert Hv; apply Forall_impl.\n          intros; apply sorted_map; auto.\n          intros; constructor; auto.\n        - rewrite Forall_forall in Hu, Hv.\n          intros ? ?; do 2 rewrite in_map_iff;\n            intros (? & ? & ?) (? & ? & ?); subst.\n          apply sorted_app.\n          ++ intros ? ?; do 2 rewrite in_map_iff;\n             intros (? & ? & ?) (? & ? & ?); subst; constructor.\n          ++ apply sorted_map; auto; intros; constructor; auto.\n          ++ apply sorted_map; auto; intros; constructor; auto.\n  Qed.\n\n  Definition bft_br t : list (list bool) := concat (niveaux_br t).\n\n  (* bft_br corresponds to bft_std *)\n\n  Theorem bft_br_std t : Forall2 (bt_path_node t) (bft_br t) (bft_std t).\n  Proof. apply Forall2_concat, niveaux_br_niveaux. Qed.\n\n  (* bft_br contains the branches of t *)\n\n  Fact bft_br_spec l t : In l (bft_br t) <-> btb t l.\n  Proof.\n    unfold bft_br; split.\n    + rewrite in_concat_iff; intros (? & H1 & H2); revert H1 H2; apply niveaux_br_spec_1.\n    + apply niveaux_br_spec_0.\n  Qed.\n\n  Hint Resolve niveaux_br_increase niveaux_br_sorted.\n\n  (* The list of branches generated by bft_br is sorted according to bft_order *)\n\n  Theorem bft_br_sorted t : sorted bft_order (bft_br t).\n  Proof.\n    apply concat_sorted with (P := fun n ll => Forall (fun l => length l = n) ll) (n := 0); auto.\n    + intros i j x l y m; do 2 rewrite Forall_forall; intros H1 H2 H3 H4 H5.\n      apply H2 in H4; apply H3 in H5; left; omega.\n    + generalize (niveaux_br_sorted t).\n      do 2 rewrite Forall_forall.\n      intros H l Hl; generalize (H _ Hl).\n      apply sorted_mono.\n      intros x y H1 H2 H3; right; split; auto.\n      generalize (niveaux_br_increase t); intros H4.\n      apply increase_inv with (2 := Hl) in H4.\n      destruct H4 as (k & _ & H4).\n      rewrite Forall_forall in H4.\n      repeat rewrite H4; auto.\n  Qed.\n\n  Hint Resolve dft_br_sorted bft_br_sorted lb_lex_irrefl bft_order_irrefl.\n\n  (* dft_br and bft_br compute the same list of branches ... up to permutation *)\n\n  Theorem bft_br_dft_br t : dft_br t ~p bft_br t.\n  Proof.\n    apply sorted_perm with (R := lb_lex) (S := bft_order); auto.\n    intro; rewrite dft_br_spec, bft_br_spec; tauto.\n  Qed.\n\n  Corollary bft_br_length t : length (bft_br t) = m_bt t.\n  Proof. rewrite <- (Permutation_length (bft_br_dft_br t)); apply dft_br_length. Qed. \n\n  Corollary bft_std_length t : length (bft_std t) = m_bt t.\n  Proof.\n    generalize (bft_br_std t); intros H.\n    apply Forall2_length in H.\n    rewrite <- H, bft_br_length; trivial.\n  Qed.\n\nEnd bt_branches.\n\nCheck dft_br_spec.\nCheck dft_br_length.\nCheck dft_br_sorted.\nCheck dft_br_std.\n\nCheck bft_br_spec.\nCheck bft_br_length.\nCheck bft_br_sorted.\nCheck bft_br_std.\n\nCheck bft_br_dft_br.", "meta": {"author": "DmxLarchey", "repo": "Breadth-First-Numbering", "sha": "7f0fa3561968bef7f927d6bae4b1da6a67236762", "save_path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering", "path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering/Breadth-First-Numbering-7f0fa3561968bef7f927d6bae4b1da6a67236762/bft_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7020704288555909}}
{"text": "(* ** Abstract Reduction Systems *)\n(* from Semantics Lecture at Programming Systems Lab, https://www.ps.uni-saarland.de/courses/sem-ws13/ *)\n\nRequire Export Undecidability.Shared.Libs.PSL.Base Lia Arith.\n\nModule ARSNotations.\n  Notation \"p '<=1' q\" := (forall x, p x -> q x) (at level 70).\n  Notation \"p '=1' q\" := (forall x, p x <-> q x) (at level 70).\n  Notation \"R '<=2' S\" := (forall x y, R x y -> S x y) (at level 70).\n  Notation \"R '=2' S\"  := (forall x y, R x y <-> S x y) (at level 70).\nEnd ARSNotations.\n\nImport ARSNotations.\n\n(* Relational composition *)\n\nDefinition rcomp X Y Z (R : X -> Y -> Prop) (S : Y -> Z -> Prop) \n: X -> Z -> Prop :=\n  fun x z => exists y, R x y /\\ S y z.\n\n(* Power predicates *)\n\nRequire Import Arith.\nDefinition pow X R n : X -> X -> Prop := it (rcomp R) n eq.\n\nDefinition functional {X Y} (R: X -> Y -> Prop) := forall x y1 y2, R x y1 -> R x y2 -> y1 = y2.\nDefinition terminal {X Y} (R: X -> Y -> Prop) x:= forall y, ~ R x y.\n\nSection FixX.\n  Variable X : Type.\n  Implicit Types R S : X -> X -> Prop.\n  Implicit Types x y z : X.\n\n  Definition reflexive R := forall x, R x x.\n  Definition symmetric R := forall x y, R x y -> R y x.\n  Definition transitive R := forall x y z, R x y -> R y z -> R x z.\n\n\n\n  (* Reflexive transitive closure *)\n\n  Inductive star R : X -> X -> Prop :=\n  | starR x : star R x x\n  | starC x y z : R x y -> star R y z -> star R x z.\n\n  Definition evaluates R x y := star R x y /\\ terminal R y.\n\n  (* Making first argument a non-uniform parameter doesn't simplify the induction principle. *)\n\n  Lemma star_simpl_ind R (p : X -> Prop) y :\n    p y ->\n    (forall x x', R x x' -> star R x' y -> p x' -> p x) -> \n    forall x, star R x y -> p x.\n  Proof.\n    intros A B. induction 1; eauto.\n  Qed.\n\n  Lemma star_trans R:\n    transitive (star R).\n  Proof.\n    induction 1; eauto using star.\n  Qed.\n\n  Lemma R_star R: R <=2 star R.\n  Proof.\n    eauto using star.\n  Qed.\n\n  Instance star_PO R: PreOrder (star R).\n  Proof.\n    constructor;repeat intro;try eapply star_trans;  now eauto using star.\n  Qed.\n  \n  (* Power characterization *)\n\n  Lemma star_pow R x y :\n    star R x y <-> exists n, pow R n x y.\n  Proof.\n    split; intros A.\n    - induction A as [|x x' y B _ [n IH]].\n      + exists 0. reflexivity.\n               + exists (S n), x'. auto.\n               - destruct A as [n A].\n                 revert x A. induction n; intros x A.\n                 + destruct A. constructor.\n                 + destruct A as [x' [A B]]. econstructor; eauto.\n  Qed.\n\n  Lemma pow_star R x y n:\n    pow R n x y -> star R x y.\n  Proof.\n    intros A. erewrite star_pow. eauto.\n  Qed.\n\n  (* Equivalence closure *)\n\n  Inductive ecl R : X -> X -> Prop :=\n  | eclR x : ecl R x x\n  | eclC x y z : R x y -> ecl R y z -> ecl R x z\n  | eclS x y z : R y x -> ecl R y z -> ecl R x z.\n\n  Lemma ecl_trans R :\n    transitive (ecl R).\n  Proof.\n    induction 1; eauto using ecl.\n  Qed.\n\n  Lemma ecl_sym R :\n    symmetric (ecl R).\n  Proof.\n    induction 1; eauto using ecl, (@ecl_trans R).\n  Qed.\n\n  Lemma star_ecl R :\n    star R <=2 ecl R.\n  Proof.\n    induction 1; eauto using ecl.\n  Qed.\n\n  (* Diamond, confluence, Church-Rosser *)\n\n  Definition joinable R x y :=\n    exists z, R x z /\\ R y z.\n\n  Definition diamond R :=\n    forall x y z, R x y -> R x z -> joinable R y z.\n\n  Definition confluent R := diamond (star R).\n\n  Definition semi_confluent R :=\n    forall x y z, R x y -> star R x z -> joinable (star R) y z.\n\n  Definition church_rosser R :=\n    ecl R <=2 joinable (star R).\n\n  Goal forall R, diamond R -> semi_confluent R.\n  Proof.\n    intros R A x y z B C.\n    revert x C y B.\n    refine (star_simpl_ind _ _).\n    - intros y C. exists y. eauto using star.\n    - intros x x' C D IH y E.\n      destruct (A _ _ _ C E) as [v [F G]].\n      destruct (IH _ F) as [u [H I]].\n      assert (J:= starC G H).\n      exists u. eauto using star.\n  Qed.\n\n  Lemma diamond_to_semi_confluent R :\n    diamond R -> semi_confluent R.\n  Proof.\n    intros A x y z B C. revert y B.\n    induction C as [|x x' z D _ IH]; intros y B.\n    - exists y. eauto using star.\n             - destruct (A _ _ _ B D) as [v [E F]].\n               destruct (IH _ F) as [u [G H]].\n               exists u. eauto using star.\n  Qed.\n\n  Lemma semi_confluent_confluent R :\n    semi_confluent R <-> confluent R.\n  Proof.\n    split; intros A x y z B C.\n    - revert y B.\n      induction C as [|x x' z D _ IH]; intros y B.\n      + exists y. eauto using star.\n               + destruct (A _ _ _ D B) as [v [E F]].\n                 destruct (IH _ E) as [u [G H]].\n                 exists u. eauto using (@star_trans R).\n               - apply (A x y z); eauto using star.\n  Qed.\n\n  Lemma diamond_to_confluent R :\n    diamond R -> confluent R.\n  Proof.\n    intros A. apply semi_confluent_confluent, diamond_to_semi_confluent, A.\n  Qed.\n\n  Lemma confluent_CR R :\n    church_rosser R <-> confluent R.\n  Proof.\n    split; intros A.\n    - intros x y z B C. apply A.\n      eauto using (@ecl_trans R), star_ecl, (@ecl_sym R).\n    - intros x y B. apply semi_confluent_confluent in A.\n      induction B as [x|x x' y C B IH|x x' y C B IH].\n      + exists x. eauto using star.\n               + destruct IH as [z [D E]]. exists z. eauto using star.\n               + destruct IH as [u [D E]].\n                 destruct (A _ _ _ C D) as [z [F G]].\n                 exists z. eauto using (@star_trans R).\n  Qed.\n\n\n  (* End Semantics Library *)\n\n\n  (* Uniform confluence and parametrized confluence *)\n\n  Definition uniform_confluent (R : X -> X -> Prop ) := forall s t1 t2, R s t1 -> R s t2 -> t1 = t2 \\/ exists u, R t1 u /\\ R t2 u.\n\n  Lemma functional_uc R :\n    functional R -> uniform_confluent R.\n  Proof.\n    intros F ? ? ? H1 H2. left. eapply F. all:eauto.\n  Qed.\n\n  Lemma pow_add R n m (s t : X) : pow R (n + m) s t <-> rcomp (pow R n) (pow R m) s t.\n  Proof.\n    revert m s t; induction n; intros m s t.\n    - simpl. split; intros. econstructor. split. unfold pow. simpl. reflexivity. eassumption.\n      destruct H as [u [H1 H2]]. unfold pow in H1. simpl in *. subst s. eassumption.\n    - simpl in *; split; intros.\n      + destruct H as [u [H1 H2]].\n        change (it (rcomp R) (n + m) eq) with (pow R (n+m)) in H2.\n        rewrite IHn in H2.\n        destruct H2 as [u' [A B]]. unfold pow in A.\n        econstructor. \n        split. econstructor. repeat split; repeat eassumption. eassumption.\n      + destruct H as [u [H1 H2]].\n        destruct H1 as [u' [A B]].\n        econstructor.  split. eassumption. change (it (rcomp R) (n + m) eq) with (pow R (n + m)).\n        rewrite IHn. econstructor. split; eassumption.\n  Qed.\n\n  Lemma rcomp_eq (R S R' S' : X -> X -> Prop) (s t : X) : (R =2 R') -> (S =2 S') -> (rcomp R S s t <-> rcomp R' S' s t).\n  Proof.\n    intros A B.\n    split; intros H; destruct H as [u [H1 H2]];\n    eapply A in H1; eapply B in H2;\n    econstructor; split; eassumption.\n  Qed.\n  \n  Lemma eq_ref : forall (R : X -> X -> Prop), R =2 R.\n  Proof.\n    split; tauto.\n  Qed.\n  \n  Lemma rcomp_1 (R : X -> X -> Prop): R =2 pow R 1.\n  Proof.\n    intros s t; split;unfold pow in *; simpl in *; intros H.\n    - econstructor. split; eauto.\n    - destruct H as [u [H1 H2]]; subst u; eassumption.\n  Qed.\n   \n  Lemma parametrized_semi_confluence (R : X -> X -> Prop) (m : nat) (s t1 t2 : X) :\n    uniform_confluent R ->\n    pow R m s t1 ->\n    R s t2 ->\n    exists k l u,\n      k <= 1 /\\ l <= m /\\ pow R k t1 u /\\ pow R l t2 u /\\ m + k = S l.\n  Proof.\n    intros unifConfR; revert s t1 t2; induction m; intros s t1 t2 s_to_t1 s_to_t2.\n    - unfold pow in s_to_t1. simpl in *. subst s.\n      exists 1, 0, t2.\n      repeat split; try lia.\n      econstructor. split; try eassumption; econstructor.\n    - destruct s_to_t1 as [v [s_to_v v_to_t1]].\n      destruct (unifConfR _ _ _ s_to_v s_to_t2) as [H | [u [v_to_u t2_to_u]]].\n      + subst v. eexists 0, m, t1; repeat split; try lia; eassumption.\n      + destruct (IHm _ _ _ v_to_t1 v_to_u) as [k [l [u' H]]].\n        eexists k, (S l), u'; repeat split; try lia; try tauto.\n        econstructor. split. eassumption. tauto.\n  Qed.\n  \n  Lemma rcomp_comm R m (s t : X) : rcomp R (it (rcomp R) m eq) s t <-> rcomp (it (rcomp R) m eq) R s t.\n  Proof.\n    split; intros H;\n    [rewrite (rcomp_eq s t (rcomp_1 R) (eq_ref _)) in H;\n      rewrite (rcomp_eq s t (eq_ref _) (rcomp_1 R)) |\n     rewrite (rcomp_eq s t (eq_ref _) (rcomp_1 R)) in H;\n       rewrite (rcomp_eq s t (rcomp_1 R) (eq_ref _))];\n    change ((it (rcomp R) m eq)) with (pow R m) in *;\n    try rewrite <- pow_add in *;\n    rewrite Nat.add_comm; eassumption.\n  Qed.\n  \n  Lemma parametrized_confluence (R : X -> X -> Prop) (m n : nat) (s t1 t2 : X) : \n    uniform_confluent R ->\n    pow R m s t1 -> \n    pow R n s t2 -> \n    exists k l u,\n      k <= n /\\ l <= m /\\ pow R k t1 u /\\ pow R l t2 u /\\ m + k = n + l.\n  Proof.\n    revert n s t1 t2; induction m; intros n s t1 t2 unifConR s_to_t1 s_to_t2.\n    - unfold pow in s_to_t1. simpl in s_to_t1. subst s.\n      exists n, 0, t2. repeat split; try now lia. eassumption.\n    - unfold pow in s_to_t1. simpl in *.\n      destruct s_to_t1 as [v [s_to_v v_to_t1]].\n      destruct (parametrized_semi_confluence unifConR s_to_t2 s_to_v) as\n          [k [l [u [k_lt_1 [l_lt_n [t2_to_u [v_to_u H]]]]]]].\n      destruct (IHm _ _ _ _ unifConR v_to_t1 v_to_u) as\n          [l'[k'[u'[l'_lt_l [k'_lt_m [t1_to_u' [u_to_u' H2]]]]]]].\n      exists l', (k + k'), u'.\n      repeat split; try lia. eassumption.\n      rewrite pow_add.\n      econstructor; split; eassumption.\n  Qed.\n\n  Lemma uniform_confluent_noloop R x y:\n    uniform_confluent R ->\n    star R x y -> (forall y', ~ R y y') ->\n    ~exists z k, star R x z /\\ pow R (S k) z z.\n  Proof.\n    intros UC (k0&R0)%star_pow Term (z&k1&R1&RL).\n    induction R1 in k0,RL,R0|-*.\n    -edestruct parametrized_confluence with (m:=k0) (n:=S k1 + k0) as (i0&i1&?&?&?&?&?&?).\n     1,2:eassumption.\n     now eapply pow_add;eexists;split;eassumption.\n     destruct i0. destruct i1.\n     +now lia.\n     +destruct H2 as (?&?&_). edestruct Term. eauto.\n     +destruct H1 as (?&?&_). edestruct Term. eauto.\n    -edestruct parametrized_semi_confluence with (R:=R) (2:= R0) as (i0&?&?&?&?&?&?&?). 1,2:eassumption.\n     destruct i0. 2:{ destruct H2 as (?&?&_). edestruct Term. eauto. }\n     cbn in H2;inv H2.\n     eapply IHR1. all:eauto.\n  Qed.\n  \n Lemma uc_terminal R x y z n:\n    uniform_confluent R ->\n    R x y ->\n    pow R n x z ->\n    terminal R z ->\n    exists n' , n = S n' /\\ pow R n' y z.\n  Proof.\n    intros ? ? ? ter. edestruct parametrized_semi_confluence as (k&?&?&?&?&R'&?&?). 1-3:now eauto.\n    destruct k as [|].\n    -inv R'. rewrite <- plus_n_O in *. eauto.\n    -edestruct R' as (?&?&?). edestruct ter. eauto.\n  Qed.  \n\nEnd FixX.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/L/Prelim/ARS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7020704239010778}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\nRequire Import List. Import ListNotations.\nRequire Import QArith.\nRequire Import Coq.micromega.Lqa.\n\nRequire Import GrappaCoq.Domain.\n\n\n(** A Poset instance for Coq rationals. *)\nSection rationalPoset.\n  Instance rationalOrder : PosetOrder := Qle.\n  Program Instance rationalPoset : Poset rationalOrder.\n  Next Obligation. unfold le, rationalOrder; lra. Qed.\n  Next Obligation. unfold equiv, le, rationalOrder in *; lra. Qed.\nEnd rationalPoset.\n\n\nSection rationalLemmas.\n  Existing Instance rationalOrder.\n  Existing Instance rationalPoset.\n\n  Lemma Qdiv_mult_shift :\n    forall x y z, ~ y == 0 -> x / y * z == x * z / y.\n  Proof. intros x y z Hy; field; auto. Qed.\n\n  Lemma Qdiv_2_not_equiv x :\n    0 < x ->\n    ~ x / (2 # 1) ~~ x.\n  Proof.\n    intros H0 [H1 H2]; unfold le, rationalOrder in *.\n    assert (H4: x * (2#1) == x / (2#1) * (2#1)).\n    { apply Qmult_inj_r; lra. }\n    rewrite Qdiv_mult_shift in H4; try lra.\n    rewrite Qdiv_mult_l in H4; lra.\n  Qed.\n\n  Lemma Qplus_Qdiv_2_not_equiv x y :\n    0 < x ->\n    ~ y == 0 ->\n    ~ y == x ->\n    ~ (x + y) / (2 # 1) ~~ x.\n  Proof.\n    intros H0 H1 H2 [H3 H4]; unfold le, rationalOrder in *.\n    assert (H6: x * (2#1) == (x + y) / (2#1) * (2#1)).\n    { apply Qmult_inj_r; lra. }\n    rewrite Qdiv_mult_shift in H6; try lra.\n    rewrite Qdiv_mult_l in H6; lra.\n  Qed.\n\n  Lemma Qdiv_2_le x :\n    0 < x ->\n    x / (2 # 1) <= x.\n  Proof. intros H0; apply Qle_shift_div_r; lra. Qed.\nEnd rationalLemmas.\n", "meta": {"author": "GaloisInc", "repo": "grappa-coq", "sha": "c0f56afcf88f2741127a358cd8263028dca76c35", "save_path": "github-repos/coq/GaloisInc-grappa-coq", "path": "github-repos/coq/GaloisInc-grappa-coq/grappa-coq-c0f56afcf88f2741127a358cd8263028dca76c35/theories/Rational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7020359295498142}}
{"text": "Require Import Arith.\nDefinition f x := x + 100.\n\nCompute f 10.\n\nDefinition g x := x - 100.\n\nCompute g 110.\n\nTheorem g_f : forall x, g (f x) = x.\nProof.\n  intros x. unfold f, g.\n  rewrite Nat.add_sub. reflexivity.\nQed.\n", "meta": {"author": "cedretaber", "repo": "software_foundations_exercises", "sha": "3b7c9803a32ae0b9e555665e56b9b52c93a8db09", "save_path": "github-repos/coq/cedretaber-software_foundations_exercises", "path": "github-repos/coq/cedretaber-software_foundations_exercises/software_foundations_exercises-3b7c9803a32ae0b9e555665e56b9b52c93a8db09/exer1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7020089802839573}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus Zero (plus lf2 z).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj255_coqofml_T1U8yU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7020089767737325}}
{"text": "(* Exercise 30 *) \n\nRequire Import BenB.\n\nVariables A B C D : Prop.\n\n\nTheorem exercise_030 : (~A /\\ ~B) -> ~((A -> B) -> B).\nProof.\nimp_i Sigma.\nneg_i B first.\ncon_e2 (~A).\nhyp Sigma.\nneg_e (A).\ncon_e1 (~B).\nhyp Sigma.\nneg_e' B second.\ncon_e2 (~A).\nhyp Sigma.\nimp_e (A -> B).\nhyp first.\nimp_i third.\nneg_e A.\nhyp second.\nhyp third.\nQed.", "meta": {"author": "KiOui", "repo": "total5", "sha": "b47117bc43a775b525813af56d54350394c22356", "save_path": "github-repos/coq/KiOui-total5", "path": "github-repos/coq/KiOui-total5/total5-b47117bc43a775b525813af56d54350394c22356/html/Uitwerkingen/BB/Coq/Taak10/Taak10_prop030.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7019477529074593}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (lf1 : natural) (y : natural) (x : natural)\n  : natural := plus y x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj275_coqofml_0ieoMS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.701764660309453}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) : natural := mult lf2 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj14_coqofml_A6hGjI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7017646555950408}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\n\nFrom LF Require Export Lists.\n\nInductive natlist : Type :=\n| nat_nil\n| nat_cons (n : nat) (lst : natlist).\n\nInductive boollist : Type :=\n| bool_nil\n| bool_cons (b : bool) (lst : boollist).\n\nInductive list (X : Type) :=\n| nil\n| cons (x : X) (lst : list X).\n\nCheck list : Type -> Type.\n\nCheck (nil nat) : list nat.\n\nCheck (cons nat 3 (nil nat)) : list nat.\n\nCheck nil : forall (X : Type), list X.\n\nCheck cons : forall (X : Type), X -> list X -> list X.\n\nCheck (cons nat 2 (cons nat 2 (nil nat))) : list nat.\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\nExample test_repeat_1 : \n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\nExample test_repeat_2 : \n  repeat bool false 2 = cons bool false (cons bool false (nil bool)).\nProof. reflexivity. Qed.\n\nModule MumbleGrumble.\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(* \nd (b a 5) - No\nd mumble (b a 5) - Yes\nd bool (b a 5) - No\ne bool true - Yes\ne mumble (b c 0) - Yes\ne bool (b c 0) - No\nc - No\n*)\nEnd MumbleGrumble.\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\nCheck repeat' : forall X : Type, X -> nat -> list X.\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0 => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n  \nDefinition  list_123 := cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\nArguments nil {X}.\nArguments cons {X}.\nArguments repeat {X}.\n\nDefinition  list_123'' := cons 1 (cons 2 (cons 3 nil)).\n\nFixpoint repeat''' {X: Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\nFixpoint app {X : Type} (l_1 l_2 : list X) : list X :=\n  match l_1 with\n  | nil => l_2\n  | cons h t => cons h (app t l_2)\n  end.\n\nFixpoint rev {X : Type} (l : list X) : list X :=\n  match l with\n  | nil => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ t => S (length t)\n  end.\n\n  Example test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\nFail Definition mynil := nil.\n\nDefinition mynil : list nat := nil.\n\nCheck @nil : forall X : Type, list X.\n\nDefinition mynil' := @nil nat.\n\nDefinition mynil'' := @nil. Check mynil''.\n\nNotation \"x :: y\" :=\n  (cons x y)\n  (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) .. ).\nNotation \"x ++ y\" :=\n  (app x y)\n  (at level 60, right associativity).\n\nDefinition list_123''' := [1; 2; 3].\n\nTheorem app_assoc : forall X (lst1 lst2 lst3 : list X),\n  (lst1 ++ lst2) ++ lst3 = lst1 ++ (lst2 ++ lst3).\nProof.\n  intros X lst1 lst2 lst3.\n  induction lst1 as [| h1 t1].\n  - simpl. reflexivity. \n  - simpl. rewrite IHt1. reflexivity.\nQed.\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros X l.\n  induction l as [|h t].\n  - simpl. reflexivity.\n  - simpl. rewrite IHt. reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros X l1 l2.\n  induction l1 as [|h1 t1].\n  - simpl. reflexivity.\n  - simpl. rewrite IHt1. reflexivity.\nQed.\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros X l1 l2.\n  induction l1 as [|h1 t1].\n  - simpl. rewrite app_nil_r. reflexivity.\n  - simpl. rewrite <- app_assoc. rewrite <- IHt1. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros X l.\n  induction l as [|h t].\n  - simpl. reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHt. simpl. reflexivity.\nQed.\n\n(* Polymorphic pairs *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y}.\n\nNotation \"( x , y )\" := (pair x y).\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y) : list (X * Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\nExample combine_ex : combine [1;2] [3;4] = [(1,3); (2,4)].\nProof. reflexivity. Qed.\n\n(* Polymorphic Options *)\n\nModule OptionPlayGround.\n\nInductive option (X : Type) :=\n| Some (x : X)\n| None.\n\nArguments Some {X}.\nArguments None {X}.\n\nEnd OptionPlayGround.\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n  match l with\n  | [] => None\n  | a :: l' => match n with\n              | 0 => 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 [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\nCheck @combine : forall X Y : Type, list X -> list Y -> list (X * Y).\nCompute (combine [1;2] [false;false;true;true]).\n\nFixpoint split {X Y : Type} (l : list (X * Y)) : (list X) * (list Y) :=\n  match l with\n  | [] => ([], [])\n  | (m, n) :: t => match (split t) with\n             | (l1, l2) => (m :: l1, n :: l2)\n             end\n  end.\n  \nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof. simpl. reflexivity. Qed.\n\nTheorem split_pair : forall (X Y : Type) (x : X) (y : Y),\n  split [(x, y)] = ([x], [y]).\nProof. \n  intros X Y x y.\n  simpl.\n  reflexivity.\nQed.\n\nDefinition hd_error {X : Type} (l : list X) : option X :=\n  match l with\n  | [] => None\n  | h :: _ => Some h\n  end.\nCheck @hd_error : forall X : Type, list X -> option X.\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. simpl. reflexivity. Qed.\nExample test_hd_error2 : hd_error [[1];[2]] = Some [1].\nProof. simpl. reflexivity. Qed.\n\n(* Higher-order functions *)\n\nDefinition doit3times {X : Type} (f : X -> X) (n : X) := \n  f (f (f n)).\n  \nCheck @doit3times : forall X : Type, (X -> X) -> X -> X.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\nFixpoint filter {X : Type} (test : X -> bool) (l : list X) : list X :=\n  match l with\n  | [] => []\n  | h :: t => if test h then h :: (filter test t) else filter test t\n  end. \n\nExample test_filter1: filter even [1;2;3;4] = [2;4].\n  Proof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\nExample test_filter2:\n      filter length_is_1\n             [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n    = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter odd l).\nExample test_countoddmembers'1: countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2: countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3: countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\nExample test_anon_fun' : doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\nDefinition filter_even_gt7 (l : list nat) : list nat :=\n  filter (fun n => (even n) && (leb 7 n)) l.\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\n  Proof. reflexivity. Qed.\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\n  Proof. reflexivity. Qed.\n\nDefinition partition {X : Type} (test : X -> bool) (l : list X) : list X * list X :=\n  (filter test l, filter (fun n => negb (test n)) l).\nExample test_partition1: partition odd [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. reflexivity. Qed.\n\nFixpoint map {X Y : Type} (f : X->Y) (l : list X) : list Y :=\n  match l with\n  | [] => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\nExample test_map2: map odd [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\nExample test_map3: map (fun n => [even n;odd n]) [2;1;2;5] = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed. \n\nLemma map_app : forall {X Y : Type} (f : X -> Y) (l1 l2 : list X),\n  map f (l1 ++ l2) = (map f l1) ++ (map f l2).\nProof.\n  intros X Y f l1 l2.\n  induction l1 as [|h1 t1].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHt1. reflexivity.\nQed.\n  \nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros X Y f l.\n  induction l as [|h t].\n  - simpl. reflexivity.\n  - simpl. rewrite <- IHt. rewrite map_app. simpl. reflexivity.\nQed.\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X) : list Y :=\n  match l with\n  | [] => []\n  | h :: t => (f h) ++ (flat_map f t)\n  end.\n\nExample test_flat_map1: flat_map (fun n => [n;n;n]) [1;5;4] = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. simpl. reflexivity. Qed.\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X) : option Y :=\n  match xo with\n  | None => None\n  | Some x => Some (f x)\n  end.\n  \nFixpoint fold {X Y : Type} (f : X->Y->Y) (l : list X) (b : Y) : Y :=\n  match l with\n  | [] => b\n  | h :: t => f h (fold f t b)\n  end.\n\nCheck (fold andb) : list bool -> bool -> bool.\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n  \nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\nDefinition constfun {X: Type} (x: X) : nat -> X :=\n  fun (k:nat) => x.\nDefinition ftrue := constfun true.\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\nDefinition plus3 := plus 3.\nCheck plus3 : nat -> nat.\nExample test_plus3 : plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' : doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' : doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\nModule Exercises.\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros X l.\n  induction l as [|h t].\n  - reflexivity.\n  - simpl. rewrite <- IHt. reflexivity.\nQed.\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y :=\n  fold (fun x b => (f x) :: b) l [].\n\nTheorem fold_map_correct : forall (X Y : Type) (f: X -> Y) (l : list X),\n  map f l = fold_map f l.\nProof.\n  intros X Y f l.\n  induction l as [|h t].\n  - reflexivity.\n  - simpl. rewrite IHt. reflexivity.\nQed.\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z :=\nf (x, y).\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z :=\nf (fst p) (snd p).\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type) (f : X -> Y -> Z) x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros X Y Z f x y.\n  reflexivity.\nQed.\n\nTheorem curry_uncurry : forall (X Y Z : Type) (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros X Y Z f p.\n  destruct p.\n  reflexivity.\nQed.\n\n(* Church Numerals (Advanced) *)\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\nDefinition three : cnat := @doit3times.\n\nDefinition zero' : cnat :=\n  fun (X : Type) (succ : X -> X) (zero : X) => zero.\nDefinition one' : cnat :=\n  fun (X : Type) (succ : X -> X) (zero : X) => succ zero.\nDefinition two' : cnat :=\n  fun (X : Type) (succ : X -> X) (zero : X) => succ (succ zero).\n\nExample zero_church_peano : zero nat S O = 0.\nProof. reflexivity. Qed.\nExample one_church_peano : one nat S O = 1.\nProof. reflexivity. Qed.\nExample two_church_peano : two nat S O = 2.\nProof. reflexivity. Qed.\n\nDefinition scc (n : cnat) : cnat :=\n  fun (X : Type) (succ : X -> X) (x : X) => n X succ(succ x).\n\nExample scc_1 : scc zero = one.\nProof. reflexivity. Qed.\nExample scc_2 : scc one = two.\nProof. reflexivity. Qed.\nExample scc_3 : scc two = three.\nProof. reflexivity. Qed.\n\nDefinition plus (n m : cnat) : cnat :=\n  fun (X : Type) (succ : X -> X) (x : X) => n X succ (m X succ x).\n  \nCompute (plus zero zero).\n\nExample plus_1 : plus zero one = one.\nProof. reflexivity. Qed.\nExample plus_2 : plus two three = plus three two.\nProof. reflexivity. Qed.\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. reflexivity. Qed.\n\nDefinition mult (n m : cnat) : cnat :=\n  fun (X : Type) (succ : X -> X) => n X (m X succ).\n\nCompute (mult zero one).\n  \nExample mult_1 : mult one one = one.\nProof. reflexivity. Qed.\nExample mult_2 : mult zero (plus three three) = zero.\nProof. reflexivity. Qed.\nExample mult_3 : mult two three = plus three three.\nProof. reflexivity. Qed.\n\nDefinition exp (n m : cnat) : cnat :=\n  fun (X : Type) => m (X -> X) (n X).\nExample exp_1 : exp two two = plus two two.\nProof. reflexivity. Qed.\nExample exp_2 : exp three zero = one.\nProof. reflexivity. Qed.\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. reflexivity. Qed.\n\nEnd Church.\nEnd Exercises.", "meta": {"author": "lchudinov", "repo": "sf", "sha": "e513f57aac1e045ebf03633d735b18928aa71b8a", "save_path": "github-repos/coq/lchudinov-sf", "path": "github-repos/coq/lchudinov-sf/sf-e513f57aac1e045ebf03633d735b18928aa71b8a/lf/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.7017233343645412}}
{"text": "(***********************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team    *)\n(* <O___,, *        INRIA-Rocquencourt  &  LRI-CNRS-Orsay              *)\n(*   \\VV/  *************************************************************)\n(*    //   *      This file is distributed under the terms of the      *)\n(*         *       GNU Lesser General Public License Version 2.1       *)\n(***********************************************************************)\n\nRequire Import Orders OrdersTac OrdersFacts Setoid Morphisms Basics.\n\n(** * A Generic construction of min and max *)\n\n(** ** First, an interface for types with [max] and/or [min] *)\n\nModule Type HasMax (Import E:EqLe').\n Parameter Inline max : t -> t -> t.\n Parameter max_l : forall x y, y<=x -> max x y == x.\n Parameter max_r : forall x y, x<=y -> max x y == y.\nEnd HasMax.\n\nModule Type HasMin (Import E:EqLe').\n Parameter Inline min : t -> t -> t.\n Parameter min_l : forall x y, x<=y -> min x y == x.\n Parameter min_r : forall x y, y<=x -> min x y == y.\nEnd HasMin.\n\nModule Type HasMinMax (E:EqLe) := HasMax E <+ HasMin E.\n\n\n(** ** Any [OrderedTypeFull] can be equipped by [max] and [min]\n    based on the compare function. *)\n\nDefinition gmax {A} (cmp : A->A->comparison) x y :=\n match cmp x y with Lt => y | _ => x end.\nDefinition gmin {A} (cmp : A->A->comparison) x y :=\n match cmp x y with Gt => y | _ => x end.\n\nModule GenericMinMax (Import O:OrderedTypeFull') <: HasMinMax O.\n\n Definition max := gmax O.compare.\n Definition min := gmin O.compare.\n\n Lemma ge_not_lt : forall x y, y<=x -> x<y -> False.\n Proof.\n intros x y H H'.\n apply (StrictOrder_Irreflexive x).\n rewrite le_lteq in *; destruct H as [H|H].\n transitivity y; auto.\n rewrite H in H'; auto.\n Qed.\n\n Lemma max_l : forall x y, y<=x -> max x y == x.\n Proof.\n intros. unfold max, gmax. case compare_spec; auto with relations.\n intros; elim (ge_not_lt x y); auto.\n Qed.\n\n Lemma max_r : forall x y, x<=y -> max x y == y.\n Proof.\n intros. unfold max, gmax. case compare_spec; auto with relations.\n intros; elim (ge_not_lt y x); auto.\n Qed.\n\n Lemma min_l : forall x y, x<=y -> min x y == x.\n Proof.\n intros. unfold min, gmin. case compare_spec; auto with relations.\n intros; elim (ge_not_lt y x); auto.\n Qed.\n\n Lemma min_r : forall x y, y<=x -> min x y == y.\n Proof.\n intros. unfold min, gmin. case compare_spec; auto with relations.\n intros; elim (ge_not_lt x y); auto.\n Qed.\n\nEnd GenericMinMax.\n\n\n(** ** Consequences of the minimalist interface: facts about [max]. *)\n\nModule MaxLogicalProperties (Import O:TotalOrder')(Import M:HasMax O).\n Module Import T := !MakeOrderTac O.\n\n(** An alternative caracterisation of [max], equivalent to\n    [max_l /\\ max_r] *)\n\nLemma max_spec : forall n m,\n  (n < m /\\ max n m == m)  \\/ (m <= n /\\ max n m == n).\nProof.\n intros n m.\n destruct (lt_total n m); [left|right].\n split; auto. apply max_r. rewrite le_lteq; auto.\n assert (m <= n) by (rewrite le_lteq; intuition).\n split; auto. apply max_l; auto.\nQed.\n\n(** A more symmetric version of [max_spec], based only on [le].\n    Beware that left and right alternatives overlap. *)\n\nLemma max_spec_le : forall n m,\n (n <= m /\\ max n m == m) \\/ (m <= n /\\ max n m == n).\nProof.\n intros. destruct (max_spec n m); [left|right]; intuition; order.\nQed.\n\nInstance : Proper (eq==>eq==>iff) le.\nProof. repeat red. intuition order. Qed.\n\nInstance max_compat : Proper (eq==>eq==>eq) max.\nProof.\nintros x x' Hx y y' Hy.\nassert (H1 := max_spec x y). assert (H2 := max_spec x' y').\nset (m := max x y) in *; set (m' := max x' y') in *; clearbody m m'.\nrewrite <- Hx, <- Hy in *.\ndestruct (lt_total x y); intuition order.\nQed.\n\n\n(** A function satisfying the same specification is equal to [max]. *)\n\nLemma max_unicity : forall n m p,\n ((n < m /\\ p == m)  \\/ (m <= n /\\ p == n)) ->  p == max n m.\nProof.\n intros. assert (Hm := max_spec n m).\n destruct (lt_total n m); intuition; order.\nQed.\n\nLemma max_unicity_ext : forall f,\n (forall n m, (n < m /\\ f n m == m)  \\/ (m <= n /\\ f n m == n)) ->\n (forall n m, f n m == max n m).\nProof.\n intros. apply max_unicity; auto.\nQed.\n\n(** [max] commutes with monotone functions. *)\n\nLemma max_mono: forall f,\n (Proper (eq ==> eq) f) ->\n (Proper (le ==> le) f) ->\n forall x y, max (f x) (f y) == f (max x y).\nProof.\n intros f Eqf Lef x y.\n destruct (max_spec x y) as [(H,E)|(H,E)]; rewrite E;\n  destruct (max_spec (f x) (f y)) as [(H',E')|(H',E')]; auto.\n assert (f x <= f y) by (apply Lef; order). order.\n assert (f y <= f x) by (apply Lef; order). order.\nQed.\n\n(** *** Semi-lattice algebraic properties of [max] *)\n\nLemma max_id : forall n, max n n == n.\nProof.\n intros. destruct (max_spec n n); intuition.\nQed.\n\nNotation max_idempotent := max_id (only parsing).\n\nLemma max_assoc : forall m n p, max m (max n p) == max (max m n) p.\nProof.\n intros.\n destruct (max_spec n p) as [(H,Eq)|(H,Eq)]; rewrite Eq.\n destruct (max_spec m n) as [(H',Eq')|(H',Eq')]; rewrite Eq'.\n destruct (max_spec m p); intuition; order. order.\n destruct (max_spec m n) as [(H',Eq')|(H',Eq')]; rewrite Eq'. order.\n destruct (max_spec m p); intuition; order.\nQed.\n\nLemma max_comm : forall n m, max n m == max m n.\nProof.\n intros.\n destruct (max_spec n m) as [(H,Eq)|(H,Eq)]; rewrite Eq.\n destruct (max_spec m n) as [(H',Eq')|(H',Eq')]; rewrite Eq'; order.\n destruct (max_spec m n) as [(H',Eq')|(H',Eq')]; rewrite Eq'; order.\nQed.\n\n(** *** Least-upper bound properties of [max] *)\n\nLemma le_max_l : forall n m, n <= max n m.\nProof.\n intros; destruct (max_spec n m); intuition; order.\nQed.\n\nLemma le_max_r : forall n m, m <= max n m.\nProof.\n intros; destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_l_iff : forall n m, max n m == n <-> m <= n.\nProof.\n split. intro H; rewrite <- H. apply le_max_r. apply max_l.\nQed.\n\nLemma max_r_iff : forall n m, max n m == m <-> n <= m.\nProof.\n split. intro H; rewrite <- H. apply le_max_l. apply max_r.\nQed.\n\nLemma max_le : forall n m p, p <= max n m -> p <= n \\/ p <= m.\nProof.\n intros n m p H; destruct (max_spec n m);\n  [right|left]; intuition; order.\nQed.\n\nLemma max_le_iff : forall n m p, p <= max n m <-> p <= n \\/ p <= m.\nProof.\n intros. split. apply max_le.\n destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_lt_iff : forall n m p, p < max n m <-> p < n \\/ p < m.\nProof.\n intros. destruct (max_spec n m); intuition;\n  order || (right; order) || (left; order).\nQed.\n\nLemma max_lub_l : forall n m p, max n m <= p -> n <= p.\nProof.\n intros; destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_lub_r : forall n m p, max n m <= p -> m <= p.\nProof.\n intros; destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_lub : forall n m p, n <= p -> m <= p -> max n m <= p.\nProof.\n intros; destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_lub_iff : forall n m p, max n m <= p <-> n <= p /\\ m <= p.\nProof.\n intros; destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_lub_lt : forall n m p, n < p -> m < p -> max n m < p.\nProof.\n intros; destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_lub_lt_iff : forall n m p, max n m < p <-> n < p /\\ m < p.\nProof.\n intros; destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_le_compat_l : forall n m p, n <= m -> max p n <= max p m.\nProof.\n intros.\n destruct (max_spec p n) as [(LT,E)|(LE,E)]; rewrite E.\n assert (LE' := le_max_r p m). order.\n apply le_max_l.\nQed.\n\nLemma max_le_compat_r : forall n m p, n <= m -> max n p <= max m p.\nProof.\n intros. rewrite (max_comm n p), (max_comm m p).\n auto using max_le_compat_l.\nQed.\n\nLemma max_le_compat : forall n m p q, n <= m -> p <= q ->\n max n p <= max m q.\nProof.\n intros  n m p q Hnm Hpq.\n assert (LE := max_le_compat_l _ _ m Hpq).\n assert (LE' := max_le_compat_r _ _ p Hnm).\n order.\nQed.\n\nEnd MaxLogicalProperties.\n\n\n(** ** Properties concernant [min], then both [min] and [max].\n\n   To avoid too much code duplication, we exploit that [min] can be\n   seen as a [max] of the reversed order.\n*)\n\nModule MinMaxLogicalProperties (Import O:TotalOrder')(Import M:HasMinMax O).\n Include MaxLogicalProperties O M.\n Import T.\n\n Module ORev := TotalOrderRev O.\n Module MRev <: HasMax ORev.\n  Definition max x y := M.min y x.\n  Definition max_l x y := M.min_r y x.\n  Definition max_r x y := M.min_l y x.\n End MRev.\n Module MPRev := MaxLogicalProperties ORev MRev.\n\nInstance min_compat : Proper (eq==>eq==>eq) min.\nProof. intros x x' Hx y y' Hy. apply MPRev.max_compat; assumption. Qed.\n\nLemma min_spec : forall n m,\n (n < m /\\ min n m == n) \\/ (m <= n /\\ min n m == m).\nProof. intros. exact (MPRev.max_spec m n). Qed.\n\nLemma min_spec_le : forall n m,\n (n <= m /\\ min n m == n) \\/ (m <= n /\\ min n m == m).\nProof. intros. exact (MPRev.max_spec_le m n). Qed.\n\nLemma min_mono: forall f,\n (Proper (eq ==> eq) f) ->\n (Proper (le ==> le) f) ->\n forall x y, min (f x) (f y) == f (min x y).\nProof.\n intros. apply MPRev.max_mono; auto. compute in *; eauto.\nQed.\n\nLemma min_unicity : forall n m p,\n ((n < m /\\ p == n)  \\/ (m <= n /\\ p == m)) ->  p == min n m.\nProof. intros n m p. apply MPRev.max_unicity. Qed.\n\nLemma min_unicity_ext : forall f,\n (forall n m, (n < m /\\ f n m == n)  \\/ (m <= n /\\ f n m == m)) ->\n (forall n m, f n m == min n m).\nProof. intros f H n m. apply MPRev.max_unicity, H; auto. Qed.\n\nLemma min_id : forall n, min n n == n.\nProof. intros. exact (MPRev.max_id n). Qed.\n\nNotation min_idempotent := min_id (only parsing).\n\nLemma min_assoc : forall m n p, min m (min n p) == min (min m n) p.\nProof. intros. symmetry; apply MPRev.max_assoc. Qed.\n\nLemma min_comm : forall n m, min n m == min m n.\nProof. intros. exact (MPRev.max_comm m n). Qed.\n\nLemma le_min_r : forall n m, min n m <= m.\nProof. intros. exact (MPRev.le_max_l m n). Qed.\n\nLemma le_min_l : forall n m, min n m <= n.\nProof. intros. exact (MPRev.le_max_r m n). Qed.\n\nLemma min_l_iff : forall n m, min n m == n <-> n <= m.\nProof. intros n m. exact (MPRev.max_r_iff m n). Qed.\n\nLemma min_r_iff : forall n m, min n m == m <-> m <= n.\nProof. intros n m. exact (MPRev.max_l_iff m n). Qed.\n\nLemma min_le : forall n m p, min n m <= p -> n <= p \\/ m <= p.\nProof. intros n m p H. destruct (MPRev.max_le _ _ _ H); auto. Qed.\n\nLemma min_le_iff : forall n m p, min n m <= p <-> n <= p \\/ m <= p.\nProof. intros n m p. rewrite (MPRev.max_le_iff m n p); intuition. Qed.\n\nLemma min_lt_iff : forall n m p, min n m < p <-> n < p \\/ m < p.\nProof. intros n m p. rewrite (MPRev.max_lt_iff m n p); intuition. Qed.\n\nLemma min_glb_l : forall n m p, p <= min n m -> p <= n.\nProof. intros n m. exact (MPRev.max_lub_r m n). Qed.\n\nLemma min_glb_r : forall n m p, p <= min n m -> p <= m.\nProof. intros n m. exact (MPRev.max_lub_l m n). Qed.\n\nLemma min_glb : forall n m p, p <= n -> p <= m -> p <= min n m.\nProof. intros. apply MPRev.max_lub; auto. Qed.\n\nLemma min_glb_iff : forall n m p, p <= min n m <-> p <= n /\\ p <= m.\nProof. intros. rewrite (MPRev.max_lub_iff m n p); intuition. Qed.\n\nLemma min_glb_lt : forall n m p, p < n -> p < m -> p < min n m.\nProof. intros. apply MPRev.max_lub_lt; auto. Qed.\n\nLemma min_glb_lt_iff : forall n m p, p < min n m <-> p < n /\\ p < m.\nProof. intros. rewrite (MPRev.max_lub_lt_iff m n p); intuition. Qed.\n\nLemma min_le_compat_l : forall n m p, n <= m -> min p n <= min p m.\nProof. intros n m. exact (MPRev.max_le_compat_r m n). Qed.\n\nLemma min_le_compat_r : forall n m p, n <= m -> min n p <= min m p.\nProof. intros n m. exact (MPRev.max_le_compat_l m n). Qed.\n\nLemma min_le_compat : forall n m p q, n <= m -> p <= q ->\n min n p <= min m q.\nProof. intros. apply MPRev.max_le_compat; auto. Qed.\n\n\n(** *** Combined properties of min and max *)\n\nLemma min_max_absorption : forall n m, max n (min n m) == n.\nProof.\n intros.\n destruct (min_spec n m) as [(C,E)|(C,E)]; rewrite E.\n apply max_l. order.\n destruct (max_spec n m); intuition; order.\nQed.\n\nLemma max_min_absorption : forall n m, min n (max n m) == n.\nProof.\n intros.\n destruct (max_spec n m) as [(C,E)|(C,E)]; rewrite E.\n destruct (min_spec n m) as [(C',E')|(C',E')]; auto. order.\n apply min_l; auto. order.\nQed.\n\n(** Distributivity *)\n\nLemma max_min_distr : forall n m p,\n max n (min m p) == min (max n m) (max n p).\nProof.\n intros. symmetry. apply min_mono.\n eauto with *.\n repeat red; intros. apply max_le_compat_l; auto.\nQed.\n\nLemma min_max_distr : forall n m p,\n min n (max m p) == max (min n m) (min n p).\nProof.\n intros. symmetry. apply max_mono.\n eauto with *.\n repeat red; intros. apply min_le_compat_l; auto.\nQed.\n\n(** Modularity *)\n\nLemma max_min_modular : forall n m p,\n max n (min m (max n p)) == min (max n m) (max n p).\nProof.\n intros. rewrite <- max_min_distr.\n destruct (max_spec n p) as [(C,E)|(C,E)]; rewrite E; auto with *.\n destruct (min_spec m n) as [(C',E')|(C',E')]; rewrite E'.\n rewrite 2 max_l; try order. rewrite min_le_iff; auto.\n rewrite 2 max_l; try order. rewrite min_le_iff; auto.\nQed.\n\nLemma min_max_modular : forall n m p,\n min n (max m (min n p)) == max (min n m) (min n p).\nProof.\n intros. rewrite <- min_max_distr.\n destruct (min_spec n p) as [(C,E)|(C,E)]; rewrite E; auto with *.\n destruct (max_spec m n) as [(C',E')|(C',E')]; rewrite E'.\n rewrite 2 min_l; try order. rewrite max_le_iff; right; order.\n rewrite 2 min_l; try order. rewrite max_le_iff; auto.\nQed.\n\n(** Disassociativity *)\n\nLemma max_min_disassoc : forall n m p,\n min n (max m p) <= max (min n m) p.\nProof.\n intros. rewrite min_max_distr.\n auto using max_le_compat_l, le_min_r.\nQed.\n\n(** Anti-monotonicity swaps the role of [min] and [max] *)\n\nLemma max_min_antimono : forall f,\n Proper (eq==>eq) f ->\n Proper (le==>inverse le) f ->\n forall x y, max (f x) (f y) == f (min x y).\nProof.\n intros f Eqf Lef x y.\n destruct (min_spec x y) as [(H,E)|(H,E)]; rewrite E;\n  destruct (max_spec (f x) (f y)) as [(H',E')|(H',E')]; auto.\n assert (f y <= f x) by (apply Lef; order). order.\n assert (f x <= f y) by (apply Lef; order). order.\nQed.\n\nLemma min_max_antimono : forall f,\n Proper (eq==>eq) f ->\n Proper (le==>inverse le) f ->\n forall x y, min (f x) (f y) == f (max x y).\nProof.\n intros f Eqf Lef x y.\n destruct (max_spec x y) as [(H,E)|(H,E)]; rewrite E;\n  destruct (min_spec (f x) (f y)) as [(H',E')|(H',E')]; auto.\n assert (f y <= f x) by (apply Lef; order). order.\n assert (f x <= f y) by (apply Lef; order). order.\nQed.\n\nEnd MinMaxLogicalProperties.\n\n\n(** ** Properties requiring a decidable order *)\n\nModule MinMaxDecProperties (Import O:OrderedTypeFull')(Import M:HasMinMax O).\n\n(** Induction principles for [max]. *)\n\nLemma max_case_strong : forall n m (P:t -> Type),\n  (forall x y, x==y -> P x -> P y) ->\n  (m<=n -> P n) -> (n<=m -> P m) -> P (max n m).\nProof.\nintros n m P Compat Hl Hr.\ndestruct (CompSpec2Type (compare_spec n m)) as [EQ|LT|GT].\nassert (n<=m) by (rewrite le_lteq; auto).\napply (Compat m), Hr; auto. symmetry; apply max_r; auto.\nassert (n<=m) by (rewrite le_lteq; auto).\napply (Compat m), Hr; auto. symmetry; apply max_r; auto.\nassert (m<=n) by (rewrite le_lteq; auto).\napply (Compat n), Hl; auto. symmetry; apply max_l; auto.\nDefined.\n\nLemma max_case : forall n m (P:t -> Type),\n  (forall x y, x == y -> P x -> P y) ->\n  P n -> P m -> P (max n m).\nProof. intros. apply max_case_strong; auto. Defined.\n\n(** [max] returns one of its arguments. *)\n\nLemma max_dec : forall n m, {max n m == n} + {max n m == m}.\nProof.\n intros n m. apply max_case; auto with relations.\n intros x y H [E|E]; [left|right]; rewrite <-H; auto.\nDefined.\n\n(** Idem for [min] *)\n\nLemma min_case_strong : forall n m (P:O.t -> Type),\n (forall x y, x == y -> P x -> P y) ->\n (n<=m -> P n) -> (m<=n -> P m) -> P (min n m).\nProof.\nintros n m P Compat Hl Hr.\ndestruct (CompSpec2Type (compare_spec n m)) as [EQ|LT|GT].\nassert (n<=m) by (rewrite le_lteq; auto).\napply (Compat n), Hl; auto. symmetry; apply min_l; auto.\nassert (n<=m) by (rewrite le_lteq; auto).\napply (Compat n), Hl; auto. symmetry; apply min_l; auto.\nassert (m<=n) by (rewrite le_lteq; auto).\napply (Compat m), Hr; auto. symmetry; apply min_r; auto.\nDefined.\n\nLemma min_case : forall n m (P:O.t -> Type),\n  (forall x y, x == y -> P x -> P y) ->\n  P n -> P m -> P (min n m).\nProof. intros. apply min_case_strong; auto. Defined.\n\nLemma min_dec : forall n m, {min n m == n} + {min n m == m}.\nProof.\n intros. apply min_case; auto with relations.\n intros x y H [E|E]; [left|right]; rewrite <- E; auto with relations.\nDefined.\n\nEnd MinMaxDecProperties.\n\nModule MinMaxProperties (Import O:OrderedTypeFull')(Import M:HasMinMax O).\n Module OT := OTF_to_TotalOrder O.\n Include MinMaxLogicalProperties OT M.\n Include MinMaxDecProperties O M.\n Definition max_l := max_l.\n Definition max_r := max_r.\n Definition min_l := min_l.\n Definition min_r := min_r.\n Notation max_monotone := max_mono.\n Notation min_monotone := min_mono.\n Notation max_min_antimonotone := max_min_antimono.\n Notation min_max_antimonotone := min_max_antimono.\nEnd MinMaxProperties.\n\n\n(** ** When the equality is Leibniz, we can skip a few [Proper] precondition. *)\n\nModule UsualMinMaxLogicalProperties\n (Import O:UsualTotalOrder')(Import M:HasMinMax O).\n\n Include MinMaxLogicalProperties O M.\n\n Lemma max_monotone : forall f, Proper (le ==> le) f ->\n  forall x y, max (f x) (f y) = f (max x y).\n Proof. intros; apply max_mono; auto. congruence. Qed.\n\n Lemma min_monotone : forall f, Proper (le ==> le) f ->\n  forall x y, min (f x) (f y) = f (min x y).\n Proof. intros; apply min_mono; auto. congruence. Qed.\n\n Lemma min_max_antimonotone : forall f, Proper (le ==> inverse le) f ->\n  forall x y, min (f x) (f y) = f (max x y).\n Proof. intros; apply min_max_antimono; auto. congruence. Qed.\n\n Lemma max_min_antimonotone : forall f, Proper (le ==> inverse le) f ->\n  forall x y, max (f x) (f y) = f (min x y).\n Proof. intros; apply max_min_antimono; auto. congruence. Qed.\n\nEnd UsualMinMaxLogicalProperties.\n\n\nModule UsualMinMaxDecProperties\n (Import O:UsualOrderedTypeFull')(Import M:HasMinMax O).\n\n Module P := MinMaxDecProperties O M.\n\n Lemma max_case_strong : forall n m (P:t -> Type),\n  (m<=n -> P n) -> (n<=m -> P m) -> P (max n m).\n Proof. intros; apply P.max_case_strong; auto. congruence. Defined.\n\n Lemma max_case : forall n m (P:t -> Type),\n  P n -> P m -> P (max n m).\n Proof. intros; apply max_case_strong; auto. Defined.\n\n Lemma max_dec : forall n m, {max n m = n} + {max n m = m}.\n Proof. exact P.max_dec. Defined.\n\n Lemma min_case_strong : forall n m (P:O.t -> Type),\n  (n<=m -> P n) -> (m<=n -> P m) -> P (min n m).\n Proof. intros; apply P.min_case_strong; auto. congruence. Defined.\n\n Lemma min_case : forall n m (P:O.t -> Type),\n  P n -> P m -> P (min n m).\n Proof. intros. apply min_case_strong; auto. Defined.\n\n Lemma min_dec : forall n m, {min n m = n} + {min n m = m}.\n Proof. exact P.min_dec. Defined.\n\nEnd UsualMinMaxDecProperties.\n\nModule UsualMinMaxProperties\n (Import O:UsualOrderedTypeFull')(Import M:HasMinMax O).\n Module OT := OTF_to_TotalOrder O.\n Include UsualMinMaxLogicalProperties OT M.\n Include UsualMinMaxDecProperties O M.\n Definition max_l := max_l.\n Definition max_r := max_r.\n Definition min_l := min_l.\n Definition min_r := min_r.\nEnd UsualMinMaxProperties.\n\n\n(** From [TotalOrder] and [HasMax] and [HasEqDec], we can prove\n    that the order is decidable and build an [OrderedTypeFull]. *)\n\nModule TOMaxEqDec_to_Compare\n (Import O:TotalOrder')(Import M:HasMax O)(Import E:HasEqDec O) <: HasCompare O.\n\n Definition compare x y :=\n  if eq_dec x y then Eq\n  else if eq_dec (M.max x y) y then Lt else Gt.\n\n Lemma compare_spec : forall x y, CompSpec eq lt x y (compare x y).\n Proof.\n intros; unfold compare; repeat destruct eq_dec; auto; constructor.\n destruct (lt_total x y); auto.\n absurd (x==y); auto. transitivity (max x y); auto.\n symmetry. apply max_l. rewrite le_lteq; intuition.\n destruct (lt_total y x); auto.\n absurd (max x y == y); auto. apply max_r; rewrite le_lteq; intuition.\n Qed.\n\nEnd TOMaxEqDec_to_Compare.\n\nModule TOMaxEqDec_to_OTF (O:TotalOrder)(M:HasMax O)(E:HasEqDec O)\n <: OrderedTypeFull\n := O <+ E <+ TOMaxEqDec_to_Compare O M E.\n\n\n\n(** TODO: Some Remaining questions...\n\n--> Compare with a type-classes version ?\n\n--> Is max_unicity and max_unicity_ext really convenient to express\n    that any possible definition of max will in fact be equivalent ?\n\n--> Is it possible to avoid copy-paste about min even more ?\n\n*)\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Structures/GenericMinMax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7017233090782521}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2010     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\nRequire Import NAxioms NSub NDiv NGcd.\n\n(** * Least Common Multiple *)\n\n(** Unlike other functions around, we will define lcm below instead of\n  axiomatizing it. Indeed, there is no \"prior art\" about lcm in the\n  standard library to be compliant with, and the generic definition\n  of lcm via gcd is quite reasonable.\n\n  By the way, we also state here some combined properties of div/mod\n  and gcd.\n*)\n\nModule Type NLcmProp\n (Import A : NAxiomsSig')\n (Import B : NSubProp A)\n (Import C : NDivProp A B)\n (Import D : NGcdProp A B).\n\n(** Divibility and modulo *)\n\nLemma mod_divide : forall a b, b~=0 -> (a mod b == 0 <-> (b|a)).\nProof.\n intros a b Hb. split.\n intros Hab. exists (a/b). rewrite (div_mod a b Hb) at 2.\n  rewrite Hab; now nzsimpl.\n intros (c,Hc). rewrite <- Hc, mul_comm. now apply mod_mul.\nQed.\n\nLemma divide_div_mul_exact : forall a b c, b~=0 -> (b|a) ->\n (c*a)/b == c*(a/b).\nProof.\n intros a b c Hb H.\n apply mul_cancel_l with b; trivial.\n rewrite mul_assoc, mul_shuffle0.\n assert (H':=H). apply mod_divide, div_exact in H'; trivial.\n rewrite <- H', (mul_comm a c).\n symmetry. apply div_exact; trivial.\n apply mod_divide; trivial.\n now apply divide_mul_r.\nQed.\n\n(** Gcd of divided elements, for exact divisions *)\n\nLemma gcd_div_factor : forall a b c, c~=0 -> (c|a) -> (c|b) ->\n gcd (a/c) (b/c) == (gcd a b)/c.\nProof.\n intros a b c Hc Ha Hb.\n apply mul_cancel_l with c; try order.\n assert (H:=gcd_greatest _ _ _ Ha Hb).\n apply mod_divide, div_exact in H; try order.\n rewrite <- H.\n rewrite <- gcd_mul_mono_l; try order.\n f_equiv; symmetry; apply div_exact; try order;\n  apply mod_divide; trivial; try order.\nQed.\n\nLemma gcd_div_gcd : forall a b g, g~=0 -> g == gcd a b ->\n gcd (a/g) (b/g) == 1.\nProof.\n intros a b g NZ EQ. rewrite gcd_div_factor.\n now rewrite <- EQ, div_same.\n generalize (gcd_nonneg a b); order.\n rewrite EQ; apply gcd_divide_l.\n rewrite EQ; apply gcd_divide_r.\nQed.\n\n(** The following equality is crucial for Euclid algorithm *)\n\nLemma gcd_mod : forall a b, b~=0 -> gcd (a mod b) b == gcd b a.\nProof.\n intros a b Hb. rewrite (gcd_comm _ b).\n rewrite <- (gcd_add_mult_diag_r b (a mod b) (a/b)).\n now rewrite add_comm, mul_comm, <- div_mod.\nQed.\n\n(** We now define lcm thanks to gcd:\n\n    lcm a b = a * (b / gcd a b)\n            = (a / gcd a b) * b\n            = (a*b) / gcd a b\n\n   Nota: [lcm 0 0] should be 0, which isn't garantee with the third\n   equation above.\n*)\n\nDefinition lcm a b := a*(b/gcd a b).\n\nInstance lcm_wd : Proper (eq==>eq==>eq) lcm.\nProof. unfold lcm. solve_proper. Qed.\n\nLemma lcm_equiv1 : forall a b, gcd a b ~= 0 ->\n  a * (b / gcd a b) == (a*b)/gcd a b.\nProof.\n intros a b H. rewrite divide_div_mul_exact; try easy. apply gcd_divide_r.\nQed.\n\nLemma lcm_equiv2 : forall a b, gcd a b ~= 0 ->\n  (a / gcd a b) * b == (a*b)/gcd a b.\nProof.\n intros a b H. rewrite 2 (mul_comm _ b).\n rewrite divide_div_mul_exact; try easy. apply gcd_divide_l.\nQed.\n\nLemma gcd_div_swap : forall a b,\n (a / gcd a b) * b == a * (b / gcd a b).\nProof.\n intros a b. destruct (eq_decidable (gcd a b) 0) as [EQ|NEQ].\n apply gcd_eq_0 in EQ. destruct EQ as (EQ,EQ'). rewrite EQ, EQ'. now nzsimpl.\n now rewrite lcm_equiv1, <-lcm_equiv2.\nQed.\n\nLemma divide_lcm_l : forall a b, (a | lcm a b).\nProof.\n unfold lcm. intros a b. apply divide_factor_l.\nQed.\n\nLemma divide_lcm_r : forall a b, (b | lcm a b).\nProof.\n unfold lcm. intros a b. rewrite <- gcd_div_swap.\n apply divide_factor_r.\nQed.\n\nLemma divide_div : forall a b c, a~=0 -> (a|b) -> (b|c) -> (b/a|c/a).\nProof.\n intros a b c Ha Hb (c',Hc). exists c'.\n now rewrite mul_comm, <- divide_div_mul_exact, mul_comm, Hc.\nQed.\n\nLemma lcm_least : forall a b c,\n (a | c) -> (b | c) -> (lcm a b | c).\nProof.\n intros a b c Ha Hb. unfold lcm.\n destruct (eq_decidable (gcd a b) 0) as [EQ|NEQ].\n apply gcd_eq_0 in EQ. destruct EQ as (EQ,EQ'). rewrite EQ in *. now nzsimpl.\n assert (Ga := gcd_divide_l a b).\n assert (Gb := gcd_divide_r a b).\n set (g:=gcd a b) in *.\n assert (Ha' := divide_div g a c NEQ Ga Ha).\n assert (Hb' := divide_div g b c NEQ Gb Hb).\n destruct Ha' as (a',Ha'). rewrite <- Ha' in Hb'.\n apply gauss in Hb'; [|apply gcd_div_gcd; unfold g; trivial using gcd_comm].\n destruct Hb' as (b',Hb').\n exists b'.\n rewrite <- mul_assoc, Hb'.\n rewrite (proj2 (div_exact c g NEQ)).\n rewrite <- Ha', mul_assoc. f_equiv.\n apply div_exact; trivial.\n apply mod_divide; trivial.\n apply mod_divide; trivial. transitivity a; trivial.\nQed.\n\nLemma lcm_comm : forall a b, lcm a b == lcm b a.\nProof.\n intros a b. unfold lcm. rewrite (gcd_comm b), (mul_comm b).\n now rewrite <- gcd_div_swap.\nQed.\n\nLemma lcm_divide_iff : forall n m p,\n  (lcm n m | p) <-> (n | p) /\\ (m | p).\nProof.\n intros. split. split.\n transitivity (lcm n m); trivial using divide_lcm_l.\n transitivity (lcm n m); trivial using divide_lcm_r.\n intros (H,H'). now apply lcm_least.\nQed.\n\nLemma lcm_unique : forall n m p,\n 0<=p -> (n|p) -> (m|p) ->\n (forall q, (n|q) -> (m|q) -> (p|q)) ->\n lcm n m == p.\nProof.\n intros n m p Hp Hn Hm H.\n apply divide_antisym; trivial.\n now apply lcm_least.\n apply H. apply divide_lcm_l. apply divide_lcm_r.\nQed.\n\nLemma lcm_unique_alt : forall n m p, 0<=p ->\n (forall q, (p|q) <-> (n|q) /\\ (m|q)) ->\n lcm n m == p.\nProof.\n intros n m p Hp H.\n apply lcm_unique; trivial.\n apply H, divide_refl.\n apply H, divide_refl.\n intros. apply H. now split.\nQed.\n\nLemma lcm_assoc : forall n m p, lcm n (lcm m p) == lcm (lcm n m) p.\nProof.\n intros. apply lcm_unique_alt. apply le_0_l.\n intros. now rewrite !lcm_divide_iff, and_assoc.\nQed.\n\nLemma lcm_0_l : forall n, lcm 0 n == 0.\nProof.\n intros. apply lcm_unique; trivial. order.\n apply divide_refl.\n apply divide_0_r.\nQed.\n\nLemma lcm_0_r : forall n, lcm n 0 == 0.\nProof.\n intros. now rewrite lcm_comm, lcm_0_l.\nQed.\n\nLemma lcm_1_l : forall n, lcm 1 n == n.\nProof.\n intros. apply lcm_unique; trivial using divide_1_l, le_0_l, divide_refl.\nQed.\n\nLemma lcm_1_r : forall n, lcm n 1 == n.\nProof.\n intros. now rewrite lcm_comm, lcm_1_l.\nQed.\n\nLemma lcm_diag : forall n, lcm n n == n.\nProof.\n intros. apply lcm_unique; trivial using divide_refl, le_0_l.\nQed.\n\nLemma lcm_eq_0 : forall n m, lcm n m == 0 <-> n == 0 \\/ m == 0.\nProof.\n intros. split.\n intros EQ.\n apply eq_mul_0.\n apply divide_0_l. rewrite <- EQ. apply lcm_least.\n  apply divide_factor_l. apply divide_factor_r.\n destruct 1 as [EQ|EQ]; rewrite EQ. apply lcm_0_l. apply lcm_0_r.\nQed.\n\nLemma divide_lcm_eq_r : forall n m, (n|m) -> lcm n m == m.\nProof.\n intros n m H. apply lcm_unique_alt; trivial using le_0_l.\n intros q. split. split; trivial. now transitivity m.\n now destruct 1.\nQed.\n\nLemma divide_lcm_iff : forall n m, (n|m) <-> lcm n m == m.\nProof.\n intros n m. split. now apply divide_lcm_eq_r.\n intros EQ. rewrite <- EQ. apply divide_lcm_l.\nQed.\n\nLemma lcm_mul_mono_l :\n  forall n m p, lcm (p * n) (p * m) == p * lcm n m.\nProof.\n intros n m p.\n destruct (eq_decidable p 0) as [Hp|Hp].\n  rewrite Hp. nzsimpl. rewrite lcm_0_l. now nzsimpl.\n destruct (eq_decidable (gcd n m) 0) as [Hg|Hg].\n  apply gcd_eq_0 in Hg. destruct Hg as (Hn,Hm); rewrite Hn, Hm.\n  nzsimpl. rewrite lcm_0_l. now nzsimpl.\n unfold lcm.\n rewrite gcd_mul_mono_l.\n rewrite mul_assoc. f_equiv.\n now rewrite div_mul_cancel_l.\nQed.\n\nLemma lcm_mul_mono_r :\n forall n m p, lcm (n * p) (m * p) == lcm n m * p.\nProof.\n intros n m p. now rewrite !(mul_comm _ p), lcm_mul_mono_l, mul_comm.\nQed.\n\nLemma gcd_1_lcm_mul : forall n m, n~=0 -> m~=0 ->\n (gcd n m == 1 <-> lcm n m == n*m).\nProof.\n intros n m Hn Hm. split; intros H.\n unfold lcm. rewrite H. now rewrite div_1_r.\n unfold lcm in *.\n apply mul_cancel_l in H; trivial.\n assert (Hg : gcd n m ~= 0) by (red; rewrite gcd_eq_0; destruct 1; order).\n assert (H' := gcd_divide_r n m).\n apply mod_divide in H'; trivial. apply div_exact in H'; trivial.\n rewrite H in H'.\n rewrite <- (mul_1_l m) in H' at 1.\n now apply mul_cancel_r in H'.\nQed.\n\nEnd NLcmProp.\n", "meta": {"author": "mattam82", "repo": "Coq-misc", "sha": "60bc3cbe72083f4fa1aa759914936e4fa3d6b42e", "save_path": "github-repos/coq/mattam82-Coq-misc", "path": "github-repos/coq/mattam82-Coq-misc/Coq-misc-60bc3cbe72083f4fa1aa759914936e4fa3d6b42e/theories/Numbers/Natural/Abstract/NLcm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7017066410056394}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\n(** Extraction of breadth-first numbering algorithm from Coq to Ocaml \n\n       see http://okasaki.blogspot.com/2008/07/breadth-first-numbering-algorithm-in.html\n       and https://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/jfp95queue.pdf\n       and https://www.cs.cmu.edu/~rwh/theses/okasaki.pdf\n       and https://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/icfp00bfn.pdf\n\n*)\n\nRequire Import List Arith Omega Extraction.\nRequire Import list_utils wf_utils bt bft bft_spec fifo.\n\nSet Implicit Arguments.\n\nSection seq_an.\n\n  (* seq_an a n = [a;a+1;...;a+(n-1)] *)\n\n  Fixpoint seq_an a n : list nat :=\n    match n with\n      | 0    => nil\n      | S n  => a::seq_an (S a) n\n    end.\n\n  Fact seq_an_length a n : length (seq_an a n) = n.\n  Proof. revert a; induction n; simpl; intros; f_equal; auto. Qed.\n\n  Fact seq_an_spec a n x : In x (seq_an a n) <-> a <= x < a+n.\n  Proof. \n    revert x a; induction n as [ | n IHn ]; intros x a; simpl;\n      [ | rewrite IHn ]; omega.\n  Qed.\n\n  Fixpoint is_seq_from n (l : list nat) { struct l }: Prop :=\n    match l with  \n      | nil  => True\n      | x::l => n = x /\\ is_seq_from (S n) l\n    end.\n\n  Theorem is_seq_from_spec a l : is_seq_from a l <-> exists n, l = seq_an a n.\n  Proof.\n    revert a; induction l as [ | x l IH ]; intros a; simpl.\n    + split; auto; exists 0; auto.\n    + rewrite IH; split.\n      * intros (? & n & Hn); subst x; exists (S n); subst; auto.\n      * intros ([ | n ] & ?); subst; try discriminate.\n        simpl in H; inversion H; subst; split; auto.\n        exists n; auto.\n  Qed.\n\nEnd seq_an.\n\nSection bfn.\n\n  Let fifo_3q_sum { X } (q : fifo_3q (bt X)) := lsum (fifo_3q_list q). \n\n  Variable (X : Type).\n\n  Notation fX := (fifo_3q (bt X)). \n  Notation fN := (fifo_3q (bt nat)).\n\n  (* the forest (list of bt nat) is a breadth first numbering from n if\n     its breadth first traversal yields [n;n+1;....;m[ for some m\n   *)\n\n  Let fX_spec := fifo_3q_spec (bt X).\n  Let fN_spec := fifo_3q_spec (bt nat).\n\n  Definition is_bfn_from n l := is_seq_from n (bft_f l).\n\n  (* Breath First Numbering: maps a forest X to a forest nat such that\n          1) the two forests are of the same shape\n          2) the result is a breadth first numbering from n\n\n     Beware that the output is a reversed queue compared to the input\n   *)\n\n  Definition bfn_3q_f n (p : fX) : { q : fN | fifo_3q_list p ~lt rev (fifo_3q_list q) /\\ is_bfn_from n (rev (fifo_3q_list q)) }.\n  Proof.\n    induction on n p as bfn_3q_f with measure (fifo_3q_sum p).\n    refine (match fifo_3q_void p as b return fifo_3q_void p = b -> _ with\n      | true  => fun H1 => exist _ fifo_3q_nil _\n      | false => fun H1 => _\n    end eq_refl).\n    { apply fifo_3q_void_spec in H1.\n      rewrite H1, fifo_3q_nil_spec; split; simpl; auto.\n      red; rewrite bft_f_fix_0; simpl; auto. }\n    assert (fifo_3q_list p <> nil) as H2.\n    { intro E; apply fifo_3q_void_spec in E; rewrite E in H1; discriminate. }\n    refine (match fifo_3q_deq p H2 as k return fifo_3q_deq p H2 = k -> _ with\n      | (leaf x ,p') => _\n      | (node a x b, p') => _\n    end eq_refl); intros H3.\n    + generalize (fifo_3q_deq_spec _ H2); rewrite H3; intros H4.\n      refine (let (q,Hq) := bfn_3q_f (S n) p' _ in exist _ (fifo_3q_enq q (leaf n)) _).\n      { unfold fifo_3q_sum; rewrite H4; simpl; omega. }\n      destruct Hq as (H5 & H6).\n      rewrite H4, fifo_3q_enq_spec.\n      subst; split; auto.\n      rewrite rev_app_distr; simpl; auto.\n      rewrite rev_app_distr; simpl; red.\n      rewrite bft_f_fix_3; simpl; rewrite <- app_nil_end; auto.\n    + generalize (fifo_3q_deq_spec _ H2); rewrite H3; intros H4.\n      refine (let (q,Hq) := bfn_3q_f (S n) (fifo_3q_enq (fifo_3q_enq p' a) b) _ in _).\n      { unfold fifo_3q_sum. \n        rewrite fifo_3q_enq_spec, fifo_3q_enq_spec, app_ass; simpl.\n        rewrite lsum_app, H4; simpl; omega. }\n      destruct Hq as (H5 & H6).\n      rewrite fifo_3q_enq_spec, fifo_3q_enq_spec, app_ass in H5; simpl in H5.\n      assert (2 <= length (fifo_3q_list q)) as H7.\n      { apply Forall2_length in H5.\n        rewrite app_length, rev_length in H5.\n        simpl in H5; omega. }\n      assert (fifo_3q_list q <> nil) as H8.\n      { revert H7; destruct (fifo_3q_list q); simpl; try discriminate; intro; omega. } \n      generalize (fifo_3q_deq_spec _ H8).\n      refine (match fifo_3q_deq _ H8 with (u,q') => _ end); intros H9.\n      assert (fifo_3q_list q' <> nil) as H10.\n      { revert H7; rewrite H9; destruct (fifo_3q_list q'); simpl; try discriminate; intro; omega. }\n      generalize (fifo_3q_deq_spec _ H10).\n      refine (match fifo_3q_deq _ H10 with (v,q'') => _ end); intros H11.\n      exists (fifo_3q_enq q'' (node v n u)).\n      rewrite H4, fifo_3q_enq_spec, rev_app_distr; simpl.\n      rewrite H9, H11 in H5; simpl in H5; rewrite app_ass in H5; simpl in H5.\n      rewrite H9, H11 in H6; simpl in H6; rewrite app_ass in H6; simpl in H6.\n      unfold is_bfn_from in H6 |- *.\n      apply Forall2_2snoc_inv in H5.\n      destruct H5 as (G1 & G2 & H5).\n      rewrite bft_f_fix_3; simpl; split; auto.\n  Defined.\n\n  Section bfn.\n\n    Let bfn_3q_full (t : bt X) : { t' | t ~t t' /\\ is_seq_from 0 (bft_std t') }.\n    Proof.\n      refine (match @bfn_3q_f 0 (fifo_3q_enq fifo_3q_nil t) with exist _ q Hq => _ end).\n      rewrite fifo_3q_enq_spec, fifo_3q_nil_spec in Hq; simpl in Hq.\n      destruct Hq as (H1 & H2).\n      assert (fifo_3q_list q <> nil) as H3.\n      { apply Forall2_length in H1; rewrite rev_length in H1.\n        destruct (fifo_3q_list q); discriminate. }\n      generalize (fifo_3q_deq_spec _ H3).\n      refine (match fifo_3q_deq _ H3 with (x,q') => _ end); intros H4.\n      exists x.\n      rewrite <- bft_std_eq_bft.\n      rewrite H4 in H1; simpl in H1.\n      apply Forall2_snoc_inv with (l := nil) in H1.\n      destruct H1 as (G1 & H1).\n      apply Forall2_nil_inv_right in H1.\n      apply f_equal with (f := @rev _) in H1.\n      rewrite rev_involutive in H1; simpl in H1.\n      rewrite H4, H1 in H2; simpl in H2.\n      auto.\n    Qed.\n\n    Definition bfn_3q t := proj1_sig (bfn_3q_full t).\n\n    Fact bfn_3q_spec_1 t : t ~t bfn_3q t.\n    Proof. apply (proj2_sig (bfn_3q_full t)). Qed.\n\n    Fact bfn_3q_spec_2 t : exists n, bft_std (bfn_3q t) = seq_an 0 n.\n    Proof. apply is_seq_from_spec, (proj2_sig (bfn_3q_full t)). Qed.\n\n    Corollary bfn_3q_spec_3 t : bft_std (bfn_3q t) = seq_an 0 (m_bt t).\n    Proof.\n      destruct (bfn_3q_spec_2 t) as (n & Hn).\n      rewrite Hn.\n      apply f_equal with (f := @length _) in Hn.\n      rewrite seq_an_length, bft_std_length in Hn.\n      generalize (bfn_3q_spec_1 t); intros E.\n      apply bt_eq_m in E.\n      rewrite <- Hn, <- E; trivial.\n    Qed.\n\n  End bfn.\n\nEnd bfn.\n\n(* Notice that fifo_3q_deq is extracted to a function that loops forever\n   if the input is the empty queue, ie does not following the spec *)\n\nExtract Inductive bool => \"bool\" [ \"true\" \"false\" ].\nExtract Inductive prod => \"(*)\"  [ \"(,)\" ].\nExtract Inductive list => \"list\" [ \"[]\" \"(::)\" ].\nExtract Inductive nat => int [ \"0\" \"succ\" ] \"(fun fO fS n -> if n=0 then fO () else fS (n-1))\".\n\nRecursive Extraction bfn_3q.\n\nCheck bfn_3q.\nCheck bfn_3q_spec_1.\nCheck bfn_3q_spec_2.\nCheck bfn_3q_spec_3.\n             \n\n", "meta": {"author": "DmxLarchey", "repo": "Breadth-First-Numbering", "sha": "7f0fa3561968bef7f927d6bae4b1da6a67236762", "save_path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering", "path": "github-repos/coq/DmxLarchey-Breadth-First-Numbering/Breadth-First-Numbering-7f0fa3561968bef7f927d6bae4b1da6a67236762/bfn_fifo_3q.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7016072233461957}}
{"text": "Require Import Bool Arith List Cpdt.CpdtTactics.\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nDefinition left_two : nat + nat := inl _ 2.\nPrint left_two.\n\nDefinition left_two' := inl nat 2.\nPrint left_two'.\n\nContext (A B C : Type).\n\nDefinition compose : (A -> B) -> (B -> C) -> (A -> C)\n  := fun f g => (fun x => g (f x)).\n\n\nDefinition addtwo_or_subtractone : nat + nat -> nat\n  := fun x_or_y => match x_or_y with\n                     | inl x => x + 2\n                     | inr y => y - 1\n                   end.\n\nEval simpl in (addtwo_or_subtractone (inl _ 5)).\n\nDefinition swap : (A * B) -> (B * A) :=\n  fun f => match f with\n  | (x, y) => (y, x)\n  end.\n\nDefinition mutate3 :=\n  fun x y z => x * z + y.\n\nDefinition mutate3' x := mutate3 x 5 2.\n\nCheck (fun _ : False => I).\n\nTheorem unit_singleton : forall x : unit, x = tt.\n  induction x.\n  reflexivity.\nQed.\n\nCheck unit_ind.\n\nInductive Empty_set : Set := .\n\nTheorem empty_set_is_empty : forall x : Empty_set, 2 + 2 = 5.\n  destruct 1.\nQed.\n\nInductive bool : Set :=\n| true\n| false.\n\nDefinition negb (b: bool) : bool :=\n  match b with\n  | true => false\n  | false => true\nend.\n\nTheorem neg_negb : forall b : bool, negb (negb b) = b.\n  destruct b; reflexivity.\nQed.\n\nFixpoint plus (m n : nat) : nat :=\n  match m with\n  | O => n\n  | S n' => S (plus n' n)\n  end.\n\nTheorem n_plus_O : forall n : nat, plus n O = n.\n  induction n.\n  reflexivity.\n  induction n; crush.\nQed.\n\nCheck nat_ind.\n\nInductive nat_list : Set :=\n| NNil : nat_list\n| NCons : nat -> nat_list -> nat_list.\n\nFixpoint nlength (ls : nat_list) : nat :=\n  match ls with\n  | NNil => O\n  | NCons _ ls' => S (nlength ls')\n  end.\n\nFixpoint napp (ls1 ls2 : nat_list) : nat_list :=\n  match ls1 with\n  | NNil => ls2\n  | NCons n ls1' => NCons n (napp ls1' ls2)\n  end.\n\nTheorem nlength_napp :\n  forall ls1 ls2 : nat_list, nlength (napp ls1 ls2)\n                             = plus (nlength ls1) (nlength ls2).\n  induction ls1; crush.\nQed.\n\nCheck nat_list_ind.\n\nInductive nat_btree : Set :=\n| NLeaf : nat_btree\n| NNode : nat_btree -> nat -> nat_btree -> nat_btree.\n\nFixpoint nsize (tr : nat_btree) : nat :=\n  match tr with\n  | NLeaf => S O\n  | NNode trl _ trr => plus (nsize trl) (nsize trr)\n  end.\n\nFixpoint nsplice (tr1 tr2 : nat_btree) : nat_btree :=\n  match tr1 with\n  | NLeaf => NNode tr2 O NLeaf\n  | NNode tr1' n tr2' => NNode (nsplice tr1' tr2) n tr2'\n  end.\n\nTheorem plus_assoc : forall n1 n2 n3 : nat,\n    plus (plus n1 n2) n3 = plus n1 (plus n2 n3).\n  induction n1; crush.\nQed.\n\nHint Rewrite n_plus_O plus_assoc.\n\nTheorem nsize_nsplice :\n  forall tr1 tr2 : nat_btree, nsize (nsplice tr1 tr2)\n                              = plus (nsize tr2) (nsize tr1).\n  induction tr1; crush.\nQed.\n\nCheck nat_btree_ind.\n\nInductive list (T : Set) : Set :=\n| Nil : list T\n| Cons : T -> list T -> list T.\n\nFixpoint length T (ls : list T) : nat :=\n  match ls with\n  | Nil => O\n  | Cons _ ls' => S (length ls')\n  end.\n\nFixpoint app T (ls1 ls2 : list T) : list T :=\n  match ls1 with\n  | Nil => ls2\n  | Cons x ls1' => Cons x (app ls1' ls2)\n  end.\n\nTheorem length_app : forall T (ls1 ls2 : list T),\n    length (app ls1 ls2) = plus (length ls1) (length ls2).\n  induction ls1; crush.\nQed.\n\nPrint list.\n\nInductive even_list : Set :=\n| ENil : even_list\n| ECons : nat -> odd_list -> even_list\nwith odd_list : Set :=\n     | OCons : nat -> even_list -> odd_list.\n\nFixpoint elength (el : even_list) : nat :=\n  match el with\n  | ENil => O\n  | ECons _ ol => S (olength ol)\n  end\n\nwith olength (ol : odd_list) : nat :=\n       match ol with\n       | OCons _ el => S (elength el)\n       end.\n\nFixpoint eapp (el1 el2 : even_list) : even_list :=\n  match el1 with\n  | ENil => el2\n  | ECons n ol => ECons n (oapp ol el2)\n  end\n\nwith oapp (ol : odd_list) (el : even_list) : odd_list :=\n       match ol with\n       | OCons n el' => OCons n (eapp el' el)\n       end.\n\nTheorem elength_eapp : forall el1 el2 : even_list,\n    elength (eapp el1 el2) = plus (elength el1) (elength el2).\n  induction el1; crush.\nAbort.\n\nCheck even_list_ind.\n", "meta": {"author": "artagnon", "repo": "proofsauce", "sha": "9465e197d95c1dfb22ff8f52bd74e66b0ce2f48e", "save_path": "github-repos/coq/artagnon-proofsauce", "path": "github-repos/coq/artagnon-proofsauce/proofsauce-9465e197d95c1dfb22ff8f52bd74e66b0ce2f48e/theories/cpdt/cpdt02.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7016072131603285}}
{"text": "Require Import List.\n\nDefinition two_first {A:Type}(l:list A) : list A :=\n match l with a :: b :: l' => a :: b :: nil\n            | _ => nil\n end.\n\n(** Tests :\n\n\nCompute two_first  (true::false::true::nil).\n\nCompute  two_first  (6 * 6::nil).\n*)\n\n\nFixpoint firsts {A:Type}(n:nat)(l:list A){struct n}: list A :=\n   match n,l  with\n   | 0, l' => nil\n   | S n', nil => nil\n   | S n', a::l' => a::firsts  n' l'\n  end.\n\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch6_inductive_data/SRC/twofirst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7015839038612179}}
{"text": "(** 116297 - Tópicos Avançados em Computadores - 2017/2           **)\n(** Provas Formais: Uma Introdução à Teoria de Tipos - Turma B    **)\n(** Prof. Flávio L. C. de Moura                                   **)\n(** Email: contato@flaviomoura.mat.br                             **)\n(** Homepage: http://flaviomoura.mat.br                           **)\n\n(** Aluno:  Gabriel F P Araujo                                    **)\n(** Matrícula: 12/0050943                                         **)\n\n(** Atividade: Formalizar um algoritmo ordenação de sua preferência. *)\n\n(** Esta atividade pode ser realizada individualmente ou em dupla. *)\n\n(** Algumas dicas:\n    1. Utilize a biblioteca Arith do Coq. Com isto você terá diversas propriedades sobre os números naturais, e listas de números naturais para utilizar. *)\n\n(** Bubble Sort **)\n\nRequire Import Arith.\nRequire Import Nat.\nRequire Import Peano.\nRequire Import Recdef.\nRequire Import Coq.Lists.SetoidList.\nRequire Import Coq.Sorting.Sorting.\nRequire Import Coq.Structures.OrderedType.\n\nPrint list.\nPrint pair.\n\n\nFunction borb(l: list nat) {measure length l}: list nat :=\n  match l with\n  | nil => nil\n  | cons h tl => \n    match tl with\n    | nil => cons h nil\n    | cons h' tl' => \n      match (le_lt_dec h h') with\n      | left _ => cons h (borb tl)\n      | right _ => cons h' (borb (cons h tl'))\n      end\n    end\n  end.\nProof.\n - intros; subst.\n   simpl.\n   apply Nat.lt_succ_diag_r.\n - intros.\n   simpl.\n   auto.\nDefined.\n\nPrint le_lt_dec.\n\nFunction borb_once(n:nat) (l: list nat) {measure length l}: list nat :=\n  match l with\n  | nil => (cons n nil)\n  | cons h tl => \n    match (le_lt_dec n h) with\n    | left _ _ => cons n (cons h tl)\n    | right _ _ => cons h (cons n tl)\n    end\n  end.\n\nPrint borb_F.\nPrint borb_ind.\nPrint borb_rec.\nPrint borb_tcc.\nCheck borb_equation.\n\nFixpoint num_oc (n:nat) (l:list nat) : nat :=\n  match l with\n    | nil => 0\n    | cons h tl =>\n      match le_lt_dec n h with\n        | left _ _ => S (num_oc n tl)\n        | right _ _ => num_oc n tl\n      end\n  end.\n\nDefinition equiv l l' := forall n, num_oc n l = num_oc n l'.\n\nLemma Sorted_sub: forall l n, Sorted le (cons n l) -> Sorted le l.\nProof.\n  intros.\n  induction l.\n  - apply Sorted_nil.\n  - inversion H; subst.\n    assumption.\nQed.\n\nLemma le_nm_falso: forall n m, (~ (n <= m)) -> (m < n).\nProof.\n  induction n.\n    - intros m H.\n      assert (le 0 m).\n      { apply (le_0_n). }\n      apply False_ind.\n      apply H; assumption.\n    - intro m. case m.\n      + intro H.\n        apply le_n_S.\n        apply le_0_n.\n      + intros n' Hfalso.\n        apply lt_n_S.\n        apply IHn.\n        intro Hle.\n        apply Hfalso.\n        apply le_n_S.\n        assumption.\nQed.\n\nLemma Sorted_l_once: forall n l, Sorted le (n :: l) -> ((n :: l) = (borb_once n l)).\nProof.\n  induction l.\n  - intro H.\n    reflexivity.\n  - intro H.\n    rewrite borb_once_equation.\n    destruct (le_lt_dec n a).\n    + reflexivity.\n    + inversion H; subst.\n      inversion H3; subst.\n      assert ((~ (n <= a))).\n      { apply lt_not_le. assumption. }\n      contradiction.\nQed.\n\nLemma Sorted_l: forall l, Sorted le (l) -> (l = (borb l)).\nProof.\n  induction l.\n  - intro H.\n    reflexivity.\n  - intro H.\n    rewrite borb_equation.\n    destruct (l).\n    + reflexivity.\n    + destruct (le_lt_dec a n).\n      * rewrite <- IHl.\n        reflexivity.\n        inversion H; subst.\n        assumption.\n      * inversion H; subst.\n        inversion H3; subst.\n        assert ((~ (a <= n))).\n        { apply lt_not_le. assumption. }\n        contradiction.\nQed.\n\nLemma Sorted_n_l_once: forall h tl, Sorted le (h :: tl) -> ((h :: tl) = borb_once h  tl).\nProof.\n  intros.\n  functional induction (borb_once h  tl).\n  - reflexivity.\n  - reflexivity.\n  - inversion H; subst.\n    inversion H3; subst.\n    assert ((~ (h <= h0))).\n    { apply lt_not_le. assumption. }\n    contradiction.\nQed.\n\n\nLemma Sorted_n_l: forall h tl, Sorted le (h :: tl) -> ((h :: tl) = borb (h :: tl)).\nProof.\n  intros h tl H.\n  functional induction (borb (tl)).\n  - reflexivity.\n  - rewrite borb_equation.\n    destruct (le_lt_dec h h0).\n    + reflexivity.\n    + inversion H; subst.\n      inversion H3; subst.\n      assert ((~ (h <= h0))).\n      { apply lt_not_le. assumption. }\n      contradiction.\n  - rewrite <- Sorted_l.\n    + reflexivity.\n    + assumption.\n  - rewrite <- Sorted_l.\n    + reflexivity.\n    + assumption.\nQed.\n\n(**deveria ser <->**)\n(*functional induction (brob l).*)\nLemma borb_preserva_ordem : forall l: list nat, Sorted le l -> Sorted le (borb l).\nProof.\n  induction l.\n  - intro.\n    rewrite borb_equation.\n    apply Sorted_nil.\n  - intro.\n    rewrite <- Sorted_n_l.\n    + assumption.\n    + assumption.\nQed.\n\nLemma num_oc_borb: forall l n, num_oc n (l) = num_oc n (borb (l)).\nProof.\n  intros l n.\n  functional induction (borb l).\n  - reflexivity.\n  - reflexivity.\n  - simpl num_oc.\n    case (le_lt_dec n h).\n    + intro nh.\n      case (le_lt_dec n h').\n      * intro nh'.\n        rewrite <- IHl0.\n        simpl num_oc.\n        destruct (le_lt_dec n h').\n        **tauto.\n        **assert ((~ (n <= h'))).\n          { apply lt_not_le. assumption. }\n          contradiction.\n      * intro h'n.\n        rewrite <- IHl0.\n        simpl num_oc.\n        destruct (le_lt_dec n h').\n        **assert ((~ (n <= h'))).\n          { apply lt_not_le. assumption. }\n          contradiction.\n        **auto.\n    + intro.\n      destruct (le_lt_dec n h').\n      * rewrite <- IHl0.\n        simpl num_oc.\n        destruct (le_lt_dec n h').\n        **reflexivity.\n        **assert ((~ (n <= h'))).\n          { apply lt_not_le. assumption. }\n          contradiction.\n      * rewrite <- IHl0.\n        simpl num_oc.\n        destruct (le_lt_dec n h').\n        **assert ((~ (n <= h'))).\n          { apply lt_not_le. assumption. }\n          contradiction.\n        **reflexivity.\n  - simpl num_oc.\n    case (le_lt_dec n h).\n    + intro nh.\n      case (le_lt_dec n h').\n      * intro nh'.\n        rewrite <- IHl0.\n        simpl num_oc.\n        destruct (le_lt_dec n h).\n        **reflexivity.\n        **assert ((~ (n <= h))).\n          { apply lt_not_le. assumption. }\n          contradiction.\n      * intro h'n.\n        rewrite <- IHl0.\n        simpl num_oc.\n        destruct (le_lt_dec n h).\n        **reflexivity.\n        **assert ((~ (n <= h))).\n          { apply lt_not_le. assumption. }\n          contradiction.\n    + intro hn.\n      case (le_lt_dec n h').\n      * intro nh'.\n        rewrite <- IHl0.\n        simpl num_oc.\n        destruct (le_lt_dec n h).\n        **assert ((~ (n <= h))).\n          { apply lt_not_le. assumption. }\n          contradiction.\n        **reflexivity.\n      * intro h'n.\n        rewrite <- IHl0.\n        simpl num_oc.\n        destruct (le_lt_dec n h).\n        **assert ((~ (n <= h))).\n          { apply lt_not_le. assumption. }\n          contradiction.\n        **reflexivity.\nQed.\n\nLemma num_oc_borb_once_seq: forall l n n', (num_oc n (borb_once n' l)) =  (num_oc n (n' :: l)).\nProof.\n  induction l.\n  - intros n n'.\n    rewrite borb_once_equation.\n    reflexivity.\n  - intros n n'.\n    rewrite borb_once_equation.\n    case (le_lt_dec n' a).\n    + intro H.\n      reflexivity.\n    + intro H.\n      apply lt_not_le in H.\n      simpl.\n      case (le_lt_dec n a).\n      * intro H'.\n        case (le_lt_dec n n').\n        ** intro Hle.\n           reflexivity.\n        ** intro Hlt.\n           reflexivity.\n      * intro H'.\n        case (le_lt_dec n n').\n        ** intro Hle.\n           reflexivity.\n        ** intro Hlt.\n           reflexivity.\nQed.\n\nLemma num_oc_borb_seq: forall l n, (num_oc n (borb l)) =  (num_oc n l).\nProof.\n  induction l.\n  - intros n.\n    rewrite borb_equation.\n    reflexivity.\n  - intros n.\n    rewrite <- num_oc_borb.\n    reflexivity.\nQed.\n\nLemma borb_sorts: forall l a, Sorted le (borb l) -> Sorted le (borb (a :: l)).\nProof.\n  intros l a.\n  intro H.\n  functional induction (borb (l)).\nAdmitted.\n\n(**\n    2. Utilize a formalização do algoritmo de ordenação por inserção desenvolvida em sala como parâmetro. *)\n    \n\nTheorem correcao: forall l, (equiv l (borb l)) /\\ Sorted le (borb l).\nProof.\n  (* induction l. *)\n  intro l.\n  functional induction (borb l).\n  - split.\n    * unfold equiv.\n      intro n.\n      reflexivity.\n    * apply Sorted_nil. \n  - split.\n    * unfold equiv.\n      intro n.\n      rewrite -> num_oc_borb.\n      reflexivity.\n    * apply Sorted_cons.\n      ** apply Sorted_nil.\n      ** apply HdRel_nil.\n  - unfold equiv in *.\n    remember (h' :: tl') as l eqn: H.\n    split.\n    + intro n.\n      destruct IHl0 as [Hequiv Hord].\n      simpl num_oc.\n      destruct (le_lt_dec n h).\n      * rewrite <- num_oc_borb.\n        reflexivity.\n      * rewrite <- num_oc_borb.\n        reflexivity.\n    + destruct IHl0 as [Hequiv Hord].\n      apply Sorted_cons.\n      * assumption.\n      * inversion Hord.\n        ** apply HdRel_nil.\n        ** \n  - split.\n    * unfold equiv.\n      intro n.\n      destruct IHl0 as [Hequiv Hord].\n      simpl num_oc.\n      destruct (le_lt_dec n h).\n      ** destruct (le_lt_dec n h').\n         *** rewrite <- num_oc_borb.\n             simpl num_oc.\n             destruct (le_lt_dec n h).\n             **** reflexivity.\n             **** assert ((~ (n <= h))).\n                  { apply lt_not_le. assumption. }\n                  contradiction.\n         *** rewrite <- num_oc_borb.\n             simpl num_oc.\n             destruct (le_lt_dec n h).\n             **** reflexivity.\n             **** assert ((~ (n <= h))).\n                  { apply lt_not_le. assumption. }\n                  contradiction.\n      ** destruct (le_lt_dec n h').\n         *** rewrite <- num_oc_borb.\n             simpl num_oc.\n             destruct (le_lt_dec n h).\n             **** assert ((~ (n <= h))).\n                  { apply lt_not_le. assumption. }\n                  contradiction.\n             **** reflexivity.\n         *** rewrite <- num_oc_borb.\n             simpl num_oc.\n             destruct (le_lt_dec n h).\n             **** assert ((~ (n <= h))).\n                  { apply lt_not_le. assumption. }\n                  contradiction.\n             **** reflexivity.\n    * destruct IHl0 as [Hequiv Hord].\n      inversion Hord; subst.\n      ** apply Sorted_cons.\n         *** apply Sorted_nil.\n         *** apply HdRel_nil.\n      ** apply Sorted_cons.\n         *** auto.\n         *** apply HdRel_cons.\n             admit.\nAdmitted.\n\nTheorem correcao_comp: forall (l:list nat), {l' | equiv l l' /\\ Sorted le l'}.\nProof.\n  intro l.\n  exists (borb l).\n  apply correcao.\nQed.\n", "meta": {"author": "Gastd", "repo": "fptt", "sha": "999472e6b0df8652a299f271f1676c8c0dc78256", "save_path": "github-repos/coq/Gastd-fptt", "path": "github-repos/coq/Gastd-fptt/fptt-999472e6b0df8652a299f271f1676c8c0dc78256/algoritmo20172.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7015838901018306}}
{"text": "(* begin snippet membersDef:: no-out *)\nRequire Import primRec cPair Arith.\nFrom Equations Require Import  Equations.\n\nEquations members (a:nat): list nat by wf a:=\n  members 0 := List.nil;\n  members (S z) := cPairPi1 z:: members (cPairPi2 z).\n(* end snippet membersDef *)\nNext Obligation.\n  apply Nat.le_lt_trans with z.\n  apply cPairLe2A.\n  apply le_n.\nDefined.\n\nLemma membersOk n : n = codeList (members n).\nProof.\n     pattern n, (members n); apply members_elim. \n      -  reflexivity. \n      -  intros; simpl; f_equal; rewrite <- H. \n         now rewrite cPairProjections.\nQed. \n\nLemma membersOk' l : l = members (codeList l).\nProof.\n  induction l. \n  - reflexivity.\n   - cbn; rewrite IHl. \n     rewrite members_equation_2. \n     now rewrite cPairProjections1, cPairProjections2, <- !IHl.\nQed. \n\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/solutions_exercises/OnCodeList.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7015838852531109}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) : natural := mult lf2 lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_commut_90_mult_zero/goal33conj14_coqofml_T6WuXX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7015235464781795}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf3 : natural) (z : natural) : natural := plus z lf3.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj146_coqofml_LU4kHW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7015235375010594}}
{"text": "(* TPPmark 2017 DP version by Mitsuharu Yamamoto *)\nFrom mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection DynamicProgramming.\n\nVariables X Y Z : Type.\n\nVariable z00 : Z.\nVariable zc0 : X -> seq X -> Z -> Z.\nVariable z0c : Y -> seq Y -> Z -> Z.\nVariable zcc : X -> seq X -> Y -> seq Y -> Z -> Z -> Z -> Z.\n\nFixpoint dp0t t :=\n  if t is y :: t' then let: (z, zs) := dp0t t' in (z0c y t' z, z :: zs)\n  else (z00, [::]).\n\nFixpoint dpt x s t zs :=\n  match t, zs with\n  | y :: t', (z, z' :: zs') => let: (zy, zt') := dpt x s t' (z', zs') in\n                               (zcc x s y t' z' z zy, zy :: zt')\n  | _, (z, _) => (zc0 x s z, [::])\n  end.\n\nFixpoint dps s t := if s is x :: s' then dpt x s' t (dps s' t) else dp0t t.\n\nDefinition dp s t := (dps s t).1.\n\nLemma dp00 : dp [::] [::] = z00.\nProof.  by [].  Qed.\n\nLemma dp0c y t : dp [::] (y :: t) = z0c y t (dp [::] t).\nProof.  by rewrite /dp /=; case: dp0t.  Qed.\n\nLemma dpc0 x s : dp (x :: s) [::] = zc0 x s (dp s [::]).\nProof.\n  by rewrite /dp; elim: s => [| x' s ->] //= in x *; case: dps => ? [| ? ?].\nQed.\n\nLemma dpscc x y s t :\n  dps (x :: s) (y :: t) = (zcc x s y t (dp s t) (dp s (y :: t)) (dp (x :: s) t),\n                           dp (x :: s) t :: (dps (x :: s) t).2).\nProof.\n  rewrite /dp; elim: s => /= [| x' s ->] in x *.\n  - by case: dp0t => ? [| ? ?]; case: dpt.\n  - by rewrite -surjective_pairing; case: dpt.\nQed.\n\nLemma dpcc x y s t :\n  dp (x :: s) (y :: t) = zcc x s y t (dp s t) (dp s (y :: t)) (dp (x :: s) t).\nProof.  by rewrite /dp dpscc.  Qed.\n\nEnd DynamicProgramming.\n\nSection LongestCommonSubsequence.\n\nDefinition argmax (X : Type) f (x y : X) := if f x < f y then y else x.\n\nLemma argmax_maxn (X : Type) f (x y : X) : f (argmax f x y) = maxn (f x) (f y).\nProof.  by rewrite /argmax fun_if.  Qed.\n\nVariable T : eqType.\n\nDefinition LCS : seq T -> seq T -> seq T :=\n  dp [::] (fun _ _ _ => [::]) (fun _ _ _ => [::])\n     (fun x _ y _ st syt xst =>\n        if x == y then x :: st else argmax size syt xst).\n\nLemma lcs_nil_l s : LCS [::] s = [::].\nProof.  by rewrite /LCS; case: s => [| ? ?]; rewrite ?dp00 ?dp0c.  Qed.\n\nLemma lcs_nil_r s : LCS s [::] = [::].\nProof.  by rewrite /LCS; case: s => [| ? ?]; rewrite ?dp00 ?dpc0.  Qed.\n\nLemma lcs_cons x s y t :\n  LCS (x :: s) (y :: t) = if x == y then x :: LCS s t\n                          else argmax size (LCS s (y :: t)) (LCS (x :: s) t).\nProof.  by rewrite /LCS dpcc.  Qed.\n\n(* Alternatively,\nFixpoint LCS2 x us t : seq (seq T) :=\n  if t is y :: t' then let p := LCS2 x (behead us) t' in\n                         (if x == y then x :: head [::] (behead us)\n                          else argmax size (head [::] us) (head [::] p)) :: p\n  else [::].\n\nFixpoint LCS1 s t : seq (seq T) :=\n  if s is x :: s' then LCS2 x (LCS1 s' t) t else [::].\n\nDefinition LCS s t := head [::] (LCS1 s t).\n\nLemma lcs_nil_l s : LCS [::] s = [::].\nProof.  by [].  Qed.\n\nLemma lcs_nil_r s : LCS s [::] = [::].\nProof.  by rewrite /LCS; case: s => [| x s] //=; case: LCS1.  Qed.\n\nLemma lcs_cons_aux x s y t :\n  LCS1 (x :: s) (y :: t) = (if x == y then x :: (LCS s t)\n                            else argmax size (LCS s (y :: t)) (LCS (x :: s) t))\n                             :: LCS1 (x :: s) t.\nProof.  by rewrite /LCS; elim: s => [| x' s /= /(_ x') [-> ->]] // in x *.  Qed.\n\nLemma lcs_cons x s y t :\n  LCS (x :: s) (y :: t) = if x == y then x :: LCS s t\n                          else argmax size (LCS s (y :: t)) (LCS (x :: s) t).\nProof.  by rewrite /LCS lcs_cons_aux.  Qed.\n*)\n\nLemma lcs_subseq s t : subseq (LCS s t) s /\\ subseq (LCS s t) t.\nProof.\n  elim: s => [| x s IHs] in t *; first by rewrite lcs_nil_l !sub0seq.\n  elim: t => [| y t [IHts IHtt]]; first by rewrite lcs_nil_r sub0seq.\n  rewrite lcs_cons; case: ifP => [/eqP -> | Hxy]; first by rewrite /= eqxx.\n  case/IHs: (y :: t) => IHss IHst; rewrite /argmax; split; case: ifP => _ //.\n  - by rewrite (subseq_trans IHss) // subseq_cons.\n  - by rewrite (subseq_trans IHtt) // subseq_cons.\nQed.\n\nLemma lcs_longest s t u : subseq u s -> subseq u t -> size u <= size (LCS s t).\nProof.\n  elim: s => [| x s IHs] in u t *; first by move=> /eqP ->.\n  elim: t => [| y t IHt] in u *; first by move=> _ /eqP ->.\n  case: u => [| z u] //; rewrite lcs_cons; case: ifP => [/eqP <- {y} | Hxy] /=.\n  - by move=> Hs Ht; move: (IHs _ _ Hs Ht); case: ifP => _ // /leqW.\n  - rewrite argmax_maxn leq_max; case: ifP => [/eqP -> | _] Hs.\n    + by rewrite Hxy => Ht; rewrite (IHt (x :: u)) ?orbT //= eqxx.\n    + by move=> Ht; rewrite (IHs (z :: u)).\nQed.\n\nEnd LongestCommonSubsequence.\n\nSection LongestCommonSubsequenceForList.  (* !!! NOT COMPLETED !!! *)\n\nFixpoint argmaxl (X : Type) f (x : X) ys :=\n  if ys is y :: ys' then argmaxl f (if f x < f y then y else x) ys'\n  else x.\n\nLemma argmaxl_sup (X : Type) f (x : X) ys m :\n  (m <= f x) || has (fun y => m <= f y) ys -> m <= f (argmaxl f x ys).\nProof.\n  elim: ys => [| y ys IHys] /= in x *; first by rewrite orbF.\n  move=> H; case: ifP => Hxy.\n  - by apply IHys; case/orP: H => // H; rewrite (ltnW (leq_ltn_trans H Hxy)).\n  - apply IHys; rewrite orbCA in H; case/orP: H => // H.\n    by rewrite (leq_trans H) // leqNgt Hxy.\nQed.\n\nLemma argmaxl_mem (X : eqType) f (x : X) ys :\n  (argmaxl f x ys == x) || (argmaxl f x ys \\in ys).\nProof.\n  elim: ys => [| y ys IHys] in x *; first by rewrite eqxx.\n  rewrite /=; case: ifP => H; first by rewrite inE (IHys y) orbT.\n  move/predU1P: (IHys x) => [-> | H']; first by rewrite eqxx.\n  by rewrite inE H' !orbT.\nQed.\n\nVariable T : eqType.\n\nFixpoint nhead_simpl (X : Type) (d : X) n : iter n seq X -> X :=\n  if n is n'.+1 then\n    fun s => if s is x :: s' then nhead_simpl d x else d\n  else\n    id.\n\nDefinition nhead := nosimpl nhead_simpl.\n\nArguments nhead [X] d n s.\n\nLemma nhead_nil (X : Type) (d : X) n : nhead d n.+1 [::] = d.\nProof.  by [].  Qed.\n\nLemma nhead_cons (X : Type) (d : X) n x s : nhead d n.+1 (x :: s) = nhead d n x.\nProof.  by [].  Qed.\n\nDefinition nheadE := (nhead_nil, nhead_cons).\n\nFixpoint LCSLs s ys diag neighbors : seq (seq T) :=\n  if s is x :: s' then\n    let prev := LCSLs s' ys (omap behead diag) (map behead neighbors) in\n    (if all (pred1 x) ys then x :: head [::] (oapp behead prev diag)\n     else argmaxl size (head [::] prev) (map (head [::]) neighbors)) :: prev\n  else [::].\n\nFixpoint LCSLts_simpl s ts ys :\n  option (iter (size ts).+1 seq (seq T)) -> (* diag *)\n  seq (iter (size ts).+1 seq (seq T)) -> (* neighbors *)\n  iter (size ts).+1 seq (seq T) :=\n  if ts is t :: ts' then\n    fun diag neighbors =>\n      let fix LCSLt t neighbors :=\n          if t is y :: t' then\n            let prev := LCSLt t' (map behead neighbors) in\n            (@LCSLts_simpl s ts' (y :: ys)\n                           (Some (head [::] (oapp behead prev diag)))\n                           (head [::] prev :: map (head [::]) neighbors))\n              :: prev\n          else [::]\n      in LCSLt t neighbors\n  else fun diag neighbors => LCSLs s ys diag neighbors.\n\nDefinition LCSLts := nosimpl LCSLts_simpl.\n\nArguments LCSLts : clear implicits.\n\nLemma LCSLts_nil s ys diag neighbors:\n  LCSLts s [::] ys diag neighbors = LCSLs s ys diag neighbors.\nProof.  by [].  Qed.\n\nLemma LCSLts_cons_nil s ts ys diag neighbors:\n  LCSLts s ([::] :: ts) ys diag neighbors = [::].\nProof.  by [].  Qed.\n\nLemma LCSLts_cons_cons s y t ts ys diag neighbors:\n  LCSLts s ((y :: t) :: ts) ys diag neighbors =\n  let prev := LCSLts s (t :: ts) ys diag (map behead neighbors) in\n  (LCSLts s ts (y :: ys) (Some (head [::] (oapp behead prev diag)))\n          (head [::] prev :: map (head [::]) neighbors)) :: prev.\nProof.  by [].  Qed.\n\nDefinition LCSLtsE := (LCSLts_nil, LCSLts_cons_nil, LCSLts_cons_cons).\n\nDefinition LCSL s ts := nhead [::] _ (LCSLts s ts [::] None [::]).\n\nLemma lcsl_nil_l ts : LCSL [::] ts = [::].\nProof.\n  rewrite /LCSL; move: {3}[::] (Nil (iter (size ts).+1 seq (seq T))) None.\n  by rewrite /nhead /LCSLts; elim: ts => //= t ts IHts; case: t.\nQed.\n\nLemma lcsl_nil_r s ts : [::] \\in ts -> LCSL s ts = [::].\nProof.\n  rewrite /LCSL; move: {3}[::] (Nil (iter (size ts).+1 seq (seq T))) None.\n  rewrite /nhead; elim: ts => //= t ts IHts ys diag neighbors.\n  rewrite inE => /predU1P [<- | Hts] //.\n  by case: t => [| y t] // in diag neighbors *; rewrite IHts.\nQed.\n\nFixpoint nmap (X : Type) n (f : seq X -> seq X) : iter n.+1 seq X -> iter n.+1 seq X :=\n  if n is n'.+1 then map (nmap f) else f.\n\nLemma nmap_behead_nil X n : nmap behead (Nil (iter n seq X)) = [::].\nProof.  by elim: n.  Qed.\n\nLemma nmap_behead_head X n (s : iter n.+2 seq X) :\n  nmap behead (head [::] s) = head [::] (map (nmap behead) s).\nProof.  by case: s => //=; rewrite nmap_behead_nil.  Qed.\n\nLemma lcsl_cons_behead x s ts ys diag neighbors :\n  size ys = size neighbors ->\n  nmap behead (LCSLts (x :: s) ts ys diag neighbors) =\n  LCSLts s ts ys (omap (nmap behead) diag) (map (nmap behead) neighbors).\nProof.\n  elim: ts => [| t ts IHts] in ys diag neighbors *; first by rewrite !LCSLtsE.\n  elim: t => [| y t IHt] // in diag neighbors *.\n  move=> Hsize; move/(_ diag (map behead neighbors)): IHt.\n  rewrite Hsize size_map -map_comp => /(_ erefl) IHt; rewrite /= in IHt.\n  rewrite !LCSLtsE /= IHts //; last by rewrite /= size_map Hsize.\n  congr cons.\n  - congr LCSLts.\n    + case: diag => [d |] /= in IHt *; rewrite nmap_behead_head.\n      * by congr (Some (head _ _)); case: d {IHt}.\n      * congr (Some (head _ _)); rewrite IHt -map_comp.\n        by congr (LCSLts _ (_ :: _)); apply: eq_map => -[].\n    + rewrite /=; congr cons.\n      * rewrite nmap_behead_head IHt -map_comp.\n        by congr (head [::] (LCSLts _ (_ :: _) _ _ _)); apply: eq_map => -[].\n      * by rewrite -!map_comp; apply: eq_map => ?; rewrite /= nmap_behead_head.\n  - by rewrite IHt -map_comp; congr (LCSLts _ (_ :: _)); apply: eq_map => -[].\nQed.\n\nLemma lcsl_cons x s ts :\n  [::] \\notin ts ->\n  LCSL (x :: s) ts =\n  if all (pred1 (Some x)) (map ohead ts) then x :: LCSL s (map behead ts)\n  else argmaxl size (LCSL s ts)\n               (rev [tuple LCSL (x :: s) (set_nth [::] ts i\n                                                  (behead (nth [::] ts i)))\n                    | i < size ts]).\nProof.\nAdmitted.\n\nDefinition LCSL_spec s ts (lcsl : seq T) :=\n  [/\\ subseq lcsl s, all (subseq lcsl) ts &\n      forall u, subseq u s -> all (subseq u) ts -> size u <= size lcsl].\n\nLemma lcsl_correct_nil_l ts : LCSL_spec [::] ts (LCSL [::] ts).\nProof.\n  rewrite lcsl_nil_l; split; first by rewrite sub0seq.\n  - by apply/allP => ?; rewrite sub0seq.\n  - by move=> ?; rewrite subseq0 => /eqP ->.\nQed.\n\nLemma lcsl_correct_nil_r s ts : [::] \\in ts -> LCSL_spec s ts (LCSL s ts).\nProof.\n  move=> Hts; rewrite lcsl_nil_r //; split; first by rewrite sub0seq.\n  - by apply/allP => ?; rewrite sub0seq.\n  - by move=> ? _ /allP /(_ _ Hts); rewrite subseq0 => /eqP ->.\nQed.\n\nLemma lcsl_correct s ts : LCSL_spec s ts (LCSL s ts).\nProof.\n  pose mes (s : seq T) (ts : seq (seq T)) := size s + (\\sum_(t <- ts) size t).\n  elim: {s ts}(mes s ts) {-2}s {-2}ts (leqnn (mes s ts)) => [| n IHn] s ts.\n  - rewrite leqn0 addn_eq0 size_eq0 => /andP [/eqP -> _].\n    exact: lcsl_correct_nil_l.\n  - case: s => [| x s] Hmes; first by apply: lcsl_correct_nil_l.\n    case: (boolP ([::] \\in ts)) => [| Hts]; first by apply: lcsl_correct_nil_r.\n    rewrite lcsl_cons //. case: ifP => Hx.\n    + have /IHn [IH1 IH2 IH3] : mes s [seq behead i | i <- ts] <= n.\n      { move: Hmes; rewrite /mes /= addSn ltnS; apply: leq_trans.\n        rewrite leq_add2l big_map leq_sum // => t.\n        by rewrite size_behead leq_pred. }\n      split; first by rewrite /= eqxx.\n      * apply/allP => t Ht; move/allP/(_ (ohead t)): Hx.\n        rewrite map_f //= => /(_ isT) H; case: t H => // _ t /eqP [] -> in Ht *.\n        by rewrite /= eqxx (allP IH2) // (map_f behead Ht).\n      * { case=> // z u; rewrite [subseq _ _] /=.\n          case: ifP => [/eqP |] Hzx Hus Hzuts.\n          - apply: IH3 => //; apply/allP => _ /mapP [t Ht ->].\n            move/allP/(_ (ohead t)): Hx.\n            rewrite map_f //= => /(_ isT) H; case: t H Ht => // _ t /eqP [] ->.\n            by move/(allP Hzuts); rewrite Hzx /= eqxx.\n          - apply: leqW; apply: IH3 => //; apply/allP => _ /mapP [t Ht ->].\n            move/allP/(_ (ohead t)): Hx.\n            rewrite map_f //= => /(_ isT) H; case: t H Ht => // y t /eqP [] ->.\n            by move/(allP Hzuts); rewrite /= Hzx.\n        }\n    + have /IHn [IHs1 IHs2 IHs3] : mes s ts <= n\n        by move: Hmes; rewrite /mes /= addSn ltnS.\n      have Htsi (i : 'I_(size ts)) :\n        mes (x :: s) (set_nth [::] ts i (behead (nth [::] ts i))) <= n.\n      {\n        move: Hmes; rewrite /mes /= addSn ltnS; apply: leq_trans.\n        rewrite addSn -addnS leq_add2l; set ts' := set_nth _ _ _ _.\n        have Hsize: size ts' = size ts by rewrite size_set_nth; apply/maxn_idPr.\n        have Hts' i0 : i0 != i :> nat -> nth [::] ts' i0 = nth [::] ts i0\n          by move=> Hi0; rewrite nth_set_nth /= (negPf Hi0).\n        rewrite !(big_nth [::]) (@big_cat_nat _ _ _ i.+1) //= Hsize //.\n        rewrite [X in _ < X](@big_cat_nat _ _ _ i.+1) //=.\n        rewrite !big_nat_recr //= -addSn -addnS !big_nat !leq_add //.\n        - apply: eq_leq; apply: eq_bigr => i0 Hi0; rewrite Hts' //.\n          by apply/negP => /eqP Hi0i; rewrite Hi0i ltnn andbF in Hi0.\n        - rewrite nth_set_nth /= eqxx size_behead prednK //.\n          case E: nth => //; case/negP: Hts; rewrite -E; apply/nthP.\n          by exists i.\n        - apply: eq_leq; apply: eq_bigr => i0 Hi0; rewrite Hts' //.\n          by apply/negP => /eqP Hi0i; rewrite Hi0i ltnn in Hi0.\n      }\n      set lts' := rev _; split.\n      * { move/predU1P: (argmaxl_mem size (LCSL s ts) lts') => [-> |].\n          - by rewrite (subseq_trans IHs1) ?subseq_cons.\n          - rewrite /lts' [rev _]/= -!map_rev.\n            by case/mapP => i Hi ->; case/IHn: (Htsi i).\n        }\n      * move/predU1P: (argmaxl_mem size (LCSL s ts) lts') => [-> |] //.\n        rewrite /lts' [rev _]/= -!map_rev.\n        case/mapP => i Hi ->; set ts' := set_nth _ _ _ _; set lt' := LCSL _ _.\n        have Hts' : size ts' = size ts\n          by rewrite size_set_nth; apply: maxn_idPr.\n        apply/allP => _ /(nthP [::]) [j Hj <-].\n        case/IHn: (Htsi i) => _ /allP /(_ (nth [::] ts' j)).\n        rewrite mem_nth ?Hts' // nth_set_nth => /(_ isT) H _.\n        rewrite /= in H; case: ifP H => // /eqP ->; rewrite /lt' /ts'.\n        by case: nth => // y t /subseq_trans -> //; rewrite subseq_cons.\n      * { case=> // z u Hzuxs Hzuts; apply: argmaxl_sup; rewrite /= in Hzuxs.\n          move: Hzuxs; case: ifP => [/eqP {z}-> | Hzx] in Hzuts *.\n          - move=> Hus'; case/allPn: Hx => _ /mapP [t Ht ->].\n            case: t Ht => [/(negP Hts) | y t Hyt] // => Hyx.\n            rewrite /= /eq_op /= in Hyx; case/(nthP [::]): (Hyt) => i Hi Hnthi.\n            apply/orP; right; apply/hasP.\n            exists (nth [::] lts' (rev_ord (Ordinal Hi))).\n            + by rewrite mem_nth // size_rev size_map size_enum_ord.\n            + rewrite /lts' (nth_rev [::]) size_tuple.\n              rewrite -[size _ - _]/(rev_ord _ : nat) rev_ordK nth_mktuple.\n              case/IHn: (Htsi (Ordinal Hi)) => _ _ -> //.\n              * by rewrite /= eqxx.\n              * { apply/allP => t' /(nthP [::]) [j].\n                  rewrite size_set_nth (maxn_idPr Hi) nth_set_nth /= => Hj <-.\n                  case: ifP => [_ | Hij].\n                  - move/allP/(_ (nth [::] ts i)): Hzuts.\n                    by rewrite Hnthi /= eq_sym (negPf Hyx) => ->.\n                  - move/allP/(_ (nth [::] ts j)): Hzuts => -> //.\n                    by rewrite mem_nth.\n                }\n              * by rewrite ltn_ord.\n          - by move/IHs3 => ->.\n        }\nQed.\n\nEnd LongestCommonSubsequenceForList.\n\nEval compute in @LCSLts _ [:: 1; 2; 3; 4; 5] [:: [:: 2; 1; 3; 5] ] [::] None [::].\n     (* = [:: [:: [:: 2; 3; 5]; [:: 2; 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*       [:: [:: 1; 3; 5]; [:: 3; 5];    [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*       [:: [:: 3; 5];    [:: 3; 5];    [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*       [:: [:: 5];       [:: 5];       [:: 5];    [:: 5]; [:: 5]]] *)\n     (* : iter (size [:: [:: 2; 1; 3; 5]]).+1 seq (seq nat_eqType) *)\nEval compute in @LCSLts _ [:: 1; 3; 4; 5] [:: [:: 2; 1; 3; 5] ] [::] None [::].\n     (* = [:: [:: [:: 1; 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*       [:: [:: 1; 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*       [:: [:: 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*       [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]]] *)\n     (* : iter (size [:: [:: 2; 1; 3; 5]]).+1 seq (seq nat_eqType) *)\nEval compute in @LCSLts _ [::] [:: [:: 2; 1; 3; 5] ] [::] None [::].\n     (* = [:: [::]; [::]; [::]; [::]] *)\n     (* : iter (size [:: [:: 2; 1; 3; 5]]).+1 seq (seq nat_eqType) *)\nEval compute in @LCSLts _ [:: 1; 2; 3; 4; 5] [:: [:: 1; 3; 4; 5]; [:: 2; 1; 3; 5] ] [::] None [::].\n     (* = [:: [:: [:: [:: 1; 3; 5]; [:: 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 1; 3; 5]; [:: 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 3; 5]; [:: 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]]; *)\n     (*       [:: [:: [:: 3; 5]; [:: 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 3; 5]; [:: 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 3; 5]; [:: 3; 5]; [:: 3; 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]]; *)\n     (*       [:: [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]]; *)\n     (*       [:: [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]; *)\n     (*           [:: [:: 5]; [:: 5]; [:: 5]; [:: 5]; [:: 5]]]] *)\n     (* : iter (size [:: [:: 1; 3; 4; 5]; [:: 2; 1; 3; 5]]).+1 seq *)\n     (*     (seq nat_eqType) *)\nEval compute in @LCSLts _ [:: 1; 2; 3; 4; 5] [:: [:: 1; 3; 4]; [:: 2; 1; 3; 5] ] [::] None [::].\n     (* = [:: [:: [:: [:: 1; 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*           [:: [:: 1; 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*           [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*           [:: [::]; [::]; [::]; [::]; [::]]]; *)\n     (*       [:: [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*           [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*           [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*           [:: [::]; [::]; [::]; [::]; [::]]]; *)\n     (*       [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*           [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*           [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*           [:: [::]; [::]; [::]; [::]; [::]]]] *)\n     (* : iter (size [:: [:: 1; 3; 4]; [:: 2; 1; 3; 5]]).+1 seq (seq nat_eqType) *)\nEval compute in @LCSLts _ [:: 1; 2; 3; 4; 5] [:: [:: 1; 3; 4; 5]; [:: 2; 1; 3; 5]; [:: 2; 1; 3]] [::] None [::].\n     (* = [:: [:: [:: [:: [:: 1; 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 1; 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]]; *)\n     (*           [:: [:: [:: 1; 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 1; 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]]; *)\n     (*           [:: [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]]; *)\n     (*           [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]]; *)\n     (*       [:: [:: [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]]; *)\n     (*           [:: [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]]; *)\n     (*           [:: [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]; *)\n     (*               [:: [:: 3]; [:: 3]; [:: 3]; [::]; [::]]]; *)\n     (*           [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]]; *)\n     (*       [:: [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]; *)\n     (*           [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]; *)\n     (*           [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]; *)\n     (*           [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]]; *)\n     (*       [:: [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]; *)\n     (*           [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]; *)\n     (*           [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]; *)\n     (*           [:: [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]; *)\n     (*               [:: [::]; [::]; [::]; [::]; [::]]]]] *)\n     (* : iter (size [:: [:: 1; 3; 4; 5]; [:: 2; 1; 3; 5]; [:: 2; 1; 3]]).+1 seq *)\n     (*     (seq nat_eqType) *)\nEval compute in @LCSLts _ [:: 1; 2; 3; 4; 5] [:: [:: 1; 3; 4; 5]; [:: 2; 1; 3; 5]; [::]] [::] None [::].\n     (* = [:: [:: [::]; [::]; [::]; [::]]; [:: [::]; [::]; [::]; [::]]; *)\n     (*       [:: [::]; [::]; [::]; [::]]; [:: [::]; [::]; [::]; [::]]] *)\n     (* : iter (size [:: [:: 1; 3; 4; 5]; [:: 2; 1; 3; 5]; [::]]).+1 seq *)\n     (*     (seq nat_eqType) *)\nEval compute in @LCSLts _ [:: 1; 2; 3; 4; 5] [:: [::]; [:: 1; 3; 4; 5]; [:: 2; 1; 3; 5]] [::] None [::].\n     (* = [::] *)\n     (* : iter (size [:: [::]; [:: 1; 3; 4; 5]; [:: 2; 1; 3; 5]]).+1 seq *)\n     (*     (seq nat_eqType) *)\nEval compute in @LCSLts _ [:: 1; 2; 3; 4; 5] [::] [::] None [::].\n     (* = [:: [:: 1; 2; 3; 4; 5]; [:: 2; 3; 4; 5]; [:: *)\n     (*       3; 4; 5]; [:: 4; 5]; [:: 5]] *)\n     (* : iter (size [::]).+1 seq (seq nat_eqType) *)\n", "meta": {"author": "aigarashi", "repo": "TPP2017", "sha": "3d27301214cebccad6262315b822f81ab273940a", "save_path": "github-repos/coq/aigarashi-TPP2017", "path": "github-repos/coq/aigarashi-TPP2017/TPP2017-3d27301214cebccad6262315b822f81ab273940a/TPPmark/yamamoto/tppmark2017-DP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7015140220461559}}
{"text": "(* BinTree the type of binary trees that store values at each node, and nothing at the leaves *)\nInductive BinTree {A : Type} := Leaf : BinTree | Branch : A -> BinTree -> BinTree -> BinTree.\n\n(* (Bin_elem x t) is a proof that x is in t, and the structure of the proof is the path taken to reach it *)\nInductive Bin_elem {A : Type} : A -> BinTree -> Prop :=\n    | Bin_elem_exact : forall x l r, Bin_elem x (Branch x l r)\n    | Bin_elem_left : forall x y l r, Bin_elem x l -> Bin_elem x (Branch y l r)\n    | Bin_elem_right : forall x y l r, Bin_elem x r -> Bin_elem x (Branch y l r).\n\n(* Bin_elem' makes use of a decideable equality procedure, and computes whether or not the element is in the tree, returning a type.\n    It doesn't explicitly store the path in a traversable form, the path is implicit in the structure of its computation. *)\nFixpoint Bin_elem' {A : Type} {eq_dec : forall x y : A, {x = y} + {x <> y}} (x : A) (t : BinTree) : Prop :=\n    match t with\n    | Leaf => False\n    | Branch y l r => match eq_dec x y with\n        | left _ => True\n        | right _ => @ Bin_elem' A eq_dec x l \\/ @ Bin_elem' A eq_dec x r\n        end\n    end.\n\n(* Both formulations are equivalent, but Bin_elem has fewer dependencies (since it doesn't need eq_dec) *)\nTheorem Bin_elems_equiv : forall A eq_dec (x : A) t, Bin_elem x t <-> @ Bin_elem' A eq_dec x t.\n    (* manual proof *)\n    intros a eq_dec x t.\n    induction t.\n    - split; inversion 1.\n    - simpl. destruct (eq_dec x a0).\n        + split.\n            * tauto.\n            * intro. rewrite e. apply Bin_elem_exact.\n        + split.\n            * inversion 1; tauto.\n            * inversion 1.\n                -- apply Bin_elem_left. exact (proj2 IHt1 H0).\n                -- apply Bin_elem_right. exact (proj2 IHt2 H0).\n    Restart.\n    (* proof with match goal and explicit inversion *)\n    intros a eq_dec x t.\n    induction t; split; simpl; match goal with\n    | |- Bin_elem _ Leaf -> _ => inversion 1\n    | |- False -> _ => inversion 1\n    | |- context[eq_dec ?x ?y] => destruct (eq_dec x y); match goal with\n        | |- _ -> True => exact (fun _ => I)\n        | |- Bin_elem x (Branch y ?l ?r) -> _ => inversion 1; tauto\n        | e:(x = y) |- _ -> Bin_elem x (Branch y _ _) => intro; rewrite e; apply Bin_elem_exact\n        | |- Bin_elem' x ?l \\/ Bin_elem' x ?r -> _ => destruct 1; [apply Bin_elem_left | apply Bin_elem_right]; tauto\n        end\n    end.\n    Restart.\n    (* more automated proof *)\n    intros a eq_dec x t.\n    induction t; split; simpl; try easy; match goal with\n    | |- context[eq_dec ?x ?y] => destruct (eq_dec x y); match goal with\n        | |- Bin_elem x (Branch y ?l ?r) -> _ => inversion 1; tauto\n        | e:(x = y) |- _ -> Bin_elem x (Branch y _ _) => intro; rewrite e; apply Bin_elem_exact\n        | |- Bin_elem' x ?l \\/ Bin_elem' x ?r -> _ => destruct 1; [apply Bin_elem_left | apply Bin_elem_right]; tauto\n        end\n    end.\n    Qed.\n", "meta": {"author": "aweinstock314", "repo": "coq-stuff", "sha": "a07354390b666226416ccd6809b0a7c50805c664", "save_path": "github-repos/coq/aweinstock314-coq-stuff", "path": "github-repos/coq/aweinstock314-coq-stuff/coq-stuff-a07354390b666226416ccd6809b0a7c50805c664/bintrees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256591565729, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7015140197706472}}
{"text": "(* ************************************************************************** *)\n(*                                                                            *)\n(* Verified Flash Translation Layer                                           *)\n(*                                                                            *)\n(*                                                                            *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\n(* Version 0.1 *)\n\nRequire Export Bool.\nRequire Import Arith.\n\n(* *********************************************************** *)\n\nTheorem nat_eq_dec : forall a b : nat, {a = b} + {a <> b}.\nProof.\n  intros; compare a b; auto.\nQed.\n\n(* *********************************************************** *)\n\nFixpoint blt_nat (n m : nat) {struct n} : bool :=\n  match n, m with\n  | O, O => false\n  | O, S _ => true\n  | S _, O => false\n  | S n', S m' => blt_nat n' m'\n  end.\n\nLemma blt_irrefl :\n  forall a : nat, blt_nat a a = false.\nProof.\n  induction a; simpl; auto.\nQed.\n\nLemma blt_irrefl_Prop :\n  forall a : nat, ~ (blt_nat a a = true).\nProof.\n  induction a; simpl; auto.\nQed.\n\nLemma blt_asym :\n  forall a b : nat, blt_nat a b = true\n    -> blt_nat b a = false.\nProof.\n  double induction a b; simpl; intros; auto.\nQed.\n\nLemma blt_O_Sn : \n  forall n : nat, blt_nat O (S n) = true.\nProof.\n  induction n; simpl; auto.\nQed.\n\nLemma blt_n_O : forall n,\n  blt_nat n O = false.\nProof.\n  induction n; simpl; auto.\nQed.\n\nLemma not_blt_n_O :\n  forall n : nat, ~ (blt_nat n 0 = true).\nProof.\n  induction n; simpl; auto.\nQed.\n\nLemma blt_true_lt : \n  forall a b : nat, blt_nat a b = true -> a < b.\nProof.\n  double induction a b; simpl; intros; \n    auto with arith; try discriminate.\nQed.\n\nLemma blt_false_le :\n  forall n m, blt_nat n m = false -> m <= n.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma le_blt_false :\n  forall n m, n <= m -> blt_nat m n = false.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith.\n  destruct (lt_n_O _ H0).\nQed.\n\nLemma lt_blt_true : \n  forall a b : nat, a < b -> blt_nat a b = true.\nProof.\n  double induction a b; simpl; intros; \n    auto with arith.\n  destruct (lt_irrefl 0 H).\n  destruct (lt_n_O (S n) H0).\nQed.\n\nLemma blt_n_Sn : \n  forall n : nat, blt_nat n (S n) = true.\nProof.\n  induction n; simpl; intros; auto with arith.\nQed.\n\nLemma blt_S_eq :\n  forall a b, blt_nat a b = blt_nat (S a) (S b).\nProof.\n  trivial.\nQed.\n\nLemma blt_n_Sm :\n  forall n m, blt_nat n m = true \n    -> blt_nat n (S m) = true.\nProof.\n  double induction n m; simpl; intros; auto with arith.\n  discriminate.\nQed.\n\nLemma blt_n_mk :\n  forall n m k, blt_nat n m = true\n    -> blt_nat n (m + k) = true.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith;  discriminate.\nQed.\n\nLemma blt_n_km :\n  forall n m k, blt_nat n m = true\n    -> blt_nat n (k + m) = true.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; try discriminate.\n  replace (k + (S n0)) with ((S n0) + k);\n    [idtac | auto with arith].\n  simpl. trivial.\n  replace (k + (S n0)) with ((S n0) + k);\n    [idtac | auto with arith].\n  simpl. \n  replace (n0 + k) with (k + n0);\n    [idtac | auto with arith].\n  apply H0; trivial.\nQed.\n\nLemma blt_nat_dec : forall a b,\n  {blt_nat a b = true} + {blt_nat a b = false}.\nProof.\n  double induction a b; simpl; intros; try tauto || auto.\nQed.\n\n\n(* *********************************************************** *)\n\nDefinition ble_nat (n m : nat) : bool := \n  match blt_nat m n with \n    | true => false \n    | false => true\n  end.\n\n(* *********************************************************** *)\n\nFixpoint beq_nat (n m : nat)  {struct n} : bool :=\n  match n, m with\n  | O, O => true\n  | O, S _ => false\n  | S _, O => false\n  | S n1, S m1 => beq_nat n1 m1\n  end.\n\nLemma beq_refl : forall m, beq_nat m m = true.\nProof.\n  induction m; simpl; intros; auto.\nQed.\n\nLemma beq_trans : forall m n k, beq_nat m n = true\n  -> beq_nat n k = true \n  -> beq_nat m k = true.\nProof.\n  induction m; induction n; destruct k; \n    simpl; intros; discriminate || auto.\n  eapply IHm; eauto.\nQed.\n\nLemma beq_sym : forall m n b, \n  beq_nat m n = b -> beq_nat n m = b.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma beq_sym2 : forall m n, \n  beq_nat m n = beq_nat n m.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma beq_true_eq :\n  forall n m, beq_nat n m = true\n    -> n = m.\nProof. \n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma beq_false_neq :\n  forall n m, beq_nat n m = false\n    -> ~ (n = m).\nProof.\n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma eq_beq_true :\n  forall n m, n = m\n    -> beq_nat n m = true.\nProof. \n  double induction n m; simpl; intros; \n    auto with arith; discriminate.\nQed.\n\nLemma neq_beq_false :\n  forall n m, ~ (n = m) \n    -> beq_nat n m = false.\nProof.\n  double induction n m; simpl; intros; \n    auto with arith.\n  destruct (H (refl_equal _)).\nQed.\n\nLemma beq_nat_dec : forall a b,\n  {beq_nat a b = true} + {beq_nat a b = false}.\nProof.\n  double induction a b; simpl; intros; try tauto || auto.\nQed.\n\n(* *********************************************************** *)\n\nLemma blt_t_beq_f : \n  forall m n, blt_nat m n = true \n    -> beq_nat m n = false.\nProof.\n  double induction n m; simpl; intros; auto with arith.\nQed.\n\nLemma bgt_t_beq_f :\n  forall m n, blt_nat n m = true\n    -> beq_nat m n = false.\nProof.\n  double induction m n; simpl; intros; auto with arith.\nQed.\n\nLemma beq_t_blt_f : \n  forall m n, beq_nat m n = true\n    -> blt_nat m n = false. \nProof.\n  double induction m n; simpl; intros; auto with arith.\nQed.\n\nLemma beq_t_bgt_f :\n  forall m n, beq_nat m n = true\n    -> blt_nat n m = false.\nProof.\n  double induction n m; simpl; intros; auto with arith.\nQed.\n\nLemma blt_S_dec : \n  forall n m,\n    blt_nat n (S m) = true \n    -> blt_nat n m = true \\/ beq_nat n m = true.\nProof.\n  intros n m H.\n  assert (Hx:=blt_true_lt _ _ H).\n  apply lt_n_Sm_le in Hx.\n  apply le_lt_or_eq_iff in Hx.\n  destruct Hx.\n    left. \n    apply lt_blt_true; trivial.\n  right.\n  apply eq_beq_true; trivial.\nQed.\n\n(* *********************************************************** *)\n\nDefinition max_nat (m n : nat) : nat :=\n  if blt_nat m n then n else m.\n\nLemma max_nat_elim_l : forall m n : nat,\n  m <= max_nat m n.\nProof.\n  unfold max_nat; intros m n.\n  destruct (blt_nat_dec m n) as [Hb | Hb]; rewrite Hb.\n  assert (Hb' := blt_true_lt m n Hb).\n  auto with arith.\n  auto with arith.\nQed.\n\nLemma max_nat_elim_r : forall m n : nat,\n  n <= max_nat m n.\nProof.\n  unfold max_nat; intros m n.\n  destruct (blt_nat_dec m n) as [Hb | Hb]; rewrite Hb.\n  auto with arith.\n  assert (Hb' := blt_false_le m n Hb).\n  auto with arith.\nQed.\n\n(* *********************************************************** *)\n\nLtac rewrite_bnat t :=\n  match type of t with\n    | blt_nat ?a ?b = ?c => rewrite t\n    | beq_nat ?a ?b = ?c => rewrite t\n  end.\n\nLtac rewrite_bnat_H t H :=\n  match type of t with\n    | blt_nat ?a ?b = ?c => rewrite t in H\n    | beq_nat ?a ?b = ?c => rewrite t in H\n  end.\n\nLtac rewrite_bnat_all t :=\n  match goal with \n    | |- context[(blt_nat ?a ?b)] => rewrite_bnat t; rewrite_bnat_all t\n    | H : context[(blt_nat ?a ?b)] |- _ => rewrite_bnat_H t H; rewrite_bnat_all t\n    | |- context[(beq_nat ?a ?b)] => rewrite_bnat t; rewrite_bnat_all t\n    | H : context[(beq_nat ?a ?b)] |- _ => rewrite_bnat_H t H; rewrite_bnat_all t\n    | _ => idtac\n  end.\n\nLtac simplbnat := \n  match goal with\n    (* blt rewrite directly *)\n    | [H : blt_nat ?x ?y = ?f\n      |- context [(blt_nat ?x ?y)]] =>\n       rewrite H; simplbnat\n    | [H : blt_nat ?x ?y = ?f,\n       H0 : context [(blt_nat ?x ?y)] \n      |- _ ] =>\n       rewrite H in H0; simplbnat\n\n    (* beq rewrite directly *)\n    | [H : beq_nat ?x ?y = ?f \n      |- context [(beq_nat ?x ?y)]] =>\n       rewrite H; simplbnat\n    | [H : beq_nat ?x ?y = ?f,\n       H0 : context [(beq_nat ?x ?y)] |- _ ] =>\n       rewrite H in H0; simplbnat\n         \n    (* blt -> beq *)\n    | [H : blt_nat ?x ?y = true \n      |- context[(beq_nat ?x ?y)]] =>\n      rewrite (blt_t_beq_f x y H); simplbnat\n    | [H : blt_nat ?x ?y = true,\n       H0 : context[(beq_nat ?x ?y)] |- _ ] =>\n      rewrite (blt_t_beq_f x y H) in H0; simplbnat\n     \n    (* bgt -> beq *)\n    | [H : blt_nat ?y ?x = true \n      |- context[(beq_nat ?x ?y)]] =>\n      rewrite (bgt_t_beq_f x y H); simplbnat\n    | [H : blt_nat ?y ?x = true, \n       H0 : context[(beq_nat ?x ?y)] |- _ ] =>\n      rewrite (bgt_t_beq_f x y H) in H0; simplbnat\n         \n    (* beq -> blt *)\n    | [H : beq_nat ?y ?x = true \n      |- context[(blt_nat ?x ?y)]] =>\n      rewrite (beq_t_blt_f x y H); simplbnat\n    | [H : beq_nat ?y ?x = true, \n       H0 : context[(blt_nat ?x ?y)] |- _ ] =>\n      rewrite (beq_t_blt_f x y H) in H0; simplbnat\n         \n    (* beq -> bgt *)\n    | [H : beq_nat ?y ?x = true \n      |- context[(blt_nat ?y ?x)]] =>\n      rewrite (beq_t_bgt_f x y H); simplbnat\n    | [H : beq_nat ?y ?x = true, \n       H0 : context[(blt_nat ?y ?x)] |- _ ] =>\n      rewrite (beq_t_bgt_f x y H) in H0; simplbnat\n\n    (* blt_irrefl *)\n    | [ |- context [blt_nat ?x ?x]] =>\n      rewrite (blt_irrefl x); simplbnat\n    | [H : context [blt_nat ?x ?x] |- _ ] =>\n      rewrite (blt_irrefl x) in H; simplbnat\n\n    (* blt_asym *)\n    | [H : blt_nat ?x ?y = true \n      |- context [blt_nat ?y ?x]] =>\n      rewrite (blt_asym x y H); simplbnat\n    | [H : blt_nat ?x ?y = true,\n       H0 : context [blt_nat ?y ?x] |- _ ] =>\n      rewrite (blt_asym x y H) in H0; simplbnat\n\n    (* blt_O_Sn *)\n    | [ |- context [(blt_nat O (S ?x))]] =>\n      rewrite (blt_O_Sn x); simplbnat\n    | [H : context [(blt_nat O (S ?x))] |- _ ] =>\n      rewrite (blt_O_Sn x) in H; simplbnat\n\n    (* blt_n_O *)\n    | [ |- context [(blt_nat ?x O)]] =>\n      rewrite (blt_n_O x); simplbnat\n    | [H : context [(blt_nat ?x O)] |- _ ] =>\n      rewrite (blt_n_O x) in H; simplbnat\n\n    (* blt_n_Sn *)\n    | [ |- context [(blt_nat ?x (S ?x))]] =>          \n      rewrite (blt_n_Sn x); simplbnat\n    | [H : context [(blt_nat ?x (S ?x))] |- _ ] =>\n      rewrite (blt_n_Sn x) in H; simplbnat\n\n    (* blt_S_eq *)\n    | [ |- context [(blt_nat (S ?x) (S ?y))]] =>\n      rewrite <- (blt_S_eq x y); simplbnat\n    | [H : context [(blt_nat (S ?x) (S ?y))] |- _ ] =>\n      rewrite <- (blt_S_eq x y) in H; simplbnat\n\n    (* blt_n_Sm *)\n    | [H : blt_nat ?x ?y = true\n      |- context [(blt_nat ?x (S ?y))]] =>\n      rewrite (blt_n_Sm x y H); simplbnat\n    | [H : blt_nat ?x ?y = true,              \n       H0 : context [(blt_nat ?x (S ?y))] |- _ ] =>\n      rewrite <- (blt_n_Sm x y H) in H0; simplbnat\n\n    (* blt_n_mk *)\n    | [H : blt_nat ?x ?y = true                       \n      |- context [(blt_nat ?x (?y + ?k))]] =>\n      rewrite (blt_n_mk x y k H); simplbnat\n    | [H : blt_nat ?x ?y = true,              \n       H0 : context [(blt_nat ?x (?y + ?k))] |- _ ] =>\n      rewrite <- (blt_n_mk x y k H) in H0; simplbnat\n\n    (* blt_n_km *)\n    | [H : blt_nat ?x ?y = true                       \n      |- context [(blt_nat ?x (?k + ?y))]] =>\n      rewrite (blt_n_km x y k H); simplbnat\n    | [H : blt_nat ?x ?y = true,              \n       H0 : context [(blt_nat ?x (?k + ?y))] |- _ ] =>\n      rewrite <- (blt_n_km x y k H) in H0; simplbnat\n\n    (* beq_refl *)\n    | [ |- context [(beq_nat ?x ?x)] ] =>\n      rewrite (beq_refl x); simplbnat\n    | [H : context [(beq_nat ?x ?x)] |- _ ] => \n      rewrite (beq_refl x) in H; simplbnat\n\n    (* beq_sym *)\n    | [ H : beq_nat ?x ?y = ?b \n        |- context [(beq_nat ?y ?x)] ] =>\n      rewrite (beq_sym x y b H); simplbnat\n    | [H : beq_nat ?x ?y = ?b,\n       H0 : context [(beq_nat ?y ?x)] |- _ ] => \n      rewrite (beq_sym x y b H) in H0; simplbnat\n\n    | [ H : ?x <> ?y |- context [(beq_nat ?x ?y)] ] => \n      rewrite (neq_beq_false x y H); simplbnat\n    | [ H : ?x <> ?y, \n        H0 : context [(beq_nat ?x ?y)] |- _ ] => \n      rewrite (neq_beq_false x y H) in H0; simplbnat\n\n    | [ H : ?y <> ?x |- context [(beq_nat ?x ?y)] ] => \n      rewrite (neq_beq_false x y (sym_not_eq H)); simplbnat\n    | [ H : ?y <> ?x, \n        H0 : context [(beq_nat ?x ?y)] |- _ ] => \n      rewrite (neq_beq_false x y (sym_not_eq H)) in H0; simplbnat\n        \n    | [H : ?x = ?x |- _ ] => clear H; simplbnat\n    | [H : true = false |- _ ] => discriminate H\n    | [H : false = true |- _ ] => discriminate H\n    | _ => idtac\n  end.\n\nTactic Notation \"bnat simpl\" := simplbnat.\n\nLtac desbnatH H := \n  match goal with\n    | H : blt_nat ?a ?b = true |- _ =>\n        generalize (blt_true_lt a b H); clear H; intro H\n\n    | H : blt_nat ?a ?b = false |- _ =>\n        generalize (blt_false_le a b H); clear H; intro H\n\n    | H : beq_nat ?a ?b = true |- _ =>\n        generalize (beq_true_eq a b H); clear H; intro H\n\n    | H : beq_nat ?a ?b = false |- _ =>\n        generalize (beq_false_neq a b H); clear H; intro H\n\n    | _ => fail 1 \"not bnat found\"\n  end.\n\nLtac desbnat := \n  match goal with\n    | H : blt_nat ?a ?b = true |- _ =>\n        generalize (blt_true_lt a b H); clear H; intro H; desbnat\n\n    | H : blt_nat ?a ?b = false |- _ =>\n        generalize (blt_false_le a b H); clear H; intro H; desbnat\n\n    | H : beq_nat ?a ?b = true |- _ =>\n        generalize (beq_true_eq a b H); clear H; intro H; desbnat\n\n    | H : beq_nat ?a ?b = false |- _ =>\n        generalize (beq_false_neq a b H); clear H; intro H; desbnat\n\n    | _ => idtac\n  end.\n\nLtac conbnat := \n  match goal with\n    | |- blt_nat ?a ?b = true =>\n        apply (lt_blt_true a b)\n\n    | |- blt_nat ?a ?b = false =>\n        apply (le_blt_false b a)\n\n    | |- beq_nat ?a ?b = true =>\n        apply (eq_beq_true a b)\n\n    | |- beq_nat ?a ?b = false =>\n        apply (neq_beq_false a b)\n\n    | _ => fail 1 \"the goal is not bnat\"\n  end.\n\nLtac solvebnat :=\n  desbnat; conbnat; auto with arith.\n\n\n(* *********************************************************** *)\n\nTactic Notation \"rewbnat\" constr (t) :=\n  match t with \n    | beq_nat ?x ?y = ?f =>\n      let Hb := fresh \"Hb\" in\n        (assert (Hb : t); \n          [solvebnat | rewrite Hb; clear Hb])\n    | blt_nat ?x ?y = ?f =>\n      let Hb := fresh \"Hb\" in\n        (assert (Hb : t); \n          [solvebnat | rewrite Hb; clear Hb])\n    | _ =>\n      match type of t with\n        | beq_nat ?x ?y = true => rewrite (beq_true_eq x y t)\n        | _ => rewrite t\n      end\n  end.\n\nTactic Notation \"rewbnat\" constr (t) \"in\" hyp (H) :=\n  match t with \n    | beq_nat ?x ?y = ?f =>\n      let Hb := fresh \"Hb\" in\n        (assert (Hb : t); \n          [solvebnat | rewrite Hb in H; clear Hb])\n    | blt_nat ?x ?y = ?f =>\n      let Hb := fresh \"Hb\" in\n        (assert (Hb : t); \n          [solvebnat | rewrite Hb in H; clear Hb])\n    | _ =>\n      match type of t with\n        | beq_nat ?x ?y = true => rewrite (beq_true_eq x y t) in H\n        | _ => rewrite t in H\n      end\n  end.\n\nTactic Notation \"assertbnat\" constr (t) :=\n  let Hb := fresh \"Hb\" in (\n    match t with \n      | beq_nat ?x ?y = ?f =>\n        (assert (Hb : t); \n            [solvebnat | idtac])\n      | blt_nat ?x ?y = ?f =>\n        (assert (Hb : t); \n            [solvebnat | idtac])\n      | _ => fail 1 \"t must be a blt_nat or beq_nat equation\"\n    end).\n\nLtac discribnat := \n  desbnat; subst;\n  match goal with\n    | H : ?x <> ?x |- _ => destruct (H (refl_equal x))\n    | H : ?x = ?y |- _ => discriminate\n    | H : ?x < ?x |- _ => destruct (lt_irrefl x H)\n    | H : ?x < O |- _ => destruct (lt_n_O x H)\n    | H : beq_nat ?x ?x = false |- _ =>\n      desbnatH H; destruct (H (refl_equal x))\n    | _ => elimtype False; \n        auto with arith || fail 1 \"no discriminatable hypothesis\"\n  end.\n\nLtac substbnat_all := desbnat; subst.\n\nLtac substbnat_one f := desbnat; subst f.\n\nTactic Notation \"substbnat\" := substbnat_all.\n\nTactic Notation \"substbnat\" constr (f) := substbnat_one f.\n\n(*\nSection test.\n\nVariables (a b c d e f g : nat).\nHypotheses \n  (H0 : beq_nat a b = true)\n  (H1 : blt_nat c b = true)\n  (H2 : blt_nat b a = true)\n  (H3 : beq_nat a b = true)\n  (H4 : beq_nat a b = true)\n  (H5 : if beq_nat a b then True else False)\n.\n\nGoal if beq_nat a b then True else False.\nsimplbnat.\nrewrite_bnat_all H0.\nsubstbnat.\nrewbnat H0 in H3.\ninvbnat.\nbnat2nat.\nomega.\nsimplbnat.\n\nEnd test. *)\n\n(* *********************************************************** *)\n\nLtac decbeqnat x y :=\n  let Hb := fresh \"Hb\" in\n    (destruct (beq_nat_dec x y) as [Hb | Hb]; simplbnat).\n\nLtac decbltnat x y :=\n  let Hb := fresh \"Hb\" in\n    (destruct (blt_nat_dec x y) as [Hb | Hb]; simplbnat).\n\n(* *********************************************************** *)\n(* deprecate *)\n\nTactic Notation \"repbnat\" constr (t1) \"with\" constr (t2) :=\n  replace t1 with t2; [idtac | desbnat; auto with arith].\n\nTactic Notation \"repbnat\" constr (t1) \"with\" constr (t2) \"in\" hyp (H) :=\n  replace t1 with t2 in H; [idtac | desbnat; auto with arith].\n\nTactic Notation \"bool_destruct\" hyp (H) \"as\" simple_intropattern (pat) :=\n  let H0 := fresh \"H\" in\n    (rename H into H0;\n    match type of (H0) with\n      | (andb ?a ?b = true) => \n        destruct (andb_prop a b H0) as pat; clear H0\n      | (orb ?a ?b = true) =>\n        destruct (orb_prop a b H0) as pat; clear H0\n      | _ => fail \"not destructable\" \n    end).\n", "meta": {"author": "vittayang", "repo": "coqnand", "sha": "dd538809cf926e04d8de9912521d4e2dfc32189e", "save_path": "github-repos/coq/vittayang-coqnand", "path": "github-repos/coq/vittayang-coqnand/coqnand-dd538809cf926e04d8de9912521d4e2dfc32189e/bnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.701514013512284}}
{"text": "(********************************************************************)\n(*                                                                  *)\n(*  The Why3 Verification Platform   /   The Why3 Development Team  *)\n(*  Copyright 2010-2015   --   INRIA - CNRS - Paris-Sud University  *)\n(*                                                                  *)\n(*  This software is distributed under the terms of the GNU Lesser  *)\n(*  General Public License version 2.1, with the special exception  *)\n(*  on linking described in file LICENSE.                           *)\n(*                                                                  *)\n(********************************************************************)\n\n(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\nRequire list.List.\nRequire list.Length.\nRequire list.Mem.\nRequire list.Append.\nRequire list.Reverse.\n\n(* Why3 goal *)\nDefinition num_occ: forall {a:Type} {a_WT:WhyType a}, a -> (list a) -> Z.\nintros a a_WT x.\nexact (fix num_occ (l : list a) : int :=\n  match l with\n  | nil => 0\n  | cons y r => (if why_decidable_eq x y then 1 else 0) + num_occ r\n  end)%Z.\nDefined.\n\n(* Why3 goal *)\nLemma num_occ_def : forall {a:Type} {a_WT:WhyType a}, forall (x:a)\n  (l:(list a)),\n  match l with\n  | Init.Datatypes.nil => ((num_occ x l) = 0%Z)\n  | (Init.Datatypes.cons y r) => ((x = y) -> ((num_occ x\n      l) = (1%Z + (num_occ x r))%Z)) /\\ ((~ (x = y)) -> ((num_occ x\n      l) = (0%Z + (num_occ x r))%Z))\n  end.\nProof.\nintros a a_WT x [|y r].\neasy.\nsplit ; intros H.\nchange ((if why_decidable_eq x y then 1 else 0) + num_occ x r = 1 + num_occ x r)%Z.\nnow case why_decidable_eq.\nchange ((if why_decidable_eq x y then 1 else 0) + num_occ x r = 0 + num_occ x r)%Z.\nnow case why_decidable_eq.\nQed.\n\n(* Why3 goal *)\nLemma Num_Occ_NonNeg : forall {a:Type} {a_WT:WhyType a}, forall (x:a)\n  (l:(list a)), (0%Z <= (num_occ x l))%Z.\nintros a a_WT x l.\ninduction l as [|lh lt IHl].\neasy.\nsimpl.\ncase why_decidable_eq ; intros H.\nomega.\neasy.\nQed.\n\n(* Why3 goal *)\nLemma Mem_Num_Occ : forall {a:Type} {a_WT:WhyType a}, forall (x:a)\n  (l:(list a)), (list.Mem.mem x l) <-> (0%Z < (num_occ x l))%Z.\nProof.\nintros a a_WT x l.\ninduction l as [|lh lt IHl].\nnow split.\nsimpl.\ncase why_decidable_eq ; intros H ; split.\nintros _.\nclear.\ngeneralize (Num_Occ_NonNeg x lt).\nomega.\nnow left.\nintros [H'|H'] ; try easy.\nnow apply IHl.\nright.\nnow apply IHl.\nQed.\n\n(* Why3 goal *)\nLemma Append_Num_Occ : forall {a:Type} {a_WT:WhyType a}, forall (x:a)\n  (l1:(list a)) (l2:(list a)), ((num_occ x\n  (Init.Datatypes.app l1 l2)) = ((num_occ x l1) + (num_occ x l2))%Z).\nProof.\nintros a a_WT x l1 l2.\ninduction l1 as [|l1h l1t IHl1].\neasy.\nsimpl.\nrewrite IHl1.\nrewrite Zplus_assoc.\nnow case why_decidable_eq.\nQed.\n\n(* Why3 goal *)\nLemma reverse_num_occ : forall {a:Type} {a_WT:WhyType a}, forall (x:a)\n  (l:(list a)), ((num_occ x l) = (num_occ x (Lists.List.rev l))).\nintros a a_WT x l.\ninduction l; simpl.\nauto.\nrewrite Append_Num_Occ.\nrewrite <- IHl.\nring_simplify.\nsimpl (num_occ x (a0 :: nil))%list.\nring.\nQed.\n\n", "meta": {"author": "ssaavedra", "repo": "why3", "sha": "e28f4cda05925849c1c203f56b9f9b49e4bfe5b4", "save_path": "github-repos/coq/ssaavedra-why3", "path": "github-repos/coq/ssaavedra-why3/why3-e28f4cda05925849c1c203f56b9f9b49e4bfe5b4/lib/coq/list/NumOcc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7015140133345547}}
{"text": "(* Gabriel Braun February 2013 *)\n\nRequire Export GeoCoq.Tarski_dev.Annexes.quadrilaterals_inter_dec.\n\nSection Vectors.\n\nContext `{TE:Tarski_euclidean}.\n\nLemma eqv_refl : forall A B, EqV A B A B.\nProof.\nintros.\nunfold EqV.\ninduction (eq_dec_points A B).\nright.\nsplit; auto.\nleft.\nright.\napply plgf_trivial.\nassumption.\nQed.\n\nLemma eqv_sym : forall A B C D, EqV A B C D -> EqV C D A B.\nProof.\nintros.\nunfold EqV in *.\ninduction H.\nleft.\napply plg_sym.\napply plg_comm2.\nassumption.\nright.\ntauto.\nQed.\n\nLemma eqv_trans : forall A B C D E F, EqV A B C D -> EqV C D E F -> EqV A B E F.\nProof.\nintros.\nunfold EqV in *.\n\ninduction H; induction H0.\nassert(Parallelogram A B F E \\/ A = B /\\ D = C /\\ E = F /\\ A = E).\napply (plg_pseudo_trans A B D C E F); auto.\napply plg_comm2.\nassumption.\ninduction H1.\nleft.\nauto.\nright.\ntauto.\nspliter.\nsubst D.\nsubst F.\ninduction (eq_dec_points A B).\nright.\ntauto.\nleft.\ninduction H.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H3.\nCol.\napply plgf_sym in H.\napply plgf_trivial_neq in H.\ntauto.\nspliter.\nsubst B.\nsubst D.\ninduction H0.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H.\nCol.\napply plgf_trivial_neq in H.\nright.\nspliter.\nsubst F.\ntauto.\nright.\ntauto.\nQed.\n\nLemma eqv_comm : forall A B C D, EqV A B C D -> EqV B A D C.\nProof.\nintros.\nunfold EqV in *.\ninduction H.\nleft.\napply plg_comm2.\nassumption.\nright.\nspliter.\nsubst B.\nsubst D.\ntauto.\nQed.\n\nLemma vector_construction : forall A B C, exists D, EqV A B C D.\nProof.\nintros.\ninduction (eq_dec_points A B).\nexists C.\nright.\ntauto.\nassert(HH:= midpoint_existence B C).\nex_and HH M.\nprolong A M D A M.\nexists D.\nleft.\napply (mid_plg _ _ _ _ M).\n\ninduction(eq_dec_points A D).\nsubst D.\nright.\nintro.\nsubst C.\napply l7_3 in H0.\napply between_identity in H1.\nsubst M.\ncontradiction.\nleft.\nassumption.\nsplit; Cong.\nassumption.\nQed.\n\nLemma vector_construction_uniqueness :\n forall A B C D D',\n EqV A B C D ->\n EqV A B C D' ->\n D = D'.\nProof.\nintros.\nunfold EqV in *.\ninduction H; induction H0.\napply plg_comm2 in H.\napply plg_comm2 in H0.\napply (plg_uniqueness B A C); auto.\nspliter.\nsubst B.\nsubst D'.\ninduction H.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H.\nCol.\napply (plgf_trivial_neq A D C ).\nassumption.\nspliter.\nsubst B.\nsubst D.\ninduction H0.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H.\nCol.\napply plgf_comm2 in H.\napply (plgf_trivial_neq A C D').\nassumption.\nspliter.\nsubst C.\nauto.\nQed.\n\nLemma null_vector : forall A B C, EqV A A B C -> B = C.\nProof.\nintros.\nunfold EqV in H.\ninduction H.\ninduction H.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H.\nCol.\napply plgf_trivial_neq in H.\nspliter.\nsubst C.\ntauto.\ntauto.\nQed.\n\nLemma vector_uniqueness : forall A B C, EqV A B A C -> B = C.\nProof.\nintros.\nunfold EqV in H.\ninduction H.\ninduction H.\ninduction H.\nunfold TS in H.\nspliter.\napply False_ind.\napply H2.\nCol.\napply plgf_permut in H.\napply plgf_sym in H.\napply (plgf_trivial_neq A B C ).\nassumption.\nspliter.\nsubst A.\nauto.\nQed.\n\nLemma eqv_trivial : forall A B , EqV A A B B.\nProof.\nintros.\nunfold EqV.\nright.\ntauto.\nQed.\n\nLemma eqv_permut :\n  forall A B C D,\n  EqV A B C D ->\n  EqV A C B D.\nProof.\nintros.\ninduction (eq_dec_points A C).\nsubst C.\nassert(B = D).\napply (vector_uniqueness A).\nassumption.\nsubst D.\napply eqv_trivial.\n\nunfold EqV in *.\ninduction H.\nleft.\napply plg_permut.\napply plg_comm2.\nassumption.\nleft.\nspliter.\nsubst B.\nsubst D.\napply plg_trivial.\nassumption.\nQed.\n\nLemma eqv_par :\n forall A B C D,\n  A <> B ->\n  EqV A B C D ->\n  Par A B C D.\nProof.\nintros.\nunfold EqV in H0.\ninduction H0.\nunfold Parallelogram in H0.\ninduction H0.\nunfold Parallelogram_strict in H0.\nspliter.\napply par_right_comm.\nassumption.\nunfold Parallelogram_flat in H0.\nspliter.\nright.\nspliter.\nrepeat split; Col.\nintro.\nsubst D.\napply cong_identity in H2.\ncontradiction.\nColR.\nColR.\n\nspliter.\ncontradiction.\nQed.\n\nLemma eqv_opp_null :\n  forall A B,\n  EqV A B B A ->\n  A = B.\nProof.\nintros.\nunfold EqV in H.\ninduction H.\napply plg_irreflexive in H.\ntauto.\ntauto.\nQed.\n\nLemma eqv_sum :\n  forall A B C A' B' C',\n  EqV A B A' B' ->\n  EqV B C B' C' ->\n  EqV A C A' C'.\nProof.\nintros.\n\nunfold EqV in *.\ninduction H.\ninduction H0.\napply plg_comm2 in H.\napply plg_permut in H.\napply plg_permut in H0.\napply plg_sym in H0.\nassert(HH:= plg_pseudo_trans A A' B' B C C' H H0).\ninduction HH.\nleft.\napply plg_permut.\napply plg_comm2.\nassumption.\nspliter.\nright.\nsubst A'.\nsubst C'.\ntauto.\nspliter.\nsubst C.\nsubst C'.\nleft.\nassumption.\nspliter.\nsubst B.\nsubst B'.\nassumption.\nQed.\n\nLemma null_sum :\n forall A B C,\n  SumV A B B A C C.\nProof.\nintros.\nunfold SumV.\nintros D H.\nassert(A = D).\napply (vector_uniqueness B).\napply H.\nsubst D.\napply eqv_trivial.\nQed.\n\nLemma chasles :\n forall A B C,\n  SumV A B B C A C.\nProof.\nintros.\nunfold SumV.\nintros D H.\nassert(C = D).\napply (vector_uniqueness B).\nassumption.\nsubst D.\napply eqv_refl.\nQed.\n\nLemma eqv_mid :\n forall A B C,\n  EqV A B B C ->\n  Midpoint B A C.\nProof.\nintros.\nunfold EqV in H.\ninduction H.\napply plg_mid in H.\nex_and H M.\napply l7_3 in H0.\nsubst M.\nassumption.\nspliter.\nsubst C.\nsubst B.\napply l7_3_2.\nQed.\n\nLemma mid_eqv :\n  forall A B C, Midpoint A B C ->\n  EqV B A A C.\nProof.\nintros.\nunfold EqV.\ninduction(eq_dec_points A B).\nsubst B.\napply is_midpoint_id in H.\nsubst C.\nright.\ntauto.\nleft.\n\napply (mid_plg _ _ _ _ A).\nleft.\nintro.\nsubst C.\napply l7_3 in H.\ncontradiction.\nassumption.\nMidpoint.\nQed.\n\n\nLemma sum_sym :\n  forall A B C D E F,\n  SumV A B C D E F ->\n  SumV C D A B E F.\nProof.\nintros.\nunfold SumV in *.\nassert(HH:=vector_construction C D B).\nex_and HH D'.\n\n\nassert(HH:= (H D' H0)).\nclear H.\n\nassert(EqV C B D D').\napply eqv_permut.\nassumption.\n\nassert(EqV A D B D'0).\napply eqv_permut.\nassumption.\n\ninduction (eq_dec_points A D'0).\nsubst D'0.\n\napply eqv_comm in H1.\nassert(HP:= (eqv_mid B A D H1)).\n\nunfold EqV in H0.\ninduction H0.\napply plg_mid in H0.\nex_and H0 M.\nassert( A = M).\napply (l7_17 B D).\napply HP.\nMidpoint.\nsubst M.\n\napply mid_eqv in H0.\napply (eqv_trans _ _ A D').\napply H0.\nassumption.\n\nspliter.\nsubst D.\nsubst D'.\napply (eqv_trans _ _ A B).\napply eqv_sym.\napply eqv_comm.\napply H1.\nassumption.\n\ninduction H0; induction H1.\napply plg_mid in H0.\napply plg_mid in H1.\nex_and H0 M0.\nex_and H1 M1.\n\nassert(M1 = M0).\napply (l7_17 B D).\napply H5.\nMidpoint.\nsubst M1.\nassert(Parallelogram A D' D'0 C).\napply (mid_plg _ _ _ _ M0).\nleft.\nassumption.\nassumption.\nMidpoint.\nassert(EqV C D'0 A D').\nunfold EqV.\nleft.\napply plg_comm2.\napply plg_sym.\nassumption.\napply (eqv_trans _ _ A D').\napply H7.\nassumption.\nspliter.\nsubst B.\nsubst D'0.\nassert(EqV C D A D').\napply eqv_permut.\nassumption.\napply (eqv_trans _ _ A D').\napply H1.\nassumption.\nspliter.\nsubst D.\nsubst D'.\n\nassert(EqV A B C D'0).\napply eqv_permut.\nassumption.\napply (eqv_trans _ _ A B).\napply eqv_sym.\napply H0.\nassumption.\nspliter.\nsubst D.\nsubst D'.\nsubst B.\nsubst D'0.\napply null_vector in HH.\nsubst F.\napply eqv_trivial.\nQed.\n\n\nLemma opposite_sum :\n  forall A B C D E F,\n  SumV A B C D E F ->\n  SumV B A D C F E.\nProof.\nintros.\nunfold SumV in *.\nintros D0 H0.\nassert(HH:=vector_construction C D B).\nex_and HH D'.\nassert(HH:= (H D' H1)).\nclear H.\n\nassert(EqV D' B A D0).\napply (eqv_trans _ _ D C).\napply eqv_sym.\napply eqv_comm.\napply H1.\nassumption.\napply eqv_permut in H.\neapply (eqv_trans _ _ D' A).\napply eqv_sym.\napply H.\napply eqv_comm.\nassumption.\nQed.\n\nLemma null_sum_eq :\n  forall A B C D,\n  SumV A B B C D D ->\n  A = C.\nProof.\nintros.\nunfold SumV in H.\nassert(HH:= vector_construction B C B).\nex_and HH D'.\nassert(HH:= (H D' H0)).\nassert(A = D').\napply (null_vector D).\napply eqv_sym.\napply HH.\nsubst D'.\napply vector_uniqueness in H0.\nauto.\nQed.\n\nLemma is_to_ise :\n  forall A B C D E F,\n  SumV A B C D E F ->\n  SumV_exists A B C D E F.\nProof.\nintros.\nunfold SumV in H.\nunfold SumV_exists.\nassert(HH:= (vector_construction C D B)).\nex_and HH D'.\nassert(HH:=(H D' H0)).\nexists D'.\nsplit.\n\napply eqv_sym.\nassumption.\nassumption.\nQed.\n\nLemma ise_to_is :\n forall A B C D E F,\n  SumV_exists A B C D E F ->\n  SumV A B C D E F.\nProof.\nintros.\nex_and H D'.\nunfold SumV.\nintros.\nassert(D'= D'0).\napply (vector_construction_uniqueness C D B).\napply eqv_sym.\napply H.\nassumption.\nsubst D'0.\nassumption.\nQed.\n\nLemma sum_exists :\n forall A B C D, exists E, exists F, SumV A B C D E F.\nintros.\nassert(HH:= vector_construction C D B).\nex_and HH F.\nexists A.\nexists F.\nunfold SumV.\nintros.\nassert(D' = F).\napply (vector_construction_uniqueness C D B); auto.\nsubst D'.\napply eqv_refl.\nQed.\n\nLemma sum_uniqueness :\n forall A B C D E F E' F',\n SumV A B C D E F ->\n SumV A B C D E' F' ->\n EqV E F E' F'.\nProof.\nintros.\nunfold SumV in *.\nassert(HH:= vector_construction C D B).\nex_and HH D'.\nassert(HH:= (H D' H1)).\nassert(HP := (H0 D' H1)).\napply (eqv_trans _ _ A D').\napply eqv_sym.\nauto.\nauto.\nQed.\n\nLemma same_dir_refl : forall A B, Same_dir A B A B.\nintros.\nunfold Same_dir.\ninduction (eq_dec_points A B).\nleft.\ntauto.\nright.\nexists B.\nsplit.\napply out_trivial.\nauto.\napply eqv_refl.\nQed.\n\nLemma same_dir_ts :\n  forall A B C D,\n  Same_dir A B C D ->\n  exists M, Bet A M D /\\ Bet B M C.\nProof.\nintros.\ninduction H.\nspliter.\nsubst B.\nsubst D.\nexists A.\nsplit; Between.\n\nex_and H D'.\ninduction H0.\n\nassert(exists M : Tpoint, Midpoint M A D' /\\ Midpoint M B C).\napply plg_mid.\nassumption.\nex_and H1 M.\nunfold Midpoint in *.\nspliter.\n\ninduction H0.\nassert(HH:=plgs_two_sides A B D' C H0).\nspliter.\n\nassert(B <> C).\nintro.\nsubst C.\nunfold TS in H6.\nspliter.\nCol.\nassert(~ Col B C D').\nintro.\nunfold TS in H6.\nspliter.\napply H9.\nCol.\n\nassert(OS B C D' D).\napply l6_6 in H.\napply (out_one_side_1 _ _ _ _ C); Col.\n\nassert(TS B C A D).\napply l9_2.\napply (l9_8_2 _ _ D').\napply l9_2.\napply H6.\nauto.\n\nassert(~ Col A B C).\ninduction H10.\nassumption.\ninduction H10.\nspliter.\nex_and H13 T.\n\nassert(OS A B D' C /\\ OS D' C A B).\napply(plgs_one_side A B D' C).\nassumption.\nspliter.\n\nassert(~Col A B C).\nassumption.\n\nassert(Par_strict A B D' C /\\ Par_strict A C B D').\n\napply(plgs_par_strict A B D' C).\nassumption.\nspliter.\n\nassert(A <> B).\nintro.\nsubst B.\napply H18.\nexists C.\nsplit; Col.\n\nassert(Par C D A B).\napply (par_col_par_2 _ D').\nunfold Out in H.\nspliter.\nauto.\napply out_col in H.\nCol.\napply par_symmetry.\napply par_right_comm.\nleft.\nassumption.\n\nassert(Par_strict A B C D).\napply par_strict_symmetry.\ninduction H21.\nauto.\nspliter.\napply False_ind.\napply H17.\nCol.\n\ninduction(col_dec A B T).\napply False_ind.\nassert(B = T).\napply (l6_21 A B C B); Col.\nsubst T.\napply H22.\nexists D.\napply bet_col in H14.\nsplit; Col.\n\ninduction(col_dec C D T).\napply False_ind.\nassert(C = T).\napply (l6_21 C D B C); Col.\nsubst T.\napply H22.\nexists A.\napply bet_col in H14.\nsplit; Col.\n\ninduction H13.\n\nassert(OS B A T D).\napply (out_one_side_1 _ _ _ _ A); Col.\n\nunfold Out.\nrepeat split.\nintro.\nsubst T.\napply H23.\nCol.\nintro.\nsubst D.\napply H22.\nexists A.\nsplit; Col.\nleft.\nauto.\n\nassert(OS B A T C).\napply (one_side_transitivity _ _ _ D).\napply H25.\napply (par_strict_one_side _ _ _ C).\napply par_strict_comm.\napply H22.\nCol.\n\nassert(TS B A T C).\nunfold TS.\nrepeat split; Col.\nexists B.\nsplit; Col.\napply l9_9 in H26.\ncontradiction.\nassumption.\n\ninduction H13.\n\nassert(OS C D T A).\napply (out_one_side_1 _ _ _ _ D).\nauto.\nCol.\nunfold Out.\nrepeat split.\nintro.\nsubst T.\napply H24.\nCol.\nintro.\nsubst D.\napply H22.\nexists A.\nsplit; Col.\nleft.\nBetween.\nassert(OS C D T B).\napply (one_side_transitivity _ _ _ A).\napply H25.\napply (par_strict_one_side _ _ _ B).\napply par_strict_symmetry.\napply H22.\nCol.\n\nassert(TS C D T B).\nunfold TS.\nrepeat split.\nunfold Out in H.\nspliter.\nauto.\n\nintro.\napply H24.\nCol.\nintro.\napply H22.\nexists B.\nsplit; Col.\nexists C.\nsplit.\nCol.\nBetween.\napply l9_9 in H27.\ncontradiction.\nexists T.\nsplit; Between.\n\nassert(HH:= plgf_bet A B C D' H0).\n\ninduction (eq_dec_points A D').\nsubst D'.\nunfold Parallelogram_flat in H0.\nspliter.\nassert(B = C \\/ Midpoint A B C).\napply l7_20.\nCol.\nCong.\ninduction H9.\nsubst C.\ntauto.\nexists A.\nsplit.\nBetween.\napply midpoint_bet.\nassumption.\n\ninduction (eq_dec_points B C).\nsubst C.\nunfold Parallelogram_flat in H0.\nspliter.\nassert(A = D' \\/ Midpoint B A D').\napply l7_20.\nCol.\nCong.\ninduction H10.\nsubst D'.\ntauto.\nexists B.\nsplit.\ninduction H10.\nunfold Out in H.\nspliter.\ninduction H13.\napply (between_inner_transitivity _ _ _ D').\napply H10.\nauto.\napply (outer_transitivity_between _ _ D').\napply H10.\nauto.\nauto.\nBetween.\n\ninduction HH.\nspliter.\nexists A.\nsplit.\nBetween.\napply (outer_transitivity_between _ _ D'); Between.\n\ninduction H7.\nspliter.\nexists A.\nsplit.\nBetween.\napply between_symmetry.\napply (outer_transitivity_between _ _ D'); Between.\n\ninduction H7.\nspliter.\nexists C.\nsplit.\ninduction H.\nspliter.\ninduction H10.\nassert(Bet C B D \\/ Bet C D B).\napply (l5_3 _ _ _ D'); auto.\ninduction H11.\napply (outer_transitivity_between _ _ B); Between.\napply (between_inner_transitivity _ _ _ B).\napply H7.\nauto.\napply (outer_transitivity_between _ _ B); Between.\napply (between_exchange4 _ _ D').\napply H8.\nauto.\nBetween.\nspliter.\n\nexists B.\nsplit.\nunfold Out in H.\nspliter.\ninduction H10.\nassert(Bet B C D).\napply (between_inner_transitivity _ _ _ D').\napply H8.\nassumption.\neBetween.\n\napply (outer_transitivity_between _ _ C).\napply H7.\napply (outer_transitivity_between _ _ D' ).\napply H8.\nauto.\nauto.\nauto.\nBetween.\nspliter.\nsubst B.\nsubst D'.\nexists A.\nsplit; Between.\nQed.\n\nLemma one_side_col_out :\n forall A B X Y,\n  Col A X Y ->\n  OS A B X Y ->\n  Out A X Y.\nProof.\nintros.\nassert(A <> B /\\ ~ Col X A B /\\ ~ Col Y A B /\\ X <> A /\\ Y <> A).\nunfold OS in H0.\nex_and H0 T.\nunfold TS in *.\nspliter.\nrepeat split; auto.\nintro.\nsubst B.\nCol.\nintro.\nsubst X.\napply H0.\nCol.\nintro;\nspliter.\nsubst Y.\napply H1.\nCol.\nspliter.\n\ninduction H.\nrepeat split; auto.\ninduction H.\nrepeat split; auto.\nright.\nBetween.\n\nassert(TS A B X Y).\nunfold TS.\nrepeat split; auto.\nexists A.\nsplit.\nCol.\nBetween.\napply l9_9 in H6.\ncontradiction.\nQed.\n\nLemma par_ts_same_dir :\n forall A B C D, Par_strict A B C D ->\n (exists M, Bet A M D /\\ Bet B M C) ->\n Same_dir A B C D.\nProof.\nintros.\nex_and H0 M.\nunfold Same_dir.\nright.\n\nassert(HH:=vector_construction A B C).\nex_and HH D'.\nexists D'.\nsplit; trivial.\n\nassert(A <> B /\\ C <> D).\napply par_strict_distinct in H.\nspliter.\nsplit; auto.\nspliter.\n\nassert(A <> M).\nintro.\nsubst M.\napply False_ind.\napply H.\nexists C.\napply bet_col in H1.\nsplit; Col.\n\ninduction (eq_dec_points B D').\nsubst D'.\nassert( A = C).\napply (vector_uniqueness B).\napply eqv_comm.\napply H2.\nsubst C.\n\nassert(Bet A D B \\/ Bet A B D).\napply (l5_1 _ M).\napply H5.\nauto.\nBetween.\nunfold Out.\nrepeat split; auto.\ninduction H2.\n\nassert(Par A B D' C).\napply plg_par in H2; auto.\nspliter.\nauto.\n\nassert(Col C D D').\napply col_permutation_1.\napply (parallel_uniqueness A B _ _ C _ C).\nleft.\napply H.\nCol.\napply par_right_comm.\napply H7.\nCol.\n\ninduction H2.\n\nassert(HH := (plgs_two_sides A B D' C H2)).\nspliter.\n\nassert(TS B C A D).\nunfold TS.\nunfold TS in H10.\nspliter.\nrepeat split;\nauto.\nintro.\napply H11.\nColR.\nexists M.\nsplit.\napply bet_col in H1.\nCol.\nauto.\n\nassert(OS B C D D').\napply (l9_8_1 _ _ _ _ A).\napply l9_2.\napply H11.\napply l9_2.\nauto.\n\napply (one_side_col_out _ B).\nCol.\napply invert_one_side.\napply H12.\n\napply False_ind.\nunfold Parallelogram_flat in H2.\nspliter.\napply H.\nexists C.\nsplit; Col.\n\nspliter.\nsubst D'.\nsubst B.\ntauto.\nQed.\n\nLemma same_dir_out : forall A B C, Same_dir A B A C -> Out A B C \\/ A = B /\\ A = C.\nintros.\nunfold Same_dir in H.\ninduction H.\nright.\nauto.\nex_and H D'.\nunfold EqV in H0.\ninduction H0.\ninduction H0.\napply plgs_par_strict in H0.\nspliter.\napply False_ind.\napply H1.\nexists B.\nsplit; Col.\napply plgf_permut in H0.\napply plgf_sym in H0.\napply plgf_trivial_neq in H0.\nspliter.\nsubst D'.\nleft.\napply l6_6.\nassumption.\nspliter.\nsubst D'.\nsubst B.\nunfold Out in H.\ntauto.\nQed.\n\nLemma same_dir_out1 : forall A B C, Same_dir A B B C -> Out A B C \\/ A = B /\\ A = C.\nintros.\nunfold Same_dir in H.\ninduction H.\nright.\nspliter.\nsubst B.\ntauto.\nex_and H D'.\nunfold EqV in H0.\n\ninduction H0.\ninduction H0.\napply plgs_par_strict in H0.\nspliter.\napply False_ind.\napply H1.\nexists B.\nsplit; Col.\nunfold Parallelogram_flat in H0.\nspliter.\nassert(A = D' \\/ Midpoint B A D').\napply l7_20.\nCol.\nCong.\ninduction H5.\nsubst D'.\ntauto.\nleft.\nunfold Midpoint in H5.\nspliter.\nunfold Out.\nrepeat split.\nintro.\nsubst B.\napply cong_symmetry in H6.\napply cong_identity in H6.\ninduction H4; tauto.\nintro.\nsubst C.\nunfold Out in H.\nspliter.\ninduction H8.\napply H.\napply (between_equality _ _ D');\nBetween.\napply H7.\napply (between_equality _ _ A);\nBetween.\ninduction H.\nspliter.\ninduction H8.\nleft.\napply (between_inner_transitivity _ _ _ D').\napply H5.\napply H8.\nleft.\napply (outer_transitivity_between _ _  D').\napply H5.\nauto.\nauto.\nspliter.\nsubst B.\nsubst D'.\nunfold Out in H.\ntauto.\nQed.\n\nLemma same_dir_null : forall A B C, Same_dir A A B C -> B = C.\nintros.\nunfold Same_dir in H.\ninduction H.\ntauto.\nex_and H D.\napply null_vector in H0.\nsubst D.\nunfold Out in H.\ntauto.\nQed.\n\n\n\nLemma plgs_out_plgs :\n forall A B C D B' C',\n Parallelogram_strict A B C D ->\n Out A B B' ->\n Out D C C' ->\n Cong A B' D C' ->\n Parallelogram_strict A B' C' D.\nProof.\nintros.\nassert(OS A D C B /\\ OS C B A D).\napply plgs_one_side.\napply plgs_permut.\napply plgs_comm2.\nassumption.\n\nassert( A <> B /\\ A <> B' /\\ D <> C /\\ D <> C').\nunfold Out in *.\nspliter.\nrepeat split; auto.\nspliter.\n\nassert(Par_strict A B C D).\napply plgs_par_strict in H.\nspliter.\nauto.\n\nassert(Par_strict A B' D C').\nassert(Par A B' D C').\napply (par_col_par_2 _ B).\nauto.\napply out_col.\nauto.\napply par_symmetry.\napply (par_col_par_2 _ C).\nauto.\napply out_col.\nauto.\napply par_symmetry.\napply par_right_comm.\nleft.\nauto.\ninduction H10.\nauto.\nspliter.\napply False_ind.\napply out_col in H0.\napply out_col in H1.\n\nassert(~Col A C D).\nintro.\napply H9.\nexists A.\nsplit; Col.\napply H14.\nColR.\n\nassert(OS A D B B').\napply (out_one_side_1 A _ _ _ A).\nintro.\napply H9.\nexists D.\nsplit; Col.\nCol.\nauto.\n\nassert(OS A D C C').\napply (out_one_side_1 _ D _ _ D).\nintro.\napply H9.\nexists A.\nsplit; Col.\nCol.\nauto.\n\nassert(OS A D B' C').\napply (one_side_transitivity _ _ _ B).\napply one_side_symmetry.\napply H11.\napply (one_side_transitivity _ _ _ C).\napply one_side_symmetry.\napply H3.\nassumption.\n\n\nassert(HH:=par_cong_mid_os  A B' D C' H10 H2 H13).\nex_and HH M.\n\napply (mid_plgs _ _ _ _ M).\nintro.\napply H10.\nexists C'.\nsplit; Col.\nassumption.\nassumption.\nQed.\n\nLemma plgs_plgs_bet :\n forall A B C D B' C',\n Parallelogram_strict A B C D ->\n Bet A B B' ->\n Parallelogram_strict A B' C' D ->\n Bet D C C'.\nProof.\nintros.\nassert(Col C' C D /\\ Col D C D).\napply (parallel_uniqueness A B C D C' D D); Col.\nleft.\napply plgs_par_strict in H.\nspliter.\nassumption.\napply (par_col_par_2 _ B').\nintro.\nsubst B.\napply plgs_par_strict in H.\nspliter.\napply H.\nexists C.\nsplit; Col.\napply bet_col in H0.\nCol.\napply plgs_par_strict in H1.\nspliter.\nleft.\nassumption.\nspliter.\nclear H3.\ninduction H2.\nBetween.\ninduction H2.\napply False_ind.\n\napply plgs_permut in H.\napply plgs_permut in H1.\n\nassert(HH1:=plgs_one_side B C D A H).\nassert(HH2:=plgs_one_side B' C' D A H1).\nspliter.\nassert(OS D A C C').\napply (one_side_transitivity _ _ _ B).\napply one_side_symmetry.\napply H6.\napply one_side_symmetry.\napply (one_side_transitivity _ _ _ B').\napply one_side_symmetry.\napply H4.\napply (out_one_side_1 _ _ _ _ A).\nintro.\napply plgs_par_strict in H1.\nspliter.\napply H1.\nexists B'.\nsplit; Col.\nCol.\nrepeat split.\nintro.\nsubst B'.\napply H1.\nCol.\nintro.\nsubst B.\napply H.\nCol.\nright.\nassumption.\nassert(TS D A C C').\nrepeat split.\nintro.\napply plgs_par_strict in H.\nspliter.\napply H.\nexists C.\nsplit; Col.\nintro.\napply plgs_par_strict in H1.\nspliter.\napply H1.\nexists C'.\nsplit; Col.\nexists D.\nsplit.\nCol.\nassumption.\napply l9_9 in H8.\ncontradiction.\n\nassert(Parallelogram_strict B C D A).\napply plgs_permut.\nassumption.\nassert(Parallelogram_strict D A B' C').\napply plgs_permut.\napply plgs_sym.\nassumption.\n\ninduction (eq_dec_points C C').\nsubst C'.\nBetween.\n\nassert(HH:= plgs_pseudo_trans B C D A B' C' H3 H4).\nassert(Parallelogram_strict B C C' B').\ninduction HH.\nassumption.\nunfold Parallelogram_flat in H6.\nspliter.\napply False_ind.\n\napply plgs_par_strict in H.\napply plgs_par_strict in H1.\nspliter.\napply H.\nexists B.\nsplit.\nCol.\napply bet_col in H2.\nColR.\n\nassert(HH1:=plgs_one_side B C C' B' H6).\nassert(HH2:=plgs_one_side B C D A H3).\nspliter.\n\n(*******************************)\n\nassert(TS B C A B').\nunfold TS.\nrepeat split.\nintro.\napply plgs_par_strict in H.\nspliter.\napply H.\nexists C.\nsplit; Col.\nintro.\napply plgs_par_strict in H6.\nspliter.\napply H6.\nexists B'.\nsplit; Col.\nexists B.\nsplit.\nCol.\nassumption.\n\nassert(OS B C C' D).\napply (out_one_side_1 _ _ _ _ C).\nintro.\napply plgs_par_strict in H6.\nspliter.\napply H6.\nexists C'.\nsplit; Col.\napply col_trivial_2.\nrepeat split.\nauto.\nintro.\nsubst D.\napply plgs_par_strict in H3.\nspliter.\napply H3.\nexists C.\nsplit; Col.\nleft.\nBetween.\n\nassert(OS B C A B').\napply (one_side_transitivity _ _ _ D).\napply one_side_symmetry.\napply H7.\napply (one_side_transitivity _ _ _ C').\napply one_side_symmetry.\napply H12.\nassumption.\napply l9_9 in H11.\ncontradiction.\nQed.\n\nLemma plgf_plgf_bet :\n forall A B C D B' C',\n Parallelogram_flat A B C D ->\n Bet A B B' ->\n Parallelogram_flat A B' C' D ->\n Bet D C C'.\nProof.\nintros.\ninduction (eq_dec_points A B).\nsubst B.\nassert(C = D /\\ A <> C).\napply plgf_trivial_neq.\nauto.\nspliter.\nsubst D.\nBetween.\n\nassert(HH:=not_col_exists A B H2).\nex_and HH P.\nassert(HH:=plg_existence A B P H2).\nex_and HH Q.\n\nassert(Parallelogram_strict A B P Q).\ninduction H4.\nassumption.\nunfold Parallelogram_flat in H4.\nspliter.\ncontradiction.\n\nassert(Parallelogram_strict C D Q P).\n\napply(plgf_plgs_trans C D A B P Q).\nintro.\nsubst D.\nassert(A = B /\\ C <> A).\napply plgf_trivial_neq.\napply plgf_sym.\nassumption.\ntauto.\napply plgf_sym.\nassumption.\nassumption.\n\nassert(A <> B').\nintro.\nsubst B'.\napply between_identity in H0.\ncontradiction.\n\nassert(HH:=vector_construction A B' Q).\nex_and HH P'.\n\ninduction H8; [|tauto].\n\nassert(B <> P).\nintro.\nsubst P.\napply H3.\nCol.\n\nassert(B' <> P').\nintro.\nsubst P'.\n\ninduction H8.\napply plgs_par_strict in H8.\nspliter.\napply H10.\napply plgs_par_strict in H5.\nexists A.\nsplit; Col.\napply plgf_permut in H8.\nassert(Q = A /\\ B' <> Q).\napply plgf_trivial_neq.\nauto.\nspliter.\nsubst Q.\napply H5.\nCol.\n\nassert(Par A B' P Q).\napply plg_par in H8; auto.\nspliter.\napply bet_col in H0.\n\napply (par_col_par_2 _ B); auto.\napply plg_par in H4; auto.\nspliter.\nassumption.\n\nassert(Col P' P Q /\\ Col Q P Q).\napply(parallel_uniqueness A B' P Q P' Q Q ); Col.\napply plg_par in H8; auto.\nspliter.\nauto.\nspliter.\nclear H13.\n\nassert(Parallelogram_strict A B' P' Q).\ninduction H8.\nauto.\nunfold Parallelogram_flat in H8.\nspliter.\napply False_ind.\nunfold Parallelogram_flat in *.\nspliter.\napply bet_col in H0.\nassert(Col B' P' Q).\nColR.\n\napply plgs_par_strict in H5.\nspliter.\napply H5.\nexists Q.\nsplit.\nColR.\nCol.\n\nassert(Parallelogram_strict D C' P' Q).\napply (plgf_plgs_trans _ _ B' A).\nintro.\nsubst C'.\napply plgf_sym in H1.\napply plgf_trivial_neq in H1.\ntauto.\napply plgf_comm2.\napply plgf_sym.\napply H1.\napply plgs_comm2.\nassumption.\n\nassert(Bet Q P P').\napply(plgs_plgs_bet A B P Q B' P'); auto.\napply(plgs_plgs_bet Q P C D P' C').\napply plgs_sym.\nauto.\nauto.\napply plgs_comm2.\napply plgs_sym.\nauto.\nQed.\n\nLemma plg_plg_bet :\n forall A B C D B' C',\n Parallelogram A B C D ->\n Bet A B B' ->\n Parallelogram A B' C' D ->\n Bet D C C'.\nProof.\nintros.\n\ninduction(eq_dec_points A B).\nsubst B.\ninduction H.\napply False_ind.\napply H.\napply plgs_sym in H.\napply False_ind.\napply H.\nCol.\napply plgf_trivial_neq in H.\nspliter.\nsubst D.\nBetween.\n\ninduction (eq_dec_points B C).\nsubst C.\ninduction H.\napply False_ind.\napply plgs_sym in H.\napply H.\nCol.\napply plgf_permut in H.\napply plgf_trivial_neq in H.\nspliter.\nsubst D.\ninduction H1.\napply False_ind.\napply H.\nCol.\napply plgf_permut in H.\napply plgf_sym in H.\napply plgf_trivial_neq in H.\nspliter.\nsubst C'.\nBetween.\n\nassert(A <> B').\nintro.\nsubst B'.\napply between_identity in H0.\ncontradiction.\n\nassert(B' <> C').\nintro.\nsubst C'.\napply plg_permut in H1.\ninduction H1.\napply plgs_par_strict in H1.\nspliter.\napply H1.\nexists A.\nsplit; Col.\napply plgf_trivial_neq in H1.\nspliter.\nsubst D.\napply plg_permut in H.\ninduction H.\napply plgs_par_strict in H.\nspliter.\napply H1.\nexists A.\nsplit; Col.\napply plgf_sym in H.\napply plgf_trivial_neq in H.\ntauto.\n\nassert(HH:=H).\nassert(HH1:=H1).\n\napply plg_par in H; auto.\napply plg_par in H1; auto.\nspliter.\n\nassert(Par A B C' D).\napply (par_col_par_2 _ B'); auto.\napply bet_col in H0.\nCol.\n\nassert(Col C' C D /\\ Col D C D).\n\napply(parallel_uniqueness A B C D C' D D); Col.\nspliter.\nclear H10.\n\ninduction HH; induction HH1.\napply (plgs_plgs_bet A B _ _ B').\napply H10.\napply H0.\nauto.\n\napply False_ind.\nunfold Parallelogram_flat in H11.\nspliter.\napply plgs_par_strict in H10.\nspliter.\napply bet_col in H0.\napply H10.\nassert(Col A B C').\nColR.\nexists C'.\nsplit; Col.\n\napply False_ind.\nunfold Parallelogram_flat in H10.\nspliter.\napply plgs_par_strict in H11.\nspliter.\napply bet_col in H0.\napply H11.\nassert(Col A B' C).\nColR.\nexists C.\nsplit; Col.\n\napply (plgf_plgf_bet A B _ _ B').\napply H10.\napply H0.\nauto.\nQed.\n\n\nLemma plgf_out_plgf :\n forall A B C D B' C',\n Parallelogram_flat A B C D ->\n Out A B B' ->\n Out D C C' ->\n Cong A B' D C' ->\n Parallelogram_flat A B' C' D.\nProof.\nintros.\nassert( A <> B /\\ A <> B' /\\ D <> C /\\ D <> C').\nunfold Out in *.\nspliter.\nrepeat split; auto.\nspliter.\n\nassert(HH:=not_col_exists A B H3).\nex_and HH P.\nassert(HH:=plg_existence A B P H3).\nex_and HH Q.\nassert(Parallelogram_strict A B P Q).\ninduction H8.\nassumption.\nunfold Parallelogram_flat in H8.\nspliter.\ncontradiction.\n\nassert(Parallelogram_strict C D Q P).\n\napply(plgf_plgs_trans C D A B P Q).\nauto.\napply plgf_sym.\nassumption.\nassumption.\n\nassert(HH:=vector_construction A B' Q).\nex_and HH P'.\ninduction H11.\n\nassert(B <> P).\nintro.\nsubst P.\napply plgs_par_strict in H9.\nspliter.\napply H9.\nexists B.\nsplit; Col.\n\nassert(B' <> P').\nintro.\nsubst P'.\ninduction H11.\napply plgs_par_strict in H11.\nspliter.\napply H11.\nexists B'.\nsplit; Col.\nunfold Parallelogram_flat in H11.\nspliter.\napply cong_identity in H15.\nsubst Q.\napply H9.\nCol.\n\nassert(Col Q P P').\napply plg_par in H8; auto.\napply plg_par in H11; auto.\nspliter.\n\nassert(Par A B' P Q).\napply (par_col_par_2 _ B).\nauto.\napply out_col.\napply H0.\nassumption.\n\nassert(Col P' P Q /\\ Col Q P Q).\napply(parallel_uniqueness A B' P Q P' Q Q); Col.\nspliter.\nCol.\n\n\nassert(Parallelogram_strict A B' P' Q).\ninduction H11.\nassumption.\nunfold Parallelogram_flat in H11.\nspliter.\napply False_ind.\n\napply plgs_par_strict in H9.\nspliter.\napply H9.\nexists Q.\nsplit.\n\napply out_col in H0.\nColR.\nCol.\n\nassert(P <> Q).\nintro.\nsubst Q.\napply H9.\nCol.\n\nassert(P' <> Q).\nintro.\nsubst Q.\napply H15.\nCol.\n\nassert(Parallelogram_strict D C' P' Q).\napply (plgs_out_plgs _ C P).\napply plgs_comm2.\napply H10.\nauto.\nrepeat split; auto.\n\nunfold Out in H0.\nspliter.\ninduction H19.\nleft.\n\napply (plgs_plgs_bet A B P Q B' P' H9); auto.\nright.\n\napply(plgs_plgs_bet A B' P' Q B P); auto.\n\napply plg_cong in H11.\nspliter.\nCongR.\n\nassert(Parallelogram A B' C' D).\napply (plgs_pseudo_trans _ _ P' Q).\napply H15.\napply plgs_sym.\nassumption.\ninduction H19.\napply False_ind.\napply plgs_par_strict in H19.\nspliter.\nunfold Parallelogram_flat in H.\nspliter.\napply out_col in H0.\napply out_col in H1.\n\napply H19.\nexists B.\nsplit.\n\nCol.\nassert(Col B C D).\nColR.\nColR.\nassumption.\nspliter.\nsubst B'.\ntauto.\nQed.\n\n\n\n\nLemma plg_out_plg : \n forall A B C D B' C',\n Parallelogram A B C D ->\n Out A B B' ->\n Out D C C' ->\n Cong A B' D C' ->\n Parallelogram A B' C' D.\nProof.\nintros.\ninduction H.\nleft.\napply (plgs_out_plgs _ B C).\napply H.\nauto.\nauto.\nauto.\nright.\napply (plgf_out_plgf _ B C).\napply H.\nauto.\nauto.\nauto.\nQed.\n\n\nLemma same_dir_sym : forall A B C D, Same_dir A B C D -> Same_dir C D A B.\nintros.\n\ninduction (eq_dec_points A B).\nsubst B.\napply same_dir_null in H.\nsubst D.\nleft.\ntauto.\n\nunfold Same_dir in *.\ninduction H.\nleft.\ntauto.\n\nex_and H D'.\nright.\nassert(HH:=vector_construction C D A).\nex_and HH B'.\nexists B'.\nsplit.\nunfold EqV in H1.\nunfold EqV in H2.\nunfold Out in *.\nspliter.\ninduction H1; induction H2.\n\n\nrepeat split.\nauto.\nintro.\nsubst B'.\ninduction H2.\napply H2.\nCol.\napply plgf_sym in H2.\napply plgf_trivial_neq in H2.\nspliter.\nauto.\n\ninduction H4.\nright.\napply (plg_plg_bet C D _ _ D').\napply H2.\napply H4.\napply plg_sym.\napply plg_comm2.\nassumption.\n\nleft.\napply (plg_plg_bet C D' _ _ D).\napply plg_sym.\napply plg_comm2.\napply H1.\napply H4.\nassumption.\n\nspliter.\nsubst D.\ntauto.\nspliter.\nsubst B.\ntauto.\nspliter.\nsubst D.\ntauto.\nassumption.\nQed.\n\n\nLemma same_dir_trans : forall A B C D E F, Same_dir A B C D -> Same_dir C D E F -> Same_dir A B E F.\nintros.\nunfold Same_dir in *.\ninduction H; induction H0; spliter.\nleft.\ntauto.\nex_and H0 F'.\nsubst B.\nsubst D.\napply null_vector in H2.\nsubst F'.\nunfold Out in H0.\ntauto.\nex_and H D'.\nsubst D.\nsubst F.\nunfold Out in H.\ntauto.\nex_and H D'.\nex_and H0 F'.\nright.\n\n\ninduction(eq_dec_points A B).\nsubst B.\napply null_vector in H1.\nsubst D'.\nunfold Out in H.\ntauto.\n\nassert(HH:=vector_construction A B E).\nex_and HH F''.\nexists F''.\nsplit; trivial.\n\nassert(C <> D /\\ C <> D' /\\ E <> F /\\ E <> F').\nunfold Out in *.\nspliter.\nrepeat split;\nauto.\nspliter.\n\nunfold EqV in *.\ninduction H1; induction H2; induction H4.\nunfold Out in *.\nspliter.\ninduction H10; induction H12.\nrepeat split.\nauto.\nintro.\nsubst F''.\n\ninduction H4.\napply H4.\nCol.\napply plgf_sym in H4.\napply plgf_trivial_neq in H4.\ntauto.\n\nleft.\nassert(Bet E F' F'').\n\napply (plg_plg_bet C D _ _ D').\napply H2.\napply H12.\n\nassert(Parallelogram C D' F'' E \\/ C = D' /\\ B = A /\\ E = F'' /\\ C = E).\n\napply(plg_pseudo_trans C D' B A E F'').\napply plg_sym.\napply plg_comm2.\nauto.\napply plg_comm2.\nauto.\ninduction H13.\nassumption.\ntauto.\napply (between_exchange4 _ _ F').\napply H10.\nauto.\n\nrepeat split.\nauto.\nintro.\nsubst F''.\ninduction H4.\napply H4.\nCol.\napply plgf_sym in H4.\napply plgf_trivial_neq in H4.\ntauto.\n\nassert(Bet E F'' F').\napply (plg_plg_bet C D' _ _ D); trivial.\n\nassert(Parallelogram C D' F'' E \\/ C = D' /\\ B = A /\\ E = F'' /\\ C = E).\napply plg_pseudo_trans.\napply plg_sym.\napply plg_comm2.\nauto.\napply plg_comm2.\nauto.\n\ninduction H13.\nassumption.\ntauto.\napply (l5_3 _ _ _ F').\napply H10.\nassumption.\n\nrepeat split.\nauto.\nintro.\nsubst F''.\ninduction H4.\napply H4.\nCol.\napply plgf_sym in H4.\napply plgf_trivial_neq in H4.\ntauto.\n\nassert(Bet E F' F'').\napply (plg_plg_bet C D _ _ D').\napply H2.\napply H12.\nassert(Parallelogram C D' F'' E \\/ C = D' /\\ B = A /\\ E = F'' /\\ C = E).\napply plg_pseudo_trans.\napply plg_sym.\napply plg_comm2.\nauto.\napply plg_comm2.\nauto.\n\ninduction H13.\nassumption.\ntauto.\napply (l5_1 _ F').\napply H8.\nauto.\nauto.\n\nrepeat split.\nauto.\nintro.\nsubst F''.\ninduction H4.\napply H4.\nCol.\napply plgf_sym in H4.\napply plgf_trivial_neq in H4.\ntauto.\n\nassert(Bet E F'' F').\napply (plg_plg_bet C D' _ _ D); trivial.\n\nassert(Parallelogram C D' F'' E \\/ C = D' /\\ B = A /\\ E = F'' /\\ C = E).\napply plg_pseudo_trans.\napply plg_sym.\napply plg_comm2.\nauto.\napply plg_comm2.\nauto.\n\ninduction H13.\nauto.\ntauto.\nright.\napply (between_exchange4 _ _ F').\napply H13.\nauto.\ntauto.\ntauto.\ntauto.\ntauto.\ntauto.\ntauto.\ntauto.\nQed.\n\nLemma same_dir_comm : forall A B C D, Same_dir A B C D -> Same_dir B A D C.\nintros.\n\nunfold Same_dir in *.\ninduction H.\nleft.\nauto.\nspliter.\nsplit; auto.\n\nright.\nex_and H D'.\nassert(A <> B).\nintro.\nsubst B.\napply null_vector in H0.\nunfold Out in H.\nspliter.\nauto.\n\nassert(HH:=vector_construction B A D).\nex_and HH C'.\nexists C'.\nsplit; trivial.\n\nunfold Out in *.\nspliter.\n\nunfold EqV in *.\n\ninduction H4.\nrepeat split.\nauto.\nintro.\nsubst C'.\napply eqv_sym in H2.\napply null_vector in H2.\nsubst B.\ntauto.\nleft.\n\ninduction H0; induction H2;try tauto.\n\nassert(Parallelogram C D' D C' \\/ C = D' /\\ B = A /\\ C' = D /\\ C = C').\n\napply(plg_pseudo_trans C D' B A C' D).\napply plg_sym.\napply plg_comm2.\nassumption.\nassumption.\ninduction H5.\n\nassert(Parallelogram_flat C D' D C').\ninduction H5.\napply False_ind.\napply plgs_par_strict in H5.\nspliter.\napply H5.\nexists D.\napply bet_col in H4.\nsplit; Col.\nassumption.\n\nunfold Parallelogram_flat in H6.\nspliter.\n\napply (col_cong2_bet1 D').\nCol.\nBetween.\nCong.\nCong.\nspliter.\nsubst B.\ntauto.\nspliter.\nsubst B.\ntauto.\n\nrepeat split.\nauto.\nintro.\nsubst C'.\ninduction H2.\ninduction H2.\napply H2.\nCol.\napply plgf_sym in H2.\napply plgf_trivial_neq in H2.\nspliter.\nauto.\nspliter.\nauto.\n\n\ninduction H0; induction H2;try tauto.\n\ninduction(eq_dec_points C C').\nsubst C'.\nleft.\nBetween.\n\nassert(Parallelogram C D' D C' \\/ C = D' /\\ B = A /\\ C' = D /\\ C = C').\n\napply(plg_pseudo_trans C D' B A C' D).\napply plg_sym.\napply plg_comm2.\nassumption.\nassumption.\ninduction H6.\n\nassert(Parallelogram_flat C D' D C').\ninduction H6.\napply False_ind.\napply plgs_par_strict in H6.\nspliter.\napply H6.\nexists D.\napply bet_col in H4.\nsplit; Col.\nassumption.\n\nright.\n\nassert(HH:= H7).\nunfold Parallelogram_flat in H7.\nspliter.\n\napply plgf_bet in HH.\ninduction HH.\nspliter.\n\napply False_ind.\n\napply H3.\napply (between_equality _ _ D).\napply between_symmetry.\napply H13.\nassumption.\ninduction H12.\nspliter.\n\nassert(D = D').\napply (between_equality _ _ C).\nBetween.\nBetween.\nsubst D'.\n\napply cong_identity in H10.\ncontradiction.\n\ninduction H12.\nspliter.\neBetween.\n\nspliter.\neBetween.\nspliter.\nsubst B.\ntauto.\nspliter.\nsubst B.\ntauto.\nQed.\n\nLemma bet_same_dir1 : forall A B C, A <> B -> B <> C -> Bet A B C -> Same_dir A B A C.\nintros.\nunfold Same_dir.\nright.\nexists B.\nsplit.\nunfold Out.\nrepeat split.\nintro.\nsubst C.\napply between_identity in H1.\ntauto.\nauto.\nright.\nassumption.\napply eqv_refl.\nQed.\n\nLemma bet_same_dir2 : forall A B C, A <> B -> B <> C -> Bet A B C -> Same_dir A B B C.\nintros.\nunfold Same_dir.\nright.\nassert(HH:=vector_construction A B B).\nex_and HH C'.\nexists C'.\nsplit; trivial.\nunfold EqV in H2.\ninduction H2; [|tauto].\n\ninduction H2.\napply plgs_par_strict in H2.\nspliter.\napply False_ind.\napply H3.\nexists B.\nsplit; Col.\nassert(HH:= H2).\nunfold Parallelogram_flat in HH.\napply plgf_bet in H2.\nspliter.\n\nunfold Out.\nrepeat split.\nauto.\nintro.\nsubst C'.\napply cong_identity in H5.\ncontradiction.\n\ninduction H2.\n\nassert(Bet B A B).\nspliter.\napply (outer_transitivity_between2 _ C').\nBetween.\nauto.\ninduction H7.\nauto.\ntauto.\napply between_identity in H8.\nsubst B.\ntauto.\ninduction H2.\n\nassert(Bet B A B).\nspliter.\napply (outer_transitivity_between _ _ C').\napply H2.\nauto.\ninduction H7.\nauto.\ntauto.\napply between_identity in H8.\nsubst B.\ntauto.\n\ninduction H2.\n\nassert( A = C' \\/ Midpoint B A C').\napply l7_20.\nCol.\nCong.\ninduction H8.\ninduction H7.\ntauto.\ntauto.\nunfold Midpoint in H8.\nspliter.\napply (l5_2 A); auto.\n\nassert( A = C' \\/ Midpoint B A C').\napply l7_20.\nCol.\nCong.\ninduction H8.\ninduction H7.\ntauto.\ntauto.\nunfold Midpoint in H8.\nspliter.\napply (l5_2 A); auto.\nQed.\n\nLemma plg_opp_dir : forall A B C D, Parallelogram A B C D -> Same_dir A B D C.\nintros.\n\ninduction(eq_dec_points A B).\nsubst B.\ninduction H.\napply False_ind.\napply plgs_sym in H.\napply H.\nCol.\napply plgf_trivial_neq in H.\nspliter.\nsubst D.\nleft.\ntauto.\n\nunfold Same_dir.\nright.\nexists C.\nsplit.\napply out_trivial.\nintro.\nsubst D.\ninduction H.\napply H.\nCol.\napply plgf_sym in H.\napply plgf_trivial_neq in H.\ntauto.\nunfold EqV.\nleft.\nassumption.\nQed.\n\nLemma same_dir_dec : forall A B C D,\n  Same_dir A B C D \\/ ~ Same_dir A B C D.\nProof.\nintros.\nunfold Same_dir.\nunfold EqV.\nelim (eq_dec_points A B); intro HAB;\nelim (eq_dec_points C D); intro HCD; try tauto.\n\n  right; intro HFalse.\n  elim HFalse; clear HFalse; intro HFalse.\n\n    spliter; intuition.\n\n    destruct HFalse as [E [HFalse HElim]].\n    elim HElim; clear HElim; intro HElim.\n\n      subst.\n      apply plg_cong in HElim.\n      destruct HElim as [HCong1 HCong2].\n      treat_equalities.\n      apply out_diff2 in HFalse; intuition.\n\n      destruct HElim as [Hclear HCE]; clear Hclear; subst.\n      apply out_diff2 in HFalse; intuition.\n\n  right; intro HFalse.\n\n  elim HFalse; clear HFalse; intro HFalse.\n\n    spliter; intuition.\n\n    destruct HFalse as [E [HFalse Hclear]]; clear Hclear.\n    subst.\n    apply out_diff1 in HFalse; intuition.\n\n  assert (H := plg_existence B A C).\n  assert (HPar : B <> A) by auto.\n  apply H in HPar; clear H.\n  destruct HPar as [E HPar].\n  elim (out_dec C D E); intro Hout.\n\n    left.\n    right.\n    exists E.\n    split; try assumption.\n    left.\n    apply plg_comm2 in HPar.\n    assumption.\n\n    right.\n    intro H.\n    elim H; clear H; intro H.\n\n      spliter; subst; intuition.\n\n      destruct H as [F [Hout' HElim]].\n      elim HElim; clear HElim; intro HElim.\n\n        apply plg_comm2 in HElim.\n        assert (HEF := plg_uniqueness B A C E F HPar HElim).\n        subst; intuition.\n\n        spliter; intuition.\nQed.\n\nLemma same_or_opp_dir : forall A B C D, Par A B C D -> Same_dir A B C D \\/ Opp_dir A B C D.\nintros.\ninduction (same_dir_dec A B C D).\nleft.\nassumption.\nright.\nunfold Opp_dir.\n\nunfold Same_dir.\nright.\nassert(HH:= vector_construction A B D).\nex_and HH C'.\nexists C'.\nsplit; trivial.\nunfold EqV in H1.\n\ninduction (eq_dec_points B C').\nsubst C'.\ninduction H1.\n\ninduction H1.\napply False_ind.\napply plgs_permut in H1.\napply plgs_sym in H1.\napply H1.\nCol.\napply plgf_permut in H1.\napply plgf_trivial_neq in H1.\nspliter.\nsubst D.\ninduction H.\napply False_ind.\napply H.\nexists A.\nsplit; Col.\nspliter.\ninduction H4.\nunfold Out.\nrepeat split; auto.\nleft.\nBetween.\ninduction H4.\nunfold Out.\nrepeat split; auto.\napply False_ind.\napply H0.\napply same_dir_sym.\napply bet_same_dir2; auto.\nunfold Out.\nrepeat split.\nauto.\nauto.\nright.\nassumption.\nspliter.\nsubst A.\nsubst D.\napply par_distinct in H.\ntauto.\n\ninduction H1.\n\nassert(Col C' C D /\\ Col D C D).\napply plg_par in H1.\nspliter.\n\napply(parallel_uniqueness A B C D C' D D); Col.\napply par_distinct in H.\ntauto.\nassumption.\nspliter.\nclear H4.\n\nunfold Out.\nrepeat split.\napply par_distinct in H.\ntauto.\nintro.\nsubst C'.\ninduction H1.\napply H1.\nCol.\napply plgf_sym in H1.\napply plgf_trivial_neq in H1.\nspliter.\napply par_distinct in H.\ntauto.\n\ninduction H3.\nleft.\nBetween.\ninduction H3.\napply False_ind.\n\nassert(Same_dir A B D C').\napply plg_opp_dir.\nassumption.\n\nassert(Same_dir C D D C').\napply bet_same_dir2.\napply par_distinct in H.\nspliter.\nauto.\nintro.\nsubst C'.\ninduction H1.\napply H1.\nCol.\napply plgf_sym in H1.\napply plgf_trivial_neq in H1.\nspliter.\napply par_distinct in H.\ntauto.\nassumption.\napply False_ind.\napply H0.\napply (same_dir_trans _ _ D C').\napply H4.\napply same_dir_sym.\nauto.\nright.\nassumption.\napply par_distinct in H.\ntauto.\nQed.\n\nLemma same_dir_id : forall A B, Same_dir A B B A -> A = B.\nintros.\nunfold Same_dir in H.\ninduction H.\ntauto.\nex_and H C.\napply eqv_mid in H0.\nunfold Midpoint in H0.\nunfold Out in H.\nspliter.\ninduction H3.\napply (between_equality _ _ C).\napply H0.\nassumption.\napply False_ind.\napply H2.\napply (between_equality _ _ A).\nBetween.\nassumption.\nQed.\n\nLemma opp_dir_id : forall A B, Opp_dir A B A B -> A = B.\nintros.\nunfold Opp_dir in H.\napply same_dir_id in H.\nauto.\nQed.\n\n\nLemma same_dir_to_null : forall A B C D, Same_dir A B C D -> Same_dir A B D C -> A = B /\\ C = D.\nintros.\n\nassert(Same_dir C D D C).\napply (same_dir_trans _ _ A B).\napply same_dir_sym.\napply H.\nassumption.\napply same_dir_id in H1.\nsubst D.\napply same_dir_sym in H.\napply same_dir_null in H.\nsubst B.\ntauto.\nQed.\n\nLemma opp_dir_to_null : forall A B C D, Opp_dir A B C D -> Opp_dir A B D C -> A = B /\\ C = D.\nunfold Opp_dir.\nintros.\napply same_dir_to_null; auto.\nQed.\n\nLemma same_not_opp_dir : forall A B C D, A <> B -> Same_dir A B C D -> ~ Opp_dir A B C D.\nintros.\nintro.\napply same_dir_to_null in H0.\ntauto.\nassumption.\nQed.\n\nLemma opp_not_same_dir : forall A B C D, A <> B -> Opp_dir A B C D -> ~ Same_dir A B C D.\nunfold Opp_dir.\nintros.\nintro.\napply same_dir_to_null in H0.\ntauto.\nassumption.\nQed.\n\nLemma vector_same_dir_cong : forall A B C D, A <> B -> C <> D -> exists X, exists Y, Same_dir A B X Y /\\ Cong X Y C D.\nintros.\nexists A.\nassert(HH:=segment_construction_3 A B C D H H0).\nex_and HH P.\nexists P.\nsplit; auto.\nunfold Same_dir.\nright.\nexists B.\nsplit.\napply l6_6.\nassumption.\napply eqv_refl.\nQed.\n\nEnd Vectors.\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Tarski_dev/Annexes/vectors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7015140068984614}}
{"text": "Require Import String.\nRequire Import List.\nRequire Import Arith.\nRequire Import Nat.\n\nModule PM.\n\nExample x : string := \"12345\".\n\nInductive eProp :=\n  | TrueP : eProp\n  | FalseP : eProp\n  | UnitP : nat -> eProp\n  | InjP : eProp -> eProp -> eProp (*OR*)\n  | ConjP : eProp -> eProp -> eProp (*AND*)\n  | ImpP : eProp -> eProp -> eProp\n  | NegP : eProp -> eProp\n  | AbsP : eProp -> eProp\n  | AppP : eProp -> eProp -> eProp\n  .\n\n(* The level is slightly lower than the level for list operator :: . *)\nNotation \"# x\" := (UnitP x) (at level 58, right associativity).\nNotation \"x \\/ y\" := (InjP x y).\nNotation \"x /\\ y\" := (ConjP x y).\nNotation \"-- x\" := (NegP x) (at level 59, right associativity).\nNotation \"x =) y\" := (ImpP x y) (at level 59, right associativity).\n\n(* Inductive eFunc := (* Only takes one argument *)\n  | EFunc : string -> eProp -> eFunc. *)\n\nExample ep1 : eProp := (# 0) \\/ (# 1).\nPrint ep1.\nExample ep2 : eProp := -- (#0 /\\ #1).\nPrint ep2.\nExample ep3 : eProp := AbsP (#0). (* lambda x.x *)\nPrint ep3.\nExample ep4 := AbsP (#0).\nExample ep5 := AppP (AbsP (#2)) (#0).\n\n(* Inductive context := \n  | None : context\n  | Some : eProp -> context -> context. *)\n\n\n(* The context here is for de bruijin interpretaton, or actually the environment. \n  How about the context for deduction? *)\nNotation context := (list eProp).\n\nExample ctx_two_vars : context := #0 :: #1 :: nil.\nPrint ctx_two_vars.\n\n(************************************************)\n(* De Bruijin Index Interpretation *)\n\nInductive ePropDB :=\n  | TrueDB : ePropDB\n  | FalseDB : ePropDB\n  | UnitDB : nat -> ePropDB\n  | InjDB : ePropDB -> ePropDB -> ePropDB (*OR*)\n  | ConjDB : ePropDB -> ePropDB -> ePropDB (*AND*)\n  | ImpDB : ePropDB -> ePropDB -> ePropDB\n  | NegDB : ePropDB -> ePropDB\n  | AbsDB : ePropDB -> ePropDB\n  | AppDB : ePropDB -> ePropDB -> ePropDB\n  .\n\n(* Notation envDB := (list (nat * string)). *)\nNotation envDB := (list nat).\n\n(* Suppose the edge case never happens... *)\n\nFixpoint lookup (n : nat) (l : envDB) : nat :=\n  match l with\n  | nil => 0\n  | x :: xs => if n =? x then 0 else S (lookup n xs)\n  end.\n\nFixpoint interpX (p : eProp) (env : envDB) : ePropDB :=\n  match p with\n  | TrueP => TrueDB\n  | FalseP => FalseDB\n  | UnitP n => UnitDB (lookup n env)\n  | InjP n1 n2 => InjDB (interpX n1 env) (interpX n2 env)\n  | ConjP n1 n2 => ConjDB (interpX n1 env) (interpX n2 env)\n  | ImpP n1 n2 => ImpDB (interpX n1 env) (interpX n2 env)\n  | NegP n => NegDB (interpX n env)\n  | AbsP p => AbsDB (interpX p (0 :: map S env))\n  | AppP p1 p2 => AppDB (interpX p1 env) (interpX p2 env)\n  end.\n\nNotation \"[[ p ]]\" := (interpX p nil).\nNotation \"[[ p | env ]]\" := (interpX p env).\n\nExample interp_1 : ePropDB := [[ AbsP (#0) ]].\nCompute interp_1.\nExample interp_2 : ePropDB := [[ AbsP (AbsP (#0)) ]].\nCompute interp_2.\nExample interp_3 : ePropDB := [[ AppP (AbsP (AppP (#0) (#0))) (AbsP (AppP (#0) (#0))) ]].\nCompute interp_3.\n(* NOTE: if the env is nil, the number being returned will be directly cut down to 0. Hence \nthe interpreted number appears to be 1.\nThe thing here could be that, even in the original language the abstraction is still somehow\nfuzzy. We don't know what is x, what is y and what does the unit number means. Or maybe it\nactually saved some efforts. *)\nExample interp_4 : ePropDB := [[ AppP (AbsP (AppP (#10) (#10))) (AbsP (AppP (#10) (#10))) ]].\nCompute interp_4.\n\n(* STUB *)\nFixpoint substX (p : ePropDB) (env : list eProp) : ePropDB :=\n  match p with\n  | _ => UnitDB 100\n  end.\n\n(* STUB *)\nFixpoint evalX (p : ePropDB) (env : list eProp) : ePropDB :=\n  match p with\n  | _ => UnitDB 100\n  end.\n \n(* **************************************** *)\n(* 1ST ATTEMPT *)\n\n(* Ideal case for deep interpretation:\n\n#\"x\" /\\ #\"y\" /\\ #\"z\"\n== interpret into =>\n$0 /\\ $1 /\\ $2 <= with a \"environment\" == [($0, \"x\"), ($1, \"y\"), ($2, \"z\")]\n\nTODO:\n  if (find var in env)\n  => interpret as var\n  else => shift all vars and interpret as new var\n*)\n\n(* Definition string_eq (s1 s2 : string) : bool :=\n  match string_dec s1 s2 with\n  | left _ => true\n  | right _ => false\n  end.\n\nFixpoint findVar (s : string) (env : envDB) : bool :=\n  match env with\n  | nil => false\n  | (_, s') :: es => \n    if string_eq s s' then true \n    else findVar s es\n  end.\n\nFixpoint createVar (s : string) (env : envDB) : envDB. Admitted.\n\nFixpoint interp (p : eProp) (env : envDB) : (ePropDB, envDB) :=\n  match p with\n  | TrueP => (TrueDB, env)\n  | FalseP => (FalseDB, env)\n  (* TODO: change environment *)\n  (* TODO: carefully calculate a variable's number? *)\n  | UnitP s => if findVar s env then _ else ((UnitDB 0), env)\n  | InjP n1 n2 => match interpX n1 ctx xx, interpX n2 ctx xx with\n                  | FalseP, FalseP => FalseP\n                  | _, _ => TrueP\n                  end\n  | ConjP n1 n2 => match interpX n1 ctx xx, interpX n2 ctx xx with\n                  | TrueP, TrueP => TrueP\n                  | _, _ => FalseP\n                  end\n  | ImpP n1 n2 => match interpX n1 ctx xx, interpX n2 ctx xx with\n                  | FalseP, _ => TrueP\n                  | TrueP, TrueP => TrueP\n                  | _, _ => FalseP\n                  end\n  | NegP n => match interpX n ctx xx with\n                  | TrueP => FalseP\n                  | _ => TrueP\n                  end *)\n\n(* **************************************** *)\n(* 2ND ATTEMPT *)\n(* **************************************** *)\n\n(* Fixpoint shift (d : nat) (c : nat) (f : eProp) : eProp :=\n  match f with\n  | UnitP n =>\n      if leb c n then UnitP (d + n) else UnitP n\n  | TrueP => TrueP\n  | FalseP => FalseP\n  | InjP n1 n2 => InjP (shift d c n1) (shift d c n2)\n  | ConjP n1 n2 => ConjP (shift d c n1) (shift d c n2)\n  | ImpP n1 n2 => ImpP (shift d c n1) (shift d c n2)\n  | AbsP n1 =>\n      AbsP (shift d (c+1) n1)\n  | AppP n1 n2 =>\n      AppP (shift d c n1) (shift d c n2)\n  | NegP n => NegP (shift d c n)\n  end.\n\nFixpoint countDepth (p : eProp) (n : nat) : nat :=\n  match p with \n  | UnitP _ => n+1\n  | TrueP => n+1\n  | FalseP => n+1\n  | InjP p1 p2 => max (countDepth p1 n) (countDepth p2 n) + 1\n  | ConjP p1 p2 => max (countDepth p1 n) (countDepth p2 n) + 1\n  | ImpP p1 p2 => max (countDepth p1 n) (countDepth p2 n) + 1\n  | AbsP _ => n+1\n  | AppP p1 p2 => max (countDepth p1 n) (countDepth p2 n) + 1\n  | NegP _ => n+1\n  end.\n\n(* This interp translates and evaluates the proposition to a de bruijin term to the end \n\n   The interpretation is actually a big-step evaluation. Maybe I just need to merely \n interpret it rather than evaluate it... *)\nFixpoint interpX (p : eProp) (ctx : context) (x : nat) {struct x} : eProp :=\n  match x with\n  | 0 => FalseP\n  | S xx => match p with\n        | TrueP => TrueP\n        | FalseP => FalseP\n        | UnitP n => nth n ctx (UnitP n)\n        | InjP n1 n2 => match interpX n1 ctx xx, interpX n2 ctx xx with\n                        | FalseP, FalseP => FalseP\n                        | _, _ => TrueP\n                        end\n        | ConjP n1 n2 => match interpX n1 ctx xx, interpX n2 ctx xx with\n                        | TrueP, TrueP => TrueP\n                        | _, _ => FalseP\n                        end\n        | ImpP n1 n2 => match interpX n1 ctx xx, interpX n2 ctx xx with\n                        | FalseP, _ => TrueP\n                        | TrueP, TrueP => TrueP\n                        | _, _ => FalseP\n                        end\n        | NegP n => match interpX n ctx xx with\n                        | TrueP => FalseP\n                        | _ => TrueP\n                        end\n        (* Append a variable to environment and add 1 index to all other values *)\n        | AbsP t1 => AbsP (interpX t1 (UnitP 0 :: map (shift 1 0) ctx) xx)\n        | AppP t1 t2 => match interpX t1 ctx xx with\n                       | AbsP t3 => interpX t3 ((interpX t2 ctx xx) :: (map (shift 1 0) ctx)) xx\n                       | _ => AppP (interpX t1 ctx xx) (interpX t2 ctx xx)\n                       end\n        end\n  end.\n\nDefinition interp (p : eProp) (ctx : context) : eProp := \n  interpX p ctx (countDepth p 1). *)\n\n(* **************************************** *)\n\n(* Notation \"[[ p ]]\" := (interp p nil).\nNotation \"[[ p | ctx ]]\" := (interp p ctx).\n\nExample interp_1 : eProp := [[ ep1 ]].\nExample interp_2 : eProp := [[ ep4 | nil ]].\nExample interp_3 : eProp := [[ ep5 | (AbsP (#0)) :: (AbsP (#0)) :: nil]].\n\n(* ep5 := AppP (AbsP (#2)) (#0). *)\n(* ctx1 :=  (AbsP (#0)) :: (AbsP (#0)) :: nil *)\n(* ctx2 :=  (AbsP (#0)) :: (AbsP (#1)) :: nil *)\n(* TODO: figure out why the result is different *)\n\n(*\nAppP (AbsP (#2)) (#0) | (AbsP (#0)) :: (AbsP (#0)) :: nil\n= [(AbsP (#2)) | ctx]\n\nAppP (AbsP (#2)) (#0) | (AbsP (#0)) :: (AbsP (#1)) :: nil\n\n*)\n\nCompute interp_1.\nCompute interp_2.\nCompute interp_3. *)\n\n(************************************************)\n\n(*  \nNOTE:\nHere I have to use Set for asserted rather than Prop.\nThe reason is that eventually I have to extract some proof from the prop.\nProp is proof irrevalent while Set allows distinction.\n\n\n*)\n\nInductive asserted : ePropDB -> Set := \n  | Asserted : forall (e: ePropDB), asserted e.\n\nDefinition extract {e : ePropDB} (p : asserted e) : ePropDB := e.\n\n(* Notation Pp := (asserted). *)\n\nDefinition pp1_1 (e : eProp) : Set := asserted [[ e ]].\n(*\nasserted nil e : Prop :=\nAsserted : forall (c : context)\n\n*)\n\n(* Definition pp1_11 := forall (e1 e2: eProp),\n  asserted [[ e1 ]]\n  -> asserted [[ e1 =) e2 ]]\n  -> asserted [[ e2 ]]. *)\n\nDefinition pp1_2 (p: eProp) : Set := asserted [[ (p \\/ p) =) p ]].\n\n(* Definition pp1_3 := forall p q: eProp, Pp [[ q =) (p \\/ q) ]].\n\nDefinition pp1_4 := forall p q: eProp, Pp [[ (p \\/ q) =) (q \\/ p) ]].\n\nDefinition pp1_5 := forall p q r: eProp, Pp [[ (p \\/ (q \\/ r)) =) (q \\/ (p \\/ r)) ]].\n\nDefinition pp1_6 := forall p q r: eProp, Pp [[ (q \\/ r) =) (p \\/ q) =) (p \\/ r) ]]. *)\n\n(* Theorem pp1_7: Pp (If p is a eProp, then --p is a eProp). *)\n\n(* Theorem pp1_71: Pp (If p, q are eProps, then p \\/ q is a eProp). *)\n\n(* Theorem pp1_72: Pp (If p, q are elemental functions, then p(x) \\/ q(x) is a elemental function). *)\n\n(* Require Import Coq.Program.Equality. *)\n\nTheorem n2_01 : forall p: eProp, asserted [[ (p =) (--p)) =) (--p) ]].\nProof.\n  intros.\n  pose (pp1_2 (--p)) as pp1_2_r1.\n  change (pp1_2 (--p)) with (asserted [[ ((--p) \\/ (--p)) =) (--p) ]]) in pp1_2_r1.\n  \n(*   pose ((pp1_2 (--p)) : asserted [[ (-- p \\/ -- p) =) -- p ]]) as pp1_2_r1. *)\n(*   change (pp1_2 (--p)) with (Asserted [[ ((--p) \\/ (--p)) =) (--p) ]]) in pp1_2_r1. *)\n(*   pose (extract pp1_2_r1) as pp1_2_e. *)\n\n(*   Check pp1_2 (--p).\n  Check pp1_2_r1.\n  Fail pose (extract pp1_2_r1) as pp1_2_e. *)\n(*   change (asserted new_prop_r2) with (asserted [[ --p ]]) in new_prop.\n  clear new_prop_r1. clear new_prop_r2. *)\n  \nAdmitted.\n\nCheck n2_01.\n\n\nEnd PM.\n", "meta": {"author": "MudroadWhite", "repo": "PM-Coq-Code", "sha": "c4b0ffce9c8549b8058e7e10c8d9d1c5b69bea25", "save_path": "github-repos/coq/MudroadWhite-PM-Coq-Code", "path": "github-repos/coq/MudroadWhite-PM-Coq-Code/PM-Coq-Code-c4b0ffce9c8549b8058e7e10c8d9d1c5b69bea25/debruijin_shallowembedding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.833324587033253, "lm_q1q2_score": 0.7015139999291804}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool eqtype ssrfun ssrnat.\nRequire Import Reals Fourier.\nRequire Import ssrR Reals_ext Ranalysis_ext.\n\n(** * log_n x and n ^ x *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope R_scope.\n\nSection addtional_lemmas_about_ln_exp.\n\nLemma ln_pos x : 1 < x -> 0 < ln x.\nProof. move=> x0; rewrite -ln_1; exact: ln_increasing. Qed.\n\nLemma ln2_gt0 : 0 < ln 2. Proof. apply ln_pos; fourier. Qed.\nLocal Hint Resolve ln2_gt0.\n\nLemma ln2_neq0 : ln 2 != 0. Proof. exact/eqP/gtR_eqF. Qed.\n\nLemma ln_increasing_le a b : 0 < a -> a <= b -> ln a <= ln b.\nProof.\nmove=> Ha.\ncase/Rle_lt_or_eq_dec; last by move=> ->; exact/leRR.\nby move/(ln_increasing _ _ Ha)/ltRW.\nQed.\n\nLemma exp_le_inv x y : exp x <= exp y -> x <= y.\nProof.\ncase/Rle_lt_or_eq_dec; [move/exp_lt_inv => ?; exact/ltRW |\n  move/exp_inv => ->; exact/leRR].\nQed.\n\nLemma exp_pow n : forall k, exp (INR k * n) = (exp n) ^ k.\nProof.\nelim => [|k IH]; first by rewrite mul0R exp_0.\nby rewrite S_INR mulRDl mul1R exp_plus IH mulRC.\nQed.\n\nLemma leR2e : 2 <= exp 1.\nProof. apply Rlt_le, exp_ineq1; fourier. Qed.\n\nLemma ltRinve1 : exp (-1) < 1.\nProof. rewrite -[X in _ < X]exp_0. apply exp_increasing. fourier. Qed.\n\nLemma ltRinve21 : exp (-2) < 1.\nProof. rewrite -[X in _ < X]exp_0. apply exp_increasing. fourier. Qed.\n\nSection exp_lower_bound.\n\nLet exp_dev (n : nat) := fun x => exp x - x ^ n * / INR (n`!).\n\nLet derivable_exp_dev (n : nat) : derivable (exp_dev n).\nProof.\nrewrite /exp_dev => x.\napply derivable_pt_minus ; first by apply derivable_pt_exp.\napply derivable_pt_mult ; first by apply derivable_pt_pow.\nby apply derivable_pt_const.\nDefined.\n\nLet exp_dev_rec n x : derive_pt (exp_dev n.+1) x (derivable_exp_dev n.+1 x) = exp_dev n x.\nProof.\nrewrite /exp_dev derive_pt_minus derive_pt_exp; congr (_ - _).\nrewrite derive_pt_mult derive_pt_const mulR0 addR0 derive_pt_pow.\nrewrite mulRC mulRA mulRC; congr (_ * _).\nrewrite factS mult_INR invRM; last 2 first.\n  exact/INR_eq0.\n  apply/eqP; by rewrite INR_eq0' -lt0n fact_gt0.\nby rewrite mulRC mulRA mulRV ?mul1R // INR_eq0'.\nQed.\n\nLet exp_dev_gt0 : forall n r, 0 < r -> 0 < exp_dev n r.\nProof.\nelim => [r rpos | n IH r rpos].\n- rewrite /exp_dev /= mul1R Rinv_1 -exp_0.\n  by apply subR_gt0, exp_increasing.\n- apply: (@ltR_trans 1) ; first by fourier.\n  rewrite (_ : 1 = exp_dev n.+1 0) ; last first.\n    rewrite /exp_dev exp_0 pow_i ?mul0R ?subR0 //; by apply/ltP.\n  move: derive_increasing_interv.\n  move/(_ 0 r (exp_dev n.+1) (derivable_exp_dev n.+1) rpos).\n  have Haux : forall t : R,\n     0 < t < r -> 0 < derive_pt (exp_dev n.+1) t (derivable_exp_dev n.+1 t).\n    move=>x Hx.\n    rewrite exp_dev_rec.\n    by apply IH, Hx.\n  move/(_ Haux 0 r) => {Haux}.\n  apply => //.\n  - split; [exact/leRR | exact: ltRW].\n  - split; [exact: ltRW | exact/leRR].\nQed.\n\nLemma exp_strict_lb (n : nat) x : 0 < x -> x ^ n * / INR (n`!) < exp x.\nProof. move=> xpos; by apply Rgt_lt, Rminus_gt, Rlt_gt, exp_dev_gt0. Qed.\n\nLet exp_dev_ge0 n r : 0 <= r -> 0 <= exp_dev n r.\nProof.\nmove=> Hr.\ncase/boolP : (r == 0) => [/eqP ->|]; last first.\n- move=> Hr2.\n  have {Hr Hr2}R_pos : 0 < r by apply/ltRP; rewrite lt0R Hr2 /=; exact/leRP.\n  exact/ltRW/exp_dev_gt0.\n- case: n.\n  + rewrite /exp_dev exp_0 mul1R invR1 subRR; exact/leRR.\n  - move=> n.\n    rewrite -(_ : 1 = exp_dev n.+1 0) //.\n    rewrite /exp_dev exp_0 pow_i ?mul0R ?subR0 //; exact/ltP.\nQed.\n\nLemma exp_lb x (n : nat) : 0 <= x -> x ^ n / INR (n`!) <= exp x.\nProof. move=> xpos; by apply Rge_le, Rminus_ge, Rle_ge, exp_dev_ge0. Qed.\n\nEnd exp_lower_bound.\n\nEnd addtional_lemmas_about_ln_exp.\nHint Resolve ln2_gt0.\n\n(** log_n x *)\n\nDefinition Log (n : R) x := ln x / ln n.\n\nLemma ltR0Log n x : 1 < n -> 1 < x -> 0 < Log n x.\nProof. move=> ? ?; apply mulR_gt0; [exact/ln_pos | exact/invR_gt0/ln_pos]. Qed.\n\nLemma Log_1 (n : R) : Log n 1 = 0.\nProof. by rewrite /Log ln_1 div0R. Qed.\n\nLemma Log_n (n : R) : 1 < n -> Log n n = 1.\nProof. move=> n1; rewrite /Log /Rdiv mulRV //; exact/eqP/gtR_eqF/ln_pos. Qed.\n\nLemma LogV n x : 0 < x -> Log n (/ x) = - Log n x.\nProof.\nby move=> x0; rewrite /Log ln_Rinv // -mulNR.\nQed.\n\nLemma LogM n x y : 0 < x -> 0 < y -> Log n (x * y) = Log n x + Log n y.\nProof. move=> *; by rewrite /Log -mulRDl ln_mult. Qed.\n\nLemma Log_increasing_le n x y : 1 < n -> 0 < x -> x <= y -> Log n x <= Log n y.\nProof.\nmove=> n1 x0 xy.\napply leR_wpmul2r; [exact/leRP/ltRW'/ltRP/invR_gt0/ln_pos|].\nexact: ln_increasing_le.\nQed.\n\nLemma Log_increasing n a b : 1 < n -> 0 < a -> a < b -> Log n a < Log n b.\nProof.\nmove=> n1 Ha a_b.\nrewrite /Log.\napply ltR_pmul2r; last exact: ln_increasing.\nexact/invR_gt0/ln_pos.\nQed.\n\nLemma Log_inv n x y : 1 < n -> 0 < x -> 0 < y -> Log n x = Log n y -> x = y.\nProof.\nmove=> n1 Hx Hy.\nrewrite /Log /Rdiv eqR_mul2r; last exact/eqP/invR_neq0/eqP/gtR_eqF/ln_pos.\napply ln_inv => //; exact: H.\nQed.\n\nLemma Log_lt_inv n x y : 1 < n -> 0 < x -> 0 < y -> Log n x < Log n y -> x < y.\nProof.\nmove=> n1 Hx Hy.\nrewrite /Log /Rdiv.\nhave H : 0 < / ln n by exact/invR_gt0/ln_pos.\nmove/(ltR_pmul2r H); exact: ln_lt_inv.\nQed.\n\nLemma Log_le_inv n x y : 1 < n -> 0 < x -> 0 < y -> Log n x <= Log n y -> x <= y.\nProof.\nmove=> n1 Hx Hy.\ncase/Rle_lt_or_eq_dec; first by move/(Log_lt_inv n1 Hx Hy)/ltRW.\nmove/(Log_inv n1 Hx Hy) => ->; exact/leRR.\nQed.\n\nLemma derivable_pt_Log n : forall x : R, 0 < x -> derivable_pt (Log n) x.\nmove=> x Hx.\nrewrite /Log /Rdiv.\napply derivable_pt_mult.\n  exact: derivable_pt_ln.\napply derivable_pt_const.\nDefined.\n\nLemma derive_pt_Log n : forall (a : R) (Ha : 0 < a),\n  derive_pt (Log n) a (derivable_pt_Log n Ha) = / a * / ln n.\nmove=> a Ha.\nrewrite /Log.\nrewrite /Rdiv.\nrewrite derive_pt_mult.\nrewrite derive_pt_const.\nrewrite derive_pt_ln.\nrewrite mulR0 addR0.\nreflexivity.\nDefined.\n\n(** Log base 2 *)\n\n(* NB: log is 0 for input < 0 *)\nDefinition log x := Log 2 x.\n\nLemma logexp1E : log (exp 1) = / ln 2.\nProof. by rewrite /log /Log ln_exp div1R. Qed.\n\nLemma log_exp1_Rle_0 : 0 <= log (exp 1).\nProof. rewrite logexp1E; exact/leRP/ltRW'/ltRP/invR_gt0. Qed.\n\n(** n ^ x *)\nDefinition Exp (n : R) x := exp (x * ln n).\n\nLemma pow_Exp x n : 0 < x -> x ^ n = Exp x (INR n).\nProof. by move=> x0; rewrite /Exp exp_pow exp_ln. Qed.\n\nLemma LogK n x : 1 < n -> 0 < x -> Exp n (Log n x) = x.\nProof.\nmove=> n1 x0.\nrewrite /Log /Exp -mulRA mulVR ?mulR1; last first.\n  rewrite -ln_1.\n  apply/eqP => /ln_inv H.\n  have : 0 < n by fourier.\n  move/H => /(_ Rlt_0_1) ?; fourier.\nby rewrite exp_ln.\nQed.\n\nLemma ExpK n x : 1 < n -> Log n (Exp n x) = x.\nProof.\nmove=> n1.\nrewrite /Log /Exp ln_exp /Rdiv -mulRA mulRV ?mulR1 //.\nrewrite -ln_1; apply/eqP => /ln_inv H.\nhave : 0 < n by fourier.\nmove/H => /(_ Rlt_0_1) ?; fourier.\nQed.\n\nLemma Exp_gt0 n x : 0 < Exp n x. Proof. rewrite /Exp; exact: exp_pos. Qed.\nLemma Exp_ge0 n x : 0 <= Exp n x. Proof. exact/ltRW/Exp_gt0. Qed.\nHint Resolve Exp_gt0.\nHint Resolve Exp_ge0.\n\nLemma Exp_0 n : Exp n 0 = 1.\nProof. by rewrite /Exp mul0R exp_0. Qed.\n\nLemma ExpD n x y : Exp n (x + y) = Exp n x * Exp n y.\nProof. by rewrite /Exp mulRDl exp_plus. Qed.\n\nLemma Exp_INR n : (0 < n)%nat -> forall m, Exp (INR n) (INR m) = INR (expn n m).\nProof.\nmove=> n0.\nelim=> [|m IH]; first by rewrite /Exp mul0R exp_0.\nrewrite S_INR ExpD expnS mult_INR IH /Exp mul1R exp_ln;\n  [by rewrite mulRC | exact/ltR0n].\nQed.\n\nLemma Exp_increasing n x y : 1 < n -> x < y -> Exp n x < Exp n y.\nProof. move=> ? ?; apply/exp_increasing/ltR_pmul2r => //; exact/ln_pos. Qed.\n\nLemma Exp_le_inv n x y : 1 < n -> Exp n x <= Exp n y -> x <= y.\nProof.\nrewrite /Exp => n1 /exp_le_inv H.\napply/leRP; rewrite -(leR_pmul2l' (ln n)); last exact/ltRP/ln_pos.\nrewrite mulRC -(mulRC y); exact/leRP.\nQed.\n\nLemma Exp_le_increasing n x y : 1 < n -> x <= y -> Exp n x <= Exp n y.\nProof.\nmove=> n1; rewrite /Exp; case/Rle_lt_or_eq_dec.\nmove/Exp_increasing => x_y; exact/ltRW/x_y.\nmove=> ->; exact/leRR.\nQed.\n\nLemma Exp_Ropp n x : Exp n (- x) = / Exp n x.\nProof. by rewrite /Exp mulNR exp_Ropp. Qed.\n\n(** 2 ^ x *)\n\nDefinition exp2 (x : R) := Exp 2 x.\n\nLemma exp2_gt0 x : 0 < exp2 x. Proof. exact: Exp_gt0. Qed.\nLemma exp2_ge0 x : 0 <= exp2 x. Proof. exact: Exp_ge0. Qed.\nHint Resolve exp2_gt0.\nHint Resolve exp2_ge0.\n\nLemma exp2_neq0 l : exp2 l <> 0. Proof. exact/gtR_eqF. Qed.\nHint Resolve exp2_neq0.\n\nLemma exp2_0 : exp2 0 = 1.\nProof. by rewrite /exp2 -/(Exp 2 0) Exp_0. Qed.\n\nLemma exp2_INR : forall m, exp2 (INR m) = INR (expn 2 m).\nProof. move=> m; by rewrite -Exp_INR. Qed.\n\nLemma exp2_pow n k : exp2 (INR k * n) = (exp2 n) ^ k.\nProof. by rewrite /exp2 /Exp -mulRA exp_pow. Qed.\n\nLemma exp2_Ropp x : exp2 (- x) = / exp2 x.\nProof. by rewrite /exp2 Exp_Ropp. Qed.\n\nLemma logK x : 0 < x -> exp2 (log x) = x.\nProof. move=> Hx; by rewrite /exp2 -/(Exp 2 (log x)) /log -/(Log 2 _) LogK. Qed.\n\nLemma exp2K x : log (exp2 x) = x.\nProof. by rewrite /exp2 -/(Exp 2 x) /log -/(Log 2 _) ExpK. Qed.\n\nLemma Rle_exp2_log1_L a b : 0 < b -> exp2 a <b= b = (a <b= log b).\nProof.\nmove=> Hb; move H1 : (_ <b= _ ) => [|] /=.\n- move/leRP in H1.\n  have {H1}H1 : a <= log b.\n    rewrite (_ : a = log (exp2 a)); last by rewrite exp2K.\n    exact: Log_increasing_le.\n  move/leRP in H1; by rewrite H1.\n- move H2 : (_ <b= _ ) => [|] //=.\n  move/leRP in H2.\n  rewrite -(@ExpK 2 a _) // in H2.\n  apply Log_le_inv in H2 => //.\n  move/leRP in H2.\n  by rewrite H2 in H1.\nQed.\n\nLemma Rle_exp2_log2_R b c : 0 < b -> b <b= exp2 c = (log b <b= c).\nProof.\nmove=> Hb; move H1 : (_ <b= _ ) => [|] /=.\n- move/leRP in H1.\n  have {H1}H1 : log b <= c.\n    rewrite (_ : c = log (exp2 c)); last by rewrite exp2K.\n    apply Log_increasing_le => //; exact: exp2_pos.\n  by move/leRP in H1.\n- move H2 : (_ <b= _ ) => [|] //=.\n  move/leRP in H2.\n  rewrite -(exp2K c) in H2.\n  apply Log_le_inv in H2 => //.\n  move/leRP in H2.\n  by rewrite H2 in H1.\nQed.\n\nLemma Rle2_exp2_log a b c : 0 < b ->\n  exp2 a <b= b <b= exp2 c = (a <b= log b <b= c).\nProof.\nmove=> Hb; move H1 : (_ <b= _ ) => [|] /=.\n- rewrite Rle_exp2_log1_L // in H1.\n  by rewrite H1 /= Rle_exp2_log2_R.\n- move H2 : (_ <b= _ ) => [|] //=.\n  rewrite -Rle_exp2_log1_L // in H2.\n  by rewrite H2 in H1.\nQed.\n\nLemma exists_frac_part (P : nat -> Prop) : (exists n, P n) ->\n  forall num den, (0 < num)%nat -> (0 < den)%nat ->\n  (forall n m, (n <= m)%nat -> P n -> P m) ->\n  exists n, P n /\\\n    frac_part (exp2 (INR n * (log (INR num) / INR den))) = 0.\nProof.\ncase=> n Pn num den Hden HP.\nexists (n * den)%nat.\nsplit.\n  apply H with n => //.\n  by rewrite -{1}(muln1 n) leq_mul2l HP orbC.\nrewrite mult_INR -mulRA (mulRCA (INR den)) mulRV // ?mulR1; last first.\n  by rewrite INR_eq0' -lt0n.\nrewrite exp2_pow logK; [exact/frac_part_pow/frac_part_INR | exact/ltR0n].\nQed.\n", "meta": {"author": "erikmd", "repo": "coq-bool-games", "sha": "659e9ac9c7f40d07ed651dde31d575f4ef0bce19", "save_path": "github-repos/coq/erikmd-coq-bool-games", "path": "github-repos/coq/erikmd-coq-bool-games/coq-bool-games-659e9ac9c7f40d07ed651dde31d575f4ef0bce19/external/infotheo/logb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7014905961255485}}
{"text": "Require Export CatSem.CAT.category.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nUnset Automatic Introduction.\n\nSection defs.\n\nVariable obC : Type.\nVariable morC : obC -> obC -> Type.\nVariable C : Cat_struct morC.\n\n(** definition of \n      - monic\n      - epi\n      - invertible\n      - ismorphic objects\n*)\n\n\nSection morphisms.  \n\nVariables a b : obC.\n\nClass Monic (f: morC a b) := {\n  monic_cond : forall d (g1 g2 : morC d a),\n                 g1 ;; f == g2 ;; f -> g1 == g2\n}.\n\nClass Epi (f: morC a b) := {\n  epi_cond : forall d (g1 g2 : morC b d),\n                 f ;; g1 == f ;; g2 -> g1 == g2\n}.\n\nClass Invertible (f: morC a b) := {\n  inverse : morC b a ;\n  inv_prae : inverse ;; f == id _ ;\n  inv_post : f ;; inverse == id _ \n}.\n\nClass isomorphic := {\n  inv_morphism : morC a b;\n  invertible :> Invertible inv_morphism\n}.\n\nEnd morphisms.\n\nImplicit Arguments inverse [a b Invertible].\n\nNotation \"-- f\" := (inverse f) (at level 30).\n\n(**   lemmata, such as \"composition of monics...\" etc bla bla *)\n\nSection lemmata.\n\nVariables a b c : obC.\nVariable f : morC a b.\nVariable g : morC b c.\n\nGlobal Instance comp_of_monics \n   (Hf : Monic f) (Hg : Monic g) : Monic (f ;; g).\nProof.\n  intros Hf Hg.\n  constructor.\n  intros d g1 g2.\n  repeat rewrite <- assoc.\n  intro H.\n  assert (H': g1 ;; f == g2 ;; f).\n  apply Hg; auto.\n  apply Hf; auto.\nQed.\n\nGlobal Instance comp_of_epis (Hf : Epi f) (Hg : Epi g) : Epi (f ;; g).\nProof.\n  intros Hf Hg.\n  constructor.\n  intros d g1 g2.\n  repeat rewrite assoc.\n  intro H.\n  assert (H': g ;; g1 == g ;; g2).\n  apply Hf; auto.\n  apply Hg; auto.\nQed.\n\nGlobal Instance comp_monic_fst_monic (H : Monic (f ;; g)) : Monic f.\nProof.\n  intro H.\n  set (H':= monic_cond (Monic:=H)).\n  constructor.\n  intros d g1 g2 H2.\n  apply (H' _ g1 g2).\n  repeat rewrite <- assoc.\n  rewrite H2.\n  cat.\nQed.\n\nGlobal Instance comp_epi_snd_epi (H : Epi (f ;; g)) : Epi g.\nProof.\n  intro H.\n  set (H':= epi_cond (Epi:=H)).\n  constructor.\n  intros d g1 g2 H2.\n  apply (H' _ g1 g2).\n  repeat rewrite assoc.\n  rewrite H2.\n  cat.\nQed.\n\n(** uniqueness of the inverse *)\n\nLemma inverse_unique (H : Invertible f) h \n   (H1 : f ;; h == id _ ) (H2 : h ;; f == id _ ) : \n         h == -- f.\nProof.\n  intros  H h H1 H2.\n  transitivity (h ;; (f ;; --f)).\n  rewrite inv_post; cat.\n  rewrite <- assoc.\n  rewrite H2.\n  cat.\nQed.\n\nProgram Instance inverse_invertible (H : Invertible f) : \n                                 Invertible (--f):= {\n  inverse := f;\n  inv_prae := inv_post (Invertible := H);\n  inv_post := inv_prae (Invertible := H)\n}.\n\nEnd lemmata.\n\nExisting Instance inverse_invertible.\n\nSection more_lemmata.\n\nVariables a b c : obC.\nVariable f : morC a b.\nVariable g : morC b c.\n\n\nLemma inverse_inverse (H : Invertible f) : -- (-- f) == f.\nProof.\n  intro H.\n  apply hom_sym.\n  apply inverse_unique.\n  apply inv_prae.\n  apply inv_post.\nQed.\n  \n\nLemma put_inv_to_right (H : Invertible f) h : \n        f ;; g == h <-> g == -- f ;; h.\nProof.\n  intros H h.\n  split; intro H'.\n  transitivity (--f ;; f ;; g).\n  rewrite inv_prae; cat.\n  rewrite <- H'; apply assoc.\n\n  transitivity (f ;; --f ;; h).\n  repeat rewrite assoc.\n  apply praecomp; auto.\n  rewrite inv_post; cat.\nQed.\n\nEnd more_lemmata.\n\n\nSection still_more_lemmata.\n\nVariables a b c : obC.\nVariable f : morC a b.\nVariable g : morC b c.\n\n(** inverse of a composition *)\n\nProgram Instance inv_of_comp (Hf : Invertible f) (Hg : Invertible g) :\n      Invertible (f ;; g) := {\n  inverse := --g ;; --f\n}.\nNext Obligation.\nProof.\n  apply hom_sym.\n  rewrite assoc.\n  rewrite <- put_inv_to_right.\n  rewrite <- assoc.\n  rewrite inv_prae.\n  cat.\nQed.\n\nEnd still_more_lemmata.\n\nEnd defs.\n\nImplicit Arguments Invertible [obC morC C a b].\nImplicit Arguments inverse [obC morC C a b Invertible].\n\n\n\n", "meta": {"author": "JasonGross", "repo": "benediktahrens-coq-fossil", "sha": "834bc904a07549ac3f659e68d94a3f1c73c5b72a", "save_path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil", "path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil/benediktahrens-coq-fossil-834bc904a07549ac3f659e68d94a3f1c73c5b72a/CAT/monic_epi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7014905893985134}}
{"text": "Require Import pure_lemmas.\nRequire Import Coqlib.\nRequire Import Integers.\n(* Require Import HMAC_spec_harvard_concat. *)\nRequire Import SHA256.\nRequire Import functional_prog.\nRequire Import hmac_pure_lemmas.\n\n(* Lemma 1: M = Prefix(Pad(M)) *)\n\nInductive Prefix {X : Type} : list X -> list X -> Prop :=\n  | p_nil : forall (l : list X), Prefix [] l\n  | p_self : forall (l : list X), Prefix l l\n  | p_cons : forall (l1 l2 : list X) (x : X), Prefix l1 l2 -> Prefix (x :: l1) (x :: l2)\n  | p_append : forall (l1 l2 : list X) (l3 : list X), Prefix l1 l2 -> Prefix l1 (l2 ++ l3).\n  (* | p_trans : forall (l1 l2 l3 : list X), Prefix l1 l2 -> Prefix l2 l3 -> Prefix l1 l2. *)\n\n(* TODO: replace InWords with InBlocks 4? *)\nInductive InWords : list Z -> Prop :=\n  | words_nil : InWords []\n  | words_word : forall (a b c d : Z) (msg : list Z),\n                   InWords msg -> InWords (a :: b :: c :: d :: msg).\n\n(* *** New definition for this lemma. *)\nDefinition pad (msg : list Z) : list Z := \n  let n := Zlength msg in\n  msg ++ [128%Z] \n      ++ list_repeat (Z.to_nat (-(n + 9) mod 64)) 0\n      ++ intlist_to_Zlist ([Int.repr (n * 8 / Int.modulus), Int.repr (n * 8)]).\n\nDefinition generate_and_pad' (msg : list Z) : list int :=\n  Zlist_to_intlist (pad msg).\n\n(* TODO: total_pad_len_Zlist  *)\nInductive InBlocks {A : Type} (n : nat) : list A -> Prop :=\n  | list_nil : InBlocks n []\n  | list_block : forall (front back full : list A),\n                   length front = n ->\n                   full = front ++ back ->\n                   InBlocks n back ->\n                   InBlocks n full. \n\n(* ----------------- ^ Definitions *)\n(*\nCheck NPeano.divide.\nPrint NPeano.divide.\nCheck list_repeat.\nPrint list_repeat.\n*)\n\nLemma fstpad_len :\n  forall (msg : list Z),\n    Datatypes.length (msg ++ [128]\n                 ++ list_repeat (Z.to_nat (- (Zlength msg + 9) mod 64)) 0)\n= (Datatypes.length msg + (S (Z.to_nat (- (Zlength msg + 9) mod 64))))%nat.\nProof.\n  intros msg.\n  simpl.\n  rewrite -> app_length.\n  simpl.\n  rewrite -> length_list_repeat.\n  reflexivity.\nQed.  \n\nLemma InWords_len4 : forall (l : list Z),\n                       NPeano.divide (Z.to_nat WORD) (length l) -> InWords l.\nProof.\n  intros l [x H].\n  revert l H.\n  induction x.\n  intros l H. simpl in H. \n  destruct l.\n    apply words_nil.\n    simpl in H. inversion H.\n  intros l H.\n  destruct l as [ | a [ | b [ | c [ | d ? ]]]].\n    inversion H.\n    inversion H.\n    inversion H.\n    inversion H.\n    specialize (IHx l).\n      apply words_word.\n      apply IHx.\n      simpl in H. inversion H.\n      simpl. apply H1.\nQed.  \n\nLemma InBlocks_len : forall {A : Type} (l : list A) (n : nat),\n                       NPeano.divide (n) (length l) -> InBlocks n l.\nProof. \n  intros A l n div.\n  destruct div.\n  revert A l n H.\n  induction x; intros; simpl in *.\n  - destruct l; simpl in *. constructor. inversion H.\n  - destruct (list_splitLength _ _ _ H) as [l1 [l2 [L [L1 L2]]]]. clear H; subst.\n    apply IHx in L2. clear IHx. \n    apply (list_block _ l1 l2); trivial.\nQed. \n\n(* TODO: clear out the SearchAbouts / clean up proof *)\nLemma pad_len_64_mod : forall (msg : list Z), \n                           (Zlength (pad msg)) mod 64 = 0.\nProof.\n  intros msg.\n  unfold pad.\n  rewrite -> Zlength_correct.\n  repeat rewrite -> app_length.\n  simpl.\n  assert (succ: forall (n : nat), S n = (n + 1)%nat).\n    intros. induction n. reflexivity. omega.\n  rewrite -> succ.\n  assert ((length msg +\n      (length (list_repeat (Z.to_nat (- (Zlength msg + 9) mod 64)) 0%Z) + 8 +\n       1))%nat = (length msg +\n      (length (list_repeat (Z.to_nat (- (Zlength msg + 9) mod 64)) 0%Z) + 9))%nat) by omega.\n  rewrite -> H. clear H.\n\n(*  SearchAbout generate_and_pad.*)\n  rewrite -> Zlength_correct.\n  rewrite -> length_list_repeat.\n\n  repeat rewrite -> Nat2Z.inj_add.\n  rewrite -> Z2Nat.id.\n\n  assert (move : forall (a b c : Z), a + (b + c) = (a + c) + b).\n  intros. omega.\n\n  rewrite -> move.\n  rewrite -> Zplus_mod_idemp_r.\n\n  assert (Z_9 : 9 = Z.of_nat (9%nat)). reflexivity.\n  rewrite -> Z_9.\n\n  repeat rewrite <- Nat2Z.inj_add.\n  \n  assert (forall (x : Z), x + (-x) = 0). intros. omega.\n\n  rewrite -> H.\n  reflexivity.\n\n  * apply Z.mod_pos_bound.\n    omega.\nQed.\n\n(* more usable versions *)\nLemma pad_len_64 : forall (msg : list Z), exists (n : Z),\n                           Zlength (pad msg) = 64 * n /\\ n >= 0.\nProof.\n  intros msg.\n  pose proof pad_len_64_mod msg as pad_len_mod.\n  rewrite -> Zmod_divides in *. 2: omega.\n\n  destruct pad_len_mod.\n  exists x.\n  split.\n  apply H.\n  specialize (Zlength_nonneg (pad msg)); intros. omega.\nQed.\n\nLemma pad_len_64_nat : forall (msg : list Z), exists (n : nat),\n                           (length (pad msg))%nat = (64 * n)%nat.\nProof. \n  intros msg.\n  pose proof pad_len_64 msg as pad_len_64.\n\n  rewrite -> Zlength_correct in *.\n  destruct pad_len_64.\n  exists (Z.to_nat x).\n  destruct H.\n\n  assert (app_each : Z.to_nat (Z.of_nat (length (pad msg))) = Z.to_nat (64 * x)).\n    rewrite -> H. reflexivity.\n\n  rewrite -> Nat2Z.id in app_each.\n\n  rewrite -> app_each.\n(*  SearchAbout (Z.to_nat (_ * _)).*)\n  rewrite -> Z2Nat.inj_mul.\n  assert (n_64 : Z.to_nat 64 = 64%nat). reflexivity.\n\n  rewrite -> n_64.\n  reflexivity.\n\n  * omega.\n  * omega.\nQed.\n\nLemma total_pad_len_Zlist : forall (msg : list Z), exists (n : nat),\n     length\n       (msg ++ [128] ++ list_repeat (Z.to_nat (- (Zlength msg + 9) mod 64)) 0)\n     =  (n * Z.to_nat WORD (* 4 *))%nat.\nProof.\n  intros msg.\n  pose proof pad_len_64_nat msg as pad_len_64_nat.\n\n  unfold pad in *.\n  repeat rewrite -> app_length in *.\n  destruct pad_len_64_nat.\n  assert (sym: (64 * x)%nat = (x * 64)%nat) by omega.\n  rewrite -> sym in *. clear sym.\n\n  simpl in *.\n  assert (Pos.to_nat 4 = 4%nat) by reflexivity.\n  rewrite -> H0. clear H0.\n\n  rewrite -> length_list_repeat in *.\n\n  assert (add_both: (length msg + S (Z.to_nat (- (Zlength msg + 9) mod 64) ))%nat =\n      (x * 64 - 8)%nat) by omega. clear H.\n  \n  rewrite -> add_both.\n  assert ((x * 64 - 8)%nat = (4 * (16 * x - 2))%nat) by omega.\n\n  rewrite -> H.\n  exists (16 * x - 2)%nat.\n  omega.\nQed.\n\nLemma pad_inwords :\n  forall (msg : list Z),\n    InWords (msg ++ [128]\n                 ++ list_repeat (Z.to_nat (- (Zlength msg + 9) mod 64)) 0).\nProof.\n  intros msg.\n  apply InWords_len4.\n  pose proof total_pad_len_Zlist.\n  specialize (H msg).\n  unfold NPeano.divide.\n  apply H.\nQed.  \n\nDefinition fulllen (len : Z) :=\n  len + 1%Z + (- (len + 9) mod 64).\n\nLemma app_left : forall (a b c d : list Z),\n   a ++ b ++ c ++ d = (a ++ b ++ c) ++ d.\n(* a ++ (b ++ (c ++ d)) = (a ++ (b ++ c)) ++ d *)\nProof.\n   intros a b c d.\n   assert (b ++ (c ++ d) = (b ++ c) ++ d) as assert1.\n     rewrite -> app_assoc. reflexivity.\n   rewrite -> assert1.\n   rewrite -> app_assoc.\n   reflexivity.\nQed.\n\n(* can use extensionality *)\nTheorem pad_compose_equal : forall (msg : list Z),\n                              generate_and_pad' msg = generate_and_pad msg.\nProof.\n  intros msg.\n  unfold generate_and_pad'.\n  unfold pad.\n  unfold generate_and_pad.\n  (* need il => ZIL (IZL il), and\n     ZIL a ++ Zil b = ZIL (a ++ b) (with length a being a multiple of 4)\n   *)\n  pose proof pad_inwords as pad_inwords.\n  specialize (pad_inwords msg).\n  rewrite -> app_left.\n  induction pad_inwords.\n  (* case none *)\n    assert (forall l : list Z, [] ++ l = l) as Happend. reflexivity.\n    specialize (Happend (intlist_to_Zlist\n        [Int.repr (Zlength msg * 8 / Int.modulus),\n        Int.repr (Zlength msg * 8)])).\n    rewrite -> Happend.\n    rewrite -> intlist_to_Zlist_to_intlist.\n    reflexivity.\n  (* case a :: b :: c :: d :: msg0 *)\n    Opaque intlist_to_Zlist.\n    simpl.\n    apply f_equal.\n    apply IHpad_inwords.\nQed.    \n\n(* Proof easy with pad definition *)\nTheorem prefix : forall (msg : list Z),\n                   Prefix msg (pad msg).\nProof.\n  intros msg.\n  unfold pad.\n  apply p_append.\n  apply p_self.\nQed.  \n  \n(* ------------------------------------------------ *)\n\n(* Lemma 2: |M1| = |M2| -> |Pad(M1)| = |Pad(M2)| *)\n\nTheorem length_equal_pad_length : forall (msg1 : list Z) (msg2 : list Z),\n     Zlength msg1  = Zlength msg2 ->\n     Zlength (generate_and_pad msg1) = Zlength (generate_and_pad msg2).\nProof.\n  intros m1 m2 H.\n  repeat rewrite -> functional_prog.length_generate_and_pad.\n  rewrite -> H.\n  reflexivity.\nQed.  \n\n(* ------------------------------------------------ *)\n\n(* Lemma 3: |M1| =/= |M2| ->\nlast block of Pad(M1) =/= last block of Pad(M2) \n\nor, if one-to-one property is desired (for HMAC), only need to prove that\nthe padded messages differ\n*)\n\nDefinition generate_and_pad_copy msg := \n  let n := Zlength msg in\n   Zlist_to_intlist (msg ++ [128%Z] \n                ++ list_repeat (Z.to_nat (-(n + 9) mod 64)) 0)\n           ++ [Int.repr (n * 8 / Int.modulus), Int.repr (n * 8)].\n\n(* Probably easier to use the rewritten version; already \"proved\"\n that that's in blocks of 4 *)\n\nTheorem length_differ_pad_differ : forall (m1 m2 : list Z),\n                                     Zlength m1 <> Zlength m2 ->\n                                     generate_and_pad m1 <> generate_and_pad m2.\nProof.\n  intros m1 m2 len_diff.\n  unfold generate_and_pad.\n  \n  \nAdmitted.\n\n(* TODO prove equivalent to above *)\nTheorem contrapositive_gap : forall (m1 m2 : list Z),\n                                     generate_and_pad m1 = generate_and_pad m2 ->\n                                     Zlength m1 = Zlength m2.\n\nProof.\n  intros m1 m2 gap_eq.\n  unfold generate_and_pad in *.\n  \n  \nAdmitted.\n\n(* ---------------------------------------------- *)\n\n(* TODO: Prove that the above three lemmas imply that generate_and_pad is one-to-one\n-- actually, that has type list Z -> list int.\n\nProve first that it implies the pad function is one-to-one (defined above).\n\nThen, lift it to the vector version.\n\n  Variable splitAndPad : Blist -> list (Bvector b).\n  Hypothesis splitAndPad_1_1 : \n    forall b1 b2,\n      splitAndPad b1 = splitAndPad b2 ->\n      b1 = b2.\n*)\n\nSearchAbout (_ <> _ -> _ <> _).\n\nRequire Import Coq.Logic.Decidable.\n\n\nLemma f_app_equal : forall {A B : Type} (f : A -> B) (x y : A),\n                      x = y -> f x = f y.\nProof. intros. rewrite H. reflexivity. Qed.\n\nTheorem pad_1_1_len : forall (m1 m2 : list Z),\n                    pad m1 = pad m2 ->\n                    length m1 = length m2.\nProof.\n  intros m1 m2.\n  \n  (* apply contrapositive. *)\n  (* * unfold decidable. *)\n  (*   omega. *)\n  (* * intros lenfalse. *)\n  (*   unfold pad. *)\n\n  intros pad_eq.\n  unfold pad in *.\n\n(*\n  assert (lp : length (pad m1) = length (pad m2)).\n    apply f_app_equal. apply pad_eq.\n  unfold pad in lp.\n  repeat rewrite app_length in lp.\n  simpl in lp.\n  rewrite plus_comm in lp.\n  symmetry in lp.\n  rewrite plus_comm in lp.\n  inversion lp.\n  clear lp.\n  repeat rewrite -> length_list_repeat in *.\n  repeat rewrite -> length_intlist_to_Zlist in *.\n  simpl in *.\n  repeat rewrite -> Zlength_correct in *.\n  assert (forall x y z : nat, (x + y + z)%nat = (y + x + z)%nat) as plus_comm_3.\n    intros. omega.\n  rewrite -> plus_comm_3 in H0. symmetry in H0.\n  rewrite -> plus_comm_3 in H0.\n  inversion H0. clear H0.\n  SearchAbout ((_ + _) mod _).\n  SearchAbout (-_ mod _).\n  SearchAbout (- (_ + _)).\n  rewrite -> Z.opp_add_distr in H1. symmetry in H1. rewrite -> Z.opp_add_distr in H1.\n  \n  SearchAbout ((_ + _) mod _).\n\nnot true\n*)\n\n  (* f(x) + x = f(y) + y. x = y? not necessarily; f(c) = -c for example. \n     what if x,y,f(c):nat? then it must be true by inversion? *)\n  \n  \n  \n  (* generalize dependent H1. *)\n  (* apply contrapositive. *)\n  (* * admit. *)\n  (* * intros lenfalse. *)\n  (*   SearchAbout (_ -> False). *)\n  (*   SearchAbout (_ <> _). *)\n    \n\n  assert (forall x y : nat, -(x + y) = -x + -y).\n\n  (* specialize (f_app_equal length). *)\n  SearchAbout (_ ++ _ = _ ++ _).\n  (* apply app_inv_tail in pad_eq. *)\n  (* apply app_inj_tail in pad_eq. *)\n\nAdmitted.\n\n\n\nTheorem pad_general : forall (m1 m2 l1 l2 : list Z),\n                     length l1 = length l2 ->\n                     m1 ++ l1 = m2 ++ l2 ->\n                     m1 = m2.\nProof.\n  intros m1 m2 l1 l2 len_tail_eq concat_eq.\n  SearchAbout (_ ++ _ = _ ++ _).\n  revert m2 l1 l2 len_tail_eq concat_eq.\n  induction m1; intros.\n  *\n    destruct m2.\n    - reflexivity.\n    - rewrite -> app_nil_l in concat_eq.\n      assert (length l1 = length (z :: m2 ++ l2)) as length_absurd.\n      { apply f_app_equal. apply concat_eq. }\n      simpl in length_absurd.\n      rewrite -> len_tail_eq in length_absurd.\n      rewrite -> app_length in length_absurd.\n      omega.\n  *\n    destruct m2.\n    - \n      rewrite -> app_nil_l in concat_eq.\n      assert (length (a :: m1 ++ l1) = length l2) as length_absurd.\n      { apply f_app_equal. apply concat_eq. }\n      simpl in length_absurd.\n      rewrite <- len_tail_eq in length_absurd.\n      rewrite -> app_length in length_absurd.\n      omega.\n    -\n      f_equal.\n      + \n        inversion concat_eq.\n        reflexivity.\n      +\n        apply (IHm1 m2 l1 l2).\n        apply len_tail_eq.\n        inversion concat_eq.\n        reflexivity.\nQed.\n\n\nTheorem pad_1_1 : forall (m1 m2 : list Z),\n                    pad m1 = pad m2 ->\n                    m1 = m2.\nProof.\n  intros m1 m2 pad_eq.\n  unfold pad in *.\n  apply pad_general in pad_eq.\n  apply pad_eq.\n  repeat rewrite -> app_length.\n  simpl.\n  f_equal.\n  f_equal.\n  *\n    do 6 f_equal.\n    (* apply pad_1_1_len. *)\n    admit.\nQed.", "meta": {"author": "k-qy", "repo": "vst-hmac", "sha": "324239050b2a0a29cb771ef93e8c7583f6731741", "save_path": "github-repos/coq/k-qy-vst-hmac", "path": "github-repos/coq/k-qy-vst-hmac/vst-hmac-324239050b2a0a29cb771ef93e8c7583f6731741/sha_padding_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7014905873352609}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Import Logic.Class.Eq.\n\nRequire Import Logic.STLC.Syntax.\n\nFixpoint subst_(b v:Type)(eq:Eq v)(f:v -> Exp b v)(xs:list v)(e:Exp b v):Exp b v:=\n    match e with\n    | Ann e' Ty => Ann (subst_ b v eq f xs e') Ty\n    | Var x     =>\n        match in_dec eqDec x xs with\n        | left _    => Var x    (* x is deemed bound    -> Var x                *)\n        | right _   => f x      (* x is deemed free     -> f x                  *)\n        end\n    | App t1 t2 => App (subst_ b v eq f xs t1) (subst_ b v eq f xs t2)\n    | Lam x t1  => Lam x (subst_ b v eq f (x :: xs) t1)  (* x now bound         *)\n    end.\nArguments subst_ {b} {v} {eq}.\n\nDefinition subst(b v:Type)(eq:Eq v)(f:v -> Exp b v)(e:Exp b v):Exp b v:=\n    subst_ f [] e.\n\nArguments subst {b} {v} {eq}.\n\nLemma substAnn : forall (b v:Type)(eq:Eq v)(f:v -> Exp b v)(e:Exp b v)(Ty:T b),\n    subst f (Ann e Ty) = Ann (subst f e) Ty.\nProof. intros b v eq f e Ty. reflexivity. Qed.\n\nLemma substVar : forall (b v:Type)(eq:Eq v)(f:v -> Exp b v)(x:v),\n    subst f (Var x) = f x.\nProof. intros b v eq f x. reflexivity. Qed.\n\nLemma substApp : forall (b v:Type)(eq:Eq v)(f:v -> Exp b v)(e1 e2:Exp b v),\n    subst f (App e1 e2) = App (subst f e1) (subst f e2).\nProof. intros b v eq f e1 e2. reflexivity. Qed.\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/Logic/STLC/Subst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.7014623036992159}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\n\nImport ListNotations.\n\nRequire Import GHC.Num.\nRequire Import GHC.List.\nRequire Import Proofs.GHC.Base.\n\n(* NOTE: both GHC and Coq.Lists modules are in scope. But we import the GHC module \n   second to make it the default one. *)\n\n(* -------------------------------------------------------------------- *)\n\n(* Haskell-Coq equivalence: we can relate various operation in GHC.List with \n   those defined in Coq.Lists.List *)\n\nLemma hs_coq_lenAcc_add {A} (l : list A) (acc1 acc2 : Z) :\n  List.lenAcc l (acc1 + acc2)%Z = (lenAcc l acc1 + acc2)%Z.\nProof.\n  generalize dependent acc1; generalize dependent acc2;\n    induction l as [|x l IH]; simpl; auto; intros.\n  rewrite <-Z.add_assoc, Z.add_comm, <-Z.add_assoc, Z.add_comm, IH; do 2 f_equal;\n    apply Z.add_comm.\nQed.\n\nLemma hs_coq_lenAcc {A} (l : list A) (acc : Z) :\n  List.lenAcc l acc = (Zlength l + acc)%Z.\nProof.\n  generalize dependent acc; induction l as [|x l IH]; simpl; auto; intros.\n  rewrite Zlength_cons, Z.add_succ_l, <-IH, hs_coq_lenAcc_add, Z.add_1_r; reflexivity.\nQed.\n\nTheorem hs_coq_list_length {A} (l : list A) :\n  List.length l = Zlength l.\nProof.\n  unfold length; rewrite hs_coq_lenAcc, Z.add_0_r; reflexivity.\nQed.\n\nTheorem hs_coq_filter {A} (p : A -> bool) (l : list A) :\n  List.filter p l = Coq.Lists.List.filter p l.\nProof.\n  induction l; simpl; auto.\n  destruct (p _); f_equal; auto.\nQed.\n\nTheorem hs_coq_reverse : forall A (xs : list A), \n  List.reverse xs = Coq.Lists.List.rev xs.\nProof.\n  intros A.\n  unfold List.reverse.\n  set (rev := fix rev (arg_0__ arg_1__ : list A) {struct arg_0__} : \n   list A :=\n     match arg_0__ with\n     | nil => arg_1__\n     | cons x xs => rev xs (cons x arg_1__)\n     end).\n  induction xs.\n  simpl.\n  auto.\n  simpl.\n  rewrite <- List.rev_append_rev.\n  replace (List.rev_append xs (a :: nil)) with \n      (List.rev_append (a :: xs) nil); auto.\nQed.\n\n(* ------------------------- length ----------------------------------- *)\n\nSection Length.\n\nLocal Parameter A : Type.\n\nLemma length_nil : List.length (@nil A) = 0%Z.\nProof. reflexivity. Qed.\n\nLemma length_cons (x:A) xs : List.length (x :: xs) = (List.length xs + 1)%Z.\nProof. rewrite hs_coq_list_length. rewrite Zlength_cons. \n       rewrite hs_coq_list_length. reflexivity.\nQed.\n\nLemma length_app (xs : list A) (ys : list A) : List.length (xs ++ ys) = (List.length xs + List.length ys)%Z.\nProof.\n  rewrite !hs_coq_list_length. rewrite !Zlength_correct. \n  rewrite app_length. rewrite Nat2Z.inj_add. reflexivity.\nQed. \n\nHint Rewrite @length_nil @length_cons @length_app : hs_simpl.\n\nEnd Length.\n\n(* ------------------------- reverse ----------------------------------- *)\n\nSection Reverse.\n\nLemma reverse_nil : reverse (@nil A) = @nil A.\nProof. rewrite !hs_coq_reverse. reflexivity. Qed.\n\nLemma reverse_unit : forall (l:list A) (a:A), List.reverse (l ++ [a]) = a :: List.reverse l.\nProof. intros. rewrite !hs_coq_reverse. rewrite rev_unit. reflexivity. Qed.\n\nLemma reverse_involutive : forall l:list A, List.reverse (List.reverse l) = l.\nProof. intros. rewrite !hs_coq_reverse. rewrite rev_involutive. reflexivity. Qed.\n\nHint Rewrite @reverse_nil @reverse_unit @reverse_involutive : hs_simpl.\n\nEnd Reverse.\n\n(* -------------------------------------------------------------------- *)\n\n(* Make sure by-hand definitions are suitable for reasoning. *)\n\nLemma take_drop : forall (a:Set) (xs : list a) n,\n    xs = (List.take n xs) ++ (List.drop n xs).\nProof.\n  intros a xs.\n  induction xs; intro n.\n  unfold take. unfold drop.\n  destruct (n <=? 0)%Z; auto.\n  unfold take. unfold drop.\n  destruct (n <=? 0)%Z.\n  auto.\n  fold (@take a).\n  fold (@drop a).\n  simpl.\n  f_equal.\n  auto.\nQed.\n\n\n\nLemma List_foldl_foldr:\n  forall {a b} f (x : b) (xs : list a),\n    List.fold_left f xs x = Coq.Lists.List.fold_right (fun x g a => g (f a x)) id xs x.\nProof.\n  intros. revert x.\n  induction xs; intro.\n  * reflexivity.\n  * simpl. rewrite IHxs. reflexivity.\nQed.\n\n\nLemma reverse_append : forall A (vs1:list A) (vs0:list A)  a ,\n  (List.reverse (a :: vs0) ++ vs1 = List.reverse vs0 ++ (a :: vs1)).\nProof.\n  intros A.\n  intros.\n  rewrite hs_coq_reverse.\n  rewrite hs_coq_reverse.\n  rewrite <- List.rev_append_rev.\n  rewrite <- List.rev_append_rev.\n  simpl.\n  auto.\nQed.\n\n\nLtac expand_pairs :=\nmatch goal with\n  |- context[let (_,_) := ?e in _] =>\n  rewrite (surjective_pairing e)\nend.\n\n\nLemma flat_map_unpack_cons_f:\n  forall (A B C : Type) (f : A -> B -> C ) (xs : list (A * B)),\n   flat_map (fun '(x,y) => [f x y]) xs = map (fun '(x,y) => f x y) xs.\nProof.\n  intros.\n  induction xs.\n  * reflexivity.\n  * simpl. repeat expand_pairs. simpl.\n    f_equal. apply IHxs.\nQed.\n\n\n(* ---------------------------------- zip ----------------------------- *)\n\n(** [zip] and [unzip] *)\n\nLemma snd_unzip:\n  forall a b (xs : list (a * b)),\n  snd (List.unzip xs) = map snd xs.\nProof.\n  intros.\n  induction xs.\n  * reflexivity.\n  * simpl. repeat expand_pairs. simpl. f_equal. apply IHxs.\nQed.\n\nLemma snd_unzip_map:\n  forall a b c (f : a -> b) (g : a -> c) xs,\n  snd (List.unzip (map (fun x => (f x, g x)) xs)) = map g xs.\nProof.\n  intros.\n  induction xs.\n  * reflexivity.\n  * simpl. repeat expand_pairs. simpl. f_equal. apply IHxs.\nQed.\n\n\nLemma zip_unzip_map:\n  forall a b c (f : b -> c) (xs : list (a * b)),\n  List.zip (fst (List.unzip xs)) (Base.map f (snd (List.unzip xs)))\n  = map (fun '(x,y) => (x, f y)) xs.\nProof.\n  intros.\n  induction xs.\n  * reflexivity.\n  * simpl. repeat expand_pairs. simpl. f_equal. apply IHxs.\nQed.\n\n\nLemma unzip_zip : forall A B l (la : list A)( lb : list B),\n          List.unzip l = (la,lb) ->\n          l = List.zip la lb.\nProof.\n  induction l; intros; simpl. \n  - inversion H; simpl; auto.\n  - destruct a as [a b].\n    simpl in H.\n    destruct (List.unzip l) as [as_ bs].\n    inversion H. subst.\n    simpl.\n    erewrite IHl.\n    eauto.\n    eauto.\nQed.\n\nLemma In_zip_swap : forall {A B} {x:A}{y:B} {xs}{ys},\n      In (x,y) (List.zip xs ys) -> In (y,x) (List.zip ys xs).\nProof.\n  induction xs; intros; destruct ys; \n    simpl in *; inversion H; try contradiction.\n  - inversion H0; subst. eauto.\n  - right. eapply IHxs; eauto.\nQed.\n\n\nLemma In_zip_map : \n  forall {A B : Type} {f : A -> B} {x:A}{y:B}{xs},\n       In (x,y) (List.zip xs (map f xs)) -> y = f x.\nProof.\n  induction xs; intros; \n    simpl in *; inversion H; try contradiction.\n  - inversion H0; subst. eauto.\n  - eapply IHxs; eauto.\nQed.\n\nLemma In_zip : forall {a} {b} (x:a) (y:b) xs ys, \n    In (x,y) (List.zip xs ys) -> In x xs /\\ In y ys.\nProof.\n  induction xs;\n  intros; destruct ys; simpl in H; try contradiction.\n  destruct H as [h0 | h1].\n  - inversion h0; subst.\n    split; econstructor; eauto.\n  - simpl. edestruct IHxs; eauto.\nQed.\n\n\n\n\nLemma unzip_equal_length : \n  forall A B l (al:list A) (bl:list B), \n    List.unzip l = (al,bl) -> Datatypes.length al = Datatypes.length bl.\nProof.                           \n  induction l. intros; simpl in *. inversion H. auto.\n  intros; simpl in *.\n  destruct a as [a b].\n  destruct (List.unzip l) eqn:UL.  \n  inversion H.\n  simpl.\n  f_equal.\n  eauto.\nQed.\n\n \nLemma length_zip : forall {a}{b} (xs : list a) (ys :list b), \n             Datatypes.length xs = Datatypes.length ys ->\n             Datatypes.length xs = Datatypes.length (List.zip xs ys).\nProof.\n  induction xs; intros; destruct ys; simpl in *; try discriminate.\n  auto.\n  inversion H.\n  erewrite IHxs; eauto.\nQed.\n\n\n\nLemma map_fst_zip : forall A B  (l2:list B) (l1 : list A), \n    Datatypes.length l2 = Datatypes.length l1 -> List.map fst (List.zip l2 l1) = l2.\n  intros A B l2. \n  induction l2; intros; simpl in *. auto.\n  destruct l1; simpl in *.\n  inversion H.\n  f_equal. \n  apply IHl2.\n  inversion H.\n  auto.\nQed.  \n\n\nLemma map_snd_zip : forall A B  (l1:list B) (l2 : list A), \n    Datatypes.length l1 = Datatypes.length l2 -> List.map snd (List.zip l1 l2) = l2.\nProof.\n  intros A B l1. \n  induction l1; intros; destruct l2; simpl in *; auto.\n  inversion H.\n  f_equal. \n  apply IHl1.\n  inversion H.\n  auto.\nQed.  \n\n\n\nLemma In_zip_fst : forall {A B} {x:A}{y:B} {xs}{ys}{C}(zs: list C),\n             In (x,y) (List.zip xs ys) ->\n             Datatypes.length ys = Datatypes.length zs ->\n             exists z, In (x,z) (List.zip xs zs).\nProof.\n  induction xs; intros; destruct ys; destruct zs; \n    simpl in *; inversion H0; clear H0; try contradiction.\n  - destruct H. inversion H; subst. eauto.\n    edestruct IHxs; eauto.\nQed.\n\nLemma In_zip_snd : forall {A B} {x:A}{y:B} {xs}{ys}{C}(zs: list C),\n             In (x,y) (List.zip xs ys) ->\n             Datatypes.length xs = Datatypes.length zs ->\n             exists z, In (z,y) (List.zip zs ys).\nProof.\n  induction xs; intros; destruct ys; destruct zs; \n    simpl in *; inversion H0; clear H0; try contradiction.\n  - destruct H. inversion H; subst. eauto.\n    edestruct IHxs; eauto.\nQed.\n\n\n\n(* List simplifications, similar to Coq std library. *)\n\n(*\nLemma map_length : forall l, length (map l) = length l.\nProof. Admitted.\n\nLemma map_nth : forall l d n,\n    nth n (map l) (f d) = f (nth n l d).\nProof. Admitted.\n\nLemma map_app : forall l l',\n    map (l++l') = (map l)++(map l').\nProof. Admitted.\n\nHint Rewrite\n  rev_involutive \n  rev_unit \n  map_nth \n  map_length \n  seq_length \n  app_length \n  rev_length \n  app_nil_r \n  : list.\n*)", "meta": {"author": "DavidFHCh", "repo": "Tesis-FTW", "sha": "f84ab8eb92f3984e973ce6a441262d9a8a62e9b0", "save_path": "github-repos/coq/DavidFHCh-Tesis-FTW", "path": "github-repos/coq/DavidFHCh-Tesis-FTW/Tesis-FTW-f84ab8eb92f3984e973ce6a441262d9a8a62e9b0/tesis/hs-to-coq/base-thy/GHC/List.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.701397559164032}}
{"text": "Require Import List.\nRequire Import PeanoNat.\nImport PeanoNat.Nat.\n\nOpen Scope list_scope.\n\nPrint filter.\nPrint map.\n\n\nLtac dismiss := eexists; reflexivity.  (* used to finish a goal {y | y = ...} in the obvious way *)\n\n\n\nSection MapFilter.\n\n  Variables A B : Set.\n  \n  Lemma mapfilt (f: A -> B) (p : A -> bool) l : {ll | ll = map f (filter p l)}.\n  Proof.\n    generalize l.\n    fix H0 1.\n    case l0 as [|x xs]; simpl.\n    - eexists; reflexivity.\n    - edestruct H0 as [r R].\n      case (p x); simpl.\n      + rewrite <- R.\n        eexists; reflexivity.\n      + rewrite <- R.\n        eexists; reflexivity.   \n  Defined.\n\nEnd MapFilter.\n\n\nExtraction mapfilt.\n\n\nPrint length.\n\n\nSection FilterLength.\n\n  Variable A : Set.\n\n  Lemma count (p : A -> bool) l : {y | y = length (filter p l)}.\n  Proof.\n    generalize l.\n    fix H0 1.\n    case l0 as [|x xs]; simpl.\n    - dismiss.\n    - edestruct H0 as [r R].\n      case (p x); simpl.\n      + rewrite <- R.\n        dismiss.\n      + rewrite <- R.\n        dismiss.\n  Defined.\n\n  Lemma lt_S_S : forall n m, S n < S m <-> n < m.\n  Proof.\n    split.\n    apply Lt.lt_S_n. apply Lt.lt_n_S.\n  Qed.\n  \n  Lemma reflect_rewrite P p Q q : (P <-> Q) -> Bool.reflect P p -> Bool.reflect Q q -> p = q.\n  Proof.\n    intros. case H0; case H1; try reflexivity.\n    - intros; absurd Q; try assumption; apply H; assumption.\n    - intros; absurd P; try assumption; apply H; assumption.\n  Qed.\n\n  Lemma ltb_S_S : forall n m, (S n <? S m) = (n <? m).\n  Proof.\n    intros.\n    eapply reflect_rewrite.\n    eapply lt_S_S.\n    apply ltb_spec0.\n    apply ltb_spec0.\n  Qed.\n\n \n  Lemma less_than (p : A -> bool) n l :\n    {y | y = (length (filter p l) <? n)}.\n  Proof.\n    generalize l n.\n    fix H0 1.\n    case l0 as [|x xs]; simpl.\n    - dismiss.\n    - \n      case (p x); simpl.\n      + intro; case n0.\n        * compute. dismiss.\n        * intros; rewrite ltb_S_S.\n          ecase H0 as [r R].\n          rewrite <- R. dismiss.\n      + intros; ecase H0 as [r R].\n        rewrite <- R. dismiss.\n  Defined.\n        \nEnd FilterLength.\n\n\nExtraction count.\nExtraction less_than.\n\n", "meta": {"author": "corwin-of-amber", "repo": "various-proofs", "sha": "e7c19549f1d573487f9fb3ebd5d6b80b2c52184b", "save_path": "github-repos/coq/corwin-of-amber-various-proofs", "path": "github-repos/coq/corwin-of-amber-various-proofs/various-proofs-e7c19549f1d573487f9fb3ebd5d6b80b2c52184b/funcprogs/map-filter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7013975536029766}}
{"text": "Set Warnings \"-notation-overridden, -parsing\".\nFrom LF Require Export Tactics.\n\nDefinition injective {A B} (f : A -> B) :=\n  forall x y : A, f x = f y -> x = y.\n\nLemma succ_inj : injective S.\nProof.\n  unfold injective. intros x y H.\n  injection H as H. apply H.\nQed.\n\nExample and_example : 3 + 4 = 7 /\\ 2 * 2 = 4.\nProof. split; reflexivity. Qed.\n\nLemma and_intro : forall A B : Prop, A -> B -> A /\\ B.\nProof. intros A B HA HB; split; assumption. Qed.\n\nExample and_exercise :\n  forall n m : nat, n + m = 0 -> n = 0 /\\ m = 0.\nProof.\n  intros n m H. apply and_intro.\n  - induction n as [| n' IHn'].\n    + reflexivity.\n    + simpl in H. discriminate H.\n  - destruct m as [| m'].\n    + reflexivity.\n    + rewrite plus_comm in H. simpl in H. discriminate H.\nQed.\n\nLemma and_example2 :\n  forall n m : nat, n = 0 /\\ m = 0 -> n + m = 0.\nProof.\n  intros n m [H1 H2]. rewrite H1, H2. reflexivity.\nQed.\n\nLemma and_example3 :\n  forall n m : nat, n + m = 0 -> n * m = 0.\nProof.\n  intros n m H.\n  assert (H' : n = 0).\n  { apply and_exercise in H. destruct H as [Hn Hm]. assumption. }\n  rewrite H'. simpl. reflexivity.\nQed.\n\nLemma proj1 : forall P Q : Prop, P /\\ Q -> P.\nProof. intros P Q [HP HQ]; assumption. Qed.\n\nLemma proj2 : forall P Q : Prop, P /\\ Q -> Q.\nProof. intros P Q [HP HQ]; assumption. Qed.\n\nTheorem and_commut : forall P Q : Prop, P /\\ Q -> Q /\\ P.\nProof. intros P Q [HP HQ]; split; assumption. Qed.\n\nTheorem and_assoc : forall P Q R : Prop,\n    P /\\ (Q /\\ R) -> (P /\\ Q) /\\ R.\nProof.\n  intros P Q R [HP [HQ HR]]. split.\n  - split; assumption.\n  - assumption.\nQed.\n\nLemma or_example :\n  forall n m : nat, n = 0 \\/ m = 0 -> n * m = 0.\nProof.\n  intros n m [Hn | Hm].\n  - rewrite Hn. simpl. reflexivity.\n  - rewrite Hm. rewrite mult_comm. simpl. reflexivity.\nQed.\n\nLemma or_intro_l : forall A B : Prop, A -> A \\/ B.\nProof. intros A B HA; left; assumption. Qed.\n\nLemma or_intro_r : forall A B : Prop, B -> A \\/ B.\nProof. intros A B HB; right; assumption. Qed.\n\nLemma zero_or_succ :\n  forall n : nat, n = 0 \\/ n = S (pred n).\nProof.\n  intro n. destruct n as [| n'] eqn:E.\n  - left. reflexivity.\n  - right. simpl. reflexivity.\nQed.\n\nModule MyNot.\n  Definition not (P : Prop) := P -> False.\n\n  Notation \"~ x\" := (not x) : type_scope.\nEnd MyNot.\n\nTheorem ex_falso_quodlibet : forall P : Prop,\n    False -> P.\nProof. intros P HF. destruct HF. Qed.\n\nFact not_implies_our_not : forall P : Prop,\n    ~ P -> (forall Q : Prop, P -> Q).\nProof.\n  unfold not. intros Pf H Q P.\n  apply H in P. destruct P.\nQed.\n\nNotation \"x <> y\" := (~(x = y)).\n\nTheorem zero_not_one : 0 <> 1.\nProof. unfold not. intro H. discriminate H. Qed.\n\nTheorem not_False : ~ False.\nProof. unfold not. intro H. assumption. Qed.\n\nTheorem contradiction_implies_anything : forall P Q : Prop,\n    ( P /\\ ~P) -> Q.\nProof.\n  intros P Q [H1 H2].\n  unfold not in H2.\n  apply H2 in H1. destruct H1.\nQed.\n\nTheorem double_neg : forall P : Prop, P -> ~ ~ P.\nProof.\n  intros P HP.\n  unfold not. intro HPF. apply HPF in HP. assumption.\nQed.\n\nTheorem contrapositive : forall P Q : Prop,\n    (P -> Q) -> (~ Q -> ~ P).\nProof.\n  intros P Q H.\n  unfold not. intros HQF HP.\n  apply H in HP. apply HQF in HP. assumption.\nQed.\n\nTheorem not_both_true_and_false : forall P : Prop,\n    ~(P /\\ ~P).\nProof.\n  unfold not. intros P [H1 H2]. apply H2 in H1. assumption.\nQed.\n\nTheorem not_true_is_false : forall b : bool,\n    b <> true -> b = false.\nProof.\n  intros [] H.\n  - unfold not in H. exfalso.\n    apply H. reflexivity.\n  - reflexivity.\nQed.\n\nLemma True_is_true : True.\nProof. apply I. Qed.\n\nModule MyIff.\n  Definition iff (P Q : Prop) := (P -> Q) /\\ (Q -> P).\n\n  Notation \"P <-> Q\" := (iff P Q)\n                          (at level 95, no associativity) : type_scope.\n\nEnd MyIff.\n\nTheorem iff_sym : forall P Q : Prop, (P <-> Q) -> (Q <-> P).\nProof. intros P Q [HAB HBA]. split; assumption. Qed.\n\nLemma not_true_iff_false : forall b,\n    b <> true <-> b = false.\nProof.\n  intros b. split.\n  - apply not_true_is_false.\n  - intro H. rewrite H. unfold not. intro 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  intros P Q R. split.\n  - intros [HP | [HQ HR]].\n    + split; left; apply HP.\n    + split; right; assumption.\n  - intros [[HP | HQ] [HP' | HR]].\n    + left; assumption.\n    + left; assumption.\n    + left; assumption.\n    + right; split; assumption.\nQed.\n\nFrom Coq Require Import Setoids.Setoid.\n\nLemma mult_O : forall n m, n * m = 0 <-> n = 0 \\/ m = 0.\nProof.\n  intros n m. split.\n  - intro H. destruct n as [| n'].\n    + left. reflexivity.\n    + destruct m as [| m'].\n      * right. reflexivity.\n      * simpl in H. discriminate H.\n  - intros [Hn | Hm].\n    + rewrite Hn; simpl. reflexivity.\n    + rewrite Hm; rewrite mult_comm; simpl. reflexivity.\nQed.\n\nLemma or_assoc :\n  forall P Q R : Prop, P \\/ (Q \\/ R) <-> (P \\/ Q) \\/ R.\nProof.\n  intros P Q R. split.\n  - intros [HP | [HQ | HR]].\n    + left; left; assumption.\n    + left; right; assumption.\n    + right; assumption.\n  - intros [[HP | HQ] | HR].\n    + left; assumption.\n    + right; left; assumption.\n    + right; right; assumption.\nQed.\n\nLemma mult_O_3 :\n  forall n m p, n * m * p = 0 <-> n = 0 \\/ m = 0 \\/ p = 0.\nProof.\n  intros n m p. rewrite mult_O. rewrite mult_O. rewrite or_assoc.\n  reflexivity.\nQed.\n\nLemma apply_iff_example :\n  forall n m : nat, n * m = 0 -> n = 0 \\/ m = 0.\nProof. intros n m H. apply mult_O. apply H. Qed.\n\nLemma four_is_even : exists n : nat, 4 = n + n.\nProof. exists 2. reflexivity. Qed.\n\nTheorem exists_example_2 : forall n,\n    (exists m, n = 4 + m) -> (exists o, n = 2 + o).\nProof.\n  intros n [m Hm]. exists (2 + m).\n  simpl in *. apply Hm.\nQed.\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. unfold not. intros [x H'].\n  apply H'. apply H.\nQed.\n\nFixpoint In {A : Type} (x : A) (l : list A) : Prop :=\n  match l with\n  | [] => False\n  | x' :: l' => x = x' \\/ In x l'\n  end.\n\nExample In_example_1 : In 4 [1; 2; 3; 4; 5].\nProof. simpl. right; right; right; left; reflexivity. Qed.\n\nExample In_example_2 :\n  forall n, In n [2; 4] -> exists n', n = 2 * n'.\nProof.\n  intros n H. simpl in H. destruct H.\n  - rewrite H. exists 1. reflexivity.\n  - destruct H.\n    + rewrite H. exists 2. reflexivity.\n    + destruct H.\nQed.\n\nLemma In_map :\n  forall (A B : Type) (f : A -> B) (l : list A) (x : A),\n    In x l -> In (f x) (map f l).\nProof.\n  intros. induction l as [| h t IHt].\n  - simpl in H. destruct H.\n  - simpl in H. simpl. destruct H.\n    + rewrite H. left. reflexivity.\n    + apply IHt in H. right. assumption.\nQed.\n\nLemma In_map_iff :\n  forall (A B : Type) (f : A -> B) (l : list A) (y : B),\n    In y (map f l) -> exists x, f x = y /\\ In x l.\nProof.\n  intros. induction l as [| h t IHt].\n  - simpl in H. destruct H.\n  - simpl in H. destruct H.\n    + exists h. split.\n      * symmetry. apply H.\n      * simpl. left. reflexivity.\n    + apply IHt in H. destruct H. exists x.\n      destruct H. split.\n      * apply H.\n      * simpl; right; assumption.\nQed.\n\nLemma In_app_iff : forall A l l' (a : A),\n    In a (l ++ l') <-> In a l \\/ In a l'.\nProof.\n  intros A l l' a.\n  split.\n  - intro H. induction l as [| h t IH].\n    + simpl in H. right. apply H.\n    + simpl in H. destruct H.\n      * left. simpl. left. apply H.\n      * apply IH in H. simpl. destruct H.\n        left. right. apply H. right. apply H.\n  - intros [Hl | Hr].\n    + induction l as [| h t IH].\n      * inversion Hl.\n      * simpl in Hl. destruct Hl.\n        { rewrite <- H. simpl. left. reflexivity. }\n        { simpl. right. apply IH. apply H. }\n    + induction l as [| h t IH].\n      * simpl. apply Hr.\n      * simpl. right. apply IH.\nQed.\n\nFixpoint All {T : Type} (P : T -> Prop) (l : list T) : Prop :=\n  match l with\n  | [] => True\n  | h :: t => P h /\\ All P t\n  end.\n\nLemma All_In : forall T (P : T -> Prop) (l : list T),\n    (forall x, In x l -> P x) <-> All P l.\nProof.\n  intros. split.\n  - intro H. induction l as [| h t IHt].\n    + reflexivity.\n    + simpl. split.\n      * apply H. simpl. left. reflexivity.\n      * apply IHt. intros x H'. apply H. simpl; right. assumption.\n  - intros H x H'. induction l as [| h t IHt].\n    + simpl in H'. destruct H'.\n    + simpl in H. simpl in H'. destruct H. destruct H'.\n      * rewrite H1. apply H.\n      * apply IHt. apply H0. apply H1.\nQed.\n\nDefinition combine_odd_even (Podd Peven : nat -> Prop)\n  : nat -> Prop :=\n  fun n => if oddb n then Podd n else Peven n.\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.\n  unfold combine_odd_even.\n  destruct (oddb n) eqn:E.\n  - apply H1. reflexivity.\n  - apply H2. 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 -> Podd n.\nProof.\n  intros. unfold combine_odd_even in H.\n  rewrite H0 in H. 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. unfold combine_odd_even in H.\n  rewrite H0 in H. assumption.\nQed.\n\nLemma plus_comm3 :\n  forall x y z, x + (y + z) = (z + y) + x.\nProof.\n  intros x y z.\n  rewrite plus_comm.\n  rewrite (plus_comm y z).\n  reflexivity.\nQed.\n\nLemma in_not_nil :\n  forall A (x : A) (l : list A), In x l -> l <> [].\nProof.\n  intros. unfold not. intro H'. destruct l.\n  - simpl in H. assumption.\n  - discriminate H'.\nQed.\n\nLemma in_not_nil_42 :\n  forall l : list nat, In 42 l -> l <> [].\nProof.\n  apply (in_not_nil nat 42).\nQed.\n\nExample lemma_application_ex :\n  forall {n : nat} {ns : list nat},\n    In n (map (fun m => m * 0) ns) -> n = 0.\nProof.\n  intros n ns H.\n  induction ns.\n  - simpl in H. destruct H.\n  - simpl in H. destruct H.\n    + rewrite mult_comm in H. simpl in H. apply H.\n    + apply IHns. apply H.\nQed.\n\nExample function_equality_ex1 :\n  (fun x => 3 + x) = (fun x => (pred 4) + x).\nProof. simpl. reflexivity. Qed.\n\nAxiom functional_extensionality :\n  forall {X Y : Type} {f g : X -> Y},\n    (forall (x : X), f x = g x) -> f = g.\n\nExample function_equality_ex2 :\n  (fun x => plus x 1) = (fun y => plus 1 y).\nProof.\n  apply functional_extensionality. intro x.\n  apply plus_comm.\nQed.\n\nPrint Assumptions function_equality_ex2.\n\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\nLemma tr_rev_correct : forall X, @tr_rev X = @rev X.\n  intro X. apply functional_extensionality.\n  intro x. induction x as [| h t IHt].\n  - reflexivity.\n  - simpl. unfold tr_rev.\n    simpl. unfold tr_rev in IHt. rewrite <- IHt.\n    assert (H : forall (X : Type) (l1 l2 : list X),\n               rev_append l1 l2 = rev_append l1 [] ++ l2).\n    { intros X0 l1.  induction l1.\n      - simpl. reflexivity.\n      - simpl. intro l2. rewrite (IHl1 [x]).\n        rewrite <- app_assoc. simpl. apply IHl1.\n    }\n    rewrite <- H. reflexivity.\nQed.\n\nExample even_42_bool : evenb 42 = true.\nProof. reflexivity. Qed.\n\nExample even_42_prop : exists k, 42 = double k.\nProof. exists 21. reflexivity. Qed.\n\nTheorem evenb_double : forall k, evenb (double k) = true.\nProof.\n  intro k. induction k as [|k' IHk'].\n  - reflexivity.\n  - simpl. apply IHk'.\nQed.\n\nTheorem evenb_double_conv : forall n,\n    exists k, n = if evenb n then double k else S (double k).\nProof.\n  intro n. induction n as [| n' IHn'].\n  - exists 0. reflexivity.\n  - destruct IHn'. destruct (evenb n') eqn:E.\n    + exists x. rewrite evenb_S. rewrite E.\n      simpl. rewrite H. reflexivity.\n    + exists (S x). rewrite evenb_S. rewrite E.\n      simpl. rewrite H. reflexivity.\nQed.\n\nTheorem even_bool_prop : forall n,\n    evenb n = true <-> exists k, n = double k.\nProof.\n  intro n. split.\n  - intro H. assert (H' : exists k, n = if evenb n then double k\n                                        else S (double k)).\n    { apply evenb_double_conv. }\n    rewrite H in H'. assumption.\n  - intro H. destruct H. rewrite H. apply evenb_double.\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  - intro H. rewrite H. apply eqb_refl.\nQed.\n\nExample even_1000 : exists k, 1000 = double k.\nProof. apply even_bool_prop. reflexivity. Qed.\n\nLemma plus_eqb_example : forall n m p : nat,\n    n =? m = true -> n + p =? m + p = true.\nProof.\n  intros. rewrite eqb_eq in H. rewrite H.\n  apply eqb_refl.\nQed.\n\nLemma andb_true_iff : forall b1 b2 : bool,\n    b1 && b2 = true <-> b1 = true /\\ b2 = true.\nProof.\n  intros b1 b2. split.\n  - intro H. split.\n    + apply (andb_true_elim2 b2).\n      rewrite andb_commutative. assumption.\n    + apply (andb_true_elim2 b1). assumption.\n  - intros [H1 H2]. rewrite H1, H2. reflexivity.\nQed.\n\nLemma orb_true_iff : forall b1 b2,\n    b1 || b2 = true <-> b1 = true \\/ b2 = true.\nProof.\n  intros b1 b2. split.\n  - intro H. destruct b1 eqn:Eb1.\n    + left. reflexivity.\n    + simpl in H. right. apply H.\n  - intros [H1 | H2].\n    + rewrite H1. simpl. reflexivity.\n    + rewrite H2. destruct b1; reflexivity.\nQed.\n\nTheorem eqb_neq : forall x y : nat,\n    x =? y = false <-> x <> y.\nProof.\n  intros x y. split.\n  - intro H. unfold not. rewrite <- eqb_eq.\n    intro H'. rewrite H in H'. discriminate H'.\n  - intro H. destruct (x =? y) eqn:E.\n    + rewrite eqb_eq in E. rewrite E in H. unfold not in H.\n      exfalso. apply H. reflexivity.\n    + reflexivity.\nQed.\n\nFixpoint eqb_list {A : Type} (eqb : A -> A -> bool) (l1 l2 : list A)\n  : bool :=\n  match l1, l2 with\n  | [], [] => true\n  | [], _ => false\n  | _ , [] => false\n  | h1 :: t1, h2 :: t2 => if eqb h1 h2 then eqb_list eqb t1 t2 else false\n  end.\n\nLemma 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 l1. induction l1 as [| h1 t1 IHt1].\n  - intro l2. split.\n    + intro H'. destruct l2 eqn:E.\n      * reflexivity.\n      * simpl in H'. discriminate H'.\n    + intro H'. rewrite <- H'. reflexivity.\n  - intro l2. split.\n    + intro H'. destruct l2 as [| h2 t2] eqn:E.\n      * simpl in H'. discriminate H'.\n      * simpl in H'. destruct (eqb h1 h2) eqn:E'.\n        rewrite H in E'. rewrite IHt1 in H'.\n        rewrite E'. rewrite H'. reflexivity.\n        discriminate H'.\n    + intro H'. destruct l2 as [| h2 t2] eqn:E.\n      * discriminate H'.\n      * simpl. injection H'. intros. rewrite <- H in H1.\n        rewrite H1. apply IHt1. apply H0.\nQed.\n\nCheck @forallb.\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. induction l as [| h t IHt].\n  - split.\n    + intro H. reflexivity.\n    + intro H. reflexivity.\n  - split.\n    + intro H. simpl in H. destruct (test h) eqn:E.\n      * simpl. split. apply E. apply IHt. apply H.\n      * discriminate H.\n    + intro H. simpl in H. destruct H. simpl. \n      rewrite H. apply IHt. apply H0.\nQed.\n\n(** Classical vs. Constructive Logic *)\n\nDefinition excluded_middle := forall P : Prop, P \\/ ~ P.\n\nTheorem restricted_excluded_middle : forall P b,\n    (P <-> b = true) -> P \\/ ~ P.\nProof.\n  intros P [] H.\n  - left. rewrite H. reflexivity.\n  - right. rewrite H. intros constra. discriminate constra.\nQed.\n\nTheorem restricted_excluded_middle_eq : forall n m : nat,\n    n = m \\/ n <> m.\nProof.\n  intros n m.\n  apply (restricted_excluded_middle (n = m) (n =? m)).\n  rewrite eqb_eq. reflexivity.\nQed.\n\nTheorem excluded_middle_irrefutable : forall P : Prop,\n    ~~(P \\/ ~P).\nProof.\n  intro P. unfold not. intro H. apply H. right.\n  intro H'. apply H. left. apply H'.\nQed.\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  intros. unfold excluded_middle in H.\n  unfold not in H0. destruct H with (P x).\n  - apply H1.\n  - unfold not in H1. exfalso. apply H0. exists x. apply H1.\nQed.\n\nDefinition peirce := forall P Q : Prop, ((P -> Q) -> P) -> P.\n\nDefinition double_negation_elimination := forall P : Prop, ~~ P -> P.\n\nDefinition de_morgan_not_and_not := forall P Q : Prop,\n    ~(~P /\\ ~Q) -> P \\/ Q.\n\nDefinition implies_to_or := forall P Q : Prop,\n    (P -> Q) -> (~P \\/ Q).\n\nTheorem excluded_middle_iff_peirce : excluded_middle <-> peirce.\nProof.\n  unfold excluded_middle. unfold peirce. split.\n  - intros H P Q. intro H1. destruct H with P.\n    + assumption.\n    + apply H1. destruct H with Q.\n      * intro H3. assumption.\n      * intro H3. apply H0 in H3. destruct H3.\n  - intros H P. apply (H (P \\/ ~P) False).\n    intro H1. apply excluded_middle_irrefutable in H1.\n    destruct H1.\nQed.\n\nTheorem double_negation_elimination_valid :\n  excluded_middle <-> double_negation_elimination.\nProof.\n  split. \n  - (* -> *) intros E P.\n    destruct (E P) as [H' | H'].\n    + intro HP. apply H'.\n    + intro HNP.\n      unfold not in H'.\n      unfold not in HNP.\n      apply HNP in H'.\n      inversion H'.\n  - (* <- *) intros DNE EXM.\n    apply DNE. apply excluded_middle_irrefutable.\nQed.\n\nTheorem de_morgan_not_and_not_valid :\n  excluded_middle <-> de_morgan_not_and_not.\nProof.\n  split.\n  - (* -> *) intros E P Q.\n    destruct (E P) as [HP | HP].   \n    + intro H. left. apply HP.\n    + destruct (E Q) as [HQ | HQ].\n      * intro H. right. apply HQ.\n      * intro H. exfalso. apply H. split.\n        { apply HP. }\n        { apply HQ. }\n  - (* <- *) intros D E.\n    apply D.\n    unfold not.\n    intros [H1 H2].\n    apply H2. apply H1.\nQed.\n\nTheorem implies_to_or_valid :\n  excluded_middle <-> implies_to_or.\nProof.\n  split.\n  - (* -> *) intros E P Q.\n    destruct (E P) as [HP | HP].\n    + intro H. right. apply H. apply HP.\n    + intro H. left. apply HP.\n  - (* <- *) intros IO E.\n    rewrite -> or_comm. apply IO. intro HE. apply HE.\nQed.", "meta": {"author": "kailiangji", "repo": "software-foundation-exercise", "sha": "1538f43bcf240d3f9f2502aa4164cecf821da61b", "save_path": "github-repos/coq/kailiangji-software-foundation-exercise", "path": "github-repos/coq/kailiangji-software-foundation-exercise/software-foundation-exercise-1538f43bcf240d3f9f2502aa4164cecf821da61b/logic_foundation/Logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7013975491081613}}
{"text": "(*\n * Abstract Algebra\n *\n * (c) 2018, Marvin H. Sielenkemper\n *)\n\nRequire Import ProofIrrelevance.\nRequire Import EqdepFacts.\nRequire Import PeanoNat.\nRequire Import RelationClasses.\nRequire Import Morphisms.\nRequire Import FunctionalExtensionality.\nRequire Import ProofIrrelevance.\nRequire List.\n\nDelimit Scope group_scope with group.\nLocal Open Scope group_scope.\n\n\nRecord SemiGroupSig := makeSemiGroupSig {\n  carrier:> Set;\n  op: carrier -> carrier -> carrier\n}.\n\nArguments makeSemiGroupSig {carrier}.\nArguments op {s}.\n\nNotation \"x * y\" := (op x y) : group_scope.\n\nRecord SemiGroupAx(sig: SemiGroupSig) := {\n  associative: forall x y z: sig, (x * y) * z = x * (y * z);\n}.\n\nArguments associative {sig}.\n\nRecord SemiGroup := {\n  semiGroupSig:> SemiGroupSig;\n  semiGroupAx :> SemiGroupAx semiGroupSig\n}.\n\n\n\nRecord SemiGroupHom(h1 h2: SemiGroupSig) := makeSemiGroupHom {\n  semiGroupHomFun:> h1 -> h2;\n  isSemiGroupHom: forall x1 x2, semiGroupHomFun (x1 * x2) = semiGroupHomFun x1 * semiGroupHomFun x2\n}.\n\nArguments isSemiGroupHom {h1 h2}.\n\n\nDefinition abelian(h: SemiGroupSig) := forall a b: h, a * b = b * a.\n\n\n(***************************************************************)\n\n\nRecord MonoidSig := {\n  monoidSigIsSemiGroup:> SemiGroupSig;\n  unit: monoidSigIsSemiGroup;\n}.\n\nArguments unit {m}.\n\nDefinition makeMonoidSig{X: Set}(op: X -> X -> X)(unit: X): MonoidSig :=\n  Build_MonoidSig (makeSemiGroupSig op) unit.\n\nRecord MonoidAx(sig: MonoidSig) := {\n  monoidIsSemiGroupAx:> SemiGroupAx sig;\n  leftUnit:  forall x: sig, unit * x = x;\n  rightUnit: forall x: sig, x * unit = x\n}.\n\nArguments leftUnit {sig}.\nArguments rightUnit {sig}.\n\nRecord Monoid := {\n  monoidSig:> MonoidSig;\n  monoidAx :> MonoidAx monoidSig\n}.\n\n\nRecord MonoidHom(m1 m2: MonoidSig) := {\n  monoidHomIsSemiGroupHom:> SemiGroupHom m1 m2;\n  isMonoidHom: monoidHomIsSemiGroupHom unit = unit\n}.\n\nArguments isMonoidHom {m1 m2}.\n\nDefinition makeMonoidHom{m1 m2: MonoidSig}(f: m1 -> m2):\n    (forall x1 x2, f (x1 * x2) = f x1 * f x2) ->\n    f unit = unit ->\n    MonoidHom m1 m2 :=\n  fun H1 => Build_MonoidHom m1 m2 (makeSemiGroupHom m1 m2 f H1).\n\n\nLemma unitUnique(m: Monoid): forall e: m, (forall x, x * e = x) -> e = unit.\nProof.\n  intros e H.\n  rewrite <- (leftUnit m e).\n  apply H.\nQed.\n\n\n(***************************************************************)\n\n\nRecord GroupSig := {\n  groupSigIsMonoidSig:> MonoidSig;\n  invert: groupSigIsMonoidSig -> groupSigIsMonoidSig\n}.\n\nArguments invert {g}.\n\nDefinition makeGroupSig{X: Set}(op: X -> X -> X)(unit: X)(invert: X -> X): GroupSig :=\n  Build_GroupSig (makeMonoidSig op unit) invert.\n\nRecord GroupAx(sig: GroupSig) := {\n  groupIsMonoidAx:> MonoidAx sig;\n  leftInverse:  forall x: sig, invert x * x = unit;\n  rightInverse: forall x: sig, x * invert x = unit\n}.\n\nArguments leftInverse {sig}.\nArguments rightInverse {sig}.\n\nRecord Group := {\n  groupSig:> GroupSig;\n  groupAx :> GroupAx groupSig\n}.\n\n\nRecord GroupHom(g1 g2: GroupSig) := {\n  groupHomIsMonoidHom:> MonoidHom g1 g2;\n  isGroupHom: forall x, invert (groupHomIsMonoidHom x) = groupHomIsMonoidHom (invert x)\n}.\n\nArguments isGroupHom {g1 g2}.\n\nDefinition makeGroupHom{g1 g2: GroupSig}(f: g1 -> g2):\n    (forall x1 x2, f (x1 * x2) = f x1 * f x2) ->\n    f unit = unit ->\n    (forall x, invert (f x) = f (invert x)) ->\n    GroupHom g1 g2 :=\n  fun H1 H2 => Build_GroupHom g1 g2 (makeMonoidHom f H1 H2).\n\n\nLemma makeGroupAx(sig: GroupSig):\n  (forall x y z: sig, (x * y) * z = x * (y * z)) ->\n  (forall x: sig, unit * x = x) ->\n  (forall x: sig, invert x * x = unit) ->\n  GroupAx sig.\nProof.\n  intros assoc leftUnit leftInverse.\n  assert (rightInverse: forall x : sig, x * invert x = unit).\n  intros x.\n  rewrite <- (leftUnit (x * invert x)).\n  transitivity ((invert (invert x) * invert x) * (x * invert x)).\n  f_equal. symmetry. apply leftInverse.\n  transitivity (invert (invert x) * ((invert x * x) * invert x)).\n  rewrite assoc. f_equal. symmetry. apply assoc.\n  rewrite leftInverse.\n  rewrite leftUnit.\n  apply leftInverse.\n  repeat (split; try assumption).\n  intros x.\n  rewrite <- (leftInverse x).\n  rewrite <- assoc.\n  rewrite rightInverse.\n  apply leftUnit.\nQed.\n\n\nLemma inverseUnique(g: Group): forall x y: g, x * y = unit -> y = invert x.\nProof.\n  intros x y H.\n  rewrite <- (rightUnit g (invert x)).\n  rewrite <- H.\n  rewrite <- (associative g).\n  rewrite (leftInverse g).\n  symmetry. apply (leftUnit g).\nQed.\n\nLemma inverseId(g: Group): forall x: g, invert (invert x) = x.\nProof.\n  intros x.\n  symmetry.\n  apply (inverseUnique g).\n  apply (leftInverse g).\nQed.\n\nLemma inverseUnit(g: Group): @invert g unit = unit.\nProof.\n  symmetry.\n  apply (inverseUnique g).\n  apply (leftUnit g).\nQed.\n\nLemma inverseOp(g: Group): forall a b: g, invert (a * b) = invert b * invert a.\nProof.\n  intros a b.\n  symmetry.\n  apply (inverseUnique g).\n  rewrite (associative g).\n  rewrite <- (associative g b (invert b)).\n  rewrite (rightInverse g).\n  rewrite (leftUnit g).\n  apply (rightInverse g).\nQed.\n\nLemma leftInjection(g: Group): forall a x y: g, a * x = a * y-> x = y.\nProof.\n  intros a x y H.\n  rewrite <- (leftUnit g x).\n  rewrite <- (leftInverse g a).\n  rewrite (associative g).\n  rewrite H.\n  rewrite <- (associative g).\n  rewrite (leftInverse g a).\n  apply (leftUnit g y).\nQed.\n\nLemma rightInjection(g: Group): forall a x y: g, x * a = y * a -> x = y.\nProof.\n  intros a x y H.\n  rewrite <- (rightUnit g x).\n  rewrite <- (rightInverse g a).\n  rewrite <- (associative g).\n  rewrite H.\n  rewrite (associative g).\n  rewrite (rightInverse g a).\n  apply (rightUnit g y).\nQed.\n\nLemma unitUnique2(g: Group): forall x y: g, x * y = x -> y = unit.\nProof.\n  intros x y H.\n  apply (leftInjection g x).\n  rewrite (rightUnit g).\n  assumption.\nQed.\n\n\nDefinition groupFromSemigroup(h: SemiGroup):\n  h ->\n  (forall a y: h, { x | a * x = y }) ->\n  (forall a y: h, { x | x * a = y }) ->\n  Group.\n\n  intros b H1 H2.\n  destruct (H2 b b) as [e He].\n  set (inv y := proj1_sig (H2 y e)).\n  exists (makeGroupSig op e inv).\n  apply makeGroupAx; simpl.\n  apply (associative h).\n  intro a.\n  destruct (H1 b a) as [a' Ha'].\n  transitivity (e * (b * a')).\n  f_equal. auto.\n  rewrite <- (associative h).\n  rewrite He. assumption.\n  intro a.\n  unfold inv.\n  destruct (H2 a e) as [a' Ha'].\n  simpl. assumption.\nDefined.\n\n\nDefinition makeGroupHom2(g1 g2: Group)(f: g1 -> g2): (forall x1 x2, f (x1 * x2) = f x1 * f x2) -> GroupHom g1 g2.\n  intro H1.\n  assert (H2: f unit = unit).\n  apply (unitUnique2 _ (f unit)).\n  rewrite <- H1. f_equal. apply (rightUnit g1).\n  refine (makeGroupHom f H1 H2 _).\n  intro x.\n  symmetry. apply inverseUnique.\n  rewrite <- H1.\n  rewrite (rightInverse g1).\n  assumption.\nDefined.\n\nDefinition groupHomId{g: Group}: GroupHom g g := makeGroupHom2 g g (fun a => a) (fun x y => eq_refl).\n\nDefinition groupHomComp{g1 g2 g3: Group}: GroupHom g2 g3 -> GroupHom g1 g2 -> GroupHom g1 g3.\n  intros g f.\n  apply (makeGroupHom2 _ _ (fun a => g (f a))).\n  intros x y.\n  rewrite (isSemiGroupHom f).\n  rewrite (isSemiGroupHom g).\n  reflexivity.\nDefined.\n\n\nLemma groupAxFromHom{g1: GroupSig}{g2: Group}(f: GroupHom g1 g2): (forall x y, f x = f y -> x = y) -> GroupAx g1.\nProof.\n  intro H1.\n  set (H2 := isMonoidHom f).\n  apply makeGroupAx; intros; apply H1; repeat rewrite (isSemiGroupHom f); try rewrite H2.\n  apply (associative g2).\n  apply (leftUnit g2).\n  rewrite <- (isGroupHom f). apply (leftInverse g2).\nQed.\n\n\nInductive SubGroup(g: Group) :=\n  makeSubGroup(P: g -> Prop): (exists a, P a) -> (forall a b, P a -> P b -> P (a * invert b)) -> SubGroup g.\n\nDefinition isIn{g: Group}(h: SubGroup g): g -> Prop := let (P, _, _) := h in P.\n\nLemma unitIsIn{g: Group}(h: SubGroup g): isIn h unit.\nProof.\n  destruct h as [P H1 H2]. simpl.\n  destruct H1 as [a Ha].\n  rewrite <- (rightInverse g a).\n  apply H2; assumption.\nQed.\n\nLemma invertIsIn{g: Group}(h: SubGroup g)(a: g): isIn h a -> isIn h (invert a).\nProof.\n  set (H1 := unitIsIn h).\n  destruct h as [P H2 H3]. simpl in H1 |- *.\n  intro Ha.\n  rewrite <- (leftUnit g (invert a)).\n  apply H3; try assumption.\nQed.\n\nLemma opIsIn{g: Group}(h: SubGroup g)(a b: g): isIn h a -> isIn h b -> isIn h (a * b).\nProof.\n  set (H1 := invertIsIn h).\n  destruct h as [P H2 H3]. simpl in H1 |- *.\n  intros Ha Hb.\n  rewrite <- (inverseId g b).\n  apply H3; try assumption.\n  apply H1; try assumption.\nQed.\n\n\nDefinition subGroupSig{g: Group}(h: SubGroup g): GroupSig :=\n    makeGroupSig (X := sig (isIn h))\n      (fun x y =>\n        let (x', Hx) := x in\n        let (y', Hy) := y in\n          exist _ (x' * y') (opIsIn h x' y' Hx Hy))\n      (exist _ unit (unitIsIn h))\n      (fun x =>\n        let (x', Hx) := x in\n          exist _ (invert x') (invertIsIn h x' Hx)).\n\n\n\nDefinition subGroupInsert{g: Group}(h: SubGroup g): forall x, isIn h x -> subGroupSig h :=\n  match h as h' return (forall x, isIn h' x -> subGroupSig h') with\n  | makeSubGroup _ P _ _ => exist P\n  end.\n\nDefinition subGroupExtract{g: Group}(h: SubGroup g): GroupHom (subGroupSig h) g.\n  set (k := subGroupSig h).\n  apply (makeGroupHom (g1:=k) (g2:=g) (@proj1_sig _ _)); simpl.\n  intros [x Hx] [y Hy]; simpl.\n  reflexivity.\n  reflexivity.\n  intros [x Hx]; simpl.\n  reflexivity.\nDefined.\n\n\nLemma subGroupInsertUnit{g: Group}(h: SubGroup g) H: subGroupInsert h unit H = unit.\nProof.\n  destruct h as [P H1 H2].\n  simpl.\n  f_equal.\n  apply proof_irrelevance.\nQed.\n\nLemma subGroupInsertInvert{g: Group}(h: SubGroup g) x H1 H2: subGroupInsert h (invert x) H1 = invert (subGroupInsert h x H2).\nProof.\n  destruct h as [P H3 H4].\n  simpl.\n  f_equal.\n  apply proof_irrelevance.\nQed.\n\nLemma subGroupInsertOp{g: Group}(h: SubGroup g) x y H1 H2 H3:\n  subGroupInsert h (op x y) H1 = op (subGroupInsert h x H2) (subGroupInsert h y H3).\nProof.\n  destruct h as [P H4 H5].\n  simpl.\n  f_equal.\n  apply proof_irrelevance.\nQed.\n\nLemma subGroupEmbedding{g: Group}(h: SubGroup g): forall x y, subGroupExtract h x = subGroupExtract h y -> x = y.\nProof.\n  destruct h as [P H1 H2].\n  intros [x Hx] [y Hy]. simpl.\n  apply subset_eq_compat.\nQed.\n\nLemma subGroupInOut{g: Group}(h: SubGroup g) x H: subGroupExtract h (subGroupInsert h x H) = x.\nProof.\n  destruct h as [P H1 H2].\n  reflexivity.\nQed.\n\n\nLemma subGroupAx{g: Group}(h: SubGroup g): GroupAx (subGroupSig h).\nProof.\n  apply (groupAxFromHom _ (subGroupEmbedding _)).\nQed.\n\nDefinition subGroup{g: Group}(h: SubGroup g): Group := Build_Group _ (subGroupAx h).\nCoercion   subGroup: SubGroup >-> Group.\n\n\nDefinition subSubGroup_1{g: Group}(h: SubGroup g)(k: SubGroup h): SubGroup g.\n  refine (makeSubGroup g (fun x => ex (fun H => isIn k (subGroupInsert h x H))) _ _).\n  exists unit.\n  exists (unitIsIn h).\n  rewrite subGroupInsertUnit.\n  apply (unitIsIn k).\n  intros a b [Ha1 Ha2] [Hb1 Hb2].\n  exists (opIsIn _ _ _ Ha1 (invertIsIn _ _ Hb1)).\n  rewrite (subGroupInsertOp _ _ _ _ Ha1 (invertIsIn _ _ Hb1)).\n  rewrite (subGroupInsertInvert _ _ (invertIsIn _ _ Hb1) Hb1).\n  apply (opIsIn k); try assumption.\n  apply (invertIsIn k); assumption.\nDefined.\n\nDefinition subSubGroup_2{g: Group}(h k: SubGroup g): (forall a, isIn h a -> isIn k a) -> SubGroup k.\n  destruct h as [P H1 H2]. simpl.\n  intro H3.\n  refine (makeSubGroup k (fun x => P (subGroupExtract k x)) _ _).\n  destruct H1 as [a Pa]. exists (subGroupInsert k _ (H3 _ Pa)).\n  rewrite subGroupInOut. assumption.\n  intros [a Pa] [b Pb]. apply H2.\nDefined.\n\n\nDefinition subGroupCut{g: Group}(I: Type)(hi: I -> SubGroup g): SubGroup g.\n  refine (makeSubGroup g (fun x => forall i, isIn (hi i) x) _ _).\n  exists unit.\n  intro i; apply (unitIsIn _).\n  intros a b Ha Hb i.\n  apply opIsIn; try apply Ha; apply invertIsIn; apply Hb.\nDefined.\n\n\nDefinition minimalSubGroup(g: Group): SubGroup g.\n  refine (makeSubGroup g (eq unit) (ex_intro _ _ eq_refl) (fun a b => _)).\n  intros [] [].\n  rewrite inverseUnit.\n  rewrite (rightUnit g).\n  reflexivity.\nDefined.\n\nDefinition maximalSubGroup(g: Group): SubGroup g :=\n  makeSubGroup g (fun x => True) (ex_intro _ unit I) (fun _ _ _ _ => I).\n\nDefinition kern{g1 g2: Group}(f: GroupHom g1 g2): SubGroup g1.\n  set (H1 := isSemiGroupHom f).\n  set (H2 := isMonoidHom f).\n  set (H3 := isGroupHom f).\n  refine (makeSubGroup g1 (fun x => f x = unit) (ex_intro _ unit H2) (fun a b H4 H5 => _)).\n  simpl in H4, H5.\n  rewrite H1, H4.\n  rewrite <- H3.\n  rewrite H5.\n  rewrite inverseUnit.\n  apply (rightUnit g2).\nDefined.\n\nDefinition image{g1 g2: Group}(f: GroupHom g1 g2): SubGroup g2.\n  refine (makeSubGroup g2 (fun x => ex (fun y => f y = x)) (ex_intro _ _ (ex_intro _ _ (isMonoidHom f))) (fun a b => _)).\n  intros [a' Ha] [b' Hb].\n  exists (a' * invert b').\n  rewrite (isSemiGroupHom f). rewrite <- (isGroupHom f), Ha, Hb.\n  reflexivity.\nDefined.\n\n\nDefinition konjugate{g: Group}(a x: g): g := a * x * invert a.\n\nLemma konjugate_1{g: Group}(a x: g): konjugate a x = x <-> a * x = x * a.\nProof.\n  unfold konjugate.\n  split; intro H; [\n    apply (rightInjection g (invert a)); rewrite H |\n    apply (rightInjection g a); rewrite H; f_equal\n  ];\n  rewrite (associative g); rewrite (rightInverse g); rewrite (rightUnit g); reflexivity.\nQed.\n\nLemma konjugateUnit1{g: Group}(a: g): konjugate unit a = a.\nProof.\n  unfold konjugate.\n  rewrite (inverseUnit g).\n  rewrite (rightUnit g).\n  apply (leftUnit g).\nQed.\n\nLemma konjugateUnit2{g: Group}(a: g): konjugate a unit = unit.\nProof.\n  unfold konjugate.\n  rewrite (rightUnit g).\n  rewrite (rightInverse g).\n  reflexivity.\nQed.\n\nLemma konjugateOp1{g: Group}(a b x: g): konjugate a (konjugate b x) = konjugate (a * b) x.\nProof.\n  unfold konjugate.\n  rewrite (inverseOp g).\n  repeat rewrite <- (associative g).\n  reflexivity.\nQed.\n\nLemma konjugateOp2{g: Group}(a x y: g): konjugate a x * konjugate a y = konjugate a (x * y).\nProof.\n  unfold konjugate.\n  transitivity (a * x * (invert a * a) * y * invert a).\n  repeat rewrite <- (associative g).\n  reflexivity.\n  rewrite (leftInverse g).\n  rewrite (rightUnit g).\n  repeat rewrite <- (associative g).\n  reflexivity.\nQed.\n\nLemma konjugateInvert{g: Group}(a x: g): konjugate a (invert x) = invert (konjugate a x).\nProof.\n  unfold konjugate.\n  repeat rewrite (inverseOp g).\n  rewrite (inverseId g).\n  apply (associative g).\nQed.\n\nLemma konjugateInjective{g: Group}(a x y: g): konjugate a x = konjugate a y -> x = y.\nProof.\n  unfold konjugate.\n  intro H.\n  apply (leftInjection g a).\n  apply (rightInjection g (invert a)).\n  apply H.\nQed.\n\n\nDefinition centralizer(g: Group)(P: g -> Prop): SubGroup g.\n  refine (makeSubGroup g (fun a => forall x, P x -> konjugate a x = x) (ex_intro _ unit _) (fun a b => _)).\n  intros x H.\n  apply konjugateUnit1.\n  intros H1 H2 x Hx.\n  rewrite <- konjugateOp1.\n  rewrite <- H1; try assumption.\n  f_equal. clear H1 a.\n  rewrite <- (H2 x Hx) at 1.\n  rewrite konjugateOp1.\n  rewrite (leftInverse g).\n  apply konjugateUnit1.\nDefined.\n\nLemma centralizer_1{g: Group}(P: g -> Prop):\n  forall(a: centralizer g P) x, P x -> konjugate (subGroupExtract _ a) x = x.\nProof.\n  intros [a Pa]. apply Pa.\nQed.\n\nDefinition center(g: Group) := centralizer g (fun _ => True).\n\nLemma centerInCentralizer(g: Group)(P: g -> Prop): forall a, isIn (center g) a -> isIn (centralizer g P) a.\nProof.\n  intros a Ha.\n  simpl in Ha.\n  intros b Hb.\n  apply Ha.\n  auto.\nQed.\n\nLemma centerAbelian(g: Group): abelian (center g).\nProof.\n  intros [a Ha] [b Hb].\n  apply subGroupEmbedding; simpl.\n  rewrite <- konjugate_1.\n  rewrite Ha; auto.\nQed.\n\n\nDefinition normalizer{g: Group}(h: SubGroup g): SubGroup g.\n  refine (makeSubGroup g (fun a => forall x, isIn h x <-> isIn h (konjugate a x)) (ex_intro _ unit _) (fun a b => _)).\n  intro x.\n  rewrite konjugateUnit1.\n  reflexivity.\n  intros H1 H2 x.\n  rewrite <- konjugateOp1.\n  rewrite <- H1.\n  clear H1 a.\n  rewrite (H2 (konjugate (invert b) x)).\n  rewrite konjugateOp1.\n  rewrite (rightInverse g).\n  rewrite konjugateUnit1.\n  reflexivity.\nDefined.\n\nLemma normalizer_1{g: Group}(h: SubGroup g): forall a x, isIn (normalizer h) a -> isIn h x <-> isIn h (konjugate a x).\nProof.\n  simpl.\n  intros a x H. apply H.\nQed.\n\nLemma normalizer_2{g: Group}(h: SubGroup g): forall a, isIn h a -> isIn (normalizer h) a.\nProof.\n  simpl.\n  intros a Ha x.\n  split; intro Hx.\n  repeat apply (opIsIn h); try apply (invertIsIn h); assumption.\n  rewrite <- konjugateUnit1.\n  rewrite <- (rightInverse g (invert a)).\n  rewrite inverseId.\n  rewrite <- konjugateOp1.\n  apply opIsIn.\n  apply opIsIn; try assumption.\n  apply invertIsIn; assumption.\n  repeat apply invertIsIn; assumption.\nQed.\n\n\nDefinition generatedSubGroup{g: Group}(P: g -> Prop): SubGroup g.\n  refine (subGroupCut { h: SubGroup g | forall a: g, P a -> isIn h a } (@proj1_sig _ _)).\nDefined.\n\nDefinition generatedSubGroup_2{g: Group}(P: g -> Prop): SubGroup g.\n  set (reduce_1 (tx: bool * sig P) := match tx with (t, (exist _ x _)) => if t then invert x else x end).\n  set (reduce_2 := List.fold_right (fun tx y => reduce_1 tx * y) unit).\n\n  assert (H1: forall xs ys, reduce_2 (app xs ys) = reduce_2 xs * reduce_2 ys).\n  intro xs.\n  induction xs as [ | [t [x Hx]]]; intro ys.\n  rewrite (leftUnit g). reflexivity.\n  simpl. rewrite IHxs.\n  symmetry; apply (associative g).\n\n  set (invert_1 (tx: bool * sig P) := let (t, x) := tx in (negb t, x)).\n  set (invert_2 txs := List.rev (List.map invert_1 txs)).\n\n  assert (H2: forall xs, reduce_2 (invert_2 xs) = invert (reduce_2 xs)).\n  intro xs.\n  unfold reduce_2 at 1, invert_2.\n  rewrite List.fold_left_rev_right.\n  induction xs as [ | [t [x Hx]]].\n  symmetry. apply (inverseUnit g).\n  simpl. rewrite (inverseOp g).\n  set (x' := invert (if t then invert x else x)).\n  assert (x' = if negb t then invert x else x).\n  destruct t; auto; apply inverseId. destruct H.\n  generalize dependent x'. clear Hx x t. intro y.\n  rewrite <- IHxs. clear IHxs.\n  rewrite (rightUnit g).\n  generalize (List.map invert_1 xs). clear xs.\n  intros [ | x xs]; simpl.\n  symmetry; apply (leftUnit g).\n  rewrite (rightUnit g).\n  generalize (reduce_1 x) as x'. clear x. intro x.\n  generalize dependent y.\n  generalize dependent x.\n  induction xs as [ | x' xs]; auto.\n  simpl. generalize (reduce_1 x') as w. clear x'.\n  intros x y z.\n  rewrite <- IHxs.\n  rewrite <- (associative g).\n  reflexivity.\n\n  set (P' a := exists xs, reduce_2 xs = a).\n\n  apply (makeSubGroup g P').\n\n  exists unit.\n  exists nil.\n  reflexivity.\n\n  intros a b [xas Hxa] [xbs Hxb].\n  exists (xas ++ (invert_2 xbs))%list.\n  rewrite H1, H2, Hxa, Hxb.\n  reflexivity.\nDefined.\n\nLemma generatedSubGroupEquiv{g: Group}(P: g -> Prop): forall a: g, isIn (generatedSubGroup P) a <-> isIn (generatedSubGroup_2 P) a.\nProof.\n  intro a.\n  split.\n\n  intro H.\n  simpl in H.\n  refine (H (exist _ (generatedSubGroup_2 P) _)).\n  intros x Hx.\n  exists (cons (false, exist _ x Hx) nil).\n  apply (rightUnit g).\n\n  intros [txs H] [h Hh].\n  simpl. destruct H.\n  induction txs as [ | tx].\n  apply (unitIsIn h).\n  simpl.\n  apply (opIsIn h); try assumption.\n  destruct tx as [[ | ] [x Hx]]; try apply (invertIsIn h); auto.\nQed.\n\n\nDefinition konjugated{g: Group}(x y: g): Prop :=\n  ex (fun a => x = konjugate a y).\n\nLemma konjugatedReflexive{g: Group}: Reflexive (konjugated (g:=g)).\nProof.\n  exists unit.\n  rewrite konjugateUnit1.\n  reflexivity.\nQed.\n\nLemma konjugatedSymmetric{g: Group}: Symmetric (konjugated (g:=g)).\nProof.\n  intros x y [a H].\n  exists (invert a).\n  rewrite H.\n  rewrite konjugateOp1.\n  rewrite (leftInverse g).\n  rewrite konjugateUnit1.\n  reflexivity.\nQed.\n\nLemma konjugatedTransitive{g: Group}: Transitive (konjugated (g:=g)).\nProof.\n  intros x y z [a Ha] [b Hb].\n  exists (a * b).\n  rewrite Ha, Hb.\n  apply konjugateOp1.\nQed.\n\nInstance konjugatedEquiv{g: Group}: Equivalence (konjugated (g:=g)).\nProof.\n  split; [apply konjugatedReflexive | apply konjugatedSymmetric | apply konjugatedTransitive].\nQed.\n\n\nDefinition innerAutomorphism{g: Group}(a: g): GroupHom g g.\n  apply (makeGroupHom2 _ _ (konjugate a)).\n  intros x y.\n  rewrite konjugateOp2.\n  reflexivity.\nDefined.\n\n\nDefinition isNormal{g: Group}(h: SubGroup g): Prop :=\n  let (P, _, _) := h in forall x a, P (konjugate a x) -> P x.\n\nLemma normal_1{g: Group}(h: SubGroup g): isNormal h -> forall x a, isIn h (konjugate a x) <-> isIn h x.\nProof.\n  intro H1.\n  assert (H2: forall x a, isIn h (konjugate a x) -> isIn h x).\n  destruct h as [P H3 H4].\n  apply H1.\n  split; try apply H2.\n  intro H3.\n  apply (H2 _ (invert a)).\n  rewrite konjugateOp1.\n  rewrite (leftInverse g).\n  rewrite konjugateUnit1.\n  assumption.\nQed.\n\n\nLemma minimalIsNormal(g: Group): isNormal (minimalSubGroup g).\nProof.\n  intros x a H.\n  rewrite <- (konjugateUnit2 a) in H.\n  apply (konjugateInjective _ _ _ H).\nQed.\n\nLemma maximalIsNormal(g: Group): isNormal (maximalSubGroup g).\nProof.\n  intros x a H.\n  auto.\nQed.\n\nLemma kernIsNormal{g1 g2: Group}(f: GroupHom g1 g2): isNormal (kern f).\nProof.\n  set (H1 := isSemiGroupHom f).\n  set (H3 := isGroupHom f).\n  intros x a H4.\n  unfold konjugate in H4.\n  repeat rewrite H1 in H4.\n  apply (leftInjection g2 (f a)).\n  apply (rightInjection g2 (f (invert a))).\n  rewrite H4.\n  rewrite (rightUnit g2).\n  rewrite <- H3.\n  rewrite (rightInverse g2).\n  reflexivity.\nQed.\n\nLemma centerIsNormal(g: Group): isNormal (center g).\nProof.\n  intros x a Hx y _.\n  set (H := Hx (konjugate a y) I).\n  unfold konjugate in H.\n  repeat rewrite (associative g) in H.  clear Hx.\n  apply (leftInjection g) in H.\n  repeat rewrite inverseOp in H.\n  repeat rewrite <- (associative g) in H.\n  apply (rightInjection g) in H.\n  rewrite <- H at 2. clear H.\n  unfold konjugate.\n  f_equal.\n  repeat rewrite (associative g).\n  f_equal.\n  rewrite (rightInverse g).\n  rewrite (rightUnit g).\n  rewrite <- (associative g).\n  rewrite (leftInverse g).\n  rewrite (leftUnit g).\n  reflexivity.\nQed.\n\nLemma isNormalInNormalizer(g: Group)(h: SubGroup g): isNormal (subSubGroup_2 h (normalizer h) (normalizer_2 h)).\nProof.\n  destruct h as [P H1 H2]. simpl.\n  intros [x Hx] [a Ha]. simpl.\n  apply Ha.\nQed.\n\n\nDefinition injective {A B}(f: A -> B) := forall a1 a2, f a1 = f a2 -> a1 = a2.\nDefinition surjective{A B}(f: A -> B) := forall a, exists x, f x = a.\nDefinition bijective {A B}(f: A -> B) := injective f /\\ surjective f.\n\nInductive bij(A B: Type) := makeBij (u: A -> B)(v: B -> A): injective u -> (forall a, u (v a) = a) -> bij A B.\n\nDefinition bij2Fun{A B}(f: bij A B): A -> B := let (f', _, _, _) := f in f'.\nCoercion   bij2Fun: bij >-> Funclass.\n\nDefinition bijComp{A B C}(g: bij B C)(f: bij A B): bij A C.\n  refine (match g, f with\n          | makeBij _ _ g g' H1 H2, makeBij _ _ f f' H3 H4 =>\n              makeBij _ _ (fun a => g (f a)) (fun b => f' (g' b)) _ _\n          end).\n  intros a1 a2 H5.\n  apply H3.\n  apply H1.\n  apply H5.\n  intro c.\n  rewrite H4.\n  apply H2.\nDefined.\n\nDefinition bijInvert{A B}(f: bij A B): bij B A.\n  refine (match f with makeBij _ _ u v H1 H2 => makeBij _ _ v u _ _ end).\n  intros b1 b2 H3.\n  rewrite <- (H2 b1).\n  rewrite <- (H2 b2).\n  rewrite H3.\n  reflexivity.\n  intros a.\n  apply H1.\n  apply H2.\nDefined.\n\n\nInductive aut(g: Group) := makeAut (u: GroupHom g g)(v: GroupHom g g): injective u -> (forall a, u (v a) = a) -> aut g.\n\nDefinition aut2hom{g}(f: aut g): GroupHom g g := let (f', _, _, _) := f in f'.\nCoercion   aut2hom: aut >-> GroupHom.\n\nDefinition autId{g}: aut g.\n  refine (makeAut _ groupHomId groupHomId _ _).\n  intros b1 b2 H3. apply H3.\n  intros a. reflexivity.\nDefined.\n\nDefinition autComp{g}(f1 f2: aut g): aut g.\n  refine (match f1, f2 with\n          | makeAut _ f1 f1' H1 H2, makeAut _ f2 f2' H3 H4 =>\n              makeAut _ (groupHomComp f1 f2) (groupHomComp f2' f1') _ _\n          end).\n  intros a1 a2 H5.\n  apply H3.\n  apply H1.\n  apply H5. simpl.\n  intro c.\n  rewrite H4.\n  apply H2.\nDefined.\n\nDefinition autInvert{g}(f: aut g): aut g.\n  refine (match f with makeAut _ f f' H1 H2 => makeAut _ f' f _ _ end).\n  intros b1 b2 H3.\n  rewrite <- (H2 b1).\n  rewrite <- (H2 b2).\n  rewrite H3.\n  reflexivity.\n  intros a.\n  apply H1.\n  apply H2.\nDefined.\n\nDefinition autEq{g}(f1 f2: aut g): (forall x, f1 x = f2 x) -> f1 = f2.\n  destruct f1 as [[[[f1 H1] H2] H3] [[[f1' H4] H5] H6] H7 H8].\n  destruct f2 as [[[[f2 H9] Ha] Hb] [[[f2' Hc] Hd] He] Hf Hg].\n  simpl in * |- *.\n  intro Hh.\n  assert (Hi: f1 = f2).\n  apply (functional_extensionality f1 f2 Hh).\n  assert (Hj: f1' = f2').\n  apply (functional_extensionality f1' f2').\n  intro x.\n  apply Hf.\n  rewrite Hg.\n  rewrite <- Hi.\n  apply H8.\n  subst.\n  rewrite (proof_irrelevance _ H1 H9).\n  rewrite (proof_irrelevance _ H2 Ha).\n  rewrite (proof_irrelevance _ H3 Hb).\n  rewrite (proof_irrelevance _ H4 Hc).\n  rewrite (proof_irrelevance _ H5 Hd).\n  rewrite (proof_irrelevance _ H6 He).\n  rewrite (proof_irrelevance _ H7 Hf).\n  rewrite (proof_irrelevance _ H8 Hg).\n  reflexivity.\nDefined.\n\n\nDefinition AutSig(g: Group): GroupSig := makeGroupSig (X := aut g) autComp autId autInvert.\n\nDefinition Aut(g: Group): Group.\n  exists (AutSig g).\n  apply makeGroupAx; intros; apply autEq; simpl.\n  destruct x, y, z; reflexivity.\n  destruct x; reflexivity.\n  destruct x.\n  intro a. simpl.\n  apply i.\n  rewrite e.\n  reflexivity.\nDefined.\n\n\nDefinition foo(g: Group): GroupHom g (Aut g).\n  refine (makeGroupHom2 g (Aut g)\n    (fun a => makeAut g (innerAutomorphism a)\n                        (innerAutomorphism (invert a))\n                        (fun b1 b2 => _)\n                        (fun b => _))\n    (fun a1 a2 => _)).\n  apply autEq.\n  simpl.\n  intro a3. symmetry. apply konjugateOp1.\n  Unshelve.\n  simpl.\n  apply konjugateInjective.\n  simpl.\n  rewrite konjugateOp1.\n  rewrite (rightInverse g).\n  apply konjugateUnit1.\nDefined.\n\n\nDefinition natMonoid: Monoid.\n  exists (Build_MonoidSig (makeSemiGroupSig plus) 0).\n  repeat split; simpl.\n  symmetry. apply Nat.add_assoc.\n  apply Nat.add_0_r.\nDefined.\n", "meta": {"author": "sielenk", "repo": "coq-playground", "sha": "a1ac659ce5724fc2ae0953653570d6113d41f7f2", "save_path": "github-repos/coq/sielenk-coq-playground", "path": "github-repos/coq/sielenk-coq-playground/coq-playground-a1ac659ce5724fc2ae0953653570d6113d41f7f2/Algebra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7013811925415141}}
{"text": "From Coq Require Import Arith Relations Lia.\nFrom AlmostFull.Default Require Import AlmostFull.\nFrom AlmostFull.Default Require Import AFConstructions.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nSet Printing Implicit Defensive.\nSet Transparent Obligations.\n\n(* **************************************************************\n *                                                              * \n *  af_induction principle                                      *\n *                                                              * \n ****************************************************************)\n\n(* AfInduction *)\nTheorem af_induction:\n  forall (A:Type) (T : A -> A -> Prop) (R : A -> A -> Prop), \n  almost_full R -> \n  (forall x y, clos_trans_1n A T x y /\\ R y x -> False) -> \n  forall P : A -> Type, \n    (forall x, (forall y, T y x -> P y) -> P x) ->\n    forall a, P a.\nProof.\nintros A T R AF Disj P g.\napply well_founded_induction_type with (R := T).\ndestruct AF as (p,HSec); apply wf_from_af with (R := R) (p := p).\napply Disj. apply HSec. apply g.\nDefined.\n\n(* A very simple test that the fixpoint combinator /indeed/ gives us a fixpoint *)\n(* Fibonacci *)\nDefinition fib : nat -> nat.\nProof.\napply af_induction with (T := lt) (R := le).\n(* (i) Prove <= is AF *)\napply leq_af.\n(* (ii) Prove intersection emptyness *)\nintros x y (CT,H). induction CT; try lia.\n(* (iii) Give the functional *)\nrefine (fun x => \n  match x as w return (forall y, y < w -> nat) -> nat with \n    | O => fun frec => 1\n    | 1 => fun frec => 1\n    | (S (S x)) => fun frec => (frec (S x) _  + frec x _)%nat\n  end); firstorder.\nDefined.\n\nEval compute in (fib 0). (* 1 *) \nEval compute in (fib 1). (* 1 *)\nEval compute in (fib 2). (* 2 *)\nEval compute in (fib 3). (* 3 *)\nEval compute in (fib 4). (* 5 *)\nEval compute in (fib 5). (* 8 *)\n\n(* **************************************************************\n *                                                              * \n * A principle more akin to size-change-termination             *\n *                                                              * \n ****************************************************************)\n\n(* Power of a relation *) \nFixpoint power n X (R : X -> X -> Prop) (x y:X) :=\n  match n with \n  | O => x = y\n  | S m => exists z, R x z /\\ power m R z y\n  end.\n\n(* Addition modulo k *) \nFixpoint plus_mod_aux k n (x:nat) := \n match n with \n | O => x \n | S m => match (k - S x) with \n          | O => plus_mod_aux k m O \n          | _ => plus_mod_aux k m (S x) \n          end \n end.\n\n(* Interesting lemmas about addition modulo k *) \nLemma plus_mod_aux_fin k n (x:nat):\n  (x < k) -> plus_mod_aux k n x < k.\nProof.\ngeneralize dependent k. generalize dependent x.\ninduction n. auto. intros. simpl. destruct k. lia.\nsimpl. destruct (Nat.eq_dec (S k) (S x)). auto. inversion e.\nrewrite Nat.sub_diag.  apply IHn. auto. lia.\nassert (k - x <> O) by lia. set (k - x) as diff.\nfold diff in H0. destruct diff. firstorder.\napply IHn. lia.\nDefined.\n\nLemma plus_mod k (n:nat) (x:Finite k) : Finite k.\nProof.\ninversion x.\nrefine (@FinIntro k (plus_mod_aux k n x0) _).\napply plus_mod_aux_fin. apply H.\nDefined.\n\nLemma plus_mod_lt (m:nat): \n  forall k n, m+n < k -> plus_mod_aux k m n = (m+n)%nat.\nProof.\ninduction m. firstorder. intros. simpl. \nremember (k - S n) as j. \ndestruct j. lia.\nassert (S (m + n) = (m + (S n))%nat).\n2: { rewrite H0. apply IHm. lia. }\nlia.\nDefined.\n\nLemma plus_mod_gt (m:nat): \n forall k x, k > 0 -> m < k -> x < k -> k <= m+x -> plus_mod_aux k m x = m + x - k.\nProof.\ninduction m.\nintros; lia.\nintros. \nsimpl. remember (k - S x) as diff. destruct diff.\ndestruct k. lia.\nassert (x = k). lia. subst x.\nassert (plus_mod_aux (S k) m O = (m + O)%nat). apply plus_mod_lt. lia.\nrewrite H3. lia.\ndestruct k. lia.\nassert (plus_mod_aux (S k) m (S x) = m + (S x) - (S k)).\napply IHm. lia. lia. lia. lia.\nrewrite H3. lia.\nDefined.\n\nLemma plus_mod_diff: \n forall m k x, k > 1 -> m > 0 -> x < k -> m < k -> x <> plus_mod_aux k m x.\nProof. \nintros.\ndestruct (le_lt_dec k (m+x)).\nassert (plus_mod_aux k m x = m + x - k). \napply plus_mod_gt. lia. lia. lia. lia.\nrewrite H3. lia.\nassert (plus_mod_aux k m x = (m + x)%nat). apply plus_mod_lt. lia. \nrewrite H3. lia.\nDefined.\n\nLemma plus_mod_wraparound (m:nat):\n forall x n, x < m -> n > 0 -> \n  plus_mod_aux (n + m) m (n + x) = x.\nProof.\ninduction m. intros; lia. intros. simpl.\nremember (n + S m - (S (n + x))) as diff.\ndestruct diff. \nassert (m = x). lia. rewrite H1.\nassert (plus_mod_aux (n + S x) x O = (x + O)%nat). apply plus_mod_lt. lia.\nlia.\nassert (plus_mod_aux (S n + m) m (S n + x) = x).\napply IHm. lia. lia. \nassert ((S n + m)%nat = (n + S m)%nat). lia. rewrite <- H2.\nassert (S (n+x) = (S n + x)%nat). lia. rewrite H3. apply H1.\nDefined.\n\nLemma plus_mod_suc m :\n forall x, x < m -> plus_mod_aux (S m) m (S x) = x.\nProof.\nintros. assert (S m = (1 + m)%nat). firstorder. rewrite H0. \nassert (S x = (1 + x)%nat). firstorder. rewrite H1.\napply plus_mod_wraparound. firstorder.\nfirstorder.\nDefined.\n\nLemma ctr_from_ct X (T : X -> X -> Prop): \n forall x y, \n clos_trans_1n X T x y -> clos_refl_trans X T x y.\nProof.\nintros x y CT. induction CT. constructor 1. apply H.\neconstructor 3. constructor 1. apply H. apply IHCT.\nDefined.\n\nLemma ct_from_ctr X (T : X -> X -> Prop): \n forall x y z, \n  clos_trans X T x y -> \n  clos_refl_trans X T y z -> clos_trans_1n X T x z.\nProof.\nintros x y z Txy CTR.\ninduction CTR. apply clos_trans_t1n. apply clos_tn1_trans. \neconstructor 2. apply H. apply clos_trans_tn1. apply Txy. \napply clos_trans_t1n. apply Txy. apply IHCTR2. apply clos_t1n_trans. \napply IHCTR1. apply Txy.\nDefined.\n\n(* Some lemmas about composing diagonally *) \nLemma diag_pow_decomp k X T: \n forall x y, k > 1 -> \n clos_trans_1n _ (@lift_diag k X T) x y -> \n    exists m, m < k /\\ (eq_fin (fst y) (@plus_mod k m (fst x))) /\\ \n     ((m = O /\\ clos_trans_1n _ (power k T) (snd x) (snd y)) \\/\n      ((m > 0 /\\ exists z: Finite k * X, power m T (snd x) (snd z) /\\\n        clos_refl_trans _ (power k T) (snd z) (snd y)))).\nProof.\nintros x y kGt. \nintro CT.\ninduction CT. \nunfold lift_diag in H. unfold next_fin in H. simpl in H.\ndestruct x as ((kx,Hx),x). \ndestruct y as ((ky,Hy),y). simpl in H.\nexists 1. split. firstorder. split. destruct H. destruct H. destruct H. subst k.\nunfold plus_mod. unfold fst. unfold eq_fin. auto. unfold plus_mod_aux. simpl. \nrewrite Nat.sub_diag. apply H1. unfold plus_mod. unfold fst. unfold eq_fin.\nauto. unfold plus_mod_aux. remember (k - S kx) as diff. destruct diff.\nlia. lia. right. split. lia. \nexists (@FinIntro k ky Hy, y).\nsplit. simpl. exists y. firstorder.\nsimpl. apply rt_refl.\ndestruct IHCT as (m,(MltK,(HEqfin,G))).\ndestruct G. destruct H0. subst m.\ndestruct x as ((kx,Hx),x).\ndestruct y as ((ky,Hy),y).\ndestruct z as ((kz,Hz),z).\nunfold fst in *. unfold snd in *. unfold lift_diag in H. unfold fst in *. unfold snd in *.\nsimpl in H. unfold next_fin in H. destruct H. \nunfold plus_mod in HEqfin. unfold eq_fin in HEqfin. \nexists (S O). split. lia. split. unfold plus_mod. unfold eq_fin.\ndestruct H. destruct H. subst ky.  simpl in HEqfin. subst kz. simpl.\nremember (k - S kx) as diff. destruct diff. auto. lia. simpl.\ndestruct H. subst ky.  simpl in HEqfin. subst kz.\nremember (k - S kx) as diff. destruct diff. lia. reflexivity.\nright. split. auto. \nexists (@FinIntro k ky Hy,y). split. simpl. exists y. split. apply H0. reflexivity.\napply ctr_from_ct. apply H1.\ndestruct H0. destruct H1. destruct H1.\n\ndestruct (eq_nat_dec k (S m)).\n(* Case that we have to wrap-around *)\nexists O. split. lia. split.\n2: { \n  left.\n  assert (power k T (snd x) (snd x0)).\n  subst k. simpl. exists (snd y). split. destruct H. apply H3.\n  apply H1. split. reflexivity.\n  eapply ct_from_ctr. 2: apply H2.\n  constructor 1.\n  subst k. simpl. exists (snd y). split. destruct H. apply H4. apply H1.\n}\ndestruct x as ((kx,Hx),x).\ndestruct y as ((ky,Hy),y).\ndestruct z as ((kz,Hz),z).\nunfold fst. \nunfold plus_mod. simpl. unfold eq_fin. unfold fst in HEqfin. \nunfold plus_mod in HEqfin. unfold eq_fin in HEqfin. subst kz. subst k. \nunfold lift_diag in H. unfold fst in H. unfold snd in H. unfold next_fin in H.\nsimpl in H. destruct H. destruct H. destruct H. subst ky. inversion H.\nassert (plus_mod_aux (S m) m O = (m + O)%nat). apply plus_mod_lt. lia.\nrewrite H4. auto. destruct H. subst ky. \napply plus_mod_suc. lia. \n(* No wraparound needed here *)\nexists (S m). split.  lia.\nsplit. \n2: {\n  right. split. lia. \n  exists x0. split. simpl. exists (snd y). split. destruct H. apply H3.\n  apply H1. apply H2. \n}\ndestruct x as ((kx,Hx),x).\ndestruct y as ((ky,Hy),y).\ndestruct z as ((kz,Hz),z).\nunfold fst. unfold plus_mod. unfold eq_fin. unfold plus_mod in HEqfin. \nunfold fst in *. unfold snd in *. unfold eq_fin in HEqfin. subst kz.\nunfold lift_diag in H. unfold fst in H. unfold snd in H. destruct H.\nunfold next_fin in H. destruct H. destruct H. subst.\nsimpl. rewrite Nat.sub_diag. reflexivity. simpl.\ndestruct H. subst ky.\nremember (k - S kx) as diff. destruct diff. lia. reflexivity.\nDefined.\n\nLemma diag_pow_decomp_mod k X T: \n forall x y, k > 1 -> \n clos_trans_1n _ (@lift_diag k X T) x y -> \n    clos_trans_1n X (power k T) (snd x) (snd y) /\\ eq_fin (fst x) (fst y) \\/ \n    ~ (eq_fin (fst x) (fst y)).\nProof.\nintros x y kGt CT. \ndestruct (diag_pow_decomp kGt CT) as (m,H).\ndestruct H. destruct H0. destruct H1.\ndestruct H1. subst m. left. split. apply H2. destruct x. destruct y. unfold fst in *. unfold snd in *. simpl. \nunfold plus_mod in H0. destruct f. destruct f0. unfold eq_fin in *. simpl in H0. auto.\nright. destruct H1. destruct x. destruct y. unfold plus_mod in H0. unfold fst in *. unfold snd in *.\ndestruct f. destruct f0. unfold eq_fin in *. subst x2.\napply plus_mod_diff. firstorder. firstorder. firstorder. apply H.\nDefined.\n\nLemma af_power_induction_non_trivial: \n  forall (A:Type) k\n  (T : A -> A -> Prop) \n  (R : A -> A -> Prop), \n  k > 1 -> almost_full R -> \n (forall x y, @clos_trans_1n _ (power k T) x y /\\ R y x -> False) -> \n forall P : A -> Type, \n (forall x, (forall y, T y x -> P y) -> P x) -> \n forall x, P x.\nProof.\nintros X k T R kGt afR Hct P frec.\nassert (forall (x: Finite k * X), P (snd x)).\napply af_induction with (T := @lift_diag k X T) (R := @lift_pointwise k X R).\n(* Almost Full condition *)\nunfold lift_pointwise; apply af_intersection. \napply af_cofmap; apply af_finite. apply af_cofmap; apply afR.\n(* Intersection emptyness *)\nintros x y (CTxy,Tyx). \ninduction CTxy. unfold lift_diag in H. unfold lift_pointwise in Tyx.\nunfold next_fin in H.\ndestruct x. destruct y. simpl in H. destruct f. destruct f0. simpl in Tyx.\ndestruct H. unfold eq_fin in H. unfold eq_fin in Tyx. lia.\ndestruct x as ((kx,Hx),x).\ndestruct y as ((ky,Hy),y).\ndestruct z as ((kz,Hz),z).\nunfold lift_diag in H. unfold next_fin in H. simpl in H. destruct H as (H2,H4).\nunfold lift_pointwise in Tyx. simpl in Tyx. unfold eq_fin in Tyx. destruct Tyx as (H3,H5).\nassert (clos_trans_1n X (power k T) x z /\\ kx = kz \\/ (kx <> kz)).\nassert (@clos_trans_1n (Finite k * X) (@lift_diag k X T) \n                        (FinIntro (k:=k) (x:=kx) Hx, x) \n                        (FinIntro (k:=k) (x:=kz) Hz, z)).\nconstructor 2 with (y := (@FinIntro k ky Hy,y)).\nunfold lift_diag. unfold fst. unfold snd. split. unfold next_fin.\napply H2. apply H4. apply CTxy.\ndestruct (diag_pow_decomp_mod kGt H). simpl in H0.\ndestruct H0. left. split. apply H0. unfold eq_fin in H1. apply H1.\nunfold eq_fin in H0. unfold fst in H0. right. apply H0. \nfirstorder.\n(* Functional requirement *)\nintros. destruct x as ((kx,Hx),x). unfold snd.\napply frec. intros. \ndestruct kx.\n  (* kx = O *) \n  assert (k-1 < k). lia.\n  intros. apply (X0 (@FinIntro k (k-1) H0,y)). simpl. \n  unfold lift_diag. unfold fst. unfold snd. split. unfold next_fin. lia. apply H.\n  (* Now it is an (S kx) *) \n  assert (kx < k). intuition auto; lia.\n  intros. apply (X0 (@FinIntro k kx H0,y)). simpl. unfold lift_diag. simpl. split. \n  simpl. unfold next_fin. right. intuition lia. apply H.\n(* Show the goal *)\nintros. apply frec. intros. apply (X0 (@FinIntro k 1 kGt, y)).\nDefined.\n\n(* AfPowerInduction *)\nLemma af_power_induction: \n  forall (A:Type) k\n  (T : A -> A -> Prop) (R : A -> A -> Prop), \n  k >= 1 -> almost_full R -> \n  (forall x y,\n    clos_trans_1n A (power k T) x y /\\ R y x -> False) -> \n  forall P : A -> Type, \n  (forall x, (forall y, T y x -> P y) -> P x) -> \n  forall x, P x.\nProof.\nintros.\ndestruct (le_lt_dec k 1). assert (k = 1). lia. \napply af_induction with (T := T) (R := R). apply H0. \nintros. eapply H1. split. 2: { destruct H3. apply r. }\nsubst k. simpl. \ndestruct H3. clear H3 H H1 l. induction H2. constructor. exists y. auto.\nconstructor 2 with (y := y). exists y. auto. auto.\napply X. \napply af_power_induction_non_trivial with (k := k) (T := T) (R := R).\nlia. assumption. assumption. assumption.\nDefined.\n\n(* **************************************************************\n *                                                              * \n * A particular mutual induction principle                      *\n *                                                              * \n ****************************************************************)\n\nDefinition lift_rel_union (A:Type) (B:Type) \n                          (TA : A -> A -> Prop) (TB : B -> B -> Prop)\n                          (SA : A -> B -> Prop) (SB : B -> A -> Prop) \n                          (x : A + B) \n                          (y : A + B) : Prop.\nProof.\ndestruct x as [xl|xr]. \ndestruct y as [yl|yr]. apply (TA xl yl). apply (SA xl yr).\ndestruct y as [yl|yr]. apply (SB xr yl). apply (TB xr yr).\nDefined. \n\n(* AfInduction *)\n\nLemma af_mut_induction_aux:\n   forall (A:Type) (B:Type) \n          (TA : A -> A -> Prop) (SA : A -> B -> Prop) \n          (TB : B -> B -> Prop) (SB : B -> A -> Prop)\n          (R : A + B -> A + B -> Prop),\n          almost_full R -> \n          (forall x y, @clos_trans_1n (A+B) (@lift_rel_union _ _ TA TB SA SB) x y /\\ R y x -> False) -> \n          forall (P : A -> Type) (Q : B -> Type),\n             (forall x : A, (forall y, TA y x -> P y) ->\n                            (forall y, SB y x -> Q y) -> P x) -> \n             (forall x : B, (forall y, TB y x -> Q y) -> \n                            (forall y, SA y x -> P y) -> Q x) ->  \n          forall a: A+B, match a with \n                         | inl l => P l\n                         | inr r => Q r\n                         end.\nProof.\nintros A B TA SA TB SB R Raf HTrans P Q fA fB.\napply af_induction with (R := R) (T := @lift_rel_union _ _ TA TB SA SB).\napply Raf. intros. eapply HTrans. apply H. intros.\ndestruct x. apply fA. intros. remember (X (inl _ y)). simpl in y0. apply y0. apply H.\nintros. remember (X (inr _ y)). simpl in y0. apply y0. apply H.\napply fB. intros. remember (X (inr _ y)). simpl in y0. apply y0. apply H.\nintros. remember (X (inl _ y)). simpl in y0. apply y0. apply H. \nDefined.\n\nLemma af_mut_induction : forall (A:Type) (B:Type) \n (TA : A -> A -> Prop) (SA : A -> B -> Prop) \n (TB : B -> B -> Prop) (SB : B -> A -> Prop)\n (R : A + B -> A + B -> Prop),\n almost_full R -> \n (forall x y, @clos_trans_1n (A+B) (@lift_rel_union _ _ TA TB SA SB) x y /\\ R y x -> False) -> \n forall (P : A -> Type) (Q : B -> Type),\n    (forall x : A, (forall y, TA y x -> P y) ->\n                   (forall y, SB y x -> Q y) -> P x) -> \n    (forall x : B, (forall y, TB y x -> Q y) -> \n                   (forall y, SA y x -> P y) -> Q x) ->  \n (forall a, P a) * (forall b, Q b).\nProof.\nintros. \nassert (forall a:A+B, match a with \n                      | inl l => P l \n                      | inr r => Q r\n                      end).\neapply af_mut_induction_aux. apply H. apply H0. apply X. apply X0.\nsplit. intros. remember (X1 (inl _ a)). auto. \nintros. remember (X1 (inr _ b)). auto.\nDefined.\n", "meta": {"author": "coq-community", "repo": "almost-full", "sha": "0320247f651548e061ab5a2fed52f91ab959894d", "save_path": "github-repos/coq/coq-community-almost-full", "path": "github-repos/coq/coq-community-almost-full/almost-full-0320247f651548e061ab5a2fed52f91ab959894d/theories/Default/AlmostFullInduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7013621278387092}}
{"text": "\nRequire Import Arith NArith Pow Compatibility Lia.\nOpen Scope positive_scope.\nImport Monoid_def.\nRequire Import Recdef  Wf_transparent. \n\n(** * Basic lemmas about positive and N *)\n\nDefinition pos_eq_dec : forall p p':positive, {p = p'}+{p <> p'}.\nProof.  decide equality. Defined.\n\nLemma N_0_le_n: forall n:N, (0 <= n)%N.\nProof.\n destruct n; simpl;[reflexivity | discriminate].\nQed.   \n\nLemma Pos_to_nat_neq_0 : forall p, Pos.to_nat p <> 0%nat.\nProof.\n induction p; cbn.\n  discriminate.\n rewrite Pos2Nat.inj_xO.\n      simpl; lia.\n  discriminate.\nQed.\n\n#[global] Hint Resolve Pos_to_nat_neq_0 : chains.\n\n\n(** ** Relationship with [nat] and [N] \n*)\nLemma Npos_diff_zero : forall p, N.pos p <> 0%N.\nProof. discriminate. Qed.\n\nLemma Npos_gt_0 : forall p, (0 < N.pos p)%N.\nProof. reflexivity. Qed.\n\n#[global] Hint Resolve Npos_diff_zero  Npos_gt_0 : chains.\n\n\nLemma pos2N_inj_lt : forall n p, (n < p)%positive <-> (N.pos n < N.pos p)%N.\nProof.\n intros n p; tauto. \nQed.\n\n\nLemma pos2N_inj_add : forall n p, N.pos (n + p) = (N.pos n + N.pos p)%N.\nProof. reflexivity. Qed.\n\n\nLtac pos2nat_inj_tac :=\n  repeat (rewrite Pos2Nat.inj_add || rewrite Pos2Nat.inj_mul ||\n          rewrite Pos2Nat.inj_lt  || rewrite Pos2Nat.inj_le).\n\nLemma Pos2Nat_le_1_p : forall p, (1 <= Pos.to_nat p)%nat.\nintro p;  change (Pos.to_nat 1 <= Pos.to_nat p)%nat;\n              rewrite <-  Pos2Nat.inj_le.\n            apply Pos.le_1_l.\nQed.\n\n\nLemma N_le_1_pos : forall p, (1 <= N.pos p)%N.\nProof. destruct p; discriminate. Qed.\n\nLemma pos_le_mul : forall p q , (p <= p * q)%positive.\nProof.\n  intros p q; replace p with (p * 1)%positive at 1\n              by ( now rewrite Pos.mul_1_r). \n  apply Pos.mul_le_mono_l; apply Pos.le_1_l.\nQed.\n\n\nLemma pos_lt_mul : forall p q , (1 < q -> p < p * q)%positive.\nProof.\n  intros p q H; replace p with (p * 1)%positive at 1\n              by ( now rewrite Pos.mul_1_r). \n  apply Pos.mul_lt_mono_l; auto. \nQed.\n\n\nLemma Pos2Nat_le_n_pn :\n  forall p q,\n    (Pos.to_nat p <= Pos.to_nat p  * Pos.to_nat q)%nat.\nProof.\n intros p q;\n replace (Pos.to_nat p  * Pos.to_nat q)%nat with (Pos.to_nat (p * q))\n by (now rewrite Pos2Nat.inj_mul).\n apply Pos2Nat.inj_le; apply pos_le_mul.\nQed.\n\n#[global] Hint Resolve Pos2Nat_le_1_p : chains.\n\n(** ** Surjection from [N] into [positive] \n*)\n\nDefinition N2pos (n:N) : positive :=\n match n with 0%N => xH | Npos p => p end.\n\nLemma N2pos_pos :\n  forall i,  N2pos (Npos i) = i.\nProof. reflexivity. Qed. \n\nLemma N_pos_N2pos : forall n, 0%N <> n ->  n = Npos (N2pos n).\nProof. \n destruct n;[ now destruct 1 | reflexivity].\nQed. \n\nLemma N2pos_lt_switch : forall  n p, (0%N < n)%N ->\n                                     ( (N.pos p < n)%N <-> (p < N2pos n)%positive).\nProof.\ndestruct n.\n- split; discriminate.\n-  intros;simpl;split; now  rewrite pos2N_inj_lt.\nQed.\n\n\n\n\nLtac N2pos_simpl x := simpl (N2pos (N.pos x)) in *.\n\nLtac N2pos_destruct t y :=\n destruct t as [| y] ; [try (discriminate || contradiction) | N2pos_simpl y].\n\n\nLemma N2pos_lt_switch2 : forall  n p, (0%N < n)%N ->\n                                      ((N2pos n < p)%positive \n                                       <-> (n < N.pos p)%N).\nProof.\n intros n p H;  N2pos_destruct n n;\n split; simpl;now  rewrite pos2N_inj_lt.\nQed.\n\nLemma pos_lt_wf : well_founded Pos.lt.\nProof.\n  intros x.\n  assert (H:= wf_inverse_image_transparent  _ _ Nat.lt Pos.to_nat lt_wf).\n  assert (H0 : Relation_Definitions.inclusion\n            positive Pos.lt\n            (fun x y : positive =>\n               Nat.lt (Pos.to_nat x) (Pos.to_nat y))).\n  -  red;  intros x0 y0 ;  now rewrite Pos2Nat.inj_lt . \n  - apply  (wf_incl_transparent positive  _ _ H0 H ).\nDefined.\n\n(** Partial exact log2 function  *)\n\nFixpoint  exact_log2(p:positive) : option positive :=\nmatch p with\n  | 1%positive | xI _ => None\n  | 2%positive =>  Some xH\n  | xO q => match exact_log2 q with\n              | Some l => Some (l+1)%positive\n              | _ => None\n            end\nend.\n\n\n\n(**\nCompute exact_log2 16.\n = Some 4\n     : option positive\n\nCompute exact_log2 10.\n= None\n    : option positive\n*)\n\n\nLemma exact_log2xOx0 :\n  forall p i, exact_log2 (xO p) = Some i ->\n              exact_log2 (xO (xO p)) = Some (i+1)%positive.\nProof.\n  simpl; destruct p.\n  -  intro i; cbn; discriminate.\n  -  destruct (exact_log2 p~0) . \n     +  injection 1; intro; now subst i.\n     +  discriminate.\n  -  injection 1; intro; now subst i.\nQed.\n\nLemma exact_log2_spec :\n  forall p i: positive, exact_log2 p = Some i -> p = (2 ^ i)%positive.\nProof.\n  induction p. \n  -  simpl; discriminate.\n  - intro i; destruct p.\n    + destruct p; discriminate.\n        \n    +  case_eq (exact_log2 (xO p)).   \n       *  intros p0 H H0; generalize (exact_log2xOx0 _ _ H); intro H1.\n          generalize (IHp _ H); intro H2; rewrite H0 in H1; injection H1;\n          rewrite H2;  intro; subst i.\n          repeat rewrite Pos_pow_power.\n          rewrite Pos2Nat.inj_add.\n          rewrite power_of_plus.\n          replace (2%positive ^ Pos.to_nat 1)%M with 2%positive by reflexivity.\n          rewrite Pos.mul_xO_r.\n          now rewrite Pos.mul_1_r.\n       * cbn; destruct p.\n         destruct (exact_log2 p~1);  discriminate.\n         destruct (exact_log2 p~0);  discriminate.\n         discriminate.\n\n    + cbn;   injection 1;intro; now subst i.\n  - discriminate.\nQed.\n\n\n\n\n(** Another induction principle for positive *)\n\nLemma positive_4step_ind : forall P : positive -> Prop,\n   P 1%positive -> P 2%positive -> P 3%positive ->\n  (forall p, P p -> P (xO (xO p)) /\\ P (xI (xO p)) /\\ P (xO (xI p)) /\\\n               P (xI (xI p))) ->\n  forall p, P p.\nProof.\n  intros P H H0 H1 H2 p;  assert (P p /\\ P (xO p) /\\ P (xI p)).\n  -   induction p.\n      + repeat split; try tauto.\n        * destruct (H2 p);tauto.\n        * destruct (H2 p);tauto.\n      + repeat split; try tauto.\n        * destruct (H2 p);tauto.\n        * destruct (H2 p);tauto.\n      + repeat split;tauto.\n  - tauto.\nQed.\n\n\nLemma pos_gt_3 : forall p:positive, \n  p <> 1  -> p <> 3  ->  exact_log2 p = None ->  3 < p.\nProof.\n intro p;pattern p; apply  positive_4step_ind.\n -  destruct 1;auto.\n -  discriminate.\n -  destruct 2;auto.\n -  split; intros; now compute.\nQed.\n\n#[global] Hint Resolve pos_gt_3 : chains.\n\n(** ** Lemmas on Euclidean division \n    N.pos_div_eucl (a:positive) (b:N) : N * N \n*)\n  \nLemma pos_div_eucl_quotient_pos : forall a b q r,\n                                    N.pos_div_eucl a b = (q, r) ->\n                                    (b <= N.pos a)%N ->\n                                    b <> 0%N -> \n                                    (q <> 0%N).\nProof.\n  intros a b q r H H1; generalize (N.pos_div_eucl_spec a b); rewrite H.\n  intros  H0 H2 H3. rewrite H3 in H0 ;   simpl in H0.\n  generalize (N.pos_div_eucl_remainder a b H2);  rewrite H;  simpl;\n  intro; subst r.\n  destruct (N.lt_irrefl b);auto.\n  apply N.le_lt_trans with (N.pos a);auto.\nQed.\n\nLemma pos_div_eucl_quotient_lt : forall a b q r,\n                                   N.pos_div_eucl a b = (q, r) ->\n                                   (1 < b)%N ->\n                                   (q < N.pos a)%N.\nProof.\n  intros a b q r H H1; generalize (N.pos_div_eucl_spec a b); rewrite H.\n  destruct q.\n  - reflexivity.\n  -  intro H2; rewrite H2;  apply N.lt_le_trans with (N.pos p * b)%N.\n      + replace (N.pos p)  with ((N.pos p) * 1)%N at 1\n       by (now rewrite N.mul_1_r).\n       apply N.mul_lt_mono_pos_l; auto with chains.\n      +  apply N.le_add_r.\nQed.\n\n\nLemma N_pos_div_eucl_divides : forall i b q,\n                                 N.pos_div_eucl i (N.pos b) = (q, 0%N) ->\n                                 (b * N2pos q)%positive = i.\nProof.\n  intros i b q H;  generalize  (N.pos_div_eucl_spec   i (N.pos b)).\n  rewrite H,  N.add_0_r.\n  intro H3;  destruct q ; [discriminate | ].\n  rewrite Pos.mul_comm; injection H3; symmetry; assumption.\nQed.\n\n\n Lemma N_pos_div_eucl_rest : forall i b q r,\n                               N.pos_div_eucl i (N.pos b) = (q,  r) ->\n                               (0 < r)%N -> (0 < q)%N ->\n                               (b * N2pos q + N2pos r)%positive = i.\n Proof.\n   intros i b q r H H0 H1.   generalize  (N.pos_div_eucl_spec   i (N.pos b)).\n   rewrite H.\n   destruct r ;[discriminate | ].\n   destruct q ; [discriminate | ].\n   injection 1.\n   cbn. \n   intro H3;subst i.\n   now rewrite Pos.mul_comm.\n Qed.\n\n Lemma N_pos_div_eucl_q0 : forall i b  r,\n                             N.pos_div_eucl i (N.pos b) = (0%N,   r) ->\n                             i = N2pos r.\n\n Proof.\n   intros i b  r H;   generalize  (N.pos_div_eucl_spec   i (N.pos b)).\n   rewrite H.\n   simpl.\n   destruct r.\n   discriminate.\n   injection 1;now cbn.\n Qed.\n\n\n\n\n(** An auxiliary lemma *)\nLemma lt_S_2i : \nforall i j:nat, (i < j -> 2 * i + 1 < 2 * j)%nat.\nProof.  intros; lia. Qed.\n\nLemma N_le_mul_pos  : forall q p, (q <= q * N.pos p)%N.\nProof. \n  intros q p; replace q with (q * 1)%N at 1.\n  apply N.mul_le_mono_nonneg_l.\n  apply N_0_le_n.\n  destruct p;discriminate.\n  rewrite N.mul_1_r; auto.\nQed.\n  \n\n\n\n\n\n\n\nLtac quotient_small div_equation H :=\n  match type of div_equation with\n    (N.pos_div_eucl ?a ?b = (?q,?r)) =>\n    assert  (H : (q < N.pos a)%N);\n    [apply (pos_div_eucl_quotient_lt _ _ _ _ div_equation); auto|]\n  end.\n\nLtac rest_small div_equation H :=\n  match type of div_equation with\n    (N.pos_div_eucl ?a ?b = (?q,?r)) =>\n    let H0 := fresh \"H\" in\n    assert  (H : (r < b)%N);\n    [generalize (N.pos_div_eucl_remainder a b); simpl; intro  H0;\n     rewrite div_equation in H0; apply H0 ; try discriminate| ]\n  end.\n\n\n\n\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/additions/More_on_positive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699185, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7013621275017414}}
{"text": "Require Import QArith PArith Nat.\n\nInductive division : Type :=\n    | whole\n    | half : division -> division\n    | third : division -> division\n  .\n\nNotation \"'Half'\"     := ((half whole)) (at level 80, right associativity).\nNotation \"'Quarter'\"  := ((half (half whole))) (at level 80, right associativity).\nNotation \"'Eighth'\"   := ((half (half (half whole)))) (at level 80, right associativity).\nNotation \"'Sixteenth'\"   := ((half(half (half (half whole))))) (at level 80, right associativity).\nNotation \"'QTriplet'\"  := ((third (half (half whole)))) (at level 80, right associativity).\nNotation \"'ETriplet'\" := ((third (half (half (half whole))))) (at level 80, right associativity).\n\n(*This is would not be needed if Q.eqb existed to write eqb_division.*)\n(* turns out, it exists Qeq_bool*)\nFixpoint fraction_inverse (x : division) : nat := \n  match x with\n  | whole => 1\n  | half d => 2 * fraction_inverse d\n  | third d => 3 * fraction_inverse d\n  end.\n\nDefinition eqb (d1 d2 : division) : bool :=\n  Nat.eqb (fraction_inverse d1) (fraction_inverse d2).\n\nLemma unittest1 : eqb (Half) (Half) = true. Proof. auto. Qed.\nLemma unittest2 : eqb (Half) (Quarter) = false. Proof. auto. Qed.\n\nFixpoint fraction (x : division) : Q :=\n  match x with\n  | whole => 1\n  | half d => ((fraction d) / 2)\n  | third d => ((fraction d) / 3)\n  end.\n\nLemma unittest3 : fraction (Half) = 1 / 2 . Proof. unfold fraction. reflexivity. Qed.\nLemma unittest4 : fraction (QTriplet) = 1 / 2 / 2 / 3 . Proof. unfold fraction. reflexivity. Qed.\n\nFixpoint half_count (x : division) : nat :=\n  match x with\n  | whole => 0\n  | half d => S (half_count d)\n  | third d => half_count d\n  end.\n\nFixpoint third_count (x : division) : nat :=\n  match x with\n  | whole => 0\n  | third d => S (third_count d)\n  | half d => third_count d\n  end.\n\nFixpoint nth_half (h : nat) (base : division) : division :=\n  match h with\n  | O => base\n  | S n => half (nth_half n base )\n  end.\n\nFixpoint nth_third (h : nat) (base : division) : division :=\n  match h with\n  | O => base\n  | S n => third (nth_third n base )\n  end.\n", "meta": {"author": "fajtaiandris", "repo": "bremen", "sha": "49d9324e5894d86966884f681c09d9db876a6d09", "save_path": "github-repos/coq/fajtaiandris-bremen", "path": "github-repos/coq/fajtaiandris-bremen/bremen-49d9324e5894d86966884f681c09d9db876a6d09/theories/rhythm/Division.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7013621207656855}}
{"text": "\nRequire Import Lia.\nRequire Import ZArith.\nOpen Scope Z_scope.\n(* Goal transforming inequalities + transitivities. *)\nLemma gt_ge : forall m n, m > n -> m >= n + 1. lia. Qed.\nLemma gt_ge2 : forall m n, m > n -> m >=n. lia. Qed.\nLemma gt_ge3 : forall m n, m > n - 1 -> m >= n. lia. Qed.\nLemma gt_ge4 : forall m n, m > n - 1 -> m >= n. lia. Qed.\n\nLemma ge_gt : forall m n, m >= n + 1 <-> m > n.  lia. Qed.\nLemma ge_gt_l : forall m n, m > n -> m >= n + 1.  lia. Qed.\nLemma eq_ge: forall m n, m = n -> m >= n. lia. Qed.\n\nLemma gt_ge_gt: forall m n p, m > n -> n >= p -> m > p. lia. Qed.\nLemma gt_gt_gt: forall m n p, m > n -> n > p -> m > p. lia. Qed.\nLemma ge_ge_ge: forall m n p, m >= n -> n >= p -> m >= p. lia. Qed.\nLemma gt_plus : forall m n p, m > n -> m + p > n + p. lia. Qed.\n", "meta": {"author": "lykmast", "repo": "coq-refinements", "sha": "0ec3cbfdcf9d26c14b2781d632d33d256938c765", "save_path": "github-repos/coq/lykmast-coq-refinements", "path": "github-repos/coq/lykmast-coq-refinements/coq-refinements-0ec3cbfdcf9d26c14b2781d632d33d256938c765/theories/Arithmetic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.7013591334625672}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (x : natural) (lf1 : natural) : natural :=\n  plus (Succ Zero) y.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj208_coqofml_67nl3x.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7013108167165486}}
{"text": "Require Export Arith.\nRequire Export XR_lt_INR.\n\nLocal Open Scope R_scope.\n\nLemma INR_lt : forall n m:nat,\n  INR n < INR m ->\n  (n < m)%nat.\nProof.\n  intros n.\n  induction n as [ | n hn ].\n  {\n    intros m hm.\n    destruct m as [ | m ].\n    {\n      exfalso.\n      apply Rlt_irrefl in hm.\n      contradiction.\n    }\n    {\n      unfold lt.\n      apply le_n_S.\n      apply le_O_n.\n    }\n  }\n  {\n    intros m hnm.\n    destruct m as [ | m ].\n    {\n      exfalso.\n      clear hn.\n      apply Rlt_irrefl with R0.\n      apply Rlt_trans with (INR (S n)).\n      {\n        replace R0 with (INR 0%nat).\n        {\n          apply lt_INR.\n          unfold lt.\n          apply le_n_S.\n          apply le_O_n.\n        }\n        {\n          simpl.\n          reflexivity.\n        }\n      }\n      {\n        simpl in hnm.\n        exact hnm.\n      }\n    }\n    {\n      apply lt_n_S.\n      apply hn.\n      apply Rplus_lt_reg_r with R1.\n      rewrite <- S_INR.\n      rewrite <- S_INR.\n      exact hnm.\n    }\n  }\nQed.", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_INR_lt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7013108157678184}}
{"text": "Require Import Setoid Morphisms.\nRequire SetoidList.\nRequire Export Coq.Classes.Equivalence.\nOpen Scope equiv_scope.\n\nGlobal Set Asymmetric Patterns.\nGeneralizable All Variables.\n\n(** * Ordered Types\n\n   This file corresponds to OrderedType.v in the standard FSets/FMaps\n   library. It contains a formalization of types equipped with a total\n   and decidable order.\n   Notations on ordered types are defined in scope [compare_scope],\n   delimited by key [compare].\n   *)\nDelimit Scope compare_scope with compare.\n\n(** ** Strict orders : the [StrictOrder] class\n\n   A strict order [lt] with respect to an equivalence relation [eq]\n   on a type [A] is an antireflexive transitive relation, ie. it\n   is a transitive relation that does not contain two congruent terms.\n   We define the class [StrictOrder A lt eq] of such objects.\n   *)\nClass StrictOrder {A} lt eq {equiv : Equivalence eq} := {\n  StrictOrder_Transitive :> Transitive lt;\n  StrictOrder_Irreflexive : forall (x y : A), lt x y -> x =/= y\n}.\nDefinition lt_StrictOrder `{StrictOrder A lt_ eq_} := lt_.\n\n(** If [x] and [y] belong to a strict order, we define the\n   notations [x >>> y] and [y <<< x]. *)\nNotation \" x >>> y \" := (lt_StrictOrder y x)\n  (at level 70, no associativity, only parsing) : compare_scope.\nNotation \" x <<< y \" := (lt_StrictOrder x y)\n  (at level 70, no associativity) : compare_scope.\nOpen Scope compare_scope.\n\n(** A couple of useful basic properties about strict orders. *)\nSet Implicit Arguments. Unset Strict Implicit.\nSection StrictOrderProps.\n  Context `{StrictOrder A}.\n\n  Property lt_antirefl : forall x, ~x <<< x.\n  Proof.\n    intros; intro Hlt; apply (StrictOrder_Irreflexive x x Hlt); reflexivity.\n  Qed.\n  Property lt_not_eq : forall x y, x <<< y -> x =/= y.\n  Proof.\n    intros; apply StrictOrder_Irreflexive; auto.\n  Qed.\n  Property gt_not_eq : forall x y, x >>> y -> x =/= y.\n  Proof.\n    intros; intro abs; symmetry in abs; revert abs; apply lt_not_eq; auto.\n  Qed.\n  Property eq_not_lt : forall x y, x === y -> ~ x <<< y.\n  Proof.\n    intros; intro abs; apply (lt_not_eq abs); auto.\n  Qed.\n  Property eq_not_gt : forall x y, x === y -> ~ x >>> y.\n  Proof.\n    intros; intro abs; apply (gt_not_eq abs); auto.\n  Qed.\n  Property lt_not_gt : forall x y, x <<< y -> ~(x >>> y).\n  Proof.\n    intros; intro abs; refine (lt_not_eq _ _); shelve_unifiable.\n    transitivity y; eauto. reflexivity.\n  Qed.\nEnd StrictOrderProps.\nUnset Implicit Arguments.\n\n(** ** Ordered types : the [OrderedType] class\n\n   [OrderedType] is the class of types that enjoy decidable comparison for\n   a given setoid equality and strict order relation with respect to this\n   equality. An instance of [OrderedType] for a type [A] must bring :\n   - the equality relation [eq]\n   - a proof that [eq] is an equivalence relation\n   - the order relation [lt]\n   - an instance of [StrictOrder] for [lt] and [eq]\n   - a comparison function [cmp : A -> A -> comparison]\n   - a proof that [cmp] really implements [lt] and [eq]\n\n   With respect to the original formalization in the FSets/FMaps library,\n   the fundamental difference is that the comparison function is purely\n   computational, whereas the return type of the [compare] function in\n   [FSets.OrderedType] includes proofs. In that sense, this formalisation\n   is more similar to [FSets.OrderedTypeAlt]. To define the specification\n   that the function [cmp] must meet, unlike [OrderedTypeAlt], we use\n   the following inductive view [compare_spec] :\n   *)\nInductive compare_spec {A} eq lt (x y : A) : comparison -> Prop :=\n| compare_spec_lt : lt x y -> compare_spec eq lt x y Lt\n| compare_spec_eq : eq x y -> compare_spec eq lt x y Eq\n| compare_spec_gt : lt y x -> compare_spec eq lt x y Gt.\n\n(** [compare_spec] describes what is the correct result for a comparison\n   between two elements [x] and [y] ; in particular, a suitable comparison\n   function is a function that is included in this relation.\n\n   Given these definitions, we can now define the [OrderedType] class.\n   *)\nClass OrderedType (A : Type) := {\n  _eq : relation A;\n  _lt : relation A;\n  OT_Equivalence :> Equivalence _eq;\n  OT_StrictOrder :> StrictOrder _lt _eq;\n  _cmp : A -> A -> comparison;\n  _compare_spec : forall x y, compare_spec _eq _lt x y (_cmp x y)\n}.\n\n(** If [x] and [y] belong to an ordered type [A], we can write [compare x y]\n   to denote the comparison of [x] and [y], as well as the special handy\n   notation [x =?= y]. *)\nDefinition compare `{OrderedType A} := _cmp.\nNotation \" x =?= y \" :=\n  (compare (x :>) (y :>)) (no associativity, at level 70) : compare_scope.\n\n(** The following lemma is a convenient way to access the specification of\n   the [compare] function. Its typical use is the following : if a comparison\n   [x =?= y] appears in the Coq context, [destruct (compare_dec x y)] will\n   create 3 branches for each result of the comparison, and add the correct\n   hypothesis in each branch. It is almost as easy to work with as the\n   original dependently-typed [OrderedType.compare] function.\n   *)\nDefinition compare_dec `{H : OrderedType A} :\n  forall x y, compare_spec equiv lt_StrictOrder x y (compare x y) :=\n    @_compare_spec A H.\n\n(** [compare] is made globally opaque so that case analysis can be done\n   easily by destructing [compare_dec _ _]. *)\nGlobal Opaque compare.\n\n(** We define shortcut notations [x == y], [x << y] and [x >> y]\n   for purely computational equality and ordering tests, and\n   their specification as well. *)\nDefinition is_compare `{OrderedType A} (x y : A) c :=\n  match x =?= y, c with\n    | Eq, Eq | Lt, Lt | Gt, Gt => true\n    | _, _ => false\n  end.\nNotation \" x == y \" :=\n  (is_compare x y Eq) (no associativity, at level 70) : compare_scope.\nNotation \" x << y \" :=\n  (is_compare x y Lt) (no associativity, at level 70) : compare_scope.\nNotation \" x >> y \" :=\n  (is_compare x y Gt) (no associativity, at level 70) : compare_scope.\n\nProperty compare_1 `{OrderedType A} : forall x y, x =?= y = Lt -> x <<< y.\nProof.\n  intros; destruct (compare_dec x y); auto; congruence.\nQed.\nProperty compare_2 `{OrderedType A} : forall x y, x =?= y = Eq -> x === y.\nProof.\n  intros; destruct (compare_dec x y); auto; congruence.\nQed.\nProperty compare_3 `{OrderedType A} : forall x y, x =?= y = Gt -> x >>> y.\nProof.\n  intros; destruct (compare_dec x y); auto; congruence.\nQed.\n\n(** Decidability lemmas for equality and orders, specified in a way\n   similar to [compare_spec]. *)\nInductive decides {A} (R : relation A) (x y : A) : bool -> Prop :=\n| decides_true : R x y -> decides R x y true\n| decides_false : ~(R x y) -> decides R x y false.\n\nProperty eq_dec `{OrderedType A} :\n  forall (x y : A), decides equiv x y (x==y).\nProof.\n  intros; unfold is_compare. destruct (compare_dec x y); constructor.\n  apply lt_not_eq; auto.\n  assumption.\n  apply gt_not_eq; auto.\nQed.\nProperty lt_dec `{OrderedType A} :\n  forall x y, decides lt_StrictOrder x y (x<<y).\nProof.\n  intros; unfold is_compare. destruct (compare_dec x y); constructor.\n  assumption.\n  intro abs; apply (lt_not_eq abs); auto.\n  apply lt_not_gt; auto.\nQed.\nProperty gt_dec `{OrderedType A} :\n  forall x y, decides lt_StrictOrder y x (x>>y).\nProof.\n  intros; unfold is_compare. destruct (compare_dec x y); constructor.\n  apply lt_not_gt; auto.\n  intro abs; apply (gt_not_eq abs); auto.\n  assumption.\nQed.\n\n(** More lemmas about ordered types, in particular the fact that\n   the order relations are morphisms for equality. *)\nSet Implicit Arguments. Unset Strict Implicit.\nProperty eq_lt `{OrderedType A} :\n  forall (x x' y : A), x === x' -> x <<< y -> x' <<< y.\nProof.\n  intros; destruct (compare_dec x' y); auto.\n  contradiction (lt_not_eq H1); transitivity x'; auto.\n  contradiction (lt_not_eq (x:=x) (y:=x')); auto; transitivity y; auto.\nQed.\nCorollary eq_lt2 `{OrderedType A} :\n  forall (x x' y : A), x === x' -> x' <<< y -> x <<< y.\nProof.\n  intros; apply eq_lt with x'; auto; symmetry; auto.\nQed.\nProperty eq_gt `{OrderedType A} :\n  forall (x x' y : A), x === x' -> x >>> y -> x' >>> y.\nProof.\n  intros; destruct (compare_dec x' y); auto.\n  contradiction (gt_not_eq (x:=x) (y:=x')); auto; transitivity y; auto.\n  contradiction (gt_not_eq H1); transitivity x'; auto.\nQed.\nInstance lt_m `{OrderedType A} : Proper (_eq ==> _eq ==> iff) _lt.\nProof.\n  repeat intro; split; intro Hlt.\n  apply (eq_lt (x:=x)); auto. apply (eq_gt (x:=x0)); auto.\n  apply (eq_lt (x:=y)); try symmetry; auto.\n  apply (eq_gt (x:=y0)); try symmetry; auto.\nQed.\nInstance le_m `{OrderedType A} : Proper (_eq ==> _eq ==> iff) (complement _lt).\nProof.\n  repeat intro; split; intro Hlt; unfold complement in  *.\n  rewrite H1 in Hlt; rewrite H0 in Hlt; assumption.\n  rewrite H0, H1; assumption.\nQed.\n\n(** Shortcut lemmas for the [order] tactic *)\nSection OrderLemmas.\n  Context `{OrderedType A}.\n  Variables x y z : A.\n\n  Corollary lt_eq : x <<< y -> y === z -> x <<< z.\n  Proof.\n    intros; rewrite <- H1; assumption.\n  Qed.\n  Corollary le_eq : ~x <<< y -> y === z -> ~x <<< z.\n  Proof.\n    intros; rewrite <- H1; assumption.\n  Qed.\n  Corollary eq_le : x === y -> ~y <<< z -> ~x <<< z.\n  Proof.\n    intros; rewrite H0; assumption.\n  Qed.\n  Corollary neq_eq : x =/= y -> y === z -> x =/= z.\n  Proof.\n    intros; rewrite <- H1; assumption.\n  Qed.\n  Corollary eq_neq : x === y -> y =/= z -> x =/= z.\n  Proof.\n    intros; rewrite H0; assumption.\n  Qed.\n\n  Property le_lt_trans : ~ y <<< x -> y <<< z -> x <<< z.\n  Proof.\n    intros; destruct (compare_dec x z); auto.\n    rewrite <- H2 in H1; contradiction.\n    contradiction H0; transitivity z; auto.\n  Qed.\n  Property lt_le_trans : x <<< y -> ~ z <<< y -> x <<< z.\n  Proof.\n    intros; destruct (compare_dec x z); auto.\n    rewrite <- H2 in H1; contradiction.\n    contradiction H1; transitivity x; auto.\n  Qed.\n  Property le_neq : ~x <<< y -> x =/= y -> x >>> y.\n  Proof.\n    intros; destruct (compare_dec x y); auto; contradiction.\n  Qed.\n\n  Lemma elim_compare_eq : x === y -> x =?= y = Eq.\n  Proof.\n    intros; destruct (compare_dec x y); auto.\n    contradiction (lt_not_eq H1 H0).\n    contradiction (lt_not_eq H1 (symmetry H0)).\n  Qed.\n  Lemma elim_compare_lt : x <<< y -> x =?= y = Lt.\n  Proof.\n    intros; destruct (compare_dec x y); auto.\n    contradiction (lt_not_eq H0 H1).\n    contradiction (lt_not_gt H1 H0).\n  Qed.\n  Lemma elim_compare_gt : x >>> y -> x =?= y = Gt.\n  Proof.\n    intros; destruct (compare_dec x y); auto.\n    contradiction (lt_not_gt H1 H0).\n    contradiction (gt_not_eq H0 H1).\n  Qed.\nEnd OrderLemmas.\nUnset Implicit Arguments.\n\n(** The following is the adaptation of the original [order] tactic\n   developed by P. Letouzey in the original library. It should\n   prove exactly the same goals, with a slight decrease in performance\n   due to the extra implicit instance parameters.\n   *)\nLtac normalize_notations :=\n  match goal with\n | H : ?R ?x ?y |- _ =>\n   progress ((change (x === y) in H) || (change (x <<< y) in H) ||\n     (change (x >>> y) in H)); normalize_notations\n | H : ~(?R ?x ?y) |- _ =>\n   progress ((change (x =/= y) in H) || (change (~ x <<< y) in H) ||\n     (change (~ y <<< x) in H)); normalize_notations\n | |- ?R ?x ?y =>\n   progress (change (x === y) || change (x <<< y) || change (y <<< x))\n | |- ~?R ?x ?y =>\n   progress (change (x =/= y) || change (~x <<< y) || change (~y <<< x))\n | _ => idtac\n  end.\n\nLtac abstraction := match goal with\n | H : False |- _ => elim H\n | H : ?x <<< ?x |- _ => elim (lt_antirefl H)\n | H : ?x =/= ?x |- _ => elim (H (reflexivity x))\n | H : ?x === ?x |- _ => clear H; abstraction\n | H : ~?x <<< ?x |- _ => clear H; abstraction\n | |- ?x === ?x => reflexivity\n | |- ?x <<< ?x => elimtype False; abstraction\n | |- ~ _ => intro; abstraction\n | H1: ~?x <<< ?y, H2: ?x =/= ?y |- _ =>\n     generalize (le_neq H1 H2); clear H1 H2; intro; abstraction\n | H1: ~?x <<< ?y, H2: ?y =/= ?x |- _ =>\n     symmetry in H2; generalize (le_neq H1 H2);\n       clear H1 H2; intro; abstraction\n | H : ?x =/= ?y |- _ => revert H; abstraction\n | H : ~?x <<< ?y |- _ => revert H; abstraction\n | H : ?x <<< ?y |- _ => revert H; abstraction\n | H : ?x === ?y |- _ => revert H; abstraction\n | _ => idtac\nend.\n\nLtac do_eq a b EQ := match goal with\n | |- ?x <<< ?y -> _ => let H := fresh \"H\" in\n     (intro H;\n      (generalize (eq_lt EQ H); clear H; intro H) ||\n      (generalize (lt_eq H EQ); clear H; intro H) ||\n      idtac);\n      do_eq a b EQ\n | |- ~?x <<< ?y -> _ => let H := fresh \"H\" in\n     (intro H;\n      (generalize (eq_le (symmetry EQ) H); clear H; intro H) ||\n      (generalize (le_eq H EQ); clear H; intro H) ||\n      idtac);\n      do_eq a b EQ\n | |- ?x === ?y -> _ => let H := fresh \"H\" in\n     (intro H;\n      (generalize (transitivity (symmetry EQ) H); clear H; intro H) ||\n      (generalize (transitivity H EQ); clear H; intro H) ||\n      idtac);\n      do_eq a b EQ\n | |- ?x =/= ?y -> _ => let H := fresh \"H\" in\n     (intro H;\n      (generalize (eq_neq (symmetry EQ) H); clear H; intro H) ||\n      (generalize (neq_eq H EQ); clear H; intro H) ||\n      idtac);\n      do_eq a b EQ\n | |- a <<< ?y => apply eq_lt with b; [exact (symmetry EQ)|]\n | |- ?y <<< a => apply lt_eq with b; [|exact (symmetry EQ)]\n | |- a === ?y => transitivity b; [exact EQ|]\n | |- ?y === a => transitivity b; [|exact (symmetry EQ)]\n | _ => idtac\n end.\n\nLtac propagate_eq := abstraction; match goal with\n | |- ?a === ?b -> _ =>\n     let EQ := fresh \"EQ\" in (intro EQ; do_eq a b EQ; clear EQ);\n     propagate_eq\n | _ => idtac\nend.\n\n(* Example test `{OrderedType A} : *)\n(*   forall (x x' x'' x''' y a b c d e f g h : A), *)\n(*     x === x -> x === x' -> x' === x'' -> *)\n(*     x =/= y -> b =/= x -> *)\n(*     y >>> x -> c <<< x -> *)\n(*     x'' === x''' -> *)\n(*     ~a >>> x -> ~d <<< x -> *)\n(*     e === x -> x === e -> *)\n(*     f >>> x. *)\n(* Proof. *)\n(*   intros. *)\n(*   propagate_eq. *)\n\nLtac do_lt x y LT := match goal with\n | |- x <<< y -> _ => intros _; do_lt x y LT\n | |- y <<< ?z -> _ => let H := fresh \"H\" in\n     (intro H; generalize (transitivity LT H); intro); do_lt x y LT\n | |- ?z <<< x -> _ => let H := fresh \"H\" in\n     (intro H; generalize (transitivity H LT); intro); do_lt x y LT\n | |- _ <<< _ -> _ => intro; do_lt x y LT\n\n | |- ~y <<< x -> _ => intros _; do_lt x y LT\n | |- ~x <<< ?z -> _ => let H := fresh \"H\" in\n     (intro H; generalize (le_lt_trans H LT); intro); do_lt x y LT\n | |- ~?z <<< y -> _ => let H := fresh \"H\" in\n     (intro H; generalize (lt_le_trans LT H); intro); do_lt x y LT\n | |- ~_ <<< _ -> _ => intro; do_lt x y LT\n | _ => idtac\n end.\n\nDefinition hide_lt `{StrictOrder A lt_ eq_} := lt_StrictOrder.\n\nLtac propagate_lt := abstraction; match goal with\n | |- ?x <<< ?y -> _ =>\n     let LT := fresh \"LT\" in\n       (intro LT; do_lt x y LT; change (hide_lt x y) in LT);\n       propagate_lt\n | _ => unfold hide_lt in *\nend.\n\nLtac order :=\n intros;\n normalize_notations;\n abstraction;\n propagate_eq;\n propagate_lt;\n auto;\n propagate_lt;\n eauto.\n\nLtac false_order := elimtype False; order.\n\nHint Extern 0 (_eq _ _) => reflexivity.\nHint Extern 0 (_ === _) => reflexivity.\nHint Extern 2 (_eq _ _) => symmetry; assumption.\nHint Extern 2 (_ === _) => symmetry; assumption.\nHint Extern 1 (Equivalence _) => constructor; congruence.\nHint Extern 1 (Equivalence _) => apply OT_Equivalence.\nHint Extern 1 (StrictOrder _) => apply OT_StrictOrder.\nHint Extern 1 (RelationClasses.StrictOrder _) =>\n  constructor; repeat intro; order.\nHint Extern 1 (Proper _ _) => apply lt_m.\nHint Extern 1 (Proper _ _) => repeat intro; intuition order.\n\n(** ** Specific Ordered types : [OrderedType] with specific equality\n\n   Sometimes, one wants to consider ordered types where the equality\n   has to be Leibniz equality or any other specific equality. Because there\n   is no 'with' construct for  typeclasses, as there is for modules, we\n   define another class for these types and show that such types\n   also match [OrderedType]. An alternative would be to take the equality\n   relation ouf of the [OrderedType] instance and add it as a parameter.\n*)\nClass SpecificOrderedType\n  (A : Type) (eqA : relation A) := {\n  SOT_Equivalence :> Equivalence eqA ;\n  SOT_lt : relation A;\n  SOT_StrictOrder : StrictOrder SOT_lt eqA;\n  SOT_cmp : A -> A -> comparison;\n  SOT_compare_spec : forall x y, compare_spec eqA SOT_lt x y (SOT_cmp x y)\n}.\nInstance SOT_as_OT `{SpecificOrderedType A} : OrderedType A := {\n  _eq := eqA;\n  OT_StrictOrder := SOT_StrictOrder;\n  _compare_spec := SOT_compare_spec\n}.\nInstance SOT_SO_to_SO `{SpecificOrderedType A eqA} : StrictOrder SOT_lt eqA | 4.\nProof.\n  intros; apply SOT_StrictOrder.\nDefined.\n\n(** ** Usual Ordered types : [OrderedType] with Leibniz equality\n\n   A typical case is to require an instance of [OrderedType] where the equality\n   is the Leibniz equality. We define the notation [UsualOrderedType] for that\n   purpose.\n   *)\nNotation \"'UsualOrderedType' A\" :=\n  (SpecificOrderedType A (@eq A))(at level 30).\n\n(** * Facts about setoid list membership\n\n   The remainer of this file correspond to the final section\n   of the [OrderedTypeFacts] functor and the [KeyOrderedType] functor.\n   They are used especially in [SetList] and [MapList].\n   *)\nSet Implicit Arguments. Unset Strict Implicit.\nSection ForNotations.\n  Import SetoidList.\n  Notation In:=(InA _eq).\n  Notation Inf:=(lelistA _lt).\n  Notation Sort:=(sort _lt).\n  Notation NoDup:=(NoDupA _eq).\n\n  Context `{Helt : OrderedType elt}.\n  Implicit Types x y : elt.\n\n  Lemma In_eq : forall l x y, x === y -> In x l -> In y l.\n  Proof. apply InA_eqA; eauto with typeclass_instances. Qed.\n\n  Lemma ListIn_In : forall l x, List.In x l -> In x l.\n  Proof. apply In_InA; eauto with typeclass_instances. Qed.\n\n  Lemma Inf_lt : forall l x y, x <<< y -> Inf y l -> Inf x l.\n  Proof.\n    apply InfA_ltA; constructor; repeat intro; order.\n  Qed.\n\n  Lemma Inf_eq : forall l x y, x === y -> Inf y l -> Inf x l.\n  Proof.\n    apply InfA_eqA; eauto with typeclass_instances.\n  Qed.\n\n  Lemma Sort_Inf_In : forall l x a, Sort l -> Inf a l -> In x l -> a <<< x.\n  Proof.\n    apply SortA_InfA_InA; eauto with typeclass_instances.\n  Qed.\n\n  Lemma ListIn_Inf : forall l x, (forall y, List.In y l -> x <<< y) -> Inf x l.\n  Proof. exact (@In_InfA _ _lt). Qed.\n\n  Lemma In_Inf : forall l x, (forall y, In y l -> x <<< y) -> Inf x l.\n  Proof.\n    apply InA_InfA; eauto with typeclass_instances.\n  Qed.\n\n  Lemma Inf_alt :\n    forall l x, Sort l -> (Inf x l <-> (forall y, In y l -> x <<< y)).\n  Proof.\n    apply InfA_alt; eauto with typeclass_instances.\n  Qed.\n\n  Lemma Sort_NoDup : forall l, Sort l -> NoDup l.\n  Proof.\n    apply SortA_NoDupA; eauto with typeclass_instances.\n  Qed.\nEnd ForNotations.\nUnset Implicit Arguments.\nHint Resolve @ListIn_In @Sort_NoDup @Inf_lt.\nHint Immediate @In_eq @Inf_lt.\n\nModule KeyOrderedType.\nSection KeyOrderedType.\n  Import SetoidList.\n  Set Implicit Arguments.\n  Unset Strict Implicit.\n\n  Variable key : Type.\n  Hypothesis (key_OT : OrderedType key).\n  Variable elt : Type.\n\n  Definition eqk (p p':key*elt) := fst p === fst p'.\n  Definition eqke (p p':key*elt) :=\n    fst p === fst p' /\\ (snd p) = (snd p').\n  Definition ltk (p p':key*elt) := fst p <<< fst p'.\n\n  Local Instance eqk_Equiv : Equivalence eqk.\n  Proof.\n    constructor; repeat intro; unfold eqk in *; eauto. order.\n  Qed.\n  Local Instance eqke_Equiv : Equivalence eqke.\n  Proof.\n    constructor; repeat intro; unfold eqke in *; intuition; order.\n  Qed.\n  Local Instance ltk_SO : RelationClasses.StrictOrder ltk.\n  Proof.\n    constructor; repeat intro; unfold ltk in *; intuition order.\n  Qed.\n  Local Instance ltk_m : Proper (eqk ==> eqk ==> iff) ltk.\n  Proof.\n    repeat intro; unfold ltk, eqk in *; intuition order.\n  Qed.\n  Ltac teauto := eauto with typeclass_instances.\n\n  Hint Unfold eqk eqke ltk.\n  Hint Extern 2 (eqke ?a ?b) => split.\n\n  (* eqke is stricter than eqk *)\n  Lemma eqke_eqk : forall x x', eqke x x' -> eqk x x'.\n  Proof.\n    unfold eqk, eqke; intuition.\n  Qed.\n\n  (* ltk ignore the second components *)\n  Lemma ltk_right_r : forall x k e e', ltk x (k,e) -> ltk x (k,e').\n  Proof. auto. Qed.\n\n  Lemma ltk_right_l : forall x k e e', ltk (k,e) x -> ltk (k,e') x.\n  Proof. auto. Qed.\n  Hint Immediate ltk_right_r ltk_right_l.\n\n  (* eqk, eqke are equalities, ltk is a strict order *)\n  Lemma eqk_refl : forall e, eqk e e.\n  Proof. auto. Qed.\n\n  Lemma eqke_refl : forall e, eqke e e.\n  Proof. auto. Qed.\n\n  Lemma eqk_sym : forall e e', eqk e e' -> eqk e' e.\n  Proof. auto. Qed.\n\n  Lemma eqke_sym : forall e e', eqke e e' -> eqke e' e.\n  Proof. unfold eqke; intuition. Qed.\n\n  Lemma eqk_trans : forall e e' e'', eqk e e' -> eqk e' e'' -> eqk e e''.\n  Proof.\n    intros; unfold eqk in *; auto; transitivity (fst e'); auto.\n  Qed.\n\n  Lemma eqke_trans : forall e e' e'', eqke e e' -> eqke e' e'' -> eqke e e''.\n  Proof.\n    unfold eqke; intuition; [ order | congruence ].\n  Qed.\n\n  Lemma ltk_trans : forall e e' e'', ltk e e' -> ltk e' e'' -> ltk e e''.\n  Proof.\n    intros; unfold ltk in *; auto; transitivity (fst e'); auto.\n  Qed.\n\n  Lemma ltk_not_eqk : forall e e', ltk e e' -> ~ eqk e e'.\n  Proof.\n    unfold eqk, ltk; auto; intros; apply lt_not_eq; auto.\n  Qed.\n\n  Lemma ltk_not_eqke : forall e e', ltk e e' -> ~eqke e e'.\n  Proof.\n    unfold eqke, ltk; intuition; simpl in *; subst.\n    exact (lt_not_eq H H1).\n  Qed.\n\n  Hint Resolve eqk_trans eqke_trans eqk_refl eqke_refl.\n  Hint Resolve ltk_trans ltk_not_eqk ltk_not_eqke.\n  Hint Immediate eqk_sym eqke_sym.\n\n  (* Additionnal facts *)\n\n  Lemma eqk_not_ltk : forall x x', eqk x x' -> ~ltk x x'.\n  Proof.\n    unfold eqk, ltk; simpl; auto.\n    intros; apply eq_not_lt; auto.\n  Qed.\n\n  Lemma ltk_eqk : forall e e' e'', ltk e e' -> eqk e' e'' -> ltk e e''.\n  Proof.\n    intros; unfold ltk, eqk in *; auto; order.\n  Qed.\n\n  Lemma eqk_ltk : forall e e' e'', eqk e e' -> ltk e' e'' -> ltk e e''.\n  Proof.\n      intros (k,e) (k',e') (k'',e'').\n      unfold ltk, eqk; simpl; eauto; order.\n  Qed.\n  Hint Resolve eqk_not_ltk.\n  Hint Immediate ltk_eqk eqk_ltk.\n\n  Lemma InA_eqke_eqk :\n     forall x m, InA eqke x m -> InA eqk x m.\n  Proof.\n    unfold eqke; induction 1; intuition.\n  Qed.\n  Hint Resolve InA_eqke_eqk.\n\n  Definition MapsTo (k:key)(e:elt):= InA eqke (k,e).\n  Definition In k m := exists e:elt, MapsTo k e m.\n  Notation Sort := (sort ltk).\n  Notation Inf := (lelistA ltk).\n\n  Hint Unfold MapsTo In.\n\n  (* An alternative formulation for [In k l] is [exists e, InA eqk (k,e) l] *)\n  Lemma In_alt : forall k l, In k l <-> exists e, InA eqk (k,e) l.\n  Proof.\n    firstorder.\n    exists x; auto.\n    induction H.\n    destruct y.\n    exists e; auto.\n    destruct IHInA as [e H0].\n    exists e; auto.\n  Qed.\n\n  Lemma MapsTo_eq : forall l x y e, x === y -> MapsTo x e l -> MapsTo y e l.\n  Proof.\n    intros; unfold MapsTo in *; apply InA_eqA with (x,e); teauto.\n  Qed.\n\n  Lemma In_eq : forall l x y, x === y -> In x l -> In y l.\n  Proof.\n    destruct 2 as (e,E); exists e; eapply MapsTo_eq; eauto.\n  Qed.\n\n  Lemma Inf_eq : forall l x x', eqk x x' -> Inf x' l -> Inf x l.\n  Proof. apply InfA_eqA; teauto. Qed.\n\n  Lemma Inf_lt : forall l x x', ltk x x' -> Inf x' l -> Inf x l.\n  Proof. apply InfA_ltA; teauto. Qed.\n\n  Hint Immediate Inf_eq.\n  Hint Resolve Inf_lt.\n\n  Lemma Sort_Inf_In :\n      forall l p q, Sort l -> Inf q l -> InA eqk p l -> ltk q p.\n  Proof.\n    apply SortA_InfA_InA; teauto.\n  Qed.\n\n  Lemma Sort_Inf_NotIn :\n      forall l k e, Sort l -> Inf (k,e) l ->  ~In k l.\n  Proof.\n    intros; red; intros.\n    destruct H1 as [e' H2].\n    elim (@ltk_not_eqk (k,e) (k,e')).\n    eapply Sort_Inf_In; eauto.\n    red; simpl; auto.\n  Qed.\n\n  Lemma Sort_NoDupA: forall l, Sort l -> NoDupA eqk l.\n  Proof.\n    apply SortA_NoDupA; teauto.\n  Qed.\n\n  Lemma Sort_In_cons_1 : forall e l e', Sort (e::l) -> InA eqk e' l -> ltk e e'.\n  Proof.\n   inversion 1; intros; eapply Sort_Inf_In; eauto.\n  Qed.\n\n  Lemma Sort_In_cons_2 : forall l e e', Sort (e::l) -> InA eqk e' (e::l) ->\n      ltk e e' \\/ eqk e e'.\n  Proof.\n    inversion_clear 2; auto.\n    left; apply Sort_In_cons_1 with l; auto.\n  Qed.\n\n  Lemma Sort_In_cons_3 :\n    forall x l k e, Sort ((k,e)::l) -> In x l -> x =/= k.\n  Proof.\n    inversion_clear 1; red; intros.\n    exact (Sort_Inf_NotIn H0 H1 (In_eq H2 H)).\n  Qed.\n\n  Lemma In_inv : forall k k' e l, In k ((k',e) :: l) -> k === k' \\/ In k l.\n  Proof.\n    inversion 1.\n    inversion_clear H0; eauto.\n    destruct H1; simpl in *; intuition.\n  Qed.\n\n  Lemma In_inv_2 : forall k k' e e' l,\n      InA eqk (k, e) ((k', e') :: l) -> k =/= k' -> InA eqk (k, e) l.\n  Proof.\n   inversion_clear 1; unfold eqk in H0; simpl in H0; order.\n  Qed.\n\n  Lemma In_inv_3 : forall x x' l,\n      InA eqke x (x' :: l) -> ~eqk x x' -> InA eqke x l.\n  Proof.\n   inversion_clear 1; compute in H0; intuition.\n  Qed.\n\nEnd KeyOrderedType.\nHint Unfold eqk eqke ltk.\nHint Extern 2 (eqke ?a ?b) => split.\nHint Resolve eqk_trans eqke_trans eqk_refl eqke_refl.\nHint Resolve ltk_trans ltk_not_eqk ltk_not_eqke.\nHint Immediate eqk_sym eqke_sym.\nHint Resolve eqk_not_ltk.\nHint Immediate ltk_eqk eqk_ltk.\nHint Resolve InA_eqke_eqk.\nHint Unfold MapsTo In.\nHint Immediate Inf_eq.\nHint Resolve Inf_lt.\nHint Resolve Sort_Inf_NotIn.\nHint Resolve In_inv_2 In_inv_3.\n\nArguments eqk {key key_OT elt}.\nArguments eqke {key key_OT elt}.\nArguments ltk {key key_OT elt}.\nArguments MapsTo {key key_OT elt}.\nArguments In {key key_OT elt}.\nEnd KeyOrderedType.\n", "meta": {"author": "coq-contribs", "repo": "containers", "sha": "105a3ca030f0dc9712c88bfc87c39c33e168f1a2", "save_path": "github-repos/coq/coq-contribs-containers", "path": "github-repos/coq/coq-contribs-containers/containers-105a3ca030f0dc9712c88bfc87c39c33e168f1a2/theories/OrderedType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7013108052693423}}
{"text": "Require Export aula3 aula4 aula5 aula6.\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\nNotation \"x :: l\" := (cons x l)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition mylist1 := 1 :: (2 :: (3 :: nil)).\nDefinition mylist2 := 1 :: 2 :: 3 :: nil.\nDefinition mylist3 := [1;2;3].\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 length (l:natlist) : nat :=\n  match l with\n  | nil => O\n  | h :: t => S (length t)\n  end.\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\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", "meta": {"author": "AndressaUmetsu", "repo": "coqExercicios", "sha": "f583bea6a32ef359cbddb786f7fb71803d7bf189", "save_path": "github-repos/coq/AndressaUmetsu-coqExercicios", "path": "github-repos/coq/AndressaUmetsu-coqExercicios/coqExercicios-f583bea6a32ef359cbddb786f7fb71803d7bf189/aula7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7012893091328983}}
{"text": "(** 6. 述語論理 *)\nModule Section6.\n\n(** 述語論理 *)\n(* 述語 iszero:nat -> Prop *)\nDefinition iszero(n:nat):Prop :=\nmatch n with\n| O => True\n| _ => False\nend.\n\n(* 動作確認 *)\nEval compute in (iszero 0).\nEval compute in (iszero 3).\n\n(** forall がある場合 *)\nTheorem sample_forall : forall (X:Type)(P Q:X->Prop)(x:X),\n  P x -> (forall y:X, Q y) -> (P x /\\ Q x).\nProof.\n  (* 最初は intro(s) する。名前は判りやすく付けると良い *)\n  intros X P Q x px Hqy.\n  (* ゴールが /\\ の形ならば split. する *)\n  split.\n    (* goal = P x *)\n    assumption.\n    (* goal = Q x. Hqy の forall y の y に x を代入 *)\n    apply (Hqy x).\nQed.\n\nTheorem sample_exists : forall (P Q:nat->Prop),\n  (forall n, P n) -> (exists n, Q n) ->\n  (exists n, P n /\\ Q n).\nProof.\n  intros P Q Hpn Hqn.\n  (* exists の式は /\\ と同様に destruct する *)\n  destruct Hqn as [n' qn'].\n  (* ゴールの exists n に具体的な n' という値を示す *)\n  exists n'.\n  split.\n    (* 仮定 Hpn から P n' を得る *)\n    apply (Hpn n').\n    (* goal = Q n' *)\n    assumption.\nQed.\n\n(** 課題５：述語論理の証明 *)\nTheorem ex5_1 : forall (A:Set)(P:A->Prop),\n  (~exists a, P a) -> (forall a, ~P a).\nProof.\n(* Proof here *)\nQed.\n\nTheorem ex5_2 : forall (A:Set)(P Q:A->Prop),\n  (exists a, P a \\/ Q a) ->\n  (exists a, P a) \\/ (exists a, Q a).\nProof.\n(* Proof here *)\nQed.\n\nTheorem ex5_3 : forall (A:Set)(P Q:A->Prop),\n  (exists a, P a) \\/ (exists a, Q a) ->\n  (exists a, P a \\/ Q a).\nProof.\n(* Proof here *)\nQed.\n\nTheorem ex5_4 : forall (A:Set)(R:A->A->Prop),\n  (exists x, forall y, R x y) -> (forall y, exists x, R x y).\nProof.\n(* Proof here *)\nQed.\n\nTheorem ex5_5 : forall (A:Set)(R:A->A->Prop),\n  (forall x y, R x y -> R y x) ->\n  (forall x y z, R x y -> R y z -> R x z) ->\n  (forall x, exists y, R x y) ->\n  (forall x, R x x).\nProof.\n(* Proof here *)\nQed.\n\n(** 6.3 =を含む証明 *)\n(* =　は eq という名前で定義されている *)\nPrint eq.\n\nTheorem plus_0_l : forall n, 0 + n = n.\nProof.\n  intro n.\n  (* 0 + n をplusの定義に従い簡単にする *)\n  simpl.\n  (* = の左辺と右辺が同じ形ならば reflexivity. *)\n  reflexivity.\nQed.\n\n(* simpl では簡単にならない例 *)\nTheorem plus_0_r : forall n, n + 0 = n.\nProof.\n  intro n.\n  simpl.\nAbort. (* 中断して破棄 *)\n\n(* natに関する帰納法 *)\nCheck nat_ind.\n\n(* 証明課題を無名関数にして渡した例 *)\nCheck (nat_ind (fun n => n + 0 = n)). \n\n(* boolに関する帰納法は、単なる場合分け *)\nCheck bool_ind.\n\nTheorem plus_0_r : forall n, n + 0 = n.\nProof.\n  (* n を O と S n' とに場合分けする *)\n  induction n as [|n'].\n    (* n=0 の場合 *)\n    reflexivity.\n    (* n=S n' の場合. 簡単にする *)\n    simpl.\n    (* ゴールに対して、IHn'の左辺->右辺と書き換え *)  \n    rewrite IHn'.\n    reflexivity.\nQed.\n\n(** 課題６：n+m=m+nの証明 *)\nSearchAbout plus.\n\n(*\nplus_n_O: forall n : nat, n = n + 0\nplus_O_n: forall n : nat, 0 + n = n\nplus_n_Sm: forall n m : nat, S (n + m) = n + S m\nplus_Sn_m: forall n m : nat, S n + m = S (n + m)\nmult_n_Sm: forall n m : nat, n * m + n = n * S m\nplus_0_r: forall n : nat, n + 0 = n\nplus_0_l: forall n : nat, 0 + n = n\n*)\n\nTheorem plus_comm : forall m n, m + n = n + m.\nProof.\n(* Proof here *)\nQed.\n\n(* リストライブラリをインポート *)\nRequire Import List.\nTheorem length_app : forall (A:Type)(l1 l2:list A),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n(* (1) 最初に全て intros する場合 *)\n  intros A l1 l2.\n  induction l1 as [|a l1'].\n    simpl. reflexivity.\n    (* ここでの IHl1'は、\nIHl1' : length (l1' ++ l2) = length l1' + length l2 *)\n    simpl. rewrite IHl1'. reflexivity.\nQed.\n(* (2) 最初に全て l1 のみ intros する場合\n  intros A l1.\n  induction l1 as [|a l1'].\n    intro l2. simpl. reflexivity.\n    (* ここでの IHl1'は、任意の l2 に対する仮定\nIHl1' : forall l2 : list A, \n  length (l1' ++ l2) = length l1' + length l2 *)\n    intro l2. simpl. rewrite IHl1'. reflexivity.\nQed.\n*)\n(** 課題７：リストに関する証明 *)\nFixpoint append{A:Type}(l1 l2:list A) :=\nmatch l1 with\n| nil => l2\n| a::l1' => a::(append l1' l2)\nend.\n(* 動作確認 *)\nEval compute in (append (1::2::3::nil) (4::5::nil)).\n\nFixpoint reverse{A:Type}(l:list A):=\nmatch l with\n| nil => nil\n| a::l' => append (reverse l') (a::nil)\nend.\n(* 動作確認 *)\nEval compute in (reverse (1::2::3::4::nil)).\n\n(* Lemma は補題の意味だが、Coq の処理としては Theorem と同じ *)\nLemma append_nil : forall (A:Type)(l:list A),\n  append l nil = l.\nProof.\n(* proof here *)\nQed.\n\nLemma append_assoc : forall (A:Type)(l1 l2 l3:list A),\n  append (append l1 l2) l3 = append l1 (append l2 l3).\nProof.\n(* proof here *)\nQed.\n\nLemma reverse_append : forall (A:Type)(l1 l2:list A),\n  reverse (append l1 l2) = append (reverse l2) (reverse l1).\nProof.\n(* proof here *)\nQed.\n\nTheorem reverse_reverse : forall (A:Type)(l:list A),\n  reverse (reverse l) = l.\nProof.\n(* proof here *)\nQed.\nEnd Section6.\n\n", "meta": {"author": "tmiya", "repo": "coq", "sha": "6944819890670961f5641e89b853c6639f695251", "save_path": "github-repos/coq/tmiya-coq", "path": "github-repos/coq/tmiya-coq/coq-6944819890670961f5641e89b853c6639f695251/tutorial20120209/tutorial4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7012893021212881}}
{"text": "Require Import A1_Plan A2_Orientation .\nRequire Import B5_BetweenProp .\nRequire Import C1_Distance C3_SumDistance C6_DistanceTimesN C7_Tactics .\nRequire Import E4_Tactics .\nRequire Import F3_Graduation.\n\nSection ARCHIMEDIAN_DISTANCE.\n\nLemma GraduationSegmentSn : forall n : nat, forall A B : Point, forall Hab : A <> B, \n\tSegment A (Graduation (S n) A B Hab) B.\nProof.\n\tintros; induction n.\n\t rewrite Graduation1; immediate4.\n\t apply (SegmentTransADB A B (Graduation (S n) A B Hab)).\n\t  trivial.\n\t  apply GraduationSegment.\nQed.\n\nLemma GraduationBetweenAnSn : forall n : nat, forall A B : Point, forall Hab : A <> B, \n\tn >= 1 ->\n\tBetween A (Graduation n A B Hab) (Graduation (S n) A B Hab).\nProof.\n\tintros.\n\tinduction H.\n\t apply SegmentBetween.\n\t  rewrite Graduation1; apply GraduationSegmentSn.\n\t  rewrite Graduation1; immediate4.\n\t  apply GraduationDistinctnSn.\n\t step4 IHle.\n\t  apply GraduationBetweennSnSSn.\nQed.\n\nLemma GraduationSegmentB : forall n : nat, forall A B : Point, forall Hab : A <> B, \n\tSegment B (Graduation (S (S n)) A B Hab) (Graduation (S n) A B Hab).\nProof.\n\tintros.\n\tapply (SegmentTransBDC A).\n\t apply GraduationSegmentSn.\n\t apply GraduationSegment.\nQed.\n\nLemma GraduationEqDistance : forall n : nat, forall A B : Point, forall Hab : A <> B, \n\tDistance A (Graduation n A B Hab) = Distance B (Graduation (S n) A B Hab).\nProof.\n\tintros; induction n.\n\t rewrite Graduation0; rewrite Graduation1; immediate4.\n\t usingChasles2 A (Graduation n A B Hab) (Graduation (S n) A B Hab).\n\t  usingChasles2 B (Graduation (S n) A B Hab) (Graduation (S (S n)) A B Hab).\n\t   repeat rewrite EqDistanceGraduation.\n\t     immediate4.\n\t   apply GraduationSegmentB.\n\t  apply GraduationSegment.\nQed.\n\nLemma DistanceGraduation : forall n : nat, forall A B : Point, forall Hab : A <> B, \n\tDistance A (Graduation n A B Hab) = DistanceTimes n A B.\nProof.\n\tintros; induction n.\n\t rewrite Graduation0; simpl in |- *; immediate4.\n\t usingChasles2 A (Graduation n A B Hab) (Graduation (S n) A B Hab).\n\t  rewrite EqDistanceGraduation; simpl in |- *.\n\t    rewrite IHn; apply DistancePlusCommut.\n\t  apply GraduationSegment.\nQed.\n\nEnd ARCHIMEDIAN_DISTANCE.\n\n", "meta": {"author": "coq-contribs", "repo": "euclidean-geometry", "sha": "06838851a5924918d98e5a9c07ffa84021e13af7", "save_path": "github-repos/coq/coq-contribs-euclidean-geometry", "path": "github-repos/coq/coq-contribs-euclidean-geometry/euclidean-geometry-06838851a5924918d98e5a9c07ffa84021e13af7/F4_ArchimedianDistance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7012893012812395}}
{"text": "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.\nProof.\nintros f.\nintros H.\nintros b.\ndestruct b.\n- rewrite -> H. rewrite -> H. reflexivity.\n- rewrite -> H. rewrite -> H. reflexivity.\nQed.", "meta": {"author": "Asap7772", "repo": "coq_softwarefoundations", "sha": "a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d", "save_path": "github-repos/coq/Asap7772-coq_softwarefoundations", "path": "github-repos/coq/Asap7772-coq_softwarefoundations/coq_softwarefoundations-a7a58d9f82aed0966d8a2fcd2fc3be1d4b7b1f0d/chapter1/identityfnappliedtwice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7012604470317066}}
{"text": "Require Export Properties.\n\nDefinition Un X :=\n  forall x y z, M x -> M y -> M z ->\n  <|x,y|> ∈ X -> <|x,z|> ∈ X -> y = z.\n\n\n    \nDefinition Fnc X :=\n  Rel X /\\ Un X.\n\nDefinition Map f X Y :=\n  Fnc f /\\ Dom f = X /\\ Ran f ⊂ Y.\nNotation \"f : X → Y\" := (Map f X Y) (at level 10).\n\nDefinition Restriction f X  :=\n  f ∩ (X × V).\nNotation \"f | ( X )\" := (Restriction f X)(at level 10).\n\nTheorem in_restrict f X g :\n    g ∈ (f | (X)) <-> exists x y, M x /\\ M y /\\ g = <|x,y|> /\\ g ∈ f /\\ x ∈ X.\nProof.\n  unfold Restriction.\n  rewrite in_cap.\n  rewrite in_prod.\n  split => [ [gf [x [y [ x_ [y_  [g_xy [ xX _]]]]]]] | [x [y [x_ [y_ [g_xy [gf xX]]]]]]]; [|split] => //; exists x; exists y => //.\n  by rewrite in_universe.\nQed.    \n\n\nDefinition Image f X :=\n  Ran (f | (X)).\n\nTheorem in_image f X y (y_ : M y):\n    y ∈ (Image f X) <-> exists x, M x /\\ x ∈ X /\\ <|x,y|> ∈ f.\nProof.\n  unfold Image.\n  rewrite in_ran => //.\n  split => [[x [x_ H]]| [x [x_ [xX xy_f]]]].\n  + move /in_restrict : H => [x0 [y0 [x0_ [y0_ [xyxy [xy_f xX]]]]]].\n    move /(orderd_eq x y x0 y0 x_ y_ x0_ y0_) : xyxy => [xx0 yy0]; subst x0 y0.\n    by exists x.\n  + exists x; split => //; rewrite in_restrict.\n    by exists x ; exists y.\nQed.    ", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "MK", "sha": "ac16a400fa4fcb4c7568d010ec8677defd0a5b94", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-MK", "path": "github-repos/coq/gaxiiiiiiiiiiii-MK/MK-ac16a400fa4fcb4c7568d010ec8677defd0a5b94/Functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359675, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7012604469248099}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (x : natural) (y : natural) (lf1 : natural)\n  : natural := plus x (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_80_plus_succ/goal33conj245_coqofml_LqMceI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7012447684554367}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf1 : natural) (lf2 : natural) (y : natural) (x : natural)\n  : natural := mult (Succ Zero) lf1.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj214_coqofml_Mg4BWZ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7012447652162083}}
{"text": "Require Import ZArith Lia.\n\n(**  contributed by GhasSee \n\n  This version solves some computing issues \n    (computation of [sqrt' n]) \n*)\n\n(** Euclidean division specification *) \n\nDefinition div_type'' m n q r := m = q*n+r /\\ r < n. \n\nDefinition div_type  (m:nat)  :=\n  forall n, 0 < n -> {q & { r | m = q*n+r /\\ r < n }}.\n\nDefinition div_type' m n q    := { r | m = q*n+r /\\ r < n }.\n\n(* implementation by well-founded recursion *)\n\nDefinition div_F : \n  forall x, (forall y, y < x -> div_type y) -> div_type x. \nProof. \n  unfold div_type at 2. \n  refine (fun m div_rec n Hlt => \n      match le_gt_dec n m with \n      | left H_n_le_m => \n          match div_rec (m-n) _ n _ with \n          | existT _ q (exist _ r H_spec) => \n              existT (div_type' m n) (S q)\n                (exist (div_type'' m n (S q)) r _ )\n          end \n      | right H_n_gt_m => \n            existT (div_type' m n) O (exist (div_type'' m n O) m _ ) end );  \n  unfold div_type'' ; lia. \nDefined.  \n\nDefinition div :\n  forall m n, 0 < n ->\n              {q & {r | m = q*n+r /\\ r < n }} :=\n  well_founded_induction lt_wf div_type div_F.\n\nCompute  match div 100 15 _\n         with \n         | existT _ q (exist _ r _ )   => (q,r)\n         end . \n\n\n(*   square root spec *)\n\nDefinition sqrt_type (n:nat)  :=\n  {s & { r | n = s*s+r /\\ n < S s * S s }}. \n\nDefinition sqrt_type' n s := { r | n = s*s+r /\\ n < (S s)*(S s) }.\n\nDefinition sqrt_type'' n s r  := n = s*s+r /\\ n < (S s)*(S s).  \n\n\nDefinition sqrt_F : \n  forall x, (forall y, y < x -> sqrt_type y) -> sqrt_type x. \nProof. \n  destruct x. \n  - refine (fun sqrt_rec => existT _ 0 (exist _ 0 _ )); lia. \n  - unfold sqrt_type at 2. \n    refine (fun sqrt_rec => \n      let n := S x in \n      match div n 4 _ with \n      | existT _ q (exist _ r0 _ ) => \n          match sqrt_rec q _ with \n          | existT _ s' (exist _ r' H_spec) => \n              match le_gt_dec (S(4*s')) (4*r'+r0) with \n              | left HSs => \n                  let s := S(2*s') in \n                  let r := 4*r'+r0 - S(4*s') in \n                  existT(sqrt_type' n) s\n                    (exist (sqrt_type'' n s) r _ ) \n              | right Hs => \n                  let s := 2*s' in \n                  let r := 4*r'+r0 in \n                  existT(sqrt_type' n) s\n                    (exist (sqrt_type'' n s) r _ )  end end end); \n    unfold sqrt_type''; auto with zarith. \nDefined. \n\nDefinition sqrt : forall n, sqrt_type n :=\n  well_founded_induction lt_wf sqrt_type sqrt_F. \n\nCompute match sqrt 10 with | existT _ s _ => s end . \n\n\n\n(* ex. 15.11 *) \nDefinition sqrt_F' : \n  forall x, (forall y, y < x -> sqrt_type y) -> sqrt_type x. \nProof. \n  destruct x. \n  - intros. exists 0. exists 0. auto with arith.  \n  - intros sqrt_rec. set (S x) as n. fold n. \n    refine (match div n 4 _ with \n            | existT _ q (exist _ r0 _) => _ end );\n      auto with zarith. \n    + destruct (sqrt_rec q) as [s' [r' [H1' H2']]];\n        auto with zarith.  \n      * { destruct (le_gt_dec (S(4*s')) (4*r'+r0)).   \n          - exists (S(2*s')); exists (4*r'+r0-S(4*s'));\n              auto with zarith.            \n        - exists (2*s'), (4*r'+r0); auto with zarith. }\nDefined.  \n\nDefinition sqrt' : forall n:nat, sqrt_type n :=\n  well_founded_induction lt_wf sqrt_type sqrt_F'. \n\n(* hurrah !!! *)\n\nCompute match sqrt' 42 with existT _ s _ => s end. \n\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/ch15_general_recursion/SRC/sqrt_compute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7012447633444605}}
{"text": "Add LoadPath \".\" as OPAT.\nRequire Import OPAT.aula3 OPAT.aula4 OPAT.aula5.\n\n(** **** Exercise: 2 stars, each one, recommended (basic_induction)  *)\n(** Prove the following using induction. You might need previously\n    proven results. *)\n\nTheorem mult_0_r : forall n:nat,\n  n * 0 = 0.\nProof.\n  intros n. induction n as [| n' IHn'].\n  - simpl. 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. induction n as [| n' IHn'].\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. induction n as [| n' IHn'].\n  - rewrite <- plus_n_O. simpl. reflexivity.\n  - rewrite <- plus_n_Sm. simpl. rewrite <- IHn'. 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\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 as [| n' IHn'].\n  -simpl. reflexivity.\n  -simpl. rewrite -> IHn'. rewrite <- plus_n_Sm. reflexivity.\nQed.\n\n(** **** Exercise: 2 stars, optional (evenb_S)  *)\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: *)\nLemma negb_negb : forall a:bool,\n  negb (negb a) = a.\nProof.\n  intros a.\n  destruct a.\n  -simpl. reflexivity.\n  -simpl. 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  -simpl. reflexivity.\n  -rewrite -> IHn'. simpl. rewrite negb_negb. reflexivity.\nQed.\n", "meta": {"author": "bugarela", "repo": "Coq", "sha": "9f4973fec5b34ed836aa2239a009385e0549c024", "save_path": "github-repos/coq/bugarela-Coq", "path": "github-repos/coq/bugarela-Coq/Coq-9f4973fec5b34ed836aa2239a009385e0549c024/OPAT exercises/doit3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.7012356345604683}}
{"text": "(** %\\chapter{Encoding Mathematical Structures}% *)\n\nFrom mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat ssrfun.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule DepRecords.\n\n(** * Encoding partial commutative monoids *)\n\nModule PCMDef. \n\n(**\n\nWe have already seen a use of a dependent pair type, exemplified by\nthe Coq's definition of the universal quantification.\n\n*)\n\nPrint ex.\n\n(**\n[[\nInductive ex (A : Type) (P : A -> Prop) : Prop :=\n    ex_intro : forall x : A, P x -> ex P\n]]\n\n*)\n\nRecord mixin_of (T : Type) := Mixin {\n    valid_op : T -> bool;\n    join_op : T -> T -> T;\n    unit_op : T;\n    _ : commutative join_op;\n    _ : associative join_op;\n    _ : left_id unit_op join_op;\n    _ : forall x y, valid_op (join_op x y) -> valid_op x; \n    _ : valid_op unit_op \n}.\n\n(**\n[[\nmixin_of is defined\nmixin_of_rect is defined\nmixin_of_ind is defined\nmixin_of_rec is defined\nvalid_op is defined\njoin_op is defined\nunit_op is defined\n]]\n*)\n\nCheck valid_op.\n\n(**\n[[\nvalid_op\n     : forall T : Type, mixin_of T -> T -> bool\n]]\n*)\n\n\nLemma r_unit T (pcm: mixin_of T) (t: T) : (join_op pcm t (unit_op pcm)) = t.\nProof.\ncase: pcm=>_ join unit Hc _ Hlu _ _ /=.\n\n(** \n[[\n  T : Type\n  t : T\n  join : T -> T -> T\n  unit : T\n  Hc : commutative join\n  Hlu : left_id unit join\n  ============================\n   join t unit = t\n]]\n*)\n\nby rewrite Hc Hlu.\nQed.\n\n\n(** ** An alternative definition *)\n\nInductive mixin_of' (T: Type) := \n  Mixin' (valid_op: T -> bool) (join_op : T -> T -> T) (unit_op: T) of\n    commutative join_op &\n    associative join_op &\n    left_id unit_op join_op &\n    forall x y, valid_op (join_op x y) -> valid_op x &\n    valid_op unit_op.\n\n(**\n\nAlthough this definition seems more principled and is closer to what\nwe have seen in previous chapters, the record notation is more\nconvenient in this case, as it defined getters automatically as well\nas allows one to express inheritance between data structures by means\nof the coercion operator %\\texttt{:>}%\noperator%~\\cite{Garillot-al:TPHOL09}%.%\\footnote{In the next section\nwill show a different way to encode implicit inheritance, though.}%\n\n** Packaging the structure from mixins\n%\\label{sec:packaging}%\n\n*)\n\nSection Packing.\n\nStructure pack_type : Type := Pack {type : Type; _ : mixin_of type}.\n\n(** \n\nThe dependent data structure [pack_type] declares two fields: the\nfield [type] of type [Type], which described the carrier type of the\nPCM instance, and the actual PCM structure (without an explicit name\ngiven) of type [mixin_of type]. That is, in order to construct an\ninstance of [pack_type], one will have to provide _both_ arguments:\nthe carrier set and a PCM structure for it.\n\n*)\n\nLocal Coercion type : pack_type >-> Sortclass.\n\n(**\n\nNext, in the same section, we provide a number of abbreviations to\nsimplify the work with the PCM packed structure and prepare it to be\nexported by clients.\n\n*)\nVariable cT: pack_type.\n\nDefinition pcm_struct : mixin_of cT := \n    let: Pack _ c := cT return mixin_of cT in c.\n\nDefinition valid := valid_op pcm_struct.\nDefinition join := join_op pcm_struct.\nDefinition unit := unit_op pcm_struct.\n\nEnd Packing.\n\nModule Exports.\n\nNotation pcm := pack_type.\nNotation PCMMixin := Mixin.\nNotation PCM T m := (@Pack T m).\n\nNotation \"x \\+ y\" := (join x y) (at level 43, left associativity).\nNotation valid := valid.\nNotation Unit := unit.\n\n\nCoercion type : pack_type >-> Sortclass.\n\n\n(** * Properties of partial commutative monoids *)\n\nSection PCMLemmas.\nVariable U : pcm.\n\n(** \n\nFor instance, the following lemma re-establishes the commutativity of\nthe [\\+] operation:\n\n*)\n\nLemma joinC (x y : U) : x \\+ y = y \\+ x.\nProof.\nby case: U x y=> tp [v j z Cj *]; apply Cj.\nQed.\n\n\n(** \n\nNotice that in order to make the proof to go through, we had to \"push\"\nthe PCM elements [x] and [y] to be the assumption of the goal before\ncase-analysing on [U]. This is due to the fact that the structure of\n[U] affects the type of [x] and [y], therefore destructing it by means\nof [case] would change the representation of [x] and [y] as well,\ndoing some rewriting and simplifications. Therefore, when [U] is being\ndecomposed, al values, whose type depends on it (i.e., [x] and [y])\nshould be in the scope of decomposition. The naming pattern [*] helped\nus to give automatic names to all remaining assumptions, appearing\nfrom decomposition of [U]'s second component before moving it to the\ncontext before finishing the proof by applying the commutativity\n\"field\" [Cj].\n\n*)\n\nLemma joinA (x y z : U) : x \\+ (y \\+ z) = x \\+ y \\+ z.\nProof. \nby case: U x y z=>tp [v j z Cj Aj *]; apply: Aj. \nQed.\n\n(*******************************************************************)\n(**                     * Exercices 1 *                            *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [PCM Laws]\n---------------------------------------------------------------------\n\nProove the rest of the PCM laws.\n*)\n\nLemma joinAC (x y z : U) : x \\+ y \\+ z = x \\+ z \\+ y.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\nLemma joinCA (x y z : U) : x \\+ (y \\+ z) = y \\+ (x \\+ z).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\nLemma validL (x y : U) : valid (x \\+ y) -> valid x.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\nLemma validR (x y : U) : valid (x \\+ y) -> valid y.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\nLemma unitL (x : U) : (@Unit U) \\+ x = x.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\nLemma unitR (x : U) : x \\+ (@Unit U) = x.\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\nLemma valid_unit : valid (@Unit U).\nProof.\n(* fill in your proof here instead of [admit] *)\nAdmitted.\n\n\n\n(*******************************************************************)\n(**                 * End of Exercices 1 *                         *)\n(*******************************************************************)\n\nEnd PCMLemmas.\n\nEnd Exports.\n\nEnd PCMDef.\n\nExport PCMDef.Exports.\n\n(** * Implementing inheritance hierarchies\n\nWe will now go even further and show how to build hierarchies of\nmathematical structures using the same way of encoding inheritance. We\nwill use a _cancellative PCM_ as a running example.\n\n*)\n\nModule CancelPCM.\n\nRecord mixin_of (U : pcm) := Mixin {\n  _ : forall a b c: U, valid (a \\+ b) -> a \\+ b = a \\+ c -> b = c\n}.\n\nStructure pack_type : Type := Pack {pcmT : pcm; _ : mixin_of pcmT}.\n\nModule Exports.\n\nNotation cancel_pcm := pack_type.\nNotation CancelPCMMixin := Mixin.\nNotation CancelPCM T m:= (@Pack T m).\n\nCoercion pcmT : pack_type >-> pcm.\n\nLemma cancel (U: cancel_pcm) (x y z: U): \n  valid (x \\+ y) -> x \\+ y = x \\+ z -> y = z.\nProof.\nby case: U x y z=>Up [Hc] x y z; apply: Hc.\nQed.\n\nEnd Exports.\nEnd CancelPCM. \n\nExport CancelPCM.Exports.\n\nLemma cancelC (U: cancel_pcm) (x y z : U) :\n  valid (y \\+ x \\+ z) -> y \\+ x = x \\+ z -> y = z.\nProof.\nby move/validL; rewrite ![y \\+ _]joinC; apply: cancel.\nQed.\n\n\n(**\n\n* Instantiation and canonical structures\n\nNow, as we have defined a PCM structure along with its specialized\nversion, a cancellative PCM, it is time to see how to _instantiate_\nthese abstract definitions with concrete datatypes, i.e., _prove_ the\nlater ones to be instances of a PCM.\n\n** Defining arbitrary PCM instances\n\nNatural numbers form a PCM, in particular, with addition as a join\noperation and zero as a unit element. The validity predicate is\nconstant true, because the addition of two natural numbers is again a\nvalid natural number. Therefore, we can instantiate the PCM structure\nfor [nat] as follows, first by constructing the appropriate mixin.\n\n*)\n\nDefinition natPCMMixin := \n  PCMMixin addnC addnA add0n (fun x y => @id true) (erefl _).\n\nDefinition NatPCM := PCM nat natPCMMixin.\n\n(** \n\nThis definition will indeed work, although, being somewhat\nunsatisfactory. For example, assume we want to prove the following\nlemma for natural numbers treated as elements of a PCM, which should\ntrivially follow from the PCM properties of [nat] with addition and\nzero:\n\n[[\nLemma add_perm (a b c : nat) : a \\+ (b \\+ c) = a \\+ (c \\+ b).\n]]\n\n\n[[\nThe term \"a\" has type \"nat\" while it is expected to have type \"PCMDef.type ?135\".\n]]\n\n*)\n\nCanonical natPCM := PCM nat natPCMMixin.\n\nPrint Canonical Projections.\n\n(**\n[[\n...\nnat <- PCMDef.type ( natPCM )\npred_of_mem <- topred ( memPredType )\npred_of_simpl <- topred ( simplPredType )\nsig <- sub_sort ( sig_subType )\nnumber <- sub_sort ( number_subType )\n...\n]]\n*)\n\n\nLemma cancelNat : forall a b c: nat, true -> a + b = a + c -> b = c.\nProof.\nmove=> a b c; elim: a=>// n /(_ is_true_true) Hn _ H.\nby apply: Hn; rewrite !addSn in H; move/eq_add_S: H.\nQed.\n\nDefinition cancelNatPCMMixin := CancelPCMMixin cancelNat.\n\nCanonical cancelNatPCM := CancelPCM natPCM cancelNatPCMMixin.\n\n(** \n\nLet us now see the canonical instances in action, so we can prove a\nnumber of lemmas about natural numbers employing the general PCM\nmachinery.\n\n*)\n\nSection PCMExamples.\n\nVariables a b c: nat.\n\nGoal a \\+ (b \\+ c) =  c \\+ (b \\+ a).\nby rewrite joinA [c \\+ _]joinC [b \\+ _]joinC.\nQed.\n\nGoal c \\+ a = a \\+ b -> c = b.\nby rewrite [c \\+ _]joinC; apply: cancel.\nQed.\n\n(** \n\nIt might look a bit cumbersome, though, to write the PCM join\noperation [\\+] instead of the boolean addition when specifying the\nfacts about natural numbers (even though they are treated as elements\nof the appropriate PCM). Unfortunately, it is not trivial to encode\nthe mechanism, which will perform such conversion implicitly. Even\nthough Coq is capable of figuring out what PCM is necessary for a\nparticular type (if the necessary canonical instance is defined),\ne.g., when seeing [(a b : nat)] being used, it infers the [natPCM],\nalas, it's not powerful enough to infer that the by writing the\naddition function [+] on natural numbers, we mean the PCM's\njoin. However, if necessary, in most of the cases the conversion like\nthis can be done by manual rewriting using the following trivial\n\"conversion\" lemma.\n\n*)\n\nLemma addn_join (x y: nat): x + y = x \\+ y. \nProof. by []. Qed.\n\nEnd PCMExamples.\n\n(** ** Types with decidable equalities\n\nThe module [eqtype] of SSReflect's standard library provides a\ndefinition of the equality mixin and packaged class of the familiar\nshape, which, after some simplifications, boil to the following ones:\n\n[[\nModule Equality.\n\nDefinition axiom T (e : rel T) := forall x y, reflect (x = y) (e x y).\n\nStructure mixin_of T := Mixin {op : rel T; _ : axiom op}.\nStructure type := Pack {sort; _ : mixin_of sort}.\n\n...\n\nNotation EqMixin := Mixin.\nNotation EqType T m := Pack T m.\n\nEnd Equality.\n]]\n\nDEMO: check the corresponding files ssreflect-1.4/theories/eqtype.v\nand ssreflect-1.4/theories/ssrnat.v\n\n*)\n\n(*******************************************************************)\n(**                     * Exercices 2 *                            *)\n(*******************************************************************)\n\n(** \n---------------------------------------------------------------------\nExercise [Partially-ordered sets]\n---------------------------------------------------------------------\n\nA partially ordered set order is a pair (T, <==), where T is a carrier\nset and <== is a relation on T, such that\n\n- forall x in T, x <== x (reflexivity);\n\n- forall x, y in T, x <== y /\\ y <== x \\implies x = y (antisymmetry);\n\n- forall x, y, z in T, x <== y /\\ y <== z \\implies x <== z (transitivity).\n\nImplement a data structure for partially-ordered sets using mixins and\npacked classes. Prove the following laws:\n\nLemma poset_refl (x : T) : x <== x.\nLemma poset_asym (x y : T) : x <== y -> y <== x -> x = y.\nLemma poset_trans (y x z : T) : x <== y -> y <== z -> x <== z.\n*)\n\n(**\n---------------------------------------------------------------------\nExercise [Canonical instances of partially ordered sets]\n---------------------------------------------------------------------\n\nProvide canonical instances of partially ordered sets for the\nfollowing types:\n\n- [nat] and [<=];\n\n- [prod], whose components are posets;\n\n- functions [A -> B], whose codomain (range) [B] is a partially\n  ordered set.\n\nIn order to provide a canonical instance for functions, you will need\nto assume and make use of the following axiom of functional\nextensionality:\n\n*)\n\nAxiom fext : forall A (B : A -> Type) (f1 f2 : forall x, B x), \n               (forall x, f1 x = f2 x) -> f1 = f2.\n\n\n(*******************************************************************)\n(**                 * End of Exercices 2 *                         *)\n(*******************************************************************)\n\nEnd DepRecords.\n", "meta": {"author": "rodrigogribeiro", "repo": "program-proofs-coq", "sha": "d69fc3382392a4d569b8a77409fc96fd1fa176a7", "save_path": "github-repos/coq/rodrigogribeiro-program-proofs-coq", "path": "github-repos/coq/rodrigogribeiro-program-proofs-coq/program-proofs-coq-d69fc3382392a4d569b8a77409fc96fd1fa176a7/lectures/DepRecords.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.84594244507642, "lm_q1q2_score": 0.7012345294799683}}
{"text": "Require Export stlc.Maps.\n\nInductive ty : Type := \n  | TVar  : string -> ty \n  | TArrow : ty -> ty -> ty.\n\nInductive tm : Type :=\n  | tvar : string -> tm\n  | tapp : tm -> tm -> tm\n  | tabs : string -> ty -> tm -> tm.\n\nDefinition context := partial_map ty.\n\nDefinition extend {A:Type} (Gamma : partial_map A) (x:string) (T : A) :=\n  fun x' => if beq_string x x' then Some T else Gamma x'.\n\nInductive has_type : context -> tm -> ty -> Prop :=\n  | T_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      has_type Gamma (tvar x) T\n  | T_Abs : forall Gamma x T11 T12 t12,\n      has_type (extend Gamma x T11) t12 T12 -> \n      has_type Gamma (tabs x T11 t12) (TArrow T11 T12)\n  | T_App : forall T11 T12 Gamma t1 t2,\n      has_type Gamma t1 (TArrow T11 T12) -> \n      has_type Gamma t2 T11 -> \n      has_type Gamma (tapp t1 t2) T12.\n\nFixpoint beq_ty (T1 T2:ty) : bool :=\n  match T1,T2 with\n  | TVar a, TVar b => beq_string a b\n  | TArrow T11 T12, TArrow T21 T22 =>\n      andb (beq_ty T11 T21) (beq_ty T12 T22)\n  | _,_ => \n      false\n  end.\n\nLemma beq_ty_refl : forall T1,\n  beq_ty T1 T1 = true.\nProof.\n  intros T1. induction T1; simpl.\n    apply beq_string_true_iff. reflexivity.\n    rewrite IHT1_1. rewrite IHT1_2. reflexivity.  Qed.\n\nLemma beq_ty__eq : forall T1 T2,\n  beq_ty T1 T2 = true -> T1 = T2.\nProof.\n  intros T1. induction T1; intros T2 Hbeq; destruct T2; inversion Hbeq.\n  - apply beq_string_true_iff in H0. rewrite H0. reflexivity.\n  - apply andb_prop in H0. inversion H0 as [Hbeq1 Hbeq2].\n    apply IHT1_1 in Hbeq1. apply IHT1_2 in Hbeq2. subst... reflexivity. Qed.\n\nFixpoint type_check (Gamma:context) (t:tm) : option ty :=\n  match t with\n  | tvar x => Gamma x\n  | tabs x T11 t12 => match type_check (extend Gamma x T11) t12 with\n                          | Some T12 => Some (TArrow T11 T12)\n                          | _ => None\n                        end\n  | tapp t1 t2 => match type_check Gamma t1, type_check Gamma t2 with\n                      | Some (TArrow T11 T12),Some T2 =>\n                        if beq_ty T11 T2 then Some T12 else None\n                      | _,_ => None\n                    end\n  end.\n\nLtac solve_by_inverts n :=\n  match goal with | H : ?T |- _ =>\n  match type of T with Prop =>\n    solve [\n      inversion H;\n      match n with S (S (?n')) => subst; solve_by_inverts (S n') end ]\n  end end.\n\nLtac solve_by_invert :=\n  solve_by_inverts 1.\n\nFixpoint subst (x:string) (s:tm) (t:tm) : tm :=\n  match t with\n  | tvar x' => \n      if beq_string x x' then s else t\n  | tabs x' T t1 => \n      tabs x' T (if beq_string x x' then t1 else (subst x s t1)) \n  | tapp t1 t2 => \n      tapp (subst x s t1) (subst x s t2)\n  end.\n\nTheorem type_checking_sound : forall Gamma t T,\n  type_check Gamma t = Some T -> has_type Gamma t T.\nProof.\n  intros Gamma t. generalize dependent Gamma.\n  induction t; intros Gamma T Htc; inversion Htc.\n  - apply T_Var. apply H0.\n  - remember (type_check Gamma t1) as TO1.\n    remember (type_check Gamma t2) as TO2.\n    destruct TO1 as [T1|]; try solve_by_invert;\n    destruct T1 as [|T11 T12]; try solve_by_invert.\n    destruct TO2 as [T2|]; try solve_by_invert.\n    remember (beq_ty T11 T2) as b.\n    destruct b; try solve_by_invert.\n    symmetry in Heqb. apply beq_ty__eq in Heqb.\n    inversion H0; subst... \n    apply T_App with (T11 := T2) (T12 := T).\n    symmetry in HeqTO1.\n    apply IHt1 in HeqTO1. apply HeqTO1.\n    symmetry in HeqTO2.\n    apply IHt2 in HeqTO2. apply HeqTO2.\n  - remember (extend Gamma s t) as G'.\n    remember (type_check G' t0) as TO2.\n    destruct TO2; try solve_by_invert.\n    inversion H0. apply T_Abs. rewrite <- HeqG'.\n    apply IHt. rewrite HeqTO2. reflexivity. Qed.\n\n\nLemma typecheck_complete : forall E t A,\n  has_type E t A ->\n  type_check E t = Some A.\nProof.\nintros E t A H.\ninduction H.\n- apply H.\n- simpl.\n  rewrite IHtyped1. rewrite IHtyped2.\n  rewrite beq_ty_refl.\n  reflexivity.\n- simpl.\n  rewrite IHtyped. reflexivity.\nQed.\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "TBruyn", "repo": "Software-Verification", "sha": "b2772007b9a02ef300257f0166662fdf175c6152", "save_path": "github-repos/coq/TBruyn-Software-Verification", "path": "github-repos/coq/TBruyn-Software-Verification/Software-Verification-b2772007b9a02ef300257f0166662fdf175c6152/STLC2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7012345276925144}}
{"text": "Require Arith_base.\n\n(* fin n is a convenient way to represent \\1 .. n\\\nfin n can be seen as a n-uplet of unit. F1 is the first element of the n-uplet. \nIf f is the k-th element of the (n-1)-uplet, FS f is the (k+1)-th element of the n-uplet.\nAuthor: Pierre Boutillier Institution: PPS, INRIA 12/2010-01/2012-07/2012 *)\n\n(* Vom Prinzip her die gleiche Definition mit t = Finite_Set *)\nInductive t : nat -> Set :=\n|F1 : forall {n}, t (S n)\n|FS : forall {n}, t n -> t (S n).\n\nPrint False_rect.\nPrint ID.\n\nSection SCHEMES.\n(**)\nDefinition case0 P (p: t 0): P p :=\n  match p with \n  | F1    => fun devil => False_rect (@ID) devil\n  | FS _ => fun devil => False_rect (@ID) devil end.\nPrint case0.\n\n(**)\nDefinition caseS' {n : nat} (p : t (S n)) :\nforall (P : t (S n) -> Type) (P1 : P F1) (PS : forall (p : t n), P (FS p)), P p :=\n  match p with\n  | @F1 k => fun P P1 PS => P1\n  | FS pp  => fun P P1 PS => PS pp\n  end.\n\n(**)\nDefinition caseS (P: forall {n}, t (S n) -> Type)\n  (P1: forall n, @P n F1) (PS : forall {n} (p: t n), P (FS p))\n  {n} (p: t (S n)) : P p := caseS' p P (P1 n) PS.\n\n(**)\nDefinition rectS (P: forall {n}, t (S n) -> Type)\n  (P1: forall n, @P n F1) (PS : forall {n} (p: t (S n)), P p -> P (FS p)):\n  forall {n} (p: t (S n)), P p :=\nfix rectS_fix {n} (p: t (S n)): P p:=\n  match p with\n  | @F1 k => P1 k\n  | @FS 0 pp => case0 (fun f => P (FS f)) pp\n  | @FS (S k) pp => PS pp (rectS_fix pp)\n  end.\n\n(**)\nDefinition rect2 (P : forall {n} (a b : t n), Type)\n  (H0 : forall n, @P (S n) F1 F1)\n  (H1 : forall {n} (f : t n), P F1 (FS f))\n  (H2 : forall {n} (f : t n), P (FS f) F1)\n  (HS : forall {n} (f g : t n), P f g -> P (FS f) (FS g)) :\n    forall {n} (a b : t n), P a b :=\n  fix rect2_fix {n} (a : t n) {struct a} : forall (b : t n), P a b :=\n    match a with\n    | @F1 m => fun (b : t (S m)) => caseS' b (P F1) (H0 _) H1\n    | @FS m a' => fun (b : t (S m)) =>\n      caseS' b (fun b => P (@FS m a') b) (H2 a') (fun b' => HS _ _ (rect2_fix a' b'))\n    end.\n\nEnd SCHEMES.\n\n(**)\nDefinition FS_inj {n} (x y: t n) (eq: FS x = FS y): x = y :=\nmatch eq in _ = a return\n  match a as a' in t m return \n    match m with \n      |0 => Prop \n      |S n' => t n' -> Prop \n    end\n  with \n     F1 => fun _ => True \n    |FS y => fun x' => x' = y \n  end \nx with\n  eq_refl => eq_refl\nend.\n\n(* to_nat f = p iff f is the p{^ th} element of fin m. *)\nFixpoint to_nat {m} (n : t m) : {i | i < m} :=\n  match n with\n    |@F1 j => exist _ 0 (Lt.lt_0_Sn j)\n    |FS p => \n      match to_nat p with \n       |exist _ i P => exist _ (S i) (Lt.lt_n_S _ _ P) \n     end\n  end.\n\n(* of_nat p n answers the p{^ th} element of fin n if p < n or a proof of p >= n else *)\nFixpoint of_nat (p n : nat) : (t n) + { exists m, p = n + m } :=\n  match n with\n   |0 => inright _ (ex_intro _ p eq_refl)\n   |S n' => \n      match p with\n        |0 => inleft _ (F1)\n        |S p' => \n          match of_nat p' n' with\n            |inleft f => inleft _ (FS f)\n            |inright arg => inright _ (match arg with |ex_intro _ m e =>\n          ex_intro (fun x => S p' = S n' + x) m (f_equal S e) end)\n          end\n      end\n  end.\n\n(* of_nat_lt p n H answers the p{^ th} element of fin n it behaves much better than of_nat p n on open term *)\nFixpoint of_nat_lt {p n : nat} : p < n -> t n :=\n  match n with\n    |0 => fun H : p < 0 => False_rect _ (Lt.lt_n_O p H)\n    |S n' => match p with\n      |0 => fun _ => @F1 n'\n      |S p' => fun H => FS (of_nat_lt (Lt.lt_S_n _ _ H))\n    end\n  end.\n\n(**)\nLemma of_nat_ext {p}{n} (h h' : p < n) : of_nat_lt h = of_nat_lt h'.\n\n(**)\nLemma of_nat_to_nat_inv {m} (p : t m) : of_nat_lt (proj2_sig (to_nat p)) = p.\n\n(**)\nLemma to_nat_of_nat {p}{n} (h : p < n) : to_nat (of_nat_lt h) = exist _ p h.\n\n(**)\nLemma to_nat_inj {n} (p q : t n) :\n proj1_sig (to_nat p) = proj1_sig (to_nat q) -> p = q.\n\n(* weak p f answers a function witch is the identity for the p{^ th} first element of \nfin (p + m) and FS (FS .. (FS (f k))) for FS (FS .. (FS k)) with p FSs *)\nFixpoint weak {m}{n} p (f : t m -> t n) :\n  t (p + m) -> t (p + n) :=\nmatch p as p' return t (p' + m) -> t (p' + n) with\n  |0 => f\n  |S p' => fun x => match x with\n     |@F1 n' => fun eq : n' = p' + m => F1\n     |@FS n' y => fun eq : n' = p' + m => FS (weak p' f (eq_rect _ t y _ eq))\n  end (eq_refl _)\nend.\n\n(* The p{^ th} element of fin m viewed as the p{^ th} element of fin (m + n) *)\nFixpoint L {m} n (p : t m) : t (m + n) :=\n  match p with |F1 => F1 |FS p' => FS (L n p') end.\n\n(**)\nLemma L_sanity {m} n (p : t m) : proj1_sig (to_nat (L n p)) = proj1_sig (to_nat p).\n\n(* The p{^ th} element of fin m viewed as the p{^ th} element of fin (n + m) Really really ineficient !!! *)\nDefinition L_R {m} n (p : t m) : t (n + m).\n\n(* The p{^ th} element of fin m viewed as the (n + p){^ th} element of fin (n + m) *)\nFixpoint R {m} n (p : t m) : t (n + m) :=\n  match n with |0 => p |S n' => FS (R n' p) end.\n\n(**)\nLemma R_sanity {m} n (p : t m) : proj1_sig (to_nat (R n p)) = n + proj1_sig (to_nat p).\n\n(**)\nFixpoint depair {m n} (o : t m) (p : t n) : t (m * n) :=\nmatch o with\n  |@F1 m' => L (m' * n) p\n  |FS o' => R n (depair o' p)\nend.\n\n(**)\nLemma depair_sanity {m n} (o : t m) (p : t n) :\n  proj1_sig (to_nat (depair o p)) = n * (proj1_sig (to_nat o)) + (proj1_sig (to_nat p)).\n\n(**)\nFixpoint eqb {m n} (p : t m) (q : t n) :=\nmatch p, q with\n| @F1 m', @F1 n' => EqNat.beq_nat m' n'\n| FS _, F1 => false\n| F1, FS _ => false\n| FS p', FS q' => eqb p' q'\nend.\n\n(**)\nLemma eqb_nat_eq : forall m n (p : t m) (q : t n), eqb p q = true -> m = n.\n\n(**)\nLemma eqb_eq : forall n (p q : t n), eqb p q = true <-> p = q.\n\n(**)\nLemma eq_dec {n} (x y : t n): {x = y} + {x <> y}.\n\n(**)\nDefinition cast: forall {m} (v: t m) {n}, m = n -> t n.", "meta": {"author": "margrit", "repo": "Code", "sha": "b3e89580b33732c23cdf4df8171d6c76ce9186e7", "save_path": "github-repos/coq/margrit-Code", "path": "github-repos/coq/margrit-Code/Code-b3e89580b33732c23cdf4df8171d6c76ce9186e7/Code/alt/Vectors_Fin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7012345276925143}}
{"text": "Require Import Classical.\n\nClass Hilbert := {\n  Line : Type;\n  Point : Type;\n  Inc : Point -> Line -> Prop;\n  Par l m := forall P:Point, ~(Inc P l /\\ Inc P m);\n  Algn A B C := exists l:Line, Inc A l /\\ Inc B l /\\ Inc C l;\n  nAlgn A B C := forall l:Line, ~(Inc A l /\\ Inc B l /\\ Inc C l);\n\n  I1: forall P Q:Point, P<>Q -> (exists ! l:Line, Inc P l /\\ Inc Q l);\n  I2: forall l:Line, (exists P Q:Point, Inc P l /\\ Inc Q l /\\ P<>Q);\n  I3: exists A B C:Point, (A<>B/\\B<>C/\\C<>A) /\\ nAlgn A B C;\n}.\n\nContext `{Hilbert}.\n\nProposition prop3_1: (forall l m:Line, \n  l<>m -> ~(Par l m) -> exists ! P:Point, Inc P l /\\ Inc P m).\nProof.\n  intros l m l_ne_m nPar.\n  apply not_all_ex_not in nPar.\n  destruct nPar as [P].\n  apply NNPP in H0.\n  refine (ex_intro _ P _).\n  split.\n    assumption.\n\n    intros Q H1.\n    case (classic (P = Q)).\n      trivial.\n\n      intros P_ne_Q.\n      pose (I1 P Q) as only.\n      apply only in P_ne_Q.\n      unfold unique in P_ne_Q.\n      destruct P_ne_Q as [s].\n      destruct H2 as [H2 only_s].\n\n      specialize (only_s l) as only_sl.\n      pose (conj (proj1 H0) (proj1 H1)) as bothl.\n      apply only_sl in bothl.\n\n      specialize (only_s m) as only_sm.\n      pose (conj (proj2 H0) (proj2 H1)) as bothm.\n      apply only_sm in bothm.\n      rewrite bothl in bothm.\n      apply l_ne_m in bothm.\n      case bothm.\nQed.\n\nProposition prop3_2 : (exists l m n: Line, (l<>m/\\m<>n/\\n<>l) /\\\n  forall P:Point, ~(Inc P l /\\ Inc P m /\\ Inc P n)).\nProof.\n  destruct I3 as [A [B [C [[AneB [BneC CneA]] nAlgnABC]]]].\n\n  destruct ((I1 A B) AneB) as [AB [incAB unAB]].\n  destruct ((I1 B C) BneC) as [BC [incBC unBC]].\n  destruct ((I1 C A) CneA) as [CA [incCA unCA]].\n\n  exists AB, BC, CA.\n  assert(AB <> BC) as AB_neq_BC.\n    case (classic (AB = BC)).\n    intros AB_e_BC.\n    rewrite AB_e_BC in incAB.\n    pose (conj incBC (proj2 incAB)) as incABC.\n    specialize (nAlgnABC BC).\n    tauto.\n    trivial.\n\n  assert(BC <> CA) as BC_neq_CA.\n    case (classic (BC = CA)).\n    intros BC_e_CA.\n    rewrite BC_e_CA in incBC.\n    pose (conj incCA (proj2 incBC)) as incABC.\n    specialize (nAlgnABC CA).\n    tauto.\n    trivial.\n\n  assert(CA <> AB) as CA_neq_AB.\n    case (classic (CA = AB)).\n    intros CA_e_AB.\n    rewrite CA_e_AB in incCA.\n    pose (conj incAB (proj2 incCA)) as incABC.\n    specialize (nAlgnABC AB).\n    tauto.\n    trivial.\n\n  split.\n  tauto.\n\n  intros P.\n  case (classic (Inc P AB /\\ Inc P BC /\\ Inc P CA)).\n  intros absurd.\n  case (classic (P = A)).\n    intros P_eq_A.\n    case (classic (P = B)).\n      intros P_eq_B.\n      rewrite P_eq_A in P_eq_B.\n      tauto.\n\n      intros P_neq_B.\n      destruct ((I1 P B) P_neq_B) as [PB [ incPB unPB]].\n\n      pose (conj (proj1 absurd) (proj2 incAB)) as BnP_inc_AB.\n      pose ((unPB AB) BnP_inc_AB) as PB_eq_AB.\n\n      pose (conj (proj1 (proj2 absurd)) (proj1 incBC)) as BnP_inc_BC.\n      pose ((unPB BC) BnP_inc_BC) as PB_eq_BC.\n\n      rewrite PB_eq_AB in PB_eq_BC.\n      tauto.\n\n    intros P_neq_A.\n    destruct ((I1 P A) P_neq_A) as [PA [ incPA unPA]].\n\n    pose (conj (proj1 absurd) (proj1 incAB)) as AnP_inc_AB.\n    pose ((unPA AB) AnP_inc_AB) as PA_eq_AB.\n\n    pose (conj (proj2 (proj2 absurd)) (proj2 incCA)) as AnP_inc_CA.\n    pose ((unPA CA) AnP_inc_CA) as PA_eq_CA.\n\n    rewrite PA_eq_CA in PA_eq_AB.\n    tauto.\n\n  trivial.\nQed.\n\nProposition prop3_3 : (forall r:Line, exists P:Point, ~(Inc P r)).\nProof.\n  intros r.\n  destruct I3.\n  destruct H0.\n  destruct H0.\n  apply proj2 in H0.\n  specialize (H0 r).\n  apply not_and_or in H0.\n  case H0.\n    intros nInc_x_r.\n    refine (ex_intro _ x _).\n    assumption.\n\n    intros H1.\n    apply not_and_or in H1.\n    case H1.\n      intros nInc_x0_r.\n      exists x0.\n      assumption.\n\n      intros nInc_x1_r.\n      exists x1.\n      assumption.\nQed.\n\nProposition prop3_4: (forall P:Point, exists r:Line, ~(Inc P r)).\nProof.\n  intros P.\n  destruct prop3_2 as [l [m [n [[l_ne_m [m_ne_n n_ne_l]] nAlgn_lmn]]]].\n  case (classic(forall r : Line, Inc P r)).\n\n  intros all_inc.\n  specialize (nAlgn_lmn P).\n  pose (all_inc l) as l_inc.\n  pose (all_inc m) as m_inc.\n  pose (all_inc n) as n_inc.\n  tauto.\n\n  intros not_all_inc.\n  apply not_all_ex_not in not_all_inc.\n  trivial.\nQed.", "meta": {"author": "GiacomoMaletto", "repo": "Hilbert", "sha": "f825cc26974d8080761bce8511b99e447d8585bf", "save_path": "github-repos/coq/GiacomoMaletto-Hilbert", "path": "github-repos/coq/GiacomoMaletto-Hilbert/Hilbert-f825cc26974d8080761bce8511b99e447d8585bf/hilbert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7011368221795202}}
{"text": "Class ordered (T : Type) :=\n  { eq  : T -> T -> bool\n  ; lt  : T -> T -> bool\n  ; leq : T -> T -> bool\n\n  ; eq_sym\n      : forall (t1 t2 : T)\n      , eq t1 t2 = eq t2 t1\n  ; lt_asym\n      : forall (t1 t2 : T) (b : bool)\n      , lt t1 t2 = true -> lt t2 t1 = false\n  ; eq_implies_leq\n      : forall (t1 t2 : T)\n      , eq t1 t2 = true -> leq t1 t2 = true\n  ; lt_implies_leq\n      : forall (t1 t2 : T)\n      , lt t1 t2 = true -> leq t1 t2 = true\n  ; lt_not_eq\n      : forall (t1 t2 : T)\n      , lt t1 t2 = true -> eq t1 t2 = false\n  }.\n\nClass heap (H : Type) (E : Type) `{o : ordered E} : Type :=\n  { empty     : H\n  ; isEmpty   : H -> bool\n  ; insert    : E -> H -> H\n  ; merge     : H -> H -> H\n  ; findMin   : H -> option E\n  ; deleteMin : H -> option H\n\n  ; empty_is_empty\n      : isEmpty empty = true\n  ; non_empty_is_not_empty\n      : forall (h : H) (e : E)\n      , isEmpty (insert e h) = true\n  ; merge_empty_left\n      : forall (h : H)\n      , merge empty h = h\n  ; merge_empty_right\n      : forall (h : H)\n      , merge h empty = h\n  ; empty_findMin\n      : findMin empty = None\n  ; empty_deleteMin\n      : deleteMin empty = None\n  ; insert_min\n      : forall (h : H) (e1 e2 : E)\n      , findMin h = Some e1 -> lt e2 e1 = true -> findMin (insert e2 h) = Some e2\n  ; insert_non_min\n      : forall (h : H) (e1 e2 : E)\n      , findMin h = Some e1 -> lt e2 e1 = false -> findMin (insert e2 h) = Some e1\n  ; merge_min_left\n      : forall (h1 h2 : H) (e1 e2 : E)\n      , findMin h1 = Some e1 -> findMin h2 = Some e2 -> lt e1 e2 = true -> findMin (merge h1 h2) = Some e1\n  ; merge_min_right\n      : forall (h1 h2 : H) (e1 e2 : E)\n      , findMin h1 = Some e1 -> findMin h2 = Some e2 -> lt e2 e1 = true -> findMin (merge h1 h2) = Some e2\n  ; delete_min\n      : forall (h1 h2 : H) (e1 e2 : E)\n      , findMin h1 = Some e1 -> lt e2 e1 = true -> deleteMin (insert e2 h1) = Some h2 -> findMin h2 = Some e1\n  }.\n\nRequire Import Arith.\n\nInductive leftish_heap (E : Type) : Type :=\n  | Empty : leftish_heap E\n  | Node  : nat -> E -> leftish_heap E -> leftish_heap E -> leftish_heap E\n  .\n\nDefinition lh_empty {E : Type} : leftish_heap E :=\n  Empty E.\n\nDefinition lh_isEmpty {E : Type} (h : leftish_heap E) : bool :=\n  match h with\n    | Empty _         => true\n    | Node  _ _ _ _ _ => false\n  end.\n\nDefinition lh_findMin {E : Type} `{o : ordered E} (h : leftish_heap E) : option E :=\n  match h with\n    | Empty _ => None\n    | Node _ _ x _ _ => Some x\n  end.\n\nDefinition rank {E : Type} (e : leftish_heap E) : nat :=\n  match e with\n    | Empty _         => 0\n    | Node  _ r _ _ _ => r\n  end.\n\n(* Cannot guess decreasing argument of fix. *)\nDefinition makeT {E : Type} (x : E) (a : leftish_heap E) (b : leftish_heap E) : leftish_heap E :=\n  if (rank b) <? (rank a)\n    then Node E (rank b + 1) x a b\n    else Node E (rank a + 1) x b a.\n\n(* FAIL *)\nFail Fixpoint lh_merge1 {E : Type} {o : ordered E} (e1 : leftish_heap E) (e2 : leftish_heap E) : leftish_heap E :=\n  match e1, e2 with\n    | h, Empty _ => h\n    | Empty _, h => h\n    | Node _ _ x a1 b1 as h1, Node _ _ y a2 b2 as h2 =>\n        if leq x y\n          then makeT x a1 (lh_merge1 b1 h2)\n          else makeT y a2 (lh_merge1 h1 b2)\n  end.\n\n(* the name 'merge' seems to be in scope already *)\nFixpoint lh_merge (E:Type) (o:ordered E) (e1 e2:leftish_heap E) : leftish_heap E :=\nmatch e1 with\n| Empty _ => e2\n| Node _ _ x a1 b1 as h1  =>\n   (fix g (e2' : leftish_heap E) : leftish_heap E :=\n        match e2' with\n        | Empty _   => e1\n        | Node _ _ y a2 b2 as h2 =>\n           if leq x y\n              then makeT x a1 (lh_merge _ _ b1 h2)\n              else makeT y a2 (g b2) \n        end) e2\nend.\n\n(* declares arguments as implicit going forward *)\nArguments lh_merge {E} {o}.\nArguments Empty  {E}.\nArguments Node {E}.\n\n(* These 4 lemmas to check that lh_merge as the intended semantics *)\nLemma checkMerge1 : forall (E:Type) (o:ordered E) (e:leftish_heap E),\n  lh_merge Empty e = e.\nProof.\n  intros E o e.\n  reflexivity.\nQed.\n\nLemma checkMerge2 : forall (E:Type) (o:ordered E) (e:leftish_heap E),\n  lh_merge e Empty = e.\nProof.\n  intros E o. destruct e as [|x a b]; reflexivity.\nQed.\n\nLemma checkMerge3\n  : forall (E:Type) (o:ordered E) (e1 e2:leftish_heap E)\n  , forall (n m:nat) (x y:E) (a1 b1 a2 b2:leftish_heap E) ,\n  e1 = Node n x a1 b1 ->\n  e2 = Node m y a2 b2 ->\n  leq x y = true ->\n  lh_merge e1 e2 = makeT x a1 (lh_merge b1 e2).\nProof.\n  intros E o e1 e2 n m x y a1 b1 a2 b2 H1 H2 H.\n  rewrite H1, H2. simpl. rewrite H. reflexivity.\nQed.\n\nLemma checkMerge4\n  : forall (E:Type) (o:ordered E) (e1 e2:leftish_heap E), \n    forall (n m:nat) (x y:E) (a1 b1 a2 b2:leftish_heap E),\n  e1 = Node n x a1 b1 ->\n  e2 = Node m y a2 b2 ->\n  leq x y = false ->\n  lh_merge e1 e2 = makeT y a2 (lh_merge e1 b2).\nProof.\n  intros E o e1 e2 n m x y a1 b1 a2 b2 H1 H2 H.\n  rewrite H1, H2. simpl. rewrite H. reflexivity.\nQed.\n\nDefinition lh_insert {E : Type} `{o : ordered E} (x : E) (h : leftish_heap E) : leftish_heap E :=\n  lh_merge (Node 1 x Empty Empty) h.\n\nDefinition lh_deleteMin {E : Type} `{o : ordered E} (h : leftish_heap E) : option (leftish_heap E) :=\n  match h with\n    | Empty         => None\n    | Node  _ x a b => Some (lh_merge a b)\n  end.\n\nTheorem lh_empty_is_empty\n  : forall (E : Type)\n  , @lh_isEmpty E lh_empty = true.\nProof.\n    intros E. reflexivity. \nQed.\n\nLemma makeT_is_not_empty \n  : forall (E : Type) (x : E) (a b : leftish_heap E)\n  , lh_isEmpty (makeT x a b) = false.\nProof.\n    intros E x a b. unfold makeT. destruct (rank b <? rank a); reflexivity.\nQed.\n\nTheorem lh_non_empty_is_not_empty\n  : forall (E : Type) (o : ordered E) (h : leftish_heap E) (e : E)\n  , lh_isEmpty (lh_insert e h) = false.\nProof.\n    intros E o h e. destruct h as [|n x h1 h2].\n    - reflexivity.\n    - unfold lh_insert, lh_merge. destruct (leq e x).\n        + reflexivity.\n        + apply makeT_is_not_empty.\nQed.\n\n\nTheorem lh_merge_empty_left\n  : forall (E : Type) (o : ordered E) (h : leftish_heap E)\n  , lh_merge lh_empty h = h.\nProof.\n    intros E o h. reflexivity.\nQed.\n\n\n\nTheorem lh_merge_empty_right\n  : forall (E : Type) (o : ordered E) (h : leftish_heap E)\n  , lh_merge h lh_empty = h.\nProof.\n    intros E o h. destruct h; reflexivity.\nQed.\n\n\n\nTheorem lh_empty_findMin\n  : forall (E : Type) (o : ordered E)\n  , lh_findMin lh_empty = None.\nProof.\n    intros E o. reflexivity.\nQed.\n\n\n\nTheorem lh_empty_deleteMin\n  : forall (E : Type) (o : ordered E)\n  , lh_deleteMin lh_empty = None.\nProof.\n    intros E o. reflexivity.\nQed.\n\n\nTheorem lh_insert_min\n  : forall (E : Type) (o : ordered E) (h : leftish_heap E) (e1 e2 : E)\n  , lh_findMin h = Some e1 -> lt e2 e1 = true -> lh_findMin (lh_insert e2 h) = Some e2.\nProof.\n    intros E o h e1 e2 H1 H2. unfold lh_insert, lh_findMin. destruct h.\n    - reflexivity.\n    - simpl. unfold lh_findMin in H1. inversion H1. subst.\n      assert (leq e2 e1 = true) as H3. { apply lt_implies_leq. assumption. } \n      rewrite H3. reflexivity.\nQed.\n\n\nTheorem lh_insert_non_min\n  : forall (E : Type) (o : ordered E) (h : leftish_heap E) (e1 e2 : E)\n  , lh_findMin h = Some e1 -> lt e2 e1 = false -> lh_findMin (lh_insert e2 h) = Some e1.\nProof.\n    intros E o h e1 e2 H1 H2. unfold lh_insert, lh_findMin. destruct h.\n    - inversion H1.\n    - simpl. unfold lh_findMin in H1. inversion H1. subst. destruct (leq e2 e1) eqn:H3.\n        + simpl. \n          assert (e2 = e1).\n\nShow.\n(*\n\nTheorem lh_merge_min_left\n  : forall (E : Type) (o : ordered E) (h1 h2 : leftish_heap E) (e1 e2 : E)\n  , lh_findMin h1 = Some e1 -> lh_findMin h2 = Some e2 -> lt e1 e2 = true -> lh_findMin (lh_merge h1 h2) = Some e1.\nProof.\nAdmitted.\n\nTheorem lh_merge_min_right\n  : forall (E : Type) (o : ordered E) (h1 h2 : leftish_heap E) (e1 e2 : E)\n  , lh_findMin h1 = Some e1 -> lh_findMin h2 = Some e2 -> lt e2 e1 = true -> lh_findMin (lh_merge h1 h2) = Some e2.\nProof.\nAdmitted.\n\nTheorem lh_delete_min\n  : forall (E : Type) (o : ordered E) (h1 h2 : leftish_heap E) (e1 e2 : E)\n  , lh_findMin h1 = Some e1 -> lt e2 e1 = true -> lh_deleteMin (lh_insert e2 h1) = Some h2 -> lh_findMin h2 = Some e1.\nProof.\nAdmitted.\n\nInstance leftish {E : Type} `{o : ordered E} : heap (leftish_heap E) E :=\n  { empty     := lh_empty\n  ; isEmpty   := lh_isEmpty\n  ; insert    := lh_insert\n  ; merge     := lh_merge\n  ; findMin   := lh_findMin\n  ; deleteMin := lh_deleteMin\n\n  (* Type and ordered instance come from the type class, thus we use _ _ *)\n  ; empty_is_empty          := lh_empty_is_empty _\n  ; non_empty_is_not_empty  := lh_non_empty_is_not_empty _ _\n  ; merge_empty_left        := lh_merge_empty_left _ _\n  ; merge_empty_right       := lh_merge_empty_right _ _\n  ; empty_findMin           := lh_empty_findMin _ _\n  ; empty_deleteMin         := lh_empty_deleteMin _ _\n  ; insert_min              := lh_insert_min _ _\n  ; insert_non_min          := lh_insert_non_min _ _\n  ; merge_min_left          := lh_merge_min_left _ _\n  ; merge_min_right         := lh_merge_min_right _ _\n  ; delete_min              := lh_delete_min _ _\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/Heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.701136810587191}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Coq.Lists.List.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.ModOps.\nRequire Import Crypto.Arithmetic.Partition.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.ZUtil.Modulo Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.\n\nRequire Import Crypto.Util.Notations.\nLocal Open Scope Z_scope.\nImport Weight.\n\nDefinition uweight (lgr : Z) : nat -> Z\n  := weight lgr 1.\nDefinition uwprops lgr (Hr : 0 < lgr) : @weight_properties (uweight lgr).\nProof using Type. apply wprops; lia. Qed.\nLemma uweight_eq_alt' lgr n : uweight lgr n = 2^(lgr*Z.of_nat n).\nProof using Type. now cbv [uweight weight]; autorewrite with zsimplify_fast. Qed.\nLemma uweight_eq_alt lgr (Hr : 0 <= lgr) n : uweight lgr n = (2^lgr)^Z.of_nat n.\nProof using Type. now rewrite uweight_eq_alt', Z.pow_mul_r by lia. Qed.\nLemma uweight_eval_shift lgr (Hr : 0 <= lgr) xs :\n  forall n,\n    length xs = n ->\n    Positional.eval (fun i => uweight lgr (S i)) n xs =\n    (uweight lgr 1) * Positional.eval (uweight lgr) n xs.\nProof using Type.\n  induction xs using rev_ind; destruct n; distr_length;\n    intros; [cbn; ring | ].\n  rewrite !Positional.eval_snoc with (n:=n) by distr_length.\n  rewrite IHxs, !uweight_eq_alt by lia.\n  autorewrite with push_Zof_nat push_Zpow.\n  rewrite !Z.pow_succ_r by auto with zarith.\n  ring.\nQed.\nLemma uweight_S lgr (Hr : 0 <= lgr) n : uweight lgr (S n) = 2 ^ lgr * uweight lgr n.\nProof using Type.\n  rewrite !uweight_eq_alt by auto.\n  autorewrite with push_Zof_nat.\n  rewrite Z.pow_succ_r by auto with zarith.\n  reflexivity.\nQed.\nLemma uweight_double_le lgr (Hr : 0 < lgr) n : uweight lgr n + uweight lgr n <= uweight lgr (S n).\nProof using Type.\n  rewrite uweight_S, uweight_eq_alt by lia.\n  rewrite Z.add_diag.\n  apply Z.mul_le_mono_nonneg_r.\n  { auto with zarith. }\n  { transitivity (2 ^ 1); [ reflexivity | ].\n    apply Z.pow_le_mono_r; lia. }\nQed.\nLemma uweight_sum_indices lgr (Hr : 0 <= lgr) i j : uweight lgr (i + j) = uweight lgr i * uweight lgr j.\nProof.\n  rewrite !uweight_eq_alt by lia.\n  rewrite Nat2Z.inj_add; auto using Z.pow_add_r with zarith.\nQed.\nLemma uweight_0 lgr : uweight lgr 0 = 1.\nProof.\n  rewrite uweight_eq_alt', Z.mul_0_r; reflexivity.\nQed.\nLemma uweight_1 lgr : uweight lgr 1 = 2^lgr.\nProof using Type.\n  cbv [uweight weight].\n  f_equal; autorewrite with zsimplify_const; lia.\nQed.\n\n(* Because the weight is uniform, we can start partitioning from\n  any index and end up with the same result. *)\nLemma uweight_recursive_partition_change_start lgr (Hr : 0 <= lgr) n :\n  forall i j x,\n    recursive_partition (uweight lgr) n i x\n    = recursive_partition (uweight lgr) n j x.\nProof using Type.\n  induction n; intros; [reflexivity | ].\n  cbn [recursive_partition].\n  rewrite !uweight_eq_alt by lia.\n  autorewrite with push_Zof_nat push_Zpow.\n  rewrite <-!Z.pow_sub_r by auto using Z.pow_nonzero with lia.\n  rewrite !Z.sub_succ_l.\n  autorewrite with zsimplify_fast.\n  erewrite IHn. reflexivity.\nQed.\nLemma uweight_recursive_partition_equiv lgr (Hr : 0 < lgr) n i x:\n  Partition.partition (uweight lgr) n x =\n  recursive_partition (uweight lgr) n i x.\nProof using Type.\n  rewrite recursive_partition_equiv by auto using uwprops.\n  auto using uweight_recursive_partition_change_start with lia.\nQed.\n\nLemma uweight_firstn_partition lgr (Hr : 0 < lgr) n x m (Hm : (m <= n)%nat) :\n  firstn m (Partition.partition (uweight lgr) n x) = Partition.partition (uweight lgr) m x.\nProof.\n  cbv [Partition.partition];\n    repeat match goal with\n           | _ => progress intros\n           | _ => progress autorewrite with push_firstn natsimplify zsimplify_fast\n           | _ => rewrite Nat.min_l by lia\n           | _ => rewrite weight_0 by auto using uwprops\n           | _ => reflexivity\n           end.\nQed.\n\nLemma uweight_skipn_partition lgr (Hr : 0 < lgr) n x m :\n  skipn m (Partition.partition (uweight lgr) n x) = Partition.partition (uweight lgr) (n - m) (x / uweight lgr m).\nProof.\n  cbv [Partition.partition];\n    repeat match goal with\n           | _ => progress intros\n           | _ => progress autorewrite with push_skipn natsimplify zsimplify_fast\n           | _ => rewrite skipn_seq by auto\n           | _ => rewrite weight_0 by auto using uwprops\n           | _ => rewrite recursive_partition_equiv' by auto using uwprops\n           | _ => auto using uweight_recursive_partition_change_start with zarith\n           end.\nQed.\n\nLemma uweight_partition_unique lgr (Hr : 0 < lgr) n ls :\n  length ls = n -> (forall x, List.In x ls -> 0 <= x <= 2^lgr - 1) ->\n  ls = Partition.partition (uweight lgr) n (Positional.eval (uweight lgr) n ls).\nProof using Type.\n  intro; subst n.\n  rewrite uweight_recursive_partition_equiv with (i:=0%nat) by assumption.\n  induction ls as [|x xs IHxs]; [ reflexivity | ].\n  repeat first [ progress cbn [List.length recursive_partition List.In] in *\n               | progress intros\n               | assumption\n               | rewrite Positional.eval_cons by reflexivity\n               | rewrite weight_0 by now apply uwprops\n               | rewrite uweight_1\n               | progress specialize_by_assumption\n               | progress split_contravariant_or\n               | rewrite uweight_recursive_partition_change_start with (i:=1%nat) (j:=0%nat) by lia\n               | rewrite uweight_eval_shift by lia\n               | rewrite Z.div_1_r\n               | progress Z.rewrite_mod_small\n               | rewrite Z.div_add' by auto with arith lia\n               | rewrite Z.div_small by lia\n               | match goal with\n                 | [ H : forall x, _ = x -> _ |- _ ] => specialize (H _ eq_refl)\n                 | [ |- context[(_ + ?x * _) mod ?x] ]\n                   => let k := fresh in\n                      set (k := x); push_Zmod; pull_Zmod; subst k;\n                      progress autorewrite with zsimplify_const\n                 | [ |- ?x :: _ = ?x :: _ ] => apply f_equal\n                 end ].\nQed.\n\nLemma uweight_eval_app' lgr (Hr : 0 <= lgr) n x y :\n  n = length x ->\n  Positional.eval (uweight lgr) (n + length y) (x ++ y) = Positional.eval (uweight lgr) n x + (uweight lgr n) * Positional.eval (uweight lgr) (length y) y.\nProof using Type.\n  induction y using rev_ind;\n    repeat match goal with\n           | _ => progress intros\n           | _ => progress distr_length\n           | _ => progress autorewrite with push_eval zsimplify natsimplify\n           | _ => rewrite Nat.add_succ_r\n           | H : ?x = 0%nat |- _ => subst x\n           | _ => progress rewrite ?app_nil_r, ?app_assoc\n           | _ => reflexivity\n           end.\n  rewrite IHy by auto. rewrite uweight_sum_indices; lia.\nQed.\n\nLemma uweight_eval_app lgr (Hr : 0 <= lgr) n m x y :\n  n = length x ->\n  m = (n + length y)%nat ->\n  Positional.eval (uweight lgr) m (x ++ y) = Positional.eval (uweight lgr) n x + (uweight lgr n) * Positional.eval (uweight lgr) (length y) y.\nProof using Type. intros. subst m. apply uweight_eval_app'; lia. Qed.\n\nLemma uweight_partition_app lgr (Hr : 0 < lgr) n m a b :\n Partition.partition (uweight lgr) n a ++ Partition.partition (uweight lgr) m b\n  = Partition.partition (uweight lgr) (n+m) (a mod uweight lgr n + b * uweight lgr n).\nProof.\n  assert (0 < uweight lgr n) by auto using uwprops.\n  match goal with |- _ = ?rhs => rewrite <-(firstn_skipn n rhs) end.\n  rewrite uweight_firstn_partition, uweight_skipn_partition by lia.\n  rewrite Z.div_add by lia.\n  rewrite (Z.div_small (_ mod _)) by auto with zarith.\n  f_equal.\n  { apply partition_eq_mod; [ auto using uwprops | ].\n    push_Zmod. autorewrite with zsimplify. reflexivity. }\n  { f_equal; lia. }\nQed.\n\nLemma mod_mod_uweight lgr (Hr : 0 < lgr) a i j :\n  (i <= j)%nat -> (a mod (uweight lgr j)) mod (uweight lgr i) = a mod (uweight lgr i).\nProof.\n  intros. rewrite <-Znumtheory.Zmod_div_mod; auto using uwprops; [ ].\n  rewrite !uweight_eq_alt'. apply Divide.Z.divide_pow_le. nia.\nQed.\n\nLemma uweight_pull_mod lgr (Hr : 0 < lgr) x i j :\n  (j <= i)%nat ->\n  x mod (uweight lgr i) / uweight lgr j = (x / uweight lgr j) mod (uweight lgr (i - j)).\nProof.\n  intros. rewrite Z.mod_pull_div by auto using Z.lt_le_incl, uwprops.\n  rewrite <-uweight_sum_indices by lia.\n  repeat (f_equal; try lia).\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Arithmetic/UniformWeight.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.7011368092100528}}
{"text": "(**\n池渕さん 「プログラマのための圏論の基礎」\n- Categories for the Working Programmer -\n1. 圏論とプログラミング、プロダクト\nhttp://www.iij-ii.co.jp/lab/techdoc/category/category1.html\n\n勉強のために、この表層をSSReflectに移した。\nオリジナルと異なり、Setoid は自分で定義している。\nまた、Mor の定義を Obj -> Obj -> Setoid とした。\n*)\n\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import Classes.RelationClasses.     (* Equivalence *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(*\nReserved Notation \"A ~> B\" (at level 89, right associativity, only parsing).\nReserved Notation \"f 'o' g\" (at level 41, right associativity, only parsing).\n *)\n\nSection Categories.\n\n  Class Setoid :=\n    {\n      carrier : Type;\n      equiv : carrier -> carrier -> Prop\n    }.\n  Coercion carrier : Setoid >-> Sortclass.\n  Notation \"x === z\" := (equiv x z) (at level 70).\n  \n  Class Category :=\n    {\n      (* 対象の定義 *)\n      Obj : Type;                           (* Category -> Type *)\n      \n      (* 射の定義 *)      \n      Mor : Obj -> Obj -> Setoid;           (* Coersion が有効になる。 *)\n      \n      (* 恒等射の定義 *)\n      idC : forall {A : Obj}, Mor A A;\n      \n      (* 射の合成の定義 *)\n      composeC : forall {A B C : Obj}, Mor B C -> Mor A B -> Mor A C;\n      \n      (* 単位律の定義 *)\n      left_identity : forall (A B : Obj) (f : Mor A B), composeC idC f === f;\n      right_identity : forall (A B : Obj) (f : Mor A B), composeC f idC === f;\n      \n      (* 結合律の定義 *)\n      associativity : forall (A B C D : Obj)\n                             (f : Mor A B) (g : Mor B C) (h : Mor C D),\n          composeC (composeC h g) f === composeC h (composeC g f)\n    }.\n  \n  Check @Obj : Category -> Type.\n  (* Obj が出現する文脈では、CP : Category を省略できない。\n     ここで、CPは、ProductをもつCategoryの意味。 *)\n  \n  (* 可換の定義 *)\n  Definition commute {CP : Category} {A B C : Obj}\n             (f : Mor A B) (g : Mor B C) (h : Mor A C) :=\n    @composeC CP _ _ _ g f === h.\n  \n  (* 直積 *)\n  Class Product {CP : Category} (P : Obj -> Obj -> Obj) :=\n    {\n      proj1 : forall {A B : Obj}, Mor (P A B) A;\n      proj2 : forall {A B : Obj}, Mor (P A B) B;\n      \n      (* 仲介射 *)\n      mediating : forall {A B X : Obj}, Mor X A -> Mor X B -> Mor X (P A B);\n      (* mediating = (&&&) *)\n      \n      (* CP は、commute を経由して、composeC に渡される。 *)\n      med_commute1 : forall (A B X : Obj) (f : Mor X A) (g : Mor X B),\n          commute (mediating f g) proj1 f;\n      med_commute2 : forall (A B X : Obj) (f : Mor X A) (g : Mor X B),\n          commute (mediating f g) proj2 g;\n      med_unique : forall (A B X : Obj)\n                          (f : Mor X A) (g : Mor X B) (h : Mor X (P A B)),\n                     @commute CP X (P A B) A h proj1 f ->\n                     @commute CP X (P A B) B h proj2 g ->\n                     h === @mediating A B X f g\n    }.\n  \n  Definition parallel {CP : Category} {A B C D : Obj} {P : Obj -> Obj -> Obj}\n             {Prod : Product P}\n             (f : Mor A B) (g : Mor C D) : Mor (P A C) (P B D) :=\n    let (p1, p2) :=\n        (@proj1 CP P Prod A C, @proj2 CP P Prod A C) in\n    mediating (composeC f p1) (composeC g p2).\n  (* parallel = (***) または <f,g> *)\nEnd Categories.\n\n(* *********************** *)\n(* 関数の世界、関数 と 直積 *)\n(* *********************** *)\nSection Functions.\n  (* Ordinary tuples are products *)\n  \n  Instance EquivExt : forall (A B : Set), Equivalence (@eqfun A B) := (* notu *)\n    {\n      Equivalence_Reflexive := @frefl A B;\n      Equivalence_Symmetric := @fsym A B;\n      Equivalence_Transitive := @ftrans A B\n    }.\n  \n  Instance EqMor : forall (A B : Set), Setoid :=\n    {\n      carrier := A -> B;\n      equiv := @eqfun B A\n    }.\n  \n  Instance Func : Category :=               (* Category *)\n    {\n      Obj := Set;\n      Mor := EqMor;\n      idC A := id;\n      composeC A B C := funcomp tt          (* compose *)\n    }.\n  Proof.\n    - by rewrite //=.\n    - by rewrite //=.\n    - by rewrite //=.\n  Defined.\n  \n  (* Instance Prod : @Product Func prod := *)\n  Instance Prod : Product prod :=\n    {\n      proj1 A B := @fst A B;\n      proj2 A B := @snd A B ;\n      mediating A B X := fun f g x => (f x, g x)\n    }.\n  Proof.\n    - by rewrite //=.\n    - by rewrite //=.\n    - rewrite /commute /= /eqfun.\n      move=> A B X f g h H H0 x.\n      rewrite -H -H0.\n        by apply surjective_pairing.\n  Qed.\nEnd Functions.\n\n(* ********************** *)\n(* 半順序の世界、>= と max *)\n(* >= はProp、つまり (m >= n)%coq_nat にするべき *)\n(* ********************** *)\nSection Orders.\n  (* max of nat is a product *)\n  \n  Definition geq m n := m >= n.\n  \n  Check leqnn : forall n : nat, n <= n.\n\n  Lemma geq_trans : forall m n p : nat, n >= p -> m >= n -> m >= p.\n  Proof.\n    move=> m n p H1 H2.\n    move: H1 H2.\n      by apply: leq_trans.\n  Qed.\n  \n  Definition eq_geq m n (p q : m >= n) := true.\n  \n  Instance EquivGeq : forall m n, Equivalence (@eq_geq m n). (* notu *)\n  Proof.\n      by [].\n  Qed. \n  \n  Instance EqGeq : forall m n, Setoid :=\n    {\n      carrier := m >= n;\n      equiv := @eq_geq m n\n    }.\n  \n  Instance Order : Category :=\n    {\n      Obj := nat;\n      Mor := EqGeq;\n      idC := leqnn;\n      composeC := geq_trans\n    }.\n  Proof.\n    - by [].\n    - by [].\n    - by [].\n  Defined.\n  \n  Check leq_maxl : forall m n : nat, m <= maxn m n.\n  Check leq_maxr : forall m n : nat, n <= maxn m n.  \n  \n  Lemma max_med : forall m n x,\n      m <= x -> n <= x -> maxn m n <= x.\n  Proof.\n    move=> m n x H1 H2.\n    rewrite geq_max.\n    apply/andP.\n      by split.\n  Qed.\n  \n  (* Instance Max : Product maxn := *)\n  Instance Max : @Product Order maxn :=\n    {\n      proj1 := leq_maxl;\n      proj2 := leq_maxr;\n      mediating := max_med\n    }.\n  Proof.\n    - by [].\n    - by [].\n    - by [].\n  Defined.\n  (* an application of parallel (***) *)\n  \n  Theorem parallel_max : forall m n p q,\n      m >= n -> p >= q -> maxn m p >= maxn n q.\n  Proof.\n    move=> m n p q.\n    Check @parallel.\n    Check @parallel Order.\n    Check @parallel Order m n p q maxn Max.\n      by apply: (@parallel Order m n p q maxn Max).\n  Qed.\nEnd Orders.\n\n(* ********************** *)\n(* 半順序の世界、<= と min *)\n(* >= はProp、つまり (m <= n)%coq_nat にするべき *)\n(* ********************** *)\nSection Orders'.\n  \n  Check leqnn : forall n : nat, n <= n.\n\n  (* leq_trans とは前提の順番が違うので、作り直しておく。 *)\n  Lemma leq_trans' : forall m n p : nat, n <= p -> m <= n -> m <= p.\n  Proof.\n    move=> m n p H1 H2.\n    move: H2 H1.\n      by apply: leq_trans.\n  Qed.\n  \n  Definition eq_leq m n (p q : m <= n) := true.\n  \n  Instance EquivLeq : forall m n, Equivalence (@eq_leq m n). (* notu *)\n  Proof.\n      by [].\n  Qed. \n  \n  Instance EqLeq : forall m n, Setoid :=\n    {\n      carrier := m <= n;\n      equiv := @eq_leq m n\n    }.\n  \n  Instance Order' : Category :=\n    {\n      Obj := nat;\n      Mor := EqLeq;\n      idC := leqnn;\n      composeC := leq_trans'\n    }.\n  Proof.\n    - by [].\n    - by [].\n    - by [].\n  Defined.\n\n  Check geq_minl : forall m n : nat, minn m n <= m.\n  Check geq_minr : forall m n : nat, minn m n <= n.\n  \n  Lemma min_med : forall m n x,\n      x <= m -> x <= n -> x <= minn m n.\n  Proof.\n    move=> m n x H1 H2.\n    rewrite leq_min.\n    apply/andP.\n      by split.\n  Qed.  \n  \n  (* Instance Min : Product minn := *)\n  Instance Min : @Product Order' minn :=\n    {\n      proj1 := geq_minl;\n      proj2 := geq_minr;\n      mediating := min_med\n    }.\n  Proof.\n    - by [].\n    - by [].\n    - by [].\n  Defined.\n  (* an application of parallel (***) *)\n  \n  Theorem parallel_min : forall m n p q,\n      m <= n -> p <= q -> minn m p <= minn n q.\n  Proof.\n    move=> m n p q.\n    Check @parallel Order' m n p q minn Min.\n      by apply: (@parallel Order' m n p q minn Min).\n  Qed.  \nEnd Orders'.\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "coq", "sha": "7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d", "save_path": "github-repos/coq/suharahiromichi-coq", "path": "github-repos/coq/suharahiromichi-coq/coq-7509c2b5f686fc0fef7f97c016f6ecbf99b2de5d/monad/ssr_cat_product_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7011368081641332}}
{"text": "(**************************************************************)\n(*   Copyright Dominique Larchey-Wendling [*]                 *)\n(*                                                            *)\n(*                             [*] Affiliation LORIA -- CNRS  *)\n(**************************************************************)\n(*      This file is distributed under the terms of the       *)\n(*         CeCILL v2 FREE SOFTWARE LICENSE AGREEMENT          *)\n(**************************************************************)\n\nRequire Import Arith Omega.\n\nRequire Import utils decidable_t.\nRequire Import recalg ra_ca.\n\nSet Implicit Arguments.\n\n(* Computation always have a cost greater than 1 *)\n\nTheorem ra_ca_cost k (f : recalg k) v q x : [f;v] -[q>> x -> 0 < q.\nProof.\n  induction 1; omega.\nQed.\n\nSection functionality.\n\n  (* This one is not very complicated but it requires inversion lemmas \n     which can be difficult to obtain if you do not know how to proceed\n     with dependent types  \n  *)\n  \n  Theorem ra_ca_fun k (f : recalg k) v n m x y : \n           [f;v] -[n>> x \n        -> [f;v] -[m>> y \n        -> n = m /\\ x = y.\n  Proof.\n    intros H.\n    revert H m y.\n    induction 1 as [ n v | v | v \n                   | k v p \n                   | k i f gj v n w q x H1 IH1 H2 IH2 \n                   | k f g v n x H1 IH2 \n                   | k f g v n p x q y H1 IH1 H2 IH2\n                   | k f v p n w q H1 IH1 H2 IH2 ]; intros n2 x2 H3.\n    apply ra_ca_cst_inv  in H3; destruct H3; split; auto.\n    apply ra_ca_zero_inv in H3; destruct H3; split; auto.\n    apply ra_ca_succ_inv in H3; destruct H3; split; auto.\n    apply ra_ca_proj_inv in H3; destruct H3; split; auto.\n    \n    apply ra_ca_comp_inv in H3.\n    destruct H3 as (q' & w' & n' & H5 & H3 & H4).\n    assert (forall p, vec_pos n p = vec_pos n' p /\\ vec_pos w p = vec_pos w' p) as E.\n      intros p; apply IH1, H3.\n    assert (n = n' /\\ w = w') as E'.\n      split; apply vec_pos_ext; intro; apply E.\n    destruct E'; subst n' w'.  \n    destruct (IH2 _ _ H4); subst; auto.\n    \n    apply ra_ca_rec_0_inv in H3.\n    destruct H3 as (m & ? & H3).\n    apply IH2 in H3; destruct H3; subst; auto.\n    apply ra_ca_rec_S_inv in H3.\n    destruct H3 as (y' & q' & p' & H3 & H5 & H4).\n    apply IH1 in H5; destruct H5; subst.\n    apply IH2 in H4; destruct H4; subst; auto.\n\n    apply ra_ca_min_inv in H3.\n    destruct H3 as (q' & w' & n' & H3 & H5 & H4).\n    destruct (lt_eq_lt_dec p x2) as [ [ C | E ] | C ].\n\n    specialize (H4 (nat2pos C)).\n    rewrite pos2nat_nat2pos in H4.\n    apply IH2, proj2 in H4; discriminate H4.\n\n    subst x2.\n    apply IH2, proj1 in H5; subst q'.\n    assert (forall p, vec_pos q p = vec_pos n' p /\\ S (vec_pos w p) = S(vec_pos w' p)) as E.\n      intros i; apply IH1, H4.\n    assert (q = n' /\\ w = w') as E'.\n      split; apply vec_pos_ext; intro i.\n      apply E.\n      generalize (proj2 (E i)); omega.\n    destruct E'; subst; auto.\n\n    rewrite <- (pos2nat_nat2pos C) in H5.\n    apply IH1, proj2 in H5.\n    discriminate H5.\n  Qed.\n  \nEnd functionality.\n\nSection decidability.\n\n  (* These next two forms of *ra_ca_min* are better suited for the decidability proof,\n     they generate lesser subcases *)\n\n  Local Lemma in_ra_ca_min' k (f : recalg (S k)) v x (q w : vec nat (x+1)) :\n       (forall p, [f;pos2nat p##v] -[vec_pos q p>> vec_pos w p)\n    -> (forall p, 0 < vec_pos w (pos_lft _ p))\n    -> 0 = vec_pos w (pos_rt _ pos0)\n    -> [ra_min f;v] -[1+vec_sum q>> x.\n  Proof.\n    intros H1 H2 H3.\n    rewrite (vec_app_lft_rt _ _ q), vec_sum_app.\n    rewrite (plus_comm (vec_sum _)), plus_assoc.\n    apply in_ra_ca_min with (vec_set_pos (fun p => vec_pos (vec_lft w) p - 1)).\n    intros j.\n    generalize (H1 (pos_lft _ j)).\n    rewrite pos2nat_pos_lft; eqgoal; f_equal.\n    unfold vec_lft; rewrite vec_pos_set; auto.\n    rewrite vec_pos_set.\n    generalize (H2 j); unfold vec_lft; rewrite vec_pos_set; omega.\n    rewrite H3.\n    generalize (H1 (pos_rt _ pos0)).\n    eqgoal; f_equal.\n    rewrite pos2nat_pos_rt; f_equal; auto.\n    simpl; auto.\n  Qed.\n\n  Local Lemma ra_ca_min_inv' k (f : recalg (S k)) v n x :\n       [ra_min f;v] -[n>> x\n    -> exists q w : vec nat (x+1),\n         n = 1+vec_sum q\n      /\\ 0 = vec_pos w (pos_rt _ pos0)\n      /\\ (forall p, 0 < vec_pos w (pos_lft _ p))\n      /\\ (forall p, [f;pos2nat p##v] -[vec_pos q p>> vec_pos w p).\n  Proof.\n    intros H.\n    apply ra_ca_min_inv in H.\n    destruct H as (p & w & q & H1 & H2 & H3).\n    exists (vec_app q (p##vec_nil)), \n           (vec_app (vec_set_pos (fun p => S (vec_pos w p))) (0##vec_nil)).\n    split.\n    rewrite vec_sum_app; simpl; omega.\n    split.\n    rewrite vec_pos_app_rt; auto.\n    split.\n    intros i; rewrite vec_pos_app_lft, vec_pos_set; omega.\n    intros i.\n    destruct (pos_split i) as [ (j & ?) | (j & ?) ]; subst i.\n    repeat rewrite vec_pos_app_lft.\n    rewrite vec_pos_set, pos2nat_pos_lft; auto.\n    repeat rewrite vec_pos_app_rt.\n    rewrite pos2nat_pos_rt.\n    pos_inv j; simpl.\n    revert H2; eqgoal; do 2 f_equal; auto.\n    pos_inv j.\n  Qed.\n\n  (* Since ra_ca is functional, sequences of computations with the same total cost\n     must have the same length *)\n\n  Local Lemma ra_ca_id_prefix k (f : recalg (S k)) (v : vec nat k) x qx wx y qy wy :\n       (forall p : pos x, [f;pos2nat p##v] -[vec_pos qx p>> vec_pos wx p)\n    -> (forall p : pos y, [f;pos2nat p##v] -[vec_pos qy p>> vec_pos wy p)\n    -> vec_sum qx = vec_sum qy\n    -> x < y -> False.\n  Proof.\n    intros H3 H4 H5 H.\n\n    assert ({ p | y = x + S p }) as E.\n      exists (y-x-1); omega.\n    destruct E as (p & ?); subst y.\n  \n    assert (qx = vec_lft qy) as E2.\n      apply vec_pos_ext.\n      intros i.\n      unfold vec_lft; rewrite vec_pos_set.\n      generalize (H4 (pos_lft _ i)).\n      rewrite pos2nat_pos_lft; intros H6.\n      apply (ra_ca_fun (H3 i) H6).\n    rewrite (vec_app_lft_rt _ _ qy), vec_sum_app in H5.\n    generalize (vec_pos_sum (vec_rt qy) pos0).\n    specialize (H4 (pos_rt _ pos0)).\n    apply ra_ca_cost in H4.\n    rewrite <- E2 in H5.\n    simpl in H5.\n    omega.\n  Qed.\n\n  Local Lemma ra_ca_prefix_eq k (f : recalg (S k)) (v : vec nat k) x qx wx y qy wy :\n       (forall p : pos x, [f;pos2nat p##v] -[vec_pos qx p>> vec_pos wx p)\n    -> (forall p : pos y, [f;pos2nat p##v] -[vec_pos qy p>> vec_pos wy p)\n    -> vec_sum qx = vec_sum qy\n    -> x = y.\n  Proof.\n    intros H3 H4 H5.\n    destruct (lt_eq_lt_dec x y) as [ [ H | ] | H ]; auto; exfalso.\n    apply ra_ca_id_prefix with (1 := H3) (2 := H4); auto.\n    apply ra_ca_id_prefix with (1 := H4) (2 := H3); auto.\n  Qed.\n \n  Theorem ra_ca_decidable_t k (f : recalg k) v n : decidable_t { x | [f;v] -[n>> x }.\n  Proof.\n    revert v n; induction f as [ i | | | | k i f g Hf Hg | k f g Hf Hg | k f ]; intros v n.\n \n    (* case of ra_cst *) \n    destruct (eq_nat_dec n 1) as [ H | H ]; subst.\n    left; exists i; constructor.\n    right; intros (x & Hx); apply ra_ca_cst_inv in Hx; omega.\n\n    (* case of ra_zero *)\n    destruct (eq_nat_dec n 1) as [ H | H ]; subst.\n    left; exists 0; constructor.\n    right; intros (x & Hx); apply ra_ca_zero_inv in Hx; omega.\n\n    (* case of ra_succ *)\n    destruct (eq_nat_dec n 1) as [ H | H ]; subst.\n    left; exists (1+vec_head v); constructor.\n    right; intros (x & Hx); apply ra_ca_succ_inv in Hx; omega.\n\n    (* case of ra_proj *)\n    destruct (eq_nat_dec n 1) as [ H | H ]; subst.\n    left; exists (vec_pos v p); constructor.\n    right; intros (x & Hx); apply ra_ca_proj_inv in Hx; omega.\n\n    (* case of ra_comp *) \n\n    destruct n as [ | n ].\n    right; intros (x & Hx); apply ra_ca_cost in Hx; omega.\n\n    (* first we try to compute [vec_pos g *;v] in less than n steps total *) \n\n    generalize (@vec_sum_decide_t _ (vec_set_pos (fun p n => { x | [vec_pos g p;v] -[n>> x} : Type))). \n    intros Hg'; inst Hg'.\n    intros; rewrite vec_pos_set; auto.\n    apply (@decidable_t_bounded' (S n)) in Hg'.\n    destruct Hg' as [ (m & Hm & q & Hq & Hg') | Hg' ].\n\n    assert (Hq' : forall p, { x | [vec_pos g p;v] -[vec_pos q p>> x }).\n      intros p; specialize (Hg' p); rewrite vec_pos_set in Hg'; auto.\n    clear Hg'.\n    apply vec_reif_t in Hq'.\n    destruct Hq' as (w & Hw).\n\n    (* then we try to compute [f;_] in the remaining number of steps *)\n\n    destruct (Hf w (n-m)) as [ (x & Hx) | C ].\n\n    (* we can compute [ f o g ; v ] *) \n\n    left; exists x.\n    cutrewrite (n = (n-m)+vec_sum q); try omega.\n    apply in_ra_ca_comp with (1 := Hw); auto.\n\n    (* [f;_] cannot be computed *)\n\n    right; intros (x & Hx).\n    apply ra_ca_comp_inv in Hx.\n    destruct Hx as (p & w' & q' & H1 & H2 & H3).\n    assert ( q = q' /\\ w = w' ) as E.\n      split; apply vec_pos_ext; intros u;\n      apply (ra_ca_fun (Hw u) (H2 u)).\n    destruct E; subst q' w'.\n    apply C; exists x; revert H3; eqgoal; f_equal; omega.\n\n    (* [vec_pos g *;v] cannot be computed in less than n steps total *)\n\n    right; intros (x & Hx).\n    apply ra_ca_comp_inv in Hx.\n    destruct Hx as (p & w & q & H1 & H2 & H3).\n    apply Hg'.\n    exists (vec_sum q).\n    exists. omega.\n    exists q; split; auto.\n    intros j; rewrite vec_pos_set; exists (vec_pos w j); auto.\n\n    (* case of ra_rec *)\n   \n    rewrite (vec_head_tail v); generalize (vec_head v) (vec_tail v).\n    clear v; intros u v.\n    revert n; induction u as [ | u IHu ]; intros n.\n\n    (* case of rec 0 *)\n\n    destruct n as [ | n ].\n    right; intros (x & Hx); apply ra_ca_cost in Hx; omega.\n    destruct (Hf v n) as [ (x & Hx) | C ].\n    left; exists x; constructor; auto.\n    right; intros (x & Hx); apply C; exists x.\n    apply ra_ca_rec_0_inv in Hx.\n    destruct Hx as (m & Hm & Hx).\n    revert Hx; eqgoal; f_equal; omega.\n\n    (* case of rec S *)\n\n    destruct n as [ | n ].\n    right; intros (x & Hx); apply ra_ca_cost in Hx; omega.\n    apply (decidable_t_bounded' (S n)) in IHu.\n    destruct IHu as [ (p & H1 & y & Hy) | C ].\n\n    destruct (Hg (u##y##v) (n-p)) as [ (x & Hx) | C ].\n    left; exists x.\n    cutrewrite (n = p+(n-p)); try omega.\n    apply in_ra_ca_rec_S with y; auto.\n\n    right; intros (x & Hx).\n    apply ra_ca_rec_S_inv in Hx.\n    destruct Hx as (y' & q' & p' & H2 & H3 & H4).\n    destruct (ra_ca_fun Hy H3); subst p' y'.\n    apply C; exists x; revert H4; eqgoal; f_equal; omega.\n\n    right; intros (x & Hx).\n    apply ra_ca_rec_S_inv in Hx.\n    destruct Hx as (y & q & p & H2 & H3 & H4).\n    apply C.\n    exists p.\n    exists.\n    omega.\n    exists y; auto.\n\n    (* case of ra_min *)\n\n    specialize (fun i => IHf (i##v)).\n    destruct n as [ | n ].\n    right; intros (x & Hx); apply ra_ca_cost in Hx; omega.\n    apply (vec_sum_unbounded_decide_t) with (m := n) in IHf.\n    2: intros ? (? & H); apply ra_ca_cost in H; omega.\n    destruct IHf as [ (x' & q & H1 & H2) | C ].\n  \n    (* no sequence of computation as a total cost of n *)\n    Focus 2.\n    right.\n    intros (x & Hx).\n    apply ra_ca_min_inv' in Hx.\n    destruct Hx as (q & w & H2 & H3 & H4 & H5).\n    apply C.\n    exists (x+1), q; split.\n    omega.\n    intros p; exists (vec_pos w p); auto.\n\n    (* the sequence q has a total cost of n *)  \n    apply vec_reif_t in H2.\n    destruct H2 as (w & Hw).\n  \n    assert ( (x' = 0) + { x | (x' = x + 1)%nat } )%type as E.\n      destruct x' as [ | x' ]; [ left | right ]; auto; exists x'; omega.\n    destruct E as [ ? | (x & ?) ]; subst x'.\n  \n    (* q is of length 0 *)\n    rewrite (vec_0_nil q) in H1; simpl in H1.\n    right.\n    intros (x & Hx).\n    apply ra_ca_min_inv' in Hx.\n    destruct Hx as (q' & w' & H2 & H3 & H4 & H5).\n    specialize (H5 (pos_rt _ pos0)).\n    apply ra_ca_cost in H5.\n    generalize (vec_pos_sum q' (pos_rt _ pos0)).\n    omega.\n \n    (* q is of length x+1 *)\n    destruct (eq_nat_dec (vec_pos w (pos_rt _ pos0)) 0) as [ H2 | H2 ].\n    destruct (vec_strict_pos (vec_lft w)) as [ H3 | (p & Hp) ].\n \n    (* the sequence is strictly positive and ends with 0 *)\n    left; exists x.\n    cutrewrite (S n = 1+vec_sum q); try omega.\n    apply in_ra_ca_min' with w; auto.\n    intros p; generalize (H3 p); unfold vec_lft; rewrite vec_pos_set; auto.\n\n    (* the sequence contains a zero before it ends *)\n    right; intros (x' & Hx').\n    apply ra_ca_min_inv' in Hx'.\n    destruct Hx' as (q' & w' & H3 & H4 & H5 & H6).\n    generalize (@ra_ca_prefix_eq k f v _ q w _ q' w' Hw H6); intros H7.\n    assert (x = x') as E. omega.\n    subst x'; clear H7.\n    specialize (Hw (pos_lft _ p)).\n    rewrite pos2nat_pos_lft in Hw.\n    specialize (H6 (pos_lft _ p)).\n    rewrite pos2nat_pos_lft in H6.\n    generalize (proj2 (ra_ca_fun Hw H6)).\n    generalize (H5 p).\n    unfold vec_lft in Hp; rewrite vec_pos_set in Hp; omega.\n\n    (* the sequence does not end with a zero *)\n\n    right; intros (x' & Hx').\n    apply ra_ca_min_inv' in Hx'.\n    destruct Hx' as (q' & w' & H3 & H4 & H5 & H6).\n    generalize (@ra_ca_prefix_eq k f v _ q w _ q' w' Hw H6); intros H7.\n    assert (x = x') as E. omega.\n    subst x'; clear H7.\n    specialize (Hw (pos_rt _ pos0)).\n    rewrite pos2nat_pos_rt in Hw.\n    specialize (H6 (pos_rt _ pos0)).\n    rewrite pos2nat_pos_rt in H6.\n    generalize (proj2 (ra_ca_fun Hw H6)).\n    omega.\n  Qed.\n\nEnd decidability.\n\nDefinition ra_ca_eval k (f : recalg k) v n : option nat := \n  match ra_ca_decidable_t f v n with\n    | inl T  => Some (proj1_sig T)\n    | inr _ => None \n  end.\n  \nFact ra_ca_eval_prop k f v n x : [f;v] -[n>> x <-> @ra_ca_eval k f v n = Some x.\nProof.\n  unfold ra_ca_eval.\n  destruct (ra_ca_decidable_t f v n) as [ (y & Hy) | C ]; simpl.\n  split.\n  intros Hx; generalize (ra_ca_fun Hx Hy); intros (? & ?); subst; auto.\n  injection 1; intros; subst; auto.\n  split.\n  intro; exfalso; apply C; exists x; auto.\n  discriminate 1.\nQed.\n\n(*\nExtraction Language Haskell.\nExtraction \"ra_compute\" ra_ca_eval.\n*)", "meta": {"author": "DmxLarchey", "repo": "Coq-is-total", "sha": "0f3facc9cf06e0b41194fdb0cc952816fb09c39a", "save_path": "github-repos/coq/DmxLarchey-Coq-is-total", "path": "github-repos/coq/DmxLarchey-Coq-is-total/Coq-is-total-0f3facc9cf06e0b41194fdb0cc952816fb09c39a/ra_ca_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7931059462938814, "lm_q1q2_score": 0.7011368062640353}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.omega.Omega.\n\nLemma plus_eq_right_0 : forall a b, a + b = b -> a = 0.\n  induction a; simpl; intuition.\nQed.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Cito/NatFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7010827907474303}}
{"text": "Require Import Ascii.\nRequire Import List.\nRequire Import String.\nRequire Import Program.\nRequire Import ZArith.\n\n(** Unicode codepoint literal support, based on\n    https://github.com/arthuraa/poleiro/blob/master/theories/ForceOption.v *)\n\nOpen Scope char_scope.\nOpen Scope Z_scope.\n\nFixpoint _parse_hex_digit c :=\n  match c with\n  | \"0\" => Some 0\n  | \"1\" => Some 1\n  | \"2\" => Some 2\n  | \"3\" => Some 3\n  | \"4\" => Some 4\n  | \"5\" => Some 5\n  | \"6\" => Some 6\n  | \"7\" => Some 7\n  | \"8\" => Some 8\n  | \"9\" => Some 9\n  | \"A\" | \"a\" => Some 10\n  | \"B\" | \"b\" => Some 11\n  | \"C\" | \"c\" => Some 12\n  | \"D\" | \"d\" => Some 13\n  | \"E\" | \"e\" => Some 14\n  | \"F\" | \"f\" => Some 15\n  | _ => None\n  end.\n\nOpen Scope string_scope.\n\nFixpoint _parse_hex_opt_aux s accum :=\n  match s with\n  | \"\" => Some accum\n  | String c s' => \n      match _parse_hex_digit c with\n      | Some n => _parse_hex_opt_aux s' (16 * accum + n)\n      | None => None\n      end\n  end.\n\nDefinition _parse_hex_opt s := _parse_hex_opt_aux s 0.\n\nLemma _parse_hex_opt_1: _parse_hex_opt \"FFfE\" = Some 65534.\nProof.\n  auto.\nQed.\n\nLemma _parse_hex_opt_2: _parse_hex_opt \"AAfg\" = None.\nProof.\n  auto.\nQed.\n\nInductive hexParseError := HexParseError.\n\nDefinition force_some {A} {ErrType} (o:option A) (e:ErrType) :\n  match o with\n  | Some _ => A\n  | None => ErrType\n  end\n:=\n  match o with\n  | Some a => a\n  | None => e\n  end.\n\nDefinition parse_hex (s:string) := force_some (_parse_hex_opt s) HexParseError.\n\nLemma parse_hex_1: (parse_hex \"FFfE\" - 65534 = 0).\nProof.\n  auto.\nQed.\n\nLemma parse_hex_2: parse_hex \"AAfg\" = HexParseError.\nProof.\n  auto.\nQed.\n\nNotation \"U+ s\" := (parse_hex s) (at level 0, no associativity).\n\nLemma U_1: U+\"FfFe\" = 65534.\nProof.\n  auto.\nQed.\n\nLemma U_2: U+\"AAfg\" = HexParseError.\nProof.\n  auto.\nQed.\n\nLemma U_3: U+\"FfFe\" + U+\"0002\" = 65536.\nProof.\n  auto.\nQed.\n\nLemma U_4: Z.land U+\"AA\" U+\"F0\" = U+\"A0\".\nProof.\n  auto.\nQed.\n\n\n(** UTF-8 description based on https://tools.ietf.org/html/rfc3629#section-3 **)\n\n(** UTF-8 decoding support **)\n\nDefinition _get_lo_bits c n :=\n  Z.land (Z.of_N (N_of_ascii c)) ((Z.shiftl 1 n) - 1).\n\nFixpoint _utf8_decode_aux (s:string) (acc:Z) (phase:nat) (bound:Z): option (list Z) :=\n  match s, acc, phase, bound with\n  (* base case *)\n  | \"\", 0, 0%nat, 0 => Some []\n  (* normal case, decides based on the first byte *)\n  | String c s, 0, 0%nat, 0 =>\n    match c with\n    (* ASCII character, just decodes it *)\n    | Ascii _ _ _ _ _ _ _ false =>\n      match _utf8_decode_aux s 0 0 0 with\n      | Some l => Some ((Z.of_N (N_of_ascii c)) :: l)\n      | _ => None\n      end\n    (* two bytes codepoint *)\n    | Ascii _ _ _ _ _ false true true =>\n      _utf8_decode_aux s (_get_lo_bits c 5) 1 U+\"80\"\n    (* three bytes codepoint *)\n    | Ascii _ _ _ _ false true true true =>\n      _utf8_decode_aux s (_get_lo_bits c 4) 2 U+\"800\"\n    (* four bytes codepoint *)\n    | Ascii _ _ _ false true true true true =>\n      _utf8_decode_aux s (_get_lo_bits c 3) 3 U+\"10000\"\n    (* invalid *)\n    | _ => None\n    end\n  (* final phase of multibyte codepoint *)\n  | String c s, acc, 1%nat, bound =>\n    (* checks c & the tail decoding *)\n    match c, _utf8_decode_aux s 0 O 0 with\n    | Ascii _ _ _ _ _ _ false true, Some l =>\n      (* calculates the codepoint and checks it *)\n      let cp := (Z.lor (Z.shiftl acc 6) (_get_lo_bits c 6)) in\n      match (Z_ge_dec cp bound), (Z_le_dec cp U+\"D7FF\"), (Z_le_dec cp U+\"DFFF\") with\n      | left _, left _, _ => Some (cp :: l)\n      | left _, _, right _ => Some (cp :: l)\n      | _, _, _ => None\n      end\n    | _, _ => None\n    end\n  (* intermediate phase of multibyte codepoint *)\n  | String c s, acc, S n, bound =>\n    (* checks c *)\n    match c with\n    | Ascii _ _ _ _ _ _ false true =>\n      _utf8_decode_aux s (Z.lor (Z.shiftl acc 6) (_get_lo_bits c 6)) n bound\n    | _ => None\n    end\n  (* invalid *)\n  | _, _, _, _ => None\n  end.\n\nDefinition utf8_decode (s:string): option (list Z) :=\n  _utf8_decode_aux s 0 0 0.\n\n\n(** UTF-8 encoding support **)\n\nDefinition _aux_enc_cp_byte cp hi lo offset :=\n  ascii_of_N (Z.to_N (Z.lor offset (Z.land (Z.shiftr cp lo) ((Z.shiftl 1 (hi - lo + 1)) - 1)))).\n\nDefinition _encode_codepoint cp :=\n  match (Z_lt_dec cp 0), (Z_le_dec cp U+\"7F\"), (Z_le_dec cp U+\"7FF\"),\n        (Z_le_dec cp U+\"D7FF\"), (Z_le_dec cp U+\"DFFF\"),\n        (Z_le_dec cp U+\"FFFF\"), (Z_le_dec cp U+\"10FFFF\") with\n  | left _, _, _, _, _, _, _ => None\n  | _, left _, _, _, _, _, _ =>\n      Some (String (ascii_of_N (Z.to_N cp)) \"\")\n  | _, _, left _, _, _, _, _ =>\n      Some (String (_aux_enc_cp_byte cp 10 6 U+\"C0\") \n           (String (_aux_enc_cp_byte cp 5 0 U+\"80\") \"\"))\n  | _, _, _, left _, _, _, _ =>\n      Some (String (_aux_enc_cp_byte cp 15 12 U+\"E0\")\n           (String (_aux_enc_cp_byte cp 11 6 U+\"80\")\n           (String (_aux_enc_cp_byte cp 5 0 U+\"80\") \"\")))\n  | _, _, _, _, left _, _, _ => None\n  | _, _, _, _, _, left _, _ =>\n      Some (String (_aux_enc_cp_byte cp 15 12 U+\"E0\")\n           (String (_aux_enc_cp_byte cp 11 6 U+\"80\")\n           (String (_aux_enc_cp_byte cp 5 0 U+\"80\") \"\")))\n  | _, _, _, _, _, _, left _ =>\n      Some (String (_aux_enc_cp_byte cp 20 18 U+\"F0\")\n           (String (_aux_enc_cp_byte cp 17 12 U+\"80\")\n           (String (_aux_enc_cp_byte cp 11 6 U+\"80\")\n           (String (_aux_enc_cp_byte cp 5 0 U+\"80\") \"\"))))\n  | _, _, _, _, _, _, _ => None\n  end.\n\nFixpoint utf8_encode (l:list Z) :=\n  match l with\n  | nil => Some \"\"\n  | cp :: l' =>\n      match _encode_codepoint cp, utf8_encode l' with\n      | Some s, Some s' => Some (s ++ s')\n      | _, _ => None\n      end\n  end.\n\n\n(** Auxiliary theorems **)\n\nLemma land_bounds:\n  forall a b,\n  0 <= a ->\n  0 <= b ->\n  0 <= Z.land a b <= a.\nProof.\n  intros a b a_bounds b_bounds.\n  (* clears the easy cases first *)\n  destruct a as [|p|p], b as [|q|q]; simpl; try omega;\n  assert (Z.neg p < 0) as np_is_neg by apply Zlt_neg_0;\n  assert (Z.neg q < 0) as nq_is_neg by apply Zlt_neg_0; try omega.\n  clear a_bounds b_bounds np_is_neg nq_is_neg; generalize q; clear q.\n  (* easy lemmas for positive values *)\n  assert (forall p, 0 < Z.pos p) as pos_gt_0 by apply Pos2Z.is_pos.\n  assert (forall p, 0 <= Z.pos p) as pos_ge_0 by (intros p'; specialize (pos_gt_0 p'); omega).\n  assert (forall p, 1 <= Z.pos p) as pos_ge_1 by (intros p'; specialize (pos_gt_0 p'); omega).\n  (* now the main induction, clearing the trivial cases first *)\n  induction p; destruct q; try (split; discriminate);\n  simpl; remember (Pos.land p q) as pnq; destruct pnq; simpl;\n  specialize (IHp q); rewrite <-Heqpnq in IHp; simpl in IHp;\n  unfold \"<=\", \"?=\", \"?=\"%positive in *; simpl; auto.\n  (* the final case *)\n  rewrite Pos.compare_cont_spec in *; destruct (p0 ?= p)%positive; simpl; auto.\nQed.\n\nLemma lor_bounds:\n  forall a b,\n  0 <= a ->\n  0 <= b ->\n  a <= Z.lor a b <= a + b.\nProof.\n  intros a b a_bound b_bound.\n  (* clears the easy cases *)\n  destruct a as [|p|p], b as [|q|q]; simpl; try omega;\n  assert (Z.neg p < 0) as np_is_neg by apply Zlt_neg_0;\n  assert (Z.neg q < 0) as nq_is_neg by apply Zlt_neg_0; try omega.\n  clear a_bound b_bound np_is_neg nq_is_neg; generalize q; clear q.\n  (* comparison lemmas *)\n  assert (forall c, Pos.switch_Eq Eq c = c) as switch_eq_eq by\n    (destruct c; auto).\n  assert (forall p' c, Pos.compare_cont p' p' c = c) as p_p_keeps by\n    (induction p'; simpl; auto).\n  assert (forall p' c, Pos.compare_cont p' (Pos.succ p') c = Lt) as p_lt_succ by\n    (induction p'; simpl; auto).\n  (* now the main induction *)\n  induction p; destruct q; simpl; try specialize IHp with (q := q);\n  (* cleans up the easy cases *)\n  try apply IHp; try omega;\n  unfold \"<=\", \"?=\", \"?=\"%positive in *; simpl; \n  repeat rewrite p_p_keeps; repeat rewrite p_lt_succ; \n  try (split; discriminate); split; try apply IHp.\n  (* now the two hardest inequalities remain *)\n  + repeat rewrite Pos.add_carry_spec in *; repeat rewrite Pos.compare_cont_spec in *;\n    repeat rewrite Pos.compare_succ_r in *.\n    remember (Pos.lor p q ?= p + q)%positive as c.\n    repeat rewrite switch_eq_eq in *; destruct c; simpl; try discriminate.\n    apply IHp.\n  + repeat rewrite Pos.compare_cont_spec in *.\n    remember (p ?= Pos.lor p q)%positive as c.\n    repeat rewrite switch_eq_eq in *; destruct c; simpl; try discriminate.\n    apply IHp.\nQed.\n\nLemma lor_acc_lo_bits_bounds:\n  forall acc acc_lo acc_hi a n,\n  0 <= acc_lo ->\n  acc_lo <= acc_hi ->\n  acc_lo <= acc <= acc_hi ->\n  0 <= n < 8 ->\n  Z.shiftl acc_lo n <=\n  Z.lor (Z.shiftl acc n) (_get_lo_bits a n) <\n  (Z.shiftl acc_hi n) + (Z.shiftl 1 n).\nProof.\n  (* intros *)\n  intros acc acc_lo acc_hi a n.\n  intros acc_lo_bound acc_hi_bounds acc_bounds n_bounds.\n  (* bounds _get_lo_bits *)\n  assert (0 <= _get_lo_bits a n <= Z.shiftl 1 n - 1) as get_lo_bits_bounds.\n  {\n    unfold _get_lo_bits.\n    rewrite Z.land_comm.\n    apply land_bounds.\n    + rewrite Z.shiftl_1_l.\n      cut (0 < 2 ^ n). omega.\n      apply Z.pow_pos_nonneg; omega.\n    + apply N2Z.is_nonneg.\n  }\n  (* bounds the logical OR *)\n  assert (Z.shiftl acc n <=\n          Z.lor (Z.shiftl acc n) (_get_lo_bits a n) <=\n          Z.shiftl acc n + _get_lo_bits a n) as acc_lor_lo_bounds.\n  {\n    apply lor_bounds.\n    + rewrite Z.shiftl_mul_pow2, <-Zmult_0_r with (n := 0) by omega.\n      apply Zmult_le_compat; try omega.\n      apply Z.pow_nonneg; omega.\n    + omega.\n  }\n  (* bounds the shifted accumulator *)\n  assert (0 <= 2^n) as two_to_n_nonneg by (apply Z.pow_nonneg; omega).\n  assert (Z.shiftl acc_lo n <= Z.shiftl acc n <= Z.shiftl acc_hi n) as shifted_acc_bounds.\n  {\n    repeat rewrite Z.shiftl_mul_pow2 by omega.\n    split; apply Zmult_le_compat; omega.\n  }\n  (* finally omega has all the info it needs *)\n  omega.\nQed.\n\n\n(** Unicode encoding/decoding theorems **)\n\nInductive is_valid_unicode: list Z -> Prop :=\n  | ivu_empty: is_valid_unicode nil\n  | ivu_cons: \n      forall c l, (0 <= c < U+\"D800\" \\/ U+\"DFFF\" < c <= U+\"10FFFF\") ->\n      is_valid_unicode l -> is_valid_unicode (c :: l).\n\nLemma valid_cp_is_encoded:\n  forall a, (0 <= a < U+\"D800\" \\/ U+\"DFFF\" < a <= U+\"10FFFF\") <->\n  exists s, _encode_codepoint a = Some s.\nProof.\n  assert (forall t:string, exists s, Some t = Some s) as ex_eq by (intros; exists t; auto).\n  Ltac oor_tactic := unfold \"U+\" in *; simpl in *; split; [intros; omega | intros [s Habs]; discriminate].\n  Ltac ir_tactic := unfold \"U+\" in *; simpl in *; split; [intros | intros; omega].\n  intros a; unfold _encode_codepoint.\n  destruct (Z_lt_dec a 0). oor_tactic.\n  destruct (Z_le_dec a U+\"7F\"). ir_tactic; apply ex_eq.\n  destruct (Z_le_dec a U+\"7FF\"). ir_tactic; apply ex_eq.\n  destruct (Z_le_dec a U+\"D7FF\"). ir_tactic; apply ex_eq.\n  destruct (Z_le_dec a U+\"DFFF\"). oor_tactic.\n  destruct (Z_le_dec a U+\"FFFF\"). ir_tactic; apply ex_eq.\n  destruct (Z_le_dec a U+\"10FFFF\"). ir_tactic; apply ex_eq.\n  oor_tactic.\nQed.\n\nTheorem valid_unicode_is_encoded:\n  forall l, is_valid_unicode l <-> exists s, utf8_encode l = Some s.\nProof.\n  induction l.\n  + simpl; split; intros; [exists \"\"; auto | apply ivu_empty].\n  + unfold utf8_encode; fold utf8_encode; split.\n    - intros ivu_a_l; inversion ivu_a_l as [|a' l' a_bounds ivu_l].\n      rewrite IHl in ivu_l; destruct ivu_l as [s' l_enc_eq].\n      rewrite valid_cp_is_encoded in a_bounds; destruct a_bounds as [s'' a_enc_eq].\n      rewrite l_enc_eq, a_enc_eq; exists (s'' ++ s'); auto.\n    - remember (_encode_codepoint a) as ecp_a.\n      destruct ecp_a, (utf8_encode l); try (intros [s' Habs]; discriminate).\n      intros _; apply ivu_cons.\n      * rewrite valid_cp_is_encoded, <-Heqecp_a; exists s; auto.\n      * rewrite IHl; exists s0; auto.\nQed.\n\nLemma aux_decode_higher_phase_non_empty:\n  forall s acc n bound,\n  _utf8_decode_aux s acc (S n) bound <> Some [].\nProof.\n  intros s acc n bound.\n  generalize s acc; clear s acc.\n  induction n.\n  + destruct s.\n    - intros; case acc; discriminate.\n    - unfold _utf8_decode_aux; fold _utf8_decode_aux; intros.\n      remember (Z.lor (Z.shiftl acc 6) (_get_lo_bits a 6)) as cp.\n      destruct (_utf8_decode_aux s 0 0 0), (Z_ge_dec cp bound),\n               (Z_le_dec cp U+(\"D7FF\")), (Z_le_dec cp U+(\"DFFF\")),\n               acc, a;\n      destruct b5, b6; discriminate.\n  + destruct s.\n    - intros; case acc; discriminate.\n    - unfold _utf8_decode_aux; fold _utf8_decode_aux; intros.\n      destruct acc, a; destruct b5, b6; try discriminate; apply IHn.\nQed.\n\nLemma encode_codepoint_non_empty:\n  forall cp, _encode_codepoint cp <> Some \"\".\nProof.\n  intros; unfold _encode_codepoint.\n  destruct (Z_lt_dec cp 0). discriminate.\n  destruct (Z_le_dec cp U+\"7F\"). discriminate.\n  destruct (Z_le_dec cp U+\"7FF\"). discriminate.\n  destruct (Z_le_dec cp U+\"D7FF\"). discriminate.\n  destruct (Z_le_dec cp U+\"DFFF\"). discriminate.\n  destruct (Z_le_dec cp U+\"FFFF\"). discriminate.\n  destruct (Z_le_dec cp U+\"10FFFF\"). discriminate.\n  discriminate.\nQed.\n\nLemma empty_encodes_empty:\n  forall l, utf8_encode l = Some \"\" -> l = [].\nProof.\n  destruct l as [|cp l]; unfold utf8_encode; fold utf8_encode.\n  + auto.\n  + remember (_encode_codepoint cp) as enc_cp.\n    destruct (utf8_encode l), enc_cp as [s'|]; try discriminate.\n    destruct s'.\n    - assert (_encode_codepoint cp <> Some \"\") as enc_cp_ne by apply encode_codepoint_non_empty.\n      rewrite Heqenc_cp in enc_cp_ne; exfalso; apply enc_cp_ne; auto.\n    - discriminate.\nQed.\n\nLemma empty_decodes_empty:\n  forall s, utf8_decode s = Some [] -> s = \"\".\nProof.\n  destruct s; unfold utf8_decode.\n  + auto.\n  + simpl; destruct (_utf8_decode_aux s 0 0 0), a; destruct b2, b3, b4, b5, b6;\n    try discriminate; intros Habs; exfalso;\n    generalize Habs; apply aux_decode_higher_phase_non_empty.\nQed.\n\nLemma dec_lemma_1:\n  forall cp s s' l,\n  0 <= cp <= U+\"7F\" ->\n  utf8_decode s' = Some l ->\n  Some (String (ascii_of_N (Z.to_N cp)) \"\" ++ s') = Some s ->\n  utf8_decode s = Some (cp :: l).\nProof.\n  intros cp s s' l cp_bounds s'_dec_eq s_eq'; unfold \"U+\" in *; simpl in *.\n  inversion s_eq' as [s_eq]; unfold utf8_decode in *; unfold _utf8_decode_aux; fold _utf8_decode_aux.\n  assert (cp = Z.of_N (N_of_ascii (ascii_of_N (Z.to_N cp)))) as cp_eq.\n  {\n    rewrite N_ascii_embedding by (apply N2Z.inj_lt; rewrite Z2N.id; simpl; omega).\n    rewrite Z2N.id; omega.\n  }\n  rewrite s'_dec_eq.\n  destruct (ascii_of_N (Z.to_N cp)); destruct b, b0, b1, b2, b3, b4, b5, b6;\n  simpl in *; try omega; rewrite cp_eq; auto.\nQed.\n\nLemma dec_lemma_2:\n  forall cp s s' l,\n  U+\"7F\" < cp <= U+\"7FF\" ->\n  utf8_decode s' = Some l ->\n  Some (String (_aux_enc_cp_byte cp 10 6 U+(\"C0\"))\n               (String (_aux_enc_cp_byte cp 5 0 U+(\"80\")) \"\") ++ s') = Some s ->\n  utf8_decode s = Some (cp :: l).\nProof.\nAdmitted. (** FIXME **)\n\nLemma dec_lemma_3:\n  forall cp s s' l,\n  (U+\"7FF\" < cp <= U+\"D7FF\") \\/ (U+\"DFFF\" < cp <= U+\"FFFF\") ->\n  utf8_decode s' = Some l ->\n  Some (String (_aux_enc_cp_byte cp 15 12 U+(\"E0\"))\n               (String (_aux_enc_cp_byte cp 11 6 U+(\"80\"))\n                       (String (_aux_enc_cp_byte cp 5 0 U+(\"80\")) \"\")) ++ s') = Some s ->\n  utf8_decode s = Some (cp :: l).\nProof.\nAdmitted. (** FIXME **)\n\nLemma dec_lemma_4:\n  forall cp s s' l,\n  U+\"FFFF\" < cp <= U+\"10FFFF\" ->\n  utf8_decode s' = Some l ->\n  Some (String (_aux_enc_cp_byte cp 20 18 U+(\"F0\"))\n               (String (_aux_enc_cp_byte cp 17 12 U+(\"80\"))\n                       (String (_aux_enc_cp_byte cp 11 6 U+(\"80\"))\n                               (String (_aux_enc_cp_byte cp 5 0 U+(\"80\")) \"\"))) ++ s') = Some s ->\n  utf8_decode s = Some (cp :: l).\nProof.\nAdmitted. (** FIXME **)  \n\nLemma enc_lemma_1:\n  forall a s' cp l,\n  Z.of_N (N_of_ascii a) < U+\"80\" ->\n  (forall s'', utf8_encode l = Some s'' <-> _utf8_decode_aux s'' 0 0 0 = Some l) ->\n  _utf8_decode_aux (String a s') 0 0 0 = Some (cp :: l) -> \n  utf8_encode (cp :: l) = Some (String a s').\nProof.\n  intros a s' cp l a_bounds s'_dec_eq s_dec_eq.\n  unfold \"U+\" in *; simpl in *.\n  remember (_utf8_decode_aux s' 0 0 0) as dec_s'.\n  destruct a; destruct b, b0, b1, b2, b3, b4, b5, b6;\n  simpl in *; try omega;\n  destruct dec_s'; try discriminate;\n  injection s_dec_eq; intros l_eq cp_eq; rewrite <-cp_eq; simpl;\n  assert (utf8_encode l = Some s') as l_enc_eq by (apply s'_dec_eq; rewrite <-l_eq, Heqdec_s'; auto);\n  rewrite l_enc_eq; auto.\nQed.\n\nLemma enc_fail_lemma:\n  forall a s',\n  (U+\"80\" <= Z.of_N (N_of_ascii a) < U+\"C0\") \\/ (U+\"F8\" <= Z.of_N (N_of_ascii a))->\n  _utf8_decode_aux (String a s') 0 0 0 = None.\nProof.\n  intros a s' a_bounds; unfold \"U+\" in *; simpl in *.\n  destruct a; destruct b, b0, b1, b2, b3, b4, b5, b6;\n  simpl in *; auto; omega.\nQed.\n\nLemma enc_lemma_2:\n  forall a s' cp l,\n  U+\"C0\" <= Z.of_N (N_of_ascii a) < U+\"E0\" ->\n  (forall s'', utf8_encode l = Some s'' <-> _utf8_decode_aux s'' 0 0 0 = Some l) ->\n  _utf8_decode_aux (String a s') 0 0 0 = Some (cp :: l) -> \n  utf8_encode (cp :: l) = Some (String a s').\nProof.\nAdmitted. (** FIXME **)\n\nLemma enc_lemma_3:\n  forall a s' cp l,\n  U+\"E0\" <= Z.of_N (N_of_ascii a) < U+\"F0\" ->\n  (forall s'', utf8_encode l = Some s'' <-> _utf8_decode_aux s'' 0 0 0 = Some l) ->\n  _utf8_decode_aux (String a s') 0 0 0 = Some (cp :: l) -> \n  utf8_encode (cp :: l) = Some (String a s').\nProof.\nAdmitted. (** FIXME **)\n\nLemma enc_lemma_4:\n  forall a s' cp l,\n  U+\"F0\" <= Z.of_N (N_of_ascii a) < U+\"F8\" ->\n  (forall s'', utf8_encode l = Some s'' <-> _utf8_decode_aux s'' 0 0 0 = Some l) ->\n  _utf8_decode_aux (String a s') 0 0 0 = Some (cp :: l) -> \n  utf8_encode (cp :: l) = Some (String a s').\nProof.\nAdmitted. (** FIXME **)\n\nTheorem decoded_iff_encoded:\n  forall l s, utf8_encode l = Some s <-> utf8_decode s = Some l.\nProof.\n  induction l as [|cp l].\n  + intros; simpl; split; unfold utf8_decode.\n    - intros Heq; injection Heq; intros Heq'; rewrite <-Heq'; auto.\n    - destruct s.\n      * auto.\n      * intros dec_eq; rewrite empty_decodes_empty with (s := String a s); auto.\n  + intros; split.\n    - unfold utf8_encode; fold utf8_encode.\n      destruct (utf8_encode l) as [s'|]; try (destruct (_encode_codepoint cp); discriminate).\n      unfold _encode_codepoint.\n      destruct (Z_lt_dec cp 0).\n        discriminate.\n      destruct (Z_le_dec cp U+\"7F\").\n        apply dec_lemma_1; try omega; apply IHl; auto.\n      destruct (Z_le_dec cp U+\"7FF\").\n        apply dec_lemma_2; try omega; apply IHl; auto.\n      destruct (Z_le_dec cp U+\"D7FF\").\n        apply dec_lemma_3; try omega; apply IHl; auto.\n      destruct (Z_le_dec cp U+\"DFFF\").\n        discriminate.\n      destruct (Z_le_dec cp U+\"FFFF\").\n        apply dec_lemma_3; try omega; apply IHl; auto.\n      destruct (Z_le_dec cp U+\"10FFFF\").\n        apply dec_lemma_4; try omega; apply IHl; auto.\n        discriminate.\n   - unfold utf8_decode in *.\n     destruct s as [|a s'].\n       simpl; discriminate.\n     destruct (Z_lt_dec (Z.of_N (N_of_ascii a)) U+\"80\").\n       apply enc_lemma_1; auto.\n     destruct (Z_lt_dec (Z.of_N (N_of_ascii a)) U+\"C0\").\n       rewrite enc_fail_lemma by omega; discriminate.\n     destruct (Z_lt_dec (Z.of_N (N_of_ascii a)) U+\"E0\").\n       apply enc_lemma_2; auto; try omega.\n     destruct (Z_lt_dec (Z.of_N (N_of_ascii a)) U+\"F0\").\n       apply enc_lemma_3; auto; try omega.\n     destruct (Z_lt_dec (Z.of_N (N_of_ascii a)) U+\"F8\").\n       apply enc_lemma_4; auto; try omega.\n       rewrite enc_fail_lemma by omega; discriminate.\nQed.", "meta": {"author": "mchouza", "repo": "json-coq", "sha": "5169bafb42e8cdf3085d1e199b01cdd6a3a17236", "save_path": "github-repos/coq/mchouza-json-coq", "path": "github-repos/coq/mchouza-json-coq/json-coq-5169bafb42e8cdf3085d1e199b01cdd6a3a17236/utf8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7010628233591365}}
{"text": "Require Import CT.Algebra.Magma.\nRequire Import CT.Algebra.Monoid.\nRequire Import CT.Category.\n\n(** * Mon: The category of monoids. *)\nProgram Definition Mon (T : Type) : Category :=\n  {| ob := @Monoid T;\n     mor := MonoidHomomorphism;\n     comp := fun _ _ _ => monoid_hom_composition;\n     id := fun _ => monoid_hom_id;\n     assoc := fun _ _ _ _ => monoid_hom_composition_assoc\n  |}.\nNext Obligation.\nProof.\n  symmetry.\n  apply monoid_hom_composition_assoc.\nQed.\nNext Obligation.\nProof.\n  apply monoid_hom_eq.\n  apply magma_hom_eq.\n  reflexivity.\nQed.\nNext Obligation.\nProof.\n  apply monoid_hom_eq.\n  apply magma_hom_eq.\n  reflexivity.\nQed.", "meta": {"author": "relrod", "repo": "ct", "sha": "abd8b0067e219ee4867f7136bdf1b35885224cb4", "save_path": "github-repos/coq/relrod-ct", "path": "github-repos/coq/relrod-ct/ct-abd8b0067e219ee4867f7136bdf1b35885224cb4/CT/Instance/Algebra/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7010628161024555}}
{"text": "(* Exercise coq_list_05 *)\n\n(* Those are the definitions from the previous exercise: *)\n\nInductive natlist : Set :=\n  | nil : natlist\n  | cons : nat -> natlist -> natlist.\n\nFixpoint append (l m : natlist) {struct l} : natlist :=\n  match l with\n  | nil => m\n  | cons x xs => cons x (append xs m)\n  end.\n\n(* Now define a function 'reverse' that given a list returns\n   the list with the elements in the reversed order. *)\nFixpoint reverse (l : natlist) : natlist :=\n  match l with \n  | nil => nil\n  | cons s rem => append (reverse rem) (cons s nil)\n  end.\n\nLemma reverse_nil : reverse nil = nil.\n\nProof.\n  unfold reverse.\n  reflexivity.\n\nQed.\n\nLemma reverse_one_elt : forall a, \n  reverse (cons a nil) = cons a nil.\n  \nProof.\n  intros.\n  unfold reverse.\n  simpl.\nreflexivity.\nQed.\n\nLemma reverse_two_elts : forall a b,\n  reverse (cons a (cons b nil)) = cons b (cons a nil).\n  \nProof.\n  intros.\n  simpl.\n  reflexivity.\nQed.", "meta": {"author": "adityachandla", "repo": "PCA_coq_files", "sha": "eceb6ca21074dfe13eb0f28a9b28be440a4ee17d", "save_path": "github-repos/coq/adityachandla-PCA_coq_files", "path": "github-repos/coq/adityachandla-PCA_coq_files/PCA_coq_files-eceb6ca21074dfe13eb0f28a9b28be440a4ee17d/coq_list_05.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7010249604359207}}
{"text": "From LF Require Export D_Polymorphism.\n\nTheorem silly1 : forall (n m : nat),\n    n = m -> n = m.\nProof.\n    intros n m eq. apply eq.\nQed.\n\nTheorem silly2 : forall (n m o p : nat),\n    n = m ->\n        (n = m -> [n;o] = [m;p]) ->\n            [n;o] = [m;p].\nProof.\n    intros n m o p eq_1 eq_2.\n    apply eq_2. apply eq_1.\nQed.\n\nTheorem silly_ex : forall p,\n    (forall n, even n = true -> even (S n) = false) ->\n        (forall n, even n = false -> odd n = true) ->\n            even p = true ->\n                odd (S p) = true.\nProof.\n    intros p eq_1 eq_2 eq_3. apply eq_2. apply eq_1. apply eq_3.\nQed.\n\nTheorem silly3 : forall (n m : nat),\n    n = m -> m = n.\nProof.\n    intros n m H. symmetry. apply H.\nQed.\n\nSearch rev.\n\nTheorem rev_exercise1 : forall (l l' : list nat),\n    l = rev l' -> l' = rev l.\nProof.\n    intros l l' H. rewrite -> H. symmetry. apply rev_involutive.\nQed.\n\n(*\n    apply_rewrite\n\n    The apply tactic works similarly to\n    a rewrite followed by reflexivity\n    or another resolving tactic. It is\n    applicable whenever the current\n    problem space is identical to an\n    existing proven Theorem.\n\n    Whenever apply can be used, so can\n    rewrite.\n*)\n\nExample trans_eq_example : forall (a b c d e f : nat),\n    [a;b] = [c;d] ->\n        [c;d] = [e;f] -> \n            [a;b] = [e;f].\nProof.\n    intros a b c d e f eq_1 eq_2.\n    rewrite -> eq_1. rewrite -> eq_2.\n    reflexivity.\nQed.\n\nExample trans_eq : forall (X : Type) (n m o : X),\n    n = m -> m = o -> n = o.\nProof.\n    intros X n m o eq_1 eq_2. rewrite -> eq_1. rewrite -> eq_2.\n    reflexivity.\nQed.\n\nExample trans_eq_example' : forall (a b c d e f : nat),\n    [a;b] = [c;d] ->\n        [c;d] = [e;f] -> \n            [a;b] = [e;f].\nProof.\n    intros a b c d e f eq_1 eq_2. \n    apply trans_eq with (m := [c;d]).\n    apply eq_1. apply eq_2.\nQed.\n\nExample trans_eq_example'' : forall (a b c d e f : nat),\n    [a;b] = [c;d] ->\n        [c;d] = [e;f] -> \n            [a;b] = [e;f].\nProof.\n    intros a b c d e f eq_1 eq_2.\n    transitivity [c;d].\n    apply eq_1. apply eq_2.\nQed.\n\nExample trans_eq_exercise : forall (n m o p : nat),\n    m = (minustwo o) -> \n        (n + p) = m ->\n            (n + p) = (minustwo o).\nProof.\n    intros n m o p H1 H2.\n    transitivity (minustwo o).\n    - (* n + p = minustwo o *) \n        rewrite <- H1. apply H2.\n    - (* minustwo o = minustwo o *)\n        reflexivity.\nQed. \n\nTheorem S_injective : forall (n m : nat),\n    S n = S m -> n = m.\nProof.\n    intros n m H1.\n    assert (H2 : n = pred (S n)).\n    {\n        reflexivity.\n    }\n    rewrite -> H2. rewrite -> H1.\n    simpl. reflexivity.\nQed.\n\nTheorem S_injective' : forall (n m : nat),\n    S n = S m -> n = m.\nProof.\n    intros n m H.\n    injection H as Hnm. apply Hnm.\nQed.\n\nTheorem injection_ex1 : forall (n m o : nat),\n    [n;m] = [o;o] -> n = m.\nProof.\n    intros n m o H.\n    injection H as H1 H2.\n    rewrite -> H1, H2. reflexivity.\nQed.\n\nExample injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = z :: j ->\n        j = z :: l ->\n            x = y.\nProof.\n    intros X x y z l j H1 H2.\n    injection H1 as H3 H4.\n    symmetry in H4.\n    rewrite -> H4 in H2.\n    injection H2 as H5.\n    rewrite -> H3, H5.\n    reflexivity.\nQed.\n\nTheorem discriminate_ex1 : forall (n m : nat),\n    false = true -> n = m.\nProof.\n    intros n m contra. discriminate contra.\nQed.\n\nTheorem discriminate_ex2 : forall (n : nat),\n    S n = O -> 2 + 2 = 5.\nProof.\n    intros n contra. discriminate contra.\nQed.\n\nTheorem discriminate_tf_tt :\n    false = true -> true = true.\nProof.\n    intros contra. discriminate contra.\nQed.\n\nExample discriminate_ex3 : forall (X : Type) (x y z : X) (l j : list X),\n    x :: y :: l = [] -> x = z.\nProof.\n    intros X x y z l j contra. discriminate contra.\nQed.\n\nTheorem eqb_0_l : forall (n : nat),\n    0 =? n = true -> n = 0.\nProof.\n    intros n. destruct n as [| n' ] eqn : E.\n    - (* n = 0 *)\n        intros H. reflexivity.\n    - (* n = S n' *)\n        simpl. intros H.\n        discriminate H.\nQed.\n\nTheorem f_equal : forall (A B : Type) (f : A -> B) (x y : A),\n    x = y -> f x = f y.\nProof.\n    intros A B f x y eq. rewrite -> eq.\n    reflexivity.\nQed.\n\nTheorem eq_implies_succ_equal : forall (n m : nat),\n    n = m -> S n = S m.\nProof.\n    intros n m H. apply f_equal. apply H.\nQed.\n\nTheorem eq_implies_succ_equal' : forall (n m : nat),\n    n = m -> S n = S m.\nProof.\n    intros n m H. f_equal. apply H.\nQed.\n\nTheorem silly4 : forall (n m p q : nat),\n    (n = m -> p = q) ->\n        m = n ->\n            q = p.\nProof.\n    intros n m p q H1 H2.\n    symmetry in H2. apply H1 in H2. symmetry in H2.\n    apply H2.\nQed.\n\nTheorem double_injective_FAILED : forall (n m : nat),\n    double n = double m -> n = m.\nProof.\n    intros n m. induction n as [| n' IHn' ].\n    - (* n = 0 *)\n        simpl. intros eq. destruct m as [| m'] eqn : E.\n        -- reflexivity.\n        -- discriminate eq.\n    - (* n = S n' *)\n        intros eq. destruct m as [| m'] eqn : E.\n        -- discriminate eq.\n        -- apply f_equal.\nAbort.\n\nTheorem double_injective : forall (n m : nat),\n    double n = double m -> n = m.\nProof.\n    intros n. induction n as [| n' IHn' ].\n    - (* n = 0 *)\n        simpl. intros m eq. destruct m as [| m'] eqn : E.\n        -- reflexivity.\n        -- discriminate eq.\n    - (* n = S n' *)\n        intros m eq. destruct m as [| m'] eqn : E.\n        -- discriminate eq.\n        -- f_equal. apply IHn'. simpl in eq.\n           injection eq as goal. apply goal.\nQed.\n\nTheorem eqb_true : forall (n m : nat),\n    n =? m = true -> n = m.\nProof.\n    intros n. induction n as [| n' IHn' ].\n    - (* n = 0 *)\n        intros m H. destruct m as [| m' ] eqn : E.\n        -- reflexivity.\n        -- discriminate H.\n    - (* n = S n' *)\n        intros m H. destruct m as [| m' ] eqn : E.\n        -- discriminate H.\n        -- f_equal. apply IHn'. simpl in H. apply H.\nQed.\n\n(*\n    eqb_true_informal\n\n    If (eqb n m) = true, then n = m.\n\n    We will perform induction on n,\n    with an inductive hypothesis:\n        If (eqb S n m) = true, then\n        S n = m.\n\n    For the base case, we have n = 0.\n    So, if (eqb 0 m) = true, then 0 = m.\n    We know that, as a natural number,\n    m is of the form 0 or S m' for some\n    m' in the natural numbers. For the\n    case where m = 0, (eqb 0 0) = true\n    does imply that 0 = 0, so this case\n    is handled.\n    For the case where m = S m', we have\n    the hypothesis (eqb 0 S m') = true,\n    which is clearly a contradiction.\n    By the principle of explosion, this\n    case is handled.\n\n    For the inductive case, we have \n    n = S n' for some n' in the natural\n    numbers. So if (eqb S n' m) = true,\n    then S n' = m. We know that, as a \n    natural number, m is of the form 0 \n    or S m' for some m' in the natural \n    numbers. For the case where m = 0,\n    we have the hypothesis \n    (eqb S n' 0) = true, which is\n    clearly a contradiction. By the\n    principle of explosion, this case is\n    handled.\n    For the case where m = S m', we have\n    the hypothesis \n    (eqb S n' S m') = true. By the\n    property of injection, this can be\n    simplified to (eqb n' m') = true.\n    So, (eqb n' m') implies that\n    n' = m', as injectivity can also be\n    applied to S n' = S m'.\n*)\n        \n", "meta": {"author": "CharlesAverill", "repo": "SoftwareFoundationsExercises", "sha": "577a0ee051c393abc17bb0a5167139cb38366df4", "save_path": "github-repos/coq/CharlesAverill-SoftwareFoundationsExercises", "path": "github-repos/coq/CharlesAverill-SoftwareFoundationsExercises/SoftwareFoundationsExercises-577a0ee051c393abc17bb0a5167139cb38366df4/E_Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7010249420781941}}
{"text": "Require Import Arith.\n\nDefinition Nat : Type :=\n  forall A : Type, (A -> A) -> (A -> A).\n\nDefinition NatPlus(n m : Nat) : Nat\n  := (fun (A : Type) (s : A -> A) (z : A) =>\n         n A s (m A s z)).\n\nDefinition nat2Nat : nat -> Nat := nat_iter.\n\nDefinition Nat2nat(n : Nat) : nat := n _ S 0.\n\nLemma NatPlus_plus :\n  forall n m, Nat2nat (NatPlus (nat2Nat n) (nat2Nat m)) = n + m.\nProof.\n  intros.\n  induction n.\n  simpl.\n  induction m.\n  compute.\n  ring.\n  rewrite <- IHm at 2.\n  compute.\n  reflexivity.\n  rewrite (plus_Sn_m n m).\n  rewrite <- IHn.\n  compute.\n  reflexivity.\nQed.", "meta": {"author": "KeenS", "repo": "coqex", "sha": "325a48569d54a8925e41f757cbb4c3c74443c5a3", "save_path": "github-repos/coq/KeenS-coqex", "path": "github-repos/coq/KeenS-coqex/coqex-325a48569d54a8925e41f757cbb4c3c74443c5a3/4/18.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.7008697196076015}}
{"text": "From mathcomp Require Import ssreflect.\nRequire Import Coq.Sets.Ensembles.\n\nInductive IntersectionT (U : Type) (T : Type) (A : T -> Ensemble U) : Ensemble U :=\n  | IntersectionT_intro : forall (x : U), (forall (t : T), In U (A t) x) -> In U (IntersectionT U T A) x.\n\nInductive UnionT (U : Type) (T : Type) (A : T -> Ensemble U) : Ensemble U :=\n  | UnionT_intro : forall (x : U) (t : T), In U (A t) x -> In U (UnionT U T A) x.\n", "meta": {"author": "itleigns", "repo": "CoqLibrary", "sha": "de210b755ab010e835e3777b9b47351972bbb577", "save_path": "github-repos/coq/itleigns-CoqLibrary", "path": "github-repos/coq/itleigns-CoqLibrary/CoqLibrary-de210b755ab010e835e3777b9b47351972bbb577/LibraryExtension/EnsemblesExtension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7008697153506106}}
{"text": "Require Import MathClasses.interfaces.abstract_algebra.\n\nInstance bool_eq: Equiv bool := eq.\nInstance bool_bottom: Bottom bool := false.\nInstance bool_top: Top bool := true.\nInstance bool_join: Join bool := orb.\nInstance bool_meet: Meet bool := andb.\n\nInstance: BoundedJoinSemiLattice bool.\nProof.\n  repeat (split; try apply _); repeat intro.\n     apply Bool.orb_assoc.\n    apply Bool.orb_false_r.\n   apply Bool.orb_comm.\n  apply Bool.orb_diag.\nQed.\n\nInstance: MeetSemiLattice bool.\nProof.\n  repeat (split; try apply _); repeat intro.\n    apply Bool.andb_assoc.\n   apply Bool.andb_comm.\n  apply Bool.andb_diag.\nQed.\n\nInstance: DistributiveLattice bool.\nProof.\n  repeat (split; try apply _); repeat intro.\n    apply Bool.absoption_orb.\n   apply Bool.absoption_andb.\n  apply Bool.orb_andb_distrib_r.\nQed.\n\n(* We don't have a boolean algebra class yet *)", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/math-classes/implementations/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.7008697144883772}}
{"text": "Require Import List.\n\n\nModule Type DecidableEqLe.\n\n  Parameter A : Type.\n  Parameter default : A.\n\n  Parameter le : A -> A -> Prop.\n  Infix \"<=\" := le.\n  Parameter le_total : forall a b, a <= b \\/ b <= a.\n  Parameter leb : A -> A -> bool.\n  Infix \"<=?\" := leb (at level 68).\n  Parameter leb_le : forall a b, a <=? b = true <-> a <= b.\n  Parameter eqb : A -> A -> bool.\n  Infix \"=?\" := eqb (at level 68).\n  Parameter eqb_eq : forall a b, a =? b = true <-> a = b.\n\nEnd DecidableEqLe.\n\n\nModule InsertionSort (M : DecidableEqLe).\n\n  Import M.\n\n  Lemma neqb_neq : forall a b, a =? b = false <-> a <> b.\n  Proof.\n    intros ; split ; intro.\n    - intro.\n      apply eqb_eq in H0.\n      now rewrite H0 in H.\n    - destruct (a =? b) as []eqn:?.\n      now apply eqb_eq in Heqb0.\n      reflexivity.\n  Qed.\n\n  Lemma eqb_refl : forall a, a =? a = true.\n  Proof.\n    intro.\n    now apply eqb_eq.\n  Qed.\n\n  Lemma eqb_sym : forall a b, a =? b = b =? a.\n  Proof.\n    intros.\n    destruct (b =? a) as []eqn:?.\n    - apply eqb_eq in Heqb0.\n      subst.\n      now rewrite eqb_refl.\n    - apply neqb_neq in Heqb0.\n      apply neqb_neq.\n      intro.\n      now apply eq_sym in H.\n  Qed.\n\n\n  Fixpoint insert l n :=\n    match l with\n    | nil => n::nil\n    | m::t => if n <=? m then n::l else m::(insert t n)\n    end.\n\n  Fixpoint sort l :=\n    match l with\n    | nil => nil\n    | n::t => insert (sort t) n\n    end.\n\n  Fixpoint occ l n :=\n    match l with\n    | nil => 0\n    | m::t => if m =? n then 1 + occ t n else occ t n\n    end.\n\n\n  Definition is_perm l l' := forall a, occ l a = occ l' a.\n\n  Definition is_sorted l := forall n, S n < length l -> nth n l default <= nth (S n) l default.\n\n  Lemma insert_occ : forall l a, occ (insert l a) a = S (occ l a).\n  Proof.\n    induction l.\n    - intro a.\n      simpl.\n      now rewrite eqb_refl.\n\n    - intro b.\n      simpl.\n      destruct (leb b a) ; simpl.\n      + destruct (a =? b) ; rewrite eqb_refl ; reflexivity.\n      + destruct (a =? b) ; now rewrite IHl.\n  Qed.\n\n  Theorem insert_neq_occ : forall l a b, a <> b -> occ (insert l b) a = occ l a.\n  Proof.\n    intros.\n    induction l ; simpl.\n    - apply neqb_neq in H.\n      rewrite eqb_sym.\n      now rewrite H.\n\n    - apply neqb_neq in H.\n      rewrite eqb_sym in H.\n      destruct (a0 =? a) as []eqn:? ; destruct (leb b a0) ; simpl ; rewrite Heqb0.\n      + now rewrite H.\n      + now rewrite IHl.\n      + now rewrite H.\n      + assumption.\n  Qed.\n\n  Lemma insert_length : forall l a, length (insert l a) = S (length l).\n  Proof.\n    induction l.\n    - easy.\n\n    - intro a0.\n      simpl.\n      destruct (a0 <=? a).\n      + easy.\n      + simpl.\n        now rewrite IHl.\n  Qed.\n\n\n  Theorem sort_correct : forall l, is_perm (sort l) l.\n  Proof.\n    induction l.\n    - simpl.\n      unfold is_perm.\n      intro n.\n      simpl.\n      reflexivity.\n\n    - unfold is_perm.\n      intro b.\n      simpl.\n      destruct (a =? b) as []eqn:?.\n      + apply (eqb_eq) in Heqb0.\n        now rewrite Heqb0, insert_occ, IHl.\n      + apply (neqb_neq a b) in Heqb0.\n        rewrite insert_neq_occ.\n        apply IHl.\n        intro.\n        now apply eq_sym in H.\n  Qed.\n\n\n  Lemma insert_le : forall l n, exists m,\n    (nth m (insert l n) default = n)\n    /\\ (m <= length l)%nat\n    /\\ (m < length l -> n <= nth (S m) (insert l n) default)\n    /\\ (forall p, p < length l ->\n    (p < m -> \n      (nth p (insert l n) default = nth p l default)\n      /\\ (nth p (insert l n) default <= n))\n    /\\ ((m <= p)%nat -> nth (S p) (insert l n) default = nth p l default)).\n  Proof.\n    induction l.\n\n    - intro n.\n      now exists 0.\n\n    - intro n.\n      destruct (n <=? a) as []eqn:?.\n      + exists 0.\n        repeat split.\n        * simpl.\n          now rewrite Heqb.\n        * now rewrite (PeanoNat.Nat.le_0_l (length (a::l))).\n        * intros.\n          simpl.\n          rewrite Heqb.\n          simpl.\n          now apply leb_le in Heqb.\n        * easy.\n        * easy.\n        * intro.\n          simpl.\n          rewrite Heqb.\n          reflexivity.\n      + destruct (IHl n) as [m' IHl'].\n        exists (S m').\n        repeat split.\n        * simpl.\n          rewrite Heqb.\n          easy.\n        * destruct IHl' as [_ [H _]].\n          simpl.\n          now apply PeanoNat.Nat.succ_le_mono in H.\n        * intro.\n          simpl.\n          rewrite Heqb.\n          simpl.\n          destruct IHl' as [_ [_ [H' _]]].\n          now apply PeanoNat.Nat.succ_lt_mono, H' in H.\n        * simpl.\n          rewrite Heqb.\n          simpl.\n          destruct p.\n          reflexivity.\n          destruct IHl' as [_ [_ [H']]].\n          pose proof (H1 p) as H1'.\n          apply PeanoNat.Nat.succ_lt_mono, H1' in H.\n          destruct H as [H _].\n          apply PeanoNat.Nat.succ_lt_mono, H in H0.\n          now destruct H0 as [H0 _].\n        * simpl.\n          rewrite Heqb.\n          simpl.\n          destruct p.\n          destruct (le_total a n) as [Hle|Hle].\n          easy.\n          apply leb_le in Hle.\n          now rewrite Hle in Heqb.\n          destruct IHl' as [_ [_ [_ H']]].\n          apply PeanoNat.Nat.succ_lt_mono, (H' p) in H.\n          destruct H as [H _].\n          apply PeanoNat.Nat.succ_lt_mono, H in H0.\n          now destruct H0 as [_ H0].\n        * intro.\n          simpl.\n          rewrite Heqb.\n          simpl.\n          destruct p.\n          easy.\n          apply PeanoNat.Nat.succ_lt_mono in H.\n          apply PeanoNat.Nat.succ_le_mono in H0.\n          destruct (IHl') as [_ [_ [_ H1]]].\n          pose proof (H1 p) as H1.\n          apply H1 in H.\n          destruct H as [_ H].\n          now apply H in H0.\n  Qed.\n\n\n  Theorem sort_correct2 : forall l, is_sorted (sort l).\n  Proof.\n    induction l.\n\n    - simpl.\n      unfold is_sorted.\n      now intros.\n\n    - simpl.\n      unfold is_sorted.\n      intros.\n      destruct (insert_le (sort l) a) as [m Hinsert].\n      destruct Hinsert as [Ha_in [Hm_in [Hm_next Horder]]].\n      rewrite (insert_length (sort l) a) in H.\n      apply PeanoNat.Nat.succ_lt_mono in H as H'.\n      apply PeanoNat.Nat.succ_lt_mono in H.\n      destruct (PeanoNat.Nat.lt_trichotomy n m) as [H0|[H0|H0]].\n      + apply (Horder n) in H.\n        destruct H as [H _].\n        apply H in H0 as H1.\n        destruct H1 as [H1 _].\n        apply PeanoNat.Nat.le_succ_l in H0.\n        apply PeanoNat.Nat.le_lteq in H0.\n        destruct H0 as [H0|H0].\n        * apply (PeanoNat.Nat.lt_le_trans (S n) m (length (sort l))) in H0 as H2.\n          apply (Horder (S n)) in H2 as H3.\n          destruct H3 as [H3 _].\n          apply H3 in H0 as H4.\n          clear H3.\n          destruct H4 as [H4 _].\n          rewrite H4, H1.\n          now apply IHl.\n          assumption.\n        * rewrite H0, Ha_in.\n          assert (n < m).\n          unfold lt.\n          rewrite H0.\n          apply Peano.le_n.\n          now apply (Horder n) in H2.\n      + rewrite H0 in H, H'.\n        apply Hm_next in H.\n        now rewrite H0, Ha_in.\n      + apply (Horder n) in H.\n        destruct H as [_ H].\n        apply PeanoNat.Nat.lt_le_incl in H0 as H1.\n        apply H in H1.\n        apply PeanoNat.Nat.lt_le_pred in H0 as H2.\n        pose proof (PeanoNat.Nat.le_pred_l n) as H3.\n        apply (PeanoNat.Nat.le_lt_trans (PeanoNat.Nat.pred n) n (length (sort l))) in H3.\n        apply (Horder (PeanoNat.Nat.pred n)) in H3.\n        destruct H3 as [_ H3].\n        apply H3 in H2.\n        clear H3.\n        apply (PeanoNat.Nat.le_lt_trans 0 m n) in H0.\n        apply PeanoNat.Nat.lt_neq, PeanoNat.Nat.neq_sym in H0.\n        apply (PeanoNat.Nat.succ_pred n) in H0 as H3.\n        rewrite H3 in H2.\n        rewrite H1, H2.\n        rewrite <- H3 at 2.\n        apply IHl.\n        now rewrite H3.\n        now pose proof (PeanoNat.Nat.le_0_l m) as H3.\n        assumption.\n  Qed.\n\nEnd InsertionSort.\n\n\nModule NatDecidableEqLe <: DecidableEqLe.\n\n  Definition A := nat.\n  Definition le := Peano.le.\n  Definition le_total := PeanoNat.Nat.le_ge_cases.\n  Definition leb := PeanoNat.Nat.leb.\n  Definition leb_le := PeanoNat.Nat.leb_le.\n  Definition eqb := PeanoNat.Nat.eqb.\n  Definition eqb_eq := PeanoNat.Nat.eqb_eq.\n  Definition default := 0.\n\nEnd NatDecidableEqLe.\n\nModule NatInsertionSort := InsertionSort NatDecidableEqLe.\n", "meta": {"author": "esum", "repo": "CoqProofs", "sha": "706ee3489f78fd8c691378356b41594059d11c28", "save_path": "github-repos/coq/esum-CoqProofs", "path": "github-repos/coq/esum-CoqProofs/CoqProofs-706ee3489f78fd8c691378356b41594059d11c28/insertionSort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7008258193338761}}
{"text": "Require Import Coq.Arith.Compare_dec.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Program.Equality.\n\nOpaque lt_eq_lt_dec.\n\n(** Terms *)\nInductive Trm : Type :=\n| Trm_Unit : Trm\n| Trm_Var : nat -> Trm\n| Trm_Func : Trm -> Trm\n| Trm_App : Trm -> Trm -> Trm\n.\n\nNotation un := (Trm_Unit).\nNotation \"𝔳( n )\" := (Trm_Var n).\nNotation \"'λ' f\" := (Trm_Func f) (at level 0).\nNotation \"x · y\" := (Trm_App x y) (at level 50, y at next level, left associativity).\n\n(** Types *)\nInductive Typ  : Type :=\n| Typ_Unit : Typ\n| Typ_Func : Typ -> Typ -> Typ\n.\n\nNotation Un := (Typ_Unit).\nNotation \"A —≻ B\" := (Typ_Func A B) (at level 99, right associativity).\n\n(** A context is just a list of types.\nThe head of the list is the type of the variable 0. *)\nInductive Context :=\n| Emp : Context\n| Cons : Typ -> Context -> Context\n.\n\nNotation ε := Emp.\nNotation \"A ,, C\" := (Cons A C) (at level 100).\n\nReserved Notation \"Δ +++ Γ\" (at level 60, right associativity).\n\nFixpoint ContextCompose (Δ Γ : Context) : Context :=\n  match Δ with\n  | ε => Γ\n  | (A,, Δ') => A,, Δ' +++ Γ\n  end\nwhere \"Δ +++ Γ\" := (ContextCompose Δ Γ)\n.\n\nFixpoint CLen (Γ : Context) : nat :=\n  match Γ with\n  | ε => O\n  | (A,, Γ') => S (CLen Γ')\n  end\n.\n\nReserved Notation \"[ Γ ] ⊢ t ::: T\" (at level 100, no associativity).\n\n(** Typing relation *)\nInductive Typed : Context -> Trm -> Typ -> Prop :=\n| Tpd_Un : forall (Γ: Context), [Γ] ⊢ un ::: Un\n| Tpd_Var : forall (T : Typ) (Γ Γ' : Context),\n    [Γ +++ (T,, Γ')] ⊢ 𝔳(CLen Γ) ::: T\n| Tpd_Func : forall (Γ : Context) (t : Trm) (T T' : Typ),\n    ([T,, Γ] ⊢ t ::: T') -> ([Γ] ⊢ (λ t) ::: (T —≻ T'))\n| Tpd_App : forall (Γ : Context) (t t' : Trm) (T T' : Typ),\n    ([Γ] ⊢ t ::: (T —≻ T')) -> ([Γ] ⊢ t' ::: T) -> ([Γ] ⊢ (t · t') ::: T')\nwhere \"[ Γ ] ⊢ t ::: T \" := (Typed Γ t T).\n\n\nTheorem not_lt_O : forall n, ~ (n < 0).\nProof.\n  intros n H.\n  inversion H.\nQed.\n\n(** shift free m-variables (greater than or equal to  m) by n. *)\nFixpoint shift (n : nat) (m : nat) (t : Trm) : Trm :=\n  match t with\n  | un => un\n  | 𝔳(y) => if le_dec m y then 𝔳(n + y) else 𝔳(y)\n  | λ f => λ (shift n (S m) f)\n  | t1 · t2 => (shift n m t1) · (shift n (m) t2)\n  end\n.\n\nReserved Notation \"t [ m // x ]\" (at level 100, no associativity).\n\n(** substitution *)\nFixpoint subst (t : Trm) (x : nat) (m : Trm) : Trm :=\n  match t with\n  | un => un\n  | 𝔳(y) =>\n    match lt_eq_lt_dec x y with\n    | inleft H =>\n      match H with\n      | left H' =>\n        (match y as u return x < u -> Trm with\n         | O => fun G => False_rect _ (not_lt_O _ G)\n         | S y' => fun G => 𝔳(y')\n         end)\n          H'\n      | right _ => m\n      end\n    | inright _ =>\n      𝔳(y)\n    end\n  | λ f => λ (f [(shift 1 O m) // (S x)])\n  | t1 · t2 => (t1 [m // x]) · (t2 [m // x])\n  end\nwhere \"t [ m // x ]\" := (subst t x m)\n.\n\nTheorem shift_O (t : Trm) (m : nat) : shift O m t = t.\nProof.\n  revert m.\n  induction t; cbn; intros m; trivial; try destruct le_dec; trivial.\n  + rewrite <- IHt at 2; trivial.\n  + rewrite <- IHt1 at 2; rewrite <- IHt2 at 2; trivial.\nQed.\n\n(** Shifts can be swapped changing their arguments. *)\nTheorem shift_shift (t : Trm) (k l m n : nat) :\n  shift k l (shift m (l + n) t) = shift m (k + l + n) (shift k l t).\nProof.\n  revert k l m n.\n  induction t; intros k l m n'; cbn;\n  trivial; repeat (try destruct le_dec; cbn);\n  trivial; try omega.\n  - match goal with\n      |- 𝔳(?A) = 𝔳(?B) => replace A with B by omega; trivial\n    end.\n  - change (S (l + n')) with ((S l) + n').\n    rewrite IHt.\n    match goal with\n      |- _ (shift _ ?A _) = _ (shift _ ?B _) => replace A with B by omega; trivial\n    end.\n  - rewrite IHt1.\n    rewrite IHt2.\n    trivial.    \nQed.\n\nLemma Typed_shift (Δ Δ' Γ : Context) (t : Trm) (T : Typ) :\n  ([Δ' +++ Γ]⊢ t ::: T) ->\n  [Δ' +++ Δ +++ Γ]⊢ shift (CLen Δ) (CLen Δ') t ::: T\n.\nProof.\n  intros H.\n  remember (Δ' +++ Γ) as ξ.\n  revert Δ' Δ Heqξ.\n  set (H' := H); clearbody H'.\n  induction H; cbn in *.\n  + constructor.\n  + intros Δ' Δ Heqξ.\n    destruct le_dec.\n    admit.\n    admit.\n  + intros Δ' Δ Heqξ.\n    constructor.\n    change (T,, Δ' +++ Δ +++ Γ) with ((T,, Δ') +++ Δ +++ Γ).\n    apply IHTyped; trivial.\n    rewrite Heqξ.\n    trivial.\n  + intros Δ.\n    econstructor; eauto.\nAdmitted.\n\nTheorem Typed_Subst (Δ Δ' Γ : Context) (t t' : Trm) (T T' : Typ) :\n  ([Δ' +++ Γ] ⊢ t' ::: T') ->\n  ([Δ' +++ Δ +++ (T',, Γ)] ⊢ t ::: T) ->\n  ([Δ' +++ Δ +++ Γ] ⊢ t [(shift (CLen Δ) (CLen Δ') t') // (CLen (Δ' +++ Δ))] ::: T)\n.\nProof.\n  intros H1 H2.\n  remember (Δ' +++ Δ +++ (T',, Γ)) as Υ.\n  revert Δ Δ' t' HeqΥ H1.\n  set (H2' := H2); clearbody H2'.\n  induction H2; intros Δ Δ' s HeqΥ H1; cbn in *.\n  - constructor.\n  - destruct lt_eq_lt_dec as [[G|G]|G].\n    + destruct Γ0; [inversion G|]; cbn in *.\n      rewrite HeqΥ in H2'.\n        admit.\n    + apply Typed_shift.\n      rewrite HeqΥ in H2'.\n      admit.\n    + rewrite HeqΥ in H2'.\n      admit.\n  - constructor.\n    set (W := fun t => shift_shift t 1 0); cbn in W; rewrite W; clear W.\n    change (T,, Δ' +++ Δ +++ Γ) with ((T,, Δ') +++ Δ +++ Γ).\n    change (S (CLen (Δ' +++ Δ))) with (CLen (T,, Δ' +++ Δ)).\n    apply IHTyped; trivial.\n    + rewrite HeqΥ.\n      trivial.\n    + admit.\n  - econstructor.\n    + apply IHTyped1; trivial.\n    + apply IHTyped2; trivial.\nAdmitted.\n  \nReserved Notation \"s ↝₁ t\" (at level 100, no associativity).\n\nInductive Red1 : Trm -> Trm -> Type :=\n| Red_Refl : forall t, t ↝₁ t\n| Beta : forall t1 s1 t2 s2, (t1 ↝₁ s1) -> (t2 ↝₁ s2) -> ((λ t1) · t2) ↝₁ (s1 [s2 // O])\n| Red_App : forall t1 t2 t13 t23, (t1 ↝₁ t13) -> (t2 ↝₁ t23) -> (t1 · t2) ↝₁ (t13 · t23)\n| Red_Func : forall t1 t2, (t1 ↝₁ t2) -> (λ t1) ↝₁ (λ t2)\nwhere \"s ↝₁ t\" := (Red1 s t).\n\nHint Constructors Red1.\n\nTheorem SubjectRed1 (Γ : Context) (t t' : Trm) (T : Typ) :\n        ([Γ] ⊢ t ::: T) -> (t ↝₁ t') -> ([Γ] ⊢ t' ::: T)\n.\nProof.\n  intros H1 H2.\n  revert Γ T H1.\n  induction H2; auto;\n  intros Γ T H1; inversion H1; subst;\n  try (econstructor; eauto).\n  + inversion H3; subst.\n    apply IHRed1_1 in H4.\n    apply IHRed1_2 in H5.\n    set (W := Typed_Subst ε ε _ _ _ _ _ H5 H4); cbn in W.\n    rewrite shift_O in W.\n    trivial.\nQed.\n\nLemma unit_red1 (t : Trm) : (un ↝₁ t) -> t = un.\nProof.\n  intros H.\n  inversion H; auto.\nQed.\n\nHint Extern 1 =>\nmatch goal with\n  [H : un ↝₁ _ |- _] => apply unit_red1 in H; subst\nend.\n\nLemma var_red1 (n : nat) (t : Trm) : (𝔳(n) ↝₁ t) -> t = 𝔳(n).\nProof.\n  intros H.\n  inversion H; auto.\nQed.\n\nHint Extern 1 =>\nmatch goal with\n  [H : 𝔳(_) ↝₁ _ |- _] => apply var_red1 in H; subst\nend.\n\nLemma fun_red1 (t1 t2 : Trm) : ((λ t1) ↝₁ t2) -> {s : Trm & t2 = λ s & t1 ↝₁ s}.\nProof.\n  intros H.\n  inversion H; eexists; eauto.\nQed.\n\nHint Extern 1 =>\nmatch goal with\n  [H : (λ _) ↝₁ _ |- _] =>\n  apply fun_red1 in H;\n    let s := fresh \"s\" in\n    let H1 := fresh \"H\" in\n    let H2 := fresh \"H2\" in\n    destruct H as [s H1 H2];\n      subst\nend.\n\nLemma subst_red1 (t1 t2 s1 s2: Trm) (l : nat) :\n  (t1 ↝₁ s1) ->\n  (t2 ↝₁ s2) ->\n  (t1 [t2 // l]) ↝₁ (s1 [s2 // l])\n.\nProof.\n  intros H1 H2.\n  revert s1 H1 t2 s2 l H2.\n  induction t1; intros s1 H1 t2 s2 l H2; eauto.\n   - apply var_red1 in H1; subst.\n     cbn; destruct lt_eq_lt_dec as [[]|]; destruct n; auto.\n   - apply fun_red1 in H1; destruct H1 as [v H1]; subst.\n     constructor; fold subst.\n     apply IHt1; eauto.\n     admit.\n   - cbn.\n     inversion H1; subst; cbn in *; auto.\n     + assert (G1 : λ t1 ↝₁ λ s0) by auto.\n       specialize (IHt1_1 _ G1 _ _ l H2).\n       inversion IHt1_1; subst.\n       admit.\n       admit.\nAdmitted.\n\nHint Resolve subst_red1.\n\nHint Extern 1 => match goal with [H : λ _ = λ _ |- _] => inversion H; subst end.\n\nTheorem ChurchRosser1 (t s1 s2 : Trm) :\n  (t ↝₁ s1) -> (t ↝₁ s2) -> {r : Trm & (s1 ↝₁ r) & (s2 ↝₁ r)}.\nProof.\n  revert s1 s2.\n  induction t; intros s1 s2 H1 H2; eauto.\n  - inversion H1; subst; inversion H2; subst; eauto.\n    match goal with\n      [H1 : t ↝₁ _ , H2 : t ↝₁ _ |- _] => \n      destruct (IHt _ _ H1 H2); eauto\n    end.\n  - destruct t1;\n    inversion H1; subst; inversion H2; subst; eauto;\n    repeat match goal with\n             [H1 : ?t ↝₁ ?s1 , H2 : ?t ↝₁ ?s2 |- _] => \n             (destruct (IHt1 _ _ H1 H2); clear H1 H2) +\n             (destruct (IHt2 _ _ H1 H2); clear H1 H2) +\n             (\n               let H1' := fresh \"H\" in\n               let H2' := fresh \"H\" in\n               assert (H1' : (λ t) ↝₁ (λ s1)) by eauto;\n                 assert (H2' : (λ t) ↝₁ (λ s2)) by eauto;\n                 clear H1 H2;\n                 (destruct (IHt1 _ _ H1' H2'); clear H1' H2')\n             ) +\n             (match goal with\n                [H : λ _ ↝₁ ?s |- _] =>\n                inversion H; subst; clear H\n              end)\n           end;\n    eauto 7.\nQed.\n\nReserved Notation \"s ↝* t\" (at level 100, no associativity).\n\nInductive Red (t1 : Trm) (t3 : Trm) : Type :=\n| Red_Red1 : (t1 ↝₁ t3) -> (t1 ↝* t3)\n| Red_Trans : forall t2, (t1 ↝₁ t2) -> (t2 ↝* t3) -> (t1 ↝* t3)\nwhere \"s ↝* t\" := (Red s t).\n\nHint Constructors Red.\n\nLemma Red_Trans' : forall t1 t2 t3, (t1 ↝* t2) -> (t2 ↝* t3) -> (t1 ↝* t3).\nProof.\n  intros t1 t2 t3 H1.\n  revert t3.\n  induction H1; eauto.\nQed.\n\nHint Resolve Red_Trans'.\n\nTheorem ChurchRosser1_many (t s1 s2 : Trm) :\n  (t ↝₁ s1) -> (t ↝* s2) -> {r : Trm & (s1 ↝* r) & (s2 ↝* r)}.\nProof.\n  intros H1 H2.\n  assert (G : forall s, (t ↝₁ s) -> {r : Trm & (s1 ↝* r) & (s ↝₁ r)}).\n  {  \n    intros s G.\n    edestruct (ChurchRosser1 _ _ _ G H1); eauto.\n  }\n  {    \n    clear H1.\n    induction H2 as [? ? H2|].\n    - edestruct G; eauto.\n    - apply IHRed.\n      intros s H3.\n      edestruct G as [s' G1 G2]; [eassumption|].\n      edestruct (ChurchRosser1 _ _ _ H3 G2); eauto.\n  }\nQed.\n  \nTheorem ChurchRosser (t s1 s2 : Trm) :\n  (t ↝* s1) -> (t ↝* s2) -> {r : Trm & (s1 ↝* r) & (s2 ↝* r)}.\nProof.\n  intros H1.\n  revert s2.\n  induction H1; eauto; intros s2 H2.\n  - eapply ChurchRosser1_many; eauto.\n  - edestruct ChurchRosser1_many; try eassumption.\n    edestruct IHRed; eauto.\nQed.\n", "meta": {"author": "amintimany", "repo": "STLC", "sha": "dae6c524ee23c02352eb626daecd53b7f4b24e4d", "save_path": "github-repos/coq/amintimany-STLC", "path": "github-repos/coq/amintimany-STLC/STLC-dae6c524ee23c02352eb626daecd53b7f4b24e4d/stlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7008258173307816}}
{"text": "Require Export Categories.\n\nClass Isomorphism {C: Category} (x y : @obj C) : Type := {\n  to   : arrow y x;\n  from : arrow x y;\n\n  iso_to_from : to o from = @identity C y;\n  iso_from_to : from o to = @identity C x\n}.\n\nArguments to {_ _ _} _. \nArguments from {_ _ _} _.\n\nLemma iso_split: forall C x y (I1 I2: Isomorphism x y), \n        to I1 = to I2 /\\ from I1 = @from C x y I2 -> I1 = I2.\nProof. intros.\n       destruct H as (H1, H2).\n       destruct I1, I2. simpl in *. subst.\n       specialize (proof_irrelevance (to1 o from1 = identity y) iso_to_from0 iso_to_from1); intros.\n       specialize (proof_irrelevance (from1 o to1 = identity x) iso_from_to0 iso_from_to1); intros.\n       now subst.\nQed.\n\n(** Groupoid is a category with all maps isomorphisms => category of isomorphisms *)\nDefinition Groupoid (C: Category): Category.\nProof. unshelve econstructor.\n       - exact (@obj C).\n       - exact Isomorphism.\n       - intros. unshelve econstructor.\n         + exact (identity a).\n         + exact (identity a).\n         + now rewrite f_identity.\n         + now rewrite f_identity.\n      - intros a b c I1 I2.\n        unshelve econstructor.\n        + destruct I1, I2. exact (to1 o to0).\n        + destruct I1, I2. exact (from0 o from1).\n        + simpl. destruct I1, I2. rewrite <- iso_to_from1.\n          rewrite assoc. repeat apply compose_respects. rewrite <- assoc.\n          now rewrite iso_to_from0, f_identity. easy.\n        + simpl. destruct I1, I2. rewrite <- iso_from_to0.\n          rewrite assoc. repeat apply compose_respects. rewrite <- assoc.\n          now rewrite iso_from_to1, f_identity. easy.\n      - repeat intro. simpl in *. subst. easy.\n      - repeat intro. simpl. destruct f, g,  h. simpl in *.\n        apply iso_split. simpl. split; now rewrite assoc.\n      - intros. simpl. destruct f. simpl.\n        apply iso_split. simpl. split. now rewrite f_identity.\n        now rewrite identity_f.\n      - intros. destruct f. apply iso_split. simpl.\n        split. now rewrite identity_f.\n        now rewrite f_identity.\nDefined.\nCheck Groupoid.\n\nInfix \"≅\" := Isomorphism (at level 40, left associativity).\n", "meta": {"author": "ekiciburak", "repo": "ComparisonTheorem-MacLane", "sha": "f1a5b0e35554c7115fc0dba32d550dfa0121d07a", "save_path": "github-repos/coq/ekiciburak-ComparisonTheorem-MacLane", "path": "github-repos/coq/ekiciburak-ComparisonTheorem-MacLane/ComparisonTheorem-MacLane-f1a5b0e35554c7115fc0dba32d550dfa0121d07a/Iso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7008133285378769}}
{"text": "Require Import List.\n\nTheorem app_nil_r : forall (A : Type)(l : list A), l ++ nil = l.\nProof.\nintros.\ninduction l.\nreflexivity.\nsimpl.\napply (f_equal(cons a)).\napply IHl.\nQed.\n\nTheorem app_assoc : forall (A : Type)(l1 l2 l3 : list A), l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.\nProof.\nintros.\ninduction l1.\nreflexivity.\nsimpl.\nf_equal.\napply IHl1.\nQed.\n\nTheorem rev_app_distr : forall (A : Type)(l1 l2 : list A), rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\nintros.\ninduction l1.\nsimpl.\nrewrite app_nil_r.\nreflexivity.\nsimpl.\nrewrite app_assoc.\nf_equal.\napply IHl1.\nQed.\n\n\nTheorem rev_involutive : forall (A : Type)(l : list A), rev (rev l) = l.\nProof.\nintros.\ninduction l.\nreflexivity.\nsimpl.\nrewrite rev_app_distr.\nsimpl.\nf_equal.\napply IHl.\nQed.\n\nTheorem fold_right_app :\n  forall (A B : Type)(f : B -> A -> A)(l l' : list B)(i : A),\n  fold_right f i (l ++ l') = fold_right f (fold_right f i l') l.\nProof.\nintros.\ninduction l.\nreflexivity.\nsimpl.\nf_equal.\napply IHl.\nQed.\n", "meta": {"author": "kogai", "repo": "sandbox-coq", "sha": "e09bbf942cb1e21478368913293dbe831b48b276", "save_path": "github-repos/coq/kogai-sandbox-coq", "path": "github-repos/coq/kogai-sandbox-coq/sandbox-coq-e09bbf942cb1e21478368913293dbe831b48b276/third.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.7008133281821493}}
{"text": "(* This file is generated by Why3's Coq-realize driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\n\n(* Why3 comment *)\n(* max is replaced with (ZArith.BinInt.Z.max x x1) by the coq driver *)\n\n(* Why3 goal *)\nLemma max_def : forall (x:Z) (y:Z), ((y <= x)%Z ->\n  ((ZArith.BinInt.Z.max x y) = x)) /\\ ((~ (y <= x)%Z) ->\n  ((ZArith.BinInt.Z.max x y) = y)).\nProof.\nintros x y.\nsplit ; intros H.\nnow apply Zmax_l.\napply Zmax_r.\nomega.\nQed.\n\n(* Why3 comment *)\n(* min is replaced with (ZArith.BinInt.Z.min x x1) by the coq driver *)\n\n(* Why3 goal *)\nLemma min_def : forall (x:Z) (y:Z), ((y <= x)%Z ->\n  ((ZArith.BinInt.Z.min x y) = y)) /\\ ((~ (y <= x)%Z) ->\n  ((ZArith.BinInt.Z.min x y) = x)).\nProof.\nintros x y.\nsplit ; intros H.\nnow apply Zmin_r.\napply Zmin_l.\nomega.\nQed.\n\n(* Why3 goal *)\nLemma Max_r : forall (x:Z) (y:Z), (x <= y)%Z ->\n  ((ZArith.BinInt.Z.max x y) = y).\nexact Zmax_r.\nQed.\n\n(* Why3 goal *)\nLemma Min_l : forall (x:Z) (y:Z), (x <= y)%Z ->\n  ((ZArith.BinInt.Z.min x y) = x).\nexact Zmin_l.\nQed.\n\n(* Why3 goal *)\nLemma Max_comm : forall (x:Z) (y:Z),\n  ((ZArith.BinInt.Z.max x y) = (ZArith.BinInt.Z.max y x)).\nexact Zmax_comm.\nQed.\n\n(* Why3 goal *)\nLemma Min_comm : forall (x:Z) (y:Z),\n  ((ZArith.BinInt.Z.min x y) = (ZArith.BinInt.Z.min y x)).\nexact Zmin_comm.\nQed.\n\n(* Why3 goal *)\nLemma Max_assoc : forall (x:Z) (y:Z) (z:Z),\n  ((ZArith.BinInt.Z.max (ZArith.BinInt.Z.max x y) z) = (ZArith.BinInt.Z.max x (ZArith.BinInt.Z.max y z))).\nProof.\nintros x y z.\napply eq_sym, Zmax_assoc.\nQed.\n\n(* Why3 goal *)\nLemma Min_assoc : forall (x:Z) (y:Z) (z:Z),\n  ((ZArith.BinInt.Z.min (ZArith.BinInt.Z.min x y) z) = (ZArith.BinInt.Z.min x (ZArith.BinInt.Z.min y z))).\nProof.\nintros x y z.\napply eq_sym, Zmin_assoc.\nQed.\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/lib/coq/int/MinMax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7008133175125064}}
{"text": "(******************************************************************************)\n(*                                                                            *)\n(*      LECTURE :  Floating-point numbers and formal proof                    *)\n(*                       Laurent.Thery@inria.fr       12/05/2016              *)\n(*                                                                            *)\n(******************************************************************************)\n\n\n(*                                                                              \n  After having seeen the rounding mode, we are going to see the formats for     \n  our floating point numbers. We start from a very generic representation       \n*)\n\nRequire Import Psatz ZArith Reals.\nFrom Flocq Require Import FTZ Core Operations.\n\nOpen Scope R_scope.\n\nAxiom todo : forall P, P.\nLtac todo := apply todo.\n\nSection Lecture3.\n\nCheck radix.                                                   (* A basis     *)\nPrint radix.\n\nDefinition  radix2 : radix. exists  2%Z. auto. Defined. \nDefinition radix10 : radix. exists 10%Z. auto. Defined.\n\nPrint Coercion Paths radix Z.\nCompute (radix2 + 2)%Z.\n \nCheck float.\nCheck float radix2.                                 (* Floating point number as \n                                                       pair of integers       *)\nCheck float radix10.                               \nPrint float.\n\nDefinition val1 : float radix2  := {| Fnum := 7; Fexp := 1 |}.\nCompute Fnum val1.\nCompute Fexp val1.\n\nDefinition val2 : float radix2  := {| Fnum := 7; Fexp := 0 |}.\nCompute Fnum val2.\nCompute Fexp val2.\n\nDefinition val3 : float radix10 := {| Fnum := 7; Fexp := 10 |}.\n\nCheck F2R val1.                                   (* Converting float to real *)\nEval lazy beta delta [F2R] in F2R val1.\nCompute F2R val1.\nCompute F2R val2.\nCompute F2R val3.\n\nVariable r : radix.\n\n(*                                                                              \n  Prove that the positivity of a floating point number is the one of its matissa\n                                                                                \nFact ex1 : forall (f : float r), (0 <= Fnum f)%Z <->  0 <= F2R f.               \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \n*)\n\n(******************************************************************************)\n(*                            OPERATIONS                                      *)\n(******************************************************************************)\n\nCheck Fopp val1.\nEval lazy beta delta [Fopp] in Fopp val1.\nCompute Fopp val1.\nSearch Fopp.\n\nCheck Fabs val1.\nEval lazy beta delta [Fabs] in Fabs val1.\nCompute Fabs val1.\nSearch Fabs.\n\nCheck Falign val1 val2.\nEval lazy beta delta [Falign] in Falign val1 val2.\nCompute Falign val1 val2.\nSearch Falign.\n\nCheck Fplus val1 val2.\nEval lazy beta delta [Fplus] in Fplus val1 val2.\nCompute Fplus val1 val2.\nSearch Fplus.\n\nCheck Fminus val1 val2.\nEval lazy beta delta [Fminus] in Fminus val1 val2.\nCompute Fminus val1 val2.\nSearch Fminus.\n\nCheck Fmult val1 val2.\nEval lazy beta delta [Fmult] in Fmult val1 val2.\nCompute Fmult val1 val2.\nSearch Fmult.\n\n\n(******************************************************************************)\n(*                               FORMATS                                      *)\n(******************************************************************************)\n\n\nVariable e : Z.                                 (* Bound on the exponent      *)\nVariable p : Z.                                 (* Precision for the mantissa *)\nVariables x y : R.                             \n\n(* Format with a fixed exponent                                               *)\nCheck FIX_format r e x.\nCheck FIX_spec.\n\n(*                                                                              \n  Prove that zero is in the FIX format and that this format is symmetric        \n*)             \nFact ex2 : FIX_format r e 0.\nProof.\nexists {| Fnum := 0; Fexp := e |}.\n- unfold F2R.\n  simpl.\n  ring.\n- simpl.\n  trivial.\nQed.\n\nFact ex3 : FIX_format r e x -> FIX_format r e (- x).\nProof.\nintros [f Hf].\nexists (Fopp f).\n- todo.\n- todo.\nQed.\n\n(* Format without bound on the exponent                                       *)\nCheck FLX_format r p x.\nCheck FLX_spec.\n\n(*                                                                              \n  Prove that zero is in the FLX format and that this format is symmetric        \n                                                                                \nFact ex4 : (0 <= p)%Z ->  FLX_format r p 0.                                     \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \nFact ex5 : FLX_format r p x -> FLX_format r p (- x).                            \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \n*)\n\n(* Format with normalised numbers but without bound on the exponent           *)\nCheck FLXN_format r p x.\nCheck FLXN_spec.\n\n(*                                                                              \n  Prove that zero is in the FLXN format and that this format is symmetric       \n                                                                                \nFact ex6 : FLXN_format r p 0.                                                   \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \nFact ex7 : FLXN_format r p x -> FLXN_format r p (- x).                          \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \n*)\n\n(* Format with denormalised numbers and with bound on the exponent            *)\nCheck FLT_format r e p x.\nCheck FLT_spec.\n\n(*                                                                              \n  Prove that zero is in the FLT format and that this format is symmetric        \n                                                                                \nFact ex8 : (0 <= p)%Z -> FLT_format r e p 0.                                    \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \nFact ex9 : FLT_format r e p x -> FLT_format r e p (- x).                        \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \n*)\n\n(* Format without denormalised numbers but with bound on the exponent         *)\n\nCheck FTZ_format r e p x.\nCheck FTZ_spec.\n\n(*                                                                              \n  Prove that zero is in the FTZ format and that this format is symmetric        \n                                                                                \nFact ex10 : (0 <= p)%Z -> FTZ_format r e p 0.                                   \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \nFact ex11 : FTZ_format r e p x -> FTZ_format r e p (- x).                       \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n                                                                                \n*)\n\n(******************************************************************************)\n(*                 A more algorithmic version                                 *)\n(******************************************************************************)\n\nCheck bpow radix2 10.\nEval lazy beta delta [bpow] in bpow radix2 10.\nCompute bpow radix2 10.\n\nCheck (mag r x).          (* An exponent and the proof of the bound  *)\nPrint mag.\n\nCheck mag r x.                 (* The logarithm associated to a real      *)\nPrint Coercion Paths mag_prop Z.\nCheck (mag r x + 2)%Z.\nCheck (bpow_mag_gt r x).       (* lemma for the upper bound               *)\n\nCheck archimed.                    (* Archimedian property                    *)\nCheck Zfloor.                      (* The floor function                      *)\nPrint Zfloor.\nCheck Zceil.                       (* The ceiling function                    *)\nPrint Zceil.\nCheck Ztrunc.                      (* The truncating function                 *)\nPrint Ztrunc.\n\nVariable phi : Z -> Z.             (* translating exponent                    *)\n\nCheck cexp r phi x.\nEval lazy beta delta [cexp] in cexp r phi x.\n\nCheck scaled_mantissa r phi x.\nEval lazy beta delta [scaled_mantissa] in scaled_mantissa r phi x.\n\nCheck generic_format r phi x. (* Generic format that depends only on phi      *)\nEval lazy beta delta [generic_format] in generic_format r phi x.\nEval lazy beta delta [generic_format F2R Fnum Fexp] iota in \n   generic_format r phi x.\nEval lazy beta delta [generic_format F2R scaled_mantissa Fnum Fexp] iota in \n   generic_format r phi x.\n\n\n(*                                                                              \n  Prove that the generic format contains zero and is symmetric                  \n*)\n\nFact ex12 : generic_format r phi 0.\nProof.\nunfold generic_format, F2R, scaled_mantissa; simpl.\ntodo.\nQed.\n\nFact ex13 : forall z,  z <> 0 -> mag r (- z) = mag r z :> Z.\nProof.\nSearch mag inside Raux.\ntodo.\nQed.\n\nFact ex14 : forall z, generic_format r phi z -> generic_format r phi (- z).\nProof.\nintros z; unfold generic_format, scaled_mantissa, cexp, F2R; simpl.\ntodo.\nQed.\n\n(*                                                                              \nHint : we can rely on the following properties of Ztrunc and mag            \n                                                                                \nSearch Ztrunc inside Fcore_Raux.                                           \nSearch mag inside Fcore_Raux.                                          \n                                                                                \n*)\n\n(* We can revisit the previous format using the algorithmic version           *)\n\nVariable z : Z.\n\n(* Format with fixed exponent                                                 *)\nCheck FIX_exp e z.\nEval lazy beta delta [FIX_exp] in FIX_exp e z.\n\nCheck generic_format_FIX r e x.\nCheck FIX_format_generic r e x.\n\n(* Format without bound on the exponent                                       *)\nCheck FLX_exp p z.\nEval lazy beta delta [FLX_exp] in FLX_exp p z.\n\nCheck generic_format_FLX r p x.\nCheck FLX_format_generic r p x.\n\n(* Format with denormalised numbers and with bound on the exponent            *)\nCheck FLT_exp e p z.\nEval lazy beta delta [FLT_exp] in FLT_exp e p z.\n\nCheck generic_format_FLT r e p x.\nCheck FLT_format_generic r e p x.\n\n(* Format without denormalised numbers but with a bound on the exponent       *)\nCheck FTZ_exp e p z.\nEval lazy beta delta [FTZ_exp] in FTZ_exp e p z.\n\n(*                                                                              \n  Prove Sterbenz lemma using the only property that phi is monotone             \n                                                                                \nFact ex15 :                                                                     \n  Monotone_exp phi ->                                                           \n  generic_format r phi x -> generic_format r phi y ->                           \n  (y / 2 <= x <= 2 * y)%R ->                                                    \n  generic_format r phi (x - y)%R.                                               \nProof.                                                                          \n...                                                                             \nQed.                                                                            \n\nFor this proof, we use the following lemma that gives a simple criterion to     \nensure that a float is in the format                                            \n                                                                                \nCheck generic_format_F2R.                                                       \n                                                                                \nHere is the informal proof :                                                    \n From (y / 2 <= x <= 2 * y) we deduce that                                      \n    - 0 <= y       (1)                                                          \n    - 0 <= x       (2)                                                          \n    - x - y <= x   (3)                                                          \n    - x - y <= y.  (4)                                                          \n  generic_format r phi x can be rewritten as                                    \n    x = F2R {| Fnum := mx; Fexp := phi (mag r x) |}                         \n  generic_format r phi y can be rewritten as                                    \n    y = F2R {| Fnum := my, Fexp := phi (mag r y) |}                         \n  using Fopp, we can rewrite x - y as                                           \n    x - y =                                                                     \n     F2R {|Fnum := mz, Fexp := Z.min (phi (mag r x), phi (mag r y) |}   \n  so in order to have generic_format r phi (x - y) using  generic_format_F2R,   \n  it is sufficient that                                                         \n                                                                                \n   phi (mag r (x - y)) <= Z.min (phi (mag r x), phi (mag r y))      \n                                                                                \n  so that                                                                       \n                                                                                \n     phi (mag r (x - y)) <= phi (mag r x)                               \n  and                                                                           \n     phi (mag r (x - y)) <= phi (mag r y)                               \n                                                                                \n  but mag is monotone so is phi, it is then sufficient to prove that        \n                                                                                \n     x - y <= x                                                                 \n  and                                                                           \n     x - y <= y                                                                 \n                                                                                \n  that come from (3) and (4).                                                   \n                                                                                \n*)\n\n\n(* We can derive a generic rounding function                                  *)\n\nVariable rnd : R -> Z.                           (* Rounding on the mantissa  *)\n\nCheck round r phi rnd x.\nEval lazy beta delta [round] in round r phi rnd x.\n\nCheck round r phi Zfloor x.                      (* Rounding down             *)\nEval lazy beta delta [round] in round r phi Zfloor x.\n\nCheck round r phi Zceil x.                       (* Rounding up               *)\nEval lazy beta delta [round] in round r phi Zfloor x.\n\nCheck round r phi Ztrunc x.                      (* Rounding to zero          *)\nEval lazy beta delta [round] in round r phi Ztrunc x.\n\nVariable choice : Z -> bool.\nCheck round r phi (Znearest choice) x.\nEval lazy beta delta [round] in round r phi (Znearest choice) x.\nEval lazy beta delta [Znearest] in round r phi (Znearest choice) x.\n\n(* Which conditions on phi for this rounding to have good properties?         *)\n\nPrint Valid_exp.\nVariable vExp : Valid_exp phi.\n\nCheck @generic_format_satisfies_any r phi.\nCheck @round_DN_pt r phi.\nCheck @round_UP_pt r phi.\nCheck @round_ZR_pt r phi.\nCheck @round_N_pt r phi.\n\nPrint Valid_rnd.\n\nCheck valid_rnd_DN.\nCheck valid_rnd_UP.\nCheck valid_rnd_ZR.\nCheck valid_rnd_N choice.\n\n\n(*                                                                              \n  Prove that the error resulting of an addition in rounded to the nearest      \n  can always be represented exactly                                             \n                                                                                \n  We first prove a first general result on how a rounded value can be           \n  represented                                                                   \n                                                                                \n  Fact ex16 :                                                                   \n    forall (f : float r) rnd, Valid_rnd rnd ->                                  \n    exists m',                                                                  \n      round r phi rnd (F2R f) =                                                 \n      F2R ({| Fnum := m'; Fexp := Fexp f |} : float r).                         \n  Proof.                                                                        \n  ...                                                                           \n  Qed.                                                                          \n                                                                                \n  Informal proof                                                                \n    we can rewrite the rounded value as:                                        \n                                                                                \n     round r phi rnd (F2R f) =                                                  \n       F2R {| Fnum := m; Fexp := phi (mag r (Fexp f)) |}                    \n                                                                                \n     if phi (mag r (Fexp f)) <= Fexp f                                      \n                                                                                \n       we can choose m' = (Fnum f)                                              \n                                                                                \n    if phi (mag r (Fexp f)) > Fexp f                                        \n                                                                                \n       we can choose m' = m * r ^ (phi (mag r (Fexp f)) - Fexp f).          \n                                                                                \n  Fact ex17 :                                                                   \n    Monotone_exp phi ->                                                         \n    generic_format r phi x -> generic_format r phi y ->                         \n    generic_format r phi (round r phi (Znearest choice) (x + y) - (x + y))%R.   \n  Proof.                                                                        \n  ....                                                                          \n  Qed.                                                                          \n                                                                                \n  Informal proof                                                                \n                                                                                \n  generic_format r phi x can be rewritten as                                    \n    x  = F2R {| Fnum := mx; Fexp := phi (mag r x) |}                        \n                                                                                \n  generic_format r phi y, can be rewritten as                                   \n    y  = F2R {| Fnum := my; Fexp := phi (mag r y) |}                        \n                                                                                \n  without loss of generality we can suppose that                                \n        phi (mag r x) <= phi (mag r y)                                  \n                                                                                \n  so using Fplus we have                                                        \n    x + y = F2R {| Fnum := mx +                                                 \n                           my * r ^ (phi (mag r y) - phi (mag r x));    \n                   Fexp := phi (mag x) |}                                   \n                                                                                \n  applyin ex16 we get                                                           \n    round r phi (Znearest choice) (F2R (x + y)) =                               \n            F2R {| Fnum := m; Fexp := phi (mag r x) |}                      \n                                                                                \n  the definition of Fopp gives                                                  \n    round r phi (Znearest choice) (x + y) - (x + y) =                           \n       F2R {| Fnum := m - mx + my * r ^ (phi (mag r y) - phi (mag r x));\n              Fexp := phi (mag r x) |}                                      \n                                                                                \n  using  generic_format_F2R, a sufficient condition for this float to be in     \n  the format is :                                                               \n                                                                                \n    phi (mag r (round r phi (Znearest choice) (x + y) - (x + y))) <=        \n    phi (mag r x)                                                           \n                                                                                \n   phi and mag are monotone so it is sufficient that                        \n                                                                                \n    |round r phi (Znearest choice) (x + y) - (x + y))| <= |x|                   \n                                                                                \n   so                                                                           \n                                                                                \n    |round r phi (Znearest choice) (x + y) - (x + y))| <= |y - (x + y)|         \n                                                                                \n  but y is a float so its distance to x + y must be greater or equal to the one \n  of the rounded value to the nearest of x + y.                                 \n                                                                                \n*)\n\nEnd Lecture3.", "meta": {"author": "thery", "repo": "FlocqLecture", "sha": "94ca2865053998c7ede0cc40a631729b044be0e6", "save_path": "github-repos/coq/thery-FlocqLecture", "path": "github-repos/coq/thery-FlocqLecture/FlocqLecture-94ca2865053998c7ede0cc40a631729b044be0e6/lecture3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.700770320745204}}
{"text": "Require Import Category.Lib.\nRequire Import Category.Theory.Category.\nRequire Import Category.Theory.Functor.\nRequire Import Category.Theory.Natural.Transformation.\nRequire Import Category.Functor.Diagonal.\nRequire Import Category.Structure.Cone.\n\nGeneralizable All Variables.\n\n(* A natural transformation Δd ⟹ F (where Δd is the Constant functor on d) is\n   the same as a cone over F (whose vertex is d). *)\n\nMonomorphic Theorem Cone_Transform `(F : J ⟶ C) (d : C) :\n  Δ[J](d) ⟹ F ↔ { c : Cone F | vertex_obj = d }.\nProof. \n  split; intros.\n  - unshelve eexists.\n    + unshelve econstructor; intros; [ exact d | unshelve econstructor ].\n      * apply X.\n      * abstract(simpl; intros;\n        rewrite (naturality[X]); cat).\n    + reflexivity.\n  - transform; simpl; intros;\n    destruct X; subst.\n    + apply x0.\n    + cat; apply cone_coherence.\n    + cat; symmetry; apply cone_coherence.\nDefined.\n", "meta": {"author": "jwiegley", "repo": "category-theory", "sha": "5376e32a4eeace4a84674820083bc2985a2a593f", "save_path": "github-repos/coq/jwiegley-category-theory", "path": "github-repos/coq/jwiegley-category-theory/category-theory-5376e32a4eeace4a84674820083bc2985a2a593f/Structure/Cone/Natural/Transformation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7007703151802798}}
{"text": "(* Coq assignment - LDI 2018\n\nProve the lemmas given below (and replace Admitted with Qed).\n\nIt is not allowed to: \n1. import other modules than List,\n2. define Ltac tactics,\n3. erase statements of the lemma (if you fail to prove a lemma leave Admitted).\n\nIt is allowed to:\n\n1. introduce your own definitions and auxiliary lemmas,\n2. change the order of the lemmas to prove,\n3. add comments.\n\nRemember about revert/generalize tactics.\n*)\n\n\n\nRequire Import List.\nSet Implicit Arguments.\n\nSection Zal.\n\nCheck list.\nPrint list.\n\nVariable A: Type.\n\nInductive podciag : list A -> list A -> Prop :=\n| PC_Nil : forall l, podciag nil l\n| PC_ConsH : forall a l1 l2, podciag l1 l2 -> podciag (cons a l1) (cons a l2)\n| PC_ConsT : forall a l1 l2, podciag l1 l2 -> podciag l1 (cons a l2).\n\nInductive prefix : list A -> list A -> Prop :=\n| P_Nil : forall l, prefix nil l\n| P_Cons : forall a l1 l2, prefix l1 l2 -> prefix (cons a l1) (cons a l2).\n\nInductive sufix : list A -> list A -> Prop :=\n| S_Nil : forall l, sufix l l\n| S_Cons : forall a l1 l2, sufix l1 l2 -> sufix l1 (cons a l2).\n\nInductive podlista : list A -> list A -> Prop :=\n| PL_Base : forall l1 l2, prefix l1 l2 -> podlista l1 l2\n| PL_Cons : forall a l1 l2, podlista l1 l2 -> podlista l1 (cons a l2).\n\n\nLemma Prefix_Podlista : forall l1 l2, prefix l1 l2 -> podlista l1 l2.\nProof.\nAdmitted.\n\nLemma Sufix_Podlista : forall l1 l2, sufix l1 l2 -> podlista l1 l2.\nProof.\nAdmitted.\n\nLemma Prefix_Podciag : forall l1 l2, prefix l1 l2 -> podciag l1 l2.\nProof.\nAdmitted.\n\nLemma Podlista_Podciag: forall l1 l2, podlista l1 l2 -> podciag l1 l2.\nProof.\nAdmitted.\n\nLemma Append_Podciag_Podciag_Podciag: \n      forall p1 l1 p2 l2, podciag p1 l1 -> podciag p2 l2 \n       -> podciag (p1 ++ p2) (l1 ++ l2).\nProof.\nAdmitted.\n\nLemma Append_Eq_Prefix_Prefix:\n      forall l p2 l2, prefix p2 l2 -> prefix (l ++ p2)(l ++ l2).\nProof.\nAdmitted.\n\nLemma Append_Sufix_Prefix_Podlista:\n      forall p1 l1 p2 l2, sufix p1 l1 -> prefix p2 l2\n       -> podlista (p1 ++ p2) (l1 ++ l2).\nProof.\nAdmitted.\n\nDefinition sufixD (s l : list A):= exists p, p ++ s = l.\n\nLemma Sufix_SufixD: forall s l, sufix s l <-> sufixD s l.\nProof.\nAdmitted.\n\nLemma Sufix_Prefix: forall s l, sufix s l -> exists p, prefix p l /\\ p ++ s = l.\nProof.\nAdmitted.\n\nLemma Trans_Podciag: forall l1 l2 l3, podciag l1 l2 -> podciag l2 l3 -> podciag l1 l3.\nProof.\nAdmitted.\n\nEnd Zal.", "meta": {"author": "przxmek", "repo": "log-coq", "sha": "f189acd09bfef04f6961fb0ab45db88c61d35b14", "save_path": "github-repos/coq/przxmek-log-coq", "path": "github-repos/coq/przxmek-log-coq/log-coq-f189acd09bfef04f6961fb0ab45db88c61d35b14/zal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7007688804140353}}
{"text": "(**\n  This module defines the Ring record type which can be used to\n  represent algebraic rings and provides a collection of axioms\n  and theorems describing them.\n\n  Copyright (C) 2018 Larry D. Lee Jr. <llee454@gmail.com>\n\n  This program is free software: you can redistribute it and/or modify\n  it under the terms of the GNU Lesser General Public License as\n  published by the Free Software Foundation, either version 3 of the\n  License, or (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public\n  License along with this program. If not, see\n  <https://www.gnu.org/licenses/>.\n*)\n\nRequire Import Description.\nRequire Import FunctionalExtensionality.\nRequire Import base.\nRequire Import function.\nRequire Import monoid.\nRequire Import group.\nRequire Import abelian_group.\n\nModule Ring.\n\nClose Scope nat_scope.\n\n(**\n  Accepts two binary functions, f and g, and\n  asserts that f is left distributive over g.\n*)\nDefinition is_distrib_l (T : Type) (f g : T -> T -> T)\n  :  Prop\n  := forall x y z : T, f x (g y z) = g (f x y) (f x z).\n\n(**\n  Accepts two binary functions, f and g, and\n  asserts that f is right distributive over g.\n*)\nDefinition is_distrib_r (T : Type) (f g : T -> T -> T)\n  :  Prop\n  := forall x y z : T, f (g y z) x = g (f y x) (f z x).\n\n(**\n  Accepts two binary functions, f and g, and\n  asserts that f is distributive over g.\n*)\nDefinition is_distrib (T : Type) (f g : T -> T -> T)\n  :  Prop\n  := is_distrib_l T f g /\\ is_distrib_r T f g.\n\n(** Represents algebraic rings *)\nStructure Ring : Type := ring {\n\n  (** Represents the set of ring elements. *)\n  E : Set;\n\n  (** Represents 0 - the additive identity. *)\n  E_0 : E;\n\n  (** Represents 1 - the multiplicative identity. *)\n  E_1 : E;\n\n  (** Represents addition. *)\n  sum : E -> E -> E;\n\n  (** Represents multiplication. *)\n  prod : E -> E -> E;\n\n  (** Asserts that 0 /= 1. *)\n  distinct_0_1 : E_0 <> E_1;\n\n  (** Asserts that addition is associative. *)\n  sum_is_assoc : Monoid.is_assoc E sum;\n\n  (** Asserts that addition is commutative. *)\n  sum_is_comm : Abelian_Group.is_comm E sum;\n\n  (** Asserts that E_0 is the left identity element. *)\n  sum_id_l : Monoid.is_id_l E sum E_0;\n\n  (**\n    Asserts that every element has an additive\n    inverse.\n  *)\n  sum_inv_l_ex : forall x : E, exists y : E, sum y x = E_0;\n\n  (** Asserts that multiplication is associative. *)\n  prod_is_assoc : Monoid.is_assoc E prod;\n\n  (**\n    Asserts that 1 is the left identity\n    element.\n  *)\n  prod_id_l : Monoid.is_id_l E prod E_1;\n\n  (**\n    Asserts that 1 is the right identity\n    element.\n  *)\n  prod_id_r : Monoid.is_id_r E prod E_1;\n\n  (**\n    Asserts that multiplication is left\n    distributive over addition.\n  *)\n  prod_sum_distrib_l : is_distrib_l E prod sum;\n   \n  (**\n    Asserts that multiplication is right\n    distributive over addition.\n  *)\n  prod_sum_distrib_r : is_distrib_r E prod sum\n}.\n\n(** Enable implicit arguments for ring properties. *)\n\nArguments E_0 {r}.\n\nArguments E_1 {r}.\n\nArguments sum {r} x y.\n\nArguments prod {r} x y.\n\nArguments distinct_0_1 {r} _.\n\nArguments sum_is_assoc {r} x y z.\n\nArguments sum_is_comm {r} x y.\n\nArguments sum_id_l {r} x.\n\nArguments sum_inv_l_ex {r} x.\n\nArguments prod_is_assoc {r} x y z.\n\nArguments prod_id_l {r} x.\n\nArguments prod_id_r {r} x.\n\nArguments prod_sum_distrib_l {r} x y z.\n\nArguments prod_sum_distrib_r {r} x y z.\n\n(** Define notations for ring properties. *)\n\nNotation \"0\" := E_0 : ring_scope.\n\nNotation \"1\" := E_1 : ring_scope.\n\nNotation \"x + y\" := (sum x y) (at level 50, left associativity) : ring_scope.\n\nNotation \"{+}\" := sum : ring_scope.\n\nNotation \"x # y\" := (prod x y) (at level 50, left associativity) : ring_scope.\n\nNotation \"{#}\" := prod : ring_scope.\n\nOpen Scope ring_scope.\n\nSection Theorems.\n\n(**\n  Represents an arbitrary ring.\n\n  Note: we use Variable rather than Parameter\n  to ensure that the following theorems are\n  generalized w.r.t r.\n*)\nVariable r : Ring.\n\n(**\n  Represents the set of group elements.\n\n  Note: We use Let to define E as a \n  local abbreviation.\n*)\nLet E := E r.\n\n(**\n  A predicate that accepts one element, x,\n  and asserts that x is nonzero.\n*)\nDefinition nonzero (x : E) : Prop := x <> 0.\n\n(**\n  Accepts one ring element, x, and asserts\n  that x is the left identity element.\n*)\nDefinition sum_is_id_l := Monoid.is_id_l E sum.\n\n(**\n  Accepts one ring element, x, and asserts\n  that x is the right identity element.\n*)\nDefinition sum_is_id_r := Monoid.is_id_r E sum.\n\n(**\n  Accepts one ring element, x, and asserts\n  that x is the identity element.\n*)\nDefinition sum_is_id := Monoid.is_id E sum.\n\n(**\n  Represents the abelian group formed by\n  addition over E.\n*)\nDefinition sum_abelian_group\n  := Abelian_Group.abelian_group E 0 {+} sum_is_assoc sum_is_comm sum_id_l sum_inv_l_ex.\n\n(**\n  Represents the group formed by addition\n  over E.\n*)\nDefinition sum_group\n  := Abelian_Group.op_group sum_abelian_group.\n\n(**\n  Represents the monoid formed by addition\n  over E.\n*)\nDefinition sum_monoid\n  := Abelian_Group.op_monoid sum_abelian_group.\n\n(** Proves that 0 is the right identity element. *)\nTheorem sum_id_r\n  :  sum_is_id_r 0.\nProof Abelian_Group.op_id_r sum_abelian_group.\n\n(** Proves that 0 is the identity element. *)\nTheorem sum_id\n  :  sum_is_id 0.\nProof Abelian_Group.op_id sum_abelian_group.\n\n(**\n  Accepts two elements, x and y, and\n  asserts that y is x's left inverse.\n*)\nDefinition sum_is_inv_l\n  := Abelian_Group.op_is_inv_l sum_abelian_group.\n\n(**\n  Accepts two elements, x and y, and\n  asserts that y is x's right inverse.\n*)\nDefinition sum_is_inv_r\n  := Abelian_Group.op_is_inv_r sum_abelian_group.\n\n(**\n  Accepts two elements, x and y, and\n  asserts that y is x's inverse.\n*)\nDefinition sum_is_inv\n  := Abelian_Group.op_is_inv sum_abelian_group.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has a left inverse.\n*)\nDefinition sum_has_inv_l := Abelian_Group.has_inv_l sum_abelian_group.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has a right inverse.\n*)\nDefinition sum_has_inv_r := Abelian_Group.has_inv_r sum_abelian_group.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has an inverse.\n*)\nDefinition sum_has_inv := Abelian_Group.has_inv sum_abelian_group.\n\n(** Asserts that every element has a right inverse. *)\nTheorem sum_inv_r_ex\n  :  forall x : E, exists y : E, sum_is_inv_r x y.\nProof Abelian_Group.op_inv_r_ex sum_abelian_group.\n\n(** Proves that the left identity element is unique. *)\nTheorem sum_id_l_uniq\n  :  forall x : E, Monoid.is_id_l E {+} x -> x = 0.\nProof Abelian_Group.op_id_l_uniq sum_abelian_group.\n\n(** Proves that the right identity element is unique. *)\nTheorem sum_id_r_uniq\n  :  forall x : E, Monoid.is_id_r E {+} x -> x = 0.\nProof Abelian_Group.op_id_r_uniq sum_abelian_group.\n\n(** Proves that the identity element is unique. *)\nTheorem sum_id_uniq\n  :  forall x : E, Monoid.is_id E {+} x -> x = 0.\nProof Abelian_Group.op_id_uniq sum_abelian_group.\n\n(**\n  Proves that for every group element, x,\n  its left and right inverses are equal.\n*)\nTheorem sum_inv_l_r_eq\n  :  forall x y : E, sum_is_inv_l x y -> forall z : E, sum_is_inv_r x z -> y = z.\nProof Abelian_Group.op_inv_l_r_eq sum_abelian_group.\n\n(**\n  Proves that the inverse relation is\n  symmetrical.\n*)\nTheorem sum_inv_sym\n  :  forall x y : E, sum_is_inv x y <-> sum_is_inv y x.\nProof Abelian_Group.op_inv_sym sum_abelian_group.\n\n(** Proves that an element's inverse is unique. *)\nTheorem sum_inv_uniq\n  :  forall x y z :  E, sum_is_inv x y -> sum_is_inv x z -> z = y.\nProof Abelian_Group.op_inv_uniq sum_abelian_group.\n\n(**\n  Proves that every group element has an\n  inverse.\n*)\nTheorem sum_inv_ex\n  :  forall x : E, exists y : E, sum_is_inv x y.\nProof Abelian_Group.op_inv_ex sum_abelian_group.\n\n(**\n  Proves explicitly that every element has a\n  unique inverse.\n*)\nTheorem sum_inv_uniq_ex\n  :  forall x : E, exists! y : E, sum_is_inv x y.\nProof Abelian_Group.op_inv_uniq_ex sum_abelian_group.\n\n(** Proves the left introduction rule. *)\nTheorem sum_intro_l\n  :  forall x y z : E, x = y -> z + x = z + y.\nProof Abelian_Group.op_intro_l sum_abelian_group.\n\n(** Proves the right introduction rule. *)\nTheorem sum_intro_r\n  :  forall x y z : E, x = y -> x + z = y + z.\nProof Abelian_Group.op_intro_r sum_abelian_group.\n\n(** Proves the left cancellation rule. *)\nTheorem sum_cancel_l\n  :   forall x y z : E, z + x = z + y -> x = y.\nProof Abelian_Group.op_cancel_l sum_abelian_group.\n\n(** Proves the right cancellation rule. *)\nTheorem sum_cancel_r\n  :   forall x y z : E, x + z = y + z -> x = y.\nProof Abelian_Group.op_cancel_r sum_abelian_group.\n\n(**\n  Proves that an element's left inverse\n  is unique.\n*)\nTheorem sum_inv_l_uniq\n  :  forall x y z : E, sum_is_inv_l x y -> sum_is_inv_l x z -> z = y.\nProof Abelian_Group.op_inv_l_uniq sum_abelian_group.\n\n(**\n  Proves that an element's right inverse\n  is unique.\n*)\nTheorem sum_inv_r_uniq\n  :  forall x y z : E, sum_is_inv_r x y -> sum_is_inv_r x z -> z = y.\nProof Abelian_Group.op_inv_r_uniq sum_abelian_group.\n\n(**\n  Proves that 0 is its own left additive\n  inverse.\n*)\nTheorem sum_0_inv_l\n  :  sum_is_inv_l 0 0.\nProof Abelian_Group.op_inv_0_l sum_abelian_group.\n\n(**\n  Proves that 0 is its own right additive\n  inverse.\n*)\nTheorem sum_0_inv_r\n  :  sum_is_inv_r 0 0.\nProof Abelian_Group.op_inv_0_r sum_abelian_group.\n\n(** Proves that 0 is it's own additive inverse. *)\nTheorem sum_0_inv\n  :  sum_is_inv 0 0.\nProof Abelian_Group.op_inv_0 sum_abelian_group.\n\n(**\n  Proves that the identity element has a\n  left inverse.\n*)\nTheorem sum_has_inv_l_0\n  :  sum_has_inv_l 0.\nProof Abelian_Group.op_has_inv_l_0 sum_abelian_group.\n\n(**\n  Proves that the identity element has a\n  right inverse.\n*)\nTheorem sum_has_inv_r_0\n  :  sum_has_inv_r 0.\nProof Abelian_Group.op_has_inv_r_0 sum_abelian_group.\n\n(**\n  Proves that the identity element has an\n  inverse.\n*)\nTheorem sum_has_inv_0\n  :  sum_has_inv 0.\nProof Abelian_Group.op_has_inv_0 sum_abelian_group.\n\n(**\n  Proves that if an element's, x, inverse\n  equals 0, x equals 0.\n*)\nTheorem sum_inv_0_eq_0\n  :  forall x : E, sum_is_inv x 0 -> x = 0.\nProof Abelian_Group.op_inv_0_eq_0 sum_abelian_group.\n\n(**\n  Proves that 0 is the only element whose\n  additive inverse is 0.\n*)\nTheorem sum_inv_0_uniq\n  :  unique (fun x => sum_is_inv x 0) 0.\nProof Abelian_Group.op_inv_0_uniq sum_abelian_group.\n\n(** Represents strongly-specified negation. *)\nDefinition sum_neg_strong\n  :  forall x : E, { y | sum_is_inv x y }\n  := Abelian_Group.op_neg_strong sum_abelian_group.\n\n(** Represents negation. *)\nDefinition sum_neg \n  :  E -> E\n  := Abelian_Group.op_neg sum_abelian_group.\n\nNotation \"{-}\" := (sum_neg) : ring_scope.\n\nNotation \"- x\" := (sum_neg x) : ring_scope.\n\n(**\n  Asserts that the negation returns the inverse\n  of its argument.\n*)\nDefinition sum_neg_def \n  :  forall x : E, sum_is_inv x (- x)\n  := Abelian_Group.op_neg_def sum_abelian_group.\n\n(** Proves that negation is one-to-one *)\nDefinition sum_neg_inj\n  :  is_injective E E {-}\n  := Abelian_Group.op_neg_inj sum_abelian_group.\n\n(** Proves the cancellation property for negation. *)\nTheorem sum_cancel_neg\n  :  forall x : E, - (- x) = x.\nProof Abelian_Group.op_cancel_neg sum_abelian_group.\n\n(** Proves that negation is onto *)\nTheorem sum_neg_onto\n  :  is_onto E E {-}.\nProof Abelian_Group.op_neg_onto sum_abelian_group.\n\n(** Proves that negation is surjective *)\nTheorem sum_neg_bijective\n  :  is_bijective E E {-}.\nProof Abelian_Group.op_neg_bijective sum_abelian_group.\n\n(** Proves that neg x = y -> neg y = x *)\nTheorem sum_neg_rev\n  :  forall x y : E, - x = y -> - y = x.\nProof Abelian_Group.op_neg_rev sum_abelian_group.\n\n(**\n  Proves that the left inverse of x + y is -y + -x.\n*)\nTheorem sum_neg_distrib_inv_l\n  :  forall x y : E, sum_is_inv_l (x + y) (- y + - x).\nProof Abelian_Group.op_neg_distrib_inv_l sum_abelian_group.\n\n(**\n  Proves that the right inverse of x + y is -y + -x.\n*)\nTheorem sum_neg_distrib_inv_r\n  :  forall x y : E, sum_is_inv_r (x + y) (- y + - x).\nProof Abelian_Group.op_neg_distrib_inv_r sum_abelian_group.\n\n(**\n  Proves that the inverse of x + y is -y + -x.\n*)\nTheorem sum_neg_distrib_inv\n  :  forall x y : E, sum_is_inv (x + y) (- y + - x).\nProof Abelian_Group.op_neg_distrib_inv sum_abelian_group.\n\n(**\n  Proves that negation is distributive: i.e.\n  -(x + y) = -y + -x.\n*)\nTheorem sum_neg_distrib\n  :  forall x y : E, - (x + y) = - y + - x.\nProof Abelian_Group.op_neg_distrib sum_abelian_group.\n\n(** Proves that 0's negation is 0. *)\nTheorem sum_0_neg\n  :  - 0 = 0.\nProof\n  proj2 (sum_neg_def 0)\n  || a = 0 @a by <- sum_id_l (- 0).\n\n(**\n  Proves that if an element's, x, negation\n  equals 0, x must equal 0.\n*)\nTheorem sum_neg_0\n  :  forall x : E, - x = 0 -> x = 0.\nProof\n  fun x H\n    => proj2 (sum_neg_def x)\n      || x + a = 0 @a by <- H\n      || a = 0     @a by <- sum_id_r x.\n\n(**\n  Prove that 0 is the only element whose additive\n  inverse (negation) equals 0.\n*)\nTheorem sum_neg_0_uniq\n  :  unique (fun x => - x = 0) 0.\nProof\n  conj sum_0_neg \n    (fun x H => eq_sym (sum_neg_0 x H)).\n\n(**\n  Accepts one element, x, and asserts\n  that x is the left identity element.\n*)\nDefinition prod_is_id_l := Monoid.is_id_l E prod.\n\n(**\n  Accepts one element, x, and asserts\n  that x is the right identity element.\n*)\nDefinition prod_is_id_r := Monoid.is_id_r E prod.\n\n(**\n  Accepts one element, x, and asserts\n  that x is the identity element.\n*)\nDefinition prod_is_id := Monoid.is_id E prod.\n\n(** Represents the monoid formed by op over E. *)\nDefinition prod_monoid := Monoid.monoid E 1 {#} prod_is_assoc prod_id_l prod_id_r.\n\n(** Proves that 1 is the identity element. *)\nTheorem prod_id\n  :  prod_is_id 1.\nProof Monoid.op_id prod_monoid.\n\n(** Proves that the left identity element is unique. *)\nTheorem prod_id_l_uniq\n  :  forall x : E, (Monoid.is_id_l E prod x) -> x = 1.\nProof Monoid.op_id_l_uniq prod_monoid.\n\n(** Proves that the right identity element is unique. *)\nTheorem prod_id_r_uniq\n  :  forall x : E, (Monoid.is_id_r E prod x) -> x = 1.\nProof Monoid.op_id_r_uniq prod_monoid.\n\n(** Proves that the identity element is unique. *)\nTheorem prod_id_uniq\n  :  forall x : E, (Monoid.is_id E prod x) -> x = 1.\nProof Monoid.op_id_uniq prod_monoid.\n\n(** Proves the left introduction rule. *)\nTheorem prod_intro_l\n  :  forall x y z : E, x = y -> z # x = z # y.\nProof Monoid.op_intro_l prod_monoid.\n\n(** Proves the right introduction rule. *)\nTheorem prod_intro_r\n  :  forall x y z : E, x = y -> x # z = y # z.\nProof Monoid.op_intro_r prod_monoid.\n\n(**\n  Accepts two elements, x and y, and\n  asserts that y is x's left inverse.\n*)\nDefinition prod_is_inv_l := Monoid.op_is_inv_l prod_monoid.\n\n(**\n  Accepts two elements, x and y, and\n  asserts that y is x's right inverse.\n*)\nDefinition prod_is_inv_r := Monoid.op_is_inv_r prod_monoid.\n\n(**\n  Accepts two elements, x and y, and\n  asserts that y is x's inverse.\n*)\nDefinition prod_is_inv := Monoid.op_is_inv prod_monoid.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has a left inverse.\n*)\nDefinition prod_has_inv_l := Monoid.has_inv_l prod_monoid.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has a right inverse.\n*)\nDefinition prod_has_inv_r := Monoid.has_inv_r prod_monoid.\n\n(**\n  Accepts one argument, x, and asserts that\n  x has an inverse.\n*)\nDefinition prod_has_inv := Monoid.has_inv prod_monoid.\n\n(**\n  Proves that the left and right inverses of\n  an element must be equal.\n*)\nTheorem prod_inv_l_r_eq\n  :  forall x y : E, prod_is_inv_l x y -> forall z : E, prod_is_inv_r x z -> y = z.\nProof Monoid.op_inv_l_r_eq prod_monoid.\n\n(**\n  Proves that the inverse relationship is\n  symmetric.\n*)\nTheorem prod_inv_sym\n  :  forall x y : E, prod_is_inv x y <-> prod_is_inv y x.\nProof Monoid.op_inv_sym prod_monoid.\n\n(**\n  Proves the left cancellation law for elements\n  possessing a left inverse.\n*)\nTheorem prod_cancel_l\n  :  forall x y z : E, prod_has_inv_l z -> z # x = z # y -> x = y.\nProof Monoid.op_cancel_l prod_monoid.\n\n(**\n  Proves the right cancellation law for\n  elements possessing a right inverse.\n*)\nTheorem prod_cancel_r \n  :  forall x y z : E, prod_has_inv_r z -> x # z = y # z -> x = y.\nProof Monoid.op_cancel_r prod_monoid.\n\n(**\n  Proves that an element's left inverse\n  is unique.\n*)\nTheorem prod_inv_l_uniq\n  :  forall x : E, prod_has_inv_r x -> forall y z : E, prod_is_inv_l x y -> prod_is_inv_l x z -> z = y.\nProof Monoid.op_inv_l_uniq prod_monoid.\n\n(**\n  Proves that an element's right inverse\n  is unique.\n*)\nTheorem prod_inv_r_uniq\n  :  forall x : E, prod_has_inv_l x -> forall y z : E, prod_is_inv_r x y -> prod_is_inv_r x z -> z = y.\nProof Monoid.op_inv_r_uniq prod_monoid.\n\n(**\n  Proves that an element's inverse is unique.\n\n  Note: this theorem is defined as transparent to\n  allow a theorem in the field module to compile.\n*)\nDefinition prod_inv_uniq\n  :  forall x y z : E, prod_is_inv x y -> prod_is_inv x z -> z = y\n  := Monoid.op_inv_uniq prod_monoid.\n\n(**\n  Proves that the identity element is its own\n  left inverse.\n*)\nTheorem prod_inv_1_l\n  :  prod_is_inv_l 1 1.\nProof Monoid.op_inv_0_l prod_monoid.\n\n(**\n  Proves that the identity element is its own\n  right inverse.\n*)\nTheorem prod_inv_1_r\n  :  prod_is_inv_r 1 1.\nProof Monoid.op_inv_0_l prod_monoid.\n\n(**\n  Proves that the identity element is its own\n  inverse.\n*)\nTheorem prod_inv_1\n  :  prod_is_inv 1 1.\nProof Monoid.op_inv_0 prod_monoid.\n\n(** Proves that 1 has a left multiplicative inverse. *)\nTheorem prod_has_inv_l_1\n  :  prod_has_inv_l 1.\nProof Monoid.op_has_inv_l_0 prod_monoid.\n\n(** Proves that 1 has a right multiplicative inverse. *)\nTheorem prod_has_inv_r_1\n  :  prod_has_inv_r 1.\nProof Monoid.op_has_inv_r_0 prod_monoid.\n\n(** Proves that 1 has a reciprical *)\nTheorem prod_has_inv_1\n  :  prod_has_inv 1.\nProof Monoid.op_has_inv_0 prod_monoid.\n\n(**\n  Proves that if an element's, x, inverse\n  equals 0, x equals 0.\n*)\nTheorem prod_inv_1_eq_1\n  :  forall x : E, prod_is_inv x 1 -> x = 1.\nProof Monoid.op_inv_0_eq_0 prod_monoid.\n\n(**\n  Proves that 0 is the only element whose\n  inverse is 0.\n*)\nTheorem prod_inv_1_uniq\n  :  unique (fun x => prod_is_inv x 1) 1.\nProof Monoid.op_inv_0_uniq prod_monoid.\n\n(** Proves that 1 is its own left multiplicative inverse. *)\nTheorem recipr_1_l\n  :  prod_is_inv_l 1 1.\nProof Monoid.op_inv_0_l prod_monoid.\n\n(** Proves that 1 is its own right multiplicative inverse. *)\nTheorem recipr_1_r\n  :  prod_is_inv_r 1 1.\nProof Monoid.op_inv_0_r prod_monoid.\n\n(** Proves that 1 is its own recriprical. *)\nTheorem recipr_1\n  :  prod_is_inv 1 1.\nProof Monoid.op_inv_0 prod_monoid.\n\n(** TODO Reciprical functions (op_neg) from Monoid. *)\n\n(**\n  Asserts that multiplication is\n  distributive over addition.\n*)\nTheorem prod_sum_distrib\n  :  is_distrib E prod sum.\nProof conj prod_sum_distrib_l prod_sum_distrib_r.\n\n(**\n  Proves that 0 times every number equals 0.\n\n  0 x = 0 x\n  (0 + 0) x = 0 x\n  0 x + 0 x = 0 x\n        0 x = 0\n*)\nTheorem prod_0_l\n  :  forall x : E, 0 # x = 0.\nProof\n  fun x\n    => let H\n         : (0 # x) + (0 # x) = (0 # x) + 0\n         := eq_refl (0 # x)\n           || a # x = 0 # x         @a by (sum_id_l 0)\n           || a = 0 # x             @a by <- prod_sum_distrib_r x 0 0\n           || (0 # x) + (0 # x) = a @a by sum_id_r (0 # x)\n       in sum_cancel_l (0 # x) 0 (0 # x) H.\n\n(** Proves that 0 times every number equals 0. *)\nTheorem prod_0_r\n  :  forall x : E, x # 0 = 0.\nProof\n  fun x\n    => let H\n         :  (x # 0) + (x # 0) = 0 + (x # 0)\n         := eq_refl (x # 0)\n           || x # a = x # 0         @a by sum_id_r 0\n           || a = x # 0             @a by <- prod_sum_distrib_l x 0 0\n           || (x # 0) + (x # 0) = a @a by sum_id_l (x # 0)\n       in sum_cancel_r (x # 0) 0 (x # 0) H.\n\n(**\n  Proves that 0 does not have a left\n  multiplicative inverse.\n*)\nTheorem prod_0_inv_l\n  :  ~ prod_has_inv_l 0.\nProof\n  ex_ind\n    (fun x (H : x # 0 = 1)\n      => distinct_0_1 (H || a = 1 @a by <- prod_0_r x)).\n\n(**\n  Proves that 0 does not have a right\n  multiplicative inverse.\n*)\nTheorem prod_0_inv_r\n  :  ~ prod_has_inv_r 0.\nProof\n  ex_ind\n    (fun x (H : 0 # x = 1)\n      => distinct_0_1 (H || a = 1 @a by <- prod_0_l x)).\n\n(**\n  Proves that 0 does not have a multiplicative\n  inverse - I.E. 0 does not have a\n  reciprocal.\n*)\nTheorem prod_0_inv\n  :  ~ prod_has_inv 0.\nProof\n  ex_ind\n    (fun x H\n      => prod_0_inv_l\n           (ex_intro\n             (fun x\n                => prod_is_inv_l 0 x)\n             x (proj1 H))).\n\n(**\n  Proves that multiplicative inverses, when\n  they exist are always nonzero.\n*)\nTheorem prod_inv_0\n  :  forall x y : E, prod_is_inv x y -> nonzero y.\nProof\n  fun x y H (H0 : y = 0)\n    => distinct_0_1\n         (proj1 H\n          || a # x = 1 @a by <- H0\n          || a = 1     @a by <- prod_0_l x).\n\n(** Represents -1 and proves that it exists. *)\nDefinition E_n1_strong\n  :  { x : E | sum_is_inv 1 x }\n  := constructive_definite_description (sum_is_inv 1) (sum_inv_uniq_ex 1).\n\n(** Represents -1. *)\nDefinition E_n1 : E := proj1_sig E_n1_strong.\n\n(**\n  Defines a symbolic representation for -1\n  \n  Note: here we represent the inverse of 1\n  rather than the negation of 1. Letter we prove\n  that the negation equals the inverse.\n\n  Note: brackets are needed to ensure Coq parses\n  the symbol as a single token instead of a\n  prefixed function call.\n*)\nNotation \"{-1}\" := E_n1 : ring_scope.\n\n(** Asserts that -1 is the additive inverse of 1. *)\nTheorem E_n1_def\n  :  sum_is_inv 1 {-1}.\nProof proj2_sig E_n1_strong.\n\n(** Asserts that -1 is the left inverse of 1. *)\nTheorem E_n1_inv_l\n  :  sum_is_inv_l 1 {-1}.\nProof proj1 E_n1_def.\n\n(** Asserts that -1 is the right inverse of 1. *)\nTheorem E_n1_inv_r\n  :  sum_is_inv_r 1 {-1}.\nProof proj2 E_n1_def.\n\n(**\n  Asserts that every additive inverse\n  of 1 must be equal to -1.\n*)\nTheorem E_n1_uniq\n  :  forall x : E, sum_is_inv 1 x -> x = {-1}.\nProof fun x => sum_inv_uniq 1 {-1} x E_n1_def.\n\n(**\n  Proves that -1 * x equals the multiplicative\n  inverse of x.\n\n  -1 x + x = 0\n  -1 x + 1 x = 0\n  (-1 + 1) x = 0\n  0 x = 0\n  0 = 0\n*) \nTheorem prod_n1_x_inv_l\n  :  forall x : E, sum_is_inv_l x ({-1} # x).\nProof\n  fun x\n    => prod_0_l x\n       || a # x = 0          @a by E_n1_inv_l\n       || a = 0              @a by <- prod_sum_distrib_r x {-1} 1\n       || ({-1} # x) + a = 0 @a by <- prod_id_l x.\n\n(**\n  Proves that x * -1 equals the multiplicative\n  inverse of x.\n\n  x -1 + x = 0\n*)\nTheorem prod_x_n1_inv_l\n  :  forall x : E, sum_is_inv_l x (x # {-1}).\nProof\n  fun x\n    => prod_0_r x\n       || x # a = 0          @a by E_n1_inv_l\n       || a = 0              @a by <- prod_sum_distrib_l x {-1} 1\n       || (x # {-1}) + a = 0 @a by <- prod_id_r x.\n\n(** Proves that x + -1 x = 0. *)\nTheorem prod_n1_x_inv_r\n  :  forall x : E, sum_is_inv_r x ({-1} # x).\nProof\n  fun x\n    => prod_0_l x\n       || a # x = 0          @a by E_n1_inv_r\n       || a = 0              @a by <- prod_sum_distrib_r x 1 {-1}\n       || a + ({-1} # x) = 0 @a by <- prod_id_l x.\n\n(** Proves that x + x -1 = 0. *)\nTheorem prod_x_n1_inv_r\n  :  forall x : E, sum_is_inv_r x (x # {-1}).\nProof\n  fun x\n    => prod_0_r x\n       || x # a = 0          @a by E_n1_inv_r\n       || a = 0              @a by <- prod_sum_distrib_l x 1 {-1}\n       || a + (x # {-1}) = 0 @a by <- prod_id_r x.\n\n(** Proves that -1 x is the additive inverse of x. *)\nTheorem prod_n1_x_inv\n  :  forall x : E, sum_is_inv x ({-1} # x).\nProof fun x => conj (prod_n1_x_inv_l x) (prod_n1_x_inv_r x).\n\n(** Proves that x -1 is the additive inverse of x. *)\nTheorem prod_x_n1_inv\n  :  forall x : E, sum_is_inv x (x # {-1}).\nProof fun x => conj (prod_x_n1_inv_l x) (prod_x_n1_inv_r x).\n\n(**\n  Proves that multiplying by -1 is equivalent\n  to negation.\n*)\nTheorem prod_n1_neg\n  :  prod {-1} = {-}.\nProof\n  functional_extensionality\n    (prod {-1}) {-}\n    (fun x\n      => sum_inv_uniq x (- x) ({-1} # x)\n           (sum_neg_def x)\n           (prod_n1_x_inv x)).\n\n(**\n  Accepts one element, x, and proves that\n  x -1 equals the additive negation of x.\n*)\nTheorem prod_x_n1_neg\n  :  forall x : E, x # {-1} = - x.\nProof\n  fun x\n    => sum_inv_uniq x (- x) (x # {-1})\n         (sum_neg_def x)\n         (prod_x_n1_inv x).\n\n(**\n  Accepts one element, x, and proves that\n  -1 x equals the additive negation of x.\n*)\nTheorem prod_n1_x_neg\n  :  forall x : E, {-1} # x = - x.\nProof\n  fun x\n    => sum_inv_uniq x (- x) ({-1} # x)\n         (sum_neg_def x)\n         (prod_n1_x_inv x).\n\n(** Proves that -1 x = x -1. *)\nTheorem prod_n1_eq\n  :  forall x : E, {-1} # x = x # {-1}.\nProof\n  fun x\n    => sum_inv_uniq x (x # {-1}) ({-1} # x)\n         (prod_x_n1_inv x)\n         (prod_n1_x_inv x).\n\n(** Proves that the additive negation of 1 equals -1. *)\nTheorem neg_1\n  :  {-} 1 = {-1}.\nProof\n  eq_refl ({-} 1)\n    || {-} 1 = a @a by prod_x_n1_neg 1\n    || {-} 1 = a @a by <- prod_id_l {-1}.\n\n(** Proves that the additive negation of -1 equals 1. *)\nTheorem neg_n1\n  :  {-} {-1} = 1.\nProof sum_neg_rev 1 {-1} neg_1.\n\n(**\n  Proves that -1 * -1 = 1.\n\n  -1 * -1 = -1 * -1\n  -1 * -1 = prod -1 -1\n  -1 * -1 = - -1\n  -1 * -1 = 1 \n*)\nTheorem prod_n1_n1\n  :  {-1} # {-1} = 1.\nProof\n  eq_refl ({-1} # {-1})\n    || {-1} # {-1} = a @a by <- prod_n1_x_neg {-1}\n    || {-1} # {-1} = a @a by <- neg_n1.\n\n(**\n  Proves that -1 is its own multiplicative\n  inverse.\n*)\nTheorem E_n1_inv\n  :  prod_is_inv {-1} {-1}.\nProof conj prod_n1_n1 prod_n1_n1.\n\nEnd Theorems.\n\nEnd Ring.\n\nNotation \"0\" := (Ring.E_0) : ring_scope.\n\nNotation \"1\" := (Ring.E_1) : ring_scope.\n\nNotation \"x + y\" := (Ring.sum x y) (at level 50, left associativity) : ring_scope.\n\nNotation \"{+}\" := (Ring.sum) : ring_scope.\n\nNotation \"{-}\" := (Ring.sum_neg _) : ring_scope.\n\nNotation \"- x\" := (Ring.sum_neg _ x) : ring_scope.\n\nNotation \"x # y\" := (Ring.prod x y) (at level 50, left associativity) : ring_scope.\n\nNotation \"{#}\" := (Ring.prod) : ring_scope.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/functional-algebra/ring.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7007688796465175}}
{"text": "From NaturalNumbers Require Export Base Tutorial Addition.\n\nRequire Import Ring_theory.\nRequire Export Ring.\n\nModule SemiRingFaking.\n    (* Some stuff to fake the `simpl` tactic to only affect\n    our own version of addition by defining some sort of fake \n    multiplication and a bunch of axioms to make the semi-ring \n    structure hold *)\n\n    Axiom _fake_mul : mynat -> mynat -> mynat.\n    Axiom _fake_one : mynat.\n\n    Axiom _fake_one_mul : forall a : mynat, _fake_mul _fake_one a = a.\n    Axiom _fake_zero_mul : forall a : mynat, _fake_mul 0 a = 0.\n    Axiom _fake_mul_comm : forall (a b: mynat), _fake_mul a b = _fake_mul b a.\n    Axiom _fake_mul_assoc : forall (a b c: mynat), _fake_mul a (_fake_mul b c) = _fake_mul (_fake_mul a b) c.\n    Axiom _fake_distr_mul : forall (a b c : mynat), _fake_mul (a + b) c = (_fake_mul a c) + (_fake_mul b c).\n\n    Lemma assoc_add (a b c : mynat) : a + (b + c) = (a + b) + c.\n    Proof.\n        rewrite add_assoc; easy.\n    Qed.\n\n    Definition mynat_semi_ring :=\n        mk_srt 0 _fake_one add _fake_mul (@eq _) \n        zero_add add_comm assoc_add _fake_one_mul _fake_zero_mul _fake_mul_comm \n        _fake_mul_assoc _fake_distr_mul.\n\nEnd SemiRingFaking.\n\nAdd Ring _fake_mynat_ring : SemiRingFaking.mynat_semi_ring.\n\nLemma test (a b c d e : mynat) : (((a+b)+c)+d)+e=(c+((b+e)+a))+d.\nProof.\n    ring.\nQed.\n\nFixpoint mul (n m : mynat) : mynat :=\n    match m with\n    | O => O\n    | S p => (mul n p) + n\n    end.\n\nInfix \"*\" := mul.\nNotation \"(*)\" := mul (only parsing).\nNotation \"( f *)\" := (mul f) (only parsing).\nNotation \"(* f )\" := (fun g => mul g f) (only parsing).\n\nFact mul_zero (a : mynat) : a * 0 = 0.\nProof.\n    trivial.\nQed.\n\nFact mul_succ (a b : mynat) : a * S b = a * b + a.\nProof.\n    trivial.\nQed.\n\n(* Level 0 data *)\n(* name `zero_mul` *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 0 prologue *)\n(*\nI have just defined multiplication for you. It is defined to satisfy the following\ntwo statements:\n<ul>\n    <li>`Fact mul_zero (a : mynat) : a * 0 = 0.`</li>\n    <li>`Fact mul_succ (a b : mynat) : a * S b = a * b + a.`</li>\n</ul>\nBasically, we have defined multiplication inductively on the second variable.\n\nYou can still use all your theorems from Addition World, even from levels you have\nnot completed yet! I do recommend you complete all of them before you continue,\njust so you are familiar with them.\n\nAnyway, just like for addition in the previous world, we know next to nothing \nabout multiplication so let's start proving some lemmas! Remember that the\n`induction` tactic will come in very useful, like in the previous world.\n*)\nLemma zero_mul (m : mynat) : 0 * m = 0.\nProof.\n    induction m as [| ? H].\n    - rewrite mul_zero; easy.\n    - rewrite mul_succ. easy.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 1 data *)\n(* name `mul_one` *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 1 prologue *)\n(*\nRecall that you can find all the theorems we have shown before in the side\nmenu on the left. In this level in particular, we will need to use\n```\n#Fact one_eq_succ_zero : 1 = S 0.\n```\nLet's prove that `1` is actually the neutral element for multiplication\n(at least on the right, since we don't know that multiplication is commutative yet)!\n*)\nLemma mul_one (m : mynat) : m * 1 = m.\nProof.\n    rewrite one_eq_succ_zero, mul_succ.\n    rewrite mul_zero, zero_add.\n    reflexivity.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 2 *)\n(* Level 2 data *)\n(* name `one_mul` *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 2 prologue *)\n(*\nLet's show that `1` is also a unit on the left. the following theorems\nmay be useful:\n<ul>\n    <li>`Fact one_eq_succ_zero : 1 = S 0.`</li>\n    <li>`Fact succ_eq_add_one a : S a = a + 1`</li>\n</ul>\n*)\nLemma one_mul (m : mynat) : 1 * m = m.\nProof.\n    induction m as [| ? H].\n    - trivial.\n    - rewrite mul_succ.\n      now rewrite H.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 3 *)\n(* Level 3 data *)\n(* name `mul_add` *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 3 prologue *)\n(*\nThe goal for this world is to show `mul_comm` and `mul_assoc`,\ni.e. that multiplication is commutative (`a * b = b * a`) and associative\n(`(a * b) * c = a * (b * c)`). However, we also want to show\nhow multiplication interacts with addition. In this level\nwe show that multiplication is left distributive. Note that\nthe name of the lemma (`mul_add`) refers to the order in which\nthe operations are written here, and is not `mul_left_distrib`\nor something like that, which would be much harder to remember!\n*)\nLemma mul_add (t a b : mynat) : t * (a + b) = t * a + t * b.\nProof.\n    induction b as [| ? H].\n    - easy.\n    - rewrite add_succ.\n      repeat rewrite mul_succ.\n      rewrite H.\n      ring.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 4 *)\n(* Level 4 data *)\n(* name `mul_assoc` *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 4 prologue *)\n(*\nAlright, time to show that multiplication is associative!\n\nBy the way, did you know you could add the tactic `now` before\nany tactic you type, and it will check if it can be easily\nshown (for example by `reflexivity`) after performing the\ntactic you write after it. So for example, you could write\n```\nnow rewrite mul_add.\n```\nto perform a `rewrite mul_add`, and then check if the proof\ncan easily be finished. You can think of this as if it was\nthe same as\n```\nrewrite mul_add.\nreflexivity.\n``` \nfor now. Try it out!\n*)\nLemma mul_assoc (a b c : mynat) : (a * b) * c = a * (b * c).\nProof.\n    induction c as [| ? H].\n    - repeat rewrite mul_zero; easy.\n    - repeat rewrite mul_succ.\n      rewrite H.\n      now rewrite mul_add.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 5 *)\n(* Level 5 data *)\n(* name `succ_mul` *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 5 prologue *)\n(* \nThe `ring` tactic is powerful, but not almighty. For example,\nit does not know that it can rewrite expressions inside of\nthe successor function `S`, so if we have a goal of the form\n```S (a + b) = S (b + a)```\nour `ring` tactic won't solve it. Thankfully, we know that\n`succ_eq_add_one`, which we can use to turn this goal into\n```a + b + 1 = b + a + 1```\nwhich our `ring` tactic can solve!\n*)\nLemma succ_mul (a b : mynat) : (S a) * b = a * b + b.\nProof.\n    induction b as [| ? H].\n    - repeat rewrite mul_zero; easy.\n    - repeat rewrite mul_succ.\n      rewrite H.\n      repeat rewrite add_succ.\n      repeat rewrite succ_eq_add_one.\n      ring.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 6 *)\n(* Level 6 data *)\n(* name `add_mul` *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 6 prologue *)\n(*\nWe already have `mul_add`, but we have not shown how multiplication\ninteracts on the right with addition. If you end up with a goal\nthat only contains addition, with some messy parentheses or different\norders of terms, try not to mess with `rewrite add_comm` and friends, \nbut use the powerful `ring` tactic instead!\n*)\nLemma add_mul (a b t : mynat) : (a + b) * t = a * t + b * t.\nProof.\n    induction t as [| ? H].\n    - now repeat rewrite mul_zero.\n    - repeat rewrite mul_succ.\n      rewrite H.\n      ring.\nQed.\n(* Level epilogue *)\n(* Level end *)\n\n(* Level 7 *)\n(* Level 7 data *)\n(* name `mul_comm` (boss level!) *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 7 prologue *)\n(*\nThe boss level for this world! You should be well prepared,\nif you've done all the levels so far. \n*)\nLemma mul_comm (a b : mynat) : a * b = b * a.\nProof.\n    induction b as [| ? H].\n    - now rewrite mul_zero, zero_mul.\n    - rewrite mul_succ, succ_mul.\n      now rewrite H.\nQed.\n(* Level epilogue *)\n(*\nNow we know that `mynat` is a commutative semiring! Just one\nmore level and we will be able to beef up our `ring` tactic!\n*)\n(* Level end *)\n\n(* Level 8 *)\n(* Level 8 data *)\n(* name `mul_left_assoc` *)\n(* tactics ring *)\n(* theorems mul_succ *)\n(* Level 8 prologue *)\n(*\nEquipped with\n<ul>\n    <li>`Lemma mul_assoc (a b c : mynat) : (a * b) * c = a * (b * c).`</li>\n    <li>`Lemma mul_comm (a b : mynat) : a * b = b * a.`</li>\n</ul>\nthis level should be a piece of cake!\n*)\nLemma mul_left_assoc (a b c : mynat) : a * (b * c) = (a * b) * c.\nProof.\n    rewrite <- mul_assoc.\n    reflexivity.\nQed.\n(* Level epilogue *)\n(*\nAnd now, after I invert `add_assoc` into \n```\n#Lemma add_left_assoc (a b c : mynat) : a + (b + c) = (a + b) + c.\n```\nI can type\n```\n#Definition mynat_semi_ring : semi_ring_theory 0 1 add mul (@eq _).\n#Proof.\n#    constructor.\n#    - exact zero_add.\n#    - exact add_comm.\n#    - exact add_left_assoc.\n#    - exact one_mul.\n#    - exact zero_mul.\n#    - exact mul_comm.\n#    - exact mul_left_assoc.\n#    - exact add_mul.\n#Qed.\n#\n#Add Ring mynat_ring : mynat_semi_ring.\n```\nand our `ring` tactic will now also solve basic\nequations involving multiplications for us!\n\nIf you click \"Next Level\", you will be sent to Power World.\nThis world is optional, but can be seen as kind of a \"Boss World\",\ninvolving the theorems we have shown in Addition and Multiplication World.\n\nIf you want to skip this world though, you can go back to the main menu to\ngo to Function World instead!\n*)\n(* Level end *)\n\nLemma add_left_assoc (a b c : mynat) : a + (b + c) = (a + b) + c.\nProof.\n    rewrite <- add_assoc.\n    reflexivity.\nQed.\n\nDefinition mynat_semi_ring : semi_ring_theory 0 1 add mul (@eq _).\nProof.\n    constructor.\n    - exact zero_add.\n    - exact add_comm.\n    - exact add_left_assoc.\n    - exact one_mul.\n    - exact zero_mul.\n    - exact mul_comm.\n    - exact mul_left_assoc.\n    - exact add_mul.\nQed.\n\nAdd Ring mynat_ring : mynat_semi_ring.", "meta": {"author": "DenSinH", "repo": "natural-numbers-game", "sha": "db704cdc7f0bf5f02017e94d86a6adc82ed55793", "save_path": "github-repos/coq/DenSinH-natural-numbers-game", "path": "github-repos/coq/DenSinH-natural-numbers-game/natural-numbers-game-db704cdc7f0bf5f02017e94d86a6adc82ed55793/webapp/coq/Multiplication.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7007688772807527}}
{"text": "\nRequire Import List Omega.\n\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\nExtraction Language Ocaml.\n\n(* Extract Inductive nat => \"Prelude.Int\" [\"0\" \"\\x -> x + 1\"] *)\n(*                             \"\\zero succ n -> *)\n(*                               if n == 0 then zero () else succ (n-1)\". *)\n\nExtract Inductive nat => \"int\"\n  [ \"0\" \"(fun x -> x + 1)\" ]\n  \"(fun zero succ n ->\n    if n=0 then zero () else succ (n-1))\".\n\nInductive bintree : Type :=\n| leaf : bintree\n| branch : nat -> bintree -> bintree -> bintree.\n\n\nFixpoint lookup (n:nat) (t:bintree) : Prop :=\n  match t with\n  | leaf => False\n  | branch n' l r =>\n    if eq_nat_dec n n' \n    then True\n    else if le_lt_dec n n'\n    then lookup n l\n    else lookup n r\n  end.\n\nFixpoint insert (x : nat) (t:bintree) : bintree :=\n  match t with\n  | leaf => branch x leaf leaf\n  | branch y l r =>\n    if le_dec x y\n    then branch y (insert x l) r\n    else branch y l (insert x r)\n  end.\n\nFixpoint list2bin (l : list nat) : bintree :=\n  match l with\n  | [] => leaf\n  | x :: xs => insert x (list2bin xs)\n  end.\n\n\nFixpoint inorder (t : bintree) : list nat :=\n  match t with\n  | leaf => []\n  | branch x l r => inorder l ++ (x :: inorder r)\n  end.\n\nDefinition binsort (l : list nat) : list nat :=\n  inorder (list2bin l).\n\nExtraction \"binsort_core.ml\" binsort.\n\nExample lookup_1 : lookup 1 (branch 1 leaf leaf).\nProof. reflexivity. Qed.\n\nExample lookup_2 : lookup 2 (branch 1 leaf (branch 2 leaf leaf)).\nProof. simpl. reflexivity. Qed.\n\nExample lookup_3 : lookup 3 (branch 4 (branch 3 leaf leaf) (branch 5 leaf leaf)).\nProof. reflexivity. Qed.\n\nExample lookup_4 : ~ (lookup 4 (branch 1 leaf (branch 2 leaf leaf))).\nProof. unfold not. simpl. intros. assumption. Qed.\n\nLemma lookup_left : forall l r x n, lookup x (branch n l r) -> x < n -> lookup x l.\nProof.\n  intros. unfold lookup in H.\n  destruct (Nat.eq_dec x n); [omega | ].\n  destruct (le_lt_dec x n); [assumption | ].\n  unfold not in n0. contradiction n0. omega.\nQed.\n\nLemma lookup_right : forall l r x n, lookup x (branch n l r) -> n < x -> lookup x r.\nProof.\n  intros. unfold lookup in H.\n  destruct (Nat.eq_dec x n); [omega | ].\n  destruct (le_lt_dec x n); [| assumption].\n  unfold not in n0. contradiction n0. omega.\nQed.\n\nInductive valid : forall (t : bintree), Prop :=\n| val_leaf : valid leaf\n| val_cons : forall (l r : bintree) n,\n    valid l -> valid r ->\n    (forall x, lookup x l -> x <= n) ->\n    (forall x, lookup x r -> x > n) ->\n    valid (branch n l r).\n\nExample valid_1 : valid (leaf).\nProof. apply val_leaf. Qed.\n\nLemma valid_end : forall x, valid (branch x leaf leaf).\nProof.\n  induction x.\n  - apply (val_cons _ _ 0 val_leaf val_leaf); intros; contradiction H.\n  - apply (val_cons _ _ (S x) val_leaf val_leaf); intros; contradiction H.\nQed.\n\n\nLemma lookup_insert : forall t x y, valid t -> lookup x t -> lookup x (insert y t).\nProof.\n  intros. generalize dependent x. generalize dependent y.\n  induction H; intros; [inversion H0 | ].\n  intros. simpl in *. destruct (Nat.eq_dec x n).\n  destruct (le_dec y n).\n  - simpl. rewrite e. destruct (Nat.eq_dec n n); [assumption | ].\n    destruct (le_lt_dec n n); omega.\n  - simpl. destruct (Nat.eq_dec x n); [assumption | ].\n    rewrite e. destruct (le_lt_dec n n); omega.\n  - unfold not in n0. destruct (le_dec y n); simpl;\n    (destruct (Nat.eq_dec x n); [apply I | ]).\n    + destruct (le_lt_dec x n); [| assumption].\n      apply (IHvalid1 _ _ H3).\n    + destruct (le_lt_dec x n); [assumption |].\n      apply (IHvalid2 _ _ H3).\nQed.\n\nLemma lookup_branch_x : forall l r x, lookup x (branch x l r).\nProof.\n  induction l.\n  - intros. simpl. destruct (Nat.eq_dec x x); [apply I |].\n    destruct (le_lt_dec x x); omega.\n  - intros. simpl. destruct (Nat.eq_dec x x); [apply I |].\n    destruct (le_lt_dec x x); omega.\nQed.\n\nLemma insert_lookup_x : forall t x, valid t -> lookup x (insert x t).\nProof.\n  intros. generalize dependent x. assert (H' : valid t). assumption.\n  induction H; intros; simpl.\n  - destruct (Nat.eq_dec x x); [apply I |].\n    destruct (le_lt_dec x x); omega.\n  - destruct (le_dec x n).\n    + pose proof (IHvalid1 H n). destruct (insert n l); [inversion H3 |].\n      simpl in *. destruct (Nat.eq_dec x n); [apply I |].\n      destruct (le_lt_dec x n); [| omega].\n      apply (IHvalid1 H x).\n    + pose proof (IHvalid2 H0 n). destruct (insert n r); [inversion H3 |].\n      simpl in *. destruct (Nat.eq_dec x n); [apply I |] .\n      destruct (le_lt_dec x n); [omega |].\n      apply (IHvalid2 H0 x).\nQed.\n\nLemma lookup_branch : forall l r x n, valid (branch n l r) ->\n                                lookup x (branch n l r) ->\n                                x = n \\/ lookup x l \\/ lookup x r.\nProof.\n  intros. inversion H. unfold lookup in H0.\n  destruct (Nat.eq_dec x n); [(left; assumption) |].\n  destruct (le_lt_dec x n); right; [left | right]; assumption.\nQed.\n\nLemma insert_lookup : forall t x y,\n    valid t -> x <> y -> lookup x (insert y t) -> lookup x t.\nProof.\n  intros. generalize dependent x. generalize dependent y.\n  induction H; intros; simpl in *.\n  - destruct (Nat.eq_dec x y); [omega |].\n    destruct (le_lt_dec x y); omega.\n  - destruct (Nat.eq_dec x y); [omega |]; simpl.\n    destruct (Nat.eq_dec x n); [apply I |].\n    destruct (le_lt_dec x n).\n    + destruct (le_dec y n); simpl in H4.\n      * destruct (Nat.eq_dec x n); [omega | ].\n        {destruct (le_lt_dec x n); [ | omega ].\n          - apply IHvalid1 with (y := y); assumption.\n        }\n      * destruct (Nat.eq_dec x n); [omega | ].\n        destruct (le_lt_dec x n); [| omega]; assumption.\n    + destruct (le_dec y n); simpl in H4.\n      * destruct (Nat.eq_dec x n); [omega | ].\n        destruct (le_lt_dec x n); [ omega | assumption ].\n      * destruct (Nat.eq_dec x n); [omega | ].\n        destruct (le_lt_dec x n); [ omega | ].\n        apply IHvalid2 with (y := y). assumption. assumption.\nQed.\n\nLemma lookup_cases : forall t x y, valid t ->\n                              lookup x (insert y t) -> x = y \\/ lookup x t.\nProof.\n  intros. destruct (Nat.eq_dec x y); [(left ; assumption) |].\n  right. induction t.\n  - simpl in *. destruct (Nat.eq_dec x y); [omega | ].\n    destruct (le_lt_dec x y); assumption.\n  - simpl. destruct (Nat.eq_dec x n0); [apply I | ].\n    destruct (le_lt_dec x n0).\n    + simpl in H0. destruct (le_dec y n0).\n      * simpl in H0. destruct (Nat.eq_dec x n0); [omega |].\n        destruct (le_lt_dec x n0); [ | omega].\n        simpl in H. destruct (le_dec y n0); [ | omega].\n        inversion H. apply (IHt1 H4 H0).\n      * simpl in H0. destruct (Nat.eq_dec x n0); [omega |].\n        destruct (le_lt_dec x n0); [ | omega].\n        simpl in H. destruct (le_dec y n0); [ omega | assumption ].\n    + simpl in H0. destruct (le_dec y n0).\n      * simpl in H0. destruct (Nat.eq_dec x n0); [omega |].\n        destruct (le_lt_dec x n0); [ omega | ].\n        simpl in H. destruct (le_dec y n0); [ assumption | omega].\n      * simpl in H0. destruct (Nat.eq_dec x n0); [omega |].\n        destruct (le_lt_dec x n0); [ omega | ].\n        simpl in H. destruct (le_dec y n0); [ omega | ].\n        inversion H. apply (IHt2 H5 H0).\nQed.\n\nLemma insert_preserves : forall t x, valid t -> valid (insert x t).\nProof.\nintros. induction H.\n- simpl. constructor 2; (intros; try constructor; inversion H).\n- simpl. destruct (le_dec x n).\n  + apply val_cons; intros; [ assumption | assumption | | (apply H2; assumption)].\n    destruct (lookup_cases _ _ _ H H3); [omega | ].\n    apply (H1 _ H4).\n  + constructor 2; intros; [assumption | assumption | (apply H1; assumption) |].\n      intros. destruct (lookup_cases _ _ _ H0 H3); [omega | ].\n      apply H2. assumption.\nQed.\n\nLemma in_app_iff : forall A l l' (a:A),\n  In a (l++l') <-> In a l \\/ In a l'.\nProof.\n  intros. split.\n  - generalize dependent l'. induction l.\n    + simpl. intros. right. assumption.\n    + simpl. intros. destruct H; [(left; left; assumption) | ].\n      rewrite or_assoc. right. apply (IHl _ H).\n  - intros. generalize dependent l'. induction l.\n    + simpl. intros. destruct H; [contradiction H | assumption].\n    + simpl. intros. rewrite or_assoc in H.\n      destruct H; [(left; assumption) |].\n      right. apply (IHl _ H).\nQed.\n\nInductive ordered : list nat -> Prop :=\n| o_nil : ordered []\n| o_singleton x : ordered [x]\n| o_step x y xs : x <= y -> ordered (y :: xs) -> ordered (x :: y :: xs).\n\n\nLemma ordered_app (xs ys : list nat) \n  (Hxs : ordered xs) (Hys : ordered ys) \n  (H : match (rev xs), ys with\n       | x::_, y::_ => x <= y\n       | _, _ => True\n       end) :\n  ordered (xs ++ ys).\nProof.\n  induction Hxs; simpl in *; [assumption | |].\n  - destruct ys; [apply o_singleton |].\n    + apply (o_step x n ys H Hys).\n  - apply (o_step x y (xs ++ ys) H0).\n    + apply IHHxs. destruct (rev xs); simpl in *; apply H.\nQed.\n\nLemma lookup_in_inorder : forall t x, lookup x t -> In x (inorder t).\nProof.\n  induction t; intros; simpl in *; [assumption | ].\n  rewrite in_app_iff. destruct (Nat.eq_dec x n).\n  - right. rewrite e. apply in_eq.\n  - destruct (le_lt_dec x n).\n    + left. apply IHt1. assumption.\n    + right. apply in_cons. apply IHt2. assumption.\nQed.\n\nLemma order_cons (x:nat) (l:list nat )\n  (H1: ordered l)\n  (H2 : match l with\n  | [] => True\n  | y :: _ => x <= y\n  end) : ordered (x :: l).\nProof.\n  generalize dependent H2. induction H1; intros.\n  - apply o_singleton.\n  - apply o_step. assumption. apply o_singleton.\n  - apply o_step. assumption. apply o_step. assumption. assumption.\nQed.\n\nLemma lookup_tree : forall t n, {lookup n t} + {~(lookup n t)}.\nProof.\n  induction t; intros; simpl in *.\n  - right. unfold not. intros. assumption.\n  - destruct (Nat.eq_dec n0 n); [(left; apply I) |].\n    destruct (le_lt_dec n0 n); [apply IHt1 | apply IHt2 ].\nQed.\n\nLemma cons_ordered : forall l x, ordered (x :: l) -> ordered l.\nProof.\n  induction l.\n  - intros. apply o_nil.\n  - intros. inversion H. assumption.\nQed.\n\nLemma app_ordered_left : forall l1 l2, ordered (l1 ++ l2) -> ordered l1. \nProof.\n  induction l1; intros; [apply o_nil |].\n  simpl in *. apply order_cons.\n  - apply (IHl1 l2). inversion H; [apply o_nil | assumption].\n  - destruct l1; [apply I |].\n    inversion H. assumption.\nQed.  \n\nLemma app_sing : forall X (l1 l2 : list X) x,\n   l1 ++ (x :: l2) = (l1 ++ [x]) ++ l2.\nProof.\n  intros. replace (x :: l2) with ([x] ++ l2); [| reflexivity].\n  rewrite app_assoc. reflexivity.\nQed.\n\nLemma app_ordered_right: forall l2 l1, ordered (l1 ++ l2) -> ordered l2.\nProof.\n  induction l1; intros; [assumption |].\n  simpl in H. pose proof (cons_ordered _ _ H). apply (IHl1 H0).\nQed.\n\nLemma in_inorder_lookup : forall t x, valid t ->\n                                 In x (inorder t) -> lookup x t.\nProof.\n  induction t; intros; simpl in *; [assumption |].\n  simpl. destruct (Nat.eq_dec x n), (le_lt_dec x n); [apply I | apply I | |].\n  - simpl in *. rewrite app_sing in H0.\n    rewrite in_app_iff in H0. inversion H.\n    apply (IHt1 _ H4).\n    + destruct H0.\n      * rewrite in_app_iff in H0. destruct H0; [assumption | ].\n        inversion H0; [| inversion H8].\n        unfold not in n0. exfalso. symmetry in H8.\n        apply (n0 H8).\n      * pose proof (IHt2 _ H5 H0). pose proof (H7 _ H8). omega.\n  - simpl in *. inversion H. rewrite in_app_iff in H0.\n    apply (IHt2 _ H5). destruct H0.\n    + pose proof (IHt1 _ H4 H0). pose proof (H6 _ H8). omega.\n    + inversion H0; [| assumption].\n      unfold not in n0. symmetry in H8. contradiction (n0 H8).\nQed.\n\n\nLemma gt_leb : forall a b, a > b -> b <= a.\nProof.\n  - intros. omega.\nQed.\n\n\nLemma inorder_valid_sorted (t : bintree) (H : valid t) : ordered (inorder t).\nProof.\n  induction H; simpl; [apply o_nil |].\n  apply (ordered_app _ _ IHvalid1).\n  - apply (order_cons n (inorder r) IHvalid2).\n    destruct (inorder r) eqn:Hr; simpl; [apply I | ].\n    simpl in *. apply gt_leb. apply H2.\n    apply in_inorder_lookup; [assumption |].\n    rewrite Hr. constructor. reflexivity.\n  - destruct (rev (inorder l)) eqn:Hr; [apply I | ].\n    apply H1. apply in_inorder_lookup; [assumption |].\n    assert (In n0 (n0 :: l0)); [constructor; reflexivity |].\n    rewrite <- Hr in H3. rewrite <- in_rev in H3. assumption.\nQed.\n\n\nTheorem list2bin_valid : forall (l : list nat), valid (list2bin l).\nProof.\n  intros. induction l; [constructor |].\n  simpl. apply insert_preserves. assumption.\nQed.\n\n\nTheorem ordered_binsort (l : list nat) : ordered (binsort l).\nProof.\n  unfold binsort. induction l; simpl; [constructor |].\n  simpl. apply inorder_valid_sorted. apply insert_preserves.\n  apply list2bin_valid.\nQed.\n\nLemma app_nil_nil : forall X (l1 l2 : list X), l1 ++ l2 = [] -> l1 = [] /\\ l2 = [].\nProof.\n  induction l1; intros; simpl in H; [| inversion H].\n  split; [reflexivity | assumption].\nQed.\n\nLemma inorder_insert_nil_false : forall t x, inorder (insert x t) = [] -> False.\nProof.\n  induction t; intros; [inversion H | ].\n  simpl in H. destruct (le_dec x n).\n  - inversion H. destruct (app_nil_nil _ _ _ H1); inversion H2.\n  - simpl in H. destruct (app_nil_nil _ _ _ H). inversion H1.\nQed.\n\nLemma insert_leaf_false : forall t x, insert x t = leaf -> False.\nProof.\n  induction t; intros; [inversion H | ].\n  intros. simpl in H. destruct (le_dec x n); inversion H.\nQed.\n\nLemma binsort_perm_lr x (xs : list nat) : In x xs -> In x (binsort xs).\n  generalize dependent x. induction xs; intros; [inversion H |].\n  inversion H.\n  - pose proof (list2bin_valid xs). rewrite H0.\n    unfold binsort. simpl. apply lookup_in_inorder.\n    apply insert_lookup_x. assumption.\n  - unfold binsort in *. pose proof (list2bin_valid xs).\n    apply lookup_in_inorder. simpl.\n    apply (lookup_insert _ _ _ H1).\n    apply (in_inorder_lookup _ _ H1).\n    apply (IHxs _ H0).\nQed.\n\nLemma binsort_perm_rl x (xs : list nat) : In x (binsort xs) -> In x xs.\n  generalize dependent x. unfold binsort in *. induction xs; intros; [inversion H |].\n  simpl in H. destruct (Nat.eq_dec x a).\n  - constructor 1. symmetry. assumption.\n  - constructor 2. pose proof (list2bin_valid xs).\n    apply IHxs. apply lookup_in_inorder.\n    apply (insert_lookup _ _ _ H0 n).\n    apply in_inorder_lookup; [| assumption].\n    apply (insert_preserves _ _ H0).\nQed.\n\nTheorem binsort_perm x (xs : list nat) : In x xs <-> In x (binsort xs).\nProof.\n  split; [apply binsort_perm_lr | apply binsort_perm_rl].\nQed.\n\n\n\n\n        ", "meta": {"author": "adamschoenemann", "repo": "pls_sf_exercises", "sha": "feefd3857e4a5d3fe4001a78262c3d805267a993", "save_path": "github-repos/coq/adamschoenemann-pls_sf_exercises", "path": "github-repos/coq/adamschoenemann-pls_sf_exercises/pls_sf_exercises-feefd3857e4a5d3fe4001a78262c3d805267a993/assignment_05/BinTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7007688723144537}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom LF Require Export IndProp.\n\nModule ProofObjects.\nImport IndProp.\n\nPrint IndProp.ev.\n\nTheorem ev_4 : ev 4.\nProof.\n  apply ev_SS. apply ev_SS. apply ev_0. Qed.\n\nPrint ev_4.\n\nTheorem ev_4': ev 4.\nProof.\n  apply (ev_SS 2 (ev_SS 0 ev_0)).\nQed.\n\nTheorem ev_4'' : ev 4.\nProof.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_SS.\n  Show Proof.\n  apply ev_0.\n  Show Proof.\nQed.\n\nDefinition ev_4''' : ev 4 :=\n  ev_SS 2 (ev_SS 0 ev_0).\n\n\nTheorem ev_8 : ev 8.\nProof.\n  apply ev_SS.\n  apply ev_SS.\n  apply ev_4.\nQed.\n\nDefinition ev_8' : ev 8 :=\n  ev_SS 6 (ev_SS 4 ev_4).\n\n\n\nTheorem ev_plus4 : forall n, ev n -> ev (4 + n).\nProof.\n  intros n H. simpl.\n  apply ev_SS.\n  apply ev_SS.\n  apply H.\nQed.\n\nDefinition ev_plus4' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS (S (S n)) (ev_SS n H).\n\nDefinition ev_plus4'' : forall n, ev n -> ev (4 + n) :=\n  fun (n : nat) => fun (H : ev n) =>\n    ev_SS _ (ev_SS _ H).\n\n\nDefinition add1 : nat -> nat.\n  intros n.\n  Show Proof.\n  apply S.\n  Show Proof.\n  apply n. Defined.\n\nPrint add1.\n\n\n\nModule Props.\n\n  Module And.\n    Inductive and (P Q : Prop) : Prop :=\n      | conj : P -> Q -> and P Q.\n    Arguments conj [P] [Q].\n    Notation \"P /\\ Q\" := (and P Q) : type_scope.\n  \n    Print prod.\n\n    Theorem proj1' : forall P Q,\n      P /\\ Q -> P.\n    Proof.\n      intros P Q HPQ. destruct HPQ as [HP HQ]. apply HP.\n      Show Proof.\n    Qed.\n\n    Lemma and_comm : forall P Q : Prop, P /\\ Q <-> Q /\\ P.\n    Proof.\n      intros P Q. split.\n      - intros [HP HQ]. split.\n        + apply HQ.\n        + apply HP.\n      - intros [HQ HP]. split.\n        + apply HP.\n        + apply HQ.\n    Qed.\n\n    Definition conj_fact : forall P Q R, P /\\ Q -> Q /\\ R -> P /\\ R :=\n      fun p => fun q => fun r => fun pq => fun qr => \n        match pq with \n        | conj p' q' => \n          match qr with\n          | conj q'' r' => conj p' r'\n          end\n        end.\n  End And.\n\n  Module Or.\n    Inductive or (P Q : Prop) : Prop :=\n      | or_introl : P -> or P Q\n      | or_intror : Q -> or P Q.\n    Arguments or_introl [P] [Q].\n    Arguments or_intror [P] [Q].\n    Notation \"P \\/ Q\" := (or P Q) : type_scope.\n\n    Definition inj_l : forall (P Q : Prop), P -> P \\/ Q :=\n      fun P Q HP => or_introl HP.\n\n    Theorem inj_l' : forall (P Q : Prop), P -> P \\/ Q.\n    Proof.\n      intros P Q HP. left. apply HP.\n    Qed.\n\n    Definition or_elim : forall (P Q R : Prop), (P \\/ Q) -> (P -> R) -> (Q -> R) -> R :=\n      fun P Q R HPQ HPR HQR =>\n        match HPQ with\n        | or_introl HP => HPR HP\n        | or_intror HQ => HQR HQ\n        end.\n\n    Theorem or_elim' : forall (P Q R : Prop), (P \\/ Q) -> (P -> R) -> (Q -> R) -> R.\n    Proof.\n      intros P Q R HPQ HPR HQR.\n      destruct HPQ as [HP | HQ].\n      - apply HPR. apply HP.\n      - apply HQR. apply HQ.\n    Qed.\n\n    Definition or_commut' : forall P Q, P \\/ Q -> Q \\/ P :=\n      fun P Q PQ => \n        match PQ with\n        | or_introl HP => or_intror HP\n        | or_intror HQ => or_introl HQ\n        end.\n  End Or.\n\n  Module Ex.\n    Inductive ex {A : Type} (P : A -> Prop) : Prop :=\n      | ex_intro : forall (x : A), P x -> ex P.\n\n    Print ex_intro.\n\n    Notation \"'exists' x , p\" :=\n      (ex (fun x => p))\n        (at level 200, right associativity) : type_scope.\n\n    Check ex (fun n => ev n) : Prop.\n\n    Definition ex_ev_Sn : ex (fun n => ev (S n)) :=\n      ex_intro _ 1 (ev_SS _ ev_0).\n  End Ex.\n\n\n  Module TrueFalse.\n    Inductive True : Prop :=\n      | I : True.\n\n    Definition p_implies_true : forall P, P -> True :=\n      fun P HP => I.\n\n    Inductive False : Prop := .\n\n    Definition ex_falso_quodlibet' : forall P, False -> P :=\n      fun P F => match F with end.\n  End TrueFalse.\nEnd Props.\n\nModule MyEquality.\n  Inductive eq {X:Type} : X -> X -> Prop :=\n    | eq_refl : forall x, eq x x.\n  Notation \"x == y\" := (eq x y)\n                         (at level 70, no associativity)\n                       : type_scope.\n\n  Lemma four: 2 + 2 == 1 + 3.\n  Proof.\n    apply eq_refl.\n  Qed.\n  \n  Definition four' : 2 + 2 == 1 + 3 :=\n    eq_refl 4.\n\n  Definition singleton : forall (X:Type) (x:X), [] ++ [x] == x :: []  :=\n    fun (X:Type) (x:X) => eq_refl [x].\n\n\n  Lemma equality__leibniz_equality : forall (X : Type) (x y: X),\n    x == y -> forall (P: X -> Prop), P x -> P y.\n  Proof.\n    intros.\n    destruct H.\n    apply H0.\n  Qed.\n\n  Lemma leibniz_equality__equality : forall (X : Type) (x y: X),\n    (forall (P : X -> Prop), P x -> P y) -> x == y.\n  Proof.\n    intros.\n    destruct (H (fun i => i == x)).\n    - apply eq_refl.\n    - apply eq_refl.\n  Qed.\nEnd MyEquality.\n\nEnd ProofObjects.\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/ProofObjects.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7007688697139197}}
{"text": "(** * Teorija tipov in λ-račun. *)\n\n(** Tipi so posplošitev množic, topološki prostorov in podatkovnih tipov. Naivno si jih\n    lahko predstavljamo kot množice. Dejstvo, da ima izraz [e] tip [A] pišemo [e : A].\n\n    Razne konstrukcije tipov se vedno uvede po istem vzorcu:\n\n    - _formacija_: kako se naredi nov tip\n\n    - _vpeljava_: kako se naredi ali sestavi elemente tipa (konstruktorji)\n\n    - _uporaba_: kako se elemente uporabi ali razstavi na sestavne dele (eliminatorji)\n\n    - _enačbe_: kakšne enačbe povezujejo konstruktorje in eliminatorje\n*)\n\n(** ** Funkcije\n\n  Za vsaka dva tipa [A] in [B] lahko tvorimo tip funkcij:\n\n  - _formacija_: če sta [A] in [B] tipa, je tudi [A -> B] tip\n\n  - _vpeljava_: če je [x : A] spremenljivka tipa [A] in [t : B] izraz tipa [B],\n    odvisen od [x], potem je [fun (x : A) => t] tipa [A -> B]. Izrazu [fun ...]\n    pravimo _λ-abstrakcija_, ker se v logiki piše $\\lambda x : A . t$.\n\n  - _uporaba_: če je [f : A -> B] in [e : A] potem je [f e : B]. Pravimo, da smo\n    funkcijo [f] aplicirali na argumentu [e].\n\n  - _enačbe_:\n\n    - _pravilo $\\beta$_: [(fun (x : A) => t) e = t{e/x}] kjer zapis \"[t{e/x}]\" pomeni,\n      da v izrazu [t] vstavimo [e] namesto [x].\n\n    - _pravilo $\\eta$_: [(fun (x : A) => f x) = f]\n*)\n   \n(** ** Kartezični produkt\n\n    Da bomo lahko počeli kaj zanimivega, vpeljemo še kartezični produkt tipov:\n\n    - _formacija_: če sta [A] in [B] tipa, je [A * B] tip (matematični zapis $A \\times B$)\n\n    - _vpeljava_: če je [a : A] in [b : B], potem je [(a,b) : A * B], _urejeni par_\n\n    - _uporaba_: če je [p : A * B], potem imamo\n\n      - _prva projekcija_: [fst p : A]\n      - _druga projekcija_: [snd p : B]\n\n    - enačbe, pri čemer je [a : A], [b : B] in [p : A * B]:\n      - [fst (a, b) = a]\n      - [snd (a, b) = b]\n      - [p = (fst p, snd p)]\n\n    Poznamo še enotski tip:\n\n    - _formacija_: [unit] je tip\n    - _vpeljava_: [tt : unit]\n    - _uporaba_: pravil za uporabo ni\n    - _enačbe_: če je [u : unit], je [u = tt].\n*)\n\n(** V Coqu lahko datoteko razdelimo na posamične razdelke z [Section X.] in [End X.] *)\nSection RazneFunkcije.\n\n  (* Predpostavimo, da imamo tipe [A], [B] in [C]. *)\n  Context {A B C : Type}.\n\n  Definition vaja1_1 : A * B -> B * A :=\n    fun (u : A * B) => (snd u, fst u).\n                                  \n  Definition vaja1_2 : (A * B) * C -> A * (B * C).\n  Admitted.\n\n  Definition vaja1_3 : A -> (B -> A).\n  Admitted.\n\n  \n  Definition vaja1_4 : (A -> B -> C) -> (A -> B) -> (A -> C).\n  Admitted.\n\n  Definition vaja1_5 : (A * B -> C) -> (A -> (B -> C)).\n  Admitted.\n  \n  Definition vaja1_6 : (A -> (B -> C)) -> (A * B -> C).\n  Admitted.\n\n  Definition vaja1_7 : unit * A -> A.\n  Admitted.\n\n  Definition vaja1_8 : A -> unit * A.\n  Admitted.\n\nEnd RazneFunkcije.\n\n(** Ko zapremo razdelek [RazneFunkcije] nimamo več predpostavke, da so [A], [B], [C] tipi,\n    vse definicije iz razdelka pa postanejo funkcije z dodatnimi parametri [A], [B], [C]. *)\nPrint vaja1_1.\n\n(** Coq pravi: \"Arguments [A], [B] are implicit and maximally inserted\". To pomeni,\n    da jih ni treba podati, ko uporabimo funkcijo [vaja1_1]. *)\nEval compute in vaja1_1 (42, false).\n\n(* Če želimo eksplicitno nastaviti tudi [A] in [B], pišemo [@vaja1_1] namesto [vaja1_1]: *)\nEval compute in @vaja1_1 nat bool (42, false).\n\n(** ** Izomorfni tipi\n\n   Pravimo, da sta tipa [X] in [Y] izomorfna, če obstajata [f : X -> Y] in\n   [g : Y -> X], da velja [g (f x) = x] za vse [x : X] in [g (g y) = y] za vse [y : Y].\n*)\nDefinition iso (X : Type) (Y : Type) :=\n  exists (f : X -> Y) (g : Y -> X),\n    (forall x : X, g (f x) = x) /\\ (forall y : Y, f (g y) = y).\n\n(** V Coqu lahko uvedemo prikladno notacijo za izomorfizem. *)\nNotation \"X <~> Y\" := (iso X Y) (at level 60).\n\nSection Izomorfizmi1.\n  (** Predpostavimo, da imamo tipe [A], [B] in [C]. *)\n  Context {A B C : Type}.\n\n  (** Dokaži, da so naslednji tipi izomorfni. *)\n\n  Lemma vaja2_1 : A * B <~> B * A.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja2_2 : (A * B) * C <~> A * (B * C).\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja2_3 : unit * A <~> A.\n  Proof.\n    admit.\n  Qed.\n\n  (** Pravimo, da sta funkciji [f g : X -> Y] _enaki po točkah_, če velja [forall x : X, f\n      x = g x]. Aksiom _funkcijske ekstenzionalnosti_ pravi, da sta funkciji enaki,\n      če sta enaki po točkah. Coq ne verjame v ta aksiom, zato ga po potrebi predpostavimo. \n      Najprej ga definirajmo. *)\n  Definition funext :=\n    forall (X Y : Type) (f g : X -> Y), (forall x, f x = g x) -> f = g.\n\n  (** S pomočjo ekstenzionalnosti lahko dokažemo nekatere izomorfizme. *)\n  Lemma vaja2_4 (F : funext) : (A * B -> C) <~> (A -> (B -> C)).\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja2_5 (F : funext) : (unit -> A) <~> A.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja2_6 (F : funext) : (A -> unit) <~> unit.\n  Proof.\n    admit.\n  Qed.\nEnd Izomorfizmi1.\n\n(** ** Vsota tipov\n\n   Vsota tipov je kot disjunktna unija v teorijo množic ali koprodukt v kategorijah:\n\n   - _formacija_: če sta [A] in [B] tipa, je [A + B] tip\n\n   - _vpeljava_:\n\n      - če je [a : A], potem je [inl a : A + B]\n      - če je [b : B], potem je [inr b : A + B]\n\n   - _uporaba_: če pri predpostavki [x : A] velja [u(x) : C] in\n     če pri predpostavki [y : B] velja [v(y) : C] in če je [t : A + B], potem\n     ima\n     [(match t with\n       | inl x => u(x)\n       | inr y => v(y)\n      end)]\n     tip [C].\n\n   - _enačbe_:\n\n      - [match (inl a) with\n         | x => u(x)\n         | y => v(y)\n         end] je enako [u(a)].\n\n      - [match (inr b) with\n         | x => u(x)\n         | y => v(y)\n         end] je enako [v(b)].\n\n      - [match t with\n         | inl x => inl x\n         | inr y => inr y\n         end] je enako [t].\n\n*) \n\n(** ** Prazen tip\n\n    Nekoliko bolj nenavaden je prazen tip:\n\n    - _formacija_: [Empty_set] je tip\n   \n    - _vpeljava_: ni pravil za uporabo\n\n    - _uporaba_: če [t : Empty_set], potem ima [match t with end] tip [A]\n\n    - _enačbe_: [match t with end] je enako [a] za vse [a : A]\n*)\n\nSection FunkcijeVsote.\n  (** Predpostavimo, da imamo tipe [A], [B] in [C]. *)\n  Context {A B C : Type}.\n\n  Definition vaja3_1 : (A + B -> C) -> (A -> C) * (B -> C).\n  Admitted.\n\n  (* S stavkom match obravnavmo element, ki je vsota tipov. *)\n\n  Definition vaja3_2 : A + B -> B + A.\n  Admitted.\n\n  Definition vaja3_3 : (A + B) * C -> A * C + B * C.\n  Admitted.\n  \n  Definition vaja3_4 : A * C + B * C -> (A + B) * C.\n  Admitted.\n\n  Definition vaja3_5 : (A -> C) * (B -> C) -> (A + B -> C).\n  Admitted.\n\n  Definition vaja3_6 : Empty_set -> A.\n  Admitted.\n\n  Definition vaja3_7 : Empty_set + A -> A.\n  Admitted.\n\n  Definition vaja3_8 : A -> ((A -> Empty_set) -> Empty_set).\n  Admitted.\n\n  Definition vaja3_9 : A + (A -> Empty_set) -> (((A -> Empty_set) -> Empty_set) -> A).\n  Admitted.\n\nEnd FunkcijeVsote.\n\nSection Izomorfizmi2.\n  (** Sam ugotovi, kje potrebuješ funkcijsko ekstenzionalnost. *)\n\n  Context {A B C : Type}.\n\n  Lemma vaja4_1 : A + B <~> B + A.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja4_2 : (A + B) * C <~> A * C + B * C.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja4_3 : (A + B -> C) <~> (A -> C) * (B -> C).\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja4_4 : Empty_set + A <~> A.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja4_5 : (A -> Empty_set) <~> Empty_set.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma vaja5_5 : (Empty_set -> A) <~> unit.\n  Proof.\n    admit.\n  Qed.\n\nEnd Izomorfizmi2.\n\nSection Zabava.\n  (** Pa še neka vaj za zabavo. *)\n  Context {A B : Type}.\n\n  (* Koliko funkcij A * B -> A + B lahko definiraš? *)  \n  Definition vaja5_1_XX : A * B -> A + B.\n  Admitted.\n\n  (* Koliko funkcij tipa (A * A) * A -> A * A lahko definiraš? *)\n  Definition vaja5_2_XX : (A * A) * A -> A * A.\n  Admitted.\n\n  (* Koliko funkcij tipa (A -> A) -> (A -> A) lahko definiraš? *)\n  Definition vaja5_3_XX : (A -> A) -> (A -> A).\n  Admitted.\n\nEnd Zabava.\n", "meta": {"author": "andrejbauer", "repo": "lvr-coq", "sha": "b39e034ac4b9e373b08737dd064ac8972ff3d272", "save_path": "github-repos/coq/andrejbauer-lvr-coq", "path": "github-repos/coq/andrejbauer-lvr-coq/lvr-coq-b39e034ac4b9e373b08737dd064ac8972ff3d272/tipi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7007688584810545}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) : natural := mult (Succ Zero) lf2.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj14_coqofml_oOlo35.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7007272783975189}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (lf2 : natural) (y : natural) (x : natural) (lf1 : natural)\n  : natural := plus lf1 x.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj194_coqofml_EJyffd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7007272742312478}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.lemma_extension.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_lessthancongruence2.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma lemma_TTflip2 : \n   forall A B C D E F G H, \n   TT A B C D E F G H ->\n   TT A B C D H G F E.\nProof.\nintros.\nlet Tf:=fresh in\nassert (Tf:exists J, (BetS E F J /\\ Cong F J G H /\\ TG A B C D E J)) by (conclude_def TT );destruct Tf as [J];spliter.\nlet Tf:=fresh in\nassert (Tf:exists K, (BetS A B K /\\ Cong B K C D /\\ Lt E J A K)) by (conclude_def TG );destruct Tf as [K];spliter.\nassert (neq F J) by (forward_using lemma_betweennotequal).\nassert (neq G H) by (conclude axiom_nocollapse).\nassert (neq H G) by (conclude lemma_inequalitysymmetric).\nassert (neq E F) by (forward_using lemma_betweennotequal).\nassert (neq F E) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists L, (BetS H G L /\\ Cong G L F E)) by (conclude lemma_extension);destruct Tf as [L];spliter.\nassert (Cong L G E F) by (forward_using lemma_congruenceflip).\nassert (Cong G H F J) by (conclude lemma_congruencesymmetric).\nassert (BetS L G H) by (conclude axiom_betweennesssymmetry).\nassert (Cong L H E J) by (conclude cn_sumofparts).\nassert (Cong H L L H) by (conclude cn_equalityreverse).\nassert (Cong H L E J) by (conclude lemma_congruencetransitive).\nassert (Cong E J H L) by (conclude lemma_congruencesymmetric).\nassert (Lt H L A K) by (conclude lemma_lessthancongruence2).\nassert (TG A B C D H L) by (conclude_def TG ).\nassert (TT A B C D H G F E) by (conclude_def TT ).\nclose.\nQed.\n\nEnd Euclid.", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/lemma_TTflip2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7007272697076529}}
{"text": "Require Import Ashley.Axioms.\nRequire Import Ashley.PartialOrder.\nRequire Import Ashley.Set.\nRequire Import Ashley.SetFunction.\nRequire Import Ashley.Lattice.\n\nClass Topology (A : Type) : Type :=\n{\n  open : set (set A);\n  top_empty_is_open : open empty;\n  top_full_is_open : open full;\n  top_intersect_is_open : all a:open, all b:open, open (intersect a b);\n  top_Union_is_open : forall ff, ff <= open -> open (Union ff)\n}.\n\nDefinition topology_open {A} (top: Topology A) : set (set A) := @open _ top.\n\nDefinition open_type {A} (top: Topology A) := set_type open.\n\nDefinition open_val {A} {t: Topology A} (x: set A): open x -> open_type t := stc open x.\n\nLemma val_open: forall {A:Type} `{Topology A} (v:set A) (st:open v), val (open_val v st) = v.\nintros.\nunfold open_val.\napply val_stc.\nQed.\n\nDefinition topology_union {A} {top: Topology A} (u v: open_type top): open_type top.\napply (open_val (join (val u) (val v))).\ncase u.\ncase v.\nintros.\nunfold val.\nunfold join.\nunfold indexed_JoinSemilattice.\nunfold join.\nunfold prop_JoinSemilattice.\nfold (union x0 x).\nrewrite <- Union2.\napply top_Union_is_open.\nunfold within. unfold indexed_Preorder.\nunfold within. unfold prop_Preorder.\nintros.\ndestruct H.\nrewrite H.\napply o0.\nrewrite H.\napply o.\nDefined.\n\nInstance open_JoinSemilattice `(top: Topology) : JoinSemilattice (open_type top) :=\n{\n  join := topology_union\n}.\nintros.\napply set_type_ext.\nunfold topology_union.\nunfold open_val.\nunfold val.\ncase p.\ncase q.\ncase r.\nintros.\nfirstorder.\napply join_associates.\nintros.\napply set_type_ext.\nunfold topology_union.\nunfold open_val.\nunfold val.\ncase p.\ncase q.\nfirstorder.\napply join_commutes.\nintros.\napply set_type_ext.\nunfold topology_union.\nunfold open_val.\nunfold val.\ncase p.\nfirstorder.\napply join_idem.\nDefined.\n\nDefinition topology_intersect {A} {top: Topology A} (u v: open_type top): open_type top.\napply (open_val (meet (val u) (val v))).\ncase u.\ncase v.\nunfold val.\nintros.\napply top_intersect_is_open.\nexact o0.\nexact o.\nDefined.\n\nInstance open_MeetSemilattice `(top: Topology) : MeetSemilattice (open_type top) :=\n{\n  meet := topology_intersect\n}.\nintros.\napply set_type_ext.\nunfold topology_intersect. unfold open_val. unfold val.\ncase p. case q. case r.\nintros.\napply meet_associates.\nintros.\napply set_type_ext.\nunfold topology_intersect. unfold open_val. unfold val.\ncase p. case q.\nintros.\napply meet_commutes.\nintros.\napply set_type_ext.\nunfold topology_intersect. unfold open_val. unfold val.\ncase p.\nintros.\napply meet_idem.\nDefined.\n\nInstance open_Preorder `(top: Topology) : Preorder (open_type top) :=\n{\n  within a b := within (val a) (val b)\n}.\nintros.\napply within_reflex.\nintros.\napply (within_trans (val p) (val q) (val r)).\nexact H.\nexact H0.\nDefined.\n\nInstance open_PartialOrder `(top: Topology) : PartialOrder (open_type top) :=\n{\n}.\nintros.\napply within_antisym.\nexact H.\nexact H0.\nDefined.\n\nInstance open_Lattice `(top: Topology) : Lattice (open_type top) :=\n{\n}.\nintros.\nunfold within. unfold open_Preorder.\nunfold join. unfold open_JoinSemilattice.\nreplace (topology_union p q = q) with (val (topology_union p q) = val q).\nunfold topology_union. rewrite val_open.\napply join_within.\napply set_type_ext_eq.\n\nintros.\nunfold join. unfold open_JoinSemilattice.\nunfold meet. unfold open_MeetSemilattice.\napply set_type_ext.\nunfold topology_union.\nunfold topology_intersect.\nrewrite !val_open.\napply meet_join_absorbs.\n\nintros.\nunfold join. unfold open_JoinSemilattice.\nunfold meet. unfold open_MeetSemilattice.\napply set_type_ext.\nunfold topology_union.\nunfold topology_intersect.\nrewrite !val_open.\napply join_meet_absorbs.\nDefined.\n\nDefinition topology_bottom {A} {t: Topology A}: open_type t.\napply (open_val bottom).\nunfold bottom. unfold indexed_BoundedPartialOrder.\nunfold bottom. unfold prop_BoundedPartialOrder.\napply top_empty_is_open.\nDefined.\n\nDefinition topology_top {A} {t: Topology A}: open_type t.\napply (open_val top).\nunfold top. unfold indexed_BoundedPartialOrder.\nunfold top. unfold prop_BoundedPartialOrder.\napply top_full_is_open.\nDefined.\n\nInstance open_BoundedPartialOrder `(t: Topology) : BoundedPartialOrder (open_type t) :=\n{\n  bottom := topology_bottom;\n  top := topology_top\n}.\nintros.\nunfold within. unfold open_Preorder.\napply bottom_within.\n\nintros.\nunfold within. unfold open_Preorder.\napply top_without.\nDefined.\n\n\nRequire Import Ashley.BoundedLattice.\n\nInstance open_BoundedLattice `(t: Topology) : BoundedLattice (open_type t) :=\n{\n}.\n\nDefinition topology_Join {A} {t: Topology A} (uu: set (open_type t)): open_type t.\napply (open_val (Union (map val uu))).\napply top_Union_is_open.\nunfold within. unfold indexed_Preorder.\nunfold within. unfold prop_Preorder.\nunfold map.\nintros.\ndestruct H.\ndestruct H.\nrewrite <- H0.\napply struct.\nDefined.\n\nLemma Join_is_Union: forall {A} (f:set (set A)), Join f = Union f.\nintros.\nunfold Join. unfold indexed_SemicompleteBoundedLattice.\nunfold Join. unfold prop_SemicompleteBoundedLattice.\nunfold Union.\napply member_ext.\nintros.\nunfold map.\nsplit.\nintros.\ndestruct H.\nexists x0.\ndestruct H.\nsplit.\nexact H.\nrewrite H0.\ntrivial.\nintros.\ndestruct H.\ndestruct H.\nexists x0.\nsplit.\nexact H.\napply prop_ext.\nfirstorder.\nQed.\n\nInstance open_SemicompleteBoundedLattice `(t: Topology) : SemicompleteBoundedLattice (open_type t) :=\n{\n  Join := topology_Join\n}.\nintros.\nunfold within. unfold open_Preorder.\nunfold topology_Join. rewrite val_open.\nrewrite <- Join_is_Union.\napply Join_bound.\nunfold map.\nexists a.\nfirstorder.\n\nintros.\nunfold within. unfold open_Preorder.\nunfold topology_Join. rewrite val_open.\nunfold within in H. unfold open_Preorder in H.\nrewrite <- Join_is_Union.\napply Join_least.\nintros.\nunfold map in H0.\ndestruct H0.\ndestruct H0.\nrewrite <- H1.\napply (H x).\nexact H0.\nDefined.\n\n\n\n(*\nInstance top_empty {A} {top: Topology A}: set_type open :=\n*)\nDefinition tunion {A} {top: Topology A} (u v: open_type top): open_type top := topology_union u v.\n\nInstance discrete {A} : Topology A :=\n{\n  open := full\n}.\napply all_full.\napply all_full.\nintros.\napply all_full.\nintros.\napply all_full.\nDefined.\n\nInstance indiscrete {A} : Topology A :=\n{\n  open := {s : set A | not_empty s -> is_full s}\n}.\nfirstorder.\nfirstorder.\nfirstorder.\nfirstorder.\nDefined.\n\nInstance particular_point {A} (p:A) : Topology A :=\n{\n  open := {s : set A | not_empty s -> s p}\n}.\nfirstorder.\nfirstorder.\nfirstorder.\nfirstorder.\nDefined.\n\nDefinition sierpinski := particular_point True.\n\nNotation \"'all_open' x : t , P\" := (all x : topology_open t, P) (at level 20, x at level 99).\nNotation \"'some_open' x : t , P\" := (some x : topology_open t, P) (at level 20, x at level 99).\n\nClass Continuous {A} {B} (TA : Topology A) (TB : Topology B) : Type :=\n{\n  f: A -> B;\n  is_continuous: all_open sb: TB, topology_open TA {a : A|sb (f a)}\n}.\n\nDefinition continuous_f {A} {B} {TA:Topology A} {TB:Topology B} (c: Continuous TA TB) := @f _ _ _ _ c.\n\nRequire Import Ashley.Proposition.\n\nLemma not_noncontinuous: forall (cont: Continuous sierpinski sierpinski), ~ continuous_f cont = not.\nunfold sierpinski.\nintro.\nintro.\ndestruct cont.\nunfold continuous_f in H.\nunfold f in H.\nunfold topology_open in is_continuous0.\nrewrite H in is_continuous0.\nclear H f0.\nspecialize (is_continuous0 {b:Prop|b}).\nfirstorder.\nspecialize (H False).\nfirstorder.\nDefined.\n\nClass Cover {A} `{SemicompleteBoundedLattice A} (s : A) : Type :=\n{\n  cover_sets : set A;\n  covering : Join cover_sets >= s\n}.\n\nDefinition OpenCover {A} (top : Topology A) (s : open_type top) : Type := Cover s.\n", "meta": {"author": "AshleyYakeley", "repo": "maths", "sha": "42d4de811802c553d8bf0dcd69902ea01dda9a3e", "save_path": "github-repos/coq/AshleyYakeley-maths", "path": "github-repos/coq/AshleyYakeley-maths/maths-42d4de811802c553d8bf0dcd69902ea01dda9a3e/coq/theory/Topology.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.700727262283979}}
{"text": "Require Import\n        Coq.Vectors.Vector\n        VectorLib.\n\nInductive Bit := Zero | One.\n\nDefinition And (x y : Bit) :=\n  match x, y with\n  | One, One => One\n  | _, _ => Zero\n  end.\n\nDefinition Or (x y : Bit) :=\n  match x, y with\n  | Zero, Zero => Zero\n  | _, _ => One\n  end.\n\nDefinition Bitflip (x : Bit) : Bit :=\n  match x with\n  | Zero => One\n  | One => Zero\n  end.\n\nLemma and_bit_flip : forall (x : Bit), And x (Bitflip x) = Zero.\nProof.\n  refine (fun x => match x with\n                | Zero => eq_refl\n                | One => eq_refl\n                end).\nQed.\n\nLemma bit_and_flip : forall (x : Bit), And (Bitflip x) x = Zero.\nProof.\n  refine (fun x => match x with\n                | Zero => eq_refl\n                | One => eq_refl\n                end).\nQed.\n\n\n\nDefinition Bitstream (n : nat) := Vector.t Bit n.\n\nFixpoint repeatN (n : nat) (x : Bit) : Bitstream n :=\n  match n with\n  | O => nil _\n  | S n' => cons _ x _ (repeatN n' x)\n  end.\n\n   \nDefinition zipBits {n : nat} (f : Bit -> Bit -> Bit) (xs ys : Bitstream n) : Bitstream n :=\n  zip_vectors f n xs ys.\n\nDefinition mapBits {n : nat} (f : Bit -> Bit) (xs : Bitstream n) : Bitstream n :=\n  map_vector f n xs.\n\nDefinition appendBits {n m : nat} (xs : Bitstream n) (ys : Bitstream m) : Bitstream (n + m) :=\n  append_vector n m xs ys.\n  \n(* All bits are zero *)\nDefinition allZero (n : nat) := repeatN n Zero. \n\n(* All bits are One *)\nDefinition allOne (n : nat) := repeatN n One.\n\nDefinition bitstreamAnd {n : nat} (xs ys : Bitstream n) : Bitstream n :=\n  zipBits And xs ys.\n\nDefinition bistreamOr {n : nat} (xs ys : Bitstream n) : Bitstream n :=\n  zipBits Or xs ys.\n\n\nDefinition bitstreamFlip {n : nat} (xs : Bitstream n) : Bitstream n :=\n  mapBits Bitflip xs.\n\n(* n is index. n = 0 means set the 0th bit *)\nFixpoint setBit {m : nat} (n : nat) : Bitstream (n + S m) -> Bitstream (n + S m).\n  refine (match n as n' return n = n' -> Bitstream (n' + S m) -> Bitstream (n' + S m) with\n          | O => fun H v => _\n          | S n' => fun H v => _\n          end eq_refl); inversion v.\n  + exact (cons _ One _ H1).\n  + exact (cons _ One _ (setBit _ _ H1)).\nDefined.\n\nFixpoint fetchBit {m : nat} (n : nat) : Bitstream (n + S m) -> Bit.\n  refine (match n as n' return n = n' -> Bitstream (n' + S m) -> Bit with\n          | O => fun H v => _\n          | S n' => fun H v => _\n          end eq_refl); inversion v.\n  + exact h.\n  + exact (fetchBit _ _ H1).\nDefined.                                         \n  \nTheorem  compliment_of_each_other :\n  forall (n : nat) (xs : Bitstream n), bitstreamAnd xs (bitstreamFlip xs) = allZero n.\nProof.\n  unfold Bitstream; unfold bitstreamAnd; unfold bitstreamFlip;\n    unfold zipBits; unfold mapBits; unfold allZero.\n  induction xs.\n  + auto.\n  + cbn. rewrite IHxs. rewrite and_bit_flip.\n    auto.\nQed.\n\n\n \n  \n  \n    \n \n  \n", "meta": {"author": "mukeshtiwari", "repo": "Bitvector", "sha": "33e8725350c4200c05b8eba67b26dabfd4b28b5e", "save_path": "github-repos/coq/mukeshtiwari-Bitvector", "path": "github-repos/coq/mukeshtiwari-Bitvector/Bitvector-33e8725350c4200c05b8eba67b26dabfd4b28b5e/Bitvector.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7006465420002692}}
{"text": "Require Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nLocal Open Scope Z_scope.\n\nModule Z.\n  Lemma div_abs_sgn_nonneg a b : 0 <= Z.sgn (Z.abs a / Z.abs b).\n  Proof.\n    generalize (Zdiv_sgn (Z.abs a) (Z.abs b)).\n    destruct a, b; simpl; lia.\n  Qed.\n  Hint Resolve div_abs_sgn_nonneg : zarith.\nEnd Z.\n", "meta": {"author": "dip-proto", "repo": "fiat-crypto", "sha": "fc3a9280c51f413943c167cc9292e953b8e42c02", "save_path": "github-repos/coq/dip-proto-fiat-crypto", "path": "github-repos/coq/dip-proto-fiat-crypto/fiat-crypto-fc3a9280c51f413943c167cc9292e953b8e42c02/src/Util/ZUtil/Sgn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.7006430264062701}}
{"text": "(** * Poly: Polymorphism and Higher-Order Functions *)\n\n(* Final reminder: Please do not put solutions to the exercises in\n   publicly accessible places.  Thank you!! *)\n\n(* Suppress some annoying warnings from Coq: *)\nSet Warnings \"-notation-overridden,-parsing\".\nFrom LF Require Export Lists.\n\n(* ################################################################# *)\n(** * Polymorphism *)\n\n(** In this chapter we continue our development of basic\n    concepts of functional programming.  The critical new ideas are\n    _polymorphism_ (abstracting functions over the types of the data\n    they manipulate) and _higher-order functions_ (treating functions\n    as data).  We begin with polymorphism. *)\n\n(* ================================================================= *)\n(** ** Polymorphic Lists *)\n\n(** For the last chapter, we've been working with lists\n    containing just numbers.  Obviously, interesting programs also\n    need to be able to manipulate lists with elements from other\n    types -- lists of booleans, lists of lists, etc.  We _could_ just\n    define a new inductive datatype for each of these, for\n    example... *)\n\nInductive boollist : Type :=\n  | bool_nil\n  | bool_cons (b : bool) (l : boollist).\n\nCheck boollist.\n\n(** ... but this would quickly become tedious, partly because we\n    have to make up different constructor names for each datatype, but\n    mostly because we would also need to define new versions of all\n    our list manipulating functions ([length], [rev], etc.) and all\n    their properties ([rev_length], [app_assoc], etc.) for each\n    new datatype definition. *)\n\n(** To avoid all this repetition, Coq supports _polymorphic_\n    inductive type definitions.  For example, here is a _polymorphic\n    list_ datatype. *)\n\nInductive list (X:Type) : Type :=\n  | nil\n  | cons (x : X) (l : list X).\n\n(** This is exactly like the definition of [natlist] from the\n    previous chapter, except that the [nat] argument to the [cons]\n    constructor has been replaced by an arbitrary type [X], a binding\n    for [X] has been added to the function header on the first line,\n    and the occurrences of [natlist] in the types of the constructors\n    have been replaced by [list X].\n\n    What sort of thing is [list] itself?  A good way to think about it\n    is that the definition of [list] is a _function_ from [Type]s to\n    [Inductive] definitions; or, to put it more concisely, [list] is a\n    function from [Type]s to [Type]s.  For any particular type [X],\n    the type [list X] is the [Inductive]ly defined set of lists whose\n    elements are of type [X]. *)\n\nCheck list : Type -> Type.\n\n(** The parameter [X] in the definition of [list] automatically\n    becomes a parameter to the constructors [nil] and [cons] -- that\n    is, [nil] and [cons] are now polymorphic constructors; when we use\n    them, we must now provide a first argument that is the type of the\n    list they are building. For example, [nil nat] constructs the\n    empty list of type [nat]. *)\n\nCheck (nil nat) : list nat.\n\n(** Similarly, [cons nat] adds an element of type [nat] to a list of\n    type [list nat]. Here is an example of forming a list containing\n    just the natural number 3. *)\n\nCheck (cons nat 3 (nil nat)) : list nat.\n\n(** What might the type of [nil] be? We can read off the type\n    [list X] from the definition, but this omits the binding for [X]\n    which is the parameter to [list]. [Type -> list X] does not\n    explain the meaning of [X]. [(X : Type) -> list X] comes\n    closer. Coq's notation for this situation is [forall X : Type,\n    list X]. *)\n\nCheck nil : forall X : Type, list X.\n\n(** Similarly, the type of [cons] from the definition looks like\n    [X -> list X -> list X], but using this convention to explain the\n    meaning of [X] results in the type [forall X, X -> list X -> list\n    X]. *)\n\nCheck cons : forall X : Type, X -> list X -> list X.\n\n(** (Side note on notation: In .v files, the \"forall\" quantifier\n    is spelled out in letters.  In the generated HTML files and in the\n    way various IDEs show .v files, depending on the settings of their\n    display controls, [forall] is usually typeset as the usual\n    mathematical \"upside down A,\" though you'll still see the\n    spelled-out \"forall\" in a few places.  This is just a quirk of\n    typesetting: there is no difference in meaning.) *)\n\n(** Having to supply a type argument for every single use of a\n    list constructor would be rather burdensome; we will soon see ways\n    of reducing this annotation burden. *)\n\nCheck (cons nat 2 (cons nat 1 (nil nat)))\n      : list nat.\n\n(** We can now go back and make polymorphic versions of all the\n    list-processing functions that we wrote before.  Here is [repeat],\n    for example: *)\n\nFixpoint repeat (X : Type) (x : X) (count : nat) : list X :=\n  match count with\n  | 0 => nil X\n  | S count' => cons X x (repeat X x count')\n  end.\n\n(** As with [nil] and [cons], we can use [repeat] by applying it\n    first to a type and then to an element of this type (and a number): *)\n\nExample test_repeat1 :\n  repeat nat 4 2 = cons nat 4 (cons nat 4 (nil nat)).\nProof. reflexivity. Qed.\n\n(** To use [repeat] to build other kinds of lists, we simply\n    instantiate it with an appropriate type parameter: *)\n\nExample test_repeat2 :\n  repeat bool false 1 = cons bool false (nil bool).\nProof. reflexivity. Qed.\n\n\n(** **** Exercise: 2 stars, standard (mumble_grumble) \n\n    Consider the following two inductively defined types. *)\n\nModule MumbleGrumble.\n\nInductive mumble : Type :=\n  | a\n  | b (x : mumble) (y : nat)\n  | c.\n\nInductive grumble (X:Type) : Type :=\n  | d (m : mumble)\n  | e (x : X).\n\n(** Which of the following are well-typed elements of [grumble X] for\n    some type [X]?  (Add YES or NO to each line.)\n      - [d (b a 5)]\n      - [d mumble (b a 5)]\n      - [d bool (b a 5)]\n      - [e bool true]\n      - [e mumble (b c 0)]\n      - [e bool (b c 0)]\n      - [c]  *)\n(* FILL IN HERE *)\nEnd MumbleGrumble.\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_mumble_grumble : option (nat*string) := None.\n(** [] *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Annotation Inference *)\n\n(** Let's write the definition of [repeat] again, but this time we\n    won't specify the types of any of the arguments.  Will Coq still\n    accept it? *)\n\nFixpoint repeat' X x count : list X :=\n  match count with\n  | 0        => nil X\n  | S count' => cons X x (repeat' X x count')\n  end.\n\n(** Indeed it will.  Let's see what type Coq has assigned to [repeat']: *)\n\nCheck repeat'\n  : forall X : Type, X -> nat -> list X.\nCheck repeat\n  : forall X : Type, X -> nat -> list X.\n\n(** It has exactly the same type as [repeat].  Coq was able to\n    use _type inference_ to deduce what the types of [X], [x], and\n    [count] must be, based on how they are used.  For example, since\n    [X] is used as an argument to [cons], it must be a [Type], since\n    [cons] expects a [Type] as its first argument; matching [count]\n    with [0] and [S] means it must be a [nat]; and so on.\n\n    This powerful facility means we don't always have to write\n    explicit type annotations everywhere, although explicit type\n    annotations can still be quite useful as documentation and sanity\n    checks, so we will continue to use them much of the time. *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Type Argument Synthesis *)\n\n(** To use a polymorphic function, we need to pass it one or\n    more types in addition to its other arguments.  For example, the\n    recursive call in the body of the [repeat] function above must\n    pass along the type [X].  But since the second argument to\n    [repeat] is an element of [X], it seems entirely obvious that the\n    first argument can only be [X] -- why should we have to write it\n    explicitly?\n\n    Fortunately, Coq permits us to avoid this kind of redundancy.  In\n    place of any type argument we can write a \"hole\" [_], which can be\n    read as \"Please try to figure out for yourself what belongs here.\"\n    More precisely, when Coq encounters a [_], it will attempt to\n    _unify_ all locally available information -- the type of the\n    function being applied, the types of the other arguments, and the\n    type expected by the context in which the application appears --\n    to determine what concrete type should replace the [_].\n\n    This may sound similar to type annotation inference -- and, indeed,\n    the two procedures rely on the same underlying mechanisms.  Instead\n    of simply omitting the types of some arguments to a function, like\n\n      repeat' X x count : list X :=\n\n    we can also replace the types with holes\n\n      repeat' (X : _) (x : _) (count : _) : list X :=\n\n    to tell Coq to attempt to infer the missing information.\n\n    Using holes, the [repeat] function can be written like this: *)\n\nFixpoint repeat'' X x count : list X :=\n  match count with\n  | 0        => nil _\n  | S count' => cons _ x (repeat'' _ x count')\n  end.\n\n(** In this instance, we don't save much by writing [_] instead of\n    [X].  But in many cases the difference in both keystrokes and\n    readability is nontrivial.  For example, suppose we want to write\n    down a list containing the numbers [1], [2], and [3].  Instead of\n    this... *)\n\nDefinition list123 :=\n  cons nat 1 (cons nat 2 (cons nat 3 (nil nat))).\n\n(** ...we can use holes to write this: *)\n\nDefinition list123' :=\n  cons _ 1 (cons _ 2 (cons _ 3 (nil _))).\n\n(* ----------------------------------------------------------------- *)\n(** *** Implicit Arguments *)\n\n(** In fact, we can go further and even avoid writing [_]'s in most\n    cases by telling Coq _always_ to infer the type argument(s) of a\n    given function.\n\n    The [Arguments] directive specifies the name of the function (or\n    constructor) and then lists its argument names, with curly braces\n    around any arguments to be treated as implicit.  (If some\n    arguments of a definition don't have a name, as is often the case\n    for constructors, they can be marked with a wildcard pattern\n    [_].) *)\n\nArguments nil {X}.\nArguments cons {X} _ _.\nArguments repeat {X} x count.\n\n(** Now, we don't have to supply type arguments at all: *)\n\nDefinition list123'' := cons 1 (cons 2 (cons 3 nil)).\n\n(** Alternatively, we can declare an argument to be implicit\n    when defining the function itself, by surrounding it in curly\n    braces instead of parens.  For example: *)\n\nFixpoint repeat''' {X : Type} (x : X) (count : nat) : list X :=\n  match count with\n  | 0        => nil\n  | S count' => cons x (repeat''' x count')\n  end.\n\n(** (Note that we didn't even have to provide a type argument to the\n    recursive call to [repeat'''].  Indeed, it would be invalid to\n    provide one, because Coq is not expecting it.)\n\n    We will use the latter style whenever possible, but we will\n    continue to use explicit [Argument] declarations for [Inductive]\n    constructors.  The reason for this is that marking the parameter\n    of an inductive type as implicit causes it to become implicit for\n    the type itself, not just for its constructors.  For instance,\n    consider the following alternative definition of the [list]\n    type: *)\n\nInductive list' {X:Type} : Type :=\n  | nil'\n  | cons' (x : X) (l : list').\n\n(** Because [X] is declared as implicit for the _entire_ inductive\n    definition including [list'] itself, we now have to write just\n    [list'] whether we are talking about lists of numbers or booleans\n    or anything else, rather than [list' nat] or [list' bool] or\n    whatever; this is a step too far. *)\n\n(** Let's finish by re-implementing a few other standard list\n    functions on our new polymorphic lists... *)\n\nFixpoint app {X : Type} (l1 l2 : list X)\n             : (list X) :=\n  match l1 with\n  | nil      => l2\n  | cons h t => cons h (app t l2)\n  end.\n\nFixpoint rev {X:Type} (l:list X) : list X :=\n  match l with\n  | nil      => nil\n  | cons h t => app (rev t) (cons h nil)\n  end.\n\nFixpoint length {X : Type} (l : list X) : nat :=\n  match l with\n  | nil => 0\n  | cons _ l' => S (length l')\n  end.\n\nExample test_rev1 :\n  rev (cons 1 (cons 2 nil)) = (cons 2 (cons 1 nil)).\nProof. reflexivity. Qed.\n\nExample test_rev2:\n  rev (cons true nil) = cons true nil.\nProof. reflexivity. Qed.\n\nExample test_length1: length (cons 1 (cons 2 (cons 3 nil))) = 3.\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Supplying Type Arguments Explicitly *)\n\n(** One small problem with declaring arguments [Implicit] is\n    that, once in a while, Coq does not have enough local information\n    to determine a type argument; in such cases, we need to tell Coq\n    that we want to give the argument explicitly just this time.  For\n    example, suppose we write this: *)\n\nFail Definition mynil := nil.\n\n(** (The [Fail] qualifier that appears before [Definition] can be\n    used with _any_ command, and is used to ensure that that command\n    indeed fails when executed. If the command does fail, Coq prints\n    the corresponding error message, but continues processing the rest\n    of the file.)\n\n    Here, Coq gives us an error because it doesn't know what type\n    argument to supply to [nil].  We can help it by providing an\n    explicit type declaration (so that Coq has more information\n    available when it gets to the \"application\" of [nil]): *)\n\nDefinition mynil : list nat := nil.\n\n(** Alternatively, we can force the implicit arguments to be explicit by\n   prefixing the function name with [@]. *)\n\nCheck @nil : forall X : Type, list X.\n\nDefinition mynil' := @nil nat.\n\n(** Using argument synthesis and implicit arguments, we can\n    define convenient notation for lists, as before.  Since we have\n    made the constructor type arguments implicit, Coq will know to\n    automatically infer these when we use the notations. *)\n\nNotation \"x :: y\" := (cons x y)\n                     (at level 60, right associativity).\nNotation \"[ ]\" := nil.\nNotation \"[ x ; .. ; y ]\" := (cons x .. (cons y []) ..).\nNotation \"x ++ y\" := (app x y)\n                     (at level 60, right associativity).\n\n(** Now lists can be written just the way we'd hope: *)\n\nDefinition list123''' := [1; 2; 3].\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 2 stars, standard, optional (poly_exercises) \n\n    Here are a few simple exercises, just like ones in the [Lists]\n    chapter, for practice with polymorphism.  Complete the proofs below. *)\n\nTheorem app_nil_r : forall (X:Type), forall l:list X,\n  l ++ [] = l.\nProof.\n  intros. simpl. induction l.\n  - reflexivity.\n  - simpl. rewrite IHl. reflexivity.\nQed.\n\nTheorem app_assoc : forall A (l m n:list A),\n  l ++ m ++ n = (l ++ m) ++ n.\nProof.\n  intros. induction l; simpl.\n  - reflexivity.\n  - rewrite IHl. reflexivity.\nQed.\n\nLemma app_length : forall (X:Type) (l1 l2 : list X),\n  length (l1 ++ l2) = length l1 + length l2.\nProof.\n  intros. induction l1; simpl.\n  - reflexivity.\n  - rewrite IHl1. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, optional (more_poly_exercises) \n\n    Here are some slightly more interesting ones... *)\n\nTheorem rev_app_distr: forall X (l1 l2 : list X),\n  rev (l1 ++ l2) = rev l2 ++ rev l1.\nProof.\n  intros. induction l1; simpl.\n  - rewrite app_nil_r. reflexivity.\n  - rewrite IHl1. rewrite app_assoc. reflexivity.\nQed.\n\nTheorem rev_involutive : forall X : Type, forall l : list X,\n  rev (rev l) = l.\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. rewrite rev_app_distr. rewrite IHl. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Pairs *)\n\n(** Following the same pattern, the definition for pairs of\n    numbers that we gave in the last chapter can be generalized to\n    _polymorphic pairs_, often called _products_: *)\n\nInductive prod (X Y : Type) : Type :=\n| pair (x : X) (y : Y).\n\nArguments pair {X} {Y} _ _.\n\n(** As with lists, we make the type arguments implicit and define the\n    familiar concrete notation. *)\n\nNotation \"( x , y )\" := (pair x y).\n\n(** We can also use the [Notation] mechanism to define the standard\n    notation for product _types_: *)\n\nNotation \"X * Y\" := (prod X Y) : type_scope.\n\n(** (The annotation [: type_scope] tells Coq that this abbreviation\n    should only be used when parsing types, not when parsing\n    expressions.  This avoids a clash with the multiplication\n    symbol.) *)\n\n(** It is easy at first to get [(x,y)] and [X*Y] confused.\n    Remember that [(x,y)] is a _value_ built from two other values,\n    while [X*Y] is a _type_ built from two other types.  If [x] has\n    type [X] and [y] has type [Y], then [(x,y)] has type [X*Y]. *)\n\n(** The first and second projection functions now look pretty\n    much as they would in any functional programming language. *)\n\nDefinition fst {X Y : Type} (p : X * Y) : X :=\n  match p with\n  | (x, y) => x\n  end.\n\nDefinition snd {X Y : Type} (p : X * Y) : Y :=\n  match p with\n  | (x, y) => y\n  end.\n\n(** The following function takes two lists and combines them\n    into a list of pairs.  In other functional languages, it is often\n    called [zip]; we call it [combine] for consistency with Coq's\n    standard library. *)\n\nFixpoint combine {X Y : Type} (lx : list X) (ly : list Y)\n           : list (X*Y) :=\n  match lx, ly with\n  | [], _ => []\n  | _, [] => []\n  | x :: tx, y :: ty => (x, y) :: (combine tx ty)\n  end.\n\n(** **** Exercise: 1 star, standard, optional (combine_checks) \n\n    Try answering the following questions on paper and\n    checking your answers in Coq:\n    - What is the type of [combine] (i.e., what does [Check\n      @combine] print?)\n    - What does\n\n        Compute (combine [1;2] [false;false;true;true]).\n\n      print?\n\n    [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (split) \n\n    The function [split] is the right inverse of [combine]: it takes a\n    list of pairs and returns a pair of lists.  In many functional\n    languages, it is called [unzip].\n\n    Fill in the definition of [split] below.  Make sure it passes the\n    given unit test. *)\n\nFixpoint split {X Y : Type} (l : list (X*Y))\n               : (list X) * (list Y) :=\n               match l with \n               | nil => ([], [])\n               | (x, y) :: t => match split t with \n                                | (xs, ys) => (x :: xs, y :: ys)\n                                end\n               end.\n\nExample test_split:\n  split [(1,false);(2,false)] = ([1;2],[false;false]).\nProof.\n  intros. reflexivity.\nQed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Polymorphic Options *)\n\n(** Our last polymorphic type for now is _polymorphic options_,\n    which generalize [natoption] from the previous chapter.  (We put\n    the definition inside a module because the standard library\n    already defines [option] and it's this one that we want to use\n    below.) *)\n\nModule OptionPlayground.\n\nInductive option (X:Type) : Type :=\n  | Some (x : X)\n  | None.\n\nArguments Some {X} _.\nArguments None {X}.\n\nEnd OptionPlayground.\n\n(** We can now rewrite the [nth_error] function so that it works\n    with any type of lists. *)\n\nFixpoint nth_error {X : Type} (l : list X) (n : nat)\n                   : option X :=\n  match l with\n  | [] => None\n  | a :: l' => if n =? O then Some a else nth_error l' (pred n)\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 [[1];[2]] 1 = Some [2].\nProof. reflexivity. Qed.\nExample test_nth_error3 : nth_error [true] 2 = None.\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, standard, optional (hd_error_poly) \n\n    Complete the definition of a polymorphic version of the\n    [hd_error] function from the last chapter. Be sure that it\n    passes the unit tests below. *)\n\nDefinition hd_error {X : Type} (l : list X) : option X := \n  match l with \n  | nil => None\n  | h :: _ => Some h\n  end.\n\n(** Once again, to force the implicit arguments to be explicit,\n    we can use [@] before the name of the function. *)\n\nCheck @hd_error : forall X : Type, list X -> option X.\n\nExample test_hd_error1 : hd_error [1;2] = Some 1.\nProof. simpl. reflexivity. Qed.\nExample test_hd_error2 : hd_error  [[1];[2]]  = Some [1].\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ################################################################# *)\n(** * Functions as Data *)\n\n(** Like most modern programming languages -- especially other\n    \"functional\" languages, including OCaml, Haskell, Racket, Scala,\n    Clojure, etc. -- Coq treats functions as first-class citizens,\n    allowing them to be passed as arguments to other functions,\n    returned as results, stored in data structures, etc. *)\n\n(* ================================================================= *)\n(** ** Higher-Order Functions *)\n\n(** Functions that manipulate other functions are often called\n    _higher-order_ functions.  Here's a simple one: *)\n\nDefinition doit3times {X:Type} (f:X->X) (n:X) : X :=\n  f (f (f n)).\n\n(** The argument [f] here is itself a function (from [X] to\n    [X]); the body of [doit3times] applies [f] three times to some\n    value [n]. *)\n\nCheck @doit3times : forall X : Type, (X -> X) -> X -> X.\n\nExample test_doit3times: doit3times minustwo 9 = 3.\nProof. reflexivity. Qed.\n\nExample test_doit3times': doit3times negb true = false.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Filter *)\n\n(** Here is a more useful higher-order function, taking a list\n    of [X]s and a _predicate_ on [X] (a function from [X] to [bool])\n    and \"filtering\" the list, returning a new list containing just\n    those elements for which the predicate returns [true]. *)\n\nFixpoint filter {X:Type} (test: X->bool) (l:list X)\n                : (list X) :=\n  match l with\n  | []     => []\n  | h :: t => if test h then h :: (filter test t)\n                        else       filter test t\n  end.\n\n(** For example, if we apply [filter] to the predicate [evenb]\n    and a list of numbers [l], it returns a list containing just the\n    even members of [l]. *)\n\nExample test_filter1: filter evenb [1;2;3;4] = [2;4].\nProof. reflexivity. Qed.\n\nDefinition length_is_1 {X : Type} (l : list X) : bool :=\n  (length l) =? 1.\n\nExample test_filter2:\n    filter length_is_1\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** We can use [filter] to give a concise version of the\n    [countoddmembers] function from the [Lists] chapter. *)\n\nDefinition countoddmembers' (l:list nat) : nat :=\n  length (filter oddb l).\n\nExample test_countoddmembers'1:   countoddmembers' [1;0;3;1;4;5] = 4.\nProof. reflexivity. Qed.\nExample test_countoddmembers'2:   countoddmembers' [0;2;4] = 0.\nProof. reflexivity. Qed.\nExample test_countoddmembers'3:   countoddmembers' nil = 0.\nProof. reflexivity. Qed.\n\n(* ================================================================= *)\n(** ** Anonymous Functions *)\n\n(** It is arguably a little sad, in the example just above, to\n    be forced to define the function [length_is_1] and give it a name\n    just to be able to pass it as an argument to [filter], since we\n    will probably never use it again.  Moreover, this is not an\n    isolated example: when using higher-order functions, we often want\n    to pass as arguments \"one-off\" functions that we will never use\n    again; having to give each of these functions a name would be\n    tedious.\n\n    Fortunately, there is a better way.  We can construct a function\n    \"on the fly\" without declaring it at the top level or giving it a\n    name. *)\n\nExample test_anon_fun':\n  doit3times (fun n => n * n) 2 = 256.\nProof. reflexivity. Qed.\n\n(** The expression [(fun n => n * n)] can be read as \"the function\n    that, given a number [n], yields [n * n].\" *)\n\n(** Here is the [filter] example, rewritten to use an anonymous\n    function. *)\n\nExample test_filter2':\n    filter (fun l => (length l) =? 1)\n           [ [1; 2]; [3]; [4]; [5;6;7]; []; [8] ]\n  = [ [3]; [4]; [8] ].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 2 stars, standard (filter_even_gt7) \n\n    Use [filter] (instead of [Fixpoint]) to write a Coq function\n    [filter_even_gt7] that takes a list of natural numbers as input\n    and returns a list of just those that are even and greater than\n    7. *)\n\nDefinition filter_even_gt7 (l : list nat) : list nat := \n  filter (fun x => andb (negb (x <=? 7)) (evenb x)) l.\n\nExample test_filter_even_gt7_1 :\n  filter_even_gt7 [1;2;6;9;10;3;12;8] = [10;12;8].\nProof. simpl. reflexivity. Qed.\n\nExample test_filter_even_gt7_2 :\n  filter_even_gt7 [5;2;6;19;129] = [].\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (partition) \n\n    Use [filter] to write a Coq function [partition]:\n\n      partition : forall X : Type,\n                  (X -> bool) -> list X -> list X * list X\n\n   Given a set [X], a predicate of type [X -> bool] and a [list X],\n   [partition] should return a pair of lists.  The first member of the\n   pair is the sublist of the original list containing the elements\n   that satisfy the test, and the second is the sublist containing\n   those that fail the test.  The order of elements in the two\n   sublists should be the same as their order in the original list. *)\n\nDefinition partition {X : Type}\n                     (test : X -> bool)\n                     (l : list X)\n                   : list X * list X :=\n                   (filter test l, filter (fun x => negb (test x)) l).\n\nExample test_partition1: partition oddb [1;2;3;4;5] = ([1;3;5], [2;4]).\nProof. simpl. reflexivity. Qed.\nExample test_partition2: partition (fun x => false) [5;9;0] = ([], [5;9;0]).\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Map *)\n\n(** Another handy higher-order function is called [map]. *)\n\nFixpoint map {X Y: Type} (f:X->Y) (l:list X) : (list Y) :=\n  match l with\n  | []     => []\n  | h :: t => (f h) :: (map f t)\n  end.\n\n(** It takes a function [f] and a list [ l = [n1, n2, n3, ...] ]\n    and returns the list [ [f n1, f n2, f n3,...] ], where [f] has\n    been applied to each element of [l] in turn.  For example: *)\n\nExample test_map1: map (fun x => plus 3 x) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** The element types of the input and output lists need not be\n    the same, since [map] takes _two_ type arguments, [X] and [Y]; it\n    can thus be applied to a list of numbers and a function from\n    numbers to booleans to yield a list of booleans: *)\n\nExample test_map2:\n  map oddb [2;1;2;5] = [false;true;false;true].\nProof. reflexivity. Qed.\n\n(** It can even be applied to a list of numbers and\n    a function from numbers to _lists_ of booleans to\n    yield a _list of lists_ of booleans: *)\n\nExample test_map3:\n    map (fun n => [evenb n;oddb n]) [2;1;2;5]\n  = [[true;false];[false;true];[true;false];[false;true]].\nProof. reflexivity. Qed.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exercises *)\n\n(** **** Exercise: 3 stars, standard (map_rev) \n\n    Show that [map] and [rev] commute.  You may need to define an\n    auxiliary lemma. *)\n\nTheorem map_rev : forall (X Y : Type) (f : X -> Y) (l : list X),\n  map f (rev l) = rev (map f l).\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. \n    assert (H: forall xs, forall v, map f (xs ++ [v]) = map f xs ++ [f v]). {\n      intros. induction xs.\n        + reflexivity.\n        + simpl. rewrite IHxs. reflexivity.\n    }\n    rewrite H. rewrite IHl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, standard, recommended (flat_map) \n\n    The function [map] maps a [list X] to a [list Y] using a function\n    of type [X -> Y].  We can define a similar function, [flat_map],\n    which maps a [list X] to a [list Y] using a function [f] of type\n    [X -> list Y].  Your definition should work by 'flattening' the\n    results of [f], like so:\n\n        flat_map (fun n => [n;n+1;n+2]) [1;5;10]\n      = [1; 2; 3; 5; 6; 7; 10; 11; 12].\n*)\n\nFixpoint flat_map {X Y: Type} (f: X -> list Y) (l: list X)\n                   : (list Y) := \n                   match l with \n                   | [] => []\n                   | h :: t => f h ++ flat_map f t\n                   end.\n\n\nExample test_flat_map1:\n  flat_map (fun n => [n;n;n]) [1;5;4]\n  = [1; 1; 1; 5; 5; 5; 4; 4; 4].\nProof. simpl. reflexivity. Qed.\n(** [] *)\n\n(** Lists are not the only inductive type for which [map] makes sense.\n    Here is a [map] for the [option] type: *)\n\nDefinition option_map {X Y : Type} (f : X -> Y) (xo : option X)\n                      : option Y :=\n  match xo with\n    | None => None\n    | Some x => Some (f x)\n  end.\n\n(** **** Exercise: 2 stars, standard, optional (implicit_args) \n\n    The definitions and uses of [filter] and [map] use implicit\n    arguments in many places.  Replace the curly braces around the\n    implicit arguments with parentheses, and then fill in explicit\n    type parameters where necessary and use Coq to check that you've\n    done so correctly.  (This exercise is not to be turned in; it is\n    probably easiest to do it on a _copy_ of this file that you can\n    throw away afterwards.)\n*)\n(** [] *)\n\n(* ================================================================= *)\n(** ** Fold *)\n\n(** An even more powerful higher-order function is called\n    [fold].  This function is the inspiration for the \"[reduce]\"\n    operation that lies at the heart of Google's map/reduce\n    distributed programming framework. *)\n\nFixpoint fold {X Y: Type} (f: X->Y->Y) (l: list X) (b: Y)\n                         : Y :=\n  match l with\n  | nil => b\n  | h :: t => f h (fold f t b)\n  end.\n\n(** Intuitively, the behavior of the [fold] operation is to\n    insert a given binary operator [f] between every pair of elements\n    in a given list.  For example, [ fold plus [1;2;3;4] ] intuitively\n    means [1+2+3+4].  To make this precise, we also need a \"starting\n    element\" that serves as the initial second input to [f].  So, for\n    example,\n\n       fold plus [1;2;3;4] 0\n\n    yields\n\n       1 + (2 + (3 + (4 + 0))).\n\n    Some more examples: *)\n\nCheck (fold andb) : list bool -> bool -> bool.\n\nExample fold_example1 :\n  fold mult [1;2;3;4] 1 = 24.\nProof. reflexivity. Qed.\n\nExample fold_example2 :\n  fold andb [true;true;false;true] true = false.\nProof. reflexivity. Qed.\n\nExample fold_example3 :\n  fold app  [[1];[];[2;3];[4]] [] = [1;2;3;4].\nProof. reflexivity. Qed.\n\n(** **** Exercise: 1 star, advanced (fold_types_different) \n\n    Observe that the type of [fold] is parameterized by _two_ type\n    variables, [X] and [Y], and the parameter [f] is a binary operator\n    that takes an [X] and a [Y] and returns a [Y].  Can you think of a\n    situation where it would be useful for [X] and [Y] to be\n    different? *)\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_types_different : option (nat*string) := None.\n(** [] *)\n\n(* ================================================================= *)\n(** ** Functions That Construct Functions *)\n\n(** Most of the higher-order functions we have talked about so\n    far take functions as arguments.  Let's look at some examples that\n    involve _returning_ functions as the results of other functions.\n    To begin, here is a function that takes a value [x] (drawn from\n    some type [X]) and returns a function from [nat] to [X] that\n    yields [x] whenever it is called, ignoring its [nat] argument. *)\n\nDefinition constfun {X: Type} (x: X) : nat->X :=\n  fun (k:nat) => x.\n\nDefinition ftrue := constfun true.\n\nExample constfun_example1 : ftrue 0 = true.\nProof. reflexivity. Qed.\n\nExample constfun_example2 : (constfun 5) 99 = 5.\nProof. reflexivity. Qed.\n\n(** In fact, the multiple-argument functions we have already\n    seen are also examples of passing functions as data.  To see why,\n    recall the type of [plus]. *)\n\nCheck plus : nat -> nat -> nat.\n\n(** Each [->] in this expression is actually a _binary_ operator\n    on types.  This operator is _right-associative_, so the type of\n    [plus] is really a shorthand for [nat -> (nat -> nat)] -- i.e., it\n    can be read as saying that \"[plus] is a one-argument function that\n    takes a [nat] and returns a one-argument function that takes\n    another [nat] and returns a [nat].\"  In the examples above, we\n    have always applied [plus] to both of its arguments at once, but\n    if we like we can supply just the first.  This is called _partial\n    application_. *)\n\nDefinition plus3 := plus 3.\nCheck plus3 : nat -> nat.\n\nExample test_plus3 :    plus3 4 = 7.\nProof. reflexivity. Qed.\nExample test_plus3' :   doit3times plus3 0 = 9.\nProof. reflexivity. Qed.\nExample test_plus3'' :  doit3times (plus 3) 0 = 9.\nProof. reflexivity. Qed.\n\n(* ################################################################# *)\n(** * Additional Exercises *)\n\nModule Exercises.\n\n(** **** Exercise: 2 stars, standard (fold_length) \n\n    Many common functions on lists can be implemented in terms of\n    [fold].  For example, here is an alternative definition of [length]: *)\n\nDefinition fold_length {X : Type} (l : list X) : nat :=\n  fold (fun _ n => S n) l 0.\n\nExample test_fold_length1 : fold_length [4;7;0] = 3.\nProof. reflexivity. Qed.\n\n(** Prove the correctness of [fold_length].  (Hint: It may help to\n    know that [reflexivity] simplifies expressions a bit more\n    aggressively than [simpl] does -- i.e., you may find yourself in a\n    situation where [simpl] does nothing but [reflexivity] solves the\n    goal.) *)\n\nTheorem fold_length_correct : forall X (l : list X),\n  fold_length l = length l.\nProof.\n  intros. induction l. \n  - reflexivity.\n  - simpl. rewrite <- IHl. reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 3 stars, standard (fold_map) \n\n    We can also define [map] in terms of [fold].  Finish [fold_map]\n    below. *)\n\nDefinition fold_map {X Y: Type} (f: X -> Y) (l: list X) : list Y := \n  fold (fun x accu => f x :: accu) l [].\n\n(** Write down a theorem [fold_map_correct] in Coq stating that\n   [fold_map] is correct, and prove it.  (Hint: again, remember that\n   [reflexivity] simplifies expressions a bit more aggressively than\n   [simpl].) *)\n\nTheorem fold_map_correct: forall X Y : Type, forall l : list X, forall f : X -> Y,\n  fold_map f l = map f l.\nProof.\n  intros. induction l.\n  - reflexivity.\n  - simpl. rewrite <- IHl. reflexivity.\nQed.\n\n\n(* FILL IN HERE *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_fold_map : option (nat*string) := None.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (currying) \n\n    In Coq, a function [f : A -> B -> C] really has the type [A\n    -> (B -> C)].  That is, if you give [f] a value of type [A], it\n    will give you function [f' : B -> C].  If you then give [f'] a\n    value of type [B], it will return a value of type [C].  This\n    allows for partial application, as in [plus3].  Processing a list\n    of arguments with functions that return functions is called\n    _currying_, in honor of the logician Haskell Curry.\n\n    Conversely, we can reinterpret the type [A -> B -> C] as [(A *\n    B) -> C].  This is called _uncurrying_.  With an uncurried binary\n    function, both arguments must be given at once as a pair; there is\n    no partial application. *)\n\n(** We can define currying as follows: *)\n\nDefinition prod_curry {X Y Z : Type}\n  (f : X * Y -> Z) (x : X) (y : Y) : Z := f (x, y).\n\n(** As an exercise, define its inverse, [prod_uncurry].  Then prove\n    the theorems below to show that the two are inverses. *)\n\nDefinition prod_uncurry {X Y Z : Type}\n  (f : X -> Y -> Z) (p : X * Y) : Z := \n  match p with \n  | (x, y) => f x y\n  end.\n\n(** As a (trivial) example of the usefulness of currying, we can use it\n    to shorten one of the examples that we saw above: *)\n\nExample test_map1': map (plus 3) [2;0;2] = [5;3;5].\nProof. reflexivity. Qed.\n\n(** Thought exercise: before running the following commands, can you\n    calculate the types of [prod_curry] and [prod_uncurry]? *)\n\nCheck @prod_curry.\nCheck @prod_uncurry.\n\nTheorem uncurry_curry : forall (X Y Z : Type)\n                        (f : X -> Y -> Z)\n                        x y,\n  prod_curry (prod_uncurry f) x y = f x y.\nProof.\n  intros. reflexivity. \nQed.\n\nTheorem curry_uncurry : forall (X Y Z : Type)\n                        (f : (X * Y) -> Z) (p : X * Y),\n  prod_uncurry (prod_curry f) p = f p.\nProof.\n  intros. destruct p.\n  - reflexivity.\nQed.\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (nth_error_informal) \n\n    Recall the definition of the [nth_error] function:\n\n   Fixpoint nth_error {X : Type} (l : list X) (n : nat) : option X :=\n     match l with\n     | [] => None\n     | a :: l' => if n =? O then Some a else nth_error l' (pred n)\n     end.\n\n   Write an informal proof of the following theorem:\n\n   forall X l n, length l = n -> @nth_error X l n = None\n*)\n(* FILL IN HERE *)\n\n(* Theorem nth_of_length_n: forall X l n, \n  length l = n -> @nth_error X l n = None.\nProof.\n  intros. induction l as [ | h t IHl'].\n  - simpl. reflexivity.\n  - simpl in H. \nQed. *)\n\n(* Do not modify the following line: *)\nDefinition manual_grade_for_informal_proof : option (nat*string) := None.\n(** [] *)\n\n(** The following exercises explore an alternative way of defining\n    natural numbers, using the so-called _Church numerals_, named\n    after mathematician Alonzo Church.  We can represent a natural\n    number [n] as a function that takes a function [f] as a parameter\n    and returns [f] iterated [n] times. *)\n\nModule Church.\nDefinition cnat := forall X : Type, (X -> X) -> X -> X.\n\n(** Let's see how to write some numbers with this notation. Iterating\n    a function once should be the same as just applying it.  Thus: *)\n\nDefinition one : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f x.\n\n(** Similarly, [two] should apply [f] twice to its argument: *)\n\nDefinition two : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => f (f x).\n\n(** Defining [zero] is somewhat trickier: how can we \"apply a function\n    zero times\"?  The answer is actually simple: just return the\n    argument untouched. *)\n\nDefinition zero : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => x.\n\n(** More generally, a number [n] can be written as [fun X f x => f (f\n    ... (f x) ...)], with [n] occurrences of [f].  Notice in\n    particular how the [doit3times] function we've defined previously\n    is actually just the Church representation of [3]. *)\n\nDefinition three : cnat := @doit3times.\n\n(** Complete the definitions of the following functions. Make sure\n    that the corresponding unit tests pass by proving them with\n    [reflexivity]. *)\n\n(** **** Exercise: 1 star, advanced (church_succ)  *)\n\n(** Successor of a natural number: given a Church numeral [n],\n    the successor [succ n] is a function that iterates its\n    argument once more than [n]. *)\nDefinition succ (n : cnat) : cnat :=\n  fun (X : Type) (f : X -> X) (x : X) => n X f (f x).\n\nExample succ_1 : succ zero = one.\nProof. simpl. reflexivity. Qed.\n\nExample succ_2 : succ one = two.\nProof. simpl. reflexivity. Qed.\n\nExample succ_3 : succ two = three.\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 1 star, advanced (church_plus)  *)\n\n(** Addition of two natural numbers: *)\nDefinition plus (n m : cnat) : cnat := \n  fun (X : Type) (f : X -> X) (x : X) => n X f (m X f x).\n\nExample plus_1 : plus zero one = one.\nProof. simpl. reflexivity. Qed.\n\nExample plus_2 : plus two three = plus three two.\nProof. simpl. reflexivity. Qed.\n\nExample plus_3 :\n  plus (plus two two) three = plus one (plus three three).\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_mult)  *)\n\n(** Multiplication: *)\nDefinition mult (n m : cnat) : cnat := \n  fun (X : Type) (f : X -> X) (x : X) => n X (m X f) x.\n\nExample mult_1 : mult one one = one.\nProof. simpl. reflexivity. Qed.\n\nExample mult_2 : mult zero (plus three three) = zero.\nProof. simpl. reflexivity. Qed.\n\nExample mult_3 : mult two three = plus three three.\nProof. simpl. reflexivity. Qed.\n\n(** [] *)\n\n(** **** Exercise: 2 stars, advanced (church_exp)  *)\n\n(** Exponentiation: *)\n\n(** (_Hint_: Polymorphism plays a crucial role here.  However,\n    choosing the right type to iterate over can be tricky.  If you hit\n    a \"Universe inconsistency\" error, try iterating over a different\n    type.  Iterating over [cnat] itself is usually problematic.) *)\n\nDefinition exp (n m : cnat) : cnat . Admitted.\n       \nExample exp_1 : exp two two = plus two two.\nProof. Admitted.\n\nExample exp_2 : exp three zero = one.\nProof. Admitted.\n\nExample exp_3 : exp three two = plus (mult two (mult two two)) one.\nProof. Admitted.\n\n(** [] *)\n\nEnd Church.\n\nEnd Exercises.\n\n\n(* Tue Oct 8 15:58:02 EDT 2019 *)\n", "meta": {"author": "Shuumatsu", "repo": "logical-foundations", "sha": "1d45cd66513aa6a736e228e3aac72a3c390799fd", "save_path": "github-repos/coq/Shuumatsu-logical-foundations", "path": "github-repos/coq/Shuumatsu-logical-foundations/logical-foundations-1d45cd66513aa6a736e228e3aac72a3c390799fd/Poly.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749421, "lm_q2_score": 0.867035763237924, "lm_q1q2_score": 0.7006231772578569}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bvector.\nRequire Import List.\nRequire Import Arith.\n\nRequire Import HMAC_functional_prog.\nRequire Import Integers.\nRequire Import Coqlib.\n\n(* Require Import List. Import ListNotations. *)\n\nDefinition Blist := list bool.\n\nFixpoint splitVector (A : Set) (n m : nat) :\n  Vector.t A (n + m) -> (Vector.t A n * Vector.t A m) :=\n  match n with\n    | 0%nat =>\n      fun (v : Vector.t A (O + m)) => (@Vector.nil A, v) (* why the function? TODO *)\n    | S n' =>\n      fun (v : Vector.t A (S n' + m)) =>\n        let (v1, v2) := splitVector _ _ (Vector.tl v) in\n          (Vector.cons _ (Vector.hd v) _ v1, v2)\n  end.\n\nEval compute in splitVector 1 2 [true; true; true].\n\nSection HMAC.\n\nSearchAbout Bvector.\nPrint Bvector.\nCheck Bvector 10.\nCheck [true].\nPrint Vector.\n\n(* b = block size\n   c = digest (output) size\n   p = padding = b - c (fixed) *)\n  Variable c p : nat.\n  Definition b := (c + p)%nat.\n\n  (* The compression function *)\n  Variable h : Bvector c -> Bvector b -> Bvector c.\n  (* The initialization vector is part of the spec of the hash function. *)\n  Variable iv : Bvector c.\n  (* The iteration of the compression function gives a keyed hash function on lists of words. *)\n  Definition h_star k (m : list (Bvector b)) :=\n    fold_left h m k.\n  (* The composition of the keyed hash function with the IV gives a hash function on lists of words. *)\n  Definition hash_words := h_star iv.\n\n  (* TODO check how this corresponds to SHA\n     Seems that h = SHA compression function\n     hash_words with SHA's iv is SHA\n   *)\n  Check hash_words.\n  Check h_star.\n\n  Variable splitAndPad : Blist -> list (Bvector b).\n\n  Hypothesis splitAndPad_1_1 :\n    forall b1 b2,\n      splitAndPad b1 = splitAndPad b2 ->\n      b1 = b2.\n\n  (* constant-length padding. *)\n  Variable fpad : Bvector p.\n\n  Definition app_fpad (x : Bvector c) : Bvector b :=\n    (Vector.append x fpad).\n  Definition h_star_pad k x :=\n    app_fpad (h_star k x).\n\n  Definition GNMAC k m :=\n    let (k_Out, k_In) := splitVector c c k in\n    h k_Out (app_fpad (h_star k_In m)).\n\nCheck hash_words.\n\n  (* The \"two-key\" version of GHMAC and HMAC. *)\n  (* Concatenate (K xor opad) and (K xor ipad) *)\n  Definition GHMAC_2K (k : Bvector (b + b)) m :=\n    let (k_Out, k_In) := splitVector b b k in (* concat earlier, then split *)\n      let h_in := (hash_words (k_In :: m)) in\n        hash_words (k_Out :: (app_fpad h_in) :: nil).\n\nSearchAbout Bvector.\n\n  Definition HMAC_2K (k : Bvector (b + b)) (m : Blist) :=\n    GHMAC_2K k (splitAndPad m).\n\nCheck HMAC_2K.\n(* HMAC_2K\n     : Bvector (b + b) -> Blist -> Bvector c *)\n\n(* opad and ipad are constants defined in the HMAC spec. *)\nVariable opad ipad : Bvector b.\nDefinition GHMAC (k : Bvector b) :=\n  GHMAC_2K (Vector.append (BVxor _ k opad) (BVxor _ k ipad)).\n\nPrint BVxor.\n\n\nDefinition HMAC (k : Bvector b) :=\n  HMAC_2K (Vector.append (BVxor _ k opad) (BVxor _ k ipad)).\n\nCheck HMAC.                     (*  : Bvector b -> Blist -> Bvector c *)\n\nEnd HMAC.\n\n(* ----------------------------------------------------------- Theorem definitions *)\n\nCheck HMAC_SHA256.HMAC.            (* list Z -> list Z -> list Z *)\n\n  (* Bvector is little-endian (least significant bit at head; list Z are just translated\nfrom the string (ascii -> nat -> Z); but Int are packed big-endian (with 4 Z -> 1 Int)\n\neach Z is one byte (8 bits) *)\n\n(* TODO: add isbyteZ (from SHA256.v), 0 <= i <= 256 *)\n\n(* *************** byte/bit computational *)\n\n(* TODO: finish this\n\nThe term \"Vector.append (iterate n' num_new) [bool_digit]\" has type\n \"Vector.t bool (n' + 1)\" while it is expected to have type\n\"Bvector (S n')\".\n\nFunction with proof of equivalence? see hash_blocks  *)\n\n(*\nFixpoint iterate (n : nat) (byte : nat) : Bvector n :=\n  match n as x return Bvector x with\n    | O => Vector.nil bool\n    | S n' =>\n      let byte_subtract := (byte - NPeano.pow 2 n')%nat in\n      let bool_digit := negb (leb byte_subtract 0) in\n      let num_new := if bool_digit then byte_subtract else byte in\n      Vector.append (iterate n' num_new) [bool_digit] (* could reverse instead *)\n  end.\n\n*)\n\nLemma add_1_r_S : forall (n : nat), (n + 1)%nat = S n.\nProof.\n  induction n.\n    reflexivity.\n    simpl. rewrite -> IHn. reflexivity.\nDefined.\n\n(* TODO step through this *)\nLocate leb. Check negb.\n(* little-endian *)\nFixpoint iterate (n : nat) (byte : nat) : Bvector n.\nProof.\n  destruct n.\n     apply (Vector.nil bool).\n  remember ((byte - NPeano.pow 2 n)%nat) as byte_subtract.\n  remember (negb (leb byte_subtract 0)) as bool_digit. (* changed from leb: gt now *)\n  remember (if bool_digit then byte_subtract else byte) as num_new.\n  rewrite <- add_1_r_S.\n  apply (Vector.append (iterate n num_new) [bool_digit]). (* n' *)\nDefined.\n\nPrint iterate.\nEval compute in iterate 1 255.\nCheck eq_rec. Print eq_rec. Print eq_rect. Check eq_rect.\nPrint NPeano.Nat.add_1_r.\n\n(* TODO: fix the latter + 1 *)\nFixpoint byte_to_bits (byte : Z) : Bvector 8 :=\n  let max_pow_two := 7%nat in\n  iterate (max_pow_two + 1) (nat_of_Z byte + 1).\n\n  Print add_1_r_S.\nEval compute in iterate 8 2.\nEval compute in byte_to_bits 0.\nEval compute in byte_to_bits 1.\nEval compute in byte_to_bits 2.\n\nEval compute in byte_to_bits 127.\nEval compute in byte_to_bits 128.\nEval compute in byte_to_bits 129.\nEval compute in byte_to_bits 200.\nEval compute in byte_to_bits 255.\nEval compute in byte_to_bits 256. (* not valid *)\n\n(* Parameter byte_to_bits : Z -> Bvector 8. *)\n\n(* Or: concatMap byte_to_bit bytes *)\nCheck Bvector.\nSearchAbout Bvector.\nPrint Vector.t.\n\n(* how to prove that it's length bytes * 8? *)\n(* list of bytes? (type) *)\nFixpoint bytes_to_bits (bytes : list Z) : Bvector (length bytes * 8) :=\n  match bytes as x return Bvector (length x * 8) with (* CPDT *)\n    | nil => Vector.nil bool\n    | x :: xs => Vector.append (byte_to_bits x) (bytes_to_bits xs)\n  end.\n\n\n\n(* ************* inductive defs *)\n\nSearchAbout Bvector.\n\nDefinition asZ (x : bool) : Z := if x then 1 else 0.\n\n(* TODO: maybe prefer b : byte, with Byte.repr? *)\nDefinition convertByteBits (b : Z) (B : Bvector 8) : Prop :=\n  exists (b0 b1 b2 b3 b4 b5 b6 b7 : bool),\n   B = [b0; b1; b2; b3; b4; b5; b6; b7] /\\\n   b =  (1 * (asZ b0) + 2 * (asZ b1) + 4 * (asZ b2) + 8 * (asZ b3)\n         + 16 * (asZ b4) + 32 * (asZ b5) + 64 * (asZ b6) + 128 * (asZ b7)).\n\n(* *** *)\n\n(* relating list Z to Blist\nbytes_to_bits m = length M\n\nTODO: big-endian, little-endian?\n*)\nInductive bytes_bits_lists : list Z -> Blist -> Prop :=\n  | eq_empty : bytes_bits_lists nil nil\n  | eq_cons : forall (bytes : list Z) (bits : Blist)\n                     (byte : Z) (b0 b1 b2 b3 b4 b5 b6 b7 : bool),\n                bytes_bits_lists bytes bits ->\n                convertByteBits byte [b0; b1; b2; b3; b4; b5; b6; b7] ->\n                bytes_bits_lists (byte :: bytes)\n                                (b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: bits).\n\n(*\nInductive bytes_bits_vector' (l : list Z) : Bvector (8 * length l) -> Prop :=\n  | eq_empty_v : forall (bits : Bvector (8 * length nil)),\n                   bytes_bits_vector' nil bits\n  (* TODO: might want to use Vector.nil bool? *)\n  | eq_cons_v : forall (bytes : list Z) (bits : Bvector (8 * length bytes))\n                       (byte : Z) (b0 b1 b2 b3 b4 b5 b6 b7 : bool),\n                  bytes_bits_vector' bytes bits ->\n                  convertByteBits byte [b0; b1; b2; b3; b4; b5; b6; b7] ->\n                  bytes_bits_vector' (byte :: bytes)\n                                     (* TODO: is this the right endianness? *)\n                                     (Vector.append [b0; b1; b2; b3; b4; b5; b6; b7] bits)\n.\n*)\n\nLemma list_cons_len {A : Type} :\n      forall (x : A) (xs : list A), length (x :: xs) = (1 + length xs)%nat.\nProof. intros. reflexivity. Defined.\n\nLemma mul_dist : forall (n m : nat), (n * (1 + m))%nat = (n + n * m)%nat.\nProof.\n  intros. simpl.\n  rewrite -> mult_succ_r. rewrite -> plus_comm. reflexivity.\nDefined.\n\nPrint mult_succ_r.\nPrint plus_comm.\n\nFixpoint squash_list_vector\n         (bits_list : list (Bvector 8)) : Bvector (8 * length bits_list).\nProof.\n  destruct bits_list.\n    apply (Vector.nil bool).\n    rewrite -> list_cons_len.\n    rewrite -> mul_dist.\n    (* TODO watch out for endianness *)\n  apply (Vector.append b0 (squash_list_vector bits_list)).\nDefined.\n\nSearchAbout Vector.cons.\nCheck Vector.cons.\nCheck Vector.cons bool true 1 [false].\n\n(* TODO: how to write a better dependent pattern match? doesn't use the equality of their len\nwriting it as a proof and destructing n or b1/b2 doesn't work\n*)\nFixpoint bvector_eq (n : nat) (m : nat) (b1 : Bvector n) (b2 : Bvector m) : bool :=\n  match b1, b2 with             (*  match n as n0 return (Bvector n0) with *)\n    | Vector.nil, Vector.nil => true\n    | Vector.cons x1 _ xs1, Vector.cons x2 _ xs2 =>\n      eqb x1 x2 && bvector_eq xs1 xs2\n    | _, _ => false\n  end.\n\n(* TODO watch out for endianness *)\n\nDefinition bytes_bits_vector_comp\n         (n : nat) (bytes : list Z) (bits : Bvector n) : bool.\nProof.\n  remember (map byte_to_bits bytes) as bits_list_vector.\n  remember (squash_list_vector bits_list_vector) as bvector.\n  apply (bvector_eq bvector bits).\nDefined.\n\nPrint bytes_bits_vector_comp.\n(* Seems hard to use in a proof... *)\n\n(* TODO: get this to be required *)\nEval compute in\n    bytes_bits_vector_comp (0 :: nil) [true; true; true; true; true; true; true; true].\n\nLemma bytes_bits_vector_comp_len : forall (n : nat) (bytes : list Z) (bits : Bvector n),\n                                     bytes_bits_vector_comp bytes bits = true\n                                     -> n = (8 * length bytes)%nat.\nProof.\n  (* TODO: bvector_eq is true iff the vectors are the same length *)\nAdmitted.\n\n(* --------------------- *)\n\n(* Lennart's definitions: *)\n\nDefinition bveqF :=\nfix bveqF (n : nat) (b1 b2 : Bvector n) {struct n} : bool :=\n  match n as n0 return (Bvector n0 -> Bvector n0 -> bool) with\n  | 0%nat => fun _ _ : Bvector 0 => true\n  | S n0 =>\n      fun b3 b4 : Bvector (S n0) =>\n      eqb (Vector.hd b3) (Vector.hd b4) &&\n      bveqF n0 (Vector.tl b3) (Vector.tl b4)\n  end b1 b2.\n\nFixpoint bveq (n:nat) (b1 b2:Bvector n): bool.\n  destruct n; intros. apply true. remember (S n) as m.\ndestruct b1. inversion Heqm. inversion Heqm. subst.  inversion b2. subst.\n  apply (eqb h h0 && bveq _ b1 H0).\n(*  apply (eqb (Vector.hd b1) (Vector.hd b2) && (bveq _ (Vector.tl b1) (Vector.tl b2))).*)\nDefined.\nPrint bveq.\n\nDefinition bveq1 (n:nat) (b1 b2:Bvector n): bool.\n  induction n; intros. apply true.\n  apply (eqb (Vector.hd b1) (Vector.hd b2) && (IHn (Vector.tl b1) (Vector.tl b2))).\nDefined.\n\nDefinition bveqD :=\nfun (n : nat) (b1 b2 : Bvector n) =>\nnat_rec (fun n0 : nat => Bvector n0 -> Bvector n0 -> bool)\n  (fun _ _ : Bvector 0 => true)\n  (fun (n0 : nat) (IHn : Bvector n0 -> Bvector n0 -> bool)\n     (b3 b4 : Bvector (S n0)) =>\n   eqb (Vector.hd b3) (Vector.hd b4) && IHn (Vector.tl b3) (Vector.tl b4)) n\n  b1 b2.\n\n\nEval compute in (bveqD [true; true; false] [true; true; false]).\n\n(* TODO watch out for endianness *)\nSearch Bvector.\n\n(* TODO replace bytes_bits_vector_comp with bytes_bits_vector *)\n\nInductive bytes_bits_vector : forall n\n         (bytes : list Z) (bits : Bvector n), Prop :=\n| bvv_nil: bytes_bits_vector nil []\n| bvv_cons: forall n bytes1 bits1\n                   (bt : Z) (b0 b1 b2 b3 b4 b5 b6 b7 : bool),\n              @bytes_bits_vector n bytes1 bits1 ->\n              convertByteBits bt [b0; b1; b2; b3; b4; b5; b6; b7] ->\n              @bytes_bits_vector (8 + n) (bt :: bytes1)\n                                     (* TODO: is this the right endianness? *)\n                                     (Vector.append [b0; b1; b2; b3; b4; b5; b6; b7] bits1).\n\nDefinition bytes_bits_vector_comp'\n         (bytes : list Z) (bits : Bvector (8 * length bytes)) : bool.\nProof.\n  remember (map byte_to_bits bytes) as bits_list_vector.\n  remember (squash_list_vector bits_list_vector) as bvector.\n  assert (len_eq: length bytes = length bits_list_vector).\n    rewrite -> Heqbits_list_vector.\n    rewrite -> list_length_map.\n    reflexivity.\n  rewrite -> len_eq in bits.\n  apply (bvector_eq bvector bits).\nDefined.\n\n(* ----------------------------------------- Theorem and parameters *)\n\nCheck HMAC_SHA256.HMAC.         (* ? *)\nCheck HMAC.\n(* HMAC\n     : forall c p : nat,\n       (Bvector c -> Bvector (b c p) -> Bvector c) ->   // compression function h\n       Bvector c ->                          // iv, h's initialization vector\n       (Blist -> list (Bvector (b c p))) ->  // splitAndPad (e.g. generate_and_pad)\n       Bvector p ->                          // fpad, constant-length padding\n       Bvector (b c p) ->                    // opad\n       Bvector (b c p) ->                    // ipad\n\n^ Note: this has to do with the internals of SHA256 and HMAC too\nSHA's compression function, iv, generate_and_pad (with block vectors),\nHMAC's key padding function, HMAC's opad and ipad.\nHow to convert?\n\n       Bvector (b c p) -> Blist -> Bvector c        // key, message, outputted hash\n\nk is of length b\nb = block size\nc = output size\np = padding = b - c\n\nwhy pad the key? why not just let it be size b?\n *)\n\n\n(* want Bvector b = 512 bits *)\nPrint Byte.int.\nPrint Byte.repr.\nCheck Byte.unsigned.\nCheck HMAC_SHA256.sixtyfour.\n\nDefinition opad_test :=\n     bytes_to_bits\n                     (map Byte.unsigned (HMAC_SHA256.sixtyfour (Byte.repr 52))).\nCheck opad_test.\n(* Definition ipad_test := bytes_to_bits\n                     (map Byte.unsigned (HMAC_SHA256.sixtyfour HMAC_SHA256.Ipad)). *)\n\nCheck HMAC.\n\n(* ------------------------------------- *)\nModule Equiv.\n\nDefinition c:nat := (SHA256_.DigestLength * 8)%nat.\n(*Variable p:nat.\nLocate HMAC.\nCheck @HMAC. Check @sha_h.\nCheck (@HMAC _ p (@sha_h _ p plus) sha_iv (sha_splitandpad_vector p) (fpad p)).\nCheck (HMAC (sha_h p plus) sha_iv).\n*)\nDefinition p:=(32 * 8)%nat.\n\nParameter sha_iv : Bvector (SHA256_.DigestLength * 8).\n\n(* Definition sha_h : list Z -> list Z := SHA256_.Hash. *)\nParameter sha_h : Bvector c -> Bvector (c + p) -> Bvector c.\n\n(* corresponds to block size. b = plus *)\n\n(*  \"Blist -> list (Bvector (b SHA256_.DigestLength c))\" *)\nParameter sha_splitandpad_vector :\n  Blist -> list (Bvector (SHA256_.DigestLength * 8 + p)).\n\nParameter fpad : Bvector p.\n\n(* Is this the theorem we want? Is it useful for the rest of the proofs?\nShould it be more abstract? *)\n\n(* TODO: opad <> ipad? *)\nLocate sixtyfour.\n\nDefinition bytes_bits_conv_vector'\n           (byte_pad : byte) (bits_pad : Bvector (c + p)) : Prop :=\n  let bytes_pad := map Byte.unsigned (HMAC_SHA256.sixtyfour byte_pad) in\n  bytes_bits_vector bytes_pad bits_pad.\n\n(* -------------- *)\n\n(*  (let (k_Out, k_In) :=\n                       splitVector (b 256 256) (b 256 256)\n                         (Vector.append (BVxor (b 256 256) K OP)\n                            (BVxor (b 256 256) K IP)) in\nPossibly try n = m -> splitVector n m...\n*)\n\nSearchAbout Bvector.\n(* SearchAbout Vector. *)\n\nLemma empty_vector : forall (v : Bvector 0),\n                       v = [].\nProof.\n  intros v.\n  (* destruct v. *)\n\nAdmitted.\n\nLemma split_append_id : forall (len : nat) (v1 v2 : Bvector len),\n                          splitVector len len (Vector.append v1 v2) = (v1, v2).\nProof.\n  induction len; intros v1 v2.\n  (* Case len = 0 *)\n    (* simpl. rewrite -> empty_vector. *)\n\n\n    Admitted.\n\n(* TODO: 10/25/14\n\n- add lemma for xor **\n   - lennart: B2b (Byte.xor B1 B2) = Vector.map2 xorb (B2b B1) (B2b B2)\n- fill in parameters: sha_h, sha_iv, sha_splitandpad_vector, (fpad) **\n- step through theorem\n  - figure out how to use relations in theorem: compositional? f property? **\n\n- clean up file\n- look at ASCII library\n   - rewrite iterate to emulate their conversion\n- check bytes_bits_vector' fixpoint\n   - look at new definitions, inductive?\n   - see if induction works with it\n\n- figure out how to get split lemmas to work\n- skim Bellare proof and Adam's proof\n- some other paper with a good approach?\n- generalize technique for crypto\n *)\n\n(* Options:\nbytes_bits_vector (inductive, returns prop)\nbytes_bits_vector_comp (returns bool)\nbytes_bits_vector_comp' (returns bool) *)\n\n\nTheorem HMAC_unfold : forall\n                            (k m h : list Z)\n                            (K : Bvector (plus c p)) (M : Blist) (H : Bvector c)\n                            (op ip : byte) (OP IP : Bvector (plus c p)),\n  ((length k) * 8)%nat = (c + p)%nat ->\n  bytes_bits_vector k K ->\n  bytes_bits_lists m M ->\n  bytes_bits_conv_vector' op OP ->\n  bytes_bits_conv_vector' ip IP ->\n  HMAC sha_h sha_iv sha_splitandpad_vector fpad OP IP K M = H ->\n  HMAC_SHA256.HMAC op ip m k = h -> (* m k, not k m *)\n  bytes_bits_vector h H.\nProof.\n  intros k m h K M H op ip OP IP.\n  intros padded_key_len padded_keys_eq msgs_eq ops_eq ips_eq.\n  intros HMAC_abstract HMAC_concrete.\n  unfold p, c in *.\n  simpl in *.\n\n  unfold HMAC in *. simpl in *.\n  rewrite <- HMAC_abstract.\n  unfold HMAC_2K.\n  unfold GHMAC_2K.\n  rewrite -> split_append_id.\n  (* simpl. *)\n\nAbort.\n  \nTheorem HMAC_spec_equiv : forall\n                            (k m h : list Z)\n                            (K : Bvector (plus c p)) (M : Blist) (H : Bvector c)\n                            (op ip : byte) (OP IP : Bvector (plus c p)),\n  ((length k) * 8)%nat = (c + p)%nat ->\n  bytes_bits_vector k K ->\n  bytes_bits_lists m M ->\n  bytes_bits_conv_vector' op OP ->\n  bytes_bits_conv_vector' ip IP ->\n  HMAC sha_h sha_iv sha_splitandpad_vector fpad OP IP K M = H ->\n  HMAC_SHA256.HMAC op ip m k = h -> (* m k, not k m *)\n  bytes_bits_vector h H.\nProof.\n  intros k m h K M H op ip OP IP.\n  intros padded_key_len padded_keys_eq msgs_eq ops_eq ips_eq.\n  intros HMAC_abstract HMAC_concrete.\n  unfold p, c in *.\n  simpl in *.\n\n  unfold HMAC in *. simpl in *.\n  unfold HMAC_SHA256.HMAC in *.\n\n  unfold HMAC_2K in *. unfold GHMAC_2K in *. (* unfold splitVector in *. *)\n  (* Still abstract: sha_h, sha_splitandpad_vector, fpad *)\n  Check sha_h. \n  rewrite -> split_append_id in HMAC_abstract.\n\n  unfold HMAC_SHA256.OUTER in *. unfold HMAC_SHA256.INNER in *.\n    unfold HMAC_SHA256.outerArg in *. unfold HMAC_SHA256.innerArg in *.\n    unfold HMAC_SHA256.mkArgZ in *. unfold HMAC_SHA256.mkArg in *.\n\n    unfold SHA256_.Hash in *. unfold functional_prog.SHA_256' in *.\n    Print SHA256_.Hash.\n    Print functional_prog.SHA_256'.\nPrint functional_prog.generate_and_pad'.    \n    simpl in *.\n    Check hash_words. Print hash_words. Print h_star. Print fold_left.\n    (*  : forall c p : nat,\n       (Bvector c -> Bvector (b c p) -> Bvector c) ->\n       Bvector c -> list (Bvector (b c p)) -> Bvector c  *)\n    Check sha_h.    (*  : Bvector c -> Bvector (c + p) -> Bvector c *)\n\n  unfold BVxor in *. unfold xorb in *. (* unfold Vector.map2 in *. *) \n  unfold Byte.xor in *. unfold Z.lxor in *.\n\n    (* Lemma:\n\nBVxor (b 256 256) K OP = Vector.map2 xorb K OP (can unfold xorb)\n     ~\n                          (map\n                          (fun p0 : byte * byte => Byte.xor (fst p0) (snd p0))\n                          (combine (map Byte.repr (HMAC_SHA256.mkKey k))\n                             (HMAC_SHA256.sixtyfour ip)))\n\nprobably want a meta-lemma for composition of relations\nr1 x X -> r2 y Y -> ?f ? -> f x y ~ F X Y\n\ntry with smaller examples first\n\nfigure out how to approach proof: avoid 4-way induction\n *)\n\n\n  rewrite <- HMAC_abstract.\n  rewrite <- HMAC_concrete.\n\n\n  induction msgs_eq.\n\n\nAbort.\n", "meta": {"author": "k-qy", "repo": "vst-crypto", "sha": "43532fbb3a3fc04f4ace993dddaae462908b75c0", "save_path": "github-repos/coq/k-qy-vst-crypto", "path": "github-repos/coq/k-qy-vst-crypto/vst-crypto-43532fbb3a3fc04f4ace993dddaae462908b75c0/HMAC_spec_harvard.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7006231724777402}}
{"text": "\nSet Implicit Arguments.\n\nRequire Import ZArith.\nRequire Import Div2.\nRequire Import Recdef.\nRequire Import Mat.\nRequire Import Arith.\n\nClass Monoid {A:Type}(dot : A -> A -> A)(one : A) : Type := {\n  dot_assoc : forall x y z:A, dot x (dot y z)= dot (dot x y) z;\n  one_left : forall x, dot one x = x;\n  one_right : forall x, dot x one = x}.\n\n\n\n(*\nPrint Monoid.\n\nRecord Monoid (A : Type) (dot : A -> A -> A) (one : A) : Type := Build_Monoid\n  { dot_assoc : forall x y z : A, dot x (dot y z) = dot (dot x y) z;\n    one_left : forall x : A, dot one x = x;\n    one_right : forall x : A, dot x one = x }\n\nFor Monoid: Argument A is implicit\nFor Build_Monoid: Argument A is implicit\nFor Monoid: Argument scopes are [type_scope _ _]\nFor Build_Monoid: Argument scopes are [type_scope _ _ _ _ _]\n*)\n\n\n\n\nOpen Scope Z_scope.\n\n#[export] Instance ZMult : Monoid  Zmult 1.\nProof. split;intros;ring. Qed.\n\n\n\n(*\nAbout one_right.\n\none_right :\nforall (A : Type) (dot : A -> A -> A) (one : A),\nMonoid dot one -> forall x : A, dot x one = x\n\nArguments A, dot, one, Monoid are implicit and maximally inserted\nArgument scopes are [type_scope _ _ _ _]\none_right is transparent\nExpands to: Constant Top.one_right\n*)\n\nGeneralizable Variables A dot one.\n\nFixpoint power `{M: Monoid A dot one}(a:A)(n:nat) :=\n  match n with 0%nat => one\n             | S p => dot a (power a p)\n  end.\n\nFunction binary_power_mult (A:Type) (dot:A->A->A) (one:A) (M: @Monoid A dot one)\n     (acc x:A)(n:nat){measure (fun i=>i) n} : A \n  (* acc * (x ** n) *) :=\n  match n with 0%nat => acc\n             | _ => if  Even.even_odd_dec n\n                    then binary_power_mult  _   acc (dot x x) (div2 n)\n                    else binary_power_mult   _ (dot acc  x) (dot  x  x) (div2 n)\n  end.\nProof. \n- intros;apply lt_div2; auto with arith.\n- intros; apply lt_div2; auto with arith.\nDefined.\n\n\nDefinition binary_power `{M:Monoid} x n := binary_power_mult M one x n.\n\n(* Example : 2 x 2 Matrices on some ring  *)\n\nSection M2_def.\nVariables (A:Type)\n           (zero one : A) \n           (plus mult minus : A -> A -> A)\n           (sym : A -> A).\n Notation \"0\" := zero.  \n Notation \"1\" := one.\n Notation \"x + y\" := (plus x y).  \n Notation \"x * y \" := (mult x y).\n\n Variable rt : ring_theory  zero one plus mult minus sym (@eq A).\n Add  Ring Aring : rt.\n\n\n#[export] Instance M2_Monoid : Monoid   (M2_mult  plus mult ) (Id2 0 1).\nProof. \n split.\n - destruct x;destruct y;destruct z;simpl.\n   unfold M2_mult;apply M2_eq_intros;simpl;  ring.\n - destruct x;simpl;\n   unfold M2_mult; apply M2_eq_intros; simpl; ring. \n - destruct x;simpl;\n   unfold M2_mult;apply M2_eq_intros;simpl;ring. \nQed.\n\nEnd M2_def.\n\n#[export] Instance M2Z : Monoid  _ _ := M2_Monoid Zth.\n\n(** Tests: \nCompute power (Build_M2  1 1 1 0) 40.\n\n*)\n\n\nDefinition fibonacci (n:nat) :=\n  c00 (power  (Build_M2  1 1 1 0) n).\n\n(* Generic study of power functions *)\n\nSection About_power.\n\n\n Context `(M:Monoid A dot one ).\n\nLtac monoid_rw :=\n    rewrite (@one_left A dot one M) || \n    rewrite (@one_right A dot one M)|| \n    rewrite (@dot_assoc A dot one M).\n\n  Ltac monoid_simpl := repeat monoid_rw.\n\n  Local Infix \"*\" := dot.\n  Local Infix \"**\" := power (at level 30, no associativity).\n\n  Lemma power_x_plus : forall x n p, x ** (n + p) =  x ** n *  x ** p.\n  Proof.\n    induction n as [| p IHp];simpl.\n    -  intros;  monoid_simpl;trivial.\n    - intro q;rewrite (IHp q);  monoid_simpl;trivial. \n  Qed.\n\n Ltac power_simpl := repeat (monoid_rw || rewrite <- power_x_plus).\n\n  Lemma power_commute : forall x n p,  \n               x ** n * x ** p = x ** p * x ** n. \n  Proof.\n   intros x n p;power_simpl; rewrite (plus_comm n p);trivial.\n Qed.\n\n Lemma power_commute_with_x : forall x n ,  \n        x * x ** n = x ** n * x.\n Proof.\n  induction n;simpl;power_simpl;trivial.\n  repeat rewrite <- (@dot_assoc A dot one M); rewrite IHn; trivial.\n Qed.\n\n Lemma power_of_power : forall x n p,  (x ** n) ** p = x ** (p * n).\n Proof.\n   induction p;simpl;[| rewrite power_x_plus; rewrite IHp]; trivial.\nQed.\n\n\nLemma power_S : forall x n, x *  x ** n = x ** S n.\nProof. intros;simpl;auto. Qed.\n\nLemma sqr : forall x, x ** 2 =  x * x.\nProof.\n simpl;intros;monoid_simpl;trivial.\nQed.\n\nLtac factorize := repeat (\n                rewrite <- power_commute_with_x ||\n                rewrite  <- power_x_plus  ||\n                rewrite <- sqr ||\n                rewrite power_S ||\n                rewrite power_of_power).\n\n Lemma power_of_square : forall x n, (x * x) ** n = x ** n * x ** n.\n  induction n;simpl;monoid_simpl;trivial.\n  repeat rewrite dot_assoc;rewrite IHn; repeat rewrite dot_assoc.\n factorize; simpl;trivial.\n Qed.\n\n \nLemma binary_power_mult_ok :\n  forall n a x,  binary_power_mult  M  a x n = a * x ** n.\nProof.\n  intro n; pattern n;apply lt_wf_ind.\n  clear n; intros n Hn;   destruct n.\n   intros;simpl; rewrite binary_power_mult_equation;monoid_simpl;\n    trivial.\n  intros;  \n    rewrite binary_power_mult_equation; destruct (Even.even_odd_dec (S n)).\n  rewrite Hn, power_of_square;  factorize.\n  pattern (S n) at 3;replace (S n) with (div2 (S n) + div2 (S n))%nat;auto.\n  generalize (even_double _ e);simpl;auto. \n  apply lt_div2;auto with arith.\n  rewrite Hn. \n  rewrite power_of_square ; factorize.\n  pattern (S n) at 3;replace (S n) with (S (div2 (S n) + div2 (S n)))%nat;auto.\n  rewrite <- dot_assoc; factorize;auto.\n  generalize (odd_double _ o);intro H;auto.\n  apply lt_div2;auto with arith.\nQed.\n\nLemma binary_power_ok : forall (x:A) (n:nat), binary_power x n = x ** n.\nProof.\n  intros n x;unfold binary_power;rewrite binary_power_mult_ok;\n  monoid_simpl;auto.\nQed.\n\nEnd About_power.\n\n(*\n\nbinary_power_ok :\nforall (A : Type) (dot : A -> A -> A) (one : A) (M : @Monoid A dot one)\n  (x : A) (n : nat),\n@binary_power A dot one (x:A) (n:nat) = @power A dot one M x n\n\nArguments A, dot, one are implicit and maximally inserted\nArgument scopes are [type_scope _ _ _ _ nat_scope]\nbinary_power_ok is opaque\nExpands to: Constant Top.binary_power_ok\n\n*)\n\n\nClass Abelian_Monoid `(M:Monoid ):= {\n  dot_comm : forall x y, dot x  y = dot y  x}.\n(**\n\nPrint Abelian_Monoid.\n\nRecord Abelian_Monoid (A : Type) (dot : A -> A -> A) \n(one : A) (M : Monoid dot one) : Prop := Build_Abelian_Monoid\n  { dot_comm : forall x y : A, dot x y = dot y x }\n\nFor Abelian_Monoid: Arguments A, dot, one are implicit and maximally inserted\nFor Build_Abelian_Monoid: Arguments A, dot, one are implicit\nFor Abelian_Monoid: Argument scopes are [type_scope _ _ _]\nFor Build_Abelian_Monoid: Argument scopes are [type_scope _ _ _ _]\n\n*)\n\n#[export] Instance ZMult_Abelian : Abelian_Monoid ZMult.\nProof. split; exact Zmult_comm. Qed.\n\n\nSection Power_of_dot.\n Context `{M: Monoid A} {AM:Abelian_Monoid M}.\n \nTheorem power_of_mult :\n   forall n x y, \n    power (dot x y)  n =  dot (power x  n) (power y n). \nProof.\n induction n;simpl.\n -  rewrite one_left;auto.\n -  intros; rewrite IHn; repeat rewrite dot_assoc.\n    rewrite <- (dot_assoc  x y (power x n)); rewrite (dot_comm y (power x n)).\n    repeat rewrite dot_assoc;trivial.\nQed.\n\nEnd Power_of_dot.\n\n\n\n", "meta": {"author": "coq-community", "repo": "coq-art", "sha": "b3aaf69bc0c4809e482e931b633fa88ba1646996", "save_path": "github-repos/coq/coq-community-coq-art", "path": "github-repos/coq/coq-community-coq-art/coq-art-b3aaf69bc0c4809e482e931b633fa88ba1646996/tutorial_type_classes/SRC/Monoid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7006231624587539}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import maps.\nRequire Import types.\nRequire Import smallstep.\nRequire Import stlc.\nFrom Coq Require Import Strings.String.\n\nModule STLCExtended.\n\n(*letの導入*)\n(*\n構文:\n       t ::=                項\n           | ...               （前と同じ他の項）\n           | let x=t in t      let束縛\n\n簡約:\n                                 t1 --> t1' \n                     ----------------------------------               (ST_Let1) \n                     let x=t1 in t2 --> let x=t1' in t2 \n \n                        ----------------------------              (ST_LetValue) \n                        let x=v1 in t2 --> [x:=v1]t2 \n型付け:\n             Gamma |- t1 \\in T1      x|->T1; Gamma |- t2 \\in T2 \n             --------------------------------------------------        (T_Let) \n                        Gamma |- let x=t1 in t2 \\in T2 \n *)\n\n(*\n対 射影 直積\n*)\n\n(*\n構文:\n       t ::=                項\n           | ... \n           | (t,t)             対\n           | t.fst             第1射影\n           | t.snd             第2射影\n \n       v ::=                値\n           | ... \n           | (v,v)             対値\n \n       T ::=                型\n           | ... \n           | T * T             直積型\n\n\n簡約：\n                              t1 --> t1' \n                         --------------------                        (ST_Pair1) \n                         (t1,t2) --> (t1',t2) \n \n                              t2 --> t2' \n                         --------------------                        (ST_Pair2) \n                         (v1,t2) --> (v1,t2') \n \n                              t1 --> t1' \n                          ------------------                          (ST_Fst1) \n                          t1.fst --> t1'.fst \n \n                          ------------------                       (ST_FstPair) \n                          (v1,v2).fst --> v1 \n \n                              t1 --> t1' \n                          ------------------                          (ST_Snd1) \n                          t1.snd --> t1'.snd \n\n                           ------------------                       (ST_SndPair) \n                          (v1,v2).snd --> v2 \n\n\n型付け：\n               Gamma |- t1 \\in T1     Gamma |- t2 \\in T2 \n               -----------------------------------------               (T_Pair) \n                       Gamma |- (t1,t2) \\in T1*T2 \n \n                        Gamma |- t \\in T1*T2 \n                        ---------------------                          (T_Fst) \n                        Gamma |- t.fst \\in T1 \n \n                        Gamma |- t \\in T1*T2 \n                        ---------------------                          (T_Snd) \n                        Gamma |- t.snd \\in T2 \n\n *)\n\n(*1要素の型Unit*)\n(*\n構文:\n       t ::=                項\n           | ...               （前と同様）\n           | unit              unit値\n \n       v ::=                値\n           | ... \n           | unit              unit \n \n       T ::=                型\n           | ... \n           | Unit              Unit型\n型付け:\n                         ----------------------                        (T_Unit) \n                         Gamma |- unit \\in Unit \n\n *)\n(*\n Unitが本当に便利なのはよりリッチな言語で副作用(side effects)を持つ場合です。 例えば、変更可能な変数やポインタについての代入文や、例外その他のローカルではないコントロール機構を持つ場合、などです。 そのような言語では、副作用のためだけに評価される式の(どうでもよい)結果のための型が便利なのです。\n *)\n\n(*直和型*)\n(*\n構文:\n       t ::=                項\n           | ...               （前と同様）\n           | inl T t           タグ付け（左）\n           | inr T t           タグ付け（右）\n           | case t of         case \n               inl x => t \n             | inr x => t \n \n       v ::=                値\n           | ... \n           | inl T v           タグ付き値（左）\n           | inr T v           タグ付き値（右）\n \n       T ::=                型\n           | ... \n           | T + T             直和型\n\n簡約:\n                               t1 --> t1' \n                        ------------------------                       (ST_Inl) \n                        inl T2 t1 --> inl T2 t1' \n \n                               t2 --> t2' \n                        ------------------------                       (ST_Inr) \n                        inr T1 t2 --> inr T1 t2' \n \n                               t0 --> t0' \n               -------------------------------------------            (ST_Case) \n                case t0 of inl x1 => t1 | inr x2 => t2 --> \n               case t0' of inl x1 => t1 | inr x2 => t2 \n \n            -----------------------------------------------        (ST_CaseInl) \n            case (inl T2 v1) of inl x1 => t1 | inr x2 => t2 \n                           -->  [x1:=v1]t1 \n \n            -----------------------------------------------        (ST_CaseInr) \n            case (inr T1 v2) of inl x1 => t1 | inr x2 => t2 \n                           -->  [x2:=v1]t2 \n\n型付け:\n                          Gamma |- t1 \\in T1 \n                   ------------------------------                       (T_Inl) \n                   Gamma |- inl T2 t1 \\in T1 + T2 \n \n                          Gamma |- t2 \\in T2 \n                   -------------------------------                      (T_Inr) \n                    Gamma |- inr T1 t2 \\in T1 + T2 \n \n                        Gamma |- t \\in T1+T2 \n                     x1|->T1; Gamma |- t1 \\in T \n                     x2|->T2; Gamma |- t2 \\in T \n         ----------------------------------------------------          (T_Case) \n         Gamma |- case t of inl x1 => t1 | inr x2 => t2 \\in T \n\ninlとinrに型を付記する理由は、関数に対して行ったのと同様、型付け規則を単純にするためです。\n*)\n\n(*リスト*)\n(*\n構文:\n       t ::=                項\n           | ... \n           | nil T \n           | cons t t \n           | lcase t of nil  => t \n                      | x::x => t \n \n       v ::=                値\n           | ... \n           | nil T             nil値\n           | cons v v          cons値\n \n       T ::=                型\n           | ... \n           | List T            Tのリスト\n\n簡約:\n                                t1 --> t1' \n                       --------------------------                    (ST_Cons1) \n                       cons t1 t2 --> cons t1' t2 \n \n                                t2 --> t2' \n                       --------------------------                    (ST_Cons2) \n                       cons v1 t2 --> cons v1 t2' \n \n                              t1 --> t1' \n                -------------------------------------------         (ST_Lcase1) \n                 (lcase t1 of nil => t2 | xh::xt => t3) --> \n                (lcase t1' of nil => t2 | xh::xt => t3) \n \n               -----------------------------------------          (ST_LcaseNil) \n               (lcase nil T of nil => t2 | xh::xt => t3) \n                                --> t2 \n \n            ------------------------------------------------     (ST_LcaseCons) \n            (lcase (cons vh vt) of nil => t2 | xh::xt => t3) \n                          --> [xh:=vh,xt:=vt]t3 \n\n型付け:\n                        -------------------------                       (T_Nil) \n                        Gamma |- nil T \\in List T \n \n             Gamma |- t1 \\in T      Gamma |- t2 \\in List T \n             ---------------------------------------------             (T_Cons) \n                    Gamma |- cons t1 t2 \\in List T \n \n                        Gamma |- t1 \\in List T1 \n                        Gamma |- t2 \\in T \n                (h|->T1; t|->List T1; Gamma) |- t3 \\in T \n          ---------------------------------------------------         (T_Lcase) \n          Gamma |- (lcase t1 of nil => t2 | h::t => t3) \\in T \n\n*)\n\n(*一般再帰*)\n(*\n      fact = \\x:Nat. \n                test x=0 then 1 else x * (fact (pred x))) \nのように書く代わりに、次のように書きます。\n      fact = \n          fix \n            (\\f:Nat->Nat. \n               \\x:Nat. \n                  test x=0 then 1 else x * (f (pred x))) \n*)\n\n(*\n構文:\n       t ::=                項\n           | ... \n           | fix t             不動点演算子\n簡約:\n                                t1 --> t1' \n                            ------------------                        (ST_Fix1) \n                            fix t1 --> fix t1' \n \n               --------------------------------------------         (ST_FixAbs) \n               fix (\\xf:T1.t2) --> [xf:=fix (\\xf:T1.t2)] t2 \n型付け:\n                           Gamma |- t1 \\in T1->T1 \n                           ----------------------                       (T_Fix) \n                           Gamma |- fix t1 \\in T1 \n*)\n\n(*レコード*)\n(*\n構文:\n       t ::=                          項\n           | ... \n           | {i1=t1, ..., in=tn}         レコード\n           | t.i                         射影\n \n       v ::=                          値\n           | ... \n           | {i1=v1, ..., in=vn}         レコード値\n \n       T ::=                          型\n           | ... \n           | {i1:T1, ..., in:Tn}         レコード型\n\n簡約:\n                              ti --> ti' \n                 ------------------------------------                  (ST_Rcd) \n                     {i1=v1, ..., im=vm, in=ti , ...} \n                 --> {i1=v1, ..., im=vm, in=ti', ...} \n \n                              t1 --> t1' \n                            --------------                           (ST_Proj1) \n                            t1.i --> t1'.i \n \n                      -------------------------                    (ST_ProjRcd) \n                      {..., i=vi, ...}.i --> vi \n\n型付け；\n            Gamma |- t1 \\in T1     ...     Gamma |- tn \\in Tn \n          ----------------------------------------------------          (T_Rcd) \n          Gamma |- {i1=t1, ..., in=tn} \\in {i1:T1, ..., in:Tn} \n \n                    Gamma |- t \\in {..., i:Ti, ...} \n                    -------------------------------                    (T_Proj) \n                          Gamma |- t.i \\in Ti \n\n*)\n\n\n(*構文*)\nInductive ty : Type :=\n  | Arrow : ty -> ty -> ty\n  | Nat : ty\n  | Sum : ty -> ty -> ty (*直和*)\n  | List : ty -> ty\n  | Unit : ty\n  | Prod : ty -> ty -> ty (*直積*) .\n\nInductive tm : Type :=\n  (*puree*)\n  | var : string -> tm\n  | app : tm -> tm -> tm\n  | abs : string -> ty -> tm -> tm\n  (*数値*)\n  | const : nat -> tm\n  | scc : tm -> tm\n  | prd : tm -> tm\n  | mlt : tm -> tm -> tm\n  | test0 : tm -> tm -> tm -> tm\n  (*直和*)\n  | tinl : ty -> tm -> tm\n  | tinr : ty -> tm -> tm\n  | tcase : tm -> string -> tm -> string -> tm -> tm\n  (*リスト*)\n  | tnil : ty -> tm\n  | tcons : tm -> tm -> tm\n  | tlcase : tm -> tm -> string -> string -> tm -> tm\n  (*Unit*)\n  | unit : tm\n  (*直積*)\n  | pair : tm -> tm -> tm\n  | fst : tm -> tm\n  | snd : tm -> tm\n  (*let*)\n  | tlet : string -> tm -> tm -> tm\n  (*fix*)\n  | tfix : tm -> tm.\n\n\n(*置換*)\nFixpoint subst (x : string) (s : tm) (t : tm) : tm :=\n  match t with\n\n  | var y =>\n      if eqb_string x y then s else t\n  | abs y T t1 =>\n      abs y T (if eqb_string x y then t1 else (subst x s t1))\n  | app t1 t2 =>\n      app (subst x s t1) (subst x s t2)\n\n  | const n =>\n      const n\n  | scc t1 =>\n      scc (subst x s t1)\n  | prd t1 =>\n      prd (subst x s t1)\n  | mlt t1 t2 =>\n      mlt (subst x s t1) (subst x s t2)\n  | test0 t1 t2 t3 =>\n      test0 (subst x s t1) (subst x s t2) (subst x s t3)\n\n  | tinl T t1 =>\n      tinl T (subst x s t1)\n  | tinr T t1 =>\n      tinr T (subst x s t1)\n  | tcase t0 y1 t1 y2 t2 =>\n      tcase (subst x s t0)\n         y1 (if eqb_string x y1 then t1 else (subst x s t1))\n         y2 (if eqb_string x y2 then t2 else (subst x s t2))\n\n  | tnil T =>\n      tnil T\n  | tcons t1 t2 =>\n      tcons (subst x s t1) (subst x s t2)\n  | tlcase t1 t2 y1 y2 t3 =>\n      tlcase (subst x s t1) (subst x s t2) y1 y2\n        (if eqb_string x y1 then\n           t3\n         else if eqb_string x y2 then t3\n              else (subst x s t3))\n\n  | unit => unit\n\n\n  | _ => t\n  end.\n\nNotation \"'[' x ':=' s ']' t\" := (subst x s t) (at level 20).\n\n\n(*簡約*)\n\nInductive value : tm -> Prop :=\n  (*pure*)\n  | v_abs : forall x T11 t12,\n      value (abs x T11 t12)\n  (*数値*)\n  | v_nat : forall n1,\n      value (const n1)\n  (*直和*)\n  | v_inl : forall v T,\n      value v ->\n      value (tinl T v)\n  | v_inr : forall v T,\n      value v ->\n      value (tinr T v)\n  (*リスト*)\n  | v_lnil : forall T, value (tnil T)\n  | v_lcons : forall v1 vl,\n      value v1 ->\n      value vl ->\n      value (tcons v1 vl)\n  (*unit*)\n  | v_unit : value unit\n  (*直積*)\n  | v_pair : forall v1 v2,\n      value v1 ->\n      value v2 ->\n      value (pair v1 v2).\n\nHint Constructors value.\n\nReserved Notation \"t1 '-->' t2\" (at level 40).\n\nInductive step : tm -> tm -> Prop :=\n  (*pure*)\n  | ST_AppAbs : forall x T11 t12 v2,\n         value v2 ->\n         (app (abs x T11 t12) v2) --> [x:=v2]t12\n  | ST_App1 : forall t1 t1' t2,\n         t1 --> t1' ->\n         (app t1 t2) --> (app t1' t2)\n  | ST_App2 : forall v1 t2 t2',\n         value v1 ->\n         t2 --> t2' ->\n         (app v1 t2) --> (app v1 t2')\n  (*数値*)\n  | ST_Succ1 : forall t1 t1',\n       t1 --> t1' ->\n       (scc t1) --> (scc t1')\n  | ST_SuccNat : forall n1,\n       (scc (const n1)) --> (const (S n1))\n  | ST_Pred : forall t1 t1',\n       t1 --> t1' ->\n       (prd t1) --> (prd t1')\n  | ST_PredNat : forall n1,\n       (prd (const n1)) --> (const (pred n1))\n  | ST_Mult1 : forall t1 t1' t2,\n       t1 --> t1' ->\n       (mlt t1 t2) --> (mlt t1' t2)\n  | ST_Mult2 : forall v1 t2 t2',\n       value v1 ->\n       t2 --> t2' ->\n       (mlt v1 t2) --> (mlt v1 t2')\n  | ST_Mulconsts : forall n1 n2,\n       (mlt (const n1) (const n2)) --> (const (mult n1 n2))\n  | ST_Test01 : forall t1 t1' t2 t3,\n       t1 --> t1' ->\n       (test0 t1 t2 t3) --> (test0 t1' t2 t3)\n  | ST_Test0Zero : forall t2 t3,\n       (test0 (const 0) t2 t3) --> t2\n  | ST_Test0Nonzero : forall n t2 t3,\n       (test0 (const (S n)) t2 t3) --> t3\n  (*直和*)\n  | ST_Inl : forall t1 t1' T,\n        t1 --> t1' ->\n        (tinl T t1) --> (tinl T t1')\n  | ST_Inr : forall t1 t1' T,\n        t1 --> t1' ->\n        (tinr T t1) --> (tinr T t1')\n  | ST_Case : forall t0 t0' x1 t1 x2 t2,\n        t0 --> t0' ->\n        (tcase t0 x1 t1 x2 t2) --> (tcase t0' x1 t1 x2 t2)\n  | ST_CaseInl : forall v0 x1 t1 x2 t2 T,\n        value v0 ->\n        (tcase (tinl T v0) x1 t1 x2 t2) --> [x1:=v0]t1\n  | ST_CaseInr : forall v0 x1 t1 x2 t2 T,\n        value v0 ->\n        (tcase (tinr T v0) x1 t1 x2 t2) --> [x2:=v0]t2\n  (*リスト*)\n  | ST_Cons1 : forall t1 t1' t2,\n       t1 --> t1' ->\n       (tcons t1 t2) --> (tcons t1' t2)\n  | ST_Cons2 : forall v1 t2 t2',\n       value v1 ->\n       t2 --> t2' ->\n       (tcons v1 t2) --> (tcons v1 t2')\n  | ST_Lcase1 : forall t1 t1' t2 x1 x2 t3,\n       t1 --> t1' ->\n       (tlcase t1 t2 x1 x2 t3) --> (tlcase t1' t2 x1 x2 t3)\n  | ST_LcaseNil : forall T t2 x1 x2 t3,\n       (tlcase (tnil T) t2 x1 x2 t3) --> t2\n  | ST_LcaseCons : forall v1 vl t2 x1 x2 t3,\n       value v1 ->\n       value vl ->\n       (tlcase (tcons v1 vl) t2 x1 x2 t3)\n         --> (subst x2 vl (subst x1 v1 t3))\n  (*UnitはStepない*)\n  (*直積*)\n  | ST_Pair1 : forall t1 t1' t2,\n      t1 --> t1' ->\n      pair t1 t2 --> pair t1' t2\n  | ST_Pair2 : forall t1 t2 t2',\n      value t1 ->\n      t2 --> t2' ->\n      pair t1 t2 --> pair t1 t2'\n  | ST_Fst1 : forall t1 t1',\n      t1 --> t1' ->\n      fst t1 --> fst t1'\n  | ST_FstPair : forall v1 v2,\n      value (pair v1 v2) ->\n      fst (pair v1 v2) --> v1\n  | ST_Snd1 : forall t1 t1',\n      t1 --> t1' ->\n      snd t1 --> snd t1'\n  | ST_SndPair : forall v1 v2,\n      value (pair v1 v2) ->\n      snd (pair v1 v2) --> v2\n  (*let*)\n  | ST_Let1 : forall x t1 t1' t2,\n      t1 --> t1' ->\n      tlet x t1 t2 --> tlet x t1' t2\n  | ST_LetValue : forall x v1 t2,\n      value v1 ->\n      tlet x v1 t2 --> [x:= v1]t2\n  (*fix*)\n  | ST_Fix1 : forall t1 t1',\n      t1 --> t1' ->\n      tfix t1 --> tfix t1'\n  | ST_FixAbs : forall x T t,\n      tfix (abs x T t) --> [x:= tfix (abs x T t)]t\nwhere \"t1 '-->' t2\" := (step t1 t2).\n\nNotation multistep := (multi step).\n\nNotation \"t1 '-->*' t2\" := (multistep t1 t2) (at level 40).\n\nHint Constructors step.\n\nDefinition context := partial_map ty.\n\n\nReserved Notation \"Gamma '|-' t '\\in' T\" (at level 40).\n\nInductive has_type : context -> tm -> ty -> Prop :=\n  (*pure*)\n  | T_Var : forall Gamma x T,\n      Gamma x = Some T ->\n      Gamma |- (var x) \\in T\n  | T_Abs : forall Gamma x T11 T12 t12,\n      (update Gamma x T11) |- t12 \\in T12 ->\n      Gamma |- (abs x T11 t12) \\in (Arrow T11 T12)\n  | T_App : forall T1 T2 Gamma t1 t2,\n      Gamma |- t1 \\in (Arrow T1 T2) ->\n      Gamma |- t2 \\in T1 ->\n      Gamma |- (app t1 t2) \\in T2\n  (*数値*)\n  | T_Nat : forall Gamma n1,\n      Gamma |- (const n1) \\in Nat\n  | T_Succ : forall Gamma t1,\n      Gamma |- t1 \\in Nat ->\n      Gamma |- (scc t1) \\in Nat\n  | T_Pred : forall Gamma t1,\n      Gamma |- t1 \\in Nat ->\n      Gamma |- (prd t1) \\in Nat\n  | T_Mult : forall Gamma t1 t2,\n      Gamma |- t1 \\in Nat ->\n      Gamma |- t2 \\in Nat ->\n      Gamma |- (mlt t1 t2) \\in Nat\n  | T_Test0 : forall Gamma t1 t2 t3 T1,\n      Gamma |- t1 \\in Nat ->\n      Gamma |- t2 \\in T1 ->\n      Gamma |- t3 \\in T1 ->\n      Gamma |- (test0 t1 t2 t3) \\in T1\n  (*直和*)\n  | T_Inl : forall Gamma t1 T1 T2,\n      Gamma |- t1 \\in T1 ->\n      Gamma |- (tinl T2 t1) \\in (Sum T1 T2)\n  | T_Inr : forall Gamma t2 T1 T2,\n      Gamma |- t2 \\in T2 ->\n      Gamma |- (tinr T1 t2) \\in (Sum T1 T2)\n  | T_Case : forall Gamma t0 x1 T1 t1 x2 T2 t2 T,\n      Gamma |- t0 \\in (Sum T1 T2) ->\n      (update Gamma x1 T1) |- t1 \\in T ->\n      (update Gamma x2 T2) |- t2 \\in T ->\n      Gamma |- (tcase t0 x1 t1 x2 t2) \\in T\n  (*リスト*)\n  | T_Nil : forall Gamma T,\n      Gamma |- (tnil T) \\in (List T)\n  | T_Cons : forall Gamma t1 t2 T1,\n      Gamma |- t1 \\in T1 ->\n      Gamma |- t2 \\in (List T1) ->\n      Gamma |- (tcons t1 t2) \\in (List T1)\n  | T_Lcase : forall Gamma t1 T1 t2 x1 x2 t3 T2,\n      Gamma |- t1 \\in (List T1) ->\n      Gamma |- t2 \\in T2 ->\n      (update (update Gamma x2 (List T1)) x1 T1) |- t3 \\in T2 ->\n      Gamma |- (tlcase t1 t2 x1 x2 t3) \\in T2\n  (*Unit*)\n  | T_Unit : forall Gamma,\n      Gamma |- unit \\in Unit\n  (*直積*)\n  | T_Pair : forall Gemma t1 t2 T1 T2,\n      Gemma |- t1 \\in T1 ->\n      Gemma |- t2 \\in T2 ->\n      Gemma |- (pair t1 t2) \\in (Prod T1 T2)\n  | T_Fst : forall Gemma t T1 T2,\n      Gemma |- t \\in (Prod T1 T2) ->\n      Gemma |- fst t \\in T1\n  | T_Snd : forall Gemma t T1 T2,\n      Gemma |- t \\in (Prod T1 T2) ->\n      Gemma |- snd t \\in T2\n  (*let*)\n  | T_Let : forall Gemma x t1 t2 T1 T2,\n      Gemma |- t1 \\in T1 ->\n      (update Gemma x T1) |- t2 \\in T2 ->\n      Gemma |- (tlet x t1 t2) \\in T2\n(*fix*)\n  | T_Fix : forall Gemma t1 T1,\n      Gemma |- t1 \\in (Arrow T1 T1) ->\n      Gemma |- (tfix t1) \\in T1\nwhere \"Gamma '|-' t '\\in' T\" := (has_type Gamma t T).\n\nHint Constructors has_type.\n\nDefinition manual_grade_for_extensions_definition : option (nat*string) := None.\n\n\n\nModule Examples.\n\nOpen Scope string_scope.\nNotation x := \"x\".\nNotation y := \"y\".\nNotation a := \"a\".\nNotation f := \"f\".\nNotation g := \"g\".\nNotation l := \"l\".\nNotation k := \"k\".\nNotation i1 := \"i1\".\nNotation i2 := \"i2\".\nNotation processSum := \"processSum\".\nNotation n := \"n\".\nNotation eq := \"eq\".\nNotation m := \"m\".\nNotation evenodd := \"evenodd\".\nNotation even := \"even\".\nNotation odd := \"odd\".\nNotation eo := \"eo\".\n\nModule Numtest.\n\nDefinition test :=\n  test0\n    (prd\n      (scc\n        (prd\n          (mlt\n            (const 2)\n            (const 0)))))\n    (const 5)\n    (const 6).\n\nExample typechecks :\n  empty |- test \\in Nat.\nProof.\n  unfold test.\n  auto 10.\nQed.\n\nExample numtest_reduces :\n  test -->* const 5.\nProof.\n  unfold test. eauto 20. Qed.\n  (* econstructor. constructor. constructor. constructor. constructor. apply ST_Mulconsts. *)\n  (* econstructor. constructor. constructor. constructor. apply ST_PredNat. *)\n  (* econstructor. constructor. constructor. apply ST_SuccNat. *)\n  (* econstructor. constructor. apply ST_PredNat. *)\n  (* econstructor. apply ST_Test0Zero. *)\n  (* constructor. *)\n(* Qed. *)\n\nEnd Numtest.\n\nModule Prodtest.\n\nDefinition test :=\n  snd\n    (fst\n      (pair\n        (pair\n          (const 5)\n          (const 6))\n        (const 7))).\n\nExample typechecks :\n  empty |- test \\in Nat.\nProof. unfold test. eauto 15. Qed.\n\nExample reduces :\n  test -->* const 6.\nProof.\n  unfold test.\n  econstructor. constructor. apply ST_FstPair; constructor; constructor; constructor.\n  econstructor. apply ST_SndPair; constructor; constructor.\n  constructor.\nQed.\n\nEnd Prodtest.\n\n\nModule LetTest.\n\nDefinition test :=\n  tlet\n    x\n    (prd (const 6))\n    (scc (var x)).\n\nExample typechecks :\n  empty |- test \\in Nat.\nProof. unfold test. eauto 15. Qed.\n\nExample reduces :\n  test -->* const 6.\nProof.\n  unfold test. \n  econstructor. constructor. apply ST_PredNat.\n  econstructor. apply ST_LetValue. constructor.\n  econstructor. unfold subst. rewrite <- eqb_string_refl. simpl. apply ST_SuccNat.\n  constructor.\nQed.\n\nEnd LetTest.\n\n\nModule Sumtest1.\n\nDefinition test :=\n  tcase (tinl Nat (const 5))\n    x (var x)\n    y (var y).\n\nExample typechecks :\n  empty |- test \\in Nat.\nProof. unfold test. eauto 15. Qed.\n\nExample reduces :\n  test -->* (const 5).\nProof.\n  unfold test.\n  econstructor. apply ST_CaseInl. constructor.\n  constructor.\nQed.\n\nEnd Sumtest1.\n\nModule Sumtest2.\n\nDefinition test :=\n  tlet\n    processSum\n    (abs x (Sum Nat Nat)\n      (tcase (var x)\n         n (var n)\n         n (test0 (var n) (const 1) (const 0))))\n    (pair\n      (app (var processSum) (tinl Nat (const 5)))\n      (app (var processSum) (tinr Nat (const 5)))).\n\nExample typechecks :\n  empty |- test \\in (Prod Nat Nat).\nProof.\n  unfold test.\n  econstructor. constructor. econstructor; constructor. constructor. constructor. constructor. constructor. constructor. constructor.\n  econstructor. econstructor; constructor. constructor. constructor. econstructor. constructor. constructor.\n  constructor. constructor.\nQed.\n\nExample reduces :\n  test -->* (pair (const 5) (const 0)).\nProof.\n  unfold test.\n  econstructor. apply ST_LetValue. constructor.\n  econstructor. Abort.\n\nEnd Sumtest2.\n\n\nModule ListTest.\n\nDefinition test :=\n  tlet l\n    (tcons (const 5) (tcons (const 6) (tnil Nat)))\n    (tlcase (var l)\n       (const 0)\n       x y (mlt (var x) (var x))).\n\nExample typechecks :\n  empty |- test \\in Nat.\nProof.\n  unfold test.\n  econstructor. constructor. constructor. constructor. constructor. constructor.\n  econstructor. constructor. constructor. constructor. constructor. constructor. constructor. constructor. constructor.\nQed.\n\nExample reduces :\n  test -->* (const 25).\nProof.\n  unfold test.\n  econstructor. apply ST_LetValue. constructor. constructor. constructor. constructor. constructor.\n  econstructor. simpl. apply ST_LcaseCons. constructor. constructor. constructor. constructor.\n  econstructor. simpl. apply ST_Mulconsts.\n  constructor.\nQed.\n\nEnd ListTest.\n\nModule FixTest1.\n\nDefinition fact :=\n  tfix\n    (abs f (Arrow Nat Nat)\n      (abs a Nat\n        (test0\n           (var a)\n           (const 1)\n           (mlt\n              (var a)\n              (app (var f) (prd (var a))))))).\n\nExample typechecks :\n  empty |- fact \\in (Arrow Nat Nat).\nProof.\n  unfold fact.\n  econstructor. constructor. constructor. constructor.\n  constructor. constructor.\n  constructor.\n  constructor.\n  constructor. constructor.\n  econstructor. constructor. constructor. constructor. constructor. constructor.\nQed.\n\nExample reduces :\n  (app fact (const 4)) -->* (const 24).\nProof.\n  unfold fact. normalize. \n  (* econstructor. constructor. apply ST_FixAbs. *)\n  (* simpl. econstructor. constructor. constructor. *)\n  (* econstructor. unfold subst. simpl. apply ST_Test0Nonzero. *)\n  (* econstructor. apply ST_Mult2. constructor. constructor. apply ST_FixAbs. *)\n  (* econstructor. apply ST_Mult2. constructor. simpl. apply ST_App2. constructor. apply ST_PredNat. *)\n  (* econstructor. apply ST_Mult2. constructor. apply ST_AppAbs. constructor. *)\n  (* econstructor. apply ST_Mult2. constructor. simpl. apply ST_Test0Nonzero. *)\n  (* econstructor. apply ST_Mult2. constructor. apply ST_Mult2. constructor. apply ST_App1. apply ST_FixAbs. *)\n  (* econstructor. apply ST_Mult2. constructor. apply ST_Mult2. constructor. apply ST_App2. constructor. apply ST_PredNat. *)\n  (* econstructor. apply ST_Mult2. constructor. simpl. apply ST_Mult2. constructor. apply ST_AppAbs. constructor. *)\n  (* econstructor. apply ST_Mult2. constructor. simpl. apply ST_Mult2. constructor. apply ST_Test0Nonzero. *)\n  (* econstructor. apply ST_Mult2. constructor. simpl. apply ST_Mult2. constructor. apply ST_Mult2. constructor. apply ST_App1. apply ST_FixAbs. *)\n  (* econstructor. apply ST_Mult2. constructor. simpl. apply ST_Mult2. constructor. apply ST_Mult2. constructor. apply ST_App2. constructor. apply ST_PredNat. *)\n  (* econstructor. apply ST_Mult2. constructor. simpl. apply ST_Mult2. constructor. apply ST_Mult2. constructor. apply ST_AppAbs. constructor. *)\n  (* econstructor. apply ST_Mult2. constructor. simpl. apply ST_Mult2. constructor. apply ST_Mult2. constructor. apply ST_Test0Nonzero. *)\n  (*以下略*)\nQed.\n\nEnd FixTest1.\n\n\nModule FixTest2.\n\nDefinition map :=\n  abs g (Arrow Nat Nat)\n    (tfix\n      (abs f (Arrow (List Nat) (List Nat))\n        (abs l (List Nat)\n          (tlcase (var l)\n            (tnil Nat)\n            a l (tcons (app (var g) (var a))\n                         (app (var f) (var l))))))).\n\nExample typechecks :\n  empty |- map \\in\n    (Arrow (Arrow Nat Nat)\n      (Arrow (List Nat)\n        (List Nat))).\nProof.\n  unfold map. \n  econstructor. constructor. constructor. constructor.\n  econstructor. constructor. constructor. constructor. constructor.\n  econstructor. constructor. constructor. constructor. constructor.\n  econstructor. constructor. constructor.\n  constructor. constructor.\nQed.\n\nExample reduces :\n  app (app map (abs a Nat (scc (var a))))\n         (tcons (const 1) (tcons (const 2) (tnil Nat)))\n  -->* (tcons (const 2) (tcons (const 3) (tnil Nat))).\nProof.\n  econstructor. constructor. constructor. constructor.\n  econstructor. constructor. simpl. apply ST_FixAbs.\n  econstructor. simpl. constructor. constructor. constructor. constructor. constructor. constructor.\n  econstructor. simpl. apply ST_LcaseCons. constructor. constructor. constructor. constructor.\n  econstructor. simpl. apply ST_Cons1. constructor. Abort.\n\nEnd FixTest2.\n\nEnd Examples.\n\nTheorem progress : forall t T,\n     empty |- t \\in T ->\n     value t \\/ exists t', t --> t'.\nProof with eauto.\n  intros t T Ht.\n  remember empty as Gamma.\n  generalize dependent HeqGamma.\n  induction Ht; intros HeqGamma; subst.\n  -\n    \n    inversion H.\n  -\n    \n    left...\n  -\n    \n    right.\n    destruct IHHt1; subst...\n    +\n      destruct IHHt2; subst...\n      *\n        \n        inversion H; subst; try solve_by_invert.\n        exists (subst x t2 t12)...\n      *\n        \n        inversion H0 as [t2' Hstp]. exists (app t1 t2')...\n    +\n      \n      inversion H as [t1' Hstp]. exists (app t1' t2)...\n  -\n    left...\n  -\n    right.\n    destruct IHHt...\n    +\n      inversion H; subst; try solve_by_invert.\n      exists (const (S n1))...\n    +\n      inversion H as [t1' Hstp].\n      exists (scc t1')...\n  -\n    right.\n    destruct IHHt...\n    +\n      inversion H; subst; try solve_by_invert.\n      exists (const (pred n1))...\n    +\n      inversion H as [t1' Hstp].\n      exists (prd t1')...\n  -\n    right.\n    destruct IHHt1...\n    +\n      destruct IHHt2...\n      *\n        inversion H; subst; try solve_by_invert.\n        inversion H0; subst; try solve_by_invert.\n        exists (const (mult n1 n0))...\n      *\n        inversion H0 as [t2' Hstp].\n        exists (mlt t1 t2')...\n    +\n      inversion H as [t1' Hstp].\n      exists (mlt t1' t2)...\n  -\n    right.\n    destruct IHHt1...\n    +\n      inversion H; subst; try solve_by_invert.\n      destruct n1 as [|n1'].\n      *\n        exists t2...\n      *\n        exists t3...\n    +\n      inversion H as [t1' H0].\n      exists (test0 t1' t2 t3)...\n  -\n    destruct IHHt...\n    +\n      right. inversion H as [t1' Hstp]...\n  -\n    destruct IHHt...\n    +\n      right. inversion H as [t1' Hstp]...\n  -\n    right.\n    destruct IHHt1...\n    +\n      inversion H; subst; try solve_by_invert.\n      *\n        exists ([x1:=v]t1)...\n      *\n        exists ([x2:=v]t2)...\n    +\n      inversion H as [t0' Hstp].\n      exists (tcase t0' x1 t1 x2 t2)...\n  -\n    left...\n  -\n    destruct IHHt1...\n    +\n      destruct IHHt2...\n      *\n        right. inversion H0 as [t2' Hstp].\n        exists (tcons t1 t2')...\n    +\n      right. inversion H as [t1' Hstp].\n      exists (tcons t1' t2)...\n  -\n    right.\n    destruct IHHt1...\n    +\n      inversion H; subst; try solve_by_invert.\n      *\n        exists t2...\n      *\n        exists ([x2:=vl]([x1:=v1]t3))...\n    +\n      inversion H as [t1' Hstp].\n      exists (tlcase t1' t2 x1 x2 t3)...\n  -\n    left...\n  -\n    destruct IHHt1... destruct IHHt2...\n    inversion H0. right. exists (pair t1 x). constructor; assumption.\n    inversion H. right. exists (pair x t2). constructor; assumption.\n  -\n    right. destruct IHHt...\n    inversion H; subst; inversion Ht; subst. exists v1. constructor; assumption.\n    inversion H. exists (fst x). constructor; assumption.\n  -\n    right. destruct IHHt...\n    inversion H; subst; inversion Ht; subst. exists v2. constructor; assumption.\n    inversion H. exists (snd x). constructor; assumption.\n  -\n    destruct IHHt1... inversion H. right. exists (tlet x x0 t2). constructor; assumption.\n  -\n    right. destruct IHHt...\n    inversion H; subst; inversion Ht; subst. exists ([x:= tfix (abs x T1 t12)]t12). apply ST_FixAbs.\n    inversion H. exists (tfix x). constructor. assumption.\nQed.\n\nDefinition manual_grade_for_progress : option (nat*string) := None.\n\nEnd STLCExtended.\n", "meta": {"author": "NeM-T", "repo": "sfc", "sha": "e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e", "save_path": "github-repos/coq/NeM-T-sfc", "path": "github-repos/coq/NeM-T-sfc/sfc-e52eb817e2e9afbd7d731020e1f5f146ac8ffd4e/practice/Coq/SF/2nd/morestlc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.700623159368664}}
{"text": "(******************************************************************************)\n(* Binary trees and their forests                                             *)\n(*             bintree := a binary tree                                       *)\n(*              forest := a sequence of trees                                 *)\n(*        count_node t := the number of nodes on a tree t                     *)\n(* count_node_forest f := the number of nodes on a forest f                   *)\n(*          subtrees t := trees just below the root of a tree t               *)\n(*         subforest f := subtrees of trees in a forest f                     *)\n(*                                                                            *)\n(* Specifications of leaves:                                                  *)\n(*             leave_spec := a sequence specifying the number of leaves at    *)\n(*                           each level in a forest                           *)\n(* satisfy_leave_spec f s := check whether a forest f satisfies a spec s      *)\n(*                           (for a tree t, use satisfy_leave_spec [:: t] s)  *)\n(*                                                                            *)\n(* Forest lifts:                                                              *)\n(*    simple_lift f : adds one node on to the top of each tree in a forest f  *)\n(* pairing_lift p f : divides trees in a forest f into p pairs and other      *)\n(*                    individuals, and adds one node on to the top of each    *)\n(*                    group                                                   *)\n(*                                                                            *)\n(* Bounds:                                                                    *)\n(*     lower_bound_bottomup s, : a tight bound of the size of forests that    *)\n(*     upper_bound_bottomup s    satisfy a spec s; see in_bottomup_boundP     *)\n(* lower_bounds_backforth s n, : tight bounds of the number of nodes at all   *)\n(* upper_bounds_backforth s n    levels of forests consisting n trees and     *)\n(*                               satisfying a spec s                          *)\n(*      lower_bound_total s n, : a tight bound of the total numbers of nodes  *)\n(*      upper_bound_total s n    in forests consisting n trees and satisfying *)\n(*                               a spec s; see in_total_boundP                *)\n(*                                                                            *)\n(* Efficiently computed bounds:                                               *)\n(*    lower_bounds_topdown s n, : bounds of the number of nodes at all levels *)\n(*    upper_bounds_topdown s n    of forests consisting n trees and           *)\n(*                                satisfying a spec s; they may not be tight  *)\n(* lower_bounds_backforth' s n, : the same as lower/upper_bound_backforth     *)\n(* upper_bounds_backforth' s n                                                *)\n(*      lower_bound_total' s n, : the same as lower/upper_bound_total; the    *)\n(*      upper_bound_total' s n    time complexity is Θ(|s|) (|s| is the size  *)\n(*                                of s)                                       *)\n(******************************************************************************)\n\nFrom mathcomp Require Import all_ssreflect.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nFrom Coq Require Import Lia.\nFrom mathcomp.zify Require Import zify.\n\nSection SsrnatExt.\nLemma leq_div2 n : n./2 <= n.\nProof. by rewrite -divn2 leq_div. Qed.\n\nLemma leq_uphalf n : uphalf n <= n.\nProof.\n  rewrite [in X in _ <= X](divn_eq n 2) addnC uphalf_half -modn2 -divn2.\n  by apply: leq_add => //; apply: leq_pmulr.\nQed.\n\nLemma homo_maxl n :\n  {homo maxn n : m l / m <= l}.\nProof.\n  move=> m l leq_ml.\n  by rewrite geq_max leq_maxl leq_max leq_ml orbT.\nQed.\n\nLemma homo_minl n :\n  {homo minn n : m l / m <= l}.\nProof.\n  move=> m l leq_ml.\n  by rewrite leq_min geq_minl geq_min leq_ml orbT.\nQed.\nEnd SsrnatExt.\n\nSection SeqExt.\nLemma flatten_nseq_nil (T : Type) (n : nat) :\n  @flatten T (nseq n [::]) = [::].\nProof. by elim: n. Qed.\n\nSection Map.\n  Variable A B C : Type.\n\n  Definition map2 (f : A -> B -> C) :=\n    fix map2 (s1 : seq A) (s2 : seq B) :=\n      match s1, s2 with\n        x :: s1', y :: s2' => f x y :: map2 s1' s2'\n      | _, _ => [::]\n      end.\nEnd Map.\n\nSection Scan.\nVariable T S : Type.\nVariable f : T -> S -> S.\nVariable y0 : S.\n\nFixpoint scanr_aux (s : seq T) : {r : seq S | size r > 0} :=\n  match s with\n    [::] => exist _ [:: y0] erefl\n  | x :: s' =>\n      match scanr_aux s' with\n        exist r Hr =>\n          (match r return size r > 0 -> {r : seq S | size r > 0} with\n             [::] => fun cont => match notF cont with end\n           | y :: _ => fun Hr => exist _ (f x y :: r) erefl\n           end) Hr\n      end\n  end.\n\nLemma scanr_auxE (x : T) (s' : seq T) :\n  scanr_aux (x :: s') =\n    match scanr_aux s' with\n      exist r Hr =>\n        (match r return size r > 0 -> {r : seq S | size r > 0} with\n           [::] => fun cont => match notF cont with end\n         | y :: _ => fun Hr => exist _ (f x y :: r) erefl\n         end) Hr\n    end.\nProof. by []. Qed.\n\nDefinition scanr (s : seq T) := proj1_sig (scanr_aux s).\n\nLemma scanrE (x : T) (s : seq T) :\n  scanr (x :: s) = foldr f y0 (x :: s) :: scanr s.\nProof.\n  rewrite /scanr.\n  elim: s => // x' s' IH in x *.\n  rewrite scanr_auxE.\n  case: (scanr_aux (x' :: s')) (IH x') => /= r Hr Er.\n  rewrite Er /= in Hr *.\n  by congr (_ :: _).\nQed.\nEnd Scan.\nEnd SeqExt.\n\nSection BinaryTree.\nInductive bintree := L | B1 of bintree | B2 of bintree & bintree.\nDefinition forest := seq bintree.\n\nFixpoint bintree_eq (t1 t2 : bintree) :=  \n  match t1, t2 with\n  | L, L => true\n  | B1 t1', B1 t2' => bintree_eq t1' t2'\n  | B2 t11 t12, B2 t21 t22 => bintree_eq t11 t21 && bintree_eq t12 t22\n  | _, _ => false\n  end.\n\nLemma bintree_eqP : Equality.axiom bintree_eq.\nProof.\nmove=> t1 t2; apply/(iffP idP).\n- elim: t1 t2 => [| t1' IH | t11 IH1 t12 IH2].\n  + by case.\n  + by case => //= t2' E; congr B1; apply: IH.\n  + by case => //= t21 t22 /andP [E1 E2]; congr B2; [ apply: IH1 | apply: IH2 ].\n- by move<-; elim: t1 => //= t11 IH1 t12 IH2; rewrite IH1 IH2.\nQed.\n\nCanonical bintree_eqMixin := EqMixin bintree_eqP.\nCanonical bintree_eqType := Eval hnf in EqType bintree bintree_eqMixin.\n\nFixpoint count_node (t : bintree) :=\n  match t with\n    L => 1\n  | B1 t1 => (count_node t1).+1\n  | B2 t1 t2 => (count_node t1 + count_node t2).+1\n  end.\n\nDefinition count_node_forest (f : forest) :=\n  sumn (map count_node f).\n\nLemma count_node_forest_cat (f1 f2 : forest) :\n  count_node_forest (f1 ++ f2) = count_node_forest f1 + count_node_forest f2.\nProof. by rewrite /count_node_forest map_cat sumn_cat. Qed.\n\nLemma count_node_forest_nseq n t :\n  count_node_forest (nseq n t) = (count_node t) * n.\nProof. by rewrite /count_node_forest map_nseq sumn_nseq. Qed.\n\nDefinition subtrees (t : bintree) : forest :=\n  match t with\n    L => [::]\n  | B1 t => [:: t]\n  | B2 t1 t2 => [:: t1; t2]\n  end.\n\nDefinition subforest (f : forest) : forest :=\n  flatten (map subtrees f).\n\nLemma subforest_cat f1 f2 :\n  subforest (f1 ++ f2) = subforest f1 ++ subforest f2.\nProof. by rewrite /subforest map_cat flatten_cat. Qed.\n\nLemma subforest_nseq n t :\n  subforest (nseq n t) = flatten (nseq n (subtrees t)).\nProof. by rewrite /subforest map_nseq. Qed.\n\nLemma eq_count_node t :\n  count_node t = (count_node_forest (subtrees t)).+1.\nProof.\n  rewrite /count_node_forest.\n  by case: t => //= [t1 | t1 t2]; rewrite addn0.\nQed.\n\nLemma eq_count_node_forest f :\n  count_node_forest f = size f + count_node_forest (subforest f).\nProof.\n  rewrite /count_node_forest /subforest.\n  elim: f => //= t0 f' IH.\n  rewrite map_cat sumn_cat.\n  rewrite -addn1 addn.[AC (2*2) ((3*2)*(1*4))] addn1.\n  congr (_ + _) => //.\n  by apply: eq_count_node.\nQed.\nEnd BinaryTree.\n\nSection LeaveSpec.\nDefinition leave_spec := seq nat.\n\nFixpoint satisfy_leave_spec (f : forest) (s : leave_spec) :=\n  match s with\n    [::] => f == [::]\n  | l0 :: s' =>\n      let f' := subforest f in\n      (count_mem L f == l0) && satisfy_leave_spec f' s'\n  end.\nEnd LeaveSpec.\n\nDefinition lower_bound_bottomup (s : leave_spec) :=\n  foldr (fun l0 lb => l0 + uphalf lb) 0 s.\n\nDefinition upper_bound_bottomup (s : leave_spec) :=\n  foldr (fun l0 ub => l0 + ub) 0 s.\n\nLemma leq_bottomup_bound (s : leave_spec) :\n  lower_bound_bottomup s <= upper_bound_bottomup s.\nProof.\n  elim: s => //= l0 s' IH.\n  by rewrite leq_add2l (leq_trans _ IH) ?leq_uphalf.\nQed.\n\nSection ForestLift.\nDefinition simple_lift (f : forest) := map B1 f.\n\nFixpoint pairing_lift (p : nat) (f : forest) :=\n  match p, f with\n    p'.+1, t0 :: t1 :: f' => B2 t0 t1 :: pairing_lift p' f'\n  | _, _ => simple_lift f\n  end.\n\nLemma subforest_simple_lift f :\n  subforest (simple_lift f) = f.\nProof.\n  rewrite /subforest.\n  elim: f => //= t0 f' IH.\n  by congr (_ :: _).\nQed.\n\nLemma subforest_pairing_lift p f :\n  subforest (pairing_lift p f) = f.\nProof.\n  rewrite /subforest.\n  elim: p f => [| p' IH]; first by apply: subforest_simple_lift.\n  case => [| t0 [| t1 f']] //=.\n  by congr (_ :: _ :: _).\nQed.\n\nLemma size_simple_lift f :\n  size (simple_lift f) = size f.\nProof. by rewrite size_map. Qed.\n\nLemma size_pairing_lift p f :\n  p <= half (size f) ->\n  size (pairing_lift p f) = size f - p.\nProof.\n  elim: p => [| p' IH] in f *.\n  - by rewrite subn0 size_simple_lift.\n  - case: f => [| t0 [| t1 f']] //= /[!ltnS] ltn_p'.\n    rewrite subSS subSn; last first.\n    + by apply/(leq_trans ltn_p')/leq_div2.\n    + by congr _.+1; apply: IH.\nQed.\n\nLemma count_mem_L_simple_lift f :\n  count_mem L (simple_lift f) = 0.\nProof. by rewrite count_map count_pred0. Qed.\n\nLemma count_mem_L_pairing_lift p f :\n  count_mem L (pairing_lift p f) = 0.\nProof.\n  elim: p => [| p' IH] in f *; first by rewrite count_mem_L_simple_lift.\n  case: f => [| t0 [| t1 f']] //=.\n  by rewrite add0n.\nQed.\n\nLemma count_node_forest_pairing_lift p f :\n  p <= half (size f) ->\n  count_node_forest (pairing_lift p f) = count_node_forest f + (size f - p).\nProof.\n  move=> ltn_p.\n  rewrite eq_count_node_forest.\n  by rewrite size_pairing_lift // subforest_pairing_lift addnC.\nQed.\nEnd ForestLift.\n\nLemma in_size_forest f :\n  count_mem L f + uphalf (size (subforest f)) <= size f <= count_mem L f + size (subforest f).\nProof.\n  rewrite /subforest.\n  elim: f => // t0 f' IH.\n  case: t0 => [| t0' | t01 t02] /=.\n  - by rewrite add1n !addSn ltnS.\n  - case/andP: IH => IHlb IHub.\n    rewrite add0n !addnS !ltnS; apply/andP; split => //.\n    by rewrite (leq_trans _ IHlb) ?leq_add2l ?uphalf_half ?leq_addl.\n  - case/andP: IH => IHlb IHub.\n    rewrite add0n !addnS !ltnS; apply/andP; split => //.\n    by rewrite (leq_trans IHub).\nQed.\n\nProposition in_bottomup_boundP (n : nat) (s : leave_spec) :\n  reflect (exists2 f, size f = n & satisfy_leave_spec f s) (lower_bound_bottomup s <= n <= upper_bound_bottomup s).\nProof.\n  apply: (iffP idP).\n  - elim: s => [| l0 s' IH] /= in n *.\n    + by rewrite leqn0 => /eqP ->; exists [::].\n    + move=> ineq_n.\n      set lbb' := lower_bound_bottomup s'.\n      set ubb' := upper_bound_bottomup s'.\n      set i0 := n - l0.\n      case: (leqP lbb' i0).\n      * move=> le_lbb'_i0.\n        have ineq_i0 : lbb' <= i0 <= ubb' by lia.\n        case: (IH _ ineq_i0) => f' eq_size_f' sat_f'.\n        exists (simple_lift f' ++ nseq l0 L).\n        -- by rewrite size_cat size_simple_lift eq_size_f' size_nseq; lia.\n        -- apply/andP; split.\n           ++ by rewrite count_cat count_mem_L_simple_lift count_nseq mul1n.\n           ++ rewrite subforest_cat subforest_simple_lift.\n              by rewrite subforest_nseq flatten_nseq_nil cats0.\n      * move=> lt_i0_lbb'.\n        have ? := leq_bottomup_bound s'.\n        have ineq_lbb' : lbb' <= lbb' <= ubb' by lia.\n        case: (IH _ ineq_lbb') => f' eq_size_f' sat_f'.\n        exists (pairing_lift (lbb' - i0) f' ++ nseq l0 L).\n        -- by rewrite size_cat size_pairing_lift ?eq_size_f' ?size_nseq; lia.\n        -- apply/andP; split. \n           ++ by rewrite count_cat count_mem_L_pairing_lift count_nseq mul1n.\n           ++ rewrite subforest_cat subforest_pairing_lift.\n              by rewrite subforest_nseq flatten_nseq_nil cats0.\n  - elim: s => [| l0 s' IH] in n *.\n    + by case; case; case: n. (* :) *)\n    + set lbb' := lower_bound_bottomup s'.\n      set ubb' := upper_bound_bottomup s'.\n      case => f Esize /= /andP [/eqP EcountL sat].\n      have /[!Esize] /[!EcountL] := in_size_forest f.\n      have : lbb' <= size (subforest f) <= ubb'.\n      { by apply: IH; exists (subforest f). }\n      by lia.\nQed.\n\nFixpoint lower_bounds_backforth (s : leave_spec) (n : nat) :=\n  match s with\n    [::] => [::]\n  | l0 :: s' =>\n      n :: lower_bounds_backforth s' (maxn (lower_bound_bottomup s') (n - l0))\n  end.\n\nFixpoint upper_bounds_backforth (s : leave_spec) (n : nat) :=\n  match s with\n    [::] => [::]\n  | l0 :: s' =>\n      n :: upper_bounds_backforth s' (minn (upper_bound_bottomup s') (n - l0).*2)\n  end.\n\nDefinition lower_bound_total s n :=\n  sumn (lower_bounds_backforth s n).\n\nDefinition upper_bound_total s n :=\n  sumn (upper_bounds_backforth s n).\n\nLemma homo_lower_bound_total s :\n  {homo lower_bound_total s : n m / n <= m}.\nProof.\n  rewrite /lower_bound_total.\n  elim: s => //= l0 s' IH n m leq_nm.\n  by apply/leq_add => //; apply/IH/homo_maxl/leq_sub2r.\nQed.\n\nLemma homo_upper_bound_total s :\n  {homo (upper_bound_total s) : n m / n <= m}.\nProof.\n  rewrite /upper_bound_total.\n  elim: s => //= l0 s' IH n m leq_nm.\n  apply/leq_add => //; apply/IH.\n  by rewrite homo_minl ?leq_double ?leq_sub2r.\nQed.\n\nLemma leq_total_bound s n m :\n  [&& lower_bound_bottomup s <= n, n <= m & m <= upper_bound_bottomup s] ->\n  lower_bound_total s n <= upper_bound_total s m.\nProof.\n  rewrite /lower_bound_total /upper_bound_total.\n  elim: s => //= l0 s' IH in n m *.\n  move=> ineq_nm.\n  apply: leq_add; first by lia.\n  by apply: IH; move: (leq_bottomup_bound s'); lia.\nQed.\n\nLemma consecutive_total_bounds_touch_each_other s n :\n  lower_bound_bottomup s <= n ->\n  n.+1 <= upper_bound_bottomup s ->\n  lower_bound_total s n <= lower_bound_total s n.+1 <= (upper_bound_total s n).+1.\nProof.\n  rewrite /lower_bound_total /upper_bound_total.\n  case: s => //= l0 s' in n *.\n  move=> geq_n leq_n1.\n  apply/andP; split.\n  - rewrite ltnW // addSn ltnS leq_add2l homo_lower_bound_total //.\n    by lia.\n  - rewrite addSn ltnS leq_add2l.\n    apply: leq_total_bound.\n    apply/and3P; split; [ apply: leq_maxl | | apply: geq_minl ].\n    have := leq_bottomup_bound s'.\n    suff : 1 <= n - l0 by lia.\n    rewrite ltnNge.\n    apply/negP => leq_nl0.\n    have : upper_bound_bottomup s' > 0 by lia.\n    apply/negP.\n    rewrite -leqNgt leqn0.\n    have : lower_bound_bottomup s' == 0 by lia.\n    elim: s' {l0 n geq_n leq_n1 leq_nl0} => //= l1 s'' IH.\n    by lia.\nQed.\n\nLemma interval_chain_forms_closed_interval (f g : nat -> nat) (a b n : nat) :\n  a <= b ->\n  (forall x, a <= x <= b -> f x <= g x) ->\n  (forall x, a <= x -> x.+1 <= b -> f x <= f x.+1 <= (g x).+1) ->\n  f a <= n <= g b ->\n  exists2 m, a <= m <= b & f m <= n <= g m.\nProof.\n  move/leP.\n  elim: b / => [| b /leP leq_ab IH] leq_fg touching ineq_n.\n  - by exists a; rewrite ?leqnn.\n  - case: (leqP n (g b)) => [le_n_gb | lt_gb_n].\n    + case: IH.\n      * by move=> ??; apply: leq_fg; lia.\n      * by move=> ???; apply: touching; lia.\n      * by lia.\n      * move=> m ineq_m ineq_fgm.\n        exists m => //.\n        by lia.\n    + have ? := touching b leq_ab (leqnn _).\n      by exists b.+1; lia.\nQed.\n\nLemma total_bound_chain_forms_closed_interval m s lb ub :\n  [&& lower_bound_bottomup s <= lb, lb <= ub & ub <= upper_bound_bottomup s] ->\n  lower_bound_total s lb <= m <= upper_bound_total s ub ->\n  exists2 n, lb <= n <= ub & lower_bound_total s n <= m <= upper_bound_total s n.\nProof.\n  move=> ineq_bound ineq_m.\n  case: (@interval_chain_forms_closed_interval (lower_bound_total s) (upper_bound_total s) lb ub m) => //.\n  - by lia.\n  - by move=> ??; apply: leq_total_bound; lia.\n  - by move=> ???; apply: consecutive_total_bounds_touch_each_other; lia.\n  - by move=> n ??; exists n.\nQed.\n\nProposition in_total_boundP (n m : nat) (s : leave_spec) :\n  lower_bound_bottomup s <= n <= upper_bound_bottomup s ->\n  reflect (exists f, [/\\ count_node_forest f = m, size f = n & satisfy_leave_spec f s]) (lower_bound_total s n <= m <= upper_bound_total s n).\nProof.\n  rewrite /lower_bound_total /upper_bound_total.\n  move=> ineq_n.\n  apply: (iffP idP).\n  - elim: s => [| l0 s' IH] /= in m n ineq_n *.\n    + move: ineq_n; rewrite !leqn0; do 2!move/eqP->.\n      by exists [::].\n    + move=> ineq_m.\n      set lb := maxn _ _ in ineq_m.\n      set ub := minn _ _ in ineq_m.\n      case: (@total_bound_chain_forms_closed_interval (m - n) s' lb ub).\n      * by move: (leq_bottomup_bound s'); lia.\n      * by rewrite /lower_bound_total /upper_bound_total; lia.\n      * move=> n' ineq_n' ineq_m'.\n        case: (IH (m - n) n').\n        -- by lia.\n        -- by rewrite /lower_bound_total /upper_bound_total in ineq_m'; lia.\n        -- move=> f' [Ecount Esize sat].\n           exists (pairing_lift (n' - (n - l0)) f' ++ nseq l0 L); split.\n           ++ by rewrite count_node_forest_cat count_node_forest_pairing_lift ?Ecount ?Esize ?count_node_forest_nseq /=; lia.\n           ++ by rewrite size_cat size_pairing_lift Esize ?size_nseq; lia.\n           ++ apply/andP; split.\n              ** by rewrite count_cat count_mem_L_pairing_lift count_nseq mul1n.\n              ** rewrite subforest_cat subforest_pairing_lift.\n                 by rewrite subforest_nseq flatten_nseq_nil cats0.\n  - elim: s => [| l0 s' IH] /= in m n ineq_n *.\n    + case => f [Ecount _ /eqP Ef].\n      rewrite Ef in Ecount.\n      by rewrite -Ecount.\n    + case => f [Ecount Esize /andP [/eqP EcountL sat]].\n      set f' := subforest f.\n      have ineq_size_f' : lower_bound_bottomup s' <= size f' <= upper_bound_bottomup s'.\n      { by apply/in_bottomup_boundP; exists f' => //. }\n      have ex_f' : exists f, [/\\ count_node_forest f = m - n, size f = size f' & satisfy_leave_spec f s'].\n      { \n        exists f'; split => //.\n        by rewrite -Ecount (eq_count_node_forest f) Esize addKn.\n      }\n      have {ex_f'} := IH _ _ ineq_size_f' ex_f'.\n      set lb := maxn _ _.\n      set ub := minn _ _. \n      have ineq_n' := in_size_forest f.\n      rewrite EcountL Esize -/f' in ineq_n'.\n      have : lower_bound_total s' lb <= lower_bound_total s' (size f').\n      { by apply: homo_lower_bound_total; lia. }\n      have : upper_bound_total s' (size f') <= upper_bound_total s' ub.\n      { by apply: homo_upper_bound_total; lia. }\n      have : n <= m.\n      { by rewrite -Esize -Ecount eq_count_node_forest leq_addr. }\n      rewrite /lower_bound_total /upper_bound_total.\n      by lia.\nQed.\n\nDefinition lower_bounds_topdown (s : leave_spec) (n : nat) :=\n  belast n (scanl subn n s).\n\nDefinition upper_bounds_topdown (s : leave_spec) (n : nat) :=\n  belast n (scanl (fun ub l0 => (ub - l0).*2) n s).\n\nDefinition lower_bounds_bottomup s :=\n  scanr (fun l0 lb : nat => l0 + uphalf lb) 0 s.\n\nDefinition upper_bounds_bottomup s :=\n  scanr (fun l0 ub : nat => l0 + ub) 0 s.\n\nDefinition lower_bounds_backforth' s n :=\n  map2 maxn (lower_bounds_bottomup s) (lower_bounds_topdown s n).\n\nDefinition upper_bounds_backforth' s n :=\n  map2 minn (upper_bounds_bottomup s) (upper_bounds_topdown s n).\n\nLemma lower_bounds_backforth'E l0 s n :\n  lower_bounds_backforth' (l0 :: s) n =\n    maxn (lower_bound_bottomup (l0 :: s)) n :: lower_bounds_backforth' s (n - l0).\nProof. by rewrite /lower_bounds_backforth' /lower_bounds_bottomup scanrE. Qed.\n\nLemma upper_bounds_backforth'E l0 s n :\n  upper_bounds_backforth' (l0 :: s) n =\n    minn (upper_bound_bottomup (l0 :: s)) n :: upper_bounds_backforth' s (n - l0).*2.\nProof. by rewrite /upper_bounds_backforth' /upper_bounds_bottomup scanrE. Qed.\n\nDefinition lower_bound_total' s n :=\n  sumn (lower_bounds_backforth' s n).\n\nDefinition upper_bound_total' s n :=\n  sumn (upper_bounds_backforth' s n).\n\nLemma lower_bound_lower_bounds_backforth' s n :\n  n <= lower_bound_bottomup s ->\n  lower_bounds_backforth' s n = lower_bounds_backforth' s (lower_bound_bottomup s).\nProof.\n  elim: s => //= l0 s' IH in n *.\n  move=> leq_n.\n  rewrite !lower_bounds_backforth'E /=.\n  congr (_ :: _).\n  - by rewrite maxnn; apply/maxn_idPl.\n  - rewrite addKn !IH //.\n    + by apply: leq_uphalf.\n    + by lia.\nQed.\n\nLemma upper_bound_upper_bounds_backforth' s n :\n  upper_bound_bottomup s <= n ->\n  upper_bounds_backforth' s n = upper_bounds_backforth' s (upper_bound_bottomup s).\nProof.\n  elim: s => //= l0 s' IH in n *.\n  move=> leq_n.\n  rewrite !upper_bounds_backforth'E /=.\n  congr (_ :: _).\n  - by rewrite minnn; apply/minn_idPl.\n  - rewrite addKn !IH //.\n    + by rewrite -mul2n leq_pmull.\n    + by lia.\nQed.\n\nLemma lower_bounds_backforth_equiv s n :\n  lower_bound_bottomup s <= n ->\n  lower_bounds_backforth' s n = lower_bounds_backforth s n.\nProof.\n  elim: s => //= l0 s' IH in n *.\n  move=> geq_n.\n  rewrite lower_bounds_backforth'E /=.\n  congr (_ :: _).\n  - by apply/maxn_idPr.\n  - set lbb' := lower_bound_bottomup s'.\n    case: (ltnP lbb' (n - l0)).\n    + by move=> ?; apply/IH/ltnW.\n    + by move=> le_nl0_lbb'; rewrite lower_bound_lower_bounds_backforth' // IH.\nQed.\n\nLemma upper_bounds_backforth_equiv s n :\n  n <= upper_bound_bottomup s ->\n  upper_bounds_backforth' s n = upper_bounds_backforth s n.\nProof.\n  rewrite /upper_bound_total /upper_bound_total'.\n  elim: s => //= l0 s' IH in n *.\n  move=> leq_n.\n  rewrite upper_bounds_backforth'E /=.\n  congr (_ :: _).\n  - by apply/minn_idPr.\n  - set ubb' := upper_bound_bottomup s'.\n    case: (ltnP (n - l0).*2 ubb').\n    + by move=> ?; apply/IH/ltnW.\n    + by move=> le_ubb'_nl02; rewrite upper_bound_upper_bounds_backforth' // IH.\nQed.\n\nLemma lower_bound_total_equiv s n :\n  lower_bound_bottomup s <= n ->\n  lower_bound_total' s n = lower_bound_total s n.\nProof. by move=> ?; rewrite /lower_bound_total' lower_bounds_backforth_equiv. Qed.\n\nLemma upper_bound_total_equiv s n :\n  n <= upper_bound_bottomup s ->\n  upper_bound_total' s n = upper_bound_total s n.\nProof. by move=> ?; rewrite /upper_bound_total' upper_bounds_backforth_equiv. Qed.\n\nRequire Extraction.\nExtract Inductive list => \"list\" [ \"[]\" \"( :: )\" ].\nExtract Inductive nat => \"int\" [ \"0\" \"succ\" ] \"(fun fO fS n -> if n = 0 then fO () else fS (n - 1))\".\nExtract Inlined Constant addn => \"( + )\".\nExtract Inlined Constant subn => \"( - )\".\nExtract Inlined Constant maxn => \"max\".\nExtract Inlined Constant minn => \"min\".\nExtract Inlined Constant double => \"(fun n -> n * 2)\".\nExtract Inlined Constant half => \"(fun n -> n / 2)\".\nExtract Inlined Constant uphalf => \"(fun n -> (n + 1) / 2)\".\nExtraction Inline scanr_aux.\n\nExtraction \"folia\" lower_bound_bottomup upper_bound_total'.\n", "meta": {"author": "samosica", "repo": "folia-formalization", "sha": "e17942a1d6b7ac4e7a726266e2b697de2e029862", "save_path": "github-repos/coq/samosica-folia-formalization", "path": "github-repos/coq/samosica-folia-formalization/folia-formalization-e17942a1d6b7ac4e7a726266e2b697de2e029862/Folia.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7004663297841696}}
{"text": "(* begin hide *)\nRequire Import Coq.Lists.List.\nNotation \"[]\" := nil : list_scope.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) .. ) : list_scope.\nOpen Scope bool_scope.\n(* end hide *)\n(** In this post, I will begin to formalize a small part of #<a\nhref=\"http://en.wikipedia.org/wiki/Combinatorial_game_theory\">#\ncombinatorial game theory#</a># using Coq. Combinatorial game theory\nattempts to model sequential, deterministic games between two players,\nboth of which take turns causing the game state to change. It\nrestricts itself to _perfect information_ games, where the current\nconfiguration of the game is known to both players. Thus, it can be\nused to study games such as chess, tic-tac-toe, and go, but not games\nsuch as poker or blackjack.\n\nThe power of combinatorial game theory comes from abstracting away\ndetails that are too specific to each game, such as whether it is\nplayed moving pieces on a board, how the pieces can move, etc. It\ndefines a single mathematical object that can represent all games\nuniformily, allowing us to study general situations that could occur\nin many kinds of games. In this post, I will present this\nrepresentation and discuss why it makes sense. I will start with a\nmore intuitive formalization of combinatorial games, and then show how\ncombinatorial game theory applies to all of those.\n\n** Defining combinatorial games\n\nIn combinatorial games, players are traditionally called _left_ and\n_right_. *)\n\nInductive player : Type := Left | Right.\n\n(** Each combinatorial game has a set of _positions_. In chess, for\ninstance, a position is a chess board with black and white pieces on\nit. The rules of the game determine which _moves_ are available to\neach player at a given position. They also describe how the game ends,\nand which player wins in that case. To simplify our analysis, we will\nassume that games end when some player must play but has no moves\nleft, in which case the other player wins. This frees us from having\nto model how matches end separately for each game. We will also\nconsider only _finite_ games, i.e. ones that can't be played\nindefinitely. Notice that these two assumptions taken together,\nstrictly speaking, rule out many interesting games: chess can end in a\ndraw, something that can't happen in our model.\n\nTranslating the above requirements into code results in the following\ndefinition: *)\n\nInductive combinatorial_game := CombinatorialGame {\n  position : Type;\n  moves : player -> position -> list position;\n  valid_move next current := exists s, In next (moves s current);\n  finite_game : well_founded valid_move\n}.\n\n(** To formalize how games are played, we define a predicate [Match cg\nfirst winner m] that represents a match of game [cg] where player\n[first] starts and player [winner] wins. [m] is the sequence of\npositions traversed during the match, from first to last. *)\n\nDefinition other (s : player) : player :=\n  match s with\n    | Left => Right\n    | Right => Left\n  end.\n\nInductive Match cg : forall (first winner : player), list (position cg) -> Prop :=\n| Match_end : forall pl pos,\n                moves cg pl pos = [] ->\n                Match cg pl (other pl) [pos]\n| Match_move : forall pl winner pos next m,\n                 In next (moves cg pl pos) ->\n                 Match cg (other pl) winner (next :: m) ->\n                 Match cg pl winner (pos :: next :: m).\n\n(** In the [Match_end] clause, we check that the current player has no\nmoves left. In [Match_move], we check that the current player can make\na move and that the match can then proceed with the other positions.\n\n** A universal game\n\nWe will now define a combinatorial game that is, in a precise sense to\nbe explained later, the most general one. This is what combinatorial\ngame theory uses to study combinatorial games.\n\nThe crucial observation is that in the definition of [Match] we only\ncare about the moves that can be made from a given position, but not\nabout what the positions themselves _are_. This suggests a definition\nwhere each position is just a pair of sets, one for each player's\nmoves. This forms the type [game] of games. *)\n\nInductive game := Game {\n  left_moves : list game;\n  right_moves : list game\n}.\n\n(** Each position in this game can be pictured as an\narbitrarily-branching tree with two sets of children. On each player's\nturn, they choose one child in their set of moves to be the new\nposition, and lose if they can't choose anything.\n\nThe simplest [game] is [zero], where both players have no moves\navailable. It is a game where the first player always loses. *)\n\nDefinition zero : game := Game [] [].\n\n(** Using [zero] we can define [star], where the first player _always_\nwins by making a move to [zero]. *)\n\nDefinition star : game := Game [zero] [zero].\n\n(** A small variation gives us [one] and [minus_one], where [Left] and\n[Right] always win, respectively. *)\n\nDefinition one : game := Game [zero] [].\nDefinition minus_one : game := Game [] [zero].\n\n(** It should be possible to encapsulate [game] in a\n[combinatorial_game] record. Defining [moves] is simple, but proving\nthat [game]s are finite requires some additional work. The nested\ninductive in the definition of [game] makes Coq generate an induction\nprinciple that is too weak to be useful:\n\n[[\ngame_ind\n     : forall P : game -> Prop,\n       (forall left_moves right_moves : list game,\n        P {| left_moves := left_moves; right_moves := right_moves |}) ->\n       forall g : game, P g\n]]\n\nThe usual solution is to define a new one by hand that gives us\ninduction hypotheses to use: *)\n\nLemma lift_forall :\n  forall T (P : T -> Prop),\n    (forall t, P t) ->\n    forall l, Forall P l.\nProof. induction l; auto. Defined.\n\nDefinition game_ind' (P : game -> Prop)\n                     (H : forall l r, Forall P l -> Forall P r -> P (Game l r)) :\n  forall g : game, P g :=\n  fix F (g : game) : P g :=\n  match g with\n    | Game l r =>\n      H l r (lift_forall _ P F l) (lift_forall _ P F r)\n  end.\n\n(** Using this principle, we can now prove that [game]s always\nterminate and define a [combinatorial_game] for [game]. *)\n\nDefinition game_as_cg : combinatorial_game.\n  refine ({| position := game;\n             moves s := if s then left_moves else right_moves |}).\n  intros p1.\n  induction p1 as [l r IHl IHr] using game_ind'.\n  (* ... *)\n  (* begin hide *)\n  constructor.\n  intros p2 [s H].\n  destruct s; simpl in H.\n  - rewrite Forall_forall in IHl.\n    apply IHl.\n    assumption.\n  - rewrite Forall_forall in IHr.\n    apply IHr.\n    assumption.\n  (* end hide *)\nDefined.\n\n(** ** Game embeddings\n\nI claimed that [game] is the most general combinatorial game. One way\nof seeing this is that we lose no information by representing each\nposition in a combinatorial game as the tree of all possible moves,\nand such a tree can always be encoded as a [game]. To make this\nintuition formal, we can define a notion of _game embedding_ between\ntwo combinatorial games. This will be a mapping between the positions\nof each combinatorial game that preserves matches. Thus, if we have an\nembedding of [cg1] into [cg2], then we can study [cg1] matches by\nregarding them as [cg2] matches. *)\n\nDefinition game_embedding (cg1 cg2 : combinatorial_game)\n           (embedding : position cg1 -> position cg2) : Prop :=\n  forall first winner (m : list (position cg1)),\n    Match cg1 first winner m ->\n    Match cg2 first winner (map embedding m).\n\n(** With this notion of game embedding, combinatorial games form a\ncategory. I will now show that every combinatorial game can be\nembedded in [game], making [game] a terminal object in this category\nand the most general combinatorial game. In this formulation, it is\nonly a _weakly_ terminal object (i.e., embeddings are not unique), as\nwe are using Coq lists to represent sets.\n\nTo embed an arbitrary combinatorial game into [game], we can define a\nfunction by well-founded recursion over the proof that games are\nfinite. In order to do this, we need a higher-order function\n[map_game] that allows us to perform a well-founded recursive call on\na list of next moves. [map_game] acts like [map], but passes to its\nargument function a proof that the element is a [valid_move]. *)\n\nFixpoint map_In {A B} (l : list A) : (forall x, In x l -> B) -> list B :=\n  match l with\n    | [] => fun _ => []\n    | x :: l' => fun f =>\n                   f x (or_introl _ eq_refl)\n                     :: map_In l' (fun x P => f x (or_intror _ P))\n  end.\n\nDefinition map_game {A} (cg : combinatorial_game)\n                    (pos : position cg) (p : player)\n                    (f : forall pos', valid_move cg pos' pos -> A) : list A :=\n  map_In (moves cg p pos) (fun pos' P => f pos' (ex_intro _ p P)).\n\n(** Using this function and the [Fix] combinator in the standard\nlibrary, we write a generic embedding function [embed_in_game]. Like a\nregular fixpoint combinator, [Fix] takes a function that does a\nrecursive call by applying its argument (here, [F]). The difference is\nthat this argument must take a _proof_ that shows that the recursive\ncall is valid.\n\nThe behavior of [embed_in_game] is simple: it calls itself recursively\nfor each possible next position, and includes that position in the set\nof moves of the appropriate player. *)\n\nDefinition embed_in_game cg (pos : position cg) : game :=\n  Fix (finite_game cg)\n      (fun _ => position game_as_cg)\n      (fun pos F =>\n         Game (map_game cg pos Left F)\n              (map_game cg pos Right F))\n      pos.\n(* begin hide *)\nLemma map_In_map :\n  forall A B\n         (l : list A)\n         (f : forall x, In x l -> B)\n         (g : A -> B)\n         (H : forall x P, f x P = g x),\n    map_In l f = map g l.\nProof.\n  intros.\n  induction l as [|x l IH]; auto.\n  simpl.\n  rewrite H. f_equal.\n  apply IH.\n  intros x' P.\n  apply H.\nQed.\n\nLemma map_game_map :\n  forall A\n         (cg : combinatorial_game)\n         (pos : position cg) (p : player)\n         (f : forall pos', valid_move cg pos' pos -> A)\n         (g : position cg -> A)\n         (H : forall pos' P, f pos' P = g pos'),\n    map_game cg pos p f = map g (moves cg p pos).\nProof. eauto using map_In_map. Qed.\n\nLemma map_In_ext :\n  forall A B\n         (l : list A)\n         (f g : forall x, In x l -> B)\n         (EXT : forall x P, f x P = g x P),\n    map_In l f = map_In l g.\nProof.\n  intros.\n  induction l as [|x l IH]; auto.\n  simpl. rewrite EXT.\n  f_equal.\n  apply IH.\n  intros x' P.\n  apply EXT.\nQed.\n\nLemma map_game_ext :\n  forall A\n         (cg : combinatorial_game)\n         (pos : position cg) (p : player)\n         (f g : forall pos', valid_move cg pos' pos -> A)\n         (EXT : forall pos' P, f pos' P = g pos' P),\n    map_game cg pos p f = map_game cg pos p g.\nProof. eauto using map_In_ext. Qed.\n\n(* end hide *)\n(** Definitions that use [Fix] can be hard to manipulate directly, so\nwe need to prove some equations that describe the reduction behavior\nof the function. I've hidden some of the auxiliary lemmas and proofs\nfor clarity; as usual, you can find them in the original [.v] file.\n\nThe proof that we can unfold [embed_in_game] once uses the [Fix_eq]\nlemma in the standard library. *)\n\nLemma embed_in_game_eq cg (pos : position cg) :\n  embed_in_game cg pos =\n  Game (map (embed_in_game cg) (moves cg Left pos))\n       (map (embed_in_game cg) (moves cg Right pos)).\nProof.\n  unfold embed_in_game in *.\n  rewrite Fix_eq.\n  (* ... *)\n  (* begin hide *)\n  - intros.\n    f_equal; apply map_game_map; reflexivity.\n  - intros.\n    f_equal; apply map_game_ext; intros; eauto.\n  (* end hide *)\nQed.\n\n(** With this lemma, we can show that [moves] and [embed_in_game] commute. *)\n\nLemma embed_in_game_moves cg (p : position cg) :\n  forall s, moves game_as_cg s (embed_in_game cg p) =\n            map (embed_in_game cg) (moves cg s p).\nProof.\n  intros.\n  rewrite embed_in_game_eq.\n  destruct s; reflexivity.\nQed.\n\n(** We are now ready to state and prove our theorem: every\ncombinatorial game can be embedded in [game]. *)\n\nTheorem embed_in_game_correct cg :\n  game_embedding cg game_as_cg (embed_in_game cg).\nProof.\n  unfold game_embedding.\n  intros first winner m MATCH.\n  induction MATCH as [winner p H|s winner p p' m IN MATCH IH];\n  simpl; constructor; eauto.\n  - rewrite embed_in_game_moves, H. reflexivity.\n  - rewrite embed_in_game_moves. auto using in_map.\nQed.\n\n(** ** Summary\n\nWe've developed the foundations of combinatorial game theory, showing\nhow it can model combinatorial games in a simple yet general way. We\nhaven't explored yet how to use this representation in practice to\nstudy games, something I plan to do on future posts.\n\n_Update_: I'll leave the list of posts in this series here.\n\n- #<a href=\"/posts/2013-10-27-summing-combinatorial-games.html\">#Summing combinatorial games#</a>#\n\n*)\n", "meta": {"author": "arthuraa", "repo": "poleiro", "sha": "c2f2159470872ac83d305b4a50fda8fccc89ae53", "save_path": "github-repos/coq/arthuraa-poleiro", "path": "github-repos/coq/arthuraa-poleiro/poleiro-c2f2159470872ac83d305b4a50fda8fccc89ae53/theories/CGT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914788, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7004663260803236}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf1 : natural) (z : natural) (x : natural)\n  : natural := plus (mult x z) z.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj235_coqofml_a14kAY.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.7003992729410439}}
{"text": "Require Export GeoCoq.Elements.OriginalProofs.proposition_27.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_collinearparallel.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_parallelsymmetric.\nRequire Export GeoCoq.Elements.OriginalProofs.lemma_parallelflip.\n\nSection Euclid.\n\nContext `{Ax:euclidean_neutral_ruler_compass}.\n\nLemma proposition_27B : \n   forall A D E F, \n   CongA A E F E F D -> TS A E F D ->\n   Par A E F D.\nProof.\nintros.\nassert (neq A E) by (forward_using lemma_angledistinct).\nlet Tf:=fresh in\nassert (Tf:exists B, (BetS A E B /\\ Cong E B A E)) by (conclude lemma_extension);destruct Tf as [B];spliter.\nassert (neq F D) by (forward_using lemma_angledistinct).\nassert (neq D F) by (conclude lemma_inequalitysymmetric).\nlet Tf:=fresh in\nassert (Tf:exists C, (BetS D F C /\\ Cong F C F D)) by (conclude lemma_extension);destruct Tf as [C];spliter.\nassert (BetS C F D) by (conclude axiom_betweennesssymmetry).\nassert (Par A B C D) by (conclude proposition_27).\nassert (Col D F C) by (conclude_def Col ).\nassert (Col C D F) by (forward_using lemma_collinearorder).\nassert (Par A B F D) by (conclude lemma_collinearparallel).\nassert (Par F D A B) by (conclude lemma_parallelsymmetric).\nassert (Par F D B A) by (forward_using lemma_parallelflip).\nassert (Col A E B) by (conclude_def Col ).\nassert (Col B A E) by (forward_using lemma_collinearorder).\nassert (neq A E) by (forward_using lemma_betweennotequal).\nassert (neq E A) by (conclude lemma_inequalitysymmetric).\nassert (Par F D E A) by (conclude lemma_collinearparallel).\nassert (Par F D A E) by (forward_using lemma_parallelflip).\nassert (Par A E F D) by (conclude lemma_parallelsymmetric).\nclose.\nQed.\n\nEnd Euclid.\n\n\n", "meta": {"author": "GeoCoq", "repo": "GeoCoq", "sha": "453539e41a5f356e9ac233ae0ea40889c68dbf3d", "save_path": "github-repos/coq/GeoCoq-GeoCoq", "path": "github-repos/coq/GeoCoq-GeoCoq/GeoCoq-453539e41a5f356e9ac233ae0ea40889c68dbf3d/Elements/OriginalProofs/proposition_27B.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7003903746563623}}
{"text": "Require Import Arith.\nRequire Import List.\n\nRequire Import perm list_ind.\nRequire Import list_incl.\n\nSection pigeon.\n\n  Variable (X : Type).\n\n  Inductive list_has_dup : list X -> Prop :=\n    | in_lhd_1 : forall x l, In x l -> list_has_dup (x::l)\n    | in_lhd_2 : forall x l, list_has_dup l -> list_has_dup (x::l).\n\n  Notation lhd := list_has_dup.\n\n  Fact lhd_app_left l m : lhd l -> lhd (l++m).\n  Proof.\n    intros H.\n    induction H as [ x l H | x l H IH ]; simpl.\n  Admitted.\n\n  Fact lhd_app_right l m : lhd m -> lhd (l++m).\n  Proof.\n    induction l.\n  Admitted.\n\n  Fact lhd_app x l m : In x l -> In x m -> lhd (l++m).\n  Proof.\n    induction l as [ | y l IHl ]; simpl.\n  Admitted.\n \n  Fact lhd_cons_inv x l : lhd (x::l) -> In x l \\/ lhd l.\n  Proof.\n    inversion_clear 1; auto.\n  Qed.\n\n  (* these are the equivalent characterizations *)\n\n  Section alternate.\n\n    Definition lhd_alt1 (m : list X) := exists x a b c, m = a++x::b++x::c.\n    \n    Fixpoint lhd_alt2 (m : list X) :=\n      match m with \n        | nil  => False\n        | x::m => In x m \\/ lhd_alt2 m\n      end.\n  \n    Fact lhd_lhd_alt_1 m : lhd m -> lhd_alt1 m.\n    Proof.     \n      induction 1 as [ x m Hm | x m Hm IHm ].\n      apply in_split in Hm.\n      destruct Hm as (l & r & Hm).\n      subst m.\n      exists x, nil, l, r.\n      reflexivity.\n      \n      destruct IHm as (y & a & b & c & H).\n      subst m.\n      exists y, (x::a), b, c.\n      reflexivity.\n    Qed.\n    \n    Fact lhd_alt2_app_right l m : lhd_alt2 m -> lhd_alt2 (l++m).\n    Proof.\n      induction l; simpl; auto.\n    Qed.\n    \n    Fact lhd_alt1_lhd_alt2 m : lhd_alt1 m -> lhd_alt2 m.\n    Proof.    \n      intros (x & a & b & c & H).\n      subst m.\n      apply lhd_alt2_app_right.    \n      constructor 1.\n      apply in_or_app; right; left; auto.\n    Qed.\n    \n    Fact lhd_alt2_lhd m : lhd_alt2 m -> lhd m.\n    Proof.\n      induction m as [ | x m ].\n      intros [].\n      intros [ H | H ].\n      constructor 1; auto.\n      constructor 2; auto.\n    Qed.\n\n    Fact lhd_equiv m : lhd m <-> exists x a b c, m = a++x::b++x::c.\n    Proof.\n      split.\n      apply lhd_lhd_alt_1.\n      intros H; apply lhd_alt2_lhd, lhd_alt1_lhd_alt2, H.\n    Qed. \n  \n  End alternate.     \n\n  Fact perm_lhd l m : l ~p m -> list_has_dup l -> list_has_dup m.\n  Proof.\n    intros H.\n    induction H as [ | x l m H1 IH1 | x y l | ]; auto.\n    intros H.\n    apply lhd_cons_inv in H; destruct H as [ H | H ].\n    \n    admit.\n    admit.\n    \n    intros H.\n    apply lhd_cons_inv in H.\n    destruct H as [ [ H | H ] | H ]; subst.\n    \n    admit.\n    admit.\n\n    apply lhd_cons_inv in H.\n    destruct H as [ H | H ].\n    \n    admit.\n    admit.\n   \n  Admitted.\n  \n  Fact In_perm_head (x : X) l : In x l -> exists m, l ~p x::m.\n  Proof.\n    intros H.\n    apply in_split in H.\n    destruct H as (u & v & ?).\n    subst l.\n    exists (u++v).\n    apply perm_sym, perm_middle.\n  Qed.\n  \n  Fact repeat_choice_two (x : X) m : (forall a, In a m -> a = x) -> (exists m', m = x::x::m') \\/ m = nil \\/ m = x::nil.\n  Proof.\n    intros H.\n    destruct m as [ | a [ | b m ] ].\n    right; left; auto.\n    right; right; rewrite (H a); auto; left; auto.\n    left; rewrite (H a), (H b).\n    exists m; auto.\n    right; left; auto.\n    left; auto.\n  Qed.\n\n  Fact incl_right_cons_incl_or_lhd_or_perm m x l : incl m (x::l) -> incl m l \\/ lhd m \\/ exists m', m ~p x::m' /\\ incl m' l.\n  Proof.\n    intros H.\n    apply incl_right_cons_split in H.\n    destruct H as (m1 & m2 & H1 & H2 & H3).\n    destruct (repeat_choice_two _ _ H2) as [ (m3 & H4) | [ H4 | H4 ] ]; \n      subst m1; simpl in H1; clear H2.\n    \n    apply perm_sym in H1.\n    right; left.\n    apply perm_lhd with (1 := H1).\n    constructor 1; left; auto.\n    \n    left.\n    intros u Hu.\n    apply H3.\n    apply perm_incl with (1 := H1); auto.\n    \n    right; right.\n    exists m2; auto.\n  Qed.\n    \n  Fact length_le_and_incl_implies_dup_or_perm l :  \n               forall m, length l <= length m \n                      -> incl m l \n                      -> lhd m \\/ m ~p l.\n  Proof.   \n    \n    (* the proof is by generalized induction over length l *) \n\n    induction l as [ [ | x l ] IHl ] using list_gen_ind.\n\n    (* case l -> nil *)\n    \n    admit.\n    \n    intros [ | y m ] H1 H2.\n    \n    (* case l -> x::l and m -> nil *)\n    \n    apply le_Sn_0 in H1; destruct H1.\n    \n    (* case l -> x::l and m -> y :: m *)\n    \n    simpl in H1; apply le_S_n in H1.\n    apply incl_left_cons in H2. \n    destruct H2 as [ H3 H4 ].\n\n    simpl in H3.\n    destruct H3 as [ H3 | H3 ].\n    \n    (* case x = y *)\n    \n    subst y.\n    apply incl_right_cons_choose in H4.\n    destruct H4 as [ H4 | H4 ].\n    \n    (* case x = y & In x m *)\n    \n    admit.\n    \n    (* case x = y & incl m l *)\n \n    destruct IHl with (3 := H4).\n    simpl; apply lt_n_Sn.\n    assumption.\n    admit.\n    admit.\n    \n    (* case In y l *)\n    \n    apply incl_right_cons_incl_or_lhd_or_perm in H4.\n    destruct H4 as [ H4 | [ H4 | (m' & H4 & H5) ] ].\n    \n    (* case In y l and incl m l *)\n    \n    destruct IHl with (3 := H4) as [ H5 | H5 ]; auto.\n    admit.\n    admit.\n    \n    (* case In y l and lhd m *)\n    \n    admit.\n    \n    (* case In y l and m ~p x::m' and incl m' l *)\n    \n    apply perm_sym in H4.\n    apply In_perm_head in H3.\n    destruct H3 as (l' & Hl').\n    \n    (* l ~p y::l' for some l' *)\n\n    assert (incl m' (y::l')) as H6.\n      intros ? ?; apply perm_incl with (1 := Hl'), H5; auto.\n    clear H5.\n    \n    (* and incl m' (y::l') *)\n\n    apply incl_right_cons_choose in H6.\n    destruct H6 as [ H6 | H6 ].\n    \n    (* subcase In y m' *)\n    \n    admit.\n    \n    (* subcase incl m' l' *)\n\n    (* apply the induction hypothesis *)\n    \n    apply IHl in H6.\n    destruct H6 as [ H6 | H6 ].\n    \n    (* and either lhd m' *)\n    \n    admit.\n    \n    (* or m' ~p l', which leads to y::m ~p x::l *)\n    \n    admit.\n    \n    (* two checks that the induction hypothesis can be used *)\n    \n    apply perm_length in Hl'.\n    simpl in Hl' |- *.\n    rewrite Hl'.\n    apply le_n_Sn.\n    \n    apply perm_length in Hl'.\n    apply perm_length in H4.\n    simpl in H4, Hl'.\n    apply le_S_n.\n    rewrite <- Hl', H4; auto.\n  Admitted.\n\n  (* if l is strictly shorter that m but m has all its elements in l \n     then some element of m must be repeated *)\n \n  Theorem finite_pigeon_hole l m : incl m l -> length l < length m -> lhd m.\n  Proof.\n    intros H2 H1.\n    destruct length_le_and_incl_implies_dup_or_perm with (2 := H2) as [ H3 | H3 ]; auto.\n    apply lt_le_weak; auto.\n    apply perm_length in H3.\n    exfalso; revert H1; rewrite H3; apply lt_irrefl.\n  Qed.\n\nEnd pigeon.\n", "meta": {"author": "DmxLarchey", "repo": "PHP-etudiants", "sha": "5d9f86703a0070a55600a68bfda9cf1384a5ff72", "save_path": "github-repos/coq/DmxLarchey-PHP-etudiants", "path": "github-repos/coq/DmxLarchey-PHP-etudiants/PHP-etudiants-5d9f86703a0070a55600a68bfda9cf1384a5ff72/list_pigeon_hole.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7003468822492985}}
{"text": "Require Import Utf8 Lia.\nLocal Set Implicit Arguments.\n\nDefinition lt' (p1 p2 : nat * nat) : Prop :=\n  match p1, p2 with\n  | (n1, m1), (n2, m2) => n1 < n2 ∨ n1 = n2 ∧ m1 < m2\n  end.\n\nLemma lt'_wf_aux :\nwell_founded lt → forall x, Acc lt x → forall y, Acc lt y → Acc lt' (x, y).\nProof.\n  intros Hlt x Hx.\n  induction Hx as [x _ IHaccx].\n  intros y Hy.\n  induction Hy as [y _ IHaccy].\n  constructor.\n  intros (x', y').\n  destruct 1 as [ | [] ]; subst ; auto.\nQed.\n\nLemma lt'_wf : well_founded lt'.\nProof.\n  intros (x, y).\n  apply lt'_wf_aux ; apply Wf_nat.lt_wf.\nQed.\n\nLtac lt'_left := simpl ; left ; lia.\nLtac lt'_right := simpl ; right ; split ; [ reflexivity | lia ].\nLtac lt'_solve :=\n  match goal with\n  | [ W : Acc lt' (?n2, 0) |- Acc lt' (?n1, ?m1) ] =>\n    apply (Acc_inv W) ; lt'_left\n  | [ W : Acc lt' (S ?n2, ?m2) |- Acc lt' (?n1, ?m1) ] =>\n    apply (Acc_inv W) ; lt'_left\n  | [ W : Acc lt' (?n, ?m2) |- Acc lt' (?n, ?m1) ] =>\n    apply (Acc_inv W) ; lt'_right\n  | [ W : Acc lt' (?n2, ?m2) |- Acc lt' (?n1, ?m1) ] =>\n    (* general case *)\n    apply (Acc_inv W) ;\n    simpl;\n    let L := fresh \"H_le\" in\n    assert (n1 <= n2) as L ; [ lia | ] ;\n    inversion L ; subst ; [ lt'_right | lt'_left ]\n  end.\n", "meta": {"author": "yizhouzhang", "repo": "olaf-coq", "sha": "03090a5e60e739dfa45ad60322d848c18faad48d", "save_path": "github-repos/coq/yizhouzhang-olaf-coq", "path": "github-repos/coq/yizhouzhang-olaf-coq/olaf-coq-03090a5e60e739dfa45ad60322d848c18faad48d/coq-src/UFO/Util/Wf_natnat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888304, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7003468710291201}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) : natural := Succ (plus y lf2).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_81_plus_assoc/goal33conj82_coqofml_X78cXR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7003181484127262}}
{"text": "Require Import ZArith.\nRequire Import Lists.List.\nImport ListNotations.\nRequire Import Coq.extraction.ExtrOcamlNatInt.\n\n(********************************************)\n(* Languages definitions                    *)\n(********************************************)\n\n(* Logic language *)\nInductive logic : Set :=\n  | Land  : logic -> logic -> logic\n  | Lor   : logic -> logic -> logic\n  | Limpl : logic -> logic -> logic\n  | Lneg  : logic -> logic\n  | Latom : nat -> logic.\n\n(* Logic without impl *)\nInductive logic_1 : Set :=\n  | L1and   : logic_1 -> logic_1 -> logic_1\n  | L1or    : logic_1 -> logic_1 -> logic_1\n  | L1neg   : logic_1 -> logic_1\n  | L1atom  : nat -> logic_1.\n\n(* Literals *)\nInductive literal : Set :=\n  | Pos : nat -> literal\n  | Neg : nat -> literal.\n\n(* Logic_1 with distributed negations *)\nInductive logic_2 : Set :=\n  | L2and   : logic_2 -> logic_2 -> logic_2\n  | L2or    : logic_2 -> logic_2 -> logic_2\n  | L2lit   : literal -> logic_2.\n\n(* Clauses *)\nDefinition clause := list literal.\n\n(* CNF *)\nDefinition logic_3 := list clause.\n\n(* Conversion algorithm from logic to logic_1 *)\nFixpoint remove_impl (l : logic) : logic_1 :=\n  match l with\n  | Land a b =>\n    L1and (remove_impl a) (remove_impl b)\n  | Lor a b =>\n    L1or (remove_impl a) (remove_impl b)\n  | Limpl a b =>\n    L1or (L1neg (remove_impl a)) (remove_impl b)\n  | Lneg a => L1neg (remove_impl a)\n  | Latom a => L1atom a\n  end.\n\n(* Conversion algorithm from logic_1 to logic_2 *)\nFixpoint remove_neg' (sign : bool) (l : logic_1) : logic_2 :=\n  match l with\n  | L1and a b =>\n    if sign then L2and (remove_neg' sign a) (remove_neg' sign b)\n    else L2or (remove_neg' false a) (remove_neg' false b)\n  | L1or a b =>\n    if sign then L2or (remove_neg' sign a) (remove_neg' sign b)\n    else L2and (remove_neg' false a) (remove_neg' false b)\n  | L1neg a =>\n    if sign then remove_neg' false a\n    else remove_neg' true a\n  | L1atom n =>\n    if sign then L2lit (Pos n)\n    else L2lit (Neg n)\n  end.\n\nDefinition remove_neg := remove_neg' true.\n\n(* Distribute a clause on a set of clauses *)\nDefinition merge_clause (c : clause) (l : logic_3) :=\n  map (fun c' => c ++ c') l.\n\n(* Double distribute a set of clauses on another one *)\nFixpoint merge (l1 : logic_3) (l2 : logic_3) : logic_3 :=\n  match l1 with\n  | [] => []\n  | c::cs => (merge_clause c l2) ++ (merge cs l2)\n  end.\n\n(* Logic_2 to logic_3 conversion *)\nFixpoint cnf' (l : logic_2) : logic_3 :=\n  match l with\n  | L2and a b => (cnf' a) ++ (cnf' b)\n  | L2or a b => merge (cnf' a) (cnf' b)\n  | L2lit a => [[a]]\n  end.\n\n(* CNF conversion *)\nDefinition cnf (l : logic) : logic_3 :=\n    cnf' (remove_neg (remove_impl l)).\n\n(********************************************)\n(* Semantics for the intermediate languages *)\n(********************************************)\n\n(* Denotational semantic for the logic language *)\nFixpoint semL (l : logic) (v : nat -> bool) : bool :=\n  match l with\n  | Land a b =>\n    andb (semL a v) (semL b v)\n  | Lor a b =>\n    orb (semL a v) (semL b v)\n  | Limpl a b =>\n    implb (semL a v) (semL b v)\n  | Lneg a =>\n    negb (semL a v)\n  | Latom n => v n\n  end.\n\n(* Denotational semantic for the logic_1 language *)\nFixpoint semL1 (l : logic_1) (v : nat -> bool) : bool :=\n  match l with\n  | L1and a b =>\n    andb (semL1 a v) (semL1 b v)\n  | L1or a b =>\n    orb (semL1 a v) (semL1 b v)\n  | L1neg a =>\n    negb (semL1 a v)\n  | L1atom n => v n\n  end.\n\n(* Denotational semantic for the logic_2 language *)\nFixpoint semL2 (l : logic_2) (v : nat -> bool) : bool :=\n  match l with\n  | L2and a b =>\n    andb (semL2 a v) (semL2 b v)\n  | L2or a b =>\n    orb (semL2 a v) (semL2 b v)\n  | L2lit (Pos n) => v n\n  | L2lit (Neg n) => negb (v n)\n  end.\n\n(* Denotational semantic for clauses *)\nFixpoint semC (c : clause) (v : nat -> bool) : bool :=\n  match c with\n  | [] => false\n  | Pos n::xs => orb (v n) (semC xs v)\n  | Neg n::xs => orb (negb (v n)) (semC xs v)\n  end.\n\n(* Denotational semantic for CNFs *)\nFixpoint semL3 (l : logic_3) (v : nat -> bool) : bool :=\n  match l with\n  | [] => true\n  | c::cs => andb (semC c v) (semL3 cs v)\n  end.\n\n(********************************************)\n(* Correction proofs                        *)\n(********************************************)\n\n(* [remove_impl] preserve the semantic *)\nTheorem remove_impl_correct:\n  forall l v, semL l v = semL1 (remove_impl l) v.\nProof.\n  intros.\n  induction l; simpl.\n  - rewrite IHl1, IHl2; reflexivity.\n  - rewrite IHl1, IHl2; reflexivity.\n  - rewrite IHl1, IHl2; unfold implb; destruct semL1; reflexivity.\n  - rewrite IHl; reflexivity.\n  - reflexivity.\nQed.\n\n(* [remove_neg' false] inverse the denotations *)\nLemma remove_neg_false_negb:\n  forall l v, semL2 (remove_neg' false l) v = negb (semL2 (remove_neg' true l) v).\nProof.\n  intros.\n  induction l; simpl.\n  - rewrite IHl1, IHl2, Bool.negb_andb; reflexivity.\n  - rewrite IHl1, IHl2, Bool.negb_orb; reflexivity.\n  - rewrite IHl, Bool.negb_involutive; reflexivity.\n  - reflexivity.\nQed.\n\n(* [remove_neg] preserve the semantic *)\nTheorem remove_neg_correct:\n  forall l v, semL1 l v = semL2 (remove_neg l) v.\nProof.\n  intros.\n  induction l; simpl.\n  - rewrite IHl1, IHl2; reflexivity.\n  - rewrite IHl1, IHl2; reflexivity.\n  - rewrite IHl. unfold remove_neg. simpl.\n    rewrite remove_neg_false_negb; reflexivity.\n  - reflexivity.\nQed.\n\n(* semantic of the union of two clauses *)\nTheorem semC_union:\n  forall c1 c2 v, semC (c1 ++ c2) v = orb (semC c1 v) (semC c2 v).\nProof.\n  intros.\n  induction c1; simpl.\n  - reflexivity.\n  - destruct a; rewrite IHc1, Bool.orb_assoc; reflexivity.\nQed.\n\n(* semantic of the union of two set of clauses *)\nTheorem semL3_union:\n  forall c1 c2 v, semL3 (c1 ++ c2) v = andb (semL3 c1 v) (semL3 c2 v).\nProof.\n  intros.\n  induction c1; simpl.\n  - reflexivity.\n  - rewrite IHc1, Bool.andb_assoc; reflexivity.\nQed.\n\n(* [merge_clause] preserve the semantic *)\nTheorem merge_clause_correct:\n  forall c l v, semL3 (merge_clause c l) v = orb (semC c v) (semL3 l v).\nProof.\n  intros.\n  induction l; simpl.\n  - rewrite Bool.orb_comm. reflexivity.\n  - rewrite semC_union, IHl, Bool.orb_andb_distrib_r; reflexivity.\nQed.\n\n(* [merge] preserve the semantic *)\nTheorem merge_correct:\n  forall l1 l2 v, orb (semL3 l1 v) (semL3 l2 v) = semL3 (merge l1 l2) v.\nProof.\n  intros.\n  induction l1; simpl.\n  - reflexivity.\n  - rewrite semL3_union,\n            merge_clause_correct,\n            <- IHl1,\n            Bool.orb_andb_distrib_l.\n    reflexivity.\nQed.\n\n(* [cnf'] preserve the semantic *)\nTheorem cnf'_correct:\n  forall l v, semL2 l v = semL3 (cnf' l) v.\nProof.\n  intros.\n  induction l; simpl.\n  - rewrite semL3_union, IHl1, IHl2. reflexivity.\n  - rewrite <- merge_correct, IHl1, IHl2. reflexivity.\n  - destruct l; rewrite Bool.andb_comm, Bool.orb_comm; simpl; reflexivity.\nQed.\n\n(* [cnf] preserve the semantic *)\nTheorem cnf_correct:\n  forall l v, semL l v = semL3 (cnf l) v.\nProof.\n  intros.\n  unfold cnf.\n  rewrite remove_impl_correct,\n          remove_neg_correct,\n          cnf'_correct.\n  reflexivity.\nQed.\n\nRecursive Extraction cnf.", "meta": {"author": "acorrenson", "repo": "neutron", "sha": "8070f0a8dc87a8c132e055bfd88d2563944e0e00", "save_path": "github-repos/coq/acorrenson-neutron", "path": "github-repos/coq/acorrenson-neutron/neutron-8070f0a8dc87a8c132e055bfd88d2563944e0e00/src/language/logic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7003181396292847}}
{"text": "Require Import ProofCheckingEuclid.euclidean_axioms.\nRequire Import ProofCheckingEuclid.euclidean_defs.\nRequire Import ProofCheckingEuclid.lemma_betweennotequal.\n\nSection Euclid.\n\nContext `{Ax1:euclidean_neutral}.\n\n(* TODO: rename to lemma_onray_neq_A_C *)\nLemma lemma_onray_strict :\n\tforall A B C,\n\tOnRay A B C ->\n\tneq A C.\nProof.\n\tintros A B C.\n\tintros OnRay_AB_C.\n\n\tdestruct OnRay_AB_C as (J & BetS_J_A_C & _).\n\n\tpose proof (lemma_betweennotequal _ _ _ BetS_J_A_C) as (neq_A_C & _).\n\n\texact neq_A_C.\nQed.\n\nEnd Euclid.\n", "meta": {"author": "blin", "repo": "proof-checking-euclid", "sha": "3bbd59a09f3f89e9f1ff96837ea099bab395af19", "save_path": "github-repos/coq/blin-proof-checking-euclid", "path": "github-repos/coq/blin-proof-checking-euclid/proof-checking-euclid-3bbd59a09f3f89e9f1ff96837ea099bab395af19/lemma_onray_strict.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.7003181352375637}}
{"text": "Set Implicit Arguments.\nRequire Import Arith.\n\nRequire Import set.\nRequire Import order.\nRequire Import order_elements.\nRequire Import subset.\nRequire Import equiv.\nRequire Import subset_elements.\n\nProposition subset_reflexive : forall (a:set), subset a a.\nProof.\n  (* induction on the order of a *)\n  cut(forall (n:nat) (a:set), order a <= n -> subset a a).\n  intros H a. apply H with (n:= order a). apply le_n. intro n. elim n.\n  (* order a <= 0 *)\n  intros a H. cut (a = Empty). intro H'. rewrite H'. unfold subset. simpl.\n  reflexivity. apply order_eq_0. symmetry. apply le_n_0_eq. exact H.\n  (* order a <= S n *)\n  clear n. intros n IH a H. cut(order a < S n \\/ order a = S n). intro H'. elim H'.\n  (* order a < S n *)\n  intro H''. unfold lt in H''. apply IH. apply le_S_n. exact H''.\n  (* order a = S n *)\n  intro H''. apply subset_elements. intros x Hx. exists x. split. exact Hx.\n  unfold equiv. cut (subset x x). intro Hx'. split. exact Hx'. exact Hx'.\n\n  apply IH. apply le_S_n. rewrite <- H''. apply order_elements.\n  exact Hx.\n  (* clean up *)\n  apply le_lt_or_eq. exact H.\nQed.\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/set2/subset_reflexive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7003181350932101}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)\n(* <O___,, *       (see CREDITS file for the list of authors)           *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\nSection Relation_Definition.\n\n  Variable A : Type.\n\n  Definition relation := A -> A -> Prop.\n\n  Variable R : relation.\n\n\n  Section General_Properties_of_Relations.\n\n    Definition reflexive : Prop := forall x:A, R x x.\n    Definition transitive : Prop := forall x y z:A, R x y -> R y z -> R x z.\n    Definition symmetric : Prop := forall x y:A, R x y -> R y x.\n    Definition antisymmetric : Prop := forall x y:A, R x y -> R y x -> x = y.\n\n    (* for compatibility with Equivalence in  ../PROGRAMS/ALG/  *)\n    Definition equiv := reflexive /\\ transitive /\\ symmetric.\n\n  End General_Properties_of_Relations.\n\n\n\n  Section Sets_of_Relations.\n\n    Record preorder : Prop :=\n      { preord_refl : reflexive; preord_trans : transitive}.\n\n    Record order : Prop :=\n      { ord_refl : reflexive;\n\tord_trans : transitive;\n\tord_antisym : antisymmetric}.\n\n    Record equivalence : Prop :=\n      { equiv_refl : reflexive;\n\tequiv_trans : transitive;\n\tequiv_sym : symmetric}.\n\n    Record PER : Prop :=  {per_sym : symmetric; per_trans : transitive}.\n\n  End Sets_of_Relations.\n\n\n  Section Relations_of_Relations.\n\n    Definition inclusion (R1 R2:relation) : Prop :=\n      forall x y:A, R1 x y -> R2 x y.\n\n    Definition same_relation (R1 R2:relation) : Prop :=\n      inclusion R1 R2 /\\ inclusion R2 R1.\n\n    Definition commut (R1 R2:relation) : Prop :=\n      forall x y:A,\n\tR1 y x -> forall z:A, R2 z y ->  exists2 y' : A, R2 y' x & R1 z y'.\n\n  End Relations_of_Relations.\n\n\nEnd Relation_Definition.\n\nHint Unfold reflexive transitive antisymmetric symmetric: sets.\n\nHint Resolve Build_preorder Build_order Build_equivalence Build_PER\n  preord_refl preord_trans ord_refl ord_trans ord_antisym equiv_refl\n  equiv_trans equiv_sym per_sym per_trans: sets.\n\nHint Unfold inclusion same_relation commut: sets.\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/theories/Relations/Relation_Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7003162709326469}}
{"text": "Set Warnings \"-notation-overridden\".\nRequire Import Equations.Type.Loader Equations.Type.Relation Equations.Type.WellFounded.\nImport Id_Notations.\n\nSection Lt.\n  Inductive le : nat -> nat -> Set :=\n    | le_0 x : le 0 x\n    | le_S {x y} : le x y -> le (S x) (S y).\n\n  Definition lt x y := le (S x) y.\n\n  Lemma le_eq_lt x y : le x y -> (x = y) + (lt x y).\n  Proof.\n    induction 1. destruct x. left; constructor.\n    right; constructor. constructor.\n    dependent elimination IHle as [inl id_refl|inr Hlt].\n    left; constructor. right; now constructor.\n  Defined.\n\n  Global Instance lt_wf : WellFounded lt.\n  Proof.\n    intros x. induction x.\n    constructor. intros y Hy. depelim Hy.\n    constructor. intros y Hy.\n    dependent elimination Hy as [@le_S y x Hle].\n    apply le_eq_lt in Hle.\n    dependent elimination Hle as [inl id_refl|inr Hlt].\n    assumption.\n    destruct IHx. now apply a.\n  Defined.\n\n  Lemma lt_n_Sn n : lt n (S n).\n  Proof.\n    constructor.\n    induction n; now constructor.\n  Defined.\nEnd Lt.\n\n#[global]\nHint Resolve lt_n_Sn : Below.\n\n(** Define non-dependent lexicographic products *)\n\nImport Sigma_Notations.\nLocal Open Scope equations_scope.\n\nSection Lexicographic_Product.\n\n  Variable A : Type.\n  Variable B : Type.\n  Variable leA : relation A.\n  Variable leB : relation B.\n\n  Inductive lexprod : A * B -> A * B -> Type :=\n    | left_lex :\n      forall {x x':A} {y:B} {y':B},\n        leA x x' -> lexprod (x, y) (x', y')\n    | right_lex :\n      forall {x:A} {y y':B},\n        leB y y' -> lexprod (x, y) (x, y').\n\n  Lemma acc_A_B_lexprod :\n    forall x:A, Acc leA x -> (well_founded leB) ->\n                forall y:B, Acc leB y -> Acc lexprod (x, y).\n  Proof.\n    induction 1 as [x _ IHAcc]; intros H2 y.\n    induction 1 as [x0 H IHAcc0].\n    apply Acc_intro.\n    destruct y as [x2 y1]; intro Hlex.\n    depelim Hlex. apply IHAcc; auto with relations.\n    now apply IHAcc0.\n  Defined.\n\n  Theorem wf_lexprod :\n    well_founded leA ->\n    well_founded leB -> well_founded lexprod.\n  Proof.\n    intros wfA wfB; unfold well_founded.\n    destruct x.\n    apply acc_A_B_lexprod; auto with relations; intros.\n  Defined.\n\nEnd Lexicographic_Product.\n\n#[export]\nInstance wellfounded_lexprod A B R S `(wfR : WellFounded A R, wfS : WellFounded B S) :\n  WellFounded (lexprod A B R S) := wf_lexprod A B R S wfR wfS.\n\n#[global]\nHint Constructors lexprod : Below.\n", "meta": {"author": "mattam82", "repo": "Coq-Equations", "sha": "5603bfff39f3866eed8f010591b5503d5776fa4e", "save_path": "github-repos/coq/mattam82-Coq-Equations", "path": "github-repos/coq/mattam82-Coq-Equations/Coq-Equations-5603bfff39f3866eed8f010591b5503d5776fa4e/theories/Type/WellFoundedInstances.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7003162582786646}}
{"text": "(* infotheo (c) AIST. R. Affeldt, M. Hagiwara, J. Senizergues. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice fintype.\nFrom mathcomp Require Import tuple div path bigop prime finset fingroup perm.\nRequire Import Reals.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(** Some additional lemmas about ssrnat, seq, finset, tuple *)\n\nSection ssrnat_ext.\n\nLemma leq_lt_predn : forall a b : nat, a < b -> a <= b.-1.\nProof. move=> a ; case ; first by rewrite ltn0.\nmove=> b Hab ; rewrite -ltnS prednK //. Qed.\n\nLemma mul2_inj a b : a.*2 = b.*2 -> a = b.\nProof. rewrite -!muln2; move/eqP; rewrite eqn_pmul2r //; by move/eqP. Qed.\n\nLemma nat_of_pos_not_0 : forall p, nat_of_pos p <> O.\nProof.\nelim => // p H.\ncontradict H.\nrewrite /= NatTrec.doubleE in H.\napply/eqP; rewrite -double_eq0; by apply/eqP.\nQed.\n\nLemma nat_of_pos_inj : forall i j, nat_of_pos i = nat_of_pos j -> i = j.\nProof.\nelim=> [i Hi [] | i Hi [] | j /=].\n- move=> j /= [].\n  rewrite !NatTrec.doubleE => Hj; f_equal.\n  by apply Hi, mul2_inj.\n- move=> j /=.\n  rewrite !NatTrec.doubleE => Hj.\n  have absurd : odd ((nat_of_pos j).*2) by rewrite -Hj /= odd_double.\n  by rewrite odd_double in absurd.\n- rewrite /= NatTrec.doubleE.\n  case => Habsurd.\n  suff : False by done.\n  move: (@nat_of_pos_not_0 i).\n  by destruct (nat_of_pos i).\n- move=> j /=.\n  rewrite !NatTrec.doubleE => Hj.\n  have absurd : odd ((nat_of_pos i).*2) by rewrite Hj /= odd_double.\n  by rewrite odd_double in absurd.\n- move=> j /= [].\n  rewrite !NatTrec.doubleE => Hj; f_equal.\n  by apply Hi, mul2_inj.\n- rewrite /= NatTrec.doubleE => absurd.\n  suff : False by done.\n  move: (@nat_of_pos_not_0 i).\n  by destruct (nat_of_pos i).\n  destruct j => //=;\n    rewrite NatTrec.doubleE => absurd ;\n      have [//] : False ;\n        move: (@nat_of_pos_not_0 j) => H' ;\n          by destruct (nat_of_pos j).\nQed.\n\nLemma bin_of_nat_inj : forall a b, bin_of_nat a = bin_of_nat b -> a = b.\nProof.\nmove=> a b X.\nhave : nat_of_bin (bin_of_nat a) = nat_of_bin (bin_of_nat b) by rewrite X.\nby rewrite 2!bin_of_natK.\nQed.\n\nLemma bin_of_nat_nat_of_pos_not_0 : forall i, bin_of_nat (nat_of_pos i) <> 0%num.\nProof.\nelim=> // a Ha /=.\nrewrite NatTrec.doubleE.\ncontradict Ha.\nby destruct (nat_of_pos a).\nQed.\n\nLemma expn_2 : forall r, r <= (expn 2 r).-1.\nProof.\ncase=> // r; rewrite -subn1 ltn_subRL addnC addn1; by apply ltn_expl.\nQed.\n\nEnd ssrnat_ext.\n\nSection seq_ext.\n\nVariables A B : Type.\n\nLemma behead_zip : forall n (a : seq A) (b : seq B),\n  size a = n.+1 -> size b = n.+1 ->\n  zip (behead a) (behead b) = behead (zip a b).\nProof.\nelim.\nby case=> // h1 [] // [].\nby move=> m IH [|h1 t1] // [|h2 t2].\nQed.\n\nLemma zip_swap : forall (a : seq A) (b : seq B),\n  zip a b = map (fun x => (x.2, x.1)) (zip b a).\nProof. elim => [ [] // | h t IH [|hd tl] //=]; by rewrite IH. Qed.\n\nLemma sumn_big_addn s : sumn s = \\sum_ ( i <- s ) i.\nProof.\nelim s => [|a l HR] /= ; first by rewrite big_nil.\nby rewrite -cat1s big_cat /= big_seq1 HR.\nQed.\n\nLemma filter_flatten T u (s : seq (seq T)) : filter u (flatten s) = flatten (map (filter u) s).\nProof.\nelim s => // hd tl HR.\nrewrite -cat1s map_cat !flatten_cat filter_cat -HR.\nf_equal ; by rewrite /flatten /= 2!cats0.\nQed.\n\nLemma drop_take_iota a b c : a <= b <= c ->\n  drop a (take b (iota 0 c)) = filter (fun n => a <= n < b) (iota 0 c).\nProof.\nmove=> /andP [Hab Hbc].\nset f := fun n => a <= n < b.\nrewrite -(subnKC Hbc) iota_add take_cat size_iota subnn take0 add0n (ltnn b) cats0 filter_cat.\nrewrite (_ : filter f (iota b (c-b)) = [::]) ; last first.\n  apply/eqP/negPn ; rewrite -has_filter ; apply/hasPn => l.\n  rewrite mem_iota (subnKC Hbc) /f negb_and => /andP [H _].\n  by rewrite -leqNgt H orbT.\nrewrite cats0 -(subnKC Hab) iota_add drop_cat size_iota subnn drop0 add0n (ltnn a) filter_cat.\nrewrite (_ : filter f (iota 0 a) = [::]) ; last first.\n  apply/eqP/negPn ; rewrite -has_filter ; apply/hasPn => l.\n  rewrite mem_iota /f negb_and add0n => /andP [_ H].\n  by rewrite -ltnNge H orTb.\nrewrite cat0s.\nsymmetry ; apply/all_filterP/allP.\nmove=> l.\nby rewrite mem_iota /f (subnKC Hab).\nQed.\n\nLemma take_take : forall (n m :nat) (s : seq A), take n (take (n + m) s) = take n s.\nProof.\nelim=> [* | n0 IH m0 z0].\n- by rewrite !take0.\n- destruct z0 => //=; by rewrite IH.\nQed.\n\nLemma take_drop_take : forall m n (z : seq A),\n  m + n <= size z -> take n (drop m (take (m + n) z)) = (drop m (take (m + n) z)).\nProof.\nelim=> [n0 z Hsz | m IH n1 [|hd tl] //=].\n- rewrite drop0 add0n take_oversize // size_take.\n  case: ifP => // {Hsz}.\n  move/negbT; by rewrite -leqNgt.\nrewrite addnC addnS => ?; by rewrite IH // addnC.\nQed.\n\nLemma zip_mask : forall bs (al : seq A) (bl : seq B),\n  zip (mask bs al) (mask bs bl) = mask bs (zip al bl).\nProof.\nelim=> // h t IH [|a1 a2] [|b1 b2] //=.\n- destruct h => //=; by case: mask.\n- destruct h => //=; by case: mask.\n- destruct h => /=; by rewrite IH.\nQed.\n\nLemma nseq_add : forall n (a : A) m, nseq (n + m) a = nseq n a ++ nseq m a.\nProof. elim=> // n0 IH a m; by rewrite addSn /= IH. Qed.\n\nVariable def : A.\n\nLemma nseq_S : forall n, nseq n.+1 def = nseq n def ++ [:: def].\nProof. by elim=> //= n <-. Qed.\n\nLemma rev_nseq : forall n, rev (nseq n def) = nseq n def.\nProof. elim=> // n H; by rewrite nseq_S rev_cat H /= -nseq_S. Qed.\n\nLemma nseq_cat : forall (l1 l2 : seq A) n n1, size l1 = n1 ->\n  l1 ++ l2 = nseq n def ->\n  l1 = nseq n1 def /\\ l2 = nseq (n - n1) def.\nProof.\nelim/last_ind => [l2 n [] // _ /= ? | h1 t1 IH l2 n []].\n- by rewrite subn0.\n- by rewrite size_rcons.\n- move=> n1; rewrite size_rcons; move=> [] Hh1.\n  rewrite cat_rcons => X.\n  destruct n.\n  * by destruct h1.\n  * have [i Hi] : exists i, n.+1 - n1 = i.+1.\n      rewrite subSn; last first.\n        match goal with | X : ?a = ?b |- _ =>\n          have {X}X : (size a = size b) by rewrite X\n        end.\n        rewrite size_nseq size_cat /= addnS Hh1 in X.\n        move/eqP : X; rewrite eqSS; move/eqP => <-.\n        by apply leq_addr.\n      by exists (n - n1).\n   case: (IH (t1 :: l2) _ _ Hh1 X) => IH1.\n   rewrite Hi; case=> IH2 IH3; subst t1.\n   rewrite nseq_S IH1 -cat_rcons cats0 subSS.\n   split; first by done.\n   rewrite subSn in Hi; last first.\n     have -> : n = (size (nseq n.+1 def)).-1.\n       by rewrite size_nseq.\n     rewrite -X size_cat /= addnS /= Hh1; by apply leq_addr.\n   by case: Hi => ->.\nQed.\n\nLemma map_nil_inv : forall (f : A -> B) (l : seq A), map f l = [::] -> l = [::].\nProof. by move=> f; case. Qed.\n\nEnd seq_ext.\n\nSection seq_eqType_ext.\n\nVariables A B : eqType.\n\nLemma mem_nseq (l : A) k (i : A) : l \\in nseq k i -> (l == i).\nProof.\nhave : nseq k i = nseq (size (nseq k i)) i by rewrite size_nseq.\nby move/all_pred1P/allP/(_ l).\nQed.\n\nLemma in_cat (s : seq A) x : x \\in s -> exists hd tl, s = hd ++ x :: tl.\nProof.\nelim: s => // h t IH; rewrite in_cons; case/orP.\n- move/eqP => ?; subst h.\n  by exists [::], t.\n- case/IH => h1 [] t1 ht1.\n  exists (h ::h1), t1 => /=.\n  congruence.\nQed.\n\nLemma rev_inj : forall (a b : seq A), rev a = rev b -> a = b.\nProof.\nelim => [ [] // hb tb | ta ha IH [| hb tb] //].\n- rewrite rev_cons -cats1; by destruct (rev tb).\n- rewrite rev_cons -cats1; by destruct (rev ha).\n- rewrite !rev_cons.\n  move/eqseqP; rewrite eqseqE eqseq_rcons.\n  case/andP; move/eqP; move/IH => ->; by move/eqP => ->.\nQed.\n\nLemma sorted_cat (l1 l2 : seq A) (Rel : @rel A) :\n  sorted Rel l1 -> sorted Rel l2 ->\n  (forall a, a \\in l1 -> forall b, b \\in l2 -> Rel a b) ->\n  sorted Rel (l1 ++ l2).\nProof.\nmove=> Hl1 Hl2 H.\ndestruct l1 => //.\nrewrite /sorted /= cat_path.\nrewrite /sorted in Hl1.\napply/andP; split => //.\ndestruct l2 => //.\nrewrite /sorted in Hl2.\nrewrite /= Hl2 andbC /=.\napply H.\nby rewrite mem_last.\nby rewrite in_cons eqxx.\nQed.\n\nLemma sorted_is_flattened leT (Htrans : transitive leT) (Hanti : antisymmetric leT) (Hrefl : reflexive leT) : forall n (lst v : seq A),\n  n = size lst -> uniq lst -> sorted leT lst ->\n  sorted leT v -> (forall i, i \\in v -> i \\in lst) ->\n  v = flatten (map (fun elt => filter (pred1 elt) v) lst).\nProof.\nelim=> /=.\n  case=> //.\n  move=> v _ _ _ Hv H.\n  destruct v => //.\n  suff : false by done.\n  move: (H s).\n  rewrite in_cons eqxx /= in_nil.\n  by apply.\nmove=> n0 IH [|hd tl] // v [lst_sz] lst_uniq lst_sorted v_sorted Hincl.\nhave X1 : v = filter (pred1 hd) v ++ filter (predC (pred1 hd)) v.\n  apply eq_sorted with leT => //.\n  - apply: sorted_cat.\n    + by apply sorted_filter.\n    + by apply sorted_filter.\n    + move=> a.\n      rewrite mem_filter.\n      case/andP => /= /eqP ?; subst hd => av b.\n      rewrite mem_filter.\n      case/andP => /= ba bv.\n      apply Hincl in bv.\n      rewrite in_cons in bv.\n      case/orP : bv.\n      * move/eqP => ?; by subst b.\n      * move=> btl.\n        rewrite /sorted in lst_sorted.\n        move: (@subseq_order_path _ _ (Htrans) a [:: b] tl).\n        rewrite /= andbC /=.\n        apply => //; by rewrite sub1seq.\n  - rewrite perm_eq_sym; by apply perm_eqlE, perm_filterC.\nrewrite {1}X1 {X1} /=.\nf_equal.\nsimpl in lst_uniq. case/andP : lst_uniq => hdtl tl_uniq.\nrewrite (IH tl (filter (predC (pred1 hd)) v) lst_sz tl_uniq).\n- f_equal.\n  apply eq_in_map => i i_tl.\n  rewrite -filter_predI.\n  apply eq_in_filter => j j_v /=.\n  case/orP : (orbN ( j == i)) => ij.\n  + rewrite ij /=.\n    apply/negP.\n    move/eqP => ?; subst j.\n    move/eqP : ij => ?; subst i.\n    by rewrite i_tl in hdtl.\n  + move/negbTE in ij;  by rewrite ij.\n- destruct tl => //=.\n  rewrite /= in lst_sorted.\n  by case/andP : lst_sorted.\n- apply sorted_filter => //.\n- move=> i.\n  rewrite mem_filter.\n  case/andP => /= Hi.\n  move/Hincl.\n  rewrite in_cons.\n  case/orP => // /eqP.\n  move=> ?; subst i.\n  by rewrite eqxx in Hi.\nQed.\n\nLemma filter_zip_L m (al : seq A) (bl : seq B) a :\n  size al = m -> size bl = m ->\n  filter (fun x => x.1 == a) (zip al bl) =\n  zip (filter (pred1 a) al) (mask (map (pred1 a) al) bl).\nProof.\nmove=> mal mbl.\nrewrite filter_mask.\nsymmetry. rewrite filter_mask zip_mask. symmetry.\nf_equal.\nelim: m al bl mal mbl a.\n  case=> //; by case.\nmove=> m IHm [|a1 a2] // [|b1 b2] // [sza2] [szb2] a /=; by rewrite IHm.\nQed.\n\nLemma filter_zip_R m (al : seq A) (bl : seq B) b :\n  size al = m -> size bl = m ->\n  filter (fun x => x.2 == b) (zip al bl) =\n  zip (mask (map (pred1 b) bl) al)\n     (filter (pred1 b) bl).\nProof.\nmove=> mal mbl.\nrewrite filter_mask.\nsymmetry. rewrite filter_mask zip_mask. symmetry.\nf_equal.\nelim: m al bl mal mbl b.\n  case=> //; by case.\nmove=> m IHm [|a1 a2] // [|b1 b2] // [sza2] [szb2] b /=; by rewrite IHm.\nQed.\n\nLemma undup_nil_inv : forall (l : seq A), undup l = [::] -> l = [::].\nProof.\nelim=> // h t IH /=.\ncase/orP : (orbN (h \\in t)) => X.\nrewrite X; move/IH => ?; by subst t.\nby rewrite (negbTE X).\nQed.\n\nLemma undup_filter : forall (P : pred B) x, undup (filter P x) = filter P (undup x).\nmove=> P; elim=> // h t IH /=.\ncase/orP : (orbN (P h)) => X.\n- rewrite X /=.\n  case/orP : (orbN (h \\in t)) => Y.\n  + rewrite Y /=.\n    have -> : h \\in filter P t by rewrite mem_filter X Y.\n    done.\n  + rewrite (negbTE Y).\n    have -> : h \\in filter P t = false by rewrite mem_filter (negbTE Y) andbC.\n    by rewrite IH /= X.\n- rewrite (negbTE X) IH.\n  case/orP : (orbN (h \\in t)) => Y.\n  + by rewrite Y.\n  + by rewrite (negbTE Y) /= (negbTE X).\nQed.\n\nLemma undup_perm : forall (f : A -> B) p h t, undup (map f p) = h :: t ->\n  exists preh : seq A,\n    exists pret : seq A,\n      perm_eq p (preh ++ pret) /\\\n      undup (map f preh) = [:: h] /\\ undup (map f pret) = t.\nProof.\nmove=> f p h t p_t.\nexists (filter (preim f [pred x | x == h]) p), (filter (preim f [pred x | x \\in t]) p).\nsplit.\n- apply/perm_eqlP => x.\n  rewrite -(@perm_filterC A (preim f [pred x | (x == h)]) p).\n  move: x.\n  apply/perm_eqlP.\n  rewrite perm_cat2l (@eq_in_filter _ _ [pred x | (f x \\in t)]) //.\n  move=> x X /=.\n  case/orP : (orbN (f x == h)) => Y.\n  + rewrite Y /=.\n    symmetry.\n    apply/negP => abs.\n    move/eqP : Y => Y; subst h.\n    have : uniq (f x :: t).\n      rewrite -p_t; by apply undup_uniq.\n    by rewrite /= abs.\n  - rewrite Y.\n    symmetry.\n    have Htmp : f x \\in map f p by apply/mapP; exists x.\n    have {Htmp}Htmp : f x \\in h :: t by rewrite -p_t mem_undup.\n    rewrite in_cons in Htmp.\n    case/orP : Htmp => [Htmp|->//].\n    by rewrite Htmp in Y.\n- split.\n  + rewrite -filter_map undup_filter p_t /= eqxx.\n    have -> : filter [pred x | x == h] t = [::]; last by done.\n    apply trans_eq with (filter pred0 t); last by apply filter_pred0.\n    apply eq_in_filter => i Hi /=.\n    apply/negP => X.\n    move/eqP : X => X; subst h.\n    have : uniq (i :: t).\n      rewrite -p_t; by apply undup_uniq.\n    rewrite /=.\n    case/andP => H1 H2.\n    by rewrite Hi in H1.\n  + rewrite -filter_map undup_filter p_t /=.\n    have -> : h \\in t = false.\n      apply/negP => X.\n      have : uniq (h :: t).\n        rewrite -p_t.\n        by apply undup_uniq.\n      by rewrite /= X.\n    apply trans_eq with (filter predT t); last by apply filter_predT.\n    by apply eq_in_filter.\nQed.\n\nEnd seq_eqType_ext.\n\nSection ordered_ranks.\n\nVariable X : finType.\n\nDefinition le_rank (x y : X) := enum_rank x <= enum_rank y.\n\nDefinition lt_rank x y := le_rank x y && (x != y).\n\nLemma lt_rank_alt x0 x1 : lt_rank x0 x1 = (enum_rank x0 < enum_rank x1).\nProof.\nrewrite /lt_rank /le_rank ltn_neqAle andbC.\napply andb_id2r => _.\ncase/orP : (orbN (x0 != x1)) => Hcase.\n- rewrite Hcase.\n  symmetry ; apply/eqP => abs ; move: Hcase.\n  apply/negP/negPn/eqP.\n  apply: enum_rank_inj => /=.\n  by apply ord_inj.\n- move/negbTE in Hcase ; rewrite Hcase ; move/negbT/negPn/eqP in Hcase.\n  symmetry ; apply/eqP ; by subst.\nQed.\n\nDefinition sort_le_rank : seq X -> seq X := sort le_rank.\n\nVariable n : nat.\n\nDefinition sort_le_rank_tuple (y : n.-tuple X) : n.-tuple X.\napply Tuple with (sort_le_rank y).\nby rewrite size_sort size_tuple.\nDefined.\n\nLemma transitive_le_rank : transitive le_rank.\nProof. rewrite /le_rank /transitive => a b c /leq_trans; by apply. Qed.\n\nLemma reflexive_le_rank : reflexive le_rank.\nProof. by rewrite /le_rank /reflexive => a. Qed.\n\nLemma antisymmetric_le_rank : antisymmetric le_rank.\nProof.\nrewrite /le_rank /antisymmetric => a b H ; apply enum_rank_inj.\nrewrite -eqn_leq in H ; by apply/eqP.\nQed.\n\nLemma total_le_rank : total le_rank.\nProof.\nrewrite /total /le_rank => a b.\ncase/orP : (orbN (enum_rank a <= enum_rank b)) ; move=> Hcase ; first by rewrite Hcase /=.\nmove/negbTE in Hcase ; rewrite Hcase /= ; move/negbT in Hcase ; rewrite -ltnNge in Hcase ; by apply ltnW.\nQed.\n\nLemma lt_le_rank_trans (u v w : X) : lt_rank u v -> le_rank v w -> lt_rank u w.\nProof.\nrewrite /lt_rank.\nmove=> /andP [Huv Diffuv] Hvw.\ncase/orP : (orbN (u != w)) => Hcase.\n- rewrite Hcase andbT.\n  apply (transitive_le_rank Huv Hvw).\n- move/negPn/eqP in Hcase.\n  subst w.\n  contradict Diffuv.\n  apply/negP/negPn/eqP.\n  apply antisymmetric_le_rank.\n  by rewrite Huv Hvw.\nQed.\n\nLemma le_lt_rank_trans (u v w : X) : le_rank u v -> lt_rank v w -> lt_rank u w.\nProof.\nrewrite /lt_rank.\nmove=> Huv /andP [Hvw Diffvw].\ncase/orP : (orbN (u != w)) => Hcase.\n- rewrite Hcase andbT.\n  apply (transitive_le_rank Huv Hvw).\n- move/negPn/eqP in Hcase.\n  subst w.\n  contradict Diffvw.\n  apply/negP/negPn/eqP.\n  apply antisymmetric_le_rank.\n  by rewrite Huv Hvw.\nQed.\n\nLemma lt_le_rank_weak (u v : X) : lt_rank u v -> le_rank u v.\nProof. by rewrite /lt_rank => /andP [H _]. Qed.\n\nLemma lt_neq_rank (u v : X) : lt_rank u v -> u != v.\nProof. by rewrite /lt_rank => /andP [_ H]. Qed.\n\nEnd ordered_ranks.\n\nSection finset_ext.\n\nVariable A : finType.\n\nLemma seq_index_enum_card : forall l (Y : {set A}) i,\n  l =i enum Y -> uniq l ->\n  i \\in Y -> (seq.index i l < #| Y |)%nat.\nProof.\nelim => [Y i Hl Hl' Hi | h t IH Y i Hl Hl' Hi /= ].\n  have {Hi}Hi : i \\in enum Y by rewrite mem_enum.\n  by rewrite -Hl in Hi.\ncase: ifP => // Hif.\n  rewrite card_gt0.\n  apply/negP.\n  move/eqP => Habs.\n  by rewrite Habs inE in Hi.\napply leq_ltn_trans with (#|Y :\\ h|); last first.\n  rewrite (cardsD1 h Y).\n  suff : h \\in Y by move=> ->; rewrite addnC addn1.\n  by rewrite -mem_enum -Hl in_cons eqxx.\napply IH.\n- move=> j.\n  move H1 : (j \\in (enum (Y :\\ h))) => [].\n    rewrite mem_enum in_setD1 in H1.\n    case/andP : H1 => H1.\n    rewrite -mem_enum -Hl in_cons.\n    case/orP => H1' //.\n    by rewrite H1' in H1.\n  move: H1.\n  rewrite mem_enum in_setD1.\n  move/negbT.\n  rewrite negb_and.\n  case/orP => [|H1].\n  - move/negPn/eqP => ?; subst j.\n      apply/negP => Habs'.\n      rewrite /= in Hl'.\n      by rewrite Habs' in Hl'.\n  - rewrite -mem_enum -Hl in H1.\n    apply/negP/negP.\n    move: H1; apply: contra.\n    rewrite in_cons.\n    move=> ->; by rewrite orbC.\n- rewrite /= in Hl'; by case/andP: Hl'.\n- apply/setD1P.\n  move/negbT in Hif.\n  split; last by done.\n  move: Hif.\n  apply contra.\n  by move/eqP => ->.\nQed.\n\nLemma sorted_enum : sorted (@le_rank A) (enum A).\nProof.\nrewrite /sorted.\nmove HA : (enum A) => Alst.\ndestruct Alst => //.\napply/(pathP s) => i Hi.\nrewrite /le_rank -HA.\ndestruct Alst => //.\nhave Hi' : (i < #|A|)%nat.\n  rewrite cardE HA.\n  by apply (ltn_trans Hi).\nrewrite -(@enum_val_nth A (xpredT) s (Ordinal Hi')).\nhave Hi'' : (i.+1 < #|A|)%nat.\n  rewrite cardE HA.\n  by apply (leq_ltn_trans Hi).\nhave -> : (nth s (s0 :: Alst) i) = (nth s (enum A) i.+1).\n  by rewrite /= HA.\nrewrite -(@enum_val_nth A (xpredT) s (Ordinal Hi'')).\nrewrite 2!enum_valK.\nby apply leqnSn.\nQed.\n\nLemma cardsltn1P (s : {set A}) :\n  (1 < #| s |) = [exists a, exists b, (a \\in s) && (b \\in s) && (a != b)].\nProof.\ncase/boolP : (s == set0) => [ /eqP -> | /set0Pn [] /= a Ha ].\n  rewrite cards0 /=.\n  apply/esym/negbTE.\n  rewrite negb_exists.\n  apply/forallP => a.\n  rewrite negb_exists.\n  apply/forallP => b.\n  by rewrite !inE.\ncase/boolP : (s :\\ a == set0) => [sa | ].\n  have Hs : s == [set a].\n    apply/eqP/setP => /= a'.\n    move/eqP/setP/(_ a') in sa.\n    rewrite !inE in sa.\n    move/negbT in sa.\n    rewrite negb_and negbK in sa.\n    case/orP : sa => sa.\n      move/eqP in sa; subst a'.\n      by rewrite inE eqxx.\n    rewrite (negbTE sa) inE.\n    apply/esym/negbTE.\n    apply/eqP => ?; subst a'.\n    by rewrite Ha in sa.\n  rewrite (eqP Hs) cards1.\n  apply/esym/negbTE.\n  rewrite negb_exists.\n  apply/forallP => b.\n  rewrite negb_exists.\n  apply/forallP => c.\n  rewrite 2!in_set1.\n  case/boolP : (b == c).\n    move/eqP => ?; subst c; by rewrite /= andbC.\n  rewrite /= andbT negb_and => bc.\n  case/boolP : (b == a) => // /eqP ?; subst b => /=; by rewrite eq_sym.\ncase/set0Pn => b Hb.\nhave -> : 1 < #| s |.\n  by rewrite (cardsD1 a s) Ha /= (cardsD1 b (s :\\ a)) Hb.\napply/esym; apply/existsP; exists a; apply/existsP; exists b.\nrewrite !inE eq_sym in Hb.\ncase/andP : Hb => -> ->; by rewrite Ha.\nQed.\n\nEnd finset_ext.\n\nLemma ord0_false : forall i : 'I_0, False.\nProof. by case=> [] []. Qed.\n\nLemma ord1 : forall i : 'I_1, i = ord0. Proof. case=> [[]] // ?; exact/eqP. Qed.\n\nModule Two_set.\n\nSection two_set.\n\nVariable X : finType.\n\nHypothesis HX : #|X| = 2%nat.\n\nDefinition val0 := enum_val (cast_ord (sym_eq HX) ord0).\n\nDefinition val1 := enum_val (cast_ord (sym_eq HX) (lift ord0 ord0)).\n\nLemma enum : enum X = val0 :: val1 :: [::].\nProof.\napply (@eq_from_nth _ val0); first by rewrite -cardE HX.\nmove=> i Hi.\ndestruct i.\n  by rewrite [X in _ = X]/= {2}/val0 (enum_val_nth val0).\ndestruct i; last first.\n  rewrite -cardE HX in Hi.\n  by destruct i.\nby rewrite [X in _ = X]/= {1}/val1 (enum_val_nth val0).\nQed.\n\nLemma val0_neq_val1 : val0 != val1.\nProof. rewrite /val0 /val1. apply/eqP. by move/enum_val_inj. Qed.\n\nLemma neq_val0_val1 : forall x, x != val0 -> x == val1.\nProof.\nmove=> x xi.\nhave : x \\in X by done.\nrewrite -mem_enum enum !inE.\ncase/orP => // abs.\nby rewrite abs in xi.\nQed.\n\nEnd two_set.\n\nEnd Two_set.\n\nNotation \"t '\\_' i\" := (tnth t i) (at level 9) : tuple_ext_scope.\n\nLocal Open Scope tuple_ext_scope.\n\nSection tuple_ext.\n\nVariable A : Type.\n\nLemma tcast_take_simpl n m k (H : minn n k = m) (nk : n = k) (t v : k.-tuple A) :\n  tcast H [tuple of take n t] = tcast H [tuple of take n v] -> t = v.\nProof.\nsubst m => /=.\nsubst n; case => /= Htv.\napply eq_from_tnth => i.\nby rewrite (tnth_nth t\\_i) [in X in _ = X](tnth_nth t\\_i) -(@nth_take k) // -[in X in _ = X](@nth_take k) // Htv.\nQed.\n\nEnd tuple_ext.\n\nSection tuple_ext_finType.\n\nVariables A B : finType.\nVariable n : nat.\n\nLemma tnth_zip_1 (x1 : n.-tuple A) (x2 : n.-tuple B) i:\n  (tnth [tuple of zip x1 x2] i).1 = tnth x1 i.\nProof.\nrewrite /tnth.\nset def := tnth_default _ _.\ndestruct def as [def1 def2].\nrewrite nth_zip /=; last by rewrite !size_tuple.\napply set_nth_default.\nby rewrite size_tuple.\nQed.\n\nLemma tnth_zip_2 (x1 : n.-tuple A) (x2 : n.-tuple B) i:\n  (tnth [tuple of zip x1 x2] i).2 = tnth x2 i.\nProof.\nrewrite /tnth.\nset def := tnth_default _ _.\ndestruct def as [def1 def2].\nrewrite nth_zip /=; last by rewrite !size_tuple.\napply set_nth_default.\nby rewrite size_tuple.\nQed.\n\nLemma thead_tuple1 : forall (i : 1.-tuple A), [tuple thead i] = i.\nProof. move=> [ [|h []] H] //. by apply val_inj. Qed.\n\nLemma eq_tcast (t : {:n.-tuple A}) m (t' : {:m.-tuple A}) (H' : m = n) :\n  tval t = tval t' -> t = tcast H' t'.\nProof.\nsubst m.\nrewrite tcast_id.\nmove=> tt'.\nby apply val_inj.\nQed.\n\nLemma eq_tcast2 (t : seq A) m (t' : {:m.-tuple A}) (H : m = n) :\n  t = tval t' -> t = tval (tcast H t').\nProof. subst m. by rewrite tcast_id. Qed.\n\nEnd tuple_ext_finType.\n\nDefinition tbehead (n : nat) (T : Type) (t : (n.+1).-tuple T) : n.-tuple T :=\n  [tuple of behead t].\n\nSection perm_tuples.\n\nLocal Open Scope nat_scope.\nLocal Open Scope group_scope.\n\nVariables A : finType.\nVariable n : nat.\nVariable s : 'S_n.\n\nDefinition perm_tuple (t : n.-tuple A) : n.-tuple A := [tuple (t \\_ (s i)) | i < n].\nDefinition perm_tuple_set (E : {set n.-tuple A}) := perm_tuple @: E.\n\nEnd perm_tuples.\n\nSection perm_tuples_facts.\n\nVariable A : finType.\n\nLocal Open Scope group_scope.\n\nLemma perm_tuple_id {m} (b : m.-tuple A) : perm_tuple 1 b = b.\nProof.\napply eq_from_tnth => i.\nby rewrite /perm_tuple /= tnth_map /= perm1 tnth_ord_tuple.\nQed.\n\nVariable n : nat.\n\nLemma perm_tuple_comp (s1 s2 : 'S_n) (b : n.-tuple A) :\n  perm_tuple s1 (perm_tuple s2 b) = perm_tuple (s1 * s2) b.\nProof.\napply eq_from_tnth => i.\nby rewrite /perm_tuple !tnth_map /= tnth_ord_tuple permM.\nQed.\n\nLemma perm_tuple_inj (s : 'S_n) : injective (@perm_tuple A n s).\nProof.\nrewrite /injective.\nmove=> a b H.\nhave H2 : perm_tuple 1 a = perm_tuple 1 b.\n- rewrite -(mulVg s).\n  rewrite -!perm_tuple_comp.\n  f_equal ; apply H.\nrewrite !perm_tuple_id in H2 ; apply H2.\nQed.\n\nLemma perm_tuple0 : forall (u : 'S_0) (t : 0.-tuple A), perm_tuple u t = t.\nProof.\nmove=> u t.\nrewrite (tuple0 t).\nhave -> : u = 1%g.\n  apply/permP => /= x.\n  suff : False by done.\n  by move/ord0_false in x.\nby rewrite perm_tuple_id.\nQed.\n\nVariable B : finType.\n\nLemma zip_perm_tuple (ta : n.-tuple A) (tb : n.-tuple B) (s : 'S_n) :\n  zip_tuple (perm_tuple s ta) (perm_tuple s tb) = perm_tuple s (zip_tuple ta tb).\nProof.\napply eq_from_tnth.\ncase.\ndestruct n => //.\ncase=> [Hi | i Hi].\n  rewrite (tnth_nth (thead ta, thead tb)) (tnth_nth (thead (zip_tuple ta tb))).\n  rewrite /= enum_ordS /= (tnth_nth (thead ta, thead tb)) /= nth_zip; last\n    by rewrite (size_tuple ta) (size_tuple tb).\n  by rewrite (tnth_nth (thead ta)) /= (tnth_nth (thead tb)) /=.\nrewrite (tnth_nth (thead ta, thead tb)) (tnth_nth (thead (zip_tuple ta tb))) /= enum_ordS /=.\nrewrite ltnS in Hi.\nrewrite nth_zip; last by rewrite 4!size_map size_enum_ord.\nsymmetry.\nrewrite (nth_map ord0); last by rewrite size_map size_enum_ord.\nrewrite (tnth_nth (thead ta, thead tb)) /zip_tuple /=.\nrewrite nth_zip; last by rewrite (size_tuple ta) (size_tuple tb).\nsymmetry.\nrewrite (nth_map ord0); last by rewrite size_map size_enum_ord.\nrewrite (nth_map ord0); last by rewrite size_map size_enum_ord.\nby rewrite (tnth_nth (thead ta)) (tnth_nth (thead tb)).\nQed.\n\nEnd perm_tuples_facts.\n\nLemma tcast2tval (T : Type) (m n0 : nat) (H : m = n0) : forall (v : m.-tuple T) w,\n  tcast H v = w -> tval v = tval w.\nProof. subst n0. by move=> [v Hv] [w Hw] <- /=. Qed.\n", "meta": {"author": "johnbender", "repo": "shannon", "sha": "552c66f7c76ad687430f4fb8122a2a2b94b741ee", "save_path": "github-repos/coq/johnbender-shannon", "path": "github-repos/coq/johnbender-shannon/shannon-552c66f7c76ad687430f4fb8122a2a2b94b741ee/ssr_ext.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7003162535935887}}
{"text": "Require Import HoTT.\nRequire Import UnivalenceAxiom.\n\nFrom GCTT Require Import path_lemmas.\n\n(** We definine the type of monoidal 1-Types (this corresponds to a monoidal category)*)\nDefinition associative {A : Type}  (m : A-> A -> A) := forall (a b c: A),  m (m a b) c = m a (m b c).\nDefinition left_identity_mult {A : Type} (m : A->A->A) (e : A) := forall a : A, m e a = a.\nDefinition right_identity_mult {A : Type} (m : A->A->A) (e : A) := forall a : A, m a e = a.\n\n(* Unneccesary but perhaps easier to just assume *)\nDefinition coherence_triangle1 {A : Type} {m : A -> A -> A} {e : A}\n           (assoc : associative m) (lid : left_identity_mult m e)  :=\n  forall a b : A,\n    ap (fun x => m x b) (lid a) = assoc e a b @ lid (m a b).\n\nDefinition coherence_triangle2 {A : Type} {m : A -> A -> A} {e : A}\n           (assoc : associative m) (lid : left_identity_mult m e) (rid : right_identity_mult m e) :=\n  forall a b : A,\n    ap (fun c => m c b) (rid a) = assoc a e b @ ap (m a) (lid b).\n\nDefinition coherence_pentagon {A : Type} {m : A -> A -> A} (assoc : associative m) :=\n  forall a b c d: A,\n    ap (fun x => m x d) (assoc a b c) =\n    assoc (m a b) c d @ assoc a b (m c d) @ (ap (m a) (assoc b c d))^ @ (assoc a (m b c) d)^.\n\n\nRecord Monoidal_1Type : Type := { montype_type :> 1-Type;\n                                  montype_mult  : montype_type->montype_type->montype_type;\n                                  montype_id : montype_type;\n                                  montype_assoc : associative montype_mult;\n                                  montype_lid : left_identity_mult montype_mult montype_id ;\n                                  montype_rid : right_identity_mult montype_mult montype_id ;\n                                  montype_triangle1 : coherence_triangle1 montype_assoc montype_lid ;\n                                  montype_triangle2 : coherence_triangle2 montype_assoc montype_lid montype_rid ;\n                                  montype_pentagon : coherence_pentagon montype_assoc\n                                }.\n\nGlobal Arguments montype_mult {M} a b : rename.\nGlobal Arguments montype_id {M} : rename.\nGlobal Arguments montype_assoc {M} a b c : rename.\nGlobal Arguments montype_lid {M} a : rename.\nGlobal Arguments montype_rid {M} a : rename.\n\n\nInfix \"⊗\" := montype_mult (at level 50,no associativity).\n\nDefinition left_faithful {A B : Type} (m : A -> B -> B) :=\n  forall (s t : A) (p q : s = t) (b : B),\n    ap (fun x => m x b) p = ap (fun x => m x b) q -> p = q.\n\n\n\nSection Monoidal_Map.\n  (** Definining monoidal maps.  *)\n  Record Monoidal_Map (M N : Monoidal_1Type) :=\n    {montype_map :> M -> N;\n     montype_map_mult (a b : M) : montype_map (a ⊗ b) = (montype_map a) ⊗ (montype_map b) ;\n     montype_map_id : montype_map (montype_id) = montype_id;\n     montype_map_assoc (a b c : M) :\n       ap montype_map (montype_assoc a b c) =\n       montype_map_mult (a ⊗ b) c @ ap (fun x => x ⊗ (montype_map c)) (montype_map_mult a b) @\n                        montype_assoc (montype_map a) (montype_map b) (montype_map c) @\n                        (ap (montype_mult (montype_map a)) (montype_map_mult b c))^\n       @ (montype_map_mult a (b ⊗ c))^ ;\n     montype_map_lid (x : M)\n     : ap montype_map (montype_lid x) =\n       montype_map_mult montype_id x @\n                        ap (fun s => s ⊗ montype_map x) montype_map_id @ montype_lid (montype_map x);\n     montype_map_rid (x : M)\n     : ap montype_map (montype_rid x) =\n       montype_map_mult x montype_id @ ap (montype_mult (montype_map x)) montype_map_id\n                        @ montype_rid (montype_map x) }.\n  \n  Global Arguments montype_map_mult {M N} F a b : rename.\n  Global Arguments montype_map_id {M N} F : rename.\n  Global Arguments montype_map_assoc {M N} F a b c : rename.\n  Global Arguments montype_map_lid {M N} F a : rename.\n  Global Arguments montype_map_rid {M N} F a : rename.\n\n  Definition monoidal_map_id (M : Monoidal_1Type) : Monoidal_Map M M.\n  Proof.\n    srapply (Build_Monoidal_Map M M idmap); try reflexivity.\n    - intros. simpl.\n      rewrite ap_idmap. repeat rewrite concat_p1. apply inverse. apply concat_1p.\n  Defined.\n  \n  Definition monoidal_map_compose (M N O : Monoidal_1Type) :\n    Monoidal_Map M N -> Monoidal_Map N O -> Monoidal_Map M O.\n  Proof.\n    intros F G.\n    srapply @Build_Monoidal_Map.\n    - exact (G o F).\n    - intros a b.\n      refine (ap G (montype_map_mult F a b) @ montype_map_mult G _ _).\n    - refine (ap G (montype_map_id F) @ montype_map_id G).\n    - intros.\n      refine (ap_compose F G _ @ _).\n      refine (ap (ap G) (montype_map_assoc F a b c) @ _).\n      repeat rewrite ap_pp.\n      rewrite (montype_map_assoc G (F a) (F b) (F c)). \n      repeat rewrite (concat_pp_p). apply whiskerL.\n      repeat rewrite <- (ap_compose G).\n      rewrite ap_V. rewrite ap_V. \n      rewrite <- (ap_compose (montype_mult (F a)) G (montype_map_mult F b c)).\n      rewrite <- (ap_compose (fun x : N => x ⊗ F c) G).\n      rewrite inv_pp. rewrite inv_pp. \n      \n      repeat rewrite concat_p_pp.\n      assert (H : (ap (fun x : N => G (x ⊗ F c)) (montype_map_mult F a b) @ montype_map_mult G (F a ⊗ F b) (F c)) =\n                  (montype_map_mult G (F (a ⊗ b)) (F c) @ ap (fun x : N => G x ⊗ G (F c)) (montype_map_mult F a b))).\n      { destruct (montype_map_mult F a b). hott_simpl. }\n      rewrite H. repeat rewrite concat_pp_p. repeat (apply whiskerL).\n      repeat rewrite concat_p_pp. apply whiskerR.\n      destruct (montype_map_mult F b c). hott_simpl.\n    - intro x.\n      refine (ap_compose F G _ @ _).\n      refine ( ap (ap G) (montype_map_lid F x) @ _).\n      refine (ap_pp G _ _ @ _).\n      refine (ap (fun p => p @ ap G (montype_lid (F x))) (ap_pp G _ _) @ _).\n      refine (whiskerL _ (montype_map_lid G (F x)) @ _).\n      repeat refine (concat_p_pp _ _ _ @ _). apply whiskerR.\n      repeat refine (concat_pp_p _ _ _ @ _).\n      repeat refine (_ @ concat_p_pp _ _ _). apply whiskerL.\n      refine (_ @ whiskerL _ (ap_pp (fun s : O => s ⊗ G (F x)) _ _)^).\n      repeat refine (_ @ concat_pp_p _ _ _).\n      repeat refine (concat_p_pp _ _ _ @ _). apply whiskerR.\n      refine (whiskerR (ap_compose _ G (montype_map_id F))^ _ @ _).\n      refine (_ @ whiskerL _ (ap_compose G _ (montype_map_id F))).\n      destruct (montype_map_id F). cbn.\n      exact (concat_1p _ @ (concat_p1 _)^).\n    - intro x.\n      refine (ap_compose F G _ @ _ ).\n      refine ( ap (ap G) (montype_map_rid F x) @ _).\n      refine (ap_pp G _ _ @ _).\n      refine (ap (fun p => p @ ap G (montype_rid (F x))) (ap_pp G _ _) @ _).\n      refine (whiskerL _ (montype_map_rid G (F x)) @ _).\n      repeat refine (concat_p_pp _ _ _ @ _). apply whiskerR.\n      repeat refine (concat_pp_p _ _ _ @ _).\n      repeat refine (_ @ concat_p_pp _ _ _). apply whiskerL.\n      refine (_ @ whiskerL _ (ap_pp (fun s : O => G (F x) ⊗ s) _ _)^).\n      repeat refine (_ @ concat_pp_p _ _ _).\n      repeat refine (concat_p_pp _ _ _ @ _). apply whiskerR.\n      refine (whiskerR (ap_compose _ G (montype_map_id F))^ _ @ _).\n      refine (_ @ whiskerL _ (ap_compose G _ (montype_map_id F))).\n      destruct (montype_map_id F). cbn.\n      exact (concat_1p _ @ (concat_p1 _)^).\n  Defined.\n  \n\n  (** Given a 1-Type X, the type X->X is a monoidal 1-type *)\n  Definition endomorphism (X : 1-Type) : Monoidal_1Type.\n  Proof.\n    srapply @Build_Monoidal_1Type.\n    - apply (BuildTruncType 1 (X -> X)).\n    - intros f g. exact (f o g).\n    - cbn. exact idmap.\n    - cbn. unfold associative. reflexivity.\n    - cbn. unfold left_identity_mult. reflexivity.\n    - cbn. unfold right_identity_mult. reflexivity.\n    - unfold coherence_triangle1. cbn. reflexivity.\n    - unfold coherence_triangle2. cbn. reflexivity.\n    - unfold coherence_pentagon. cbn. reflexivity.\n  Defined.\n  \n  Definition to_endomorphism (M : Monoidal_1Type) : Monoidal_Map M (endomorphism M).\n  Proof.    \n    srapply @Build_Monoidal_Map.\n    - simpl. apply montype_mult.\n    - intros a b. apply path_arrow. intro c.\n      apply montype_assoc.\n    - apply path_arrow. apply montype_lid.\n    - intros a b c. simpl. hott_simpl.\n      transitivity (path_arrow _ _ (fun d : M => ap (fun x : M => x ⊗ d) (montype_assoc a b c)));\n        simpl.     \n      { destruct (montype_assoc a b c). simpl. apply inverse. apply path_forall_1. }      \n      rewrite (path_forall _ _ (montype_pentagon M a b c) ).\n      repeat rewrite path_arrow_pp.\n      rewrite path_arrow_V. rewrite path_arrow_V.\n      apply whiskerR. apply concat2.\n      + apply whiskerL.\n        apply inverse.\n        refine (ap_functor_arrow _ idmap (montype_mult (a ⊗ b)) (fun x : M => a ⊗ (b ⊗ x)) (fun c0 : M => montype_assoc a b c0) @ _).\n        apply (ap (path_arrow (fun b0 : M => (a ⊗ b) ⊗ (c ⊗ b0)) (fun b0 : M => a ⊗ (b ⊗ (c ⊗ b0))))).\n        apply path_forall. intro m.\n        apply ap_idmap.\n      + apply (ap inverse).\n        apply inverse.\n        refine (ap_functor_arrow idmap _ (montype_mult (b ⊗ c)) (fun x : M => b ⊗ (c ⊗ x)) (fun c0 : M => montype_assoc b c c0) ).        \n    - intro a. simpl. hott_simpl.\n      transitivity (path_arrow _ _ (fun b : M => ap (fun x : M => x ⊗ b) (montype_lid a))).\n      { simpl. destruct (montype_lid a). simpl. apply inverse. apply path_forall_1. }\n      (* Check (montype_triangle1 M a). *)\n      rewrite (path_forall _ _ (montype_triangle1 M a)).\n      repeat rewrite path_arrow_pp.\n      apply whiskerL.\n      apply inverse.\n      refine (ap_functor_arrow (montype_mult a) idmap (montype_mult montype_id) idmap montype_lid @ _).\n      apply (ap (path_arrow (fun b : M => montype_id ⊗ (a ⊗ b)) (fun b : M => a ⊗ b))).\n      apply path_forall. intro b. apply ap_idmap.\n    - intro a. simpl. hott_simpl.\n      transitivity (path_arrow _ _ (fun b : M => ap (fun x : M => x ⊗ b) (montype_rid a))).\n      { simpl. destruct (montype_rid a). simpl. apply inverse. apply path_forall_1. }\n      (* Check (montype_triangle2 M a). *)\n      rewrite (path_forall _ _ (montype_triangle2 M a)).\n      repeat rewrite path_arrow_pp.\n      apply whiskerL.\n      apply inverse.\n      refine (ap_functor_arrow _ _ (montype_mult montype_id) idmap montype_lid ).\n  Defined.\n\n  \n  (* Definition old_act_on_prod (M : Monoidal_1Type) (X Y: 1-Type) (a1 : Monoidal_Map M (endomorphism X)) (a2 : Monoidal_Map M (endomorphism Y)): *)\n  (*   Monoidal_Map M (endomorphism (BuildTruncType 1 (X*Y))). *)\n  (* Proof. *)\n  (*   srapply @Build_Monoidal_Map. *)\n  (*   - simpl. intro s. *)\n  (*     apply (functor_prod (a1 s) (a2 s)). *)\n  (*   - intros s t. simpl. *)\n  (*     apply (ap011 functor_prod (montype_map_mult a1 _ _) (montype_map_mult a2 _ _)). *)\n  (*   - apply (ap011 functor_prod (montype_map_id a1) (montype_map_id a2)). *)\n  (*   - intros s t u. simpl. *)\n  (*     transitivity (ap011 (functor_prod) (ap a1 (montype_assoc s t u)) (ap a2 (montype_assoc s t u))). *)\n  (*     { destruct (montype_assoc s t u). reflexivity. } hott_simpl. *)\n  (*     transitivity (ap011 functor_prod *)\n  (*                         (((montype_map_mult a1 (s ⊗ t) u @ ap (fun x : (X -> X) => x o (a1 u)) (montype_map_mult a1 s t)) *)\n  (*                             @ (ap (montype_mult (a1 s)) (montype_map_mult a1 t u))^) @ (montype_map_mult a1 s (t ⊗ u))^) *)\n  (*                         (((montype_map_mult a2 (s ⊗ t) u @ ap (fun y : (Y -> Y) => y o (a2 u)) (montype_map_mult a2 s t)) *)\n  (*                             @ (ap (montype_mult (a2 s)) (montype_map_mult a2 t u))^) @ (montype_map_mult a2 s (t ⊗ u))^)). *)\n  (*     { apply (ap011 (ap011 functor_prod)). *)\n  (*       - refine (montype_map_assoc a1 s t u @ _). simpl. hott_simpl. *)\n  (*       - refine (montype_map_assoc a2 s t u @ _). simpl. hott_simpl. } *)\n  (*     refine (ap011_pp_pp functor_prod _ _ _ _ @ _). *)\n  (*     refine (whiskerR (ap011_pp_pp functor_prod _ _ _ _ ) _ @ _). *)\n  (*     refine (whiskerR (whiskerR (ap011_pp_pp functor_prod _ _ _ _ ) _) _ @ _). *)\n  (*     apply concat2. *)\n  (*     + apply concat2. *)\n  (*       * apply whiskerL. *)\n  (*         cut (forall (f1 f2 : X -> X) (g1 g2 : Y -> Y) (p : f1 = f2) (q : g1 = g2), *)\n  (*                 ap011 functor_prod (ap (fun f => f o (a1 u)) p) (ap (fun g => g o (a2 u)) q) = *)\n  (*                 ap (fun f => f o (functor_prod (a1 u) (a2 u))) (ap011 functor_prod p q)). *)\n  (*         { intro H. apply H. } *)\n  (*           by path_induction. *)\n  (*       *  simpl. *)\n  (*          cut (forall (f1 f2 : X -> X) (g1 g2 : Y -> Y) (p : f1 = f2) (q : g1 = g2), *)\n  (*                  ap011 functor_prod (ap (fun f => (a1 s) o f) p)^ (ap (fun g => (a2 s) o g) q)^ = *)\n  (*                  (ap (fun f => (functor_prod (a1 s) (a2 s)) o f) (ap011 functor_prod p q))^). *)\n  (*          { intro H. apply H. } *)\n  (*            by path_induction.         *)\n  (*     + cut (forall (f1 f2 : X -> X) (g1 g2 : Y -> Y) (p : f1 = f2) (q : g1 = g2), *)\n  (*               ap011 functor_prod p^ q^ = (ap011 functor_prod p q)^). *)\n  (*       { intro H. apply H. } *)\n  (*         by path_induction.         *)\n  (*   - intro s. *)\n  (*     transitivity (ap011 functor_prod (ap a1 (montype_lid s)) (ap a2 (montype_lid s))). *)\n  (*     { destruct (montype_lid s). reflexivity. } *)\n  (*     transitivity (ap011 functor_prod *)\n  (*                         ((montype_map_mult a1 montype_id s @ ap (fun f => f o (a1 s)) (montype_map_id a1))) *)\n  (*                         ((montype_map_mult a2 montype_id s @ ap (fun f => f o (a2 s)) (montype_map_id a2)))). *)\n  (*     { apply (ap011 (ap011 functor_prod)). *)\n  (*       - refine (montype_map_lid a1 s @ _). hott_simpl. *)\n  (*       - refine (montype_map_lid a2 s @ _). hott_simpl. } *)\n  (*     refine (ap011_pp_pp functor_prod _ _ _ _ @ _). simpl. hott_simpl. apply whiskerL. *)\n  (*     cut (forall (f1 f2 : X -> X) (g1 g2 : Y -> Y) (p : f1 = f2) (q : g1 = g2), *)\n  (*             ap011 functor_prod (ap (fun f => f o (a1 s)) p) (ap (fun g => g o (a2 s)) q) = *)\n  (*             ap (fun f => f o (functor_prod (a1 s) (a2 s))) (ap011 functor_prod p q)). *)\n  (*     { intro H.  apply (H _ _ _ _ (montype_map_id a1) (montype_map_id a2)). } *)\n  (*       by path_induction. *)\n  (*   - intro s. *)\n  (*     transitivity (ap011 functor_prod (ap a1 (montype_rid s)) (ap a2 (montype_rid s))). *)\n  (*     { destruct (montype_rid s). reflexivity. } *)\n  (*     transitivity (ap011 functor_prod *)\n  (*                         ((montype_map_mult a1 s montype_id @ ap (montype_mult (a1 s)) (montype_map_id a1))) *)\n  (*                         ((montype_map_mult a2 s montype_id @ ap (montype_mult (a2 s)) (montype_map_id a2)))). *)\n  (*     { apply (ap011 (ap011 functor_prod)). *)\n  (*       - refine (montype_map_rid a1 s @ _). hott_simpl. *)\n  (*       - refine (montype_map_rid a2 s @ _). hott_simpl. } *)\n  (*     refine (ap011_pp_pp functor_prod _ _ _ _ @ _). simpl. hott_simpl. apply whiskerL. *)\n  (*     cut (forall (f1 f2 : X -> X) (g1 g2 : Y -> Y) (p : f1 = f2) (q : g1 = g2), *)\n  (*             ap011 functor_prod (ap (fun f => (a1 s) o f) p) (ap (fun g => (a2 s) o g) q) = *)\n  (*             ap (fun f => (functor_prod (a1 s) (a2 s)) o f) (ap011 functor_prod p q)). *)\n  (*     { intro H.  apply (H _ _ _ _ (montype_map_id a1) (montype_map_id a2)). } *)\n  (*       by path_induction. *)\n  (* Defined. *)\nEnd Monoidal_Map.\n\nSection Monoidal_Action.\n  (** We could define monoidal actions to be [Monoidal_Map M (endomorphism X)],\nbut the following definition is easier to work with.*)\n\n  Record monoidal_action (M : Monoidal_1Type) (X : 1-Type) :=\n    { act :> M -> X -> X;\n      montype_act_mult : forall (s t : M) (x : X), act (s ⊗ t) x = act s (act t x) ;\n      montype_act_id : forall x : X, act montype_id x = x;\n      montype_act_triangle1 : forall (a : M) (x : X),\n          ap (fun m : M => act m x) (montype_lid a) = montype_act_mult montype_id a x @ montype_act_id (act a x);\n      montype_act_triangle2 : forall (a : M) (x : X),\n          ap (fun m : M => act m x) (montype_rid a) = montype_act_mult a montype_id x @ ap (fun y : X => act a y) (montype_act_id x);\n      montype_act_pentagon : forall (a b c : M) (x : X),\n          ap (fun m : M => act m x) (montype_assoc a b c) =\n          montype_act_mult (a ⊗ b) c x @ montype_act_mult a b (act c x) @ (ap (act a) (montype_act_mult b c x))^ @ (montype_act_mult a (b ⊗ c) x)^ }.\n\n  Global Arguments montype_act_mult {M} {X} a s t x : rename.\n  Global Arguments montype_act_id {M} {X} a x : rename.\n  \n\n  Definition action_on_path {M} {X} (a : monoidal_action M X) {s t : M} (x : X) (p : s = t)\n    := ap (fun s => a s x) p.\n\n  (** A monoidal 1-type acts on itself per definition.  *)\n  Definition act_on_self (M : Monoidal_1Type) : monoidal_action M M.\n  Proof.\n    srapply @Build_monoidal_action.\n    - exact montype_mult.\n    - apply montype_assoc.\n    - apply montype_lid.\n    - apply montype_triangle1.\n    - apply montype_triangle2.\n    - apply montype_pentagon.\n  Defined.\n\n  Definition endomorphism_to_action (M : Monoidal_1Type) (X : 1-Type)\n             (F : Monoidal_Map M (endomorphism X))\n    : monoidal_action M X.\n  Proof.\n    srapply @Build_monoidal_action.\n    - exact F.\n    - intros s t. apply ap10.\n      apply (montype_map_mult F).\n    - apply ap10.\n      apply (montype_map_id F).\n    - intros a x.      \n      refine (ap_compose F (fun f => f x) (montype_lid a) @ _).\n      rewrite montype_map_lid.\n      repeat rewrite ap_pp. simpl. rewrite concat_p1.\n      rewrite <- (ap_compose (fun (s : X -> X) (x0 : X) => s (F a x0)) (fun f : X -> X => f x) (montype_map_id F)). simpl.\n      rewrite ap_apply_l. rewrite ap_apply_l. reflexivity.\n    - intros a x.\n      refine (ap_compose F (fun f => f x) (montype_rid a) @ _).\n      rewrite montype_map_rid.\n      repeat rewrite ap_pp. simpl. rewrite concat_p1.\n      rewrite ap_apply_l. apply whiskerL.\n      rewrite ap_apply_l.\n      apply (ap10_ap_postcompose (F a) (montype_map_id F) x).\n    - intros a b c x. simpl.\n      refine (ap_compose F (fun f => f x) (montype_assoc a b c) @ _).\n      rewrite montype_map_assoc.\n      repeat rewrite ap_pp. simpl. rewrite concat_p1.\n      rewrite ap_apply_l. rewrite ap_apply_l. rewrite ap_apply_l. rewrite ap_apply_l.\n      apply concat2.\n      { apply concat2.\n        { apply whiskerL.\n          apply (ap10_ap_precompose (F c) (montype_map_mult F a b) x ). }\n        rewrite ap10_V. apply (ap inverse).\n        apply (ap10_ap_postcompose (F a) (montype_map_mult F b c) x). }\n      apply (ap10_V (montype_map_mult F a (b ⊗ c)) x).\n  Defined.\n\n  Definition monmap_to_action {M : Monoidal_1Type} {X : Monoidal_1Type} (F : Monoidal_Map M X) :\n    monoidal_action M X.\n  Proof.\n    apply endomorphism_to_action.\n    apply (monoidal_map_compose M X (endomorphism X) F).\n    apply (to_endomorphism).\n  Defined.\n\n  Definition act_on_prod (M : Monoidal_1Type) (X Y: 1-Type)\n             (act1 : monoidal_action M X) (act2 : monoidal_action M Y) :\n    monoidal_action M (BuildTruncType 1 (X*Y)).\n  Proof.\n    srapply @Build_monoidal_action; simpl.\n    - intro s.\n      apply (functor_prod (act1 s) (act2 s)).\n    - simpl. intros s t x.\n      apply path_prod; apply montype_act_mult.\n    - simpl. intro x.\n      apply path_prod; apply montype_act_id.\n    - simpl. intros s x.\n      transitivity (path_prod (_,_) (_,_) (ap (fun m : M => act1 m (fst x)) (montype_lid s)) (ap (fun m : M => act2 m (snd x)) (montype_lid s))).\n      { destruct (montype_lid s). reflexivity. }\n      refine (_ @ path_prod_pp _ _ _ _ _ _ _).      \n      apply (ap011 (path_prod _ _)); apply montype_act_triangle1.\n    - intros s x. simpl.\n      transitivity (path_prod (_,_) (_,_) (ap (fun m : M => act1 m (fst x)) (montype_rid s)) (ap (fun m : M => act2 m (snd x)) (montype_rid s))).\n      { destruct (montype_rid s). reflexivity. }\n      refine (_ @ whiskerL _ (ap_functor_prod _ _ _ _ _ _)^).      \n      refine (_ @ path_prod_pp _ _ _ _ _ _ _).\n      apply (ap011 (path_prod _ _)); apply montype_act_triangle2.\n    - intros a b c x. simpl.\n      transitivity (path_prod (_,_) (_,_)\n                              (ap (fun m : M => act1 m (fst x)) (montype_assoc a b c)) (ap (fun m : M => act2 m (snd x)) (montype_assoc a b c))).\n      { destruct (montype_assoc a b c). reflexivity. }\n      rewrite (ap_functor_prod).\n      repeat rewrite <- path_prod_VV.\n      repeat rewrite <- path_prod_pp.\n      apply (ap011 (path_prod _ _)); apply montype_act_pentagon.\n  Defined.\n\n  (* Definition act_from_monmap (M X : Monoidal_1Type) (F : Monoidal_Map M X) : *)\n  (*   monoidal_action M X. *)\n  (* Proof. *)\n  (*   srapply @Build_monoidal_action. *)\n  (*   - intros m x. exact ((F m) ⊗ x). *)\n  (*   - intros s t x. simpl. *)\n  (*     refine (ap (fun y => y ⊗ x) (montype_map_mult F s t) @ _). *)\n  (*     apply montype_assoc. *)\n  (*   - intro x. simpl. *)\n  (*     exact (ap (fun y => y ⊗ x) (montype_map_id F) @ (montype_lid x)). *)\n  (*   - intros a x. simpl. *)\n  (*     refine (ap_compose F (fun y : X => y ⊗ x) (montype_lid a) @ _). *)\n  (*     rewrite montype_map_lid. *)\n  (*     repeat rewrite ap_pp. *)\n  (*     rewrite montype_triangle1. *)\n  (*     repeat rewrite concat_p_pp. apply whiskerR. *)\n  (*     repeat rewrite concat_pp_p. apply whiskerL. *)\n  (*     rewrite <- (ap_compose (fun s : X => s ⊗ F a) (fun y : X => y ⊗ x)). *)\n  (*     destruct (montype_map_id F). simpl. *)\n  (*     destruct (montype_assoc (F montype_id) (F a) x). reflexivity. *)\n  (*   - intros a x. simpl. *)\n  (*     refine (ap_compose F (fun y : X => y ⊗ x) (montype_rid a) @ _). *)\n  (*     rewrite montype_map_rid. *)\n  (*     repeat rewrite ap_pp. *)\n  (*     rewrite montype_triangle2. *)\n  (*     repeat rewrite concat_p_pp. apply whiskerR. *)\n  (*     repeat rewrite concat_pp_p. apply whiskerL. *)\n  (*     rewrite <- (ap_compose (montype_mult (F a)) (fun y : X => y ⊗ x)). *)\n  (*     destruct (montype_map_id F). simpl. *)\n  (*     destruct (montype_assoc (F a) (F montype_id)  x). reflexivity. *)\n  (*   - intros a b c x. simpl. *)\n  (*     refine (ap_compose F (fun y : X => y ⊗ x) (montype_assoc a b c) @ _). *)\n  (*     rewrite montype_map_assoc. *)\n  (*     repeat rewrite ap_pp. *)\n  (*     rewrite montype_pentagon. *)\n  (*     repeat rewrite concat_pp_p. apply whiskerL. *)\n  (*     repeat rewrite concat_p_pp. apply whiskerR. *)\n  (*     refine (ap_pp _ _ _ @ _). *)\n  (*     refine (montype_triangle1 M _ _ @ _). *)\nEnd Monoidal_Action.\n\n\nSection Symmetric_Monoidal_1Type.\n  (** Define symmetric monoidal 1-type.  *)\n  \n  Definition symmetric {A : Type} (m : A->A->A) := forall a b : A, m a b = m b a.\n  Definition coherence_hexagon {A : Type} {m : A -> A -> A} (assoc : associative m)\n             (symm : symmetric m) :=\n    forall (a b c : A),\n      ap (fun x : A => m x c) (symm a b) =\n      assoc a b c @ symm a (m b c) @ assoc b c a @ (ap (m b) (symm a c))^ @ (assoc b a c)^.\n\n  Record Symmetric_Monoidal_1Type : Type :=\n    { smontype_type :> 1-Type;\n      smontype_mult  : smontype_type -> smontype_type -> smontype_type;\n      smontype_id : smontype_type;\n      smontype_assoc : associative smontype_mult;\n      smontype_lid : left_identity_mult smontype_mult smontype_id ;\n      smontype_rid : right_identity_mult smontype_mult smontype_id ;\n      smontype_sym : symmetric smontype_mult ;\n      smontype_sym_inv : forall a b : smontype_type, smontype_sym a b = (smontype_sym b a)^ ;\n      smontype_triangle1 : coherence_triangle1 smontype_assoc smontype_lid ;\n      smontype_triangle2 : coherence_triangle2 smontype_assoc smontype_lid smontype_rid ;\n      smontype_pentagon : coherence_pentagon smontype_assoc;\n      smontype_hexagon : coherence_hexagon smontype_assoc smontype_sym\n    }.\n  Global Arguments smontype_mult {S} a b : rename.\n  Global Arguments smontype_id {S} : rename.\n  Global Arguments smontype_assoc {S} a b c : rename.\n  Global Arguments smontype_lid {S} a : rename.\n  Global Arguments smontype_rid {S} a : rename.\n  Global Arguments smontype_sym {S} a b : rename.\n\n  Definition forget_symmetry : Symmetric_Monoidal_1Type -> Monoidal_1Type :=\n    fun S => Build_Monoidal_1Type S smontype_mult smontype_id smontype_assoc smontype_lid smontype_rid\n                                  (smontype_triangle1 S) (smontype_triangle2 S) (smontype_pentagon S).\n\n  Coercion forget_symmetry : Symmetric_Monoidal_1Type >-> Monoidal_1Type.\nEnd Symmetric_Monoidal_1Type.\n\n\n\n  \n    \n\n\n\n  \n\n\n\n     \n                   \n  \n  ", "meta": {"author": "kalfsvag", "repo": "group_completions", "sha": "cc65e902a68dbb6dc05315651dce3064704a9815", "save_path": "github-repos/coq/kalfsvag-group_completions", "path": "github-repos/coq/kalfsvag-group_completions/group_completions-cc65e902a68dbb6dc05315651dce3064704a9815/background/monoidal_1type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7577943822145997, "lm_q1q2_score": 0.7003094811327022}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf1 : natural) (lf2 : natural)\n  : natural := mult z (Succ y).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj174_coqofml_XKvfHO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7003094659675912}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (z : natural) (y : natural) (lf2 : natural) (lf1 : natural)\n  : natural := mult lf1 (Succ Zero).\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_distrib_100_plus_assoc/goal33conj43_coqofml_g8RPzQ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7003094646897299}}
{"text": "Require Import Bool List Arith Nat Coq.Arith.Div2.\nImport ListNotations.\n\n\n(*=bitn *) \nFixpoint bit_n (l : list bool) : nat :=\n  match l with\n    | [] => 0\n    | a :: tl => 2 * bit_n tl + Nat.b2n a\n  end.\n(*=End *)\n(*=nbit *) \nFixpoint n_bit (n : nat) (k : nat) : option (list bool) :=\n    match n with\n      | 0 => match k with\n             | 0 => Some []\n             | S _ => None\n             end\n      | S n' => match n_bit n' (Nat.div2 k) with\n                  | None => None\n                  | Some l => Some (Nat.odd k :: l)\n                end\n    end.\n(*=End *)\nCompute pow 2 8.\nCheck leb 2 3.\n\n    \n\n\nSearchAbout (_ mod _).\n(*=size_n_bit *)\nTheorem size_n_bit : forall (n k: nat) (l : list bool),\n    n_bit n k = Some l -> length l = n.\n(*=End *)\nProof.\n  induction n.\n  -intros k l.\n   induction k.\n   +intros.\n    inversion H.\n    reflexivity.\n   +simpl.\n    discriminate.\n  -intros k l.\n   simpl.\n   case_eq (n_bit n (Nat.div2 k)).  \n   +intros.\n    inversion H0.\n    assert (help1: forall (l' : list bool) (b : bool), length l' = n -> length(b :: l') = S n).\n    {\n      induction l'.\n      -intros b.\n       simpl.\n       intros.\n       rewrite H1.\n       reflexivity.\n      -intros b.\n       simpl.\n       intros.\n       rewrite H1.\n       reflexivity.\n    }    \n    apply help1.\n    specialize (IHn (Nat.div2 k)).\n    apply IHn.\n    exact H.\n   +intros.\n    discriminate.\nQed.\n     \n\n(* first proof that we need on binary representation *)\n(*=nbitn *)\nLemma n_bit_n : forall (l : list bool) (n k : nat),\n    n_bit n k = Some l -> bit_n l = k.\n(*=End *)\nProof.\n  assert (I : forall (l : list bool) (n k : nat), n_bit n k = Some l -> bit_n l = k).\n  {\n    intros l; induction l; intros n k.\n    simpl.\n    assert (I_1 : n_bit n k = Some [] -> bit_n [] = k).\n    {\n      induction k.\n      - reflexivity.\n       (* the hypothesis is false so we will need to find how to demonstrate this *)\n      - assert (I_1_1 : n_bit n (S k) = Some [] -> bit_n [] = S k).\n       {\n         induction n.\n         - discriminate.\n         - unfold n_bit; fold n_bit.\n           destruct (n_bit n (Nat.div2 (S k))); discriminate.\n       }\n       exact I_1_1.\n    }\n    exact I_1.\n    assert (I_2 : n_bit n k = Some (a :: l) -> bit_n (a :: l) = k).\n    {\n      intros H.\n      simpl.\n      About Nat.div2_odd.\n      rewrite (Nat.div2_odd k).\n      simpl.\n      destruct n; simpl in H.\n      - destruct k; discriminate.\n      - destruct (n_bit n (Nat.div2 k)) eqn:Hl; try discriminate.\n        inversion H; subst.\n        erewrite IHl; eauto.\n    }\n    assumption.\n  }\n  assumption.\nQed.\n\n\n(* second proof *)\n(*=bitnbit *)\nTheorem bit_n_bit : forall (l : list bool) (n : nat),\n    n = length l -> (n_bit n (bit_n l)) = Some l.\n(*=End *)\nProof.\n  assert (I : forall (l : list bool) (n : nat), n = length l -> n_bit n (bit_n l) = Some l).\n  {\n    induction l.\n    assert (I_1 : forall n : nat, n = length ([] : list bool) -> n_bit n (bit_n []) = Some []).\n    {\n      simpl.\n      intros n H.\n      rewrite H.\n      reflexivity.\n    }\n    exact I_1.\n    assert (I_2 : forall n : nat, n = length (a :: l) -> n_bit n (bit_n (a :: l)) = Some (a :: l)).\n    {\n      intros n.\n      simpl.\n      destruct a.\n      assert (I_2_1 : n = length (true :: l) -> n_bit n (bit_n (true :: l)) = Some (true :: l)).\n      {\n        simpl.\n        Search (_ + 0).\n        rewrite <- plus_n_O.\n        intros H.\n        rewrite H.\n        simpl.\n        assert (I_2_1_1 : forall l' : (list bool), bit_n l' + bit_n l' = 2 * bit_n l').\n        {\n          induction l'.\n          -reflexivity.\n          -simpl.\n           rewrite <- plus_n_O.\n           rewrite <- plus_n_O.\n           reflexivity.\n        }        \n        rewrite I_2_1_1.\n        Search (_ + 1 = S _).\n        Search (Nat.div2 _).\n        rewrite Nat.add_1_r.\n        Check even_div2.\n        rewrite <- even_div2.\n        -Search (Nat.div2 (2 * _)).\n         rewrite div2_double.\n         rewrite IHl.\n         +assert (I_2_1_2 : forall (n' : nat), Nat.odd (S (2 * n')) = true).\n          {\n            intros n'.\n            induction n'.\n            -reflexivity.\n            -simpl.\n             rewrite <- plus_n_Sm.\n             simpl in IHn'.\n             rewrite <- IHn'.\n             Search (Nat.odd (S (S _))).\n             rewrite Nat.odd_succ_succ. reflexivity.\n          }\n          rewrite I_2_1_2.\n          reflexivity.\n         +reflexivity.\n        -assert (I_2_1_3 : Even.even (2 * bit_n l)).\n         {\n           (* this is supposed to be trivial -_-_-_-_-_-_-_-_-_-_-_-_- *)\n           Check Nat.even_add_mul_2.\n           Search (0 + _).\n           rewrite <- Nat.add_0_l.\n           SearchAbout (even (_ + _)).\n           specialize (Nat.even_add_mul_2 0 (bit_n l)).\n           intros.\n           Check Even.even_equiv.\n           apply Even.even_equiv.\n           (* even spec *)\n           Check Nat.even_spec.\n           simpl in H0.\n           Search (_ + _ = 2 * _).\n           Check I_2_1_1.\n           rewrite <- I_2_1_1.\n           assert (0 + (bit_n l + bit_n l) = bit_n l + (bit_n l + 0)).\n           { simpl. Search (_ + 0). rewrite <- plus_n_O. reflexivity. }\n           rewrite H1. \n           rewrite Nat.even_spec in H0.\n           exact H0.\n         }\n         exact I_2_1_3.\n      }\n      exact I_2_1.\n      assert (I_2_2 : n = S (length l) -> n_bit n (bit_n l + (bit_n l + 0) + Nat.b2n false) = Some (false :: l)).\n      {\n        simpl.\n        Search (_ + 0).\n        rewrite <- plus_n_O.\n        rewrite <- plus_n_O.\n        intros H.\n        rewrite H.\n        simpl.\n        Search (2 * _ = _).\n        assert (I_2_2_0 : forall (n' : nat), 2 * n' = n' + n').\n        {\n          intros n'. simpl. rewrite <- plus_n_O. reflexivity.\n        }\n        rewrite <- I_2_2_0.\n        rewrite div2_double.\n        rewrite IHl.\n        -assert (I_2_2_1 : forall (n' : nat), Nat.odd (2 * n') = false).\n         {\n           induction n'.\n           -simpl. Search (Nat.odd 0).\n            rewrite Nat.odd_0. reflexivity.\n           -simpl.\n            Search (_ + 0).\n            rewrite <- plus_n_O.\n            Search (_ + _ = _ + _).\n            rewrite <- plus_Snm_nSm.\n            Search (S _ + _).\n            rewrite plus_Sn_m.\n            Search (Nat.odd (S (S _))).\n            rewrite Nat.odd_succ_succ.\n            simpl in IHn'.\n            rewrite <- plus_n_O in IHn'.\n            rewrite IHn'.\n            reflexivity.            \n         }\n         rewrite I_2_2_1.\n         reflexivity.\n        -reflexivity.\n      }\n      exact I_2_2.\n    }\n    exact I_2.\n  }\n  exact I.\nQed.\n", "meta": {"author": "romisfrag", "repo": "Certified-MMIX-encoder-decoder", "sha": "dd1554dc5e5328258aa4fc716693106fc26dfded", "save_path": "github-repos/coq/romisfrag-Certified-MMIX-encoder-decoder", "path": "github-repos/coq/romisfrag-Certified-MMIX-encoder-decoder/Certified-MMIX-encoder-decoder-dd1554dc5e5328258aa4fc716693106fc26dfded/src/binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7003030452633556}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype fingraph finfun finset.\n\nRequire Import misc.\nRequire Import regexp.\n\nSet Implicit Arguments.\n\nModule Automata.\n\n  Import Misc.\n  \n  (** Finite automata. ***)\n  Section FA.\n\n    Variable char: finType.\n    \n    (** Type of input sequences ***)\n    Definition word := word char.\n\n    (** Deterministic finite automata. **)\n    Section DFA.\n\n      (** The type of deterministic finite automata. ***)\n      Record dfa : Type :=\n        {\n          dfa_state :> finType;\n          dfa_s: dfa_state;\n          dfa_fin: pred dfa_state;\n          dfa_step: dfa_state -> char -> dfa_state\n        }.\n\n\n      (** Acceptance on DFAs **)\n      Section Acceptance.\n\n        (** Assume some automaton **)\n        Variable A: dfa.\n\n        (** We define a run of w on the automaton A\n   to be the list of states x_1 .. x_|w|\n   traversed when following the edges labeled\n   w_1 .. w_|w| starting in x. **)\n        Fixpoint dfa_run' (x: A) (w: word) : seq A :=\n          match w with\n            | [::] => [::]\n            | a::w => (dfa_step A x a) ::dfa_run' (dfa_step A x a) w\n          end.\n\n        (** A simplifying function for a \"aux2\" run\n   (i.e. starting at s). **)\n        Definition dfa_run := [fun w => dfa_run' (dfa_s A) w].\n\n        (** Acceptance of w in x is defined as\n   finality of the last state of a run of w on A\n   starting in x. **)\n        Fixpoint dfa_accept x w :=\n          match w with\n            | [::] => dfa_fin A x\n            | a::w => dfa_accept (dfa_step A x a) w\n          end.\n\n        (** **)\n        Fixpoint dfa_final x w :=\n          match w with\n            | [::] => x\n            | a::w => dfa_final (dfa_step A x a) w\n          end.\n        \n        Lemma dfa_final_accept x w:\n          dfa_fin A (dfa_final x w) <-> dfa_accept x w.\n        Proof.\n          elim: w x => [| a w IH] x; split; intros; try done.\n          simpl in *; apply IH; by done.\n          simpl in *; apply IH; by done.\n        Qed.          \n          \n        Lemma dfa_accept_cons x a w:\n          a::w \\in dfa_accept x = (w \\in dfa_accept (dfa_step A x a)).\n        Proof. by rewrite -simpl_predE /=. Qed.\n\n        (** We define the language of the deterministic\n   automaton, i.e. acceptance in the starting state. **)\n        Definition dfa_lang := [pred w | dfa_accept (dfa_s A) w].\n\n        (** take lemma. **)\n        Lemma dfa_run'_take x w n: take n (dfa_run' x w) = dfa_run' x (take n w).\n        Proof. elim: w x n => [|a w IHw] x n //.\n               case: n => [|n] //=. by rewrite IHw.\n        Qed.\n\n        (** rcons and cat lemmas. **)\n        Lemma dfa_run'_cat x w1 w2 :\n          dfa_run' x (w1 ++ w2) = dfa_run' x w1 ++ dfa_run' (last x (dfa_run' x w1)) w2.\n        Proof. elim: w1 w2 x => [|a w1 IHw1] w2 x //.\n               simpl. by rewrite IHw1.\n        Qed.\n\n\n        (* slightly altered acceptance statement. *)\n        Lemma dfa_run_accept x w: last x (dfa_run' x w) \\in dfa_fin A = (w \\in dfa_accept x).\n        Proof. elim: w x => [|a w IHw] x //. by rewrite /= IHw. Qed.\n\n      End Acceptance.\n\n    End DFA.\n\n    Implicit Arguments Build_dfa [dfa_state]. \n\n\n    (** Non-deterministic automata. **)\n    Section NFA.\n\n      (** The type of non-deterministic finite automata. ***)\n      Record nfa : Type :=\n        {\n          nfa_state :> finType;\n          nfa_s: nfa_state;\n          nfa_fin: pred nfa_state;\n          nfa_step: nfa_state -> char -> pred nfa_state\n        }.\n\n      (** Acceptance on non-deterministic automata. **)\n      Section Acceptance.\n\n        Variable A: nfa.\n\n        (** Non-deterministic acceptance. **)\n        Fixpoint nfa_accept (x: A) w :=\n          match w with\n            | [::] => nfa_fin A x\n            | a::w => [ exists y, (nfa_step A x a y) && nfa_accept y w ]\n          end.\n\n        (** We define the language of the non-deterministic\n   automaton, i.e. acceptance in the starting state. **)\n        Definition nfa_lang := [pred w | nfa_accept (nfa_s A) w].\n\n        (** We define labeled paths over the non-deterministic step relation **)\n        Fixpoint nfa_run x (xs : seq A) (w: word) {struct xs} :=\n          match xs,w with\n            | y :: xs', a::w' => nfa_step A x a y && nfa_run y xs' w'\n            | [::]    , [::]  => true\n            | _       , _     => false\n          end.\n\n        Lemma nfa_run_accept x w:\n          reflect (exists2 xs, nfa_run x xs w & last x xs \\in nfa_fin A)\n                  (nfa_accept x w).\n        Proof.\n          elim: w x => [|a w IHw] x.\n          case H: (nfa_accept x [::]); constructor.\n            by exists [::].\n                      move => [[|y xs]] //.\n                      move: H => /= H _.\n                        by rewrite -topredE /= H.\n                        case H: nfa_accept => /=; constructor.\n                        move/existsP: H => [] y /andP [] H1 /IHw [] xs H2 H3.\n                        exists (y::xs) => //=.\n                          by rewrite H1 H2 /=.\n                          move => [[|y xs]] //= /andP [] H1 H2 H3.\n                          move/existsP: H => H.\n                          apply: H. exists y.\n                          rewrite H1 /=.\n                          apply/IHw.\n                            by exists xs.\n        Qed.\n        \n\n        (** Helpful facts **)\n        Lemma nfa_accept_cat x w1 w2:\n          nfa_accept x (w1 ++ w2) <->\n          exists xs,\n            nfa_run x xs w1\n                    && nfa_accept (last x xs) w2.\n        Proof. split.\n               elim: w1 w2 x => [|a w1 IHw1] w2 x.\n               simpl. exists [::]. simpl. exact: H.\n               move/existsP => [] y /andP [] H0 /IHw1 [] ys /andP [] H1 H2.\n               exists (y::ys) => /=. by rewrite H0 H1 H2.\n               elim: w1 w2 x => [|a w1 IHw1] w2 x; move => [] [|y ys] /andP [] H0 H1 //.\n               move: H0 => /= /andP [] H2 H3. \n               apply/existsP. exists y. rewrite H2 /=.\n               apply: IHw1.\n               exists ys. by rewrite H3 H1.\n        Qed.\n\n      End Acceptance.\n\n    End NFA.\n\n    Implicit Arguments Build_nfa [nfa_state]. \n\n    (** We define the powerset construction to obtain\n   a deterministic automaton from a non-deterministic one. **) \n    Section PowersetConstruction.\n\n      Variable A: nfa.\n\n      Definition nfa_to_dfa :=\n        {| dfa_s := set1 (nfa_s A);\n           dfa_fin := [ pred X: {set A} | [ exists x: A, (x \\in X) && nfa_fin A x] ];\n           dfa_step := [ fun X a => \\bigcup_(x | x \\in X) finset (nfa_step A x a) ]\n        |}.\n\n      (** We prove that for every state x, the new automaton\n   accepts at least the language of the given automaton\n   when starting in a set containing x. **)\n      Lemma nfa_to_dfa_aux2 (x: A) w (X: nfa_to_dfa):\n        x \\in X -> nfa_accept A x w -> dfa_accept nfa_to_dfa X w.\n      Proof. move => H0.\n             elim: w X x H0 => [|a w IHw] X x H0.\n             (* [::] *)\n             move => /= H1. apply/existsP. exists x.\n               by rewrite H0 H1.\n               (* a::w *)\n               move => /= /existsP [] y /andP [] H1.\n               apply (IHw).\n               apply/bigcupP.\n               exists x => //.\n                 by rewrite in_set.\n      Qed.\n\n      (** Next we prove that in any set of states X, for every word w,\n   if the powerset automaton accepts w in X, there exists one\n   representative state of that set in which the given automaton\n   accepts w. **)\n      Lemma nfa_to_dfa_aux1 (X: nfa_to_dfa) w:\n        dfa_accept nfa_to_dfa X w -> [ exists x, (x \\in X) && nfa_accept A x w ].\n      Proof. elim: w X => [|a w IHw] X => //.\n             move/IHw => /existsP [] y /andP [].\n             rewrite /dfa_step /nfa_to_dfa. \n             move/bigcupP => [] x H0. rewrite in_set => H1 H2 /=.\n             apply/existsP. exists x. rewrite H0 /=.\n             apply/existsP. exists y. \n               by rewrite H1 H2.\n      Qed.\n\n      (** Finally, we prove that the language of the powerset\n   automaton is exactly the language of the given\n   automaton. **)\n      Lemma nfa_to_dfa_correct : nfa_lang A =i dfa_lang nfa_to_dfa.\n      Proof. move => w. apply/idP/idP => /=.\n             apply: nfa_to_dfa_aux2. by apply/set1P.\n               by move/nfa_to_dfa_aux1 => /existsP [] x /andP [] /set1P ->.\n      Qed.\n      \n\n    End PowersetConstruction.\n\n\n    (** Embedding deterministic automata in non-deterministic automata. **)\n    Section Embed.\n\n      Variable A: dfa.\n\n      Definition dfa_to_nfa : nfa :=\n        {|\n          nfa_s := dfa_s A;\n          nfa_fin := dfa_fin A;\n          nfa_step := fun x a y => y == dfa_step A x a \n        |}.\n\n      (** We prove that dfa_to_nfa accepts the same language as\n   the given automaton in any state. **)\n      Lemma dfa_to_nfa_correct' x w : dfa_accept A x w = nfa_accept dfa_to_nfa x w.\n      Proof. elim: w x => [|b w IHw] x.\n               by [].\n               simpl. rewrite IHw.\n               apply/idP/existsP.\n               move => H0. exists (dfa_step A x b). by rewrite eq_refl H0.\n                 by move => [] y /andP [] /eqP ->.\n      Qed.\n\n      (** We prove that dfa_to_nfa accepts the same language\n   as the given automaton in the starting state, i.e. their\n   languages are equal. **)\n      Lemma dfa_to_nfa_correct : dfa_lang A =i nfa_lang dfa_to_nfa.\n      Proof.\n        exact: dfa_to_nfa_correct'.\n      Qed.\n      \n    End Embed.\n\n    (** Primitive automata **)\n    Section Primitive.\n      Definition dfa_void :=\n        {| \n          dfa_s := tt;\n          dfa_fin := pred0;\n          dfa_step := [fun x a => tt]\n        |}.\n      \n      Lemma dfa_void_correct x w: ~~ dfa_accept dfa_void x w.\n      Proof. by elim: w x => [|a w IHw] //= x. Qed.\n\n      Definition dfa_eps :=\n        {|\n          dfa_s := true;\n          dfa_fin := pred1 true;\n          dfa_step := [fun x a => false]\n        |}.\n\n      Lemma dfa_eps_correct: dfa_lang dfa_eps =i pred1 [::].\n      Proof.\n        have H: (forall w, ~~ dfa_accept dfa_eps false w).\n          by elim => [|a v IHv] //=.\n          move => w.\n          elim: w => [|a w IHw] //.\n          apply/idP/idP.\n          exact: H. \n      Qed.\n      \n      Definition dfa_char a :=\n        {|\n          dfa_s := None;\n          dfa_fin := pred1 (Some true);\n          dfa_step := [fun x b => if x == None then if b == a then Some true else Some false else Some false ]\n        |}.\n      \n      Lemma dfa_char_correct'' a w: ~~ dfa_accept (dfa_char a) (Some false) w.\n      Proof. by elim: w => [|b v IHv] //=. Qed.\n      Lemma dfa_char_correct' a w: dfa_accept (dfa_char a) (Some true) w = (w == [::]).\n      Proof.\n        elim: w a => [|b w IHw] a //=.\n        apply/idP/idP.\n        exact: dfa_char_correct''.\n      Qed.\n      Lemma dfa_char_correct a w: dfa_lang (dfa_char a) w = (w == [::a]).\n      Proof.\n        elim: w a => [|b w IHw] a //=.\n        case H: (b == a).\n        move/eqP: H => ->.\n        rewrite dfa_char_correct'.\n          by apply/eqP/eqP => [-> | []].\n          apply/idP/eqP.\n          move => H0. move: (dfa_char_correct'' a w). by rewrite H0.\n          move => [] /eqP. by rewrite H.\n      Qed.\n\n      Definition dfa_dot :=\n        {|\n          dfa_s := None;\n          dfa_fin := pred1 (Some true);\n          dfa_step := [fun x b => if x == None then Some true else Some false ]\n        |}.\n      \n      Lemma dfa_dot_correct'' w: ~~ dfa_accept dfa_dot (Some false) w.\n      Proof. by elim: w => [|b v IHv] //=. Qed.\n      Lemma dfa_dot_correct' w: dfa_accept dfa_dot (Some true) w = (w == [::]).\n      Proof.\n        elim: w => [|b w IHw] //=.\n        apply/idP/idP.\n        exact: dfa_dot_correct''.\n      Qed.\n      Lemma dfa_dot_correct w: dfa_lang dfa_dot w = (size w == 1).\n      Proof.\n        elim: w => [|b w IHw] //=.\n        rewrite dfa_dot_correct'.\n        apply/eqP/eqP => [-> | []] //=.\n        exact: size0nil.\n      Qed.\n\n      \n    End Primitive.\n\n    (** Operations on non-deterministic automata. **)\n    Section DFAOps.\n\n      Variable A1: dfa.\n\n\n      (** Complement automaton **)\n      \n      (** We construct the resulting automaton. **)\n      Definition dfa_compl :=\n        {| \n          dfa_s := dfa_s A1;\n          dfa_fin := [ fun x1 => ~~ dfa_fin A1 x1 ];\n          dfa_step := (dfa_step A1)\n        |}.\n\n      (** We prove that the complement automaton accepts exactly\n   the words not accepted by the original automaton. **)\n      Lemma dfa_compl_correct' x:\n        [ predC dfa_accept A1 x ] =i dfa_accept dfa_compl x.\n      Proof. move => w. elim: w x => [|a w IHw] x.  \n               by apply/idP/idP.\n               simpl. rewrite -topredE dfa_accept_cons /= -IHw.\n               apply/negP/idP; rewrite dfa_accept_cons; by move/negP.\n      Qed.\n\n      (** Language correctness for dfa_compl **)\n      Lemma dfa_compl_correct:\n        [ predC dfa_lang A1 ] =i dfa_lang dfa_compl.\n      Proof. exact: dfa_compl_correct'. Qed.\n\n      \n      (** Operations on two automata. **)\n      Section BinaryOps.\n        \n        Variable A2: dfa.\n\n        (** Disjunction automaton **)\n\n        Definition dfa_disj :=\n          {|\n            dfa_s := (dfa_s A1, dfa_s A2);\n            dfa_fin := (fun q => let (x1,x2) := q in dfa_fin A1 x1 || dfa_fin A2 x2);\n            dfa_step := [fun x a => (dfa_step A1 x.1 a, dfa_step A2 x.2 a)]\n          |}.\n\n        (** Correctness w.r.t. any state. **)\n        Lemma dfa_disj_correct' x:\n          [ predU dfa_accept A1 x.1 & dfa_accept A2 x.2 ]\n          =i dfa_accept dfa_disj x.\n        Proof. move => w. elim: w x => [|a w IHw].\n                 by move => [].\n                 move => x /=. by rewrite dfa_accept_cons -IHw.\n        Qed.\n\n        (** Language correctness. **)\n        Lemma dfa_disj_correct:\n          [ predU  dfa_lang A1 & dfa_lang A2 ]\n          =i dfa_lang dfa_disj.\n        Proof. move => w /=. by rewrite -dfa_disj_correct'. Qed.\n\n        (** Conjunction **) \n        \n        Definition dfa_conj :=\n          {| \n            dfa_s := (dfa_s A1, dfa_s A2);\n            dfa_fin := (fun x => dfa_fin A1 x.1 && dfa_fin A2 x.2);\n            dfa_step := [fun x a => (dfa_step A1 x.1 a, dfa_step A2 x.2 a)]\n          |}.\n\n        (** Correctness w.r.t. any state. **)\n        Lemma dfa_conj_correct' x1 x2 :\n          [ predI  dfa_accept A1 x1 & dfa_accept A2 x2 ]\n          =i dfa_accept dfa_conj (x1, x2).\n        Proof. move => w. elim: w x1 x2 => [|a w IHw].\n                 by [].\n                 move => x1 x2.\n                 exact: IHw.\n        Qed.\n\n        (** Language correctness. **)\n        Lemma dfa_conj_correct:\n          [ predI dfa_lang A1 & dfa_lang A2 ]\n          =i dfa_lang dfa_conj.\n        Proof. move => w. by rewrite -dfa_conj_correct'  /=. Qed.\n\n      End BinaryOps.\n\n      (* Remove unreachable states *)\n      Section Reachability.\n        Definition reachable1 := [ fun x y => [ exists a, dfa_step A1 x a == y ] ].\n\n        Definition reachable := enum (connect reachable1 (dfa_s A1)).\n\n        Lemma reachable_step x a: x \\in reachable ->  dfa_step A1 x a \\in reachable.\n        Proof.\n          rewrite 2!mem_enum -2!topredE /= => Hx.\n          eapply connect_trans.\n          eassumption.\n          apply/connectP.\n          exists [::dfa_step A1 x a] => //=.\n          rewrite andbT. apply/existsP. by exists a.\n        Qed.\n\n        Lemma reachable0 : dfa_s A1 \\in reachable. \n        Proof. rewrite mem_enum -topredE /=. by apply connect0. Qed.\n\n        Definition dfa_connected :=\n          {| \n            dfa_s := SeqSub reachable0;\n            dfa_fin := fun x => match x with SeqSub x _ => dfa_fin A1 x end;\n            dfa_step := fun x a => match x with\n                                     | SeqSub _ Hx => SeqSub (reachable_step _ a Hx)\n                                   end\n          |}.\n        \n\n        Lemma dfa_connected_correct' x (Hx: x \\in reachable) :\n          dfa_accept dfa_connected (SeqSub Hx) =i dfa_accept A1 x.\n        Proof. move => w. elim: w x Hx => [|a w IHw] x Hx //=.\n                 by rewrite 2!dfa_accept_cons IHw.\n        Qed. \n\n        Lemma dfa_connected_correct: dfa_lang dfa_connected =i dfa_lang A1.\n        Proof.\n          move => w. by rewrite /dfa_lang /= dfa_connected_correct'.\n        Qed.\n\n        Definition reachable1_connected := [ fun x y => [ exists a, dfa_step dfa_connected x a == y ] ].\n        Lemma reachable1_connected_aux2 x y (Hx: x \\in reachable) (Hy: y \\in reachable) : connect reachable1 x y -> connect reachable1_connected (SeqSub Hx) (SeqSub Hy).\n        Proof.\n          move/connectP => [p].\n          elim: p x Hx y Hy => [|z p IHp] x Hx y Hy //=.\n          move => _ H.                                \n          move: Hx Hy. rewrite H => Hx Hy.\n          have: (Hx = Hy).\n            by apply: bool_irrelevance.\n            move => ->.\n            apply: connect0.\n            move/andP => [] /existsP [] a /eqP Ha Hpz H.\n            have Hz: (z \\in reachable).\n            rewrite -Ha. by apply reachable_step.\n            pose H0 := (IHp _ Hz _ Hy Hpz H).\n            eapply connect_trans.\n            apply connect1.\n            instantiate (1 := SeqSub Hz).\n            apply/existsP. exists a.\n            simpl. move: Hz H0.\n            rewrite -Ha => Hz H0.\n            have: Hz = reachable_step x a Hx.\n            apply bool_irrelevance.\n              by move => ->.\n              assumption.\n        Qed.\n\n        \n        Lemma dfa_connected_repr' (x y: dfa_connected):\n          connect reachable1_connected y x ->\n          exists w, last y (dfa_run' dfa_connected y w) = x.\n        Proof.\n          move/connectP => [] p.\n          elim: p x y => [|z p IHp] x y.\n          move => _ -> /=. by exists [::].\n                                     move => /= /andP [] /existsP [] a /eqP Ha Hp Hx.\n                                     destruct (IHp x z) as [w Hw] => //.\n                                     exists (a::w).\n                                       by rewrite /= Ha.\n        Qed.\n\n        Lemma dfa_connected_repr x :\n          exists w, last (dfa_s dfa_connected) (dfa_run dfa_connected w) = x.\n        Proof.\n          apply dfa_connected_repr'.\n          destruct x as [x Hx].\n          apply (reachable1_connected_aux2 (dfa_s A1) x reachable0).\n            by rewrite mem_enum -topredE /= in Hx.\n        Qed.\n        \n        Lemma dfa_connected_repr_pred x :\n          exists w, last (dfa_s dfa_connected) (dfa_run dfa_connected w) == x.\n        Proof.\n          move: (dfa_connected_repr x) => [w /eqP].\n            by eauto.\n        Defined.\n        \n        Lemma dfa_connected_repr_fun (x: dfa_connected):\n          word.\n        Proof.\n          move: (dfa_connected_repr_pred x).\n          apply (xchoose).\n        Defined.\n\n        Lemma dfa_connected_repr_fun_correct x: last (dfa_s dfa_connected) (dfa_run dfa_connected (dfa_connected_repr_fun x)) = x.\n        Proof.\n          rewrite /dfa_connected_repr_fun. \n            by move: (xchooseP (dfa_connected_repr_pred x)) => /eqP.\n        Qed.\n        \n        Lemma dfa_connected_repr_fun_injective: injective dfa_connected_repr_fun.\n        Proof.\n          move => x y.\n          rewrite /dfa_connected_repr_fun => H.\n          move: (xchooseP (dfa_connected_repr_pred x)) => /eqP.\n          move: (xchooseP (dfa_connected_repr_pred y)) => /eqP.\n          rewrite H. by move => -> ->.\n        Qed.\n        \n      End Reachability.\n\n      Section Emptiness.\n\n        Definition dfa_lang_empty := #|dfa_fin dfa_connected| == 0.\n\n        Lemma dfa_lang_empty_aux2: dfa_lang dfa_connected =i pred0 -> dfa_lang_empty.\n        Proof.\n          rewrite /dfa_lang_empty.\n          move => H.\n          apply/eqP/eq_card0.\n          move => x.\n          apply/idP/idP.\n          apply/negP.\n          move: (dfa_connected_repr x) => [w Hw].\n          move: (H w).\n          rewrite /dfa_lang /= -dfa_run_accept.\n          rewrite Hw.\n            by move/negP.\n        Qed. \n        \n        Lemma dfa_lang_empty_aux1: dfa_lang_empty -> dfa_lang dfa_connected =i pred0.\n        Proof.\n          rewrite /dfa_lang_empty.\n          move => H w.\n          apply/idP/idP.\n          apply/negP.\n          rewrite /dfa_lang /= -dfa_run_accept.\n            by move/eqP/card0_eq: H => ->.\n        Qed.\n        \n        Lemma dfa_lang_empty_correct:\n          reflect (dfa_lang A1 =i pred0)\n                  dfa_lang_empty.\n        Proof.\n          apply/iffP.\n          eexact (@idP dfa_lang_empty ).\n          move => H w. rewrite -dfa_connected_correct.\n          exact: dfa_lang_empty_aux1.\n          move => H.\n          apply: dfa_lang_empty_aux2.\n          move => w.\n            by rewrite dfa_connected_correct.\n        Qed.\n        \n      End Emptiness.\n\n    End DFAOps.\n\n    Section Equivalence.\n      Definition dfa_sym_diff A1 A2 :=\n        dfa_disj (dfa_conj A1 (dfa_compl A2)) (dfa_conj A2 (dfa_compl A1)).\n\n      Definition dfa_equiv A1 A2 := dfa_lang_empty (dfa_sym_diff A1 A2).\n\n      Lemma dfa_equiv_correct A1 A2:\n        dfa_equiv A1 A2 <-> dfa_lang A1 =i dfa_lang A2.\n      Proof.\n        split; rewrite /dfa_sym_diff.\n        move/dfa_lang_empty_correct => H w.\n        move: (H w).\n        rewrite -dfa_disj_correct -topredE /= -2!dfa_conj_correct -2!topredE /= -2!dfa_compl_correct.\n        move/norP => [] /nandP [] /negP H1 /nandP [] /negP H2;\n          apply/idP/idP; try by [];\n          move/negP: H1; move/negP: H2;\n            by auto using negbNE.\n        move => H. apply/dfa_lang_empty_correct => w. move: (H w).\n        rewrite -dfa_disj_correct -3!topredE /= -2!dfa_conj_correct -2!topredE /= -2!dfa_compl_correct.\n        rewrite -H -4!topredE /= -2!topredE /= andbN => ->.\n          by rewrite andbN.\n      Qed.    \n\n    End Equivalence.\n\n\n    (** Operations on non-deterministic automata. **)\n    Section NFAOps.\n      Variable A1: nfa.\n      Variable A2: nfa.\n\n      (** Concatenation of two non-deterministic automata. **)\n\n      Definition nfa_conc : nfa :=\n        {|\n          nfa_s := inl _ (nfa_s A1);\n          nfa_fin := [fun x => \n                        match x with\n                          | inl x => nfa_fin A1 x && nfa_fin A2 (nfa_s A2)\n                          | inr x => nfa_fin A2 x\n                        end];\n          nfa_step := fun x a y =>\n                        match x,y with\n                          | inl x, inl y => nfa_step A1 x a y\n                          | inl x, inr y => nfa_fin A1 x && nfa_step A2 (nfa_s A2) a y\n                          | inr x, inr y => nfa_step A2 x a y\n                          | inr x, inl y => false\n                        end\n        |}.\n\n      (** We prove that every path of A2 can be mapped to a path\n   of nfa_conc. **)\n      Lemma nfa_conc_cont x xs w:\n        nfa_run A2 x xs w\n        -> nfa_run nfa_conc (inr _ x) (map (@inr A1 A2) xs) w.\n      Proof. elim: xs x w => [|y xs IHxs] x w; case: w => [|a w] => //.\n             simpl. by move/andP => [] -> /IHxs ->.\n      Qed.\n\n      (** We prove that every word in the language of A2\n   is also accepted by any final state of A1 in\n   nfa_conc. **)\n      Lemma nfa_conc_fin1 x1 w:\n        nfa_fin A1 x1 ->\n        nfa_lang A2 w ->\n        nfa_accept nfa_conc (inl _ x1) w.\n      Proof.\n        move => H0 /nfa_run_accept [] ys.\n        elim: ys w x1 H0 => [|y ys IHys] [|a w] x1 H0 //=.\n        rewrite -topredE /=.\n          by move: H0 => -> _ ->.\n          move => /andP [] H1 H2 H3.\n          apply/existsP. exists (inr _ y).\n          rewrite H0 H1 /=.\n          apply/nfa_run_accept.\n          eexists _.\n          apply nfa_conc_cont.\n            by eassumption.\n              by rewrite last_map /nfa_fin.\n      Qed.\n\n      (** We prove that for every word w1 accepted by A1 in\n   some state x and for every word w2 in the language of A2\n   w1 ++ w2 will be accepted by the corresponding state in\n   nfa_conc. **)\n      Lemma nfa_conc_aux2 x w1 w2:\n        nfa_accept A1 x w1 ->\n        nfa_lang A2 w2 ->\n        nfa_accept nfa_conc (inl _ x) (w1 ++ w2).\n      Proof. elim: w1 w2 x => [|a w1 IHw1] w2 x.\n             move => H0 /nfa_run_accept [] xs [] H1 H2.\n             move: (nfa_conc_cont _ _ _ H1) => H3.\n             apply/nfa_accept_cat.\n             exists [::] => /=.\n             apply: nfa_conc_fin1 => //.\n             apply/nfa_run_accept.\n               by eauto.\n               move => /existsP [] y /andP [] H1 H2 H3 /=.\n               apply/existsP. exists (inl _ y).\n               rewrite H1 /=.\n               apply: IHw1.\n               exact: H2.\n               exact: H3.\n      Qed.\n\n      (** We prove that every word accepted by some state X in nfa_conc is\n   - EITHER a concatenation of two words w1, w2 which are accpeted\n   by A1, A2 (resp.) if X corresponds to one of A1's states\n   - OR accepted by A2 in the state corresponding to X if X\n   corresponds to one of A2's states. **)\n      Lemma nfa_conc_aux1 X w :\n        nfa_accept nfa_conc X w ->\n        match X with\n          | inl x => exists w1, exists w2, (w == w1 ++ w2) && (nfa_accept A1 x w1) && nfa_lang A2 w2\n          | inr x => nfa_accept A2 x w\n        end.\n      Proof.\n        elim: w X => [|a w IHw] [x|x] //=.\n        move => /andP [] H0 H1. exists [::]. exists [::].\n          by rewrite /= H0 H1.\n          move/existsP => [] [y|y] /andP [] H0 /IHw.\n          (* inl / inl *)\n          move => [] w1 [] w2 /andP [] /andP [] /eqP H1 H2 /= H3.\n          exists (a::w1). exists w2.\n          rewrite H1 eq_refl H3 andTb andbT.\n          apply/existsP. exists y.\n          move: H0 => /= ->. rewrite andTb.\n          exact H2.\n          (* inl / inr *)\n          move: H0 => /= /andP [] H0 H1 /= H2.\n          exists [::]. exists (a::w) => /=.\n          rewrite H0 eq_refl 2!andTb.\n          apply/existsP. exists y.\n            by rewrite H1 H2.\n            (* inr / inl  *)\n            move/existsP => [] [y|y] /andP [] H0 /IHw.\n              by [].\n              (* inr / inr *)\n              move: H0 => /= H0 H1.\n              apply/existsP. exists y.\n                by rewrite H0 H1.\n      Qed.\n\n      Lemma nfa_conc_correct: nfa_lang nfa_conc =i conc (nfa_lang A1) (nfa_lang A2).\n      Proof.\n        move => w.\n        apply/idP/concP.\n        move/nfa_conc_aux1.\n        rewrite /nfa_conc /nfa_s.\n        move => [] w1 [] w2 /andP [] /andP [] /eqP H0 H1 H2.\n          by eauto.\n          move => [] w1 H0 [] w2 H2 ->.\n            by apply/nfa_conc_aux2.\n      Qed.  \n\n      (** Plus operator for non-deterministic automata. **)\n\n      (** The step relation implements the following rule:\n   - every edge to a final state will also be duplicated\n   to point to s0.\n       **)\n      Definition step_plus x a y : bool :=\n        nfa_step A1 x a y || (\n                   (y == nfa_s A1)\n                     && [ exists z, (nfa_fin A1 z) && (nfa_step A1 x a z) ]\n                 ).\n\n      (** **)\n      Definition nfa_repeat : nfa :=\n        {|\n          nfa_s := nfa_s A1;\n          nfa_fin := nfa_fin A1;\n          nfa_step := fun x a y =>\n                        nfa_step A1 x a y || (\n                                   (y == nfa_s A1)\n                                     && [ exists  z, (nfa_fin A1 z) && (nfa_step A1 x a z) ]\n                                 )\n        |}.\n\n\n      (** We prove that every path of A1 can be mapped to a path\n   of nfa_repeat. **)\n      Lemma nfa_repeat_cont x xs w:\n        nfa_run A1 x xs w\n        -> nfa_run nfa_repeat x xs w.\n      Proof. elim: xs x w => [|y xs IHxs] x w; case: w => [|a w] => //.\n             move/andP => [] H0 /= /IHxs ->.\n               by rewrite /step_plus H0 orTb.\n      Qed.\n\n      (** We prove that every accepting path labeled (a::w) in A1\n   exists in nfa_repeat with only the last state changed to\n   A1's starting state. This new path need not be accepting. **)\n      Lemma nfa_repeat_lpath x y xs a w:\n        nfa_fin nfa_repeat (last x (y::xs)) ->\n        nfa_run nfa_repeat x (y::xs) (a::w) ->\n        nfa_run nfa_repeat x (rcons (belast y xs) (nfa_s A1)) (a::w).\n      Proof. elim: xs x y a w => [|z xs IHxs] x y a [|b w] //=.\n             rewrite 2!andbT.\n             move => H0 /orP [|/andP [] /eqP].\n             move => H1. rewrite/step_plus.\n             apply/orP. right. rewrite eq_refl.\n             apply/existsP. exists y. by rewrite H0 H1.\n             move => H1 /existsP [] z /andP [] H2 H3. move: H1 H0 => -> H4.\n             apply/orP. right. rewrite eq_refl /=.\n             apply/existsP. exists z. by rewrite H2 H3.\n               by rewrite andbF.\n                 by rewrite andbF.\n                 rewrite -(last_cons y). move => H0 /andP [] H1 /andP [] H3 H4.\n                 rewrite H1 /=. apply: IHxs.\n                   by rewrite H0.\n                   simpl. by rewrite H3 H4.\n      Qed.\n      \n      (** We prove that every word accepted by A1 in\n   some state x is also accepted by nfa_repeat in\n   that state. **)\n      Lemma nfa_repeat_correct0' x w1 :\n        nfa_accept A1 x w1 ->\n        nfa_accept nfa_repeat x w1.\n      Proof.\n        move/nfa_run_accept => [] xs [].\n        move/nfa_repeat_cont => H0 H1.\n        apply/nfa_run_accept.\n          by exists xs. \n      Qed.\n\n      (** We prove that every word accepted by A1 is also\n   accepted by nfa_repeat. **)\n      Lemma nfa_repeat_correct0 w :\n        nfa_lang A1 w ->\n        nfa_lang nfa_repeat w.\n      Proof. exact: nfa_repeat_correct0'. Qed.\n\n      (** We prove that every prefix accpeted by A1 followed\n   by a suffix accepted by nfa_repeat is again accepted\n   by nfa_repeat. This is the first part of the proof of\n   language correctness for nfa_repeat. **)\n      Lemma nfa_repeat_aux2 w1 w2:\n        nfa_lang A1 w1 ->\n        nfa_lang nfa_repeat w2 ->\n        nfa_lang nfa_repeat (w1 ++ w2).\n      Proof.\n        move => /nfa_run_accept [] [|x xs] []; case: w1 => [|a w1] => //.\n        move => H0 H1 H2.\n        apply/(nfa_accept_cat).\n        exists (rcons (belast x xs) (nfa_s A1)).\n        apply/andP. split.\n        apply: nfa_repeat_lpath.\n        exact: H1.\n        apply: nfa_repeat_cont.\n        exact: H0.\n        rewrite last_rcons.\n        exact H2.\n      Qed.\n\n\n      (** We prove that every word accepted by some state x in nfa_repeat\n   is a concatenation of two words w1, w2 which are accpeted by\n   A1 in x and nfa_repeat (resp.). **) \n      Lemma nfa_repeat_aux1' x w :\n        nfa_accept nfa_repeat x w ->\n        ((exists w1, exists w2, (w == w1 ++ w2) && (w1 != [::]) && (nfa_accept A1 x w1) && nfa_lang nfa_repeat w2\n         ) \\/ nfa_accept A1 x w ).\n      Proof. elim: w x => [|a w IHw] x.\n             move => H0. right.\n             exact: H0.\n             case/existsP => y /andP [H0 H1].\n             case: (IHw _ H1) => [[w1 [w2 /andP [/andP [/andP [/eqP H2 H9] H3] H4]]]|H2].\n             move: H0 => /orP [H5|].\n             left. exists (a::w1). exists w2.\n             rewrite H2 eq_refl H4 andbT /=.\n             apply/existsP. exists y.\n               by rewrite H5 H3.\n               move/andP => [] H5 /existsP [] z /andP [H6 H7].\n               move: H5 H1 H3 => /eqP -> H1 H3.\n               left. exists ([::a]). exists w.\n               rewrite eq_refl /=. apply/andP. split.\n               apply/existsP. exists z. by rewrite H6 H7.\n               exact: H1.\n               move: H0 => /orP [H5|].\n               right => /=. apply/existsP. exists y.\n                 by rewrite H5 H2.\n                 move/andP => [/eqP H3 /existsP [z /andP [H4 H5]]].\n                 move: H3 H1 H2 => -> H1 H2.\n                 left. exists [::a]. exists w.\n                 rewrite eq_refl /=. apply/andP. split.\n                 apply/existsP. exists z. by rewrite H5 H4.\n                 exact H1.\n      Qed.\n\n      (** We prove the second part of language correctness\n   for nfa_repeat. **)\n      Lemma nfa_repeat_aux1 w:\n        nfa_lang nfa_repeat w ->\n        ((exists w1, exists w2, (w == w1 ++ w2) && (w1 != [::]) && (nfa_lang A1 w1) && nfa_lang nfa_repeat w2\n         ) \\/ nfa_lang A1 w ).\n      Proof. exact: nfa_repeat_aux1'. Qed.\n\n\n      (* Star operator *)\n      Definition nfa_star := (dfa_disj dfa_eps (nfa_to_dfa nfa_repeat)).\n\n      Lemma nfa_star_aux1 w: w \\in dfa_lang nfa_star -> w \\in star (nfa_lang A1).\n      Proof.\n        rewrite /nfa_star -dfa_disj_correct -topredE /=.\n        rewrite dfa_eps_correct => /orP [].\n        move => /eqP ->.\n        apply/starP. by exists [::].\n                               rewrite -nfa_to_dfa_correct.\n                               move: w.\n                               apply: (size_induction size).\n                               move => w IHw.\n                               move/nfa_repeat_aux1' => [].\n                               move => [] w1 [] w2 [/andP [/andP [/andP [/eqP H1 H2] H3] H4]].\n                               have H5: (size w2 < size w).\n                               rewrite H1 size_cat addnC -{1}(addn0 (size w2)).\n                               rewrite ltn_add2l.\n                                 by destruct w1.\n                                 move: (IHw w2 H5 H4) => /starP [] vv H6 H7.\n                                 apply/starP. exists (w1::vv).\n                                   by rewrite /= H6 -topredE /= /eps /= H2 /nfa_lang /= -topredE /= H3.\n                                     by rewrite H1 H7.\n                                     rewrite /nfa_lang /=.\n\n                                     case: w IHw => [|a w] IHw H.\n                                     apply/starP. by exists [::].\n                                                            apply/starP.\n                                                            exists [::(a::w)] => //=.\n                                                              by rewrite -topredE andbT.\n                                                                by rewrite cats0.\n      Qed.  \n      \n      Lemma nfa_star_aux2 w: w \\in star (nfa_lang A1) -> w \\in dfa_lang nfa_star.\n      Proof.\n        rewrite /nfa_star -dfa_disj_correct -2!topredE /= -nfa_to_dfa_correct.\n        move/starP => [] vv. elim: vv w => [|v vv IHvv] w.\n        rewrite /= => _ ->. move: (dfa_eps_correct [::]).\n          by rewrite /dfa_lang /=.\n          rewrite [all _ _]/=.\n          move/andP => [] /andP [] H0 H1 H2 H3.\n          rewrite H3 [flatten _]/=.\n          move/orP: (IHvv (flatten vv) H2 (Logic.eq_refl _)) => [].\n          rewrite dfa_eps_correct => /eqP H4.\n          move: H3. rewrite [flatten _]/= H4 cats0.\n          move => H5. subst. apply/orP. right.\n          rewrite H4 in IHvv.\n            by apply nfa_repeat_correct0.\n            move => H4.\n            apply/orP. right.\n              by apply: nfa_repeat_aux2.\n      Qed.\n\n      Lemma nfa_star_correct: dfa_lang nfa_star =i star (nfa_lang A1).\n      Proof.\n        move => w.\n        apply/idP/idP.\n          by move/nfa_star_aux1.\n            by move/nfa_star_aux2.\n      Qed.\n\n    End NFAOps.\n\n  End FA.\n\nEnd Automata.", "meta": {"author": "YaccConstructor", "repo": "YC_in_Coq", "sha": "d94a9ec10d532b86ae4f48871c38369f9ce5f1d8", "save_path": "github-repos/coq/YaccConstructor-YC_in_Coq", "path": "github-repos/coq/YaccConstructor-YC_in_Coq/YC_in_Coq-d94a9ec10d532b86ae4f48871c38369f9ce5f1d8/aut/automata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7002807899680004}}
{"text": "(** * Book I: Definitions and Axioms *)\n\nModule Euclid.\n\n(** ** Definitions *)\n\n(* We close the nat scope as we will want to use the addition operator for magnitudes. *)\nClose Scope nat_scope.\n\n(**** Coq Note\nWe move the notition of a magnitude to the start of this note.\n\nA magnitude appears in the form of length and angle. It should be thought of as a positive unit with equality , comparison and summation relations but no units of measurement.*)\n\n(** General Axioms\n-1. Things which are equal to the same thing are equal to one another.\n-2. If equals be added to equals, the wholes are equal.\n-3. If equals be taken from equals the remainders are equal.\n-4. If equals be added to unequals, the whole are unequal, the greater sum being that which includes the greater of the unequals.\n-5. If equals be taken from unequals, the remainders are unequal, the greater remainder being that which is left from the greater of the unequals.\n-6. Things which are doubles of the same thing, or of equal things, are equal to each other.\n-7. Things which are halves of the same thing, or of equal things, are equal to each other.\nThe eighth axiom is geometric in nature and has thus been placed later\n-9. The whole is greater than it's parts.\n*)\n\nClass Magnitude {M : Type} (add : M -> M -> M) (greaterThan : M -> M -> Prop): Type := {\n  general_axiom_1 : forall x y z : M, x=y -> x=z -> y=z;\n  general_axiom_2 : forall x1 x2 y1 y2 : M, x1=x2 -> y1=y2 -> (add x1 y1)=(add x2 y2);\n  general_axiom_3 : forall x1 x2 y1 y2 : M, x1=x2 -> (add x1 y1)=(add x2 y2) -> y1=y2;\n  general_axiom_4 : forall x1 x2 y1 y2 : M, x1=x2 -> y1<>y2 -> (add x1 y1)<>(add x2 y2);\n  general_axiom_4_1 : forall x1 x2 y1 y2 : M, x1=x2 -> greaterThan y1 y2 -> greaterThan (add x1 y1) (add x2 y2);\n  general_axiom_4_2 : forall x1 x2 y1 y2 : M, x1=x2 -> greaterThan y2 y1 -> greaterThan (add x2 y2) (add x1 y1);\n  general_axiom_5 : forall x1 x2 y1 y2 : M, x1=x2 -> (add x1 y1)<>(add x2 y2) -> y1<>y2;\n  general_axiom_5_1 : forall x1 x2 y1 y2 : M, x1=x2 -> greaterThan (add x1 y1) (add x2 y2) -> greaterThan y1 y2;\n  general_axiom_5_2 : forall x1 x2 y1 y2 : M, x1=x2 -> greaterThan (add x2 y2) (add x1 y1) -> greaterThan y2 y1;\n  general_axiom_6 : forall x y : M, x = y -> (add x x)=(add y y);\n  general_axiom_7 : forall x y : M, (add x x)=(add y y) -> x=y;\n  general_axiom_9 : forall x y : M, greaterThan (add x y) x;\n}.\n\n\n(**\n-1. A [Point] is that which has position, but no [Magnitude]\n*) \nDefinition Point : Type. Admitted.\n(**\n-2. A [Line] is that which has length without breadth \n*)\nDefinition Line : Type. Admitted.\n\nDefinition lineLength : Line -> Magnitude. Admitted.\n(**\n-3. The [extremities] of a [Line] are [Point]s, and the [intersection] of two [Line]s is a [Point]. \n*)\n\nDefinition extremals : Line -> Point * Point. Admitted.\n(* Helper funtion to see if a point is one of the extremals of a line. *) \nDefinition isExtremal (l : Line) (p : Point) : Prop :=\n  match (extremals l) with\n    | (p1, p2) => p1 = p /\\ p2 = p\n  end.\n\nDefinition intersection : Line -> Line -> Point -> Prop. Admitted.\n\n(** \n-4. A [StraightLine] is that which evenly between its extreme points. Any portion cut off from a straight line is called a segment of it.\n*)\nDefinition straightLine (l : Line) : Prop. Admitted.\n\n(* Set of helper types for a pair of line and proof of straightness *)\nInductive StraightLine : Type :=\n  straightLineCons (l : Line) : straightLine l -> StraightLine.\nDefinition line (s : StraightLine) : Line :=\n  match s with\n    | straightLineCons l _ => l\n  end.\n\nDefinition straightLineDeterminedByExtremals (p1 p2 q1 q2 : Point) \n                                 (l1 l2 : Line) : \n    straightLine l1 -> straightLine l2 -> \n    extremals l1 = (p1,p2) -> extremals l2 = (q1,q2) ->\n                              (p1 = q1) -> (p2 = q2) -> l1 = l2.\nAdmitted.\n\nDefinition segmentOf : StraightLine -> StraightLine -> Prop. Admitted.\n(**\n-5. A [Surface] (or superficies) is that which has length and breadth, but no thickness.\n*)\nDefinition Surface : Type. Admitted.\n\n(**\n-6. The boundaries of a [Surface] are [Line]s.\n*)\nDefinition surfaceBoundary : Surface -> list Line. Admitted.\n\n(**\n-7. A plane surface is one in which any [DistinctPoints] being taken the [Line] between them lies wholly in that [Surface]. A plane surface is frequently referred to as a [Plane].\n*)\nDefinition pointOnSurface : Point -> Surface -> Prop. Admitted.\nDefinition lineOnSurface : Line -> Surface -> Prop. Admitted.\n\nDefinition planeSurface (s : Surface) : Prop :=\n  forall (p1 p2 : Point) (l : Line),\n    pointOnSurface p1 s -> pointOnSurface p2 s ->\n    (p1 , p2) = extremals l -> straightLine l ->\n    lineOnSurface l s.\n\n(* Helper type for a pair of a surface and a proof that it is a plane *)\nInductive PlaneSurface : Type :=\n  plane (s : Surface) : planeSurface s -> PlaneSurface.\n\n(**\n-8. A plane angle is the inclination of two [Line]s to each other which meet together, but are not in the same direction.\n(Definition 8. is not required in Euclid's geometry the only angles employed by him being those formed by [StraightLine]s.\n*)\n\n(**\n-9. A plane rectilinear angle is the inclination of two [StraightLine]s to one another, which meet together, but are not in the same [StraightLine].\nThe [Point] at which the [StraightLine] meet is called the [vertex] of the angle, and the [StraightLine]s themselves the [arms] of the [Angle]. \n*)\n\n\nDefinition colinear (l1 l2 : StraightLine) : Prop :=\n  exists (l : StraightLine), (segmentOf l1 l) /\\ (segmentOf l2 l).\n\nInductive Angle : Type :=\n  angle (l1 l2 : StraightLine) (p : Point) : \n       not (colinear l1 l2) -> isExtremal (line l1) p -> isExtremal (line l2) p -> Angle.\n\nDefinition vertex (a : Angle) : Point :=\n  match a with\n    angle _ _ p _ _ _ => p\n  end.\n\nDefinition arms (a : Angle) : StraightLine * StraightLine :=\n  match a with\n    angle l1 l2 _ _ _ _ => (l1, l2)\n  end.\n\n(**** Note.\nWhen there are several [Angle]s at one [Point] each is expressed by three letters, of which the letter that refers to the vertex is put between the other two.\nThus the angle contained by the [StraightLine]s OA, OB is named the angle AOB or BOA; and the angle contained by OA, OC is named the angle AOC or COA.\nBut if there is only one [Angle] at a [Point], it may be expressed by a single letter, as the angle at O.\n\nOf the two [StraightLine]s OB, OC shewn in the adjoining diagram, we recognize that OC is more inclined than OB to the [StraightLine] OA : this we express by saying that the [Angle] AOC is greater thn the angle AOB.\nThus the [Angle] must be regarded as having a [Magnitude].\n*)\nDefinition angleMagnitude : Angle -> Magnitude. Admitted.\n\n(**\nIt must be carefully observed that the size of an angle in no way depends on the length of its arms, but only on their inclination to one another.\nThe angle AOC is the sum of the angles AOB and BOC; and AOB is the difference of the angles AOC and BOC.\n*)\n\n(* Add comment as to the formation of this definition *)\nDefinition angleSum (a1 a2 asum : Angle) : Prop :=\n  match (arms a1, arms a2,arms asum) with\n    | ((l1,l2), (l3,l4), (l5,l6)) => vertex a1 = vertex a2\n                                     /\\ vertex a1 = vertex asum\n                                     /\\ colinear l2 l3\n                                     /\\ colinear l1 l4\n                                     /\\ colinear l2 l5\n  end.\n\n(* Implicit assertation that the sum of angles goes to the sum of magnitudes *)\nDefinition angleSumToMagSum (a1 a2 asum : Angle) :\n  angleSum a1 a2 asum -> \n       (angleMagnitude a1 + angleMagnitude a2) = angleMagnitude asum.\nAdmitted.\n\n(* Helper defintions for when [Angle]s are equal in magnitude *)\nDefinition equalAngleMagnitude (a1 a2 : Angle) : Prop :=\n  angleMagnitude a1 = angleMagnitude a2.\n\nDefinition angleGreaterEqual (a1 a2 : Angle) : Prop :=\n  ex (fun adiff => angleSum a1 adiff a2). \n\n(* Helper defintions for when [Angle]s are greater than or equal in magnitude *)\nDefinition greaterEqualAngleMagnitude (a1 a2 : Angle) : Prop :=\n  angleMagnitude a1 <= angleMagnitude a2.\n\n\n\n\n\n(** ( Another view of an [Angle] is recognized in many branches of mathematics; and though not employed by Euclid, it is here given because it furnishes more clearly than any other a conception of what is meant by the [Magnitude] of an [Angle].\nSuppose that the [StraightLine] OP in the diagram is capable of revolution about the [Point] O like the hands of a watch, but in the opposite direction; and suppose that in this way it has passed successively from the positions OA to the positions occupied by OB and OC. Such a [Line] must have undergone more turning in passing from OA to OC than in passing from OA to OB; and consequently the [Angle] AOC is said to be greater than the [Angle] AOB. )  *)\n\n(** \n[Angle]s which lie on either side of a common arm are called [adjacent] angles.\nFor example, when one [StraightLine] OC is drawn from a [Point] in another [StraightLine] AB, the angles COA, COB are adjacent.\n*)\n\nDefinition adjancent (a1 a2 : Angle) : Prop :=\n  ex (fun asum => angleSum a1 a2 asum).\n \n(**\nWhen two [StraightLine]s, such as AB, CD, cross one another at E the two [Angle]s CEA, BED are said to be vertically opposite.\nThe two [Angle]s CEB, AED are also vertically opposite to one another.\n*)\n\n(* Define a helper method wherre we make explicit the lines we assue exist*)\nDefinition verticallyOppositeLines' (a1 a2 : Angle) (lA lB : StraightLine) : Prop :=\n  match (arms a1, arms a2) with\n    | ((l1,l2),(l3,l4)) => vertex a1 = vertex a2\n                        /\\ segmentOf l1 lA\n                        /\\ segmentOf l2 lB\n                        /\\ segmentOf l3 lA\n                        /\\ segmentOf l4 lB\n  end.\n\nDefinition verticallyOpposite (a1 a2 : Angle) : Prop :=\n  ex (fun lA => ex (fun lB => verticallyOppositeLines' a1 a2 lA lB)).\n\n(**\n-10. When a [StraightLine] standing on another makes the [adjancent] [Angle]s equal to one another, each of the [Angle]s is called a [rightAngle]; and the [StraightLine] which stands on the other is called [perpendicular] to it.\n*)\n\n(* Define helper method which add extra lines which are assumed to exist *)\nDefinition perpendicularDiagram (lBase lStanding : StraightLine) (pMeeting : Point) : Prop :=\n  intersection lBase lStanding pMeeting\n  /\\ isExtremal lStanding pMeeting\n  /\\ not (isExtremal lBase pMeeting) \n  /\\ not (colinear lBase lStanding)\n  \n(* To pove we can form an angle need to prove that \n\nDefinition rightAngle (a : Angle) : Prop :=\n  ex (\n", "meta": {"author": "robertgoss", "repo": "euclids-elements", "sha": "cd11822e862952332c3621d79d9ce17403a5e52e", "save_path": "github-repos/coq/robertgoss-euclids-elements", "path": "github-repos/coq/robertgoss-euclids-elements/euclids-elements-cd11822e862952332c3621d79d9ce17403a5e52e/coq/BookIDefinitionsandAxioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7002807880810608}}
{"text": "Require Import Nat Arith.\n\nInductive Lst : Type := cons : nat -> Lst -> Lst |  nil : Lst.\n\nFixpoint append (append_arg0 : Lst) (append_arg1 : Lst) : Lst\n           := match append_arg0, append_arg1 with\n              | nil, x => x\n              | cons x y, z => cons x (append y z)\n              end.\n\nTheorem theorem0 : forall (x : Lst), eq x (append x nil).\nProof.\n   intros.\n   induction x.\n   - simpl. rewrite <- IHx. reflexivity.\n   - simpl. reflexivity.\nQed.\n\n", "meta": {"author": "qsctr", "repo": "coq-quantified-theorems", "sha": "d3456ea0a70121e8de87956b45349aa7b943e37d", "save_path": "github-repos/coq/qsctr-coq-quantified-theorems", "path": "github-repos/coq/qsctr-coq-quantified-theorems/coq-quantified-theorems-d3456ea0a70121e8de87956b45349aa7b943e37d/benchmarks/list_append_nil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7002807787946481}}
{"text": "(** * 6.822 Formal Reasoning About Programs, Spring 2020 - Pset 2 *)\n\n(*\nAuthor: Samuel Gruetter <gruetter@mit.edu>\n\nThis PSet will introduce you to one of the major applications of formal reasoning\nabout programs: proving that an optimized program behaves the same as a simple program.\n\nImagine you're writing a program which needs a some function F. You know how to implement\nF naively, but as you run your program, you notice that it spends a lot of time in\nthe function F. You find a library which claims to provide a very efficient implementation\nof F, but looking at its source code, you don't really understand why this code should\ncalculate F, and you've seen some bug reports against previous versions of the library,\nso you can't really know whether this library implements F correctly.\nSince you care a lot about writing a correct program, you finally decide to keep using\nyour naive slow implementation.\nFormal reasoning about programs to the rescue! If the authors of the library want to\nincrease the user's trust in their library, they can include the naive but simple-to-\nunderstand version of F in their library as well, and write a proof that for all possible\ninputs, the optimized version of F returns the same value as the simple version of F.\nIf that proof is in a machine-checkable format (e.g. in a Coq file), the library users do\nnot need to understand the implementation of the optimized F, nor the body of the proof,\nbut can still use the optimized F and be sure that it does the same as the simple\nimplementation, as long as they trust the proof checker.\n\nIn this PSet, we will put you in the role of the library author who writes a naive\nversion of F, an optimized implementation of F, and a proof that the two of them behave\nthe same.\n*)\n\n\nRequire Import Coq.NArith.NArith. Open Scope N_scope.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.micromega.Lia.\nRequire Import Frap.Frap.\nRequire Import Pset2Sig.\nSet Default Goal Selector \"!\".\n\n(* Each of the exercises below is worth some number of points.\n   If you just want to enjoy the proof hacking without getting distracted by points,\n   feel free to ignore these points. On the other hand, if you want to know how\n   many points each exercise earns you, you can find the points in Pset2Sig.v. *)\n\n\n(* Recursive functions *)\n(* ******************* *)\n\n(* We will need some recursive functions in this PSet. Defining recursive functions in Coq can be\n   a bit tricky, because Coq only accepts recursive functions for which it believes that they always\n   terminate.\n   For natural numbers represented as \"nat\", and for data structures like the abstract syntax trees\n   we saw in class, recursive functions can usually be defined using \"Fixpoint\", because each\n   recursive call is with an argument which is a subterm of the original argument, which is required\n   for Coq to be convinced that the recursive function terminates.\n   In this pset, however, we will use the binary representation of natural numbers, which is\n   called \"N\" in Coq. If we wanted to use a Fixpoint and call it with, e.g. the binary number\n   11001101, we could only make recursive calls with 1001101.\n   What we want in this Pset, however, is to make recursive calls with the one less than the argument,\n   i.e. with 11001100 in this example.\n   For this kind of recursion, which does not follow the structure of the data, we use the\n   following pattern: *)\n\nDefinition fact: N -> N :=\n  recurse by cases\n  | 0 => 1\n  | n + 1 => (n + 1) * recurse\n  end.\n\n(* This pattern can only define functions recursing over a natural number with base case 0, and\n   one recursive case where the recursive call is for one less than the argument.\n   The above function implements factorial, i.e. \"fact n = 1 * 2 * ... * n\".\n   In the recursive case, you can use the word \"recurse\" to refer to the result of the recursive\n   call. *)\n\n(* Let's compute the first few values of fact: *)\nCompute fact 0.\nCompute fact 1.\nCompute fact 2.\nCompute fact 3.\nCompute fact 4.\n\n(* Aside: If you don't like the above Notation and want to see the real definition, you can do this:\nClose Scope N_recursion_scope.\nPrint fact.\n*)\n\n(* Instead of writing \"(fact x)\" all the time, it's more convenient to just write \"x!\",\n   so we make a Notation for this: *)\nLocal Notation \"x !\" := (fact x) (at level 12, format \"x !\").\n\n(* Exercise: Define a simple exponentiation function in the same style,\n   so that \"exp base n\" equals \"base^n\". *)\n\nDefinition exp(base: N): N -> N. Admitted.\n\n(* Once you define \"exp\", you can replace \"Admitted.\" below by \"Proof. equality. Qed.\" *)\nLemma test_exp_2_3: exp 2 3 = 8. Admitted.\nLemma test_exp_3_2: exp 3 2 = 9. Admitted.\nLemma test_exp_4_1: exp 4 1 = 4. Admitted.\nLemma test_exp_5_0: exp 5 0 = 1. Admitted.\nLemma test_exp_1_3: exp 1 3 = 1. Admitted.\n\n(* Here's another recursive function defined in the same style to apply a function f to\n   a range of values:\n   \"seq f len start\" computes the list [f start; f (start+1); ... f (start+len-1)] *)\nDefinition seq(f: N -> N): N -> N -> list N :=\n  recurse by cases\n  | 0 => fun start => []\n  | n + 1 => fun start => f start :: recurse (start + 1)\n  end.\n\nCompute (seq (fun x => x * x) 4 10).\n\n(* \"ith i l\" returns the i-th element of the list l.\n   To understand the recursion, note that \"ith i\" returns a function which takes a list and,\n   depending on whether i was 0 or not, returns the head of the list or the (i-1)-th element\n   of the tail.\n   If the index is out of bounds, it returns the default value 0. *)\nDefinition ith: N -> list N -> N :=\n  recurse by cases\n  | 0 => fun (l: list N) => match l with\n                            | h :: t => h\n                            | nil => 0\n                            end\n  | i + 1 => fun (l: list N) => match l with\n                                | h :: t => recurse t\n                                | nil => 0\n                                end\n  end.\n\n(* The standard library already contains a function called \"length\": *)\nCheck length.\n(* However, it returns a \"nat\", i.e., the representation of natural numbers using O and S,\n   which is very inefficient: To represent the number n, it needs roughly c*n bytes of RAM,\n   where c is some constant, whereas \"N\", the binary representation of natural numbers,\n   only used c*log(n) bytes of RAM.\n   Therefore, we redefine our own length function which returns an N: *)\nFixpoint len(l: list N): N :=\n  match l with\n  | [] => 0\n  | h :: t => 1 + len t\n  end.\n(* Note that since the recursion follows the structure of the data (the list) here,\n   we use Fixpoint instead of \"recurse by cases\". *)\n\n(* Here's a simple lemma: If we tell \"seq\" to return a list of length \"count\", it indeed does: *)\nLemma seq_len: forall f count start, len (seq f count start) = count.\nProof.\n  induct count; simplify.\n  - (* base case: count = 0 *)\n    equality.\n  - (* recursive case: assuming the statement holds for some \"count\", show that it\n       also holds for \"count + 1\".\n       This goal contains \"seq f (count + 1) start\", so we know that we're in the\n       recursive case of \"seq\", so we'd like to replace \"seq f (count + 1) start\"\n       by the recursive case we wrote in its definition.\n       Unfortunately, neither \"unfold seq\" nor \"simplify\" can do this, but the\n       tactic \"unfold_recurse F k\", where F is the function in question, and k\n       its argument, does the job: *)\n    unfold_recurse (seq f) count.\n    (* And here's a hint you'll need later: Sometimes, your goal won't exactly contain\n       (seq f (count + 1) start), but maybe (seq f someOtherExpression start), but you\n       still know that someOtherExpression is strictly greater than 0.\n       In such cases, if you want to use \"unfold_recurse\", you first have to run\n\n       replace someOtherExpression with (someOtherExpression - 1 + 1) by linear_arithmetic.\n\n       Note that if someOtherExpression could be 0, this won't work, because subtraction\n       on natural numbers in Coq returns 0 if the result is negative, so \"0 - 1 + 1\"\n       equals 1 in Coq's natural numbers, and linear_arithmetic can't prove \"0 = 1\"\n       for you! *)\n\n    simplify. rewrite IHcount. linear_arithmetic.\nQed.\n\n(* An here's another general hint: You don't always need induction.\n   Some lemmas in this pset can be solved using induction, but don't actually require it,\n   and are simpler to solve if you don't use induction, so before doing induction,\n   try to think where/if you would need an inductive hypothesis. *)\n\n(* Exercise: Prove that the i-th element of seq has the value we'd expect. *)\nLemma seq_spec: forall f count i start, i < count -> ith i (seq f count start) = f (start + i).\nProof.\n  induct count; simplify.\nAdmitted.\n\n(* Exercise: Prove that if the index is out of bounds, \"ith\" returns 0. *)\nLemma ith_out_of_bounds_0: forall i l, len l <= i -> ith i l = 0.\nProof.\nAdmitted.\n\n\n(* Binomial coefficients *)\n(* ********************* *)\n\n(* You might remember binomial coefficients from you math classes, which appear in many combinatorics\n   problems, and form the coefficients of the expansion of the polynomial (x + y)^n.\n   In math notation, they are defined as follows:\n\n      / n \\        n!\n      |   |  = ---------\n      \\ k /    (n-k)! k!\n\n   We can transcribe this to Coq as follows: *)\n\nDefinition C(n k: N): N := n! / ((n - k)! * k!).\n\n(* If we want to know how many ways there are to pick 2 items out of 4 items, we can compute this in Coq: *)\nCompute C 4 2.\n\n(* And here are the coefficients of the expansion of (x + y)^3: *)\nCompute [C 3 0; C 3 1; C 3 2; C 3 3].\n\n(* For larger numbers, however, this way of computing C becomes quite slow: If I do\n\nCompute C 1000 100.\n\n   it takes about 2 seconds on my computer. You can measure the time by putting \"Time\" in front of any command:\n\nTime Compute C 1000 100.\n\n   In the fraction defining C, there are many factors which appear both in the numerator and in the\n   denominator, so it seems that we should be able to cancel these out and write a more efficient\n   implementation of C. Here is one candidate: *)\n\nDefinition bcoeff(n: N): N -> N :=\n  recurse by cases\n  | 0 => 1\n  | k + 1 => recurse * (n - k) / (k + 1)\n  end.\n\n(* Now if we do\n\nTime Compute bcoeff 1000 100.\n\n   it only takes about 0.02 seconds on my computer, so we got a 100x speed improvement, yay!\n   But how do we know whether it's correct?\n   We could do some quick tests: *)\n\nCompute [bcoeff 3 0; bcoeff 3 1; bcoeff 3 2; bcoeff 3 3].\n\n(* This test produces the same values as for C, but we want to be sure that bcoeff will *always* produce\n   the same values as C, so let's prove it, i.e. let's show that\n\n   forall n k, k <= n -> bcoeff n k = C n k\n\n   We will do so further below, but we first need a few helper lemmas and techniques:\n\n   Many arithmetic goals in this Pset are linear, i.e. we there are only multiplications by\n   constants, but no multiplications of two variables.\n   For these linear arithmetic goals, the linear_arithmetic tactic works just fine, but for\n   some non-linear goals which will appear in this Pset, you can try the tactic \"nia\"\n   (which stands for \"non-linear integer arithmetic\"), but it does not always work, so\n   sometimes you will have to search for appropriate lemmas to apply manually.\n   For instance, to prove the following: *)\nGoal forall n m, n <> 0 -> m <> 0 -> n * m <> 0.\nProof.\n  simplify.\n  (* you could use the \"Search\" command with a pattern: *)\n  Search (_ * _ <> 0).\n  (* which outputs the name of a handy lemma we can apply: *)\n  apply N.neq_mul_0.\n  split; assumption.\n  (* (note that in this case \"nia\" would have worked as well, but in any case, it's good to know\n     the \"Search\" command. *)\nQed.\n\n(* Here's another example of how to use the \"Search\" command:\n   Suppose you have the goal *)\nGoal forall n, n <> 0 -> n / n = 1.\nProof.\n  simplify.\n  (* If we do \"Search (_ / _)\" we get a very long list, but if we do *)\n  Search (?x / ?x).\n  (* we force the two numbers on both sides of the / to be the same, and we only get the lemma we need: *)\n  apply N.div_same.\n  assumption.\nQed.\n\n(* Now we're ready to prove a few simple facts: *)\n\nLemma fact_nonzero: forall n, n! <> 0.\nProof.\nAdmitted.\n\nLemma Cn0: forall n, C n 0 = 1.\nProof.\nAdmitted.\n\nLemma Cnn: forall n, C n n = 1.\nProof.\nAdmitted.\n\n\n(* It's somewhat surprising that in the definition of C(n, k),\n\n      n!\n  -----------\n  (n - k)! k!\n\n  the denominator always divides the numerator.\n  The following lemma proves it. Note that \"(a | b)\" means \"a divides b\".\n  We provide the solution for you, so that you can step through it and use it as a\n  source of useful strategies you can apply in the exercises below.\n  Make sure to step through it and to understand each proof step! *)\nLemma C_is_integer: forall n k, k <= n ->\n    (((n - k)! * k!) | n!).\nProof.\n  induct n.\n  - simplify.\n    replace k with 0 by linear_arithmetic.\n    simplify.\n(* How can we prove that 1 divides 1? Probably it follows immediately from the definition of\n   divisibility, so let's try to unfold it:\n\n    unfold \"|\".\n\n   Unfortunately that fails (reported at https://github.com/coq/coq/issues/11420), but we can do\n\n    Locate \"|\".\n\n   The output of this command shows us all notations involving \"|\", and the last one (N.divide) is the one\n   we want. So we just unfold that one: *)\n    unfold N.divide.\n    exists 1. equality.\n  - simplify. unfold N.divide in *.\n    assert (k = 0 \\/ k = n + 1 \\/ 1 <= k <= n) as C by linear_arithmetic. cases C.\n    + subst.\n      replace (n + 1 - 0) with (n + 1) by linear_arithmetic.\n      replace (0!) with 1 by equality.\n      exists 1.\n      linear_arithmetic.\n    + subst.\n      replace (n + 1 - (n + 1)) with 0 by linear_arithmetic.\n      replace (0!) with 1 by equality.\n      exists 1. linear_arithmetic.\n    + pose proof (IHn k) as IH1.\n      assert (k <= n) as A by linear_arithmetic. specialize (IH1 A). invert IH1.\n      pose proof (IHn (k - 1)) as IH2.\n      assert (k - 1 <= n) as B by linear_arithmetic. specialize (IH2 B). invert IH2.\n      replace (n - (k - 1)) with (n - k + 1) in H1 by linear_arithmetic.\n      unfold_recurse fact n.\n      replace (k!) with ((k - 1 + 1)!) in *.\n      2: { f_equal. linear_arithmetic. }\n      unfold_recurse fact (k - 1).\n      replace (k - 1 + 1) with k in * by linear_arithmetic.\n      apply N.mul_cancel_r with (p := n - k + 1) in H0. 2: linear_arithmetic.\n      apply N.mul_cancel_r with (p := k) in H1. 2: linear_arithmetic.\n      assert (forall l1 r1 l2 r2, l1 = r1 -> l2 = r2 -> l1 + l2 = r1 + r2) as E. {\n        simplify. linear_arithmetic.\n      }\n      specialize E with (1 := H0) (2 := H1).\n      replace (n! * (n - k + 1) + n! * k) with ((n + 1) * n!) in E by nia.\n      rewrite E.\n      replace (n + 1 - k) with (n - k + 1) by linear_arithmetic.\n      unfold_recurse fact (n - k).\n      remember ((n - k)!) as F1.\n      remember ((k - 1)!) as F2.\n      remember (n - k + 1) as F3.\n      remember k as F4.\n      exists (x + x0).\n      nia.\nQed.\n\n(* Now we're ready to prove correctness of our optimized implementation bcoeff.\n   Since this is not a class about math, we're providing a paper proof of each proof step\n   of the inductive case:\n\n  C(n, k + 1)\n\n             n!\n= -----------------------\n  (n - (k + 1))! (k + 1)!\n\n             n!\n= -----------------------\n  (n - k - 1)! k! (k + 1)\n\n         n! (n - k)\n= -------------------------------\n  (n - k - 1)! (n - k) k! (k + 1)\n\n               n! (n - k)\n= ---------------------------------------\n  (n - k - 1)! (n - k - 1 + 1) k! (k + 1)\n\n          n! (n - k)\n= ---------------------------\n  (n - k - 1 + 1)! k! (k + 1)\n\n      n! (n - k)\n= -------------------\n  (n - k)! k! (k + 1)\n\n  n! (n - k)\n= ----------- / (k + 1)\n  (n - k)! k!\n\n      n!\n= ----------- * (n - k) / (k + 1)\n  (n - k)! k!\n\n= C(n, k) * (n - k) / (k + 1)\n\n= bcoeff(n, k) * (n - k) / (k + 1)\n\n= bcoeff(n, k + 1)\n\nYour task is to translate this proof into Coq!\n\nPotentially useful hint:\nNote that multiplication and division have the same operator priority, and both are left-associative, so\n   \"a / b * c / d\" is \"((a / b) * c) / d\", NOT \"(a / b) * (c / d)\"\n\nHere we go: *)\nLemma bcoeff_correct: forall n k, k <= n -> bcoeff n k = C n k.\nProof.\n  induct k.\nAdmitted.\n\n\n(* All binomial coefficients for a given n *)\n(* *************************************** *)\n\n(* In some applications, we need to know all binomal coefficients C(n,k) for a fixed n.\n   For instance, if we want to symbolically evaluate (x + y)^4, the result is\n\n   C(4,0)*x^4 + C(4,1)*x^3*y + C(4,2)*x^2*y^2 + C(4,3)*x*y^3 + C(4,4)*y^4\n\n   The simplest way to compute such lists would be to just use the C we defined above: *)\n\nDefinition all_coeffs_slow1(n: N): list N :=\n  (recurse by cases\n   | 0 => [1]\n   | k + 1 => C n (k + 1) :: recurse\n   end) n.\n\nCompute all_coeffs_slow1 0.\nCompute all_coeffs_slow1 1.\nCompute all_coeffs_slow1 2.\nCompute all_coeffs_slow1 3.\nCompute all_coeffs_slow1 4.\nCompute all_coeffs_slow1 5.\nCompute all_coeffs_slow1 15.\n(* However, this is not very efficient:\n\nTime Compute all_coeffs_slow1 100.\n\ntakes 0.8s on my machine *)\n\n(* We could use our more efficient bcoeff from above: *)\nDefinition all_coeffs_slow2(n: N): list N :=\n  (recurse by cases\n   | 0 => [1]\n   | k + 1 => bcoeff n (k + 1) :: recurse\n   end) n.\n\nCompute all_coeffs_slow2 5.\nCompute all_coeffs_slow2 15.\n(* This is faster:\n\n   Time Compute all_coeffs_slow2 100.\n\ntakes 0.2s on my machine and\n\n  Time Compute all_coeffs_slow2 200.\n\ntakes 1.7 s on my machine.\n\nBut we can do even better by using Pascal's triangle:\n\n      1\n     1 1\n    1 2 1\n   1 3 3 1\n  1 4 6 4 1\n\nYou can observe that the i-th row of this triangle is the result of \"all_coeffs_slow1 i\",\nand that each value not at the boundary of the triangle is the sum of the values to\nits upper left and its upper right. For instance, the 6 in the last row is the sum of the\ntwo 3s above it.\nMore formally, we can state this as follows: *)\nDefinition Pascal's_rule: Prop := forall n k,\n    1 <= k <= n ->\n    C (n+1) k = C n (k - 1) + C n k.\n(* Note that the above is only a definition which gives a name to this proposition,\n   but not a lemma.\n   We don't ask you to prove it, but it's a fun optional exercise, have a look at the\n   end of this file if you're interested! *)\n\n(* The following function takes in a line of Pascal's triangle and computes the line below it: *)\nDefinition nextLine(l: list N): list N :=\n  1 :: seq (fun k => ith (k - 1) l + ith k l) (len l) 1.\n\nCompute nextLine [1; 3; 3; 1].\nCompute nextLine (nextLine [1; 3; 3; 1]).\n\n(* This allows us to define a faster all_coeffs function: *)\nDefinition all_coeffs_fast: N -> list N :=\n  recurse by cases\n  | 0 => [1]\n  | n + 1 => nextLine recurse\n  end.\n\n(* Time Compute all_coeffs_fast 200. takes 0.35s on my computer *)\n\n\n(* Exercise: Let's prove that all_coeffs_fast is correct.\n   Note that you can assume Pascal's rule to prove this. *)\nLemma all_coeffs_fast_correct:\n  Pascal's_rule ->\n  forall n k,\n    k <= n ->\n    ith k (all_coeffs_fast n) = C n k.\nProof.\nAdmitted.\n\n(* ----- THIS IS THE END OF PSET2 ----- All exercises below this line are optional. *)\n\n(* Optional exercise: Let's prove that Pascal's rule holds.\n   On paper, this can be proved as follows, but feel free to ignore this if you want\n   the full challenge!\n\n   C(n, k-1) + C(n, k)\n\n           n!                 n!\n= --------------------- + -----------\n  (n - k + 1)! (k - 1)!   (n - k)! k!\n\n              n!                          n!\n= ----------------------------- + -------------------\n  (n - k)! (n - k + 1) (k - 1)!   (n - k)! k (k - 1)!\n\n               n! k                          n! (n - k + 1)\n= ------------------------------- + -------------------------------\n  (n - k)! (n - k + 1) (k - 1)! k   (n - k)! k (k - 1)! (n - k + 1)\n\n         n! (k + n - k + 1)\n= -------------------------------\n  (n - k)! (n - k + 1) (k - 1)! k\n\n    (n + 1)!\n= ---------------\n  (n - k + 1)! k!\n\n= C(n+1, k)\n*)\nLemma Pascal's_rule_holds: Pascal's_rule.\nProof.\n  unfold Pascal's_rule.\n\n  (* Note: Proving\n       a     b     a+b\n      --- + --- =  ---\n       c     c      c\n     is a bit trickier than you might expect, because we're using integer division here.\n     So, for instance,\n      1     3                                                              1+3\n     --- + ---   equals 0 + 1 in round-down integer division, which is not ---\n      2     2                                                               2\n     To make sure this rule holds, we must also require that c and b both divide a: *)\n  assert (forall a b c, c <> 0 -> (c | a) -> (c | b) -> a / c + b / c = (a + b) / c)\n    as add_fractions. {\n    clear.\n    simplify.\n    unfold N.divide in *. invert H0. invert H1.\n    rewrite N.div_mul by assumption.\n    rewrite N.div_mul by assumption.\n    replace (x * c + x0 * c) with ((x + x0) * c) by nia.\n    rewrite N.div_mul by assumption.\n    reflexivity.\n  }\n\nAdmitted.\n\n\n(* Optional exercise:\n   all_coeffs_fast is still not as fast as it could be, because nextLine uses ith\n   to access the elements of the previous line, and each invocation of ith takes\n   linear time in i.\n   It would be more efficient to implement nextLine as a recursive function\n   which iterates through the previous line just once and computes the next line\n   on the fly.\n   Define such a nextLine' function, and then use it to define all_coeffs_faster,\n   observe how it's even faster than all_coeffs_fast, and finally, prove that\n   it's correct. *)\n\nDefinition nextLine'(l: list N): list N. Admitted.\n\nDefinition all_coeffs_faster: N -> list N. Admitted.\n\nLemma all_coeffs_faster_correct: forall n k,\n    k <= n ->\n    ith k (all_coeffs_faster n) = C n k.\nProof.\nAdmitted.\n", "meta": {"author": "mit-frap", "repo": "spring20", "sha": "dcf3f6a6d41373c8df89bbda98b941e49f22e50c", "save_path": "github-repos/coq/mit-frap-spring20", "path": "github-repos/coq/mit-frap-spring20/spring20-dcf3f6a6d41373c8df89bbda98b941e49f22e50c/pset02_BinomialCoefficients/Pset2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.8887588023318196, "lm_q1q2_score": 0.7002807769077083}}
{"text": "\n(*************************************************************)\n(*      This file is distributed under the terms of the      *)\n(*      GNU Lesser General Public License Version 2.1        *)\n(*************************************************************)\n(*    Benjamin.Gregoire@inria.fr Laurent.Thery@inria.fr      *)\n(*************************************************************)\n\n(**********************************************************************\n    Proth.v\n\n    Proth's Test\n\n    Definition: ProthTest\n **********************************************************************)\nRequire Import ZArith.\nRequire Import ZCAux.\nRequire Import Pocklington.\n\nOpen Scope Z_scope.\n\nTheorem ProthTest: forall h k a, let n := h * 2 ^ k + 1 in 1 < a -> 0 < h < 2 ^k -> (a ^ ((n - 1) / 2) + 1) mod n = 0 -> prime n.\nintros h k a n; unfold n; intros H H1 H2.\nassert (Hu: 0 < h * 2 ^ k).\napply Zmult_lt_O_compat; auto with zarith.\nassert (Hu1: 0 < k).\ncase (Zle_or_lt k 0); intros Hv; auto.\ngeneralize H1 Hv; case k; simpl.\nintros (Hv1, Hv2); contradict Hv2; auto with zarith.\nintros p1 _ Hv1; contradict Hv1; auto with zarith.\nintros   p (Hv1, Hv2); contradict Hv2; auto with zarith.\napply PocklingtonCorollary1 with (F1 := 2 ^ k) (R1 := h). 1-2: auto with zarith.\nring.\napply Z.lt_le_trans with ((h + 1) * 2 ^ k). 2: auto with zarith.\nrewrite Zmult_plus_distr_l; apply Zplus_lt_compat_l.\nrewrite Zmult_1_l; apply Z.lt_le_trans with 2; auto with zarith.\nintros p H3 H4.\ngeneralize H2; replace (h * 2 ^ k + 1 - 1) with (h * 2 ^k) by auto with zarith; clear H2; intros H2.\nexists a; split; auto; split.\npattern (h * 2 ^k) at 1; rewrite (Zdivide_Zdiv_eq  2 (h * 2 ^ k)). 2: auto with zarith.\nrewrite (Zmult_comm 2); rewrite Zpower_mult. 3: auto with zarith.\nrewrite Zpower_mod by auto with zarith.\nassert (tmp: forall p, p = (p + 1) -1) by auto with zarith; rewrite (fun x => (tmp (a ^ x))).\nrewrite Zminus_mod by auto with zarith.\nrewrite H2.\nrewrite (Zmod_small 1) by auto with zarith.\nrewrite <- Zpower_mod by auto with zarith.\nrewrite Zmod_small. auto with zarith.\nsimpl; unfold Zpower_pos; simpl; auto with zarith.\napply Z_div_pos; auto with zarith.\napply Z.divide_trans with (2 ^ k).\napply Zpower_divide; auto with zarith.\napply Zdivide_factor_l; auto with zarith.\napply Zis_gcd_gcd. auto with zarith.\napply Zis_gcd_intro. 1-2: auto with zarith.\nintros x HD1 HD2.\nassert (Hd1: p = 2).\napply prime_div_Zpower_prime with (4 := H4). 1-2: auto with zarith.\napply prime_2.\nassert (Hd2: (x | 2)).\nreplace 2 with ((a ^ (h * 2 ^ k / 2) + 1) - (a ^ (h * 2 ^ k/ 2) - 1)) by auto with zarith.\napply Zdivide_minus_l; auto.\napply Z.divide_trans with (1 := HD2).\napply Zmod_divide; auto with zarith.\npattern 2 at 2; rewrite <- Hd1; auto.\nreplace 1 with ((h * 2 ^k + 1) - (h * 2 ^ k)) by auto with zarith.\napply Zdivide_minus_l; auto.\napply Z.divide_trans with (1 := Hd2); auto.\napply Z.divide_trans with (2 ^ k).\napply Zpower_divide; auto with zarith.\napply Zdivide_factor_l; auto with zarith.\nQed.\n\n\nDefinition proth_test h k a :=\n  let n := h * 2 ^ k + 1 in\n   if (Z_lt_dec 1  a) then\n      if (Z_lt_dec 0 h) then\n        if (Z_lt_dec h (2 ^k)) then\n            if Z.eq_dec (Zpow_mod a  ((n - 1) / 2) n) (n - 1) then true\n            else false else false else false else false.\n\n\nTheorem ProthTestOp: forall h k a, proth_test h k a = true -> prime (h * 2 ^ k + 1).\nintros h k a; unfold proth_test.\nrepeat match goal with |- context[if ?X then _ else _] => case X end; try (intros; discriminate).\nintros H1 H2 H3 H4 _.\nassert (Hu: 0 < h * 2 ^ k).\napply Zmult_lt_O_compat; auto with zarith.\napply ProthTest with (a := a); auto.\nrewrite Zplus_mod; auto with zarith.\nrewrite <- Zpow_mod_Zpower_correct; auto with zarith.\nrewrite H1.\nrewrite (Zmod_small 1); auto with zarith.\nreplace (h * 2 ^ k + 1 - 1 + 1) with (h * 2 ^ k + 1); auto with zarith.\napply Zdivide_mod; auto with zarith.\napply Z_div_pos; auto with zarith.\nQed.\n\nTheorem prime5: prime 5.\nexact (ProthTestOp 1 2 2 (refl_equal _)).\nQed.\n\nTheorem prime17: prime 17.\nexact (ProthTestOp 1 4 3 (refl_equal _)).\nQed.\n\nTheorem prime257:  prime 257.\nexact (ProthTestOp 1 8 3 (refl_equal _)).\nQed.\n\nTheorem prime65537:  prime 65537.\nexact (ProthTestOp 1 16 3 (refl_equal _)).\nQed.\n\n(* Too tough !!\nTheorem prime4294967297:  prime 4294967297.\nexact (ProthTestOp 1 32 3 (refl_equal _)).\nQed.\n*)\n", "meta": {"author": "thery", "repo": "coqprime", "sha": "431d7a66877cbe8688fc8864ef892369401440e1", "save_path": "github-repos/coq/thery-coqprime", "path": "github-repos/coq/thery-coqprime/coqprime-431d7a66877cbe8688fc8864ef892369401440e1/src/Coqprime/PrimalityTest/Proth.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7002807741514415}}
{"text": "Require Import XR_R.\nRequire Import XR_Rsqr.\nRequire Import XR_Rminus.\nRequire Import XR_Rmult_comm.\nRequire Import XR_Rsqr_minus_plus.\n\nLocal Open Scope R_scope.\n\nLemma Rsqr_plus_minus : forall a b:R, (a + b) * (a - b) = Rsqr a - Rsqr b.\nProof.\n  intros x y.\n  rewrite Rmult_comm.\n  apply Rsqr_minus_plus.\nQed.\n", "meta": {"author": "xavierdpt", "repo": "research", "sha": "de47f996cbb40312e21057fa343ed8346f8cb39f", "save_path": "github-repos/coq/xavierdpt-research", "path": "github-repos/coq/xavierdpt-research/research-de47f996cbb40312e21057fa343ed8346f8cb39f/coq/XReals/XR_Rsqr_plus_minus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.700195959347568}}
{"text": "(** Generated by coq-of-ocaml *)\nRequire Import OCaml.OCaml.\n\nLocal Set Primitive Projections.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope type_scope.\nImport ListNotations.\n\nUnset Positivity Checking.\nUnset Guard Checking.\n\nInductive nat : Set :=\n| O : nat\n| S : nat -> nat.\n\nInductive natural : Set :=\n| Zero : natural\n| Succ : natural -> natural.\n\nFixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}\n  : natural :=\n  match plus_arg0 with\n  | Zero => plus_arg1\n  | Succ n => Succ (plus n plus_arg1)\n  end.\n\nFixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}\n  : natural :=\n  match mult_arg0 with\n  | Zero => Zero\n  | Succ n => plus (mult n mult_arg1) mult_arg1\n  end.\n\nDefinition synth (y : natural) (lf2 : natural) (lf1 : natural) : natural :=\n  plus lf1 Zero.\n", "meta": {"author": "yalhessi", "repo": "lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "save_path": "github-repos/coq/yalhessi-lemmaranker", "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal33_mult_succ_82_plus_assoc/goal33conj33_coqofml_husfwO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7001959587049471}}
{"text": "From mathcomp Require Import all_ssreflect all_algebra.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport intZmod.\nImport intOrdered.\nImport GRing.Theory.\nOpen Scope ring_scope.\n\nSection Reversible.\n  Definition enc1 (m n:int) := m - n.\n  Definition enc2 (m n:int) := ((m + n) %/ 2)%Z.\n\n  Definition dec1 (e1: int) (e2: int) := ((e1 + e2 * 2 + 1) %/2)%Z.\n  Definition dec2 (e1: int) (e2: int) := dec1 e1 e2 - e1.\n \n  Lemma addmn (m n:int) : (m + (- n) + m + n) = m * (2:int).\n  Proof.\n    rewrite addrC.\n    rewrite [m + (-n) + m]addrC.\n    rewrite [m + (m + (-n))]addrA.\n    rewrite [m + m + (-n)]addrC addrA.\n    rewrite addrN add0r.\n    rewrite -{1}[m]mulr1.\n    rewrite -{2}[m]mulr1.\n    rewrite -mulrDr //=.\n  Qed.\n\n\n  Lemma divmn (d:int) : d - (d %% 2)%Z = (d %/ 2)%Z * 2.\n  Proof.\n    apply/subr0_eq.\n    rewrite -opprB.\n    rewrite [-(d - (d %% 2)%Z)]opprB addrA.\n    rewrite -divz_eq //=.\n    rewrite opprB.\n    rewrite addrN //.\n  Qed.\n\n  Lemma lezrl (n m:int): lez n m = (n <= m).\n  Proof.\n    rewrite /lez //=.\n  Qed.\n\n  Lemma ltzrl (n m:int): ltz n m = (n < m).\n  Proof.\n    rewrite /ltz //=.\n  Qed.\n\n  Lemma lt_d_1 (d:int) : (d %% 2)%Z <= 1 .\n  Proof.\n    have lt_2 : (d %% 2)%Z < `|Posz 2| .\n    - rewrite ltz_mod //.\n    have eq_2 : `|Posz 2| = Posz 2.\n    - by [].\n    have eq_21 : (d %% 2)%Z < 2 .\n    - rewrite -{2}eq_2 lt_2 //\n    rewrite ltz_mod //.\n    rewrite -ltz_add1r //.\n  Qed.\n\n  Lemma modDiv0 (d:int) : ((1 - (d %% 2)%Z) %/ 2)%Z = 0%Z.\n  Proof.\n    rewrite divz_small //.\n    (* 0 <= 1 - (d %% 2)%Z < `|2|%N *)\n    rewrite -lezrl subz_ge0 lezrl lt_d_1 /=.\n    rewrite -lez_add1r addrA.\n    rewrite -lezrl -subz_ge0 lezrl.\n    have eq_2 : 1 + 1 = (2:int).\n    - by [].\n    have eq0_2 : (2:int) + (-(2:int)) = 0.\n    - by [].\n    rewrite addrC opprB /=.\n    rewrite eq_2.\n    rewrite [(d %% 2)%Z + (-(2:int))]addrC addrC addrA eq0_2.\n    rewrite add0r.\n    rewrite modz_ge0 //.\n  Qed.\n\n  Theorem dec1_correct (m n :int): dec1 (enc1 m n) (enc2 m n) = m.\n  Proof.\n    rewrite /dec1 /enc1 /enc2.\n    rewrite -divmn.\n    rewrite !addrA.\n    rewrite [m - n + m + n]addmn.\n    have divrMDl2 (m0: int): ((m * (Posz 2) + m0) %/ (Posz 2))%Z = m + (m0 %/ (Posz 2))%Z.\n    - rewrite divzMDl //.\n    rewrite {1}addrC !addrA.\n    rewrite [1 + m * 2]addrC.\n    set mn := - ((m + n) %% 2)%Z.\n    rewrite -/mn.\n    set mn1 := 1 + mn.\n    rewrite addrC addrA.\n    rewrite addrC addrA.\n    rewrite -/mn1.\n    rewrite addrC.\n    rewrite divrMDl2.\n    rewrite /mn1 /mn modDiv0.\n    rewrite addr0 //.\n  Qed.\n\n  Theorem dec2_correct (m n :int): dec2 (enc1 m n) (enc2 m n) = n.\n  Proof.\n    rewrite /dec2.\n    rewrite dec1_correct /enc1.\n    rewrite [-(m - n)]opprB addrA.\n    rewrite addrC addrA addNr add0r //.\n  Qed.\nEnd Reversible.\n", "meta": {"author": "junjihashimoto", "repo": "coq-elgamal", "sha": "671a6c93a0ee60b4a7b40928579252357489245d", "save_path": "github-repos/coq/junjihashimoto-coq-elgamal", "path": "github-repos/coq/junjihashimoto-coq-elgamal/coq-elgamal-671a6c93a0ee60b4a7b40928579252357489245d/Haar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7001445171324804}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat div seq choice fintype.\nRequire Import finfun bigop prime binomial.\n\n(******************************************************************************)\n(*   The algebraic part of the Algebraic Hierarchy, as described in           *)\n(*          ``Packaging mathematical structures'', TPHOLs09, by               *)\n(*   Francois Garillot, Georges Gonthier, Assia Mahboubi, Laurence Rideau     *)\n(*                                                                            *)\n(* This file defines for each Structure (Zmodule, Ring, etc ...) its type,    *)\n(* its packers and its canonical properties :                                 *)\n(*                                                                            *)\n(*  * Zmodule (additive abelian groups):                                      *)\n(*              zmodType == interface type for Zmodule structure.             *)\n(* ZmodMixin addA addC add0x addNx == builds the mixin for a Zmodule from the *)\n(*                          algebraic properties of its operations.           *)\n(*          ZmodType V m == packs the mixin m to build a Zmodule of type      *)\n(*                          zmodType. The carrier type V must have a          *)\n(*                          choiceType canonical structure.                   *)\n(* [zmodType of V for S] == V-clone of the zmodType structure S: a copy of S  *)\n(*                          where the sort carrier has been replaced by V,    *)\n(*                          and which is therefore a zmodType structure on V. *)\n(*                          The sort carrier for S must be convertible to V.  *)\n(*       [zmodType of V] == clone of a canonical zmodType structure on V.     *)\n(*                          Similar to the above, except S is inferred, but   *)\n(*                          possibly with a syntactically different carrier.  *)\n(*                     0 == the zero (additive identity) of a Zmodule.        *)\n(*                 x + y == the sum of x and y (in a Zmodule).                *)\n(*                   - x == the opposite (additive inverse) of x.             *)\n(*                 x - y == the difference of x and y; this is only notation  *)\n(*                          for x + (- y).                                    *)\n(*                x *+ n == n times x, with n in nat (non-negative), i.e.,    *)\n(*                          x + (x + .. (x + x)..) (n terms); x *+ 1 is thus  *)\n(*                          convertible to x, and x *+ 2 to x + x.            *)\n(*                x *- n == notation for - (x *+ n), the opposite of x *+ n.  *)\n(*        \\sum_<range> e == iterated sum for a Zmodule (cf bigop.v).          *)\n(*                  e`_i == nth 0 e i, when e : seq M and M has a zmodType    *)\n(*                          structure.                                        *)\n(*             support f == 0.-support f, i.e., [pred x | f x != 0].          *)\n(*         oppr_closed S <-> collective predicate S is closed under opposite. *)\n(*         addr_closed S <-> collective predicate S is closed under finite    *)\n(*                           sums (0 and x + y in S, for x, y in S).          *)\n(*         zmod_closed S <-> collective predicate S is closed under zmodType  *)\n(*                          operations (0 and x - y in S, for x, y in S).     *)\n(*                          This property coerces to oppr_pred and addr_pred. *)\n(*         OpprPred oppS == packs oppS : oppr_closed S into an opprPred S     *)\n(*                          interface structure associating this property to  *)\n(*                          the canonical pred_key S, i.e. the k for which S  *)\n(*                          has a Canonical keyed_pred k structure (see file  *)\n(*                          ssrbool.v).                                       *)\n(*         AddrPred addS == packs addS : addr_closed S into an addrPred S     *)\n(*                          interface structure associating this property to  *)\n(*                          the canonical pred_key S (see above).             *)\n(*         ZmodPred oppS == packs oppS : oppr_closed S into an zmodPred S     *)\n(*                          interface structure associating the zmod_closed   *)\n(*                          property to the canonical pred_key S (see above), *)\n(*                          which must already be an addrPred.                *)\n(* [zmodMixin of M by <:] == zmodType mixin for a subType whose base type is  *)\n(*                          a zmodType and whose predicate's canonical        *)\n(*                          pred_key is a zmodPred.                           *)\n(* --> Coq can be made to behave as if all predicates had canonical zmodPred  *)\n(*     keys by executing Import DefaultKeying GRing.DefaultPred. The required *)\n(*     oppr_closed and addr_closed assumptions will be either abstracted,     *)\n(*     resolved or issued as separate proof obligations by the ssreflect      *)\n(*     plugin abstraction and Prop-irrelevance functions.                     *)\n(*  * Ring (non-commutative rings):                                           *)\n(*              ringType == interface type for a Ring structure.              *)\n(* RingMixin mulA mul1x mulx1 mulDx mulxD == builds the mixin for a Ring from *)\n(*                           the algebraic properties of its multiplicative   *)\n(*                           operators; the carrier type must have a zmodType *)\n(*                           structure.                                       *)\n(*           RingType R m == packs the ring mixin m into a ringType.          *)\n(*                    R^c == the converse Ring for R: R^c is convertible to R *)\n(*                           but when R has a canonical ringType structure    *)\n(*                           R^c has the converse one: if x y : R^c, then     *)\n(*                           x * y = (y : R) * (x : R).                       *)\n(*  [ringType of R for S] == R-clone of the ringType structure S.             *)\n(*        [ringType of R] == clone of a canonical ringType structure on R.    *)\n(*                      1 == the multiplicative identity element of a Ring.   *)\n(*                   n%:R == the ring image of an n in nat; this is just      *)\n(*                           notation for 1 *+ n, so 1%:R is convertible to 1 *)\n(*                           and 2%:R to 1 + 1.                               *)\n(*                  x * y == the ring product of x and y.                     *)\n(*        \\prod_<range> e == iterated product for a ring (cf bigop.v).        *)\n(*                 x ^+ n == x to the nth power with n in nat (non-negative), *)\n(*                           i.e., x * (x * .. (x * x)..) (n factors); x ^+ 1 *)\n(*                           is thus convertible to x, and x ^+ 2 to x * x.   *)\n(*         GRing.sign R b := (-1) ^+ b in R : ringType, with b : bool.        *)\n(*                           This is a parsing-only helper notation, to be    *)\n(*                           used for defining more specific instances.       *)\n(*         GRing.comm x y <-> x and y commute, i.e., x * y = y * x.           *)\n(*           GRing.lreg x <-> x if left-regular, i.e., *%R x is injective.    *)\n(*           GRing.rreg x <-> x if right-regular, i.e., *%R x is injective.   *)\n(*               [char R] == the characteristic of R, defined as the set of   *)\n(*                           prime numbers p such that p%:R = 0 in R. The set *)\n(*                           [char p] has a most one element, and is          *)\n(*                           implemented as a pred_nat collective predicate   *)\n(*                           (see prime.v); thus the statement p \\in [char R] *)\n(*                           can be read as `R has characteristic p', while   *)\n(*                           [char R] =i pred0 means `R has characteristic 0' *)\n(*                           when R is a field.                               *)\n(*     Frobenius_aut chRp == the Frobenius automorphism mapping x in R to     *)\n(*                           x ^+ p, where chRp : p \\in [char R] is a proof   *)\n(*                           that R has (non-zero) characteristic p.          *)\n(*          mulr_closed S <-> collective predicate S is closed under finite   *)\n(*                           products (1 and x * y in S for x, y in S).       *)\n(*         smulr_closed S <-> collective predicate S is closed under products *)\n(*                           and opposite (-1 and x * y in S for x, y in S).  *)\n(*      semiring_closed S <-> collective predicate S is closed under semiring *)\n(*                           operations (0, 1, x + y and x * y in S).         *)\n(*       subring_closed S <-> collective predicate S is closed under ring     *)\n(*                           operations (1, x - y and x * y in S).            *)\n(*          MulrPred mulS == packs mulS : mulr_closed S into a mulrPred S,    *)\n(*        SmulrPred mulS     smulrPred S, semiringPred S, or subringPred S    *)\n(*     SemiringPred mulS     interface structure, corresponding to the above  *)\n(*      SubRingPred mulS     properties, respectively, provided S already has *)\n(*                           the supplementary zmodType closure properties.   *)\n(*                           The properties above coerce to subproperties so, *)\n(*                           e.g., ringS : subring_closed S can be used for   *)\n(*                           the proof obligations of all prerequisites.      *)\n(* [ringMixin of R by <:] == ringType mixin for a subType whose base type is  *)\n(*                           a ringType and whose predicate's canonical key   *)\n(*                           is a SubringPred.                                *)\n(*  --> As for zmodType predicates, Import DefaultKeying GRing.DefaultPred    *)\n(*      turns unresolved GRing.Pred unification constraints into proof        *)\n(*      obligations for basic closure assumptions.                            *)\n(*                                                                            *)\n(*  * ComRing (commutative Rings):                                            *)\n(*            comRingType == interface type for commutative ring structure.   *)\n(*     ComRingType R mulC == packs mulC into a comRingType; the carrier type  *)\n(*                           R must have a ringType canonical structure.      *)\n(* ComRingMixin mulA mulC mul1x mulDx == builds the mixin for a Ring (i.e., a *)\n(*                           *non commutative* ring), using the commutativity *)\n(*                           to reduce the number of proof obligagtions.      *)\n(* [comRingType of R for S] == R-clone of the comRingType structure S.        *)\n(*     [comRingType of R] == clone of a canonical comRingType structure on R. *)\n(* [comRingMixin of R by <:] == comutativity mixin axiom for R when it is a   *)\n(*                           subType of a commutative ring.                   *)\n(*                                                                            *)\n(*  * UnitRing (Rings whose units have computable inverses):                  *)\n(*           unitRingType == interface type for the UnitRing structure.       *)\n(* UnitRingMixin mulVr mulrV unitP inv0id == builds the mixin for a UnitRing  *)\n(*                           from the properties of the inverse operation and *)\n(*                           the boolean test for being a unit (invertible).  *)\n(*                           The inverse of a non-unit x is constrained to be *)\n(*                           x itself (property inv0id). The carrier type     *)\n(*                           must have a ringType canonical structure.        *)\n(*       UnitRingType R m == packs the unit ring mixin m into a unitRingType. *)\n(*                  WARNING: while it is possible to omit R for most of the   *)\n(*                           XxxType functions, R MUST be explicitly given    *)\n(*                           when UnitRingType is used with a mixin produced  *)\n(*                           by ComUnitRingMixin, otherwise the resulting     *)\n(*                           structure will have the WRONG sort key and will  *)\n(*                           NOT BE USED during type inference.               *)\n(* [unitRingType of R for S] == R-clone of the unitRingType structure S.      *)\n(*    [unitRingType of R] == clones a canonical unitRingType structure on R.  *)\n(*     x \\is a GRing.unit <=> x is a unit (i.e., has an inverse).             *)\n(*                   x^-1 == the ring inverse of x, if x is a unit, else x.   *)\n(*                  x / y == x divided by y (notation for x * y^-1).          *)\n(*                 x ^- n := notation for (x ^+ n)^-1, the inverse of x ^+ n. *)\n(*         invr_closed S <-> collective predicate S is closed under inverse.  *)\n(*         divr_closed S <-> collective predicate S is closed under division  *)\n(*                           (1 and x / y in S).                              *)\n(*        sdivr_closed S <-> collective predicate S is closed under division  *)\n(*                           and opposite (-1 and x / y in S, for x, y in S). *)\n(*      divring_closed S <-> collective predicate S is closed under unitRing  *)\n(*                           operations (1, x - y and x / y in S).            *)\n(*         DivrPred invS == packs invS : mulr_closed S into a divrPred S,     *)\n(*        SdivrPred invS    sdivrPred S or divringPred S interface structure, *)\n(*      DivringPred invS    corresponding to the above properties, resp.,     *)\n(*                          provided S already has the supplementary ringType *)\n(*                          closure properties. The properties above coerce   *)\n(*                          to subproperties, as explained above.             *)\n(* [unitRingMixin of R by <:] == unitRingType mixin for a subType whose base  *)\n(*                           type is a unitRingType and whose predicate's     *)\n(*                           canonical key is a divringPred and whose ring    *)\n(*                           structure is compatible with the base type's.    *)\n(*                                                                            *)\n(*  * ComUnitRing (commutative rings with computable inverses):               *)\n(*        comUnitRingType == interface type for ComUnitRing structure.        *)\n(* ComUnitRingMixin mulVr unitP inv0id == builds the mixin for a UnitRing (a  *)\n(*                           *non commutative* unit ring, using commutativity *)\n(*                           to simplify the proof obligations; the carrier   *)\n(*                           type must have a comRingType structure.          *)\n(*                           WARNING: ALWAYS give an explicit type argument   *)\n(*                           to UnitRingType along with a mixin produced by   *)\n(*                           ComUnitRingMixin (see above).                    *)\n(* [comUnitRingType of R] == a comUnitRingType structure for R created by     *)\n(*                           merging canonical comRingType and unitRingType   *)\n(*                           structures on R.                                 *)\n(*                                                                            *)\n(*  * IntegralDomain (integral, commutative, ring with partial inverses):     *)\n(*            idomainType == interface type for the IntegralDomain structure. *)\n(* IdomainType R mulf_eq0 == packs the integrality property into an           *)\n(*                           idomainType integral domain structure; R must    *)\n(*                           have a comUnitRingType canonical structure.      *)\n(* [idomainType of R for S] == R-clone of the idomainType structure S.        *)\n(*     [idomainType of R] == clone of a canonical idomainType structure on R. *)\n(* [idomainMixin of R by <:] == mixin axiom for a idomain subType.            *)\n(*                                                                            *)\n(*  * Field (commutative fields):                                             *)\n(*              fieldType == interface type for fields.                       *)\n(*  GRing.Field.axiom inv == the field axiom (x != 0 -> inv x * x = 1).       *)\n(* FieldUnitMixin mulVx unitP inv0id == builds a *non commutative unit ring*  *)\n(*                           mixin, using the field axiom to simplify proof   *)\n(*                           obligations. The carrier type must have a        *)\n(*                           comRingType canonical structure.                 *)\n(*       FieldMixin mulVx == builds the field mixin from the field axiom. The *)\n(*                           carrier type must have a comRingType structure.  *)\n(*    FieldIdomainMixin m == builds an *idomain* mixin from a field mixin m.  *)\n(*          FieldType R m == packs the field mixin M into a fieldType. The    *)\n(*                           carrier type R must be an idomainType.           *)\n(* [fieldType of F for S] == F-clone of the fieldType structure S.            *)\n(*       [fieldType of F] == clone of a canonical fieldType structure on F.   *)\n(*   [fieldMixin of R by <:] == mixin axiom for a field subType.              *)\n(*                                                                            *)\n(*  * DecidableField (fields with a decidable first order theory):            *)\n(*           decFieldType == interface type for DecidableField structure.     *)\n(*     DecFieldMixin satP == builds the mixin for a DecidableField from the   *)\n(*                           correctness of its satisfiability predicate. The *)\n(*                           carrier type must have a unitRingType structure. *)\n(*       DecFieldType F m == packs the decidable field mixin m into a         *)\n(*                           decFieldType; the carrier type F must have a     *)\n(*                           fieldType structure.                             *)\n(* [decFieldType of F for S] == F-clone of the decFieldType structure S.      *)\n(*    [decFieldType of F] == clone of a canonical decFieldType structure on F *)\n(*           GRing.term R == the type of formal expressions in a unit ring R  *)\n(*                           with formal variables 'X_k, k : nat, and         *)\n(*                           manifest constants x%:T, x : R. The notation of  *)\n(*                           all the ring operations is redefined for terms,  *)\n(*                           in scope %T.                                     *)\n(*        GRing.formula R == the type of first order formulas over R; the %T  *)\n(*                           scope binds the logical connectives /\\, \\/, ~,   *)\n(*                           ==>, ==, and != to formulae; GRing.True/False    *)\n(*                           and GRing.Bool b denote constant formulae, and   *)\n(*                           quantifiers are written 'forall/'exists 'X_k, f. *)\n(*                             GRing.Unit x tests for ring units              *)\n(*                             GRing.If p_f t_f e_f emulates if-then-else     *)\n(*                             GRing.Pick p_f t_f e_f emulates fintype.pick   *)\n(*                             foldr GRing.Exists/Forall q_f xs can be used   *)\n(*                               to write iterated quantifiers.               *)\n(*         GRing.eval e t == the value of term t with valuation e : seq R     *)\n(*                           (e maps 'X_i to e`_i).                           *)\n(*  GRing.same_env e1 e2 <-> environments e1 and e2 are extensionally equal.  *)\n(*        GRing.qf_form f == f is quantifier-free.                            *)\n(*        GRing.holds e f == the intuitionistic CiC interpretation of the     *)\n(*                           formula f holds with valuation e.                *)\n(*      GRing.qf_eval e f == the value (in bool) of a quantifier-free f.      *)\n(*          GRing.sat e f == valuation e satisfies f (only in a decField).    *)\n(*          GRing.sol n f == a sequence e of size n such that e satisfies f,  *)\n(*                           if one exists, or [::] if there is no such e.    *)\n(* QEdecFieldMixin wfP okP == a decidable field Mixin built from a quantifier *)\n(*                           eliminator p and proofs wfP : GRing.wf_QE_proj p *)\n(*                           and okP : GRing.valid_QE_proj p that p returns   *)\n(*                           well-formed and valid formulae, i.e., p i (u, v) *)\n(*                           is a quantifier-free formula equivalent to       *)\n(*        'exists 'X_i, u1 == 0 /\\ ... /\\ u_m == 0 /\\ v1 != 0 ... /\\ v_n != 0 *)\n(*                                                                            *)\n(*  * ClosedField (algebraically closed fields):                              *)\n(*        closedFieldType == interface type for the ClosedField structure.    *)\n(*    ClosedFieldType F m == packs the closed field mixin m into a            *)\n(*                           closedFieldType. The carrier F must have a       *)\n(*                           decFieldType structure.                          *)\n(* [closedFieldType of F on S] == F-clone of a closedFieldType structure S.   *)\n(* [closedFieldType of F] == clone of a canonicalclosedFieldType structure    *)\n(*                           on F.                                            *)\n(*                                                                            *)\n(*  * Lmodule (module with left multiplication by external scalars).          *)\n(*             lmodType R == interface type for an Lmodule structure with     *)\n(*                           scalars of type R; R must have a ringType        *)\n(*                           structure.                                       *)\n(* LmodMixin scalA scal1v scalxD scalDv == builds an Lmodule mixin from the   *)\n(*                           algebraic properties of the scaling operation;   *)\n(*                           the module carrier type must have a zmodType     *)\n(*                           structure, and the scalar carrier must have a    *)\n(*                           ringType structure.                              *)\n(*         LmodType R V m == packs the mixin v to build an Lmodule of type    *)\n(*                           lmodType R. The carrier type V must have a       *)\n(*                           zmodType structure.                              *)\n(* [lmodType R of V for S] == V-clone of an lmodType R structure S.           *)\n(*      [lmodType R of V] == clone of a canonical lmodType R structure on V.  *)\n(*                 a *: v == v scaled by a, when v is in an Lmodule V and a   *)\n(*                           is in the scalar Ring of V.                      *)\n(*        scaler_closed S <-> collective predicate S is closed under scaling. *)\n(*        linear_closed S <-> collective predicate S is closed under linear   *)\n(*                           combinations (a *: u + v in S when u, v in S).   *)\n(*        submod_closed S <-> collective predicate S is closed under lmodType *)\n(*                           operations (0 and a *: u + v in S).              *)\n(*      SubmodPred scaleS == packs scaleS : scaler_closed S in a submodPred S *)\n(*                           interface structure corresponding to the above   *)\n(*                           property, provided S's key is a zmodPred;        *)\n(*                           submod_closed coerces to all the prerequisites.  *)\n(* [lmodMixin of V by <:] == mixin for a subType of an lmodType, whose        *)\n(*                           predicate's key is a submodPred.                 *)\n(*                                                                            *)\n(*  * Lalgebra (left algebra, ring with scaling that associates on the left): *)\n(*             lalgType R == interface type for Lalgebra structures with      *)\n(*                           scalars in R; R must have ringType structure.    *)\n(*    LalgType R V scalAl == packs scalAl : k (x y) = (k x) y into an         *)\n(*                           Lalgebra of type lalgType R. The carrier type V  *)\n(*                           must have both lmodType R and ringType canonical *)\n(*                           structures.                                      *)\n(*                    R^o == the regular algebra of R: R^o is convertible to  *)\n(*                           R, but when R has a ringType structure then R^o  *)\n(*                           extends it to an lalgType structure by letting R *)\n(*                           act on itself: if x : R and y : R^o then         *)\n(*                           x *: y = x * (y : R).                            *)\n(*                   k%:A == the image of the scalar k in an L-algebra; this  *)\n(*                           is simply notation for k *: 1.                   *)\n(* [lalgType R of V for S] == V-clone the lalgType R structure S.             *)\n(*      [lalgType R of V] == clone of a canonical lalgType R structure on V.  *)\n(*        subalg_closed S <-> collective predicate S is closed under lalgType *)\n(*                           operations (1, a *: u + v and u * v in S).       *)\n(*      SubalgPred scaleS == packs scaleS : scaler_closed S in a subalgPred S *)\n(*                           interface structure corresponding to the above   *)\n(*                           property, provided S's key is a subringPred;     *)\n(*                           subalg_closed coerces to all the prerequisites.  *)\n(* [lalgMixin of V by <:] == mixin axiom for a subType of an lalgType.        *)\n(*                                                                            *)\n(*  * Algebra (ring with scaling that associates both left and right):        *)\n(*              algType R == type for Algebra structure with scalars in R.    *)\n(*                           R should be a commutative ring.                  *)\n(*     AlgType R A scalAr == packs scalAr : k (x y) = x (k y) into an Algebra *)\n(*                           Structure of type algType R. The carrier type A  *)\n(*                           must have an lalgType R structure.               *)\n(*        CommAlgType R A == creates an Algebra structure for an A that has   *)\n(*                           both lalgType R and comRingType structures.      *)\n(* [algType R of V for S] == V-clone of an algType R structure on S.          *)\n(*       [algType R of V] == clone of a canonical algType R structure on V.   *)\n(*  [algMixin of V by <:] == mixin axiom for a subType of an algType.         *)\n(*                                                                            *)\n(*  * UnitAlgebra (algebra with computable inverses):                         *)\n(*          unitAlgType R == interface type for UnitAlgebra structure with    *)\n(*                           scalars in R; R should have a unitRingType       *)\n(*                           structure.                                       *)\n(*   [unitAlgType R of V] == a unitAlgType R structure for V created by       *)\n(*                           merging canonical algType and unitRingType on V. *)\n(*        divalg_closed S <-> collective predicate S is closed under all      *)\n(*                           unitAlgType operations (1, a *: u + v and u / v  *)\n(*                           are in S fo u, v in S).                          *)\n(*      DivalgPred scaleS == packs scaleS : scaler_closed S in a divalgPred S *)\n(*                           interface structure corresponding to the above   *)\n(*                           property, provided S's key is a divringPred;     *)\n(*                           divalg_closed coerces to all the prerequisites.  *)\n(*                                                                            *)\n(*   In addition to this strcture hierarchy, we also develop a separate,      *)\n(* parallel hierarchy for morphisms linking these structures:                 *)\n(*                                                                            *)\n(* * Additive (additive functions):                                           *)\n(*             additive f <-> f of type U -> V is additive, i.e., f maps the  *)\n(*                           Zmodule structure of U to that of V, 0 to 0,     *)\n(*                           - to - and + to + (equivalently, binary - to -). *)\n(*                        := {morph f : u v / u + v}.                         *)\n(*      {additive U -> V} == the interface type for a Structure (keyed on     *)\n(*                           a function f : U -> V) that encapsulates the     *)\n(*                           additive property; both U and V must have        *)\n(*                           zmodType canonical structures.                   *)\n(*         Additive add_f == packs add_f : additive f into an additive        *)\n(*                           function structure of type {additive U -> V}.    *)\n(*   [additive of f as g] == an f-clone of the additive structure on the      *)\n(*                           function g -- f and g must be convertible.       *)\n(*        [additive of f] == a clone of an existing additive structure on f.  *)\n(*                                                                            *)\n(* * RMorphism (ring morphisms):                                              *)\n(*       multiplicative f <-> f of type R -> S is multiplicative, i.e., f     *)\n(*                           maps 1 and * in R to 1 and * in S, respectively, *)\n(*                           R ans S must have canonical ringType structures. *)\n(*            rmorphism f <-> f is a ring morphism, i.e., f is both additive  *)\n(*                           and multiplicative.                              *)\n(*     {rmorphism R -> S} == the interface type for ring morphisms, i.e.,     *)\n(*                           a Structure that encapsulates the rmorphism      *)\n(*                           property for functions f : R -> S; both R and S  *)\n(*                           must have ringType structures.                   *)\n(*      RMorphism morph_f == packs morph_f : rmorphism f into a Ring morphism *)\n(*                           structure of type {rmorphism R -> S}.            *)\n(*     AddRMorphism mul_f == packs mul_f : multiplicative f into an rmorphism *)\n(*                           structure of type {rmorphism R -> S}; f must     *)\n(*                           already have an {additive R -> S} structure.     *)\n(*  [rmorphism of f as g] == an f-clone of the rmorphism structure of g.      *)\n(*       [rmorphism of f] == a clone of an existing additive structure on f.  *)\n(*  -> If R and S are UnitRings the f also maps units to units and inverses   *)\n(*     of units to inverses; if R is a field then f if a field isomorphism    *)\n(*     between R and its image.                                               *)\n(*  -> As rmorphism coerces to both additive and multiplicative, all          *)\n(*     structures for f can be built from a single proof of rmorphism f.      *)\n(*  -> Additive properties (raddf_suffix, see below) are duplicated and       *)\n(*     specialised for RMorphism (as rmorph_suffix). This allows more         *)\n(*     precise rewriting and cleaner chaining: although raddf lemmas will     *)\n(*     recognize RMorphism functions, the converse will not hold (we cannot   *)\n(*     add reverse inheritance rules because of incomplete backtracking in    *)\n(*     the Canonical Projection unification), so one would have to insert a   *)\n(*     /= every time one switched from additive to multiplicative rules.      *)\n(*  -> The property duplication also means that it is not strictly necessary  *)\n(*     to declare all Additive instances.                                     *)\n(*                                                                            *)\n(* * Linear (linear functions):                                               *)\n(*             scalable f <-> f of type U -> V is scalable, i.e., f morphs    *)\n(*                           scaling on U to scaling on V, a *: _ to a *: _.  *)\n(*                           U and V must both have lmodType R structures,    *)\n(*                           for the same ringType R.                         *)\n(*       scalable_for s f <-> f is scalable for scaling operator s, i.e.,     *)\n(*                           f morphs a *: _ to s a _; the range of f only    *)\n(*                           need to be a zmodType. The scaling operator s    *)\n(*                           should be one of *:%R (see scalable, above), *%R *)\n(*                           or a combination nu \\; *%R or nu \\; *:%R with    *)\n(*                           nu : {rmorphism _}; otherwise some of the theory *)\n(*                           (e.g., the linearZ rule) will not apply.         *)\n(*               linear f <-> f of type U -> V is linear, i.e., f morphs      *)\n(*                           linear combinations a *: u + v in U to similar   *)\n(*                           linear combinations in V; U and V must both have *)\n(*                           lmodType R structures, for the same ringType R.  *)\n(*                        := forall a, {morph f: u v / a *: u + v}.           *)\n(*               scalar f <-> f of type U -> R is a scalar function, i.e.,    *)\n(*                           f (a *: u + v) = a * f u + f v.                  *)\n(*         linear_for s f <-> f is linear for the scaling operator s, i.e.,   *)\n(*                           f (a *: u + v) = s a (f u) + f v. The range of f *)\n(*                           only needs to be a zmodType, but s MUST be of    *)\n(*                           the form described in in scalable_for paragraph  *)\n(*                           for this predicate to type check.                *)\n(*            lmorphism f <-> f is both additive and scalable. This is in     *)\n(*                           fact equivalent to linear f, although somewhat   *)\n(*                           less convenient to prove.                        *)\n(*     lmorphism_for s f <-> f is both additive and scalable for s.           *)\n(*        {linear U -> V} == the interface type for linear functions, i.e., a *)\n(*                           Structure that encapsulates the linear property  *)\n(*                           for functions f : U -> V; both U and V must have *)\n(*                           lmodType R structures, for the same R.           *)\n(*             {scalar U} == the interface type for scalar functions, of type *)\n(*                           U -> R where U has an lmodType R structure.      *)\n(*    {linear U -> V | s} == the interface type for functions linear for s.   *)\n(*           Linear lin_f == packs lin_f : lmorphism_for s f into a linear    *)\n(*                           function structure of type {linear U -> V | s}.  *)\n(*                           As linear_for s f coerces to lmorphism_for s f,  *)\n(*                           Linear can be used with lin_f : linear_for s f   *)\n(*                           (indeed, that is the recommended usage). Note    *)\n(*                           that as linear f, scalar f, {linear U -> V} and  *)\n(*                           {scalar U} are simply notation for corresponding *)\n(*                           generic \"_for\" forms, Linear can be used for any *)\n(*                           of these special cases, transparantly.           *)\n(*       AddLinear scal_f == packs scal_f : scalable_for s f into a           *)\n(*                           {linear U -> V | s} structure; f must already    *)\n(*                           have an additive structure; as with Linear,      *)\n(*                           AddLinear can be used with lin_f : linear f, etc *)\n(*     [linear of f as g] == an f-clone of the linear structure of g.         *)\n(*          [linear of f] == a clone of an existing linear structure on f.    *)\n(*          (a *: u)%Rlin == transient forms that simplifiy to a *: u, a * u, *)\n(*           (a * u)%Rlin    nu a *: u, and nu a * u, respectively, and are   *)\n(*       (a *:^nu u)%Rlin    created by rewriting with the linearZ lemma. The *)\n(*        (a *^nu u)%Rlin    forms allows the RHS of linearZ to be matched    *)\n(*                           reliably, using the GRing.Scale.law structure.   *)\n(* -> Similarly to Ring morphisms, additive properties are specialized for    *)\n(*    linear functions.                                                       *)\n(* -> Although {scalar U} is convertible to {linear U -> R^o}, it does not    *)\n(*    actually use R^o, so that rewriting preserves the canonical structure   *)\n(*    of the range of scalar functions.                                       *)\n(* -> The generic linearZ lemma uses a set of bespoke interface structures to *)\n(*    ensure that both left-to-right and right-to-left rewriting work even in *)\n(*    the presence of scaling functions that simplify non-trivially (e.g.,    *)\n(*    idfun \\; *%R). Because most of the canonical instances and projections  *)\n(*    are coercions the machinery will be mostly invisible (with only the     *)\n(*    {linear ...} structure and %Rlin notations showing), but users should   *)\n(*    beware that in (a *: f u)%Rlin, a actually occurs in the f u subterm.   *)\n(* -> The simpler linear_LR, or more specialized linearZZ and scalarZ rules   *)\n(*    should be used instead of linearZ if there are complexity issues, as    *)\n(*    well as for explicit forward and backward application, as the main      *)\n(*    parameter of linearZ is a proper sub-interface of {linear fUV | s}.     *)\n(*                                                                            *)\n(* * LRMorphism (linear ring morphisms, i.e., algebra morphisms):             *)\n(*           lrmorphism f <-> f of type A -> B is a linear Ring (Algebra)     *)\n(*                           morphism: f is both additive, multiplicative and *)\n(*                           scalable. A and B must both have lalgType R      *)\n(*                           canonical structures, for the same ringType R.   *)\n(*     lrmorphism_for s f <-> f a linear Ring morphism for the scaling        *)\n(*                           operator s: f is additive, multiplicative and    *)\n(*                           scalable for s. A must be an lalgType R, but B   *)\n(*                           only needs to have a ringType structure.         *)\n(*    {lrmorphism A -> B} == the interface type for linear morphisms, i.e., a *)\n(*                           Structure that encapsulates the lrmorphism       *)\n(*                           property for functions f : A -> B; both A and B  *)\n(*                           must have lalgType R structures, for the same R. *)\n(* {lrmorphism A -> B | s} == the interface type for morphisms linear for s.  *)\n(*   LRmorphism lrmorph_f == packs lrmorph_f : lrmorphism_for s f into a      *)\n(*                           linear morphism structure of type                *)\n(*                           {lrmorphism A -> B | s}. Like Linear, LRmorphism *)\n(*                           can be used transparently for lrmorphism f.      *)\n(*   AddLRmorphism scal_f == packs scal_f : scalable_for s f into a linear    *)\n(*                           morphism structure of type                       *)\n(*                           {lrmorphism A -> B | s}; f must already have an  *)\n(*                           {rmorphism A -> B} structure, and AddLRmorphism  *)\n(*                           can be applied to a linear_for s f, linear f,    *)\n(*                           scalar f, etc argument, like AddLinear.          *)\n(*      [lrmorphism of f] == creates an lrmorphism structure from existing    *)\n(*                           rmorphism and linear structures on f; this is    *)\n(*                           the preferred way of creating lrmorphism         *)\n(*                           structures.                                      *)\n(*  -> Linear and rmorphism properties do not need to be specialized for      *)\n(*     as we supply inheritance join instances in both directions.            *)\n(* Finally we supply some helper notation for morphisms:                      *)\n(*                    x^f == the image of x under some morphism. This         *)\n(*                           notation is only reserved (not defined) here;    *)\n(*                           it is bound locally in sections where some       *)\n(*                           morphism is used heavily (e.g., the container    *)\n(*                           morphism in the parametricity sections of poly   *)\n(*                           and matrix, or the Frobenius section here).      *)\n(*                     \\0 == the constant null function, which has a          *)\n(*                           canonical linear structure, and simplifies on    *)\n(*                           application (see ssrfun.v).                      *)\n(*                 f \\+ g == the additive composition of f and g, i.e., the   *)\n(*                           function x |-> f x + g x; f \\+ g is canonically  *)\n(*                           linear when f and g are, and simplifies on       *)\n(*                           application (see ssrfun.v).                      *)\n(*                 f \\- g == the function x |-> f x - g x, canonically        *)\n(*                           linear when f and g are, and simplifies on       *)\n(*                           application.                                     *)\n(*                k \\*: f == the function x |-> k *: f x, which is            *)\n(*                           canonically linear when f is and simplifies on   *)\n(*                           application (this is a shorter alternative to    *)\n(*                           *:%R k \\o f).                                    *)\n(*         GRing.in_alg A == the ring morphism that injects R into A, where A *)\n(*                           has an lalgType R structure; GRing.in_alg A k    *)\n(*                           simplifies to k%:A.                              *)\n(*                a \\*o f == the function x |-> a * f x, canonically linear   *)\n(*                           linear when f is and its codomain is an algType  *)\n(*                           and which simplifies on application.             *)\n(*                a \\o* f == the function x |-> f x * a, canonically linear   *)\n(*                           linear when f is and its codomain is an lalgType *)\n(*                           and which simplifies on application.             *)\n(* The Lemmas about these structures are contained in both the GRing module   *)\n(* and in the submodule GRing.Theory, which can be imported when unqualified  *)\n(* access to the theory is needed (GRing.Theory also allows the unqualified   *)\n(* use of additive, linear, Linear, etc). The main GRing module should NOT be *)\n(* imported.                                                                  *)\n(*   Notations are defined in scope ring_scope (delimiter %R), except term    *)\n(* and formula notations, which are in term_scope (delimiter %T).             *)\n(*   This library also extends the conventional suffixes described in library *)\n(* ssrbool.v with the following:                                              *)\n(*   0 -- ring 0, as in addr0 : x + 0 = x.                                    *)\n(*   1 -- ring 1, as in mulr1 : x * 1 = x.                                    *)\n(*   D -- ring addition, as in linearD : f (u + v) = f u + f v.               *)\n(*   B -- ring substraction, as in opprB : - (x - y) = y - x.                 *)\n(*   M -- ring multiplication, as in invfM : (x * y)^-1 = x^-1 * y^-1.        *)\n(*  Mn -- ring by nat multiplication, as in raddfMn : f (x *+ n) = f x *+ n.  *)\n(*   N -- ring opposite, as in mulNr : (- x) * y = - (x * y).                 *)\n(*   V -- ring inverse, as in mulVr : x^-1 * x = 1.                           *)\n(*   X -- ring exponentiation, as in rmorphX : f (x ^+ n) = f x ^+ n.         *)\n(*   Z -- (left) module scaling, as in linearZ : f (a *: v)  = s *: f v.      *)\n(* The operator suffixes D, B, M and X are also used for the corresponding    *)\n(* operations on nat, as in natrX : (m ^ n)%:R = m%:R ^+ n. For the binary    *)\n(* power operator, a trailing \"n\" suffix is used to indicate the operator     *)\n(* suffix applies to the left-hand ring argument, as in                       *)\n(*   expr1n : 1 ^+ n = 1 vs. expr1 : x ^+ 1 = x.                              *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nReserved Notation \"+%R\" (at level 0).\nReserved Notation \"-%R\" (at level 0).\nReserved Notation \"*%R\" (at level 0).\nReserved Notation \"n %:R\" (at level 2, left associativity, format \"n %:R\").\nReserved Notation \"k %:A\" (at level 2, left associativity, format \"k %:A\").\nReserved Notation \"[ 'char' F ]\" (at level 0, format \"[ 'char'  F ]\").\n\nReserved Notation \"x %:T\" (at level 2, left associativity, format \"x %:T\").\nReserved Notation \"''X_' i\" (at level 8, i at level 2, format \"''X_' i\").\n(* Patch for recurring Coq parser bug: Coq seg faults when a level 200 *)\n(* notation is used as a pattern.                                      *)\nReserved Notation \"''exists' ''X_' i , f\"\n  (at level 199, i at level 2, right associativity,\n   format \"'[hv' ''exists'  ''X_' i , '/ '  f ']'\").\nReserved Notation \"''forall' ''X_' i , f\"\n  (at level 199, i at level 2, right associativity,\n   format \"'[hv' ''forall'  ''X_' i , '/ '  f ']'\").\n\nReserved Notation \"x ^f\" (at level 2, left associativity, format \"x ^f\").\n\nReserved Notation \"\\0\" (at level 0).\nReserved Notation \"f \\+ g\" (at level 50, left associativity).\nReserved Notation \"f \\- g\" (at level 50, left associativity).\nReserved Notation \"a \\*o f\" (at level 40).\nReserved Notation \"a \\o* f\" (at level 40).\nReserved Notation \"a \\*: f\" (at level 40).\n\nDelimit Scope ring_scope with R.\nDelimit Scope term_scope with T.\nLocal Open Scope ring_scope.\n\nModule Import GRing.\n\nImport Monoid.Theory.\n\nModule Zmodule.\n\nRecord mixin_of (V : Type) : Type := Mixin {\n  zero : V;\n  opp : V -> V;\n  add : V -> V -> V;\n  _ : associative add;\n  _ : commutative add;\n  _ : left_id zero add;\n  _ : left_inverse zero opp add\n}.\n\nSection ClassDef.\n\nRecord class_of T := Class { base : Choice.class_of T; mixin : mixin_of T }.\nLocal Coercion base : class_of >-> Choice.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack m :=\n  fun bT b & phant_id (Choice.class bT) b => Pack (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Choice.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nNotation zmodType := type.\nNotation ZmodType T m := (@pack T m _ _ id).\nNotation ZmodMixin := Mixin.\nNotation \"[ 'zmodType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'zmodType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'zmodType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'zmodType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Zmodule.\nImport Zmodule.Exports.\n\nDefinition zero V := Zmodule.zero (Zmodule.class V).\nDefinition opp V := Zmodule.opp (Zmodule.class V).\nDefinition add V := Zmodule.add (Zmodule.class V).\n\nLocal Notation \"0\" := (zero _) : ring_scope.\nLocal Notation \"-%R\" := (@opp _) : ring_scope.\nLocal Notation \"- x\" := (opp x) : ring_scope.\nLocal Notation \"+%R\" := (@add _) : ring_scope.\nLocal Notation \"x + y\" := (add x y) : ring_scope.\nLocal Notation \"x - y\" := (x + - y) : ring_scope.\n\nDefinition natmul V x n := nosimpl iterop _ n +%R x (zero V).\n\nLocal Notation \"x *+ n\" := (natmul x n) : ring_scope.\nLocal Notation \"x *- n\" := (- (x *+ n)) : ring_scope.\n\nLocal Notation \"\\sum_ ( i <- r | P ) F\" := (\\big[+%R/0]_(i <- r | P) F).\nLocal Notation \"\\sum_ ( m <= i < n ) F\" := (\\big[+%R/0]_(m <= i < n) F).\nLocal Notation \"\\sum_ ( i < n ) F\" := (\\big[+%R/0]_(i < n) F).\nLocal Notation \"\\sum_ ( i 'in' A ) F\" := (\\big[+%R/0]_(i in A) F).\n\nLocal Notation \"s `_ i\" := (nth 0 s i) : ring_scope.\n\nSection ZmoduleTheory.\n\nVariable V : zmodType.\nImplicit Types x y : V.\n\nLemma addrA : @associative V +%R. Proof. by case V => T [? []]. Qed.\nLemma addrC : @commutative V V +%R. Proof. by case V => T [? []]. Qed.\nLemma add0r : @left_id V V 0 +%R. Proof. by case V => T [? []]. Qed.\nLemma addNr : @left_inverse V V V 0 -%R +%R. Proof. by case V => T [? []]. Qed.\n\nLemma addr0 : @right_id V V 0 +%R.\nProof. by move=> x; rewrite addrC add0r. Qed.\nLemma addrN : @right_inverse V V V 0 -%R +%R.\nProof. by move=> x; rewrite addrC addNr. Qed.\nDefinition subrr := addrN.\n\nCanonical add_monoid := Monoid.Law addrA add0r addr0.\nCanonical add_comoid := Monoid.ComLaw addrC.\n\nLemma addrCA : @left_commutative V V +%R. Proof. exact: mulmCA. Qed.\nLemma addrAC : @right_commutative V V +%R. Proof. exact: mulmAC. Qed.\nLemma addrACA : @interchange V +%R +%R. Proof. exact: mulmACA. Qed.\n\nLemma addKr : @left_loop V V -%R +%R.\nProof. by move=> x y; rewrite addrA addNr add0r. Qed.\nLemma addNKr : @rev_left_loop V V -%R +%R.\nProof. by move=> x y; rewrite addrA addrN add0r. Qed.\nLemma addrK : @right_loop V V -%R +%R.\nProof. by move=> x y; rewrite -addrA addrN addr0. Qed.\nLemma addrNK : @rev_right_loop V V -%R +%R.\nProof. by move=> x y; rewrite -addrA addNr addr0. Qed.\nDefinition subrK := addrNK.\nLemma addrI : @right_injective V V V +%R.\nProof. move=> x; exact: can_inj (addKr x). Qed.\nLemma addIr : @left_injective V V V +%R.\nProof. move=> y; exact: can_inj (addrK y). Qed.\nLemma opprK : @involutive V -%R.\nProof. by move=> x; apply: (@addIr (- x)); rewrite addNr addrN. Qed.\nLemma oppr_inj : @injective V V -%R.\nProof. exact: inv_inj opprK. Qed.\nLemma oppr0 : -0 = 0 :> V.\nProof. by rewrite -[-0]add0r subrr. Qed.\nLemma oppr_eq0 x : (- x == 0) = (x == 0).\nProof. by rewrite (inv_eq opprK) oppr0. Qed.\n\nLemma subr0 x : x - 0 = x. Proof. by rewrite oppr0 addr0. Qed.\nLemma sub0r x : 0 - x = - x. Proof. by rewrite add0r. Qed.\n\nLemma opprD : {morph -%R: x y / x + y : V}.\nProof.\nby move=> x y; apply: (@addrI (x + y)); rewrite addrA subrr addrAC addrK subrr.\nQed.\n\nLemma opprB x y : - (x - y) = y - x.\nProof. by rewrite opprD addrC opprK. Qed.\n\nLemma subr_eq x y z : (x - z == y) = (x == y + z).\nProof. exact: can2_eq (subrK z) (addrK z) x y. Qed.\n\nLemma subr_eq0 x y : (x - y == 0) = (x == y).\nProof. by rewrite subr_eq add0r. Qed.\n\nLemma addr_eq0 x y : (x + y == 0) = (x == - y).\nProof. by rewrite -[x == _]subr_eq0 opprK. Qed.\n\nLemma eqr_opp x y : (- x == - y) = (x == y).\nProof. exact: can_eq opprK x y. Qed.\n\nLemma eqr_oppLR x y : (- x == y) = (x == - y).\nProof. exact: inv_eq opprK x y. Qed. \n\nLemma mulr0n x : x *+ 0 = 0. Proof. by []. Qed.\nLemma mulr1n x : x *+ 1 = x. Proof. by []. Qed.\nLemma mulr2n x : x *+ 2 = x + x. Proof. by []. Qed.\n\nLemma mulrS x n : x *+ n.+1 = x + x *+ n.\nProof. by case: n => //=; rewrite addr0. Qed.\n\nLemma mulrSr x n : x *+ n.+1 = x *+ n + x.\nProof. by rewrite addrC mulrS. Qed.\n\nLemma mulrb x (b : bool) : x *+ b = (if b then x else 0).\nProof. by case: b. Qed.\n\nLemma mul0rn n : 0 *+ n = 0 :> V.\nProof. by elim: n => // n IHn; rewrite mulrS add0r. Qed.\n\nLemma mulNrn x n : (- x) *+ n = x *- n.\nProof. by elim: n => [|n IHn]; rewrite ?oppr0 // !mulrS opprD IHn. Qed.\n\nLemma mulrnDl n : {morph (fun x => x *+ n) : x y / x + y}.\nProof.\nmove=> x y; elim: n => [|n IHn]; rewrite ?addr0 // !mulrS.\nby rewrite addrCA -!addrA -IHn -addrCA.\nQed.\n\nLemma mulrnDr x m n : x *+ (m + n) = x *+ m + x *+ n.\nProof.\nelim: m => [|m IHm]; first by rewrite add0r.\nby rewrite !mulrS IHm addrA.\nQed.\n\nLemma mulrnBl n : {morph (fun x => x *+ n) : x y / x - y}.\nProof.\nmove=> x y; elim: n => [|n IHn]; rewrite ?subr0 // !mulrS -!addrA; congr(_ + _).\nby rewrite addrC IHn -!addrA opprD [_ - y]addrC.\nQed.\n\nLemma mulrnBr x m n : n <= m -> x *+ (m - n) = x *+ m - x *+ n.\nProof.\nelim: m n => [|m IHm] [|n le_n_m]; rewrite ?subr0 // {}IHm //.\nby rewrite mulrSr mulrS opprD addrA addrK.\nQed.\n\nLemma mulrnA x m n : x *+ (m * n) = x *+ m *+ n.\nProof.\nby rewrite mulnC; elim: n => //= n IHn; rewrite mulrS mulrnDr IHn.\nQed.\n\nLemma mulrnAC x m n : x *+ m *+ n = x *+ n *+ m.\nProof. by rewrite -!mulrnA mulnC. Qed.\n\nLemma sumrN I r P (F : I -> V) :\n  (\\sum_(i <- r | P i) - F i = - (\\sum_(i <- r | P i) F i)).\nProof. by rewrite (big_morph _ opprD oppr0). Qed.\n\nLemma sumrB I r (P : pred I) (F1 F2 : I -> V) :\n  \\sum_(i <- r | P i) (F1 i - F2 i)\n     = \\sum_(i <- r | P i) F1 i - \\sum_(i <- r | P i) F2 i.\nProof. by rewrite -sumrN -big_split /=. Qed.\n\nLemma sumrMnl I r P (F : I -> V) n :\n  \\sum_(i <- r | P i) F i *+ n = (\\sum_(i <- r | P i) F i) *+ n.\nProof. by rewrite (big_morph _ (mulrnDl n) (mul0rn _)). Qed.\n\nLemma sumrMnr x I r P (F : I -> nat) :\n  \\sum_(i <- r | P i) x *+ F i = x *+ (\\sum_(i <- r | P i) F i).\nProof. by rewrite (big_morph _ (mulrnDr x) (erefl _)). Qed.\n\nLemma sumr_const (I : finType) (A : pred I) (x : V) :\n  \\sum_(i in A) x = x *+ #|A|.\nProof. by rewrite big_const -iteropE. Qed.\n\nSection ClosedPredicates.\n\nVariable S : predPredType V.\n\nDefinition addr_closed := 0 \\in S /\\ {in S &, forall u v, u + v \\in S}.\nDefinition oppr_closed := {in S, forall u, - u \\in S}.\nDefinition subr_2closed := {in S &, forall u v, u - v \\in S}.\nDefinition zmod_closed := 0 \\in S /\\ subr_2closed.\n\nLemma zmod_closedN : zmod_closed -> oppr_closed.\nProof. by case=> S0 SB y Sy; rewrite -sub0r !SB. Qed.\n\nLemma zmod_closedD : zmod_closed -> addr_closed.\nProof.\nby case=> S0 SB; split=> // y z Sy Sz; rewrite -[z]opprK -[- z]sub0r !SB.\nQed.\n\nEnd ClosedPredicates.\n\nEnd ZmoduleTheory.\n\nImplicit Arguments addrI [[V] x1 x2].\nImplicit Arguments addIr [[V] x1 x2].\nImplicit Arguments oppr_inj [[V] x1 x2].\n\nModule Ring.\n\nRecord mixin_of (R : zmodType) : Type := Mixin {\n  one : R;\n  mul : R -> R -> R;\n  _ : associative mul;\n  _ : left_id one mul;\n  _ : right_id one mul;\n  _ : left_distributive mul +%R;\n  _ : right_distributive mul +%R;\n  _ : one != 0\n}.\n\nDefinition EtaMixin R one mul mulA mul1x mulx1 mul_addl mul_addr nz1 :=\n  let _ := @Mixin R one mul mulA mul1x mulx1 mul_addl mul_addr nz1 in\n  @Mixin (Zmodule.Pack (Zmodule.class R) R) _ _\n     mulA mul1x mulx1 mul_addl mul_addr nz1.\n\nSection ClassDef.\n\nRecord class_of (R : Type) : Type := Class {\n  base : Zmodule.class_of R;\n  mixin : mixin_of (Zmodule.Pack base R)\n}.\nLocal Coercion base : class_of >-> Zmodule.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\n\nDefinition pack b0 (m0 : mixin_of (@Zmodule.Pack T b0 T)) :=\n  fun bT b & phant_id (Zmodule.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Zmodule.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nNotation ringType := type.\nNotation RingType T m := (@pack T _ m _ _ id _ id).\nNotation RingMixin := Mixin.\nNotation \"[ 'ringType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'ringType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'ringType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'ringType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Ring.\nImport Ring.Exports.\n\nDefinition one (R : ringType) : R := Ring.one (Ring.class R).\nDefinition mul (R : ringType) : R -> R -> R := Ring.mul (Ring.class R).\nDefinition exp R x n := nosimpl iterop _ n (@mul R) x (one R).\nNotation sign R b := (exp (- one R) (nat_of_bool b)) (only parsing).\nDefinition comm R x y := @mul R x y = mul y x.\nDefinition lreg R x := injective (@mul R x).\nDefinition rreg R x := injective ((@mul R)^~ x).\n\nLocal Notation \"1\" := (one _) : ring_scope.\nLocal Notation \"- 1\" := (- (1)) : ring_scope.\nLocal Notation \"n %:R\" := (1 *+ n) : ring_scope.\nLocal Notation \"*%R\" := (@mul _).\nLocal Notation \"x * y\" := (mul x y) : ring_scope.\nLocal Notation \"x ^+ n\" := (exp x n) : ring_scope.\n\nLocal Notation \"\\prod_ ( i <- r | P ) F\" := (\\big[*%R/1]_(i <- r | P) F).\nLocal Notation \"\\prod_ ( i | P ) F\" := (\\big[*%R/1]_(i | P) F).\nLocal Notation \"\\prod_ ( i 'in' A ) F\" := (\\big[*%R/1]_(i in A) F).\n\n(* The ``field'' characteristic; the definition, and many of the theorems,   *)\n(* has to apply to rings as well; indeed, we need the Frobenius automorphism *)\n(* results for a non commutative ring in the proof of Gorenstein 2.6.3.      *)\nDefinition char (R : Ring.type) of phant R : nat_pred :=\n  [pred p | prime p & p%:R == 0 :> R].\n\nLocal Notation \"[ 'char' R ]\" := (char (Phant R)) : ring_scope.\n\n(* Converse ring tag. *)\nDefinition converse R : Type := R.\nLocal Notation \"R ^c\" := (converse R) (at level 2, format \"R ^c\") : type_scope.\n\nSection RingTheory.\n\nVariable R : ringType.\nImplicit Types x y : R.\n\nLemma mulrA : @associative R *%R. Proof. by case R => T [? []]. Qed.\nLemma mul1r : @left_id R R 1 *%R. Proof. by case R => T [? []]. Qed.\nLemma mulr1 : @right_id R R 1 *%R. Proof. by case R => T [? []]. Qed.\nLemma mulrDl : @left_distributive R R *%R +%R.\nProof. by case R => T [? []]. Qed.\nLemma mulrDr : @right_distributive R R *%R +%R.\nProof. by case R => T [? []]. Qed.\nLemma oner_neq0 : 1 != 0 :> R. Proof. by case R => T [? []]. Qed.\nLemma oner_eq0 : (1 == 0 :> R) = false. Proof. exact: negbTE oner_neq0. Qed.\n\nLemma mul0r : @left_zero R R 0 *%R.\nProof.\nby move=> x; apply: (addIr (1 * x)); rewrite -mulrDl !add0r mul1r.\nQed.\nLemma mulr0 : @right_zero R R 0 *%R.\nProof.\nby move=> x; apply: (addIr (x * 1)); rewrite -mulrDr !add0r mulr1.\nQed.\nLemma mulrN x y : x * (- y) = - (x * y).\nProof. by apply: (addrI (x * y)); rewrite -mulrDr !subrr mulr0. Qed.\nLemma mulNr x y : (- x) * y = - (x * y).\nProof. by apply: (addrI (x * y)); rewrite -mulrDl !subrr mul0r. Qed.\nLemma mulrNN x y : (- x) * (- y) = x * y.\nProof. by rewrite mulrN mulNr opprK. Qed.\nLemma mulN1r x : -1 * x = - x.\nProof. by rewrite mulNr mul1r. Qed.\nLemma mulrN1 x : x * -1 = - x.\nProof. by rewrite mulrN mulr1. Qed.\n\nCanonical mul_monoid := Monoid.Law mulrA mul1r mulr1.\nCanonical muloid := Monoid.MulLaw mul0r mulr0.\nCanonical addoid := Monoid.AddLaw mulrDl mulrDr.\n\nLemma mulr_suml I r P (F : I -> R) x :\n  (\\sum_(i <- r | P i) F i) * x = \\sum_(i <- r | P i) F i * x.\nProof. exact: big_distrl. Qed.\n\nLemma mulr_sumr I r P (F : I -> R) x :\n  x * (\\sum_(i <- r | P i) F i) = \\sum_(i <- r | P i) x * F i.\nProof. exact: big_distrr. Qed.\n\nLemma mulrBl x y z : (y - z) * x = y * x - z * x.\nProof. by rewrite mulrDl mulNr. Qed.\n\nLemma mulrBr x y z : x * (y - z) = x * y - x * z.\nProof. by rewrite mulrDr mulrN. Qed.\n\nLemma mulrnAl x y n : (x *+ n) * y = (x * y) *+ n.\nProof. by elim: n => [|n IHn]; rewrite ?mul0r // !mulrS mulrDl IHn. Qed.\n\nLemma mulrnAr x y n : x * (y *+ n) = (x * y) *+ n.\nProof. by elim: n => [|n IHn]; rewrite ?mulr0 // !mulrS mulrDr IHn. Qed.\n\nLemma mulr_natl x n : n%:R * x = x *+ n.\nProof. by rewrite mulrnAl mul1r. Qed.\n\nLemma mulr_natr x n : x * n%:R = x *+ n.\nProof. by rewrite mulrnAr mulr1. Qed.\n\nLemma natrD m n : (m + n)%:R = m%:R + n%:R :> R.\nProof. exact: mulrnDr. Qed.\n\nLemma natrB m n : n <= m -> (m - n)%:R = m%:R - n%:R :> R.\nProof. exact: mulrnBr. Qed.\n\nDefinition natr_sum := big_morph (natmul 1) natrD (mulr0n 1).\n\nLemma natrM m n : (m * n)%:R = m%:R * n%:R :> R.\nProof. by rewrite mulrnA -mulr_natr. Qed.\n\nLemma expr0 x : x ^+ 0 = 1. Proof. by []. Qed.\nLemma expr1 x : x ^+ 1 = x. Proof. by []. Qed.\nLemma expr2 x : x ^+ 2 = x * x. Proof. by []. Qed.\n\nLemma exprS x n : x ^+ n.+1 = x * x ^+ n.\nProof. by case: n => //; rewrite mulr1. Qed.\n\nLemma expr0n n : 0 ^+ n = (n == 0%N)%:R :> R.\nProof. by case: n => // n; rewrite exprS mul0r. Qed.\n\nLemma expr1n n : 1 ^+ n = 1 :> R.\nProof. by elim: n => // n IHn; rewrite exprS mul1r. Qed.\n\nLemma exprD x m n : x ^+ (m + n) = x ^+ m * x ^+ n.\nProof. by elim: m => [|m IHm]; rewrite ?mul1r // !exprS -mulrA -IHm. Qed.\n\nLemma exprSr x n : x ^+ n.+1 = x ^+ n * x.\nProof. by rewrite -addn1 exprD expr1. Qed.\n\nLemma commr_sym x y : comm x y -> comm y x. Proof. by []. Qed.\nLemma commr_refl x : comm x x. Proof. by []. Qed.\n\nLemma commr0 x : comm x 0.\nProof. by rewrite /comm mulr0 mul0r. Qed.\n\nLemma commr1 x : comm x 1.\nProof. by rewrite /comm mulr1 mul1r. Qed.\n\nLemma commrN x y : comm x y -> comm x (- y).\nProof. by move=> com_xy; rewrite /comm mulrN com_xy mulNr. Qed.\n\nLemma commrN1 x : comm x (-1).\nProof. apply: commrN; exact: commr1. Qed.\n\nLemma commrD x y z : comm x y -> comm x z -> comm x (y + z).\nProof. by rewrite /comm mulrDl mulrDr => -> ->. Qed.\n\nLemma commrMn x y n : comm x y -> comm x (y *+ n).\nProof.\nrewrite /comm => com_xy.\nby elim: n => [|n IHn]; rewrite ?commr0 // mulrS commrD.\nQed.\n\nLemma commrM x y z : comm x y -> comm x z -> comm x (y * z).\nProof. by move=> com_xy; rewrite /comm mulrA com_xy -!mulrA => ->. Qed.\n\nLemma commr_nat x n : comm x n%:R.\nProof. by apply: commrMn; exact: commr1. Qed.\n\nLemma commrX x y n : comm x y -> comm x (y ^+ n).\nProof.\nrewrite /comm => com_xy.\nby elim: n => [|n IHn]; rewrite ?commr1 // exprS commrM.\nQed.\n\nLemma exprMn_comm x y n : comm x y -> (x * y) ^+ n = x ^+ n * y ^+ n.\nProof.\nmove=> com_xy; elim: n => /= [|n IHn]; first by rewrite mulr1.\nby rewrite !exprS IHn !mulrA; congr (_ * _); rewrite -!mulrA -commrX.\nQed.\n\nLemma commr_sign x n : comm x ((-1) ^+ n).\nProof. exact: (commrX n (commrN1 x)). Qed.\n\nLemma exprMn_n x m n : (x *+ m) ^+ n = x ^+ n *+ (m ^ n) :> R.\nProof.\nelim: n => [|n IHn]; first by rewrite mulr1n.\nrewrite exprS IHn -mulr_natr -mulrA -commr_nat mulr_natr -mulrnA -expnSr.\nby rewrite -mulr_natr mulrA -exprS mulr_natr.\nQed.\n\nLemma exprM x m n : x ^+ (m * n) = x ^+ m ^+ n.\nProof.\nelim: m => [|m IHm]; first by rewrite expr1n.\nby rewrite mulSn exprD IHm exprS exprMn_comm //; exact: commrX.\nQed.\n\nLemma exprAC x m n : (x ^+ m) ^+ n = (x ^+ n) ^+ m.\nProof. by rewrite -!exprM mulnC. Qed.\n\nLemma expr_mod n x i : x ^+ n = 1 -> x ^+ (i %% n) = x ^+ i.\nProof.\nmove=> xn1; rewrite {2}(divn_eq i n) exprD mulnC exprM xn1.\nby rewrite expr1n mul1r.\nQed.\n\nLemma expr_dvd n x i : x ^+ n = 1 -> n %| i -> x ^+ i = 1.\nProof.\nby move=> xn1 dvd_n_i; rewrite -(expr_mod i xn1) (eqnP dvd_n_i).\nQed.\n\nLemma natrX n k : (n ^ k)%:R = n%:R ^+ k :> R.\nProof. by rewrite exprMn_n expr1n. Qed.\n\nLemma signr_odd n : (-1) ^+ (odd n) = (-1) ^+ n :> R.\nProof.\nelim: n => //= n IHn; rewrite exprS -{}IHn.\nby case/odd: n; rewrite !mulN1r ?opprK.\nQed.\n\nLemma signr_eq0 n : ((-1) ^+ n == 0 :> R) = false.\nProof. by rewrite -signr_odd; case: odd; rewrite ?oppr_eq0 oner_eq0. Qed.\n\nLemma mulr_sign (b : bool) x : (-1) ^+ b * x = (if b then - x else x).\nProof. by case: b; rewrite ?mulNr mul1r. Qed.\n\nLemma signr_addb b1 b2 : (-1) ^+ (b1 (+) b2) = (-1) ^+ b1 * (-1) ^+ b2 :> R.\nProof. by rewrite mulr_sign; case: b1 b2 => [] []; rewrite ?opprK. Qed.\n\nLemma signrE (b : bool) : (-1) ^+ b = 1 - b.*2%:R :> R.\nProof. by case: b; rewrite ?subr0 // opprD addNKr. Qed.\n\nLemma signrN b : (-1) ^+ (~~ b) = - (-1) ^+ b :> R.\nProof. by case: b; rewrite ?opprK. Qed.\n\nLemma mulr_signM (b1 b2 : bool) x1 x2 :\n  ((-1) ^+ b1 * x1) * ((-1) ^+ b2 * x2) = (-1) ^+ (b1 (+) b2) * (x1 * x2).\nProof.\nby rewrite signr_addb -!mulrA; congr (_ * _); rewrite !mulrA commr_sign.\nQed.\n\nLemma exprNn x n : (- x) ^+ n = (-1) ^+ n * x ^+ n :> R.\nProof. by rewrite -mulN1r exprMn_comm // /comm mulN1r mulrN mulr1. Qed.\n\nLemma sqrrN x : (- x) ^+ 2 = x ^+ 2.\nProof. exact: mulrNN. Qed.\n\nLemma sqrr_sign n : ((-1) ^+ n) ^+ 2 = 1 :> R.\nProof. by rewrite exprAC sqrrN !expr1n. Qed.\n\nLemma signrMK n : @involutive R ( *%R ((-1) ^+ n)).\nProof. by move=> x; rewrite mulrA -expr2 sqrr_sign mul1r. Qed.\n\nLemma mulrI_eq0 x y : lreg x -> (x * y == 0) = (y == 0).\nProof. by move=> reg_x; rewrite -{1}(mulr0 x) (inj_eq reg_x). Qed.\n\nLemma lreg_neq0 x : lreg x -> x != 0.\nProof. by move=> reg_x; rewrite -[x]mulr1 mulrI_eq0 ?oner_eq0. Qed.\n\nLemma mulrI0_lreg x : (forall y, x * y = 0 -> y = 0) -> lreg x.\nProof.\nmove=> reg_x y z eq_xy_xz; apply/eqP; rewrite -subr_eq0 [y - z]reg_x //.\nby rewrite mulrBr eq_xy_xz subrr.\nQed.\n\nLemma lregN x : lreg x -> lreg (- x).\nProof. by move=> reg_x y z; rewrite !mulNr => /oppr_inj/reg_x. Qed.\n\nLemma lreg1 : lreg (1 : R).\nProof. by move=> x y; rewrite !mul1r. Qed.\n\nLemma lregM x y : lreg x -> lreg y -> lreg (x * y).\nProof. by move=> reg_x reg_y z t; rewrite -!mulrA => /reg_x/reg_y. Qed.\n\nLemma lregX x n : lreg x -> lreg (x ^+ n).\nProof.\nby move=> reg_x; elim: n => [|n]; [exact: lreg1 | rewrite exprS; exact: lregM].\nQed.\n\nLemma lreg_sign n : lreg ((-1) ^+ n : R).\nProof. by apply: lregX; apply: lregN; apply: lreg1. Qed.\n\nLemma prodr_const (I : finType) (A : pred I) (x : R) :\n  \\prod_(i in A) x = x ^+ #|A|.\nProof. by rewrite big_const -iteropE. Qed.\n\nLemma prodrXr x I r P (F : I -> nat) :\n  \\prod_(i <- r | P i) x ^+ F i = x ^+ (\\sum_(i <- r | P i) F i).\nProof. by rewrite (big_morph _ (exprD _) (erefl _)). Qed.\n\nLemma prodrN (I : finType) (A : pred I) (F : I -> R) :\n  \\prod_(i in A) - F i = (- 1) ^+ #|A| * \\prod_(i in A) F i.\nProof.\nrewrite -sum1_card  -!(big_filter _ A) !unlock.\nelim: {A}(filter _ _) => /= [|i r ->]; first by rewrite mul1r.\nby rewrite mulrA -mulN1r (commrX _ (commrN1 _)) exprSr !mulrA.\nQed.\n\nLemma prodrMn n (I : finType) (A : pred I) (F : I -> R) :\n  \\prod_(i in A) (F i *+ n) = \\prod_(i in A) F i *+ n ^ #|A|.\nProof.\nrewrite -sum1_card /= -!(big_filter _ A) !unlock.\nelim: {A}(filter _ _) => //= i r ->; by rewrite mulrnAr mulrnAl expnS mulrnA.\nQed.\n\nLemma exprDn_comm x y n (cxy : comm x y) :\n  (x + y) ^+ n = \\sum_(i < n.+1) (x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof.\nelim: n => [|n IHn]; rewrite big_ord_recl mulr1 ?big_ord0 ?addr0 //=.\nrewrite exprS {}IHn /= mulrDl !big_distrr /= big_ord_recl mulr1 subn0.\nrewrite !big_ord_recr /= !binn !subnn !mul1r !subn0 bin0 !exprS -addrA.\ncongr (_ + _); rewrite addrA -big_split /=; congr (_ + _).\napply: eq_bigr => i _; rewrite !mulrnAr !mulrA -exprS -subSn ?(valP i) //.\nby rewrite  subSS (commrX _ (commr_sym cxy)) -mulrA -exprS -mulrnDr.\nQed.\n\nLemma exprBn_comm x y n (cxy : comm x y) :\n  (x - y) ^+ n =\n    \\sum_(i < n.+1) ((-1) ^+ i * x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof.\nrewrite exprDn_comm; last exact: commrN.\nby apply: eq_bigr => i _; congr (_ *+ _); rewrite -commr_sign -mulrA -exprNn.\nQed.\n\nLemma subrXX_comm x y n (cxy : comm x y) :\n  x ^+ n - y ^+ n = (x - y) * (\\sum_(i < n) x ^+ (n.-1 - i) * y ^+ i).\nProof.\ncase: n => [|n]; first by rewrite big_ord0 mulr0 subrr.\nrewrite mulrBl !big_distrr big_ord_recl big_ord_recr /= subnn mulr1 mul1r.\nrewrite subn0 -!exprS opprD -!addrA; congr (_ + _); rewrite addrA -sumrB.\nrewrite big1 ?add0r // => i _; rewrite !mulrA -exprS -subSn ?(valP i) //.\nby rewrite subSS (commrX _ (commr_sym cxy)) -mulrA -exprS subrr.\nQed.\n\nLemma exprD1n x n : (x + 1) ^+ n = \\sum_(i < n.+1) x ^+ i *+ 'C(n, i).\nProof.\nrewrite addrC (exprDn_comm n (commr_sym (commr1 x))).\nby apply: eq_bigr => i _; rewrite expr1n mul1r.\nQed.\n\nLemma subrX1 x n : x ^+ n - 1 = (x - 1) * (\\sum_(i < n) x ^+ i).\nProof.\nrewrite -!(opprB 1) mulNr -{1}(expr1n n).\nrewrite (subrXX_comm _ (commr_sym (commr1 x))); congr (- (_ * _)).\nby apply: eq_bigr => i _; rewrite expr1n mul1r.\nQed.\n\nLemma sqrrD1 x : (x + 1) ^+ 2 = x ^+ 2 + x *+ 2 + 1.\nProof.\nrewrite exprD1n !big_ord_recr big_ord0 /= add0r.\nby rewrite addrC addrA addrAC.\nQed.\n\nLemma sqrrB1 x : (x - 1) ^+ 2 = x ^+ 2 - x *+ 2 + 1.\nProof. by rewrite -sqrrN opprB addrC sqrrD1 sqrrN mulNrn. Qed.\n\nLemma subr_sqr_1 x : x ^+ 2 - 1 = (x - 1) * (x + 1).\nProof. by rewrite subrX1 !big_ord_recr big_ord0 /= addrAC add0r. Qed.\n\nDefinition Frobenius_aut p of p \\in [char R] := fun x => x ^+ p.\n\nSection FrobeniusAutomorphism.\n\nVariable p : nat.\nHypothesis charFp : p \\in [char R].\n\nLemma charf0 : p%:R = 0 :> R. Proof. by apply/eqP; case/andP: charFp. Qed.\nLemma charf_prime : prime p. Proof. by case/andP: charFp. Qed.\nHint Resolve charf_prime.\n\nLemma mulrn_char x : x *+ p = 0. Proof. by rewrite -mulr_natl charf0 mul0r. Qed.\n\nLemma natr_mod_char n : (n %% p)%:R = n%:R :> R.\nProof. by rewrite {2}(divn_eq n p) natrD mulrnA mulrn_char add0r. Qed.\n\nLemma dvdn_charf n : (p %| n)%N = (n%:R == 0 :> R).\nProof.\napply/idP/eqP=> [/dvdnP[n' ->]|n0]; first by rewrite natrM charf0 mulr0.\napply/idPn; rewrite -prime_coprime // => /eqnP pn1.\nhave [a _ /dvdnP[b]] := Bezoutl n (prime_gt0 charf_prime).\nmove/(congr1 (fun m => m%:R : R))/eqP.\nby rewrite natrD !natrM charf0 n0 !mulr0 pn1 addr0 oner_eq0.\nQed.\n\nLemma charf_eq : [char R] =i (p : nat_pred).\nProof.\nmove=> q; apply/andP/eqP=> [[q_pr q0] | ->]; last by rewrite charf0.\nby apply/eqP; rewrite eq_sym -dvdn_prime2 // dvdn_charf.\nQed.\n\nLemma bin_lt_charf_0 k : 0 < k < p -> 'C(p, k)%:R = 0 :> R.\nProof. by move=> lt0kp; apply/eqP; rewrite -dvdn_charf prime_dvd_bin. Qed.\n\nLocal Notation \"x ^f\" := (Frobenius_aut charFp x).\n\nLemma Frobenius_autE x : x^f = x ^+ p. Proof. by []. Qed.\nLocal Notation fE := Frobenius_autE.\n\nLemma Frobenius_aut0 : 0^f = 0.\nProof. by rewrite fE -(prednK (prime_gt0 charf_prime)) exprS mul0r. Qed.\n\nLemma Frobenius_aut1 : 1^f = 1.\nProof. by rewrite fE expr1n. Qed.\n\nLemma Frobenius_autD_comm x y (cxy : comm x y) : (x + y)^f = x^f + y^f.\nProof.\nhave defp := prednK (prime_gt0 charf_prime).\nrewrite !fE exprDn_comm // big_ord_recr subnn -defp big_ord_recl /= defp.\nrewrite subn0 mulr1 mul1r bin0 binn big1 ?addr0 // => i _.\nby rewrite -mulr_natl bin_lt_charf_0 ?mul0r //= -{2}defp ltnS (valP i).\nQed.\n\nLemma Frobenius_autMn x n : (x *+ n)^f = x^f *+ n.\nProof.\nelim: n => [|n IHn]; first exact: Frobenius_aut0.\nrewrite !mulrS Frobenius_autD_comm ?IHn //; exact: commrMn.\nQed.\n\nLemma Frobenius_aut_nat n : (n%:R)^f = n%:R.\nProof. by rewrite Frobenius_autMn Frobenius_aut1. Qed.\n\nLemma Frobenius_autM_comm x y : comm x y -> (x * y)^f = x^f * y^f.\nProof. by exact: exprMn_comm. Qed.\n\nLemma Frobenius_autX x n : (x ^+ n)^f = x^f ^+ n.\nProof. by rewrite !fE -!exprM mulnC. Qed.\n\nLemma Frobenius_autN x : (- x)^f = - x^f.\nProof.\napply/eqP; rewrite -subr_eq0 opprK addrC.\nby rewrite -(Frobenius_autD_comm (commrN _)) // subrr Frobenius_aut0.\nQed.\n\nLemma Frobenius_autB_comm x y : comm x y -> (x - y)^f = x^f - y^f.\nProof.\nby move/commrN/Frobenius_autD_comm->; rewrite Frobenius_autN.\nQed.\n\nEnd FrobeniusAutomorphism.\n\nLemma exprNn_char x n : [char R].-nat n -> (- x) ^+ n = - (x ^+ n).\nProof.\npose p := pdiv n; have [|n_gt1 charRn] := leqP n 1; first by case: (n) => [|[]].\nhave charRp: p \\in [char R] by rewrite (pnatPpi charRn) // pi_pdiv.\nhave /p_natP[e ->]: p.-nat n by rewrite -(eq_pnat _ (charf_eq charRp)).\nelim: e => // e IHe; rewrite expnSr !exprM {}IHe.\nby rewrite -Frobenius_autE Frobenius_autN.\nQed.\n\nSection Char2.\n\nHypothesis charR2 : 2 \\in [char R].\n\nLemma addrr_char2 x : x + x = 0. Proof. by rewrite -mulr2n mulrn_char. Qed.\n\nLemma oppr_char2 x : - x = x.\nProof. by apply/esym/eqP; rewrite -addr_eq0 addrr_char2. Qed.\n\nLemma subr_char2 x y : x - y = x + y. Proof. by rewrite oppr_char2. Qed.\n\nLemma addrK_char2 x : involutive (+%R^~ x).\nProof. by move=> y; rewrite /= -subr_char2 addrK. Qed.\n\nLemma addKr_char2 x : involutive (+%R x).\nProof. by move=> y; rewrite -{1}[x]oppr_char2 addKr. Qed.\n\nEnd Char2.\n\nCanonical converse_eqType := [eqType of R^c].\nCanonical converse_choiceType := [choiceType of R^c].\nCanonical converse_zmodType := [zmodType of R^c].\n\nDefinition converse_ringMixin :=\n  let mul' x y := y * x in\n  let mulrA' x y z := esym (mulrA z y x) in\n  let mulrDl' x y z := mulrDr z x y in\n  let mulrDr' x y z := mulrDl y z x in\n  @Ring.Mixin converse_zmodType\n    1 mul' mulrA' mulr1 mul1r mulrDl' mulrDr' oner_neq0.\nCanonical converse_ringType := RingType R^c converse_ringMixin.\n\nSection ClosedPredicates.\n\nVariable S : predPredType R.\n\nDefinition mulr_2closed := {in S &, forall u v, u * v \\in S}.\nDefinition mulr_closed := 1 \\in S /\\ mulr_2closed.\nDefinition smulr_closed := -1 \\in S /\\ mulr_2closed.\nDefinition semiring_closed := addr_closed S /\\ mulr_closed.\nDefinition subring_closed := [/\\ 1 \\in S, subr_2closed S & mulr_2closed].\n\nLemma smulr_closedM : smulr_closed -> mulr_closed.\nProof. by case=> SN1 SM; split=> //; rewrite -[1]mulr1 -mulrNN SM. Qed.\n\nLemma smulr_closedN : smulr_closed -> oppr_closed S.\nProof. by case=> SN1 SM x Sx; rewrite -mulN1r SM. Qed.\n\nLemma semiring_closedD : semiring_closed -> addr_closed S. Proof. by case. Qed.\n\nLemma semiring_closedM : semiring_closed -> mulr_closed. Proof. by case. Qed.\n\nLemma subring_closedB : subring_closed -> zmod_closed S.\nProof. by case=> S1 SB _; split; rewrite // -(subrr 1) SB. Qed.\n\nLemma subring_closedM : subring_closed -> smulr_closed.\nProof.\nby case=> S1 SB SM; split; rewrite ?(zmod_closedN (subring_closedB _)).\nQed.\n\nLemma subring_closed_semi : subring_closed -> semiring_closed.\nProof.\nby move=> ringS; split; [apply/zmod_closedD/subring_closedB | case: ringS].\nQed.\n \nEnd ClosedPredicates.\n\nEnd RingTheory.\n\nSection RightRegular.\n\nVariable R : ringType.\nImplicit Types x y : R.\nLet Rc := converse_ringType R.\n\nLemma mulIr_eq0 x y : rreg x -> (y * x == 0) = (y == 0).\nProof. exact: (@mulrI_eq0 Rc). Qed.\n\nLemma mulIr0_rreg x : (forall y, y * x = 0 -> y = 0) -> rreg x.\nProof. exact: (@mulrI0_lreg Rc). Qed.\n\nLemma rreg_neq0 x : rreg x -> x != 0.\nProof. exact: (@lreg_neq0 Rc). Qed.\n\nLemma rregN x : rreg x -> rreg (- x).\nProof. exact: (@lregN Rc). Qed.\n\nLemma rreg1 : rreg (1 : R).\nProof. exact: (@lreg1 Rc). Qed.\n\nLemma rregM x y : rreg x -> rreg y -> rreg (x * y).\nProof. by move=> reg_x reg_y; exact: (@lregM Rc). Qed.\n\nLemma revrX x n : (x : Rc) ^+ n = (x : R) ^+ n.\nProof. by elim: n => // n IHn; rewrite exprS exprSr IHn. Qed.\n\nLemma rregX x n : rreg x -> rreg (x ^+ n).\nProof. by move/(@lregX Rc x n); rewrite revrX. Qed.\n\nEnd RightRegular.\n\nModule Lmodule.\n\nStructure mixin_of (R : ringType) (V : zmodType) : Type := Mixin {\n  scale : R -> V -> V;\n  _ : forall a b v, scale a (scale b v) = scale (a * b) v;\n  _ : left_id 1 scale;\n  _ : right_distributive scale +%R;\n  _ : forall v, {morph scale^~ v: a b / a + b}\n}.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nStructure class_of V := Class {\n  base : Zmodule.class_of V;\n  mixin : mixin_of R (Zmodule.Pack base V)\n}.\nLocal Coercion base : class_of >-> Zmodule.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\n\nDefinition pack b0 (m0 : mixin_of R (@Zmodule.Pack T b0 T)) :=\n  fun bT b & phant_id (Zmodule.class bT) b =>\n  fun    m & phant_id m0 m => Pack phR (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Import Exports.\nCoercion base : class_of >-> Zmodule.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nNotation lmodType R := (type (Phant R)).\nNotation LmodType R T m := (@pack _ (Phant R) T _ m _ _ id _ id).\nNotation LmodMixin := Mixin.\nNotation \"[ 'lmodType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'lmodType'  R  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'lmodType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'lmodType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Lmodule.\nImport Lmodule.Exports.\n\nDefinition scale (R : ringType) (V : lmodType R) :=\n  Lmodule.scale (Lmodule.class V).\n\nLocal Notation \"*:%R\" := (@scale _ _).\nLocal Notation \"a *: v\" := (scale a v) : ring_scope.\n\nSection LmoduleTheory.\n\nVariables (R : ringType) (V : lmodType R).\nImplicit Types (a b c : R) (u v : V).\n\nLocal Notation \"*:%R\" := (@scale R V).\n\nLemma scalerA a b v : a *: (b *: v) = a * b *: v.\nProof. by case: V v => ? [] ? []. Qed.\n\nLemma scale1r : @left_id R V 1 *:%R.\nProof. by case: V => ? [] ? []. Qed.\n\nLemma scalerDr a : {morph *:%R a : u v / u + v}.\nProof. by case: V a => ? [] ? []. Qed.\n\nLemma scalerDl v : {morph *:%R^~ v : a b / a + b}.\nProof. by case: V v => ? [] ? []. Qed.\n\nLemma scale0r v : 0 *: v = 0.\nProof. by apply: (addIr (1 *: v)); rewrite -scalerDl !add0r. Qed.\n\nLemma scaler0 a : a *: 0 = 0 :> V.\nProof. by rewrite -{1}(scale0r 0) scalerA mulr0 scale0r. Qed.\n\nLemma scaleNr a v : - a *: v = - (a *: v).\nProof. by apply: (addIr (a *: v)); rewrite -scalerDl !addNr scale0r. Qed.\n\nLemma scaleN1r v : (- 1) *: v = - v.\nProof. by rewrite scaleNr scale1r. Qed.\n\nLemma scalerN a v : a *: (- v) = - (a *: v).\nProof. by apply: (addIr (a *: v)); rewrite -scalerDr !addNr scaler0. Qed.\n\nLemma scalerBl a b v : (a - b) *: v = a *: v - b *: v.\nProof. by rewrite scalerDl scaleNr. Qed.\n\nLemma scalerBr a u v : a *: (u - v) = a *: u - a *: v.\nProof. by rewrite scalerDr scalerN. Qed.\n\nLemma scaler_nat n v : n%:R *: v = v *+ n.\nProof.\nelim: n => /= [|n ]; first by rewrite scale0r.\nby rewrite !mulrS scalerDl ?scale1r => ->.\nQed.\n\nLemma scaler_sign (b : bool) v: (-1) ^+ b *: v = (if b then - v else v).\nProof. by case: b; rewrite ?scaleNr scale1r. Qed.\n\nLemma signrZK n : @involutive V ( *:%R ((-1) ^+ n)).\nProof. by move=> u; rewrite scalerA -expr2 sqrr_sign scale1r. Qed.\n\nLemma scalerMnl a v n : a *: v *+ n = (a *+ n) *: v.\nProof.\nelim: n => [|n IHn]; first by rewrite !mulr0n scale0r.\nby rewrite !mulrSr IHn scalerDl.\nQed.\n\nLemma scalerMnr a v n : a *: v *+ n = a *: (v *+ n).\nProof.\nelim: n => [|n IHn]; first by rewrite !mulr0n scaler0.\nby rewrite !mulrSr IHn scalerDr.\nQed.\n\nLemma scaler_suml v I r (P : pred I) F :\n  (\\sum_(i <- r | P i) F i) *: v = \\sum_(i <- r | P i) F i *: v.\nProof. exact: (big_morph _ (scalerDl v) (scale0r v)). Qed.\n\nLemma scaler_sumr a I r (P : pred I) (F : I -> V) :\n  a *: (\\sum_(i <- r | P i) F i) = \\sum_(i <- r | P i) a *: F i.\nProof. exact: big_endo (scalerDr a) (scaler0 a) I r P F. Qed.\n\nSection ClosedPredicates.\n\nVariable S : predPredType V.\n\nDefinition scaler_closed := forall a, {in S, forall v, a *: v \\in S}.\nDefinition linear_closed := forall a, {in S &, forall u v, a *: u + v \\in S}.\nDefinition submod_closed := 0 \\in S /\\ linear_closed.\n\nLemma linear_closedB : linear_closed -> subr_2closed S.\nProof. by move=> Slin u v Su Sv; rewrite addrC -scaleN1r Slin. Qed.\n\nLemma submod_closedB : submod_closed -> zmod_closed S.\nProof. by case=> S0 /linear_closedB. Qed.\n\nLemma submod_closedZ : submod_closed -> scaler_closed.\nProof. by case=> S0 Slin a v Sv; rewrite -[a *: v]addr0 Slin. Qed.\n\nEnd ClosedPredicates.\n\nEnd LmoduleTheory.\n\nModule Lalgebra.\n\nDefinition axiom (R : ringType) (V : lmodType R) (mul : V -> V -> V) :=\n  forall a u v, a *: mul u v = mul (a *: u) v.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nRecord class_of (T : Type) : Type := Class {\n  base : Ring.class_of T;\n  mixin : Lmodule.mixin_of R (Zmodule.Pack base T);\n  ext : @axiom R (Lmodule.Pack _ (Lmodule.Class mixin) T) (Ring.mul base)\n}.\nDefinition base2 R m := Lmodule.Class (@mixin R m).\nLocal Coercion base : class_of >-> Ring.class_of.\nLocal Coercion base2 : class_of >-> Lmodule.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack T b0 mul0 (axT : @axiom R (@Lmodule.Pack R _ T b0 T) mul0) :=\n  fun bT b & phant_id (Ring.class bT) (b : Ring.class_of T) =>\n  fun mT m & phant_id (@Lmodule.class R phR mT) (@Lmodule.Class R T b m) =>\n  fun ax & phant_id axT ax =>\n  Pack (Phant R) (@Class T b m ax) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\nDefinition lmodType := @Lmodule.Pack R phR cT xclass xT.\nDefinition lmod_ringType := @Lmodule.Pack R phR ringType xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Ring.class_of.\nCoercion base2 : class_of >-> Lmodule.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCanonical lmod_ringType.\nNotation lalgType R := (type (Phant R)).\nNotation LalgType R T a := (@pack _ (Phant R) T _ _ a _ _ id _ _ id _ id).\nNotation \"[ 'lalgType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'lalgType'  R  'of'  T  'for'  cT ]\")\n  : form_scope.\nNotation \"[ 'lalgType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'lalgType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Lalgebra.\nImport Lalgebra.Exports.\n\n(* Scalar injection (see the definition of in_alg A below). *)\nLocal Notation \"k %:A\" := (k *: 1) : ring_scope.\n\n(* Regular ring algebra tag. *)\nDefinition regular R : Type := R.\nLocal Notation \"R ^o\" := (regular R) (at level 2, format \"R ^o\") : type_scope.\n\nSection LalgebraTheory.\n\nVariables (R : ringType) (A : lalgType R).\nImplicit Types x y : A.\n\nLemma scalerAl k (x y : A) : k *: (x * y) = k *: x * y.\nProof. by case: A k x y => ? []. Qed.\n\nLemma mulr_algl a x : a%:A * x = a *: x.\nProof. by rewrite -scalerAl mul1r. Qed.\n\nCanonical regular_eqType := [eqType of R^o].\nCanonical regular_choiceType := [choiceType of R^o].\nCanonical regular_zmodType := [zmodType of R^o].\nCanonical regular_ringType := [ringType of R^o].\n\nDefinition regular_lmodMixin :=\n  let mkMixin := @Lmodule.Mixin R regular_zmodType (@mul R) in\n  mkMixin (@mulrA R) (@mul1r R) (@mulrDr R) (fun v a b => mulrDl a b v).\n\nCanonical regular_lmodType := LmodType R R^o regular_lmodMixin.\nCanonical regular_lalgType := LalgType R R^o (@mulrA regular_ringType).\n\nSection ClosedPredicates.\n\nVariable S : predPredType A.\n\nDefinition subalg_closed := [/\\ 1 \\in S, linear_closed S & mulr_2closed S].\n\nLemma subalg_closedZ : subalg_closed -> submod_closed S.\nProof. by case=> S1 Slin _; split; rewrite // -(subrr 1) linear_closedB. Qed.\n\nLemma subalg_closedBM : subalg_closed -> subring_closed S.\nProof. by case=> S1 Slin SM; split=> //; apply: linear_closedB. Qed.\n\nEnd ClosedPredicates.\n\nEnd LalgebraTheory.\n\n(* Morphism hierarchy. *)\n\nModule Additive.\n\nSection ClassDef.\n\nVariables U V : zmodType.\n\nDefinition axiom (f : U -> V) := {morph f : x y / x - y}.\n\nStructure map (phUV : phant (U -> V)) := Pack {apply; _ : axiom apply}.\nLocal Coercion apply : map >-> Funclass.\n\nVariables (phUV : phant (U -> V)) (f g : U -> V) (cF : map phUV).\nDefinition class := let: Pack _ c as cF' := cF return axiom cF' in c.\nDefinition clone fA of phant_id g (apply cF) & phant_id fA class :=\n  @Pack phUV f fA.\n\nEnd ClassDef.\n\nModule Exports.\nNotation additive f := (axiom f).\nCoercion apply : map >-> Funclass.\nNotation Additive fA := (Pack (Phant _) fA).\nNotation \"{ 'additive' fUV }\" := (map (Phant fUV))\n  (at level 0, format \"{ 'additive'  fUV }\") : ring_scope.\nNotation \"[ 'additive' 'of' f 'as' g ]\" := (@clone _ _ _ f g _ _ idfun id)\n  (at level 0, format \"[ 'additive'  'of'  f  'as'  g ]\") : form_scope.\nNotation \"[ 'additive' 'of' f ]\" := (@clone _ _ _ f f _ _ id id)\n  (at level 0, format \"[ 'additive'  'of'  f ]\") : form_scope.\nEnd Exports.\n\nEnd Additive.\nInclude Additive.Exports. (* Allows GRing.additive to resolve conflicts. *)\n\n(* Lifted additive operations. *)\nSection LiftedZmod.\nVariables (U : Type) (V : zmodType).\nDefinition null_fun_head (phV : phant V) of U : V := let: Phant := phV in 0.\nDefinition add_fun_head t (f g : U -> V) x := let: tt := t in f x + g x.\nDefinition sub_fun_head t (f g : U -> V) x := let: tt := t in f x - g x.\nEnd LiftedZmod.\n\n(* Lifted multiplication. *)\nSection LiftedRing.\nVariables (R : ringType) (T : Type).\nImplicit Type f : T -> R.\nDefinition mull_fun_head t a f x := let: tt := t in a * f x.\nDefinition mulr_fun_head t a f x := let: tt := t in f x * a.\nEnd LiftedRing.\n\n(* Lifted linear operations. *)\nSection LiftedScale.\nVariables (R : ringType) (U : Type) (V : lmodType R) (A : lalgType R).\nDefinition scale_fun_head t a (f : U -> V) x := let: tt := t in a *: f x.\nDefinition in_alg_head (phA : phant A) k : A := let: Phant := phA in k%:A.\nEnd LiftedScale.\n\nNotation null_fun V := (null_fun_head (Phant V)) (only parsing).\n(* The real in_alg notation is declared after GRing.Theory so that at least *)\n(* in Coq 8.2 it gets precedence when GRing.Theory is not imported.         *)\nLocal Notation in_alg_loc A := (in_alg_head (Phant A)) (only parsing).\n\nLocal Notation \"\\0\" := (null_fun _) : ring_scope.\nLocal Notation \"f \\+ g\" := (add_fun_head tt f g) : ring_scope.\nLocal Notation \"f \\- g\" := (sub_fun_head tt f g) : ring_scope.\nLocal Notation \"a \\*: f\" := (scale_fun_head tt a f) : ring_scope.\nLocal Notation \"x \\*o f\" := (mull_fun_head tt x f) : ring_scope.\nLocal Notation \"x \\o* f\" := (mulr_fun_head tt x f) : ring_scope.\n\nSection AdditiveTheory.\n\nSection Properties.\n\nVariables (U V : zmodType) (k : unit) (f : {additive U -> V}).\n\nLemma raddfB : {morph f : x y / x - y}. Proof. exact: Additive.class. Qed.\n\nLemma raddf0 : f 0 = 0.\nProof. by rewrite -[0]subr0 raddfB subrr. Qed.\n\nLemma raddf_eq0 x : injective f -> (f x == 0) = (x == 0).\nProof. by move=> /inj_eq <-; rewrite raddf0. Qed.\n\nLemma raddfN : {morph f : x / - x}.\nProof. by move=> x /=; rewrite -sub0r raddfB raddf0 sub0r. Qed.\n\nLemma raddfD : {morph f : x y / x + y}.\nProof. by move=> x y; rewrite -[y]opprK raddfB -raddfN. Qed.\n\nLemma raddfMn n : {morph f : x / x *+ n}.\nProof. by elim: n => [|n IHn] x /=; rewrite ?raddf0 // !mulrS raddfD IHn. Qed.\n\nLemma raddfMNn n : {morph f : x / x *- n}.\nProof. by move=> x /=; rewrite raddfN raddfMn. Qed.\n\nLemma raddf_sum I r (P : pred I) E :\n  f (\\sum_(i <- r | P i) E i) = \\sum_(i <- r | P i) f (E i).\nProof. exact: (big_morph f raddfD raddf0). Qed.\n\nLemma can2_additive f' : cancel f f' -> cancel f' f -> additive f'.\nProof. by move=> fK f'K x y /=; apply: (canLR fK); rewrite raddfB !f'K. Qed.\n\nLemma bij_additive :\n  bijective f -> exists2 f' : {additive V -> U}, cancel f f' & cancel f' f.\nProof. by case=> f' fK f'K; exists (Additive (can2_additive fK f'K)). Qed.\n\nFact locked_is_additive : additive (locked_with k (f : U -> V)).\nProof. by case: k f => [] []. Qed.\nCanonical locked_additive := Additive locked_is_additive.\n\nEnd Properties.\n\nSection RingProperties.\n\nVariables (R S : ringType) (f : {additive R -> S}).\n\nLemma raddfMnat n x : f (n%:R * x) = n%:R * f x.\nProof. by rewrite !mulr_natl raddfMn. Qed.\n\nLemma raddfMsign n x : f ((-1) ^+ n * x) = (-1) ^+ n * f x.\nProof. by rewrite !(mulr_sign, =^~ signr_odd) (fun_if f) raddfN. Qed.\n\nVariables (U : lmodType R) (V : lmodType S) (h : {additive U -> V}).\n\nLemma raddfZnat n u : h (n%:R *: u) = n%:R *: h u.\nProof. by rewrite !scaler_nat raddfMn. Qed.\n\nLemma raddfZsign n u : h ((-1) ^+ n *: u) = (-1) ^+ n *: h u.\nProof. by rewrite !(scaler_sign, =^~ signr_odd) (fun_if h) raddfN. Qed.\n\nEnd RingProperties.\n\nSection AddFun.\n\nVariables (U V W : zmodType) (f g : {additive V -> W}) (h : {additive U -> V}).\n\nFact idfun_is_additive : additive (@idfun U).\nProof. by []. Qed.\nCanonical idfun_additive := Additive idfun_is_additive.\n\nFact comp_is_additive : additive (f \\o h).\nProof. by move=> x y /=; rewrite !raddfB. Qed.\nCanonical comp_additive := Additive comp_is_additive.\n\nFact opp_is_additive : additive (-%R : U -> U).\nProof. by move=> x y; rewrite /= opprD. Qed.\nCanonical opp_additive := Additive opp_is_additive.\n\nFact null_fun_is_additive : additive (\\0 : U -> V).\nProof. by move=> /=; rewrite subr0. Qed.\nCanonical null_fun_additive := Additive null_fun_is_additive.\n\nFact add_fun_is_additive : additive (f \\+ g).\nProof.\nby move=> x y /=; rewrite !raddfB addrCA -!addrA addrCA -opprD.\nQed.\nCanonical add_fun_additive := Additive add_fun_is_additive.\n\nFact sub_fun_is_additive : additive (f \\- g).\nProof.\nby move=> x y /=; rewrite !raddfB addrAC -!addrA -!opprD addrAC addrA.\nQed.\nCanonical sub_fun_additive := Additive sub_fun_is_additive.\n\nEnd AddFun.\n\nSection MulFun.\n\nVariables (R : ringType) (U : zmodType).\nVariables (a : R) (f : {additive U -> R}).\n\nFact mull_fun_is_additive : additive (a \\*o f).\nProof. by move=> x y /=; rewrite raddfB mulrBr. Qed.\nCanonical mull_fun_additive := Additive mull_fun_is_additive.\n\nFact mulr_fun_is_additive : additive (a \\o* f).\nProof. by move=> x y /=; rewrite raddfB mulrBl. Qed.\nCanonical mulr_fun_additive := Additive mulr_fun_is_additive.\n\nEnd MulFun.\n\nSection ScaleFun.\n\nVariables (R : ringType) (U : zmodType) (V : lmodType R).\nVariables (a : R) (f : {additive U -> V}).\n\nCanonical scale_additive := Additive (@scalerBr R V a).\nCanonical scale_fun_additive := [additive of a \\*: f as f \\; *:%R a].\n\nEnd ScaleFun.\n\nEnd AdditiveTheory.\n\nModule RMorphism.\n\nSection ClassDef.\n\nVariables R S : ringType.\n\nDefinition mixin_of (f : R -> S) :=\n  {morph f : x y / x * y}%R * (f 1 = 1) : Prop.\n\nRecord class_of f : Prop := Class {base : additive f; mixin : mixin_of f}.\nLocal Coercion base : class_of >-> additive.\n\nStructure map (phRS : phant (R -> S)) := Pack {apply; _ : class_of apply}.\nLocal Coercion apply : map >-> Funclass.\nVariables (phRS : phant (R -> S)) (f g : R -> S) (cF : map phRS).\n\nDefinition class := let: Pack _ c as cF' := cF return class_of cF' in c.\n\nDefinition clone fM of phant_id g (apply cF) & phant_id fM class :=\n  @Pack phRS f fM.\n\nDefinition pack (fM : mixin_of f) :=\n  fun (bF : Additive.map phRS) fA & phant_id (Additive.class bF) fA =>\n  Pack phRS (Class fA fM).\n\nCanonical additive := Additive.Pack phRS class.\n\nEnd ClassDef.\n\nModule Exports.\nNotation multiplicative f := (mixin_of f).\nNotation rmorphism f := (class_of f).\nCoercion base : rmorphism >-> Additive.axiom.\nCoercion mixin : rmorphism >-> multiplicative.\nCoercion apply : map >-> Funclass.\nNotation RMorphism fM := (Pack (Phant _) fM).\nNotation AddRMorphism fM := (pack fM id).\nNotation \"{ 'rmorphism' fRS }\" := (map (Phant fRS))\n  (at level 0, format \"{ 'rmorphism'  fRS }\") : ring_scope.\nNotation \"[ 'rmorphism' 'of' f 'as' g ]\" := (@clone _ _ _ f g _ _ idfun id)\n  (at level 0, format \"[ 'rmorphism'  'of'  f  'as'  g ]\") : form_scope.\nNotation \"[ 'rmorphism' 'of' f ]\" := (@clone _ _ _ f f _ _ id id)\n  (at level 0, format \"[ 'rmorphism'  'of'  f ]\") : form_scope.\nCoercion additive : map >-> Additive.map.\nCanonical additive.\nEnd Exports.\n\nEnd RMorphism.\nInclude RMorphism.Exports.\n\nSection RmorphismTheory.\n\nSection Properties.\n\nVariables (R S : ringType) (k : unit) (f : {rmorphism R -> S}).\n\nLemma rmorph0 : f 0 = 0. Proof. exact: raddf0. Qed.\nLemma rmorphN : {morph f : x / - x}. Proof. exact: raddfN. Qed.\nLemma rmorphD : {morph f : x y / x + y}. Proof. exact: raddfD. Qed.\nLemma rmorphB : {morph f: x y / x - y}. Proof. exact: raddfB. Qed.\nLemma rmorphMn n : {morph f : x / x *+ n}. Proof. exact: raddfMn. Qed.\nLemma rmorphMNn n : {morph f : x / x *- n}. Proof. exact: raddfMNn. Qed.\nLemma rmorph_sum I r (P : pred I) E :\n  f (\\sum_(i <- r | P i) E i) = \\sum_(i <- r | P i) f (E i).\nProof. exact: raddf_sum. Qed.\nLemma rmorphMsign n : {morph f : x / (- 1) ^+ n * x}.\nProof. exact: raddfMsign. Qed.\n\nLemma rmorphismP : rmorphism f. Proof. exact: RMorphism.class. Qed.\nLemma rmorphismMP : multiplicative f. Proof. exact: rmorphismP. Qed.\nLemma rmorph1 : f 1 = 1. Proof. by case: rmorphismMP. Qed.\nLemma rmorphM : {morph f: x y  / x * y}. Proof. by case: rmorphismMP. Qed.\n\nLemma rmorph_prod I r (P : pred I) E :\n  f (\\prod_(i <- r | P i) E i) = \\prod_(i <- r | P i) f (E i).\nProof. exact: (big_morph f rmorphM rmorph1). Qed.\n\nLemma rmorphX n : {morph f: x / x ^+ n}.\nProof. by elim: n => [|n IHn] x; rewrite ?rmorph1 // !exprS rmorphM IHn. Qed.\n\nLemma rmorph_nat n : f n%:R = n%:R. Proof. by rewrite rmorphMn rmorph1. Qed.\nLemma rmorphN1 : f (- 1) = (- 1). Proof. by rewrite rmorphN rmorph1. Qed.\n\nLemma rmorph_sign n : f ((- 1) ^+ n) = (- 1) ^+ n.\nProof. by rewrite rmorphX rmorphN1. Qed.\n\nLemma rmorph_char p : p \\in [char R] -> p \\in [char S].\nProof. by rewrite !inE -rmorph_nat => /andP[-> /= /eqP->]; rewrite rmorph0. Qed.\n\nLemma rmorph_eq_nat x n : injective f -> (f x == n%:R) = (x == n%:R).\nProof. by move/inj_eq <-; rewrite rmorph_nat. Qed.\n\nLemma rmorph_eq1 x : injective f -> (f x == 1) = (x == 1).\nProof. exact: rmorph_eq_nat 1%N. Qed.\n\nLemma can2_rmorphism f' : cancel f f' -> cancel f' f -> rmorphism f'.\nProof.\nmove=> fK f'K; split; first exact: can2_additive fK f'K.\nby split=> [x y|]; apply: (canLR fK); rewrite /= (rmorphM, rmorph1) ?f'K.\nQed.\n\nLemma bij_rmorphism :\n  bijective f -> exists2 f' : {rmorphism S -> R}, cancel f f' & cancel f' f.\nProof. by case=> f' fK f'K; exists (RMorphism (can2_rmorphism fK f'K)). Qed.\n\nFact locked_is_multiplicative : multiplicative (locked_with k (f : R -> S)).\nProof. by case: k f => [] [? []]. Qed.\nCanonical locked_rmorphism := AddRMorphism locked_is_multiplicative.\n\nEnd Properties.\n\nSection Projections.\n\nVariables (R S T : ringType) (f : {rmorphism S -> T}) (g : {rmorphism R -> S}).\n\nFact idfun_is_multiplicative : multiplicative (@idfun R).\nProof. by []. Qed.\nCanonical idfun_rmorphism := AddRMorphism idfun_is_multiplicative.\n\nFact comp_is_multiplicative : multiplicative (f \\o g).\nProof. by split=> [x y|] /=; rewrite ?rmorph1 ?rmorphM. Qed.\nCanonical comp_rmorphism := AddRMorphism comp_is_multiplicative.\n\nEnd Projections.\n\nSection InAlgebra.\n\nVariables (R : ringType) (A : lalgType R).\n\nFact in_alg_is_rmorphism : rmorphism (in_alg_loc A).\nProof.\nsplit=> [x y|]; first exact: scalerBl.\nby split=> [x y|] /=; rewrite ?scale1r // -scalerAl mul1r scalerA.\nQed.\nCanonical in_alg_additive := Additive in_alg_is_rmorphism.\nCanonical in_alg_rmorphism := RMorphism in_alg_is_rmorphism.\n\nLemma in_algE a : in_alg_loc A a = a%:A. Proof. by []. Qed.\n\nEnd InAlgebra.\n\nEnd RmorphismTheory.\n\nModule Scale.\n\nSection ScaleLaw.\n\nStructure law (R : ringType) (V : zmodType) (s : R -> V -> V) := Law {\n  op : R -> V -> V;\n  _ : op = s;\n  _ : op (-1) =1 -%R;\n  _ : forall a, additive (op a)\n}.\n\nDefinition mul_law R := Law (erefl *%R) (@mulN1r R) (@mulrBr R).\nDefinition scale_law R U := Law (erefl *:%R) (@scaleN1r R U) (@scalerBr R U).\n\nVariables (R : ringType) (V : zmodType) (s : R -> V -> V) (s_law : law s).\nLocal Notation s_op := (op s_law).\n\nLemma opE : s_op = s. Proof. by case: s_law. Qed.\nLemma N1op : s_op (-1) =1 -%R. Proof. by case: s_law. Qed.\nFact opB a : additive (s_op a). Proof. by case: s_law. Qed.\nDefinition op_additive a := Additive (opB a).\n\nVariables (aR : ringType) (nu : {rmorphism aR -> R}).\nFact comp_opE : nu \\; s_op = nu \\; s. Proof. exact: congr1 opE. Qed.\nFact compN1op : (nu \\; s_op) (-1) =1 -%R.\nProof. by move=> v; rewrite /= rmorphN1 N1op. Qed.\nDefinition comp_law : law (nu \\; s) := Law comp_opE compN1op (fun a => opB _).\n\nEnd ScaleLaw.\n\nEnd Scale.\n\nModule Linear.\n\nSection ClassDef.\n\nVariables (R : ringType) (U : lmodType R) (V : zmodType) (s : R -> V -> V).\nImplicit Type phUV : phant (U -> V).\n\nLocal Coercion Scale.op : Scale.law >-> Funclass.\nDefinition axiom (f : U -> V) (s_law : Scale.law s) of s = s_law :=\n  forall a, {morph f : u v / a *: u + v >-> s a u + v}.\nDefinition mixin_of (f : U -> V) :=\n  forall a, {morph f : v / a *: v >-> s a v}.\n\nRecord class_of f : Prop := Class {base : additive f; mixin : mixin_of f}.\nLocal Coercion base : class_of >-> additive.\n\nLemma class_of_axiom f s_law Ds : @axiom f s_law Ds -> class_of f.\nProof.\nmove=> fL; have fB: additive f.\n  by move=> x y /=; rewrite -scaleN1r addrC fL Ds Scale.N1op addrC.\nby split=> // a v /=; rewrite -[a *: v](addrK v) fB fL addrK Ds.\nQed.\n\nStructure map (phUV : phant (U -> V)) := Pack {apply; _ : class_of apply}.\nLocal Coercion apply : map >-> Funclass.\n\nVariables (phUV : phant (U -> V)) (f g : U -> V) (cF : map phUV).\nDefinition class := let: Pack _ c as cF' := cF return class_of cF' in c.\nDefinition clone fL of phant_id g (apply cF) & phant_id fL class :=\n  @Pack phUV f fL.\n\nDefinition pack (fZ : mixin_of f) :=\n  fun (bF : Additive.map phUV) fA & phant_id (Additive.class bF) fA =>\n  Pack phUV (Class fA fZ).\n\nCanonical additive := Additive.Pack phUV class.\n\n(* Support for right-to-left rewriting with the generic linearZ rule. *)\nNotation mapUV := (map (Phant (U -> V))).\nDefinition map_class := mapUV.\nDefinition map_at (a : R) := mapUV.\nStructure map_for a s_a := MapFor {map_for_map : mapUV; _ : s a = s_a}.\nDefinition unify_map_at a (f : map_at a) := MapFor f (erefl (s a)).\nStructure wrapped := Wrap {unwrap : mapUV}.\nDefinition wrap (f : map_class) := Wrap f.\n\nEnd ClassDef.\n\nModule Exports.\nCanonical Scale.mul_law.\nCanonical Scale.scale_law.\nCanonical Scale.comp_law.\nCanonical Scale.op_additive.\nDelimit Scope linear_ring_scope with linR.\nNotation \"a *: u\" := (@Scale.op _ _ *:%R _ a u) : linear_ring_scope.\nNotation \"a * u\" := (@Scale.op _ _ *%R _ a u) : linear_ring_scope.\nNotation \"a *:^ nu u\" := (@Scale.op _ _ (nu \\; *:%R) _ a u)\n  (at level 40, nu at level 1, format \"a  *:^ nu  u\") : linear_ring_scope.\nNotation \"a *^ nu u\" := (@Scale.op _ _ (nu \\; *%R) _ a u)\n  (at level 40, nu at level 1, format \"a  *^ nu  u\") : linear_ring_scope.\nNotation scalable_for s f := (mixin_of s f).\nNotation scalable f := (scalable_for *:%R f).\nNotation linear_for s f := (axiom f (erefl s)).\nNotation linear f := (linear_for *:%R f).\nNotation scalar f := (linear_for *%R f).\nNotation lmorphism_for s f := (class_of s f).\nNotation lmorphism f := (lmorphism_for *:%R f).\nCoercion class_of_axiom : axiom >-> lmorphism_for.\nCoercion base : lmorphism_for >-> Additive.axiom.\nCoercion mixin : lmorphism_for >-> scalable.\nCoercion apply : map >-> Funclass.\nNotation Linear fL := (Pack (Phant _) fL).\nNotation AddLinear fZ := (pack fZ id).\nNotation \"{ 'linear' fUV | s }\" := (map s (Phant fUV))\n  (at level 0, format \"{ 'linear'  fUV  |  s }\") : ring_scope.\nNotation \"{ 'linear' fUV }\" := {linear fUV | *:%R}\n  (at level 0, format \"{ 'linear'  fUV }\") : ring_scope.\nNotation \"{ 'scalar' U }\" := {linear U -> _ | *%R}\n  (at level 0, format \"{ 'scalar'  U }\") : ring_scope.\nNotation \"[ 'linear' 'of' f 'as' g ]\" := (@clone _ _ _ _ _ f g _ _ idfun id)\n  (at level 0, format \"[ 'linear'  'of'  f  'as'  g ]\") : form_scope.\nNotation \"[ 'linear' 'of' f ]\" := (@clone _ _ _ _ _ f f _ _ id id)\n  (at level 0, format \"[ 'linear'  'of'  f ]\") : form_scope.\nCoercion additive : map >-> Additive.map.\nCanonical additive.\n(* Support for right-to-left rewriting with the generic linearZ rule. *)\nCoercion map_for_map : map_for >-> map.\nCoercion unify_map_at : map_at >-> map_for.\nCanonical unify_map_at.\nCoercion unwrap : wrapped >-> map.\nCoercion wrap : map_class >-> wrapped.\nCanonical wrap.\nEnd Exports.\n\nEnd Linear.\nInclude Linear.Exports.\n\nSection LinearTheory.\n\nVariable R : ringType.\n\nSection GenericProperties.\n\nVariables (U : lmodType R) (V : zmodType) (s : R -> V -> V) (k : unit).\nVariable f : {linear U -> V | s}.\n\nLemma linear0 : f 0 = 0. Proof. exact: raddf0. Qed.\nLemma linearN : {morph f : x / - x}. Proof. exact: raddfN. Qed.\nLemma linearD : {morph f : x y / x + y}. Proof. exact: raddfD. Qed.\nLemma linearB : {morph f : x y / x - y}. Proof. exact: raddfB. Qed.\nLemma linearMn n : {morph f : x / x *+ n}. Proof. exact: raddfMn. Qed.\nLemma linearMNn n : {morph f : x / x *- n}. Proof. exact: raddfMNn. Qed.\nLemma linear_sum I r (P : pred I) E :\n  f (\\sum_(i <- r | P i) E i) = \\sum_(i <- r | P i) f (E i).\nProof. exact: raddf_sum. Qed.\n\nLemma linearZ_LR : scalable_for s f. Proof. by case: f => ? []. Qed.\nLemma linearP a : {morph f : u v / a *: u + v >-> s a u + v}.\nProof. by move=> u v /=; rewrite linearD linearZ_LR. Qed.\n\nFact locked_is_scalable : scalable_for s (locked_with k (f : U -> V)).\nProof. by case: k f => [] [? []]. Qed.\nCanonical locked_linear := AddLinear locked_is_scalable.\n\nEnd GenericProperties.\n\nSection BidirectionalLinearZ.\n\nVariables (U : lmodType R) (V : zmodType) (s : R -> V -> V).\n\n(*   The general form of the linearZ lemma uses some bespoke interfaces to   *)\n(* allow right-to-left rewriting when a composite scaling operation such as  *)\n(* conjC \\; *%R has been expanded, say in a^* * f u. This redex is matched   *)\n(* by using the Scale.law interface to recognize a \"head\" scaling operation  *)\n(* h (here *%R), stow away its \"scalar\" c, then reconcile h c and s a, once  *)\n(* s is known, that is, once the Linear.map structure for f has been found.  *)\n(* In general, s and a need not be equal to h and c; indeed they need not    *)\n(* have the same type! The unification is performed by the unify_map_at      *)\n(* default instance for the Linear.map_for U s a h_c sub-interface of        *)\n(* Linear.map; the h_c pattern uses the Scale.law structure to insure it is  *)\n(* inferred when rewriting right-to-left.                                    *)\n(*   The wrap on the rhs allows rewriting f (a *: b *: u) into a *: b *: f u *)\n(* with rewrite !linearZ /= instead of rewrite linearZ /= linearZ /=.        *)\n(* Without it, the first rewrite linearZ would produce                       *)\n(*    (a *: apply (map_for_map (@check_map_at .. a f)) (b *: u)%R)%Rlin      *)\n(* and matching the second rewrite LHS would bypass the unify_map_at default *)\n(* instance for b, reuse the one for a, and subsequently fail to match the   *)\n(* b *: u argument. The extra wrap / unwrap ensures that this can't happen.  *)\n(* In the RL direction, the wrap / unwrap will be inserted on the redex side *)\n(* as needed, without causing unnecessary delta-expansion: using an explicit *)\n(* identity function would have Coq normalize the redex to head normal, then *)\n(* reduce the identity to expose the map_for_map projection, and the         *)\n(* expanded Linear.map structure would then be exposed in the result.        *)\n(*   Most of this machinery will be invisible to a casual user, because all  *)\n(* the projections and default instances involved are declared as coercions. *)\n\nVariables (S : ringType) (h : S -> V -> V) (h_law : Scale.law h).\n\nLemma linearZ c a (h_c := Scale.op h_law c) (f : Linear.map_for U s a h_c) u :\n  f (a *: u) = h_c (Linear.wrap f u).\nProof. by rewrite linearZ_LR; case: f => f /= ->. Qed.\n\nEnd BidirectionalLinearZ.\n\nSection LmodProperties.\n\nVariables (U V : lmodType R) (f : {linear U -> V}).\n\nLemma linearZZ : scalable f. Proof. exact: linearZ_LR. Qed.\nLemma linearPZ : linear f. Proof. exact: linearP. Qed.\n\nLemma can2_linear f' : cancel f f' -> cancel f' f -> linear f'.\nProof. by move=> fK f'K a x y /=; apply: (canLR fK); rewrite linearP !f'K. Qed.\n\nLemma bij_linear :\n  bijective f -> exists2 f' : {linear V -> U}, cancel f f' & cancel f' f.\nProof. by case=> f' fK f'K; exists (Linear (can2_linear fK f'K)). Qed.\n\nEnd LmodProperties.\n\nSection ScalarProperties.\n\nVariable (U : lmodType R) (f : {scalar U}).\n\nLemma scalarZ : scalable_for *%R f. Proof. exact: linearZ_LR. Qed.\nLemma scalarP : scalar f. Proof. exact: linearP. Qed.\n\nEnd ScalarProperties.\n\nSection LinearLmod.\n\nVariables (W U : lmodType R) (V : zmodType) (s : R -> V -> V).\nVariables (f : {linear U -> V | s}) (h : {linear W -> U}).\n\nLemma idfun_is_scalable : scalable (@idfun U). Proof. by []. Qed.\nCanonical idfun_linear := AddLinear idfun_is_scalable.\n\nLemma opp_is_scalable : scalable (-%R : U -> U).\nProof. by move=> a v /=; rewrite scalerN. Qed.\nCanonical opp_linear := AddLinear opp_is_scalable.\n\nLemma comp_is_scalable : scalable_for s (f \\o h).\nProof. by move=> a v /=; rewrite !linearZ_LR. Qed.\nCanonical comp_linear := AddLinear comp_is_scalable.\n\nVariables (s_law : Scale.law s) (g : {linear U -> V | Scale.op s_law}).\nLet Ds : s =1 Scale.op s_law. Proof. by rewrite Scale.opE. Qed.\n\nLemma null_fun_is_scalable : scalable_for (Scale.op s_law) (\\0 : U -> V).\nProof. by move=> a v /=; rewrite raddf0. Qed.\nCanonical null_fun_linear := AddLinear null_fun_is_scalable.\n\nLemma add_fun_is_scalable : scalable_for s (f \\+ g).\nProof. by move=> a u; rewrite /= !linearZ_LR !Ds raddfD. Qed.\nCanonical add_fun_linear := AddLinear add_fun_is_scalable.\n\nLemma sub_fun_is_scalable : scalable_for s (f \\- g).\nProof. by move=> a u; rewrite /= !linearZ_LR !Ds raddfB. Qed.\nCanonical sub_fun_linear := AddLinear sub_fun_is_scalable.\n\nEnd LinearLmod.\n\nSection LinearLalg.\n\nVariables (A : lalgType R) (U : lmodType R).\n\nVariables (a : A) (f : {linear U -> A}).\n\nFact mulr_fun_is_scalable : scalable (a \\o* f).\nProof. by move=> k x /=; rewrite linearZ scalerAl. Qed.\nCanonical mulr_fun_linear := AddLinear mulr_fun_is_scalable.\n\nEnd LinearLalg.\n\nEnd LinearTheory.\n\nModule LRMorphism.\n\nSection ClassDef.\n\nVariables (R : ringType) (A : lalgType R) (B : ringType) (s : R -> B -> B).\n\nRecord class_of (f : A -> B) : Prop :=\n  Class {base : rmorphism f; mixin : scalable_for s f}.\nLocal Coercion base : class_of >-> rmorphism.\nDefinition base2 f (fLM : class_of f) := Linear.Class fLM (mixin fLM).\nLocal Coercion base2 : class_of >-> lmorphism.\n\nStructure map (phAB : phant (A -> B)) := Pack {apply; _ : class_of apply}.\nLocal Coercion apply : map >-> Funclass.\n\nVariables (phAB : phant (A -> B)) (f : A -> B) (cF : map phAB).\nDefinition class := let: Pack _ c as cF' := cF return class_of cF' in c.\n\nDefinition clone :=\n  fun (g : RMorphism.map phAB) fM & phant_id (RMorphism.class g) fM =>\n  fun (h : Linear.map s phAB) fZ &\n     phant_id (Linear.mixin (Linear.class h)) fZ =>\n  Pack phAB (@Class f fM fZ).\n\nDefinition pack (fZ : scalable_for s f) :=\n  fun (g : RMorphism.map phAB) fM & phant_id (RMorphism.class g) fM =>\n  Pack phAB (Class fM fZ).\n\nCanonical additive := Additive.Pack phAB class.\nCanonical rmorphism := RMorphism.Pack phAB class.\nCanonical linear := Linear.Pack phAB class.\nCanonical join_rmorphism := @RMorphism.Pack _ _ phAB linear class.\nCanonical join_linear := @Linear.Pack R A B s phAB rmorphism class.\n\nEnd ClassDef.\n\nModule Exports.\nNotation lrmorphism_for s f := (class_of s f).\nNotation lrmorphism f := (lrmorphism_for *:%R f).\nCoercion base : lrmorphism_for >-> RMorphism.class_of.\nCoercion base2 : lrmorphism_for >-> lmorphism_for.\nCoercion apply : map >-> Funclass.\nNotation LRMorphism f_lrM := (Pack (Phant _) (Class f_lrM f_lrM)).\nNotation AddLRMorphism fZ := (pack fZ id).\nNotation \"{ 'lrmorphism' fAB | s }\" := (map s (Phant fAB))\n  (at level 0, format \"{ 'lrmorphism'  fAB  |  s }\") : ring_scope.\nNotation \"{ 'lrmorphism' fAB }\" := {lrmorphism fAB | *:%R}\n  (at level 0, format \"{ 'lrmorphism'  fAB }\") : ring_scope.\nNotation \"[ 'lrmorphism' 'of' f ]\" := (@clone _ _ _ _ _ f _ _ id _ _ id)\n  (at level 0, format \"[ 'lrmorphism'  'of'  f ]\") : form_scope.\nCoercion additive : map >-> Additive.map.\nCanonical additive.\nCoercion rmorphism : map >-> RMorphism.map.\nCanonical rmorphism.\nCoercion linear : map >-> Linear.map.\nCanonical linear.\nCanonical join_rmorphism.\nCanonical join_linear.\nEnd Exports.\n\nEnd LRMorphism.\nInclude LRMorphism.Exports.\n\nSection LRMorphismTheory.\n\nVariables (R : ringType) (A B : lalgType R) (C : ringType) (s : R -> C -> C).\nVariables (k : unit) (f : {lrmorphism A -> B}) (g : {lrmorphism B -> C | s}).\n\nDefinition idfun_lrmorphism := [lrmorphism of @idfun A].\nDefinition comp_lrmorphism := [lrmorphism of g \\o f].\nDefinition locked_lrmorphism := [lrmorphism of locked_with k (f : A -> B)].\n\nLemma rmorph_alg a : f a%:A = a%:A.\nProof. by rewrite linearZ rmorph1. Qed.\n\nLemma lrmorphismP : lrmorphism f. Proof. exact: LRMorphism.class. Qed.\n\nLemma can2_lrmorphism f' : cancel f f' -> cancel f' f -> lrmorphism f'.\nProof.\nmove=> fK f'K; split; [exact: (can2_rmorphism fK) | exact: (can2_linear fK)].\nQed.\n\nLemma bij_lrmorphism :\n  bijective f -> exists2 f' : {lrmorphism B -> A}, cancel f f' & cancel f' f.\nProof.\nby case/bij_rmorphism=> f' fK f'K; exists (AddLRMorphism (can2_linear fK f'K)).\nQed.\n\nEnd LRMorphismTheory.\n\nModule ComRing.\n\nDefinition RingMixin R one mul mulA mulC mul1x mul_addl :=\n  let mulx1 := Monoid.mulC_id mulC mul1x in\n  let mul_addr := Monoid.mulC_dist mulC mul_addl in\n  @Ring.EtaMixin R one mul mulA mul1x mulx1 mul_addl mul_addr.\n\nSection ClassDef.\n\nRecord class_of R :=\n  Class {base : Ring.class_of R; mixin : commutative (Ring.mul base)}.\nLocal Coercion base : class_of >-> Ring.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack mul0 (m0 : @commutative T T mul0) :=\n  fun bT b & phant_id (Ring.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Ring.class_of.\nImplicit Arguments mixin [R].\nCoercion mixin : class_of >-> commutative.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nNotation comRingType := type.\nNotation ComRingType T m := (@pack T _ m _ _ id _ id).\nNotation ComRingMixin := RingMixin.\nNotation \"[ 'comRingType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'comRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'comRingType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'comRingType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd ComRing.\nImport ComRing.Exports.\n\nSection ComRingTheory.\n\nVariable R : comRingType.\nImplicit Types x y : R.\n\nLemma mulrC : @commutative R R *%R. Proof. by case: R => T []. Qed.\nCanonical mul_comoid := Monoid.ComLaw mulrC.\nLemma mulrCA : @left_commutative R R *%R. Proof. exact: mulmCA. Qed.\nLemma mulrAC : @right_commutative R R *%R. Proof. exact: mulmAC. Qed.\nLemma mulrACA : @interchange R *%R *%R. Proof. exact: mulmACA. Qed.\n\nLemma exprMn n : {morph (fun x => x ^+ n) : x y / x * y}.\nProof. move=> x y; apply: exprMn_comm; exact: mulrC. Qed.\n\nLemma prodrXl n I r (P : pred I) (F : I -> R) :\n  \\prod_(i <- r | P i) F i ^+ n = (\\prod_(i <- r | P i) F i) ^+ n.\nProof. by rewrite (big_morph _ (exprMn n) (expr1n _ n)). Qed.\n\nLemma exprDn x y n :\n  (x + y) ^+ n = \\sum_(i < n.+1) (x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof. by rewrite exprDn_comm //; exact: mulrC. Qed.\n\nLemma exprBn x y n :\n  (x - y) ^+ n =\n     \\sum_(i < n.+1) ((-1) ^+ i * x ^+ (n - i) * y ^+ i) *+ 'C(n, i).\nProof. by rewrite exprBn_comm //; exact: mulrC. Qed.\n\nLemma subrXX x y n :\n  x ^+ n - y ^+ n = (x - y) * (\\sum_(i < n) x ^+ (n.-1 - i) * y ^+ i).\nProof. by rewrite -subrXX_comm //; exact: mulrC. Qed.\n\nLemma sqrrD x y : (x + y) ^+ 2 = x ^+ 2 + x * y *+ 2 + y ^+ 2.\nProof. by rewrite exprDn !big_ord_recr big_ord0 /= add0r mulr1 mul1r. Qed.\n\nLemma sqrrB x y : (x - y) ^+ 2 = x ^+ 2 - x * y *+ 2 + y ^+ 2.\nProof. by rewrite sqrrD mulrN mulNrn sqrrN. Qed.\n\nLemma subr_sqr x y : x ^+ 2 - y ^+ 2 = (x - y) * (x + y).\nProof. by rewrite subrXX !big_ord_recr big_ord0 /= add0r mulr1 mul1r. Qed.\n\nLemma subr_sqrDB x y : (x + y) ^+ 2 - (x - y) ^+ 2 = x * y *+ 4.\nProof.\nrewrite sqrrD sqrrB -!(addrAC _ (y ^+ 2)) opprB.\nby rewrite addrC addrA subrK -mulrnDr.\nQed.\n\nSection FrobeniusAutomorphism.\n\nVariables (p : nat) (charRp : p \\in [char R]).\n\nLemma Frobenius_aut_is_rmorphism : rmorphism (Frobenius_aut charRp).\nProof.\nsplit=> [x y|]; first exact: Frobenius_autB_comm (mulrC _ _).\nsplit=> [x y|]; first exact: Frobenius_autM_comm (mulrC _ _).\nexact: Frobenius_aut1.\nQed.\n\nCanonical Frobenius_aut_additive := Additive Frobenius_aut_is_rmorphism.\nCanonical Frobenius_aut_rmorphism := RMorphism Frobenius_aut_is_rmorphism.\n\nEnd FrobeniusAutomorphism.\n\nLemma exprDn_char x y n : [char R].-nat n -> (x + y) ^+ n = x ^+ n + y ^+ n.\nProof.\npose p := pdiv n; have [|n_gt1 charRn] := leqP n 1; first by case: (n) => [|[]].\nhave charRp: p \\in [char R] by rewrite (pnatPpi charRn) ?pi_pdiv.\nhave{charRn} /p_natP[e ->]: p.-nat n by rewrite -(eq_pnat _ (charf_eq charRp)).\nby elim: e => // e IHe; rewrite !expnSr !exprM IHe -Frobenius_autE rmorphD.\nQed.\n\nLemma rmorph_comm (S : ringType) (f : {rmorphism R -> S}) x y : \n  comm (f x) (f y).\nProof. by red; rewrite -!rmorphM mulrC. Qed.\n\nSection ScaleLinear.\n\nVariables (U V : lmodType R) (b : R) (f : {linear U -> V}).\n\nLemma scale_is_scalable : scalable ( *:%R b : V -> V).\nProof. by move=> a v /=; rewrite !scalerA mulrC. Qed.\nCanonical scale_linear := AddLinear scale_is_scalable.\n\nLemma scale_fun_is_scalable : scalable (b \\*: f).\nProof. by move=> a v /=; rewrite !linearZ. Qed.\nCanonical scale_fun_linear := AddLinear scale_fun_is_scalable.\n\nEnd ScaleLinear.\n\nEnd ComRingTheory.\n\nModule Algebra.\n\nSection Mixin.\n\nVariables (R : ringType) (A : lalgType R).\n\nDefinition axiom := forall k (x y : A), k *: (x * y) = x * (k *: y).\n\nLemma comm_axiom : phant A -> commutative (@mul A) -> axiom.\nProof. by move=> _ commA k x y; rewrite commA scalerAl commA. Qed.\n\nEnd Mixin.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nRecord class_of (T : Type) : Type := Class {\n  base : Lalgebra.class_of R T; \n  mixin : axiom (Lalgebra.Pack _ base T)\n}.\nLocal Coercion base : class_of >-> Lalgebra.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack phR T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack b0 (ax0 : @axiom R b0) :=\n  fun bT b & phant_id (@Lalgebra.class R phR bT) b =>\n  fun   ax & phant_id ax0 ax => Pack phR (@Class T b ax) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\nDefinition lmodType := @Lmodule.Pack R phR cT xclass xT.\nDefinition lalgType := @Lalgebra.Pack R phR cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Lalgebra.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCoercion lalgType : type >-> Lalgebra.type.\nCanonical lalgType.\nNotation algType R := (type (Phant R)).\nNotation AlgType R A ax := (@pack _ (Phant R) A _ ax _ _ id _ id).\nNotation CommAlgType R A := (AlgType R A (comm_axiom (Phant A) (@mulrC _))).\nNotation \"[ 'algType' R 'of' T 'for' cT ]\" := (@clone _ (Phant R) T cT _ idfun)\n  (at level 0, format \"[ 'algType'  R  'of'  T  'for'  cT ]\")\n  : form_scope.\nNotation \"[ 'algType' R 'of' T ]\" := (@clone _ (Phant R) T _ _ id)\n  (at level 0, format \"[ 'algType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Algebra.\nImport Algebra.Exports.\n\nSection AlgebraTheory.\n\nVariables (R : comRingType) (A : algType R).\nImplicit Types (k : R) (x y : A).\n\nLemma scalerAr k x y : k *: (x * y) = x * (k *: y).\nProof. by case: A k x y => T []. Qed.\n\nLemma scalerCA k x y : k *: x * y = x * (k *: y).\nProof. by rewrite -scalerAl scalerAr. Qed.\n\nLemma mulr_algr a x : x * a%:A = a *: x.\nProof. by rewrite -scalerAr mulr1. Qed.\n\nLemma exprZn k x n : (k *: x) ^+ n = k ^+ n *: x ^+ n.\nProof. \nelim: n => [|n IHn]; first by rewrite !expr0 scale1r.\nby rewrite !exprS IHn -scalerA scalerAr scalerAl.\nQed.\n\nLemma scaler_prod I r (P : pred I) (F : I -> R) (G : I -> A) :\n  \\prod_(i <- r | P i) (F i *: G i) =\n    \\prod_(i <- r | P i) F i *: \\prod_(i <- r | P i) G i.\nProof.\nelim/big_rec3: _ => [|i x a _ _ ->]; first by rewrite scale1r.\nby rewrite -scalerAl -scalerAr scalerA.\nQed.\n\nLemma scaler_prodl (I : finType) (S : pred I) (F : I -> A) k :\n  \\prod_(i in S) (k *: F i)  = k ^+ #|S| *: \\prod_(i in S) F i.\nProof. by rewrite scaler_prod prodr_const. Qed.\n\nLemma scaler_prodr (I : finType) (S : pred I) (F : I -> R) x :\n  \\prod_(i in S) (F i *: x)  = \\prod_(i in S) F i *: x ^+ #|S|.\nProof. by rewrite scaler_prod prodr_const. Qed.\n\nCanonical regular_comRingType := [comRingType of R^o].\nCanonical regular_algType := CommAlgType R R^o.\n\nVariables (U : lmodType R) (a : A) (f : {linear U -> A}).\n\nLemma mull_fun_is_scalable : scalable (a \\*o f).\nProof. by move=> k x /=; rewrite linearZ scalerAr. Qed.\nCanonical mull_fun_linear := AddLinear mull_fun_is_scalable.\n\nEnd AlgebraTheory.\n\nModule UnitRing.\n\nRecord mixin_of (R : ringType) : Type := Mixin {\n  unit : pred R;\n  inv : R -> R;\n  _ : {in unit, left_inverse 1 inv *%R};\n  _ : {in unit, right_inverse 1 inv *%R};\n  _ : forall x y, y * x = 1 /\\ x * y = 1 -> unit x;\n  _ : {in [predC unit], inv =1 id}\n}.\n\nDefinition EtaMixin R unit inv mulVr mulrV unitP inv_out :=\n  let _ := @Mixin R unit inv mulVr mulrV unitP inv_out in\n  @Mixin (Ring.Pack (Ring.class R) R) unit inv mulVr mulrV unitP inv_out.\n\nSection ClassDef.\n\nRecord class_of (R : Type) : Type := Class {\n  base : Ring.class_of R;\n  mixin : mixin_of (Ring.Pack base R)\n}.\nLocal Coercion base : class_of >-> Ring.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack b0 (m0 : mixin_of (@Ring.Pack T b0 T)) :=\n  fun bT b & phant_id (Ring.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Ring.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nNotation unitRingType := type.\nNotation UnitRingType T m := (@pack T _ m _ _ id _ id).\nNotation UnitRingMixin := EtaMixin.\nNotation \"[ 'unitRingType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'unitRingType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'unitRingType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'unitRingType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd UnitRing.\nImport UnitRing.Exports.\n\nDefinition unit {R : unitRingType} :=\n  [qualify a u : R | UnitRing.unit (UnitRing.class R) u].\nFact unit_key R : pred_key (@unit R). Proof. by []. Qed.\nCanonical unit_keyed R := KeyedQualifier (@unit_key R).\nDefinition inv {R : unitRingType} : R -> R := UnitRing.inv (UnitRing.class R).\n\nLocal Notation \"x ^-1\" := (inv x).\nLocal Notation \"x / y\" := (x * y^-1).\nLocal Notation \"x ^- n\" := ((x ^+ n)^-1).\n\nSection UnitRingTheory.\n\nVariable R : unitRingType.\nImplicit Types x y : R.\n\nLemma divrr : {in unit, right_inverse 1 (@inv R) *%R}.\nProof. by case: R => T [? []]. Qed.\nDefinition mulrV := divrr.\n\nLemma mulVr : {in unit, left_inverse 1 (@inv R) *%R}.\nProof. by case: R => T [? []]. Qed.\n\nLemma invr_out x : x \\isn't a unit -> x^-1 = x.\nProof. by case: R x => T [? []]. Qed.\n\nLemma unitrP x : reflect (exists y, y * x = 1 /\\ x * y = 1) (x \\is a unit).\nProof.\napply: (iffP idP) => [Ux | []]; last by case: R x => T [? []].\nby exists x^-1; rewrite divrr ?mulVr.\nQed.\n\nLemma mulKr : {in unit, left_loop (@inv R) *%R}.\nProof. by move=> x Ux y; rewrite mulrA mulVr ?mul1r. Qed.\n\nLemma mulVKr : {in unit, rev_left_loop (@inv R) *%R}.\nProof. by move=> x Ux y; rewrite mulrA mulrV ?mul1r. Qed.\n\nLemma mulrK : {in unit, right_loop (@inv R) *%R}.\nProof. by move=> x Ux y; rewrite -mulrA divrr ?mulr1. Qed.\n\nLemma mulrVK : {in unit, rev_right_loop (@inv R) *%R}.\nProof. by move=> x Ux y; rewrite -mulrA mulVr ?mulr1. Qed.\nDefinition divrK := mulrVK.\n\nLemma mulrI : {in @unit R, right_injective *%R}.\nProof. by move=> x Ux; exact: can_inj (mulKr Ux). Qed.\n\nLemma mulIr : {in @unit R, left_injective *%R}.\nProof. by move=> x Ux; exact: can_inj (mulrK Ux). Qed.\n\nLemma commrV x y : comm x y -> comm x y^-1.\nProof.\nhave [Uy cxy | /invr_out-> //] := boolP (y \\in unit).\nby apply: (canLR (mulrK Uy)); rewrite -mulrA cxy mulKr.\nQed.\n\nLemma unitrE x : (x \\is a unit) = (x / x == 1).\nProof.\napply/idP/eqP=> [Ux | xx1]; first exact: divrr.\nby apply/unitrP; exists x^-1; rewrite -commrV.\nQed.\n\nLemma invrK : involutive (@inv R).\nProof.\nmove=> x; case Ux: (x \\in unit); last by rewrite !invr_out ?Ux.\nrewrite -(mulrK Ux _^-1) -mulrA commrV ?mulKr //.\nby apply/unitrP; exists x; rewrite divrr ?mulVr.\nQed.\n\nLemma invr_inj : injective (@inv R).\nProof. exact: inv_inj invrK. Qed.\n\nLemma unitrV x : (x^-1 \\in unit) = (x \\in unit).\nProof. by rewrite !unitrE invrK commrV. Qed.\n\nLemma unitr1 : 1 \\in @unit R.\nProof. by apply/unitrP; exists 1; rewrite mulr1. Qed.\n\nLemma invr1 : 1^-1 = 1 :> R.\nProof. by rewrite -{2}(mulVr unitr1) mulr1. Qed.\n\nLemma div1r x : 1 / x = x^-1. Proof. by rewrite mul1r. Qed.\nLemma divr1 x : x / 1 = x. Proof. by rewrite invr1 mulr1. Qed.\n\nLemma natr_div m d :\n  d %| m -> d%:R \\is a @unit R -> (m %/ d)%:R = m%:R / d%:R :> R.\nProof.\nby rewrite dvdn_eq => /eqP def_m unit_d; rewrite -{2}def_m natrM mulrK.\nQed.\n\nLemma unitr0 : (0 \\is a @unit R) = false.\nProof.\nby apply/unitrP=> [[x [_]]]; apply/eqP; rewrite mul0r eq_sym oner_neq0.\nQed.\n\nLemma invr0 : 0^-1 = 0 :> R.\nProof. by rewrite invr_out ?unitr0. Qed.\n\nLemma unitrN1 : -1 \\is a @unit R.\nProof. by apply/unitrP; exists (-1); rewrite mulrNN mulr1. Qed.\n\nLemma invrN1 : (-1)^-1 = -1 :> R.\nProof. by rewrite -{2}(divrr unitrN1) mulN1r opprK. Qed.\n\nLemma invr_sign n : ((-1) ^- n) = (-1) ^+ n :> R.\nProof. by rewrite -signr_odd; case: (odd n); rewrite (invr1, invrN1). Qed.\n\nLemma unitrMl x y : y \\is a unit -> (x * y \\is a unit) = (x \\is a unit).\nProof.\nmove=> Uy; wlog Ux: x y Uy / x \\is a unit => [WHxy|].\n  by apply/idP/idP=> Ux; first rewrite -(mulrK Uy x); rewrite WHxy ?unitrV.\nrewrite Ux; apply/unitrP; exists (y^-1 * x^-1).\nby rewrite -!mulrA mulKr ?mulrA ?mulrK ?divrr ?mulVr.\nQed.\n\nLemma unitrMr x y : x \\is a unit -> (x * y \\is a unit) = (y \\is a unit).\nProof.\nmove=> Ux; apply/idP/idP=> [Uxy | Uy]; last by rewrite unitrMl.\nby rewrite -(mulKr Ux y) unitrMl ?unitrV.\nQed.\n\nLemma invrM : {in unit &, forall x y, (x * y)^-1 = y^-1 * x^-1}.\nProof.\nmove=> x y Ux Uy; have Uxy: (x * y \\in unit) by rewrite unitrMl.\nby apply: (mulrI Uxy); rewrite divrr ?mulrA ?mulrK ?divrr.\nQed.\n\nLemma unitrM_comm x y :\n  comm x y -> (x * y \\is a unit) = (x \\is a unit) && (y \\is a unit).\nProof.\nmove=> cxy; apply/idP/andP=> [Uxy | [Ux Uy]]; last by rewrite unitrMl.\nsuffices Ux: x \\in unit by rewrite unitrMr in Uxy.\napply/unitrP; case/unitrP: Uxy => z [zxy xyz]; exists (y * z).\nrewrite mulrA xyz -{1}[y]mul1r -{1}zxy cxy -!mulrA (mulrA x) (mulrA _ z) xyz.\nby rewrite mul1r -cxy.\nQed.\n\nLemma unitrX x n : x \\is a unit -> x ^+ n \\is a unit.\nProof.\nby move=> Ux; elim: n => [|n IHn]; rewrite ?unitr1 // exprS unitrMl.\nQed.\n\nLemma unitrX_pos x n : n > 0 -> (x ^+ n \\in unit) = (x \\in unit).\nProof.\ncase: n => // n _; rewrite exprS unitrM_comm; last exact: commrX.\nby case Ux: (x \\is a unit); rewrite // unitrX.\nQed.\n\nLemma exprVn x n : x^-1 ^+ n = x ^- n.\nProof.\nelim: n => [|n IHn]; first by rewrite !expr0 ?invr1.\ncase Ux: (x \\is a unit); first by rewrite exprSr exprS IHn -invrM // unitrX.\nby rewrite !invr_out ?unitrX_pos ?Ux.\nQed.\n\nLemma exprB m n x : n <= m -> x \\is a unit -> x ^+ (m - n) = x ^+ m / x ^+ n.\nProof. by move/subnK=> {2}<- Ux; rewrite exprD mulrK ?unitrX. Qed.\n\nLemma invr_neq0 x : x != 0 -> x^-1 != 0.\nProof.\nmove=> nx0; case Ux: (x \\is a unit); last by rewrite invr_out ?Ux.\nby apply/eqP=> x'0; rewrite -unitrV x'0 unitr0 in Ux.\nQed.\n\nLemma invr_eq0 x : (x^-1 == 0) = (x == 0).\nProof. by apply: negb_inj; apply/idP/idP; move/invr_neq0; rewrite ?invrK. Qed.\n\nLemma invr_eq1 x : (x^-1 == 1) = (x == 1).\nProof. by rewrite (inv_eq invrK) invr1. Qed.\n\nLemma rev_unitrP (x y : R^c) : y * x = 1 /\\ x * y = 1 -> x \\is a unit.\nProof. by case=> [yx1 xy1]; apply/unitrP; exists y. Qed.\n\nDefinition converse_unitRingMixin :=\n  @UnitRing.Mixin _ ((unit : pred_class) : pred R^c) _\n     mulrV mulVr rev_unitrP invr_out.\nCanonical converse_unitRingType := UnitRingType R^c converse_unitRingMixin.\nCanonical regular_unitRingType := [unitRingType of R^o].\n\nSection ClosedPredicates.\n\nVariables S : predPredType R.\n\nDefinition invr_closed := {in S, forall x, x^-1 \\in S}.\nDefinition divr_2closed := {in S &, forall x y, x / y \\in S}.\nDefinition divr_closed := 1 \\in S /\\ divr_2closed.\nDefinition sdivr_closed := -1 \\in S /\\ divr_2closed.\nDefinition divring_closed := [/\\ 1 \\in S, subr_2closed S & divr_2closed].\n\nLemma divr_closedV : divr_closed -> invr_closed.\nProof. by case=> S1 Sdiv x Sx; rewrite -[x^-1]mul1r Sdiv. Qed.\n\nLemma divr_closedM : divr_closed -> mulr_closed S.\nProof.\nby case=> S1 Sdiv; split=> // x y Sx Sy; rewrite -[y]invrK -[y^-1]mul1r !Sdiv.\nQed.\n\nLemma sdivr_closed_div : sdivr_closed -> divr_closed.\nProof. by case=> SN1 Sdiv; split; rewrite // -(divrr unitrN1) Sdiv. Qed.\n\nLemma sdivr_closedM : sdivr_closed -> smulr_closed S.\nProof.\nby move=> Sdiv; have [_ SM] := divr_closedM (sdivr_closed_div Sdiv); case: Sdiv.\nQed.\n\nLemma divring_closedBM : divring_closed -> subring_closed S.\nProof. by case=> S1 SB Sdiv; split=> //; case: divr_closedM. Qed.\n\nLemma divring_closed_div : divring_closed -> sdivr_closed.\nProof.\ncase=> S1 SB Sdiv; split; rewrite ?zmod_closedN //.\nexact/subring_closedB/divring_closedBM.\nQed.\n\nEnd ClosedPredicates.\n\nEnd UnitRingTheory.\n\nImplicit Arguments invr_inj [[R] x1 x2].\n\nSection UnitRingMorphism.\n\nVariables (R S : unitRingType) (f : {rmorphism R -> S}).\n\nLemma rmorph_unit x : x \\in unit -> f x \\in unit.\nProof.\ncase/unitrP=> y [yx1 xy1]; apply/unitrP.\nby exists (f y); rewrite -!rmorphM // yx1 xy1 rmorph1.\nQed.\n\nLemma rmorphV : {in unit, {morph f: x / x^-1}}.\nProof.\nmove=> x Ux; rewrite /= -[(f x)^-1]mul1r.\nby apply: (canRL (mulrK (rmorph_unit Ux))); rewrite -rmorphM mulVr ?rmorph1.\nQed.\n\nLemma rmorph_div x y : y \\in unit -> f (x / y) = f x / f y.\nProof. by move=> Uy; rewrite rmorphM rmorphV. Qed.\n\nEnd UnitRingMorphism.\n\nModule ComUnitRing.\n\nSection Mixin.\n\nVariables (R : comRingType) (unit : pred R) (inv : R -> R).\nHypothesis mulVx : {in unit, left_inverse 1 inv *%R}.\nHypothesis unitPl : forall x y, y * x = 1 -> unit x.\n\nFact mulC_mulrV : {in unit, right_inverse 1 inv *%R}.\nProof. by move=> x Ux /=; rewrite mulrC mulVx. Qed.\n\nFact mulC_unitP x y : y * x = 1 /\\ x * y = 1 -> unit x.\nProof. case=> yx _; exact: unitPl yx. Qed.\n\nDefinition Mixin := UnitRingMixin mulVx mulC_mulrV mulC_unitP.\n\nEnd Mixin.\n\nSection ClassDef.\n\nRecord class_of (R : Type) : Type := Class {\n  base : ComRing.class_of R;\n  mixin : UnitRing.mixin_of (Ring.Pack base R)\n}.\nLocal Coercion base : class_of >-> ComRing.class_of.\nDefinition base2 R m := UnitRing.Class (@mixin R m).\nLocal Coercion base2 : class_of >-> UnitRing.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariables (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack :=\n  fun bT b & phant_id (ComRing.class bT) (b : ComRing.class_of T) =>\n  fun mT m & phant_id (UnitRing.class mT) (@UnitRing.Class T b m) =>\n  Pack (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\nDefinition comRingType := @ComRing.Pack cT xclass xT.\nDefinition unitRingType := @UnitRing.Pack cT xclass xT.\nDefinition com_unitRingType := @UnitRing.Pack comRingType xclass xT.\n\nEnd ClassDef.\n\nModule Import Exports.\nCoercion base : class_of >-> ComRing.class_of.\nCoercion mixin : class_of >-> UnitRing.mixin_of.\nCoercion base2 : class_of >-> UnitRing.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCanonical com_unitRingType.\nNotation comUnitRingType := type.\nNotation ComUnitRingMixin := Mixin.\nNotation \"[ 'comUnitRingType' 'of' T ]\" := (@pack T _ _ id _ _ id)\n  (at level 0, format \"[ 'comUnitRingType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd ComUnitRing.\nImport ComUnitRing.Exports.\n\nModule UnitAlgebra.\n\nSection ClassDef.\n\nVariable R : ringType.\n\nRecord class_of (T : Type) : Type := Class {\n  base : Algebra.class_of R T; \n  mixin : GRing.UnitRing.mixin_of (Ring.Pack base T)\n}.\nDefinition base2 R m := UnitRing.Class (@mixin R m).\nLocal Coercion base : class_of >-> Algebra.class_of.\nLocal Coercion base2 : class_of >-> UnitRing.class_of.\n\nStructure type (phR : phant R) := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (phR : phant R) (T : Type) (cT : type phR).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack :=\n  fun bT b & phant_id (@Algebra.class R phR bT) (b : Algebra.class_of R T) =>\n  fun mT m & phant_id (UnitRing.mixin (UnitRing.class mT)) m =>\n  Pack (Phant R) (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\nDefinition unitRingType := @UnitRing.Pack cT xclass xT.\nDefinition lmodType := @Lmodule.Pack R phR cT xclass xT.\nDefinition lalgType := @Lalgebra.Pack R phR cT xclass xT.\nDefinition algType := @Algebra.Pack R phR cT xclass xT.\nDefinition lmod_unitRingType := @Lmodule.Pack R phR unitRingType xclass xT.\nDefinition lalg_unitRingType := @Lalgebra.Pack R phR unitRingType xclass xT.\nDefinition alg_unitRingType := @Algebra.Pack R phR unitRingType xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Algebra.class_of.\nCoercion base2 : class_of >-> UnitRing.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion lmodType : type >-> Lmodule.type.\nCanonical lmodType.\nCoercion lalgType : type >-> Lalgebra.type.\nCanonical lalgType.\nCoercion algType : type >-> Algebra.type.\nCanonical algType.\nCanonical lmod_unitRingType.\nCanonical lalg_unitRingType.\nCanonical alg_unitRingType.\nNotation unitAlgType R := (type (Phant R)).\nNotation \"[ 'unitAlgType' R 'of' T ]\" := (@pack _ (Phant R) T _ _ id _ _ id)\n  (at level 0, format \"[ 'unitAlgType'  R  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd UnitAlgebra.\nImport UnitAlgebra.Exports.\n\nSection ComUnitRingTheory.\n\nVariable R : comUnitRingType.\nImplicit Types x y : R.\n\nLemma unitrM x y : (x * y \\in unit) = (x \\in unit) && (y \\in unit).\nProof. by apply: unitrM_comm; exact: mulrC. Qed.\n\nLemma unitrPr x : reflect (exists y, x * y = 1) (x \\in unit).\nProof.\nby apply: (iffP (unitrP x)) => [[y []] | [y]]; exists y; rewrite // mulrC.\nQed.\n\nLemma expr_div_n x y n : (x / y) ^+ n = x ^+ n / y ^+ n.\nProof. by rewrite exprMn exprVn. Qed.\n\nCanonical regular_comUnitRingType := [comUnitRingType of R^o].\nCanonical regular_unitAlgType := [unitAlgType R of R^o].\n\nEnd ComUnitRingTheory.\n\nSection UnitAlgebraTheory.\n\nVariable (R : comUnitRingType) (A : unitAlgType R).\nImplicit Types (k : R) (x y : A).\n\nLemma scaler_injl : {in unit, @right_injective R A A *:%R}.\nProof.\nmove=> k Uk x1 x2 Hx1x2.\nby rewrite -[x1]scale1r -(mulVr Uk) -scalerA Hx1x2 scalerA mulVr // scale1r.\nQed.\n\nLemma scaler_unit k x : k \\in unit -> (k *: x \\in unit) = (x \\in unit).\nProof.\nmove=> Uk; apply/idP/idP=> [Ukx | Ux]; apply/unitrP; last first.\n  exists (k^-1 *: x^-1).\n  by rewrite -!scalerAl -!scalerAr !scalerA !mulVr // !mulrV // scale1r.\nexists (k *: (k *: x)^-1); split.\n  apply: (mulrI Ukx).\n  by rewrite mulr1 mulrA -scalerAr mulrV // -scalerAl mul1r.\napply: (mulIr Ukx).\nby rewrite mul1r -mulrA -scalerAl mulVr // -scalerAr mulr1.\nQed.\n \nLemma invrZ k x : k \\in unit -> x \\in unit -> (k *: x)^-1 = k^-1 *: x^-1.\nProof.\nmove=> Uk Ux; have Ukx: (k *: x \\in unit) by rewrite scaler_unit.\napply: (mulIr Ukx).\nby rewrite mulVr // -scalerAl -scalerAr scalerA !mulVr // scale1r.\nQed.\n\nSection ClosedPredicates.\n\nVariables S : predPredType A.\n\nDefinition divalg_closed := [/\\ 1 \\in S, linear_closed S & divr_2closed S].\n\nLemma divalg_closedBdiv : divalg_closed -> divring_closed S.\nProof. by case=> S1 /linear_closedB. Qed.\n\nLemma divalg_closedZ : divalg_closed -> subalg_closed S.\nProof. by case=> S1 Slin Sdiv; split=> //; have [] := @divr_closedM A S. Qed.\n\nEnd ClosedPredicates.\n\nEnd UnitAlgebraTheory.\n\n(* Interface structures for algebraically closed predicates. *)\nModule Pred.\n\nStructure opp V S := Opp {opp_key : pred_key S; _ : @oppr_closed V S}.\nStructure add V S := Add {add_key : pred_key S; _ : @addr_closed V S}.\nStructure mul R S := Mul {mul_key : pred_key S; _ : @mulr_closed R S}.\nStructure zmod V S := Zmod {zmod_add : add S; _ : @oppr_closed V S}.\nStructure semiring R S := Semiring {semiring_add : add S; _ : @mulr_closed R S}.\nStructure smul R S := Smul {smul_opp : opp S; _ : @mulr_closed R S}.\nStructure div R S := Div {div_mul : mul S; _ : @invr_closed R S}.\nStructure submod R V S :=\n  Submod {submod_zmod : zmod S; _ : @scaler_closed R V S}.\nStructure subring R S := Subring {subring_zmod : zmod S; _ : @mulr_closed R S}.\nStructure sdiv R S := Sdiv {sdiv_smul : smul S; _ : @invr_closed R S}.\nStructure subalg (R : ringType) (A : lalgType R) S :=\n  Subalg {subalg_ring : subring S; _ : @scaler_closed R A S}.\nStructure divring R S :=\n  Divring {divring_ring : subring S; _ : @invr_closed R S}.\nStructure divalg (R : ringType) (A : unitAlgType R) S :=\n  Divalg {divalg_ring : divring S; _ : @scaler_closed R A S}.\n\nSection Subtyping.\n\nLtac done := case=> *; assumption.\nFact zmod_oppr R S : @zmod R S -> oppr_closed S. Proof. by []. Qed.\nFact semiring_mulr R S : @semiring R S -> mulr_closed S. Proof. by []. Qed.\nFact smul_mulr R S : @smul R S -> mulr_closed S. Proof. by []. Qed.\nFact submod_scaler R V S : @submod R V S -> scaler_closed S. Proof. by []. Qed.\nFact subring_mulr R S : @subring R S -> mulr_closed S. Proof. by []. Qed.\nFact sdiv_invr R S : @sdiv R S -> invr_closed S. Proof. by []. Qed.\nFact subalg_scaler R A S : @subalg R A S -> scaler_closed S. Proof. by []. Qed.\nFact divring_invr R S : @divring R S -> invr_closed S. Proof. by []. Qed.\nFact divalg_scaler R A S : @divalg R A S -> scaler_closed S. Proof. by []. Qed.\n\nDefinition zmod_opp R S (addS : @zmod R S) :=\n  Opp (add_key (zmod_add addS)) (zmod_oppr addS).\nDefinition semiring_mul R S (ringS : @semiring R S) :=\n  Mul (add_key (semiring_add ringS)) (semiring_mulr ringS).\nDefinition smul_mul R S (mulS : @smul R S) :=\n  Mul (opp_key (smul_opp mulS)) (smul_mulr mulS).\nDefinition subring_semi R S (ringS : @subring R S) :=\n  Semiring (zmod_add (subring_zmod ringS)) (subring_mulr ringS).\nDefinition subring_smul R S (ringS : @subring R S) :=\n  Smul (zmod_opp (subring_zmod ringS)) (subring_mulr ringS).\nDefinition sdiv_div R S (divS : @sdiv R S) :=\n  Div (smul_mul (sdiv_smul divS)) (sdiv_invr divS).\nDefinition subalg_submod R A S (algS : @subalg R A S) :=\n  Submod (subring_zmod (subalg_ring algS)) (subalg_scaler algS).\nDefinition divring_sdiv R S (ringS : @divring R S) :=\n  Sdiv (subring_smul (divring_ring ringS)) (divring_invr ringS).\nDefinition divalg_alg R A S (algS : @divalg R A S) :=\n  Subalg (divring_ring (divalg_ring algS)) (divalg_scaler algS).\n\nEnd Subtyping.\n\nSection Extensionality.\n(* This could be avoided by exploiting the Coq 8.4 eta-convertibility.        *)\n\nLemma opp_ext (U : zmodType) S k (kS : @keyed_pred U S k) :\n  oppr_closed kS -> oppr_closed S.\nProof. by move=> oppS x; rewrite -!(keyed_predE kS); apply: oppS. Qed.\n\nLemma add_ext (U : zmodType) S k (kS : @keyed_pred U S k) :\n  addr_closed kS -> addr_closed S.\nProof.\nby case=> S0 addS; split=> [|x y]; rewrite -!(keyed_predE kS) //; apply: addS.\nQed.\n\nLemma mul_ext (R : ringType) S k (kS : @keyed_pred R S k) :\n  mulr_closed kS -> mulr_closed S.\nProof.\nby case=> S1 mulS; split=> [|x y]; rewrite -!(keyed_predE kS) //; apply: mulS.\nQed.\n\nLemma scale_ext (R : ringType) (U : lmodType R) S k (kS : @keyed_pred U S k) :\n  scaler_closed kS -> scaler_closed S.\nProof. by move=> linS a x; rewrite -!(keyed_predE kS); apply: linS. Qed.\n\nLemma inv_ext (R : unitRingType) S k (kS : @keyed_pred R S k) :\n  invr_closed kS -> invr_closed S.\nProof. by move=> invS x; rewrite -!(keyed_predE kS); apply: invS. Qed.\n\nEnd Extensionality.\n\nModule Default.\nDefinition opp V S oppS := @Opp V S (DefaultPredKey S) oppS.\nDefinition add V S addS := @Add V S (DefaultPredKey S) addS.\nDefinition mul R S mulS := @Mul R S (DefaultPredKey S) mulS.\nDefinition zmod V S addS oppS := @Zmod V S (add addS) oppS.\nDefinition semiring R S addS mulS := @Semiring R S (add addS) mulS.\nDefinition smul R S oppS mulS := @Smul R S (opp oppS) mulS.\nDefinition div R S mulS invS := @Div R S (mul mulS) invS.\nDefinition submod R V S addS oppS linS := @Submod R V S (zmod addS oppS) linS.\nDefinition subring R S addS oppS mulS := @Subring R S (zmod addS oppS) mulS.\nDefinition sdiv R S oppS mulS invS := @Sdiv R S (smul oppS mulS) invS.\nDefinition subalg R A S addS oppS mulS linS :=\n  @Subalg R A S (subring addS oppS mulS) linS.\nDefinition divring R S addS oppS mulS invS :=\n  @Divring R S (subring addS oppS mulS) invS.\nDefinition divalg R A S addS oppS mulS invS linS :=\n  @Divalg R A S (divring addS oppS mulS invS) linS.\nEnd Default.\n\nModule Exports.\n\nNotation oppr_closed := oppr_closed.\nNotation addr_closed := addr_closed.\nNotation mulr_closed := mulr_closed.\nNotation zmod_closed := zmod_closed.\nNotation smulr_closed := smulr_closed.\nNotation invr_closed := invr_closed.\nNotation divr_closed := divr_closed.\nNotation linear_closed := linear_closed.\nNotation submod_closed := submod_closed.\nNotation semiring_closed := semiring_closed.\nNotation subring_closed := subring_closed.\nNotation sdivr_closed := sdivr_closed.\nNotation subalg_closed := subalg_closed.\nNotation divring_closed := divring_closed.\nNotation divalg_closed := divalg_closed.\n \nCoercion zmod_closedD : zmod_closed >-> addr_closed.\nCoercion zmod_closedN : zmod_closed >-> oppr_closed.\nCoercion smulr_closedN : smulr_closed >-> oppr_closed.\nCoercion smulr_closedM : smulr_closed >-> mulr_closed.\nCoercion divr_closedV : divr_closed >-> invr_closed.\nCoercion divr_closedM : divr_closed >-> mulr_closed.\nCoercion submod_closedZ : submod_closed >-> scaler_closed.\nCoercion submod_closedB : submod_closed >-> zmod_closed.\nCoercion semiring_closedD : semiring_closed >-> addr_closed.\nCoercion semiring_closedM : semiring_closed >-> mulr_closed.\nCoercion subring_closedB : subring_closed >-> zmod_closed.\nCoercion subring_closedM : subring_closed >-> smulr_closed.\nCoercion subring_closed_semi : subring_closed >-> semiring_closed.\nCoercion sdivr_closedM : sdivr_closed >-> smulr_closed.\nCoercion sdivr_closed_div : sdivr_closed >-> divr_closed.\nCoercion subalg_closedZ : subalg_closed >-> submod_closed.\nCoercion subalg_closedBM : subalg_closed >-> subring_closed.\nCoercion divring_closedBM : divring_closed >-> subring_closed.\nCoercion divring_closed_div : divring_closed >-> sdivr_closed.\nCoercion divalg_closedZ : divalg_closed >-> subalg_closed.\nCoercion divalg_closedBdiv : divalg_closed >-> divring_closed.\n\nCoercion opp_key : opp >-> pred_key.\nCoercion add_key : add >-> pred_key.\nCoercion mul_key : mul >-> pred_key.\nCoercion zmod_opp : zmod >-> opp.\nCanonical zmod_opp.\nCoercion zmod_add : zmod >-> add.\nCoercion semiring_add : semiring >-> add.\nCoercion semiring_mul : semiring >-> mul.\nCanonical semiring_mul.\nCoercion smul_opp : smul >-> opp.\nCoercion smul_mul : smul >-> mul.\nCanonical smul_mul.\nCoercion div_mul : div >-> mul.\nCoercion submod_zmod : submod >-> zmod.\nCoercion subring_zmod : subring >-> zmod.\nCoercion subring_semi : subring >-> semiring.\nCanonical subring_semi.\nCoercion subring_smul : subring >-> smul.\nCanonical subring_smul.\nCoercion sdiv_smul : sdiv >-> smul.\nCoercion sdiv_div : sdiv >-> div.\nCanonical sdiv_div.\nCoercion subalg_submod : subalg >-> submod.\nCanonical subalg_submod.\nCoercion subalg_ring : subalg >-> subring.\nCoercion divring_ring : divring >-> subring.\nCoercion divring_sdiv : divring >-> sdiv.\nCanonical divring_sdiv.\nCoercion divalg_alg : divalg >-> subalg.\nCanonical divalg_alg.\nCoercion divalg_ring : divalg >-> divring.\n\nNotation opprPred := opp.\nNotation addrPred := add.\nNotation mulrPred := mul.\nNotation zmodPred := zmod.\nNotation semiringPred := semiring.\nNotation smulrPred := smul.\nNotation divrPred := div.\nNotation submodPred := submod.\nNotation subringPred := subring.\nNotation sdivrPred := sdiv.\nNotation subalgPred := subalg.\nNotation divringPred := divring.\nNotation divalgPred := divalg.\n\nDefinition OpprPred U S k kS NkS := Opp k (@opp_ext U S k kS NkS).\nDefinition AddrPred U S k kS DkS := Add k (@add_ext U S k kS DkS).\nDefinition MulrPred R S k kS MkS := Mul k (@mul_ext R S k kS MkS).\nDefinition ZmodPred U S k kS NkS := Zmod k (@opp_ext U S k kS NkS).\nDefinition SemiringPred R S k kS MkS := Semiring k (@mul_ext R S k kS MkS).\nDefinition SmulrPred R S k kS MkS := Smul k (@mul_ext R S k kS MkS).\nDefinition DivrPred R S k kS VkS := Div k (@inv_ext R S k kS VkS).\nDefinition SubmodPred R U S k kS ZkS := Submod k (@scale_ext R U S k kS ZkS).\nDefinition SubringPred R S k kS MkS := Subring k (@mul_ext R S k kS MkS).\nDefinition SdivrPred R S k kS VkS := Sdiv k (@inv_ext R S k kS VkS).\nDefinition SubalgPred (R : ringType) (A : lalgType R) S k kS ZkS :=\n  Subalg k (@scale_ext R A S k kS ZkS).\nDefinition DivringPred R S k kS VkS := Divring k (@inv_ext R S k kS VkS).\nDefinition DivalgPred (R : ringType) (A : unitAlgType R) S k kS ZkS :=\n  Divalg k (@scale_ext R A S k kS ZkS).\n\nEnd Exports.\n\nEnd Pred.\nImport Pred.Exports.\n\nModule DefaultPred.\n\nCanonical Pred.Default.opp.\nCanonical Pred.Default.add.\nCanonical Pred.Default.mul.\nCanonical Pred.Default.zmod.\nCanonical Pred.Default.semiring.\nCanonical Pred.Default.smul.\nCanonical Pred.Default.div.\nCanonical Pred.Default.submod.\nCanonical Pred.Default.subring.\nCanonical Pred.Default.sdiv.\nCanonical Pred.Default.subalg.\nCanonical Pred.Default.divring.\nCanonical Pred.Default.divalg.\n\nEnd DefaultPred.\n\nSection ZmodulePred.\n\nVariables (V : zmodType) (S : predPredType V).\n\nSection Add.\n\nVariables (addS : addrPred S) (kS : keyed_pred addS).\n\nLemma rpred0D : addr_closed kS.\nProof.\nby split=> [|x y]; rewrite !keyed_predE; case: addS => _ [_]//; apply.\nQed.\n\nLemma rpred0 : 0 \\in kS.\nProof. by case: rpred0D. Qed.\n\nLemma rpredD : {in kS &, forall u v, u + v \\in kS}.\nProof. by case: rpred0D. Qed.\n\nLemma rpred_sum I r (P : pred I) F :\n  (forall i, P i -> F i \\in kS) -> \\sum_(i <- r | P i) F i \\in kS.\nProof. by move=> IH; elim/big_ind: _; [exact: rpred0 | exact: rpredD |]. Qed.\n\nLemma rpredMn n : {in kS, forall u, u *+ n \\in kS}.\nProof. by move=> u Su; rewrite -(card_ord n) -sumr_const rpred_sum. Qed.\n\nEnd Add.\n\nSection Opp.\n\nVariables (oppS : opprPred S) (kS : keyed_pred oppS).\n\nLemma rpredNr : oppr_closed kS.\nProof. by move=> x; rewrite !keyed_predE; case: oppS => _; apply. Qed.\n\nLemma rpredN : {mono -%R: u / u \\in kS}.\nProof. by move=> u; apply/idP/idP=> /rpredNr; rewrite ?opprK; apply. Qed.\n\nEnd Opp.\n\nSection Sub.\n\nVariables (subS : zmodPred S) (kS : keyed_pred subS).\n\nLemma rpredB : {in kS &, forall u v, u - v \\in kS}.\nProof. by move=> u v Su Sv; rewrite /= rpredD ?rpredN. Qed.\n\nLemma rpredMNn n : {in kS, forall u, u *- n \\in kS}.\nProof. by move=> u Su; rewrite /= rpredN rpredMn. Qed.\n\nLemma rpredDr x y : x \\in kS -> (y + x \\in kS) = (y \\in kS).\nProof.\nmove=> Sx; apply/idP/idP=> [Sxy | /rpredD-> //].\nby rewrite -(addrK x y) rpredB.\nQed.\n\nLemma rpredDl x y : x \\in kS -> (x + y \\in kS) = (y \\in kS).\nProof. by rewrite addrC; apply: rpredDr. Qed.\n\nLemma rpredBr x y : x \\in kS -> (y - x \\in kS) = (y \\in kS).\nProof. by rewrite -rpredN; apply: rpredDr. Qed.\n\nLemma rpredBl x y : x \\in kS -> (x - y \\in kS) = (y \\in kS).\nProof. by rewrite -(rpredN _ y); apply: rpredDl. Qed.\n\nEnd Sub.\n\nEnd ZmodulePred.\n\nSection RingPred.\n\nVariables (R : ringType) (S : predPredType R).\n\nLemma rpredMsign (oppS : opprPred S) (kS : keyed_pred oppS) n x :\n  ((-1) ^+ n * x \\in kS) = (x \\in kS).\nProof. by rewrite -signr_odd mulr_sign; case: ifP => // _; rewrite rpredN. Qed.\n\nSection Mul.\n\nVariables (mulS : mulrPred S) (kS : keyed_pred mulS).\n\nLemma rpred1M : mulr_closed kS.\nProof.\nby split=> [|x y]; rewrite !keyed_predE; case: mulS => _ [_] //; apply.\nQed.\n\nLemma rpred1 : 1 \\in kS.\nProof. by case: rpred1M. Qed.\n\nLemma rpredM : {in kS &, forall u v, u * v \\in kS}.\nProof. by case: rpred1M. Qed.\n\nLemma rpred_prod I r (P : pred I) F :\n  (forall i, P i -> F i \\in kS) -> \\prod_(i <- r | P i) F i \\in kS.\nProof. by move=> IH; elim/big_ind: _; [exact: rpred1 | exact: rpredM |]. Qed.\n\nLemma rpredX n : {in kS, forall u, u ^+ n \\in kS}.\nProof. by move=> u Su; rewrite -(card_ord n) -prodr_const rpred_prod. Qed.\n\nEnd Mul.\n\nLemma rpred_nat (rngS : semiringPred S) (kS : keyed_pred rngS) n : n%:R \\in kS.\nProof. by rewrite rpredMn ?rpred1. Qed.\n\nLemma rpredN1 (mulS : smulrPred S) (kS : keyed_pred mulS) : -1 \\in kS.\nProof. by rewrite rpredN rpred1. Qed.\n\nLemma rpred_sign (mulS : smulrPred S) (kS : keyed_pred mulS) n :\n  (-1) ^+ n \\in kS.\nProof. by rewrite rpredX ?rpredN1. Qed.\n\nEnd RingPred.\n\nSection LmodPred.\n\nVariables (R : ringType) (V : lmodType R) (S : predPredType V).\n\nLemma rpredZsign (oppS : opprPred S) (kS : keyed_pred oppS) n u :\n  ((-1) ^+ n *: u \\in kS) = (u \\in kS).\nProof. by rewrite -signr_odd scaler_sign fun_if if_arg rpredN if_same. Qed.\n\nLemma rpredZnat (addS : addrPred S) (kS : keyed_pred addS) n :\n  {in kS, forall u, n%:R *: u \\in kS}.\nProof. by move=> u Su; rewrite /= scaler_nat rpredMn. Qed.\n\nLemma rpredZ (linS : submodPred S) (kS : keyed_pred linS) : scaler_closed kS.\nProof. by move=> a u; rewrite !keyed_predE; case: {kS}linS => _; apply. Qed.\n\nEnd LmodPred.\n\nSection UnitRingPred.\n\nVariable R : unitRingType. \n\nSection Div.\n\nVariables (S : predPredType R) (divS : divrPred S) (kS : keyed_pred divS).\n\nLemma rpredVr x : x \\in kS -> x^-1 \\in kS.\nProof. by rewrite !keyed_predE; case: divS x. Qed.\n\nLemma rpredV x : (x^-1 \\in kS) = (x \\in kS).\nProof. by apply/idP/idP=> /rpredVr; rewrite ?invrK; apply. Qed.\n\nLemma rpred_div : {in kS &, forall x y, x / y \\in kS}.\nProof. by move=> x y Sx Sy; rewrite /= rpredM ?rpredV. Qed.\n\nLemma rpredXN n : {in kS, forall x, x ^- n \\in kS}.\nProof. by move=> x Sx; rewrite /= rpredV rpredX. Qed.\n\nLemma rpredMl x y : x \\in kS -> x \\is a unit-> (x * y \\in kS) = (y \\in kS).\nProof.\nmove=> Sx Ux; apply/idP/idP=> [Sxy | /(rpredM Sx)-> //].\nby rewrite -(mulKr Ux y); rewrite rpredM ?rpredV.\nQed.\n\nLemma rpredMr x y : x \\in kS -> x \\is a unit -> (y * x \\in kS) = (y \\in kS).\nProof.\nmove=> Sx Ux; apply/idP/idP=> [Sxy | /rpredM-> //].\nby rewrite -(mulrK Ux y); rewrite rpred_div.\nQed.\n\nLemma rpred_divr x y : x \\in kS -> x \\is a unit -> (y / x \\in kS) = (y \\in kS).\nProof. by rewrite -rpredV -unitrV; apply: rpredMr. Qed.\n\nLemma rpred_divl x y : x \\in kS -> x \\is a unit -> (x / y \\in kS) = (y \\in kS).\nProof. by rewrite -(rpredV y); apply: rpredMl. Qed.\n\nEnd Div.\n\nFact unitr_sdivr_closed : @sdivr_closed R unit.\nProof. by split=> [|x y Ux Uy]; rewrite ?unitrN1 // unitrMl ?unitrV. Qed.\n\nCanonical unit_opprPred := OpprPred unitr_sdivr_closed.\nCanonical unit_mulrPred := MulrPred unitr_sdivr_closed.\nCanonical unit_divrPred := DivrPred unitr_sdivr_closed.\nCanonical unit_smulrPred := SmulrPred unitr_sdivr_closed.\nCanonical unit_sdivrPred := SdivrPred unitr_sdivr_closed.\n\nImplicit Type x : R.\n\nLemma unitrN x : (- x \\is a unit) = (x \\is a unit). Proof. exact: rpredN. Qed.\n\nLemma invrN x : (- x)^-1 = - x^-1.\nProof.\nhave [Ux | U'x] := boolP (x \\is a unit); last by rewrite !invr_out ?unitrN.\nby rewrite -mulN1r invrM ?unitrN1 // invrN1 mulrN1.\nQed.\n\nLemma invr_signM n x : ((-1) ^+ n * x)^-1 = (-1) ^+ n * x^-1.\nProof. by rewrite -signr_odd !mulr_sign; case: ifP => // _; rewrite invrN. Qed.\n\nLemma divr_signM (b1 b2 : bool) x1 x2:\n  ((-1) ^+ b1 * x1) / ((-1) ^+ b2 * x2) = (-1) ^+ (b1 (+) b2) * (x1 / x2).\nProof. by rewrite invr_signM mulr_signM. Qed.\n\nEnd UnitRingPred.\n\n(* Reification of the theory of rings with units, in named style  *)\nSection TermDef.\n\nVariable R : Type.\n\nInductive term : Type :=\n| Var of nat\n| Const of R\n| NatConst of nat\n| Add of term & term\n| Opp of term\n| NatMul of term & nat\n| Mul of term & term\n| Inv of term\n| Exp of term & nat.\n\nInductive formula : Type :=\n| Bool of bool\n| Equal of term & term\n| Unit of term\n| And of formula & formula\n| Or of formula & formula\n| Implies of formula & formula\n| Not of formula\n| Exists of nat & formula\n| Forall of nat & formula.\n\nEnd TermDef.\n\nBind Scope term_scope with term.\nBind Scope term_scope with formula.\nArguments Scope Add [_ term_scope term_scope].\nArguments Scope Opp [_ term_scope].\nArguments Scope NatMul [_ term_scope nat_scope].\nArguments Scope Mul [_ term_scope term_scope].\nArguments Scope Mul [_ term_scope term_scope].\nArguments Scope Inv [_ term_scope].\nArguments Scope Exp [_ term_scope nat_scope].\nArguments Scope Equal [_ term_scope term_scope].\nArguments Scope Unit [_ term_scope].\nArguments Scope And [_ term_scope term_scope].\nArguments Scope Or [_ term_scope term_scope].\nArguments Scope Implies [_ term_scope term_scope].\nArguments Scope Not [_ term_scope].\nArguments Scope Exists [_ nat_scope term_scope].\nArguments Scope Forall [_ nat_scope term_scope].\n\nImplicit Arguments Bool [R].\nPrenex Implicits Const Add Opp NatMul Mul Exp Bool Unit And Or Implies Not.\nPrenex Implicits Exists Forall.\n\nNotation True := (Bool true).\nNotation False := (Bool false).\n\nLocal Notation \"''X_' i\" := (Var _ i) : term_scope.\nLocal Notation \"n %:R\" := (NatConst _ n) : term_scope.\nLocal Notation \"x %:T\" := (Const x) : term_scope.\nLocal Notation \"0\" := 0%:R%T : term_scope.\nLocal Notation \"1\" := 1%:R%T : term_scope.\nLocal Infix \"+\" := Add : term_scope.\nLocal Notation \"- t\" := (Opp t) : term_scope.\nLocal Notation \"t - u\" := (Add t (- u)) : term_scope.\nLocal Infix \"*\" := Mul : term_scope.\nLocal Infix \"*+\" := NatMul : term_scope.\nLocal Notation \"t ^-1\" := (Inv t) : term_scope.\nLocal Notation \"t / u\" := (Mul t u^-1) : term_scope.\nLocal Infix \"^+\" := Exp : term_scope.\nLocal Infix \"==\" := Equal : term_scope.\nLocal Infix \"/\\\" := And : term_scope.\nLocal Infix \"\\/\" := Or : term_scope.\nLocal Infix \"==>\" := Implies : term_scope.\nLocal Notation \"~ f\" := (Not f) : term_scope.\nLocal Notation \"x != y\" := (Not (x == y)) : term_scope.\nLocal Notation \"''exists' ''X_' i , f\" := (Exists i f) : term_scope.\nLocal Notation \"''forall' ''X_' i , f\" := (Forall i f) : term_scope.\n\nSection Substitution.\n\nVariable R : Type.\n\nFixpoint tsubst (t : term R) (s : nat * term R) :=\n  match t with\n  | 'X_i => if i == s.1 then s.2 else t\n  | _%:T | _%:R => t\n  | t1 + t2 => tsubst t1 s + tsubst t2 s\n  | - t1 => - tsubst t1 s\n  | t1 *+ n => tsubst t1 s *+ n\n  | t1 * t2 => tsubst t1 s * tsubst t2 s\n  | t1^-1 => (tsubst t1 s)^-1\n  | t1 ^+ n => tsubst t1 s ^+ n\n  end%T.\n\nFixpoint fsubst (f : formula R) (s : nat * term R) :=\n  match f with\n  | Bool _ => f\n  | t1 == t2 => tsubst t1 s == tsubst t2 s\n  | Unit t1 => Unit (tsubst t1 s)\n  | f1 /\\ f2 => fsubst f1 s /\\ fsubst f2 s\n  | f1 \\/ f2 => fsubst f1 s \\/ fsubst f2 s\n  | f1 ==> f2 => fsubst f1 s ==> fsubst f2 s\n  | ~ f1 => ~ fsubst f1 s\n  | ('exists 'X_i, f1) => 'exists 'X_i, if i == s.1 then f1 else fsubst f1 s\n  | ('forall 'X_i, f1) => 'forall 'X_i, if i == s.1 then f1 else fsubst f1 s\n  end%T.\n\nEnd Substitution.\n\nSection EvalTerm.\n\nVariable R : unitRingType.\n\n(* Evaluation of a reified term into R a ring with units *)\nFixpoint eval (e : seq R) (t : term R) {struct t} : R :=\n  match t with\n  | ('X_i)%T => e`_i\n  | (x%:T)%T => x\n  | (n%:R)%T => n%:R\n  | (t1 + t2)%T => eval e t1 + eval e t2\n  | (- t1)%T => - eval e t1\n  | (t1 *+ n)%T => eval e t1 *+ n\n  | (t1 * t2)%T => eval e t1 * eval e t2\n  | t1^-1%T => (eval e t1)^-1\n  | (t1 ^+ n)%T => eval e t1 ^+ n\n  end.\n\nDefinition same_env (e e' : seq R) := nth 0 e =1 nth 0 e'.\n\nLemma eq_eval e e' t : same_env e e' -> eval e t = eval e' t.\nProof. by move=> eq_e; elim: t => //= t1 -> // t2 ->. Qed.\n\nLemma eval_tsubst e t s :\n  eval e (tsubst t s) = eval (set_nth 0 e s.1 (eval e s.2)) t.\nProof.\ncase: s => i u; elim: t => //=; do 2?[move=> ? -> //] => j.\nby rewrite nth_set_nth /=; case: (_ == _).\nQed.\n\n(* Evaluation of a reified formula *)\nFixpoint holds (e : seq R) (f : formula R) {struct f} : Prop :=\n  match f with\n  | Bool b => b\n  | (t1 == t2)%T => eval e t1 = eval e t2\n  | Unit t1 => eval e t1 \\in unit\n  | (f1 /\\ f2)%T => holds e f1 /\\ holds e f2\n  | (f1 \\/ f2)%T => holds e f1 \\/ holds e f2\n  | (f1 ==> f2)%T => holds e f1 -> holds e f2\n  | (~ f1)%T => ~ holds e f1\n  | ('exists 'X_i, f1)%T => exists x, holds (set_nth 0 e i x) f1\n  | ('forall 'X_i, f1)%T => forall x, holds (set_nth 0 e i x) f1\n  end.\n\nLemma same_env_sym e e' : same_env e e' -> same_env e' e.\nProof. exact: fsym. Qed.\n\n(* Extensionality of formula evaluation *)\nLemma eq_holds e e' f : same_env e e' -> holds e f -> holds e' f.\nProof.\npose sv := set_nth (0 : R).\nhave eq_i i v e1 e2: same_env e1 e2 -> same_env (sv e1 i v) (sv e2 i v).\n  by move=> eq_e j; rewrite !nth_set_nth /= eq_e.\nelim: f e e' => //=.\n- by move=> t1 t2 e e' eq_e; rewrite !(eq_eval _ eq_e).\n- by move=> t e e' eq_e; rewrite (eq_eval _ eq_e).\n- by move=> f1 IH1 f2 IH2 e e' eq_e; move/IH2: (eq_e); move/IH1: eq_e; tauto.\n- by move=> f1 IH1 f2 IH2 e e' eq_e; move/IH2: (eq_e); move/IH1: eq_e; tauto.\n- by move=> f1 IH1 f2 IH2 e e' eq_e f12; move/IH1: (same_env_sym eq_e); eauto.\n- by move=> f1 IH1 e e'; move/same_env_sym; move/IH1; tauto.\n- by move=> i f1 IH1 e e'; move/(eq_i i)=> eq_e [x f_ex]; exists x; eauto.\nby move=> i f1 IH1 e e'; move/(eq_i i); eauto.\nQed.\n\n(* Evaluation and substitution by a constant *)\nLemma holds_fsubst e f i v :\n  holds e (fsubst f (i, v%:T)%T) <-> holds (set_nth 0 e i v) f.\nProof.\nelim: f e => //=; do [\n  by move=> *; rewrite !eval_tsubst\n| move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto\n| move=> f IHf e; move: (IHf e); tauto\n| move=> j f IHf e].\n- case eq_ji: (j == i); first rewrite (eqP eq_ji).\n    by split=> [] [x f_x]; exists x; rewrite set_set_nth eqxx in f_x *.\n  split=> [] [x f_x]; exists x; move: f_x; rewrite set_set_nth eq_sym eq_ji;\n     have:= IHf (set_nth 0 e j x); tauto.\ncase eq_ji: (j == i); first rewrite (eqP eq_ji).\n  by split=> [] f_ x; move: (f_ x); rewrite set_set_nth eqxx.\nsplit=> [] f_ x; move: (IHf (set_nth 0 e j x)) (f_ x);\n  by rewrite set_set_nth eq_sym eq_ji; tauto.\nQed.\n\n(* Boolean test selecting terms in the language of rings *)\nFixpoint rterm (t : term R) :=\n  match t with\n  | _^-1 => false\n  | t1 + t2 | t1 * t2 => rterm t1 && rterm t2\n  | - t1 | t1 *+ _ | t1 ^+ _ => rterm t1\n  | _ => true\n  end%T.\n\n(* Boolean test selecting formulas in the theory of rings *)\nFixpoint rformula (f : formula R) :=\n  match f with\n  | Bool _ => true\n  | t1 == t2 => rterm t1 && rterm t2\n  | Unit t1 => false\n  | f1 /\\ f2 | f1 \\/ f2 | f1 ==> f2 => rformula f1 && rformula f2\n  | ~ f1 | ('exists 'X__, f1) | ('forall 'X__, f1) => rformula f1\n  end%T.\n\n(* Upper bound of the names used in a term *)\nFixpoint ub_var (t : term R) :=\n  match t with\n  | 'X_i => i.+1\n  | t1 + t2 | t1 * t2 => maxn (ub_var t1) (ub_var t2)\n  | - t1 | t1 *+ _ | t1 ^+ _ | t1^-1 => ub_var t1\n  | _ => 0%N\n  end%T.\n\n(* Replaces inverses in the term t by fresh variables, accumulating the *)\n(* substitution. *)\nFixpoint to_rterm (t : term R) (r : seq (term R)) (n : nat) {struct t} :=\n  match t with\n  | t1^-1 =>\n    let: (t1', r1) := to_rterm t1 r n in\n      ('X_(n + size r1), rcons r1 t1')\n  | t1 + t2 =>\n    let: (t1', r1) := to_rterm t1 r n in\n    let: (t2', r2) := to_rterm t2 r1 n in\n      (t1' + t2', r2)\n  | - t1 =>\n   let: (t1', r1) := to_rterm t1 r n in\n     (- t1', r1)\n  | t1 *+ m =>\n   let: (t1', r1) := to_rterm t1 r n in\n     (t1' *+ m, r1)\n  | t1 * t2 =>\n    let: (t1', r1) := to_rterm t1 r n in\n    let: (t2', r2) := to_rterm t2 r1 n in\n      (Mul t1' t2', r2)\n  | t1 ^+ m =>\n       let: (t1', r1) := to_rterm t1 r n in\n     (t1' ^+ m, r1)\n  | _ => (t, r)\n  end%T.\n\nLemma to_rterm_id t r n : rterm t -> to_rterm t r n = (t, r).\nProof.\nelim: t r n => //.\n- by move=> t1 IHt1 t2 IHt2 r n /= /andP[rt1 rt2]; rewrite {}IHt1 // IHt2.\n- by move=> t IHt r n /= rt; rewrite {}IHt.\n- by move=> t IHt r n m /= rt; rewrite {}IHt.\n- by move=> t1 IHt1 t2 IHt2 r n /= /andP[rt1 rt2]; rewrite {}IHt1 // IHt2.\n- by move=> t IHt r n m /= rt; rewrite {}IHt.\nQed.\n\n(* A ring formula stating that t1 is equal to 0 in the ring theory. *)\n(* Also applies to non commutative rings.                           *)\nDefinition eq0_rform t1 :=\n  let m := ub_var t1 in\n  let: (t1', r1) := to_rterm t1 [::] m in\n  let fix loop r i := match r with\n  | [::] => t1' == 0\n  | t :: r' =>\n    let f := 'X_i * t == 1 /\\ t * 'X_i == 1 in\n     'forall 'X_i, (f \\/ 'X_i == t /\\ ~ ('exists 'X_i,  f)) ==> loop r' i.+1\n  end%T\n  in loop r1 m.\n\n(* Transformation of a formula in the theory of rings with units into an *)\n(* equivalent formula in the sub-theory of rings.                        *)\nFixpoint to_rform f :=\n  match f with\n  | Bool b => f\n  | t1 == t2 => eq0_rform (t1 - t2)\n  | Unit t1 => eq0_rform (t1 * t1^-1 - 1)\n  | f1 /\\ f2 => to_rform f1 /\\ to_rform f2\n  | f1 \\/ f2 =>  to_rform f1 \\/ to_rform f2\n  | f1 ==> f2 => to_rform f1 ==> to_rform f2\n  | ~ f1 => ~ to_rform f1\n  | ('exists 'X_i, f1) => 'exists 'X_i, to_rform f1\n  | ('forall 'X_i, f1) => 'forall 'X_i, to_rform f1\n  end%T.\n\n(* The transformation gives a ring formula. *)\nLemma to_rform_rformula f : rformula (to_rform f).\nProof.\nsuffices eq0_ring t1: rformula (eq0_rform t1) by elim: f => //= => f1 ->.\nrewrite /eq0_rform; move: (ub_var t1) => m; set tr := _ m.\nsuffices: all rterm (tr.1 :: tr.2).\n  case: tr => {t1} t1 r /= /andP[t1_r].\n  by elim: r m => [|t r IHr] m; rewrite /= ?andbT // => /andP[->]; exact: IHr.\nhave: all rterm [::] by [].\nrewrite {}/tr; elim: t1 [::] => //=.\n- move=> t1 IHt1 t2 IHt2 r.\n  move/IHt1; case: to_rterm => {t1 r IHt1} t1 r /= /andP[t1_r].\n  move/IHt2; case: to_rterm => {t2 r IHt2} t2 r /= /andP[t2_r].\n  by rewrite t1_r t2_r.\n- by move=> t1 IHt1 r /IHt1; case: to_rterm.\n- by move=> t1 IHt1 n r /IHt1; case: to_rterm.\n- move=> t1 IHt1 t2 IHt2 r.\n  move/IHt1; case: to_rterm => {t1 r IHt1} t1 r /= /andP[t1_r].\n  move/IHt2; case: to_rterm => {t2 r IHt2} t2 r /= /andP[t2_r].\n  by rewrite t1_r t2_r.\n- move=> t1 IHt1 r.\n  by move/IHt1; case: to_rterm => {t1 r IHt1} t1 r /=; rewrite all_rcons.\n- by move=> t1 IHt1 n r /IHt1; case: to_rterm.\nQed.\n\n(* Correctness of the transformation. *)\nLemma to_rformP e f : holds e (to_rform f) <-> holds e f.\nProof.\nsuffices{e f} equal0_equiv e t1 t2:\n  holds e (eq0_rform (t1 - t2)) <-> (eval e t1 == eval e t2).\n- elim: f e => /=; try tauto.\n  + move=> t1 t2 e.\n    by split; [move/equal0_equiv/eqP | move/eqP/equal0_equiv].\n  + move=> t1 e; rewrite unitrE; exact: equal0_equiv.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 f2 IHf2 e; move: (IHf1 e) (IHf2 e); tauto.\n  + move=> f1 IHf1 e; move: (IHf1 e); tauto.\n  + by move=> n f1 IHf1 e; split=> [] [x] /IHf1; exists x.\n  + by move=> n f1 IHf1 e; split=> Hx x; apply/IHf1.\nrewrite -(add0r (eval e t2)) -(can2_eq (subrK _) (addrK _)).\nrewrite -/(eval e (t1 - t2)); move: (t1 - t2)%T => {t1 t2} t.\nhave sub_var_tsubst s t0: s.1 >= ub_var t0 -> tsubst t0 s = t0.\n  elim: t0 {t} => //=.\n  - by move=> n; case: ltngtP.\n  - by move=> t1 IHt1 t2 IHt2; rewrite geq_max => /andP[/IHt1-> /IHt2->].\n  - by move=> t1 IHt1 /IHt1->.\n  - by move=> t1 IHt1 n /IHt1->.\n  - by move=> t1 IHt1 t2 IHt2; rewrite geq_max => /andP[/IHt1-> /IHt2->].\n  - by move=> t1 IHt1 /IHt1->.\n  - by move=> t1 IHt1 n /IHt1->.\npose fix rsub t' m r : term R :=\n  if r is u :: r' then tsubst (rsub t' m.+1 r') (m, u^-1)%T else t'.\npose fix ub_sub m r : Prop :=\n  if r is u :: r' then ub_var u <= m /\\ ub_sub m.+1 r' else true.\nsuffices{t} rsub_to_r t r0 m: m >= ub_var t -> ub_sub m r0 ->\n  let: (t', r) := to_rterm t r0 m in\n  [/\\ take (size r0) r = r0,\n      ub_var t' <= m + size r, ub_sub m r & rsub t' m r = t].\n- have:= rsub_to_r t [::] _ (leqnn _); rewrite /eq0_rform.\n  case: (to_rterm _ _ _) => [t1' r1] [//|_ _ ub_r1 def_t].\n  rewrite -{2}def_t {def_t}.\n  elim: r1 (ub_var t) e ub_r1 => [|u r1 IHr1] m e /= => [_|[ub_u ub_r1]].\n    by split=> /eqP.\n  rewrite eval_tsubst /=; set y := eval e u; split=> t_eq0.\n    apply/IHr1=> //; apply: t_eq0.\n    rewrite nth_set_nth /= eqxx -(eval_tsubst e u (m, Const _)).\n    rewrite sub_var_tsubst //= -/y.\n    case Uy: (y \\in unit); [left | right]; first by rewrite mulVr ?divrr.\n    split=> [|[z]]; first by rewrite invr_out ?Uy.\n    rewrite nth_set_nth /= eqxx.\n    rewrite -!(eval_tsubst _ _ (m, Const _)) !sub_var_tsubst // -/y => yz1.\n    by case/unitrP: Uy; exists z.\n  move=> x def_x; apply/IHr1=> //; suff ->: x = y^-1 by []; move: def_x.\n  rewrite nth_set_nth /= eqxx -(eval_tsubst e u (m, Const _)).\n  rewrite sub_var_tsubst //= -/y; case=> [[xy1 yx1] | [xy nUy]].\n    by rewrite -[y^-1]mul1r -[1]xy1 mulrK //; apply/unitrP; exists x.\n  rewrite invr_out //; apply/unitrP=> [[z yz1]]; case: nUy; exists z.\n  rewrite nth_set_nth /= eqxx -!(eval_tsubst _ _ (m, _%:T)%T).\n  by rewrite !sub_var_tsubst.\nhave rsub_id r t0 n: ub_var t0 <= n -> rsub t0 n r = t0.\n  by elim: r n => //= t1 r IHr n let0n; rewrite IHr ?sub_var_tsubst ?leqW.\nhave rsub_acc r s t1 m1:\n  ub_var t1 <= m1 + size r -> rsub t1 m1 (r ++ s) = rsub t1 m1 r.\n  elim: r t1 m1 => [|t1 r IHr] t2 m1 /=; first by rewrite addn0; apply: rsub_id.\n  by move=> letmr; rewrite IHr ?addSnnS.\nelim: t r0 m => /=; try do [\n  by move=> n r m hlt hub; rewrite take_size (ltn_addr _ hlt) rsub_id\n| by move=> n r m hlt hub; rewrite leq0n take_size rsub_id\n| move=> t1 IHt1 t2 IHt2 r m; rewrite geq_max; case/andP=> hub1 hub2 hmr;\n  case: to_rterm {IHt1 hub1 hmr}(IHt1 r m hub1 hmr) => t1' r1;\n  case=> htake1 hub1' hsub1 <-;\n  case: to_rterm {IHt2 hub2 hsub1}(IHt2 r1 m hub2 hsub1) => t2' r2 /=;\n  rewrite geq_max; case=> htake2 -> hsub2 /= <-;\n  rewrite -{1 2}(cat_take_drop (size r1) r2) htake2; set r3 := drop _ _;\n  rewrite size_cat addnA (leq_trans _ (leq_addr _ _)) //;\n  split=> {hsub2}//;\n   first by [rewrite takel_cat // -htake1 size_take geq_min leqnn orbT];\n  rewrite -(rsub_acc r1 r3 t1') {hub1'}// -{htake1}htake2 {r3}cat_take_drop;\n  by elim: r2 m => //= u r2 IHr2 m; rewrite IHr2\n| do [ move=> t1 IHt1 r m; do 2!move/IHt1=> {IHt1}IHt1\n     | move=> t1 IHt1 n r m; do 2!move/IHt1=> {IHt1}IHt1];\n  case: to_rterm IHt1 => t1' r1 [-> -> hsub1 <-]; split=> {hsub1}//;\n  by elim: r1 m => //= u r1 IHr1 m; rewrite IHr1].\nmove=> t1 IH r m letm /IH {IH} /(_ letm) {letm}.\ncase: to_rterm => t1' r1 /= [def_r ub_t1' ub_r1 <-].\nrewrite size_rcons addnS leqnn -{1}cats1 takel_cat ?def_r; last first.\n  by rewrite -def_r size_take geq_min leqnn orbT.\nelim: r1 m ub_r1 ub_t1' {def_r} => /= [|u r1 IHr1] m => [_|[->]].\n  by rewrite addn0 eqxx.\nby rewrite -addSnnS => /IHr1 IH /IH[_ _ ub_r1 ->].\nQed.\n\n(* Boolean test selecting formulas which describe a constructible set, *)\n(* i.e. formulas without quantifiers.                                  *)\n\n(* The quantifier elimination check. *)\nFixpoint qf_form (f : formula R) :=\n  match f with\n  | Bool _ | _ == _ | Unit _ => true\n  | f1 /\\ f2 | f1 \\/ f2 | f1 ==> f2 => qf_form f1 && qf_form f2\n  | ~ f1 => qf_form f1\n  | _ => false\n  end%T.\n\n(* Boolean holds predicate for quantifier free formulas *)\nDefinition qf_eval e := fix loop (f : formula R) : bool :=\n  match f with\n  | Bool b => b\n  | t1 == t2 => (eval e t1 == eval e t2)%bool\n  | Unit t1 => eval e t1 \\in unit\n  | f1 /\\ f2 => loop f1 && loop f2\n  | f1 \\/ f2 => loop f1 || loop f2\n  | f1 ==> f2 => (loop f1 ==> loop f2)%bool\n  | ~ f1 => ~~ loop f1\n  |_ => false\n  end%T.\n\n(* qf_eval is equivalent to holds *)\nLemma qf_evalP e f : qf_form f -> reflect (holds e f) (qf_eval e f).\nProof.\nelim: f => //=; try by move=> *; exact: idP.\n- move=> t1 t2 _; exact: eqP.\n- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1T]; last by right; case.\n  by case/IHf2; [left | right; case].\n- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1F]; first by do 2 left.\n  by case/IHf2; [left; right | right; case].\n- move=> f1 IHf1 f2 IHf2 /= /andP[/IHf1[] f1T]; last by left.\n  by case/IHf2; [left | right; move/(_ f1T)].\nby move=> f1 IHf1 /IHf1[]; [right | left].\nQed.\n\nImplicit Type bc : seq (term R) * seq (term R).\n\n(* Quantifier-free formula are normalized into DNF. A DNF is *)\n(* represented by the type seq (seq (term R) * seq (term R)), where we *)\n(* separate positive and negative literals *)\n\n(* DNF preserving conjunction *)\nDefinition and_dnf bcs1 bcs2 :=\n  \\big[cat/nil]_(bc1 <- bcs1)\n     map (fun bc2 => (bc1.1 ++ bc2.1, bc1.2 ++ bc2.2)) bcs2.\n\n(* Computes a DNF from a qf ring formula *)\nFixpoint qf_to_dnf (f : formula R) (neg : bool) {struct f} :=\n  match f with\n  | Bool b => if b (+) neg then [:: ([::], [::])] else [::]\n  | t1 == t2 => [:: if neg then ([::], [:: t1 - t2]) else ([:: t1 - t2], [::])]\n  | f1 /\\ f2 => (if neg then cat else and_dnf) [rec f1, neg] [rec f2, neg]\n  | f1 \\/ f2 => (if neg then and_dnf else cat) [rec f1, neg] [rec f2, neg]\n  | f1 ==> f2 => (if neg then and_dnf else cat) [rec f1, ~~ neg] [rec f2, neg]\n  | ~ f1 => [rec f1, ~~ neg]\n  | _ =>  if neg then [:: ([::], [::])] else [::]\n  end%T where \"[ 'rec' f , neg ]\" := (qf_to_dnf f neg).\n\n(* Conversely, transforms a DNF into a formula *)\nDefinition dnf_to_form :=\n  let pos_lit t := And (t == 0) in let neg_lit t := And (t != 0) in \n  let cls bc := Or (foldr pos_lit True bc.1 /\\ foldr neg_lit True bc.2) in\n  foldr cls False.\n\n(* Catenation of dnf is the Or of formulas *)\nLemma cat_dnfP e bcs1 bcs2 :\n  qf_eval e (dnf_to_form (bcs1 ++ bcs2))\n    = qf_eval e (dnf_to_form bcs1 \\/ dnf_to_form bcs2).\nProof.\nby elim: bcs1 => //= bc1 bcs1 IH1; rewrite -orbA; congr orb; rewrite IH1.\nQed.\n\n(* and_dnf is the And of formulas *)\nLemma and_dnfP e bcs1 bcs2 :\n  qf_eval e (dnf_to_form (and_dnf bcs1 bcs2))\n   = qf_eval e (dnf_to_form bcs1 /\\ dnf_to_form bcs2).\nProof.\nelim: bcs1 => [|bc1 bcs1 IH1] /=; first by rewrite /and_dnf big_nil.\nrewrite /and_dnf big_cons -/(and_dnf bcs1 bcs2) cat_dnfP  /=.\nrewrite {}IH1 /= andb_orl; congr orb.\nelim: bcs2 bc1 {bcs1} => [|bc2 bcs2 IH] bc1 /=; first by rewrite andbF.\nrewrite {}IH /= andb_orr; congr orb => {bcs2}.\nsuffices aux (l1 l2 : seq (term R)) g : let redg := foldr (And \\o g) True in\n  qf_eval e (redg (l1 ++ l2)) = qf_eval e (redg l1 /\\ redg l2)%T.\n+ by rewrite 2!aux /= 2!andbA -andbA -andbCA andbA andbCA andbA.\nby elim: l1 => [| t1 l1 IHl1] //=; rewrite -andbA IHl1.\nQed.\n\nLemma qf_to_dnfP e :\n  let qev f b := qf_eval e (dnf_to_form (qf_to_dnf f b)) in\n  forall f, qf_form f && rformula f -> qev f false = qf_eval e f.\nProof.\nmove=> qev; have qevT f: qev f true = ~~ qev f false.\n  rewrite {}/qev; elim: f => //=; do [by case | move=> f1 IH1 f2 IH2 | ].\n  - by move=> t1 t2; rewrite !andbT !orbF.\n  - by rewrite and_dnfP cat_dnfP negb_and -IH1 -IH2.\n  - by rewrite and_dnfP cat_dnfP negb_or -IH1 -IH2.\n  - by rewrite and_dnfP cat_dnfP /= negb_or IH1 -IH2 negbK.\n  by move=> t1 ->; rewrite negbK.\nrewrite /qev; elim=> //=; first by case.\n- by move=> t1 t2 _; rewrite subr_eq0 !andbT orbF.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite and_dnfP /= => /IH1-> /IH2->.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite cat_dnfP /= => /IH1-> => /IH2->.\n- move=> f1 IH1 f2 IH2; rewrite andbCA -andbA andbCA andbA; case/andP.\n  by rewrite cat_dnfP /= [qf_eval _ _]qevT -implybE => /IH1 <- /IH2->.\nby move=> f1 IH1 /IH1 <-; rewrite -qevT.\nQed.\n\nLemma dnf_to_form_qf bcs : qf_form (dnf_to_form bcs).\nProof.\nby elim: bcs => //= [[clT clF] _ ->] /=; elim: clT => //=; elim: clF.\nQed.\n\nDefinition dnf_rterm cl := all rterm cl.1 && all rterm cl.2.\n\nLemma qf_to_dnf_rterm f b : rformula f -> all dnf_rterm (qf_to_dnf f b).\nProof.\nset ok := all dnf_rterm.\nhave cat_ok bcs1 bcs2: ok bcs1 -> ok bcs2 -> ok (bcs1 ++ bcs2).\n  by move=> ok1 ok2; rewrite [ok _]all_cat; exact/andP.\nhave and_ok bcs1 bcs2: ok bcs1 -> ok bcs2 -> ok (and_dnf bcs1 bcs2).\n  rewrite /and_dnf unlock; elim: bcs1 => //= cl1 bcs1 IH1; rewrite -andbA.\n  case/and3P=> ok11 ok12 ok1 ok2; rewrite cat_ok ?{}IH1 {bcs1 ok1}//.\n  elim: bcs2 ok2 => //= cl2 bcs2 IH2 /andP[ok2 /IH2->].\n  by rewrite /dnf_rterm !all_cat ok11 ok12 /= !andbT.\nelim: f b => //=; [ by do 2!case | | | | | by auto | | ];\n  try by repeat case/andP || intro; case: ifP; auto.\nby rewrite /dnf_rterm => ?? [] /= ->.\nQed.\n\nLemma dnf_to_rform bcs : rformula (dnf_to_form bcs) = all dnf_rterm bcs.\nProof.\nelim: bcs => //= [[cl1 cl2] bcs ->]; rewrite {2}/dnf_rterm /=; congr (_ && _).\nby congr andb; [elim: cl1 | elim: cl2] => //= t cl ->; rewrite andbT.\nQed.\n\nSection If.\n\nVariables (pred_f then_f else_f : formula R).\n\nDefinition If := (pred_f /\\ then_f \\/ ~ pred_f /\\ else_f)%T.\n\nLemma If_form_qf :\n  qf_form pred_f -> qf_form then_f -> qf_form else_f -> qf_form If.\nProof. by move=> /= -> -> ->. Qed.\n\nLemma If_form_rf :\n  rformula pred_f -> rformula then_f -> rformula else_f -> rformula If.\nProof. by move=> /= -> -> ->. Qed.\n\nLemma eval_If e :\n  let ev := qf_eval e in ev If = (if ev pred_f then ev then_f else ev else_f).\nProof. by rewrite /=; case: ifP => _; rewrite ?orbF. Qed. \n\nEnd If.\n\nSection Pick.\n\nVariables (I : finType) (pred_f then_f : I -> formula R) (else_f : formula R).\n\nDefinition Pick :=\n  \\big[Or/False]_(p : {ffun pred I})\n    ((\\big[And/True]_i (if p i then pred_f i else ~ pred_f i))\n    /\\ (if pick p is Some i then then_f i else else_f))%T.\n\nLemma Pick_form_qf :\n   (forall i, qf_form (pred_f i)) ->\n   (forall i, qf_form (then_f i)) ->\n    qf_form else_f ->\n  qf_form Pick.\nProof.\nmove=> qfp qft qfe; have mA := (big_morph qf_form) true andb.\nrewrite mA // big1 //= => p _.\nrewrite mA // big1 => [|i _]; first by case: pick.\nby rewrite fun_if if_same /= qfp.\nQed.\n\nLemma eval_Pick e (qev := qf_eval e) :\n  let P i := qev (pred_f i) in\n  qev Pick = (if pick P is Some i then qev (then_f i) else qev else_f).\nProof.\nmove=> P; rewrite ((big_morph qev) false orb) //= big_orE /=.\napply/existsP/idP=> [[p] | true_at_P].\n  rewrite ((big_morph qev) true andb) //= big_andE /=.\n  case/andP=> /forallP eq_p_P.\n  rewrite (@eq_pick _ _ P) => [|i]; first by case: pick.\n  by move/(_ i): eq_p_P => /=; case: (p i) => //=; move/negbTE.\nexists [ffun i => P i] => /=; apply/andP; split.\n  rewrite ((big_morph qev) true andb) //= big_andE /=.\n  by apply/forallP=> i; rewrite /= ffunE; case Pi: (P i) => //=; apply: negbT.\nrewrite (@eq_pick _ _ P) => [|i]; first by case: pick true_at_P.\nby rewrite ffunE.\nQed.\n\nEnd Pick.\n\nSection MultiQuant.\n\nVariable f : formula R.\nImplicit Types (I : seq nat) (e : seq R).\n\nLemma foldExistsP I e :\n  (exists2 e', {in [predC I], same_env e e'} & holds e' f)\n    <-> holds e (foldr Exists f I).\nProof.\nelim: I e => /= [|i I IHi] e.\n  by split=> [[e' eq_e] |]; [apply: eq_holds => i; rewrite eq_e | exists e].\nsplit=> [[e' eq_e f_e'] | [x]]; last set e_x := set_nth 0 e i x.\n  exists e'`_i; apply/IHi; exists e' => // j.\n  by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP => // ->.\ncase/IHi=> e' eq_e f_e'; exists e' => // j.\nby have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP.\nQed.\n\nLemma foldForallP I e :\n  (forall e', {in [predC I], same_env e e'} -> holds e' f)\n    <-> holds e (foldr Forall f I).\nProof.\nelim: I e => /= [|i I IHi] e.\n  by split=> [|f_e e' eq_e]; [exact | apply: eq_holds f_e => i; rewrite eq_e].\nsplit=> [f_e' x | f_e e' eq_e]; first set e_x := set_nth 0 e i x.\n  apply/IHi=> e' eq_e; apply: f_e' => j.\n  by have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP.\nmove/IHi: (f_e e'`_i); apply=> j.\nby have:= eq_e j; rewrite nth_set_nth /= !inE; case: eqP => // ->.\nQed.\n\nEnd MultiQuant.\n\nEnd EvalTerm.\n\nPrenex Implicits dnf_rterm.\n\nModule IntegralDomain.\n\nDefinition axiom (R : ringType) :=\n  forall x y : R, x * y = 0 -> (x == 0) || (y == 0).\n\nSection ClassDef.\n\nRecord class_of (R : Type) : Type :=\n  Class {base : ComUnitRing.class_of R; mixin : axiom (Ring.Pack base R)}.\nLocal Coercion base : class_of >-> ComUnitRing.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack b0 (m0 : axiom (@Ring.Pack T b0 T)) :=\n  fun bT b & phant_id (ComUnitRing.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\nDefinition comRingType := @ComRing.Pack cT xclass xT.\nDefinition unitRingType := @UnitRing.Pack cT xclass xT.\nDefinition comUnitRingType := @ComUnitRing.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> ComUnitRing.class_of.\nImplicit Arguments mixin [R x y].\nCoercion mixin : class_of >-> axiom.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nNotation idomainType := type.\nNotation IdomainType T m := (@pack T _ m _ _ id _ id).\nNotation \"[ 'idomainType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'idomainType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'idomainType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'idomainType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd IntegralDomain.\nImport IntegralDomain.Exports.\n\nSection IntegralDomainTheory.\n\nVariable R : idomainType.\nImplicit Types x y : R.\n\nLemma mulf_eq0 x y : (x * y == 0) = (x == 0) || (y == 0).\nProof.\napply/eqP/idP; first by case: R x y => T [].\nby case/pred2P=> ->; rewrite (mulr0, mul0r).\nQed.\n\nLemma prodf_eq0 (I : finType) (P : pred I) (F : I -> R) :\n  reflect (exists2 i, P i & (F i == 0)) (\\prod_(i | P i) F i == 0).\nProof.\napply: (iffP idP) => [|[i Pi /eqP Fi0]]; last first.\n  by rewrite (bigD1 i) //= Fi0 mul0r.\nelim: (index_enum _) => [|i r IHr]; first by rewrite big_nil oner_eq0.\nrewrite big_cons /=; have [Pi | _] := ifP; last exact: IHr.\nby rewrite mulf_eq0; case/orP=> // Fi0; exists i.\nQed.\n\nLemma prodf_seq_eq0 I r (P : pred I) (F : I -> R) :\n  (\\prod_(i <- r | P i) F i == 0) = has (fun i => P i && (F i == 0)) r.\nProof. by rewrite (big_morph _ mulf_eq0 (oner_eq0 _)) big_has_cond. Qed.\n\nLemma mulf_neq0 x y : x != 0 -> y != 0 -> x * y != 0.\nProof. move=> x0 y0; rewrite mulf_eq0; exact/norP. Qed.\n\nLemma prodf_neq0 (I : finType) (P : pred I) (F : I -> R) :\n  reflect (forall i, P i -> (F i != 0)) (\\prod_(i | P i) F i != 0).\nProof.\nby rewrite (sameP (prodf_eq0 _ _) exists_inP) negb_exists_in; exact: forall_inP.\nQed.\n\nLemma prodf_seq_neq0 I r (P : pred I) (F : I -> R) :\n  (\\prod_(i <- r | P i) F i != 0) = all (fun i => P i ==> (F i != 0)) r.\nProof.\nrewrite prodf_seq_eq0 -all_predC; apply: eq_all => i /=.\nby rewrite implybE negb_and.\nQed.\n\nLemma expf_eq0 x n : (x ^+ n == 0) = (n > 0) && (x == 0).\nProof.\nelim: n => [|n IHn]; first by rewrite oner_eq0.\nby rewrite exprS mulf_eq0 IHn andKb.\nQed.\n\nLemma sqrf_eq0 x : (x ^+ 2 == 0) = (x == 0). Proof. exact: expf_eq0. Qed.\n\nLemma expf_neq0 x m : x != 0 -> x ^+ m != 0.\nProof. by move=> x_nz; rewrite expf_eq0; apply/nandP; right. Qed.\n\nLemma natf_neq0 n : (n%:R != 0 :> R) = [char R]^'.-nat n.\nProof.\nhave [-> | /prod_prime_decomp->] := posnP n; first by rewrite eqxx.\nrewrite !big_seq; elim/big_rec: _ => [|[p e] s /=]; first by rewrite oner_eq0.\ncase/mem_prime_decomp=> p_pr _ _; rewrite pnat_mul pnat_exp eqn0Ngt orbC => <-.\nby rewrite natrM natrX mulf_eq0 expf_eq0 negb_or negb_and pnatE ?inE p_pr.\nQed.\n\nLemma eqf_sqr x y : (x ^+ 2 == y ^+ 2) = (x == y) || (x == - y).\nProof. by rewrite -subr_eq0 subr_sqr mulf_eq0 subr_eq0 addr_eq0. Qed.\n\nLemma mulfI x : x != 0 -> injective ( *%R x).\nProof.\nmove=> nz_x y z; rewrite -[x * z]add0r; move/(canLR (addrK _))/eqP.\nrewrite -mulrN -mulrDr mulf_eq0 (negbTE nz_x) /=.\nby move/eqP/(canRL (subrK _)); rewrite add0r.\nQed.\n\nLemma mulIf x : x != 0 -> injective ( *%R^~ x).\nProof. by move=> nz_x y z; rewrite -!(mulrC x); exact: mulfI. Qed.\n\nLemma sqrf_eq1 x : (x ^+ 2 == 1) = (x == 1) || (x == -1).\nProof. by rewrite -subr_eq0 subr_sqr_1 mulf_eq0 subr_eq0 addr_eq0. Qed.\n\nLemma expfS_eq1 x n :\n  (x ^+ n.+1 == 1) = (x == 1) || (\\sum_(i < n.+1) x ^+ i == 0).\nProof. by rewrite -![_ == 1]subr_eq0 subrX1 mulf_eq0. Qed.\n\nLemma lregP x : reflect (lreg x) (x != 0).\nProof. by apply: (iffP idP) => [/mulfI | /lreg_neq0]. Qed.\n\nLemma rregP x : reflect (rreg x) (x != 0).\nProof. by apply: (iffP idP) => [/mulIf | /rreg_neq0]. Qed.\n\nCanonical regular_idomainType := [idomainType of R^o].\n\nEnd IntegralDomainTheory.\n\nImplicit Arguments lregP [[R] [x]].\nImplicit Arguments rregP [[R] [x]].\n\nModule Field.\n\nDefinition mixin_of (F : unitRingType) := forall x : F, x != 0 -> x \\in unit.\n\nLemma IdomainMixin R : mixin_of R -> IntegralDomain.axiom R.\nProof.\nmove=> m x y xy0; apply/norP=> [[]] /m Ux /m.\nby rewrite -(unitrMr _ Ux) xy0 unitr0.\nQed.\n\nSection Mixins.\n\nVariables (R : comRingType) (inv : R -> R).\n\nDefinition axiom := forall x, x != 0 -> inv x * x = 1.\nHypothesis mulVx : axiom.\nHypothesis inv0 : inv 0 = 0.\n\nFact intro_unit (x y : R) : y * x = 1 -> x != 0.\nProof.\nby move=> yx1; apply: contraNneq (oner_neq0 R) => x0; rewrite -yx1 x0 mulr0.\nQed.\n\nFact inv_out : {in predC (predC1 0), inv =1 id}.\nProof. by move=> x /negbNE/eqP->. Qed.\n\nDefinition UnitMixin := ComUnitRing.Mixin mulVx intro_unit inv_out.\n\nLemma Mixin : mixin_of (UnitRing.Pack (UnitRing.Class UnitMixin) R).\nProof. by []. Qed.\n\nEnd Mixins.\n\nSection ClassDef.\n\nRecord class_of (F : Type) : Type := Class {\n  base : IntegralDomain.class_of F;\n  mixin : mixin_of (UnitRing.Pack base F)\n}.\nLocal Coercion base : class_of >-> IntegralDomain.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack b0 (m0 : mixin_of (@UnitRing.Pack T b0 T)) :=\n  fun bT b & phant_id (IntegralDomain.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\nDefinition comRingType := @ComRing.Pack cT xclass xT.\nDefinition unitRingType := @UnitRing.Pack cT xclass xT.\nDefinition comUnitRingType := @ComUnitRing.Pack cT xclass xT.\nDefinition idomainType := @IntegralDomain.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> IntegralDomain.class_of.\nImplicit Arguments mixin [F x].\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nCoercion idomainType : type >-> IntegralDomain.type.\nCanonical idomainType.\nNotation fieldType := type.\nNotation FieldType T m := (@pack T _ m _ _ id _ id).\nNotation FieldUnitMixin := UnitMixin.\nNotation FieldIdomainMixin := IdomainMixin.\nNotation FieldMixin := Mixin.\nNotation \"[ 'fieldType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'fieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'fieldType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'fieldType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd Field.\nImport Field.Exports.\n\nSection FieldTheory.\n\nVariable F : fieldType.\nImplicit Types x y : F.\n\nLemma unitfE x : (x \\in unit) = (x != 0).\nProof.\napply/idP/idP=> [Ux |]; last by case: F x => T [].\nby apply/eqP=> x0; rewrite x0 unitr0 in Ux.\nQed.\n\nLemma mulVf x : x != 0 -> x^-1 * x = 1.\nProof. by rewrite -unitfE; exact: mulVr. Qed.\nLemma divff x : x != 0 -> x / x = 1.\nProof. by rewrite -unitfE; exact: divrr. Qed.\nDefinition mulfV := divff.\nLemma mulKf x : x != 0 -> cancel ( *%R x) ( *%R x^-1).\nProof. by rewrite -unitfE; exact: mulKr. Qed.\nLemma mulVKf x : x != 0 -> cancel ( *%R x^-1) ( *%R x).\nProof. by rewrite -unitfE; exact: mulVKr. Qed.\nLemma mulfK x : x != 0 -> cancel ( *%R^~ x) ( *%R^~ x^-1).\nProof. by rewrite -unitfE; exact: mulrK. Qed.\nLemma mulfVK x : x != 0 -> cancel ( *%R^~ x^-1) ( *%R^~ x).\nProof. by rewrite -unitfE; exact: divrK. Qed.\nDefinition divfK := mulfVK.\n\nLemma invfM : {morph @inv F : x y / x * y}.\nProof.\nmove=> x y; case: (eqVneq x 0) => [-> |nzx]; first by rewrite !(mul0r, invr0).\ncase: (eqVneq y 0) => [-> |nzy]; first by rewrite !(mulr0, invr0).\nby rewrite mulrC invrM ?unitfE.\nQed.\n\nLemma expfB_cond m n x : (x == 0) + n <= m -> x ^+ (m - n) = x ^+ m / x ^+ n.\nProof.\nmove/subnK=> <-; rewrite addnA addnK !exprD.\nhave [-> | nz_x] := altP eqP; first by rewrite !mulr0 !mul0r.\nby rewrite mulfK ?expf_neq0.\nQed.\n\nLemma expfB m n x : n < m -> x ^+ (m - n) = x ^+ m / x ^+ n.\nProof. by move=> lt_n_m; apply: expfB_cond; case: eqP => // _; apply: ltnW. Qed.\n\nLemma prodf_inv I r (P : pred I) (E : I -> F) :\n  \\prod_(i <- r | P i) (E i)^-1 = (\\prod_(i <- r | P i) E i)^-1.\nProof. by rewrite (big_morph _ invfM (invr1 _)). Qed.\n\nLemma addf_div x1 y1 x2 y2 :\n  y1 != 0 -> y2 != 0 -> x1 / y1 + x2 / y2 = (x1 * y2 + x2 * y1) / (y1 * y2).\nProof. by move=> nzy1 nzy2; rewrite invfM mulrDl !mulrA mulrAC !mulfK. Qed.\n\nLemma mulf_div x1 y1 x2 y2 : (x1 / y1) * (x2 / y2) = (x1 * x2) / (y1 * y2).\nProof. by rewrite mulrACA -invfM. Qed.\n\nLemma natf0_char n : n > 0 -> n%:R == 0 :> F -> exists p, p \\in [char F].\nProof.\nelim: {n}_.+1 {-2}n (ltnSn n) => // m IHm n; rewrite ltnS => le_n_m.\nrewrite leq_eqVlt -pi_pdiv mem_primes; move: (pdiv n) => p.\ncase/predU1P=> [<-|/and3P[p_pr n_gt0 /dvdnP[n']]]; first by rewrite oner_eq0.\nmove=> def_n; rewrite def_n muln_gt0 andbC prime_gt0 // in n_gt0 *.\nrewrite natrM mulf_eq0 orbC; case/orP; first by exists p; exact/andP.\nby apply: IHm (leq_trans _ le_n_m) _; rewrite // def_n ltn_Pmulr // prime_gt1.\nQed.\n\nLemma charf'_nat n : [char F]^'.-nat n = (n%:R != 0 :> F).\nProof.\nhave [-> | n_gt0] := posnP n; first by rewrite eqxx.\napply/idP/idP => [|nz_n]; last first.\n  by apply/pnatP=> // p p_pr p_dvd_n; apply: contra nz_n => /dvdn_charf <-.\napply: contraL => n0; have [// | p charFp] := natf0_char _ n0.\nhave [p_pr _] := andP charFp; rewrite (eq_pnat _ (eq_negn (charf_eq charFp))).\nby rewrite p'natE // (dvdn_charf charFp) n0.\nQed.\n\nLemma charf0P : [char F] =i pred0 <-> (forall n, (n%:R == 0 :> F) = (n == 0)%N).\nProof.\nsplit=> charF0 n; last by rewrite !inE charF0 andbC; case: eqP => // ->.\nhave [-> | n_gt0] := posnP; first exact: eqxx.\nby apply/negP; case/natf0_char=> // p; rewrite charF0.\nQed.\n\nLemma char0_natf_div :\n  [char F] =i pred0 -> forall m d, d %| m -> (m %/ d)%:R = m%:R / d%:R :> F.\nProof.\nmove/charf0P=> char0F m [|d] d_dv_m; first by rewrite divn0 invr0 mulr0.\nby rewrite natr_div // unitfE char0F.\nQed.\n\nSection FieldMorphismInj.\n\nVariables (R : ringType) (f : {rmorphism F -> R}).\n\nLemma fmorph_eq0 x : (f x == 0) = (x == 0).\nProof.\nhave [-> | nz_x] := altP (x =P _); first by rewrite rmorph0 eqxx.\napply/eqP; move/(congr1 ( *%R (f x^-1)))/eqP.\nby rewrite -rmorphM mulVf // mulr0 rmorph1 ?oner_eq0.\nQed.\n\nLemma fmorph_inj : injective f.\nProof.\nmove=> x y eqfxy; apply/eqP; rewrite -subr_eq0 -fmorph_eq0 rmorphB //.\nby rewrite eqfxy subrr.\nQed.\n\nLemma fmorph_eq1 x : (f x == 1) = (x == 1).\nProof. by rewrite -(inj_eq fmorph_inj) rmorph1. Qed.\n\nLemma fmorph_char : [char R] =i [char F].\nProof. by move=> p; rewrite !inE -fmorph_eq0 rmorph_nat. Qed.\n\nEnd FieldMorphismInj.\n\nSection FieldMorphismInv.\n\nVariables (R : unitRingType) (f : {rmorphism F -> R}).\n\nLemma fmorph_unit x : (f x \\in unit) = (x != 0).\nProof.\nhave [-> |] := altP (x =P _); first by rewrite rmorph0 unitr0.\nby rewrite -unitfE; exact: rmorph_unit.\nQed.\n\nLemma fmorphV : {morph f: x / x^-1}.\nProof.\nmove=> x; have [-> | nz_x] := eqVneq x 0; first by rewrite !(invr0, rmorph0).\nby rewrite rmorphV ?unitfE.\nQed.\n\nLemma fmorph_div : {morph f : x y / x / y}.\nProof. by move=> x y; rewrite rmorphM fmorphV. Qed.\n\nEnd FieldMorphismInv.\n\nCanonical regular_fieldType := [fieldType of F^o].\n\nSection ModuleTheory.\n\nVariable V : lmodType F.\nImplicit Types (a : F) (v : V).\n\nLemma scalerK a : a != 0 -> cancel ( *:%R a : V -> V) ( *:%R a^-1).\nProof. by move=> nz_a v; rewrite scalerA mulVf // scale1r. Qed.\n\nLemma scalerKV a : a != 0 -> cancel ( *:%R a^-1 : V -> V) ( *:%R a).\nProof. by rewrite -invr_eq0 -{3}[a]invrK; exact: scalerK. Qed.\n\nLemma scalerI a : a != 0 -> injective ( *:%R a : V -> V).\nProof. move=> nz_a; exact: can_inj (scalerK nz_a). Qed.\n\nLemma scaler_eq0 a v : (a *: v == 0) = (a == 0) || (v == 0).\nProof.\nhave [-> | nz_a] := altP (a =P _); first by rewrite scale0r eqxx.\nby rewrite (can2_eq (scalerK nz_a) (scalerKV nz_a)) scaler0.\nQed.\n\nLemma rpredZeq S (modS : submodPred S) (kS : keyed_pred modS) a v :\n  (a *: v \\in kS) = (a == 0) || (v \\in kS).\nProof.\nhave [-> | nz_a] := altP eqP; first by rewrite scale0r rpred0.\nby apply/idP/idP; first rewrite -{2}(scalerK nz_a v); apply: rpredZ.\nQed.\n\nEnd ModuleTheory.\n\nSection Predicates.\n\nContext (S : pred_class) (divS : @divrPred F S) (kS : keyed_pred divS).\n\nLemma fpredMl x y : x \\in kS -> x != 0 -> (x * y \\in kS) = (y \\in kS).\nProof. by rewrite -!unitfE; exact: rpredMl. Qed.\n\nLemma fpredMr x y : x \\in kS -> x != 0 -> (y * x \\in kS) = (y \\in kS).\nProof. by rewrite -!unitfE; exact: rpredMr. Qed.\n\nLemma fpred_divl x y : x \\in kS -> x != 0 -> (x / y \\in kS) = (y \\in kS).\nProof. by rewrite -!unitfE; exact: rpred_divl. Qed.\n\nLemma fpred_divr x y : x \\in kS -> x != 0 -> (y / x \\in kS) = (y \\in kS).\nProof. by rewrite -!unitfE; exact: rpred_divr. Qed.\n\nEnd Predicates.\n\nEnd FieldTheory.\n\nImplicit Arguments fmorph_inj [[F] [R] x1 x2].\n\nModule DecidableField.\n\nDefinition axiom (R : unitRingType) (s : seq R -> pred (formula R)) :=\n  forall e f, reflect (holds e f) (s e f).\n\nRecord mixin_of (R : unitRingType) : Type :=\n  Mixin { sat : seq R -> pred (formula R); satP : axiom sat}.\n\nSection ClassDef.\n\nRecord class_of (F : Type) : Type :=\n  Class {base : Field.class_of F; mixin : mixin_of (UnitRing.Pack base F)}.\nLocal Coercion base : class_of >-> Field.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack b0 (m0 : mixin_of (@UnitRing.Pack T b0 T)) :=\n  fun bT b & phant_id (Field.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\nDefinition comRingType := @ComRing.Pack cT xclass xT.\nDefinition unitRingType := @UnitRing.Pack cT xclass xT.\nDefinition comUnitRingType := @ComUnitRing.Pack cT xclass xT.\nDefinition idomainType := @IntegralDomain.Pack cT xclass xT.\nDefinition fieldType := @Field.Pack cT xclass xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> Field.class_of.\nCoercion mixin : class_of >-> mixin_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nCoercion idomainType : type >-> IntegralDomain.type.\nCanonical idomainType.\nCoercion fieldType : type >-> Field.type.\nCanonical fieldType.\nNotation decFieldType := type.\nNotation DecFieldType T m := (@pack T _ m _ _ id _ id).\nNotation DecFieldMixin := Mixin.\nNotation \"[ 'decFieldType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'decFieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'decFieldType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'decFieldType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd DecidableField.\nImport DecidableField.Exports.\n\nSection DecidableFieldTheory.\n\nVariable F : decFieldType.\n\nDefinition sat := DecidableField.sat (DecidableField.class F).\n\nLemma satP : DecidableField.axiom sat.\nProof. exact: DecidableField.satP. Qed.\n\nFact sol_subproof n f :\n  reflect (exists s, (size s == n) && sat s f)\n          (sat [::] (foldr Exists f (iota 0 n))).\nProof.\napply: (iffP (satP _ _)) => [|[s]]; last first.\n  case/andP=> /eqP sz_s /satP f_s; apply/foldExistsP.\n  exists s => // i; rewrite !inE mem_iota -leqNgt add0n => le_n_i.\n  by rewrite !nth_default ?sz_s.\ncase/foldExistsP=> e e0 f_e; set s := take n (set_nth 0 e n 0).\nhave sz_s: size s = n by rewrite size_take size_set_nth leq_max leqnn.\nexists s; rewrite sz_s eqxx; apply/satP; apply: eq_holds f_e => i.\ncase: (leqP n i) => [le_n_i | lt_i_n].\n  by rewrite -e0 ?nth_default ?sz_s // !inE mem_iota -leqNgt.\nby rewrite nth_take // nth_set_nth /= eq_sym eqn_leq leqNgt lt_i_n.\nQed.\n\nDefinition sol n f :=\n  if sol_subproof n f is ReflectT sP then xchoose sP else nseq n 0.\n\nLemma size_sol n f : size (sol n f) = n.\nProof.\nrewrite /sol; case: sol_subproof => [sP | _]; last exact: size_nseq.\nby case/andP: (xchooseP sP) => /eqP.\nQed.\n\nLemma solP n f : reflect (exists2 s, size s = n & holds s f) (sat (sol n f) f).\nProof.\nrewrite /sol; case: sol_subproof => [sP | sPn].\n  case/andP: (xchooseP sP) => _ ->; left.\n  by case: sP => s; case/andP; move/eqP=> <-; move/satP; exists s.\napply: (iffP (satP _ _)); first by exists (nseq n 0); rewrite ?size_nseq.\nby case=> s sz_s; move/satP=> f_s; case: sPn; exists s; rewrite sz_s eqxx.\nQed.\n\nLemma eq_sat f1 f2 :\n  (forall e, holds e f1 <-> holds e f2) -> sat^~ f1 =1 sat^~ f2.\nProof. by move=> eqf12 e; apply/satP/satP; case: (eqf12 e). Qed.\n\nLemma eq_sol f1 f2 :\n  (forall e, holds e f1 <-> holds e f2) -> sol^~ f1 =1 sol^~ f2.\nProof.\nrewrite /sol => /eq_sat eqf12 n.\ndo 2![case: sol_subproof] => //= [f1s f2s | ns1 [s f2s] | [s f1s] []].\n- by apply: eq_xchoose => s; rewrite eqf12.\n- by case: ns1; exists s; rewrite -eqf12.\nby exists s; rewrite eqf12.\nQed.\n\nEnd DecidableFieldTheory.\n\nImplicit Arguments satP [[F] [e] [f]].\nImplicit Arguments solP [[F] [n] [f]].\n\nSection QE_Mixin.\n\nVariable F : Field.type.\nImplicit Type f : formula F.\n\nVariable proj : nat -> seq (term F) * seq (term F) -> formula F.\n(* proj is the elimination of a single existential quantifier *)\n\n(* The elimination projector is well_formed. *)\nDefinition wf_QE_proj :=\n  forall i bc (bc_i := proj i bc),\n  dnf_rterm bc -> qf_form bc_i && rformula bc_i.\n\n(* The elimination projector is valid *)\nDefinition valid_QE_proj :=\n  forall i bc (ex_i_bc := ('exists 'X_i, dnf_to_form [:: bc])%T) e,\n  dnf_rterm bc -> reflect (holds e ex_i_bc) (qf_eval e (proj i bc)).\n\nHypotheses (wf_proj : wf_QE_proj) (ok_proj : valid_QE_proj).\n\nLet elim_aux f n := foldr Or False (map (proj n) (qf_to_dnf f false)).\n\nFixpoint quantifier_elim f :=\n  match f with\n  | f1 /\\ f2 => (quantifier_elim f1) /\\ (quantifier_elim f2)\n  | f1 \\/ f2 => (quantifier_elim f1) \\/ (quantifier_elim f2)\n  | f1 ==> f2 => (~ quantifier_elim f1) \\/ (quantifier_elim f2)\n  | ~ f => ~ quantifier_elim f\n  | ('exists 'X_n, f) => elim_aux (quantifier_elim f) n\n  | ('forall 'X_n, f) => ~ elim_aux (~ quantifier_elim f) n\n  | _ => f\n  end%T.\n\nLemma quantifier_elim_wf f :\n  let qf := quantifier_elim f in rformula f -> qf_form qf && rformula qf.\nProof.\nsuffices aux_wf f0 n : let qf := elim_aux f0 n in\n  rformula f0 -> qf_form qf && rformula qf.\n- by elim: f => //=; do ?[  move=> f1 IH1 f2 IH2;\n                     case/andP=> rf1 rf2;\n                     case/andP:(IH1 rf1)=> -> ->;\n                     case/andP:(IH2 rf2)=> -> -> //\n                  |  move=> n f1 IH rf1;\n                     case/andP: (IH rf1)=> qff rf;\n                     rewrite aux_wf ].\nrewrite /elim_aux => rf.\nsuffices or_wf fs : let ofs := foldr Or False fs in \n  all (@qf_form F) fs && all (@rformula F) fs -> qf_form ofs && rformula ofs.\n- apply: or_wf.\n  suffices map_proj_wf bcs: let mbcs := map (proj n) bcs in\n    all dnf_rterm bcs -> all (@qf_form _) mbcs && all (@rformula _) mbcs.\n    by apply: map_proj_wf; exact: qf_to_dnf_rterm.\n  elim: bcs => [|bc bcs ihb] bcsr //= /andP[rbc rbcs].\n  by rewrite andbAC andbA wf_proj //= andbC ihb.\nelim: fs => //= g gs ihg; rewrite -andbA => /and4P[-> qgs -> rgs] /=.\nby apply: ihg; rewrite qgs rgs.\nQed.\n\nLemma quantifier_elim_rformP e f :\n  rformula f -> reflect (holds e f) (qf_eval e (quantifier_elim f)).\nProof.\npose rc e n f := exists x, qf_eval (set_nth 0 e n x) f.\nhave auxP f0 e0 n0: qf_form f0 && rformula f0 ->\n  reflect (rc e0 n0 f0) (qf_eval e0 (elim_aux f0 n0)).\n+ rewrite /elim_aux => cf; set bcs := qf_to_dnf f0 false.\n  apply: (@iffP (rc e0 n0 (dnf_to_form bcs))); last first.\n  - by case=> x; rewrite -qf_to_dnfP //; exists x.\n  - by case=> x; rewrite qf_to_dnfP //; exists x.\n  have: all dnf_rterm bcs by case/andP: cf => _; exact: qf_to_dnf_rterm.\n  elim: {f0 cf}bcs => [|bc bcs IHbcs] /=; first by right; case.\n  case/andP=> r_bc /IHbcs {IHbcs}bcsP.\n  have f_qf := dnf_to_form_qf [:: bc].\n  case: ok_proj => //= [ex_x|no_x].\n    left; case: ex_x => x /(qf_evalP _ f_qf); rewrite /= orbF => bc_x.\n    by exists x; rewrite /= bc_x.\n  apply: (iffP bcsP) => [[x bcs_x] | [x]] /=.\n    by exists x; rewrite /= bcs_x orbT.\n  case/orP => [bc_x|]; last by exists x.\n  by case: no_x; exists x; apply/(qf_evalP _ f_qf); rewrite /= bc_x.\nelim: f e => //.\n- move=> b e _; exact: idP.\n- move=> t1 t2 e _; exact: eqP.\n- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; last by right; case.\n  by case/IH2; [left | right; case].\n- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; first by do 2!left.\n  by case/IH2; [left; right | right; case].\n- move=> f1 IH1 f2 IH2 e /= /andP[/IH1[] f1e]; last by left.\n  by case/IH2; [left | right; move/(_ f1e)].\n- by move=> f IHf e /= /IHf[]; [right | left].\n- move=> n f IHf e /= rf; have rqf := quantifier_elim_wf rf.\n  by apply: (iffP (auxP _ _ _ rqf)) => [] [x]; exists x; exact/IHf.\nmove=> n f IHf e /= rf; have rqf := quantifier_elim_wf rf.\ncase: auxP => // [f_x|no_x]; first by right=> no_x; case: f_x => x /IHf[].\nby left=> x; apply/IHf=> //; apply/idPn=> f_x; case: no_x; exists x.\nQed.\n\nDefinition proj_sat e f := qf_eval e (quantifier_elim (to_rform f)).\n\nLemma proj_satP : DecidableField.axiom proj_sat.\nProof.\nmove=> e f; have fP := quantifier_elim_rformP e (to_rform_rformula f).\nby apply: (iffP fP); move/to_rformP.\nQed.\n\nDefinition QEdecFieldMixin := DecidableField.Mixin proj_satP.\n\nEnd QE_Mixin.\n\nModule ClosedField.\n\n(* Axiom == all non-constant monic polynomials have a root *)\nDefinition axiom (R : ringType) :=\n  forall n (P : nat -> R), n > 0 ->\n   exists x : R, x ^+ n = \\sum_(i < n) P i * (x ^+ i).\n\nSection ClassDef.\n\nRecord class_of (F : Type) : Type :=\n  Class {base : DecidableField.class_of F; _ : axiom (Ring.Pack base F)}.\nLocal Coercion base : class_of >-> DecidableField.class_of.\n\nStructure type := Pack {sort; _ : class_of sort; _ : Type}.\nLocal Coercion sort : type >-> Sortclass.\nVariable (T : Type) (cT : type).\nDefinition class := let: Pack _ c _ as cT' := cT return class_of cT' in c.\nDefinition clone c of phant_id class c := @Pack T c T.\nLet xT := let: Pack T _ _ := cT in T.\nNotation xclass := (class : class_of xT).\n\nDefinition pack b0 (m0 : axiom (@Ring.Pack T b0 T)) :=\n  fun bT b & phant_id (DecidableField.class bT) b =>\n  fun    m & phant_id m0 m => Pack (@Class T b m) T.\n\n(* There should eventually be a constructor from polynomial resolution *)\n(* that builds the DecidableField mixin using QE.                      *)\n\nDefinition eqType := @Equality.Pack cT xclass xT.\nDefinition choiceType := @Choice.Pack cT xclass xT.\nDefinition zmodType := @Zmodule.Pack cT xclass xT.\nDefinition ringType := @Ring.Pack cT xclass xT.\nDefinition comRingType := @ComRing.Pack cT xclass xT.\nDefinition unitRingType := @UnitRing.Pack cT xclass xT.\nDefinition comUnitRingType := @ComUnitRing.Pack cT xclass xT.\nDefinition idomainType := @IntegralDomain.Pack cT xclass xT.\nDefinition fieldType := @Field.Pack cT xclass xT.\nDefinition decFieldType := @DecidableField.Pack cT class xT.\n\nEnd ClassDef.\n\nModule Exports.\nCoercion base : class_of >-> DecidableField.class_of.\nCoercion sort : type >-> Sortclass.\nBind Scope ring_scope with sort.\nCoercion eqType : type >-> Equality.type.\nCanonical eqType.\nCoercion choiceType : type >-> Choice.type.\nCanonical choiceType.\nCoercion zmodType : type >-> Zmodule.type.\nCanonical zmodType.\nCoercion ringType : type >-> Ring.type.\nCanonical ringType.\nCoercion comRingType : type >-> ComRing.type.\nCanonical comRingType.\nCoercion unitRingType : type >-> UnitRing.type.\nCanonical unitRingType.\nCoercion comUnitRingType : type >-> ComUnitRing.type.\nCanonical comUnitRingType.\nCoercion idomainType : type >-> IntegralDomain.type.\nCanonical idomainType.\nCoercion fieldType : type >-> Field.type.\nCanonical fieldType.\nCoercion decFieldType : type >-> DecidableField.type.\nCanonical decFieldType.\nNotation closedFieldType := type.\nNotation ClosedFieldType T m := (@pack T _ m _ _ id _ id).\nNotation \"[ 'closedFieldType' 'of' T 'for' cT ]\" := (@clone T cT _ idfun)\n  (at level 0, format \"[ 'closedFieldType'  'of'  T  'for'  cT ]\") : form_scope.\nNotation \"[ 'closedFieldType' 'of' T ]\" := (@clone T _ _ id)\n  (at level 0, format \"[ 'closedFieldType'  'of'  T ]\") : form_scope.\nEnd Exports.\n\nEnd ClosedField.\nImport ClosedField.Exports.\n\nSection ClosedFieldTheory.\n\nVariable F : closedFieldType.\n\nLemma solve_monicpoly : ClosedField.axiom F.\nProof. by case: F => ? []. Qed.\n\nEnd ClosedFieldTheory.\n\nModule SubType.\n\nSection Zmodule.\n\nVariables (V : zmodType) (S : predPredType V).\nVariables (subS : zmodPred S) (kS : keyed_pred subS).\nVariable U : subType (mem kS).\n\nLet inU v Sv : U := Sub v Sv.\nLet zeroU := inU (rpred0 kS).\n\nLet oppU (u : U) := inU (rpredNr (valP u)).\nLet addU (u1 u2 : U) := inU (rpredD (valP u1) (valP u2)).\n\nFact addA : associative addU.\nProof. by move=> u1 u2 u3; apply: val_inj; rewrite !SubK addrA. Qed.\nFact addC : commutative addU.\nProof. by move=> u1 u2; apply: val_inj; rewrite !SubK addrC. Qed.\nFact add0 : left_id zeroU addU.\nProof. by move=> u; apply: val_inj; rewrite !SubK add0r. Qed.\nFact addN : left_inverse zeroU oppU addU.\nProof. by move=> u; apply: val_inj; rewrite !SubK addNr. Qed.\n\nDefinition zmodMixin of phant U := ZmodMixin addA addC add0 addN.\n\nEnd Zmodule.\n\nSection Ring.\n\nVariables (R : ringType) (S : predPredType R).\nVariables (ringS : subringPred S) (kS : keyed_pred ringS).\n\nDefinition cast_zmodType (V : zmodType) T (VeqT : V = T :> Type) :=\n  let cast mV := let: erefl in _ = T := VeqT return Zmodule.class_of T in mV in\n  Zmodule.Pack (cast (Zmodule.class V)) T.\n\nVariable (T : subType (mem kS)) (V : zmodType) (VeqT: V = T :> Type).\n\nLet inT x Sx : T := Sub x Sx.\nLet oneT := inT (rpred1 kS).\nLet mulT (u1 u2 : T) := inT (rpredM (valP u1) (valP u2)).\nLet T' := cast_zmodType VeqT.\n\nHypothesis valM : {morph (val : T' -> R) : x y / x - y}.\n\nLet val0 : val (0 : T') = 0.\nProof. by rewrite -(subrr (0 : T')) valM subrr. Qed.\nLet valD : {morph (val : T' -> R): x y / x + y}.\nProof.\nby move=> u v; rewrite -{1}[v]opprK -[- v]sub0r !valM val0 sub0r opprK.\nQed.\n\nFact mulA : @associative T' mulT.\nProof. by move=> u1 u2 u3; apply: val_inj; rewrite !SubK mulrA. Qed.\nFact mul1l : left_id oneT mulT.\nProof. by move=> u; apply: val_inj; rewrite !SubK mul1r. Qed.\nFact mul1r : right_id oneT mulT.\nProof. by move=> u; apply: val_inj; rewrite !SubK mulr1. Qed.\nFact mulDl : @left_distributive T' T' mulT +%R.\nProof. by move=> u1 u2 u3; apply: val_inj; rewrite !(SubK, valD) mulrDl. Qed.\nFact mulDr : @right_distributive T' T' mulT +%R.\nProof. by move=> u1 u2 u3; apply: val_inj; rewrite !(SubK, valD) mulrDr. Qed.\nFact nz1 : oneT != 0 :> T'.\nProof.\nby apply: contraNneq (oner_neq0 R) => eq10; rewrite -val0 -eq10 SubK.\nQed.\n\nDefinition ringMixin := RingMixin mulA mul1l mul1r mulDl mulDr nz1.\n\nEnd Ring.\n\nSection Lmodule.\n\nVariables (R : ringType) (V : lmodType R) (S : predPredType V).\nVariables (linS : submodPred S) (kS : keyed_pred linS).\nVariables (W : subType (mem kS)) (Z : zmodType) (ZeqW : Z = W :> Type).\n\nLet scaleW a (w : W) := (Sub _ : _ -> W) (rpredZ a (valP w)).\nLet W' := cast_zmodType ZeqW.\n\nHypothesis valD : {morph (val : W' -> V) : x y / x + y}.\n\nFact scaleA a b (w : W') : scaleW a (scaleW b w) = scaleW (a * b) w.\nProof. by apply: val_inj; rewrite !SubK scalerA. Qed.\nFact scale1 : left_id 1 scaleW.\nProof. by move=> w; apply: val_inj; rewrite !SubK scale1r. Qed.\nFact scaleDr : @right_distributive R W' scaleW +%R.\nProof. by move=> a w w2; apply: val_inj; rewrite !(SubK, valD) scalerDr. Qed.\nFact scaleDl w : {morph (scaleW^~ w : R -> W') : a b / a + b}.\nProof. by move=> a b; apply: val_inj; rewrite !(SubK, valD) scalerDl. Qed.\n\nDefinition lmodMixin := LmodMixin scaleA scale1 scaleDr scaleDl.\n\nEnd Lmodule.\n\nLemma lalgMixin (R : ringType) (A : lalgType R) (B : lmodType R) (f : B -> A) :\n     phant B -> injective f -> scalable f -> \n   forall mulB, {morph f : x y / mulB x y >-> x * y} -> Lalgebra.axiom mulB.\nProof.\nby move=> _ injf fZ mulB fM a x y; apply: injf; rewrite !(fZ, fM) scalerAl.\nQed.\n\nLemma comRingMixin (R : comRingType) (T : ringType) (f : T -> R) :\n  phant T -> injective f -> {morph f : x y / x * y} -> commutative (@mul T).\nProof. by move=> _ inj_f fM x y; apply: inj_f; rewrite !fM mulrC. Qed.\n\nLemma algMixin (R : comRingType) (A : algType R) (B : lalgType R) (f : B -> A) :\n    phant B -> injective f -> {morph f : x y / x * y} -> scalable f ->\n  @Algebra.axiom R B.\nProof.\nby move=> _ inj_f fM fZ a x y; apply: inj_f; rewrite !(fM, fZ) scalerAr.\nQed.\n\nSection UnitRing.\n\nDefinition cast_ringType (Q : ringType) T (QeqT : Q = T :> Type) :=\n  let cast rQ := let: erefl in _ = T := QeqT return Ring.class_of T in rQ in\n  Ring.Pack (cast (Ring.class Q)) T.\n\nVariables (R : unitRingType) (S : predPredType R).\nVariables (ringS : divringPred S) (kS : keyed_pred ringS).\n\nVariables (T : subType (mem kS)) (Q : ringType) (QeqT : Q = T :> Type).\n\nLet inT x Sx : T := Sub x Sx.\nLet invT (u : T) := inT (rpredVr (valP u)).\nLet unitT := [qualify a u : T | val u \\is a unit].\nLet T' := cast_ringType QeqT.\n\nHypothesis val1 : val (1 : T') = 1.\nHypothesis valM : {morph (val : T' -> R) : x y / x * y}.\n\nFact mulVr :\n  {in (unitT : predPredType T'), left_inverse (1 : T') invT (@mul T')}.\nProof. by move=> u Uu; apply: val_inj; rewrite val1 valM SubK mulVr. Qed.\n\nFact mulrV : {in unitT, right_inverse (1 : T') invT (@mul T')}.\nProof. by move=> u Uu; apply: val_inj; rewrite val1 valM SubK mulrV. Qed.\n\nFact unitP (u v : T') : v * u = 1 /\\ u * v = 1 -> u \\in unitT.\nProof.\nby case=> vu1 uv1; apply/unitrP; exists (val v); rewrite -!valM vu1 uv1.\nQed.\n\nFact unit_id : {in [predC unitT], invT =1 id}.\nProof. by move=> u /invr_out def_u1; apply: val_inj; rewrite SubK. Qed.\n\nDefinition unitRingMixin := UnitRingMixin mulVr mulrV unitP unit_id.\n\nEnd UnitRing.\n\nLemma idomainMixin (R : idomainType) (T : ringType) (f : T -> R) :\n    phant T -> injective f -> f 0 = 0 -> {morph f : u v / u * v} ->\n  @IntegralDomain.axiom T.\nProof.\nmove=> _ injf f0 fM u v uv0.\nby rewrite -!(inj_eq injf) !f0 -mulf_eq0 -fM uv0 f0.\nQed.\n\nLemma fieldMixin (F : fieldType) (K : unitRingType) (f : K -> F) : \n    phant K -> injective f -> f 0 = 0 -> {mono f : u / u \\in unit} -> \n  @Field.mixin_of K.\nProof. by move=> _ injf f0 fU u; rewrite -fU unitfE -f0 inj_eq. Qed.\n\nModule Exports.\n\nNotation \"[ 'zmodMixin' 'of' U 'by' <: ]\" := (zmodMixin (Phant U))\n  (at level 0, format \"[ 'zmodMixin'  'of'  U  'by'  <: ]\") : form_scope.\nNotation \"[ 'ringMixin' 'of' R 'by' <: ]\" :=\n  (@ringMixin _ _ _ _ _ _ (@erefl Type R%type) (rrefl _))\n  (at level 0, format \"[ 'ringMixin'  'of'  R  'by'  <: ]\") : form_scope.\nNotation \"[ 'lmodMixin' 'of' U 'by' <: ]\" :=\n  (@lmodMixin _ _ _ _ _ _ _ (@erefl Type U%type) (rrefl _))\n  (at level 0, format \"[ 'lmodMixin'  'of'  U  'by'  <: ]\") : form_scope.\nNotation \"[ 'lalgMixin' 'of' A 'by' <: ]\" :=\n  ((lalgMixin (Phant A) val_inj (rrefl _)) *%R (rrefl _))\n  (at level 0, format \"[ 'lalgMixin'  'of'  A  'by'  <: ]\") : form_scope.\nNotation \"[ 'comRingMixin' 'of' R 'by' <: ]\" :=\n  (comRingMixin (Phant R) val_inj (rrefl _))\n  (at level 0, format \"[ 'comRingMixin'  'of'  R  'by'  <: ]\") : form_scope.\nNotation \"[ 'algMixin' 'of' A 'by' <: ]\" :=\n  (algMixin (Phant A) val_inj (rrefl _) (rrefl _))\n  (at level 0, format \"[ 'algMixin'  'of'  A  'by'  <: ]\") : form_scope.\nNotation \"[ 'unitRingMixin' 'of' R 'by' <: ]\" :=\n  (@unitRingMixin _ _ _ _ _ _ (@erefl Type R%type) (erefl _) (rrefl _))\n  (at level 0, format \"[ 'unitRingMixin'  'of'  R  'by'  <: ]\") : form_scope.\nNotation \"[ 'idomainMixin' 'of' R 'by' <: ]\" :=\n  (idomainMixin (Phant R) val_inj (erefl _) (rrefl _))\n  (at level 0, format \"[ 'idomainMixin'  'of'  R  'by'  <: ]\") : form_scope.\nNotation \"[ 'fieldMixin' 'of' F 'by' <: ]\" :=\n  (fieldMixin (Phant F) val_inj (erefl _) (frefl _))\n  (at level 0, format \"[ 'fieldMixin'  'of'  F  'by'  <: ]\") : form_scope.\n\nEnd Exports.\n\nEnd SubType.\n\nModule Theory.\n\nDefinition addrA := addrA.\nDefinition addrC := addrC.\nDefinition add0r := add0r.\nDefinition addNr := addNr.\nDefinition addr0 := addr0.\nDefinition addrN := addrN.\nDefinition subrr := subrr.\nDefinition addrCA := addrCA.\nDefinition addrAC := addrAC.\nDefinition addrACA := addrACA.\nDefinition addKr := addKr.\nDefinition addNKr := addNKr.\nDefinition addrK := addrK.\nDefinition addrNK := addrNK.\nDefinition subrK := subrK.\nDefinition addrI := @addrI.\nDefinition addIr := @addIr.\nImplicit Arguments addrI [[V] x1 x2].\nImplicit Arguments addIr [[V] x1 x2].\nDefinition opprK := opprK.\nDefinition oppr_inj := @oppr_inj.\nImplicit Arguments oppr_inj [[V] x1 x2].\nDefinition oppr0 := oppr0.\nDefinition oppr_eq0 := oppr_eq0.\nDefinition opprD := opprD.\nDefinition opprB := opprB.\nDefinition subr0 := subr0.\nDefinition sub0r := sub0r.\nDefinition subr_eq := subr_eq.\nDefinition subr_eq0 := subr_eq0.\nDefinition addr_eq0 := addr_eq0.\nDefinition eqr_opp := eqr_opp.\nDefinition eqr_oppLR := eqr_oppLR.\nDefinition sumrN := sumrN.\nDefinition sumrB := sumrB.\nDefinition sumrMnl := sumrMnl.\nDefinition sumrMnr := sumrMnr.\nDefinition sumr_const := sumr_const.\nDefinition mulr0n := mulr0n.\nDefinition mulr1n := mulr1n.\nDefinition mulr2n := mulr2n.\nDefinition mulrS := mulrS.\nDefinition mulrSr := mulrSr.\nDefinition mulrb := mulrb.\nDefinition mul0rn := mul0rn.\nDefinition mulNrn := mulNrn.\nDefinition mulrnDl := mulrnDl.\nDefinition mulrnDr := mulrnDr.\nDefinition mulrnBl := mulrnBl.\nDefinition mulrnBr := mulrnBr.\nDefinition mulrnA := mulrnA.\nDefinition mulrnAC := mulrnAC.\nDefinition mulrA := mulrA.\nDefinition mul1r := mul1r.\nDefinition mulr1 := mulr1.\nDefinition mulrDl := mulrDl.\nDefinition mulrDr := mulrDr.\nDefinition oner_neq0 := oner_neq0.\nDefinition oner_eq0 := oner_eq0.\nDefinition mul0r := mul0r.\nDefinition mulr0 := mulr0.\nDefinition mulrN := mulrN.\nDefinition mulNr := mulNr.\nDefinition mulrNN := mulrNN.\nDefinition mulN1r := mulN1r.\nDefinition mulrN1 := mulrN1.\nDefinition mulr_suml := mulr_suml.\nDefinition mulr_sumr := mulr_sumr.\nDefinition mulrBl := mulrBl.\nDefinition mulrBr := mulrBr.\nDefinition mulrnAl := mulrnAl.\nDefinition mulrnAr := mulrnAr.\nDefinition mulr_natl := mulr_natl.\nDefinition mulr_natr := mulr_natr.\nDefinition natrD := natrD.\nDefinition natrB := natrB.\nDefinition natr_sum := natr_sum.\nDefinition natrM := natrM.\nDefinition natrX := natrX.\nDefinition expr0 := expr0.\nDefinition exprS := exprS.\nDefinition expr1 := expr1.\nDefinition expr2 := expr2.\nDefinition expr0n := expr0n.\nDefinition expr1n := expr1n.\nDefinition exprD := exprD.\nDefinition exprSr := exprSr.\nDefinition commr_sym := commr_sym.\nDefinition commr_refl := commr_refl.\nDefinition commr0 := commr0.\nDefinition commr1 := commr1.\nDefinition commrN := commrN.\nDefinition commrN1 := commrN1.\nDefinition commrD := commrD.\nDefinition commrMn := commrMn.\nDefinition commrM := commrM.\nDefinition commr_nat := commr_nat.\nDefinition commrX := commrX.\nDefinition exprMn_comm := exprMn_comm.\nDefinition commr_sign := commr_sign.\nDefinition exprMn_n := exprMn_n.\nDefinition exprM := exprM.\nDefinition exprAC := exprAC.\nDefinition expr_mod := expr_mod.\nDefinition expr_dvd := expr_dvd.\nDefinition signr_odd := signr_odd.\nDefinition signr_eq0 := signr_eq0.\nDefinition mulr_sign := mulr_sign.\nDefinition signr_addb := signr_addb.\nDefinition signrN := signrN.\nDefinition signrE := signrE.\nDefinition mulr_signM := mulr_signM.\nDefinition exprNn := exprNn.\nDefinition sqrrN := sqrrN.\nDefinition sqrr_sign := sqrr_sign.\nDefinition signrMK := signrMK.\nDefinition mulrI_eq0 := mulrI_eq0.\nDefinition lreg_neq0 := lreg_neq0.\nDefinition mulrI0_lreg := mulrI0_lreg.\nDefinition lregN := lregN.\nDefinition lreg1 := lreg1.\nDefinition lregM := lregM.\nDefinition lregX := lregX.\nDefinition lreg_sign := lreg_sign.\nDefinition lregP {R x} := @lregP R x.\nDefinition mulIr_eq0 := mulIr_eq0.\nDefinition mulIr0_rreg := mulIr0_rreg.\nDefinition rreg_neq0 := rreg_neq0.\nDefinition rregN := rregN.\nDefinition rreg1 := rreg1.\nDefinition rregM := rregM.\nDefinition revrX := revrX.\nDefinition rregX := rregX.\nDefinition rregP {R x} := @rregP R x.\nDefinition exprDn_comm := exprDn_comm.\nDefinition exprBn_comm := exprBn_comm.\nDefinition subrXX_comm := subrXX_comm.\nDefinition exprD1n := exprD1n.\nDefinition subrX1 := subrX1.\nDefinition sqrrD1 := sqrrD1.\nDefinition sqrrB1 := sqrrB1.\nDefinition subr_sqr_1 := subr_sqr_1.\nDefinition charf0 := charf0.\nDefinition charf_prime := charf_prime.\nDefinition mulrn_char := mulrn_char.\nDefinition dvdn_charf := dvdn_charf.\nDefinition charf_eq := charf_eq.\nDefinition bin_lt_charf_0 := bin_lt_charf_0.\nDefinition Frobenius_autE := Frobenius_autE.\nDefinition Frobenius_aut0 := Frobenius_aut0.\nDefinition Frobenius_aut1 := Frobenius_aut1.\nDefinition Frobenius_autD_comm := Frobenius_autD_comm.\nDefinition Frobenius_autMn := Frobenius_autMn.\nDefinition Frobenius_aut_nat := Frobenius_aut_nat.\nDefinition Frobenius_autM_comm := Frobenius_autM_comm.\nDefinition Frobenius_autX := Frobenius_autX.\nDefinition Frobenius_autN := Frobenius_autN.\nDefinition Frobenius_autB_comm := Frobenius_autB_comm.\nDefinition exprNn_char := exprNn_char.\nDefinition addrr_char2 := addrr_char2.\nDefinition oppr_char2 := oppr_char2.\nDefinition addrK_char2 := addrK_char2.\nDefinition addKr_char2 := addKr_char2.\nDefinition prodr_const := prodr_const.\nDefinition mulrC := mulrC.\nDefinition mulrCA := mulrCA.\nDefinition mulrAC := mulrAC.\nDefinition mulrACA := mulrACA.\nDefinition exprMn := exprMn.\nDefinition prodrXl := prodrXl.\nDefinition prodrXr := prodrXr.\nDefinition prodrN := prodrN.\nDefinition prodrMn := prodrMn.\nDefinition exprDn := exprDn.\nDefinition exprBn := exprBn.\nDefinition subrXX := subrXX.\nDefinition sqrrD := sqrrD.\nDefinition sqrrB := sqrrB.\nDefinition subr_sqr := subr_sqr.\nDefinition subr_sqrDB := subr_sqrDB.\nDefinition exprDn_char := exprDn_char.\nDefinition mulrV := mulrV.\nDefinition divrr := divrr.\nDefinition mulVr := mulVr.\nDefinition invr_out := invr_out.\nDefinition unitrP {R x} := @unitrP R x.\nDefinition mulKr := mulKr.\nDefinition mulVKr := mulVKr.\nDefinition mulrK := mulrK.\nDefinition mulrVK := mulrVK.\nDefinition divrK := divrK.\nDefinition mulrI := mulrI.\nDefinition mulIr := mulIr.\nDefinition commrV := commrV.\nDefinition unitrE := unitrE.\nDefinition invrK := invrK.\nDefinition invr_inj := @invr_inj.\nImplicit Arguments invr_inj [[R] x1 x2].\nDefinition unitrV := unitrV.\nDefinition unitr1 := unitr1.\nDefinition invr1 := invr1.\nDefinition divr1 := divr1.\nDefinition div1r := div1r.\nDefinition natr_div := natr_div.\nDefinition unitr0 := unitr0.\nDefinition invr0 := invr0.\nDefinition unitrN1 := unitrN1.\nDefinition unitrN := unitrN.\nDefinition invrN1 := invrN1.\nDefinition invrN := invrN.\nDefinition invr_sign := invr_sign.\nDefinition unitrMl := unitrMl.\nDefinition unitrMr := unitrMr.\nDefinition invrM := invrM.\nDefinition invr_eq0 := invr_eq0.\nDefinition invr_eq1 := invr_eq1.\nDefinition invr_neq0 := invr_neq0.\nDefinition unitrM_comm := unitrM_comm.\nDefinition unitrX := unitrX.\nDefinition unitrX_pos := unitrX_pos.\nDefinition exprVn := exprVn.\nDefinition invr_signM := invr_signM.\nDefinition divr_signM := divr_signM.\nDefinition rpred0D := rpred0D.\nDefinition rpred0 := rpred0.\nDefinition rpredD := rpredD.\nDefinition rpredNr := rpredNr.\nDefinition rpred_sum := rpred_sum.\nDefinition rpredMn := rpredMn.\nDefinition rpredN := rpredN.\nDefinition rpredB := rpredB.\nDefinition rpredMNn := rpredMNn.\nDefinition rpredDr := rpredDr.\nDefinition rpredDl := rpredDl.\nDefinition rpredBr := rpredBr.\nDefinition rpredBl := rpredBl.\nDefinition rpredMsign := rpredMsign.\nDefinition rpred1M := rpred1M.\nDefinition rpred1 := rpred1.\nDefinition rpredM := rpredM.\nDefinition rpred_prod := rpred_prod.\nDefinition rpredX := rpredX.\nDefinition rpred_nat := rpred_nat.\nDefinition rpredN1 := rpredN1.\nDefinition rpred_sign := rpred_sign.\nDefinition rpredZsign := rpredZsign.\nDefinition rpredZnat := rpredZnat.\nDefinition rpredZ := rpredZ.\nDefinition rpredVr := rpredVr.\nDefinition rpredV := rpredV.\nDefinition rpred_div := rpred_div.\nDefinition rpredXN := rpredXN.\nDefinition rpredZeq := rpredZeq.\nDefinition rpredMr := rpredMr.\nDefinition rpredMl := rpredMl.\nDefinition rpred_divr := rpred_divr.\nDefinition rpred_divl := rpred_divl.\nDefinition eq_eval := eq_eval.\nDefinition eval_tsubst := eval_tsubst.\nDefinition eq_holds := eq_holds.\nDefinition holds_fsubst := holds_fsubst.\nDefinition unitrM := unitrM.\nDefinition unitrPr {R x} := @unitrPr R x.\nDefinition expr_div_n := expr_div_n.\nDefinition mulf_eq0 := mulf_eq0.\nDefinition prodf_eq0 := prodf_eq0.\nDefinition prodf_seq_eq0 := prodf_seq_eq0.\nDefinition mulf_neq0 := mulf_neq0.\nDefinition prodf_neq0 := prodf_neq0.\nDefinition prodf_seq_neq0 := prodf_seq_neq0.\nDefinition expf_eq0 := expf_eq0.\nDefinition sqrf_eq0 := sqrf_eq0.\nDefinition expf_neq0 := expf_neq0.\nDefinition natf_neq0 := natf_neq0.\nDefinition eqf_sqr := eqf_sqr.\nDefinition mulfI := mulfI.\nDefinition mulIf := mulIf.\nDefinition sqrf_eq1 := sqrf_eq1.\nDefinition expfS_eq1 := expfS_eq1.\nDefinition unitfE := unitfE.\nDefinition mulVf := mulVf.\nDefinition mulfV := mulfV.\nDefinition divff := divff.\nDefinition mulKf := mulKf.\nDefinition mulVKf := mulVKf.\nDefinition mulfK := mulfK.\nDefinition mulfVK := mulfVK.\nDefinition divfK := divfK.\nDefinition invfM := invfM.\nDefinition prodf_inv := prodf_inv.\nDefinition addf_div := addf_div.\nDefinition mulf_div := mulf_div.\nDefinition natf0_char := natf0_char.\nDefinition charf'_nat := charf'_nat.\nDefinition charf0P := charf0P.\nDefinition char0_natf_div := char0_natf_div.\nDefinition fpredMr := fpredMr.\nDefinition fpredMl := fpredMl.\nDefinition fpred_divr := fpred_divr.\nDefinition fpred_divl := fpred_divl.\nDefinition satP {F e f} := @satP F e f.\nDefinition eq_sat := eq_sat.\nDefinition solP {F n f} := @solP F n f.\nDefinition eq_sol := eq_sol.\nDefinition size_sol := size_sol.\nDefinition solve_monicpoly := solve_monicpoly.\nDefinition raddf0 := raddf0.\nDefinition raddf_eq0 := raddf_eq0.\nDefinition raddfN := raddfN.\nDefinition raddfD := raddfD.\nDefinition raddfB := raddfB.\nDefinition raddf_sum := raddf_sum.\nDefinition raddfMn := raddfMn.\nDefinition raddfMNn := raddfMNn.\nDefinition raddfMnat := raddfMnat.\nDefinition raddfMsign := raddfMsign.\nDefinition can2_additive := can2_additive.\nDefinition bij_additive := bij_additive.\nDefinition rmorph0 := rmorph0.\nDefinition rmorphN := rmorphN.\nDefinition rmorphD := rmorphD.\nDefinition rmorphB := rmorphB.\nDefinition rmorph_sum := rmorph_sum.\nDefinition rmorphMn := rmorphMn.\nDefinition rmorphMNn := rmorphMNn.\nDefinition rmorphismP := rmorphismP.\nDefinition rmorphismMP := rmorphismMP.\nDefinition rmorph1 := rmorph1.\nDefinition rmorph_eq1 := rmorph_eq1.\nDefinition rmorphM := rmorphM.\nDefinition rmorphMsign := rmorphMsign.\nDefinition rmorph_nat := rmorph_nat.\nDefinition rmorph_eq_nat := rmorph_eq_nat.\nDefinition rmorph_prod := rmorph_prod.\nDefinition rmorphX := rmorphX.\nDefinition rmorphN1 := rmorphN1.\nDefinition rmorph_sign := rmorph_sign.\nDefinition rmorph_char := rmorph_char.\nDefinition can2_rmorphism := can2_rmorphism.\nDefinition bij_rmorphism := bij_rmorphism.\nDefinition rmorph_comm := rmorph_comm.\nDefinition rmorph_unit := rmorph_unit.\nDefinition rmorphV := rmorphV.\nDefinition rmorph_div := rmorph_div.\nDefinition fmorph_eq0 := fmorph_eq0.\nDefinition fmorph_inj := @fmorph_inj.\nImplicit Arguments fmorph_inj [[F] [R] x1 x2].\nDefinition fmorph_eq1 := fmorph_eq1.\nDefinition fmorph_char := fmorph_char.\nDefinition fmorph_unit := fmorph_unit.\nDefinition fmorphV := fmorphV.\nDefinition fmorph_div := fmorph_div.\nDefinition scalerA := scalerA.\nDefinition scale1r := scale1r.\nDefinition scalerDr := scalerDr.\nDefinition scalerDl := scalerDl.\nDefinition scaler0 := scaler0.\nDefinition scale0r := scale0r.\nDefinition scaleNr := scaleNr.\nDefinition scaleN1r := scaleN1r.\nDefinition scalerN := scalerN.\nDefinition scalerBl := scalerBl.\nDefinition scalerBr := scalerBr.\nDefinition scaler_nat := scaler_nat.\nDefinition scalerMnl := scalerMnl.\nDefinition scalerMnr := scalerMnr.\nDefinition scaler_suml := scaler_suml.\nDefinition scaler_sumr := scaler_sumr.\nDefinition scaler_eq0 := scaler_eq0.\nDefinition scalerK := scalerK.\nDefinition scalerKV := scalerKV.\nDefinition scalerI := scalerI.\nDefinition scalerAl := scalerAl.\nDefinition mulr_algl := mulr_algl.\nDefinition scaler_sign := scaler_sign.\nDefinition signrZK := signrZK.\nDefinition scalerCA := scalerCA.\nDefinition scalerAr := scalerAr.\nDefinition mulr_algr := mulr_algr.\nDefinition exprZn := exprZn.\nDefinition scaler_prodl := scaler_prodl.\nDefinition scaler_prodr := scaler_prodr.\nDefinition scaler_prod := scaler_prod.\nDefinition scaler_injl := scaler_injl.\nDefinition scaler_unit := scaler_unit.\nDefinition invrZ := invrZ.\nDefinition raddfZnat := raddfZnat.\nDefinition raddfZsign := raddfZsign.\nDefinition in_algE := in_algE.\nDefinition linear0 := linear0.\nDefinition linearN := linearN.\nDefinition linearD := linearD.\nDefinition linearB := linearB.\nDefinition linear_sum := linear_sum.\nDefinition linearMn := linearMn.\nDefinition linearMNn := linearMNn.\nDefinition linearP := linearP.\nDefinition linearZ_LR := linearZ_LR.\nDefinition linearZ := linearZ.\nDefinition linearPZ := linearPZ.\nDefinition linearZZ := linearZZ.\nDefinition scalarP := scalarP.\nDefinition scalarZ := scalarZ.\nDefinition can2_linear := can2_linear.\nDefinition bij_linear := bij_linear.\nDefinition rmorph_alg := rmorph_alg.\nDefinition lrmorphismP := lrmorphismP.\nDefinition can2_lrmorphism := can2_lrmorphism.\nDefinition bij_lrmorphism := bij_lrmorphism.\n\nNotation null_fun V := (null_fun V) (only parsing).\nNotation in_alg A := (in_alg_loc A).\n\nEnd Theory.\n\nNotation in_alg A := (in_alg_loc A).\n\nEnd GRing.\n\nExport Zmodule.Exports Ring.Exports Lmodule.Exports Lalgebra.Exports.\nExport Additive.Exports RMorphism.Exports Linear.Exports LRMorphism.Exports.\nExport ComRing.Exports Algebra.Exports UnitRing.Exports UnitAlgebra.Exports.\nExport ComUnitRing.Exports IntegralDomain.Exports Field.Exports.\nExport DecidableField.Exports ClosedField.Exports.\nExport Pred.Exports SubType.Exports.\nNotation QEdecFieldMixin := QEdecFieldMixin.\n\nNotation \"0\" := (zero _) : ring_scope.\nNotation \"-%R\" := (@opp _) : ring_scope.\nNotation \"- x\" := (opp x) : ring_scope.\nNotation \"+%R\" := (@add _).\nNotation \"x + y\" := (add x y) : ring_scope.\nNotation \"x - y\" := (add x (- y)) : ring_scope.\nNotation \"x *+ n\" := (natmul x n) : ring_scope.\nNotation \"x *- n\" := (opp (x *+ n)) : ring_scope.\nNotation \"s `_ i\" := (seq.nth 0%R s%R i) : ring_scope.\nNotation support := 0.-support.\n\nNotation \"1\" := (one _) : ring_scope.\nNotation \"- 1\" := (opp 1) : ring_scope.\n\nNotation \"n %:R\" := (natmul 1 n) : ring_scope.\nNotation \"[ 'char' R ]\" := (char (Phant R)) : ring_scope.\nNotation Frobenius_aut chRp := (Frobenius_aut chRp).\nNotation \"*%R\" := (@mul _).\nNotation \"x * y\" := (mul x y) : ring_scope.\nNotation \"x ^+ n\" := (exp x n) : ring_scope.\nNotation \"x ^-1\" := (inv x) : ring_scope.\nNotation \"x ^- n\" := (inv (x ^+ n)) : ring_scope.\nNotation \"x / y\" := (mul x y^-1) : ring_scope.\n\nNotation \"*:%R\" := (@scale _ _).\nNotation \"a *: m\" := (scale a m) : ring_scope.\nNotation \"k %:A\" := (scale k 1) : ring_scope.\nNotation \"\\0\" := (null_fun _) : ring_scope.\nNotation \"f \\+ g\" := (add_fun_head tt f g) : ring_scope.\nNotation \"f \\- g\" := (sub_fun_head tt f g) : ring_scope.\nNotation \"a \\*: f\" := (scale_fun_head tt a f) : ring_scope.\nNotation \"x \\*o f\" := (mull_fun_head tt x f) : ring_scope.\nNotation \"x \\o* f\" := (mulr_fun_head tt x f) : ring_scope.\n\nNotation \"\\sum_ ( <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(<- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r ) F\" :=\n  (\\big[+%R/0%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i | P ) F\" :=\n  (\\big[+%R/0%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\sum_ i F\" :=\n  (\\big[+%R/0%R]_i F%R) : ring_scope.\nNotation \"\\sum_ ( i : t | P ) F\" :=\n  (\\big[+%R/0%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i : t ) F\" :=\n  (\\big[+%R/0%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i < n ) F\" :=\n  (\\big[+%R/0%R]_(i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i 'in' A | P ) F\" :=\n  (\\big[+%R/0%R]_(i in A | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i 'in' A ) F\" :=\n  (\\big[+%R/0%R]_(i in A) F%R) : ring_scope.\n\nNotation \"\\prod_ ( <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(<- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[*%R/1%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[*%R/1%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[*%R/1%R]_i F%R) : ring_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[*%R/1%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[*%R/1%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[*%R/1%R]_(i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i 'in' A | P ) F\" :=\n  (\\big[*%R/1%R]_(i in A | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i 'in' A ) F\" :=\n  (\\big[*%R/1%R]_(i in A) F%R) : ring_scope.\n\nCanonical add_monoid.\nCanonical add_comoid.\nCanonical mul_monoid.\nCanonical mul_comoid.\nCanonical muloid.\nCanonical addoid.\n\nCanonical locked_additive.\nCanonical locked_rmorphism.\nCanonical locked_linear.\nCanonical locked_lrmorphism.\nCanonical idfun_additive.\nCanonical idfun_rmorphism.\nCanonical idfun_linear.\nCanonical idfun_lrmorphism.\nCanonical comp_additive.\nCanonical comp_rmorphism.\nCanonical comp_linear.\nCanonical comp_lrmorphism.\nCanonical opp_additive.\nCanonical opp_linear.\nCanonical scale_additive.\nCanonical scale_linear.\nCanonical null_fun_additive.\nCanonical null_fun_linear.\nCanonical scale_fun_additive.\nCanonical scale_fun_linear.\nCanonical add_fun_additive.\nCanonical add_fun_linear.\nCanonical sub_fun_additive.\nCanonical sub_fun_linear.\nCanonical mull_fun_additive.\nCanonical mull_fun_linear.\nCanonical mulr_fun_additive.\nCanonical mulr_fun_linear.\nCanonical Frobenius_aut_additive.\nCanonical Frobenius_aut_rmorphism.\nCanonical in_alg_additive.\nCanonical in_alg_rmorphism.\n\nNotation \"R ^c\" := (converse R) (at level 2, format \"R ^c\") : type_scope.\nCanonical converse_eqType.\nCanonical converse_choiceType.\nCanonical converse_zmodType.\nCanonical converse_ringType.\nCanonical converse_unitRingType.\n\nNotation \"R ^o\" := (regular R) (at level 2, format \"R ^o\") : type_scope.\nCanonical regular_eqType.\nCanonical regular_choiceType.\nCanonical regular_zmodType.\nCanonical regular_ringType.\nCanonical regular_lmodType.\nCanonical regular_lalgType.\nCanonical regular_comRingType.\nCanonical regular_algType.\nCanonical regular_unitRingType.\nCanonical regular_comUnitRingType.\nCanonical regular_unitAlgType.\nCanonical regular_idomainType.\nCanonical regular_fieldType.\n\nCanonical unit_keyed.\nCanonical unit_opprPred.\nCanonical unit_mulrPred.\nCanonical unit_smulrPred.\nCanonical unit_divrPred.\nCanonical unit_sdivrPred.\n\nBind Scope term_scope with term.\nBind Scope term_scope with formula.\n\nNotation \"''X_' i\" := (Var _ i) : term_scope.\nNotation \"n %:R\" := (NatConst _ n) : term_scope.\nNotation \"0\" := 0%:R%T : term_scope.\nNotation \"1\" := 1%:R%T : term_scope.\nNotation \"x %:T\" := (Const x) : term_scope.\nInfix \"+\" := Add : term_scope.\nNotation \"- t\" := (Opp t) : term_scope.\nNotation \"t - u\" := (Add t (- u)) : term_scope.\nInfix \"*\" := Mul : term_scope.\nInfix \"*+\" := NatMul : term_scope.\nNotation \"t ^-1\" := (Inv t) : term_scope.\nNotation \"t / u\" := (Mul t u^-1) : term_scope.\nInfix \"^+\" := Exp : term_scope.\nInfix \"==\" := Equal : term_scope.\nNotation \"x != y\" := (GRing.Not (x == y)) : term_scope.\nInfix \"/\\\" := And : term_scope.\nInfix \"\\/\" := Or : term_scope.\nInfix \"==>\" := Implies : term_scope.\nNotation \"~ f\" := (Not f) : term_scope.\nNotation \"''exists' ''X_' i , f\" := (Exists i f) : term_scope.\nNotation \"''forall' ''X_' i , f\" := (Forall i f) : term_scope.\n\n(* Lifting Structure from the codomain of finfuns. *)\nSection FinFunZmod.\n\nVariable (aT : finType) (rT : zmodType).\nImplicit Types f g : {ffun aT -> rT}.\n\nDefinition ffun_zero := [ffun a : aT => (0 : rT)].\nDefinition ffun_opp f := [ffun a => - f a].\nDefinition ffun_add f g := [ffun a => f a + g a].\n\nFact ffun_addA : associative ffun_add.\nProof. by move=> f1 f2 f3; apply/ffunP=> a; rewrite !ffunE addrA. Qed.\nFact ffun_addC : commutative ffun_add.\nProof. by move=> f1 f2; apply/ffunP=> a; rewrite !ffunE addrC. Qed.\nFact ffun_add0 : left_id ffun_zero ffun_add.\nProof. by move=> f; apply/ffunP=> a; rewrite !ffunE add0r. Qed.\nFact ffun_addN : left_inverse ffun_zero ffun_opp ffun_add.\nProof. by move=> f; apply/ffunP=> a; rewrite !ffunE addNr. Qed.\n\nDefinition ffun_zmodMixin :=\n  Zmodule.Mixin ffun_addA ffun_addC ffun_add0 ffun_addN.\nCanonical ffun_zmodType := Eval hnf in ZmodType _ ffun_zmodMixin.\n\nSection Sum.\n\nVariables (I : Type) (r : seq I) (P : pred I) (F : I -> {ffun aT -> rT}).\n\nLemma sum_ffunE x : (\\sum_(i <- r | P i) F i) x = \\sum_(i <- r | P i) F i x.\nProof. by elim/big_rec2: _ => // [|i _ y _ <-]; rewrite !ffunE. Qed.\n\nLemma sum_ffun :\n  \\sum_(i <- r | P i) F i = [ffun x => \\sum_(i <- r | P i) F i x].\nProof. by apply/ffunP=> i; rewrite sum_ffunE ffunE. Qed.\n\nEnd Sum.\n\nLemma ffunMnE f n x : (f *+ n) x = f x *+ n.\nProof. by rewrite -[n]card_ord -!sumr_const sum_ffunE. Qed.\n\nEnd FinFunZmod.\nCanonical exp_zmodType (M : zmodType) n := [zmodType of M ^ n].\n\nSection FinFunRing.\n\n(* As rings require 1 != 0 in order to lift a ring structure over finfuns     *)\n(* we need evidence that the domain is non-empty.                             *)\n\nVariable (aT : finType) (R : ringType) (a : aT).\n\nDefinition ffun_one : {ffun aT -> R} := [ffun => 1].\nDefinition ffun_mul (f g : {ffun aT -> R}) := [ffun x => f x * g x]. \n\nFact ffun_mulA : associative ffun_mul.\nProof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrA. Qed.\nFact ffun_mul_1l : left_id ffun_one ffun_mul.\nProof. by move=> f; apply/ffunP=> i; rewrite !ffunE mul1r. Qed.\nFact ffun_mul_1r : right_id ffun_one ffun_mul.\nProof. by move=> f; apply/ffunP=> i; rewrite !ffunE mulr1. Qed.\nFact ffun_mul_addl :  left_distributive ffun_mul (@ffun_add _ _).\nProof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrDl. Qed.\nFact ffun_mul_addr :  right_distributive ffun_mul (@ffun_add _ _).\nProof. by move=> f1 f2 f3; apply/ffunP=> i; rewrite !ffunE mulrDr. Qed.\nFact ffun1_nonzero : ffun_one != 0.\nProof. by apply/eqP => /ffunP/(_ a)/eqP; rewrite !ffunE oner_eq0. Qed.\n\nDefinition ffun_ringMixin :=\n  RingMixin ffun_mulA ffun_mul_1l ffun_mul_1r ffun_mul_addl ffun_mul_addr\n            ffun1_nonzero.\nDefinition ffun_ringType :=\n  Eval hnf in RingType {ffun aT -> R} ffun_ringMixin.\n\nEnd FinFunRing.\n\nSection FinFunComRing.\n\nVariable (aT : finType) (R : comRingType) (a : aT).\n\nFact ffun_mulC : commutative (@ffun_mul aT R).\nProof. by move=> f1 f2; apply/ffunP=> i; rewrite !ffunE mulrC. Qed.\n\nDefinition ffun_comRingType :=\n  Eval hnf in ComRingType (ffun_ringType R a) ffun_mulC.\n\nEnd FinFunComRing.\n\nSection FinFunLmod.\n\nVariable (R : ringType) (aT : finType) (rT : lmodType R).\n\nImplicit Types f g : {ffun aT -> rT}.\n\nDefinition ffun_scale k f := [ffun a => k *: f a].\n\nFact ffun_scaleA k1 k2 f : \n  ffun_scale k1 (ffun_scale k2 f) = ffun_scale (k1 * k2) f.\nProof. by apply/ffunP=> a; rewrite !ffunE scalerA. Qed.\nFact ffun_scale1 : left_id 1 ffun_scale.\nProof. by move=> f; apply/ffunP=> a; rewrite !ffunE scale1r. Qed.\nFact ffun_scale_addr k : {morph (ffun_scale k) : x y / x + y}.\nProof. by move=> f g; apply/ffunP=> a; rewrite !ffunE scalerDr. Qed.\nFact ffun_scale_addl u : {morph (ffun_scale)^~ u : k1 k2 / k1 + k2}.\nProof. by move=> k1 k2; apply/ffunP=> a; rewrite !ffunE scalerDl. Qed.\n\nDefinition ffun_lmodMixin := \n  LmodMixin ffun_scaleA ffun_scale1 ffun_scale_addr ffun_scale_addl.\nCanonical ffun_lmodType :=\n  Eval hnf in LmodType R {ffun aT -> rT} ffun_lmodMixin.\n\nEnd FinFunLmod.\nCanonical exp_lmodType (R : ringType) (M : lmodType R) n :=\n  [lmodType R of M ^ n].\n\n(* External direct product. *)\nSection PairZmod.\n\nVariables M1 M2 : zmodType.\n\nDefinition opp_pair (x : M1 * M2) := (- x.1, - x.2).\nDefinition add_pair (x y : M1 * M2) := (x.1 + y.1, x.2 + y.2).\n\nFact pair_addA : associative add_pair.\nProof. by move=> x y z; congr (_, _); apply: addrA. Qed.\n\nFact pair_addC : commutative add_pair.\nProof. by move=> x y; congr (_, _); apply: addrC. Qed.\n\nFact pair_add0 : left_id (0, 0) add_pair.\nProof. by case=> x1 x2; congr (_, _); apply: add0r. Qed.\n\nFact pair_addN : left_inverse (0, 0) opp_pair add_pair.\nProof. by move=> x; congr (_, _); apply: addNr. Qed.\n\nDefinition pair_zmodMixin := ZmodMixin pair_addA pair_addC pair_add0 pair_addN.\nCanonical pair_zmodType := Eval hnf in ZmodType (M1 * M2) pair_zmodMixin.\n\nEnd PairZmod.\n\nSection PairRing.\n\nVariables R1 R2 : ringType.\n\nDefinition mul_pair (x y : R1 * R2) := (x.1 * y.1, x.2 * y.2).\n\nFact pair_mulA : associative mul_pair.\nProof. by move=> x y z; congr (_, _); apply: mulrA. Qed.\n\nFact pair_mul1l : left_id (1, 1) mul_pair.\nProof. by case=> x1 x2; congr (_, _); apply: mul1r. Qed.\n\nFact pair_mul1r : right_id (1, 1) mul_pair.\nProof. by case=> x1 x2; congr (_, _); apply: mulr1. Qed.\n\nFact pair_mulDl : left_distributive mul_pair +%R.\nProof. by move=> x y z; congr (_, _); apply: mulrDl. Qed.\n\nFact pair_mulDr : right_distributive mul_pair +%R.\nProof. by move=> x y z; congr (_, _); apply: mulrDr. Qed.\n\nFact pair_one_neq0 : (1, 1) != 0 :> R1 * R2.\nProof. by rewrite xpair_eqE oner_eq0. Qed.\n\nDefinition pair_ringMixin :=\n  RingMixin pair_mulA pair_mul1l pair_mul1r pair_mulDl pair_mulDr pair_one_neq0.\nCanonical pair_ringType := Eval hnf in RingType (R1 * R2) pair_ringMixin.\n\nEnd PairRing.\n\nSection PairComRing.\n\nVariables R1 R2 : comRingType.\n\nFact pair_mulC : commutative (@mul_pair R1 R2).\nProof. by move=> x y; congr (_, _); apply: mulrC. Qed.\n\nCanonical pair_comRingType := Eval hnf in ComRingType (R1 * R2) pair_mulC.\n\nEnd PairComRing.\n\nSection PairLmod.\n\nVariables (R : ringType) (V1 V2 : lmodType R).\n\nDefinition scale_pair a (v : V1 * V2) : V1 * V2 := (a *: v.1, a *: v.2).\n\nFact pair_scaleA a b u : scale_pair a (scale_pair b u) = scale_pair (a * b) u.\nProof. by congr (_, _); apply: scalerA. Qed.\n\nFact pair_scale1 u : scale_pair 1 u = u.\nProof. by case: u => u1 u2; congr (_, _); apply: scale1r. Qed.\n\nFact pair_scaleDr : right_distributive scale_pair +%R.\nProof. by move=> a u v; congr (_, _); apply: scalerDr. Qed.\n\nFact pair_scaleDl u : {morph scale_pair^~ u: a b / a + b}.\nProof. by move=> a b; congr (_, _); apply: scalerDl. Qed.\n\nDefinition pair_lmodMixin :=\n  LmodMixin pair_scaleA pair_scale1 pair_scaleDr pair_scaleDl.\nCanonical pair_lmodType := Eval hnf in LmodType R (V1 * V2) pair_lmodMixin.\n\nEnd PairLmod.\n\nSection PairLalg.\n\nVariables (R : ringType) (A1 A2 : lalgType R).\n\nFact pair_scaleAl a (u v : A1 * A2) : a *: (u * v) = (a *: u) * v.\nProof. by congr (_, _); apply: scalerAl. Qed.\nCanonical pair_lalgType :=  Eval hnf in LalgType R (A1 * A2) pair_scaleAl.\n\nEnd PairLalg.\n\nSection PairAlg.\n\nVariables (R : comRingType) (A1 A2 : algType R).\n\nFact pair_scaleAr a (u v : A1 * A2) : a *: (u * v) = u * (a *: v).\nProof. by congr (_, _); apply: scalerAr. Qed.\nCanonical pair_algType :=  Eval hnf in AlgType R (A1 * A2) pair_scaleAr.\n\nEnd PairAlg.\n\nSection PairUnitRing.\n\nVariables R1 R2 : unitRingType.\n\nDefinition pair_unitr :=\n  [qualify a x : R1 * R2 | (x.1 \\is a GRing.unit) && (x.2 \\is a GRing.unit)].\nDefinition pair_invr x :=\n  if x \\is a pair_unitr then (x.1^-1, x.2^-1) else x.\n\nLemma pair_mulVl : {in pair_unitr, left_inverse 1 pair_invr *%R}.\nProof.\nrewrite /pair_invr=> x; case: ifP => // /andP[Ux1 Ux2] _.\nby congr (_, _); apply: mulVr.\nQed.\n\nLemma pair_mulVr : {in pair_unitr, right_inverse 1 pair_invr *%R}.\nProof.\nrewrite /pair_invr=> x; case: ifP => // /andP[Ux1 Ux2] _.\nby congr (_, _); apply: mulrV.\nQed.\n\nLemma pair_unitP x y : y * x = 1 /\\ x * y = 1 -> x \\is a pair_unitr.\nProof.\ncase=> [[y1x y2x] [x1y x2y]]; apply/andP.\nby split; apply/unitrP; [exists y.1 | exists y.2].\nQed.\n\nLemma pair_invr_out : {in [predC pair_unitr], pair_invr =1 id}.\nProof. by rewrite /pair_invr => x /negPf/= ->. Qed.\n\nDefinition pair_unitRingMixin :=\n  UnitRingMixin pair_mulVl pair_mulVr pair_unitP pair_invr_out.\nCanonical pair_unitRingType :=\n  Eval hnf in UnitRingType (R1 * R2) pair_unitRingMixin.\n\nEnd PairUnitRing.\n\nCanonical pair_comUnitRingType (R1 R2 : comUnitRingType) :=\n  Eval hnf in [comUnitRingType of R1 * R2].\n\nCanonical pair_unitAlgType (R : comUnitRingType) (A1 A2 : unitAlgType R) :=\n  Eval hnf in [unitAlgType R of A1 * A2].\n\n(* begin hide *)\n(* Testing subtype hierarchy\nSection Test0.\n\nVariables (T : choiceType) (S : predPredType T).\n\nInductive B := mkB x & x \\in S.\nDefinition vB u := let: mkB x _ := u in x.\n\nCanonical B_subType := [subType for vB].\nDefinition B_eqMixin := [eqMixin of B by <:].\nCanonical B_eqType := EqType B B_eqMixin.\nDefinition B_choiceMixin := [choiceMixin of B by <:].\nCanonical B_choiceType := ChoiceType B B_choiceMixin.\n\nEnd Test0.\n\nSection Test1.\n\nVariables (R : unitRingType) (S : pred R).\nVariables (ringS : divringPred S) (kS : keyed_pred ringS).\n\nDefinition B_zmodMixin := [zmodMixin of B kS by <:].\nCanonical B_zmodType := ZmodType (B kS) B_zmodMixin.\nDefinition B_ringMixin := [ringMixin of B kS by <:].\nCanonical B_ringType := RingType (B kS) B_ringMixin.\nDefinition B_unitRingMixin := [unitRingMixin of B kS by <:].\nCanonical B_unitRingType := UnitRingType (B kS) B_unitRingMixin.\n\nEnd Test1.\n\nSection Test2.\n\nVariables (R : comUnitRingType) (A : unitAlgType R) (S : pred A).\nVariables (algS : divalgPred S) (kS : keyed_pred algS).\n\nDefinition B_lmodMixin := [lmodMixin of B kS by <:].\nCanonical B_lmodType := LmodType R (B kS) B_lmodMixin.\nDefinition B_lalgMixin := [lalgMixin of B kS by <:].\nCanonical B_lalgType := LalgType R (B kS) B_lalgMixin.\nDefinition B_algMixin := [algMixin of B kS by <:].\nCanonical B_algType := AlgType R (B kS) B_algMixin.\nCanonical B_unitAlgType := [unitAlgType R of B kS].\n\nEnd Test2.\n\nSection Test3.\n\nVariables (F : fieldType) (S : pred F).\nVariables (ringS : divringPred S) (kS : keyed_pred ringS).\n\nDefinition B_comRingMixin := [comRingMixin of B kS by <:].\nCanonical B_comRingType := ComRingType (B kS) B_comRingMixin.\nCanonical B_comUnitRingType := [comUnitRingType of B kS].\nDefinition B_idomainMixin := [idomainMixin of B kS by <:].\nCanonical B_idomainType := IdomainType (B kS) B_idomainMixin.\nDefinition B_fieldMixin := [fieldMixin of B kS by <:].\nCanonical B_fieldType := FieldType (B kS) B_fieldMixin.\n\nEnd Test3.\n\n*)\n(* end hide *)\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect1.4_v8.3/theories/ssralg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7001445171324804}}
{"text": "Require Import HoTT.\nRequire Import UnivalenceAxiom.\n\nFrom GCTT Require Import finite_types.\n\nSection Fin_Transpose.\n  (** Defining transpositions. [fin_transpose x y] is the permutation that swaps x and y  *)\n  Definition fin_transpose {n : nat} (x y : fintype n)\n  : fintype n <~> fintype n.\n  Proof.\n    induction n.\n    - destruct x.\n    - destruct y as [y | []].\n      + destruct x as [x | []].\n        * exact (IHn x y +E 1).\n        * exact (fin_transpose_last_with n (inl y)).\n      + exact (fin_transpose_last_with n x).\n  Defined.\n\n  Definition fin_transpose_same_is_id {n : nat} (x : fintype n) :\n    fin_transpose x x == idmap.\n  Proof.\n    intro i.\n    induction n.\n    { destruct x. }\n    destruct x as [x | []].\n    - simpl. destruct i as [i | []].\n      + apply (ap inl). apply IHn.\n      + reflexivity.\n    - simpl. apply fin_transpose_last_with_last_other.\n  Defined.\n\n  Definition fin_transpose_invol {n : nat} (x y : fintype n) :\n    fin_transpose x y o fin_transpose x y == idmap.\n  Proof.\n    induction n.\n    {destruct x. }\n    intro i. ev_equiv.\n    destruct y as [y | []].\n    - destruct x as [x | []].\n      + simpl. destruct i as [i | []].\n        { simpl. apply (ap inl). apply IHn. }\n        reflexivity.\n      + simpl. apply fin_transpose_last_with_invol.\n    - simpl. apply fin_transpose_last_with_invol.\n  Defined.\n\n  Definition fin_transpose_sym {n : nat} (x y : fintype n) :\n    fin_transpose x y == fin_transpose y x.\n  Proof.\n    induction n.\n    { destruct x. }\n    intro i.\n    destruct y as [y | []]; destruct x as [x | []]; try reflexivity.\n    - simpl. destruct i as [i | []].\n      + apply (ap inl). apply IHn.\n      + reflexivity.\n  Defined.\n\n  Definition fin_transpose_beta_r {n : nat} (x y : fintype n) :\n    fin_transpose x y y = x.\n  Proof.\n    induction n.\n    { destruct x. }\n    destruct y as [y | []]; destruct x as [x | []]; try (apply fin_transpose_last_with_last).\n    - simpl. apply (ap inl). apply IHn.\n    - simpl. apply fin_transpose_last_with_with.\n  Defined.\n\n  Definition fin_transpose_beta_l {n : nat} (x y : fintype n) :\n    fin_transpose x y x = y.\n  Proof.\n    refine (fin_transpose_sym x y x @ _).\n    apply fin_transpose_beta_r.\n  Defined.\n\n  Definition fin_transpose_other {n : nat} (x y : fintype n) (i : fintype n):\n    (i <> x) -> (i <> y) -> fin_transpose x y i = i.\n  Proof.\n    intros n_x n_y.\n    induction n.\n    { destruct x.  }\n    destruct y as [y | []].\n    - destruct x as [x | []].\n      + simpl. destruct i as [i | []].\n        * apply (ap inl). apply IHn.\n          { intro p. apply n_x. exact (ap inl p). }\n          { intro p. apply n_y. exact (ap inl p). }\n        * reflexivity.\n      + simpl. destruct i as [i | []].\n        * apply fin_transpose_last_with_rest.\n          intro p. apply n_y. exact p^.\n        * destruct (n_x idpath).\n    - simpl. destruct i as [i | []].\n      + apply fin_transpose_last_with_rest.\n        intro p. apply n_x. exact p^.\n      + destruct (n_y idpath).\n  Defined.\n\n  (** either i = x, i = y, or equal to neither *)\n  Definition decompose_fin_n {n : nat} (x y : fintype n) (i : fintype n) :\n    (i = x) + (i = y) + ((i <> x) * (i <> y)).\n  Proof.\n    destruct (decidablepaths_fin n i x).\n    - exact (inl (inl p)).\n    - destruct (decidablepaths_fin n i y).\n      + apply inl. exact (inr p).\n      + apply inr. exact (n0, n1).\n  Qed.    \n\n  Definition natural_fin_transpose {n : nat} (x y : fintype n) (e : fintype n <~> fintype n) :\n    e o (fin_transpose x y) == fin_transpose (e x) (e y) o e.\n  Proof.\n    intro i. ev_equiv.\n    destruct (decompose_fin_n x y i) as [[p | p] |[n_x n_y] ].\n    - rewrite p.\n      rewrite fin_transpose_beta_l.\n      apply inverse. apply fin_transpose_beta_l.\n    - rewrite p.\n      rewrite fin_transpose_beta_r.\n      apply inverse. apply fin_transpose_beta_r.\n    - rewrite (fin_transpose_other x y i n_x n_y).\n      apply inverse. apply fin_transpose_other.\n      + intro p. apply n_x. apply (equiv_inj e p).\n      + intro p. apply n_y. apply (equiv_inj e p).\n  Qed.\n\n  Definition fin_transpose_eta {n : nat} (x y : fintype n) (e : fintype n -> fintype n) :\n    (e x = y) -> (e y = x) -> (forall i : fintype n, i <> x -> i <> y -> e i = i) ->\n    fin_transpose x y == e.\n  Proof.\n    intros p q neq.\n    intro i.\n    destruct (decidablepaths_fin n i x) as [eq_x | neq_x].\n    - rewrite eq_x.\n      rewrite p.\n      apply fin_transpose_beta_l.\n    - destruct (decidablepaths_fin n i y) as [eq_y | neq_y].\n      + rewrite eq_y.  rewrite q.\n        apply fin_transpose_beta_r.\n      + rewrite (neq i neq_x neq_y).\n        apply (fin_transpose_other _ _ _ neq_x neq_y).\n  Qed.\n  \nEnd Fin_Transpose.\n\nSection Sym2.\n  (** The permutations of two letters is the group of two elements.  *)\n  Definition sym2_fixlast (σ : fintype 2 <~> fintype 2) :\n    (σ (inr tt) = inr tt) -> σ == equiv_idmap.\n  Proof.\n    intro p.\n    intros [[[] | []] | []]; simpl.\n    - recall (σ ((inl (inr tt)))) as x eqn:q.\n      rewrite q.\n      destruct x as [[[] | []] | []].\n      + reflexivity.\n      + destruct (inr_ne_inl tt (inr tt) (equiv_inj σ (p @ q^))). (* absurd case *)\n    - exact p.\n  Qed.\n\n  Definition twist2 : fintype 2 <~> fintype 2 :=\n    fin_transpose (n := 2) (inl (inr tt)) (inr tt).\n\n  Definition twist2_inv : equiv_inverse twist2 = twist2.\n  Proof.\n    apply path_equiv. reflexivity.\n  Qed.\n\n  Definition sym2_notfixlast (σ : fintype 2 <~> fintype 2) :\n    (σ (inr tt) = inl (inr tt)) -> σ == twist2.\n  Proof.\n    intro p.\n    intros [[[] | []] | []]; simpl.\n    - recall (σ ((inl (inr tt)))) as x eqn:q.\n      rewrite q.\n      destruct x as [[[] | []] | []].\n      + destruct (inr_ne_inl tt (inr tt) (equiv_inj σ (p @ q^))). (* absurd case *)\n      + reflexivity.\n    - exact p.\n  Qed.\n\n  Definition symm_sym2 (σ1 σ2 : fintype 2 <~> fintype 2) :\n    σ1 oE σ2 = σ2 oE σ1.\n  Proof.\n    recall (σ1 (inr tt)) as x eqn:p.\n    destruct x as [[[] | []] | []].\n    - rewrite (path_equiv (path_forall _ _ (sym2_notfixlast σ1 p))).\n      recall (σ2 (inr tt)) as y eqn:q.\n      destruct y as [[[] | []] | []].\n      + rewrite (path_equiv (path_forall _ _ (sym2_notfixlast σ2 q))).\n        reflexivity.\n      + rewrite (path_equiv (path_forall _ _ (sym2_fixlast σ2 q))).\n        rewrite ecompose_e1. rewrite ecompose_1e. reflexivity.\n    - rewrite (path_equiv (path_forall _ _ (sym2_fixlast σ1 p))).\n      rewrite ecompose_e1. rewrite ecompose_1e. reflexivity.\n  Qed.\n\n  Definition SymGrp2_cases (sigma : fintype 2 <~> fintype 2)\n    : (sigma = equiv_idmap) + (sigma = twist2).\n  Proof.\n    recall (sigma (inr tt)) as x eqn:p.\n    destruct x as [[[] | []] | []].\n    - apply inr.\n      apply path_equiv. apply path_arrow. apply sym2_notfixlast. exact p.\n    - apply inl.\n      apply path_equiv. apply path_arrow. apply sym2_fixlast. exact p.\n  Defined.\n\n  Lemma invol_SymGrp2 (sigma : fintype 2 <~> fintype 2)\n    : (sigma oE sigma) = equiv_idmap.\n  Proof.\n    destruct (SymGrp2_cases sigma) as [p | p].\n    - refine (ap011 equiv_compose' p p @ _).\n      apply path_equiv. reflexivity.\n    - refine (ap011 equiv_compose' p p @ _).\n      apply path_equiv. apply path_arrow.\n      intros [[[] | []] | []]; reflexivity.\n  Qed.\nEnd Sym2.\n\nSection Restrict_Equivalence.\n  (** Given an equivalence [A + Unit <~> B + Unit] fixing Unit, we may restrict it to an equivalence [A <~> B]  *)\n  Context {n : nat}\n          {A : Type}\n          (e : A + Unit <~> fintype n.+1)\n          (fixlast : e (inr tt) = inr tt).\n\n  Lemma not_inr_is_inl {X Y : Type}\n        (x :  X + Y)\n        (not_inr : forall y : Y, x <> inr y)\n    : is_inl x.\n  Proof.\n    destruct x as [x | y'].\n    - exact tt.\n    - destruct (not_inr y' idpath).\n  Qed.\n  \n  Lemma fix_last_is_inr :\n    forall u : Unit, is_inr (e (inr u)).\n  Proof.\n    intros []. rewrite fixlast.\n    exact tt.\n  Qed.\n\n  Lemma fix_last_is_inl :\n    forall a : A, is_inl (e (inl a)).\n  Proof.\n    intro a. apply not_inr_is_inl.\n    intros []. rewrite <- fixlast.\n    intro q. apply (inl_ne_inr a tt).\n    exact (equiv_inj e q).\n  Qed.\n\n  Definition equiv_restrict :=\n    equiv_unfunctor_sum_l e fix_last_is_inl fix_last_is_inr.\n\n  Definition swap_last := fin_transpose (e (inr tt)) (inr tt).\n\n  Lemma swap_fix_last :\n    (swap_last oE e) (inr tt) = inr tt.\n  Proof.\n    unfold swap_last. ev_equiv. apply fin_transpose_last_with_with.\n  Qed.\n\n  \n  Definition equiv_restrict_eta :\n    equiv_restrict +E equiv_idmap == e.\n  Proof.\n    intro x.\n    refine (_ @ unfunctor_sum_eta _ fix_last_is_inl fix_last_is_inr x).\n    destruct x as [x | []]; try reflexivity.   \n    simpl.\n    destruct (unfunctor_sum_r e fix_last_is_inr tt).\n    reflexivity.\n  Qed.      \nEnd Restrict_Equivalence.\n\nDefinition equiv_restrict_plus1 {n : nat} {A : Type} (e : A <~> fintype n) :\n  equiv_restrict (e +E equiv_idmap) idpath == e.\nProof.\n  intro a.\n  apply (path_sum_inl Unit).\n  refine (unfunctor_sum_l_beta _ _ a ).\nQed.\n\n\nDefinition inj_equiv_plus1 {n : nat} {A : Type} (e1 e2 : A <~> fintype n) :\n  (e1 +E (equiv_idmap Unit)) == (e2 +E (equiv_idmap Unit)) -> e1 == e2.\nProof.\n  intro H.\n  intro x.\n  apply (path_sum_inl Unit). apply (H (inl x)).\nQed.\n\nDefinition fin_decompose_ind {m n : nat} (P : fintype (n+m) -> Type)\n           (Pl : forall i : fintype m, P (finl _ _ i))\n           (Pr : forall i : fintype n, P (finr _ _ i))\n  : forall i : fintype (n+m), P i.\nProof.\n  cut (forall j : (fintype m)+(fintype n), P (finsum m n j)).\n  - intro f.\n    intro i.\n    apply (transport P (eisretr (finsum m n) i)).\n    exact (f ((finsum m n)^-1 i)).\n  - intros [j | j].\n    + exact (Pl j).\n    + exact (Pr j).\nDefined.\n\nSection Transpose_and_restrict.\n  (** Given a permutation [fintype n.+1 <~> fintype n.+1], we compose it with a transposition so that it fixes [n+1] and restricts it to a permutation [fintype n <~> fintype n]  *)\n  \n  Definition transpose_and_restrict {n n': nat} (e : fintype n.+1 <~> fintype n'.+1)  :\n    fintype n <~> fintype n' :=\n    (equiv_restrict (swap_last e oE e) (swap_fix_last e)).\n\n  Definition transpose_and_restrict_eta {n n': nat} (e : fintype n.+1 <~> fintype n'.+1) :\n    (transpose_and_restrict e) +E 1 == (swap_last e) oE e.\n  Proof.\n    apply equiv_restrict_eta.\n  Defined.\n\n  (** A reformulation: *)\n  Definition factorize_permutation {a a': nat} (alpha : fintype a.+1 <~> fintype a'.+1)\n    : alpha = swap_last alpha oE (transpose_and_restrict alpha +E 1).\n  Proof.\n    apply emoveL_Me.\n    refine (_ @ (path_equiv (path_arrow _ _ (transpose_and_restrict_eta alpha)))^).\n    apply (ap (fun e => e oE alpha)).\n    unfold swap_last.\n    refine ((ecompose_e1 _)^ @ _).\n    apply emoveR_Ve. apply inverse.\n    apply path_equiv. apply path_arrow. apply fin_transpose_invol.\n  Defined.\n\n  Definition transpose_and_restrict_id {n : nat} :\n    @transpose_and_restrict n n equiv_idmap == equiv_idmap.\n  Proof.\n    intro x. simpl.\n    destruct n; reflexivity.\n  Qed.\n\n  Definition transpose_and_restrict_transpose_nfx {n : nat} (x : fintype n.+1) :\n    transpose_and_restrict (fin_transpose x (inr tt)) == equiv_idmap.\n  Proof.\n    apply (inj_equiv_plus1 ).\n    intro i.\n    refine (transpose_and_restrict_eta _ i @ _).\n    unfold swap_last.\n    ev_equiv.\n    assert (h : (1 +E 1) i = i). { destruct i as [i | []]; reflexivity. }\n    rewrite h. clear h.\n    rewrite fin_transpose_beta_r.\n    apply (fin_transpose_invol x (inr tt)).\n  Qed.\n\n  Definition transpose_and_restrict_transpose_fixlast {n : nat} (x y : fintype n) :\n    transpose_and_restrict (fin_transpose (n := n.+1) (inl x) (inl y)) == fin_transpose x y.\n  Proof.\n    apply (inj_equiv_plus1 ).\n    intro i.\n    refine (transpose_and_restrict_eta _ i @ _).\n    unfold swap_last.\n    ev_equiv.\n    assert (h : fin_transpose (n := n.+1) (inl x) (inl y) (inr tt) = inr tt).\n    { apply fin_transpose_other; apply inr_ne_inl. }\n    rewrite h. clear h.\n    refine (fin_transpose_same_is_id (n := n.+1) (inr tt) _ @ _).\n    destruct i as [i | []]; reflexivity.\n  Qed.\nEnd Transpose_and_restrict.\n\nSection Block_Sum.\n  (* First a more general definition *)\n  Definition fin_equiv_sum {a b c d : nat} (e : (fintype a + fintype b) <~> (fintype c + fintype d))\n    : fintype (b + a) <~> fintype (d + c) :=\n    (equiv_finsum c d) oE e oE (equiv_inverse (equiv_finsum a b)).\n\n  Definition fin_equiv_sum_compose {a b c d e f : nat}\n             (e1 : (fintype a + fintype b) <~> (fintype c + fintype d))\n             (e2 : (fintype c + fintype d) <~> (fintype e + fintype f))\n    : fin_equiv_sum (e2 oE e1) =\n      fin_equiv_sum e2 oE fin_equiv_sum e1.\n  Proof.\n    unfold fin_equiv_sum.\n    apply path_equiv. apply path_arrow. intro x.\n    ev_equiv.\n    rewrite (eissect (equiv_finsum c d)).\n    reflexivity.\n  Defined.\n\n  Definition block_sum {a a' b b' : nat}\n             (alpha : fintype a <~> fintype a') (betta : fintype b <~> fintype b')\n    : fintype (a +' b)%nat <~> fintype (a' +' b')\n    := fin_equiv_sum (alpha +E betta).\n             \n\n  (* Definition block_sum {m n: nat} (e1 : fintype m <~> fintype m) (e2 : fintype n <~> fintype n) : *)\n  (*   fintype (n+m)%nat <~> fintype (n+m)%nat := *)\n  (*   fin_equiv_sum (e1 +E e2). *)\n\n  Definition block_sum_beta_finl {m m' n n': nat}\n             (e1 : fintype m <~> fintype m') (e2 : fintype n <~> fintype n')\n             (i : fintype m) :\n    block_sum e1 e2 (finl _ _ i) = finl _ _ (e1 i).\n  Proof.\n    unfold block_sum. unfold fin_equiv_sum. ev_equiv.\n    rewrite (eissect (equiv_finsum m n) (inl i)). reflexivity.\n  Qed.\n\n  Definition block_sum_beta_finr {m m' n n' : nat}\n             (e1 : fintype m <~> fintype m') (e2 : fintype n <~> fintype n')\n             (i : fintype n) :\n    block_sum e1 e2 (finr _ _ i) = finr _ _ (e2 i).\n  Proof.\n    unfold block_sum. unfold fin_equiv_sum. ev_equiv.\n    rewrite (eissect (equiv_finsum m n) (inr i)). reflexivity.\n  Qed.\n\n  Definition block_sum_eta {m m' n n' : nat} \n             (e1 : fintype m <~> fintype m') (e2 : fintype n <~> fintype n')\n             (g : fintype (n + m) <~> fintype (n' + m'))\n             (eq_l : forall i : fintype m,\n                 finl _ _(e1 i)\n                 = g (finl _ _ i))\n             (eq_r : forall i : fintype n,\n                 (finr _ _ (e2 i)\n                  = g (finr _ _ i)))\n    : block_sum e1 e2 == g .\n  Proof.\n    unfold block_sum. unfold fin_equiv_sum. intro j. revert j.\n    apply fin_decompose_ind.\n    - intro i. ev_equiv. rewrite (eissect (equiv_finsum m n) (inl i)).\n      apply eq_l.\n    - intro i.  ev_equiv. rewrite (eissect (equiv_finsum m n) (inr i)).\n      apply eq_r.\n  Qed.\n\n  Definition block_sum_compose {m m' m'' n n' n'': nat}\n             (e1 : fintype m' <~> fintype m'')\n             (g1 : fintype m <~> fintype m')\n             (e2 : fintype n' <~> fintype n'')\n             (g2 : fintype n <~> fintype n') :\n    block_sum (e1 oE g1) (e2 oE g2) =\n    (block_sum e1 e2) oE (block_sum g1 g2).\n  Proof.\n    refine (_ @ fin_equiv_sum_compose _ _).\n    apply (ap fin_equiv_sum).\n    apply path_equiv. apply path_arrow.\n    intros [x | x]; reflexivity.\n  Defined.\n    \n\n  Definition block_sum_compose' {m m' m'' n n' n'': nat}\n             (e1 : fintype m' <~> fintype m'')\n             (g1 : fintype m <~> fintype m')\n             (e2 : fintype n' <~> fintype n'')\n             (g2 : fintype n <~> fintype n') :\n    block_sum (e1 oE g1) (e2 oE g2) ==\n    (block_sum e1 e2) oE (block_sum g1 g2).\n  Proof.\n    apply block_sum_eta.\n    - intro i. ev_equiv.\n      rewrite block_sum_beta_finl.\n      rewrite block_sum_beta_finl.\n      reflexivity.\n    - intro i. ev_equiv.\n      rewrite block_sum_beta_finr.\n      rewrite block_sum_beta_finr.\n      reflexivity.\n  Qed.\n\n  Definition block_sum_plus1 {m m' n n' : nat}\n             (e1 : fintype m <~> fintype m')\n             (e2 : fintype n <~> fintype n') :\n    block_sum (b := n.+1) (b' := n'.+1) e1 (e2 +E (equiv_idmap Unit))\n    == (block_sum e1 e2) +E (equiv_idmap Unit).\n  Proof.    \n    apply block_sum_eta.\n    - intro i. simpl. \n      apply (ap inl).\n      change (finsum_inv m n) with (equiv_finsum m n)^-1.\n      rewrite (eissect (finsum m n) (inl i)). reflexivity.\n    - simpl. intros [i | []].\n      + simpl.\n        change (finsum_inv m n) with (equiv_finsum m n)^-1.\n        rewrite (eissect (finsum m n) (inr i)). reflexivity.\n      + reflexivity.\n  Qed.\n\n  (* should be moved. . . *)\n  Definition functor_not {A B : Type} :\n    (B -> A) -> (not A) -> (not B).\n  Proof.\n    intro f. intros n false. apply n. exact (f false).\n  Qed.\n\n  Definition blocksum_transpose {m n : nat}\n             (x y : fintype n) :\n    fin_transpose (finr _ _ x) (finr _ _ y) ==\n    @block_sum m m n n equiv_idmap (fin_transpose x y).    \n  Proof.\n    apply fin_transpose_eta.\n    - rewrite block_sum_beta_finr.\n      rewrite fin_transpose_beta_l.  reflexivity.\n    - rewrite block_sum_beta_finr.\n      rewrite fin_transpose_beta_r. reflexivity.\n    - apply (fin_decompose_ind\n               (fun i : fintype (n+m) =>\n               i <> finr m n x -> i <> finr m n y ->\n               (block_sum equiv_idmap (fin_transpose x y)) i = i)).\n      + intros i neqx neqy.\n        apply block_sum_beta_finl.\n      + intros i neqx neqy.\n        refine (block_sum_beta_finr _ _ _ @ _).\n        apply (ap (finr m n)).  apply (fin_transpose_other x y i).\n        { apply (functor_not (ap (finr m n)) neqx). }\n        { apply (functor_not (ap (finr m n)) neqy). }\n  Qed.\n  \n  Definition swap_last_blocksum {m m' n n' : nat}\n             (e1 : fintype m <~> fintype m')\n             (e2 : fintype n.+1 <~> fintype n'.+1) :\n    swap_last (block_sum e1 e2) ==\n    block_sum equiv_idmap (swap_last e2) .\n  Proof.\n    unfold swap_last.\n    rewrite (block_sum_beta_finr (n := n.+1) e1 e2 (inr tt)).\n    apply (@blocksum_transpose m' n'.+1 (e2 (inr tt)) ((inr (fintype n') tt))).\n  Qed.\n\n  \n  Definition transpose_and_restrict_block_sum {m m' n n' : nat}\n             (e1 : fintype m <~> fintype m')\n             (e2 : fintype n.+1 <~> fintype n'.+1) :\n    transpose_and_restrict (block_sum e1 e2) == block_sum e1 (transpose_and_restrict e2).\n  Proof.\n    apply inj_equiv_plus1.\n    intro x.\n    refine (equiv_restrict_eta _ _ _ @ _).\n    refine (swap_last_blocksum e1 e2 _ @ _).\n    refine ((block_sum_compose' equiv_idmap e1 (swap_last e2) e2 x)^ @ _).\n    rewrite (ecompose_1e).\n    refine (_ @ (block_sum_plus1 _ _ x)).\n    apply (ap (fun g => ((block_sum (b:=n.+1) e1 g) x))).\n    apply path_equiv. apply path_arrow.\n    intro y.\n    apply inverse.\n    apply transpose_and_restrict_eta.\n  Defined.    \n  \nEnd Block_Sum.\n\nRequire Import monoids_and_groups.\n\nDefinition SymGrp (m : nat) := AutGroup (fintype m).\n\nSection Block_Sum_Hom.\n  (** Block sum as a homomorphism *)\n  Definition block_sum_hom (m n : nat):\n    Homomorphism (grp_prod (SymGrp m) (SymGrp n)) (SymGrp (n+m)).\n  Proof.\n    srapply @Build_Homomorphism.\n    - intros [s t].\n      exact (block_sum s t).\n    - simpl. apply path_equiv. apply path_arrow.\n      apply block_sum_eta; reflexivity.\n    - simpl. intros [s1 s2] [t1 t2].\n      (* apply path_equiv. apply path_arrow. *)\n      apply block_sum_compose.\n  Defined.\nEnd Block_Sum_Hom.\n", "meta": {"author": "kalfsvag", "repo": "group_completions", "sha": "cc65e902a68dbb6dc05315651dce3064704a9815", "save_path": "github-repos/coq/kalfsvag-group_completions", "path": "github-repos/coq/kalfsvag-group_completions/group_completions-cc65e902a68dbb6dc05315651dce3064704a9815/finite/permutations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7001185340097194}}
{"text": "Require Import SpecCert.Equality.\n\nDefinition Map\n           (K V: Type)\n          `{Eq K}\n  := K -> V.\n\nDefinition add_in_map\n           {K V: Type}\n          `{Eq K}\n           (m:   Map K V)\n           (k:   K)\n           (v:   V)\n  : Map K V :=\n  fun (k':K) => \n    if eq_dec k k'\n    then v\n    else m k'.\n\nDefinition find_in_map\n           {K V: Type}\n          `{Eq K}\n           (m:   Map K V)\n           (k: K)\n  : V :=\n  m k.\n\nLemma add_1\n      {K V: Type}\n     `{Eq K}\n      (m:   Map K V)\n      (k:   K)\n      (v:   V)\n  : find_in_map (add_in_map m k v) k = v.\nProof.\n  unfold add_in_map.\n  unfold find_in_map.\n  destruct (eq_dec k k).\n  + reflexivity.\n  + destruct n.\n    apply (eq_refl k).\nQed.\n\nLemma add_2\n      {K V:  Type}\n     `{Eq K}\n      (m:    Map K V)\n      (k k': K)\n      (v:    V)\n      (neq: ~ eq k k')\n  : find_in_map m k' = find_in_map (add_in_map m k v) k'.\nProof.\n  unfold find_in_map, add_in_map.\n  destruct (eq_dec k k').\n  + apply neq in e.\n    destruct e.\n  + reflexivity.\nQed.", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/Map/Map_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.700118529639101}}
{"text": "Require Import List.\nRequire Import Fin.\n\nRequire Import fl.cfg.Definitions.\nRequire Import fl.int.Base2.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype bigop fingraph finfun finset.\n\nModule DFA.\n\n  Import Base Base2 Definitions.\n  \n  Section Definitions. \n   \n    Context {State T: Type}.\n\n    Definition dfa_rule := State -> (@ter T) -> State.\n\n    Record dfa: Type :=\n      mkDfa {\n          start: State;\n          final: list State;\n          next: dfa_rule;\n        }.\n\n    Fixpoint final_state (next_d: dfa_rule) (s: State) (w: word): State :=\n      match w with\n        | nil => s \n        | h :: t => final_state next_d (next_d s h) t \n      end.\n\n    Definition accepts (d : dfa) (s: State) (w: word) : Prop :=\n      In (final_state (next d) s w) (final d). \n\n    Definition dfa_language (d : dfa) := (accepts d (start d)).\n\n    \n    Record s_dfa : Type :=\n      s_mkDfa {\n          s_start: State;\n          s_final: State;\n          s_next: dfa_rule;\n        }.         \n\n    Definition s_accepts (d : s_dfa) (s: State) (w: word) : Prop :=\n      (final_state (s_next d) s w) = (s_final d).\n\n    Definition s_dfa_language (d : s_dfa) := (s_accepts d (s_start d)).\n\n    Fixpoint split_dfa_list (st_d : State) (next_d : dfa_rule) (f_list : list State): list (s_dfa) :=\n      match f_list with\n        | nil => nil\n        | h :: t => (s_mkDfa st_d h next_d) :: split_dfa_list st_d next_d t\n      end.\n\n    Definition split_dfa (d: dfa) := split_dfa_list (start d) (next d) (final d).\n\n  End Definitions.\n \n  Section Lemmas.\n\n    Context {State T: Type}.\n\n        \n    Example test0:\n      forall (w1 w2: @word T)\n        (next: dfa_rule)\n        (from to: State),\n        final_state next from (w1 ++ w2) = to ->\n        final_state next (final_state next from w1) w2 = to.\n    Proof.\n      intros w1 w2 nex.\n      induction w1; eauto.\n    Qed.\n    \n    Example test0_1:\n      forall (w1 w2 : word)\n        (next : dfa_rule)\n        (from to: _),\n        final_state next (final_state next from w1) w2 = to ->\n        @final_state State T next from (w1 ++ w2) = to.\n    Proof.\n      intros w1 w2 next.\n      induction w1; simpl; eauto.\n    Qed.\n\n    Theorem lemma2_3_1:\n      forall (d : @DFA.dfa State T)  (w : word),\n        dfa_language d w ->\n        exists sdfa : s_dfa,\n          In sdfa (split_dfa d) /\\ s_dfa_language sdfa w.\n    Proof.\n      intros dfa word LANG.\n      destruct dfa; unfold split_dfa; simpl.\n      unfold dfa_language, accepts in LANG; simpl in LANG.\n      induction final0.\n      { simpl in LANG; elim LANG. }\n      { simpl in LANG.\n        destruct LANG; [subst a | ].\n        { exists ({|\n                     s_start := start0;\n                     s_final := final_state next0 start0 word;\n                     s_next := next0 |}).\n            by simpl; split; [left | ].\n        }\n        { \n          apply IHfinal0 in H; clear IHfinal0.\n          move: H => [s_dfa [IN sLANG]].\n          unfold s_dfa_language, s_accepts; simpl.\n          exists s_dfa.\n            by split; [right | ].\n        }\n      }\n    Qed.    \n\n    Theorem lemma2_3_2:\n      forall (d : @dfa State T) (w : word),\n      (exists sdfa : s_dfa,\n          In sdfa (split_dfa d) /\\ s_dfa_language sdfa w) ->\n      @dfa_language State T d w.\n    Proof.\n      move => dfa word [s_dfa [IN sLANG]].\n      unfold dfa_language, accepts.\n      destruct dfa; unfold split_dfa in *; simpl in *.\n      induction final0; first by done.\n      simpl in IN; move: IN => [EQ|IN]; [subst; clear IHfinal0 | ].\n      { by left; unfold s_dfa_language, s_accepts in sLANG; simpl in sLANG. }\n      { apply IHfinal0 in IN; clear IHfinal0; rename IN into IH.\n          by simpl; right. } \n    Qed.\n    \n  \n    (* TODO: del *)\n    (* Feed tactic -- exploit with multiple arguments.\n       (taken from http://comments.gmane.org/gmane.science.mathematics.logic.coq.club/7013) *)\n    Ltac feed H :=\n      match type of H with\n        | ?foo -> _ =>\n          let FOO := fresh in\n          assert foo as FOO; [|specialize (H FOO); clear FOO]\n      end.\n    \n    Lemma correct_split:\n      forall dfa w,\n        @dfa_language State T dfa w <->\n        exists sdfa, In sdfa (split_dfa dfa) /\\ s_dfa_language sdfa w.\n    Proof.\n      intros dfa w.\n      split; intros H. \n      - by apply lemma2_3_1. \n      - by apply lemma2_3_2. \n    Qed.\n\n  End Lemmas.\n\nEnd DFA.", "meta": {"author": "YaccConstructor", "repo": "YC_in_Coq", "sha": "d94a9ec10d532b86ae4f48871c38369f9ce5f1d8", "save_path": "github-repos/coq/YaccConstructor-YC_in_Coq", "path": "github-repos/coq/YaccConstructor-YC_in_Coq/YC_in_Coq-d94a9ec10d532b86ae4f48871c38369f9ce5f1d8/int/DFA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.700117366556724}}
